{"text": "theory EjT3A\nimports \"../Temas/Ejemplos/ExpA\"\nbegin \n\nsection \"Ejercicio 3.1: La función simp_constA simplifica\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 3.1.1. Una expresión aritmética está simplificada si no\n  contiene niguna subexpresión que sea una suma de dos números.\n  \n  Definir la función\n     simplificada :: \"expA \\<Rightarrow> bool\" where\n  tal que (simplificada a) se verifica si la expresión aritmética a está\n  simplificada. Por ejemplo, \n     simplificada (Suma (V ''x'') (N 5))              = True\n     simplificada (Suma (V ''x'') (Suma (N 2) (N 5))) = False\n     simplificada (Suma (N 2) (Suma (V ''x'') (N 5))) = True\n  ------------------------------------------------------------------- *}\n\nfun simplificada :: \"expA \\<Rightarrow> bool\" where\n\"simplificada (N _) = True\" |\n\"simplificada (V _) = True\" |\n\"simplificada (Suma (N _) (N _)) = False\" |\n\"simplificada (Suma a1 a2) = (simplificada a1 \\<and> simplificada a2)\"\n\nvalue \"simplificada (Suma (V ''x'') (N 5))\"\n  (* da True *)\nvalue \"simplificada (Suma (V ''x'') (Suma (N 2) (N 5)))\"\n  (* da False *)\nvalue \"simplificada (Suma (N 2) (Suma (V ''x'') (N 5)))\"\n  (* da True *)\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 3.1.2. Demostrar que para cualquier expresión aritmética a, \n  \n  ------------------------------------------------------------------- *}\n\nlemma \"simplificada (simp_constA a)\"\napply (induction a rule: simplificada.induct)\napply (auto split: expA.split)\ndone\n\ntext{*\nThis proof needs the same @{text \"split:\"} directive as the correctness proof of\n@{const simp_constA}. This increases the chance of nontermination\nof the simplifier. Therefore @{const simplificada} should be defined purely by\npattern matching on the left-hand side,\nwithout @{text case} expressions on the right-hand side.\n\\endexercise\n\n\n\\exercise\nIn this exercise we verify constant folding for @{typ expA}\nwhere we sum up all constants, even if they are not next to each other.\nFor example, @{term \"Plus (N 1) (Plus (V x) (N 2))\"} becomes\n@{term \"Plus (V x) (N 3)\"}. This goes beyond @{const asimp}.\nBelow we follow a particular solution strategy but there are many others.\n\nFirst, define a function @{text sumN} that returns the sum of all\nconstants in an expression and a function @{text zeroN} that replaces all\nconstants in an expression by zeroes (they will be optimized away later):\n*}\n\nfun sumN :: \"expA \\<Rightarrow> int\" where\n(* your definition/proof here *)\n\nfun zeroN :: \"expA \\<Rightarrow> expA\" where\n(* your definition/proof here *)\n\ntext {*\nNext, define a function @{text sepN} that produces an arithmetic expression\nthat adds the results of @{const sumN} and @{const zeroN}. Prove that\n@{text sepN} preserves the value of an expression.\n*}\n\ndefinition sepN :: \"expA \\<Rightarrow> expA\" where\n(* your definition/proof here *)\n\nlemma aval_sepN: \"aval (sepN t) s = aval t s\"\n(* your definition/proof here *)\n\ntext {*\nFinally, define a function @{text full_asimp} that uses @{const asimp}\nto eliminate the zeroes left over by @{const sepN}.\nProve that it preserves the value of an arithmetic expression.\n*}\n\ndefinition full_asimp :: \"expA \\<Rightarrow> expA\" where\n(* your definition/proof here *)\n\nlemma aval_full_asimp: \"aval (full_asimp t) s = aval t s\"\n(* your definition/proof here *)\n\n\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:subst}\nSubstitution is the process of replacing a variable\nby an expression in an expression. Define a substitution function\n*}\n\nfun subst :: \"vname \\<Rightarrow> expA \\<Rightarrow> expA \\<Rightarrow> expA\" where\n(* your definition/proof here *)\n\ntext{*\nsuch that @{term \"subst x a e\"} is the result of replacing\nevery occurrence of variable @{text x} by @{text a} in @{text e}.\nFor example:\n@{lemma[display] \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\" by simp}\n\nProve the so-called \\concept{substitution lemma} that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\n*}\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n(* your definition/proof here *)\n\ntext {*\nAs a consequence prove that we can substitute equal expressions by equal expressions\nand obtain the same result under evaluation:\n*}\nlemma \"aval a1 s = aval a2 s\n  \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nTake a copy of theory @{theory AExp} and modify it as follows.\nExtend type @{typ expA} with a binary constructor @{text Times} that\nrepresents multiplication. Modify the definition of the functions @{const aval}\nand @{const asimp} accordingly. You can remove @{const simp_constA}.\nFunction @{const asimp} should eliminate 0 and 1 from multiplications\nas well as evaluate constant subterms. Update all proofs concerned.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a datatype @{text expA2} of extended arithmetic expressions that has,\nin addition to the constructors of @{typ expA}, a constructor for\nmodelling a C-like post-increment operation $x{++}$, where $x$ must be a\nvariable. Define an evaluation function @{text \"aval2 :: expA2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state\"}\nthat returns both the value of the expression and the new state.\nThe latter is required because post-increment changes the state.\n\nExtend @{text expA2} and @{text aval2} with a division operation. Model partiality of\ndivision by changing the return type of @{text aval2} to\n@{typ \"(val \\<times> state) option\"}. In case of division by 0 let @{text aval2}\nreturn @{const None}. Division on @{typ int} is the infix @{text div}.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nThe following type adds a @{text LET} construct to arithmetic expressions:\n*}\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\ntext{* The @{const LET} constructor introduces a local variable:\nthe value of @{term \"LET x e\\<^sub>1 e\\<^sub>2\"} is the value of @{text e\\<^sub>2}\nin the state where @{text x} is bound to the value of @{text e\\<^sub>1} in the original state.\nDefine a function @{const lval} @{text\"::\"} @{typ \"lexp \\<Rightarrow> state \\<Rightarrow> int\"}\nthat evaluates @{typ lexp} expressions. Remember @{term\"s(x := i)\"}.\n\nDefine a conversion @{const inline} @{text\"::\"} @{typ \"lexp \\<Rightarrow> expA\"}.\nThe expression \\mbox{@{term \"LET x e\\<^sub>1 e\\<^sub>2\"}} is inlined by substituting\nthe converted form of @{text e\\<^sub>1} for @{text x} in the converted form of @{text e\\<^sub>2}.\nSee Exercise~\\ref{exe:subst} for more on substitution.\nProve that @{const inline} is correct w.r.t.\\ evaluation.\n\\endexercise\n\n\n\\exercise\nShow that equality and less-or-equal tests on @{text expA} are definable\n*}\n\ndefinition Le :: \"expA \\<Rightarrow> expA \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ndefinition Eq :: \"expA \\<Rightarrow> expA \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ntext{*\nand prove that they do what they are supposed to:\n*}\n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n(* your definition/proof here *)\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n(* your definition/proof here *)\n\nend\n", "meta": {"author": "jaalonso", "repo": "SLP", "sha": "799e829200ea0a4fbb526f47356135d98a190864", "save_path": "github-repos/isabelle/jaalonso-SLP", "path": "github-repos/isabelle/jaalonso-SLP/SLP-799e829200ea0a4fbb526f47356135d98a190864/Ejercicios/EjT3A.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942093072239, "lm_q2_score": 0.8856314783461302, "lm_q1q2_score": 0.7999857859702555}}
{"text": "theory Harmonic_Numbers\nimports Complex_Main Summation Integral_Test\nbegin\n\ntext \\<open>\n  The harmonic numbers\n\\<close>\ndefinition harm :: \"nat \\<Rightarrow> 'a :: real_normed_field\" where\n  \"harm n = (\\<Sum>k=1..n. inverse (of_nat k))\"\n\nlemma harm_altdef: \"harm n = (\\<Sum>k<n. inverse (of_nat (Suc k)))\"\n  unfolding harm_def by (induction n) simp_all\n\nlemma harm_Suc: \"harm (Suc n) = harm n + inverse (of_nat (Suc n))\"\n  by (simp add: harm_def)\n\nlemma harm_nonneg: \"harm n \\<ge> (0 :: 'a :: {real_normed_field,linordered_field})\"\n  unfolding harm_def by (intro setsum_nonneg) simp_all\n\nlemma of_real_harm: \"of_real (harm n) = harm n\"\n  unfolding harm_def by simp\n  \nlemma norm_harm: \"norm (harm n) = harm n\"\n  by (subst of_real_harm [symmetric]) (simp add: harm_nonneg)\n\nlemma harm_expand: \n  \"harm (Suc 0) = 1\"\n  \"harm (numeral n) = harm (pred_numeral n) + inverse (numeral n)\"\nproof -\n  have \"numeral n = Suc (pred_numeral n)\" by simp\n  also have \"harm \\<dots> = harm (pred_numeral n) + inverse (numeral n)\"\n    by (subst harm_Suc, subst numeral_eq_Suc[symmetric]) simp\n  finally show \"harm (numeral n) = harm (pred_numeral n) + inverse (numeral n)\" .\nqed (simp add: harm_def)\n\nlemma not_convergent_harm: \"\\<not>convergent (harm :: nat \\<Rightarrow> 'a :: real_normed_field)\"\nproof -\n  have \"convergent (\\<lambda>n. norm (harm n :: 'a)) \\<longleftrightarrow>\n            convergent (harm :: nat \\<Rightarrow> real)\" by (simp add: norm_harm)\n  also have \"\\<dots> \\<longleftrightarrow> convergent (\\<lambda>n. \\<Sum>k=Suc 0..Suc n. inverse (of_nat k) :: real)\"\n    unfolding harm_def[abs_def] by (subst convergent_Suc_iff) simp_all\n  also have \"... \\<longleftrightarrow> convergent (\\<lambda>n. \\<Sum>k\\<le>n. inverse (of_nat (Suc k)) :: real)\"\n    by (subst setsum_shift_bounds_cl_Suc_ivl) (simp add: atLeast0AtMost)\n  also have \"... \\<longleftrightarrow> summable (\\<lambda>n. inverse (of_nat n) :: real)\"\n    by (subst summable_Suc_iff [symmetric]) (simp add: summable_iff_convergent')\n  also have \"\\<not>...\" by (rule not_summable_harmonic)\n  finally show ?thesis by (blast dest: convergent_norm)\nqed\n\n\nsubsection \\<open>The Euler–Mascheroni constant\\<close>\n\ntext \\<open>\n  The limit of the difference between the partial harmonic sum and the natural logarithm\n  (approximately 0.577216). This value occurs e.g. in the definition of the Gamma function.\n \\<close>\ndefinition euler_mascheroni :: \"'a :: real_normed_algebra_1\" where\n  \"euler_mascheroni = of_real (lim (\\<lambda>n. harm n - ln (of_nat n)))\"\n\nlemma of_real_euler_mascheroni [simp]: \"of_real euler_mascheroni = euler_mascheroni\"\n  by (simp add: euler_mascheroni_def)\n\ninterpretation euler_mascheroni: antimono_fun_sum_integral_diff \"\\<lambda>x. inverse (x + 1)\"\n  by unfold_locales (auto intro!: continuous_intros)\n\nlemma euler_mascheroni_sum_integral_diff_series:\n  \"euler_mascheroni.sum_integral_diff_series n = harm (Suc n) - ln (of_nat (Suc n))\"\nproof -\n  have \"harm (Suc n) = (\\<Sum>k=0..n. inverse (of_nat k + 1) :: real)\" unfolding harm_def\n    unfolding One_nat_def by (subst setsum_shift_bounds_cl_Suc_ivl) (simp add: add_ac)\n  moreover have \"((\\<lambda>x. inverse (x + 1) :: real) has_integral ln (of_nat n + 1) - ln (0 + 1))\n                   {0..of_nat n}\"\n    by (intro fundamental_theorem_of_calculus)\n       (auto intro!: derivative_eq_intros simp: divide_inverse\n           has_field_derivative_iff_has_vector_derivative[symmetric])\n  hence \"integral {0..of_nat n} (\\<lambda>x. inverse (x + 1) :: real) = ln (of_nat (Suc n))\"\n    by (auto dest!: integral_unique)\n  ultimately show ?thesis \n    by (simp add: euler_mascheroni.sum_integral_diff_series_def atLeast0AtMost)\nqed\n\nlemma euler_mascheroni_sequence_decreasing:\n  \"m > 0 \\<Longrightarrow> m \\<le> n \\<Longrightarrow> harm n - ln (of_nat n) \\<le> harm m - ln (of_nat m :: real)\"\n  by (cases m, simp, cases n, simp, hypsubst,\n      subst (1 2) euler_mascheroni_sum_integral_diff_series [symmetric],\n      rule euler_mascheroni.sum_integral_diff_series_antimono, simp)\n\nlemma euler_mascheroni_sequence_nonneg:\n  \"n > 0 \\<Longrightarrow> harm n - ln (of_nat n) \\<ge> (0::real)\"\n  by (cases n, simp, hypsubst, subst euler_mascheroni_sum_integral_diff_series [symmetric],\n      rule euler_mascheroni.sum_integral_diff_series_nonneg)\n\nlemma euler_mascheroni_convergent: \"convergent (\\<lambda>n. harm n - ln (of_nat n) :: real)\"\nproof -\n  have A: \"(\\<lambda>n. harm (Suc n) - ln (of_nat (Suc n))) = \n             euler_mascheroni.sum_integral_diff_series\"\n    by (subst euler_mascheroni_sum_integral_diff_series [symmetric]) (rule refl)\n  have \"convergent (\\<lambda>n. harm (Suc n) - ln (of_nat (Suc n) :: real))\"\n    by (subst A) (fact euler_mascheroni.sum_integral_diff_series_convergent)\n  thus ?thesis by (subst (asm) convergent_Suc_iff)\nqed\n\nlemma euler_mascheroni_LIMSEQ: \n  \"(\\<lambda>n. harm n - ln (of_nat n) :: real) ----> euler_mascheroni\"\n  unfolding euler_mascheroni_def\n  by (simp add: convergent_LIMSEQ_iff [symmetric] euler_mascheroni_convergent)\n\nlemma euler_mascheroni_LIMSEQ_of_real: \n  \"(\\<lambda>n. of_real (harm n - ln (of_nat n))) ----> \n      (euler_mascheroni :: 'a :: {real_normed_algebra_1, topological_space})\"\nproof -\n  have \"(\\<lambda>n. of_real (harm n - ln (of_nat n))) ----> (of_real (euler_mascheroni) :: 'a)\"\n    by (intro tendsto_of_real euler_mascheroni_LIMSEQ)\n  thus ?thesis by simp\nqed\n\nlemma euler_mascheroni_sum:\n  \"(\\<lambda>n. inverse (of_nat (n+1)) + ln (of_nat (n+1)) - ln (of_nat (n+2)) :: real)\n       sums euler_mascheroni\" \n using sums_add[OF telescope_sums[OF LIMSEQ_Suc[OF euler_mascheroni_LIMSEQ]]\n                   telescope_sums'[OF LIMSEQ_inverse_real_of_nat]]\n  by (simp_all add: harm_def algebra_simps)\n\nlemma alternating_harmonic_series_sums: \"(\\<lambda>k. (-1)^k / real_of_nat (Suc k)) sums ln 2\"\nproof -\n  let ?f = \"\\<lambda>n. harm n - ln (real_of_nat n)\"\n  let ?g = \"\\<lambda>n. if even n then 0 else (2::real)\"\n  let ?em = \"\\<lambda>n. harm n - ln (real_of_nat n)\"\n  have \"eventually (\\<lambda>n. ?em (2*n) - ?em n + ln 2 = (\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) at_top\"\n    using eventually_gt_at_top[of \"0::nat\"]\n  proof eventually_elim\n    fix n :: nat assume n: \"n > 0\"\n    have \"(\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k)) =\n              (\\<Sum>k<2*n. ((-1)^k + ?g k) / of_nat (Suc k)) - (\\<Sum>k<2*n. ?g k / of_nat (Suc k))\"\n      by (simp add: setsum.distrib algebra_simps divide_inverse)\n    also have \"(\\<Sum>k<2*n. ((-1)^k + ?g k) / real_of_nat (Suc k)) = harm (2*n)\"\n      unfolding harm_altdef by (intro setsum.cong) (auto simp: field_simps)\n    also have \"(\\<Sum>k<2*n. ?g k / real_of_nat (Suc k)) = (\\<Sum>k|k<2*n \\<and> odd k. ?g k / of_nat (Suc k))\"\n      by (intro setsum.mono_neutral_right) auto\n    also have \"\\<dots> = (\\<Sum>k|k<2*n \\<and> odd k. 2 / (real_of_nat (Suc k)))\"\n      by (intro setsum.cong) auto\n    also have \"(\\<Sum>k|k<2*n \\<and> odd k. 2 / (real_of_nat (Suc k))) = harm n\" \n      unfolding harm_altdef\n      by (intro setsum.reindex_cong[of \"\\<lambda>n. 2*n+1\"]) (auto simp: inj_on_def field_simps elim!: oddE)\n    also have \"harm (2*n) - harm n = ?em (2*n) - ?em n + ln 2\" using n\n      by (simp_all add: algebra_simps ln_mult)\n    finally show \"?em (2*n) - ?em n + ln 2 = (\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))\" ..\n  qed\n  moreover have \"(\\<lambda>n. ?em (2*n) - ?em n + ln (2::real)) \n                     ----> euler_mascheroni - euler_mascheroni + ln 2\"\n    by (intro tendsto_intros euler_mascheroni_LIMSEQ filterlim_compose[OF euler_mascheroni_LIMSEQ]\n              filterlim_subseq) (auto simp: subseq_def)\n  hence \"(\\<lambda>n. ?em (2*n) - ?em n + ln (2::real)) ----> ln 2\" by simp\n  ultimately have \"(\\<lambda>n. (\\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k))) ----> ln 2\"\n    by (rule Lim_transform_eventually)\n  \n  moreover have \"summable (\\<lambda>k. (-1)^k * inverse (real_of_nat (Suc k)))\"\n    using LIMSEQ_inverse_real_of_nat\n    by (intro summable_Leibniz(1) decseq_imp_monoseq decseq_SucI) simp_all\n  hence A: \"(\\<lambda>n. \\<Sum>k<n. (-1)^k / real_of_nat (Suc k)) ----> (\\<Sum>k. (-1)^k / real_of_nat (Suc k))\"\n    by (simp add: summable_sums_iff divide_inverse sums_def)\n  from filterlim_compose[OF this filterlim_subseq[of \"op * (2::nat)\"]]\n    have \"(\\<lambda>n. \\<Sum>k<2*n. (-1)^k / real_of_nat (Suc k)) ----> (\\<Sum>k. (-1)^k / real_of_nat (Suc k))\"\n    by (simp add: subseq_def)\n  ultimately have \"(\\<Sum>k. (- 1) ^ k / real_of_nat (Suc k)) = ln 2\" by (intro LIMSEQ_unique)\n  with A show ?thesis by (simp add: sums_def)\nqed\n\nlemma alternating_harmonic_series_sums': \n  \"(\\<lambda>k. inverse (real_of_nat (2*k+1)) - inverse (real_of_nat (2*k+2))) sums ln 2\"\nunfolding sums_def\nproof (rule Lim_transform_eventually)\n  show \"(\\<lambda>n. \\<Sum>k<2*n. (-1)^k / (real_of_nat (Suc k))) ----> ln 2\"\n    using alternating_harmonic_series_sums unfolding sums_def \n    by (rule filterlim_compose) (rule mult_nat_left_at_top, simp)\n  show \"eventually (\\<lambda>n. (\\<Sum>k<2*n. (-1)^k / (real_of_nat (Suc k))) =\n            (\\<Sum>k<n. inverse (real_of_nat (2*k+1)) - inverse (real_of_nat (2*k+2)))) sequentially\"\n  proof (intro always_eventually allI)\n    fix n :: nat\n    show \"(\\<Sum>k<2*n. (-1)^k / (real_of_nat (Suc k))) =\n              (\\<Sum>k<n. inverse (real_of_nat (2*k+1)) - inverse (real_of_nat (2*k+2)))\"\n      by (induction n) (simp_all add: inverse_eq_divide)\n  qed\nqed               \n\nend", "meta": {"author": "pruvisto", "repo": "isabelle_summation", "sha": "1a93fd20d83fa8fae14c1d89d3535624b6afebbf", "save_path": "github-repos/isabelle/pruvisto-isabelle_summation", "path": "github-repos/isabelle/pruvisto-isabelle_summation/isabelle_summation-1a93fd20d83fa8fae14c1d89d3535624b6afebbf/Harmonic_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.8791467659263147, "lm_q1q2_score": 0.7999418102433578}}
{"text": "theory Chapter3\nimports \"HOL-IMP.BExp\"\n        \"HOL-IMP.ASM\"\nbegin\n\ntext{*\n\\section*{Chapter 3}\n\n\\exercise\nTo show that @{const asimp_const} really folds all subexpressions of the form\n@{term \"Plus (N i) (N j)\"}, define a function\n*}\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (N n) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus a1 a2) = conj (optimal a1) (optimal a2)\"\n\n\ntext{*\nthat checks that its argument does not contain a subexpression of the form\n@{term \"Plus (N i) (N j)\"}. Then prove that the result of @{const asimp_const}\nis optimal:\n*}\n\nlemma \"optimal (asimp_const a)\"\n  apply(induction a)\n  apply(auto split:aexp.split)\n  done\n\ntext{*\nThis proof needs the same @{text \"split:\"} directive as the correctness proof of\n@{const asimp_const}. This increases the chance of nontermination\nof the simplifier. Therefore @{const optimal} should be defined purely by\npattern matching on the left-hand side,\nwithout @{text case} expressions on the right-hand side.\n\\endexercise\n\n\n\\exercise\nIn this exercise we verify constant folding for @{typ aexp}\nwhere we sum up all constants, even if they are not next to each other.\nFor example, @{term \"Plus (N 1) (Plus (V x) (N 2))\"} becomes\n@{term \"Plus (V x) (N 3)\"}. This goes beyond @{const asimp}.\nBelow we follow a particular solution strategy but there are many others.\n\nFirst, define a function @{text sumN} that returns the sum of all\nconstants in an expression and a function @{text zeroN} that replaces all\nconstants in an expression by zeroes (they will be optimized away later):\n*}\n\nfun sumN :: \"aexp \\<Rightarrow> int\" where\n\"sumN (N n) = n\" |\n\"sumN (V x) = 0\" |\n\"sumN (Plus a b) = sumN a + sumN b\"\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n\"zeroN (N n) = N 0\" |\n\"zeroN (V x) = V x\" |\n\"zeroN (Plus a b) = Plus (zeroN a) (zeroN b)\"\n\ntext {*\nNext, define a function @{text sepN} that produces an arithmetic expression\nthat adds the results of @{const sumN} and @{const zeroN}. Prove that\n@{text sepN} preserves the value of an expression.\n*}\n\ndefinition sepN :: \"aexp \\<Rightarrow> aexp\" where\n\"sepN a = Plus (N (sumN a)) (zeroN a)\"\n\n(*\nlemma aux_1: \"aval t s = sumN t + aval (zeroN t) s\"   \n  apply(induction t arbitrary: s)\n  apply(auto)\n  done  \n    \nlemma aux_2: \"aval (sepN t) s = sumN t + aval (zeroN t) s\"\n  apply(induction t arbitrary:s)\n  apply(auto simp add:sepN_def)\n  done  \n*)\n\nlemma aval_sepN: \"aval (sepN t) s = aval t s\"\n  apply(induction t)\n  apply(auto simp add:sepN_def)\n  done\n\ntext {*\nFinally, define a function @{text full_asimp} that uses @{const asimp}\nto eliminate the zeroes left over by @{const sepN}.\nProve that it preserves the value of an arithmetic expression.\n*}\n\ndefinition full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = asimp (sepN a)\"\n\nlemma aval_full_asimp: \"aval (full_asimp t) s = aval t s\"\n  apply(induction t arbitrary:s)\n  apply(auto simp add:full_asimp_def sepN_def simp:algebra_simps)\n  done\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:subst}\nSubstitution is the process of replacing a variable\nby an expression in an expression. Define a substitution function\n*}\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst var a (N n) = N n\" |\n\"subst var a (V x) = (if var=x then a else (V x))\" |\n\"subst var a (Plus b c) = Plus (subst var a b) (subst var a c)\" \n\ntext{*\nsuch that @{term \"subst x a e\"} is the result of replacing\nevery occurrence of variable @{text x} by @{text a} in @{text e}.\nFor example:\n@{lemma[display] \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\" by simp}\n\nProve the so-called \\concept{substitution lemma} that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\n*}\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply(induction e)\n  apply(auto)\n  done\n\ntext {*\nAs a consequence prove that we can substitute equal expressions by equal expressions\nand obtain the same result under evaluation:\n*}\nlemma \"aval a1 s = aval a2 s\n  \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply(induction e)\n  apply(auto)\n  done\n\ntext{*\n\\endexercise\n\n\\exercise\nTake a copy of theory @{short_theory \"AExp\"} and modify it as follows.\nExtend type @{typ aexp} with a binary constructor @{text Times} that\nrepresents multiplication. Modify the definition of the functions @{const aval}\nand @{const asimp} accordingly. You can remove @{const asimp_const}.\nFunction @{const asimp} should eliminate 0 and 1 from multiplications\nas well as evaluate constant subterms. Update all proofs concerned.\n*}\n\n\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a datatype @{text aexp2} of extended arithmetic expressions that has,\nin addition to the constructors of @{typ aexp}, a constructor for\nmodelling a C-like post-increment operation $x{++}$, where $x$ must be a\nvariable. Define an evaluation function @{text \"aval2 :: aexp2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state\"}\nthat returns both the value of the expression and the new state.\nThe latter is required because post-increment changes the state.\n\nExtend @{text aexp2} and @{text aval2} with a division operation. Model partiality of\ndivision by changing the return type of @{text aval2} to\n@{typ \"(val \\<times> state) option\"}. In case of division by 0 let @{text aval2}\nreturn @{const None}. Division on @{typ int} is the infix @{text div}.\n*}\n\ndatatype aexp2 = N2 int | V2 vname | Plus2 aexp2 aexp2 | Times2 aexp2 aexp2 | Inc vname | Div aexp2 aexp2\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state)\" where\n\"aval2 (N2 n) s = (n, s)\" |\n\"aval2 (V2 x) s = (s x, s)\" |\n\"aval2 (Plus2 a b) s = (fst (aval2 a s) + fst (aval2 b s), (\\<lambda> x. (snd (aval2 a s) x) + (snd (aval2 b s) x) - (s x)))\" |\n\"aval2 (Times2 a b) s = (fst (aval2 a s) * fst (aval2 b s), (\\<lambda> x. (snd (aval2 a s) x) + (snd (aval2 b s) x) - (s x)))\" |\n\"aval2 (Inc x) s = (s x, s(x:= 1 + s x))\" |\n\"aval2 (Div a b) s = (fst (aval2 a s) div fst (aval2 b s), (\\<lambda> x. (snd (aval2 a s) x) + (snd (aval2 b s) x) - (s x)))\"\n\n\ntext{*\n\\endexercise\n\n\\exercise\nThe following type adds a @{text LET} construct to arithmetic expressions:\n*}\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\ntext{* The @{const LET} constructor introduces a local variable:\nthe value of @{term \"LET x e\\<^sub>1 e\\<^sub>2\"} is the value of @{text e\\<^sub>2}\nin the state where @{text x} is bound to the value of @{text e\\<^sub>1} in the original state.\nDefine a function @{const lval} @{text\"::\"} @{typ \"lexp \\<Rightarrow> state \\<Rightarrow> int\"}\nthat evaluates @{typ lexp} expressions. Remember @{term\"s(x := i)\"}.\n\nDefine a conversion @{const inline} @{text\"::\"} @{typ \"lexp \\<Rightarrow> aexp\"}.\nThe expression \\mbox{@{term \"LET x e\\<^sub>1 e\\<^sub>2\"}} is inlined by substituting\nthe converted form of @{text e\\<^sub>1} for @{text x} in the converted form of @{text e\\<^sub>2}.\nSee Exercise~\\ref{exe:subst} for more on substitution.\nProve that @{const inline} is correct w.r.t.\\ evaluation.\n\\endexercise*}\n\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n\"lval (Nl a) s = a\" |\n\"lval (Vl x) s = s x\" |\n\"lval (Plusl a b) s = lval a s + lval b s\" |\n\"lval (LET v a b) s = lval b (s(v:= lval a s))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl a) = N a\" |\n\"inline (Vl x) = V x\" |\n\"inline (Plusl a b) = Plus (inline a) (inline b)\" |\n\"inline (LET v a b) = subst v (inline a) (inline b)\"\n\nlemma \"aval (inline e) s = lval e s\"\n  apply (induction e arbitrary: s rule: inline.induct)\n  apply (auto simp: subst_lemma)\n  done\n\ntext{*\n\\exercise\nShow that equality and less-or-equal tests on @{text aexp} are definable\n*}\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a b = Not (Less b a)\"\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a b = And (Not (Less a b)) (Not (Less b a)) \"\n\ntext{*\nand prove that they do what they are supposed to:\n*}\n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply(auto simp add: Le_def)\n  done\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply(auto simp add: Eq_def)\n  done\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider an alternative type of boolean expressions featuring a conditional: *}\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\ntext {*  First define an evaluation function analogously to @{const bval}: *}\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 b) s = b\" |\n\"ifval (If a b c) s = (if (ifval a s) then (ifval b s) else (ifval c s))\" |\n\"ifval (Less2 a b) s = (aval a s < aval b s)\"\n\ntext{* Then define two translation functions *}\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc b) = Bc2 b \" |\n\"b2ifexp (Not a) = If (b2ifexp a) (Bc2 False) (Bc2 True)\" |\n\"b2ifexp (And a b) = If (b2ifexp a) (b2ifexp b) (Bc2 False)\" |\n\"b2ifexp (Less a b) = Less2 a b\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = Bc b\" |\n\"if2bexp (If a b c) = (And (Not (And (if2bexp a) (Not (if2bexp b)))) \n                           (Not (And (Not (if2bexp a)) (Not (if2bexp c)))))\" |\n\"if2bexp (Less2 a b) = Less a b\"\n\ntext{* and prove their correctness: *}\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\n  apply(induction exp)\n  apply(auto)\n  done\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\n  apply(induction exp)\n  apply(auto)\n  done\n\ntext{*\n\\endexercise\n\n\\exercise\nWe define a new type of purely boolean expressions without any arithmetic\n*}\n\ndatatype pbexp =\n  VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\ntext{*\nwhere variables range over values of type @{typ bool},\nas can be seen from the evaluation function:\n*}\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\"  |\n\"pbval (NOT b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b1 b2) s = (pbval b1 s \\<and> pbval b2 s)\" |\n\"pbval (OR b1 b2) s = (pbval b1 s \\<or> pbval b2 s)\"\n\ntext {* Define a function that checks whether a boolean exression is in NNF\n(negation normal form), i.e., if @{const NOT} is only applied directly\nto @{const VAR}s: *}\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (NOT (VAR x)) = True\" |\n\"is_nnf (NOT p) = False\" |\n\"is_nnf (AND p1 p2) = (is_nnf p1 \\<and> is_nnf p2)\" |\n\"is_nnf (OR p1 p2) = (is_nnf p1 \\<and> is_nnf p2)\"\n\ntext{*\nNow define a function that converts a @{text bexp} into NNF by pushing\n@{const NOT} inwards as much as possible:\n*}\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = VAR x\" |\n\"nnf (AND p1 p2) = AND (nnf p1) (nnf p2)\" | \n\"nnf (OR p1 p2) = OR (nnf p1) (nnf p2)\" |\n\"nnf (NOT (VAR x)) = NOT (VAR x)\" |\n\"nnf (NOT (NOT x)) = nnf x\" |\n\"nnf (NOT (AND p1 p2)) = OR (nnf (NOT p1)) (nnf (NOT p2))\" |\n\"nnf (NOT (OR p1 p2)) = AND (nnf (NOT p1)) (nnf (NOT p2))\" \n\nvalue \"nnf (NOT (OR (NOT (AND (VAR ''x'') (VAR ''y''))) (VAR ''z'')))\"\n\ntext{*\nProve that @{const nnf} does what it is supposed to do:\n*}\n\nlemma neg_aux [simp]: \"pbval (nnf (NOT b)) s = (\\<not> (pbval (nnf b) s))\"\n  apply(induction b)\n  apply(auto)\n  done\n\nlemma pbval_nnf: \"pbval (nnf b) s = pbval b s\"\n  apply(induction b)\n  apply(auto)\n  done\n\nlemma is_nnf_nnf: \"is_nnf (nnf b)\"\n  apply(induction b rule: nnf.induct)\n  apply(auto)\n  done\n\ntext{*\nAn expression is in DNF (disjunctive normal form) if it is in NNF\nand if no @{const OR} occurs below an @{const AND}. Define a corresponding\ntest:\n*}\n\nfun no_ors :: \"pbexp \\<Rightarrow> bool\" where\n\"no_ors (OR e1 e2) = False\" |\n\"no_ors (AND e1 e2) = (no_ors e1 \\<and> no_ors e2)\" |\n\"no_ors e = True\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf (VAR _) = True\" |\n\"is_dnf (NOT b) = is_nnf (NOT b)\" |\n\"is_dnf (AND b1 b2) =  (no_ors b1 \\<and> no_ors b2 \\<and> is_dnf b1 \\<and> is_dnf b2)\" |\n\"is_dnf (OR b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\"\n\nvalue \"is_dnf (OR (AND (NOT (VAR ''x'')) (VAR ''y'')) (VAR ''z''))\"\nvalue \"is_dnf (AND (OR (NOT (VAR ''x'')) (VAR ''y'')) (VAR ''z''))\"\n\ntext {*\nAn NNF can be converted into a DNF in a bottom-up manner.\nThe critical case is the conversion of @{term (sub) \"AND b1 b2\"}.\nHaving converted @{text b\\<^sub>1} and @{text b\\<^sub>2}, apply distributivity of @{const AND}\nover @{const OR}. If we write @{const OR} as a multi-argument function,\nwe can express the distributivity step as follows:\n@{text \"dist_AND (OR a\\<^sub>1 ... a\\<^sub>n) (OR b\\<^sub>1 ... b\\<^sub>m)\"}\n= @{text \"OR (AND a\\<^sub>1 b\\<^sub>1) (AND a\\<^sub>1 b\\<^sub>2) ... (AND a\\<^sub>n b\\<^sub>m)\"}. Define\n*}\n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"dist_AND (OR a b) c = OR (dist_AND a c) (dist_AND b c)\" |\n\"dist_AND a (OR b c) = OR (dist_AND a b) (dist_AND a c)\" |\n\"dist_AND a b = AND a b\" \n\ntext {* and prove that it behaves as follows: *}\n\nlemma pbval_dist [simp]: \"pbval (dist_AND b1 b2) s = pbval (AND b1 b2) s\"\n  apply(induction b1 b2 rule: dist_AND.induct)\n  apply(auto)\n  done\n\nlemma is_dnf_dist: \"is_dnf b1 \\<Longrightarrow> is_dnf b2 \\<Longrightarrow> is_dnf (dist_AND b1 b2)\"\n  apply(induction b1 b2 rule: dist_AND.induct)\n  apply(auto)\n  done\n\ntext {* Use @{const dist_AND} to write a function that converts an NNF\n  to a DNF in the above bottom-up manner.\n*}\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR x) = VAR x\" |\n\"dnf_of_nnf (NOT a) = NOT a\" |\n\"dnf_of_nnf (AND a b) = dist_AND (dnf_of_nnf a) (dnf_of_nnf b)\" |\n\"dnf_of_nnf (OR a b) = OR (dnf_of_nnf a) (dnf_of_nnf b)\" \n\nvalue \"dnf_of_nnf (AND \n                       (AND \n                          (VAR ''b'') \n                          (OR \n                            (NOT (VAR ''c'')) \n                            (VAR ''d'')\n                          ) \n                       ) \n                       (NOT (VAR ''a'')) \n                  )\"\n\ntext {* Prove the correctness of your function: *}\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply(induction b)\n  apply(auto)\n  done\n\n\n\nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply(induction b )\n  apply(auto)\n  done\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:stack-underflow}\nA \\concept{stack underflow} occurs when executing an @{text ADD}\ninstruction on a stack of size less than 2. In our semantics\na term @{term \"exec1 ADD s stk\"} where @{prop \"length stk < 2\"}\nis simply some unspecified value, not an error or exception --- HOL does not have those concepts.\nModify theory @{short_theory \"ASM\"}\nsuch that stack underflow is modelled by @{const None}\nand normal execution by @{text Some}, i.e., the execution functions\nhave return type @{typ \"stack option\"}. Modify all theorems and proofs\naccordingly.\nHint: you may find @{text\"split: option.split\"} useful in your proofs.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:register-machine}\nThis exercise is about a register machine\nand compiler for @{typ aexp}. The machine instructions are\n*}\ntype_synonym reg = nat\ndatatype instr = LDI val reg | LD vname reg | ADD reg reg\n\ntext {*\nwhere type @{text reg} is a synonym for @{typ nat}.\nInstruction @{term \"LDI i r\"} loads @{text i} into register @{text r},\n@{term \"LD x r\"} loads the value of @{text x} into register @{text r},\nand @{term[names_short] \"ADD r\\<^sub>1 r\\<^sub>2\"} adds register @{text r\\<^sub>2} to register @{text r\\<^sub>1}.\n\nDefine the execution of an instruction given a state and a register state;\nthe result is the new register state: *}\n\ntype_synonym rstate = \"reg \\<Rightarrow> val\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec1 (LDI i r) s rs = rs(r:= i)\" |\n\"exec1 (LD x r) s rs = rs(r:= s(x))\" |\n\"exec1 (ADD r1 r2) s rs = rs(r1:= (rs r1) + (rs r2))\"\n\ntext{*\nDefine the execution @{const[source] exec} of a list of instructions as for the stack machine.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto @{text r}. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"< r\"} should be left alone.\nDefine the compiler and prove it correct:\n*}\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec [] _ rs = rs\" |\n\"exec (i # is) s rs = exec is s (exec1 i s rs)\"\n\nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n\"comp (N n) r =  [LDI n r]\" |\n\"comp (V x) r = [LD x r]\" |\n\"comp (Plus a1 a2) r = (comp a1 r) @ (comp a2 (r+1)) @ [ADD r (r+1)]\"\n\nlemma [simp]: \"exec (xs @ ys) s rs = exec ys s (exec xs s rs)\"\n  apply(induction xs arbitrary: rs)\n  apply(auto)\n  done\n\nlemma [simp]: \"r < q \\<Longrightarrow> exec (comp a q) s rs r = rs r\"\n  apply(induction a arbitrary: rs r q)\n  apply(auto)\n  done\n\n\ntheorem \"exec (comp a r) s rs r = aval a s\"\n  apply(induction a arbitrary: rs r)\n  apply(auto)\n  done\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:accumulator}\nThis exercise is a variation of the previous one\nwith a different instruction set:\n*}\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\ntext{*\nAll instructions refer implicitly to register 0 as a source or target:\n@{const LDI0} and @{const LD0} load a value into register 0, @{term \"MV0 r\"}\ncopies the value in register 0 into register @{text r}, and @{term \"ADD0 r\"}\nadds the value in register @{text r} to the value in register 0;\n@{term \"MV0 0\"} and @{term \"ADD0 0\"} are legal. Define the execution functions\n*}\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec01 (LDI0 x) s rs = rs(0:= x)\" |\n\"exec01 (LD0 v) s rs = rs(0:= (s v))\" |\n\"exec01 (MV0 r) s rs = rs(r:= (rs 0))\" |\n\"exec01 (ADD0 r) s rs = rs(0:=(rs 0) + (rs r))\" \n\ntext{*\nand @{const exec0} for instruction lists.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto register 0. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"\\<le> r\"} should be left alone\n(with the exception of 0). Define the compiler and prove it correct:\n*}\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec0 [] _ rs = rs\" |\n\"exec0 (x # xs) s rs = exec0 xs s (exec01 x s rs)\"\n\nfun comp0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0 (N n) r = [LDI0 n]\" |\n\"comp0 (V x) r = [LD0 x]\" |\n\"comp0 (Plus a b) r = (comp0 a (r+1)) @ [MV0 (r+1)] @ (comp0 b (r+2)) @ [ADD0 (r+1)]\"\n\nlemma [simp]: \"exec0 (xs @ ys) s rs = exec0 ys s (exec0 xs s rs)\"\n  apply(induction xs arbitrary: rs)\n  apply(auto)\n  done\n\nlemma [simp]: \"(0 < r) \\<and> (r \\<le> q) \\<Longrightarrow> exec0 (comp0 a q) s rs r = rs r\"\n  apply(induction a arbitrary: r q rs)\n  apply(auto)\n  done\n\ntheorem \"exec0 (comp0 a r) s rs 0 = aval a s\"\n  apply(induction a arbitrary: r rs)\n  apply(auto)\n  done\n\ntext{*\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "shangsuru", "repo": "concrete-semantics", "sha": "219c05ac20de199cafb6ddec2f53a9dfe0d2679a", "save_path": "github-repos/isabelle/shangsuru-concrete-semantics", "path": "github-repos/isabelle/shangsuru-concrete-semantics/concrete-semantics-219c05ac20de199cafb6ddec2f53a9dfe0d2679a/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.9099070054272775, "lm_q1q2_score": 0.7999417939121986}}
{"text": "(*  Title: HOL/ex/Birthday_Paradox.thy\n    Author: Lukas Bulwahn, TU Muenchen, 2007\n*)\n\nsection \\<open>A Formulation of the Birthday Paradox\\<close>\n\ntheory Birthday_Paradox\nimports MainRLT \"HOL-Library.FuncSet\"\nbegin\n\nsection \\<open>Cardinality\\<close>\n\nlemma card_product_dependent:\n  assumes \"finite S\"\n  assumes \"\\<forall>x \\<in> S. finite (T x)\"\n  shows \"card {(x, y). x \\<in> S \\<and> y \\<in> T x} = (\\<Sum>x \\<in> S. card (T x))\"\n  using card_SigmaI[OF assms, symmetric] by (auto intro!: arg_cong[where f=card] simp add: Sigma_def)\n\nlemma card_extensional_funcset_inj_on:\n  assumes \"finite S\" \"finite T\" \"card S \\<le> card T\"\n  shows \"card {f \\<in> extensional_funcset S T. inj_on f S} = fact (card T) div (fact (card T - card S))\"\nusing assms\nproof (induct S arbitrary: T rule: finite_induct)\n  case empty\n  from this show ?case by (simp add: Collect_conv_if PiE_empty_domain)\nnext\n  case (insert x S)\n  { fix x\n    from \\<open>finite T\\<close> have \"finite (T - {x})\" by auto\n    from \\<open>finite S\\<close> this have \"finite (extensional_funcset S (T - {x}))\"\n      by (rule finite_PiE)\n    moreover\n    have \"{f : extensional_funcset S (T - {x}). inj_on f S} \\<subseteq> (extensional_funcset S (T - {x}))\" by auto\n    ultimately have \"finite {f : extensional_funcset S (T - {x}). inj_on f S}\"\n      by (auto intro: finite_subset)\n  } note finite_delete = this\n  from insert have hyps: \"\\<forall>y \\<in> T. card ({g. g \\<in> extensional_funcset S (T - {y}) \\<and> inj_on g S}) = fact (card T - 1) div fact ((card T - 1) - card S)\"(is \"\\<forall> _ \\<in> T. _ = ?k\") by auto\n  from extensional_funcset_extend_domain_inj_on_eq[OF \\<open>x \\<notin> S\\<close>]\n  have \"card {f. f \\<in> extensional_funcset (insert x S) T \\<and> inj_on f (insert x S)} =\n    card ((\\<lambda>(y, g). g(x := y)) ` {(y, g). y \\<in> T \\<and> g \\<in> extensional_funcset S (T - {y}) \\<and> inj_on g S})\"\n    by metis\n  also from extensional_funcset_extend_domain_inj_onI[OF \\<open>x \\<notin> S\\<close>, of T] have \"\\<dots> =  card {(y, g). y \\<in> T \\<and> g \\<in> extensional_funcset S (T - {y}) \\<and> inj_on g S}\"\n    by (simp add: card_image)\n  also have \"card {(y, g). y \\<in> T \\<and> g \\<in> extensional_funcset S (T - {y}) \\<and> inj_on g S} =\n    card {(y, g). y \\<in> T \\<and> g \\<in> {f \\<in> extensional_funcset S (T - {y}). inj_on f S}}\" by auto\n  also from \\<open>finite T\\<close> finite_delete have \"... = (\\<Sum>y \\<in> T. card {g. g \\<in> extensional_funcset S (T - {y}) \\<and>  inj_on g S})\"\n    by (subst card_product_dependent) auto\n  also from hyps have \"... = (card T) * ?k\"\n    by auto\n  also have \"... = card T * fact (card T - 1) div fact (card T - card (insert x S))\"\n    using insert unfolding div_mult1_eq[of \"card T\" \"fact (card T - 1)\"]\n    by (simp add: fact_mod)\n  also have \"... = fact (card T) div fact (card T - card (insert x S))\"\n    using insert by (simp add: fact_reduce[of \"card T\"])\n  finally show ?case .\nqed\n\nlemma card_extensional_funcset_not_inj_on:\n  assumes \"finite S\" \"finite T\" \"card S \\<le> card T\"\n  shows \"card {f \\<in> extensional_funcset S T. \\<not> inj_on f S} = (card T) ^ (card S) - (fact (card T)) div (fact (card T - card S))\"\nproof -\n  have subset: \"{f : extensional_funcset S T. inj_on f S} <= extensional_funcset S T\" by auto\n  from finite_subset[OF subset] assms have finite: \"finite {f : extensional_funcset S T. inj_on f S}\"\n    by (auto intro!: finite_PiE)\n  have \"{f \\<in> extensional_funcset S T. \\<not> inj_on f S} = extensional_funcset S T - {f \\<in> extensional_funcset S T. inj_on f S}\" by auto\n  from assms this finite subset show ?thesis\n    by (simp add: card_Diff_subset card_PiE card_extensional_funcset_inj_on prod_constant)\nqed\n\nlemma prod_upto_nat_unfold:\n  \"prod f {m..(n::nat)} = (if n < m then 1 else (if n = 0 then f 0 else f n * prod f {m..(n - 1)}))\"\n  by auto (auto simp add: gr0_conv_Suc atLeastAtMostSuc_conv)\n\nsection \\<open>Birthday paradox\\<close>\n\nlemma birthday_paradox:\n  assumes \"card S = 23\" \"card T = 365\"\n  shows \"2 * card {f \\<in> extensional_funcset S T. \\<not> inj_on f S} \\<ge> card (extensional_funcset S T)\"\nproof -\n  from \\<open>card S = 23\\<close> \\<open>card T = 365\\<close> have \"finite S\" \"finite T\" \"card S <= card T\" by (auto intro: card_ge_0_finite)\n  from assms show ?thesis\n    using card_PiE[OF \\<open>finite S\\<close>, of \"\\<lambda>i. T\"] \\<open>finite S\\<close>\n      card_extensional_funcset_not_inj_on[OF \\<open>finite S\\<close> \\<open>finite T\\<close> \\<open>card S <= card T\\<close>]\n    by (simp add: fact_div_fact prod_upto_nat_unfold prod_constant)\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/ex/Birthday_Paradox.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8791467548438124, "lm_q1q2_score": 0.7999417829766866}}
{"text": "theory ch612\nimports Main\nbegin\n\nsubsection{*Inductive definition of the even numbers*}\n\ninductive_set Ev :: \"nat set\" where\nZeroI: \"0 : Ev\" |\nAdd2I: \"n : Ev \\<Longrightarrow> Suc(Suc n) : Ev\"\n\ntext{* Using the introduction rules: *}\nlemma \"Suc(Suc(Suc(Suc 0))) \\<in> Ev\"\napply(rule Add2I)\napply(rule Add2I)\napply(rule ZeroI)\ndone\n\ntext{*A simple inductive proof: *}\nlemma \"n:Ev \\<Longrightarrow> n+n : Ev\"\napply(induct rule: Ev.induct)\n apply(simp)\n apply(rule Ev.ZeroI)\napply(simp)\napply(rule Ev.Add2I)\napply(rule Ev.Add2I)\napply(assumption)\ndone\n\ntext{* You can also use the rules for Ev as conditional simplification\nrules. This can shorten proofs considerably.  \\emph{Warning}:\nconditional rules can lead to nontermination of the simplifier.  The\nrules for Ev are OK because the premises are always smaller than the\nconclusion. The list of rules for Ev is contained in Ev.intrs.  *}\n\ndeclare Ev.intros[simp]\n\ntext{* A shorter proof: *}\n\nlemma \"n:Ev \\<Longrightarrow> n+n : Ev\"\napply(induct rule: Ev.induct)\napply(auto)\ndone\n\ntext{* Nice example, but overkill: don't need assumption @{prop\"n \\<in>\nEv\"} because @{prop\"n+n \\<in> Ev\"} is true for all @{text n}.\n\nHowever, here we really need the assumptions: *}\n\nlemma \"\\<lbrakk> m:Ev; n:Ev \\<rbrakk> \\<Longrightarrow> m+n : Ev\"\napply(induct rule: Ev.induct)\napply(auto)\ndone\n\ntext{* An inductive proof of @{prop\"1 \\<notin> Ev\"}: *}\n\nlemma \"n \\<in> Ev \\<Longrightarrow> n \\<noteq> 1\"\napply(induct rule: Ev.induct)\napply(auto)\ndone\n\ntext{* The general case: *}\nlemma \"n \\<in> Ev \\<Longrightarrow> \\<not>(\\<exists>k. n = 2*k+1)\"\napply(induct rule: Ev.induct)\n apply(simp)\napply arith\ndone\n\n\nsubsection{*Inductive definition of AVL trees*}\n\ndatatype tree = Tip | Br tree tree\n\ninductive_set AVL :: \"(tree * nat)set\" where\n\"(Tip,0) : AVL\" |\n\"\\<lbrakk> (t,m) : AVL; (u,n) : AVL; m=n | m = n+1 | n = m+1 \\<rbrakk> \\<Longrightarrow>\n (Br t u, max m n + 1) : AVL\"\n\ntext{* We prove a lower bound for the number of internal nodes in an\nAVL tree of height h. *}\n\nfun fib1 :: \"nat => nat\" where\n\"fib1 0 = 0\" |\n\"fib1 (Suc 0) = 1\" |\n\"fib1 (Suc (Suc x)) = fib1 x + fib1 (Suc x) + 1\"\n\nlemma fib1_Suc: \"fib1(Suc n) \\<le> 2*fib1(n) + 1\"\napply(induct n rule: fib1.induct)\napply auto\ndone\n\nlemma \"(t,h) : AVL \\<Longrightarrow> fib1 h \\<le> size t\"\napply(induct rule:AVL.induct)\n apply simp\napply(erule disjE)\n apply simp\n apply(cut_tac n=n in fib1_Suc)\n apply arith\napply(erule disjE)\n apply (simp add:max_def)\napply (simp add:max_def)\ndone\n\nend\n", "meta": {"author": "tecty", "repo": "COMP4161", "sha": "95aa77d289c14cb85477c7f91467f81cd66fcd62", "save_path": "github-repos/isabelle/tecty-COMP4161", "path": "github-repos/isabelle/tecty-COMP4161/COMP4161-95aa77d289c14cb85477c7f91467f81cd66fcd62/hol-tut/demo/ch612.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7997628744213376}}
{"text": "theory QuantLists\n    imports Main\nbegin\n\ntext \\<open> Define a universal and an existential quantifier on lists\nusing primitive recursion.  Expression @{term \"alls P xs\"} should\nbe true iff @{term \"P x\"} holds for every element @{term x} of\n@{term xs}, and @{term \"exs P xs\"} should be true iff @{term \"P x\"}\nholds for some element @{term x} of @{term xs}.\n\\<close>\n\nconsts \n  alls' :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  exs'  :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n\nfun alls :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where\n  \"alls _ [] = True\" |\n  \"alls P (x#xs) = (P x \\<and> (alls P xs))\"\n\nlemma alls_app[simp]:\"alls P (xs @ ys) = (alls P xs \\<and> alls P ys)\"\n  apply (induction xs)\n  by auto\n\nfun exs :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where\n  \"exs _ [] = False\" |\n  \"exs P (x#xs) = (P x \\<or> (exs P xs))\"\n\nlemma exs_app[simp]:\"exs P (xs @ ys) = (exs P xs \\<or> exs P ys)\"\n  apply (induction xs)\n  by auto\n\nlemma alls_exs_dual1:\"exs P xs = (\\<not>alls (\\<lambda> x. \\<not>P x) xs)\"\n  apply (induction xs)\n  by auto\n\nlemma exs_alls_dual1:\"alls P xs = (\\<not>exs (\\<lambda> x. \\<not>P x) xs)\"\n  apply (induction xs)\n  by auto\n\ntext \\<open>\nProve or disprove (by counterexample) the following theorems.\nYou may have to prove some lemmas first.\n\nUse the @{text \"[simp]\"}-attribute only if the equation is truly a\nsimplification and is necessary for some later proof.\n\\<close>\n\nlemma \"alls (\\<lambda>x. P x \\<and> Q x) xs = (alls P xs \\<and> alls Q xs)\"\n  apply (induction xs) by auto\n\nlemma \"alls P (rev xs) = alls P xs\"\n  apply (induction xs) by auto\n\nlemma \"exs (\\<lambda>x. P x \\<and> Q x) xs = (exs P xs \\<and> exs Q xs)\"\n  (*\nAuto Quickcheck found a counterexample:\n  P = {a\\<^sub>1}\n  Q = {a\\<^sub>2}\n  xs = [a\\<^sub>1, a\\<^sub>2]\nEvaluated terms:\n  exs (\\<lambda>x. P x \\<and> Q x) xs = False\n  exs P xs \\<and> exs Q xs = True\n*)\n  oops\n\nlemma \"exs P (map f xs) = exs (P o f) xs\"\n  apply (induction xs) by auto\n\nlemma \"exs P (rev xs) = exs P xs\"\n  apply (induction xs) by auto\n\ntext \\<open> Find a (non-trivial) term @{text Z} such that the following equation holds: \\<close>\n\nlemma \"exs (\\<lambda>x. P x \\<or> Q x) xs = (exs P xs) \\<or> (exs Q xs)\"\n  apply (induction xs) by auto\n\ntext \\<open> Express the existential via the universal quantifier --\n@{text exs} should not occur on the right-hand side: \\<close>\n\nlemma \"exs P xs = (\\<not> alls (\\<lambda>x. \\<not>P x) xs)\"\n  by (rule alls_exs_dual1)\n\ntext \\<open>\nDefine a primitive-recursive function @{term \"is_in x xs\"} that\nchecks if @{term x} occurs in @{term xs}. Now express\n@{text is_in} via @{term exs}:\n\\<close>\n\nprimrec is_in :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where\n\"is_in _ [] = False\"|\n\"is_in a (x#xs) = ((a = x) \\<or> (is_in a xs))\"\n\nlemma \"is_in a xs = exs (\\<lambda>x. x = a) xs\"\n  apply (induction xs) by auto\n\ntext \\<open> Define a primitive-recursive function @{term \"nodups xs\"}\nthat is true iff @{term xs} does not contain duplicates, and a\nfunction @{term \"deldups xs\"} that removes all duplicates.  Note\nthat @{term \"deldups[x,y,x]\"} (where @{term x} and @{term y} are\ndistinct) can be either @{term \"[x,y]\"} or @{term \"[y,x]\"}.\n\nProve or disprove (by counterexample) the following theorems.\n\\<close>\n\nprimrec nodups :: \"'a list \\<Rightarrow> bool\"\n  where\n\"nodups [] = True\" |\n\"nodups (x#xs) = ((x \\<in> set xs) \\<or> nodups xs)\"\n\nprimrec deldups :: \"'a list \\<Rightarrow> 'a list\"\n  where\n\"deldups [] = []\" |\n\"deldups (x#xs) = (if (x \\<in> set xs)\n                   then deldups xs\n                   else x#(deldups xs))\"\n\nlemma \"length (deldups xs) <= length xs\"\n  apply (induction xs) by auto\n\nlemma \"nodups (deldups xs)\"\n  apply (induction xs) by auto\n\nlemma \"deldups (rev xs) = rev (deldups xs)\"\n(* counter example:\n  xs = [1, 2, 3, 1]\n  deldups (rev xs) = [3, 2, 1]\n  rev (deldups xs) = [2, 3, 1]\n*)\n  oops\n\n(*<*) end (*>*)\n", "meta": {"author": "tomssem", "repo": "isabelle_exercises", "sha": "000b8edcb2050d4931e3177e9a339101d777dfe7", "save_path": "github-repos/isabelle/tomssem-isabelle_exercises", "path": "github-repos/isabelle/tomssem-isabelle_exercises/isabelle_exercises-000b8edcb2050d4931e3177e9a339101d777dfe7/lists/QuantLists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8840392741081575, "lm_q1q2_score": 0.7997466114625005}}
{"text": "theory iter\nimports Main\nbegin\n\nprimrec iter::\"nat \\<Rightarrow>('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\"\n  where\n\"iter 0 f = (\\<lambda> x. x)\"\n|\"iter (Suc n) f = (\\<lambda> x. f ((iter n f) x))\"\n\n(*Prove the following*)\nlemma fixedpt_iteration:\n  assumes \"f x = x\"\n  shows \"iter (n+1) f x = x\"\n  using assms\nproof(induction n)\n  case 0\n  then show ?case by simp \nnext\n  case (Suc n)\n  then show ?case by simp\nqed\n\nlemma iterative_fixed_pt:\n  assumes \"iter (n+1) f x = iter n f x\" \n  shows \"iter (k+(n+1)) f x = iter (k+n) f x\"\n  using assms\nproof(induction k)\n  case 0\n  then show ?case \n    by force\nnext\n  case (Suc m)\n  have \"iter (m + (n + 1)) f x = iter (Suc m + n) f x\" by simp\n  then show ?case using Suc.IH Suc.prems by fastforce\nqed\n\nend", "meta": {"author": "prathamesht-cs", "repo": "Groupabelle", "sha": "3b8369e3016b8e380eccd9c0033c60aa4a9755cf", "save_path": "github-repos/isabelle/prathamesht-cs-Groupabelle", "path": "github-repos/isabelle/prathamesht-cs-Groupabelle/Groupabelle-3b8369e3016b8e380eccd9c0033c60aa4a9755cf/Free Group/iter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7997031715813143}}
{"text": "(*  Title:      HOL/Int.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Author:     Tobias Nipkow, Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>The Integers as Equivalence Classes over Pairs of Natural Numbers\\<close>\n\ntheory Int\n  imports Quotient Groups_Big Fun_Def\nbegin\n\nsubsection \\<open>Definition of integers as a quotient type\\<close>\n\ndefinition intrel :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> bool\"\n  where \"intrel = (\\<lambda>(x, y) (u, v). x + v = u + y)\"\n\nlemma intrel_iff [simp]: \"intrel (x, y) (u, v) \\<longleftrightarrow> x + v = u + y\"\n  by (simp add: intrel_def)\n\nquotient_type int = \"nat \\<times> nat\" / \"intrel\"\n  morphisms Rep_Integ Abs_Integ\nproof (rule equivpI)\n  show \"reflp intrel\" by (auto simp: reflp_def)\n  show \"symp intrel\" by (auto simp: symp_def)\n  show \"transp intrel\" by (auto simp: transp_def)\nqed\n\nlemma eq_Abs_Integ [case_names Abs_Integ, cases type: int]:\n  \"(\\<And>x y. z = Abs_Integ (x, y) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (induct z) auto\n\n\nsubsection \\<open>Integers form a commutative ring\\<close>\n\ninstantiation int :: comm_ring_1\nbegin\n\nlift_definition zero_int :: \"int\" is \"(0, 0)\" .\n\nlift_definition one_int :: \"int\" is \"(1, 0)\" .\n\nlift_definition plus_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y) (u, v). (x + u, y + v)\"\n  by clarsimp\n\nlift_definition uminus_int :: \"int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y). (y, x)\"\n  by clarsimp\n\nlift_definition minus_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y) (u, v). (x + v, y + u)\"\n  by clarsimp\n\nlift_definition times_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y) (u, v). (x*u + y*v, x*v + y*u)\"\nproof (unfold intrel_def, clarify)\n  fix s t u v w x y z :: nat\n  assume \"s + v = u + t\" and \"w + z = y + x\"\n  then have \"(s + v) * w + (u + t) * x + u * (w + z) + v * (y + x) =\n    (u + t) * w + (s + v) * x + u * (y + x) + v * (w + z)\"\n    by simp\n  then show \"(s * w + t * x) + (u * z + v * y) = (u * y + v * z) + (s * x + t * w)\"\n    by (simp add: algebra_simps)\nqed\n\ninstance\n  by standard (transfer; clarsimp simp: algebra_simps)+\n\nend\n\nabbreviation int :: \"nat \\<Rightarrow> int\"\n  where \"int \\<equiv> of_nat\"\n\nlemma int_def: \"int n = Abs_Integ (n, 0)\"\n  by (induct n) (simp add: zero_int.abs_eq, simp add: one_int.abs_eq plus_int.abs_eq)\n\nlemma int_transfer [transfer_rule]:\n  includes lifting_syntax\n  shows \"rel_fun (=) pcr_int (\\<lambda>n. (n, 0)) int\"\n  by (simp add: rel_fun_def int.pcr_cr_eq cr_int_def int_def)\n\nlemma int_diff_cases: obtains (diff) m n where \"z = int m - int n\"\n  by transfer clarsimp\n\n\nsubsection \\<open>Integers are totally ordered\\<close>\n\ninstantiation int :: linorder\nbegin\n\nlift_definition less_eq_int :: \"int \\<Rightarrow> int \\<Rightarrow> bool\"\n  is \"\\<lambda>(x, y) (u, v). x + v \\<le> u + y\"\n  by auto\n\nlift_definition less_int :: \"int \\<Rightarrow> int \\<Rightarrow> bool\"\n  is \"\\<lambda>(x, y) (u, v). x + v < u + y\"\n  by auto\n\ninstance\n  by standard (transfer, force)+\n\nend\n\ninstantiation int :: distrib_lattice\nbegin\n\ndefinition \"(inf :: int \\<Rightarrow> int \\<Rightarrow> int) = min\"\n\ndefinition \"(sup :: int \\<Rightarrow> int \\<Rightarrow> int) = max\"\n\ninstance\n  by standard (auto simp add: inf_int_def sup_int_def max_min_distrib2)\n\nend\n\nsubsection \\<open>Ordering properties of arithmetic operations\\<close>\n\ninstance int :: ordered_cancel_ab_semigroup_add\nproof\n  fix i j k :: int\n  show \"i \\<le> j \\<Longrightarrow> k + i \\<le> k + j\"\n    by transfer clarsimp\nqed\n\ntext \\<open>Strict Monotonicity of Multiplication.\\<close>\n\ntext \\<open>Strict, in 1st argument; proof is by induction on \\<open>k > 0\\<close>.\\<close>\nlemma zmult_zless_mono2_lemma: \"i < j \\<Longrightarrow> 0 < k \\<Longrightarrow> int k * i < int k * j\"\n  for i j :: int\nproof (induct k)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc k)\n  then show ?case\n    by (cases \"k = 0\") (simp_all add: distrib_right add_strict_mono)\nqed\n\nlemma zero_le_imp_eq_int:\n  assumes \"k \\<ge> (0::int)\" shows \"\\<exists>n. k = int n\"\nproof -\n  have \"b \\<le> a \\<Longrightarrow> \\<exists>n::nat. a = n + b\" for a b\n    using exI[of _ \"a - b\"] by simp\n  with assms show ?thesis\n    by transfer auto\nqed\n\nlemma zero_less_imp_eq_int:\n  assumes \"k > (0::int)\" shows \"\\<exists>n>0. k = int n\"\nproof -\n  have \"b < a \\<Longrightarrow> \\<exists>n::nat. n>0 \\<and> a = n + b\" for a b\n    using exI[of _ \"a - b\"] by simp\n  with assms show ?thesis\n    by transfer auto\nqed\n\nlemma zmult_zless_mono2: \"i < j \\<Longrightarrow> 0 < k \\<Longrightarrow> k * i < k * j\"\n  for i j k :: int\n  by (drule zero_less_imp_eq_int) (auto simp add: zmult_zless_mono2_lemma)\n\n\ntext \\<open>The integers form an ordered integral domain.\\<close>\n\ninstantiation int :: linordered_idom\nbegin\n\ndefinition zabs_def: \"\\<bar>i::int\\<bar> = (if i < 0 then - i else i)\"\n\ndefinition zsgn_def: \"sgn (i::int) = (if i = 0 then 0 else if 0 < i then 1 else - 1)\"\n\ninstance\nproof\n  fix i j k :: int\n  show \"i < j \\<Longrightarrow> 0 < k \\<Longrightarrow> k * i < k * j\"\n    by (rule zmult_zless_mono2)\n  show \"\\<bar>i\\<bar> = (if i < 0 then -i else i)\"\n    by (simp only: zabs_def)\n  show \"sgn (i::int) = (if i=0 then 0 else if 0<i then 1 else - 1)\"\n    by (simp only: zsgn_def)\nqed\n\nend\n\nlemma zless_imp_add1_zle: \"w < z \\<Longrightarrow> w + 1 \\<le> z\"\n  for w z :: int\n  by transfer clarsimp\n\nlemma zless_iff_Suc_zadd: \"w < z \\<longleftrightarrow> (\\<exists>n. z = w + int (Suc n))\"\n  for w z :: int\nproof -\n  have \"\\<And>a b c d. a + d < c + b \\<Longrightarrow> \\<exists>n. c + b = Suc (a + n + d)\"\n  proof -\n    fix a b c d :: nat\n    assume \"a + d < c + b\"\n    then have \"c + b = Suc (a + (c + b - Suc (a + d)) + d) \"\n      by arith\n    then show \"\\<exists>n. c + b = Suc (a + n + d)\"\n      by (rule exI)\n  qed\n  then show ?thesis\n    by transfer auto\nqed\n\nlemma zabs_less_one_iff [simp]: \"\\<bar>z\\<bar> < 1 \\<longleftrightarrow> z = 0\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\n  for z :: int\nproof\n  assume ?rhs\n  then show ?lhs by simp\nnext\n  assume ?lhs\n  with zless_imp_add1_zle [of \"\\<bar>z\\<bar>\" 1] have \"\\<bar>z\\<bar> + 1 \\<le> 1\" by simp\n  then have \"\\<bar>z\\<bar> \\<le> 0\" by simp\n  then show ?rhs by simp\nqed\n\n\nsubsection \\<open>Embedding of the Integers into any \\<open>ring_1\\<close>: \\<open>of_int\\<close>\\<close>\n\ncontext ring_1\nbegin\n\nlift_definition of_int :: \"int \\<Rightarrow> 'a\"\n  is \"\\<lambda>(i, j). of_nat i - of_nat j\"\n  by (clarsimp simp add: diff_eq_eq eq_diff_eq diff_add_eq\n      of_nat_add [symmetric] simp del: of_nat_add)\n\nlemma of_int_0 [simp]: \"of_int 0 = 0\"\n  by transfer simp\n\nlemma of_int_1 [simp]: \"of_int 1 = 1\"\n  by transfer simp\n\nlemma of_int_add [simp]: \"of_int (w + z) = of_int w + of_int z\"\n  by transfer (clarsimp simp add: algebra_simps)\n\nlemma of_int_minus [simp]: \"of_int (- z) = - (of_int z)\"\n  by (transfer fixing: uminus) clarsimp\n\nlemma of_int_diff [simp]: \"of_int (w - z) = of_int w - of_int z\"\n  using of_int_add [of w \"- z\"] by simp\n\nlemma of_int_mult [simp]: \"of_int (w*z) = of_int w * of_int z\"\n  by (transfer fixing: times) (clarsimp simp add: algebra_simps)\n\nlemma mult_of_int_commute: \"of_int x * y = y * of_int x\"\n  by (transfer fixing: times) (auto simp: algebra_simps mult_of_nat_commute)\n\ntext \\<open>Collapse nested embeddings.\\<close>\nlemma of_int_of_nat_eq [simp]: \"of_int (int n) = of_nat n\"\n  by (induct n) auto\n\nlemma of_int_numeral [simp, code_post]: \"of_int (numeral k) = numeral k\"\n  by (simp add: of_nat_numeral [symmetric] of_int_of_nat_eq [symmetric])\n\nlemma of_int_neg_numeral [code_post]: \"of_int (- numeral k) = - numeral k\"\n  by simp\n\nlemma of_int_power [simp]: \"of_int (z ^ n) = of_int z ^ n\"\n  by (induct n) simp_all\n\nlemma of_int_of_bool [simp]:\n  \"of_int (of_bool P) = of_bool P\"\n  by auto\n\nend\n\ncontext ring_char_0\nbegin\n\nlemma of_int_eq_iff [simp]: \"of_int w = of_int z \\<longleftrightarrow> w = z\"\n  by transfer (clarsimp simp add: algebra_simps of_nat_add [symmetric] simp del: of_nat_add)\n\ntext \\<open>Special cases where either operand is zero.\\<close>\nlemma of_int_eq_0_iff [simp]: \"of_int z = 0 \\<longleftrightarrow> z = 0\"\n  using of_int_eq_iff [of z 0] by simp\n\nlemma of_int_0_eq_iff [simp]: \"0 = of_int z \\<longleftrightarrow> z = 0\"\n  using of_int_eq_iff [of 0 z] by simp\n\nlemma of_int_eq_1_iff [iff]: \"of_int z = 1 \\<longleftrightarrow> z = 1\"\n  using of_int_eq_iff [of z 1] by simp\n\nlemma numeral_power_eq_of_int_cancel_iff [simp]:\n  \"numeral x ^ n = of_int y \\<longleftrightarrow> numeral x ^ n = y\"\n  using of_int_eq_iff[of \"numeral x ^ n\" y, unfolded of_int_numeral of_int_power] .\n\nlemma of_int_eq_numeral_power_cancel_iff [simp]:\n  \"of_int y = numeral x ^ n \\<longleftrightarrow> y = numeral x ^ n\"\n  using numeral_power_eq_of_int_cancel_iff [of x n y] by (metis (mono_tags))\n\nlemma neg_numeral_power_eq_of_int_cancel_iff [simp]:\n  \"(- numeral x) ^ n = of_int y \\<longleftrightarrow> (- numeral x) ^ n = y\"\n  using of_int_eq_iff[of \"(- numeral x) ^ n\" y]\n  by simp\n\nlemma of_int_eq_neg_numeral_power_cancel_iff [simp]:\n  \"of_int y = (- numeral x) ^ n \\<longleftrightarrow> y = (- numeral x) ^ n\"\n  using neg_numeral_power_eq_of_int_cancel_iff[of x n y] by (metis (mono_tags))\n\nlemma of_int_eq_of_int_power_cancel_iff[simp]: \"(of_int b) ^ w = of_int x \\<longleftrightarrow> b ^ w = x\"\n  by (metis of_int_power of_int_eq_iff)\n\nlemma of_int_power_eq_of_int_cancel_iff[simp]: \"of_int x = (of_int b) ^ w \\<longleftrightarrow> x = b ^ w\"\n  by (metis of_int_eq_of_int_power_cancel_iff)\n\nend\n\ncontext linordered_idom\nbegin\n\ntext \\<open>Every \\<open>linordered_idom\\<close> has characteristic zero.\\<close>\nsubclass ring_char_0 ..\n\nlemma of_int_le_iff [simp]: \"of_int w \\<le> of_int z \\<longleftrightarrow> w \\<le> z\"\n  by (transfer fixing: less_eq)\n    (clarsimp simp add: algebra_simps of_nat_add [symmetric] simp del: of_nat_add)\n\nlemma of_int_less_iff [simp]: \"of_int w < of_int z \\<longleftrightarrow> w < z\"\n  by (simp add: less_le order_less_le)\n\nlemma of_int_0_le_iff [simp]: \"0 \\<le> of_int z \\<longleftrightarrow> 0 \\<le> z\"\n  using of_int_le_iff [of 0 z] by simp\n\nlemma of_int_le_0_iff [simp]: \"of_int z \\<le> 0 \\<longleftrightarrow> z \\<le> 0\"\n  using of_int_le_iff [of z 0] by simp\n\nlemma of_int_0_less_iff [simp]: \"0 < of_int z \\<longleftrightarrow> 0 < z\"\n  using of_int_less_iff [of 0 z] by simp\n\nlemma of_int_less_0_iff [simp]: \"of_int z < 0 \\<longleftrightarrow> z < 0\"\n  using of_int_less_iff [of z 0] by simp\n\nlemma of_int_1_le_iff [simp]: \"1 \\<le> of_int z \\<longleftrightarrow> 1 \\<le> z\"\n  using of_int_le_iff [of 1 z] by simp\n\nlemma of_int_le_1_iff [simp]: \"of_int z \\<le> 1 \\<longleftrightarrow> z \\<le> 1\"\n  using of_int_le_iff [of z 1] by simp\n\nlemma of_int_1_less_iff [simp]: \"1 < of_int z \\<longleftrightarrow> 1 < z\"\n  using of_int_less_iff [of 1 z] by simp\n\nlemma of_int_less_1_iff [simp]: \"of_int z < 1 \\<longleftrightarrow> z < 1\"\n  using of_int_less_iff [of z 1] by simp\n\nlemma of_int_pos: \"z > 0 \\<Longrightarrow> of_int z > 0\"\n  by simp\n\nlemma of_int_nonneg: \"z \\<ge> 0 \\<Longrightarrow> of_int z \\<ge> 0\"\n  by simp\n\nlemma of_int_abs [simp]: \"of_int \\<bar>x\\<bar> = \\<bar>of_int x\\<bar>\"\n  by (auto simp add: abs_if)\n\nlemma of_int_lessD:\n  assumes \"\\<bar>of_int n\\<bar> < x\"\n  shows \"n = 0 \\<or> x > 1\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  then have \"\\<bar>n\\<bar> \\<noteq> 0\" by simp\n  then have \"\\<bar>n\\<bar> > 0\" by simp\n  then have \"\\<bar>n\\<bar> \\<ge> 1\"\n    using zless_imp_add1_zle [of 0 \"\\<bar>n\\<bar>\"] by simp\n  then have \"\\<bar>of_int n\\<bar> \\<ge> 1\"\n    unfolding of_int_1_le_iff [of \"\\<bar>n\\<bar>\", symmetric] by simp\n  then have \"1 < x\" using assms by (rule le_less_trans)\n  then show ?thesis ..\nqed\n\nlemma of_int_leD:\n  assumes \"\\<bar>of_int n\\<bar> \\<le> x\"\n  shows \"n = 0 \\<or> 1 \\<le> x\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  then have \"\\<bar>n\\<bar> \\<noteq> 0\" by simp\n  then have \"\\<bar>n\\<bar> > 0\" by simp\n  then have \"\\<bar>n\\<bar> \\<ge> 1\"\n    using zless_imp_add1_zle [of 0 \"\\<bar>n\\<bar>\"] by simp\n  then have \"\\<bar>of_int n\\<bar> \\<ge> 1\"\n    unfolding of_int_1_le_iff [of \"\\<bar>n\\<bar>\", symmetric] by simp\n  then have \"1 \\<le> x\" using assms by (rule order_trans)\n  then show ?thesis ..\nqed\n\nlemma numeral_power_le_of_int_cancel_iff [simp]:\n  \"numeral x ^ n \\<le> of_int a \\<longleftrightarrow> numeral x ^ n \\<le> a\"\n  by (metis (mono_tags) local.of_int_eq_numeral_power_cancel_iff of_int_le_iff)\n\nlemma of_int_le_numeral_power_cancel_iff [simp]:\n  \"of_int a \\<le> numeral x ^ n \\<longleftrightarrow> a \\<le> numeral x ^ n\"\n  by (metis (mono_tags) local.numeral_power_eq_of_int_cancel_iff of_int_le_iff)\n\nlemma numeral_power_less_of_int_cancel_iff [simp]:\n  \"numeral x ^ n < of_int a \\<longleftrightarrow> numeral x ^ n < a\"\n  by (metis (mono_tags) local.of_int_eq_numeral_power_cancel_iff of_int_less_iff)\n\nlemma of_int_less_numeral_power_cancel_iff [simp]:\n  \"of_int a < numeral x ^ n \\<longleftrightarrow> a < numeral x ^ n\"\n  by (metis (mono_tags) local.of_int_eq_numeral_power_cancel_iff of_int_less_iff)\n\nlemma neg_numeral_power_le_of_int_cancel_iff [simp]:\n  \"(- numeral x) ^ n \\<le> of_int a \\<longleftrightarrow> (- numeral x) ^ n \\<le> a\"\n  by (metis (mono_tags) of_int_le_iff of_int_neg_numeral of_int_power)\n\nlemma of_int_le_neg_numeral_power_cancel_iff [simp]:\n  \"of_int a \\<le> (- numeral x) ^ n \\<longleftrightarrow> a \\<le> (- numeral x) ^ n\"\n  by (metis (mono_tags) of_int_le_iff of_int_neg_numeral of_int_power)\n\nlemma neg_numeral_power_less_of_int_cancel_iff [simp]:\n  \"(- numeral x) ^ n < of_int a \\<longleftrightarrow> (- numeral x) ^ n < a\"\n  using of_int_less_iff[of \"(- numeral x) ^ n\" a]\n  by simp\n\nlemma of_int_less_neg_numeral_power_cancel_iff [simp]:\n  \"of_int a < (- numeral x) ^ n \\<longleftrightarrow> a < (- numeral x::int) ^ n\"\n  using of_int_less_iff[of a \"(- numeral x) ^ n\"]\n  by simp\n\nlemma of_int_le_of_int_power_cancel_iff[simp]: \"(of_int b) ^ w \\<le> of_int x \\<longleftrightarrow> b ^ w \\<le> x\"\n  by (metis (mono_tags) of_int_le_iff of_int_power)\n\nlemma of_int_power_le_of_int_cancel_iff[simp]: \"of_int x \\<le> (of_int b) ^ w\\<longleftrightarrow> x \\<le> b ^ w\"\n  by (metis (mono_tags) of_int_le_iff of_int_power)\n\nlemma of_int_less_of_int_power_cancel_iff[simp]: \"(of_int b) ^ w < of_int x \\<longleftrightarrow> b ^ w < x\"\n  by (metis (mono_tags) of_int_less_iff of_int_power)\n\nlemma of_int_power_less_of_int_cancel_iff[simp]: \"of_int x < (of_int b) ^ w\\<longleftrightarrow> x < b ^ w\"\n  by (metis (mono_tags) of_int_less_iff of_int_power)\n\nlemma of_int_max: \"of_int (max x y) = max (of_int x) (of_int y)\"\n  by (auto simp: max_def)\n\nlemma of_int_min: \"of_int (min x y) = min (of_int x) (of_int y)\"\n  by (auto simp: min_def)\n\nend\n\ncontext division_ring\nbegin\n\nlemmas mult_inverse_of_int_commute =\n  mult_commute_imp_mult_inverse_commute[OF mult_of_int_commute]\n\nend\n\ntext \\<open>Comparisons involving \\<^term>\\<open>of_int\\<close>.\\<close>\n\nlemma of_int_eq_numeral_iff [iff]: \"of_int z = (numeral n :: 'a::ring_char_0) \\<longleftrightarrow> z = numeral n\"\n  using of_int_eq_iff by fastforce\n\nlemma of_int_le_numeral_iff [simp]:\n  \"of_int z \\<le> (numeral n :: 'a::linordered_idom) \\<longleftrightarrow> z \\<le> numeral n\"\n  using of_int_le_iff [of z \"numeral n\"] by simp\n\nlemma of_int_numeral_le_iff [simp]:\n  \"(numeral n :: 'a::linordered_idom) \\<le> of_int z \\<longleftrightarrow> numeral n \\<le> z\"\n  using of_int_le_iff [of \"numeral n\"] by simp\n\nlemma of_int_less_numeral_iff [simp]:\n  \"of_int z < (numeral n :: 'a::linordered_idom) \\<longleftrightarrow> z < numeral n\"\n  using of_int_less_iff [of z \"numeral n\"] by simp\n\nlemma of_int_numeral_less_iff [simp]:\n  \"(numeral n :: 'a::linordered_idom) < of_int z \\<longleftrightarrow> numeral n < z\"\n  using of_int_less_iff [of \"numeral n\" z] by simp\n\nlemma of_nat_less_of_int_iff: \"(of_nat n::'a::linordered_idom) < of_int x \\<longleftrightarrow> int n < x\"\n  by (metis of_int_of_nat_eq of_int_less_iff)\n\nlemma of_int_eq_id [simp]: \"of_int = id\"\nproof\n  show \"of_int z = id z\" for z\n    by (cases z rule: int_diff_cases) simp\nqed\n\ninstance int :: no_top\nproof\n  fix x::int\n  have \"x < x + 1\"\n    by simp\n  then show \"\\<exists>y. x < y\"\n    by (rule exI)\nqed\n\ninstance int :: no_bot\nproof\n  fix x::int\n  have \"x - 1< x\"\n    by simp\n  then show \"\\<exists>y. y < x\"\n    by (rule exI)\nqed\n\n\nsubsection \\<open>Magnitude of an Integer, as a Natural Number: \\<open>nat\\<close>\\<close>\n\nlift_definition nat :: \"int \\<Rightarrow> nat\" is \"\\<lambda>(x, y). x - y\"\n  by auto\n\nlemma nat_int [simp]: \"nat (int n) = n\"\n  by transfer simp\n\nlemma int_nat_eq [simp]: \"int (nat z) = (if 0 \\<le> z then z else 0)\"\n  by transfer clarsimp\n\nlemma nat_0_le: \"0 \\<le> z \\<Longrightarrow> int (nat z) = z\"\n  by simp\n\nlemma nat_le_0 [simp]: \"z \\<le> 0 \\<Longrightarrow> nat z = 0\"\n  by transfer clarsimp\n\nlemma nat_le_eq_zle: \"0 < w \\<or> 0 \\<le> z \\<Longrightarrow> nat w \\<le> nat z \\<longleftrightarrow> w \\<le> z\"\n  by transfer (clarsimp, arith)\n\ntext \\<open>An alternative condition is \\<^term>\\<open>0 \\<le> w\\<close>.\\<close>\nlemma nat_mono_iff: \"0 < z \\<Longrightarrow> nat w < nat z \\<longleftrightarrow> w < z\"\n  by (simp add: nat_le_eq_zle linorder_not_le [symmetric])\n\nlemma nat_less_eq_zless: \"0 \\<le> w \\<Longrightarrow> nat w < nat z \\<longleftrightarrow> w < z\"\n  by (simp add: nat_le_eq_zle linorder_not_le [symmetric])\n\nlemma zless_nat_conj [simp]: \"nat w < nat z \\<longleftrightarrow> 0 < z \\<and> w < z\"\n  by transfer (clarsimp, arith)\n\nlemma nonneg_int_cases:\n  assumes \"0 \\<le> k\"\n  obtains n where \"k = int n\"\nproof -\n  from assms have \"k = int (nat k)\"\n    by simp\n  then show thesis\n    by (rule that)\nqed\n\nlemma pos_int_cases:\n  assumes \"0 < k\"\n  obtains n where \"k = int n\" and \"n > 0\"\nproof -\n  from assms have \"0 \\<le> k\"\n    by simp\n  then obtain n where \"k = int n\"\n    by (rule nonneg_int_cases)\n  moreover have \"n > 0\"\n    using \\<open>k = int n\\<close> assms by simp\n  ultimately show thesis\n    by (rule that)\nqed\n\nlemma nonpos_int_cases:\n  assumes \"k \\<le> 0\"\n  obtains n where \"k = - int n\"\nproof -\n  from assms have \"- k \\<ge> 0\"\n    by simp\n  then obtain n where \"- k = int n\"\n    by (rule nonneg_int_cases)\n  then have \"k = - int n\"\n    by simp\n  then show thesis\n    by (rule that)\nqed\n\nlemma neg_int_cases:\n  assumes \"k < 0\"\n  obtains n where \"k = - int n\" and \"n > 0\"\nproof -\n  from assms have \"- k > 0\"\n    by simp\n  then obtain n where \"- k = int n\" and \"- k > 0\"\n    by (blast elim: pos_int_cases)\n  then have \"k = - int n\" and \"n > 0\"\n    by simp_all\n  then show thesis\n    by (rule that)\nqed\n\nlemma nat_eq_iff: \"nat w = m \\<longleftrightarrow> (if 0 \\<le> w then w = int m else m = 0)\"\n  by transfer (clarsimp simp add: le_imp_diff_is_add)\n\nlemma nat_eq_iff2: \"m = nat w \\<longleftrightarrow> (if 0 \\<le> w then w = int m else m = 0)\"\n  using nat_eq_iff [of w m] by auto\n\nlemma nat_0 [simp]: \"nat 0 = 0\"\n  by (simp add: nat_eq_iff)\n\nlemma nat_1 [simp]: \"nat 1 = Suc 0\"\n  by (simp add: nat_eq_iff)\n\nlemma nat_numeral [simp]: \"nat (numeral k) = numeral k\"\n  by (simp add: nat_eq_iff)\n\nlemma nat_neg_numeral [simp]: \"nat (- numeral k) = 0\"\n  by simp\n\nlemma nat_2: \"nat 2 = Suc (Suc 0)\"\n  by simp\n\nlemma nat_less_iff: \"0 \\<le> w \\<Longrightarrow> nat w < m \\<longleftrightarrow> w < of_nat m\"\n  by transfer (clarsimp, arith)\n\nlemma nat_le_iff: \"nat x \\<le> n \\<longleftrightarrow> x \\<le> int n\"\n  by transfer (clarsimp simp add: le_diff_conv)\n\nlemma nat_mono: \"x \\<le> y \\<Longrightarrow> nat x \\<le> nat y\"\n  by transfer auto\n\nlemma nat_0_iff[simp]: \"nat i = 0 \\<longleftrightarrow> i \\<le> 0\"\n  for i :: int\n  by transfer clarsimp\n\nlemma int_eq_iff: \"of_nat m = z \\<longleftrightarrow> m = nat z \\<and> 0 \\<le> z\"\n  by (auto simp add: nat_eq_iff2)\n\nlemma zero_less_nat_eq [simp]: \"0 < nat z \\<longleftrightarrow> 0 < z\"\n  using zless_nat_conj [of 0] by auto\n\nlemma nat_add_distrib: \"0 \\<le> z \\<Longrightarrow> 0 \\<le> z' \\<Longrightarrow> nat (z + z') = nat z + nat z'\"\n  by transfer clarsimp\n\nlemma nat_diff_distrib': \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> nat (x - y) = nat x - nat y\"\n  by transfer clarsimp\n\nlemma nat_diff_distrib: \"0 \\<le> z' \\<Longrightarrow> z' \\<le> z \\<Longrightarrow> nat (z - z') = nat z - nat z'\"\n  by (rule nat_diff_distrib') auto\n\nlemma nat_zminus_int [simp]: \"nat (- int n) = 0\"\n  by transfer simp\n\nlemma le_nat_iff: \"k \\<ge> 0 \\<Longrightarrow> n \\<le> nat k \\<longleftrightarrow> int n \\<le> k\"\n  by transfer auto\n\nlemma zless_nat_eq_int_zless: \"m < nat z \\<longleftrightarrow> int m < z\"\n  by transfer (clarsimp simp add: less_diff_conv)\n\nlemma (in ring_1) of_nat_nat [simp]: \"0 \\<le> z \\<Longrightarrow> of_nat (nat z) = of_int z\"\n  by transfer (clarsimp simp add: of_nat_diff)\n\nlemma diff_nat_numeral [simp]: \"(numeral v :: nat) - numeral v' = nat (numeral v - numeral v')\"\n  by (simp only: nat_diff_distrib' zero_le_numeral nat_numeral)\n\nlemma nat_abs_triangle_ineq:\n  \"nat \\<bar>k + l\\<bar> \\<le> nat \\<bar>k\\<bar> + nat \\<bar>l\\<bar>\"\n  by (simp add: nat_add_distrib [symmetric] nat_le_eq_zle abs_triangle_ineq)\n\nlemma nat_of_bool [simp]:\n  \"nat (of_bool P) = of_bool P\"\n  by auto\n\nlemma split_nat [linarith_split]: \"P (nat i) \\<longleftrightarrow> ((\\<forall>n. i = int n \\<longrightarrow> P n) \\<and> (i < 0 \\<longrightarrow> P 0))\"\n  (is \"?P = (?L \\<and> ?R)\")\n  for i :: int\nproof (cases \"i < 0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  have \"?P = ?L\"\n  proof\n    assume ?P\n    then show ?L using False by auto\n  next\n    assume ?L\n    moreover from False have \"int (nat i) = i\"\n      by (simp add: not_less)\n    ultimately show ?P\n      by simp\n  qed\n  with False show ?thesis by simp\nqed\n\nlemma all_nat: \"(\\<forall>x. P x) \\<longleftrightarrow> (\\<forall>x\\<ge>0. P (nat x))\"\n  by (auto split: split_nat)\n\nlemma ex_nat: \"(\\<exists>x. P x) \\<longleftrightarrow> (\\<exists>x. 0 \\<le> x \\<and> P (nat x))\"\nproof\n  assume \"\\<exists>x. P x\"\n  then obtain x where \"P x\" ..\n  then have \"int x \\<ge> 0 \\<and> P (nat (int x))\" by simp\n  then show \"\\<exists>x\\<ge>0. P (nat x)\" ..\nnext\n  assume \"\\<exists>x\\<ge>0. P (nat x)\"\n  then show \"\\<exists>x. P x\" by auto\nqed\n\n\ntext \\<open>For termination proofs:\\<close>\nlemma measure_function_int[measure_function]: \"is_measure (nat \\<circ> abs)\" ..\n\n\nsubsection \\<open>Lemmas about the Function \\<^term>\\<open>of_nat\\<close> and Orderings\\<close>\n\nlemma negative_zless_0: \"- (int (Suc n)) < (0 :: int)\"\n  by (simp add: order_less_le del: of_nat_Suc)\n\nlemma negative_zless [iff]: \"- (int (Suc n)) < int m\"\n  by (rule negative_zless_0 [THEN order_less_le_trans], simp)\n\nlemma negative_zle_0: \"- int n \\<le> 0\"\n  by (simp add: minus_le_iff)\n\nlemma negative_zle [iff]: \"- int n \\<le> int m\"\n  by (rule order_trans [OF negative_zle_0 of_nat_0_le_iff])\n\nlemma not_zle_0_negative [simp]: \"\\<not> 0 \\<le> - int (Suc n)\"\n  by (subst le_minus_iff) (simp del: of_nat_Suc)\n\nlemma int_zle_neg: \"int n \\<le> - int m \\<longleftrightarrow> n = 0 \\<and> m = 0\"\n  by transfer simp\n\nlemma not_int_zless_negative [simp]: \"\\<not> int n < - int m\"\n  by (simp add: linorder_not_less)\n\nlemma negative_eq_positive [simp]: \"- int n = of_nat m \\<longleftrightarrow> n = 0 \\<and> m = 0\"\n  by (force simp add: order_eq_iff [of \"- of_nat n\"] int_zle_neg)\n\nlemma zle_iff_zadd: \"w \\<le> z \\<longleftrightarrow> (\\<exists>n. z = w + int n)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs by auto\nnext\n  assume ?lhs\n  then have \"0 \\<le> z - w\" by simp\n  then obtain n where \"z - w = int n\"\n    using zero_le_imp_eq_int [of \"z - w\"] by blast\n  then have \"z = w + int n\" by simp\n  then show ?rhs ..\nqed\n\nlemma zadd_int_left: \"int m + (int n + z) = int (m + n) + z\"\n  by simp\n\nlemma negD:\n  assumes \"x < 0\" shows \"\\<exists>n. x = - (int (Suc n))\"\nproof -\n  have \"\\<And>a b. a < b \\<Longrightarrow> \\<exists>n. Suc (a + n) = b\"\n  proof -\n    fix a b:: nat\n    assume \"a < b\"\n    then have \"Suc (a + (b - Suc a)) = b\"\n      by arith\n    then show \"\\<exists>n. Suc (a + n) = b\"\n      by (rule exI)\n  qed\n  with assms show ?thesis\n    by transfer auto\nqed\n\n\nsubsection \\<open>Cases and induction\\<close>\n\ntext \\<open>\n  Now we replace the case analysis rule by a more conventional one:\n  whether an integer is negative or not.\n\\<close>\n\ntext \\<open>This version is symmetric in the two subgoals.\\<close>\nlemma int_cases2 [case_names nonneg nonpos, cases type: int]:\n  \"(\\<And>n. z = int n \\<Longrightarrow> P) \\<Longrightarrow> (\\<And>n. z = - (int n) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (cases \"z < 0\") (auto simp add: linorder_not_less dest!: negD nat_0_le [THEN sym])\n\ntext \\<open>This is the default, with a negative case.\\<close>\nlemma int_cases [case_names nonneg neg, cases type: int]:\n  assumes pos: \"\\<And>n. z = int n \\<Longrightarrow> P\" and neg: \"\\<And>n. z = - (int (Suc n)) \\<Longrightarrow> P\"\n  shows P\nproof (cases \"z < 0\")\n  case True\n  with neg show ?thesis\n    by (blast dest!: negD)\nnext\n  case False\n  with pos show ?thesis\n    by (force simp add: linorder_not_less dest: nat_0_le [THEN sym])\nqed\n\nlemma int_cases3 [case_names zero pos neg]:\n  fixes k :: int\n  assumes \"k = 0 \\<Longrightarrow> P\" and \"\\<And>n. k = int n \\<Longrightarrow> n > 0 \\<Longrightarrow> P\"\n    and \"\\<And>n. k = - int n \\<Longrightarrow> n > 0 \\<Longrightarrow> P\"\n  shows \"P\"\nproof (cases k \"0::int\" rule: linorder_cases)\n  case equal\n  with assms(1) show P by simp\nnext\n  case greater\n  then have *: \"nat k > 0\" by simp\n  moreover from * have \"k = int (nat k)\" by auto\n  ultimately show P using assms(2) by blast\nnext\n  case less\n  then have *: \"nat (- k) > 0\" by simp\n  moreover from * have \"k = - int (nat (- k))\" by auto\n  ultimately show P using assms(3) by blast\nqed\n\nlemma int_of_nat_induct [case_names nonneg neg, induct type: int]:\n  \"(\\<And>n. P (int n)) \\<Longrightarrow> (\\<And>n. P (- (int (Suc n)))) \\<Longrightarrow> P z\"\n  by (cases z) auto\n\nlemma sgn_mult_dvd_iff [simp]:\n  \"sgn r * l dvd k \\<longleftrightarrow> l dvd k \\<and> (r = 0 \\<longrightarrow> k = 0)\" for k l r :: int\n  by (cases r rule: int_cases3) auto\n\nlemma mult_sgn_dvd_iff [simp]:\n  \"l * sgn r dvd k \\<longleftrightarrow> l dvd k \\<and> (r = 0 \\<longrightarrow> k = 0)\" for k l r :: int\n  using sgn_mult_dvd_iff [of r l k] by (simp add: ac_simps)\n\nlemma dvd_sgn_mult_iff [simp]:\n  \"l dvd sgn r * k \\<longleftrightarrow> l dvd k \\<or> r = 0\" for k l r :: int\n  by (cases r rule: int_cases3) simp_all\n\nlemma dvd_mult_sgn_iff [simp]:\n  \"l dvd k * sgn r \\<longleftrightarrow> l dvd k \\<or> r = 0\" for k l r :: int\n  using dvd_sgn_mult_iff [of l r k] by (simp add: ac_simps)\n\nlemma int_sgnE:\n  fixes k :: int\n  obtains n and l where \"k = sgn l * int n\"\nproof -\n  have \"k = sgn k * int (nat \\<bar>k\\<bar>)\"\n    by (simp add: sgn_mult_abs)\n  then show ?thesis ..\nqed\n\n\nsubsubsection \\<open>Binary comparisons\\<close>\n\ntext \\<open>Preliminaries\\<close>\n\nlemma le_imp_0_less:\n  fixes z :: int\n  assumes le: \"0 \\<le> z\"\n  shows \"0 < 1 + z\"\nproof -\n  have \"0 \\<le> z\" by fact\n  also have \"\\<dots> < z + 1\" by (rule less_add_one)\n  also have \"\\<dots> = 1 + z\" by (simp add: ac_simps)\n  finally show \"0 < 1 + z\" .\nqed\n\nlemma odd_less_0_iff: \"1 + z + z < 0 \\<longleftrightarrow> z < 0\"\n  for z :: int\nproof (cases z)\n  case (nonneg n)\n  then show ?thesis\n    by (simp add: linorder_not_less add.assoc add_increasing le_imp_0_less [THEN order_less_imp_le])\nnext\n  case (neg n)\n  then show ?thesis\n    by (simp del: of_nat_Suc of_nat_add of_nat_1\n        add: algebra_simps of_nat_1 [where 'a=int, symmetric] of_nat_add [symmetric])\nqed\n\n\nsubsubsection \\<open>Comparisons, for Ordered Rings\\<close>\n\nlemma odd_nonzero: \"1 + z + z \\<noteq> 0\"\n  for z :: int\nproof (cases z)\n  case (nonneg n)\n  have le: \"0 \\<le> z + z\"\n    by (simp add: nonneg add_increasing)\n  then show ?thesis\n    using le_imp_0_less [OF le] by (auto simp: ac_simps)\nnext\n  case (neg n)\n  show ?thesis\n  proof\n    assume eq: \"1 + z + z = 0\"\n    have \"0 < 1 + (int n + int n)\"\n      by (simp add: le_imp_0_less add_increasing)\n    also have \"\\<dots> = - (1 + z + z)\"\n      by (simp add: neg add.assoc [symmetric])\n    also have \"\\<dots> = 0\" by (simp add: eq)\n    finally have \"0<0\" ..\n    then show False by blast\n  qed\nqed\n\n\nsubsection \\<open>The Set of Integers\\<close>\n\ncontext ring_1\nbegin\n\ndefinition Ints :: \"'a set\"  (\"\\<int>\")\n  where \"\\<int> = range of_int\"\n\nlemma Ints_of_int [simp]: \"of_int z \\<in> \\<int>\"\n  by (simp add: Ints_def)\n\nlemma Ints_of_nat [simp]: \"of_nat n \\<in> \\<int>\"\n  using Ints_of_int [of \"of_nat n\"] by simp\n\nlemma Ints_0 [simp]: \"0 \\<in> \\<int>\"\n  using Ints_of_int [of \"0\"] by simp\n\nlemma Ints_1 [simp]: \"1 \\<in> \\<int>\"\n  using Ints_of_int [of \"1\"] by simp\n\nlemma Ints_numeral [simp]: \"numeral n \\<in> \\<int>\"\n  by (subst of_nat_numeral [symmetric], rule Ints_of_nat)\n\nlemma Ints_add [simp]: \"a \\<in> \\<int> \\<Longrightarrow> b \\<in> \\<int> \\<Longrightarrow> a + b \\<in> \\<int>\"\n  by (force simp add: Ints_def simp flip: of_int_add intro: range_eqI)\n\nlemma Ints_minus [simp]: \"a \\<in> \\<int> \\<Longrightarrow> -a \\<in> \\<int>\"\n  by (force simp add: Ints_def simp flip: of_int_minus intro: range_eqI)\n\nlemma minus_in_Ints_iff: \"-x \\<in> \\<int> \\<longleftrightarrow> x \\<in> \\<int>\"\n  using Ints_minus[of x] Ints_minus[of \"-x\"] by auto\n\nlemma Ints_diff [simp]: \"a \\<in> \\<int> \\<Longrightarrow> b \\<in> \\<int> \\<Longrightarrow> a - b \\<in> \\<int>\"\n  by (force simp add: Ints_def simp flip: of_int_diff intro: range_eqI)\n\nlemma Ints_mult [simp]: \"a \\<in> \\<int> \\<Longrightarrow> b \\<in> \\<int> \\<Longrightarrow> a * b \\<in> \\<int>\"\n  by (force simp add: Ints_def simp flip: of_int_mult intro: range_eqI)\n\nlemma Ints_power [simp]: \"a \\<in> \\<int> \\<Longrightarrow> a ^ n \\<in> \\<int>\"\n  by (induct n) simp_all\n\nlemma Ints_cases [cases set: Ints]:\n  assumes \"q \\<in> \\<int>\"\n  obtains (of_int) z where \"q = of_int z\"\n  unfolding Ints_def\nproof -\n  from \\<open>q \\<in> \\<int>\\<close> have \"q \\<in> range of_int\" unfolding Ints_def .\n  then obtain z where \"q = of_int z\" ..\n  then show thesis ..\nqed\n\nlemma Ints_induct [case_names of_int, induct set: Ints]:\n  \"q \\<in> \\<int> \\<Longrightarrow> (\\<And>z. P (of_int z)) \\<Longrightarrow> P q\"\n  by (rule Ints_cases) auto\n\nlemma Nats_subset_Ints: \"\\<nat> \\<subseteq> \\<int>\"\n  unfolding Nats_def Ints_def\n  by (rule subsetI, elim imageE, hypsubst, subst of_int_of_nat_eq[symmetric], rule imageI) simp_all\n\nlemma Nats_altdef1: \"\\<nat> = {of_int n |n. n \\<ge> 0}\"\nproof (intro subsetI equalityI)\n  fix x :: 'a\n  assume \"x \\<in> {of_int n |n. n \\<ge> 0}\"\n  then obtain n where \"x = of_int n\" \"n \\<ge> 0\"\n    by (auto elim!: Ints_cases)\n  then have \"x = of_nat (nat n)\"\n    by (subst of_nat_nat) simp_all\n  then show \"x \\<in> \\<nat>\"\n    by simp\nnext\n  fix x :: 'a\n  assume \"x \\<in> \\<nat>\"\n  then obtain n where \"x = of_nat n\"\n    by (auto elim!: Nats_cases)\n  then have \"x = of_int (int n)\" by simp\n  also have \"int n \\<ge> 0\" by simp\n  then have \"of_int (int n) \\<in> {of_int n |n. n \\<ge> 0}\" by blast\n  finally show \"x \\<in> {of_int n |n. n \\<ge> 0}\" .\nqed\n\nend\n\nlemma Ints_sum [intro]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> \\<int>) \\<Longrightarrow> sum f A \\<in> \\<int>\"\n  by (induction A rule: infinite_finite_induct) auto\n\nlemma Ints_prod [intro]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> \\<int>) \\<Longrightarrow> prod f A \\<in> \\<int>\"\n  by (induction A rule: infinite_finite_induct) auto\n\nlemma (in linordered_idom) Ints_abs [simp]:\n  shows \"a \\<in> \\<int> \\<Longrightarrow> abs a \\<in> \\<int>\"\n  by (auto simp: abs_if)\n\nlemma (in linordered_idom) Nats_altdef2: \"\\<nat> = {n \\<in> \\<int>. n \\<ge> 0}\"\nproof (intro subsetI equalityI)\n  fix x :: 'a\n  assume \"x \\<in> {n \\<in> \\<int>. n \\<ge> 0}\"\n  then obtain n where \"x = of_int n\" \"n \\<ge> 0\"\n    by (auto elim!: Ints_cases)\n  then have \"x = of_nat (nat n)\"\n    by (subst of_nat_nat) simp_all\n  then show \"x \\<in> \\<nat>\"\n    by simp\nqed (auto elim!: Nats_cases)\n\nlemma (in idom_divide) of_int_divide_in_Ints: \n  \"of_int a div of_int b \\<in> \\<int>\" if \"b dvd a\"\nproof -\n  from that obtain c where \"a = b * c\" ..\n  then show ?thesis\n    by (cases \"of_int b = 0\") simp_all\nqed\n\ntext \\<open>The premise involving \\<^term>\\<open>Ints\\<close> prevents \\<^term>\\<open>a = 1/2\\<close>.\\<close>\n\nlemma Ints_double_eq_0_iff:\n  fixes a :: \"'a::ring_char_0\"\n  assumes in_Ints: \"a \\<in> \\<int>\"\n  shows \"a + a = 0 \\<longleftrightarrow> a = 0\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  from in_Ints have \"a \\<in> range of_int\"\n    unfolding Ints_def [symmetric] .\n  then obtain z where a: \"a = of_int z\" ..\n  show ?thesis\n  proof\n    assume ?rhs\n    then show ?lhs by simp\n  next\n    assume ?lhs\n    with a have \"of_int (z + z) = (of_int 0 :: 'a)\" by simp\n    then have \"z + z = 0\" by (simp only: of_int_eq_iff)\n    then have \"z = 0\" by (simp only: double_zero)\n    with a show ?rhs by simp\n  qed\nqed\n\nlemma Ints_odd_nonzero:\n  fixes a :: \"'a::ring_char_0\"\n  assumes in_Ints: \"a \\<in> \\<int>\"\n  shows \"1 + a + a \\<noteq> 0\"\nproof -\n  from in_Ints have \"a \\<in> range of_int\"\n    unfolding Ints_def [symmetric] .\n  then obtain z where a: \"a = of_int z\" ..\n  show ?thesis\n  proof\n    assume \"1 + a + a = 0\"\n    with a have \"of_int (1 + z + z) = (of_int 0 :: 'a)\" by simp\n    then have \"1 + z + z = 0\" by (simp only: of_int_eq_iff)\n    with odd_nonzero show False by blast\n  qed\nqed\n\nlemma Nats_numeral [simp]: \"numeral w \\<in> \\<nat>\"\n  using of_nat_in_Nats [of \"numeral w\"] by simp\n\nlemma Ints_odd_less_0:\n  fixes a :: \"'a::linordered_idom\"\n  assumes in_Ints: \"a \\<in> \\<int>\"\n  shows \"1 + a + a < 0 \\<longleftrightarrow> a < 0\"\nproof -\n  from in_Ints have \"a \\<in> range of_int\"\n    unfolding Ints_def [symmetric] .\n  then obtain z where a: \"a = of_int z\" ..\n  with a have \"1 + a + a < 0 \\<longleftrightarrow> of_int (1 + z + z) < (of_int 0 :: 'a)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> z < 0\"\n    by (simp only: of_int_less_iff odd_less_0_iff)\n  also have \"\\<dots> \\<longleftrightarrow> a < 0\"\n    by (simp add: a)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>\\<^term>\\<open>sum\\<close> and \\<^term>\\<open>prod\\<close>\\<close>\n\ncontext semiring_1\nbegin\n\nlemma of_nat_sum [simp]:\n  \"of_nat (sum f A) = (\\<Sum>x\\<in>A. of_nat (f x))\"\n  by (induction A rule: infinite_finite_induct) auto\n\nend\n\ncontext ring_1\nbegin\n\nlemma of_int_sum [simp]:\n  \"of_int (sum f A) = (\\<Sum>x\\<in>A. of_int (f x))\"\n  by (induction A rule: infinite_finite_induct) auto\n\nend\n\ncontext comm_semiring_1\nbegin\n\nlemma of_nat_prod [simp]:\n  \"of_nat (prod f A) = (\\<Prod>x\\<in>A. of_nat (f x))\"\n  by (induction A rule: infinite_finite_induct) auto\n\nend\n\ncontext comm_ring_1\nbegin\n\nlemma of_int_prod [simp]:\n  \"of_int (prod f A) = (\\<Prod>x\\<in>A. of_int (f x))\"\n  by (induction A rule: infinite_finite_induct) auto\n\nend\n\n\nsubsection \\<open>Setting up simplification procedures\\<close>\n\nML_file \\<open>Tools/int_arith.ML\\<close>\n\ndeclaration \\<open>K (\n  Lin_Arith.add_discrete_type \\<^type_name>\\<open>Int.int\\<close>\n  #> Lin_Arith.add_lessD @{thm zless_imp_add1_zle}\n  #> Lin_Arith.add_inj_thms @{thms of_nat_le_iff [THEN iffD2] of_nat_eq_iff [THEN iffD2]}\n  #> Lin_Arith.add_inj_const (\\<^const_name>\\<open>of_nat\\<close>, \\<^typ>\\<open>nat \\<Rightarrow> int\\<close>)\n  #> Lin_Arith.add_simps\n      @{thms of_int_0 of_int_1 of_int_add of_int_mult of_int_numeral of_int_neg_numeral nat_0 nat_1 diff_nat_numeral nat_numeral\n      neg_less_iff_less\n      True_implies_equals\n      distrib_left [where a = \"numeral v\" for v]\n      distrib_left [where a = \"- numeral v\" for v]\n      div_by_1 div_0\n      times_divide_eq_right times_divide_eq_left\n      minus_divide_left [THEN sym] minus_divide_right [THEN sym]\n      add_divide_distrib diff_divide_distrib\n      of_int_minus of_int_diff\n      of_int_of_nat_eq}\n  #> Lin_Arith.add_simprocs [Int_Arith.zero_one_idom_simproc]\n)\\<close>\n\nsimproc_setup fast_arith\n  (\"(m::'a::linordered_idom) < n\" |\n    \"(m::'a::linordered_idom) \\<le> n\" |\n    \"(m::'a::linordered_idom) = n\") =\n  \\<open>K Lin_Arith.simproc\\<close>\n\n\nsubsection\\<open>More Inequality Reasoning\\<close>\n\nlemma zless_add1_eq: \"w < z + 1 \\<longleftrightarrow> w < z \\<or> w = z\"\n  for w z :: int\n  by arith\n\nlemma add1_zle_eq: \"w + 1 \\<le> z \\<longleftrightarrow> w < z\"\n  for w z :: int\n  by arith\n\nlemma zle_diff1_eq [simp]: \"w \\<le> z - 1 \\<longleftrightarrow> w < z\"\n  for w z :: int\n  by arith\n\nlemma zle_add1_eq_le [simp]: \"w < z + 1 \\<longleftrightarrow> w \\<le> z\"\n  for w z :: int\n  by arith\n\nlemma int_one_le_iff_zero_less: \"1 \\<le> z \\<longleftrightarrow> 0 < z\"\n  for z :: int\n  by arith\n\nlemma Ints_nonzero_abs_ge1:\n  fixes x:: \"'a :: linordered_idom\"\n    assumes \"x \\<in> Ints\" \"x \\<noteq> 0\"\n    shows \"1 \\<le> abs x\"\nproof (rule Ints_cases [OF \\<open>x \\<in> Ints\\<close>])\n  fix z::int\n  assume \"x = of_int z\"\n  with \\<open>x \\<noteq> 0\\<close>\n  show \"1 \\<le> \\<bar>x\\<bar>\"\n    apply (auto simp: abs_if)\n    by (metis diff_0 of_int_1 of_int_le_iff of_int_minus zle_diff1_eq)\nqed\n  \nlemma Ints_nonzero_abs_less1:\n  fixes x:: \"'a :: linordered_idom\"\n  shows \"\\<lbrakk>x \\<in> Ints; abs x < 1\\<rbrakk> \\<Longrightarrow> x = 0\"\n    using Ints_nonzero_abs_ge1 [of x] by auto\n\nlemma Ints_eq_abs_less1:\n  fixes x:: \"'a :: linordered_idom\"\n  shows \"\\<lbrakk>x \\<in> Ints; y \\<in> Ints\\<rbrakk> \\<Longrightarrow> x = y \\<longleftrightarrow> abs (x-y) < 1\"\n  using eq_iff_diff_eq_0 by (fastforce intro: Ints_nonzero_abs_less1)\n \n\nsubsection \\<open>The functions \\<^term>\\<open>nat\\<close> and \\<^term>\\<open>int\\<close>\\<close>\n\ntext \\<open>Simplify the term \\<^term>\\<open>w + - z\\<close>.\\<close>\n\nlemma one_less_nat_eq [simp]: \"Suc 0 < nat z \\<longleftrightarrow> 1 < z\"\n  using zless_nat_conj [of 1 z] by auto\n\nlemma int_eq_iff_numeral [simp]:\n  \"int m = numeral v \\<longleftrightarrow> m = numeral v\"\n  by (simp add: int_eq_iff)\n\nlemma nat_abs_int_diff:\n  \"nat \\<bar>int a - int b\\<bar> = (if a \\<le> b then b - a else a - b)\"\n  by auto\n\nlemma nat_int_add: \"nat (int a + int b) = a + b\"\n  by auto\n\ncontext ring_1\nbegin\n\nlemma of_int_of_nat [nitpick_simp]:\n  \"of_int k = (if k < 0 then - of_nat (nat (- k)) else of_nat (nat k))\"\nproof (cases \"k < 0\")\n  case True\n  then have \"0 \\<le> - k\" by simp\n  then have \"of_nat (nat (- k)) = of_int (- k)\" by (rule of_nat_nat)\n  with True show ?thesis by simp\nnext\n  case False\n  then show ?thesis by (simp add: not_less)\nqed\n\nend\n\nlemma transfer_rule_of_int:\n  includes lifting_syntax\n  fixes R :: \"'a::ring_1 \\<Rightarrow> 'b::ring_1 \\<Rightarrow> bool\"\n  assumes [transfer_rule]: \"R 0 0\" \"R 1 1\"\n    \"(R ===> R ===> R) (+) (+)\"\n    \"(R ===> R) uminus uminus\"\n  shows \"((=) ===> R) of_int of_int\"\nproof -\n  note assms\n  note transfer_rule_of_nat [transfer_rule]\n  have [transfer_rule]: \"((=) ===> R) of_nat of_nat\"\n    by transfer_prover\n  show ?thesis\n    by (unfold of_int_of_nat [abs_def]) transfer_prover\nqed\n\nlemma nat_mult_distrib:\n  fixes z z' :: int\n  assumes \"0 \\<le> z\"\n  shows \"nat (z * z') = nat z * nat z'\"\nproof (cases \"0 \\<le> z'\")\n  case False\n  with assms have \"z * z' \\<le> 0\"\n    by (simp add: not_le mult_le_0_iff)\n  then have \"nat (z * z') = 0\" by simp\n  moreover from False have \"nat z' = 0\" by simp\n  ultimately show ?thesis by simp\nnext\n  case True\n  with assms have ge_0: \"z * z' \\<ge> 0\" by (simp add: zero_le_mult_iff)\n  show ?thesis\n    by (rule injD [of \"of_nat :: nat \\<Rightarrow> int\", OF inj_of_nat])\n      (simp only: of_nat_mult of_nat_nat [OF True]\n         of_nat_nat [OF assms] of_nat_nat [OF ge_0], simp)\nqed\n\nlemma nat_mult_distrib_neg:\n  assumes \"z \\<le> (0::int)\" shows \"nat (z * z') = nat (- z) * nat (- z')\" (is \"?L = ?R\")\nproof -\n  have \"?L = nat (- z * - z')\"\n    using assms by auto\n  also have \"... = ?R\"\n    by (rule nat_mult_distrib) (use assms in auto)\n  finally show ?thesis .\nqed\n\nlemma nat_abs_mult_distrib: \"nat \\<bar>w * z\\<bar> = nat \\<bar>w\\<bar> * nat \\<bar>z\\<bar>\"\n  by (cases \"z = 0 \\<or> w = 0\")\n    (auto simp add: abs_if nat_mult_distrib [symmetric]\n      nat_mult_distrib_neg [symmetric] mult_less_0_iff)\n\nlemma int_in_range_abs [simp]: \"int n \\<in> range abs\"\nproof (rule range_eqI)\n  show \"int n = \\<bar>int n\\<bar>\" by simp\nqed\n\nlemma range_abs_Nats [simp]: \"range abs = (\\<nat> :: int set)\"\nproof -\n  have \"\\<bar>k\\<bar> \\<in> \\<nat>\" for k :: int\n    by (cases k) simp_all\n  moreover have \"k \\<in> range abs\" if \"k \\<in> \\<nat>\" for k :: int\n    using that by induct simp\n  ultimately show ?thesis by blast\nqed\n\nlemma Suc_nat_eq_nat_zadd1: \"0 \\<le> z \\<Longrightarrow> Suc (nat z) = nat (1 + z)\"\n  for z :: int\n  by (rule sym) (simp add: nat_eq_iff)\n\nlemma diff_nat_eq_if:\n  \"nat z - nat z' =\n    (if z' < 0 then nat z\n     else\n      let d = z - z'\n      in if d < 0 then 0 else nat d)\"\n  by (simp add: Let_def nat_diff_distrib [symmetric])\n\nlemma nat_numeral_diff_1 [simp]: \"numeral v - (1::nat) = nat (numeral v - 1)\"\n  using diff_nat_numeral [of v Num.One] by simp\n\n\nsubsection \\<open>Induction principles for int\\<close>\n\ntext \\<open>Well-founded segments of the integers.\\<close>\n\ndefinition int_ge_less_than :: \"int \\<Rightarrow> (int \\<times> int) set\"\n  where \"int_ge_less_than d = {(z', z). d \\<le> z' \\<and> z' < z}\"\n\nlemma wf_int_ge_less_than: \"wf (int_ge_less_than d)\"\nproof -\n  have \"int_ge_less_than d \\<subseteq> measure (\\<lambda>z. nat (z - d))\"\n    by (auto simp add: int_ge_less_than_def)\n  then show ?thesis\n    by (rule wf_subset [OF wf_measure])\nqed\n\ntext \\<open>\n  This variant looks odd, but is typical of the relations suggested\n  by RankFinder.\\<close>\n\ndefinition int_ge_less_than2 :: \"int \\<Rightarrow> (int \\<times> int) set\"\n  where \"int_ge_less_than2 d = {(z',z). d \\<le> z \\<and> z' < z}\"\n\nlemma wf_int_ge_less_than2: \"wf (int_ge_less_than2 d)\"\nproof -\n  have \"int_ge_less_than2 d \\<subseteq> measure (\\<lambda>z. nat (1 + z - d))\"\n    by (auto simp add: int_ge_less_than2_def)\n  then show ?thesis\n    by (rule wf_subset [OF wf_measure])\nqed\n\n(* `set:int': dummy construction *)\ntheorem int_ge_induct [case_names base step, induct set: int]:\n  fixes i :: int\n  assumes ge: \"k \\<le> i\"\n    and base: \"P k\"\n    and step: \"\\<And>i. k \\<le> i \\<Longrightarrow> P i \\<Longrightarrow> P (i + 1)\"\n  shows \"P i\"\nproof -\n  have \"\\<And>i::int. n = nat (i - k) \\<Longrightarrow> k \\<le> i \\<Longrightarrow> P i\" for n\n  proof (induct n)\n    case 0\n    then have \"i = k\" by arith\n    with base show \"P i\" by simp\n  next\n    case (Suc n)\n    then have \"n = nat ((i - 1) - k)\" by arith\n    moreover have k: \"k \\<le> i - 1\" using Suc.prems by arith\n    ultimately have \"P (i - 1)\" by (rule Suc.hyps)\n    from step [OF k this] show ?case by simp\n  qed\n  with ge show ?thesis by fast\nqed\n\n(* `set:int': dummy construction *)\ntheorem int_gr_induct [case_names base step, induct set: int]:\n  fixes i k :: int\n  assumes \"k < i\" \"P (k + 1)\" \"\\<And>i. k < i \\<Longrightarrow> P i \\<Longrightarrow> P (i + 1)\"\n  shows \"P i\"\nproof -\n  have \"k+1 \\<le> i\"\n    using assms by auto\n  then show ?thesis\n    by (induction i rule: int_ge_induct) (auto simp: assms)\nqed\n\ntheorem int_le_induct [consumes 1, case_names base step]:\n  fixes i k :: int\n  assumes le: \"i \\<le> k\"\n    and base: \"P k\"\n    and step: \"\\<And>i. i \\<le> k \\<Longrightarrow> P i \\<Longrightarrow> P (i - 1)\"\n  shows \"P i\"\nproof -\n  have \"\\<And>i::int. n = nat(k-i) \\<Longrightarrow> i \\<le> k \\<Longrightarrow> P i\" for n\n  proof (induct n)\n    case 0\n    then have \"i = k\" by arith\n    with base show \"P i\" by simp\n  next\n    case (Suc n)\n    then have \"n = nat (k - (i + 1))\" by arith\n    moreover have k: \"i + 1 \\<le> k\" using Suc.prems by arith\n    ultimately have \"P (i + 1)\" by (rule Suc.hyps)\n    from step[OF k this] show ?case by simp\n  qed\n  with le show ?thesis by fast\nqed\n\ntheorem int_less_induct [consumes 1, case_names base step]:\n  fixes i k :: int\n  assumes \"i < k\" \"P (k - 1)\" \"\\<And>i. i < k \\<Longrightarrow> P i \\<Longrightarrow> P (i - 1)\"\n  shows \"P i\"\nproof -\n  have \"i \\<le> k-1\"\n    using assms by auto\n  then show ?thesis\n    by (induction i rule: int_le_induct) (auto simp: assms)\nqed\n\ntheorem int_induct [case_names base step1 step2]:\n  fixes k :: int\n  assumes base: \"P k\"\n    and step1: \"\\<And>i. k \\<le> i \\<Longrightarrow> P i \\<Longrightarrow> P (i + 1)\"\n    and step2: \"\\<And>i. k \\<ge> i \\<Longrightarrow> P i \\<Longrightarrow> P (i - 1)\"\n  shows \"P i\"\nproof -\n  have \"i \\<le> k \\<or> i \\<ge> k\" by arith\n  then show ?thesis\n  proof\n    assume \"i \\<ge> k\"\n    then show ?thesis\n      using base by (rule int_ge_induct) (fact step1)\n  next\n    assume \"i \\<le> k\"\n    then show ?thesis\n      using base by (rule int_le_induct) (fact step2)\n  qed\nqed\n\n\nsubsection \\<open>Intermediate value theorems\\<close>\n\nlemma nat_ivt_aux: \n  \"\\<lbrakk>\\<forall>i<n. \\<bar>f (Suc i) - f i\\<bar> \\<le> 1; f 0 \\<le> k; k \\<le> f n\\<rbrakk> \\<Longrightarrow> \\<exists>i \\<le> n. f i = k\"\n  for m n :: nat and k :: int\nproof (induct n)\n  case (Suc n)\n  show ?case\n  proof (cases \"k = f (Suc n)\")\n    case False\n    with Suc have \"k \\<le> f n\"\n      by auto\n    with Suc show ?thesis\n      by (auto simp add: abs_if split: if_split_asm intro: le_SucI)\n  qed (use Suc in auto)\nqed auto\n\nlemma nat_intermed_int_val:\n  fixes m n :: nat and k :: int\n  assumes \"\\<forall>i. m \\<le> i \\<and> i < n \\<longrightarrow> \\<bar>f (Suc i) - f i\\<bar> \\<le> 1\" \"m \\<le> n\" \"f m \\<le> k\" \"k \\<le> f n\"\n  shows \"\\<exists>i. m \\<le> i \\<and> i \\<le> n \\<and> f i = k\"\nproof -\n  obtain i where \"i \\<le> n - m\" \"k = f (m + i)\"\n    using nat_ivt_aux [of \"n - m\" \"f \\<circ> plus m\" k] assms by auto\n  with assms show ?thesis\n    using exI[of _ \"m + i\"] by auto\nqed\n\nlemma nat0_intermed_int_val:\n  \"\\<exists>i\\<le>n. f i = k\"\n  if \"\\<forall>i<n. \\<bar>f (i + 1) - f i\\<bar> \\<le> 1\" \"f 0 \\<le> k\" \"k \\<le> f n\"\n  for n :: nat and k :: int\n  using nat_intermed_int_val [of 0 n f k] that by auto\n\n\nsubsection \\<open>Products and 1, by T. M. Rasmussen\\<close>\n\nlemma abs_zmult_eq_1:\n  fixes m n :: int\n  assumes mn: \"\\<bar>m * n\\<bar> = 1\"\n  shows \"\\<bar>m\\<bar> = 1\"\nproof -\n  from mn have 0: \"m \\<noteq> 0\" \"n \\<noteq> 0\" by auto\n  have \"\\<not> 2 \\<le> \\<bar>m\\<bar>\"\n  proof\n    assume \"2 \\<le> \\<bar>m\\<bar>\"\n    then have \"2 * \\<bar>n\\<bar> \\<le> \\<bar>m\\<bar> * \\<bar>n\\<bar>\" by (simp add: mult_mono 0)\n    also have \"\\<dots> = \\<bar>m * n\\<bar>\" by (simp add: abs_mult)\n    also from mn have \"\\<dots> = 1\" by simp\n    finally have \"2 * \\<bar>n\\<bar> \\<le> 1\" .\n    with 0 show \"False\" by arith\n  qed\n  with 0 show ?thesis by auto\nqed\n\nlemma pos_zmult_eq_1_iff_lemma: \"m * n = 1 \\<Longrightarrow> m = 1 \\<or> m = - 1\"\n  for m n :: int\n  using abs_zmult_eq_1 [of m n] by arith\n\nlemma pos_zmult_eq_1_iff:\n  fixes m n :: int\n  assumes \"0 < m\"\n  shows \"m * n = 1 \\<longleftrightarrow> m = 1 \\<and> n = 1\"\nproof -\n  from assms have \"m * n = 1 \\<Longrightarrow> m = 1\"\n    by (auto dest: pos_zmult_eq_1_iff_lemma)\n  then show ?thesis\n    by (auto dest: pos_zmult_eq_1_iff_lemma)\nqed\n\nlemma zmult_eq_1_iff: \"m * n = 1 \\<longleftrightarrow> (m = 1 \\<and> n = 1) \\<or> (m = - 1 \\<and> n = - 1)\" (is \"?L = ?R\")\n  for m n :: int\nproof\n  assume L: ?L show ?R\n    using pos_zmult_eq_1_iff_lemma [OF L] L by force\nqed auto\n\nlemma infinite_UNIV_int [simp]: \"\\<not> finite (UNIV::int set)\"\nproof\n  assume \"finite (UNIV::int set)\"\n  moreover have \"inj (\\<lambda>i::int. 2 * i)\"\n    by (rule injI) simp\n  ultimately have \"surj (\\<lambda>i::int. 2 * i)\"\n    by (rule finite_UNIV_inj_surj)\n  then obtain i :: int where \"1 = 2 * i\" by (rule surjE)\n  then show False by (simp add: pos_zmult_eq_1_iff)\nqed\n\n\nsubsection \\<open>The divides relation\\<close>\n\nlemma zdvd_antisym_nonneg: \"0 \\<le> m \\<Longrightarrow> 0 \\<le> n \\<Longrightarrow> m dvd n \\<Longrightarrow> n dvd m \\<Longrightarrow> m = n\"\n  for m n :: int\n  by (auto simp add: dvd_def mult.assoc zero_le_mult_iff zmult_eq_1_iff)\n\nlemma zdvd_antisym_abs:\n  fixes a b :: int\n  assumes \"a dvd b\" and \"b dvd a\"\n  shows \"\\<bar>a\\<bar> = \\<bar>b\\<bar>\"\nproof (cases \"a = 0\")\n  case True\n  with assms show ?thesis by simp\nnext\n  case False\n  from \\<open>a dvd b\\<close> obtain k where k: \"b = a * k\"\n    unfolding dvd_def by blast\n  from \\<open>b dvd a\\<close> obtain k' where k': \"a = b * k'\"\n    unfolding dvd_def by blast\n  from k k' have \"a = a * k * k'\" by simp\n  with mult_cancel_left1[where c=\"a\" and b=\"k*k'\"] have kk': \"k * k' = 1\"\n    using \\<open>a \\<noteq> 0\\<close> by (simp add: mult.assoc)\n  then have \"k = 1 \\<and> k' = 1 \\<or> k = -1 \\<and> k' = -1\"\n    by (simp add: zmult_eq_1_iff)\n  with k k' show ?thesis by auto\nqed\n\nlemma zdvd_zdiffD: \"k dvd m - n \\<Longrightarrow> k dvd n \\<Longrightarrow> k dvd m\"\n  for k m n :: int\n  using dvd_add_right_iff [of k \"- n\" m] by simp\n\nlemma zdvd_reduce: \"k dvd n + k * m \\<longleftrightarrow> k dvd n\"\n  for k m n :: int\n  using dvd_add_times_triv_right_iff [of k n m] by (simp add: ac_simps)\n\nlemma dvd_imp_le_int:\n  fixes d i :: int\n  assumes \"i \\<noteq> 0\" and \"d dvd i\"\n  shows \"\\<bar>d\\<bar> \\<le> \\<bar>i\\<bar>\"\nproof -\n  from \\<open>d dvd i\\<close> obtain k where \"i = d * k\" ..\n  with \\<open>i \\<noteq> 0\\<close> have \"k \\<noteq> 0\" by auto\n  then have \"1 \\<le> \\<bar>k\\<bar>\" and \"0 \\<le> \\<bar>d\\<bar>\" by auto\n  then have \"\\<bar>d\\<bar> * 1 \\<le> \\<bar>d\\<bar> * \\<bar>k\\<bar>\" by (rule mult_left_mono)\n  with \\<open>i = d * k\\<close> show ?thesis by (simp add: abs_mult)\nqed\n\nlemma zdvd_not_zless:\n  fixes m n :: int\n  assumes \"0 < m\" and \"m < n\"\n  shows \"\\<not> n dvd m\"\nproof\n  from assms have \"0 < n\" by auto\n  assume \"n dvd m\" then obtain k where k: \"m = n * k\" ..\n  with \\<open>0 < m\\<close> have \"0 < n * k\" by auto\n  with \\<open>0 < n\\<close> have \"0 < k\" by (simp add: zero_less_mult_iff)\n  with k \\<open>0 < n\\<close> \\<open>m < n\\<close> have \"n * k < n * 1\" by simp\n  with \\<open>0 < n\\<close> \\<open>0 < k\\<close> show False unfolding mult_less_cancel_left by auto\nqed\n\nlemma zdvd_mult_cancel:\n  fixes k m n :: int\n  assumes d: \"k * m dvd k * n\"\n    and \"k \\<noteq> 0\"\n  shows \"m dvd n\"\nproof -\n  from d obtain h where h: \"k * n = k * m * h\"\n    unfolding dvd_def by blast\n  have \"n = m * h\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    with \\<open>k \\<noteq> 0\\<close> have \"k * n \\<noteq> k * (m * h)\" by simp\n    with h show False\n      by (simp add: mult.assoc)\n  qed\n  then show ?thesis by simp\nqed\n\nlemma int_dvd_int_iff [simp]:\n  \"int m dvd int n \\<longleftrightarrow> m dvd n\"\nproof -\n  have \"m dvd n\" if \"int n = int m * k\" for k\n  proof (cases k)\n    case (nonneg q)\n    with that have \"n = m * q\"\n      by (simp del: of_nat_mult add: of_nat_mult [symmetric])\n    then show ?thesis ..\n  next\n    case (neg q)\n    with that have \"int n = int m * (- int (Suc q))\"\n      by simp\n    also have \"\\<dots> = - (int m * int (Suc q))\"\n      by (simp only: mult_minus_right)\n    also have \"\\<dots> = - int (m * Suc q)\"\n      by (simp only: of_nat_mult [symmetric])\n    finally have \"- int (m * Suc q) = int n\" ..\n    then show ?thesis\n      by (simp only: negative_eq_positive) auto\n  qed\n  then show ?thesis by (auto simp add: dvd_def)\nqed\n\nlemma dvd_nat_abs_iff [simp]:\n  \"n dvd nat \\<bar>k\\<bar> \\<longleftrightarrow> int n dvd k\"\nproof -\n  have \"n dvd nat \\<bar>k\\<bar> \\<longleftrightarrow> int n dvd int (nat \\<bar>k\\<bar>)\"\n    by (simp only: int_dvd_int_iff)\n  then show ?thesis\n    by simp\nqed\n\nlemma nat_abs_dvd_iff [simp]:\n  \"nat \\<bar>k\\<bar> dvd n \\<longleftrightarrow> k dvd int n\"\nproof -\n  have \"nat \\<bar>k\\<bar> dvd n \\<longleftrightarrow> int (nat \\<bar>k\\<bar>) dvd int n\"\n    by (simp only: int_dvd_int_iff)\n  then show ?thesis\n    by simp\nqed\n\nlemma zdvd1_eq [simp]: \"x dvd 1 \\<longleftrightarrow> \\<bar>x\\<bar> = 1\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\n  for x :: int\nproof\n  assume ?lhs\n  then have \"nat \\<bar>x\\<bar> dvd nat \\<bar>1\\<bar>\"\n    by (simp only: nat_abs_dvd_iff) simp\n  then have \"nat \\<bar>x\\<bar> = 1\"\n    by simp\n  then show ?rhs\n    by (cases \"x < 0\") simp_all\nnext\n  assume ?rhs\n  then have \"x = 1 \\<or> x = - 1\"\n    by auto\n  then show ?lhs\n    by (auto intro: dvdI)\nqed\n\nlemma zdvd_mult_cancel1:\n  fixes m :: int\n  assumes mp: \"m \\<noteq> 0\"\n  shows \"m * n dvd m \\<longleftrightarrow> \\<bar>n\\<bar> = 1\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs\n    by (cases \"n > 0\") (auto simp add: minus_equation_iff)\nnext\n  assume ?lhs\n  then have \"m * n dvd m * 1\" by simp\n  from zdvd_mult_cancel[OF this mp] show ?rhs\n    by (simp only: zdvd1_eq)\nqed\n\nlemma nat_dvd_iff: \"nat z dvd m \\<longleftrightarrow> (if 0 \\<le> z then z dvd int m else m = 0)\"\n  using nat_abs_dvd_iff [of z m] by (cases \"z \\<ge> 0\") auto\n\nlemma eq_nat_nat_iff: \"0 \\<le> z \\<Longrightarrow> 0 \\<le> z' \\<Longrightarrow> nat z = nat z' \\<longleftrightarrow> z = z'\"\n  by (auto elim: nonneg_int_cases)\n\nlemma nat_power_eq: \"0 \\<le> z \\<Longrightarrow> nat (z ^ n) = nat z ^ n\"\n  by (induct n) (simp_all add: nat_mult_distrib)\n\nlemma numeral_power_eq_nat_cancel_iff [simp]:\n  \"numeral x ^ n = nat y \\<longleftrightarrow> numeral x ^ n = y\"\n  using nat_eq_iff2 by auto\n\nlemma nat_eq_numeral_power_cancel_iff [simp]:\n  \"nat y = numeral x ^ n \\<longleftrightarrow> y = numeral x ^ n\"\n  using numeral_power_eq_nat_cancel_iff[of x n y]\n  by (metis (mono_tags))\n\nlemma numeral_power_le_nat_cancel_iff [simp]:\n  \"numeral x ^ n \\<le> nat a \\<longleftrightarrow> numeral x ^ n \\<le> a\"\n  using nat_le_eq_zle[of \"numeral x ^ n\" a]\n  by (auto simp: nat_power_eq)\n\nlemma nat_le_numeral_power_cancel_iff [simp]:\n  \"nat a \\<le> numeral x ^ n \\<longleftrightarrow> a \\<le> numeral x ^ n\"\n  by (simp add: nat_le_iff)\n\nlemma numeral_power_less_nat_cancel_iff [simp]:\n  \"numeral x ^ n < nat a \\<longleftrightarrow> numeral x ^ n < a\"\n  using nat_less_eq_zless[of \"numeral x ^ n\" a]\n  by (auto simp: nat_power_eq)\n\nlemma nat_less_numeral_power_cancel_iff [simp]:\n  \"nat a < numeral x ^ n \\<longleftrightarrow> a < numeral x ^ n\"\n  using nat_less_eq_zless[of a \"numeral x ^ n\"]\n  by (cases \"a < 0\") (auto simp: nat_power_eq less_le_trans[where y=0])\n\nlemma zdvd_imp_le: \"z \\<le> n\" if \"z dvd n\" \"0 < n\" for n z :: int\nproof (cases n)\n  case (nonneg n)\n  show ?thesis\n    by (cases z) (use nonneg dvd_imp_le that in auto)\nqed (use that in auto)\n\nlemma zdvd_period:\n  fixes a d :: int\n  assumes \"a dvd d\"\n  shows \"a dvd (x + t) \\<longleftrightarrow> a dvd ((x + c * d) + t)\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  from assms have \"a dvd (x + t) \\<longleftrightarrow> a dvd ((x + t) + c * d)\"\n    by (simp add: dvd_add_left_iff)\n  then show ?thesis\n    by (simp add: ac_simps)\nqed\n\n\nsubsection \\<open>Powers with integer exponents\\<close>\n\ntext \\<open>\n  The following allows writing powers with an integer exponent. While the type signature\n  is very generic, most theorems will assume that the underlying type is a division ring or\n  a field.\n\n  The notation `powi' is inspired by the `powr' notation for real/complex exponentiation.\n\\<close>\ndefinition power_int :: \"'a :: {inverse, power} \\<Rightarrow> int \\<Rightarrow> 'a\" (infixr \"powi\" 80) where\n  \"power_int x n = (if n \\<ge> 0 then x ^ nat n else inverse x ^ (nat (-n)))\"\n\nlemma power_int_0_right [simp]: \"power_int x 0 = 1\"\n  and power_int_1_right [simp]:\n        \"power_int (y :: 'a :: {power, inverse, monoid_mult}) 1 = y\"\n  and power_int_minus1_right [simp]:\n        \"power_int (y :: 'a :: {power, inverse, monoid_mult}) (-1) = inverse y\"\n  by (simp_all add: power_int_def)\n\nlemma power_int_of_nat [simp]: \"power_int x (int n) = x ^ n\"\n  by (simp add: power_int_def)\n\nlemma power_int_numeral [simp]: \"power_int x (numeral n) = x ^ numeral n\"\n  by (simp add: power_int_def)\n\nlemma int_cases4 [case_names nonneg neg]:\n  fixes m :: int\n  obtains n where \"m = int n\" | n where \"n > 0\" \"m = -int n\"\nproof (cases \"m \\<ge> 0\")\n  case True\n  thus ?thesis using that(1)[of \"nat m\"] by auto\nnext\n  case False\n  thus ?thesis using that(2)[of \"nat (-m)\"] by auto\nqed\n\n\ncontext\n  assumes \"SORT_CONSTRAINT('a::division_ring)\"\nbegin\n\nlemma power_int_minus: \"power_int (x::'a) (-n) = inverse (power_int x n)\"\n  by (auto simp: power_int_def power_inverse)\n\nlemma power_int_minus_divide: \"power_int (x::'a) (-n) = 1 / (power_int x n)\"\n  by (simp add: divide_inverse power_int_minus)\n\nlemma power_int_eq_0_iff [simp]: \"power_int (x::'a) n = 0 \\<longleftrightarrow> x = 0 \\<and> n \\<noteq> 0\"\n  by (auto simp: power_int_def)\n\nlemma power_int_0_left_If: \"power_int (0 :: 'a) m = (if m = 0 then 1 else 0)\"\n  by (auto simp: power_int_def)\n\nlemma power_int_0_left [simp]: \"m \\<noteq> 0 \\<Longrightarrow> power_int (0 :: 'a) m = 0\"\n  by (simp add: power_int_0_left_If)\n\nlemma power_int_1_left [simp]: \"power_int 1 n = (1 :: 'a :: division_ring)\"\n  by (auto simp: power_int_def) \n\nlemma power_diff_conv_inverse: \"x \\<noteq> 0 \\<Longrightarrow> m \\<le> n \\<Longrightarrow> (x :: 'a) ^ (n - m) = x ^ n * inverse x ^ m\"\n  by (simp add: field_simps flip: power_add)\n\nlemma power_mult_inverse_distrib: \"x ^ m * inverse (x :: 'a) = inverse x * x ^ m\"\nproof (cases \"x = 0\")\n  case [simp]: False\n  show ?thesis\n  proof (cases m)\n    case (Suc m')\n    have \"x ^ Suc m' * inverse x = x ^ m'\"\n      by (subst power_Suc2) (auto simp: mult.assoc)\n    also have \"\\<dots> = inverse x * x ^ Suc m'\"\n      by (subst power_Suc) (auto simp: mult.assoc [symmetric])\n    finally show ?thesis using Suc by simp\n  qed auto\nqed auto\n\nlemma power_mult_power_inverse_commute:\n  \"x ^ m * inverse (x :: 'a) ^ n = inverse x ^ n * x ^ m\"\nproof (induction n)\n  case (Suc n)\n  have \"x ^ m * inverse x ^ Suc n = (x ^ m * inverse x ^ n) * inverse x\"\n    by (simp only: power_Suc2 mult.assoc)\n  also have \"x ^ m * inverse x ^ n = inverse x ^ n * x ^ m\"\n    by (rule Suc)\n  also have \"\\<dots> * inverse x = (inverse x ^ n * inverse x) * x ^ m\"\n    by (simp add: mult.assoc power_mult_inverse_distrib)\n  also have \"\\<dots> = inverse x ^ (Suc n) * x ^ m\"\n    by (simp only: power_Suc2)\n  finally show ?case .\nqed auto\n\nlemma power_int_add:\n  assumes \"x \\<noteq> 0 \\<or> m + n \\<noteq> 0\"\n  shows   \"power_int (x::'a) (m + n) = power_int x m * power_int x n\"\nproof (cases \"x = 0\")\n  case True\n  thus ?thesis using assms by (auto simp: power_int_0_left_If)\nnext\n  case [simp]: False\n  show ?thesis\n  proof (cases m n rule: int_cases4[case_product int_cases4])\n    case (nonneg_nonneg a b)\n    thus ?thesis\n      by (auto simp: power_int_def nat_add_distrib power_add)\n  next\n    case (nonneg_neg a b)\n    thus ?thesis\n      by (auto simp: power_int_def nat_diff_distrib not_le power_diff_conv_inverse\n                     power_mult_power_inverse_commute)\n  next\n    case (neg_nonneg a b)\n    thus ?thesis\n      by (auto simp: power_int_def nat_diff_distrib not_le power_diff_conv_inverse\n                     power_mult_power_inverse_commute)    \n  next\n    case (neg_neg a b)\n    thus ?thesis\n      by (auto simp: power_int_def nat_add_distrib add.commute simp flip: power_add)\n  qed\nqed\n\nlemma power_int_add_1:\n  assumes \"x \\<noteq> 0 \\<or> m \\<noteq> -1\"\n  shows   \"power_int (x::'a) (m + 1) = power_int x m * x\"\n  using assms by (subst power_int_add) auto\n\nlemma power_int_add_1':\n  assumes \"x \\<noteq> 0 \\<or> m \\<noteq> -1\"\n  shows   \"power_int (x::'a) (m + 1) = x * power_int x m\"\n  using assms by (subst add.commute, subst power_int_add) auto\n\nlemma power_int_commutes: \"power_int (x :: 'a) n * x = x * power_int x n\"\n  by (cases \"x = 0\") (auto simp flip: power_int_add_1 power_int_add_1')\n\nlemma power_int_inverse [field_simps, field_split_simps, divide_simps]:\n  \"power_int (inverse (x :: 'a)) n = inverse (power_int x n)\"\n  by (auto simp: power_int_def power_inverse)\n\nlemma power_int_mult: \"power_int (x :: 'a) (m * n) = power_int (power_int x m) n\"\n  by (auto simp: power_int_def zero_le_mult_iff simp flip: power_mult power_inverse nat_mult_distrib)\n\nend\n\ncontext\n  assumes \"SORT_CONSTRAINT('a::field)\"\nbegin\n\nlemma power_int_diff:\n  assumes \"x \\<noteq> 0 \\<or> m \\<noteq> n\"\n  shows   \"power_int (x::'a) (m - n) = power_int x m / power_int x n\"\n  using power_int_add[of x m \"-n\"] assms by (auto simp: field_simps power_int_minus)\n\nlemma power_int_minus_mult: \"x \\<noteq> 0 \\<or> n \\<noteq> 0 \\<Longrightarrow> power_int (x :: 'a) (n - 1) * x = power_int x n\"\n  by (auto simp flip: power_int_add_1)  \n\nlemma power_int_mult_distrib: \"power_int (x * y :: 'a) m = power_int x m * power_int y m\"\n  by (auto simp: power_int_def power_mult_distrib)\n\nlemmas power_int_mult_distrib_numeral1 = power_int_mult_distrib [where x = \"numeral w\" for w, simp]\nlemmas power_int_mult_distrib_numeral2 = power_int_mult_distrib [where y = \"numeral w\" for w, simp]\n\nlemma power_int_divide_distrib: \"power_int (x / y :: 'a) m = power_int x m / power_int y m\"\n  using power_int_mult_distrib[of x \"inverse y\" m] unfolding power_int_inverse\n  by (simp add: field_simps)\n\nend\n\n\nlemma power_int_add_numeral [simp]:\n  \"power_int x (numeral m) * power_int x (numeral n) = power_int x (numeral (m + n))\"\n  for x :: \"'a :: division_ring\"\n  by (simp add: power_int_add [symmetric])\n\nlemma power_int_add_numeral2 [simp]:\n  \"power_int x (numeral m) * (power_int x (numeral n) * b) = power_int x (numeral (m + n)) * b\"\n  for x :: \"'a :: division_ring\"\n  by (simp add: mult.assoc [symmetric])\n\nlemma power_int_mult_numeral [simp]:\n  \"power_int (power_int x (numeral m)) (numeral n) = power_int x (numeral (m * n))\"\n  for x :: \"'a :: division_ring\"\n  by (simp only: numeral_mult power_int_mult)\n  \nlemma power_int_not_zero: \"(x :: 'a :: division_ring) \\<noteq> 0 \\<or> n = 0 \\<Longrightarrow> power_int x n \\<noteq> 0\"\n  by (subst power_int_eq_0_iff) auto\n\nlemma power_int_one_over [field_simps, field_split_simps, divide_simps]:\n  \"power_int (1 / x :: 'a :: division_ring) n = 1 / power_int x n\"\n  using power_int_inverse[of x] by (simp add: divide_inverse)\n\n\ncontext\n  assumes \"SORT_CONSTRAINT('a :: linordered_field)\"\nbegin\n\nlemma power_int_numeral_neg_numeral [simp]:\n  \"power_int (numeral m) (-numeral n) = (inverse (numeral (Num.pow m n)) :: 'a)\"\n  by (simp add: power_int_minus)\n\nlemma zero_less_power_int [simp]: \"0 < (x :: 'a) \\<Longrightarrow> 0 < power_int x n\"\n  by (auto simp: power_int_def)\n\nlemma zero_le_power_int [simp]: \"0 \\<le> (x :: 'a) \\<Longrightarrow> 0 \\<le> power_int x n\"\n  by (auto simp: power_int_def)\n\nlemma power_int_mono: \"(x :: 'a) \\<le> y \\<Longrightarrow> n \\<ge> 0 \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> power_int x n \\<le> power_int y n\"\n  by (cases n rule: int_cases4) (auto intro: power_mono)\n\nlemma one_le_power_int [simp]: \"1 \\<le> (x :: 'a) \\<Longrightarrow> n \\<ge> 0 \\<Longrightarrow> 1 \\<le> power_int x n\"\n  using power_int_mono [of 1 x n] by simp\n\nlemma power_int_le_one: \"0 \\<le> (x :: 'a) \\<Longrightarrow> n \\<ge> 0 \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> power_int x n \\<le> 1\"\n  using power_int_mono [of x 1 n] by simp\n\nlemma power_int_le_imp_le_exp:\n  assumes gt1: \"1 < (x :: 'a :: linordered_field)\"\n  assumes \"power_int x m \\<le> power_int x n\" \"n \\<ge> 0\"\n  shows   \"m \\<le> n\"\nproof (cases \"m < 0\")\n  case True\n  with \\<open>n \\<ge> 0\\<close> show ?thesis by simp\nnext\n  case False\n  with assms have \"x ^ nat m \\<le> x ^ nat n\"\n    by (simp add: power_int_def)\n  from gt1 and this show ?thesis\n    using False \\<open>n \\<ge> 0\\<close> by auto\nqed\n\nlemma power_int_le_imp_less_exp:\n  assumes gt1: \"1 < (x :: 'a :: linordered_field)\"\n  assumes \"power_int x m < power_int x n\" \"n \\<ge> 0\"\n  shows   \"m < n\"\nproof (cases \"m < 0\")\n  case True\n  with \\<open>n \\<ge> 0\\<close> show ?thesis by simp\nnext\n  case False\n  with assms have \"x ^ nat m < x ^ nat n\"\n    by (simp add: power_int_def)\n  from gt1 and this show ?thesis\n    using False \\<open>n \\<ge> 0\\<close> by auto\nqed\n\nlemma power_int_strict_mono:\n  \"(a :: 'a :: linordered_field) < b \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 < n \\<Longrightarrow> power_int a n < power_int b n\"\n  by (auto simp: power_int_def intro!: power_strict_mono)\n\nlemma power_int_mono_iff [simp]:\n  fixes a b :: \"'a :: linordered_field\"\n  shows \"\\<lbrakk>a \\<ge> 0; b \\<ge> 0; n > 0\\<rbrakk> \\<Longrightarrow> power_int a n \\<le> power_int b n \\<longleftrightarrow> a \\<le> b\"\n  by (auto simp: power_int_def intro!: power_strict_mono)\n\nlemma power_int_strict_increasing:\n  fixes a :: \"'a :: linordered_field\"\n  assumes \"n < N\" \"1 < a\"\n  shows   \"power_int a N > power_int a n\"\nproof -\n  have *: \"a ^ nat (N - n) > a ^ 0\"\n    using assms by (intro power_strict_increasing) auto\n  have \"power_int a N = power_int a n * power_int a (N - n)\"\n    using assms by (simp flip: power_int_add)\n  also have \"\\<dots> > power_int a n * 1\"\n    using assms *\n    by (intro mult_strict_left_mono zero_less_power_int) (auto simp: power_int_def)\n  finally show ?thesis by simp\nqed\n\nlemma power_int_increasing:\n  fixes a :: \"'a :: linordered_field\"\n  assumes \"n \\<le> N\" \"a \\<ge> 1\"\n  shows   \"power_int a N \\<ge> power_int a n\"\nproof -\n  have *: \"a ^ nat (N - n) \\<ge> a ^ 0\"\n    using assms by (intro power_increasing) auto\n  have \"power_int a N = power_int a n * power_int a (N - n)\"\n    using assms by (simp flip: power_int_add)\n  also have \"\\<dots> \\<ge> power_int a n * 1\"\n    using assms * by (intro mult_left_mono) (auto simp: power_int_def)\n  finally show ?thesis by simp\nqed\n\nlemma power_int_strict_decreasing:\n  fixes a :: \"'a :: linordered_field\"\n  assumes \"n < N\" \"0 < a\" \"a < 1\"\n  shows   \"power_int a N < power_int a n\"\nproof -\n  have *: \"a ^ nat (N - n) < a ^ 0\"\n    using assms by (intro power_strict_decreasing) auto\n  have \"power_int a N = power_int a n * power_int a (N - n)\"\n    using assms by (simp flip: power_int_add)\n  also have \"\\<dots> < power_int a n * 1\"\n    using assms *\n    by (intro mult_strict_left_mono zero_less_power_int) (auto simp: power_int_def)\n  finally show ?thesis by simp\nqed\n\nlemma power_int_decreasing:\n  fixes a :: \"'a :: linordered_field\"\n  assumes \"n \\<le> N\" \"0 \\<le> a\" \"a \\<le> 1\" \"a \\<noteq> 0 \\<or> N \\<noteq> 0 \\<or> n = 0\"\n  shows   \"power_int a N \\<le> power_int a n\"\nproof (cases \"a = 0\")\n  case False\n  have *: \"a ^ nat (N - n) \\<le> a ^ 0\"\n    using assms by (intro power_decreasing) auto\n  have \"power_int a N = power_int a n * power_int a (N - n)\"\n    using assms False by (simp flip: power_int_add)\n  also have \"\\<dots> \\<le> power_int a n * 1\"\n    using assms * by (intro mult_left_mono) (auto simp: power_int_def)\n  finally show ?thesis by simp\nqed (use assms in \\<open>auto simp: power_int_0_left_If\\<close>)\n\nlemma one_less_power_int: \"1 < (a :: 'a) \\<Longrightarrow> 0 < n \\<Longrightarrow> 1 < power_int a n\"\n  using power_int_strict_increasing[of 0 n a] by simp\n\nlemma power_int_abs: \"\\<bar>power_int a n :: 'a\\<bar> = power_int \\<bar>a\\<bar> n\"\n  by (auto simp: power_int_def power_abs)\n\nlemma power_int_sgn [simp]: \"sgn (power_int a n :: 'a) = power_int (sgn a) n\"\n  by (auto simp: power_int_def)\n\nlemma abs_power_int_minus [simp]: \"\\<bar>power_int (- a) n :: 'a\\<bar> = \\<bar>power_int a n\\<bar>\"\n  by (simp add: power_int_abs)\n\nlemma power_int_strict_antimono:\n  assumes \"(a :: 'a :: linordered_field) < b\" \"0 < a\" \"n < 0\"\n  shows   \"power_int a n > power_int b n\"\nproof -\n  have \"inverse (power_int a (-n)) > inverse (power_int b (-n))\"\n    using assms by (intro less_imp_inverse_less power_int_strict_mono zero_less_power_int) auto\n  thus ?thesis by (simp add: power_int_minus)\nqed\n\nlemma power_int_antimono:\n  assumes \"(a :: 'a :: linordered_field) \\<le> b\" \"0 < a\" \"n < 0\"\n  shows   \"power_int a n \\<ge> power_int b n\"\n  using power_int_strict_antimono[of a b n] assms by (cases \"a = b\") auto\n\nend\n\n\nsubsection \\<open>Finiteness of intervals\\<close>\n\nlemma finite_interval_int1 [iff]: \"finite {i :: int. a \\<le> i \\<and> i \\<le> b}\"\nproof (cases \"a \\<le> b\")\n  case True\n  then show ?thesis\n  proof (induct b rule: int_ge_induct)\n    case base\n    have \"{i. a \\<le> i \\<and> i \\<le> a} = {a}\" by auto\n    then show ?case by simp\n  next\n    case (step b)\n    then have \"{i. a \\<le> i \\<and> i \\<le> b + 1} = {i. a \\<le> i \\<and> i \\<le> b} \\<union> {b + 1}\" by auto\n    with step show ?case by simp\n  qed\nnext\n  case False\n  then show ?thesis\n    by (metis (lifting, no_types) Collect_empty_eq finite.emptyI order_trans)\nqed\n\nlemma finite_interval_int2 [iff]: \"finite {i :: int. a \\<le> i \\<and> i < b}\"\n  by (rule rev_finite_subset[OF finite_interval_int1[of \"a\" \"b\"]]) auto\n\nlemma finite_interval_int3 [iff]: \"finite {i :: int. a < i \\<and> i \\<le> b}\"\n  by (rule rev_finite_subset[OF finite_interval_int1[of \"a\" \"b\"]]) auto\n\nlemma finite_interval_int4 [iff]: \"finite {i :: int. a < i \\<and> i < b}\"\n  by (rule rev_finite_subset[OF finite_interval_int1[of \"a\" \"b\"]]) auto\n\n\nsubsection \\<open>Configuration of the code generator\\<close>\n\ntext \\<open>Constructors\\<close>\n\ndefinition Pos :: \"num \\<Rightarrow> int\"\n  where [simp, code_abbrev]: \"Pos = numeral\"\n\ndefinition Neg :: \"num \\<Rightarrow> int\"\n  where [simp, code_abbrev]: \"Neg n = - (Pos n)\"\n\ncode_datatype \"0::int\" Pos Neg\n\n\ntext \\<open>Auxiliary operations.\\<close>\n\ndefinition dup :: \"int \\<Rightarrow> int\"\n  where [simp]: \"dup k = k + k\"\n\nlemma dup_code [code]:\n  \"dup 0 = 0\"\n  \"dup (Pos n) = Pos (Num.Bit0 n)\"\n  \"dup (Neg n) = Neg (Num.Bit0 n)\"\n  by (simp_all add: numeral_Bit0)\n\ndefinition sub :: \"num \\<Rightarrow> num \\<Rightarrow> int\"\n  where [simp]: \"sub m n = numeral m - numeral n\"\n\nlemma sub_code [code]:\n  \"sub Num.One Num.One = 0\"\n  \"sub (Num.Bit0 m) Num.One = Pos (Num.BitM m)\"\n  \"sub (Num.Bit1 m) Num.One = Pos (Num.Bit0 m)\"\n  \"sub Num.One (Num.Bit0 n) = Neg (Num.BitM n)\"\n  \"sub Num.One (Num.Bit1 n) = Neg (Num.Bit0 n)\"\n  \"sub (Num.Bit0 m) (Num.Bit0 n) = dup (sub m n)\"\n  \"sub (Num.Bit1 m) (Num.Bit1 n) = dup (sub m n)\"\n  \"sub (Num.Bit1 m) (Num.Bit0 n) = dup (sub m n) + 1\"\n  \"sub (Num.Bit0 m) (Num.Bit1 n) = dup (sub m n) - 1\"\n  by (simp_all only: sub_def dup_def numeral.simps Pos_def Neg_def numeral_BitM)\n\nlemma sub_BitM_One_eq:\n  \\<open>(Num.sub (Num.BitM n) num.One) = 2 * (Num.sub n Num.One :: int)\\<close>\n  by (cases n) simp_all\n\ntext \\<open>Implementations.\\<close>\n\nlemma one_int_code [code]: \"1 = Pos Num.One\"\n  by simp\n\nlemma plus_int_code [code]:\n  \"k + 0 = k\"\n  \"0 + l = l\"\n  \"Pos m + Pos n = Pos (m + n)\"\n  \"Pos m + Neg n = sub m n\"\n  \"Neg m + Pos n = sub n m\"\n  \"Neg m + Neg n = Neg (m + n)\"\n  for k l :: int\n  by simp_all\n\nlemma uminus_int_code [code]:\n  \"uminus 0 = (0::int)\"\n  \"uminus (Pos m) = Neg m\"\n  \"uminus (Neg m) = Pos m\"\n  by simp_all\n\nlemma minus_int_code [code]:\n  \"k - 0 = k\"\n  \"0 - l = uminus l\"\n  \"Pos m - Pos n = sub m n\"\n  \"Pos m - Neg n = Pos (m + n)\"\n  \"Neg m - Pos n = Neg (m + n)\"\n  \"Neg m - Neg n = sub n m\"\n  for k l :: int\n  by simp_all\n\nlemma times_int_code [code]:\n  \"k * 0 = 0\"\n  \"0 * l = 0\"\n  \"Pos m * Pos n = Pos (m * n)\"\n  \"Pos m * Neg n = Neg (m * n)\"\n  \"Neg m * Pos n = Neg (m * n)\"\n  \"Neg m * Neg n = Pos (m * n)\"\n  for k l :: int\n  by simp_all\n\ninstantiation int :: equal\nbegin\n\ndefinition \"HOL.equal k l \\<longleftrightarrow> k = (l::int)\"\n\ninstance\n  by standard (rule equal_int_def)\n\nend\n\nlemma equal_int_code [code]:\n  \"HOL.equal 0 (0::int) \\<longleftrightarrow> True\"\n  \"HOL.equal 0 (Pos l) \\<longleftrightarrow> False\"\n  \"HOL.equal 0 (Neg l) \\<longleftrightarrow> False\"\n  \"HOL.equal (Pos k) 0 \\<longleftrightarrow> False\"\n  \"HOL.equal (Pos k) (Pos l) \\<longleftrightarrow> HOL.equal k l\"\n  \"HOL.equal (Pos k) (Neg l) \\<longleftrightarrow> False\"\n  \"HOL.equal (Neg k) 0 \\<longleftrightarrow> False\"\n  \"HOL.equal (Neg k) (Pos l) \\<longleftrightarrow> False\"\n  \"HOL.equal (Neg k) (Neg l) \\<longleftrightarrow> HOL.equal k l\"\n  by (auto simp add: equal)\n\nlemma equal_int_refl [code nbe]: \"HOL.equal k k \\<longleftrightarrow> True\"\n  for k :: int\n  by (fact equal_refl)\n\nlemma less_eq_int_code [code]:\n  \"0 \\<le> (0::int) \\<longleftrightarrow> True\"\n  \"0 \\<le> Pos l \\<longleftrightarrow> True\"\n  \"0 \\<le> Neg l \\<longleftrightarrow> False\"\n  \"Pos k \\<le> 0 \\<longleftrightarrow> False\"\n  \"Pos k \\<le> Pos l \\<longleftrightarrow> k \\<le> l\"\n  \"Pos k \\<le> Neg l \\<longleftrightarrow> False\"\n  \"Neg k \\<le> 0 \\<longleftrightarrow> True\"\n  \"Neg k \\<le> Pos l \\<longleftrightarrow> True\"\n  \"Neg k \\<le> Neg l \\<longleftrightarrow> l \\<le> k\"\n  by simp_all\n\nlemma less_int_code [code]:\n  \"0 < (0::int) \\<longleftrightarrow> False\"\n  \"0 < Pos l \\<longleftrightarrow> True\"\n  \"0 < Neg l \\<longleftrightarrow> False\"\n  \"Pos k < 0 \\<longleftrightarrow> False\"\n  \"Pos k < Pos l \\<longleftrightarrow> k < l\"\n  \"Pos k < Neg l \\<longleftrightarrow> False\"\n  \"Neg k < 0 \\<longleftrightarrow> True\"\n  \"Neg k < Pos l \\<longleftrightarrow> True\"\n  \"Neg k < Neg l \\<longleftrightarrow> l < k\"\n  by simp_all\n\nlemma nat_code [code]:\n  \"nat (Int.Neg k) = 0\"\n  \"nat 0 = 0\"\n  \"nat (Int.Pos k) = nat_of_num k\"\n  by (simp_all add: nat_of_num_numeral)\n\nlemma (in ring_1) of_int_code [code]:\n  \"of_int (Int.Neg k) = - numeral k\"\n  \"of_int 0 = 0\"\n  \"of_int (Int.Pos k) = numeral k\"\n  by simp_all\n\n\ntext \\<open>Serializer setup.\\<close>\n\ncode_identifier\n  code_module Int \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nquickcheck_params [default_type = int]\n\nhide_const (open) Pos Neg sub dup\n\n\ntext \\<open>De-register \\<open>int\\<close> as a quotient type:\\<close>\n\nlifting_update int.lifting\nlifting_forget int.lifting\n\n\nsubsection \\<open>Duplicates\\<close>\n\nlemmas int_sum = of_nat_sum [where 'a=int]\nlemmas int_prod = of_nat_prod [where 'a=int]\nlemmas zle_int = of_nat_le_iff [where 'a=int]\nlemmas int_int_eq = of_nat_eq_iff [where 'a=int]\nlemmas nonneg_eq_int = nonneg_int_cases\nlemmas double_eq_0_iff = double_zero\n\nlemmas int_distrib =\n  distrib_right [of z1 z2 w]\n  distrib_left [of w z1 z2]\n  left_diff_distrib [of z1 z2 w]\n  right_diff_distrib [of w z1 z2]\n  for z1 z2 w :: int\n\nend\n\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7996941057478747}}
{"text": "theory SumFlat\n  imports Main\nbegin\n\ntext\\<open> Define a function @{text sum}, which computes the sum of\nelements of a list of natural numbers. \\<close>\n\nprimrec  sum :: \"nat list \\<Rightarrow> nat\"\n  where\n\"sum [] = 0\" |\n\"sum (x#xs) = x + sum xs\"\n\ntext\\<open> Then, define a function @{text flatten} which flattens a list\nof lists by appending the member lists. \\<close>\n\nprimrec  flatten :: \"'a list list \\<Rightarrow> 'a list\"\n  where\n\"flatten [] = []\" |\n\"flatten (x#xs) = x @ flatten xs\"\n\ntext\\<open> Test your functions by applying them to the following example lists: \\<close>\n\nlemma \"sum [2::nat, 4, 8] = 14\"\n  by simp\n\nlemma \"flatten [[2::nat, 3], [4, 5], [7, 9]] = [2, 3, 4, 5, 7, 9]\"\n  by simp\n\ntext\\<open> Prove the following statements, or give a counterexample: \\<close>\n\nlemma \"length (flatten xs) = sum (map length xs)\"\n  apply (induction xs) by auto\n\nlemma sum_append[simp]: \"sum (xs @ ys) = sum xs + sum ys\"\n  apply (induction xs) by auto\n\nlemma flatten_append[simp]: \"flatten (xs @ ys) = flatten xs @ flatten ys\"\n  apply (induction xs) by auto\n\nlemma \"flatten (map rev (rev xs)) = rev (flatten xs)\"\n  apply (induction xs) by auto\n\nlemma \"flatten (rev (map rev xs)) = rev (flatten xs)\"\n  apply (induction xs) by auto\n\nlemma \"list_all (list_all P) xs = list_all P (flatten xs)\"\n  apply (induction xs) by auto\n\nlemma \"flatten (rev xs) = flatten xs\"\n(*\nAuto Quickcheck found a counterexample:\n  xs = [[a\\<^sub>1], [a\\<^sub>2]]\n*)\n  oops\n\nlemma \"sum (rev xs) = sum xs\"\n apply (induction xs) by auto\n\ntext\\<open> Find a (non-trivial) predicate @{text P} which satisfies \\<close>\n\nlemma \"list_all (\\<lambda>x. 1 < x) xs \\<longrightarrow> length xs \\<le> sum xs\"\n  apply (induction xs) by auto\n\n\ntext\\<open> Define, by means of primitive recursion, a function @{text\nlist_exists} which checks whether an element satisfying a given property\nis contained in the list: \\<close>\n\n\nprimrec  list_exists :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a list \\<Rightarrow> bool)\"\n  where\n\"list_exists _ [] = False\" |\n\"list_exists P (x#xs) = (P x \\<or> list_exists P xs)\"\n\n\ntext\\<open> Test your function on the following examples: \\<close>\n\nlemma \"list_exists (\\<lambda> n. n < 3) [4::nat, 3, 7] = False\"\n  by simp\n\nlemma \"list_exists (\\<lambda> n. n < 4) [4::nat, 3, 7] = True\"\n  by simp\n\n\ntext\\<open> Prove the following statements: \\<close>\n\nlemma list_exists_append: \n  \"list_exists P (xs @ ys) = (list_exists P xs \\<or> list_exists P ys)\"\n  apply (induction xs) by auto\n\nlemma \"list_exists (list_exists P) xs = list_exists P (flatten xs)\"\n  apply (induction xs) by (auto simp add: list_exists_append)\n\ntext\\<open> You could have defined @{text list_exists} only with the aid of\n@{text list_all}.  Do this now, i.e. define a function @{text\nlist_exists2} and show that it is equivalent to @{text list_exists}. \\<close>\n\ndefinition list_exists2 :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where\n\"list_exists2 P xs = (\\<not>(list_all (\\<lambda>x. \\<not>P x) xs))\"\n\nlemma list_exists_equiv:\"list_exists2 P xs = list_exists P xs\"\n  apply (induction xs) by (auto simp add: list_exists2_def)\n\n(*<*) end (*>*)\n", "meta": {"author": "tomssem", "repo": "isabelle_exercises", "sha": "000b8edcb2050d4931e3177e9a339101d777dfe7", "save_path": "github-repos/isabelle/tomssem-isabelle_exercises", "path": "github-repos/isabelle/tomssem-isabelle_exercises/isabelle_exercises-000b8edcb2050d4931e3177e9a339101d777dfe7/lists/SumFlat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7996940971899608}}
{"text": "theory Tree_Exist\nimports Main \"HOL-Library.Tree\"\nbegin\n\nsubsection \"Existence of Trees\"\n\ntext \\<open>As the height/size theorem in the weak heap definition is shown\nbased on a comparison to a complete tree of similar height,\nthis short proof shows that a complete tree of a given height always exists (constructively)\\<close>\n\nfind_theorems \"\\<exists>x. size x = _\"\n\nfun build_tree :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a tree\" where\n\"build_tree 0 a = Leaf\" |\n\"build_tree (Suc n) a = \\<langle>build_tree n a, a, build_tree n a\\<rangle>\"\n\nlemma build_height: \"height (build_tree n a) = n\"\n  by (induction n) auto\n\nlemma build_complete: \"complete (build_tree n a)\"\n  by (induction n) auto\n\nlemma Ex_complete_tree_of_height: \"\\<exists>t. height (t:: 'a tree) = n \\<and> complete t\"\nproof\n  show \"height (build_tree n undefined) = n \\<and> complete (build_tree n undefined)\" using build_complete[of n undefined] build_height[of n undefined] by simp\nqed\n\ncorollary Ex_tree_of_height: \"\\<exists>t. height (t:: 'a tree) = n\"\n  using Ex_complete_tree_of_height by auto\n\nend", "meta": {"author": "nielstron", "repo": "weak_heap_sort", "sha": "e279d4519e480c8ade531d8b8541eea2ebed35db", "save_path": "github-repos/isabelle/nielstron-weak_heap_sort", "path": "github-repos/isabelle/nielstron-weak_heap_sort/weak_heap_sort-e279d4519e480c8ade531d8b8541eea2ebed35db/Tree_Exist.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802529509909, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7996263900548705}}
{"text": "theory InduccionGeneral\nimports Main\nbegin\n\nsection {* La función mitad *}\n\ntext {* (mitad x) es la mitad del número natural x. Por ejemplo, \n     mitad (Suc (Suc (Suc (Suc 0)))) = Suc (Suc 0) \n     mitad (Suc (Suc (Suc 0)))       = Suc 0 \n*}\nfun mitad :: \"nat \\<Rightarrow> nat\" where\n  \"mitad 0             = 0\" \n| \"mitad (Suc 0)       = 0\" \n| \"mitad (Suc (Suc n)) = 1 + mitad n\"\n\nvalue \"mitad (Suc (Suc (Suc (Suc 0))))\"\nlemma \"mitad (Suc (Suc (Suc (Suc 0)))) = Suc (Suc 0)\" by simp \nvalue \"mitad (Suc (Suc (Suc 0)))\"\nlemma \"mitad (Suc (Suc (Suc 0))) = Suc 0\" by simp \n\ntext {* El esquema de inducción correspondiente a la función mitad es\n     \\<lbrakk>P 0; P (Suc 0); \\<And>n. P n \\<Longrightarrow> P (Suc (Suc n))\\<rbrakk> \\<Longrightarrow> P a\n  es decir, para demostrar que todo número a tiene la propiedad P basta\n  demostrar que:\n  · 0 tiene la propiedad P\n  · (Suc 0) tiene la propiedad P\n  · si n tiene la propiedad P, entonces (Suc (Suc n)) también la tiene.\n*}\nthm mitad.induct [no_vars]\n\ntext {* Prop.: Para todo n, 2 * mitad n \\<le> n *}\nlemma \"2 * mitad n \\<le> n\"\napply (induction n rule: mitad.induct)\napply auto\ndone\n\nsection {* La función intercala *}\n\ntext {* (intercala x ys) es la lista obtenida intercalando x entre los\n  elementos de ys. Por ejemplo, \n     intercala a [x,y,z] = [x, a, y, a, z]\" by simp\n*} \nfun intercala :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" \nwhere\n  \"intercala a []       = []\" \n| \"intercala a [x]      = [x]\" \n| \"intercala a (x#y#zs) = x # a # intercala a (y#zs)\"\n\nvalue \"intercala a [x,y,z]\"\nlemma \"intercala a [x,y,z] = [x, a, y, a, z]\" by simp\n\ntext {* El esquema de inducción correspondiente a la función intercala es\n     \\<lbrakk>\\<And>a. P a []; \n      \\<And>a x. P a [x]; \n      \\<And>a x y zs. P a (y # zs) \\<Longrightarrow> P a (x # y # zs)\\<rbrakk> \n     \\<Longrightarrow> P b xs\n  es decir, para demostrar que para todo b y xs el par (b,xs) se tiene\n  la propiedad P basta demostrar que:\n  · para todo a, el par (a,[]) tiene la propiedad P\n  · para todo a, el par (a,[x]) tiene la propiedad P\n  · para todo a, x, y, zs, si el par (a,y#zs) tiene la propiedad P\n    entonces el par (a,x#y#zs) tiene la propiedad P.\n*}\nthm intercala.induct [no_vars]\n\ntext {* Prop.: Aplicar la función f al resultado de intercalar a en xs\n  es lo mismo que intercalar (f a) en las imágenes de xs mediante f. *} \nlemma \"map f (intercala a xs) = intercala (f a) (map f xs)\"\napply (induction a xs rule: intercala.induct)\napply auto\ndone\n\nend\n", "meta": {"author": "jaalonso", "repo": "SLP", "sha": "799e829200ea0a4fbb526f47356135d98a190864", "save_path": "github-repos/isabelle/jaalonso-SLP", "path": "github-repos/isabelle/jaalonso-SLP/SLP-799e829200ea0a4fbb526f47356135d98a190864/Temas/Ejemplos/InduccionGeneral.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.7994706701108659}}
{"text": "(*  Title:      HOL/ex/Primrec.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n\nAckermann's Function and the\nPrimitive Recursive Functions.\n*)\n\nsection {* Primitive Recursive Functions *}\n\ntheory Primrec imports Main begin\n\ntext {*\n  Proof adopted from\n\n  Nora Szasz, A Machine Checked Proof that Ackermann's Function is not\n  Primitive Recursive, In: Huet \\& Plotkin, eds., Logical Environments\n  (CUP, 1993), 317-338.\n\n  See also E. Mendelson, Introduction to Mathematical Logic.  (Van\n  Nostrand, 1964), page 250, exercise 11.\n  \\medskip\n*}\n\n\nsubsection{* Ackermann's Function *}\n\nfun ack :: \"nat => nat => nat\" where\n\"ack 0 n =  Suc n\" |\n\"ack (Suc m) 0 = ack m 1\" |\n\"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\n\ntext {* PROPERTY A 4 *}\n\nlemma less_ack2 [iff]: \"j < ack i j\"\nby (induct i j rule: ack.induct) simp_all\n\n\ntext {* PROPERTY A 5-, the single-step lemma *}\n\nlemma ack_less_ack_Suc2 [iff]: \"ack i j < ack i (Suc j)\"\nby (induct i j rule: ack.induct) simp_all\n\n\ntext {* PROPERTY A 5, monotonicity for @{text \"<\"} *}\n\nlemma ack_less_mono2: \"j < k ==> ack i j < ack i k\"\nusing lift_Suc_mono_less[where f = \"ack i\"]\nby (metis ack_less_ack_Suc2)\n\n\ntext {* PROPERTY A 5', monotonicity for @{text \\<le>} *}\n\nlemma ack_le_mono2: \"j \\<le> k ==> ack i j \\<le> ack i k\"\napply (simp add: order_le_less)\napply (blast intro: ack_less_mono2)\ndone\n\n\ntext {* PROPERTY A 6 *}\n\nlemma ack2_le_ack1 [iff]: \"ack i (Suc j) \\<le> ack (Suc i) j\"\nproof (induct j)\n  case 0 show ?case by simp\nnext\n  case (Suc j) show ?case \n    by (auto intro!: ack_le_mono2)\n      (metis Suc Suc_leI Suc_lessI less_ack2 linorder_not_less)\nqed\n\n\ntext {* PROPERTY A 7-, the single-step lemma *}\n\nlemma ack_less_ack_Suc1 [iff]: \"ack i j < ack (Suc i) j\"\nby (blast intro: ack_less_mono2 less_le_trans)\n\n\ntext {* PROPERTY A 4'? Extra lemma needed for @{term CONSTANT} case, constant functions *}\n\nlemma less_ack1 [iff]: \"i < ack i j\"\napply (induct i)\n apply simp_all\napply (blast intro: Suc_leI le_less_trans)\ndone\n\n\ntext {* PROPERTY A 8 *}\n\nlemma ack_1 [simp]: \"ack (Suc 0) j = j + 2\"\nby (induct j) simp_all\n\n\ntext {* PROPERTY A 9.  The unary @{text 1} and @{text 2} in @{term\n  ack} is essential for the rewriting. *}\n\nlemma ack_2 [simp]: \"ack (Suc (Suc 0)) j = 2 * j + 3\"\nby (induct j) simp_all\n\n\ntext {* PROPERTY A 7, monotonicity for @{text \"<\"} [not clear why\n  @{thm [source] ack_1} is now needed first!] *}\n\nlemma ack_less_mono1_aux: \"ack i k < ack (Suc (i +i')) k\"\nproof (induct i k rule: ack.induct)\n  case (1 n) show ?case\n    by (simp, metis ack_less_ack_Suc1 less_ack2 less_trans_Suc) \nnext\n  case (2 m) thus ?case by simp\nnext\n  case (3 m n) thus ?case\n    by (simp, blast intro: less_trans ack_less_mono2)\nqed\n\nlemma ack_less_mono1: \"i < j ==> ack i k < ack j k\"\napply (drule less_imp_Suc_add)\napply (blast intro!: ack_less_mono1_aux)\ndone\n\n\ntext {* PROPERTY A 7', monotonicity for @{text \"\\<le>\"} *}\n\nlemma ack_le_mono1: \"i \\<le> j ==> ack i k \\<le> ack j k\"\napply (simp add: order_le_less)\napply (blast intro: ack_less_mono1)\ndone\n\n\ntext {* PROPERTY A 10 *}\n\nlemma ack_nest_bound: \"ack i1 (ack i2 j) < ack (2 + (i1 + i2)) j\"\napply (simp add: numerals)\napply (rule ack2_le_ack1 [THEN [2] less_le_trans])\napply simp\napply (rule le_add1 [THEN ack_le_mono1, THEN le_less_trans])\napply (rule ack_less_mono1 [THEN ack_less_mono2])\napply (simp add: le_imp_less_Suc le_add2)\ndone\n\n\ntext {* PROPERTY A 11 *}\n\nlemma ack_add_bound: \"ack i1 j + ack i2 j < ack (4 + (i1 + i2)) j\"\napply (rule less_trans [of _ \"ack (Suc (Suc 0)) (ack (i1 + i2) j)\"])\n prefer 2\n apply (rule ack_nest_bound [THEN less_le_trans])\n apply (simp add: Suc3_eq_add_3)\napply simp\napply (cut_tac i = i1 and m1 = i2 and k = j in le_add1 [THEN ack_le_mono1])\napply (cut_tac i = \"i2\" and m1 = i1 and k = j in le_add2 [THEN ack_le_mono1])\napply auto\ndone\n\n\ntext {* PROPERTY A 12.  Article uses existential quantifier but the ALF proof\n  used @{text \"k + 4\"}.  Quantified version must be nested @{text\n  \"\\<exists>k'. \\<forall>i j. ...\"} *}\n\nlemma ack_add_bound2: \"i < ack k j ==> i + j < ack (4 + k) j\"\napply (rule less_trans [of _ \"ack k j + ack 0 j\"])\n apply (blast intro: add_less_mono) \napply (rule ack_add_bound [THEN less_le_trans])\napply simp\ndone\n\n\nsubsection{*Primitive Recursive Functions*}\n\nprimrec hd0 :: \"nat list => nat\" where\n\"hd0 [] = 0\" |\n\"hd0 (m # ms) = m\"\n\n\ntext {* Inductive definition of the set of primitive recursive functions of type @{typ \"nat list => nat\"}. *}\n\ndefinition SC :: \"nat list => nat\" where\n\"SC l = Suc (hd0 l)\"\n\ndefinition CONSTANT :: \"nat => nat list => nat\" where\n\"CONSTANT k l = k\"\n\ndefinition PROJ :: \"nat => nat list => nat\" where\n\"PROJ i l = hd0 (drop i l)\"\n\ndefinition\nCOMP :: \"(nat list => nat) => (nat list => nat) list => nat list => nat\"\nwhere \"COMP g fs l = g (map (\\<lambda>f. f l) fs)\"\n\ndefinition PREC :: \"(nat list => nat) => (nat list => nat) => nat list => nat\"\nwhere\n  \"PREC f g l =\n    (case l of\n      [] => 0\n    | x # l' => rec_nat (f l') (\\<lambda>y r. g (r # y # l')) x)\"\n  -- {* Note that @{term g} is applied first to @{term \"PREC f g y\"} and then to @{term y}! *}\n\ninductive PRIMREC :: \"(nat list => nat) => bool\" where\nSC: \"PRIMREC SC\" |\nCONSTANT: \"PRIMREC (CONSTANT k)\" |\nPROJ: \"PRIMREC (PROJ i)\" |\nCOMP: \"PRIMREC g ==> \\<forall>f \\<in> set fs. PRIMREC f ==> PRIMREC (COMP g fs)\" |\nPREC: \"PRIMREC f ==> PRIMREC g ==> PRIMREC (PREC f g)\"\n\n\ntext {* Useful special cases of evaluation *}\n\nlemma SC [simp]: \"SC (x # l) = Suc x\"\nby (simp add: SC_def)\n\nlemma CONSTANT [simp]: \"CONSTANT k l = k\"\nby (simp add: CONSTANT_def)\n\nlemma PROJ_0 [simp]: \"PROJ 0 (x # l) = x\"\nby (simp add: PROJ_def)\n\nlemma COMP_1 [simp]: \"COMP g [f] l = g [f l]\"\nby (simp add: COMP_def)\n\nlemma PREC_0 [simp]: \"PREC f g (0 # l) = f l\"\nby (simp add: PREC_def)\n\nlemma PREC_Suc [simp]: \"PREC f g (Suc x # l) = g (PREC f g (x # l) # x # l)\"\nby (simp add: PREC_def)\n\n\ntext {* MAIN RESULT *}\n\nlemma SC_case: \"SC l < ack 1 (listsum l)\"\napply (unfold SC_def)\napply (induct l)\napply (simp_all add: le_add1 le_imp_less_Suc)\ndone\n\nlemma CONSTANT_case: \"CONSTANT k l < ack k (listsum l)\"\nby simp\n\nlemma PROJ_case: \"PROJ i l < ack 0 (listsum l)\"\napply (simp add: PROJ_def)\napply (induct l arbitrary:i)\n apply (auto simp add: drop_Cons split: nat.split)\napply (blast intro: less_le_trans le_add2)\ndone\n\n\ntext {* @{term COMP} case *}\n\nlemma COMP_map_aux: \"\\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (listsum l))\n  ==> \\<exists>k. \\<forall>l. listsum (map (\\<lambda>f. f l) fs) < ack k (listsum l)\"\napply (induct fs)\n apply (rule_tac x = 0 in exI)\n apply simp\napply simp\napply (blast intro: add_less_mono ack_add_bound less_trans)\ndone\n\nlemma COMP_case:\n  \"\\<forall>l. g l < ack kg (listsum l) ==>\n  \\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (listsum l))\n  ==> \\<exists>k. \\<forall>l. COMP g fs  l < ack k (listsum l)\"\napply (unfold COMP_def)\napply (drule COMP_map_aux)\napply (meson ack_less_mono2 ack_nest_bound less_trans)\ndone\n\n\ntext {* @{term PREC} case *}\n\nlemma PREC_case_aux:\n  \"\\<forall>l. f l + listsum l < ack kf (listsum l) ==>\n    \\<forall>l. g l + listsum l < ack kg (listsum l) ==>\n    PREC f g l + listsum l < ack (Suc (kf + kg)) (listsum l)\"\napply (unfold PREC_def)\napply (case_tac l)\n apply simp_all\n apply (blast intro: less_trans)\napply (erule ssubst) -- {* get rid of the needless assumption *}\napply (induct_tac a)\n apply simp_all\n txt {* base case *}\n apply (blast intro: le_add1 [THEN le_imp_less_Suc, THEN ack_less_mono1] less_trans)\ntxt {* induction step *}\napply (rule Suc_leI [THEN le_less_trans])\n apply (rule le_refl [THEN add_le_mono, THEN le_less_trans])\n  prefer 2\n  apply (erule spec)\n apply (simp add: le_add2)\ntxt {* final part of the simplification *}\napply simp\napply (rule le_add2 [THEN ack_le_mono1, THEN le_less_trans])\napply (erule ack_less_mono2)\ndone\n\nlemma PREC_case:\n  \"\\<forall>l. f l < ack kf (listsum l) ==>\n    \\<forall>l. g l < ack kg (listsum l) ==>\n    \\<exists>k. \\<forall>l. PREC f g l < ack k (listsum l)\"\nby (metis le_less_trans [OF le_add1 PREC_case_aux] ack_add_bound2)\n\nlemma ack_bounds_PRIMREC: \"PRIMREC f ==> \\<exists>k. \\<forall>l. f l < ack k (listsum l)\"\napply (erule PRIMREC.induct)\n    apply (blast intro: SC_case CONSTANT_case PROJ_case COMP_case PREC_case)+\ndone\n\ntheorem ack_not_PRIMREC:\n  \"\\<not> PRIMREC (\\<lambda>l. case l of [] => 0 | x # l' => ack x x)\"\napply (rule notI)\napply (erule ack_bounds_PRIMREC [THEN exE])\napply (rule less_irrefl [THEN notE])\napply (drule_tac x = \"[x]\" in spec)\napply simp\ndone\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/ex/Primrec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8918110511888303, "lm_q1q2_score": 0.7992868742610163}}
{"text": "(*  \n  Title:    Random_Permutations.thy\n  Author:   Manuel Eberl, TU München\n\n  Random permutations and folding over them.\n  This provides the basic theory for the concept of doing something\n  in a random order, e.g. inserting elements from a fixed set into a \n  data structure in random order.\n*)\n\nsection \\<open>Random Permutations\\<close>\n\ntheory Random_Permutations\nimports \n  \"HOL-Combinatorics.Multiset_Permutations\"\n  Probability_Mass_Function\nbegin\n\ntext \\<open>\n  Choosing a set permutation (i.e. a distinct list with the same elements as the set)\n  uniformly at random is the same as first choosing the first element of the list\n  and then choosing the rest of the list as a permutation of the remaining set.\n\\<close>\nlemma random_permutation_of_set:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   \"pmf_of_set (permutations_of_set A) = \n             do {\n               x \\<leftarrow> pmf_of_set A;\n               xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x})); \n               return_pmf (x#xs)\n             }\" (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"permutations_of_set A = (\\<Union>x\\<in>A. (#) x ` permutations_of_set (A - {x}))\"\n    by (simp add: permutations_of_set_nonempty)\n  also from assms have \"pmf_of_set \\<dots> = ?rhs\"\n    by (subst pmf_of_set_UN[where n = \"fact (card A - 1)\"])\n       (auto simp: card_image disjoint_family_on_def map_pmf_def [symmetric] map_pmf_of_set_inj)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  A generic fold function that takes a function, an initial state, and a set \n  and chooses a random order in which it then traverses the set in the same \n  fashion as a left fold over a list.\n    We first give a recursive definition.\n\\<close>\nfunction fold_random_permutation :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b pmf\" where\n  \"fold_random_permutation f x {} = return_pmf x\"\n| \"\\<not>finite A \\<Longrightarrow> fold_random_permutation f x A = return_pmf x\"\n| \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \n     fold_random_permutation f x A = \n       pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}))\"\n  by simp_all fastforce\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(_,_,A). card A)\")\n  fix A :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and x :: 'b and y :: 'a\n  assume A: \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  then have \"card A > 0\" by (simp add: card_gt_0_iff)\n  with A show \"((f, f y x, A - {y}), f, x, A) \\<in> Wellfounded.measure (\\<lambda>(_, _, A). card A)\"\n    by simp\nqed simp_all\n\n\ntext \\<open>\n  We can now show that the above recursive definition is equivalent to \n  choosing a random set permutation and folding over it (in any direction).\n\\<close>\nlemma fold_random_permutation_foldl:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set A))\"\nusing assms\nproof (induction f x A rule: fold_random_permutation.induct [case_names empty infinite remove])\n  case (remove A f x)\n  from remove \n    have \"fold_random_permutation f x A = \n            pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}))\" by simp\n  also from remove\n    have \"\\<dots> = pmf_of_set A \\<bind> (\\<lambda>a. map_pmf (foldl (\\<lambda>x y. f y x) x)\n                 (map_pmf ((#) a) (pmf_of_set (permutations_of_set (A - {a})))))\"\n      by (intro bind_pmf_cong) (simp_all add: pmf.map_comp o_def)\n  also from remove have \"\\<dots> = map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set A))\"\n    by (simp_all add: random_permutation_of_set map_bind_pmf map_pmf_def [symmetric])\n  finally show ?case .\nqed (simp_all add: pmf_of_set_singleton)\n\nlemma fold_random_permutation_foldr:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (\\<lambda>xs. foldr f xs x) (pmf_of_set (permutations_of_set A))\"\nproof -\n  have \"fold_random_permutation f x A =\n          map_pmf (foldl (\\<lambda>x y. f y x) x \\<circ> rev) (pmf_of_set (permutations_of_set A))\"\n    using assms by (subst fold_random_permutation_foldl [OF assms])\n                   (simp_all add: pmf.map_comp [symmetric] map_pmf_of_set_inj)\n  also have \"foldl (\\<lambda>x y. f y x) x \\<circ> rev = (\\<lambda>xs. foldr f xs x)\"\n    by (intro ext) (simp add: foldl_conv_foldr)\n  finally show ?thesis .\nqed\n\nlemma fold_random_permutation_fold:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (\\<lambda>xs. fold f xs x) (pmf_of_set (permutations_of_set A))\"\n  by (subst fold_random_permutation_foldl [OF assms], intro map_pmf_cong)\n     (simp_all add: foldl_conv_fold)\n     \nlemma fold_random_permutation_code [code]: \n  \"fold_random_permutation f x (set xs) =\n     map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set (set xs)))\"\n  by (simp add: fold_random_permutation_foldl)\n\ntext \\<open>\n  We now introduce a slightly generalised version of the above fold \n  operation that does not simply return the result in the end, but applies\n  a monadic bind to it.\n    This may seem somewhat arbitrary, but it is a common use case, e.g. \n  in the Social Decision Scheme of Random Serial Dictatorship, where \n  voters narrow down a set of possible winners in a random order and \n  the winner is chosen from the remaining set uniformly at random.\n\\<close>\nfunction fold_bind_random_permutation \n    :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'c pmf) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'c pmf\" where\n  \"fold_bind_random_permutation f g x {} = g x\"\n| \"\\<not>finite A \\<Longrightarrow> fold_bind_random_permutation f g x A = g x\"\n| \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \n     fold_bind_random_permutation f g x A = \n       pmf_of_set A \\<bind> (\\<lambda>a. fold_bind_random_permutation f g (f a x) (A - {a}))\"\n  by simp_all fastforce\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(_,_,_,A). card A)\")\n  fix A :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and x :: 'b \n    and y :: 'a and g :: \"'b \\<Rightarrow> 'c pmf\"\n  assume A: \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  then have \"card A > 0\" by (simp add: card_gt_0_iff)\n  with A show \"((f, g, f y x, A - {y}), f, g, x, A) \\<in> Wellfounded.measure (\\<lambda>(_, _, _, A). card A)\"\n    by simp\nqed simp_all\n\ntext \\<open>\n  We now show that the recursive definition is equivalent to \n  a random fold followed by a monadic bind.\n\\<close>\nlemma fold_bind_random_permutation_altdef [code]:\n  \"fold_bind_random_permutation f g x A = fold_random_permutation f x A \\<bind> g\"\nproof (induction f x A rule: fold_random_permutation.induct [case_names empty infinite remove])\n  case (remove A f x)\n  from remove have \"pmf_of_set A \\<bind> (\\<lambda>a. fold_bind_random_permutation f g (f a x) (A - {a})) =\n                      pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}) \\<bind> g)\"\n    by (intro bind_pmf_cong) simp_all\n  with remove show ?case by (simp add: bind_return_pmf bind_assoc_pmf)\nqed (simp_all add: bind_return_pmf)\n\n\ntext \\<open>\n  We can now derive the following nice monadic representations of the \n  combined fold-and-bind:\n\\<close>\nlemma fold_bind_random_permutation_foldl:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (foldl (\\<lambda>x y. f y x) x xs)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_foldl bind_return_pmf map_pmf_def)\n\nlemma fold_bind_random_permutation_foldr:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (foldr f xs x)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_foldr bind_return_pmf map_pmf_def)\n\nlemma fold_bind_random_permutation_fold:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (fold f xs x)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_fold bind_return_pmf map_pmf_def)\n\ntext \\<open>\n  The following useful lemma allows us to swap partitioning a set w.\\,r.\\,t.\\ a \n  predicate and drawing a random permutation of that set.\n\\<close>\nlemma partition_random_permutations:\n  assumes \"finite A\"\n  shows   \"map_pmf (partition P) (pmf_of_set (permutations_of_set A)) = \n             pair_pmf (pmf_of_set (permutations_of_set {x\\<in>A. P x}))\n                      (pmf_of_set (permutations_of_set {x\\<in>A. \\<not>P x}))\" (is \"?lhs = ?rhs\")\nproof (rule pmf_eqI, clarify, goal_cases)\n  case (1 xs ys)\n  show ?case\n  proof (cases \"xs \\<in> permutations_of_set {x\\<in>A. P x} \\<and> ys \\<in> permutations_of_set {x\\<in>A. \\<not>P x}\")\n    case True\n    let ?n1 = \"card {x\\<in>A. P x}\" and ?n2 = \"card {x\\<in>A. \\<not>P x}\"\n    have card_eq: \"card A = ?n1 + ?n2\"\n    proof -\n      have \"?n1 + ?n2 = card ({x\\<in>A. P x} \\<union> {x\\<in>A. \\<not>P x})\"\n        using assms by (intro card_Un_disjoint [symmetric]) auto\n      also have \"{x\\<in>A. P x} \\<union> {x\\<in>A. \\<not>P x} = A\" by blast\n      finally show ?thesis ..\n    qed\n\n    from True have lengths [simp]: \"length xs = ?n1\" \"length ys = ?n2\"\n      by (auto intro!: length_finite_permutations_of_set)\n    have \"pmf ?lhs (xs, ys) = \n            real (card (permutations_of_set A \\<inter> partition P -` {(xs, ys)})) / fact (card A)\"\n      using assms by (auto simp: pmf_map measure_pmf_of_set)\n    also have \"partition P -` {(xs, ys)} = shuffles xs ys\" \n      using True by (intro inv_image_partition) (auto simp: permutations_of_set_def)\n    also have \"permutations_of_set A \\<inter> shuffles xs ys = shuffles xs ys\"\n      using True distinct_disjoint_shuffles[of xs ys] \n      by (auto simp: permutations_of_set_def dest: set_shuffles)\n    also have \"card (shuffles xs ys) = length xs + length ys choose length xs\"\n      using True by (intro card_disjoint_shuffles) (auto simp: permutations_of_set_def)\n    also have \"length xs + length ys = card A\" by (simp add: card_eq)\n    also have \"real (card A choose length xs) = fact (card A) / (fact ?n1 * fact (card A - ?n1))\"\n      by (subst binomial_fact) (auto intro!: card_mono assms)\n    also have \"\\<dots> / fact (card A) = 1 / (fact ?n1 * fact ?n2)\"\n      by (simp add: field_split_simps card_eq)\n    also have \"\\<dots> = pmf ?rhs (xs, ys)\" using True assms by (simp add: pmf_pair)\n    finally show ?thesis .\n  next\n    case False\n    hence *: \"xs \\<notin> permutations_of_set {x\\<in>A. P x} \\<or> ys \\<notin> permutations_of_set {x\\<in>A. \\<not>P x}\" by blast\n    hence eq: \"permutations_of_set A \\<inter> (partition P -` {(xs, ys)}) = {}\"\n      by (auto simp: o_def permutations_of_set_def)\n    from * show ?thesis\n      by (elim disjE) (insert assms eq, simp_all add: pmf_pair pmf_map measure_pmf_of_set)\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Probability/Random_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7991579522815526}}
{"text": "(*  Title:      HOL/Examples/Ackermann.thy\n    Author:     Larry Paulson\n*)\n\nsection \\<open>A Tail-Recursive, Stack-Based Ackermann's Function\\<close>\n\ntheory Ackermann imports Main\n\nbegin\n\ntext\\<open>This theory investigates a stack-based implementation of Ackermann's function.\nLet's recall the traditional definition,\nas modified by R{\\'o}zsa P\\'eter and Raphael Robinson.\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n             = Suc n\"\n| \"ack (Suc m) 0       = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\ntext\\<open>Here is the stack-based version, which uses lists.\\<close>\n\nfunction (domintros) ackloop :: \"nat list \\<Rightarrow> nat\" where\n  \"ackloop (n # 0 # l)         = ackloop (Suc n # l)\"\n| \"ackloop (0 # Suc m # l)     = ackloop (1 # m # l)\"\n| \"ackloop (Suc n # Suc m # l) = ackloop (n # Suc m # m # l)\"\n| \"ackloop [m] = m\"\n| \"ackloop [] =  0\"\n  by pat_completeness auto\n\ntext\\<open>\nThe key task is to prove termination. In the first recursive call, the head of the list gets bigger\nwhile the list gets shorter, suggesting that the length of the list should be the primary\ntermination criterion. But in the third recursive call, the list gets longer. The idea of trying\na multiset-based termination argument is frustrated by the second recursive call when m = 0:\nthe list elements are simply permuted.\n\nFortunately, the function definition package allows us to define a function and only later identify its domain of termination.\nInstead, it makes all the recursion equations conditional on satisfying\nthe function's domain predicate. Here we shall eventually be able\nto show that the predicate is always satisfied.\\<close>\n\ntext\\<open>@{thm [display] ackloop.domintros[no_vars]}\\<close>\ndeclare ackloop.domintros [simp]\n\ntext \\<open>Termination is trivial if the length of the list is less then two.\nThe following lemma is the key to proving termination for longer lists.\\<close>\nlemma \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\nproof (induction m arbitrary: n l)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (Suc m)\n  show ?case\n    using Suc.prems\n    by (induction n arbitrary: l) (simp_all add: Suc)\nqed\n\ntext \\<open>The proof above (which actually is unused) can be expressed concisely as follows.\\<close>\nlemma ackloop_dom_longer:\n  \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\ntext\\<open>This function codifies what @{term ackloop} is designed to do.\nProving the two functions equivalent also shows that @{term ackloop} can be used\nto compute Ackermann's function.\\<close>\nfun acklist :: \"nat list \\<Rightarrow> nat\" where\n  \"acklist (n#m#l) = acklist (ack m n # l)\"\n| \"acklist [m] = m\"\n| \"acklist [] =  0\"\n\ntext\\<open>The induction rule for @{term acklist} is @{thm [display] acklist.induct[no_vars]}.\\<close>\n\nlemma ackloop_dom: \"ackloop_dom l\"\n  by (induction l rule: acklist.induct) (auto simp: ackloop_dom_longer)\n\ntermination ackloop\n  by (simp add: ackloop_dom)\n\ntext\\<open>This result is trivial even by inspection of the function definitions\n(which faithfully follow the definition of Ackermann's function).\nAll that we needed was termination.\\<close>\nlemma ackloop_acklist: \"ackloop l = acklist l\"\n  by (induction l rule: ackloop.induct) auto\n\ntheorem ack: \"ack m n = ackloop [n,m]\"\n  by (simp add: ackloop_acklist)\n\nend\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Examples/Ackermann.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8887588045416601, "lm_q1q2_score": 0.7991020404002859}}
{"text": "theory Concrete_semantic\nimports Main\nbegin\n(*2.2.1 P7*)\ndatatype bool=True|False\nfun conj::\"bool\\<Rightarrow>bool\\<Rightarrow>bool\"\n  where\n\"conj True True=True\"|\n\"conj _ _=False\"\n\n(*------------------*)\n(*2.2.2 P8*)\nfun add::\"nat\\<Rightarrow>nat\\<Rightarrow>nat\"\nwhere\n\"add 0 n =n\"|\n\"add(Suc m) n=Suc(add m n)\"\nlemma add_02:\"add m 0=m\"\napply(induction m)\napply(auto)\n  done\n(*------------------*)\n\n\n(*2.2.3 P10,11*)\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n\nfun app::\"'a list\\<Rightarrow>'a list \\<Rightarrow>'a list\"\nwhere\n\"app Nil ys = ys\" |\n\"app(Cons x xs) ys=Cons x(app xs ys)\"\n\nfun rev::\" 'a list\\<Rightarrow>'a list\"\nwhere\n\"rev Nil = Nil \" |\n\"rev(Cons x xs)=app(rev xs)(Cons x Nil)\"\nvalue \"rev(Cons True (Cons False Nil))\"\nvalue \"rev(Cons a (Cons b Nil))\"\nlemma app_Nil2 [simp]:\"app xs Nil = xs\" \n  apply(induction xs) \n  apply(auto) \n  done\nlemma app_assoc [simp]: \"app (app xs ys) zs = app xs (app ys zs)\" \n  apply(induction xs) \n  apply(auto) \n  done\nlemma rev_app [simp]:\"rev(app xs ys) = app(rev ys)(rev xs)\"\napply (induction xs)\n   apply(auto)\n  done\nlemma rev_rev [simp]: \"rev (rev xs) =xs\"\n  apply (induction xs)\n   apply(auto)\n  done\n(*-------------------*)\n\n(*2.2.5 P14*)\nfun map::\"('a\\<Rightarrow>'b) \\<Rightarrow> 'a list \\<Rightarrow>'b list\"\n  where\n\"map f Nil=Nil\"|\n\"map f (Cons x xs) = Cons (f x) (map f xs)\"\n(*-------------------*)\n\n(*Exercises P15*)\n\n(*2.1*)\nvalue\"1+(2::nat)\"\nvalue\"1+(2::int)\"\nvalue\"1-(2::nat)\"\nvalue\"1-(2::int)\"\n(*--------------*)\n\n(*exercise2.2*)\nfun double::\"nat \\<Rightarrow>nat\" where\n\"double 0=add 0 0\"|\n\"double n=add(add n 0) n\"\nlemma add_com: \"add m n=add n m\"\napply(induction m)\n   apply(auto)\nfun add_1::\"nat\\<Rightarrow>nat\"where\n\"add_1 add (add 0 n)p=add 0(add n p)\"|\n\"add_1 add (add (Suc m)n) p=add (Sucm) (add n p)\"\n\n\n(*2.3.1 P16*)\n(*e1*)\ndatatype 'a tree=Tip | Node \"'a tree\" 'a \"'a tree\"\nfun mirror::\"'a tree\\<Rightarrow>'a tree\"\n  where\n\"mirror Tip=Tip\"|\n\"mirror(Node l a r) = Node (mirror r) a (mirror l)\"\nlemma \"mirror(mirror t) =t\"\n  apply(induction t)\n   apply(auto)\n  done\n(*e2*)\ndatatype 'a option=None | Some 'a\nfun lookup::\"('a *'b)list \\<Rightarrow> 'a \\<Rightarrow> 'b option\"\n  where\n\"lookup [] x= None\"|\n\"lookup ((a,b)#ps)x= (if a=x then Some b else lookup ps x)\"\n\n\n(*-------------------*)\n\n(*2.3.2 P17*)\ndefinition sq::\"nat\\<Rightarrow>nat\"where\n\"sq n=n*n\"\n(*-------------------*)\n\n(*2.3.3 P17*)\nabbreviation sq' :: \"nat\\<Rightarrow>nat\" where(*? ? ?*)\n\"sq' n=n*n\"\n(*------------------*)\n\n\n(*2.3.4*)\nfun div2::\"nat\\<Rightarrow>nat\"where\n\"div2 0= 0\"|\n\"div2 (Suc 0) = 0\"|\n\"div2 (Suc (Suc n)) =Suc(div2 n)\"\nlemma \"div2(n) = n div 2\"\n  apply(induction n rule:div2.induct)\n  apply(auto)\n  done\n(*-------------------*)\n\n(*2.4 P20*)\nfun itrev::\"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where\n\"itrev []      ys = ys\" |\n\"itrev (x#xs) ys = itrev xs (x#ys)\"\nlemma \"itrev xs [] = rev xs\"\n  apply(induction xs)\n  apply(auto)\nlemma \"itrev xs ys=rev xs @ ys\"\n  apply(induction xs arbitrary: ys)\n  apply(auto)\n  done\n(*---------------*)\n\n(*3.12 P29*)\ntype_synonym vname=string\ndatatype aexp=N int | V vname | Plud aexp aexp\ntype_synonym val=int\ntype_synonym state = vname\\<Rightarrow>val(*? ? ?*)\nfun aval::\"aexp \\<Rightarrow> state \\<Rightarrow> val\"\n  where\n\"aval (N n) s =n\"|\n\"aval (V x) s=s x\"|\n\"aval (Plus a b)s=aval a s +aval b s\"\n\nvalue \"aval (Plus (N 3)(V ''x'')) (\\<lambda>x.0)\"", "meta": {"author": "Strongman86", "repo": "Isabelle_Learning", "sha": "721bc6b04735f03a3bc1788c5970f681d78f1b47", "save_path": "github-repos/isabelle/Strongman86-Isabelle_Learning", "path": "github-repos/isabelle/Strongman86-Isabelle_Learning/Isabelle_Learning-721bc6b04735f03a3bc1788c5970f681d78f1b47/Isabelle_Learning/formal/Concrete-Semantics/Concrete_semantic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7989788228205861}}
{"text": "\ntext \\<open>Authors: Anthony Bordg and Lawrence Paulson,\nwith some contributions from Wenda Li\\<close>\n\ntheory Topological_Space\n  imports Complex_Main\n          \"Jacobson_Basic_Algebra.Set_Theory\"\n          Set_Extras\n          Sketch_and_Explore\n          HOL.Filter\n\nbegin\n\nsection \\<open>Topological Spaces\\<close>\n\nlocale topological_space = fixes S :: \"'a set\" and is_open :: \"'a set \\<Rightarrow> bool\"\n  assumes open_space [simp, intro]: \"is_open S\" and open_empty [simp, intro]: \"is_open {}\" \n    and open_imp_subset: \"is_open U \\<Longrightarrow> U \\<subseteq> S\"\n    and open_inter [intro]: \"\\<lbrakk>is_open U; is_open V\\<rbrakk> \\<Longrightarrow> is_open (U \\<inter> V)\" \n    and open_union [intro]: \"\\<And>F::('a set) set. (\\<And>x. x \\<in> F \\<Longrightarrow> is_open x) \\<Longrightarrow> is_open (\\<Union>x\\<in>F. x)\"\n\nbegin\n\ndefinition is_closed :: \"'a set \\<Rightarrow> bool\"\n  where \"is_closed U \\<equiv> U \\<subseteq> S \\<and> is_open (S - U)\"\n\ndefinition neighborhoods:: \"'a \\<Rightarrow> ('a set) set\"\n  where \"neighborhoods x \\<equiv> {U. is_open U \\<and> x \\<in> U}\"\n\ntext \\<open>Note that by a neighborhood we mean what some authors call an open neighborhood.\\<close>\n\nlemma open_union' [intro]: \"\\<And>F::('a set) set. (\\<And>x. x \\<in> F \\<Longrightarrow> is_open x) \\<Longrightarrow> is_open (\\<Union>F)\"\n  using open_union by auto\n\nlemma open_preimage_identity [simp]: \"is_open B \\<Longrightarrow> identity S \\<^sup>\\<inverse> S B = B\"\n  by (metis inf.orderE open_imp_subset preimage_identity_self)\n\n\ndefinition is_connected:: \"bool\" where \n\"is_connected \\<equiv> \\<not> (\\<exists>U V. is_open U \\<and> is_open V \\<and> (U \\<noteq> {}) \\<and> (V \\<noteq> {}) \\<and> (U \\<inter> V = {}) \\<and> (U \\<union> V = S))\"\n\ndefinition is_hausdorff:: \"bool\" where\n\"is_hausdorff \\<equiv> \n\\<forall>x y. (x \\<in> S \\<and> y \\<in> S \\<and> x \\<noteq> y) \\<longrightarrow> (\\<exists>U V. U \\<in> neighborhoods x \\<and> V \\<in> neighborhoods y \\<and> U \\<inter> V = {})\"\n\nend (* topological_space *)\n\ntext \\<open>T2 spaces are also known as Hausdorff spaces.\\<close>\n\nlocale t2_space = topological_space +\n  assumes hausdorff: \"is_hausdorff\"\n\n\nsubsection \\<open>Topological Basis\\<close>\n\ninductive generated_topology :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" \n    for S :: \"'a set\" and B :: \"'a set set\"\n  where\n    UNIV: \"generated_topology S B S\"\n  | Int: \"generated_topology S B (U \\<inter> V)\" \n            if \"generated_topology S B U\" and \"generated_topology S B V\"\n  | UN: \"generated_topology S B (\\<Union>K)\" if \"(\\<And>U. U \\<in> K \\<Longrightarrow> generated_topology S B U)\"\n  | Basis: \"generated_topology S B b\" if \"b \\<in> B \\<and> b \\<subseteq> S\"\n\nlemma generated_topology_empty [simp]: \"generated_topology S B {}\"\n  by (metis UN Union_empty empty_iff)\n\nlemma generated_topology_subset: \"generated_topology S B U \\<Longrightarrow> U \\<subseteq> S\"\n  by (induct rule:generated_topology.induct) auto\n\nlemma generated_topology_is_topology:\n  fixes S:: \"'a set\" and B:: \"'a set set\"\n  shows \"topological_space S (generated_topology S B)\"\n  by (simp add: Int UN UNIV generated_topology_subset topological_space_def)\n\n\nsubsection \\<open>Covers\\<close>\n\nlocale cover_of_subset =\n  fixes X:: \"'a set\" and U:: \"'a set\" and index:: \"real set\" and cover:: \"real \\<Rightarrow> 'a set\"\n(* We use real instead of index::\"'b set\" otherwise we get some troubles with locale sheaf_of_rings\nin Comm_Ring_Theory.thy *)\n  assumes is_subset: \"U \\<subseteq> X\" and are_subsets: \"\\<And>i. i \\<in> index \\<Longrightarrow> cover i \\<subseteq> X\"\nand covering: \"U \\<subseteq> (\\<Union>i\\<in>index. cover i)\"\nbegin\n\nlemma \n  assumes \"x \\<in> U\"\n  shows \"\\<exists>i\\<in>index. x \\<in> cover i\"\n  using assms covering by auto\n\ndefinition select_index:: \"'a \\<Rightarrow> real\" \n  where \"select_index x \\<equiv> SOME i. i \\<in> index \\<and> x \\<in> cover i\"\n\nlemma cover_of_select_index:\n  assumes \"x \\<in> U\"\n  shows \"x \\<in> cover (select_index x)\"\n  using assms by (metis (mono_tags, lifting) UN_iff covering select_index_def someI_ex subset_iff)\n\nlemma select_index_belongs:\n  assumes \"x \\<in> U\"\n  shows \"select_index x \\<in> index\"\n  using assms by (metis (full_types, lifting) UN_iff covering in_mono select_index_def tfl_some)\n\nend (* cover_of_subset *)\n\nlocale open_cover_of_subset = topological_space X is_open + cover_of_subset X U I C \n  for X and is_open and U and I and C +\n  assumes are_open_subspaces: \"\\<And>i. i\\<in>I \\<Longrightarrow> is_open (C i)\"\nbegin\n\nlemma cover_of_select_index_is_open:\n  assumes \"x \\<in> U\"\n  shows \"is_open (C (select_index x))\" \n  using assms by (simp add: are_open_subspaces select_index_belongs)\n\nend (* open_cover_of_subset *)\n\nlocale open_cover_of_open_subset = open_cover_of_subset X is_open U I C \n  for X and is_open and U and I and C +\n  assumes is_open_subset: \"is_open U\"\n\n\nsubsection \\<open>Induced Topology\\<close>\n\nlocale ind_topology = topological_space X is_open for X and is_open +\n  fixes S:: \"'a set\"\n  assumes is_subset: \"S \\<subseteq> X\"\nbegin\n\ndefinition ind_is_open:: \"'a set \\<Rightarrow> bool\"\n  where \"ind_is_open U \\<equiv> U \\<subseteq> S \\<and> (\\<exists>V. V \\<subseteq> X \\<and> is_open V \\<and> U = S \\<inter> V)\"\n\nlemma ind_is_open_S [iff]: \"ind_is_open S\"\n    by (metis ind_is_open_def inf.orderE is_subset open_space order_refl)\n\nlemma ind_is_open_empty [iff]: \"ind_is_open {}\"\n    using ind_is_open_def by auto\n\nlemma ind_space_is_top_space:\n  shows \"topological_space S (ind_is_open)\"\nproof\n  fix U V\n  assume \"ind_is_open U\" then obtain UX where \"UX \\<subseteq> X\" \"is_open UX\" \"U = S \\<inter> UX\"\n    using ind_is_open_def by auto\n  moreover\n  assume \"ind_is_open V\" then obtain VX where \"VX \\<subseteq> X\" \"is_open VX\" \"V = S \\<inter> VX\"\n    using ind_is_open_def by auto\n  ultimately have \"is_open (UX \\<inter> VX) \\<and> (U \\<inter> V = S \\<inter> (UX \\<inter> VX))\" using open_inter by auto\n  then show \"ind_is_open (U \\<inter> V)\"\n    by (metis \\<open>UX \\<subseteq> X\\<close> ind_is_open_def le_infI1 subset_refl)\nnext\n  fix F\n  assume F: \"\\<And>x. x \\<in> F \\<Longrightarrow> ind_is_open x\"\n  obtain F' where F': \"\\<And>x. x \\<in> F \\<and> ind_is_open x \\<Longrightarrow> is_open (F' x) \\<and> x = S \\<inter> (F' x)\"\n    using ind_is_open_def by metis\n  have \"is_open (\\<Union> (F' ` F))\"\n    by (metis (mono_tags, lifting) F F' imageE image_ident open_union)\n  moreover\n  have \"(\\<Union>x\\<in>F. x) = S \\<inter> \\<Union> (F' ` F)\"\n    using F' \\<open>\\<And>x. x \\<in> F \\<Longrightarrow> ind_is_open x\\<close> by fastforce\n  ultimately show \"ind_is_open (\\<Union>x\\<in>F. x)\"\n    by (metis ind_is_open_def inf_sup_ord(1) open_imp_subset)\nnext\n  show \"\\<And>U. ind_is_open U \\<Longrightarrow> U \\<subseteq> S\"\n    by (simp add: ind_is_open_def)\nqed auto\n\nlemma is_open_from_ind_is_open:\n  assumes \"is_open S\" and \"ind_is_open U\"\n  shows \"is_open U\"\n  using assms open_inter ind_is_open_def is_subset by auto\n\nlemma open_cover_from_ind_open_cover:\n  assumes \"is_open S\" and \"open_cover_of_open_subset S ind_is_open U I C\"\n  shows \"open_cover_of_open_subset X is_open U I C\"\nproof\n  show \"is_open U\" \n    using assms is_open_from_ind_is_open open_cover_of_open_subset.is_open_subset by blast\n  show \"\\<And>i. i \\<in> I \\<Longrightarrow> is_open (C i)\" \n    using assms is_open_from_ind_is_open open_cover_of_open_subset_def open_cover_of_subset.are_open_subspaces by blast\n  show \"\\<And>i. i \\<in> I \\<Longrightarrow> C i \\<subseteq> X\" \n    using assms(2) is_subset\n    by (meson cover_of_subset_def open_cover_of_open_subset_def open_cover_of_subset_def subset_trans)\n  show \"U \\<subseteq> X\"\n    by (simp add: \\<open>is_open U\\<close> open_imp_subset)\n  show \"U \\<subseteq> \\<Union> (C ` I)\"\n    by (meson assms(2) cover_of_subset_def open_cover_of_open_subset_def open_cover_of_subset_def)\nqed\n\nend (* induced topology *)\n\nlemma (in topological_space) ind_topology_is_open_self [iff]: \"ind_topology S is_open S\"\n  by (simp add: ind_topology_axioms_def ind_topology_def topological_space_axioms)\n\nlemma (in topological_space) ind_topology_is_open_empty [iff]: \"ind_topology S is_open {}\"\n  by (simp add: ind_topology_axioms_def ind_topology_def topological_space_axioms)\n\nlemma (in topological_space) ind_is_open_iff_open:\n  shows \"ind_topology.ind_is_open S is_open S U \\<longleftrightarrow> is_open U \\<and> U \\<subseteq> S\"\n  by (metis ind_topology.ind_is_open_def ind_topology_is_open_self inf.absorb_iff2)\n\nsubsection \\<open>Continuous Maps\\<close>\n\nlocale continuous_map = source: topological_space S is_open + target: topological_space S' is_open' \n+ map f S S'\n  for S and is_open and S' and is_open' and f +\n  assumes is_continuous: \"\\<And>U. is_open' U \\<Longrightarrow> is_open (f\\<^sup>\\<inverse> S U)\"\nbegin\n\nlemma open_cover_of_open_subset_from_target_to_source:\n  assumes \"open_cover_of_open_subset S' is_open' U I C\"\n  shows \"open_cover_of_open_subset S is_open (f\\<^sup>\\<inverse> S U) I (\\<lambda>i. f\\<^sup>\\<inverse> S (C i))\"\nproof\n  show \"f \\<^sup>\\<inverse> S U \\<subseteq> S\" by simp\n  show \"f \\<^sup>\\<inverse> S (C i) \\<subseteq> S\" if \"i \\<in> I\" for i\n    using that by simp\n  show \"is_open (f \\<^sup>\\<inverse> S U)\"\n    by (meson assms is_continuous open_cover_of_open_subset.is_open_subset) \n  show \"\\<And>i. i \\<in> I \\<Longrightarrow> is_open (f \\<^sup>\\<inverse> S (C i))\"\n    by (meson assms is_continuous open_cover_of_open_subset_def open_cover_of_subset.are_open_subspaces)\n  show \"f \\<^sup>\\<inverse> S U \\<subseteq> (\\<Union>i\\<in>I. f \\<^sup>\\<inverse> S (C i))\"\n    using assms unfolding open_cover_of_open_subset_def cover_of_subset_def open_cover_of_subset_def\n    by blast\nqed\n\nend (* continuous map *)\n\n\nsubsection \\<open>Homeomorphisms\\<close>\n\ntext \\<open>The topological isomorphisms between topological spaces are called homeomorphisms.\\<close>\n\nlocale homeomorphism = \n  continuous_map + bijective_map f S S' + \n  continuous_map S' is_open' S is_open \"inverse_map f S S'\"\n\nlemma (in topological_space) id_is_homeomorphism:\n  shows \"homeomorphism S is_open S is_open (identity S)\"\nproof\n  show \"inverse_map (identity S) S S \\<in> S \\<rightarrow>\\<^sub>E S\"\n    by (simp add: inv_into_into inverse_map_def)\nqed (auto simp: open_inter bij_betwI')\n\n\nsubsection \\<open>Topological Filters\\<close> (* Imported from HOL.Topological_Spaces *)\n\ndefinition (in topological_space) nhds :: \"'a \\<Rightarrow> 'a filter\"\n  where \"nhds a = (INF S\\<in>{S. is_open S \\<and> a \\<in> S}. principal S)\"\n\nabbreviation (in topological_space)\n  tendsto :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'b filter \\<Rightarrow> bool\"  (infixr \"\\<longlongrightarrow>\" 55)\n  where \"(f \\<longlongrightarrow> l) F \\<equiv> filterlim f (nhds l) F\"\n\ndefinition (in t2_space) Lim :: \"'f filter \\<Rightarrow> ('f \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"Lim A f = (THE l. (f \\<longlongrightarrow> l) A)\"\n\nend", "meta": {"author": "zibo-yang", "repo": "The_Silicon_Geometer", "sha": "6b8ecf0642d9a27e168f6bae5c54a035cf5a8ebb", "save_path": "github-repos/isabelle/zibo-yang-The_Silicon_Geometer", "path": "github-repos/isabelle/zibo-yang-The_Silicon_Geometer/The_Silicon_Geometer-6b8ecf0642d9a27e168f6bae5c54a035cf5a8ebb/Topological_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7989589013600386}}
{"text": "theory Prog_Prove_3_5\n  imports Main\nbegin\n\ninductive ev:: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev m \\<Longrightarrow> evn m\"\napply(induction rule: ev.induct)\n  by(simp_all)\n\nlemma \"ev(Suc(Suc(Suc(Suc 0))))\"\n  apply(rule evSS)\n  apply(rule evSS)\n  apply(rule ev0)\n  done\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply(induction n rule: evn.induct)\n  by(simp_all add: ev0 evSS)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  apply(induction rule: star.induct)\n  apply(assumption)\n  apply(metis step)\n  done\n\nlemma star_pre: \"\\<lbrakk>r x y; star r y z\\<rbrakk> \\<Longrightarrow> star r x z\"\n  by (rule step)\n\nlemma star_ap: \"\\<lbrakk>star r x y; r y z\\<rbrakk> \\<Longrightarrow> star r x z\"\n  apply(induction rule: star.induct)\n   apply(auto intro: star.intros)\n  done\n\n\ninductive palindrome:: \"'a list \\<Rightarrow> bool\" where\nemp: \"palindrome []\" |\nsing: \"palindrome [x]\" |\nlist: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction rule: palindrome.induct)\n  by(simp_all)\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma star'_ap: \"\\<lbrakk>star' r y z; r x y\\<rbrakk> \\<Longrightarrow> star' r x z\"\n  apply(induction rule: star'.induct)\n   apply(auto intro: star'.intros)\n  done\n\n(*\nwhy this lemma couldn't be shown?\nlemma star'_pre: \"\\<lbrakk>r x y; star' r y z\\<rbrakk> \\<Longrightarrow> star' r x z\"\n  apply(induction rule: star'.induct)\n  done\n*)\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\n  apply(induction rule: star'.induct)\n   apply(rule refl)\n    apply(auto intro:  star_ap)\n  done\n\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n  apply(induction rule: star.induct)\n   apply(rule refl')\n    apply(auto intro: star'_ap)\n  done\n\ninductive iter:: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter_refl: \"iter r n x x\" |\niter_step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r n x z\"\n\n\nlemma iter_ap: \"\\<lbrakk> r x y; iter r n y z\\<rbrakk> \\<Longrightarrow> iter r n x z\"\n  by (rule iter_step)\n\n\nlemma \"star r x y \\<Longrightarrow> iter r n x y\"\n  apply(induction rule: star.induct)\n   apply(rule iter_refl)\n  apply(auto intro: iter_ap)\n  done\n\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\ns_emp: \"S[]\" |\ns_list: \"S xs \\<Longrightarrow> S (a # xs @ [b])\" |\ns_const: \"S xs \\<Longrightarrow> S ys \\<Longrightarrow> S(xs@ys)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nt_emp: \"T[]\" |\nt_const: \"T xs \\<Longrightarrow> T ys \\<Longrightarrow>  T(a # xs @ b # ys)\"\n\n\nlemma s_formed_for_t: \"S xs \\<Longrightarrow> S ys \\<Longrightarrow> S (a # xs @ b # ys)\"\n  using s_const s_emp s_list apply force\n  done\n\nlemma TS: \"T w \\<Longrightarrow> S w\"\n  apply(induction rule: T.induct)\n   apply(rule s_emp)\n  apply(auto intro: s_formed_for_t)\n  done\n\nlemma t_formed_for_s: \" T xs \\<Longrightarrow>  T ys \\<Longrightarrow> T (xs @ ys)\"\n  apply(induction rule: T.induct)\n   apply simp\n  by (simp add: t_const)\n\nlemma ST: \"S w \\<Longrightarrow> T w\"\n  apply(induction rule: S.induct)\n  apply(rule t_emp)\n   apply(auto intro: t_formed_for_s)\n  by (simp add: t_const t_emp)\n\ncorollary SeqT: \"S w \\<longleftrightarrow> T w\"\n  using ST TS by blast\n\n(* Exercise 4.6 *)\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\" \n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus x y) s = aval x s + aval y s\" \n\ninductive aval_rel2 :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nrel_nat: \"aval_rel2 (N n) s n\" |\nrel_var: \"s x = n \\<Longrightarrow> aval_rel2 (V x) s n\" |\nrel_plus: \"(aval_rel2 x s n1) \\<Longrightarrow>  (aval_rel2 y s n2) \\<Longrightarrow> aval_rel2 (Plus x y) s (n1 + n2)\"\n\nlemma aval_rel_to_aval: \"aval_rel2 x s v \\<Longrightarrow> (aval x s = v)\"\n  apply(induction rule: aval_rel2.induct)\n  apply(auto)\n  done\n\nlemma aval_to_aval_rel: \"(aval x s = v) \\<Longrightarrow> aval_rel2 x s v\"\n  apply(induction x arbitrary: v)\n(*    apply (simp add: rel_nat)\n   apply (simp add: rel_var)\n apply (simp add: rel_plus) *)\n  apply(auto intro: rel_nat rel_var rel_plus)\n  done\n\nlemma \"(aval_rel2 x s v) \\<longleftrightarrow> (aval x s = v)\"\n  apply(auto simp add: aval_rel_to_aval)\n  apply(auto simp add: aval_to_aval_rel)\n  done\n\n(* Exercise 4.7. *)\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk = n # stk\" |\n\"exec1 (LOAD x) s stk = s(x) # stk\" |\n\"exec1 ADD _ (j # i # stk) = (i + j) # stk\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i#is) s stk = exec is s (exec1 i s stk)\"\n\nlemma exec_division: \"exec (is1 @ is2) s stk = exec is2 s (exec is1 s stk)\"\n  apply(induction is1 arbitrary:stk)\n   apply(auto)\n  done\n\nlemma exec_append: \"exec is\\<^sub>1 s stk = stk' \\<Longrightarrow> exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s stk'\"\napply(induction is\\<^sub>1 arbitrary: stk)\napply(auto)\ndone\n\nfun comp:: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\nlemma \"exec (comp x) s stk = aval x s # stk\"\n  apply(induction x arbitrary:stk)\n    apply(auto simp add: exec_division )\n  done\n\n(* the size of the execution become + 1 when LOADI or LOAD\nbut when ADD which is compiled and become -1.\n*)\ninductive  ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where \nok_emp: \"ok n [] n\" |\nok_LOADI: \"ok n is n'  \\<Longrightarrow> ok n (is @ [LOADI _]) (n' + 1)\" |\nok_LOAD: \"ok n is n'  \\<Longrightarrow> ok n (is @ [LOAD _]) (n' + 1)\" |\n(* when n' = 0 or 1, n' -1 would be not nat*)\nok_ADD: \"ok n is (n' + 2)   \\<Longrightarrow> ok n (is @ [ADD]) (n' + 1)\"\n\n(*\nlemma \"length (exec is s stk) = Suc (Suc n') \\<Longrightarrow>\n       length (exec1 ADD s (exec is s stk)) = Suc n'\"\n  by (smt Nitpick.size_list_simp(2) add_diff_cancel_left' exec1.elims instr.distinct(3) instr.distinct(5) list.sel(3) nat.distinct(1) null_rec(1) null_rec(2) plus_1_eq_Suc)\n*)\n\n\nlemma \"\\<lbrakk>ok n is n'; length stk = n \\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"\n  apply(induction rule: ok.induct)\n    apply(auto simp add: exec_division)\n  by (smt exec1.elims instr.distinct(3) instr.distinct(5) length_Cons list.size(3) nat.distinct(1) nat.inject)\n\n\n (* The followings are timed-out:\n  by (smt exec1.elims instr.distinct(3) instr.distinct(5) length_Cons list.size(3) nat.distinct(1) nat.inject)\n  by (smt Nitpick.size_list_simp(2) add_left_cancel exec1.elims instr.distinct(3) instr.distinct(5) length_Cons nat.distinct(1) plus_1_eq_Suc)\n*)\n\n(* the followings are copied and pasted from following github:\nhttps://github.com/cmr/ConcreteSemantics/blob/master/CS_Ch4.thy\n\nI couldn't understand what have done and how to know this proof.\n*)\n\n(* TODO: try again!*)\nlemma ok_append: \"ok n (e2) n' \\<Longrightarrow> ok n'' (e1) n \\<Longrightarrow> ok n'' (e1 @ e2) n'\"\napply(induction rule: ok.induct)\napply(simp)\napply (metis append_assoc ok.simps)\napply (metis append_assoc ok.simps)\napply (metis append_assoc ok.simps)\ndone\n\n\nlemma \"ok n (comp x) (Suc n)\"\napply(induction x arbitrary: n)\n\nusing ok_LOADI ok_emp apply fastforce\nusing ok_LOAD ok_emp apply fastforce\nusing ok_ADD ok_append apply fastforce\n  done\n\nend", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/previous_studied_result/Prog_Prove_3_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8872046026642945, "lm_q1q2_score": 0.7989541710800873}}
{"text": "(*  Title:      HOL/Algebra/Polynomials.thy\n    Author:     Paulo Emílio de Vilhena\n*)\n\ntheory Polynomials\n  imports Ring Ring_Divisibility Subrings\n\nbegin\n\nsection \\<open>Polynomials\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\nabbreviation lead_coeff :: \"'a list \\<Rightarrow> 'a\"\n  where \"lead_coeff \\<equiv> hd\"\n\nabbreviation degree :: \"'a list \\<Rightarrow> nat\"\n  where \"degree p \\<equiv> length p - 1\"\n\ndefinition polynomial :: \"_ \\<Rightarrow> 'a set \\<Rightarrow> 'a list \\<Rightarrow> bool\" (\"polynomial\\<index>\")\n  where \"polynomial\\<^bsub>R\\<^esub> K p \\<longleftrightarrow> p = [] \\<or> (set p \\<subseteq> K \\<and> lead_coeff p \\<noteq> \\<zero>\\<^bsub>R\\<^esub>)\"\n\ndefinition (in ring) monom :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a list\"\n  where \"monom a n = a # (replicate n \\<zero>\\<^bsub>R\\<^esub>)\"\n\nfun (in ring) eval :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where\n    \"eval [] = (\\<lambda>_. \\<zero>)\"\n  | \"eval p = (\\<lambda>x. ((lead_coeff p) \\<otimes> (x [^] (degree p))) \\<oplus> (eval (tl p) x))\"\n\nfun (in ring) coeff :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  where\n    \"coeff [] = (\\<lambda>_. \\<zero>)\"\n  | \"coeff p = (\\<lambda>i. if i = degree p then lead_coeff p else (coeff (tl p)) i)\"\n\nfun (in ring) normalize :: \"'a list \\<Rightarrow> 'a list\"\n  where\n    \"normalize [] = []\"\n  | \"normalize p = (if lead_coeff p \\<noteq> \\<zero> then p else normalize (tl p))\"\n\nfun (in ring) poly_add :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"poly_add p1 p2 =\n           (if length p1 \\<ge> length p2\n            then normalize (map2 (\\<oplus>) p1 ((replicate (length p1 - length p2) \\<zero>) @ p2))\n            else poly_add p2 p1)\"\n\nfun (in ring) poly_mult :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where\n    \"poly_mult [] p2 = []\"\n  | \"poly_mult p1 p2 =\n       poly_add ((map (\\<lambda>a. lead_coeff p1 \\<otimes> a) p2) @ (replicate (degree p1) \\<zero>)) (poly_mult (tl p1) p2)\"\n\nfun (in ring) dense_repr :: \"'a list \\<Rightarrow> ('a \\<times> nat) list\"\n  where\n    \"dense_repr [] = []\"\n  | \"dense_repr p = (if lead_coeff p \\<noteq> \\<zero>\n                     then (lead_coeff p, degree p) # (dense_repr (tl p))\n                     else (dense_repr (tl p)))\"\n\nfun (in ring) poly_of_dense :: \"('a \\<times> nat) list \\<Rightarrow> 'a list\"\n  where \"poly_of_dense dl = foldr (\\<lambda>(a, n) l. poly_add (monom a n) l) dl []\"\n\ndefinition (in ring) poly_of_const :: \"'a \\<Rightarrow> 'a list\"\n  where \"poly_of_const = (\\<lambda>k. normalize [ k ])\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\ncontext ring\nbegin\n\nlemma polynomialI [intro]: \"\\<lbrakk> set p \\<subseteq> K; lead_coeff p \\<noteq> \\<zero> \\<rbrakk> \\<Longrightarrow> polynomial K p\"\n  unfolding polynomial_def by auto\n\nlemma polynomial_incl: \"polynomial K p \\<Longrightarrow> set p \\<subseteq> K\"\n  unfolding polynomial_def by auto\n\nlemma monom_in_carrier [intro]: \"a \\<in> carrier R \\<Longrightarrow> set (monom a n) \\<subseteq> carrier R\"\n  unfolding monom_def by auto\n\nlemma lead_coeff_not_zero: \"polynomial K (a # p) \\<Longrightarrow> a \\<in> K - { \\<zero> }\"\n  unfolding polynomial_def by simp\n\nlemma zero_is_polynomial [intro]: \"polynomial K []\"\n  unfolding polynomial_def by simp\n\nlemma const_is_polynomial [intro]: \"a \\<in> K - { \\<zero> } \\<Longrightarrow> polynomial K [ a ]\"\n  unfolding polynomial_def by auto\n\nlemma normalize_gives_polynomial: \"set p \\<subseteq> K \\<Longrightarrow> polynomial K (normalize p)\"\n  by (induction p) (auto simp add: polynomial_def)\n\nlemma normalize_in_carrier: \"set p \\<subseteq> carrier R \\<Longrightarrow> set (normalize p) \\<subseteq> carrier R\"\n  by (induction p) (auto)\n\nlemma normalize_polynomial: \"polynomial K p \\<Longrightarrow> normalize p = p\"\n  unfolding polynomial_def by (cases p) (auto)\n\nlemma normalize_idem: \"normalize ((normalize p) @ q) = normalize (p @ q)\"\n  by (induct p) (auto)\n\nlemma normalize_length_le: \"length (normalize p) \\<le> length p\"\n  by (induction p) (auto)\n\nlemma eval_in_carrier: \"\\<lbrakk> set p \\<subseteq> carrier R; x \\<in> carrier R \\<rbrakk> \\<Longrightarrow> (eval p) x \\<in> carrier R\"\n  by (induction p) (auto)\n\nlemma coeff_in_carrier [simp]: \"set p \\<subseteq> carrier R \\<Longrightarrow> (coeff p) i \\<in> carrier R\"\n  by (induction p) (auto)\n\nlemma lead_coeff_simp [simp]: \"p \\<noteq> [] \\<Longrightarrow> (coeff p) (degree p) = lead_coeff p\"\n  by (metis coeff.simps(2) list.exhaust_sel)\n\nlemma coeff_list: \"map (coeff p) (rev [0..< length p]) = p\"\nproof (induction p)\n  case Nil thus ?case by simp\nnext\n  case (Cons a p)\n  have \"map (coeff (a # p)) (rev [0..<length (a # p)]) =\n         a # (map (coeff p) (rev [0..<length p]))\"\n    by auto\n  also have \" ... = a # p\"\n    using Cons by simp\n  finally show ?case . \nqed\n\nlemma coeff_nth: \"i < length p \\<Longrightarrow> (coeff p) i = p ! (length p - 1 - i)\"\nproof -\n  assume i_lt: \"i < length p\"\n  hence \"(coeff p) i = (map (coeff p) [0..< length p]) ! i\"\n    by simp\n  also have \" ... = (rev (map (coeff p) (rev [0..< length p]))) ! i\"\n    by (simp add: rev_map)\n  also have \" ... = (map (coeff p) (rev [0..< length p])) ! (length p - 1 - i)\"\n    using coeff_list i_lt rev_nth by auto\n  also have \" ... = p ! (length p - 1 - i)\"\n    using coeff_list[of p] by simp\n  finally show \"(coeff p) i = p ! (length p - 1 - i)\" .\nqed\n\nlemma coeff_iff_length_cond:\n  assumes \"length p1 = length p2\"\n  shows \"p1 = p2 \\<longleftrightarrow> coeff p1 = coeff p2\"\nproof\n  show \"p1 = p2 \\<Longrightarrow> coeff p1 = coeff p2\"\n    by simp\nnext\n  assume A: \"coeff p1 = coeff p2\"\n  have \"p1 = map (coeff p1) (rev [0..< length p1])\"\n    using coeff_list[of p1] by simp\n  also have \" ... = map (coeff p2) (rev [0..< length p2])\"\n    using A assms by simp\n  also have \" ... = p2\"\n    using coeff_list[of p2] by simp\n  finally show \"p1 = p2\" .\nqed\n\nlemma coeff_img_restrict: \"(coeff p) ` {..< length p} = set p\"\n  using coeff_list[of p] by (metis atLeast_upt image_set set_rev)\n\nlemma coeff_length: \"\\<And>i. i \\<ge> length p \\<Longrightarrow> (coeff p) i = \\<zero>\"\n  by (induction p) (auto)\n\nlemma coeff_degree: \"\\<And>i. i > degree p \\<Longrightarrow> (coeff p) i = \\<zero>\"\n  using coeff_length by (simp)\n\nlemma replicate_zero_coeff [simp]: \"coeff (replicate n \\<zero>) = (\\<lambda>_. \\<zero>)\"\n  by (induction n) (auto)\n\nlemma scalar_coeff: \"a \\<in> carrier R \\<Longrightarrow> coeff (map (\\<lambda>b. a \\<otimes> b) p) = (\\<lambda>i. a \\<otimes> (coeff p) i)\"\n  by (induction p) (auto)\n\nlemma monom_coeff: \"coeff (monom a n) = (\\<lambda>i. if i = n then a else \\<zero>)\"\n  unfolding monom_def by (induction n) (auto)\n\nlemma coeff_img:\n  \"(coeff p) ` {..< length p} = set p\"\n  \"(coeff p) ` { length p ..} = { \\<zero> }\"\n  \"(coeff p) ` UNIV = (set p) \\<union> { \\<zero> }\"\n  using coeff_img_restrict\nproof (simp)\n  show coeff_img_up: \"(coeff p) ` { length p ..} = { \\<zero> }\"\n    using coeff_length[of p] by force\n  from coeff_img_up and coeff_img_restrict[of p]\n  show \"(coeff p) ` UNIV = (set p) \\<union> { \\<zero> }\"\n    by force\nqed\n\nlemma degree_def':\n  assumes \"polynomial K p\"\n  shows \"degree p = (LEAST n. \\<forall>i. i > n \\<longrightarrow> (coeff p) i = \\<zero>)\"\nproof (cases p)\n  case Nil thus ?thesis by auto\nnext\n  define P where \"P = (\\<lambda>n. \\<forall>i. i > n \\<longrightarrow> (coeff p) i = \\<zero>)\"\n\n  case (Cons a ps)\n  hence \"(coeff p) (degree p) \\<noteq> \\<zero>\"\n    using assms unfolding polynomial_def by auto\n  hence \"\\<And>n. n < degree p \\<Longrightarrow> \\<not> P n\"\n    unfolding P_def by auto\n  moreover have \"P (degree p)\"\n    unfolding P_def using coeff_degree[of p] by simp\n  ultimately have \"degree p = (LEAST n. P n)\"\n    by (meson LeastI nat_neq_iff not_less_Least)\n  thus ?thesis unfolding P_def .\nqed\n\nlemma coeff_iff_polynomial_cond:\n  assumes \"polynomial K p1\" and \"polynomial K p2\"\n  shows \"p1 = p2 \\<longleftrightarrow> coeff p1 = coeff p2\"\nproof\n  show \"p1 = p2 \\<Longrightarrow> coeff p1 = coeff p2\"\n    by simp\nnext\n  assume coeff_eq: \"coeff p1 = coeff p2\"\n  hence deg_eq: \"degree p1 = degree p2\"\n    using degree_def'[OF assms(1)] degree_def'[OF assms(2)] by auto\n  thus \"p1 = p2\"\n  proof (cases)\n    assume \"p1 \\<noteq> [] \\<and> p2 \\<noteq> []\"\n    hence \"length p1 = length p2\"\n      using deg_eq by (simp add: Nitpick.size_list_simp(2)) \n    thus ?thesis\n      using coeff_iff_length_cond[of p1 p2] coeff_eq by simp\n  next\n    { fix p1 p2 assume A: \"p1 = []\" \"coeff p1 = coeff p2\" \"polynomial K p2\"\n      have \"p2 = []\"\n      proof (rule ccontr)\n        assume \"p2 \\<noteq> []\"\n        hence \"(coeff p2) (degree p2) \\<noteq> \\<zero>\"\n          using A(3) unfolding polynomial_def\n          by (metis coeff.simps(2) list.collapse)\n        moreover have \"(coeff p1) ` UNIV = { \\<zero> }\"\n          using A(1) by auto\n        hence \"(coeff p2) ` UNIV = { \\<zero> }\"\n          using A(2) by simp\n        ultimately show False\n          by blast\n      qed } note aux_lemma = this\n    assume \"\\<not> (p1 \\<noteq> [] \\<and> p2 \\<noteq> [])\"\n    hence \"p1 = [] \\<or> p2 = []\" by simp\n    thus ?thesis\n      using assms coeff_eq aux_lemma[of p1 p2] aux_lemma[of p2 p1] by auto\n  qed\nqed\n\nlemma normalize_lead_coeff:\n  assumes \"length (normalize p) < length p\"\n  shows \"lead_coeff p = \\<zero>\"\nproof (cases p)\n  case Nil thus ?thesis\n    using assms by simp\nnext\n  case (Cons a ps) thus ?thesis\n    using assms by (cases \"a = \\<zero>\") (auto)\nqed\n\nlemma normalize_length_lt:\n  assumes \"lead_coeff p = \\<zero>\" and \"length p > 0\"\n  shows \"length (normalize p) < length p\"\nproof (cases p)\n  case Nil thus ?thesis\n    using assms by simp\nnext\n  case (Cons a ps) thus ?thesis\n    using normalize_length_le[of ps] assms by simp\nqed\n\nlemma normalize_length_eq:\n  assumes \"lead_coeff p \\<noteq> \\<zero>\"\n  shows \"length (normalize p) = length p\"\n  using normalize_length_le[of p] assms nat_less_le normalize_lead_coeff by auto\n\nlemma normalize_replicate_zero: \"normalize ((replicate n \\<zero>) @ p) = normalize p\"\n  by (induction n) (auto)\n\nlemma normalize_def':\n  shows   \"p = (replicate (length p - length (normalize p)) \\<zero>) @\n                    (drop (length p - length (normalize p)) p)\" (is ?statement1)\n  and \"normalize p = drop (length p - length (normalize p)) p\"  (is ?statement2)\nproof -\n  show ?statement1\n  proof (induction p)\n    case Nil thus ?case by simp\n  next\n    case (Cons a p) thus ?case\n    proof (cases \"a = \\<zero>\")\n      assume \"a \\<noteq> \\<zero>\" thus ?case\n        using Cons by simp\n    next\n      assume eq_zero: \"a = \\<zero>\"\n      hence len_eq:\n        \"Suc (length p - length (normalize p)) = length (a # p) - length (normalize (a # p))\"\n        by (simp add: Suc_diff_le normalize_length_le)\n      have \"a # p = \\<zero> # (replicate (length p - length (normalize p)) \\<zero> @\n                              drop (length p - length (normalize p)) p)\"\n        using eq_zero Cons by simp\n      also have \" ... = (replicate (Suc (length p - length (normalize p))) \\<zero> @\n                              drop (Suc (length p - length (normalize p))) (a # p))\"\n        by simp\n      also have \" ... = (replicate (length (a # p) - length (normalize (a # p))) \\<zero> @\n                              drop (length (a # p) - length (normalize (a # p))) (a # p))\"\n        using len_eq by simp\n      finally show ?case .\n    qed\n  qed\nnext\n  show ?statement2\n  proof -\n    have \"\\<exists>m. normalize p = drop m p\"\n    proof (induction p)\n      case Nil thus ?case by simp\n    next\n      case (Cons a p) thus ?case\n        apply (cases \"a = \\<zero>\")\n        apply (auto)\n        apply (metis drop_Suc_Cons)\n        apply (metis drop0)\n        done\n    qed\n    then obtain m where m: \"normalize p = drop m p\" by auto\n    hence \"length (normalize p) = length p - m\" by simp\n    thus ?thesis\n      using m by (metis rev_drop rev_rev_ident take_rev)\n  qed\nqed\n\ncorollary normalize_trick:\n  shows \"p = (replicate (length p - length (normalize p)) \\<zero>) @ (normalize p)\"\n  using normalize_def'(1)[of p] unfolding sym[OF normalize_def'(2)] .\n\nlemma normalize_coeff: \"coeff p = coeff (normalize p)\"\nproof (induction p)\n  case Nil thus ?case by simp\nnext\n  case (Cons a p)\n  have \"coeff (normalize p) (length p) = \\<zero>\"\n    using normalize_length_le[of p] coeff_degree[of \"normalize p\"] coeff_length by blast\n  then show ?case\n    using Cons by (cases \"a = \\<zero>\") (auto)\nqed\n\nlemma append_coeff:\n  \"coeff (p @ q) = (\\<lambda>i. if i < length q then (coeff q) i else (coeff p) (i - length q))\"\nproof (induction p)\n  case Nil thus ?case\n    using coeff_length[of q] by auto\nnext\n  case (Cons a p)\n  have \"coeff ((a # p) @ q) = (\\<lambda>i. if i = length p + length q then a else (coeff (p @ q)) i)\"\n    by auto\n  also have \" ... = (\\<lambda>i. if i = length p + length q then a\n                         else if i < length q then (coeff q) i\n                         else (coeff p) (i - length q))\"\n    using Cons by auto\n  also have \" ... = (\\<lambda>i. if i < length q then (coeff q) i\n                         else if i = length p + length q then a else (coeff p) (i - length q))\"\n    by auto\n  also have \" ... = (\\<lambda>i. if i < length q then (coeff q) i\n                         else if i - length q = length p then a else (coeff p) (i - length q))\"\n    by fastforce\n  also have \" ... = (\\<lambda>i. if i < length q then (coeff q) i else (coeff (a # p)) (i - length q))\"\n    by auto\n  finally show ?case .\nqed\n\nlemma prefix_replicate_zero_coeff: \"coeff p = coeff ((replicate n \\<zero>) @ p)\"\n  using append_coeff[of \"replicate n \\<zero>\" p] replicate_zero_coeff[of n] coeff_length[of p] by auto\n\n(* ========================================================================== *)\ncontext\n  fixes K :: \"'a set\" assumes K: \"subring K R\"\nbegin\n\nlemma polynomial_in_carrier [intro]: \"polynomial K p \\<Longrightarrow> set p \\<subseteq> carrier R\"\n  unfolding polynomial_def using subringE(1)[OF K] by auto\n\nlemma carrier_polynomial [intro]: \"polynomial K p \\<Longrightarrow> polynomial (carrier R) p\"\n  unfolding polynomial_def using subringE(1)[OF K] by auto\n\nlemma append_is_polynomial: \"\\<lbrakk> polynomial K p; p \\<noteq> [] \\<rbrakk> \\<Longrightarrow> polynomial K (p @ (replicate n \\<zero>))\"\n  unfolding polynomial_def using subringE(2)[OF K] by auto\n\nlemma lead_coeff_in_carrier: \"polynomial K (a # p) \\<Longrightarrow> a \\<in> carrier R - { \\<zero> }\"\n  unfolding polynomial_def using subringE(1)[OF K] by auto\n\nlemma monom_is_polynomial [intro]: \"a \\<in> K - { \\<zero> } \\<Longrightarrow> polynomial K (monom a n)\"\n  unfolding polynomial_def monom_def using subringE(2)[OF K] by auto\n\nlemma eval_poly_in_carrier: \"\\<lbrakk> polynomial K p; x \\<in> carrier R \\<rbrakk> \\<Longrightarrow> (eval p) x \\<in> carrier R\"\n  using eval_in_carrier[OF polynomial_in_carrier] .\n\nlemma poly_coeff_in_carrier [simp]: \"polynomial K p \\<Longrightarrow> coeff p i \\<in> carrier R\"\n  using coeff_in_carrier[OF polynomial_in_carrier] .\n\nend (* of fixed K context. *)\n(* ========================================================================== *)\n\n\nsubsection \\<open>Polynomial Addition\\<close>\n\n(* ========================================================================== *)\ncontext\n  fixes K :: \"'a set\" assumes K: \"subring K R\"\nbegin\n\nlemma poly_add_is_polynomial:\n  assumes \"set p1 \\<subseteq> K\" and \"set p2 \\<subseteq> K\"\n  shows \"polynomial K (poly_add p1 p2)\"\nproof -\n  { fix p1 p2 assume A: \"set p1 \\<subseteq> K\" \"set p2 \\<subseteq> K\" \"length p1 \\<ge> length p2\"\n    hence \"polynomial K (poly_add p1 p2)\"\n    proof -\n      define p2' where \"p2' = (replicate (length p1 - length p2) \\<zero>) @ p2\"\n      hence \"set p2' \\<subseteq> K\" and \"length p1 = length p2'\"\n        using A(2-3) subringE(2)[OF K] by auto\n      hence \"set (map2 (\\<oplus>) p1 p2') \\<subseteq> K\"\n        using A(1) subringE(7)[OF K]\n        by (induct p1) (auto, metis set_ConsD subsetD set_zip_leftD set_zip_rightD)\n      thus ?thesis\n        unfolding p2'_def using normalize_gives_polynomial A(3) by simp\n    qed }\n  thus ?thesis\n    using assms by auto\nqed\n\nlemma poly_add_closed: \"\\<lbrakk> polynomial K p1; polynomial K p2 \\<rbrakk> \\<Longrightarrow> polynomial K (poly_add p1 p2)\"\n  using poly_add_is_polynomial polynomial_incl by simp\n\nlemma poly_add_length_eq:\n  assumes \"polynomial K p1\" \"polynomial K p2\" and \"length p1 \\<noteq> length p2\"\n  shows \"length (poly_add p1 p2) = max (length p1) (length p2)\"\nproof -\n  { fix p1 p2 assume A: \"polynomial K p1\" \"polynomial K p2\" \"length p1 > length p2\"\n    hence \"length (poly_add p1 p2) = max (length p1) (length p2)\"\n    proof -\n      let ?p2 = \"(replicate (length p1 - length p2) \\<zero>) @ p2\"\n      have p1: \"p1 \\<noteq> []\" and p2: \"?p2 \\<noteq> []\"\n        using A(3) by auto\n      then have \"zip p1 (replicate (length p1 - length p2) \\<zero> @ p2) = zip (lead_coeff p1 # tl p1) (lead_coeff (replicate (length p1 - length p2) \\<zero> @ p2) # tl (replicate (length p1 - length p2) \\<zero> @ p2))\"\n        by auto\n      hence \"lead_coeff (map2 (\\<oplus>) p1 ?p2) = lead_coeff p1 \\<oplus> lead_coeff ?p2\"\n        by simp\n      moreover have \"lead_coeff p1 \\<in> carrier R\"\n        using p1 A(1) lead_coeff_in_carrier[OF K, of \"hd p1\" \"tl p1\"] by auto\n      ultimately have \"lead_coeff (map2 (\\<oplus>) p1 ?p2) = lead_coeff p1\"\n        using A(3) by auto\n      moreover have \"lead_coeff p1 \\<noteq> \\<zero>\"\n        using p1 A(1) unfolding polynomial_def by simp\n      ultimately have \"length (normalize (map2 (\\<oplus>) p1 ?p2)) = length p1\"\n        using normalize_length_eq by auto\n      thus ?thesis\n        using A(3) by auto\n    qed }\n  thus ?thesis\n    using assms by auto\nqed\n\nlemma poly_add_degree_eq:\n  assumes \"polynomial K p1\" \"polynomial K p2\" and \"degree p1 \\<noteq> degree p2\"\n  shows \"degree (poly_add p1 p2) = max (degree p1) (degree p2)\"\n  using poly_add_length_eq[OF assms(1-2)] assms(3) by simp\n\nend (* of fixed K context. *)\n(* ========================================================================== *)\n\nlemma poly_add_in_carrier:\n  \"\\<lbrakk> set p1 \\<subseteq> carrier R; set p2 \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow> set (poly_add p1 p2) \\<subseteq> carrier R\"\n  using polynomial_incl[OF poly_add_is_polynomial[OF carrier_is_subring]] by simp\n\nlemma poly_add_length_le: \"length (poly_add p1 p2) \\<le> max (length p1) (length p2)\"\nproof -\n  { fix p1 p2 :: \"'a list\" assume A: \"length p1 \\<ge> length p2\"\n    let ?p2 = \"(replicate (length p1 - length p2) \\<zero>) @ p2\"\n    have \"length (poly_add p1 p2) \\<le> max (length p1) (length p2)\"\n      using normalize_length_le[of \"map2 (\\<oplus>) p1 ?p2\"] A by auto }\n  thus ?thesis\n    by (metis le_cases max.commute poly_add.simps)\nqed\n\nlemma poly_add_degree: \"degree (poly_add p1 p2) \\<le> max (degree p1) (degree p2)\"\n  using poly_add_length_le by (meson diff_le_mono le_max_iff_disj)\n\nlemma poly_add_coeff_aux:\n  assumes \"length p1 \\<ge> length p2\"\n  shows \"coeff (poly_add p1 p2) = (\\<lambda>i. ((coeff p1) i) \\<oplus> ((coeff p2) i))\"\nproof\n  fix i\n  have \"i < length p1 \\<Longrightarrow> (coeff (poly_add p1 p2)) i = ((coeff p1) i) \\<oplus> ((coeff p2) i)\"\n  proof -\n    let ?p2 = \"(replicate (length p1 - length p2) \\<zero>) @ p2\"\n    have len_eqs: \"length p1 = length ?p2\" \"length (map2 (\\<oplus>) p1 ?p2) = length p1\"\n      using assms by auto\n    assume i_lt: \"i < length p1\"\n    have \"(coeff (poly_add p1 p2)) i = (coeff (map2 (\\<oplus>) p1 ?p2)) i\"\n      using normalize_coeff[of \"map2 (\\<oplus>) p1 ?p2\"] assms by auto\n    also have \" ... = (map2 (\\<oplus>) p1 ?p2) ! (length p1 - 1 - i)\"\n      using coeff_nth[of i \"map2 (\\<oplus>) p1 ?p2\"] len_eqs(2) i_lt by auto\n    also have \" ... = (p1 ! (length p1 - 1 - i)) \\<oplus> (?p2 ! (length ?p2 - 1 - i))\"\n      using len_eqs i_lt by auto\n    also have \" ... = ((coeff p1) i) \\<oplus> ((coeff ?p2) i)\"\n      using coeff_nth[of i p1] coeff_nth[of i ?p2] i_lt len_eqs(1) by auto\n    also have \" ... = ((coeff p1) i) \\<oplus> ((coeff p2) i)\"\n      using prefix_replicate_zero_coeff by simp\n    finally show \"(coeff (poly_add p1 p2)) i = ((coeff p1) i) \\<oplus> ((coeff p2) i)\" .\n  qed\n  moreover\n  have \"i \\<ge> length p1 \\<Longrightarrow> (coeff (poly_add p1 p2)) i = ((coeff p1) i) \\<oplus> ((coeff p2) i)\"\n    using coeff_length[of \"poly_add p1 p2\"] coeff_length[of p1] coeff_length[of p2]\n          poly_add_length_le[of p1 p2] assms by auto\n  ultimately show \"(coeff (poly_add p1 p2)) i = ((coeff p1) i) \\<oplus> ((coeff p2) i)\"\n    using not_le by blast\nqed\n\nlemma poly_add_coeff:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"coeff (poly_add p1 p2) = (\\<lambda>i. ((coeff p1) i) \\<oplus> ((coeff p2) i))\"\nproof -\n  have \"length p1 \\<ge> length p2 \\<or> length p2 > length p1\"\n    by auto\n  thus ?thesis\n  proof\n    assume \"length p1 \\<ge> length p2\" thus ?thesis\n      using poly_add_coeff_aux by simp\n  next\n    assume \"length p2 > length p1\"\n    hence \"coeff (poly_add p1 p2) = (\\<lambda>i. ((coeff p2) i) \\<oplus> ((coeff p1) i))\"\n      using poly_add_coeff_aux by simp\n    thus ?thesis\n      using assms by (simp add: add.m_comm)\n  qed\nqed\n\nlemma poly_add_comm:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"poly_add p1 p2 = poly_add p2 p1\"\nproof -\n  have \"coeff (poly_add p1 p2) = coeff (poly_add p2 p1)\"\n    using poly_add_coeff[OF assms] poly_add_coeff[OF assms(2) assms(1)]\n          coeff_in_carrier[OF assms(1)] coeff_in_carrier[OF assms(2)] add.m_comm by auto\n  thus ?thesis\n    using coeff_iff_polynomial_cond[OF\n          poly_add_is_polynomial[OF carrier_is_subring assms] \n          poly_add_is_polynomial[OF carrier_is_subring assms(2,1)]] by simp \nqed\n\nlemma poly_add_monom:\n  assumes \"set p \\<subseteq> carrier R\" and \"a \\<in> carrier R - { \\<zero> }\"\n  shows \"poly_add (monom a (length p)) p = a # p\"\n  unfolding monom_def using assms by (induction p) (auto)\n\nlemma poly_add_append_replicate:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\"\n  shows \"poly_add (p @ (replicate (length q) \\<zero>)) q = normalize (p @ q)\"\nproof -\n  have \"map2 (\\<oplus>) (p @ (replicate (length q) \\<zero>)) ((replicate (length p) \\<zero>) @ q) = p @ q\"\n    using assms by (induct p) (induct q, auto)\n  thus ?thesis by simp\nqed\n\nlemma poly_add_append_zero:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\"\n  shows \"poly_add (p @ [ \\<zero> ]) (q @ [ \\<zero> ]) = normalize ((poly_add p q) @ [ \\<zero> ])\"\nproof -\n  have in_carrier: \"set (p @ [ \\<zero> ]) \\<subseteq> carrier R\" \"set (q @ [ \\<zero> ]) \\<subseteq> carrier R\"\n    using assms by auto\n  have \"coeff (poly_add (p @ [ \\<zero> ]) (q @ [ \\<zero> ])) = coeff ((poly_add p q) @ [ \\<zero> ])\"\n    using append_coeff[of p \"[ \\<zero> ]\"] poly_add_coeff[OF in_carrier]\n          append_coeff[of q \"[ \\<zero> ]\"] append_coeff[of \"poly_add p q\" \"[ \\<zero> ]\"]\n          poly_add_coeff[OF assms] assms[THEN coeff_in_carrier] by auto\n  hence \"coeff (poly_add (p @ [ \\<zero> ]) (q @ [ \\<zero> ])) = coeff (normalize ((poly_add p q) @ [ \\<zero> ]))\"\n    using normalize_coeff by simp\n  moreover have \"set ((poly_add p q) @ [ \\<zero> ]) \\<subseteq> carrier R\"\n    using poly_add_in_carrier[OF assms] by simp\n  ultimately show ?thesis\n    using coeff_iff_polynomial_cond[OF poly_add_is_polynomial[OF carrier_is_subring in_carrier]\n          normalize_gives_polynomial] by simp\nqed\n\nlemma poly_add_normalize_aux:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"poly_add p1 p2 = poly_add (normalize p1) p2\"\nproof -\n  { fix n p1 p2 assume \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n    hence \"poly_add p1 p2 = poly_add ((replicate n \\<zero>) @ p1) p2\"\n    proof (induction n)\n      case 0 thus ?case by simp\n    next\n      { fix p1 p2 :: \"'a list\"\n        assume in_carrier: \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n        have \"poly_add p1 p2 = poly_add (\\<zero> # p1) p2\"\n        proof -\n          have \"length p1 \\<ge> length p2 \\<Longrightarrow> ?thesis\"\n          proof -\n            assume A: \"length p1 \\<ge> length p2\"\n            let ?p2 = \"\\<lambda>n. (replicate n \\<zero>) @ p2\"\n            have \"poly_add p1 p2 = normalize (map2 (\\<oplus>) (\\<zero> # p1) (\\<zero> # ?p2 (length p1 - length p2)))\"\n              using A by simp\n            also have \" ... = normalize (map2 (\\<oplus>) (\\<zero> # p1) (?p2 (length (\\<zero> # p1) - length p2)))\"\n              by (simp add: A Suc_diff_le)\n            also have \" ... = poly_add (\\<zero> # p1) p2\"\n              using A by simp\n            finally show ?thesis .\n          qed\n\n          moreover have \"length p2 > length p1 \\<Longrightarrow> ?thesis\"\n          proof -\n            assume A: \"length p2 > length p1\"\n            let ?f = \"\\<lambda>n p. (replicate n \\<zero>) @ p\"\n            have \"poly_add p1 p2 = poly_add p2 p1\"\n              using A by simp\n            also have \" ... = normalize (map2 (\\<oplus>) p2 (?f (length p2 - length p1) p1))\"\n              using A by simp\n            also have \" ... = normalize (map2 (\\<oplus>) p2 (?f (length p2 - Suc (length p1)) (\\<zero> # p1)))\"\n              by (metis A Suc_diff_Suc append_Cons replicate_Suc replicate_app_Cons_same)\n            also have \" ... = poly_add p2 (\\<zero> # p1)\"\n              using A by simp\n            also have \" ... = poly_add (\\<zero> # p1) p2\"\n              using poly_add_comm[of p2 \"\\<zero> # p1\"] in_carrier by auto\n            finally show ?thesis .\n          qed\n\n          ultimately show ?thesis by auto\n        qed } note aux_lemma = this\n\n      case (Suc n)\n      hence in_carrier: \"set (replicate n \\<zero> @ p1) \\<subseteq> carrier R\"\n        by auto\n      have \"poly_add p1 p2 = poly_add (replicate n \\<zero> @ p1) p2\"\n        using Suc by simp\n      also have \" ... = poly_add (replicate (Suc n) \\<zero> @ p1) p2\"\n        using aux_lemma[OF in_carrier Suc(3)] by simp\n      finally show ?case .\n    qed } note aux_lemma = this\n\n  have \"poly_add p1 p2 =\n        poly_add ((replicate (length p1 - length (normalize p1)) \\<zero>) @ normalize p1) p2\"\n    using normalize_def'[of p1] by simp\n  also have \" ... = poly_add (normalize p1) p2\"\n    using aux_lemma[OF normalize_in_carrier[OF assms(1)] assms(2)] by simp\n  finally show ?thesis .\nqed\n\nlemma poly_add_normalize:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"poly_add p1 p2 = poly_add (normalize p1) p2\"\n    and \"poly_add p1 p2 = poly_add p1 (normalize p2)\"\n    and \"poly_add p1 p2 = poly_add (normalize p1) (normalize p2)\"\nproof -\n  show \"poly_add p1 p2 = poly_add p1 (normalize p2)\"\n    unfolding poly_add_comm[OF assms] poly_add_normalize_aux[OF assms(2) assms(1)]\n              poly_add_comm[OF normalize_in_carrier[OF assms(2)] assms(1)] by simp \nnext\n  show \"poly_add p1 p2 = poly_add (normalize p1) p2\"\n    using poly_add_normalize_aux[OF assms] .\n  also have \" ... = poly_add (normalize p2) (normalize p1)\"\n    unfolding  poly_add_comm[OF normalize_in_carrier[OF assms(1)] assms(2)]\n               poly_add_normalize_aux[OF assms(2) normalize_in_carrier[OF assms(1)]] by simp\n  finally show \"poly_add p1 p2 = poly_add (normalize p1) (normalize p2)\"\n    unfolding  poly_add_comm[OF assms[THEN normalize_in_carrier]] .\nqed\n\nlemma poly_add_zero':\n  assumes \"set p \\<subseteq> carrier R\"\n  shows \"poly_add p [] = normalize p\" and \"poly_add [] p = normalize p\"\nproof -\n  have \"map2 (\\<oplus>) p (replicate (length p) \\<zero>) = p\"\n    using assms by (induct p) (auto)\n  thus \"poly_add p [] = normalize p\" and \"poly_add [] p = normalize p\"\n    using poly_add_comm[OF assms, of \"[]\"] by simp+\nqed\n\nlemma poly_add_zero:\n  assumes \"subring K R\" \"polynomial K p\"\n  shows \"poly_add p [] = p\" and \"poly_add [] p = p\"\n  using poly_add_zero' normalize_polynomial polynomial_in_carrier assms by auto\n\nlemma poly_add_replicate_zero':\n  assumes \"set p \\<subseteq> carrier R\"\n  shows \"poly_add p (replicate n \\<zero>) = normalize p\" and \"poly_add (replicate n \\<zero>) p = normalize p\"\nproof -\n  have \"poly_add p (replicate n \\<zero>) = poly_add p []\"\n    using poly_add_normalize(2)[OF assms, of \"replicate n \\<zero>\"]\n          normalize_replicate_zero[of n \"[]\"] by force\n  also have \" ... = normalize p\"\n    using poly_add_zero'[OF assms] by simp\n  finally show \"poly_add p (replicate n \\<zero>) = normalize p\" .\n  thus \"poly_add (replicate n \\<zero>) p = normalize p\"\n    using poly_add_comm[OF assms, of \"replicate n \\<zero>\"] by force\nqed\n\nlemma poly_add_replicate_zero:\n  assumes \"subring K R\" \"polynomial K p\"\n  shows \"poly_add p (replicate n \\<zero>) = p\" and \"poly_add (replicate n \\<zero>) p = p\"\n  using poly_add_replicate_zero' normalize_polynomial polynomial_in_carrier assms by auto\n\n\n\nsubsection \\<open>Dense Representation\\<close>\n\nlemma dense_repr_replicate_zero: \"dense_repr ((replicate n \\<zero>) @ p) = dense_repr p\"\n  by (induction n) (auto)\n\nlemma dense_repr_normalize: \"dense_repr (normalize p) = dense_repr p\"\n  by (induct p) (auto)\n\nlemma polynomial_dense_repr:\n  assumes \"polynomial K p\" and \"p \\<noteq> []\"\n  shows \"dense_repr p = (lead_coeff p, degree p) # dense_repr (normalize (tl p))\"\nproof -\n  let ?len = length and ?norm = normalize\n  obtain a p' where p: \"p = a # p'\"\n    using assms(2) list.exhaust_sel by blast \n  hence a: \"a \\<in> K - { \\<zero> }\" and p': \"set p' \\<subseteq> K\"\n    using assms(1) unfolding p by (auto simp add: polynomial_def)\n  hence \"dense_repr p = (lead_coeff p, degree p) # dense_repr p'\"\n    unfolding p by simp\n  also have \" ... =\n    (lead_coeff p, degree p) # dense_repr ((replicate (?len p' - ?len (?norm p')) \\<zero>) @ ?norm p')\"\n    using normalize_def' dense_repr_replicate_zero by simp\n  also have \" ... = (lead_coeff p, degree p) # dense_repr (?norm p')\"\n    using dense_repr_replicate_zero by simp\n  finally show ?thesis\n    unfolding p by simp\nqed\n\nlemma monom_decomp:\n  assumes \"subring K R\" \"polynomial K p\"\n  shows \"p = poly_of_dense (dense_repr p)\"\n  using assms(2)\nproof (induct \"length p\" arbitrary: p rule: less_induct)\n  case less thus ?case\n  proof (cases p)\n    case Nil thus ?thesis by simp\n  next\n    case (Cons a l)\n    hence a: \"a \\<in> carrier R - { \\<zero> }\" and l: \"set l \\<subseteq> carrier R\"  \"set l \\<subseteq> K\"\n      using less(2) subringE(1)[OF assms(1)] by (auto simp add: polynomial_def)\n    hence \"a # l = poly_add (monom a (degree (a # l))) l\"\n      using poly_add_monom[of l a] by simp\n    also have \" ... = poly_add (monom a (degree (a # l))) (normalize l)\"\n      using poly_add_normalize(2)[of \"monom a (degree (a # l))\", OF _ l(1)] a\n      unfolding monom_def by force\n    also have \" ... = poly_add (monom a (degree (a # l))) (poly_of_dense (dense_repr (normalize l)))\"\n      using less(1)[OF _ normalize_gives_polynomial[OF l(2)]] normalize_length_le[of l]\n      unfolding Cons by simp\n    also have \" ... = poly_of_dense ((a, degree (a # l)) # dense_repr (normalize l))\"\n      by simp\n    also have \" ... = poly_of_dense (dense_repr (a # l))\"\n      using polynomial_dense_repr[OF less(2)] unfolding Cons by simp\n    finally show ?thesis\n      unfolding Cons by simp\n  qed\nqed\n\n\nsubsection \\<open>Polynomial Multiplication\\<close>\n\nlemma poly_mult_is_polynomial:\n  assumes \"subring K R\" \"set p1 \\<subseteq> K\" and \"set p2 \\<subseteq> K\"\n  shows \"polynomial K (poly_mult p1 p2)\"\n  using assms(2-3)\nproof (induction p1)\n  case Nil thus ?case\n    by (simp add: polynomial_def)\nnext\n  case (Cons a p1)\n  let ?a_p2 = \"(map (\\<lambda>b. a \\<otimes> b) p2) @ (replicate (degree (a # p1)) \\<zero>)\"\n  \n  have \"set (poly_mult p1 p2) \\<subseteq> K\"\n    using Cons unfolding polynomial_def by auto\n  moreover have \"set ?a_p2 \\<subseteq> K\"\n      using assms(3) Cons(2) subringE(1-2,6)[OF assms(1)] by(induct p2) (auto)\n  ultimately have \"polynomial K (poly_add ?a_p2 (poly_mult p1 p2))\"\n    using poly_add_is_polynomial[OF assms(1)] by blast\n  thus ?case by simp\nqed\n\nlemma poly_mult_closed:\n  assumes \"subring K R\"\n  shows \"\\<lbrakk> polynomial K p1; polynomial K p2 \\<rbrakk> \\<Longrightarrow> polynomial K (poly_mult p1 p2)\"\n  using poly_mult_is_polynomial polynomial_incl assms by simp\n\nlemma poly_mult_in_carrier:\n  \"\\<lbrakk> set p1 \\<subseteq> carrier R; set p2 \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow> set (poly_mult p1 p2) \\<subseteq> carrier R\"\n  using poly_mult_is_polynomial polynomial_in_carrier carrier_is_subring by simp\n\nlemma poly_mult_coeff:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"coeff (poly_mult p1 p2) = (\\<lambda>i. \\<Oplus> k \\<in> {..i}. (coeff p1) k \\<otimes> (coeff p2) (i - k))\"\n  using assms(1) \nproof (induction p1)\n  case Nil thus ?case using assms(2) by auto\nnext\n  case (Cons a p1)\n  hence in_carrier:\n    \"a \\<in> carrier R\" \"\\<And>i. (coeff p1) i \\<in> carrier R\" \"\\<And>i. (coeff p2) i \\<in> carrier R\"\n    using coeff_in_carrier assms(2) by auto\n\n  let ?a_p2 = \"(map (\\<lambda>b. a \\<otimes> b) p2) @ (replicate (degree (a # p1)) \\<zero>)\"\n  have \"coeff  (replicate (degree (a # p1)) \\<zero>) = (\\<lambda>_. \\<zero>)\"\n   and \"length (replicate (degree (a # p1)) \\<zero>) = length p1\"\n    using prefix_replicate_zero_coeff[of \"[]\" \"length p1\"] by auto\n  hence \"coeff ?a_p2 = (\\<lambda>i. if i < length p1 then \\<zero> else (coeff (map (\\<lambda>b. a \\<otimes> b) p2)) (i - length p1))\"\n    using append_coeff[of \"map (\\<lambda>b. a \\<otimes> b) p2\" \"replicate (length p1) \\<zero>\"] by auto\n  also have \" ... = (\\<lambda>i. if i < length p1 then \\<zero> else a \\<otimes> ((coeff p2) (i - length p1)))\"\n  proof -\n    have \"\\<And>i. i < length p2 \\<Longrightarrow> (coeff (map (\\<lambda>b. a \\<otimes> b) p2)) i = a \\<otimes> ((coeff p2) i)\"\n    proof -\n      fix i assume i_lt: \"i < length p2\"\n      hence \"(coeff (map (\\<lambda>b. a \\<otimes> b) p2)) i = (map (\\<lambda>b. a \\<otimes> b) p2) ! (length p2 - 1 - i)\"\n        using coeff_nth[of i \"map (\\<lambda>b. a \\<otimes> b) p2\"] by auto\n      also have \" ... = a \\<otimes> (p2 ! (length p2 - 1 - i))\"\n        using i_lt by auto\n      also have \" ... = a \\<otimes> ((coeff p2) i)\"\n        using coeff_nth[OF i_lt] by simp\n      finally show \"(coeff (map (\\<lambda>b. a \\<otimes> b) p2)) i = a \\<otimes> ((coeff p2) i)\" .\n    qed\n    moreover have \"\\<And>i. i \\<ge> length p2 \\<Longrightarrow> (coeff (map (\\<lambda>b. a \\<otimes> b) p2)) i = a \\<otimes> ((coeff p2) i)\"\n      using coeff_length[of p2] coeff_length[of \"map (\\<lambda>b. a \\<otimes> b) p2\"] in_carrier by auto\n    ultimately show ?thesis by (meson not_le)\n  qed\n  also have \" ... = (\\<lambda>i. \\<Oplus> k \\<in> {..i}. (if k = length p1 then a else \\<zero>) \\<otimes> (coeff p2) (i - k))\"\n  (is \"?f1 = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k)))\")\n  proof\n    fix i\n    have \"\\<And>k. k \\<in> {..i} \\<Longrightarrow> ?f2 k \\<otimes> ?f3 (i - k) = \\<zero>\" if \"i < length p1\"\n      using in_carrier that by auto\n    hence \"(\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k)) = \\<zero>\" if \"i < length p1\"\n      using that in_carrier\n            add.finprod_cong'[of \"{..i}\" \"{..i}\" \"\\<lambda>k. ?f2 k \\<otimes> ?f3 (i - k)\" \"\\<lambda>i. \\<zero>\"]\n      by auto\n    hence eq_lt: \"?f1 i = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k))) i\" if \"i < length p1\"\n      using that by auto\n\n    have \"\\<And>k. k \\<in> {..i} \\<Longrightarrow>\n              ?f2 k \\<otimes>\\<^bsub>R\\<^esub> ?f3 (i - k) = (if length p1 = k then a \\<otimes> coeff p2 (i - k) else \\<zero>)\"\n      using in_carrier by auto\n    hence \"(\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k)) = \n           (\\<Oplus> k \\<in> {..i}. (if length p1 = k then a \\<otimes> coeff p2 (i - k) else \\<zero>))\"\n      using in_carrier\n            add.finprod_cong'[of \"{..i}\" \"{..i}\" \"\\<lambda>k. ?f2 k \\<otimes> ?f3 (i - k)\"\n                             \"\\<lambda>k. (if length p1 = k then a \\<otimes> coeff p2 (i - k) else \\<zero>)\"]\n      by fastforce\n    also have \" ... = a \\<otimes> (coeff p2) (i - length p1)\" if \"i \\<ge> length p1\"\n      using add.finprod_singleton[of \"length p1\" \"{..i}\" \"\\<lambda>j. a \\<otimes> (coeff p2) (i - j)\"]\n            in_carrier that by auto\n    finally\n    have \"(\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k)) =  a \\<otimes> (coeff p2) (i - length p1)\" if \"i \\<ge> length p1\"\n      using that by simp\n    hence eq_ge: \"?f1 i = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k))) i\" if \"i \\<ge> length p1\"\n      using that by auto\n\n    from eq_lt eq_ge show \"?f1 i = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ?f2 k \\<otimes> ?f3 (i - k))) i\" by auto\n  qed\n\n  finally have coeff_a_p2:\n    \"coeff ?a_p2 = (\\<lambda>i. \\<Oplus> k \\<in> {..i}. (if k = length p1 then a else \\<zero>) \\<otimes> (coeff p2) (i - k))\" .\n\n  have \"set ?a_p2 \\<subseteq> carrier R\"\n    using in_carrier(1) assms(2) by auto\n\n  moreover have \"set (poly_mult p1 p2) \\<subseteq> carrier R\"\n    using poly_mult_in_carrier[OF _ assms(2)] Cons(2) by simp\n\n  ultimately\n  have \"coeff (poly_mult (a # p1) p2) = (\\<lambda>i. ((coeff ?a_p2) i) \\<oplus> ((coeff (poly_mult p1 p2)) i))\"\n    using poly_add_coeff[of ?a_p2 \"poly_mult p1 p2\"] by simp\n  also have \" ... = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. (if k = length p1 then a else \\<zero>) \\<otimes> (coeff p2) (i - k)) \\<oplus>\n                         (\\<Oplus> k \\<in> {..i}. (coeff p1) k \\<otimes> (coeff p2) (i - k)))\"\n    using Cons  coeff_a_p2 by simp\n  also have \" ... = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ((if k = length p1 then a else \\<zero>) \\<otimes> (coeff p2) (i - k)) \\<oplus>\n                                                            ((coeff p1) k \\<otimes> (coeff p2) (i - k))))\"\n    using add.finprod_multf in_carrier by auto\n  also have \" ... = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. (coeff (a # p1) k) \\<otimes> (coeff p2) (i - k)))\"\n   (is \"(\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ?f i k)) = (\\<lambda>i. (\\<Oplus> k \\<in> {..i}. ?g i k))\")\n  proof\n    fix i\n    have \"\\<And>k. ?f i k = ?g i k\"\n      using in_carrier coeff_length[of p1] by auto\n    thus \"(\\<Oplus> k \\<in> {..i}. ?f i k) = (\\<Oplus> k \\<in> {..i}. ?g i k)\" by simp\n  qed\n  finally show ?case .\nqed\n\nlemma poly_mult_zero:\n  assumes \"set p \\<subseteq> carrier R\"\n  shows \"poly_mult [] p = []\" and \"poly_mult p [] = []\"\nproof (simp)\n  have \"coeff (poly_mult p []) = (\\<lambda>_. \\<zero>)\"\n    using poly_mult_coeff[OF assms, of \"[]\"] coeff_in_carrier[OF assms] by auto\n  thus \"poly_mult p [] = []\"\n    using coeff_iff_polynomial_cond[OF\n          poly_mult_is_polynomial[OF carrier_is_subring assms] zero_is_polynomial] by simp\nqed\n\nlemma poly_mult_l_distr':\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\" \"set p3 \\<subseteq> carrier R\"\n  shows \"poly_mult (poly_add p1 p2) p3 = poly_add (poly_mult p1 p3) (poly_mult p2 p3)\"\nproof -\n  let ?c1 = \"coeff p1\" and ?c2 = \"coeff p2\" and ?c3 = \"coeff p3\"\n  have in_carrier:\n    \"\\<And>i. ?c1 i \\<in> carrier R\" \"\\<And>i. ?c2 i \\<in> carrier R\" \"\\<And>i. ?c3 i \\<in> carrier R\"\n    using assms coeff_in_carrier by auto\n\n  have \"coeff (poly_mult (poly_add p1 p2) p3) = (\\<lambda>n. \\<Oplus>i \\<in> {..n}. (?c1 i \\<oplus> ?c2 i) \\<otimes> ?c3 (n - i))\"\n    using poly_mult_coeff[of \"poly_add p1 p2\" p3]  poly_add_coeff[OF assms(1-2)]\n          poly_add_in_carrier[OF assms(1-2)] assms by auto\n  also have \" ... = (\\<lambda>n. \\<Oplus>i \\<in> {..n}. (?c1 i \\<otimes> ?c3 (n - i)) \\<oplus> (?c2 i \\<otimes> ?c3 (n - i)))\"\n    using in_carrier l_distr by auto\n  also\n  have \" ... = (\\<lambda>n. (\\<Oplus>i \\<in> {..n}. (?c1 i \\<otimes> ?c3 (n - i))) \\<oplus> (\\<Oplus>i \\<in> {..n}. (?c2 i \\<otimes> ?c3 (n - i))))\"\n    using add.finprod_multf in_carrier by auto\n  also have \" ... = coeff (poly_add (poly_mult p1 p3) (poly_mult p2 p3))\"\n    using poly_mult_coeff[OF assms(1) assms(3)] poly_mult_coeff[OF assms(2-3)]\n          poly_add_coeff[OF poly_mult_in_carrier[OF assms(1) assms(3)]]\n                            poly_mult_in_carrier[OF assms(2-3)] by simp\n  finally have \"coeff (poly_mult (poly_add p1 p2) p3) =\n                coeff (poly_add (poly_mult p1 p3) (poly_mult p2 p3))\" .\n  moreover have \"polynomial (carrier R) (poly_mult (poly_add p1 p2) p3)\"\n            and \"polynomial (carrier R) (poly_add (poly_mult p1 p3) (poly_mult p2 p3))\"\n    using assms poly_add_is_polynomial poly_mult_is_polynomial polynomial_in_carrier\n          carrier_is_subring by auto\n  ultimately show ?thesis\n    using coeff_iff_polynomial_cond by auto \nqed\n\nlemma poly_mult_l_distr:\n  assumes \"subring K R\" \"polynomial K p1\" \"polynomial K p2\" \"polynomial K p3\"\n  shows \"poly_mult (poly_add p1 p2) p3 = poly_add (poly_mult p1 p3) (poly_mult p2 p3)\"\n  using poly_mult_l_distr' polynomial_in_carrier assms by auto\n\nlemma poly_mult_prepend_replicate_zero:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"poly_mult p1 p2 = poly_mult ((replicate n \\<zero>) @ p1) p2\"\nproof -\n  { fix p1 p2 assume A: \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n    hence \"poly_mult p1 p2 = poly_mult (\\<zero> # p1) p2\"\n    proof -\n      let ?a_p2 = \"(map ((\\<otimes>) \\<zero>) p2) @ (replicate (length p1) \\<zero>)\"\n      have \"?a_p2 = replicate (length p2 + length p1) \\<zero>\"\n        using A(2) by (induction p2) (auto)\n      hence \"poly_mult (\\<zero> # p1) p2 = poly_add (replicate (length p2 + length p1) \\<zero>) (poly_mult p1 p2)\"\n        by simp\n      also have \" ... = poly_add (normalize (replicate (length p2 + length p1) \\<zero>)) (poly_mult p1 p2)\"\n        using poly_add_normalize(1)[of \"replicate (length p2 + length p1) \\<zero>\" \"poly_mult p1 p2\"]\n              poly_mult_in_carrier[OF A] by force\n      also have \" ... = poly_mult p1 p2\"\n        using poly_add_zero(2)[OF _ poly_mult_is_polynomial[OF _ A]] carrier_is_subring\n              normalize_replicate_zero[of \"length p2 + length p1\" \"[]\"] by simp\n      finally show ?thesis by auto\n    qed } note aux_lemma = this\n  \n  from assms show ?thesis\n  proof (induction n)\n    case 0 thus ?case by simp\n  next\n    case (Suc n) thus ?case\n      using aux_lemma[of \"replicate n \\<zero> @ p1\" p2] by force\n  qed\nqed\n\nlemma poly_mult_normalize:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"poly_mult p1 p2 = poly_mult (normalize p1) p2\"\nproof -\n  let ?replicate = \"replicate (length p1 - length (normalize p1)) \\<zero>\"\n  have \"poly_mult p1 p2 = poly_mult (?replicate @ (normalize p1)) p2\"\n    using normalize_def'[of p1] by simp\n  thus ?thesis\n    using poly_mult_prepend_replicate_zero normalize_in_carrier assms by auto\nqed\n\nlemma poly_mult_append_zero:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\"\n  shows \"poly_mult (p @ [ \\<zero> ]) q = normalize ((poly_mult p q) @ [ \\<zero> ])\"\n  using assms(1)\nproof (induct p)\n  case Nil thus ?case\n    using poly_mult_normalize[OF _ assms(2), of \"[] @ [ \\<zero> ]\"]\n          poly_mult_zero(1) poly_mult_zero(1)[of \"q @ [ \\<zero> ]\"] assms(2) by auto\nnext\n  case (Cons a p)\n  let ?q_a = \"\\<lambda>n. (map ((\\<otimes>) a) q) @ (replicate n \\<zero>)\"\n  have set_q_a: \"\\<And>n. set (?q_a n) \\<subseteq> carrier R\"\n    using Cons(2) assms(2) by (induct q) (auto)\n  have set_poly_mult: \"set ((poly_mult p q) @ [ \\<zero> ]) \\<subseteq> carrier R\"\n    using poly_mult_in_carrier[OF _ assms(2)] Cons(2) by auto\n  have \"poly_mult ((a # p) @ [\\<zero>]) q = poly_add (?q_a (Suc (length p))) (poly_mult (p @ [\\<zero>]) q)\"\n    by auto\n  also have \" ... = poly_add (?q_a (Suc (length p))) (normalize ((poly_mult p q) @ [ \\<zero> ]))\"\n    using Cons by simp\n  also have \" ... = poly_add ((?q_a (length p)) @ [ \\<zero> ]) ((poly_mult p q) @ [ \\<zero> ])\"\n    using poly_add_normalize(2)[OF set_q_a[of \"Suc (length p)\"] set_poly_mult]\n    by (simp add: replicate_append_same)\n  also have \" ... = normalize ((poly_add (?q_a (length p)) (poly_mult p q)) @ [ \\<zero> ])\"\n    using poly_add_append_zero[OF set_q_a[of \"length p\"] poly_mult_in_carrier[OF _ assms(2)]] Cons(2) by auto\n  also have \" ... = normalize ((poly_mult (a # p) q) @ [ \\<zero> ])\"\n    by auto\n  finally show ?case .\nqed\n\nend (* of ring context. *)\n\n\nsubsection \\<open>Properties Within a Domain\\<close>\n\ncontext domain\nbegin\n\nlemma one_is_polynomial [intro]: \"subring K R \\<Longrightarrow> polynomial K [ \\<one> ]\"\n  unfolding polynomial_def using subringE(3) by auto\n\nlemma poly_mult_comm:\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\"\n  shows \"poly_mult p1 p2 = poly_mult p2 p1\"\nproof -\n  let ?c1 = \"coeff p1\" and ?c2 = \"coeff p2\"\n  have \"\\<And>i. (\\<Oplus>k \\<in> {..i}. ?c1 k \\<otimes> ?c2 (i - k)) = (\\<Oplus>k \\<in> {..i}. ?c2 k \\<otimes> ?c1 (i - k))\"\n  proof -\n    fix i :: nat\n    let ?f = \"\\<lambda>k. ?c1 k \\<otimes> ?c2 (i - k)\"\n    have in_carrier: \"\\<And>i. ?c1 i \\<in> carrier R\" \"\\<And>i. ?c2 i \\<in> carrier R\"\n      using coeff_in_carrier[OF assms(1)] coeff_in_carrier[OF assms(2)] by auto\n\n    have reindex_inj: \"inj_on (\\<lambda>k. i - k) {..i}\"\n      using inj_on_def by force\n    moreover have \"(\\<lambda>k. i - k) ` {..i} \\<subseteq> {..i}\" by auto\n    hence \"(\\<lambda>k. i - k) ` {..i} = {..i}\"\n      using reindex_inj endo_inj_surj[of \"{..i}\" \"\\<lambda>k. i - k\"] by simp \n    ultimately have \"(\\<Oplus>k \\<in> {..i}. ?f k) = (\\<Oplus>k \\<in> {..i}. ?f (i - k))\"\n      using add.finprod_reindex[of ?f \"\\<lambda>k. i - k\" \"{..i}\"] in_carrier by auto\n\n    moreover have \"\\<And>k. k \\<in> {..i} \\<Longrightarrow> ?f (i - k) = ?c2 k \\<otimes> ?c1 (i - k)\"\n      using in_carrier m_comm by auto\n    hence \"(\\<Oplus>k \\<in> {..i}. ?f (i - k)) = (\\<Oplus>k \\<in> {..i}. ?c2 k \\<otimes> ?c1 (i - k))\"\n      using add.finprod_cong'[of \"{..i}\" \"{..i}\"] in_carrier by auto\n    ultimately show \"(\\<Oplus>k \\<in> {..i}. ?f k) = (\\<Oplus>k \\<in> {..i}. ?c2 k \\<otimes> ?c1 (i - k))\"\n      by simp\n  qed\n  hence \"coeff (poly_mult p1 p2) = coeff (poly_mult p2 p1)\"\n    using poly_mult_coeff[OF assms] poly_mult_coeff[OF assms(2,1)] by simp\n  thus ?thesis\n    using coeff_iff_polynomial_cond[OF poly_mult_is_polynomial[OF _ assms]\n                                       poly_mult_is_polynomial[OF _ assms(2,1)]]\n          carrier_is_subring by simp\nqed\n\nlemma poly_mult_r_distr':\n  assumes \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\" \"set p3 \\<subseteq> carrier R\"\n  shows \"poly_mult p1 (poly_add p2 p3) = poly_add (poly_mult p1 p2) (poly_mult p1 p3)\"\n  unfolding poly_mult_comm[OF assms(1) poly_add_in_carrier[OF assms(2-3)]]\n            poly_mult_l_distr'[OF assms(2-3,1)] assms(2-3)[THEN poly_mult_comm[OF _ assms(1)]] ..\n\nlemma poly_mult_r_distr:\n  assumes \"subring K R\" \"polynomial K p1\" \"polynomial K p2\" \"polynomial K p3\"\n  shows \"poly_mult p1 (poly_add p2 p3) = poly_add (poly_mult p1 p2) (poly_mult p1 p3)\"\n  using poly_mult_r_distr' polynomial_in_carrier assms by auto\n\nlemma poly_mult_replicate_zero:\n  assumes \"set p \\<subseteq> carrier R\"\n  shows \"poly_mult (replicate n \\<zero>) p = []\"\n    and \"poly_mult p (replicate n \\<zero>) = []\"\nproof -\n  have in_carrier: \"\\<And>n. set (replicate n \\<zero>) \\<subseteq> carrier R\" by auto\n  show \"poly_mult (replicate n \\<zero>) p = []\" using assms\n  proof (induction n)\n    case 0 thus ?case by simp\n  next\n    case (Suc n)\n    hence \"poly_mult (replicate (Suc n) \\<zero>) p = poly_mult (\\<zero> # (replicate n \\<zero>)) p\"\n      by simp\n    also have \" ... = poly_add ((map (\\<lambda>a. \\<zero> \\<otimes> a) p) @ (replicate n \\<zero>)) []\"\n      using Suc by simp\n    also have \" ... = poly_add ((map (\\<lambda>a. \\<zero>) p) @ (replicate n \\<zero>)) []\"\n    proof -\n      have \"map ((\\<otimes>) \\<zero>) p = map (\\<lambda>a. \\<zero>) p\"\n        using Suc.prems by auto\n      then show ?thesis\n        by presburger\n    qed\n    also have \" ... = poly_add (replicate (length p + n) \\<zero>) []\"\n      by (simp add: map_replicate_const replicate_add)\n    also have \" ... = poly_add [] []\"\n      using poly_add_normalize(1)[of \"replicate (length p + n) \\<zero>\" \"[]\"]\n            normalize_replicate_zero[of \"length p + n\" \"[]\"] by auto\n    also have \" ... = []\" by simp\n    finally show ?case . \n  qed\n  thus \"poly_mult p (replicate n \\<zero>) = []\"\n    using poly_mult_comm[OF assms in_carrier] by simp\nqed\n\nlemma poly_mult_const':\n  assumes \"set p \\<subseteq> carrier R\" \"a \\<in> carrier R\"\n  shows \"poly_mult [ a ] p = normalize (map (\\<lambda>b. a \\<otimes> b) p)\"\n    and \"poly_mult p [ a ] = normalize (map (\\<lambda>b. a \\<otimes> b) p)\"\nproof -\n  have \"map2 (\\<oplus>) (map ((\\<otimes>) a) p) (replicate (length p) \\<zero>) = map ((\\<otimes>) a) p\"\n    using assms by (induction p) (auto)\n  thus \"poly_mult [ a ] p = normalize (map (\\<lambda>b. a \\<otimes> b) p)\" by simp\n  thus \"poly_mult p [ a ] = normalize (map (\\<lambda>b. a \\<otimes> b) p)\"\n    using poly_mult_comm[OF assms(1), of \"[ a ]\"] assms(2) by auto\nqed\n\nlemma poly_mult_const:\n  assumes \"subring K R\" \"polynomial K p\" \"a \\<in> K - { \\<zero> }\"\n  shows \"poly_mult [ a ] p = map (\\<lambda>b. a \\<otimes> b) p\"\n    and \"poly_mult p [ a ] = map (\\<lambda>b. a \\<otimes> b) p\"\nproof -\n  have in_carrier: \"set p \\<subseteq> carrier R\" \"a \\<in> carrier R\"\n    using polynomial_in_carrier[OF assms(1-2)] assms(3) subringE(1)[OF assms(1)] by auto\n\n  show \"poly_mult [ a ] p = map (\\<lambda>b. a \\<otimes> b) p\"\n  proof (cases p)\n    case Nil thus ?thesis\n      using poly_mult_const'(1) in_carrier by auto\n  next\n    case (Cons b q)\n    have \"lead_coeff (map (\\<lambda>b. a \\<otimes> b) p) \\<noteq> \\<zero>\"\n      using assms subringE(1)[OF assms(1)] integral[of a b] Cons lead_coeff_in_carrier by auto\n    hence \"normalize (map (\\<lambda>b. a \\<otimes> b) p) = (map (\\<lambda>b. a \\<otimes> b) p)\"\n      unfolding Cons by simp\n    thus ?thesis\n      using poly_mult_const'(1) in_carrier by auto\n  qed\n  thus \"poly_mult p [ a ] = map (\\<lambda>b. a \\<otimes> b) p\"\n    using poly_mult_comm[OF in_carrier(1)] in_carrier(2) by auto\nqed\n\nlemma poly_mult_semiassoc:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n  shows \"poly_mult (poly_mult [ a ] p) q = poly_mult [ a ] (poly_mult p q)\"\nproof -\n  let ?cp = \"coeff p\" and ?cq = \"coeff q\"\n  have \"coeff (poly_mult [ a ] p) = (\\<lambda>i. (a \\<otimes> ?cp i))\"\n    using poly_mult_const'(1)[OF assms(1,3)] normalize_coeff scalar_coeff[OF assms(3)] by simp\n\n  hence \"coeff (poly_mult (poly_mult [ a ] p) q) = (\\<lambda>i. (\\<Oplus>j \\<in> {..i}. (a \\<otimes> ?cp j) \\<otimes> ?cq (i - j)))\"\n    using poly_mult_coeff[OF poly_mult_in_carrier[OF _ assms(1)] assms(2), of \"[ a ]\"] assms(3) by auto\n  also have \" ... = (\\<lambda>i. a \\<otimes> (\\<Oplus>j \\<in> {..i}. ?cp j \\<otimes> ?cq (i - j)))\"\n  proof\n    fix i show \"(\\<Oplus>j \\<in> {..i}. (a \\<otimes> ?cp j) \\<otimes> ?cq (i - j)) = a \\<otimes> (\\<Oplus>j \\<in> {..i}. ?cp j \\<otimes> ?cq (i - j))\"\n      using finsum_rdistr[OF _ assms(3), of _ \"\\<lambda>j. ?cp j \\<otimes> ?cq (i - j)\"]\n            assms(1-2)[THEN coeff_in_carrier] by (simp add: assms(3) m_assoc)\n  qed\n  also have \" ... = coeff (poly_mult [ a ] (poly_mult p q))\"\n    unfolding poly_mult_const'(1)[OF poly_mult_in_carrier[OF assms(1-2)] assms(3)]\n    using scalar_coeff[OF assms(3), of \"poly_mult p q\"]\n          poly_mult_coeff[OF assms(1-2)] normalize_coeff by simp\n  finally have \"coeff (poly_mult (poly_mult [ a ] p) q) = coeff (poly_mult [ a ] (poly_mult p q))\" .\n  moreover have \"polynomial (carrier R) (poly_mult (poly_mult [ a ] p) q)\"\n            and \"polynomial (carrier R) (poly_mult [ a ] (poly_mult p q))\"\n    using poly_mult_is_polynomial[OF _ poly_mult_in_carrier[OF _ assms(1)] assms(2)]\n          poly_mult_is_polynomial[OF _ _ poly_mult_in_carrier[OF assms(1-2)]]\n          carrier_is_subring assms(3) by (auto simp del: poly_mult.simps)\n  ultimately show ?thesis\n    using coeff_iff_polynomial_cond by simp\nqed\n\n\ntext \\<open>Note that \"polynomial (carrier R) p\" and \"subring K p; polynomial K p\" are \"equivalent\"\n      assumptions for any lemma in ring which the result doesn't depend on K, because carrier\n      is a subring and a polynomial for a subset of the carrier is a carrier polynomial. The\n      decision between one of them should be based on how the lemma is going to be used and\n      proved. These are some tips:\n        (a) Lemmas about the algebraic structure of polynomials should use the latter option.\n        (b) Also, if the lemma deals with lots of polynomials, then the latter option is preferred.\n        (c) If the proof is going to be much easier with the first option, do not hesitate. \\<close>\n\nlemma poly_mult_monom':\n  assumes \"set p \\<subseteq> carrier R\" \"a \\<in> carrier R\"\n  shows \"poly_mult (monom a n) p = normalize ((map ((\\<otimes>) a) p) @ (replicate n \\<zero>))\"\nproof -\n  have set_map: \"set ((map ((\\<otimes>) a) p) @ (replicate n \\<zero>)) \\<subseteq> carrier R\"\n    using assms by (induct p) (auto)\n  show ?thesis\n  using poly_mult_replicate_zero(1)[OF assms(1), of n]\n        poly_add_zero'(1)[OF set_map]\n  unfolding monom_def by simp\nqed\n\nlemma poly_mult_monom:\n  assumes \"polynomial (carrier R) p\" \"a \\<in> carrier R - { \\<zero> }\"\n  shows \"poly_mult (monom a n) p =\n           (if p = [] then [] else (poly_mult [ a ] p) @ (replicate n \\<zero>))\"\nproof (cases p)\n  case Nil thus ?thesis\n    using poly_mult_zero(2)[of \"monom a n\"] assms(2) monom_def by fastforce\nnext\n  case (Cons b ps)\n  hence \"lead_coeff ((map (\\<lambda>b. a \\<otimes> b) p) @ (replicate n \\<zero>)) \\<noteq> \\<zero>\"\n    using Cons assms integral[of a b] unfolding polynomial_def by auto\n  thus ?thesis\n    using poly_mult_monom'[OF polynomial_incl[OF assms(1)], of a n] assms(2) Cons\n    unfolding poly_mult_const(1)[OF carrier_is_subring assms] by simp\nqed\n\nlemma poly_mult_one':\n  assumes \"set p \\<subseteq> carrier R\"\n  shows \"poly_mult [ \\<one> ] p = normalize p\" and \"poly_mult p [ \\<one> ] = normalize p\"\nproof -\n  have \"map2 (\\<oplus>) (map ((\\<otimes>) \\<one>) p) (replicate (length p) \\<zero>) = p\"\n    using assms by (induct p) (auto)\n  thus \"poly_mult [ \\<one> ] p = normalize p\" and \"poly_mult p [ \\<one> ] = normalize p\"\n    using poly_mult_comm[OF assms, of \"[ \\<one> ]\"] by auto\nqed\n\nlemma poly_mult_one:\n  assumes \"subring K R\" \"polynomial K p\"\n  shows \"poly_mult [ \\<one> ] p = p\" and \"poly_mult p [ \\<one> ] = p\"\n  using poly_mult_one'[OF polynomial_in_carrier[OF assms]] normalize_polynomial[OF assms(2)] by auto\n\nlemma poly_mult_lead_coeff_aux:\n  assumes \"subring K R\" \"polynomial K p1\" \"polynomial K p2\" and \"p1 \\<noteq> []\" and \"p2 \\<noteq> []\"\n  shows \"(coeff (poly_mult p1 p2)) (degree p1 + degree p2) = (lead_coeff p1) \\<otimes> (lead_coeff p2)\"\nproof -\n  have p1: \"lead_coeff p1 \\<in> carrier R - { \\<zero> }\" and p2: \"lead_coeff p2 \\<in> carrier R - { \\<zero> }\"\n    using assms(2-5) lead_coeff_in_carrier[OF assms(1)] by (metis list.collapse)+\n\n  have \"(coeff (poly_mult p1 p2)) (degree p1 + degree p2) = \n        (\\<Oplus> k \\<in> {..((degree p1) + (degree p2))}.\n          (coeff p1) k \\<otimes> (coeff p2) ((degree p1) + (degree p2) - k))\"\n    using poly_mult_coeff[OF assms(2-3)[THEN polynomial_in_carrier[OF assms(1)]]] by simp\n  also have \" ... = (lead_coeff p1) \\<otimes> (lead_coeff p2)\"\n  proof -\n    let ?f = \"\\<lambda>i. (coeff p1) i \\<otimes> (coeff p2) ((degree p1) + (degree p2) - i)\"\n    have in_carrier: \"\\<And>i. (coeff p1) i \\<in> carrier R\" \"\\<And>i. (coeff p2) i \\<in> carrier R\"\n      using coeff_in_carrier assms by auto\n    have \"\\<And>i. i < degree p1 \\<Longrightarrow> ?f i = \\<zero>\"\n      using coeff_degree[of p2] in_carrier by auto\n    moreover have \"\\<And>i. i > degree p1 \\<Longrightarrow> ?f i = \\<zero>\"\n      using coeff_degree[of p1] in_carrier by auto\n    moreover have \"?f (degree p1) = (lead_coeff p1) \\<otimes> (lead_coeff p2)\"\n      using assms(4-5) lead_coeff_simp by simp \n    ultimately have \"?f = (\\<lambda>i. if degree p1 = i then (lead_coeff p1) \\<otimes> (lead_coeff p2) else \\<zero>)\"\n      using nat_neq_iff by auto\n    thus ?thesis\n      using add.finprod_singleton[of \"degree p1\" \"{..((degree p1) + (degree p2))}\"\n                                     \"\\<lambda>i. (lead_coeff p1) \\<otimes> (lead_coeff p2)\"] p1 p2 by auto\n  qed\n  finally show ?thesis .\nqed\n\nlemma poly_mult_degree_eq:\n  assumes \"subring K R\" \"polynomial K p1\" \"polynomial K p2\"\n  shows \"degree (poly_mult p1 p2) = (if p1 = [] \\<or> p2 = [] then 0 else (degree p1) + (degree p2))\"\nproof (cases p1)\n  case Nil thus ?thesis by simp\nnext\n  case (Cons a p1') note p1 = Cons\n  show ?thesis\n  proof (cases p2)\n    case Nil thus ?thesis\n      using poly_mult_zero(2)[OF polynomial_in_carrier[OF assms(1-2)]] by simp\n  next\n    case (Cons b p2') note p2 = Cons\n    have a: \"a \\<in> carrier R\" and b: \"b \\<in> carrier R\"\n      using p1 p2 polynomial_in_carrier[OF assms(1-2)] polynomial_in_carrier[OF assms(1,3)] by auto\n    have \"(coeff (poly_mult p1 p2)) ((degree p1) + (degree p2)) = a \\<otimes> b\"\n      using poly_mult_lead_coeff_aux[OF assms] p1 p2 by simp\n    hence neq0: \"(coeff (poly_mult p1 p2)) ((degree p1) + (degree p2)) \\<noteq> \\<zero>\"\n      using assms(2-3) integral[of a b] lead_coeff_in_carrier[OF assms(1)] p1 p2 by auto  \n    moreover have eq0: \"\\<And>i. i > (degree p1) + (degree p2) \\<Longrightarrow> (coeff (poly_mult p1 p2)) i = \\<zero>\"\n    proof -\n      have aux_lemma: \"degree (poly_mult p1 p2) \\<le> (degree p1) + (degree p2)\"\n      proof (induct p1)\n        case Nil\n        then show ?case by simp\n      next\n        case (Cons a p1)\n        let ?a_p2 = \"(map (\\<lambda>b. a \\<otimes> b) p2) @ (replicate (degree (a # p1)) \\<zero>)\"\n        have \"poly_mult (a # p1) p2 = poly_add ?a_p2 (poly_mult p1 p2)\" by simp\n        hence \"degree (poly_mult (a # p1) p2) \\<le> max (degree ?a_p2) (degree (poly_mult p1 p2))\"\n          using poly_add_degree[of ?a_p2 \"poly_mult p1 p2\"] by simp\n        also have \" ... \\<le> max ((degree (a # p1)) + (degree p2)) (degree (poly_mult p1 p2))\"\n          by auto\n        also have \" ... \\<le> max ((degree (a # p1)) + (degree p2)) ((degree p1) + (degree p2))\"\n          using Cons by simp\n        also have \" ... \\<le> (degree (a # p1)) + (degree p2)\"\n          by auto\n        finally show ?case .\n      qed\n      fix i show \"i > (degree p1) + (degree p2) \\<Longrightarrow> (coeff (poly_mult p1 p2)) i = \\<zero>\"\n        using coeff_degree aux_lemma by simp\n    qed\n    moreover have \"polynomial K (poly_mult p1 p2)\"\n        by (simp add: assms poly_mult_closed)\n    ultimately have \"degree (poly_mult p1 p2) = degree p1 + degree p2\"\n      by (metis (no_types) assms(1) coeff.simps(1) coeff_degree domain.poly_mult_one(1) domain_axioms eq0 lead_coeff_simp length_greater_0_conv neq0 normalize_length_lt not_less_iff_gr_or_eq poly_mult_one'(1) polynomial_in_carrier)\n    thus ?thesis\n      using p1 p2 by auto\n  qed\nqed\n\nlemma poly_mult_integral:\n  assumes \"subring K R\" \"polynomial K p1\" \"polynomial K p2\"\n  shows \"poly_mult p1 p2 = [] \\<Longrightarrow> p1 = [] \\<or> p2 = []\"\nproof (rule ccontr)\n  assume A: \"poly_mult p1 p2 = []\" \"\\<not> (p1 = [] \\<or> p2 = [])\"\n  hence \"degree (poly_mult p1 p2) = degree p1 + degree p2\"\n    using poly_mult_degree_eq[OF assms] by simp\n  hence \"length p1 = 1 \\<and> length p2 = 1\"\n    using A Suc_diff_Suc by fastforce\n  then obtain a b where p1: \"p1 = [ a ]\" and p2: \"p2 = [ b ]\"\n    by (metis One_nat_def length_0_conv length_Suc_conv)\n  hence \"a \\<in> carrier R - { \\<zero> }\" and \"b \\<in> carrier R - { \\<zero> }\"\n    using assms lead_coeff_in_carrier by auto\n  hence \"poly_mult [ a ] [ b ] = [ a \\<otimes> b ]\"\n    using integral by auto\n  thus False using A(1) p1 p2 by simp\nqed\n\nlemma poly_mult_lead_coeff:\n  assumes \"subring K R\" \"polynomial K p1\" \"polynomial K p2\" and \"p1 \\<noteq> []\" and \"p2 \\<noteq> []\"\n  shows \"lead_coeff (poly_mult p1 p2) = (lead_coeff p1) \\<otimes> (lead_coeff p2)\"\nproof -\n  have \"poly_mult p1 p2 \\<noteq> []\"\n    using poly_mult_integral[OF assms(1-3)] assms(4-5) by auto\n  hence \"lead_coeff (poly_mult p1 p2) = (coeff (poly_mult p1 p2)) (degree p1 + degree p2)\"\n    using poly_mult_degree_eq[OF assms(1-3)] assms(4-5) by (metis coeff.simps(2) list.collapse)\n  thus ?thesis\n    using poly_mult_lead_coeff_aux[OF assms] by simp\nqed\n\nlemma poly_mult_append_zero_lcancel:\n  assumes \"subring K R\" and \"polynomial K p\" \"polynomial K q\"\n  shows \"poly_mult (p @ [ \\<zero> ]) q = r @ [ \\<zero> ] \\<Longrightarrow> poly_mult p q = r\"\nproof -\n  note in_carrier = assms(2-3)[THEN polynomial_in_carrier[OF assms(1)]]\n\n  assume pmult: \"poly_mult (p @ [ \\<zero> ]) q = r @ [ \\<zero> ]\"\n  have \"poly_mult (p @ [ \\<zero> ]) q = []\" if \"q = []\"\n    using poly_mult_zero(2)[of \"p @ [ \\<zero> ]\"] that in_carrier(1) by auto\n  moreover have \"poly_mult (p @ [ \\<zero> ]) q = []\" if \"p = []\"\n    using poly_mult_normalize[OF _ in_carrier(2), of \"p @ [ \\<zero> ]\"] poly_mult_zero[OF in_carrier(2)]\n    unfolding that by auto\n  ultimately have \"p \\<noteq> []\" and \"q \\<noteq> []\"\n    using pmult by auto\n  hence \"poly_mult p q \\<noteq> []\"\n    using poly_mult_integral[OF assms] by auto\n  hence \"normalize ((poly_mult p q) @ [ \\<zero> ]) = (poly_mult p q) @ [ \\<zero> ]\"\n    using normalize_polynomial[OF append_is_polynomial[OF assms(1) poly_mult_closed[OF assms], of \"Suc 0\"]] by auto\n  thus \"poly_mult p q = r\"\n    using poly_mult_append_zero[OF assms(2-3)[THEN polynomial_in_carrier[OF assms(1)]]] pmult by simp\nqed\n\nlemma poly_mult_append_zero_rcancel:\n  assumes \"subring K R\" and \"polynomial K p\" \"polynomial K q\"\n  shows \"poly_mult p (q @ [ \\<zero> ]) = r @ [ \\<zero> ] \\<Longrightarrow> poly_mult p q = r\"\n  using poly_mult_append_zero_lcancel[OF assms(1,3,2)]\n        poly_mult_comm[of p \"q @ [ \\<zero> ]\"] poly_mult_comm[of p q]\n        assms(2-3)[THEN polynomial_in_carrier[OF assms(1)]]\n  by auto\n\nend (* of domain context. *)\n\n\nsubsection \\<open>Algebraic Structure of Polynomials\\<close>\n\ndefinition univ_poly :: \"('a, 'b) ring_scheme \\<Rightarrow>'a set \\<Rightarrow> ('a list) ring\" (\"_ [X]\\<index>\" 80)\n  where \"univ_poly R K =\n           \\<lparr> carrier = { p. polynomial\\<^bsub>R\\<^esub> K p },\n                mult = ring.poly_mult R,\n                 one = [ \\<one>\\<^bsub>R\\<^esub> ],\n                zero = [],\n                 add = ring.poly_add R \\<rparr>\"\n\n\ntext \\<open>These lemmas allow you to unfold one field of the record at a time. \\<close>\n\nlemma univ_poly_carrier: \"polynomial\\<^bsub>R\\<^esub> K p \\<longleftrightarrow> p \\<in> carrier (K[X]\\<^bsub>R\\<^esub>)\"\n  unfolding univ_poly_def by simp\n\nlemma univ_poly_mult: \"mult (K[X]\\<^bsub>R\\<^esub>) = ring.poly_mult R\"\n  unfolding univ_poly_def by simp\n\nlemma univ_poly_one: \"one (K[X]\\<^bsub>R\\<^esub>) = [ \\<one>\\<^bsub>R\\<^esub> ]\"\n  unfolding univ_poly_def by simp\n\nlemma univ_poly_zero: \"zero (K[X]\\<^bsub>R\\<^esub>) = []\"\n  unfolding univ_poly_def by simp\n\nlemma univ_poly_add: \"add (K[X]\\<^bsub>R\\<^esub>) = ring.poly_add R\"\n  unfolding univ_poly_def by simp\n\n\n(* NEW  ========== *)\nlemma univ_poly_zero_closed [intro]: \"[] \\<in> carrier (K[X]\\<^bsub>R\\<^esub>)\"\n  unfolding sym[OF univ_poly_carrier] polynomial_def by simp\n\n\ncontext domain\nbegin\n\nlemma poly_mult_monom_assoc:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n    shows \"poly_mult (poly_mult (monom a n) p) q =\n           poly_mult (monom a n) (poly_mult p q)\"\nproof (induct n)\n  case 0 thus ?case\n    unfolding monom_def using poly_mult_semiassoc[OF assms] by (auto simp del: poly_mult.simps)\nnext\n  case (Suc n)\n  have \"poly_mult (poly_mult (monom a (Suc n)) p) q =\n        poly_mult (normalize ((poly_mult (monom a n) p) @ [ \\<zero> ])) q\"\n    using poly_mult_append_zero[OF monom_in_carrier[OF assms(3), of n] assms(1)]\n    unfolding monom_def by (auto simp del: poly_mult.simps simp add: replicate_append_same)\n  also have \" ... = normalize ((poly_mult (poly_mult (monom a n) p) q) @ [ \\<zero> ])\"\n    using poly_mult_normalize[OF _ assms(2)] poly_mult_append_zero[OF _ assms(2)]\n          poly_mult_in_carrier[OF monom_in_carrier[OF assms(3), of n] assms(1)] by auto\n  also have \" ... = normalize ((poly_mult (monom a n) (poly_mult p q)) @ [ \\<zero> ])\"\n    using Suc by simp\n  also have \" ... = poly_mult (monom a (Suc n)) (poly_mult p q)\"\n    using poly_mult_append_zero[OF monom_in_carrier[OF assms(3), of n]\n                                   poly_mult_in_carrier[OF assms(1-2)]]\n    unfolding monom_def by (simp add: replicate_append_same)\n  finally show ?case .\nqed\n\n\ncontext\n  fixes K :: \"'a set\" assumes K: \"subring K R\"\nbegin\n\nlemma univ_poly_is_monoid: \"monoid (K[X])\"\n  unfolding univ_poly_def using poly_mult_one[OF K]\nproof (auto simp add: K poly_add_closed poly_mult_closed one_is_polynomial monoid_def)\n  fix p1 p2 p3\n  let ?P = \"poly_mult (poly_mult p1 p2) p3 = poly_mult p1 (poly_mult p2 p3)\"\n\n  assume A: \"polynomial K p1\" \"polynomial K p2\" \"polynomial K p3\"\n  show ?P using polynomial_in_carrier[OF K A(1)]\n  proof (induction p1)\n    case Nil thus ?case by simp\n  next\nnext\n    case (Cons a p1) thus ?case\n    proof (cases \"a = \\<zero>\")\n      assume eq_zero: \"a = \\<zero>\"\n      have p1: \"set p1 \\<subseteq> carrier R\"\n        using Cons(2) by simp\n      have \"poly_mult (poly_mult (a # p1) p2) p3 = poly_mult (poly_mult p1 p2) p3\"\n        using poly_mult_prepend_replicate_zero[OF p1 polynomial_in_carrier[OF K A(2)], of \"Suc 0\"]\n              eq_zero by simp\n      also have \" ... = poly_mult p1 (poly_mult p2 p3)\"\n        using p1[THEN Cons(1)] by simp\n      also have \" ... = poly_mult (a # p1) (poly_mult p2 p3)\"\n        using poly_mult_prepend_replicate_zero[OF p1\n              poly_mult_in_carrier[OF A(2-3)[THEN polynomial_in_carrier[OF K]]], of \"Suc 0\"] eq_zero\n        by simp\n      finally show ?thesis .\n    next\n      assume \"a \\<noteq> \\<zero>\" hence in_carrier:\n        \"set p1 \\<subseteq> carrier R\" \"set p2 \\<subseteq> carrier R\" \"set p3 \\<subseteq> carrier R\" \"a \\<in> carrier R - { \\<zero> }\"\n        using A(2-3) polynomial_in_carrier[OF K] Cons by auto\n\n      let ?a_p2 = \"(map (\\<lambda>b. a \\<otimes> b) p2) @ (replicate (length p1) \\<zero>)\"\n      have a_p2_in_carrier: \"set ?a_p2 \\<subseteq> carrier R\"\n        using in_carrier by auto\n\n      have \"poly_mult (poly_mult (a # p1) p2) p3 = poly_mult (poly_add ?a_p2 (poly_mult p1 p2)) p3\"\n        by simp\n      also have \" ... = poly_add (poly_mult ?a_p2 p3) (poly_mult (poly_mult p1 p2) p3)\"\n        using poly_mult_l_distr'[OF a_p2_in_carrier poly_mult_in_carrier[OF in_carrier(1-2)] in_carrier(3)] .\n      also have \" ... = poly_add (poly_mult ?a_p2 p3) (poly_mult p1 (poly_mult p2 p3))\"\n        using Cons(1)[OF in_carrier(1)] by simp\n      also have \" ... = poly_add (poly_mult (normalize ?a_p2) p3) (poly_mult p1 (poly_mult p2 p3))\"\n        using poly_mult_normalize[OF a_p2_in_carrier in_carrier(3)] by simp\n      also have \" ... = poly_add (poly_mult (poly_mult (monom a (length p1)) p2) p3)\n                                 (poly_mult p1 (poly_mult p2 p3))\"\n        using poly_mult_monom'[OF in_carrier(2), of a \"length p1\"] in_carrier(4) by simp\n      also have \" ... = poly_add (poly_mult (a # (replicate (length p1) \\<zero>)) (poly_mult p2 p3))\n                                 (poly_mult p1 (poly_mult p2 p3))\"\n        using poly_mult_monom_assoc[of p2 p3 a \"length p1\"] in_carrier unfolding monom_def by simp\n      also have \" ... = poly_mult (poly_add (a # (replicate (length p1) \\<zero>)) p1) (poly_mult p2 p3)\"\n        using poly_mult_l_distr'[of \"a # (replicate (length p1) \\<zero>)\" p1 \"poly_mult p2 p3\"]\n              poly_mult_in_carrier[OF in_carrier(2-3)] in_carrier by force\n      also have \" ... = poly_mult (a # p1) (poly_mult p2 p3)\"\n        using poly_add_monom[OF in_carrier(1) in_carrier(4)] unfolding monom_def by simp\n      finally show ?thesis .\n    qed\n  qed\nqed\n\ndeclare poly_add.simps[simp del]\n\nlemma univ_poly_is_abelian_monoid: \"abelian_monoid (K[X])\"\n  unfolding univ_poly_def\n  using poly_add_closed poly_add_zero zero_is_polynomial K\nproof (auto simp add: abelian_monoid_def comm_monoid_def monoid_def comm_monoid_axioms_def)\n  fix p1 p2 p3\n  let ?c = \"\\<lambda>p. coeff p\"\n  assume A: \"polynomial K p1\" \"polynomial K p2\" \"polynomial K p3\"\n  hence\n    p1: \"\\<And>i. (?c p1) i \\<in> carrier R\" \"set p1 \\<subseteq> carrier R\" and\n    p2: \"\\<And>i. (?c p2) i \\<in> carrier R\" \"set p2 \\<subseteq> carrier R\" and\n    p3: \"\\<And>i. (?c p3) i \\<in> carrier R\" \"set p3 \\<subseteq> carrier R\"\n    using A[THEN polynomial_in_carrier[OF K]] coeff_in_carrier by auto\n  have \"?c (poly_add (poly_add p1 p2) p3) = (\\<lambda>i. (?c p1 i \\<oplus> ?c p2 i) \\<oplus> (?c p3 i))\"\n    using poly_add_coeff[OF poly_add_in_carrier[OF p1(2) p2(2)] p3(2)]\n          poly_add_coeff[OF p1(2) p2(2)] by simp\n  also have \" ... = (\\<lambda>i. (?c p1 i) \\<oplus> ((?c p2 i) \\<oplus> (?c p3 i)))\"\n    using p1 p2 p3 add.m_assoc by simp\n  also have \" ... = ?c (poly_add p1 (poly_add p2 p3))\"\n    using poly_add_coeff[OF p1(2) poly_add_in_carrier[OF p2(2) p3(2)]]\n          poly_add_coeff[OF p2(2) p3(2)] by simp\n  finally have \"?c (poly_add (poly_add p1 p2) p3) = ?c (poly_add p1 (poly_add p2 p3))\" .\n  thus \"poly_add (poly_add p1 p2) p3 = poly_add p1 (poly_add p2 p3)\"\n    using coeff_iff_polynomial_cond poly_add_closed[OF K] A by meson\n  show \"poly_add p1 p2 = poly_add p2 p1\"\n    using poly_add_comm[OF p1(2) p2(2)] .\nqed\n\nlemma univ_poly_is_abelian_group: \"abelian_group (K[X])\"\nproof -\n  interpret abelian_monoid \"K[X]\"\n    using univ_poly_is_abelian_monoid .\n  show ?thesis\n  proof (unfold_locales)\n    show \"carrier (add_monoid (K[X])) \\<subseteq> Units (add_monoid (K[X]))\"\n      unfolding univ_poly_def Units_def\n    proof (auto)\n      fix p assume p: \"polynomial K p\"\n      have \"polynomial K [ \\<ominus> \\<one> ]\"\n        unfolding polynomial_def using r_neg subringE(3,5)[OF K] by force\n      hence cond0: \"polynomial K (poly_mult [ \\<ominus> \\<one> ] p)\"\n        using poly_mult_closed[OF K, of \"[ \\<ominus> \\<one> ]\" p] p by simp\n      \n      have \"poly_add p (poly_mult [ \\<ominus> \\<one> ] p) = poly_add (poly_mult [ \\<one> ] p) (poly_mult [ \\<ominus> \\<one> ] p)\"\n        using poly_mult_one[OF K p] by simp\n      also have \" ... = poly_mult (poly_add [ \\<one> ] [ \\<ominus> \\<one> ]) p\"\n        using poly_mult_l_distr' polynomial_in_carrier[OF K p] by auto\n      also have \" ... = poly_mult [] p\"\n        using poly_add.simps[of \"[ \\<one> ]\" \"[ \\<ominus> \\<one> ]\"]\n        by (simp add: case_prod_unfold r_neg)\n      also have \" ... = []\" by simp\n      finally have cond1: \"poly_add p (poly_mult [ \\<ominus> \\<one> ] p) = []\" .\n\n      have \"poly_add (poly_mult [ \\<ominus> \\<one> ] p) p = poly_add (poly_mult [ \\<ominus> \\<one> ] p) (poly_mult [ \\<one> ] p)\"\n        using poly_mult_one[OF K p] by simp\n      also have \" ... = poly_mult (poly_add [ \\<ominus>  \\<one> ] [ \\<one> ]) p\"\n        using poly_mult_l_distr' polynomial_in_carrier[OF K p] by auto\n      also have \" ... = poly_mult [] p\"\n        using \\<open>poly_mult (poly_add [\\<one>] [\\<ominus> \\<one>]) p = poly_mult [] p\\<close> poly_add_comm by auto\n      also have \" ... = []\" by simp\n      finally have cond2: \"poly_add (poly_mult [ \\<ominus> \\<one> ] p) p = []\" .\n\n      from cond0 cond1 cond2 show \"\\<exists>q. polynomial K q \\<and> poly_add q p = [] \\<and> poly_add p q = []\"\n        by auto\n    qed\n  qed\nqed\n\nlemma univ_poly_is_ring: \"ring (K[X])\"\nproof -\n  interpret UP: abelian_group \"K[X]\" + monoid \"K[X]\"\n    using univ_poly_is_abelian_group univ_poly_is_monoid .\n  show ?thesis\n    by (unfold_locales)\n       (auto simp add: univ_poly_def poly_mult_r_distr[OF K] poly_mult_l_distr[OF K])\nqed\n\nlemma univ_poly_is_cring: \"cring (K[X])\"\nproof -\n  interpret UP: ring \"K[X]\"\n    using univ_poly_is_ring .\n  have \"\\<And>p q. \\<lbrakk> p \\<in> carrier (K[X]); q \\<in> carrier (K[X]) \\<rbrakk> \\<Longrightarrow> p \\<otimes>\\<^bsub>K[X]\\<^esub> q = q \\<otimes>\\<^bsub>K[X]\\<^esub> p\"\n    unfolding univ_poly_def using poly_mult_comm polynomial_in_carrier[OF K] by auto\n  thus ?thesis\n    by unfold_locales auto\nqed\n\nlemma univ_poly_is_domain: \"domain (K[X])\"\nproof -\n  interpret UP: cring \"K[X]\"\n    using univ_poly_is_cring .\n  show ?thesis\n    by (unfold_locales, auto simp add: univ_poly_def poly_mult_integral[OF K])\nqed\n\ndeclare poly_add.simps[simp]\n\nlemma univ_poly_a_inv_def':\n  assumes \"p \\<in> carrier (K[X])\" shows \"\\<ominus>\\<^bsub>K[X]\\<^esub> p = map (\\<lambda>a. \\<ominus> a) p\"\nproof -\n  have aux_lemma:\n    \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> p \\<oplus>\\<^bsub>K[X]\\<^esub> (map (\\<lambda>a. \\<ominus> a) p) = []\"\n    \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> (map (\\<lambda>a. \\<ominus> a) p) \\<in> carrier (K[X])\"\n  proof -\n    fix p assume p: \"p \\<in> carrier (K[X])\"\n    hence set_p: \"set p \\<subseteq> K\"\n      unfolding univ_poly_def using polynomial_incl by auto\n    show \"(map (\\<lambda>a. \\<ominus> a) p) \\<in> carrier (K[X])\"\n    proof (cases \"p = []\")\n      assume \"p = []\" thus ?thesis\n        unfolding univ_poly_def polynomial_def by auto\n    next\n      assume not_nil: \"p \\<noteq> []\"\n      hence \"lead_coeff p \\<noteq> \\<zero>\"\n        using p unfolding univ_poly_def polynomial_def by auto\n      moreover have \"lead_coeff (map (\\<lambda>a. \\<ominus> a) p) = \\<ominus> (lead_coeff p)\"\n        using not_nil by (simp add: hd_map)\n      ultimately have \"lead_coeff (map (\\<lambda>a. \\<ominus> a) p) \\<noteq> \\<zero>\"\n        using hd_in_set local.minus_zero not_nil set_p subringE(1)[OF K] by force\n      moreover have \"set (map (\\<lambda>a. \\<ominus> a) p) \\<subseteq> K\"\n        using set_p subringE(5)[OF K] by (induct p) (auto)\n      ultimately show ?thesis\n        unfolding univ_poly_def polynomial_def by simp\n    qed\n\n    have \"map2 (\\<oplus>) p (map (\\<lambda>a. \\<ominus> a) p) = replicate (length p) \\<zero>\"\n      using set_p subringE(1)[OF K] by (induct p) (auto simp add: r_neg)\n    thus \"p \\<oplus>\\<^bsub>K[X]\\<^esub> (map (\\<lambda>a. \\<ominus> a) p) = []\"\n      unfolding univ_poly_def using normalize_replicate_zero[of \"length p\" \"[]\"] by auto\n  qed\n\n  interpret UP: ring \"K[X]\"\n    using univ_poly_is_ring .\n\n  from aux_lemma\n  have \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> \\<ominus>\\<^bsub>K[X]\\<^esub> p = map (\\<lambda>a. \\<ominus> a) p\"\n    by (metis Nil_is_map_conv UP.add.inv_closed UP.l_zero UP.r_neg1 UP.r_zero UP.zero_closed)\n  thus ?thesis\n    using assms by simp\nqed\n\n(* NEW ========== *)\ncorollary univ_poly_a_inv_length:\n  assumes \"p \\<in> carrier (K[X])\" shows \"length (\\<ominus>\\<^bsub>K[X]\\<^esub> p) = length p\"\n  unfolding univ_poly_a_inv_def'[OF assms] by simp\n\n(* NEW ========== *)\ncorollary univ_poly_a_inv_degree:\n  assumes \"p \\<in> carrier (K[X])\" shows \"degree (\\<ominus>\\<^bsub>K[X]\\<^esub> p) = degree p\"\n  using univ_poly_a_inv_length[OF assms] by simp\n\n\nsubsection \\<open>Long Division Theorem\\<close>\n\nlemma long_division_theorem:\n  assumes \"polynomial K p\" and \"polynomial K b\" \"b \\<noteq> []\"\n     and \"lead_coeff b \\<in> Units (R \\<lparr> carrier := K \\<rparr>)\"\n  shows \"\\<exists>q r. polynomial K q \\<and> polynomial K r \\<and>\n               p = (b \\<otimes>\\<^bsub>K[X]\\<^esub> q) \\<oplus>\\<^bsub>K[X]\\<^esub> r \\<and> (r = [] \\<or> degree r < degree b)\"\n    (is \"\\<exists>q r. ?long_division p q r\")\n  using assms(1)\nproof (induct \"length p\" arbitrary: p rule: less_induct)\n  case less thus ?case\n  proof (cases p)\n    case Nil\n    hence \"?long_division p [] []\"\n      using zero_is_polynomial poly_mult_zero[OF polynomial_in_carrier[OF K assms(2)]]\n      by (simp add: univ_poly_def)\n    thus ?thesis by blast\n  next\n    case (Cons a p') thus ?thesis\n    proof (cases \"length b > length p\")\n      assume \"length b > length p\"\n      hence \"p = [] \\<or> degree p < degree b\"\n        by (meson diff_less_mono length_0_conv less_one not_le) \n      hence \"?long_division p [] p\"\n        using poly_mult_zero(2)[OF polynomial_in_carrier[OF K assms(2)]]\n              poly_add_zero(2)[OF K less(2)] zero_is_polynomial less(2)\n        by (simp add: univ_poly_def)\n      thus ?thesis by blast\n    next\n      interpret UP: cring \"K[X]\"\n        using univ_poly_is_cring .\n\n      assume \"\\<not> length b > length p\"\n      hence len_ge: \"length p \\<ge> length b\" by simp\n      obtain c b' where b: \"b = c # b'\"\n        using assms(3) list.exhaust_sel by blast\n      then obtain c' where c': \"c' \\<in> carrier R\" \"c' \\<in> K\" \"c' \\<otimes> c = \\<one>\" \"c \\<otimes> c' = \\<one>\"\n        using assms(4) subringE(1)[OF K] unfolding Units_def by auto\n      have c: \"c \\<in> carrier R\" \"c \\<in> K\" \"c \\<noteq> \\<zero>\" and a: \"a \\<in> carrier R\" \"a \\<in> K\" \"a \\<noteq> \\<zero>\"\n        using less(2) assms(2) lead_coeff_not_zero subringE(1)[OF K] b Cons by auto\n      hence lc: \"c' \\<otimes> (\\<ominus> a) \\<in> K - { \\<zero> }\"\n        using subringE(5-6)[OF K] c' add.inv_solve_right integral_iff by fastforce\n\n      let ?len = \"length\"\n      define s where \"s = monom (c' \\<otimes> (\\<ominus> a)) (?len p - ?len b)\"\n      hence s: \"polynomial K s\" \"s \\<noteq> []\" \"degree s = ?len p - ?len b\" \"length s \\<ge> 1\"\n        using monom_is_polynomial[OF K lc] unfolding monom_def by auto\n      hence is_polynomial: \"polynomial K (p \\<oplus>\\<^bsub>K[X]\\<^esub> (b \\<otimes>\\<^bsub>K[X]\\<^esub> s))\"\n        using poly_add_closed[OF K less(2) poly_mult_closed[OF K assms(2), of s]]\n        by (simp add: univ_poly_def)\n\n      have \"lead_coeff (b \\<otimes>\\<^bsub>K[X]\\<^esub> s) = \\<ominus> a\"\n        using poly_mult_lead_coeff[OF K assms(2) s(1) assms(3) s(2)] c c' a\n        unfolding b s_def monom_def univ_poly_def by (auto simp del: poly_mult.simps, algebra)\n      then obtain s' where s': \"b \\<otimes>\\<^bsub>K[X]\\<^esub> s = (\\<ominus> a) # s'\"\n        using poly_mult_integral[OF K assms(2) s(1)] assms(2-3) s(2)\n        by (simp add: univ_poly_def, metis hd_Cons_tl)\n      moreover have \"degree p = degree (b \\<otimes>\\<^bsub>K[X]\\<^esub> s)\"\n        using poly_mult_degree_eq[OF K assms(2) s(1)] assms(3) s(2-4) len_ge b Cons\n        by (auto simp add: univ_poly_def)\n      hence \"?len p = ?len (b \\<otimes>\\<^bsub>K[X]\\<^esub> s)\"\n        unfolding Cons s' by simp\n      hence \"?len (p \\<oplus>\\<^bsub>K[X]\\<^esub> (b \\<otimes>\\<^bsub>K[X]\\<^esub> s)) < ?len p\"\n        unfolding Cons s' using a normalize_length_le[of \"map2 (\\<oplus>) p' s'\"]\n        by (auto simp add: univ_poly_def r_neg)\n      then obtain q' r' where l_div: \"?long_division (p \\<oplus>\\<^bsub>K[X]\\<^esub> (b \\<otimes>\\<^bsub>K[X]\\<^esub> s)) q' r'\"\n        using less(1)[OF _ is_polynomial] by blast\n\n      have in_carrier:\n         \"p \\<in> carrier (K[X])\"  \"b \\<in> carrier (K[X])\" \"s \\<in> carrier (K[X])\"\n        \"q' \\<in> carrier (K[X])\" \"r' \\<in> carrier (K[X])\"\n        using l_div assms less(2) s unfolding univ_poly_def by auto\n      have \"(p \\<oplus>\\<^bsub>K[X]\\<^esub> (b \\<otimes>\\<^bsub>K[X]\\<^esub> s)) \\<ominus>\\<^bsub>K[X]\\<^esub> (b \\<otimes>\\<^bsub>K[X]\\<^esub> s) =\n          ((b \\<otimes>\\<^bsub>K[X]\\<^esub> q') \\<oplus>\\<^bsub>K[X]\\<^esub> r') \\<ominus>\\<^bsub>K[X]\\<^esub> (b \\<otimes>\\<^bsub>K[X]\\<^esub> s)\"\n        using l_div by simp\n      hence \"p = (b \\<otimes>\\<^bsub>K[X]\\<^esub> (q' \\<ominus>\\<^bsub>K[X]\\<^esub> s)) \\<oplus>\\<^bsub>K[X]\\<^esub> r'\"\n        using in_carrier by algebra\n      moreover have \"q' \\<ominus>\\<^bsub>K[X]\\<^esub> s \\<in> carrier (K[X])\"\n        using in_carrier by algebra\n      hence \"polynomial K (q' \\<ominus>\\<^bsub>K[X]\\<^esub> s)\"\n        unfolding univ_poly_def by simp\n      ultimately have \"?long_division p (q' \\<ominus>\\<^bsub>K[X]\\<^esub> s) r'\"\n        using l_div by auto\n      thus ?thesis by blast\n    qed\n  qed\nqed\n\nend (* of fixed K context. *)\n\nend (* of domain context. *)\n\n(* PROOF ========== *)\nlemma (in domain) field_long_division_theorem:\n  assumes \"subfield K R\" \"polynomial K p\" and \"polynomial K b\" \"b \\<noteq> []\"\n  shows \"\\<exists>q r. polynomial K q \\<and> polynomial K r \\<and>\n               p = (b \\<otimes>\\<^bsub>K[X]\\<^esub> q) \\<oplus>\\<^bsub>K[X]\\<^esub> r \\<and> (r = [] \\<or> degree r < degree b)\"\n  using long_division_theorem[OF subfieldE(1)[OF assms(1)] assms(2-4)] assms(3-4)\n        subfield.subfield_Units[OF assms(1)] lead_coeff_not_zero[of K \"hd b\" \"tl b\"]\n  by simp\n\n(* PROOF ========== *)\ntext \\<open>The same theorem as above, but now, everything is in a shell. \\<close>\nlemma (in domain) field_long_division_theorem_shell:\n  assumes \"subfield K R\" \"p \\<in> carrier (K[X])\" and \"b \\<in> carrier (K[X])\" \"b \\<noteq> \\<zero>\\<^bsub>K[X]\\<^esub>\"\n  shows \"\\<exists>q r. q \\<in> carrier (K[X]) \\<and> r \\<in> carrier (K[X]) \\<and>\n               p = (b \\<otimes>\\<^bsub>K[X]\\<^esub> q) \\<oplus>\\<^bsub>K[X]\\<^esub> r \\<and> (r = \\<zero>\\<^bsub>K[X]\\<^esub> \\<or> degree r < degree b)\"\n  using field_long_division_theorem assms by (auto simp add: univ_poly_def)\n\n\nsubsection \\<open>Consistency Rules\\<close>\n\nlemma polynomial_consistent [simp]:\n  shows \"polynomial\\<^bsub>(R \\<lparr> carrier := K \\<rparr>)\\<^esub> K p \\<Longrightarrow> polynomial\\<^bsub>R\\<^esub> K p\"\n  unfolding polynomial_def by auto\n\nlemma (in ring) eval_consistent [simp]:\n  assumes \"subring K R\" shows \"ring.eval (R \\<lparr> carrier := K \\<rparr>) = eval\"\nproof\n  fix p show \"ring.eval (R \\<lparr> carrier := K \\<rparr>) p = eval p\"\n    using nat_pow_consistent ring.eval.simps[OF subring_is_ring[OF assms]] by (induct p) (auto)\nqed\n\nlemma (in ring) coeff_consistent [simp]:\n  assumes \"subring K R\" shows \"ring.coeff (R \\<lparr> carrier := K \\<rparr>) = coeff\"\nproof\n  fix p show \"ring.coeff (R \\<lparr> carrier := K \\<rparr>) p = coeff p\"\n    using ring.coeff.simps[OF subring_is_ring[OF assms]] by (induct p) (auto)\nqed\n\nlemma (in ring) normalize_consistent [simp]:\n  assumes \"subring K R\" shows \"ring.normalize (R \\<lparr> carrier := K \\<rparr>) = normalize\"\nproof\n  fix p show \"ring.normalize (R \\<lparr> carrier := K \\<rparr>) p = normalize p\"\n    using ring.normalize.simps[OF subring_is_ring[OF assms]] by (induct p) (auto)\nqed\n\nlemma (in ring) poly_add_consistent [simp]:\n  assumes \"subring K R\" shows \"ring.poly_add (R \\<lparr> carrier := K \\<rparr>) = poly_add\" \nproof -\n  have \"\\<And>p q. ring.poly_add (R \\<lparr> carrier := K \\<rparr>) p q = poly_add p q\"\n  proof -\n    fix p q show \"ring.poly_add (R \\<lparr> carrier := K \\<rparr>) p q = poly_add p q\"\n    using ring.poly_add.simps[OF subring_is_ring[OF assms]] normalize_consistent[OF assms] by auto\n  qed\n  thus ?thesis by (auto simp del: poly_add.simps)\nqed\n\nlemma (in ring) poly_mult_consistent [simp]:\n  assumes \"subring K R\" shows \"ring.poly_mult (R \\<lparr> carrier := K \\<rparr>) = poly_mult\"\nproof -\n  have \"\\<And>p q. ring.poly_mult (R \\<lparr> carrier := K \\<rparr>) p q = poly_mult p q\"\n  proof - \n    fix p q show \"ring.poly_mult (R \\<lparr> carrier := K \\<rparr>) p q = poly_mult p q\"\n      using ring.poly_mult.simps[OF subring_is_ring[OF assms]] poly_add_consistent[OF assms]\n      by (induct p) (auto)\n  qed\n  thus ?thesis by auto\nqed\n\nlemma (in domain) univ_poly_a_inv_consistent:\n  assumes \"subring K R\" \"p \\<in> carrier (K[X])\"\n  shows \"\\<ominus>\\<^bsub>K[X]\\<^esub> p = \\<ominus>\\<^bsub>(carrier R)[X]\\<^esub> p\"\nproof -\n  have in_carrier: \"p \\<in> carrier ((carrier R)[X])\"\n    using assms carrier_polynomial by (auto simp add: univ_poly_def)\n  show ?thesis\n    using univ_poly_a_inv_def'[OF assms]\n          univ_poly_a_inv_def'[OF carrier_is_subring in_carrier] by simp\nqed\n\nlemma (in domain) univ_poly_a_minus_consistent:\n  assumes \"subring K R\" \"q \\<in> carrier (K[X])\"\n  shows \"p \\<ominus>\\<^bsub>K[X]\\<^esub> q = p \\<ominus>\\<^bsub>(carrier R)[X]\\<^esub> q\"\n  using univ_poly_a_inv_consistent[OF assms]\n  unfolding a_minus_def univ_poly_def by auto\n\nlemma (in ring) univ_poly_consistent:\n  assumes \"subring K R\"\n  shows \"univ_poly (R \\<lparr> carrier := K \\<rparr>) = univ_poly R\"\n  unfolding univ_poly_def polynomial_def\n  using poly_add_consistent[OF assms]\n        poly_mult_consistent[OF assms]\n        subringE(1)[OF assms]\n  by auto\n\n\nsubsubsection \\<open>Corollaries\\<close>\n\n(* PROOF ========== *)\ncorollary (in ring) subfield_long_division_theorem_shell:\n  assumes \"subfield K R\" \"p \\<in> carrier (K[X])\" and \"b \\<in> carrier (K[X])\" \"b \\<noteq> \\<zero>\\<^bsub>K[X]\\<^esub>\"\n  shows \"\\<exists>q r. q \\<in> carrier (K[X]) \\<and> r \\<in> carrier (K[X]) \\<and>\n               p = (b \\<otimes>\\<^bsub>K[X]\\<^esub> q) \\<oplus>\\<^bsub>K[X]\\<^esub> r \\<and> (r = \\<zero>\\<^bsub>K[X]\\<^esub> \\<or> degree r < degree b)\"\n  using domain.field_long_division_theorem_shell[OF subdomain_is_domain[OF subfield.axioms(1)]\n        field.carrier_is_subfield[OF subfield_iff(2)[OF assms(1)]]] assms(1-4)\n  unfolding univ_poly_consistent[OF subfieldE(1)[OF assms(1)]]\n  by auto\n\ncorollary (in domain) univ_poly_is_euclidean:\n  assumes \"subfield K R\" shows \"euclidean_domain (K[X]) degree\"\nproof -\n  interpret UP: domain \"K[X]\"\n    using univ_poly_is_domain[OF subfieldE(1)[OF assms]] field_def by blast\n  show ?thesis\n    using subfield_long_division_theorem_shell[OF assms]\n    by (auto intro!: UP.euclidean_domainI)\nqed\n\ncorollary (in domain) univ_poly_is_principal:\n  assumes \"subfield K R\" shows \"principal_domain (K[X])\"\nproof -\n  interpret UP: euclidean_domain \"K[X]\" degree\n    using univ_poly_is_euclidean[OF assms] .\n  show ?thesis ..\nqed\n\n\nsubsection \\<open>The Evaluation Homomorphism\\<close>\n\nlemma (in ring) eval_replicate:\n  assumes \"set p \\<subseteq> carrier R\" \"a \\<in> carrier R\"\n  shows \"eval ((replicate n \\<zero>) @ p) a = eval p a\"\n  using assms eval_in_carrier by (induct n) (auto)\n\nlemma (in ring) eval_normalize:\n  assumes \"set p \\<subseteq> carrier R\" \"a \\<in> carrier R\"\n  shows \"eval (normalize p) a = eval p a\"\n  using eval_replicate[OF normalize_in_carrier] normalize_def'[of p] assms by metis\n\nlemma (in ring) eval_poly_add_aux:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" and \"length p = length q\" and \"a \\<in> carrier R\"\n  shows \"eval (poly_add p q) a = (eval p a) \\<oplus> (eval q a)\"\nproof -\n  have \"eval (map2 (\\<oplus>) p q) a = (eval p a) \\<oplus> (eval q a)\"\n    using assms\n  proof (induct p arbitrary: q)\n    case Nil thus ?case by simp\n  next\n    case (Cons b1 p')\n    then obtain b2 q' where q: \"q = b2 # q'\"\n      by (metis length_Cons list.exhaust list.size(3) nat.simps(3))\n    show ?case\n      using eval_in_carrier[OF _ Cons(5), of q']\n            eval_in_carrier[OF _ Cons(5), of p'] Cons unfolding q\n      by (auto simp add: ring_simprules(7,13,22))\n  qed\n  moreover have \"set (map2 (\\<oplus>) p q) \\<subseteq> carrier R\"\n    using assms(1-2)\n    by (induct p arbitrary: q) (auto, metis add.m_closed in_set_zipE set_ConsD subsetCE)\n  ultimately show ?thesis\n    using assms(3) eval_normalize[OF _ assms(4), of \"map2 (\\<oplus>) p q\"] by auto\nqed\n\nlemma (in ring) eval_poly_add:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n  shows \"eval (poly_add p q) a = (eval p a) \\<oplus> (eval q a)\"\nproof -\n  { fix p q assume A: \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" \"length p \\<ge> length q\"\n    hence \"eval (poly_add p ((replicate (length p - length q) \\<zero>) @ q)) a =\n         (eval p a) \\<oplus> (eval ((replicate (length p - length q) \\<zero>) @ q) a)\"\n      using eval_poly_add_aux[OF A(1) _ _ assms(3), of \"(replicate (length p - length q) \\<zero>) @ q\"] by force\n    hence \"eval (poly_add p q) a = (eval p a) \\<oplus> (eval q a)\"\n      using eval_replicate[OF A(2) assms(3)] A(3) by auto }\n  note aux_lemma = this\n\n  have ?thesis if \"length q \\<ge> length p\"\n    using assms(1-2)[THEN eval_in_carrier[OF _ assms(3)]] poly_add_comm[OF assms(1-2)]\n          aux_lemma[OF assms(2,1) that]\n    by (auto simp del: poly_add.simps simp add: add.m_comm)\n  moreover have ?thesis if \"length p \\<ge> length q\"\n    using aux_lemma[OF assms(1-2) that] .\n  ultimately show ?thesis by auto\nqed\n\nlemma (in ring) eval_append_aux:\n  assumes \"set p \\<subseteq> carrier R\" and \"b \\<in> carrier R\" and \"a \\<in> carrier R\"\n  shows \"eval (p @ [ b ]) a = ((eval p a) \\<otimes> a) \\<oplus> b\"\n  using assms(1)\nproof (induct p)\n  case Nil thus ?case by (auto simp add: assms(2-3))\nnext\n  case (Cons l q)\n  have \"a [^] length q \\<in> carrier R\" \"eval q a \\<in> carrier R\"\n    using eval_in_carrier Cons(2) assms(2-3) by auto\n  thus ?case\n    using Cons assms(2-3) by (auto, algebra)\nqed\n\nlemma (in ring) eval_append:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n  shows \"eval (p @ q) a = ((eval p a) \\<otimes> (a [^] (length q))) \\<oplus> (eval q a)\"\n  using assms(2)\nproof (induct \"length q\" arbitrary: q)\n  case 0 thus ?case\n    using eval_in_carrier[OF assms(1,3)] by auto\nnext\n  case (Suc n)\n  then obtain b q' where q: \"q = q' @ [ b ]\"\n    by (metis length_Suc_conv list.simps(3) rev_exhaust)\n  hence in_carrier: \"eval p a \\<in> carrier R\" \"eval q' a \\<in> carrier R\"\n                    \"a [^] (length q') \\<in> carrier R\" \"b \\<in> carrier R\"\n    using assms(1,3) Suc(3) eval_in_carrier[OF _ assms(3)] by auto\n\n  have \"eval (p @ q) a = ((eval (p @ q') a) \\<otimes> a) \\<oplus> b\"\n    using eval_append_aux[OF _ _ assms(3), of \"p @ q'\" b] assms(1) Suc(3) unfolding q by auto\n  also have \" ... = ((((eval p a) \\<otimes> (a [^] (length q'))) \\<oplus> (eval q' a)) \\<otimes> a) \\<oplus> b\"\n    using Suc unfolding q by auto\n  also have \" ... = (((eval p a) \\<otimes> ((a [^] (length q')) \\<otimes> a))) \\<oplus> (((eval q' a) \\<otimes> a) \\<oplus> b)\"\n    using assms(3) in_carrier by algebra\n  also have \" ... = (eval p a) \\<otimes> (a [^] (length q)) \\<oplus> (eval q a)\"\n    using eval_append_aux[OF _ in_carrier(4) assms(3), of q'] Suc(3) unfolding q by auto\n  finally show ?case .\nqed\n\nlemma (in ring) eval_monom:\n  assumes \"b \\<in> carrier R\" and \"a \\<in> carrier R\"\n  shows \"eval (monom b n) a = b \\<otimes> (a [^] n)\"\nproof (induct n)\n  case 0 thus ?case\n    using assms unfolding monom_def by auto\nnext\n  case (Suc n)\n  have \"monom b (Suc n) = (monom b n) @ [ \\<zero> ]\"\n    unfolding monom_def by (simp add: replicate_append_same)\n  hence \"eval (monom b (Suc n)) a = ((eval (monom b n) a) \\<otimes> a) \\<oplus> \\<zero>\"\n    using eval_append_aux[OF monom_in_carrier[OF assms(1)] zero_closed assms(2), of n] by simp\n  also have \" ... =  b \\<otimes> (a [^] (Suc n))\"\n    using Suc assms m_assoc by auto\n  finally show ?case .\nqed\n\nlemma (in cring) eval_poly_mult:\n  assumes \"set p \\<subseteq> carrier R\" \"set q \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n  shows \"eval (poly_mult p q) a = (eval p a) \\<otimes> (eval q a)\"\n  using assms(1)\nproof (induct p)\n  case Nil thus ?case\n    using eval_in_carrier[OF assms(2-3)] by simp\nnext\n  { fix n b assume b: \"b \\<in> carrier R\"\n    hence \"set (map ((\\<otimes>) b) q) \\<subseteq> carrier R\" and \"set (replicate n \\<zero>) \\<subseteq> carrier R\"\n      using assms(2) by (induct q) (auto)\n    hence \"eval ((map ((\\<otimes>) b) q) @ (replicate n \\<zero>)) a = (eval ((map ((\\<otimes>) b) q)) a) \\<otimes> (a [^] n) \\<oplus> \\<zero>\"\n      using eval_append[OF _ _ assms(3), of \"map ((\\<otimes>) b) q\" \"replicate n \\<zero>\"] \n            eval_replicate[OF _ assms(3), of \"[]\"] by auto\n    moreover have \"eval (map ((\\<otimes>) b) q) a = b \\<otimes> eval q a\"\n      using assms(2-3) eval_in_carrier b by(induct q) (auto simp add: m_assoc r_distr)\n    ultimately have \"eval ((map ((\\<otimes>) b) q) @ (replicate n \\<zero>)) a = (b \\<otimes> eval q a) \\<otimes> (a [^] n) \\<oplus> \\<zero>\"\n      by simp\n    also have \" ... = (b \\<otimes> (a [^] n)) \\<otimes> (eval q a)\"\n      using eval_in_carrier[OF assms(2-3)] b assms(3) m_assoc m_comm by auto\n    finally have \"eval ((map ((\\<otimes>) b) q) @ (replicate n \\<zero>)) a = (eval (monom b n) a) \\<otimes> (eval q a)\"\n      using eval_monom[OF b assms(3)] by simp }\n  note aux_lemma = this\n\n  case (Cons b p)\n  hence in_carrier:\n    \"eval (monom b (length p)) a \\<in> carrier R\" \"eval p a \\<in> carrier R\" \"eval q a \\<in> carrier R\" \"b \\<in> carrier R\"\n    using eval_in_carrier monom_in_carrier assms by auto\n  have set_map: \"set ((map ((\\<otimes>) b) q) @ (replicate (length p) \\<zero>)) \\<subseteq> carrier R\"\n    using in_carrier(4) assms(2) by (induct q) (auto)\n  have set_poly: \"set (poly_mult p q) \\<subseteq> carrier R\"\n    using poly_mult_in_carrier[OF _ assms(2), of p] Cons(2) by auto\n  have \"eval (poly_mult (b # p) q) a =\n      ((eval (monom b (length p)) a) \\<otimes> (eval q a)) \\<oplus> ((eval p a) \\<otimes> (eval q a))\"\n    using eval_poly_add[OF set_map set_poly assms(3)] aux_lemma[OF in_carrier(4), of \"length p\"] Cons\n    by (auto simp del: poly_add.simps)\n  also have \" ... = ((eval (monom b (length p)) a) \\<oplus> (eval p a)) \\<otimes> (eval q a)\"\n    using l_distr[OF in_carrier(1-3)] by simp\n  also have \" ... = (eval (b # p) a) \\<otimes> (eval q a)\"\n    unfolding eval_monom[OF in_carrier(4) assms(3), of \"length p\"] by auto\n  finally show ?case .\nqed\n\nproposition (in cring) eval_is_hom:\n  assumes \"subring K R\" and \"a \\<in> carrier R\"\n  shows \"(\\<lambda>p. (eval p) a) \\<in> ring_hom (K[X]) R\"\n  unfolding univ_poly_def\n  using polynomial_in_carrier[OF assms(1)] eval_in_carrier\n        eval_poly_add eval_poly_mult assms(2)\n  by (auto intro!: ring_hom_memI\n         simp add: univ_poly_carrier\n         simp del: poly_add.simps poly_mult.simps)\n\ntheorem (in domain) eval_cring_hom:\n  assumes \"subring K R\" and \"a \\<in> carrier R\"\n  shows \"ring_hom_cring (K[X]) R (\\<lambda>p. (eval p) a)\"\n  unfolding ring_hom_cring_def ring_hom_cring_axioms_def\n  using domain.axioms(1)[OF univ_poly_is_domain[OF assms(1)]]\n        eval_is_hom[OF assms] cring_axioms by auto\n\ncorollary (in domain) eval_ring_hom:\n  assumes \"subring K R\" and \"a \\<in> carrier R\"\n  shows \"ring_hom_ring (K[X]) R (\\<lambda>p. (eval p) a)\"\n  using eval_cring_hom[OF assms] ring_hom_ringI2\n  unfolding ring_hom_cring_def ring_hom_cring_axioms_def cring_def by auto\n\n\nsubsection \\<open>Homomorphisms\\<close>\n\nlemma (in ring_hom_ring) eval_hom':\n  assumes \"a \\<in> carrier R\" and \"set p \\<subseteq> carrier R\"\n  shows \"h (R.eval p a) = eval (map h p) (h a)\"\n  using assms by (induct p, auto simp add: R.eval_in_carrier hom_nat_pow)\n\nlemma (in ring_hom_ring) eval_hom:\n  assumes \"subring K R\" and \"a \\<in> carrier R\" and \"p \\<in> carrier (K[X])\"\n  shows \"h (R.eval p a) = eval (map h p) (h a)\"\nproof -\n  have \"set p \\<subseteq> carrier R\"\n    using subringE(1)[OF assms(1)] R.polynomial_incl assms(3)\n    unfolding sym[OF univ_poly_carrier[of R]] by auto\n  thus ?thesis\n    using eval_hom'[OF assms(2)] by simp\nqed\n\nlemma (in ring_hom_ring) coeff_hom':\n  assumes \"set p \\<subseteq> carrier R\" shows \"h (R.coeff p i) = coeff (map h p) i\"\n  using assms by (induct p) (auto)\n\nlemma (in ring_hom_ring) poly_add_hom':\n  assumes \"set p \\<subseteq> carrier R\" and \"set q \\<subseteq> carrier R\"\n  shows \"normalize (map h (R.poly_add p q)) = poly_add (map h p) (map h q)\"\nproof -\n  have set_map: \"set (map h s) \\<subseteq> carrier S\" if \"set s \\<subseteq> carrier R\" for s\n    using that by auto\n  have \"coeff (normalize (map h (R.poly_add p q))) = coeff (map h (R.poly_add p q))\"\n    using S.normalize_coeff by auto\n  also have \" ... = (\\<lambda>i. h ((R.coeff p i) \\<oplus> (R.coeff q i)))\"\n    using coeff_hom'[OF R.poly_add_in_carrier[OF assms]] R.poly_add_coeff[OF assms] by simp\n  also have \" ... = (\\<lambda>i. (coeff (map h p) i) \\<oplus>\\<^bsub>S\\<^esub> (coeff (map h q) i))\"\n    using assms[THEN R.coeff_in_carrier] assms[THEN coeff_hom'] by simp\n  also have \" ... = (\\<lambda>i. coeff (poly_add (map h p) (map h q)) i)\"\n    using S.poly_add_coeff[OF assms[THEN set_map]] by simp\n  finally have \"coeff (normalize (map h (R.poly_add p q))) = (\\<lambda>i. coeff (poly_add (map h p) (map h q)) i)\" .\n  thus ?thesis\n    unfolding coeff_iff_polynomial_cond[OF\n              normalize_gives_polynomial[OF set_map[OF R.poly_add_in_carrier[OF assms]]]\n              poly_add_is_polynomial[OF carrier_is_subring assms[THEN set_map]]] .\nqed\n\nlemma (in ring_hom_ring) poly_mult_hom':\n  assumes \"set p \\<subseteq> carrier R\" and \"set q \\<subseteq> carrier R\"\n  shows \"normalize (map h (R.poly_mult p q)) = poly_mult (map h p) (map h q)\"\n  using assms(1)\nproof (induct p, simp)\n  case (Cons a p)\n  have set_map: \"set (map h s) \\<subseteq> carrier S\" if \"set s \\<subseteq> carrier R\" for s\n    using that by auto\n\n  let ?q_a = \"(map ((\\<otimes>) a) q) @ (replicate (length p) \\<zero>)\"\n  have set_q_a: \"set ?q_a \\<subseteq> carrier R\"\n    using assms(2) Cons(2) by (induct q) (auto)\n  have q_a_simp: \"map h ?q_a = (map ((\\<otimes>\\<^bsub>S\\<^esub>) (h a)) (map h q)) @ (replicate (length (map h p)) \\<zero>\\<^bsub>S\\<^esub>)\"\n    using assms(2) Cons(2) by (induct q) (auto)\n\n  have \"S.normalize (map h (R.poly_mult (a # p) q)) = \n        S.normalize (map h (R.poly_add ?q_a (R.poly_mult p q)))\"\n    by simp\n  also have \" ... = S.poly_add (map h ?q_a) (map h (R.poly_mult p q))\"\n    using poly_add_hom'[OF set_q_a R.poly_mult_in_carrier[OF _ assms(2)]] Cons by simp\n  also have \" ... = S.poly_add (map h ?q_a) (S.normalize (map h (R.poly_mult p q)))\"\n    using poly_add_normalize(2)[OF set_map[OF set_q_a] set_map[OF R.poly_mult_in_carrier[OF _ assms(2)]]] Cons by simp\n  also have \" ... = S.poly_add (map h ?q_a) (S.poly_mult (map h p) (map h q))\"\n    using Cons by simp\n  also have \" ... = S.poly_mult (map h (a # p)) (map h q)\"\n    unfolding q_a_simp by simp\n  finally show ?case . \nqed\n\n\nsubsection \\<open>The X Variable\\<close>\n\ndefinition var :: \"_ \\<Rightarrow> 'a list\" (\"X\\<index>\")\n  where \"X\\<^bsub>R\\<^esub> = [ \\<one>\\<^bsub>R\\<^esub>, \\<zero>\\<^bsub>R\\<^esub> ]\"\n\nlemma (in ring) eval_var:\n  assumes \"x \\<in> carrier R\" shows \"eval X x = x\"\n  using assms unfolding var_def by auto\n\nlemma (in domain) var_closed:\n  assumes \"subring K R\" shows \"X \\<in> carrier (K[X])\" and \"polynomial K X\"\n  using subringE(2-3)[OF assms]\n  by (auto simp add: var_def univ_poly_def polynomial_def)\n\nlemma (in domain) poly_mult_var':\n  assumes \"set p \\<subseteq> carrier R\"\n  shows \"poly_mult X p = normalize (p @ [ \\<zero> ])\"\n    and \"poly_mult p X = normalize (p @ [ \\<zero> ])\"\nproof -\n  from \\<open>set p \\<subseteq> carrier R\\<close> have \"poly_mult [ \\<one> ] p = normalize p\"\n    using poly_mult_one' by simp\n  thus \"poly_mult X p = normalize (p @ [ \\<zero> ])\"\n    using poly_mult_append_zero[OF _ assms, of \"[ \\<one> ]\"] normalize_idem\n    unfolding var_def by (auto simp del: poly_mult.simps)\n  thus \"poly_mult p X = normalize (p @ [ \\<zero> ])\"\n    using poly_mult_comm[OF assms] unfolding var_def by simp\nqed\n\nlemma (in domain) poly_mult_var:\n  assumes \"subring K R\" \"p \\<in> carrier (K[X])\"\n  shows \"p \\<otimes>\\<^bsub>K[X]\\<^esub> X = (if p = [] then [] else p @ [ \\<zero> ])\"\nproof -\n  have is_poly: \"polynomial K p\"\n    using assms(2) unfolding univ_poly_def by simp\n  hence \"polynomial K (p @ [ \\<zero> ])\" if \"p \\<noteq> []\"\n    using that subringE(2)[OF assms(1)] unfolding polynomial_def by auto\n  thus ?thesis\n    using poly_mult_var'(2)[OF polynomial_in_carrier[OF assms(1) is_poly]]\n          normalize_polynomial[of K \"p @ [ \\<zero> ]\"]\n    by (auto simp add: univ_poly_mult[of R K])\nqed\n\nlemma (in domain) var_pow_closed:\n  assumes \"subring K R\" shows \"X [^]\\<^bsub>K[X]\\<^esub> (n :: nat) \\<in> carrier (K[X])\"\n  using monoid.nat_pow_closed[OF univ_poly_is_monoid[OF assms] var_closed(1)[OF assms]] . \n\nlemma (in domain) unitary_monom_eq_var_pow:\n  assumes \"subring K R\" shows \"monom \\<one> n = X [^]\\<^bsub>K[X]\\<^esub> n\"\n  using poly_mult_var[OF assms var_pow_closed[OF assms]] unfolding nat_pow_def monom_def\n  by (induct n) (auto simp add: univ_poly_one, metis append_Cons replicate_append_same)\n\nlemma (in domain) monom_eq_var_pow:\n  assumes \"subring K R\" \"a \\<in> carrier R - { \\<zero> }\"\n  shows \"monom a n = [ a ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> n)\"\nproof -\n  have \"monom a n = map ((\\<otimes>) a) (monom \\<one> n)\"\n    unfolding monom_def using assms(2) by (induct n) (auto)\n  also have \" ... = poly_mult [ a ] (monom \\<one> n)\"\n    using poly_mult_const(1)[OF _ monom_is_polynomial assms(2)] carrier_is_subring by simp\n  also have \" ... = [ a ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> n)\"\n    unfolding unitary_monom_eq_var_pow[OF assms(1)] univ_poly_mult[of R K] by simp\n  finally show ?thesis .\nqed\n\nlemma (in domain) eval_rewrite:\n  assumes \"subring K R\" and \"p \\<in> carrier (K[X])\"\n  shows \"p = (ring.eval (K[X])) (map poly_of_const p) X\"\nproof -\n  let ?map_norm = \"\\<lambda>p. map poly_of_const p\"\n\n  interpret UP: domain \"K[X]\"\n    using univ_poly_is_domain[OF assms(1)] .\n\n  { fix l assume \"set l \\<subseteq> K\"\n    hence \"poly_of_const a \\<in> carrier (K[X])\" if \"a \\<in> set l\" for a\n      using that normalize_gives_polynomial[of \"[ a ]\" K]\n      unfolding univ_poly_carrier poly_of_const_def by auto\n    hence \"set (?map_norm l) \\<subseteq> carrier (K[X])\"\n      by auto }\n  note aux_lemma1 = this\n\n  { fix q l assume set_l: \"set l \\<subseteq> K\" and q: \"q \\<in> carrier (K[X])\"\n    from set_l have \"UP.eval (?map_norm l) q = UP.eval (?map_norm ((replicate n \\<zero>) @ l)) q\" for n\n    proof (induct n, simp)\n      case (Suc n)\n      from \\<open>set l \\<subseteq> K\\<close> have set_replicate: \"set ((replicate n \\<zero>) @ l) \\<subseteq> K\"\n        using subringE(2)[OF assms(1)] by (induct n) (auto)\n      have step: \"UP.eval (?map_norm l') q = UP.eval (?map_norm (\\<zero> # l')) q\" if \"set l' \\<subseteq> K\" for l'\n        using UP.eval_in_carrier[OF aux_lemma1[OF that]] q unfolding poly_of_const_def\n        by (simp, simp add: sym[OF univ_poly_zero[of R K]])\n      have \"UP.eval (?map_norm l) q = UP.eval (?map_norm ((replicate n \\<zero>) @ l)) q\"\n        using Suc by simp\n      also have \" ... = UP.eval (map poly_of_const ((replicate (Suc n) \\<zero>) @ l)) q\"\n        using step[OF set_replicate] by simp\n      finally show ?case .\n    qed }\n  note aux_lemma2 = this\n\n  { fix q l assume \"set l \\<subseteq> K\" and q: \"q \\<in> carrier (K[X])\"\n    from \\<open>set l \\<subseteq> K\\<close> have set_norm: \"set (normalize l) \\<subseteq> K\"\n      by (induct l) (auto)\n    have \"UP.eval (?map_norm l) q = UP.eval (?map_norm (normalize l)) q\"\n      using aux_lemma2[OF set_norm q, of \"length l - length (local.normalize l)\"]\n      unfolding sym[OF normalize_trick[of l]] .. }\n  note aux_lemma3 = this\n\n  from \\<open>p \\<in> carrier (K[X])\\<close> show ?thesis\n  proof (induct \"length p\" arbitrary: p rule: less_induct)\n    case less thus ?case\n    proof (cases p, simp add: univ_poly_zero)\n      case (Cons a l)\n      hence a: \"a \\<in> carrier R - { \\<zero> }\" and set_l: \"set l \\<subseteq> carrier R\" \"set l \\<subseteq> K\"\n        using less(2) subringE(1)[OF assms(1)] unfolding sym[OF univ_poly_carrier] polynomial_def by auto\n\n      have \"a # l = poly_add (monom a (length l)) l\"\n        using poly_add_monom[OF set_l(1) a] ..\n      also have \" ... = poly_add (monom a (length l)) (normalize l)\"\n        using poly_add_normalize(2)[OF monom_in_carrier[of a] set_l(1)] a by simp\n      also have \" ... = poly_add (monom a (length l)) (UP.eval (?map_norm (normalize l)) X)\"\n        using less(1)[of \"normalize l\"] normalize_gives_polynomial[OF set_l(2)] normalize_length_le[of l]\n        by (auto simp add: univ_poly_carrier Cons(1))\n      also have \" ... = poly_add ([ a ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> (length l))) (UP.eval (?map_norm l) X)\"\n        unfolding monom_eq_var_pow[OF assms(1) a] aux_lemma3[OF set_l(2) var_closed(1)[OF assms(1)]] ..\n      also have \" ... = UP.eval (?map_norm (a # l)) X\"\n        using a unfolding sym[OF univ_poly_add[of R K]] unfolding poly_of_const_def by auto\n      finally show ?thesis\n        unfolding Cons(1) .\n    qed\n  qed   \nqed\n\nlemma (in ring) dense_repr_set_fst:\n  assumes \"set p \\<subseteq> K\" shows \"fst ` (set (dense_repr p)) \\<subseteq> K - { \\<zero> }\"\n  using assms by (induct p) (auto)\n\nlemma (in ring) dense_repr_set_snd:\n  shows \"snd ` (set (dense_repr p)) \\<subseteq> {..< length p}\"\n  by (induct p) (auto)\n\nlemma (in domain) dense_repr_monom_closed:\n  assumes \"subring K R\" \"set p \\<subseteq> K\"\n  shows \"t \\<in> set (dense_repr p) \\<Longrightarrow> monom (fst t) (snd t) \\<in> carrier (K[X])\"\n  using dense_repr_set_fst[OF assms(2)] monom_is_polynomial[OF assms(1)]\n  by (auto simp add: univ_poly_carrier)\n\nlemma (in domain) monom_finsum_decomp:\n  assumes \"subring K R\" \"p \\<in> carrier (K[X])\"\n  shows \"p = (\\<Oplus>\\<^bsub>K[X]\\<^esub> t \\<in> set (dense_repr p). monom (fst t) (snd t))\"\nproof -\n  interpret UP: domain \"K[X]\"\n    using univ_poly_is_domain[OF assms(1)] .\n\n  from \\<open>p \\<in> carrier (K[X])\\<close> show ?thesis\n  proof (induct \"length p\" arbitrary: p rule: less_induct)\n    case less thus ?case\n    proof (cases p)\n      case Nil thus ?thesis\n        using UP.finsum_empty univ_poly_zero[of R K] by simp\n    next\n      case (Cons a l)\n      hence in_carrier:\n        \"normalize l \\<in> carrier (K[X])\" \"polynomial K (normalize l)\" \"polynomial K (a # l)\"\n        using normalize_gives_polynomial polynomial_incl[of K p] less(2)\n        unfolding univ_poly_carrier by auto\n      have len_lt: \"length (local.normalize l) < length p\"\n        using normalize_length_le by (simp add: Cons le_imp_less_Suc) \n\n      have a: \"a \\<in> K - { \\<zero> }\"\n        using less(2) subringE(1)[OF assms(1)] unfolding Cons univ_poly_def polynomial_def by auto \n      hence \"p = (monom a (length l)) \\<oplus>\\<^bsub>K[X]\\<^esub> (poly_of_dense (dense_repr (normalize l)))\"\n        using monom_decomp[OF assms(1), of p] less(2) dense_repr_normalize\n        unfolding univ_poly_add univ_poly_carrier Cons by (auto simp del: poly_add.simps)\n      also have \" ... = (monom a (length l)) \\<oplus>\\<^bsub>K[X]\\<^esub> (normalize l)\"\n        using monom_decomp[OF assms(1) in_carrier(2)] by simp\n      finally have \"p = monom a (length l) \\<oplus>\\<^bsub>K[X]\\<^esub>\n                       (\\<Oplus>\\<^bsub>K[X]\\<^esub> t \\<in> set (dense_repr l). monom (fst t) (snd t))\"\n        using less(1)[OF len_lt in_carrier(1)] dense_repr_normalize by simp\n\n      moreover have \"(a, (length l)) \\<notin> set (dense_repr l)\"\n        using dense_repr_set_snd[of l] by auto\n      moreover have \"monom a (length l) \\<in> carrier (K[X])\"\n        using monom_is_polynomial[OF assms(1) a] unfolding univ_poly_carrier by simp\n      moreover have \"\\<And>t. t \\<in> set (dense_repr l) \\<Longrightarrow> monom (fst t) (snd t) \\<in> carrier (K[X])\"\n        using dense_repr_monom_closed[OF assms(1)] polynomial_incl[OF in_carrier(3)] by auto\n      ultimately have \"p = (\\<Oplus>\\<^bsub>K[X]\\<^esub> t \\<in> set (dense_repr (a # l)). monom (fst t) (snd t))\"\n        using UP.add.finprod_insert a by auto\n      thus ?thesis unfolding Cons . \n    qed\n  qed\nqed\n\nlemma (in domain) var_pow_finsum_decomp:\n  assumes \"subring K R\" \"p \\<in> carrier (K[X])\"\n  shows \"p = (\\<Oplus>\\<^bsub>K[X]\\<^esub> t \\<in> set (dense_repr p). [ fst t ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> (snd t)))\"\nproof -\n  let ?f = \"\\<lambda>t. monom (fst t) (snd t)\"\n  let ?g = \"\\<lambda>t. [ fst t ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> (snd t))\"\n\n  interpret UP: domain \"K[X]\"\n    using univ_poly_is_domain[OF assms(1)] .\n\n  have set_p: \"set p \\<subseteq> K\"\n    using polynomial_incl assms(2) by (simp add: univ_poly_carrier)\n  hence f: \"?f \\<in> set (dense_repr p) \\<rightarrow> carrier (K[X])\"\n    using dense_repr_monom_closed[OF assms(1)] by auto\n\n  moreover\n  have \"\\<And>t. t \\<in> set (dense_repr p) \\<Longrightarrow> fst t \\<in> carrier R - { \\<zero> }\"\n    using dense_repr_set_fst[OF set_p] subringE(1)[OF assms(1)] by auto\n  hence \"\\<And>t. t \\<in> set (dense_repr p) \\<Longrightarrow> monom (fst t) (snd t) = [ fst t ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> (snd t))\"\n    using monom_eq_var_pow[OF assms(1)] by auto\n\n  ultimately show ?thesis\n    using UP.add.finprod_cong[of _ _ ?f ?g] monom_finsum_decomp[OF assms] by auto\nqed\n\ncorollary (in domain) hom_var_pow_finsum:\n  assumes \"subring K R\" and \"p \\<in> carrier (K[X])\" \"ring_hom_ring (K[X]) A h\"\n  shows \"h p = (\\<Oplus>\\<^bsub>A\\<^esub> t \\<in> set (dense_repr p). h [ fst t ] \\<otimes>\\<^bsub>A\\<^esub> (h X [^]\\<^bsub>A\\<^esub> (snd t)))\"\nproof -\n  let ?f = \"\\<lambda>t. [ fst t ] \\<otimes>\\<^bsub>K[X]\\<^esub> (X [^]\\<^bsub>K[X]\\<^esub> (snd t))\"\n  let ?g = \"\\<lambda>t. h [ fst t ] \\<otimes>\\<^bsub>A\\<^esub> (h X [^]\\<^bsub>A\\<^esub> (snd t))\"\n\n  interpret UP: domain \"K[X]\" + A: ring A\n    using univ_poly_is_domain[OF assms(1)] ring_hom_ring.axioms(2)[OF assms(3)] by simp+\n\n  have const_in_carrier:\n    \"\\<And>t. t \\<in> set (dense_repr p) \\<Longrightarrow> [ fst t ] \\<in> carrier (K[X])\"\n    using dense_repr_set_fst[OF polynomial_incl, of K p] assms(2) const_is_polynomial[of _ K]\n    by (auto simp add: univ_poly_carrier)\n  hence f: \"?f: set (dense_repr p) \\<rightarrow> carrier (K[X])\"\n    using UP.m_closed[OF _ var_pow_closed[OF assms(1)]] by auto\n  hence h: \"h \\<circ> ?f: set (dense_repr p) \\<rightarrow> carrier A\"\n    using ring_hom_memE(1)[OF ring_hom_ring.homh[OF assms(3)]] by (auto simp add: Pi_def)\n\n  have hp: \"h p = (\\<Oplus>\\<^bsub>A\\<^esub> t \\<in> set (dense_repr p). (h \\<circ> ?f) t)\"\n    using ring_hom_ring.hom_finsum[OF assms(3) f] var_pow_finsum_decomp[OF assms(1-2)]\n    by (auto, meson o_apply)\n  have eq: \"\\<And>t. t \\<in> set (dense_repr p) \\<Longrightarrow> h [ fst t ] \\<otimes>\\<^bsub>A\\<^esub> (h X [^]\\<^bsub>A\\<^esub> (snd t)) = (h \\<circ> ?f) t\"\n    using ring_hom_memE(2)[OF ring_hom_ring.homh[OF assms(3)]\n          const_in_carrier var_pow_closed[OF assms(1)]]\n          ring_hom_ring.hom_nat_pow[OF assms(3) var_closed(1)[OF assms(1)]] by auto\n  show ?thesis\n    using A.add.finprod_cong'[OF _ h eq] hp by simp\nqed\n\ncorollary (in domain) determination_of_hom:\n  assumes \"subring K R\"\n    and \"ring_hom_ring (K[X]) A h\" \"ring_hom_ring (K[X]) A g\"\n    and \"\\<And>k. k \\<in> K \\<Longrightarrow> h [ k ] = g [ k ]\" and \"h X = g X\"\n  shows \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> h p = g p\"\nproof -\n  interpret A: ring A\n    using ring_hom_ring.axioms(2)[OF assms(2)] by simp\n\n  fix p assume p: \"p \\<in> carrier (K[X])\"\n  hence\n    \"\\<And>t. t \\<in> set (dense_repr p) \\<Longrightarrow> [ fst t ] \\<in> carrier (K[X])\"\n    using dense_repr_set_fst[OF polynomial_incl, of K p] const_is_polynomial[of _ K]\n    by (auto simp add: univ_poly_carrier)\n  hence f: \"(\\<lambda>t. h [ fst t ] \\<otimes>\\<^bsub>A\\<^esub> (h X [^]\\<^bsub>A\\<^esub> (snd t))): set (dense_repr p) \\<rightarrow> carrier A\"\n    using ring_hom_memE(1)[OF ring_hom_ring.homh[OF assms(2)]] var_closed(1)[OF assms(1)]\n          A.m_closed[OF _ A.nat_pow_closed]\n    by auto\n\n  have eq: \"\\<And>t. t \\<in> set (dense_repr p) \\<Longrightarrow>\n    g [ fst t ] \\<otimes>\\<^bsub>A\\<^esub> (g X [^]\\<^bsub>A\\<^esub> (snd t)) = h [ fst t ] \\<otimes>\\<^bsub>A\\<^esub> (h X [^]\\<^bsub>A\\<^esub> (snd t))\"\n    using dense_repr_set_fst[OF polynomial_incl, of K p] p assms(4-5)\n    by (auto simp add: univ_poly_carrier)\n  show \"h p = g p\"\n    unfolding assms(2-3)[THEN hom_var_pow_finsum[OF assms(1) p]]\n    using A.add.finprod_cong'[OF _ f eq] by simp\nqed\n\ncorollary (in domain) eval_as_unique_hom:\n  assumes \"subring K R\" \"x \\<in> carrier R\"\n    and \"ring_hom_ring (K[X]) R h\"\n    and \"\\<And>k. k \\<in> K \\<Longrightarrow> h [ k ] = k\" and \"h X = x\"\n  shows \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> h p = eval p x\"\n  using determination_of_hom[OF assms(1,3) eval_ring_hom[OF assms(1-2)]]\n        eval_var[OF assms(2)] assms(4-5) subringE(1)[OF assms(1)]\n  by fastforce\n\n\nsubsection \\<open>The Constant Term\\<close>\n\ndefinition (in ring) const_term :: \"'a list \\<Rightarrow> 'a\"\n  where \"const_term p = eval p \\<zero>\"\n\nlemma (in ring) const_term_eq_last:\n  assumes \"set p \\<subseteq> carrier R\" and \"a \\<in> carrier R\"\n  shows \"const_term (p @ [ a ]) = a\"\n  using assms by (induct p) (auto simp add: const_term_def)\n\nlemma (in ring) const_term_not_zero:\n  assumes \"const_term p \\<noteq> \\<zero>\" shows \"p \\<noteq> []\"\n  using assms by (auto simp add: const_term_def)\n\nlemma (in ring) const_term_explicit:\n  assumes \"set p \\<subseteq> carrier R\" \"p \\<noteq> []\" and \"const_term p = a\"\n  obtains p' where \"set p' \\<subseteq> carrier R\" and \"p = p' @ [ a ]\"\nproof -\n  obtain a' p' where p: \"p = p' @ [ a' ]\"\n    using assms(2) rev_exhaust by blast\n  have p': \"set p' \\<subseteq> carrier R\" and a: \"a = a'\"\n    using assms const_term_eq_last[of p' a'] unfolding p by auto\n  show thesis\n    using p p' that unfolding a by blast\nqed\n\nlemma (in ring) const_term_zero:\n  assumes \"subring K R\" \"polynomial K p\" \"p \\<noteq> []\" and \"const_term p = \\<zero>\"\n  obtains p' where \"polynomial K p'\" \"p' \\<noteq> []\" and \"p = p' @ [ \\<zero> ]\"\nproof -\n  obtain p' where p': \"p = p' @ [ \\<zero> ]\"\n    using const_term_explicit[OF polynomial_in_carrier[OF assms(1-2)] assms(3-4)] by auto\n  have \"polynomial K p'\" \"p' \\<noteq> []\"\n    using assms(2) unfolding p' polynomial_def by auto\n  thus thesis using p' ..\nqed\n\nlemma (in cring) const_term_simprules:\n  shows \"\\<And>p. set p \\<subseteq> carrier R \\<Longrightarrow> const_term p \\<in> carrier R\"\n    and \"\\<And>p q. \\<lbrakk> set p \\<subseteq> carrier R; set q \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow>\n                 const_term (poly_mult p q) = const_term p \\<otimes> const_term q\"\n    and \"\\<And>p q. \\<lbrakk> set p \\<subseteq> carrier R; set q \\<subseteq> carrier R \\<rbrakk> \\<Longrightarrow>\n                 const_term (poly_add  p q) = const_term p \\<oplus> const_term q\"\n  using eval_poly_mult eval_poly_add eval_in_carrier zero_closed\n  unfolding const_term_def by auto\n\nlemma (in domain) const_term_simprules_shell:\n  assumes \"subring K R\"\n  shows \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> const_term p \\<in> K\"\n    and \"\\<And>p q. \\<lbrakk> p \\<in> carrier (K[X]); q \\<in> carrier (K[X]) \\<rbrakk> \\<Longrightarrow>\n                 const_term (p \\<otimes>\\<^bsub>K[X]\\<^esub> q) = const_term p \\<otimes> const_term q\"\n    and \"\\<And>p q. \\<lbrakk> p \\<in> carrier (K[X]); q \\<in> carrier (K[X]) \\<rbrakk> \\<Longrightarrow>\n                 const_term (p \\<oplus>\\<^bsub>K[X]\\<^esub> q) = const_term p \\<oplus> const_term q\"\n    and \"\\<And>p. p \\<in> carrier (K[X]) \\<Longrightarrow> const_term (\\<ominus>\\<^bsub>K[X]\\<^esub> p) = \\<ominus> (const_term p)\"\n  using eval_is_hom[OF assms(1) zero_closed]\n  unfolding ring_hom_def const_term_def\nproof (auto)\n  fix p assume p: \"p \\<in> carrier (K[X])\"\n  hence \"set p \\<subseteq> carrier R\"\n    using polynomial_in_carrier[OF assms(1)] by (auto simp add: univ_poly_def)\n  thus \"eval (\\<ominus>\\<^bsub>K [X]\\<^esub> p) \\<zero> = \\<ominus> local.eval p \\<zero>\"\n    unfolding univ_poly_a_inv_def'[OF assms(1) p]\n    by (induct p) (auto simp add: eval_in_carrier l_minus local.minus_add)\n\n  have \"set p \\<subseteq> K\"\n    using p by (auto simp add: univ_poly_def polynomial_def)\n  thus \"eval p \\<zero> \\<in> K\"\n    using subringE(1-2,6-7)[OF assms]\n    by (induct p) (auto, metis assms nat_pow_0 nat_pow_zero subringE(3))\nqed\n\n\nsubsection \\<open>The Canonical Embedding of K in K[X]\\<close>\n\nlemma (in ring) poly_of_const_consistent:\n  assumes \"subring K R\" shows \"ring.poly_of_const (R \\<lparr> carrier := K \\<rparr>) = poly_of_const\"\n  unfolding ring.poly_of_const_def[OF subring_is_ring[OF assms]]\n            normalize_consistent[OF assms] poly_of_const_def ..\n\nlemma (in domain) canonical_embedding_is_hom:\n  assumes \"subring K R\" shows \"poly_of_const \\<in> ring_hom (R \\<lparr> carrier := K \\<rparr>) (K[X])\"\n  using subringE(1)[OF assms] unfolding subset_iff poly_of_const_def\n  by (auto intro!: ring_hom_memI simp add: univ_poly_def)\n\nlemma (in domain) canonical_embedding_ring_hom:\n  assumes \"subring K R\" shows \"ring_hom_ring (R \\<lparr> carrier := K \\<rparr>) (K[X]) poly_of_const\"\n  using canonical_embedding_is_hom[OF assms] unfolding symmetric[OF ring_hom_ring_axioms_def]\n  by (rule ring_hom_ring.intro[OF subring_is_ring[OF assms] univ_poly_is_ring[OF assms]])\n\nlemma (in field) poly_of_const_over_carrier:\n  shows \"poly_of_const ` (carrier R) = { p \\<in> carrier ((carrier R)[X]). degree p = 0 }\"\nproof -\n  have \"poly_of_const ` (carrier R) = insert [] { [ k ] | k. k \\<in> carrier R - { \\<zero> } }\"\n    unfolding poly_of_const_def by auto\n  also have \" ... = { p \\<in> carrier ((carrier R)[X]). degree p = 0 }\"\n    unfolding univ_poly_def polynomial_def\n    by (auto, metis le_Suc_eq le_zero_eq length_0_conv length_Suc_conv list.sel(1) list.set_sel(1) subsetCE)\n  finally show ?thesis .\nqed\n\nlemma (in ring) poly_of_const_over_subfield:\n  assumes \"subfield K R\" shows \"poly_of_const ` K = { p \\<in> carrier (K[X]). degree p = 0 }\"\n  using field.poly_of_const_over_carrier[OF subfield_iff(2)[OF assms]]\n        poly_of_const_consistent[OF subfieldE(1)[OF assms]]\n        univ_poly_consistent[OF subfieldE(1)[OF assms]] by simp\n    \nlemma (in field) univ_poly_carrier_subfield_of_consts:\n  \"subfield (poly_of_const ` (carrier R)) ((carrier R)[X])\"\nproof -\n  have ring_hom: \"ring_hom_ring R ((carrier R)[X]) poly_of_const\"\n    using canonical_embedding_ring_hom[OF carrier_is_subring] by simp\n  thus ?thesis\n    using ring_hom_ring.img_is_subfield(2)[OF ring_hom carrier_is_subfield]\n    unfolding univ_poly_def by auto\nqed\n\nproposition (in ring) univ_poly_subfield_of_consts:\n  assumes \"subfield K R\" shows \"subfield (poly_of_const ` K) (K[X])\"\n  using field.univ_poly_carrier_subfield_of_consts[OF subfield_iff(2)[OF assms]]\n  unfolding poly_of_const_consistent[OF subfieldE(1)[OF assms]]\n            univ_poly_consistent[OF subfieldE(1)[OF assms]] by simp\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Algebra/Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8791467690927438, "lm_q1q2_score": 0.7988084840773916}}
{"text": "(* author: wzh *)\ntheory Exercise2_2\n  imports Main\n\nbegin\n(* Exer 2.6 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\n(* Convert a tree to a list *)\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l x r) = (contents l) @ [x] @ (contents r)\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l x r) = (sum_tree l) + x + (sum_tree r)\"\n\ntheorem \"sum_tree t = sum_list(contents t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n\n(* Exer 2.7 *)\nfun pre_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"pre_order Tip = []\" |\n\"pre_order (Node l x r) = [x] @ (pre_order l) @ (pre_order r)\"\n\nfun post_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"post_order Tip = []\" |\n\"post_order (Node l x r) = (post_order l) @ (post_order r) @ [x]\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l x r) = Node (mirror r) x (mirror l)\"\n\n\nlemma mirr: \"mirror (mirror t) = t\"\n  apply(induction t)\n   apply(auto)\n  done\n\ntheorem \"rev(post_order t) = pre_order(mirror  t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n\n(* Exer 2.8 *)\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse x [] = [x]\" |\n\"intersperse x (y # ys) = [y] @ [x] @ (intersperse x ys)\"\n\ntheorem \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n(* Exer 2.9 *)\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 x = x\" |\n\"itadd (Suc m) n = itadd m (Suc n)\"\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 m = m\" |\n\"add (Suc(n)) m = Suc(add n m)\"\n\n\n(* Exer 2.10 *)\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 0\" |\n\"nodes (Node l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\n(* arbitrary t is used to fix t when inducting *)\ntheorem \"nodes (explode n t) = 2^n * (nodes t) + (2^n - 1)\"\n  apply(induction n arbitrary: t)\n   apply(auto)\n  apply(simp add: algebra_simps)\n  done\n\n(* Exer 2.11 *)\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\" |\n\"eval (Const n) x = n\" |\n\"eval (Add ex1 ex2) x = (eval ex1 x) + (eval ex2 x)\" |\n\"eval (Mult ex1 ex2) x = (eval ex1 x) * (eval ex2 x)\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] y = 0\" |\n\"evalp (x # xs) y = x + y * (evalp xs y)\"\n\nvalue \"evalp [4, 2, -1, 3] 2\"\n\nfun sum :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"sum [] ys = ys\" |\n\"sum xs [] = xs\" |\n\"sum (x # xs) (y # ys) = [x + y] @ (sum xs ys)\"\n\nvalue \"sum [4, 2, 1] [1, 4]\"\n\nfun mul :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"mul [] ys = []\" |\n\"mul xs [] = []\" |\n\"mul [x] (y # ys) = [x * y]  @ (mul [x] ys)\" |\n\"mul (x # xs) ys = sum (mul [x] ys) ([0] @ (mul xs ys))\"\n\nvalue \"mul [2] [2, 3]\"\nvalue \"mul [1, 2] [2, 3]\"\nvalue \"mul [1, 2, 3] [4, 5, 6]\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0, 1]\" |\n\"coeffs (Const n) = [n]\" |\n\"coeffs (Add ex1 ex2) = sum (coeffs ex1) (coeffs ex2)\" |\n\"coeffs (Mult ex1 ex2) = mul (coeffs ex1) (coeffs ex2)\"\n\n(* prove correctness for add and mul respectively *)\nlemma evalp_add[simp]: \"evalp (sum xs ys) a = evalp xs a + evalp ys a\"\n  apply (induction rule: sum.induct)\n  apply (auto simp add:Int.int_distrib)\n  done\n\nlemma evalp_mul[simp]: \"evalp (mul xs ys) a = evalp xs a * evalp ys a\"\n  apply (induction rule: mul.induct)\n  apply (auto simp add:Int.int_distrib)\n  done\n\ntheorem \"evalp (coeffs e) x = eval e x\"\n  apply(induction e)\n     apply(auto)\n  done\n\nend", "meta": {"author": "yogurt-shadow", "repo": "Isar_Exercise", "sha": "27658bff434e0845a23aeb310eeb971e4fc20b98", "save_path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise", "path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise/Isar_Exercise-27658bff434e0845a23aeb310eeb971e4fc20b98/Exercise2_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8774767954920547, "lm_q1q2_score": 0.7984222859977843}}
{"text": "(*  Title:       HFSetCat\n    Author:      Eugene W. Stark <stark@cs.stonybrook.edu>, 2020\n    Maintainer:  Eugene W. Stark <stark@cs.stonybrook.edu>\n*)\n\nchapter \"The Category of Hereditarily Finite Sets\"\n\ntheory HFSetCat\nimports CategoryWithFiniteLimits CartesianClosedCategory HereditarilyFinite.HF\nbegin\n\n  text\\<open>\n    This theory constructs a category whose objects are in bijective correspondence with\n    the hereditarily finite sets and whose arrows correspond to the functions between such\n    sets.  We show that this category is cartesian closed and has finite limits.\n    Note that up to this point we have not constructed any other interpretation for the\n    @{locale cartesian_closed_category} locale, but it is important to have one to ensure\n    that the locale assumptions are consistent.\n  \\<close>\n\n  section \"Preliminaries\"\n\n  text\\<open>\n    We begin with some preliminary definitions and facts about hereditarily finite sets,\n    which are better targeted toward what we are trying to do here than what already exists\n    in @{theory HereditarilyFinite.HF}.\n  \\<close>\n\n  text\\<open>\n    The following defines when a hereditarily finite set \\<open>F\\<close> represents a function from\n    a hereditarily finite set \\<open>B\\<close> to a hereditarily finite set \\<open>C\\<close>.  Specifically, \\<open>F\\<close>\n    must be a relation from \\<open>B\\<close> to \\<open>C\\<close>, whose domain is \\<open>B\\<close>, whose range is contained in \\<open>C\\<close>,\n    and which is single-valued on its domain.\n  \\<close>\n\n  definition hfun\n  where \"hfun B C F \\<equiv> F \\<le> B * C \\<and> hfunction F \\<and> hdomain F = B \\<and> hrange F \\<le> C\"\n\n  lemma hfunI [intro]:\n  assumes \"F \\<le> A * B\"\n  and \"\\<And>X. X \\<^bold>\\<in> A \\<Longrightarrow> \\<exists>!Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> F\"\n  and \"\\<And>X Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> F \\<Longrightarrow> Y \\<^bold>\\<in> B\"\n  shows \"hfun A B F\"\n    unfolding hfun_def\n    using assms hfunction_def hrelation_def is_hpair_def hrange_def hconverse_def hdomain_def\n    apply (intro conjI)\n    apply auto\n    by fast\n\n  lemma hfunE [elim]:\n  assumes \"hfun B C F\"\n  and \"(\\<And>Y. Y \\<^bold>\\<in> B \\<Longrightarrow> (\\<exists>!Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F) \\<and> (\\<forall>Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F \\<longrightarrow> Z \\<^bold>\\<in> C)) \\<Longrightarrow> T\"\n  shows T\n  proof -\n    have \"\\<And>Y. Y \\<^bold>\\<in> B \\<Longrightarrow> (\\<exists>!Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F) \\<and> (\\<forall>Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F \\<longrightarrow> Z \\<^bold>\\<in> C)\"\n    proof (intro allI impI conjI)\n      fix Y\n      assume Y: \"Y \\<^bold>\\<in> B\"\n      show \"\\<exists>!Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F\"\n      proof -\n        have \"\\<exists>Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F\"\n          using assms Y hfun_def hdomain_def by auto\n        moreover have \"\\<And>Z Z'. \\<lbrakk> \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F; \\<langle>Y, Z'\\<rangle> \\<^bold>\\<in> F \\<rbrakk> \\<Longrightarrow> Z = Z'\"\n          using assms hfun_def hfunction_def by simp\n        ultimately show ?thesis by blast\n      qed\n      show \"\\<And>Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> F \\<Longrightarrow> Z \\<^bold>\\<in> C\"\n        using assms Y hfun_def by auto\n    qed\n    thus ?thesis\n      using assms(2) by simp\n  qed\n\n  text\\<open>\n    The hereditarily finite set \\<open>hexp B C\\<close> represents the collection of all functions\n    from \\<open>B\\<close> to \\<open>C\\<close>.\n  \\<close>\n\n  definition hexp\n  where \"hexp B C = \\<lbrace>F \\<^bold>\\<in> HPow (B * C). hfun B C F\\<rbrace>\"\n\n  lemma hfun_in_hexp:\n  assumes \"hfun B C F\"\n  shows \"F \\<^bold>\\<in> hexp B C\"\n    using assms by (simp add: hexp_def hfun_def)\n\n  text\\<open>\n    The function \\<open>happ\\<close> applies a function \\<open>F\\<close> from \\<open>B\\<close> to \\<open>C\\<close> to an element of \\<open>B\\<close>,\n    yielding an element of \\<open>C\\<close>.\n  \\<close>\n\n  abbreviation happ\n  where \"happ \\<equiv> app\"\n\n  lemma happ_mapsto:\n  assumes \"F \\<^bold>\\<in> hexp B C\" and \"Y \\<^bold>\\<in> B\"\n  shows \"happ F Y \\<^bold>\\<in> C\" and \"happ F Y \\<^bold>\\<in> hrange F\"\n  proof -\n    show \"happ F Y \\<^bold>\\<in> C\"\n      using assms app_def hexp_def app_equality hdomain_def hfun_def by auto\n    show \"happ F Y \\<^bold>\\<in> hrange F\"\n    proof -\n      have \"\\<langle>Y, happ F Y\\<rangle> \\<^bold>\\<in> F\"\n        using assms app_def hexp_def app_equality hdomain_def hfun_def by auto\n      thus ?thesis\n        using hdomain_def hrange_def hconverse_def by auto\n    qed\n  qed\n\n  lemma happ_expansion:\n  assumes \"hfun B C F\"\n  shows \"F = \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace>\"\n  proof\n    fix XY\n    show \"XY \\<^bold>\\<in> F \\<longleftrightarrow> XY \\<^bold>\\<in> \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace>\"\n    proof\n      show \"XY \\<^bold>\\<in> F \\<Longrightarrow> XY \\<^bold>\\<in> \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace>\"\n      proof -\n        assume XY: \"XY \\<^bold>\\<in> F\"\n        have \"XY \\<^bold>\\<in> B * C\"\n          using assms XY hfun_def by auto\n        moreover have \"hsnd XY = happ F (hfst XY)\"\n          using assms XY hfunE app_def [of F \"hfst XY\"] the1_equality [of \"\\<lambda>y. \\<langle>hfst XY, y\\<rangle> \\<^bold>\\<in> F\"]\n                calculation\n          by auto\n        ultimately show \"XY \\<^bold>\\<in> \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace>\" by simp\n      qed\n      show \"XY \\<^bold>\\<in> \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace> \\<Longrightarrow> XY \\<^bold>\\<in> F\"\n      proof -\n        assume XY: \"XY \\<^bold>\\<in> \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace>\"\n        show \"XY \\<^bold>\\<in> F\"\n          using assms XY app_def [of F \"hfst XY\"] the1_equality [of \"\\<lambda>y. \\<langle>hfst XY, y\\<rangle> \\<^bold>\\<in> F\"]\n          by fastforce\n      qed\n    qed\n  qed\n\n  text\\<open>\n    Function \\<open>hlam\\<close> takes a function \\<open>F\\<close> from \\<open>A * B\\<close> to \\<open>C\\<close> to a function \\<open>hlam F\\<close>\n    from \\<open>A\\<close> to \\<open>hexp B C\\<close>.\n  \\<close>\n\n  definition hlam\n  where \"hlam A B C F =\n         \\<lbrace>XG \\<^bold>\\<in> A * hexp B C.\n            \\<forall>YZ. YZ \\<^bold>\\<in> hsnd XG \\<longleftrightarrow> is_hpair YZ \\<and> \\<langle>\\<langle>hfst XG, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n\n  lemma hfun_hlam:\n  assumes \"hfun (A * B) C F\"\n  shows \"hfun A (hexp B C) (hlam A B C F)\"\n  proof\n    show \"hlam A B C F \\<le> A * hexp B C\"\n      using assms hlam_def by auto\n    show \"\\<And>X. X \\<^bold>\\<in> A \\<Longrightarrow> \\<exists>!Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n    proof\n      fix X\n      assume X: \"X \\<^bold>\\<in> A\"\n      let ?G = \"\\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n      have 1: \"?G \\<^bold>\\<in> hexp B C\"\n        using assms X hexp_def by fastforce\n      show \"\\<langle>X, ?G\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n        using assms X 1 is_hpair_def hfun_def hlam_def by auto\n      fix Y\n      assume XY: \"\\<langle>X, Y\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n      show \"Y = ?G\"\n        using assms X XY hlam_def hexp_def by fastforce\n    qed\n    show \"\\<And>X Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> hlam A B C F \\<Longrightarrow> Y \\<^bold>\\<in> hexp B C\"\n      using assms hlam_def hexp_def by simp\n  qed\n\n  lemma happ_hlam:\n  assumes \"X \\<^bold>\\<in> A\" and \"hfun (A * B) C F\"\n  shows \"\\<exists>!G. \\<langle>X, G\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n  and \"happ (hlam A B C F) X = (THE G. \\<langle>X, G\\<rangle> \\<^bold>\\<in> hlam A B C F)\"\n  and \"happ (hlam A B C F) X = \\<lbrace>yz \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst yz\\<rangle>, hsnd yz\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n  and \"Y \\<^bold>\\<in> B \\<Longrightarrow> happ (happ (hlam A B C F) X) Y = happ F \\<langle>X, Y\\<rangle>\"\n  proof -\n    show 1: \"\\<exists>!G. \\<langle>X, G\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n      using assms(1,2) hfun_hlam hfunE\n      by (metis (full_types))\n    show 2: \"happ (hlam A B C F) X = (THE G. \\<langle>X, G\\<rangle> \\<^bold>\\<in> hlam A B C F)\"\n      using assms app_def by simp\n    show \"happ (happ (hlam A B C F) X) Y = happ F \\<langle>X, Y\\<rangle>\"\n    proof -\n      have 3: \"\\<langle>X, happ (hlam A B C F) X\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n        using assms(1) 1 2 theI' [of \"\\<lambda>G. \\<langle>X, G\\<rangle> \\<^bold>\\<in> hlam A B C F\"] by simp\n      hence \"\\<exists>!Z. happ (happ (hlam A B C F) X) = Z\"\n        by simp\n      moreover have \"happ (happ (hlam A B C F) X) Y = happ F \\<langle>X, Y\\<rangle>\"\n        using assms(1-2) 3 hlam_def is_hpair_def app_def by simp\n      ultimately show ?thesis by simp\n    qed\n    show \"happ (hlam A B C F) X = \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n    proof -\n      let ?G = \"\\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n      have 4: \"hfun B C ?G\"\n      proof\n        show \"\\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace> \\<le> B * C\"\n          using assms by auto\n        show \"\\<And>Y. Y \\<^bold>\\<in> B \\<Longrightarrow> \\<exists>!Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n        proof -\n          fix Y\n          assume Y: \"Y \\<^bold>\\<in> B\"\n          have XY: \"\\<langle>X, Y\\<rangle> \\<^bold>\\<in> A * B\"\n            using assms Y by simp\n          hence 1: \"\\<exists>!Z. \\<langle>\\<langle>X, Y\\<rangle>, Z\\<rangle> \\<^bold>\\<in> F\"\n            using assms XY hfunE [of \"A * B\" C F] by metis\n          obtain Z where Z: \"\\<langle>\\<langle>X, Y\\<rangle>, Z\\<rangle> \\<^bold>\\<in> F\"\n            using 1 by auto\n          have \"\\<exists>Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n          proof -\n            have \"\\<langle>Y, Z\\<rangle> \\<^bold>\\<in> B * C\"\n              using assms Y Z by blast\n            moreover have \"\\<langle>\\<langle>X, hfst \\<langle>Y, Z\\<rangle>\\<rangle>, hsnd \\<langle>Y, Z\\<rangle>\\<rangle> \\<^bold>\\<in> F\"\n              using assms Y Z by simp\n            ultimately show ?thesis by auto\n          qed\n          moreover have \"\\<And>Z Z'. \\<lbrakk>\\<langle>Y, Z\\<rangle> \\<^bold>\\<in> \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>;\n                                 \\<langle>Y, Z'\\<rangle> \\<^bold>\\<in> \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\\<rbrakk> \\<Longrightarrow> Z = Z'\"\n            using assms Y by auto\n          ultimately show \"\\<exists>!Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace>\"\n            by auto\n        qed\n        show \"\\<And>Y Z. \\<langle>Y, Z\\<rangle> \\<^bold>\\<in> \\<lbrace>YZ \\<^bold>\\<in> B * C. \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\\<rbrace> \\<Longrightarrow> Z \\<^bold>\\<in> C\"\n          using assms by simp\n      qed\n      have \"\\<langle>X, ?G\\<rangle> \\<^bold>\\<in> hlam A B C F\"\n      proof -\n        have \"\\<langle>X, ?G\\<rangle> \\<^bold>\\<in> A * hexp B C\"\n          using assms 4\n          by (simp add: hfun_in_hexp)\n        moreover have \"\\<forall>YZ. YZ \\<^bold>\\<in> ?G \\<longleftrightarrow> is_hpair YZ \\<and> \\<langle>\\<langle>X, hfst YZ\\<rangle>, hsnd YZ\\<rangle> \\<^bold>\\<in> F\"\n          using assms 1 is_hpair_def hfun_def by auto\n        ultimately show ?thesis\n          using assms 1 hlam_def by simp\n      qed\n      thus \"happ (hlam A B C F) X = ?G\"\n        using assms 2 4 app_equality hfun_def hfun_hlam by auto\n    qed\n  qed\n\n  section \"Construction of the Category\"\n\n  locale hfsetcat\n  begin\n\n    text\\<open>\n      We construct the category of hereditarily finite sets and functions simply by applying\n      the generic ``set category'' construction, using the hereditarily finite sets as the\n      universe, and constraining the collections of such sets that determine objects of the\n      category to those that are finite.\n    \\<close>\n\n    interpretation setcat \\<open>undefined :: hf\\<close> finite\n      using finite_subset\n      by unfold_locales blast+\n    interpretation set_category comp \\<open>\\<lambda>A. A \\<subseteq> Collect terminal \\<and> finite (elem_of ` A)\\<close>\n      using is_set_category by blast\n\n    lemma set_ide_char:\n    shows \"A \\<in> set ` Collect ide \\<longleftrightarrow> A \\<subseteq> Univ \\<and> finite A\"\n    proof\n      assume A: \"A \\<in> set ` Collect ide\"\n      show \"A \\<subseteq> Univ \\<and> finite A\"\n      proof\n        show \"A \\<subseteq> Univ\"\n          using A setp_set' by auto\n        obtain a where a: \"ide a \\<and> A = set a\"\n          using A by blast\n        have \"finite (elem_of ` set a)\"\n          using a setp_set_ide by blast\n        moreover have \"inj_on elem_of (set a)\"\n        proof -\n          have \"inj_on elem_of Univ\"\n            using bij_elem_of bij_betw_imp_inj_on by auto\n          moreover have \"set a \\<subseteq> Univ\"\n            using a setp_set' [of a] by blast\n          ultimately show ?thesis\n            using inj_on_subset by auto\n        qed\n        ultimately show \"finite A\"\n          using a A finite_imageD [of elem_of \"set a\"] by blast\n      qed\n      next\n      assume A: \"A \\<subseteq> Univ \\<and> finite A\"\n      have \"ide (mkIde A)\"\n        using A ide_mkIde by simp\n      moreover have \"set (mkIde A) = A\"\n        using A finite_imp_setp set_mkIde by presburger\n      ultimately show \"A \\<in> set ` Collect ide\" by blast\n    qed\n\n    lemma set_ideD:\n    assumes \"ide a\"\n    shows \"set a \\<subseteq> Univ\" and \"finite (set a)\"\n      using assms set_ide_char by auto\n\n    lemma ide_mkIdeI [intro]:\n    assumes \"A \\<subseteq> Univ\" and \"finite A\"\n    shows \"ide (mkIde A)\" and \"set (mkIde A) = A\"\n      using assms ide_mkIde set_mkIde by auto\n\n    interpretation category_with_terminal_object comp\n      using terminal_unity by unfold_locales auto\n\n    text\\<open>\n      We verify that the objects of HF are indeed in bijective correspondence with the\n      hereditarily finite sets.\n    \\<close>\n\n    definition ide_to_hf\n    where \"ide_to_hf a = HF (elem_of ` set a)\"\n\n    definition hf_to_ide\n    where \"hf_to_ide x = mkIde (arr_of ` hfset x)\"\n\n    lemma ide_to_hf_mapsto:\n    shows \"ide_to_hf \\<in> Collect ide \\<rightarrow> UNIV\"\n      by simp\n\n    lemma hf_to_ide_mapsto:\n    shows \"hf_to_ide \\<in> UNIV \\<rightarrow> Collect ide\"\n    proof\n      fix x :: hf\n      have \"finite (arr_of ` hfset x)\"\n        by simp\n      moreover have \"arr_of ` hfset x \\<subseteq> Univ\"\n        by (metis (mono_tags, lifting) UNIV_I bij_arr_of bij_betw_def imageE image_eqI subsetI)\n      ultimately have \"ide (mkIde (arr_of ` hfset x))\"\n        using finite_imp_setp ide_mkIde by presburger\n      thus \"hf_to_ide x \\<in> Collect ide\"\n        using hf_to_ide_def by simp\n    qed\n\n    lemma hf_to_ide_ide_to_hf:\n    assumes \"a \\<in> Collect ide\"\n    shows \"hf_to_ide (ide_to_hf a) = a\"\n    proof -\n      have \"hf_to_ide (ide_to_hf a) = mkIde (arr_of ` hfset (HF (elem_of ` set a)))\"\n        using hf_to_ide_def ide_to_hf_def by simp\n      also have \"... = a\"\n      proof -\n        have \"mkIde (arr_of ` hfset (HF (elem_of ` set a))) = mkIde (arr_of ` elem_of ` set a)\"\n        proof -\n          have \"finite (set a)\"\n            using assms set_ide_char by blast\n          hence \"finite (elem_of ` set a)\"\n            by simp\n          hence \"hfset (HF (elem_of ` set a)) = elem_of ` set a\"\n            using hfset_HF [of \"elem_of ` set a\"] by simp\n          thus ?thesis by simp\n        qed\n        also have \"... = a\"\n        proof -\n          have \"set a \\<subseteq> Univ\"\n            using assms set_ide_char by blast\n          hence \"\\<And>x. x \\<in> set a \\<Longrightarrow> arr_of (elem_of x) = x\"\n            using assms by auto\n          hence \"arr_of ` elem_of ` set a = set a\"\n            by force\n          thus ?thesis\n            using assms ide_char mkIde_set by simp\n        qed\n        finally show ?thesis by blast\n      qed\n      finally show \"hf_to_ide (ide_to_hf a) = a\" by blast\n    qed\n\n    lemma ide_to_hf_hf_to_ide:\n    assumes \"x \\<in> UNIV\"\n    shows \"ide_to_hf (hf_to_ide x) = x\"\n    proof -\n      have \"HF (elem_of ` set (mkIde (arr_of ` hfset x))) = x\"\n      proof -\n        have \"HF (elem_of ` set (mkIde (arr_of ` hfset x))) = HF (elem_of ` arr_of ` hfset x)\"\n          using assms set_mkIde [of \"arr_of ` hfset x\"] arr_of_mapsto mkIde_def by auto\n        also have \"... = HF (hfset x)\"\n        proof -\n          have \"\\<And>A. elem_of ` arr_of ` A = A\"\n            using elem_of_arr_of by force\n          thus ?thesis by metis\n        qed\n        also have \"... = x\" by simp\n        finally show ?thesis by blast\n      qed\n      thus ?thesis\n        using assms ide_to_hf_def hf_to_ide_def by simp\n    qed\n\n    lemma bij_betw_ide_hf_set:\n    shows \"bij_betw ide_to_hf (Collect ide) (UNIV :: hf set)\"\n      using ide_to_hf_mapsto hf_to_ide_mapsto ide_to_hf_hf_to_ide hf_to_ide_ide_to_hf\n      by (intro bij_betwI) auto\n\n    lemma ide_implies_finite_set:\n    assumes \"ide a\"\n    shows \"finite (set a)\" and \"finite (hom unity a)\"\n    proof -\n      show 1: \"finite (set a)\"\n        using assms set_ide_char by blast\n      show \"finite (hom unity a)\"\n        using assms 1 bij_betw_points_and_set finite_imageD inj_img set_def by auto\n    qed\n\n    text\\<open>\n      We establish the connection between the membership relation defined for hereditarily\n      finite sets and the corresponding membership relation associated with the set category.\n    \\<close>\n\n    lemma arr_of_membI [intro]:\n    assumes \"x \\<^bold>\\<in> ide_to_hf a\"\n    shows \"arr_of x \\<in> set a\"\n    proof -\n      let ?X = \"inv_into (set a) elem_of x\"\n      have \"x = elem_of ?X \\<and> ?X \\<in> set a\"\n        using assms\n        by (simp add: f_inv_into_f ide_to_hf_def inv_into_into)\n      thus ?thesis\n        by (metis (no_types, lifting) arr_of_elem_of elem_set_implies_incl_in\n            elem_set_implies_set_eq_singleton incl_in_def mem_Collect_eq terminal_char2)\n    qed\n\n    lemma elem_of_membI [intro]:\n    assumes \"ide a\" and \"x \\<in> set a\"\n    shows \"elem_of x \\<^bold>\\<in> ide_to_hf a\"\n    proof -\n      have \"finite (elem_of ` set a)\"\n        using assms ide_implies_finite_set [of a] by simp\n      hence \"elem_of x \\<in> hfset (ide_to_hf a)\"\n        using assms ide_to_hf_def hfset_HF [of \"elem_of ` set a\"] by simp\n      thus ?thesis\n        using hmem_def by blast\n    qed\n\n    text\\<open>\n      We show that each hom-set \\<open>hom a b\\<close> is in bijective correspondence with\n      the elements of the hereditarily finite set \\<open>hfun (ide_to_hf a) (ide_to_hf b)\\<close>.\n    \\<close>\n\n    definition arr_to_hfun\n    where \"arr_to_hfun f = \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (dom f) * ide_to_hf (cod f).\n                              hsnd XY = elem_of (Fun f (arr_of (hfst XY)))\\<rbrace>\"\n\n    definition hfun_to_arr\n    where \"hfun_to_arr B C F =\n           mkArr (arr_of ` hfset B) (arr_of ` hfset C) (\\<lambda>x. arr_of (happ F (elem_of x)))\"\n\n    lemma hfun_arr_to_hfun:\n    assumes \"arr f\"\n    shows \"hfun (ide_to_hf (dom f)) (ide_to_hf (cod f)) (arr_to_hfun f)\"\n    proof\n      show \"arr_to_hfun f \\<le> ide_to_hf (dom f) * ide_to_hf (cod f)\"\n        using assms arr_to_hfun_def by auto\n      show \"\\<And>X. X \\<^bold>\\<in> ide_to_hf (dom f) \\<Longrightarrow> \\<exists>!Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> arr_to_hfun f\"\n      proof\n        fix X\n        assume X: \"X \\<^bold>\\<in> ide_to_hf (dom f)\"\n        show \"\\<langle>X, elem_of (Fun f (arr_of X))\\<rangle> \\<^bold>\\<in> arr_to_hfun f\"\n        proof -\n          have \"\\<langle>X, elem_of (Fun f (arr_of X))\\<rangle> \\<^bold>\\<in> \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (dom f) * ide_to_hf (cod f).\n                     hsnd XY = elem_of (Fun f (arr_of (hfst XY)))\\<rbrace>\"\n          proof -\n            have \"hsnd \\<langle>X, elem_of (Fun f (arr_of X))\\<rangle> =\n                  elem_of (Fun f (arr_of (hfst \\<langle>X, elem_of (Fun f (arr_of X))\\<rangle>)))\"\n              using assms X by simp\n            moreover have \"\\<langle>X, elem_of (Fun f (arr_of X))\\<rangle> \\<^bold>\\<in> ide_to_hf (dom f) * ide_to_hf (cod f)\"\n            proof -\n              have \"elem_of (Fun f (arr_of X)) \\<^bold>\\<in> ide_to_hf (cod f)\"\n              proof (intro elem_of_membI)\n                show \"ide (cod f)\"\n                  using assms ide_cod by simp\n                show \"Fun f (arr_of X) \\<in> Cod f\"\n                  using assms X Fun_mapsto arr_of_membI by auto\n              qed\n              thus ?thesis\n                using X by simp\n            qed\n            ultimately show ?thesis by simp\n          qed\n          thus ?thesis\n            using arr_to_hfun_def by simp\n        qed\n        fix Y\n        assume XY: \"\\<langle>X, Y\\<rangle> \\<^bold>\\<in> arr_to_hfun f\"\n        show \"Y = elem_of (Fun f (arr_of X))\"\n          using assms X XY arr_to_hfun_def by auto\n      qed\n      show \"\\<And>X Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> arr_to_hfun f \\<Longrightarrow> Y \\<^bold>\\<in> ide_to_hf (cod f)\"\n        using assms arr_to_hfun_def ide_to_hf_def\n              \\<open>arr_to_hfun f \\<le> ide_to_hf (dom f) * ide_to_hf (cod f)\\<close>\n        by blast\n    qed\n\n    lemma arr_to_hfun_in_hexp:\n    assumes \"arr f\"\n    shows \"arr_to_hfun f \\<^bold>\\<in> hexp (ide_to_hf (dom f)) (ide_to_hf (cod f))\"\n      using assms arr_to_hfun_def hfun_arr_to_hfun hexp_def by auto\n\n    lemma hfun_to_arr_in_hom:\n    assumes \"hfun B C F\"\n    shows \"\\<guillemotleft>hfun_to_arr B C F : hf_to_ide B \\<rightarrow> hf_to_ide C\\<guillemotright>\"\n    proof\n      let ?f = \"mkArr (arr_of ` hfset B) (arr_of ` hfset C) (\\<lambda>x. arr_of (happ F (elem_of x)))\"\n      have 0: \"arr ?f\"\n      proof -\n        have \"arr_of ` hfset B \\<subseteq> Univ \\<and> arr_of ` hfset C \\<subseteq> Univ\"\n          using arr_of_mapsto by auto\n        moreover have \"(\\<lambda>x. arr_of (happ F (elem_of x))) \\<in> arr_of ` hfset B \\<rightarrow> arr_of ` hfset C\"\n        proof\n          fix x\n          assume x: \"x \\<in> arr_of ` hfset B\"\n          have \"happ F (elem_of x) \\<in> hfset C\"\n            using assms x happ_mapsto hfun_in_hexp\n            by (metis elem_of_arr_of HF_hfset finite_hfset hmem_HF_iff imageE)\n          thus \"arr_of (happ F (elem_of x)) \\<in> arr_of ` hfset C\"\n            by simp\n        qed\n        ultimately show ?thesis\n          using arr_mkArr\n          by (meson finite_hfset finite_iff_ordLess_natLeq finite_imageI)\n      qed\n      show 1: \"arr (hfun_to_arr B C F)\"\n        using 0 hfun_to_arr_def by simp\n      show \"dom (hfun_to_arr B C F) = hf_to_ide B\"\n        using 1 hfun_to_arr_def hf_to_ide_def dom_mkArr by auto\n      show \"cod (hfun_to_arr B C F) = hf_to_ide C\"\n        using 1 hfun_to_arr_def hf_to_ide_def cod_mkArr by auto\n    qed\n\n    text\\<open>\n      The comprehension notation from @{theory HereditarilyFinite.HF} interferes in an\n      unfortunate way with the restriction notation from @{theory \"HOL-Library.FuncSet\"},\n      making it impossible to use both in the present context.\n    \\<close>\n\n    lemma Fun_char:\n    assumes \"arr f\"\n    shows \"Fun f = restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f)\"\n    proof\n      fix x\n      show \"Fun f x = restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f) x\"\n      proof (cases \"x \\<in> Dom f\")\n        show \"x \\<notin> Dom f \\<Longrightarrow> ?thesis\"\n          using assms Fun_mapsto Fun_def restrict_apply by simp\n        show \"x \\<in> Dom f \\<Longrightarrow> ?thesis\"\n        proof -\n          assume x: \"x \\<in> Dom f\"\n          have 1: \"hfun (ide_to_hf (dom f)) (ide_to_hf (cod f)) (arr_to_hfun f)\"\n            using assms app_def arr_to_hfun_def hfun_arr_to_hfun\n                  the1_equality [of \"\\<lambda>y. \\<langle>elem_of x, y\\<rangle> \\<^bold>\\<in> arr_to_hfun f\" \"elem_of (Fun f x)\"]\n            by simp\n          have 2: \"\\<exists>!Y. \\<langle>elem_of x, Y\\<rangle> \\<^bold>\\<in> arr_to_hfun f\"\n            using assms x 1 hfunE elem_of_membI ide_dom\n            by (metis (no_types, lifting))\n          have \"Fun f x = arr_of (elem_of (Fun f x))\"\n          proof -\n            have \"Fun f x \\<in> Univ\"\n              using assms x ide_cod Fun_mapsto [of f] set_ide_char by blast\n            thus ?thesis\n              using arr_of_elem_of by simp\n          qed\n          also have \"... = arr_of (happ (arr_to_hfun f) (elem_of x))\"\n          proof -\n            have \"\\<langle>elem_of x, elem_of (Fun f x)\\<rangle> \\<^bold>\\<in> arr_to_hfun f\"\n            proof -\n              have \"\\<langle>elem_of x, elem_of (Fun f x)\\<rangle> \\<^bold>\\<in> ide_to_hf (dom f) * ide_to_hf (cod f)\"\n                using assms x ide_dom ide_cod Fun_mapsto by fast\n              moreover have \"elem_of (Fun f x) = elem_of (Fun f (arr_of (elem_of x)))\"\n                by (metis (no_types, lifting) arr_of_elem_of setp_set_ide assms ide_dom subsetD x)\n              ultimately show ?thesis\n                using arr_to_hfun_def by auto\n            qed\n            moreover have \"\\<langle>elem_of x, happ (arr_to_hfun f) (elem_of x)\\<rangle> \\<^bold>\\<in> arr_to_hfun f\"\n              using assms x 1 2 app_equality hfun_def by blast\n            ultimately show ?thesis\n              using 2 by fastforce\n          qed\n          also have \"... = restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f) x\"\n            using assms x ide_dom by auto\n          finally show ?thesis by simp\n        qed\n      qed\n    qed\n\n    lemma Fun_hfun_to_arr:\n    assumes \"hfun B C F\"\n    shows \"Fun (hfun_to_arr B C F) = restrict (\\<lambda>x. arr_of (happ F (elem_of x))) (arr_of ` hfset B)\"\n    proof -\n      have \"arr (hfun_to_arr B C F)\"\n        using assms hfun_to_arr_in_hom by blast\n      hence \"arr (mkArr (arr_of ` hfset B) (arr_of ` hfset C) (\\<lambda>x. arr_of (happ F (elem_of x))))\"\n        using hfun_to_arr_def by simp\n      thus ?thesis\n        using assms hfun_to_arr_def Fun_mkArr by simp\n    qed\n\n    lemma arr_of_img_hfset_ide_to_hf:\n    assumes \"ide a\"\n    shows \"arr_of ` hfset (ide_to_hf a) = set a\"\n    proof -\n      have \"arr_of ` hfset (ide_to_hf a) = arr_of ` hfset (HF (elem_of ` set a))\"\n        using ide_to_hf_def by simp\n      also have \"... = arr_of ` elem_of ` set a\"\n        using assms ide_implies_finite_set(1) ide_char by auto\n      also have \"... = set a\"\n      proof -\n        have \"\\<And>x. x \\<in> set a \\<Longrightarrow> arr_of (elem_of x) = x\"\n          using assms ide_char arr_of_elem_of setp_set_ide by blast\n        thus ?thesis by force\n      qed\n      finally show ?thesis by blast\n    qed\n\n    lemma hfun_to_arr_arr_to_hfun:\n    assumes \"arr f\"\n    shows \"hfun_to_arr (ide_to_hf (dom f)) (ide_to_hf (cod f)) (arr_to_hfun f) = f\"\n    proof -\n      have 0: \"hfun_to_arr (ide_to_hf (dom f)) (ide_to_hf (cod f)) (arr_to_hfun f) =\n               mkArr (arr_of ` hfset (ide_to_hf (dom f))) (arr_of ` hfset (ide_to_hf (cod f)))\n                     (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x)))\"\n        unfolding hfun_to_arr_def by blast\n      also have \"... = mkArr (Dom f) (Cod f)\n                             (restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f))\"\n      proof (intro mkArr_eqI)\n        show 1: \"arr_of ` hfset (ide_to_hf (dom f)) = Dom f\"\n          using assms arr_of_img_hfset_ide_to_hf ide_dom by simp\n        show 2: \"arr_of ` hfset (ide_to_hf (cod f)) = Cod f\"\n          using assms arr_of_img_hfset_ide_to_hf ide_cod by simp\n        show \"arr (mkArr (arr_of ` hfset (ide_to_hf (dom f))) (arr_of ` hfset (ide_to_hf (cod f)))\n                         (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))))\"\n          using 0 1 2\n          by (metis (no_types, lifting) arrI assms hfun_arr_to_hfun hfun_to_arr_in_hom)\n        show \"\\<And>x. x \\<in> arr_of ` hfset (ide_to_hf (dom f)) \\<Longrightarrow>\n                     arr_of (happ (arr_to_hfun f) (elem_of x)) =\n                     restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f) x\"\n          using assms 1 by simp\n      qed\n      also have \"... = mkArr (Dom f) (Cod f) (Fun f)\"\n        using assms Fun_char mkArr_eqI by simp\n      also have \"... = f\"\n        using assms mkArr_Fun by blast\n      finally show ?thesis by simp\n    qed\n\n    lemma arr_to_hfun_hfun_to_arr:\n    assumes \"hfun B C F\"\n    shows \"arr_to_hfun (hfun_to_arr B C F) = F\"\n    proof -\n      have \"arr_to_hfun (hfun_to_arr B C F) =\n            \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (dom (hfun_to_arr B C F)) * ide_to_hf (cod (hfun_to_arr B C F)).\n               hsnd XY = elem_of (Fun (hfun_to_arr B C F) (arr_of (hfst XY)))\\<rbrace>\"\n        unfolding arr_to_hfun_def by blast\n      also have\n          \"... = \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C)).\n                    hsnd XY = elem_of (Fun (hfun_to_arr B C F) (arr_of (hfst XY)))\\<rbrace>\"\n        using assms hfun_to_arr_in_hom [of B C F] hf_to_ide_def\n        by (metis (no_types, lifting) in_homE)\n      also have\n          \"... = \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C)).\n                    hsnd XY = elem_of (restrict (\\<lambda>x. arr_of (happ F (elem_of x))) (arr_of ` hfset B)\n                                   (arr_of (hfst XY)))\\<rbrace>\"\n        using assms Fun_hfun_to_arr by simp\n      also have\n          \"... = \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C)).\n                    hsnd XY = elem_of (arr_of (happ F (elem_of (arr_of (hfst XY)))))\\<rbrace>\"\n      proof -\n        have\n          1: \"\\<And>XY. XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C))\n                     \\<Longrightarrow> arr_of (hfst XY) \\<in> arr_of ` hfset B\"\n        proof -\n          fix XY\n          assume\n            XY: \"XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C))\"\n          have \"hfst XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B))\"\n            using XY by auto\n          thus \"arr_of (hfst XY) \\<in> arr_of ` hfset B\"\n            using assms arr_of_membI [of \"hfst XY\" \"mkIde (arr_of ` hfset B)\"] set_mkIde\n            by (metis (mono_tags, lifting) arrI arr_mkArr hfun_to_arr_def hfun_to_arr_in_hom)\n        qed\n        show ?thesis\n        proof -\n          have\n            \"\\<And>XY. (XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C)) \\<and>\n                     hsnd XY = elem_of (restrict (\\<lambda>x. arr_of (happ F (elem_of x))) (arr_of ` hfset B)\n                                       (arr_of (hfst XY))))\n                   \\<longleftrightarrow>\n                   (XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C)) \\<and>\n                     hsnd XY = elem_of (arr_of (happ F (elem_of (arr_of (hfst XY))))))\"\n            using 1 by auto\n          thus ?thesis by blast\n        qed\n      qed\n      also have\n        \"... = \\<lbrace>XY \\<^bold>\\<in> ide_to_hf (mkIde (arr_of ` hfset B)) * ide_to_hf (mkIde (arr_of ` hfset C)).\n                  hsnd XY = happ F (hfst XY)\\<rbrace>\"\n        by simp\n      also have \"... = \\<lbrace>XY \\<^bold>\\<in> B * C. hsnd XY = happ F (hfst XY)\\<rbrace>\"\n        using assms hf_to_ide_def ide_to_hf_hf_to_ide by force\n      also have \"... = F\"\n        using assms happ_expansion by simp\n      finally show ?thesis by simp\n    qed\n\n    lemma bij_betw_hom_hfun:\n    assumes \"ide a\" and \"ide b\"\n    shows \"bij_betw arr_to_hfun (hom a b) {F. hfun (ide_to_hf a) (ide_to_hf b) F}\"\n    proof (intro bij_betwI)\n      show \"arr_to_hfun \\<in> hom a b \\<rightarrow> {F. hfun (ide_to_hf a) (ide_to_hf b) F}\"\n        using assms arr_to_hfun_in_hexp hexp_def hfun_arr_to_hfun by blast\n      show \"hfun_to_arr (ide_to_hf a) (ide_to_hf b)\n              \\<in> {F. hfun (ide_to_hf a) (ide_to_hf b) F} \\<rightarrow> hom a b\"\n        using assms hfun_to_arr_in_hom\n        by (metis (no_types, lifting) Pi_I hf_to_ide_ide_to_hf mem_Collect_eq)\n      show \"\\<And>x. x \\<in> hom a b \\<Longrightarrow> hfun_to_arr (ide_to_hf a) (ide_to_hf b) (arr_to_hfun x) = x\"\n        using assms hfun_to_arr_arr_to_hfun by blast\n      show \"\\<And>y. y \\<in> {F. hfun (ide_to_hf a) (ide_to_hf b) F} \\<Longrightarrow>\n                  arr_to_hfun (hfun_to_arr (ide_to_hf a) (ide_to_hf b) y) = y\"\n        using assms arr_to_hfun_hfun_to_arr by simp\n    qed\n\n    text\\<open>\n      We next relate composition of arrows in the category to the corresponding operation\n      on hereditarily finite sets.\n    \\<close>\n\n    definition hcomp\n    where \"hcomp G F =\n           \\<lbrace>XZ \\<^bold>\\<in> hdomain F * hrange G. hsnd XZ = happ G (happ F (hfst XZ))\\<rbrace>\"\n\n    lemma hfun_hcomp:\n    assumes \"hfun A B F\" and \"hfun B C G\"\n    shows \"hfun A C (hcomp G F)\"\n    proof\n      show \"hcomp G F \\<le> A * C\"\n        using assms hcomp_def hfun_def by auto\n      show \"\\<And>X. X \\<^bold>\\<in> A \\<Longrightarrow> \\<exists>!Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> hcomp G F\"\n      proof\n        fix X\n        assume X: \"X \\<^bold>\\<in> A\"\n        show \"\\<langle>X, happ G (happ F X)\\<rangle> \\<^bold>\\<in> hcomp G F\"\n          unfolding hcomp_def\n          using assms X hfunE happ_mapsto hfun_in_hexp\n          by (metis (mono_tags, lifting) HCollect_iff hfst_conv hfun_def hsnd_conv timesI)\n        show \"\\<And>X Y. \\<lbrakk>X \\<^bold>\\<in> A; \\<langle>X, Y\\<rangle> \\<^bold>\\<in> hcomp G F\\<rbrakk> \\<Longrightarrow> Y = happ G (happ F X)\"\n          unfolding hcomp_def by simp\n      qed\n      show \"\\<And>X Y. \\<langle>X, Y\\<rangle> \\<^bold>\\<in> hcomp G F \\<Longrightarrow> Y \\<^bold>\\<in> C\"\n        unfolding hcomp_def\n        using assms hfunE happ_mapsto hfun_in_hexp\n        by (metis HCollectE hfun_def hsubsetCE timesD2)\n    qed\n\n    lemma arr_to_hfun_comp:\n    assumes \"seq g f\"\n    shows \"arr_to_hfun (comp g f) = hcomp (arr_to_hfun g) (arr_to_hfun f)\"\n    proof -\n      have 1: \"hdomain (arr_to_hfun f) = ide_to_hf (dom f)\"\n        using assms hfun_arr_to_hfun hfun_def by blast\n      have \"arr_to_hfun (comp g f) =\n            \\<lbrace>XZ \\<^bold>\\<in> ide_to_hf (dom f) * ide_to_hf (cod g).\n               hsnd XZ = elem_of (Fun (comp g f) (arr_of (hfst XZ)))\\<rbrace>\"\n        unfolding arr_to_hfun_def comp_def\n        using assms by fastforce\n      also have \"... = \\<lbrace>XZ \\<^bold>\\<in> hdomain (arr_to_hfun f) * hrange (arr_to_hfun g).\n                          hsnd XZ = happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\\<rbrace>\"\n      proof\n        fix XZ\n        have \"hfst XZ \\<^bold>\\<in> hdomain (arr_to_hfun f)\n                 \\<Longrightarrow> hsnd XZ \\<^bold>\\<in> ide_to_hf (cod g) \\<and>\n                       hsnd XZ = elem_of (Fun (comp g f) (arr_of (hfst XZ)))\n                      \\<longleftrightarrow>\n                     hsnd XZ \\<^bold>\\<in> hrange (arr_to_hfun g) \\<and>\n                       hsnd XZ = happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\"\n        proof\n          assume XZ: \"hfst XZ \\<^bold>\\<in> hdomain (arr_to_hfun f)\"\n          have 2: \"arr_of (hfst XZ) \\<in> Dom f\"\n            using XZ 1 hfsetcat.arr_of_membI by auto\n          have 3: \"arr_of (happ (arr_to_hfun f) (hfst XZ)) \\<in> Dom g\"\n            using assms XZ 2\n            by (metis (no_types, lifting) \"1\" happ_mapsto(1) hfsetcat.arr_of_membI\n                arr_to_hfun_in_hexp seqE)\n          have 4: \"elem_of (Fun (comp g f) (arr_of (hfst XZ))) =\n                   happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\"\n          proof -\n            have \"elem_of (Fun (comp g f) (arr_of (hfst XZ))) =\n                  elem_of (restrict (Fun g o Fun f) (Dom f) (arr_of (hfst XZ)))\"\n              using assms Fun_comp Fun_char by simp\n            also have \"... = elem_of ((Fun g o Fun f) (arr_of (hfst XZ)))\"\n              using XZ 2 by auto\n            also have \"... = elem_of (Fun g (Fun f (arr_of (hfst XZ))))\"\n              by simp\n            also have\n              \"... = elem_of (Fun g (restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f)\n                                           (arr_of (hfst XZ))))\"\n            proof -\n              have \"Fun f = restrict (\\<lambda>x. arr_of (happ (arr_to_hfun f) (elem_of x))) (Dom f)\"\n                using assms Fun_char [of f] by blast\n              thus ?thesis by simp\n            qed\n            also have \"... = elem_of (Fun g (arr_of (happ (arr_to_hfun f) (hfst XZ))))\"\n              using 2 by simp\n            also have \"... = elem_of (restrict (\\<lambda>x. arr_of (happ (arr_to_hfun g) (elem_of x))) (Dom g)\n                                            (arr_of (happ (arr_to_hfun f) (hfst XZ))))\"\n            proof -\n              have \"Fun g = restrict (\\<lambda>x. arr_of (happ (arr_to_hfun g) (elem_of x))) (Dom g)\"\n                using assms Fun_char [of g] by blast\n              thus ?thesis by simp\n            qed\n            also have \"... = happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\"\n              using 3 by simp\n            finally show ?thesis by blast\n          qed\n          have 5: \"elem_of (Fun (comp g f) (arr_of (hfst XZ))) \\<^bold>\\<in> hrange (arr_to_hfun g)\"\n          proof -\n            have \"happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ)) \\<^bold>\\<in> hrange (arr_to_hfun g)\"\n              using assms 1 3 XZ hfun_arr_to_hfun happ_mapsto arr_to_hfun_in_hexp arr_to_hfun_def\n              by (metis (no_types, lifting) seqE)\n            thus ?thesis\n              using XZ 4 by simp\n          qed\n          show \"hsnd XZ \\<^bold>\\<in> ide_to_hf (cod g) \\<and>\n                  hsnd XZ = elem_of (Fun (comp g f) (arr_of (hfst XZ)))\n                          \\<Longrightarrow>\n                hsnd XZ \\<^bold>\\<in> hrange (arr_to_hfun g) \\<and>\n                  hsnd XZ = happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\"\n            using XZ 4 5 by simp\n          show \"hsnd XZ \\<^bold>\\<in> hrange (arr_to_hfun g) \\<and>\n                  hsnd XZ = happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\n                          \\<Longrightarrow>\n                hsnd XZ \\<^bold>\\<in> ide_to_hf (cod g) \\<and>\n                  hsnd XZ = elem_of (Fun (comp g f) (arr_of (hfst XZ)))\"\n            using assms XZ 1 4\n            by (metis (no_types, lifting) arr_to_hfun_in_hexp happ_mapsto(1) seqE)\n        qed\n        thus \"XZ \\<^bold>\\<in> \\<lbrace>XZ \\<^bold>\\<in> ide_to_hf (dom f) * ide_to_hf (cod g).\n                      hsnd XZ = elem_of (Fun (comp g f) (arr_of (hfst XZ)))\\<rbrace>\n                \\<longleftrightarrow>\n              XZ \\<^bold>\\<in> \\<lbrace>XZ \\<^bold>\\<in> hdomain (arr_to_hfun f) * hrange (arr_to_hfun g).\n                      hsnd XZ = happ (arr_to_hfun g) (happ (arr_to_hfun f) (hfst XZ))\\<rbrace>\"\n          using 1 is_hpair_def by auto\n      qed\n      also have \"... = hcomp (arr_to_hfun g) (arr_to_hfun f)\"\n        using assms arr_to_hfun_def hcomp_def by simp\n      finally show ?thesis by simp\n    qed\n\n    lemma hfun_to_arr_hcomp:\n    assumes \"hfun A B F\" and \"hfun B C G\"\n    shows \"hfun_to_arr A C (hcomp G F) = comp (hfun_to_arr B C G) (hfun_to_arr A B F)\"\n    proof -\n      have 1: \"arr_to_hfun (hfun_to_arr A C (hcomp G F)) =\n               arr_to_hfun (comp (hfun_to_arr B C G) (hfun_to_arr A B F))\"\n      proof -\n        have \"arr_to_hfun (comp (hfun_to_arr B C G) (hfun_to_arr A B F)) =\n              hcomp (arr_to_hfun (hfun_to_arr B C G)) (arr_to_hfun (hfun_to_arr A B F))\"\n          using assms arr_to_hfun_comp hfun_to_arr_in_hom by blast\n        also have \"... = hcomp G F\"\n          using assms by (simp add: arr_to_hfun_hfun_to_arr)\n        also have \"... = arr_to_hfun (hfun_to_arr A C (hcomp G F))\"\n        proof -\n          have \"hfun A C (hcomp G F)\"\n            using assms hfun_hcomp by simp\n          thus ?thesis\n            by (simp add: arr_to_hfun_hfun_to_arr)\n        qed\n        finally show ?thesis by simp\n      qed\n      show ?thesis\n      proof -\n        have \"hfun_to_arr A C (hcomp G F) \\<in> hom (hf_to_ide A) (hf_to_ide C)\"\n          using assms hfun_hcomp hf_to_ide_def hfun_to_arr_in_hom by auto\n        moreover have \"comp (hfun_to_arr B C G) (hfun_to_arr A B F)\n                          \\<in> hom (hf_to_ide A) (hf_to_ide C)\"\n          using assms hfun_to_arr_in_hom hf_to_ide_def\n          by (metis (no_types, lifting) comp_in_homI mem_Collect_eq)\n        moreover have \"inj_on arr_to_hfun (hom (hf_to_ide A) (hf_to_ide C))\"\n        proof -\n          have \"ide (hf_to_ide A) \\<and> ide (hf_to_ide C)\"\n            using assms hf_to_ide_mapsto by auto\n          thus ?thesis\n            using bij_betw_hom_hfun [of \"hf_to_ide A\" \"hf_to_ide C\"] bij_betw_imp_inj_on\n            by auto\n        qed\n        ultimately show ?thesis\n          using 1 inj_on_def [of arr_to_hfun \"hom (hf_to_ide A) (hf_to_ide C)\"] by simp\n      qed\n    qed\n\n    section \"Binary Products\"\n\n    text\\<open>\n      The category of hereditarily finite sets has binary products,\n      given by cartesian product of sets in the usual way.\n    \\<close>\n\n    definition prod\n    where \"prod a b = hf_to_ide (ide_to_hf a * ide_to_hf b)\"\n\n    definition pr0\n    where \"pr0 a b = (if ide a \\<and> ide b then\n                         mkArr (set (prod a b)) (set b) (\\<lambda>x. arr_of (hsnd (elem_of x)))\n                      else null)\"\n\n    definition pr1\n    where \"pr1 a b = (if ide a \\<and> ide b then\n                         mkArr (set (prod a b)) (set a) (\\<lambda>x. arr_of (hfst (elem_of x)))\n                      else null)\"\n\n    definition tuple\n    where \"tuple f g = mkArr (set (dom f)) (set (prod (cod f) (cod g)))\n                             (\\<lambda>x. arr_of (hpair (elem_of (Fun f x)) (elem_of (Fun g x))))\"\n\n    lemma ide_prod:\n    assumes \"ide a\" and \"ide b\"\n    shows \"ide (prod a b)\"\n      using assms prod_def hf_to_ide_mapsto ide_to_hf_mapsto by auto\n\n    lemma pr1_in_hom [intro]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<guillemotleft>pr1 a b : prod a b \\<rightarrow> a\\<guillemotright>\"\n    proof\n      show 0: \"arr (pr1 a b)\"\n      proof -\n        have \"set (prod a b) \\<subseteq> Univ \\<and> finite (set (prod a b))\"\n          using assms ide_implies_finite_set(1) set_ideD(1) ide_prod by presburger\n        moreover have \"set a \\<subseteq> Univ \\<and> finite (set a)\"\n          using assms ide_char set_ide_char by blast\n        moreover have \"(\\<lambda>x. arr_of (hfst (elem_of x))) \\<in> set (prod a b) \\<rightarrow> set a\"\n        proof (unfold prod_def)\n          show \"(\\<lambda>x. arr_of (hfst (elem_of x))) \\<in> set (hf_to_ide (ide_to_hf a * ide_to_hf b)) \\<rightarrow> set a\"\n          proof\n            fix x\n              assume x: \"x \\<in> set (hf_to_ide (ide_to_hf a * ide_to_hf b))\"\n              have \"elem_of x \\<in> hfset (ide_to_hf a * ide_to_hf b)\"\n                using assms ide_char x\n                by (metis (no_types, lifting) prod_def elem_of_membI HF_hfset UNIV_I hmem_HF_iff\n                    ide_prod ide_to_hf_hf_to_ide)\n              hence \"hfst (elem_of x) \\<^bold>\\<in> ide_to_hf a\"\n                by (metis HF_hfset finite_hfset hfst_conv hmem_HF_iff timesE)\n              thus \"arr_of (hfst (elem_of x)) \\<in> set a\"\n                using arr_of_membI by simp\n          qed\n        qed\n        ultimately show ?thesis\n          unfolding pr1_def\n          using assms arr_mkArr finite_imp_setp by presburger\n      qed\n      show \"dom (pr1 a b) = prod a b\"\n        using assms 0 ide_char ide_prod dom_mkArr\n        by (metis (no_types, lifting) mkIde_set pr1_def)\n      show \"cod (pr1 a b) = a\"\n        using assms 0 ide_char ide_prod cod_mkArr\n        by (metis (no_types, lifting) mkIde_set pr1_def)\n    qed\n\n    lemma pr1_simps [simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"arr (pr1 a b)\" and \"dom (pr1 a b) = prod a b\" and \"cod (pr1 a b) = a\"\n      using assms pr1_in_hom by blast+\n\n    lemma pr0_in_hom [intro]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"\\<guillemotleft>pr0 a b : prod a b \\<rightarrow> b\\<guillemotright>\"\n    proof\n      show 0: \"arr (pr0 a b)\"\n      proof -\n        have \"set (prod a b) \\<subseteq> Univ \\<and> finite (set (prod a b))\"\n          using setp_set_ide assms ide_implies_finite_set(1) ide_prod by presburger\n        moreover have \"set b \\<subseteq> Univ \\<and> finite (set b)\"\n          using assms ide_char set_ide_char by blast\n        moreover have \"(\\<lambda>x. arr_of (hsnd (elem_of x))) \\<in> set (prod a b) \\<rightarrow> set b\"\n        proof (unfold prod_def)\n          show \"(\\<lambda>x. arr_of (hsnd (elem_of x))) \\<in> set (hf_to_ide (ide_to_hf a * ide_to_hf b)) \\<rightarrow> set b\"\n          proof\n            fix x\n              assume x: \"x \\<in> set (hf_to_ide (ide_to_hf a * ide_to_hf b))\"\n              have \"elem_of x \\<in> hfset (ide_to_hf a * ide_to_hf b)\"\n                using assms ide_char x\n                by (metis (no_types, lifting) prod_def elem_of_membI HF_hfset UNIV_I hmem_HF_iff\n                    ide_prod ide_to_hf_hf_to_ide)\n              hence \"hsnd (elem_of x) \\<^bold>\\<in> ide_to_hf b\"\n                by (metis HF_hfset finite_hfset hsnd_conv hmem_HF_iff timesE)\n              thus \"arr_of (hsnd (elem_of x)) \\<in> set b\"\n                using arr_of_membI by simp\n          qed\n        qed\n        ultimately show ?thesis\n          unfolding pr0_def\n          using assms arr_mkArr finite_imp_setp by presburger\n      qed\n      show \"dom (pr0 a b) = prod a b\"\n        using assms 0 ide_char ide_prod dom_mkArr\n        by (metis (no_types, lifting) mkIde_set pr0_def)\n      show \"cod (pr0 a b) = b\"\n        using assms 0 ide_char ide_prod cod_mkArr\n        by (metis (no_types, lifting) mkIde_set pr0_def)\n    qed\n\n    lemma pr0_simps [simp]:\n    assumes \"ide a\" and \"ide b\"\n    shows \"arr (pr0 a b)\" and \"dom (pr0 a b) = prod a b\" and \"cod (pr0 a b) = b\"\n      using assms pr0_in_hom by blast+\n\n    lemma arr_of_tuple_elem_of_membI:\n    assumes \"span f g\" and \"x \\<in> Dom f\"\n    shows \"arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle> \\<in> set (prod (cod f) (cod g))\"\n    proof -\n      have \"Fun f x \\<in> set (cod f)\"\n        using assms Fun_mapsto by blast\n      moreover have \"Fun g x \\<in> set (cod g)\"\n        using assms Fun_mapsto by auto\n      ultimately have \"\\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>\n                          \\<^bold>\\<in> ide_to_hf (cod f) * ide_to_hf (cod g)\"\n        using assms ide_cod by auto\n      moreover have \"set (prod (cod f) (cod g)) \\<subseteq> Univ\"\n        using setp_set_ide assms(1) ide_cod ide_prod by presburger\n      ultimately show ?thesis\n        using prod_def arr_of_membI ide_to_hf_hf_to_ide by auto\n    qed\n\n    lemma tuple_in_hom [intro]:\n    assumes \"span f g\"\n    shows \"\\<guillemotleft>tuple f g : dom f \\<rightarrow> prod (cod f) (cod g)\\<guillemotright>\"\n    proof\n      show 1: \"arr (tuple f g)\"\n      proof -\n        have \"Dom f \\<subseteq> Univ \\<and> finite (Dom f)\"\n          using assms set_ideD(1) ide_dom ide_implies_finite_set(1) by presburger\n        moreover have \"set (prod (cod f) (cod g)) \\<subseteq> Univ \\<and> finite (set (prod (cod f) (cod g)))\"\n          using assms set_ideD(1) ide_cod ide_prod ide_implies_finite_set(1) by presburger\n        moreover have \"(\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>)\n                          \\<in> Dom f \\<rightarrow> set (prod (cod f) (cod g))\"\n          using assms arr_of_tuple_elem_of_membI by simp\n        ultimately show ?thesis\n          using assms ide_prod tuple_def arr_mkArr ide_dom ide_cod by simp\n      qed\n      show \"dom (tuple f g) = dom f\"\n        using assms 1 dom_mkArr ide_dom mkIde_set tuple_def by auto\n      show \"cod (tuple f g) = prod (cod f) (cod g)\"\n        using assms 1 cod_mkArr ide_cod mkIde_set tuple_def ide_prod by auto\n    qed\n\n    lemma tuple_simps [simp]:\n    assumes \"span f g\"\n    shows \"arr (tuple f g)\" and \"dom (tuple f g) = dom f\"\n    and \"cod (tuple f g) = prod (cod f) (cod g)\"\n      using assms tuple_in_hom by blast+\n\n    lemma Fun_pr1:\n    assumes \"ide a\" and \"ide b\"\n    shows \"Fun (pr1 a b) = restrict (\\<lambda>x. arr_of (hfst (elem_of x))) (set (prod a b))\"\n      using assms pr1_def Fun_mkArr arr_char pr1_simps(1) by presburger\n\n    lemma Fun_pr0:\n    assumes \"ide a\" and \"ide b\"\n    shows \"Fun (pr0 a b) = restrict (\\<lambda>x. arr_of (hsnd (elem_of x))) (set (prod a b))\"\n      using assms pr0_def Fun_mkArr arr_char pr0_simps(1) by presburger\n\n    lemma Fun_tuple:\n    assumes \"span f g\"\n    shows \"Fun (tuple f g) = restrict (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>) (Dom f)\"\n    proof -\n      have \"arr (tuple f g)\"\n        using assms tuple_in_hom by blast\n      thus ?thesis\n        using assms tuple_def Fun_mkArr by simp\n    qed\n\n    lemma pr1_tuple:\n    assumes \"span f g\"\n    shows \"comp (pr1 (cod f) (cod g)) (tuple f g) = f\"\n    proof (intro arr_eqI\\<^sub>S\\<^sub>C)\n      have pr1: \"\\<guillemotleft>pr1 (cod f) (cod g) : prod (cod f) (cod g) \\<rightarrow> cod f\\<guillemotright>\"\n        using assms ide_cod by blast\n      have tuple: \"\\<guillemotleft>tuple f g : dom f \\<rightarrow> prod (cod f) (cod g)\\<guillemotright>\"\n        using assms by blast\n      show par: \"par (comp (pr1 (cod f) (cod g)) (tuple f g)) f\"\n        using assms pr1_in_hom tuple_in_hom\n        by (metis (no_types, lifting) comp_in_homI' ide_cod in_homE)\n      show \"Fun (comp (pr1 (cod f) (cod g)) (tuple f g)) = Fun f\"\n      proof -\n        have seq: \"seq (pr1 (cod f) (cod g)) (tuple f g)\"\n          using par by blast\n        have \"Fun (comp (pr1 (cod f) (cod g)) (tuple f g)) =\n              restrict (Fun (pr1 (cod f) (cod g)) \\<circ> Fun (tuple f g)) (Dom (tuple f g))\"\n          using pr1 tuple seq Fun_comp by simp\n        also have \"... = restrict\n                           (Fun (mkArr (set (prod (cod f) (cod g))) (Cod f)\n                                       (\\<lambda>x. arr_of (hfst (elem_of x)))) \\<circ>\n                            Fun (mkArr (Dom f) (set (prod (cod f) (cod g)))\n                                       (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>)))\n                           (Dom (tuple f g))\"\n          unfolding pr1_def tuple_def\n          using assms ide_cod by presburger\n        also have\n          \"... = restrict\n                   (restrict (\\<lambda>x. arr_of (hfst (elem_of x))) (set (prod (cod f) (cod g))) o\n                      restrict (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>) (Dom f))\n                   (Dom f)\"\n        proof -\n          have \"Fun (mkArr (set (prod (cod f) (cod g))) (Cod f) (\\<lambda>x. arr_of (hfst (elem_of x)))) =\n                restrict (\\<lambda>x. arr_of (hfst (elem_of x))) (set (prod (cod f) (cod g)))\"\n            using assms Fun_mkArr ide_prod pr1\n            by (metis (no_types, lifting) arrI ide_cod pr1_def)\n          moreover have \"Fun (mkArr (Dom f) (set (prod (cod f) (cod g)))\n                                    (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>)) =\n                         restrict (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>) (Dom f)\"\n            using assms Fun_mkArr ide_prod ide_cod tuple_def tuple arrI by simp\n          ultimately show ?thesis\n            using assms tuple_simps(2) by simp\n        qed\n        also have\n          \"... = restrict\n                   ((\\<lambda>x. arr_of (hfst (elem_of x))) o (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>))\n                   (Dom f)\"\n          using assms tuple tuple_def arr_of_tuple_elem_of_membI by auto\n        also have \"... = restrict (Fun f) (Dom f)\"\n        proof\n          fix x\n          have \"restrict ((\\<lambda>x. arr_of (hfst (elem_of x))) o (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>))\n                         (Dom f) x =\n                restrict (\\<lambda>x. arr_of (elem_of (Fun f x))) (Dom f) x\"\n            by simp\n          also have \"... = restrict (Fun f) (Dom f) x\"\n          proof (cases \"x \\<in> Dom f\")\n            show \"x \\<notin> Dom f \\<Longrightarrow> ?thesis\" by simp\n            assume x: \"x \\<in> Dom f\"\n            have \"Fun f x \\<in> Cod f\"\n              using assms x Fun_mapsto arr_char by blast\n            moreover have \"Cod f \\<subseteq> Univ\"\n              using setp_set_ide assms ide_cod by blast\n            ultimately show ?thesis\n              using assms arr_of_elem_of Fun_mapsto by auto\n          qed\n          finally show \"restrict ((\\<lambda>x. arr_of (hfst (elem_of x))) \\<circ>\n                                    (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>))\n                                 (Dom f) x =\n                        restrict (Fun f) (Dom f) x\"\n            by blast\n        qed\n        also have \"... = Fun f\"\n          using assms par Fun_mapsto Fun_mkArr mkArr_Fun\n          by (metis (no_types, lifting))\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma pr0_tuple:\n    assumes \"span f g\"\n    shows \"comp (pr0 (cod f) (cod g)) (tuple f g) = g\"\n    proof (intro arr_eqI\\<^sub>S\\<^sub>C)\n      have pr0: \"\\<guillemotleft>pr0 (cod f) (cod g) : prod (cod f) (cod g) \\<rightarrow> cod g\\<guillemotright>\"\n        using assms ide_cod by blast\n      have tuple: \"\\<guillemotleft>tuple f g : dom f \\<rightarrow> prod (cod f) (cod g)\\<guillemotright>\"\n        using assms by blast\n      show par: \"par (comp (pr0 (cod f) (cod g)) (tuple f g)) g\"\n        using assms pr0_in_hom tuple_in_hom\n        by (metis (no_types, lifting) comp_in_homI' ide_cod in_homE)\n      show \"Fun (comp (pr0 (cod f) (cod g)) (tuple f g)) = Fun g\"\n      proof -\n        have seq: \"seq (pr0 (cod f) (cod g)) (tuple f g)\"\n          using par by blast\n        have \"Fun (comp (pr0 (cod f) (cod g)) (tuple f g)) =\n              restrict (Fun (pr0 (cod f) (cod g)) \\<circ> Fun (tuple f g)) (Dom (tuple f g))\"\n          using pr0 tuple seq Fun_comp by simp\n        also have\n          \"... = restrict\n                   (Fun (mkArr (set (prod (cod f) (cod g))) (Cod g)\n                               (\\<lambda>x. arr_of (hsnd (elem_of x)))) \\<circ>\n                    Fun (mkArr (Dom f) (set (prod (cod f) (cod g)))\n                               (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>)))\n                   (Dom (tuple f g))\"\n          unfolding pr0_def tuple_def\n          using assms ide_cod by presburger\n        also have \"... = restrict\n                           (restrict (\\<lambda>x. arr_of (hsnd (elem_of x))) (set (prod (cod f) (cod g))) o\n                            restrict (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>) (Dom g))\n                           (Dom g)\"\n        proof -\n          have \"Fun (mkArr (set (prod (cod f) (cod g))) (Cod g) (\\<lambda>x. arr_of (hsnd (elem_of x)))) =\n                restrict (\\<lambda>x. arr_of (hsnd (elem_of x))) (set (prod (cod f) (cod g)))\"\n            using assms Fun_mkArr ide_prod arrI\n            by (metis (no_types, lifting) ide_cod pr0 pr0_def)\n          moreover have \"Fun (mkArr (Dom f) (set (prod (cod f) (cod g)))\n                                    (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>)) =\n                         restrict (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>) (Dom f)\"\n            using assms Fun_mkArr ide_prod ide_cod tuple_def tuple arrI by simp\n          ultimately show ?thesis\n            using assms tuple_simps(2) by simp\n        qed\n        also have \"... = restrict\n                           ((\\<lambda>x. arr_of (hsnd (elem_of x))) o (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>))\n                           (Dom g)\"\n          using assms tuple tuple_def arr_of_tuple_elem_of_membI by auto\n        also have \"... = restrict (Fun g) (Dom g)\"\n        proof\n          fix x\n          have \"restrict ((\\<lambda>x. arr_of (hsnd (elem_of x)))\n                            o (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>))\n                         (Dom g) x =\n                restrict (\\<lambda>x. arr_of (elem_of (Fun g x))) (Dom g) x\"\n            by simp\n          also have \"... = restrict (Fun g) (Dom g) x\"\n          proof (cases \"x \\<in> Dom g\")\n            show \"x \\<notin> Dom g \\<Longrightarrow> ?thesis\" by simp\n            assume x: \"x \\<in> Dom g\"\n            have \"Fun g x \\<in> Cod g\"\n              using assms x Fun_mapsto arr_char by blast\n            moreover have \"Cod g \\<subseteq> Univ\"\n              using assms set_ideD(1) ide_cod by blast\n            ultimately show ?thesis\n              using assms arr_of_elem_of Fun_mapsto by auto\n          qed\n          finally show \"restrict ((\\<lambda>x. arr_of (hsnd (elem_of x))) \\<circ>\n                                    (\\<lambda>x. arr_of \\<langle>elem_of (Fun f x), elem_of (Fun g x)\\<rangle>))\n                                 (Dom g) x =\n                        restrict (Fun g) (Dom g) x\"\n            by blast\n        qed\n        also have \"... = Fun g\"\n          using assms par Fun_mapsto Fun_mkArr mkArr_Fun\n          by (metis (no_types, lifting))\n        finally show ?thesis by blast\n      qed\n    qed\n\n    lemma tuple_pr:\n    assumes \"ide a\" and \"ide b\" and \"\\<guillemotleft>h : dom h \\<rightarrow> prod a b\\<guillemotright>\"\n    shows \"tuple (comp (pr1 a b) h) (comp (pr0 a b) h) = h\"\n    proof (intro arr_eqI\\<^sub>S\\<^sub>C)\n      have pr0: \"\\<guillemotleft>pr0 a b : prod a b \\<rightarrow> b\\<guillemotright>\"\n        using assms pr0_in_hom ide_cod by blast\n      have pr1: \"\\<guillemotleft>pr1 a b : prod a b \\<rightarrow> a\\<guillemotright>\"\n        using assms pr1_in_hom ide_cod by blast\n      have tuple: \"\\<guillemotleft>tuple (comp (pr1 a b) h) (comp (pr0 a b) h) : dom h \\<rightarrow> prod a b\\<guillemotright>\"\n        using assms pr0 pr1\n        by (metis (no_types, lifting) cod_comp dom_comp pr0_simps(3) pr1_simps(3)\n            seqI' tuple_in_hom)\n      show par: \"par (tuple (comp (pr1 a b) h) (comp (pr0 a b) h)) h\"\n        using assms tuple by (metis (no_types, lifting) in_homE)\n      show \"Fun (tuple (comp (pr1 a b) h) (comp (pr0 a b) h)) = Fun h\"\n      proof -\n        have 1: \"Fun (comp (pr1 a b) h) =\n                 restrict (restrict (\\<lambda>x. arr_of (hfst (elem_of x))) (set (prod a b)) \\<circ> Fun h) (Dom h)\"\n          using assms pr1 Fun_comp Fun_pr1 seqI' by auto\n        have 2: \"Fun (comp (pr0 a b) h) =\n                 restrict (restrict (\\<lambda>x. arr_of (hsnd (elem_of x))) (set (prod a b)) \\<circ> Fun h) (Dom h)\"\n          using assms pr0 Fun_comp Fun_pr0 seqI' by auto\n        have \"Fun (tuple (comp (pr1 a b) h) (comp (pr0 a b) h)) =\n              restrict (\\<lambda>x. arr_of \\<langle>elem_of (restrict\n                                       (restrict (\\<lambda>x. arr_of (hfst (elem_of x))) (set (prod a b)) \\<circ> Fun h)\n                                                 (Dom h) x),\n                                elem_of (restrict\n                                       (restrict (\\<lambda>x. arr_of (hsnd (elem_of x))) (set (prod a b)) \\<circ> Fun h)\n                                                 (Dom h) x)\\<rangle>)\n                       (Dom h)\"\n        proof -\n          have \"Dom (comp (pr1 a b) h) = Dom h\"\n            using assms pr1_in_hom\n            by (metis (no_types, lifting) in_homE dom_comp seqI)\n          moreover have \"arr (mkArr (Dom (comp (pr1 a b) h))\n                             (set (prod (cod (comp (pr1 a b) h)) (cod (comp (pr0 a b) h))))\n                             (\\<lambda>x. arr_of \\<langle>elem_of (Fun (comp (pr1 a b) h) x),\n                                      elem_of (Fun (comp (pr0 a b) h) x)\\<rangle>))\"\n            using tuple unfolding tuple_def by blast\n          ultimately show ?thesis\n            using 1 2 tuple tuple_def\n                  Fun_mkArr [of \"Dom (comp (pr1 a b) h)\"\n                                 \"set (prod (cod (comp (pr1 a b) h))\n                                            (cod (comp (pr0 a b) h)))\"\n                                 \"\\<lambda>x. arr_of \\<langle>elem_of (Fun (comp (pr1 a b) h) x),\n                                          elem_of (Fun (comp (pr0 a b) h) x)\\<rangle>\"]\n            by simp\n        qed\n        also have \"... = Fun h\"\n        proof\n          let ?f = \"...\"\n          fix x\n          show \"?f x = Fun h x\"\n          proof -\n            have \"x \\<notin> Dom h \\<Longrightarrow> ?f x = Fun h x\"\n            proof -\n              assume x: \"x \\<notin> Dom h\"\n              have \"restrict ?f (Dom h) x = undefined\"\n                using assms x restrict_apply by auto\n              also have \"... = Fun h x\"\n              proof -\n                have \"arr h\"\n                  using assms by blast\n                thus ?thesis\n                  using assms x Fun_mapsto [of h] extensional_arb [of \"Fun h\" \"Dom h\" x]\n                  by simp\n              qed\n              finally show ?thesis by auto\n            qed\n            moreover have \"x \\<in> Dom h \\<Longrightarrow> ?f x = Fun h x\"\n            proof -\n              assume x: \"x \\<in> Dom h\"\n              have 1: \"Fun h x \\<in> set (prod a b)\"\n              proof -\n                have \"Fun h x \\<in> Cod h\"\n                  using assms x Fun_mapsto [of h] by blast\n                moreover have \"Cod h = set (prod a b)\"\n                  using assms ide_prod\n                  by (metis (no_types, lifting) in_homE)\n                ultimately show ?thesis by fast\n              qed\n              have \"?f x = arr_of \\<langle>hfst (elem_of (Fun h x)), hsnd (elem_of (Fun h x))\\<rangle>\"\n                using x 1 by simp\n              also have \"... = arr_of (elem_of (Fun h x))\"\n              proof -\n                have \"elem_of (Fun h x) \\<^bold>\\<in> ide_to_hf a * ide_to_hf b\"\n                  using assms x 1 par\n                  by (metis (no_types, lifting) prod_def elem_of_membI UNIV_I ide_prod\n                      ide_to_hf_hf_to_ide)\n                thus ?thesis\n                  using x is_hpair_def by auto\n              qed\n              also have \"... = Fun h x\"\n                using 1 arr_of_elem_of assms set_ideD(1) ide_prod by blast\n              finally show ?thesis by blast\n            qed\n            ultimately show ?thesis by blast\n          qed\n        qed\n        finally show ?thesis by blast\n      qed\n    qed\n\n    interpretation HF': elementary_category_with_binary_products comp pr0 pr1\n    proof\n      show \"\\<And>a b. \\<lbrakk>ide a; ide b\\<rbrakk> \\<Longrightarrow> span (pr1 a b) (pr0 a b)\"\n        using pr0_simps(1) pr0_simps(2) pr1_simps(1) pr1_simps(2) by auto\n      show \"\\<And>a b. \\<lbrakk>ide a; ide b\\<rbrakk> \\<Longrightarrow> cod (pr0 a b) = b\"\n        using pr0_simps(1-3) by blast\n      show \"\\<And>a b. \\<lbrakk>ide a; ide b\\<rbrakk> \\<Longrightarrow> cod (pr1 a b) = a\"\n        using pr1_simps(1-3) by blast\n      show \"\\<And>f g. span f g \\<Longrightarrow>\n                    \\<exists>!l. comp (pr1 (cod f) (cod g)) l = f \\<and> comp (pr0 (cod f) (cod g)) l = g\"\n      proof\n        fix f g\n        assume fg: \"span f g\"\n        show \"comp (pr1 (cod f) (cod g)) (tuple f g) = f \\<and>\n              comp (pr0 (cod f) (cod g)) (tuple f g) = g\"\n          using fg pr0_simps pr1_simps tuple_simps pr0_tuple pr1_tuple by presburger\n        show \"\\<And>l. \\<lbrakk>comp (pr1 (cod f) (cod g)) l = f \\<and> comp (pr0 (cod f) (cod g)) l = g\\<rbrakk>\n                      \\<Longrightarrow> l = tuple f g \"\n        proof -\n          fix l\n          assume l: \"comp (pr1 (cod f) (cod g)) l = f \\<and> comp (pr0 (cod f) (cod g)) l = g\"\n          show \"l = tuple f g\"\n            using fg l tuple_pr\n            by (metis (no_types, lifting) arr_iff_in_hom ide_cod seqE pr0_simps(2))\n        qed\n      qed\n      show \"\\<And>a b. \\<not> (ide a \\<and> ide b) \\<Longrightarrow> pr0 a b = null\"\n        using pr0_def by auto\n      show \"\\<And>a b. \\<not> (ide a \\<and> ide b) \\<Longrightarrow> pr1 a b = null\"\n        using pr1_def by auto\n    qed\n\n    text\\<open>\n      For reasons of economy of locale parameters, the notion \\<open>prod\\<close> is a defined notion\n      of the @{locale elementary_category_with_binary_products} locale.\n      However, we need to be able to relate this notion to that of cartesian product of\n      hereditarily finite sets, which we have already used to give a definition of \\<open>prod\\<close>.\n      The locale assumptions for @{locale elementary_cartesian_closed_category} refer\n      specifically to \\<open>HF'.prod\\<close>, even though in the end the notion itself does not depend\n      on that choice.  To be able to show that the locale assumptions of\n      @{locale elementary_cartesian_closed_category} are satisfied, we need to use a choice\n      of products that we can relate to the cartesian product of hereditarily\n      finite sets.  We therefore need to show that our previously defined \\<open>prod\\<close> coincides\n      (on objects) with the one defined in the @{locale elementary_category_with_binary_products} locale;\n      \\emph{i.e.}~\\<open>HF'.prod\\<close>.  Note that the latter is defined for all arrows,\n      not just identity arrows, so we need to use that for the subsequent definitions and proofs.\n    \\<close>\n\n    lemma prod_ide_eq:\n    assumes \"ide a\" and \"ide b\"\n    shows \"prod a b = HF'.prod a b\"\n      using assms prod_def HF'.pr_simps(2) HF'.prod_def pr0_simps(2) by presburger\n\n    lemma tuple_span_eq:\n    assumes \"span f g\"\n    shows \"tuple f g = HF'.tuple f g\"\n      using assms tuple_def HF'.tuple_def\n      by (metis (no_types, lifting) HF'.tuple_eqI pr0_tuple pr1_tuple)\n\n    section \"Exponentials\"\n\n    text\\<open>\n      We now turn our attention to exponentials.\n    \\<close>\n\n    definition exp\n    where \"exp b c = hf_to_ide (hexp (ide_to_hf b) (ide_to_hf c))\"\n\n    definition eval\n    where \"eval b c = mkArr (set (HF'.prod (exp b c) b)) (set c)\n                            (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\"\n\n    definition \\<Lambda>\n    where \"\\<Lambda> a b c f = mkArr (set a) (set (exp b c))\n                             (\\<lambda>x. arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c)\n                                                 (arr_to_hfun f))\n                                           (elem_of x)))\"\n\n    lemma ide_exp:\n    assumes \"ide b\" and \"ide c\"\n    shows \"ide (exp b c)\"\n      using assms exp_def hf_to_ide_mapsto ide_to_hf_mapsto by auto\n\n    lemma hfset_ide_to_hf:\n    assumes \"ide a\"\n    shows \"hfset (ide_to_hf a) = elem_of ` set a\"\n      using assms ide_to_hf_def ide_implies_finite_set(1) by auto\n\n    lemma eval_in_hom [intro]:\n    assumes \"ide b\" and \"ide c\"\n    shows \"in_hom (eval b c) (HF'.prod (exp b c) b) c\"\n    proof\n      show 1: \"arr (eval b c)\"\n      proof (unfold eval_def arr_mkArr, intro conjI)\n        show \"set (HF'.prod (exp b c) b) \\<subseteq> Univ\"\n          using HF'.ide_prod assms set_ideD(1) ide_exp by presburger\n        show \"set c \\<subseteq> Univ\"\n          using assms set_ideD(1) by blast\n        show \"(\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                 \\<in> set (HF'.prod (exp b c) b) \\<rightarrow> set c\"\n        proof\n          fix x\n          assume \"x \\<in> set (HF'.prod (exp b c) b)\"\n          hence x: \"x \\<in> set (prod (exp b c) b)\"\n            using assms prod_ide_eq ide_exp by auto\n          show \"arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))) \\<in> set c\"\n          proof (intro arr_of_membI)\n            show \"happ (hfst (elem_of x)) (hsnd (elem_of x)) \\<^bold>\\<in> ide_to_hf c\"\n            proof -\n              have 1: \"elem_of x \\<^bold>\\<in> ide_to_hf (exp b c) * ide_to_hf b\"\n              proof -\n                have \"elem_of x \\<^bold>\\<in> ide_to_hf (prod (exp b c) b)\"\n                  using assms x elem_of_membI ide_prod ide_exp by simp\n                thus ?thesis\n                  using assms x prod_def ide_to_hf_hf_to_ide by auto\n              qed\n              have \"hfst (elem_of x) \\<^bold>\\<in> hexp (ide_to_hf b) (ide_to_hf c)\"\n                using assms 1 x exp_def ide_to_hf_hf_to_ide by auto\n              moreover have \"hsnd (elem_of x) \\<^bold>\\<in> ide_to_hf b\"\n                using assms 1 by auto\n              ultimately show ?thesis\n                using happ_mapsto [of \"hfst (elem_of x)\" \"ide_to_hf b\" \"ide_to_hf c\"\n                                      \"hsnd (elem_of x)\"]\n                by simp\n            qed\n          qed\n        qed\n        show \"finite (elem_of ` set (HF'.prod (exp b c) b))\"\n          using HF'.ide_prod setp_set_ide assms ide_exp by presburger\n        show \"finite (elem_of ` set c)\"\n          using setp_set_ide assms(2) by blast\n      qed\n      show \"dom (eval b c) = HF'.prod (exp b c) b\"\n        using assms 1 ide_char HF'.ide_prod ide_exp dom_mkArr eval_def\n        by (metis (no_types, lifting) mkIde_set)\n      show \"cod (eval b c) = c\"\n        using assms 1 ide_char cod_mkArr eval_def\n        by (metis (no_types, lifting) mkIde_set)\n    qed\n\n    lemma eval_simps [simp]:\n    assumes \"ide b\" and \"ide c\"\n    shows \"arr (eval b c)\"\n    and \"dom (eval b c) = HF'.prod (exp b c) b\"\n    and \"cod (eval b c) = c\"\n      using assms eval_in_hom by blast+\n\n    lemma hlam_arr_to_hfun_in_hexp:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    and \"in_hom f (prod a b) c\"\n    shows \"hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c) (arr_to_hfun f)\n             \\<^bold>\\<in> hexp (ide_to_hf a) (ide_to_hf (exp b c))\"\n      using assms hfun_in_hexp hfun_hlam\n      by (metis (no_types, lifting) prod_def HCollect_iff in_homE UNIV_I\n          arr_to_hfun_in_hexp exp_def hexp_def ide_to_hf_hf_to_ide)\n\n    lemma lam_in_hom [intro]:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    and \"in_hom f (prod a b) c\"\n    shows \"in_hom (\\<Lambda> a b c f) a (exp b c)\"\n    proof\n      show 1: \"arr (\\<Lambda> a b c f)\"\n      proof (unfold \\<Lambda>_def arr_mkArr, intro conjI)\n        show \"set a \\<subseteq> Univ\"\n          using assms(1) set_ideD(1) by blast\n        show \"set (exp b c) \\<subseteq> Univ\"\n          using assms(2-3) set_ideD(1) ide_exp ide_char by blast\n        show \"finite (elem_of ` set a)\"\n          using assms(1) set_ideD(1) setp_set_ide by presburger\n        show \"finite (elem_of ` set (exp b c))\"\n          using assms(2-3) set_ideD(1) setp_set_ide ide_exp by presburger\n        show \"(\\<lambda>x. arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c) (arr_to_hfun f))\n                            (elem_of x)))\n                 \\<in> set a \\<rightarrow> set (exp b c)\"\n        proof\n          fix x\n          assume x: \"x \\<in> set a\"\n          show \"arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c) (arr_to_hfun f))\n                         (elem_of x))\n                     \\<in> set (exp b c)\"\n            using assms x hlam_arr_to_hfun_in_hexp ide_to_hf_def elem_of_membI happ_mapsto\n                  arr_of_membI\n            by meson\n        qed\n      qed\n      show \"dom (\\<Lambda> a b c f) = a\"\n        using assms(1) 1 \\<Lambda>_def ide_char dom_mkArr mkIde_set by auto\n      show \"cod (\\<Lambda> a b c f) = exp b c\"\n        using assms(2-3) 1 \\<Lambda>_def cod_mkArr ide_exp mkIde_set by auto\n    qed\n\n    lemma lam_simps [simp]:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    and \"in_hom f (prod a b) c\"\n    shows \"arr (\\<Lambda> a b c f)\"\n    and \"dom (\\<Lambda> a b c f) = a\"\n    and \"cod (\\<Lambda> a b c f) = exp b c\"\n      using assms lam_in_hom by blast+\n\n    lemma Fun_lam:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    and \"in_hom f (prod a b) c\"\n    shows \"Fun (\\<Lambda> a b c f) =\n           restrict (\\<lambda>x. arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c) (arr_to_hfun f))\n                                  (elem_of x)))\n                    (set a)\"\n      using assms arr_char lam_simps(1) \\<Lambda>_def Fun_mkArr by simp\n\n    lemma Fun_eval:\n    assumes \"ide b\" and \"ide c\"\n    shows \"Fun (eval b c) = restrict (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                                     (set (HF'.prod (exp b c) b))\"\n      using assms arr_char eval_simps(1) eval_def Fun_mkArr by force\n\n    lemma Fun_prod:\n    assumes \"arr f\" and \"arr g\" and \"x \\<in> set (prod (dom f) (dom g))\"\n    shows \"Fun (HF'.prod f g) x = arr_of \\<langle>elem_of (Fun f (arr_of (hfst (elem_of x)))),\n                                     elem_of (Fun g (arr_of (hsnd (elem_of x))))\\<rangle>\"\n    proof -\n      have 1: \"span (comp f (pr1 (dom f) (dom g))) (comp g (pr0 (dom f) (dom g)))\"\n        using assms\n        by (metis (no_types, lifting) HF'.prod_def HF'.prod_simps(1) HF'.tuple_ext not_arr_null)\n      have 2: \"Dom (comp f (pr1 (dom f) (dom g))) = set (prod (dom f) (dom g))\"\n        using assms\n        by (metis (mono_tags, lifting) 1 dom_comp ide_dom pr0_simps(2))\n      have 3: \"Dom (comp g (pr0 (dom f) (dom g))) = set (prod (dom f) (dom g))\"\n        using assms 1 2 by force\n      have \"Fun (HF'.prod f g) x =\n            Fun (HF'.tuple (comp f (pr1 (dom f) (dom g))) (comp g (pr0 (dom f) (dom g)))) x\"\n        using assms(3) HF'.prod_def by simp\n      also have \"... = restrict (\\<lambda>x. arr_of \\<langle>elem_of (Fun (comp f (pr1 (dom f) (dom g))) x),\n                                         elem_of (Fun (comp g (pr0 (dom f) (dom g))) x)\\<rangle>)\n                                (Dom (comp f (pr1 (dom f) (dom g))))\n                                x\"\n        using assms 1 tuple_span_eq Fun_tuple by simp\n      also have \"... = arr_of \\<langle>elem_of (Fun (comp f (pr1 (dom f) (dom g))) x),\n                           elem_of (Fun (comp g (pr0 (dom f) (dom g))) x)\\<rangle>\"\n        using assms(3) 2 by simp\n      also have \"... = arr_of \\<langle>elem_of (Fun f (arr_of (hfst (elem_of x)))),\n                           elem_of (Fun g (arr_of (hsnd (elem_of x))))\\<rangle>\"\n      proof -\n        have \"Fun (comp f (pr1 (dom f) (dom g))) x = Fun f (arr_of (hfst (elem_of x)))\"\n        proof -\n          (* TODO: Figure out what is making this proof so \"stiff\". *)\n          have 4: \"seq f (pr1 (dom f) (dom g))\"\n            using assms 1 by blast\n          have \"Fun (comp f (pr1 (dom f) (dom g))) x =\n                restrict (Fun f \\<circ> Fun (pr1 (dom f) (dom g))) (Dom (pr1 (dom f) (dom g))) x\"\n            using assms 1 Fun_comp [of f \"pr1 (dom f) (dom g)\"]\n            by (metis (no_types, lifting))\n          also have \"... = (Fun f \\<circ> Fun (pr1 (dom f) (dom g))) x\"\n          proof -\n            have \"x \\<in> Dom (pr1 (dom f) (dom g))\"\n              using assms 1 2 4\n              by (metis (no_types, lifting) dom_comp)\n            thus ?thesis by simp\n          qed\n          also have \"... = Fun f (Fun (pr1 (dom f) (dom g)) x)\"\n            by simp\n          also have \"... = Fun f (arr_of (hfst (elem_of x)))\"\n            using assms 1 Fun_pr1 [of \"dom f\" \"dom g\"] ide_dom by simp\n          finally show ?thesis by blast\n        qed\n        moreover\n        have \"Fun (comp g (pr0 (dom f) (dom g))) x = Fun g (arr_of (hsnd (elem_of x)))\"\n        proof -\n          have 4: \"seq g (pr0 (dom f) (dom g))\"\n            using assms 1 by blast\n          have \"Fun (comp g (pr0 (dom f) (dom g))) x =\n                restrict (Fun g \\<circ> Fun (pr0 (dom f) (dom g))) (Dom (pr0 (dom f) (dom g))) x\"\n            using assms 1 Fun_comp [of g \"pr0 (dom f) (dom g)\"]\n            by (metis (no_types, lifting))\n          also have \"... = (Fun g \\<circ> Fun (pr0 (dom f) (dom g))) x\"\n          proof -\n            have \"x \\<in> Dom (pr0 (dom f) (dom g))\"\n              using assms 1 2 4\n              by (metis (no_types, lifting) dom_comp)\n            thus ?thesis by simp\n          qed\n          also have \"... = Fun g (Fun (pr0 (dom f) (dom g)) x)\"\n            by simp\n          also have \"... = Fun g (arr_of (hsnd (elem_of x)))\"\n            using assms 1 Fun_pr0 [of \"dom f\" \"dom g\"] ide_dom by simp\n          finally show ?thesis by blast\n        qed\n        ultimately show ?thesis by simp\n      qed\n      finally show ?thesis by simp\n    qed\n\n    lemma prod_in_terms_of_tuple:\n    assumes \"arr f\" and \"arr g\"\n    shows \"HF'.prod f g =\n           tuple (comp f (pr1 (dom f) (dom g))) (comp g (pr0 (dom f) (dom g)))\"\n      using assms HF'.prod_def tuple_span_eq\n      by (metis (no_types, lifting) HF'.prod_simps(1) HF'.tuple_ext not_arr_null)\n\n    lemma eval_prod_lam:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    and \"in_hom g (prod a b) c\"\n    shows \"comp (eval b c) (HF'.prod (\\<Lambda> a b c g) b) = g\"\n    proof -\n      have ide_dom_lam: \"ide (dom (\\<Lambda> a b c g))\"\n        using assms lam_in_hom [of a b c g] ide_dom by blast\n      have ide_dom_b: \"ide (dom b)\"\n        using assms ide_dom ideD(1) by blast\n      define \\<Lambda>_pr1 where \"\\<Lambda>_pr1 = comp (\\<Lambda> a b c g) (pr1 (dom (\\<Lambda> a b c g)) (dom b))\"\n      define b_pr0 where \"b_pr0 = comp b (pr0 (dom (\\<Lambda> a b c g)) (dom b))\"\n      have lam_pr1: \"in_hom \\<Lambda>_pr1 (prod a b) (exp b c)\"\n      proof (unfold \\<Lambda>_pr1_def, intro comp_in_homI)\n        show \"in_hom (pr1 (dom (\\<Lambda> a b c g)) (dom b)) (prod a b) a\"\n          using assms ide_dom_lam ide_dom_b ideD(2) lam_simps(2) pr1_in_hom by auto\n        show \"in_hom (\\<Lambda> a b c g) a (exp b c)\"\n          using assms lam_in_hom by simp\n      qed\n      have b_pr0: \"in_hom b_pr0 (prod a b) b\"\n        using assms b_pr0_def\n        by (metis (no_types, lifting) HF'.arr_pr0_iff HF'.cod_pr0 comp_in_homI'\n            ideD(1-3) lam_simps(2) pr0_simps(2))\n      have 1: \"span \\<Lambda>_pr1 b_pr0\"\n        using lam_pr1 b_pr0\n        by (metis (no_types, lifting) in_homE)\n      have tuple: \"in_hom (tuple \\<Lambda>_pr1 b_pr0) (prod a b) (prod (exp b c) b)\"\n        using 1 lam_pr1 b_pr0 tuple_in_hom [of \\<Lambda>_pr1 b_pr0]\n        by (metis (mono_tags, lifting) in_homE)\n      define \\<Lambda>_pr1' where \"\\<Lambda>_pr1' = comp (\\<Lambda> a b c g) (pr1 a b)\"\n      define b_pr0' where \"b_pr0' = pr0 a b\"\n      have lam_pr1_eq: \"\\<Lambda>_pr1 = \\<Lambda>_pr1'\"\n        using assms \\<Lambda>_pr1_def \\<Lambda>_pr1'_def ideD(2) lam_simps(2) by auto\n      have b_pr0_eq: \"b_pr0 = b_pr0'\"\n        using assms b_pr0_def b_pr0'_def b_pr0 comp_ide_arr\n        by (metis (no_types, lifting) ideD(2) in_homE lam_simps(2))\n      have Fun_pr0: \"Fun (pr0 a b) = restrict (\\<lambda>x. arr_of (hsnd (elem_of x))) (set (prod a b))\"\n        using assms Fun_pr0 by simp\n      have Fun_lam_pr1: \"Fun \\<Lambda>_pr1 =\n                         restrict (Fun (\\<Lambda> a b c g) o\n                                   restrict (\\<lambda>x. arr_of (hfst (elem_of x))) (set (prod a b)))\n                                  (set (prod a b))\"\n        using assms 1 Fun_comp Fun_pr1 lam_pr1_eq \\<Lambda>_pr1'_def\n        by (metis (no_types, lifting) pr1_simps(2))\n      have \"comp (eval b c) (HF'.prod (\\<Lambda> a b c g) b) = comp (eval b c) (tuple \\<Lambda>_pr1 b_pr0)\"\n        using assms \\<Lambda>_pr1_def b_pr0_def 1 prod_in_terms_of_tuple ideD(1) lam_simps(1)\n        by presburger\n      also have 5: \"... = comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')\"\n        using lam_pr1_eq b_pr0_eq by simp\n      also have \"... = g\"\n      proof (intro arr_eqI\\<^sub>S\\<^sub>C)\n        have 2: \"arr (comp (eval b c) (tuple \\<Lambda>_pr1 b_pr0))\"\n          using assms tuple arr_char\n          by (metis (no_types, lifting) in_homE seqI eval_simps(1-2) ide_exp prod_ide_eq)\n        have 3: \"arr g\"\n          using assms by blast\n        have tuple': \"in_hom (tuple \\<Lambda>_pr1' b_pr0') (prod a b) (prod (exp b c) b)\"\n          using tuple lam_pr1_eq b_pr0_eq by blast\n        have 4: \"Dom g = set (prod a b)\"\n          using assms\n          by (metis (no_types, lifting) in_homE)\n        show par: \"par (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) g\"\n          using assms tuple' 2 3 5\n          by (metis (no_types, lifting) cod_comp dom_comp in_homE eval_simps(3))\n        show \"Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) = Fun g\"\n        proof\n          fix x\n          have \"x \\<notin> set (prod a b) \\<Longrightarrow> Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) x = Fun g x\"\n          proof -\n            have 5: \"Fun g \\<in> extensional (Dom g)\"\n              using assms 3 Fun_mapsto by simp\n            moreover have \"Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) \\<in> extensional (Dom g)\"\n              using 5 par Fun_mapsto by (metis (no_types, lifting) Int_iff)\n            ultimately show \"x \\<notin> set (prod a b) \\<Longrightarrow>\n                             Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) x = Fun g x\"\n              using 4 extensional_arb [of \"Fun g\" \"Dom g\" x]\n                    extensional_arb [of \"Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0'))\" \"Dom g\" x]\n              by force\n          qed\n          moreover have \"x \\<in> set (prod a b) \\<Longrightarrow>\n                           Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) x = Fun g x\"\n          proof -\n            assume x: \"x \\<in> set (prod a b)\"\n            have 6: \"Dom (tuple \\<Lambda>_pr1' b_pr0') = set (prod a b)\"\n              using assms 4 tuple' par\n              by (metis (no_types, lifting) in_homE)\n            have \"Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) x =\n                  Fun (eval b c) (Fun (tuple \\<Lambda>_pr1' b_pr0') x)\"\n            proof -\n              have \"Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) x =\n                    (Fun (eval b c) \\<circ> Fun (tuple \\<Lambda>_pr1' b_pr0')) x\"\n                using assms par x 6 Fun_comp [of \"eval b c\" \"tuple \\<Lambda>_pr1' b_pr0'\"] by auto\n              also have \"... = Fun (eval b c) (Fun (tuple \\<Lambda>_pr1' b_pr0') x)\"\n                by simp\n              finally show ?thesis by blast\n            qed\n            also have \"... = restrict (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                                      (set (HF'.prod (exp b c) b))\n                                      (Fun (tuple \\<Lambda>_pr1' b_pr0') x)\"\n              using assms Fun_eval by simp\n            also have \"... = (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                               (Fun (tuple \\<Lambda>_pr1' b_pr0') x)\"\n            proof -\n              have \"Fun (tuple \\<Lambda>_pr1' b_pr0') x \\<in> set (HF'.prod (exp b c) b)\"\n              proof -\n                have \"x \\<in> Dom (tuple \\<Lambda>_pr1' b_pr0')\"\n                  using x 6 by blast\n                moreover have \"Cod (tuple \\<Lambda>_pr1' b_pr0') = set (HF'.prod (exp b c) b)\"\n                  by (metis (no_types, lifting) in_homE assms(2-3) ide_exp\n                      prod_ide_eq tuple')\n                moreover have \"arr (tuple \\<Lambda>_pr1' b_pr0')\"\n                  using tuple' by blast\n                ultimately show ?thesis\n                  using tuple' Fun_mapsto [of \"tuple \\<Lambda>_pr1' b_pr0'\"] by auto\n              qed\n              thus ?thesis\n                using restrict_apply by simp\n            qed\n            also have \"... = (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                               (arr_of \\<langle>elem_of (Fun \\<Lambda>_pr1' x), elem_of (Fun b_pr0' x)\\<rangle>)\"\n            proof -\n              have 7: \"Dom \\<Lambda>_pr1' = set (prod a b)\"\n                using assms\n                by (metis (no_types, lifting) 1 comp_ide_arr ideD(2)\n                    b_pr0_def lam_pr1_eq lam_simps(2) pr0_simps(2))\n              moreover have \"span \\<Lambda>_pr1' b_pr0'\"\n                using assms 1 b_pr0_eq lam_pr1_eq by auto\n              moreover have \"x \\<in> Dom \\<Lambda>_pr1'\"\n                using x 7 by simp\n              ultimately have \"Fun (tuple \\<Lambda>_pr1' b_pr0') x =\n                               arr_of \\<langle>elem_of (Fun \\<Lambda>_pr1' x), elem_of (Fun b_pr0' x)\\<rangle>\"\n                using assms x restrict_apply Fun_tuple by simp\n              thus ?thesis by simp\n            qed\n            also have \"... = arr_of (happ (elem_of (Fun \\<Lambda>_pr1' x)) (elem_of (Fun b_pr0' x)))\"\n              using assms by simp\n            also have \"... = arr_of (happ (elem_of (arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b)\n                                                            (ide_to_hf c) (arr_to_hfun g))\n                                      (hfst (elem_of x)))))\n                                      (elem_of (arr_of (hsnd (elem_of x)))))\"\n            proof -\n              have \"Fun b_pr0' x = arr_of (hsnd (elem_of x))\"\n                using assms x Fun_pr0 b_pr0'_def by simp\n              moreover have \"Fun \\<Lambda>_pr1' x =\n                             arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c)\n                                            (arr_to_hfun g))\n                                      (hfst (elem_of x)))\"\n              proof -\n                have \"Fun \\<Lambda>_pr1' x =\n                      restrict (Fun (\\<Lambda> a b c g) o Fun (pr1 a b)) (Dom (pr1 a b)) x\"\n                  using assms x Fun_pr1 Fun_comp lam_pr1_eq Fun_lam_pr1 pr1_simps(1-2)\n                  by presburger\n                also have \"... = Fun (\\<Lambda> a b c g) (Fun (pr1 a b) x)\"\n                  using assms x restrict_apply Fun_lam_pr1 Fun_pr1 calculation lam_pr1_eq\n                  by auto\n                also have \"... = restrict (\\<lambda>x. arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b)\n                                                              (ide_to_hf c) (arr_to_hfun g))\n                                          (elem_of x)))\n                                          (set a)\n                                          (Fun (pr1 a b) x)\"\n                  using assms x Fun_lam by simp\n                also have \"... = arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c)\n                                                (arr_to_hfun g))\n                                          (elem_of (Fun (pr1 a b) x)))\"\n                proof -\n                  have \"Fun (pr1 a b) x \\<in> set a\"\n                  proof -\n                    have \"x \\<in> Dom (pr1 a b)\"\n                      using assms x pr1_simps(1-2) by auto\n                    moreover have \"Cod (pr1 a b) = set a\"\n                      using assms HF'.cod_pr1 pr1_simps(1) by auto\n                    moreover have \"arr (pr1 a b)\"\n                      using assms arr_char by blast\n                    ultimately show ?thesis\n                      using Fun_mapsto [of \"pr1 a b\"] by auto\n                  qed\n                  thus ?thesis\n                    using restrict_apply by simp\n                qed\n                also have \"... = arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c)\n                                                (arr_to_hfun g))\n                                          (hfst (elem_of x)))\"\n                  using assms x Fun_pr1 Fun_lam [of a b c g] by simp\n                finally show ?thesis by simp\n              qed\n              ultimately show ?thesis by simp\n            qed\n            also have \"... = arr_of (happ (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c)\n                                                  (arr_to_hfun g))\n                                            (hfst (elem_of x)))\n                                      (hsnd (elem_of x)))\"\n              by simp\n            also have \"... = arr_of (happ (arr_to_hfun g) (elem_of x))\"\n              using assms x happ_hlam\n              by (metis (no_types, lifting) prod_def elem_of_membI HCollect_iff ide_dom\n                  in_homE UNIV_I arr_to_hfun_in_hexp hexp_def hfst_conv hsnd_conv\n                  ide_to_hf_hf_to_ide timesE)\n            also have \"... = Fun g x\"\n              using assms x 3 4 Fun_char [of g] restrict_apply [of \"Fun g\" \"Dom g\" x]\n              by simp\n            finally show ?thesis by simp\n          qed\n          ultimately show \"Fun (comp (eval b c) (tuple \\<Lambda>_pr1' b_pr0')) x = Fun g x\"\n            by auto\n        qed\n      qed\n      finally show ?thesis by simp\n    qed\n\n    lemma lam_eval_prod:\n    assumes \"ide a\" and \"ide b\" and \"ide c\"\n    and \"in_hom h a (exp b c)\"\n    shows \"\\<Lambda> a b c (comp (eval b c) (HF'.prod h b)) = h\"\n    proof (intro arr_eqI\\<^sub>S\\<^sub>C)\n      have 0: \"in_hom (comp (eval b c) (HF'.prod h b)) (prod a b) c\"\n      proof\n        show \"in_hom (HF'.prod h b) (prod a b) (HF'.prod (exp b c) b)\"\n        proof\n          show 1: \"arr (HF'.prod h b)\"\n            using assms HF'.prod_in_hom'\n            by (metis (no_types, lifting) ideD(1) in_homE)\n          show \"dom (HF'.prod h b) = prod a b\"\n            using assms 1\n            by (metis (no_types, lifting) HF'.prod_simps(2) ideD(1-2) in_homE prod_ide_eq)\n          show \"cod (HF'.prod h b) = HF'.prod (exp b c) b\"\n            using assms 1\n            by (metis (no_types, lifting) HF'.prod_simps(3) ideD(1,3) in_homE)\n        qed\n        show \"in_hom (eval b c) (HF'.prod (exp b c) b) c\"\n          using assms by blast\n      qed\n      have 1: \"in_hom (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b))) a (exp b c)\"\n        using assms 0 by blast\n      have 2: \"Fun (comp (eval b c) (HF'.prod h b)) =\n               restrict (Fun (eval b c) \\<circ> Fun (HF'.prod h b))\n                        (set (HF'.prod a b))\"\n      proof -\n        have \"seq (eval b c) (HF'.prod h b)\"\n          using assms 1\n          by (metis (no_types, lifting) 0 in_homE)\n        moreover have \"Dom (HF'.prod h b) = set (HF'.prod a b)\"\n          using assms\n          by (metis (no_types, lifting) HF'.prod_simps(2) ideD(1-2) in_homE)\n        ultimately show ?thesis\n          using assms Fun_comp [of \"eval b c\" \"HF'.prod h b\"] by simp\n      qed\n      show par: \"par (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b))) h\"\n        using assms 1\n        by (metis (no_types, lifting) in_homE)\n      show \"Fun (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b))) = Fun h\"\n      proof\n        fix x\n        show \"Fun (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b))) x = Fun h x\"\n        proof -\n          have \"x \\<notin> set a \\<Longrightarrow> ?thesis\"\n            using assms 1 Fun_mapsto\n                  extensional_arb [of \"Fun h\" \"set a\" x]\n                  extensional_arb [of \"Fun (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b)))\"\n                                      \"set a\" x]\n            by (metis (no_types, lifting) 0 Int_iff lam_simps(2) par)\n          moreover have \"x \\<in> set a \\<Longrightarrow> ?thesis\"\n          proof -\n            assume x: \"x \\<in> set a\"\n            have 3: \"dom (comp (eval b c) (HF'.prod h b)) = HF'.prod a b\"\n              using assms 0 in_homE prod_ide_eq by auto\n            have 4: \"cod (comp (eval b c) (HF'.prod h b)) = c\"\n              using assms 0 by blast\n            have 5: \"dom (comp (eval b c) (HF'.prod h b)) = HF'.prod a b\"\n              using assms 3\n              by (metis (mono_tags, lifting))\n            have 6: \"cod (comp (eval b c) (HF'.prod h b)) = c\"\n              using assms 4 by (metis (no_types, lifting))\n            have 7: \"arr_to_hfun (comp (eval b c) (HF'.prod h b)) =\n                     \\<lbrace>xy \\<^bold>\\<in> ide_to_hf (HF'.prod a b) * ide_to_hf c.\n                        hsnd xy = elem_of (Fun (comp (eval b c) (HF'.prod h b)) (arr_of (hfst xy)))\\<rbrace>\"\n              unfolding arr_to_hfun_def\n              using 2 5 6 by metis\n            have \"Fun (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b))) x =\n                  arr_of (happ (hlam (ide_to_hf a) (ide_to_hf b) (ide_to_hf c)\n                                 (arr_to_hfun (comp (eval b c) (HF'.prod h b))))\n                           (elem_of x))\"\n              using assms 0 x Fun_lam by auto\n            also have \"... = arr_of \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                                   \\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle>\n                                      \\<^bold>\\<in> arr_to_hfun (comp (eval b c) (HF'.prod h b))\\<rbrace>\"\n            proof -\n              have \"seq (eval b c) (HF'.prod h b)\"\n                using assms 0 by blast\n              moreover have \"ide_to_hf (dom (comp (eval b c) (HF'.prod h b))) =\n                             ide_to_hf a * ide_to_hf b\"\n                using assms 1 3\n                by (metis (no_types, lifting) prod_def UNIV_I ide_to_hf_hf_to_ide prod_ide_eq)\n              moreover have \"ide_to_hf (cod (comp (eval b c) (HF'.prod h b))) = ide_to_hf c\"\n                using assms 2 4 by auto\n              ultimately show ?thesis\n                using assms 0 x happ_hlam(3) elem_of_membI\n                      hfun_arr_to_hfun [of \"comp (eval b c) (HF'.prod h b)\"]\n                by simp\n            qed\n            also have \"... = arr_of \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                                   hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                                       (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\\<rbrace>\"\n            proof -\n              have \"\\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                       \\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle>\n                          \\<^bold>\\<in> arr_to_hfun (comp (eval b c) (HF'.prod h b))\\<rbrace> =\n                    \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                                   hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                                       (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\\<rbrace>\"\n              proof\n                fix yz\n                show \"yz \\<^bold>\\<in> \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                                   \\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle>\n                                      \\<^bold>\\<in> arr_to_hfun (comp (eval b c) (HF'.prod h b))\\<rbrace> \\<longleftrightarrow>\n                      yz \\<^bold>\\<in> \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                                   hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                                     (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\\<rbrace>\"\n                proof -\n                  have \"yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c \\<Longrightarrow>\n                        \\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle> \\<^bold>\\<in> arr_to_hfun (comp (eval b c) (HF'.prod h b))\n                          \\<longleftrightarrow> hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                                     (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\"\n                  proof -\n                    assume yz: \"yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c\"\n                    have \"\\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle>\n                             \\<^bold>\\<in> arr_to_hfun (comp (eval b c) (HF'.prod h b))\n                            \\<longleftrightarrow>\n                          \\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle> \\<^bold>\\<in> ide_to_hf (HF'.prod a b) * ide_to_hf c \\<and>\n                          hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                         (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\"\n                      using 7 by auto\n                    moreover have \"\\<langle>\\<langle>elem_of x, hfst yz\\<rangle>, hsnd yz\\<rangle>\n                                      \\<^bold>\\<in> ide_to_hf (prod a b) * ide_to_hf c\"\n                    proof -\n                      have \"\\<langle>elem_of x, hfst yz\\<rangle> \\<^bold>\\<in> ide_to_hf (HF'.prod a b)\"\n                        using assms x yz\n                        by (metis (no_types, lifting) prod_def elem_of_membI UNIV_I hfst_conv\n                            ide_to_hf_hf_to_ide prod_ide_eq timesE times_iff)\n                      thus ?thesis\n                        using yz assms(1-2) prod_ide_eq by auto\n                    qed\n                    ultimately show ?thesis\n                      using assms(1-2) prod_ide_eq by auto\n                  qed\n                  thus ?thesis by auto\n                qed\n              qed\n              thus ?thesis by simp\n            qed\n            also have \"... = arr_of \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\"\n            proof -\n              have \"\\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c.\n                       hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                               (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\\<rbrace> =\n                    \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\"\n              proof -\n                have \"\\<And>yz. yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c \\<Longrightarrow>\n                             hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                            (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\n                               \\<longleftrightarrow>\n                             yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                proof -\n                  fix yz\n                  assume yz: \"yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c\"\n                  have 7: \"arr_of \\<langle>elem_of x, hfst yz\\<rangle> \\<in> set (HF'.prod a b)\"\n                    using assms x yz arr_of_membI\n                    by (metis (no_types, lifting) prod_def elem_of_membI UNIV_I hfst_conv\n                        ide_to_hf_hf_to_ide prod_ide_eq timesE times_iff)\n                  have 8: \"Fun h x \\<in> set (exp b c)\"\n                  proof -\n                    have \"Fun h x \\<in> Cod h\"\n                      using assms x Fun_mapsto by blast\n                    moreover have \"Cod h = set (exp b c)\"\n                      using assms 0 lam_simps(3) par by auto\n                    ultimately show ?thesis by blast\n                  qed\n                  show \"hsnd yz = elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                            (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\n                           \\<longleftrightarrow>\n                        yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                  proof -\n                    have \"Fun (comp (eval b c) (HF'.prod h b)) (arr_of \\<langle>elem_of x, hfst yz\\<rangle>) =\n                            arr_of (happ (elem_of (Fun h x)) (hfst yz))\"\n                    proof -\n                      have \"Fun (comp (eval b c) (HF'.prod h b)) (arr_of \\<langle>elem_of x, hfst yz\\<rangle>) =\n                            restrict (Fun (eval b c) \\<circ> Fun (HF'.prod h b))\n                                     (set (HF'.prod a b))\n                                     (arr_of \\<langle>elem_of x, hfst yz\\<rangle>)\"\n                        using assms x yz 2 by simp\n                      also have \"... = Fun (eval b c)\n                                               (Fun (HF'.prod h b) (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))\"\n                        using 7 by simp\n                      also have \"... = Fun (eval b c)\n                                               (arr_of \\<langle>elem_of (Fun h x),\n                                                    elem_of (Fun b (arr_of (hfst yz)))\\<rangle>)\"\n                      proof -\n                        have \"Fun (HF'.prod h b) (arr_of \\<langle>elem_of x, hfst yz\\<rangle>) =\n                           arr_of \\<langle>elem_of (Fun h x), elem_of (Fun b (arr_of (hfst yz)))\\<rangle>\"\n                        proof -\n                          have \"Fun (HF'.prod h b) (arr_of \\<langle>elem_of x, hfst yz\\<rangle>) =\n                                arr_of \\<langle>elem_of (Fun h (arr_of (hfst (elem_of (arr_of \\<langle>elem_of x, hfst yz\\<rangle>))))),\n                                    elem_of (Fun b (arr_of (hsnd (elem_of (arr_of \\<langle>elem_of x, hfst yz\\<rangle>)))))\\<rangle>\"\n                          proof -\n                            have \"arr_of \\<langle>elem_of x, hfst yz\\<rangle> \\<in> set (prod (dom h) (dom b))\"\n                              using assms x yz 7\n                              by (metis (no_types, lifting) ideD(2) in_homE prod_ide_eq)\n                            thus ?thesis\n                              using assms x yz Fun_prod ideD(1) by blast\n                          qed\n                          also have \"... = arr_of \\<langle>elem_of (Fun h (arr_of (elem_of x))),\n                                               elem_of (Fun b (arr_of (hfst yz)))\\<rangle>\"\n                            using assms x yz by simp\n                          also have \"... = arr_of \\<langle>elem_of (Fun h x), elem_of (Fun b (arr_of (hfst yz)))\\<rangle>\"\n                            using assms(1) set_ideD(1) x by force\n                          finally show ?thesis by simp\n                        qed\n                        thus ?thesis by simp\n                      qed\n                      also have \"... = Fun (eval b c) (arr_of \\<langle>elem_of (Fun h x), hfst yz\\<rangle>)\"\n                        using assms x yz Fun_ide ide_char arr_of_membI by auto\n                      also have \"... = restrict (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                                                (set (HF'.prod (exp b c) b))\n                                                (arr_of \\<langle>elem_of (Fun h x), hfst yz\\<rangle>)\"\n                        using assms Fun_eval [of b c] by simp\n                      also have \"... = (\\<lambda>x. arr_of (happ (hfst (elem_of x)) (hsnd (elem_of x))))\n                                         (arr_of \\<langle>elem_of (Fun h x), hfst yz\\<rangle>)\"\n                      proof -\n                        have \"arr_of \\<langle>elem_of (Fun h x), hfst yz\\<rangle>\n                                 \\<in> set (HF'.prod (exp b c) b)\"\n                        proof -\n                          have 1: \"ide_to_hf (HF'.prod (exp b c) b) =\n                                   HF (elem_of ` set (HF'.prod (exp b c) b))\"\n                            unfolding ide_to_hf_def by blast\n                          have \"\\<langle>elem_of (Fun h x), hfst yz\\<rangle>\n                                  \\<^bold>\\<in> HF (elem_of ` set (HF'.prod (exp b c) b))\"\n                            using assms x yz 1 8 Fun_mapsto [of h]\n                            by (metis (no_types, lifting) prod_def elem_of_membI UNIV_I\n                                hfst_conv ide_exp ide_to_hf_hf_to_ide prod_ide_eq timesE times_iff)\n                          thus ?thesis\n                            using assms x yz 1 arr_of_membI [of \"\\<langle>elem_of (Fun h x), hfst yz\\<rangle>\"]\n                            by auto\n                        qed\n                        thus ?thesis by simp\n                      qed\n                      also have \"... = arr_of (happ (elem_of (Fun h x)) (hfst yz))\"\n                        by simp\n                      finally show ?thesis by simp\n                    qed\n                    hence 9: \"elem_of (Fun (comp (eval b c) (HF'.prod h b))\n                                        (arr_of \\<langle>elem_of x, hfst yz\\<rangle>)) =\n                              happ (elem_of (Fun h x)) (hfst yz)\"\n                      by simp\n                    show ?thesis\n                    proof -\n                      have \"hsnd yz = happ (elem_of (Fun h x)) (hfst yz)\n                              \\<longleftrightarrow> yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                      proof\n                        have 10: \"\\<exists>!z. \\<langle>hfst yz, z\\<rangle> \\<^bold>\\<in> elem_of (Fun h x)\"\n                        proof -\n                          have \"hfun (ide_to_hf b) (ide_to_hf c) (elem_of (Fun h x))\"\n                            using assms x 8\n                            by (metis (no_types, lifting) elem_of_membI HCollect_iff UNIV_I\n                                exp_def hexp_def ide_exp ide_to_hf_hf_to_ide)\n                          thus ?thesis\n                            using assms yz\n                                  hfunE [of \"ide_to_hf b\" \"ide_to_hf c\" \"elem_of (Fun h x)\"]\n                            by (metis (no_types, lifting) hfst_conv timesE)\n                        qed\n                        show \"yz \\<^bold>\\<in> elem_of (Fun h x)\n                                \\<Longrightarrow> hsnd yz = happ (elem_of (Fun h x)) (hfst yz)\"\n                        proof -\n                          assume yz1: \"yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                          show \"hsnd yz = happ (elem_of (Fun h x)) (hfst yz)\"\n                            unfolding app_def\n                            using assms x yz yz1 10 hfun_arr_to_hfun arr_to_hfun_def\n                                  the1_equality\n                                    [of \"\\<lambda>y. \\<langle>hfst yz, y\\<rangle> \\<^bold>\\<in> elem_of (Fun h x)\" \"hsnd yz\"]\n                            by (metis (no_types, lifting) hfst_conv hsnd_conv timesE)\n                        qed\n                        show \"hsnd yz = happ (elem_of (Fun h x)) (hfst yz)\n                                \\<Longrightarrow> yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                          unfolding app_def\n                          using assms x yz 10\n                                theI' [of \"\\<lambda>y. \\<langle>hfst yz, y\\<rangle> \\<^bold>\\<in> elem_of (Fun h x)\"]\n                          by (metis (no_types, lifting) hfst_conv hsnd_conv timesE)\n                      qed\n                      thus ?thesis\n                        using 9 by simp\n                    qed\n                  qed\n                qed\n                thus ?thesis by blast\n              qed\n              thus ?thesis by simp\n            qed\n            also have \"... = Fun h x\"\n            proof -\n              have H: \"Fun h x = restrict (\\<lambda>x. arr_of (happ (arr_to_hfun h) (elem_of x))) (Dom h) x\"\n              proof -\n                have \"arr h\"\n                  using assms by blast\n                thus ?thesis\n                  using assms x Fun_char by simp\n              qed\n              also have \"... = arr_of (happ (arr_to_hfun h) (elem_of x))\"\n                using assms x par\n                by (metis (no_types, lifting) 0 lam_simps(2) restrict_apply)\n              also have \"... = arr_of (THE g. \\<langle>elem_of x, g\\<rangle> \\<^bold>\\<in> arr_to_hfun h)\"\n                using app_def by simp\n              also have \"... = arr_of \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\"\n              proof -\n                have ex_un_g: \"\\<exists>!g. \\<langle>elem_of x, g\\<rangle> \\<^bold>\\<in> arr_to_hfun h\"\n                  using assms x arr_to_hfun_def hfun_arr_to_hfun\n                        hfunE [of \"ide_to_hf a\" \"ide_to_hf (exp b c)\" \"arr_to_hfun h\"]\n                  by (metis (no_types, lifting) elem_of_membI in_homE)\n                moreover have\n                   \"\\<langle>elem_of x, \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\\<rangle>\n                       \\<^bold>\\<in> arr_to_hfun h\"\n                proof -\n                  have \"elem_of (Fun h x) =\n                        \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\"\n                  proof\n                    fix yz\n                    show \"yz \\<^bold>\\<in> elem_of (Fun h x) \\<longleftrightarrow>\n                          yz \\<^bold>\\<in> \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\"\n                    proof\n                      show \"yz \\<^bold>\\<in> elem_of (Fun h x)\n                              \\<Longrightarrow> yz \\<^bold>\\<in> \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\"\n                      proof -\n                        assume yz: \"yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                        have \"yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c\"\n                        proof -\n                          have \"elem_of (Fun h x) \\<^bold>\\<in> hexp (ide_to_hf b) (ide_to_hf c)\"\n                          proof -\n                            have \"ide (hf_to_ide (hexp (ide_to_hf b) (ide_to_hf c)))\"\n                              using assms exp_def ide_exp by auto\n                            moreover have\n                              \"Fun h x \\<in> set (hf_to_ide (hexp (ide_to_hf b) (ide_to_hf c)))\"\n                            proof -\n                              have \"Fun h x \\<in> Cod h\"\n                                using assms x Fun_mapsto by blast\n                              moreover have\n                                \"Cod h = set (hf_to_ide (hexp (ide_to_hf b) (ide_to_hf c)))\"\n                                using assms 0 exp_def lam_simps(3) par by auto\n                              ultimately show ?thesis by blast\n                            qed\n                            ultimately show ?thesis\n                              using elem_of_membI [of \"hf_to_ide (hexp (ide_to_hf b) (ide_to_hf c))\"\n                                                   \"Fun h x\"]\n                              by (simp add: ide_to_hf_hf_to_ide)\n                          qed\n                          thus ?thesis\n                            using assms yz hexp_def by auto\n                        qed\n                        thus ?thesis\n                          using assms x yz by blast\n                      qed\n                      show \"yz \\<^bold>\\<in> \\<lbrace>yz \\<^bold>\\<in> ide_to_hf b * ide_to_hf c. yz \\<^bold>\\<in> elem_of (Fun h x)\\<rbrace>\n                              \\<Longrightarrow> yz \\<^bold>\\<in> elem_of (Fun h x)\"\n                        using assms by simp\n                    qed\n                  qed\n                  moreover have \"arr_of (elem_of x) = x\"\n                    using arr_of_elem_of assms(1) set_ideD(1) x by blast\n                  ultimately show ?thesis\n                    using assms x arr_to_hfun_def ex_un_g by auto\n                qed\n                ultimately show ?thesis\n                  using assms x theI' [of \"\\<lambda>g. \\<langle>elem_of x, g\\<rangle> \\<^bold>\\<in> arr_to_hfun h\"]\n                  by fastforce\n              qed\n              finally show ?thesis\n                using assms x by simp\n            qed\n            finally show ?thesis by simp\n          qed\n          ultimately show \"Fun (\\<Lambda> a b c (comp (eval b c) (HF'.prod h b))) x = Fun h x\"\n            by blast\n        qed\n      qed\n    qed\n\n    section \"The Main Results\"\n\n    interpretation cartesian_closed_category comp\n    proof -\n      interpret elementary_cartesian_closed_category comp pr0 pr1\n                       some_terminal trm exp eval \\<Lambda>\n        using ide_exp eval_in_hom lam_in_hom prod_ide_eq eval_prod_lam lam_eval_prod\n        by unfold_locales auto\n      show \"cartesian_closed_category comp\"\n        using is_cartesian_closed_category by simp\n    qed\n\n    theorem is_cartesian_closed_category:\n    shows \"cartesian_closed_category comp\"\n      ..\n\n    theorem is_category_with_finite_limits:\n    shows \"category_with_finite_limits comp\"\n    proof\n      fix J :: \"'j comp\"\n      assume J: \"category J\"\n      interpret J: category J\n        using J by simp\n      assume finite: \"finite (Collect J.arr)\"\n      have \"has_products (Collect J.ide)\"\n      proof -\n        have \"Collect J.ide \\<noteq> UNIV\"\n          using J.not_arr_null by blast\n        moreover have \"finite (Collect J.ide)\"\n        proof -\n          have \"Collect J.ide \\<subseteq> Collect J.arr\"\n            by auto\n          thus ?thesis\n            using finite J.ideD(1) finite_subset by blast\n        qed\n        ultimately show ?thesis\n          using finite has_finite_products' by simp\n      qed\n      moreover have \"has_products (Collect J.arr)\"\n      proof -\n        have \"Collect J.arr \\<noteq> UNIV\"\n          using J.not_arr_null by blast\n        thus ?thesis\n          using finite has_finite_products' by simp\n      qed\n      ultimately show \"has_limits_of_shape J\"\n        using J.category_axioms has_limits_if_has_products [of J] by simp\n    qed\n\n  end\n\nend\n\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Category3/HFSetCat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8824278757303677, "lm_q1q2_score": 0.7982888499674193}}
{"text": "theory MyNat imports Main\nbegin\n\n(* This is the first part of the workshop, introducing some basic concepts of\n   Isabelle through some small examples about natural numbers *)\n\n(*\n   Unary natural numbers\n*)\n\ndatatype mynat =\n  M0\n  | MS \"mynat\"\n\n(* This looks simple, right? In fact, Isabelle is doing a lot of work behind the scenes\n   to present us with the ability to define datatypes this way. Try querying \"name:mynat\"\n   (without quotes) in the \"find theorems\" pane if you don't believe me :)\n*)\n\nfun mynatD :: \"mynat \\<Rightarrow> nat\" where\n\"mynatD M0 = 0\"\n| \"mynatD (MS m') = 1 + mynatD m'\"\n\nfun mynat_plus :: \"mynat \\<Rightarrow> mynat \\<Rightarrow> mynat\" where\n\"mynat_plus M0 x = x\"\n| \"mynat_plus (MS x1) x2 = mynat_plus x1 (MS x2)\"\n\nfun mynat_minus :: \"mynat \\<Rightarrow> mynat \\<Rightarrow> mynat\" where\n\"mynat_minus M0 x2 = M0\"\n| \"mynat_minus x1 (M0) = x1\"\n| \"mynat_minus (MS x1) (MS x2) =\n   mynat_minus x1 x2\"\n\nfunction (sequential) mynat_minus' :: \"mynat \\<Rightarrow> mynat \\<Rightarrow> mynat\" where\n\"mynat_minus' M0 x2 = M0\"\n| \"mynat_minus' x1 (M0) = x1\"\n| \"mynat_minus' (MS x1) (MS x2) =\n   mynat_minus' x1 x2\"\n  by pat_completeness auto\n\n(*termination by lexicographic_order*)\n(* termination by size_change *)\n\ntermination\nproof(relation \"measure (\\<lambda> (n1, n2) . mynatD n1)\")\n  show \"wf (measure (\\<lambda>(n1, n2). mynatD n1))\"\n    by auto\nnext\n  fix x1 x2\n  show \"((x1, x2), MS x1, MS x2) \\<in> measure (\\<lambda>(n1, n2). mynatD n1)\"\n    by auto\nqed\n\nlemma mynat_plus_correct :\n  \"mynatD (mynat_plus x1 x2) =\n   mynatD x1 + mynatD x2\"\nproof(induction x1 arbitrary: x2)\ncase M0\n  then show ?case by(auto)\nnext\n  case (MS x1)\n    (*  then show ?case by auto *)\n\n    (* let's be pedantic and look at a more manual argument. *)\n  show ?case\n    unfolding mynat_plus.simps\n    using MS.prems MS.IH[of \"MS x2\"]\n    unfolding mynatD.simps\n    by simp (* Isabelle's arithmetic automation handles things from here. *)\nqed\n\nfun mynat_times :: \"mynat \\<Rightarrow> mynat \\<Rightarrow> mynat\" where\n\"mynat_times M0 _ = M0\"\n| \"mynat_times (MS x) y = mynat_plus y (mynat_times x y)\"\n\n(* checking results of a computation is easy!\n   (We can generate Haskell/ML code using a related mechanism) *)\n(* 2 * 3 = 6 *)\nvalue \"mynatD (mynat_times (MS (MS (MS M0))) (MS (MS M0)))\"\n\n\n(*\n * Inductive predicates: evenness and oddness\n *)\n\n(* other uses of induction in isabelle: inductive predicates! *)\ninductive myeven :: \"mynat \\<Rightarrow> bool\" and\n          myodd :: \"mynat \\<Rightarrow> bool\" where\n\"myeven M0\"\n| \"myeven x \\<Longrightarrow> myodd (MS x)\"\n| \"myodd x \\<Longrightarrow> myeven (MS x)\"\n\n(* an example of an apply-style proof - \n   good for experimentation, but less maintainable. *)\nlemma three_odd : \"myodd (MS (MS (MS (M0))))\"\n  apply(rule myeven_myodd.intros)\n  apply(rule myeven_myodd.intros)\n  apply(rule myeven_myodd.intros)\n  apply(rule myeven_myodd.intros)\n  done\n\n(* or, more automated: *)\nlemma three_odd' : \"myodd (MS (MS (MS (M0))))\"\n  by(auto intro: myeven_myodd.intros)\n\ndefinition mynat_two :: \"mynat\" where\n\"mynat_two = MS (MS (M0))\"\n\n(* we could have defined even and odd differently: *)\n\n(* definition is used for defining non-recursive things *)\ndefinition myeven' :: \"mynat \\<Rightarrow> bool\" where\n\"myeven' x =  (\\<exists> x' . x = mynat_times mynat_two x')\"\n\ndefinition myodd' :: \"mynat \\<Rightarrow> bool\" where\n\"myodd' x = (\\<exists> x' . x = MS (mynat_times mynat_two x'))\"\n\n(* which is better? the non-inductive definitions tend to be easier to\n   compute with, but at the cost of potentially obscuring the inductive structure\n   of the predicates, which may complicate some proofs *)\n\n(* exercise, possibly annoying: show these definitions are equivalent *)\n\n(*\n * Rational numbers: a taste of Isabelle typedefs\n *)\n\n\n(* Originally I was going to try to show this proof using the natural numbers developed\n   above, but the details of the proof got annoying. *)\n\n(* isabelle's answer to dependent types: subset types!\n   all types (even mynat, e.g.), except for some extremely basic ones,\n   are defined \"under the hood\" as\n   nonempty subsets of different\n   existing types *)\n\n\ndefinition coprime :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"coprime x y =\n  (\\<forall> n x' y' . n * x' = x \\<longrightarrow> n * y' = y \\<longrightarrow> n = 1)\"\n\n(* convenience lemma for more easily applying coprime in Isabelle proof scripts (see below)\n   \"E\" stands for eliminator (though this might technically be a destructor)\n *)\nlemma coprimeE :\n  assumes H : \"coprime x y\"\n  assumes Hx : \"n * x' = x\"\n  assumes Hy : \"n * y' = y\"\n  shows \"n = 1\" using assms\n  unfolding coprime_def by auto\n\nlemma mul_bound :\n  fixes a b c :: nat\n  assumes H1 : \"a * b = c\"\n  assumes H2 : \"c \\<noteq> 0\"\n  shows \"a \\<le> c\" using assms\nproof-\n\n  have Bnz : \"1 \\<le> b\" using H1 H2\n    by(cases b; auto)\n\n  hence \"1 * a \\<le> b * a\" by auto\n\n  thus \"a \\<le> c\" using H1 by  auto\nqed\n\ntypedef myrat = \"{xy :: (nat * nat) .\n                  (case xy of (x, y) \\<Rightarrow> coprime x y)}\"\n(* cool, but now we need to show this set isn't empty\n   (no, there is no empty/False type in Isabelle's logic - another key\n    difference from CiC/dependent types based systems.)\n*)\nproof-\n  have \"coprime 2 3\" unfolding coprime_def\n  proof(step+)\n    fix n x' y' :: nat\n    assume Hx : \"n * x' = 2\"\n    assume Hy : \"n * y' = 3\"\n\n    have Xnz : \"0 < x'\" using Hx by (cases x'; auto)\n    have Ynz : \"0 < y'\" using Hy by (cases y'; auto)\n    have Nnz : \"0 < n\" using Hy by (cases n; auto)\n\n    have Bound : \"n \\<le> 2\" using mul_bound[OF Hx] by auto\n\n    show \"n = 1\"\n    proof(cases n)\n      case 0\n      then show ?thesis using Nnz by auto\n    next\n      case Suc1 : (Suc n')\n      then show ?thesis\n      proof(cases n')\n        case 0 (* n = 1 *)\n        then show ?thesis using Suc1 by auto\n      next\n        case Suc2 : (Suc n'') \n        then show ?thesis\n        proof(cases n'')\n          case 0 (* n = 2 is the only interesting case really *)\n\n          hence N2 : \"n = 2\" using Suc1 Suc2 by auto\n\n          have Hy' : \"y' * n = 3\" using Hy by(simp add: mult.commute)\n\n          have Bound' : \"y' \\<le> 3\" using mul_bound[OF Hy'] by auto\n\n          (* out of laziness i am not going to write out the full case analysis on y here *)\n          then show ?thesis using N2 Hy'\n            by(cases y'; auto)\n        next\n          case Suc3 : (Suc n''')\n          then show ?thesis using Suc1 Suc2 Suc3 Bound by auto\n        qed\n      qed\n    qed\n  qed\n\n  then show \"\\<exists>x. x \\<in> {xy. case xy of (x, y) \\<Rightarrow> MyNat.coprime x y}\"\n    by auto\nqed\n\n(* luckily Isabelle provides primitives for working with typedef'd types more\n   conveniently - handles a lot of annoying bookkeeping that comes with converting\n   between (nat * nat) and myrat, which while the same structurally are\n   different types from Isabelle's point of view. *)\nsetup_lifting type_definition_myrat\n\n(* an example of an \"admitted\" theorem.\n   be careful with these, you can \"prove\" absurdities!\n   proving this may be annoying because we may need to show a bunch of basic\n   mathematical identities. As we'll see below, Isabelle's standard library\n   contains such theorems, which is a good reason to use the standard natural\n   numbers (and other datatypes too) instead of rolling your own\n*)\nlemma coprime_square : \"coprime a b \\<Longrightarrow> coprime (a * a) (b * b)\" sorry\n\ndefinition rat_square' :: \"(nat * nat) \\<Rightarrow> (nat * nat)\" where\n\"rat_square' xy =\n  (case xy of (x, y) \\<Rightarrow> ((x * x), (y * y)))\"\n\n\n(* a lifted definition, giving us a function we can use on the typedef'd type *)\nlift_definition rat_square :: \"myrat \\<Rightarrow> myrat\" is rat_square'\n  using coprime_square unfolding rat_square'_def  \n  by(auto)\n\n\n(*\n * A (sort of) interesting theorem: square root of 2 is irrational\n *)\n\n(* we could use what we developed above to prove that sqrt(2) is irrational, but let's simplify\n   things again and just express this directly on natural numbers. \n   this will let us use some library theorems.\n\n   note the number of library lemmas we end up using here\n   (a fun exercise might be seeing if the automation can get through parts of this proof\n    with less hand-holding - although arguably the result would be a less clear proof)\n*)\n\nlemma sqrt2_irrational :\n  fixes x :: nat\n  fixes y :: nat\n  assumes Coprime : \"coprime x y\"\n  assumes Hxy : \"x * x = 2 * y * y\"\n  shows False\nproof-\n  have  \"(2 * y * y) mod 2 = 0\" using Hxy mod_mult_self2_is_0[of \"y * y\" 2] by auto\n  hence \"x * x mod 2 = 0\" using Hxy by auto\n\n  hence Xeven : \"x mod 2 = 0\" using sym[OF mod_mult_eq[of x 2 x]] by auto\n\n  obtain x' where X' : \"x = 2 * x'\"\n    using mod_eq_0D[OF Xeven] by auto\n\n  then have \"4 * x' * x' = 2 * y * y\" using Hxy by auto\n\n  then have Hxy' : \"2 * x' * x' = y * y\" by auto\n\n(* now we repeat the above argument to show y must be even and derive a contradiction *)\n  have  \"(2 * x' * x') mod 2 = 0\" using Hxy mod_mult_self2_is_0[of \"x' * x'\" 2] by auto\n  hence \"y * y mod 2 = 0\" using Hxy' by auto\n\n  hence Yeven : \"y mod 2 = 0\" using sym[OF mod_mult_eq[of x 2 x]] by auto\n\n  obtain y' where Y' : \"y = 2 * y'\"\n    using mod_eq_0D[OF Yeven] by auto\n\n  (* unfolding the definition of Coprime into Isabelle's meta-logic in order to\n     make it easier to work with here - this could be done as a separate lemma\n     (in fact there's probably automation for it, I just don't know how to use it. *)\n  show False using coprimeE[OF Coprime, of 2 x' y'] X' Y' by auto\nqed \n    \n\nend", "meta": {"author": "mmalvarez", "repo": "CS-isabelle-tutorial", "sha": "b64a2892b74cd1845be50accc5f144dc37425b00", "save_path": "github-repos/isabelle/mmalvarez-CS-isabelle-tutorial", "path": "github-repos/isabelle/mmalvarez-CS-isabelle-tutorial/CS-isabelle-tutorial-b64a2892b74cd1845be50accc5f144dc37425b00/MyNat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898305367525, "lm_q2_score": 0.8807970811069351, "lm_q1q2_score": 0.7979931982493385}}
{"text": "section \\<open>Challenge 1.B\\<close>\ntheory Challenge1B\n  imports Challenge1A \"HOL-Library.Multiset\"\nbegin\n\n(* TODO: Move *)\nlemma mset_concat:\n  \"mset (concat xs) = fold (+) (map mset xs) {#}\"\nproof -\n  have \"mset (concat xs) + a = fold (+) (map mset xs) a\" for a\n  proof2 (induction xs arbitrary: a)\n    case Nil\n    then show ?case\n      by auto\n  next\n    case (Cons x xs)\n    show ?case\n      using Cons.IH[of \"mset x + a\", symmetric] by simp\n  qed\n  from this[of \"{#}\"] show ?thesis\n    by auto\nqed\n\nsubsection \\<open>Merging Two Segments\\<close>\n\nfun merge :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"merge [] l2 = l2\"\n | \"merge l1 [] = l1\"\n | \"merge (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then x1 # (merge l1 (x2 # l2)) else x2 # (merge (x1 # l1) l2))\"\n\nlemma merge_correct:\n  assumes \"sorted l1\"\n  assumes \"sorted l2\"\n  shows \"\n    sorted (merge l1 l2)\n  \\<and> mset (merge l1 l2) = mset l1 + mset l2\n  \\<and> set (merge l1 l2) = set l1 \\<union> set l2\"\n  using assms\nproof2 (induction l1 arbitrary: l2)\n  case Nil thus ?case\n    by simp\nnext\n  case (Cons x1 l1 l2)\n  note IH = Cons.IH\n\n  show ?case\n    using Cons.prems\n  proof2 (induction l2)\n    case Nil then show ?case\n      by simp\n  next\n    case (Cons x2 l2)\n    then show ?case\n      using IH by (force split: if_split_asm)\n  qed\nqed\n\nsubsection \\<open>Merging a List of Segments\\<close>\n\nfunction merge_list :: \"'a::{linorder} list list \\<Rightarrow> 'a list list \\<Rightarrow> 'a list\" where\n   \"merge_list [] [] = []\"\n | \"merge_list [] [l] = l\"\n | \"merge_list (la # acc2) [] = merge_list [] (la # acc2)\"\n | \"merge_list (la # acc2) [l] = merge_list [] (l # la # acc2)\"\n | \"merge_list acc2 (l1 # l2 # ls) =\n    merge_list ((merge l1 l2) # acc2) ls\"\nby pat_completeness simp_all\ntermination by (relation \"measure (\\<lambda>(acc, ls). 3 * length acc + 2 * length ls)\"; simp)\n\nlemma merge_list_correct:\nassumes \"\\<And>l. l \\<in> set ls \\<Longrightarrow> sorted l\"\nassumes \"\\<And>l. l \\<in> set as \\<Longrightarrow> sorted l\"\nshows \"\n  sorted (merge_list as ls)\n\\<and> mset (merge_list as ls) = mset (concat (as @ ls))\n\\<and> set (merge_list as ls) = set (concat (as @ ls))\"\nusing assms\nproof2 (induction as ls rule: merge_list.induct)\nnext\n  case (4 la acc2 l)\n  then show ?case\n    by (auto simp: algebra_simps)\nnext\n  case (5 acc2 l1 l2 ls)\n  have \"sorted (merge_list (merge l1 l2 # acc2) ls)\n    \\<and> mset (merge_list (merge l1 l2 # acc2) ls) = mset (concat ((merge l1 l2 # acc2) @ ls))\n    \\<and> set (merge_list (merge l1 l2 # acc2) ls) = set (concat ((merge l1 l2 # acc2) @ ls))\"\n    using 5(2-) merge_correct[of l1 l2] by (intro 5(1)) auto\n  then show ?case\n    using merge_correct[of l1 l2] 5(2-) by auto\nqed simp+\n\nsubsection \\<open>GHC-Sort\\<close>\n\ndefinition\n  \"ghc_sort xs = merge_list [] (map (\\<lambda>ys. if decr ys then rev ys else ys) (cuts xs))\"\n\nlemma decr_sorted:\n  assumes \"decr xs\"\n  shows \"sorted (rev xs)\"\n  using assms apply2 (induction xs rule: decr.induct) by(auto simp: sorted_append)\n\nlemma incr_sorted:\n  assumes \"incr xs\"\n  shows \"sorted xs\"\n  using assms apply2 (induction xs rule: incr.induct) by auto\n\nlemma reverse_phase_sorted:\n  \"\\<forall>ys \\<in> set (map (\\<lambda>ys. if decr ys then rev ys else ys) (cuts xs)). sorted ys\"\n  using cuts_incr_decr by (auto intro: decr_sorted incr_sorted)\n\nlemma reverse_phase_elements:\n  \"set (concat (map (\\<lambda>ys. if decr ys then rev ys else ys) (cuts xs))) = set xs\"\nproof -\n  have \"set (concat (map (\\<lambda>ys. if decr ys then rev ys else ys) (cuts xs)))\n    = set (concat (cuts xs))\"\n    by auto\n  also have \"\\<dots> = set xs\"\n    by (simp add: concat_cuts)\n  finally show ?thesis .\nqed\n\nlemma reverse_phase_permutation:\n  \"mset (concat (map (\\<lambda>ys. if decr ys then rev ys else ys) (cuts xs))) = mset xs\"\nproof -\n  have \"mset (concat (map (\\<lambda>ys. if decr ys then rev ys else ys) (cuts xs)))\n    = mset (concat (cuts xs))\"\n    unfolding mset_concat by (auto simp: comp_def intro!: arg_cong2[where f = \"fold (+)\"])\n  also have \"\\<dots> = mset xs\"\n    by (simp add: concat_cuts)\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Correctness Lemmas\\<close>\ntext \\<open>The result is sorted and a permutation of the original elements.\\<close>\n\ntheorem sorted_ghc_sort:\n  \"sorted (ghc_sort xs)\"\n  unfolding ghc_sort_def using reverse_phase_sorted\n  by (intro merge_list_correct[THEN conjunct1]) auto\n\ntheorem permutation_ghc_sort:\n  \"mset (ghc_sort xs) = mset xs\"\n  unfolding ghc_sort_def\n  apply (subst merge_list_correct[THEN conjunct2])\n  subgoal\n    using reverse_phase_sorted by auto\n  subgoal\n    using reverse_phase_sorted by auto\n  apply (subst (2) reverse_phase_permutation[symmetric])\n  apply simp\n  done\n\ncorollary elements_ghc_sort: \"set (ghc_sort xs) = set xs\"\n  using permutation_ghc_sort by (metis set_mset_mset)\n\nsubsection \\<open>Executable Code\\<close>\n(*\nexport_code ghc_sort checking SML Scala OCaml? Haskell?\n*)\nvalue [code] \"ghc_sort [1,2,7,3,5,6,9,8,4]\"\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/VerifyThis2019/Challenge1B.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8918110461567923, "lm_q1q2_score": 0.7979831348591672}}
{"text": "theory Chapter4\nimports \"~~/src/HOL/IMP/ASM\"\nbegin\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  for r where\nrefl:  \"star r x x\" |\nstep:  \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ntext{*\n\\section*{Chapter 4}\n\n\\exercise\nFormalize the following definition of palindromes\n\\begin{itemize}\n\\item The empty list and a singleton list are palindromes.\n\\item If @{text xs} is a palindrome, so is @{term \"a # xs @ [a]\"}.\n\\end{itemize}\nas an inductive predicate\n*}\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\npalindromeE: \"palindrome []\" |\npalindromeSS: \"palindrome xs \\<Longrightarrow> palindrome (x # xs @ [x])\"\n\ntext {* and prove *}\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\napply (induction rule: palindrome.induct)\n  apply(simp)\n  apply(simp)\ndone\n\ntext{*\n\\exercise\nIn Chapter 3 we defined a recursive evaluation function\n@{text \"aval ::\"} @{typ \"aexp \\<Rightarrow> state \\<Rightarrow> val\"}.\nDefine an inductive evaluation predicate and prove that it agrees with\nthe recursive function:\n*}\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n  n: \"aval_rel (N n) s n\" |\n  v: \"aval_rel (V v) s (s v)\" |\n  p: \"\\<lbrakk>aval_rel a\\<^sub>1 s v\\<^sub>1; aval_rel a\\<^sub>2 s v\\<^sub>2\\<rbrakk> \\<Longrightarrow> aval_rel (Plus a\\<^sub>1 a\\<^sub>2) s (v\\<^sub>1 + v\\<^sub>2)\"\n\nlemma aval_rel_aval: \"aval_rel a s v \\<Longrightarrow> aval a s = v\"\n  apply (induction rule:\"aval_rel.induct\")\n  apply simp\n  apply simp\n  apply simp\ndone\n\nlemma aval_aval_rel: \"aval a s = v \\<Longrightarrow> aval_rel a s v\"\n  apply (induction a arbitrary: s v)\n  apply auto\n  apply (rule aval_rel.n)\n  apply (rule aval_rel.v)\n  apply (rule aval_rel.p)\n  apply auto\ndone\n\ncorollary \"aval_rel a s v \\<longleftrightarrow> aval a s = v\"\n  apply auto\n  apply (rule aval_rel_aval)\n  apply simp\n  apply (rule aval_aval_rel)\n  apply simp\ndone\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider the stack machine from Chapter~3\nand recall the concept of \\concept{stack underflow}\nfrom Exercise~\\ref{exe:stack-underflow}.\nDefine an inductive predicate\n*}\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{*\nsuch that @{text \"ok n is n'\"} means that with any initial stack of length\n@{text n} the instructions @{text \"is\"} can be executed\nwithout stack underflow and that the final stack has length @{text n'}.\n\nUsing the introduction rules for @{const ok},\nprove the following special cases: *}\n\nlemma \"ok 0 [LOAD x] (Suc 0)\"\n(* your definition/proof here *)\n\nlemma \"ok 0 [LOAD x, LOADI v, ADD] (Suc 0)\"\n(* your definition/proof here *)\n\nlemma \"ok (Suc (Suc 0)) [LOAD x, ADD, ADD, LOAD y] (Suc (Suc 0))\"\n(* your definition/proof here *)\n\ntext {* Prove that @{text ok} correctly computes the final stack size: *}\n\nlemma \"\\<lbrakk>ok n is n'; length stk = n\\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"\n(* your definition/proof here *)\n\ntext {*\nProve that instruction sequences generated by @{text comp}\ncannot cause stack underflow: \\ @{text \"ok n (comp a) ?\"} \\ for\nsome suitable value of @{text \"?\"}.\n\\endexercise\n*}\n\n\nend\n\n", "meta": {"author": "HrNilsson", "repo": "concrete-semantics", "sha": "e8d4cb6a0be5dc004eae15a08b29d8fc4dba7184", "save_path": "github-repos/isabelle/HrNilsson-concrete-semantics", "path": "github-repos/isabelle/HrNilsson-concrete-semantics/concrete-semantics-e8d4cb6a0be5dc004eae15a08b29d8fc4dba7184/Exercises/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.7979274209254107}}
{"text": "(*  Title:      HOL/Induct/ABexp.thy\n    Author:     Stefan Berghofer, TU Muenchen\n*)\n\nsection {* Arithmetic and boolean expressions *}\n\ntheory ABexp\nimports Main\nbegin\n\ndatatype 'a aexp =\n    IF \"'a bexp\"  \"'a aexp\"  \"'a aexp\"\n  | Sum \"'a aexp\"  \"'a aexp\"\n  | Diff \"'a aexp\"  \"'a aexp\"\n  | Var 'a\n  | Num nat\nand 'a bexp =\n    Less \"'a aexp\"  \"'a aexp\"\n  | And \"'a bexp\"  \"'a bexp\"\n  | Neg \"'a bexp\"\n\n\ntext {* \\medskip Evaluation of arithmetic and boolean expressions *}\n\nprimrec evala :: \"('a => nat) => 'a aexp => nat\"\n  and evalb :: \"('a => nat) => 'a bexp => bool\"\nwhere\n  \"evala env (IF b a1 a2) = (if evalb env b then evala env a1 else evala env a2)\"\n| \"evala env (Sum a1 a2) = evala env a1 + evala env a2\"\n| \"evala env (Diff a1 a2) = evala env a1 - evala env a2\"\n| \"evala env (Var v) = env v\"\n| \"evala env (Num n) = n\"\n\n| \"evalb env (Less a1 a2) = (evala env a1 < evala env a2)\"\n| \"evalb env (And b1 b2) = (evalb env b1 \\<and> evalb env b2)\"\n| \"evalb env (Neg b) = (\\<not> evalb env b)\"\n\n\ntext {* \\medskip Substitution on arithmetic and boolean expressions *}\n\nprimrec substa :: \"('a => 'b aexp) => 'a aexp => 'b aexp\"\n  and substb :: \"('a => 'b aexp) => 'a bexp => 'b bexp\"\nwhere\n  \"substa f (IF b a1 a2) = IF (substb f b) (substa f a1) (substa f a2)\"\n| \"substa f (Sum a1 a2) = Sum (substa f a1) (substa f a2)\"\n| \"substa f (Diff a1 a2) = Diff (substa f a1) (substa f a2)\"\n| \"substa f (Var v) = f v\"\n| \"substa f (Num n) = Num n\"\n\n| \"substb f (Less a1 a2) = Less (substa f a1) (substa f a2)\"\n| \"substb f (And b1 b2) = And (substb f b1) (substb f b2)\"\n| \"substb f (Neg b) = Neg (substb f b)\"\n\nlemma subst1_aexp:\n  \"evala env (substa (Var (v := a')) a) = evala (env (v := evala env a')) a\"\nand subst1_bexp:\n  \"evalb env (substb (Var (v := a')) b) = evalb (env (v := evala env a')) b\"\n    --  {* one variable *}\n  by (induct a and b) simp_all\n\nlemma subst_all_aexp:\n  \"evala env (substa s a) = evala (\\<lambda>x. evala env (s x)) a\"\nand subst_all_bexp:\n  \"evalb env (substb s b) = evalb (\\<lambda>x. evala env (s x)) b\"\n  by (induct a and b) auto\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Induct/ABexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7978919570408796}}
{"text": "(*\n  File: Group_Sort.thy\n  Author: Manuel Eberl <eberlm@in.tum.de>\n\n  A sorting algorithm that sorts values according to a key function and groups equivalent \n  elements using a commutative and associative binary operation.\n*)\nsection \\<open>Sorting and grouping factors\\<close>\n\ntheory Group_Sort\nimports Main \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>\n  For the reification of products of powers of primitive functions such as\n  @{term \"\\<lambda>x. x * ln x ^2\"} into a canonical form, we need to be able to sort the factors \n  according to the growth of the primitive function it contains and merge terms with the same \n  function by adding their exponents. The following locale defines such an operation in a \n  general setting; we can then instantiate it for our setting.\n\n  The locale takes as parameters a key function @{term \"f\"} that sends list elements into a \n  linear ordering that determines the sorting order, a @{term \"merge\"} function to merge to \n  equivalent (w.r.t. @{term \"f\"}) elements into one, and a list reduction function @{term \"g\"} \n  that reduces a list to a single value. This function must be invariant w.r.t. the order of \n  list elements and be compatible with merging of equivalent elements. In our case, this list \n  reduction function will be the product of all list elements.\n\\<close>\n\nlocale groupsort = \n  fixes f :: \"'a \\<Rightarrow> ('b::linorder)\"\n  fixes merge :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  fixes g :: \"'a list \\<Rightarrow> 'c\"\n  assumes f_merge: \"f x = f y \\<Longrightarrow> f (merge x y) = f x\"\n  assumes g_cong: \"mset xs = mset ys \\<Longrightarrow> g xs = g ys\"\n  assumes g_merge: \"f x = f y \\<Longrightarrow> g [x,y] = g [merge x y]\"\n  assumes g_append_cong: \"g xs1 = g xs2 \\<Longrightarrow> g ys1 = g ys2 \\<Longrightarrow> g (xs1 @ ys1) = g (xs2 @ ys2)\"\nbegin\n\ncontext\nbegin\n\nprivate function part_aux :: \n  \"'b \\<Rightarrow> 'a list \\<Rightarrow> ('a list) \\<times> ('a list) \\<times> ('a list) \\<Rightarrow> ('a list) \\<times> ('a list) \\<times> ('a list)\" \nwhere\n  \"part_aux p [] (ls, eq, gs) = (ls, eq, gs)\"\n| \"f x < p \\<Longrightarrow> part_aux p (x#xs) (ls, eq, gs) = part_aux p xs (x#ls, eq, gs)\"\n| \"f x > p \\<Longrightarrow> part_aux p (x#xs) (ls, eq, gs) = part_aux p xs (ls, eq, x#gs)\"\n| \"f x = p \\<Longrightarrow> part_aux p (x#xs) (ls, eq, gs) = part_aux p xs (ls, eq@[x], gs)\"\nproof (clarify, goal_cases)\n  case prems: (1 P p xs ls eq gs)\n  show ?case\n  proof (cases xs)\n    fix x xs' assume \"xs = x # xs'\"\n    thus ?thesis using prems by (cases \"f x\" p rule: linorder_cases) auto\n  qed (auto intro: prems(1))\nqed simp_all\ntermination by (relation \"Wellfounded.measure (size \\<circ> fst \\<circ> snd)\") simp_all\n\nprivate lemma groupsort_locale: \"groupsort f merge g\" by unfold_locales\n\nprivate lemmas part_aux_induct = part_aux.induct[split_format (complete), OF groupsort_locale]\n\nprivate definition part where \"part p xs = part_aux (f p) xs ([], [p], [])\"\n\nprivate lemma part: \n  \"part p xs = (rev (filter (\\<lambda>x. f x < f p) xs), \n     p # filter (\\<lambda>x. f x = f p) xs, rev (filter (\\<lambda>x. f x > f p) xs))\"\nproof-\n  {\n    fix p xs ls eq gs\n    have \"fst (part_aux p xs (ls, eq, gs)) = rev (filter (\\<lambda>x. f x < p) xs) @ ls\"\n      by (induction p xs ls eq gs rule: part_aux_induct) simp_all\n  } note A = this\n  {\n    fix p xs ls eq gs\n    have \"snd (snd (part_aux p xs (ls, eq, gs))) = rev (filter (\\<lambda>x. f x > p) xs) @ gs\"\n      by (induction p xs ls eq gs rule: part_aux_induct) simp_all\n  } note B = this\n  {\n    fix p xs ls eq gs\n    have \"fst (snd (part_aux p xs (ls, eq, gs))) = eq @ filter (\\<lambda>x. f x = p) xs\"\n      by (induction p xs ls eq gs rule: part_aux_induct) auto\n  } note C = this\n  note ABC = A B C\n  from ABC[of \"f p\" xs \"[]\" \"[p]\" \"[]\"] show ?thesis unfolding part_def\n    by (intro prod_eqI) simp_all\nqed\n\nprivate function sort :: \"'a list \\<Rightarrow> 'a list\" where\n  \"sort [] = []\"\n| \"sort (x#xs) = (case part x xs of (ls, eq, gs) \\<Rightarrow> sort ls @ eq @ sort gs)\"\nby pat_completeness simp_all\ntermination by (relation \"Wellfounded.measure length\") (simp_all add: part less_Suc_eq_le)\n\nprivate lemma filter_mset_union:\n  assumes \"\\<And>x. x \\<in># A \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> False\"\n  shows \"filter_mset P A + filter_mset Q A = filter_mset (\\<lambda>x. P x \\<or> Q x) A\" (is \"?lhs = ?rhs\")\n  using assms by (auto simp add: count_eq_zero_iff intro!: multiset_eqI) blast\n\nprivate lemma multiset_of_sort: \"mset (sort xs) = mset xs\"\nproof (induction xs rule: sort.induct)\n  case (2 x xs)\n  let ?M = \"\\<lambda>oper. {#y:# mset xs. oper (f y) (f x)#}\"\n  from 2 have \"mset (sort (x#xs)) = ?M (<) + ?M (=) + ?M (>) + {#x#}\"\n    by (simp add: part Multiset.union_assoc mset_filter)\n  also have \"?M (<) + ?M (=) + ?M (>) = mset xs\"\n    by ((subst filter_mset_union, force)+, subst multiset_eq_iff, force)\n  finally show ?case by simp\nqed simp\n\nprivate lemma g_sort: \"g (sort xs) = g xs\"\n  by (intro g_cong multiset_of_sort)\n\nprivate lemma set_sort: \"set (sort xs) = set xs\"\n  using arg_cong[OF multiset_of_sort[of xs], of \"set_mset\"] by (simp only: set_mset_mset)\n\nprivate \n\nprivate lemma sorted_sort: \"sorted (map f (sort xs))\"\napply (induction xs rule: sort.induct)\napply simp\napply (simp only: sorted_append sort.simps part map_append split)\napply (intro conjI TrueI)\nusing sorted_map_same by (auto simp: set_sort)\n\n\n\nprivate fun group where\n  \"group [] = []\"\n| \"group (x#xs) = (case partition (\\<lambda>y. f y = f x) xs of (xs', xs'') \\<Rightarrow> \n                     fold merge xs' x # group xs'')\"\n\nprivate lemma f_fold_merge: \"(\\<And>y. y \\<in> set xs \\<Longrightarrow> f y = f x) \\<Longrightarrow> f (fold merge xs x) = f x\"\n  by (induction xs rule: rev_induct) (auto simp: f_merge)\n\nprivate lemma f_group: \"x \\<in> set (group xs) \\<Longrightarrow> \\<exists>x'\\<in>set xs. f x = f x'\"\nproof (induction xs rule: group.induct)\n  case (2 x' xs)\n  hence \"x = fold merge [y\\<leftarrow>xs . f y = f x'] x' \\<or> x \\<in> set (group [xa\\<leftarrow>xs . f xa \\<noteq> f x'])\"\n    by (auto simp: o_def)\n  thus ?case\n  proof\n    assume \"x = fold merge [y\\<leftarrow>xs . f y = f x'] x'\"\n    also have \"f ... = f x'\" by (rule f_fold_merge) simp\n    finally show ?thesis by simp\n  next\n    assume \"x \\<in> set (group [xa\\<leftarrow>xs . f xa \\<noteq> f x'])\"\n    from 2(1)[OF _ this] have \"\\<exists>x'\\<in>set [xa\\<leftarrow>xs . f xa \\<noteq> f x']. f x = f x'\" by (simp add: o_def)\n    thus ?thesis by force\n  qed\nqed simp\n\nprivate lemma sorted_group: \"sorted (map f xs) \\<Longrightarrow> sorted (map f (group xs))\"\nproof (induction xs rule: group.induct)\n  case (2 x xs)\n  {\n    fix x' assume x': \"x' \\<in> set (group [y\\<leftarrow>xs . f y \\<noteq> f x])\"\n    with f_group obtain x'' where x'': \"x'' \\<in> set xs\" \"f x' = f x''\" by force\n    have \"f (fold merge [y\\<leftarrow>xs . f y = f x] x) = f x\"\n      by (subst f_fold_merge) simp_all\n    also from 2(2) x'' have \"... \\<le> f x'\" by (auto) \n    finally have \"f (fold merge [y\\<leftarrow>xs . f y = f x] x) \\<le> f x'\" .\n  }\n  moreover from 2(2) have \"sorted (map f (group [xa\\<leftarrow>xs . f xa \\<noteq> f x]))\"\n    by (intro 2 sorted_filter) (simp_all add: o_def)\n  ultimately show ?case by (simp add: o_def)\nqed simp_all\n\nprivate lemma distinct_group: \"distinct (map f (group xs))\"\nproof (induction xs rule: group.induct)\n  case (2 x xs)\n  have \"distinct (map f (group [xa\\<leftarrow>xs . f xa \\<noteq> f x]))\" by (intro 2) (simp_all add: o_def)\n  moreover have \"f (fold merge [y\\<leftarrow>xs . f y = f x] x) \\<notin> set (map f (group [xa\\<leftarrow>xs . f xa \\<noteq> f x]))\"\n    by (rule notI, subst (asm) f_fold_merge) (auto dest: f_group)\n  ultimately show ?case by (simp add: o_def)\nqed simp\n\nprivate lemma g_fold_same:\n  assumes \"\\<And>z. z \\<in> set xs \\<Longrightarrow> f z = f x\"\n  shows   \"g (fold merge xs x # ys) = g (x#xs@ys)\"\nusing assms\nproof (induction xs arbitrary: x)\n  case (Cons y xs)\n  have \"g (x # y # xs @ ys) = g (y # x # xs @ ys)\" by (intro g_cong) (auto simp: add_ac)\n  also have \"y # x # xs @ ys = [y,x] @ xs @ ys\" by simp\n  also from Cons.prems have \"g ... = g ([merge y x] @ xs @ ys)\" \n    by (intro g_append_cong g_merge) auto\n  also have \"[merge y x] @ xs @ ys = merge y x # xs @ ys\" by simp\n  also from Cons.prems have \"g ... = g (fold merge xs (merge y x) # ys)\"\n    by (intro Cons.IH[symmetric]) (auto simp: f_merge)\n  also have \"... = g (fold merge (y # xs) x # ys)\" by simp\n  finally show ?case by simp\nqed simp\n\nprivate lemma g_group: \"g (group xs) = g xs\"\nproof (induction xs rule: group.induct)\n  case (2 x xs)\n  have \"g (group (x#xs)) = g (fold merge [y\\<leftarrow>xs . f y = f x] x # group [xa\\<leftarrow>xs . f xa \\<noteq> f x])\"\n    by (simp add: o_def)\n  also have \"... = g (x # [y\\<leftarrow>xs . f y = f x] @ group [y\\<leftarrow>xs . f y \\<noteq> f x])\"\n    by (intro g_fold_same) simp_all\n  also have \"... = g ((x # [y\\<leftarrow>xs . f y = f x]) @ group [y\\<leftarrow>xs . f y \\<noteq> f x])\" (is \"_ = ?A\") by simp\n  also from 2 have \"g (group [y\\<leftarrow>xs . f y \\<noteq> f x]) = g [y\\<leftarrow>xs . f y \\<noteq> f x]\" by (simp add: o_def)\n  hence \"?A = g ((x # [y\\<leftarrow>xs . f y = f x]) @ [y\\<leftarrow>xs . f y \\<noteq> f x])\"\n    by (intro g_append_cong) simp_all\n  also have \"... = g (x#xs)\" by (intro g_cong) (simp_all)\n  finally show ?case .\nqed simp\n\n\nfunction group_part_aux :: \n  \"'b \\<Rightarrow> 'a list \\<Rightarrow> ('a list) \\<times> 'a \\<times> ('a list) \\<Rightarrow> ('a list) \\<times> 'a \\<times> ('a list)\" \nwhere\n  \"group_part_aux p [] (ls, eq, gs) = (ls, eq, gs)\"\n| \"f x < p \\<Longrightarrow> group_part_aux p (x#xs) (ls, eq, gs) = group_part_aux p xs (x#ls, eq, gs)\"\n| \"f x > p \\<Longrightarrow> group_part_aux p (x#xs) (ls, eq, gs) = group_part_aux p xs (ls, eq, x#gs)\"\n| \"f x = p \\<Longrightarrow> group_part_aux p (x#xs) (ls, eq, gs) = group_part_aux p xs (ls, merge x eq, gs)\"\nproof (clarify, goal_cases)\n  case prems: (1 P p xs ls eq gs)\n  show ?case\n  proof (cases xs)\n    fix x xs' assume \"xs = x # xs'\"\n    thus ?thesis using prems by (cases \"f x\" p rule: linorder_cases) auto\n  qed (auto intro: prems(1))\nqed simp_all\ntermination by (relation \"Wellfounded.measure (size \\<circ> fst \\<circ> snd)\") simp_all\n\nprivate lemmas group_part_aux_induct = \n  group_part_aux.induct[split_format (complete), OF groupsort_locale]\n\ndefinition group_part where \"group_part p xs = group_part_aux (f p) xs ([], p, [])\"\n\nprivate lemma group_part: \n  \"group_part p xs = (rev (filter (\\<lambda>x. f x < f p) xs), \n     fold merge (filter (\\<lambda>x. f x = f p) xs) p, rev (filter (\\<lambda>x. f x > f p) xs))\"\nproof-\n  {\n    fix p xs ls eq gs\n    have \"fst (group_part_aux p xs (ls, eq, gs)) = rev (filter (\\<lambda>x. f x < p) xs) @ ls\"\n      by (induction p xs ls eq gs rule: group_part_aux_induct) simp_all\n  } note A = this\n  {\n    fix p xs ls eq gs\n    have \"snd (snd (group_part_aux p xs (ls, eq, gs))) = rev (filter (\\<lambda>x. f x > p) xs) @ gs\"\n      by (induction p xs ls eq gs rule: group_part_aux_induct) simp_all\n  } note B = this\n  {\n    fix p xs ls eq gs\n    have \"fst (snd (group_part_aux p xs (ls, eq, gs))) = \n            fold merge (filter (\\<lambda>x. f x = p) xs) eq\"\n      by (induction p xs ls eq gs rule: group_part_aux_induct) auto\n  } note C = this\n  note ABC = A B C\n  from ABC[of \"f p\" xs \"[]\" \"p\" \"[]\"] show ?thesis unfolding group_part_def\n    by (intro prod_eqI) simp_all\nqed\n\n\nfunction group_sort :: \"'a list \\<Rightarrow> 'a list\" where\n  \"group_sort [] = []\"\n| \"group_sort (x#xs) = (case group_part x xs of (ls, eq, gs) \\<Rightarrow> group_sort ls @ eq # group_sort gs)\"\nby pat_completeness simp_all\ntermination by (relation \"Wellfounded.measure length\") (simp_all add: group_part less_Suc_eq_le)\n\nprivate lemma group_append:\n  assumes \"\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> f x \\<noteq> f y\"\n  shows   \"group (xs @ ys) = group xs @ group ys\"\nusing assms\nproof (induction xs arbitrary: ys rule: length_induct)\n  case (1 xs')\n  hence IH: \"\\<And>x xs ys. length xs < length xs' \\<Longrightarrow> (\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> f x \\<noteq> f y)\n                \\<Longrightarrow> group (xs @ ys) = group xs @ group ys\" by blast\n  show ?case\n  proof (cases xs')\n    case (Cons x xs)\n    note [simp] = this\n    have \"group (xs' @ ys) = fold merge [y\\<leftarrow>xs@ys . f y = f x] x #\n            group ([xa\\<leftarrow>xs . f xa \\<noteq> f x] @ [xa\\<leftarrow>ys . f xa \\<noteq> f x])\" by (simp add: o_def)\n    also from 1(2) have \"[y\\<leftarrow>xs@ys . f y = f x] = [y\\<leftarrow>xs . f y = f x]\"\n      by (force simp: filter_empty_conv)\n    also from 1(2) have \"[xa\\<leftarrow>ys . f xa \\<noteq> f x] = ys\" by (force simp: filter_id_conv)\n    also have \"group ([xa\\<leftarrow>xs . f xa \\<noteq> f x] @ ys) =\n               group [xa\\<leftarrow>xs . f xa \\<noteq> f x] @ group ys\" using 1(2)\n      by (intro IH) (simp_all add: less_Suc_eq_le)\n    finally show ?thesis by (simp add: o_def)\n  qed simp\nqed\n\nprivate lemma group_empty_iff [simp]: \"group xs = [] \\<longleftrightarrow> xs = []\"\n  by (induction xs rule: group.induct) auto\n\nlemma group_sort_correct: \"group_sort xs = group (sort xs)\"\nproof (induction xs rule: group_sort.induct)\n  case (2 x xs)\n  have \"group_sort (x#xs) = \n          group_sort (rev [xa\\<leftarrow>xs . f xa < f x]) @ group (x#[xa\\<leftarrow>xs . f xa = f x]) @\n          group_sort (rev [xa\\<leftarrow>xs . f x < f xa])\" by (simp add: group_part)\n  also have \"group_sort (rev [xa\\<leftarrow>xs . f xa < f x]) = group (sort (rev [xa\\<leftarrow>xs . f xa < f x]))\"\n    by (rule 2) (simp_all add: group_part)\n  also have \"group_sort (rev [xa\\<leftarrow>xs . f xa > f x]) = group (sort (rev [xa\\<leftarrow>xs . f xa > f x]))\"\n    by (rule 2) (simp_all add: group_part)\n  also have \"group (x#[xa\\<leftarrow>xs . f xa = f x]) @ group (sort (rev [xa\\<leftarrow>xs . f xa > f x])) =\n             group ((x#[xa\\<leftarrow>xs . f xa = f x]) @ sort (rev [xa\\<leftarrow>xs . f xa > f x]))\"\n    by (intro group_append[symmetric]) (auto simp: set_sort)\n  also have \"group (sort (rev [xa\\<leftarrow>xs . f xa < f x])) @ ... = \n             group (sort (rev [xa\\<leftarrow>xs . f xa < f x]) @ (x#[xa\\<leftarrow>xs . f xa = f x]) @\n                 sort (rev [xa\\<leftarrow>xs . f xa > f x]))\"\n    by (intro group_append[symmetric]) (auto simp: set_sort)\n  also have \"sort (rev [xa\\<leftarrow>xs . f xa < f x]) @ (x#[xa\\<leftarrow>xs . f xa = f x]) @\n                 sort (rev [xa\\<leftarrow>xs . f xa > f x]) = sort (x # xs)\" by (simp add: part)\n  finally show ?case .\nqed simp\n\n\nlemma sorted_group_sort: \"sorted (map f (group_sort xs))\"\n  by (auto simp: group_sort_correct intro!: sorted_group sorted_sort)\n\n\n\nlemma g_group_sort: \"g (group_sort xs) = g xs\"\n  by (simp add: group_sort_correct g_group g_sort)\n\nlemmas [simp del] = group_sort.simps group_part_aux.simps\n\nend\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Landau_Symbols/Group_Sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.9073122188543453, "lm_q1q2_score": 0.7976606129465154}}
{"text": "theory Ex1_8 \n  imports Main \nbegin \n  \n  \nprimrec ListSum :: \"nat list \\<Rightarrow> nat \" where \n  \"ListSum [] = 0\"|\n  \"ListSum (x#xs) = x + ListSum xs\"\n\nlemma helper : \"ListSum (xs @ ys) = ListSum xs + ListSum ys\" by (induct xs; simp)  \n \ntheorem \"2 * ListSum [0 ..<n+1] = n * (n + 1)\" \nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  assume hyp:\" 2 * ListSum [0..<n + 1] = n * (n + 1)\"  \n  then show ?case by (auto simp add : helper)\nqed\n  \ntheorem \"ListSum (replicate n a) = n * a\" using helper by (induct n; simp)\n    \nprimrec ListSumTAux :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\" where \n  \"ListSumTAux [] res = res\"|\n  \"ListSumTAux (x#xs) res = ListSumTAux xs (res + x)\"\n    \ndefinition ListSumT :: \"nat list \\<Rightarrow> nat \" where \n  \"ListSumT ls = ListSumTAux ls 0\"\n\nlemma \"ListSumTAux xs n  = n + ListSumTAux xs 0\" \nproof (induct xs arbitrary : n)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  note hyp =  this\n  have \" n + ListSumTAux (a # xs) 0  = n + ListSumTAux xs a\"  by (simp)\n  also have \"\\<dots> =  n + a + ListSumTAux xs 0\" by (subst hyp, simp)\n  finally have tmp:\" n + ListSumTAux (a # xs) 0  = n + a + ListSumTAux xs 0\" by assumption\n      \n  have \"ListSumTAux (a # xs) n = ListSumTAux xs (n + a)\" by (simp)\n  also have \"\\<dots> =n + a + ListSumTAux xs 0\" by (subst hyp, rule refl)\n  finally have tmp2:\"ListSumTAux (a # xs) n = n + a + ListSumTAux xs 0\" by simp\n\n  from tmp and tmp2 show ?case by simp \nqed\n  \n  \nlemma helper2 : \"ListSumTAux xs n  = n + ListSumTAux xs 0\" \nproof (induct xs  arbitrary : n)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case  by (metis ListSumTAux.simps(2) semiring_normalization_rules(25) semiring_normalization_rules(5))\nqed\n  \n  \n  \ntheorem \"ListSum xs = ListSumT xs\" \nproof (induct xs)\n  case Nil\n  then show ?case by (simp add : ListSumT_def)\nnext\n  case (Cons a xs)\n  assume hyp:\"ListSum xs = ListSumT xs\"\n  then show ?case by (metis ListSum.simps(2) ListSumTAux.simps(2) ListSumT_def add_cancel_left_left helper2)\nqed\n\ntheorem \"ListSum xs = ListSumT xs\"\nproof (induct xs)\n  case Nil\n  then show ?case by (simp add : ListSumT_def)\nnext\n  case (Cons a xs)\n  assume hyp:\"ListSum xs = ListSumT xs\"\n  have \" ListSum (a#xs) = a + ListSum xs\" by simp\n  also have \"\\<dots> = a + ListSumT xs\" using hyp by simp\n  also have \"\\<dots> = a + ListSumTAux xs 0\" by (simp add: ListSumT_def)\n  also have \"\\<dots> = ListSumTAux xs a\" by (subst helper2, rule refl)\n  also have \"\\<dots> = ListSumTAux (a#xs) 0 \" by (simp)\n  also have \"\\<dots> = ListSumT (a#xs)\" by (simp only : ListSumT_def)\n  finally show ?case by assumption\nqed\n  ", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/1. Lists/Ex1_8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7975625363809922}}
{"text": "theory fol\n  imports Main\nbegin\n\nthm exI\nthm allI\nthm exE\nthm allE\n\nthm impE\n\n(*\nexI: ?P ?x \\<Longrightarrow> \\<exists>x. ?P x\nallI: (\\<And>x. ?P x) \\<Longrightarrow> \\<forall>x. ?P x\nexE: \\<exists>x. ?P x \\<Longrightarrow> (\\<And>x. ?P x \\<Longrightarrow> ?Q) \\<Longrightarrow> ?Q\nallE: \\<forall>x. ?P x \\<Longrightarrow> (?P ?x \\<Longrightarrow> ?R) \\<Longrightarrow> ?R\n*)\n\nlemma ex1: \"(\\<exists>x::int. \\<forall>y::int. x \\<le> y) \\<longrightarrow> (\\<forall>x::int. \\<exists>y::int. y \\<le> x)\"\n  apply (rule impI)\n  apply (rule allI)\n  (* apply (rule exE) *)\n  (* apply (rule_tac P = \"\\<lambda>x. \\<forall>y. x<y\" and Q = \"\\<exists>y. y \\<le> x\" in exE) *)\n  apply (rule_tac P = \"\\<lambda>x. \\<forall>y. x\\<le>y\" in exE)\n   apply assumption\n  apply (rule_tac x = \"xa\" in exI)\n  apply (rule_tac x = \"x\" in allE)\n   apply (assumption)\n  apply (assumption)\n  done\n\nlemma ex2: \"(\\<forall>x.\\<forall>y. P x \\<longrightarrow> Q y) \\<longrightarrow> ( (\\<exists>x. P x)\\<longrightarrow>(\\<forall>y. Q y) )\"\n  apply (rule impI)\n  apply (rule impI)\n  apply (rule allI) (* introduces \\<and>y for Q y in final goal *)\n  apply (rule_tac P = \"\\<lambda>x. P x\" in exE) (* introduces \\<and>x for the existential to have P x *)\n   apply assumption\n  apply (rule_tac P = \"\\<lambda>x. \\<forall>y. P x \\<longrightarrow> Q y\" and x = \"x\" in allE)\n   apply assumption\n  apply (rule_tac P = \"\\<lambda>y. P x \\<longrightarrow> Q y\" and x = \"y\" in allE)\n  (* apply (rule allE) *)\n   apply assumption\n  apply (erule impE)\n   apply assumption\n  apply assumption\n  done\n\n(* TODO do same proof as above but let isabelle unify for you *)\n\nlemma ex3: \"(\\<forall>x. \\<forall>y. P x \\<and> P y) \\<longrightarrow> ( (\\<forall> x. P x) \\<and> (\\<forall>y. P y) )\"\n  apply (rule impI)\n  thm conjI\n  apply (rule conjI)\n   apply (rule allI)\n   apply (rule_tac P = \"\\<lambda> x. \\<forall>y. P x \\<and> P y\" and x = \"x\" in allE)\n    apply assumption\n   apply (rule_tac P = \"\\<lambda>y. P x \\<and> P y\" and x = \"x\" in allE)\n    apply assumption\n   apply (erule conjE)\n   apply assumption\n  apply (rule allI)\n  apply (rule_tac P = \"\\<lambda>x. \\<forall> y. P x \\<and> P y\" and x = \"y\" in allE)\n   apply assumption\n  apply (rule_tac P = \"\\<lambda>ya. P y \\<and> P ya\" and x = \"y\" in allE)\n   apply assumption\n  apply (erule conjE)\n  apply assumption\n\n", "meta": {"author": "brando90", "repo": "cs477", "sha": "665326c27c24669db79c3e5e070f2b8e00a73d02", "save_path": "github-repos/isabelle/brando90-cs477", "path": "github-repos/isabelle/brando90-cs477/cs477-665326c27c24669db79c3e5e070f2b8e00a73d02/lectures/fol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7975625313111822}}
{"text": "theory Demo\nimports Datatype\nbegin\n\ntext {*\n Note: to avoid name clashes with the existing type of lists we build\n on top of Datatype rather than Main. This is an exception!\n*}\n\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n\nprimrec app :: \"'a list => 'a list => 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nprimrec rev :: \"'a list => 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\nvalue \"rev(Cons a (Cons b Nil))\"\n\n\ntext {*\n  Simple proofs:\n\n  Command 'lemma' / 'theorem': state a proposition\n  Attribute 'simp': use this theorem as a simplification rule in future proofs\n  Method 'induct': structural induction\n  Method 'auto':  automatic proof (mostly by simplification)\n  Command 'done':  end of proof\n*}\n\nlemma app_Nil2[simp]: \"app xs Nil = xs\"\napply (induct xs)\napply auto\ndone\n\nlemma app_assoc[simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply (induct xs)\napply auto\ndone\n\nlemma rev_app[simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"\napply (induct xs)\napply auto\ndone\n\ntheorem rev_rev[simp]: \"rev (rev xs) = xs\"\napply (induct xs)\napply auto\ndone\n\n(* Hint for demo:\n   do the proof top down, discovering the lemmas one by one,\n   as described in LNCS2283.\n*)\n\nend\n", "meta": {"author": "AaronCrighton", "repo": "Padics", "sha": "b451038d52193e2c351fe4a44c30c87586335656", "save_path": "github-repos/isabelle/AaronCrighton-Padics", "path": "github-repos/isabelle/AaronCrighton-Padics/Padics-b451038d52193e2c351fe4a44c30c87586335656/Other/Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.7975396713398686}}
{"text": "(*<*)\ntheory Ifexpr imports Main begin\n(*>*)\n\nsubsection{*Case Study: Boolean Expressions*}\n\ntext{*\\label{sec:boolex}\\index{boolean expressions example|(}\nThe aim of this case study is twofold: it shows how to model boolean\nexpressions and some algorithms for manipulating them, and it demonstrates\nthe constructs introduced above.\n*}\n\nsubsubsection{*Modelling Boolean Expressions*}\n\ntext{*\nWe want to represent boolean expressions built up from variables and\nconstants by negation and conjunction. The following datatype serves exactly\nthat purpose:\n*}\n\ndatatype boolex = Const bool | Var nat | Neg boolex\n                | And boolex boolex\n\ntext{*\\noindent\nThe two constants are represented by @{term\"Const True\"} and\n@{term\"Const False\"}. Variables are represented by terms of the form\n@{term\"Var n\"}, where @{term\"n\"} is a natural number (type @{typ\"nat\"}).\nFor example, the formula $P@0 \\land \\neg P@1$ is represented by the term\n@{term\"And (Var 0) (Neg(Var 1))\"}.\n\n\\subsubsection{The Value of a Boolean Expression}\n\nThe value of a boolean expression depends on the value of its variables.\nHence the function @{text\"value\"} takes an additional parameter, an\n\\emph{environment} of type @{typ\"nat => bool\"}, which maps variables to their\nvalues:\n*}\n\nprimrec \"value\" :: \"boolex \\<Rightarrow> (nat \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"value (Const b) env = b\" |\n\"value (Var x)   env = env x\" |\n\"value (Neg b)   env = (\\<not> value b env)\" |\n\"value (And b c) env = (value b env \\<and> value c env)\"\n\ntext{*\\noindent\n\\subsubsection{If-Expressions}\n\nAn alternative and often more efficient (because in a certain sense\ncanonical) representation are so-called \\emph{If-expressions} built up\nfrom constants (@{term\"CIF\"}), variables (@{term\"VIF\"}) and conditionals\n(@{term\"IF\"}):\n*}\n\ndatatype ifex = CIF bool | VIF nat | IF ifex ifex ifex\n\ntext{*\\noindent\nThe evaluation of If-expressions proceeds as for @{typ\"boolex\"}:\n*}\n\nprimrec valif :: \"ifex \\<Rightarrow> (nat \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"valif (CIF b)    env = b\" |\n\"valif (VIF x)    env = env x\" |\n\"valif (IF b t e) env = (if valif b env then valif t env\n                                        else valif e env)\"\n\ntext{*\n\\subsubsection{Converting Boolean and If-Expressions}\n\nThe type @{typ\"boolex\"} is close to the customary representation of logical\nformulae, whereas @{typ\"ifex\"} is designed for efficiency. It is easy to\ntranslate from @{typ\"boolex\"} into @{typ\"ifex\"}:\n*}\n\nprimrec bool2if :: \"boolex \\<Rightarrow> ifex\" where\n\"bool2if (Const b) = CIF b\" |\n\"bool2if (Var x)   = VIF x\" |\n\"bool2if (Neg b)   = IF (bool2if b) (CIF False) (CIF True)\" |\n\"bool2if (And b c) = IF (bool2if b) (bool2if c) (CIF False)\"\n\ntext{*\\noindent\nAt last, we have something we can verify: that @{term\"bool2if\"} preserves the\nvalue of its argument:\n*}\n\nlemma \"valif (bool2if b) env = value b env\"\n\ntxt{*\\noindent\nThe proof is canonical:\n*}\n\napply(induct_tac b)\napply(auto)\ndone\n\ntext{*\\noindent\nIn fact, all proofs in this case study look exactly like this. Hence we do\nnot show them below.\n\nMore interesting is the transformation of If-expressions into a normal form\nwhere the first argument of @{term\"IF\"} cannot be another @{term\"IF\"} but\nmust be a constant or variable. Such a normal form can be computed by\nrepeatedly replacing a subterm of the form @{term\"IF (IF b x y) z u\"} by\n@{term\"IF b (IF x z u) (IF y z u)\"}, which has the same value. The following\nprimitive recursive functions perform this task:\n*}\n\nprimrec normif :: \"ifex \\<Rightarrow> ifex \\<Rightarrow> ifex \\<Rightarrow> ifex\" where\n\"normif (CIF b)    t e = IF (CIF b) t e\" |\n\"normif (VIF x)    t e = IF (VIF x) t e\" |\n\"normif (IF b t e) u f = normif b (normif t u f) (normif e u f)\"\n\nprimrec norm :: \"ifex \\<Rightarrow> ifex\" where\n\"norm (CIF b)    = CIF b\" |\n\"norm (VIF x)    = VIF x\" |\n\"norm (IF b t e) = normif b (norm t) (norm e)\"\n\ntext{*\\noindent\nTheir interplay is tricky; we leave it to you to develop an\nintuitive understanding. Fortunately, Isabelle can help us to verify that the\ntransformation preserves the value of the expression:\n*}\n\ntheorem \"valif (norm b) env = valif b env\"(*<*)oops(*>*)\n\ntext{*\\noindent\nThe proof is canonical, provided we first show the following simplification\nlemma, which also helps to understand what @{term\"normif\"} does:\n*}\n\n\n\ntheorem \"valif (norm b) env = valif b env\"\napply(induct_tac b)\nby(auto)\n(*>*)\ntext{*\\noindent\nNote that the lemma does not have a name, but is implicitly used in the proof\nof the theorem shown above because of the @{text\"[simp]\"} attribute.\n\nBut how can we be sure that @{term\"norm\"} really produces a normal form in\nthe above sense? We define a function that tests If-expressions for normality:\n*}\n\nprimrec normal :: \"ifex \\<Rightarrow> bool\" where\n\"normal(CIF b) = True\" |\n\"normal(VIF x) = True\" |\n\"normal(IF b t e) = (normal t \\<and> normal e \\<and>\n     (case b of CIF b \\<Rightarrow> True | VIF x \\<Rightarrow> True | IF x y z \\<Rightarrow> False))\"\n\ntext{*\\noindent\nNow we prove @{term\"normal(norm b)\"}. Of course, this requires a lemma about\nnormality of @{term\"normif\"}:\n*}\n\nlemma [simp]: \"\\<forall>t e. normal(normif b t e) = (normal t \\<and> normal e)\"\n(*<*)\napply(induct_tac b)\nby(auto)\n\ntheorem \"normal(norm b)\"\napply(induct_tac b)\nby(auto)\n(*>*)\n\ntext{*\\medskip\nHow do we come up with the required lemmas? Try to prove the main theorems\nwithout them and study carefully what @{text auto} leaves unproved. This \ncan provide the clue.  The necessity of universal quantification\n(@{text\"\\<forall>t e\"}) in the two lemmas is explained in\n\\S\\ref{sec:InductionHeuristics}\n\n\\begin{exercise}\n  We strengthen the definition of a @{const normal} If-expression as follows:\n  the first argument of all @{term IF}s must be a variable. Adapt the above\n  development to this changed requirement. (Hint: you may need to formulate\n  some of the goals as implications (@{text\"\\<longrightarrow>\"}) rather than\n  equalities (@{text\"=\"}).)\n\\end{exercise}\n\\index{boolean expressions example|)}\n*}\n(*<*)\n\nprimrec normif2 :: \"ifex => ifex => ifex => ifex\" where\n\"normif2 (CIF b)    t e = (if b then t else e)\" |\n\"normif2 (VIF x)    t e = IF (VIF x) t e\" |\n\"normif2 (IF b t e) u f = normif2 b (normif2 t u f) (normif2 e u f)\"\n\nprimrec norm2 :: \"ifex => ifex\" where\n\"norm2 (CIF b)    = CIF b\" |\n\"norm2 (VIF x)    = VIF x\" |\n\"norm2 (IF b t e) = normif2 b (norm2 t) (norm2 e)\"\n\nprimrec normal2 :: \"ifex => bool\" where\n\"normal2(CIF b) = True\" |\n\"normal2(VIF x) = True\" |\n\"normal2(IF b t e) = (normal2 t & normal2 e &\n     (case b of CIF b => False | VIF x => True | IF x y z => False))\"\n\nlemma [simp]:\n  \"ALL t e. valif (normif2 b t e) env = valif (IF b t e) env\"\napply(induct b)\nby(auto)\n\ntheorem \"valif (norm2 b) env = valif b env\"\napply(induct b)\nby(auto)\n\nlemma [simp]: \"ALL t e. normal2 t & normal2 e --> normal2(normif2 b t e)\"\napply(induct b)\nby(auto)\n\ntheorem \"normal2(norm2 b)\"\napply(induct b)\nby(auto)\n\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/Ifexpr/Ifexpr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.797537522701839}}
{"text": "(*  Author:     L C Paulson, University of Cambridge [ported from HOL Light]\n*)\n\nsection \\<open>Operators involving abstract topology\\<close>\n\ntheory Abstract_Topology\n  imports\n    Complex_Main\n    \"HOL-Library.Set_Idioms\"\n    \"HOL-Library.FuncSet\"\nbegin\n\nsubsection \\<open>General notion of a topology as a value\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> istopology :: \"('a set \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"istopology L \\<equiv> (\\<forall>S T. L S \\<longrightarrow> L T \\<longrightarrow> L (S \\<inter> T)) \\<and> (\\<forall>\\<K>. (\\<forall>K\\<in>\\<K>. L K) \\<longrightarrow> L (\\<Union>\\<K>))\"\n\ntypedef\\<^marker>\\<open>tag important\\<close> 'a topology = \"{L::('a set) \\<Rightarrow> bool. istopology L}\"\n  morphisms \"openin\" \"topology\"\n  unfolding istopology_def by blast\n\nlemma istopology_openin[intro]: \"istopology(openin U)\"\n  using openin[of U] by blast\n\nlemma istopology_open: \"istopology open\"\n  by (auto simp: istopology_def)\n\nlemma topology_inverse': \"istopology U \\<Longrightarrow> openin (topology U) = U\"\n  using topology_inverse[unfolded mem_Collect_eq] .\n\nlemma topology_inverse_iff: \"istopology U \\<longleftrightarrow> openin (topology U) = U\"\n  using topology_inverse[of U] istopology_openin[of \"topology U\"] by auto\n\nlemma topology_eq: \"T1 = T2 \\<longleftrightarrow> (\\<forall>S. openin T1 S \\<longleftrightarrow> openin T2 S)\"\nproof\n  assume \"T1 = T2\"\n  then show \"\\<forall>S. openin T1 S \\<longleftrightarrow> openin T2 S\" by simp\nnext\n  assume H: \"\\<forall>S. openin T1 S \\<longleftrightarrow> openin T2 S\"\n  then have \"openin T1 = openin T2\" by (simp add: fun_eq_iff)\n  then have \"topology (openin T1) = topology (openin T2)\" by simp\n  then show \"T1 = T2\" unfolding openin_inverse .\nqed\n\n\ntext\\<open>The \"universe\": the union of all sets in the topology.\\<close>\ndefinition \"topspace T = \\<Union>{S. openin T S}\"\n\nsubsubsection \\<open>Main properties of open sets\\<close>\n\nproposition openin_clauses:\n  fixes U :: \"'a topology\"\n  shows\n    \"openin U {}\"\n    \"\\<And>S T. openin U S \\<Longrightarrow> openin U T \\<Longrightarrow> openin U (S\\<inter>T)\"\n    \"\\<And>K. (\\<forall>S \\<in> K. openin U S) \\<Longrightarrow> openin U (\\<Union>K)\"\n  using openin[of U] unfolding istopology_def by auto\n\nlemma openin_subset[intro]: \"openin U S \\<Longrightarrow> S \\<subseteq> topspace U\"\n  unfolding topspace_def by blast\n\nlemma openin_empty[simp]: \"openin U {}\"\n  by (rule openin_clauses)\n\nlemma openin_Int[intro]: \"openin U S \\<Longrightarrow> openin U T \\<Longrightarrow> openin U (S \\<inter> T)\"\n  by (rule openin_clauses)\n\nlemma openin_Union[intro]: \"(\\<And>S. S \\<in> K \\<Longrightarrow> openin U S) \\<Longrightarrow> openin U (\\<Union>K)\"\n  using openin_clauses by blast\n\nlemma openin_Un[intro]: \"openin U S \\<Longrightarrow> openin U T \\<Longrightarrow> openin U (S \\<union> T)\"\n  using openin_Union[of \"{S,T}\" U] by auto\n\nlemma openin_topspace[intro, simp]: \"openin U (topspace U)\"\n  by (force simp: openin_Union topspace_def)\n\nlemma openin_subopen: \"openin U S \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<exists>T. openin U T \\<and> x \\<in> T \\<and> T \\<subseteq> S)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs by auto\nnext\n  assume H: ?rhs\n  let ?t = \"\\<Union>{T. openin U T \\<and> T \\<subseteq> S}\"\n  have \"openin U ?t\" by (force simp: openin_Union)\n  also have \"?t = S\" using H by auto\n  finally show \"openin U S\" .\nqed\n\nlemma openin_INT [intro]:\n  assumes \"finite I\"\n          \"\\<And>i. i \\<in> I \\<Longrightarrow> openin T (U i)\"\n  shows \"openin T ((\\<Inter>i \\<in> I. U i) \\<inter> topspace T)\"\nusing assms by (induct, auto simp: inf_sup_aci(2) openin_Int)\n\nlemma openin_INT2 [intro]:\n  assumes \"finite I\" \"I \\<noteq> {}\"\n          \"\\<And>i. i \\<in> I \\<Longrightarrow> openin T (U i)\"\n  shows \"openin T (\\<Inter>i \\<in> I. U i)\"\nproof -\n  have \"(\\<Inter>i \\<in> I. U i) \\<subseteq> topspace T\"\n    using \\<open>I \\<noteq> {}\\<close> openin_subset[OF assms(3)] by auto\n  then show ?thesis\n    using openin_INT[of _ _ U, OF assms(1) assms(3)] by (simp add: inf.absorb2 inf_commute)\nqed\n\nlemma openin_Inter [intro]:\n  assumes \"finite \\<F>\" \"\\<F> \\<noteq> {}\" \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> openin T X\" shows \"openin T (\\<Inter>\\<F>)\"\n  by (metis (full_types) assms openin_INT2 image_ident)\n\nlemma openin_Int_Inter:\n  assumes \"finite \\<F>\" \"openin T U\" \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> openin T X\" shows \"openin T (U \\<inter> \\<Inter>\\<F>)\"\n  using openin_Inter [of \"insert U \\<F>\"] assms by auto\n\n\nsubsubsection \\<open>Closed sets\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> closedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"closedin U S \\<longleftrightarrow> S \\<subseteq> topspace U \\<and> openin U (topspace U - S)\"\n\nlemma closedin_subset: \"closedin U S \\<Longrightarrow> S \\<subseteq> topspace U\"\n  by (metis closedin_def)\n\nlemma closedin_empty[simp]: \"closedin U {}\"\n  by (simp add: closedin_def)\n\nlemma closedin_topspace[intro, simp]: \"closedin U (topspace U)\"\n  by (simp add: closedin_def)\n\nlemma closedin_Un[intro]: \"closedin U S \\<Longrightarrow> closedin U T \\<Longrightarrow> closedin U (S \\<union> T)\"\n  by (auto simp: Diff_Un closedin_def)\n\nlemma Diff_Inter[intro]: \"A - \\<Inter>S = \\<Union>{A - s|s. s\\<in>S}\"\n  by auto\n\nlemma closedin_Union:\n  assumes \"finite S\" \"\\<And>T. T \\<in> S \\<Longrightarrow> closedin U T\"\n    shows \"closedin U (\\<Union>S)\"\n  using assms by induction auto\n\nlemma closedin_Inter[intro]:\n  assumes Ke: \"K \\<noteq> {}\"\n    and Kc: \"\\<And>S. S \\<in>K \\<Longrightarrow> closedin U S\"\n  shows \"closedin U (\\<Inter>K)\"\n  using Ke Kc unfolding closedin_def Diff_Inter by auto\n\nlemma closedin_INT[intro]:\n  assumes \"A \\<noteq> {}\" \"\\<And>x. x \\<in> A \\<Longrightarrow> closedin U (B x)\"\n  shows \"closedin U (\\<Inter>x\\<in>A. B x)\"\n  apply (rule closedin_Inter)\n  using assms\n  apply auto\n  done\n\nlemma closedin_Int[intro]: \"closedin U S \\<Longrightarrow> closedin U T \\<Longrightarrow> closedin U (S \\<inter> T)\"\n  using closedin_Inter[of \"{S,T}\" U] by auto\n\nlemma openin_closedin_eq: \"openin U S \\<longleftrightarrow> S \\<subseteq> topspace U \\<and> closedin U (topspace U - S)\"\n  apply (auto simp: closedin_def Diff_Diff_Int inf_absorb2)\n  apply (metis openin_subset subset_eq)\n  done\n\nlemma topology_finer_closedin:\n  \"topspace X = topspace Y \\<Longrightarrow> (\\<forall>S. openin Y S \\<longrightarrow> openin X S) \\<longleftrightarrow> (\\<forall>S. closedin Y S \\<longrightarrow> closedin X S)\"\n  apply safe\n   apply (simp add: closedin_def)\n  by (simp add: openin_closedin_eq)\n\nlemma openin_closedin: \"S \\<subseteq> topspace U \\<Longrightarrow> (openin U S \\<longleftrightarrow> closedin U (topspace U - S))\"\n  by (simp add: openin_closedin_eq)\n\nlemma openin_diff[intro]:\n  assumes oS: \"openin U S\"\n    and cT: \"closedin U T\"\n  shows \"openin U (S - T)\"\nproof -\n  have \"S - T = S \\<inter> (topspace U - T)\" using openin_subset[of U S]  oS cT\n    by (auto simp: topspace_def openin_subset)\n  then show ?thesis using oS cT\n    by (auto simp: closedin_def)\nqed\n\nlemma closedin_diff[intro]:\n  assumes oS: \"closedin U S\"\n    and cT: \"openin U T\"\n  shows \"closedin U (S - T)\"\nproof -\n  have \"S - T = S \\<inter> (topspace U - T)\"\n    using closedin_subset[of U S] oS cT by (auto simp: topspace_def)\n  then show ?thesis\n    using oS cT by (auto simp: openin_closedin_eq)\nqed\n\n\nsubsection\\<open>The discrete topology\\<close>\n\ndefinition discrete_topology where \"discrete_topology U \\<equiv> topology (\\<lambda>S. S \\<subseteq> U)\"\n\nlemma openin_discrete_topology [simp]: \"openin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U\"\nproof -\n  have \"istopology (\\<lambda>S. S \\<subseteq> U)\"\n    by (auto simp: istopology_def)\n  then show ?thesis\n    by (simp add: discrete_topology_def topology_inverse')\nqed\n\nlemma topspace_discrete_topology [simp]: \"topspace(discrete_topology U) = U\"\n  by (meson openin_discrete_topology openin_subset openin_topspace order_refl subset_antisym)\n\nlemma closedin_discrete_topology [simp]: \"closedin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U\"\n  by (simp add: closedin_def)\n\nlemma discrete_topology_unique:\n   \"discrete_topology U = X \\<longleftrightarrow> topspace X = U \\<and> (\\<forall>x \\<in> U. openin X {x})\" (is \"?lhs = ?rhs\")\nproof\n  assume R: ?rhs\n  then have \"openin X S\" if \"S \\<subseteq> U\" for S\n    using openin_subopen subsetD that by fastforce\n  moreover have \"x \\<in> topspace X\" if \"openin X S\" and \"x \\<in> S\" for x S\n    using openin_subset that by blast\n  ultimately\n  show ?lhs\n    using R by (auto simp: topology_eq)\nqed auto\n\nlemma discrete_topology_unique_alt:\n  \"discrete_topology U = X \\<longleftrightarrow> topspace X \\<subseteq> U \\<and> (\\<forall>x \\<in> U. openin X {x})\"\n  using openin_subset\n  by (auto simp: discrete_topology_unique)\n\nlemma subtopology_eq_discrete_topology_empty:\n   \"X = discrete_topology {} \\<longleftrightarrow> topspace X = {}\"\n  using discrete_topology_unique [of \"{}\" X] by auto\n\nlemma subtopology_eq_discrete_topology_sing:\n   \"X = discrete_topology {a} \\<longleftrightarrow> topspace X = {a}\"\n  by (metis discrete_topology_unique openin_topspace singletonD)\n\n\nsubsection \\<open>Subspace topology\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> subtopology :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a topology\" where\n\"subtopology U V = topology (\\<lambda>T. \\<exists>S. T = S \\<inter> V \\<and> openin U S)\"\n\nlemma istopology_subtopology: \"istopology (\\<lambda>T. \\<exists>S. T = S \\<inter> V \\<and> openin U S)\"\n  (is \"istopology ?L\")\nproof -\n  have \"?L {}\" by blast\n  {\n    fix A B\n    assume A: \"?L A\" and B: \"?L B\"\n    from A B obtain Sa and Sb where Sa: \"openin U Sa\" \"A = Sa \\<inter> V\" and Sb: \"openin U Sb\" \"B = Sb \\<inter> V\"\n      by blast\n    have \"A \\<inter> B = (Sa \\<inter> Sb) \\<inter> V\" \"openin U (Sa \\<inter> Sb)\"\n      using Sa Sb by blast+\n    then have \"?L (A \\<inter> B)\" by blast\n  }\n  moreover\n  {\n    fix K\n    assume K: \"K \\<subseteq> Collect ?L\"\n    have th0: \"Collect ?L = (\\<lambda>S. S \\<inter> V) ` Collect (openin U)\"\n      by blast\n    from K[unfolded th0 subset_image_iff]\n    obtain Sk where Sk: \"Sk \\<subseteq> Collect (openin U)\" \"K = (\\<lambda>S. S \\<inter> V) ` Sk\"\n      by blast\n    have \"\\<Union>K = (\\<Union>Sk) \\<inter> V\"\n      using Sk by auto\n    moreover have \"openin U (\\<Union>Sk)\"\n      using Sk by (auto simp: subset_eq)\n    ultimately have \"?L (\\<Union>K)\" by blast\n  }\n  ultimately show ?thesis\n    unfolding subset_eq mem_Collect_eq istopology_def by auto\nqed\n\nlemma openin_subtopology: \"openin (subtopology U V) S \\<longleftrightarrow> (\\<exists>T. openin U T \\<and> S = T \\<inter> V)\"\n  unfolding subtopology_def topology_inverse'[OF istopology_subtopology]\n  by auto\n\nlemma openin_subtopology_Int:\n   \"openin X S \\<Longrightarrow> openin (subtopology X T) (S \\<inter> T)\"\n  using openin_subtopology by auto\n\nlemma openin_subtopology_Int2:\n   \"openin X T \\<Longrightarrow> openin (subtopology X S) (S \\<inter> T)\"\n  using openin_subtopology by auto\n\nlemma openin_subtopology_diff_closed:\n   \"\\<lbrakk>S \\<subseteq> topspace X; closedin X T\\<rbrakk> \\<Longrightarrow> openin (subtopology X S) (S - T)\"\n  unfolding closedin_def openin_subtopology\n  by (rule_tac x=\"topspace X - T\" in exI) auto\n\nlemma openin_relative_to: \"(openin X relative_to S) = openin (subtopology X S)\"\n  by (force simp: relative_to_def openin_subtopology)\n\nlemma topspace_subtopology [simp]: \"topspace (subtopology U V) = topspace U \\<inter> V\"\n  by (auto simp: topspace_def openin_subtopology)\n\nlemma topspace_subtopology_subset:\n   \"S \\<subseteq> topspace X \\<Longrightarrow> topspace(subtopology X S) = S\"\n  by (simp add: inf.absorb_iff2)\n\nlemma closedin_subtopology: \"closedin (subtopology U V) S \\<longleftrightarrow> (\\<exists>T. closedin U T \\<and> S = T \\<inter> V)\"\n  unfolding closedin_def topspace_subtopology\n  by (auto simp: openin_subtopology)\n\nlemma openin_subtopology_refl: \"openin (subtopology U V) V \\<longleftrightarrow> V \\<subseteq> topspace U\"\n  unfolding openin_subtopology\n  by auto (metis IntD1 in_mono openin_subset)\n\nlemma subtopology_subtopology:\n   \"subtopology (subtopology X S) T = subtopology X (S \\<inter> T)\"\nproof -\n  have eq: \"\\<And>T'. (\\<exists>S'. T' = S' \\<inter> T \\<and> (\\<exists>T. openin X T \\<and> S' = T \\<inter> S)) = (\\<exists>Sa. T' = Sa \\<inter> (S \\<inter> T) \\<and> openin X Sa)\"\n    by (metis inf_assoc)\n  have \"subtopology (subtopology X S) T = topology (\\<lambda>Ta. \\<exists>Sa. Ta = Sa \\<inter> T \\<and> openin (subtopology X S) Sa)\"\n    by (simp add: subtopology_def)\n  also have \"\\<dots> = subtopology X (S \\<inter> T)\"\n    by (simp add: openin_subtopology eq) (simp add: subtopology_def)\n  finally show ?thesis .\nqed\n\nlemma openin_subtopology_alt:\n     \"openin (subtopology X U) S \\<longleftrightarrow> S \\<in> (\\<lambda>T. U \\<inter> T) ` Collect (openin X)\"\n  by (simp add: image_iff inf_commute openin_subtopology)\n\nlemma closedin_subtopology_alt:\n     \"closedin (subtopology X U) S \\<longleftrightarrow> S \\<in> (\\<lambda>T. U \\<inter> T) ` Collect (closedin X)\"\n  by (simp add: image_iff inf_commute closedin_subtopology)\n\nlemma subtopology_superset:\n  assumes UV: \"topspace U \\<subseteq> V\"\n  shows \"subtopology U V = U\"\nproof -\n  {\n    fix S\n    {\n      fix T\n      assume T: \"openin U T\" \"S = T \\<inter> V\"\n      from T openin_subset[OF T(1)] UV have eq: \"S = T\"\n        by blast\n      have \"openin U S\"\n        unfolding eq using T by blast\n    }\n    moreover\n    {\n      assume S: \"openin U S\"\n      then have \"\\<exists>T. openin U T \\<and> S = T \\<inter> V\"\n        using openin_subset[OF S] UV by auto\n    }\n    ultimately have \"(\\<exists>T. openin U T \\<and> S = T \\<inter> V) \\<longleftrightarrow> openin U S\"\n      by blast\n  }\n  then show ?thesis\n    unfolding topology_eq openin_subtopology by blast\nqed\n\nlemma subtopology_topspace[simp]: \"subtopology U (topspace U) = U\"\n  by (simp add: subtopology_superset)\n\nlemma subtopology_UNIV[simp]: \"subtopology U UNIV = U\"\n  by (simp add: subtopology_superset)\n\nlemma subtopology_restrict:\n   \"subtopology X (topspace X \\<inter> S) = subtopology X S\"\n  by (metis subtopology_subtopology subtopology_topspace)\n\nlemma openin_subtopology_empty:\n   \"openin (subtopology U {}) S \\<longleftrightarrow> S = {}\"\nby (metis Int_empty_right openin_empty openin_subtopology)\n\nlemma closedin_subtopology_empty:\n   \"closedin (subtopology U {}) S \\<longleftrightarrow> S = {}\"\nby (metis Int_empty_right closedin_empty closedin_subtopology)\n\nlemma closedin_subtopology_refl [simp]:\n   \"closedin (subtopology U X) X \\<longleftrightarrow> X \\<subseteq> topspace U\"\nby (metis closedin_def closedin_topspace inf.absorb_iff2 le_inf_iff topspace_subtopology)\n\nlemma closedin_topspace_empty: \"topspace T = {} \\<Longrightarrow> (closedin T S \\<longleftrightarrow> S = {})\"\n  by (simp add: closedin_def)\n\nlemma open_in_topspace_empty:\n   \"topspace X = {} \\<Longrightarrow> openin X S \\<longleftrightarrow> S = {}\"\n  by (simp add: openin_closedin_eq)\n\nlemma openin_imp_subset:\n   \"openin (subtopology U S) T \\<Longrightarrow> T \\<subseteq> S\"\nby (metis Int_iff openin_subtopology subsetI)\n\nlemma closedin_imp_subset:\n   \"closedin (subtopology U S) T \\<Longrightarrow> T \\<subseteq> S\"\nby (simp add: closedin_def)\n\nlemma openin_open_subtopology:\n     \"openin X S \\<Longrightarrow> openin (subtopology X S) T \\<longleftrightarrow> openin X T \\<and> T \\<subseteq> S\"\n  by (metis inf.orderE openin_Int openin_imp_subset openin_subtopology)\n\nlemma closedin_closed_subtopology:\n     \"closedin X S \\<Longrightarrow> (closedin (subtopology X S) T \\<longleftrightarrow> closedin X T \\<and> T \\<subseteq> S)\"\n  by (metis closedin_Int closedin_imp_subset closedin_subtopology inf.orderE)\n\nlemma openin_subtopology_Un:\n    \"\\<lbrakk>openin (subtopology X T) S; openin (subtopology X U) S\\<rbrakk>\n     \\<Longrightarrow> openin (subtopology X (T \\<union> U)) S\"\nby (simp add: openin_subtopology) blast\n\nlemma closedin_subtopology_Un:\n    \"\\<lbrakk>closedin (subtopology X T) S; closedin (subtopology X U) S\\<rbrakk>\n     \\<Longrightarrow> closedin (subtopology X (T \\<union> U)) S\"\nby (simp add: closedin_subtopology) blast\n\nlemma openin_trans_full:\n   \"\\<lbrakk>openin (subtopology X U) S; openin X U\\<rbrakk> \\<Longrightarrow> openin X S\"\n  by (simp add: openin_open_subtopology)\n\n\nsubsection \\<open>The canonical topology from the underlying type class\\<close>\n\nabbreviation\\<^marker>\\<open>tag important\\<close> euclidean :: \"'a::topological_space topology\"\n  where \"euclidean \\<equiv> topology open\"\n\nabbreviation top_of_set :: \"'a::topological_space set \\<Rightarrow> 'a topology\"\n  where \"top_of_set \\<equiv> subtopology (topology open)\"\n\nlemma open_openin: \"open S \\<longleftrightarrow> openin euclidean S\"\n  apply (rule cong[where x=S and y=S])\n  apply (rule topology_inverse[symmetric])\n  apply (auto simp: istopology_def)\n  done\n\ndeclare open_openin [symmetric, simp]\n\nlemma topspace_euclidean [simp]: \"topspace euclidean = UNIV\"\n  by (force simp: topspace_def)\n\nlemma topspace_euclidean_subtopology[simp]: \"topspace (top_of_set S) = S\"\n  by (simp)\n\nlemma closed_closedin: \"closed S \\<longleftrightarrow> closedin euclidean S\"\n  by (simp add: closed_def closedin_def Compl_eq_Diff_UNIV)\n\ndeclare closed_closedin [symmetric, simp]\n\nlemma openin_subtopology_self [simp]: \"openin (top_of_set S) S\"\n  by (metis openin_topspace topspace_euclidean_subtopology)\n\nsubsubsection\\<open>The most basic facts about the usual topology and metric on R\\<close>\n\nabbreviation euclideanreal :: \"real topology\"\n  where \"euclideanreal \\<equiv> topology open\"\n\nsubsection \\<open>Basic \"localization\" results are handy for connectedness.\\<close>\n\nlemma openin_open: \"openin (top_of_set U) S \\<longleftrightarrow> (\\<exists>T. open T \\<and> (S = U \\<inter> T))\"\n  by (auto simp: openin_subtopology)\n\nlemma openin_Int_open:\n   \"\\<lbrakk>openin (top_of_set U) S; open T\\<rbrakk>\n        \\<Longrightarrow> openin (top_of_set U) (S \\<inter> T)\"\nby (metis open_Int Int_assoc openin_open)\n\nlemma openin_open_Int[intro]: \"open S \\<Longrightarrow> openin (top_of_set U) (U \\<inter> S)\"\n  by (auto simp: openin_open)\n\nlemma open_openin_trans[trans]:\n  \"open S \\<Longrightarrow> open T \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> openin (top_of_set S) T\"\n  by (metis Int_absorb1  openin_open_Int)\n\nlemma open_subset: \"S \\<subseteq> T \\<Longrightarrow> open S \\<Longrightarrow> openin (top_of_set T) S\"\n  by (auto simp: openin_open)\n\nlemma closedin_closed: \"closedin (top_of_set U) S \\<longleftrightarrow> (\\<exists>T. closed T \\<and> S = U \\<inter> T)\"\n  by (simp add: closedin_subtopology Int_ac)\n\nlemma closedin_closed_Int: \"closed S \\<Longrightarrow> closedin (top_of_set U) (U \\<inter> S)\"\n  by (metis closedin_closed)\n\nlemma closed_subset: \"S \\<subseteq> T \\<Longrightarrow> closed S \\<Longrightarrow> closedin (top_of_set T) S\"\n  by (auto simp: closedin_closed)\n\nlemma closedin_closed_subset:\n \"\\<lbrakk>closedin (top_of_set U) V; T \\<subseteq> U; S = V \\<inter> T\\<rbrakk>\n             \\<Longrightarrow> closedin (top_of_set T) S\"\n  by (metis (no_types, lifting) Int_assoc Int_commute closedin_closed inf.orderE)\n\nlemma finite_imp_closedin:\n  fixes S :: \"'a::t1_space set\"\n  shows \"\\<lbrakk>finite S; S \\<subseteq> T\\<rbrakk> \\<Longrightarrow> closedin (top_of_set T) S\"\n    by (simp add: finite_imp_closed closed_subset)\n\nlemma closedin_singleton [simp]:\n  fixes a :: \"'a::t1_space\"\n  shows \"closedin (top_of_set U) {a} \\<longleftrightarrow> a \\<in> U\"\nusing closedin_subset  by (force intro: closed_subset)\n\nlemma openin_euclidean_subtopology_iff:\n  fixes S U :: \"'a::metric_space set\"\n  shows \"openin (top_of_set U) S \\<longleftrightarrow>\n    S \\<subseteq> U \\<and> (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>x'\\<in>U. dist x' x < e \\<longrightarrow> x'\\<in> S)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding openin_open open_dist by blast\nnext\n  define T where \"T = {x. \\<exists>a\\<in>S. \\<exists>d>0. (\\<forall>y\\<in>U. dist y a < d \\<longrightarrow> y \\<in> S) \\<and> dist x a < d}\"\n  have 1: \"\\<forall>x\\<in>T. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> T\"\n    unfolding T_def\n    apply clarsimp\n    apply (rule_tac x=\"d - dist x a\" in exI)\n    apply (clarsimp simp add: less_diff_eq)\n    by (metis dist_commute dist_triangle_lt)\n  assume ?rhs then have 2: \"S = U \\<inter> T\"\n    unfolding T_def\n    by auto (metis dist_self)\n  from 1 2 show ?lhs\n    unfolding openin_open open_dist by fast\nqed\n\nlemma connected_openin:\n      \"connected S \\<longleftrightarrow>\n       \\<not>(\\<exists>E1 E2. openin (top_of_set S) E1 \\<and>\n                 openin (top_of_set S) E2 \\<and>\n                 S \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  unfolding connected_def openin_open disjoint_iff_not_equal by blast\n\nlemma connected_openin_eq:\n      \"connected S \\<longleftrightarrow>\n       \\<not>(\\<exists>E1 E2. openin (top_of_set S) E1 \\<and>\n                 openin (top_of_set S) E2 \\<and>\n                 E1 \\<union> E2 = S \\<and> E1 \\<inter> E2 = {} \\<and>\n                 E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  apply (simp add: connected_openin, safe, blast)\n  by (metis Int_lower1 Un_subset_iff openin_open subset_antisym)\n\nlemma connected_closedin:\n      \"connected S \\<longleftrightarrow>\n       (\\<nexists>E1 E2.\n        closedin (top_of_set S) E1 \\<and>\n        closedin (top_of_set S) E2 \\<and>\n        S \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n       (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs \n    by (auto simp add: connected_closed closedin_closed)\nnext\n  assume R: ?rhs\n  then show ?lhs \n  proof (clarsimp simp add: connected_closed closedin_closed)\n    fix A B \n    assume s_sub: \"S \\<subseteq> A \\<union> B\" \"B \\<inter> S \\<noteq> {}\"\n      and disj: \"A \\<inter> B \\<inter> S = {}\"\n      and cl: \"closed A\" \"closed B\"\n    have \"S \\<inter> (A \\<union> B) = S\"\n      using s_sub(1) by auto\n    have \"S - A = B \\<inter> S\"\n      using Diff_subset_conv Un_Diff_Int disj s_sub(1) by auto\n    then have \"S \\<inter> A = {}\"\n      by (metis Diff_Diff_Int Diff_disjoint Un_Diff_Int R cl closedin_closed_Int inf_commute order_refl s_sub(2))\n    then show \"A \\<inter> S = {}\"\n      by blast\n  qed\nqed\n\nlemma connected_closedin_eq:\n      \"connected S \\<longleftrightarrow>\n           \\<not>(\\<exists>E1 E2.\n                 closedin (top_of_set S) E1 \\<and>\n                 closedin (top_of_set S) E2 \\<and>\n                 E1 \\<union> E2 = S \\<and> E1 \\<inter> E2 = {} \\<and>\n                 E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  apply (simp add: connected_closedin, safe, blast)\n  by (metis Int_lower1 Un_subset_iff closedin_closed subset_antisym)\n\ntext \\<open>These \"transitivity\" results are handy too\\<close>\n\nlemma openin_trans[trans]:\n  \"openin (top_of_set T) S \\<Longrightarrow> openin (top_of_set U) T \\<Longrightarrow>\n    openin (top_of_set U) S\"\n  by (metis openin_Int_open openin_open)\n\nlemma openin_open_trans: \"openin (top_of_set T) S \\<Longrightarrow> open T \\<Longrightarrow> open S\"\n  by (auto simp: openin_open intro: openin_trans)\n\nlemma closedin_trans[trans]:\n  \"closedin (top_of_set T) S \\<Longrightarrow> closedin (top_of_set U) T \\<Longrightarrow>\n    closedin (top_of_set U) S\"\n  by (auto simp: closedin_closed closed_Inter Int_assoc)\n\nlemma closedin_closed_trans: \"closedin (top_of_set T) S \\<Longrightarrow> closed T \\<Longrightarrow> closed S\"\n  by (auto simp: closedin_closed intro: closedin_trans)\n\nlemma openin_subtopology_Int_subset:\n   \"\\<lbrakk>openin (top_of_set u) (u \\<inter> S); v \\<subseteq> u\\<rbrakk> \\<Longrightarrow> openin (top_of_set v) (v \\<inter> S)\"\n  by (auto simp: openin_subtopology)\n\nlemma openin_open_eq: \"open s \\<Longrightarrow> (openin (top_of_set s) t \\<longleftrightarrow> open t \\<and> t \\<subseteq> s)\"\n  using open_subset openin_open_trans openin_subset by fastforce\n\n\nsubsection\\<open>Derived set (set of limit points)\\<close>\n\ndefinition derived_set_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixl \"derived'_set'_of\" 80)\n  where \"X derived_set_of S \\<equiv>\n         {x \\<in> topspace X.\n                (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y\\<noteq>x. y \\<in> S \\<and> y \\<in> T))}\"\n\nlemma derived_set_of_restrict [simp]:\n   \"X derived_set_of (topspace X \\<inter> S) = X derived_set_of S\"\n  by (simp add: derived_set_of_def) (metis openin_subset subset_iff)\n\nlemma in_derived_set_of:\n   \"x \\<in> X derived_set_of S \\<longleftrightarrow> x \\<in> topspace X \\<and> (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y\\<noteq>x. y \\<in> S \\<and> y \\<in> T))\"\n  by (simp add: derived_set_of_def)\n\nlemma derived_set_of_subset_topspace:\n   \"X derived_set_of S \\<subseteq> topspace X\"\n  by (auto simp add: derived_set_of_def)\n\nlemma derived_set_of_subtopology:\n   \"(subtopology X U) derived_set_of S = U \\<inter> (X derived_set_of (U \\<inter> S))\"\n  by (simp add: derived_set_of_def openin_subtopology) blast\n\nlemma derived_set_of_subset_subtopology:\n   \"(subtopology X S) derived_set_of T \\<subseteq> S\"\n  by (simp add: derived_set_of_subtopology)\n\nlemma derived_set_of_empty [simp]: \"X derived_set_of {} = {}\"\n  by (auto simp: derived_set_of_def)\n\nlemma derived_set_of_mono:\n   \"S \\<subseteq> T \\<Longrightarrow> X derived_set_of S \\<subseteq> X derived_set_of T\"\n  unfolding derived_set_of_def by blast\n\nlemma derived_set_of_Un:\n   \"X derived_set_of (S \\<union> T) = X derived_set_of S \\<union> X derived_set_of T\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    apply (clarsimp simp: in_derived_set_of)\n    by (metis IntE IntI openin_Int)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (simp add: derived_set_of_mono)\nqed\n\nlemma derived_set_of_Union:\n   \"finite \\<F> \\<Longrightarrow> X derived_set_of (\\<Union>\\<F>) = (\\<Union>S \\<in> \\<F>. X derived_set_of S)\"\nproof (induction \\<F> rule: finite_induct)\n  case (insert S \\<F>)\n  then show ?case\n    by (simp add: derived_set_of_Un)\nqed auto\n\nlemma derived_set_of_topspace:\n  \"X derived_set_of (topspace X) = {x \\<in> topspace X. \\<not> openin X {x}}\"\n  apply (auto simp: in_derived_set_of)\n  by (metis Set.set_insert all_not_in_conv insertCI openin_subset subsetCE)\n\nlemma discrete_topology_unique_derived_set:\n     \"discrete_topology U = X \\<longleftrightarrow> topspace X = U \\<and> X derived_set_of U = {}\"\n  by (auto simp: discrete_topology_unique derived_set_of_topspace)\n\nlemma subtopology_eq_discrete_topology_eq:\n   \"subtopology X U = discrete_topology U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> U \\<inter> X derived_set_of U = {}\"\n  using discrete_topology_unique_derived_set [of U \"subtopology X U\"]\n  by (auto simp: eq_commute derived_set_of_subtopology)\n\nlemma subtopology_eq_discrete_topology:\n   \"S \\<subseteq> topspace X \\<and> S \\<inter> X derived_set_of S = {}\n        \\<Longrightarrow> subtopology X S = discrete_topology S\"\n  by (simp add: subtopology_eq_discrete_topology_eq)\n\nlemma subtopology_eq_discrete_topology_gen:\n   \"S \\<inter> X derived_set_of S = {} \\<Longrightarrow> subtopology X S = discrete_topology(topspace X \\<inter> S)\"\n  by (metis Int_lower1 derived_set_of_restrict inf_assoc inf_bot_right subtopology_eq_discrete_topology_eq subtopology_subtopology subtopology_topspace)\n\nlemma subtopology_discrete_topology [simp]: \"subtopology (discrete_topology U) S = discrete_topology(U \\<inter> S)\"\nproof -\n  have \"(\\<lambda>T. \\<exists>Sa. T = Sa \\<inter> S \\<and> Sa \\<subseteq> U) = (\\<lambda>Sa. Sa \\<subseteq> U \\<and> Sa \\<subseteq> S)\"\n    by force\n  then show ?thesis\n    by (simp add: subtopology_def) (simp add: discrete_topology_def)\nqed\nlemma openin_Int_derived_set_of_subset:\n   \"openin X S \\<Longrightarrow> S \\<inter> X derived_set_of T \\<subseteq> X derived_set_of (S \\<inter> T)\"\n  by (auto simp: derived_set_of_def)\n\nlemma openin_Int_derived_set_of_eq:\n  \"openin X S \\<Longrightarrow> S \\<inter> X derived_set_of T = S \\<inter> X derived_set_of (S \\<inter> T)\"\n  apply auto\n   apply (meson IntI openin_Int_derived_set_of_subset subsetCE)\n  by (meson derived_set_of_mono inf_sup_ord(2) subset_eq)\n\n\nsubsection\\<open> Closure with respect to a topological space\\<close>\n\ndefinition closure_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixr \"closure'_of\" 80)\n  where \"X closure_of S \\<equiv> {x \\<in> topspace X. \\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y \\<in> S. y \\<in> T)}\"\n\nlemma closure_of_restrict: \"X closure_of S = X closure_of (topspace X \\<inter> S)\"\n  unfolding closure_of_def\n  apply safe\n  apply (meson IntI openin_subset subset_iff)\n  by auto\n\nlemma in_closure_of:\n   \"x \\<in> X closure_of S \\<longleftrightarrow>\n    x \\<in> topspace X \\<and> (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y. y \\<in> S \\<and> y \\<in> T))\"\n  by (auto simp: closure_of_def)\n\nlemma closure_of: \"X closure_of S = topspace X \\<inter> (S \\<union> X derived_set_of S)\"\n  by (fastforce simp: in_closure_of in_derived_set_of)\n\nlemma closure_of_alt: \"X closure_of S = topspace X \\<inter> S \\<union> X derived_set_of S\"\n  using derived_set_of_subset_topspace [of X S]\n  unfolding closure_of_def in_derived_set_of\n  by safe (auto simp: in_derived_set_of)\n\nlemma derived_set_of_subset_closure_of:\n   \"X derived_set_of S \\<subseteq> X closure_of S\"\n  by (fastforce simp: closure_of_def in_derived_set_of)\n\nlemma closure_of_subtopology:\n  \"(subtopology X U) closure_of S = U \\<inter> (X closure_of (U \\<inter> S))\"\n  unfolding closure_of_def topspace_subtopology openin_subtopology\n  by safe (metis (full_types) IntI Int_iff inf.commute)+\n\nlemma closure_of_empty [simp]: \"X closure_of {} = {}\"\n  by (simp add: closure_of_alt)\n\nlemma closure_of_topspace [simp]: \"X closure_of topspace X = topspace X\"\n  by (simp add: closure_of)\n\nlemma closure_of_UNIV [simp]: \"X closure_of UNIV = topspace X\"\n  by (simp add: closure_of)\n\nlemma closure_of_subset_topspace: \"X closure_of S \\<subseteq> topspace X\"\n  by (simp add: closure_of)\n\nlemma closure_of_subset_subtopology: \"(subtopology X S) closure_of T \\<subseteq> S\"\n  by (simp add: closure_of_subtopology)\n\nlemma closure_of_mono: \"S \\<subseteq> T \\<Longrightarrow> X closure_of S \\<subseteq> X closure_of T\"\n  by (fastforce simp add: closure_of_def)\n\nlemma closure_of_subtopology_subset:\n   \"(subtopology X U) closure_of S \\<subseteq> (X closure_of S)\"\n  unfolding closure_of_subtopology\n  by clarsimp (meson closure_of_mono contra_subsetD inf.cobounded2)\n\nlemma closure_of_subtopology_mono:\n   \"T \\<subseteq> U \\<Longrightarrow> (subtopology X T) closure_of S \\<subseteq> (subtopology X U) closure_of S\"\n  unfolding closure_of_subtopology\n  by auto (meson closure_of_mono inf_mono subset_iff)\n\nlemma closure_of_Un [simp]: \"X closure_of (S \\<union> T) = X closure_of S \\<union> X closure_of T\"\n  by (simp add: Un_assoc Un_left_commute closure_of_alt derived_set_of_Un inf_sup_distrib1)\n\nlemma closure_of_Union:\n   \"finite \\<F> \\<Longrightarrow> X closure_of (\\<Union>\\<F>) = (\\<Union>S \\<in> \\<F>. X closure_of S)\"\nby (induction \\<F> rule: finite_induct) auto\n\nlemma closure_of_subset: \"S \\<subseteq> topspace X \\<Longrightarrow> S \\<subseteq> X closure_of S\"\n  by (auto simp: closure_of_def)\n\nlemma closure_of_subset_Int: \"topspace X \\<inter> S \\<subseteq> X closure_of S\"\n  by (auto simp: closure_of_def)\n\nlemma closure_of_subset_eq: \"S \\<subseteq> topspace X \\<and> X closure_of S \\<subseteq> S \\<longleftrightarrow> closedin X S\"\nproof (cases \"S \\<subseteq> topspace X\")\n  case True\n  then have \"\\<forall>x. x \\<in> topspace X \\<and> (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y\\<in>S. y \\<in> T)) \\<longrightarrow> x \\<in> S\n             \\<Longrightarrow> openin X (topspace X - S)\"\n    apply (subst openin_subopen, safe)\n    by (metis DiffI subset_eq openin_subset [of X])\n  then show ?thesis\n    by (auto simp: closedin_def closure_of_def)\nnext\n  case False\n  then show ?thesis\n    by (simp add: closedin_def)\nqed\n\nlemma closure_of_eq: \"X closure_of S = S \\<longleftrightarrow> closedin X S\"\nproof (cases \"S \\<subseteq> topspace X\")\n  case True\n  then show ?thesis\n    by (metis closure_of_subset closure_of_subset_eq set_eq_subset)\nnext\n  case False\n  then show ?thesis\n    using closure_of closure_of_subset_eq by fastforce\nqed\n\nlemma closedin_contains_derived_set:\n   \"closedin X S \\<longleftrightarrow> X derived_set_of S \\<subseteq> S \\<and> S \\<subseteq> topspace X\"\nproof (intro iffI conjI)\n  show \"closedin X S \\<Longrightarrow> X derived_set_of S \\<subseteq> S\"\n    using closure_of_eq derived_set_of_subset_closure_of by fastforce\n  show \"closedin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n    using closedin_subset by blast\n  show \"X derived_set_of S \\<subseteq> S \\<and> S \\<subseteq> topspace X \\<Longrightarrow> closedin X S\"\n    by (metis closure_of closure_of_eq inf.absorb_iff2 sup.orderE)\nqed\n\nlemma derived_set_subset_gen:\n   \"X derived_set_of S \\<subseteq> S \\<longleftrightarrow> closedin X (topspace X \\<inter> S)\"\n  by (simp add: closedin_contains_derived_set derived_set_of_restrict derived_set_of_subset_topspace)\n\nlemma derived_set_subset: \"S \\<subseteq> topspace X \\<Longrightarrow> (X derived_set_of S \\<subseteq> S \\<longleftrightarrow> closedin X S)\"\n  by (simp add: closedin_contains_derived_set)\n\nlemma closedin_derived_set:\n     \"closedin (subtopology X T) S \\<longleftrightarrow>\n      S \\<subseteq> topspace X \\<and> S \\<subseteq> T \\<and> (\\<forall>x. x \\<in> X derived_set_of S \\<and> x \\<in> T \\<longrightarrow> x \\<in> S)\"\n  by (auto simp: closedin_contains_derived_set derived_set_of_subtopology Int_absorb1)\n\nlemma closedin_Int_closure_of:\n     \"closedin (subtopology X S) T \\<longleftrightarrow> S \\<inter> X closure_of T = T\"\n  by (metis Int_left_absorb closure_of_eq closure_of_subtopology)\n\nlemma closure_of_closedin: \"closedin X S \\<Longrightarrow> X closure_of S = S\"\n  by (simp add: closure_of_eq)\n\nlemma closure_of_eq_diff: \"X closure_of S = topspace X - \\<Union>{T. openin X T \\<and> disjnt S T}\"\n  by (auto simp: closure_of_def disjnt_iff)\n\nlemma closedin_closure_of [simp]: \"closedin X (X closure_of S)\"\n  unfolding closure_of_eq_diff by blast\n\nlemma closure_of_closure_of [simp]: \"X closure_of (X closure_of S) = X closure_of S\"\n  by (simp add: closure_of_eq)\n\nlemma closure_of_hull:\n  assumes \"S \\<subseteq> topspace X\" shows \"X closure_of S = (closedin X) hull S\"\nproof (rule hull_unique [THEN sym])\n  show \"S \\<subseteq> X closure_of S\"\n    by (simp add: closure_of_subset assms)\nnext\n  show \"closedin X (X closure_of S)\"\n    by simp\n  show \"\\<And>T. \\<lbrakk>S \\<subseteq> T; closedin X T\\<rbrakk> \\<Longrightarrow> X closure_of S \\<subseteq> T\"\n    by (metis closure_of_eq closure_of_mono)\nqed\n\nlemma closure_of_minimal:\n   \"\\<lbrakk>S \\<subseteq> T; closedin X T\\<rbrakk> \\<Longrightarrow> (X closure_of S) \\<subseteq> T\"\n  by (metis closure_of_eq closure_of_mono)\n\nlemma closure_of_minimal_eq:\n   \"\\<lbrakk>S \\<subseteq> topspace X; closedin X T\\<rbrakk> \\<Longrightarrow> (X closure_of S) \\<subseteq> T \\<longleftrightarrow> S \\<subseteq> T\"\n  by (meson closure_of_minimal closure_of_subset subset_trans)\n\nlemma closure_of_unique:\n   \"\\<lbrakk>S \\<subseteq> T; closedin X T;\n     \\<And>T'. \\<lbrakk>S \\<subseteq> T'; closedin X T'\\<rbrakk> \\<Longrightarrow> T \\<subseteq> T'\\<rbrakk>\n    \\<Longrightarrow> X closure_of S = T\"\n  by (meson closedin_closure_of closedin_subset closure_of_minimal closure_of_subset eq_iff order.trans)\n\nlemma closure_of_eq_empty_gen: \"X closure_of S = {} \\<longleftrightarrow> disjnt (topspace X) S\"\n  unfolding disjnt_def closure_of_restrict [where S=S]\n  using closure_of by fastforce\n\nlemma closure_of_eq_empty: \"S \\<subseteq> topspace X \\<Longrightarrow> X closure_of S = {} \\<longleftrightarrow> S = {}\"\n  using closure_of_subset by fastforce\n\nlemma openin_Int_closure_of_subset:\n  assumes \"openin X S\"\n  shows \"S \\<inter> X closure_of T \\<subseteq> X closure_of (S \\<inter> T)\"\nproof -\n  have \"S \\<inter> X derived_set_of T = S \\<inter> X derived_set_of (S \\<inter> T)\"\n    by (meson assms openin_Int_derived_set_of_eq)\n  moreover have \"S \\<inter> (S \\<inter> T) = S \\<inter> T\"\n    by fastforce\n  ultimately show ?thesis\n    by (metis closure_of_alt inf.cobounded2 inf_left_commute inf_sup_distrib1)\nqed\n\nlemma closure_of_openin_Int_closure_of:\n  assumes \"openin X S\"\n  shows \"X closure_of (S \\<inter> X closure_of T) = X closure_of (S \\<inter> T)\"\nproof\n  show \"X closure_of (S \\<inter> X closure_of T) \\<subseteq> X closure_of (S \\<inter> T)\"\n    by (simp add: assms closure_of_minimal openin_Int_closure_of_subset)\nnext\n  show \"X closure_of (S \\<inter> T) \\<subseteq> X closure_of (S \\<inter> X closure_of T)\"\n    by (metis Int_lower1 Int_subset_iff assms closedin_closure_of closure_of_minimal_eq closure_of_mono inf_le2 le_infI1 openin_subset)\nqed\n\nlemma openin_Int_closure_of_eq:\n  \"openin X S \\<Longrightarrow> S \\<inter> X closure_of T = S \\<inter> X closure_of (S \\<inter> T)\"\n  apply (rule equalityI)\n   apply (simp add: openin_Int_closure_of_subset)\n  by (meson closure_of_mono inf.cobounded2 inf_mono subset_refl)\n\nlemma openin_Int_closure_of_eq_empty:\n   \"openin X S \\<Longrightarrow> S \\<inter> X closure_of T = {} \\<longleftrightarrow> S \\<inter> T = {}\"\n  apply (subst openin_Int_closure_of_eq, auto)\n  by (meson IntI closure_of_subset_Int disjoint_iff_not_equal openin_subset subset_eq)\n\nlemma closure_of_openin_Int_superset:\n   \"openin X S \\<and> S \\<subseteq> X closure_of T\n        \\<Longrightarrow> X closure_of (S \\<inter> T) = X closure_of S\"\n  by (metis closure_of_openin_Int_closure_of inf.orderE)\n\nlemma closure_of_openin_subtopology_Int_closure_of:\n  assumes S: \"openin (subtopology X U) S\" and \"T \\<subseteq> U\"\n  shows \"X closure_of (S \\<inter> X closure_of T) = X closure_of (S \\<inter> T)\" (is \"?lhs = ?rhs\")\nproof\n  obtain S0 where S0: \"openin X S0\" \"S = S0 \\<inter> U\"\n    using assms by (auto simp: openin_subtopology)\n  show \"?lhs \\<subseteq> ?rhs\"\n  proof -\n    have \"S0 \\<inter> X closure_of T = S0 \\<inter> X closure_of (S0 \\<inter> T)\"\n      by (meson S0(1) openin_Int_closure_of_eq)\n    moreover have \"S0 \\<inter> T = S0 \\<inter> U \\<inter> T\"\n      using \\<open>T \\<subseteq> U\\<close> by fastforce\n    ultimately have \"S \\<inter> X closure_of T \\<subseteq> X closure_of (S \\<inter> T)\"\n      using S0(2) by auto\n    then show ?thesis\n      by (meson closedin_closure_of closure_of_minimal)\n  qed\nnext\n  show \"?rhs \\<subseteq> ?lhs\"\n  proof -\n    have \"T \\<inter> S \\<subseteq> T \\<union> X derived_set_of T\"\n      by force\n    then show ?thesis\n      by (metis Int_subset_iff S closure_of closure_of_mono inf.cobounded2 inf.coboundedI2 inf_commute openin_closedin_eq topspace_subtopology)\n  qed\nqed\n\nlemma closure_of_subtopology_open:\n     \"openin X U \\<or> S \\<subseteq> U \\<Longrightarrow> (subtopology X U) closure_of S = U \\<inter> X closure_of S\"\n  by (metis closure_of_subtopology inf_absorb2 openin_Int_closure_of_eq)\n\nlemma discrete_topology_closure_of:\n     \"(discrete_topology U) closure_of S = U \\<inter> S\"\n  by (metis closedin_discrete_topology closure_of_restrict closure_of_unique discrete_topology_unique inf_sup_ord(1) order_refl)\n\n\ntext\\<open> Interior with respect to a topological space.                             \\<close>\n\ndefinition interior_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixr \"interior'_of\" 80)\n  where \"X interior_of S \\<equiv> {x. \\<exists>T. openin X T \\<and> x \\<in> T \\<and> T \\<subseteq> S}\"\n\nlemma interior_of_restrict:\n   \"X interior_of S = X interior_of (topspace X \\<inter> S)\"\n  using openin_subset by (auto simp: interior_of_def)\n\nlemma interior_of_eq: \"(X interior_of S = S) \\<longleftrightarrow> openin X S\"\n  unfolding interior_of_def  using openin_subopen by blast\n\nlemma interior_of_openin: \"openin X S \\<Longrightarrow> X interior_of S = S\"\n  by (simp add: interior_of_eq)\n\nlemma interior_of_empty [simp]: \"X interior_of {} = {}\"\n  by (simp add: interior_of_eq)\n\nlemma interior_of_topspace [simp]: \"X interior_of (topspace X) = topspace X\"\n  by (simp add: interior_of_eq)\n\nlemma openin_interior_of [simp]: \"openin X (X interior_of S)\"\n  unfolding interior_of_def\n  using openin_subopen by fastforce\n\nlemma interior_of_interior_of [simp]:\n   \"X interior_of X interior_of S = X interior_of S\"\n  by (simp add: interior_of_eq)\n\nlemma interior_of_subset: \"X interior_of S \\<subseteq> S\"\n  by (auto simp: interior_of_def)\n\nlemma interior_of_subset_closure_of: \"X interior_of S \\<subseteq> X closure_of S\"\n  by (metis closure_of_subset_Int dual_order.trans interior_of_restrict interior_of_subset)\n\nlemma subset_interior_of_eq: \"S \\<subseteq> X interior_of S \\<longleftrightarrow> openin X S\"\n  by (metis interior_of_eq interior_of_subset subset_antisym)\n\nlemma interior_of_mono: \"S \\<subseteq> T \\<Longrightarrow> X interior_of S \\<subseteq> X interior_of T\"\n  by (auto simp: interior_of_def)\n\nlemma interior_of_maximal: \"\\<lbrakk>T \\<subseteq> S; openin X T\\<rbrakk> \\<Longrightarrow> T \\<subseteq> X interior_of S\"\n  by (auto simp: interior_of_def)\n\nlemma interior_of_maximal_eq: \"openin X T \\<Longrightarrow> T \\<subseteq> X interior_of S \\<longleftrightarrow> T \\<subseteq> S\"\n  by (meson interior_of_maximal interior_of_subset order_trans)\n\nlemma interior_of_unique:\n   \"\\<lbrakk>T \\<subseteq> S; openin X T; \\<And>T'. \\<lbrakk>T' \\<subseteq> S; openin X T'\\<rbrakk> \\<Longrightarrow> T' \\<subseteq> T\\<rbrakk> \\<Longrightarrow> X interior_of S = T\"\n  by (simp add: interior_of_maximal_eq interior_of_subset subset_antisym)\n\nlemma interior_of_subset_topspace: \"X interior_of S \\<subseteq> topspace X\"\n  by (simp add: openin_subset)\n\nlemma interior_of_subset_subtopology: \"(subtopology X S) interior_of T \\<subseteq> S\"\n  by (meson openin_imp_subset openin_interior_of)\n\nlemma interior_of_Int: \"X interior_of (S \\<inter> T) = X interior_of S \\<inter> X interior_of T\"\n  apply (rule equalityI)\n   apply (simp add: interior_of_mono)\n  apply (auto simp: interior_of_maximal_eq openin_Int interior_of_subset le_infI1 le_infI2)\n  done\n\nlemma interior_of_Inter_subset: \"X interior_of (\\<Inter>\\<F>) \\<subseteq> (\\<Inter>S \\<in> \\<F>. X interior_of S)\"\n  by (simp add: INT_greatest Inf_lower interior_of_mono)\n\nlemma union_interior_of_subset:\n   \"X interior_of S \\<union> X interior_of T \\<subseteq> X interior_of (S \\<union> T)\"\n  by (simp add: interior_of_mono)\n\nlemma interior_of_eq_empty:\n   \"X interior_of S = {} \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<subseteq> S \\<longrightarrow> T = {})\"\n  by (metis bot.extremum_uniqueI interior_of_maximal interior_of_subset openin_interior_of)\n\nlemma interior_of_eq_empty_alt:\n   \"X interior_of S = {} \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<noteq> {} \\<longrightarrow> T - S \\<noteq> {})\"\n  by (auto simp: interior_of_eq_empty)\n\nlemma interior_of_Union_openin_subsets:\n   \"\\<Union>{T. openin X T \\<and> T \\<subseteq> S} = X interior_of S\"\n  by (rule interior_of_unique [symmetric]) auto\n\nlemma interior_of_complement:\n   \"X interior_of (topspace X - S) = topspace X - X closure_of S\"\n  by (auto simp: interior_of_def closure_of_def)\n\nlemma interior_of_closure_of:\n   \"X interior_of S = topspace X - X closure_of (topspace X - S)\"\n  unfolding interior_of_complement [symmetric]\n  by (metis Diff_Diff_Int interior_of_restrict)\n\nlemma closure_of_interior_of:\n   \"X closure_of S = topspace X - X interior_of (topspace X - S)\"\n  by (simp add: interior_of_complement Diff_Diff_Int closure_of)\n\nlemma closure_of_complement: \"X closure_of (topspace X - S) = topspace X - X interior_of S\"\n  unfolding interior_of_def closure_of_def\n  by (blast dest: openin_subset)\n\nlemma interior_of_eq_empty_complement:\n  \"X interior_of S = {} \\<longleftrightarrow> X closure_of (topspace X - S) = topspace X\"\n  using interior_of_subset_topspace [of X S] closure_of_complement by fastforce\n\nlemma closure_of_eq_topspace:\n   \"X closure_of S = topspace X \\<longleftrightarrow> X interior_of (topspace X - S) = {}\"\n  using closure_of_subset_topspace [of X S] interior_of_complement by fastforce\n\nlemma interior_of_subtopology_subset:\n     \"U \\<inter> X interior_of S \\<subseteq> (subtopology X U) interior_of S\"\n  by (auto simp: interior_of_def openin_subtopology)\n\nlemma interior_of_subtopology_subsets:\n   \"T \\<subseteq> U \\<Longrightarrow> T \\<inter> (subtopology X U) interior_of S \\<subseteq> (subtopology X T) interior_of S\"\n  by (metis inf.absorb_iff2 interior_of_subtopology_subset subtopology_subtopology)\n\nlemma interior_of_subtopology_mono:\n   \"\\<lbrakk>S \\<subseteq> T; T \\<subseteq> U\\<rbrakk> \\<Longrightarrow> (subtopology X U) interior_of S \\<subseteq> (subtopology X T) interior_of S\"\n  by (metis dual_order.trans inf.orderE inf_commute interior_of_subset interior_of_subtopology_subsets)\n\nlemma interior_of_subtopology_open:\n  assumes \"openin X U\"\n  shows \"(subtopology X U) interior_of S = U \\<inter> X interior_of S\"\nproof -\n  have \"\\<forall>A. U \\<inter> X closure_of (U \\<inter> A) = U \\<inter> X closure_of A\"\n    using assms openin_Int_closure_of_eq by blast\n  then have \"topspace X \\<inter> U - U \\<inter> X closure_of (topspace X \\<inter> U - S) = U \\<inter> (topspace X - X closure_of (topspace X - S))\"\n    by (metis (no_types) Diff_Int_distrib Int_Diff inf_commute)\n  then show ?thesis\n    unfolding interior_of_closure_of closure_of_subtopology_open topspace_subtopology\n    using openin_Int_closure_of_eq [OF assms]\n    by (metis assms closure_of_subtopology_open)\nqed\n\nlemma dense_intersects_open:\n   \"X closure_of S = topspace X \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<noteq> {} \\<longrightarrow> S \\<inter> T \\<noteq> {})\"\nproof -\n  have \"X closure_of S = topspace X \\<longleftrightarrow> (topspace X - X interior_of (topspace X - S) = topspace X)\"\n    by (simp add: closure_of_interior_of)\n  also have \"\\<dots> \\<longleftrightarrow> X interior_of (topspace X - S) = {}\"\n    by (simp add: closure_of_complement interior_of_eq_empty_complement)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<noteq> {} \\<longrightarrow> S \\<inter> T \\<noteq> {})\"\n    unfolding interior_of_eq_empty_alt\n    using openin_subset by fastforce\n  finally show ?thesis .\nqed\n\nlemma interior_of_closedin_union_empty_interior_of:\n  assumes \"closedin X S\" and disj: \"X interior_of T = {}\"\n  shows \"X interior_of (S \\<union> T) = X interior_of S\"\nproof -\n  have \"X closure_of (topspace X - T) = topspace X\"\n    by (metis Diff_Diff_Int disj closure_of_eq_topspace closure_of_restrict interior_of_closure_of)\n  then show ?thesis\n    unfolding interior_of_closure_of\n    by (metis Diff_Un Diff_subset assms(1) closedin_def closure_of_openin_Int_superset)\nqed\n\nlemma interior_of_union_eq_empty:\n   \"closedin X S\n        \\<Longrightarrow> (X interior_of (S \\<union> T) = {} \\<longleftrightarrow>\n             X interior_of S = {} \\<and> X interior_of T = {})\"\n  by (metis interior_of_closedin_union_empty_interior_of le_sup_iff subset_empty union_interior_of_subset)\n\nlemma discrete_topology_interior_of [simp]:\n    \"(discrete_topology U) interior_of S = U \\<inter> S\"\n  by (simp add: interior_of_restrict [of _ S] interior_of_eq)\n\n\nsubsection \\<open>Frontier with respect to topological space \\<close>\n\ndefinition frontier_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixr \"frontier'_of\" 80)\n  where \"X frontier_of S \\<equiv> X closure_of S - X interior_of S\"\n\nlemma frontier_of_closures:\n     \"X frontier_of S = X closure_of S \\<inter> X closure_of (topspace X - S)\"\n  by (metis Diff_Diff_Int closure_of_complement closure_of_subset_topspace double_diff frontier_of_def interior_of_subset_closure_of)\n\n\nlemma interior_of_union_frontier_of [simp]:\n     \"X interior_of S \\<union> X frontier_of S = X closure_of S\"\n  by (simp add: frontier_of_def interior_of_subset_closure_of subset_antisym)\n\nlemma frontier_of_restrict: \"X frontier_of S = X frontier_of (topspace X \\<inter> S)\"\n  by (metis closure_of_restrict frontier_of_def interior_of_restrict)\n\nlemma closedin_frontier_of: \"closedin X (X frontier_of S)\"\n  by (simp add: closedin_Int frontier_of_closures)\n\nlemma frontier_of_subset_topspace: \"X frontier_of S \\<subseteq> topspace X\"\n  by (simp add: closedin_frontier_of closedin_subset)\n\nlemma frontier_of_subset_subtopology: \"(subtopology X S) frontier_of T \\<subseteq> S\"\n  by (metis (no_types) closedin_derived_set closedin_frontier_of)\n\nlemma frontier_of_subtopology_subset:\n  \"U \\<inter> (subtopology X U) frontier_of S \\<subseteq> (X frontier_of S)\"\nproof -\n  have \"U \\<inter> X interior_of S - subtopology X U interior_of S = {}\"\n    by (simp add: interior_of_subtopology_subset)\n  moreover have \"X closure_of S \\<inter> subtopology X U closure_of S = subtopology X U closure_of S\"\n    by (meson closure_of_subtopology_subset inf.absorb_iff2)\n  ultimately show ?thesis\n    unfolding frontier_of_def\n    by blast\nqed\n\nlemma frontier_of_subtopology_mono:\n   \"\\<lbrakk>S \\<subseteq> T; T \\<subseteq> U\\<rbrakk> \\<Longrightarrow> (subtopology X T) frontier_of S \\<subseteq> (subtopology X U) frontier_of S\"\n    by (simp add: frontier_of_def Diff_mono closure_of_subtopology_mono interior_of_subtopology_mono)\n\nlemma clopenin_eq_frontier_of:\n   \"closedin X S \\<and> openin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> X frontier_of S = {}\"\nproof (cases \"S \\<subseteq> topspace X\")\n  case True\n  then show ?thesis\n    by (metis Diff_eq_empty_iff closure_of_eq closure_of_subset_eq frontier_of_def interior_of_eq interior_of_subset interior_of_union_frontier_of sup_bot_right)\nnext\n  case False\n  then show ?thesis\n    by (simp add: frontier_of_closures openin_closedin_eq)\nqed\n\nlemma frontier_of_eq_empty:\n     \"S \\<subseteq> topspace X \\<Longrightarrow> (X frontier_of S = {} \\<longleftrightarrow> closedin X S \\<and> openin X S)\"\n  by (simp add: clopenin_eq_frontier_of)\n\nlemma frontier_of_openin:\n     \"openin X S \\<Longrightarrow> X frontier_of S = X closure_of S - S\"\n  by (metis (no_types) frontier_of_def interior_of_eq)\n\nlemma frontier_of_openin_straddle_Int:\n  assumes \"openin X U\" \"U \\<inter> X frontier_of S \\<noteq> {}\"\n  shows \"U \\<inter> S \\<noteq> {}\" \"U - S \\<noteq> {}\"\nproof -\n  have \"U \\<inter> (X closure_of S \\<inter> X closure_of (topspace X - S)) \\<noteq> {}\"\n    using assms by (simp add: frontier_of_closures)\n  then show \"U \\<inter> S \\<noteq> {}\"\n    using assms openin_Int_closure_of_eq_empty by fastforce\n  show \"U - S \\<noteq> {}\"\n  proof -\n    have \"\\<exists>A. X closure_of (A - S) \\<inter> U \\<noteq> {}\"\n      using \\<open>U \\<inter> (X closure_of S \\<inter> X closure_of (topspace X - S)) \\<noteq> {}\\<close> by blast\n    then have \"\\<not> U \\<subseteq> S\"\n      by (metis Diff_disjoint Diff_eq_empty_iff Int_Diff assms(1) inf_commute openin_Int_closure_of_eq_empty)\n    then show ?thesis\n      by blast\n  qed\nqed\n\nlemma frontier_of_subset_closedin: \"closedin X S \\<Longrightarrow> (X frontier_of S) \\<subseteq> S\"\n  using closure_of_eq frontier_of_def by fastforce\n\nlemma frontier_of_empty [simp]: \"X frontier_of {} = {}\"\n  by (simp add: frontier_of_def)\n\nlemma frontier_of_topspace [simp]: \"X frontier_of topspace X = {}\"\n  by (simp add: frontier_of_def)\n\nlemma frontier_of_subset_eq:\n  assumes \"S \\<subseteq> topspace X\"\n  shows \"(X frontier_of S) \\<subseteq> S \\<longleftrightarrow> closedin X S\"\nproof\n  show \"X frontier_of S \\<subseteq> S \\<Longrightarrow> closedin X S\"\n    by (metis assms closure_of_subset_eq interior_of_subset interior_of_union_frontier_of le_sup_iff)\n  show \"closedin X S \\<Longrightarrow> X frontier_of S \\<subseteq> S\"\n    by (simp add: frontier_of_subset_closedin)\nqed\n\nlemma frontier_of_complement: \"X frontier_of (topspace X - S) = X frontier_of S\"\n  by (metis Diff_Diff_Int closure_of_restrict frontier_of_closures inf_commute)\n\nlemma frontier_of_disjoint_eq:\n  assumes \"S \\<subseteq> topspace X\"\n  shows \"((X frontier_of S) \\<inter> S = {} \\<longleftrightarrow> openin X S)\"\nproof\n  assume \"X frontier_of S \\<inter> S = {}\"\n  then have \"closedin X (topspace X - S)\"\n    using assms closure_of_subset frontier_of_def interior_of_eq interior_of_subset by fastforce\n  then show \"openin X S\"\n    using assms by (simp add: openin_closedin)\nnext\n  show \"openin X S \\<Longrightarrow> X frontier_of S \\<inter> S = {}\"\n    by (simp add: Diff_Diff_Int closedin_def frontier_of_openin inf.absorb_iff2 inf_commute)\nqed\n\nlemma frontier_of_disjoint_eq_alt:\n  \"S \\<subseteq> (topspace X - X frontier_of S) \\<longleftrightarrow> openin X S\"\nproof (cases \"S \\<subseteq> topspace X\")\n  case True\n  show ?thesis\n    using True frontier_of_disjoint_eq by auto\nnext\n  case False\n  then show ?thesis\n    by (meson Diff_subset openin_subset subset_trans)\nqed\n\nlemma frontier_of_Int:\n     \"X frontier_of (S \\<inter> T) =\n      X closure_of (S \\<inter> T) \\<inter> (X frontier_of S \\<union> X frontier_of T)\"\nproof -\n  have *: \"U \\<subseteq> S \\<and> U \\<subseteq> T \\<Longrightarrow> U \\<inter> (S \\<inter> A \\<union> T \\<inter> B) = U \\<inter> (A \\<union> B)\" for U S T A B :: \"'a set\"\n    by blast\n  show ?thesis\n    by (simp add: frontier_of_closures closure_of_mono Diff_Int * flip: closure_of_Un)\nqed\n\nlemma frontier_of_Int_subset: \"X frontier_of (S \\<inter> T) \\<subseteq> X frontier_of S \\<union> X frontier_of T\"\n  by (simp add: frontier_of_Int)\n\nlemma frontier_of_Int_closedin:\n  \"\\<lbrakk>closedin X S; closedin X T\\<rbrakk> \\<Longrightarrow> X frontier_of(S \\<inter> T) = X frontier_of S \\<inter> T \\<union> S \\<inter> X frontier_of T\"\n  apply (simp add: frontier_of_Int closedin_Int closure_of_closedin)\n  using frontier_of_subset_closedin by blast\n\nlemma frontier_of_Un_subset: \"X frontier_of(S \\<union> T) \\<subseteq> X frontier_of S \\<union> X frontier_of T\"\n  by (metis Diff_Un frontier_of_Int_subset frontier_of_complement)\n\nlemma frontier_of_Union_subset:\n   \"finite \\<F> \\<Longrightarrow> X frontier_of (\\<Union>\\<F>) \\<subseteq> (\\<Union>T \\<in> \\<F>. X frontier_of T)\"\nproof (induction \\<F> rule: finite_induct)\n  case (insert A \\<F>)\n  then show ?case\n    using frontier_of_Un_subset by fastforce\nqed simp\n\nlemma frontier_of_frontier_of_subset:\n     \"X frontier_of (X frontier_of S) \\<subseteq> X frontier_of S\"\n  by (simp add: closedin_frontier_of frontier_of_subset_closedin)\n\nlemma frontier_of_subtopology_open:\n     \"openin X U \\<Longrightarrow> (subtopology X U) frontier_of S = U \\<inter> X frontier_of S\"\n  by (simp add: Diff_Int_distrib closure_of_subtopology_open frontier_of_def interior_of_subtopology_open)\n\nlemma discrete_topology_frontier_of [simp]:\n     \"(discrete_topology U) frontier_of S = {}\"\n  by (simp add: Diff_eq discrete_topology_closure_of frontier_of_closures)\n\n\nsubsection\\<open>Locally finite collections\\<close>\n\ndefinition locally_finite_in\n  where\n \"locally_finite_in X \\<A> \\<longleftrightarrow>\n        (\\<Union>\\<A> \\<subseteq> topspace X) \\<and>\n        (\\<forall>x \\<in> topspace X. \\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}})\"\n\nlemma finite_imp_locally_finite_in:\n   \"\\<lbrakk>finite \\<A>; \\<Union>\\<A> \\<subseteq> topspace X\\<rbrakk> \\<Longrightarrow> locally_finite_in X \\<A>\"\n  by (auto simp: locally_finite_in_def)\n\nlemma locally_finite_in_subset:\n  assumes \"locally_finite_in X \\<A>\" \"\\<B> \\<subseteq> \\<A>\"\n  shows \"locally_finite_in X \\<B>\"\nproof -\n  have \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}} \\<Longrightarrow> finite {U \\<in> \\<B>. U \\<inter> V \\<noteq> {}}\" for V\n    apply (erule rev_finite_subset) using \\<open>\\<B> \\<subseteq> \\<A>\\<close> by blast\n  then show ?thesis\n  using assms unfolding locally_finite_in_def by (fastforce simp add:)\nqed\n\nlemma locally_finite_in_refinement:\n  assumes \\<A>: \"locally_finite_in X \\<A>\" and f: \"\\<And>S. S \\<in> \\<A> \\<Longrightarrow> f S \\<subseteq> S\"\n  shows \"locally_finite_in X (f ` \\<A>)\"\nproof -\n  show ?thesis\n    unfolding locally_finite_in_def\n  proof safe\n    fix x\n    assume \"x \\<in> topspace X\"\n    then obtain V where \"openin X V\" \"x \\<in> V\" \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n      using \\<A> unfolding locally_finite_in_def by blast\n    moreover have \"{U \\<in> \\<A>. f U \\<inter> V \\<noteq> {}} \\<subseteq> {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\" for V\n      using f by blast\n    ultimately have \"finite {U \\<in> \\<A>. f U \\<inter> V \\<noteq> {}}\"\n      using finite_subset by blast\n    moreover have \"f ` {U \\<in> \\<A>. f U \\<inter> V \\<noteq> {}} = {U \\<in> f ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n      by blast\n    ultimately have \"finite {U \\<in> f ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n      by (metis (no_types, lifting) finite_imageI)\n    then show \"\\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {U \\<in> f ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n      using \\<open>openin X V\\<close> \\<open>x \\<in> V\\<close> by blast\n  next\n    show \"\\<And>x xa. \\<lbrakk>xa \\<in> \\<A>; x \\<in> f xa\\<rbrakk> \\<Longrightarrow> x \\<in> topspace X\"\n      by (meson Sup_upper \\<A> f locally_finite_in_def subset_iff)\n  qed\nqed\n\nlemma locally_finite_in_subtopology:\n  assumes \\<A>: \"locally_finite_in X \\<A>\" \"\\<Union>\\<A> \\<subseteq> S\"\n  shows \"locally_finite_in (subtopology X S) \\<A>\"\n  unfolding locally_finite_in_def\nproof safe\n  fix x\n  assume x: \"x \\<in> topspace (subtopology X S)\"\n  then obtain V where \"openin X V\" \"x \\<in> V\" and fin: \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n    using \\<A> unfolding locally_finite_in_def topspace_subtopology by blast\n  show \"\\<exists>V. openin (subtopology X S) V \\<and> x \\<in> V \\<and> finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n  proof (intro exI conjI)\n    show \"openin (subtopology X S) (S \\<inter> V)\"\n      by (simp add: \\<open>openin X V\\<close> openin_subtopology_Int2)\n    have \"{U \\<in> \\<A>. U \\<inter> (S \\<inter> V) \\<noteq> {}} \\<subseteq> {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n      by auto\n    with fin show \"finite {U \\<in> \\<A>. U \\<inter> (S \\<inter> V) \\<noteq> {}}\"\n      using finite_subset by auto\n    show \"x \\<in> S \\<inter> V\"\n      using x \\<open>x \\<in> V\\<close> by (simp)\n  qed\nnext\n  show \"\\<And>x A. \\<lbrakk>x \\<in> A; A \\<in> \\<A>\\<rbrakk> \\<Longrightarrow> x \\<in> topspace (subtopology X S)\"\n    using assms unfolding locally_finite_in_def topspace_subtopology by blast\nqed\n\n\nlemma closedin_locally_finite_Union:\n  assumes clo: \"\\<And>S. S \\<in> \\<A> \\<Longrightarrow> closedin X S\" and \\<A>: \"locally_finite_in X \\<A>\"\n  shows \"closedin X (\\<Union>\\<A>)\"\n  using \\<A> unfolding locally_finite_in_def closedin_def\nproof clarify\n  show \"openin X (topspace X - \\<Union>\\<A>)\"\n  proof (subst openin_subopen, clarify)\n    fix x\n    assume \"x \\<in> topspace X\" and \"x \\<notin> \\<Union>\\<A>\"\n    then obtain V where \"openin X V\" \"x \\<in> V\" and fin: \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n      using \\<A> unfolding locally_finite_in_def by blast\n    let ?T = \"V - \\<Union>{S \\<in> \\<A>. S \\<inter> V \\<noteq> {}}\"\n    show \"\\<exists>T. openin X T \\<and> x \\<in> T \\<and> T \\<subseteq> topspace X - \\<Union>\\<A>\"\n    proof (intro exI conjI)\n      show \"openin X ?T\"\n        by (metis (no_types, lifting) fin \\<open>openin X V\\<close> clo closedin_Union mem_Collect_eq openin_diff)\n      show \"x \\<in> ?T\"\n        using \\<open>x \\<notin> \\<Union>\\<A>\\<close> \\<open>x \\<in> V\\<close> by auto\n      show \"?T \\<subseteq> topspace X - \\<Union>\\<A>\"\n        using \\<open>openin X V\\<close> openin_subset by auto\n    qed\n  qed\nqed\n\nlemma locally_finite_in_closure:\n  assumes \\<A>: \"locally_finite_in X \\<A>\"\n  shows \"locally_finite_in X ((\\<lambda>S. X closure_of S) ` \\<A>)\"\n  using \\<A> unfolding locally_finite_in_def\nproof (intro conjI; clarsimp)\n  fix x A\n  assume \"x \\<in> X closure_of A\"\n  then show \"x \\<in> topspace X\"\n    by (meson in_closure_of)\nnext\n  fix x\n  assume \"x \\<in> topspace X\" and \"\\<Union>\\<A> \\<subseteq> topspace X\"\n  then obtain V where V: \"openin X V\" \"x \\<in> V\" and fin: \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n    using \\<A> unfolding locally_finite_in_def by blast\n  have eq: \"{y \\<in> f ` \\<A>. Q y} = f ` {x. x \\<in> \\<A> \\<and> Q(f x)}\" for f Q\n    by blast\n  have eq2: \"{A \\<in> \\<A>. X closure_of A \\<inter> V \\<noteq> {}} = {A \\<in> \\<A>. A \\<inter> V \\<noteq> {}}\"\n    using openin_Int_closure_of_eq_empty V  by blast\n  have \"finite {U \\<in> (closure_of) X ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n    by (simp add: eq eq2 fin)\n  with V show \"\\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {U \\<in> (closure_of) X ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n    by blast\nqed\n\nlemma closedin_Union_locally_finite_closure:\n   \"locally_finite_in X \\<A> \\<Longrightarrow> closedin X (\\<Union>((\\<lambda>S. X closure_of S) ` \\<A>))\"\n  by (metis (mono_tags) closedin_closure_of closedin_locally_finite_Union imageE locally_finite_in_closure)\n\nlemma closure_of_Union_subset: \"\\<Union>((\\<lambda>S. X closure_of S) ` \\<A>) \\<subseteq> X closure_of (\\<Union>\\<A>)\"\n  by clarify (meson Union_upper closure_of_mono subsetD)\n\nlemma closure_of_locally_finite_Union:\n   \"locally_finite_in X \\<A> \\<Longrightarrow> X closure_of (\\<Union>\\<A>) = \\<Union>((\\<lambda>S. X closure_of S) ` \\<A>)\"\n  apply (rule closure_of_unique)\n  apply (simp add: SUP_upper2 Sup_le_iff closure_of_subset locally_finite_in_def)\n  apply (simp add: closedin_Union_locally_finite_closure)\n  by (simp add: Sup_le_iff closure_of_minimal)\n\n\nsubsection\\<^marker>\\<open>tag important\\<close> \\<open>Continuous maps\\<close>\n\ntext \\<open>We will need to deal with continuous maps in terms of topologies and not in terms\nof type classes, as defined below.\\<close>\n\ndefinition continuous_map where\n  \"continuous_map X Y f \\<equiv>\n     (\\<forall>x \\<in> topspace X. f x \\<in> topspace Y) \\<and>\n     (\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U})\"\n\nlemma continuous_map:\n   \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and> (\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U})\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_image_subset_topspace:\n   \"continuous_map X Y f \\<Longrightarrow> f ` (topspace X) \\<subseteq> topspace Y\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_on_empty: \"topspace X = {} \\<Longrightarrow> continuous_map X Y f\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_closedin:\n   \"continuous_map X Y f \\<longleftrightarrow>\n         (\\<forall>x \\<in> topspace X. f x \\<in> topspace Y) \\<and>\n         (\\<forall>C. closedin Y C \\<longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C})\"\nproof -\n  have \"(\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}) =\n        (\\<forall>C. closedin Y C \\<longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C})\"\n    if \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y\"\n  proof -\n    have eq: \"{x \\<in> topspace X. f x \\<in> topspace Y \\<and> f x \\<notin> C} = (topspace X - {x \\<in> topspace X. f x \\<in> C})\" for C\n      using that by blast\n    show ?thesis\n    proof (intro iffI allI impI)\n      fix C\n      assume \"\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}\" and \"closedin Y C\"\n      then have \"openin X {x \\<in> topspace X. f x \\<in> topspace Y - C}\" by blast\n      then show \"closedin X {x \\<in> topspace X. f x \\<in> C}\"\n        by (auto simp add: closedin_def eq)\n    next\n      fix U\n      assume \"\\<forall>C. closedin Y C \\<longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C}\" and \"openin Y U\"\n      then have \"closedin X {x \\<in> topspace X. f x \\<in> topspace Y - U}\" by blast\n      then show \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n        by (auto simp add: openin_closedin_eq eq)\n    qed\n  qed\n  then show ?thesis\n    by (auto simp: continuous_map_def)\nqed\n\nlemma openin_continuous_map_preimage:\n   \"\\<lbrakk>continuous_map X Y f; openin Y U\\<rbrakk> \\<Longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}\"\n  by (simp add: continuous_map_def)\n\nlemma closedin_continuous_map_preimage:\n   \"\\<lbrakk>continuous_map X Y f; closedin Y C\\<rbrakk> \\<Longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C}\"\n  by (simp add: continuous_map_closedin)\n\nlemma openin_continuous_map_preimage_gen:\n  assumes \"continuous_map X Y f\" \"openin X U\" \"openin Y V\"\n  shows \"openin X {x \\<in> U. f x \\<in> V}\"\nproof -\n  have eq: \"{x \\<in> U. f x \\<in> V} = U \\<inter> {x \\<in> topspace X. f x \\<in> V}\"\n    using assms(2) openin_closedin_eq by fastforce\n  show ?thesis\n    unfolding eq\n    using assms openin_continuous_map_preimage by fastforce\nqed\n\nlemma closedin_continuous_map_preimage_gen:\n  assumes \"continuous_map X Y f\" \"closedin X U\" \"closedin Y V\"\n  shows \"closedin X {x \\<in> U. f x \\<in> V}\"\nproof -\n  have eq: \"{x \\<in> U. f x \\<in> V} = U \\<inter> {x \\<in> topspace X. f x \\<in> V}\"\n    using assms(2) closedin_def by fastforce\n  show ?thesis\n    unfolding eq\n    using assms closedin_continuous_map_preimage by fastforce\nqed\n\nlemma continuous_map_image_closure_subset:\n  assumes \"continuous_map X Y f\"\n  shows \"f ` (X closure_of S) \\<subseteq> Y closure_of f ` S\"\nproof -\n  have *: \"f ` (topspace X) \\<subseteq> topspace Y\"\n    by (meson assms continuous_map)\n  have \"X closure_of T \\<subseteq> {x \\<in> X closure_of T. f x \\<in> Y closure_of (f ` T)}\" if \"T \\<subseteq> topspace X\" for T\n  proof (rule closure_of_minimal)\n    show \"T \\<subseteq> {x \\<in> X closure_of T. f x \\<in> Y closure_of f ` T}\"\n      using closure_of_subset * that  by (fastforce simp: in_closure_of)\n  next\n    show \"closedin X {x \\<in> X closure_of T. f x \\<in> Y closure_of f ` T}\"\n      using assms closedin_continuous_map_preimage_gen by fastforce\n  qed\n  then have \"f ` (X closure_of (topspace X \\<inter> S)) \\<subseteq> Y closure_of (f ` (topspace X \\<inter> S))\"\n    by blast\n  also have \"\\<dots> \\<subseteq> Y closure_of (topspace Y \\<inter> f ` S)\"\n    using * by (blast intro!: closure_of_mono)\n  finally have \"f ` (X closure_of (topspace X \\<inter> S)) \\<subseteq> Y closure_of (topspace Y \\<inter> f ` S)\" .\n  then show ?thesis\n    by (metis closure_of_restrict)\nqed\n\nlemma continuous_map_subset_aux1: \"continuous_map X Y f \\<Longrightarrow>\n       (\\<forall>S. f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_image_closure_subset by blast\n\nlemma continuous_map_subset_aux2:\n  assumes \"\\<forall>S. S \\<subseteq> topspace X \\<longrightarrow> f ` (X closure_of S) \\<subseteq> Y closure_of f ` S\"\n  shows \"continuous_map X Y f\"\n  unfolding continuous_map_closedin\nproof (intro conjI ballI allI impI)\n  fix x\n  assume \"x \\<in> topspace X\"\n  then show \"f x \\<in> topspace Y\"\n    using assms closure_of_subset_topspace by fastforce\nnext\n  fix C\n  assume \"closedin Y C\"\n  then show \"closedin X {x \\<in> topspace X. f x \\<in> C}\"\n  proof (clarsimp simp flip: closure_of_subset_eq, intro conjI)\n    fix x\n    assume x: \"x \\<in> X closure_of {x \\<in> topspace X. f x \\<in> C}\"\n      and \"C \\<subseteq> topspace Y\" and \"Y closure_of C \\<subseteq> C\"\n    show \"x \\<in> topspace X\"\n      by (meson x in_closure_of)\n    have \"{a \\<in> topspace X. f a \\<in> C} \\<subseteq> topspace X\"\n      by simp\n    moreover have \"Y closure_of f ` {a \\<in> topspace X. f a \\<in> C} \\<subseteq> C\"\n      by (simp add: \\<open>closedin Y C\\<close> closure_of_minimal image_subset_iff)\n    ultimately have \"f ` (X closure_of {a \\<in> topspace X. f a \\<in> C}) \\<subseteq> C\"\n      using assms by blast\n    then show \"f x \\<in> C\"\n      using x by auto\n  qed\nqed\n\nlemma continuous_map_eq_image_closure_subset:\n     \"continuous_map X Y f \\<longleftrightarrow> (\\<forall>S. f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_subset_aux1 continuous_map_subset_aux2 by metis\n\nlemma continuous_map_eq_image_closure_subset_alt:\n     \"continuous_map X Y f \\<longleftrightarrow> (\\<forall>S. S \\<subseteq> topspace X \\<longrightarrow> f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_subset_aux1 continuous_map_subset_aux2 by metis\n\nlemma continuous_map_eq_image_closure_subset_gen:\n     \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and>\n        (\\<forall>S. f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_subset_aux1 continuous_map_subset_aux2 continuous_map_image_subset_topspace by metis\n\nlemma continuous_map_closure_preimage_subset:\n   \"continuous_map X Y f\n        \\<Longrightarrow> X closure_of {x \\<in> topspace X. f x \\<in> T}\n            \\<subseteq> {x \\<in> topspace X. f x \\<in> Y closure_of T}\"\n  unfolding continuous_map_closedin\n  by (rule closure_of_minimal) (use in_closure_of in \\<open>fastforce+\\<close>)\n\n\nlemma continuous_map_frontier_frontier_preimage_subset:\n  assumes \"continuous_map X Y f\"\n  shows \"X frontier_of {x \\<in> topspace X. f x \\<in> T} \\<subseteq> {x \\<in> topspace X. f x \\<in> Y frontier_of T}\"\nproof -\n  have eq: \"topspace X - {x \\<in> topspace X. f x \\<in> T} = {x \\<in> topspace X. f x \\<in> topspace Y - T}\"\n    using assms unfolding continuous_map_def by blast\n  have \"X closure_of {x \\<in> topspace X. f x \\<in> T} \\<subseteq> {x \\<in> topspace X. f x \\<in> Y closure_of T}\"\n    by (simp add: assms continuous_map_closure_preimage_subset)\n  moreover\n  have \"X closure_of (topspace X - {x \\<in> topspace X. f x \\<in> T}) \\<subseteq> {x \\<in> topspace X. f x \\<in> Y closure_of (topspace Y - T)}\"\n    using continuous_map_closure_preimage_subset [OF assms] eq by presburger\n  ultimately show ?thesis\n    by (auto simp: frontier_of_closures)\nqed\n\nlemma topology_finer_continuous_id:\n  \"topspace X = topspace Y \\<Longrightarrow> ((\\<forall>S. openin X S \\<longrightarrow> openin Y S) \\<longleftrightarrow> continuous_map Y X id)\"\n  unfolding continuous_map_def\n  apply auto\n  using openin_subopen openin_subset apply fastforce\n  using openin_subopen topspace_def by fastforce\n\nlemma continuous_map_const [simp]:\n   \"continuous_map X Y (\\<lambda>x. C) \\<longleftrightarrow> topspace X = {} \\<or> C \\<in> topspace Y\"\nproof (cases \"topspace X = {}\")\n  case False\n  show ?thesis\n  proof (cases \"C \\<in> topspace Y\")\n    case True\n    with openin_subopen show ?thesis\n      by (auto simp: continuous_map_def)\n  next\n    case False\n    then show ?thesis\n      unfolding continuous_map_def by fastforce\n  qed\nqed (auto simp: continuous_map_on_empty)\n\ndeclare continuous_map_const [THEN iffD2, continuous_intros]\n\nlemma continuous_map_compose [continuous_intros]:\n  assumes f: \"continuous_map X X' f\" and g: \"continuous_map X' X'' g\"\n  shows \"continuous_map X X'' (g \\<circ> f)\"\n  unfolding continuous_map_def\nproof (intro conjI ballI allI impI)\n  fix x\n  assume \"x \\<in> topspace X\"\n  then show \"(g \\<circ> f) x \\<in> topspace X''\"\n    using assms unfolding continuous_map_def by force\nnext\n  fix U\n  assume \"openin X'' U\"\n  have eq: \"{x \\<in> topspace X. (g \\<circ> f) x \\<in> U} = {x \\<in> topspace X. f x \\<in> {y. y \\<in> topspace X' \\<and> g y \\<in> U}}\"\n    by auto (meson f continuous_map_def)\n  show \"openin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> U}\"\n    unfolding eq\n    using assms unfolding continuous_map_def\n    using \\<open>openin X'' U\\<close> by blast\nqed\n\nlemma continuous_map_eq:\n  assumes \"continuous_map X X' f\" and \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\" shows \"continuous_map X X' g\"\nproof -\n  have eq: \"{x \\<in> topspace X. f x \\<in> U} = {x \\<in> topspace X. g x \\<in> U}\" for U\n    using assms by auto\n  show ?thesis\n    using assms by (simp add: continuous_map_def eq)\nqed\n\nlemma restrict_continuous_map [simp]:\n     \"topspace X \\<subseteq> S \\<Longrightarrow> continuous_map X X' (restrict f S) \\<longleftrightarrow> continuous_map X X' f\"\n  by (auto simp: elim!: continuous_map_eq)\n\nlemma continuous_map_in_subtopology:\n  \"continuous_map X (subtopology X' S) f \\<longleftrightarrow> continuous_map X X' f \\<and> f ` (topspace X) \\<subseteq> S\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  show ?rhs\n  proof -\n    have \"\\<And>A. f ` (X closure_of A) \\<subseteq> subtopology X' S closure_of f ` A\"\n      by (meson L continuous_map_image_closure_subset)\n    then show ?thesis\n      by (metis (no_types) closure_of_subset_subtopology closure_of_subtopology_subset closure_of_topspace continuous_map_eq_image_closure_subset dual_order.trans)\n  qed\nnext\n  assume R: ?rhs\n  then have eq: \"{x \\<in> topspace X. f x \\<in> U} = {x \\<in> topspace X. f x \\<in> U \\<and> f x \\<in> S}\" for U\n    by auto\n  show ?lhs\n    using R\n    unfolding continuous_map\n    by (auto simp: openin_subtopology eq)\nqed\n\n\nlemma continuous_map_from_subtopology:\n     \"continuous_map X X' f \\<Longrightarrow> continuous_map (subtopology X S) X' f\"\n  by (auto simp: continuous_map openin_subtopology)\n\nlemma continuous_map_into_fulltopology:\n   \"continuous_map X (subtopology X' T) f \\<Longrightarrow> continuous_map X X' f\"\n  by (auto simp: continuous_map_in_subtopology)\n\nlemma continuous_map_into_subtopology:\n   \"\\<lbrakk>continuous_map X X' f; f ` topspace X \\<subseteq> T\\<rbrakk> \\<Longrightarrow> continuous_map X (subtopology X' T) f\"\n  by (auto simp: continuous_map_in_subtopology)\n\nlemma continuous_map_from_subtopology_mono:\n     \"\\<lbrakk>continuous_map (subtopology X T) X' f; S \\<subseteq> T\\<rbrakk>\n      \\<Longrightarrow> continuous_map (subtopology X S) X' f\"\n  by (metis inf.absorb_iff2 continuous_map_from_subtopology subtopology_subtopology)\n\nlemma continuous_map_from_discrete_topology [simp]:\n  \"continuous_map (discrete_topology U) X f \\<longleftrightarrow> f ` U \\<subseteq> topspace X\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_iff_continuous [simp]: \"continuous_map (top_of_set S) euclidean g = continuous_on S g\"\n  by (fastforce simp add: continuous_map openin_subtopology continuous_on_open_invariant)\n\nlemma continuous_map_iff_continuous2 [simp]: \"continuous_map euclidean euclidean g = continuous_on UNIV g\"\n  by (metis continuous_map_iff_continuous subtopology_UNIV)\n\nlemma continuous_map_openin_preimage_eq:\n   \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and> (\\<forall>U. openin Y U \\<longrightarrow> openin X (topspace X \\<inter> f -` U))\"\n  by (auto simp: continuous_map_def vimage_def Int_def)\n\nlemma continuous_map_closedin_preimage_eq:\n   \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and> (\\<forall>U. closedin Y U \\<longrightarrow> closedin X (topspace X \\<inter> f -` U))\"\n  by (auto simp: continuous_map_closedin vimage_def Int_def)\n\nlemma continuous_map_square_root: \"continuous_map euclideanreal euclideanreal sqrt\"\n  by (simp add: continuous_at_imp_continuous_on isCont_real_sqrt)\n\nlemma continuous_map_sqrt [continuous_intros]:\n   \"continuous_map X euclideanreal f \\<Longrightarrow> continuous_map X euclideanreal (\\<lambda>x. sqrt(f x))\"\n  by (meson continuous_map_compose continuous_map_eq continuous_map_square_root o_apply)\n\nlemma continuous_map_id [simp, continuous_intros]: \"continuous_map X X id\"\n  unfolding continuous_map_def  using openin_subopen topspace_def by fastforce\n\ndeclare continuous_map_id [unfolded id_def, simp, continuous_intros]\n\nlemma continuous_map_id_subt [simp]: \"continuous_map (subtopology X S) X id\"\n  by (simp add: continuous_map_from_subtopology)\n\ndeclare continuous_map_id_subt [unfolded id_def, simp]\n\n\nlemma\\<^marker>\\<open>tag important\\<close> continuous_map_alt:\n   \"continuous_map T1 T2 f \n    = ((\\<forall>U. openin T2 U \\<longrightarrow> openin T1 (f -` U \\<inter> topspace T1)) \\<and> f ` topspace T1 \\<subseteq> topspace T2)\"\n  by (auto simp: continuous_map_def vimage_def image_def Collect_conj_eq inf_commute)\n\nlemma continuous_map_open [intro]:\n  \"continuous_map T1 T2 f \\<Longrightarrow> openin T2 U \\<Longrightarrow> openin T1 (f-`U \\<inter> topspace(T1))\"\n  unfolding continuous_map_alt by auto\n\nlemma continuous_map_preimage_topspace [intro]:\n  assumes \"continuous_map T1 T2 f\"\n  shows \"f-`(topspace T2) \\<inter> topspace T1 = topspace T1\"\nusing assms unfolding continuous_map_def by auto\n\n\n\nsubsection\\<open>Open and closed maps (not a priori assumed continuous)\\<close>\n\ndefinition open_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"open_map X1 X2 f \\<equiv> \\<forall>U. openin X1 U \\<longrightarrow> openin X2 (f ` U)\"\n\ndefinition closed_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"closed_map X1 X2 f \\<equiv> \\<forall>U. closedin X1 U \\<longrightarrow> closedin X2 (f ` U)\"\n\nlemma open_map_imp_subset_topspace:\n     \"open_map X1 X2 f \\<Longrightarrow> f ` (topspace X1) \\<subseteq> topspace X2\"\n  unfolding open_map_def by (simp add: openin_subset)\n\nlemma open_map_on_empty:\n   \"topspace X = {} \\<Longrightarrow> open_map X Y f\"\n  by (metis empty_iff imageE in_mono open_map_def openin_subopen openin_subset)\n\nlemma closed_map_on_empty:\n   \"topspace X = {} \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: closed_map_def closedin_topspace_empty)\n\nlemma closed_map_const:\n   \"closed_map X Y (\\<lambda>x. c) \\<longleftrightarrow> topspace X = {} \\<or> closedin Y {c}\"\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    by (simp add: closed_map_on_empty)\nnext\n  case False\n  then show ?thesis\n    by (auto simp: closed_map_def image_constant_conv)\nqed\n\nlemma open_map_imp_subset:\n    \"\\<lbrakk>open_map X1 X2 f; S \\<subseteq> topspace X1\\<rbrakk> \\<Longrightarrow> f ` S \\<subseteq> topspace X2\"\n  by (meson order_trans open_map_imp_subset_topspace subset_image_iff)\n\nlemma topology_finer_open_id:\n     \"(\\<forall>S. openin X S \\<longrightarrow> openin X' S) \\<longleftrightarrow> open_map X X' id\"\n  unfolding open_map_def by auto\n\nlemma open_map_id: \"open_map X X id\"\n  unfolding open_map_def by auto\n\nlemma open_map_eq:\n     \"\\<lbrakk>open_map X X' f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> open_map X X' g\"\n  unfolding open_map_def\n  by (metis image_cong openin_subset subset_iff)\n\nlemma open_map_inclusion_eq:\n  \"open_map (subtopology X S) X id \\<longleftrightarrow> openin X (topspace X \\<inter> S)\"\nproof -\n  have *: \"openin X (T \\<inter> S)\" if \"openin X (S \\<inter> topspace X)\" \"openin X T\" for T\n  proof -\n    have \"T \\<subseteq> topspace X\"\n      using that by (simp add: openin_subset)\n    with that show \"openin X (T \\<inter> S)\"\n      by (metis inf.absorb1 inf.left_commute inf_commute openin_Int)\n  qed\n  show ?thesis\n    by (fastforce simp add: open_map_def Int_commute openin_subtopology_alt intro: *)\nqed\n\nlemma open_map_inclusion:\n     \"openin X S \\<Longrightarrow> open_map (subtopology X S) X id\"\n  by (simp add: open_map_inclusion_eq openin_Int)\n\nlemma open_map_compose:\n     \"\\<lbrakk>open_map X X' f; open_map X' X'' g\\<rbrakk> \\<Longrightarrow> open_map X X'' (g \\<circ> f)\"\n  by (metis (no_types, lifting) image_comp open_map_def)\n\nlemma closed_map_imp_subset_topspace:\n     \"closed_map X1 X2 f \\<Longrightarrow> f ` (topspace X1) \\<subseteq> topspace X2\"\n  by (simp add: closed_map_def closedin_subset)\n\nlemma closed_map_imp_subset:\n     \"\\<lbrakk>closed_map X1 X2 f; S \\<subseteq> topspace X1\\<rbrakk> \\<Longrightarrow> f ` S \\<subseteq> topspace X2\"\n  using closed_map_imp_subset_topspace by blast\n\nlemma topology_finer_closed_id:\n    \"(\\<forall>S. closedin X S \\<longrightarrow> closedin X' S) \\<longleftrightarrow> closed_map X X' id\"\n  by (simp add: closed_map_def)\n\nlemma closed_map_id: \"closed_map X X id\"\n  by (simp add: closed_map_def)\n\nlemma closed_map_eq:\n   \"\\<lbrakk>closed_map X X' f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> closed_map X X' g\"\n  unfolding closed_map_def\n  by (metis image_cong closedin_subset subset_iff)\n\nlemma closed_map_compose:\n    \"\\<lbrakk>closed_map X X' f; closed_map X' X'' g\\<rbrakk> \\<Longrightarrow> closed_map X X'' (g \\<circ> f)\"\n  by (metis (no_types, lifting) closed_map_def image_comp)\n\nlemma closed_map_inclusion_eq:\n   \"closed_map (subtopology X S) X id \\<longleftrightarrow>\n        closedin X (topspace X \\<inter> S)\"\nproof -\n  have *: \"closedin X (T \\<inter> S)\" if \"closedin X (S \\<inter> topspace X)\" \"closedin X T\" for T\n  proof -\n    have \"T \\<subseteq> topspace X\"\n      using that by (simp add: closedin_subset)\n    with that show \"closedin X (T \\<inter> S)\"\n      by (metis inf.absorb1 inf.left_commute inf_commute closedin_Int)\n  qed\n  show ?thesis\n    by (fastforce simp add: closed_map_def Int_commute closedin_subtopology_alt intro: *)\nqed\n\nlemma closed_map_inclusion: \"closedin X S \\<Longrightarrow> closed_map (subtopology X S) X id\"\n  by (simp add: closed_map_inclusion_eq closedin_Int)\n\nlemma open_map_into_subtopology:\n    \"\\<lbrakk>open_map X X' f; f ` topspace X \\<subseteq> S\\<rbrakk> \\<Longrightarrow> open_map X (subtopology X' S) f\"\n  unfolding open_map_def openin_subtopology\n  using openin_subset by fastforce\n\nlemma closed_map_into_subtopology:\n    \"\\<lbrakk>closed_map X X' f; f ` topspace X \\<subseteq> S\\<rbrakk> \\<Longrightarrow> closed_map X (subtopology X' S) f\"\n  unfolding closed_map_def closedin_subtopology\n  using closedin_subset by fastforce\n\nlemma open_map_into_discrete_topology:\n    \"open_map X (discrete_topology U) f \\<longleftrightarrow> f ` (topspace X) \\<subseteq> U\"\n  unfolding open_map_def openin_discrete_topology using openin_subset by blast\n\nlemma closed_map_into_discrete_topology:\n    \"closed_map X (discrete_topology U) f \\<longleftrightarrow> f ` (topspace X) \\<subseteq> U\"\n  unfolding closed_map_def closedin_discrete_topology using closedin_subset by blast\n\nlemma bijective_open_imp_closed_map:\n     \"\\<lbrakk>open_map X X' f; f ` (topspace X) = topspace X'; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> closed_map X X' f\"\n  unfolding open_map_def closed_map_def closedin_def\n  by auto (metis Diff_subset inj_on_image_set_diff)\n\nlemma bijective_closed_imp_open_map:\n     \"\\<lbrakk>closed_map X X' f; f ` (topspace X) = topspace X'; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> open_map X X' f\"\n  unfolding closed_map_def open_map_def openin_closedin_eq\n  by auto (metis Diff_subset inj_on_image_set_diff)\n\nlemma open_map_from_subtopology:\n     \"\\<lbrakk>open_map X X' f; openin X U\\<rbrakk> \\<Longrightarrow> open_map (subtopology X U) X' f\"\n  unfolding open_map_def openin_subtopology_alt by blast\n\nlemma closed_map_from_subtopology:\n     \"\\<lbrakk>closed_map X X' f; closedin X U\\<rbrakk> \\<Longrightarrow> closed_map (subtopology X U) X' f\"\n  unfolding closed_map_def closedin_subtopology_alt by blast\n\nlemma open_map_restriction:\n     \"\\<lbrakk>open_map X X' f; {x. x \\<in> topspace X \\<and> f x \\<in> V} = U\\<rbrakk>\n      \\<Longrightarrow> open_map (subtopology X U) (subtopology X' V) f\"\n  unfolding open_map_def openin_subtopology_alt\n  apply clarify\n  apply (rename_tac T)\n  apply (rule_tac x=\"f ` T\" in image_eqI)\n  using openin_closedin_eq by fastforce+\n\nlemma closed_map_restriction:\n     \"\\<lbrakk>closed_map X X' f; {x. x \\<in> topspace X \\<and> f x \\<in> V} = U\\<rbrakk>\n      \\<Longrightarrow> closed_map (subtopology X U) (subtopology X' V) f\"\n  unfolding closed_map_def closedin_subtopology_alt\n  apply clarify\n  apply (rename_tac T)\n  apply (rule_tac x=\"f ` T\" in image_eqI)\n  using closedin_def by fastforce+\n\nsubsection\\<open>Quotient maps\\<close>\n                                      \ndefinition quotient_map where\n \"quotient_map X X' f \\<longleftrightarrow>\n        f ` (topspace X) = topspace X' \\<and>\n        (\\<forall>U. U \\<subseteq> topspace X' \\<longrightarrow> (openin X {x. x \\<in> topspace X \\<and> f x \\<in> U} \\<longleftrightarrow> openin X' U))\"\n\nlemma quotient_map_eq:\n  assumes \"quotient_map X X' f\" \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\"\n  shows \"quotient_map X X' g\"\nproof -\n  have eq: \"{x \\<in> topspace X. f x \\<in> U} = {x \\<in> topspace X. g x \\<in> U}\" for U\n    using assms by auto\n  show ?thesis\n  using assms\n  unfolding quotient_map_def\n  by (metis (mono_tags, lifting) eq image_cong)\nqed\n\nlemma quotient_map_compose:\n  assumes f: \"quotient_map X X' f\" and g: \"quotient_map X' X'' g\"\n  shows \"quotient_map X X'' (g \\<circ> f)\"\n  unfolding quotient_map_def\nproof (intro conjI allI impI)\n  show \"(g \\<circ> f) ` topspace X = topspace X''\"\n    using assms by (simp only: image_comp [symmetric]) (simp add: quotient_map_def)\nnext\n  fix U''\n  assume \"U'' \\<subseteq> topspace X''\"\n  define U' where \"U' \\<equiv> {y \\<in> topspace X'. g y \\<in> U''}\"\n  have \"U' \\<subseteq> topspace X'\"\n    by (auto simp add: U'_def)\n  then have U': \"openin X {x \\<in> topspace X. f x \\<in> U'} = openin X' U'\"\n    using assms unfolding quotient_map_def by simp\n  have eq: \"{x \\<in> topspace X. f x \\<in> topspace X' \\<and> g (f x) \\<in> U''} = {x \\<in> topspace X. (g \\<circ> f) x \\<in> U''}\"\n    using f quotient_map_def by fastforce\n  have \"openin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> U''} = openin X {x \\<in> topspace X. f x \\<in> U'}\"\n    using assms  by (simp add: quotient_map_def U'_def eq)\n  also have \"\\<dots> = openin X'' U''\"\n    using U'_def \\<open>U'' \\<subseteq> topspace X''\\<close> U' g quotient_map_def by fastforce\n  finally show \"openin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> U''} = openin X'' U''\" .\nqed\n\nlemma quotient_map_from_composition:\n  assumes f: \"continuous_map X X' f\" and g: \"continuous_map X' X'' g\" and gf: \"quotient_map X X'' (g \\<circ> f)\"\n  shows  \"quotient_map X' X'' g\"\n  unfolding quotient_map_def\nproof (intro conjI allI impI)\n  show \"g ` topspace X' = topspace X''\"\n    using assms unfolding continuous_map_def quotient_map_def by fastforce\nnext\n  fix U'' :: \"'c set\"\n  assume U'': \"U'' \\<subseteq> topspace X''\"\n  have eq: \"{x \\<in> topspace X. g (f x) \\<in> U''} = {x \\<in> topspace X. f x \\<in> {y. y \\<in> topspace X' \\<and> g y \\<in> U''}}\"\n    using continuous_map_def f by fastforce\n  show \"openin X' {x \\<in> topspace X'. g x \\<in> U''} = openin X'' U''\"\n    using assms unfolding continuous_map_def quotient_map_def\n    by (metis (mono_tags, lifting) Collect_cong U'' comp_apply eq)\nqed\n\nlemma quotient_imp_continuous_map:\n    \"quotient_map X X' f \\<Longrightarrow> continuous_map X X' f\"\n  by (simp add: continuous_map openin_subset quotient_map_def)\n\nlemma quotient_imp_surjective_map:\n    \"quotient_map X X' f \\<Longrightarrow> f ` (topspace X) = topspace X'\"\n  by (simp add: quotient_map_def)\n\nlemma quotient_map_closedin:\n  \"quotient_map X X' f \\<longleftrightarrow>\n        f ` (topspace X) = topspace X' \\<and>\n        (\\<forall>U. U \\<subseteq> topspace X' \\<longrightarrow> (closedin X {x. x \\<in> topspace X \\<and> f x \\<in> U} \\<longleftrightarrow> closedin X' U))\"\nproof -\n  have eq: \"(topspace X - {x \\<in> topspace X. f x \\<in> U'}) = {x \\<in> topspace X. f x \\<in> topspace X' \\<and> f x \\<notin> U'}\"\n    if \"f ` topspace X = topspace X'\" \"U' \\<subseteq> topspace X'\" for U'\n      using that by auto\n  have \"(\\<forall>U\\<subseteq>topspace X'. openin X {x \\<in> topspace X. f x \\<in> U} = openin X' U) =\n          (\\<forall>U\\<subseteq>topspace X'. closedin X {x \\<in> topspace X. f x \\<in> U} = closedin X' U)\"\n    if \"f ` topspace X = topspace X'\"\n  proof (rule iffI; intro allI impI subsetI)\n    fix U'\n    assume *[rule_format]: \"\\<forall>U\\<subseteq>topspace X'. openin X {x \\<in> topspace X. f x \\<in> U} = openin X' U\"\n      and U': \"U' \\<subseteq> topspace X'\"\n    show \"closedin X {x \\<in> topspace X. f x \\<in> U'} = closedin X' U'\"\n      using U'  by (auto simp add: closedin_def simp flip: * [of \"topspace X' - U'\"] eq [OF that])\n  next\n    fix U' :: \"'b set\"\n    assume *[rule_format]: \"\\<forall>U\\<subseteq>topspace X'. closedin X {x \\<in> topspace X. f x \\<in> U} = closedin X' U\"\n      and U': \"U' \\<subseteq> topspace X'\"\n    show \"openin X {x \\<in> topspace X. f x \\<in> U'} = openin X' U'\"\n      using U'  by (auto simp add: openin_closedin_eq simp flip: * [of \"topspace X' - U'\"] eq [OF that])\n  qed\n  then show ?thesis\n    unfolding quotient_map_def by force\nqed\n\nlemma continuous_open_imp_quotient_map:\n  assumes \"continuous_map X X' f\" and om: \"open_map X X' f\" and feq: \"f ` (topspace X) = topspace X'\"\n  shows \"quotient_map X X' f\"\nproof -\n  { fix U\n    assume U: \"U \\<subseteq> topspace X'\" and \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n    then have ope: \"openin X' (f ` {x \\<in> topspace X. f x \\<in> U})\"\n      using om unfolding open_map_def by blast\n    then have \"openin X' U\"\n      using U feq by (subst openin_subopen) force\n  }\n  moreover have \"openin X {x \\<in> topspace X. f x \\<in> U}\" if \"U \\<subseteq> topspace X'\" and \"openin X' U\" for U\n    using that assms unfolding continuous_map_def by blast\n  ultimately show ?thesis\n    unfolding quotient_map_def using assms by blast\nqed\n\nlemma continuous_closed_imp_quotient_map:\n  assumes \"continuous_map X X' f\" and om: \"closed_map X X' f\" and feq: \"f ` (topspace X) = topspace X'\"\n  shows \"quotient_map X X' f\"\nproof -\n  have \"f ` {x \\<in> topspace X. f x \\<in> U} = U\" if \"U \\<subseteq> topspace X'\" for U\n    using that feq by auto\n  with assms show ?thesis\n    unfolding quotient_map_closedin closed_map_def continuous_map_closedin by auto\nqed\n\nlemma continuous_open_quotient_map:\n   \"\\<lbrakk>continuous_map X X' f; open_map X X' f\\<rbrakk> \\<Longrightarrow> quotient_map X X' f \\<longleftrightarrow> f ` (topspace X) = topspace X'\"\n  by (meson continuous_open_imp_quotient_map quotient_map_def)\n\nlemma continuous_closed_quotient_map:\n     \"\\<lbrakk>continuous_map X X' f; closed_map X X' f\\<rbrakk> \\<Longrightarrow> quotient_map X X' f \\<longleftrightarrow> f ` (topspace X) = topspace X'\"\n  by (meson continuous_closed_imp_quotient_map quotient_map_def)\n\nlemma injective_quotient_map:\n  assumes \"inj_on f (topspace X)\"\n  shows \"quotient_map X X' f \\<longleftrightarrow>\n         continuous_map X X' f \\<and> open_map X X' f \\<and> closed_map X X' f \\<and> f ` (topspace X) = topspace X'\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  have \"open_map X X' f\"\n  proof (clarsimp simp add: open_map_def)\n    fix U\n    assume \"openin X U\"\n    then have \"U \\<subseteq> topspace X\"\n      by (simp add: openin_subset)\n    moreover have \"{x \\<in> topspace X. f x \\<in> f ` U} = U\"\n      using \\<open>U \\<subseteq> topspace X\\<close> assms inj_onD by fastforce\n    ultimately show \"openin X' (f ` U)\"\n      using L unfolding quotient_map_def\n      by (metis (no_types, lifting) Collect_cong \\<open>openin X U\\<close> image_mono)\n  qed\n  moreover have \"closed_map X X' f\"\n  proof (clarsimp simp add: closed_map_def)\n    fix U\n    assume \"closedin X U\"\n    then have \"U \\<subseteq> topspace X\"\n      by (simp add: closedin_subset)\n    moreover have \"{x \\<in> topspace X. f x \\<in> f ` U} = U\"\n      using \\<open>U \\<subseteq> topspace X\\<close> assms inj_onD by fastforce\n    ultimately show \"closedin X' (f ` U)\"\n      using L unfolding quotient_map_closedin\n      by (metis (no_types, lifting) Collect_cong \\<open>closedin X U\\<close> image_mono)\n  qed\n  ultimately show ?rhs\n    using L by (simp add: quotient_imp_continuous_map quotient_imp_surjective_map)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (simp add: continuous_closed_imp_quotient_map)\nqed\n\nlemma continuous_compose_quotient_map:\n  assumes f: \"quotient_map X X' f\" and g: \"continuous_map X X'' (g \\<circ> f)\"\n  shows \"continuous_map X' X'' g\"\n  unfolding quotient_map_def continuous_map_def\nproof (intro conjI ballI allI impI)\n  show \"\\<And>x'. x' \\<in> topspace X' \\<Longrightarrow> g x' \\<in> topspace X''\"\n    using assms unfolding quotient_map_def\n    by (metis (no_types, hide_lams) continuous_map_image_subset_topspace image_comp image_subset_iff)\nnext\n  fix U'' :: \"'c set\"\n  assume U'': \"openin X'' U''\"\n  have \"f ` topspace X = topspace X'\"\n    by (simp add: f quotient_imp_surjective_map)\n  then have eq: \"{x \\<in> topspace X. f x \\<in> topspace X' \\<and> g (f x) \\<in> U} = {x \\<in> topspace X. g (f x) \\<in> U}\" for U\n    by auto\n  have \"openin X {x \\<in> topspace X. f x \\<in> topspace X' \\<and> g (f x) \\<in> U''}\"\n    unfolding eq using U'' g openin_continuous_map_preimage by fastforce\n  then have *: \"openin X {x \\<in> topspace X. f x \\<in> {x \\<in> topspace X'. g x \\<in> U''}}\"\n    by auto\n  show \"openin X' {x \\<in> topspace X'. g x \\<in> U''}\"\n    using f unfolding quotient_map_def\n    by (metis (no_types) Collect_subset *)\nqed\n\nlemma continuous_compose_quotient_map_eq:\n   \"quotient_map X X' f \\<Longrightarrow> continuous_map X X'' (g \\<circ> f) \\<longleftrightarrow> continuous_map X' X'' g\"\n  using continuous_compose_quotient_map continuous_map_compose quotient_imp_continuous_map by blast\n\nlemma quotient_map_compose_eq:\n   \"quotient_map X X' f \\<Longrightarrow> quotient_map X X'' (g \\<circ> f) \\<longleftrightarrow> quotient_map X' X'' g\"\n  apply safe\n  apply (meson continuous_compose_quotient_map_eq quotient_imp_continuous_map quotient_map_from_composition)\n  by (simp add: quotient_map_compose)\n\nlemma quotient_map_restriction:\n  assumes quo: \"quotient_map X Y f\" and U: \"{x \\<in> topspace X. f x \\<in> V} = U\" and disj: \"openin Y V \\<or> closedin Y V\"\n shows \"quotient_map (subtopology X U) (subtopology Y V) f\"\n  using disj\nproof\n  assume V: \"openin Y V\"\n  with U have sub: \"U \\<subseteq> topspace X\" \"V \\<subseteq> topspace Y\"\n    by (auto simp: openin_subset)\n  have fim: \"f ` topspace X = topspace Y\"\n     and Y: \"\\<And>U. U \\<subseteq> topspace Y \\<Longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U} = openin Y U\"\n    using quo unfolding quotient_map_def by auto\n  have \"openin X U\"\n    using U V Y sub(2) by blast\n  show ?thesis\n    unfolding quotient_map_def\n  proof (intro conjI allI impI)\n    show \"f ` topspace (subtopology X U) = topspace (subtopology Y V)\"\n      using sub U fim by (auto)\n  next\n    fix Y' :: \"'b set\"\n    assume \"Y' \\<subseteq> topspace (subtopology Y V)\"\n    then have \"Y' \\<subseteq> topspace Y\" \"Y' \\<subseteq> V\"\n      by (simp_all)\n    then have eq: \"{x \\<in> topspace X. x \\<in> U \\<and> f x \\<in> Y'} = {x \\<in> topspace X. f x \\<in> Y'}\"\n      using U by blast\n    then show \"openin (subtopology X U) {x \\<in> topspace (subtopology X U). f x \\<in> Y'} = openin (subtopology Y V) Y'\"\n      using U V Y \\<open>openin X U\\<close>  \\<open>Y' \\<subseteq> topspace Y\\<close> \\<open>Y' \\<subseteq> V\\<close>\n      by (simp add: openin_open_subtopology eq) (auto simp: openin_closedin_eq)\n  qed\nnext\n  assume V: \"closedin Y V\"\n  with U have sub: \"U \\<subseteq> topspace X\" \"V \\<subseteq> topspace Y\"\n    by (auto simp: closedin_subset)\n  have fim: \"f ` topspace X = topspace Y\"\n     and Y: \"\\<And>U. U \\<subseteq> topspace Y \\<Longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> U} = closedin Y U\"\n    using quo unfolding quotient_map_closedin by auto\n  have \"closedin X U\"\n    using U V Y sub(2) by blast\n  show ?thesis\n    unfolding quotient_map_closedin\n  proof (intro conjI allI impI)\n    show \"f ` topspace (subtopology X U) = topspace (subtopology Y V)\"\n      using sub U fim by (auto)\n  next\n    fix Y' :: \"'b set\"\n    assume \"Y' \\<subseteq> topspace (subtopology Y V)\"\n    then have \"Y' \\<subseteq> topspace Y\" \"Y' \\<subseteq> V\"\n      by (simp_all)\n    then have eq: \"{x \\<in> topspace X. x \\<in> U \\<and> f x \\<in> Y'} = {x \\<in> topspace X. f x \\<in> Y'}\"\n      using U by blast\n    then show \"closedin (subtopology X U) {x \\<in> topspace (subtopology X U). f x \\<in> Y'} = closedin (subtopology Y V) Y'\"\n      using U V Y \\<open>closedin X U\\<close>  \\<open>Y' \\<subseteq> topspace Y\\<close> \\<open>Y' \\<subseteq> V\\<close>\n      by (simp add: closedin_closed_subtopology eq) (auto simp: closedin_def)\n  qed\nqed\n\nlemma quotient_map_saturated_open:\n     \"quotient_map X Y f \\<longleftrightarrow>\n        continuous_map X Y f \\<and> f ` (topspace X) = topspace Y \\<and>\n        (\\<forall>U. openin X U \\<and> {x \\<in> topspace X. f x \\<in> f ` U} \\<subseteq> U \\<longrightarrow> openin Y (f ` U))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have fim: \"f ` topspace X = topspace Y\"\n    and Y: \"\\<And>U. U \\<subseteq> topspace Y \\<Longrightarrow> openin Y U = openin X {x \\<in> topspace X. f x \\<in> U}\"\n    unfolding quotient_map_def by auto\n  show ?rhs\n  proof (intro conjI allI impI)\n    show \"continuous_map X Y f\"\n      by (simp add: L quotient_imp_continuous_map)\n    show \"f ` topspace X = topspace Y\"\n      by (simp add: fim)\n  next\n    fix U :: \"'a set\"\n    assume U: \"openin X U \\<and> {x \\<in> topspace X. f x \\<in> f ` U} \\<subseteq> U\"\n    then have sub:  \"f ` U \\<subseteq> topspace Y\" and eq: \"{x \\<in> topspace X. f x \\<in> f ` U} = U\"\n      using fim openin_subset by fastforce+\n    show \"openin Y (f ` U)\"\n      by (simp add: sub Y eq U)\n  qed\nnext\n  assume ?rhs\n  then have YX: \"\\<And>U. openin Y U \\<Longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}\"\n       and fim: \"f ` topspace X = topspace Y\"\n       and XY: \"\\<And>U. \\<lbrakk>openin X U; {x \\<in> topspace X. f x \\<in> f ` U} \\<subseteq> U\\<rbrakk> \\<Longrightarrow> openin Y (f ` U)\"\n    by (auto simp: quotient_map_def continuous_map_def)\n  show ?lhs\n  proof (simp add: quotient_map_def fim, intro allI impI iffI)\n    fix U :: \"'b set\"\n    assume \"U \\<subseteq> topspace Y\" and X: \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n    have feq: \"f ` {x \\<in> topspace X. f x \\<in> U} = U\"\n      using \\<open>U \\<subseteq> topspace Y\\<close> fim by auto\n    show \"openin Y U\"\n      using XY [OF X] by (simp add: feq)\n  next\n    fix U :: \"'b set\"\n    assume \"U \\<subseteq> topspace Y\" and Y: \"openin Y U\"\n    show \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n      by (metis YX [OF Y])\n  qed\nqed\n\nsubsection\\<open> Separated Sets\\<close>\n\ndefinition separatedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"separatedin X S T \\<equiv>\n           S \\<subseteq> topspace X \\<and> T \\<subseteq> topspace X \\<and>\n           S \\<inter> X closure_of T = {} \\<and> T \\<inter> X closure_of S = {}\"\n\nlemma separatedin_empty [simp]:\n     \"separatedin X S {} \\<longleftrightarrow> S \\<subseteq> topspace X\"\n     \"separatedin X {} S \\<longleftrightarrow> S \\<subseteq> topspace X\"\n  by (simp_all add: separatedin_def)\n\nlemma separatedin_refl [simp]:\n     \"separatedin X S S \\<longleftrightarrow> S = {}\"\nproof -\n  have \"\\<And>x. \\<lbrakk>separatedin X S S; x \\<in> S\\<rbrakk> \\<Longrightarrow> False\"\n    by (metis all_not_in_conv closure_of_subset inf.orderE separatedin_def)\n  then show ?thesis\n    by auto\nqed\n\nlemma separatedin_sym:\n     \"separatedin X S T \\<longleftrightarrow> separatedin X T S\"\n  by (auto simp: separatedin_def)\n\nlemma separatedin_imp_disjoint:\n     \"separatedin X S T \\<Longrightarrow> disjnt S T\"\n  by (meson closure_of_subset disjnt_def disjnt_subset2 separatedin_def)\n\nlemma separatedin_mono:\n   \"\\<lbrakk>separatedin X S T; S' \\<subseteq> S; T' \\<subseteq> T\\<rbrakk> \\<Longrightarrow> separatedin X S' T'\"\n  unfolding separatedin_def\n  using closure_of_mono by blast\n\nlemma separatedin_open_sets:\n     \"\\<lbrakk>openin X S; openin X T\\<rbrakk> \\<Longrightarrow> separatedin X S T \\<longleftrightarrow> disjnt S T\"\n  unfolding disjnt_def separatedin_def\n  by (auto simp: openin_Int_closure_of_eq_empty openin_subset)\n\nlemma separatedin_closed_sets:\n     \"\\<lbrakk>closedin X S; closedin X T\\<rbrakk> \\<Longrightarrow> separatedin X S T \\<longleftrightarrow> disjnt S T\"\n  unfolding closure_of_eq disjnt_def separatedin_def\n  by (metis closedin_def closure_of_eq inf_commute)\n\nlemma separatedin_subtopology:\n     \"separatedin (subtopology X U) S T \\<longleftrightarrow> S \\<subseteq> U \\<and> T \\<subseteq> U \\<and> separatedin X S T\"\n  apply (simp add: separatedin_def closure_of_subtopology)\n  apply (safe; metis Int_absorb1 inf.assoc inf.orderE insert_disjoint(2) mk_disjoint_insert)\n  done\n\nlemma separatedin_discrete_topology:\n     \"separatedin (discrete_topology U) S T \\<longleftrightarrow> S \\<subseteq> U \\<and> T \\<subseteq> U \\<and> disjnt S T\"\n  by (metis openin_discrete_topology separatedin_def separatedin_open_sets topspace_discrete_topology)\n\nlemma separated_eq_distinguishable:\n   \"separatedin X {x} {y} \\<longleftrightarrow>\n        x \\<in> topspace X \\<and> y \\<in> topspace X \\<and>\n        (\\<exists>U. openin X U \\<and> x \\<in> U \\<and> (y \\<notin> U)) \\<and>\n        (\\<exists>v. openin X v \\<and> y \\<in> v \\<and> (x \\<notin> v))\"\n  by (force simp: separatedin_def closure_of_def)\n\nlemma separatedin_Un [simp]:\n   \"separatedin X S (T \\<union> U) \\<longleftrightarrow> separatedin X S T \\<and> separatedin X S U\"\n   \"separatedin X (S \\<union> T) U \\<longleftrightarrow> separatedin X S U \\<and> separatedin X T U\"\n  by (auto simp: separatedin_def)\n\nlemma separatedin_Union:\n  \"finite \\<F> \\<Longrightarrow> separatedin X S (\\<Union>\\<F>) \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> (\\<forall>T \\<in> \\<F>. separatedin X S T)\"\n  \"finite \\<F> \\<Longrightarrow> separatedin X (\\<Union>\\<F>) S \\<longleftrightarrow> (\\<forall>T \\<in> \\<F>. separatedin X S T) \\<and> S \\<subseteq> topspace X\"\n  by (auto simp: separatedin_def closure_of_Union)\n\nlemma separatedin_openin_diff:\n   \"\\<lbrakk>openin X S; openin X T\\<rbrakk> \\<Longrightarrow> separatedin X (S - T) (T - S)\"\n  unfolding separatedin_def\n  apply (intro conjI)\n  apply (meson Diff_subset openin_subset subset_trans)+\n  using openin_Int_closure_of_eq_empty by fastforce+\n\nlemma separatedin_closedin_diff:\n     \"\\<lbrakk>closedin X S; closedin X T\\<rbrakk> \\<Longrightarrow> separatedin X (S - T) (T - S)\"\n  apply (simp add: separatedin_def Diff_Int_distrib2 closure_of_minimal inf_absorb2)\n  apply (meson Diff_subset closedin_subset subset_trans)\n  done\n\nlemma separation_closedin_Un_gen:\n     \"separatedin X S T \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and> T \\<subseteq> topspace X \\<and> disjnt S T \\<and>\n        closedin (subtopology X (S \\<union> T)) S \\<and>\n        closedin (subtopology X (S \\<union> T)) T\"\n  apply (simp add: separatedin_def closedin_Int_closure_of disjnt_iff)\n  using closure_of_subset apply blast\n  done\n\nlemma separation_openin_Un_gen:\n     \"separatedin X S T \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and> T \\<subseteq> topspace X \\<and> disjnt S T \\<and>\n        openin (subtopology X (S \\<union> T)) S \\<and>\n        openin (subtopology X (S \\<union> T)) T\"\n  unfolding openin_closedin_eq topspace_subtopology separation_closedin_Un_gen disjnt_def\n  by (auto simp: Diff_triv Int_commute Un_Diff inf_absorb1 topspace_def)\n\n\nsubsection\\<open>Homeomorphisms\\<close>\ntext\\<open>(1-way and 2-way versions may be useful in places)\\<close>\n\ndefinition homeomorphic_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where\n \"homeomorphic_map X Y f \\<equiv> quotient_map X Y f \\<and> inj_on f (topspace X)\"\n\ndefinition homeomorphic_maps :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where\n \"homeomorphic_maps X Y f g \\<equiv>\n    continuous_map X Y f \\<and> continuous_map Y X g \\<and>\n     (\\<forall>x \\<in> topspace X. g(f x) = x) \\<and> (\\<forall>y \\<in> topspace Y. f(g y) = y)\"\n\n\nlemma homeomorphic_map_eq:\n   \"\\<lbrakk>homeomorphic_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> homeomorphic_map X Y g\"\n  by (meson homeomorphic_map_def inj_on_cong quotient_map_eq)\n\nlemma homeomorphic_maps_eq:\n     \"\\<lbrakk>homeomorphic_maps X Y f g;\n       \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = f' x; \\<And>y. y \\<in> topspace Y \\<Longrightarrow> g y = g' y\\<rbrakk>\n      \\<Longrightarrow> homeomorphic_maps X Y f' g'\"\n  apply (simp add: homeomorphic_maps_def)\n  by (metis continuous_map_eq continuous_map_eq_image_closure_subset_gen image_subset_iff)\n\nlemma homeomorphic_maps_sym:\n     \"homeomorphic_maps X Y f g \\<longleftrightarrow> homeomorphic_maps Y X g f\"\n  by (auto simp: homeomorphic_maps_def)\n\nlemma homeomorphic_maps_id:\n     \"homeomorphic_maps X Y id id \\<longleftrightarrow> Y = X\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have \"topspace X = topspace Y\"\n    by (auto simp: homeomorphic_maps_def continuous_map_def)\n  with L show ?rhs\n    unfolding homeomorphic_maps_def\n    by (metis topology_finer_continuous_id topology_eq)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding homeomorphic_maps_def by auto\nqed\n\nlemma homeomorphic_map_id [simp]: \"homeomorphic_map X Y id \\<longleftrightarrow> Y = X\"\n       (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have eq: \"topspace X = topspace Y\"\n    by (auto simp: homeomorphic_map_def continuous_map_def quotient_map_def)\n  then have \"\\<And>S. openin X S \\<longrightarrow> openin Y S\"\n    by (meson L homeomorphic_map_def injective_quotient_map topology_finer_open_id)\n  then show ?rhs\n    using L unfolding homeomorphic_map_def\n    by (metis eq quotient_imp_continuous_map topology_eq topology_finer_continuous_id)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding homeomorphic_map_def\n    by (simp add: closed_map_id continuous_closed_imp_quotient_map)\nqed\n\nlemma homeomorphic_map_compose:\n  assumes \"homeomorphic_map X Y f\" \"homeomorphic_map Y X'' g\"\n  shows \"homeomorphic_map X X'' (g \\<circ> f)\"\nproof -\n  have \"inj_on g (f ` topspace X)\"\n    by (metis (no_types) assms homeomorphic_map_def quotient_imp_surjective_map)\n  then show ?thesis\n    using assms by (meson comp_inj_on homeomorphic_map_def quotient_map_compose_eq)\nqed\n\nlemma homeomorphic_maps_compose:\n   \"homeomorphic_maps X Y f h \\<and>\n        homeomorphic_maps Y X'' g k\n        \\<Longrightarrow> homeomorphic_maps X X'' (g \\<circ> f) (h \\<circ> k)\"\n  unfolding homeomorphic_maps_def\n  by (auto simp: continuous_map_compose; simp add: continuous_map_def)\n\nlemma homeomorphic_eq_everything_map:\n   \"homeomorphic_map X Y f \\<longleftrightarrow>\n        continuous_map X Y f \\<and> open_map X Y f \\<and> closed_map X Y f \\<and>\n        f ` (topspace X) = topspace Y \\<and> inj_on f (topspace X)\"\n  unfolding homeomorphic_map_def\n  by (force simp: injective_quotient_map intro: injective_quotient_map)\n\nlemma homeomorphic_imp_continuous_map:\n     \"homeomorphic_map X Y f \\<Longrightarrow> continuous_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_open_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> open_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_closed_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_surjective_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> f ` (topspace X) = topspace Y\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_injective_map:\n    \"homeomorphic_map X Y f \\<Longrightarrow> inj_on f (topspace X)\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma bijective_open_imp_homeomorphic_map:\n   \"\\<lbrakk>continuous_map X Y f; open_map X Y f; f ` (topspace X) = topspace Y; inj_on f (topspace X)\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map X Y f\"\n  by (simp add: homeomorphic_map_def continuous_open_imp_quotient_map)\n\nlemma bijective_closed_imp_homeomorphic_map:\n   \"\\<lbrakk>continuous_map X Y f; closed_map X Y f; f ` (topspace X) = topspace Y; inj_on f (topspace X)\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map X Y f\"\n  by (simp add: continuous_closed_quotient_map homeomorphic_map_def)\n\nlemma open_eq_continuous_inverse_map:\n  assumes X: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y \\<and> g(f x) = x\"\n    and Y: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> g y \\<in> topspace X \\<and> f(g y) = y\"\n  shows \"open_map X Y f \\<longleftrightarrow> continuous_map Y X g\"\nproof -\n  have eq: \"{x \\<in> topspace Y. g x \\<in> U} = f ` U\" if \"openin X U\" for U\n    using openin_subset [OF that] by (force simp: X Y image_iff)\n  show ?thesis\n    by (auto simp: Y open_map_def continuous_map_def eq)\nqed\n\nlemma closed_eq_continuous_inverse_map:\n  assumes X: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y \\<and> g(f x) = x\"\n    and Y: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> g y \\<in> topspace X \\<and> f(g y) = y\"\n  shows \"closed_map X Y f \\<longleftrightarrow> continuous_map Y X g\"\nproof -\n  have eq: \"{x \\<in> topspace Y. g x \\<in> U} = f ` U\" if \"closedin X U\" for U\n    using closedin_subset [OF that] by (force simp: X Y image_iff)\n  show ?thesis\n    by (auto simp: Y closed_map_def continuous_map_closedin eq)\nqed\n\nlemma homeomorphic_maps_map:\n  \"homeomorphic_maps X Y f g \\<longleftrightarrow>\n        homeomorphic_map X Y f \\<and> homeomorphic_map Y X g \\<and>\n        (\\<forall>x \\<in> topspace X. g(f x) = x) \\<and> (\\<forall>y \\<in> topspace Y. f(g y) = y)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have L: \"continuous_map X Y f\" \"continuous_map Y X g\" \"\\<forall>x\\<in>topspace X. g (f x) = x\" \"\\<forall>x'\\<in>topspace Y. f (g x') = x'\"\n    by (auto simp: homeomorphic_maps_def)\n  show ?rhs\n  proof (intro conjI bijective_open_imp_homeomorphic_map L)\n    show \"open_map X Y f\"\n      using L using open_eq_continuous_inverse_map [of concl: X Y f g] by (simp add: continuous_map_def)\n    show \"open_map Y X g\"\n      using L using open_eq_continuous_inverse_map [of concl: Y X g f] by (simp add: continuous_map_def)\n    show \"f ` topspace X = topspace Y\" \"g ` topspace Y = topspace X\"\n      using L by (force simp: continuous_map_closedin)+\n    show \"inj_on f (topspace X)\" \"inj_on g (topspace Y)\"\n      using L unfolding inj_on_def by metis+\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by (auto simp: homeomorphic_maps_def homeomorphic_imp_continuous_map)\nqed\n\nlemma homeomorphic_maps_imp_map:\n    \"homeomorphic_maps X Y f g \\<Longrightarrow> homeomorphic_map X Y f\"\n  using homeomorphic_maps_map by blast\n\nlemma homeomorphic_map_maps:\n     \"homeomorphic_map X Y f \\<longleftrightarrow> (\\<exists>g. homeomorphic_maps X Y f g)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have L: \"continuous_map X Y f\" \"open_map X Y f\" \"closed_map X Y f\"\n    \"f ` (topspace X) = topspace Y\" \"inj_on f (topspace X)\"\n    by (auto simp: homeomorphic_eq_everything_map)\n  have X: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y \\<and> inv_into (topspace X) f (f x) = x\"\n    using L by auto\n  have Y: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> inv_into (topspace X) f y \\<in> topspace X \\<and> f (inv_into (topspace X) f y) = y\"\n    by (simp add: L f_inv_into_f inv_into_into)\n  have \"homeomorphic_maps X Y f (inv_into (topspace X) f)\"\n    unfolding homeomorphic_maps_def\n  proof (intro conjI L)\n    show \"continuous_map Y X (inv_into (topspace X) f)\"\n      by (simp add: L X Y flip: open_eq_continuous_inverse_map [where f=f])\n  next\n    show \"\\<forall>x\\<in>topspace X. inv_into (topspace X) f (f x) = x\"\n         \"\\<forall>y\\<in>topspace Y. f (inv_into (topspace X) f y) = y\"\n      using X Y by auto\n  qed\n  then show ?rhs\n    by metis\nnext\n  assume ?rhs\n  then show ?lhs\n    using homeomorphic_maps_map by blast\nqed\n\nlemma homeomorphic_maps_involution:\n   \"\\<lbrakk>continuous_map X X f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f(f x) = x\\<rbrakk> \\<Longrightarrow> homeomorphic_maps X X f f\"\n  by (auto simp: homeomorphic_maps_def)\n\nlemma homeomorphic_map_involution:\n   \"\\<lbrakk>continuous_map X X f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f(f x) = x\\<rbrakk> \\<Longrightarrow> homeomorphic_map X X f\"\n  using homeomorphic_maps_involution homeomorphic_maps_map by blast\n\nlemma homeomorphic_map_openness:\n  assumes hom: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"openin Y (f ` U) \\<longleftrightarrow> openin X U\"\nproof -\n  obtain g where \"homeomorphic_maps X Y f g\"\n    using assms by (auto simp: homeomorphic_map_maps)\n  then have g: \"homeomorphic_map Y X g\" and gf: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> g(f x) = x\"\n    by (auto simp: homeomorphic_maps_map)\n  then have \"openin X U \\<Longrightarrow> openin Y (f ` U)\"\n    using hom homeomorphic_imp_open_map open_map_def by blast\n  show \"openin Y (f ` U) = openin X U\"\n  proof\n    assume L: \"openin Y (f ` U)\"\n    have \"U = g ` (f ` U)\"\n      using U gf by force\n    then show \"openin X U\"\n      by (metis L homeomorphic_imp_open_map open_map_def g)\n  next\n    assume \"openin X U\"\n    then show \"openin Y (f ` U)\"\n      using hom homeomorphic_imp_open_map open_map_def by blast\n  qed\nqed\n\n\nlemma homeomorphic_map_closedness:\n  assumes hom: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"closedin Y (f ` U) \\<longleftrightarrow> closedin X U\"\nproof -\n  obtain g where \"homeomorphic_maps X Y f g\"\n    using assms by (auto simp: homeomorphic_map_maps)\n  then have g: \"homeomorphic_map Y X g\" and gf: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> g(f x) = x\"\n    by (auto simp: homeomorphic_maps_map)\n  then have \"closedin X U \\<Longrightarrow> closedin Y (f ` U)\"\n    using hom homeomorphic_imp_closed_map closed_map_def by blast\n  show \"closedin Y (f ` U) = closedin X U\"\n  proof\n    assume L: \"closedin Y (f ` U)\"\n    have \"U = g ` (f ` U)\"\n      using U gf by force\n    then show \"closedin X U\"\n      by (metis L homeomorphic_imp_closed_map closed_map_def g)\n  next\n    assume \"closedin X U\"\n    then show \"closedin Y (f ` U)\"\n      using hom homeomorphic_imp_closed_map closed_map_def by blast\n  qed\nqed\n\nlemma homeomorphic_map_openness_eq:\n     \"homeomorphic_map X Y f \\<Longrightarrow> openin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> openin Y (f ` U)\"\n  by (meson homeomorphic_map_openness openin_closedin_eq)\n\nlemma homeomorphic_map_closedness_eq:\n    \"homeomorphic_map X Y f \\<Longrightarrow> closedin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> closedin Y (f ` U)\"\n  by (meson closedin_subset homeomorphic_map_closedness)\n\nlemma all_openin_homeomorphic_image:\n  assumes \"homeomorphic_map X Y f\"\n  shows \"(\\<forall>V. openin Y V \\<longrightarrow> P V) \\<longleftrightarrow> (\\<forall>U. openin X U \\<longrightarrow> P(f ` U))\"  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (meson assms homeomorphic_map_openness_eq)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (metis (no_types, lifting) assms homeomorphic_imp_surjective_map homeomorphic_map_openness openin_subset subset_image_iff)\nqed\n\nlemma all_closedin_homeomorphic_image:\n  assumes \"homeomorphic_map X Y f\"\n  shows \"(\\<forall>V. closedin Y V \\<longrightarrow> P V) \\<longleftrightarrow> (\\<forall>U. closedin X U \\<longrightarrow> P(f ` U))\"  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (meson assms homeomorphic_map_closedness_eq)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (metis (no_types, lifting) assms homeomorphic_imp_surjective_map homeomorphic_map_closedness closedin_subset subset_image_iff)\nqed\n\n\nlemma homeomorphic_map_derived_set_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y derived_set_of (f ` S) = f ` (X derived_set_of S)\"\nproof -\n  have fim: \"f ` (topspace X) = topspace Y\" and inj: \"inj_on f (topspace X)\"\n    using hom by (auto simp: homeomorphic_eq_everything_map)\n  have iff: \"(\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y. y \\<noteq> x \\<and> y \\<in> S \\<and> y \\<in> T)) =\n            (\\<forall>T. T \\<subseteq> topspace Y \\<longrightarrow> f x \\<in> T \\<longrightarrow> openin Y T \\<longrightarrow> (\\<exists>y. y \\<noteq> f x \\<and> y \\<in> f ` S \\<and> y \\<in> T))\"\n    if \"x \\<in> topspace X\" for x\n  proof -\n    have 1: \"(x \\<in> T \\<and> openin X T) = (T \\<subseteq> topspace X \\<and> f x \\<in> f ` T \\<and> openin Y (f ` T))\" for T\n      by (meson hom homeomorphic_map_openness_eq inj inj_on_image_mem_iff that)\n    have 2: \"(\\<exists>y. y \\<noteq> x \\<and> y \\<in> S \\<and> y \\<in> T) = (\\<exists>y. y \\<noteq> f x \\<and> y \\<in> f ` S \\<and> y \\<in> f ` T)\" (is \"?lhs = ?rhs\")\n      if \"T \\<subseteq> topspace X \\<and> f x \\<in> f ` T \\<and> openin Y (f ` T)\" for T\n    proof\n      show \"?lhs \\<Longrightarrow> ?rhs\"\n        by (meson \"1\" imageI inj inj_on_eq_iff inj_on_subset that)\n      show \"?rhs \\<Longrightarrow> ?lhs\"\n        using S inj inj_onD that by fastforce\n    qed\n    show ?thesis\n      apply (simp flip: fim add: all_subset_image)\n      apply (simp flip: imp_conjL)\n      by (intro all_cong1 imp_cong 1 2)\n  qed\n  have *: \"\\<lbrakk>T = f ` S; \\<And>x. x \\<in> S \\<Longrightarrow> P x \\<longleftrightarrow> Q(f x)\\<rbrakk> \\<Longrightarrow> {y. y \\<in> T \\<and> Q y} = f ` {x \\<in> S. P x}\" for T S P Q\n    by auto\n  show ?thesis\n    unfolding derived_set_of_def\n    apply (rule *)\n    using fim apply blast\n    using iff openin_subset by force\nqed\n\n\nlemma homeomorphic_map_closure_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y closure_of (f ` S) = f ` (X closure_of S)\"\n  unfolding closure_of\n  using homeomorphic_imp_surjective_map [OF hom] S\n  by (auto simp: in_derived_set_of homeomorphic_map_derived_set_of [OF assms])\n\nlemma homeomorphic_map_interior_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y interior_of (f ` S) = f ` (X interior_of S)\"\nproof -\n  { fix y\n    assume \"y \\<in> topspace Y\" and \"y \\<notin> Y closure_of (topspace Y - f ` S)\"\n    then have \"y \\<in> f ` (topspace X - X closure_of (topspace X - S))\"\n      using homeomorphic_eq_everything_map [THEN iffD1, OF hom] homeomorphic_map_closure_of [OF hom]\n      by (metis DiffI Diff_subset S closure_of_subset_topspace inj_on_image_set_diff) }\n  moreover\n  { fix x\n    assume \"x \\<in> topspace X\"\n    then have \"f x \\<in> topspace Y\"\n      using hom homeomorphic_imp_surjective_map by blast }\n  moreover\n  { fix x\n    assume \"x \\<in> topspace X\" and \"x \\<notin> X closure_of (topspace X - S)\" and \"f x \\<in> Y closure_of (topspace Y - f ` S)\"\n    then have \"False\"\n      using homeomorphic_map_closure_of [OF hom] hom\n      unfolding homeomorphic_eq_everything_map\n      by (metis Diff_subset S closure_of_subset_topspace inj_on_image_mem_iff inj_on_image_set_diff)\n  }\n  ultimately  show ?thesis\n    by (auto simp: interior_of_closure_of)\nqed\n\nlemma homeomorphic_map_frontier_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y frontier_of (f ` S) = f ` (X frontier_of S)\"\n  unfolding frontier_of_def\nproof (intro equalityI subsetI DiffI)\n  fix y\n  assume \"y \\<in> Y closure_of f ` S - Y interior_of f ` S\"\n  then show \"y \\<in> f ` (X closure_of S - X interior_of S)\"\n    using S hom homeomorphic_map_closure_of homeomorphic_map_interior_of by fastforce\nnext\n  fix y\n  assume \"y \\<in> f ` (X closure_of S - X interior_of S)\"\n  then show \"y \\<in> Y closure_of f ` S\"\n    using S hom homeomorphic_map_closure_of by fastforce\nnext\n  fix x\n  assume \"x \\<in> f ` (X closure_of S - X interior_of S)\"\n  then obtain y where y: \"x = f y\" \"y \\<in> X closure_of S\" \"y \\<notin> X interior_of S\"\n    by blast\n  then have \"y \\<in> topspace X\"\n    by (simp add: in_closure_of)\n  then have \"f y \\<notin> f ` (X interior_of S)\"\n    by (meson hom homeomorphic_map_def inj_on_image_mem_iff interior_of_subset_topspace y(3))\n  then show \"x \\<notin> Y interior_of f ` S\"\n    using S hom homeomorphic_map_interior_of y(1) by blast\nqed\n\nlemma homeomorphic_maps_subtopologies:\n   \"\\<lbrakk>homeomorphic_maps X Y f g;  f ` (topspace X \\<inter> S) = topspace Y \\<inter> T\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_maps (subtopology X S) (subtopology Y T) f g\"\n  unfolding homeomorphic_maps_def\n  by (force simp: continuous_map_from_subtopology continuous_map_in_subtopology)\n\nlemma homeomorphic_maps_subtopologies_alt:\n     \"\\<lbrakk>homeomorphic_maps X Y f g; f ` (topspace X \\<inter> S) \\<subseteq> T; g ` (topspace Y \\<inter> T) \\<subseteq> S\\<rbrakk>\n      \\<Longrightarrow> homeomorphic_maps (subtopology X S) (subtopology Y T) f g\"\n  unfolding homeomorphic_maps_def\n  by (force simp: continuous_map_from_subtopology continuous_map_in_subtopology)\n\nlemma homeomorphic_map_subtopologies:\n   \"\\<lbrakk>homeomorphic_map X Y f; f ` (topspace X \\<inter> S) = topspace Y \\<inter> T\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map (subtopology X S) (subtopology Y T) f\"\n  by (meson homeomorphic_map_maps homeomorphic_maps_subtopologies)\n\nlemma homeomorphic_map_subtopologies_alt:\n   \"\\<lbrakk>homeomorphic_map X Y f;\n     \\<And>x. \\<lbrakk>x \\<in> topspace X; f x \\<in> topspace Y\\<rbrakk> \\<Longrightarrow> f x \\<in> T \\<longleftrightarrow> x \\<in> S\\<rbrakk>\n    \\<Longrightarrow> homeomorphic_map (subtopology X S) (subtopology Y T) f\"\n  unfolding homeomorphic_map_maps\n  apply (erule ex_forward)\n  apply (rule homeomorphic_maps_subtopologies)\n  apply (auto simp: homeomorphic_maps_def continuous_map_def)\n  by (metis IntI image_iff)\n\n\nsubsection\\<open>Relation of homeomorphism between topological spaces\\<close>\n\ndefinition homeomorphic_space (infixr \"homeomorphic'_space\" 50)\n  where \"X homeomorphic_space Y \\<equiv> \\<exists>f g. homeomorphic_maps X Y f g\"\n\nlemma homeomorphic_space_refl: \"X homeomorphic_space X\"\n  by (meson homeomorphic_maps_id homeomorphic_space_def)\n\nlemma homeomorphic_space_sym:\n   \"X homeomorphic_space Y \\<longleftrightarrow> Y homeomorphic_space X\"\n  unfolding homeomorphic_space_def by (metis homeomorphic_maps_sym)\n\nlemma homeomorphic_space_trans [trans]:\n     \"\\<lbrakk>X1 homeomorphic_space X2; X2 homeomorphic_space X3\\<rbrakk> \\<Longrightarrow> X1 homeomorphic_space X3\"\n  unfolding homeomorphic_space_def by (metis homeomorphic_maps_compose)\n\nlemma homeomorphic_space:\n     \"X homeomorphic_space Y \\<longleftrightarrow> (\\<exists>f. homeomorphic_map X Y f)\"\n  by (simp add: homeomorphic_map_maps homeomorphic_space_def)\n\nlemma homeomorphic_maps_imp_homeomorphic_space:\n     \"homeomorphic_maps X Y f g \\<Longrightarrow> X homeomorphic_space Y\"\n  unfolding homeomorphic_space_def by metis\n\nlemma homeomorphic_map_imp_homeomorphic_space:\n     \"homeomorphic_map X Y f \\<Longrightarrow> X homeomorphic_space Y\"\n  unfolding homeomorphic_map_maps\n  using homeomorphic_space_def by blast\n\nlemma homeomorphic_empty_space:\n     \"X homeomorphic_space Y \\<Longrightarrow> topspace X = {} \\<longleftrightarrow> topspace Y = {}\"\n  by (metis homeomorphic_imp_surjective_map homeomorphic_space image_is_empty)\n\nlemma homeomorphic_empty_space_eq:\n  assumes \"topspace X = {}\"\n    shows \"X homeomorphic_space Y \\<longleftrightarrow> topspace Y = {}\"\nproof -\n  have \"\\<forall>f t. continuous_map X (t::'b topology) f\"\n    using assms continuous_map_on_empty by blast\n  then show ?thesis\n    by (metis (no_types) assms continuous_map_on_empty empty_iff homeomorphic_empty_space homeomorphic_maps_def homeomorphic_space_def)\nqed\n\nsubsection\\<open>Connected topological spaces\\<close>\n\ndefinition connected_space :: \"'a topology \\<Rightarrow> bool\" where\n  \"connected_space X \\<equiv>\n        \\<not>(\\<exists>E1 E2. openin X E1 \\<and> openin X E2 \\<and>\n                  topspace X \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n\ndefinition connectedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"connectedin X S \\<equiv> S \\<subseteq> topspace X \\<and> connected_space (subtopology X S)\"\n\nlemma connected_spaceD:\n  \"\\<lbrakk>connected_space X;\n    openin X U; openin X V; topspace X \\<subseteq> U \\<union> V; U \\<inter> V = {}; U \\<noteq> {}; V \\<noteq> {}\\<rbrakk> \\<Longrightarrow> False\"\n  by (auto simp: connected_space_def)\n\nlemma connectedin_subset_topspace: \"connectedin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n  by (simp add: connectedin_def)\n\nlemma connectedin_topspace:\n     \"connectedin X (topspace X) \\<longleftrightarrow> connected_space X\"\n  by (simp add: connectedin_def)\n\nlemma connected_space_subtopology:\n     \"connectedin X S \\<Longrightarrow> connected_space (subtopology X S)\"\n  by (simp add: connectedin_def)\n\nlemma connectedin_subtopology:\n     \"connectedin (subtopology X S) T \\<longleftrightarrow> connectedin X T \\<and> T \\<subseteq> S\"\n  by (force simp: connectedin_def subtopology_subtopology inf_absorb2)\n\nlemma connected_space_eq:\n     \"connected_space X \\<longleftrightarrow>\n      (\\<nexists>E1 E2. openin X E1 \\<and> openin X E2 \\<and> E1 \\<union> E2 = topspace X \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  unfolding connected_space_def\n  by (metis openin_Un openin_subset subset_antisym)\n\nlemma connected_space_closedin:\n     \"connected_space X \\<longleftrightarrow>\n      (\\<nexists>E1 E2. closedin X E1 \\<and> closedin X E2 \\<and> topspace X \\<subseteq> E1 \\<union> E2 \\<and>\n               E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have L: \"\\<And>E1 E2. \\<lbrakk>openin X E1; E1 \\<inter> E2 = {}; topspace X \\<subseteq> E1 \\<union> E2; openin X E2\\<rbrakk> \\<Longrightarrow> E1 = {} \\<or> E2 = {}\"\n    by (simp add: connected_space_def)\n  show ?rhs\n    unfolding connected_space_def\n  proof clarify\n    fix E1 E2\n    assume \"closedin X E1\" and \"closedin X E2\" and \"topspace X \\<subseteq> E1 \\<union> E2\" and \"E1 \\<inter> E2 = {}\"\n      and \"E1 \\<noteq> {}\" and \"E2 \\<noteq> {}\"\n    have \"E1 \\<union> E2 = topspace X\"\n      by (meson Un_subset_iff \\<open>closedin X E1\\<close> \\<open>closedin X E2\\<close> \\<open>topspace X \\<subseteq> E1 \\<union> E2\\<close> closedin_def subset_antisym)\n    then have \"topspace X - E2 = E1\"\n      using \\<open>E1 \\<inter> E2 = {}\\<close> by fastforce\n    then have \"topspace X = E1\"\n      using \\<open>E1 \\<noteq> {}\\<close> L \\<open>closedin X E1\\<close> \\<open>closedin X E2\\<close> by blast\n    then show \"False\"\n      using \\<open>E1 \\<inter> E2 = {}\\<close> \\<open>E1 \\<union> E2 = topspace X\\<close> \\<open>E2 \\<noteq> {}\\<close> by blast\n  qed\nnext\n  assume R: ?rhs\n  show ?lhs\n    unfolding connected_space_def\n  proof clarify\n    fix E1 E2\n    assume \"openin X E1\" and \"openin X E2\" and \"topspace X \\<subseteq> E1 \\<union> E2\" and \"E1 \\<inter> E2 = {}\"\n      and \"E1 \\<noteq> {}\" and \"E2 \\<noteq> {}\"\n    have \"E1 \\<union> E2 = topspace X\"\n      by (meson Un_subset_iff \\<open>openin X E1\\<close> \\<open>openin X E2\\<close> \\<open>topspace X \\<subseteq> E1 \\<union> E2\\<close> openin_closedin_eq subset_antisym)\n    then have \"topspace X - E2 = E1\"\n      using \\<open>E1 \\<inter> E2 = {}\\<close> by fastforce\n    then have \"topspace X = E1\"\n      using \\<open>E1 \\<noteq> {}\\<close> R \\<open>openin X E1\\<close> \\<open>openin X E2\\<close> by blast\n    then show \"False\"\n      using \\<open>E1 \\<inter> E2 = {}\\<close> \\<open>E1 \\<union> E2 = topspace X\\<close> \\<open>E2 \\<noteq> {}\\<close> by blast\n  qed\nqed\n\nlemma connected_space_closedin_eq:\n     \"connected_space X \\<longleftrightarrow>\n       (\\<nexists>E1 E2. closedin X E1 \\<and> closedin X E2 \\<and>\n                E1 \\<union> E2 = topspace X \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  apply (simp add: connected_space_closedin)\n  apply (intro all_cong)\n  using closedin_subset apply blast\n  done\n\nlemma connected_space_clopen_in:\n     \"connected_space X \\<longleftrightarrow>\n        (\\<forall>T. openin X T \\<and> closedin X T \\<longrightarrow> T = {} \\<or> T = topspace X)\"\nproof -\n  have eq: \"openin X E1 \\<and> openin X E2 \\<and> E1 \\<union> E2 = topspace X \\<and> E1 \\<inter> E2 = {} \\<and> P\n        \\<longleftrightarrow> E2 = topspace X - E1 \\<and> openin X E1 \\<and> openin X E2 \\<and> P\" for E1 E2 P\n    using openin_subset by blast\n  show ?thesis\n    unfolding connected_space_eq eq closedin_def\n    by (auto simp: openin_closedin_eq)\nqed\n\nlemma connectedin:\n     \"connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n         (\\<nexists>E1 E2.\n             openin X E1 \\<and> openin X E2 \\<and>\n             S \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 \\<inter> S = {} \\<and> E1 \\<inter> S \\<noteq> {} \\<and> E2 \\<inter> S \\<noteq> {})\"\nproof -\n  have *: \"(\\<exists>E1:: 'a set. \\<exists>E2:: 'a set. (\\<exists>T1:: 'a set. P1 T1 \\<and> E1 = f1 T1) \\<and> (\\<exists>T2:: 'a set. P2 T2 \\<and> E2 = f2 T2) \\<and>\n             R E1 E2) \\<longleftrightarrow> (\\<exists>T1 T2. P1 T1 \\<and> P2 T2 \\<and> R(f1 T1) (f2 T2))\" for P1 f1 P2 f2 R\n    by auto\n  show ?thesis\n    unfolding connectedin_def connected_space_def openin_subtopology topspace_subtopology Not_eq_iff *\n    apply (intro conj_cong arg_cong [where f=Not] ex_cong1 refl)\n    apply (blast elim: dest!: openin_subset)+\n    done\nqed\n\nlemma connectedin_iff_connected [simp]: \"connectedin euclidean S \\<longleftrightarrow> connected S\"\n  by (simp add: connected_def connectedin)\n\nlemma connectedin_closedin:\n   \"connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n        \\<not>(\\<exists>E1 E2. closedin X E1 \\<and> closedin X E2 \\<and>\n                  S \\<subseteq> (E1 \\<union> E2) \\<and>\n                  (E1 \\<inter> E2 \\<inter> S = {}) \\<and>\n                  \\<not>(E1 \\<inter> S = {}) \\<and> \\<not>(E2 \\<inter> S = {}))\"\nproof -\n  have *: \"(\\<exists>E1:: 'a set. \\<exists>E2:: 'a set. (\\<exists>T1:: 'a set. P1 T1 \\<and> E1 = f1 T1) \\<and> (\\<exists>T2:: 'a set. P2 T2 \\<and> E2 = f2 T2) \\<and>\n             R E1 E2) \\<longleftrightarrow> (\\<exists>T1 T2. P1 T1 \\<and> P2 T2 \\<and> R(f1 T1) (f2 T2))\" for P1 f1 P2 f2 R\n    by auto\n  show ?thesis\n    unfolding connectedin_def connected_space_closedin closedin_subtopology topspace_subtopology Not_eq_iff *\n    apply (intro conj_cong arg_cong [where f=Not] ex_cong1 refl)\n    apply (blast elim: dest!: openin_subset)+\n    done\nqed\n\nlemma connectedin_empty [simp]: \"connectedin X {}\"\n  by (simp add: connectedin)\n\nlemma connected_space_topspace_empty:\n     \"topspace X = {} \\<Longrightarrow> connected_space X\"\n  using connectedin_topspace by fastforce\n\nlemma connectedin_sing [simp]: \"connectedin X {a} \\<longleftrightarrow> a \\<in> topspace X\"\n  by (simp add: connectedin)\n\nlemma connectedin_absolute [simp]:\n  \"connectedin (subtopology X S) S \\<longleftrightarrow> connectedin X S\"\n  apply (simp only: connectedin_def topspace_subtopology subtopology_subtopology)\n  apply (intro conj_cong imp_cong arg_cong [where f=Not] all_cong1 ex_cong1 refl)\n  by auto\n\nlemma connectedin_Union:\n  assumes \\<U>: \"\\<And>S. S \\<in> \\<U> \\<Longrightarrow> connectedin X S\" and ne: \"\\<Inter>\\<U> \\<noteq> {}\"\n  shows \"connectedin X (\\<Union>\\<U>)\"\nproof -\n  have \"\\<Union>\\<U> \\<subseteq> topspace X\"\n    using \\<U> by (simp add: Union_least connectedin_def)\n  moreover have False\n    if \"openin X E1\" \"openin X E2\" and cover: \"\\<Union>\\<U> \\<subseteq> E1 \\<union> E2\" and disj: \"E1 \\<inter> E2 \\<inter> \\<Union>\\<U> = {}\"\n       and overlap1: \"E1 \\<inter> \\<Union>\\<U> \\<noteq> {}\" and overlap2: \"E2 \\<inter> \\<Union>\\<U> \\<noteq> {}\"\n      for E1 E2\n  proof -\n    have disjS: \"E1 \\<inter> E2 \\<inter> S = {}\" if \"S \\<in> \\<U>\" for S\n      using Diff_triv that disj by auto\n    have coverS: \"S \\<subseteq> E1 \\<union> E2\" if \"S \\<in> \\<U>\" for S\n      using that cover by blast\n    have \"\\<U> \\<noteq> {}\"\n      using overlap1 by blast\n    obtain a where a: \"\\<And>U. U \\<in> \\<U> \\<Longrightarrow> a \\<in> U\"\n      using ne by force\n    with \\<open>\\<U> \\<noteq> {}\\<close> have \"a \\<in> \\<Union>\\<U>\"\n      by blast\n    then consider \"a \\<in> E1\" | \"a \\<in> E2\"\n      using \\<open>\\<Union>\\<U> \\<subseteq> E1 \\<union> E2\\<close> by auto\n    then show False\n    proof cases\n      case 1\n      then obtain b S where \"b \\<in> E2\" \"b \\<in> S\" \"S \\<in> \\<U>\"\n        using overlap2 by blast\n      then show ?thesis\n        using \"1\" \\<open>openin X E1\\<close> \\<open>openin X E2\\<close> disjS coverS a [OF \\<open>S \\<in> \\<U>\\<close>]  \\<U>[OF \\<open>S \\<in> \\<U>\\<close>]\n        unfolding connectedin\n        by (meson disjoint_iff_not_equal)\n    next\n      case 2\n      then obtain b S where \"b \\<in> E1\" \"b \\<in> S\" \"S \\<in> \\<U>\"\n        using overlap1 by blast\n      then show ?thesis\n        using \"2\" \\<open>openin X E1\\<close> \\<open>openin X E2\\<close> disjS coverS a [OF \\<open>S \\<in> \\<U>\\<close>]  \\<U>[OF \\<open>S \\<in> \\<U>\\<close>]\n        unfolding connectedin\n        by (meson disjoint_iff_not_equal)\n    qed\n  qed\n  ultimately show ?thesis\n    unfolding connectedin by blast\nqed\n\nlemma connectedin_Un:\n     \"\\<lbrakk>connectedin X S; connectedin X T; S \\<inter> T \\<noteq> {}\\<rbrakk> \\<Longrightarrow> connectedin X (S \\<union> T)\"\n  using connectedin_Union [of \"{S,T}\"] by auto\n\nlemma connected_space_subconnected:\n  \"connected_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. \\<exists>S. connectedin X S \\<and> x \\<in> S \\<and> y \\<in> S)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    using connectedin_topspace by blast\nnext\n  assume R [rule_format]: ?rhs\n  have False if \"openin X U\" \"openin X V\" and disj: \"U \\<inter> V = {}\" and cover: \"topspace X \\<subseteq> U \\<union> V\"\n    and \"U \\<noteq> {}\" \"V \\<noteq> {}\" for U V\n  proof -\n    obtain u v where \"u \\<in> U\" \"v \\<in> V\"\n      using \\<open>U \\<noteq> {}\\<close> \\<open>V \\<noteq> {}\\<close> by auto\n    then obtain T where \"u \\<in> T\" \"v \\<in> T\" and T: \"connectedin X T\"\n      using R [of u v] that\n      by (meson \\<open>openin X U\\<close> \\<open>openin X V\\<close> subsetD openin_subset)\n    then show False\n      using that unfolding connectedin\n      by (metis IntI \\<open>u \\<in> U\\<close> \\<open>v \\<in> V\\<close> empty_iff inf_bot_left subset_trans)\n  qed\n  then show ?lhs\n    by (auto simp: connected_space_def)\nqed\n\nlemma connectedin_intermediate_closure_of:\n  assumes \"connectedin X S\" \"S \\<subseteq> T\" \"T \\<subseteq> X closure_of S\"\n  shows \"connectedin X T\"\nproof -\n  have S: \"S \\<subseteq> topspace X\"and T: \"T \\<subseteq> topspace X\"\n    using assms by (meson closure_of_subset_topspace dual_order.trans)+\n  show ?thesis\n  using assms\n  apply (simp add: connectedin closure_of_subset_topspace S T)\n  apply (elim all_forward imp_forward2 asm_rl)\n  apply (blast dest: openin_Int_closure_of_eq_empty [of X _ S])+\n  done\nqed\n\nlemma connectedin_closure_of:\n     \"connectedin X S \\<Longrightarrow> connectedin X (X closure_of S)\"\n  by (meson closure_of_subset connectedin_def connectedin_intermediate_closure_of subset_refl)\n\nlemma connectedin_separation:\n  \"connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n        (\\<nexists>C1 C2. C1 \\<union> C2 = S \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> C1 \\<inter> X closure_of C2 = {} \\<and> C2 \\<inter> X closure_of C1 = {})\" (is \"?lhs = ?rhs\")\n  unfolding connectedin_def connected_space_closedin_eq closedin_Int_closure_of topspace_subtopology\n  apply (intro conj_cong refl arg_cong [where f=Not])\n  apply (intro ex_cong1 iffI, blast)\n  using closure_of_subset_Int by force\n\nlemma connectedin_eq_not_separated:\n   \"connectedin X S \\<longleftrightarrow>\n         S \\<subseteq> topspace X \\<and>\n         (\\<nexists>C1 C2. C1 \\<union> C2 = S \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\n  apply (simp add: separatedin_def connectedin_separation)\n  apply (intro conj_cong all_cong1 refl, blast)\n  done\n\nlemma connectedin_eq_not_separated_subset:\n  \"connectedin X S \\<longleftrightarrow>\n      S \\<subseteq> topspace X \\<and> (\\<nexists>C1 C2. S \\<subseteq> C1 \\<union> C2 \\<and> S \\<inter> C1 \\<noteq> {} \\<and> S \\<inter> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\nproof -\n  have *: \"\\<forall>C1 C2. S \\<subseteq> C1 \\<union> C2 \\<longrightarrow> S \\<inter> C1 = {} \\<or> S \\<inter> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n    if \"\\<And>C1 C2. C1 \\<union> C2 = S \\<longrightarrow> C1 = {} \\<or> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n  proof (intro allI)\n    fix C1 C2\n    show \"S \\<subseteq> C1 \\<union> C2 \\<longrightarrow> S \\<inter> C1 = {} \\<or> S \\<inter> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n      using that [of \"S \\<inter> C1\" \"S \\<inter> C2\"]\n      by (auto simp: separatedin_mono)\n  qed\n  show ?thesis\n    apply (simp add: connectedin_eq_not_separated)\n    apply (intro conj_cong refl iffI *)\n    apply (blast elim!: all_forward)+\n    done\nqed\n\nlemma connected_space_eq_not_separated:\n     \"connected_space X \\<longleftrightarrow>\n      (\\<nexists>C1 C2. C1 \\<union> C2 = topspace X \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\n  by (simp add: connectedin_eq_not_separated flip: connectedin_topspace)\n\nlemma connected_space_eq_not_separated_subset:\n  \"connected_space X \\<longleftrightarrow>\n    (\\<nexists>C1 C2. topspace X \\<subseteq> C1 \\<union> C2 \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\n  apply (simp add: connected_space_eq_not_separated)\n  apply (intro all_cong1)\n  by (metis Un_absorb dual_order.antisym separatedin_def subset_refl sup_mono)\n\nlemma connectedin_subset_separated_union:\n     \"\\<lbrakk>connectedin X C; separatedin X S T; C \\<subseteq> S \\<union> T\\<rbrakk> \\<Longrightarrow> C \\<subseteq> S \\<or> C \\<subseteq> T\"\n  unfolding connectedin_eq_not_separated_subset  by blast\n\nlemma connectedin_nonseparated_union:\n   \"\\<lbrakk>connectedin X S; connectedin X T; \\<not>separatedin X S T\\<rbrakk> \\<Longrightarrow> connectedin X (S \\<union> T)\"\n  apply (simp add: connectedin_eq_not_separated_subset, auto)\n    apply (metis (no_types, hide_lams) Diff_subset_conv Diff_triv disjoint_iff_not_equal separatedin_mono sup_commute)\n  apply (metis (no_types, hide_lams) Diff_subset_conv Diff_triv disjoint_iff_not_equal separatedin_mono separatedin_sym sup_commute)\n  by (meson disjoint_iff_not_equal)\n\nlemma connected_space_closures:\n     \"connected_space X \\<longleftrightarrow>\n        (\\<nexists>e1 e2. e1 \\<union> e2 = topspace X \\<and> X closure_of e1 \\<inter> X closure_of e2 = {} \\<and> e1 \\<noteq> {} \\<and> e2 \\<noteq> {})\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding connected_space_closedin_eq\n    by (metis Un_upper1 Un_upper2 closedin_closure_of closure_of_Un closure_of_eq_empty closure_of_topspace)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding connected_space_closedin_eq\n    by (metis closure_of_eq)\nqed\n\nlemma connectedin_inter_frontier_of:\n  assumes \"connectedin X S\" \"S \\<inter> T \\<noteq> {}\" \"S - T \\<noteq> {}\"\n  shows \"S \\<inter> X frontier_of T \\<noteq> {}\"\nproof -\n  have \"S \\<subseteq> topspace X\" and *:\n    \"\\<And>E1 E2. openin X E1 \\<longrightarrow> openin X E2 \\<longrightarrow> E1 \\<inter> E2 \\<inter> S = {} \\<longrightarrow> S \\<subseteq> E1 \\<union> E2 \\<longrightarrow> E1 \\<inter> S = {} \\<or> E2 \\<inter> S = {}\"\n    using \\<open>connectedin X S\\<close> by (auto simp: connectedin)\n  have \"S - (topspace X \\<inter> T) \\<noteq> {}\"\n    using assms(3) by blast\n  moreover\n  have \"S \\<inter> topspace X \\<inter> T \\<noteq> {}\"\n    using assms(1) assms(2) connectedin by fastforce\n  moreover\n  have False if \"S \\<inter> T \\<noteq> {}\" \"S - T \\<noteq> {}\" \"T \\<subseteq> topspace X\" \"S \\<inter> X frontier_of T = {}\" for T\n  proof -\n    have null: \"S \\<inter> (X closure_of T - X interior_of T) = {}\"\n      using that unfolding frontier_of_def by blast\n    have 1: \"X interior_of T \\<inter> (topspace X - X closure_of T) \\<inter> S = {}\"\n      by (metis Diff_disjoint inf_bot_left interior_of_Int interior_of_complement interior_of_empty)\n    have 2: \"S \\<subseteq> X interior_of T \\<union> (topspace X - X closure_of T)\"\n      using that \\<open>S \\<subseteq> topspace X\\<close> null by auto\n    have 3: \"S \\<inter> X interior_of T \\<noteq> {}\"\n      using closure_of_subset that(1) that(3) null by fastforce\n    show ?thesis\n      using null \\<open>S \\<subseteq> topspace X\\<close> that * [of \"X interior_of T\" \"topspace X - X closure_of T\"]\n      apply (clarsimp simp add: openin_diff 1 2)\n      apply (simp add: Int_commute Diff_Int_distrib 3)\n      by (metis Int_absorb2 contra_subsetD interior_of_subset)\n  qed\n  ultimately show ?thesis\n    by (metis Int_lower1 frontier_of_restrict inf_assoc)\nqed\n\nlemma connectedin_continuous_map_image:\n  assumes f: \"continuous_map X Y f\" and \"connectedin X S\"\n  shows \"connectedin Y (f ` S)\"\nproof -\n  have \"S \\<subseteq> topspace X\" and *:\n    \"\\<And>E1 E2. openin X E1 \\<longrightarrow> openin X E2 \\<longrightarrow> E1 \\<inter> E2 \\<inter> S = {} \\<longrightarrow> S \\<subseteq> E1 \\<union> E2 \\<longrightarrow> E1 \\<inter> S = {} \\<or> E2 \\<inter> S = {}\"\n    using \\<open>connectedin X S\\<close> by (auto simp: connectedin)\n  show ?thesis\n    unfolding connectedin connected_space_def\n  proof (intro conjI notI; clarify)\n    show \"f x \\<in> topspace Y\" if  \"x \\<in> S\" for x\n      using \\<open>S \\<subseteq> topspace X\\<close> continuous_map_image_subset_topspace f that by blast\n  next\n    fix U V\n    let ?U = \"{x \\<in> topspace X. f x \\<in> U}\"\n    let ?V = \"{x \\<in> topspace X. f x \\<in> V}\"\n    assume UV: \"openin Y U\" \"openin Y V\" \"f ` S \\<subseteq> U \\<union> V\" \"U \\<inter> V \\<inter> f ` S = {}\" \"U \\<inter> f ` S \\<noteq> {}\" \"V \\<inter> f ` S \\<noteq> {}\"\n    then have 1: \"?U \\<inter> ?V \\<inter> S = {}\"\n      by auto\n    have 2: \"openin X ?U\" \"openin X ?V\"\n      using \\<open>openin Y U\\<close> \\<open>openin Y V\\<close> continuous_map f by fastforce+\n    show \"False\"\n      using  * [of ?U ?V] UV \\<open>S \\<subseteq> topspace X\\<close>\n      by (auto simp: 1 2)\n  qed\nqed\n\nlemma homeomorphic_connected_space:\n     \"X homeomorphic_space Y \\<Longrightarrow> connected_space X \\<longleftrightarrow> connected_space Y\"\n  unfolding homeomorphic_space_def homeomorphic_maps_def\n  apply safe\n  apply (metis connectedin_continuous_map_image connected_space_subconnected continuous_map_image_subset_topspace image_eqI image_subset_iff)\n  by (metis (no_types, hide_lams) connectedin_continuous_map_image connectedin_topspace continuous_map_def continuous_map_image_subset_topspace imageI set_eq_subset subsetI)\n\nlemma homeomorphic_map_connectedness:\n  assumes f: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"connectedin Y (f ` U) \\<longleftrightarrow> connectedin X U\"\nproof -\n  have 1: \"f ` U \\<subseteq> topspace Y \\<longleftrightarrow> U \\<subseteq> topspace X\"\n    using U f homeomorphic_imp_surjective_map by blast\n  moreover have \"connected_space (subtopology Y (f ` U)) \\<longleftrightarrow> connected_space (subtopology X U)\"\n  proof (rule homeomorphic_connected_space)\n    have \"f ` U \\<subseteq> topspace Y\"\n      by (simp add: U 1)\n    then have \"topspace Y \\<inter> f ` U = f ` U\"\n      by (simp add: subset_antisym)\n    then show \"subtopology Y (f ` U) homeomorphic_space subtopology X U\"\n      by (metis (no_types) Int_subset_iff U f homeomorphic_map_imp_homeomorphic_space homeomorphic_map_subtopologies homeomorphic_space_sym subset_antisym subset_refl)\n  qed\n  ultimately show ?thesis\n    by (auto simp: connectedin_def)\nqed\n\nlemma homeomorphic_map_connectedness_eq:\n   \"homeomorphic_map X Y f\n        \\<Longrightarrow> connectedin X U \\<longleftrightarrow>\n             U \\<subseteq> topspace X \\<and> connectedin Y (f ` U)\"\n  using homeomorphic_map_connectedness connectedin_subset_topspace by metis\n\nlemma connectedin_discrete_topology:\n   \"connectedin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U \\<and> (\\<exists>a. S \\<subseteq> {a})\"\nproof (cases \"S \\<subseteq> U\")\n  case True\n  show ?thesis\n  proof (cases \"S = {}\")\n    case False\n    moreover have \"connectedin (discrete_topology U) S \\<longleftrightarrow> (\\<exists>a. S = {a})\"\n      apply safe\n      using False connectedin_inter_frontier_of insert_Diff apply fastforce\n      using True by auto\n    ultimately show ?thesis\n      by auto\n  qed simp\nnext\n  case False\n  then show ?thesis\n    by (simp add: connectedin_def)\nqed\n\nlemma connected_space_discrete_topology:\n     \"connected_space (discrete_topology U) \\<longleftrightarrow> (\\<exists>a. U \\<subseteq> {a})\"\n  by (metis connectedin_discrete_topology connectedin_topspace order_refl topspace_discrete_topology)\n\n\nsubsection\\<open>Compact sets\\<close>\n\ndefinition compactin where\n \"compactin X S \\<longleftrightarrow>\n     S \\<subseteq> topspace X \\<and>\n     (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> S \\<subseteq> \\<Union>\\<U>\n          \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>))\"\n\ndefinition compact_space where\n   \"compact_space X \\<equiv> compactin X (topspace X)\"\n\nlemma compact_space_alt:\n   \"compact_space X \\<longleftrightarrow>\n        (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> topspace X \\<subseteq> \\<Union>\\<U>\n            \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> topspace X \\<subseteq> \\<Union>\\<F>))\"\n  by (simp add: compact_space_def compactin_def)\n\nlemma compact_space:\n   \"compact_space X \\<longleftrightarrow>\n        (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> \\<Union>\\<U> = topspace X\n            \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> \\<Union>\\<F> = topspace X))\"\n  unfolding compact_space_alt\n  using openin_subset by fastforce\n\nlemma compactinD:\n  \"\\<lbrakk>compactin X S; \\<And>U. U \\<in> \\<U> \\<Longrightarrow> openin X U; S \\<subseteq> \\<Union>\\<U>\\<rbrakk> \\<Longrightarrow> \\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>\"\n  by (auto simp: compactin_def)\n\nlemma compactin_euclidean_iff [simp]: \"compactin euclidean S \\<longleftrightarrow> compact S\"\n  by (simp add: compact_eq_Heine_Borel compactin_def) meson\n\nlemma compactin_absolute [simp]:\n   \"compactin (subtopology X S) S \\<longleftrightarrow> compactin X S\"\nproof -\n  have eq: \"(\\<forall>U \\<in> \\<U>. \\<exists>Y. openin X Y \\<and> U = Y \\<inter> S) \\<longleftrightarrow> \\<U> \\<subseteq> (\\<lambda>Y. Y \\<inter> S) ` {y. openin X y}\" for \\<U>\n    by auto\n  show ?thesis\n    by (auto simp: compactin_def openin_subtopology eq imp_conjL all_subset_image ex_finite_subset_image)\nqed\n\nlemma compactin_subspace: \"compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> compact_space (subtopology X S)\"\n  unfolding compact_space_def topspace_subtopology\n  by (metis compactin_absolute compactin_def inf.absorb2)\n\nlemma compact_space_subtopology: \"compactin X S \\<Longrightarrow> compact_space (subtopology X S)\"\n  by (simp add: compactin_subspace)\n\nlemma compactin_subtopology: \"compactin (subtopology X S) T \\<longleftrightarrow> compactin X T \\<and> T \\<subseteq> S\"\napply (simp add: compactin_subspace)\n  by (metis inf.orderE inf_commute subtopology_subtopology)\n\n\nlemma compactin_subset_topspace: \"compactin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n  by (simp add: compactin_subspace)\n\nlemma compactin_contractive:\n   \"\\<lbrakk>compactin X' S; topspace X' = topspace X;\n     \\<And>U. openin X U \\<Longrightarrow> openin X' U\\<rbrakk> \\<Longrightarrow> compactin X S\"\n  by (simp add: compactin_def)\n\nlemma finite_imp_compactin:\n   \"\\<lbrakk>S \\<subseteq> topspace X; finite S\\<rbrakk> \\<Longrightarrow> compactin X S\"\n  by (metis compactin_subspace compact_space finite_UnionD inf.absorb_iff2 order_refl topspace_subtopology)\n\nlemma compactin_empty [iff]: \"compactin X {}\"\n  by (simp add: finite_imp_compactin)\n\nlemma compact_space_topspace_empty:\n   \"topspace X = {} \\<Longrightarrow> compact_space X\"\n  by (simp add: compact_space_def)\n\nlemma finite_imp_compactin_eq:\n   \"finite S \\<Longrightarrow> (compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X)\"\n  using compactin_subset_topspace finite_imp_compactin by blast\n\nlemma compactin_sing [simp]: \"compactin X {a} \\<longleftrightarrow> a \\<in> topspace X\"\n  by (simp add: finite_imp_compactin_eq)\n\nlemma closed_compactin:\n  assumes XK: \"compactin X K\" and \"C \\<subseteq> K\" and XC: \"closedin X C\"\n  shows \"compactin X C\"\n  unfolding compactin_def\nproof (intro conjI allI impI)\n  show \"C \\<subseteq> topspace X\"\n    by (simp add: XC closedin_subset)\nnext\n  fix \\<U> :: \"'a set set\"\n  assume \\<U>: \"Ball \\<U> (openin X) \\<and> C \\<subseteq> \\<Union>\\<U>\"\n  have \"(\\<forall>U\\<in>insert (topspace X - C) \\<U>. openin X U)\"\n    using XC \\<U> by blast\n  moreover have \"K \\<subseteq> \\<Union>(insert (topspace X - C) \\<U>)\"\n    using \\<U> XK compactin_subset_topspace by fastforce\n  ultimately obtain \\<F> where \"finite \\<F>\" \"\\<F> \\<subseteq> insert (topspace X - C) \\<U>\" \"K \\<subseteq> \\<Union>\\<F>\"\n    using assms unfolding compactin_def by metis\n  moreover have \"openin X (topspace X - C)\"\n    using XC by auto\n  ultimately show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> C \\<subseteq> \\<Union>\\<F>\"\n    using \\<open>C \\<subseteq> K\\<close>\n    by (rule_tac x=\"\\<F> - {topspace X - C}\" in exI) auto\nqed\n\nlemma closedin_compact_space:\n   \"\\<lbrakk>compact_space X; closedin X S\\<rbrakk> \\<Longrightarrow> compactin X S\"\n  by (simp add: closed_compactin closedin_subset compact_space_def)\n\nlemma compact_Int_closedin:\n  assumes \"compactin X S\" \"closedin X T\" shows \"compactin X (S \\<inter> T)\"\nproof -\n  have \"compactin (subtopology X S) (S \\<inter> T)\"\n    by (metis assms closedin_compact_space closedin_subtopology compactin_subspace inf_commute)\n  then show ?thesis\n    by (simp add: compactin_subtopology)\nqed\n\nlemma closed_Int_compactin: \"\\<lbrakk>closedin X S; compactin X T\\<rbrakk> \\<Longrightarrow> compactin X (S \\<inter> T)\"\n  by (metis compact_Int_closedin inf_commute)\n\nlemma compactin_Un:\n  assumes S: \"compactin X S\" and T: \"compactin X T\" shows \"compactin X (S \\<union> T)\"\n  unfolding compactin_def\nproof (intro conjI allI impI)\n  show \"S \\<union> T \\<subseteq> topspace X\"\n    using assms by (auto simp: compactin_def)\nnext\n  fix \\<U> :: \"'a set set\"\n  assume \\<U>: \"Ball \\<U> (openin X) \\<and> S \\<union> T \\<subseteq> \\<Union>\\<U>\"\n  with S obtain \\<F> where \\<V>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<U>\" \"S \\<subseteq> \\<Union>\\<F>\"\n    unfolding compactin_def by (meson sup.bounded_iff)\n  obtain \\<W> where \"finite \\<W>\" \"\\<W> \\<subseteq> \\<U>\" \"T \\<subseteq> \\<Union>\\<W>\"\n    using \\<U> T\n    unfolding compactin_def by (meson sup.bounded_iff)\n  with \\<V> show \"\\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> S \\<union> T \\<subseteq> \\<Union>\\<V>\"\n    by (rule_tac x=\"\\<F> \\<union> \\<W>\" in exI) auto\nqed\n\nlemma compactin_Union:\n   \"\\<lbrakk>finite \\<F>; \\<And>S. S \\<in> \\<F> \\<Longrightarrow> compactin X S\\<rbrakk> \\<Longrightarrow> compactin X (\\<Union>\\<F>)\"\nby (induction rule: finite_induct) (simp_all add: compactin_Un)\n\nlemma compactin_subtopology_imp_compact:\n  assumes \"compactin (subtopology X S) K\" shows \"compactin X K\"\n  using assms\nproof (clarsimp simp add: compactin_def)\n  fix \\<U>\n  define \\<V> where \"\\<V> \\<equiv> (\\<lambda>U. U \\<inter> S) ` \\<U>\"\n  assume \"K \\<subseteq> topspace X\" and \"K \\<subseteq> S\" and \"\\<forall>x\\<in>\\<U>. openin X x\" and \"K \\<subseteq> \\<Union>\\<U>\"\n  then have \"\\<forall>V \\<in> \\<V>. openin (subtopology X S) V\" \"K \\<subseteq> \\<Union>\\<V>\"\n    unfolding \\<V>_def by (auto simp: openin_subtopology)\n  moreover\n  assume \"\\<forall>\\<U>. (\\<forall>x\\<in>\\<U>. openin (subtopology X S) x) \\<and> K \\<subseteq> \\<Union>\\<U> \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>)\"\n  ultimately obtain \\<F> where \"finite \\<F>\" \"\\<F> \\<subseteq> \\<V>\" \"K \\<subseteq> \\<Union>\\<F>\"\n    by meson\n  then have \\<F>: \"\\<exists>U. U \\<in> \\<U> \\<and> V = U \\<inter> S\" if \"V \\<in> \\<F>\" for V\n    unfolding \\<V>_def using that by blast\n  let ?\\<F> = \"(\\<lambda>F. @U. U \\<in> \\<U> \\<and> F = U \\<inter> S) ` \\<F>\"\n  show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>\"\n  proof (intro exI conjI)\n    show \"finite ?\\<F>\"\n      using \\<open>finite \\<F>\\<close> by blast\n    show \"?\\<F> \\<subseteq> \\<U>\"\n      using someI_ex [OF \\<F>] by blast\n    show \"K \\<subseteq> \\<Union>?\\<F>\"\n    proof clarsimp\n      fix x\n      assume \"x \\<in> K\"\n      then show \"\\<exists>V \\<in> \\<F>. x \\<in> (SOME U. U \\<in> \\<U> \\<and> V = U \\<inter> S)\"\n        using \\<open>K \\<subseteq> \\<Union>\\<F>\\<close> someI_ex [OF \\<F>]\n        by (metis (no_types, lifting) IntD1 Union_iff subsetCE)\n    qed\n  qed\nqed\n\nlemma compact_imp_compactin_subtopology:\n  assumes \"compactin X K\" \"K \\<subseteq> S\" shows \"compactin (subtopology X S) K\"\n  using assms\nproof (clarsimp simp add: compactin_def)\n  fix \\<U> :: \"'a set set\"\n  define \\<V> where \"\\<V> \\<equiv> {V. openin X V \\<and> (\\<exists>U \\<in> \\<U>. U = V \\<inter> S)}\"\n  assume \"K \\<subseteq> S\" and \"K \\<subseteq> topspace X\" and \"\\<forall>U\\<in>\\<U>. openin (subtopology X S) U\" and \"K \\<subseteq> \\<Union>\\<U>\"\n  then have \"\\<forall>V \\<in> \\<V>. openin X V\" \"K \\<subseteq> \\<Union>\\<V>\"\n    unfolding \\<V>_def by (fastforce simp: subset_eq openin_subtopology)+\n  moreover\n  assume \"\\<forall>\\<U>. (\\<forall>U\\<in>\\<U>. openin X U) \\<and> K \\<subseteq> \\<Union>\\<U> \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>)\"\n  ultimately obtain \\<F> where \"finite \\<F>\" \"\\<F> \\<subseteq> \\<V>\" \"K \\<subseteq> \\<Union>\\<F>\"\n    by meson\n  let ?\\<F> = \"(\\<lambda>F. F \\<inter> S) ` \\<F>\"\n  show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>\"\n  proof (intro exI conjI)\n    show \"finite ?\\<F>\"\n      using \\<open>finite \\<F>\\<close> by blast\n    show \"?\\<F> \\<subseteq> \\<U>\"\n      using \\<V>_def \\<open>\\<F> \\<subseteq> \\<V>\\<close> by blast\n    show \"K \\<subseteq> \\<Union>?\\<F>\"\n      using \\<open>K \\<subseteq> \\<Union>\\<F>\\<close> assms(2) by auto\n  qed\nqed\n\n\nproposition compact_space_fip:\n   \"compact_space X \\<longleftrightarrow>\n    (\\<forall>\\<U>. (\\<forall>C\\<in>\\<U>. closedin X C) \\<and> (\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> \\<Inter>\\<U> \\<noteq> {})\"\n   (is \"_ = ?rhs\")\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    apply (clarsimp simp add: compact_space_def closedin_topspace_empty)\n    by (metis finite.emptyI finite_insert infinite_super insertI1 subsetI)\nnext\n  case False\n  show ?thesis\n  proof safe\n    fix \\<U> :: \"'a set set\"\n    assume * [rule_format]: \"\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}\"\n    define \\<V> where \"\\<V> \\<equiv> (\\<lambda>S. topspace X - S) ` \\<U>\"\n    assume clo: \"\\<forall>C\\<in>\\<U>. closedin X C\" and [simp]: \"\\<Inter>\\<U> = {}\"\n    then have \"\\<forall>V \\<in> \\<V>. openin X V\" \"topspace X \\<subseteq> \\<Union>\\<V>\"\n      by (auto simp: \\<V>_def)\n    moreover assume [unfolded compact_space_alt, rule_format, of \\<V>]: \"compact_space X\"\n    ultimately obtain \\<F> where \\<F>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<U>\" \"topspace X \\<subseteq> topspace X - \\<Inter>\\<F>\"\n      by (auto simp: ex_finite_subset_image \\<V>_def)\n    moreover have \"\\<F> \\<noteq> {}\"\n      using \\<F> \\<open>topspace X \\<noteq> {}\\<close> by blast\n    ultimately show \"False\"\n      using * [of \\<F>]\n      by auto (metis Diff_iff Inter_iff clo closedin_def subsetD)\n  next\n    assume R [rule_format]: ?rhs\n    show \"compact_space X\"\n      unfolding compact_space_alt\n    proof clarify\n      fix \\<U> :: \"'a set set\"\n      define \\<V> where \"\\<V> \\<equiv> (\\<lambda>S. topspace X - S) ` \\<U>\"\n      assume \"\\<forall>C\\<in>\\<U>. openin X C\" and \"topspace X \\<subseteq> \\<Union>\\<U>\"\n      with \\<open>topspace X \\<noteq> {}\\<close> have *: \"\\<forall>V \\<in> \\<V>. closedin X V\" \"\\<U> \\<noteq> {}\"\n        by (auto simp: \\<V>_def)\n      show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> topspace X \\<subseteq> \\<Union>\\<F>\"\n      proof (rule ccontr; simp)\n        assume \"\\<forall>\\<F>\\<subseteq>\\<U>. finite \\<F> \\<longrightarrow> \\<not> topspace X \\<subseteq> \\<Union>\\<F>\"\n        then have \"\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<V> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}\"\n          by (simp add: \\<V>_def all_finite_subset_image)\n        with \\<open>topspace X \\<subseteq> \\<Union>\\<U>\\<close> show False\n          using R [of \\<V>] * by (simp add: \\<V>_def)\n      qed\n    qed\n  qed\nqed\n\ncorollary compactin_fip:\n  \"compactin X S \\<longleftrightarrow>\n    S \\<subseteq> topspace X \\<and>\n    (\\<forall>\\<U>. (\\<forall>C\\<in>\\<U>. closedin X C) \\<and> (\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> S \\<inter> \\<Inter>\\<U> \\<noteq> {})\"\nproof (cases \"S = {}\")\n  case False\n  show ?thesis\n  proof (cases \"S \\<subseteq> topspace X\")\n    case True\n    then have \"compactin X S \\<longleftrightarrow>\n          (\\<forall>\\<U>. \\<U> \\<subseteq> (\\<lambda>T. S \\<inter> T) ` {T. closedin X T} \\<longrightarrow>\n           (\\<forall>\\<F>. finite \\<F> \\<longrightarrow> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> \\<Inter>\\<U> \\<noteq> {})\"\n      by (simp add: compact_space_fip compactin_subspace closedin_subtopology image_def subset_eq Int_commute imp_conjL)\n    also have \"\\<dots> = (\\<forall>\\<U>\\<subseteq>Collect (closedin X). (\\<forall>\\<F>. finite \\<F> \\<longrightarrow> \\<F> \\<subseteq> (\\<inter>) S ` \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> \\<Inter> ((\\<inter>) S ` \\<U>) \\<noteq> {})\"\n      by (simp add: all_subset_image)\n    also have \"\\<dots> = (\\<forall>\\<U>. (\\<forall>C\\<in>\\<U>. closedin X C) \\<and> (\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> S \\<inter> \\<Inter>\\<U> \\<noteq> {})\"\n    proof -\n      have eq: \"((\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter> ((\\<inter>) S ` \\<F>) \\<noteq> {}) \\<longrightarrow> \\<Inter> ((\\<inter>) S ` \\<U>) \\<noteq> {}) \\<longleftrightarrow>\n                ((\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> S \\<inter> \\<Inter>\\<U> \\<noteq> {})\"  for \\<U>\n        by simp (use \\<open>S \\<noteq> {}\\<close> in blast)\n      show ?thesis\n        apply (simp only: imp_conjL [symmetric] all_finite_subset_image eq)\n        apply (simp add: subset_eq)\n        done\n    qed\n    finally show ?thesis\n      using True by simp\n  qed (simp add: compactin_subspace)\nqed force\n\ncorollary compact_space_imp_nest:\n  fixes C :: \"nat \\<Rightarrow> 'a set\"\n  assumes \"compact_space X\" and clo: \"\\<And>n. closedin X (C n)\"\n    and ne: \"\\<And>n. C n \\<noteq> {}\" and inc: \"\\<And>m n. m \\<le> n \\<Longrightarrow> C n \\<subseteq> C m\"\n  shows \"(\\<Inter>n. C n) \\<noteq> {}\"\nproof -\n  let ?\\<U> = \"range (\\<lambda>n. \\<Inter>m \\<le> n. C m)\"\n  have \"closedin X A\" if \"A \\<in> ?\\<U>\" for A\n    using that clo by auto\n  moreover have \"(\\<Inter>n\\<in>K. \\<Inter>m \\<le> n. C m) \\<noteq> {}\" if \"finite K\" for K\n  proof -\n    obtain n where \"\\<And>k. k \\<in> K \\<Longrightarrow> k \\<le> n\"\n      using Max.coboundedI \\<open>finite K\\<close> by blast\n    with inc have \"C n \\<subseteq> (\\<Inter>n\\<in>K. \\<Inter>m \\<le> n. C m)\"\n    by blast\n  with ne [of n] show ?thesis\n    by blast\n  qed\n  ultimately show ?thesis\n    using \\<open>compact_space X\\<close> [unfolded compact_space_fip, rule_format, of ?\\<U>]\n    by (simp add: all_finite_subset_image INT_extend_simps UN_atMost_UNIV del: INT_simps)\nqed\n\nlemma compactin_discrete_topology:\n   \"compactin (discrete_topology X) S \\<longleftrightarrow> S \\<subseteq> X \\<and> finite S\" (is \"?lhs = ?rhs\")\nproof (intro iffI conjI)\n  assume L: ?lhs\n  then show \"S \\<subseteq> X\"\n    by (auto simp: compactin_def)\n  have *: \"\\<And>\\<U>. Ball \\<U> (openin (discrete_topology X)) \\<and> S \\<subseteq> \\<Union>\\<U> \\<Longrightarrow>\n        (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>)\"\n    using L by (auto simp: compactin_def)\n  show \"finite S\"\n    using * [of \"(\\<lambda>x. {x}) ` X\"] \\<open>S \\<subseteq> X\\<close>\n    by clarsimp (metis UN_singleton finite_subset_image infinite_super)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (simp add: finite_imp_compactin)\nqed\n\nlemma compact_space_discrete_topology: \"compact_space(discrete_topology X) \\<longleftrightarrow> finite X\"\n  by (simp add: compactin_discrete_topology compact_space_def)\n\nlemma compact_space_imp_Bolzano_Weierstrass:\n  assumes \"compact_space X\" \"infinite S\" \"S \\<subseteq> topspace X\"\n  shows \"X derived_set_of S \\<noteq> {}\"\nproof\n  assume X: \"X derived_set_of S = {}\"\n  then have \"closedin X S\"\n    by (simp add: closedin_contains_derived_set assms)\n  then have \"compactin X S\"\n    by (rule closedin_compact_space [OF \\<open>compact_space X\\<close>])\n  with X show False\n    by (metis \\<open>infinite S\\<close> compactin_subspace compact_space_discrete_topology inf_bot_right subtopology_eq_discrete_topology_eq)\nqed\n\nlemma compactin_imp_Bolzano_Weierstrass:\n   \"\\<lbrakk>compactin X S; infinite T \\<and> T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> S \\<inter> X derived_set_of T \\<noteq> {}\"\n  using compact_space_imp_Bolzano_Weierstrass [of \"subtopology X S\"]\n  by (simp add: compactin_subspace derived_set_of_subtopology inf_absorb2)\n\nlemma compact_closure_of_imp_Bolzano_Weierstrass:\n   \"\\<lbrakk>compactin X (X closure_of S); infinite T; T \\<subseteq> S; T \\<subseteq> topspace X\\<rbrakk> \\<Longrightarrow> X derived_set_of T \\<noteq> {}\"\n  using closure_of_mono closure_of_subset compactin_imp_Bolzano_Weierstrass by fastforce\n\nlemma discrete_compactin_eq_finite:\n   \"S \\<inter> X derived_set_of S = {} \\<Longrightarrow> compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> finite S\"\n  apply (rule iffI)\n  using compactin_imp_Bolzano_Weierstrass compactin_subset_topspace apply blast\n  by (simp add: finite_imp_compactin_eq)\n\nlemma discrete_compact_space_eq_finite:\n   \"X derived_set_of (topspace X) = {} \\<Longrightarrow> (compact_space X \\<longleftrightarrow> finite(topspace X))\"\n  by (metis compact_space_discrete_topology discrete_topology_unique_derived_set)\n\nlemma image_compactin:\n  assumes cpt: \"compactin X S\" and cont: \"continuous_map X Y f\"\n  shows \"compactin Y (f ` S)\"\n  unfolding compactin_def\nproof (intro conjI allI impI)\n  show \"f ` S \\<subseteq> topspace Y\"\n    using compactin_subset_topspace cont continuous_map_image_subset_topspace cpt by blast\nnext\n  fix \\<U> :: \"'b set set\"\n  assume \\<U>: \"Ball \\<U> (openin Y) \\<and> f ` S \\<subseteq> \\<Union>\\<U>\"\n  define \\<V> where \"\\<V> \\<equiv> (\\<lambda>U. {x \\<in> topspace X. f x \\<in> U}) ` \\<U>\"\n  have \"S \\<subseteq> topspace X\"\n    and *: \"\\<And>\\<U>. \\<lbrakk>\\<forall>U\\<in>\\<U>. openin X U; S \\<subseteq> \\<Union>\\<U>\\<rbrakk> \\<Longrightarrow> \\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>\"\n    using cpt by (auto simp: compactin_def)\n  obtain \\<F> where \\<F>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<V>\" \"S \\<subseteq> \\<Union>\\<F>\"\n  proof -\n    have 1: \"\\<forall>U\\<in>\\<V>. openin X U\"\n      unfolding \\<V>_def using \\<U> cont[unfolded continuous_map] by blast\n    have 2: \"S \\<subseteq> \\<Union>\\<V>\"\n      unfolding \\<V>_def using compactin_subset_topspace cpt \\<U> by fastforce\n    show thesis\n      using * [OF 1 2] that by metis\n  qed\n  have \"\\<forall>v \\<in> \\<V>. \\<exists>U. U \\<in> \\<U> \\<and> v = {x \\<in> topspace X. f x \\<in> U}\"\n    using \\<V>_def by blast\n  then obtain U where U: \"\\<forall>v \\<in> \\<V>. U v \\<in> \\<U> \\<and> v = {x \\<in> topspace X. f x \\<in> U v}\"\n    by metis\n  show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> f ` S \\<subseteq> \\<Union>\\<F>\"\n  proof (intro conjI exI)\n    show \"finite (U ` \\<F>)\"\n      by (simp add: \\<open>finite \\<F>\\<close>)\n  next\n    show \"U ` \\<F> \\<subseteq> \\<U>\"\n      using \\<open>\\<F> \\<subseteq> \\<V>\\<close> U by auto\n  next\n    show \"f ` S \\<subseteq> \\<Union> (U ` \\<F>)\"\n      using \\<F>(2-3) U UnionE subset_eq U by fastforce\n  qed\nqed\n\n\nlemma homeomorphic_compact_space:\n  assumes \"X homeomorphic_space Y\"\n  shows \"compact_space X \\<longleftrightarrow> compact_space Y\"\n    using homeomorphic_space_sym\n    by (metis assms compact_space_def homeomorphic_eq_everything_map homeomorphic_space image_compactin)\n\nlemma homeomorphic_map_compactness:\n  assumes hom: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"compactin Y (f ` U) \\<longleftrightarrow> compactin X U\"\nproof -\n  have \"f ` U \\<subseteq> topspace Y\"\n    using hom U homeomorphic_imp_surjective_map by blast\n  moreover have \"homeomorphic_map (subtopology X U) (subtopology Y (f ` U)) f\"\n    using U hom homeomorphic_imp_surjective_map by (blast intro: homeomorphic_map_subtopologies)\n  then have \"compact_space (subtopology Y (f ` U)) = compact_space (subtopology X U)\"\n    using homeomorphic_compact_space homeomorphic_map_imp_homeomorphic_space by blast\n  ultimately show ?thesis\n    by (simp add: compactin_subspace U)\nqed\n\nlemma homeomorphic_map_compactness_eq:\n   \"homeomorphic_map X Y f\n        \\<Longrightarrow> compactin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> compactin Y (f ` U)\"\n  by (meson compactin_subset_topspace homeomorphic_map_compactness)\n\n\nsubsection\\<open>Embedding maps\\<close>\n\ndefinition embedding_map\n  where \"embedding_map X Y f \\<equiv> homeomorphic_map X (subtopology Y (f ` (topspace X))) f\"\n\nlemma embedding_map_eq:\n   \"\\<lbrakk>embedding_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> embedding_map X Y g\"\n  unfolding embedding_map_def\n  by (metis homeomorphic_map_eq image_cong)\n\nlemma embedding_map_compose:\n  assumes \"embedding_map X X' f\" \"embedding_map X' X'' g\"\n  shows \"embedding_map X X'' (g \\<circ> f)\"\nproof -\n  have hm: \"homeomorphic_map X (subtopology X' (f ` topspace X)) f\" \"homeomorphic_map X' (subtopology X'' (g ` topspace X')) g\"\n    using assms by (auto simp: embedding_map_def)\n  then obtain C where \"g ` topspace X' \\<inter> C = (g \\<circ> f) ` topspace X\"\n    by (metis (no_types) Int_absorb1 continuous_map_image_subset_topspace continuous_map_in_subtopology homeomorphic_eq_everything_map image_comp image_mono)\n  then have \"homeomorphic_map (subtopology X' (f ` topspace X)) (subtopology X'' ((g \\<circ> f) ` topspace X)) g\"\n    by (metis hm homeomorphic_imp_surjective_map homeomorphic_map_subtopologies image_comp subtopology_subtopology topspace_subtopology)\n  then show ?thesis\n  unfolding embedding_map_def\n  using hm(1) homeomorphic_map_compose by blast\nqed\n\nlemma surjective_embedding_map:\n   \"embedding_map X Y f \\<and> f ` (topspace X) = topspace Y \\<longleftrightarrow> homeomorphic_map X Y f\"\n  by (force simp: embedding_map_def homeomorphic_eq_everything_map)\n\nlemma embedding_map_in_subtopology:\n   \"embedding_map X (subtopology Y S) f \\<longleftrightarrow> embedding_map X Y f \\<and> f ` (topspace X) \\<subseteq> S\"\n  apply (auto simp: embedding_map_def subtopology_subtopology Int_absorb1)\n    apply (metis (no_types) homeomorphic_imp_surjective_map subtopology_subtopology subtopology_topspace topspace_subtopology)\n  apply (simp add: continuous_map_def homeomorphic_eq_everything_map)\n  done\n\nlemma injective_open_imp_embedding_map:\n   \"\\<lbrakk>continuous_map X Y f; open_map X Y f; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> embedding_map X Y f\"\n  unfolding embedding_map_def\n  apply (rule bijective_open_imp_homeomorphic_map)\n  using continuous_map_in_subtopology apply blast\n    apply (auto simp: continuous_map_in_subtopology open_map_into_subtopology continuous_map)\n  done\n\nlemma injective_closed_imp_embedding_map:\n  \"\\<lbrakk>continuous_map X Y f; closed_map X Y f; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> embedding_map X Y f\"\n  unfolding embedding_map_def\n  apply (rule bijective_closed_imp_homeomorphic_map)\n     apply (simp_all add: continuous_map_into_subtopology closed_map_into_subtopology)\n  apply (simp add: continuous_map inf.absorb_iff2)\n  done\n\nlemma embedding_map_imp_homeomorphic_space:\n   \"embedding_map X Y f \\<Longrightarrow> X homeomorphic_space (subtopology Y (f ` (topspace X)))\"\n  unfolding embedding_map_def\n  using homeomorphic_space by blast\n\nlemma embedding_imp_closed_map:\n   \"\\<lbrakk>embedding_map X Y f; closedin Y (f ` topspace X)\\<rbrakk> \\<Longrightarrow> closed_map X Y f\"\n  unfolding closed_map_def\n  by (auto simp: closedin_closed_subtopology embedding_map_def homeomorphic_map_closedness_eq)\n\n\nsubsection\\<open>Retraction and section maps\\<close>\n\ndefinition retraction_maps :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"retraction_maps X Y f g \\<equiv>\n           continuous_map X Y f \\<and> continuous_map Y X g \\<and> (\\<forall>x \\<in> topspace Y. f(g x) = x)\"\n\ndefinition section_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"section_map X Y f \\<equiv> \\<exists>g. retraction_maps Y X g f\"\n\ndefinition retraction_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"retraction_map X Y f \\<equiv> \\<exists>g. retraction_maps X Y f g\"\n\nlemma retraction_maps_eq:\n   \"\\<lbrakk>retraction_maps X Y f g; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = f' x; \\<And>x. x \\<in> topspace Y \\<Longrightarrow> g x = g' x\\<rbrakk>\n        \\<Longrightarrow> retraction_maps X Y f' g'\"\n  unfolding retraction_maps_def by (metis (no_types, lifting) continuous_map_def continuous_map_eq)\n\nlemma section_map_eq:\n   \"\\<lbrakk>section_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> section_map X Y g\"\n  unfolding section_map_def using retraction_maps_eq by blast\n\nlemma retraction_map_eq:\n   \"\\<lbrakk>retraction_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> retraction_map X Y g\"\n  unfolding retraction_map_def using retraction_maps_eq by blast\n\nlemma homeomorphic_imp_retraction_maps:\n   \"homeomorphic_maps X Y f g \\<Longrightarrow> retraction_maps X Y f g\"\n  by (simp add: homeomorphic_maps_def retraction_maps_def)\n\nlemma section_and_retraction_eq_homeomorphic_map:\n   \"section_map X Y f \\<and> retraction_map X Y f \\<longleftrightarrow> homeomorphic_map X Y f\"\n  apply (auto simp: section_map_def retraction_map_def homeomorphic_map_maps retraction_maps_def homeomorphic_maps_def)\n  by (metis (full_types) continuous_map_image_subset_topspace image_subset_iff)\n\nlemma section_imp_embedding_map:\n   \"section_map X Y f \\<Longrightarrow> embedding_map X Y f\"\n  unfolding section_map_def embedding_map_def homeomorphic_map_maps retraction_maps_def homeomorphic_maps_def\n  by (force simp: continuous_map_in_subtopology continuous_map_from_subtopology)\n\nlemma retraction_imp_quotient_map:\n  assumes \"retraction_map X Y f\"\n  shows \"quotient_map X Y f\"\n  unfolding quotient_map_def\nproof (intro conjI subsetI allI impI)\n  show \"f ` topspace X = topspace Y\"\n    using assms by (force simp: retraction_map_def retraction_maps_def continuous_map_def)\nnext\n  fix U\n  assume U: \"U \\<subseteq> topspace Y\"\n  have \"openin Y U\"\n    if \"\\<forall>x\\<in>topspace Y. g x \\<in> topspace X\" \"\\<forall>x\\<in>topspace Y. f (g x) = x\"\n       \"openin Y {x \\<in> topspace Y. g x \\<in> {x \\<in> topspace X. f x \\<in> U}}\" for g\n    using openin_subopen U that by fastforce\n  then show \"openin X {x \\<in> topspace X. f x \\<in> U} = openin Y U\"\n    using assms by (auto simp: retraction_map_def retraction_maps_def continuous_map_def)\nqed\n\nlemma retraction_maps_compose:\n   \"\\<lbrakk>retraction_maps X Y f f'; retraction_maps Y Z g g'\\<rbrakk> \\<Longrightarrow> retraction_maps X Z (g \\<circ> f) (f' \\<circ> g')\"\n  by (clarsimp simp: retraction_maps_def continuous_map_compose) (simp add: continuous_map_def)\n\nlemma retraction_map_compose:\n   \"\\<lbrakk>retraction_map X Y f; retraction_map Y Z g\\<rbrakk> \\<Longrightarrow> retraction_map X Z (g \\<circ> f)\"\n  by (meson retraction_map_def retraction_maps_compose)\n\nlemma section_map_compose:\n   \"\\<lbrakk>section_map X Y f; section_map Y Z g\\<rbrakk> \\<Longrightarrow> section_map X Z (g \\<circ> f)\"\n  by (meson retraction_maps_compose section_map_def)\n\nlemma surjective_section_eq_homeomorphic_map:\n   \"section_map X Y f \\<and> f ` (topspace X) = topspace Y \\<longleftrightarrow> homeomorphic_map X Y f\"\n  by (meson section_and_retraction_eq_homeomorphic_map section_imp_embedding_map surjective_embedding_map)\n\nlemma surjective_retraction_or_section_map:\n   \"f ` (topspace X) = topspace Y \\<Longrightarrow> retraction_map X Y f \\<or> section_map X Y f \\<longleftrightarrow> retraction_map X Y f\"\n  using section_and_retraction_eq_homeomorphic_map surjective_section_eq_homeomorphic_map by fastforce\n\nlemma retraction_imp_surjective_map:\n   \"retraction_map X Y f \\<Longrightarrow> f ` (topspace X) = topspace Y\"\n  by (simp add: retraction_imp_quotient_map quotient_imp_surjective_map)\n\nlemma section_imp_injective_map:\n   \"\\<lbrakk>section_map X Y f; x \\<in> topspace X; y \\<in> topspace X\\<rbrakk> \\<Longrightarrow> f x = f y \\<longleftrightarrow> x = y\"\n  by (metis (mono_tags, hide_lams) retraction_maps_def section_map_def)\n\nlemma retraction_maps_to_retract_maps:\n   \"retraction_maps X Y r s\n        \\<Longrightarrow> retraction_maps X (subtopology X (s ` (topspace Y))) (s \\<circ> r) id\"\n  unfolding retraction_maps_def\n  by (auto simp: continuous_map_compose continuous_map_into_subtopology continuous_map_from_subtopology)\nsubsection \\<open>Continuity\\<close>\n\nlemma continuous_on_open:\n  \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. openin (top_of_set (f ` S)) T \\<longrightarrow>\n      openin (top_of_set S) (S \\<inter> f -` T))\"\n  unfolding continuous_on_open_invariant openin_open Int_def vimage_def Int_commute\n  by (simp add: imp_ex imageI conj_commute eq_commute cong: conj_cong)\n\nlemma continuous_on_closed:\n  \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. closedin (top_of_set (f ` S)) T \\<longrightarrow>\n      closedin (top_of_set S) (S \\<inter> f -` T))\"\n  unfolding continuous_on_closed_invariant closedin_closed Int_def vimage_def Int_commute\n  by (simp add: imp_ex imageI conj_commute eq_commute cong: conj_cong)\n\nlemma continuous_on_imp_closedin:\n  assumes \"continuous_on S f\" \"closedin (top_of_set (f ` S)) T\"\n  shows \"closedin (top_of_set S) (S \\<inter> f -` T)\"\n  using assms continuous_on_closed by blast\n\nlemma continuous_map_subtopology_eu [simp]:\n  \"continuous_map (top_of_set S) (subtopology euclidean T) h \\<longleftrightarrow> continuous_on S h \\<and> h ` S \\<subseteq> T\"\n  apply safe\n  apply (metis continuous_map_closedin_preimage_eq continuous_map_in_subtopology continuous_on_closed order_refl topspace_euclidean_subtopology)\n  apply (simp add: continuous_map_closedin_preimage_eq image_subset_iff)\n  by (metis (no_types, hide_lams) continuous_map_closedin_preimage_eq continuous_map_in_subtopology continuous_on_closed order_refl topspace_euclidean_subtopology)\n\nlemma continuous_map_euclidean_top_of_set:\n  assumes eq: \"f -` S = UNIV\" and cont: \"continuous_on UNIV f\"\n  shows \"continuous_map euclidean (top_of_set S) f\"\n  by (simp add: cont continuous_map_into_subtopology eq image_subset_iff_subset_vimage)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Half-global and completely global cases\\<close>\n\nlemma continuous_openin_preimage_gen:\n  assumes \"continuous_on S f\"  \"open T\"\n  shows \"openin (top_of_set S) (S \\<inter> f -` T)\"\nproof -\n  have *: \"(S \\<inter> f -` T) = (S \\<inter> f -` (T \\<inter> f ` S))\"\n    by auto\n  have \"openin (top_of_set (f ` S)) (T \\<inter> f ` S)\"\n    using openin_open_Int[of T \"f ` S\", OF assms(2)] unfolding openin_open by auto\n  then show ?thesis\n    using assms(1)[unfolded continuous_on_open, THEN spec[where x=\"T \\<inter> f ` S\"]]\n    using * by auto\nqed\n\nlemma continuous_closedin_preimage:\n  assumes \"continuous_on S f\" and \"closed T\"\n  shows \"closedin (top_of_set S) (S \\<inter> f -` T)\"\nproof -\n  have *: \"(S \\<inter> f -` T) = (S \\<inter> f -` (T \\<inter> f ` S))\"\n    by auto\n  have \"closedin (top_of_set (f ` S)) (T \\<inter> f ` S)\"\n    using closedin_closed_Int[of T \"f ` S\", OF assms(2)]\n    by (simp add: Int_commute)\n  then show ?thesis\n    using assms(1)[unfolded continuous_on_closed, THEN spec[where x=\"T \\<inter> f ` S\"]]\n    using * by auto\nqed\n\nlemma continuous_openin_preimage_eq:\n   \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. open T \\<longrightarrow> openin (top_of_set S) (S \\<inter> f -` T))\"\napply safe\napply (simp add: continuous_openin_preimage_gen)\napply (fastforce simp add: continuous_on_open openin_open)\ndone\n\nlemma continuous_closedin_preimage_eq:\n   \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. closed T \\<longrightarrow> closedin (top_of_set S) (S \\<inter> f -` T))\"\napply safe\napply (simp add: continuous_closedin_preimage)\napply (fastforce simp add: continuous_on_closed closedin_closed)\ndone\n\nlemma continuous_open_preimage:\n  assumes contf: \"continuous_on S f\" and \"open S\" \"open T\"\n  shows \"open (S \\<inter> f -` T)\"\nproof-\n  obtain U where \"open U\" \"(S \\<inter> f -` T) = S \\<inter> U\"\n    using continuous_openin_preimage_gen[OF contf \\<open>open T\\<close>]\n    unfolding openin_open by auto\n  then show ?thesis\n    using open_Int[of S U, OF \\<open>open S\\<close>] by auto\nqed\n\nlemma continuous_closed_preimage:\n  assumes contf: \"continuous_on S f\" and \"closed S\" \"closed T\"\n  shows \"closed (S \\<inter> f -` T)\"\nproof-\n  obtain U where \"closed U\" \"(S \\<inter> f -` T) = S \\<inter> U\"\n    using continuous_closedin_preimage[OF contf \\<open>closed T\\<close>]\n    unfolding closedin_closed by auto\n  then show ?thesis using closed_Int[of S U, OF \\<open>closed S\\<close>] by auto\nqed\n\nlemma continuous_open_vimage: \"open S \\<Longrightarrow> (\\<And>x. continuous (at x) f) \\<Longrightarrow> open (f -` S)\"\n  by (metis continuous_on_eq_continuous_within open_vimage) \n \nlemma continuous_closed_vimage: \"closed S \\<Longrightarrow> (\\<And>x. continuous (at x) f) \\<Longrightarrow> closed (f -` S)\"\n  by (simp add: closed_vimage continuous_on_eq_continuous_within)\n\nlemma Times_in_interior_subtopology:\n  assumes \"(x, y) \\<in> U\" \"openin (top_of_set (S \\<times> T)) U\"\n  obtains V W where \"openin (top_of_set S) V\" \"x \\<in> V\"\n                    \"openin (top_of_set T) W\" \"y \\<in> W\" \"(V \\<times> W) \\<subseteq> U\"\nproof -\n  from assms obtain E where \"open E\" \"U = S \\<times> T \\<inter> E\" \"(x, y) \\<in> E\" \"x \\<in> S\" \"y \\<in> T\"\n    by (auto simp: openin_open)\n  from open_prod_elim[OF \\<open>open E\\<close> \\<open>(x, y) \\<in> E\\<close>]\n  obtain E1 E2 where \"open E1\" \"open E2\" \"(x, y) \\<in> E1 \\<times> E2\" \"E1 \\<times> E2 \\<subseteq> E\"\n    by blast\n  show ?thesis\n  proof\n    show \"openin (top_of_set S) (E1 \\<inter> S)\"\n      \"openin (top_of_set T) (E2 \\<inter> T)\"\n      using \\<open>open E1\\<close> \\<open>open E2\\<close>\n      by (auto simp: openin_open)\n    show \"x \\<in> E1 \\<inter> S\" \"y \\<in> E2 \\<inter> T\"\n      using \\<open>(x, y) \\<in> E1 \\<times> E2\\<close> \\<open>x \\<in> S\\<close> \\<open>y \\<in> T\\<close> by auto\n    show \"(E1 \\<inter> S) \\<times> (E2 \\<inter> T) \\<subseteq> U\"\n      using \\<open>E1 \\<times> E2 \\<subseteq> E\\<close> \\<open>U = _\\<close>\n      by (auto simp: )\n  qed\nqed\n\nlemma closedin_Times:\n  \"closedin (top_of_set S) S' \\<Longrightarrow> closedin (top_of_set T) T' \\<Longrightarrow>\n    closedin (top_of_set (S \\<times> T)) (S' \\<times> T')\"\n  unfolding closedin_closed using closed_Times by blast\n\nlemma openin_Times:\n  \"openin (top_of_set S) S' \\<Longrightarrow> openin (top_of_set T) T' \\<Longrightarrow>\n    openin (top_of_set (S \\<times> T)) (S' \\<times> T')\"\n  unfolding openin_open using open_Times by blast\n\nlemma openin_Times_eq:\n  fixes S :: \"'a::topological_space set\" and T :: \"'b::topological_space set\"\n  shows\n    \"openin (top_of_set (S \\<times> T)) (S' \\<times> T') \\<longleftrightarrow>\n      S' = {} \\<or> T' = {} \\<or> openin (top_of_set S) S' \\<and> openin (top_of_set T) T'\"\n    (is \"?lhs = ?rhs\")\nproof (cases \"S' = {} \\<or> T' = {}\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then obtain x y where \"x \\<in> S'\" \"y \\<in> T'\"\n    by blast\n  show ?thesis\n  proof\n    assume ?lhs\n    have \"openin (top_of_set S) S'\"\n      apply (subst openin_subopen, clarify)\n      apply (rule Times_in_interior_subtopology [OF _ \\<open>?lhs\\<close>])\n      using \\<open>y \\<in> T'\\<close>\n       apply auto\n      done\n    moreover have \"openin (top_of_set T) T'\"\n      apply (subst openin_subopen, clarify)\n      apply (rule Times_in_interior_subtopology [OF _ \\<open>?lhs\\<close>])\n      using \\<open>x \\<in> S'\\<close>\n       apply auto\n      done\n    ultimately show ?rhs\n      by simp\n  next\n    assume ?rhs\n    with False show ?lhs\n      by (simp add: openin_Times)\n  qed\nqed\n\nlemma Lim_transform_within_openin:\n  assumes f: \"(f \\<longlongrightarrow> l) (at a within T)\"\n    and \"openin (top_of_set T) S\" \"a \\<in> S\"\n    and eq: \"\\<And>x. \\<lbrakk>x \\<in> S; x \\<noteq> a\\<rbrakk> \\<Longrightarrow> f x = g x\"\n  shows \"(g \\<longlongrightarrow> l) (at a within T)\"\nproof -\n  have \"\\<forall>\\<^sub>F x in at a within T. x \\<in> T \\<and> x \\<noteq> a\"\n    by (simp add: eventually_at_filter)\n  moreover\n  from \\<open>openin _ _\\<close> obtain U where \"open U\" \"S = T \\<inter> U\"\n    by (auto simp: openin_open)\n  then have \"a \\<in> U\" using \\<open>a \\<in> S\\<close> by auto\n  from topological_tendstoD[OF tendsto_ident_at \\<open>open U\\<close> \\<open>a \\<in> U\\<close>]\n  have \"\\<forall>\\<^sub>F x in at a within T. x \\<in> U\" by auto\n  ultimately\n  have \"\\<forall>\\<^sub>F x in at a within T. f x = g x\"\n    by eventually_elim (auto simp: \\<open>S = _\\<close> eq)\n  with f show ?thesis\n    by (rule Lim_transform_eventually)\nqed\n\nlemma continuous_on_open_gen:\n  assumes \"f ` S \\<subseteq> T\"\n    shows \"continuous_on S f \\<longleftrightarrow>\n             (\\<forall>U. openin (top_of_set T) U\n                  \\<longrightarrow> openin (top_of_set S) (S \\<inter> f -` U))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (clarsimp simp add: continuous_openin_preimage_eq openin_open)\n      (metis Int_assoc assms image_subset_iff_subset_vimage inf.absorb_iff1)\nnext\n  assume R [rule_format]: ?rhs\n  show ?lhs\n  proof (clarsimp simp add: continuous_openin_preimage_eq)\n    fix U::\"'a set\"\n    assume \"open U\"\n    then have \"openin (top_of_set S) (S \\<inter> f -` (U \\<inter> T))\"\n      by (metis R inf_commute openin_open)\n    then show \"openin (top_of_set S) (S \\<inter> f -` U)\"\n      by (metis Int_assoc Int_commute assms image_subset_iff_subset_vimage inf.absorb_iff2 vimage_Int)\n  qed\nqed\n\nlemma continuous_openin_preimage:\n  \"\\<lbrakk>continuous_on S f; f ` S \\<subseteq> T; openin (top_of_set T) U\\<rbrakk>\n        \\<Longrightarrow> openin (top_of_set S) (S \\<inter> f -` U)\"\n  by (simp add: continuous_on_open_gen)\n\nlemma continuous_on_closed_gen:\n  assumes \"f ` S \\<subseteq> T\"\n  shows \"continuous_on S f \\<longleftrightarrow>\n             (\\<forall>U. closedin (top_of_set T) U\n                  \\<longrightarrow> closedin (top_of_set S) (S \\<inter> f -` U))\"\n    (is \"?lhs = ?rhs\")\nproof -\n  have *: \"U \\<subseteq> T \\<Longrightarrow> S \\<inter> f -` (T - U) = S - (S \\<inter> f -` U)\" for U\n    using assms by blast\n  show ?thesis\n  proof\n    assume L: ?lhs\n    show ?rhs\n    proof clarify\n      fix U\n      assume \"closedin (top_of_set T) U\"\n      then show \"closedin (top_of_set S) (S \\<inter> f -` U)\"\n        using L unfolding continuous_on_open_gen [OF assms]\n        by (metis * closedin_def inf_le1 topspace_euclidean_subtopology)\n    qed\n  next\n    assume R [rule_format]: ?rhs\n    show ?lhs\n      unfolding continuous_on_open_gen [OF assms]\n      by (metis * R inf_le1 openin_closedin_eq topspace_euclidean_subtopology)\n  qed\nqed\n\nlemma continuous_closedin_preimage_gen:\n  assumes \"continuous_on S f\" \"f ` S \\<subseteq> T\" \"closedin (top_of_set T) U\"\n    shows \"closedin (top_of_set S) (S \\<inter> f -` U)\"\nusing assms continuous_on_closed_gen by blast\n\nlemma continuous_transform_within_openin:\n  assumes \"continuous (at a within T) f\"\n    and \"openin (top_of_set T) S\" \"a \\<in> S\"\n    and eq: \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  shows \"continuous (at a within T) g\"\n  using assms by (simp add: Lim_transform_within_openin continuous_within)\n\n\nsubsection\\<^marker>\\<open>tag important\\<close> \\<open>The topology generated by some (open) subsets\\<close>\n\ntext \\<open>In the definition below of a generated topology, the \\<open>Empty\\<close> case is not necessary,\nas it follows from \\<open>UN\\<close> taking for \\<open>K\\<close> the empty set. However, it is convenient to have,\nand is never a problem in proofs, so I prefer to write it down explicitly.\n\nWe do not require \\<open>UNIV\\<close> to be an open set, as this will not be the case in applications. (We are\nthinking of a topology on a subset of \\<open>UNIV\\<close>, the remaining part of \\<open>UNIV\\<close> being irrelevant.)\\<close>\n\ninductive generate_topology_on for S where\n  Empty: \"generate_topology_on S {}\"\n| Int: \"generate_topology_on S a \\<Longrightarrow> generate_topology_on S b \\<Longrightarrow> generate_topology_on S (a \\<inter> b)\"\n| UN: \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology_on S k) \\<Longrightarrow> generate_topology_on S (\\<Union>K)\"\n| Basis: \"s \\<in> S \\<Longrightarrow> generate_topology_on S s\"\n\nlemma istopology_generate_topology_on:\n  \"istopology (generate_topology_on S)\"\nunfolding istopology_def by (auto intro: generate_topology_on.intros)\n\ntext \\<open>The basic property of the topology generated by a set \\<open>S\\<close> is that it is the\nsmallest topology containing all the elements of \\<open>S\\<close>:\\<close>\n\nlemma generate_topology_on_coarsest:\n  assumes \"istopology T\"\n          \"\\<And>s. s \\<in> S \\<Longrightarrow> T s\"\n          \"generate_topology_on S s0\"\n  shows \"T s0\"\nusing assms(3) apply (induct rule: generate_topology_on.induct)\nusing assms(1) assms(2) unfolding istopology_def by auto\n\nabbreviation\\<^marker>\\<open>tag unimportant\\<close> topology_generated_by::\"('a set set) \\<Rightarrow> ('a topology)\"\n  where \"topology_generated_by S \\<equiv> topology (generate_topology_on S)\"\n\nlemma openin_topology_generated_by_iff:\n  \"openin (topology_generated_by S) s \\<longleftrightarrow> generate_topology_on S s\"\n  using topology_inverse'[OF istopology_generate_topology_on[of S]] by simp\n\nlemma openin_topology_generated_by:\n  \"openin (topology_generated_by S) s \\<Longrightarrow> generate_topology_on S s\"\nusing openin_topology_generated_by_iff by auto\n\nlemma topology_generated_by_topspace [simp]:\n  \"topspace (topology_generated_by S) = (\\<Union>S)\"\nproof\n  {\n    fix s assume \"openin (topology_generated_by S) s\"\n    then have \"generate_topology_on S s\" by (rule openin_topology_generated_by)\n    then have \"s \\<subseteq> (\\<Union>S)\" by (induct, auto)\n  }\n  then show \"topspace (topology_generated_by S) \\<subseteq> (\\<Union>S)\"\n    unfolding topspace_def by auto\nnext\n  have \"generate_topology_on S (\\<Union>S)\"\n    using generate_topology_on.UN[OF generate_topology_on.Basis, of S S] by simp\n  then show \"(\\<Union>S) \\<subseteq> topspace (topology_generated_by S)\"\n    unfolding topspace_def using openin_topology_generated_by_iff by auto\nqed\n\nlemma topology_generated_by_Basis:\n  \"s \\<in> S \\<Longrightarrow> openin (topology_generated_by S) s\"\n  by (simp only: openin_topology_generated_by_iff, auto simp: generate_topology_on.Basis)\n\nlemma generate_topology_on_Inter:\n  \"\\<lbrakk>finite \\<F>; \\<And>K. K \\<in> \\<F> \\<Longrightarrow> generate_topology_on \\<S> K; \\<F> \\<noteq> {}\\<rbrakk> \\<Longrightarrow> generate_topology_on \\<S> (\\<Inter>\\<F>)\"\n  by (induction \\<F> rule: finite_induct; force intro: generate_topology_on.intros)\n\nsubsection\\<open>Topology bases and sub-bases\\<close>\n\nlemma istopology_base_alt:\n   \"istopology (arbitrary union_of P) \\<longleftrightarrow>\n    (\\<forall>S T. (arbitrary union_of P) S \\<and> (arbitrary union_of P) T\n           \\<longrightarrow> (arbitrary union_of P) (S \\<inter> T))\"\n  by (simp add: istopology_def) (blast intro: arbitrary_union_of_Union)\n\nlemma istopology_base_eq:\n   \"istopology (arbitrary union_of P) \\<longleftrightarrow>\n    (\\<forall>S T. P S \\<and> P T \\<longrightarrow> (arbitrary union_of P) (S \\<inter> T))\"\n  by (simp add: istopology_base_alt arbitrary_union_of_Int_eq)\n\nlemma istopology_base:\n   \"(\\<And>S T. \\<lbrakk>P S; P T\\<rbrakk> \\<Longrightarrow> P(S \\<inter> T)) \\<Longrightarrow> istopology (arbitrary union_of P)\"\n  by (simp add: arbitrary_def istopology_base_eq union_of_inc)\n\nlemma openin_topology_base_unique:\n   \"openin X = arbitrary union_of P \\<longleftrightarrow>\n        (\\<forall>V. P V \\<longrightarrow> openin X V) \\<and> (\\<forall>U x. openin X U \\<and> x \\<in> U \\<longrightarrow> (\\<exists>V. P V \\<and> x \\<in> V \\<and> V \\<subseteq> U))\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (auto simp: union_of_def arbitrary_def)\nnext\n  assume R: ?rhs\n  then have *: \"\\<exists>\\<U>\\<subseteq>Collect P. \\<Union>\\<U> = S\" if \"openin X S\" for S\n    using that by (rule_tac x=\"{V. P V \\<and> V \\<subseteq> S}\" in exI) fastforce\n  from R show ?lhs\n    by (fastforce simp add: union_of_def arbitrary_def intro: *)\nqed\n\nlemma topology_base_unique:\n  assumes \"\\<And>S. P S \\<Longrightarrow> openin X S\"\n          \"\\<And>U x. \\<lbrakk>openin X U; x \\<in> U\\<rbrakk> \\<Longrightarrow> \\<exists>B. P B \\<and> x \\<in> B \\<and> B \\<subseteq> U\"\n  shows   \"topology (arbitrary union_of P) = X\"\nproof -\n  have \"X = topology (openin X)\"\n    by (simp add: openin_inverse)\n  also from assms have \"openin X = arbitrary union_of P\"\n    by (subst openin_topology_base_unique) auto\n  finally show ?thesis ..\nqed\n\nlemma topology_bases_eq_aux:\n   \"\\<lbrakk>(arbitrary union_of P) S;\n     \\<And>U x. \\<lbrakk>P U; x \\<in> U\\<rbrakk> \\<Longrightarrow> \\<exists>V. Q V \\<and> x \\<in> V \\<and> V \\<subseteq> U\\<rbrakk>\n        \\<Longrightarrow> (arbitrary union_of Q) S\"\n  by (metis arbitrary_union_of_alt arbitrary_union_of_idempot)\n\nlemma topology_bases_eq:\n   \"\\<lbrakk>\\<And>U x. \\<lbrakk>P U; x \\<in> U\\<rbrakk> \\<Longrightarrow> \\<exists>V. Q V \\<and> x \\<in> V \\<and> V \\<subseteq> U;\n    \\<And>V x. \\<lbrakk>Q V; x \\<in> V\\<rbrakk> \\<Longrightarrow> \\<exists>U. P U \\<and> x \\<in> U \\<and> U \\<subseteq> V\\<rbrakk>\n        \\<Longrightarrow> topology (arbitrary union_of P) =\n            topology (arbitrary union_of Q)\"\n  by (fastforce intro:  arg_cong [where f=topology]  elim: topology_bases_eq_aux)\n\nlemma istopology_subbase:\n   \"istopology (arbitrary union_of (finite intersection_of P relative_to S))\"\n  by (simp add: finite_intersection_of_Int istopology_base relative_to_Int)\n\nlemma openin_subbase:\n  \"openin (topology (arbitrary union_of (finite intersection_of B relative_to U))) S\n   \\<longleftrightarrow> (arbitrary union_of (finite intersection_of B relative_to U)) S\"\n  by (simp add: istopology_subbase topology_inverse')\n\nlemma topspace_subbase [simp]:\n   \"topspace(topology (arbitrary union_of (finite intersection_of B relative_to U))) = U\" (is \"?lhs = _\")\nproof\n  show \"?lhs \\<subseteq> U\"\n    by (metis arbitrary_union_of_relative_to openin_subbase openin_topspace relative_to_imp_subset)\n  show \"U \\<subseteq> ?lhs\"\n    by (metis arbitrary_union_of_inc finite_intersection_of_empty inf.orderE istopology_subbase \n              openin_subset relative_to_inc subset_UNIV topology_inverse')\nqed\n\nlemma minimal_topology_subbase:\n   \"\\<lbrakk>\\<And>S. P S \\<Longrightarrow> openin X S; openin X U;\n     openin(topology(arbitrary union_of (finite intersection_of P relative_to U))) S\\<rbrakk>\n    \\<Longrightarrow> openin X S\"\n  apply (simp add: istopology_subbase topology_inverse)\n  apply (simp add: union_of_def intersection_of_def relative_to_def)\n  apply (blast intro: openin_Int_Inter)\n  done\n\nlemma istopology_subbase_UNIV:\n   \"istopology (arbitrary union_of (finite intersection_of P))\"\n  by (simp add: istopology_base finite_intersection_of_Int)\n\n\nlemma generate_topology_on_eq:\n  \"generate_topology_on S = arbitrary union_of finite' intersection_of (\\<lambda>x. x \\<in> S)\" (is \"?lhs = ?rhs\")\nproof (intro ext iffI)\n  fix A\n  assume \"?lhs A\"\n  then show \"?rhs A\"\n  proof induction\n    case (Int a b)\n    then show ?case\n      by (metis (mono_tags, lifting) istopology_base_alt finite'_intersection_of_Int istopology_base)\n  next\n    case (UN K)\n    then show ?case\n      by (simp add: arbitrary_union_of_Union)\n  next\n    case (Basis s)\n    then show ?case\n      by (simp add: Sup_upper arbitrary_union_of_inc finite'_intersection_of_inc relative_to_subset)\n  qed auto\nnext\n  fix A\n  assume \"?rhs A\"\n  then obtain \\<U> where \\<U>: \"\\<And>T. T \\<in> \\<U> \\<Longrightarrow> \\<exists>\\<F>. finite' \\<F> \\<and> \\<F> \\<subseteq> S \\<and> \\<Inter>\\<F> = T\" and eq: \"A = \\<Union>\\<U>\"\n    unfolding union_of_def intersection_of_def by auto\n  show \"?lhs A\"\n    unfolding eq\n  proof (rule generate_topology_on.UN)\n    fix T\n    assume \"T \\<in> \\<U>\"\n    with \\<U> obtain \\<F> where \"finite' \\<F>\" \"\\<F> \\<subseteq> S\" \"\\<Inter>\\<F> = T\"\n      by blast\n    have \"generate_topology_on S (\\<Inter>\\<F>)\"\n    proof (rule generate_topology_on_Inter)\n      show \"finite \\<F>\" \"\\<F> \\<noteq> {}\"\n        by (auto simp: \\<open>finite' \\<F>\\<close>)\n      show \"\\<And>K. K \\<in> \\<F> \\<Longrightarrow> generate_topology_on S K\"\n        by (metis \\<open>\\<F> \\<subseteq> S\\<close> generate_topology_on.simps subset_iff)\n    qed\n    then show \"generate_topology_on S T\"\n      using \\<open>\\<Inter>\\<F> = T\\<close> by blast\n  qed\nqed\n\nlemma continuous_on_generated_topo_iff:\n  \"continuous_map T1 (topology_generated_by S) f \\<longleftrightarrow>\n      ((\\<forall>U. U \\<in> S \\<longrightarrow> openin T1 (f-`U \\<inter> topspace(T1))) \\<and> (f`(topspace T1) \\<subseteq> (\\<Union> S)))\"\nunfolding continuous_map_alt topology_generated_by_topspace\nproof (auto simp add: topology_generated_by_Basis)\n  assume H: \"\\<forall>U. U \\<in> S \\<longrightarrow> openin T1 (f -` U \\<inter> topspace T1)\"\n  fix U assume \"openin (topology_generated_by S) U\"\n  then have \"generate_topology_on S U\" by (rule openin_topology_generated_by)\n  then show \"openin T1 (f -` U \\<inter> topspace T1)\"\n  proof (induct)\n    fix a b\n    assume H: \"openin T1 (f -` a \\<inter> topspace T1)\" \"openin T1 (f -` b \\<inter> topspace T1)\"\n    have \"f -` (a \\<inter> b) \\<inter> topspace T1 = (f-`a \\<inter> topspace T1) \\<inter> (f-`b \\<inter> topspace T1)\"\n      by auto\n    then show \"openin T1 (f -` (a \\<inter> b) \\<inter> topspace T1)\" using H by auto\n  next\n    fix K\n    assume H: \"openin T1 (f -` k \\<inter> topspace T1)\" if \"k\\<in> K\" for k\n    define L where \"L = {f -` k \\<inter> topspace T1|k. k \\<in> K}\"\n    have *: \"openin T1 l\" if \"l \\<in>L\" for l using that H unfolding L_def by auto\n    have \"openin T1 (\\<Union>L)\" using openin_Union[OF *] by simp\n    moreover have \"(\\<Union>L) = (f -` \\<Union>K \\<inter> topspace T1)\" unfolding L_def by auto\n    ultimately show \"openin T1 (f -` \\<Union>K \\<inter> topspace T1)\" by simp\n  qed (auto simp add: H)\nqed\n\nlemma continuous_on_generated_topo:\n  assumes \"\\<And>U. U \\<in>S \\<Longrightarrow> openin T1 (f-`U \\<inter> topspace(T1))\"\n          \"f`(topspace T1) \\<subseteq> (\\<Union> S)\"\n  shows \"continuous_map T1 (topology_generated_by S) f\"\n  using assms continuous_on_generated_topo_iff by blast\n\n\nsubsection\\<^marker>\\<open>tag important\\<close> \\<open>Pullback topology\\<close>\n\ntext \\<open>Pulling back a topology by map gives again a topology. \\<open>subtopology\\<close> is\na special case of this notion, pulling back by the identity. We introduce the general notion as\nwe will need it to define the strong operator topology on the space of continuous linear operators,\nby pulling back the product topology on the space of all functions.\\<close>\n\ntext \\<open>\\<open>pullback_topology A f T\\<close> is the pullback of the topology \\<open>T\\<close> by the map \\<open>f\\<close> on\nthe set \\<open>A\\<close>.\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> pullback_topology::\"('a set) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b topology) \\<Rightarrow> ('a topology)\"\n  where \"pullback_topology A f T = topology (\\<lambda>S. \\<exists>U. openin T U \\<and> S = f-`U \\<inter> A)\"\n\nlemma istopology_pullback_topology:\n  \"istopology (\\<lambda>S. \\<exists>U. openin T U \\<and> S = f-`U \\<inter> A)\"\n  unfolding istopology_def proof (auto)\n  fix K assume \"\\<forall>S\\<in>K. \\<exists>U. openin T U \\<and> S = f -` U \\<inter> A\"\n  then have \"\\<exists>U. \\<forall>S\\<in>K. openin T (U S) \\<and> S = f-`(U S) \\<inter> A\"\n    by (rule bchoice)\n  then obtain U where U: \"\\<forall>S\\<in>K. openin T (U S) \\<and> S = f-`(U S) \\<inter> A\"\n    by blast\n  define V where \"V = (\\<Union>S\\<in>K. U S)\"\n  have \"openin T V\" \"\\<Union>K = f -` V \\<inter> A\" unfolding V_def using U by auto\n  then show \"\\<exists>V. openin T V \\<and> \\<Union>K = f -` V \\<inter> A\" by auto\nqed\n\nlemma openin_pullback_topology:\n  \"openin (pullback_topology A f T) S \\<longleftrightarrow> (\\<exists>U. openin T U \\<and> S = f-`U \\<inter> A)\"\nunfolding pullback_topology_def topology_inverse'[OF istopology_pullback_topology] by auto\n\nlemma topspace_pullback_topology:\n  \"topspace (pullback_topology A f T) = f-`(topspace T) \\<inter> A\"\nby (auto simp add: topspace_def openin_pullback_topology)\n\nproposition continuous_map_pullback [intro]:\n  assumes \"continuous_map T1 T2 g\"\n  shows \"continuous_map (pullback_topology A f T1) T2 (g o f)\"\nunfolding continuous_map_alt\nproof (auto)\n  fix U::\"'b set\" assume \"openin T2 U\"\n  then have \"openin T1 (g-`U \\<inter> topspace T1)\"\n    using assms unfolding continuous_map_alt by auto\n  have \"(g o f)-`U \\<inter> topspace (pullback_topology A f T1) = (g o f)-`U \\<inter> A \\<inter> f-`(topspace T1)\"\n    unfolding topspace_pullback_topology by auto\n  also have \"... = f-`(g-`U \\<inter> topspace T1) \\<inter> A \"\n    by auto\n  also have \"openin (pullback_topology A f T1) (...)\"\n    unfolding openin_pullback_topology using \\<open>openin T1 (g-`U \\<inter> topspace T1)\\<close> by auto\n  finally show \"openin (pullback_topology A f T1) ((g \\<circ> f) -` U \\<inter> topspace (pullback_topology A f T1))\"\n    by auto\nnext\n  fix x assume \"x \\<in> topspace (pullback_topology A f T1)\"\n  then have \"f x \\<in> topspace T1\"\n    unfolding topspace_pullback_topology by auto\n  then show \"g (f x) \\<in> topspace T2\"\n    using assms unfolding continuous_map_def by auto\nqed\n\nproposition continuous_map_pullback' [intro]:\n  assumes \"continuous_map T1 T2 (f o g)\" \"topspace T1 \\<subseteq> g-`A\"\n  shows \"continuous_map T1 (pullback_topology A f T2) g\"\nunfolding continuous_map_alt\nproof (auto)\n  fix U assume \"openin (pullback_topology A f T2) U\"\n  then have \"\\<exists>V. openin T2 V \\<and> U = f-`V \\<inter> A\"\n    unfolding openin_pullback_topology by auto\n  then obtain V where \"openin T2 V\" \"U = f-`V \\<inter> A\"\n    by blast\n  then have \"g -` U \\<inter> topspace T1 = g-`(f-`V \\<inter> A) \\<inter> topspace T1\"\n    by blast\n  also have \"... = (f o g)-`V \\<inter> (g-`A \\<inter> topspace T1)\"\n    by auto\n  also have \"... = (f o g)-`V \\<inter> topspace T1\"\n    using assms(2) by auto\n  also have \"openin T1 (...)\"\n    using assms(1) \\<open>openin T2 V\\<close> by auto\n  finally show \"openin T1 (g -` U \\<inter> topspace T1)\" by simp\nnext\n  fix x assume \"x \\<in> topspace T1\"\n  have \"(f o g) x \\<in> topspace T2\"\n    using assms(1) \\<open>x \\<in> topspace T1\\<close> unfolding continuous_map_def by auto\n  then have \"g x \\<in> f-`(topspace T2)\"\n    unfolding comp_def by blast\n  moreover have \"g x \\<in> A\" using assms(2) \\<open>x \\<in> topspace T1\\<close> by blast\n  ultimately show \"g x \\<in> topspace (pullback_topology A f T2)\"\n    unfolding topspace_pullback_topology by blast\nqed\nsubsection\\<open>Proper maps (not a priori assumed continuous) \\<close>\n\ndefinition proper_map\n  where\n \"proper_map X Y f \\<equiv>\n        closed_map X Y f \\<and> (\\<forall>y \\<in> topspace Y. compactin X {x \\<in> topspace X. f x = y})\"\n\nlemma proper_imp_closed_map:\n   \"proper_map X Y f \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: proper_map_def)\n\nlemma proper_map_imp_subset_topspace:\n   \"proper_map X Y f \\<Longrightarrow> f ` (topspace X) \\<subseteq> topspace Y\"\n  by (simp add: closed_map_imp_subset_topspace proper_map_def)\n\nlemma closed_injective_imp_proper_map:\n  assumes f: \"closed_map X Y f\" and inj: \"inj_on f (topspace X)\"\n  shows \"proper_map X Y f\"\n  unfolding proper_map_def\nproof (clarsimp simp: f)\n  show \"compactin X {x \\<in> topspace X. f x = y}\"\n    if \"y \\<in> topspace Y\" for y\n  proof -\n    have \"{x \\<in> topspace X. f x = y} = {} \\<or> (\\<exists>a \\<in> topspace X. {x \\<in> topspace X. f x = y} = {a})\"\n      using inj_on_eq_iff [OF inj] by auto\n    then show ?thesis\n      using that by (metis (no_types, lifting) compactin_empty compactin_sing)\n  qed\nqed\n\nlemma injective_imp_proper_eq_closed_map:\n   \"inj_on f (topspace X) \\<Longrightarrow> (proper_map X Y f \\<longleftrightarrow> closed_map X Y f)\"\n  using closed_injective_imp_proper_map proper_imp_closed_map by blast\n\nlemma homeomorphic_imp_proper_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> proper_map X Y f\"\n  by (simp add: closed_injective_imp_proper_map homeomorphic_eq_everything_map)\n\nlemma compactin_proper_map_preimage:\n  assumes f: \"proper_map X Y f\" and \"compactin Y K\"\n  shows \"compactin X {x. x \\<in> topspace X \\<and> f x \\<in> K}\"\nproof -\n  have \"f ` (topspace X) \\<subseteq> topspace Y\"\n    by (simp add: f proper_map_imp_subset_topspace)\n  have *: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> compactin X {x \\<in> topspace X. f x = y}\"\n    using f by (auto simp: proper_map_def)\n  show ?thesis\n    unfolding compactin_def\n  proof clarsimp\n    show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> {x \\<in> topspace X. f x \\<in> K} \\<subseteq> \\<Union>\\<F>\"\n      if \\<U>: \"\\<forall>U\\<in>\\<U>. openin X U\" and sub: \"{x \\<in> topspace X. f x \\<in> K} \\<subseteq> \\<Union>\\<U>\"\n      for \\<U>\n    proof -\n      have \"\\<forall>y \\<in> K. \\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U>  \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>\\<V>\"\n      proof\n        fix y\n        assume \"y \\<in> K\"\n        then have \"compactin X {x \\<in> topspace X. f x = y}\"\n          by (metis \"*\" \\<open>compactin Y K\\<close> compactin_subspace subsetD)\n        with \\<open>y \\<in> K\\<close> show \"\\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U>  \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>\\<V>\"\n          unfolding compactin_def using \\<U> sub by fastforce\n      qed\n      then obtain \\<V> where \\<V>: \"\\<And>y. y \\<in> K \\<Longrightarrow> finite (\\<V> y) \\<and> \\<V> y \\<subseteq> \\<U>  \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>(\\<V> y)\"\n        by (metis (full_types))\n      define F where \"F \\<equiv> \\<lambda>y. topspace Y - f ` (topspace X - \\<Union>(\\<V> y))\"\n      have \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> F ` K \\<and> K \\<subseteq> \\<Union>\\<F>\"\n      proof (rule compactinD [OF \\<open>compactin Y K\\<close>])\n        have \"\\<And>x. x \\<in> K \\<Longrightarrow> closedin Y (f ` (topspace X - \\<Union>(\\<V> x)))\"\n          using f unfolding proper_map_def closed_map_def\n          by (meson \\<U> \\<V> openin_Union openin_closedin_eq subsetD)\n        then show \"openin Y U\" if \"U \\<in> F ` K\" for U\n          using that by (auto simp: F_def)\n        show \"K \\<subseteq> \\<Union>(F ` K)\"\n          using \\<V> \\<open>compactin Y K\\<close> unfolding F_def compactin_def by fastforce\n      qed\n      then obtain J where \"finite J\" \"J \\<subseteq> K\" and J: \"K \\<subseteq> \\<Union>(F ` J)\"\n        by (auto simp: ex_finite_subset_image)\n      show ?thesis\n        unfolding F_def\n      proof (intro exI conjI)\n        show \"finite (\\<Union>(\\<V> ` J))\"\n          using \\<V> \\<open>J \\<subseteq> K\\<close> \\<open>finite J\\<close> by blast\n        show \"\\<Union>(\\<V> ` J) \\<subseteq> \\<U>\"\n          using \\<V> \\<open>J \\<subseteq> K\\<close> by blast\n        show \"{x \\<in> topspace X. f x \\<in> K} \\<subseteq> \\<Union>(\\<Union>(\\<V> ` J))\"\n          using J \\<open>J \\<subseteq> K\\<close> unfolding F_def by auto\n      qed\n    qed\n  qed\nqed\n\n\nlemma compact_space_proper_map_preimage:\n  assumes f: \"proper_map X Y f\" and fim: \"f ` (topspace X) = topspace Y\" and \"compact_space Y\"\n  shows \"compact_space X\"\nproof -\n  have eq: \"topspace X = {x \\<in> topspace X. f x \\<in> topspace Y}\"\n    using fim by blast\n  moreover have \"compactin Y (topspace Y)\"\n    using \\<open>compact_space Y\\<close> compact_space_def by auto\n  ultimately show ?thesis\n    unfolding compact_space_def\n    using eq f compactin_proper_map_preimage by fastforce\nqed\n\nlemma proper_map_alt:\n   \"proper_map X Y f \\<longleftrightarrow>\n    closed_map X Y f \\<and> (\\<forall>K. compactin Y K \\<longrightarrow> compactin X {x. x \\<in> topspace X \\<and> f x \\<in> K})\"\n  proof (intro iffI conjI allI impI)\n  show \"compactin X {x \\<in> topspace X. f x \\<in> K}\"\n    if \"proper_map X Y f\" and \"compactin Y K\" for K\n    using that by (simp add: compactin_proper_map_preimage)\n  show \"proper_map X Y f\"\n    if f: \"closed_map X Y f \\<and> (\\<forall>K. compactin Y K \\<longrightarrow> compactin X {x \\<in> topspace X. f x \\<in> K})\"\n  proof -\n    have \"compactin X {x \\<in> topspace X. f x = y}\" if \"y \\<in> topspace Y\" for y\n    proof -\n      have \"compactin X {x \\<in> topspace X. f x \\<in> {y}}\"\n        using f compactin_sing that by fastforce\n      then show ?thesis\n        by auto\n    qed\n    with f show ?thesis\n      by (auto simp: proper_map_def)\n  qed\nqed (simp add: proper_imp_closed_map)\n\nlemma proper_map_on_empty:\n   \"topspace X = {} \\<Longrightarrow> proper_map X Y f\"\n  by (auto simp: proper_map_def closed_map_on_empty)\n\nlemma proper_map_id [simp]:\n   \"proper_map X X id\"\nproof (clarsimp simp: proper_map_alt closed_map_id)\n  fix K\n  assume K: \"compactin X K\"\n  then have \"{a \\<in> topspace X. a \\<in> K} = K\"\n    by (simp add: compactin_subspace subset_antisym subset_iff)\n  then show \"compactin X {a \\<in> topspace X. a \\<in> K}\"\n    using K by auto\nqed\n\nlemma proper_map_compose:\n  assumes \"proper_map X Y f\" \"proper_map Y Z g\"\n  shows \"proper_map X Z (g \\<circ> f)\"\nproof -\n  have \"closed_map X Y f\" and f: \"\\<And>K. compactin Y K \\<Longrightarrow> compactin X {x \\<in> topspace X. f x \\<in> K}\"\n    and \"closed_map Y Z g\" and g: \"\\<And>K. compactin Z K \\<Longrightarrow> compactin Y {x \\<in> topspace Y. g x \\<in> K}\"\n    using assms by (auto simp: proper_map_alt)\n  show ?thesis\n    unfolding proper_map_alt\n  proof (intro conjI allI impI)\n    show \"closed_map X Z (g \\<circ> f)\"\n      using \\<open>closed_map X Y f\\<close> \\<open>closed_map Y Z g\\<close> closed_map_compose by blast\n    have \"{x \\<in> topspace X. g (f x) \\<in> K} = {x \\<in> topspace X. f x \\<in> {b \\<in> topspace Y. g b \\<in> K}}\" for K\n      using \\<open>closed_map X Y f\\<close> closed_map_imp_subset_topspace by blast\n    then show \"compactin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> K}\"\n      if \"compactin Z K\" for K\n      using f [OF g [OF that]] by auto\n  qed\nqed\n\nlemma proper_map_const:\n   \"proper_map X Y (\\<lambda>x. c) \\<longleftrightarrow> compact_space X \\<and> (topspace X = {} \\<or> closedin Y {c})\"\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    by (simp add: compact_space_topspace_empty proper_map_on_empty)\nnext\n  case False\n  have *: \"compactin X {x \\<in> topspace X. c = y}\" if \"compact_space X\" for y\n  proof (cases \"c = y\")\n    case True\n    then show ?thesis\n      using compact_space_def \\<open>compact_space X\\<close> by auto\n  qed auto\n  then show ?thesis\n    using closed_compactin closedin_subset\n    by (force simp: False proper_map_def closed_map_const compact_space_def)\nqed\n\nlemma proper_map_inclusion:\n   \"s \\<subseteq> topspace X\n        \\<Longrightarrow> proper_map (subtopology X s) X id \\<longleftrightarrow> closedin X s \\<and> (\\<forall>k. compactin X k \\<longrightarrow> compactin X (s \\<inter> k))\"\n  by (auto simp: proper_map_alt closed_map_inclusion_eq inf.absorb_iff2 Collect_conj_eq compactin_subtopology intro: closed_Int_compactin)\n\n\nsubsection\\<open>Perfect maps (proper, continuous and surjective)\\<close>\n\ndefinition perfect_map \n  where \"perfect_map X Y f \\<equiv> continuous_map X Y f \\<and> proper_map X Y f \\<and> f ` (topspace X) = topspace Y\"\n\nlemma homeomorphic_imp_perfect_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> perfect_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map homeomorphic_imp_proper_map perfect_map_def)\n\nlemma perfect_imp_quotient_map:\n   \"perfect_map X Y f \\<Longrightarrow> quotient_map X Y f\"\n  by (simp add: continuous_closed_imp_quotient_map perfect_map_def proper_map_def)\n\nlemma homeomorphic_eq_injective_perfect_map:\n   \"homeomorphic_map X Y f \\<longleftrightarrow> perfect_map X Y f \\<and> inj_on f (topspace X)\"\n  using homeomorphic_imp_perfect_map homeomorphic_map_def perfect_imp_quotient_map by blast\n\nlemma perfect_injective_eq_homeomorphic_map:\n   \"perfect_map X Y f \\<and> inj_on f (topspace X) \\<longleftrightarrow> homeomorphic_map X Y f\"\n  by (simp add: homeomorphic_eq_injective_perfect_map)\n\nlemma perfect_map_id [simp]: \"perfect_map X X id\"\n  by (simp add: homeomorphic_imp_perfect_map)\n\nlemma perfect_map_compose:\n   \"\\<lbrakk>perfect_map X Y f; perfect_map Y Z g\\<rbrakk> \\<Longrightarrow> perfect_map X Z (g \\<circ> f)\"\n  by (meson continuous_map_compose perfect_imp_quotient_map perfect_map_def proper_map_compose quotient_map_compose_eq quotient_map_def)\n\nlemma perfect_imp_continuous_map:\n   \"perfect_map X Y f \\<Longrightarrow> continuous_map X Y f\"\n  using perfect_map_def by blast\n\nlemma perfect_imp_closed_map:\n   \"perfect_map X Y f \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: perfect_map_def proper_map_def)\n\nlemma perfect_imp_proper_map:\n   \"perfect_map X Y f \\<Longrightarrow> proper_map X Y f\"\n  by (simp add: perfect_map_def)\n\nlemma perfect_imp_surjective_map:\n   \"perfect_map X Y f \\<Longrightarrow> f ` (topspace X) = topspace Y\"\n  by (simp add: perfect_map_def)\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Analysis/Abstract_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8856314723088732, "lm_q1q2_score": 0.7975375179733294}}
{"text": "(*  \n  Title:    Random_Permutations.thy\n  Author:   Manuel Eberl, TU München\n\n  Random permutations and folding over them.\n  This provides the basic theory for the concept of doing something\n  in a random order, e.g. inserting elements from a fixed set into a \n  data structure in random order.\n*)\n\nsection \\<open>Random Permutations\\<close>\n\ntheory Random_Permutations\nimports \n  \"~~/src/HOL/Probability/Probability_Mass_Function\" \n  \"HOL-Library.Multiset_Permutations\"\nbegin\n\ntext \\<open>\n  Choosing a set permutation (i.e. a distinct list with the same elements as the set)\n  uniformly at random is the same as first choosing the first element of the list\n  and then choosing the rest of the list as a permutation of the remaining set.\n\\<close>\nlemma random_permutation_of_set:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   \"pmf_of_set (permutations_of_set A) = \n             do {\n               x \\<leftarrow> pmf_of_set A;\n               xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x})); \n               return_pmf (x#xs)\n             }\" (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"permutations_of_set A = (\\<Union>x\\<in>A. (#) x ` permutations_of_set (A - {x}))\"\n    by (simp add: permutations_of_set_nonempty)\n  also from assms have \"pmf_of_set \\<dots> = ?rhs\"\n    by (subst pmf_of_set_UN[where n = \"fact (card A - 1)\"])\n       (auto simp: card_image disjoint_family_on_def map_pmf_def [symmetric] map_pmf_of_set_inj)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  A generic fold function that takes a function, an initial state, and a set \n  and chooses a random order in which it then traverses the set in the same \n  fashion as a left fold over a list.\n    We first give a recursive definition.\n\\<close>\nfunction fold_random_permutation :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b pmf\" where\n  \"fold_random_permutation f x {} = return_pmf x\"\n| \"\\<not>finite A \\<Longrightarrow> fold_random_permutation f x A = return_pmf x\"\n| \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \n     fold_random_permutation f x A = \n       pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}))\"\nby (force, simp_all)\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(_,_,A). card A)\")\n  fix A :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and x :: 'b and y :: 'a\n  assume A: \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  then have \"card A > 0\" by (simp add: card_gt_0_iff)\n  with A show \"((f, f y x, A - {y}), f, x, A) \\<in> Wellfounded.measure (\\<lambda>(_, _, A). card A)\"\n    by simp\nqed simp_all\n\n\ntext \\<open>\n  We can now show that the above recursive definition is equivalent to \n  choosing a random set permutation and folding over it (in any direction).\n\\<close>\nlemma fold_random_permutation_foldl:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set A))\"\nusing assms\nproof (induction f x A rule: fold_random_permutation.induct [case_names empty infinite remove])\n  case (remove A f x)\n  from remove \n    have \"fold_random_permutation f x A = \n            pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}))\" by simp\n  also from remove\n    have \"\\<dots> = pmf_of_set A \\<bind> (\\<lambda>a. map_pmf (foldl (\\<lambda>x y. f y x) x)\n                 (map_pmf ((#) a) (pmf_of_set (permutations_of_set (A - {a})))))\"\n      by (intro bind_pmf_cong) (simp_all add: pmf.map_comp o_def)\n  also from remove have \"\\<dots> = map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set A))\"\n    by (simp_all add: random_permutation_of_set map_bind_pmf map_pmf_def [symmetric])\n  finally show ?case .\nqed (simp_all add: pmf_of_set_singleton)\n\nlemma fold_random_permutation_foldr:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (\\<lambda>xs. foldr f xs x) (pmf_of_set (permutations_of_set A))\"\nproof -\n  have \"fold_random_permutation f x A =\n          map_pmf (foldl (\\<lambda>x y. f y x) x \\<circ> rev) (pmf_of_set (permutations_of_set A))\"\n    using assms by (subst fold_random_permutation_foldl [OF assms])\n                   (simp_all add: pmf.map_comp [symmetric] map_pmf_of_set_inj)\n  also have \"foldl (\\<lambda>x y. f y x) x \\<circ> rev = (\\<lambda>xs. foldr f xs x)\"\n    by (intro ext) (simp add: foldl_conv_foldr)\n  finally show ?thesis .\nqed\n\nlemma fold_random_permutation_fold:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (\\<lambda>xs. fold f xs x) (pmf_of_set (permutations_of_set A))\"\n  by (subst fold_random_permutation_foldl [OF assms], intro map_pmf_cong)\n     (simp_all add: foldl_conv_fold)\n     \nlemma fold_random_permutation_code [code]: \n  \"fold_random_permutation f x (set xs) =\n     map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set (set xs)))\"\n  by (simp add: fold_random_permutation_foldl)\n\ntext \\<open>\n  We now introduce a slightly generalised version of the above fold \n  operation that does not simply return the result in the end, but applies\n  a monadic bind to it.\n    This may seem somewhat arbitrary, but it is a common use case, e.g. \n  in the Social Decision Scheme of Random Serial Dictatorship, where \n  voters narrow down a set of possible winners in a random order and \n  the winner is chosen from the remaining set uniformly at random.\n\\<close>\nfunction fold_bind_random_permutation \n    :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'c pmf) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'c pmf\" where\n  \"fold_bind_random_permutation f g x {} = g x\"\n| \"\\<not>finite A \\<Longrightarrow> fold_bind_random_permutation f g x A = g x\"\n| \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \n     fold_bind_random_permutation f g x A = \n       pmf_of_set A \\<bind> (\\<lambda>a. fold_bind_random_permutation f g (f a x) (A - {a}))\"\nby (force, simp_all)\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(_,_,_,A). card A)\")\n  fix A :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and x :: 'b \n    and y :: 'a and g :: \"'b \\<Rightarrow> 'c pmf\"\n  assume A: \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  then have \"card A > 0\" by (simp add: card_gt_0_iff)\n  with A show \"((f, g, f y x, A - {y}), f, g, x, A) \\<in> Wellfounded.measure (\\<lambda>(_, _, _, A). card A)\"\n    by simp\nqed simp_all\n\ntext \\<open>\n  We now show that the recursive definition is equivalent to \n  a random fold followed by a monadic bind.\n\\<close>\nlemma fold_bind_random_permutation_altdef [code]:\n  \"fold_bind_random_permutation f g x A = fold_random_permutation f x A \\<bind> g\"\nproof (induction f x A rule: fold_random_permutation.induct [case_names empty infinite remove])\n  case (remove A f x)\n  from remove have \"pmf_of_set A \\<bind> (\\<lambda>a. fold_bind_random_permutation f g (f a x) (A - {a})) =\n                      pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}) \\<bind> g)\"\n    by (intro bind_pmf_cong) simp_all\n  with remove show ?case by (simp add: bind_return_pmf bind_assoc_pmf)\nqed (simp_all add: bind_return_pmf)\n\n\ntext \\<open>\n  We can now derive the following nice monadic representations of the \n  combined fold-and-bind:\n\\<close>\nlemma fold_bind_random_permutation_foldl:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (foldl (\\<lambda>x y. f y x) x xs)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_foldl bind_return_pmf map_pmf_def)\n\nlemma fold_bind_random_permutation_foldr:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (foldr f xs x)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_foldr bind_return_pmf map_pmf_def)\n\nlemma fold_bind_random_permutation_fold:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (fold f xs x)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_fold bind_return_pmf map_pmf_def)\n\ntext \\<open>\n  The following useful lemma allows us to swap partitioning a set w.\\,r.\\,t.\\ a \n  predicate and drawing a random permutation of that set.\n\\<close>\nlemma partition_random_permutations:\n  assumes \"finite A\"\n  shows   \"map_pmf (partition P) (pmf_of_set (permutations_of_set A)) = \n             pair_pmf (pmf_of_set (permutations_of_set {x\\<in>A. P x}))\n                      (pmf_of_set (permutations_of_set {x\\<in>A. \\<not>P x}))\" (is \"?lhs = ?rhs\")\nproof (rule pmf_eqI, clarify, goal_cases)\n  case (1 xs ys)\n  show ?case\n  proof (cases \"xs \\<in> permutations_of_set {x\\<in>A. P x} \\<and> ys \\<in> permutations_of_set {x\\<in>A. \\<not>P x}\")\n    case True\n    let ?n1 = \"card {x\\<in>A. P x}\" and ?n2 = \"card {x\\<in>A. \\<not>P x}\"\n    have card_eq: \"card A = ?n1 + ?n2\"\n    proof -\n      have \"?n1 + ?n2 = card ({x\\<in>A. P x} \\<union> {x\\<in>A. \\<not>P x})\"\n        using assms by (intro card_Un_disjoint [symmetric]) auto\n      also have \"{x\\<in>A. P x} \\<union> {x\\<in>A. \\<not>P x} = A\" by blast\n      finally show ?thesis ..\n    qed\n\n    from True have lengths [simp]: \"length xs = ?n1\" \"length ys = ?n2\"\n      by (auto intro!: length_finite_permutations_of_set)\n    have \"pmf ?lhs (xs, ys) = \n            real (card (permutations_of_set A \\<inter> partition P -` {(xs, ys)})) / fact (card A)\"\n      using assms by (auto simp: pmf_map measure_pmf_of_set)\n    also have \"partition P -` {(xs, ys)} = shuffles xs ys\" \n      using True by (intro inv_image_partition) (auto simp: permutations_of_set_def)\n    also have \"permutations_of_set A \\<inter> shuffles xs ys = shuffles xs ys\"\n      using True distinct_disjoint_shuffles[of xs ys] \n      by (auto simp: permutations_of_set_def dest: set_shuffles)\n    also have \"card (shuffles xs ys) = length xs + length ys choose length xs\"\n      using True by (intro card_disjoint_shuffles) (auto simp: permutations_of_set_def)\n    also have \"length xs + length ys = card A\" by (simp add: card_eq)\n    also have \"real (card A choose length xs) = fact (card A) / (fact ?n1 * fact (card A - ?n1))\"\n      by (subst binomial_fact) (auto intro!: card_mono assms)\n    also have \"\\<dots> / fact (card A) = 1 / (fact ?n1 * fact ?n2)\"\n      by (simp add: field_split_simps card_eq)\n    also have \"\\<dots> = pmf ?rhs (xs, ys)\" using True assms by (simp add: pmf_pair)\n    finally show ?thesis .\n  next\n    case False\n    hence *: \"xs \\<notin> permutations_of_set {x\\<in>A. P x} \\<or> ys \\<notin> permutations_of_set {x\\<in>A. \\<not>P x}\" by blast\n    hence eq: \"permutations_of_set A \\<inter> (partition P -` {(xs, ys)}) = {}\"\n      by (auto simp: o_def permutations_of_set_def)\n    from * show ?thesis\n      by (elim disjE) (insert assms eq, simp_all add: pmf_pair pmf_map measure_pmf_of_set)\n  qed\nqed\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Probability/Random_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.8856314632529872, "lm_q1q2_score": 0.7975375027254694}}
{"text": "(*  Author: Tobias Nipkow, 2007 *)\n\nsection \\<open>Lists as vectors\\<close>\n\ntheory ListVector\nimports List Main\nbegin\n\ntext\\<open>\\noindent\nA vector-space like structure of lists and arithmetic operations on them.\nIs only a vector space if restricted to lists of the same length.\\<close>\n\ntext\\<open>Multiplication with a scalar:\\<close>\n\nabbreviation scale :: \"('a::times) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" (infix \"*\\<^sub>s\" 70)\nwhere \"x *\\<^sub>s xs \\<equiv> map (op * x) xs\"\n\nlemma scale1[simp]: \"(1::'a::monoid_mult) *\\<^sub>s xs = xs\"\nby (induct xs) simp_all\n\nsubsection \\<open>\\<open>+\\<close> and \\<open>-\\<close>\\<close>\n\nfun zipwith0 :: \"('a::zero \\<Rightarrow> 'b::zero \\<Rightarrow> 'c) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'c list\"\nwhere\n\"zipwith0 f [] [] = []\" |\n\"zipwith0 f (x#xs) (y#ys) = f x y # zipwith0 f xs ys\" |\n\"zipwith0 f (x#xs) [] = f x 0 # zipwith0 f xs []\" |\n\"zipwith0 f [] (y#ys) = f 0 y # zipwith0 f [] ys\"\n\ninstantiation list :: (\"{zero, plus}\") plus\nbegin\n\ndefinition\n  list_add_def: \"op + = zipwith0 (op +)\"\n\ninstance ..\n\nend\n\ninstantiation list :: (\"{zero, uminus}\") uminus\nbegin\n\ndefinition\n  list_uminus_def: \"uminus = map uminus\"\n\ninstance ..\n\nend\n\ninstantiation list :: (\"{zero,minus}\") minus\nbegin\n\ndefinition\n  list_diff_def: \"op - = zipwith0 (op -)\"\n\ninstance ..\n\nend\n\nlemma zipwith0_Nil[simp]: \"zipwith0 f [] ys = map (f 0) ys\"\nby(induct ys) simp_all\n\nlemma list_add_Nil[simp]: \"[] + xs = (xs::'a::monoid_add list)\"\nby (induct xs) (auto simp:list_add_def)\n\nlemma list_add_Nil2[simp]: \"xs + [] = (xs::'a::monoid_add list)\"\nby (induct xs) (auto simp:list_add_def)\n\nlemma list_add_Cons[simp]: \"(x#xs) + (y#ys) = (x+y)#(xs+ys)\"\nby(auto simp:list_add_def)\n\nlemma list_diff_Nil[simp]: \"[] - xs = -(xs::'a::group_add list)\"\nby (induct xs) (auto simp:list_diff_def list_uminus_def)\n\nlemma list_diff_Nil2[simp]: \"xs - [] = (xs::'a::group_add list)\"\nby (induct xs) (auto simp:list_diff_def)\n\nlemma list_diff_Cons_Cons[simp]: \"(x#xs) - (y#ys) = (x-y)#(xs-ys)\"\nby (induct xs) (auto simp:list_diff_def)\n\nlemma list_uminus_Cons[simp]: \"-(x#xs) = (-x)#(-xs)\"\nby (induct xs) (auto simp:list_uminus_def)\n\nlemma self_list_diff:\n  \"xs - xs = replicate (length(xs::'a::group_add list)) 0\"\nby(induct xs) simp_all\n\nlemma list_add_assoc: fixes xs :: \"'a::monoid_add list\"\nshows \"(xs+ys)+zs = xs+(ys+zs)\"\napply(induct xs arbitrary: ys zs)\n apply simp\napply(case_tac ys)\n apply(simp)\napply(simp)\napply(case_tac zs)\n apply(simp)\napply(simp add: add.assoc)\ndone\n\nsubsection \"Inner product\"\n\ndefinition iprod :: \"'a::ring list \\<Rightarrow> 'a list \\<Rightarrow> 'a\" (\"\\<langle>_,_\\<rangle>\") where\n\"\\<langle>xs,ys\\<rangle> = (\\<Sum>(x,y) \\<leftarrow> zip xs ys. x*y)\"\n\nlemma iprod_Nil[simp]: \"\\<langle>[],ys\\<rangle> = 0\"\nby(simp add: iprod_def)\n\nlemma iprod_Nil2[simp]: \"\\<langle>xs,[]\\<rangle> = 0\"\nby(simp add: iprod_def)\n\nlemma iprod_Cons[simp]: \"\\<langle>x#xs,y#ys\\<rangle> = x*y + \\<langle>xs,ys\\<rangle>\"\nby(simp add: iprod_def)\n\nlemma iprod0_if_coeffs0: \"\\<forall>c\\<in>set cs. c = 0 \\<Longrightarrow> \\<langle>cs,xs\\<rangle> = 0\"\napply(induct cs arbitrary:xs)\n apply simp\napply(case_tac xs) apply simp\napply auto\ndone\n\nlemma iprod_uminus[simp]: \"\\<langle>-xs,ys\\<rangle> = -\\<langle>xs,ys\\<rangle>\"\nby(simp add: iprod_def uminus_sum_list_map o_def split_def map_zip_map list_uminus_def)\n\nlemma iprod_left_add_distrib: \"\\<langle>xs + ys,zs\\<rangle> = \\<langle>xs,zs\\<rangle> + \\<langle>ys,zs\\<rangle>\"\napply(induct xs arbitrary: ys zs)\napply (simp add: o_def split_def)\napply(case_tac ys)\napply simp\napply(case_tac zs)\napply (simp)\napply(simp add: distrib_right)\ndone\n\nlemma iprod_left_diff_distrib: \"\\<langle>xs - ys, zs\\<rangle> = \\<langle>xs,zs\\<rangle> - \\<langle>ys,zs\\<rangle>\"\napply(induct xs arbitrary: ys zs)\napply (simp add: o_def split_def)\napply(case_tac ys)\napply simp\napply(case_tac zs)\napply (simp)\napply(simp add: left_diff_distrib)\ndone\n\nlemma iprod_assoc: \"\\<langle>x *\\<^sub>s xs, ys\\<rangle> = x * \\<langle>xs,ys\\<rangle>\"\napply(induct xs arbitrary: ys)\napply simp\napply(case_tac ys)\napply (simp)\napply (simp add: distrib_left mult.assoc)\ndone\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/ListVector.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240142763573, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7973783677618349}}
{"text": "(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Library Aditions for Set Cardinality\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>In this sections some additional simple lemmas about set cardinality are proved.\\<close>\n\ntheory More_Set\nimports Main\nbegin\n\ntext \\<open>Every infinite set has at least two different elements\\<close>\nlemma infinite_contains_2_elems:\n  assumes \"infinite A\"\n  shows \"\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A\"\nproof(rule ccontr)\n  assume *: \" \\<nexists>x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A\"\n  have \"\\<exists> x. x \\<in> A \"\n    using assms\n    by (simp add: ex_in_conv infinite_imp_nonempty)\n  hence \"card A = 1\"\n    using *\n    by (metis assms ex_in_conv finite_insert infinite_imp_nonempty insertCI mk_disjoint_insert)\n  thus False\n    using assms\n    by simp\nqed\n\ntext \\<open>Every infinite set has at least three different elements\\<close>\nlemma infinite_contains_3_elems:\n  assumes \"infinite A\"\n  shows \"\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A\"\nproof(rule ccontr)\n  assume \" \\<nexists>x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A\"\n  hence \"card A = 2\"\n    by (smt DiffE assms finite_insert infinite_contains_2_elems insert_Diff insert_iff)\n  thus False\n    using assms\n    by simp\nqed\n\ntext \\<open>Every set with cardinality greater than 1 has at least two different elements\\<close>\nlemma card_geq_2_iff_contains_2_elems:\n  shows \"card A \\<ge> 2 \\<longleftrightarrow> finite A \\<and> (\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A)\"\nproof\n  assume *: \"finite A \\<and> (\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A)\"\n  thus \"card A \\<ge> 2\"\n  proof -\n    obtain a :: 'a and b :: 'a where\n      f1: \"a \\<noteq> b \\<and> a \\<in> A \\<and> b \\<in> A\"\n      using *\n      by blast\n    then have \"0 < card (A - {b})\"\n      by (metis * card_eq_0_iff ex_in_conv finite_insert insertE insert_Diff neq0_conv)\n    then show ?thesis\n      using f1 by (simp add: *)\n  qed\nnext\n  assume *: \" 2 \\<le> card A\"\n  hence \"finite A\"\n    using card_infinite\n    by force\n  moreover\n  have \"\\<exists>x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A\"\n  proof(rule ccontr)\n    assume \" \\<nexists>x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A\"\n    hence \"card A \\<le> 1\"\n      by (metis One_nat_def card.empty card.insert card_mono finite.emptyI finite_insert insertCI le_SucI subsetI)\n    thus False\n      using *\n      by auto\n  qed\n  ultimately\n  show \"finite A \\<and> (\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A)\"\n    by simp\nqed\n\ntext \\<open>Set cardinality is at least 3 if and only if it contains three different elements\\<close>\nlemma card_geq_3_iff_contains_3_elems:\n  shows \"card A \\<ge> 3 \\<longleftrightarrow> finite A \\<and> (\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A)\"\nproof\n  assume *: \"card A \\<ge> 3\"\n  hence \"finite A\"\n    using card_infinite\n    by force\n  moreover\n  have \"\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A\"\n  proof(rule ccontr)\n    assume \"\\<nexists>x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A\"\n    hence \"card A \\<le> 2\"\n      by (smt DiffE Suc_leI card.remove card_geq_2_iff_contains_2_elems insert_iff le_cases not_le)\n    thus False\n      using *\n      by auto\n  qed\n  ultimately\n  show \"finite A \\<and> (\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A)\"\n    by simp\nnext\n  assume *: \"finite A \\<and> (\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A)\"\n  thus \"card A \\<ge> 3\"\n    by (smt \"*\" Suc_eq_numeral Suc_le_mono card.remove card_geq_2_iff_contains_2_elems finite_insert insert_Diff insert_iff pred_numeral_simps(3))\nqed\n\ntext \\<open>Set cardinality of A is equal to 2 if and only if A={x, y} for two different elements x and y\\<close>\nlemma card_eq_2_iff_doubleton: \"card A = 2 \\<longleftrightarrow> (\\<exists> x y. x \\<noteq> y \\<and> A = {x, y})\"\n  using card_geq_2_iff_contains_2_elems[of A]\n  using card_geq_3_iff_contains_3_elems[of A]\n  by auto (rule_tac x=x in exI, rule_tac x=y in exI, auto)\n\nlemma card_eq_2_doubleton:\n  assumes \"card A = 2\" and \"x \\<noteq> y\" and \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"A = {x, y}\"\n  using assms\n  using card_eq_2_iff_doubleton[of A]\n  by auto\n\ntext \\<open>Bijections map singleton to singleton sets\\<close>\n\nlemma bij_image_singleton:\n  shows \"\\<lbrakk>f ` A = {b}; f a = b; bij f\\<rbrakk> \\<Longrightarrow> A = {a}\"\n  by (metis (mono_tags) bij_betw_imp_inj_on image_empty image_insert inj_vimage_image_eq)\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/More_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425289753969, "lm_q2_score": 0.8670357649558006, "lm_q1q2_score": 0.7973629635960703}}
{"text": "theory Playground\n  imports Main\nbegin\n\n(*\ndatatype boolean = True | False\n\nfun conjuction :: \"boolean \\<Rightarrow> boolean \\<Rightarrow> boolean\" where\n\"conjuction True True = True\" |\n\"conjuction _    _    = False\"\n*)\n\n(*\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double x = x + x\"\n*)\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0       n = n\" |\n\"add (Suc m) n = Suc (add m n)\"\n\nlemma add_0: \"add m 0 = m\"\napply(induction m) (* Do the induction on m, thus splitting initial goal into two subgoals *)\napply(auto)        (* Try to prove subgoals automatically - i.e. using simplification *)\ndone\n\n(* NB Natural numbers and arithmetic operators are overloaded. *)\n\n(* thm add_02: add 10 0 = 10 done *)\n\n\n(* Don't qualify ambiguous names when printing, i.e. print \"lst\" constructors unqualified *)\ndeclare [[names_short]]\n\n(* NB can omit quotes around variables, e.g. datatype 'a lst = Nil | Cons 'a \"'a lst\" *)\ndatatype 'a lst = Nil | Cons \"'a\" \"'a lst\"\n\nthm lst.rec\nthm lst.rec[no_vars]\nprint_theorems\n\nfun app :: \"'a lst \\<Rightarrow> 'a lst \\<Rightarrow> 'a lst\" where\n\"app Nil         ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun reverse_go :: \"'a lst \\<Rightarrow> 'a lst \\<Rightarrow> 'a lst\" where\n\"reverse_go Nil         ys = ys\" |\n\"reverse_go (Cons x xs) ys = reverse_go xs (Cons x ys)\"\n\nfun reverse :: \"'a lst \\<Rightarrow> 'a lst\" where\n\"reverse xs = reverse_go xs Nil\"\n\nfun rev' :: \"'a lst \\<Rightarrow> 'a lst\" where\n\"rev' Nil         = Nil\" |\n\"rev' (Cons x xs) = app (rev' xs) (Cons x Nil)\"\n\n(* The \"value\" command evaluates a term *)\nvalue \"add 1 (add 2 0)\"\n\nvalue \"reverse (Cons False (Cons True (Cons True Nil)))\"\n\n(* Can also work symbolically *)\nvalue \"reverse (Cons (a + 1) (Cons b Nil))\"\n\nlemma app_Nil [simp] : \"app xs Nil = xs\"\napply(induction xs)\napply(auto)\ndone\n\nlemma app_assoc [simp] : \"app (app xs ys) zs = app xs (app ys zs)\"\napply(induction xs)\napply(auto)\ndone\n\nlemma rev'_app [simp] : \"rev' (app xs ys) = app (rev' ys) (rev' xs)\"\napply(induction xs)\napply(auto)\ndone\n\n(* Define new theorem (can be a lemma, all the same). The [simp] annotation means that it will\n   be automatically applied when using simplification to prove new theorems. *)\ntheorem rev'_rev' [simp] : \"rev' (rev' xs) = xs\"\napply(induction xs)\napply(simp)\napply(simp)\ndone\n\nvalue \"rev (rev xs)\"\n\n(* Predefined lists:\n   []                - empty list\n   x # xs            - cons x onto xs\n   [x1, x2, ..., xn] = x1 # x2 # ... # xn # []\n   xs @ ys           - append xs and ys\n\n   List library:\n   length :: 'a list \\<Rightarrow> nat\n   map    :: ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\n   hd     :: 'a list \\<Rightarrow> 'a\n   tl     :: 'a list \\<Rightarrow> 'a list\n   sum_list :: 'a list \\<Rightarrow> 'a\n   *)\n\n(* HOL is a logic of total functions, the head function (as well as hd) has some result on\n   empty list, but we don't know what it is.\n\n   Thus (head []) is underdefined rather than undefined. This means that head [] will not be\n   simplified (reduced).\n   *)\n\nfun head :: \"'a lst \\<Rightarrow> 'a\" where\n\"head (Cons x xs) = x\"\n\nvalue \"head Nil\"\n\nvalue \"f \\<circ> g\"\n\n(* Exercises 2.2 *)\n\n(* 2.1 *)\n\nvalue \"1 + (2 :: nat)\"\nvalue \"1 + (2 :: int)\"\nvalue \"1 - (2 :: nat)\"\nvalue \"1 - (2 :: int)\"\nvalue \"1 - 2\"\nvalue \"2 + 1\"\n\n(* 2.2 *)\n\ntheorem add_associative : \"add (add x y) z = add x (add y z)\"\napply(induction x)\napply(auto)\ndone\n\ntheorem add0 [simp] : \"add x 0 = x\"\napply(induction x)\napply(auto)\ndone\n\ntheorem add_nonzero_snd [simp] : \"add x (Suc y) = Suc (add x y)\"\napply(induction x)\napply(auto)\ndone\n\ntheorem add_commutative : \"add x y = add y x\"\napply(induction x)\napply(auto)\ndone\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0        = 0\" |\n\"double (Suc n) = Suc (Suc (double n))\"\n\ntheorem double_eq_add [simp] : \"double x = add x x\"\napply(induction x)\napply(simp)\napply(simp)\n(*apply(auto)*)\ndone\n\n(* 2.3 *)\n\nfun cond :: \"bool \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n\"cond True  t _ = t\" |\n\"cond False _ f = f\"\n\n(*\ntheorem cond_nonzero_left [simp] : \"(x \\<le> y) \\<and> (cond c (Suc x) x \\<le> Suc y)\"\napply(induction c)\napply(auto)\ndone\n*)\n\nlemma cond_distribute [simp] : \"cond c t f \\<le> x = cond c (t \\<le> x) (f \\<le> x)\"\napply(induction c)\napply(auto)\ndone\n\nlemma cond_same_opt_branches [simp] : \"cond c x x = x\"\napply(induction c)\napply(auto)\ndone\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count x []       = 0\" |\n\"count x (y # ys) = cond (x = y) (Suc (count x ys)) (count x ys)\"\n\nvalue \"equal 1 1 :: bool\"\nvalue \"(1 :: nat) = 1\"\nvalue \"(\\<le>)\"\n(* value \"op \\<le>\" *)\n\nvalue \"equal\"\nvalue \"op = x y\"\n\ntheorem count_lt_length : \"count x xs \\<le> length xs\"\napply(induction xs)\napply(simp)\napply(simp)\ndone\n\n(* 2.4 *)\n\nfun snoc :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"snoc x []       = [x]\" |\n\"snoc x (y # ys) = y # snoc x ys\"\n\nfun reverse' :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse' []       = []\" |\n\"reverse' (x # xs) = snoc x (reverse' xs)\"\n\nlemma reverse_snoc [simp] : \"reverse' (snoc x xs) = x # reverse' xs\"\napply(induction xs)\napply(auto)\ndone\n\nvalue \"reverse' (snoc x (a # xs)) = reverse' (a # snoc x xs)\"\nvalue \"reverse' (a # snoc x xs)   = snoc a (reverse' (snoc x xs))\"\n(* by IH *)\nvalue \"snoc a (reverse' (snoc x xs)) = snoc a (x # reverse' xs)\"\nvalue \"snoc a (x # reverse' xs)      = x # snoc a (reverse' xs)\"\n\ntheorem reverse'_reverse' : \"reverse' (reverse' xs) = xs\"\napply(induction xs)\napply(auto)\ndone\n\n(* 2.5 *)\n\nfun sum_up_to :: \"nat \\<Rightarrow> nat\" where\n\"sum_up_to 0       = 0\" |\n\"sum_up_to (Suc n) = add (Suc n) (sum_up_to n)\"\n\nvalue \"sum_up_to 3\"\n\nfun mul :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mul 0       _ = 0\" |\n\"mul (Suc n) m = add m (mul n m)\"\n\nlemma add_into_div [simp] : \"add n (x div 2) = (add n (add n x)) div 2\"\napply(induction n)\napply(auto)\ndone\n\nlemma add_commutative2 [simp] : \"add x (add y z) = add y (add x z)\"\napply(induction x)\napply(auto)\ndone\n\nlemma add_mul [simp] : \"add n (mul n m) = mul n (Suc m)\"\napply(induction n)\napply(auto)\ndone\n\ntheorem sum_up_to_n : \"sum_up_to n = mul n (Suc n) div 2\"\napply(induction n)\napply(auto)\ndone\n\n(* 2.3 Type and Function Definitions *)\n\ntype_synonym string = \"char list\"\n\ndatatype ('a, 'b) three =\n    One \"'a\"\n  | Two \"'b\"\n  | Three\n\n(* case expressions are supported *)\n\nfun three_to_nat :: \"('a, 'b) three \\<Rightarrow> nat\" where\n\"three_to_nat x = (case x of\n    One _ \\<Rightarrow> 1\n  | Two _ \\<Rightarrow> 2\n  | Three \\<Rightarrow> 3\n  )\"\n\ndatatype 'a option = None | Some 'a\n\n(* NB Tuples are simulated by pairs nested to the right.\n      I.e. (a * b * c) is a shorthand for (a * (b * c)).\n\n   Can also use pretty version of *, namely \\<times>. Enter it as \\<times>.\n *)\n\nfun lookup :: \"('a * 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup []             _  = None\" |\n\"lookup ((k, v) # kvs) k' = (if k = k' then Some v else lookup kvs k')\"\n\nvalue \"lookup [(1, 2), (2, 3)] (2 :: nat) :: nat option\"\n\n(* Definitions are non-recursive functions that are not allowed to pattern-match *)\n\ndefinition sq :: \"nat \\<Rightarrow> nat\" where\n\"sq x = x + x\"\n\n(* Can also define abbreviations, which are similar to definitions but are expanded upon parsing\n   and folded back on prettyprinting.\n *)\n\n(* NB to enter \\<equiv> either leave == in ascii, enter == and complete or enter \\<equiv> and complete *)\n\nabbreviation sq' :: \"nat \\<Rightarrow> nat\" where\n\"sq' x \\<equiv> x * x\"\n\n(* Recursive functions are defined with fun keyword. They must be total and must always\n   terminate.\n\n   Every function defines it's own customized induction rule, e.g. see div2 below\n *)\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0             = 0\" |\n\"div2 (Suc 0)       = 0\" |\n\"div2 (Suc (Suc n)) = Suc (div2 n)\"\n\nthm div2.induct\n\nlemma div2_is_div : \"div2 n = n div 2\"\n(* apply customized induction rule *)\napply(induction n rule: div2.induct)\napply(auto)\ndone\n\n(* Customized induction rule is more convenient for proving properties of non-trivial functions,\n   where there's more than one equation for each constructor of input.\n *)\n\n(* If function takes several arguments then induction rule is applied like this:\n   apply(induction x1, x2, ..., xN rule: f.induct)\n  *)\n\n(* Exercises 2.3 *)\n\n(* 2.6 *)\n\ndatatype 'a tree =\n    Leaf\n  | Branch \"'a\" \"'a tree\" \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Leaf = []\" |\n\"contents (Branch x left right) = contents left @ x # contents right\"\n\nfun treesum :: \"nat tree \\<Rightarrow> nat\" where\n\"treesum Leaf = 0\" |\n\"treesum (Branch x left right) = treesum left + treesum right + x\"\n\ntheorem treesum_is_listsum : \"treesum t = sum_list (contents t)\"\napply(induction t)\napply(auto)\ndone\n\n(* Try to find out which theorems about addition were used to prove treesum_is_listsum *)\n(*\nfun my_add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"my_add 0       m = m\" |\n\"my_add (Suc n) m = Suc (my_add n m)\"\n\nfun my_listsum :: \"nat list \\<Rightarrow> nat\" where\n\"my_listsum []       = 0\" |\n\"my_listsum (x # xs) = my_add x (my_listsum xs)\"\n\nfun my_treesum :: \"nat tree \\<Rightarrow> nat\" where\n\"my_treesum Leaf = 0\" |\n\"my_treesum (Branch x left right) = my_add x (my_add (my_treesum left) (my_treesum right))\"\n\nlemma my_listsum_distributes_over_append [simp] : \"my_listsum (xs @ ys) = my_add (my_listsum xs) (my_listsum ys)\"\napply(induction xs)\napply(auto)\napply(induction ys)\napply(auto)\ndone\n\ntheorem my_treesum_is_my_listsum : \"my_treesum t = my_listsum (contents t)\"\napply(induction t)\napply(auto)\ndone\n\n*)\n\n(* 2.7 *)\n\ndatatype 'a tree2 =\n    Leaf 'a\n  | Branch 'a \"'a tree2\" \"'a tree2\"\n\nfun mirror2 :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror2 (Leaf x)              = Leaf x\" |\n\"mirror2 (Branch x left right) = Branch x (mirror2 right) (mirror2 left)\"\n\n(* NB Function is an involution if it is its own inverse, i.e. it cancels itself *)\nlemma mirror2_is_involution : \"mirror2 (mirror2 t) = t\"\napply(induction t)\napply(auto)\ndone\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order (Leaf x)              = [x]\" |\n\"pre_order (Branch x left right) = x # pre_order left @ pre_order right\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Leaf x)              = [x]\" |\n\"post_order (Branch x left right) = post_order left @ post_order right @ [x]\"\n\nvalue \"rev [1, 2, 3] :: int list\"\n\ntheorem pre_post_order : \"pre_order (mirror2 t) = rev (post_order t)\"\napply(induction t)\napply(auto)\ndone\n\n(* 2.8 *)\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse x []       = []\" |\n\"intersperse x (y # ys) = y # concat (map (\\<lambda> z. [x, z]) ys)\"\n\nlemma map_over_concat [simp] : \"map f (concat xs) = concat (map (map f) xs)\"\napply(induction xs)\napply(auto)\ndone\n\nlemma map_f_comp_list_valued_lambda [simp] : \"map f \\<circ> (\\<lambda>y. [x, y]) = (\\<lambda>y. [f x, y]) \\<circ> f\"\napply(auto)\ndone\n\ntheorem intersperse_distributes_over_map : \"map f (intersperse x xs) = intersperse (f x) (map f xs)\"\napply(induction xs)\napply(auto)\ndone\n\n\nfun itrev_helper :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"itrev_helper []       ys = ys\" |\n\"itrev_helper (x # xs) ys = itrev_helper xs (x # ys)\"\n\nfun itrev :: \"'a list \\<Rightarrow> 'a list\" where\n(*definition itrev :: \"'a list \\<Rightarrow> 'a list\" where*)\n\"itrev xs = itrev_helper xs []\"\n\n(* Cannot prove weaker statement, \"itrev_helper xs [] = rev xs\", by induction - IH would be too\n   weak to prove the step.\n\n   Can, and sometimes must, further strengthen IH by universally quantifying over free variables\n   that we're not inducting over.\n *)\nlemma itrev_helper_reverses [simp] : \"itrev_helper xs ys = rev xs @ ys\"\napply(induction xs arbitrary: ys)\napply(auto)\ndone\n\nlemma itrev_helper_reverses_alt : \"\\<forall> ys. itrev_helper xs ys = rev xs @ ys\"\napply(induction xs)\napply(auto)\ndone\n\ntheorem itrev_reverses : \"itrev xs = rev xs\"\napply(auto)\ndone\n\n(* Exercise 2.9 *)\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0       m = m\" |\n\"itadd (Suc n) m = itadd n (Suc m)\"\n\ntheorem itadd_sums : \"itadd n m = add n m\"\napply(induction n arbitrary: m)\napply(auto)\ndone\n\n(* 2.5 Simplification rules *)\n\n(* Definitions do not automatically become simplification rules.\n   OTOH functions and datatypes automatically produce some rules.\n\n   Functions produce a rule for every equation.\n\n   Datatypes produce injectivity and distinctness (of constructors) rules.\n\n   NB only real simplifications should become automatic rules - e.g.\n   distributivity should remain manual.\n\n   Simplification rules can be conditional, e.g. p(n) \\<Rightarrow> f(n) = g(n).\n   This way f(n) will be substituted by g(n) only when p(n) is provable.\n\n   Right-hand side should always simpler than left-hand side to ensure termination.\n   Termination check is undecidable and cannot be performed automatically.\n\n   For conditional rules the precondition is proved first, therefore it must be simpler\n   than rhs.\n *)\n\n(* Definitions are intended for abstract concepts, but can be expanded with\n\n     apply(simp add: definition_name_def)\n\n   for some definition definition_name.\n\n   Simplification can be temporarily undone by\n\n     apply(simp del: rule_name)\n *)\n\n(* Exercise 2.10 *)\n\ndatatype tree0 = Leaf0 | Branch0 tree0 tree0\n\nfun tree0_size :: \"tree0 \\<Rightarrow> nat\" where\n\"tree0_size Leaf0                = 1\" |\n\"tree0_size (Branch0 left right) = 1 + tree0_size left + tree0_size right\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0       t = t\" |\n\"explode (Suc n) t = explode n (Branch0 t t)\"\n\ntheorem exploded_size : \"tree0_size (explode n t) = 2^n * (tree0_size t + 1) - 1\"\napply(induction n arbitrary: t)\napply(auto)\napply(simp add: algebra_simps) (* Standard arithmetic operations properties *)\ndone\n\nthm algebra[no_vars]\nthm algebra_simps[no_vars]\n\n(* Exercise 2.11 *)\n\ndatatype exp =\n    Var\n  | Const int\n  | Add exp exp\n  | Mul exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var       v = v\" |\n\"eval (Const n) _ = n\" |\n\"eval (Add x y) v = eval x v + eval y v\" |\n\"eval (Mul x y) v = eval x v * eval y v\"\n\n(* List of coefficients *)\ntype_synonym polynomial = \"int list\"\n\nfun evalp_helper :: \"polynomial \\<Rightarrow> int \\<Rightarrow> nat \\<Rightarrow> int\" where\n\"evalp_helper []       _ _ = 0\" |\n\"evalp_helper (c # cs) v n = c * v^n + evalp_helper cs v (n + 1)\"\n\nfun evalp :: \"polynomial \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp cs v = evalp_helper cs v 0\"\n\nfun poly_add :: \"polynomial \\<Rightarrow> polynomial \\<Rightarrow> polynomial\" where\n\"poly_add []       []       = []\"     |\n\"poly_add (x # xs) []       = x # xs\" |\n\"poly_add []       (y # ys) = y # ys\" |\n\"poly_add (x # xs) (y # ys) = (x + y) # poly_add xs ys\"\n\nfun poly_shift :: \"nat \\<Rightarrow> polynomial \\<Rightarrow> polynomial\" where\n\"poly_shift 0       xs = xs\" |\n\"poly_shift (Suc n) xs = poly_shift n (0 # xs)\"\n\nfun poly_scale :: \"int \\<Rightarrow> polynomial \\<Rightarrow> polynomial\" where\n\"poly_scale c xs = map (( *) c) xs\"\n\nfun poly_mul :: \"polynomial \\<Rightarrow> nat \\<Rightarrow> polynomial \\<Rightarrow> polynomial\" where\n\"poly_mul []       _ _  = []\" |\n\"poly_mul (x # xs) n ys = poly_add (poly_scale x (poly_shift n ys)) (poly_mul xs (Suc n) ys)\"\n(*\"poly_mul (x # xs) ys = poly_add (poly_scale x ys) (poly_mul xs (poly_shift ys))\"*)\n\n\nlemma eval_shifted_poly [simp] : \"evalp_helper (poly_shift n xs) v m = evalp_helper xs v (n + m)\"\napply(induction n xs rule: poly_shift.induct)\napply(auto)\ndone\n\nfun coeffs :: \"exp \\<Rightarrow> polynomial\" where\n\"coeffs Var       = [0, 1]\"                         |\n\"coeffs (Const n) = [n]\"                            |\n\"coeffs (Add x y) = poly_add (coeffs x) (coeffs y)\" |\n\"coeffs (Mul x y) = poly_mul (coeffs x) 0 (coeffs y)\"\n\ntheorem poly_add_sums [simp] : \"evalp_helper (poly_add xs ys) v n = evalp_helper xs v n + evalp_helper ys v n\"\napply(induction xs ys arbitrary: n rule: poly_add.induct)\napply(auto simp add: algebra_simps)\ndone\n\nlemma poly_scale_scales [simp] : \"evalp_helper (map (( *) c) xs) v n = c * evalp_helper xs v n\"\napply(induction xs arbitrary: n)\napply(auto simp add: algebra_simps)\ndone\n\n(*\nvalue \"poly_mul [-1] 0 [-1]\"\nvalue \"let xs = [-1]; ys = xs; zs = poly_mul xs ys; v = -2; n = 1 in (zs, evalp_helper zs v n, evalp_helper xs v n, evalp_helper ys v n, evalp_helper xs v n * evalp_helper ys v n)\"\n*)\n\nlemma evalp_helper_nonzero_power : \"evalp_helper xs v (Suc n) = v * evalp_helper xs v n\"\napply(induction xs arbitrary: n)\napply(auto simp add: algebra_simps)\ndone\n\nlemma evalp_helper_composite_power : \"evalp_helper xs v (m + n) = v^m * evalp_helper xs v n\"\napply(induction m (*arbitrary: n*))\napply(auto simp add: evalp_helper_nonzero_power)\ndone\n\ntheorem poly_mul_multiplies [simp] : \"evalp_helper (poly_mul xs m ys) v n = evalp_helper xs v m * evalp_helper ys v n\"\napply(induction xs arbitrary: m)\napply(simp)\napply(simp)\napply(simp add: algebra_simps evalp_helper_composite_power)\ndone\n\ntheorem poly_conversion_preserves_value : \"evalp (coeffs exp) v = eval exp v\"\napply(induction exp (*arbitrary: v*))\napply(auto)\n(*apply(simp add: algebra_simps)*)\ndone\n\n\n\nnotepad\nbegin\n  fix A B :: bool\n  have \"A \\<and> B \\<longrightarrow> B \\<and> A\"\n  proof(rule impI)\n    assume it: \"A \\<and> B\"\n    show \"B \\<and> A\"\n    proof(rule conjI)\n      from it show B by(rule conjunct2)\n      from it show A by(rule conjunct1)\n    qed\n  qed\nend\n\n(* print_theorems rule impI*)\nthm impI conjunct1 conjunct2\n\nvalue \"1 # 2 # (3 :: int) # []\"\n\ndefinition xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixl \"[+]\" 35) where\n  \"xor x y \\<equiv> x \\<and> \\<not> y \\<or> \\<not> x \\<and> y\"\n\nclass number =\n  fixes add     :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<oplus>\" 70)\n    and add_inv :: \"'a \\<Rightarrow> 'a\"       (\"\\<ominus>_\" 20)\n    and add_id  :: \"'a\"             (\"\\<zero>\")\n\n    and mul     :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<otimes>\" 60)\n    and mul_inv :: \"'a \\<Rightarrow> 'a\"       (\"_\\<^sup>-\\<^sup>1\" 20)\n    and mul_id  :: \"'a\"             (\"\\<one>\")\n\n    and is_pos  :: \"'a \\<Rightarrow> bool\"     (\"_ \\<in> \\<P>\" 20)\n\n  assumes add_assoc:          \"(x \\<oplus> y) \\<oplus> z = x \\<oplus> (y \\<oplus> z)\"\n      and add_identity:       \"x \\<oplus> \\<zero> = x\"\n      and add_inverse:        \"x \\<oplus> (\\<ominus> x) = \\<zero>\"\n      and add_commutativity:  \"x \\<oplus> y = y \\<oplus> x\"\n\n      and mul_assoc:          \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n      and mul_identity:       \"x \\<otimes> \\<one> = x\"\n      and mul_inverse:        \"x \\<otimes> (x\\<^sup>-\\<^sup>1) = \\<one>\"\n      and mul_commutativity:  \"x \\<otimes> y = y \\<otimes> x\"\n\n      and distributive_law:   \"x \\<otimes> (y \\<oplus> z) = x \\<otimes> y \\<oplus> x \\<otimes> z\"\n\n      and pos_trichotomy:        \"x = \\<zero> [+] (x \\<in> \\<P>) [+] \\<not> (x \\<in> \\<P>)\"\n      and pos_closure_under_add: \"(x \\<in> \\<P>) \\<Longrightarrow> (y \\<in> \\<P>) \\<Longrightarrow> (x \\<oplus> y \\<in> \\<P>)\"\n      and pos_closure_under_mul: \"(x \\<in> \\<P>) \\<Longrightarrow> (y \\<in> \\<P>) \\<Longrightarrow> (x \\<otimes> y \\<in> \\<P>)\"\n\nbegin\nend\n\nlemma nonzero_either_pos_or_neg: \"x \\<noteq> \\<zero> \\<Longrightarrow> (x \\<in> \\<P>) [+] \\<not> (x \\<in> \\<P>)\"\n  sorry\n\nend\n", "meta": {"author": "sergv", "repo": "isabelle-playground", "sha": "ab4fc19ca9d393a63584f42bea1ca23b651babce", "save_path": "github-repos/isabelle/sergv-isabelle-playground", "path": "github-repos/isabelle/sergv-isabelle-playground/isabelle-playground-ab4fc19ca9d393a63584f42bea1ca23b651babce/Playground.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.9086179000259899, "lm_q1q2_score": 0.7972911072294329}}
{"text": "theory Poincare_Distance\n  imports Poincare_Lines_Ideal_Points Hyperbolic_Functions\nbegin\n\n(* ------------------------------------------------------------------ *)\nsection \\<open>H-distance in the Poincar\\'e model\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Informally, the \\emph{h-distance} between the two h-points is defined as the absolute value of\nthe logarithm of the cross ratio between those two points and the two ideal points.\\<close>\n\nabbreviation Re_cross_ratio where \"Re_cross_ratio z u v w \\<equiv> Re (to_complex (cross_ratio z u v w))\"\n\ndefinition calc_poincare_distance :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> real\" where\n  [simp]: \"calc_poincare_distance u i1 v i2 = abs (ln (Re_cross_ratio u i1 v i2))\"\n\ndefinition poincare_distance_pred :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> real \\<Rightarrow> bool\" where\n  [simp]: \"poincare_distance_pred u v d \\<longleftrightarrow>\n            (u = v \\<and> d = 0) \\<or> (u \\<noteq> v \\<and> (\\<forall> i1 i2. ideal_points (poincare_line u v) = {i1, i2} \\<longrightarrow> d = calc_poincare_distance u i1 v i2))\"\n\ndefinition poincare_distance :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> real\" where\n  \"poincare_distance u v = (THE d. poincare_distance_pred u v d)\"\n\ntext\\<open>We shown that the described cross-ratio is always finite,\npositive real number.\\<close>\nlemma distance_cross_ratio_real_positive:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"u \\<noteq> v\"\n  shows \"\\<forall> i1 i2. ideal_points (poincare_line u v) = {i1, i2} \\<longrightarrow> \n                  cross_ratio u i1 v i2 \\<noteq> \\<infinity>\\<^sub>h \\<and> is_real (to_complex (cross_ratio u i1 v i2)) \\<and> Re_cross_ratio u i1 v i2 > 0\" (is \"?P u v\")\nproof (rule wlog_positive_x_axis[OF assms])\n  fix x\n  assume *: \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n  hence \"x \\<noteq> -1\" \"x \\<noteq> 1\"\n    by auto\n  hence **: \"of_complex x \\<noteq> \\<infinity>\\<^sub>h\" \"of_complex x \\<noteq> 0\\<^sub>h\" \"of_complex x \\<noteq> of_complex (-1)\" \"of_complex 1 \\<noteq> of_complex x\"\n        \"of_complex x \\<in> circline_set x_axis\"\n    using *\n    unfolding circline_set_x_axis\n    by (auto simp add: of_complex_inj)\n\n  have ***:  \"0\\<^sub>h \\<noteq> of_complex (-1)\" \"0\\<^sub>h \\<noteq> of_complex 1\"\n    by (metis of_complex_zero_iff zero_neq_neg_one, simp)\n\n  have ****: \"- x - 1 \\<noteq> 0\" \"x - 1 \\<noteq> 0\"\n    using \\<open>x \\<noteq> -1\\<close> \\<open>x \\<noteq> 1\\<close>\n    by (metis add.inverse_inverse eq_iff_diff_eq_0, simp)\n\n  have \"poincare_line 0\\<^sub>h (of_complex x) = x_axis\"\n    using **\n    by (simp add: poincare_line_0_real_is_x_axis)\n  thus \"?P 0\\<^sub>h (of_complex x)\"\n    using * ** *** ****\n    using cross_ratio_not_inf[of \"0\\<^sub>h\" \"of_complex 1\" \"of_complex (-1)\" \"of_complex x\"]\n    using cross_ratio_not_inf[of \"0\\<^sub>h\" \"of_complex (-1)\" \"of_complex 1\" \"of_complex x\"]\n    using cross_ratio_real[of 0 \"-1\" x 1] cross_ratio_real[of 0 1 x \"-1\"]\n    apply (auto simp add: poincare_line_0_real_is_x_axis doubleton_eq_iff circline_set_x_axis)\n    apply (subst cross_ratio, simp_all, subst Re_complex_div_gt_0, simp, subst mult_neg_neg, simp_all)+\n    done\nnext\n  fix M u v\n  let ?Mu = \"moebius_pt M u\" and ?Mv = \"moebius_pt M v\"\n  assume *: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n            \"?P ?Mu ?Mv\"\n  show \"?P u v\"\n  proof safe\n    fix i1 i2\n    let ?cr = \"cross_ratio u i1 v i2\"\n    assume **: \"ideal_points (poincare_line u v) = {i1, i2}\"\n    have \"i1 \\<noteq> u\" \"i1 \\<noteq> v\" \"i2 \\<noteq> u\" \"i2 \\<noteq> v\" \"i1 \\<noteq> i2\"\n      using ideal_points_different[OF *(2-3), of i1 i2] ** \\<open>u \\<noteq> v\\<close>\n      by auto\n    hence \"0 < Re (to_complex ?cr) \\<and> is_real (to_complex ?cr) \\<and> ?cr \\<noteq> \\<infinity>\\<^sub>h\"\n      using * **\n      apply (erule_tac x=\"moebius_pt M i1\" in allE)\n      apply (erule_tac x=\"moebius_pt M i2\" in allE)\n      apply (subst (asm) ideal_points_poincare_line_moebius[of M u v i1 i2], simp_all)\n      done\n    thus \"0 < Re (to_complex ?cr)\" \"is_real (to_complex ?cr)\" \"?cr = \\<infinity>\\<^sub>h \\<Longrightarrow> False\"\n      by simp_all\n  qed\nqed\n\ntext\\<open>Next we can show that for every different points from the unit disc there is exactly one number\nthat satisfies the h-distance predicate.\\<close>\nlemma distance_unique:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"\\<exists>! d. poincare_distance_pred u v d\"\nproof (cases \"u = v\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  obtain i1 i2 where *: \"i1 \\<noteq> i2\" \"ideal_points (poincare_line u v) = {i1, i2}\"\n    using obtain_ideal_points[OF is_poincare_line_poincare_line] \\<open>u \\<noteq> v\\<close>\n    by blast\n  let ?d = \"calc_poincare_distance u i1 v i2\"\n  show ?thesis\n  proof (rule ex1I)\n    show \"poincare_distance_pred u v ?d\"\n      using * \\<open>u \\<noteq> v\\<close>\n    proof (simp del: calc_poincare_distance_def, safe)\n      fix i1' i2'\n      assume \"{i1, i2} = {i1', i2'}\"\n      hence **: \"(i1' = i1 \\<and> i2' = i2) \\<or> (i1' = i2 \\<and> i2' = i1)\"\n        using doubleton_eq_iff[of i1 i2 i1' i2']\n        by blast\n      have all_different: \"u \\<noteq> i1\" \"u \\<noteq> i2\" \"v \\<noteq> i1\" \"v \\<noteq> i2\" \"u \\<noteq> i1'\" \"u \\<noteq> i2'\" \"v \\<noteq> i1'\" \"v \\<noteq> i2'\" \"i1 \\<noteq> i2\"\n        using ideal_points_different[OF assms, of i1 i2] * ** \\<open>u \\<noteq> v\\<close>\n        by auto\n\n      show \"calc_poincare_distance u i1 v i2 = calc_poincare_distance u i1' v i2'\"\n      proof-\n        let ?cr = \"cross_ratio u i1 v i2\"\n        let ?cr' = \"cross_ratio u i1' v i2'\"\n\n        have \"Re (to_complex ?cr) > 0\" \"is_real (to_complex ?cr)\"\n             \"Re (to_complex ?cr') > 0\" \"is_real (to_complex ?cr')\"\n          using False distance_cross_ratio_real_positive[OF assms(1-2)] * **\n          by auto\n\n        thus ?thesis\n          using **\n          using cross_ratio_not_zero cross_ratio_not_inf all_different\n          by auto (subst cross_ratio_commute_24, subst reciprocal_real, simp_all add: ln_div)\n      qed\n    qed\n  next\n    fix d\n    assume \"poincare_distance_pred u v d\"\n    thus \"d = ?d\"\n      using * \\<open>u \\<noteq> v\\<close>\n      by auto\n  qed\nqed\n\nlemma poincare_distance_satisfies_pred [simp]:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance_pred u v (poincare_distance u v)\"\n    using distance_unique[OF assms] theI'[of \"poincare_distance_pred u v\"]\n    unfolding poincare_distance_def\n    by blast\n\nlemma poincare_distance_I:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"u \\<noteq> v\" and \"ideal_points (poincare_line u v) = {i1, i2}\"\n  shows \"poincare_distance u v = calc_poincare_distance u i1 v i2\"\n  using assms\n  using poincare_distance_satisfies_pred[OF assms(1-2)]\n  by simp\n\nlemma poincare_distance_refl [simp]:\n  assumes \"u \\<in> unit_disc\"\n  shows \"poincare_distance u u = 0\"\n  using assms\n  using poincare_distance_satisfies_pred[OF assms assms]\n  by simp\n\ntext\\<open>Unit disc preserving Möbius transformations preserve h-distance. \\<close>\nlemma unit_disc_fix_preserve_poincare_distance [simp]:\n  assumes \"unit_disc_fix M\" and \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance (moebius_pt M u) (moebius_pt M v) = poincare_distance u v\"\nproof (cases \"u = v\")\n  case True\n  have \"moebius_pt M u \\<in> unit_disc\" \"moebius_pt M v \\<in> unit_disc\"\n    using unit_disc_fix_iff[OF assms(1), symmetric] assms\n    by blast+\n  thus ?thesis\n    using assms \\<open>u = v\\<close>\n    by simp\nnext\n  case False\n  obtain i1 i2 where *: \"ideal_points (poincare_line u v) = {i1, i2}\"\n    using \\<open>u \\<noteq> v\\<close>\n    by (rule obtain_ideal_points[OF is_poincare_line_poincare_line[of u v]])\n  let ?Mu = \"moebius_pt M u\" and ?Mv = \"moebius_pt M v\" and ?Mi1 = \"moebius_pt M i1\" and ?Mi2 = \"moebius_pt M i2\"\n\n  have **: \"?Mu \\<in> unit_disc\" \"?Mv \\<in> unit_disc\"\n    using assms\n    using unit_disc_fix_iff\n    by blast+\n\n  have ***: \"?Mu \\<noteq> ?Mv\"   \n    using \\<open>u \\<noteq> v\\<close> \n    by simp\n\n  have \"poincare_distance u v = calc_poincare_distance u i1 v i2\"\n    using poincare_distance_I[OF assms(2-3) \\<open>u \\<noteq> v\\<close> *]\n    by auto\n  moreover\n  have \"unit_circle_fix M\"\n    using assms\n    by simp\n  hence ++: \"ideal_points (poincare_line ?Mu ?Mv) = {?Mi1, ?Mi2}\"\n    using \\<open>u \\<noteq> v\\<close> assms *\n    by simp\n  have \"poincare_distance ?Mu ?Mv = calc_poincare_distance ?Mu ?Mi1 ?Mv ?Mi2\"\n    by (rule poincare_distance_I[OF ** *** ++])\n  moreover\n  have \"calc_poincare_distance ?Mu ?Mi1 ?Mv ?Mi2 = calc_poincare_distance u i1 v i2\"\n    using ideal_points_different[OF assms(2-3) \\<open>u \\<noteq> v\\<close> *]\n    unfolding calc_poincare_distance_def\n    by (subst moebius_preserve_cross_ratio[symmetric], simp_all)\n  ultimately\n  show ?thesis\n    by simp\nqed\n\n\ntext\\<open>Knowing ideal points for x-axis, we can easily explicitly calculate distances.\\<close>\nlemma poincare_distance_x_axis_x_axis:\n  assumes \"x \\<in> unit_disc\" and \"y \\<in> unit_disc\" and \"x \\<in> circline_set x_axis\" and \"y \\<in> circline_set x_axis\"\n  shows \"poincare_distance x y =\n            (let x' = to_complex x; y' = to_complex y\n              in abs (ln (Re (((1 + x') * (1 - y')) / ((1 - x') * (1 + y'))))))\"\nproof-\n  obtain x' y' where *: \"x = of_complex x'\" \"y = of_complex y'\"\n    using inf_or_of_complex[of x] inf_or_of_complex[of y] \\<open>x \\<in> unit_disc\\<close> \\<open>y \\<in> unit_disc\\<close>\n    by auto\n\n  have \"cmod x' < 1\" \"cmod y' < 1\"\n    using \\<open>x \\<in> unit_disc\\<close> \\<open>y \\<in> unit_disc\\<close> *\n    by (metis unit_disc_iff_cmod_lt_1)+\n  hence **: \"x' \\<noteq> 1\" \"x' \\<noteq> 1\" \"y' \\<noteq> -1\" \"y' \\<noteq> 1\"\n    by auto\n\n  have \"1 + y' \\<noteq> 0\"\n    using **\n    by (metis add.left_cancel add_neg_numeral_special(7))\n\n  show ?thesis\n  proof (cases \"x = y\")\n    case True\n    thus ?thesis\n      using assms(1-2)\n      using unit_disc_iff_cmod_lt_1[of \"to_complex x\"] * ** `1 + y' \\<noteq> 0`\n      by auto\n      \n  next\n    case False\n    hence \"poincare_line x y = x_axis\"\n      using poincare_line_x_axis[OF assms]\n      by simp\n    hence \"ideal_points (poincare_line x y) = {of_complex (-1), of_complex 1}\"\n      by simp\n    hence \"poincare_distance x y = calc_poincare_distance x (of_complex (-1)) y (of_complex 1)\"\n      using poincare_distance_I assms \\<open>x \\<noteq> y\\<close>\n      by auto\n    also have \"... = abs (ln (Re (((x' + 1) * (y' - 1)) / ((x' - 1) * (y' + 1)))))\"\n      using * \\<open>cmod x' < 1\\<close> \\<open>cmod y' < 1\\<close>\n      by (simp, transfer, transfer, auto)\n    finally\n    show ?thesis\n      using *\n      by (metis (no_types, lifting) add.commute minus_diff_eq minus_divide_divide mult_minus_left mult_minus_right to_complex_of_complex)\n  qed\nqed\n\nlemma poincare_distance_zero_x_axis:\n  assumes \"x \\<in> unit_disc\" and \"x \\<in> circline_set x_axis\"\n  shows \"poincare_distance 0\\<^sub>h x = (let x' = to_complex x in abs (ln (Re ((1 - x') / (1 + x')))))\"\n  using assms\n  using poincare_distance_x_axis_x_axis[of \"0\\<^sub>h\" x]\n  by (simp add: Let_def)\n\nlemma poincare_distance_zero:\n  assumes \"x \\<in> unit_disc\"\n  shows \"poincare_distance 0\\<^sub>h x = (let x' = to_complex x in abs (ln (Re ((1 - cmod x') / (1 + cmod x')))))\" (is \"?P x\")\nproof (cases \"x = 0\\<^sub>h\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  show ?thesis\n  proof (rule wlog_rotation_to_positive_x_axis)\n    show \"x \\<in> unit_disc\" \"x \\<noteq> 0\\<^sub>h\" by fact+\n  next\n    fix \\<phi> u\n    assume \"u \\<in> unit_disc\" \"u \\<noteq> 0\\<^sub>h\" \"?P (moebius_pt (moebius_rotation \\<phi>) u)\"\n    thus \"?P u\"\n      using unit_disc_fix_preserve_poincare_distance[of \"moebius_rotation \\<phi>\" \"0\\<^sub>h\" u]\n      by (cases \"u = \\<infinity>\\<^sub>h\") (simp_all add: Let_def)\n  next\n    fix x\n    assume \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    thus \"?P (of_complex x)\"\n      using poincare_distance_zero_x_axis[of \"of_complex x\"]\n      by simp (auto simp add: circline_set_x_axis cmod_eq_Re complex_is_Real_iff)\n  qed\nqed\n\nlemma poincare_distance_zero_opposite [simp]:\n  assumes \"of_complex z \\<in> unit_disc\"\n  shows \"poincare_distance 0\\<^sub>h (of_complex (- z)) = poincare_distance 0\\<^sub>h (of_complex z)\"\nproof-\n  have *: \"of_complex (-z) \\<in> unit_disc\"\n    using assms\n    by auto\n  show ?thesis\n    using poincare_distance_zero[OF assms]\n    using poincare_distance_zero[OF *]\n    by simp\nqed\n\n(* ------------------------------------------------------------------ *)\nsubsection\\<open>Distance explicit formula\\<close>\n(* ------------------------------------------------------------------ *)\n\ntext\\<open>Instead of the h-distance itself, very frequently its hyperbolic cosine is analyzed.\\<close>\n\nabbreviation \"cosh_dist u v \\<equiv> cosh (poincare_distance u v)\"\n\nlemma cosh_poincare_distance_cross_ratio_average:\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\" \"ideal_points (poincare_line u v) = {i1, i2}\"\n  shows \"cosh_dist u v =\n           ((Re_cross_ratio u i1 v i2) + (Re_cross_ratio v i1 u i2)) / 2\"\nproof-\n  let ?cr = \"cross_ratio u i1 v i2\"\n  let ?crRe = \"Re (to_complex ?cr)\"\n  have \"?cr \\<noteq> \\<infinity>\\<^sub>h\" \"is_real (to_complex ?cr)\" \"?crRe > 0\" \n    using distance_cross_ratio_real_positive[OF assms(1-3)] assms(4)\n    by simp_all\n  then obtain cr where *: \"cross_ratio u i1 v i2 = of_complex cr\" \"cr \\<noteq> 0\" \"is_real cr\" \"Re cr > 0\"\n    using inf_or_of_complex[of \"cross_ratio u i1 v i2\"]\n    by (smt to_complex_of_complex zero_complex.simps(1))\n  thus ?thesis\n    using *\n    using assms cross_ratio_commute_13[of v i1 u i2]\n    unfolding poincare_distance_I[OF assms] calc_poincare_distance_def cosh_def\n    by (cases \"Re cr \\<ge> 1\")\n       (auto simp add: ln_div[of 0] exp_minus field_simps Re_divide power2_eq_square complex.expand)\nqed\n\ndefinition poincare_distance_formula' :: \"complex \\<Rightarrow> complex \\<Rightarrow> real\" where\n[simp]: \"poincare_distance_formula' u v = 1 + 2 * ((cmod (u - v))\\<^sup>2 / ((1 - (cmod u)\\<^sup>2) * (1 - (cmod v)\\<^sup>2)))\"\n\ntext\\<open>Next we show that the following formula expresses h-distance between any two h-points (note\nthat the ideal points do not figure anymore).\\<close>\n\ndefinition poincare_distance_formula :: \"complex \\<Rightarrow> complex \\<Rightarrow> real\" where\n  [simp]: \"poincare_distance_formula u v = arcosh (poincare_distance_formula' u v)\"\n\nlemma blaschke_preserve_distance_formula [simp]:\n  assumes \"of_complex k \\<in> unit_disc\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  shows \"poincare_distance_formula (to_complex (moebius_pt (blaschke k) u)) (to_complex (moebius_pt (blaschke k) v)) =\n         poincare_distance_formula (to_complex u) (to_complex v)\"\nproof (cases \"k = 0\")\n  case True\n  thus ?thesis\n    by simp\nnext\n  case False\n  obtain u' v' where *: \"u' = to_complex u\" \"v' = to_complex v\"\n    by auto\n\n  have \"cmod u' < 1\" \"cmod v' < 1\" \"cmod k < 1\"\n    using assms *\n    using inf_or_of_complex[of u] inf_or_of_complex[of v]\n    by auto\n\n  obtain nu du nv dv d kk ddu ddv where\n    **: \"nu = u' - k\" \"du = 1 - cnj k *u'\" \"nv = v' - k\" \"dv = 1 - cnj k * v'\"\n        \"d = u' - v'\" \"ddu = 1 - u'*cnj u'\" \"ddv = 1 - v'*cnj v'\" \"kk = 1 - k*cnj k\"\n    by auto\n\n  have d: \"nu*dv - nv*du = d*kk\"                          \n    by (subst **)+ (simp add: field_simps)\n  have ddu: \"du*cnj du - nu*cnj nu = ddu*kk\"\n    by (subst **)+ (simp add: field_simps)\n  have ddv: \"dv*cnj dv - nv*cnj nv = ddv*kk\"\n    by (subst **)+ (simp add: field_simps)\n\n  have \"du \\<noteq> 0\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence \"cmod (1 - cnj k * u') = 0\"\n      using \\<open>du = 1 - cnj k * u'\\<close>\n      by auto\n    hence \"cmod (cnj k * u') = 1\"\n      by auto\n    hence \"cmod k * cmod u' = 1\"\n      by auto\n    thus False\n      using \\<open>cmod k < 1\\<close> \\<open>cmod u' < 1\\<close>\n      using mult_strict_mono[of \"cmod k\" 1 \"cmod u'\" 1]\n      by simp\n  qed\n\n  have \"dv \\<noteq> 0\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence \"cmod (1 - cnj k * v') = 0\"\n      using \\<open>dv = 1 - cnj k * v'\\<close>\n      by auto\n    hence \"cmod (cnj k * v') = 1\"\n      by auto\n    hence \"cmod k * cmod v' = 1\"\n      by auto\n    thus False\n      using \\<open>cmod k < 1\\<close> \\<open>cmod v' < 1\\<close>\n      using mult_strict_mono[of \"cmod k\" 1 \"cmod v'\" 1]\n      by simp\n  qed\n\n  have \"kk \\<noteq> 0\" \n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence \"cmod (1 - k * cnj k) = 0\"\n      using \\<open>kk = 1 - k * cnj k\\<close>\n      by auto\n    hence \"cmod (k * cnj k) = 1\"\n      by auto\n    hence \"cmod k * cmod k = 1\"\n      by auto\n    thus False\n      using \\<open>cmod k < 1\\<close>\n      using mult_strict_mono[of \"cmod k\" 1 \"cmod k\" 1]\n      by simp\n  qed\n\n  note nz = \\<open>du \\<noteq> 0\\<close> \\<open>dv \\<noteq> 0\\<close> \\<open>kk \\<noteq> 0\\<close>\n\n\n  have \"nu / du - nv / dv = (nu*dv - nv*du) / (du * dv)\"              \n    using nz\n    by (simp add: field_simps)                               \n  hence \"(cmod (nu/du - nv/dv))\\<^sup>2 = cmod ((d*kk) / (du*dv) * (cnj ((d*kk) / (du*dv))))\" (is \"?lhs = _\")\n    unfolding complex_mod_mult_cnj[symmetric]\n    by (subst (asm) d) simp\n  also have \"... = cmod ((d*cnj d*kk*kk) / (du*cnj du*dv*cnj dv))\"\n    by (simp add: field_simps)\n  finally have 1: \"?lhs = cmod ((d*cnj d*kk*kk) / (du*cnj du*dv*cnj dv))\"\n    .                                                                           \n\n  have \"(1 - ((cmod nu) / (cmod du))\\<^sup>2)*(1 - ((cmod nv) / (cmod dv))\\<^sup>2) =\n        (1 - cmod((nu * cnj nu) / (du * cnj du)))*(1 - cmod((nv * cnj nv) / (dv * cnj dv)))\" (is \"?rhs = _\")\n    by (metis cmod_divide complex_mod_mult_cnj power_divide)\n  also have \"... = cmod(((du*cnj du - nu*cnj nu) / (du * cnj du)) * ((dv*cnj dv - nv*cnj nv) / (dv * cnj dv)))\"\n  proof-\n    have \"u' \\<noteq> 1 / cnj k\" \"v' \\<noteq> 1 / cnj k\"\n      using \\<open>cmod u' < 1\\<close> \\<open>cmod v' < 1\\<close> \\<open>cmod k < 1\\<close>\n      by (auto simp add: False)\n    moreover\n    have \"cmod k \\<noteq> 1\"\n      using \\<open>cmod k < 1\\<close>\n      by linarith\n    ultimately\n    have \"cmod (nu/du) < 1\" \"cmod (nv/dv) < 1\"\n      using **(1-4)\n      using unit_disc_fix_discI[OF blaschke_unit_disc_fix[OF \\<open>cmod k < 1\\<close>] \\<open>u \\<in> unit_disc\\<close>] \\<open>u' = to_complex u\\<close>\n      using unit_disc_fix_discI[OF blaschke_unit_disc_fix[OF \\<open>cmod k < 1\\<close>] \\<open>v \\<in> unit_disc\\<close>] \\<open>v' = to_complex v\\<close>\n      using inf_or_of_complex[of u] \\<open>u \\<in> unit_disc\\<close> inf_or_of_complex[of v] \\<open>v \\<in> unit_disc\\<close>\n      using moebius_pt_blaschke[of k u'] using moebius_pt_blaschke[of k v'] \n      by auto\n    hence \"(cmod (nu/du))\\<^sup>2 < 1\" \"(cmod (nv/dv))\\<^sup>2 < 1\"\n      by (simp_all add: cmod_def)\n    hence \"cmod (nu * cnj nu / (du * cnj du)) < 1\"  \"cmod (nv * cnj nv / (dv * cnj dv)) < 1\"\n      by (metis complex_mod_mult_cnj norm_divide power_divide)+\n    moreover\n    have \"is_real (nu * cnj nu / (du * cnj du))\" \"is_real (nv * cnj nv / (dv * cnj dv))\"\n      using eq_cnj_iff_real[of \"nu * cnj nu / (du * cnj du)\"]      \n      using eq_cnj_iff_real[of \"nv * cnj nv / (dv * cnj dv)\"]      \n      by (auto simp add: mult.commute)\n    moreover          \n    have \"Re (nu * cnj nu / (du * cnj du)) \\<ge> 0\"  \"Re (nv * cnj nv / (dv * cnj dv)) \\<ge> 0\"\n      using \\<open>du \\<noteq> 0\\<close> \\<open>dv \\<noteq> 0\\<close>\n      unfolding complex_mult_cnj_cmod\n      by simp_all\n    ultimately                           \n    have \"1 - cmod (nu * cnj nu / (du * cnj du)) = cmod (1 - nu * cnj nu / (du * cnj du))\"\n         \"1 - cmod (nv * cnj nv / (dv * cnj dv)) = cmod (1 - nv * cnj nv / (dv * cnj dv))\"     \n      by (simp_all add: cmod_def)\n    thus ?thesis\n      using nz\n      apply simp\n      apply (subst diff_divide_eq_iff, simp, simp)\n      apply (subst diff_divide_eq_iff, simp, simp)\n      done\n  qed    \n  also have \"... = cmod(((ddu * kk) / (du * cnj du)) * ((ddv * kk) / (dv * cnj dv)))\"\n    by (subst ddu, subst ddv, simp)\n  also have \"... = cmod((ddu*ddv*kk*kk) / (du*cnj du*dv*cnj dv))\"\n    by (simp add: field_simps)\n  finally have 2: \"?rhs = cmod((ddu*ddv*kk*kk) / (du*cnj du*dv*cnj dv))\"\n    .\n\n  have \"?lhs / ?rhs =\n       cmod ((d*cnj d*kk*kk) / (du*cnj du*dv*cnj dv)) / cmod((ddu*ddv*kk*kk) / (du*cnj du*dv*cnj dv))\"\n    by (subst 1, subst 2, simp)\n  also have \"... = cmod ((d*cnj d)/(ddu*ddv))\"\n    using nz\n    by simp\n  also have \"... = (cmod d)\\<^sup>2 / ((1 - (cmod u')\\<^sup>2)*(1 - (cmod v')\\<^sup>2))\"\n  proof-\n    have \"(cmod u')\\<^sup>2 < 1\" \"(cmod v')\\<^sup>2 < 1\"\n      using \\<open>cmod u' < 1\\<close> \\<open>cmod v' < 1\\<close>\n      by (simp_all add: cmod_def)\n    hence \"cmod (1 - u' * cnj u') = 1 - (cmod u')\\<^sup>2\" \"cmod (1 - v' * cnj v') = 1 - (cmod v')\\<^sup>2\"\n      by (auto simp add: cmod_eq_Re cmod_power2 power2_eq_square[symmetric])\n    thus ?thesis\n      using nz\n      apply (subst **)+\n      unfolding complex_mod_mult_cnj[symmetric]      \n      by simp\n  qed\n  finally\n  have 3: \"?lhs / ?rhs = (cmod d)\\<^sup>2 / ((1 - (cmod u')\\<^sup>2)*(1 - (cmod v')\\<^sup>2))\"\n    .\n\n  have \"cmod k \\<noteq> 1\" \"u' \\<noteq> 1 / cnj k\" \"v' \\<noteq> 1 / cnj k\" \"u \\<noteq> \\<infinity>\\<^sub>h\" \"v \\<noteq> \\<infinity>\\<^sub>h\"\n    using \\<open>cmod k < 1\\<close> \\<open>u \\<in> unit_disc\\<close> \\<open>v \\<in> unit_disc\\<close> * \\<open>k \\<noteq> 0\\<close> ** \\<open>kk \\<noteq> 0\\<close> nz\n    by auto\n  thus ?thesis using assms\n    using * ** 3\n    using moebius_pt_blaschke[of k u']\n    using moebius_pt_blaschke[of k v']\n    by simp\nqed\n\ntext \\<open>To prove the equivalence between the h-distance definition and the distance formula, we shall\nemploy the without loss of generality principle. Therefore, we must show that the distance formula\nis preserved by h-isometries.\\<close>\n\ntext\\<open>Rotation preserve @{term poincare_distance_formula}.\\<close>\nlemma rotation_preserve_distance_formula [simp]:\n  assumes \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  shows \"poincare_distance_formula (to_complex (moebius_pt (moebius_rotation \\<phi>) u)) (to_complex (moebius_pt (moebius_rotation \\<phi>) v)) =\n         poincare_distance_formula (to_complex u) (to_complex v)\"\n  using assms\n  using inf_or_of_complex[of u] inf_or_of_complex[of v]\n  by auto\n\ntext\\<open>Unit disc fixing Möbius preserve @{term poincare_distance_formula}.\\<close>\nlemma unit_disc_fix_preserve_distance_formula [simp]:\n  assumes \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  shows \"poincare_distance_formula (to_complex (moebius_pt M u)) (to_complex (moebius_pt M v)) =\n         poincare_distance_formula (to_complex u) (to_complex v)\" (is \"?P' u v M\")\nproof-\n  have \"\\<forall> u \\<in> unit_disc. \\<forall> v \\<in> unit_disc. ?P' u v M\" (is \"?P M\")\n  proof (rule wlog_unit_disc_fix[OF assms(1)])\n    fix k\n    assume \"cmod k < 1\"\n    hence \"of_complex k \\<in> unit_disc\"\n      by simp\n    thus  \"?P (blaschke k)\"\n      using blaschke_preserve_distance_formula\n      by simp\n  next\n    fix \\<phi>\n    show \"?P (moebius_rotation \\<phi>)\"\n      using rotation_preserve_distance_formula\n      by simp\n  next\n    fix M1 M2\n    assume *: \"?P M1\" and **: \"?P M2\"  and u11: \"unit_disc_fix M1\" \"unit_disc_fix M2\"\n    thus \"?P (M1 + M2)\"\n      by (auto simp del: poincare_distance_formula_def)\n  qed\n  thus ?thesis\n    using assms\n    by simp\nqed\n\ntext\\<open>The equivalence between the two h-distance representations.\\<close>\nlemma poincare_distance_formula:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance u v = poincare_distance_formula (to_complex u) (to_complex v)\" (is \"?P u v\")\nproof (rule wlog_x_axis)\n  fix x\n  assume *: \"is_real x\" \"0 \\<le> Re x\" \"Re x < 1\"\n  show \"?P  0\\<^sub>h (of_complex x)\" (is \"?lhs = ?rhs\")\n  proof-\n    have \"of_complex x \\<in> unit_disc\" \"of_complex x \\<in> circline_set x_axis\" \"cmod x < 1\"\n      using * cmod_eq_Re\n      by (auto simp add: circline_set_x_axis)\n    hence \"?lhs = \\<bar>ln (Re ((1 - x) / (1 + x)))\\<bar>\"\n      using poincare_distance_zero_x_axis[of \"of_complex x\"]\n      by simp\n    moreover\n    have \"?rhs = \\<bar>ln (Re ((1 - x) / (1 + x)))\\<bar>\"\n    proof-\n      let ?x = \"1 + 2 * (cmod x)\\<^sup>2 / (1 - (cmod x)\\<^sup>2)\"\n      have \"0 \\<le> 2 * (cmod x)\\<^sup>2 / (1 - (cmod x)\\<^sup>2)\"\n        by (smt \\<open>cmod x < 1\\<close> divide_nonneg_nonneg norm_ge_zero power_le_one zero_le_power2)\n      hence arcosh_real_gt: \"1 \\<le> ?x\"\n        by auto\n      have \"?rhs = arcosh ?x\"\n        by simp\n      also have \"... = ln ((1 + (cmod x)\\<^sup>2) / (1 - (cmod x)\\<^sup>2) + 2 * (cmod x) / (1 - (cmod x)\\<^sup>2))\"\n      proof-\n        have \"1 - (cmod x)\\<^sup>2 > 0\"\n          using \\<open>cmod x < 1\\<close>\n          by (smt norm_not_less_zero one_power2 power2_eq_imp_eq power_mono)\n        hence 1: \"?x = (1 + (cmod x)\\<^sup>2) / (1 - (cmod x)\\<^sup>2)\"\n          by (simp add: field_simps)\n        have 2: \"?x\\<^sup>2 - 1 = (4 * (cmod x)\\<^sup>2) / (1 - (cmod x)\\<^sup>2)\\<^sup>2\"\n          using \\<open>1 - (cmod x)\\<^sup>2 > 0\\<close>       \n          apply (subst 1)\n          unfolding power_divide\n          by (subst divide_diff_eq_iff, simp, simp add: power2_eq_square field_simps)\n        show ?thesis\n          using \\<open>1 - (cmod x)\\<^sup>2 > 0\\<close>\n          apply (subst arcosh_real_def[OF arcosh_real_gt])\n          apply (subst 2)\n          apply (subst 1)\n          apply (subst real_sqrt_divide)\n          apply (subst real_sqrt_mult)\n          apply simp\n          done\n      qed\n      also have \"... = ln (((1 + (cmod x))\\<^sup>2) / (1 - (cmod x)\\<^sup>2))\"\n        apply (subst add_divide_distrib[symmetric])\n        apply (simp add: field_simps power2_eq_square)\n        done\n      also have \"... = ln ((1 + cmod x) / (1 - (cmod x)))\"\n        using \\<open>cmod x < 1\\<close>      \n        using square_diff_square_factored[of 1 \"cmod x\"]\n        by (simp add: power2_eq_square)\n      also have \"... = \\<bar>ln (Re ((1 - x) / (1 + x)))\\<bar>\"\n      proof-\n        have *: \"Re ((1 - x) / (1 + x)) \\<le> 1\" \"Re ((1 - x) / (1 + x)) > 0\"\n          using \\<open>is_real x\\<close> \\<open>Re x \\<ge> 0\\<close> \\<open>Re x < 1\\<close>\n          using complex_is_Real_iff\n          by auto\n        hence \"\\<bar>ln (Re ((1 - x) / (1 + x)))\\<bar> = - ln (Re ((1 - x) / (1 + x)))\"\n          by auto\n        hence \"\\<bar>ln (Re ((1 - x) / (1 + x)))\\<bar> = ln (Re ((1 + x) / (1 - x)))\"\n          using ln_div[of 1 \"Re ((1 - x)/(1 + x))\"] * \\<open>is_real x\\<close>\n          by (simp add: complex_is_Real_iff)\n        moreover\n        have \"ln ((1 + cmod x) / (1 - cmod x)) = ln ((1 + Re x) / (1 - Re x))\"\n          using \\<open>Re x \\<ge> 0\\<close> \\<open>is_real x\\<close>\n          using cmod_eq_Re by auto\n        moreover\n        have \"(1 + Re x) / (1 - Re x) = Re ((1 + x) / (1 - x))\"\n          using \\<open>is_real x\\<close> \\<open>Re x < 1\\<close>\n          by (smt Re_divide_real eq_iff_diff_eq_0 minus_complex.simps one_complex.simps plus_complex.simps)\n        ultimately\n        show ?thesis\n          by simp\n      qed\n      finally\n      show ?thesis\n        .\n    qed\n    ultimately\n    show ?thesis\n      by simp\n  qed\nnext\n  fix M u v\n  assume *: \"unit_disc_fix M\"  \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n  assume \"?P (moebius_pt M u) (moebius_pt M v)\"\n  thus \"?P u v\"\n    using *(1-3)\n    by (simp del: poincare_distance_formula_def)\nnext\n  show \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n    by fact+\nqed\n\ntext\\<open>Some additional properties proved easily using the distance formula.\\<close>\n\n\ntext \\<open>@{term poincare_distance} is symmetric.\\<close>\nlemma poincare_distance_sym:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance u v = poincare_distance v u\"\n  using assms\n  using poincare_distance_formula[OF assms(1) assms(2)]\n  using poincare_distance_formula[OF assms(2) assms(1)]\n  by (simp add: mult.commute norm_minus_commute)\n\nlemma poincare_distance_formula'_ge_1:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"1 \\<le> poincare_distance_formula' (to_complex u) (to_complex v)\"\n  using unit_disc_cmod_square_lt_1[OF assms(1)] unit_disc_cmod_square_lt_1[OF assms(2)]\n  by auto\n\ntext\\<open>@{term poincare_distance} is non-negative.\\<close>\nlemma poincare_distance_ge0:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance u v \\<ge> 0\"\n  using poincare_distance_formula'_ge_1\n  unfolding poincare_distance_formula[OF assms(1) assms(2)]\n  unfolding poincare_distance_formula_def\n  unfolding poincare_distance_formula'_def\n  by (rule arcosh_ge_0, simp_all add: assms)\n\nlemma cosh_dist:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"cosh_dist u v = poincare_distance_formula' (to_complex u) (to_complex v)\"\n  using poincare_distance_formula[OF assms] poincare_distance_formula'_ge_1[OF assms]\n  by simp\n\ntext\\<open>@{term poincare_distance}  is zero only if the two points are equal.\\<close>\nlemma poincare_distance_eq_0_iff:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance u v = 0 \\<longleftrightarrow> u = v\"\n  using assms\n  apply auto\n  using poincare_distance_formula'_ge_1[OF assms]\n  using unit_disc_cmod_square_lt_1[OF assms(1)] unit_disc_cmod_square_lt_1[OF assms(2)]\n  unfolding poincare_distance_formula[OF assms(1) assms(2)]\n  unfolding poincare_distance_formula_def\n  unfolding poincare_distance_formula'_def\n  apply (subst (asm) arcosh_eq_0_iff)\n  apply assumption\n  apply (simp add: unit_disc_to_complex_inj)\n  done\n\ntext\\<open>Conjugate preserve @{term poincare_distance_formula}.\\<close>\nlemma conjugate_preserve_poincare_distance [simp]:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance (conjugate u) (conjugate v) = poincare_distance u v\"\nproof-\n  obtain u' v' where *: \"u = of_complex u'\" \"v = of_complex v'\"\n    using assms inf_or_of_complex[of u] inf_or_of_complex[of v]\n    by auto\n\n  have **: \"conjugate u \\<in> unit_disc\" \"conjugate v \\<in> unit_disc\"\n    using * assms\n    by auto\n\n  show ?thesis\n    using *\n    using poincare_distance_formula[OF assms]\n    using poincare_distance_formula[OF **]\n    by (metis complex_cnj_diff complex_mod_cnj conjugate_of_complex poincare_distance_def poincare_distance_formula'_def poincare_distance_formula_def to_complex_of_complex)\nqed\n\n(* ------------------------------------------------------------------ *)\nsubsection\\<open>Existence and uniqueness of points with a given distance\\<close>\n(* ------------------------------------------------------------------ *)\n\nlemma ex_x_axis_poincare_distance_negative':\n  fixes d :: real\n  assumes \"d \\<ge> 0\"\n  shows \"let z = (1 - exp d) / (1 + exp d)\n          in is_real z \\<and> Re z \\<le> 0 \\<and> Re z > -1 \\<and>\n              of_complex z \\<in> unit_disc \\<and> of_complex z \\<in> circline_set x_axis \\<and>\n              poincare_distance 0\\<^sub>h (of_complex z) = d\"\nproof-\n  have \"exp d \\<ge> 1\"\n    using assms\n    using one_le_exp_iff[of d, symmetric]\n    by blast\n\n  hence \"1 + exp d \\<noteq> 0\"\n    by linarith\n\n  let ?z = \"(1 - exp d) / (1 + exp d)\"\n\n  have \"?z \\<le> 0\"\n    using \\<open>exp d \\<ge> 1\\<close>\n    by (simp add: divide_nonpos_nonneg)\n\n  moreover\n\n  have \"?z > -1\"\n    using exp_gt_zero[of d]\n    by (smt divide_less_eq_1_neg nonzero_minus_divide_right)\n\n  moreover\n\n  hence \"abs ?z < 1\"\n    using \\<open>?z \\<le> 0\\<close>\n    by simp\n  hence \"cmod ?z < 1\"\n    by (metis norm_of_real)\n  hence \"of_complex ?z \\<in> unit_disc\"\n    by simp\n\n  moreover\n  have \"of_complex ?z \\<in> circline_set x_axis\"\n    unfolding circline_set_x_axis\n    by simp\n\n  moreover\n  have \"(1 - ?z) / (1 + ?z) = exp d\"\n  proof-\n    have \"1 + ?z = 2 / (1 + exp d)\"\n      using \\<open>1 + exp d \\<noteq> 0\\<close>\n      by (subst add_divide_eq_iff, auto)\n    moreover\n    have \"1 - ?z = 2 * exp d / (1 + exp d)\"\n      using \\<open>1 + exp d \\<noteq> 0\\<close>\n      by (subst diff_divide_eq_iff, auto)\n    ultimately\n    show ?thesis\n      using \\<open>1 + exp d \\<noteq> 0\\<close>\n      by simp\n  qed\n\n  ultimately\n  show ?thesis\n    using poincare_distance_zero_x_axis[of \"of_complex ?z\"]\n    using \\<open>d \\<ge> 0\\<close> \\<open>exp d \\<ge> 1\\<close>\n    by simp (simp add: cmod_eq_Re)\nqed\n\nlemma ex_x_axis_poincare_distance_negative:\n  assumes \"d \\<ge> 0\"\n  shows \"\\<exists> z. is_real z \\<and> Re z \\<le> 0 \\<and> Re z > -1 \\<and>\n              of_complex z \\<in> unit_disc \\<and> of_complex z \\<in> circline_set x_axis \\<and>\n              poincare_distance 0\\<^sub>h (of_complex z) = d\" (is \"\\<exists> z. ?P z\")\n  using ex_x_axis_poincare_distance_negative'[OF assms]\n  unfolding Let_def\n  by blast\n\ntext\\<open>For each real number $d$ there is exactly one point on the positive x-axis such that h-distance\nbetween 0 and that point is $d$.\\<close>\nlemma unique_x_axis_poincare_distance_negative:\n  assumes \"d \\<ge> 0\"\n  shows \"\\<exists>! z. is_real z \\<and> Re z \\<le> 0 \\<and> Re z > -1 \\<and>\n              poincare_distance 0\\<^sub>h (of_complex z) = d\" (is \"\\<exists>! z. ?P z\")\nproof-\n  let ?z = \"(1 - exp d) / (1 + exp d)\"\n\n  have \"?P ?z\"\n    using ex_x_axis_poincare_distance_negative'[OF assms]\n    unfolding Let_def\n    by blast\n\n  moreover\n\n  have \"\\<forall> z'. ?P z' \\<longrightarrow> z' = ?z\"\n  proof-\n    let ?g = \"\\<lambda> x'. \\<bar>ln (Re ((1 - x') / (1 + x')))\\<bar>\"\n    let ?A = \"{x. is_real x \\<and> Re x > -1 \\<and> Re x \\<le> 0}\"\n    have \"inj_on (poincare_distance 0\\<^sub>h \\<circ> of_complex) ?A\"\n    proof (rule comp_inj_on)\n      show \"inj_on of_complex ?A\"\n        using of_complex_inj\n        unfolding inj_on_def\n        by blast\n    next\n      show \"inj_on (poincare_distance 0\\<^sub>h) (of_complex ` ?A)\" (is \"inj_on ?f (of_complex ` ?A)\")\n      proof (subst inj_on_cong)\n        have *: \"of_complex ` ?A =\n                 {z. z \\<in> unit_disc \\<and> z \\<in> circline_set x_axis \\<and> Re (to_complex z) \\<le> 0}\" (is \"_ = ?B\")\n          by (auto simp add: cmod_eq_Re circline_set_x_axis)\n\n        fix x\n        assume \"x \\<in> of_complex ` ?A\"\n        hence \"x \\<in> ?B\"\n          using *\n          by simp\n        thus \"poincare_distance 0\\<^sub>h x = (?g \\<circ> to_complex) x\"\n          using poincare_distance_zero_x_axis\n          by (simp add: Let_def)\n      next\n        have *: \"to_complex ` of_complex ` ?A = ?A\"\n          by (auto simp add: image_iff)\n\n        show \"inj_on (?g \\<circ> to_complex) (of_complex ` ?A)\"\n        proof (rule comp_inj_on)\n          show \"inj_on to_complex (of_complex ` ?A)\"\n            unfolding inj_on_def\n            by auto\n        next\n          have \"inj_on ?g ?A\"\n            unfolding inj_on_def\n          proof(safe)\n            fix x y\n            assume hh: \"is_real x\" \"is_real y\" \"- 1 < Re x\" \"Re x \\<le> 0\"\n              \"- 1 < Re y\" \"Re y \\<le> 0\" \"\\<bar>ln (Re ((1 - x) / (1 + x)))\\<bar> = \\<bar>ln (Re ((1 - y) / (1 + y)))\\<bar>\"\n\n            have \"is_real ((1 - x)/(1 + x))\"\n              using \\<open>is_real x\\<close> div_reals[of \"1-x\" \"1+x\"]\n              by auto\n            have \"is_real ((1 - y)/(1 + y))\"\n              using \\<open>is_real y\\<close> div_reals[of \"1-y\" \"1+y\"]\n              by auto\n\n            have \"Re (1 + x) > 0\"\n              using \\<open>- 1 < Re x\\<close> by auto\n            hence \"1 + x \\<noteq> 0\"\n              by force\n            have \"Re (1 - x) \\<ge> 0\"\n              using \\<open>Re x \\<le> 0\\<close> by auto\n            hence \"Re ((1 - x)/(1 + x)) > 0\"\n              using Re_divide_real \\<open>0 < Re (1 + x)\\<close> complex_eq_if_Re_eq hh(1) hh(4) by auto\n            have \"Re(1 - x) \\<ge> Re ( 1 + x)\"\n              using hh by auto\n            hence \"Re ((1 - x)/(1 + x)) \\<ge> 1\"\n              using \\<open>Re (1 + x) > 0\\<close> \\<open>is_real ((1 - x)/(1 + x))\\<close>\n              by (smt Re_divide_real arg_0_iff hh(1) le_divide_eq_1_pos one_complex.simps(2) plus_complex.simps(2))            \n\n            have \"Re (1 + y) > 0\"\n              using \\<open>- 1 < Re y\\<close> by auto\n            hence \"1 + y \\<noteq> 0\"\n              by force\n            have \"Re (1 - y) \\<ge> 0\"\n              using \\<open>Re y \\<le> 0\\<close> by auto\n            hence \"Re ((1 - y)/(1 + y)) > 0\"\n              using Re_divide_real \\<open>0 < Re (1 + y)\\<close> complex_eq_if_Re_eq hh by auto\n            have \"Re(1 - y) \\<ge> Re ( 1 + y)\"\n              using hh by auto\n            hence \"Re ((1 - y)/(1 + y)) \\<ge> 1\"\n              using \\<open>Re (1 + y) > 0\\<close> \\<open>is_real ((1 - y)/(1 + y))\\<close>\n              by (smt Re_divide_real arg_0_iff hh le_divide_eq_1_pos one_complex.simps(2) plus_complex.simps(2))\n\n            have \"ln (Re ((1 - x) / (1 + x))) = ln (Re ((1 - y) / (1 + y)))\"\n              using \\<open>Re ((1 - y)/(1 + y)) \\<ge> 1\\<close> \\<open>Re ((1 - x)/(1 + x)) \\<ge> 1\\<close> hh\n              by auto\n            hence \"Re ((1 - x) / (1 + x)) = Re ((1 - y) / (1 + y))\"\n              using \\<open>Re ((1 - y)/(1 + y)) > 0\\<close> \\<open>Re ((1 - x)/(1 + x)) > 0\\<close>\n              by auto\n            hence \"(1 - x) / (1 + x) = (1 - y) / (1 + y)\"\n              using \\<open>is_real ((1 - y)/(1 + y))\\<close> \\<open>is_real ((1 - x)/(1 + x))\\<close>\n              using complex_eq_if_Re_eq by blast\n            hence \"(1 - x) * (1 + y) = (1 - y) * (1 + x)\"\n              using \\<open>1 + y \\<noteq> 0\\<close> \\<open>1 + x \\<noteq> 0\\<close> \n              by (simp add:field_simps)\n            thus \"x = y\"\n              by (simp add:field_simps)\n          qed            \n          thus \"inj_on ?g (to_complex ` of_complex ` ?A)\"\n            using *\n            by simp\n        qed\n      qed\n    qed\n    thus ?thesis\n      using \\<open>?P ?z\\<close>\n      unfolding inj_on_def\n      by auto\n  qed\n  ultimately\n  show ?thesis\n    by blast\nqed\n\nlemma ex_x_axis_poincare_distance_positive:\n  assumes \"d \\<ge> 0\"\n  shows \"\\<exists> z. is_real z \\<and> Re z \\<ge> 0 \\<and> Re z < 1 \\<and>\n              of_complex z \\<in> unit_disc \\<and> of_complex z \\<in> circline_set x_axis \\<and>\n              poincare_distance 0\\<^sub>h (of_complex z) = d\" (is \"\\<exists> z. is_real z \\<and> Re z \\<ge> 0 \\<and> Re z < 1 \\<and> ?P z\")\nproof-\n  obtain z where *: \"is_real z\" \"Re z \\<le> 0\" \"Re z > -1\" \"?P z\"\n    using ex_x_axis_poincare_distance_negative[OF assms]\n    by auto\n  hence **: \"of_complex z \\<in> unit_disc\" \"of_complex z \\<in> circline_set x_axis\"\n    by (auto simp add: cmod_eq_Re)\n  have \"is_real (-z) \\<and> Re (-z) \\<ge> 0 \\<and> Re (-z) < 1 \\<and> ?P (-z)\"\n    using * **\n    by (simp add: circline_set_x_axis)\n  thus ?thesis\n    by blast\nqed\n\nlemma unique_x_axis_poincare_distance_positive:\n  assumes \"d \\<ge> 0\"\n  shows \"\\<exists>! z. is_real z \\<and> Re z \\<ge> 0 \\<and> Re z < 1 \\<and>\n               poincare_distance 0\\<^sub>h (of_complex z) = d\" (is \"\\<exists>! z. is_real z \\<and> Re z \\<ge> 0 \\<and> Re z < 1 \\<and> ?P z\")\nproof-\n  obtain z where *: \"is_real z\" \"Re z \\<le> 0\" \"Re z > -1\" \"?P z\"\n    using unique_x_axis_poincare_distance_negative[OF assms]\n    by auto\n  hence **: \"of_complex z \\<in> unit_disc\" \"of_complex z \\<in> circline_set x_axis\"\n    by (auto simp add: cmod_eq_Re circline_set_x_axis)\n  show ?thesis\n  proof\n    show \"is_real (-z) \\<and> Re (-z) \\<ge> 0 \\<and> Re (-z) < 1 \\<and> ?P (-z)\"\n      using * **\n      by simp\n  next\n    fix z'\n    assume \"is_real z' \\<and> Re z' \\<ge> 0 \\<and> Re z' < 1 \\<and> ?P z'\"\n    hence \"is_real (-z') \\<and> Re (-z') \\<le> 0 \\<and> Re (-z') > -1 \\<and> ?P (-z')\"\n      by (auto simp add: circline_set_x_axis cmod_eq_Re)\n    hence \"-z' = z\"\n      using unique_x_axis_poincare_distance_negative[OF assms] *\n      by blast\n    thus \"z' = -z\"\n      by auto\n  qed\nqed\n\ntext\\<open>Equal distance implies that segments are isometric - this means that congruence could be\ndefined either by two segments having the same distance or by requiring existence of an isometry\nthat maps one segment to the other.\\<close>\nlemma poincare_distance_eq_ex_moebius:\n  assumes in_disc: \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"u' \\<in> unit_disc\" and \"v' \\<in> unit_disc\"\n  assumes \"poincare_distance u v = poincare_distance u' v'\"\n  shows \"\\<exists> M. unit_disc_fix M \\<and> moebius_pt M u = u' \\<and> moebius_pt M v = v'\" (is \"?P' u v u' v'\")\nproof (cases \"u = v\")\n  case True\n  thus ?thesis\n    using assms poincare_distance_eq_0_iff[of u' v']\n    by (simp add: unit_disc_fix_transitive)\nnext\n  case False\n  have \"\\<forall> u' v'. u \\<noteq> v \\<and> u' \\<in> unit_disc \\<and> v' \\<in> unit_disc \\<and> poincare_distance u v = poincare_distance u' v' \\<longrightarrow>\n                 ?P' u' v' u v\" (is \"?P u v\")\n  proof (rule wlog_positive_x_axis[where P=\"?P\"])\n    fix x\n    assume \"is_real x\" \"0 < Re x\" \"Re x < 1\"\n    hence \"of_complex x \\<in> unit_disc\" \"of_complex x \\<in> circline_set x_axis\"\n      unfolding circline_set_x_axis\n      by (auto simp add: cmod_eq_Re)\n\n    show \"?P 0\\<^sub>h (of_complex x)\"\n    proof safe\n      fix u' v'\n      assume \"0\\<^sub>h \\<noteq> of_complex x\" and in_disc: \"u' \\<in> unit_disc\" \"v' \\<in> unit_disc\" and\n             \"poincare_distance 0\\<^sub>h (of_complex x) = poincare_distance u' v'\"\n      hence \"u' \\<noteq> v'\" \"poincare_distance u' v' > 0\"\n        using poincare_distance_eq_0_iff[of \"0\\<^sub>h\" \"of_complex x\"] \\<open>of_complex x \\<in> unit_disc\\<close>\n        using poincare_distance_ge0[of \"0\\<^sub>h\" \"of_complex x\"]\n        by auto\n      then obtain M where M: \"unit_disc_fix M\" \"moebius_pt M u' = 0\\<^sub>h\" \"moebius_pt M v' \\<in> positive_x_axis\"\n        using ex_unit_disc_fix_to_zero_positive_x_axis[of u' v'] in_disc\n        by auto\n\n      then obtain Mv' where Mv': \"moebius_pt M v' = of_complex Mv'\"\n        using inf_or_of_complex[of \"moebius_pt M v'\"] in_disc unit_disc_fix_iff[of M]\n        by (metis image_eqI inf_notin_unit_disc)\n\n      have \"moebius_pt M v' \\<in> unit_disc\"\n        using M(1) \\<open>v' \\<in> unit_disc\\<close>\n        by auto\n\n      have \"Re Mv' > 0\" \"is_real Mv'\" \"Re Mv' < 1\"\n        using M Mv' of_complex_inj \\<open>moebius_pt M v' \\<in> unit_disc\\<close>\n        unfolding positive_x_axis_def circline_set_x_axis\n        using cmod_eq_Re\n        by auto fastforce\n\n      have \"poincare_distance 0\\<^sub>h (moebius_pt M v') = poincare_distance u' v'\"\n        using M(1)\n        using in_disc\n        by (subst M(2)[symmetric], simp)\n\n      have \"Mv' = x\"\n        using \\<open>poincare_distance 0\\<^sub>h (moebius_pt M v') = poincare_distance u' v'\\<close> Mv'\n        using \\<open>poincare_distance 0\\<^sub>h (of_complex x) = poincare_distance u' v'\\<close>\n        using unique_x_axis_poincare_distance_positive[of \"poincare_distance u' v'\"]\n          \\<open>poincare_distance u' v' > 0\\<close>\n        using \\<open>Re Mv' > 0\\<close> \\<open>Re Mv' < 1\\<close> \\<open>is_real Mv'\\<close>\n        using \\<open>is_real x\\<close> \\<open>Re x > 0\\<close> \\<open>Re x < 1\\<close>\n        unfolding positive_x_axis_def\n        by auto\n\n      thus \"?P' u' v' 0\\<^sub>h (of_complex x)\"\n        using M Mv'\n        by auto\n    qed\n  next\n    show \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n      by fact+\n  next\n    fix M u v\n    let ?Mu = \"moebius_pt M u\" and ?Mv = \"moebius_pt M v\"\n    assume 1: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\" \"u \\<noteq> v\"\n    hence 2: \"?Mu \\<noteq> ?Mv\" \"?Mu \\<in> unit_disc\" \"?Mv \\<in> unit_disc\"\n      by auto\n    assume 3: \"?P (moebius_pt M u) (moebius_pt M v)\"\n    show \"?P u v\"\n    proof safe\n      fix u' v'\n      assume 4: \"u' \\<in> unit_disc\" \"v' \\<in> unit_disc\" \"poincare_distance u v = poincare_distance u' v'\"\n      hence \"poincare_distance ?Mu ?Mv = poincare_distance u v\"\n        using 1\n        by simp\n      then obtain M' where 5: \"unit_disc_fix M'\" \"moebius_pt M' u' = ?Mu\" \"moebius_pt M' v' = ?Mv\"\n        using 2 3 4\n        by auto\n      let ?M = \"(-M) + M'\"\n      have \"unit_disc_fix ?M \\<and> moebius_pt ?M u' = u \\<and> moebius_pt ?M v' = v\"\n        using 5 \\<open>unit_disc_fix M\\<close>\n        using unit_disc_fix_moebius_comp[of \"-M\" \"M'\"]\n        using unit_disc_fix_moebius_inv[of M]\n        by simp\n      thus \"\\<exists>M. unit_disc_fix M \\<and> moebius_pt M u' = u \\<and> moebius_pt M v' = v\"\n        by blast\n    qed\n  qed\n  then obtain M where \"unit_disc_fix M \\<and> moebius_pt M u' = u \\<and> moebius_pt M v' = v\"\n    using assms \\<open>u \\<noteq> v\\<close>\n    by blast\n  hence \"unit_disc_fix (-M) \\<and> moebius_pt (-M) u = u' \\<and> moebius_pt (-M) v = v'\"\n    using unit_disc_fix_moebius_inv[of M]\n    by auto\n  thus ?thesis\n    by blast\nqed\n\nlemma unique_midpoint_x_axis:\n  assumes x: \"is_real x\" \"-1 < Re x\" \"Re x < 1\" and\n          y: \"is_real y\" \"-1 < Re y\" \"Re y < 1\" and\n          \"x \\<noteq> y\"\n  shows \"\\<exists>! z. -1 < Re z \\<and> Re z < 1 \\<and> is_real z \\<and> poincare_distance (of_complex z) (of_complex x) = poincare_distance (of_complex z) (of_complex y)\" (is \"\\<exists>! z. ?R z (of_complex x) (of_complex y)\")\nproof-\n  let ?x = \"of_complex x\" and ?y = \"of_complex y\"\n  let ?P = \"\\<lambda> x y. \\<exists>! z. ?R z x y\"\n  have \"\\<forall> x. -1 < Re x \\<and> Re x < 1 \\<and> is_real x \\<and> of_complex x \\<noteq> ?y \\<longrightarrow> ?P (of_complex x) ?y\" (is \"?Q (of_complex y)\")\n  proof (rule wlog_real_zero)\n    show \"?y \\<in> unit_disc\"\n      using y\n      by (simp add: cmod_eq_Re)\n  next\n    show \"is_real (to_complex ?y)\"\n      using y\n      by simp\n  next\n    show \"?Q 0\\<^sub>h\"\n    proof (rule allI, rule impI, (erule conjE)+)\n      fix x\n      assume x: \"-1 < Re x\" \"Re x < 1\" \"is_real x\" \n      let ?x = \"of_complex x\"\n      assume \"?x \\<noteq> 0\\<^sub>h\"\n      hence \"x \\<noteq> 0\"\n        by auto\n      hence \"Re x \\<noteq> 0\"\n        using x\n        using complex_neq_0\n        by auto\n\n      have *: \"\\<forall> a. -1 < a \\<and> a < 1 \\<longrightarrow> \n                 (poincare_distance (of_complex (cor a)) ?x = poincare_distance (of_complex (cor a)) 0\\<^sub>h \\<longleftrightarrow>\n                 (Re x) * a * a - 2 * a + Re x = 0)\"\n      proof (rule allI, rule impI)\n        fix a :: real\n        assume \"-1 < a \\<and> a < 1\"\n        hence \"of_complex (cor a) \\<in> unit_disc\"\n          by auto\n        moreover\n        have \"(a - Re x)\\<^sup>2 / ((1 - a\\<^sup>2) * (1 - (Re x)\\<^sup>2)) = a\\<^sup>2 / (1 - a\\<^sup>2) \\<longleftrightarrow>\n              (Re x) * a * a - 2 * a + Re x = 0\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\n        proof-\n          have \"1 - a\\<^sup>2 \\<noteq> 0\"\n            using \\<open>-1 < a \\<and> a < 1\\<close>\n            by (metis cancel_comm_monoid_add_class.diff_cancel diff_eq_diff_less less_numeral_extra(4) power2_eq_1_iff right_minus_eq)\n          hence \"?lhs \\<longleftrightarrow> (a - Re x)\\<^sup>2 / (1 - (Re x)\\<^sup>2) = a\\<^sup>2\"\n            by (smt divide_cancel_right divide_divide_eq_left mult.commute)\n          also have \"... \\<longleftrightarrow> (a - Re x)\\<^sup>2 = a\\<^sup>2 * (1 - (Re x)\\<^sup>2)\"\n          proof-\n            have \"1 - (Re x)\\<^sup>2 \\<noteq> 0\"\n              using x\n              by (smt power2_eq_1_iff)\n            thus ?thesis\n              by (simp add: divide_eq_eq)\n          qed\n          also have \"... \\<longleftrightarrow> a\\<^sup>2 * (Re x)\\<^sup>2 - 2*a*Re x + (Re x)\\<^sup>2 = 0\"\n            by (simp add: power2_diff field_simps)\n          also have \"... \\<longleftrightarrow> Re x * (a\\<^sup>2 * Re x - 2 * a + Re x) = 0\"\n            by (simp add: power2_eq_square field_simps)\n          also have \"... \\<longleftrightarrow> ?rhs\"\n            using \\<open>Re x \\<noteq> 0\\<close>\n            by (simp add: mult.commute mult.left_commute power2_eq_square)\n          finally\n          show ?thesis\n            .\n        qed\n        moreover \n        have \"arcosh (1 + 2 * ((a - Re x)\\<^sup>2 / ((1 - a\\<^sup>2) * (1 - (Re x)\\<^sup>2)))) = arcosh (1 + 2 * a\\<^sup>2 / (1 - a\\<^sup>2)) \\<longleftrightarrow> ?lhs\"\n          using \\<open>-1 < a \\<and> a < 1\\<close> x mult_left_cancel[of \"2::real\" \"(a - Re x)\\<^sup>2 / ((1 - a\\<^sup>2) * (1 - (Re x)\\<^sup>2))\" \"a\\<^sup>2 / (1 - a\\<^sup>2)\"]\n          by (subst arcosh_eq_iff, simp_all add: square_le_1)\n        ultimately\n        show \"poincare_distance (of_complex (cor a)) (of_complex x) = poincare_distance (of_complex (cor a)) 0\\<^sub>h \\<longleftrightarrow>\n              (Re x) * a * a - 2 * a + Re x = 0\"\n          using x\n          by (auto simp add: poincare_distance_formula cmod_eq_Re)\n      qed\n\n      show \"?P ?x 0\\<^sub>h\"\n      proof\n        let ?a = \"(1 - sqrt(1 - (Re x)\\<^sup>2)) / (Re x)\"        \n        let ?b = \"(1 + sqrt(1 - (Re x)\\<^sup>2)) / (Re x)\"\n\n        have \"is_real ?a\"\n          by simp                                                       \n        moreover\n        have \"1 - (Re x)\\<^sup>2 > 0\"\n          using x\n          by (smt power2_eq_1_iff square_le_1)\n        have \"\\<bar>?a\\<bar> < 1\"\n        proof (cases \"Re x > 0\")\n          case True\n          have \"(1 - Re x)\\<^sup>2 < 1 - (Re x)\\<^sup>2\"\n            using \\<open>Re x > 0\\<close> x\n            by (simp add: power2_eq_square field_simps)\n          hence \"1 - Re x < sqrt (1 - (Re x)\\<^sup>2)\"\n            using real_less_rsqrt by fastforce\n          thus ?thesis\n            using \\<open>1 - (Re x)\\<^sup>2 > 0\\<close> \\<open>Re x > 0\\<close>\n            by simp\n        next\n          case False\n          hence \"Re x < 0\"\n            using \\<open>Re x \\<noteq> 0\\<close>\n            by simp\n\n          have \"1 + Re x > 0\"\n            using \\<open>Re x > -1\\<close>           \n            by simp\n          hence \"2*Re x + 2*Re x*Re x < 0\"\n            using \\<open>Re x < 0\\<close>\n            by (metis comm_semiring_class.distrib mult.commute mult_2_right mult_less_0_iff one_add_one zero_less_double_add_iff_zero_less_single_add)\n          hence \"(1 + Re x)\\<^sup>2 < 1 - (Re x)\\<^sup>2\"\n            by (simp add: power2_eq_square field_simps)\n          hence \"1 + Re x < sqrt (1 - (Re x)\\<^sup>2)\"\n            using \\<open>1 - (Re x)\\<^sup>2 > 0\\<close>\n            using real_less_rsqrt by blast\n          thus ?thesis\n            using \\<open>Re x < 0\\<close>\n            by (simp add: field_simps)\n        qed\n        hence \"-1 < ?a\" \"?a < 1\"\n          by linarith+\n        moreover\n        have \"(Re x) * ?a * ?a - 2 * ?a + Re x = 0\"\n          using \\<open>Re x \\<noteq> 0\\<close> \\<open>1 - (Re x)\\<^sup>2 > 0\\<close>\n          by (simp add: field_simps power2_eq_square)\n        ultimately\n        show \"-1 < Re (cor ?a) \\<and> Re (cor ?a) < 1 \\<and> is_real ?a \\<and> poincare_distance (of_complex ?a) (of_complex x) = poincare_distance (of_complex ?a) 0\\<^sub>h\"\n          using *\n          by auto\n\n        fix z\n        assume **: \"- 1 < Re z \\<and> Re z < 1 \\<and> is_real z \\<and>\n               poincare_distance (of_complex z) (of_complex x) = poincare_distance (of_complex z) 0\\<^sub>h\"\n        hence \"Re x * Re z * Re z - 2 * Re z + Re x = 0\"\n          using *[rule_format, of \"Re z\"] x\n          by auto\n        moreover \n        have \"sqrt (4 - 4 * Re x * Re x) = 2 * sqrt(1 - Re x * Re x)\"\n        proof-\n          have \"sqrt (4 - 4 * Re x * Re x) = sqrt(4 * (1 - Re x * Re x))\"\n            by simp\n          thus ?thesis\n            by (simp only: real_sqrt_mult, simp)\n        qed\n        moreover\n        have \"(2 - 2 * sqrt (1 - Re x * Re x)) / (2 * Re x) = ?a\"\n        proof-\n          have \"(2 - 2 * sqrt (1 - Re x * Re x)) / (2 * Re x) = \n               (2 * (1 - sqrt (1 - Re x * Re x))) / (2 * Re x)\"\n            by simp\n          thus ?thesis\n            by (subst (asm) mult_divide_mult_cancel_left) (auto simp add: power2_eq_square)\n        qed\n        moreover\n        have \"(2 + 2 * sqrt (1 - Re x * Re x)) / (2 * Re x) = ?b\"\n        proof-\n          have \"(2 + 2 * sqrt (1 - Re x * Re x)) / (2 * Re x) = \n               (2 * (1 + sqrt (1 - Re x * Re x))) / (2 * Re x)\"\n            by simp\n          thus ?thesis\n            by (subst (asm) mult_divide_mult_cancel_left) (auto simp add: power2_eq_square)\n        qed\n        ultimately\n        have \"Re z = ?a \\<or> Re z = ?b\"\n          using discriminant_nonneg[of \"Re x\" \"-2\" \"Re x\" \"Re z\"] discrim_def[of \"Re x\" \"-2\" \"Re x\"]\n          using \\<open>Re x \\<noteq> 0\\<close> \\<open>-1 < Re x\\<close> \\<open>Re x < 1\\<close> \\<open>1 - (Re x)\\<^sup>2 > 0\\<close>\n          by (auto simp add:power2_eq_square)    \n        have \"\\<bar>?b\\<bar> > 1\"\n        proof (cases \"Re x > 0\")\n          case True\n          have \"(Re x - 1)\\<^sup>2 < 1 - (Re x)\\<^sup>2\"\n            using \\<open>Re x > 0\\<close> x\n            by (simp add: power2_eq_square field_simps)\n          hence \"Re x - 1 < sqrt (1 - (Re x)\\<^sup>2)\"\n            using real_less_rsqrt\n            by simp\n          thus ?thesis\n            using \\<open>1 - (Re x)\\<^sup>2 > 0\\<close> \\<open>Re x > 0\\<close>\n            by simp\n        next\n          case False\n          hence \"Re x < 0\"\n            using \\<open>Re x \\<noteq> 0\\<close>\n            by simp      \n          have \"1 + Re x > 0\"\n            using \\<open>Re x > -1\\<close>\n            by simp\n          hence \"2*Re x + 2*Re x*Re x < 0\"\n            using \\<open>Re x < 0\\<close>\n            by (metis comm_semiring_class.distrib mult.commute mult_2_right mult_less_0_iff one_add_one zero_less_double_add_iff_zero_less_single_add)\n          hence \"1 - (Re x)\\<^sup>2 > (- 1 - (Re x))\\<^sup>2\"\n            by (simp add: field_simps power2_eq_square)\n          hence \"sqrt (1 - (Re x)\\<^sup>2) > -1 - Re x\"\n            using real_less_rsqrt\n            by simp\n          thus ?thesis\n            using \\<open>Re x < 0\\<close>\n            by (simp add: field_simps)\n        qed\n        hence \"?b < -1 \\<or> ?b > 1\"\n          by auto\n\n        hence \"Re z = ?a\"\n          using \\<open>Re z = ?a \\<or> Re z = ?b\\<close> **\n          by auto\n        thus \"z = ?a\"\n          using ** complex_of_real_Re\n          by fastforce\n      qed\n    qed\n  next\n    fix a u\n    let ?M = \"moebius_pt (blaschke a)\"\n    let ?Mu = \"?M u\"\n    assume \"u \\<in> unit_disc\" \"is_real a\" \"cmod a < 1\"\n    assume *: \"?Q ?Mu\"\n    show \"?Q u\"\n    proof (rule allI, rule impI, (erule conjE)+)\n      fix x                                    \n      assume x: \"-1 < Re x\" \"Re x < 1\" \"is_real x\" \"of_complex x \\<noteq> u\"\n      let ?Mx = \"?M (of_complex x)\"\n      have \"of_complex x \\<in> unit_disc\"\n        using x cmod_eq_Re\n        by auto\n      hence \"?Mx \\<in> unit_disc\"\n        using \\<open>is_real a\\<close> \\<open>cmod a < 1\\<close> blaschke_unit_disc_fix[of a]\n        using unit_disc_fix_discI\n        by blast\n      hence \"?Mx \\<noteq> \\<infinity>\\<^sub>h\"\n        by auto\n      moreover\n      have \"of_complex x \\<in> circline_set x_axis\"\n        using x\n        by auto\n      hence \"?Mx \\<in> circline_set x_axis\"\n        using blaschke_real_preserve_x_axis[OF \\<open>is_real a\\<close> \\<open>cmod a < 1\\<close>, of \"of_complex x\"]\n        by auto\n      hence \"-1 < Re (to_complex ?Mx) \\<and> Re (to_complex ?Mx) < 1 \\<and> is_real (to_complex ?Mx)\"\n        using \\<open>?Mx \\<noteq> \\<infinity>\\<^sub>h\\<close> \\<open>?Mx \\<in> unit_disc\\<close>\n        unfolding circline_set_x_axis\n        by (auto simp add: cmod_eq_Re)\n      moreover\n      have \"?Mx \\<noteq> ?Mu\"\n        using \\<open>of_complex x \\<noteq> u\\<close>\n        by simp\n      ultimately\n      have \"?P ?Mx ?Mu\"\n        using *[rule_format, of \"to_complex ?Mx\"] \\<open>?Mx \\<noteq> \\<infinity>\\<^sub>h\\<close>\n        by simp\n      then obtain Mz where\n        \"?R Mz ?Mx ?Mu\"\n        by blast\n      have \"of_complex Mz \\<in> unit_disc\" \"of_complex Mz \\<in> circline_set x_axis\"\n        using \\<open>?R Mz ?Mx ?Mu\\<close>\n        using cmod_eq_Re \n        by auto\n\n      let ?Minv = \"- (blaschke a)\"\n      let ?z = \"moebius_pt ?Minv (of_complex Mz)\"\n      have \"?z \\<in> unit_disc\"\n        using \\<open>of_complex Mz \\<in> unit_disc\\<close> \\<open>cmod a < 1\\<close>\n        by auto\n      moreover\n      have \"?z \\<in> circline_set x_axis\"\n        using \\<open>of_complex Mz \\<in> circline_set x_axis\\<close>\n        using blaschke_real_preserve_x_axis \\<open>is_real a\\<close> \\<open>cmod a < 1\\<close>\n        by fastforce\n      ultimately\n      have z1: \"-1 < Re (to_complex ?z)\" \"Re (to_complex ?z) < 1\" \"is_real (to_complex ?z)\"\n        using inf_or_of_complex[of \"?z\"]\n        unfolding circline_set_x_axis\n        by (auto simp add: cmod_eq_Re)\n      \n      have z2: \"poincare_distance ?z (of_complex x) = poincare_distance ?z u\"\n        using \\<open>?R Mz ?Mx ?Mu\\<close> \\<open>cmod a < 1\\<close> \\<open>?z \\<in> unit_disc\\<close> \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>u \\<in> unit_disc\\<close>\n        by (metis blaschke_preserve_distance_formula blaschke_unit_disc_fix moebius_pt_comp_inv_right poincare_distance_formula uminus_moebius_def unit_disc_fix_discI unit_disc_iff_cmod_lt_1)\n      show \"?P (of_complex x) u\"\n      proof\n        show \"?R (to_complex ?z) (of_complex x) u\"\n          using z1 z2 \\<open>?z \\<in> unit_disc\\<close> inf_or_of_complex[of ?z]\n          by auto\n      next\n        fix z'\n        assume \"?R z' (of_complex x) u\"\n        hence \"of_complex z' \\<in> unit_disc\" \"of_complex z' \\<in> circline_set x_axis\"\n          by (auto simp add: cmod_eq_Re)\n        let ?Mz' = \"?M (of_complex z')\"\n        have \"?Mz' \\<in> unit_disc\" \"?Mz' \\<in> circline_set x_axis\"\n          using \\<open>of_complex z' \\<in> unit_disc\\<close> \\<open>of_complex z' \\<in> circline_set x_axis\\<close> \\<open>cmod a < 1\\<close> \\<open>is_real a\\<close>\n          using  blaschke_unit_disc_fix unit_disc_fix_discI\n          using blaschke_real_preserve_x_axis circline_set_x_axis\n          by blast+\n        hence \"-1 < Re (to_complex ?Mz')\" \"Re (to_complex ?Mz') < 1\" \"is_real (to_complex ?Mz')\"\n          unfolding circline_set_x_axis\n          by (auto simp add: cmod_eq_Re)\n        moreover\n        have \"poincare_distance ?Mz' ?Mx = poincare_distance ?Mz' ?Mu\"\n          using \\<open>?R z' (of_complex x) u\\<close>\n          using \\<open>cmod a < 1\\<close> \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>of_complex z' \\<in> unit_disc\\<close> \\<open>u \\<in> unit_disc\\<close>\n          by auto\n        ultimately\n        have \"?R (to_complex ?Mz') ?Mx ?Mu\"\n          using \\<open>?Mz' \\<in> unit_disc\\<close> inf_or_of_complex[of ?Mz']\n          by auto\n        hence \"?Mz' = of_complex Mz\"\n          using \\<open>?P ?Mx ?Mu\\<close> \\<open>?R Mz ?Mx ?Mu\\<close>\n          by (metis \\<open>moebius_pt (blaschke a) (of_complex z') \\<in> unit_disc\\<close> \\<open>of_complex Mz \\<in> unit_disc\\<close> to_complex_of_complex unit_disc_to_complex_inj)\n        thus \"z' = to_complex ?z\"\n          using moebius_pt_invert by auto\n      qed\n    qed\n  qed\n  thus ?thesis\n    using assms\n    by (metis to_complex_of_complex)\nqed\n\n(* ------------------------------------------------------------------ *)\nsubsection\\<open>Triangle inequality\\<close>\n(* ------------------------------------------------------------------ *)\n\nlemma poincare_distance_formula_zero_sum:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\"\n  shows \"poincare_distance u 0\\<^sub>h + poincare_distance 0\\<^sub>h v =\n         (let u' = cmod (to_complex u); v' = cmod (to_complex v)\n           in arcosh (((1 + u'\\<^sup>2) * (1 + v'\\<^sup>2) + 4 * u' * v') / ((1 - u'\\<^sup>2) * (1 - v'\\<^sup>2))))\"\nproof-\n  obtain u' v' where uv: \"u' = to_complex u\" \"v' = to_complex v\"\n    by auto\n  have uv': \"u = of_complex u'\" \"v = of_complex v'\"\n    using uv assms inf_or_of_complex[of u] inf_or_of_complex[of v]\n    by auto\n\n  let ?u' = \"cmod u'\" and ?v' = \"cmod v'\"\n\n  have disc: \"?u'\\<^sup>2 < 1\" \"?v'\\<^sup>2 < 1\"\n    using unit_disc_cmod_square_lt_1[OF \\<open>u \\<in> unit_disc\\<close>]\n    using unit_disc_cmod_square_lt_1[OF \\<open>v \\<in> unit_disc\\<close>] uv\n    by auto\n  thm arcosh_add\n  have \"arcosh (1 + 2 * ?u'\\<^sup>2 / (1 - ?u'\\<^sup>2)) + arcosh (1 + 2 * ?v'\\<^sup>2 / (1 - ?v'\\<^sup>2)) =\n        arcosh (((1 + ?u'\\<^sup>2) * (1 + ?v'\\<^sup>2) + 4 * ?u' * ?v') / ((1 - ?u'\\<^sup>2) * (1 - ?v'\\<^sup>2)))\" (is \"arcosh ?ll + arcosh ?rr = arcosh ?r\")\n  proof (subst arcosh_add)\n    show \"?ll \\<ge> 1\"  \"?rr \\<ge> 1\"\n      using disc\n      by auto\n  next\n    show \"arcosh ((1 + 2 * ?u'\\<^sup>2 / (1 - ?u'\\<^sup>2)) * (1 + 2 * ?v'\\<^sup>2 / (1 - ?v'\\<^sup>2)) +\n                  sqrt (((1 + 2 * ?u'\\<^sup>2 / (1 - ?u'\\<^sup>2))\\<^sup>2 - 1) * ((1 + 2 * ?v'\\<^sup>2 / (1 - ?v'\\<^sup>2))\\<^sup>2 - 1))) =\n          arcosh ?r\" (is \"arcosh ?l = _\")\n    proof-\n      have \"1 + 2 * ?u'\\<^sup>2 / (1 - ?u'\\<^sup>2) = (1 + ?u'\\<^sup>2) / (1 - ?u'\\<^sup>2)\"\n        using disc\n        by (subst add_divide_eq_iff, simp_all)\n      moreover\n      have \"1 + 2 * ?v'\\<^sup>2 / (1 - ?v'\\<^sup>2) = (1 + ?v'\\<^sup>2) / (1 - ?v'\\<^sup>2)\"\n        using disc\n        by (subst add_divide_eq_iff, simp_all)\n      moreover\n      have \"sqrt (((1 + 2 * ?u'\\<^sup>2 / (1 - ?u'\\<^sup>2))\\<^sup>2 - 1) * ((1 + 2 * ?v'\\<^sup>2 / (1 - ?v'\\<^sup>2))\\<^sup>2 - 1)) =\n               (4  * ?u' * ?v') / ((1 - ?u'\\<^sup>2) * (1 - ?v'\\<^sup>2))\" (is \"sqrt ?s = ?t\")\n      proof-\n        have \"?s = ?t\\<^sup>2\"\n          using disc\n          apply (subst add_divide_eq_iff, simp)+\n          apply (subst power_divide)+\n          apply simp\n          apply (subst divide_diff_eq_iff, simp)+\n          apply (simp add: power2_eq_square field_simps)\n          done\n        thus ?thesis\n          using disc\n          by simp\n      qed\n      ultimately\n      have \"?l = ?r\"\n        using disc\n        by simp (subst add_divide_distrib, simp)\n      thus ?thesis\n        by simp\n    qed\n  qed\n  thus ?thesis\n    using uv' assms\n    using poincare_distance_formula\n    by (simp add: Let_def)\nqed\n\nlemma poincare_distance_triangle_inequality:\n  assumes \"u \\<in> unit_disc\" and \"v \\<in> unit_disc\" and \"w \\<in> unit_disc\"\n  shows \"poincare_distance u v + poincare_distance v w \\<ge> poincare_distance u w\" (is \"?P' u v w\")\nproof-\n  have \"\\<forall> w. w \\<in> unit_disc \\<longrightarrow> ?P' u v w\"  (is \"?P v u\")\n  proof (rule wlog_x_axis[where P=\"?P\"])\n    fix x\n    assume \"is_real x\" \"0 \\<le> Re x\" \"Re x < 1\"\n    hence \"of_complex x \\<in> unit_disc\"\n      by (simp add: cmod_eq_Re)\n\n    show \"?P 0\\<^sub>h (of_complex x)\"\n    proof safe\n      fix w\n      assume \"w \\<in> unit_disc\"\n      then obtain w' where w: \"w = of_complex w'\"\n        using inf_or_of_complex[of w]\n        by auto\n\n      let ?x = \"cmod x\" and ?w = \"cmod w'\" and ?xw = \"cmod (x - w')\"\n\n      have disc: \"?x\\<^sup>2 < 1\" \"?w\\<^sup>2 < 1\"\n        using unit_disc_cmod_square_lt_1[OF \\<open>of_complex x \\<in> unit_disc\\<close>]\n        using unit_disc_cmod_square_lt_1[OF \\<open>w \\<in> unit_disc\\<close>] w\n        by auto\n\n      have \"poincare_distance (of_complex x) 0\\<^sub>h + poincare_distance 0\\<^sub>h w =\n           arcosh (((1 + ?x\\<^sup>2) * (1 + ?w\\<^sup>2) + 4 * ?x * ?w) / ((1 - ?x\\<^sup>2) * (1 - ?w\\<^sup>2)))\" (is \"_ = arcosh ?r1\")\n        using poincare_distance_formula_zero_sum[OF \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close>] w\n        by (simp add: Let_def)\n      moreover\n      have \"poincare_distance (of_complex x) (of_complex w') =\n            arcosh (((1 - ?x\\<^sup>2) * (1 - ?w\\<^sup>2) + 2 * ?xw\\<^sup>2) / ((1 - ?x\\<^sup>2) * (1 - ?w\\<^sup>2)))\" (is \"_ = arcosh ?r2\")\n        using disc\n        using poincare_distance_formula[OF \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close>] w\n        by (subst add_divide_distrib) simp\n      moreover\n      have *: \"(1 - ?x\\<^sup>2) * (1 - ?w\\<^sup>2) + 2 * ?xw\\<^sup>2 \\<le> (1 + ?x\\<^sup>2) * (1 + ?w\\<^sup>2) + 4 * ?x * ?w\"\n      proof-\n        have \"(cmod (x - w'))\\<^sup>2 \\<le> (cmod x + cmod w')\\<^sup>2\"\n          using norm_triangle_ineq4[of x w']\n          by (simp add: power_mono)\n        thus ?thesis\n          by (simp add: field_simps power2_sum)\n      qed\n      have \"arcosh ?r1 \\<ge> arcosh ?r2\"\n      proof (subst arcosh_mono)\n        show \"?r1 \\<ge> 1\"\n          using disc\n          by (smt \"*\" le_divide_eq_1_pos mult_pos_pos zero_le_power2)\n      next\n        show \"?r2 \\<ge> 1\"\n          using disc\n          by simp\n      next\n        show \"?r1 \\<ge> ?r2\"\n          using disc\n          using *\n          by (subst divide_right_mono, simp_all)\n      qed\n      ultimately\n      show \"poincare_distance (of_complex x) w \\<le> poincare_distance (of_complex x) 0\\<^sub>h + poincare_distance 0\\<^sub>h w\"\n        using \\<open>of_complex x \\<in> unit_disc\\<close> \\<open>w \\<in> unit_disc\\<close> w\n        using poincare_distance_formula\n        by simp\n    qed\n  next\n    show \"v \\<in> unit_disc\" \"u \\<in> unit_disc\"\n      by fact+\n  next\n    fix M u v\n    assume *: \"unit_disc_fix M\" \"u \\<in> unit_disc\" \"v \\<in> unit_disc\"\n    assume **: \"?P (moebius_pt M u) (moebius_pt M v)\"\n    show \"?P u v\"\n    proof safe\n      fix w\n      assume \"w \\<in> unit_disc\"\n      thus \"?P' v u w\"\n        using * **[rule_format, of \"moebius_pt M w\"]\n        by simp\n    qed\n  qed\n  thus ?thesis\n    using assms\n    by auto\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Poincare_Disc/Poincare_Distance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404096760998, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7972443439781813}}
{"text": "(*  Author:  Sébastien Gouëzel   sebastien.gouezel@univ-rennes1.fr\n    License: BSD\n*)\n\nsection \\<open>Hausdorff distance\\<close>\n\ntheory Hausdorff_Distance\n  imports Library_Complements\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\n\n\nsubsection \\<open>Hausdorff distance\\<close>\n\ntext \\<open>The Hausdorff distance between two subsets of a metric space is the minimal $M$ such that\neach set is included in the $M$-neighborhood of the other. For nonempty bounded sets, it\nsatisfies the triangular inequality, it is symmetric, but it vanishes on sets that have the same\nclosure. In particular, it defines a distance on closed bounded nonempty sets. We establish\nall these properties below.\\<close>\n\ndefinition hausdorff_distance::\"('a::metric_space) set \\<Rightarrow> 'a set \\<Rightarrow> real\"\n  where \"hausdorff_distance A B = (if A = {} \\<or> B = {} \\<or> (\\<not>(bounded A)) \\<or> (\\<not>(bounded B)) then 0\n                                   else max (SUP x\\<in>A. infdist x B) (SUP x\\<in>B. infdist x A))\"\n\nlemma hausdorff_distance_self [simp]:\n  \"hausdorff_distance A A = 0\"\nunfolding hausdorff_distance_def by auto\n\nlemma hausdorff_distance_sym:\n  \"hausdorff_distance A B = hausdorff_distance B A\"\nunfolding hausdorff_distance_def by auto\n\nlemma hausdorff_distance_points [simp]:\n  \"hausdorff_distance {x} {y} = dist x y\"\nunfolding hausdorff_distance_def by (auto, metis dist_commute max.idem)\n\ntext \\<open>The Hausdorff distance is expressed in terms of a supremum. To use it, one needs again\nand again to show that this is the supremum of a set which is bounded from above.\\<close>\n\nlemma bdd_above_infdist_aux:\n  assumes \"bounded A\" \"bounded B\"\n  shows \"bdd_above ((\\<lambda>x. infdist x B)`A)\"\nproof (cases \"B = {}\")\n  case True\n  then show ?thesis unfolding infdist_def by auto\nnext\n  case False\n  then obtain y where \"y \\<in> B\" by auto\n  then have \"infdist x B \\<le> dist x y\" if \"x \\<in> A\" for x\n    by (simp add: infdist_le)\n  then show ?thesis unfolding bdd_above_def\n    by (auto, metis assms(1) bounded_any_center dist_commute order_trans)\nqed\n\nlemma hausdorff_distance_nonneg [simp, mono_intros]:\n  \"hausdorff_distance A B \\<ge> 0\"\nproof (cases \"A = {} \\<or> B = {} \\<or> (\\<not>(bounded A)) \\<or> (\\<not>(bounded B))\")\n  case True\n  then show ?thesis unfolding hausdorff_distance_def by auto\nnext\n  case False\n  then have \"A \\<noteq> {}\" \"B \\<noteq> {}\" \"bounded A\" \"bounded B\" by auto\n  have \"(SUP x\\<in>A. infdist x B) \\<ge> 0\"\n    using bdd_above_infdist_aux[OF \\<open>bounded A\\<close> \\<open>bounded B\\<close>] infdist_nonneg\n    by (metis \\<open>A \\<noteq> {}\\<close> all_not_in_conv cSUP_upper2)\n  moreover have \"(SUP x\\<in>B. infdist x A) \\<ge> 0\"\n    using bdd_above_infdist_aux[OF \\<open>bounded B\\<close> \\<open>bounded A\\<close>] infdist_nonneg\n    by (metis \\<open>B \\<noteq> {}\\<close> all_not_in_conv cSUP_upper2)\n  ultimately show ?thesis unfolding hausdorff_distance_def by auto\nqed\n\nlemma hausdorff_distanceI:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> infdist x B \\<le> D\"\n          \"\\<And>x. x \\<in> B \\<Longrightarrow> infdist x A \\<le> D\"\n          \"D \\<ge> 0\"\n  shows \"hausdorff_distance A B \\<le> D\"\nproof (cases \"A = {} \\<or> B = {} \\<or> (\\<not>(bounded A)) \\<or> (\\<not>(bounded B))\")\n  case True\n  then show ?thesis unfolding hausdorff_distance_def using \\<open>D \\<ge> 0\\<close> by auto\nnext\n  case False\n  then have \"A \\<noteq> {}\" \"B \\<noteq> {}\" \"bounded A\" \"bounded B\" by auto\n  have \"(SUP x\\<in>A. infdist x B) \\<le> D\"\n    apply (rule cSUP_least, simp add: \\<open>A \\<noteq> {}\\<close>) using assms(1) by blast\n  moreover have \"(SUP x\\<in>B. infdist x A) \\<le> D\"\n    apply (rule cSUP_least, simp add: \\<open>B \\<noteq> {}\\<close>) using assms(2) by blast\n  ultimately show ?thesis unfolding hausdorff_distance_def using False by auto\nqed\n\nlemma hausdorff_distanceI2:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> \\<exists>y\\<in>B. dist x y \\<le> D\"\n          \"\\<And>x. x \\<in> B \\<Longrightarrow> \\<exists>y\\<in>A. dist x y \\<le> D\"\n          \"D \\<ge> 0\"\n  shows \"hausdorff_distance A B \\<le> D\"\nproof (rule hausdorff_distanceI[OF _ _ \\<open>D \\<ge> 0\\<close>])\n  fix x assume \"x \\<in> A\" show \"infdist x B \\<le> D\" using assms(1)[OF \\<open>x \\<in> A\\<close>] infdist_le2 by fastforce\nnext\n  fix x assume \"x \\<in> B\" show \"infdist x A \\<le> D\" using assms(2)[OF \\<open>x \\<in> B\\<close>] infdist_le2 by fastforce\nqed\n\nlemma infdist_le_hausdorff_distance [mono_intros]:\n  assumes \"x \\<in> A\" \"bounded A\" \"bounded B\"\n  shows \"infdist x B \\<le> hausdorff_distance A B\"\nproof (cases \"B = {}\")\n  case True\n  then have \"infdist x B = 0\" unfolding infdist_def by auto\n  then show ?thesis using hausdorff_distance_nonneg by auto\nnext\n  case False\n  have \"infdist x B \\<le> (SUP y\\<in>A. infdist y B)\"\n    using bdd_above_infdist_aux[OF \\<open>bounded A\\<close> \\<open>bounded B\\<close>] by (meson assms(1) cSUP_upper)\n  then show ?thesis unfolding hausdorff_distance_def using assms False by auto\nqed\n\nlemma hausdorff_distance_infdist_triangle [mono_intros]:\n  assumes \"B \\<noteq> {}\" \"bounded B\" \"bounded C\"\n  shows \"infdist x C \\<le> infdist x B + hausdorff_distance B C\"\nproof (cases \"C = {}\")\n  case True\n  then have \"infdist x C = 0\" unfolding infdist_def by auto\n  then show ?thesis using infdist_nonneg[of x B] hausdorff_distance_nonneg[of B C] by auto\nnext\n  case False\n  have \"infdist x C - hausdorff_distance B C \\<le> dist x b\" if \"b \\<in> B\" for b\n  proof -\n    have \"infdist x C \\<le> infdist b C + dist x b\" by (rule infdist_triangle)\n    also have \"... \\<le> dist x b + hausdorff_distance B C\"\n      using infdist_le_hausdorff_distance[OF \\<open>b \\<in> B\\<close> \\<open>bounded B\\<close> \\<open>bounded C\\<close>] by auto\n    finally show ?thesis by auto\n  qed\n  then have \"infdist x C - hausdorff_distance B C \\<le> infdist x B\"\n    unfolding infdist_def using \\<open>B \\<noteq> {}\\<close> by (simp add: le_cINF_iff)\n  then show ?thesis by auto\nqed\n\nlemma hausdorff_distance_triangle [mono_intros]:\n  assumes \"B \\<noteq> {}\" \"bounded B\"\n  shows \"hausdorff_distance A C \\<le> hausdorff_distance A B + hausdorff_distance B C\"\nproof (cases \"A = {} \\<or> C = {} \\<or> (\\<not>(bounded A)) \\<or> (\\<not>(bounded C))\")\n  case True\n  then have \"hausdorff_distance A C = 0\" unfolding hausdorff_distance_def by auto\n  then show ?thesis\n    using hausdorff_distance_nonneg[of A B] hausdorff_distance_nonneg[of B C] by auto\nnext\n  case False\n  then have *: \"A \\<noteq> {}\" \"C \\<noteq> {}\" \"bounded A\" \"bounded C\" by auto\n  define M where \"M = hausdorff_distance A B + hausdorff_distance B C\"\n  have \"infdist x C \\<le> M\" if \"x \\<in> A\" for x\n    using hausdorff_distance_infdist_triangle[OF \\<open>B \\<noteq> {}\\<close> \\<open>bounded B \\<close> \\<open>bounded C\\<close>, of x]\n          infdist_le_hausdorff_distance[OF \\<open>x \\<in> A\\<close> \\<open>bounded A\\<close> \\<open>bounded B\\<close>] by (auto simp add: M_def)\n  moreover have \"infdist x A \\<le> M\" if \"x \\<in> C\" for x\n    using hausdorff_distance_infdist_triangle[OF \\<open>B \\<noteq> {}\\<close> \\<open>bounded B \\<close> \\<open>bounded A\\<close>, of x]\n          infdist_le_hausdorff_distance[OF \\<open>x \\<in> C\\<close> \\<open>bounded C\\<close> \\<open>bounded B\\<close>]\n    by (auto simp add: hausdorff_distance_sym M_def)\n  ultimately have \"hausdorff_distance A C \\<le> M\"\n    unfolding hausdorff_distance_def using * bdd_above_infdist_aux by (auto simp add: cSUP_least)\n  then show ?thesis unfolding M_def by auto\nqed\n\nlemma hausdorff_distance_subset:\n  assumes \"A \\<subseteq> B\" \"A \\<noteq> {}\" \"bounded B\"\n  shows \"hausdorff_distance A B = (SUP x\\<in>B. infdist x A)\"\nproof -\n  have H: \"B \\<noteq> {}\" \"bounded A\" using assms bounded_subset by auto\n  have \"(SUP x\\<in>A. infdist x B) = 0\" using assms by (simp add: subset_eq)\n  moreover have \"(SUP x\\<in>B. infdist x A) \\<ge> 0\"\n    using bdd_above_infdist_aux[OF \\<open>bounded B\\<close> \\<open>bounded A\\<close>] infdist_nonneg[of _ A]\n    by (meson H(1) cSUP_upper2 ex_in_conv)\n  ultimately show ?thesis unfolding hausdorff_distance_def using assms H by auto\nqed\n\nlemma hausdorff_distance_closure [simp]:\n  \"hausdorff_distance A (closure A) = 0\"\nproof (cases \"A = {} \\<or> (\\<not>(bounded A))\")\n  case True\n  then show ?thesis unfolding hausdorff_distance_def by auto\nnext\n  case False\n  then have \"A \\<noteq> {}\" \"bounded A\" by auto\n  then have \"closure A \\<noteq> {}\" \"bounded (closure A)\" \"A \\<subseteq> closure A\"\n    using closure_subset by auto\n  have \"infdist x A = 0\" if \"x \\<in> closure A\" for x\n    using in_closure_iff_infdist_zero[OF \\<open>A \\<noteq> {}\\<close>] that by auto\n  then have \"(SUP x\\<in>closure A. infdist x A) = 0\"\n    using \\<open>closure A \\<noteq> {}\\<close> by auto\n  then show ?thesis\n    unfolding hausdorff_distance_subset[OF \\<open>A \\<subseteq> closure A\\<close> \\<open>A \\<noteq> {}\\<close> \\<open>bounded (closure A)\\<close>] by simp\nqed\n\nlemma hausdorff_distance_closures [simp]:\n  \"hausdorff_distance (closure A) (closure B) = hausdorff_distance A B\"\nproof (cases \"A = {} \\<or> B = {} \\<or> (\\<not>(bounded A)) \\<or> (\\<not>(bounded B))\")\n  case True\n  then have *: \"hausdorff_distance A B = 0\" unfolding hausdorff_distance_def by auto\n  have \"closure A = {} \\<or> (\\<not>(bounded (closure A))) \\<or> closure B = {} \\<or> (\\<not>(bounded (closure B)))\"\n    using True bounded_subset closure_subset by auto\n  then have \"hausdorff_distance (closure A) (closure B) = 0\"\n    unfolding hausdorff_distance_def by auto\n  then show ?thesis using * by simp\nnext\n  case False\n  then have H: \"A \\<noteq> {}\" \"B \\<noteq> {}\" \"bounded A\" \"bounded B\" by auto\n  then have H2: \"closure A \\<noteq> {}\" \"closure B \\<noteq> {}\" \"bounded (closure A)\" \"bounded (closure B)\"\n    by auto\n  have \"hausdorff_distance A B \\<le> hausdorff_distance A (closure A) + hausdorff_distance (closure A) B\"\n    apply (rule hausdorff_distance_triangle) using H H2 by auto\n  also have \"... = hausdorff_distance (closure A) B\"\n    using hausdorff_distance_closure by auto\n  also have \"... \\<le> hausdorff_distance (closure A) (closure B) + hausdorff_distance (closure B) B\"\n    apply (rule hausdorff_distance_triangle) using H H2 by auto\n  also have \"... = hausdorff_distance (closure A) (closure B)\"\n    using hausdorff_distance_closure by (auto simp add: hausdorff_distance_sym)\n  finally have *: \"hausdorff_distance A B \\<le> hausdorff_distance (closure A) (closure B)\" by simp\n\n  have \"hausdorff_distance (closure A) (closure B) \\<le> hausdorff_distance (closure A) A + hausdorff_distance A (closure B)\"\n    apply (rule hausdorff_distance_triangle) using H H2 by auto\n  also have \"... = hausdorff_distance A (closure B)\"\n    using hausdorff_distance_closure by (auto simp add: hausdorff_distance_sym)\n  also have \"... \\<le> hausdorff_distance A B + hausdorff_distance B (closure B)\"\n    apply (rule hausdorff_distance_triangle) using H H2 by auto\n  also have \"... = hausdorff_distance A B\"\n    using hausdorff_distance_closure by (auto simp add: hausdorff_distance_sym)\n  finally have \"hausdorff_distance (closure A) (closure B) \\<le> hausdorff_distance A B\" by simp\n  then show ?thesis using * by auto\nqed\n\nlemma hausdorff_distance_zero:\n  assumes \"A \\<noteq> {}\" \"bounded A\" \"B \\<noteq> {}\" \"bounded B\"\n  shows \"hausdorff_distance A B = 0 \\<longleftrightarrow> closure A = closure B\"\nproof\n  assume H: \"hausdorff_distance A B = 0\"\n  have \"A \\<subseteq> closure B\"\n  proof\n    fix x assume \"x \\<in> A\"\n    have \"infdist x B = 0\"\n      using infdist_le_hausdorff_distance[OF \\<open>x \\<in> A\\<close> \\<open>bounded A\\<close> \\<open>bounded B\\<close>] H infdist_nonneg[of x B] by auto\n    then show \"x \\<in> closure B\" using in_closure_iff_infdist_zero[OF \\<open>B \\<noteq> {}\\<close>] by auto\n  qed\n  then have A: \"closure A \\<subseteq> closure B\" by (simp add: closure_minimal)\n\n  have \"B \\<subseteq> closure A\"\n  proof\n    fix x assume \"x \\<in> B\"\n    have \"infdist x A = 0\"\n      using infdist_le_hausdorff_distance[OF \\<open>x \\<in> B\\<close> \\<open>bounded B\\<close> \\<open>bounded A\\<close>] H infdist_nonneg[of x A]\n      by (auto simp add: hausdorff_distance_sym)\n    then show \"x \\<in> closure A\" using in_closure_iff_infdist_zero[OF \\<open>A \\<noteq> {}\\<close>] by auto\n  qed\n  then have \"closure B \\<subseteq> closure A\" by (simp add: closure_minimal)\n  then show \"closure A = closure B\" using A by auto\nnext\n  assume \"closure A = closure B\"\n  then show \"hausdorff_distance A B = 0\"\n    using hausdorff_distance_closures[of A B] by auto\nqed\n\nlemma hausdorff_distance_vimage:\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> dist (f x) (g x) \\<le> C\"\n          \"C \\<ge> 0\"\n  shows \"hausdorff_distance (f`A) (g`A) \\<le> C\"\napply (rule hausdorff_distanceI2[OF _ _ \\<open>C \\<ge> 0\\<close>]) using assms by (auto simp add: dist_commute, auto)\n\nlemma hausdorff_distance_union [mono_intros]:\n  assumes \"A \\<noteq> {}\" \"B \\<noteq> {}\" \"C \\<noteq> {}\" \"D \\<noteq> {}\"\n  shows \"hausdorff_distance (A \\<union> B) (C \\<union> D) \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\nproof (cases \"bounded A \\<and> bounded B \\<and> bounded C \\<and> bounded D\")\n  case False\n  then have \"hausdorff_distance (A \\<union> B) (C \\<union> D) = 0\"\n    unfolding hausdorff_distance_def by auto\n  then show ?thesis\n    by (simp add: hausdorff_distance_nonneg le_max_iff_disj)\nnext\n  case True\n  show ?thesis\n  proof (rule hausdorff_distanceI, auto)\n    fix x assume H: \"x \\<in> A\"\n    have \"infdist x (C \\<union> D) \\<le> infdist x C\"\n      by (simp add: assms infdist_union_min)\n    also have \"... \\<le> hausdorff_distance A C\"\n      apply (rule infdist_le_hausdorff_distance) using H True by auto\n    also have \"... \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      by auto\n    finally show \"infdist x (C \\<union> D) \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      by simp\n  next\n    fix x assume H: \"x \\<in> B\"\n    have \"infdist x (C \\<union> D) \\<le> infdist x D\"\n      by (simp add: assms infdist_union_min)\n    also have \"... \\<le> hausdorff_distance B D\"\n      apply (rule infdist_le_hausdorff_distance) using H True by auto\n    also have \"... \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      by auto\n    finally show \"infdist x (C \\<union> D) \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      by simp\n  next\n    fix x assume H: \"x \\<in> C\"\n    have \"infdist x (A \\<union> B) \\<le> infdist x A\"\n      by (simp add: assms infdist_union_min)\n    also have \"... \\<le> hausdorff_distance C A\"\n      apply (rule infdist_le_hausdorff_distance) using H True by auto\n    also have \"... \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      using hausdorff_distance_sym[of A C] by auto\n    finally show \"infdist x (A \\<union> B) \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      by simp\n  next\n    fix x assume H: \"x \\<in> D\"\n    have \"infdist x (A \\<union> B) \\<le> infdist x B\"\n      by (simp add: assms infdist_union_min)\n    also have \"... \\<le> hausdorff_distance D B\"\n      apply (rule infdist_le_hausdorff_distance) using H True by auto\n    also have \"... \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      using hausdorff_distance_sym[of B D] by auto\n    finally show \"infdist x (A \\<union> B) \\<le> max (hausdorff_distance A C) (hausdorff_distance B D)\"\n      by simp\n  qed (simp add: le_max_iff_disj)\nqed\n\nend (*of theory Hausdorff_Distance*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gromov_Hyperbolicity/Hausdorff_Distance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299509069106, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7971209552163047}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Braun Trees\\<close>\n\ntheory Braun_Tree\nimports \"HOL-Library.Tree_Real\"\nbegin\n\ntext \\<open>Braun Trees were studied by Braun and Rem~\\cite{BraunRem}\nand later Hoogerwoord~\\cite{Hoogerwoord}.\\<close>\n\nfun braun :: \"'a tree \\<Rightarrow> bool\" where\n\"braun Leaf = True\" |\n\"braun (Node l x r) = ((size l = size r \\<or> size l = size r + 1) \\<and> braun l \\<and> braun r)\"\n\nlemma braun_Node':\n  \"braun (Node l x r) = (size r \\<le> size l \\<and> size l \\<le> size r + 1 \\<and> braun l \\<and> braun r)\"\nby auto\n\ntext \\<open>The shape of a Braun-tree is uniquely determined by its size:\\<close>\n\nlemma braun_unique: \"\\<lbrakk> braun (t1::unit tree); braun t2; size t1 = size t2 \\<rbrakk> \\<Longrightarrow> t1 = t2\"\nproof (induction t1 arbitrary: t2)\n  case Leaf thus ?case by simp\nnext\n  case (Node l1 _ r1)\n  from Node.prems(3) have \"t2 \\<noteq> Leaf\" by auto\n  then obtain l2 x2 r2 where [simp]: \"t2 = Node l2 x2 r2\" by (meson neq_Leaf_iff)\n  with Node.prems have \"size l1 = size l2 \\<and> size r1 = size r2\" by auto\n  thus ?case using Node.prems(1,2) Node.IH by auto\nqed\n\ntext \\<open>Braun trees are almost complete:\\<close>\n\nlemma acomplete_if_braun: \"braun t \\<Longrightarrow> acomplete t\"\nproof(induction t)\n  case Leaf show ?case by (simp add: acomplete_def)\nnext\n  case (Node l x r) thus ?case using acomplete_Node_if_wbal2 by force\nqed\n\nsubsection \\<open>Numbering Nodes\\<close>\n\ntext \\<open>We show that a tree is a Braun tree iff a parity-based\nnumbering (\\<open>braun_indices\\<close>) of nodes yields an interval of numbers.\\<close>\n\nfun braun_indices :: \"'a tree \\<Rightarrow> nat set\" where\n\"braun_indices Leaf = {}\" |\n\"braun_indices (Node l _ r) = {1} \\<union> (*) 2 ` braun_indices l \\<union> Suc ` (*) 2 ` braun_indices r\"\n\nlemma braun_indices1: \"0 \\<notin> braun_indices t\"\nby (induction t) auto\n\nlemma finite_braun_indices: \"finite(braun_indices t)\"\nby (induction t) auto\n\ntext \"One direction:\"\n\nlemma braun_indices_if_braun: \"braun t \\<Longrightarrow> braun_indices t = {1..size t}\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  have *: \"(*) 2 ` {a..b} \\<union> Suc ` (*) 2 ` {a..b} = {2*a..2*b+1}\" (is \"?l = ?r\") for a b\n  proof\n    show \"?l \\<subseteq> ?r\" by auto\n  next\n    have \"\\<exists>x2\\<in>{a..b}. x \\<in> {Suc (2*x2), 2*x2}\" if *: \"x \\<in> {2*a .. 2*b+1}\" for x\n    proof -\n      have \"x div 2 \\<in> {a..b}\" using * by auto\n      moreover have \"x \\<in> {2 * (x div 2), Suc(2 * (x div 2))}\" by auto\n      ultimately show ?thesis by blast\n    qed\n    thus \"?r \\<subseteq> ?l\" by fastforce\n  qed\n  case (Node l x r)\n  hence \"size l = size r \\<or> size l = size r + 1\" (is \"?A \\<or> ?B\") by auto\n  thus ?case\n  proof\n    assume ?A\n    with Node show ?thesis by (auto simp: *)\n  next\n    assume ?B\n    with Node show ?thesis by (auto simp: * atLeastAtMostSuc_conv)\n  qed\nqed\n\ntext \"The other direction is more complicated. The following proof is due to Thomas Sewell.\"\n\nlemma disj_evens_odds: \"(*) 2 ` A \\<inter> Suc ` (*) 2 ` B = {}\"\nusing double_not_eq_Suc_double by auto\n\nlemma card_braun_indices: \"card (braun_indices t) = size t\"\nproof (induction t)\n  case Leaf thus ?case by simp\nnext\n  case Node\n  thus ?case\n    by(auto simp: UNION_singleton_eq_range finite_braun_indices card_Un_disjoint\n                  card_insert_if disj_evens_odds card_image inj_on_def braun_indices1)\nqed\n\nlemma braun_indices_intvl_base_1:\n  assumes bi: \"braun_indices t = {m..n}\"\n  shows \"{m..n} = {1..size t}\"\nproof (cases \"t = Leaf\")\n  case True then show ?thesis using bi by simp\nnext\n  case False\n  note eqs = eqset_imp_iff[OF bi]\n  from eqs[of 0] have 0: \"0 < m\"\n    by (simp add: braun_indices1)\n  from eqs[of 1] have 1: \"m \\<le> 1\"\n    by (cases t; simp add: False)\n  from 0 1 have eq1: \"m = 1\" by simp\n  from card_braun_indices[of t] show ?thesis\n    by (simp add: bi eq1)\nqed\n\nlemma even_of_intvl_intvl:\n  fixes S :: \"nat set\"\n  assumes \"S = {m..n} \\<inter> {i. even i}\"\n  shows \"\\<exists>m' n'. S = (\\<lambda>i. i * 2) ` {m'..n'}\"\n  apply (rule exI[where x=\"Suc m div 2\"], rule exI[where x=\"n div 2\"])\n  apply (fastforce simp add: assms mult.commute)\n  done\n\nlemma odd_of_intvl_intvl:\n  fixes S :: \"nat set\"\n  assumes \"S = {m..n} \\<inter> {i. odd i}\"\n  shows \"\\<exists>m' n'. S = Suc ` (\\<lambda>i. i * 2) ` {m'..n'}\"\nproof -\n  have step1: \"\\<exists>m'. S = Suc ` ({m'..n - 1} \\<inter> {i. even i})\"\n    apply (rule_tac x=\"if n = 0 then 1 else m - 1\" in exI)\n    apply (auto simp: assms image_def elim!: oddE)\n    done\n  thus ?thesis\n    by (metis even_of_intvl_intvl)\nqed\n\nlemma image_int_eq_image:\n  \"(\\<forall>i \\<in> S. f i \\<in> T) \\<Longrightarrow> (f ` S) \\<inter> T = f ` S\"\n  \"(\\<forall>i \\<in> S. f i \\<notin> T) \\<Longrightarrow> (f ` S) \\<inter> T = {}\"\n  by auto\n\nlemma braun_indices1_le:\n  \"i \\<in> braun_indices t \\<Longrightarrow> Suc 0 \\<le> i\"\n  using braun_indices1 not_less_eq_eq by blast\n\nlemma braun_if_braun_indices: \"braun_indices t = {1..size t} \\<Longrightarrow> braun t\"\nproof(induction t)\ncase Leaf\n  then show ?case by simp\nnext\n  case (Node l x r)\n  obtain t where t: \"t = Node l x r\" by simp\n  from Node.prems have eq: \"{2 .. size t} = (\\<lambda>i. i * 2) ` braun_indices l \\<union> Suc ` (\\<lambda>i. i * 2) ` braun_indices r\"\n    (is \"?R = ?S \\<union> ?T\")\n    apply clarsimp\n    apply (drule_tac f=\"\\<lambda>S. S \\<inter> {2..}\" in arg_cong)\n    apply (simp add: t mult.commute Int_Un_distrib2 image_int_eq_image braun_indices1_le)\n    done\n  then have ST: \"?S = ?R \\<inter> {i. even i}\" \"?T = ?R \\<inter> {i. odd i}\"\n    by (simp_all add: Int_Un_distrib2 image_int_eq_image)\n  from ST have l: \"braun_indices l = {1 .. size l}\"\n    by (fastforce dest: braun_indices_intvl_base_1 dest!: even_of_intvl_intvl\n                  simp: mult.commute inj_image_eq_iff[OF inj_onI])\n  from ST have r: \"braun_indices r = {1 .. size r}\"\n    by (fastforce dest: braun_indices_intvl_base_1 dest!: odd_of_intvl_intvl\n                  simp: mult.commute inj_image_eq_iff[OF inj_onI])\n  note STa = ST[THEN eqset_imp_iff, THEN iffD2]\n  note STb = STa[of \"size t\"] STa[of \"size t - 1\"]\n  then have sizes: \"size l = size r \\<or> size l = size r + 1\"\n    apply (clarsimp simp: t l r inj_image_mem_iff[OF inj_onI])\n    apply (cases \"even (size l)\"; cases \"even (size r)\"; clarsimp elim!: oddE; fastforce)\n    done\n  from l r sizes show ?case\n    by (clarsimp simp: Node.IH)\nqed\n\nlemma braun_iff_braun_indices: \"braun t \\<longleftrightarrow> braun_indices t = {1..size t}\"\nusing braun_if_braun_indices braun_indices_if_braun by blast\n\n(* An older less appealing proof:\nlemma Suc0_notin_double: \"Suc 0 \\<notin> ( * ) 2 ` A\"\nby(auto)\n\nlemma zero_in_double_iff: \"(0::nat) \\<in> ( * ) 2 ` A \\<longleftrightarrow> 0 \\<in> A\"\nby(auto)\n\nlemma Suc_in_Suc_image_iff: \"Suc n \\<in> Suc ` A \\<longleftrightarrow> n \\<in> A\"\nby(auto)\n\nlemmas nat_in_image = Suc0_notin_double zero_in_double_iff Suc_in_Suc_image_iff\n\nlemma disj_union_eq_iff:\n  \"\\<lbrakk> L1 \\<inter> R2 = {}; L2 \\<inter> R1 = {} \\<rbrakk> \\<Longrightarrow> L1 \\<union> R1 = L2 \\<union> R2 \\<longleftrightarrow> L1 = L2 \\<and> R1 = R2\"\nby blast\n\nlemma inj_braun_indices: \"braun_indices t1 = braun_indices t2 \\<Longrightarrow> t1 = (t2::unit tree)\"\nproof(induction t1 arbitrary: t2)\n  case Leaf thus ?case using braun_indices.elims by blast\nnext\n  case (Node l1 x1 r1)\n  have \"t2 \\<noteq> Leaf\"\n  proof\n    assume \"t2 = Leaf\"\n    with Node.prems show False by simp\n  qed\n  thus ?case using Node\n    by (auto simp: neq_Leaf_iff insert_ident nat_in_image braun_indices1\n                  disj_union_eq_iff disj_evens_odds inj_image_eq_iff inj_def)\nqed\n\ntext \\<open>How many even/odd natural numbers are there between m and n?\\<close>\n\nlemma card_Icc_even_nat:\n  \"card {i \\<in> {m..n::nat}. even i} = (n+1-m + (m+1) mod 2) div 2\" (is \"?l m n = ?r m n\")\nproof(induction \"n+1 - m\" arbitrary: n m)\n   case 0 thus ?case by simp\nnext\n  case Suc\n  have \"m \\<le> n\" using Suc(2) by arith\n  hence \"{m..n} = insert m {m+1..n}\" by auto\n  hence \"?l m n = card {i \\<in> insert m {m+1..n}. even i}\" by simp\n  also have \"\\<dots> = ?r m n\" (is \"?l = ?r\")\n  proof (cases)\n    assume \"even m\"\n    hence \"{i \\<in> insert m {m+1..n}. even i} = insert m {i \\<in> {m+1..n}. even i}\" by auto\n    hence \"?l = card {i \\<in> {m+1..n}. even i} + 1\" by simp\n    also have \"\\<dots> = (n-m + (m+2) mod 2) div 2 + 1\" using Suc(1)[of n \"m+1\"] Suc(2) by simp\n    also have \"\\<dots> = ?r\" using \\<open>even m\\<close> \\<open>m \\<le> n\\<close> by auto\n    finally show ?thesis .\n  next\n    assume \"odd m\"\n    hence \"{i \\<in> insert m {m+1..n}. even i} = {i \\<in> {m+1..n}. even i}\" by auto\n    hence \"?l = card ...\" by simp\n    also have \"\\<dots> = (n-m + (m+2) mod 2) div 2\" using Suc(1)[of n \"m+1\"] Suc(2) by simp\n    also have \"\\<dots> = ?r\" using \\<open>odd m\\<close> \\<open>m \\<le> n\\<close> even_iff_mod_2_eq_zero[of m] by simp\n    finally show ?thesis .\n  qed\n  finally show ?case .\nqed\n\nlemma card_Icc_odd_nat: \"card {i \\<in> {m..n::nat}. odd i} = (n+1-m + m mod 2) div 2\"\nproof -\n  let ?A = \"{i \\<in> {m..n}. odd i}\"\n  let ?B = \"{i \\<in> {m+1..n+1}. even i}\"\n  have \"card ?A = card (Suc ` ?A)\" by (simp add: card_image)\n  also have \"Suc ` ?A = ?B\" using Suc_le_D by(force simp: image_iff)\n  also have \"card ?B = (n+1-m + (m) mod 2) div 2\"\n    using card_Icc_even_nat[of \"m+1\" \"n+1\"] by simp\n  finally show ?thesis .\nqed\n\nlemma compact_Icc_even: assumes \"A = {i \\<in> {m..n}. even i}\"\nshows \"A = (\\<lambda>j. 2*(j-1) + m + m mod 2) ` {1..card A}\" (is \"_ = ?A\")\nproof\n  let ?a = \"(n+1-m + (m+1) mod 2) div 2\"\n  have \"\\<exists>j \\<in> {1..?a}. i = 2*(j-1) + m + m mod 2\" if *: \"i \\<in> {m..n}\" \"even i\" for i\n  proof -\n    let ?j = \"(i - (m + m mod 2)) div 2 + 1\"\n    have \"?j \\<in> {1..?a} \\<and> i = 2*(?j-1) + m + m mod 2\" using * by(auto simp: mod2_eq_if) presburger+\n    thus ?thesis by blast\n  qed\n  thus \"A \\<subseteq> ?A\" using assms\n    by(auto simp: image_iff card_Icc_even_nat simp del: atLeastAtMost_iff)\nnext\n  let ?a = \"(n+1-m + (m+1) mod 2) div 2\"\n  have 1: \"2 * (j - 1) + m + m mod 2 \\<in> {m..n}\" if *: \"j \\<in> {1..?a}\" for j\n    using * by(auto simp: mod2_eq_if)\n  have 2: \"even (2 * (j - 1) + m + m mod 2)\" for j by presburger\n  show \"?A \\<subseteq> A\"\n    apply(simp add: assms card_Icc_even_nat del: atLeastAtMost_iff One_nat_def)\n    using 1 2 by blast\nqed\n\nlemma compact_Icc_odd:\n  assumes \"B = {i \\<in> {m..n}. odd i}\" shows \"B = (\\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..card B}\"\nproof -\n  define A :: \" nat set\" where \"A = Suc ` B\"\n  have \"A = {i \\<in> {m+1..n+1}. even i}\"\n    using Suc_le_D by(force simp add: A_def assms image_iff)\n  from compact_Icc_even[OF this]\n  have \"A = Suc ` (\\<lambda>i. 2 * (i - 1) + m + (m + 1) mod 2) ` {1..card A}\"\n    by (simp add: image_comp o_def)\n  hence B: \"B = (\\<lambda>i. 2 * (i - 1) + m + (m + 1) mod 2) ` {1..card A}\"\n    using A_def by (simp add: inj_image_eq_iff)\n  have \"card A = card B\" by (metis A_def bij_betw_Suc bij_betw_same_card) \n  with B show ?thesis by simp\nqed\n\nlemma even_odd_decomp: assumes \"\\<forall>x \\<in> A. even x\" \"\\<forall>x \\<in> B. odd x\"  \"A \\<union> B = {m..n}\"\nshows \"(let a = card A; b = card B in\n   a + b = n+1-m \\<and>\n   A = (\\<lambda>i. 2*(i-1) + m + m mod 2) ` {1..a} \\<and>\n   B = (\\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..b} \\<and>\n   (a = b \\<or> a = b+1 \\<and> even m \\<or> a+1 = b \\<and> odd m))\"\nproof -\n  let ?a = \"card A\" let ?b = \"card B\"\n  have \"finite A \\<and> finite B\"\n    by (metis \\<open>A \\<union> B = {m..n}\\<close> finite_Un finite_atLeastAtMost)\n  hence ab: \"?a + ?b = Suc n - m\"\n    by (metis Int_emptyI assms card_Un_disjoint card_atLeastAtMost)\n  have A: \"A = {i \\<in> {m..n}. even i}\" using assms by auto\n  hence A': \"A = (\\<lambda>i. 2*(i-1) + m + m mod 2) ` {1..?a}\" by(rule compact_Icc_even)\n  have B: \"B = {i \\<in> {m..n}. odd i}\" using assms by auto\n  hence B': \"B = (\\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..?b}\" by(rule compact_Icc_odd)\n  have \"?a = ?b \\<or> ?a = ?b+1 \\<and> even m \\<or> ?a+1 = ?b \\<and> odd m\"\n    apply(simp add: Let_def mod2_eq_if\n      card_Icc_even_nat[of m n, simplified A[symmetric]]\n      card_Icc_odd_nat[of m n, simplified B[symmetric]] split!: if_splits)\n    by linarith\n  with ab A' B' show ?thesis by simp\nqed\n\nlemma braun_if_braun_indices: \"braun_indices t = {1..size t} \\<Longrightarrow> braun t\"\nproof(induction t)\ncase Leaf\n  then show ?case by simp\nnext\n  case (Node t1 x2 t2)\n  have 1: \"i > 0 \\<Longrightarrow> Suc(Suc(2 * (i - Suc 0))) = 2*i\" for i::nat by(simp add: algebra_simps)\n  have 2: \"i > 0 \\<Longrightarrow> 2 * (i - Suc 0) + 3 = 2*i + 1\" for i::nat by(simp add: algebra_simps)\n  have 3: \"( * ) 2 ` braun_indices t1 \\<union> Suc ` ( * ) 2 ` braun_indices t2 =\n     {2..size t1 + size t2 + 1}\" using Node.prems\n    by (simp add: insert_ident Icc_eq_insert_lb_nat nat_in_image braun_indices1)\n  thus ?case using Node.IH even_odd_decomp[OF _ _ 3]\n    by(simp add: card_image inj_on_def card_braun_indices Let_def 1 2 inj_image_eq_iff image_comp\n           cong: image_cong_simp)\nqed\n*)\n\nend", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Data_Structures/Braun_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.9032942034496965, "lm_q1q2_score": 0.7970919767308248}}
{"text": "theory Ex5_3\n  imports Main\nbegin\n\n(*\nBy: Vadim Zaliva <vzaliva@cmu.edu>\nFrom: T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL. Springer, 2014.\nExercise 5.3:\n*)\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where \n  ev0: \"ev 0\" |\n  evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nlemma \n  assumes a: \"ev (Suc (Suc n))\"\n  shows \"ev n\"\nusing a\nproof cases\n  case evSS thus \"ev n\" by simp\nqed\n\n\nend\n\n\n", "meta": {"author": "vzaliva", "repo": "isabelle-semantics-ex", "sha": "4e1acf1c9850f17057dd98454e42262d01301670", "save_path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex", "path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex/isabelle-semantics-ex-4e1acf1c9850f17057dd98454e42262d01301670/Ex5_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430812881347, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7970684681770015}}
{"text": "(*  Title:      HOL/Finite_Set.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n    Author:     Andrei Popescu\n*)\n\nsection \\<open>Finite sets\\<close>\n\ntheory Finite_Set\n  imports Product_Type Sum_Type Fields Relation\nbegin\n\nsubsection \\<open>Predicate for finite sets\\<close>\n\ncontext notes [[inductive_internals]]\nbegin\n\ninductive finite :: \"'a set \\<Rightarrow> bool\"\n  where\n    emptyI [simp, intro!]: \"finite {}\"\n  | insertI [simp, intro!]: \"finite A \\<Longrightarrow> finite (insert a A)\"\n\nend\n\nsimproc_setup finite_Collect (\"finite (Collect P)\") = \\<open>K Set_Comprehension_Pointfree.simproc\\<close>\n\ndeclare [[simproc del: finite_Collect]]\n\nlemma finite_induct [case_names empty insert, induct set: finite]:\n  \\<comment> \\<open>Discharging \\<open>x \\<notin> F\\<close> entails extra work.\\<close>\n  assumes \"finite F\"\n  assumes \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\n  using \\<open>finite F\\<close>\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume F: \"finite F\" and P: \"P F\"\n  show \"P (insert x F)\"\n  proof cases\n    assume \"x \\<in> F\"\n    then have \"insert x F = F\" by (rule insert_absorb)\n    with P show ?thesis by (simp only:)\n  next\n    assume \"x \\<notin> F\"\n    from F this P show ?thesis by (rule insert)\n  qed\nqed\n\nlemma infinite_finite_induct [case_names infinite empty insert]:\n  assumes infinite: \"\\<And>A. \\<not> finite A \\<Longrightarrow> P A\"\n    and empty: \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P A\"\nproof (cases \"finite A\")\n  case False\n  with infinite show ?thesis .\nnext\n  case True\n  then show ?thesis by (induct A) (fact empty insert)+\nqed\n\n\nsubsubsection \\<open>Choice principles\\<close>\n\nlemma ex_new_if_finite: \\<comment> \\<open>does not depend on def of finite at all\\<close>\n  assumes \"\\<not> finite (UNIV :: 'a set)\" and \"finite A\"\n  shows \"\\<exists>a::'a. a \\<notin> A\"\nproof -\n  from assms have \"A \\<noteq> UNIV\" by blast\n  then show ?thesis by blast\nqed\n\ntext \\<open>A finite choice principle. Does not need the SOME choice operator.\\<close>\n\nlemma finite_set_choice: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. \\<exists>y. P x y \\<Longrightarrow> \\<exists>f. \\<forall>x\\<in>A. P x (f x)\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then obtain f b where f: \"\\<forall>x\\<in>A. P x (f x)\" and ab: \"P a b\"\n    by auto\n  show ?case (is \"\\<exists>f. ?P f\")\n  proof\n    show \"?P (\\<lambda>x. if x = a then b else f x)\"\n      using f ab by auto\n  qed\nqed\n\n\nsubsubsection \\<open>Finite sets are the images of initial segments of natural numbers\\<close>\n\nlemma finite_imp_nat_seg_image_inj_on:\n  assumes \"finite A\"\n  shows \"\\<exists>(n::nat) f. A = f ` {i. i < n} \\<and> inj_on f {i. i < n}\"\n  using assms\nproof induct\n  case empty\n  show ?case\n  proof\n    show \"\\<exists>f. {} = f ` {i::nat. i < 0} \\<and> inj_on f {i. i < 0}\"\n      by simp\n  qed\nnext\n  case (insert a A)\n  have notinA: \"a \\<notin> A\" by fact\n  from insert.hyps obtain n f where \"A = f ` {i::nat. i < n}\" \"inj_on f {i. i < n}\"\n    by blast\n  then have \"insert a A = f(n:=a) ` {i. i < Suc n}\" and \"inj_on (f(n:=a)) {i. i < Suc n}\"\n    using notinA by (auto simp add: image_def Ball_def inj_on_def less_Suc_eq)\n  then show ?case by blast\nqed\n\nlemma nat_seg_image_imp_finite: \"A = f ` {i::nat. i < n} \\<Longrightarrow> finite A\"\nproof (induct n arbitrary: A)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  let ?B = \"f ` {i. i < n}\"\n  have finB: \"finite ?B\" by (rule Suc.hyps[OF refl])\n  show ?case\n  proof (cases \"\\<exists>k<n. f n = f k\")\n    case True\n    then have \"A = ?B\"\n      using Suc.prems by (auto simp:less_Suc_eq)\n    then show ?thesis\n      using finB by simp\n  next\n    case False\n    then have \"A = insert (f n) ?B\"\n      using Suc.prems by (auto simp:less_Suc_eq)\n    then show ?thesis using finB by simp\n  qed\nqed\n\nlemma finite_conv_nat_seg_image: \"finite A \\<longleftrightarrow> (\\<exists>n f. A = f ` {i::nat. i < n})\"\n  by (blast intro: nat_seg_image_imp_finite dest: finite_imp_nat_seg_image_inj_on)\n\nlemma finite_imp_inj_to_nat_seg:\n  assumes \"finite A\"\n  shows \"\\<exists>f n. f ` A = {i::nat. i < n} \\<and> inj_on f A\"\nproof -\n  from finite_imp_nat_seg_image_inj_on [OF \\<open>finite A\\<close>]\n  obtain f and n :: nat where bij: \"bij_betw f {i. i<n} A\"\n    by (auto simp: bij_betw_def)\n  let ?f = \"the_inv_into {i. i<n} f\"\n  have \"inj_on ?f A \\<and> ?f ` A = {i. i<n}\"\n    by (fold bij_betw_def) (rule bij_betw_the_inv_into[OF bij])\n  then show ?thesis by blast\nqed\n\nlemma finite_Collect_less_nat [iff]: \"finite {n::nat. n < k}\"\n  by (fastforce simp: finite_conv_nat_seg_image)\n\nlemma finite_Collect_le_nat [iff]: \"finite {n::nat. n \\<le> k}\"\n  by (simp add: le_eq_less_or_eq Collect_disj_eq)\n\n\nsubsection \\<open>Finiteness and common set operations\\<close>\n\nlemma rev_finite_subset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> finite A\"\nproof (induct arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F A)\n  have A: \"A \\<subseteq> insert x F\" and r: \"A - {x} \\<subseteq> F \\<Longrightarrow> finite (A - {x})\"\n    by fact+\n  show \"finite A\"\n  proof cases\n    assume x: \"x \\<in> A\"\n    with A have \"A - {x} \\<subseteq> F\" by (simp add: subset_insert_iff)\n    with r have \"finite (A - {x})\" .\n    then have \"finite (insert x (A - {x}))\" ..\n    also have \"insert x (A - {x}) = A\"\n      using x by (rule insert_Diff)\n    finally show ?thesis .\n  next\n    show ?thesis when \"A \\<subseteq> F\"\n      using that by fact\n    assume \"x \\<notin> A\"\n    with A show \"A \\<subseteq> F\"\n      by (simp add: subset_insert_iff)\n  qed\nqed\n\nlemma finite_subset: \"A \\<subseteq> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  by (rule rev_finite_subset)\n\nsimproc_setup finite (\"finite A\") = \\<open>fn _ =>\nlet\n  val finite_subset = @{thm finite_subset}\n  val Eq_TrueI = @{thm Eq_TrueI}\n\n  fun is_subset A th = case Thm.prop_of th of\n        (_ $ (Const (\\<^const_name>\\<open>less_eq\\<close>, Type (\\<^type_name>\\<open>fun\\<close>, [Type (\\<^type_name>\\<open>set\\<close>, _), _])) $ A' $ B))\n        => if A aconv A' then SOME(B,th) else NONE\n      | _ => NONE;\n\n  fun is_finite th = case Thm.prop_of th of\n        (_ $ (Const (\\<^const_name>\\<open>finite\\<close>, _) $ A)) => SOME(A,th)\n      |  _ => NONE;\n\n  fun comb (A,sub_th) (A',fin_th) ths = if A aconv A' then (sub_th,fin_th) :: ths else ths\n\n  fun proc ss ct =\n    (let\n       val _ $ A = Thm.term_of ct\n       val prems = Simplifier.prems_of ss\n       val fins = map_filter is_finite prems\n       val subsets = map_filter (is_subset A) prems\n     in case fold_product comb subsets fins [] of\n          (sub_th,fin_th) :: _ => SOME((fin_th RS (sub_th RS finite_subset)) RS Eq_TrueI)\n        | _ => NONE\n     end)\nin proc end\n\\<close>\n\n(* Needs to be used with care *)\ndeclare [[simproc del: finite]]\n\nlemma finite_UnI:\n  assumes \"finite F\" and \"finite G\"\n  shows \"finite (F \\<union> G)\"\n  using assms by induct simp_all\n\nlemma finite_Un [iff]: \"finite (F \\<union> G) \\<longleftrightarrow> finite F \\<and> finite G\"\n  by (blast intro: finite_UnI finite_subset [of _ \"F \\<union> G\"])\n\nlemma finite_insert [simp]: \"finite (insert a A) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite {a} \\<and> finite A \\<longleftrightarrow> finite A\" by simp\n  then have \"finite ({a} \\<union> A) \\<longleftrightarrow> finite A\" by (simp only: finite_Un)\n  then show ?thesis by simp\nqed\n\nlemma finite_Int [simp, intro]: \"finite F \\<or> finite G \\<Longrightarrow> finite (F \\<inter> G)\"\n  by (blast intro: finite_subset)\n\nlemma finite_Collect_conjI [simp, intro]:\n  \"finite {x. P x} \\<or> finite {x. Q x} \\<Longrightarrow> finite {x. P x \\<and> Q x}\"\n  by (simp add: Collect_conj_eq)\n\nlemma finite_Collect_disjI [simp]:\n  \"finite {x. P x \\<or> Q x} \\<longleftrightarrow> finite {x. P x} \\<and> finite {x. Q x}\"\n  by (simp add: Collect_disj_eq)\n\nlemma finite_Diff [simp, intro]: \"finite A \\<Longrightarrow> finite (A - B)\"\n  by (rule finite_subset, rule Diff_subset)\n\nlemma finite_Diff2 [simp]:\n  assumes \"finite B\"\n  shows \"finite (A - B) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite A \\<longleftrightarrow> finite ((A - B) \\<union> (A \\<inter> B))\"\n    by (simp add: Un_Diff_Int)\n  also have \"\\<dots> \\<longleftrightarrow> finite (A - B)\"\n    using \\<open>finite B\\<close> by simp\n  finally show ?thesis ..\nqed\n\nlemma finite_Diff_insert [iff]: \"finite (A - insert a B) \\<longleftrightarrow> finite (A - B)\"\nproof -\n  have \"finite (A - B) \\<longleftrightarrow> finite (A - B - {a})\" by simp\n  moreover have \"A - insert a B = A - B - {a}\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma finite_compl [simp]:\n  \"finite (A :: 'a set) \\<Longrightarrow> finite (- A) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Compl_eq_Diff_UNIV)\n\nlemma finite_Collect_not [simp]:\n  \"finite {x :: 'a. P x} \\<Longrightarrow> finite {x. \\<not> P x} \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Collect_neg_eq)\n\nlemma finite_Union [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>M. M \\<in> A \\<Longrightarrow> finite M) \\<Longrightarrow> finite (\\<Union>A)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN_I [intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (\\<Union>a\\<in>A. B a)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN [simp]: \"finite A \\<Longrightarrow> finite (\\<Union>(B ` A)) \\<longleftrightarrow> (\\<forall>x\\<in>A. finite (B x))\"\n  by (blast intro: finite_subset)\n\nlemma finite_Inter [intro]: \"\\<exists>A\\<in>M. finite A \\<Longrightarrow> finite (\\<Inter>M)\"\n  by (blast intro: Inter_lower finite_subset)\n\nlemma finite_INT [intro]: \"\\<exists>x\\<in>I. finite (A x) \\<Longrightarrow> finite (\\<Inter>x\\<in>I. A x)\"\n  by (blast intro: INT_lower finite_subset)\n\nlemma finite_imageI [simp, intro]: \"finite F \\<Longrightarrow> finite (h ` F)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_image_set [simp]: \"finite {x. P x} \\<Longrightarrow> finite {f x |x. P x}\"\n  by (simp add: image_Collect [symmetric])\n\nlemma finite_image_set2:\n  \"finite {x. P x} \\<Longrightarrow> finite {y. Q y} \\<Longrightarrow> finite {f x y |x y. P x \\<and> Q y}\"\n  by (rule finite_subset [where B = \"\\<Union>x \\<in> {x. P x}. \\<Union>y \\<in> {y. Q y}. {f x y}\"]) auto\n\nlemma finite_imageD:\n  assumes \"finite (f ` A)\" and \"inj_on f A\"\n  shows \"finite A\"\n  using assms\nproof (induct \"f ` A\" arbitrary: A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x B)\n  then have B_A: \"insert x B = f ` A\"\n    by simp\n  then obtain y where \"x = f y\" and \"y \\<in> A\"\n    by blast\n  from B_A \\<open>x \\<notin> B\\<close> have \"B = f ` A - {x}\"\n    by blast\n  with B_A \\<open>x \\<notin> B\\<close> \\<open>x = f y\\<close> \\<open>inj_on f A\\<close> \\<open>y \\<in> A\\<close> have \"B = f ` (A - {y})\"\n    by (simp add: inj_on_image_set_diff)\n  moreover from \\<open>inj_on f A\\<close> have \"inj_on f (A - {y})\"\n    by (rule inj_on_diff)\n  ultimately have \"finite (A - {y})\"\n    by (rule insert.hyps)\n  then show \"finite A\"\n    by simp\nqed\n\nlemma finite_image_iff: \"inj_on f A \\<Longrightarrow> finite (f ` A) \\<longleftrightarrow> finite A\"\n  using finite_imageD by blast\n\nlemma finite_surj: \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> finite B\"\n  by (erule finite_subset) (rule finite_imageI)\n\nlemma finite_range_imageI: \"finite (range g) \\<Longrightarrow> finite (range (\\<lambda>x. f (g x)))\"\n  by (drule finite_imageI) (simp add: range_composition)\n\nlemma finite_subset_image:\n  assumes \"finite B\"\n  shows \"B \\<subseteq> f ` A \\<Longrightarrow> \\<exists>C\\<subseteq>A. finite C \\<and> B = f ` C\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (clarsimp simp del: image_insert simp add: image_insert [symmetric]) blast\nqed\n\nlemma all_subset_image: \"(\\<forall>B. B \\<subseteq> f ` A \\<longrightarrow> P B) \\<longleftrightarrow> (\\<forall>B. B \\<subseteq> A \\<longrightarrow> P(f ` B))\"\n  by (safe elim!: subset_imageE) (use image_mono in \\<open>blast+\\<close>) (* slow *)\n\nlemma all_finite_subset_image:\n  \"(\\<forall>B. finite B \\<and> B \\<subseteq> f ` A \\<longrightarrow> P B) \\<longleftrightarrow> (\\<forall>B. finite B \\<and> B \\<subseteq> A \\<longrightarrow> P (f ` B))\"\nproof safe\n  fix B :: \"'a set\"\n  assume B: \"finite B\" \"B \\<subseteq> f ` A\" and P: \"\\<forall>B. finite B \\<and> B \\<subseteq> A \\<longrightarrow> P (f ` B)\"\n  show \"P B\"\n    using finite_subset_image [OF B] P by blast\nqed blast\n\nlemma ex_finite_subset_image:\n  \"(\\<exists>B. finite B \\<and> B \\<subseteq> f ` A \\<and> P B) \\<longleftrightarrow> (\\<exists>B. finite B \\<and> B \\<subseteq> A \\<and> P (f ` B))\"\nproof safe\n  fix B :: \"'a set\"\n  assume B: \"finite B\" \"B \\<subseteq> f ` A\" and \"P B\"\n  show \"\\<exists>B. finite B \\<and> B \\<subseteq> A \\<and> P (f ` B)\"\n    using finite_subset_image [OF B] \\<open>P B\\<close> by blast\nqed blast\n\nlemma finite_vimage_IntI: \"finite F \\<Longrightarrow> inj_on h A \\<Longrightarrow> finite (h -` F \\<inter> A)\"\nproof (induct rule: finite_induct)\n  case (insert x F)\n  then show ?case\n    by (simp add: vimage_insert [of h x F] finite_subset [OF inj_on_vimage_singleton] Int_Un_distrib2)\nqed simp\n\nlemma finite_finite_vimage_IntI:\n  assumes \"finite F\"\n    and \"\\<And>y. y \\<in> F \\<Longrightarrow> finite ((h -` {y}) \\<inter> A)\"\n  shows \"finite (h -` F \\<inter> A)\"\nproof -\n  have *: \"h -` F \\<inter> A = (\\<Union> y\\<in>F. (h -` {y}) \\<inter> A)\"\n    by blast\n  show ?thesis\n    by (simp only: * assms finite_UN_I)\nqed\n\nlemma finite_vimageI: \"finite F \\<Longrightarrow> inj h \\<Longrightarrow> finite (h -` F)\"\n  using finite_vimage_IntI[of F h UNIV] by auto\n\nlemma finite_vimageD': \"finite (f -` A) \\<Longrightarrow> A \\<subseteq> range f \\<Longrightarrow> finite A\"\n  by (auto simp add: subset_image_iff intro: finite_subset[rotated])\n\nlemma finite_vimageD: \"finite (h -` F) \\<Longrightarrow> surj h \\<Longrightarrow> finite F\"\n  by (auto dest: finite_vimageD')\n\nlemma finite_vimage_iff: \"bij h \\<Longrightarrow> finite (h -` F) \\<longleftrightarrow> finite F\"\n  unfolding bij_def by (auto elim: finite_vimageD finite_vimageI)\n\nlemma finite_inverse_image_gen:\n  assumes \"finite A\" \"inj_on f D\"\n  shows \"finite {j\\<in>D. f j \\<in> A}\"\n  using finite_vimage_IntI [OF assms]\n  by (simp add: Collect_conj_eq inf_commute vimage_def)\n\nlemma finite_inverse_image:\n  assumes \"finite A\" \"inj f\"\n  shows \"finite {j. f j \\<in> A}\"\n  using finite_inverse_image_gen [OF assms] by simp\n\nlemma finite_Collect_bex [simp]:\n  assumes \"finite A\"\n  shows \"finite {x. \\<exists>y\\<in>A. Q x y} \\<longleftrightarrow> (\\<forall>y\\<in>A. finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y\\<in>A. Q x y} = (\\<Union>y\\<in>A. {x. Q x y})\" by auto\n  with assms show ?thesis by simp\nqed\n\nlemma finite_Collect_bounded_ex [simp]:\n  assumes \"finite {y. P y}\"\n  shows \"finite {x. \\<exists>y. P y \\<and> Q x y} \\<longleftrightarrow> (\\<forall>y. P y \\<longrightarrow> finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y. P y \\<and> Q x y} = (\\<Union>y\\<in>{y. P y}. {x. Q x y})\"\n    by auto\n  with assms show ?thesis\n    by simp\nqed\n\nlemma finite_Plus: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A <+> B)\"\n  by (simp add: Plus_def)\n\nlemma finite_PlusD:\n  fixes A :: \"'a set\" and B :: \"'b set\"\n  assumes fin: \"finite (A <+> B)\"\n  shows \"finite A\" \"finite B\"\nproof -\n  have \"Inl ` A \\<subseteq> A <+> B\"\n    by auto\n  then have \"finite (Inl ` A :: ('a + 'b) set)\"\n    using fin by (rule finite_subset)\n  then show \"finite A\"\n    by (rule finite_imageD) (auto intro: inj_onI)\nnext\n  have \"Inr ` B \\<subseteq> A <+> B\"\n    by auto\n  then have \"finite (Inr ` B :: ('a + 'b) set)\"\n    using fin by (rule finite_subset)\n  then show \"finite B\"\n    by (rule finite_imageD) (auto intro: inj_onI)\nqed\n\nlemma finite_Plus_iff [simp]: \"finite (A <+> B) \\<longleftrightarrow> finite A \\<and> finite B\"\n  by (auto intro: finite_PlusD finite_Plus)\n\nlemma finite_Plus_UNIV_iff [simp]:\n  \"finite (UNIV :: ('a + 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  by (subst UNIV_Plus_UNIV [symmetric]) (rule finite_Plus_iff)\n\nlemma finite_SigmaI [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a\\<in>A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (SIGMA a:A. B a)\"\n  unfolding Sigma_def by blast\n\nlemma finite_SigmaI2:\n  assumes \"finite {x\\<in>A. B x \\<noteq> {}}\"\n  and \"\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)\"\n  shows \"finite (Sigma A B)\"\nproof -\n  from assms have \"finite (Sigma {x\\<in>A. B x \\<noteq> {}} B)\"\n    by auto\n  also have \"Sigma {x:A. B x \\<noteq> {}} B = Sigma A B\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma finite_cartesian_product: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<times> B)\"\n  by (rule finite_SigmaI)\n\nlemma finite_Prod_UNIV:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> finite (UNIV :: 'b set) \\<Longrightarrow> finite (UNIV :: ('a \\<times> 'b) set)\"\n  by (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product)\n\nlemma finite_cartesian_productD1:\n  assumes \"finite (A \\<times> B)\" and \"B \\<noteq> {}\"\n  shows \"finite A\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"fst ` (A \\<times> B) = fst ` f ` {i::nat. i < n}\"\n    by simp\n  with \\<open>B \\<noteq> {}\\<close> have \"A = (fst \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. A = f ` {i::nat. i < n}\"\n    by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_productD2:\n  assumes \"finite (A \\<times> B)\" and \"A \\<noteq> {}\"\n  shows \"finite B\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"snd ` (A \\<times> B) = snd ` f ` {i::nat. i < n}\"\n    by simp\n  with \\<open>A \\<noteq> {}\\<close> have \"B = (snd \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. B = f ` {i::nat. i < n}\"\n    by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_product_iff:\n  \"finite (A \\<times> B) \\<longleftrightarrow> (A = {} \\<or> B = {} \\<or> (finite A \\<and> finite B))\"\n  by (auto dest: finite_cartesian_productD1 finite_cartesian_productD2 finite_cartesian_product)\n\nlemma finite_prod:\n  \"finite (UNIV :: ('a \\<times> 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  using finite_cartesian_product_iff[of UNIV UNIV] by simp\n\nlemma finite_Pow_iff [iff]: \"finite (Pow A) \\<longleftrightarrow> finite A\"\nproof\n  assume \"finite (Pow A)\"\n  then have \"finite ((\\<lambda>x. {x}) ` A)\"\n    by (blast intro: finite_subset)  (* somewhat slow *)\n  then show \"finite A\"\n    by (rule finite_imageD [unfolded inj_on_def]) simp\nnext\n  assume \"finite A\"\n  then show \"finite (Pow A)\"\n    by induct (simp_all add: Pow_insert)\nqed\n\ncorollary finite_Collect_subsets [simp, intro]: \"finite A \\<Longrightarrow> finite {B. B \\<subseteq> A}\"\n  by (simp add: Pow_def [symmetric])\n\nlemma finite_set: \"finite (UNIV :: 'a set set) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp only: finite_Pow_iff Pow_UNIV[symmetric])\n\nlemma finite_UnionD: \"finite (\\<Union>A) \\<Longrightarrow> finite A\"\n  by (blast intro: finite_subset [OF subset_Pow_Union])\n\nlemma finite_bind:\n  assumes \"finite S\"\n  assumes \"\\<forall>x \\<in> S. finite (f x)\"\n  shows \"finite (Set.bind S f)\"\nusing assms by (simp add: bind_UNION)\n\nlemma finite_filter [simp]: \"finite S \\<Longrightarrow> finite (Set.filter P S)\"\nunfolding Set.filter_def by simp\n\nlemma finite_set_of_finite_funs:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {f. \\<forall>x. (x \\<in> A \\<longrightarrow> f x \\<in> B) \\<and> (x \\<notin> A \\<longrightarrow> f x = d)}\" (is \"finite ?S\")\nproof -\n  let ?F = \"\\<lambda>f. {(a,b). a \\<in> A \\<and> b = f a}\"\n  have \"?F ` ?S \\<subseteq> Pow(A \\<times> B)\"\n    by auto\n  from finite_subset[OF this] assms have 1: \"finite (?F ` ?S)\"\n    by simp\n  have 2: \"inj_on ?F ?S\"\n    by (fastforce simp add: inj_on_def set_eq_iff fun_eq_iff)  (* somewhat slow *)\n  show ?thesis\n    by (rule finite_imageD [OF 1 2])\nqed\n\nlemma not_finite_existsD:\n  assumes \"\\<not> finite {a. P a}\"\n  shows \"\\<exists>a. P a\"\nproof (rule classical)\n  assume \"\\<not> ?thesis\"\n  with assms show ?thesis by auto\nqed\n\nlemma finite_converse [iff]: \"finite (r\\<inverse>) \\<longleftrightarrow> finite r\"\n  unfolding converse_def conversep_iff\n  using [[simproc add: finite_Collect]]\n  by (auto elim: finite_imageD simp: inj_on_def)\n\nlemma finite_Domain: \"finite r \\<Longrightarrow> finite (Domain r)\"\n  by (induct set: finite) auto\n\nlemma finite_Range: \"finite r \\<Longrightarrow> finite (Range r)\"\n  by (induct set: finite) auto\n\nlemma finite_Field: \"finite r \\<Longrightarrow> finite (Field r)\"\n  by (simp add: Field_def finite_Domain finite_Range)\n\nlemma finite_Image[simp]: \"finite R \\<Longrightarrow> finite (R `` A)\"\n  by(rule finite_subset[OF _ finite_Range]) auto\n\n\nsubsection \\<open>Further induction rules on finite sets\\<close>\n\nlemma finite_ne_induct [case_names singleton insert, consumes 2]:\n  assumes \"finite F\" and \"F \\<noteq> {}\"\n  assumes \"\\<And>x. P {x}\"\n    and \"\\<And>x F. finite F \\<Longrightarrow> F \\<noteq> {} \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F  \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case by cases auto\nqed\n\nlemma finite_subset_induct [consumes 2, case_names empty insert]:\n  assumes \"finite F\" and \"F \\<subseteq> A\"\n    and empty: \"P {}\"\n    and insert: \"\\<And>a F. finite F \\<Longrightarrow> a \\<in> A \\<Longrightarrow> a \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert a F)\"\n  shows \"P F\"\n  using \\<open>finite F\\<close> \\<open>F \\<subseteq> A\\<close>\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume \"finite F\" and \"x \\<notin> F\" and P: \"F \\<subseteq> A \\<Longrightarrow> P F\" and i: \"insert x F \\<subseteq> A\"\n  show \"P (insert x F)\"\n  proof (rule insert)\n    from i show \"x \\<in> A\" by blast\n    from i have \"F \\<subseteq> A\" by blast\n    with P show \"P F\" .\n    show \"finite F\" by fact\n    show \"x \\<notin> F\" by fact\n  qed\nqed\n\nlemma finite_empty_induct:\n  assumes \"finite A\"\n    and \"P A\"\n    and remove: \"\\<And>a A. finite A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> P A \\<Longrightarrow> P (A - {a})\"\n  shows \"P {}\"\nproof -\n  have \"P (A - B)\" if \"B \\<subseteq> A\" for B :: \"'a set\"\n  proof -\n    from \\<open>finite A\\<close> that have \"finite B\"\n      by (rule rev_finite_subset)\n    from this \\<open>B \\<subseteq> A\\<close> show \"P (A - B)\"\n    proof induct\n      case empty\n      from \\<open>P A\\<close> show ?case by simp\n    next\n      case (insert b B)\n      have \"P (A - B - {b})\"\n      proof (rule remove)\n        from \\<open>finite A\\<close> show \"finite (A - B)\"\n          by induct auto\n        from insert show \"b \\<in> A - B\"\n          by simp\n        from insert show \"P (A - B)\"\n          by simp\n      qed\n      also have \"A - B - {b} = A - insert b B\"\n        by (rule Diff_insert [symmetric])\n      finally show ?case .\n    qed\n  qed\n  then have \"P (A - A)\" by blast\n  then show ?thesis by simp\nqed\n\nlemma finite_update_induct [consumes 1, case_names const update]:\n  assumes finite: \"finite {a. f a \\<noteq> c}\"\n    and const: \"P (\\<lambda>a. c)\"\n    and update: \"\\<And>a b f. finite {a. f a \\<noteq> c} \\<Longrightarrow> f a = c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> P f \\<Longrightarrow> P (f(a := b))\"\n  shows \"P f\"\n  using finite\nproof (induct \"{a. f a \\<noteq> c}\" arbitrary: f)\n  case empty\n  with const show ?case by simp\nnext\n  case (insert a A)\n  then have \"A = {a'. (f(a := c)) a' \\<noteq> c}\" and \"f a \\<noteq> c\"\n    by auto\n  with \\<open>finite A\\<close> have \"finite {a'. (f(a := c)) a' \\<noteq> c}\"\n    by simp\n  have \"(f(a := c)) a = c\"\n    by simp\n  from insert \\<open>A = {a'. (f(a := c)) a' \\<noteq> c}\\<close> have \"P (f(a := c))\"\n    by simp\n  with \\<open>finite {a'. (f(a := c)) a' \\<noteq> c}\\<close> \\<open>(f(a := c)) a = c\\<close> \\<open>f a \\<noteq> c\\<close>\n  have \"P ((f(a := c))(a := f a))\"\n    by (rule update)\n  then show ?case by simp\nqed\n\n\n\n\nsubsection \\<open>Class \\<open>finite\\<close>\\<close>\n\nclass finite =\n  assumes finite_UNIV: \"finite (UNIV :: 'a set)\"\nbegin\n\nlemma finite [simp]: \"finite (A :: 'a set)\"\n  by (rule subset_UNIV finite_UNIV finite_subset)+\n\nlemma finite_code [code]: \"finite (A :: 'a set) \\<longleftrightarrow> True\"\n  by simp\n\nend\n\ninstance prod :: (finite, finite) finite\n  by standard (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product finite)\n\nlemma inj_graph: \"inj (\\<lambda>f. {(x, y). y = f x})\"\n  by (rule inj_onI) (auto simp add: set_eq_iff fun_eq_iff)\n\ninstance \"fun\" :: (finite, finite) finite\nproof\n  show \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  proof (rule finite_imageD)\n    let ?graph = \"\\<lambda>f::'a \\<Rightarrow> 'b. {(x, y). y = f x}\"\n    have \"range ?graph \\<subseteq> Pow UNIV\"\n      by simp\n    moreover have \"finite (Pow (UNIV :: ('a * 'b) set))\"\n      by (simp only: finite_Pow_iff finite)\n    ultimately show \"finite (range ?graph)\"\n      by (rule finite_subset)\n    show \"inj ?graph\"\n      by (rule inj_graph)\n  qed\nqed\n\ninstance bool :: finite\n  by standard (simp add: UNIV_bool)\n\ninstance set :: (finite) finite\n  by standard (simp only: Pow_UNIV [symmetric] finite_Pow_iff finite)\n\ninstance unit :: finite\n  by standard (simp add: UNIV_unit)\n\ninstance sum :: (finite, finite) finite\n  by standard (simp only: UNIV_Plus_UNIV [symmetric] finite_Plus finite)\n\n\nsubsection \\<open>A basic fold functional for finite sets\\<close>\n\ntext \\<open>\n  The intended behaviour is \\<open>fold f z {x\\<^sub>1, \\<dots>, x\\<^sub>n} = f x\\<^sub>1 (\\<dots> (f x\\<^sub>n z)\\<dots>)\\<close>\n  if \\<open>f\\<close> is ``left-commutative''.\n  The commutativity requirement is relativised to the carrier set \\<open>S\\<close>:\n\\<close>\n\nlocale comp_fun_commute_on =\n  fixes S :: \"'a set\"\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  assumes comp_fun_commute_on: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma fun_left_comm: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y (f x z) = f x (f y z)\"\n  using comp_fun_commute_on by (simp add: fun_eq_iff)\n\nlemma commute_left_comp: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y \\<circ> (f x \\<circ> g) = f x \\<circ> (f y \\<circ> g)\"\n  by (simp add: o_assoc comp_fun_commute_on)\n\nend\n\ninductive fold_graph :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  for f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: 'b\n  where\n    emptyI [intro]: \"fold_graph f z {} z\"\n  | insertI [intro]: \"x \\<notin> A \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> fold_graph f z (insert x A) (f x y)\"\n\ninductive_cases empty_fold_graphE [elim!]: \"fold_graph f z {} x\"\n\nlemma fold_graph_closed_lemma:\n  \"fold_graph f z A x \\<and> x \\<in> B\"\n  if \"fold_graph g z A x\"\n    \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> f a b = g a b\"\n    \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> g a b \\<in> B\"\n    \"z \\<in> B\"\n  using that(1-3)\nproof (induction rule: fold_graph.induct)\n  case (insertI x A y)\n  have \"fold_graph f z A y\" \"y \\<in> B\"\n    unfolding atomize_conj\n    by (rule insertI.IH) (auto intro: insertI.prems)\n  then have \"g x y \\<in> B\" and f_eq: \"f x y = g x y\"\n    by (auto simp: insertI.prems)\n  moreover have \"fold_graph f z (insert x A) (f x y)\"\n    by (rule fold_graph.insertI; fact)\n  ultimately\n  show ?case\n    by (simp add: f_eq)\nqed (auto intro!: that)\n\nlemma fold_graph_closed_eq:\n  \"fold_graph f z A = fold_graph g z A\"\n  if \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> f a b = g a b\"\n     \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> g a b \\<in> B\"\n     \"z \\<in> B\"\n  using fold_graph_closed_lemma[of f z A _ B g] fold_graph_closed_lemma[of g z A _ B f] that\n  by auto\n\ndefinition fold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b\"\n  where \"fold f z A = (if finite A then (THE y. fold_graph f z A y) else z)\"\n\nlemma fold_closed_eq: \"fold f z A = fold g z A\"\n  if \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> f a b = g a b\"\n     \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> g a b \\<in> B\"\n     \"z \\<in> B\"\n  unfolding Finite_Set.fold_def\n  by (subst fold_graph_closed_eq[where B=B and g=g]) (auto simp: that)\n\ntext \\<open>\n  A tempting alternative for the definition is\n  \\<^term>\\<open>if finite A then THE y. fold_graph f z A y else e\\<close>.\n  It allows the removal of finiteness assumptions from the theorems\n  \\<open>fold_comm\\<close>, \\<open>fold_reindex\\<close> and \\<open>fold_distrib\\<close>.\n  The proofs become ugly. It is not worth the effort. (???)\n\\<close>\n\nlemma finite_imp_fold_graph: \"finite A \\<Longrightarrow> \\<exists>x. fold_graph f z A x\"\n  by (induct rule: finite_induct) auto\n\n\nsubsubsection \\<open>From \\<^const>\\<open>fold_graph\\<close> to \\<^term>\\<open>fold\\<close>\\<close>\n\ncontext comp_fun_commute_on\nbegin\n\n\n\nlemma fold_graph_insertE_aux:\n  assumes \"A \\<subseteq> S\"\n  assumes \"fold_graph f z A y\" \"a \\<in> A\"\n  shows \"\\<exists>y'. y = f a y' \\<and> fold_graph f z (A - {a}) y'\"\n  using assms(2-,1)\nproof (induct set: fold_graph)\n  case emptyI\n  then show ?case by simp\nnext\n  case (insertI x A y)\n  show ?case\n  proof (cases \"x = a\")\n    case True\n    with insertI show ?thesis by auto\n  next\n    case False\n    then obtain y' where y: \"y = f a y'\" and y': \"fold_graph f z (A - {a}) y'\"\n      using insertI by auto\n    from insertI have \"x \\<in> S\" \"a \\<in> S\" by auto\n    then have \"f x y = f a (f x y')\"\n      unfolding y by (intro fun_left_comm; simp)\n    moreover have \"fold_graph f z (insert x A - {a}) (f x y')\"\n      using y' and \\<open>x \\<noteq> a\\<close> and \\<open>x \\<notin> A\\<close>\n      by (simp add: insert_Diff_if fold_graph.insertI)\n    ultimately show ?thesis\n      by fast\n  qed\nqed\n\nlemma fold_graph_insertE:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes \"fold_graph f z (insert x A) v\" and \"x \\<notin> A\"\n  obtains y where \"v = f x y\" and \"fold_graph f z A y\"\n  using assms by (auto dest: fold_graph_insertE_aux[OF \\<open>insert x A \\<subseteq> S\\<close> _ insertI1])\n\nlemma fold_graph_determ:\n  assumes \"A \\<subseteq> S\"\n  assumes \"fold_graph f z A x\" \"fold_graph f z A y\"\n  shows \"y = x\"\n  using assms(2-,1)\nproof (induct arbitrary: y set: fold_graph)\n  case emptyI\n  then show ?case by fast\nnext\n  case (insertI x A y v)\n  from \\<open>insert x A \\<subseteq> S\\<close> and \\<open>fold_graph f z (insert x A) v\\<close> and \\<open>x \\<notin> A\\<close>\n  obtain y' where \"v = f x y'\" and \"fold_graph f z A y'\"\n    by (rule fold_graph_insertE)\n  from \\<open>fold_graph f z A y'\\<close> insertI have \"y' = y\"\n    by simp\n  with \\<open>v = f x y'\\<close> show \"v = f x y\"\n    by simp\nqed\n\nlemma fold_equality: \"A \\<subseteq> S \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> fold f z A = y\"\n  by (cases \"finite A\") (auto simp add: fold_def intro: fold_graph_determ dest: fold_graph_finite)\n\nlemma fold_graph_fold:\n  assumes \"A \\<subseteq> S\"\n  assumes \"finite A\"\n  shows \"fold_graph f z A (fold f z A)\"\nproof -\n  from \\<open>finite A\\<close> have \"\\<exists>x. fold_graph f z A x\"\n    by (rule finite_imp_fold_graph)\n  moreover note fold_graph_determ[OF \\<open>A \\<subseteq> S\\<close>]\n  ultimately have \"\\<exists>!x. fold_graph f z A x\"\n    by (rule ex_ex1I)\n  then have \"fold_graph f z A (The (fold_graph f z A))\"\n    by (rule theI')\n  with assms show ?thesis\n    by (simp add: fold_def)\nqed\n\ntext \\<open>The base case for \\<open>fold\\<close>:\\<close>\n\nlemma (in -) fold_infinite [simp]: \"\\<not> finite A \\<Longrightarrow> fold f z A = z\"\n  by (auto simp: fold_def)\n\nlemma (in -) fold_empty [simp]: \"fold f z {} = z\"\n  by (auto simp: fold_def)\n\ntext \\<open>The various recursion equations for \\<^const>\\<open>fold\\<close>:\\<close>\n\nlemma fold_insert [simp]:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"fold f z (insert x A) = f x (fold f z A)\"\nproof (rule fold_equality[OF \\<open>insert x A \\<subseteq> S\\<close>])\n  fix z\n  from \\<open>insert x A \\<subseteq> S\\<close> \\<open>finite A\\<close> have \"fold_graph f z A (fold f z A)\"\n    by (blast intro: fold_graph_fold)\n  with \\<open>x \\<notin> A\\<close> have \"fold_graph f z (insert x A) (f x (fold f z A))\"\n    by (rule fold_graph.insertI)\n  then show \"fold_graph f z (insert x A) (f x (fold f z A))\"\n    by simp\nqed\n\ndeclare (in -) empty_fold_graphE [rule del] fold_graph.intros [rule del]\n  \\<comment> \\<open>No more proofs involve these.\\<close>\n\nlemma fold_fun_left_comm:\n  assumes \"insert x A \\<subseteq> S\" \"finite A\" \n  shows \"f x (fold f z A) = fold f (f x z) A\"\n  using assms(2,1)\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert y F)\n  then have \"fold f (f x z) (insert y F) = f y (fold f (f x z) F)\"\n    by simp\n  also have \"\\<dots> = f x (f y (fold f z F))\"\n    using insert by (simp add: fun_left_comm[where ?y=x])\n  also have \"\\<dots> = f x (fold f z (insert y F))\"\n  proof -\n    from insert have \"insert y F \\<subseteq> S\" by simp\n    from fold_insert[OF this] insert show ?thesis by simp\n  qed\n  finally show ?case ..\nqed\n\nlemma fold_insert2:\n  \"insert x A \\<subseteq> S \\<Longrightarrow> finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> fold f z (insert x A)  = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nlemma fold_rec:\n  assumes \"A \\<subseteq> S\"\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"fold f z A = f x (fold f z (A - {x}))\"\nproof -\n  have A: \"A = insert x (A - {x})\"\n    using \\<open>x \\<in> A\\<close> by blast\n  then have \"fold f z A = fold f z (insert x (A - {x}))\"\n    by simp\n  also have \"\\<dots> = f x (fold f z (A - {x}))\"\n    by (rule fold_insert) (use assms in \\<open>auto\\<close>)\n  finally show ?thesis .\nqed\n\nlemma fold_insert_remove:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes \"finite A\"\n  shows \"fold f z (insert x A) = f x (fold f z (A - {x}))\"\nproof -\n  from \\<open>finite A\\<close> have \"finite (insert x A)\"\n    by auto\n  moreover have \"x \\<in> insert x A\"\n    by auto\n  ultimately have \"fold f z (insert x A) = f x (fold f z (insert x A - {x}))\"\n    using \\<open>insert x A \\<subseteq> S\\<close> by (blast intro: fold_rec)\n  then show ?thesis\n    by simp\nqed\n\nlemma fold_set_union_disj:\n  assumes \"A \\<subseteq> S\" \"B \\<subseteq> S\"\n  assumes \"finite A\" \"finite B\" \"A \\<inter> B = {}\"\n  shows \"Finite_Set.fold f z (A \\<union> B) = Finite_Set.fold f (Finite_Set.fold f z A) B\"\n  using \\<open>finite B\\<close> assms(1,2,3,5)\nproof induct\n  case (insert x F)\n  have \"fold f z (A \\<union> insert x F) = f x (fold f (fold f z A) F)\"\n    using insert by auto\n  also have \"\\<dots> = fold f (fold f z A) (insert x F)\"\n    using insert by (blast intro: fold_insert[symmetric])\n  finally show ?case .\nqed simp\n\n\nend\n\ntext \\<open>Other properties of \\<^const>\\<open>fold\\<close>:\\<close>\n\nlemma fold_graph_image:\n  assumes \"inj_on g A\"\n  shows \"fold_graph f z (g ` A) = fold_graph (f \\<circ> g) z A\"\nproof\n  fix w\n  show \"fold_graph f z (g ` A) w = fold_graph (f o g) z A w\"\n  proof\n    assume \"fold_graph f z (g ` A) w\"\n    then show \"fold_graph (f \\<circ> g) z A w\"\n      using assms\n    proof (induct \"g ` A\" w arbitrary: A)\n      case emptyI\n      then show ?case by (auto intro: fold_graph.emptyI)\n    next\n      case (insertI x A r B)\n      from \\<open>inj_on g B\\<close> \\<open>x \\<notin> A\\<close> \\<open>insert x A = image g B\\<close> obtain x' A'\n        where \"x' \\<notin> A'\" and [simp]: \"B = insert x' A'\" \"x = g x'\" \"A = g ` A'\"\n        by (rule inj_img_insertE)\n      from insertI.prems have \"fold_graph (f \\<circ> g) z A' r\"\n        by (auto intro: insertI.hyps)\n      with \\<open>x' \\<notin> A'\\<close> have \"fold_graph (f \\<circ> g) z (insert x' A') ((f \\<circ> g) x' r)\"\n        by (rule fold_graph.insertI)\n      then show ?case\n        by simp\n    qed\n  next\n    assume \"fold_graph (f \\<circ> g) z A w\"\n    then show \"fold_graph f z (g ` A) w\"\n      using assms\n    proof induct\n      case emptyI\n      then show ?case\n        by (auto intro: fold_graph.emptyI)\n    next\n      case (insertI x A r)\n      from \\<open>x \\<notin> A\\<close> insertI.prems have \"g x \\<notin> g ` A\"\n        by auto\n      moreover from insertI have \"fold_graph f z (g ` A) r\"\n        by simp\n      ultimately have \"fold_graph f z (insert (g x) (g ` A)) (f (g x) r)\"\n        by (rule fold_graph.insertI)\n      then show ?case\n        by simp\n    qed\n  qed\nqed\n\nlemma fold_image:\n  assumes \"inj_on g A\"\n  shows \"fold f z (g ` A) = fold (f \\<circ> g) z A\"\nproof (cases \"finite A\")\n  case False\n  with assms show ?thesis\n    by (auto dest: finite_imageD simp add: fold_def)\nnext\n  case True\n  then show ?thesis\n    by (auto simp add: fold_def fold_graph_image[OF assms])\nqed\n\nlemma fold_cong:\n  assumes \"comp_fun_commute_on S f\" \"comp_fun_commute_on S g\"\n    and \"A \\<subseteq> S\" \"finite A\"\n    and cong: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"fold f s A = fold g t B\"\nproof -\n  have \"fold f s A = fold g s A\"\n    using \\<open>finite A\\<close> \\<open>A \\<subseteq> S\\<close> cong\n  proof (induct A)\n    case empty\n    then show ?case by simp\n  next\n    case insert\n    interpret f: comp_fun_commute_on S f by (fact \\<open>comp_fun_commute_on S f\\<close>)\n    interpret g: comp_fun_commute_on S g by (fact \\<open>comp_fun_commute_on S g\\<close>)\n    from insert show ?case by simp\n  qed\n  with assms show ?thesis by simp\nqed\n\n\ntext \\<open>A simplified version for idempotent functions:\\<close>\n\nlocale comp_fun_idem_on = comp_fun_commute_on +\n  assumes comp_fun_idem_on: \"x \\<in> S \\<Longrightarrow> f x \\<circ> f x = f x\"\nbegin\n\nlemma fun_left_idem: \"x \\<in> S \\<Longrightarrow> f x (f x z) = f x z\"\n  using comp_fun_idem_on by (simp add: fun_eq_iff)\n\nlemma fold_insert_idem:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes fin: \"finite A\"\n  shows \"fold f z (insert x A)  = f x (fold f z A)\"\nproof cases\n  assume \"x \\<in> A\"\n  then obtain B where \"A = insert x B\" and \"x \\<notin> B\"\n    by (rule set_insert)\n  then show ?thesis\n    using assms by (simp add: comp_fun_idem_on fun_left_idem)\nnext\n  assume \"x \\<notin> A\"\n  then show ?thesis\n    using assms by auto\nqed\n\ndeclare fold_insert [simp del] fold_insert_idem [simp]\n\nlemma fold_insert_idem2: \"insert x A \\<subseteq> S \\<Longrightarrow> finite A \\<Longrightarrow> fold f z (insert x A) = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nend\n\n\nsubsubsection \\<open>Liftings to \\<open>comp_fun_commute_on\\<close> etc.\\<close>\n                   \nlemma (in comp_fun_commute_on) comp_comp_fun_commute_on:\n  \"range g \\<subseteq> S \\<Longrightarrow> comp_fun_commute_on R (f \\<circ> g)\"\n  by standard (force intro: comp_fun_commute_on)\n\nlemma (in comp_fun_idem_on) comp_comp_fun_idem_on:\n  assumes \"range g \\<subseteq> S\"\n  shows \"comp_fun_idem_on R (f \\<circ> g)\"\nproof\n  interpret f_g: comp_fun_commute_on R \"f o g\"\n    by (fact comp_comp_fun_commute_on[OF \\<open>range g \\<subseteq> S\\<close>])\n  show \"x \\<in> R \\<Longrightarrow> y \\<in> R \\<Longrightarrow> (f \\<circ> g) y \\<circ> (f \\<circ> g) x = (f \\<circ> g) x \\<circ> (f \\<circ> g) y\" for x y\n    by (fact f_g.comp_fun_commute_on)\nqed (use \\<open>range g \\<subseteq> S\\<close> in \\<open>force intro: comp_fun_idem_on\\<close>)\n\nlemma (in comp_fun_commute_on) comp_fun_commute_on_funpow:\n  \"comp_fun_commute_on S (\\<lambda>x. f x ^^ g x)\"\nproof\n  fix x y assume \"x \\<in> S\" \"y \\<in> S\"\n  show \"f y ^^ g y \\<circ> f x ^^ g x = f x ^^ g x \\<circ> f y ^^ g y\"\n  proof (cases \"x = y\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    show ?thesis\n    proof (induct \"g x\" arbitrary: g)\n      case 0\n      then show ?case by simp\n    next\n      case (Suc n g)\n      have hyp1: \"f y ^^ g y \\<circ> f x = f x \\<circ> f y ^^ g y\"\n      proof (induct \"g y\" arbitrary: g)\n        case 0\n        then show ?case by simp\n      next\n        case (Suc n g)\n        define h where \"h z = g z - 1\" for z\n        with Suc have \"n = h y\"\n          by simp\n        with Suc have hyp: \"f y ^^ h y \\<circ> f x = f x \\<circ> f y ^^ h y\"\n          by auto\n        from Suc h_def have \"g y = Suc (h y)\"\n          by simp\n        with \\<open>x \\<in> S\\<close> \\<open>y \\<in> S\\<close> show ?case\n          by (simp add: comp_assoc hyp) (simp add: o_assoc comp_fun_commute_on)\n      qed\n      define h where \"h z = (if z = x then g x - 1 else g z)\" for z\n      with Suc have \"n = h x\"\n        by simp\n      with Suc have \"f y ^^ h y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ h y\"\n        by auto\n      with False h_def have hyp2: \"f y ^^ g y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ g y\"\n        by simp\n      from Suc h_def have \"g x = Suc (h x)\"\n        by simp\n      then show ?case\n        by (simp del: funpow.simps add: funpow_Suc_right o_assoc hyp2) (simp add: comp_assoc hyp1)\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>\\<^term>\\<open>UNIV\\<close> as carrier set\\<close>\n\nlocale comp_fun_commute =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma (in -) comp_fun_commute_def': \"comp_fun_commute f = comp_fun_commute_on UNIV f\"\n  unfolding comp_fun_commute_def comp_fun_commute_on_def by blast\n\ntext \\<open>\n  We abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale comp_fun_commute_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"comp_fun_commute_on UNIV f\"\n    by standard  (simp add: comp_fun_commute)\nqed simp_all\n\nend\n\nlemma (in comp_fun_commute) comp_comp_fun_commute: \"comp_fun_commute (f o g)\"\n  unfolding comp_fun_commute_def' by (fact comp_comp_fun_commute_on)\n\nlemma (in comp_fun_commute) comp_fun_commute_funpow: \"comp_fun_commute (\\<lambda>x. f x ^^ g x)\"\n  unfolding comp_fun_commute_def' by (fact comp_fun_commute_on_funpow)\n\nlocale comp_fun_idem = comp_fun_commute +\n  assumes comp_fun_idem: \"f x o f x = f x\"\nbegin\n\nlemma (in -) comp_fun_idem_def': \"comp_fun_idem f = comp_fun_idem_on UNIV f\"\n  unfolding comp_fun_idem_on_def comp_fun_idem_def comp_fun_commute_def'\n  unfolding comp_fun_idem_axioms_def comp_fun_idem_on_axioms_def\n  by blast\n\ntext \\<open>\n  Again, we abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale comp_fun_idem_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"comp_fun_idem_on UNIV f\"\n    by standard (simp_all add: comp_fun_idem comp_fun_commute)\nqed simp_all\n\nend\n\nlemma (in comp_fun_idem) comp_comp_fun_idem: \"comp_fun_idem (f o g)\"\n  unfolding comp_fun_idem_def' by (fact comp_comp_fun_idem_on)\n\n\nsubsubsection \\<open>Expressing set operations via \\<^const>\\<open>fold\\<close>\\<close>\n\nlemma comp_fun_commute_const: \"comp_fun_commute (\\<lambda>_. f)\"\n  by standard (rule refl)\n\nlemma comp_fun_idem_insert: \"comp_fun_idem insert\"\n  by standard auto\n\nlemma comp_fun_idem_remove: \"comp_fun_idem Set.remove\"\n  by standard auto\n\nlemma (in semilattice_inf) comp_fun_idem_inf: \"comp_fun_idem inf\"\n  by standard (auto simp add: inf_left_commute)\n\nlemma (in semilattice_sup) comp_fun_idem_sup: \"comp_fun_idem sup\"\n  by standard (auto simp add: sup_left_commute)\n\nlemma union_fold_insert:\n  assumes \"finite A\"\n  shows \"A \\<union> B = fold insert B A\"\nproof -\n  interpret comp_fun_idem insert\n    by (fact comp_fun_idem_insert)\n  from \\<open>finite A\\<close> show ?thesis\n    by (induct A arbitrary: B) simp_all\nqed\n\nlemma minus_fold_remove:\n  assumes \"finite A\"\n  shows \"B - A = fold Set.remove B A\"\nproof -\n  interpret comp_fun_idem Set.remove\n    by (fact comp_fun_idem_remove)\n  from \\<open>finite A\\<close> have \"fold Set.remove B A = B - A\"\n    by (induct A arbitrary: B) auto  (* slow *)\n  then show ?thesis ..\nqed\n\nlemma comp_fun_commute_filter_fold:\n  \"comp_fun_commute (\\<lambda>x A'. if P x then Set.insert x A' else A')\"\nproof -\n  interpret comp_fun_idem Set.insert by (fact comp_fun_idem_insert)\n  show ?thesis by standard (auto simp: fun_eq_iff)\nqed\n\nlemma Set_filter_fold:\n  assumes \"finite A\"\n  shows \"Set.filter P A = fold (\\<lambda>x A'. if P x then Set.insert x A' else A') {} A\"\n  using assms\nproof -\n  interpret commute_insert: comp_fun_commute \"(\\<lambda>x A'. if P x then Set.insert x A' else A')\"\n    by (fact comp_fun_commute_filter_fold)\n  from \\<open>finite A\\<close> show ?thesis\n    by induct (auto simp add: Set.filter_def)\nqed\n\nlemma inter_Set_filter:\n  assumes \"finite B\"\n  shows \"A \\<inter> B = Set.filter (\\<lambda>x. x \\<in> A) B\"\n  using assms\n  by induct (auto simp: Set.filter_def)\n\nlemma image_fold_insert:\n  assumes \"finite A\"\n  shows \"image f A = fold (\\<lambda>k A. Set.insert (f k) A) {} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k A. Set.insert (f k) A\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma Ball_fold:\n  assumes \"finite A\"\n  shows \"Ball A P = fold (\\<lambda>k s. s \\<and> P k) True A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<and> P k\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma Bex_fold:\n  assumes \"finite A\"\n  shows \"Bex A P = fold (\\<lambda>k s. s \\<or> P k) False A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<or> P k\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma comp_fun_commute_Pow_fold: \"comp_fun_commute (\\<lambda>x A. A \\<union> Set.insert x ` A)\"\n  by (clarsimp simp: fun_eq_iff comp_fun_commute_def) blast\n\nlemma Pow_fold:\n  assumes \"finite A\"\n  shows \"Pow A = fold (\\<lambda>x A. A \\<union> Set.insert x ` A) {{}} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>x A. A \\<union> Set.insert x ` A\"\n    by (rule comp_fun_commute_Pow_fold)\n  show ?thesis\n    using assms by (induct A) (auto simp: Pow_insert)\nqed\n\nlemma fold_union_pair:\n  assumes \"finite B\"\n  shows \"(\\<Union>y\\<in>B. {(x, y)}) \\<union> A = fold (\\<lambda>y. Set.insert (x, y)) A B\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>y. Set.insert (x, y)\"\n    by standard auto\n  show ?thesis\n    using assms by (induct arbitrary: A) simp_all\nqed\n\nlemma comp_fun_commute_product_fold:\n  \"finite B \\<Longrightarrow> comp_fun_commute (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B)\"\n  by standard (auto simp: fold_union_pair [symmetric])\n\nlemma product_fold:\n  assumes \"finite A\" \"finite B\"\n  shows \"A \\<times> B = fold (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B) {} A\"\nproof -\n  interpret commute_product: comp_fun_commute \"(\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B)\"\n    by (fact comp_fun_commute_product_fold[OF \\<open>finite B\\<close>])\n  from assms show ?thesis unfolding Sigma_def\n    by (induct A) (simp_all add: fold_union_pair)\nqed\n\ncontext complete_lattice\nbegin\n\nlemma inf_Inf_fold_inf:\n  assumes \"finite A\"\n  shows \"inf (Inf A) B = fold inf B A\"\nproof -\n  interpret comp_fun_idem inf\n    by (fact comp_fun_idem_inf)\n  from \\<open>finite A\\<close> fold_fun_left_comm show ?thesis\n    by (induct A arbitrary: B) (simp_all add: inf_commute fun_eq_iff)\nqed\n\nlemma sup_Sup_fold_sup:\n  assumes \"finite A\"\n  shows \"sup (Sup A) B = fold sup B A\"\nproof -\n  interpret comp_fun_idem sup\n    by (fact comp_fun_idem_sup)\n  from \\<open>finite A\\<close> fold_fun_left_comm show ?thesis\n    by (induct A arbitrary: B) (simp_all add: sup_commute fun_eq_iff)\nqed\n\nlemma Inf_fold_inf: \"finite A \\<Longrightarrow> Inf A = fold inf top A\"\n  using inf_Inf_fold_inf [of A top] by (simp add: inf_absorb2)\n\nlemma Sup_fold_sup: \"finite A \\<Longrightarrow> Sup A = fold sup bot A\"\n  using sup_Sup_fold_sup [of A bot] by (simp add: sup_absorb2)\n\nlemma inf_INF_fold_inf:\n  assumes \"finite A\"\n  shows \"inf B (\\<Sqinter>(f ` A)) = fold (inf \\<circ> f) B A\" (is \"?inf = ?fold\")\nproof -\n  interpret comp_fun_idem inf by (fact comp_fun_idem_inf)\n  interpret comp_fun_idem \"inf \\<circ> f\" by (fact comp_comp_fun_idem)\n  from \\<open>finite A\\<close> have \"?fold = ?inf\"\n    by (induct A arbitrary: B) (simp_all add: inf_left_commute)\n  then show ?thesis ..\nqed\n\nlemma sup_SUP_fold_sup:\n  assumes \"finite A\"\n  shows \"sup B (\\<Squnion>(f ` A)) = fold (sup \\<circ> f) B A\" (is \"?sup = ?fold\")\nproof -\n  interpret comp_fun_idem sup by (fact comp_fun_idem_sup)\n  interpret comp_fun_idem \"sup \\<circ> f\" by (fact comp_comp_fun_idem)\n  from \\<open>finite A\\<close> have \"?fold = ?sup\"\n    by (induct A arbitrary: B) (simp_all add: sup_left_commute)\n  then show ?thesis ..\nqed\n\nlemma INF_fold_inf: \"finite A \\<Longrightarrow> \\<Sqinter>(f ` A) = fold (inf \\<circ> f) top A\"\n  using inf_INF_fold_inf [of A top] by simp\n\nlemma SUP_fold_sup: \"finite A \\<Longrightarrow> \\<Squnion>(f ` A) = fold (sup \\<circ> f) bot A\"\n  using sup_SUP_fold_sup [of A bot] by simp\n\nlemma finite_Inf_in:\n  assumes \"finite A\" \"A\\<noteq>{}\" and inf: \"\\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> inf x y \\<in> A\"\n  shows \"Inf A \\<in> A\"\nproof -\n  have \"Inf B \\<in> A\" if \"B \\<le> A\" \"B\\<noteq>{}\" for B\n    using finite_subset [OF \\<open>B \\<subseteq> A\\<close> \\<open>finite A\\<close>] that\n  by (induction B) (use inf in \\<open>force+\\<close>)\n  then show ?thesis\n    by (simp add: assms)\nqed\n\nlemma finite_Sup_in:\n  assumes \"finite A\" \"A\\<noteq>{}\" and sup: \"\\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> sup x y \\<in> A\"\n  shows \"Sup A \\<in> A\"\nproof -\n  have \"Sup B \\<in> A\" if \"B \\<le> A\" \"B\\<noteq>{}\" for B\n    using finite_subset [OF \\<open>B \\<subseteq> A\\<close> \\<open>finite A\\<close>] that\n  by (induction B) (use sup in \\<open>force+\\<close>)\n  then show ?thesis\n    by (simp add: assms)\nqed\n\nend\n\nsubsubsection \\<open>Expressing relation operations via \\<^const>\\<open>fold\\<close>\\<close>\n\nlemma Id_on_fold:\n  assumes \"finite A\"\n  shows \"Id_on A = Finite_Set.fold (\\<lambda>x. Set.insert (Pair x x)) {} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>x. Set.insert (Pair x x)\"\n    by standard auto\n  from assms show ?thesis\n    unfolding Id_on_def by (induct A) simp_all\nqed\n\nlemma comp_fun_commute_Image_fold:\n  \"comp_fun_commute (\\<lambda>(x,y) A. if x \\<in> S then Set.insert y A else A)\"\nproof -\n  interpret comp_fun_idem Set.insert\n    by (fact comp_fun_idem_insert)\n  show ?thesis\n    by standard (auto simp: fun_eq_iff comp_fun_commute split: prod.split)\nqed\n\nlemma Image_fold:\n  assumes \"finite R\"\n  shows \"R `` S = Finite_Set.fold (\\<lambda>(x,y) A. if x \\<in> S then Set.insert y A else A) {} R\"\nproof -\n  interpret comp_fun_commute \"(\\<lambda>(x,y) A. if x \\<in> S then Set.insert y A else A)\"\n    by (rule comp_fun_commute_Image_fold)\n  have *: \"\\<And>x F. Set.insert x F `` S = (if fst x \\<in> S then Set.insert (snd x) (F `` S) else (F `` S))\"\n    by (force intro: rev_ImageI)\n  show ?thesis\n    using assms by (induct R) (auto simp: * )\nqed\n\nlemma insert_relcomp_union_fold:\n  assumes \"finite S\"\n  shows \"{x} O S \\<union> X = Finite_Set.fold (\\<lambda>(w,z) A'. if snd x = w then Set.insert (fst x,z) A' else A') X S\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>(w,z) A'. if snd x = w then Set.insert (fst x,z) A' else A'\"\n  proof -\n    interpret comp_fun_idem Set.insert\n      by (fact comp_fun_idem_insert)\n    show \"comp_fun_commute (\\<lambda>(w,z) A'. if snd x = w then Set.insert (fst x,z) A' else A')\"\n      by standard (auto simp add: fun_eq_iff split: prod.split)\n  qed\n  have *: \"{x} O S = {(x', z). x' = fst x \\<and> (snd x, z) \\<in> S}\"\n    by (auto simp: relcomp_unfold intro!: exI)\n  show ?thesis\n    unfolding * using \\<open>finite S\\<close> by (induct S) (auto split: prod.split)\nqed\n\nlemma insert_relcomp_fold:\n  assumes \"finite S\"\n  shows \"Set.insert x R O S =\n    Finite_Set.fold (\\<lambda>(w,z) A'. if snd x = w then Set.insert (fst x,z) A' else A') (R O S) S\"\nproof -\n  have \"Set.insert x R O S = ({x} O S) \\<union> (R O S)\"\n    by auto\n  then show ?thesis\n    by (auto simp: insert_relcomp_union_fold [OF assms])\nqed\n\nlemma comp_fun_commute_relcomp_fold:\n  assumes \"finite S\"\n  shows \"comp_fun_commute (\\<lambda>(x,y) A.\n    Finite_Set.fold (\\<lambda>(w,z) A'. if y = w then Set.insert (x,z) A' else A') A S)\"\nproof -\n  have *: \"\\<And>a b A.\n    Finite_Set.fold (\\<lambda>(w, z) A'. if b = w then Set.insert (a, z) A' else A') A S = {(a,b)} O S \\<union> A\"\n    by (auto simp: insert_relcomp_union_fold[OF assms] cong: if_cong)\n  show ?thesis\n    by standard (auto simp: * )\nqed\n\nlemma relcomp_fold:\n  assumes \"finite R\" \"finite S\"\n  shows \"R O S = Finite_Set.fold\n    (\\<lambda>(x,y) A. Finite_Set.fold (\\<lambda>(w,z) A'. if y = w then Set.insert (x,z) A' else A') A S) {} R\"\nproof -\n  interpret commute_relcomp_fold: comp_fun_commute\n    \"(\\<lambda>(x, y) A. Finite_Set.fold (\\<lambda>(w, z) A'. if y = w then insert (x, z) A' else A') A S)\"\n    by (fact comp_fun_commute_relcomp_fold[OF \\<open>finite S\\<close>])\n  from assms show ?thesis\n    by (induct R) (auto simp: comp_fun_commute_relcomp_fold insert_relcomp_fold cong: if_cong)\nqed\n\n\nsubsection \\<open>Locales as mini-packages for fold operations\\<close>\n\nsubsubsection \\<open>The natural case\\<close>\n\nlocale folding_on =\n  fixes S :: \"'a set\"\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: \"'b\"\n  assumes comp_fun_commute_on: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y o f x = f x o f y\"\nbegin\n\ninterpretation fold?: comp_fun_commute_on S f\n  by standard (simp add: comp_fun_commute_on)\n\ndefinition F :: \"'a set \\<Rightarrow> 'b\"\n  where eq_fold: \"F A = Finite_Set.fold f z A\"\n\nlemma empty [simp]: \"F {} = z\"\n  by (simp add: eq_fold)\n\nlemma infinite [simp]: \"\\<not> finite A \\<Longrightarrow> F A = z\"\n  by (simp add: eq_fold)\n\nlemma insert [simp]:\n  assumes \"insert x A \\<subseteq> S\" and \"finite A\" and \"x \\<notin> A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert assms\n  have \"Finite_Set.fold f z (insert x A) \n      = f x (Finite_Set.fold f z A)\"\n    by simp\n  with \\<open>finite A\\<close> show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nlemma remove:\n  assumes \"A \\<subseteq> S\" and \"finite A\" and \"x \\<in> A\"\n  shows \"F A = f x (F (A - {x}))\"\nproof -\n  from \\<open>x \\<in> A\\<close> obtain B where A: \"A = insert x B\" and \"x \\<notin> B\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from \\<open>finite A\\<close> A have \"finite B\" by simp\n  ultimately show ?thesis\n    using \\<open>A \\<subseteq> S\\<close> by auto\nqed\n\nlemma insert_remove:\n  assumes \"insert x A \\<subseteq> S\" and \"finite A\"\n  shows \"F (insert x A) = f x (F (A - {x}))\"\n  using assms by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nend\n\n\nsubsubsection \\<open>With idempotency\\<close>\n\nlocale folding_idem_on = folding_on +\n  assumes comp_fun_idem_on: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f x \\<circ> f x = f x\"\nbegin\n\ndeclare insert [simp del]\n\ninterpretation fold?: comp_fun_idem_on S f\n  by standard (simp_all add: comp_fun_commute_on comp_fun_idem_on)\n\nlemma insert_idem [simp]:\n  assumes \"insert x A \\<subseteq> S\" and \"finite A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert_idem assms\n  have \"fold f z (insert x A) = f x (fold f z A)\" by simp\n  with \\<open>finite A\\<close> show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nend\n\nsubsubsection \\<open>\\<^term>\\<open>UNIV\\<close> as the carrier set\\<close>\n\nlocale folding =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: \"'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma (in -) folding_def': \"folding f = folding_on UNIV f\"\n  unfolding folding_def folding_on_def by blast\n\ntext \\<open>\n  Again, we abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale folding_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"folding_on UNIV f\"\n    by standard (simp add: comp_fun_commute)\nqed simp_all\n\nend\n\nlocale folding_idem = folding +\n  assumes comp_fun_idem: \"f x \\<circ> f x = f x\"\nbegin\n\nlemma (in -) folding_idem_def': \"folding_idem f = folding_idem_on UNIV f\"\n  unfolding folding_idem_def folding_def' folding_idem_on_def\n  unfolding folding_idem_axioms_def folding_idem_on_axioms_def\n  by blast\n\ntext \\<open>\n  Again, we abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale folding_idem_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"folding_idem_on UNIV f\"\n    by standard (simp add: comp_fun_idem)\nqed simp_all\n\nend\n\n\nsubsection \\<open>Finite cardinality\\<close>\n\ntext \\<open>\n  The traditional definition\n  \\<^prop>\\<open>card A \\<equiv> LEAST n. \\<exists>f. A = {f i |i. i < n}\\<close>\n  is ugly to work with.\n  But now that we have \\<^const>\\<open>fold\\<close> things are easy:\n\\<close>\n\nglobal_interpretation card: folding \"\\<lambda>_. Suc\" 0\n  defines card = \"folding_on.F (\\<lambda>_. Suc) 0\"\n  by standard (rule refl)\n\nlemma card_insert_disjoint: \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> card (insert x A) = Suc (card A)\"\n  by (fact card.insert)\n\nlemma card_insert_if: \"finite A \\<Longrightarrow> card (insert x A) = (if x \\<in> A then card A else Suc (card A))\"\n  by auto (simp add: card.insert_remove card.remove)\n\nlemma card_ge_0_finite: \"card A > 0 \\<Longrightarrow> finite A\"\n  by (rule ccontr) simp\n\nlemma card_0_eq [simp]: \"finite A \\<Longrightarrow> card A = 0 \\<longleftrightarrow> A = {}\"\n  by (auto dest: mk_disjoint_insert)\n\nlemma finite_UNIV_card_ge_0: \"finite (UNIV :: 'a set) \\<Longrightarrow> card (UNIV :: 'a set) > 0\"\n  by (rule ccontr) simp\n\nlemma card_eq_0_iff: \"card A = 0 \\<longleftrightarrow> A = {} \\<or> \\<not> finite A\"\n  by auto\n\nlemma card_range_greater_zero: \"finite (range f) \\<Longrightarrow> card (range f) > 0\"\n  by (rule ccontr) (simp add: card_eq_0_iff)\n\nlemma card_gt_0_iff: \"0 < card A \\<longleftrightarrow> A \\<noteq> {} \\<and> finite A\"\n  by (simp add: neq0_conv [symmetric] card_eq_0_iff)\n\nlemma card_Suc_Diff1:\n  assumes \"finite A\" \"x \\<in> A\" shows \"Suc (card (A - {x})) = card A\"\nproof -\n  have \"Suc (card (A - {x})) = card (insert x (A - {x}))\"\n    using assms by (simp add: card.insert_remove)\n  also have \"... = card A\"\n    using assms by (simp add: card_insert_if)\n  finally show ?thesis .\nqed\n\nlemma card_insert_le_m1:\n  assumes \"n > 0\" \"card y \\<le> n - 1\" shows  \"card (insert x y) \\<le> n\"\n  using assms\n  by (cases \"finite y\") (auto simp: card_insert_if)\n\nlemma card_Diff_singleton:\n  assumes \"x \\<in> A\" shows \"card (A - {x}) = card A - 1\"\nproof (cases \"finite A\")\n  case True\n  with assms show ?thesis\n    by (simp add: card_Suc_Diff1 [symmetric])\nqed auto\n\nlemma card_Diff_singleton_if:\n  \"card (A - {x}) = (if x \\<in> A then card A - 1 else card A)\"\n  by (simp add: card_Diff_singleton)\n\nlemma card_Diff_insert[simp]:\n  assumes \"a \\<in> A\" and \"a \\<notin> B\"\n  shows \"card (A - insert a B) = card (A - B) - 1\"\nproof -\n  have \"A - insert a B = (A - B) - {a}\"\n    using assms by blast\n  then show ?thesis\n    using assms by (simp add: card_Diff_singleton)\nqed\n\nlemma card_insert_le: \"card A \\<le> card (insert x A)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis   by (simp add: card_insert_if)\nqed auto\n\nlemma card_Collect_less_nat[simp]: \"card {i::nat. i < n} = n\"\n  by (induct n) (simp_all add:less_Suc_eq Collect_disj_eq)\n\nlemma card_Collect_le_nat[simp]: \"card {i::nat. i \\<le> n} = Suc n\"\n  using card_Collect_less_nat[of \"Suc n\"] by (simp add: less_Suc_eq_le)\n\nlemma card_mono:\n  assumes \"finite B\" and \"A \\<subseteq> B\"\n  shows \"card A \\<le> card B\"\nproof -\n  from assms have \"finite A\"\n    by (auto intro: finite_subset)\n  then show ?thesis\n    using assms\n  proof (induct A arbitrary: B)\n    case empty\n    then show ?case by simp\n  next\n    case (insert x A)\n    then have \"x \\<in> B\"\n      by simp\n    from insert have \"A \\<subseteq> B - {x}\" and \"finite (B - {x})\"\n      by auto\n    with insert.hyps have \"card A \\<le> card (B - {x})\"\n      by auto\n    with \\<open>finite A\\<close> \\<open>x \\<notin> A\\<close> \\<open>finite B\\<close> \\<open>x \\<in> B\\<close> show ?case\n      by simp (simp only: card.remove)\n  qed\nqed\n\nlemma card_seteq: \n  assumes \"finite B\" and A: \"A \\<subseteq> B\" \"card B \\<le> card A\"\n  shows \"A = B\"\n  using assms\nproof (induction arbitrary: A rule: finite_induct)\n  case (insert b B)\n  then have A: \"finite A\" \"A - {b} \\<subseteq> B\" \n    by force+\n  then have \"card B \\<le> card (A - {b})\"\n    using insert by (auto simp add: card_Diff_singleton_if)\n  then have \"A - {b} = B\"\n    using A insert.IH by auto\n  then show ?case \n    using insert.hyps insert.prems by auto\nqed auto\n\nlemma psubset_card_mono: \"finite B \\<Longrightarrow> A < B \\<Longrightarrow> card A < card B\"\n  using card_seteq [of B A] by (auto simp add: psubset_eq)\n\nlemma card_Un_Int:\n  assumes \"finite A\" \"finite B\"\n  shows \"card A + card B = card (A \\<union> B) + card (A \\<inter> B)\"\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (auto simp add: insert_absorb Int_insert_left)\nqed\n\nlemma card_Un_disjoint: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> A \\<inter> B = {} \\<Longrightarrow> card (A \\<union> B) = card A + card B\"\n  using card_Un_Int [of A B] by simp\n\nlemma card_Un_disjnt: \"\\<lbrakk>finite A; finite B; disjnt A B\\<rbrakk> \\<Longrightarrow> card (A \\<union> B) = card A + card B\"\n  by (simp add: card_Un_disjoint disjnt_def)\n\nlemma card_Un_le: \"card (A \\<union> B) \\<le> card A + card B\"\nproof (cases \"finite A \\<and> finite B\")\n  case True\n  then show ?thesis\n    using le_iff_add card_Un_Int [of A B] by auto\nqed auto\n\nlemma card_Diff_subset:\n  assumes \"finite B\"\n    and \"B \\<subseteq> A\"\n  shows \"card (A - B) = card A - card B\"\n  using assms\nproof (cases \"finite A\")\n  case False\n  with assms show ?thesis\n    by simp\nnext\n  case True\n  with assms show ?thesis\n    by (induct B arbitrary: A) simp_all\nqed\n\nlemma card_Diff_subset_Int:\n  assumes \"finite (A \\<inter> B)\"\n  shows \"card (A - B) = card A - card (A \\<inter> B)\"\nproof -\n  have \"A - B = A - A \\<inter> B\" by auto\n  with assms show ?thesis\n    by (simp add: card_Diff_subset)\nqed\n\nlemma diff_card_le_card_Diff:\n  assumes \"finite B\"\n  shows \"card A - card B \\<le> card (A - B)\"\nproof -\n  have \"card A - card B \\<le> card A - card (A \\<inter> B)\"\n    using card_mono[OF assms Int_lower2, of A] by arith\n  also have \"\\<dots> = card (A - B)\"\n    using assms by (simp add: card_Diff_subset_Int)\n  finally show ?thesis .\nqed\n\nlemma card_le_sym_Diff:\n  assumes \"finite A\" \"finite B\" \"card A \\<le> card B\"\n  shows \"card(A - B) \\<le> card(B - A)\"\nproof -\n  have \"card(A - B) = card A - card (A \\<inter> B)\" using assms(1,2) by(simp add: card_Diff_subset_Int)\n  also have \"\\<dots> \\<le> card B - card (A \\<inter> B)\" using assms(3) by linarith\n  also have \"\\<dots> = card(B - A)\" using assms(1,2) by(simp add: card_Diff_subset_Int Int_commute)\n  finally show ?thesis .\nqed\n\nlemma card_less_sym_Diff:\n  assumes \"finite A\" \"finite B\" \"card A < card B\"\n  shows \"card(A - B) < card(B - A)\"\nproof -\n  have \"card(A - B) = card A - card (A \\<inter> B)\" using assms(1,2) by(simp add: card_Diff_subset_Int)\n  also have \"\\<dots> < card B - card (A \\<inter> B)\" using assms(1,3) by (simp add: card_mono diff_less_mono)\n  also have \"\\<dots> = card(B - A)\" using assms(1,2) by(simp add: card_Diff_subset_Int Int_commute)\n  finally show ?thesis .\nqed\n\nlemma card_Diff1_less_iff: \"card (A - {x}) < card A \\<longleftrightarrow> finite A \\<and> x \\<in> A\"\nproof (cases \"finite A \\<and> x \\<in> A\")\n  case True\n  then show ?thesis\n    by (auto simp: card_gt_0_iff intro: diff_less)\nqed auto\n\nlemma card_Diff1_less: \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> card (A - {x}) < card A\"\n  unfolding card_Diff1_less_iff by auto\n\nlemma card_Diff2_less:\n  assumes \"finite A\" \"x \\<in> A\" \"y \\<in> A\" shows \"card (A - {x} - {y}) < card A\"\nproof (cases \"x = y\")\n  case True\n  with assms show ?thesis\n    by (simp add: card_Diff1_less del: card_Diff_insert)\nnext\n  case False\n  then have \"card (A - {x} - {y}) < card (A - {x})\" \"card (A - {x}) < card A\"\n    using assms by (intro card_Diff1_less; simp)+\n  then show ?thesis\n    by (blast intro: less_trans)\nqed\n\nlemma card_Diff1_le: \"card (A - {x}) \\<le> card A\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis  \n    by (cases \"x \\<in> A\") (simp_all add: card_Diff1_less less_imp_le)\nqed auto\n\nlemma card_psubset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> card A < card B \\<Longrightarrow> A < B\"\n  by (erule psubsetI) blast\n\nlemma card_le_inj:\n  assumes fA: \"finite A\"\n    and fB: \"finite B\"\n    and c: \"card A \\<le> card B\"\n  shows \"\\<exists>f. f ` A \\<subseteq> B \\<and> inj_on f A\"\n  using fA fB c\nproof (induct arbitrary: B rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x s t)\n  then show ?case\n  proof (induct rule: finite_induct [OF insert.prems(1)])\n    case 1\n    then show ?case by simp\n  next\n    case (2 y t)\n    from \"2.prems\"(1,2,5) \"2.hyps\"(1,2) have cst: \"card s \\<le> card t\"\n      by simp\n    from \"2.prems\"(3) [OF \"2.hyps\"(1) cst]\n    obtain f where *: \"f ` s \\<subseteq> t\" \"inj_on f s\"\n      by blast\n    let ?g = \"(\\<lambda>a. if a = x then y else f a)\"\n    have \"?g ` insert x s \\<subseteq> insert y t \\<and> inj_on ?g (insert x s)\"\n      using * \"2.prems\"(2) \"2.hyps\"(2) unfolding inj_on_def by auto\n    then show ?case by (rule exI[where ?x=\"?g\"])\n  qed\nqed\n\nlemma card_subset_eq:\n  assumes fB: \"finite B\"\n    and AB: \"A \\<subseteq> B\"\n    and c: \"card A = card B\"\n  shows \"A = B\"\nproof -\n  from fB AB have fA: \"finite A\"\n    by (auto intro: finite_subset)\n  from fA fB have fBA: \"finite (B - A)\"\n    by auto\n  have e: \"A \\<inter> (B - A) = {}\"\n    by blast\n  have eq: \"A \\<union> (B - A) = B\"\n    using AB by blast\n  from card_Un_disjoint[OF fA fBA e, unfolded eq c] have \"card (B - A) = 0\"\n    by arith\n  then have \"B - A = {}\"\n    unfolding card_eq_0_iff using fA fB by simp\n  with AB show \"A = B\"\n    by blast\nqed\n\nlemma insert_partition:\n  \"x \\<notin> F \\<Longrightarrow> \\<forall>c1 \\<in> insert x F. \\<forall>c2 \\<in> insert x F. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {} \\<Longrightarrow> x \\<inter> \\<Union>F = {}\"\n  by auto\n\nlemma finite_psubset_induct [consumes 1, case_names psubset]:\n  assumes finite: \"finite A\"\n    and major: \"\\<And>A. finite A \\<Longrightarrow> (\\<And>B. B \\<subset> A \\<Longrightarrow> P B) \\<Longrightarrow> P A\"\n  shows \"P A\"\n  using finite\nproof (induct A taking: card rule: measure_induct_rule)\n  case (less A)\n  have fin: \"finite A\" by fact\n  have ih: \"card B < card A \\<Longrightarrow> finite B \\<Longrightarrow> P B\" for B by fact\n  have \"P B\" if \"B \\<subset> A\" for B\n  proof -\n    from that have \"card B < card A\"\n      using psubset_card_mono fin by blast\n    moreover\n    from that have \"B \\<subseteq> A\"\n      by auto\n    then have \"finite B\"\n      using fin finite_subset by blast\n    ultimately show ?thesis using ih by simp\n  qed\n  with fin show \"P A\" using major by blast\nqed\n\nlemma finite_induct_select [consumes 1, case_names empty select]:\n  assumes \"finite S\"\n    and \"P {}\"\n    and select: \"\\<And>T. T \\<subset> S \\<Longrightarrow> P T \\<Longrightarrow> \\<exists>s\\<in>S - T. P (insert s T)\"\n  shows \"P S\"\nproof -\n  have \"0 \\<le> card S\" by simp\n  then have \"\\<exists>T \\<subseteq> S. card T = card S \\<and> P T\"\n  proof (induct rule: dec_induct)\n    case base with \\<open>P {}\\<close>\n    show ?case\n      by (intro exI[of _ \"{}\"]) auto\n  next\n    case (step n)\n    then obtain T where T: \"T \\<subseteq> S\" \"card T = n\" \"P T\"\n      by auto\n    with \\<open>n < card S\\<close> have \"T \\<subset> S\" \"P T\"\n      by auto\n    with select[of T] obtain s where \"s \\<in> S\" \"s \\<notin> T\" \"P (insert s T)\"\n      by auto\n    with step(2) T \\<open>finite S\\<close> show ?case\n      by (intro exI[of _ \"insert s T\"]) (auto dest: finite_subset)\n  qed\n  with \\<open>finite S\\<close> show \"P S\"\n    by (auto dest: card_subset_eq)\nqed\n\nlemma remove_induct [case_names empty infinite remove]:\n  assumes empty: \"P ({} :: 'a set)\"\n    and infinite: \"\\<not> finite B \\<Longrightarrow> P B\"\n    and remove: \"\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A\"\n  shows \"P B\"\nproof (cases \"finite B\")\n  case False\n  then show ?thesis by (rule infinite)\nnext\n  case True\n  define A where \"A = B\"\n  with True have \"finite A\" \"A \\<subseteq> B\"\n    by simp_all\n  then show \"P A\"\n  proof (induct \"card A\" arbitrary: A)\n    case 0\n    then have \"A = {}\" by auto\n    with empty show ?case by simp\n  next\n    case (Suc n A)\n    from \\<open>A \\<subseteq> B\\<close> and \\<open>finite B\\<close> have \"finite A\"\n      by (rule finite_subset)\n    moreover from Suc.hyps have \"A \\<noteq> {}\" by auto\n    moreover note \\<open>A \\<subseteq> B\\<close>\n    moreover have \"P (A - {x})\" if x: \"x \\<in> A\" for x\n      using x Suc.prems \\<open>Suc n = card A\\<close> by (intro Suc) auto\n    ultimately show ?case by (rule remove)\n  qed\nqed\n\nlemma finite_remove_induct [consumes 1, case_names empty remove]:\n  fixes P :: \"'a set \\<Rightarrow> bool\"\n  assumes \"finite B\"\n    and \"P {}\"\n    and \"\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A\"\n  defines \"B' \\<equiv> B\"\n  shows \"P B'\"\n  by (induct B' rule: remove_induct) (simp_all add: assms)\n\n\ntext \\<open>Main cardinality theorem.\\<close>\nlemma card_partition [rule_format]:\n  \"finite C \\<Longrightarrow> finite (\\<Union>C) \\<Longrightarrow> (\\<forall>c\\<in>C. card c = k) \\<Longrightarrow>\n    (\\<forall>c1 \\<in> C. \\<forall>c2 \\<in> C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}) \\<Longrightarrow>\n    k * card C = card (\\<Union>C)\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case\n    by (simp add: card_Un_disjoint insert_partition finite_subset [of _ \"\\<Union>(insert _ _)\"])\nqed\n\nlemma card_eq_UNIV_imp_eq_UNIV:\n  assumes fin: \"finite (UNIV :: 'a set)\"\n    and card: \"card A = card (UNIV :: 'a set)\"\n  shows \"A = (UNIV :: 'a set)\"\nproof\n  show \"A \\<subseteq> UNIV\" by simp\n  show \"UNIV \\<subseteq> A\"\n  proof\n    show \"x \\<in> A\" for x\n    proof (rule ccontr)\n      assume \"x \\<notin> A\"\n      then have \"A \\<subset> UNIV\" by auto\n      with fin have \"card A < card (UNIV :: 'a set)\"\n        by (fact psubset_card_mono)\n      with card show False by simp\n    qed\n  qed\nqed\n\ntext \\<open>The form of a finite set of given cardinality\\<close>\n\nlemma card_eq_SucD:\n  assumes \"card A = Suc k\"\n  shows \"\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> (k = 0 \\<longrightarrow> B = {})\"\nproof -\n  have fin: \"finite A\"\n    using assms by (auto intro: ccontr)\n  moreover have \"card A \\<noteq> 0\"\n    using assms by auto\n  ultimately obtain b where b: \"b \\<in> A\"\n    by auto\n  show ?thesis\n  proof (intro exI conjI)\n    show \"A = insert b (A - {b})\"\n      using b by blast\n    show \"b \\<notin> A - {b}\"\n      by blast\n    show \"card (A - {b}) = k\" and \"k = 0 \\<longrightarrow> A - {b} = {}\"\n      using assms b fin by (fastforce dest: mk_disjoint_insert)+\n  qed\nqed\n\nlemma card_Suc_eq:\n  \"card A = Suc k \\<longleftrightarrow>\n    (\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> (k = 0 \\<longrightarrow> B = {}))\"\n  by (auto simp: card_insert_if card_gt_0_iff elim!: card_eq_SucD)\n\nlemma card_Suc_eq_finite:\n  \"card A = Suc k \\<longleftrightarrow> (\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> finite B)\"\n  unfolding card_Suc_eq using card_gt_0_iff by fastforce\n\nlemma card_1_singletonE:\n  assumes \"card A = 1\"\n  obtains x where \"A = {x}\"\n  using assms by (auto simp: card_Suc_eq)\n\nlemma is_singleton_altdef: \"is_singleton A \\<longleftrightarrow> card A = 1\"\n  unfolding is_singleton_def\n  by (auto elim!: card_1_singletonE is_singletonE simp del: One_nat_def)\n\nlemma card_1_singleton_iff: \"card A = Suc 0 \\<longleftrightarrow> (\\<exists>x. A = {x})\"\n  by (simp add: card_Suc_eq)\n\nlemma card_le_Suc0_iff_eq:\n  assumes \"finite A\"\n  shows \"card A \\<le> Suc 0 \\<longleftrightarrow> (\\<forall>a1 \\<in> A. \\<forall>a2 \\<in> A. a1 = a2)\" (is \"?C = ?A\")\nproof\n  assume ?C thus ?A using assms by (auto simp: le_Suc_eq dest: card_eq_SucD)\nnext\n  assume ?A\n  show ?C\n  proof cases\n    assume \"A = {}\" thus ?C using \\<open>?A\\<close> by simp\n  next\n    assume \"A \\<noteq> {}\"\n    then obtain a where \"A = {a}\" using \\<open>?A\\<close> by blast\n    thus ?C by simp\n  qed\nqed\n\nlemma card_le_Suc_iff:\n  \"Suc n \\<le> card A = (\\<exists>a B. A = insert a B \\<and> a \\<notin> B \\<and> n \\<le> card B \\<and> finite B)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    by (fastforce simp: card_Suc_eq less_eq_nat.simps split: nat.splits)\nqed auto\n\nlemma finite_fun_UNIVD2:\n  assumes fin: \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  shows \"finite (UNIV :: 'b set)\"\nproof -\n  from fin have \"finite (range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary))\" for arbitrary\n    by (rule finite_imageI)\n  moreover have \"UNIV = range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary)\" for arbitrary\n    by (rule UNIV_eq_I) auto\n  ultimately show \"finite (UNIV :: 'b set)\"\n    by simp\nqed\n\nlemma card_UNIV_unit [simp]: \"card (UNIV :: unit set) = 1\"\n  unfolding UNIV_unit by simp\n\nlemma infinite_arbitrarily_large:\n  assumes \"\\<not> finite A\"\n  shows \"\\<exists>B. finite B \\<and> card B = n \\<and> B \\<subseteq> A\"\nproof (induction n)\n  case 0\n  show ?case by (intro exI[of _ \"{}\"]) auto\nnext\n  case (Suc n)\n  then obtain B where B: \"finite B \\<and> card B = n \\<and> B \\<subseteq> A\" ..\n  with \\<open>\\<not> finite A\\<close> have \"A \\<noteq> B\" by auto\n  with B have \"B \\<subset> A\" by auto\n  then have \"\\<exists>x. x \\<in> A - B\"\n    by (elim psubset_imp_ex_mem)\n  then obtain x where x: \"x \\<in> A - B\" ..\n  with B have \"finite (insert x B) \\<and> card (insert x B) = Suc n \\<and> insert x B \\<subseteq> A\"\n    by auto\n  then show \"\\<exists>B. finite B \\<and> card B = Suc n \\<and> B \\<subseteq> A\" ..\nqed\n\ntext \\<open>Sometimes, to prove that a set is finite, it is convenient to work with finite subsets\nand to show that their cardinalities are uniformly bounded. This possibility is formalized in\nthe next criterion.\\<close>\n\nlemma finite_if_finite_subsets_card_bdd:\n  assumes \"\\<And>G. G \\<subseteq> F \\<Longrightarrow> finite G \\<Longrightarrow> card G \\<le> C\"\n  shows \"finite F \\<and> card F \\<le> C\"\nproof (cases \"finite F\")\n  case False\n  obtain n::nat where n: \"n > max C 0\" by auto\n  obtain G where G: \"G \\<subseteq> F\" \"card G = n\" using infinite_arbitrarily_large[OF False] by auto\n  hence \"finite G\" using \\<open>n > max C 0\\<close> using card.infinite gr_implies_not0 by blast\n  hence False using assms G n not_less by auto\n  thus ?thesis ..\nnext\n  case True thus ?thesis using assms[of F] by auto\nqed\n\nlemma obtain_subset_with_card_n:\n  assumes \"n \\<le> card S\"\n  obtains T where \"T \\<subseteq> S\" \"card T = n\" \"finite T\"\nproof -\n  obtain n' where \"card S = n + n'\"\n    using le_Suc_ex[OF assms] by blast\n  with that show thesis\n  proof (induct n' arbitrary: S)\n    case 0 \n    thus ?case by (cases \"finite S\") auto\n  next\n    case Suc \n    thus ?case by (auto simp add: card_Suc_eq)\n  qed\nqed\n\nlemma exists_subset_between: \n  assumes \n    \"card A \\<le> n\" \n    \"n \\<le> card C\"\n    \"A \\<subseteq> C\"\n    \"finite C\"\n  shows \"\\<exists>B. A \\<subseteq> B \\<and> B \\<subseteq> C \\<and> card B = n\" \n  using assms \nproof (induct n arbitrary: A C)\n  case 0\n  thus ?case using finite_subset[of A C] by (intro exI[of _ \"{}\"], auto)\nnext\n  case (Suc n A C)\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    from obtain_subset_with_card_n[OF Suc(3)]\n    obtain B where \"B \\<subseteq> C\" \"card B = Suc n\" by blast\n    thus ?thesis unfolding True by blast\n  next\n    case False\n    then obtain a where a: \"a \\<in> A\" by auto\n    let ?A = \"A - {a}\" \n    let ?C = \"C - {a}\" \n    have 1: \"card ?A \\<le> n\" using Suc(2-) a \n      using finite_subset by fastforce \n    have 2: \"card ?C \\<ge> n\" using Suc(2-) a by auto\n    from Suc(1)[OF 1 2 _ finite_subset[OF _ Suc(5)]] Suc(2-)\n    obtain B where \"?A \\<subseteq> B\" \"B \\<subseteq> ?C\" \"card B = n\" by blast\n    thus ?thesis using a Suc(2-) \n      by (intro exI[of _ \"insert a B\"], auto intro!: card_insert_disjoint finite_subset[of B C])\n  qed\nqed\n\n\nsubsubsection \\<open>Cardinality of image\\<close>\n\nlemma card_image_le: \"finite A \\<Longrightarrow> card (f ` A) \\<le> card A\"\n  by (induct rule: finite_induct) (simp_all add: le_SucI card_insert_if)\n\nlemma card_image: \"inj_on f A \\<Longrightarrow> card (f ` A) = card A\"\nproof (induct A rule: infinite_finite_induct)\n  case (infinite A)\n  then have \"\\<not> finite (f ` A)\" by (auto dest: finite_imageD)\n  with infinite show ?case by simp\nqed simp_all\n\nlemma bij_betw_same_card: \"bij_betw f A B \\<Longrightarrow> card A = card B\"\n  by (auto simp: card_image bij_betw_def)\n\nlemma endo_inj_surj: \"finite A \\<Longrightarrow> f ` A \\<subseteq> A \\<Longrightarrow> inj_on f A \\<Longrightarrow> f ` A = A\"\n  by (simp add: card_seteq card_image)\n\nlemma eq_card_imp_inj_on:\n  assumes \"finite A\" \"card(f ` A) = card A\"\n  shows \"inj_on f A\"\n  using assms\nproof (induct rule:finite_induct)\n  case empty\n  show ?case by simp\nnext\n  case (insert x A)\n  then show ?case\n    using card_image_le [of A f] by (simp add: card_insert_if split: if_splits)\nqed\n\nlemma inj_on_iff_eq_card: \"finite A \\<Longrightarrow> inj_on f A \\<longleftrightarrow> card (f ` A) = card A\"\n  by (blast intro: card_image eq_card_imp_inj_on)\n\nlemma card_inj_on_le:\n  assumes \"inj_on f A\" \"f ` A \\<subseteq> B\" \"finite B\"\n  shows \"card A \\<le> card B\"\nproof -\n  have \"finite A\"\n    using assms by (blast intro: finite_imageD dest: finite_subset)\n  then show ?thesis\n    using assms by (force intro: card_mono simp: card_image [symmetric])\nqed\n\nlemma inj_on_iff_card_le:\n  \"\\<lbrakk> finite A; finite B \\<rbrakk> \\<Longrightarrow> (\\<exists>f. inj_on f A \\<and> f ` A \\<le> B) = (card A \\<le> card B)\"\nusing card_inj_on_le[of _ A B] card_le_inj[of A B] by blast\n\nlemma surj_card_le: \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> card B \\<le> card A\"\n  by (blast intro: card_image_le card_mono le_trans)\n\nlemma card_bij_eq:\n  \"inj_on f A \\<Longrightarrow> f ` A \\<subseteq> B \\<Longrightarrow> inj_on g B \\<Longrightarrow> g ` B \\<subseteq> A \\<Longrightarrow> finite A \\<Longrightarrow> finite B\n    \\<Longrightarrow> card A = card B\"\n  by (auto intro: le_antisym card_inj_on_le)\n\nlemma bij_betw_finite: \"bij_betw f A B \\<Longrightarrow> finite A \\<longleftrightarrow> finite B\"\n  unfolding bij_betw_def using finite_imageD [of f A] by auto\n\nlemma inj_on_finite: \"inj_on f A \\<Longrightarrow> f ` A \\<le> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  using finite_imageD finite_subset by blast\n\nlemma card_vimage_inj_on_le:\n  assumes \"inj_on f D\" \"finite A\"\n  shows \"card (f-`A \\<inter> D) \\<le> card A\"\nproof (rule card_inj_on_le)\n  show \"inj_on f (f -` A \\<inter> D)\"\n    by (blast intro: assms inj_on_subset)\nqed (use assms in auto)\n\nlemma card_vimage_inj: \"inj f \\<Longrightarrow> A \\<subseteq> range f \\<Longrightarrow> card (f -` A) = card A\"\n  by (auto 4 3 simp: subset_image_iff inj_vimage_image_eq\n      intro: card_image[symmetric, OF subset_inj_on])\n\nlemma card_inverse[simp]: \"card (R\\<inverse>) = card R\"\nproof -\n  have *: \"\\<And>R. prod.swap ` R = R\\<inverse>\" by auto\n  {\n    assume \"\\<not>finite R\"\n    hence ?thesis\n      by auto\n  } moreover {\n    assume \"finite R\"\n    with card_image_le[of R prod.swap] card_image_le[of \"R\\<inverse>\" prod.swap]\n    have ?thesis by (auto simp: * )\n  } ultimately show ?thesis by blast\nqed\n\nsubsubsection \\<open>Pigeonhole Principles\\<close>\n\nlemma pigeonhole: \"card A > card (f ` A) \\<Longrightarrow> \\<not> inj_on f A \"\n  by (auto dest: card_image less_irrefl_nat)\n\nlemma pigeonhole_infinite:\n  assumes \"\\<not> finite A\" and \"finite (f`A)\"\n  shows \"\\<exists>a0\\<in>A. \\<not> finite {a\\<in>A. f a = f a0}\"\n  using assms(2,1)\nproof (induct \"f`A\" arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert b F)\n  show ?case\n  proof (cases \"finite {a\\<in>A. f a = b}\")\n    case True\n    with \\<open>\\<not> finite A\\<close> have \"\\<not> finite (A - {a\\<in>A. f a = b})\"\n      by simp\n    also have \"A - {a\\<in>A. f a = b} = {a\\<in>A. f a \\<noteq> b}\"\n      by blast\n    finally have \"\\<not> finite {a\\<in>A. f a \\<noteq> b}\" .\n    from insert(3)[OF _ this] insert(2,4) show ?thesis\n      by simp (blast intro: rev_finite_subset)\n  next\n    case False\n    then have \"{a \\<in> A. f a = b} \\<noteq> {}\" by force\n    with False show ?thesis by blast\n  qed\nqed\n\nlemma pigeonhole_infinite_rel:\n  assumes \"\\<not> finite A\"\n    and \"finite B\"\n    and \"\\<forall>a\\<in>A. \\<exists>b\\<in>B. R a b\"\n  shows \"\\<exists>b\\<in>B. \\<not> finite {a:A. R a b}\"\nproof -\n  let ?F = \"\\<lambda>a. {b\\<in>B. R a b}\"\n  from finite_Pow_iff[THEN iffD2, OF \\<open>finite B\\<close>] have \"finite (?F ` A)\"\n    by (blast intro: rev_finite_subset)\n  from pigeonhole_infinite [where f = ?F, OF assms(1) this]\n  obtain a0 where \"a0 \\<in> A\" and infinite: \"\\<not> finite {a\\<in>A. ?F a = ?F a0}\" ..\n  obtain b0 where \"b0 \\<in> B\" and \"R a0 b0\"\n    using \\<open>a0 \\<in> A\\<close> assms(3) by blast\n  have \"finite {a\\<in>A. ?F a = ?F a0}\" if \"finite {a\\<in>A. R a b0}\"\n    using \\<open>b0 \\<in> B\\<close> \\<open>R a0 b0\\<close> that by (blast intro: rev_finite_subset)\n  with infinite \\<open>b0 \\<in> B\\<close> show ?thesis\n    by blast\nqed\n\n\nsubsubsection \\<open>Cardinality of sums\\<close>\n\nlemma card_Plus:\n  assumes \"finite A\" \"finite B\"\n  shows \"card (A <+> B) = card A + card B\"\nproof -\n  have \"Inl`A \\<inter> Inr`B = {}\" by fast\n  with assms show ?thesis\n    by (simp add: Plus_def card_Un_disjoint card_image)\nqed\n\nlemma card_Plus_conv_if:\n  \"card (A <+> B) = (if finite A \\<and> finite B then card A + card B else 0)\"\n  by (auto simp add: card_Plus)\n\ntext \\<open>Relates to equivalence classes.  Based on a theorem of F. Kammüller.\\<close>\n\nlemma dvd_partition:\n  assumes f: \"finite (\\<Union>C)\"\n    and \"\\<forall>c\\<in>C. k dvd card c\" \"\\<forall>c1\\<in>C. \\<forall>c2\\<in>C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}\"\n  shows \"k dvd card (\\<Union>C)\"\nproof -\n  have \"finite C\"\n    by (rule finite_UnionD [OF f])\n  then show ?thesis\n    using assms\n  proof (induct rule: finite_induct)\n    case empty\n    show ?case by simp\n  next\n    case (insert c C)\n    then have \"c \\<inter> \\<Union>C = {}\"\n      by auto\n    with insert show ?case\n      by (simp add: card_Un_disjoint)\n  qed\nqed\n\n\nsubsection \\<open>Minimal and maximal elements of finite sets\\<close>\n\ncontext begin\n\nqualified lemma\n  assumes \"finite A\" and \"A \\<noteq> {}\" and \"transp_on A R\" and \"asymp_on A R\"\n  shows\n    bex_min_element: \"\\<exists>m \\<in> A. \\<forall>x \\<in> A. x \\<noteq> m \\<longrightarrow> \\<not> R x m\" and\n    bex_max_element: \"\\<exists>m \\<in> A. \\<forall>x \\<in> A. x \\<noteq> m \\<longrightarrow> \\<not> R m x\"\n  unfolding atomize_conj\n  using assms\nproof (induction A rule: finite_induct)\n  case empty\n  hence False\n    by simp\n  thus ?case ..\nnext\n  case (insert a A')\n  show ?case\n  proof (cases \"A' = {}\")\n    case True\n    show ?thesis\n    proof (intro conjI bexI)\n      show \"\\<forall>x\\<in>insert a A'. x \\<noteq> a \\<longrightarrow> \\<not> R x a\" and \"\\<forall>x\\<in>insert a A'. x \\<noteq> a \\<longrightarrow> \\<not> R a x\"\n        using True by blast+\n    qed simp_all\n  next\n    case False\n    moreover have \"transp_on A' R\"\n      using insert.prems transp_on_subset by blast\n    moreover have \"asymp_on A' R\"\n      using insert.prems asymp_on_subset by blast\n    ultimately obtain min max where\n      \"min \\<in> A'\" and \"max \\<in> A'\" and\n      min_is_min: \"\\<forall>x\\<in>A'. x \\<noteq> min \\<longrightarrow> \\<not> R x min\" and\n      max_is_max: \"\\<forall>x\\<in>A'. x \\<noteq> max \\<longrightarrow> \\<not> R max x\"\n      using insert.IH by auto\n\n    show ?thesis\n    proof (rule conjI)\n      show \"\\<exists>min\\<in>insert a A'. \\<forall>x\\<in>insert a A'. x \\<noteq> min \\<longrightarrow> \\<not> R x min\"\n      proof (cases \"R a min\")\n        case True\n        show ?thesis\n        proof (intro bexI ballI impI)\n          show \"a \\<in> insert a A'\"\n            by simp\n        next\n          fix x\n          show \"x \\<in> insert a A' \\<Longrightarrow> x \\<noteq> a \\<Longrightarrow> \\<not> R x a\"\n            using True \\<open>min \\<in> A'\\<close> min_is_min[rule_format, of x] insert.prems(2,3)\n            by (auto dest: asymp_onD transp_onD)\n        qed\n      next\n        case False\n        show ?thesis\n        proof (rule bexI)\n          show \"min \\<in> insert a A'\"\n            using \\<open>min \\<in> A'\\<close> by auto\n        next\n          show \"\\<forall>x\\<in>insert a A'. x \\<noteq> min \\<longrightarrow> \\<not> R x min\"\n            using False min_is_min by blast\n        qed\n      qed\n    next\n      show \"\\<exists>max\\<in>insert a A'. \\<forall>x\\<in>insert a A'. x \\<noteq> max \\<longrightarrow> \\<not> R max x\"\n      proof (cases \"R max a\")\n        case True\n        show ?thesis\n        proof (intro bexI ballI impI)\n          show \"a \\<in> insert a A'\"\n            by simp\n        next\n          fix x\n          show \"x \\<in> insert a A' \\<Longrightarrow> x \\<noteq> a \\<Longrightarrow> \\<not> R a x\"\n            using True \\<open>max \\<in> A'\\<close> max_is_max[rule_format, of x] insert.prems(2,3)\n            by (auto dest: asymp_onD transp_onD)\n        qed\n      next\n        case False\n        show ?thesis\n        proof (rule bexI)\n          show \"max \\<in> insert a A'\"\n            using \\<open>max \\<in> A'\\<close> by auto\n        next\n          show \"\\<forall>x\\<in>insert a A'. x \\<noteq> max \\<longrightarrow> \\<not> R max x\"\n            using False max_is_max by blast\n        qed\n      qed\n    qed\n  qed\nqed\n\nend\n\ntext \\<open>The following alternative form might sometimes be easier to work with.\\<close>\n\nlemma is_min_element_in_set_iff:\n  \"asymp_on A R \\<Longrightarrow> (\\<forall>y \\<in> A. y \\<noteq> x \\<longrightarrow> \\<not> R y x) \\<longleftrightarrow> (\\<forall>y. R y x \\<longrightarrow> y \\<notin> A)\"\n  by (auto dest: asymp_onD)\n\nlemma is_max_element_in_set_iff:\n  \"asymp_on A R \\<Longrightarrow> (\\<forall>y \\<in> A. y \\<noteq> x \\<longrightarrow> \\<not> R x y) \\<longleftrightarrow> (\\<forall>y. R x y \\<longrightarrow> y \\<notin> A)\"\n  by (auto dest: asymp_onD)\n\ncontext begin\n\nqualified lemma\n  assumes \"finite A\" and \"A \\<noteq> {}\" and \"transp_on A R\" and \"totalp_on A R\"\n  shows\n    bex_least_element: \"\\<exists>l \\<in> A. \\<forall>x \\<in> A. x \\<noteq> l \\<longrightarrow> R l x\" and\n    bex_greatest_element: \"\\<exists>g \\<in> A. \\<forall>x \\<in> A. x \\<noteq> g \\<longrightarrow> R x g\"\n  unfolding atomize_conj\n  using assms\nproof (induction A rule: finite_induct)\n  case empty\n  hence False by simp\n  thus ?case ..\nnext\n  case (insert a A')\n\n  from insert.prems(2) have transp_on_A': \"transp_on A' R\"\n    by (auto intro: transp_onI dest: transp_onD)\n\n  from insert.prems(3) have\n    totalp_on_a_A'_raw: \"\\<forall>y \\<in> A'. a \\<noteq> y \\<longrightarrow> R a y \\<or> R y a\" and\n    totalp_on_A': \"totalp_on A' R\"\n    by (simp_all add: totalp_on_def)\n\n  show ?case\n  proof (cases \"A' = {}\")\n    case True\n    thus ?thesis by simp\n  next\n    case False\n    then obtain least greatest where\n      \"least \\<in> A'\" and least_of_A': \"\\<forall>x\\<in>A'. x \\<noteq> least \\<longrightarrow> R least x\" and\n      \"greatest \\<in> A'\" and greatest_of_A': \"\\<forall>x\\<in>A'. x \\<noteq> greatest \\<longrightarrow> R x greatest\"\n      using insert.IH[OF _ transp_on_A' totalp_on_A'] by auto\n\n    show ?thesis\n    proof (rule conjI)\n      show \"\\<exists>l\\<in>insert a A'. \\<forall>x\\<in>insert a A'. x \\<noteq> l \\<longrightarrow> R l x\"\n      proof (cases \"R a least\")\n        case True\n        show ?thesis\n        proof (intro bexI ballI impI)\n          show \"a \\<in> insert a A'\"\n            by simp\n        next\n          fix x\n          show \"\\<And>x. x \\<in> insert a A' \\<Longrightarrow> x \\<noteq> a \\<Longrightarrow> R a x\"\n            using True \\<open>least \\<in> A'\\<close> least_of_A'\n            using insert.prems(2)[THEN transp_onD, of a least]\n            by auto\n        qed\n      next\n        case False\n        show ?thesis\n        proof (intro bexI ballI impI)\n          show \"least \\<in> insert a A'\"\n            using \\<open>least \\<in> A'\\<close> by simp\n        next\n          fix x\n          show \"x \\<in> insert a A' \\<Longrightarrow> x \\<noteq> least \\<Longrightarrow> R least x\"\n            using False \\<open>least \\<in> A'\\<close> least_of_A' totalp_on_a_A'_raw\n            by (cases \"x = a\") auto\n        qed\n      qed\n    next\n      show \"\\<exists>g \\<in> insert a A'. \\<forall>x \\<in> insert a A'. x \\<noteq> g \\<longrightarrow> R x g\"\n      proof (cases \"R greatest a\")\n        case True\n        show ?thesis\n        proof (intro bexI ballI impI)\n          show \"a \\<in> insert a A'\"\n            by simp\n        next\n          fix x\n          show \"\\<And>x. x \\<in> insert a A' \\<Longrightarrow> x \\<noteq> a \\<Longrightarrow> R x a\"\n            using True \\<open>greatest \\<in> A'\\<close> greatest_of_A'\n            using insert.prems(2)[THEN transp_onD, of _ greatest a]\n            by auto\n        qed\n      next\n        case False\n        show ?thesis\n        proof (intro bexI ballI impI)\n          show \"greatest \\<in> insert a A'\"\n            using \\<open>greatest \\<in> A'\\<close> by simp\n        next\n          fix x\n          show \"x \\<in> insert a A' \\<Longrightarrow> x \\<noteq> greatest \\<Longrightarrow> R x greatest\"\n            using False \\<open>greatest \\<in> A'\\<close> greatest_of_A' totalp_on_a_A'_raw\n            by (cases \"x = a\") auto\n        qed\n      qed\n    qed\n  qed\nqed\n\nend\n\nsubsubsection \\<open>Finite orders\\<close>\n\ncontext order\nbegin\n\nlemma finite_has_maximal:\n  assumes \"finite A\" and \"A \\<noteq> {}\"\n  shows \"\\<exists> m \\<in> A. \\<forall> b \\<in> A. m \\<le> b \\<longrightarrow> m = b\"\nproof -\n  obtain m where \"m \\<in> A\" and m_is_max: \"\\<forall>x\\<in>A. x \\<noteq> m \\<longrightarrow> \\<not> m < x\"\n    using Finite_Set.bex_max_element[OF \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>, of \"(<)\"] by auto\n  moreover have \"\\<forall>b \\<in> A. m \\<le> b \\<longrightarrow> m = b\"\n    using m_is_max by (auto simp: le_less)\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma finite_has_maximal2:\n  \"\\<lbrakk> finite A; a \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists> m \\<in> A. a \\<le> m \\<and> (\\<forall> b \\<in> A. m \\<le> b \\<longrightarrow> m = b)\"\nusing finite_has_maximal[of \"{b \\<in> A. a \\<le> b}\"] by fastforce\n\nlemma finite_has_minimal:\n  assumes \"finite A\" and \"A \\<noteq> {}\"\n  shows \"\\<exists> m \\<in> A. \\<forall> b \\<in> A. b \\<le> m \\<longrightarrow> m = b\"\nproof -\n  obtain m where \"m \\<in> A\" and m_is_min: \"\\<forall>x\\<in>A. x \\<noteq> m \\<longrightarrow> \\<not> x < m\"\n    using Finite_Set.bex_min_element[OF \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>, of \"(<)\"] by auto\n  moreover have \"\\<forall>b \\<in> A. b \\<le> m \\<longrightarrow> m = b\"\n    using m_is_min by (auto simp: le_less)\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma finite_has_minimal2:\n  \"\\<lbrakk> finite A; a \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists> m \\<in> A. m \\<le> a \\<and> (\\<forall> b \\<in> A. b \\<le> m \\<longrightarrow> m = b)\"\nusing finite_has_minimal[of \"{b \\<in> A. b \\<le> a}\"] by fastforce\n\nend\n\nsubsubsection \\<open>Relating injectivity and surjectivity\\<close>\n\nlemma finite_surj_inj:\n  assumes \"finite A\" \"A \\<subseteq> f ` A\"\n  shows \"inj_on f A\"\nproof -\n  have \"f ` A = A\"\n    by (rule card_seteq [THEN sym]) (auto simp add: assms card_image_le)\n  then show ?thesis using assms\n    by (simp add: eq_card_imp_inj_on)\nqed\n\nlemma finite_UNIV_surj_inj: \"finite(UNIV:: 'a set) \\<Longrightarrow> surj f \\<Longrightarrow> inj f\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  by (blast intro: finite_surj_inj subset_UNIV)\n\nlemma finite_UNIV_inj_surj: \"finite(UNIV:: 'a set) \\<Longrightarrow> inj f \\<Longrightarrow> surj f\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  by (fastforce simp:surj_def dest!: endo_inj_surj)\n\nlemma surjective_iff_injective_gen:\n  assumes fS: \"finite S\"\n    and fT: \"finite T\"\n    and c: \"card S = card T\"\n    and ST: \"f ` S \\<subseteq> T\"\n  shows \"(\\<forall>y \\<in> T. \\<exists>x \\<in> S. f x = y) \\<longleftrightarrow> inj_on f S\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume h: \"?lhs\"\n  {\n    fix x y\n    assume x: \"x \\<in> S\"\n    assume y: \"y \\<in> S\"\n    assume f: \"f x = f y\"\n    from x fS have S0: \"card S \\<noteq> 0\"\n      by auto\n    have \"x = y\"\n    proof (rule ccontr)\n      assume xy: \"\\<not> ?thesis\"\n      have th: \"card S \\<le> card (f ` (S - {y}))\"\n        unfolding c\n      proof (rule card_mono)\n        show \"finite (f ` (S - {y}))\"\n          by (simp add: fS)\n        have \"\\<lbrakk>x \\<noteq> y; x \\<in> S; z \\<in> S; f x = f y\\<rbrakk>\n         \\<Longrightarrow> \\<exists>x \\<in> S. x \\<noteq> y \\<and> f z = f x\" for z\n          by (cases \"z = y \\<longrightarrow> z = x\") auto\n        then show \"T \\<subseteq> f ` (S - {y})\"\n          using h xy x y f by fastforce\n      qed\n      also have \" \\<dots> \\<le> card (S - {y})\"\n        by (simp add: card_image_le fS)\n      also have \"\\<dots> \\<le> card S - 1\" using y fS by simp\n      finally show False using S0 by arith\n    qed\n  }\n  then show ?rhs\n    unfolding inj_on_def by blast\nnext\n  assume h: ?rhs\n  have \"f ` S = T\"\n    by (simp add: ST c card_image card_subset_eq fT h)\n  then show ?lhs by blast\nqed\n\nhide_const (open) Finite_Set.fold\n\n\nsubsection \\<open>Infinite Sets\\<close>\n\ntext \\<open>\n  Some elementary facts about infinite sets, mostly by Stephan Merz.\n  Beware! Because \"infinite\" merely abbreviates a negation, these\n  lemmas may not work well with \\<open>blast\\<close>.\n\\<close>\n\nabbreviation infinite :: \"'a set \\<Rightarrow> bool\"\n  where \"infinite S \\<equiv> \\<not> finite S\"\n\ntext \\<open>\n  Infinite sets are non-empty, and if we remove some elements from an\n  infinite set, the result is still infinite.\n\\<close>\n\nlemma infinite_UNIV_nat [iff]: \"infinite (UNIV :: nat set)\"\nproof\n  assume \"finite (UNIV :: nat set)\"\n  with finite_UNIV_inj_surj [of Suc] show False\n    by simp (blast dest: Suc_neq_Zero surjD)\nqed\n\nlemma infinite_UNIV_char_0: \"infinite (UNIV :: 'a::semiring_char_0 set)\"\nproof\n  assume \"finite (UNIV :: 'a set)\"\n  with subset_UNIV have \"finite (range of_nat :: 'a set)\"\n    by (rule finite_subset)\n  moreover have \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n    by (simp add: inj_on_def)\n  ultimately have \"finite (UNIV :: nat set)\"\n    by (rule finite_imageD)\n  then show False\n    by simp\nqed\n\nlemma infinite_imp_nonempty: \"infinite S \\<Longrightarrow> S \\<noteq> {}\"\n  by auto\n\nlemma infinite_remove: \"infinite S \\<Longrightarrow> infinite (S - {a})\"\n  by simp\n\nlemma Diff_infinite_finite:\n  assumes \"finite T\" \"infinite S\"\n  shows \"infinite (S - T)\"\n  using \\<open>finite T\\<close>\nproof induct\n  from \\<open>infinite S\\<close> show \"infinite (S - {})\"\n    by auto\nnext\n  fix T x\n  assume ih: \"infinite (S - T)\"\n  have \"S - (insert x T) = (S - T) - {x}\"\n    by (rule Diff_insert)\n  with ih show \"infinite (S - (insert x T))\"\n    by (simp add: infinite_remove)\nqed\n\nlemma Un_infinite: \"infinite S \\<Longrightarrow> infinite (S \\<union> T)\"\n  by simp\n\nlemma infinite_Un: \"infinite (S \\<union> T) \\<longleftrightarrow> infinite S \\<or> infinite T\"\n  by simp\n\nlemma infinite_super:\n  assumes \"S \\<subseteq> T\"\n    and \"infinite S\"\n  shows \"infinite T\"\nproof\n  assume \"finite T\"\n  with \\<open>S \\<subseteq> T\\<close> have \"finite S\" by (simp add: finite_subset)\n  with \\<open>infinite S\\<close> show False by simp\nqed\n\nproposition infinite_coinduct [consumes 1, case_names infinite]:\n  assumes \"X A\"\n    and step: \"\\<And>A. X A \\<Longrightarrow> \\<exists>x\\<in>A. X (A - {x}) \\<or> infinite (A - {x})\"\n  shows \"infinite A\"\nproof\n  assume \"finite A\"\n  then show False\n    using \\<open>X A\\<close>\n  proof (induction rule: finite_psubset_induct)\n    case (psubset A)\n    then obtain x where \"x \\<in> A\" \"X (A - {x}) \\<or> infinite (A - {x})\"\n      using local.step psubset.prems by blast\n    then have \"X (A - {x})\"\n      using psubset.hyps by blast\n    show False\n    proof (rule psubset.IH [where B = \"A - {x}\"])\n      show \"A - {x} \\<subset> A\"\n        using \\<open>x \\<in> A\\<close> by blast\n    qed fact\n  qed\nqed\n\ntext \\<open>\n  For any function with infinite domain and finite range there is some\n  element that is the image of infinitely many domain elements.  In\n  particular, any infinite sequence of elements from a finite set\n  contains some element that occurs infinitely often.\n\\<close>\n\nlemma inf_img_fin_dom':\n  assumes img: \"finite (f ` A)\"\n    and dom: \"infinite A\"\n  shows \"\\<exists>y \\<in> f ` A. infinite (f -` {y} \\<inter> A)\"\nproof (rule ccontr)\n  have \"A \\<subseteq> (\\<Union>y\\<in>f ` A. f -` {y} \\<inter> A)\" by auto\n  moreover assume \"\\<not> ?thesis\"\n  with img have \"finite (\\<Union>y\\<in>f ` A. f -` {y} \\<inter> A)\" by blast\n  ultimately have \"finite A\" by (rule finite_subset)\n  with dom show False by contradiction\nqed\n\nlemma inf_img_fin_domE':\n  assumes \"finite (f ` A)\" and \"infinite A\"\n  obtains y where \"y \\<in> f`A\" and \"infinite (f -` {y} \\<inter> A)\"\n  using assms by (blast dest: inf_img_fin_dom')\n\nlemma inf_img_fin_dom:\n  assumes img: \"finite (f`A)\" and dom: \"infinite A\"\n  shows \"\\<exists>y \\<in> f`A. infinite (f -` {y})\"\n  using inf_img_fin_dom'[OF assms] by auto\n\nlemma inf_img_fin_domE:\n  assumes \"finite (f`A)\" and \"infinite A\"\n  obtains y where \"y \\<in> f`A\" and \"infinite (f -` {y})\"\n  using assms by (blast dest: inf_img_fin_dom)\n\nproposition finite_image_absD: \"finite (abs ` S) \\<Longrightarrow> finite S\"\n  for S :: \"'a::linordered_ring set\"\n  by (rule ccontr) (auto simp: abs_eq_iff vimage_def dest: inf_img_fin_dom)\n\n\nsubsection \\<open>The finite powerset operator\\<close>\n\ndefinition Fpow :: \"'a set \\<Rightarrow> 'a set set\"\nwhere \"Fpow A \\<equiv> {X. X \\<subseteq> A \\<and> finite X}\"\n\nlemma Fpow_mono: \"A \\<subseteq> B \\<Longrightarrow> Fpow A \\<subseteq> Fpow B\"\nunfolding Fpow_def by auto\n\nlemma empty_in_Fpow: \"{} \\<in> Fpow A\"\nunfolding Fpow_def by auto\n\nlemma Fpow_not_empty: \"Fpow A \\<noteq> {}\"\nusing empty_in_Fpow by blast\n\nlemma Fpow_subset_Pow: \"Fpow A \\<subseteq> Pow A\"\nunfolding Fpow_def by auto\n\nlemma Fpow_Pow_finite: \"Fpow A = Pow A Int {A. finite A}\"\nunfolding Fpow_def Pow_def by blast\n\nlemma inj_on_image_Fpow:\n  assumes \"inj_on f A\"\n  shows \"inj_on (image f) (Fpow A)\"\n  using assms Fpow_subset_Pow[of A] subset_inj_on[of \"image f\" \"Pow A\"]\n    inj_on_image_Pow by blast\n\nlemma image_Fpow_mono:\n  assumes \"f ` A \\<subseteq> B\"\n  shows \"(image f) ` (Fpow A) \\<subseteq> Fpow B\"\n  using assms by(unfold Fpow_def, auto)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Finite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.9230391664210672, "lm_q1q2_score": 0.7969442654760271}}
{"text": "(*<*)theory Even imports Main begin\nML_file \"../../antiquote_setup.ML\" \n(*>*)\n\nsection{* The Set of Even Numbers *}\n\ntext {*\n\\index{even numbers!defining inductively|(}%\nThe set of even numbers can be inductively defined as the least set\ncontaining 0 and closed under the operation $+2$.  Obviously,\n\\emph{even} can also be expressed using the divides relation (@{text dvd}). \nWe shall prove below that the two formulations coincide.  On the way we\nshall examine the primary means of reasoning about inductively defined\nsets: rule induction.\n*}\n\nsubsection{* Making an Inductive Definition *}\n\ntext {*\nUsing \\commdx{inductive\\protect\\_set}, we declare the constant @{text even} to be\na set of natural numbers with the desired properties.\n*}\n\ninductive_set even :: \"nat set\" where\nzero[intro!]: \"0 \\<in> even\" |\nstep[intro!]: \"n \\<in> even \\<Longrightarrow> (Suc (Suc n)) \\<in> even\"\n\ntext {*\nAn inductive definition consists of introduction rules.  The first one\nabove states that 0 is even; the second states that if $n$ is even, then so\nis~$n+2$.  Given this declaration, Isabelle generates a fixed point\ndefinition for @{term even} and proves theorems about it,\nthus following the definitional approach (see {\\S}\\ref{sec:definitional}).\nThese theorems\ninclude the introduction rules specified in the declaration, an elimination\nrule for case analysis and an induction rule.  We can refer to these\ntheorems by automatically-generated names.  Here are two examples:\n@{named_thms[display,indent=0] even.zero[no_vars] (even.zero) even.step[no_vars] (even.step)}\n\nThe introduction rules can be given attributes.  Here\nboth rules are specified as \\isa{intro!},%\n\\index{intro\"!@\\isa {intro\"!} (attribute)}\ndirecting the classical reasoner to \napply them aggressively. Obviously, regarding 0 as even is safe.  The\n@{text step} rule is also safe because $n+2$ is even if and only if $n$ is\neven.  We prove this equivalence later.\n*}\n\nsubsection{*Using Introduction Rules*}\n\ntext {*\nOur first lemma states that numbers of the form $2\\times k$ are even.\nIntroduction rules are used to show that specific values belong to the\ninductive set.  Such proofs typically involve \ninduction, perhaps over some other inductive set.\n*}\n\nlemma two_times_even[intro!]: \"2*k \\<in> even\"\napply (induct_tac k)\n apply auto\ndone\n(*<*)\nlemma \"2*k \\<in> even\"\napply (induct_tac k)\n(*>*)\ntxt {*\n\\noindent\nThe first step is induction on the natural number @{text k}, which leaves\ntwo subgoals:\n@{subgoals[display,indent=0,margin=65]}\nHere @{text auto} simplifies both subgoals so that they match the introduction\nrules, which are then applied automatically.\n\nOur ultimate goal is to prove the equivalence between the traditional\ndefinition of @{text even} (using the divides relation) and our inductive\ndefinition.  One direction of this equivalence is immediate by the lemma\njust proved, whose @{text \"intro!\"} attribute ensures it is applied automatically.\n*}\n(*<*)oops(*>*)\nlemma dvd_imp_even: \"2 dvd n \\<Longrightarrow> n \\<in> even\"\nby (auto simp add: dvd_def)\n\nsubsection{* Rule Induction \\label{sec:rule-induction} *}\n\ntext {*\n\\index{rule induction|(}%\nFrom the definition of the set\n@{term even}, Isabelle has\ngenerated an induction rule:\n@{named_thms [display,indent=0,margin=40] even.induct [no_vars] (even.induct)}\nA property @{term P} holds for every even number provided it\nholds for~@{text 0} and is closed under the operation\n\\isa{Suc(Suc \\(\\cdot\\))}.  Then @{term P} is closed under the introduction\nrules for @{term even}, which is the least set closed under those rules. \nThis type of inductive argument is called \\textbf{rule induction}. \n\nApart from the double application of @{term Suc}, the induction rule above\nresembles the familiar mathematical induction, which indeed is an instance\nof rule induction; the natural numbers can be defined inductively to be\nthe least set containing @{text 0} and closed under~@{term Suc}.\n\nInduction is the usual way of proving a property of the elements of an\ninductively defined set.  Let us prove that all members of the set\n@{term even} are multiples of two.\n*}\n\nlemma even_imp_dvd: \"n \\<in> even \\<Longrightarrow> 2 dvd n\"\ntxt {*\nWe begin by applying induction.  Note that @{text even.induct} has the form\nof an elimination rule, so we use the method @{text erule}.  We get two\nsubgoals:\n*}\napply (erule even.induct)\ntxt {*\n@{subgoals[display,indent=0]}\nWe unfold the definition of @{text dvd} in both subgoals, proving the first\none and simplifying the second:\n*}\napply (simp_all add: dvd_def)\ntxt {*\n@{subgoals[display,indent=0]}\nThe next command eliminates the existential quantifier from the assumption\nand replaces @{text n} by @{text \"2 * k\"}.\n*}\napply clarify\ntxt {*\n@{subgoals[display,indent=0]}\nTo conclude, we tell Isabelle that the desired value is\n@{term \"Suc k\"}.  With this hint, the subgoal falls to @{text simp}.\n*}\napply (rule_tac x = \"Suc k\" in exI, simp)\n(*<*)done(*>*)\n\ntext {*\nCombining the previous two results yields our objective, the\nequivalence relating @{term even} and @{text dvd}. \n%\n%we don't want [iff]: discuss?\n*}\n\ntheorem even_iff_dvd: \"(n \\<in> even) = (2 dvd n)\"\nby (blast intro: dvd_imp_even even_imp_dvd)\n\n\nsubsection{* Generalization and Rule Induction \\label{sec:gen-rule-induction} *}\n\ntext {*\n\\index{generalizing for induction}%\nBefore applying induction, we typically must generalize\nthe induction formula.  With rule induction, the required generalization\ncan be hard to find and sometimes requires a complete reformulation of the\nproblem.  In this  example, our first attempt uses the obvious statement of\nthe result.  It fails:\n*}\n\nlemma \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\napply (erule even.induct)\noops\n(*<*)\nlemma \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\napply (erule even.induct)\n(*>*)\ntxt {*\nRule induction finds no occurrences of @{term \"Suc(Suc n)\"} in the\nconclusion, which it therefore leaves unchanged.  (Look at\n@{text even.induct} to see why this happens.)  We have these subgoals:\n@{subgoals[display,indent=0]}\nThe first one is hopeless.  Rule induction on\na non-variable term discards information, and usually fails.\nHow to deal with such situations\nin general is described in {\\S}\\ref{sec:ind-var-in-prems} below.\nIn the current case the solution is easy because\nwe have the necessary inverse, subtraction:\n*}\n(*<*)oops(*>*)\nlemma even_imp_even_minus_2: \"n \\<in> even \\<Longrightarrow> n - 2 \\<in> even\"\napply (erule even.induct)\n apply auto\ndone\n(*<*)\nlemma \"n \\<in>  even \\<Longrightarrow> n - 2 \\<in> even\"\napply (erule even.induct)\n(*>*)\ntxt {*\nThis lemma is trivially inductive.  Here are the subgoals:\n@{subgoals[display,indent=0]}\nThe first is trivial because @{text \"0 - 2\"} simplifies to @{text 0}, which is\neven.  The second is trivial too: @{term \"Suc (Suc n) - 2\"} simplifies to\n@{term n}, matching the assumption.%\n\\index{rule induction|)}  %the sequel isn't really about induction\n\n\\medskip\nUsing our lemma, we can easily prove the result we originally wanted:\n*}\n(*<*)oops(*>*)\nlemma Suc_Suc_even_imp_even: \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\nby (drule even_imp_even_minus_2, simp)\n\ntext {*\nWe have just proved the converse of the introduction rule @{text even.step}.\nThis suggests proving the following equivalence.  We give it the\n\\attrdx{iff} attribute because of its obvious value for simplification.\n*}\n\n\n\n\nsubsection{* Rule Inversion \\label{sec:rule-inversion} *}\n\ntext {*\n\\index{rule inversion|(}%\nCase analysis on an inductive definition is called \\textbf{rule\ninversion}.  It is frequently used in proofs about operational\nsemantics.  It can be highly effective when it is applied\nautomatically.  Let us look at how rule inversion is done in\nIsabelle/HOL\\@.\n\nRecall that @{term even} is the minimal set closed under these two rules:\n@{thm [display,indent=0] even.intros [no_vars]}\nMinimality means that @{term even} contains only the elements that these\nrules force it to contain.  If we are told that @{term a}\nbelongs to\n@{term even} then there are only two possibilities.  Either @{term a} is @{text 0}\nor else @{term a} has the form @{term \"Suc(Suc n)\"}, for some suitable @{term n}\nthat belongs to\n@{term even}.  That is the gist of the @{term cases} rule, which Isabelle proves\nfor us when it accepts an inductive definition:\n@{named_thms [display,indent=0,margin=40] even.cases [no_vars] (even.cases)}\nThis general rule is less useful than instances of it for\nspecific patterns.  For example, if @{term a} has the form\n@{term \"Suc(Suc n)\"} then the first case becomes irrelevant, while the second\ncase tells us that @{term n} belongs to @{term even}.  Isabelle will generate\nthis instance for us:\n*}\n\ninductive_cases Suc_Suc_cases [elim!]: \"Suc(Suc n) \\<in> even\"\n\ntext {*\nThe \\commdx{inductive\\protect\\_cases} command generates an instance of\nthe @{text cases} rule for the supplied pattern and gives it the supplied name:\n@{named_thms [display,indent=0] Suc_Suc_cases [no_vars] (Suc_Suc_cases)}\nApplying this as an elimination rule yields one case where @{text even.cases}\nwould yield two.  Rule inversion works well when the conclusions of the\nintroduction rules involve datatype constructors like @{term Suc} and @{text \"#\"}\n(list ``cons''); freeness reasoning discards all but one or two cases.\n\nIn the \\isacommand{inductive\\_cases} command we supplied an\nattribute, @{text \"elim!\"},\n\\index{elim\"!@\\isa {elim\"!} (attribute)}%\nindicating that this elimination rule can be\napplied aggressively.  The original\n@{term cases} rule would loop if used in that manner because the\npattern~@{term a} matches everything.\n\nThe rule @{text Suc_Suc_cases} is equivalent to the following implication:\n@{term [display,indent=0] \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"}\nJust above we devoted some effort to reaching precisely\nthis result.  Yet we could have obtained it by a one-line declaration,\ndispensing with the lemma @{text even_imp_even_minus_2}. \nThis example also justifies the terminology\n\\textbf{rule inversion}: the new rule inverts the introduction rule\n@{text even.step}.  In general, a rule can be inverted when the set of elements\nit introduces is disjoint from those of the other introduction rules.\n\nFor one-off applications of rule inversion, use the \\methdx{ind_cases} method. \nHere is an example:\n*}\n\n(*<*)lemma \"Suc(Suc n) \\<in> even \\<Longrightarrow> P\"(*>*)\napply (ind_cases \"Suc(Suc n) \\<in> even\")\n(*<*)oops(*>*)\n\ntext {*\nThe specified instance of the @{text cases} rule is generated, then applied\nas an elimination rule.\n\nTo summarize, every inductive definition produces a @{text cases} rule.  The\n\\commdx{inductive\\protect\\_cases} command stores an instance of the\n@{text cases} rule for a given pattern.  Within a proof, the\n@{text ind_cases} method applies an instance of the @{text cases}\nrule.\n\nThe even numbers example has shown how inductive definitions can be\nused.  Later examples will show that they are actually worth using.%\n\\index{rule inversion|)}%\n\\index{even numbers!defining inductively|)}\n*}\n\n(*<*)end(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/Inductive/Even.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.7968847138889088}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Proving Falling Factorial of a Sum with Induction\\<close>\n\ntheory Falling_Factorial_Sum_Induction\nimports\n  Discrete_Summation.Factorials\nbegin\n\ntext \\<open>Note the potentially special copyright license condition of the following proof.\\<close>\n\nlemma ffact_add_nat:\n  \"ffact n (x + y) = (\\<Sum>k=0..n. (n choose k) * ffact k x * ffact (n - k) y)\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  let ?s = \"\\<lambda>k. (n choose k) * ffact k x * ffact (n - k) y\"\n  let ?t = \"\\<lambda>k. ffact k x * ffact (Suc n - k) y\"\n  let ?u = \"\\<lambda>k. ffact (Suc k) x * ffact (n - k) y\"\n  have \"ffact (Suc n) (x + y) = (x + y - n) * ffact n (x + y)\"\n    by (simp add: ffact_Suc_rev_nat)\n  also have \"\\<dots> = (x + y - n) * (\\<Sum>k = 0..n. (n choose k) * ffact k x * ffact (n - k) y)\"\n    using Suc.hyps by simp\n  also have \"\\<dots> = (\\<Sum>k = 0..n. ?s k * (x + y - n))\"\n    by (simp add: mult.commute sum_distrib_left)\n  also have \"\\<dots> = (\\<Sum>k = 0..n. ?s k * ((y + k - n) + (x - k)))\"\n  proof -\n    have \"?s k * (x + y - n) = ?s k * ((y + k - n) + (x - k))\" for k\n      by (cases \"k \\<le> x \\<or> n - k \\<le> y\") (auto simp add: ffact_nat_triv)\n    from this show ?thesis\n      by (auto intro: sum.cong simp only: refl)\n  qed\n  also have \"\\<dots> = (\\<Sum>k = 0..n. (n choose k) * (?t k + ?u k))\"\n    by (auto intro!: sum.cong simp add: Suc_diff_le ffact_Suc_rev_nat) algebra\n  also have \"\\<dots> = (\\<Sum>k = 0..n. (n choose k) * ?t k) + (\\<Sum>k = 0..n. (n choose k) * ?u k)\"\n    by (simp add: sum.distrib add_mult_distrib2 mult.commute mult.left_commute)\n  also have \"\\<dots> = ?t 0 + (\\<Sum>k = 0..n. (n choose k + (n choose Suc k)) * ?u k)\"\n  proof -\n    have \"\\<dots> = (?t 0 + (\\<Sum>k = 0..n. (n choose Suc k) * ?u k)) + (\\<Sum>k = 0..n. (n choose k) * ?u k)\"\n    proof -\n      have \"(\\<Sum>k = Suc 0..n. (n choose k) * ?t k) = (\\<Sum>k = 0..n. (n choose Suc k) * ?u k)\"\n      proof -\n        have \"(\\<Sum>k = Suc 0..n. (n choose k) * ?t k) = (\\<Sum>k = Suc 0..Suc n. (n choose k) * ?t k)\"\n          by simp\n        also have \"\\<dots> = (sum ((\\<lambda>k. (n choose k) * ?t k) o Suc) {0..n})\"\n          by (simp only: sum.reindex[symmetric, of Suc] inj_Suc image_Suc_atLeastAtMost)\n        also have \"\\<dots> = (\\<Sum>k = 0..n. (n choose Suc k) * ?u k)\"\n          by simp\n        finally show ?thesis .\n      qed\n      from this show ?thesis\n        by (simp add: sum.atLeast_Suc_atMost[of _ _ \"\\<lambda>k. (n choose k) * ?t k\"])\n    qed\n    also have \"\\<dots> = ?t 0 + (\\<Sum>k = 0..n. (n choose k + (n choose Suc k)) * ?u k)\"\n      by (simp add: distrib_right sum.distrib)\n    finally show ?thesis .\n  qed\n  also have \"\\<dots> = (\\<Sum>k = 0..Suc n. (Suc n choose k) * ffact k x * ffact (Suc n - k) y)\"\n  proof -\n    let ?v = \"\\<lambda>k. (Suc n choose k) * ffact k x * ffact (Suc n - k) y\"\n    have \"\\<dots> = ?v 0 + (\\<Sum>k = 0..n. (Suc n choose (Suc k)) * ?u k)\"\n      by simp\n    also have \"\\<dots> = ?v 0 + (\\<Sum>k = Suc 0..Suc n. ?v k)\"\n      by (simp only: sum.shift_bounds_cl_Suc_ivl diff_Suc_Suc mult.assoc)\n    also have \"\\<dots> = (\\<Sum>k = 0..Suc n. (Suc n choose k) * ffact k x * ffact (Suc n - k) y)\"\n      by (simp add: sum.atLeast_Suc_atMost)\n    finally show ?thesis .\n  qed\n  finally show ?case .\nqed\n\n(* TODO: what's the right class here? *)\nlemma ffact_add:\n  fixes x y :: \"'a::{ab_group_add, comm_semiring_1_cancel, ring_1}\"\n  shows \"ffact n (x + y) = (\\<Sum>k=0..n. of_nat (n choose k) * ffact k x * ffact (n - k) y)\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  let ?s = \"\\<lambda>k. of_nat (n choose k) * ffact k x * ffact (n - k) y\"\n  let ?t = \"\\<lambda>k. ffact k x * ffact (Suc n - k) y\"\n  let ?u = \"\\<lambda>k. ffact (Suc k) x * ffact (n - k) y\"\n  have \"ffact (Suc n) (x + y) = (x + y - of_nat n) * ffact n (x + y)\"\n    by (simp add: ffact_Suc_rev)\n  also have \"\\<dots> = (x + y - of_nat n) * (\\<Sum>k = 0..n. of_nat (n choose k) * ffact k x * ffact (n - k) y)\"\n    using Suc.hyps by simp\n  also have \"\\<dots> = (\\<Sum>k = 0..n. ?s k * (x + y - of_nat n))\"\n    by (simp add: mult.commute sum_distrib_left)\n  also have \"\\<dots> = (\\<Sum>k = 0..n. ?s k * ((y + of_nat k - of_nat n) + (x - of_nat k)))\"\n    by (auto intro: sum.cong simp add: diff_add_eq add_diff_eq add.commute)\n  also have \"\\<dots> = (\\<Sum>k = 0..n. of_nat (n choose k) * (?t k + ?u k))\"\n  proof -\n    {\n      fix k\n      assume \"k \\<le> n\"\n      have \"?u k = ffact k x * ffact (n - k) y * (x - of_nat k)\"\n        by (simp add: ffact_Suc_rev Suc_diff_le of_nat_diff mult.commute mult.left_commute)\n      moreover from \\<open>k \\<le> n\\<close> have \"?t k = ffact k x * ffact (n - k) y * (y + of_nat k - of_nat n)\"\n        by (simp add: ffact_Suc_rev Suc_diff_le of_nat_diff diff_diff_eq2 mult.commute mult.left_commute)\n      ultimately have\n        \"?s k * ((y + of_nat k - of_nat n) + (x - of_nat k)) = of_nat (n choose k) * (?t k + ?u k)\"\n        by (metis (no_types, lifting) distrib_left mult.assoc)\n    }\n    from this show ?thesis by (auto intro: sum.cong)\n  qed\n  also have \"\\<dots> = (\\<Sum>k = 0..n. of_nat (n choose k) * ?t k) + (\\<Sum>k = 0..n. of_nat (n choose k) * ?u k)\"\n    by (simp add: sum.distrib distrib_left mult.commute mult.left_commute)\n  also have \"\\<dots> = ?t 0 + (\\<Sum>k = 0..n. of_nat (n choose k + (n choose Suc k)) * ?u k)\"\n  proof -\n    have \"\\<dots> = (?t 0 + (\\<Sum>k = 0..n. of_nat (n choose Suc k) * ?u k)) + (\\<Sum>k = 0..n. of_nat (n choose k) * ?u k)\"\n    proof -\n      have \"(\\<Sum>k = Suc 0..n. of_nat (n choose k) * ?t k) = (\\<Sum>k = 0..n. of_nat (n choose Suc k) * ?u k)\"\n      proof -\n        have \"(\\<Sum>k = Suc 0..n. of_nat (n choose k) * ?t k) = (\\<Sum>k = Suc 0..Suc n. of_nat (n choose k) * ?t k)\"\n          by (simp add: binomial_eq_0)\n        also have \"\\<dots> = (sum ((\\<lambda>k. of_nat (n choose k) * ?t k) o Suc) {0..n})\"\n          by (simp only: sum.reindex[symmetric, of Suc] inj_Suc image_Suc_atLeastAtMost)\n        also have \"\\<dots> = (\\<Sum>k = 0..n. of_nat (n choose Suc k) * ?u k)\"\n          by simp\n        finally show ?thesis .\n      qed\n      from this show ?thesis\n        by (simp add: sum.atLeast_Suc_atMost[of _ _ \"\\<lambda>k. of_nat (n choose k) * ?t k\"])\n    qed\n    also have \"\\<dots> = ?t 0 + (\\<Sum>k = 0..n. of_nat (n choose k + (n choose Suc k)) * ?u k)\"\n      by (simp add: distrib_right sum.distrib)\n    finally show ?thesis .\n  qed\n  also have \"\\<dots> = (\\<Sum>k = 0..Suc n. of_nat (Suc n choose k) * ffact k x * ffact (Suc n - k) y)\"\n  proof -\n    let ?v = \"\\<lambda>k. of_nat (Suc n choose k) * ffact k x * ffact (Suc n - k) y\"\n    have \"\\<dots> = ?v 0 + (\\<Sum>k = 0..n. of_nat (Suc n choose (Suc k)) * ?u k)\"\n      by simp\n    also have \"\\<dots> = ?v 0 + (\\<Sum>k = Suc 0..Suc n. ?v k)\"\n      by (simp only: sum.shift_bounds_cl_Suc_ivl diff_Suc_Suc mult.assoc)\n    also have \"\\<dots> = (\\<Sum>k = 0..Suc n. of_nat (Suc n choose k) * ffact k x * ffact (Suc n - k) y)\"\n      by (simp add: sum.atLeast_Suc_atMost)\n    finally show ?thesis .\n  qed\n  finally show ?case .\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Falling_Factorial_Sum/Falling_Factorial_Sum_Induction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8807970732843033, "lm_q1q2_score": 0.7968135481904505}}
{"text": "(*\n    File:      Moebius_Mu.thy\n    Author:    Manuel Eberl, TU München\n*)\nsection \\<open>The M\\\"{o}bius $\\mu$ function\\<close>\ntheory Moebius_Mu\nimports\n  Main\n  \"HOL-Number_Theory.Number_Theory\"\n  \"HOL-Computational_Algebra.Squarefree\"\n  Dirichlet_Series\n  Dirichlet_Misc\nbegin\n\ndefinition moebius_mu :: \"nat \\<Rightarrow> 'a :: comm_ring_1\" where\n  \"moebius_mu n = \n     (if squarefree n then (-1) ^ card (prime_factors n) else 0)\"\n  \nlemma abs_moebius_mu_le: \"abs (moebius_mu n :: 'a :: {linordered_idom}) \\<le> 1\"\n  by (auto simp add: moebius_mu_def)\n\nlemma of_int_moebius_mu [simp]: \"of_int (moebius_mu n) = moebius_mu n\"\n  by (simp add: moebius_mu_def)\n  \nlemma minus_1_power_ring_neq_zero [simp]: \"(- 1 :: 'a :: ring_1) ^ n \\<noteq> 0\"\n  by (cases \"even n\") simp_all\n\nlemma moebius_mu_0 [simp]: \"moebius_mu 0 = 0\"\n  by (simp add: moebius_mu_def)\n\nlemma fds_nth_fds_moebius_mu [simp]: \"fds_nth (fds moebius_mu) = moebius_mu\"\n  by (simp add: fun_eq_iff fds_nth_fds)\n    \nlemma prime_factors_Suc_0 [simp]: \"prime_factors (Suc 0) = {}\"\n  by simp\n  \nlemma moebius_mu_Suc_0 [simp]: \"moebius_mu (Suc 0) = 1\"\n  by (simp add: moebius_mu_def)\n    \nlemma moebius_mu_1 [simp]: \"moebius_mu 1 = 1\"\n  by (simp add: moebius_mu_def)\n\nlemma moebius_mu_eq_zero_iff: \"moebius_mu n = 0 \\<longleftrightarrow> \\<not>squarefree n\"\n  by (simp add: moebius_mu_def)\n    \nlemma moebius_mu_not_squarefree [simp]: \"\\<not>squarefree n \\<Longrightarrow> moebius_mu n = 0\"\n  by (simp add: moebius_mu_def)\n\nlemma moebius_mu_power:\n  assumes \"a > 1\" \"n > 1\"\n  shows   \"moebius_mu (a ^ n) = 0\"\nproof -\n  from assms have \"a ^ 2 dvd a ^ n\" by (simp add: le_imp_power_dvd)\n  with moebius_mu_eq_zero_iff[of \"a ^ n\"] and \\<open>a > 1\\<close> show ?thesis by (auto simp: squarefree_def)\nqed\n  \nlemma moebius_mu_power':\n  \"moebius_mu (a ^ n) = (if a = 1 \\<or> n = 0 then 1 else if n = 1 then moebius_mu a else 0)\"\n  by (simp add: squarefree_power_iff)\n\nlemma moebius_mu_squarefree_eq: \n  \"squarefree n \\<Longrightarrow> moebius_mu n = (-1) ^ card (prime_factors n)\"\n  by (simp add: moebius_mu_def split: if_splits)\n\nlemma moebius_mu_squarefree_eq': \n  assumes \"squarefree n\"\n  shows   \"moebius_mu n = (-1) ^ size (prime_factorization n)\"\nproof -\n  let ?P = \"prime_factorization n\"\n  from assms have [simp]: \"n > 0\" by (auto intro!: Nat.gr0I)\n  have \"size ?P = sum (count ?P) (set_mset ?P)\" by (rule size_multiset_overloaded_eq)\n  also from assms have \"\\<dots> = sum (\\<lambda>_. 1) (set_mset ?P)\"\n    by (intro sum.cong refl, subst count_prime_factorization_prime)\n       (auto simp: moebius_mu_eq_zero_iff squarefree_factorial_semiring')\n  also have \"\\<dots> = card (set_mset ?P)\" by simp\n  finally show ?thesis by (simp add: moebius_mu_squarefree_eq[OF assms])\nqed\n \nlemma sum_moebius_mu_divisors:\n  assumes \"n > 1\"\n  shows   \"(\\<Sum>d | d dvd n. moebius_mu d) = (0 :: 'a :: comm_ring_1)\"\nproof -\n  have \"(\\<Sum>d | d dvd n. moebius_mu d :: int) = \n          (\\<Sum>d \\<in> Prod ` {P. P \\<subseteq> prime_factors n}. moebius_mu d)\"\n  proof (rule sum.mono_neutral_right; safe?)\n    fix A assume A: \"A \\<subseteq> prime_factors n\"\n    from A have [simp]: \"finite A\" by (rule finite_subset) auto\n    from A have A': \"x > 0\" \"prime x\" if \"x \\<in> A\" for x using that \n      by (auto simp: prime_factors_multiplicity prime_gt_0_nat)\n    from A' have A_nz: \"\\<Prod>A \\<noteq> 0\" by (intro notI) auto\n    from A' have \"prime_factorization (\\<Prod>A) = sum prime_factorization A\"\n      by (subst prime_factorization_prod) (auto dest: finite_subset)\n    also from A' have \"\\<dots> = sum (\\<lambda>x. {#x#}) A\"\n      by (intro sum.cong refl) (auto simp: prime_factorization_prime)\n    also have \"\\<dots> = mset_set A\" by simp\n    also from A have \"\\<dots> \\<subseteq># mset_set (prime_factors n)\"\n      by (rule subset_imp_msubset_mset_set) simp_all\n    also have \"\\<dots> \\<subseteq># prime_factorization n\" by (rule mset_set_set_mset_msubset)\n    finally show \"\\<Prod>A dvd n\" using A_nz\n      by (intro prime_factorization_subset_imp_dvd) auto\n  next\n    fix x assume x: \"x \\<notin> Prod ` {P. P \\<subseteq> prime_factors n}\" \"x dvd n\"\n    from x assms have [simp]: \"x > 0\" by (auto intro!: Nat.gr0I)\n    {\n      assume nz: \"moebius_mu x \\<noteq> 0\"\n      have \"(\\<Prod>(set_mset (prime_factorization x))) = (\\<Prod>p\\<in>prime_factors x. p ^ multiplicity p x)\"\n        using nz by (intro prod.cong refl)\n                    (auto simp: moebius_mu_eq_zero_iff squarefree_factorial_semiring')\n      also have \"\\<dots> = x\" by (intro Primes.prime_factorization_nat [symmetric]) auto\n      finally have \"x = \\<Prod>(prime_factors x)\" \"prime_factors x \\<subseteq> prime_factors n\"\n        using dvd_prime_factors[of n x] assms \\<open>x dvd n\\<close> by auto\n      hence \"x \\<in> Prod ` {P. P \\<subseteq> prime_factors n}\" by blast\n      with x(1) have False by contradiction\n    }\n    thus \"moebius_mu x = 0\" by blast\n  qed (insert assms, auto)\n  also have \"\\<dots> = (\\<Sum>P | P \\<subseteq> prime_factors n. moebius_mu (\\<Prod>P))\"\n    by (subst sum.reindex) (auto intro!: inj_on_Prod_primes dest: finite_subset)\n  also have \"\\<dots> = (\\<Sum>P | P \\<subseteq> prime_factors n. (-1) ^ card P)\"\n  proof (intro sum.cong refl)\n    fix P assume P: \"P \\<in> {P. P \\<subseteq> prime_factors n}\"\n    hence [simp]: \"finite P\" by (auto dest: finite_subset)\n    from P have prime: \"prime p\" if \"p \\<in> P\" for p using that by (auto simp: prime_factors_dvd)\n    hence \"squarefree (\\<Prod>P)\"\n      by (intro squarefree_prod_coprime prime_imp_coprime squarefree_prime)\n         (auto simp: primes_dvd_imp_eq)\n    hence \"moebius_mu (\\<Prod>P) = (-1) ^ card (prime_factors (\\<Prod>P))\"\n      by (rule moebius_mu_squarefree_eq)\n    also from P have \"prime_factors (\\<Prod>P) = P\"\n      by (subst prime_factors_prod) (auto simp: prime_factorization_prime prime)\n    finally show  \"moebius_mu (\\<Prod>P) = (-1) ^ card P\" .\n  qed\n  also have \"{P. P \\<subseteq> prime_factors n} = \n               {P. P \\<subseteq> prime_factors n \\<and> even (card P)} \\<union> {P. P \\<subseteq> prime_factors n \\<and> odd (card P)}\"\n    (is \"_ = ?A \\<union> ?B\") by blast\n  also have \"(\\<Sum>P \\<in> \\<dots>. (-1) ^ card P) = (\\<Sum>P \\<in> ?A. (-1) ^ card P) + (\\<Sum>P \\<in> ?B. (-1) ^ card P)\"\n    by (intro sum.union_disjoint) auto\n  also have \"(\\<Sum>P \\<in> ?A. (-1) ^ card P :: int) = (\\<Sum>P \\<in> ?A. 1)\" by (intro sum.cong refl) auto\n  also have \"\\<dots> = int (card ?A)\" by simp\n  also have \"(\\<Sum>P \\<in> ?B. (-1) ^ card P :: int) = (\\<Sum>P \\<in> ?B. -1)\" by (intro sum.cong refl) auto\n  also have \"\\<dots> = -int (card ?B)\" by simp\n  also have \"card ?B = card ?A\" \n    by (rule card_even_odd_subset [symmetric]) \n       (insert assms, auto simp: prime_factorization_empty_iff)\n  also have \"int (card ?A) + (- int (card ?A)) = 0\" by simp\n  finally have \"(\\<Sum>d | d dvd n. of_int (moebius_mu d) :: 'a) = 0\"\n    unfolding of_int_sum [symmetric] by (simp only: of_int_0)\n  thus ?thesis by simp\nqed\n\nlemma sum_moebius_mu_divisors':\n  \"(\\<Sum>d | d dvd n. moebius_mu d) = (if n = 1 then 1 else 0)\"\nproof -\n  have \"n = 0 \\<or> n = 1 \\<or> n > 1\" by force\n  thus ?thesis using sum_moebius_mu_divisors[of n] by auto\nqed\n\nlemma fds_zeta_times_moebius_mu: \"fds_zeta * fds moebius_mu = 1\"\nproof\n  fix n :: nat assume n: \"n > 0\"\n  from n have \"fds_nth (fds_zeta * fds moebius_mu :: 'a fds) n = (\\<Sum>d | d dvd n. moebius_mu d)\"\n    unfolding fds_nth_mult dirichlet_prod_altdef1\n    by (intro sum.cong refl) (auto simp: fds_nth_fds elim: dvdE)\n  also have \"\\<dots> = fds_nth 1 n\" by (simp add: sum_moebius_mu_divisors')\n  finally show \"fds_nth (fds_zeta * fds moebius_mu :: 'a fds) n = fds_nth 1 n\" .\nqed\n\nlemma fds_moebius_inverse_zeta:\n  \"fds moebius_mu = inverse (fds_zeta :: 'a :: field fds)\"\n  using fds_right_inverse_unique fds_zeta_times_moebius_mu by blast\n\nlemma moebius_mu_formula_real: \"(moebius_mu n :: real) = dirichlet_inverse (\\<lambda>_. 1) 1 n\"\nproof -\n  have \"moebius_mu n = (fds_nth (fds moebius_mu) n :: real)\" by simp\n  also have \"fds moebius_mu = (inverse fds_zeta :: real fds)\" by (fact fds_moebius_inverse_zeta)\n  also have \"fds_nth \\<dots> n = dirichlet_inverse (fds_nth fds_zeta) 1 n\"\n    unfolding fds_nth_inverse by simp\n  also have \"\\<dots> = dirichlet_inverse (\\<lambda>_. 1) 1 n\" by (rule dirichlet_inverse_cong) simp_all\n  finally show ?thesis .\nqed\n\nlemma moebius_mu_formula_int: \"moebius_mu n = dirichlet_inverse (\\<lambda>_. 1 :: int) 1 n\"\nproof -\n  have \"real_of_int (moebius_mu n) = moebius_mu n\" by simp\n  also have \"\\<dots> = dirichlet_inverse (\\<lambda>_. 1) 1 n\" by (fact moebius_mu_formula_real)\n  also have \"\\<dots> = real_of_int (dirichlet_inverse (\\<lambda>_. 1) 1 n)\"\n    by (induction n rule: dirichlet_inverse_induct) (simp_all add: dirichlet_inverse_gt_1)\n  finally show ?thesis by (subst (asm) of_int_eq_iff)\nqed\n\nlemma moebius_mu_formula: \"moebius_mu n = dirichlet_inverse (\\<lambda>_. 1) 1 n\"\n  by (subst of_int_moebius_mu [symmetric], subst moebius_mu_formula_int)\n     (simp add: of_int_dirichlet_inverse)\n\ninterpretation moebius_mu: multiplicative_function moebius_mu\nproof -\n  have \"multiplicative_function (dirichlet_inverse (\\<lambda>n. if n = 0 then 0 else 1 :: 'a) 1)\"\n    by (rule multiplicative_dirichlet_inverse, standard) simp_all\n  also have \"dirichlet_inverse (\\<lambda>n. if n = 0 then 0 else 1 :: 'a) 1 = moebius_mu\"\n    by (auto simp: fun_eq_iff moebius_mu_formula)\n  finally show \"multiplicative_function (moebius_mu :: nat \\<Rightarrow> 'a)\" .\nqed\n\ninterpretation moebius_mu: \n  multiplicative_function' moebius_mu \"\\<lambda>p k. if k = 1 then -1 else 0\" \"\\<lambda>_. -1\"\nproof\n  fix p k :: nat assume \"prime p\" \"k > 0\"\n  moreover from this have \"moebius_mu p = -1\" \n    by (simp add: moebius_mu_def prime_factorization_prime squarefree_prime)\n  ultimately show \"moebius_mu (p ^ k) = (if k = 1 then - 1 else 0)\"\n    by (auto simp: moebius_mu_power')\nqed auto\n  \nlemma moebius_mu_2 [simp]: \"moebius_mu 2 = -1\"\n  and moebius_mu_3 [simp]: \"moebius_mu 3 = -1\"\n  by (rule moebius_mu.prime; simp)+\n\n\nlemma moebius_mu_code [code]:\n  \"moebius_mu n = of_int (dirichlet_inverse (\\<lambda>_. 1 :: int) 1 n)\"\n  by (subst moebius_mu_formula_int [symmetric]) simp\n\n\nlemma fds_moebius_inversion: \"f = fds moebius_mu * g \\<longleftrightarrow> g = f * fds_zeta\"\n  by (metis fds_zeta_times_moebius_mu mult.commute mult.left_commute mult.right_neutral)\n\nlemma moebius_inversion:\n  assumes \"\\<And>n. n > 0 \\<Longrightarrow> g n = (\\<Sum>d | d dvd n. f d)\" \"n > 0\"\n  shows   \"f n = dirichlet_prod moebius_mu g n\"\nproof -\n  from assms have \"fds g = fds f * fds_zeta\"\n    by (intro fds_eqI) (simp add: fds_nth_mult dirichlet_prod_def)\n  thus ?thesis using assms\n    by (subst (asm) fds_moebius_inversion [symmetric]) (simp add: fds_eq_iff fds_nth_mult)\nqed\n\nlemma fds_mangoldt: \"fds mangoldt = fds moebius_mu * fds (\\<lambda>n. of_real (ln (real n)))\"\n  by (subst fds_moebius_inversion) (rule fds_mangoldt_times_zeta [symmetric])\n\n(* 2.18 *)\nlemma sum_divisors_moebius_mu_times_multiplicative:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {comm_ring_1}\"\n  assumes \"multiplicative_function f\" \"n > 0\"\n  shows   \"(\\<Sum>d | d dvd n. moebius_mu d * f d) = (\\<Prod>p\\<in>prime_factors n. 1 - f p)\"\nproof -\n  define g where \"g = (\\<lambda>n. \\<Sum>d | d dvd n. moebius_mu d * f d)\"\n  define g' where \"g' = dirichlet_prod (\\<lambda>n. moebius_mu n * f n) (\\<lambda>n. if n = 0 then 0 else 1)\"\n  interpret f: multiplicative_function f by fact\n  have \"multiplicative_function (\\<lambda>n. if n = 0 then 0 else 1 :: 'a)\"\n    by standard auto\n  interpret multiplicative_function g' unfolding g'_def\n    by (intro multiplicative_dirichlet_prod multiplicative_function_mult\n              moebius_mu.multiplicative_function_axioms assms) fact+\n\n  have g'_primepow: \"g' (p ^ k) = 1 - f p\" if \"prime p\" \"k > 0\" for p k\n  proof -\n    have \"g' (p ^ k) = (\\<Sum>i\\<le>k. moebius_mu (p ^ i) * f (p ^ i))\"\n      using that by (simp add: g'_def dirichlet_prod_prime_power)\n    also have \"\\<dots> = (\\<Sum>i\\<in>{0, 1}. moebius_mu (p ^ i) * f (p ^ i))\"\n      using that by (intro sum.mono_neutral_right) (auto simp: moebius_mu_power')\n    also have \"\\<dots> = 1 - f p\"\n      using that by (simp add: moebius_mu.prime)\n    finally show ?thesis .\n  qed\n\n  have \"g' n = g n\"\n    by (simp add: g_def g'_def dirichlet_prod_def)\n  also from assms have \"g' n = (\\<Prod>p\\<in>prime_factors n. g' (p ^ multiplicity p n))\"\n      by (intro prod_prime_factors) auto\n  also have \"\\<dots> = (\\<Prod>p\\<in>prime_factors n. 1 - f p)\"\n    by (intro prod.cong) (auto simp: g'_primepow prime_factors_multiplicity)\n  finally show ?thesis by (simp add: g_def)\nqed\n  \n\n(* Theorem 2.17 *)\nlemma completely_multiplicative_iff_inverse_moebius_mu:\n  fixes f :: \"nat \\<Rightarrow> 'a :: {comm_ring_1, ring_no_zero_divisors}\"\n  assumes \"multiplicative_function f\"\n  defines \"g \\<equiv> dirichlet_inverse f 1\"\n  shows   \"completely_multiplicative_function f \\<longleftrightarrow>\n             (\\<forall>n. g n = moebius_mu n * f n)\"\nproof -\n  interpret multiplicative_function f by fact\n  show ?thesis\n  proof safe\n    assume \"completely_multiplicative_function f\"\n    then interpret completely_multiplicative_function f .\n    have [simp]: \"fds f \\<noteq> 0\" by (auto simp: fds_eq_iff)\n\n    have \"fds (\\<lambda>n. moebius_mu n * f n) * fds f = 1\"\n    proof\n      fix n :: nat\n      have \"fds_nth (fds (\\<lambda>n. moebius_mu n * f n) * fds f) n =\n              (\\<Sum>(r, d) | r * d = n. moebius_mu r * f (r * d))\"\n        by (simp add: fds_eq_iff fds_nth_mult fds_nth_fds dirichlet_prod_altdef2 mult mult.assoc)\n      also have \"\\<dots> = (\\<Sum>(r, d) | r * d = n. moebius_mu r * f n)\"\n        by (intro sum.cong) auto\n      also have \"\\<dots> = dirichlet_prod moebius_mu (\\<lambda>_. 1) n * f n\"\n        by (simp add: dirichlet_prod_altdef2 sum_distrib_right case_prod_unfold mult)\n      also have \"dirichlet_prod moebius_mu (\\<lambda>_. 1) n = fds_nth (fds moebius_mu * fds_zeta) n\"\n        by (simp add: fds_nth_mult)\n      also have \"fds moebius_mu * fds_zeta = 1\"\n        by (simp add: mult_ac fds_zeta_times_moebius_mu)\n      also have \"fds_nth 1 n * f n = fds_nth 1 n\"\n        by (auto simp: fds_eq_iff fds_nth_one)\n      finally show \"fds_nth (fds (\\<lambda>n. moebius_mu n * f n) * fds f) n = fds_nth 1 n\" .\n    qed\n    also have \"1 = fds g * fds f\"\n      by (auto simp: fds_eq_iff g_def fds_nth_mult dirichlet_prod_inverse')\n    finally have \"fds g = fds (\\<lambda>n. moebius_mu n * f n)\"\n      by (subst (asm) mult_cancel_right) auto\n    thus \"g n = moebius_mu n * f n\" for n\n      by (cases \"n = 0\") (auto simp: fds_eq_iff g_def)\n  next\n    assume g: \"\\<forall>n. g n = moebius_mu n * f n\"\n    show \"completely_multiplicative_function f\"\n    proof (rule completely_multiplicativeI)\n      fix p k :: nat assume pk: \"prime p\" \"k > 0\"\n      show \"f (p ^ k) = f p ^ k\"\n      proof (induction k)\n        case (Suc k)\n        have eq: \"dirichlet_prod g f n = 0\" if \"n \\<noteq> 1\" for n\n          unfolding g_def using dirichlet_prod_inverse'[of f 1] that by auto\n        have \"dirichlet_prod g f (p ^ Suc k) = 0\"\n          using pk by (intro eq) auto\n        also have \"dirichlet_prod g f (p ^ Suc k) = (\\<Sum>i\\<le>Suc k. g (p ^ i) * f (p ^ (Suc k - i)))\"\n          by (intro dirichlet_prod_prime_power) fact+\n        also have \"\\<dots> = (\\<Sum>i\\<le>Suc k. moebius_mu (p ^ i) * f (p ^ i) * f (p ^ (Suc k - i)))\"\n          by (intro sum.cong refl, subst g) auto\n        also have \"\\<dots> = (\\<Sum>i\\<in>{0, 1}. moebius_mu (p ^ i) * f (p ^ i) * f (p ^ (Suc k - i)))\"\n          using pk by (intro sum.mono_neutral_right) (auto simp: moebius_mu_power')\n        also have \"\\<dots> = f (p ^ Suc k) - f p ^ Suc k\"\n          using pk Suc.IH by (auto simp: moebius_mu.prime)\n        finally show \"f (p ^ Suc k) = f p ^ Suc k\" by simp\n      qed auto\n    qed\n  qed\nqed\n\nlemma completely_multiplicative_fds_inverse:\n  fixes f :: \"nat \\<Rightarrow> 'a :: field\"\n  assumes \"completely_multiplicative_function f\"\n  shows   \"inverse (fds f) = fds (\\<lambda>n. moebius_mu n * f n)\"\nproof -\n  interpret completely_multiplicative_function f by fact\n  from assms show ?thesis\n    by (subst (asm) completely_multiplicative_iff_inverse_moebius_mu)\n       (auto simp: inverse_fds_def multiplicative_function_axioms)\nqed\n\nlemma completely_multiplicative_fds_inverse':\n  fixes f :: \"'a :: field fds\"\n  assumes \"completely_multiplicative_function (fds_nth f)\"\n  shows   \"inverse f = fds (\\<lambda>n. moebius_mu n * fds_nth f n)\"\n  by (metis assms completely_multiplicative_fds_inverse fds_fds_nth)\n    \n\ncontext\n  includes fds_syntax\nbegin\n\nlemma selberg_aux:\n  \"(\\<chi> n. of_real ((ln n)\\<^sup>2)) * fds moebius_mu =\n     (fds mangoldt)\\<^sup>2 - fds_deriv (fds mangoldt :: 'a :: {comm_ring_1,real_algebra_1} fds)\"\nproof -\n  have \"(\\<chi> n. of_real (ln (real n) ^ 2)) = fds_deriv (fds_deriv fds_zeta :: 'a fds)\"\n    by (rule fds_eqI) (simp add: fds_nth_fds fds_nth_deriv power2_eq_square scaleR_conv_of_real)\n  also have \"\\<dots> = (fds mangoldt ^ 2 - fds_deriv (fds mangoldt)) * fds_zeta\"\n    by (simp add: fds_deriv_zeta algebra_simps power2_eq_square)\n  also have \"\\<dots> * fds moebius_mu = ((fds mangoldt)\\<^sup>2 - fds_deriv (fds mangoldt)) * \n                                      (fds_zeta * fds moebius_mu)\" by (simp add: mult_ac)\n  also have \"fds_zeta * fds moebius_mu = (1 :: 'a fds)\" by (fact fds_zeta_times_moebius_mu)\n  finally show ?thesis by simp\nqed\n  \nlemma selberg_aux':\n  \"mangoldt n * of_real (ln n) + (mangoldt \\<star> mangoldt) n =\n     ((moebius_mu \\<star> (\\<lambda>b. of_real (ln b) ^ 2)) n\n         :: 'a :: {comm_ring_1,real_algebra_1})\" if \"n > 0\"\n  using selberg_aux [symmetric] that \n  by (auto simp add: fds_eq_iff fds_nth_mult power2_eq_square fds_nth_deriv\n        dirichlet_prod_commutes algebra_simps scaleR_conv_of_real)\n\nend\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Dirichlet_Series/Moebius_Mu.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8918110497511051, "lm_q1q2_score": 0.7966632067651414}}
{"text": "(*  Title:      HOL/Examples/Ackermann.thy\n    Author:     Larry Paulson\n*)\n\nsection \\<open>A Tail-Recursive, Stack-Based Ackermann's Function\\<close>\n\ntheory Ackermann imports \"HOL-Library.Multiset_Order\" \"HOL-Library.Product_Lexorder\" \n\nbegin\n\ntext\\<open>This theory investigates a stack-based implementation of Ackermann's function.\nLet's recall the traditional definition,\nas modified by R{\\'o}zsa P\\'eter and Raphael Robinson.\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n             = Suc n\"\n| \"ack (Suc m) 0       = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\nsubsection \\<open>Example of proving termination by reasoning about the domain\\<close>\n\ntext\\<open>The stack-based version uses lists.\\<close>\n\nfunction (domintros) ackloop :: \"nat list \\<Rightarrow> nat\" where\n  \"ackloop (n # 0 # l)         = ackloop (Suc n # l)\"\n| \"ackloop (0 # Suc m # l)     = ackloop (1 # m # l)\"\n| \"ackloop (Suc n # Suc m # l) = ackloop (n # Suc m # m # l)\"\n| \"ackloop [m] = m\"\n| \"ackloop [] =  0\"\n  by pat_completeness auto\n\ntext\\<open>\nThe key task is to prove termination. In the first recursive call, the head of the list gets bigger\nwhile the list gets shorter, suggesting that the length of the list should be the primary\ntermination criterion. But in the third recursive call, the list gets longer. The idea of trying\na multiset-based termination argument is frustrated by the second recursive call when m = 0:\nthe list elements are simply permuted.\n\nFortunately, the function definition package allows us to define a function and only later identify its domain of termination.\nInstead, it makes all the recursion equations conditional on satisfying\nthe function's domain predicate. Here we shall eventually be able\nto show that the predicate is always satisfied.\\<close>\n\ntext\\<open>@{thm [display] ackloop.domintros[no_vars]}\\<close>\ndeclare ackloop.domintros [simp]\n\ntext \\<open>Termination is trivial if the length of the list is less then two.\nThe following lemma is the key to proving termination for longer lists.\\<close>\nlemma \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\nproof (induction m arbitrary: n l)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (Suc m)\n  show ?case\n    using Suc.prems\n    by (induction n arbitrary: l) (simp_all add: Suc)\nqed\n\ntext \\<open>The proof above (which actually is unused) can be expressed concisely as follows.\\<close>\nlemma ackloop_dom_longer:\n  \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\ntext\\<open>This function codifies what @{term ackloop} is designed to do.\nProving the two functions equivalent also shows that @{term ackloop} can be used\nto compute Ackermann's function.\\<close>\nfun acklist :: \"nat list \\<Rightarrow> nat\" where\n  \"acklist (n#m#l) = acklist (ack m n # l)\"\n| \"acklist [m] = m\"\n| \"acklist [] =  0\"\n\ntext\\<open>The induction rule for @{term acklist} is @{thm [display] acklist.induct[no_vars]}.\\<close>\n\nlemma ackloop_dom: \"ackloop_dom l\"\n  by (induction l rule: acklist.induct) (auto simp: ackloop_dom_longer)\n\ntermination ackloop\n  by (simp add: ackloop_dom)\n\ntext\\<open>This result is trivial even by inspection of the function definitions\n(which faithfully follow the definition of Ackermann's function).\nAll that we needed was termination.\\<close>\nlemma ackloop_acklist: \"ackloop l = acklist l\"\n  by (induction l rule: ackloop.induct) auto\n\ntheorem ack: \"ack m n = ackloop [n,m]\"\n  by (simp add: ackloop_acklist)\n\nsubsection \\<open>Example of proving termination using a multiset ordering\\<close>\n\ntext \\<open>This termination proof uses the argument from\nNachum Dershowitz and Zohar Manna. Proving termination with multiset orderings.\nCommunications of the ACM 22 (8) 1979, 465--476.\\<close>\n\ntext\\<open>Setting up the termination proof. Note that Dershowitz had @{term z} as a global variable.\nThe top two stack elements are treated differently from the rest.\\<close>\n\nfun ack_mset :: \"nat list \\<Rightarrow> (nat\\<times>nat) multiset\" where\n  \"ack_mset [] = {#}\"\n| \"ack_mset [x] = {#}\"\n| \"ack_mset (z#y#l) = mset ((y,z) # map (\\<lambda>x. (Suc x, 0)) l)\"\n\nlemma case1: \"ack_mset (Suc n # l) < add_mset (0,n) {# (Suc x, 0). x \\<in># mset l #}\"\nproof (cases l)\n  case (Cons m list)\n  have \"{#(m, Suc n)#} < {#(Suc m, 0)#}\"\n    by auto\n  also have \"\\<dots> \\<le> {#(Suc m, 0), (0,n)#}\"\n    by auto\n  finally show ?thesis  \n    by (simp add: Cons)\nqed auto\n\ntext\\<open>The stack-based version again. We need a fresh copy because \n  we've already proved the termination of @{term ackloop}.\\<close>\n\nfunction Ackloop :: \"nat list \\<Rightarrow> nat\" where\n  \"Ackloop (n # 0 # l)         = Ackloop (Suc n # l)\"\n| \"Ackloop (0 # Suc m # l)     = Ackloop (1 # m # l)\"\n| \"Ackloop (Suc n # Suc m # l) = Ackloop (n # Suc m # m # l)\"\n| \"Ackloop [m] = m\"\n| \"Ackloop [] =  0\"\n  by pat_completeness auto\n\n\ntext \\<open>In each recursive call, the function @{term ack_mset} decreases according to the multiset\nordering.\\<close>\ntermination\n  by (relation \"inv_image {(x,y). x<y} ack_mset\") (auto simp: wf case1)\n\ntext \\<open>Another shortcut compared with before: equivalence follows directly from this lemma.\\<close>\nlemma Ackloop_ack: \"Ackloop (n # m # l) = Ackloop (ack m n # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\ntheorem \"ack m n = Ackloop [n,m]\"\n  by (simp add: Ackloop_ack)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Examples/Ackermann.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8902942333990421, "lm_q1q2_score": 0.7966258917859604}}
{"text": "section \"Weak Integer Compositions\"\n\ntheory Weak_Integer_Compositions\n  imports\n    \"HOL-Combinatorics.Multiset_Permutations\"\n    Common_Lemmas\nbegin\n\nsubsection\"Definition\"\n\ndefinition weak_integer_compositions :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list set\" where\n  \"weak_integer_compositions i l = {xs. length xs = l \\<and> sum_list xs = i}\"\ntext \"Weak integer compositions are similar to integer compositions, with the trade-off that 0 is\n  allowed but the composition must have a fixed length.\"\ntext \"Cardinality: \\<open>binomial (i + n - 1) i\\<close>\"\ntext \"Example: \\<open>weak_integer_compositions 2 2 = {[2,0], [1,1], [0,2]}\\<close>\"\n\nsubsection\"Algorithm\"\n\nfun weak_integer_composition_enum :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list list\" where\n  \"weak_integer_composition_enum i 0 = (if i = 0 then [[]] else [])\"\n| \"weak_integer_composition_enum i (Suc 0) = [[i]]\"\n| \"weak_integer_composition_enum i l =\n  [h#r . h \\<leftarrow> [0..< Suc i], r \\<leftarrow> weak_integer_composition_enum (i-h) (l-1)]\"\n\nsubsection\"Verification\"\n\nsubsubsection\"Correctness\"\n\nlemma weak_integer_composition_enum_length:\n  \"xs \\<in> set (weak_integer_composition_enum i l) \\<Longrightarrow> length xs = l\"\nproof(induct l arbitrary: xs i)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc l)\n  then show ?case by(cases l) auto \nqed\n\nlemma weak_integer_composition_enum_sum_list:\n  \"xs \\<in> set (weak_integer_composition_enum i l) \\<Longrightarrow> sum_list xs = i\"\nproof(induct l arbitrary: xs i)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc l)\n  then show ?case by(cases l) auto \nqed\n  \nlemma weak_integer_composition_enum_head:\n  assumes \"xs \\<in> set (weak_integer_composition_enum (sum_list xs) (length xs))\"\n  shows \"x # xs \\<in> set (weak_integer_composition_enum (x + sum_list xs) (Suc (length xs)))\"\nproof(cases \"length xs\")\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc y)\n\n  (*maybe this should be proven elsewhere*)\n  have 1: \"\\<lbrakk>n \\<in> set xs; 0 < n\\<rbrakk> \\<Longrightarrow> 0 < sum_list xs\" for n\n    using sum_list_eq_0_iff by fast\n\n\n  have 2: \"xs \\<notin> set (weak_integer_composition_enum 0 (Suc y)) \\<Longrightarrow> 0 < sum_list xs\"\n    using Suc assms not_gr0 by fastforce\n\n  have \"x # xs \\<notin> (#) (x + sum_list xs) ` set (weak_integer_composition_enum 0 (Suc y))\n    \\<Longrightarrow> \\<exists>xa\\<in>{0..<x + sum_list xs}. x # xs \\<in> (#) xa ` set (weak_integer_composition_enum (x + sum_list xs - xa) (Suc y))\"\n   unfolding image_def using Suc assms 1 2 by auto\n    \n  from Suc this show ?thesis\n    by auto\nqed\n\nlemma weak_integer_composition_enum_correct_aux:\n  \"xs \\<in> set (weak_integer_composition_enum (sum_list xs) (length xs))\"\n  by (induct xs) (auto simp: weak_integer_composition_enum_head)\n\ntheorem weak_integer_composition_enum_correct:\n  \"set (weak_integer_composition_enum i l) = weak_integer_compositions i l\"\nproof standard\n  show \"set (weak_integer_composition_enum i l) \\<subseteq> weak_integer_compositions i l\"\n    unfolding weak_integer_compositions_def\n    using weak_integer_composition_enum_length weak_integer_composition_enum_sum_list\n    by auto\nnext\n  show \"weak_integer_compositions i l \\<subseteq> set (weak_integer_composition_enum i l)\"\n    unfolding weak_integer_compositions_def\n    using weak_integer_composition_enum_correct_aux by auto\nqed\n\nsubsubsection\"Distinctness\"\n\ntheorem weak_integer_composition_enum_distinct: \"distinct (weak_integer_composition_enum i l)\"\nproof(induct rule: weak_integer_composition_enum.induct)\n  case (1 i)\n  then show ?case\n    by simp\nnext\n  case (2 i)\n  then show ?case \n    by simp\nnext\n  case (3 i l)\n  have \"distinct [h#r . h \\<leftarrow> [0..< Suc i], r \\<leftarrow> weak_integer_composition_enum (i-h) (Suc l)]\"\n    apply(subst Cons_distinct_concat_map_function)\n    using 3 by auto\n  then show ?case by simp\nqed\n\n\nsubsubsection\"Cardinality\"\n\ntext \\<open>The following is a generalization of the binomial coefficient to multisets. Sometimes it\nis called multiset coefficient. Here we call it \"multichoose\" \\cite{stanleyenumerative}.\\<close>\n\ndefinition multichoose:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" (infixl \"multichoose\" 65) where\n  \"n multichoose k = (n + k -1) choose k\"\n\nlemma weak_integer_composition_enum_zero: \"length (weak_integer_composition_enum 0 (Suc n)) = 1\"\n  by(induct n) auto\n\nlemma a_choose_equivalence: \"Suc (\\<Sum>x\\<leftarrow>[0..<k]. n + (k - x) choose (k - x)) = Suc (n + k) choose k\"\nproof -\n  have \"m \\<ge> k \\<Longrightarrow> (\\<Sum>x\\<leftarrow>[0..< Suc k]. m - x choose (k - x)) = Suc m choose k\" for m\n    using sum_choose_diagonal leq_sum_to_sum_list by metis\n  then have 1: \"Suc (\\<Sum>x\\<leftarrow>[0..<k]. (n + k) - x choose (k - x)) = Suc (n + k) choose k\"\n    by simp\n\n  have \"Suc (\\<Sum>x\\<leftarrow>[0..<k]. (n + k) - x choose (k - x)) = Suc (\\<Sum>x\\<leftarrow>[0..<k]. n + (k - x) choose (k - x))\"\n    by (metis (no_types, opaque_lifting) Nat.diff_add_assoc2 add.commute binomial_n_0 diff_is_0_eq' nle_le)\n  \n  then show ?thesis using 1 by simp \nqed\n\nlemma composition_enum_length: \"length (weak_integer_composition_enum i n) = n multichoose i\"\n  unfolding multichoose_def\nproof(induct i n rule: weak_integer_composition_enum.induct)\n  case (1 i)\n  then show ?case by simp\nnext\n  case (2 i)\n  then show ?case by simp\nnext\n  case (3 i n)\n\n  then have \"x \\<in> set [0..< i] \\<Longrightarrow>\n    length (weak_integer_composition_enum (i - x) (Suc n)) = n + (i - x) choose (i - x)\" for x\n    by simp\n\n  then have ev: \"length [h#r . h \\<leftarrow> [0..< i], r \\<leftarrow> weak_integer_composition_enum (i-h) (Suc n)] =\n     (\\<Sum>x\\<leftarrow>[0..< i]. n + (i - x) choose (i - x))\"\n    using length_concat_map_function_sum_list [of\n      \"[0..< i]\"\n      \"\\<lambda>x. (weak_integer_composition_enum (i-x) (Suc n))\"\n      \"\\<lambda>x. n + (i-x) choose (i-x)\"\n      \"\\<lambda>h r. h#r\"\n      ] by simp\n\n  have \"Suc (\\<Sum>x\\<leftarrow>[0..<i]. n + (i - x) choose (i - x)) = Suc (n + i) choose i\"\n    using a_choose_equivalence by simp\n\n  then show ?case using weak_integer_composition_enum_zero ev by auto\nqed\n\ntheorem weak_integer_compositions_cardinality: \"card (weak_integer_compositions n k) = k multichoose n\"\n  using weak_integer_composition_enum_correct weak_integer_composition_enum_distinct composition_enum_length\n  distinct_card by metis\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Combinatorial_Enumeration_Algorithms/Weak_Integer_Compositions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772450055545, "lm_q2_score": 0.9111797166446537, "lm_q1q2_score": 0.7964414564297007}}
{"text": "theory Simp_Demo\nimports Main\nbegin\n\nsection \"How to simplify\"\n\ntext \\<open>No assumption:\\<close>\n\nlemma \"ys @ [] = []\"\napply(simp)\noops (* abandon proof *)\n\ntext \\<open>Simplification in assumption:\\<close>\n\nlemma \"\\<lbrakk> xs @ zs = ys @ xs; [] @ xs = [] @ [] \\<rbrakk> \\<Longrightarrow> ys = zs\"\napply(simp)\ndone\n\ntext \\<open>Using additional rules:\\<close>\n\nlemma \"(a+b)*(a-b) = a*a - b*(b::int)\"\napply(simp add: algebra_simps)\ndone\n\ntext \\<open>Giving a lemma the simp-attribute:\\<close>\n\ndeclare algebra_simps [simp]\n\n\nsubsection \"Rewriting with definitions\"\n\ndefinition sq :: \"nat \\<Rightarrow> nat\" where\n\"sq n = n*n\"\n\nlemma \"sq(n*n) = sq(n)*sq(n)\"\napply(simp add: sq_def) (* Definition of function is implicitly called f_def *)\ndone\n\nsubsection \"Case distinctions\"\n\ntext \\<open>Automatic:\\<close>\n\nlemma \"(A & B) = (if A then B else False)\"\napply(simp)\ndone\n\nlemma \"if A then B else C\"\napply(simp)\noops\n\ntext \\<open>By hand (for case):\\<close>\n\nlemma \"1 \\<le> (case ns of [] \\<Rightarrow> 1 | n#_ \\<Rightarrow> Suc n)\"\napply(simp split: list.split)\ndone\n\nsubsection \"Arithmetic\"\n\ntext \\<open>A bit of linear arithmetic (no multiplication) is automatic:\\<close>\n\nlemma \"\\<lbrakk> (x::nat) \\<le> y+z;  z+x < y \\<rbrakk> \\<Longrightarrow> x < y\"\napply(simp)\ndone\n\n\nsubsection \"Tracing\"\n\nlemma \"rev[x] = []\"\nusing [[simp_trace]] apply(simp)\noops\n\ntext \\<open>Method ``auto'' can be modified almost like ``simp'':\n instead of ``add'' use ``simp add''.\\<close>\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Simp_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8740772450055544, "lm_q1q2_score": 0.7964414443074294}}
{"text": "(*\n  File:    IMO2019_Q1.thy\n  Author:  Manuel Eberl, TU München\n*)\nsection \\<open>Q1\\<close>\ntheory IMO2019_Q1\n  imports Main\nbegin\n\ntext \\<open>\n  Consider a function \\<open>f : \\<int> \\<rightarrow> \\<int>\\<close> that fulfils the functional equation\n  \\<open>f(2a) + 2f(b) = f(f(a+b))\\<close> for all \\<open>a, b \\<in> \\<int>\\<close>.\n\n  Then \\<open>f\\<close> is either identically 0 or of the form \\<open>f(x) = 2x + c\\<close> for some constant \\<open>c \\<in> \\<int>\\<close>.\n\\<close>\n\ncontext\n  fixes f :: \"int \\<Rightarrow> int\" and m :: int\n  assumes f_eq: \"f (2 * a) + 2 * f b = f (f (a + b))\"\n  defines \"m \\<equiv> (f 0 - f (-2)) div 2\"\nbegin\n\ntext \\<open>\n  We first show that \\<open>f\\<close> is affine with slope \\<open>(f(0) - f(-2)) / 2\\<close>.\n  This follows from plugging in \\<open>(0, b)\\<close> and \\<open>(-1, b + 1)\\<close> into the functional equation.\n\\<close>\nlemma f_eq': \"f x = m * x + f 0\"\nproof -\n  have rec: \"f (b + 1) = f b + m\" for b\n    using f_eq[of 0 b] f_eq[of \"-1\" \"b + 1\"] by (simp add: m_def)\n  moreover have \"f (b - 1) = f b - m\" for b\n    using rec[of \"b - 1\"] by simp\n  ultimately show ?thesis\n    by (induction x rule: int_induct[of _ 0]) (auto simp: algebra_simps)\nqed\n\ntext \\<open>\n  This version is better for the simplifier because it prevents it from looping.\n\\<close>\nlemma f_eq'_aux [simp]: \"NO_MATCH 0 x \\<Longrightarrow> f x = m * x + f 0\"\n  by (rule f_eq')\n\ntext \\<open>\n  Plugging in \\<open>(0, 0)\\<close> and \\<open>(0, 1)\\<close>.\n\\<close>\nlemma f_classification: \"(\\<forall>x. f x = 0) \\<or> (\\<forall>x. f x = 2 * x + f 0)\"\n  using f_eq[of 0 0] f_eq[of 0 1] by auto\n\nend\n\ntext \\<open>\n  It is now easy to derive the full characterisation of the functions we considered:\n\\<close>\ntheorem\n  fixes f :: \"int \\<Rightarrow> int\"\n  shows \"(\\<forall>a b. f (2 * a) + 2 * f b = f (f (a + b))) \\<longleftrightarrow>\n           (\\<forall>x. f x = 0) \\<or> (\\<forall>x. f x = 2 * x + f 0)\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  thus ?rhs using f_classification[of f] by blast\nnext\n  assume ?rhs\n  thus ?lhs by smt\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/IMO2019/IMO2019_Q1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7964414389434556}}
{"text": "theory reverse_even\nimports Main\nbegin\ndatatype nat = zero | s nat\ndatatype lst = nil | cons nat lst\n\nfun snoc :: \"lst \\<Rightarrow> nat \\<Rightarrow> lst\" where\n\"snoc nil x = cons x nil\" |\n\"snoc (cons x xs) y = cons x (snoc xs y)\"\n\nfun reverse :: \"lst \\<Rightarrow> lst\" where\n\"reverse nil = nil\" |\n\"reverse (cons x xs) = snoc (reverse xs) x\"\n\nfun reverse_n :: \"nat \\<Rightarrow> lst \\<Rightarrow> lst\" where\n\"reverse_n zero xs = xs\" |\n\"reverse_n (s n) xs = reverse (reverse_n n xs)\"\n \nfun even_fn :: \"nat \\<Rightarrow> bool\" where\n\"even_fn zero = True\" |\n\"even_fn (s zero) = False\" |\n\"even_fn (s (s n)) = even_fn n\"\n\ninductive even :: \"nat \\<Rightarrow> bool\" where\n\"even zero\" |\n\"even n \\<Longrightarrow> even (s (s n))\"\n\nlemma reverse_snoc: \"\\<And>xs. \\<And>x. reverse (snoc xs x) = cons x (reverse xs)\"\nproof -\nfix xs\nshow \"\\<And>x. reverse (snoc xs x) = cons x (reverse xs)\"\nproof(induct xs)\ncase nil\nthen show ?case by simp\nnext\ncase (cons x1 xs)\nthen show ?case by simp\nqed\nqed\n\nlemma reverse_involution: \"\\<And>xs. reverse (reverse xs) = xs\" proof -\nfix xs\nshow \"reverse (reverse xs) = xs\" proof(induct xs)\ncase nil\nthen show ?case by simp\nnext\ncase (cons x1 xs)\nthen show ?case by (simp add: reverse_snoc)\nqed\nqed\n\ntheorem \"\\<And>n xs. (even n \\<Longrightarrow> reverse_n n xs = xs)\" proof (rule even.induct)\nshow \"\\<And>n xs. reverse_even.even n \\<Longrightarrow> reverse_even.even n\" by simp\nnext\nshow \"\\<And>n xs. reverse_even.even n \\<Longrightarrow> reverse_n zero xs = xs\" by simp\nnext\nshow \n\"\\<And>n xs na. \nreverse_even.even n\n\\<Longrightarrow> reverse_even.even na \n\\<Longrightarrow> reverse_n na xs = xs \n\\<Longrightarrow> reverse_n (s (s na)) xs = xs\" by (simp add: reverse_involution)\nqed\n\ntheorem \"\\<And>n xs. (even_fn n \\<longrightarrow> reverse_n n xs = xs)\" proof (rule even_fn.induct)\nshow \"\\<And>n xs. even_fn n \\<longrightarrow> reverse_n zero xs = xs\" by simp\nnext\nshow \"\\<And>n xs. even_fn (s zero) \\<longrightarrow> reverse_n (s zero) xs = xs\" by simp\nnext\nshow \n\"\\<And>n xs na. even_fn na \n\\<longrightarrow> reverse_n na xs = xs \n\\<Longrightarrow> even_fn (s (s na)) \n\\<longrightarrow> reverse_n (s (s na)) xs = xs\" by (simp add: reverse_involution)\nqed\n\nend", "meta": {"author": "fachammer", "repo": "induction_project", "sha": "7ed850794a51fe4601f3fa518d9a3c8ace9283ef", "save_path": "github-repos/isabelle/fachammer-induction_project", "path": "github-repos/isabelle/fachammer-induction_project/induction_project-7ed850794a51fe4601f3fa518d9a3c8ace9283ef/isabelle/dty/list/crafted_assorted/isabelle/reverse_even.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8558511543206819, "lm_q1q2_score": 0.7963337687110827}}
{"text": "theory Ex1_2 \nimports Main \nbegin \n\n\n\nprimrec replace :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where \n\"replace _  _ [] = []\"|\n\"replace x  y (z # zs) = (if z = y then x else z) # replace x y zs\"\n\ntheorem helper : \"replace x y (ls @ xs) = replace x y ls @ replace x y xs\"\nproof (induct ls)\n  case Nil \n  show ?case by simp\n next \n  fix a ls \n  assume \"replace x y (ls @ xs) = replace x y ls @ replace x y xs\"\n  thus \"replace x y ((a # ls) @ xs) = replace x y (a # ls) @ replace x y xs \" by simp\nqed\n\ntheorem \"rev(replace x y zs) = replace x y (rev zs)\"\nproof (induct zs)\n  case Nil \n  show ?case by simp\n next \n  fix a zs \n  assume \"rev (replace x y zs) = replace x y (rev zs)\"\n  thus \" rev (replace x y (a # zs)) = replace x y (rev (a # zs)) \" by (simp add : helper)\nqed\n\n\n  \n  \n\n", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions", "sha": "1a71e30f3369d34c4691a4d010257b8c8afc566c", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions/ExerciseSolutions-1a71e30f3369d34c4691a4d010257b8c8afc566c/src/isabelle/Lists/Ex1_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7961834993301606}}
{"text": "section \\<open>Normal Polynomials\\<close>\n\ntheory Normal_Poly\n  imports \"RRI_Misc\"\nbegin\n\ntext \\<open>\nHere we define normal polynomials as defined in\n  Basu, S., Pollack, R., Roy, M.-F.: Algorithms in Real Algebraic Geometry. \n  Springer Berlin Heidelberg, Berlin, Heidelberg (2016).\n\\<close>\n\ndefinition normal_poly :: \"('a::{comm_ring_1,ord}) poly \\<Rightarrow> bool\" where\n\"normal_poly p \\<equiv>\n  (p \\<noteq> 0) \\<and>\n  (\\<forall> i. 0 \\<le> coeff p i) \\<and>\n  (\\<forall> i. coeff p i * coeff p (i+2) \\<le> (coeff p (i+1))^2) \\<and>\n  (\\<forall> i j k. i \\<le> j \\<longrightarrow> j \\<le> k \\<longrightarrow> 0 < coeff p i \n      \\<longrightarrow> 0 < coeff p k \\<longrightarrow> 0 < coeff p j)\"\n\nlemma normal_non_zero: \"normal_poly p \\<Longrightarrow> p \\<noteq> 0\" \n  using normal_poly_def by blast\n\nlemma normal_coeff_nonneg: \"normal_poly p \\<Longrightarrow> 0 \\<le> coeff p i\" \n  using normal_poly_def by metis\n\nlemma normal_poly_coeff_mult: \n    \"normal_poly p \\<Longrightarrow> coeff p i * coeff p (i+2) \\<le> (coeff p (i+1))^2\" \n  using normal_poly_def by blast\n\nlemma normal_poly_pos_interval: \n    \"normal_poly p \\<Longrightarrow> i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> 0 < coeff p i \\<Longrightarrow> 0 < coeff p k \n      \\<Longrightarrow> 0 < coeff p j\" \n  using normal_poly_def by blast\n\nlemma normal_polyI:\n  assumes \"(p \\<noteq> 0)\"\n      and \"(\\<And> i. 0 \\<le> coeff p i)\"\n      and \"(\\<And> i. coeff p i * coeff p (i+2) \\<le> (coeff p (i+1))^2)\"\n      and \"(\\<And> i j k. i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> 0 < coeff p i \\<Longrightarrow> 0 < coeff p k \\<Longrightarrow> 0 < coeff p j)\"\n    shows \"normal_poly p\"\n  using assms by (force simp: normal_poly_def)\n\nlemma linear_normal_iff: \n  fixes x::real \n  shows \"normal_poly [:-x, 1:] \\<longleftrightarrow> x \\<le> 0\"\nproof\n  assume \"normal_poly [:-x, 1:]\"\n  thus \"x \\<le> 0\" using normal_coeff_nonneg[of \"[:-x, 1:]\" 0] by auto\nnext\n  assume \"x \\<le> 0\"\n  then have \"0 \\<le> coeff [:- x, 1:] i\" for i\n    by (cases i) (simp_all add: pCons_one)\n  moreover have \"0 < coeff [:- x, 1:] j\"\n    if \"i \\<le> j\" \"j \\<le> k\" \"0 < coeff [:- x, 1:] i\" \n        \"0 < coeff [:- x, 1:] k\" for i j k\n    apply (cases \"k=0 \\<or> i=0\")\n    subgoal using that \n      by (smt (z3) bot_nat_0.extremum_uniqueI degree_pCons_eq_if \n          le_antisym le_degree not_less_eq_eq)\n    subgoal using that \n      by (smt (z3) One_nat_def degree_pCons_eq_if le_degree less_one\n          not_le one_neq_zero pCons_one verit_la_disequality)\n    done\n  ultimately show \"normal_poly [:-x, 1:]\"\n    unfolding normal_poly_def by auto\nqed\n\nlemma quadratic_normal_iff: \n  fixes z::complex \n  shows \"normal_poly [:(cmod z)\\<^sup>2, -2*Re z, 1:] \n          \\<longleftrightarrow> Re z \\<le> 0 \\<and> 4*(Re z)^2 \\<ge> (cmod z)^2\"\nproof\n  assume \"normal_poly [:(cmod z)\\<^sup>2, - 2 * Re z, 1:]\"\n  hence \"-2*Re z \\<ge> 0 \\<and> (cmod z)^2 \\<ge> 0 \\<and> (-2*Re z)^2 \\<ge> (cmod z)^2\"\n    using normal_coeff_nonneg[of _ 1] normal_poly_coeff_mult[of _ 0] \n    by fastforce\n  thus \"Re z \\<le> 0 \\<and> 4*(Re z)^2 \\<ge> (cmod z)^2\"\n    by auto\nnext\n  assume asm:\"Re z \\<le> 0 \\<and> 4*(Re z)^2 \\<ge> (cmod z)^2\"\n  define P where \"P=[:(cmod z)\\<^sup>2, - 2 * Re z, 1:]\"\n\n  have \"0 \\<le> coeff P i\" for i \n    unfolding P_def using asm\n    apply (cases \"i=0\\<or>i=1\\<or>i=2\")\n    by (auto simp:numeral_2_eq_2 coeff_eq_0)\n  moreover have \"coeff P i * coeff P (i + 2) \\<le> (coeff P (i + 1))\\<^sup>2\" for i\n    apply (cases \"i=0\\<or>i=1\\<or>i=2\")\n    using asm \n    unfolding P_def by (auto simp:coeff_eq_0)\n  moreover have \"0 < coeff P j\"\n    if \"0 < coeff P k\" \"0 < coeff P i\" \"j \\<le> k\" \"i \\<le> j\"\n    for i j k\n    using that unfolding P_def \n    apply (cases \"k=0 \\<or> k=1 \\<or> k=2\")\n    subgoal using asm\n      by (smt (z3) One_nat_def Suc_1 bot_nat_0.extremum_uniqueI \n          coeff_pCons_0 coeff_pCons_Suc le_Suc_eq \n          zero_less_power2)\n    subgoal by (auto simp:coeff_eq_0)\n    done\n  moreover have \"P\\<noteq>0\" unfolding P_def by auto\n  ultimately show \"normal_poly P\"\n    unfolding normal_poly_def by blast\nqed\n\nlemma normal_of_no_zero_root: \n  fixes f::\"real poly\" \n  assumes hzero: \"poly f 0 \\<noteq> 0\" and hdeg: \"i \\<le> degree f\" \n    and hnorm: \"normal_poly f\"\n  shows \"0 < coeff f i\"\nproof -\n  have \"coeff f 0 > 0\" using hzero normal_coeff_nonneg[OF hnorm]\n    by (metis eq_iff not_le_imp_less poly_0_coeff_0)\n  moreover have \"coeff f (degree f) > 0\" using normal_coeff_nonneg[OF hnorm] normal_non_zero[OF hnorm]\n    by (meson dual_order.irrefl eq_iff eq_zero_or_degree_less not_le_imp_less)\n  moreover have \"0 \\<le> i\" by simp\n  ultimately show \"0 < coeff f i\" using hdeg normal_poly_pos_interval[OF hnorm] by blast\nqed\n\nlemma normal_divide_x: \n  fixes f::\"real poly\" \n  assumes hnorm: \"normal_poly (f*[:0,1:])\"\n  shows \"normal_poly f\"\nproof (rule normal_polyI)\n  show \"f \\<noteq> 0\"\n    using normal_non_zero[OF hnorm] by auto\nnext\n  fix i\n  show \"0 \\<le> coeff f i\"\n    using normal_coeff_nonneg[OF hnorm, of \"Suc i\"] by (simp add: coeff_pCons)\nnext\n  fix i\n  show \"coeff f i * coeff f (i + 2) \\<le> (coeff f (i + 1))\\<^sup>2\"\n    using normal_poly_coeff_mult[OF hnorm, of \"Suc i\"] by (simp add: coeff_pCons)\nnext\n  fix i j k\n  show \"i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> 0 < coeff f i \\<Longrightarrow> 0 < coeff f k \\<Longrightarrow> 0 < coeff f j\"\n    using normal_poly_pos_interval[of _ \"Suc i\" \"Suc j\" \"Suc k\", OF hnorm]\n    by (simp add: coeff_pCons)\nqed\n\nlemma normal_mult_x: \n  fixes f::\"real poly\" \n  assumes hnorm: \"normal_poly f\"\n  shows \"normal_poly (f * [:0, 1:])\"\nproof (rule normal_polyI)\n  show \"f * [:0, 1:] \\<noteq> 0\"\n    using normal_non_zero[OF hnorm] by auto\nnext\n  fix i\n  show \"0 \\<le> coeff (f * [:0, 1:]) i\"\n    using normal_coeff_nonneg[OF hnorm, of \"i-1\"] by (cases i, auto simp: coeff_pCons)\nnext\n  fix i\n  show \"coeff (f * [:0, 1:]) i * coeff (f * [:0, 1:]) (i + 2) \\<le> (coeff (f * [:0, 1:]) (i + 1))\\<^sup>2\"\n    using normal_poly_coeff_mult[OF hnorm, of \"i-1\"] by (cases i, auto simp: coeff_pCons)\nnext\n  fix i j k\n  show \"i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> 0 < coeff (f * [:0, 1:]) i \\<Longrightarrow> 0 < coeff (f * [:0, 1:]) k \\<Longrightarrow> 0 < coeff (f * [:0, 1:]) j\"\n    using normal_poly_pos_interval[of _ \"i-1\" \"j-1\" \"k-1\", OF hnorm]\n    apply (cases i, force)\n    apply (cases j, force)\n    apply (cases k, force)\n    by (auto simp: coeff_pCons)\nqed\n\nlemma normal_poly_general_coeff_mult: \n  fixes f::\"real poly\" \n  assumes \"normal_poly f\" and \"h \\<le> j\"\n  shows \"coeff f (h+1) * coeff f (j+1) \\<ge> coeff f h * coeff f (j+2)\"\nusing assms proof (induction j)\n  case 0\n  then show ?case\n    using normal_poly_coeff_mult by (auto simp: power2_eq_square)[1]\nnext\n  case (Suc j)\n  then show ?case\n  proof (cases \"h = Suc j\")\n    assume \"h = Suc j\" \"normal_poly f\"\n    thus ?thesis\n      using normal_poly_coeff_mult by (auto simp: power2_eq_square)\n  next\n    assume \"(normal_poly f \\<Longrightarrow>\n       h \\<le> j \\<Longrightarrow> coeff f h * coeff f (j + 2) \\<le> coeff f (h + 1) * coeff f (j + 1))\"\n      \"normal_poly f\" and h: \"h \\<le> Suc j\" \"h \\<noteq> Suc j\"\n    hence IH: \"coeff f h * coeff f (j + 2) \\<le> coeff f (h + 1) * coeff f (j + 1)\"\n      by linarith\n    show ?thesis\n    proof (cases \"coeff f (Suc j + 1) = 0\", cases \"coeff f (Suc j + 2) = 0\")\n      show \"coeff f (Suc j + 1) = 0 \\<Longrightarrow> coeff f (Suc j + 2) = 0 \\<Longrightarrow>\n        coeff f h * coeff f (Suc j + 2) \\<le> coeff f (h + 1) * coeff f (Suc j + 1)\"\n        by (metis assms(1) mult_zero_right normal_coeff_nonneg)\n    next\n      assume 1: \"coeff f (Suc j + 1) = 0\" \"coeff f (Suc j + 2) \\<noteq> 0\"\n      hence \"coeff f (Suc j + 2) > 0\" \"\\<not>coeff f (Suc j + 1) > 0\" \n        using normal_coeff_nonneg[of f \"Suc j + 2\"] assms(1) by auto\n      hence \"coeff f h > 0 \\<Longrightarrow> False\"\n        using normal_poly_pos_interval[of f h \"Suc j + 1\" \"Suc j + 2\"] assms(1) h by force\n      hence \"coeff f h = 0\"\n        using normal_coeff_nonneg[OF assms(1)] less_eq_real_def by auto\n      thus \"coeff f h * coeff f (Suc j + 2) \\<le> coeff f (h + 1) * coeff f (Suc j + 1)\"\n        using 1 by fastforce\n    next\n      assume 1: \"coeff f (Suc j + 1) \\<noteq> 0\"\n      show \"coeff f h * coeff f (Suc j + 2) \\<le> coeff f (h + 1) * coeff f (Suc j + 1)\"\n      proof (cases \"coeff f (Suc j) = 0\")\n        assume 2: \"coeff f (Suc j) = 0\"\n        hence \"coeff f (Suc j + 1) > 0\" \"\\<not>coeff f (Suc j) > 0\" \n          using normal_coeff_nonneg[of f \"Suc j + 1\"] assms(1) 1 by auto\n        hence \"coeff f h > 0 \\<Longrightarrow> False\"\n          using normal_poly_pos_interval[of f h \"Suc j\" \"Suc j + 1\"] assms(1) h by force\n        hence \"coeff f h = 0\"\n          using normal_coeff_nonneg[OF assms(1)] less_eq_real_def by auto\n        thus \"coeff f h * coeff f (Suc j + 2) \\<le> coeff f (h + 1) * coeff f (Suc j + 1)\"\n          by (simp add: assms(1) normal_coeff_nonneg)\n      next\n        assume 2: \"coeff f (Suc j) \\<noteq> 0\"\n        from normal_poly_coeff_mult[OF assms(1), of \"Suc j\"] normal_coeff_nonneg[OF assms(1), of \"Suc j\"]\n          normal_coeff_nonneg[OF assms(1), of \"Suc (Suc j)\"] 1 2 \n        have 3: \"coeff f (Suc j + 1) / coeff f (Suc j) \\<ge> coeff f (Suc j + 2) / coeff f (Suc j + 1)\"\n          by (auto simp: power2_eq_square divide_simps algebra_simps)\n        have \"(coeff f h * coeff f (j + 2)) * (coeff f (Suc j + 2) / coeff f (Suc j + 1)) \\<le> (coeff f (h + 1) * coeff f (j + 1)) * (coeff f (Suc j + 1) / coeff f (Suc j))\"\n          apply (rule mult_mono[OF IH])\n          using 3 by (simp_all add: assms(1) normal_coeff_nonneg)\n        thus \"coeff f h * coeff f (Suc j + 2) \\<le> coeff f (h + 1) * coeff f (Suc j + 1)\"\n          using 1 2 by fastforce\n      qed\n    qed\n  qed\nqed\n\nlemma normal_mult: \n  fixes f g::\"real poly\"\n  assumes hf: \"normal_poly f\" and hg: \"normal_poly g\"\n  defines \"df \\<equiv> degree f\" and \"dg \\<equiv> degree g\"\n  shows \"normal_poly (f*g)\"\nusing df_def hf proof (induction df arbitrary: f)\ntext \\<open>We shall first show that without loss of generality we may assume \\<open>poly f 0 \\<noteq> 0\\<close>,\n      this is done by induction on the degree, if 0 is a root then we derive the result from \\<open>f/[:0,1:]\\<close>.\\<close>\n  fix f::\"real poly\" fix i::nat\n  assume \"0 = degree f\" and hf: \"normal_poly f\"\n  then obtain a where \"f = [:a:]\" using degree_0_iff by auto\n  then show \"normal_poly (f*g)\"\n    apply (subst normal_polyI)\n    subgoal using normal_non_zero[OF hf] normal_non_zero[OF hg] by auto\n    subgoal \n      using normal_coeff_nonneg[of _ 0, OF hf] normal_coeff_nonneg[OF hg] \n      by simp\n    subgoal \n      using normal_coeff_nonneg[of _ 0, OF hf] normal_poly_coeff_mult[OF hg] \n      by (auto simp: algebra_simps power2_eq_square mult_left_mono)[1]\n    subgoal \n      using normal_non_zero[OF hf] normal_coeff_nonneg[of _ 0, OF hf] normal_poly_pos_interval[OF hg]\n      by (simp add: zero_less_mult_iff)\n    subgoal by simp\n    done\nnext\n  case (Suc df)\n  then show ?case\n  proof (cases \"poly f 0 = 0\")\n    assume \"poly f 0 = 0\" and hf:\"normal_poly f\"\n    moreover then obtain f' where hdiv: \"f = f'*[:0,1:]\"\n      by (smt (verit) dvdE mult.commute poly_eq_0_iff_dvd) \n    ultimately have hf': \"normal_poly f'\" using normal_divide_x by blast\n    assume \"Suc df = degree f\"\n    hence \"degree f' = df\" using hdiv normal_non_zero[OF hf'] by (auto simp: degree_mult_eq)\n    moreover assume \"\\<And>f. df = degree f \\<Longrightarrow> normal_poly f \\<Longrightarrow> normal_poly (f * g)\"\n    ultimately have \"normal_poly (f'*g)\" using hf' by blast\n    thus \"normal_poly (f*g)\" using hdiv normal_mult_x by fastforce\n  next\n    assume hf: \"normal_poly f\" and hf0: \"poly f 0 \\<noteq> 0\"\n    define dg where \"dg \\<equiv> degree g\"\n    show \"normal_poly (f * g)\"\n    using dg_def hg proof (induction dg arbitrary: g)\n      text \\<open>Similarly we may assume \\<open>poly g 0 \\<noteq> 0\\<close>.\\<close>\n      fix g::\"real poly\" fix i::nat\n      assume \"0 = degree g\" and hg: \"normal_poly g\"\n      then obtain a where \"g = [:a:]\" using degree_0_iff by auto\n      then show \"normal_poly (f*g)\"\n        apply (subst normal_polyI)\n        subgoal \n          using normal_non_zero[OF hg] normal_non_zero[OF hf] by auto\n        subgoal \n          using normal_coeff_nonneg[of _ 0, OF hg] normal_coeff_nonneg[OF hf] \n          by simp\n        subgoal \n          using normal_coeff_nonneg[of _ 0, OF hg] normal_poly_coeff_mult[OF hf] \n          by (auto simp: algebra_simps power2_eq_square mult_left_mono)\n        subgoal \n          using normal_non_zero[OF hf] normal_coeff_nonneg[of _ 0, OF hg] \n            normal_poly_pos_interval[OF hf]\n          by (simp add: zero_less_mult_iff)\n        by simp\n    next\n      case (Suc dg)\n      then show ?case\n      proof (cases \"poly g 0 = 0\")\n        assume \"poly g 0 = 0\" and hg:\"normal_poly g\"\n        moreover then obtain g' where hdiv: \"g = g'*[:0,1:]\"\n          by (smt (verit) dvdE mult.commute poly_eq_0_iff_dvd) \n        ultimately have hg': \"normal_poly g'\" using normal_divide_x by blast\n        assume \"Suc dg = degree g\"\n        hence \"degree g' = dg\" using hdiv normal_non_zero[OF hg'] by (auto simp: degree_mult_eq)\n        moreover assume \"\\<And>g. dg = degree g \\<Longrightarrow> normal_poly g \\<Longrightarrow> normal_poly (f * g)\"\n        ultimately have \"normal_poly (f*g')\" using hg' by blast\n        thus \"normal_poly (f*g)\" using hdiv normal_mult_x by fastforce\n      next\n        text \\<open>It now remains to show that $(fg)_i \\geq 0$. This follows by decomposing $\\{(h, j) \\in\n              \\mathbf{Z}^2 | h > j\\} = \\{(h, j) \\in \\mathbf{Z}^2 | h \\leq j\\} \\cup \\{(h, h - 1) \\in \n              \\mathbf{Z}^2 | h \\in \\mathbf{Z}\\}$.\n              Note in order to avoid working with infinite sums over integers all these sets are\n              bounded, which adds some complexity compared to the proof of lemma 2.55 in\n              Basu, S., Pollack, R., Roy, M.-F.: Algorithms in Real Algebraic Geometry.\n              Springer Berlin Heidelberg, Berlin, Heidelberg (2016).\\<close>\n        assume hg0: \"poly g 0 \\<noteq> 0\" and hg: \"normal_poly g\"\n        have \"f * g \\<noteq> 0\" using hf hg by (simp add: normal_non_zero Suc.prems)\n        moreover have \"\\<And>i. coeff (f*g) i \\<ge> 0\"\n          apply (subst coeff_mult, rule sum_nonneg, rule mult_nonneg_nonneg)\n          using normal_coeff_nonneg[OF hf] normal_coeff_nonneg[OF hg] by auto\n        moreover have \"\n          coeff (f*g) i * coeff (f*g) (i+2) \\<le> (coeff (f*g) (i+1))^2\" for i\n        proof -\n\n          text \\<open>$(fg)_{i+1}^2 - (fg)_i(fg)_{i+2} = \\left(\\sum_x f_xg_{i+1-x}\\right)^2 - \n                \\left(\\sum_x f_xg_{i+2-x}\\right)\\left(\\sum_x f_xg_{i-x}\\right)$\\<close>\n          have \"(coeff (f*g) (i+1))^2 - coeff (f*g) i * coeff (f*g) (i+2) = \n              (\\<Sum>x\\<le>i+1. coeff f x * coeff g (i + 1 - x)) *\n              (\\<Sum>x\\<le>i+1. coeff f x * coeff g (i + 1 - x)) -\n              (\\<Sum>x\\<le>i+2. coeff f x * coeff g (i + 2 - x)) *\n              (\\<Sum>x\\<le>i. coeff f x * coeff g (i - x))\"\n            by (auto simp: coeff_mult power2_eq_square algebra_simps)\n          \n          text \\<open>$\\dots = \\sum_{x, y} f_xg_{i+1-x}f_yg_{i+1-y} - \\sum_{x, y} f_xg_{i+2-x}f_yg_{i-y}$\\<close>\n          also have \"... =\n              (\\<Sum>x\\<le>i+1. \\<Sum>y\\<le>i+1. coeff f x * coeff g (i + 1 - x) *\n                                  coeff f y * coeff g (i + 1 - y)) -\n              (\\<Sum>x\\<le>i+2. \\<Sum>y\\<le>i. coeff f x * coeff g (i + 2 - x) *\n                                coeff f y * coeff g (i - y))\"\n            by (subst sum_product, subst sum_product, auto simp: algebra_simps)\n\n          text \\<open>$\\dots = \\sum_{h \\leq j} f_hg_{i+1-h}f_jg_{i+1-j} + \\sum_{h>j} f_hg_{i+1-h}f_jg_{i+1-j}\n                       - \\sum_{h \\leq j} f_hg_{i+2-h}f_jg_{i-j} - \\sum_{h>j} f_hg_{i+2-h}f_jg_{i-j}$\\<close>\n          also have \"... =\n              (\\<Sum>(h, j)\\<in>{(h, j). i+1 \\<ge> j \\<and> j \\<ge> h}. \n                coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j)) +\n              (\\<Sum>(h, j)\\<in>{(h, j). i+1 \\<ge> h \\<and> h > j}. \n                coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j)) -\n             ((\\<Sum>(h, j)\\<in>{(h, j). i \\<ge> j \\<and> j \\<ge> h}. \n                coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j)) +\n              (\\<Sum>(h, j)\\<in>{(h, j). i + 2 \\<ge> h \\<and> h > j \\<and> i \\<ge> j}.\n                coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j)))\"\n          proof -\n            have \"(\\<Sum>x\\<le>i + 1. \\<Sum>y\\<le>i + 1. coeff f x * coeff g (i + 1 - x) * coeff f y * coeff g (i + 1 - y)) =\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j}.\n                 coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j)) +\n              (\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 1 \\<and> j < h}.\n                 coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j))\"\n            proof (subst sum.union_disjoint[symmetric])\n              have H:\"{(h, j). j \\<le> i + 1 \\<and> h \\<le> j} \\<subseteq> {..i+1} \\<times> {..i+1}\"\n                     \"{(h, j). h \\<le> i + 1 \\<and> j < h} \\<subseteq> {..i+1} \\<times> {..i+1}\"\n                     \"finite ({..i+1} \\<times> {..i+1})\"\n                by (fastforce, fastforce, fastforce)\n              show \"finite {(h, j). j \\<le> i + 1 \\<and> h \\<le> j}\"\n                apply (rule finite_subset) using H by (blast, blast)\n              show \"finite {(h, j). h \\<le> i + 1 \\<and> j < h}\"\n                apply (rule finite_subset) using H by (blast, blast)\n              show \"{(h, j). j \\<le> i + 1 \\<and> h \\<le> j} \\<inter> {(h, j). h \\<le> i + 1 \\<and> j < h} = {}\"\n                by fastforce\n              show \"(\\<Sum>x\\<le>i + 1. \\<Sum>y\\<le>i + 1. coeff f x * coeff g (i + 1 - x) * coeff f y * coeff g (i + 1 - y)) =\n                  (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j} \\<union> {(h, j). h \\<le> i + 1 \\<and> j < h}.\n                    coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j))\"\n                apply (subst sum.cartesian_product, rule sum.cong)\n                apply force by blast\n            qed\n            moreover have \"(\\<Sum>x\\<le>i + 2. \\<Sum>y\\<le>i. coeff f x * coeff g (i + 2 - x) * coeff f y * coeff g (i - y)) =\n               (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                  coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j)) +\n               (\\<Sum>(h, j)\\<in>{(h, j). i + 2 \\<ge> h \\<and> h > j \\<and> i \\<ge> j}.\n                  coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j))\"\n            proof (subst sum.union_disjoint[symmetric])\n              have H:\"{(h, j). j \\<le> i \\<and> h \\<le> j} \\<subseteq> {..i+2} \\<times> {..i}\"\n                     \"{(h, j). i + 2 \\<ge> h \\<and> h > j \\<and> i \\<ge> j} \\<subseteq> {..i+2} \\<times> {..i}\"\n                     \"finite ({..i+2} \\<times> {..i})\"\n                by (fastforce, fastforce, fastforce)\n              show \"finite {(h, j). j \\<le> i \\<and> h \\<le> j}\"\n                apply (rule finite_subset) using H by (blast, blast)\n              show \"finite {(h, j). i + 2 \\<ge> h \\<and> h > j \\<and> i \\<ge> j}\"\n                apply (rule finite_subset) using H by (blast, blast)\n              show \"{(h, j). j \\<le> i \\<and> h \\<le> j} \\<inter> {(h, j). i + 2 \\<ge> h \\<and> h > j \\<and> i \\<ge> j} = {}\"\n                by fastforce\n              show \"(\\<Sum>x\\<le>i + 2. \\<Sum>y\\<le>i. coeff f x * coeff g (i + 2 - x) * coeff f y * coeff g (i - y)) =\n                  (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j} \\<union> {(h, j). i + 2 \\<ge> h \\<and> h > j \\<and> i \\<ge> j}.\n                     coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j))\"\n                apply (subst sum.cartesian_product, rule sum.cong)\n                apply force by blast\n            qed\n            ultimately show ?thesis by presburger\n          qed\n\n          text \\<open>$\\dots = \\sum_{h \\leq j} f_hg_{i+1-h}f_jg_{i+1-j} + \\sum_{h \\leq j} f_{j+1}g_{i-j}f_{h-2}g_{i+2-h} \n                       + \\sum_h f_hg_{i+1-h}f_{h-1}g_{i+2-h} - \\sum_{h \\leq j} f_hg_{i+2-h}f_jg_{i-j}\n                       - \\sum_{h \\leq j} f_{j+1}g_{i+1-j}f_{h-2}g_{i+1-h} - \\sum_h f_hg_{i+2-h}f_{h-1}g_{i+1-h}$\\<close>\n          also have \"... =\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j}.\n                 coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j)) +\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                 coeff f (j+1) * coeff g (i - j) * coeff f (h-1) * coeff g (i + 2 - h)) +\n              (\\<Sum>h\\<in>{1..i+1}.\n                 coeff f h * coeff g (i + 1 - h) * coeff f (h-1) * coeff g (i + 2 - h)) -\n              ((\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                  coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j)) +\n               (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                  coeff f (j+1) * coeff g (i + 1 - j) * coeff f (h-1) * coeff g (i + 1 - h)) +\n               (\\<Sum>h\\<in>{1..i+1}.\n                  coeff f h * coeff g (i + 2 - h) * coeff f (h-1) * coeff g (i + 1 - h)))\"\n          proof -\n            have \"(\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 1 \\<and> j < h}.\n                   coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j)) = \n                  (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                   coeff f (j + 1) * coeff g (i - j) * coeff f (h - 1) * coeff g (i + 2 - h)) +\n                  (\\<Sum>h = 1..i + 1. coeff f h * coeff g (i + 1 - h) * coeff f (h - 1) * coeff g (i + 2 - h))\"\n            proof -\n              have 1: \"(\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                     coeff f (j + 1) * coeff g (i - j) * coeff f (h - 1) * coeff g (i + 2 - h)) =\n                    (\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}.\n                     coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j))\"\n              proof (rule sum.reindex_cong)\n                show \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h} = (\\<lambda>(h, j). (j+1, h-1)) ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\"\n                proof\n                  show \"(\\<lambda>(h, j). (j + 1, h - 1)) ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1} \\<subseteq> {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}\"\n                    by fastforce\n                  show \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h} \\<subseteq> (\\<lambda>(h, j). (j + 1, h - 1)) ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\"\n                  proof\n                    fix x\n                    assume \"x \\<in> {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}\"\n                    then obtain h j where \"x = (h, j)\" \"j \\<le> i\" \"h \\<le> j\" \"0 < h\" by blast\n                    hence \"j + 1 \\<le> i + 1 \\<and> h - 1 < j + 1 \\<and> j + 1 \\<noteq> h - 1 + 1 \\<and> x = ((h - 1) + 1, (j + 1) - 1)\"\n                      by auto\n                    thus \"x \\<in> (\\<lambda>(h, j). (j + 1, h - 1)) ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\"\n                      by (auto simp: image_iff)\n                  qed\n                qed\n                show \"inj_on (\\<lambda>(h, j). (j + 1, h - 1)) {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\"\n                proof\n                  fix x y::\"nat\\<times>nat\"\n                  assume \"x \\<in> {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\" \"y \\<in> {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\"\n                  thus \"(case x of (h, j) \\<Rightarrow> (j + 1, h - 1)) = (case y of (h, j) \\<Rightarrow> (j + 1, h - 1)) \\<Longrightarrow> x = y\"\n                    by auto\n                qed\n                show \"\\<And>x. x \\<in> {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1} \\<Longrightarrow>\n                 (case case x of (h, j) \\<Rightarrow> (j + 1, h - 1) of\n                  (h, j) \\<Rightarrow> coeff f (j + 1) * coeff g (i - j) * coeff f (h - 1) * coeff g (i + 2 - h)) =\n                 (case x of (h, j) \\<Rightarrow> coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j))\"\n                  by fastforce\n              qed\n              have 2: \"(\\<Sum>h = 1..i + 1. coeff f h * coeff g (i + 1 - h) * coeff f (h - 1) * coeff g (i + 2 - h)) =\n                    (\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}.\n                     coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j))\"\n              proof (rule sum.reindex_cong)\n                show \"{1..i + 1} = fst ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                proof\n                  show \"{1..i + 1} \\<subseteq> fst ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                  proof\n                    fix x\n                    assume \"x \\<in> {1..i + 1}\"\n                    hence \"x \\<le> i + 1 \\<and> x - 1 < x \\<and> x = x - 1 + 1 \\<and> x = fst (x, x-1)\"\n                      by auto\n                    thus \"x \\<in> fst ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                      by blast\n                  qed\n                  show \"fst ` {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1} \\<subseteq> {1..i + 1}\"\n                    by force\n                qed\n                show \"inj_on fst {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                proof\n                  fix x y\n                  assume \"x \\<in> {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                         \"y \\<in> {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                  hence \"x = (fst x, fst x - 1)\" \"y = (fst y, fst y - 1)\" \"fst x > 0\" \"fst y > 0\"\n                    by auto\n                  thus \"fst x = fst y \\<Longrightarrow> x = y\" by presburger\n                qed\n                show \"\\<And>x. x \\<in> {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1} \\<Longrightarrow>\n                   coeff f (fst x) * coeff g (i + 1 - fst x) * coeff f (fst x - 1) * coeff g (i + 2 - fst x) =\n                   (case x of (h, j) \\<Rightarrow> coeff f h * coeff g (i + 1 - h) * coeff f j * coeff g (i + 1 - j))\"\n                  by fastforce\n              qed\n              have H: \"{(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1} \\<subseteq> {0..i+1}\\<times>{0..i+1}\"\n                      \"{(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1} \\<subseteq> {0..i+1}\\<times>{0..i+1}\"\n                      \"finite ({0..i+1}\\<times>{0..i+1})\"\n                by (fastforce, fastforce, fastforce)\n              have \"finite {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h \\<noteq> j + 1}\"\n                   \"finite {(h, j). h \\<le> i + 1 \\<and> j < h \\<and> h = j + 1}\"\n                apply (rule finite_subset) using H apply (simp, simp)\n                apply (rule finite_subset) using H apply (simp, simp)\n                done\n              thus ?thesis \n                apply (subst 1, subst 2, subst sum.union_disjoint[symmetric])\n                   apply auto[3]\n                apply (rule sum.cong)\n                by auto\n            qed\n            moreover have \"(\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i}.\n                  coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j)) = \n               (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                  coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) +\n               (\\<Sum>h = 1..i + 1. coeff f h * coeff g (i + 2 - h) * coeff f (h - 1) * coeff g (i + 1 - h))\"\n            proof -\n              have 1: \"(\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                     coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) =\n                    (\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}.\n                     coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j))\"\n              proof (rule sum.reindex_cong)\n                show \"{(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h} = (\\<lambda>(h, j). (j+1, h-1)) ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\"\n                proof\n                  show \"(\\<lambda>(h, j). (j + 1, h - 1)) ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1} \\<subseteq> {(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h}\"\n                    by fastforce\n                  show \"{(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h} \\<subseteq> (\\<lambda>(h, j). (j + 1, h - 1)) ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\"\n                  proof\n                    fix x\n                    assume \"x \\<in> {(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h}\"\n                    then obtain h j where \"x = (h, j)\" \"j \\<le> i + 1\" \"h \\<le> j\" \"0 < h\" by blast\n                    hence \"j + 1 \\<le> i + 2 \\<and> h - 1 < j + 1 \\<and> h - 1 \\<le> i \\<and> j + 1 \\<noteq> h - 1 + 1 \\<and> x = ((h - 1) + 1, (j + 1) - 1)\"\n                      by auto\n                    thus \"x \\<in> (\\<lambda>(h, j). (j + 1, h - 1)) ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\"\n                      by (auto simp: image_iff)\n                  qed\n                qed\n                show \"inj_on (\\<lambda>(h, j). (j + 1, h - 1)) {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\"\n                proof\n                  fix x y::\"nat\\<times>nat\"\n                  assume \"x \\<in> {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\" \"y \\<in> {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\"\n                  thus \"(case x of (h, j) \\<Rightarrow> (j + 1, h - 1)) = (case y of (h, j) \\<Rightarrow> (j + 1, h - 1)) \\<Longrightarrow> x = y\"\n                    by auto\n                qed\n                show \"\\<And>x. x \\<in> {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1} \\<Longrightarrow>\n                   (case case x of (h, j) \\<Rightarrow> (j + 1, h - 1) of\n                    (h, j) \\<Rightarrow> coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) =\n                   (case x of (h, j) \\<Rightarrow> coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j))\"\n                  by fastforce\n              qed\n              have 2: \"(\\<Sum>h = 1..i + 1. coeff f h * coeff g (i + 2 - h) * coeff f (h - 1) * coeff g (i + 1 - h)) =\n                    (\\<Sum>(h, j)\\<in>{(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}.\n                     coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j))\"\n              proof (rule sum.reindex_cong)\n                show \"{1..i + 1} = fst ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                proof\n                  show \"{1..i + 1} \\<subseteq> fst ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                  proof\n                    fix x\n                    assume \"x \\<in> {1..i + 1}\"\n                    hence \"x \\<le> i + 2 \\<and> x - 1 < x \\<and> x - 1 \\<le> i \\<and> x = x - 1 + 1 \\<and> x = fst (x, x-1)\"\n                      by auto\n                    thus \"x \\<in> fst ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                      by blast\n                  qed\n                  show \"fst ` {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1} \\<subseteq> {1..i + 1}\"\n                    by force\n                qed\n                show \"inj_on fst {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                proof\n                  fix x y\n                  assume \"x \\<in> {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                         \"y \\<in> {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                  hence \"x = (fst x, fst x - 1)\" \"y = (fst y, fst y - 1)\" \"fst x > 0\" \"fst y > 0\"\n                    by auto\n                  thus \"fst x = fst y \\<Longrightarrow> x = y\" by presburger\n                qed\n                show \"\\<And>x. x \\<in> {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1} \\<Longrightarrow>\n                   coeff f (fst x) * coeff g (i + 2 - fst x) * coeff f (fst x - 1) * coeff g (i + 1 - fst x) =\n                   (case x of (h, j) \\<Rightarrow> coeff f h * coeff g (i + 2 - h) * coeff f j * coeff g (i - j))\"\n                  by fastforce\n              qed\n              have H: \"{(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1} \\<subseteq> {0..i+2}\\<times>{0..i}\"\n                      \"{(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1} \\<subseteq> {0..i+2}\\<times>{0..i}\"\n                      \"finite ({0..i+2}\\<times>{0..i})\"\n                by (fastforce, fastforce, fastforce)\n              have \"finite {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h \\<noteq> j + 1}\"\n                   \"finite {(h, j). h \\<le> i + 2 \\<and> j < h \\<and> j \\<le> i \\<and> h = j + 1}\"\n                apply (rule finite_subset) using H apply (simp, simp)\n                apply (rule finite_subset) using H apply (simp, simp)\n                done\n              thus ?thesis \n                apply (subst 1, subst 2, subst sum.union_disjoint[symmetric])\n                   apply auto[3]\n                apply (rule sum.cong)\n                by auto\n            qed\n            ultimately show ?thesis\n              by algebra\n          qed\n\n          text \\<open>$\\dots = \\sum_{h \\leq j} f_hf_j\\left(g_{i+1-h}g_{i+1-j} - g_{i+2-h}g_{i-j}\\right) + \n                         \\sum_{h \\leq j} f_{j+1}f_{h-1}\\left(g_{i-j}g_{i+2-h} - g_{i+1-j}f_jg_{i+1-h}\\right)$\n\n                Note we have to also consider the edge cases caused by making these sums finite.\\<close>\n          also have \"... =\n              (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}.\n                 coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) +\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                 coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j))) +\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                 coeff f (j+1) * coeff f (h-1) * (coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h))) -\n              ((\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                  coeff f (j+1) * coeff g (i + 1 - j) * coeff f (h-1) * coeff g (i + 1 - h)))\" (is \"?L = ?R\")\n          proof -\n            have \"?R = \n              (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}.\n                 coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) +\n              ((\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                 coeff f h * coeff f j * coeff g (i + 1 - h) * coeff g (i + 1 - j)) -\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                 coeff f h * coeff f j * coeff g (i + 2 - h) * coeff g (i - j))) +\n              ((\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                 coeff f (j+1) * coeff f (h-1) * coeff g (i - j) * coeff g (i + 2 - h)) - \n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                 coeff f (j+1) * coeff f (h-1) * coeff g (i + 1 - j) * coeff g (i + 1 - h))) -\n              ((\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                  coeff f (j+1) * coeff g (i + 1 - j) * coeff f (h-1) * coeff g (i + 1 - h)))\"\n              apply (subst sum_subtractf[symmetric], subst sum_subtractf[symmetric])\n              by (auto simp: algebra_simps split_beta)\n            also have \"... =\n                ((\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}.\n                   coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) +\n                (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                   coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j)))) -\n                 (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                    coeff f h * coeff f j * coeff g (i + 2 - h) * coeff g (i - j)) +\n                (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff f (h - 1) * coeff g (i - j) * coeff g (i + 2 - h)) -\n                ((\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                   coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) +\n                (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                   coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)))\"\n              by (auto simp: algebra_simps)\n            also have \"... = ?L\"\n            proof -\n              have \"(\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}.\n                       coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) +\n                    (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n                       coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) =\n                    (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j}.\n                       coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j)))\"\n              proof (subst sum.union_disjoint[symmetric])\n                have \"{(h, j). j = i + 1 \\<and> h \\<le> j} \\<subseteq> {..i + 1} \\<times> {..i + 1}\"\n                     \"{(h, j). j \\<le> i \\<and> h \\<le> j} \\<subseteq> {..i + 1} \\<times> {..i + 1}\"\n                  by (fastforce, fastforce)\n                thus \"finite {(h, j). j = i + 1 \\<and> h \\<le> j}\" \"finite {(h, j). j \\<le> i \\<and> h \\<le> j}\"\n                  by (auto simp: finite_subset)\n                show \"{(h, j). j = i + 1 \\<and> h \\<le> j} \\<inter> {(h, j). j \\<le> i \\<and> h \\<le> j} = {}\"\n                  by fastforce\n              qed (rule sum.cong, auto)\n              moreover have \"(\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) +\n                 (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) =\n                 (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h))\"\n              proof (subst sum.union_disjoint[symmetric])\n                have \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h} \\<subseteq> {..i + 1} \\<times> {..i + 1}\"\n                     \"{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h} \\<subseteq> {..i + 1} \\<times> {..i + 1}\"\n                  by (fastforce, fastforce)\n                thus \"finite {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}\" \"finite {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}\"\n                  by (auto simp: finite_subset)\n                show \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h} \\<inter> {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h} = {}\"\n                  by fastforce\n              qed (rule sum.cong, auto)\n              ultimately show ?thesis \n                by (auto simp: algebra_simps)\n            qed\n            finally show ?thesis by presburger\n          qed\n\n          text \\<open>$\\dots = \\sum_{h \\leq j} \\left(f_hf_j - f_{j+1}f_{h-1}\\right)\n                                         \\left(g_{i+1-h}g_{i+1-j} - g_{i+2-h}g_{i-j}\\right)$\\<close>\n          also have \"... = \n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                 -(coeff f h * coeff f j - coeff f (j+1) * coeff f (h-1)) * (coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h))) +\n              (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> h = 0}.\n                 coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j))) +\n              (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}.\n                 coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) -\n              ((\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                  coeff f (j+1) * coeff g (i + 1 - j) * coeff f (h-1) * coeff g (i + 1 - h)))\" (is \"?L = ?R\")\n          proof -\n            have \"(\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j}.\n               coeff f h * coeff f j *\n               (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j))) =\n             (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n               coeff f h * coeff f j *\n               (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j))) +\n             (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 = h}.\n               coeff f h * coeff f j *\n               (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j)))\"\n            proof (subst sum.union_disjoint[symmetric])\n              have \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h} \\<subseteq> {..i}\\<times>{..i}\" \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 = h} \\<subseteq> {..i}\\<times>{..i}\"\n                by (force, force)\n              thus \"finite {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}\" \"finite {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 = h}\"\n                by (auto simp: finite_subset)\n              show \"{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h} \\<inter> {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 = h} = {}\"\n                by fast\n            qed (rule sum.cong, auto)\n            \n            moreover have \"(\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n               (-coeff f h * coeff f j + coeff f (j + 1) * coeff f (h - 1)) *\n               (coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h))) =\n                (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                   coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j))) +\n                (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                   coeff f (j + 1) * coeff f (h - 1) *\n                   (coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h)))\"\n              by (subst sum.distrib[symmetric], rule sum.cong, fast, auto simp: algebra_simps)\n\n            ultimately show ?thesis\n              by (auto simp: algebra_simps)\n          qed\n\n          text \\<open>$\\dots \\geq 0$ by \\<open>normal_poly_general_coeff_mult\\<close>\\<close>\n          also have \"... \\<ge> 0\"\n          proof -\n            have \"0 \\<le> (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}.\n                        - (coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1)) *\n                        (coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h)))\"\n            proof (rule sum_nonneg)\n              fix x assume \"x \\<in> {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> 0 < h}\"\n              then obtain h j where H: \"x = (h, j)\" \"j \\<le> i\" \"h \\<le> j\" \"0 < h\" by fast\n              hence \"h - 1 \\<le> j - 1\" by force\n              hence 1: \"coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1) \\<ge> 0\"\n                using normal_poly_general_coeff_mult[OF hf, of \"h-1\" \"j-1\"] H\n                by (auto simp: algebra_simps)\n              from H have \"i - j \\<le> i - h\" by force\n              hence 2: \"coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h) \\<le> 0\"\n                using normal_poly_general_coeff_mult[OF hg, of \"i - j\" \"i - h\"] H\n                by (smt (verit, del_insts) Nat.add_diff_assoc2 le_trans)\n              show \"0 \\<le> (case x of\n               (h, j) \\<Rightarrow>\n                 - (coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1)) *\n                 (coeff g (i - j) * coeff g (i + 2 - h) -\n                  coeff g (i + 1 - j) * coeff g (i + 1 - h)))\"\n                apply (subst H(1), subst split, rule mult_nonpos_nonpos, subst neg_le_0_iff_le)\n                subgoal using 1 by blast\n                subgoal using 2 by blast\n                done\n            qed\n            moreover have \"0 \\<le> (\\<Sum>(h, j)\\<in>{(h, j). j \\<le> i \\<and> h \\<le> j \\<and> h = 0}.\n                        coeff f h * coeff f j *\n                        (coeff g (i + 1 - h) * coeff g (i + 1 - j) - coeff g (i + 2 - h) * coeff g (i - j)))\"\n            proof (rule sum_nonneg)\n              fix x assume \"x \\<in> {(h, j). j \\<le> i \\<and> h \\<le> j \\<and> h = 0}\"\n              then obtain h j where H: \"x = (h, j)\" \"j \\<le> i\" \"h \\<le> j\" \"h = 0\" by fast\n              have 1: \"coeff f h * coeff f j \\<ge> 0\"\n                by (simp add: hf normal_coeff_nonneg)\n              from H have \"i - j \\<le> i - h\" by force\n              hence 2: \"coeff g (i - j) * coeff g (i + 2 - h) - coeff g (i + 1 - j) * coeff g (i + 1 - h) \\<le> 0\"\n                using normal_poly_general_coeff_mult[OF hg, of \"i - j\" \"i - h\"] H\n                by (smt (verit, del_insts) Nat.add_diff_assoc2 le_trans)\n              show \"0 \\<le> (case x of\n               (h, j) \\<Rightarrow>\n                 coeff f h * coeff f j *\n                 (coeff g (i + 1 - h) * coeff g (i + 1 - j) -\n                  coeff g (i + 2 - h) * coeff g (i - j)))\"\n                apply (subst H(1), subst split, rule mult_nonneg_nonneg)\n                subgoal using 1 by blast\n                subgoal using 2 by argo\n                done\n            qed\n            moreover have \"0 \\<le> (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}. coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) -\n                 (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h))\"\n            proof -\n              have \"(\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}. coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) -\n                 (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) = \n                 (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0}. coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) +\n                 (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}. coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) -\n                 (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                    coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h))\"\n              proof (subst sum.union_disjoint[symmetric])\n                have \"{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0} = {(0, i + 1)}\"\n                     \"{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h} = {1..i+1} \\<times> {i + 1}\"\n                  by (fastforce, force)\n                thus \"finite {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0}\"\n                     \"finite {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}\"\n                  by auto\n                show \"{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0} \\<inter> {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h} = {}\" \n                  by fastforce\n                have \"{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0} \\<union> {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h} = {(h, j). j = i + 1 \\<and> h \\<le> j}\"\n                  by fastforce\n                thus \"(\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j}. coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) -\n                      (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                         coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h)) =\n                      (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0} \\<union> {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                         coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) -\n                      (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                         coeff f (j + 1) * coeff g (i + 1 - j) * coeff f (h - 1) * coeff g (i + 1 - h))\"\n                  by presburger\n              qed\n              also have \"... =\n                (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> h = 0}. coeff f h * coeff f j * (coeff g (i + 1 - h) * coeff g (i + 1 - j))) +\n                (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}. \n                   (coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1)) * (coeff g (i + 1 - h) * coeff g (i + 1 - j)))\"\n                by (subst add_diff_eq[symmetric], subst sum_subtractf[symmetric], subst add_left_cancel, rule sum.cong, auto simp: algebra_simps)\n              also have \"... \\<ge> 0\"\n              proof (rule add_nonneg_nonneg)\n                show \"0 \\<le> (\\<Sum>(h, j)\\<in>{(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}.\n                        (coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1)) *\n                        (coeff g (i + 1 - h) * coeff g (i + 1 - j)))\"\n                proof (rule sum_nonneg)\n                  fix x assume \"x \\<in> {(h, j). j = i + 1 \\<and> h \\<le> j \\<and> 0 < h}\"\n                  then obtain h j where H: \"x = (h, j)\" \"j = i + 1\" \"h \\<le> j\" \"0 < h\" by fast\n                  hence \"h - 1 \\<le> j - 1\" by force\n                  hence 1: \"coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1) \\<ge> 0\"\n                    using normal_poly_general_coeff_mult[OF hf, of \"h-1\" \"j-1\"] H\n                    by (auto simp: algebra_simps)\n                  hence 2: \"0 \\<le> coeff g (i + 1 - h) * coeff g (i + 1 - j)\"\n                    by (meson hg mult_nonneg_nonneg normal_coeff_nonneg)\n                  show \"0 \\<le> (case x of\n                   (h, j) \\<Rightarrow>\n                     (coeff f h * coeff f j - coeff f (j + 1) * coeff f (h - 1)) *\n                     (coeff g (i + 1 - h) * coeff g (i + 1 - j)))\"\n                    apply (subst H(1), subst split, rule mult_nonneg_nonneg)\n                    subgoal using 1 by blast\n                    subgoal using 2 by blast\n                    done\n                qed\n              qed (rule sum_nonneg, auto simp: hf hg normal_coeff_nonneg)[1]\n              finally show ?thesis .\n            qed\n            ultimately show ?thesis by auto\n          qed\n          finally show \"coeff (f * g) i * coeff (f * g) (i + 2) \\<le> (coeff (f * g) (i + 1))\\<^sup>2\" by (auto simp: power2_eq_square)\n        qed\n        moreover have \"\\<And>i j k. i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> 0 < coeff (f*g) i \\<Longrightarrow> 0 < coeff (f*g) k \\<Longrightarrow> 0 < coeff (f*g) j\"\n        proof -\n          fix j k\n          assume \"0 < coeff (f * g) k\"\n          hence \"k \\<le> degree (f * g)\" using le_degree by force\n          moreover assume \"j \\<le> k\"\n          ultimately have \"j \\<le> degree (f * g)\" by auto\n          hence 1: \"j \\<le> degree f + degree g\"\n            by (simp add: degree_mult_eq hf hg normal_non_zero)\n          show \"0 < coeff (f * g) j\"\n            apply (subst coeff_mult, rule sum_pos2[of _ \"min j (degree f)\"], simp, simp)\n            apply (rule mult_pos_pos, rule normal_of_no_zero_root, simp add: hf0, simp)\n            using hf apply auto[1]\n             apply (rule normal_of_no_zero_root)\n               apply (simp add: hg0)\n            using 1 apply force\n            using hg apply auto[1]\n            by (simp add: hf hg normal_coeff_nonneg)\n        qed\n        ultimately show \"normal_poly (f*g)\" \n          by (rule normal_polyI)\n      qed\n    qed\n  qed\nqed\n\nlemma normal_poly_of_roots: \n  fixes p::\"real poly\"\n  assumes \"\\<And>z. poly (map_poly complex_of_real p) z = 0 \n        \\<Longrightarrow> Re z \\<le> 0 \\<and> 4*(Re z)^2 \\<ge> (cmod z)^2\"\n      and \"lead_coeff p = 1\"\n  shows \"normal_poly p\"\n  using assms\nproof (induction p rule: real_poly_roots_induct)\n  fix p::\"real poly\" and x::real\n  assume \"lead_coeff (p * [:- x, 1:]) = 1\"\n  hence 1: \"lead_coeff p = 1\"\n    by (metis coeff_degree_mult lead_coeff_pCons(1) mult_cancel_left1 pCons_one zero_neq_one)\n  assume h: \"(\\<And>z. poly (map_poly complex_of_real (p * [:- x, 1:])) z = 0 \\<Longrightarrow>\n                 Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2)\"\n  hence 2: \"(\\<And>z. poly (map_poly complex_of_real p) z = 0 \\<Longrightarrow>\n                 Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2)\"\n    by (metis four_x_squared mult_zero_left of_real_poly_map_mult poly_mult)\n  have 3: \"normal_poly [:-x, 1:]\"\n    apply (subst linear_normal_iff, \n        subst Re_complex_of_real[symmetric], rule conjunct1)\n    by (rule h[of x], subst of_real_poly_map_poly[symmetric], force)\n  assume \"(\\<And>z. poly (map_poly complex_of_real p) z = 0\n             \\<Longrightarrow> Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2) \\<Longrightarrow>\n            lead_coeff p = 1 \\<Longrightarrow> normal_poly p\"\n  hence \"normal_poly p\" using 1 2 by fast\n  then show \"normal_poly (p * [:-x, 1:])\" \n    using 3 by (rule normal_mult)\nnext\n  fix p::\"real poly\" and a b::real\n  assume \"lead_coeff (p * [:a * a + b * b, - 2 * a, 1:]) = 1\"\n  hence 1: \"lead_coeff p = 1\"\n    by (smt (verit) coeff_degree_mult lead_coeff_pCons(1) mult_cancel_left1 pCons_eq_0_iff pCons_one)\n  assume h: \"(\\<And>z. poly (map_poly complex_of_real (p * [:a * a + b * b, - 2 * a, 1:])) z = 0 \\<Longrightarrow>\n                 Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2)\"\n  hence 2: \"(\\<And>z. poly (map_poly complex_of_real p) z = 0 \\<Longrightarrow>\n                 Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2)\"\n  proof -\n    fix z :: complex\n    assume \"poly (map_poly complex_of_real p) z = 0\"\n    then have \"\\<forall>q. 0 = poly (map_poly complex_of_real (p * q)) z\"\n      by simp\n    then show \"Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2\"\n      using h by presburger\n  qed\n  have 3: \"[:a * a + b * b, - 2 * a, 1:] = [:cmod (a + \\<i>*b) ^ 2, -2 * Re (a + \\<i>*b), 1:]\"\n    by (force simp: cmod_def power2_eq_square)\n  interpret map_poly_idom_hom complex_of_real ..\n  have 4: \"normal_poly [:a * a + b * b, - 2 * a, 1:]\"\n    apply (subst 3, subst quadratic_normal_iff)\n    apply (rule h, unfold hom_mult poly_mult)\n    by (auto simp: algebra_simps)\n  assume \"(\\<And>z. poly (map_poly complex_of_real p) z = 0 \\<Longrightarrow> Re z \\<le> 0 \\<and> (cmod z)\\<^sup>2 \\<le> 4 * (Re z)\\<^sup>2) \\<Longrightarrow>\n            lead_coeff p = 1 \\<Longrightarrow> normal_poly p\"\n  hence \"normal_poly p\" using 1 2 by fast\n  then show \"normal_poly (p * [:a * a + b * b, - 2 * a, 1:])\" \n    using 4 by (rule normal_mult)\nnext\n  fix a::real \n  assume \"lead_coeff [:a:] = 1\"\n  moreover have \"\\<And>i j k.\n       lead_coeff [:a:] = 1 \\<Longrightarrow>\n       i \\<le> j \\<Longrightarrow>\n       j \\<le> k \\<Longrightarrow> 0 < coeff [:a:] i \\<Longrightarrow> 0 < coeff [:a:] k \\<Longrightarrow> 0 < coeff [:a:] j\"\n    by (metis bot_nat_0.extremum_uniqueI coeff_eq_0 degree_pCons_0 leI \n        less_numeral_extra(3))\n  ultimately show \"normal_poly [:a:]\"\n    apply (subst normal_polyI)\n    by (auto simp:pCons_one)\nqed\n\nlemma normal_changes: \n  fixes f::\"real poly\"\n  assumes hf: \"normal_poly f\" and hx: \"x > 0\"\n  defines \"df \\<equiv> degree f\"\n  shows \"changes (coeffs (f*[:-x,1:])) = 1\"\n  using df_def hf \nproof (induction df arbitrary: f)\n  case 0\n  then obtain a where \"f = [:a:]\" using degree_0_iff by auto\n  thus \"changes (coeffs (f*[:-x, 1:])) = 1\"\n    using normal_non_zero[OF \\<open>normal_poly f\\<close>] hx \n    by (auto simp: algebra_simps zero_less_mult_iff mult_less_0_iff)\nnext\n  case (Suc df)\n  then show ?case\n  proof (cases \"poly f 0 = 0\")\n    assume \"poly f 0 = 0\" and hf:\"normal_poly f\"\n    moreover then obtain f' where hdiv: \"f = f'*[:0, 1:]\"\n      by (smt (verit) dvdE mult.commute poly_eq_0_iff_dvd) \n    ultimately have hf': \"normal_poly f'\" using normal_divide_x by blast\n    assume \"Suc df = degree f\"\n    hence \"degree f' = df\" using hdiv normal_non_zero[OF hf'] by (auto simp: degree_mult_eq)\n    moreover assume \"\\<And>f::real poly. df = degree f \\<Longrightarrow> normal_poly f \\<Longrightarrow> changes (coeffs (f * [:- x, 1:])) = 1\"\n    ultimately have \"changes (coeffs (f' * [:- x, 1:])) = 1\" using hf' by fast\n    thus \"changes (coeffs (f * [:- x, 1:])) = 1\"\n      apply (subst hdiv, subst mult_pCons_right, subst smult_0_left, subst add_0)\n      apply (subst mult_pCons_left, subst smult_0_left, subst add_0)\n      by (subst changes_pCons, auto)\n  next\n    assume hf:\"normal_poly f\" and \"poly f 0 \\<noteq> 0\"\n    hence h': \"\\<And>i. i \\<le> degree f \\<Longrightarrow> coeff f i > 0\"\n      by (auto simp: normal_of_no_zero_root)\n    hence \"\\<And>i. i < degree f - 1 \\<Longrightarrow> (coeff f i)/(coeff f (i+1)) \\<le> (coeff f (i+1))/(coeff f (i+2))\"\n      using normal_poly_coeff_mult[OF hf] normal_coeff_nonneg[OF hf]\n      by (auto simp: divide_simps power2_eq_square)\n    hence h'': \"\\<And>i. i < degree f - 1 \\<Longrightarrow> (coeff f i)/(coeff f (i+1)) - x \\<le> (coeff f (i+1))/(coeff f (i+2)) - x\"\n      by fastforce\n    have hdeg: \"degree (pCons 0 f - smult x f) = degree f + 1\"\n      apply (subst diff_conv_add_uminus)\n      apply (subst degree_add_eq_left)\n      by (auto simp: hf normal_non_zero)\n\n    let ?f = \"\\<lambda> z w. \\<lambda>i. if i=0 then z/(x * coeff f 0) else (if i = degree (pCons 0 f - smult x f) then w/(lead_coeff f) else inverse (coeff f i))\"\n\n    have 1: \"\\<And>z w. 0 < z \\<Longrightarrow> 0 < w \\<Longrightarrow> changes (coeffs (f * [:-x, 1:])) =\n          changes (-z # map (\\<lambda>i. (coeff f (i-1))/(coeff f i) - x) [1..<degree (pCons 0 f - smult x f)] @ [w])\"\n    proof -\n      fix z w :: real\n      assume hz: \"0 < z\" and hw: \"0 < w\"\n\n      have \"-z # map (\\<lambda>i. (coeff f (i-1))/(coeff f i) - x) [1..<degree (pCons 0 f - smult x f)] @ [w] =\n            map (\\<lambda>i. if i = 0 then -z else if i = degree (pCons 0 f - smult x f) then w else \n              (coeff f (i-1))/(coeff f i) - x) [0..<degree (pCons 0 f - smult x f) + 1]\"\n      proof (rule nth_equalityI)\n        fix i assume \"i < length (- z # map (\\<lambda>i. coeff f (i - 1) / coeff f i - x) [1..<degree (pCons 0 f - smult x f)] @ [w])\"\n        hence \"i \\<le> degree (pCons 0 f - smult x f)\"\n          using hdeg Suc.hyps(2) by auto\n        then consider (a)\"i = 0\" | (b)\"(0 < i \\<and> i < degree (pCons 0 f - smult x f))\" |\n          (c)\"i = degree (pCons 0 f - smult x f)\"\n          by fastforce\n        then show \"(- z #\n              map (\\<lambda>i. coeff f (i - 1) / coeff f i - x)\n               [1..<degree (pCons 0 f - smult x f)] @\n              [w]) ! i =\n             map (\\<lambda>i. if i = 0 then - z\n                      else if i = degree (pCons 0 f - smult x f) then w\n                           else coeff f (i - 1) / coeff f i - x)\n              [0..<degree (pCons 0 f - smult x f) + 1] ! i\"\n          apply (cases)\n          by (auto simp: nth_append)\n      qed (force simp: hdeg)      \n\n      also have \"... = [?f z w i * (nth_default 0 (coeffs (f * [:-x, 1:])) i). \n                        i \\<leftarrow> [0..<Suc (degree (pCons 0 f - smult x f))]]\"\n      proof (rule map_cong)\n        fix i assume \"i \\<in> set [0..<Suc (degree (pCons 0 f - smult x f))]\"\n        then consider (a)\"i = 0\" | (b)\"(0 \\<noteq> i \\<and> i < degree (pCons 0 f - smult x f))\" |\n          (c)\"i = degree (pCons 0 f - smult x f)\"\n          by fastforce\n        then show \"(if i = 0 then - z\n           else if i = degree (pCons 0 f - smult x f) then w\n                else coeff f (i - 1) / coeff f i - x) =\n          (if i = 0 then z / (x * coeff f 0)\n           else if i = degree (pCons 0 f - smult x f) then w / lead_coeff f\n                else inverse (coeff f i)) *\n          nth_default 0 (coeffs (f * [:- x, 1:])) i\"\n        proof (cases)\n          case (a)\n          thus ?thesis using hx \\<open>poly f 0 \\<noteq> 0\\<close> by (auto simp: nth_default_coeffs_eq poly_0_coeff_0)\n        next\n          case (b)\n          thus ?thesis using hx h'[of i] hdeg\n            by (auto simp: field_simps nth_default_coeffs_eq coeff_pCons nat.split poly_0_coeff_0)\n        next\n          case (c)\n          thus ?thesis using hdeg by (auto simp: nth_default_coeffs_eq coeff_eq_0)\n        qed\n      qed force\n\n      finally have 1: \" - z #\n        map (\\<lambda>i. coeff f (i - 1) / coeff f i - x) [1..<degree (pCons 0 f - smult x f)] @ [w] =\n        map (\\<lambda>i. (if i = 0 then z / (x * coeff f 0)\n                  else if i = degree (pCons 0 f - smult x f) then w / lead_coeff f\n                       else inverse (coeff f i)) *\n                 nth_default 0 (coeffs (f * [:- x, 1:])) i)\n         [0..<Suc (degree (pCons 0 f - smult x f))]\" .\n\n      have \"f * [:-x, 1:] \\<noteq> 0\" using hdeg by force\n\n      show \"changes (coeffs (f * [:- x, 1:])) =\n           changes\n            (- z #\n             map (\\<lambda>i. coeff f (i - 1) / coeff f i - x)\n              [1..<degree (pCons 0 f - smult x f)] @\n             [w])\"\n        apply (subst 1)\n        apply (rule changes_scale[symmetric])\n        subgoal using hz hw hx h' hdeg by auto\n        subgoal using hdeg \\<open>f * [:-x, 1:] \\<noteq> 0\\<close> \n          by (auto simp: length_coeffs)\n        done\n    qed\n\n    hence \"changes (coeffs (f * [:- x, 1:])) =\n        changes\n         (- (max 1 (-(coeff f 0 / coeff f 1 - x))) #\n          map (\\<lambda>i. coeff f (i - 1) / coeff f i - x)\n           [1..<degree (pCons 0 f - smult x f)] @\n          [max 1 (coeff f (degree f - 1) / lead_coeff f - x)])\"\n      by force\n\n    also have \"... = 1\"\n    proof (rule changes_increasing)\n      fix i\n      assume \"i < length\n              (- max 1 (- (coeff f 0 / coeff f 1 - x)) #\n               map (\\<lambda>i. coeff f (i - 1) / coeff f i - x) [1..<degree (pCons 0 f - smult x f)] @\n               [max 1 (coeff f (degree f - 1) / lead_coeff f - x)]) - 1\"\n      hence \"i < degree (pCons 0 f - smult x f)\"\n        using hdeg Suc.hyps(2) by fastforce\n      then consider (a)\"i = 0\" | (b)\"0 \\<noteq> i \\<and> i < degree (pCons 0 f - smult x f) - 1\" |\n        (c)\"i = degree (pCons 0 f - smult x f) - 1\"\n        by fastforce\n      then show \"(- max 1 (- (coeff f 0 / coeff f 1 - x)) #\n          map (\\<lambda>i. coeff f (i - 1) / coeff f i - x)\n           [1..<degree (pCons 0 f - smult x f)] @\n          [max 1 (coeff f (degree f - 1) / lead_coeff f - x)]) !\n         i\n         \\<le> (- max 1 (- (coeff f 0 / coeff f 1 - x)) #\n             map (\\<lambda>i. coeff f (i - 1) / coeff f i - x)\n              [1..<degree (pCons 0 f - smult x f)] @\n             [max 1 (coeff f (degree f - 1) / lead_coeff f - x)]) !\n            (i + 1)\"\n      proof (cases)\n        case a\n        then show ?thesis by (auto simp: nth_append)\n      next\n        case b\n        have \"coeff f (i - 1) * coeff f (i - 1 + 2) \\<le> (coeff f (i - 1 + 1))\\<^sup>2\"\n          by (rule normal_poly_coeff_mult[OF hf, of \"i - 1\"])\n        hence \"coeff f (i - 1) / coeff f i \\<le> coeff f i / coeff f (i + 1)\"\n          using h'[of i] h'[of \"i+1\"] h'[of \"i-1\"] h' b hdeg\n          by (auto simp: power2_eq_square divide_simps)\n        then show ?thesis\n          using b by (auto simp: nth_append)\n      next\n        case c\n        then show ?thesis using hdeg by (auto simp: nth_append not_le)\n      qed\n    qed auto\n\n    finally show \"changes (coeffs (f * [:-x, 1:])) = 1\" .\n  qed\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Three_Circles/Normal_Poly.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669025, "lm_q2_score": 0.8774767826757122, "lm_q1q2_score": 0.7961454110810751}}
{"text": "section \\<open> Types of Cardinality 2 or Greater \\<close>\n\ntheory Two\nimports HOL.Real\nbegin\n\ntext \\<open> The two class states that a type's carrier is either infinite, or else it has a finite \n  cardinality of at least 2. It is needed when we depend on having at least two distinguishable\n  elements. \\<close>\n  \nclass two =\n  assumes card_two: \"infinite (UNIV :: 'a set) \\<or> card (UNIV :: 'a set) \\<ge> 2\"\nbegin\nlemma two_diff: \"\\<exists> x y :: 'a. x \\<noteq> y\"\nproof -\n  obtain A where \"finite A\" \"card A = 2\" \"A \\<subseteq> (UNIV :: 'a set)\"\n  proof (cases \"infinite (UNIV :: 'a set)\")\n    case True\n    with infinite_arbitrarily_large[of \"UNIV :: 'a set\" 2] that\n    show ?thesis by auto\n  next\n    case False\n    with card_two that\n    show ?thesis\n      by (metis UNIV_bool card_UNIV_bool card_image card_le_inj finite.intros(1) finite_insert finite_subset)\n  qed\n  thus ?thesis\n    by (metis (full_types) One_nat_def Suc_1 UNIV_eq_I card.empty card.insert finite.intros(1) insertCI nat.inject nat.simps(3))\nqed\nend\n\ninstance bool :: two\n  by (intro_classes, auto)\n\ninstance nat :: two\n  by (intro_classes, auto)\n\ninstance int :: two\n  by (intro_classes, auto simp add: infinite_UNIV_int)\n\ninstance rat :: two\n  by (intro_classes, auto simp add: infinite_UNIV_char_0)\n\ninstance real :: two\n  by (intro_classes, auto simp add: infinite_UNIV_char_0)\n\ninstance list :: (type) two\n  by (intro_classes, auto simp add: infinite_UNIV_listI)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Optics/Two.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.8840392878563336, "lm_q1q2_score": 0.7961037155330871}}
{"text": "theory Ex3_12\nimports\n  \"~~/src/HOL/IMP/AExp\"\nbegin\n\n(*\nBy: Vadim Zaliva <vzaliva@cmu.edu>\nFrom: T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL. Springer, 2014.\nExercise 3.12:\n*)\n\ntype_synonym reg = \"nat\"\ntype_synonym rstate = \"reg \\<Rightarrow> int\"\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun comp0 :: \"aexp \\<Rightarrow> nat \\<Rightarrow> instr0 list\" where\n\"comp0 (N n) sp = [LDI0 n]\"\n| \"comp0 (V v) sp = [LD0 v]\"\n| \"comp0 (Plus e1 e2) sp = comp0 e1 sp @ [MV0 (Suc sp)] @ comp0 e2 (Suc sp) @ [ADD0 (Suc sp)]\"\n\ndefinition rupdate :: \"rstate \\<Rightarrow> reg \\<Rightarrow> val \\<Rightarrow> rstate\" where\n\"rupdate f a v = (\\<lambda>x. (if x = a then v else (f x)))\"\n\n(* execute single instruction *)\nfun exec0single :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"exec0single (LDI0 n) s rs = rupdate rs 0 n\"\n  | \"exec0single (LD0 v) s rs = rupdate rs 0 (s v)\" \n  | \"exec0single (MV0 r) s rs = rupdate rs r (rs 0)\"\n  | \"exec0single (ADD0 r) s rs = rupdate rs 0 ((rs 0) + (rs r))\"\n\n(* execute sequence of instrctions *)\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"exec0 [] _ rs = rs\"\n  | \"exec0 (i#is) s rs = exec0 is s (exec0single i s rs)\" \n\nlemma rupdate_eq[simp]: \"(rupdate rs r v) r = v\" \n  apply(auto simp add: rupdate_def)\ndone\n\nlemma rupdate_ne[simp]: \"\\<lbrakk>x \\<noteq> y\\<rbrakk> \\<Longrightarrow> (rupdate rs x a) y = rs y\"\napply (auto simp add: rupdate_def)\ndone\n\nlemma exec_seq : \"exec0 (xs@ys) s rs = exec0 ys s (exec0 xs s rs)\" \n  apply(induction xs arbitrary: ys s rs)\n  apply(auto)\ndone\n\n(* Making sure generated code modifies only registers above SP, excep 0 *)\n\nlemma reg_safe: \"\\<lbrakk>r \\<noteq> 0 \\<and> sp \\<ge> r\\<rbrakk> \\<Longrightarrow> (exec0 (comp0 e sp) s rs) r = rs r\"\n  apply (induction e arbitrary: rs r sp)\n  apply (auto simp add: exec_seq)\ndone\n\n(* Prove that compiler is correct: for arbitrary expression 'a' it retuns evaluation results in register 0 *)\n\ntheorem \"(exec0 (comp0 a sp) s rs) 0 = aval a s\"\n  apply (induction a arbitrary: sp s rs)\n  apply(auto simp add: exec_seq reg_safe)\ndone\n\n\nend\n\n", "meta": {"author": "vzaliva", "repo": "isabelle-semantics-ex", "sha": "4e1acf1c9850f17057dd98454e42262d01301670", "save_path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex", "path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex/isabelle-semantics-ex-4e1acf1c9850f17057dd98454e42262d01301670/Ex3_12.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8840392756357327, "lm_q1q2_score": 0.7961036950880546}}
{"text": "\\<^marker>\\<open>creator Bilel Ghorbel, Florian Kessler\\<close>\nsection \"Arithmetic Expressions\"\n\ntext \\<open>\nWe define non-nested arithmetic expressions on natural numbers.\nThe defined operations are addition and modified subtraction. Based on the AExp theory of IMP.\n\\<close>\n\ntheory AExp imports Main begin\n\ntype_synonym vname = string\ntype_synonym val = nat\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext \"Defining atomic expressions:\"\ndatatype atomExp = N val | V vname\n\nfun atomVal :: \"atomExp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"atomVal (V var) s = s var\"|\n\"atomVal (N number) _ = number\"\n\ntext \"Defining arithmetic operators and general form of expressions: \"\n\ndatatype aexp =  A atomExp            |\n                 Plus atomExp atomExp |\n                 Sub atomExp atomExp  | \n                 Parity atomExp       |\n                 RightShift atomExp\n\nbundle aexp_syntax\nbegin\nnotation Plus            (\"_ \\<oplus> _\" [60,60] 60) and\n         Sub             (\"_ \\<ominus> _\" [60,60] 60) and\n         Parity          (\"_ \\<doteq>1\" [60] 60)   and\n         RightShift      (\"_\\<then>\" [60] 60)\n\nend\nbundle no_aexp_syntax\nbegin\nnotation Plus            (\"_ \\<oplus> _\" [60,60] 60) and\n         Sub             (\"_ \\<ominus> _\" [60,60] 60) and\n         Parity          (\"_ \\<doteq>1\" [60] 60)    and\n         RightShift      (\"_\\<then>\" [60] 60)\nend\nunbundle aexp_syntax\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (A atomExp) s = atomVal atomExp s\"        |\n\"aval (a \\<oplus> b) s = atomVal a s  + atomVal b s\" |\n\"aval (a \\<ominus> b) s = atomVal a s - atomVal b s\"  |\n\"aval (a \\<doteq>1) s = atomVal a s  mod 2\"        |\n\"aval (a \\<then>) s = atomVal a s div 2\"\n\ntext \"evaluation examples:\"\nvalue \"aval (V ''x'' \\<oplus> N 5)  (\\<lambda>x. if x = ''x'' then 7 else 0)\"\nvalue \"aval (V ''x'' \\<ominus> N 5)  ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \"Syntactic sugar to write states:\"     \ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\nbundle state_syntax\nbegin\nnotation null_state (\"<>\")\nend\n\nbundle no_state_syntax\nbegin\nno_notation null_state (\"<>\")\nend\n\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (V ''x'' \\<ominus> N 5) <''x'' := 7>\"\nvalue \"aval (V ''x'' \\<ominus> N 10) <''x'' := 7>\"\n\nend", "meta": {"author": "wimmers", "repo": "poly-reductions", "sha": "b2d7c584bcda9913dd5c3785817a5d63b14d1455", "save_path": "github-repos/isabelle/wimmers-poly-reductions", "path": "github-repos/isabelle/wimmers-poly-reductions/poly-reductions-b2d7c584bcda9913dd5c3785817a5d63b14d1455/IMP-/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409306, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7960605803847196}}
{"text": "theory types\n  imports Main\nbegin\n\ndeclare [[names_short]]\n\ndatatype bool = True | False\n\n(* A function representing logical and *)\nfun conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n \"conj True True = True\" |\n \"conj _ _ = False\"\n\ndatatype nat = 0 | Suc nat\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n \"add 0 n = n\" |\n \"add (Suc m) n = Suc(add m n)\"\n\nlemma add_02: \"add m 0 = m\"\n  apply(induction m)\n   apply(auto)\n  done\n\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n \"app Nil ys = ys\" |\n \"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n \"rev Nil = Nil\" |\n \"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\nlemma app_Nil2 [simp]: \"app xs Nil = xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma app_assoc [simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma rev_app [simp]: \"rev(app xs ys) = app (rev ys) (rev xs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nend", "meta": {"author": "nnooney", "repo": "isabelle-theories", "sha": "194126c8eaca0c87e9e714bf7be7e0b1b9a448be", "save_path": "github-repos/isabelle/nnooney-isabelle-theories", "path": "github-repos/isabelle/nnooney-isabelle-theories/isabelle-theories-194126c8eaca0c87e9e714bf7be7e0b1b9a448be/types.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218262741297, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7959795714771036}}
{"text": "section \\<open>Peano's axioms for Natural Numbers\\<close>\n\ntheory Peano_Axioms\n  imports Main\nbegin\n\nlocale peano =\n  fixes zero :: 'n\n  fixes succ :: \"'n \\<Rightarrow> 'n\"\n  assumes succ_neq_zero [simp]: \"succ m \\<noteq> zero\"\n  assumes succ_inject [simp]: \"succ m = succ n \\<longleftrightarrow> m = n\"\n  assumes induct [case_names zero succ, induct type: 'n]:\n    \"P zero \\<Longrightarrow> (\\<And>n. P n \\<Longrightarrow> P (succ n)) \\<Longrightarrow> P n\"\nbegin\n\nlemma zero_neq_succ [simp]: \"zero \\<noteq> succ m\"\n  by (rule succ_neq_zero [symmetric])\n\n\ntext \\<open>\\<^medskip> Primitive recursion as a (functional) relation -- polymorphic!\\<close>\n\ninductive Rec :: \"'a \\<Rightarrow> ('n \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'n \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  for e :: 'a and r :: \"'n \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  Rec_zero: \"Rec e r zero e\"\n| Rec_succ: \"Rec e r m n \\<Longrightarrow> Rec e r (succ m) (r m n)\"\n\nlemma Rec_functional: \"\\<exists>!y::'a. Rec e r x y\" for x :: 'n\nproof -\n  let ?R = \"Rec e r\"\n  show ?thesis\n  proof (induct x)\n    case zero\n    show \"\\<exists>!y. ?R zero y\"\n    proof\n      show \"?R zero e\" ..\n      show \"y = e\" if \"?R zero y\" for y\n        using that by cases simp_all\n    qed\n  next\n    case (succ m)\n    from \\<open>\\<exists>!y. ?R m y\\<close>\n    obtain y where y: \"?R m y\" and yy': \"\\<And>y'. ?R m y' \\<Longrightarrow> y = y'\"\n      by blast\n    show \"\\<exists>!z. ?R (succ m) z\"\n    proof\n      from y show \"?R (succ m) (r m y)\" ..\n    next\n      fix z\n      assume \"?R (succ m) z\"\n      then obtain u where \"z = r m u\" and \"?R m u\"\n        by cases simp_all\n      with yy' show \"z = r m y\"\n        by (simp only:)\n    qed\n  qed\nqed\n\n\ntext \\<open>\\<^medskip> The recursion operator -- polymorphic!\\<close>\n\ndefinition rec :: \"'a \\<Rightarrow> ('n \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'n \\<Rightarrow> 'a\"\n  where \"rec e r x = (THE y. Rec e r x y)\"\n\nlemma rec_eval:\n  assumes Rec: \"Rec e r x y\"\n  shows \"rec e r x = y\"\n  unfolding rec_def\n  using Rec_functional and Rec by (rule the1_equality)\n\nlemma rec_zero [simp]: \"rec e r zero = e\"\nproof (rule rec_eval)\n  show \"Rec e r zero e\" ..\nqed\n\nlemma rec_succ [simp]: \"rec e r (succ m) = r m (rec e r m)\"\nproof (rule rec_eval)\n  let ?R = \"Rec e r\"\n  have \"?R m (rec e r m)\"\n    unfolding rec_def using Rec_functional by (rule theI')\n  then show \"?R (succ m) (r m (rec e r m))\" ..\nqed\n\n\ntext \\<open>\\<^medskip> Example: addition (monomorphic)\\<close>\n\ndefinition add :: \"'n \\<Rightarrow> 'n \\<Rightarrow> 'n\"\n  where \"add m n = rec n (\\<lambda>_ k. succ k) m\"\n\nlemma add_zero [simp]: \"add zero n = n\"\n  and add_succ [simp]: \"add (succ m) n = succ (add m n)\"\n  unfolding add_def by simp_all\n\n\n\nlemma add_zero_right: \"add m zero = m\"\n  by (induct m) simp_all\n\nlemma add_succ_right: \"add m (succ n) = succ (add m n)\"\n  by (induct m) simp_all\n\nlemma \"add (succ (succ (succ zero))) (succ (succ zero)) =\n    succ (succ (succ (succ (succ zero))))\"\n  by simp\n\n\ntext \\<open>\\<^medskip> Example: replication (polymorphic)\\<close>\n\ndefinition repl :: \"'n \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\n  where \"repl n x = rec [] (\\<lambda>_ xs. x # xs) n\"\n\nlemma repl_zero [simp]: \"repl zero x = []\"\n  and repl_succ [simp]: \"repl (succ n) x = x # repl n x\"\n  unfolding repl_def by simp_all\n\nlemma \"repl (succ (succ (succ zero))) True = [True, True, True]\"\n  by simp\n\nend\n\n\ntext \\<open>\\<^medskip> Just see that our abstract specification makes sense \\dots\\<close>\n\ninterpretation peano 0 Suc\nproof\n  fix m n\n  show \"Suc m \\<noteq> 0\" by simp\n  show \"Suc m = Suc n \\<longleftrightarrow> m = n\" by simp\n  show \"P n\"\n    if zero: \"P 0\"\n    and succ: \"\\<And>n. P n \\<Longrightarrow> P (Suc n)\"\n    for P\n  proof (induct n)\n    case 0\n    show ?case by (rule zero)\n  next\n    case Suc\n    then show ?case by (rule succ)\n  qed\nqed\n\nend\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/examples/src/HOL/ex/Peano_Axioms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218305645895, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.7959795654595615}}
{"text": "theory Range imports Main begin\n\n(* NLS-1 *)\ndefinition R :: \"(int \\<times> int) set\" where\n  \"R == { (x, y) | x y. x \\<le> y }\"\n\nlemma le_le_trans: \"\\<lbrakk> a \\<le> b; b \\<le> c \\<rbrakk> \\<Longrightarrow> a \\<le> c\" for type a::int\n  apply(rule leI)\n  apply(rule notI)\n  apply(drule_tac x=c and y=a and z=b in less_le_trans)\n  apply(assumption)\n  apply(drule_tac y=b in leD)\n  apply(erule notE)\n  apply(assumption)\n  done\n\n(* NLS-5 *)\ntheorem \"a > b \\<Longrightarrow> (a, b) \\<notin> R\"\n  apply(unfold R_def)\n  apply(rule notI)\n  apply(erule CollectE)\n  apply(elim exE)\n  apply(erule conjE)\n  apply(erule Pair_inject)\n  apply(drule_tac eq_refl)\n  apply(drule sym)\n  apply(drule_tac a=x and b=y and c=b in ord_le_eq_trans)\n  apply(assumption)\n  apply(drule_tac a=a and b=x and c=b in le_le_trans)\n  apply(assumption)\n  apply(drule_tac y=a in leD)\n  apply(erule notE)\n  apply(assumption)\n  done\n\nfun lower_endpoint :: \"(int \\<times> int) \\<Rightarrow> int\" where\n  \"lower_endpoint (x, y) = x\"\n\nfun upper_endpoint :: \"(int \\<times> int) \\<Rightarrow> int\" where\n  \"upper_endpoint (x, y) = y\"\n\n(* NLS-2 *)\ntheorem \"r \\<in> R \\<Longrightarrow> \\<exists>x. x = lower_endpoint r\"\n  apply(unfold R_def)\n  apply(erule CollectE)\n  apply(elim exE)\n  apply(drule conjunct1)\n  apply(erule ssubst)\n  apply(subst lower_endpoint.simps)\n  apply(rule_tac x=x in exI)\n  apply(rule refl)\n  done\n\n(* NLS-2 *)\ntheorem \"r \\<in> R \\<Longrightarrow> \\<exists>x. x = upper_endpoint r\"\n  apply(unfold R_def)\n  apply(erule CollectE)\n  apply(elim exE)\n  apply(drule conjunct1)\n  apply(erule ssubst)\n  apply(subst upper_endpoint.simps)\n  apply(rule_tac x=y in exI)\n  apply(rule refl)\n  done\n\nfun in_range :: \"int \\<Rightarrow> (int \\<times> int) \\<Rightarrow> bool\" where\n  \"in_range n (x, y) = (x \\<le> n \\<and> n \\<le> y)\"\n\n(* NLS-6 *)\ntheorem \"\\<forall>n. \\<forall>r \\<in> R. \\<exists>b. b = in_range n r\"\n  apply(unfold R_def)\n  apply(intro allI)\n  apply(rule ballI)\n  apply(erule CollectE)\n  apply(elim exE)\n  apply(erule conjE)\n  apply(erule ssubst)\n  apply(subst in_range.simps)\n  apply(rule_tac x=\"x \\<le> n \\<and> n \\<le> y\" in exI)\n  apply(rule refl)\n  done\n\n(* NLS-9 *)\nlemma example_3_8_in_R: \"(3, 8) \\<in> R\"\n  apply(unfold R_def)\n  apply(rule CollectI)\n  apply(rule_tac x=3 in exI)\n  apply(rule_tac x=8 in exI)\n  apply(rule conjI)\n  apply(rule refl)\n  apply(simp)\n  done\n\n(* NLS-10 *)\ntheorem \"lower_endpoint (3, 8) = 3\"\n  apply(subst lower_endpoint.simps)\n  apply(rule refl)\n  done\n\n(* NLS-10 *)\ntheorem \"upper_endpoint (3, 8) = 8\"\n  apply(subst upper_endpoint.simps)\n  apply(rule refl)\n  done\n\nfun char_of_digit :: \"nat \\<Rightarrow> char\" where\n  c0: \"char_of_digit 0 = CHR ''0''\" |\n  c1: \"char_of_digit (Suc 0) = CHR ''1''\" |\n  c2: \"char_of_digit (Suc (Suc 0)) = CHR ''2''\" |\n  c3: \"char_of_digit (Suc (Suc (Suc 0))) = CHR ''3''\" |\n  c4: \"char_of_digit (Suc (Suc (Suc (Suc 0)))) = CHR ''4''\" |\n  c5: \"char_of_digit (Suc (Suc (Suc (Suc (Suc 0))))) = CHR ''5''\" |\n  c6: \"char_of_digit (Suc (Suc (Suc (Suc (Suc (Suc 0)))))) = CHR ''6''\" |\n  c7: \"char_of_digit (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0))))))) = CHR ''7''\" |\n  c8: \"char_of_digit (Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0)))))))) = CHR ''8''\" |\n  c9: \"char_of_digit (Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0))))))))) = CHR ''9''\" |\n  \"char_of_digit _ = CHR ''?''\"\n\nfun string_of_nat :: \"nat \\<Rightarrow> string\" where\n  \"string_of_nat i = (if i < 10\n    then [char_of_digit i]\n    else (string_of_nat (i div 10)) @ [char_of_digit (i mod 10)])\"\n\nfun string_of_int :: \"int \\<Rightarrow> string\" where\n  \"string_of_int i = (if i > 0\n    then string_of_nat (nat i)\n    else (CHR ''-'') # (string_of_nat (nat \\<bar>i\\<bar>)))\"\n\nfun range_string :: \"(int \\<times> int) \\<Rightarrow> string\" where\n  \"range_string (a, b) = [CHR ''[''] @ (string_of_int a) @ [CHR '',''] @ (string_of_int b) @ [CHR '']'']\"\n\n(* NLS-3 *)\ntheorem stringify: \"r \\<in> R \\<Longrightarrow> \\<exists>s. s = range_string r\"\n  apply(unfold R_def)\n  apply(erule CollectE)\n  apply(elim exE)\n  apply(erule conjE)\n  apply(erule ssubst)\n  apply(rule_tac x=\"range_string (x, y)\" in exI)\n  apply(rule refl)\n  done\n\n(* NLS-4 *)\ntheorem stringify_3_8: \"range_string (3, 8) = ''[3,8]''\"\n  apply(unfold range_string.simps)\n  apply(unfold string_of_int.simps)\n  apply(simp)\n  apply(rule conjI)\n  apply(subgoal_tac \"3 = (Suc (Suc (Suc 0)))\")\n  apply(erule ssubst)\n  apply(rule c3)\n  apply(simp)\n  apply(subgoal_tac \"8 = (Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc 0))))))))\")\n  apply(erule ssubst)\n  apply(rule c8)\n  apply(simp)\n  done\n\n(* NLS-11, NLS-12 *)\ntheorem example_3_8: \"\\<lbrakk> r = (3, 8); E = { x | x. 3 \\<le> x \\<and> x \\<le> 8 } \\<rbrakk> \\<Longrightarrow>\n    \\<forall>n. n \\<in> E \\<longleftrightarrow> in_range n r\"\n  apply(elim ssubst)\n  apply(subst in_range.simps)\n  apply(rule allI)\n  apply(rule iffI)\n  apply(erule CollectE)\n  apply(erule exE)\n  apply(erule conjE)\n  apply(erule ssubst)\n  apply(assumption)\n  apply(rule CollectI)\n  apply(rule_tac x=n in exI)\n  apply(rule conjI)\n  apply(rule refl)\n  apply(assumption)\n  done\n\nfun range_eq :: \"(int \\<times> int) \\<Rightarrow> (int \\<times> int) \\<Rightarrow> bool\" where\n  \"range_eq (a1, a2) (b1, b2) = (a1 = b1 \\<and> a2 = b2)\"\n\n(* NLS-7 *)\ntheorem \"range_eq (a1, a2) (b1, b2) \\<Longrightarrow>\n    \\<forall>n. in_range n (a1, a2) \\<longleftrightarrow> in_range n (b1, b2)\"\n  apply(erule range_eq.elims)\n  apply(rule allI)\n  apply(erule conjE)\n  apply(elim Pair_inject)\n  apply(drule_tac r=a1 and s=a1a and t=b1a in trans)\n  apply(assumption)\n  apply(drule_tac r=a1 and s=b1a and t=b1 in trans_sym)\n  apply(assumption)\n  apply(drule_tac r=a2 and s=a2a and t=b2a in trans)\n  apply(assumption)\n  apply(drule_tac r=a2 and s=b2a and t=b2 in trans_sym)\n  apply(assumption)\n  apply(erule_tac t=b1 and s=a1 in subst)\n  apply(erule_tac t=b2 and s=a2 in subst)\n  apply(rule refl)\n  done\n\ntheorem range_eq_sym: \"range_eq (a1, a2) (b1, b2) \\<longleftrightarrow> range_eq (b1, b2) (a1, a2)\"\n  apply(subst range_eq.simps)\n  apply(subst range_eq.simps)\n  apply(rule iffI)\n  apply(erule conjE)\n  apply(erule subst)\n  apply(erule subst)\n  apply(rule conjI)\n  apply(rule refl)\n  apply(rule refl)\n  apply(erule conjE)\n  apply(erule subst)\n  apply(erule subst)\n  apply(rule conjI)\n  apply(rule refl)\n  apply(rule refl)\n  done\n\nlemma all_iffD: \"(\\<forall>x. P x \\<longleftrightarrow> Q x) \\<Longrightarrow> (\\<forall>x. P x \\<longrightarrow> Q x) \\<and> (\\<forall>x. Q x \\<longrightarrow> P x)\"\n  apply(rule conjI)\n  apply(rule allI)\n  apply(erule_tac x=x in allE)\n  apply(erule iffE)\n  apply(assumption)\n  apply(rule allI)\n  apply(erule_tac x=x in allE)\n  apply(erule iffE)\n  apply(assumption)\n  done\n\nlemma range_uniq: \"\\<lbrakk> a1 \\<le> a2; b1 \\<le> b2; \\<forall>n. (a1 \\<le> n \\<and> n \\<le> a2) \\<longleftrightarrow> (b1 \\<le> n \\<and> n \\<le> b2) \\<rbrakk> \\<Longrightarrow> a1 = b1 \\<and> a2 = b2\" for a1::int and a2::int and b1::int and b2::int\n  apply(drule all_iffD)\n  apply(erule conjE)\n  apply(rule conjI)\n  apply(erule_tac x=a1 in allE)\n  apply(erule impE)\n  apply(rule conjI)\n  apply(rule order_refl)\n  apply(assumption)\n  apply(erule conjE)\n  apply(erule_tac x=b1 in allE)\n  apply(erule impE)\n  apply(rule conjI)\n  apply(rule order_refl)\n  apply(assumption)\n  apply(erule conjE)\n  apply(erule antisym)\n  apply(assumption)\n  apply(erule_tac x=a2 in allE)\n  apply(erule impE)\n  apply(erule conjI)\n  apply(rule order_refl)\n  apply(erule_tac x=b2 in allE)\n  apply(erule impE)\n  apply(erule conjI)\n  apply(rule order_refl)\n  apply(elim conjE)\n  apply(erule antisym)\n  apply(assumption)\n  done\n\ntheorem in_range_uniq: \"\\<forall>r1 \\<in> R. \\<forall>r2 \\<in> R.\n    r1 = (a1, a2) \\<and> r2 = (b1, b2)\n    \\<longrightarrow> (\\<forall>n. in_range n (a1, a2) \\<longleftrightarrow> in_range n (b1, b2))\n    \\<longrightarrow> range_eq (a1, a2) (b1, b2)\"\n  apply(unfold R_def)\n  apply(subst range_eq.simps)\n  apply(subst in_range.simps)\n  apply(subst in_range.simps)\n  apply(intro ballI)\n  apply(intro impI)\n  apply(elim conjE)\n  apply(drule_tac a=r1 and b=\"(a1, a2)\" in back_subst)\n  apply(assumption)\n  apply(drule_tac a=r2 and b=\"(b1, b2)\" in back_subst)\n  apply(assumption)\n  apply(elim CollectE)\n  apply(elim exE)\n  apply(elim conjE)\n  apply(elim Pair_inject)\n  apply(drule_tac a=a1 and b=x and c=y in ord_eq_le_trans)\n  apply(assumption)\n  apply(drule_tac a=a1 and b=y and c=a2 in ord_le_eq_trans)\n  apply(erule sym)\n  apply(drule_tac a=b1 and b=xa and c=ya in ord_eq_le_trans)\n  apply(assumption)\n  apply(drule_tac a=b1 and b=ya and c=b2 in ord_le_eq_trans)\n  apply(erule sym)\n  apply(erule range_uniq)\n  apply(assumption)\n  apply(assumption)\n  done\n\nfun range_contains :: \"(int \\<times> int) \\<Rightarrow> (int \\<times> int) \\<Rightarrow> bool\" where\n  \"range_contains (a1, a2) (b1, b2) = (a1 \\<le> b1 \\<and> b2 \\<le> a2)\"\n\n(* NLS-8 *)\ntheorem \"range_contains (a1, a2) (b1, b2) \\<Longrightarrow>\n    \\<forall>n. in_range n (b1, b2) \\<longrightarrow> in_range n (a1, a2)\"\n  apply(unfold in_range.simps)\n  apply(erule range_contains.elims)\n  apply(elim Pair_inject)\n  apply(rule allI)\n  apply(rule impI)\n  apply(elim conjE)\n  apply(rule conjI)\n  apply(erule ssubst)\n  apply(drule_tac s=b2 in sym)\n  apply(drule_tac s=b1 in sym)\n  apply(drule_tac x=b1a in eq_refl)\n  apply(erule_tac a=a1 and b=b1a and c=n in le_le_trans)\n  apply(erule_tac b=b1 and c=n in le_le_trans)\n  apply(assumption)\n  apply(drule_tac s=b2 in sym)\n  apply(drule_tac s=b2 and P=\"\\<lambda>b2. n \\<le> b2\" in ssubst)\n  apply(assumption)\n  apply(drule_tac a=n and b=b2a and c=a2a in le_le_trans)\n  apply(assumption)\n  apply(erule_tac t=a2 in ssubst)\n  apply(assumption)\n  done\n\ntheorem range_contains_antisym: \"range_contains (a1, a2) (b1, b2) \\<and> range_contains (b1, b2) (a1, a2) \\<longleftrightarrow> range_eq (a1, a2) (b1, b2)\"\n  apply(subst range_contains.simps)\n  apply(subst range_contains.simps)\n  apply(subst range_eq.simps)\n  apply(rule iffI)\n  apply(elim conjE)\n  apply(rule conjI)\n  apply(erule antisym)\n  apply(assumption)\n  apply(erule_tac x=a2 in antisym)\n  apply(assumption)\n  apply(erule conjE)\n  apply(rule conjI)\n  apply(erule subst)\n  apply(erule subst)\n  apply(rule conjI)\n  apply(rule order_refl)\n  apply(rule order_refl)\n  apply(erule subst)\n  apply(erule subst)\n  apply(rule conjI)\n  apply(rule order_refl)\n  apply(rule order_refl)\n  done\n", "meta": {"author": "Kuniwak", "repo": "isabelle-range", "sha": "79e76247112c1c13e6c83ba6c41a7d4d1fab546d", "save_path": "github-repos/isabelle/Kuniwak-isabelle-range", "path": "github-repos/isabelle/Kuniwak-isabelle-range/isabelle-range-79e76247112c1c13e6c83ba6c41a7d4d1fab546d/Range.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.88242786954645, "lm_q1q2_score": 0.7958799341108034}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Omega\\<close>\n\ntheory OrdinalOmega\nimports OrdinalFix\nbegin\n\nsubsection \\<open>Embedding naturals in the ordinals\\<close>\n\nprimrec ordinal_of_nat :: \"nat \\<Rightarrow> ordinal\"\nwhere\n  \"ordinal_of_nat 0 = 0\"\n| \"ordinal_of_nat (Suc n) = oSuc (ordinal_of_nat n)\"\n\nlemma strict_mono_ordinal_of_nat: \"strict_mono ordinal_of_nat\"\nby (rule strict_mono_natI, simp)\n\nlemma not_limit_ordinal_nat: \"\\<not> limit_ordinal (ordinal_of_nat n)\"\nby (induct n) simp_all\n\nlemma ordinal_of_nat_eq [simp]:\n\"(ordinal_of_nat x = ordinal_of_nat y) = (x = y)\"\nby (rule strict_mono_cancel_eq[OF strict_mono_ordinal_of_nat])\n\nlemma ordinal_of_nat_less [simp]:\n\"(ordinal_of_nat x < ordinal_of_nat y) = (x < y)\"\nby (rule strict_mono_cancel_less[OF strict_mono_ordinal_of_nat])\n\nlemma ordinal_of_nat_le [simp]:\n\"(ordinal_of_nat x \\<le> ordinal_of_nat y) = (x \\<le> y)\"\nby (rule strict_mono_cancel_le[OF strict_mono_ordinal_of_nat])\n\nlemma ordinal_of_nat_plus [simp]:\n\"ordinal_of_nat x + ordinal_of_nat y = ordinal_of_nat (x + y)\"\nby (induct y) simp_all\n\nlemma ordinal_of_nat_times [simp]:\n\"ordinal_of_nat x * ordinal_of_nat y = ordinal_of_nat (x * y)\"\nby (induct y) (simp_all add: add.commute)\n\nlemma ordinal_of_nat_exp [simp]:\n\"ordinal_of_nat x ** ordinal_of_nat y = ordinal_of_nat (x ^ y)\"\nby (induct y, cases x) (simp_all add: mult.commute)\n\nlemma oSuc_plus_ordinal_of_nat:\n\"oSuc x + ordinal_of_nat n = oSuc (x + ordinal_of_nat n)\"\nby (induct n) simp_all\n\nlemma less_ordinal_of_nat:\n\"(x < ordinal_of_nat n) = (\\<exists>m. x = ordinal_of_nat m \\<and> m < n)\"\n apply (induct n)\n  apply simp\n apply (safe, simp_all del: ordinal_of_nat.simps)\n apply (auto elim: less_oSucE)\ndone\n\nlemma le_ordinal_of_nat:\n\"(x \\<le> ordinal_of_nat n) = (\\<exists>m. x = ordinal_of_nat m \\<and> m \\<le> n)\"\nby (auto simp add: order_le_less less_ordinal_of_nat)\n\n\nsubsection \\<open>Omega, the least limit ordinal\\<close>\n\ndefinition\n  omega :: \"ordinal\"  (\"\\<omega>\") where\n  \"omega = oLimit ordinal_of_nat\"\n\nlemma less_omegaD: \"x < \\<omega> \\<Longrightarrow> \\<exists>n. x = ordinal_of_nat n\"\n apply (unfold omega_def)\n apply (drule less_oLimitD)\n apply (clarsimp simp add: less_ordinal_of_nat)\ndone\n\nlemma omega_leI: \"\\<forall>n. ordinal_of_nat n \\<le> x \\<Longrightarrow> \\<omega> \\<le> x\"\nby (unfold omega_def, erule oLimit_leI)\n\nlemma nat_le_omega [simp]: \"ordinal_of_nat n \\<le> \\<omega>\"\nby (unfold omega_def, rule le_oLimit)\n\nlemma nat_less_omega [simp]: \"ordinal_of_nat n < \\<omega>\"\n apply (rule_tac y=\"ordinal_of_nat (Suc n)\" in order_less_le_trans, simp)\n apply (rule nat_le_omega)\ndone\n\nlemma zero_less_omega [simp]: \"0 < \\<omega>\"\nby (cut_tac n=0 in nat_less_omega, simp)\n\nlemma limit_ordinal_omega: \"limit_ordinal \\<omega>\"\n apply (rule limit_ordinalI[rule_format], simp)\n apply (drule less_omegaD, clarify)\n apply (subgoal_tac \"ordinal_of_nat (Suc n) < \\<omega>\", simp)\n apply (simp only: nat_less_omega)\ndone\n\nlemma Least_limit_ordinal: \"(LEAST x. limit_ordinal x) = \\<omega>\"\n apply (rule Least_equality)\n  apply (rule limit_ordinal_omega)\n apply (erule contrapos_pp)\n apply (simp add: linorder_not_le)\n apply (drule less_omegaD, erule exE)\n apply (simp add: not_limit_ordinal_nat)\ndone\n\nlemma \"range f = range ordinal_of_nat \\<Longrightarrow> oLimit f = \\<omega>\"\n apply (rule order_antisym)\n  apply (rule oLimit_leI, clarify)\n  apply (drule equalityD1)\n  apply (drule_tac c=\"f n\" in subsetD, simp)\n  apply clarsimp\n apply (rule omega_leI, clarify)\n apply (drule equalityD2)\n apply (drule_tac c=\"ordinal_of_nat n\" in subsetD, simp)\n apply clarsimp\ndone\n\n\nsubsection \\<open>Arithmetic properties of @{term \\<omega>}\\<close>\n\nlemma oSuc_less_omega [simp]: \"(oSuc x < \\<omega>) = (x < \\<omega>)\"\nby (rule oSuc_less_limit_ordinal[OF limit_ordinal_omega])\n\nlemma oSuc_plus_omega [simp]: \"oSuc x + \\<omega> = x + \\<omega>\"\n apply (simp add: omega_def)\n apply (rule oLimit_eqI)\n  apply (rule_tac x=\"Suc n\" in exI)\n  apply (simp add: oSuc_plus_ordinal_of_nat)\n apply (rule_tac x=n in exI)\n apply (simp add: oSuc_plus_ordinal_of_nat order_less_imp_le)\ndone\n\nlemma ordinal_of_nat_plus_omega [simp]:\n\"ordinal_of_nat n + \\<omega> = \\<omega>\"\nby (induct n) simp_all\n\nlemma ordinal_of_nat_times_omega [simp]:\n\"0 < k \\<Longrightarrow> ordinal_of_nat k * \\<omega> = \\<omega>\"\n apply (simp add: omega_def)\n apply (rule oLimit_eqI)\n  apply (rule_tac exI, rule order_refl)\n apply (rule_tac x=n in exI, simp)\ndone\n\nlemma ordinal_plus_times_omega: \"x + x * \\<omega> = x * \\<omega>\"\n apply (subgoal_tac \"x + x * \\<omega> = x * (1 + \\<omega>)\", simp)\n apply (simp del: oSuc_plus_omega add: ordinal_times_distrib)\ndone\n\nlemma ordinal_plus_absorb: \"x * \\<omega> \\<le> y \\<Longrightarrow> x + y = y\"\n apply (drule ordinal_plus_minus2)\n apply (erule subst)\n apply (simp only: ordinal_plus_assoc[symmetric] ordinal_plus_times_omega)\ndone\n\nlemma ordinal_less_plusL: \"y < x * \\<omega> \\<Longrightarrow> y < x + y\"\n apply (case_tac \"x = 0\", simp_all)\n apply (drule ordinal_div_less)\n apply (drule less_omegaD, clarify)\n apply (rule_tac y=\"x * (1 + ordinal_of_nat n)\" in order_less_le_trans)\n  apply (simp add: oSuc_plus_ordinal_of_nat)\n  apply (erule subst)\n  apply (erule ordinal_less_times_div_plus)\n apply (simp add: ordinal_times_distrib)\n apply (erule subst)\n apply (rule ordinal_times_div_le)\ndone\n\nlemma ordinal_plus_absorb_iff: \"(x + y = y) = (x * \\<omega> \\<le> y)\"\n apply safe\n  apply (rule ccontr, simp add: linorder_not_le)\n  apply (drule ordinal_less_plusL, simp)\n apply (erule ordinal_plus_absorb)\ndone\n\nlemma ordinal_less_plusL_iff: \"(y < x + y) = (y < x * \\<omega>)\"\n apply safe\n  apply (rule ccontr, simp add: linorder_not_less)\n  apply (drule ordinal_plus_absorb, simp)\n apply (erule ordinal_less_plusL)\ndone\n\n\nsubsection \\<open>Additive principal ordinals\\<close>\n\nlocale additive_principal =\n  fixes a :: ordinal\n  assumes not_0:  \"0 < a\"\n  assumes sum_eq: \"\\<And>b. b < a \\<Longrightarrow> b + a = a\"\n\nlemma (in additive_principal) sum_less:\n\"\\<lbrakk>x < a; y < a\\<rbrakk> \\<Longrightarrow> x + y < a\"\nby (drule sum_eq, erule subst, simp)\n\nlemma (in additive_principal) times_nat_less:\n\"x < a \\<Longrightarrow> x * ordinal_of_nat n < a\"\n apply (induct_tac n)\n  apply (simp add: not_0)\n apply (simp add: sum_less)\ndone\n\nlemma not_additive_principal_0: \"\\<not> additive_principal 0\"\nby (clarify, drule additive_principal.not_0, simp)\n\nlemma additive_principal_oSuc:\n\"additive_principal (oSuc a) = (a = 0)\"\n apply safe\n  apply (rule ccontr, simp)\n  apply (subgoal_tac \"a + oSuc 0 < oSuc a\", simp)\n  apply (erule additive_principal.sum_less, simp_all)\n apply (simp add: additive_principal_def)\ndone\n\nlemma additive_principal_intro2 [rule_format]:\nassumes not_0: \"0 < a\"\nshows \"(\\<forall>x<a. \\<forall>y<a. x + y < a) \\<longrightarrow> additive_principal a\"\n apply (simp add: additive_principal_def not_0)\n apply (rule_tac a=a in oLimit_induct)\n   apply simp\n  apply clarsimp\n  apply (drule_tac x=x in spec, simp)\n  apply (drule_tac x=1 in spec, simp)\n  apply (simp add: linorder_not_less)\n apply clarsimp\n apply (rule order_antisym)\n  apply (rule oLimit_leI, clarify)\n  apply (rule order_less_imp_le)\n  apply (simp add: strict_mono_less_oLimit)\n apply (rule oLimit_leI, clarify)\n apply (rule_tac n=n in le_oLimitI)\n apply (rule ordinal_le_plusL)\ndone\n\nlemma additive_principal_1: \"additive_principal (oSuc 0)\"\nby (simp add: additive_principal_def)\n\nlemma additive_principal_omega: \"additive_principal \\<omega>\"\n apply (rule additive_principal.intro)\n  apply (rule zero_less_omega)\n apply (drule less_omegaD, clarify)\n apply (rule ordinal_of_nat_plus_omega)\ndone\n\nlemma additive_principal_times_omega:\n\"0 < x \\<Longrightarrow> additive_principal (x * \\<omega>)\"\n apply (rule additive_principal.intro)\n  apply simp\n apply (simp add: omega_def)\n apply (drule less_oLimitD, clarify, rename_tac k)\n apply (drule_tac x=b in order_less_imp_le)\n apply (rule oLimit_eqI)\n  apply (rule_tac x=\"k + n\" in exI)\n  apply (erule order_trans[OF ordinal_plus_monoL])\n  apply (simp add: ordinal_times_distrib[symmetric])\n apply (rule_tac x=n in exI, simp)\ndone\n\nlemma additive_principal_oLimit:\n\"\\<forall>n. additive_principal (f n) \\<Longrightarrow> additive_principal (oLimit f)\"\n apply (rule additive_principal.intro)\n  apply (rule_tac n=0 in less_oLimitI)\n  apply (simp add: additive_principal.not_0)\n apply simp\n apply (drule less_oLimitD, clarify, rename_tac k)\n apply (rule oLimit_eqI)\n  apply (rule_tac x=\"f n\" and y = \"f k\" in linorder_le_cases)\n   apply (rule_tac x=k in exI)\n   apply (rule_tac y=\"b + f k\" in order_trans, simp)\n   apply (simp add: additive_principal.sum_eq)\n  apply (rule_tac x=n in exI)\n  apply (drule order_less_le_trans, assumption)\n  apply (simp add: additive_principal.sum_eq)\n apply (rule_tac x=n in exI, simp)\ndone\n\nlemma additive_principal_omega_exp: \"additive_principal (\\<omega> ** x)\"\n apply (rule_tac a=x in oLimit_induct)\n   apply (simp add: additive_principal_1)\n  apply (simp add: additive_principal_times_omega)\n apply (simp add: additive_principal_oLimit)\ndone\n\nlemma (in additive_principal) omega_exp: \"\\<exists>x. a = \\<omega> ** x\"\n apply (subgoal_tac \"\\<exists>x. \\<omega> ** x \\<le> a \\<and> a < \\<omega> ** (oSuc x)\")\n  prefer 2\n  apply (rule normal.oInv_ex)\n   apply (rule normal_exp, simp)\n  apply (simp add: oSuc_le_eq_less not_0)\n apply (auto simp add: order_le_less)\n apply (subgoal_tac \"a < a\", simp)\n apply (rule order_less_trans)\n  apply (rule_tac y=\"\\<omega> ** x\" in ordinal_less_times_div_plus)\n  apply simp\n apply (drule ordinal_div_less)\n apply (drule less_omegaD, clarify)\n apply (drule_tac n=\"Suc n\" in times_nat_less)\n apply simp\ndone\n\nlemma additive_principal_iff:\n\"additive_principal a = (\\<exists>x. a = \\<omega> ** x)\"\nby (auto intro: additive_principal_omega_exp\n                additive_principal.omega_exp)\n\nlemma absorb_omega_exp:\n\"x < \\<omega> ** a \\<Longrightarrow> x + \\<omega> ** a = \\<omega> ** a\"\nby (rule additive_principal.sum_eq[OF additive_principal_omega_exp])\n\nlemma absorb_omega_exp2: \"a < b \\<Longrightarrow> \\<omega> ** a + \\<omega> ** b = \\<omega> ** b\"\nby (rule absorb_omega_exp, simp add: ordinal_exp_strict_monoR)\n\n\nsubsection \\<open>Cantor normal form\\<close>\n\nlemma cnf_lemma: \"x > 0 \\<Longrightarrow> x - \\<omega> ** oLog \\<omega> x < x\"\n  apply (subst ordinal_minus_less_eq)\n   apply (erule ordinal_exp_oLog_le, simp)\n  apply (rule ordinal_less_plusL)\n  apply (rule ordinal_less_exp_oLog, simp)\n  done\n\nprimrec from_cnf where\n  \"from_cnf []       = 0\"\n  | \"from_cnf (x # xs) = \\<omega> ** x + from_cnf xs\"\n\nfunction to_cnf where\n [simp del]: \"to_cnf x = (if x = 0 then [] else\n    oLog \\<omega> x # to_cnf (x - \\<omega> ** oLog \\<omega> x))\"\nby pat_completeness auto\n\ntermination by (relation \"{(x, y). x < y}\")\n  (simp_all add: wf cnf_lemma)\n\nlemma to_cnf_0 [simp]: \"to_cnf 0 = []\"\nby (simp add: to_cnf.simps)\n\nlemma to_cnf_not_0:\n\"0 < x \\<Longrightarrow> to_cnf x = oLog \\<omega> x # to_cnf (x - \\<omega> ** oLog \\<omega> x)\"\nby (simp add: to_cnf.simps[of x])\n\nlemma to_cnf_eq_Cons: \"to_cnf x = a # list \\<Longrightarrow> a = oLog \\<omega> x\"\nby (case_tac \"x = 0\", simp, simp add: to_cnf_not_0)\n\nlemma to_cnf_inverse: \"from_cnf (to_cnf x) = x\"\n apply (rule wf_induct[OF wf], simp)\n apply (case_tac \"x = 0\", simp_all)\n apply (simp add: to_cnf_not_0)\n apply (simp add: cnf_lemma)\n apply (rule ordinal_plus_minus2)\n apply (erule ordinal_exp_oLog_le, simp)\ndone\n\nprimrec normalize_cnf where\n  normalize_cnf_Nil: \"normalize_cnf [] = []\"\n  | normalize_cnf_Cons: \"normalize_cnf (x # xs) =\n      (case xs of [] \\<Rightarrow> [x] | y # ys \\<Rightarrow>\n        (if x < y then [] else [x]) @ normalize_cnf xs)\"\n\nlemma from_cnf_normalize_cnf: \"from_cnf (normalize_cnf xs) = from_cnf xs\"\n apply (induct_tac xs, simp_all)\n apply (case_tac list, simp, clarsimp simp del: normalize_cnf_Cons)\n apply (simp add: ordinal_plus_assoc[symmetric] absorb_omega_exp2)\ndone\n\nlemma normalize_cnf_to_cnf: \"normalize_cnf (to_cnf x) = to_cnf x\"\n apply (rule_tac a=x in wf_induct[OF wf], simp)\n apply (case_tac \"x = 0\", simp_all)\n apply (drule spec, drule mp, erule cnf_lemma)\n apply (simp add: to_cnf_not_0)\n apply (case_tac \"to_cnf (x - \\<omega> ** oLog \\<omega> x)\", simp_all)\n apply (drule to_cnf_eq_Cons, simp add: linorder_not_less)\n apply (rule ordinal_oLog_monoR)\n apply (rule order_less_imp_le)\n apply (erule cnf_lemma)\ndone\n\n\ntext \"alternate form of CNF\"\n\nlemma cnf2_lemma:\n\"0 < x \\<Longrightarrow> x mod \\<omega> ** oLog \\<omega> x < x\"\n apply (rule order_less_le_trans)\n  apply (rule ordinal_mod_less, simp)\n apply (erule ordinal_exp_oLog_le, simp)\ndone\n\nprimrec from_cnf2 where\n  \"from_cnf2 []       = 0\"\n  | \"from_cnf2 (x # xs) = \\<omega> ** fst x * ordinal_of_nat (snd x) + from_cnf2 xs\"\n\nfunction to_cnf2 where\n  [simp del]: \"to_cnf2 x = (if x = 0 then [] else\n    (oLog \\<omega> x, inv ordinal_of_nat (x div (\\<omega> ** oLog \\<omega> x)))\n      # to_cnf2 (x mod (\\<omega> ** oLog \\<omega> x)))\"\nby pat_completeness auto\n\ntermination by (relation \"{(x,y). x < y}\")\n  (simp_all add: wf cnf2_lemma)\n\nlemma to_cnf2_0 [simp]: \"to_cnf2 0 = []\"\nby (simp add: to_cnf2.simps)\n\nlemma to_cnf2_not_0:\n\"0 < x \\<Longrightarrow> to_cnf2 x =\n  (oLog \\<omega> x, inv ordinal_of_nat (x div (\\<omega> ** oLog \\<omega> x)))\n     # to_cnf2 (x mod (\\<omega> ** oLog \\<omega> x))\"\nby (simp add: to_cnf2.simps[of x])\n\nlemma to_cnf2_eq_Cons: \"to_cnf2 x = (a,b) # list \\<Longrightarrow> a = oLog \\<omega> x\"\nby (case_tac \"x = 0\", simp, simp add: to_cnf2_not_0)\n\nlemma ordinal_of_nat_of_ordinal:\n\"x < \\<omega> \\<Longrightarrow> ordinal_of_nat (inv ordinal_of_nat x) = x\"\n apply (rule f_inv_into_f)\n apply (simp add: image_def)\n apply (erule less_omegaD)\ndone\n\nlemma to_cnf2_inverse: \"from_cnf2 (to_cnf2 x) = x\"\n apply (rule wf_induct[OF wf], simp)\n apply (case_tac \"x = 0\", simp_all)\n apply (simp add: to_cnf2_not_0)\n apply (simp add: cnf2_lemma)\n apply (drule_tac x=\"x mod \\<omega> ** oLog \\<omega> x\" in spec)\n apply (simp add: cnf2_lemma)\n apply (subst ordinal_of_nat_of_ordinal)\n  apply (rule ordinal_div_less)\n  apply (rule ordinal_less_exp_oLog, simp)\n apply (rule ordinal_div_plus_mod)\ndone\n\nprimrec is_normalized2 where\n  is_normalized2_Nil: \"is_normalized2 [] = True\"\n  | is_normalized2_Cons: \"is_normalized2 (x # xs) =\n      (case xs of [] \\<Rightarrow> True | y # ys \\<Rightarrow> fst y < fst x \\<and> is_normalized2 xs)\"\n\nlemma is_normalized2_to_cnf2: \"is_normalized2 (to_cnf2 x)\"\n apply (rule_tac a=x in wf_induct[OF wf], simp)\n apply (case_tac \"x = 0\", simp_all)\n apply (drule spec, drule mp, erule cnf2_lemma)\n apply (simp add: to_cnf2_not_0)\n apply (case_tac \"x mod \\<omega> ** oLog \\<omega> x = 0\", simp_all)\n apply (case_tac \"to_cnf2 (x mod \\<omega> ** oLog \\<omega> x)\", simp_all)\n apply (case_tac a, simp)\n apply (drule to_cnf2_eq_Cons, simp)\n apply (erule ordinal_oLog_less, simp)\n apply (rule ordinal_mod_less, simp)\ndone\n\n\nsubsection \\<open>Epsilon 0\\<close>\n\ndefinition epsilon0 :: ordinal  (\"\\<epsilon>\\<^sub>0\") where\n  \"epsilon0 = oFix ((**) \\<omega>) 0\"\n\nlemma less_omega_exp: \"x < \\<epsilon>\\<^sub>0 \\<Longrightarrow> x < \\<omega> ** x\"\n apply (unfold epsilon0_def)\n apply (erule less_oFix_0D)\n apply (rule continuous.mono)\n apply (rule continuous_exp)\n apply (rule zero_less_omega)\ndone\n\nlemma omega_exp_epsilon0: \"\\<omega> ** \\<epsilon>\\<^sub>0 = \\<epsilon>\\<^sub>0\"\n apply (unfold epsilon0_def)\n apply (rule oFix_fixed)\n  apply (rule continuous_exp)\n  apply (rule zero_less_omega)\n apply simp\ndone\n\nlemma oLog_omega_less: \"\\<lbrakk>0 < x; x < \\<epsilon>\\<^sub>0\\<rbrakk> \\<Longrightarrow> oLog \\<omega> x < x\"\n apply (erule ordinal_oLog_less)\n  apply simp\n apply (erule less_omega_exp)\ndone\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Ordinal/OrdinalOmega.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.7957557424866454}}
{"text": "(*********************************************************************** \n* HiVe theory files\n* \n* Copyright (C) 2015 Commonwealth of Australia as represented by Defence Science and Technology \n* Group (DST Group)\n* \n* All rights reserved.\n*\n* The HiVe theory files are free software: released for redistribution and use, and/or modification,\n* under the BSD License, details of which can be found in the LICENSE file included in the \n* distribution. \n************************************************************************)\n\ntheory Metric_Class\n \nimports \n  Metric_Locale\n\nbegin\n\ntext {*\nThis theory introduces the metric space class.\n%We include instance results here -- largely because it is a small theory but also because the fact that the reals is a metri%c space is a natural result to show continuity of the distance function.\n%It might be that later this should be rationalised into the Metric_Topology theory, but it might also be nice to keep some clean results separately.\n\n\nA metric space has a distance function between its elements.\n\n*}\n\nclass dist =\n  fixes\n    distance :: \"['a, 'a] \\<rightarrow> \\<real>\"\n\nnotation (xsymbols output)\n  distance (\"\\<rho>'(_, _')\")\n\nnotation (zed)\n  distance (\"\\<^mcdist>{:_:}{:_:}\") \n\nclass metric = dist +\nassumes\n  class_nonneg: \"0 \\<le> \\<^mcdist>{:x:}{:y:}\" and\n  class_refl: \"\\<^mcdist>{:x:}{:y:} = 0 \\<Leftrightarrow> x = y\"  and \n  class_sym: \"\\<^mcdist>{:x:}{:y:} = \\<^mcdist>{:y:}{:x:}\" and\n  class_subadd: \"\\<^mcdist>{:x:}{:z:} \\<le> \\<^mcdist>{:x:}{:y:} + \\<^mcdist>{:y:}{:z:}\"\nbegin\n\n  lemma class_zero_dist: \n  shows \"\\<^mcdist>{:x:}{:x:} = 0\"\n  by (auto simp add: class_refl)\n\n\n  lemma metric_class_diff_triangle:\n  \"abs (\\<^mcdist>{:x:}{:z:} - \\<^mcdist>{:y:}{:z:})\\<le> \\<^mcdist>{:x:}{:y:}\"\n  proof-\n    have\n    \"\\<^mcdist>{:x:}{:z:} \\<le> \\<^mcdist>{:x:}{:y:} + \\<^mcdist>{:y:}{:z:}\"\n    by (rule class_subadd)\n    then have R1:\n    \"\\<^mcdist>{:x:}{:z:} - \\<^mcdist>{:y:}{:z:} \\<le> \\<^mcdist>{:x:}{:y:}\"\n    by auto\n    have\n    \"\\<^mcdist>{:z:}{:y:} \\<le> \\<^mcdist>{:z:}{:x:} + \\<^mcdist>{:x:}{:y:}\"\n    by (rule class_subadd)\n    then have\n    \"- \\<^mcdist>{:x:}{:y:} \\<le> \\<^mcdist>{:z:}{:x:} - \\<^mcdist>{:z:}{:y:}\"\n    by auto\n    then have R2:\n    \"- \\<^mcdist>{:x:}{:y:} \\<le> \\<^mcdist>{:x:}{:z:} - \\<^mcdist>{:y:}{:z:}\"\n    by (auto simp add: class_sym)\n    from R1 R2 show\n      ?thesis\n    by (auto simp add: abs_if)\n  qed\n  \nend\n\nlemmas metric_class_defs = class_nonneg class_refl class_sym class_subadd class_zero_dist\n  \ntheorem metric_classI:\n  assumes \n    a1: \"\\<^metricspace>{:\\<univ>-[('a::dist)]:}{:distance:}\"\n  shows \n  \"OFCLASS('a::dist, metric_class)\"\n  apply (intro_classes)\n  apply (auto intro!: \n         metric_space.nonneg [OF a1]\n         metric_space.strict [OF a1]\n         metric_space.symmetric [OF a1]\n         metric_space.subadd [OF a1])\ndone\n\nlemma metric_classD:\n  \"\\<^metricspace>{:\\<univ>-[('a::metric)]:}{:distance:}\"\n  apply (unfold_locales)\n  apply simp\n  apply (intro metric_class_defs)+\ndone\n\n\nend\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mccartjg", "repo": "HiVe", "sha": "0dd4e0f4ca1dd1ce605b5a5c998b9adb619dc58e", "save_path": "github-repos/isabelle/mccartjg-HiVe", "path": "github-repos/isabelle/mccartjg-HiVe/HiVe-0dd4e0f4ca1dd1ce605b5a5c998b9adb619dc58e/isa_13-2/mathKit/Metric_Class.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.8757869997529962, "lm_q1q2_score": 0.7957557375423585}}
{"text": "(*\n    $Id: sol.thy,v 1.3 2011/06/28 18:11:37 webertj Exp $\n    Author: Gerwin Klein\n*)\n\nheader {* Sorting with Lists and Trees *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {*\n  For simplicity we sort natural numbers.\n*}\n\nsubsubsection {* Sorting with lists *}\n\ntext {*\n  The task is to define insertion sort and prove its correctness.  The\n  following functions are required:\n\n  @{text \"insort :: nat \\<Rightarrow> nat list \\<Rightarrow> nat list\"}\\\\\n  @{text \"sort   :: nat list \\<Rightarrow> nat list\"}\\\\\n  @{text \"le     :: nat \\<Rightarrow> nat list \\<Rightarrow> bool\"}\\\\\n  @{text \"sorted :: nat list \\<Rightarrow> bool\"}\n\n  In your definition, @{term \"insort x xs\"} should insert a number @{term x}\n  into an already sorted list @{text xs}, and @{term \"sort ys\"} should build on\n  @{text insort} to produce the sorted version of @{text ys}.\n\n  To show that the resulting list is indeed sorted we need a predicate @{term\n  sorted} that checks if each element in the list is less or equal to the\n  following ones; @{term \"le n xs\"} should be true iff @{term n} is less or\n  equal to all elements of @{text xs}.\n*}\n\nprimrec le :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"le a []     = True\"\n| \"le a (x#xs) = (a <= x & le a xs)\"\n\nprimrec sorted :: \"nat list \\<Rightarrow> bool\" where\n  \"sorted []     = True\"\n| \"sorted (x#xs) = (le x xs & sorted xs)\"\n\nprimrec insort :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"insort a []     = [a]\"\n| \"insort a (x#xs) = (if a <= x then a#x#xs else x # insort a xs)\"\n\nprimrec sort :: \"nat list \\<Rightarrow> nat list\" where\n  \"sort []     = []\"\n| \"sort (x#xs) = insort x (sort xs)\"\n\n\ntext {*\n  Start out by showing a monotonicity property of @{term le}.  For technical\n  reasons the lemma should be phrased as follows:\n*}\n\n\n\n\ntext {*\n  Now show the following correctness theorem:\n*}\n\nlemma [simp]: \n  \"le x (insort a xs) = (x <= a & le x xs)\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\nlemma [simp]:\n  \"sorted (insort a xs) = sorted xs\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\ntheorem \"sorted (sort xs)\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\n\ntext {*\n  This theorem alone is too weak.  It does not guarantee that the sorted list\n  contains the same elements as the input.  In the worst case, @{term sort}\n  might always return @{term\"[]\"}~-- surely an undesirable implementation of\n  sorting.\n\n  Define a function @{term \"count xs x\"} that counts how often @{term x} occurs\n  in @{term xs}.\n*}\n\nprimrec count :: \"nat list => nat => nat\" where\n  \"count []     y = 0\"\n| \"count (x#xs) y = (if x=y then Suc(count xs y) else count xs y)\"\n\n\ntext {*\n  Show that\n*}\n\nlemma [simp]:\n  \"count (insort x xs) y =\n  (if x=y then Suc (count xs y) else count xs y)\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\ntheorem \"count (sort xs) x = count xs x\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\n\nsubsubsection {* Sorting with trees *}\n\ntext {*\n  Our second sorting algorithm uses trees.  Thus you should first define a data\n  type @{text bintree} of binary trees that are either empty or consist of a\n  node carrying a natural number and two subtrees.\n*}\n\ndatatype bintree = Empty | Node nat bintree bintree\n\n\ntext {*\n  Define a function @{text tsorted} that checks if a binary tree is sorted.  It\n  is convenient to employ two auxiliary functions @{text tge}/@{text tle} that\n  test whether a number is greater-or-equal/less-or-equal to all elements of a\n  tree.\n\n  Finally define a function @{text tree_of} that turns a list into a sorted\n  tree.  It is helpful to base @{text tree_of} on a function @{term \"ins n b\"}\n  that inserts a number @{term n} into a sorted tree @{term b}.\n*}\n\nprimrec tge :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bool\" where\n  \"tge x Empty          = True\"\n| \"tge x (Node n t1 t2) = (n \\<le> x \\<and> tge x t1 \\<and> tge x t2)\"\n\nprimrec tle :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bool\" where\n  \"tle x Empty          = True\"\n| \"tle x (Node n t1 t2) = (x \\<le> n \\<and> tle x t1 \\<and> tle x t2)\"\n\nprimrec tsorted :: \"bintree \\<Rightarrow> bool\" where\n  \"tsorted Empty          = True\"\n| \"tsorted (Node n t1 t2) = (tsorted t1 \\<and> tsorted t2 \\<and> tge n t1 \\<and> tle n t2)\"\n\nprimrec ins :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bintree\" where\n  \"ins x Empty          = Node x Empty Empty\"\n| \"ins x (Node n t1 t2) = (if x \\<le> n then Node n (ins x t1) t2 else Node n t1 (ins x t2))\"\n\nprimrec tree_of :: \"nat list \\<Rightarrow> bintree\" where\n  \"tree_of []     = Empty\"\n| \"tree_of (x#xs) = ins x (tree_of xs)\"\n\n\ntext {*\n  Show\n*}\n\nlemma [simp]: \"tge a (ins x t) = (x \\<le> a \\<and> tge a t)\"\n  apply (induct_tac t)\n  apply auto\ndone\n\nlemma [simp]: \"tle a (ins x t) = (a \\<le> x \\<and> tle a t)\"\n  apply (induct_tac t)\n  apply auto\ndone\n\nlemma [simp]: \"tsorted (ins x t) = tsorted t\"\n  apply (induct_tac t)\n  apply auto\ndone\n\ntheorem [simp]: \"tsorted (tree_of xs)\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\n\ntext {*\n  Again we have to show that no elements are lost (or added).  As for lists,\n  define a function @{term \"tcount x b\"} that counts the number of occurrences\n  of the number @{term x} in the tree @{term b}.\n*}\n\nprimrec tcount :: \"bintree => nat => nat\" where\n  \"tcount Empty          y = 0\"\n| \"tcount (Node x t1 t2) y = (if x=y then\n                                Suc (tcount t1 y + tcount t2 y)\n                              else\n                                tcount t1 y + tcount t2 y)\"\n\n\ntext {*\n  Show\n*}\n\nlemma [simp]: \"tcount (ins x t) y =\n  (if x=y then Suc (tcount t y) else tcount t y)\"\n  apply(induct_tac t)\n  apply auto\ndone\n\ntheorem \"tcount (tree_of xs) x = count xs x\"\n  apply (induct_tac xs)\n  apply auto\ndone\n\n\ntext {*\n  Now we are ready to sort lists.  We know how to produce an ordered tree from\n  a list.  Thus we merely need a function @{text list_of} that turns an\n  (ordered) tree into an (ordered) list.  Define this function and prove\n*}\n\ntheorem \"sorted (list_of (tree_of xs))\"\n(*<*) oops (*>*)\n\ntheorem \"count (list_of (tree_of xs)) n = count xs n\"\n(*<*) oops (*>*)\n\ntext {*\n  Hints:\n  \\begin{itemize}\n  \\item\n  Try to formulate all your lemmas as equations rather than implications\n  because that often simplifies their proof.  Make sure that the right-hand\n  side is (in some sense) simpler than the left-hand side.\n  \\item\n  Eventually you need to relate @{text sorted} and @{text tsorted}.  This is\n  facilitated by a function @{text ge} on lists (analogously to @{text tge} on\n  trees) and the following lemma (that you will need to prove):\\\\\n  @{term[display] \"sorted (a@x#b) = (sorted a \\<and> sorted b \\<and> ge x a\n  \\<and> le x b)\"}\n  \\end{itemize}\n*}\n\nprimrec ge :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"ge a []     = True\"\n| \"ge a (x#xs) = (x \\<le> a \\<and> ge a xs)\"\n\nprimrec list_of :: \"bintree \\<Rightarrow> nat list\" where\n  \"list_of Empty          = []\"\n| \"list_of (Node n t1 t2) = list_of t1 @ [n] @ list_of t2\"\n\nlemma [simp]: \"le x (a@b) = (le x a \\<and> le x b)\"\n  apply (induct_tac a)\n  apply auto\ndone\n\nlemma [simp]: \"ge x (a@b) = (ge x a \\<and> ge x b)\"\n  apply (induct_tac a)\n  apply auto\ndone\n\nlemma [simp]:\n  \"sorted (a@x#b) = (sorted a \\<and> sorted b \\<and> ge x a \\<and> le x b)\"\n  apply (induct_tac a)\n  apply auto\ndone\n\nlemma [simp]: \"ge n (list_of t) = tge n t\"\n  apply (induct_tac t)\n  apply auto\ndone\n\nlemma [simp]: \"le n (list_of t) = tle n t\"\n  apply (induct_tac t)\n  apply auto\ndone\n  \nlemma [simp]: \"sorted (list_of t) = tsorted t\"\n  apply (induct_tac t)\n  apply auto\ndone\n\ntheorem \"sorted (list_of (tree_of xs))\"\n  by auto\n\nlemma count_append [simp]: \"count (a@b) n = count a n + count b n\"\n  apply (induct a)\n  apply auto\ndone\n\nlemma [simp]: \"count (list_of b) n = tcount b n\"\n  apply (induct b)\n  apply auto\ndone\n\ntheorem \"count (list_of (tree_of xs)) n = count xs n\"    \n  apply (induct xs)\n  apply auto\ndone\n\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/advanced/sorting/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8757869867849166, "lm_q1q2_score": 0.795755723592169}}
{"text": "section \\<open>Trees\\<close>\n\ntheory Tree imports Main begin\n\ntext \\<open>Sometimes it is nice to think of @{typ bool}s as directions in a binary tree\\<close>\nhide_const (open) Left Right\ntype_synonym dir = bool\ndefinition Left :: bool where \"Left = True\"\ndefinition Right :: bool where \"Right = False\"\ndeclare Left_def [simp]\ndeclare Right_def [simp]\n\ndatatype tree =\n  Leaf\n| Branching (ltree: tree) (rtree: tree) \n\n\nsubsection \\<open>Sizes\\<close>\n\nfun treesize :: \"tree \\<Rightarrow> nat\" where\n  \"treesize Leaf = 0\"\n| \"treesize (Branching l r) = 1 + treesize l + treesize r\"\n\nlemma treesize_Leaf:\n  assumes \"treesize T = 0\"\n  shows \"T = Leaf\"\n  using assms by (cases T) auto\n\nlemma treesize_Branching:\n  assumes \"treesize T = Suc n\"\n  shows \"\\<exists>l r. T = Branching l r\" \n  using assms by (cases T) auto\n\n\nsubsection \\<open>Paths\\<close>\n\nfun path :: \"dir list \\<Rightarrow> tree \\<Rightarrow> bool\" where\n  \"path [] T \\<longleftrightarrow> True\"\n| \"path (d#ds) (Branching T1 T2) \\<longleftrightarrow> (if d then path ds T1 else path ds T2)\"\n| \"path _ _ \\<longleftrightarrow> False\"\n\nlemma path_inv_Leaf: \"path p Leaf \\<longleftrightarrow> p = []\"\n  by (induction p)  auto\n\nlemma path_inv_Cons: \"path (a#ds) T \\<longrightarrow> (\\<exists>l r. T=Branching l r)\"\n  by  (cases T) (auto simp add: path_inv_Leaf)\n\n\nlemma path_inv_Branching_Left: \"path (Left#p) (Branching l r) \\<longleftrightarrow> path p l\"\n  using Left_def Right_def path.cases by (induction p) auto\n\nlemma path_inv_Branching_Right: \"path (Right#p) (Branching l r) \\<longleftrightarrow> path p r\"\nusing Left_def Right_def path.cases by (induction p)  auto\n\n\nlemma path_inv_Branching: \n  \"path p (Branching l r) \\<longleftrightarrow> (p=[] \\<or> (\\<exists>a p'. p=a#p'\\<and> (a \\<longrightarrow> path p' l) \\<and> (\\<not>a \\<longrightarrow> path p' r)))\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L then show ?R by (induction p) auto\nnext\n  assume r: ?R\n  then show ?L\n    proof\n      assume \"p = []\" then show ?L by auto\n    next\n      assume \"\\<exists>a p'. p=a#p'\\<and> (a \\<longrightarrow> path p' l) \\<and> (\\<not>a \\<longrightarrow> path p' r)\"\n      then obtain a p' where \"p=a#p'\\<and> (a \\<longrightarrow> path p' l) \\<and> (\\<not>a \\<longrightarrow> path p' r)\" by auto\n      then show ?L by (cases a) auto\n    qed\nqed\n\nlemma path_prefix: \n  assumes \"path (ds1@ds2) T\"\n  shows \"path ds1 T\"\nusing assms proof (induction ds1 arbitrary: T)\n  case (Cons a ds1)\n  then have \"\\<exists>l r. T = Branching l r\" using path_inv_Leaf by (cases T) auto\n  then obtain l r where p_lr: \"T = Branching l r\" by auto\n  show ?case\n    proof (cases a)\n      assume atrue: \"a\"\n      then have \"path ((ds1) @ ds2) l\" using p_lr Cons(2) path_inv_Branching by auto\n      then have \"path ds1 l\" using Cons(1) by auto\n      then show \"path (a # ds1) T\" using p_lr atrue by auto\n    next\n      assume afalse: \"\\<not>a\"\n      then have \"path ((ds1) @ ds2) r\" using p_lr Cons(2) path_inv_Branching by auto\n      then have \"path ds1 r\" using Cons(1) by auto\n      then show \"path (a # ds1) T\" using p_lr afalse by auto\n    qed\nnext\n  case (Nil) then show ?case  by auto\nqed\n\n\nsubsection \\<open>Branches\\<close>\n\nfun branch :: \"dir list \\<Rightarrow> tree \\<Rightarrow> bool\" where\n  \"branch [] Leaf \\<longleftrightarrow> True\"    \n| \"branch (d # ds) (Branching l r) \\<longleftrightarrow> (if d then branch ds l else branch ds r)\"\n| \"branch _ _ \\<longleftrightarrow> False\"\n\nlemma has_branch: \"\\<exists>b. branch b T\"\nproof (induction T)\n  case (Leaf) \n  have \"branch [] Leaf\" by auto\n  then show ?case by blast\nnext\n  case (Branching T\\<^sub>1 T\\<^sub>2)\n  then obtain b where \"branch b T\\<^sub>1\" by auto\n  then have \"branch (Left#b) (Branching T\\<^sub>1 T\\<^sub>2)\"  by auto\n  then show ?case by blast\nqed\n\nlemma branch_inv_Leaf: \"branch b Leaf \\<longleftrightarrow> b = []\"\nby (cases b) auto\n\nlemma branch_inv_Branching_Left:  \n  \"branch (Left#b) (Branching l r) \\<longleftrightarrow> branch b l\"\nby auto\n\n\n\nlemma branch_inv_Branching: \n  \"branch b (Branching l r) \\<longleftrightarrow> \n     (\\<exists>a b'. b=a#b'\\<and> (a \\<longrightarrow> branch b' l) \\<and> (\\<not>a \\<longrightarrow>  branch b' r))\"\nby (induction b) auto\n\nlemma branch_inv_Leaf2:\n  \"T = Leaf \\<longleftrightarrow> (\\<forall>b. branch b T \\<longrightarrow> b = [])\"\nproof -\n  {\n    assume \"T=Leaf\"\n    then have \"\\<forall>b. branch b T \\<longrightarrow> b = []\" using branch_inv_Leaf by auto\n  }\n  moreover \n  {\n    assume \"\\<forall>b. branch b T \\<longrightarrow> b = []\"\n    then have \"\\<forall>b. branch b T \\<longrightarrow> \\<not>(\\<exists>a b'. b = a # b')\" by auto\n    then have \"\\<forall>b. branch b T \\<longrightarrow> \\<not>(\\<exists>l r. branch b (Branching l r))\" \n      using branch_inv_Branching by auto\n    then have \"T=Leaf\" using has_branch[of T] by (metis branch.elims(2))\n  }\n  ultimately show \"T = Leaf \\<longleftrightarrow> (\\<forall>b. branch b T \\<longrightarrow> b = [])\" by auto\nqed\n\nlemma branch_is_path: \n  assumes\"branch ds T\"\n  shows \"path ds T\"\nusing assms proof (induction T arbitrary: ds)\n  case Leaf\n  then have \"ds = []\" using branch_inv_Leaf by auto\n  then show ?case  by auto\nnext\n  case (Branching T\\<^sub>1 T\\<^sub>2) \n  then obtain a b where ds_p: \"ds = a # b \\<and> (a \\<longrightarrow> branch b T\\<^sub>1) \\<and> (\\<not> a \\<longrightarrow> branch b T\\<^sub>2)\" using branch_inv_Branching[of ds] by blast\n  then have \"(a \\<longrightarrow> path b T\\<^sub>1) \\<and> (\\<not>a \\<longrightarrow> path b T\\<^sub>2)\" using Branching by auto\n  then show \"?case\" using ds_p by (cases a) auto\nqed\n\nlemma Branching_Leaf_Leaf_Tree:\n  assumes \"T = Branching T1 T2\"\n  shows \"(\\<exists>B. branch (B@[True]) T \\<and> branch (B@[False]) T)\"\nusing assms proof (induction T arbitrary: T1 T2)\n  case Leaf then show ?case by auto\nnext\n  case (Branching T1' T2')\n  {\n    assume \"T1'=Leaf \\<and> T2'=Leaf\"\n    then have \"branch ([] @ [True]) (Branching T1' T2') \\<and> branch ([] @ [False]) (Branching T1' T2')\" by auto\n    then have ?case by metis\n  }\n  moreover\n  {\n    fix T11 T12\n    assume \"T1' = Branching T11 T12\"\n    then obtain B where \"branch (B @ [True]) T1' \n                       \\<and> branch (B @ [False]) T1'\" using Branching by blast\n    then have \"branch (([True] @ B) @ [True]) (Branching T1' T2') \n             \\<and> branch (([True] @ B) @ [False]) (Branching T1' T2')\" by auto\n    then have ?case by blast\n  }\n  moreover\n  {\n    fix T11 T12\n    assume \"T2' = Branching T11 T12\"\n    then obtain B where \"branch (B @ [True]) T2' \n                       \\<and> branch (B @ [False]) T2'\" using Branching by blast\n    then have \"branch (([False] @ B) @ [True]) (Branching T1' T2') \n             \\<and> branch (([False] @ B) @ [False]) (Branching T1' T2')\" by auto\n    then have ?case by blast\n  }\n  ultimately show ?case using tree.exhaust by blast\nqed\n\n\nsubsection \\<open>Internal Paths\\<close>\n\nfun internal :: \"dir list \\<Rightarrow> tree \\<Rightarrow> bool\" where\n  \"internal [] (Branching l r) \\<longleftrightarrow> True\"\n| \"internal (d#ds) (Branching l r) \\<longleftrightarrow> (if d then internal ds l else internal ds r)\"\n| \"internal _ _ \\<longleftrightarrow> False\"\n\nlemma internal_inv_Leaf: \"\\<not>internal b Leaf\" using internal.simps by blast\n\nlemma internal_inv_Branching_Left:  \n  \"internal (Left#b) (Branching l r) \\<longleftrightarrow> internal b l\" by auto\n\nlemma internal_inv_Branching_Right: \n  \"internal (Right#b) (Branching l r) \\<longleftrightarrow> internal b r\"\nby auto\n\nlemma internal_inv_Branching: \n  \"internal p (Branching l r) \\<longleftrightarrow> (p=[] \\<or> (\\<exists>a p'. p=a#p'\\<and> (a \\<longrightarrow> internal p' l) \\<and> (\\<not>a \\<longrightarrow> internal p' r)))\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume ?L then show ?R by (metis internal.simps(2) neq_Nil_conv) \nnext\n  assume r: ?R\n  then show ?L\n    proof\n      assume \"p = []\" then show ?L by auto\n    next\n      assume \"\\<exists>a p'. p=a#p'\\<and> (a \\<longrightarrow> internal p' l) \\<and> (\\<not>a \\<longrightarrow> internal p' r)\"\n      then obtain a p' where \"p=a#p'\\<and> (a \\<longrightarrow> internal p' l) \\<and> (\\<not>a \\<longrightarrow> internal p' r)\" by auto\n      then show ?L by (cases a) auto\n    qed\nqed\n\nlemma internal_is_path: \n  assumes \"internal ds T\"\n  shows \"path ds T\"\nusing assms proof (induction T arbitrary: ds)\n  case Leaf\n  then have \"False\" using internal_inv_Leaf by auto\n  then show ?case by auto\nnext\n  case (Branching T\\<^sub>1 T\\<^sub>2) \n  then obtain a b where ds_p: \"ds=[] \\<or> ds = a # b \\<and> (a \\<longrightarrow> internal b T\\<^sub>1) \\<and> (\\<not> a \\<longrightarrow> internal b T\\<^sub>2)\" using internal_inv_Branching by blast\n  then have \"ds = [] \\<or> (a \\<longrightarrow> path b T\\<^sub>1) \\<and> (\\<not>a \\<longrightarrow> path b T\\<^sub>2)\" using Branching by auto\n  then show \"?case\" using ds_p by (cases a) auto\nqed\n\nlemma internal_prefix:\n  assumes \"internal (ds1@ds2@[d]) T\"\n  shows \"internal ds1 T\" (* more or less copy paste of path_prefix *)\nusing assms proof (induction ds1 arbitrary: T)\n  case (Cons a ds1)\n  then have \"\\<exists>l r. T = Branching l r\" using internal_inv_Leaf by (cases T) auto\n  then obtain l r where p_lr: \"T = Branching l r\" by auto\n  show ?case\n    proof (cases a)\n      assume atrue: \"a\"\n      then have \"internal ((ds1) @ ds2 @[d]) l\" using p_lr Cons(2) internal_inv_Branching by auto\n      then have \"internal ds1 l\" using Cons(1) by auto\n      then show \"internal (a # ds1) T\" using p_lr atrue by auto\n    next\n      assume afalse: \"~a\"\n      then have \"internal ((ds1) @ ds2 @[d]) r\" using p_lr Cons(2) internal_inv_Branching by auto\n      then have \"internal ds1 r\" using Cons(1) by auto\n      then show \"internal (a # ds1) T\" using p_lr afalse by auto\n    qed\nnext\n  case (Nil)\n  then have \"\\<exists>l r. T = Branching l r\" using internal_inv_Leaf by (cases T) auto \n  then show ?case by auto\nqed\n\n\nlemma internal_branch:\n  assumes \"branch (ds1@ds2@[d]) T\"\n  shows \"internal ds1 T\" (* more or less copy paste of path_prefix *)\nusing assms proof (induction ds1 arbitrary: T)\n  case (Cons a ds1)\n  then have \"\\<exists>l r. T = Branching l r\" using branch_inv_Leaf by (cases T) auto\n  then obtain l r where p_lr: \"T = Branching l r\" by auto\n  show ?case\n    proof (cases a)\n      assume atrue: \"a\"\n      then have \"branch (ds1 @ ds2 @ [d]) l\" using p_lr Cons(2) branch_inv_Branching by auto\n      then have \"internal ds1 l\" using Cons(1) by auto\n      then show \"internal (a # ds1) T\" using p_lr atrue by auto\n    next\n      assume afalse: \"~a\"\n      then have \"branch ((ds1) @ ds2 @[d]) r\" using p_lr Cons(2) branch_inv_Branching by auto\n      then have \"internal ds1 r\" using Cons(1) by auto\n      then show \"internal (a # ds1) T\" using p_lr afalse by auto\n    qed\nnext\n  case (Nil)\n  then have \"\\<exists>l r. T = Branching l r\" using branch_inv_Leaf by (cases T) auto \n  then show ?case by auto\nqed\n\n\nfun parent :: \"dir list \\<Rightarrow> dir list\" where\n  \"parent ds = tl ds\"\n\n\nsubsection \\<open>Deleting Nodes\\<close>\n\nfun delete :: \"dir list \\<Rightarrow> tree \\<Rightarrow> tree\" where\n  \"delete [] T = Leaf\"\n| \"delete (True#ds)  (Branching T\\<^sub>1 T\\<^sub>2) = Branching (delete ds T\\<^sub>1) T\\<^sub>2\"\n| \"delete (False#ds) (Branching T\\<^sub>1 T\\<^sub>2) = Branching T\\<^sub>1 (delete ds T\\<^sub>2)\"\n| \"delete (a#ds) Leaf = Leaf\"\n\nlemma delete_Leaf: \"delete T Leaf = Leaf\" by (cases T) auto\n\nlemma path_delete: \n  assumes \"path p (delete ds T)\"\n  shows \"path p T \" (* What a huge proof... But the four cases can be proven shorter *)\nusing assms proof (induction p arbitrary: T ds)\n  case Nil \n  then show ?case by simp\nnext\n  case (Cons a p)\n  then obtain b ds' where bds'_p: \"ds=b#ds'\" by (cases ds) auto\n\n  have \"\\<exists>dT1 dT2. delete ds T = Branching dT1 dT2\" using Cons path_inv_Cons by auto\n  then obtain dT1 dT2 where \"delete ds T = Branching dT1 dT2\" by auto\n\n  then have \"\\<exists>T1 T2. T=Branching T1 T2\" (* Is there a lemma hidden here that I could extract? *)\n        by (cases T; cases ds) auto\n  then obtain T1 T2 where T1T2_p: \"T=Branching T1 T2\" by auto\n\n  {\n    assume a_p: \"a\"\n    assume b_p: \"\\<not>b\"\n    have \"path (a # p) (delete ds T)\" using Cons by -\n    then have \"path (a # p) (Branching (T1) (delete ds' T2))\" using b_p bds'_p T1T2_p by auto\n    then have \"path p T1\" using a_p by auto\n    then have ?case using T1T2_p a_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"\\<not>a\"\n    assume b_p: \"b\"\n    have \"path (a # p) (delete ds T)\" using Cons by -\n    then have \"path (a # p) (Branching (delete ds' T1) T2)\" using b_p bds'_p T1T2_p by auto\n    then have \"path p T2\" using a_p by auto\n    then have ?case using T1T2_p a_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"a\"\n    assume b_p: \"b\"\n    have \"path (a # p) (delete ds T)\" using Cons by -\n    then have \"path (a # p) (Branching (delete ds' T1) T2)\" using b_p bds'_p T1T2_p by auto\n    then have \"path p (delete ds' T1)\" using a_p by auto\n    then have \"path p T1\" using Cons by auto\n    then have ?case using T1T2_p a_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"\\<not>a\"\n    assume b_p: \"\\<not>b\"\n    have \"path (a # p) (delete ds T)\" using Cons by -\n    then have \"path (a # p) (Branching T1 (delete ds' T2))\" using b_p bds'_p T1T2_p by auto\n    then have \"path p (delete ds' T2)\" using a_p by auto\n    then have \"path p T2\" using Cons by auto\n    then have ?case using T1T2_p a_p by auto\n  }\n  ultimately show ?case by blast\nqed\n\nlemma branch_delete:\n  assumes \"branch p (delete ds T)\"\n  shows \"branch p T \\<or> p=ds\" (* Adapted from above *)\nusing assms proof (induction p arbitrary: T ds)\n  case Nil \n  then have \"delete ds T = Leaf\" by (cases \"delete ds T\") auto\n  then have \"ds = [] \\<or> T = Leaf\" using delete.elims by blast \n  then show ?case by auto\nnext\n  case (Cons a p)\n  then obtain b ds' where bds'_p: \"ds=b#ds'\" by (cases ds) auto\n\n  have \"\\<exists>dT1 dT2. delete ds T = Branching dT1 dT2\" using Cons path_inv_Cons branch_is_path by blast\n  then obtain dT1 dT2 where \"delete ds T = Branching dT1 dT2\" by auto\n\n  then have \"\\<exists>T1 T2. T=Branching T1 T2\" (* Is there a lemma hidden here that I could extract? *)\n        by (cases T; cases ds) auto\n  then obtain T1 T2 where T1T2_p: \"T=Branching T1 T2\" by auto\n\n  {\n    assume a_p: \"a\"\n    assume b_p: \"\\<not>b\"\n    have \"branch (a # p) (delete ds T)\" using Cons by -\n    then have \"branch (a # p) (Branching (T1) (delete ds' T2))\" using b_p bds'_p T1T2_p by auto\n    then have \"branch p T1\" using a_p by auto\n    then have ?case using T1T2_p a_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"\\<not>a\"\n    assume b_p: \"b\"\n    have \"branch (a # p) (delete ds T)\" using Cons by -\n    then have \"branch (a # p) (Branching (delete ds' T1) T2)\" using b_p bds'_p T1T2_p by auto\n    then have \"branch p T2\" using a_p by auto\n    then have ?case using T1T2_p a_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"a\"\n    assume b_p: \"b\"\n    have \"branch (a # p) (delete ds T)\" using Cons by -\n    then have \"branch (a # p) (Branching (delete ds' T1) T2)\" using b_p bds'_p T1T2_p by auto\n    then have \"branch p (delete ds' T1)\" using a_p by auto\n    then have \"branch p T1 \\<or> p = ds'\" using Cons by metis\n    then have ?case using T1T2_p a_p using bds'_p a_p b_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"\\<not>a\"\n    assume b_p: \"\\<not>b\"\n    have \"branch (a # p) (delete ds T)\" using Cons by -\n    then have \"branch (a # p) (Branching T1 (delete ds' T2))\" using b_p bds'_p T1T2_p by auto\n    then have \"branch p (delete ds' T2)\" using a_p by auto\n    then have \"branch p T2 \\<or> p = ds'\" using Cons by metis\n    then have ?case using T1T2_p a_p using bds'_p a_p b_p by auto\n  }\n  ultimately show ?case by blast\nqed\n  \n\nlemma branch_delete_postfix: \n  assumes \"path p (delete ds T)\"\n  shows \"\\<not>(\\<exists>c cs. p = ds @ c#cs)\" (* Adapted from previous proof *)\nusing assms proof (induction p arbitrary: T ds)\n  case Nil then show ?case by simp\nnext\n  case (Cons a p)\n  then obtain b ds' where bds'_p: \"ds=b#ds'\" by (cases ds) auto\n\n  have \"\\<exists>dT1 dT2. delete ds T = Branching dT1 dT2\" using Cons path_inv_Cons by auto\n  then obtain dT1 dT2 where \"delete ds T = Branching dT1 dT2\" by auto\n\n  then have \"\\<exists>T1 T2. T=Branching T1 T2\" (* Is there a lemma hidden here that I could extract? *)\n        by (cases T; cases ds) auto\n  then obtain T1 T2 where T1T2_p: \"T=Branching T1 T2\" by auto\n\n  {\n    assume a_p: \"a\"\n    assume b_p: \"\\<not>b\"\n    then have ?case using T1T2_p a_p b_p bds'_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"\\<not>a\"\n    assume b_p: \"b\"\n    then have ?case using T1T2_p a_p b_p bds'_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"a\"\n    assume b_p: \"b\"\n    have \"path (a # p) (delete ds T)\" using Cons by -\n    then have \"path (a # p) (Branching (delete ds' T1) T2)\" using b_p bds'_p T1T2_p by auto\n    then have \"path p (delete ds' T1)\" using a_p by auto\n    then have \"\\<not> (\\<exists>c cs. p = ds' @ c # cs)\" using Cons by auto\n    then have ?case using T1T2_p a_p b_p bds'_p by auto\n  }\n  moreover\n  {\n    assume a_p: \"\\<not>a\"\n    assume b_p: \"\\<not>b\"\n    have \"path (a # p) (delete ds T)\" using Cons by -\n    then have \"path (a # p) (Branching T1 (delete ds' T2))\" using b_p bds'_p T1T2_p by auto\n    then have \"path p (delete ds' T2)\" using a_p by auto\n    then have \"\\<not> (\\<exists>c cs. p = ds' @ c # cs)\" using Cons by auto\n    then have ?case using T1T2_p a_p b_p bds'_p by auto\n  }\n  ultimately show ?case by blast\nqed\n\nlemma treezise_delete: \n  assumes \"internal p T\"\n  shows \"treesize (delete p T) < treesize T\"\nusing assms proof (induction p arbitrary: T)\n  case (Nil)\n  then have \"\\<exists>T1 T2. T = Branching T1 T2\" by (cases T) auto\n  then obtain T1 T2 where T1T2_p: \"T = Branching T1 T2\" by auto \n  then show ?case by auto\nnext\n  case (Cons a p) \n  then have \"\\<exists>T1 T2. T = Branching T1 T2\" using path_inv_Cons internal_is_path by blast\n  then obtain T1 T2 where T1T2_p: \"T = Branching T1 T2\" by auto\n  show ?case\n    proof (cases a)\n      assume a_p: a\n      from a_p have \"delete (a#p) T = (Branching (delete p T1) T2)\" using T1T2_p by auto\n      moreover\n      from a_p have \"internal p T1\" using T1T2_p Cons by auto\n      then have \"treesize (delete p T1) < treesize T1\" using Cons by auto\n      ultimately\n      show ?thesis using T1T2_p by auto\n    next\n      assume a_p: \"\\<not>a\"\n      from a_p have \"delete (a#p) T = (Branching T1 (delete p T2))\" using T1T2_p by auto\n      moreover\n      from a_p have \"internal p T2\" using T1T2_p Cons by auto\n      then have \"treesize (delete p T2) < treesize T2\" using Cons by auto\n      ultimately\n      show ?thesis using T1T2_p by auto\n    qed\nqed\n\n\nfun cutoff :: \"(dir list \\<Rightarrow> bool) \\<Rightarrow> dir list \\<Rightarrow> tree \\<Rightarrow> tree\" where\n  \"cutoff red ds (Branching T\\<^sub>1 T\\<^sub>2) = \n     (if red ds then Leaf else Branching (cutoff red (ds@[Left])  T\\<^sub>1) (cutoff red (ds@[Right]) T\\<^sub>2))\"\n| \"cutoff red ds Leaf = Leaf\"\ntext \\<open>Initially you should call @{const cutoff} with @{term \"ds = []\"}.\n If all branches are red, then @{const cutoff} gives a subtree.\n If all branches are red, then so are the ones in @{const cutoff}.\n The internal paths of @{const cutoff} are not red.\\<close>\n\nlemma treesize_cutoff: \"treesize (cutoff red ds T) \\<le> treesize T\"\nproof (induction T arbitrary: ds)\n  case Leaf then show ?case by auto\nnext\n  case (Branching T1 T2) \n  then have \"treesize (cutoff red (ds@[Left]) T1) + treesize (cutoff red (ds@[Right]) T2) \\<le> treesize T1 + treesize T2\" using add_mono by blast\n  then show ?case by auto\nqed\n\nabbreviation anypath :: \"tree \\<Rightarrow> (dir list \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"anypath T P \\<equiv> \\<forall>p. path p T \\<longrightarrow> P p\"\n\nabbreviation anybranch :: \"tree \\<Rightarrow> (dir list \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"anybranch T P \\<equiv> \\<forall>p. branch p T \\<longrightarrow> P p\"\n\nabbreviation anyinternal :: \"tree \\<Rightarrow> (dir list \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"anyinternal T P \\<equiv> \\<forall>p. internal p T \\<longrightarrow> P p\"\n\n\n\n  from Branching have \"\\<forall>p. branch (Right#p) (Branching T\\<^sub>1 T\\<^sub>2) \\<longrightarrow> red (ds @ (Right#p))\" by blast\n  then have \"\\<forall>p. branch p T\\<^sub>2 \\<longrightarrow> red (ds @ (Right#p))\" by auto\n  then have \"anybranch T\\<^sub>2 (\\<lambda>p. red ((ds @ [Right]) @ p))\" by auto\n  then have bb: \"anybranch (cutoff red (ds @ [Right]) T\\<^sub>2) (\\<lambda>p. red ((ds @ [Right]) @ p)) \n         \" using Branching by blast\n  {           \n    fix b\n    assume b_p: \"branch b ?T\"\n    have \"red ds \\<or> \\<not>red ds\" by auto\n    then have \"red(ds@b)\"\n      proof\n        assume ds_p: \"red ds\"\n        then have \"?T = Leaf\" by auto\n        then have \"b = []\" using b_p branch_inv_Leaf by auto\n        then show \"red(ds@b)\" using ds_p by auto\n      next\n        assume ds_p: \"\\<not>red ds\"\n        let ?T\\<^sub>1' = \"cutoff red (ds@[Left])  T\\<^sub>1\"\n        let ?T\\<^sub>2' = \"cutoff red (ds@[Right]) T\\<^sub>2\"\n        from ds_p have \"?T = Branching ?T\\<^sub>1' ?T\\<^sub>2'\" by auto\n        from this b_p obtain a b' where \"b = a # b' \\<and> (a \\<longrightarrow> branch b' ?T\\<^sub>1') \\<and> (\\<not>a \\<longrightarrow> branch b' ?T\\<^sub>2' )\" using branch_inv_Branching[of b ?T\\<^sub>1' ?T\\<^sub>2'] by auto\n        then show \"red(ds@b)\" using aa bb by (cases a) auto\n      qed\n  }\n  then show ?case by blast\nqed\n\nlemma cutoff_branch: \n  assumes \"anybranch T (\\<lambda>p. red p)\"\n  shows \"anybranch (cutoff red [] T) (\\<lambda>p. red p)\" \n  using assms cutoff_branch'[of T red \"[]\"] by auto\n\nlemma cutoff_internal': \n  assumes \"anybranch T (\\<lambda>b. red(ds@b))\" \n  shows \"anyinternal (cutoff red ds T) (\\<lambda>b. \\<not>red(ds@b))\"\nusing assms proof (induction T arbitrary: ds) (* This proof seems a bit excessive for such a simple theorem *)\n  case (Leaf) then show ?case using internal_inv_Leaf by simp\nnext                                                     \n  case (Branching T\\<^sub>1 T\\<^sub>2)\n  let ?T = \"cutoff red ds (Branching T\\<^sub>1 T\\<^sub>2)\"\n  from Branching have \"\\<forall>p. branch (Left#p) (Branching T\\<^sub>1 T\\<^sub>2) \\<longrightarrow> red (ds @ (Left#p))\" by blast\n  then have \"\\<forall>p. branch p T\\<^sub>1 \\<longrightarrow> red (ds @ (Left#p))\" by auto\n  then have \"anybranch T\\<^sub>1 (\\<lambda>p. red ((ds @ [Left]) @ p))\" by auto\n  then have aa: \"anyinternal (cutoff red (ds @ [Left]) T\\<^sub>1) (\\<lambda>p. \\<not> red ((ds @ [Left]) @ p))\" using Branching by blast\n\n  from Branching have \"\\<forall>p. branch (Right#p) (Branching T\\<^sub>1 T\\<^sub>2) \\<longrightarrow> red (ds @ (Right#p))\" by blast\n  then have \"\\<forall>p. branch p T\\<^sub>2 \\<longrightarrow> red (ds @ (Right#p))\" by auto\n  then have \"anybranch T\\<^sub>2 (\\<lambda>p. red ((ds @ [Right]) @ p))\" by auto\n  then have bb: \"anyinternal (cutoff red (ds @ [Right]) T\\<^sub>2) (\\<lambda>p. \\<not> red ((ds @ [Right]) @ p))\" using Branching by blast\n  {\n    fix p\n    assume b_p: \"internal p ?T\"\n    then have ds_p: \"\\<not>red ds\" using internal_inv_Leaf by auto\n    have \"p=[] \\<or> p\\<noteq>[]\" by auto\n    then have \"\\<not>red(ds@p)\"\n      proof\n        assume \"p=[]\" then show \"\\<not>red(ds@p)\" using ds_p by auto\n      next\n        let ?T\\<^sub>1' = \"cutoff red (ds@[Left])  T\\<^sub>1\"\n        let ?T\\<^sub>2' = \"cutoff red (ds@[Right]) T\\<^sub>2\"\n        assume \"p\\<noteq>[]\"\n        moreover\n        have \"?T = Branching ?T\\<^sub>1' ?T\\<^sub>2'\" using ds_p by auto\n        ultimately\n        obtain a p' where b_p: \"p = a # p' \\<and>\n             (a \\<longrightarrow> internal p' (cutoff red (ds @ [Left]) T\\<^sub>1)) \\<and>\n             (\\<not> a \\<longrightarrow> internal p' (cutoff red (ds @ [Right]) T\\<^sub>2))\" \n          using b_p internal_inv_Branching[of p ?T\\<^sub>1' ?T\\<^sub>2'] by auto\n        then have \"\\<not>red(ds @ [a] @ p')\" using aa bb by (cases a) auto\n        then show \"\\<not>red(ds @ p)\" using b_p by simp\n      qed\n  }\n  then show ?case by blast\nqed\n\nlemma cutoff_internal:\n  assumes  \"anybranch T red\"\n  shows \"anyinternal (cutoff red [] T) (\\<lambda>p. \\<not>red p)\" \n  using assms cutoff_internal'[of T red \"[]\"] by auto\n\nlemma cutoff_branch_internal': \n  assumes \"anybranch T red\"\n  shows \"anyinternal (cutoff red [] T) (\\<lambda>p. \\<not>red p) \\<and> anybranch (cutoff red [] T) (\\<lambda>p. red p)\" \n  using assms cutoff_internal[of T] cutoff_branch[of T] by blast\n\nlemma cutoff_branch_internal: \n  assumes \"anybranch T red\"\n  shows \"\\<exists>T'. anyinternal T' (\\<lambda>p. \\<not>red p) \\<and> anybranch T' (\\<lambda>p. red p)\" \n  using assms cutoff_branch_internal' by blast\n\n\nsection \\<open>Possibly Infinite Trees\\<close>\ntext \\<open>Possibly infinite trees are of type @{typ \"dir list set\"}.\\<close>\n\nabbreviation wf_tree :: \"dir list set \\<Rightarrow> bool\" where\n  \"wf_tree T \\<equiv> (\\<forall>ds d. (ds @ d) \\<in> T \\<longrightarrow> ds \\<in> T)\"\n\ntext \\<open>The subtree in with root r\\<close>\nfun subtree :: \"dir list set \\<Rightarrow> dir list \\<Rightarrow> dir list set\" where \n  \"subtree T r = {ds \\<in> T. \\<exists>ds'. ds = r @ ds'}\" \n\ntext \\<open>A subtree of a tree is either in the left branch, the right branch, or is the tree itself\\<close>\nlemma subtree_pos: \n  \"subtree T ds \\<subseteq> subtree T (ds @ [Left]) \\<union> subtree T (ds @ [Right]) \\<union> {ds}\"\nproof (rule subsetI; rule Set.UnCI)\n  let ?subtree = \"subtree T\"\n  fix x\n  assume asm: \"x \\<in> ?subtree ds\"\n  assume \"x \\<notin> {ds}\"\n  then have \"x \\<noteq> ds\" by simp\n  then have \"\\<exists>e d. x = ds @ [d] @ e\" using asm list.exhaust by auto\n  then have \"(\\<exists>e. x = ds @ [Left] @ e) \\<or> (\\<exists>e. x = ds @ [Right] @ e)\" using bool.exhaust by auto\n  then show \"x \\<in> ?subtree (ds @ [Left]) \\<union> ?subtree (ds @ [Right])\" using asm by auto\nqed\n\n\nsubsection \\<open>Infinite Paths\\<close>\n\nabbreviation wf_infpath :: \"(nat \\<Rightarrow> 'a list) \\<Rightarrow> bool\" where\n  \"wf_infpath f \\<equiv> (f 0 = []) \\<and> (\\<forall>n. \\<exists>a. f (Suc n) = (f n) @ [a])\"\n\n\n\nlemma chain_prefix: \n  assumes \"wf_infpath f\"\n  assumes \"n\\<^sub>1 \\<le> n\\<^sub>2\"\n  shows \"\\<exists>a. (f n\\<^sub>1) @ a = (f n\\<^sub>2)\"\nusing assms proof (induction n\\<^sub>2)\n  case (Suc n\\<^sub>2)\n  then have \"n\\<^sub>1 \\<le> n\\<^sub>2 \\<or> n\\<^sub>1 = Suc n\\<^sub>2\" by auto\n  then show ?case\n    proof\n      assume \"n\\<^sub>1 \\<le> n\\<^sub>2\"\n      then obtain a where a: \"f n\\<^sub>1 @ a = f n\\<^sub>2\" using Suc by auto\n      have b: \"\\<exists>b. f (Suc n\\<^sub>2) = f n\\<^sub>2 @ [b]\" using Suc by auto \n      from a b have \"\\<exists>b. f n\\<^sub>1 @ (a @ [b]) = f (Suc n\\<^sub>2)\" by auto\n      then show \"\\<exists>c. f n\\<^sub>1 @ c = f (Suc n\\<^sub>2)\" by blast\n    next\n      assume \"n\\<^sub>1 = Suc n\\<^sub>2\"\n      then have \"f n\\<^sub>1 @ [] = f (Suc n\\<^sub>2)\" by auto\n      then show \"\\<exists>a. f n\\<^sub>1 @ a = f (Suc n\\<^sub>2)\" by auto\n    qed\nqed auto\n\ntext \\<open>If we make a lookup in a list, then looking up in an extension gives us the same value.\\<close>\nlemma ith_in_extension:\n  assumes chain: \"wf_infpath f\"\n  assumes smalli: \"i < length (f n\\<^sub>1)\"\n  assumes n\\<^sub>1n\\<^sub>2: \"n\\<^sub>1 \\<le> n\\<^sub>2\"\n  shows \"f n\\<^sub>1 ! i = f n\\<^sub>2 ! i\"\nproof -\n  from chain n\\<^sub>1n\\<^sub>2 have \"\\<exists>a. f n\\<^sub>1 @ a = f n\\<^sub>2\" using chain_prefix by blast\n  then obtain a where a_p: \"f n\\<^sub>1 @ a = f n\\<^sub>2\" by auto\n  have \"(f n\\<^sub>1 @ a) ! i = f n\\<^sub>1 ! i\" using smalli by (simp add: nth_append) \n  then show ?thesis using a_p by auto\nqed\n\n\nsection \\<open>König's Lemma\\<close>\n\nlemma inf_subs: \n  assumes inf: \"\\<not>finite(subtree T ds)\"\n  shows \"\\<not>finite(subtree T (ds @ [Left])) \\<or> \\<not>finite(subtree T (ds @ [Right]))\"\nproof -\n  let ?subtree = \"subtree T\"\n  {\n    assume asms: \"finite(?subtree(ds @ [Left]))\"\n                 \"finite(?subtree(ds @ [Right]))\"\n    have \"?subtree ds \\<subseteq> ?subtree (ds @ [Left] ) \\<union> ?subtree (ds @ [Right]) \\<union> {ds} \" \n      using subtree_pos by auto\n    then have \"finite(?subtree (ds))\" using asms by (simp add: finite_subset)\n  } \n  then show \"\\<not>finite(?subtree (ds @ [Left])) \\<or> \\<not>finite(?subtree (ds @ [Right]))\" using inf by auto\nqed\n\nfun buildchain :: \"(dir list \\<Rightarrow> dir list) \\<Rightarrow> nat \\<Rightarrow> dir list\" where\n  \"buildchain next 0 = []\"\n| \"buildchain next (Suc n) = next (buildchain next n)\"\n\nlemma konig:\n  assumes inf: \"\\<not>finite T\"\n  assumes wellformed: \"wf_tree T\"\n  shows \"\\<exists>c. wf_infpath c \\<and> (\\<forall>n. (c n) \\<in> T)\"\nproof\n  let ?subtree = \"subtree T\"\n  let ?nextnode = \"\\<lambda>ds. (if \\<not>finite (?subtree (ds @ [Left])) then ds @ [Left] else ds @ [Right])\" \n\n  let ?c = \"buildchain ?nextnode\"\n\n  have is_chain: \"wf_infpath ?c\" by auto\n\n  from wellformed have prefix: \"\\<forall>ds d. (ds @ d) \\<in> T \\<longrightarrow> ds \\<in> T\" by blast\n\n  { \n    fix n\n    have \"(?c n) \\<in> T \\<and> \\<not>finite (?subtree (?c n))\"\n      proof (induction n)\n        case 0\n        have \"\\<exists>ds. ds \\<in> T\" using inf by (simp add: not_finite_existsD)\n        then obtain ds where \"ds \\<in> T\" by auto\n        then have \"([]@ds) \\<in> T\" by auto\n        then have \"[] \\<in> T\" using prefix by blast \n        then show ?case using inf by auto\n      next\n        case (Suc n)\n        from Suc have next_in:  \"(?c n) \\<in> T\" by auto\n        from Suc have next_inf: \"\\<not>finite (?subtree (?c n))\" by auto\n\n        from next_inf have next_next_inf:\n           \"\\<not>finite (?subtree (?nextnode (?c n)))\" \n              using inf_subs by auto\n        then have \"\\<exists>ds. ds \\<in> ?subtree (?nextnode (?c n))\"\n          by (simp add: not_finite_existsD)\n        then obtain ds where dss: \"ds \\<in> ?subtree (?nextnode (?c n))\" by auto\n        then have \"ds \\<in> T\" \"\\<exists>suf. ds = (?nextnode (?c n)) @ suf\" by auto\n        then obtain suf where \"ds \\<in> T \\<and> ds = (?nextnode (?c n)) @ suf\" by auto\n        then have \"(?nextnode (?c n)) \\<in> T\"\n          using prefix by blast\n              \n        then have \"(?c (Suc n)) \\<in> T\" by auto\n        then show ?case using next_next_inf by auto\n      qed\n  }\n  then show \"wf_infpath ?c \\<and> (\\<forall>n. (?c n)\\<in> T) \" using is_chain by auto\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Resolution_FOL/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.9032942047513692, "lm_q1q2_score": 0.7956188904464506}}
{"text": "theory Logic\n  imports Tactics\nbegin\n\nsection {* Logic *}\n\n(* definition plus_fact where \"2 + 2 = 4\" *)\n\nsubsection {* Logical Connectives *}\n\nsubsubsection {* Conjunction *}\n\nlemma and_example: \"3 + 4 = 7 \\<and> (2::nat) * 2 = 4\"\n  apply (simp)\n  done\n\nlemma and_intro: \"A \\<longrightarrow> B \\<longrightarrow> A \\<and> B\"\n  apply (simp)\n  done\n\nlemma and_exercise: \"\\<forall> n m::nat. n + m = 0 \\<longrightarrow> n = 0 \\<and> m = 0\"\n  apply (simp)\n  done\n\nlemma and_example2: \"\\<forall> n m::nat. n = 0 \\<and> m = 0 \\<longrightarrow> n + m = 0\"\n  apply (simp)\n  done\n\nlemma and_example3: \"\\<forall> n m::nat. n + m = 0 \\<longrightarrow> n * m = 0\"\n  apply (simp)\n  done\n\nlemma proj1: \"P \\<and> Q \\<longrightarrow> P\"\n  apply (simp)\n  done\n\nlemma proj2: \"P \\<and> Q \\<longrightarrow> Q\"\n  apply (simp)\n  done\n\ntheorem and_commut: \"P \\<and> Q \\<longrightarrow> Q \\<and> P\"\n  apply (simp)\n  done\n\ntheorem and_assoc: \"P \\<and> (Q \\<and> R) \\<longrightarrow> (P \\<and> Q) \\<and> R\"\n  apply (simp)\n  done\n\nsubsubsection {* Disjunction *}\n\nlemma or_example: \"\\<forall> n m :: nat. n = 0 \\<or> m = 0 \\<longrightarrow> n * m = 0\"\n  apply (simp)\n  done\n\nlemma or_intro: \"A \\<longrightarrow> A \\<or> B\"\n  apply (simp)\n  done\n\nlemma zero_or_succ: \"n = 0 \\<or> n = Suc (pred n)\"\n  apply (induction n)\n   apply (simp_all)\n  done\n\nlemma mult_eq_0: \"\\<forall> n m::nat. n * m = 0 \\<longrightarrow> n = 0 \\<or> m = 0\"\n  apply (simp)\n  done\n\ntheorem or_commut: \"P \\<or> Q \\<longrightarrow> Q \\<or> P\"\n  apply (simp)\n  done\n\nsubsubsection {* Falsehood and Negation *}\n\ntheorem ex_falso_quodlibet: \"HOL.False \\<longrightarrow> P\"\n  apply (simp)\n  done\n\ntheorem not_implies_our_not: \"\\<forall> P. \\<not>P \\<longrightarrow> (\\<forall> Q. P \\<longrightarrow> Q)\"\n  apply (simp)\n  done\n\n(* theorem zero_not_one: \"\\<not> (0 = 1)\" *)\n\n(* theorem zero_not_one': \"0 \\<noteq> 1\" *)\n\ntheorem not_False: \"\\<not> HOL.False\"\n  apply (simp)\n  done\n\ntheorem contradiction_implies_anything: \"(P \\<and> \\<not>P) \\<longrightarrow> Q\"\n  apply (simp)\n  done\n\ntheorem double_neg: \"P \\<longrightarrow> \\<not>\\<not>P\"\n  apply (simp)\n  done\n\ntheorem contrapositive: \"(P \\<longrightarrow> Q) \\<longrightarrow> (\\<not>Q \\<longrightarrow> \\<not>P)\"\n  apply (auto)\n  done\n\ntheorem not_both_true_and_false: \"\\<not>(P \\<and> \\<not>P)\"\n  apply (simp)\n  done\n\ntheorem not_true_is_false: \"b \\<noteq> True \\<longrightarrow> b = False\"\n  apply (cases b)\n   apply (simp_all)\n  done\n\nsubsubsection {* Truth *}\n\n(* True is true. *)\ntheorem True_is_true: \"HOL.True\"\n  apply (simp)\n  done\n\nsubsubsection {* Logical Equivalance *}\n\ndefinition iff :: \"HOL.bool \\<Rightarrow> HOL.bool \\<Rightarrow> HOL.bool\" where\n   \"iff P Q \\<equiv> (P \\<longrightarrow> Q) \\<and> (Q \\<longrightarrow> P)\"\n\ntheorem iff_sym: \"\\<forall> P Q. iff P Q \\<longrightarrow> iff Q P\"\n  unfolding iff_def\n  apply (simp)\n  done\n\nlemma not_true_iff_false: \"b \\<noteq> bool.True \\<longleftrightarrow> b = bool.False\"\n  apply (cases b)\n   apply (simp_all)\n  done\n\ntheorem iff_refl: \"\\<forall> P. P \\<longleftrightarrow> P\"\n  apply (simp)\n  done\n\ntheorem iff_trans: \"\\<forall> P Q R. (P \\<longleftrightarrow> Q) \\<longrightarrow> (Q \\<longleftrightarrow> R) \\<longrightarrow> (P \\<longleftrightarrow> R)\"\n  apply (simp)\n  done\n\ntheorem or_distributes_over_and: \"\\<forall> P Q R. P \\<or> (Q \\<and> R) \\<longleftrightarrow> (P \\<or> Q) \\<and> (P \\<or> R)\"\n  using [[simp_trace]]\n  apply (auto)\n  done\n\nlemma mult_0: \"\\<forall> n m::nat. n * m = 0 \\<longleftrightarrow> n = 0 \\<or> m = 0\"\n  apply (simp)\n  done\n\nlemma or_assoc: \"\\<forall> P Q R. P \\<or> (Q \\<or> R) \\<longleftrightarrow> (P \\<or> Q) \\<or> R\"\n  apply (simp)\n  done\n\nsubsubsection {* Existential Quantification*}\n\nlemma four_is_even: \"\\<exists> n::nat. n + n = 4\"\n  apply presburger\n  done\n\nsubsubsection {* Programming with Propisition *}\n\nfun In :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> HOL.bool\" where\n  \"In _ [] = HOL.False\"\n| \"In a (x # xs) = (x = a \\<or> In a xs)\"\n\nlemma In_example_1: \"In 4 (1 # 2 # 3 # 4 # 5 # [])\"\n  apply (simp)\n  done\n\nlemma In_example_2: \"\\<forall> n. In n (2 # 4 # []) \\<longrightarrow> (\\<exists> n'. n = 2 * n')\"\n  oops\n\nlemma In_map: \"In a xs \\<longrightarrow> In (f a) (map f xs)\"\n  apply (induction xs)\n   apply (simp_all)\n  done\n\nlemma In_map_iff: \"In y (map f xs) \\<longleftrightarrow> exists x f x = y \\<and> In a xs\"\n  apply (induction xs)\n   apply (simp)\n  oops\n\nlemma In_app_iff: \"In a (xs @ ys) \\<longrightarrow> In a xs \\<or> In a ys\"\n  apply (induction xs)\n   apply (simp_all)\n  done\n\nend\n", "meta": {"author": "kubo39", "repo": "sf-by-isabelle", "sha": "b8371d744ac03235876f113145e0fde8c27073f2", "save_path": "github-repos/isabelle/kubo39-sf-by-isabelle", "path": "github-repos/isabelle/kubo39-sf-by-isabelle/sf-by-isabelle-b8371d744ac03235876f113145e0fde8c27073f2/1st/Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7954626515422929}}
{"text": "(*  Title:      Util_MinMax.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Order and linear order: min and max\\<close>\n\ntheory Util_MinMax\nimports Main\nbegin\n\nsubsection \\<open>Additional lemmata about @{term min} and @{term max}\\<close>\n\nlemma min_less_imp_conj: \"(z::'a::linorder) < min x y \\<Longrightarrow> z < x \\<and> z < y\" by simp\nlemma conj_less_imp_min: \"\\<lbrakk> z < x; z < y \\<rbrakk> \\<Longrightarrow> (z::'a::linorder) < min x y\" by simp\n\n(*lemma min_le_iff_conj: \"((z::'a::linorder) \\<le> min x y) = (z \\<le> x \\<and> z \\<le> y)\"*)\nlemmas min_le_iff_conj = min.bounded_iff\nlemma min_le_imp_conj: \"(z::'a::linorder) \\<le> min x y \\<Longrightarrow> z \\<le> x \\<and> z \\<le> y\" by simp\n(*lemma conj_le_imp_min: \"\\<lbrakk> z \\<le> x; z \\<le> y \\<rbrakk> \\<Longrightarrow> (z::'a::linorder) \\<le> min x y\"*)\nlemmas conj_le_imp_min = min.boundedI\n\n(*lemma min_eqL:\"\\<lbrakk> (x::('a::linorder)) \\<le> y \\<rbrakk> \\<Longrightarrow> min x y = x\"*)\nlemmas min_eqL = min.absorb1\n(*lemma min_eqR:\"\\<lbrakk> (y::('a::linorder)) \\<le> x \\<rbrakk> \\<Longrightarrow> min x y = y\"*)\nlemmas min_eqR = min.absorb2\nlemmas min_eq = min_eqL min_eqR\n\nlemma max_less_imp_conj:\"max x y < b \\<Longrightarrow> x < (b::('a::linorder)) \\<and> y < b\" by simp\n\n\n(*lemma max_le_iff_conj: \"(max x y \\<le> b) = (x \\<le> (b::('a::linorder)) \\<and> y \\<le> b)\"*)\nlemmas max_le_iff_conj = max.bounded_iff\nlemma max_le_imp_conj:\"max x y \\<le> b \\<Longrightarrow> x \\<le> (b::('a::linorder)) \\<and> y \\<le> b\" by simp\n(*lemma conj_le_imp_max:\"\\<lbrakk> x \\<le> (b::('a::linorder)); y \\<le> b \\<rbrakk> \\<Longrightarrow> max x y \\<le> b\"*)\nlemmas conj_le_imp_max =  max.boundedI\n\n(*lemma max_eqL:\"\\<lbrakk> (y::('a::linorder)) \\<le> x \\<rbrakk> \\<Longrightarrow> max x y = x\"*)\nlemmas max_eqL = max.absorb1\n(*lemma max_eqR:\"\\<lbrakk> (x::('a::linorder)) \\<le> y \\<rbrakk> \\<Longrightarrow> max x y = y\"*)\nlemmas max_eqR =  max.absorb2\nlemmas max_eq = max_eqL max_eqR\n\n(*lemma le_minI1:\"min x y \\<le> (x::('a::linorder))\"*)\nlemmas le_minI1 = min.cobounded1\n(*lemma le_minI2:\"min x y \\<le> (y::('a::linorder))\"*)\nlemmas le_minI2 = min.cobounded2\n\n\nlemma\n  min_le_monoR: \"(a::'a::linorder) \\<le> b \\<Longrightarrow> min x a \\<le> min x b\" and\n  min_le_monoL: \"(a::'a::linorder) \\<le> b \\<Longrightarrow> min a x \\<le> min b x\"\nby (fastforce simp: min.mono min_def)+\nlemma\n  max_le_monoR: \"(a::'a::linorder) \\<le> b \\<Longrightarrow> max x a \\<le> max x b\" and\n  max_le_monoL: \"(a::'a::linorder) \\<le> b \\<Longrightarrow> max a x \\<le> max b x\"\nby (fastforce simp: max.mono max_def)+\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/List-Infinite/CommonArith/Util_MinMax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404057671712, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7954626321876223}}
{"text": "section \\<open>Generators\\<close>\n\ntheory \"Generators\"\nimports\n   \"HOL-Algebra.Group\"\n   \"HOL-Algebra.Lattice\"\nbegin\n\n\ntext \\<open>This theory is not specific to Free Groups and could be moved to a more \ngeneral place. It defines the subgroup generated by a set of generators and\nthat homomorphisms agree on the generated subgroup if they agree on the\ngenerators.\\<close>\n\nnotation subgroup (infix \"\\<le>\" 80)\n\nsubsection \\<open>The subgroup generated by a set\\<close>\n\ntext \\<open>The span of a set of subgroup generators, i.e. the generated subgroup, can\nbe defined inductively or as the intersection of all subgroups containing the\ngenerators. Here, we define it inductively and proof the equivalence\\<close>\n\ninductive_set gen_span :: \"('a,'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (\"\\<langle>_\\<rangle>\\<index>\")\n  for G and gens\nwhere gen_one [intro!, simp]: \"\\<one>\\<^bsub>G\\<^esub> \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    | gen_gens: \"x \\<in> gens \\<Longrightarrow> x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    | gen_inv: \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> inv\\<^bsub>G\\<^esub> x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    | gen_mult: \"\\<lbrakk> x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>; y \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<rbrakk> \\<Longrightarrow>  x \\<otimes>\\<^bsub>G\\<^esub> y \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n\nlemma (in group) gen_span_closed:\n  assumes \"gens \\<subseteq> carrier G\"\n  shows \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\"\nproof (* How can I do this in one \"by\" line? *)\n  fix x\n  from assms show \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> x \\<in> carrier G\"\n    by -(induct rule:gen_span.induct, auto)\nqed\n\nlemma (in group) gen_subgroup_is_subgroup: \n      \"gens \\<subseteq> carrier G \\<Longrightarrow> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<le> G\"\nby(rule subgroupI)(auto intro:gen_span.intros simp add:gen_span_closed)\n\nlemma (in group) gen_subgroup_is_smallest_containing:\n  assumes \"gens \\<subseteq> carrier G\"\n    shows \"\\<Inter>{H. H \\<le> G \\<and> gens \\<subseteq> H} = \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\nproof\n  show \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> \\<Inter>{H. H \\<le> G \\<and> gens \\<subseteq> H}\"\n  proof(rule Inf_greatest)\n    fix H\n    assume \"H \\<in> {H. H \\<le> G \\<and> gens \\<subseteq> H}\"\n    hence \"H \\<le> G\" and \"gens \\<subseteq> H\" by auto\n    show \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> H\"\n    proof\n      fix x\n      from \\<open>H \\<le> G\\<close> and \\<open>gens \\<subseteq> H\\<close>\n      show \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> x \\<in> H\"\n       unfolding subgroup_def\n       by -(induct rule:gen_span.induct, auto)\n    qed\n  qed\nnext\n  from \\<open>gens \\<subseteq> carrier G\\<close>\n  have \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<le> G\" by (rule gen_subgroup_is_subgroup)\n  moreover\n  have \"gens \\<subseteq> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\" by (auto intro:gen_span.intros)\n  ultimately\n  show \"\\<Inter>{H. H \\<le> G \\<and> gens \\<subseteq> H} \\<subseteq> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    by(auto intro:Inter_lower)\nqed\n\nsubsection \\<open>Generators and homomorphisms\\<close>\n\ntext \\<open>Two homorphisms agreeing on some elements agree on the span of those elements.\\<close>\n\nlemma hom_unique_on_span:\n  assumes \"group G\"\n      and \"group H\"\n      and \"gens \\<subseteq> carrier G\"\n      and \"h \\<in> hom G H\"\n      and \"h' \\<in> hom G H\"\n      and \"\\<forall>g \\<in> gens. h g = h' g\"\n  shows \"\\<forall>x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>. h x = h' x\"\nproof\n  interpret G: group G by fact\n  interpret H: group H by fact\n  interpret h: group_hom G H h by unfold_locales fact\n  interpret h': group_hom G H h' by unfold_locales fact\n\n  fix x\n  from \\<open>gens \\<subseteq> carrier G\\<close> have \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\" by (rule G.gen_span_closed)\n  with assms show \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> h x = h' x\" apply -\n  proof(induct rule:gen_span.induct)\n    case (gen_mult x y)\n      hence x: \"x \\<in> carrier G\" and y: \"y \\<in> carrier G\" and\n            hx: \"h x = h' x\" and hy: \"h y = h' y\" by auto\n      thus \"h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h' (x \\<otimes>\\<^bsub>G\\<^esub> y)\" by simp\n  qed auto\nqed\n\nsubsection \\<open>Sets of generators\\<close>\n\ntext \\<open>There is no definition for ``\\<open>gens\\<close> is a generating set of\n\\<open>G\\<close>''. This is easily expressed by \\<open>\\<langle>gens\\<rangle> = carrier G\\<close>.\\<close>\n\ntext \\<open>The following is an application of \\<open>hom_unique_on_span\\<close> on a\ngenerating set of the whole group.\\<close>\n\nlemma (in group) hom_unique_by_gens:\n  assumes \"group H\"\n      and gens: \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> = carrier G\"\n      and \"h \\<in> hom G H\"\n      and \"h' \\<in> hom G H\"\n      and \"\\<forall>g \\<in> gens. h g = h' g\"\n  shows \"\\<forall>x \\<in> carrier G. h x = h' x\"\nproof\n  fix x\n\n  from gens have \"gens \\<subseteq> carrier G\" by (auto intro:gen_span.gen_gens)\n  with assms and group_axioms have r: \"\\<forall>x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>. h x = h' x\"\n    by -(erule hom_unique_on_span, auto)\n  with gens show \"x \\<in> carrier G \\<Longrightarrow> h x = h' x\" by auto\nqed\n\nlemma (in group_hom) hom_span:\n  assumes \"gens \\<subseteq> carrier G\"\n  shows \"h ` (\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>) = \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\nproof(rule Set.set_eqI, rule iffI)\n  from \\<open>gens \\<subseteq> carrier G\\<close>\n  have \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\" by (rule G.gen_span_closed)\n\n  fix y\n  assume \"y \\<in> h ` \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n  then obtain x where \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\" and \"y = h x\" by auto\n  from \\<open>x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\\<close>\n  have \"h x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n  proof(induct x)\n    case (gen_inv x)\n    hence \"x \\<in> carrier G\" and \"h x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n      using \\<open>\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\\<close>\n      by auto\n    thus ?case by (auto intro:gen_span.intros)\n  next\n    case (gen_mult x y)\n    hence \"x \\<in> carrier G\" and \"h x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n    and   \"y \\<in> carrier G\" and \"h y \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n      using \\<open>\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\\<close>\n      by auto\n    thus ?case by (auto intro:gen_span.intros)\n  qed(auto intro: gen_span.intros)\n  with \\<open>y = h x\\<close>\n  show \"y \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\" by simp\nnext\n  fix x\n  show \"x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub> \\<Longrightarrow> x \\<in> h ` \\<langle>gens\\<rangle>\"\n  proof(induct x rule:gen_span.induct)\n    case (gen_inv y)\n      then  obtain x where \"y = h x\" and \"x \\<in> \\<langle>gens\\<rangle>\" by auto\n      moreover\n      hence \"x \\<in> carrier G\"  using \\<open>gens \\<subseteq> carrier G\\<close> \n        by (auto dest:G.gen_span_closed)\n      ultimately show ?case \n        by (auto intro:hom_inv[THEN sym] rev_image_eqI gen_span.gen_inv simp del:group_hom.hom_inv hom_inv)\n  next\n   case (gen_mult y y')\n      then  obtain x and x'\n        where \"y = h x\" and \"x \\<in> \\<langle>gens\\<rangle>\"\n        and \"y' = h x'\" and \"x' \\<in> \\<langle>gens\\<rangle>\" by auto\n      moreover\n      hence \"x \\<in> carrier G\" and \"x' \\<in> carrier G\" using \\<open>gens \\<subseteq> carrier G\\<close> \n        by (auto dest:G.gen_span_closed)\n      ultimately show ?case\n        by (auto intro:hom_mult[THEN sym] rev_image_eqI gen_span.gen_mult simp del:group_hom.hom_mult hom_mult)\n  qed(auto intro:rev_image_eqI intro:gen_span.intros)\nqed\n\n\nsubsection \\<open>Product of a list of group elements\\<close>\n\ntext \\<open>Not strictly related to generators of groups, this is still a general\ngroup concept and not related to Free Groups.\\<close>\n\nabbreviation (in monoid) m_concat\n  where \"m_concat l \\<equiv> foldr (\\<otimes>) l \\<one>\"\n\nlemma (in monoid) m_concat_closed[simp]:\n \"set l \\<subseteq> carrier G \\<Longrightarrow> m_concat l \\<in> carrier G\"\n  by (induct l, auto)\n\nlemma (in monoid) m_concat_append[simp]:\n  assumes \"set a \\<subseteq> carrier G\"\n      and \"set b \\<subseteq> carrier G\"\n  shows \"m_concat (a@b) = m_concat a \\<otimes> m_concat b\"\nusing assms\nby(induct a)(auto simp add: m_assoc)\n\nlemma (in monoid) m_concat_cons[simp]:\n  \"\\<lbrakk> x \\<in> carrier G ; set xs \\<subseteq> carrier G \\<rbrakk> \\<Longrightarrow> m_concat (x#xs) = x \\<otimes> m_concat xs\"\nby(induct xs)(auto simp add: m_assoc)\n\n\n\n\nlemma (in monoid) m_concat_power[simp]: \"x \\<in> carrier G \\<Longrightarrow> m_concat (replicate n x) = x [^] n\"\nby(induct n, auto simp add:nat_pow_mult1l)\n\n\nsubsection \\<open>Isomorphisms\\<close>\n\ntext \\<open>A nicer way of proving that something is a group homomorphism or\nisomorphism.\\<close>\n\nlemma group_homI[intro]:\n  assumes range: \"h ` (carrier g1) \\<subseteq> carrier g2\"\n      and hom: \"\\<forall>x\\<in>carrier g1. \\<forall>y\\<in>carrier g1. h (x \\<otimes>\\<^bsub>g1\\<^esub> y) = h x \\<otimes>\\<^bsub>g2\\<^esub> h y\"\n  shows \"h \\<in> hom g1 g2\"\nproof-\n  have \"h \\<in> carrier g1 \\<rightarrow> carrier g2\" using range  by auto\n  thus \"h \\<in> hom g1 g2\" using hom unfolding hom_def by auto\nqed\n\nlemma (in group_hom) hom_injI:\n  assumes \"\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\n  shows \"inj_on h (carrier G)\"\nunfolding inj_on_def\nproof(rule ballI, rule ballI, rule impI)\n  fix x\n  fix y\n  assume x: \"x\\<in>carrier G\"\n     and y: \"y\\<in>carrier G\"\n     and \"h x = h y\"\n  hence \"h (x \\<otimes> inv y) = \\<one>\\<^bsub>H\\<^esub>\" and \"x \\<otimes> inv y \\<in> carrier G\"\n    by auto\n  with assms\n  have \"x \\<otimes> inv y = \\<one>\" by auto\n  thus \"x = y\" using x and y \n    by(auto dest: G.inv_equality)\nqed\n\nlemma (in group_hom) group_hom_isoI:\n  assumes inj1: \"\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\n      and surj: \"h ` (carrier G) = carrier H\"\n  shows \"h \\<in> iso G H\"\nproof-\n  from inj1\n  have \"inj_on h (carrier G)\" \n    by(auto intro: hom_injI)\n  hence bij: \"bij_betw h (carrier G) (carrier H)\"\n    using surj  unfolding bij_betw_def by auto\n  thus ?thesis\n    unfolding iso_def by auto\nqed\n\nlemma group_isoI[intro]:\n  assumes G: \"group G\"\n      and H: \"group H\"\n      and inj1: \"\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\n      and surj: \"h ` (carrier G) = carrier H\"\n      and hom: \"\\<forall>x\\<in>carrier G. \\<forall>y\\<in>carrier G. h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\n  shows \"h \\<in> iso G H\"\nproof-\n  from surj\n  have \"h \\<in> carrier G \\<rightarrow> carrier H\"\n    by auto\n  then interpret group_hom G H h using G and H and hom\n    by (auto intro!: group_hom.intro group_hom_axioms.intro)\n  show ?thesis\n  using assms unfolding hom_def by (auto intro: group_hom_isoI)\nqed\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Free-Groups/Generators.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7954442783363351}}
{"text": "\n(* Title:      Minkowski Integral Inequality\n   Author:     Omar A. Jasim <oajasim1@sheffield.ac.uk>, Sandor M. Veres <s.veres@sheffield.ac.uk>\n   Maintainer: Omar A. Jasim <oajasim1@sheffield.ac.uk>, Sandor M. Veres <s.veres@sheffield.ac.uk> \n*)\n\ntheory Minkowski_Integral_Inequality\nimports  Complex_Main \n\"~~/src/HOL/Probability/Set_Integral\"\n\"~~/src/HOL/library/Quadratic_Discriminant\"\nbegin\n\nlemma nonnegative_of_quadratic_polynomial:\n  fixes a b c x :: real\n  assumes  \"a > 0\"\n  and  \"\\<And>x. a*x^2 + b*x + c\\<ge>0 \"\n  shows \"discrim a b c \\<le>0\"\nproof -\nhave \"\\<exists>x. a*x^2 + b*x + c<0 \" when \"discrim a b c > 0\" \"a>0\"\n  proof -\n    let ?P=\"\\<lambda>x. a*x^2 + b*x +c\"\n   have \"?P (- b / (2*a)) =  (4*a*c-b^2)/(4*a)\" using \\<open>a>0\\<close>\n   apply (auto simp add:field_simps)\n      by algebra\n   also have \"... <0\"\n      using that unfolding discrim_def by (simp add: divide_neg_pos)\n   finally show ?thesis by blast\n   qed\nthen show ?thesis using assms\n  using not_less by blast\nqed\n\nlemma  schwaz_integral_ineq:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>t. t \\<in> A\"\n          \"set_integrable M A f\" \n          \"set_integrable M A g \"\n          \"set_integrable M A (\\<lambda>t. (f t)\\<^sup>2)\" \n          \"set_integrable M A (\\<lambda>t. (g t)\\<^sup>2)\"\n          \"set_integrable M A (\\<lambda>t. f t * g t)\"\n          \"(LINT t:A|M. (g t)\\<^sup>2) > 0\"\n  shows \"(LINT t:A|M. f t * g t) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\nproof -\n  fix  \\<alpha>:: \"real\"\n  let ?a =\"(LINT t:A|M. (g t)\\<^sup>2)\" and ?b=\"2*(LINT t:A|M. f t * g t)\" and ?c=\"(LINT t:A|M. (f t)\\<^sup>2)\"\n  have \"\\<And>\\<alpha>. (LINT t:A|M. (f t + \\<alpha>* g t)\\<^sup>2) \\<ge> 0\" \n    by (simp add: integral_nonneg_AE)\n  then have \"\\<And>\\<alpha>. (LINT t:A|M. (f t)\\<^sup>2 + 2 * (f t *(\\<alpha> * g t)) + (\\<alpha> * g t)\\<^sup>2 ) \\<ge> 0\" \n    by (simp add: add.commute add.left_commute mult.assoc power2_sum)\n  then have \"\\<And>\\<alpha>. (LINT t:A|M. (f t)\\<^sup>2 + 2*\\<alpha>* (f t * g t) + (\\<alpha>)\\<^sup>2*(g t)\\<^sup>2) \\<ge> 0 \" \n    by (simp add: diff_add_eq mult.assoc mult.left_commute semiring_normalization_rules(30))\n  then have \"\\<And>\\<alpha>. (LINT t:A|M. (f t)\\<^sup>2) + 2*\\<alpha>*(LINT t:A|M. f t * g t) + (\\<alpha>)\\<^sup>2* (LINT t:A|M.(g t)\\<^sup>2) \\<ge> 0\"\n    using assms by force\n  then have \"\\<And>\\<alpha>. ?c + ?b*\\<alpha> + ?a*(\\<alpha>)\\<^sup>2 \\<ge> 0\" \n    by (simp add: mult.assoc mult.commute)\n  then have \"\\<And>\\<alpha>. ?a*(\\<alpha>)\\<^sup>2 + ?b*\\<alpha> + ?c \\<ge>0\" \n    by (metis (lifting) add.assoc add.commute)\n  then have \"discrim ?a ?b ?c \\<le> 0\"  \n    using assms nonnegative_of_quadratic_polynomial by presburger\n  then have s1: \"?b\\<^sup>2 \\<le> 4 * ?a * ?c\" \n    by (simp add: discrim_def)\n  have \"?b\\<^sup>2\\<ge>0\" \n    by simp\n  then have \"?b \\<le> sqrt(4 * ?a * ?c)\" \n    using s1 by (simp add: real_le_rsqrt)\n  then have \"?b \\<le> 2 * sqrt(?a) * sqrt(?c)\" \n    by (simp add: real_sqrt_mult_distrib2)\n  then have \"2*(LINT t:A|M. f t * g t) \\<le> 2 * sqrt(LINT t:A|M. (g t)\\<^sup>2) * sqrt(LINT t:A|M. (f t)\\<^sup>2)\" \n    by blast\n  then have \"(LINT t:A|M. f t * g t) \\<le> sqrt(LINT t:A|M. (g t)\\<^sup>2) * sqrt(LINT t:A|M. (f t)\\<^sup>2)\" \n    by linarith\n  then have \"(LINT t:A|M. f t * g t) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)\" \n    by (simp add: semiring_normalization_rules(7))\n  from this assms show \"(LINT t:A|M. f t * g t) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)\" \n    by fastforce\nqed\n\nlemma minkowski_integral_ineq:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>t. t \\<in> A\"\n          \"set_integrable M A f\" \n          \"set_integrable M A g\"\n          \"set_integrable M A (\\<lambda>t. (f t)\\<^sup>2)\" \n          \"set_integrable M A (\\<lambda>t. (g t)\\<^sup>2)\"\n          \"set_integrable M A (\\<lambda>t. f t * g t)\"\n          \"(LINT t:A|M. (g t)\\<^sup>2) > 0\"\n  shows \"sqrt(LINT t:A|M. (f t + g t)\\<^sup>2) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\nproof -\n  have \"(LINT t:A|M. (f t + g t)\\<^sup>2) = (LINT t:A|M. (f t)\\<^sup>2 + 2 * (f t * g t) + (g t)\\<^sup>2)\" \n    by (simp add: add.commute add.left_commute mult.assoc power2_sum)\n  then have \"(LINT t:A|M. (f t + g t)\\<^sup>2) = (LINT t:A|M. (f t)\\<^sup>2) + 2*(LINT t:A|M. (f t * g t)) + (LINT t:A|M. (g t)\\<^sup>2)\"\n    using assms by auto\n  then have \"(LINT t:A|M. (f t + g t)\\<^sup>2) \\<le> \n   (LINT t:A|M. (f t)\\<^sup>2) + 2*(sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)) + (LINT t:A|M. (g t)\\<^sup>2)\"\n    using schwaz_integral_ineq assms by auto\n  then have \"(LINT t:A|M. (f t + g t)\\<^sup>2) \\<le> \n   (sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2)) * (sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2))\"\n    by (simp add: add.commute distrib_right sum_squares_ge_zero semiring_normalization_rules(34))\n  then have m:\"(LINT t:A|M. (f t + g t)\\<^sup>2) \\<le> (sqrt(LINT t:A|M. (f t)\\<^sup>2)+ sqrt(LINT t:A|M. (g t)\\<^sup>2))\\<^sup>2\"\n    by (simp add: power2_eq_square)\n(* to get rid of asb *)\n  have lhs: \"sqrt(LINT t:A|M. (f t + g t)\\<^sup>2) \\<ge> 0\" \n    by (simp add: integral_nonneg_AE)\n  have rhs: \"sqrt(LINT t:A|M. (f t)\\<^sup>2) \\<ge> 0 \\<and> sqrt(LINT t:A|M. (g t)\\<^sup>2) \\<ge> 0\"\n    by (simp add: integral_nonneg_AE)\n  from lhs rhs m have \"sqrt(LINT t:A|M. (f t + g t)\\<^sup>2) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2)+ sqrt(LINT t:A|M. (g t)\\<^sup>2)\" \n    using real_le_lsqrt by force\n  thus ?thesis.\nqed \n\n\n(*for negative*)\n\nlemma  schwaz_integral_ineq_ng:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>t. t \\<in> A\"\n          \"set_integrable M A f\" \n          \"set_integrable M A g \"\n          \"set_integrable M A (\\<lambda>t. (f t)\\<^sup>2)\" \n          \"set_integrable M A (\\<lambda>t. (g t)\\<^sup>2)\"\n          \"set_integrable M A (\\<lambda>t. f t * g t)\"\n          \"(LINT t:A|M. (g t)\\<^sup>2) > 0\"\n  shows \"(LINT t:A|M. f t * - g t) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\nproof -\n  fix  \\<alpha>:: \"real\"\n  let ?a =\"(LINT t:A|M. (g t)\\<^sup>2)\" and ?b=\"2*(LINT t:A|M. f t * -g t)\" and ?c=\"(LINT t:A|M. (f t)\\<^sup>2)\"\n  have \"\\<And>\\<alpha>. (LINT t:A|M. (f t - \\<alpha>* g t)\\<^sup>2) \\<ge> 0\" \n    by (simp add: integral_nonneg_AE)\n  then have \"\\<And>\\<alpha>. (LINT t:A|M. (f t)\\<^sup>2 + (\\<alpha>*g t)\\<^sup>2 - 2*\\<alpha>*(f t * g t)) \\<ge> 0\"\n    by (simp add:  power2_diff linordered_field_class.sign_simps(24) mult.left_commute)\n  then have \"\\<And>\\<alpha>. (LINT t:A|M. (f t)\\<^sup>2) + 2*\\<alpha>*(LINT t:A|M. f t * - g t) + (\\<alpha>)\\<^sup>2*(LINT t:A|M. (g t)\\<^sup>2) \\<ge> 0\"\n    using assms by (simp add: diff_add_eq semiring_normalization_rules(30))\n  then have \" \\<And>\\<alpha>. ?c + ?b*\\<alpha> + ?a*(\\<alpha>)\\<^sup>2 \\<ge> 0\" \n    by (simp add: mult.assoc mult.commute)\n  then have \"\\<And>\\<alpha>. ?a*(\\<alpha>)\\<^sup>2 + ?b*\\<alpha> + ?c \\<ge>0\" \n    by (metis (lifting) add.assoc add.commute)\n  then have \" discrim ?a ?b ?c \\<le> 0\"  \n    using assms  nonnegative_of_quadratic_polynomial by presburger\n  then have m:\" ?b\\<^sup>2 \\<le> 4 * ?a * ?c\" \n    by (simp add: discrim_def)\n  have \"?b\\<^sup>2\\<ge>0\" by simp\n  from this m have \"?b \\<le> sqrt(4 * ?a * ?c)\" \n    by (simp add: real_le_rsqrt)\n  then have \"?b \\<le> 2 * sqrt(?a) * sqrt(?c)\"\n    by (simp add: linordered_field_class.sign_simps(24) mult.left_commute real_sqrt_mult_distrib2)   \n  from this assms show \"(LINT t:A|M. f t * -g t) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)\" \n    by (simp add: linordered_field_class.sign_simps(24) mult.left_commute)\nqed\n\nlemma  minkowski_integral_ineq_ng:\n  fixes f g :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>t. t \\<in> A\"\n          \"set_integrable M A f\" \n          \"set_integrable M A g \"\n          \"set_integrable M A (\\<lambda>t. (f t)\\<^sup>2)\" \n          \"set_integrable M A (\\<lambda>t. (g t)\\<^sup>2)\"\n          \"set_integrable M A (\\<lambda>t. f t * g t)\"\n          \"(LINT t:A|M. (g t)\\<^sup>2) > 0\"\n  shows \"sqrt(LINT t:A|M. (f t - g t)\\<^sup>2) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\nproof -\n  have \"(LINT t:A|M. (f t + -g t)\\<^sup>2) = (LINT t:A|M. (f t)\\<^sup>2 + 2*(f t * -g t) + (g t)\\<^sup>2)\" \n    by (simp add: diff_add_eq power2_diff mult.assoc)\n  then have mn1: \"(LINT t:A|M. (f t + -g t)\\<^sup>2) = \n    (LINT t:A|M. (f t)\\<^sup>2) + 2*(LINT t:A|M. f t * -g t) + (LINT t:A|M. (g t)\\<^sup>2)\"\n    using assms by auto\n  have \"(LINT t:A|M. f t * -g t) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\n    using schwaz_integral_ineq_ng assms by blast\n  from this mn1  have \"(LINT t:A|M. (f t + -g t)\\<^sup>2) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) * (sqrt(LINT t:A|M. (f t)\\<^sup>2)\n    + sqrt(LINT t:A|M. (g t)\\<^sup>2)) + sqrt(LINT t:A|M. (g t)\\<^sup>2) * (sqrt(LINT t:A|M. (g t)\\<^sup>2) + sqrt(LINT t:A|M. (f t)\\<^sup>2))\"\n    by (simp add: sum_squares_ge_zero semiring_normalization_rules(34))\n  then have mn2: \"(LINT t:A|M. (f t + -g t)\\<^sup>2) \\<le> \n    (sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2))\\<^sup>2\"\n    by (simp add: add.commute distrib_right power2_eq_square)\n(* to get rid of asb *)\n  have lhs: \"sqrt(LINT t:A|M. (f t + -g t)\\<^sup>2) \\<ge> 0\" \n    by (simp add: integral_nonneg_AE)\n  have rhs: \"sqrt(LINT t:A|M. (f t)\\<^sup>2) \\<ge> 0 \\<and> sqrt(LINT t:A|M. (g t)\\<^sup>2) \\<ge> 0\"\n    by (simp add: integral_nonneg_AE)\n  show ?thesis using lhs rhs mn2 real_le_lsqrt by force\nqed \n\nend ", "meta": {"author": "Formal-Methods-of-Robotics", "repo": "Small-Gain-theorem", "sha": "03a72aa4c2d794675636829fbf9330fdf884a90d", "save_path": "github-repos/isabelle/Formal-Methods-of-Robotics-Small-Gain-theorem", "path": "github-repos/isabelle/Formal-Methods-of-Robotics-Small-Gain-theorem/Small-Gain-theorem-03a72aa4c2d794675636829fbf9330fdf884a90d/Minkowski_Integral_Inequality.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7953342025035517}}
{"text": "(*  Title:      Card_Lemmas.thy\n    Author:     Ata Keskin, TU München\n*)\n\nsection \"Lemmas involving the cardinality of sets\"\n\ntext \\<open>In this section, we prove some lemmas that make use of the term @{term card} or provide bounds for it.\\<close>\n\ntheory Card_Lemmas\n  imports Main\nbegin\n\nlemma card_Int_copy:\n  assumes \"finite X\" and \"A \\<union> B \\<subseteq> X\" and \"\\<exists>f. inj_on f (A \\<inter> B) \\<and> (A \\<union> B) \\<inter> (f ` (A \\<inter> B)) = {} \\<and> f ` (A \\<inter> B) \\<subseteq> X\"\n  shows \"card A + card B \\<le> card X\"\nproof -\n  from rev_finite_subset[OF assms(1), of A] rev_finite_subset[OF assms(1), of B] assms(2) \n  have finite_A: \"finite A\" and finite_B: \"finite B\" by blast+\n  then have finite_A_Un_B: \"finite (A \\<union> B)\" and finite_A_Int_B: \"finite (A \\<inter> B)\" by blast+\n  from assms(3) obtain f where f_inj_on: \"inj_on f (A \\<inter> B)\" \n                           and f_disjnt: \"(A \\<union> B) \\<inter> (f ` (A \\<inter> B)) = {}\" \n                           and f_imj_in: \"f ` (A \\<inter> B) \\<subseteq> X\" by blast\n  from finite_A_Int_B have finite_f_img: \"finite (f ` (A \\<inter> B))\" by blast\n  from assms(2) f_imj_in have union_in: \"(A \\<union> B) \\<union> f ` (A \\<inter> B) \\<subseteq> X\" by blast\n  \n  from card_Un_Int[OF finite_A finite_B] have \"card A + card B = card (A \\<union> B) + card (A \\<inter> B)\" .\n  also from card_image[OF f_inj_on] have \"... = card (A \\<union> B) + card (f ` (A \\<inter> B))\" by presburger\n  also from card_Un_disjoint[OF finite_A_Un_B finite_f_img f_disjnt] have \"... = card ((A \\<union> B) \\<union> f ` (A \\<inter> B))\" by argo\n  also from card_mono[OF assms(1) union_in] have \"... \\<le> card X\" by blast\n  finally show ?thesis .\nqed\n\nlemma finite_diff_not_empty: \n  assumes \"finite Y\" and \"card Y < card X\"\n  shows \"X - Y \\<noteq> {}\"\nproof\n  assume \"X - Y = {}\"\n  hence \"X \\<subseteq> Y\" by simp\n  from card_mono[OF assms(1) this] assms(2) show False by linarith\nqed\n\nlemma obtain_difference_element:\n  fixes F :: \"'a set set\"\n  assumes \"2 \\<le> card F\"\n  obtains \"x\" where \"x\\<in> \\<Union>F\" \"x \\<notin> \\<Inter>F\"\nproof -\n  from assms card_le_Suc_iff[of 1 F] obtain A F' where 0: \"F = insert A F'\" and 1: \"A \\<notin> F'\" and 2: \"1 \\<le> card F'\" by auto\n  from 2 card_le_Suc_iff[of 0 F'] obtain B F'' where 3: \"F' = insert B F''\" by auto\n  from 1 3 have A_noteq_B: \"A \\<noteq> B\" by blast\n  from 0 3 have A_in_F: \"A \\<in> F\" and B_in_F: \"B \\<in> F\" by blast+\n  from A_noteq_B have \"(A - B) \\<union> (B - A) \\<noteq> {}\" by simp\n  with A_in_F B_in_F that show thesis by blast\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Sauer_Shelah_Lemma/Card_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7953205910184565}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\nsubsection \"Arithmetic Expressions\"\n\ntheory AExp imports Main begin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw\\<open>\\snip{AExpaexpdef}{2}{1}{%\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\ntext_raw\\<open>\\snip{AExpavaldef}{1}{2}{%\\<close>\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>\\noindent\n  We can now write a series of updates to the function \\<open>\\<lambda>x. 0\\<close> compactly:\n\\<close>\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext\\<open>Note that this \\<open><\\<dots>>\\<close> syntax works for any function space\n\\<open>\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\\<close> where \\<open>\\<tau>\\<^sub>2\\<close> has a \\<open>0\\<close>.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Evaluate constant subsexpressions:\\<close>\n\ntext_raw\\<open>\\snip{AExpasimpconstdef}{0}{2}{%\\<close>\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext\\<open>Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors:\\<close>\n\ntext_raw\\<open>\\snip{AExpplusdef}{0}{2}{%\\<close>\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw\\<open>\\snip{AExpasimpdef}{2}{0}{%\\<close>\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntext\\<open>Note that in \\<^const>\\<open>asimp_const\\<close> the optimized constructor was\ninlined. Making it a separate function \\<^const>\\<open>plus\\<close> improves modularity of\nthe code and the proofs.\\<close>\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/IMP/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.7953205904139556}}
{"text": "(*\n  File: Dijkstra.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Dijkstra's algorithm for shortest paths\\<close>\n\ntheory Dijkstra\n  imports Mapping_Str Arrays_Ex\nbegin\n\ntext \\<open>\n  Verification of Dijkstra's algorithm: function part.\n\n  The algorithm is also verified by Nordhoff and Lammich in\n  \\cite{Dijkstra_Shortest_Path-AFP}.\n\\<close>\n\nsubsection \\<open>Graphs\\<close>\n\ndatatype graph = Graph \"nat list list\"\n\nfun size :: \"graph \\<Rightarrow> nat\" where\n  \"size (Graph G) = length G\"\n\nfun weight :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"weight (Graph G) m n = (G ! m) ! n\"\n\nfun valid_graph :: \"graph \\<Rightarrow> bool\" where\n  \"valid_graph (Graph G) \\<longleftrightarrow> (\\<forall>i<length G. length (G ! i) = length G)\"\nsetup \\<open>add_rewrite_rule @{thm valid_graph.simps}\\<close>\n\nsubsection \\<open>Paths on graphs\\<close>\n\ntext \\<open>The set of vertices less than n.\\<close>\ndefinition verts :: \"graph \\<Rightarrow> nat set\" where\n  \"verts G = {i. i < size G}\"\n\nlemma verts_mem [rewrite]: \"i \\<in> verts G \\<longleftrightarrow> i < size G\" by (simp add: verts_def)\nlemma card_verts [rewrite]: \"card (verts G) = size G\" using verts_def by auto\nlemma finite_verts [forward]: \"finite (verts G)\" using verts_def by auto\n\ndefinition is_path :: \"graph \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"is_path G p \\<longleftrightarrow> p \\<noteq> [] \\<and> set p \\<subseteq> verts G\"\n\nlemma is_path_to_in_verts [forward]: \"is_path G p \\<Longrightarrow> hd p \\<in> verts G \\<and> last p \\<in> verts G\"\n@proof @have \"last p \\<in> set p\" @qed\n\ndefinition joinable :: \"graph \\<Rightarrow> nat list \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"joinable G p q \\<longleftrightarrow> (is_path G p \\<and> is_path G q \\<and> last p = hd q)\"\n\ndefinition path_join :: \"graph \\<Rightarrow> nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where [rewrite]:\n  \"path_join G p q = p @ tl q\"\nsetup \\<open>register_wellform_data (\"path_join G p q\", [\"joinable G p q\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"path_join G p q\", \"joinable G p q\")\\<close>\n\nlemma path_join_is_path:\n  \"joinable G p q \\<Longrightarrow> is_path G (path_join G p q)\"\n@proof @have \"q = hd q # tl q\" @qed\nsetup \\<open>add_forward_prfstep_cond @{thm path_join_is_path} [with_term \"path_join ?G ?p ?q\"]\\<close>\n\nfun path_weight :: \"graph \\<Rightarrow> nat list \\<Rightarrow> nat\" where\n  \"path_weight G [] = 0\"\n| \"path_weight G (x # xs) = (if xs = [] then 0 else weight G x (hd xs) + path_weight G xs)\"\nsetup \\<open>fold add_rewrite_rule @{thms path_weight.simps}\\<close>\n\nlemma path_weight_singleton [rewrite]: \"path_weight G [x] = 0\" by auto2\nlemma path_weight_doubleton [rewrite]: \"path_weight G [m, n] = weight G m n\" by auto2\n\nlemma path_weight_sum [rewrite]:\n  \"joinable G p q \\<Longrightarrow> path_weight G (path_join G p q) = path_weight G p + path_weight G q\"\n@proof @induct p @qed\n\nfun path_set :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list set\" where\n  \"path_set G m n = {p. is_path G p \\<and> hd p = m \\<and> last p = n}\"\n\nlemma path_set_mem [rewrite]:\n  \"p \\<in> path_set G m n \\<longleftrightarrow> is_path G p \\<and> hd p = m \\<and> last p = n\" by simp\n\nlemma path_join_set: \"joinable G p q \\<Longrightarrow> path_join G p q \\<in> path_set G (hd p) (last q)\"\n@proof @have \"q = hd q # tl q\" @case \"tl q = []\" @qed\nsetup \\<open>add_forward_prfstep_cond @{thm path_join_set} [with_term \"path_join ?G ?p ?q\"]\\<close>\n\nsubsection \\<open>Shortest paths\\<close>\n\ndefinition is_shortest_path :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"is_shortest_path G m n p \\<longleftrightarrow>\n     (p \\<in> path_set G m n \\<and> (\\<forall>p'\\<in>path_set G m n. path_weight G p' \\<ge> path_weight G p))\"\n\nlemma is_shortest_pathD1 [forward]:\n  \"is_shortest_path G m n p \\<Longrightarrow> p \\<in> path_set G m n\" by auto2\n\nlemma is_shortest_pathD2 [forward]:\n  \"is_shortest_path G m n p \\<Longrightarrow> p' \\<in> path_set G m n \\<Longrightarrow> path_weight G p' \\<ge> path_weight G p\" by auto2\nsetup \\<open>del_prfstep_thm_eqforward @{thm is_shortest_path_def}\\<close>\n\ndefinition has_dist :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where [rewrite]:\n  \"has_dist G m n \\<longleftrightarrow> (\\<exists>p. is_shortest_path G m n p)\"\n\nlemma has_distI [forward]: \"is_shortest_path G m n p \\<Longrightarrow> has_dist G m n\" by auto2\nlemma has_distD [resolve]: \"has_dist G m n \\<Longrightarrow> \\<exists>p. is_shortest_path G m n p\" by auto2\nlemma has_dist_to_in_verts [forward]: \"has_dist G u v \\<Longrightarrow> u \\<in> verts G \\<and> v \\<in> verts G\" by auto2\nsetup \\<open>del_prfstep_thm @{thm has_dist_def}\\<close>\n\ndefinition dist :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where [rewrite]:\n  \"dist G m n = path_weight G (SOME p. is_shortest_path G m n p)\"\nsetup \\<open>register_wellform_data (\"dist G m n\", [\"has_dist G m n\"])\\<close>\n\nlemma dist_eq [rewrite]:\n  \"is_shortest_path G m n p \\<Longrightarrow> dist G m n = path_weight G p\" by auto2\n\nlemma distD [forward]:\n  \"has_dist G m n \\<Longrightarrow> p \\<in> path_set G m n \\<Longrightarrow> path_weight G p \\<ge> dist G m n\" by auto2\nsetup \\<open>del_prfstep_thm @{thm dist_def}\\<close>\n\nlemma shortest_init [resolve]: \"n \\<in> verts G \\<Longrightarrow> is_shortest_path G n n [n]\" by auto2\n\nsubsection \\<open>Interior points\\<close>\n\ntext \\<open>List of interior points\\<close>\ndefinition int_pts :: \"nat list \\<Rightarrow> nat set\" where [rewrite]:\n  \"int_pts p = set (butlast p)\"\n\nlemma int_pts_singleton [rewrite]: \"int_pts [x] = {}\" by auto2\nlemma int_pts_doubleton [rewrite]: \"int_pts [x, y] = {x}\" by auto2\n\ndefinition path_set_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> nat list set\" where\n  \"path_set_on G m n V = {p. p \\<in> path_set G m n \\<and> int_pts p \\<subseteq> V}\"\n\nlemma path_set_on_mem [rewrite]:\n  \"p \\<in> path_set_on G m n V \\<longleftrightarrow> p \\<in> path_set G m n \\<and> int_pts p \\<subseteq> V\" by (simp add: path_set_on_def)\n\ntext \\<open>Version of shortest path on a set of points\\<close>\ndefinition is_shortest_path_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> nat set \\<Rightarrow> bool\" where [rewrite]:\n  \"is_shortest_path_on G m n p V \\<longleftrightarrow>\n    (p \\<in> path_set_on G m n V \\<and> (\\<forall>p'\\<in>path_set_on G m n V. path_weight G p' \\<ge> path_weight G p))\"\n\nlemma is_shortest_path_onD1 [forward]:\n  \"is_shortest_path_on G m n p V \\<Longrightarrow> p \\<in> path_set_on G m n V\" by auto2\n\nlemma is_shortest_path_onD2 [forward]:\n  \"is_shortest_path_on G m n p V \\<Longrightarrow> p' \\<in> path_set_on G m n V \\<Longrightarrow> path_weight G p' \\<ge> path_weight G p\" by auto2\nsetup \\<open>del_prfstep_thm_eqforward @{thm is_shortest_path_on_def}\\<close>\n\ndefinition has_dist_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> bool\" where [rewrite]:\n  \"has_dist_on G m n V \\<longleftrightarrow> (\\<exists>p. is_shortest_path_on G m n p V)\"\n\nlemma has_dist_onI [forward]: \"is_shortest_path_on G m n p V \\<Longrightarrow> has_dist_on G m n V\" by auto2\nlemma has_dist_onD [resolve]: \"has_dist_on G m n V \\<Longrightarrow> \\<exists>p. is_shortest_path_on G m n p V\" by auto2\nsetup \\<open>del_prfstep_thm @{thm has_dist_on_def}\\<close>\n\ndefinition dist_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> nat\" where [rewrite]:\n  \"dist_on G m n V = path_weight G (SOME p. is_shortest_path_on G m n p V)\"\nsetup \\<open>register_wellform_data (\"dist_on G m n V\", [\"has_dist_on G m n V\"])\\<close>\n\nlemma dist_on_eq [rewrite]:\n  \"is_shortest_path_on G m n p V \\<Longrightarrow> dist_on G m n V = path_weight G p\" by auto2\n\nlemma dist_onD [forward]:\n  \"has_dist_on G m n V \\<Longrightarrow> p \\<in> path_set_on G m n V \\<Longrightarrow> path_weight G p \\<ge> dist_on G m n V\" by auto2\nsetup \\<open>del_prfstep_thm @{thm dist_on_def}\\<close>\n\nsubsection \\<open>Two splitting lemmas\\<close>\n\nlemma path_split1 [backward]: \"is_path G p \\<Longrightarrow> hd p \\<in> V \\<Longrightarrow> last p \\<notin> V \\<Longrightarrow>\n  \\<exists>p1 p2. joinable G p1 p2 \\<and> p = path_join G p1 p2 \\<and> int_pts p1 \\<subseteq> V \\<and> hd p2 \\<notin> V\"\n@proof @induct p @with\n  @subgoal \"p = a # p'\"\n    @let \"p = a # p'\"\n    @case \"p' = []\"\n    @case \"hd p' \\<notin> V\" @with @have \"p = path_join G [a, hd p'] p'\" @end\n    @obtain p1 p2 where \"joinable G p1 p2\" \"p' = path_join G p1 p2\" \"int_pts p1 \\<subseteq> V\" \"hd p2 \\<notin> V\"\n    @have \"p = path_join G (a # p1) p2\"\n  @endgoal @end\n@qed\n\nlemma path_split2 [backward]: \"is_path G p \\<Longrightarrow> hd p \\<noteq> last p \\<Longrightarrow>\n  \\<exists>q n. joinable G q [n, last p] \\<and> p = path_join G q [n, last p]\"\n@proof\n  @have \"p = butlast p @ [last p]\"\n  @have \"butlast p \\<noteq> []\"\n  @let \"n = last (butlast p)\"\n  @have \"p = path_join G (butlast p) [n, last p]\"\n@qed\n\nsubsection \\<open>Deriving has\\_dist and has\\_dist\\_on\\<close>\n\ndefinition known_dists :: \"graph \\<Rightarrow> nat set \\<Rightarrow> bool\" where [rewrite]:\n  \"known_dists G V \\<longleftrightarrow> (V \\<subseteq> verts G \\<and> 0 \\<in> V \\<and>\n      (\\<forall>i\\<in>verts G. has_dist_on G 0 i V) \\<and>\n      (\\<forall>i\\<in>V. has_dist G 0 i \\<and> dist G 0 i = dist_on G 0 i V))\"\n\nlemma derive_dist [backward2]:\n  \"known_dists G V \\<Longrightarrow>\n   m \\<in> verts G - V \\<Longrightarrow>\n   \\<forall>i\\<in>verts G - V. dist_on G 0 i V \\<ge> dist_on G 0 m V \\<Longrightarrow>\n   has_dist G 0 m \\<and> dist G 0 m = dist_on G 0 m V\"\n@proof\n  @obtain p where \"is_shortest_path_on G 0 m p V\"\n  @have \"is_shortest_path G 0 m p\" @with\n    @have \"p \\<in> path_set G 0 m\"\n    @have \"\\<forall>p'\\<in>path_set G 0 m. path_weight G p' \\<ge> path_weight G p\" @with\n      @obtain p1 p2 where \"joinable G p1 p2\" \"p' = path_join G p1 p2\"\n                          \"int_pts p1 \\<subseteq> V\" \"hd p2 \\<notin> V\"\n      @let \"x = last p1\"\n      @have \"dist_on G 0 x V \\<ge> dist_on G 0 m V\"\n      @have \"p1 \\<in> path_set_on G 0 x V\"\n      @have \"path_weight G p1 \\<ge> dist_on G 0 x V\"\n      @have \"path_weight G p' \\<ge> dist_on G 0 m V + path_weight G p2\"\n    @end\n  @end\n@qed\n\nlemma join_def' [resolve]: \"joinable G p q \\<Longrightarrow> path_join G p q = butlast p @ q\"\n@proof\n  @have \"p = butlast p @ [last p]\"\n  @have \"path_join G p q = butlast p @ [last p] @ tl q\"\n@qed\n\nlemma int_pts_join [rewrite]:\n  \"joinable G p q \\<Longrightarrow> int_pts (path_join G p q) = int_pts p \\<union> int_pts q\"\n@proof @have \"path_join G p q = butlast p @ q\" @qed\n\nlemma dist_on_triangle_ineq [backward]:\n  \"has_dist_on G k m V \\<Longrightarrow> has_dist_on G k n V \\<Longrightarrow> V \\<subseteq> verts G \\<Longrightarrow> n \\<in> verts G \\<Longrightarrow> m \\<in> V \\<Longrightarrow>\n   dist_on G k m V + weight G m n \\<ge> dist_on G k n V\"\n@proof\n  @obtain p where \"is_shortest_path_on G k m p V\"\n  @let \"pq = path_join G p [m, n]\"\n  @have \"V \\<union> {m} = V\"\n  @have \"pq \\<in> path_set_on G k n V\"\n@qed\n\nlemma derive_dist_on [backward2]:\n  \"known_dists G V \\<Longrightarrow>\n   m \\<in> verts G - V \\<Longrightarrow>\n   \\<forall>i\\<in>verts G - V. dist_on G 0 i V \\<ge> dist_on G 0 m V \\<Longrightarrow>\n   V' = V \\<union> {m} \\<Longrightarrow>\n   n \\<in> verts G - V' \\<Longrightarrow>\n   has_dist_on G 0 n V' \\<and> dist_on G 0 n V' = min (dist_on G 0 n V) (dist_on G 0 m V + weight G m n)\"\n@proof\n  @have \"has_dist G 0 m \\<and> dist G 0 m = dist_on G 0 m V\"\n  @let \"M = min (dist_on G 0 n V) (dist_on G 0 m V + weight G m n)\"\n  @have \"\\<forall>p\\<in>path_set_on G 0 n V'. path_weight G p \\<ge> M\" @with\n    @obtain q n' where \"joinable G q [n', n]\" \"p = path_join G q [n', n]\"\n    @have \"q \\<in> path_set G 0 n'\"\n    @have \"n' \\<in> V'\"\n    @case \"n' \\<in> V\" @with\n      @have \"dist_on G 0 n' V = dist G 0 n'\"\n      @have \"path_weight G q \\<ge> dist_on G 0 n' V\"\n      @have \"path_weight G p \\<ge> dist_on G 0 n' V + weight G n' n\"\n      @have \"dist_on G 0 n' V + weight G n' n \\<ge> dist_on G 0 n V\"\n    @end\n    @have \"n' = m\"\n    @have \"path_weight G q \\<ge> dist G 0 m\"\n    @have \"path_weight G p \\<ge> dist G 0 m + weight G m n\"\n  @end\n  @case \"dist_on G 0 m V + weight G m n \\<ge> dist_on G 0 n V\" @with\n    @obtain p where \"is_shortest_path_on G 0 n p V\"\n    @have \"is_shortest_path_on G 0 n p V'\" @with\n      @have \"p \\<in> path_set_on G 0 n V'\" @with @have \"V \\<subseteq> V'\" @end\n    @end\n  @end\n  @have \"M = dist_on G 0 m V + weight G m n\"\n  @obtain pm where \"is_shortest_path_on G 0 m pm V\"\n  @have \"path_weight G pm = dist G 0 m\"\n  @let \"p = path_join G pm [m, n]\"\n  @have \"joinable G pm [m, n]\"\n  @have \"path_weight G p = path_weight G pm + weight G m n\"\n  @have \"is_shortest_path_on G 0 n p V'\"\n@qed\n\nsubsection \\<open>Invariant for the Dijkstra's algorithm\\<close>\n\ntext \\<open>The state consists of an array maintaining the best estimates,\n  and a heap containing estimates for the unknown vertices.\\<close>\ndatatype state = State (est: \"nat list\") (heap: \"(nat, nat) map\")\nsetup \\<open>add_simple_datatype \"state\"\\<close>\n\ndefinition unknown_set :: \"state \\<Rightarrow> nat set\" where [rewrite]:\n  \"unknown_set S = keys_of (heap S)\"\n\ndefinition known_set :: \"state \\<Rightarrow> nat set\" where [rewrite]:\n  \"known_set S = {..<length (est S)} - unknown_set S\"\n\ntext \\<open>Invariant: for every vertex, the estimate is at least the shortest distance.\n  Furthermore, for the known vertices the estimate is exact.\\<close>\ndefinition inv :: \"graph \\<Rightarrow> state \\<Rightarrow> bool\" where [rewrite]:\n  \"inv G S \\<longleftrightarrow> (let V = known_set S; W = unknown_set S; M = heap S in\n      (length (est S) = size G \\<and> known_dists G V \\<and>\n      keys_of M \\<subseteq> verts G \\<and>\n      (\\<forall>i\\<in>W. M\\<langle>i\\<rangle> = Some (est S ! i)) \\<and>\n      (\\<forall>i\\<in>V. est S ! i = dist G 0 i) \\<and>\n      (\\<forall>i\\<in>verts G. est S ! i = dist_on G 0 i V)))\"\n\nlemma invE1 [forward]: \"inv G S \\<Longrightarrow> length (est S) = size G \\<and> known_dists G (known_set S) \\<and> unknown_set S \\<subseteq> verts G\" by auto2\nlemma invE2 [forward]: \"inv G S \\<Longrightarrow> i \\<in> known_set S \\<Longrightarrow> est S ! i = dist G 0 i\" by auto2\nlemma invE3 [forward]: \"inv G S \\<Longrightarrow> i \\<in> verts G \\<Longrightarrow> est S ! i = dist_on G 0 i (known_set S)\" by auto2\nlemma invE4 [rewrite]: \"inv G S \\<Longrightarrow> i \\<in> unknown_set S \\<Longrightarrow> (heap S)\\<langle>i\\<rangle> = Some (est S ! i)\" by auto2\nsetup \\<open>del_prfstep_thm_str \"@eqforward\" @{thm inv_def}\\<close>\n\nlemma inv_unknown_set [rewrite]:\n  \"inv G S \\<Longrightarrow> unknown_set S = verts G - known_set S\" by auto2\n\nlemma dijkstra_end_inv [forward]:\n  \"inv G S \\<Longrightarrow> unknown_set S = {} \\<Longrightarrow> \\<forall>i\\<in>verts G. has_dist G 0 i \\<and> est S ! i = dist G 0 i\" by auto2\n\nsubsection \\<open>Starting state\\<close>\n\ndefinition dijkstra_start_state :: \"graph \\<Rightarrow> state\" where [rewrite]:\n  \"dijkstra_start_state G =\n     State (list (\\<lambda>i. if i = 0 then 0 else weight G 0 i) (size G))\n           (map_constr (\\<lambda>i. i > 0) (\\<lambda>i. weight G 0 i) (size G))\"\nsetup \\<open>register_wellform_data (\"dijkstra_start_state G\", [\"size G > 0\"])\\<close>\n\nlemma dijkstra_start_known_set [rewrite]:\n  \"size G > 0 \\<Longrightarrow> known_set (dijkstra_start_state G) = {0}\" by auto2\n    \nlemma dijkstra_start_unknown_set [rewrite]:\n  \"size G > 0 \\<Longrightarrow> unknown_set (dijkstra_start_state G) = verts G - {0}\" by auto2\n\nlemma card_start_state [rewrite]:\n  \"size G > 0 \\<Longrightarrow> card (unknown_set (dijkstra_start_state G)) = size G - 1\"\n@proof @have \"0 \\<in> verts G\" @qed\n\ntext \\<open>Starting start of Dijkstra's algorithm satisfies the invariant.\\<close>\ntheorem dijkstra_start_inv [backward]:\n  \"size G > 0 \\<Longrightarrow> inv G (dijkstra_start_state G)\"\n@proof\n  @let \"V = {0::nat}\"\n  @have \"has_dist G 0 0 \\<and> dist G 0 0 = 0\" @with\n    @have \"is_shortest_path G 0 0 [0]\" @end\n  @have \"has_dist_on G 0 0 V \\<and> dist_on G 0 0 V = 0\" @with\n    @have \"is_shortest_path_on G 0 0 [0] V\" @end\n  @have \"V \\<subseteq> verts G \\<and> 0 \\<in> V\"\n  @have (@rule) \"\\<forall>i\\<in>verts G. i \\<noteq> 0 \\<longrightarrow> has_dist_on G 0 i V \\<and> dist_on G 0 i V = weight G 0 i\" @with\n    @let \"p = [0, i]\"\n    @have \"is_shortest_path_on G 0 i p V\" @with\n      @have \"p \\<in> path_set_on G 0 i V\"\n      @have \"\\<forall>p'\\<in>path_set_on G 0 i V. path_weight G p' \\<ge> weight G 0 i\" @with\n        @obtain q n where \"joinable G q [n, last p']\" \"p' = path_join G q [n, last p']\"\n        @have \"n \\<in> V\" @have \"n = 0\"\n        @have \"path_weight G p' = path_weight G q + weight G 0 i\"\n      @end\n    @end\n  @end\n@qed\n\nsubsection \\<open>Step of Dijkstra's algorithm\\<close>\n\nfun dijkstra_step :: \"graph \\<Rightarrow> nat \\<Rightarrow> state \\<Rightarrow> state\" where\n  \"dijkstra_step G m (State e M) =\n    (let M' = delete_map m M;\n         e' = list_update_set (\\<lambda>i. i \\<in> keys_of M') (\\<lambda>i. min (e ! m + weight G m i) (e ! i)) e;\n         M'' = map_update_all (\\<lambda>i. e' ! i) M'\n     in State e' M'')\"\nsetup \\<open>add_rewrite_rule @{thm dijkstra_step.simps}\\<close>\nsetup \\<open>register_wellform_data (\"dijkstra_step G m S\", [\"inv G S\", \"m \\<in> unknown_set S\"])\\<close>\n\nlemma has_dist_on_larger [backward1]:\n  \"has_dist G m n \\<Longrightarrow> has_dist_on G m n V \\<Longrightarrow> dist_on G m n V = dist G m n \\<Longrightarrow>\n   has_dist_on G m n (V \\<union> {x}) \\<and> dist_on G m n (V \\<union> {x}) = dist G m n\"\n@proof\n  @obtain p where \"is_shortest_path_on G m n p V\"\n  @let \"V' = V \\<union> {x}\"\n  @have \"p \\<in> path_set_on G m n V'\" @with @have \"V \\<subseteq> V'\" @end\n  @have \"is_shortest_path_on G m n p V'\"\n@qed\n\nlemma dijkstra_step_unknown_set [rewrite]:\n  \"inv G S \\<Longrightarrow> m \\<in> unknown_set S \\<Longrightarrow> unknown_set (dijkstra_step G m S) = unknown_set S - {m}\" by auto2\n\nlemma dijkstra_step_known_set [rewrite]:\n  \"inv G S \\<Longrightarrow> m \\<in> unknown_set S \\<Longrightarrow> known_set (dijkstra_step G m S) = known_set S \\<union> {m}\" by auto2\n\ntext \\<open>One step of Dijkstra's algorithm preserves the invariant.\\<close>\ntheorem dijkstra_step_preserves_inv [backward]:\n  \"inv G S \\<Longrightarrow> is_heap_min m (heap S) \\<Longrightarrow> inv G (dijkstra_step G m S)\"\n@proof\n  @let \"V = known_set S\" \"V' = V \\<union> {m}\"\n  @have (@rule) \"\\<forall>i\\<in>V. has_dist G 0 i \\<and> has_dist_on G 0 i V' \\<and> dist_on G 0 i V' = dist G 0 i\"\n  @have \"has_dist G 0 m \\<and> dist G 0 m = dist_on G 0 m V\"\n  @have \"has_dist_on G 0 m V' \\<and> dist_on G 0 m V' = dist G 0 m\"\n  @have (@rule) \"\\<forall>i\\<in>verts G - V'. has_dist_on G 0 i V' \\<and> dist_on G 0 i V' = min (dist_on G 0 i V) (dist_on G 0 m V + weight G m i)\"\n  @let \"S' = dijkstra_step G m S\"\n  @have \"known_dists G V'\"\n  @have \"\\<forall>i\\<in>V'. est S' ! i = dist G 0 i\"\n  @have \"\\<forall>i\\<in>verts G. est S' ! i = dist_on G 0 i V'\" @with @case \"i \\<in> V'\" @end\n@qed\n\ndefinition is_dijkstra_step :: \"graph \\<Rightarrow> state \\<Rightarrow> state \\<Rightarrow> bool\" where [rewrite]:\n  \"is_dijkstra_step G S S' \\<longleftrightarrow> (\\<exists>m. is_heap_min m (heap S) \\<and> S' = dijkstra_step G m S)\"\n\nlemma is_dijkstra_stepI [backward2]:\n  \"is_heap_min m (heap S) \\<Longrightarrow> dijkstra_step G m S = S' \\<Longrightarrow> is_dijkstra_step G S S'\" by auto2\n\nlemma is_dijkstra_stepD1 [forward]:\n  \"inv G S \\<Longrightarrow> is_dijkstra_step G S S' \\<Longrightarrow> inv G S'\" by auto2\n\nlemma is_dijkstra_stepD2 [forward]:\n  \"inv G S \\<Longrightarrow> is_dijkstra_step G S S' \\<Longrightarrow> card (unknown_set S') = card (unknown_set S) - 1\" by auto2\nsetup \\<open>del_prfstep_thm @{thm is_dijkstra_step_def}\\<close>\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Auto2_Imperative_HOL/Functional/Dijkstra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8791467580102418, "lm_q1q2_score": 0.7953205895862007}}
{"text": "theory \"ch2\"\n  imports Main\nbegin\nfun add2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add2 0 n = n \" |\n\"add2 (Suc m) n = Suc (add2 m n)\"\n\nlemma add2_assoc [simp]: \"add2 (add2 x y) z = add2 x (add2 y z)\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma add2_0rneutral [simp] : \"add2 x 0 = x\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma add2_rightsucc [simp] : \"Suc (add2 x y) = add2 x (Suc y)\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma add2_comm [simp]: \"add2 x y = add2 y x\"\n  apply(induction x)\n  apply(auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc m) = Suc (Suc (double m))\"\n\nlemma double_correct : \"double x = add2 x x\"\n  apply(induction x)\n  apply(auto)\n  done\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count x [] = 0\" |\n\"count x (y # xs) = (if x = y then count x xs + 1 else count x xs)\"\n\nlemma count_bounded_length : \"count x xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nfun snoc :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"snoc x [] = [x]\" |\n\"snoc x (y # xs) = y # snoc x xs\"\n\nfun snocrev :: \" 'a list \\<Rightarrow> 'a list\" where\n\"snocrev [] = []\" |\n\"snocrev (x # xs) = snoc x (snocrev xs)\"\n\nlemma snocrev_snoc [simp] : \"snocrev (snoc x xs) = x # snocrev xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nlemma snocrev_self_inverse : \"snocrev (snocrev xs) = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n  \"sum_upto 0 = 0\" |\n  \"sum_upto (Suc m) = (Suc m) + sum_upto m\"\n\nlemma sum_upto_closed_form : \"sum_upto m = m * (m + 1) div 2\"\n  apply(induction m)\n  apply(auto)\n  done\n\ndatatype 'a tree = Tip | Node \"'a tree * 'a * 'a tree\"\n\nfun mirror :: \"'a tree => 'a tree\" where\n  \"mirror Tip = Tip\" |\n  \"mirror (Node (l, v, r)) = Node (mirror r, v, mirror l)\"\n\nfun contents :: \"'a tree => 'a list\" where\n  \"contents Tip = []\" |\n  \"contents (Node (l, v, r)) = v # (contents l @ contents r)\"\n\nfun sum_tree :: \"nat tree => nat\" where\n  \"sum_tree Tip = 0\" |\n  \"sum_tree (Node (l, v, r)) = sum_tree l + v + sum_tree r\"\n\nlemma sum_tree_contents : \"sum_tree x = sum_list (contents x)\"\n  apply(induction x)\n  apply(auto)\n  done\n\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2 * 'a * 'a tree2\"\n\nfun mirror2 :: \"'a tree2 => 'a tree2\" where\n  \"mirror2 (Tip x) = Tip x\" |\n  \"mirror2 (Node (l,v,r)) = Node (mirror2 r, v, mirror2 l)\"\n\nfun preorder :: \"'a tree2 => 'a list\" where\n  \"preorder (Tip x) = [x]\" |\n  \"preorder (Node (l,v,r)) = v # (preorder l @ preorder r)\" \n\nfun postorder :: \"'a tree2 => 'a list\" where\n  \"postorder (Tip x) = [x]\" |\n  \"postorder (Node (l,v,r)) = snoc v (postorder l @ postorder r)\"\n\n(* This one is needed because we're using snoc and so have no\n   builtin simplification rules. *)\nlemma snoc_rev_simp [simp] : \"rev (snoc x xs) = x # rev xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nlemma \"preorder (mirror2 t) = rev (postorder t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\nfun intersperse :: \"'a => 'a list => 'a list\" where\n  \"intersperse _ [] = []\" |\n  \"intersperse _ [x] = [x]\" |\n  \"intersperse x (y # ys) = y # x # intersperse x ys\"\n\nlemma \"map f (intersperse x xs) = intersperse (f x) (map f xs)\"\n  apply(induction xs rule: intersperse.induct)\n  apply(auto)\n  done\n\nfun itadd :: \"nat => nat => nat\" where\n  \"itadd 0 m = m\" |\n  \"itadd (Suc m) n = itadd m (Suc n)\"\n\n(* Obviously, we want to prove this thing correct, so... \n  Proof notes:\n  We need to allow n to be arbitrary in the induction hypothesis,\n  otherwise the proof doesn't go through in the induction step.\n  We delete the add2_comm rule, to stop auto trying to apply it.\n  When it does, we end up with the add2 on the rhs in the wrong shape,\n  which stops us applying the induction hypothesis and finishing the proof.\n*)\nlemma \"itadd m n = add2 m n\"\n  apply(induction m arbitrary: n)\n  apply(auto simp del: add2_comm)\n  done\n\ndatatype tree0 = Tip | Node \"tree0 * tree0\"\n\nfun explode :: \"nat => tree0 => tree0\" where\n  \"explode 0 t = t\" |\n  \"explode (Suc n) t = explode n (Node (t, t))\"\n\nfun nodes :: \"tree0 => nat\" where\n  \"nodes Tip = 1\" |\n  \"nodes (Node (l, r)) = nodes l + nodes r + 1\"\n\nlemma \"nodes (explode n t) = 2^n * (nodes t) + 2^n - 1\"\n  apply(induction n arbitrary: t)\n  apply(auto simp add: algebra_simps)\n  done\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp => int => int\" where\n  \"eval Var x = x\" |\n  \"eval (Const y) x = y\" |\n  \"eval (Add y z) x = eval y x + eval z x\" |\n  \"eval (Mult y z) x = eval y x * eval z x\"\n\nfun evalp :: \"int list => int => int\" where\n  \"evalp [] x = 0\" |\n  \"evalp (c # cs) x = c + x * (evalp cs x)\"\n\nfun add_coeffs :: \"int list => int list => int list\" where\n  \"add_coeffs [] xs = xs\" |\n  \"add_coeffs xs [] = xs\" |\n  \"add_coeffs (x # xs) (y # ys) = (x + y) # add_coeffs xs ys\"\n\nfun mul_coeffs :: \"int list => int list => int list\" where\n  \"mul_coeffs [] xs = []\" |\n  \"mul_coeffs (y # ys) xs = add_coeffs (map (\\<lambda> z . y * z) xs) (0 # mul_coeffs ys xs)\"\n\nfun coeffs :: \"exp => int list\" where\n  \"coeffs Var = [0, 1]\" |\n  \"coeffs (Const x) = [x]\" |\n  \"coeffs (Add x y) = add_coeffs (coeffs x) (coeffs y)\" |\n  \"coeffs (Mult x y) = mul_coeffs (coeffs x) (coeffs y)\"\n\n(*Note to self: SERIOUSLY use the right induction rules please.*)\nlemma evalp_addcoeffs [simp] : \"evalp (add_coeffs xs ys) x = evalp xs x + evalp ys x\"\n  apply(induction rule: add_coeffs.induct)\n  apply(auto simp add: algebra_simps)\n  done\n\nlemma evalp_scaling [simp] : \"evalp (map (( * ) y) xs) x = y * evalp xs x\"\n  apply(induction xs)\n  apply(auto simp add: algebra_simps)\n  done\n\nlemma evalp_mulcoeffs [simp] : \"evalp (mul_coeffs xs ys) x = evalp xs x * evalp ys x\"\n  apply(induction rule: mul_coeffs.induct)\n  apply(auto simp add: algebra_simps)\n  done\n\nlemma \"evalp (coeffs e) x = eval e x\"\n  apply(induction e)\n  apply(auto)\n  done\nend", "meta": {"author": "rvb", "repo": "isabelle-concrete-semantics", "sha": "88837f88c56f127a2d988395a89b46e4bea3ad13", "save_path": "github-repos/isabelle/rvb-isabelle-concrete-semantics", "path": "github-repos/isabelle/rvb-isabelle-concrete-semantics/isabelle-concrete-semantics-88837f88c56f127a2d988395a89b46e4bea3ad13/ch2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8933094124452287, "lm_q1q2_score": 0.7953082172409489}}
{"text": "section \"Derivatives of Extended Regular Expressions\"\n\n(* Author: Christian Urban *)\n\ntheory Derivatives3\nimports Regular_Exps3\nbegin\n\ntext\\<open>This theory is based on work by Brozowski.\\<close>\n\nsubsection \\<open>Brzozowski's derivatives of regular expressions\\<close>\n\nfun\n  deriv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"deriv c (Zero) = Zero\"\n| \"deriv c (One) = Zero\"\n| \"deriv c (Atom c') = (if c = c' then One else Zero)\"\n| \"deriv c (Plus r1 r2) = Plus (deriv c r1) (deriv c r2)\"\n| \"deriv c (Times r1 r2) = \n    (if nullable r1 then Plus (Times (deriv c r1) r2) (deriv c r2) else Times (deriv c r1) r2)\"\n| \"deriv c (Star r) = Times (deriv c r) (Star r)\"\n| \"deriv c (NTimes r n) = (if n = 0 then Zero else Times (deriv c r) (NTimes r (n - 1)))\"\n| \"deriv c (Upto r n) = (if n = 0 then Zero else Times (deriv c r) (Upto r (n - 1)))\"\n| \"deriv c (From r n) = (if n = 0 then Times (deriv c r) (Star r) else Times (deriv c r) (From r (n - 1)))\"\n| \"deriv c (Rec l r) = deriv c r\"\n| \"deriv c (Charset cs) = (if c \\<in> cs then One else Zero)\"\n\nfun \n  derivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"derivs [] r = r\"\n| \"derivs (c # s) r = derivs s (deriv c r)\"\n\n\nlemma deriv_pow [simp]:\n  shows \"Deriv c (A ^^ n) = (if n = 0 then {} else (Deriv c A) @@ (A ^^ (n - 1)))\"\n  apply(induct n arbitrary: A)\n  apply(auto)\n  by (metis Suc_pred concI_if_Nil2 conc_assoc conc_pow_comm lang_pow.simps(2))\n\nlemma lang_deriv: \"lang (deriv c r) = Deriv c (lang r)\"\n  apply (induct r rule: lang.induct) \n  apply(auto simp add: nullable_iff conc_UNION_distrib)\n  apply (metis IntI Suc_pred atMost_iff diff_Suc_1 mem_Collect_eq not_less_eq_eq zero_less_Suc)\n  apply(auto)\n  apply(simp add: conc_def)\n  apply(metis diff_Suc_Suc minus_nat.diff_0 star_pow zero_less_Suc)\n     apply(metis IntI Suc_le_mono Suc_pred atLeast_iff diff_Suc_1 mem_Collect_eq zero_less_Suc)\n  apply(auto simp add: Deriv_def)\n  done    \n  \n\nlemma lang_derivs: \"lang (derivs s r) = Derivs s (lang r)\"\nby (induct s arbitrary: r) (simp_all add: lang_deriv)\n\ntext \\<open>A regular expression matcher:\\<close>\n\ndefinition matcher :: \"'a rexp \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"matcher r s = nullable (derivs s r)\"\n\nlemma matcher_correctness: \"matcher r s \\<longleftrightarrow> s \\<in> lang r\"\nby (induct s arbitrary: r)\n   (simp_all add: nullable_iff lang_deriv matcher_def Deriv_def)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Posix-Lexing/Extensions/Derivatives3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.795233509398759}}
{"text": "(*  Title:      HOL/Cardinals/Ordinal_Arithmetic.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Copyright   2014\n\nOrdinal arithmetic.\n*)\n\nsection \\<open>Ordinal Arithmetic\\<close>\n\ntheory Ordinal_Arithmetic\nimports Wellorder_Constructions\nbegin\n\ndefinition osum :: \"'a rel \\<Rightarrow> 'b rel \\<Rightarrow> ('a + 'b) rel\"  (infixr \"+o\" 70)\nwhere\n  \"r +o r' = map_prod Inl Inl ` r \\<union> map_prod Inr Inr ` r' \\<union>\n     {(Inl a, Inr a') | a a' . a \\<in> Field r \\<and> a' \\<in> Field r'}\"\n\nlemma Field_osum: \"Field(r +o r') = Inl ` Field r \\<union> Inr ` Field r'\"\n  unfolding osum_def Field_def by auto\n\nlemma osum_Refl:\"\\<lbrakk>Refl r; Refl r'\\<rbrakk> \\<Longrightarrow> Refl (r +o r')\"\n  (*Need first unfold Field_osum, only then osum_def*)\n  unfolding refl_on_def Field_osum unfolding osum_def by blast\n\nlemma osum_trans:\nassumes TRANS: \"trans r\" and TRANS': \"trans r'\"\nshows \"trans (r +o r')\"\nproof(unfold trans_def, safe)\n  fix x y z assume *: \"(x, y) \\<in> r +o r'\" \"(y, z) \\<in> r +o r'\"\n  thus \"(x, z) \\<in> r +o r'\"\n  proof (cases x y z rule: sum.exhaust[case_product sum.exhaust sum.exhaust])\n    case (Inl_Inl_Inl a b c)\n    with * have \"(a,b) \\<in> r\" \"(b,c) \\<in> r\" unfolding osum_def by auto\n    with TRANS have \"(a,c) \\<in> r\" unfolding trans_def by blast\n    with Inl_Inl_Inl show ?thesis unfolding osum_def by auto\n  next\n    case (Inl_Inl_Inr a b c)\n    with * have \"a \\<in> Field r\" \"c \\<in> Field r'\" unfolding osum_def Field_def by auto\n    with Inl_Inl_Inr show ?thesis unfolding osum_def by auto\n  next\n    case (Inl_Inr_Inr a b c)\n    with * have \"a \\<in> Field r\" \"c \\<in> Field r'\" unfolding osum_def Field_def by auto\n    with Inl_Inr_Inr show ?thesis unfolding osum_def by auto\n  next\n    case (Inr_Inr_Inr a b c)\n    with * have \"(a,b) \\<in> r'\" \"(b,c) \\<in> r'\" unfolding osum_def by auto\n    with TRANS' have \"(a,c) \\<in> r'\" unfolding trans_def by blast\n    with Inr_Inr_Inr show ?thesis unfolding osum_def by auto\n  qed (auto simp: osum_def)\nqed\n\nlemma osum_Preorder: \"\\<lbrakk>Preorder r; Preorder r'\\<rbrakk> \\<Longrightarrow> Preorder (r +o r')\"\n  unfolding preorder_on_def using osum_Refl osum_trans by blast\n\nlemma osum_antisym: \"\\<lbrakk>antisym r; antisym r'\\<rbrakk> \\<Longrightarrow> antisym (r +o r')\"\n  unfolding antisym_def osum_def by auto\n\nlemma osum_Partial_order: \"\\<lbrakk>Partial_order r; Partial_order r'\\<rbrakk> \\<Longrightarrow> Partial_order (r +o r')\"\n  unfolding partial_order_on_def using osum_Preorder osum_antisym by blast\n\nlemma osum_Total: \"\\<lbrakk>Total r; Total r'\\<rbrakk> \\<Longrightarrow> Total (r +o r')\"\n  unfolding total_on_def Field_osum unfolding osum_def by blast\n\nlemma osum_Linear_order: \"\\<lbrakk>Linear_order r; Linear_order r'\\<rbrakk> \\<Longrightarrow> Linear_order (r +o r')\"\n  unfolding linear_order_on_def using osum_Partial_order osum_Total by blast\n\nlemma osum_wf:\nassumes WF: \"wf r\" and WF': \"wf r'\"\nshows \"wf (r +o r')\"\nunfolding wf_eq_minimal2 unfolding Field_osum\nproof(intro allI impI, elim conjE)\n  fix A assume *: \"A \\<subseteq> Inl ` Field r \\<union> Inr ` Field r'\" and **: \"A \\<noteq> {}\"\n  obtain B where B_def: \"B = A Int Inl ` Field r\" by blast\n  show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a', a) \\<notin> r +o r'\"\n  proof(cases \"B = {}\")\n    case False\n    hence \"B \\<noteq> {}\" \"B \\<le> Inl ` Field r\" using B_def by auto\n    hence \"Inl -` B \\<noteq> {}\" \"Inl -` B \\<le> Field r\" unfolding vimage_def by auto\n    then obtain a where 1: \"a \\<in> Inl -` B\" and \"\\<forall>a1 \\<in> Inl -` B. (a1, a) \\<notin> r\"\n      using WF unfolding wf_eq_minimal2 by metis\n    hence \"\\<forall>a1 \\<in> A. (a1, Inl a) \\<notin> r +o r'\"\n      unfolding osum_def using B_def ** by (auto simp: vimage_def Field_def)\n    thus ?thesis using 1 unfolding B_def by auto\n  next\n    case True\n    hence 1: \"A \\<le> Inr ` Field r'\" using * B_def by auto\n    with ** have \"Inr -`A \\<noteq> {}\" \"Inr -` A \\<le> Field r'\" unfolding vimage_def by auto\n    with ** obtain a' where 2: \"a' \\<in> Inr -` A\" and \"\\<forall>a1' \\<in> Inr -` A. (a1',a') \\<notin> r'\"\n      using WF' unfolding wf_eq_minimal2 by metis\n    hence \"\\<forall>a1' \\<in> A. (a1', Inr a') \\<notin> r +o r'\"\n      unfolding osum_def using ** 1 by (auto simp: vimage_def Field_def)\n    thus ?thesis using 2 by blast\n  qed\nqed\n\nlemma osum_minus_Id:\n  assumes r: \"Total r\" \"\\<not> (r \\<le> Id)\" and r': \"Total r'\" \"\\<not> (r' \\<le> Id)\"\n  shows \"(r +o r') - Id \\<le> (r - Id) +o (r' - Id)\"\n  unfolding osum_def Total_Id_Field[OF r] Total_Id_Field[OF r'] by auto\n\nlemma osum_minus_Id1:\n  \"r \\<le> Id \\<Longrightarrow> (r +o r') - Id \\<le> (Inl ` Field r \\<times> Inr ` Field r') \\<union> (map_prod Inr Inr ` (r' - Id))\"\n  unfolding osum_def by auto\n\nlemma osum_minus_Id2:\n  \"r' \\<le> Id \\<Longrightarrow> (r +o r') - Id \\<le> (map_prod Inl Inl ` (r - Id)) \\<union> (Inl ` Field r \\<times> Inr ` Field r')\"\n  unfolding osum_def by auto\n\nlemma osum_wf_Id:\n  assumes TOT: \"Total r\" and TOT': \"Total r'\" and WF: \"wf(r - Id)\" and WF': \"wf(r' - Id)\"\n  shows \"wf ((r +o r') - Id)\"\nproof(cases \"r \\<le> Id \\<or> r' \\<le> Id\")\n  case False\n  thus ?thesis\n  using osum_minus_Id[of r r'] assms osum_wf[of \"r - Id\" \"r' - Id\"]\n    wf_subset[of \"(r - Id) +o (r' - Id)\" \"(r +o r') - Id\"] by auto\nnext\n  have 1: \"wf (Inl ` Field r \\<times> Inr ` Field r')\" by (rule wf_Int_Times) auto\n  case True\n  thus ?thesis\n  proof (elim disjE)\n    assume \"r \\<subseteq> Id\"\n    thus \"wf ((r +o r') - Id)\"\n      by (rule wf_subset[rotated, OF osum_minus_Id1 wf_Un[OF 1 wf_map_prod_image[OF WF']]]) auto\n  next\n    assume \"r' \\<subseteq> Id\"\n    thus \"wf ((r +o r') - Id)\"\n      by (rule wf_subset[rotated, OF osum_minus_Id2 wf_Un[OF wf_map_prod_image[OF WF] 1]]) auto\n  qed\nqed\n\nlemma osum_Well_order:\nassumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\nshows \"Well_order (r +o r')\"\nproof-\n  have \"Total r \\<and> Total r'\" using WELL WELL' by (auto simp add: order_on_defs)\n  thus ?thesis using assms unfolding well_order_on_def\n    using osum_Linear_order osum_wf_Id by blast\nqed\n\nlemma osum_embedL:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\n  shows \"embed r (r +o r') Inl\"\nproof -\n  have 1: \"Well_order (r +o r')\" using assms by (auto simp add: osum_Well_order)\n  moreover\n  have \"compat r (r +o r') Inl\" unfolding compat_def osum_def by auto\n  moreover\n  have \"ofilter (r +o r') (Inl ` Field r)\"\n    unfolding wo_rel.ofilter_def[unfolded wo_rel_def, OF 1] Field_osum under_def\n    unfolding osum_def Field_def by auto\n  ultimately show ?thesis using assms by (auto simp add: embed_iff_compat_inj_on_ofilter)\nqed\n\ncorollary osum_ordLeqL:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\n  shows \"r \\<le>o r +o r'\"\n  using assms osum_embedL osum_Well_order unfolding ordLeq_def by blast\n\nlemma dir_image_alt: \"dir_image r f = map_prod f f ` r\"\n  unfolding dir_image_def map_prod_def by auto\n\nlemma map_prod_ordIso: \"\\<lbrakk>Well_order r; inj_on f (Field r)\\<rbrakk> \\<Longrightarrow> map_prod f f ` r =o r\"\n  unfolding dir_image_alt[symmetric] by (rule ordIso_symmetric[OF dir_image_ordIso])\n\ndefinition oprod :: \"'a rel \\<Rightarrow> 'b rel \\<Rightarrow> ('a \\<times> 'b) rel\"  (infixr \"*o\" 80)\nwhere \"r *o r' = {((x1, y1), (x2, y2)).\n  (((y1, y2) \\<in> r' - Id \\<and> x1 \\<in> Field r \\<and> x2 \\<in> Field r) \\<or>\n   ((y1, y2) \\<in> Restr Id (Field r') \\<and> (x1, x2) \\<in> r))}\"\n\nlemma Field_oprod: \"Field (r *o r') = Field r \\<times> Field r'\"\n  unfolding oprod_def Field_def by auto blast+\n\nlemma oprod_Refl:\"\\<lbrakk>Refl r; Refl r'\\<rbrakk> \\<Longrightarrow> Refl (r *o r')\"\n  unfolding refl_on_def Field_oprod unfolding oprod_def by auto\n\nlemma oprod_trans:\n  assumes \"trans r\" \"trans r'\" \"antisym r\" \"antisym r'\"\n  shows \"trans (r *o r')\"\nproof(unfold trans_def, safe)\n  fix x y z assume *: \"(x, y) \\<in> r *o r'\" \"(y, z) \\<in> r *o r'\"\n  thus \"(x, z) \\<in> r *o r'\"\n  unfolding oprod_def\n  apply safe\n  apply (metis assms(2) transE)\n  apply (metis assms(2) transE)\n  apply (metis assms(2) transE)\n  apply (metis assms(4) antisymD)\n  apply (metis assms(4) antisymD)\n  apply (metis assms(2) transE)\n  apply (metis assms(4) antisymD)\n  apply (metis Field_def Range_iff Un_iff)\n  apply (metis Field_def Range_iff Un_iff)\n  apply (metis Field_def Range_iff Un_iff)\n  apply (metis Field_def Domain_iff Un_iff)\n  apply (metis Field_def Domain_iff Un_iff)\n  apply (metis Field_def Domain_iff Un_iff)\n  apply (metis assms(1) transE)\n  apply (metis assms(1) transE)\n  apply (metis assms(1) transE)\n  apply (metis assms(1) transE)\n  done\nqed\n\nlemma oprod_Preorder: \"\\<lbrakk>Preorder r; Preorder r'; antisym r; antisym r'\\<rbrakk> \\<Longrightarrow> Preorder (r *o r')\"\n  unfolding preorder_on_def using oprod_Refl oprod_trans by blast\n\nlemma oprod_antisym: \"\\<lbrakk>antisym r; antisym r'\\<rbrakk> \\<Longrightarrow> antisym (r *o r')\"\n  unfolding antisym_def oprod_def by auto\n\nlemma oprod_Partial_order: \"\\<lbrakk>Partial_order r; Partial_order r'\\<rbrakk> \\<Longrightarrow> Partial_order (r *o r')\"\n  unfolding partial_order_on_def using oprod_Preorder oprod_antisym by blast\n\nlemma oprod_Total: \"\\<lbrakk>Total r; Total r'\\<rbrakk> \\<Longrightarrow> Total (r *o r')\"\n  unfolding total_on_def Field_oprod unfolding oprod_def by auto\n\nlemma oprod_Linear_order: \"\\<lbrakk>Linear_order r; Linear_order r'\\<rbrakk> \\<Longrightarrow> Linear_order (r *o r')\"\n  unfolding linear_order_on_def using oprod_Partial_order oprod_Total by blast\n\nlemma oprod_wf:\nassumes WF: \"wf r\" and WF': \"wf r'\"\nshows \"wf (r *o r')\"\nunfolding wf_eq_minimal2 unfolding Field_oprod\nproof(intro allI impI, elim conjE)\n  fix A assume *: \"A \\<subseteq> Field r \\<times> Field r'\" and **: \"A \\<noteq> {}\"\n  then obtain y where y: \"y \\<in> snd ` A\" \"\\<forall>y'\\<in>snd ` A. (y', y) \\<notin> r'\"\n    using spec[OF WF'[unfolded wf_eq_minimal2], of \"snd ` A\"] by auto\n  let ?A = \"fst ` A \\<inter> {x. (x, y) \\<in> A}\"\n  from * y have \"?A \\<noteq> {}\" \"?A \\<subseteq> Field r\" by auto\n  then obtain x where x: \"x \\<in> ?A\" and \"\\<forall>x'\\<in> ?A. (x', x) \\<notin> r\"\n    using spec[OF WF[unfolded wf_eq_minimal2], of \"?A\"] by auto\n  with y have \"\\<forall>a'\\<in>A. (a', (x, y)) \\<notin> r *o r'\"\n    unfolding oprod_def mem_Collect_eq split_beta fst_conv snd_conv Id_def by auto\n  moreover from x have \"(x, y) \\<in> A\" by auto\n  ultimately show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a', a) \\<notin> r *o r'\" by blast\nqed\n\nlemma oprod_minus_Id:\n  assumes r: \"Total r\" \"\\<not> (r \\<le> Id)\" and r': \"Total r'\" \"\\<not> (r' \\<le> Id)\"\n  shows \"(r *o r') - Id \\<le> (r - Id) *o (r' - Id)\"\n  unfolding oprod_def Total_Id_Field[OF r] Total_Id_Field[OF r'] by auto\n\nlemma oprod_minus_Id1:\n  \"r \\<le> Id \\<Longrightarrow> r *o r' - Id \\<le> {((x,y1), (x,y2)). x \\<in> Field r \\<and> (y1, y2) \\<in> (r' - Id)}\"\n  unfolding oprod_def by auto\n\nlemma wf_extend_oprod1:\n  assumes \"wf r\"\n  shows \"wf {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\"\nproof (unfold wf_eq_minimal2, intro allI impI, elim conjE)\n  fix B\n  assume *: \"B \\<subseteq> Field {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\" and \"B \\<noteq> {}\"\n  from image_mono[OF *, of snd] have \"snd ` B \\<subseteq> Field r\" unfolding Field_def by force\n  with \\<open>B \\<noteq> {}\\<close> obtain x where x: \"x \\<in> snd ` B\" \"\\<forall>x'\\<in>snd ` B. (x', x) \\<notin> r\"\n    using spec[OF assms[unfolded wf_eq_minimal2], of \"snd ` B\"] by auto\n  then obtain a where \"(a, x) \\<in> B\" by auto\n  moreover\n  from * x have \"\\<forall>a'\\<in>B. (a', (a, x)) \\<notin> {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\" by auto\n  ultimately show \"\\<exists>ax\\<in>B. \\<forall>a'\\<in>B. (a', ax) \\<notin> {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\" by blast\nqed\n\nlemma oprod_minus_Id2:\n  \"r' \\<le> Id \\<Longrightarrow> r *o r' - Id \\<le> {((x1,y), (x2,y)). (x1, x2) \\<in> (r - Id) \\<and> y \\<in> Field r'}\"\n  unfolding oprod_def by auto\n\nlemma wf_extend_oprod2:\n  assumes \"wf r\"\n  shows \"wf {((x1,y), (x2,y)) . (x1, x2) \\<in> r \\<and> y \\<in> A}\"\nproof (unfold wf_eq_minimal2, intro allI impI, elim conjE)\n  fix B\n  assume *: \"B \\<subseteq> Field {((x1, y), (x2, y)). (x1, x2) \\<in> r \\<and> y \\<in> A}\" and \"B \\<noteq> {}\"\n  from image_mono[OF *, of fst] have \"fst ` B \\<subseteq> Field r\" unfolding Field_def by force\n  with \\<open>B \\<noteq> {}\\<close> obtain x where x: \"x \\<in> fst ` B\" \"\\<forall>x'\\<in>fst ` B. (x', x) \\<notin> r\"\n    using spec[OF assms[unfolded wf_eq_minimal2], of \"fst ` B\"] by auto\n  then obtain a where \"(x, a) \\<in> B\" by auto\n  moreover\n  from * x have \"\\<forall>a'\\<in>B. (a', (x, a)) \\<notin> {((x1, y), x2, y). (x1, x2) \\<in> r \\<and> y \\<in> A}\" by auto\n  ultimately show \"\\<exists>xa\\<in>B. \\<forall>a'\\<in>B. (a', xa) \\<notin> {((x1, y), x2, y). (x1, x2) \\<in> r \\<and> y \\<in> A}\" by blast\nqed\n\nlemma oprod_wf_Id:\n  assumes TOT: \"Total r\" and TOT': \"Total r'\" and WF: \"wf(r - Id)\" and WF': \"wf(r' - Id)\"\n  shows \"wf ((r *o r') - Id)\"\nproof(cases \"r \\<le> Id \\<or> r' \\<le> Id\")\n  case False\n  thus ?thesis\n  using oprod_minus_Id[of r r'] assms oprod_wf[of \"r - Id\" \"r' - Id\"]\n    wf_subset[of \"(r - Id) *o (r' - Id)\" \"(r *o r') - Id\"] by auto\nnext\n  case True\n  thus ?thesis using wf_subset[OF wf_extend_oprod1[OF WF'] oprod_minus_Id1]\n                     wf_subset[OF wf_extend_oprod2[OF WF] oprod_minus_Id2] by auto\nqed\n\nlemma oprod_Well_order:\nassumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\nshows \"Well_order (r *o r')\"\nproof-\n  have \"Total r \\<and> Total r'\" using WELL WELL' by (auto simp add: order_on_defs)\n  thus ?thesis using assms unfolding well_order_on_def\n    using oprod_Linear_order oprod_wf_Id by blast\nqed\n\nlemma oprod_embed:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\" and \"r' \\<noteq> {}\"\n  shows \"embed r (r *o r') (\\<lambda>x. (x, minim r' (Field r')))\" (is \"embed _ _ ?f\")\nproof -\n  from assms(3) have r': \"Field r' \\<noteq> {}\" unfolding Field_def by auto\n  have minim[simp]: \"minim r' (Field r') \\<in> Field r'\"\n    using wo_rel.minim_inField[unfolded wo_rel_def, OF WELL' _ r'] by auto\n  { fix b\n    assume b: \"(b, minim r' (Field r')) \\<in> r'\"\n    hence \"b \\<in> Field r'\" unfolding Field_def by auto\n    hence \"(minim r' (Field r'), b) \\<in> r'\"\n      using wo_rel.minim_least[unfolded wo_rel_def, OF WELL' subset_refl] r' by auto\n    with b have \"b = minim r' (Field r')\"\n      by (metis WELL' antisym_def linear_order_on_def partial_order_on_def well_order_on_def)\n  } note * = this\n  have 1: \"Well_order (r *o r')\" using assms by (auto simp add: oprod_Well_order)\n  moreover\n  from r' have \"compat r (r *o r') ?f\"  unfolding compat_def oprod_def by auto\n  moreover\n  from * have \"ofilter (r *o r') (?f ` Field r)\"\n    unfolding wo_rel.ofilter_def[unfolded wo_rel_def, OF 1] Field_oprod under_def\n    unfolding oprod_def by auto (auto simp: image_iff Field_def)\n  moreover have \"inj_on ?f (Field r)\" unfolding inj_on_def by auto\n  ultimately show ?thesis using assms by (auto simp add: embed_iff_compat_inj_on_ofilter)\nqed\n\ncorollary oprod_ordLeq: \"\\<lbrakk>Well_order r; Well_order r'; r' \\<noteq> {}\\<rbrakk> \\<Longrightarrow> r \\<le>o r *o r'\"\n  using oprod_embed oprod_Well_order unfolding ordLeq_def by blast\n\ndefinition \"support z A f = {x \\<in> A. f x \\<noteq> z}\"\n\nlemma support_Un[simp]: \"support z (A \\<union> B) f = support z A f \\<union> support z B f\"\n  unfolding support_def by auto\n\nlemma support_upd[simp]: \"support z A (f(x := z)) = support z A f - {x}\"\n  unfolding support_def by auto\n\nlemma support_upd_subset[simp]: \"support z A (f(x := y)) \\<subseteq> support z A f \\<union> {x}\"\n  unfolding support_def by auto\n\nlemma fun_unequal_in_support:\n  assumes \"f \\<noteq> g\" \"f \\<in> Func A B\" \"g \\<in> Func A C\"\n  shows \"(support z A f \\<union> support z A g) \\<inter> {a. f a \\<noteq> g a} \\<noteq> {}\" (is \"?L \\<inter> ?R \\<noteq> {}\")\nproof -\n  from assms(1) obtain x where x: \"f x \\<noteq> g x\" by blast\n  hence \"x \\<in> ?R\" by simp\n  moreover from assms(2-3) x have \"x \\<in> A\" unfolding Func_def by fastforce\n  with x have \"x \\<in> ?L\" unfolding support_def by auto\n  ultimately show ?thesis by auto\nqed\n\ndefinition fin_support where\n  \"fin_support z A = {f. finite (support z A f)}\"\n\nlemma finite_support: \"f \\<in> fin_support z A \\<Longrightarrow> finite (support z A f)\"\n  unfolding support_def fin_support_def by auto\n\nlemma fin_support_Field_osum:\n  \"f \\<in> fin_support z (Inl ` A \\<union> Inr ` B) \\<longleftrightarrow>\n  (f o Inl) \\<in> fin_support z A \\<and> (f o Inr) \\<in> fin_support z B\" (is \"?L \\<longleftrightarrow> ?R1 \\<and> ?R2\")\nproof safe\n  assume ?L\n  from \\<open>?L\\<close> show ?R1 unfolding fin_support_def support_def\n    by (fastforce simp: image_iff elim: finite_surj[of _ _ \"case_sum id undefined\"])\n  from \\<open>?L\\<close> show ?R2 unfolding fin_support_def support_def\n    by (fastforce simp: image_iff elim: finite_surj[of _ _ \"case_sum undefined id\"])\nnext\n  assume ?R1 ?R2\n  thus ?L unfolding fin_support_def support_Un\n    by (auto simp: support_def elim: finite_surj[of _ _ Inl] finite_surj[of _ _ Inr])\nqed\n\nlemma Func_upd: \"\\<lbrakk>f \\<in> Func A B; x \\<in> A; y \\<in> B\\<rbrakk> \\<Longrightarrow> f(x := y) \\<in> Func A B\"\n  unfolding Func_def by auto\n\ncontext wo_rel\nbegin\n\ndefinition isMaxim :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere \"isMaxim A b \\<equiv> b \\<in> A \\<and> (\\<forall>a \\<in> A. (a,b) \\<in> r)\"\n\ndefinition maxim :: \"'a set \\<Rightarrow> 'a\"\nwhere \"maxim A \\<equiv> THE b. isMaxim A b\"\n\nlemma isMaxim_unique[intro]: \"\\<lbrakk>isMaxim A x; isMaxim A y\\<rbrakk> \\<Longrightarrow> x = y\"\n  unfolding isMaxim_def using antisymD[OF ANTISYM, of x y] by auto\n\nlemma maxim_isMaxim: \"\\<lbrakk>finite A; A \\<noteq> {}; A \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> isMaxim A (maxim A)\"\nunfolding maxim_def\nproof (rule theI', rule ex_ex1I[OF _ isMaxim_unique, rotated], assumption+,\n  induct A rule: finite_induct)\n  case (insert x A)\n  thus ?case\n  proof (cases \"A = {}\")\n    case True\n    moreover have \"isMaxim {x} x\" unfolding isMaxim_def using refl_onD[OF REFL] insert(5) by auto\n    ultimately show ?thesis by blast\n  next\n    case False\n    with insert(3,5) obtain y where \"isMaxim A y\" by blast\n    with insert(2,5) have \"if (y, x) \\<in> r then isMaxim (insert x A) x else isMaxim (insert x A) y\"\n      unfolding isMaxim_def subset_eq by (metis insert_iff max2_def max2_equals1 max2_iff)\n    thus ?thesis by metis\n  qed\nqed simp\n\nlemma maxim_in: \"\\<lbrakk>finite A; A \\<noteq> {}; A \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> maxim A \\<in> A\"\n  using maxim_isMaxim unfolding isMaxim_def by auto\n\nlemma maxim_greatest: \"\\<lbrakk>finite A; x \\<in> A; A \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> (x, maxim A) \\<in> r\"\n  using maxim_isMaxim unfolding isMaxim_def by auto\n\nlemma isMaxim_zero: \"isMaxim A zero \\<Longrightarrow> A = {zero}\"\n  unfolding isMaxim_def by auto\n\nlemma maxim_insert:\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> Field r\" \"x \\<in> Field r\"\n  shows \"maxim (insert x A) = max2 x (maxim A)\"\nproof -\n  from assms have *: \"isMaxim (insert x A) (maxim (insert x A))\" \"isMaxim A (maxim A)\"\n    using maxim_isMaxim by auto\n  show ?thesis\n  proof (cases \"(x, maxim A) \\<in> r\")\n    case True\n    with *(2) have \"isMaxim (insert x A) (maxim A)\" unfolding isMaxim_def\n      using transD[OF TRANS, of _ x \"maxim A\"] by blast\n    with *(1) True show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  next\n    case False\n    hence \"(maxim A, x) \\<in> r\" by (metis *(2) assms(3,4) in_mono in_notinI isMaxim_def)\n    with *(2) assms(4) have \"isMaxim (insert x A) x\" unfolding isMaxim_def\n      using transD[OF TRANS, of _ \"maxim A\" x] refl_onD[OF REFL, of x] by blast\n    with *(1) False show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  qed\nqed\n\nlemma maxim_Un:\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> Field r\" \"finite B\" \"B \\<noteq> {}\" \"B \\<subseteq> Field r\"\n  shows   \"maxim (A \\<union> B) = max2 (maxim A) (maxim B)\"\nproof -\n  from assms have *: \"isMaxim (A \\<union> B) (maxim (A \\<union> B))\" \"isMaxim A (maxim A)\" \"isMaxim B (maxim B)\"\n    using maxim_isMaxim by auto\n  show ?thesis\n  proof (cases \"(maxim A, maxim B) \\<in> r\")\n    case True\n    with *(2,3) have \"isMaxim (A \\<union> B) (maxim B)\" unfolding isMaxim_def\n      using transD[OF TRANS, of _ \"maxim A\" \"maxim B\"] by blast\n    with *(1) True show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  next\n    case False\n    hence \"(maxim B, maxim A) \\<in> r\" by (metis *(2,3) assms(3,6) in_mono in_notinI isMaxim_def)\n    with *(2,3) have \"isMaxim (A \\<union> B) (maxim A)\" unfolding isMaxim_def\n      using transD[OF TRANS, of _ \"maxim B\" \"maxim A\"] by blast\n    with *(1) False show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  qed\nqed\n\nlemma maxim_insert_zero:\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> Field r\"\n  shows \"maxim (insert zero A) = maxim A\"\nusing assms zero_in_Field maxim_in[OF assms] by (subst maxim_insert[unfolded max2_def]) auto\n\nlemma maxim_equality: \"isMaxim A x \\<Longrightarrow> maxim A = x\"\n  unfolding maxim_def by (rule the_equality) auto\n\nlemma maxim_singleton:\n  \"x \\<in> Field r \\<Longrightarrow> maxim {x} = x\"\n  using refl_onD[OF REFL] by (intro maxim_equality) (simp add: isMaxim_def)\n\nlemma maxim_Int: \"\\<lbrakk>finite A; A \\<noteq> {}; A \\<subseteq> Field r; maxim A \\<in> B\\<rbrakk> \\<Longrightarrow> maxim (A \\<inter> B) = maxim A\"\n  by (rule maxim_equality) (auto simp: isMaxim_def intro: maxim_in maxim_greatest)\n\nlemma maxim_mono: \"\\<lbrakk>X \\<subseteq> Y; finite Y; X \\<noteq> {}; Y \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> (maxim X, maxim Y) \\<in> r\"\n  using maxim_in[OF finite_subset, of X Y] by (auto intro: maxim_greatest)\n\ndefinition \"max_fun_diff f g \\<equiv> maxim ({a \\<in> Field r. f a \\<noteq> g a})\"\n\nlemma max_fun_diff_commute: \"max_fun_diff f g = max_fun_diff g f\"\n  unfolding max_fun_diff_def by metis\n\nlemma zero_under: \"x \\<in> Field r \\<Longrightarrow> zero \\<in> under x\"\n  unfolding under_def by (auto intro: zero_smallest)\n\nend\n\ndefinition \"FinFunc r s = Func (Field s) (Field r) \\<inter> fin_support (zero r) (Field s)\"\n\nlemma FinFuncD: \"\\<lbrakk>f \\<in> FinFunc r s; x \\<in> Field s\\<rbrakk> \\<Longrightarrow> f x \\<in> Field r\"\n  unfolding FinFunc_def Func_def by (fastforce split: option.splits)\n\nlocale wo_rel2 =\n  fixes r s\n  assumes rWELL: \"Well_order r\"\n  and     sWELL: \"Well_order s\"\nbegin\n\ninterpretation r: wo_rel r by unfold_locales (rule rWELL)\ninterpretation s: wo_rel s by unfold_locales (rule sWELL)\n\nabbreviation \"SUPP \\<equiv> support r.zero (Field s)\"\nabbreviation \"FINFUNC \\<equiv> FinFunc r s\"\nlemmas FINFUNCD = FinFuncD[of _ r s]\n\nlemma fun_diff_alt: \"{a \\<in> Field s. f a \\<noteq> g a} = (SUPP f \\<union> SUPP g) \\<inter> {a. f a \\<noteq> g a}\"\n  by (auto simp: support_def)\n\nlemma max_fun_diff_alt:\n  \"s.max_fun_diff f g = s.maxim ((SUPP f \\<union> SUPP g) \\<inter> {a. f a \\<noteq> g a})\"\n   unfolding s.max_fun_diff_def fun_diff_alt ..\n\nlemma isMaxim_max_fun_diff: \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC\\<rbrakk> \\<Longrightarrow>\n  s.isMaxim {a \\<in> Field s. f a \\<noteq> g a} (s.max_fun_diff f g)\"\n  using fun_unequal_in_support[of f g] unfolding max_fun_diff_alt fun_diff_alt fun_eq_iff\n  by (intro s.maxim_isMaxim) (auto simp: FinFunc_def fin_support_def support_def)\n\nlemma max_fun_diff_in: \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC\\<rbrakk> \\<Longrightarrow>\n  s.max_fun_diff f g \\<in> {a \\<in> Field s. f a \\<noteq> g a}\"\n  using isMaxim_max_fun_diff unfolding s.isMaxim_def by blast\n\nlemma max_fun_diff_max: \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC; x \\<in> {a \\<in> Field s. f a \\<noteq> g a}\\<rbrakk> \\<Longrightarrow>\n  (x, s.max_fun_diff f g) \\<in> s\"\n  using isMaxim_max_fun_diff unfolding s.isMaxim_def by blast\n\nlemma max_fun_diff:\n  \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC\\<rbrakk> \\<Longrightarrow>\n  (\\<exists>a b. a \\<noteq> b \\<and> a \\<in> Field r \\<and> b \\<in> Field r \\<and>\n     f (s.max_fun_diff f g) = a \\<and> g (s.max_fun_diff f g) = b)\"\n  using isMaxim_max_fun_diff[of f g] unfolding s.isMaxim_def FinFunc_def Func_def by auto\n\nlemma max_fun_diff_le_eq:\n  \"\\<lbrakk>(s.max_fun_diff f g, x) \\<in> s; f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC; x \\<noteq> s.max_fun_diff f g\\<rbrakk> \\<Longrightarrow>\n  f x = g x\"\n  using max_fun_diff_max[of f g x] antisymD[OF s.ANTISYM, of \"s.max_fun_diff f g\" x]\n  by (auto simp: Field_def)\n\nlemma max_fun_diff_max2:\n  assumes ineq: \"s.max_fun_diff f g = s.max_fun_diff g h \\<longrightarrow>\n    f (s.max_fun_diff f g) \\<noteq> h (s.max_fun_diff g h)\" and\n    fg: \"f \\<noteq> g\" and gh: \"g \\<noteq> h\" and fh: \"f \\<noteq> h\" and\n    f: \"f \\<in> FINFUNC\" and g: \"g \\<in> FINFUNC\" and h: \"h \\<in> FINFUNC\"\n  shows \"s.max_fun_diff f h = s.max2 (s.max_fun_diff f g) (s.max_fun_diff g h)\"\n    (is \"?fh = s.max2 ?fg ?gh\")\nproof (cases \"?fg = ?gh\")\n  case True\n  with ineq have \"f ?fg \\<noteq> h ?fg\" by simp\n  moreover\n  { fix x assume x: \"x \\<in> {a \\<in> Field s. f a \\<noteq> h a}\"\n    hence \"(x, ?fg) \\<in> s\"\n    proof (cases \"x = ?fg\")\n      case False show ?thesis\n      proof (rule ccontr)\n        assume \"(x, ?fg) \\<notin> s\"\n        with max_fun_diff_in[OF fg f g] x False have *: \"(?fg, x) \\<in> s\" by (blast intro: s.in_notinI)\n        hence \"f x = g x\" by (rule max_fun_diff_le_eq[OF _ fg f g False])\n        moreover have \"g x = h x\" using max_fun_diff_le_eq[OF _ gh g h] False True * by simp\n        ultimately show False using x by simp\n      qed\n    qed (simp add: refl_onD[OF s.REFL])\n  }\n  ultimately have \"s.isMaxim {a \\<in> Field s. f a \\<noteq> h a} ?fg\"\n    unfolding s.isMaxim_def using max_fun_diff_in[OF fg f g] by simp\n  hence \"?fh = ?fg\" using isMaxim_max_fun_diff[OF fh f h] by blast\n  thus ?thesis unfolding True s.max2_def by simp\nnext\n  case False note * = this\n  show ?thesis\n  proof (cases \"(?fg, ?gh) \\<in> s\")\n    case True\n    hence *: \"f ?gh = g ?gh\" by (rule max_fun_diff_le_eq[OF _ fg f g *[symmetric]])\n    hence \"s.isMaxim {a \\<in> Field s. f a \\<noteq> h a} ?gh\" using isMaxim_max_fun_diff[OF gh g h]\n      isMaxim_max_fun_diff[OF fg f g] transD[OF s.TRANS _ True]\n      unfolding s.isMaxim_def by auto\n    hence \"?fh = ?gh\" using isMaxim_max_fun_diff[OF fh f h] by blast\n    thus ?thesis using True unfolding s.max2_def by simp\n  next\n    case False\n    with max_fun_diff_in[OF fg f g] max_fun_diff_in[OF gh g h] have True: \"(?gh, ?fg) \\<in> s\"\n      by (blast intro: s.in_notinI)\n    hence *: \"g ?fg = h ?fg\" by (rule max_fun_diff_le_eq[OF _ gh g h *])\n    hence \"s.isMaxim {a \\<in> Field s. f a \\<noteq> h a} ?fg\" using isMaxim_max_fun_diff[OF gh g h]\n      isMaxim_max_fun_diff[OF fg f g] True transD[OF s.TRANS, of _ _ ?fg]\n      unfolding s.isMaxim_def by auto\n    hence \"?fh = ?fg\" using isMaxim_max_fun_diff[OF fh f h] by blast\n    thus ?thesis using False unfolding s.max2_def by simp\n  qed\nqed\n\ndefinition oexp where\n  \"oexp = {(f, g) . f \\<in> FINFUNC \\<and> g \\<in> FINFUNC \\<and>\n    ((let m = s.max_fun_diff f g in (f m, g m) \\<in> r) \\<or> f = g)}\"\n\nlemma Field_oexp: \"Field oexp = FINFUNC\"\n  unfolding oexp_def FinFunc_def by (auto simp: Let_def Field_def)\n\nlemma oexp_Refl: \"Refl oexp\"\n  unfolding refl_on_def Field_oexp unfolding oexp_def by (auto simp: Let_def)\n\nlemma oexp_trans: \"trans oexp\"\nproof (unfold trans_def, safe)\n  fix f g h :: \"'b \\<Rightarrow> 'a\"\n  let ?fg = \"s.max_fun_diff f g\"\n  and ?gh = \"s.max_fun_diff g h\"\n  and ?fh = \"s.max_fun_diff f h\"\n  assume oexp: \"(f, g) \\<in> oexp\" \"(g, h) \\<in> oexp\"\n  thus \"(f, h) \\<in> oexp\"\n  proof (cases \"f = g \\<or> g = h\")\n    case False\n    with oexp have \"f \\<in> FINFUNC\" \"g \\<in> FINFUNC\" \"h \\<in> FINFUNC\"\n      \"(f ?fg, g ?fg) \\<in> r\" \"(g ?gh, h ?gh) \\<in> r\" unfolding oexp_def Let_def by auto\n    note * = this False\n    show ?thesis\n    proof (cases \"f \\<noteq> h\")\n      case True\n      show ?thesis\n      proof (cases \"?fg = ?gh \\<longrightarrow> f ?fg \\<noteq> h ?gh\")\n        case True\n        show ?thesis using max_fun_diff_max2[of f g h, OF True] * \\<open>f \\<noteq> h\\<close> max_fun_diff_in\n          r.max2_iff[OF FINFUNCD FINFUNCD] r.max2_equals1[OF FINFUNCD FINFUNCD] max_fun_diff_le_eq\n          s.in_notinI[OF disjI1] unfolding oexp_def Let_def s.max2_def mem_Collect_eq by safe metis\n      next\n        case False with * show ?thesis unfolding oexp_def Let_def\n          using antisymD[OF r.ANTISYM, of \"g ?gh\" \"h ?gh\"] max_fun_diff_in[of g h] by auto\n      qed\n    qed (auto simp: oexp_def *(3))\n  qed auto\nqed\n\nlemma oexp_Preorder: \"Preorder oexp\"\n  unfolding preorder_on_def using oexp_Refl oexp_trans by blast\n\nlemma oexp_antisym: \"antisym oexp\"\nproof (unfold antisym_def, safe, rule ccontr)\n  fix f g assume \"(f, g) \\<in> oexp\" \"(g, f) \\<in> oexp\" \"g \\<noteq> f\"\n  thus False using refl_onD[OF r.REFL FINFUNCD] max_fun_diff_in unfolding oexp_def Let_def\n    by (auto dest!: antisymD[OF r.ANTISYM] simp: s.max_fun_diff_commute)\nqed\n\nlemma oexp_Partial_order: \"Partial_order oexp\"\n  unfolding partial_order_on_def using oexp_Preorder oexp_antisym by blast\n\nlemma oexp_Total: \"Total oexp\"\n  unfolding total_on_def Field_oexp unfolding oexp_def using FINFUNCD max_fun_diff_in\n  by (auto simp: Let_def s.max_fun_diff_commute intro!: r.in_notinI)\n\nlemma oexp_Linear_order: \"Linear_order oexp\"\n  unfolding linear_order_on_def using oexp_Partial_order oexp_Total by blast\n\ndefinition \"const = (\\<lambda>x. if x \\<in> Field s then r.zero else undefined)\"\n\nlemma const_in[simp]: \"x \\<in> Field s \\<Longrightarrow> const x = r.zero\"\n  unfolding const_def by auto\n\nlemma const_notin[simp]: \"x \\<notin> Field s \\<Longrightarrow> const x = undefined\"\n  unfolding const_def by auto\n\nlemma const_Int_Field[simp]: \"Field s \\<inter> - {x. const x = r.zero} = {}\"\n  by auto\n\nlemma const_FINFUNC[simp]: \"Field r \\<noteq> {} \\<Longrightarrow> const \\<in> FINFUNC\"\n  unfolding FinFunc_def Func_def fin_support_def support_def const_def Int_iff mem_Collect_eq\n  using r.zero_in_Field by (metis (lifting) Collect_empty_eq finite.emptyI)\n\nlemma const_least:\n  assumes \"Field r \\<noteq> {}\" \"f \\<in> FINFUNC\"\n  shows \"(const, f) \\<in> oexp\"\nproof (cases \"f = const\")\n  case True thus ?thesis using refl_onD[OF oexp_Refl] assms(2) unfolding Field_oexp by auto\nnext\n  case False\n  with assms show ?thesis using max_fun_diff_in[of f const]\n    unfolding oexp_def Let_def by (auto intro: r.zero_smallest FinFuncD simp: s.max_fun_diff_commute)\nqed\n\nlemma support_not_const:\n  assumes \"F \\<subseteq> FINFUNC\" and \"const \\<notin> F\"\n  shows \"\\<forall>f \\<in> F. finite (SUPP f) \\<and> SUPP f \\<noteq> {} \\<and> SUPP f \\<subseteq> Field s\"\nproof (intro ballI conjI)\n  fix f assume \"f \\<in> F\"\n  thus \"finite (SUPP f)\" \"SUPP f \\<subseteq> Field s\"\n    using assms(1) unfolding FinFunc_def fin_support_def support_def by auto\n  show \"SUPP f \\<noteq> {}\"\n  proof (rule ccontr, unfold not_not)\n    assume \"SUPP f = {}\"\n    moreover from \\<open>f \\<in> F\\<close> assms(1) have \"f \\<in> FINFUNC\" by blast\n    ultimately have \"f = const\"\n      by (auto simp: fun_eq_iff support_def FinFunc_def Func_def const_def)\n    with assms(2) \\<open>f \\<in> F\\<close> show False by blast\n  qed\nqed\n\nlemma maxim_isMaxim_support:\n  assumes f: \"F \\<subseteq> FINFUNC\" and \"const \\<notin> F\"\n  shows \"\\<forall>f \\<in> F. s.isMaxim (SUPP f) (s.maxim (SUPP f))\"\n  using support_not_const[OF assms] by (auto intro!: s.maxim_isMaxim)\n\nlemma oexp_empty2: \"Field s = {} \\<Longrightarrow> oexp = {(\\<lambda>x. undefined, \\<lambda>x. undefined)}\"\n  unfolding oexp_def FinFunc_def fin_support_def support_def by auto\n\nlemma oexp_empty: \"\\<lbrakk>Field r = {}; Field s \\<noteq> {}\\<rbrakk> \\<Longrightarrow> oexp = {}\"\n  unfolding oexp_def FinFunc_def Let_def by auto\n\nlemma fun_upd_FINFUNC: \"\\<lbrakk>f \\<in> FINFUNC; x \\<in> Field s; y \\<in> Field r\\<rbrakk> \\<Longrightarrow> f(x := y) \\<in> FINFUNC\"\n  unfolding FinFunc_def Func_def fin_support_def\n  by (auto intro: finite_subset[OF support_upd_subset])\n\nlemma fun_upd_same_oexp:\n  assumes \"(f, g) \\<in> oexp\" \"f x = g x\" \"x \\<in> Field s\" \"y \\<in> Field r\"\n  shows   \"(f(x := y), g(x := y)) \\<in> oexp\"\nproof -\n  from assms(1) fun_upd_FINFUNC[OF _ assms(3,4)] have fg: \"f(x := y) \\<in> FINFUNC\" \"g(x := y) \\<in> FINFUNC\"\n    unfolding oexp_def by auto\n  moreover from assms(2) have \"s.max_fun_diff (f(x := y)) (g(x := y)) = s.max_fun_diff f g\"\n    unfolding s.max_fun_diff_def by auto metis\n  ultimately show ?thesis using assms refl_onD[OF r.REFL] unfolding oexp_def Let_def by auto\nqed\n\nlemma fun_upd_smaller_oexp:\n  assumes \"f \\<in> FINFUNC\" \"x \\<in> Field s\" \"y \\<in> Field r\"  \"(y, f x) \\<in> r\"\n  shows   \"(f(x := y), f) \\<in> oexp\"\n  using assms fun_upd_FINFUNC[OF assms(1-3)] s.maxim_singleton[of \"x\"]\n  unfolding oexp_def FinFunc_def Let_def fin_support_def s.max_fun_diff_def by (auto simp: fun_eq_iff)\n\nlemma oexp_wf_Id: \"wf (oexp - Id)\"\nproof (cases \"Field r = {} \\<or> Field s = {}\")\n  case True thus ?thesis using oexp_empty oexp_empty2 by fastforce\nnext\n  case False\n  hence Fields: \"Field s \\<noteq> {}\" \"Field r \\<noteq> {}\" by simp_all\n  hence [simp]: \"r.zero \\<in> Field r\" by (intro r.zero_in_Field)\n  have const[simp]: \"\\<And>F. \\<lbrakk>const \\<in> F; F \\<subseteq> FINFUNC\\<rbrakk> \\<Longrightarrow> \\<exists>f0\\<in>F. \\<forall>f\\<in>F. (f0, f) \\<in> oexp\"\n    using const_least[OF Fields(2)] by auto\n  show ?thesis\n  unfolding Linear_order_wf_diff_Id[OF oexp_Linear_order] Field_oexp\n  proof (intro allI impI)\n    fix A assume A: \"A \\<subseteq> FINFUNC\" \"A \\<noteq> {}\"\n    { fix y F\n      have \"F \\<subseteq> FINFUNC \\<and> (\\<exists>f \\<in> F. y = s.maxim (SUPP f)) \\<longrightarrow>\n        (\\<exists>f0 \\<in> F. \\<forall>f \\<in> F. (f0, f) \\<in> oexp)\" (is \"?P F y\")\n      proof (induct y arbitrary: F rule: s.well_order_induct)\n        case (1 y)\n        show ?case\n        proof (intro impI, elim conjE bexE)\n          fix f assume F: \"F \\<subseteq> FINFUNC\" \"f \\<in> F\" \"y = s.maxim (SUPP f)\"\n          thus \"\\<exists>f0\\<in>F. \\<forall>f\\<in>F. (f0, f) \\<in> oexp\"\n          proof (cases \"const \\<in> F\")\n            case False\n            with F have maxF: \"\\<forall>f \\<in> F. s.isMaxim (SUPP f) (s.maxim (SUPP f))\"\n              and SUPPF: \"\\<forall>f \\<in> F. finite (SUPP f) \\<and> SUPP f \\<noteq> {} \\<and> SUPP f \\<subseteq> Field s\"\n              using maxim_isMaxim_support support_not_const by auto\n            define z where \"z = s.minim {s.maxim (SUPP f) | f. f \\<in> F}\"\n            from F SUPPF maxF have zmin: \"s.isMinim {s.maxim (SUPP f) | f. f \\<in> F} z\"\n              unfolding z_def by (intro s.minim_isMinim) (auto simp: s.isMaxim_def)\n            with F have zy: \"(z, y) \\<in> s\" unfolding s.isMinim_def by auto\n            hence zField: \"z \\<in> Field s\" unfolding Field_def by auto\n            define x0 where \"x0 = r.minim {f z | f. f \\<in> F \\<and> z = s.maxim (SUPP f)}\"\n            from F(1,2) maxF(1) SUPPF zmin\n              have x0min: \"r.isMinim {f z | f. f \\<in> F \\<and> z = s.maxim (SUPP f)} x0\"\n              unfolding x0_def s.isMaxim_def s.isMinim_def\n              by (blast intro!: r.minim_isMinim FinFuncD[of _ r s])\n            with maxF(1) SUPPF F(1) have x0Field: \"x0 \\<in> Field r\"\n              unfolding r.isMinim_def s.isMaxim_def by (auto intro!: FINFUNCD)\n            from x0min maxF(1) SUPPF F(1) have x0notzero: \"x0 \\<noteq> r.zero\"\n              unfolding r.isMinim_def s.isMaxim_def FinFunc_def Func_def support_def\n              by fastforce\n            define G where \"G = {f(z := r.zero) | f. f \\<in> F \\<and> z = s.maxim (SUPP f) \\<and> f z = x0}\"\n            from zmin x0min have \"G \\<noteq> {}\" unfolding G_def z_def s.isMinim_def r.isMinim_def by blast\n            have GF: \"G \\<subseteq> (\\<lambda>f. f(z := r.zero)) ` F\" unfolding G_def by auto\n            have \"G \\<subseteq> fin_support r.zero (Field s)\"\n            unfolding FinFunc_def fin_support_def proof safe\n              fix g assume \"g \\<in> G\"\n              with GF obtain f where f: \"f \\<in> F\" \"g = f(z := r.zero)\" by auto\n              with SUPPF have \"finite (SUPP f)\" by blast\n              with f show \"finite (SUPP g)\"\n                by (elim finite_subset[rotated]) (auto simp: support_def)\n            qed\n            moreover from F GF zField have \"G \\<subseteq> Func (Field s) (Field r)\"\n              using Func_upd[of _ \"Field s\" \"Field r\" z r.zero] unfolding FinFunc_def by auto\n            ultimately have G: \"G \\<subseteq> FINFUNC\" unfolding FinFunc_def by blast\n            hence \"\\<exists>g0\\<in>G. \\<forall>g\\<in>G. (g0, g) \\<in> oexp\"\n            proof (cases \"const \\<in> G\")\n              case False\n              with G have maxG: \"\\<forall>g \\<in> G. s.isMaxim (SUPP g) (s.maxim (SUPP g))\"\n                and SUPPG: \"\\<forall>g \\<in> G. finite (SUPP g) \\<and> SUPP g \\<noteq> {} \\<and> SUPP g \\<subseteq> Field s\"\n                using maxim_isMaxim_support support_not_const by auto\n              define y' where \"y' = s.minim {s.maxim (SUPP f) | f. f \\<in> G}\"\n              from G SUPPG maxG \\<open>G \\<noteq> {}\\<close> have y'min: \"s.isMinim {s.maxim (SUPP f) | f. f \\<in> G} y'\"\n                unfolding y'_def by (intro s.minim_isMinim) (auto simp: s.isMaxim_def)\n              moreover\n              have \"\\<forall>g \\<in> G. z \\<notin> SUPP g\" unfolding support_def G_def by auto\n              moreover\n              { fix g assume g: \"g \\<in> G\"\n                then obtain f where \"f \\<in> F\" \"g = f(z := r.zero)\" and z: \"z = s.maxim (SUPP f)\"\n                  unfolding G_def by auto\n                with SUPPF bspec[OF SUPPG g] have \"(s.maxim (SUPP g), z) \\<in> s\"\n                  unfolding z by (intro s.maxim_mono) auto\n              }\n              moreover from y'min have \"\\<And>g. g \\<in> G \\<Longrightarrow> (y', s.maxim (SUPP g)) \\<in> s\"\n                  unfolding s.isMinim_def by auto\n              ultimately have \"y' \\<noteq> z\" \"(y', z) \\<in> s\" using maxG\n                unfolding s.isMinim_def s.isMaxim_def by auto\n              with zy have \"y' \\<noteq> y\" \"(y', y) \\<in> s\" using antisymD[OF s.ANTISYM] transD[OF s.TRANS]\n                by blast+\n              moreover from \\<open>G \\<noteq> {}\\<close> have \"\\<exists>g \\<in> G. y' = wo_rel.maxim s (SUPP g)\" using y'min\n                by (auto simp: G_def s.isMinim_def)\n              ultimately show ?thesis using mp[OF spec[OF mp[OF spec[OF 1]]], of y' G] G by auto\n            qed simp\n            then obtain g0 where g0: \"g0 \\<in> G\" \"\\<forall>g \\<in> G. (g0, g) \\<in> oexp\" by blast\n            hence g0z: \"g0 z = r.zero\" unfolding G_def by auto\n            define f0 where \"f0 = g0(z := x0)\"\n            with x0notzero zField have SUPP: \"SUPP f0 = SUPP g0 \\<union> {z}\" unfolding support_def by auto\n            from g0z have f0z: \"f0(z := r.zero) = g0\" unfolding f0_def fun_upd_upd by auto\n            have f0: \"f0 \\<in> F\" using x0min g0(1)\n              Func_elim[OF subsetD[OF subset_trans[OF F(1)[unfolded FinFunc_def] Int_lower1]] zField]\n              unfolding f0_def r.isMinim_def G_def by (force simp: fun_upd_idem)\n            from g0(1) maxF(1) have maxf0: \"s.maxim (SUPP f0) = z\" unfolding SUPP G_def\n              by (intro s.maxim_equality) (auto simp: s.isMaxim_def)\n            show ?thesis\n            proof (intro bexI[OF _ f0] ballI)\n              fix f assume f: \"f \\<in> F\"\n              show \"(f0, f) \\<in> oexp\"\n              proof (cases \"f0 = f\")\n                case True thus ?thesis by (metis F(1) Field_oexp f0 in_mono oexp_Refl refl_onD)\n              next\n                case False\n                thus ?thesis\n                proof (cases \"s.maxim (SUPP f) = z \\<and> f z = x0\")\n                  case True\n                  with f have \"f(z := r.zero) \\<in> G\" unfolding G_def by blast\n                  with g0(2) f0z have \"(f0(z := r.zero), f(z := r.zero)) \\<in> oexp\" by auto\n                  hence oexp: \"(f0(z := r.zero, z := x0), f(z := r.zero, z := x0)) \\<in> oexp\"\n                    by (elim fun_upd_same_oexp[OF _ _ zField x0Field]) simp\n                  with f F(1) x0min True\n                    have \"(f(z := x0), f) \\<in> oexp\" unfolding G_def r.isMinim_def\n                    by (intro fun_upd_smaller_oexp[OF _ zField x0Field]) auto\n                  with oexp show ?thesis using transD[OF oexp_trans, of f0 \"f(z := x0)\" f]\n                    unfolding f0_def by auto\n                next\n                  case False note notG = this\n                  thus ?thesis\n                  proof (cases \"s.maxim (SUPP f) = z\")\n                    case True\n                    with notG have \"f0 z \\<noteq> f z\" unfolding f0_def by auto\n                    hence \"f0 z \\<noteq> f z\" by metis\n                    with True maxf0 f0 f SUPPF have \"s.max_fun_diff f0 f = z\"\n                      using s.maxim_Un[of \"SUPP f0\" \"SUPP f\", unfolded s.max2_def]\n                      unfolding max_fun_diff_alt by (intro trans[OF s.maxim_Int]) auto\n                    moreover\n                    from x0min True f have \"(x0, f z) \\<in> r\" unfolding r.isMinim_def by auto\n                    ultimately show ?thesis using f f0 F(1) unfolding oexp_def f0_def by auto\n                  next\n                    case False\n                    with notG have *: \"(z, s.maxim (SUPP f)) \\<in> s\" \"z \\<noteq> s.maxim (SUPP f)\"\n                      using zmin f unfolding s.isMinim_def G_def by auto\n                    have f0f: \"f0 (s.maxim (SUPP f)) = r.zero\"\n                    proof (rule ccontr)\n                      assume \"f0 (s.maxim (SUPP f)) \\<noteq> r.zero\"\n                      with f SUPPF maxF(1) have \"s.maxim (SUPP f) \\<in> SUPP f0\"\n                        unfolding support_def[of _ _ f0] s.isMaxim_def by auto\n                      with SUPPF f0 have \"(s.maxim (SUPP f), z) \\<in> s\" unfolding maxf0[symmetric]\n                        by (auto intro: s.maxim_greatest)\n                      with * antisymD[OF s.ANTISYM] show False by simp\n                    qed\n                    moreover\n                    have \"f (s.maxim (SUPP f)) \\<noteq> r.zero\"\n                      using bspec[OF maxF(1) f, unfolded s.isMaxim_def] by (auto simp: support_def)\n                    with f0f * f f0 maxf0 SUPPF\n                      have \"s.max_fun_diff f0 f = s.maxim (SUPP f0 \\<union> SUPP f)\"\n                      unfolding max_fun_diff_alt using s.maxim_Un[of \"SUPP f0\" \"SUPP f\"]\n                      by (intro s.maxim_Int) (auto simp: s.max2_def)\n                    moreover have \"s.maxim (SUPP f0 \\<union> SUPP f) = s.maxim (SUPP f)\"\n                       using s.maxim_Un[of \"SUPP f0\" \"SUPP f\"] * maxf0 SUPPF f0 f\n                       by (auto simp: s.max2_def)\n                    ultimately show ?thesis using f f0 F(1) maxF(1) SUPPF unfolding oexp_def Let_def\n                      by (fastforce simp: s.isMaxim_def intro!: r.zero_smallest FINFUNCD)\n                  qed\n                qed\n              qed\n            qed\n          qed simp\n        qed\n      qed\n    } note * = mp[OF this]\n    from A(2) obtain f where f: \"f \\<in> A\" by blast\n    with A(1) show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a, a') \\<in> oexp\"\n    proof (cases \"f = const\")\n      case False with f A(1) show ?thesis using maxim_isMaxim_support[of \"{f}\"]\n        by (intro *[of _ \"s.maxim (SUPP f)\"]) (auto simp: s.isMaxim_def support_def)\n    qed simp\n  qed\nqed\n\nlemma oexp_Well_order: \"Well_order oexp\"\n  unfolding well_order_on_def using oexp_Linear_order oexp_wf_Id by blast\n\ninterpretation o: wo_rel oexp by unfold_locales (rule oexp_Well_order)\n\nlemma zero_oexp: \"Field r \\<noteq> {} \\<Longrightarrow> o.zero = const\"\n  by (rule sym[OF o.leq_zero_imp[OF const_least]])\n    (auto intro!: o.zero_in_Field[unfolded Field_oexp] dest!: const_FINFUNC)\n\nend\n\nnotation wo_rel2.oexp (infixl \"^o\" 90)\nlemmas oexp_def = wo_rel2.oexp_def[unfolded wo_rel2_def, OF conjI]\nlemmas oexp_Well_order = wo_rel2.oexp_Well_order[unfolded wo_rel2_def, OF conjI]\nlemmas Field_oexp = wo_rel2.Field_oexp[unfolded wo_rel2_def, OF conjI]\n\ndefinition \"ozero = {}\"\n\nlemma ozero_Well_order[simp]: \"Well_order ozero\"\n  unfolding ozero_def by simp\n\nlemma ozero_ordIso[simp]: \"ozero =o ozero\"\n  unfolding ozero_def ordIso_def iso_def[abs_def] embed_def bij_betw_def by auto\n\nlemma Field_ozero[simp]: \"Field ozero = {}\"\n  unfolding ozero_def by simp\n\nlemma iso_ozero_empty[simp]: \"r =o ozero = (r = {})\"\n  unfolding ozero_def ordIso_def iso_def[abs_def] embed_def bij_betw_def\n  by (auto dest: well_order_on_domain)\n\nlemma ozero_ordLeq:\nassumes \"Well_order r\"  shows \"ozero \\<le>o r\"\nusing assms unfolding ozero_def ordLeq_def embed_def[abs_def] under_def by auto\n\ndefinition \"oone = {((),())}\"\n\nlemma oone_Well_order[simp]: \"Well_order oone\"\n  unfolding oone_def unfolding well_order_on_def linear_order_on_def partial_order_on_def\n    preorder_on_def total_on_def refl_on_def trans_def antisym_def by auto\n\nlemma Field_oone[simp]: \"Field oone = {()}\"\n  unfolding oone_def by simp\n\nlemma oone_ordIso: \"oone =o {(x,x)}\"\n  unfolding ordIso_def oone_def well_order_on_def linear_order_on_def partial_order_on_def\n    preorder_on_def total_on_def refl_on_def trans_def antisym_def\n  by (auto simp: iso_def embed_def bij_betw_def under_def inj_on_def intro!: exI[of _ \"\\<lambda>_. x\"])\n\nlemma osum_ordLeqR: \"Well_order r \\<Longrightarrow> Well_order s \\<Longrightarrow> s \\<le>o r +o s\"\n  unfolding ordLeq_def2 underS_def\n  by (auto intro!: exI[of _ Inr] osum_Well_order) (auto simp add: osum_def Field_def)\n\nlemma osum_congL:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"r +o t =o s +o t\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_sum f id\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_osum iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_osum iso_def bij_betw_def image_image image_Un by auto\n  moreover from f have \"compat ?L ?R ?f\"\n    unfolding osum_def iso_iff3[OF r s] compat_def bij_betw_def\n    by (auto simp: map_prod_imageI)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: osum_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: osum_Well_order r s t)\nqed\n\nlemma osum_congR:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"t +o r =o t +o s\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_sum id f\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_osum iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_osum iso_def bij_betw_def image_image image_Un by auto\n  moreover from f have \"compat ?L ?R ?f\"\n    unfolding osum_def iso_iff3[OF r s] compat_def bij_betw_def\n    by (auto simp: map_prod_imageI)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: osum_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: osum_Well_order r s t)\nqed\n\nlemma osum_cong:\n  assumes \"t =o u\" and \"r =o s\"\n  shows \"t +o r =o u +o s\"\nusing ordIso_transitive[OF osum_congL[OF assms(1)] osum_congR[OF assms(2)]]\n  assms[unfolded ordIso_def] by auto\n\nlemma Well_order_empty[simp]: \"Well_order {}\"\n  unfolding Field_empty by (rule well_order_on_empty)\n\nlemma well_order_on_singleton[simp]: \"well_order_on {x} {(x, x)}\"\n  unfolding well_order_on_def linear_order_on_def partial_order_on_def preorder_on_def total_on_def\n    Field_def refl_on_def trans_def antisym_def by auto\n\nlemma oexp_empty[simp]:\n  assumes \"Well_order r\"\n  shows \"r ^o {} = {(\\<lambda>x. undefined, \\<lambda>x. undefined)}\"\n  unfolding oexp_def[OF assms Well_order_empty] FinFunc_def fin_support_def support_def by auto\n\nlemma oexp_empty2[simp]:\n  assumes \"Well_order r\" \"r \\<noteq> {}\"\n  shows \"{} ^o r = {}\"\nproof -\n  from assms(2) have \"Field r \\<noteq> {}\" unfolding Field_def by auto\n  thus ?thesis unfolding oexp_def[OF Well_order_empty assms(1)] FinFunc_def fin_support_def support_def\n    by auto\nqed\n\nlemma oprod_zero[simp]: \"{} *o r = {}\" \"r *o {} = {}\"\n  unfolding oprod_def by simp_all\n\nlemma oprod_congL:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"r *o t =o s *o t\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_prod f id\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_oprod iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_oprod iso_def bij_betw_def by (auto intro!: map_prod_surj_on)\n  moreover from f have \"compat ?L ?R ?f\"\n    unfolding iso_iff3[OF r s] compat_def oprod_def bij_betw_def\n    by (auto simp: map_prod_imageI)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: oprod_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_congR:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"t *o r =o t *o s\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_prod id f\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_oprod iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_oprod iso_def bij_betw_def by (auto intro!: map_prod_surj_on)\n  moreover from f well_order_on_domain[OF r] have \"compat ?L ?R ?f\"\n    unfolding iso_iff3[OF r s] compat_def oprod_def bij_betw_def\n    by (auto simp: map_prod_imageI dest: inj_onD)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: oprod_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_cong:\n  assumes \"t =o u\" and \"r =o s\"\n  shows \"t *o r =o u *o s\"\nusing ordIso_transitive[OF oprod_congL[OF assms(1)] oprod_congR[OF assms(2)]]\n  assms[unfolded ordIso_def] by auto\n\nlemma Field_singleton[simp]: \"Field {(z,z)} = {z}\"\n  by (metis well_order_on_Field well_order_on_singleton)\n\nlemma zero_singleton[simp]: \"zero {(z,z)} = z\"\n  using wo_rel.zero_in_Field[unfolded wo_rel_def, of \"{(z, z)}\"] well_order_on_singleton[of z]\n  by auto\n\nlemma FinFunc_singleton: \"FinFunc {(z,z)} s = {\\<lambda>x. if x \\<in> Field s then z else undefined}\"\n  unfolding FinFunc_def Func_def fin_support_def support_def\n  by (auto simp: fun_eq_iff split: if_split_asm intro!: finite_subset[of _ \"{}\"])\n\nlemma oone_ordIso_oexp:\n  assumes \"r =o oone\" and s: \"Well_order s\"\n  shows \"r ^o s =o oone\" (is \"?L =o ?R\")\nproof -\n  from \\<open>r =o oone\\<close> obtain f where *: \"\\<forall>x\\<in>Field r. \\<forall>y\\<in>Field r. x = y\" and \"f ` Field r = {()}\"\n    and r: \"Well_order r\"\n    unfolding ordIso_def oone_def by (auto simp add: iso_def [abs_def] bij_betw_def inj_on_def)\n  then obtain x where \"x \\<in> Field r\" by auto\n  with * have Fr: \"Field r = {x}\" by auto\n  interpret r: wo_rel r by unfold_locales (rule r)\n  from Fr well_order_on_domain[OF r] refl_onD[OF r.REFL, of x] have r_def: \"r = {(x, x)}\" by fast\n  interpret wo_rel2 r s by unfold_locales (rule r, rule s)\n  have \"bij_betw (\\<lambda>x. ()) (Field ?L) (Field ?R)\"\n    unfolding bij_betw_def Field_oexp by (auto simp: r_def FinFunc_singleton)\n  moreover have \"compat ?L ?R (\\<lambda>x. ())\" unfolding compat_def oone_def by auto\n  ultimately have \"iso ?L ?R (\\<lambda>x. ())\" using s oone_Well_order\n    by (subst iso_iff3) (auto intro: oexp_Well_order)\n  thus ?thesis using s oone_Well_order unfolding ordIso_def by (auto intro: oexp_Well_order)\nqed\n\n(*Lemma 1.4.3 from Holz et al.*)\ncontext\n  fixes r s t\n  assumes r: \"Well_order r\"\n  assumes s: \"Well_order s\"\n  assumes t: \"Well_order t\"\nbegin\n\nlemma osum_ozeroL: \"ozero +o r =o r\"\n  using r unfolding osum_def ozero_def by (auto intro: map_prod_ordIso)\n\nlemma osum_ozeroR: \"r +o ozero =o r\"\n  using r unfolding osum_def ozero_def by (auto intro: map_prod_ordIso)\n\nlemma osum_assoc: \"(r +o s) +o t =o r +o s +o t\" (is \"?L =o ?R\")\nproof -\n  let ?f =\n    \"\\<lambda>rst. case rst of Inl (Inl r) \\<Rightarrow> Inl r | Inl (Inr s) \\<Rightarrow> Inr (Inl s) | Inr t \\<Rightarrow> Inr (Inr t)\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_osum bij_betw_def inj_on_def by (auto simp: image_Un image_iff)\n  moreover\n  have \"compat ?L ?R ?f\"\n  proof (unfold compat_def, safe)\n    fix a b\n    assume \"(a, b) \\<in> ?L\"\n    thus \"(?f a, ?f b) \\<in> ?R\"\n      unfolding osum_def[of \"r +o s\" t] osum_def[of r \"s +o t\"] Field_osum\n      unfolding osum_def Field_osum image_iff image_Un map_prod_def\n      by fastforce\n  qed\n  ultimately have \"iso ?L ?R ?f\" using r s t by (subst iso_iff3) (auto intro: osum_Well_order)\n  thus ?thesis using r s t unfolding ordIso_def by (auto intro: osum_Well_order)\nqed\n\nlemma osum_monoR:\n  assumes \"s <o t\"\n  shows \"r +o s <o r +o t\" (is \"?L <o ?R\")\nproof -\n  from assms obtain f where s: \"Well_order s\" and t:\" Well_order t\" and \"embedS s t f\"\n    unfolding ordLess_def by blast\n  hence *: \"inj_on f (Field s)\" \"compat s t f\" \"ofilter t (f ` Field s)\" \"f ` Field s \\<subset> Field t\"\n    using embed_iff_compat_inj_on_ofilter[OF s t, of f] embedS_iff[OF s, of t f]\n    unfolding embedS_def by auto\n  let ?f = \"map_sum id f\"\n  from *(1) have \"inj_on ?f (Field ?L)\" unfolding Field_osum inj_on_def by fastforce\n  moreover\n  from *(2,4) have \"compat ?L ?R ?f\" unfolding compat_def osum_def map_prod_def by fastforce\n  moreover\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret rt: wo_rel ?R by unfold_locales (rule osum_Well_order[OF r t])\n  from *(3) have \"ofilter ?R (?f ` Field ?L)\"\n    unfolding t.ofilter_def rt.ofilter_def Field_osum image_Un image_image under_def\n    by (auto simp: osum_def intro!: imageI) (auto simp: Field_def)\n  ultimately have \"embed ?L ?R ?f\" using embed_iff_compat_inj_on_ofilter[of ?L ?R ?f]\n    by (auto intro: osum_Well_order r s t)\n  moreover\n  from *(4) have \"?f ` Field ?L \\<subset> Field ?R\" unfolding Field_osum image_Un image_image by auto\n  ultimately have \"embedS ?L ?R ?f\" using embedS_iff[OF osum_Well_order[OF r s], of ?R ?f] by auto\n  thus ?thesis unfolding ordLess_def by (auto intro: osum_Well_order r s t)\nqed\n\nlemma osum_monoL:\n  assumes \"r \\<le>o s\"\n  shows \"r +o t \\<le>o s +o t\"\nproof -\n  from assms obtain f where f: \"\\<forall>a\\<in>Field r. f a \\<in> Field s \\<and> f ` underS r a \\<subseteq> underS s (f a)\"\n    unfolding ordLeq_def2 by blast\n  let ?f = \"map_sum f id\"\n  from f have \"\\<forall>a\\<in>Field (r +o t).\n     ?f a \\<in> Field (s +o t) \\<and> ?f ` underS (r +o t) a \\<subseteq> underS (s +o t) (?f a)\"\n     unfolding Field_osum underS_def by (fastforce simp: osum_def)\n  thus ?thesis unfolding ordLeq_def2 by (auto intro: osum_Well_order r s t)\nqed\n\nlemma oprod_ozeroL: \"ozero *o r =o ozero\"\n  using ozero_ordIso unfolding ozero_def by simp\n\nlemma oprod_ozeroR: \"r *o ozero =o ozero\"\n  using ozero_ordIso unfolding ozero_def by simp\n\nlemma oprod_ooneR: \"r *o oone =o r\" (is \"?L =o ?R\")\nproof -\n  have \"bij_betw fst (Field ?L) (Field ?R)\" unfolding Field_oprod bij_betw_def inj_on_def by simp\n  moreover have \"compat ?L ?R fst\" unfolding compat_def oprod_def by auto\n  ultimately have \"iso ?L ?R fst\" using r oone_Well_order\n    by (subst iso_iff3) (auto intro: oprod_Well_order)\n  thus ?thesis using r oone_Well_order unfolding ordIso_def by (auto intro: oprod_Well_order)\nqed\n\nlemma oprod_ooneL: \"oone *o r =o r\" (is \"?L =o ?R\")\nproof -\n  have \"bij_betw snd (Field ?L) (Field ?R)\" unfolding Field_oprod bij_betw_def inj_on_def by simp\n  moreover have \"Refl r\" by (rule wo_rel.REFL[unfolded wo_rel_def, OF r])\n  hence \"compat ?L ?R snd\" unfolding compat_def oprod_def refl_on_def by auto\n  ultimately have \"iso ?L ?R snd\" using r oone_Well_order\n    by (subst iso_iff3) (auto intro: oprod_Well_order)\n  thus ?thesis using r oone_Well_order unfolding ordIso_def by (auto intro: oprod_Well_order)\nqed\n\nlemma oprod_monoR:\n  assumes \"ozero <o r\" \"s <o t\"\n  shows \"r *o s <o r *o t\" (is \"?L <o ?R\")\nproof -\n  from assms obtain f where s: \"Well_order s\" and t:\" Well_order t\" and \"embedS s t f\"\n    unfolding ordLess_def by blast\n  hence *: \"inj_on f (Field s)\" \"compat s t f\" \"ofilter t (f ` Field s)\" \"f ` Field s \\<subset> Field t\"\n    using embed_iff_compat_inj_on_ofilter[OF s t, of f] embedS_iff[OF s, of t f]\n    unfolding embedS_def by auto\n  let ?f = \"map_prod id f\"\n  from *(1) have \"inj_on ?f (Field ?L)\" unfolding Field_oprod inj_on_def by fastforce\n  moreover\n  from *(2,4) the_inv_into_f_f[OF *(1)] have \"compat ?L ?R ?f\" unfolding compat_def oprod_def\n    by auto (metis well_order_on_domain t, metis well_order_on_domain s)\n  moreover\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret rt: wo_rel ?R by unfold_locales (rule oprod_Well_order[OF r t])\n  from *(3) have \"ofilter ?R (?f ` Field ?L)\"\n    unfolding t.ofilter_def rt.ofilter_def Field_oprod under_def\n    by (auto simp: oprod_def image_iff) (fast | metis r well_order_on_domain)+\n  ultimately have \"embed ?L ?R ?f\" using embed_iff_compat_inj_on_ofilter[of ?L ?R ?f]\n    by (auto intro: oprod_Well_order r s t)\n  moreover\n  from not_ordLess_ordIso[OF assms(1)] have \"r \\<noteq> {}\" by (metis ozero_def ozero_ordIso)\n  hence \"Field r \\<noteq> {}\" unfolding Field_def by auto\n  with *(4) have \"?f ` Field ?L \\<subset> Field ?R\" unfolding Field_oprod\n    by auto (metis SigmaD2 SigmaI map_prod_surj_on)\n  ultimately have \"embedS ?L ?R ?f\" using embedS_iff[OF oprod_Well_order[OF r s], of ?R ?f] by auto\n  thus ?thesis unfolding ordLess_def by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_monoL:\n  assumes \"r \\<le>o s\"\n  shows \"r *o t \\<le>o s *o t\"\nproof -\n  from assms obtain f where f: \"\\<forall>a\\<in>Field r. f a \\<in> Field s \\<and> f ` underS r a \\<subseteq> underS s (f a)\"\n    unfolding ordLeq_def2 by blast\n  let ?f = \"map_prod f id\"\n  from f have \"\\<forall>a\\<in>Field (r *o t).\n     ?f a \\<in> Field (s *o t) \\<and> ?f ` underS (r *o t) a \\<subseteq> underS (s *o t) (?f a)\"\n     unfolding Field_oprod underS_def unfolding map_prod_def oprod_def by auto\n  thus ?thesis unfolding ordLeq_def2 by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_assoc: \"(r *o s) *o t =o r *o s *o t\" (is \"?L =o ?R\")\nproof -\n  let ?f = \"\\<lambda>((a,b),c). (a,b,c)\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_oprod bij_betw_def inj_on_def by (auto simp: image_Un image_iff)\n  moreover\n  have \"compat ?L ?R ?f\"\n  proof (unfold compat_def, safe)\n    fix a1 a2 a3 b1 b2 b3\n    assume \"(((a1, a2), a3), ((b1, b2), b3)) \\<in> ?L\"\n    thus \"((a1, a2, a3), (b1, b2, b3)) \\<in> ?R\"\n      unfolding oprod_def[of \"r *o s\" t] oprod_def[of r \"s *o t\"] Field_oprod\n      unfolding oprod_def Field_oprod image_iff image_Un by fast\n  qed\n  ultimately have \"iso ?L ?R ?f\" using r s t by (subst iso_iff3) (auto intro: oprod_Well_order)\n  thus ?thesis using r s t unfolding ordIso_def by (auto intro: oprod_Well_order)\nqed\n\nlemma oprod_osum: \"r *o (s +o t) =o r *o s +o r *o t\" (is \"?L =o ?R\")\nproof -\n  let ?f = \"\\<lambda>(a,bc). case bc of Inl b \\<Rightarrow> Inl (a, b) | Inr c \\<Rightarrow> Inr (a, c)\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\" unfolding Field_oprod Field_osum bij_betw_def inj_on_def\n    by (fastforce simp: image_Un image_iff split: sum.splits)\n  moreover\n  have \"compat ?L ?R ?f\"\n  proof (unfold compat_def, intro allI impI)\n    fix a b\n    assume \"(a, b) \\<in> ?L\"\n    thus \"(?f a, ?f b) \\<in> ?R\"\n      unfolding oprod_def[of r \"s +o t\"] osum_def[of \"r *o s\" \"r *o t\"] Field_oprod Field_osum\n      unfolding oprod_def osum_def Field_oprod Field_osum image_iff image_Un by auto\n  qed\n  ultimately have \"iso ?L ?R ?f\" using r s t\n    by (subst iso_iff3) (auto intro: oprod_Well_order osum_Well_order)\n  thus ?thesis using r s t unfolding ordIso_def by (auto intro: oprod_Well_order osum_Well_order)\nqed\n\nlemma ozero_oexp: \"\\<not> (s =o ozero) \\<Longrightarrow> ozero ^o s =o ozero\"\n  unfolding oexp_def[OF ozero_Well_order s] FinFunc_def\n  by simp (metis Func_emp2 bot.extremum_uniqueI emptyE well_order_on_domain s subrelI)\n\nlemma oone_oexp: \"oone ^o s =o oone\" (is \"?L =o ?R\")\n  by (rule oone_ordIso_oexp[OF ordIso_reflexive[OF oone_Well_order] s])\n\nlemma oexp_monoR:\n  assumes \"oone <o r\" \"s <o t\"\n  shows   \"r ^o s <o r ^o t\" (is \"?L <o ?R\")\nproof -\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rt: wo_rel2 r t by unfold_locales (rule r, rule t)\n  interpret rexpt: wo_rel \"r ^o t\" by unfold_locales (rule rt.oexp_Well_order)\n  interpret r: wo_rel r by unfold_locales (rule r)\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret t: wo_rel t by unfold_locales (rule t)\n  have \"Field r \\<noteq> {}\" by (metis assms(1) internalize_ordLess not_psubset_empty)\n  moreover\n  { assume \"Field r = {r.zero}\"\n    hence \"r = {(r.zero, r.zero)}\" using refl_onD[OF r.REFL, of r.zero] unfolding Field_def by auto\n    hence \"r =o oone\" by (metis oone_ordIso ordIso_symmetric)\n    with not_ordLess_ordIso[OF assms(1)] have False by (metis ordIso_symmetric)\n  }\n  ultimately obtain x where x: \"x \\<in> Field r\" \"r.zero \\<in> Field r\" \"x \\<noteq> r.zero\"\n    by (metis insert_iff r.zero_in_Field subsetI subset_singletonD)\n  moreover from assms(2) obtain f where \"embedS s t f\" unfolding ordLess_def by blast\n  hence *: \"inj_on f (Field s)\" \"compat s t f\" \"ofilter t (f ` Field s)\" \"f ` Field s \\<subset> Field t\"\n    using embed_iff_compat_inj_on_ofilter[OF s t, of f] embedS_iff[OF s, of t f]\n    unfolding embedS_def by auto\n  note invff = the_inv_into_f_f[OF *(1)] and injfD = inj_onD[OF *(1)]\n  define F where [abs_def]: \"F g z =\n    (if z \\<in> f ` Field s then g (the_inv_into (Field s) f z)\n     else if z \\<in> Field t then r.zero else undefined)\" for g z\n  from *(4) x(2) the_inv_into_f_eq[OF *(1)] have FLR: \"F ` Field ?L \\<subseteq> Field ?R\"\n    unfolding rt.Field_oexp rs.Field_oexp FinFunc_def Func_def fin_support_def support_def F_def\n    by (fastforce split: option.splits if_split_asm elim!: finite_surj[of _ _ f])\n  have \"inj_on F (Field ?L)\" unfolding rs.Field_oexp inj_on_def fun_eq_iff\n  proof safe\n    fix g h x assume \"g \\<in> FinFunc r s\" \"h \\<in> FinFunc r s\" \"\\<forall>y. F g y = F h y\"\n    with invff show \"g x = h x\" unfolding F_def fun_eq_iff FinFunc_def Func_def\n      by auto (metis image_eqI)\n  qed\n  moreover\n  have \"compat ?L ?R F\" unfolding compat_def rs.oexp_def rt.oexp_def\n  proof (safe elim!: bspec[OF iffD1[OF image_subset_iff FLR[unfolded rs.Field_oexp rt.Field_oexp]]])\n    fix g h assume gh: \"g \\<in> FinFunc r s\" \"h \\<in> FinFunc r s\" \"F g \\<noteq> F h\"\n      \"let m = s.max_fun_diff g h in (g m, h m) \\<in> r\"\n    hence \"g \\<noteq> h\" by auto\n    note max_fun_diff_in = rs.max_fun_diff_in[OF \\<open>g \\<noteq> h\\<close> gh(1,2)]\n    and max_fun_diff_max = rs.max_fun_diff_max[OF \\<open>g \\<noteq> h\\<close> gh(1,2)]\n    with *(4) invff *(2) have \"t.max_fun_diff (F g) (F h) = f (s.max_fun_diff g h)\"\n      unfolding t.max_fun_diff_def compat_def\n      by (intro t.maxim_equality) (auto simp: t.isMaxim_def F_def dest: injfD)\n    with gh invff max_fun_diff_in\n      show \"let m = t.max_fun_diff (F g) (F h) in (F g m, F h m) \\<in> r\"\n      unfolding F_def Let_def by (auto simp: dest: injfD)\n  qed\n  moreover\n  from FLR have \"ofilter ?R (F ` Field ?L)\"\n  unfolding rexpt.ofilter_def under_def rs.Field_oexp rt.Field_oexp unfolding rt.oexp_def\n  proof (safe elim!: imageI)\n    fix g h assume gh: \"g \\<in> FinFunc r s\" \"h \\<in> FinFunc r t\" \"F g \\<in> FinFunc r t\"\n      \"let m = t.max_fun_diff h (F g) in (h m, F g m) \\<in> r\"\n    thus \"h \\<in> F ` FinFunc r s\"\n    proof (cases \"h = F g\")\n      case False\n      hence max_Field: \"t.max_fun_diff h (F g) \\<in> {a \\<in> Field t. h a \\<noteq> F g a}\"\n        by (rule rt.max_fun_diff_in[OF _ gh(2,3)])\n      { assume *: \"t.max_fun_diff h (F g) \\<notin> f ` Field s\"\n        with max_Field have **: \"F g (t.max_fun_diff h (F g)) = r.zero\" unfolding F_def by auto\n        with * gh(4) have \"h (t.max_fun_diff h (F g)) = r.zero\" unfolding Let_def by auto\n        with ** have False using max_Field gh(2,3) unfolding FinFunc_def Func_def by auto\n      }\n      hence max_f_Field: \"t.max_fun_diff h (F g) \\<in> f ` Field s\" by blast\n      { fix z assume z: \"z \\<in> Field t - f ` Field s\"\n        have \"(t.max_fun_diff h (F g), z) \\<in> t\"\n        proof (rule ccontr)\n          assume \"(t.max_fun_diff h (F g), z) \\<notin> t\"\n          hence \"(z, t.max_fun_diff h (F g)) \\<in> t\" using t.in_notinI[of \"t.max_fun_diff h (F g)\" z]\n            z max_Field by auto\n          hence \"z \\<in> f ` Field s\" using *(3) max_f_Field unfolding t.ofilter_def under_def\n            by fastforce\n          with z show False by blast\n        qed\n        hence \"h z = r.zero\" using rt.max_fun_diff_le_eq[OF _ False gh(2,3), of z]\n          z max_f_Field unfolding F_def by auto\n      } note ** = this\n      with *(3) gh(2) have \"h = F (\\<lambda>x. if x \\<in> Field s then h (f x) else undefined)\" using invff\n        unfolding F_def fun_eq_iff FinFunc_def Func_def Let_def t.ofilter_def under_def by auto\n      moreover from gh(2) *(1,3) have \"(\\<lambda>x. if x \\<in> Field s then h (f x) else undefined) \\<in> FinFunc r s\"\n        unfolding FinFunc_def Func_def fin_support_def support_def t.ofilter_def under_def\n        by (auto intro: subset_inj_on elim!: finite_imageD[OF finite_subset[rotated]])\n      ultimately show \"?thesis\" by (rule image_eqI)\n    qed simp\n  qed\n  ultimately have \"embed ?L ?R F\" using embed_iff_compat_inj_on_ofilter[of ?L ?R F]\n    by (auto intro: oexp_Well_order r s t)\n  moreover\n  from FLR have \"F ` Field ?L \\<subset> Field ?R\"\n  proof (intro psubsetI)\n    from *(4) obtain z where z: \"z \\<in> Field t\" \"z \\<notin> f ` Field s\" by auto\n    define h where [abs_def]: \"h z' =\n      (if z' \\<in> Field t then if z' = z then x else r.zero else undefined)\" for z'\n    from z x(3) have \"rt.SUPP h = {z}\" unfolding support_def h_def by simp\n    with x have \"h \\<in> Field ?R\" unfolding h_def rt.Field_oexp FinFunc_def Func_def fin_support_def\n      by auto\n    moreover\n    { fix g\n      from z have \"F g z = r.zero\" \"h z = x\" unfolding support_def h_def F_def by auto\n      with x(3) have \"F g \\<noteq> h\" unfolding fun_eq_iff by fastforce\n    }\n    hence \"h \\<notin> F ` Field ?L\" by blast\n    ultimately show \"F ` Field ?L \\<noteq> Field ?R\" by blast\n  qed\n  ultimately have \"embedS ?L ?R F\" using embedS_iff[OF rs.oexp_Well_order, of ?R F] by auto\n  thus ?thesis unfolding ordLess_def using r s t by (auto intro: oexp_Well_order)\nqed\n\nlemma oexp_monoL:\n  assumes \"r \\<le>o s\"\n  shows   \"r ^o t \\<le>o s ^o t\"\nproof -\n  interpret rt: wo_rel2 r t by unfold_locales (rule r, rule t)\n  interpret st: wo_rel2 s t by unfold_locales (rule s, rule t)\n  interpret r: wo_rel r by unfold_locales (rule r)\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret t: wo_rel t by unfold_locales (rule t)\n  show ?thesis\n  proof (cases \"t = {}\")\n    case True thus ?thesis using r s unfolding ordLeq_def2 underS_def by auto\n  next\n    case False thus ?thesis\n    proof (cases \"r = {}\")\n      case True thus ?thesis using t \\<open>t \\<noteq> {}\\<close> st.oexp_Well_order ozero_ordLeq[unfolded ozero_def]\n        by auto\n    next\n      case False\n      from assms obtain f where f: \"embed r s f\" unfolding ordLeq_def by blast\n      hence f_underS: \"\\<forall>a\\<in>Field r. f a \\<in> Field s \\<and> f ` underS r a \\<subseteq> underS s (f a)\"\n        using embed_in_Field embed_underS2 rt.rWELL by fastforce\n      from f \\<open>t \\<noteq> {}\\<close> False have *: \"Field r \\<noteq> {}\" \"Field s \\<noteq> {}\" \"Field t \\<noteq> {}\"\n        unfolding Field_def embed_def under_def bij_betw_def by auto\n      with f obtain x where \"s.zero = f x\" \"x \\<in> Field r\" unfolding embed_def bij_betw_def\n        using s.zero_under subsetD[OF under_Field[of r]]\n        by (metis (no_types, lifting) f_inv_into_f f_underS inv_into_into r.zero_in_Field)\n      with f have fz: \"f r.zero = s.zero\" and inj: \"inj_on f (Field r)\" and compat: \"compat r s f\"\n        unfolding embed_iff_compat_inj_on_ofilter[OF r s] compat_def\n        by (fastforce intro: s.leq_zero_imp)+\n      let ?f = \"\\<lambda>g x. if x \\<in> Field t then f (g x) else undefined\"\n      { fix g assume g: \"g \\<in> Field (r ^o t)\"\n        with fz f_underS have Field_fg: \"?f g \\<in> Field (s ^o t)\"\n          unfolding st.Field_oexp rt.Field_oexp FinFunc_def Func_def fin_support_def support_def\n          by (auto elim!: finite_subset[rotated])\n        moreover\n        have \"?f ` underS (r ^o t) g \\<subseteq> underS (s ^o t) (?f g)\"\n        proof safe\n          fix h\n          assume h_underS: \"h \\<in> underS (r ^o t) g\"\n          hence \"h \\<in> Field (r ^o t)\" unfolding underS_def Field_def by auto\n          with fz f_underS have Field_fh: \"?f h \\<in> Field (s ^o t)\"\n            unfolding st.Field_oexp rt.Field_oexp FinFunc_def Func_def fin_support_def support_def\n            by (auto elim!: finite_subset[rotated])\n          from h_underS have \"h \\<noteq> g\" and hg: \"(h, g) \\<in> rt.oexp\" unfolding underS_def by auto\n          with f inj have neq: \"?f h \\<noteq> ?f g\"\n            unfolding fun_eq_iff inj_on_def rt.oexp_def map_option_case FinFunc_def Func_def Let_def\n            by simp metis\n          with hg have \"t.max_fun_diff (?f h) (?f g) = t.max_fun_diff h g\" unfolding rt.oexp_def\n            using rt.max_fun_diff[OF \\<open>h \\<noteq> g\\<close>] rt.max_fun_diff_in[OF \\<open>h \\<noteq> g\\<close>]\n            by (subst t.max_fun_diff_def, intro t.maxim_equality)\n              (auto simp: t.isMaxim_def intro: inj_onD[OF inj] intro!: rt.max_fun_diff_max)\n          with Field_fg Field_fh hg fz f_underS compat neq have \"(?f h, ?f g) \\<in> st.oexp\"\n             using rt.max_fun_diff[OF \\<open>h \\<noteq> g\\<close>] rt.max_fun_diff_in[OF \\<open>h \\<noteq> g\\<close>] unfolding st.Field_oexp\n             unfolding rt.oexp_def st.oexp_def Let_def compat_def by auto\n          with neq show \"?f h \\<in> underS (s ^o t) (?f g)\" unfolding underS_def by auto\n        qed\n        ultimately have \"?f g \\<in> Field (s ^o t) \\<and> ?f ` underS (r ^o t) g \\<subseteq> underS (s ^o t) (?f g)\"\n          by blast\n      }\n      thus ?thesis unfolding ordLeq_def2 by (fastforce intro: oexp_Well_order r s t)\n    qed\n  qed\nqed\n\nlemma ordLeq_oexp2:\n  assumes \"oone <o r\"\n  shows   \"s \\<le>o r ^o s\"\nproof -\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret r: wo_rel r by unfold_locales (rule r)\n  interpret s: wo_rel s by unfold_locales (rule s)\n  from assms well_order_on_domain[OF r] obtain x where\n    x: \"x \\<in> Field r\" \"r.zero \\<in> Field r\" \"x \\<noteq> r.zero\"\n    unfolding ordLess_def oone_def embedS_def[abs_def] bij_betw_def embed_def under_def\n    by (auto simp: image_def)\n       (metis (lifting) equals0D mem_Collect_eq r.zero_in_Field singletonI)\n  let ?f = \"\\<lambda>a b. if b \\<in> Field s then if b = a then x else r.zero else undefined\"\n  from x(3) have SUPP: \"\\<And>y. y \\<in> Field s \\<Longrightarrow> rs.SUPP (?f y) = {y}\" unfolding support_def by auto\n  { fix y assume y: \"y \\<in> Field s\"\n    with x(1,2) SUPP have \"?f y \\<in> Field (r ^o s)\" unfolding rs.Field_oexp\n      by (auto simp: FinFunc_def Func_def fin_support_def)\n    moreover\n    have \"?f ` underS s y \\<subseteq> underS (r ^o s) (?f y)\"\n    proof safe\n      fix z\n      assume \"z \\<in> underS s y\"\n      hence z: \"z \\<noteq> y\" \"(z, y) \\<in> s\" \"z \\<in> Field s\" unfolding underS_def Field_def by auto\n      from x(3) y z(1,3) have \"?f z \\<noteq> ?f y\" unfolding fun_eq_iff by auto\n      moreover\n      { from x(1,2) have \"?f z \\<in> FinFunc r s\" \"?f y \\<in> FinFunc r s\"\n          unfolding FinFunc_def Func_def fin_support_def by (auto simp: SUPP[OF z(3)] SUPP[OF y])\n        moreover\n        from x(3) y z(1,2) refl_onD[OF s.REFL] have \"s.max_fun_diff (?f z) (?f y) = y\"\n          unfolding rs.max_fun_diff_alt SUPP[OF z(3)] SUPP[OF y]\n          by (intro s.maxim_equality) (auto simp: s.isMaxim_def)\n        ultimately have \"(?f z, ?f y) \\<in> rs.oexp\" using y x(1)\n          unfolding rs.oexp_def Let_def by auto\n      }\n      ultimately show \"?f z \\<in> underS (r ^o s) (?f y)\" unfolding underS_def by blast\n    qed\n    ultimately have \"?f y \\<in> Field (r ^o s) \\<and> ?f ` underS s y \\<subseteq> underS (r ^o s) (?f y)\" by blast\n  }\n  thus ?thesis unfolding ordLeq_def2 by (fast intro: oexp_Well_order r s)\nqed\n\nlemma FinFunc_osum:\n  \"fg \\<in> FinFunc r (s +o t) = (fg o Inl \\<in> FinFunc r s \\<and> fg o Inr \\<in> FinFunc r t)\"\n  (is \"?L = (?R1 \\<and> ?R2)\")\nproof safe\n  assume ?L\n  from \\<open>?L\\<close> show ?R1 unfolding FinFunc_def Field_osum Func_def Int_iff fin_support_Field_osum o_def\n    by (auto split: sum.splits)\n  from \\<open>?L\\<close> show ?R2 unfolding FinFunc_def Field_osum Func_def Int_iff fin_support_Field_osum o_def\n    by (auto split: sum.splits)\nnext\n  assume ?R1 ?R2\n  thus \"?L\" unfolding FinFunc_def Field_osum Func_def\n    by (auto simp: fin_support_Field_osum o_def image_iff split: sum.splits) (metis sumE)\nqed\n\nlemma max_fun_diff_eq_Inl:\n  assumes \"wo_rel.max_fun_diff (s +o t) (case_sum f1 g1) (case_sum f2 g2) = Inl x\"\n    \"case_sum f1 g1 \\<noteq> case_sum f2 g2\"\n    \"case_sum f1 g1 \\<in> FinFunc r (s +o t)\" \"case_sum f2 g2 \\<in> FinFunc r (s +o t)\"\n  shows \"wo_rel.max_fun_diff s f1 f2 = x\" (is ?P) \"g1 = g2\" (is ?Q)\nproof -\n  interpret st: wo_rel \"s +o t\" by unfold_locales (rule osum_Well_order[OF s t])\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret rst: wo_rel2 r \"s +o t\" by unfold_locales (rule r, rule osum_Well_order[OF s t])\n  from assms(1) have *: \"st.isMaxim {a \\<in> Field (s +o t). case_sum f1 g1 a \\<noteq> case_sum f2 g2 a} (Inl x)\"\n    using rst.isMaxim_max_fun_diff[OF assms(2-4)] by simp\n  hence \"s.isMaxim {a \\<in> Field s. f1 a \\<noteq> f2 a} x\"\n    unfolding st.isMaxim_def s.isMaxim_def Field_osum by (auto simp: osum_def)\n  thus ?P unfolding s.max_fun_diff_def by (rule s.maxim_equality)\n  from assms(3,4) have **: \"g1 \\<in> FinFunc r t\" \"g2 \\<in> FinFunc r t\" unfolding FinFunc_osum\n    by (auto simp: o_def)\n  show ?Q\n  proof\n    fix x\n    from * ** show \"g1 x = g2 x\" unfolding st.isMaxim_def Field_osum FinFunc_def Func_def fun_eq_iff\n      unfolding osum_def by (case_tac \"x \\<in> Field t\") auto\n  qed\nqed\n\nlemma max_fun_diff_eq_Inr:\n  assumes \"wo_rel.max_fun_diff (s +o t) (case_sum f1 g1) (case_sum f2 g2) = Inr x\"\n    \"case_sum f1 g1 \\<noteq> case_sum f2 g2\"\n    \"case_sum f1 g1 \\<in> FinFunc r (s +o t)\" \"case_sum f2 g2 \\<in> FinFunc r (s +o t)\"\n  shows \"wo_rel.max_fun_diff t g1 g2 = x\" (is ?P) \"g1 \\<noteq> g2\" (is ?Q)\nproof -\n  interpret st: wo_rel \"s +o t\" by unfold_locales (rule osum_Well_order[OF s t])\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret rst: wo_rel2 r \"s +o t\" by unfold_locales (rule r, rule osum_Well_order[OF s t])\n  from assms(1) have *: \"st.isMaxim {a \\<in> Field (s +o t). case_sum f1 g1 a \\<noteq> case_sum f2 g2 a} (Inr x)\"\n    using rst.isMaxim_max_fun_diff[OF assms(2-4)] by simp\n  hence \"t.isMaxim {a \\<in> Field t. g1 a \\<noteq> g2 a} x\"\n    unfolding st.isMaxim_def t.isMaxim_def Field_osum by (auto simp: osum_def)\n  thus ?P ?Q unfolding t.max_fun_diff_def fun_eq_iff\n    by (auto intro: t.maxim_equality simp: t.isMaxim_def)\nqed\n\nlemma oexp_osum: \"r ^o (s +o t) =o (r ^o s) *o (r ^o t)\" (is \"?R =o ?L\")\nproof (rule ordIso_symmetric)\n  interpret rst: wo_rel2 r \"s +o t\" by unfold_locales (rule r, rule osum_Well_order[OF s t])\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rt: wo_rel2 r t by unfold_locales (rule r, rule t)\n  let ?f = \"\\<lambda>(f, g). case_sum f g\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\"\n  unfolding bij_betw_def rst.Field_oexp rs.Field_oexp rt.Field_oexp Field_oprod proof (intro conjI)\n    show \"inj_on ?f (FinFunc r s \\<times> FinFunc r t)\" unfolding inj_on_def\n      by (auto simp: fun_eq_iff split: sum.splits)\n    show \"?f ` (FinFunc r s \\<times> FinFunc r t) = FinFunc r (s +o t)\"\n    proof safe\n      fix fg assume \"fg \\<in> FinFunc r (s +o t)\"\n      thus \"fg \\<in> ?f ` (FinFunc r s \\<times> FinFunc r t)\"\n        by (intro image_eqI[of _ _ \"(fg o Inl, fg o Inr)\"])\n          (auto simp: FinFunc_osum fun_eq_iff split: sum.splits)\n    qed (auto simp: FinFunc_osum o_def)\n  qed\n  moreover have \"compat ?L ?R ?f\"\n    unfolding compat_def rst.Field_oexp rs.Field_oexp rt.Field_oexp oprod_def\n    unfolding rst.oexp_def Let_def rs.oexp_def rt.oexp_def\n      by (fastforce simp: Field_osum FinFunc_osum o_def split: sum.splits\n        dest: max_fun_diff_eq_Inl max_fun_diff_eq_Inr)\n  ultimately have \"iso ?L ?R ?f\" using r s t\n    by (subst iso_iff3) (auto intro: oexp_Well_order oprod_Well_order osum_Well_order)\n  thus \"?L =o ?R\" using r s t unfolding ordIso_def\n    by (auto intro: oexp_Well_order oprod_Well_order osum_Well_order)\nqed\n\ndefinition \"rev_curr f b = (if b \\<in> Field t then \\<lambda>a. f (a, b) else undefined)\"\n\nlemma rev_curr_FinFunc:\n  assumes Field: \"Field r \\<noteq> {}\"\n  shows \"rev_curr ` (FinFunc r (s *o t)) = FinFunc (r ^o s) t\"\nproof safe\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  fix g assume g: \"g \\<in> FinFunc r (s *o t)\"\n  hence \"finite (rst.SUPP (rev_curr g))\" \"\\<forall>x \\<in> Field t. finite (rs.SUPP (rev_curr g x))\"\n    unfolding FinFunc_def Field_oprod rs.Field_oexp Func_def fin_support_def support_def\n      rs.zero_oexp[OF Field] rev_curr_def by (auto simp: fun_eq_iff rs.const_def elim!: finite_surj)\n  with g show \"rev_curr g \\<in> FinFunc (r ^o s) t\"\n    unfolding FinFunc_def Field_oprod rs.Field_oexp Func_def\n    by (auto simp: rev_curr_def fin_support_def)\nnext\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  fix fg assume *: \"fg \\<in> FinFunc (r ^o s) t\"\n  let ?g = \"\\<lambda>(a, b). if (a, b) \\<in> Field (s *o t) then fg b a else undefined\"\n  show \"fg \\<in> rev_curr ` FinFunc r (s *o t)\"\n  proof (rule image_eqI[of _ _ ?g])\n    show \"fg = rev_curr ?g\"\n    proof\n      fix x\n      from * show \"fg x = rev_curr ?g x\"\n        unfolding FinFunc_def rs.Field_oexp Func_def rev_curr_def Field_oprod by auto\n    qed\n  next\n    have **: \"(\\<Union>g \\<in> fg ` Field t. rs.SUPP g) =\n              (\\<Union>g \\<in> fg ` Field t - {rs.const}. rs.SUPP g)\"\n      unfolding support_def by auto\n    from * have ***: \"\\<forall>g \\<in> fg ` Field t. finite (rs.SUPP g)\" \"finite (rst.SUPP fg)\"\n      unfolding rs.Field_oexp FinFunc_def Func_def fin_support_def Option.these_def by force+\n    hence \"finite (fg ` Field t - {rs.const})\" using *\n      unfolding support_def rs.zero_oexp[OF Field] FinFunc_def Func_def\n      by (elim finite_surj[of _ _ fg]) (fastforce simp: image_iff Option.these_def)\n    with *** have \"finite ((\\<Union>g \\<in> fg ` Field t. rs.SUPP g) \\<times> rst.SUPP fg)\"\n      by (subst **) (auto intro!: finite_cartesian_product)\n    with * show \"?g \\<in> FinFunc r (s *o t)\"\n      unfolding Field_oprod rs.Field_oexp FinFunc_def Func_def fin_support_def Option.these_def\n        support_def rs.zero_oexp[OF Field] by (auto elim!: finite_subset[rotated])\n  qed\nqed\n\nlemma rev_curr_app_FinFunc[elim!]:\n  \"\\<lbrakk>f \\<in> FinFunc r (s *o t); z \\<in> Field t\\<rbrakk> \\<Longrightarrow> rev_curr f z \\<in> FinFunc r s\"\n  unfolding rev_curr_def FinFunc_def Func_def Field_oprod fin_support_def support_def\n  by (auto elim: finite_surj)\n\nlemma max_fun_diff_oprod:\n  assumes Field: \"Field r \\<noteq> {}\" and \"f \\<noteq> g\" \"f \\<in> FinFunc r (s *o t)\" \"g \\<in> FinFunc r (s *o t)\"\n  defines \"m \\<equiv> wo_rel.max_fun_diff t (rev_curr f) (rev_curr g)\"\n  shows \"wo_rel.max_fun_diff (s *o t) f g =\n    (wo_rel.max_fun_diff s (rev_curr f m) (rev_curr g m), m)\"\nproof -\n  interpret st: wo_rel \"s *o t\" by unfold_locales (rule oprod_Well_order[OF s t])\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret r_st: wo_rel2 r \"s *o t\" by unfold_locales (rule r, rule oprod_Well_order[OF s t])\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  from fun_unequal_in_support[OF assms(2), of \"Field (s *o t)\" \"Field r\" \"Field r\"] assms(3,4)\n    have diff1: \"rev_curr f \\<noteq> rev_curr g\"\n      \"rev_curr f \\<in> FinFunc (r ^o s) t\" \"rev_curr g \\<in> FinFunc (r ^o s) t\" using rev_curr_FinFunc[OF Field]\n    unfolding fun_eq_iff rev_curr_def[abs_def] FinFunc_def support_def Field_oprod\n    by auto fast\n  hence diff2: \"rev_curr f m \\<noteq> rev_curr g m\" \"rev_curr f m \\<in> FinFunc r s\" \"rev_curr g m \\<in> FinFunc r s\"\n    using rst.max_fun_diff[OF diff1] assms(3,4) rst.max_fun_diff_in unfolding m_def by auto\n  show ?thesis unfolding st.max_fun_diff_def\n  proof (intro st.maxim_equality, unfold st.isMaxim_def Field_oprod, safe)\n    show \"s.max_fun_diff (rev_curr f m) (rev_curr g m) \\<in> Field s\"\n      using rs.max_fun_diff_in[OF diff2] by auto\n  next\n    show \"m \\<in> Field t\" using rst.max_fun_diff_in[OF diff1] unfolding m_def by auto\n  next\n    assume \"f (s.max_fun_diff (rev_curr f m) (rev_curr g m), m) =\n            g (s.max_fun_diff (rev_curr f m) (rev_curr g m), m)\"\n           (is \"f (?x, m) = g (?x, m)\")\n    hence \"rev_curr f m ?x = rev_curr g m ?x\" unfolding rev_curr_def by auto\n    with rs.max_fun_diff[OF diff2] show False by auto\n  next\n    fix x y assume \"f (x, y) \\<noteq> g (x, y)\" \"x \\<in> Field s\" \"y \\<in> Field t\"\n    thus \"((x, y), (s.max_fun_diff (rev_curr f m) (rev_curr g m), m)) \\<in> s *o t\"\n      using rst.max_fun_diff_in[OF diff1] rs.max_fun_diff_in[OF diff2] diff1 diff2\n        rst.max_fun_diff_max[OF diff1, of y] rs.max_fun_diff_le_eq[OF _ diff2, of x]\n      unfolding oprod_def m_def rev_curr_def fun_eq_iff by (auto intro: s.in_notinI)\n  qed\nqed\n\nlemma oexp_oexp: \"(r ^o s) ^o t =o r ^o (s *o t)\" (is \"?R =o ?L\")\nproof (cases \"r = {}\")\n  case True\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  show ?thesis\n  proof (cases \"s = {} \\<or> t = {}\")\n    case True with \\<open>r = {}\\<close> show ?thesis\n      by (auto simp: oexp_empty[OF oexp_Well_order[OF Well_order_empty s]]\n        intro!: ordIso_transitive[OF ordIso_symmetric[OF oone_ordIso] oone_ordIso]\n          ordIso_transitive[OF oone_ordIso_oexp[OF ordIso_symmetric[OF oone_ordIso] t] oone_ordIso])\n  next\n     case False\n     hence \"s *o t \\<noteq> {}\" unfolding oprod_def Field_def by fastforce\n     with False show ?thesis\n       using \\<open>r = {}\\<close> ozero_ordIso\n       by (auto simp add: s t oprod_Well_order ozero_def)\n  qed\nnext\n  case False\n  hence Field: \"Field r \\<noteq> {}\" by (metis Field_def Range_empty_iff Un_empty)\n  show ?thesis\n  proof (rule ordIso_symmetric)\n    interpret r_st: wo_rel2 r \"s *o t\" by unfold_locales (rule r, rule oprod_Well_order[OF s t])\n    interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n    interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n    have bij: \"bij_betw rev_curr (Field ?L) (Field ?R)\"\n    unfolding bij_betw_def r_st.Field_oexp rst.Field_oexp Field_oprod proof (intro conjI)\n      show \"inj_on rev_curr (FinFunc r (s *o t))\"\n        unfolding inj_on_def FinFunc_def Func_def Field_oprod rs.Field_oexp rev_curr_def[abs_def]\n        by (auto simp: fun_eq_iff) metis\n      show \"rev_curr ` (FinFunc r (s *o t)) = FinFunc (r ^o s) t\" by (rule rev_curr_FinFunc[OF Field])\n    qed\n    moreover\n    have \"compat ?L ?R rev_curr\"\n    unfolding compat_def proof safe\n      fix fg1 fg2 assume fg: \"(fg1, fg2) \\<in> r ^o (s *o t)\"\n      show \"(rev_curr fg1, rev_curr fg2) \\<in> r ^o s ^o t\"\n      proof (cases \"fg1 = fg2\")\n        assume \"fg1 \\<noteq> fg2\"\n        with fg show ?thesis\n        using rst.max_fun_diff_in[of \"rev_curr fg1\" \"rev_curr fg2\"]\n          max_fun_diff_oprod[OF Field, of fg1 fg2]  rev_curr_FinFunc[OF Field, symmetric]\n        unfolding r_st.Field_oexp rs.Field_oexp rst.Field_oexp unfolding r_st.oexp_def rst.oexp_def\n        by (auto simp: rs.oexp_def Let_def) (auto simp: rev_curr_def[abs_def])\n      next\n        assume \"fg1 = fg2\"\n        with fg bij show ?thesis unfolding r_st.Field_oexp rs.Field_oexp rst.Field_oexp bij_betw_def\n          by (auto simp: r_st.oexp_def rst.oexp_def)\n      qed\n    qed\n    ultimately have \"iso ?L ?R rev_curr\" using r s t\n      by (subst iso_iff3) (auto intro: oexp_Well_order oprod_Well_order)\n    thus \"?L =o ?R\" using r s t unfolding ordIso_def\n      by (auto intro: oexp_Well_order oprod_Well_order)\n  qed\nqed\n\nend (* context with 3 wellorders *)\n\nend\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Cardinals/Ordinal_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.7951583458469317}}
{"text": "(*  Title:      HOL/Analysis/Linear_Algebra.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection \\<open>Elementary Linear Algebra on Euclidean Spaces\\<close>\n\ntheory Linear_Algebra\nimports\n  Euclidean_Space\n  \"HOL-Library.Infinite_Set\"\nbegin\n\nlemma linear_simps:\n  assumes \"bounded_linear f\"\n  shows\n    \"f (a + b) = f a + f b\"\n    \"f (a - b) = f a - f b\"\n    \"f 0 = 0\"\n    \"f (- a) = - f a\"\n    \"f (s *\\<^sub>R v) = s *\\<^sub>R (f v)\"\nproof -\n  interpret f: bounded_linear f by fact\n  show \"f (a + b) = f a + f b\" by (rule f.add)\n  show \"f (a - b) = f a - f b\" by (rule f.diff)\n  show \"f 0 = 0\" by (rule f.zero)\n  show \"f (- a) = - f a\" by (rule f.neg)\n  show \"f (s *\\<^sub>R v) = s *\\<^sub>R (f v)\" by (rule f.scale)\nqed\n\nlemma finite_Atleast_Atmost_nat[simp]: \"finite {f x |x. x \\<in> (UNIV::'a::finite set)}\"\n  using finite finite_image_set by blast\n\nlemma substdbasis_expansion_unique:\n  includes inner_syntax\n  assumes d: \"d \\<subseteq> Basis\"\n  shows \"(\\<Sum>i\\<in>d. f i *\\<^sub>R i) = (x::'a::euclidean_space) \\<longleftrightarrow>\n    (\\<forall>i\\<in>Basis. (i \\<in> d \\<longrightarrow> f i = x \\<bullet> i) \\<and> (i \\<notin> d \\<longrightarrow> x \\<bullet> i = 0))\"\nproof -\n  have *: \"\\<And>x a b P. x * (if P then a else b) = (if P then x * a else x * b)\"\n    by auto\n  have **: \"finite d\"\n    by (auto intro: finite_subset[OF assms])\n  have ***: \"\\<And>i. i \\<in> Basis \\<Longrightarrow> (\\<Sum>i\\<in>d. f i *\\<^sub>R i) \\<bullet> i = (\\<Sum>x\\<in>d. if x = i then f x else 0)\"\n    using d\n    by (auto intro!: sum.cong simp: inner_Basis inner_sum_left)\n  show ?thesis\n    unfolding euclidean_eq_iff[where 'a='a] by (auto simp: sum.delta[OF **] ***)\nqed\n\nlemma independent_substdbasis: \"d \\<subseteq> Basis \\<Longrightarrow> independent d\"\n  by (rule independent_mono[OF independent_Basis])\n\nlemma subset_translation_eq [simp]:\n    fixes a :: \"'a::real_vector\" shows \"(+) a ` s \\<subseteq> (+) a ` t \\<longleftrightarrow> s \\<subseteq> t\"\n  by auto\n\nlemma translate_inj_on:\n  fixes A :: \"'a::ab_group_add set\"\n  shows \"inj_on (\\<lambda>x. a + x) A\"\n  unfolding inj_on_def by auto\n\nlemma translation_assoc:\n  fixes a b :: \"'a::ab_group_add\"\n  shows \"(\\<lambda>x. b + x) ` ((\\<lambda>x. a + x) ` S) = (\\<lambda>x. (a + b) + x) ` S\"\n  by auto\n\nlemma translation_invert:\n  fixes a :: \"'a::ab_group_add\"\n  assumes \"(\\<lambda>x. a + x) ` A = (\\<lambda>x. a + x) ` B\"\n  shows \"A = B\"\n  using assms translation_assoc by fastforce\n\nlemma translation_galois:\n  fixes a :: \"'a::ab_group_add\"\n  shows \"T = ((\\<lambda>x. a + x) ` S) \\<longleftrightarrow> S = ((\\<lambda>x. (- a) + x) ` T)\"\n  by (metis add.right_inverse group_cancel.rule0 translation_invert translation_assoc)\n\nlemma translation_inverse_subset:\n  assumes \"((\\<lambda>x. - a + x) ` V) \\<le> (S :: 'n::ab_group_add set)\"\n  shows \"V \\<le> ((\\<lambda>x. a + x) ` S)\"\n  by (metis assms subset_image_iff translation_galois)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>More interesting properties of the norm\\<close>\n\nunbundle inner_syntax\n\ntext\\<open>Equality of vectors in terms of \\<^term>\\<open>(\\<bullet>)\\<close> products.\\<close>\n\nlemma linear_componentwise:\n  fixes f:: \"'a::euclidean_space \\<Rightarrow> 'b::real_inner\"\n  assumes lf: \"linear f\"\n  shows \"(f x) \\<bullet> j = (\\<Sum>i\\<in>Basis. (x\\<bullet>i) * (f i\\<bullet>j))\" (is \"?lhs = ?rhs\")\nproof -\n  interpret linear f by fact\n  have \"?rhs = (\\<Sum>i\\<in>Basis. (x\\<bullet>i) *\\<^sub>R (f i))\\<bullet>j\"\n    by (simp add: inner_sum_left)\n  then show ?thesis\n    by (simp add: euclidean_representation sum[symmetric] scale[symmetric])\nqed\n\nlemma vector_eq: \"x = y \\<longleftrightarrow> x \\<bullet> x = x \\<bullet> y \\<and> y \\<bullet> y = x \\<bullet> x\"\n  by (metis (no_types, opaque_lifting) inner_commute inner_diff_right inner_eq_zero_iff right_minus_eq)\n\nlemma norm_triangle_half_r:\n  \"norm (y - x1) < e/2 \\<Longrightarrow> norm (y - x2) < e/2 \\<Longrightarrow> norm (x1 - x2) < e\"\n  using dist_triangle_half_r unfolding dist_norm[symmetric] by auto\n\nlemma norm_triangle_half_l:\n  assumes \"norm (x - y) < e/2\" and \"norm (x' - y) < e/2\"\n  shows \"norm (x - x') < e\"\n  by (metis assms dist_norm dist_triangle_half_l)\n\nlemma abs_triangle_half_r:\n  fixes y :: \"'a::linordered_field\"\n  shows \"abs (y - x1) < e/2 \\<Longrightarrow> abs (y - x2) < e/2 \\<Longrightarrow> abs (x1 - x2) < e\"\n  by linarith\n\nlemma abs_triangle_half_l:\n  fixes y :: \"'a::linordered_field\"\n  assumes \"abs (x - y) < e/2\" and \"abs (x' - y) < e/2\"\n  shows \"abs (x - x') < e\"\n  using assms by linarith\n\nlemma sum_clauses:\n  shows \"sum f {} = 0\"\n    and \"finite S \\<Longrightarrow> sum f (insert x S) = (if x \\<in> S then sum f S else f x + sum f S)\"\n  by (auto simp add: insert_absorb)\n\nlemma vector_eq_ldot: \"(\\<forall>x. x \\<bullet> y = x \\<bullet> z) \\<longleftrightarrow> y = z\" and vector_eq_rdot: \"(\\<forall>z. x \\<bullet> z = y \\<bullet> z) \\<longleftrightarrow> x = y\"\n  by (metis inner_commute vector_eq)+\n\nsubsection \\<open>Substandard Basis\\<close>\n\nlemma ex_card:\n  assumes \"n \\<le> card A\"\n  shows \"\\<exists>S\\<subseteq>A. card S = n\"\n  by (meson assms obtain_subset_with_card_n)\n\nlemma subspace_substandard: \"subspace {x::'a::euclidean_space. (\\<forall>i\\<in>Basis. P i \\<longrightarrow> x\\<bullet>i = 0)}\"\n  by (auto simp: subspace_def inner_add_left)\n\nlemma dim_substandard:\n  assumes d: \"d \\<subseteq> Basis\"\n  shows \"dim {x::'a::euclidean_space. \\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x\\<bullet>i = 0} = card d\" (is \"dim ?A = _\")\nproof (rule dim_unique)\n  from d show \"d \\<subseteq> ?A\"\n    by (auto simp: inner_Basis)\n  from d show \"independent d\"\n    by (rule independent_mono [OF independent_Basis])\n  have \"x \\<in> span d\" if \"\\<forall>i\\<in>Basis. i \\<notin> d \\<longrightarrow> x \\<bullet> i = 0\" for x\n  proof -\n    have \"finite d\"\n      by (rule finite_subset [OF d finite_Basis])\n    then have \"(\\<Sum>i\\<in>d. (x \\<bullet> i) *\\<^sub>R i) \\<in> span d\"\n      by (simp add: span_sum span_clauses)\n    also have \"(\\<Sum>i\\<in>d. (x \\<bullet> i) *\\<^sub>R i) = (\\<Sum>i\\<in>Basis. (x \\<bullet> i) *\\<^sub>R i)\"\n      by (rule sum.mono_neutral_cong_left [OF finite_Basis d]) (auto simp: that)\n    finally show \"x \\<in> span d\"\n      by (simp only: euclidean_representation)\n  qed\n  then show \"?A \\<subseteq> span d\" by auto\nqed simp\n\n\nsubsection \\<open>Orthogonality\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> (in real_inner) \"orthogonal x y \\<longleftrightarrow> x \\<bullet> y = 0\"\n\ncontext real_inner\nbegin\n\nlemma orthogonal_self: \"orthogonal x x \\<longleftrightarrow> x = 0\"\n  by (simp add: orthogonal_def)\n\nlemma orthogonal_clauses:\n  \"orthogonal a 0\"\n  \"orthogonal a x \\<Longrightarrow> orthogonal a (c *\\<^sub>R x)\"\n  \"orthogonal a x \\<Longrightarrow> orthogonal a (- x)\"\n  \"orthogonal a x \\<Longrightarrow> orthogonal a y \\<Longrightarrow> orthogonal a (x + y)\"\n  \"orthogonal a x \\<Longrightarrow> orthogonal a y \\<Longrightarrow> orthogonal a (x - y)\"\n  \"orthogonal 0 a\"\n  \"orthogonal x a \\<Longrightarrow> orthogonal (c *\\<^sub>R x) a\"\n  \"orthogonal x a \\<Longrightarrow> orthogonal (- x) a\"\n  \"orthogonal x a \\<Longrightarrow> orthogonal y a \\<Longrightarrow> orthogonal (x + y) a\"\n  \"orthogonal x a \\<Longrightarrow> orthogonal y a \\<Longrightarrow> orthogonal (x - y) a\"\n  unfolding orthogonal_def inner_add inner_diff by auto\n\nend\n\nlemma orthogonal_commute: \"orthogonal x y \\<longleftrightarrow> orthogonal y x\"\n  by (simp add: orthogonal_def inner_commute)\n\nlemma orthogonal_scaleR [simp]: \"c \\<noteq> 0 \\<Longrightarrow> orthogonal (c *\\<^sub>R x) = orthogonal x\"\n  by (rule ext) (simp add: orthogonal_def)\n\nlemma pairwise_ortho_scaleR:\n    \"pairwise (\\<lambda>i j. orthogonal (f i) (g j)) B\n    \\<Longrightarrow> pairwise (\\<lambda>i j. orthogonal (a i *\\<^sub>R f i) (a j *\\<^sub>R g j)) B\"\n  by (auto simp: pairwise_def orthogonal_clauses)\n\nlemma orthogonal_rvsum:\n    \"\\<lbrakk>finite s; \\<And>y. y \\<in> s \\<Longrightarrow> orthogonal x (f y)\\<rbrakk> \\<Longrightarrow> orthogonal x (sum f s)\"\n  by (induction s rule: finite_induct) (auto simp: orthogonal_clauses)\n\nlemma orthogonal_lvsum:\n    \"\\<lbrakk>finite s; \\<And>x. x \\<in> s \\<Longrightarrow> orthogonal (f x) y\\<rbrakk> \\<Longrightarrow> orthogonal (sum f s) y\"\n  by (induction s rule: finite_induct) (auto simp: orthogonal_clauses)\n\nlemma norm_add_Pythagorean:\n  assumes \"orthogonal a b\"\n    shows \"(norm (a + b))\\<^sup>2 = (norm a)\\<^sup>2 + (norm b)\\<^sup>2\"\nproof -\n  from assms have \"(a - (0 - b)) \\<bullet> (a - (0 - b)) = a \\<bullet> a - (0 - b \\<bullet> b)\"\n    by (simp add: algebra_simps orthogonal_def inner_commute)\n  then show ?thesis\n    by (simp add: power2_norm_eq_inner)\nqed\n\nlemma norm_sum_Pythagorean:\n  assumes \"finite I\" \"pairwise (\\<lambda>i j. orthogonal (f i) (f j)) I\"\n    shows \"(norm (sum f I))\\<^sup>2 = (\\<Sum>i\\<in>I. (norm (f i))\\<^sup>2)\"\nusing assms\nproof (induction I rule: finite_induct)\n  case empty then show ?case by simp\nnext\n  case (insert x I)\n  then have \"orthogonal (f x) (sum f I)\"\n    by (metis pairwise_insert orthogonal_rvsum)\n  with insert show ?case\n    by (simp add: pairwise_insert norm_add_Pythagorean)\nqed\n\n\nsubsection  \\<open>Orthogonality of a transformation\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>  \"orthogonal_transformation f \\<longleftrightarrow> linear f \\<and> (\\<forall>v w. f v \\<bullet> f w = v \\<bullet> w)\"\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation:\n  \"orthogonal_transformation f \\<longleftrightarrow> linear f \\<and> (\\<forall>v. norm (f v) = norm v)\"\n  by (smt (verit, ccfv_threshold) dot_norm linear_add norm_eq_sqrt_inner orthogonal_transformation_def)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_id [simp]: \"orthogonal_transformation (\\<lambda>x. x)\"\n  by (simp add: linear_iff orthogonal_transformation_def)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_orthogonal_transformation:\n    \"orthogonal_transformation f \\<Longrightarrow> orthogonal (f x) (f y) \\<longleftrightarrow> orthogonal x y\"\n  by (simp add: orthogonal_def orthogonal_transformation_def)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_compose:\n   \"\\<lbrakk>orthogonal_transformation f; orthogonal_transformation g\\<rbrakk> \\<Longrightarrow> orthogonal_transformation(f \\<circ> g)\"\n  by (auto simp: orthogonal_transformation_def linear_compose)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_neg:\n  \"orthogonal_transformation(\\<lambda>x. -(f x)) \\<longleftrightarrow> orthogonal_transformation f\"\n  by (auto simp: orthogonal_transformation_def dest: linear_compose_neg)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_scaleR: \"orthogonal_transformation f \\<Longrightarrow> f (c *\\<^sub>R v) = c *\\<^sub>R f v\"\n  by (simp add: linear_iff orthogonal_transformation_def)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_linear:\n   \"orthogonal_transformation f \\<Longrightarrow> linear f\"\n  by (simp add: orthogonal_transformation_def)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_inj:\n  \"orthogonal_transformation f \\<Longrightarrow> inj f\"\n  unfolding orthogonal_transformation_def inj_on_def\n  by (metis vector_eq)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_surj:\n  \"orthogonal_transformation f \\<Longrightarrow> surj f\"\n  for f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  by (simp add: linear_injective_imp_surjective orthogonal_transformation_inj orthogonal_transformation_linear)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_bij:\n  \"orthogonal_transformation f \\<Longrightarrow> bij f\"\n  for f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  by (simp add: bij_def orthogonal_transformation_inj orthogonal_transformation_surj)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_inv:\n  \"orthogonal_transformation f \\<Longrightarrow> orthogonal_transformation (inv f)\"\n  for f :: \"'a::euclidean_space \\<Rightarrow> 'a::euclidean_space\"\n  by (metis (no_types, opaque_lifting) bijection.inv_right bijection_def inj_linear_imp_inv_linear orthogonal_transformation orthogonal_transformation_bij orthogonal_transformation_inj)\n\nlemma\\<^marker>\\<open>tag unimportant\\<close>  orthogonal_transformation_norm:\n  \"orthogonal_transformation f \\<Longrightarrow> norm (f x) = norm x\"\n  by (metis orthogonal_transformation)\n\n\nsubsection \\<open>Bilinear functions\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close>\nbilinear :: \"('a::real_vector \\<Rightarrow> 'b::real_vector \\<Rightarrow> 'c::real_vector) \\<Rightarrow> bool\" where\n\"bilinear f \\<longleftrightarrow> (\\<forall>x. linear (\\<lambda>y. f x y)) \\<and> (\\<forall>y. linear (\\<lambda>x. f x y))\"\n\nlemma bilinear_ladd: \"bilinear h \\<Longrightarrow> h (x + y) z = h x z + h y z\"\n  by (simp add: bilinear_def linear_iff)\n\nlemma bilinear_radd: \"bilinear h \\<Longrightarrow> h x (y + z) = h x y + h x z\"\n  by (simp add: bilinear_def linear_iff)\n\nlemma bilinear_times:\n  fixes c::\"'a::real_algebra\" shows \"bilinear (\\<lambda>x y::'a. x*y)\"\n  by (auto simp: bilinear_def distrib_left distrib_right intro!: linearI)\n\nlemma bilinear_lmul: \"bilinear h \\<Longrightarrow> h (c *\\<^sub>R x) y = c *\\<^sub>R h x y\"\n  by (simp add: bilinear_def linear_iff)\n\nlemma bilinear_rmul: \"bilinear h \\<Longrightarrow> h x (c *\\<^sub>R y) = c *\\<^sub>R h x y\"\n  by (simp add: bilinear_def linear_iff)\n\nlemma bilinear_lneg: \"bilinear h \\<Longrightarrow> h (- x) y = - h x y\"\n  by (drule bilinear_lmul [of _ \"- 1\"]) simp\n\nlemma bilinear_rneg: \"bilinear h \\<Longrightarrow> h x (- y) = - h x y\"\n  by (drule bilinear_rmul [of _ _ \"- 1\"]) simp\n\nlemma (in ab_group_add) eq_add_iff: \"x = x + y \\<longleftrightarrow> y = 0\"\n  using add_left_imp_eq[of x y 0] by auto\n\nlemma bilinear_lzero:\n  assumes \"bilinear h\"\n  shows \"h 0 x = 0\"\n  using bilinear_ladd [OF assms, of 0 0 x] by (simp add: eq_add_iff field_simps)\n\nlemma bilinear_rzero:\n  assumes \"bilinear h\"\n  shows \"h x 0 = 0\"\n  using bilinear_radd [OF assms, of x 0 0 ] by (simp add: eq_add_iff field_simps)\n\nlemma bilinear_lsub: \"bilinear h \\<Longrightarrow> h (x - y) z = h x z - h y z\"\n  using bilinear_ladd [of h x \"- y\"] by (simp add: bilinear_lneg)\n\nlemma bilinear_rsub: \"bilinear h \\<Longrightarrow> h z (x - y) = h z x - h z y\"\n  using bilinear_radd [of h _ x \"- y\"] by (simp add: bilinear_rneg)\n\nlemma bilinear_sum:\n  assumes \"bilinear h\"\n  shows \"h (sum f S) (sum g T) = sum (\\<lambda>(i,j). h (f i) (g j)) (S \\<times> T) \"\nproof -\n  interpret l: linear \"\\<lambda>x. h x y\" for y using assms by (simp add: bilinear_def)\n  interpret r: linear \"\\<lambda>y. h x y\" for x using assms by (simp add: bilinear_def)\n  have \"h (sum f S) (sum g T) = sum (\\<lambda>x. h (f x) (sum g T)) S\"\n    by (simp add: l.sum)\n  also have \"\\<dots> = sum (\\<lambda>x. sum (\\<lambda>y. h (f x) (g y)) T) S\"\n    by (rule sum.cong) (simp_all add: r.sum)\n  finally show ?thesis\n    unfolding sum.cartesian_product .\nqed\n\n\nsubsection \\<open>Adjoints\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> adjoint :: \"(('a::real_inner) \\<Rightarrow> ('b::real_inner)) \\<Rightarrow> 'b \\<Rightarrow> 'a\" where\n\"adjoint f = (SOME f'. \\<forall>x y. f x \\<bullet> y = x \\<bullet> f' y)\"\n\nlemma adjoint_unique:\n  assumes \"\\<forall>x y. inner (f x) y = inner x (g y)\"\n  shows \"adjoint f = g\"\n  unfolding adjoint_def\nproof (rule some_equality)\n  show \"\\<forall>x y. inner (f x) y = inner x (g y)\"\n    by (rule assms)\nnext\n  fix h\n  assume \"\\<forall>x y. inner (f x) y = inner x (h y)\"\n  then show \"h = g\"\n    by (metis assms ext vector_eq_ldot) \nqed\n\ntext \\<open>TODO: The following lemmas about adjoints should hold for any\n  Hilbert space (i.e. complete inner product space).\n  (see \\<^url>\\<open>https://en.wikipedia.org/wiki/Hermitian_adjoint\\<close>)\n\\<close>\n\nlemma adjoint_works:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'm::euclidean_space\"\n  assumes lf: \"linear f\"\n  shows \"x \\<bullet> adjoint f y = f x \\<bullet> y\"\nproof -\n  interpret linear f by fact\n  have \"\\<forall>y. \\<exists>w. \\<forall>x. f x \\<bullet> y = x \\<bullet> w\"\n  proof (intro allI exI)\n    fix y :: \"'m\" and x\n    let ?w = \"(\\<Sum>i\\<in>Basis. (f i \\<bullet> y) *\\<^sub>R i) :: 'n\"\n    have \"f x \\<bullet> y = f (\\<Sum>i\\<in>Basis. (x \\<bullet> i) *\\<^sub>R i) \\<bullet> y\"\n      by (simp add: euclidean_representation)\n    also have \"\\<dots> = (\\<Sum>i\\<in>Basis. (x \\<bullet> i) *\\<^sub>R f i) \\<bullet> y\"\n      by (simp add: sum scale)\n    finally show \"f x \\<bullet> y = x \\<bullet> ?w\"\n      by (simp add: inner_sum_left inner_sum_right mult.commute)\n  qed\n  then show ?thesis\n    unfolding adjoint_def choice_iff\n    by (intro someI2_ex[where Q=\"\\<lambda>f'. x \\<bullet> f' y = f x \\<bullet> y\"]) auto\nqed\n\nlemma adjoint_clauses:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'm::euclidean_space\"\n  assumes lf: \"linear f\"\n  shows \"x \\<bullet> adjoint f y = f x \\<bullet> y\"\n    and \"adjoint f y \\<bullet> x = y \\<bullet> f x\"\n  by (simp_all add: adjoint_works[OF lf] inner_commute)\n\nlemma adjoint_linear:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'm::euclidean_space\"\n  assumes lf: \"linear f\"\n  shows \"linear (adjoint f)\"\n  by (simp add: lf linear_iff euclidean_eq_iff[where 'a='n] euclidean_eq_iff[where 'a='m]\n    adjoint_clauses[OF lf] inner_distrib)\n\nlemma adjoint_adjoint:\n  fixes f :: \"'n::euclidean_space \\<Rightarrow> 'm::euclidean_space\"\n  assumes lf: \"linear f\"\n  shows \"adjoint (adjoint f) = f\"\n  by (rule adjoint_unique, simp add: adjoint_clauses [OF lf])\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Euclidean Spaces as Typeclass\\<close>\n\nlemma independent_Basis: \"independent Basis\"\n  by (rule independent_Basis)\n\nlemma span_Basis [simp]: \"span Basis = UNIV\"\n  by (rule span_Basis)\n\nlemma in_span_Basis: \"x \\<in> span Basis\"\n  unfolding span_Basis ..\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Linearity and Bilinearity continued\\<close>\n\nlemma linear_bounded:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes lf: \"linear f\"\n  shows \"\\<exists>B. \\<forall>x. norm (f x) \\<le> B * norm x\"\nproof\n  interpret linear f by fact\n  let ?B = \"\\<Sum>b\\<in>Basis. norm (f b)\"\n  show \"\\<forall>x. norm (f x) \\<le> ?B * norm x\"\n  proof\n    fix x :: 'a\n    let ?g = \"\\<lambda>b. (x \\<bullet> b) *\\<^sub>R f b\"\n    have \"norm (f x) = norm (f (\\<Sum>b\\<in>Basis. (x \\<bullet> b) *\\<^sub>R b))\"\n      unfolding euclidean_representation ..\n    also have \"\\<dots> = norm (sum ?g Basis)\"\n      by (simp add: sum scale)\n    finally have th0: \"norm (f x) = norm (sum ?g Basis)\" .\n    have th: \"norm (?g i) \\<le> norm (f i) * norm x\" if \"i \\<in> Basis\" for i\n    proof -\n      from Basis_le_norm[OF that, of x]\n      show \"norm (?g i) \\<le> norm (f i) * norm x\"\n        unfolding norm_scaleR by (metis mult.commute mult_left_mono norm_ge_zero)\n    qed\n    from sum_norm_le[of _ ?g, OF th]\n    show \"norm (f x) \\<le> ?B * norm x\"\n      by (simp add: sum_distrib_right th0)\n  qed\nqed\n\nlemma linear_conv_bounded_linear:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"linear f \\<longleftrightarrow> bounded_linear f\"\n  by (metis mult.commute bounded_linear_axioms.intro bounded_linear_def linear_bounded)\n\nlemmas linear_linear = linear_conv_bounded_linear[symmetric]\n\nlemma inj_linear_imp_inv_bounded_linear:\n  fixes f::\"'a::euclidean_space \\<Rightarrow> 'a\"\n  shows \"\\<lbrakk>bounded_linear f; inj f\\<rbrakk> \\<Longrightarrow> bounded_linear (inv f)\"\n  by (simp add: inj_linear_imp_inv_linear linear_linear)\n\nlemma linear_bounded_pos:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes lf: \"linear f\"\n obtains B where \"B > 0\" \"\\<And>x. norm (f x) \\<le> B * norm x\"\n  by (metis bounded_linear.pos_bounded lf linear_linear mult.commute)\n\nlemma linear_invertible_bounded_below_pos:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"linear g\" and gf: \"g \\<circ> f = id\"\n  obtains B where \"B > 0\" \"\\<And>x. B * norm x \\<le> norm(f x)\"\nproof -\n  obtain B where \"B > 0\" and B: \"\\<And>x. norm (g x) \\<le> B * norm x\"\n    using linear_bounded_pos [OF \\<open>linear g\\<close>] by blast\n  show thesis\n  proof\n    show \"0 < 1/B\"\n      by (simp add: \\<open>B > 0\\<close>)\n    show \"1/B * norm x \\<le> norm (f x)\" for x\n      by (smt (verit, ccfv_SIG) B \\<open>0 < B\\<close> gf comp_apply divide_inverse id_apply inverse_eq_divide \n              less_divide_eq mult.commute)\n  qed\nqed\n\nlemma linear_inj_bounded_below_pos:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::euclidean_space\"\n  assumes \"linear f\" \"inj f\"\n  obtains B where \"B > 0\" \"\\<And>x. B * norm x \\<le> norm(f x)\"\n  using linear_injective_left_inverse [OF assms]\n    linear_invertible_bounded_below_pos assms by blast\n\nlemma bounded_linearI':\n  fixes f ::\"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>x y. f (x + y) = f x + f y\"\n    and \"\\<And>c x. f (c *\\<^sub>R x) = c *\\<^sub>R f x\"\n  shows \"bounded_linear f\"\n  using assms linearI linear_conv_bounded_linear by blast\n\nlemma bilinear_bounded:\n  fixes h :: \"'m::euclidean_space \\<Rightarrow> 'n::euclidean_space \\<Rightarrow> 'k::real_normed_vector\"\n  assumes bh: \"bilinear h\"\n  shows \"\\<exists>B. \\<forall>x y. norm (h x y) \\<le> B * norm x * norm y\"\nproof (clarify intro!: exI[of _ \"\\<Sum>i\\<in>Basis. \\<Sum>j\\<in>Basis. norm (h i j)\"])\n  fix x :: 'm\n  fix y :: 'n\n  have \"norm (h x y) = norm (h (sum (\\<lambda>i. (x \\<bullet> i) *\\<^sub>R i) Basis) (sum (\\<lambda>i. (y \\<bullet> i) *\\<^sub>R i) Basis))\"\n    by (simp add: euclidean_representation)\n  also have \"\\<dots> = norm (sum (\\<lambda> (i,j). h ((x \\<bullet> i) *\\<^sub>R i) ((y \\<bullet> j) *\\<^sub>R j)) (Basis \\<times> Basis))\"\n    unfolding bilinear_sum[OF bh] ..\n  finally have th: \"norm (h x y) = \\<dots>\" .\n  have \"\\<And>i j. \\<lbrakk>i \\<in> Basis; j \\<in> Basis\\<rbrakk>\n           \\<Longrightarrow> \\<bar>x \\<bullet> i\\<bar> * (\\<bar>y \\<bullet> j\\<bar> * norm (h i j)) \\<le> norm x * (norm y * norm (h i j))\"\n    by (auto simp add: zero_le_mult_iff Basis_le_norm mult_mono)\n  then show \"norm (h x y) \\<le> (\\<Sum>i\\<in>Basis. \\<Sum>j\\<in>Basis. norm (h i j)) * norm x * norm y\"\n    unfolding sum_distrib_right th sum.cartesian_product\n    by (clarsimp simp add: bilinear_rmul[OF bh] bilinear_lmul[OF bh]\n      field_simps simp del: scaleR_scaleR intro!: sum_norm_le)\nqed\n\nlemma bilinear_conv_bounded_bilinear:\n  fixes h :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space \\<Rightarrow> 'c::real_normed_vector\"\n  shows \"bilinear h \\<longleftrightarrow> bounded_bilinear h\"\nproof\n  assume \"bilinear h\"\n  show \"bounded_bilinear h\"\n  proof\n    fix x y z\n    show \"h (x + y) z = h x z + h y z\"\n      using \\<open>bilinear h\\<close> unfolding bilinear_def linear_iff by simp\n  next\n    fix x y z\n    show \"h x (y + z) = h x y + h x z\"\n      using \\<open>bilinear h\\<close> unfolding bilinear_def linear_iff by simp\n  next\n    show \"h (scaleR r x) y = scaleR r (h x y)\" \"h x (scaleR r y) = scaleR r (h x y)\" for r x y\n      using \\<open>bilinear h\\<close> unfolding bilinear_def linear_iff\n      by simp_all\n  next\n    have \"\\<exists>B. \\<forall>x y. norm (h x y) \\<le> B * norm x * norm y\"\n      using \\<open>bilinear h\\<close> by (rule bilinear_bounded)\n    then show \"\\<exists>K. \\<forall>x y. norm (h x y) \\<le> norm x * norm y * K\"\n      by (simp add: ac_simps)\n  qed\nnext\n  assume \"bounded_bilinear h\"\n  then interpret h: bounded_bilinear h .\n  show \"bilinear h\"\n    unfolding bilinear_def linear_conv_bounded_linear\n    using h.bounded_linear_left h.bounded_linear_right by simp\nqed\n\nlemma bilinear_bounded_pos:\n  fixes h :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space \\<Rightarrow> 'c::real_normed_vector\"\n  assumes bh: \"bilinear h\"\n  shows \"\\<exists>B > 0. \\<forall>x y. norm (h x y) \\<le> B * norm x * norm y\"\n  by (metis mult.assoc bh bilinear_conv_bounded_bilinear bounded_bilinear.pos_bounded mult.commute)\n\nlemma bounded_linear_imp_has_derivative: \n  \"bounded_linear f \\<Longrightarrow> (f has_derivative f) net\"\n  by (auto simp add: has_derivative_def linear_diff linear_linear linear_def\n      dest: bounded_linear.linear)\n\nlemma linear_imp_has_derivative:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"linear f \\<Longrightarrow> (f has_derivative f) net\"\n  by (simp add: bounded_linear_imp_has_derivative linear_conv_bounded_linear)\n\nlemma bounded_linear_imp_differentiable: \"bounded_linear f \\<Longrightarrow> f differentiable net\"\n  using bounded_linear_imp_has_derivative differentiable_def by blast\n\nlemma linear_imp_differentiable:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_normed_vector\"\n  shows \"linear f \\<Longrightarrow> f differentiable net\"\n  by (metis linear_imp_has_derivative differentiable_def)\n\nlemma of_real_differentiable [simp,derivative_intros]: \"of_real differentiable F\"\n  by (simp add: bounded_linear_imp_differentiable bounded_linear_of_real)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>We continue\\<close>\n\nlemma independent_bound:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"independent S \\<Longrightarrow> finite S \\<and> card S \\<le> DIM('a)\"\n  by (metis dim_subset_UNIV finiteI_independent dim_span_eq_card_independent)\n\nlemmas independent_imp_finite = finiteI_independent\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> independent_card_le:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"independent S\"\n  shows \"card S \\<le> DIM('a)\"\n  using assms independent_bound by auto\n\nlemma dependent_biggerset:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"(finite S \\<Longrightarrow> card S > DIM('a)) \\<Longrightarrow> dependent S\"\n  by (metis independent_bound not_less)\n\ntext \\<open>Picking an orthogonal replacement for a spanning set.\\<close>\n\nlemma vector_sub_project_orthogonal:\n  fixes b x :: \"'a::euclidean_space\"\n  shows \"b \\<bullet> (x - ((b \\<bullet> x) / (b \\<bullet> b)) *\\<^sub>R b) = 0\"\n  unfolding inner_simps by auto\n\nlemma pairwise_orthogonal_insert:\n  assumes \"pairwise orthogonal S\"\n    and \"\\<And>y. y \\<in> S \\<Longrightarrow> orthogonal x y\"\n  shows \"pairwise orthogonal (insert x S)\"\n  using assms by (auto simp: pairwise_def orthogonal_commute)\n\nlemma basis_orthogonal:\n  fixes B :: \"'a::real_inner set\"\n  assumes fB: \"finite B\"\n  shows \"\\<exists>C. finite C \\<and> card C \\<le> card B \\<and> span C = span B \\<and> pairwise orthogonal C\"\n  (is \" \\<exists>C. ?P B C\")\n  using fB\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case\n    using pairwise_empty by blast\nnext\n  case (insert a B)\n  note fB = \\<open>finite B\\<close> and aB = \\<open>a \\<notin> B\\<close>\n  from \\<open>\\<exists>C. finite C \\<and> card C \\<le> card B \\<and> span C = span B \\<and> pairwise orthogonal C\\<close>\n  obtain C where C: \"finite C\" \"card C \\<le> card B\"\n    \"span C = span B\" \"pairwise orthogonal C\" by blast\n  let ?a = \"a - sum (\\<lambda>x. (x \\<bullet> a / (x \\<bullet> x)) *\\<^sub>R x) C\"\n  let ?C = \"insert ?a C\"\n  from C(1) have fC: \"finite ?C\"\n    by simp\n  have cC: \"card ?C \\<le> card (insert a B)\"\n    using C aB card_insert_if local.insert(1) by fastforce\n  {\n    fix x k\n    have th0: \"\\<And>(a::'a) b c. a - (b - c) = c + (a - b)\"\n      by (simp add: field_simps)\n    have \"x - k *\\<^sub>R (a - (\\<Sum>x\\<in>C. (x \\<bullet> a / (x \\<bullet> x)) *\\<^sub>R x)) \\<in> span C \\<longleftrightarrow> x - k *\\<^sub>R a \\<in> span C\"\n      unfolding scaleR_right_diff_distrib th0\n      by (intro span_add_eq span_scale span_sum span_base)\n  }\n  then have SC: \"span ?C = span (insert a B)\"\n    unfolding set_eq_iff span_breakdown_eq C(3)[symmetric] by auto\n  {\n    fix y\n    assume yC: \"y \\<in> C\"\n    then have Cy: \"C = insert y (C - {y})\"\n      by blast\n    have fth: \"finite (C - {y})\"\n      using C by simp\n    have \"y \\<noteq> 0 \\<Longrightarrow> \\<forall>x\\<in>C - {y}. x \\<bullet> a * (x \\<bullet> y) / (x \\<bullet> x) = 0\"\n      using \\<open>pairwise orthogonal C\\<close>\n      by (metis Cy DiffE div_0 insertCI mult_zero_right orthogonal_def pairwise_insert)\n    then have \"orthogonal ?a y\"\n      unfolding orthogonal_def\n      unfolding inner_diff inner_sum_left right_minus_eq\n      unfolding sum.remove [OF \\<open>finite C\\<close> \\<open>y \\<in> C\\<close>]\n      by (auto simp add: sum.neutral inner_commute[of y a])\n  }\n  with \\<open>pairwise orthogonal C\\<close> have CPO: \"pairwise orthogonal ?C\"\n    by (rule pairwise_orthogonal_insert)\n  from fC cC SC CPO have \"?P (insert a B) ?C\"\n    by blast\n  then show ?case by blast\nqed\n\nlemma orthogonal_basis_exists:\n  fixes V :: \"('a::euclidean_space) set\"\n  shows \"\\<exists>B. independent B \\<and> B \\<subseteq> span V \\<and> V \\<subseteq> span B \\<and> (card B = dim V) \\<and> pairwise orthogonal B\"\nproof -\n  from basis_exists[of V] obtain B where\n    B: \"B \\<subseteq> V\" \"independent B\" \"V \\<subseteq> span B\" \"card B = dim V\"\n    by force\n  from B have fB: \"finite B\" \"card B = dim V\"\n    using independent_bound by auto\n  from basis_orthogonal[OF fB(1)] obtain C where\n    C: \"finite C\" \"card C \\<le> card B\" \"span C = span B\" \"pairwise orthogonal C\"\n    by blast\n  from C B have CSV: \"C \\<subseteq> span V\"\n    by (metis span_superset span_mono subset_trans)\n  from span_mono[OF B(3)] C have SVC: \"span V \\<subseteq> span C\"\n    by (simp add: span_span)\n  from C fB have \"card C \\<le> dim V\"\n    by simp\n  moreover have \"dim V \\<le> card C\"\n    using span_card_ge_dim[OF CSV SVC C(1)]\n    by simp\n  ultimately have \"card C = dim V\"\n    using C(1) by simp\n  with C B CSV show ?thesis\n    by (metis SVC card_eq_dim dim_span)\nqed\n\ntext \\<open>Low-dimensional subset is in a hyperplane (weak orthogonal complement).\\<close>\n\nlemma span_not_univ_orthogonal:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes sU: \"span S \\<noteq> UNIV\"\n  shows \"\\<exists>a::'a. a \\<noteq> 0 \\<and> (\\<forall>x \\<in> span S. a \\<bullet> x = 0)\"\nproof -\n  from sU obtain a where a: \"a \\<notin> span S\"\n    by blast\n  from orthogonal_basis_exists obtain B where\n    B: \"independent B\" \"B \\<subseteq> span S\" \"S \\<subseteq> span B\" \"card B = dim S\" \"pairwise orthogonal B\"\n    by blast\n  from B have fB: \"finite B\" \"card B = dim S\"\n    using independent_bound by auto\n  have sSB: \"span S = span B\"\n    by (simp add: B span_eq)\n  let ?a = \"a - sum (\\<lambda>b. (a \\<bullet> b / (b \\<bullet> b)) *\\<^sub>R b) B\"\n  have \"sum (\\<lambda>b. (a \\<bullet> b / (b \\<bullet> b)) *\\<^sub>R b) B \\<in> span S\"\n    by (simp add: sSB span_base span_mul span_sum)\n  with a have a0:\"?a  \\<noteq> 0\"\n    by auto\n  have \"?a \\<bullet> x = 0\" if \"x\\<in>span B\" for x\n  proof (rule span_induct [OF that])\n    show \"subspace {x. ?a \\<bullet> x = 0}\"\n      by (auto simp add: subspace_def inner_add)\n  next\n    {\n      fix x\n      assume x: \"x \\<in> B\"\n      from x have B': \"B = insert x (B - {x})\"\n        by blast\n      have fth: \"finite (B - {x})\"\n        using fB by simp\n      have \"(\\<Sum>b\\<in>B - {x}. a \\<bullet> b * (b \\<bullet> x) / (b \\<bullet> b)) = 0\" if \"x \\<noteq> 0\"\n        by (smt (verit) B' B(5) DiffD2 divide_eq_0_iff inner_real_def inner_zero_right insertCI orthogonal_def pairwise_insert sum.neutral)\n      then have \"?a \\<bullet> x = 0\"\n        apply (subst B')\n        using fB fth\n        unfolding sum_clauses(2)[OF fth]\n        by (auto simp add: inner_add_left inner_diff_left inner_sum_left)\n    }\n    then show \"?a \\<bullet> x = 0\" if \"x \\<in> B\" for x\n      using that by blast\n    qed\n  with a0 sSB show ?thesis\n    by blast\nqed\n\nlemma span_not_univ_subset_hyperplane:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes SU: \"span S \\<noteq> UNIV\"\n  shows \"\\<exists> a. a \\<noteq>0 \\<and> span S \\<subseteq> {x. a \\<bullet> x = 0}\"\n  using span_not_univ_orthogonal[OF SU] by auto\n\nlemma lowdim_subset_hyperplane:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes d: \"dim S < DIM('a)\"\n  shows \"\\<exists>a::'a. a \\<noteq> 0 \\<and> span S \\<subseteq> {x. a \\<bullet> x = 0}\"\n  using d dim_eq_full nless_le span_not_univ_subset_hyperplane by blast\n\nlemma linear_eq_stdbasis:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> _\"\n  assumes lf: \"linear f\"\n    and lg: \"linear g\"\n    and fg: \"\\<And>b. b \\<in> Basis \\<Longrightarrow> f b = g b\"\n  shows \"f = g\"\n  using linear_eq_on_span[OF lf lg, of Basis] fg by auto\n\n\ntext \\<open>Similar results for bilinear functions.\\<close>\n\nlemma bilinear_eq:\n  assumes bf: \"bilinear f\"\n    and bg: \"bilinear g\"\n    and SB: \"S \\<subseteq> span B\"\n    and TC: \"T \\<subseteq> span C\"\n    and \"x\\<in>S\" \"y\\<in>T\"\n    and fg: \"\\<And>x y. \\<lbrakk>x \\<in> B; y\\<in> C\\<rbrakk> \\<Longrightarrow> f x y = g x y\"\n  shows \"f x y = g x y\"\nproof -\n  let ?P = \"{x. \\<forall>y\\<in> span C. f x y = g x y}\"\n  from bf bg have sp: \"subspace ?P\"\n    unfolding bilinear_def linear_iff subspace_def bf bg\n    by (auto simp add: span_zero bilinear_lzero[OF bf] bilinear_lzero[OF bg]\n        span_add Ball_def\n      intro: bilinear_ladd[OF bf])\n  have sfg: \"\\<And>x. x \\<in> B \\<Longrightarrow> subspace {a. f x a = g x a}\"\n    by (auto simp: subspace_def bf bg bilinear_rzero bilinear_radd bilinear_rmul)\n  have \"\\<forall>y\\<in> span C. f x y = g x y\" if \"x \\<in> span B\" for x\n    using span_induct [OF that sp] fg sfg span_induct by blast\n  then show ?thesis\n    using SB TC assms by auto\nqed\n\nlemma bilinear_eq_stdbasis:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space \\<Rightarrow> _\"\n  assumes bf: \"bilinear f\"\n    and bg: \"bilinear g\"\n    and fg: \"\\<And>i j. i \\<in> Basis \\<Longrightarrow> j \\<in> Basis \\<Longrightarrow> f i j = g i j\"\n  shows \"f = g\"\n  using bilinear_eq[OF bf bg equalityD2[OF span_Basis] equalityD2[OF span_Basis]] fg by blast\n\n\nsubsection \\<open>Infinity norm\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"infnorm (x::'a::euclidean_space) = Sup {\\<bar>x \\<bullet> b\\<bar> |b. b \\<in> Basis}\"\n\nlemma infnorm_set_image:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"{\\<bar>x \\<bullet> i\\<bar> |i. i \\<in> Basis} = (\\<lambda>i. \\<bar>x \\<bullet> i\\<bar>) ` Basis\"\n  by blast\n\nlemma infnorm_Max:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"infnorm x = Max ((\\<lambda>i. \\<bar>x \\<bullet> i\\<bar>) ` Basis)\"\n  by (simp add: infnorm_def infnorm_set_image cSup_eq_Max)\n\nlemma infnorm_set_lemma:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"finite {\\<bar>x \\<bullet> i\\<bar> |i. i \\<in> Basis}\"\n    and \"{\\<bar>x \\<bullet> i\\<bar> |i. i \\<in> Basis} \\<noteq> {}\"\n  unfolding infnorm_set_image by auto\n\nlemma infnorm_pos_le:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"0 \\<le> infnorm x\"\n  by (simp add: infnorm_Max Max_ge_iff ex_in_conv)\n\nlemma infnorm_triangle:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"infnorm (x + y) \\<le> infnorm x + infnorm y\"\nproof -\n  have *: \"\\<And>a b c d :: real. \\<bar>a\\<bar> \\<le> c \\<Longrightarrow> \\<bar>b\\<bar> \\<le> d \\<Longrightarrow> \\<bar>a + b\\<bar> \\<le> c + d\"\n    by simp\n  show ?thesis\n    by (auto simp: infnorm_Max inner_add_left intro!: *)\nqed\n\nlemma infnorm_eq_0:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"infnorm x = 0 \\<longleftrightarrow> x = 0\"\nproof -\n  have \"infnorm x \\<le> 0 \\<longleftrightarrow> x = 0\"\n    unfolding infnorm_Max by (simp add: euclidean_all_zero_iff)\n  then show ?thesis\n    using infnorm_pos_le[of x] by simp\nqed\n\nlemma infnorm_0: \"infnorm 0 = 0\"\n  by (simp add: infnorm_eq_0)\n\nlemma infnorm_neg: \"infnorm (- x) = infnorm x\"\n  unfolding infnorm_def by simp\n\nlemma infnorm_sub: \"infnorm (x - y) = infnorm (y - x)\"\n  by (metis infnorm_neg minus_diff_eq)\n\nlemma absdiff_infnorm: \"\\<bar>infnorm x - infnorm y\\<bar> \\<le> infnorm (x - y)\"\n  by (smt (verit, del_insts) diff_add_cancel infnorm_sub infnorm_triangle)\n\nlemma real_abs_infnorm: \"\\<bar>infnorm x\\<bar> = infnorm x\"\n  using infnorm_pos_le[of x] by arith\n\nlemma Basis_le_infnorm:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"b \\<in> Basis \\<Longrightarrow> \\<bar>x \\<bullet> b\\<bar> \\<le> infnorm x\"\n  by (simp add: infnorm_Max)\n\nlemma infnorm_mul: \"infnorm (a *\\<^sub>R x) = \\<bar>a\\<bar> * infnorm x\"\n  unfolding infnorm_Max\nproof (safe intro!: Max_eqI)\n  let ?B = \"(\\<lambda>i. \\<bar>x \\<bullet> i\\<bar>) ` Basis\"\n  { fix b :: 'a\n    assume \"b \\<in> Basis\"\n    then show \"\\<bar>a *\\<^sub>R x \\<bullet> b\\<bar> \\<le> \\<bar>a\\<bar> * Max ?B\"\n      by (simp add: abs_mult mult_left_mono)\n  next\n    from Max_in[of ?B] obtain b where \"b \\<in> Basis\" \"Max ?B = \\<bar>x \\<bullet> b\\<bar>\"\n      by (auto simp del: Max_in)\n    then show \"\\<bar>a\\<bar> * Max ((\\<lambda>i. \\<bar>x \\<bullet> i\\<bar>) ` Basis) \\<in> (\\<lambda>i. \\<bar>a *\\<^sub>R x \\<bullet> i\\<bar>) ` Basis\"\n      by (intro image_eqI[where x=b]) (auto simp: abs_mult)\n  }\nqed simp\n\nlemma infnorm_mul_lemma: \"infnorm (a *\\<^sub>R x) \\<le> \\<bar>a\\<bar> * infnorm x\"\n  unfolding infnorm_mul ..\n\nlemma infnorm_pos_lt: \"infnorm x > 0 \\<longleftrightarrow> x \\<noteq> 0\"\n  using infnorm_pos_le[of x] infnorm_eq_0[of x] by arith\n\ntext \\<open>Prove that it differs only up to a bound from Euclidean norm.\\<close>\n\nlemma infnorm_le_norm: \"infnorm x \\<le> norm x\"\n  by (simp add: Basis_le_norm infnorm_Max)\n\nlemma norm_le_infnorm:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"norm x \\<le> sqrt DIM('a) * infnorm x\"\n  unfolding norm_eq_sqrt_inner id_def\nproof (rule real_le_lsqrt[OF inner_ge_zero])\n  show \"sqrt DIM('a) * infnorm x \\<ge> 0\"\n    by (simp add: zero_le_mult_iff infnorm_pos_le)\n  have \"x \\<bullet> x \\<le> (\\<Sum>b\\<in>Basis. x \\<bullet> b * (x \\<bullet> b))\"\n    by (metis euclidean_inner order_refl)\n  also have \"\\<dots> \\<le> DIM('a) * \\<bar>infnorm x\\<bar>\\<^sup>2\"\n    by (rule sum_bounded_above) (metis Basis_le_infnorm abs_le_square_iff power2_eq_square real_abs_infnorm)\n  also have \"\\<dots> \\<le> (sqrt DIM('a) * infnorm x)\\<^sup>2\"\n    by (simp add: power_mult_distrib)\n  finally show \"x \\<bullet> x \\<le> (sqrt DIM('a) * infnorm x)\\<^sup>2\" .\nqed\n\nlemma tendsto_infnorm [tendsto_intros]:\n  assumes \"(f \\<longlongrightarrow> a) F\"\n  shows \"((\\<lambda>x. infnorm (f x)) \\<longlongrightarrow> infnorm a) F\"\nproof (rule tendsto_compose [OF LIM_I assms])\n  fix r :: real\n  assume \"r > 0\"\n  then show \"\\<exists>s>0. \\<forall>x. x \\<noteq> a \\<and> norm (x - a) < s \\<longrightarrow> norm (infnorm x - infnorm a) < r\"\n    by (metis real_norm_def le_less_trans absdiff_infnorm infnorm_le_norm)\nqed\n\ntext \\<open>Equality in Cauchy-Schwarz and triangle inequalities.\\<close>\n\nlemma norm_cauchy_schwarz_eq: \"x \\<bullet> y = norm x * norm y \\<longleftrightarrow> norm x *\\<^sub>R y = norm y *\\<^sub>R x\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"x=0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False \n  from inner_eq_zero_iff[of \"norm y *\\<^sub>R x - norm x *\\<^sub>R y\"]\n  have \"?rhs \\<longleftrightarrow>\n      (norm y * (norm y * norm x * norm x - norm x * (x \\<bullet> y)) -\n        norm x * (norm y * (y \\<bullet> x) - norm x * norm y * norm y) = 0)\"\n    using False unfolding inner_simps\n    by (auto simp add: power2_norm_eq_inner[symmetric] power2_eq_square inner_commute field_simps)\n  also have \"\\<dots> \\<longleftrightarrow> (2 * norm x * norm y * (norm x * norm y - x \\<bullet> y) = 0)\"\n    using False  by (simp add: field_simps inner_commute)\n  also have \"\\<dots> \\<longleftrightarrow> ?lhs\"\n    using False by auto\n  finally show ?thesis by metis\nqed\n\nlemma norm_cauchy_schwarz_abs_eq:\n  \"\\<bar>x \\<bullet> y\\<bar> = norm x * norm y \\<longleftrightarrow>\n    norm x *\\<^sub>R y = norm y *\\<^sub>R x \\<or> norm x *\\<^sub>R y = - norm y *\\<^sub>R x\"\n  using norm_cauchy_schwarz_eq [symmetric, of x y]\n  using norm_cauchy_schwarz_eq [symmetric, of \"-x\" y] Cauchy_Schwarz_ineq2 [of x y]\n  by auto\n\nlemma norm_triangle_eq:\n  fixes x y :: \"'a::real_inner\"\n  shows \"norm (x + y) = norm x + norm y \\<longleftrightarrow> norm x *\\<^sub>R y = norm y *\\<^sub>R x\"\nproof (cases \"x = 0 \\<or> y = 0\")\n  case True\n  then show ?thesis\n    by force\nnext\n  case False\n  then have n: \"norm x > 0\" \"norm y > 0\"\n    by auto\n  have \"norm (x + y) = norm x + norm y \\<longleftrightarrow> (norm (x + y))\\<^sup>2 = (norm x + norm y)\\<^sup>2\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> norm x *\\<^sub>R y = norm y *\\<^sub>R x\"\n    by (smt (verit, best) dot_norm inner_real_def inner_simps norm_cauchy_schwarz_eq power2_eq_square)\n  finally show ?thesis .\nqed\n\nlemma dist_triangle_eq:\n  fixes x y z :: \"'a::real_inner\"\n  shows \"dist x z = dist x y + dist y z \\<longleftrightarrow>\n    norm (x - y) *\\<^sub>R (y - z) = norm (y - z) *\\<^sub>R (x - y)\"\n  by (metis (no_types, lifting) add_diff_eq diff_add_cancel dist_norm norm_triangle_eq)\n\nsubsection \\<open>Collinearity\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> collinear :: \"'a::real_vector set \\<Rightarrow> bool\"\n  where \"collinear S \\<longleftrightarrow> (\\<exists>u. \\<forall>x \\<in> S. \\<forall> y \\<in> S. \\<exists>c. x - y = c *\\<^sub>R u)\"\n\nlemma collinear_alt:\n     \"collinear S \\<longleftrightarrow> (\\<exists>u v. \\<forall>x \\<in> S. \\<exists>c. x = u + c *\\<^sub>R v)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding collinear_def by (metis add.commute diff_add_cancel)\nnext\n  assume ?rhs\n  then obtain u v where *: \"\\<And>x. x \\<in> S \\<Longrightarrow> \\<exists>c. x = u + c *\\<^sub>R v\"\n    by auto\n  have \"\\<exists>c. x - y = c *\\<^sub>R v\" if \"x \\<in> S\" \"y \\<in> S\" for x y\n        by (metis *[OF \\<open>x \\<in> S\\<close>] *[OF \\<open>y \\<in> S\\<close>] scaleR_left.diff add_diff_cancel_left)\n  then show ?lhs\n    using collinear_def by blast\nqed\n\nlemma collinear:\n  fixes S :: \"'a::{perfect_space,real_vector} set\"\n  shows \"collinear S \\<longleftrightarrow> (\\<exists>u. u \\<noteq> 0 \\<and> (\\<forall>x \\<in> S. \\<forall> y \\<in> S. \\<exists>c. x - y = c *\\<^sub>R u))\"\nproof -\n  have \"\\<exists>v. v \\<noteq> 0 \\<and> (\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<exists>c. x - y = c *\\<^sub>R v)\"\n    if \"\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<exists>c. x - y = c *\\<^sub>R u\" \"u=0\" for u\n  proof -\n    have \"\\<forall>x\\<in>S. \\<forall>y\\<in>S. x = y\"\n      using that by auto\n    moreover\n    obtain v::'a where \"v \\<noteq> 0\"\n      using UNIV_not_singleton [of 0] by auto\n    ultimately have \"\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<exists>c. x - y = c *\\<^sub>R v\"\n      by auto\n    then show ?thesis\n      using \\<open>v \\<noteq> 0\\<close> by blast\n  qed\n  then show ?thesis\n    by (metis collinear_def)\nqed\n\nlemma collinear_subset: \"\\<lbrakk>collinear T; S \\<subseteq> T\\<rbrakk> \\<Longrightarrow> collinear S\"\n  by (meson collinear_def subsetCE)\n\nlemma collinear_empty [iff]: \"collinear {}\"\n  by (simp add: collinear_def)\n\nlemma collinear_sing [iff]: \"collinear {x}\"\n  by (simp add: collinear_def)\n\nlemma collinear_2 [iff]: \"collinear {x, y}\"\n  by (simp add: collinear_def) (metis minus_diff_eq scaleR_left.minus scaleR_one)\n\nlemma collinear_lemma: \"collinear {0, x, y} \\<longleftrightarrow> x = 0 \\<or> y = 0 \\<or> (\\<exists>c. y = c *\\<^sub>R x)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof (cases \"x = 0 \\<or> y = 0\")\n  case True\n  then show ?thesis\n    by (auto simp: insert_commute)\nnext\n  case False\n  show ?thesis\n  proof\n    assume h: \"?lhs\"\n    then obtain u where u: \"\\<forall> x\\<in> {0,x,y}. \\<forall>y\\<in> {0,x,y}. \\<exists>c. x - y = c *\\<^sub>R u\"\n      unfolding collinear_def by blast\n    from u[rule_format, of x 0] u[rule_format, of y 0]\n    obtain cx and cy where\n      cx: \"x = cx *\\<^sub>R u\" and cy: \"y = cy *\\<^sub>R u\"\n      by auto\n    from cx cy False have cx0: \"cx \\<noteq> 0\" and cy0: \"cy \\<noteq> 0\" by auto\n    let ?d = \"cy / cx\"\n    from cx cy cx0 have \"y = ?d *\\<^sub>R x\"\n      by simp\n    then show ?rhs using False by blast\n  next\n    assume h: \"?rhs\"\n    then obtain c where c: \"y = c *\\<^sub>R x\"\n      using False by blast\n    show ?lhs\n      apply (simp add: collinear_def c)\n      by (metis (mono_tags, lifting) scaleR_left.minus scaleR_left_diff_distrib scaleR_one)\n  qed\nqed\n\nlemma collinear_iff_Reals: \"collinear {0::complex,w,z} \\<longleftrightarrow> z/w \\<in> \\<real>\"\nproof\n  show \"z/w \\<in> \\<real> \\<Longrightarrow> collinear {0,w,z}\"\n    by (metis Reals_cases collinear_lemma nonzero_divide_eq_eq scaleR_conv_of_real)\nqed (auto simp: collinear_lemma scaleR_conv_of_real)\n\nlemma collinear_scaleR_iff: \"collinear {0, \\<alpha> *\\<^sub>R w, \\<beta> *\\<^sub>R z} \\<longleftrightarrow> collinear {0,w,z} \\<or> \\<alpha>=0 \\<or> \\<beta>=0\"\n  (is \"?lhs = ?rhs\")\nproof (cases \"\\<alpha>=0 \\<or> \\<beta>=0\")\n  case False\n  then have \"(\\<exists>c. \\<beta> *\\<^sub>R z = (c * \\<alpha>) *\\<^sub>R w) = (\\<exists>c. z = c *\\<^sub>R w)\"\n    by (metis mult.commute scaleR_scaleR vector_fraction_eq_iff)\n  then show ?thesis\n    by (auto simp add: collinear_lemma)\nqed (auto simp: collinear_lemma)\n\nlemma norm_cauchy_schwarz_equal: \"\\<bar>x \\<bullet> y\\<bar> = norm x * norm y \\<longleftrightarrow> collinear {0, x, y}\"\nproof (cases \"x=0\")\n  case True\n  then show ?thesis\n    by (auto simp: insert_commute)\nnext\n  case False\n  then have nnz: \"norm x \\<noteq> 0\"\n    by auto\n  show ?thesis\n  proof\n    assume \"\\<bar>x \\<bullet> y\\<bar> = norm x * norm y\"\n    then show \"collinear {0, x, y}\"\n      unfolding norm_cauchy_schwarz_abs_eq collinear_lemma\n      by (meson eq_vector_fraction_iff nnz)\n  next\n    assume \"collinear {0, x, y}\"\n    with False show \"\\<bar>x \\<bullet> y\\<bar> = norm x * norm y\"\n      unfolding norm_cauchy_schwarz_abs_eq collinear_lemma  by (auto simp: abs_if)\n  qed\nqed\n\nlemma norm_triangle_eq_imp_collinear:\n  fixes x y :: \"'a::real_inner\"\n  assumes \"norm (x + y) = norm x + norm y\"\n  shows \"collinear{0,x,y}\"\n  using assms norm_cauchy_schwarz_abs_eq norm_cauchy_schwarz_equal norm_triangle_eq \n  by blast\n\n\nsubsection\\<open>Properties of special hyperplanes\\<close>\n\nlemma subspace_hyperplane: \"subspace {x. a \\<bullet> x = 0}\"\n  by (simp add: subspace_def inner_right_distrib)\n\nlemma subspace_hyperplane2: \"subspace {x. x \\<bullet> a = 0}\"\n  by (simp add: inner_commute inner_right_distrib subspace_def)\n\nlemma special_hyperplane_span:\n  fixes S :: \"'n::euclidean_space set\"\n  assumes \"k \\<in> Basis\"\n  shows \"{x. k \\<bullet> x = 0} = span (Basis - {k})\"\nproof -\n  have *: \"x \\<in> span (Basis - {k})\" if \"k \\<bullet> x = 0\" for x\n  proof -\n    have \"x = (\\<Sum>b\\<in>Basis. (x \\<bullet> b) *\\<^sub>R b)\"\n      by (simp add: euclidean_representation)\n    also have \"\\<dots> = (\\<Sum>b \\<in> Basis - {k}. (x \\<bullet> b) *\\<^sub>R b)\"\n      by (auto simp: sum.remove [of _ k] inner_commute assms that)\n    finally have \"x = (\\<Sum>b\\<in>Basis - {k}. (x \\<bullet> b) *\\<^sub>R b)\" .\n    then show ?thesis\n      by (simp add: span_finite)\n  qed\n  show ?thesis\n    apply (rule span_subspace [symmetric])\n    using assms\n    apply (auto simp: inner_not_same_Basis intro: * subspace_hyperplane)\n    done\nqed\n\nlemma dim_special_hyperplane:\n  fixes k :: \"'n::euclidean_space\"\n  shows \"k \\<in> Basis \\<Longrightarrow> dim {x. k \\<bullet> x = 0} = DIM('n) - 1\"\n  by (metis Diff_subset card_Diff_singleton indep_card_eq_dim_span independent_substdbasis special_hyperplane_span)\n\nproposition dim_hyperplane:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"a \\<noteq> 0\"\n    shows \"dim {x. a \\<bullet> x = 0} = DIM('a) - 1\"\nproof -\n  have span0: \"span {x. a \\<bullet> x = 0} = {x. a \\<bullet> x = 0}\"\n    by (rule span_unique) (auto simp: subspace_hyperplane)\n  then obtain B where \"independent B\"\n              and Bsub: \"B \\<subseteq> {x. a \\<bullet> x = 0}\"\n              and subspB: \"{x. a \\<bullet> x = 0} \\<subseteq> span B\"\n              and card0: \"(card B = dim {x. a \\<bullet> x = 0})\"\n              and ortho: \"pairwise orthogonal B\"\n    using orthogonal_basis_exists by metis\n  with assms have \"a \\<notin> span B\"\n    by (metis (mono_tags, lifting) span_eq inner_eq_zero_iff mem_Collect_eq span0)\n  then have ind: \"independent (insert a B)\"\n    by (simp add: \\<open>independent B\\<close> independent_insert)\n  have \"finite B\"\n    using \\<open>independent B\\<close> independent_bound by blast\n  have \"UNIV \\<subseteq> span (insert a B)\"\n  proof fix y::'a\n    obtain r z where \"y = r *\\<^sub>R a + z\" \"a \\<bullet> z = 0\"\n      by (metis add.commute diff_add_cancel vector_sub_project_orthogonal)\n    then show \"y \\<in> span (insert a B)\"\n      by (metis (mono_tags, lifting) Bsub add_diff_cancel_left'\n          mem_Collect_eq span0 span_breakdown_eq span_eq subspB)\n  qed\n  then have \"DIM('a) = dim(insert a B)\"\n    by (metis independent_Basis span_Basis dim_eq_card top.extremum_uniqueI)\n  then show ?thesis\n    by (metis One_nat_def \\<open>a \\<notin> span B\\<close> \\<open>finite B\\<close> card0 card_insert_disjoint \n        diff_Suc_Suc diff_zero dim_eq_card_independent ind span_base)\nqed\n\nlemma lowdim_eq_hyperplane:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"dim S = DIM('a) - 1\"\n  obtains a where \"a \\<noteq> 0\" and \"span S = {x. a \\<bullet> x = 0}\"\nproof -\n  obtain b where b: \"b \\<noteq> 0\" \"span S \\<subseteq> {a. b \\<bullet> a = 0}\"\n    by (metis DIM_positive assms diff_less zero_less_one lowdim_subset_hyperplane)\n  then show ?thesis\n    by (metis assms dim_hyperplane dim_span dim_subset subspace_dim_equal subspace_hyperplane subspace_span that)\nqed\n\nlemma dim_eq_hyperplane:\n  fixes S :: \"'n::euclidean_space set\"\n  shows \"dim S = DIM('n) - 1 \\<longleftrightarrow> (\\<exists>a. a \\<noteq> 0 \\<and> span S = {x. a \\<bullet> x = 0})\"\nby (metis One_nat_def dim_hyperplane dim_span lowdim_eq_hyperplane)\n\n\nsubsection\\<open> Orthogonal bases and Gram-Schmidt process\\<close>\n\nlemma pairwise_orthogonal_independent:\n  assumes \"pairwise orthogonal S\" and \"0 \\<notin> S\"\n    shows \"independent S\"\nproof -\n  have 0: \"\\<And>x y. \\<lbrakk>x \\<noteq> y; x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> x \\<bullet> y = 0\"\n    using assms by (simp add: pairwise_def orthogonal_def)\n  have \"False\" if \"a \\<in> S\" and a: \"a \\<in> span (S - {a})\" for a\n  proof -\n    obtain T U where \"T \\<subseteq> S - {a}\" \"a = (\\<Sum>v\\<in>T. U v *\\<^sub>R v)\"\n      using a by (force simp: span_explicit)\n    then have \"a \\<bullet> a = a \\<bullet> (\\<Sum>v\\<in>T. U v *\\<^sub>R v)\"\n      by simp\n    also have \"\\<dots> = 0\"\n      apply (simp add: inner_sum_right)\n      by (smt (verit) \"0\" DiffE \\<open>T \\<subseteq> S - {a}\\<close> in_mono insertCI mult_not_zero sum.neutral that(1))\n    finally show ?thesis\n      using \\<open>0 \\<notin> S\\<close> \\<open>a \\<in> S\\<close> by auto\n  qed\n  then show ?thesis\n    by (force simp: dependent_def)\nqed\n\nlemma pairwise_orthogonal_imp_finite:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"pairwise orthogonal S\"\n    shows \"finite S\"\n  by (metis Set.set_insert assms finite_insert independent_bound pairwise_insert \n            pairwise_orthogonal_independent)\n\nlemma subspace_orthogonal_to_vector: \"subspace {y. orthogonal x y}\"\n  by (simp add: subspace_def orthogonal_clauses)\n\nlemma subspace_orthogonal_to_vectors: \"subspace {y. \\<forall>x \\<in> S. orthogonal x y}\"\n  by (simp add: subspace_def orthogonal_clauses)\n\nlemma orthogonal_to_span:\n  assumes a: \"a \\<in> span S\" and x: \"\\<And>y. y \\<in> S \\<Longrightarrow> orthogonal x y\"\n    shows \"orthogonal x a\"\n  by (metis a orthogonal_clauses(1,2,4)\n      span_induct_alt x)\n\nproposition Gram_Schmidt_step:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"pairwise orthogonal S\" and x: \"x \\<in> span S\"\n    shows \"orthogonal x (a - (\\<Sum>b\\<in>S. (b \\<bullet> a / (b \\<bullet> b)) *\\<^sub>R b))\"\nproof -\n  have \"finite S\"\n    by (simp add: S pairwise_orthogonal_imp_finite)\n  have \"orthogonal (a - (\\<Sum>b\\<in>S. (b \\<bullet> a / (b \\<bullet> b)) *\\<^sub>R b)) x\"\n       if \"x \\<in> S\" for x\n  proof -\n    have \"a \\<bullet> x = (\\<Sum>y\\<in>S. if y = x then y \\<bullet> a else 0)\"\n      by (simp add: \\<open>finite S\\<close> inner_commute that)\n    also have \"\\<dots> =  (\\<Sum>b\\<in>S. b \\<bullet> a * (b \\<bullet> x) / (b \\<bullet> b))\"\n      apply (rule sum.cong [OF refl], simp)\n      by (meson S orthogonal_def pairwise_def that)\n   finally show ?thesis\n     by (simp add: orthogonal_def algebra_simps inner_sum_left)\n  qed\n  then show ?thesis\n    using orthogonal_to_span orthogonal_commute x by blast\nqed\n\n\nlemma orthogonal_extension_aux:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"finite T\" \"finite S\" \"pairwise orthogonal S\"\n    shows \"\\<exists>U. pairwise orthogonal (S \\<union> U) \\<and> span (S \\<union> U) = span (S \\<union> T)\"\nusing assms\nproof (induction arbitrary: S)\n  case empty then show ?case\n    by simp (metis sup_bot_right)\nnext\n  case (insert a T)\n  have 0: \"\\<And>x y. \\<lbrakk>x \\<noteq> y; x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> x \\<bullet> y = 0\"\n    using insert by (simp add: pairwise_def orthogonal_def)\n  define a' where \"a' = a - (\\<Sum>b\\<in>S. (b \\<bullet> a / (b \\<bullet> b)) *\\<^sub>R b)\"\n  obtain U where orthU: \"pairwise orthogonal (S \\<union> insert a' U)\"\n             and spanU: \"span (insert a' S \\<union> U) = span (insert a' S \\<union> T)\"\n    by (rule exE [OF insert.IH [of \"insert a' S\"]])\n      (auto simp: Gram_Schmidt_step a'_def insert.prems orthogonal_commute\n        pairwise_orthogonal_insert span_clauses)\n  have orthS: \"\\<And>x. x \\<in> S \\<Longrightarrow> a' \\<bullet> x = 0\"\n    using Gram_Schmidt_step a'_def insert.prems orthogonal_commute orthogonal_def span_base by blast\n  have \"span (S \\<union> insert a' U) = span (insert a' (S \\<union> T))\"\n    using spanU by simp\n  also have \"\\<dots> = span (insert a (S \\<union> T))\"\n    by (simp add: a'_def span_neg span_sum span_base span_mul eq_span_insert_eq)\n  also have \"\\<dots> = span (S \\<union> insert a T)\"\n    by simp\n  finally show ?case\n    using orthU by blast\nqed\n\n\nproposition orthogonal_extension:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"pairwise orthogonal S\"\n  obtains U where \"pairwise orthogonal (S \\<union> U)\" \"span (S \\<union> U) = span (S \\<union> T)\"\nproof -\n  obtain B where \"finite B\" \"span B = span T\"\n    using basis_subspace_exists [of \"span T\"] subspace_span by metis\n  with orthogonal_extension_aux [of B S]\n  obtain U where \"pairwise orthogonal (S \\<union> U)\" \"span (S \\<union> U) = span (S \\<union> B)\"\n    using assms pairwise_orthogonal_imp_finite by auto\n  with \\<open>span B = span T\\<close> show ?thesis\n    by (rule_tac U=U in that) (auto simp: span_Un)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> orthogonal_extension_strong:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes S: \"pairwise orthogonal S\"\n  obtains U where \"U \\<inter> (insert 0 S) = {}\" \"pairwise orthogonal (S \\<union> U)\"\n                  \"span (S \\<union> U) = span (S \\<union> T)\"\nproof -\n  obtain U where U: \"pairwise orthogonal (S \\<union> U)\" \"span (S \\<union> U) = span (S \\<union> T)\"\n    using orthogonal_extension assms by blast\n  moreover have \"pairwise orthogonal (S \\<union> (U - insert 0 S))\"\n    by (smt (verit, best) Un_Diff_Int Un_iff U pairwise_def)\n  ultimately show ?thesis\n    by (metis Diff_disjoint Un_Diff_cancel Un_insert_left inf_commute span_insert_0 that)\nqed\n\nsubsection\\<open>Decomposing a vector into parts in orthogonal subspaces\\<close>\n\ntext\\<open>existence of orthonormal basis for a subspace.\\<close>\n\nlemma orthogonal_spanningset_subspace:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"subspace S\"\n  obtains B where \"B \\<subseteq> S\" \"pairwise orthogonal B\" \"span B = S\"\n  by (metis assms basis_orthogonal basis_subspace_exists span_eq)\n\nlemma orthogonal_basis_subspace:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"subspace S\"\n  obtains B where \"0 \\<notin> B\" \"B \\<subseteq> S\" \"pairwise orthogonal B\" \"independent B\"\n                  \"card B = dim S\" \"span B = S\"\n  by (metis assms dependent_zero orthogonal_basis_exists span_eq span_eq_iff)\n\nproposition orthonormal_basis_subspace:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"subspace S\"\n  obtains B where \"B \\<subseteq> S\" \"pairwise orthogonal B\"\n              and \"\\<And>x. x \\<in> B \\<Longrightarrow> norm x = 1\"\n              and \"independent B\" \"card B = dim S\" \"span B = S\"\nproof -\n  obtain B where \"0 \\<notin> B\" \"B \\<subseteq> S\"\n             and orth: \"pairwise orthogonal B\"\n             and \"independent B\" \"card B = dim S\" \"span B = S\"\n    by (blast intro: orthogonal_basis_subspace [OF assms])\n  have 1: \"(\\<lambda>x. x /\\<^sub>R norm x) ` B \\<subseteq> S\"\n    using \\<open>span B = S\\<close> span_superset span_mul by fastforce\n  have 2: \"pairwise orthogonal ((\\<lambda>x. x /\\<^sub>R norm x) ` B)\"\n    using orth by (force simp: pairwise_def orthogonal_clauses)\n  have 3: \"\\<And>x. x \\<in> (\\<lambda>x. x /\\<^sub>R norm x) ` B \\<Longrightarrow> norm x = 1\"\n    by (metis (no_types, lifting) \\<open>0 \\<notin> B\\<close> image_iff norm_sgn sgn_div_norm)\n  have 4: \"independent ((\\<lambda>x. x /\\<^sub>R norm x) ` B)\"\n    by (metis \"2\" \"3\" norm_zero pairwise_orthogonal_independent zero_neq_one)\n  have \"inj_on (\\<lambda>x. x /\\<^sub>R norm x) B\"\n  proof\n    fix x y\n    assume \"x \\<in> B\" \"y \\<in> B\" \"x /\\<^sub>R norm x = y /\\<^sub>R norm y\"\n    moreover have \"\\<And>i. i \\<in> B \\<Longrightarrow> norm (i /\\<^sub>R norm i) = 1\"\n      using 3 by blast\n    ultimately show \"x = y\"\n      by (metis norm_eq_1 orth orthogonal_clauses(7) orthogonal_commute orthogonal_def pairwise_def zero_neq_one)\n  qed\n  then have 5: \"card ((\\<lambda>x. x /\\<^sub>R norm x) ` B) = dim S\"\n    by (metis \\<open>card B = dim S\\<close> card_image)\n  have 6: \"span ((\\<lambda>x. x /\\<^sub>R norm x) ` B) = S\"\n    by (metis \"1\" \"4\" \"5\" assms card_eq_dim independent_imp_finite span_subspace)\n  show ?thesis\n    by (rule that [OF 1 2 3 4 5 6])\nqed\n\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> orthogonal_to_subspace_exists_gen:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"span S \\<subset> span T\"\n  obtains x where \"x \\<noteq> 0\" \"x \\<in> span T\" \"\\<And>y. y \\<in> span S \\<Longrightarrow> orthogonal x y\"\nproof -\n  obtain B where \"B \\<subseteq> span S\" and orthB: \"pairwise orthogonal B\"\n             and \"\\<And>x. x \\<in> B \\<Longrightarrow> norm x = 1\"\n             and \"independent B\" \"card B = dim S\" \"span B = span S\"\n    by (metis dim_span orthonormal_basis_subspace subspace_span)\n  with assms obtain u where spanBT: \"span B \\<subseteq> span T\" and \"u \\<notin> span B\" \"u \\<in> span T\"\n    by auto\n  obtain C where orthBC: \"pairwise orthogonal (B \\<union> C)\" and spanBC: \"span (B \\<union> C) = span (B \\<union> {u})\"\n    by (blast intro: orthogonal_extension [OF orthB])\n  show thesis\n  proof (cases \"C \\<subseteq> insert 0 B\")\n    case True\n    then have \"C \\<subseteq> span B\"\n      using span_eq\n      by (metis span_insert_0 subset_trans)\n    moreover have \"u \\<in> span (B \\<union> C)\"\n      using \\<open>span (B \\<union> C) = span (B \\<union> {u})\\<close> span_superset by force\n    ultimately show ?thesis\n      using True \\<open>u \\<notin> span B\\<close>\n      by (metis Un_insert_left span_insert_0 sup.orderE)\n  next\n    case False\n    then obtain x where \"x \\<in> C\" \"x \\<noteq> 0\" \"x \\<notin> B\"\n      by blast\n    then have \"x \\<in> span T\"\n      by (smt (verit, ccfv_SIG) Set.set_insert  \\<open>u \\<in> span T\\<close> empty_subsetI insert_subset \n          le_sup_iff spanBC spanBT span_mono span_span span_superset subset_trans)\n    moreover have \"orthogonal x y\" if \"y \\<in> span B\" for y\n      using that\n    proof (rule span_induct)\n      show \"subspace {a. orthogonal x a}\"\n        by (simp add: subspace_orthogonal_to_vector)\n      show \"\\<And>b. b \\<in> B \\<Longrightarrow> orthogonal x b\"\n        by (metis Un_iff \\<open>x \\<in> C\\<close> \\<open>x \\<notin> B\\<close> orthBC pairwise_def)\n    qed\n    ultimately show ?thesis\n      using \\<open>x \\<noteq> 0\\<close> that \\<open>span B = span S\\<close> by auto\n  qed\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> orthogonal_to_subspace_exists:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"dim S < DIM('a)\"\n  obtains x where \"x \\<noteq> 0\" \"\\<And>y. y \\<in> span S \\<Longrightarrow> orthogonal x y\"\nproof -\n  have \"span S \\<subset> UNIV\"\n    by (metis assms dim_eq_full order_less_imp_not_less top.not_eq_extremum)\n  with orthogonal_to_subspace_exists_gen [of S UNIV] that show ?thesis\n    by (auto)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> orthogonal_to_vector_exists:\n  fixes x :: \"'a :: euclidean_space\"\n  assumes \"2 \\<le> DIM('a)\"\n  obtains y where \"y \\<noteq> 0\" \"orthogonal x y\"\nproof -\n  have \"dim {x} < DIM('a)\"\n    using assms by auto\n  then show thesis\n    by (rule orthogonal_to_subspace_exists) (simp add: orthogonal_commute span_base that)\nqed\n\nproposition\\<^marker>\\<open>tag unimportant\\<close> orthogonal_subspace_decomp_exists:\n  fixes S :: \"'a :: euclidean_space set\"\n  obtains y z\n  where \"y \\<in> span S\"\n    and \"\\<And>w. w \\<in> span S \\<Longrightarrow> orthogonal z w\"\n    and \"x = y + z\"\nproof -\n  obtain T where \"0 \\<notin> T\" \"T \\<subseteq> span S\" \"pairwise orthogonal T\" \"independent T\"\n    \"card T = dim (span S)\" \"span T = span S\"\n    using orthogonal_basis_subspace subspace_span by blast\n  let ?a = \"\\<Sum>b\\<in>T. (b \\<bullet> x / (b \\<bullet> b)) *\\<^sub>R b\"\n  have orth: \"orthogonal (x - ?a) w\" if \"w \\<in> span S\" for w\n    by (simp add: Gram_Schmidt_step \\<open>pairwise orthogonal T\\<close> \\<open>span T = span S\\<close>\n        orthogonal_commute that)\n  with that[of ?a \"x-?a\"] \\<open>T \\<subseteq> span S\\<close> show ?thesis\n    by (simp add: span_mul span_sum subsetD)\nqed\n\nlemma orthogonal_subspace_decomp_unique:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"x + y = x' + y'\"\n      and ST: \"x \\<in> span S\" \"x' \\<in> span S\" \"y \\<in> span T\" \"y' \\<in> span T\"\n      and orth: \"\\<And>a b. \\<lbrakk>a \\<in> S; b \\<in> T\\<rbrakk> \\<Longrightarrow> orthogonal a b\"\n  shows \"x = x' \\<and> y = y'\"\nproof -\n  have \"x + y - y' = x'\"\n    by (simp add: assms)\n  moreover have \"\\<And>a b. \\<lbrakk>a \\<in> span S; b \\<in> span T\\<rbrakk> \\<Longrightarrow> orthogonal a b\"\n    by (meson orth orthogonal_commute orthogonal_to_span)\n  ultimately have \"0 = x' - x\"\n    using assms\n    by (metis add.commute add_diff_cancel_right' diff_right_commute orthogonal_self span_diff)\n  with assms show ?thesis by auto\nqed\n\nlemma vector_in_orthogonal_spanningset:\n  fixes a :: \"'a::euclidean_space\"\n  obtains S where \"a \\<in> S\" \"pairwise orthogonal S\" \"span S = UNIV\"\n  by (metis UnI1 Un_UNIV_right insertI1 orthogonal_extension pairwise_singleton span_UNIV)\n\nlemma vector_in_orthogonal_basis:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"a \\<noteq> 0\"\n  obtains S where \"a \\<in> S\" \"0 \\<notin> S\" \"pairwise orthogonal S\" \"independent S\" \"finite S\"\n                  \"span S = UNIV\" \"card S = DIM('a)\"\nproof -\n  obtain S where S: \"a \\<in> S\" \"pairwise orthogonal S\" \"span S = UNIV\"\n    using vector_in_orthogonal_spanningset .\n  show thesis\n  proof\n    show \"pairwise orthogonal (S - {0})\"\n      using pairwise_mono S(2) by blast\n    show \"independent (S - {0})\"\n      by (simp add: \\<open>pairwise orthogonal (S - {0})\\<close> pairwise_orthogonal_independent)\n    show \"finite (S - {0})\"\n      using \\<open>independent (S - {0})\\<close> independent_imp_finite by blast\n    show \"card (S - {0}) = DIM('a)\"\n      using span_delete_0 [of S] S\n      by (simp add: \\<open>independent (S - {0})\\<close> indep_card_eq_dim_span)\n  qed (use S \\<open>a \\<noteq> 0\\<close> in auto)\nqed\n\nlemma vector_in_orthonormal_basis:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"norm a = 1\"\n  obtains S where \"a \\<in> S\" \"pairwise orthogonal S\" \"\\<And>x. x \\<in> S \\<Longrightarrow> norm x = 1\"\n    \"independent S\" \"card S = DIM('a)\" \"span S = UNIV\"\nproof -\n  have \"a \\<noteq> 0\"\n    using assms by auto\n  then obtain S where \"a \\<in> S\" \"0 \\<notin> S\" \"finite S\"\n          and S: \"pairwise orthogonal S\" \"independent S\" \"span S = UNIV\" \"card S = DIM('a)\"\n    by (metis vector_in_orthogonal_basis)\n  let ?S = \"(\\<lambda>x. x /\\<^sub>R norm x) ` S\"\n  show thesis\n  proof\n    show \"a \\<in> ?S\"\n      using \\<open>a \\<in> S\\<close> assms image_iff by fastforce\n  next\n    show \"pairwise orthogonal ?S\"\n      using \\<open>pairwise orthogonal S\\<close> by (auto simp: pairwise_def orthogonal_def)\n    show \"\\<And>x. x \\<in> (\\<lambda>x. x /\\<^sub>R norm x) ` S \\<Longrightarrow> norm x = 1\"\n      using \\<open>0 \\<notin> S\\<close> by (auto simp: field_split_simps)\n    then show ind: \"independent ?S\"\n      by (metis \\<open>pairwise orthogonal ((\\<lambda>x. x /\\<^sub>R norm x) ` S)\\<close> norm_zero pairwise_orthogonal_independent zero_neq_one)\n    have \"inj_on (\\<lambda>x. x /\\<^sub>R norm x) S\"\n      unfolding inj_on_def\n      by (metis (full_types) S(1) \\<open>0 \\<notin> S\\<close> inverse_nonzero_iff_nonzero norm_eq_zero orthogonal_scaleR orthogonal_self pairwise_def)\n    then show \"card ?S = DIM('a)\"\n      by (simp add: card_image S)\n    then show \"span ?S = UNIV\"\n      by (metis ind dim_eq_card dim_eq_full)\n  qed\nqed\n\nproposition dim_orthogonal_sum:\n  fixes A :: \"'a::euclidean_space set\"\n  assumes \"\\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> B\\<rbrakk> \\<Longrightarrow> x \\<bullet> y = 0\"\n    shows \"dim(A \\<union> B) = dim A + dim B\"\nproof -\n  have 1: \"\\<And>x y. \\<lbrakk>x \\<in> span A; y \\<in> B\\<rbrakk> \\<Longrightarrow> x \\<bullet> y = 0\"\n    by (erule span_induct [OF _ subspace_hyperplane2]; simp add: assms)\n  have \"\\<And>x y. \\<lbrakk>x \\<in> span A; y \\<in> span B\\<rbrakk> \\<Longrightarrow> x \\<bullet> y = 0\"\n    using 1 by (simp add: span_induct [OF _ subspace_hyperplane])\n  then have 0: \"\\<And>x y. \\<lbrakk>x \\<in> span A; y \\<in> span B\\<rbrakk> \\<Longrightarrow> x \\<bullet> y = 0\"\n    by simp\n  have \"dim(A \\<union> B) = dim (span (A \\<union> B))\"\n    by (simp)\n  also have \"span (A \\<union> B) = ((\\<lambda>(a, b). a + b) ` (span A \\<times> span B))\"\n    by (auto simp add: span_Un image_def)\n  also have \"dim \\<dots> = dim {x + y |x y. x \\<in> span A \\<and> y \\<in> span B}\"\n    by (auto intro!: arg_cong [where f=dim])\n  also have \"\\<dots> = dim {x + y |x y. x \\<in> span A \\<and> y \\<in> span B} + dim(span A \\<inter> span B)\"\n    by (auto dest: 0)\n  also have \"\\<dots> = dim A + dim B\"\n    using dim_sums_Int by fastforce\n  finally show ?thesis .\nqed\n\nlemma dim_subspace_orthogonal_to_vectors:\n  fixes A :: \"'a::euclidean_space set\"\n  assumes \"subspace A\" \"subspace B\" \"A \\<subseteq> B\"\n    shows \"dim {y \\<in> B. \\<forall>x \\<in> A. orthogonal x y} + dim A = dim B\"\nproof -\n  have \"dim (span ({y \\<in> B. \\<forall>x\\<in>A. orthogonal x y} \\<union> A)) = dim (span B)\"\n  proof (rule arg_cong [where f=dim, OF subset_antisym])\n    show \"span ({y \\<in> B. \\<forall>x\\<in>A. orthogonal x y} \\<union> A) \\<subseteq> span B\"\n      by (simp add: \\<open>A \\<subseteq> B\\<close> Collect_restrict span_mono)\n  next\n    have *: \"x \\<in> span ({y \\<in> B. \\<forall>x\\<in>A. orthogonal x y} \\<union> A)\"\n         if \"x \\<in> B\" for x\n    proof -\n      obtain y z where \"x = y + z\" \"y \\<in> span A\" and orth: \"\\<And>w. w \\<in> span A \\<Longrightarrow> orthogonal z w\"\n        using orthogonal_subspace_decomp_exists [of A x] that by auto\n      moreover\n      have \"y \\<in> span B\"\n        using \\<open>y \\<in> span A\\<close> assms(3) span_mono by blast\n      ultimately have \"z \\<in> B \\<and> (\\<forall>x. x \\<in> A \\<longrightarrow> orthogonal x z)\"\n        using assms by (metis orthogonal_commute span_add_eq span_eq_iff that)\n      then have z: \"z \\<in> span {y \\<in> B. \\<forall>x\\<in>A. orthogonal x y}\"\n        by (simp add: span_base)\n      then show ?thesis\n        by (smt (verit, best) \\<open>x = y + z\\<close> \\<open>y \\<in> span A\\<close> le_sup_iff span_add_eq span_subspace_induct \n            span_superset subset_iff subspace_span)\n    qed\n    show \"span B \\<subseteq> span ({y \\<in> B. \\<forall>x\\<in>A. orthogonal x y} \\<union> A)\"\n      by (rule span_minimal) (auto intro: * span_minimal)\n  qed\n  then show ?thesis\n    by (metis (no_types, lifting) dim_orthogonal_sum dim_span mem_Collect_eq\n        orthogonal_commute orthogonal_def)\nqed\n\nsubsection\\<open>Linear functions are (uniformly) continuous on any set\\<close>\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Topological properties of linear functions\\<close>\n\nlemma linear_lim_0:\n  assumes \"bounded_linear f\"\n  shows \"(f \\<longlongrightarrow> 0) (at (0))\"\nproof -\n  interpret f: bounded_linear f by fact\n  have \"(f \\<longlongrightarrow> f 0) (at 0)\"\n    using tendsto_ident_at by (rule f.tendsto)\n  then show ?thesis unfolding f.zero .\nqed\n\nlemma linear_continuous_at:\n  \"bounded_linear f \\<Longrightarrow>continuous (at a) f\"\n  by (simp add: bounded_linear.isUCont isUCont_isCont)\n\nlemma linear_continuous_within:\n  \"bounded_linear f \\<Longrightarrow> continuous (at x within s) f\"\n  using continuous_at_imp_continuous_at_within linear_continuous_at by blast\n\nlemma linear_continuous_on:\n  \"bounded_linear f \\<Longrightarrow> continuous_on s f\"\n  using continuous_at_imp_continuous_on[of s f] using linear_continuous_at[of f] by auto\n\nlemma Lim_linear:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\" and h :: \"'b \\<Rightarrow> 'c::real_normed_vector\"\n  assumes \"(f \\<longlongrightarrow> l) F\" \"linear h\"\n  shows \"((\\<lambda>x. h(f x)) \\<longlongrightarrow> h l) F\"\nproof -\n  obtain B where B: \"B > 0\" \"\\<And>x. norm (h x) \\<le> B * norm x\"\n    using linear_bounded_pos [OF \\<open>linear h\\<close>] by blast\n  show ?thesis\n    unfolding tendsto_iff\n      by (simp add: assms bounded_linear.tendsto linear_linear tendstoD)\nqed\n\nlemma linear_continuous_compose:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\" and g :: \"'b \\<Rightarrow> 'c::real_normed_vector\"\n  assumes \"continuous F f\" \"linear g\"\n  shows \"continuous F (\\<lambda>x. g(f x))\"\n  using assms unfolding continuous_def by (rule Lim_linear)\n\nlemma linear_continuous_on_compose:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space\" and g :: \"'b \\<Rightarrow> 'c::real_normed_vector\"\n  assumes \"continuous_on S f\" \"linear g\"\n  shows \"continuous_on S (\\<lambda>x. g(f x))\"\n  using assms by (simp add: continuous_on_eq_continuous_within linear_continuous_compose)\n\ntext\\<open>Also bilinear functions, in composition form\\<close>\n\nlemma bilinear_continuous_compose:\n  fixes h :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space \\<Rightarrow> 'c::real_normed_vector\"\n  assumes \"continuous F f\" \"continuous F g\" \"bilinear h\"\n  shows \"continuous F (\\<lambda>x. h (f x) (g x))\"\n  using assms bilinear_conv_bounded_bilinear bounded_bilinear.continuous by blast\n\nlemma bilinear_continuous_on_compose:\n  fixes h :: \"'a::euclidean_space \\<Rightarrow> 'b::euclidean_space \\<Rightarrow> 'c::real_normed_vector\"\n    and f :: \"'d::t2_space \\<Rightarrow> 'a\"\n  assumes \"continuous_on S f\" \"continuous_on S g\" \"bilinear h\"\n  shows \"continuous_on S (\\<lambda>x. h (f x) (g x))\"\n  using assms by (simp add: continuous_on_eq_continuous_within bilinear_continuous_compose)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/Linear_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703476, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.7950272089392266}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n \ntheory expp (* short for for expression ++ *)\n  imports Main \"~~/src/HOL/Library/Code_Target_Nat\" \nbegin\n  \n  (* exercise 3.5\nimpl post-increment\ndivision operation *)\n\nsubsection \"State\"  \n \ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n  \ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax\n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n \nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nsubsection \"Arithmetic Expressions\"\n \ndatatype expr = N int | V vname | PostIncr vname | Plus expr expr | Times expr expr | Div expr expr\n  \n(* Returns the updated state *)\nfun increment_variable :: \"vname \\<Rightarrow> state \\<Rightarrow> state\" where\n  \"increment_variable v s = \n    (let before = s v\n        in s (v := before + 1))\"\n \nfun eval :: \"expr \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n  \"eval (N n) s = Some (n, s)\" |\n  \"eval (V v) s = Some (s v, s)\" |\n  \"eval (PostIncr v) s = Some (s v, increment_variable v s)\" |\n  \"eval (Plus a\\<^sub>1 a\\<^sub>2) s = \n    (case eval a\\<^sub>1 s of\n      None \\<Rightarrow> None\n    | Some (r\\<^sub>1, s\\<^sub>1) \\<Rightarrow> \n      (case eval a\\<^sub>2 s\\<^sub>1 of\n        None \\<Rightarrow> None\n      | Some (r\\<^sub>2, s\\<^sub>2) \\<Rightarrow> Some (r\\<^sub>1 + r\\<^sub>2, s\\<^sub>2)))\"|\n  \"eval (Times a\\<^sub>1 a\\<^sub>2) s = \n    (case eval a\\<^sub>1 s of\n      None \\<Rightarrow> None\n    | Some (r\\<^sub>1, s\\<^sub>1) \\<Rightarrow> \n      (case eval a\\<^sub>2 s\\<^sub>1 of\n        None \\<Rightarrow> None\n      | Some (r\\<^sub>2, s\\<^sub>2) \\<Rightarrow> Some (r\\<^sub>1 * r\\<^sub>2, s\\<^sub>2)))\"|\n  \"eval (Div a\\<^sub>1 a\\<^sub>2) s = \n    (case eval a\\<^sub>1 s of\n      None \\<Rightarrow> None\n    | Some (r\\<^sub>1, s\\<^sub>1) \\<Rightarrow> \n      (case eval a\\<^sub>2 s\\<^sub>1 of\n        None \\<Rightarrow> None\n      | Some (r\\<^sub>2, s\\<^sub>2) \\<Rightarrow> \n        (if r\\<^sub>2 = 0\n          then None\n          else Some (r\\<^sub>1 div r\\<^sub>2, s\\<^sub>2))))\"\n  \nvalue \"eval (Div (N 8) (N 2)) <>\"\nvalue \"eval (Div (N 8) (N 0)) <>\"\n  \nvalue \"eval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n \nvalue \"eval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n \nvalue \"eval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n \nvalue \"eval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n  \nvalue \"eval (Plus (V ''x'') (V ''x'')) <''x'' := 1>\"\n\n  (* test post increment *)\nvalue \"eval (Plus (PostIncr ''x'') (PostIncr ''x'')) <''x'' := 1>\"\n\nsubsection \"Constant Folding\"\n \nfun plus :: \"expr \\<Rightarrow> expr \\<Rightarrow> expr\" where\n  \"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n  \"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n  \"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n  \"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n     \nfun times :: \"expr \\<Rightarrow> expr \\<Rightarrow> expr\" where\n  \"times (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1 * i\\<^sub>2)\" |\n  \"times (N i) a = (if i=0 \n                    then (N 0) \n                    else (if i=1 \n                      then a\n                      else Times (N i) a))\" |\n  \"times a (N i) = (if i=0 \n                    then (N 0) \n                    else (if i=1 \n                      then a\n                      else Times a (N i)))\" |\n  \"times a\\<^sub>1 a\\<^sub>2 = Times a\\<^sub>1 a\\<^sub>2\"\n\nfun asimp :: \"expr \\<Rightarrow> expr\" where\n  \"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\" |\n  \"asimp (Times a\\<^sub>1 a\\<^sub>2) = times (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"|\n  (* Don't recurse inside N, V, or PostIncr *)\n  \"asimp e = e\"\n \nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\nend\n  ", "meta": {"author": "gittywithexcitement", "repo": "isabelle", "sha": "42c53b2797e1b14c741c316f2585449b818a8f07", "save_path": "github-repos/isabelle/gittywithexcitement-isabelle", "path": "github-repos/isabelle/gittywithexcitement-isabelle/isabelle-42c53b2797e1b14c741c316f2585449b818a8f07/Chapter 3/expp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896845856297, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7950020833666613}}
{"text": "(* author: wzh *)\n\ntheory Exercise4 \n  imports Main\n\nbegin\n\n(* Exer 4.1 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\"\n| \"set (Node l x r) = (set l) \\<union> {x} \\<union> (set r)\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\"\n| \"ord (Node l x r) = ((ord l) \\<and> (ord r) \\<and> (\\<forall> y \\<in> (set l). x \\<ge> y) \\<and> (\\<forall> z \\<in> (set r). z \\<ge> x))\"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins x Tip = (Node Tip x Tip)\"\n| \"ins x (Node l mid r) = (\n    if x = mid then (Node l mid r) else\n        (if x < mid then (Node (ins x l) mid r) else\n         (Node l mid (ins x r))))\"\n\ntheorem [simp]: \"set (ins x t) = {x} \\<union> (set t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\ntheorem [simp]: \"ord t \\<Longrightarrow> ord (ins x t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n(* Exer 4.2 *)\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n\"palindrome []\"\n| \"palindrome [x]\"\n| \"palindrome xs \\<Longrightarrow> palindrome (x#xs@[x])\"\n\ntheorem palin_rev: \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction rule: palindrome.induct)\n    apply(auto)\n  done\n\n\n(* Exer 4.3 *)\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\"\n| step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\"\n| step': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  apply(induction rule: star.induct)\n  apply(auto intro: refl step)\n  done\n\ntheorem star'_star: \"star' r x y \\<Longrightarrow> star r x y\"\n  apply(induction rule: star'.induct)\n   apply(auto intro: refl star_trans)\n  done\n\n(* star'.induct can only be applied in the first premise *)\nlemma star'_trans: \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply(induction rule: star'.induct)\n  apply(auto intro: refl' step')\n  done\n\ntheorem star_star': \"star r x y \\<Longrightarrow> star' r x y\"\n  apply(induction rule: star.induct)\n   apply(auto intro: refl' star'_trans)\n  done\n\n(* Exer 4.4 *)\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl_iter: \"iter r n x x\"\n| step_iter: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (n+1) x z\"\n\ntheorem star_iter: \"star r x y \\<Longrightarrow> \\<exists> n. iter r n x y\"\n  apply(induction rule: star.induct)\n  apply(auto intro: refl_iter step_iter)\n  done\n\n(* Exer 4.5 *)\ndatatype alpha = Aa | Bb\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\ns_empty: \"S []\"\n| s_con1: \"S w \\<Longrightarrow> S (a#w@[b])\"\n| s_con2: \"S w1 \\<Longrightarrow> S w2 \\<Longrightarrow> S (w1@w2)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nt_empty: \"T []\"\n| t_con: \"T w1 \\<Longrightarrow> T w2 \\<Longrightarrow> T (w1@[a]@w2@[b])\"\n\ntheorem T_S: \"T w \\<Longrightarrow> S w\"\n  apply(induction rule: T.induct)\n   apply(auto intro: s_empty s_con1 s_con2)\n  done\n\n\n(* Exer 4.6 *)\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\"\n| \"aval (V v) s = s v\"\n| \"aval (Plus a1 a2) s = aval a1 s + aval a2 s\"\n\ninductive aval2 :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nconst: \"aval2 (N n) s n\"\n| var: \"aval2 (V v) s (s v)\"\n| plus: \"aval2 a1 s x \\<Longrightarrow> aval2 a2 s y \\<Longrightarrow> aval2 (Plus a1 a2) s (x+y)\"\n\nlemma aval_aval2: \"aval a s = v \\<Longrightarrow> aval2 a s v\"\n  apply(induction a arbitrary: v)\n    apply(auto intro: plus var const)\n  done\n\nlemma aval2_aval: \"aval2 a s v \\<Longrightarrow> aval a s = v\"\n  apply(induction rule: aval2.induct)\n    apply(auto)\n  done\n\ntheorem \"(aval a s = v) = (aval2 a s v)\"\n  apply(auto intro: aval_aval2 aval2_aval)\n  done\n\n(* Exer 4.7 *)\ndatatype instr = LOADI val | LOAD vname | ADD\ntype_synonym stack = \"val list\"\n\nfun exec1_modi :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1_modi (LOADI v) s stk = (v#stk)\"\n| \"exec1_modi (LOAD v) s stk = (s v # stk)\"\n| \"exec1_modi ADD s (x#y#stk) = ((x+y)#stk)\"\n\nfun exec_modi :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec_modi [] s stk = stk\"\n| \"exec_modi (x#xs) s stk = exec_modi xs s (exec1_modi x s stk)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\"\n| \"comp (V x) = [LOAD x]\"\n| \"comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\nlemma exec_cons [simp]: \"exec_modi (s1@s2) s stk = exec_modi s2 s (exec_modi s1 s stk)\"\n  apply(induction s1 arbitrary: stk)\n   apply(auto split: option.split)\n  done\n\ntheorem \"exec_modi (comp a) s stk = ((aval a s) # stk)\"\n  apply(induction a arbitrary: stk)\n    apply(auto)\n  done\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\nempty: \"ok n [] n\"\n| load: \"ok n xs m \\<Longrightarrow> ok n (xs@[LOAD v]) (m+1)\"\n| loadi: \"ok n xs m \\<Longrightarrow> ok n (xs@[LOADI v]) (m+1)\"\n| add: \"ok n xs (m+2) \\<Longrightarrow> ok n (xs@[ADD]) (m+1)\"\n\nend", "meta": {"author": "yogurt-shadow", "repo": "Isar_Exercise", "sha": "27658bff434e0845a23aeb310eeb971e4fc20b98", "save_path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise", "path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise/Isar_Exercise-27658bff434e0845a23aeb310eeb971e4fc20b98/Exercise4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.795002073466251}}
{"text": "section \"Playing with HOL\"\n\ntheory Tutorial5\nimports Main \n\nbegin\n(*<*)\ntext \"Ignore this\"\nno_notation\n  subset  (\"op \\<subset>\") and\n  subset  (\"(_/ \\<subset> _)\" [51, 51] 50) and\n  subset_eq  (\"op \\<subseteq>\") and\n  subset_eq  (\"(_/ \\<subseteq> _)\" [51, 51] 50) \n\nno_notation\n  union (infixl \"\\<union>\" 65) and\n  inter (infixl \"\\<inter>\" 70)\n\nno_notation\n  Set.member  (\"op \\<in>\") and\n  Set.member  (\"(_/ \\<in> _)\" [51, 51] 50)\ntext \"Ignore this END\"\n(*>*)\n\n\nsubsection \"Sets\"\n\ntext \\<open>In the context of HOL, a set @{term \"A\"} can be defined using\n      its characteristic function @{term \"\\<chi>\\<^sub>A\"}:\n      For a set @{term \"A\"} of objects of type @{text \"'a\"},\n      an object @{term \"x :: 'a\"} is an element of @{term \"A\"}\n      if and only if @{term \"\\<chi>\\<^sub>A x\"} holds\n      (i.e. @{term \"\\<chi>\\<^sub>A\"} represents\n      the extension of the set @{term \"A\"} when interpreted as a predicate).\n\n      Speaking in HOL terms, the\n      char. function @{term \"\\<chi>\\<^sub>A\"} is a term of type @{text \"'a \\<Rightarrow> bool\"}.\\<close>\n\ntype_synonym 'a Set = \"'a \\<Rightarrow> bool\"\n\n\n\nparagraph \"Constructing sets\"\n\nterm \"\\<lambda>x. P x\" -- \"set of objects for which P holds\"\n\n\n\nparagraph \"Membership\"\ntext \\<open>Membership of a set can easily defined as application to the characteristic\n      function.\\<close>\n\ndefinition member :: \"'a \\<Rightarrow> 'a Set \\<Rightarrow> bool\" (infix \"\\<in>\" 42) where\n  \"x \\<in> A \\<equiv> A x\"\n\n\n\nparagraph \"Other operators on sets\"\n\ntext \"Define intersection by\"\nabbreviation intersect :: \"'a Set \\<Rightarrow> 'a Set \\<Rightarrow> 'a Set\" (infix \"\\<inter>\" 41) where\n  \"A \\<inter> B \\<equiv> \\<lambda> x. A x \\<and> B x\"\n\ntext \"Define union by\"\nabbreviation union :: \"'a Set \\<Rightarrow> 'a Set \\<Rightarrow> 'a Set\" (infix \"\\<union>\" 41) where\n  \"A \\<union> B \\<equiv> \\<lambda> x. A x \\<or> B x\"\n\ntext \"Define difference by\"\nabbreviation diff :: \"'a Set \\<Rightarrow> 'a Set \\<Rightarrow> 'a Set\" (infix \"\\<setminus>\" 41) where\n  \"A \\<setminus> B \\<equiv> \\<lambda> x. A x \\<and> \\<not> B x\"\n\ntext \"Define subset by\"\nabbreviation subset :: \"'a Set \\<Rightarrow> 'a Set \\<Rightarrow> bool\" (infix \"\\<subseteq>\" 41) where\n  \"A \\<subseteq> B \\<equiv> \\<forall> x. A x \\<longrightarrow> B x\"\n\ntext \"Define intersection by\"\nabbreviation setequiv :: \"'a Set \\<Rightarrow> 'a Set \\<Rightarrow> bool\" (infix \"\\<simeq>\" 41) where\n  \"A \\<simeq> B \\<equiv> \\<forall> x. A x \\<longleftrightarrow> B x\"\n\n\n\n\n\n\nsubsection \"Relations\"\n\ntext \\<open>As for sets, we can define relations in HOL.\n      A relation @{term \"R\"} can be modeled by a term @{term \"R\"}\n      of type @{text \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"}.\n       \n     Then, for two objects @{term \"x :: 'a\"}, @{term \"y :: 'a\"}\n     @{term \"x\"} is in relation to @{term \"y\"}, infix-ly written @{term \"xRy\"},\n     if and only if @{term \"R x y\"} holds.\\<close>\n\n\n\ntext \\<open>\n\\<^enum> Formulate a predicate that is true iff a given relation\n        @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"} is reflexive.\n\\<^enum> Formulate a predicate that is true iff a given relation\n        @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"} is transitive.\n\\<^enum> Formulate a predicate that is true iff a given relation\n        @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"} is symmetric.\n\\<^enum> Formulate a predicate that is true iff a given relation\n        @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"} is an equivalence relation.\n\\<^enum> Formulate a predicate that is true iff a given relation.\n        @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"} is a total order.\n\\<close>\n\ntype_synonym 'a Rel = \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n\nabbreviation reflexive :: \"'a Rel \\<Rightarrow> bool\" where\n  \"reflexive R \\<equiv> \\<forall> A. R A A\"\n\nabbreviation transitive :: \"'a Rel \\<Rightarrow> bool\" where\n  \"transitive R \\<equiv> \\<forall> A. \\<forall> B. \\<forall> C. R A B \\<and> R B C \\<longrightarrow> R A C\"\n\nabbreviation symmetric :: \"'a Rel \\<Rightarrow> bool\" where\n  \"symmetric R \\<equiv> \\<forall> A. \\<forall> B. R A B \\<longrightarrow> R B A\"\n\nabbreviation equivalence :: \"'a Rel \\<Rightarrow> bool\" where\n  \"equivalence R \\<equiv> reflexive R \\<and> transitive R \\<and> symmetric R\"\n\nabbreviation totalOrder :: \"'A Rel \\<Rightarrow> bool\" where\n  \"totalOrder R \\<equiv> reflexive R \\<and> transitive R \\<and> \\<not> symmetric R \\<and> (\\<forall> A. \\<forall> B. R A B \\<or> R B A)\"\n\n\ntext \\<open>\nBonus-task (harder):\n\\<^enum> Formulate a function that returns the reflexive closure\n        of a relation  @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"}.\n\\<^enum> Formulate a function that returns the transitive closure\n        of a relation  @{term \"R :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"}.\n\\<close> \nfun reflexclosure :: \"'a Rel \\<Rightarrow> 'a Rel\" where\n  \"reflexclosure R = (\\<lambda> x. \\<lambda> y. R x y \\<or> x = y)\"\n\nfun transitiveclosure :: \"'a Rel \\<Rightarrow> 'a Rel\" where\n(*\n  \"transitiveclosure = (\\<lambda> x. \\<lambda> y. R x y \\<or> (\\<exists> z. (transitiveclosure R) x z \\<and> (transitiveclosure R) z y))\"\n*)\n  \"transitiveclosure = (\\<lambda> x. \\<lambda> y. \\<forall> S. transitive S \\<rightarrow> ((\\<forall> a. \\<forall> b. R a b \\<longrightarrow> S a b) \\<longrightarrow> S x y))\"\n\n(* term \"(op =) b\" *)\n\ntext \"You can verify your definitions using by proving:\"\n\nlemma \"\\<forall>R. trans (transclosure R)\" oops\nlemma \"\\<forall>R. \\<forall>x. \\<forall>y. R x y \\<longrightarrow> (transclosure R) x y\" oops\n\nend", "meta": {"author": "MrChico", "repo": "CompMeta", "sha": "6ea156d26df6feaac10d652a3743252f7112655a", "save_path": "github-repos/isabelle/MrChico-CompMeta", "path": "github-repos/isabelle/MrChico-CompMeta/CompMeta-6ea156d26df6feaac10d652a3743252f7112655a/as05/Tutorial5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802507195635, "lm_q2_score": 0.8652240808393983, "lm_q1q2_score": 0.7946912306979744}}
{"text": "section \\<open>An ordinal partition theorem by Jean A. Larson\\<close>\n\ntext \\<open>Jean A. Larson,\n     A short proof of a partition theorem for the ordinal $\\omega^\\omega$.\n     \\emph{Annals of Mathematical Logic}, 6:129–145, 1973.\\<close>\n\ntheory Omega_Omega\n  imports \"HOL-Library.Product_Lexorder\" Erdos_Milner\n\nbegin\n\nabbreviation \"list_of \\<equiv> sorted_list_of_set\"\n\nsubsection \\<open>Cantor normal form for ordinals below @{term \"\\<omega>\\<up>\\<omega>\"}\\<close>\n\ntext \\<open>Unlike @{term Cantor_sum}, there is no list of ordinal exponents,\nwhich are instead taken as consecutive. We obtain an order-isomorphism between @{term \"\\<omega>\\<up>\\<omega>\"}\nand increasing lists of natural numbers (ordered lexicographically).\\<close>\n\nfun omega_sum_aux  where\n  Nil: \"omega_sum_aux 0 _ = 0\"\n| Suc: \"omega_sum_aux (Suc n) [] = 0\"\n| Cons: \"omega_sum_aux (Suc n) (m#ms) = (\\<omega>\\<up>n) * (ord_of_nat m) + omega_sum_aux n ms\"\n\nabbreviation omega_sum where \"omega_sum ms \\<equiv> omega_sum_aux (length ms) ms\"\n\ntext \\<open>A normal expansion has no leading zeroes\\<close>\ninductive normal:: \"nat list \\<Rightarrow> bool\" where\n  normal_Nil[iff]: \"normal []\"\n| normal_Cons:     \"m > 0 \\<Longrightarrow> normal (m#ms)\"\n\ninductive_simps normal_Cons_iff [simp]: \"normal (m#ms)\"\n\nlemma omega_sum_0_iff [simp]: \"normal ns \\<Longrightarrow> omega_sum ns = 0 \\<longleftrightarrow> ns = []\"\n  by (induction ns rule: normal.induct) auto\n\nlemma Ord_omega_sum_aux [simp]: \"Ord (omega_sum_aux k ms)\"\n  by (induction rule: omega_sum_aux.induct) auto\n\nlemma Ord_omega_sum: \"Ord (omega_sum ms)\"\n  by simp\n\nlemma omega_sum_less_\\<omega>\\<omega> [intro]: \"omega_sum ms < \\<omega>\\<up>\\<omega>\"\nproof (induction ms)\n  case (Cons m ms)\n  have \"\\<omega> \\<up> (length ms) * ord_of_nat m \\<in> elts (\\<omega> \\<up> Suc (length ms))\"\n    using Ord_mem_iff_lt by auto\n  then have \"\\<omega>\\<up>(length ms) * ord_of_nat m \\<in> elts (\\<omega>\\<up>\\<omega>)\"\n    using Ord_ord_of_nat oexp_mono_le omega_nonzero ord_of_nat_le_omega by blast\n  with Cons show ?case\n    by (auto simp: mult_succ OrdmemD oexp_less indecomposableD indecomposable_\\<omega>_power)\nqed (auto simp: zero_less_Limit)\n\nlemma omega_sum_aux_less: \"omega_sum_aux k ms < \\<omega> \\<up> k\"\nproof (induction rule: omega_sum_aux.induct)\n  case (3 n m ms)\n  have \" \\<omega>\\<up>n * ord_of_nat m + \\<omega>\\<up>n < \\<omega>\\<up>n * \\<omega>\"\n    by (metis Ord_ord_of_nat \\<omega>_power_succ_gtr mult_succ oexp_succ ord_of_nat.simps(2))\n  with 3 show ?case\n    using dual_order.strict_trans by force\nqed auto\n\nlemma omega_sum_less: \"omega_sum ms < \\<omega> \\<up> (length ms)\"\n  by (rule omega_sum_aux_less)\n\nlemma omega_sum_ge: \"m \\<noteq> 0 \\<Longrightarrow> \\<omega> \\<up> (length ms) \\<le> omega_sum (m#ms)\"\n  apply clarsimp\n  by (metis Ord_ord_of_nat add_le_cancel_left0 le_mult Nat.neq0_conv ord_of_eq_0_iff vsubsetD)\n\nlemma omega_sum_length_less:\n  assumes \"normal ns\" \"length ms < length ns\"\n  shows \"omega_sum ms < omega_sum ns\"\n  using assms\nproof (induction rule: normal.induct)\n  case (normal_Cons n ns')\n  have \"\\<omega> \\<up> length ms \\<le> \\<omega> \\<up> length ns'\"\n    using normal_Cons oexp_mono_le by auto\n  then show ?case\n    by (metis gr_implies_not_zero less_le_trans normal_Cons.hyps omega_sum_aux_less omega_sum_ge)\nqed auto\n\nlemma omega_sum_length_leD:\n  assumes \"omega_sum ms \\<le> omega_sum ns\" \"normal ms\"\n  shows \"length ms \\<le> length ns\"\n  by (meson assms leD leI omega_sum_length_less)\n\n\nlemma omega_sum_less_eqlen_iff_cases [simp]:\n  assumes \"length ms = length ns\"\n   shows \"omega_sum (m#ms) < omega_sum (n#ns)\n          \\<longleftrightarrow> m<n \\<or> m=n \\<and> omega_sum ms < omega_sum ns\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  have \"\\<not> Suc n < Suc m\"\n    using omega_sum_less [of ms] omega_sum_less [of ns] L assms mult_nat_less_add_less by fastforce\n  with L assms show ?rhs\n    by auto\nqed (auto simp: mult_nat_less_add_less omega_sum_aux_less assms)\n\nlemma omega_sum_lex_less_iff_cases:\n   \"((length ms, omega_sum (m#ms)), (length ns, omega_sum (n#ns))) \\<in> less_than <*lex*> VWF\n   \\<longleftrightarrow> length ms < length ns\n            \\<or> length ms = length ns \\<and> m<n\n            \\<or> m=n \\<and> ((length ms, omega_sum ms), (length ns, omega_sum ns)) \\<in> less_than <*lex*> VWF\"\n  using omega_sum_less_eqlen_iff_cases by force\n\nlemma omega_sum_less_iff_cases:\n  assumes \"m > 0\" \"n > 0\"\n  shows \"omega_sum (m#ms) < omega_sum (n#ns)\n          \\<longleftrightarrow> length ms < length ns\n            \\<or> length ms = length ns \\<and> m<n\n            \\<or> length ms = length ns \\<and> m=n \\<and> omega_sum ms < omega_sum ns\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    by (metis Suc_less_eq \\<open>m>0\\<close> length_Cons less_asym nat_neq_iff normal_Cons omega_sum_length_less omega_sum_less_eqlen_iff_cases)\nnext\n  assume ?rhs then show ?lhs\n    by (metis (full_types) Suc_less_eq \\<open>n>0\\<close> length_Cons normal_Cons omega_sum_length_less omega_sum_less_eqlen_iff_cases)\nqed\n\nlemma omega_sum_less_iff:\n  \"((length ms, omega_sum ms), (length ns, omega_sum ns)) \\<in> less_than <*lex*> VWF\n   \\<longleftrightarrow> (ms,ns) \\<in> lenlex less_than\"\nproof (induction ms arbitrary: ns)\n  case (Cons m ms)\n  then show ?case\n  proof (induction ns)\n    case (Cons n ns')\n    show ?case\n      using Cons.prems Cons_lenlex_iff omega_sum_less_eqlen_iff_cases by fastforce\n  qed auto\nqed auto\n\nlemma eq_omega_sum_less_iff:\n  assumes \"length ms = length ns\"\n  shows \"(omega_sum ms, omega_sum ns) \\<in> VWF \\<longleftrightarrow> (ms,ns) \\<in> lenlex less_than\"\n  by (metis assms in_lex_prod less_not_refl less_than_iff omega_sum_less_iff)\n\nlemma eq_omega_sum_eq_iff:\n  assumes \"length ms = length ns\"\n  shows \"omega_sum ms = omega_sum ns \\<longleftrightarrow> ms=ns\"\nproof\n  assume \"omega_sum ms = omega_sum ns\"\n  then have \"(omega_sum ms, omega_sum ns) \\<notin> VWF\" \"(omega_sum ns, omega_sum ms) \\<notin> VWF\"\n    by auto\n  then obtain \"(ms,ns) \\<notin> lenlex less_than\" \"(ns,ms) \\<notin> lenlex less_than\"\n    using assms eq_omega_sum_less_iff by metis\n  moreover have \"total (lenlex less_than)\"\n    by (simp add: total_lenlex total_less_than)\n  ultimately show \"ms=ns\"\n    by (meson UNIV_I total_on_def)\nqed auto\n\nlemma inj_omega_sum: \"inj_on omega_sum {l. length l = n}\"\n  unfolding inj_on_def using eq_omega_sum_eq_iff by fastforce\n\nlemma Ex_omega_sum: \"\\<gamma> \\<in> elts (\\<omega>\\<up>n) \\<Longrightarrow> \\<exists>ns. \\<gamma> = omega_sum ns \\<and> length ns = n\"\nproof (induction n arbitrary: \\<gamma>)\n  case 0\n  then show ?case\n    by (rule_tac x=\"[]\" in exI) auto\nnext\n  case (Suc n)\n  then obtain k::nat where k: \"\\<gamma> \\<in> elts (\\<omega> \\<up> n * k)\"\n       and kmin: \"\\<And>k'. k'<k \\<Longrightarrow> \\<gamma> \\<notin> elts (\\<omega> \\<up> n * k')\"\n    by (metis Ord_ord_of_nat elts_mult_\\<omega>E oexp_succ ord_of_nat.simps(2))\n  show ?case\n  proof (cases k)\n    case (Suc k')\n    then obtain \\<delta> where \\<delta>: \"\\<gamma> = (\\<omega> \\<up> n * k') + \\<delta>\"\n      by (metis lessI mult_succ ord_of_nat.simps(2) k kmin mem_plus_V_E)\n    then have \\<delta>in: \"\\<delta> \\<in> elts (\\<omega> \\<up> n)\"\n      using Suc k mult_succ by auto\n    then obtain ns where ns: \"\\<delta> = omega_sum ns\" and len: \"length ns = n\"\n      using Suc.IH by auto\n    moreover have \"omega_sum ns < \\<omega>\\<up>n\"\n      using OrdmemD ns \\<delta>in by auto\n    ultimately show ?thesis\n      by (rule_tac x=\"k'#ns\" in exI) (simp add: \\<delta>)\n  qed (use k in auto)\nqed\n\nlemma omega_sum_drop [simp]: \"omega_sum (dropWhile (\\<lambda>n. n=0) ns) = omega_sum ns\"\n  by (induction ns) auto\n\nlemma normal_drop [simp]: \"normal (dropWhile (\\<lambda>n. n=0) ns)\"\n  by (induction ns) auto\n\nlemma omega_sum_\\<omega>\\<omega>:\n  assumes \"\\<gamma> \\<in> elts (\\<omega>\\<up>\\<omega>)\"\n  obtains ns where \"\\<gamma> = omega_sum ns\" \"normal ns\"\nproof -\n  obtain ms where \"\\<gamma> = omega_sum ms\"\n    using assms Ex_omega_sum by (auto simp: oexp_Limit elts_\\<omega>)\n  show thesis\n  proof\n    show \"\\<gamma> = omega_sum (dropWhile (\\<lambda>n. n=0) ms)\"\n      by (simp add: \\<open>\\<gamma> = omega_sum ms\\<close>)\n    show \"normal (dropWhile (\\<lambda>n. n=0) ms)\"\n      by auto\n  qed\nqed\n\ndefinition Cantor_\\<omega>\\<omega> :: \"V \\<Rightarrow> nat list\"\n  where \"Cantor_\\<omega>\\<omega> \\<equiv> \\<lambda>x. SOME ns. x = omega_sum ns \\<and> normal ns\"\n\nlemma\n  assumes \"\\<gamma> \\<in> elts (\\<omega>\\<up>\\<omega>)\"\n  shows Cantor_\\<omega>\\<omega>: \"omega_sum (Cantor_\\<omega>\\<omega> \\<gamma>) = \\<gamma>\"\n    and normal_Cantor_\\<omega>\\<omega>: \"normal (Cantor_\\<omega>\\<omega> \\<gamma>)\"\n  by (metis (mono_tags, lifting) Cantor_\\<omega>\\<omega>_def assms omega_sum_\\<omega>\\<omega> someI)+\n\n\nsubsection \\<open>Larson's set $W(n)$\\<close>\n\ndefinition WW :: \"nat list set\"\n  where \"WW \\<equiv> {l. strict_sorted l}\"\n\nfun into_WW :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"into_WW k [] = []\"\n| \"into_WW k (n#ns) = (k+n) # into_WW (Suc (k+n)) ns\"\n\nfun from_WW :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"from_WW k [] = []\"\n| \"from_WW k (n#ns) = (n - k) # from_WW (Suc n) ns\"\n\nlemma from_into_WW [simp]: \"from_WW k (into_WW k ns) = ns\"\n  by (induction ns arbitrary: k) auto\n\nlemma inj_into_WW: \"inj (into_WW k)\"\n  by (metis from_into_WW injI)\n\nlemma into_from_WW_aux:\n  \"\\<lbrakk>strict_sorted ns; \\<forall>n\\<in>list.set ns. k \\<le> n\\<rbrakk> \\<Longrightarrow> into_WW k (from_WW k ns) = ns\"\n  by (induction ns arbitrary: k) (auto simp: Suc_leI)\n\nlemma into_from_WW [simp]: \"strict_sorted ns \\<Longrightarrow> into_WW 0 (from_WW 0 ns) = ns\"\n  by (simp add: into_from_WW_aux)\n\nlemma into_WW_imp_ge: \"y \\<in> List.set (into_WW x ns) \\<Longrightarrow> x \\<le> y\"\n  by (induction ns arbitrary: x) fastforce+\n\nlemma strict_sorted_into_WW: \"strict_sorted (into_WW x ns)\"\n  by (induction ns arbitrary: x) (auto simp: dest: into_WW_imp_ge)\n\nlemma length_into_WW: \"length (into_WW x ns) = length ns\"\n  by (induction ns arbitrary: x) auto\n\nlemma WW_eq_range_into: \"WW = range (into_WW 0)\"\nproof -\n  have \"\\<And>ns. strict_sorted ns \\<Longrightarrow> ns \\<in> range (into_WW 0)\"\n    by (metis into_from_WW rangeI)\n  then show ?thesis by (auto simp: WW_def strict_sorted_into_WW)\nqed\n\nlemma into_WW_lenlex_iff: \"(into_WW k ms, into_WW k ns) \\<in> lenlex less_than \\<longleftrightarrow> (ms, ns) \\<in> lenlex less_than\"\nproof (induction ms arbitrary: ns k)\n  case Nil\n  then show ?case\n    by simp (metis length_0_conv length_into_WW)\nnext\n  case (Cons m ms)\n  then show ?case\n    by (induction ns) (auto simp: Cons_lenlex_iff length_into_WW)\nqed\n\nlemma wf_llt [simp]: \"wf (lenlex less_than)\" and trans_llt [simp]: \"trans (lenlex less_than)\"\n  by blast+\n\nlemma total_llt [simp]: \"total_on A (lenlex less_than)\"\n  by (meson UNIV_I total_lenlex total_less_than total_on_def)\n\nlemma omega_sum_1_less:\n  assumes \"(ms,ns) \\<in> lenlex less_than\" shows \"omega_sum (1#ms) < omega_sum (1#ns)\"\nproof -\n  have \"omega_sum (1#ms) < omega_sum (1#ns)\" if \"length ms < length ns\"\n    using omega_sum_less_iff_cases that zero_less_one by blast\n  then show ?thesis\n    using assms by (auto simp: mult_succ simp flip: omega_sum_less_iff)\nqed\n\nlemma ordertype_WW_1: \"ordertype WW (lenlex less_than) \\<le> ordertype UNIV (lenlex less_than)\"\n  by (rule ordertype_mono) auto\n\nlemma ordertype_WW_2: \"ordertype UNIV (lenlex less_than) \\<le> \\<omega>\\<up>\\<omega>\"\nproof (rule ordertype_inc_le_Ord)\n  show \"range (\\<lambda>ms. omega_sum (1#ms)) \\<subseteq> elts (\\<omega>\\<up>\\<omega>)\"\n    by (meson Ord_\\<omega> Ord_mem_iff_lt Ord_oexp Ord_omega_sum image_subset_iff omega_sum_less_\\<omega>\\<omega>)\nqed (use omega_sum_1_less in auto)\n\nlemma ordertype_WW_3: \"\\<omega>\\<up>\\<omega> \\<le> ordertype WW (lenlex less_than)\"\nproof -\n  define \\<pi> where \"\\<pi> \\<equiv> into_WW 0 \\<circ> Cantor_\\<omega>\\<omega>\"\n  have \\<omega>\\<omega>: \"\\<omega>\\<up>\\<omega> = tp (elts (\\<omega>\\<up>\\<omega>))\"\n    by simp\n  also have \"\\<dots> \\<le> ordertype WW (lenlex less_than)\"\n  proof (rule ordertype_inc_le)\n    fix \\<alpha> \\<beta>\n    assume \\<alpha>: \"\\<alpha> \\<in> elts (\\<omega>\\<up>\\<omega>)\" and \\<beta>: \"\\<beta> \\<in> elts (\\<omega>\\<up>\\<omega>)\" and \"(\\<alpha>, \\<beta>) \\<in> VWF\"\n    then obtain *: \"Ord \\<alpha>\" \"Ord \\<beta>\" \"\\<alpha><\\<beta>\"\n      by (metis Ord_in_Ord Ord_ordertype VWF_iff_Ord_less \\<omega>\\<omega>)\n    then have \"length (Cantor_\\<omega>\\<omega> \\<alpha>) \\<le> length (Cantor_\\<omega>\\<omega> \\<beta>)\"\n      using \\<alpha> \\<beta> by (simp add: Cantor_\\<omega>\\<omega> normal_Cantor_\\<omega>\\<omega> omega_sum_length_leD)\n    with \\<alpha> \\<beta> * have \"(Cantor_\\<omega>\\<omega> \\<alpha>, Cantor_\\<omega>\\<omega> \\<beta>) \\<in> lenlex less_than\"\n      by (auto simp: Cantor_\\<omega>\\<omega> simp flip: omega_sum_less_iff)\n    then show \"(\\<pi> \\<alpha>, \\<pi> \\<beta>) \\<in> lenlex less_than\"\n      by (simp add: \\<pi>_def into_WW_lenlex_iff)\n  qed (auto simp: \\<pi>_def WW_def strict_sorted_into_WW)\n  finally show \"\\<omega>\\<up>\\<omega> \\<le> ordertype WW (lenlex less_than)\" .\nqed\n\nlemma ordertype_WW: \"ordertype WW (lenlex less_than) = \\<omega>\\<up>\\<omega>\"\n  and ordertype_UNIV_\\<omega>\\<omega>: \"ordertype UNIV (lenlex less_than) = \\<omega>\\<up>\\<omega>\"\n  using ordertype_WW_1 ordertype_WW_2 ordertype_WW_3 by auto\n\n\nlemma ordertype_\\<omega>\\<omega>:\n  fixes F :: \"nat \\<Rightarrow> nat list set\"\n  assumes \"\\<And>j::nat. ordertype (F j) (lenlex less_than) = \\<omega>\\<up>j\"\n  shows \"ordertype (\\<Union>j. F j) (lenlex less_than) = \\<omega>\\<up>\\<omega>\"\nproof (rule antisym)\n  show \"ordertype (\\<Union> (range F)) (lenlex less_than) \\<le> \\<omega> \\<up> \\<omega>\"\n    by (metis ordertype_UNIV_\\<omega>\\<omega> ordertype_mono small top_greatest trans_llt wf_llt)\n  have \"\\<And>n. \\<omega> \\<up> ord_of_nat n \\<le> ordertype (\\<Union> (range F)) (lenlex less_than)\"\n    by (metis TC_small Union_upper assms ordertype_mono rangeI trans_llt wf_llt)\n  then show \"\\<omega> \\<up> \\<omega> \\<le> ordertype (\\<Union> (range F)) (lenlex less_than)\"\n    by (auto simp: oexp_\\<omega>_Limit ZFC_in_HOL.SUP_le_iff elts_\\<omega>)\nqed\n\n\n\ndefinition WW_seg :: \"nat \\<Rightarrow> nat list set\"\n  where \"WW_seg n \\<equiv> {l \\<in> WW. length l = n}\"\n\nlemma WW_seg_subset_WW: \"WW_seg n \\<subseteq> WW\"\n  by (auto simp: WW_seg_def)\n\nlemma WW_eq_UN_WW_seg: \"WW = (\\<Union> n. WW_seg n)\"\n  by (auto simp: WW_seg_def)\n\nlemma ordertype_list_seg: \"ordertype {l. length l = n} (lenlex less_than) = \\<omega>\\<up>n\"\nproof -\n  have \"bij_betw omega_sum {l. length l = n} (elts (\\<omega>\\<up>n))\"\n    unfolding WW_seg_def bij_betw_def\n    by (auto simp: inj_omega_sum Ord_mem_iff_lt omega_sum_less dest: Ex_omega_sum)\n  then show ?thesis\n    by (force simp: ordertype_eq_iff simp flip: eq_omega_sum_less_iff)\nqed\n\nlemma ordertype_WW_seg: \"ordertype (WW_seg n) (lenlex less_than) = \\<omega>\\<up>n\"\n  (is \"ordertype ?W ?R = \\<omega>\\<up>n\")\nproof -\n  have \"ordertype {l. length l = n} ?R = ordertype ?W ?R\"\n  proof (subst ordertype_eq_ordertype)\n    show \"\\<exists>f. bij_betw f {l. length l = n} ?W \\<and> (\\<forall>x\\<in>{l. length l = n}. \\<forall>y\\<in>{l. length l = n}. ((f x, f y) \\<in> lenlex less_than) = ((x, y) \\<in> lenlex less_than))\"\n    proof (intro exI conjI)\n      have \"inj_on (into_WW 0) {l. length l = n}\"\n        by (metis from_into_WW inj_onI)\n      then show \"bij_betw (into_WW 0) {l. length l = n} ?W\"\n        by (auto simp: bij_betw_def WW_seg_def WW_eq_range_into length_into_WW)\n    qed (simp add: into_WW_lenlex_iff)\n  qed auto\n  then show ?thesis\n    using ordertype_list_seg by auto\nqed\n\n\nsubsection \\<open>Definitions required for the lemmas\\<close>\n\nsubsubsection \\<open>Larson's \"$<$\"-relation on ordered lists\\<close>\n\ninstantiation list :: (ord)ord\nbegin\n\ndefinition \"xs < ys \\<equiv> xs \\<noteq> [] \\<and> ys \\<noteq> [] \\<longrightarrow> last xs < hd ys\" for xs ys :: \"'a list\"\ndefinition \"xs \\<le> ys \\<equiv> xs < ys \\<or> xs = ys\" for xs ys :: \"'a list\"\n\ninstance\n  by standard\n\nend\n\nlemma less_Nil [simp]: \"xs < []\" \"[] < xs\"\n  by (auto simp: less_list_def)\n\nlemma less_sets_imp_list_less:\n  assumes \"list.set xs \\<lless> list.set ys\"\n  shows \"xs < ys\"\n  by (metis assms last_in_set less_list_def less_sets_def list.set_sel(1))\n\nlemma less_sets_imp_sorted_list_of_set:\n  assumes \"A \\<lless> B\" \"finite A\" \"finite B\"\n  shows \"list_of A < list_of B\"\n  by (simp add: assms less_sets_imp_list_less)\n\nlemma sorted_list_of_set_imp_less_sets:\n  assumes \"xs < ys\" \"sorted xs\" \"sorted ys\"\n  shows \"list.set xs \\<lless> list.set ys\"\n  using assms sorted_hd_le sorted_le_last\n  by (force simp: less_list_def less_sets_def intro: order.trans)\n\nlemma less_list_iff_less_sets:\n  assumes \"sorted xs\" \"sorted ys\"\n  shows \"xs < ys \\<longleftrightarrow> list.set xs \\<lless> list.set ys\"\n  using assms sorted_hd_le sorted_le_last\n  by (force simp: less_list_def less_sets_def intro: order.trans)\n\nlemma strict_sorted_append_iff:\n  \"strict_sorted (xs @ ys) \\<longleftrightarrow> xs < ys \\<and> strict_sorted xs \\<and> strict_sorted ys\" (is \"?lhs = ?rhs\")\n  by (metis less_list_iff_less_sets less_setsD sorted_wrt_append strict_sorted_imp_less_sets strict_sorted_imp_sorted)\n\nlemma singleton_less_list_iff: \"sorted xs \\<Longrightarrow> [n] < xs \\<longleftrightarrow> {..n} \\<inter> list.set xs = {}\"\n  apply (simp add: less_list_def disjoint_iff)\n  by (metis empty_iff less_le_trans list.set(1) list.set_sel(1) not_le sorted_hd_le)\n\nlemma less_hd_imp_less: \"xs < [hd ys] \\<Longrightarrow> xs < ys\"\n  by (simp add: less_list_def)\n\nlemma strict_sorted_concat_I:\n  assumes \"\\<And>x. x \\<in> list.set xs \\<Longrightarrow> strict_sorted x\"\n          \"\\<And>n. Suc n < length xs \\<Longrightarrow> xs!n < xs!Suc n\"\n          \"xs \\<in> lists (- {[]})\"\n  shows \"strict_sorted (concat xs)\"\n  using assms\nproof (induction xs)\n  case (Cons x xs)\n  then have \"x < concat xs\"\n    apply (simp add: less_list_def)\n    by (metis Compl_iff hd_concat insertI1 length_greater_0_conv length_pos_if_in_set list.sel(1) lists.cases nth_Cons_0)\n  with Cons show ?case\n    by (force simp: strict_sorted_append_iff)\nqed auto\n\n\nsubsection \\<open>Nash Williams for lists\\<close>\n\nsubsubsection \\<open>Thin sets of lists\\<close>\n\ninductive initial_segment :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"initial_segment xs (xs@ys)\"\n\ndefinition thin :: \"'a list set \\<Rightarrow> bool\"\n  where \"thin A \\<equiv> \\<not> (\\<exists>x y. x \\<in> A \\<and> y \\<in> A \\<and> x \\<noteq> y \\<and> initial_segment x y)\"\n\nlemma initial_segment_ne:\n  assumes \"initial_segment xs ys\" \"xs \\<noteq> []\"\n  shows \"ys \\<noteq> [] \\<and> hd ys = hd xs\"\n  using assms by (auto elim!: initial_segment.cases)\n\nlemma take_initial_segment:\n  assumes \"initial_segment xs ys\" \"k \\<le> length xs\"\n  shows \"take k xs = take k ys\"\n  by (metis append_eq_conv_conj assms initial_segment.cases min_def take_take)\n\nlemma initial_segment_length_eq:\n  assumes \"initial_segment xs ys\" \"length xs = length ys\"\n  shows \"xs = ys\"\n  using assms initial_segment.cases by fastforce\n\nlemma initial_segment_Nil [simp]: \"initial_segment [] ys\"\n  by (simp add: initial_segment.simps)\n\nlemma initial_segment_Cons [simp]: \"initial_segment (x#xs) (y#ys) \\<longleftrightarrow> x=y \\<and> initial_segment xs ys\"\n  by (metis append_Cons initial_segment.simps list.inject)\n\nlemma init_segment_iff_initial_segment:\n  assumes \"strict_sorted xs\" \"strict_sorted ys\"\n  shows \"init_segment (list.set xs) (list.set ys) \\<longleftrightarrow> initial_segment xs ys\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain S' where S': \"list.set ys = list.set xs \\<union> S'\" \"list.set xs \\<lless> S'\"\n    by (auto simp: init_segment_def)\n  then have \"finite S'\"\n    by (metis List.finite_set finite_Un)\n  have \"ys = xs @ list_of S'\"\n    using S' \\<open>strict_sorted xs\\<close>\n  proof (induction xs)\n    case Nil\n    with \\<open>strict_sorted ys\\<close> show ?case\n      by auto\n  next\n    case (Cons a xs)\n    with \\<open>finite S'\\<close> have \"ys = a # xs @ list_of S'\"\n      by (metis List.finite_set append_Cons assms(2) sorted_list_of_set_Un sorted_list_of_set_set_of)\n    then show ?case\n      by (auto simp: Cons)\n  qed\n  then show ?rhs\n    using initial_segment.intros by blast\nnext\n  assume ?rhs\n  then show ?lhs\n  proof cases\n    case (1 ys)\n    with assms(2) show ?thesis\n      by (metis init_segment_def set_append sorted_list_of_set_imp_less_sets strict_sorted_append_iff strict_sorted_imp_sorted)\n  qed\nqed\n\ntheorem Nash_Williams_WW:\n  fixes h :: \"nat list \\<Rightarrow> nat\"\n  assumes \"infinite M\" and h: \"h ` {l \\<in> A. List.set l \\<subseteq> M} \\<subseteq> {..<2}\" and \"thin A\" \"A \\<subseteq> WW\"\n  obtains i N where \"i < 2\" \"infinite N\" \"N \\<subseteq> M\" \"h ` {l \\<in> A. List.set l \\<subseteq> N} \\<subseteq> {i}\"\nproof -\n  define AM where \"AM \\<equiv> {l \\<in> A. List.set l \\<subseteq> M}\"\n  have \"thin_set (list.set ` A)\"\n    using \\<open>thin A\\<close> \\<open>A \\<subseteq> WW\\<close> unfolding thin_def thin_set_def WW_def\n    by (auto simp: subset_iff init_segment_iff_initial_segment)\n  then have \"thin_set (list.set ` AM)\"\n    by (simp add: AM_def image_subset_iff thin_set_def)\n  then have \"Ramsey (list.set ` AM) 2\"\n    using Nash_Williams_2 by metis\n  moreover have \"(h \\<circ> list_of) \\<in> list.set ` AM \\<rightarrow> {..<2}\"\n    unfolding AM_def\n  proof clarsimp\n    fix l\n    assume \"l \\<in> A\" \"list.set l \\<subseteq> M\"\n    then have \"strict_sorted l\"\n      using WW_def \\<open>A \\<subseteq> WW\\<close> by blast\n    then show \"h (list_of (list.set l)) < 2\"\n      using h \\<open>l \\<in> A\\<close> \\<open>list.set l \\<subseteq> M\\<close> by auto\n  qed\n  ultimately obtain N i where N: \"N \\<subseteq> M\" \"infinite N\" \"i<2\" \n              and \"list.set ` AM \\<inter> Pow N \\<subseteq> (h \\<circ> list_of) -` {i}\"\n    unfolding Ramsey_eq by (metis \\<open>infinite M\\<close>)\n  then have N_disjoint: \"(h \\<circ> list_of) -` {1-i} \\<inter> (list.set ` AM) \\<inter> Pow N = {}\"\n    unfolding subset_vimage_iff less_2_cases_iff by force\n  have \"h ` {l \\<in> A. list.set l \\<subseteq> N} \\<subseteq> {i}\"\n  proof clarify\n    fix l\n    assume \"l \\<in> A\" and \"list.set l \\<subseteq> N\"\n    then have \"h l < 2\"\n      using h \\<open>N \\<subseteq> M\\<close> by force\n    with \\<open>i<2\\<close> have \"h l \\<noteq> Suc 0 - i \\<Longrightarrow> h l = i\"\n      by (auto simp: eval_nat_numeral less_Suc_eq)\n    moreover have \"strict_sorted l\"\n      using \\<open>A \\<subseteq> WW\\<close> \\<open>l \\<in> A\\<close> unfolding WW_def by blast\n    moreover have \"h (list_of (list.set l)) = 1 - i \\<longrightarrow> \\<not> (list.set l \\<subseteq> N)\"\n      using N_disjoint \\<open>N \\<subseteq> M\\<close> \\<open>l \\<in> A\\<close> by (auto simp: AM_def)\n    ultimately\n    show \"h l = i\"\n      using N \\<open>N \\<subseteq> M\\<close> \\<open>l \\<in> A\\<close> \\<open>list.set l \\<subseteq> N\\<close>\n      by (auto simp: vimage_def set_eq_iff AM_def WW_def subset_iff)\n  qed\n  then show thesis\n    using that \\<open>i<2\\<close> N by auto\nqed\n\nsubsection \\<open>Specialised functions on lists\\<close>\n\nlemma mem_lists_non_Nil: \"xss \\<in> lists (- {[]}) \\<longleftrightarrow> (\\<forall>x \\<in> list.set xss. x \\<noteq> [])\"\n  by auto\n\nfun acc_lengths :: \"nat \\<Rightarrow> 'a list list \\<Rightarrow> nat list\"\n  where \"acc_lengths acc [] = []\"\n      | \"acc_lengths acc (l#ls) = (acc + length l) # acc_lengths (acc + length l) ls\"\n\nlemma length_acc_lengths [simp]: \"length (acc_lengths acc ls) = length ls\"\n  by (induction ls arbitrary: acc) auto\n\nlemma acc_lengths_eq_Nil_iff [simp]: \"acc_lengths acc ls = [] \\<longleftrightarrow> ls = []\"\n  by (metis length_0_conv length_acc_lengths)\n\nlemma set_acc_lengths:\n  assumes \"ls \\<in> lists (- {[]})\" shows \"list.set (acc_lengths acc ls) \\<subseteq> {acc<..}\"\n  using assms by (induction ls rule: acc_lengths.induct) fastforce+\n\ntext \\<open>Useful because @{text acc_lengths.simps} will sometimes be deleted from the simpset.\\<close>\nlemma hd_acc_lengths [simp]: \"hd (acc_lengths acc (l#ls)) = acc + length l\"\n  by simp\n\nlemma last_acc_lengths [simp]:\n  \"ls \\<noteq> [] \\<Longrightarrow> last (acc_lengths acc ls) = acc + sum_list (map length ls)\"\nby (induction acc ls rule: acc_lengths.induct) auto\n\nlemma nth_acc_lengths [simp]:\n  \"\\<lbrakk>ls \\<noteq> []; k < length ls\\<rbrakk> \\<Longrightarrow> acc_lengths acc ls ! k = acc + sum_list (map length (take (Suc k) ls))\"\n  by (induction acc ls arbitrary: k rule: acc_lengths.induct) (fastforce simp: less_Suc_eq nth_Cons')+\n\nlemma acc_lengths_plus: \"acc_lengths (m+n) as = map ((+)m) (acc_lengths n as)\"\n  by (induction n as arbitrary: m rule: acc_lengths.induct) (auto simp: add.assoc)\n\nlemma acc_lengths_shift: \"NO_MATCH 0 acc \\<Longrightarrow> acc_lengths acc as = map ((+)acc) (acc_lengths 0 as)\"\n  by (metis acc_lengths_plus add.comm_neutral)\n\nlemma length_concat_acc_lengths:\n  \"ls \\<noteq> [] \\<Longrightarrow> k + length (concat ls) \\<in> list.set (acc_lengths k ls)\"\n  by (metis acc_lengths_eq_Nil_iff last_acc_lengths last_in_set length_concat)\n\nlemma strict_sorted_acc_lengths:\n  assumes \"ls \\<in> lists (- {[]})\" shows \"strict_sorted (acc_lengths acc ls)\"\n  using assms\nproof (induction ls rule: acc_lengths.induct)\n  case (2 acc l ls)\n  then have \"strict_sorted (acc_lengths (acc + length l) ls)\"\n    by auto\n  then show ?case\n    using set_acc_lengths \"2.prems\" by auto\nqed auto\n\nlemma acc_lengths_append:\n  \"acc_lengths acc (xs @ ys)\n   = acc_lengths acc xs @ acc_lengths (acc + sum_list (map length xs)) ys\"\nby (induction acc xs rule: acc_lengths.induct) (auto simp: add.assoc)\n\n\n\nlemma length_concat_ge:\n  assumes \"as \\<in> lists (- {[]})\"\n  shows \"length (concat as) \\<ge> length as\"\n  using assms\nproof (induction as)\n  case (Cons a as)\n  then have \"length a \\<ge> Suc 0\" \"\\<And>l. l \\<in> list.set as \\<Longrightarrow> length l \\<ge> Suc 0\"\n    by (auto simp: Suc_leI)\n  then show ?case\n    using Cons.IH by force\nqed auto\n\n\nfun interact :: \"'a list list \\<Rightarrow> 'a list list \\<Rightarrow> 'a list\"\n  where\n  \"interact [] ys = concat ys\"\n| \"interact xs [] = concat xs\"\n| \"interact (x#xs) (y#ys) = x @ y @ interact xs ys\"\n\nlemma (in monoid_add) length_interact:\n  \"length (interact xs ys) = sum_list (map length xs) + sum_list (map length ys)\"\n  by (induction rule: interact.induct) (auto simp: length_concat)\n\nlemma length_interact_ge:\n  assumes \"xs \\<in> lists (- {[]})\" \"ys \\<in> lists (- {[]})\"\n  shows \"length (interact xs ys) \\<ge> length xs + length ys\"\n  by (metis add_mono assms length_concat length_concat_ge length_interact)\n\nlemma set_interact [simp]:\n  shows \"list.set (interact xs ys) = list.set (concat xs) \\<union> list.set (concat ys)\"\nby (induction rule: interact.induct) auto\n\nlemma interact_eq_Nil_iff [simp]:\n  assumes \"xs \\<in> lists (- {[]})\" \"ys \\<in> lists (- {[]})\"\n  shows \"interact xs ys = [] \\<longleftrightarrow> xs=[] \\<and> ys=[]\"\n  using length_interact_ge [OF assms]  by fastforce\n\nlemma interact_sing [simp]: \"interact [x] ys = x @ concat ys\"\n  by (metis (no_types) concat.simps(2) interact.simps neq_Nil_conv)\n\nlemma hd_interact: \"\\<lbrakk>xs \\<noteq> []; hd xs \\<noteq> []\\<rbrakk> \\<Longrightarrow> hd (interact xs ys) = hd (hd xs)\"\n  by (smt (verit, best) hd_append2 hd_concat interact.elims list.sel(1))\n\nlemma acc_lengths_concat_injective:\n  assumes \"concat as' = concat as\" \"acc_lengths n as' = acc_lengths n as\"\n  shows \"as' = as\"\n  using assms\nproof (induction as arbitrary: n as')\n  case Nil\n  then show ?case\n    by (metis acc_lengths_eq_Nil_iff)\nnext\n  case (Cons a as)\n  then obtain a' bs where \"as' = a'#bs\"\n    by (metis Suc_length_conv length_acc_lengths)\n  with Cons show ?case\n    by simp\nqed\n\nlemma acc_lengths_interact_injective:\n  assumes \"interact as' bs' = interact as bs\" \"acc_lengths a as' = acc_lengths a as\" \"acc_lengths b bs' = acc_lengths b bs\"\n  shows \"as' = as \\<and> bs' = bs\"\n  using assms\nproof (induction as bs arbitrary: a b as' bs' rule: interact.induct)\n  case (1 cs) then show ?case\n    by (metis acc_lengths_concat_injective acc_lengths_eq_Nil_iff interact.simps(1))\nnext\n  case (2 c cs)\n  then show ?case\n    by (metis acc_lengths_concat_injective acc_lengths_eq_Nil_iff interact.simps(2) list.exhaust)\nnext\n  case (3 x xs y ys) \n  then obtain a' us b' vs where \"as' = a'#us\" \"bs' = b'#vs\"\n    by (metis length_Suc_conv length_acc_lengths)\n  with 3 show ?case\n    by auto\nqed\n\n\nlemma strict_sorted_interact_I:\n  assumes \"length ys \\<le> length xs\" \"length xs \\<le> Suc (length ys)\"\n    \"\\<And>x. x \\<in> list.set xs \\<Longrightarrow> strict_sorted x\"\n    \"\\<And>y. y \\<in> list.set ys \\<Longrightarrow> strict_sorted y\"\n    \"\\<And>n. n < length ys \\<Longrightarrow> xs!n < ys!n\"\n    \"\\<And>n. Suc n < length xs \\<Longrightarrow> ys!n < xs!Suc n\"\n  assumes \"xs \\<in> lists (- {[]})\" \"ys \\<in> lists (- {[]})\"\n  shows \"strict_sorted (interact xs ys)\"\n  using assms\nproof (induction rule: interact.induct)\n  case (3 x xs y ys)\n  then have \"x < y\"\n    by force\n  moreover have \"strict_sorted (interact xs ys)\"\n    using 3 by simp (metis Suc_less_eq nth_Cons_Suc)\n  moreover have \"y < interact xs ys\"\n    using 3 apply (simp add: less_list_def)\n    by (metis hd_interact le_zero_eq length_greater_0_conv list.sel(1) list.set_sel(1) list.size(3) lists.simps mem_lists_non_Nil nth_Cons_0)\n  ultimately show ?case\n    using 3 by (simp add: strict_sorted_append_iff less_list_def)\nqed auto\n\n\nsubsection \\<open>Forms and interactions\\<close>\n\nsubsubsection \\<open>Forms\\<close>\n\ninductive Form_Body :: \"[nat, nat, nat list, nat list, nat list] \\<Rightarrow> bool\"\n  where \"Form_Body ka kb xs ys zs\"\n  if \"length xs < length ys\" \"xs = concat (a#as)\" \"ys = concat (b#bs)\"\n          \"a#as \\<in> lists (- {[]})\" \"b#bs \\<in> lists (- {[]})\"\n          \"length (a#as) = ka\" \"length (b#bs) = kb\"\n          \"c = acc_lengths 0 (a#as)\"\n          \"d = acc_lengths 0 (b#bs)\"\n          \"zs = concat [c, a, d, b] @ interact as bs\"\n          \"strict_sorted zs\"\n\n\ninductive Form :: \"[nat, nat list set] \\<Rightarrow> bool\"\n  where \"Form 0 {xs,ys}\" if \"length xs = length ys\" \"xs \\<noteq> ys\"\n      | \"Form (2*k-1) {xs,ys}\" if \"Form_Body k k xs ys zs\" \"k > 0\"\n      | \"Form (2*k)   {xs,ys}\" if \"Form_Body (Suc k) k xs ys zs\" \"k > 0\"\n\ninductive_cases Form_0_cases_raw: \"Form 0 u\"\n\nlemma Form_elim_upair:\n  assumes \"Form l U\"\n  obtains xs ys where \"xs \\<noteq> ys\" \"U = {xs,ys}\" \"length xs \\<le> length ys\"\n  using assms\n  by (smt (verit, best) Form.simps Form_Body.cases less_or_eq_imp_le nat_neq_iff)\n\n\nlemma assumes \"Form_Body ka kb xs ys zs\"\n  shows Form_Body_WW: \"zs \\<in> WW\" \n    and Form_Body_nonempty: \"length zs > 0\" \n    and Form_Body_length: \"length xs < length ys\"\n  using Form_Body.cases [OF assms] by (fastforce simp: WW_def)+\n\nlemma form_cases:\n  fixes l::nat\n  obtains (zero) \"l = 0\" | (nz) ka kb where \"l = ka+kb - 1\" \"0 < kb\" \"kb \\<le> ka\" \"ka \\<le> Suc kb\"\nproof -\n  have \"l = 0 \\<or> (\\<exists>ka kb. l = ka+kb - 1 \\<and> 0 < kb \\<and> kb \\<le> ka \\<and> ka \\<le> Suc kb)\"\n    by presburger\n  then show thesis\n    using nz zero by blast\nqed\n\nsubsubsection \\<open>Interactions\\<close>\n\nlemma interact:\n  assumes \"Form l U\" \"l>0\"\n  obtains ka kb xs ys zs where \"l = ka+kb - 1\" \"U = {xs,ys}\" \"Form_Body ka kb xs ys zs\" \"0 < kb\" \"kb \\<le> ka\" \"ka \\<le> Suc kb\"\n  using assms\n  unfolding Form.simps\n  by (smt (verit, best) add_Suc diff_Suc_1 lessI mult_2 nat_less_le order_refl)\n\n\ndefinition inter_scheme :: \"nat \\<Rightarrow> nat list set \\<Rightarrow> nat list\"\n  where \"inter_scheme l U \\<equiv> \n          SOME zs. \\<exists>k xs ys. U = {xs,ys} \\<and> \n            (l = 2*k-1 \\<and> Form_Body k k xs ys zs \\<or> l = 2*k \\<and> Form_Body (Suc k) k xs ys zs)\"\n\n\nlemma inter_scheme:\n  assumes \"Form l U\" \"l>0\"\n  obtains ka kb xs ys where \"l = ka+kb - 1\" \"U = {xs,ys}\" \"Form_Body ka kb xs ys (inter_scheme l U)\" \"0 < kb\" \"kb \\<le> ka\" \"ka \\<le> Suc kb\"\n  using interact [OF \\<open>Form l U\\<close>]\nproof cases\n  case (2 ka kb xs ys zs)\n  then have \\<section>: \"\\<And>ka kb zs. \\<not> Form_Body ka kb ys xs zs\"\n    using Form_Body_length less_asym' by blast\n  have \"Form_Body ka kb xs ys (inter_scheme l U)\"\n  proof (cases \"ka = kb\")\n    case True \n    with 2 have l: \"\\<forall>k. l \\<noteq> k * 2\"\n      by presburger\n    have [simp]: \"\\<And>k. kb + kb - Suc 0 = k * 2 - Suc 0 \\<longleftrightarrow> k=kb\"\n      by auto\n    show ?thesis\n      unfolding inter_scheme_def using 2 l True\n      by (auto simp: \\<section> \\<open>l > 0\\<close> Set.doubleton_eq_iff conj_disj_distribR ex_disj_distrib algebra_simps some_eq_ex)\n  next\n    case False\n    with 2 have l: \"\\<forall>k. l \\<noteq> k * 2 - Suc 0\" and [simp]: \"ka = Suc kb\"\n      by presburger+\n    have [simp]: \"\\<And>k. kb + kb = k * 2 \\<longleftrightarrow> k=kb\"\n      by auto\n    show ?thesis\n      unfolding inter_scheme_def using 2 l False\n      by (auto simp: \\<section> \\<open>l > 0\\<close> Set.doubleton_eq_iff conj_disj_distribR ex_disj_distrib algebra_simps some_eq_ex)\n  qed\n  then show ?thesis\n    by (simp add: 2 that)\nqed (use \\<open>l > 0\\<close> in auto)\n\nlemma inter_scheme_strict_sorted:\n  assumes \"Form l U\" \"l>0\"\n  shows \"strict_sorted (inter_scheme l U)\"\n  using Form_Body.simps assms inter_scheme by fastforce\n\nlemma inter_scheme_simple:\n  assumes \"Form l U\" \"l>0\"\n  shows \"inter_scheme l U \\<in> WW \\<and> length (inter_scheme l U) > 0\"\n  using inter_scheme [OF assms] by (meson Form_Body_WW Form_Body_nonempty)\n\nsubsubsection \\<open>Injectivity of interactions\\<close>\n\nproposition inter_scheme_injective:\n  assumes \"Form l U\" \"Form l U'\" \"l > 0\" and eq: \"inter_scheme l U' = inter_scheme l U\"\n  shows \"U' = U\"\nproof -\n  obtain ka kb xs ys \n    where l: \"l = ka+kb - 1\" and U: \"U = {xs,ys}\" \n      and FB: \"Form_Body ka kb xs ys (inter_scheme l U)\" \n      and kb: \"0 < kb\" \"kb \\<le> ka\" \"ka \\<le> Suc kb\"\n    using assms inter_scheme by blast\n  then obtain a as b bs c d\n    where xs: \"xs = concat (a#as)\" and ys: \"ys = concat (b#bs)\"\n      and len: \"length (a#as) = ka\" \"length (b#bs) = kb\"\n      and c: \"c = acc_lengths 0 (a#as)\"\n      and d: \"d = acc_lengths 0 (b#bs)\"\n      and Ueq: \"inter_scheme l U = concat [c, a, d, b] @ interact as bs\"\n    by (auto simp: Form_Body.simps)\n  obtain ka' kb' xs' ys' \n    where l': \"l = ka'+kb' - 1\" and U': \"U' = {xs',ys'}\" \n      and FB': \"Form_Body ka' kb' xs' ys' (inter_scheme l U')\" \n      and kb': \"0 < kb'\" \"kb' \\<le> ka'\" \"ka' \\<le> Suc kb'\"\n    using assms inter_scheme by blast\n  then obtain a' as' b' bs' c' d'\n    where xs': \"xs' = concat (a'#as')\" and ys': \"ys' = concat (b'#bs')\"\n      and len': \"length (a'#as') = ka'\" \"length (b'#bs') = kb'\"\n      and c': \"c' = acc_lengths 0 (a'#as')\"\n      and d': \"d' = acc_lengths 0 (b'#bs')\"\n      and Ueq': \"inter_scheme l U' = concat [c', a', d', b'] @ interact as' bs'\"\n    using Form_Body.simps by auto\n  have [simp]: \"ka' = ka \\<and> kb' = kb\"\n    using \\<open>l > 0\\<close> l l' kb kb' le_SucE le_antisym mult_2 by linarith \n  have [simp]: \"length c = length c'\" \"length d = length d'\"\n    using c c' d d' len' len by auto\n  have c_off: \"c' = c\" \"a' @ d' @ b' @ interact as' bs' = a @ d @ b @ interact as bs\"\n    using eq by (auto simp: Ueq Ueq')\n  then have len_a: \"length a' = length a\"\n    by (metis acc_lengths.simps(2) add.left_neutral c c' nth_Cons_0)\n  with c_off have \\<section>: \"a' = a\" \"d' = d\" \"b' @ interact as' bs' = b @ interact as bs\"\n    by auto\n  then have \"length (interact as' bs') = length (interact as bs)\"\n    by (metis acc_lengths.simps(2) add_left_cancel append_eq_append_conv d d' list.inject)\n  with \\<section> have \"b' = b\" \"interact as' bs' = interact as bs\"\n    by auto\n  moreover have \"acc_lengths 0 as' = acc_lengths 0 as\"\n    using \\<open>a' = a\\<close> \\<open>c' = c\\<close> by (simp add: c' c acc_lengths_shift)\n  moreover have \"acc_lengths 0 bs' = acc_lengths 0 bs\"\n    using \\<open>b' = b\\<close> \\<open>d' = d\\<close> by (simp add: d' d acc_lengths_shift)\n  ultimately have \"as' = as \\<and> bs' = bs\"\n    using acc_lengths_interact_injective by blast\n  then show ?thesis\n    by (simp add: \\<open>a' = a\\<close> U U' \\<open>b' = b\\<close> xs xs' ys ys')\nqed\n\n\nlemma strict_sorted_interact_imp_concat:\n    \"strict_sorted (interact as bs) \\<Longrightarrow> strict_sorted (concat as) \\<and> strict_sorted (concat bs)\"\nproof (induction as bs rule: interact.induct)\n  case (3 x xs y ys)\n  have \"x < concat xs\"\n    using \"3.prems\"\n    by (smt (verit, del_insts) Un_iff hd_in_set interact.simps(3) last_in_set less_list_def set_append set_interact sorted_wrt_append)\n  moreover have \"y < concat ys\"\n    using 3 sorted_wrt_append strict_sorted_append_iff by fastforce \n  ultimately show ?case\n    using 3 by (auto simp add: strict_sorted_append_iff)\nqed auto\n\n\nlemma strict_sorted_interact_hd:\n  \"\\<lbrakk>strict_sorted (interact cs ds); cs \\<noteq> []; ds \\<noteq> []; hd cs \\<noteq> []; hd ds \\<noteq> []\\<rbrakk>\n       \\<Longrightarrow> hd (hd cs) < hd (hd ds)\"\n  by (metis append_is_Nil_conv hd_append2 hd_in_set interact.simps(3) list.exhaust_sel sorted_wrt_append)\n\n\ntext \\<open>the lengths of the two lists can differ by one\\<close>\nproposition interaction_scheme_unique_aux:\n  assumes \"concat as = concat as'\" and ys': \"concat bs = concat bs'\"\n    and \"as \\<in> lists (- {[]})\" \"bs \\<in> lists (- {[]})\"\n    and \"strict_sorted (interact as bs)\"\n    and \"length bs \\<le> length as\" \"length as \\<le> Suc (length bs)\"\n    and \"as' \\<in> lists (- {[]})\" \"bs' \\<in> lists (- {[]})\"\n    and \"strict_sorted (interact as' bs')\"\n    and \"length bs' \\<le> length as'\" \"length as' \\<le> Suc (length bs')\"\n    and \"length as = length as'\" \"length bs = length bs'\"\n  shows \"as = as' \\<and> bs = bs'\"\n  using assms\nproof (induction \"length as\" arbitrary: as bs as' bs')\n  case 0 then show ?case\n    by auto\nnext\n  case (Suc k)\n  show ?case\n  proof (cases k)\n    case 0\n    then obtain a a' where aa': \"as = [a]\" \"as' = [a']\"\n      by (metis Suc.hyps(2) \\<open>length as = length as'\\<close> Suc_length_conv length_0_conv)\n    show ?thesis\n    proof\n      show \"as = as'\"\n        using aa' \\<open>concat as = concat as'\\<close> by force\n      with Suc 0 show \" bs = bs'\"\n        by (metis Suc_leI append_Nil2 concat.simps impossible_Cons le_antisym length_greater_0_conv list.exhaust)\n    qed\n  next\n    case (Suc k')\n    then obtain a cs b ds where eq: \"as = a#cs\" \"bs = b#ds\"\n      using Suc.prems\n      by (metis Suc.hyps(2) le0 list.exhaust list.size(3) not_less_eq_eq)\n    have \"length as' \\<noteq> 0\"\n      using Suc.hyps(2) \\<open>length as = length as'\\<close> by force\n    then obtain a' cs' b' ds' where eq': \"as' = a'#cs'\" \"bs' = b'#ds'\"\n      by (metis \\<open>length bs = length bs'\\<close> eq(2) length_0_conv list.exhaust)\n    obtain k: \"k = length cs\" \"k \\<le> Suc (length ds)\"\n      using eq \\<open>Suc k = length as\\<close> \\<open>length bs \\<le> length as\\<close> \\<open>length as \\<le> Suc (length bs)\\<close> by auto\n    case (Suc k')\n    obtain [simp]: \"b \\<noteq> []\" \"b' \\<noteq> []\" \"a \\<noteq> []\" \"a' \\<noteq> []\"\n      using Suc.prems by (simp add: eq eq')\n    then have \"hd b' = hd b\"\n      using Suc.prems(2) by (metis concat.simps(2) eq'(2) eq(2) hd_append2)\n    have ss_ab: \"strict_sorted (concat as)\" \"strict_sorted (concat bs)\"\n      using strict_sorted_interact_imp_concat Suc.prems(5) by blast+\n    have sw_ab: \"strict_sorted (a @ b @ interact cs ds)\"\n      by (metis Suc.prems(5) eq interact.simps(3))\n    then obtain \"a < b\" \"strict_sorted a\" \"strict_sorted b\"\n      by (metis append_assoc strict_sorted_append_iff)\n    have b_cs: \"strict_sorted (concat (b # cs))\"\n      by (metis append.simps(1) concat.simps(2) interact.simps(3) strict_sorted_interact_imp_concat sw_ab)\n    then have \"b < concat cs\"\n      using strict_sorted_append_iff by auto\n    have \"strict_sorted (a @ concat cs)\"\n      using eq(1) ss_ab(1) by force\n    have \"list.set a = list.set (concat as) \\<inter> {..< hd b}\"\n    proof -\n      have \"x \\<in> list.set a\"\n        if \"x < hd b\" and \"l \\<in> list.set cs\" and \"x \\<in> list.set l\" for x l\n        using b_cs sorted_hd_le strict_sorted_imp_sorted that by fastforce\n      then show ?thesis\n        using \\<open>b \\<noteq> []\\<close> sw_ab by (force simp: strict_sorted_append_iff sorted_wrt_append eq)\n    qed\n    moreover\n    have ss_ab': \"strict_sorted (concat as')\" \"strict_sorted (concat bs')\"\n      using strict_sorted_interact_imp_concat Suc.prems(10) by blast+\n    have sw_ab': \"strict_sorted (a' @ b' @ interact cs' ds')\"\n      by (metis Suc.prems(10) eq' interact.simps(3))\n    then obtain \"a' < b'\" \"strict_sorted a'\" \"strict_sorted b'\"\n      by (metis append_assoc strict_sorted_append_iff)\n    have b_cs': \"strict_sorted (concat (b' # cs'))\"\n      by (metis (no_types) Suc.prems(10) append_Nil eq' interact.simps(3) strict_sorted_append_iff strict_sorted_interact_imp_concat)\n    then have \"b' < concat cs'\"\n      by (simp add: strict_sorted_append_iff)\n    then have \"hd b' \\<notin> list.set (concat cs')\"\n      by (metis Un_iff \\<open>b' \\<noteq> []\\<close> list.set_sel(1) not_less_iff_gr_or_eq set_interact sorted_wrt_append sw_ab')\n    have \"strict_sorted (a' @ concat cs')\"\n      using eq'(1) ss_ab'(1) by force\n    then have b_cs': \"strict_sorted (b' @ concat cs')\"\n      using \\<open>b' < concat cs'\\<close> eq'(2) ss_ab'(2) strict_sorted_append_iff by auto\n    have \"list.set a' = list.set (concat as') \\<inter> {..< hd b'}\"\n    proof -\n      have \"x \\<in> list.set a'\"\n        if \"x < hd b'\" and \"l \\<in> list.set cs'\" and \"x \\<in> list.set l\" for x l\n        using b_cs' sorted_hd_le strict_sorted_imp_sorted that by fastforce\n      then show ?thesis\n        using \\<open>b' \\<noteq> []\\<close> sw_ab' by (force simp: strict_sorted_append_iff sorted_wrt_append eq')\n    qed\n    ultimately have \"a=a'\"\n      by (simp add: Suc.prems(1) \\<open>hd b' = hd b\\<close> \\<open>strict_sorted a'\\<close> \\<open>strict_sorted a\\<close> strict_sorted_equal)\n    moreover\n    have ccat_cs_cs': \"concat cs = concat cs'\"\n      using Suc.prems(1) \\<open>a = a'\\<close> eq'(1) eq(1) by fastforce\n    have \"b=b'\"\n    proof (cases \"ds = [] \\<or> ds' = []\")\n      case True\n      then show ?thesis\n        using \\<open>length bs = length bs'\\<close> Suc.prems(2) eq'(2) eq(2) by auto\n    next\n      case False\n      then have \"ds \\<noteq> []\" \"ds' \\<noteq> []\" \"sorted (concat ds)\" \"sorted (concat ds')\"\n        using eq(2) ss_ab(2) eq'(2) ss_ab'(2) strict_sorted_append_iff strict_sorted_imp_sorted by auto\n      have \"strict_sorted b\" \"strict_sorted b'\"\n        using b_cs b_cs' sorted_wrt_append by auto\n      moreover\n      have \"cs \\<noteq> []\"\n        using k local.Suc by auto\n      then obtain \"hd cs \\<noteq> []\" \"hd ds \\<noteq> []\"\n        using Suc.prems(3) Suc.prems(4) eq list.set_sel(1)\n        by (simp add: \\<open>ds \\<noteq> []\\<close> mem_lists_non_Nil)\n      then have \"concat cs \\<noteq> []\"\n        using \\<open>cs \\<noteq> []\\<close> hd_in_set by auto\n      have \"hd (concat cs) < hd (concat ds)\"\n        using strict_sorted_interact_hd\n        by (metis \\<open>cs \\<noteq> []\\<close> \\<open>ds \\<noteq> []\\<close> \\<open>hd cs \\<noteq> []\\<close> \\<open>hd ds \\<noteq> []\\<close> hd_concat sorted_wrt_append sw_ab)\n\n      have \"list.set b = list.set (concat bs) \\<inter> {..< hd (concat cs)}\"\n      proof -\n        have 1: \"x \\<in> list.set b\"\n          if \"x < hd (concat cs)\" and \"l \\<in> list.set ds\" and \"x \\<in> list.set l\" for x l\n          using \\<open>hd (concat cs) < hd (concat ds)\\<close> \\<open>sorted (concat ds)\\<close> sorted_hd_le that by fastforce\n        have 2: \"l < hd (concat cs)\" if \"l \\<in> list.set b\" for l\n          by (meson \\<open>b < concat cs\\<close> \\<open>b \\<noteq> []\\<close> \\<open>concat cs \\<noteq> []\\<close> \\<open>strict_sorted b\\<close> le_less_trans less_list_def sorted_le_last strict_sorted_imp_sorted that)\n        show ?thesis\n          using 1 2 by (auto simp: strict_sorted_append_iff sorted_wrt_append eq)\n      qed\n      moreover\n      have \"cs' \\<noteq> []\"\n        using k local.Suc \\<open>concat cs \\<noteq> []\\<close> ccat_cs_cs' by auto\n      then obtain \"hd cs' \\<noteq> []\" \"hd ds' \\<noteq> []\"\n        using Suc.prems(8,9) \\<open>ds' \\<noteq> []\\<close> eq'(1) eq'(2) list.set_sel(1) by auto\n      then have \"concat cs' \\<noteq> []\"\n        using \\<open>cs' \\<noteq> []\\<close> hd_in_set by auto\n      have \"hd (concat cs') < hd (concat ds')\"\n        using strict_sorted_interact_hd\n        by (metis \\<open>cs' \\<noteq> []\\<close> \\<open>ds' \\<noteq> []\\<close> \\<open>hd cs' \\<noteq> []\\<close> \\<open>hd ds' \\<noteq> []\\<close> hd_concat sorted_wrt_append sw_ab')\n      have \"list.set b' = list.set (concat bs') \\<inter> {..< hd (concat cs')}\"\n      proof -\n        have 1: \"x \\<in> list.set b'\"\n          if \"x < hd (concat cs')\" and \"l \\<in> list.set ds'\" and \"x \\<in> list.set l\" for x l\n          using \\<open>hd (concat cs') < hd (concat ds')\\<close> \\<open>sorted (concat ds')\\<close> sorted_hd_le that by fastforce\n        have 2: \"l < hd (concat cs')\" if \"l \\<in> list.set b'\" for l\n          by (metis \\<open>concat cs' \\<noteq> []\\<close> b_cs' list.set_sel(1) sorted_wrt_append that)\n        show ?thesis\n          using 1 2 by (auto simp: strict_sorted_append_iff sorted_wrt_append eq')\n      qed\n      ultimately show \"b = b'\"\n        by (simp add: Suc.prems(2) ccat_cs_cs' strict_sorted_equal)\n    qed\n    moreover\n    have \"cs = cs' \\<and> ds = ds'\"\n    proof (rule Suc.hyps)\n      show \"k = length cs\"\n        using eq Suc.hyps(2) by auto[1]\n      show \"concat ds = concat ds'\"\n        using Suc.prems(2) \\<open>b = b'\\<close> eq'(2) eq(2) by auto\n      show \"strict_sorted (interact cs ds)\"\n        using eq Suc.prems(5) strict_sorted_append_iff by auto\n      show \"length ds \\<le> length cs\" \"length cs \\<le> Suc (length ds)\"\n        using eq Suc.hyps(2) Suc.prems(6) k by auto\n      show \"strict_sorted (interact cs' ds')\"\n        using eq' Suc.prems(10) strict_sorted_append_iff by auto\n      show \"length cs = length cs'\"\n        using Suc.hyps(2) Suc.prems(13) eq'(1) k(1) by force\n    qed (use ccat_cs_cs' eq eq' Suc.prems in auto)\n    ultimately show ?thesis\n      by (simp add: \\<open>a = a'\\<close> \\<open>b = b'\\<close> eq eq')\n  qed\nqed\n\n\nproposition Form_Body_unique:\n  assumes \"Form_Body ka kb xs ys zs\" \"Form_Body ka kb xs ys zs'\" and \"kb \\<le> ka\" \"ka \\<le> Suc kb\"\n  shows \"zs' = zs\"\nproof -\n  obtain a as b bs c d\n      where xs: \"xs = concat (a#as)\" and ys: \"ys = concat (b#bs)\"\n        and ne: \"a#as \\<in> lists (- {[]})\" \"b#bs \\<in> lists (- {[]})\"\n        and len: \"length (a#as) = ka\" \"length (b#bs) = kb\"\n        and c: \"c = acc_lengths 0 (a#as)\"\n        and d: \"d = acc_lengths 0 (b#bs)\"\n        and Ueq: \"zs = concat [c, a, d, b] @ interact as bs\"\n        and ss_zs: \"strict_sorted zs\"\n    using Form_Body.cases [OF assms(1)] by (metis (no_types))\n  obtain a' as' b' bs' c' d'\n      where xs': \"xs = concat (a'#as')\" and ys': \"ys = concat (b'#bs')\"\n        and ne': \"a'#as' \\<in> lists (- {[]})\" \"b'#bs' \\<in> lists (- {[]})\"\n        and len': \"length (a'#as') = ka\" \"length (b'#bs') = kb\"\n        and c': \"c' = acc_lengths 0 (a'#as')\"\n        and d': \"d' = acc_lengths 0 (b'#bs')\"\n        and Ueq': \"zs' = concat [c', a', d', b'] @ interact as' bs'\"\n        and ss_zs': \"strict_sorted zs'\"\n    using Form_Body.cases [OF assms(2)] by (metis (no_types))\n  have [simp]: \"length c = length c'\" \"length d = length d'\"\n    using c c' d d' len' len by auto\n  note acc_lengths.simps [simp del]\n  have \"a < b\"\n    using ss_zs by (auto simp: Ueq strict_sorted_append_iff less_list_def c d)\n  have \"a' < b'\"\n    using ss_zs' by (auto simp: Ueq' strict_sorted_append_iff less_list_def c' d')\n  have \"a#as = a'#as' \\<and> b#bs = b'#bs'\"\n  proof (rule interaction_scheme_unique_aux)\n    show \"strict_sorted (interact (a # as) (b # bs))\"\n      using ss_zs \\<open>a < b\\<close> by (auto simp: Ueq strict_sorted_append_iff less_list_def d)\n    show \"strict_sorted (interact (a' # as') (b' # bs'))\"\n      using ss_zs' \\<open>a' < b'\\<close> by (auto simp: Ueq' strict_sorted_append_iff less_list_def d')\n    show \"length (b # bs) \\<le> length (a # as)\" \"length (b' # bs') \\<le> length (a' # as')\"\n      using \\<open>kb \\<le> ka\\<close> len len' by auto\n    show \"length (a # as) \\<le> Suc (length (b # bs))\"\n      using \\<open>ka \\<le> Suc kb\\<close> len by linarith\n    then show \"length (a' # as') \\<le> Suc (length (b' # bs'))\"\n      using len len' by fastforce\n  qed (use len len' xs xs' ys ys' ne ne' in fastforce)+\n  then show ?thesis\n    using Ueq Ueq' c c' d d' by blast\nqed\n\n\nlemma Form_Body_imp_inter_scheme:\n  assumes FB: \"Form_Body ka kb xs ys zs\" and \"0 < kb\" \"kb \\<le> ka\" \"ka \\<le> Suc kb\"\n  shows \"zs = inter_scheme ((ka+kb) - Suc 0) {xs,ys}\"\nproof -\n  have \"length xs < length ys\"\n    by (meson Form_Body_length assms(1))\n  have [simp]: \"a + a = b + b \\<longleftrightarrow> a=b\"  \"a + a - Suc 0 = b + b - Suc 0 \\<longleftrightarrow> a=b\" for a b::nat\n    by auto\n  show ?thesis\n  proof (cases \"ka = kb\")\n    case True\n    show ?thesis\n      unfolding inter_scheme_def\n      apply (rule some_equality [symmetric], metis One_nat_def True FB mult_2)\n      subgoal for zs'\n        using assms \\<open>length xs < length ys\\<close>\n        by (auto simp: True mult_2 Set.doubleton_eq_iff Form_Body_unique dest: Form_Body_length, presburger)\n      done\n  next\n    case False\n    then have eq: \"ka = Suc kb\"\n      using assms by linarith\n    show ?thesis\n      unfolding inter_scheme_def\n      apply (rule some_equality [symmetric], use assms False mult_2 one_is_add eq in fastforce)\n      subgoal for zs'\n        using assms \\<open>length xs < length ys\\<close>\n        by (auto simp: eq mult_2 Set.doubleton_eq_iff Form_Body_unique dest: Form_Body_length, presburger)\n      done\n  qed\nqed\n\n\nsubsection \\<open>For Lemma 3.8 AND PROBABLY 3.7\\<close>\n\ndefinition grab :: \"nat set \\<Rightarrow> nat \\<Rightarrow> nat set \\<times> nat set\"\n  where \"grab N n \\<equiv> (N \\<inter> enumerate N ` {..<n}, N \\<inter> {enumerate N n..})\"\n\nlemma grab_0 [simp]: \"grab N 0 = ({}, N)\"\n  by (fastforce simp: grab_def enumerate_0 Least_le)\n\nlemma less_sets_grab:\n  \"infinite N \\<Longrightarrow> fst (grab N n) \\<lless> snd (grab N n)\"\n  by (auto simp: grab_def less_sets_def intro: enumerate_mono less_le_trans)\n\nlemma finite_grab [iff]: \"finite (fst (grab N n))\"\n  by (simp add: grab_def)\n\nlemma card_grab [simp]:\n  assumes \"infinite N\" shows \"card (fst (grab N n)) = n\"\nproof -\n  have \"N \\<inter> enumerate N ` {..<n} = enumerate N ` {..<n}\"\n    using assms by (auto simp: enumerate_in_set)\n  with assms show ?thesis\n    by (simp add: card_image grab_def strict_mono_enum strict_mono_imp_inj_on)\nqed\n\nlemma fst_grab_subset: \"fst (grab N n) \\<subseteq> N\"\n  using grab_def range_enum by fastforce\n\nlemma snd_grab_subset: \"snd (grab N n) \\<subseteq> N\"\n  by (auto simp: grab_def)\n\nlemma grab_Un_eq:\n  assumes \"infinite N\" shows \"fst (grab N n) \\<union> snd (grab N n) = N\"\nproof\n  show \"N \\<subseteq> fst (grab N n) \\<union> snd (grab N n)\"\n    unfolding grab_def\n    using assms enumerate_Ex le_less_linear strict_mono_enum strict_mono_less by fastforce\nqed (simp add: grab_def)\n\nlemma finite_grab_iff [simp]: \"finite (snd (grab N n)) \\<longleftrightarrow> finite N\"\n  by (metis finite_grab grab_Un_eq infinite_Un infinite_super snd_grab_subset)\n\nlemma grab_eqD:\n    \"\\<lbrakk>grab N n = (A,M); infinite N\\<rbrakk>\n    \\<Longrightarrow> A \\<lless> M \\<and> finite A \\<and> card A = n \\<and> infinite M \\<and> A \\<subseteq> N \\<and> M \\<subseteq> N\"\n  using card_grab grab_def less_sets_grab finite_grab_iff by auto\n\nlemma less_sets_fst_grab: \"A \\<lless> N \\<Longrightarrow> A \\<lless> fst (grab N n)\"\n  by (simp add: fst_grab_subset less_sets_weaken2)\n\ntext\\<open>Possibly redundant, given @{term grab}\\<close>\ndefinition nxt where \"nxt \\<equiv> \\<lambda>N. \\<lambda>n::nat. N \\<inter> {n<..}\"\n\nlemma infinite_nxtN: \"infinite N \\<Longrightarrow> infinite (nxt N n)\"\n  by (simp add: infinite_nat_greaterThan nxt_def)\n\nlemma nxt_subset: \"nxt N n \\<subseteq> N\"\n  unfolding nxt_def by blast\n\nlemma nxt_subset_greaterThan: \"m \\<le> n \\<Longrightarrow> nxt N n \\<subseteq> {m<..}\"\n  by (auto simp: nxt_def)\n\n\n\nlemma enum_nxt_ge: \"infinite N \\<Longrightarrow> a \\<le> enum (nxt N a) n\"\n  by (simp add: atLeast_le_enum infinite_nxtN nxt_subset_atLeast)\n\nlemma inj_enum_nxt: \"infinite N \\<Longrightarrow> inj_on (enum (nxt N a)) A\"\n  by (simp add: infinite_nxtN strict_mono_enum strict_mono_imp_inj_on)\n\n\nsubsection \\<open>Larson's Lemma 3.11\\<close>\n\ntext \\<open>Again from Jean A. Larson,\n     A short proof of a partition theorem for the ordinal $\\omega^\\omega$.\n     \\emph{Annals of Mathematical Logic}, 6:129–145, 1973.\\<close>\n\nlemma lemma_3_11:\n  assumes \"l > 0\"\n  shows \"thin (inter_scheme l ` {U. Form l U})\"\n  using form_cases [of l]\nproof cases\n  case zero\n  then show ?thesis\n    using assms by auto\nnext\n  case (nz ka kb)\n  note acc_lengths.simps [simp del]\n  show ?thesis\n    unfolding thin_def\n  proof clarify\n    fix U U'\n    assume ne: \"inter_scheme l U \\<noteq> inter_scheme l U'\" and init: \"initial_segment (inter_scheme l U) (inter_scheme l U')\"\n    assume \"Form l U\"\n    then obtain kp kq xs ys where \"l = kp+kq - 1\" \"U = {xs,ys}\" \n            and U: \"Form_Body kp kq xs ys (inter_scheme l U)\" and \"0 < kq\" \"kq \\<le> kp\" \"kp \\<le> Suc kq\"\n      using assms inter_scheme by blast\n    then have \"kp = ka \\<and> kq = kb\"\n      using nz by linarith\n    then obtain a as b bs c d\n      where len: \"length (a#as) = ka\" \"length (b#bs) = kb\"\n        and c: \"c = acc_lengths 0 (a#as)\"\n        and d: \"d = acc_lengths 0 (b#bs)\"\n        and Ueq: \"inter_scheme l U = concat [c, a, d, b] @ interact as bs\"\n      using U by (auto simp: Form_Body.simps)\n    assume \"Form l U'\"\n    then obtain kp' kq' xs' ys'  where \"l = kp'+kq' - 1\" \"U' = {xs',ys'}\" \n            and U': \"Form_Body kp' kq' xs' ys' (inter_scheme l U')\" and \"0 < kq'\" \"kq' \\<le> kp'\" \"kp' \\<le> Suc kq'\"\n      using assms inter_scheme by blast\n    then have \"kp' = ka \\<and> kq' = kb\"\n      using nz by linarith\n    then obtain a' as' b' bs' c' d'\n      where len': \"length (a'#as') = ka\" \"length (b'#bs') = kb\"\n        and c': \"c' = acc_lengths 0 (a'#as')\"\n        and d': \"d' = acc_lengths 0 (b'#bs')\"\n        and Ueq': \"inter_scheme l U' = concat [c', a', d', b'] @ interact as' bs'\"\n      using U' by (auto simp: Form_Body.simps)\n    have [simp]: \"length bs' = length bs\" \"length as' = length as\"\n      using len len' by auto\n    have \"inter_scheme l U \\<noteq> []\" \"inter_scheme l U' \\<noteq> []\"\n      using Form_Body_nonempty U U' by auto\n    define u1 where \"u1 \\<equiv> hd (inter_scheme l U)\"\n    have u1_eq': \"u1 = hd (inter_scheme l U')\"\n      using \\<open>inter_scheme l U \\<noteq> []\\<close> init u1_def initial_segment_ne by fastforce\n    have au1: \"u1 = length a\"\n      by (simp add: u1_def Ueq c)\n    have au1': \"u1 = length a'\"\n      by (simp add: u1_eq' Ueq' c')\n    have len_eqk: \"length c' = ka\" \"length d' = kb\" \"length c' = ka\" \"length d' = kb\"\n      using c d len c' d' len' by auto\n    have take: \"take (ka + u1 + kb) (c @ a @ d @ l) = c @ a @ d\"\n               \"take (ka + u1 + kb) (c' @ a' @ d' @ l) = c' @ a' @ d'\" for l\n      using c d c' d' len by (simp_all flip: au1 au1')\n    have leU: \"ka + u1 + kb \\<le> length (inter_scheme l U)\"\n      using c d len by (simp add: au1 Ueq)\n    then have \"take (ka + u1 + kb) (inter_scheme l U) = take (ka + u1 + kb) (inter_scheme l U')\"\n      using take_initial_segment init by blast\n    then have \\<section>: \"c @ a @ d = c' @ a' @ d'\"\n      by (metis Ueq Ueq' append.assoc concat.simps(2) take)\n    have \"length (inter_scheme l U) = ka + (c @ a @ d)!(ka-1) + kb + last d\"\n      by (simp add: Ueq c d length_interact nth_append flip: len)\n    moreover have \"length (inter_scheme l U') = ka + (c' @ a' @ d')!(ka-1) + kb + last d'\"\n      by (simp add: Ueq' c' d' length_interact nth_append flip: len')\n    moreover have \"last d = last d'\"\n      using \"\\<section>\" c d d' len'(1) len_eqk(1) by auto\n    ultimately have \"length (inter_scheme l U) = length (inter_scheme l U')\"\n      by (simp add: \\<section>)\n    then show False\n      using init initial_segment_length_eq ne by blast\n  qed\nqed\n\n\nsubsection \\<open>Larson's Lemma 3.6\\<close>\n\nproposition lemma_3_6:\n  fixes g :: \"nat list set \\<Rightarrow> nat\"\n  assumes g: \"g \\<in> [WW]\\<^bsup>2\\<^esup> \\<rightarrow> {0,1}\"\n  obtains N j where \"infinite N\"\n    and \"\\<And>k u. \\<lbrakk>k > 0; u \\<in> [WW]\\<^bsup>2\\<^esup>; Form k u; [enum N k] < inter_scheme k u; List.set (inter_scheme k u) \\<subseteq> N\\<rbrakk> \\<Longrightarrow> g u = j k\"\nproof -\n  define \\<Phi> where \"\\<Phi> \\<equiv> \\<lambda>m::nat. \\<lambda>M. infinite M \\<and> m < Inf M\"\n  define \\<Psi> where \"\\<Psi> \\<equiv> \\<lambda>l m n::nat. \\<lambda>M N j. n > m \\<and> N \\<subseteq> M \\<and> n \\<in> M \n                     \\<and> (\\<forall>U. Form l U \\<and> U \\<subseteq> WW \\<and> [n] < inter_scheme l U \\<and> list.set (inter_scheme l U) \\<subseteq> N \\<longrightarrow> g U = j)\"\n  have *: \"\\<exists>n N j. \\<Phi> n N \\<and> \\<Psi> l m n M N j\" if \"l > 0\" \"\\<Phi> m M\" for l m::nat and M :: \"nat set\"\n  proof -\n    define FF where \"FF \\<equiv> {U \\<in> [WW]\\<^bsup>2\\<^esup>. Form l U}\"\n    define h where \"h \\<equiv> \\<lambda>zs. g (inv_into FF (inter_scheme l) zs)\"\n    have \"thin (inter_scheme l ` FF)\"\n      using \\<open>l > 0\\<close> lemma_3_11 by (simp add: thin_def FF_def)\n    moreover\n    have \"inter_scheme l ` FF \\<subseteq> WW\"\n      using inter_scheme_simple \\<open>0 < l\\<close> FF_def by blast\n    moreover\n    have \"h ` {xs \\<in> inter_scheme l ` FF. List.set xs \\<subseteq> M} \\<subseteq> {..<2}\"\n      using g inv_into_into[of concl: \"FF\" \"inter_scheme l\"]\n      by (force simp: h_def FF_def Pi_iff)\n    ultimately\n    obtain j N where \"j < 2\" \"infinite N\" \"N \\<subseteq> M\" and hj: \"h ` {xs \\<in> inter_scheme l ` FF. List.set xs \\<subseteq> N} \\<subseteq> {j}\"\n      using \\<open>\\<Phi> m M\\<close> unfolding \\<Phi>_def by (blast intro: Nash_Williams_WW [of M])\n    let ?n = \"Inf N\"\n    have \"?n > m\"\n      using \\<open>\\<Phi> m M\\<close> \\<open>infinite N\\<close> unfolding \\<Phi>_def Inf_nat_def infinite_nat_iff_unbounded\n      by (metis LeastI_ex \\<open>N \\<subseteq> M\\<close> le_less_trans not_less not_less_Least subsetD)\n    have \"g U = j\" if \"Form l U\" \"U \\<subseteq> WW\" \"[?n] < inter_scheme l U\" \"list.set (inter_scheme l U) \\<subseteq> N - {?n}\" for U\n    proof -\n      obtain xs ys where xys: \"xs \\<noteq> ys\" \"U = {xs,ys}\"\n        using Form_elim_upair \\<open>Form l U\\<close> by blast\n      moreover have \"inj_on (inter_scheme l) FF\"\n        using \\<open>0 < l\\<close> inj_on_def inter_scheme_injective FF_def by blast\n      moreover \n      have \"g (inv_into FF (inter_scheme l) (inter_scheme l U)) = j\"\n        using hj that xys subset_Diff_insert by (fastforce simp: h_def FF_def image_iff)\n      ultimately show ?thesis\n        using that FF_def by auto\n    qed\n    moreover have \"?n < Inf (N - {?n})\"\n      by (metis Diff_iff Inf_nat_def Inf_nat_def1 \\<open>infinite N\\<close> finite.emptyI infinite_remove linorder_neqE_nat not_less_Least singletonI)\n    moreover have \"?n \\<in> M\"\n      by (metis Inf_nat_def1 \\<open>N \\<subseteq> M\\<close> \\<open>infinite N\\<close> finite.emptyI subsetD)\n    ultimately have \"\\<Phi> ?n (N - {?n}) \\<and> \\<Psi> l m ?n M (N - {?n}) j\"\n      using \\<open>\\<Phi> m M\\<close> \\<open>infinite N\\<close> \\<open>N \\<subseteq> M\\<close> \\<open>?n > m\\<close> by (auto simp: \\<Phi>_def \\<Psi>_def)\n    then show ?thesis\n      by blast\n  qed\n  have base: \"\\<Phi> 0 {0<..}\"\n    unfolding \\<Phi>_def by (metis infinite_Ioi Inf_nat_def1 greaterThan_iff greaterThan_non_empty)\n  have step: \"Ex (\\<lambda>(n,N,j). \\<Phi> n N \\<and> \\<Psi> l m n M N j)\" if \"\\<Phi> m M\" \"l > 0\" for m M l\n    using * [of l m M] that by (auto simp: \\<Phi>_def)\n  define G where \"G \\<equiv> \\<lambda>l m M. @(n,N,j). \\<Phi> n N \\<and> \\<Psi> (Suc l) m n M N j\"\n  have G\\<Phi>: \"(\\<lambda>(n,N,j). \\<Phi> n N) (G l m M)\" and G\\<Psi>: \"(\\<lambda>(n,N,j). \\<Psi> (Suc l) m n M N j) (G l m M)\"\n    if \"\\<Phi> m M\" for l m M\n    using step [OF that, of \"Suc l\"] by (force simp: G_def dest: some_eq_imp)+\n  have G_increasing: \"(\\<lambda>(n,N,j). n > m \\<and> N \\<subseteq> M \\<and> n \\<in> M) (G l m M)\"  if \"\\<Phi> m M\" for l m M\n    using G\\<Psi> [OF that, of l] that by (simp add: \\<Psi>_def split: prod.split_asm)\n  define H where \"H \\<equiv> rec_nat (0,{0<..},0) (\\<lambda>l (m,M,j). G l m M)\"\n  have H_simps: \"H 0 = (0,{0<..},0)\" \"\\<And>l. H (Suc l) = (case H l of (m,M,j) \\<Rightarrow> G l m M)\"\n    by (simp_all add: H_def)\n  have H\\<Phi>: \"(\\<lambda>(n,N,j). \\<Phi> n N) (H l)\" for l\n    by (induction l) (use base G\\<Phi> in \\<open>auto simp: H_simps split: prod.split_asm\\<close>)\n  define \\<nu> where \"\\<nu> \\<equiv> (\\<lambda>l. case H l of (n,M,j) \\<Rightarrow> n)\"\n  have H_inc: \"\\<nu> l \\<ge> l\" for l\n  proof (induction l)\n    case (Suc l)\n    then show ?case\n      using H\\<Phi> [of l] G_increasing [of \"\\<nu> l\"]\n      apply (clarsimp simp: H_simps \\<nu>_def split: prod.split)\n      by (metis (no_types, lifting) case_prodD leD le_less_trans not_less_eq_eq)\n  qed auto\n  let ?N = \"range \\<nu>\"\n  define j where \"j \\<equiv> \\<lambda>l. case H l of (n,M,j) \\<Rightarrow> j\"\n  have H_increasing_Suc: \"(case H k of (n, N, j') \\<Rightarrow> N) \\<supseteq> (case H (Suc k) of (n, N, j') \\<Rightarrow> insert n N)\" for k\n    using H\\<Phi> [of k]\n    by (force simp: H_simps split: prod.split dest: G_increasing [where l=k])\n  have H_increasing_superset: \"(case H k of (n, N, j') \\<Rightarrow> N) \\<supseteq> (case H (n+k) of (n, N, j') \\<Rightarrow> N)\" for k n\n  proof (induction n)\n    case (Suc n)\n    then show ?case\n      using H_increasing_Suc [of \"n+k\"] by (auto split: prod.split_asm)\n  qed auto\n  then have H_increasing_less: \"(case H k of (n, N, j') \\<Rightarrow> N) \\<supseteq> (case H l of (n, N, j') \\<Rightarrow> insert n N)\"\n    if \"k<l\" for k l\n    by (smt (verit, best) H_increasing_Suc add.commute less_natE order_trans that)\n  have \"\\<nu> k < \\<nu> (Suc k)\" for k\n    using H\\<Phi> [of k] unfolding \\<nu>_def\n    by (auto simp: H_simps split: prod.split dest: G_increasing [where l=k])\n  then have strict_mono_\\<nu>: \"strict_mono \\<nu>\"\n    by (simp add: strict_mono_Suc_iff)\n  then have enum_N: \"enum ?N = \\<nu>\"\n    by (metis enum_works nat_infinite_iff range_strict_mono_ext)\n  have **: \"?N \\<inter> {n<..} \\<subseteq> N'\" if H: \"H k = (n, N', j)\" for n N' k j\n  proof clarify\n    fix l\n    assume \"n < \\<nu> l\"\n    then have False if \"l \\<le> k\"\n      using that strict_monoD [OF strict_mono_\\<nu>, of l k ] H by (force simp: \\<nu>_def)\n    then have \"k < l\" using not_less by blast\n    then obtain M j where Mj: \"H l = (\\<nu> l,M,j)\"\n      unfolding \\<nu>_def\n      by (metis (mono_tags, lifting) case_prod_conv old.prod.exhaust)\n    then show \"\\<nu> l \\<in> N'\"\n      using that H_increasing_less [OF \\<open>k<l\\<close>] Mj by auto\n  qed\n  show thesis\n  proof\n    show \"infinite (?N::nat set)\"\n      using H_inc infinite_nat_iff_unbounded_le by auto\n  next\n    fix l U\n    assume \"0 < l\" and U: \"U \\<in> [WW]\\<^bsup>2\\<^esup>\"\n      and interU: \"[enum ?N l] < inter_scheme l U\" \"Form l U\"\n      and sub: \"list.set (inter_scheme l U) \\<subseteq> ?N\"\n    obtain k where k: \"l = Suc k\"\n      using \\<open>0 < l\\<close> gr0_conv_Suc by blast\n    have \"g U = v\" if \"H k = (m, M, j0)\" and \"G k m M = (n, N', v)\"\n      for m M j0 n N' v\n    proof -\n      have n: \"\\<nu> (Suc k) = n\"\n        using that by (simp add: \\<nu>_def H_simps)\n      have \"{..enum (range \\<nu>) l} \\<inter> list.set (inter_scheme l U) = {}\"\n        using inter_scheme_strict_sorted \\<open>0 < l\\<close> interU singleton_less_list_iff strict_sorted_iff by blast\n      then have \"list.set (inter_scheme (Suc k) U) \\<subseteq> N'\"\n        using that sub ** [of \"Suc k\" n N' v] Suc_le_eq not_less_eq_eq\n        by (fastforce simp:  k n enum_N H_simps)\n      then show ?thesis\n        using that interU U G\\<Psi> [of m M k] H\\<Phi> [of k]\n        by (auto simp: \\<Psi>_def k enum_N H_simps n nsets_def)\n    qed\n    with U show \"g U = j l\"\n      by (auto simp: k j_def H_simps split: prod.split)\n  qed\nqed\n\n\nsubsection \\<open>Larson's Lemma 3.7\\<close>\n\nsubsubsection \\<open>Preliminaries\\<close>\n\ntext \\<open>Analogous to @{thm [source] ordered_nsets_2_eq}, but without type classes\\<close>\nlemma total_order_nsets_2_eq:\n  assumes tot: \"total_on A r\" and irr: \"irrefl r\"\n  shows \"nsets A 2 = {{x,y} | x y. x \\<in> A \\<and> y \\<in> A \\<and> (x,y) \\<in> r}\"\n     (is \"_ = ?rhs\")\nproof\n  show \"nsets A 2 \\<subseteq> ?rhs\"\n    using tot\n    unfolding numeral_nat total_on_def nsets_def\n    by (fastforce simp: card_Suc_eq Set.doubleton_eq_iff not_less)\n  show \"?rhs \\<subseteq> nsets A 2\"\n    using irr unfolding numeral_nat by (force simp: nsets_def card_Suc_eq irrefl_def)\nqed\n\nlemma lenlex_nsets_2_eq: \"nsets A 2 = {{x,y} | x y. x \\<in> A \\<and> y \\<in> A \\<and> (x,y) \\<in> lenlex less_than}\"\n  using total_order_nsets_2_eq by (simp add: total_order_nsets_2_eq irrefl_def)\n\nlemma sum_sorted_list_of_set_map: \"finite I \\<Longrightarrow> sum_list (map f (list_of I)) = sum f I\"\nproof (induction \"card I\" arbitrary: I)\n  case (Suc n I)\n  then have [simp]: \"I \\<noteq> {}\"\n    by auto\n  have \"sum_list (map f (list_of (I - {Min I}))) = sum f (I - {Min I})\"\n    using Suc by auto\n  then show ?case\n    using Suc.prems sum.remove [of I \"Min I\" f]\n    by (simp add: sorted_list_of_set_nonempty Suc)\nqed auto\n\n\nlemma sorted_list_of_set_UN_eq_concat:\n  assumes I: \"strict_mono_sets I f\" \"finite I\" and fin: \"\\<And>i. finite (f i)\"\n  shows \"list_of (\\<Union>i \\<in> I. f i) = concat (map (list_of \\<circ> f) (list_of I))\"\n  using I\nproof (induction \"card I\" arbitrary: I)\n  case (Suc n I)\n  then have \"I \\<noteq> {}\" and Iexp: \"I = insert (Min I) (I - {Min I})\"\n    using Min_in Suc.hyps(2) Suc.prems(2) by fastforce+\n  have IH: \"list_of (\\<Union> (f ` (I - {Min I}))) = concat (map (list_of \\<circ> f) (list_of (I - {Min I})))\"\n    using Suc unfolding strict_mono_sets_def\n    by (metis DiffE Iexp card_Diff_singleton diff_Suc_1 finite_Diff insertI1)\n  have \"list_of (\\<Union> (f ` I)) = list_of (\\<Union> (f ` (insert (Min I) (I - {Min I}))))\"\n    using Iexp by auto\n  also have \"\\<dots> = list_of (f (Min I) \\<union> \\<Union> (f ` (I - {Min I})))\"\n    by (metis Union_image_insert)\n  also have \"\\<dots> = list_of (f (Min I)) @ list_of (\\<Union> (f ` (I - {Min I})))\"\n  proof (rule sorted_list_of_set_Un)\n    show \"f (Min I) \\<lless> \\<Union> (f ` (I - {Min I}))\"\n      using Suc.prems \\<open>I \\<noteq> {}\\<close> strict_mono_less_sets_Min by blast\n    show \"finite (\\<Union> (f ` (I - {Min I})))\"\n      by (simp add: \\<open>finite I\\<close> fin)\n  qed (use fin in auto)\n  also have \"\\<dots> = list_of (f (Min I)) @ concat (map (list_of \\<circ> f) (list_of (I - {Min I})))\"\n    using IH by metis\n  also have \"\\<dots> = concat (map (list_of \\<circ> f) (list_of I))\"\n    by (simp add: Suc.prems(2) \\<open>I \\<noteq> {}\\<close> sorted_list_of_set_nonempty)\n  finally show ?case .\nqed auto\n\nsubsubsection \\<open>Lemma 3.7 of Jean A. Larson, ibid.\\<close>\n\nproposition lemma_3_7:\n  assumes \"infinite N\" \"l > 0\"\n  obtains M where \"M \\<in> [WW]\\<^bsup>m\\<^esup>\"\n                  \"\\<And>U. U \\<in> [M]\\<^bsup>2\\<^esup> \\<Longrightarrow> Form l U \\<and> List.set (inter_scheme l U) \\<subseteq> N\"\nproof (cases \"m < 2\")\n  case True\n  obtain w where w: \"w \\<in> WW\"\n    using WW_def strict_sorted_into_WW by auto\n  define M where \"M \\<equiv> if m=0 then {} else {w}\"\n  have M: \"M \\<in> [WW]\\<^bsup>m\\<^esup>\"\n    using True by (auto simp: M_def nsets_def w)\n  have [simp]: \"[M]\\<^bsup>2\\<^esup> = {}\"\n    using True by (auto simp: M_def nsets_def w dest: subset_singletonD)\n  show ?thesis\n    using M that by fastforce\nnext\n  case False\n  then have \"m \\<ge> 2\"\n    by auto\n  have nonz: \"(enum N \\<circ> Suc) i > 0\" for i\n    using assms(1) le_enumerate less_le_trans by fastforce\n  note infinite_nxt_N = infinite_nxtN [OF \\<open>infinite N\\<close>, iff]\n  note \\<open>infinite N\\<close> [ iff]\n  have [simp]: \"{n<..<Suc n} = {}\" \"{..<1::nat} = {0}\" for n\n    by auto\n  note One_nat_def [simp del]\n\n  define DF_Suc where \"DF_Suc \\<equiv> \\<lambda>k D. enum (nxt N (enum (nxt N (Max D)) (Inf D - 1))) ` {..<Suc k}\"\n  define DF where \"DF \\<equiv> \\<lambda>k. rec_nat ((enum N \\<circ> Suc) ` {..<Suc k}) (\\<lambda>r. DF_Suc k)\"\n  have DF_simps: \"DF k 0 = (enum N \\<circ> Suc) ` {..<Suc k}\" \"DF k (Suc i) = DF_Suc k (DF k i)\" for i k\n    by (auto simp: DF_def)\n\n  have card_DF: \"card (DF k i) = Suc k\" for i k\n  proof (induction i)\n    case 0\n    have \"inj_on (enum N \\<circ> Suc) {..<Suc k}\"\n      by (simp add: assms(1) strict_mono_def strict_mono_imp_inj_on)\n    with 0 show ?case\n      using card_image DF_simps by fastforce\n  next\n    case (Suc i)\n    then show ?case\n      by (simp add: \\<open>infinite N\\<close> DF_simps DF_Suc_def card_image infinite_nxtN strict_mono_enum strict_mono_imp_inj_on)\n  qed\n  have DF_ne: \"DF k i \\<noteq> {}\" for i k\n    by (metis card_DF card_lessThan lessThan_empty_iff nat.simps(3))\n\n  have finite_DF: \"finite (DF k i)\" for i k\n    by (induction i) (auto simp: DF_simps DF_Suc_def)\n  have DF_Suc: \"DF k i \\<lless> DF k (Suc i)\" for i k\n    unfolding less_sets_def\n    by (force simp: finite_DF DF_simps DF_Suc_def\n        intro!: greaterThan_less_enum nxt_subset_greaterThan atLeast_le_enum nxt_subset_atLeast infinite_nxtN [OF \\<open>infinite N\\<close>])\n  have DF_DF: \"DF k i \\<lless> DF k j\" if \"i<j\" for i j k\n    by (meson DF_Suc DF_ne UNIV_I less_sets_imp_strict_mono_sets strict_mono_setsD that)\n  then have sm_DF: \"strict_mono_sets UNIV (DF k)\" for k\n    by (simp add: strict_mono_sets_def)\n\n  have DF_gt0: \"0 < Inf (DF k i)\" for i k\n  proof (cases i)\n    case 0\n    then show ?thesis\n      by (metis DF_ne DF_simps(1) Inf_nat_def1 imageE nonz)\n  next\n    case (Suc n)\n    then show ?thesis\n      by (metis DF_Suc DF_ne Inf_nat_def1 gr0I gr_implies_not0 less_sets_def)\n  qed\n  have DF_N: \"DF k i \\<subseteq> N\" for i k\n  proof (induction i)\n    case 0\n    then show ?case\n      using \\<open>infinite N\\<close> range_enum by (auto simp: DF_simps)\n  next\n    case (Suc i)\n    then show ?case\n      unfolding DF_simps DF_Suc_def image_subset_iff\n      by (metis IntE \\<open>infinite N\\<close> enumerate_in_set infinite_nxtN nxt_def)\n  qed\n\n  have sm_enum_DF: \"strict_mono_on (enum (DF k i)) {..k}\" for k i\n    by (metis card_DF enum_works_finite finite_DF lessThan_Suc_atMost)\n\n  define AF where \"AF \\<equiv> \\<lambda>k i. enum (nxt N (Max (DF k i))) ` {..<Inf (DF k i)}\"\n  have AF_ne: \"AF k i \\<noteq> {}\" for i k\n    by (auto simp: AF_def lessThan_empty_iff DF_gt0)\n  have finite_AF [simp]: \"finite (AF k i)\" for i k\n    by (simp add: AF_def)\n  have card_AF: \"card (AF k i) = \\<Sqinter> (DF k i)\" for k i\n    by (simp add: AF_def card_image inj_enum_nxt)\n\n  have DF_AF: \"DF k i \\<lless> AF k i\" for i k\n    unfolding less_sets_def AF_def\n    by (simp add: finite_DF greaterThan_less_enum nxt_subset_greaterThan)\n\n  have E: \"\\<lbrakk>x \\<le> y; infinite M\\<rbrakk> \\<Longrightarrow> enum M x < enum (nxt N (enum M y)) z\" for x y z M\n    by (metis infinite_nxt_N dual_order.eq_iff enumerate_mono greaterThan_less_enum nat_less_le nxt_subset_greaterThan)\n\n  have AF_DF_Suc: \"AF k i \\<lless> DF k (Suc i)\" for i k\n    by (auto simp: DF_simps DF_Suc_def less_sets_def AF_def E)\n\n  have AF_DF: \"AF k p \\<lless> DF k q\" if \"p<q\" for k p q\n    by (metis AF_DF_Suc DF_ne Suc_lessI UNIV_I less_sets_trans sm_DF strict_mono_sets_def that)\n\n  have AF_Suc: \"AF k i \\<lless> AF k (Suc i)\" for i k\n    using AF_DF_Suc DF_AF DF_ne less_sets_trans by blast\n  then have sm_AF: \"strict_mono_sets UNIV (AF k)\" for k\n    by (simp add: AF_ne less_sets_imp_strict_mono_sets)\n\n  define del where \"del \\<equiv> \\<lambda>k i j. enum (DF k i) j - enum (DF k i) (j - 1)\"\n\n  define QF where \"QF k \\<equiv> wfrec pair_less (\\<lambda>f (j,i).\n       if j=0 then AF k i\n       else let r = (if i=0 then f (j-1,m-1) else f (j,i-1)) in\n                enum (nxt N (Suc (Max r))) ` {..< del k (if j=k then m - Suc i else i) j})\"\n    for k\n  note cut_apply [simp]\n\n  have finite_QF [simp]: \"finite (QF k p)\" for p k\n    using wf_pair_less\n  proof (induction p rule: wf_induct_rule)\n    case (less p)\n    then show ?case\n      by (simp add: def_wfrec [OF QF_def, of k p] split: prod.split)\n  qed\n\n  have del_gt_0: \"\\<lbrakk>j < Suc k; 0 < j\\<rbrakk> \\<Longrightarrow> 0 < del k i j\" for i j k\n    by (simp add: card_DF del_def finite_DF)\n\n  have QF_ne [simp]: \"QF k (j,i) \\<noteq> {}\" if j: \"j < Suc k\" for j i k\n    using wf_pair_less j\n  proof (induction \"(j,i)\" rule: wf_induct_rule)\n    case less\n    then show ?case\n      by (auto simp: def_wfrec [OF QF_def, of k \"(j,i)\"] AF_ne lessThan_empty_iff del_gt_0)\n  qed\n\n  have QF_0 [simp]: \"QF k (0,i) = AF k i\" for i k\n    by (simp add: def_wfrec [OF QF_def])\n\n  have QF_Suc: \"QF k (Suc j,0) = enum (nxt N (Suc (Max (QF k (j, m - 1))))) `\n                       {..< del k (if Suc j = k then m - 1 else 0) (Suc j)}\" for j k\n    apply (simp add: def_wfrec [OF QF_def, of k \"(Suc j,0)\"] One_nat_def)\n    apply (simp add: pair_less_def cut_def)\n    done\n\n  have QF_Suc_Suc: \"QF k (Suc j, Suc i)\n                  = enum (nxt N (Suc (Max (QF k (Suc j, i))))) ` {..< del k (if Suc j = k then m - Suc(Suc i) else Suc i) (Suc j)}\"\n    for i j k\n    by (simp add: def_wfrec [OF QF_def, of k \"(Suc j,Suc i)\"])\n\n  have less_QF1: \"QF k (j, m - 1) \\<lless> QF k (Suc j,0)\" for j k\n    by (auto simp: def_wfrec [OF QF_def, of k \"(Suc j,0)\"] pair_lessI1 enum_nxt_ge\n        intro!: less_sets_weaken2 [OF less_sets_Suc_Max])\n\n  have less_QF2: \"QF k (j,i) \\<lless> QF k (j, Suc i)\" for j i k\n    by (auto simp: def_wfrec [OF QF_def, of k \"(j, Suc i)\"] pair_lessI2 enum_nxt_ge\n        intro: less_sets_weaken2 [OF less_sets_Suc_Max] strict_mono_setsD [OF sm_AF])\n\n  have less_QF_same: \"QF k (j,i') \\<lless> QF k (j,i)\"\n    if \"i' < i\" \"j \\<le> k\" for i' i j k\n  proof (rule strict_mono_setsD [OF less_sets_imp_strict_mono_sets])\n    show \"QF k (j, i) \\<lless> QF k (j, Suc i)\" for i\n      by (simp add: less_QF2)\n    show \"QF k (j, i) \\<noteq> {}\" if \"0 < i\" for i\n      using that by (simp add: \\<open>j \\<le> k\\<close> le_imp_less_Suc)\n  qed (use that in auto)\n\n  have less_QF_step: \"QF k (j-1, i') \\<lless> QF k (j,i)\"\n    if \"0 < j\" \"j \\<le> k\" \"i' < m\" for j i' i k\n  proof -\n    have less_QF1': \"QF k (j - 1, m-1) \\<lless> QF k (j,0)\" if \"j > 0\" for j\n      by (metis less_QF1 that Suc_pred One_nat_def)\n    have \"QF k (j-1, i') \\<lless> QF k (j,0)\"\n    proof (cases \"i' = m - 1\")\n      case True\n      then show ?thesis\n        using less_QF1' \\<open>0 < j\\<close> by blast\n    next\n      case False\n      show ?thesis\n        using False that less_sets_trans [OF less_QF_same less_QF1' QF_ne] by auto\n    qed\n    then show ?thesis\n      by (metis QF_ne less_QF_same less_Suc_eq_le less_sets_trans \\<open>j \\<le> k\\<close> zero_less_iff_neq_zero)\n  qed\n\n  have less_QF: \"QF k (j',i') \\<lless> QF k (j,i)\"\n    if j: \"j' < j\" \"j \\<le> k\" and i: \"i' < m\" \"i < m\" for j' j i' i k\n    using j\n  proof (induction \"j-j'\" arbitrary: j)\n    case (Suc d)\n    show ?case\n    proof (cases \"j' < j - 1\")\n      case True\n      then have \"QF k (j', i') \\<lless> QF k (j - 1, i)\"\n        using Suc.hyps Suc.prems(2) by force\n      then show ?thesis\n        by (rule less_sets_trans [OF _ less_QF_step QF_ne]) (use Suc i in auto)\n    next\n      case False\n      then have \"j' = j - 1\"\n        using \\<open>j' < j\\<close> by linarith\n      then show ?thesis\n        using Suc.hyps \\<open>j \\<le> k\\<close> less_QF_step i by auto\n    qed\n  qed auto\n\n  have sm_QF: \"strict_mono_sets ({..k} \\<times> {..<m}) (QF k)\" for k\n    unfolding strict_mono_sets_def\n  proof (intro strip)\n    fix p q\n    assume p: \"p \\<in> {..k} \\<times> {..<m}\" and q: \"q \\<in> {..k} \\<times> {..<m}\" and \"p < q\"\n    then obtain j' i' j i where \\<section>: \"p = (j',i')\" \"q = (j,i)\" \"i' < m\" \"i < m\" \"j' \\<le> k\" \"j \\<le> k\"\n      using surj_pair [of p] surj_pair [of q] by blast\n    with \\<open>p < q\\<close> have \"j' < j \\<or> j' = j \\<and> i' < i\"\n      by auto\n    then show \"QF k p \\<lless> QF k q\"\n      using \\<section> less_QF less_QF_same by presburger\n  qed\n  then have sm_QF1: \"strict_mono_sets {..<ka} (\\<lambda>j. QF k (j,i))\"\n    if \"i<m\" \"Suc k \\<ge> ka\" \"ka \\<ge> k\" for ka k i\n  proof -\n    have \"{..<ka} \\<subseteq> {..k}\"\n      by (metis lessThan_Suc_atMost lessThan_subset_iff \\<open>Suc k \\<ge> ka\\<close>)\n    then show ?thesis\n      by (simp add: less_QF strict_mono_sets_def subset_iff that)\n  qed\n\n  have disjoint_QF: \"i'=i \\<and> j'=j\" if \"\\<not> disjnt (QF k (j', i')) (QF k (j,i))\" \"j' \\<le> k\" \"j \\<le> k\" \"i' < m\" \"i < m\" for i' i j' j k\n    using that strict_mono_sets_imp_disjoint [OF sm_QF]\n    by (force simp: pairwise_def)\n\n  have card_QF: \"card (QF k (j,i)) = (if j=0 then \\<Sqinter> (DF k i) else del k (if j = k then m - Suc i else i) j)\"\n    for i k j\n  proof (cases j)\n    case 0\n    then show ?thesis\n      by (simp add: AF_def card_image inj_enum_nxt)\n  next\n    case (Suc j')\n    show ?thesis\n      by (cases i; simp add: Suc One_nat_def QF_Suc QF_Suc_Suc card_image inj_enum_nxt)\n  qed\n  have AF_non_Nil: \"list_of (AF k i) \\<noteq> []\" for k i\n    by (simp add: AF_ne)\n  have QF_non_Nil: \"list_of (QF k (j,i)) \\<noteq> []\" if \"j < Suc k\" for i j k\n    by (simp add: that)\n\n  have AF_subset_N: \"AF k i \\<subseteq> N\" for i k\n    unfolding AF_def image_subset_iff\n    using nxt_subset enumerate_in_set infinite_nxtN \\<open>infinite N\\<close> by blast\n\n  have QF_subset_N: \"QF k (j,i) \\<subseteq> N\" for i j k\n  proof (induction j)\n    case (Suc j)\n    show ?case\n      by (cases i) (use nxt_subset enumerate_in_set in \\<open>(force simp: QF_Suc QF_Suc_Suc)+\\<close>)\n  qed (use AF_subset_N in auto)\n\n  obtain ka k where \"k>0\" and kka: \"k \\<le> ka\" \"ka \\<le> Suc k\" \"l = ((ka+k) - 1)\"\n    by (metis One_nat_def assms(2) diff_add_inverse form_cases le0 le_refl)\n  then have \"ka > 0\"\n    using dual_order.strict_trans1 by blast\n  have ka_k_or_Suc: \"ka = k \\<or> ka = Suc k\"\n    using kka by linarith\n  have lessThan_k: \"{..<k} = insert 0 {0<..<k}\" if \"k>0\" for k::nat\n    using that by auto\n  then have sorted_list_of_set_k: \"list_of {..<k} = 0 # list_of {0<..<k}\" if \"k>0\" for k::nat\n    using sorted_list_of_set_insert_remove_cons [of concl: 0 \"{0<..<k}\"] that by simp\n\n  define RF where \"RF \\<equiv> \\<lambda>j i. if j = k then QF k (j, m - Suc i) else QF k (j,i)\"\n  have RF_subset_N: \"RF j i \\<subseteq> N\" if \"i<m\" for i j\n    using that QF_subset_N by (simp add: RF_def)\n  have finite_RF [simp]: \"finite (RF k p)\" for p k\n    by (simp add: RF_def)\n  have RF_0: \"RF 0 i = AF k i\" for i\n    using RF_def \\<open>0 < k\\<close> by auto\n  have disjoint_RF: \"i'=i \\<and> j'=j\" if \"\\<not> disjnt (RF j' i') (RF j i)\" \"j' \\<le> k\" \"j \\<le> k\" \"i' < m\" \"i < m\" for i' i j' j\n    using disjoint_QF that\n    by (auto simp: RF_def split: if_split_asm dest: disjoint_QF)\n\n  have sum_card_RF [simp]: \"(\\<Sum>j\\<le>n. card (RF j i)) = enum (DF k i) n\" if \"n \\<le> k\" \"i < m\" for i n\n    using that\n  proof (induction n)\n    case 0\n    then show ?case\n      using DF_ne [of k i] finite_DF [of k i] \\<open>k>0\\<close>\n      by (simp add: RF_def AF_def card_image inj_enum_nxt enum_0_eq_Inf_finite)\n  next\n    case (Suc n)\n    then have \"enum (DF k i) 0 \\<le> enum (DF k i) n \\<and> enum (DF k i) n \\<le> enum (DF k i) (Suc n)\"\n      using sm_enum_DF [of k i]\n      by (metis Suc_leD card_DF dual_order.eq_iff finite_DF finite_enumerate_mono le_imp_less_Suc less_imp_le_nat not_gr_zero)\n    with Suc show ?case\n      by (auto simp: RF_def card_QF del_def)\n  qed\n  have DF_in_N: \"enum (DF k i) j \\<in> N\" if \"j \\<le> k\" for i j\n    by (metis DF_N card_DF finite_DF finite_enumerate_in_set le_imp_less_Suc subsetD that)\n  have Inf_DF_N: \"\\<Sqinter>(DF k p) \\<in> N\" for k p\n    using DF_N DF_ne Inf_nat_def1 by blast\n  have RF_in_N: \"(\\<Sum>j\\<le>n. card (RF j i)) \\<in> N\" if \"n \\<le> k\" \"i < m\" for i n\n    by (auto simp: DF_in_N that)\n\n  have \"ka - 1 \\<le> k\"\n    using kka(2) by linarith\n  then have sum_card_RF' [simp]:\n    \"(\\<Sum>j<ka. card (RF j i)) = enum (DF k i) (ka - 1)\" if \"i < m\" for i\n    using sum_card_RF [of \"ka - 1\" i]\n    by (metis Suc_diff_1 \\<open>0 < ka\\<close> lessThan_Suc_atMost that)\n\n  have enum_DF_le_iff [simp]:\n    \"enum (DF k i) j \\<le> enum (DF k i') j \\<longleftrightarrow> i \\<le> i'\" (is \"?lhs = _\")\n    if \"j \\<le> k\" for i' i j k\n  proof\n    show \"i \\<le> i'\" if ?lhs\n    proof -\n      have \"enum (DF k i) j \\<in> DF k i\"\n        by (simp add: card_DF finite_enumerate_in_set finite_DF le_imp_less_Suc \\<open>j \\<le> k\\<close>)\n      moreover have \"enum (DF k i') j \\<in> DF k i'\"\n        by (simp add: \\<open>j \\<le> k\\<close> card_DF finite_enumerate_in_set finite_DF le_imp_less_Suc that)\n      ultimately have \"enum (DF k i') j < enum (DF k i) j\" if \"i' < i\"\n        using sm_DF [of k] by (meson UNIV_I less_sets_def strict_mono_setsD that)\n      then show ?thesis\n        using not_less that by blast\n    qed\n    show ?lhs if \"i \\<le> i'\"\n      using sm_DF [of k] that \\<open>j \\<le> k\\<close> card_DF finite_enumerate_in_set finite_DF le_eq_less_or_eq\n      by (force simp: strict_mono_sets_def less_sets_def finite_enumerate_in_set)\n  qed\n  then have enum_DF_eq_iff[simp]:\n    \"enum (DF k i) j = enum (DF k i') j \\<longleftrightarrow> i = i'\" if \"j \\<le> k\" for i' i j k\n    by (metis le_antisym order_refl that)\n  have enum_DF_less_iff [simp]:\n    \"enum (DF k i) j < enum (DF k i') j \\<longleftrightarrow> i < i'\" if \"j \\<le> k\" for i' i j k\n    by (meson enum_DF_le_iff not_less that)\n\n  have card_AF_sum: \"card (AF k i) + (\\<Sum>j\\<in>{0<..<ka}. card (RF j i)) = enum (DF k i) (ka-1)\"\n    if \"i < m\" for i\n    using that \\<open>k > 0\\<close>  \\<open>k \\<le> ka\\<close> \\<open>ka \\<le> Suc k\\<close>\n    by (simp add: lessThan_k RF_0 flip: sum_card_RF')\n\n  have sorted_list_of_set_iff [simp]: \"list_of {0<..<k} = [] \\<longleftrightarrow> k = 1\" if \"k>0\" for k::nat\n  proof -\n    have \"list_of {0<..<k} = [] \\<longleftrightarrow> {0<..<k} = {}\"\n      by simp\n    also have \"\\<dots> \\<longleftrightarrow> k = 1\"\n      using \\<open>k > 0\\<close> atLeastSucLessThan_greaterThanLessThan by fastforce\n    finally show ?thesis .\n  qed\n  show thesis \\<comment>\\<open>proof of main result\\<close>\n  proof\n    have inj: \"inj_on (\\<lambda>i. list_of (\\<Union>j<ka. RF j i)) {..<m}\"\n    proof (clarsimp simp: inj_on_def)\n      fix x y\n      assume \"x < m\" \"y < m\" \"list_of (\\<Union>j<ka. RF j x) = list_of (\\<Union>j<ka. RF j y)\"\n      then have eq: \"(\\<Union>j<ka. RF j x) = (\\<Union>j<ka. RF j y)\"\n        by (simp add: sorted_list_of_set_inject)\n      show \"x = y\"\n      proof -\n        obtain n where n: \"n \\<in> RF 0 x\"\n          using AF_ne QF_0 \\<open>0 < k\\<close> Inf_nat_def1 \\<open>k \\<le> ka\\<close> by (force simp: RF_def)\n        with eq \\<open>ka > 0\\<close> obtain j' where \"j' < ka\" \"n \\<in> RF j' y\"\n          by blast\n        then show ?thesis\n          using disjoint_QF [of k 0 x j'] n \\<open>x < m\\<close> \\<open>y < m\\<close> \\<open>ka \\<le> Suc k\\<close> \\<open>0 < k\\<close>\n          by (force simp: RF_def disjnt_iff simp del: QF_0 split: if_split_asm)\n      qed\n    qed\n\n    define M where \"M \\<equiv> (\\<lambda>i. list_of (\\<Union>j<ka. RF j i)) ` {..<m}\"\n    have \"finite M\"\n      unfolding M_def by blast\n    moreover have \"card M = m\"\n      by (simp add: M_def \\<open>k \\<le> ka\\<close> card_image inj)\n    moreover have \"M \\<subseteq> WW\"\n      by (force simp: M_def WW_def)\n    ultimately show \"M \\<in> [WW]\\<^bsup>m\\<^esup>\"\n      by (simp add: nsets_def)\n\n    have sm_RF: \"strict_mono_sets {..<ka} (\\<lambda>j. RF j i)\" if \"i<m\" for i\n      using sm_QF1 that kka\n      by (simp add: less_QF RF_def strict_mono_sets_def)\n\n    have RF_non_Nil: \"list_of (RF j i) \\<noteq> []\" if \"j < Suc k\" for i j\n      using that by (simp add: RF_def)\n\n    have less_RF_same: \"RF j i' \\<lless> RF j i\"\n      if \"i' < i\" \"j < k\" for i' i j\n      using that by (simp add: less_QF_same RF_def)\n\n    have less_RF_same_k: \"RF k i' \\<lless> RF k i\" \\<comment>\\<open>reversed version for @{term k}\\<close>\n      if \"i < i'\" \"i' < m\" for i' i\n      using that by (simp add: less_QF_same RF_def)\n\n    show \"Form l U \\<and> list.set (inter_scheme l U) \\<subseteq> N\" if \"U \\<in> [M]\\<^bsup>2\\<^esup>\" for U\n    proof -\n      from that obtain x y where \"U = {x,y}\" \"x \\<in> M\" \"y \\<in> M\" and xy: \"(x,y) \\<in> lenlex less_than\"\n        by (auto simp: lenlex_nsets_2_eq)\n      let ?R = \"\\<lambda>p. list_of \\<circ> (\\<lambda>j. RF j p)\"\n      obtain p q where x: \"x = list_of (\\<Union>j<ka. RF j p)\"\n        and y: \"y = list_of (\\<Union>j<ka. RF j q)\" and \"p < m\" \"q < m\"\n        using \\<open>x \\<in> M\\<close> \\<open>y \\<in> M\\<close> by (auto simp: M_def)\n      then have pq: \"p<q\" \"length x < length y\"\n        using xy \\<open>k \\<le> ka\\<close> \\<open>ka \\<le> Suc k\\<close> lexl_not_refl [OF irrefl_less_than]\n        by (auto simp: lenlex_def sm_RF sorted_list_of_set_UN_lessThan length_concat sum_sorted_list_of_set_map)\n      moreover\n      have xc: \"x = concat (map (?R p) (list_of {..<ka}))\"\n        by (simp add: x sorted_list_of_set_UN_eq_concat \\<open>k \\<le> ka\\<close> \\<open>ka \\<le> Suc k\\<close> \\<open>p < m\\<close> sm_RF)\n      have yc: \"y = concat (map (?R q) (list_of {..<ka}))\"\n        by (simp add: y sorted_list_of_set_UN_eq_concat \\<open>k \\<le> ka\\<close> \\<open>ka \\<le> Suc k\\<close> \\<open>q < m\\<close> sm_RF)\n      have enum_DF_AF: \"enum (DF k p) (ka - 1) < hd (list_of (AF k p))\" for p\n      proof (rule less_setsD [OF DF_AF])\n        show \"enum (DF k p) (ka - 1) \\<in> DF k p\"\n          using \\<open>ka \\<le> Suc k\\<close> card_DF finite_DF by (auto simp: finite_enumerate_in_set)\n        show \"hd (list_of (AF k p)) \\<in> AF k p\"\n          using AF_non_Nil finite_AF hd_in_set set_sorted_list_of_set by blast\n      qed\n\n      have less_RF_RF: \"RF n p \\<lless> RF n q\" if \"n < k\" for n\n        using that \\<open>p<q\\<close> by (simp add: less_RF_same)\n      have less_RF_Suc: \"RF n q \\<lless> RF (Suc n) q\" if \"n < k\" for n\n        using \\<open>q < m\\<close> that by (auto simp: RF_def less_QF)\n      have less_RF_k: \"RF k q \\<lless> RF k p\"\n        using \\<open>q < m\\<close> less_RF_same_k \\<open>p<q\\<close> by blast\n      have less_RF_k_ka: \"RF (k-1) p \\<lless> RF (ka - 1) q\"\n        using ka_k_or_Suc less_RF_RF\n        by (metis One_nat_def RF_def \\<open>0 < k\\<close> \\<open>ka - 1 \\<le> k\\<close> \\<open>p < m\\<close> diff_Suc_1 diff_Suc_less less_QF_step)\n      have Inf_DF_eq_enum: \"\\<Sqinter> (DF k i) = enum (DF k i) 0\" for k i\n        by (simp add: Inf_nat_def enumerate_0)\n\n      have Inf_DF_less: \"\\<Sqinter> (DF k i') < \\<Sqinter> (DF k i)\" if \"i'<i\" for i' i k\n        by (metis DF_ne enum_0_eq_Inf enum_0_eq_Inf_finite enum_DF_less_iff le0 that)\n      have AF_Inf_DF_less: \"\\<And>x. x \\<in> AF k i \\<Longrightarrow> \\<Sqinter> (DF k i') < x\" if \"i'\\<le>i\" for i' i k\n        using less_setsD [OF DF_AF] DF_ne that\n        by (metis Inf_DF_less Inf_nat_def1 dual_order.order_iff_strict dual_order.strict_trans)\n\n      show ?thesis \\<comment>\\<open>The general case requires @{term\\<open>k>1\\<close>}, necessitating a painful special case\\<close>\n      proof (cases \"k=1\")\n        case True\n        with kka consider \"ka=1\" | \"ka=2\" by linarith\n        then show ?thesis\n        proof cases\n          case 1\n          define zs where \"zs = card (AF 1 p) # list_of (AF 1 p)\n                              @ card (AF 1 q) # list_of (AF 1 q)\"\n          have zs: \"Form_Body ka k x y zs\"\n          proof (intro that exI conjI Form_Body.intros)\n            show \"x = concat ([list_of (AF k p)])\" \"y = concat ([list_of (AF k q)])\"\n              by (simp_all add: x y 1 lessThan_Suc RF_0)\n            have \"AF k p \\<lless> insert (\\<Sqinter> (DF k q)) (AF k q)\"\n              by (metis AF_DF DF_ne Inf_nat_def1 RF_0 \\<open>0 < k\\<close> insert_iff less_RF_RF less_sets_def pq(1))\n            then have \"strict_sorted (list_of (AF k p) @ \\<Sqinter> (DF k q) # list_of (AF k q))\"\n              by (auto simp: strict_sorted_append_iff intro: less_sets_imp_list_less AF_Inf_DF_less)\n            moreover have \"\\<And>x. x \\<in> AF k q \\<Longrightarrow> \\<Sqinter> (DF k p) < x\"\n              by (meson AF_Inf_DF_less less_imp_le_nat \\<open>p < q\\<close>)\n            moreover have \"\\<And>x. x \\<in> AF 1 p \\<Longrightarrow> \\<Sqinter> (DF 1 p) < x\"\n              by (meson DF_AF DF_ne Inf_nat_def1 less_setsD)\n            ultimately show \"strict_sorted zs\"\n              using \\<open>p < q\\<close> True Inf_DF_less DF_AF DF_ne\n              by (auto simp: zs_def less_sets_def card_AF AF_Inf_DF_less)\n          qed (auto simp: \\<open>k=1\\<close> \\<open>ka=1\\<close> zs_def AF_ne \\<open>length x < length y\\<close>)\n          have zs_N: \"list.set zs \\<subseteq> N\"\n            using AF_subset_N by (auto simp: zs_def card_AF Inf_DF_N \\<open>k=1\\<close>)\n          show ?thesis\n          proof\n            have \"l = 1\"\n              using kka \\<open>k=1\\<close> \\<open>ka=1\\<close> by auto\n            have \"Form (2*1-1) {x,y}\"\n              using \"1\" Form.intros(2) True zs by fastforce\n            then show \"Form l U\"\n              by (simp add: \\<open>U = {x,y}\\<close> \\<open>l = 1\\<close> One_nat_def)\n            show \"list.set (inter_scheme l U) \\<subseteq> N\"\n              using kka zs zs_N \\<open>k=1\\<close> Form_Body_imp_inter_scheme by (fastforce simp: \\<open>U = {x,y}\\<close>)\n          qed\n        next\n          case 2\n          note True [simp] note 2 [simp]\n          have [simp]: \"{0<..<2} = {1::nat}\"\n            by auto\n          have enum_DF1_eq: \"enum (DF 1 i) 1 = card (AF 1 i) + card (RF 1 i)\"\n            if \"i < m\" for i\n            using card_AF_sum that by (simp add: One_nat_def)\n          have card_RF: \"card (RF 1 i) = enum (DF 1 i) 1 - enum (DF 1 i) 0\" if \"i < m\" for i\n            using that by (auto simp: RF_def card_QF del_def)\n          have list_of_AF_RF: \"list_of (AF 1 q \\<union> RF 1 q) = list_of (AF 1 q) @ list_of (RF 1 q)\"\n            by (metis One_nat_def RF_0 True \\<open>0 < k\\<close> finite_RF less_RF_Suc sorted_list_of_set_Un)\n\n          define zs where \"zs = card (AF 1 p) # (card (AF 1 p) + card (RF 1 p)) # list_of (AF 1 p)\n                  @ (card (AF 1 q) + card (RF 1 q)) # list_of (AF 1 q) @ list_of (RF 1 q) @ list_of (RF 1 p)\"\n          have zs: \"Form_Body ka k x y zs\"\n          proof (intro that exI conjI Form_Body.intros)\n            have \"x = list_of (RF 0 p \\<union> RF 1 p)\"\n              by (simp add: x eval_nat_numeral lessThan_Suc RF_0 Un_commute One_nat_def)\n            also have \"\\<dots> = list_of (RF 0 p) @ list_of (RF 1 p)\"\n              using RF_def True \\<open>p < m\\<close> less_QF_step\n              by (metis QF_0 RF_0 diff_self_eq_0 finite_RF le_refl sorted_list_of_set_Un zero_less_one)\n            finally show \"x = concat ([list_of (AF 1 p),list_of (RF 1 p)])\"\n              by (simp add: RF_0)\n            show \"y = concat [list_of (RF 1 q \\<union> AF 1 q)]\"\n              by (simp add: y eval_nat_numeral lessThan_Suc RF_0 One_nat_def)\n            show zs: \"zs = concat [[card (AF 1 p), card (AF 1 p) + card (RF 1 p)], list_of (AF 1 p),\n                              [card (AF 1 q) + card (RF 1 q)], list_of (RF 1 q \\<union> AF 1 q)] @ interact [list_of (RF 1 p)] []\"\n              using list_of_AF_RF by (simp add: zs_def Un_commute)\n            show \"strict_sorted zs\"\n            proof (simp add: \\<open>p<m\\<close> \\<open>q<m\\<close> \\<open>p<q\\<close> zs_def strict_sorted_append_iff, intro conjI strip)\n              show \"0 < card (RF 1 p)\"\n                using \\<open>p<m\\<close> by (simp add: card_RF card_DF finite_DF)\n              show \"card (AF 1 p) < card (AF 1 q) + card (RF 1 q)\"\n                using \\<open>p<q\\<close> \\<open>q<m\\<close> by (simp add: Inf_DF_less card_AF trans_less_add1)\n              show \"card (AF 1 p) < x\"\n                if \"x \\<in> AF 1 p \\<union> (AF 1 q \\<union> (RF 1 q \\<union> RF 1 p))\" for x\n                using that\n                apply (simp add: card_AF)\n                by (metis AF_ne DF_AF DF_ne less_RF_RF less_RF_Suc less_RF_k Inf_nat_def1 One_nat_def RF_0 RF_non_Nil True finite_RF lessI less_setsD less_sets_trans sorted_list_of_set_eq_Nil_iff)\n              show \"card (AF 1 p) + card (RF 1 p) < card (AF 1 q) + card (RF 1 q)\"\n                using \\<open>p < q\\<close> \\<open>p < m\\<close> \\<open>q < m\\<close> by (metis enum_DF1_eq enum_DF_less_iff le_refl)\n              show \"card (AF 1 p) + card (RF 1 p) < x\"\n                if \"x \\<in> AF 1 p \\<union> (AF 1 q \\<union> (RF 1 q \\<union> RF 1 p))\" for x\n                using that \\<open>p < m\\<close>\n                apply (simp flip: enum_DF1_eq)\n                by (metis AF_ne DF_AF less_RF_RF less_RF_Suc less_RF_k One_nat_def RF_0 RF_non_Nil Suc_mono True \\<open>0 < k\\<close> card_DF finite_enumerate_in_set finite_DF less_setsD less_sets_trans sorted_list_of_set_empty)\n              have \"list_of (AF 1 p) < list_of {enum (DF 1 q) 1}\"\n              proof (rule less_sets_imp_sorted_list_of_set)\n                show \"AF 1 p \\<lless> {enum (DF 1 q) 1}\"\n                  by (metis AF_DF card_DF empty_subsetI finite_DF finite_enumerate_in_set insert_subset less_Suc_eq less_sets_weaken2 pq(1))\n              qed auto\n              then show \"list_of (AF 1 p) < (card (AF 1 q) + card (RF 1 q)) # list_of (AF 1 q) @ list_of (RF 1 q) @ list_of (RF 1 p)\"\n                using \\<open>q < m\\<close> by (simp add: less_list_def enum_DF1_eq)\n              show \"card (AF 1 q) + card (RF 1 q) < x\"\n                if \"x \\<in> AF 1 q \\<union> (RF 1 q \\<union> RF 1 p)\" for x\n                using that \\<open>q < m\\<close>\n                apply (simp flip: enum_DF1_eq)\n                by (metis AF_ne DF_AF less_RF_Suc less_RF_k One_nat_def RF_0 RF_non_Nil True card_DF finite_enumerate_in_set finite_DF finite_RF lessI less_setsD less_sets_trans sorted_list_of_set_eq_Nil_iff)\n              have \"list_of (AF 1 q) < list_of (RF 1 q)\"\n              proof (rule less_sets_imp_sorted_list_of_set)\n                show \"AF 1 q \\<lless> RF 1 q\"\n                  by (metis less_RF_Suc One_nat_def RF_0 True \\<open>0 < k\\<close>)\n              qed auto\n              then show \"list_of (AF 1 q) < list_of (RF 1 q) @ list_of (RF 1 p)\"\n                using RF_non_Nil by (auto simp: less_list_def)\n              show \"list_of (RF 1 q) < list_of (RF 1 p)\"\n              proof (rule less_sets_imp_sorted_list_of_set)\n                show \"RF 1 q \\<lless> RF 1 p\"\n                  by (metis less_RF_k True)\n              qed auto\n            qed\n            show \"[list_of (AF 1 p), list_of (RF 1 p)] \\<in> lists (- {[]})\"\n              using RF_non_Nil \\<open>0 < k\\<close> by (auto simp: zs_def AF_ne)\n            show \"[card (AF 1 q) + card (RF 1 q)] = acc_lengths 0 [list_of (RF 1 q \\<union> AF 1 q)]\"\n              using list_of_AF_RF\n              by (auto simp: zs_def AF_ne sup_commute)\n          qed (auto simp: zs_def AF_ne \\<open>length x < length y\\<close>)\n          have zs_N: \"list.set zs \\<subseteq> N\"\n            using \\<open>p < m\\<close> \\<open>q < m\\<close> DF_in_N  enum_DF1_eq [symmetric]\n            by (auto simp: zs_def card_AF AF_subset_N RF_subset_N Inf_DF_N)\n          show ?thesis\n          proof\n            have \"Form (2*1) {x,y}\"\n              by (metis \"2\" Form.simps Suc_1 True zero_less_one zs)\n            with kka show \"Form l U\"\n              by (simp add: \\<open>U = {x,y}\\<close>)\n            show \"list.set (inter_scheme l U) \\<subseteq> N\"\n              using kka zs zs_N \\<open>k=1\\<close> Form_Body_imp_inter_scheme by (fastforce simp: \\<open>U = {x, y}\\<close>)\n          qed\n        qed\n      next\n        case False\n        then have \"k \\<ge> 2\" \"ka \\<ge> 2\"\n          using kka \\<open>k>0\\<close> by auto\n        then have k_minus_1 [simp]: \"Suc (k - Suc (Suc 0)) = k - Suc 0\"\n          by auto\n        have [simp]: \"Suc (k - 2) = k-1\"\n          using \\<open>k \\<ge> 2\\<close> by linarith\n        define PP where \"PP \\<equiv> map (?R p) (list_of {0<..<ka})\"\n        define QQ where \"QQ \\<equiv> map (?R q) (list_of {0<..<k-1}) @ ([list_of (RF (k-1) q \\<union> RF (ka-1) q)])\"\n        let ?INT = \"interact PP QQ\"\n        \\<comment>\\<open>No separate sets A and B as in the text, but instead we treat both cases as once\\<close>\n        have [simp]: \"length PP = ka - 1\"\n          by (simp add: PP_def)\n        have [simp]: \"length QQ = k-1\"\n          using \\<open>k \\<ge> 2\\<close> by (simp add: QQ_def)\n\n        have PP_n: \"PP ! n = list_of (RF (Suc n) p)\"\n          if \"n < ka-1\" for n\n          using that kka by (auto simp: PP_def nth_sorted_list_of_set_greaterThanLessThan)\n\n        have QQ_n: \"QQ ! n = (if n < k-2 then list_of (RF (Suc n) q)\n                              else list_of (RF (k-1) q \\<union> RF (ka - 1) q))\"\n          if \"n < k-1\" for n\n          using that kka by (auto simp: QQ_def nth_append nth_sorted_list_of_set_greaterThanLessThan)\n\n        have QQ_n_same: \"QQ ! n = list_of (RF (Suc n) q)\"\n          if \"n < k-1\" \"k=ka\" for n\n          using that kka Suc_diff_Suc\n          by (fastforce simp: One_nat_def QQ_def nth_append nth_sorted_list_of_set_greaterThanLessThan)\n\n        have split_nat_interval: \"{0<..<n} = insert (n-1) {0<..<n-1}\" if \"n \\<ge> 2\" for n::nat\n          using that by auto\n        have split_list_interval: \"list_of{0<..<n} = list_of{0<..<n-1} @ [n-1]\" if \"n \\<ge> 2\" for n::nat\n        proof (intro sorted_list_of_set_unique [THEN iffD1] conjI)\n          have \"list_of {0<..<n - 1} < [n - 1]\"\n            by (auto intro: less_sets_imp_list_less)\n          then show \"strict_sorted (list_of {0<..<n - 1} @ [n - 1])\"\n            by (auto simp: strict_sorted_append_iff)\n        qed (use \\<open>n \\<ge> 2\\<close> in auto)\n\n        have list_of_RF_Un: \"list_of (RF (k-1) q \\<union> RF k q) = list_of (RF (k-1) q) @ list_of (RF k q)\"\n          by (metis Suc_diff_1 \\<open>0 < k\\<close> finite_RF lessI less_RF_Suc sorted_list_of_set_Un)\n\n        have card_AF_sum_QQ: \"card (AF k q) + sum_list (map length QQ) = (\\<Sum>j<ka. card (RF j q))\"\n        proof (cases \"ka = Suc k\")\n          case True\n          have \"RF (k-1) q \\<inter> RF k q = {}\"\n            using less_RF_Suc [of \"k-1\"] \\<open>k > 0\\<close> by (auto simp: less_sets_def)\n          then have \"card (RF (k-1) q \\<union> RF k q) = card (RF (k-1) q) + card (RF k q)\"\n            by (simp add: card_Un_disjoint)\n          then show ?thesis\n            using \\<open>k\\<ge>2\\<close> \\<open>q < m\\<close>\n            apply (simp add: QQ_def True flip: RF_0)\n            apply (simp add: lessThan_k split_nat_interval sum_sorted_list_of_set_map)\n            done\n        next\n          case False\n          with kka have \"ka=k\" by linarith\n          with \\<open>k\\<ge>2\\<close> show ?thesis by (simp add: QQ_def lessThan_k split_nat_interval sum_sorted_list_of_set_map flip: RF_0)\n        qed\n\n        define LENS where \"LENS \\<equiv> \\<lambda>i. acc_lengths 0 (list_of (AF k i) # map (?R i) (list_of {0<..<ka}))\"\n        have LENS_subset_N: \"list.set (LENS i) \\<subseteq> N\" if \"i < m\" for i\n        proof -\n          have eq: \"(list_of (AF k i) # map (?R i) (list_of {0<..<ka})) = map (?R i) (list_of {..<ka})\"\n            using RF_0 \\<open>0 < ka\\<close> sorted_list_of_set_k by auto\n          let ?f = \"rec_nat [card (AF k i)] (\\<lambda>n r. r @ [(\\<Sum>j\\<le>Suc n. card (RF j i))])\"\n          have f: \"acc_lengths 0 (map (?R i) (list_of {..v})) = ?f v\" for v\n            by (induction v) (auto simp: RF_0 acc_lengths_append sum_sorted_list_of_set_map)\n          have 3: \"list.set (?f v) \\<subseteq> N\" if \"v \\<le> k\" for v\n            using that\n          proof (induction v)\n            case 0\n            have \"card (AF k i) \\<in> N\"\n              by (metis DF_N DF_ne Inf_nat_def1 card_AF subsetD)\n            with 0 show ?case by simp\n          next\n            case (Suc v)\n            then have \"enum (DF k i) (Suc v) \\<in> N\"\n              by (metis DF_N card_DF finite_enumerate_in_set finite_DF in_mono le_imp_less_Suc)\n            with Suc \\<open>i < m\\<close> show ?case\n              by (simp del: sum.atMost_Suc)\n          qed\n          show ?thesis\n            unfolding LENS_def\n            by (metis 3 Suc_pred' \\<open>0 < ka\\<close> \\<open>ka - 1 \\<le> k\\<close> eq f lessThan_Suc_atMost)\n        qed\n        define LENS_QQ where \"LENS_QQ \\<equiv> acc_lengths 0 (list_of (AF k q) # QQ)\"\n        have LENS_QQ_subset: \"list.set LENS_QQ \\<subseteq> list.set (LENS q)\"\n        proof (cases \"ka = Suc k\")\n          case True\n          with \\<open>k \\<ge> 2\\<close> show ?thesis\n            unfolding QQ_def LENS_QQ_def LENS_def\n            by (auto simp: list_of_RF_Un split_list_interval acc_lengths_append)\n        next\n          case False\n          then have \"ka=k\"\n            using kka by linarith\n          with \\<open>k \\<ge> 2\\<close> show ?thesis\n            by (simp add: QQ_def LENS_QQ_def LENS_def split_list_interval)\n        qed\n        have ss_INT: \"strict_sorted ?INT\"\n        proof (rule strict_sorted_interact_I)\n          fix n\n          assume \"n < length QQ\"\n          then have n: \"n < k-1\"\n            by simp\n          have \"n = k - 2\" if \"\\<not> n < k - 2\"\n            using n that by linarith\n          moreover have \"list_of (RF (Suc (k - 2)) p) < list_of (RF (k-1) q \\<union> RF (ka - 1) q)\"\n            by (auto simp: less_sets_imp_sorted_list_of_set less_sets_Un2 less_RF_RF less_RF_k_ka \\<open>0 < k\\<close>)\n          ultimately show \"PP ! n < QQ ! n\"\n            using \\<open>k \\<le> ka\\<close> n by (auto simp: PP_n QQ_n less_sets_imp_sorted_list_of_set less_RF_RF)\n        next\n          fix n\n          have V: \"\\<lbrakk>Suc n < ka - 1\\<rbrakk> \\<Longrightarrow> list_of (RF (Suc n) q) < list_of (RF (Suc (Suc n)) p)\" for n\n            by (smt RF_def Suc_leI \\<open>ka - 1 \\<le> k\\<close> \\<open>q < m\\<close> diff_Suc_1 finite_RF less_QF_step less_le_trans less_sets_imp_sorted_list_of_set nat_neq_iff zero_less_Suc)\n          have \"RF (k -  1) q \\<lless> RF k p\"\n            by (metis One_nat_def RF_non_Nil Suc_pred \\<open>0 < k\\<close> finite_RF lessI less_RF_Suc less_RF_k less_sets_trans sorted_list_of_set_eq_Nil_iff)\n          with kka have \"RF (k-1) q \\<union> RF (ka - 1) q \\<lless> RF k p\"\n            by (metis less_RF_k One_nat_def less_sets_Un1 antisym_conv2 diff_Suc_1 le_less_Suc_eq)\n          then have VI: \"list_of (RF (k-1) q \\<union> RF (ka - 1) q) < list_of (RF k p)\"\n            by (rule less_sets_imp_sorted_list_of_set) auto\n          assume \"Suc n < length PP\"\n          with \\<open>ka \\<le> Suc k\\<close> VI\n          show \"QQ ! n < PP ! Suc n\"\n            apply (clarsimp simp: PP_n QQ_n V)\n            by (metis One_nat_def Suc_1 Suc_lessI add.right_neutral add_Suc_right diff_Suc_Suc ka_k_or_Suc less_diff_conv)\n        next \n          show \"PP \\<in> lists (- {[]})\"\n            using RF_non_Nil kka\n            by (clarsimp simp: PP_def) (metis RF_non_Nil less_le_trans)\n          show \"QQ \\<in> lists (- {[]})\"\n            using RF_non_Nil kka\n            by (clarsimp simp: QQ_def) (metis RF_non_Nil Suc_pred \\<open>0 < k\\<close> less_SucI One_nat_def)\n        qed (use kka PP_def QQ_def in auto)\n        then have ss_QQ: \"strict_sorted (concat QQ)\"\n          using strict_sorted_interact_imp_concat by blast\n\n        obtain zs where zs: \"Form_Body ka k x y zs\" and zs_N: \"list.set zs \\<subseteq> N\"\n        proof (intro that exI conjI Form_Body.intros [OF \\<open>length x < length y\\<close>])\n          show \"x = concat (list_of (AF k p) # PP)\"\n            using \\<open>ka > 0\\<close> by (simp add: PP_def RF_0 xc sorted_list_of_set_k)\n          let ?YR = \"(map (list_of \\<circ> (\\<lambda>j. RF j q)) (list_of {0<..<ka}))\"\n          have \"concat ?YR = concat QQ\"\n          proof (rule strict_sorted_equal [OF ss_QQ])\n            show \"strict_sorted (concat ?YR)\"\n            proof (rule strict_sorted_concat_I, simp_all)\n              fix n\n              assume 0: \"Suc n < ka - Suc 0\" \n              then have \"Suc n < k\"\n                by (metis One_nat_def \\<open>ka - 1 \\<le> k\\<close> less_le_trans)\n              then show \"list_of (RF (list_of {0<..<ka} ! n) q) < list_of (RF (list_of {0<..<ka} ! Suc n) q)\"\n                by (simp add: Suc_lessD 0 less_RF_Suc less_sets_imp_sorted_list_of_set nth_sorted_list_of_set_greaterThanLessThan)\n            next\n              show \"?YR \\<in> lists (- {[]})\"\n                using RF_non_Nil \\<open>ka \\<le> Suc k\\<close> by (auto simp: mem_lists_non_Nil)\n            qed auto\n            show \"list.set (concat ?YR) = list.set (concat QQ)\"\n              using ka_k_or_Suc\n            proof\n              assume \"ka = k\"\n              then show \"list.set (concat (map (list_of \\<circ> (\\<lambda>j. RF j q)) (list_of {0<..<ka}))) = list.set (concat QQ)\"\n                using \\<open>k\\<ge>2\\<close> by simp (simp add: split_nat_interval QQ_def)\n            next\n              assume \"ka = Suc k\"\n              then show \"list.set (concat (map (list_of \\<circ> (\\<lambda>j. RF j q)) (list_of {0<..<ka}))) = list.set (concat QQ)\"\n                using \\<open>k\\<ge>2\\<close> by simp (auto simp: QQ_def split_nat_interval)\n            qed\n          qed\n          then show \"y = concat (list_of (AF k q) # QQ)\"\n            using \\<open>ka > 0\\<close> by (simp add: RF_0 yc sorted_list_of_set_k)\n          show \"list_of (AF k p) # PP \\<in> lists (- {[]})\" \"list_of (AF k q) # QQ \\<in> lists (- {[]})\"\n            using  RF_non_Nil kka by (auto simp: AF_ne PP_def QQ_def eq_commute [of \"[]\"])\n          show \"list.set ((LENS p @ list_of (AF k p) @ LENS_QQ @ list_of (AF k q) @ ?INT)) \\<subseteq> N\"\n            using AF_subset_N RF_subset_N LENS_subset_N \\<open>p < m\\<close> \\<open>q < m\\<close> LENS_QQ_subset\n            by (auto simp: subset_iff PP_def QQ_def)\n          show \"length (list_of (AF k p) # PP) = ka\" \"length (list_of (AF k q) # QQ) = k\"\n            using \\<open>0 < ka\\<close> \\<open>0 < k\\<close> by auto\n          show \"LENS p = acc_lengths 0 (list_of (AF k p) # PP)\"\n            by (auto simp: LENS_def PP_def)\n          show \"strict_sorted (LENS p @ list_of (AF k p) @ LENS_QQ @ list_of (AF k q) @ ?INT)\"\n            unfolding strict_sorted_append_iff\n          proof (intro conjI ss_INT)\n            show \"LENS p < list_of (AF k p) @ LENS_QQ @ list_of (AF k q) @ ?INT\"\n              using AF_non_Nil [of k p] \\<open>k \\<le> ka\\<close> \\<open>ka \\<le> Suc k\\<close> \\<open>p < m\\<close> card_AF_sum enum_DF_AF\n              by (simp add: enum_DF_AF less_list_def card_AF_sum LENS_def sum_sorted_list_of_set_map\n                       del: acc_lengths.simps)\n            show \"strict_sorted (LENS p)\"\n              unfolding LENS_def\n              by (rule strict_sorted_acc_lengths) (use RF_non_Nil AF_non_Nil kka in \\<open>auto simp: in_lists_conv_set\\<close>)\n            show \"strict_sorted LENS_QQ\"\n              unfolding LENS_QQ_def QQ_def\n              by (rule strict_sorted_acc_lengths) (use RF_non_Nil AF_non_Nil kka in \\<open>auto simp: in_lists_conv_set\\<close>)\n            have last_AF_DF: \"last (list_of (AF k p)) < \\<Sqinter> (DF k q)\"\n              using AF_DF [OF \\<open>p < q\\<close>, of k] AF_non_Nil [of k p] DF_ne [of k q]\n              by (metis Inf_nat_def1 finite_AF last_in_set less_sets_def set_sorted_list_of_set)\n            then show \"list_of (AF k p) < LENS_QQ @ list_of (AF k q) @ ?INT\"\n              by (simp add: less_list_def card_AF LENS_QQ_def)\n            show \"LENS_QQ < list_of (AF k q) @ ?INT\"\n              using AF_non_Nil [of k q] \\<open>q < m\\<close> card_AF_sum enum_DF_AF card_AF_sum_QQ\n              by (auto simp: less_list_def AF_ne hd_append card_AF_sum LENS_QQ_def)\n            show \"list_of (AF k q) < ?INT\"\n            proof -\n              have \"AF k q \\<lless> RF 1 p\"\n                using \\<open>0 < k\\<close> \\<open>p < m\\<close> \\<open>q < m\\<close> by (simp add: RF_def less_QF flip: QF_0)\n              then have \"last (list_of (AF k q)) < hd (list_of (RF 1 p))\"\n              proof (rule less_setsD)\n                show \"last (list_of (AF k q)) \\<in> AF k q\"\n                  using AF_non_Nil finite_AF last_in_set set_sorted_list_of_set by blast\n                show \"hd (list_of (RF 1 p)) \\<in> RF 1 p\"\n                  by (metis One_nat_def RF_non_Nil \\<open>0 < k\\<close> finite_RF hd_in_set not_less_eq set_sorted_list_of_set)\n              qed\n              with \\<open>k > 0\\<close> \\<open>ka \\<ge> 2\\<close> RF_non_Nil show ?thesis\n                by (simp add: One_nat_def hd_interact less_list_def sorted_list_of_set_greaterThanLessThan PP_def QQ_def)\n            qed\n          qed auto\n        qed (auto simp: LENS_QQ_def)\n        show ?thesis\n        proof (cases \"ka = k\")\n          case True\n          then have \"l = 2*k-1\"\n            by (simp add: kka(3) mult_2)\n          then show ?thesis\n            by (metis One_nat_def Form.intros(2) Form_Body_imp_inter_scheme True \\<open>0 < k\\<close> \\<open>U = {x, y}\\<close> kka zs zs_N)\n        next\n          case False\n          then have \"l = 2*k\"\n            using kka by linarith\n          then show ?thesis\n            by (metis One_nat_def False Form.intros(3) Form_Body_imp_inter_scheme \\<open>0 < k\\<close> \\<open>U = {x, y}\\<close> antisym kka le_SucE zs zs_N)\n        qed\n      qed\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Larson's Lemma 3.8\\<close>\n\nsubsubsection \\<open>Primitives needed for the inductive construction of @{term b}\\<close>\n\ndefinition IJ where \"IJ \\<equiv> \\<lambda>k. Sigma {..k} (\\<lambda>j::nat. {..<j})\"\n\nlemma IJ_iff: \"u \\<in> IJ k \\<longleftrightarrow> (\\<exists>j i. u = (j,i) \\<and> i<j \\<and> j\\<le>k)\"\n  by (auto simp: IJ_def)\n\nlemma finite_IJ: \"finite (IJ k)\"\n  by (auto simp: IJ_def)\n\nfun prev where\n  \"prev 0 0 = None\"\n| \"prev (Suc 0) 0 = None\"\n| \"prev (Suc j) 0 = Some (j, j - Suc 0)\"\n| \"prev j (Suc i) = Some (j,i)\"\n\nlemma prev_eq_None_iff: \"prev j i = None \\<longleftrightarrow> j \\<le> Suc 0 \\<and> i = 0\"\n  by (auto simp: le_Suc_eq elim: prev.elims)\n\nlemma prev_pair_less:\n  \"prev j i = Some ji' \\<Longrightarrow> (ji', (j,i)) \\<in> pair_less\"\n  by (auto simp: pair_lessI1 elim: prev.elims)\n\n\n\nlemma prev_maximal:\n  \"\\<lbrakk>prev j i = Some (j',i'); (ji'', (j,i)) \\<in> pair_less; ji'' \\<in> IJ k\\<rbrakk>\n   \\<Longrightarrow> (ji'', (j',i')) \\<in> pair_less \\<or> ji'' = (j',i')\"\n  by (force simp: IJ_def pair_less_def elim: prev.elims)\n\nlemma pair_less_prev:\n  assumes \"(u, (j,i)) \\<in> pair_less\" \"u \\<in> IJ k\"\n  shows \"prev j i = Some u \\<or> (\\<exists>x. (u, x) \\<in> pair_less \\<and> prev j i = Some x)\"\nproof (cases \"prev j i\")\n  case None\n  then show ?thesis\n    using assms by (force simp: prev_eq_None_iff pair_less_def IJ_def split: prod.split)\nnext\n  case (Some a)\n  then show ?thesis\n    by (metis assms prev_maximal prod.exhaust_sel)\nqed\n\n\nsubsubsection \\<open>Special primitives for the ordertype proof\\<close>\n\ndefinition USigma :: \"'a set set \\<Rightarrow> ('a set \\<Rightarrow> 'a set) \\<Rightarrow> 'a set set\"\n  where \"USigma \\<A> B \\<equiv> \\<Union>X\\<in>\\<A>. \\<Union>y \\<in> B X. {insert y X}\"\n\ndefinition usplit\n  where \"usplit f A \\<equiv> f (A - {Max A}) (Max A)\"\n\nlemma USigma_empty [simp]: \"USigma {} B = {}\"\n  by (auto simp: USigma_def)\n\nlemma USigma_iff:\n  assumes \"\\<And>I j. I \\<in> \\<I> \\<Longrightarrow> I \\<lless> J I \\<and> finite I\"\n  shows \"x \\<in> USigma \\<I> J \\<longleftrightarrow> usplit (\\<lambda>I j. I \\<in> \\<I> \\<and> j \\<in> J I \\<and> x = insert j I) x\"\nproof -\n  have [simp]: \"\\<And>I j. \\<lbrakk>I \\<in> \\<I>; j \\<in> J I\\<rbrakk> \\<Longrightarrow> Max (insert j I) = j\"\n    by (meson Max_insert2 assms less_imp_le less_sets_def)\n  show ?thesis\n  proof -\n    have \\<section>: \"j \\<notin> I\" if \"I \\<in> \\<I>\" \"j \\<in> J I\" for I j\n      using that by (metis assms less_irrefl less_sets_def)\n    have \"\\<exists>I\\<in>\\<I>. \\<exists>j\\<in>J I. x = insert j I\"\n      if \"x - {Max x} \\<in> \\<I>\" and \"Max x \\<in> J (x - {Max x})\" \"x \\<noteq> {}\"\n      using that by (metis Max_in assms infinite_remove insert_Diff)\n    then show ?thesis\n      by (auto simp: USigma_def usplit_def \\<section>)\n  qed\nqed\n\n\nproposition ordertype_append_image_IJ:\n  assumes lenB [simp]: \"\\<And>i j. i \\<in> \\<I> \\<Longrightarrow> j \\<in> J i \\<Longrightarrow> length (B j) = c\"\n    and AB: \"\\<And>i j. i \\<in> \\<I> \\<Longrightarrow> j \\<in> J i \\<Longrightarrow> A i < B j\"\n    and IJ: \"\\<And>i. i \\<in> \\<I> \\<Longrightarrow> i \\<lless> J i \\<and> finite i\"\n    and \\<beta>: \"\\<And>i. i \\<in> \\<I> \\<Longrightarrow> ordertype (B ` J i) (lenlex less_than) = \\<beta>\"\n    and A: \"inj_on A \\<I>\"\n  shows \"ordertype (usplit (\\<lambda>i j. A i @ B j) ` USigma \\<I> J) (lenlex less_than)\n       = \\<beta> * ordertype (A ` \\<I>) (lenlex less_than)\"\n    (is \"ordertype ?AB ?R = _ * ?\\<alpha>\")\nproof (cases \"\\<I> = {}\")\n  case False\n  have \"Ord \\<beta>\"\n    using \\<beta> False wf_Ord_ordertype by fastforce\n  show ?thesis\n  proof (subst ordertype_eq_iff)\n    define split where \"split \\<equiv> \\<lambda>l::nat list. (take (length l - c) l, (drop (length l - c) l))\"\n    have oB: \"ordermap (B ` J i) ?R (B j) \\<sqsubset> \\<beta>\" if \\<open>i \\<in> \\<I>\\<close> \\<open>j \\<in> J i\\<close> for i j\n      using \\<beta> less_TC_iff that by fastforce\n    then show \"Ord (\\<beta> * ?\\<alpha>)\"\n      by (intro \\<open>Ord \\<beta>\\<close> wf_Ord_ordertype Ord_mult; simp)\n    define f where \"f \\<equiv> \\<lambda>u. let (x,y) = split u in let i = inv_into \\<I> A x in\n                        \\<beta> * ordermap (A`\\<I>) ?R x + ordermap (B`J i) ?R y\"\n    have inv_into_IA [simp]: \"inv_into \\<I> A (A i) = i\" if \"i \\<in> \\<I>\" for i\n      by (simp add: A that)\n    show \"\\<exists>f. bij_betw f ?AB (elts (\\<beta> * ?\\<alpha>)) \\<and> (\\<forall>x\\<in>?AB. \\<forall>y\\<in>?AB. (f x < f y) = ((x, y) \\<in> ?R))\"\n      unfolding bij_betw_def\n    proof (intro exI conjI strip)\n      show \"inj_on f ?AB\"\n      proof (clarsimp simp: f_def inj_on_def split_def USigma_iff IJ usplit_def)\n        fix x y\n        assume \\<section>: \"\\<beta> * ordermap (A ` \\<I>) ?R (A (x - {Max x})) + ordermap (B ` J (x - {Max x})) ?R (B (Max x))\n                 = \\<beta> * ordermap (A ` \\<I>) ?R (A (y - {Max y})) + ordermap (B ` J (y - {Max y})) ?R (B (Max y))\"\n          and x: \"x - {Max x} \\<in> \\<I>\"\n          and y: \"y - {Max y} \\<in> \\<I>\"\n          and mx: \"Max x \\<in> J (x - {Max x})\"\n          and \"x = insert (Max x) x\"\n          and my: \"Max y \\<in> J (y - {Max y})\"\n        have \"ordermap (A`\\<I>) ?R (A (x - {Max x})) = ordermap (A`\\<I>) ?R (A (y - {Max y}))\"\n          and B_eq: \"ordermap (B ` J (x - {Max x})) ?R (B (Max x)) = ordermap (B ` J (y - {Max y})) ?R (B (Max y))\"\n          using mult_cancellation_lemma [OF \\<section>] oB mx my x y by blast+\n        then have \"A (x - {Max x}) = A (y - {Max y})\"\n          using x y by auto\n        then have \"x - {Max x} = y - {Max y}\"\n          by (metis x y inv_into_IA)\n        then show \"A (x - {Max x}) = A (y - {Max y}) \\<and> B (Max x) = B (Max y)\"\n          using B_eq mx my by auto\n      qed\n      show \"f ` ?AB = elts (\\<beta> * ?\\<alpha>)\"\n      proof\n        show \"f ` ?AB \\<subseteq> elts (\\<beta> * ?\\<alpha>)\"\n          using \\<open>Ord \\<beta>\\<close>\n          apply (clarsimp simp add: f_def split_def USigma_iff IJ usplit_def)\n          by (metis TC_small \\<beta> add_mult_less image_eqI ordermap_in_ordertype trans_llt wf_Ord_ordertype wf_llt)\n        show \"elts (\\<beta> * ?\\<alpha>) \\<subseteq> f ` ?AB\"\n        proof (clarsimp simp: f_def split_def image_iff USigma_iff IJ usplit_def Bex_def elim!: elts_multE split: prod.split)\n          fix \\<gamma> \\<delta>\n          assume \\<delta>: \"\\<delta> \\<in> elts \\<beta>\" and \\<gamma>: \"\\<gamma> \\<in> elts ?\\<alpha>\"\n          have \"\\<gamma> \\<in> ordermap (A ` \\<I>) (lenlex less_than) ` A ` \\<I>\"\n            by (meson \\<gamma> ordermap_surj subset_iff)\n          then obtain i where \"i \\<in> \\<I>\" and yv: \"\\<gamma> = ordermap (A`\\<I>) ?R (A i)\"\n            by blast\n          have \"\\<delta> \\<in> ordermap (B ` J i) (lenlex less_than) ` B ` J i\"\n            by (metis (no_types) \\<beta> \\<delta> \\<open>i \\<in> \\<I>\\<close> in_mono ordermap_surj)\n          then obtain j where \"j \\<in> J i\" and xu: \"\\<delta> = ordermap (B`J i) ?R (B j)\"\n            by blast\n          then have mji: \"Max (insert j i) = j\"\n            by (meson IJ Max_insert2 \\<open>i \\<in> \\<I>\\<close> less_imp_le less_sets_def)\n          have [simp]: \"i - {j} = i\"\n            using IJ \\<open>i \\<in> \\<I>\\<close> \\<open>j \\<in> J i\\<close> less_setsD by fastforce\n          show \"\\<exists>l. (\\<exists>K. K - {Max K} \\<in> \\<I> \\<and> Max K \\<in> J (K - {Max K}) \\<and> K = insert (Max K) K \\<and>\n                         l = A (K - {Max K}) @ B (Max K)) \\<and> \\<beta> * \\<gamma> + \\<delta> =\n                    \\<beta> *\n                    ordermap (A ` \\<I>) ?R (take (length l - c) l) +\n                    ordermap (B ` J (inv_into \\<I> A (take (length l - c) l)))\n                     ?R (drop (length l - c) l)\"\n          proof (intro conjI exI)\n          let ?ji = \"insert j i\"\n            show \"A i @ B j = A (?ji - {Max ?ji}) @ B (Max ?ji)\"\n              by (auto simp: mji)\n          qed (use \\<open>i \\<in> \\<I>\\<close> \\<open>j \\<in> J i\\<close> mji xu yv in auto)\n        qed\n      qed\n    next\n      fix p q\n      assume \"p \\<in> ?AB\" and \"q \\<in> ?AB\"\n      then obtain x y where peq: \"p = A (x - {Max x}) @ B (Max x)\"\n                      and qeq: \"q = A (y - {Max y}) @ B (Max y)\"\n                      and x: \"x - {Max x} \\<in> \\<I>\"\n                      and y: \"y - {Max y} \\<in> \\<I>\"\n                      and mx: \"Max x \\<in> J (x - {Max x})\"\n                      and my: \"Max y \\<in> J (y - {Max y})\"\n        by (auto simp: USigma_iff IJ usplit_def)\n      let ?mx = \"x - {Max x}\"\n      let ?my = \"y - {Max y}\"\n      show \"(f p < f q) \\<longleftrightarrow> ((p, q) \\<in> ?R)\"\n      proof\n        assume \"f p < f q\"\n        then\n        consider \"ordermap (A`\\<I>) ?R (A (x - {Max x})) < ordermap (A`\\<I>) ?R (A (y - {Max y}))\"\n          | \"ordermap (A`\\<I>) ?R (A (x - {Max x})) = ordermap (A`\\<I>) ?R (A (y - {Max y}))\"\n            \"ordermap (B`J (x - {Max x})) ?R (B (Max x)) < ordermap (B`J (y - {Max y})) ?R (B (Max y))\"\n          using x y mx my\n          by (auto dest: mult_cancellation_less simp: f_def split_def peq qeq oB)\n        then have \"(A ?mx @ B (Max x), A ?my @ B (Max y)) \\<in> ?R\"\n        proof cases\n          case 1\n          then have \"(A ?mx, A ?my) \\<in> ?R\"\n            using x y by (force simp: Ord_mem_iff_lt intro: converse_ordermap_mono)\n          then show ?thesis\n            using x y mx my lenB lenlex_append1 by blast\n        next\n          case 2\n          then have \"A ?mx = A ?my\"\n            using \\<open>?my \\<in> \\<I>\\<close> \\<open>?mx \\<in> \\<I>\\<close> by auto\n          then have eq: \"?mx = ?my\"\n            by (metis \\<open>?my \\<in> \\<I>\\<close> \\<open>?mx \\<in> \\<I>\\<close> inv_into_IA)\n          then have \"(B (Max x), B (Max y)) \\<in> ?R\"\n            using mx my 2 by (force simp: Ord_mem_iff_lt intro: converse_ordermap_mono)\n          with 2 show ?thesis\n            by (simp add: eq irrefl_less_than)\n        qed\n        then show \"(p,q) \\<in> ?R\"\n          by (simp add: peq qeq f_def split_def sorted_list_of_set_Un AB)\n      next\n        assume pqR: \"(p,q) \\<in> ?R\"\n        then have \\<section>: \"(A ?mx @ B (Max x), A ?my @ B (Max y)) \\<in> ?R\"\n          using peq qeq by blast\n        then consider \"(A ?mx, A ?my) \\<in> ?R\" | \"A ?mx = A ?my \\<and> (B (Max x), B (Max y)) \\<in> ?R\"\n        proof (cases \"(A ?mx, A ?my) \\<in> ?R\")\n          case False\n          have False if \"(A ?my, A ?mx) \\<in> ?R\"\n            by (metis \\<open>?my \\<in> \\<I>\\<close> \\<open>?mx \\<in> \\<I>\\<close> \"\\<section>\" \\<open>(Max y) \\<in> J ?my\\<close> \\<open>(Max x) \\<in> J ?mx\\<close> lenB lenlex_append1 omega_sum_1_less order.asym that)\n          then have \"A ?mx = A ?my\"\n            by (meson False UNIV_I total_llt total_on_def)\n          then show ?thesis\n            using \"\\<section>\" irrefl_less_than that(2) by auto\n        qed (use that in blast)\n        then have \"\\<beta> * ordermap (A`\\<I>) ?R (A ?mx) + ordermap (B`J ?mx) ?R (B (Max x))\n                 < \\<beta> * ordermap (A`\\<I>) ?R (A ?my) + ordermap (B`J ?my) ?R (B (Max y))\"\n        proof cases\n          case 1\n          show ?thesis\n          proof (rule add_mult_less_add_mult)\n            show \"ordermap (A`\\<I>) (lenlex less_than) (A ?mx) < ordermap (A`\\<I>) (lenlex less_than) (A ?my)\"\n              by (simp add: \"1\" \\<open>?my \\<in> \\<I>\\<close> \\<open>?mx \\<in> \\<I>\\<close> ordermap_mono_less)\n            show \"Ord (ordertype (A`\\<I>) ?R)\"\n              using wf_Ord_ordertype by blast\n            show \"ordermap (B ` J ?mx) ?R (B (Max x)) \\<in> elts \\<beta>\"\n              using Ord_less_TC_mem \\<open>Ord \\<beta>\\<close> \\<open>?mx \\<in> \\<I>\\<close> \\<open>(Max x) \\<in> J ?mx\\<close> oB by blast\n            show \"ordermap (B ` J ?my) ?R (B (Max y)) \\<in> elts \\<beta>\"\n              using Ord_less_TC_mem \\<open>Ord \\<beta>\\<close> \\<open>?my \\<in> \\<I>\\<close> \\<open>(Max y) \\<in> J ?my\\<close> oB by blast\n          qed (use \\<open>?my \\<in> \\<I>\\<close> \\<open>?mx \\<in> \\<I>\\<close> \\<open>Ord \\<beta>\\<close> in auto)\n        next\n          case 2\n          with \\<open>?mx \\<in> \\<I>\\<close> show ?thesis\n            using \\<open>(Max y) \\<in> J ?my\\<close> \\<open>(Max x) \\<in> J ?mx\\<close> ordermap_mono_less\n            by (metis (no_types, hide_lams) Kirby.add_less_cancel_left TC_small image_iff inv_into_IA trans_llt wf_llt y)\n        qed\n        then show \"f p < f q\"\n          using \\<open>?my \\<in> \\<I>\\<close> \\<open>?mx \\<in> \\<I>\\<close> \\<open>(Max y) \\<in> J ?my\\<close> \\<open>(Max x) \\<in> J ?mx\\<close>\n          by (auto simp: peq qeq f_def split_def AB)\n      qed\n    qed\n  qed auto\nqed auto\n\n\nsubsubsection \\<open>The final part of 3.8, where two sequences are merged\\<close>\n\ninductive merge :: \"[nat list list,nat list list,nat list list,nat list list] \\<Rightarrow> bool\"\n  where NullNull: \"merge [] [] [] []\"\n      | Null: \"as \\<noteq> [] \\<Longrightarrow> merge as [] [concat as] []\"\n      | App: \"\\<lbrakk>as1 \\<noteq> []; bs1 \\<noteq> [];\n               concat as1 < concat bs1; concat bs1 < concat as2; merge as2 bs2 as bs\\<rbrakk>\n              \\<Longrightarrow> merge (as1@as2) (bs1@bs2) (concat as1 # as) (concat bs1 # bs)\"\n\ninductive_simps Null1 [simp]: \"merge [] bs us vs\"\ninductive_simps Null2 [simp]: \"merge as [] us vs\"\n\nlemma merge_single:\n  \"\\<lbrakk>concat as < concat bs; concat as \\<noteq> []; concat bs \\<noteq> []\\<rbrakk> \\<Longrightarrow> merge as bs [concat as] [concat bs]\"\n  using merge.App [of as bs \"[]\" \"[]\"]\n  by (fastforce simp: less_list_def)\n\nlemma merge_length1_nonempty:\n  assumes \"merge as bs us vs\" \"as \\<in> lists (- {[]})\"\n  shows \"us \\<in> lists (- {[]})\"\n  using assms by induction (auto simp: mem_lists_non_Nil)\n\nlemma merge_length2_nonempty:\n  assumes \"merge as bs us vs\" \"bs \\<in> lists (- {[]})\"\n  shows \"vs \\<in> lists (- {[]})\"\n  using assms by induction (auto simp: mem_lists_non_Nil)\n\nlemma merge_length1_gt_0:\n  assumes \"merge as bs us vs\" \"as \\<noteq> []\"\n  shows \"length us > 0\"\n  using assms by induction auto\n\nlemma merge_length_le:\n  assumes \"merge as bs us vs\"\n  shows \"length vs \\<le> length us\"\n  using assms by induction auto\n\nlemma merge_length_le_Suc:\n  assumes \"merge as bs us vs\"\n  shows \"length us \\<le> Suc (length vs)\"\n  using assms by induction auto\n\nlemma merge_length_less2:\n  assumes \"merge as bs us vs\"\n  shows \"length vs \\<le> length as\"\n  using assms\nproof induction\ncase (App as1 bs1 as2 bs2 as bs)\n  then show ?case\n    using length_greater_0_conv [of as1] by (simp, presburger)\nqed auto\n\nlemma merge_preserves:\n  assumes \"merge as bs us vs\"\n  shows \"concat as = concat us \\<and> concat bs = concat vs\"\n  using assms by induction auto\n\nlemma merge_interact:\n  assumes \"merge as bs us vs\" \"strict_sorted (concat as)\" \"strict_sorted (concat bs)\"\n           \"bs \\<in> lists (- {[]})\"\n  shows \"strict_sorted (interact us vs)\"\n  using assms\nproof induction\n  case (App as1 bs1 as2 bs2 as bs)\n  then have bs: \"concat bs1 < concat bs\" \"concat bs1 < concat as\" and xx: \"concat bs1 \\<noteq> []\"\n    using merge_preserves strict_sorted_append_iff by fastforce+\n  then have \"concat bs1 < interact as bs\"\n    unfolding less_list_def using App bs\n    by (metis (no_types, lifting) Un_iff concat_append hd_in_set last_in_set merge_preserves set_interact sorted_wrt_append strict_sorted_append_iff)\n  with App show ?case\n    apply (simp add: strict_sorted_append_iff del: concat_eq_Nil_conv)\n    by (metis hd_append2 less_list_def xx)\nqed auto\n\n\nlemma acc_lengths_merge1:\n  assumes \"merge as bs us vs\"\n  shows \"list.set (acc_lengths k us) \\<subseteq> list.set (acc_lengths k as)\"\n  using assms\nproof (induction arbitrary: k)\n  case (App as1 bs1 as2 bs2 as bs)\n  then show ?case\n    apply (simp add: acc_lengths_append strict_sorted_append_iff length_concat_acc_lengths)\n    by (simp add: le_supI2 length_concat)\nqed (auto simp: length_concat_acc_lengths)\n\nlemma acc_lengths_merge2:\n  assumes \"merge as bs us vs\"\n  shows \"list.set (acc_lengths k vs) \\<subseteq> list.set (acc_lengths k bs)\"\n  using assms\nproof (induction arbitrary: k)\n  case (App as1 bs1 as2 bs2 as bs)\n  then show ?case\n    apply (simp add: acc_lengths_append strict_sorted_append_iff length_concat_acc_lengths)\n    by (simp add: le_supI2 length_concat)\nqed (auto simp: length_concat_acc_lengths)\n\nlemma length_hd_le_concat:\n  assumes \"as \\<noteq> []\" shows \"length (hd as) \\<le> length (concat as)\"\n  by (metis (no_types) add.commute assms concat.simps(2) le_add2 length_append list.exhaust_sel)\n\nlemma length_hd_merge2:\n  assumes \"merge as bs us vs\"\n  shows \"length (hd bs) \\<le> length (hd vs)\"\n  using assms by induction (auto simp: length_hd_le_concat)\n\nlemma merge_less_sets_hd:\n  assumes \"merge as bs us vs\" \"strict_sorted (concat as)\" \"strict_sorted (concat bs)\" \"bs \\<in> lists (- {[]})\"\n  shows \"list.set (hd us) \\<lless> list.set (concat vs)\"\n  using assms\nproof induction\n  case (App as1 bs1 as2 bs2 as bs)\n  then have \\<section>: \"list.set (concat bs1) \\<lless> list.set (concat bs2)\"\n    by (force simp: dest: strict_sorted_imp_less_sets)\n  have *: \"list.set (concat as1) \\<lless> list.set (concat bs1)\"\n    using App by (metis concat_append strict_sorted_append_iff strict_sorted_imp_less_sets)\n  then have \"list.set (concat as1) \\<lless> list.set (concat bs)\"\n    using App \\<section> less_sets_trans merge_preserves\n    by (metis List.set_empty append_in_lists_conv le_zero_eq length_0_conv length_concat_ge)\n  with * App.hyps show ?case\n    by (fastforce simp: less_sets_UN1 less_sets_UN2 less_sets_Un2)\nqed auto\n\nlemma set_takeWhile:\n  assumes \"strict_sorted (concat as)\" \"as \\<in> lists (- {[]})\"\n  shows \"list.set (takeWhile (\\<lambda>x. x < y) as) = {x \\<in> list.set as. x < y}\"\n  using assms\nproof (induction as)\n  case (Cons a as)\n  have \"a < y\"\n    if a: \"a < concat as\" \"strict_sorted a\" \"strict_sorted (concat as)\" \"x < y\" \"x \\<noteq> []\" \"x \\<in> list.set as\"\n    for x\n  proof -\n    have \"last x \\<in> list.set (concat as)\"\n      using set_concat that(5) that(6) by fastforce\n    then have \"last a < hd (concat as)\"\n      using Cons.prems that by (auto simp: less_list_def)\n    also have \"\\<dots> \\<le> hd y\" if \"y \\<noteq> []\"\n      using that a\n      by (meson \\<open>last x \\<in> list.set (concat as)\\<close> dual_order.strict_trans less_list_def not_le sorted_hd_le strict_sorted_imp_sorted)\n    finally show ?thesis\n      by (simp add: less_list_def)\n  qed\n  then show ?case\n    using Cons by (auto simp: strict_sorted_append_iff)\nqed auto\n\nproposition merge_exists:\n  assumes \"strict_sorted (concat as)\" \"strict_sorted (concat bs)\"\n          \"as \\<in> lists (- {[]})\" \"bs \\<in> lists (- {[]})\"\n          \"hd as < hd bs\" \"as \\<noteq> []\" \"bs \\<noteq> []\"\n  and disj: \"\\<And>a b. \\<lbrakk>a \\<in> list.set as; b \\<in> list.set bs\\<rbrakk> \\<Longrightarrow> a<b \\<or> b<a\"\nshows \"\\<exists>us vs. merge as bs us vs\"\n  using assms\nproof (induction \"length as + length bs\" arbitrary: as bs rule: less_induct)\n  case (less as bs)\n  obtain as1 as2 bs1 bs2\n    where A: \"as1 \\<noteq> []\" \"bs1 \\<noteq> []\" \"concat as1 < concat bs1\" \"concat bs1 < concat as2\"\n      and B: \"as = as1@as2\" \"bs = bs1@bs2\" and C: \"bs2 = [] \\<or> (as2 \\<noteq> [] \\<and> hd as2 < hd bs2)\"\n  proof\n    define as1 where \"as1 \\<equiv> takeWhile (\\<lambda>x. x < hd bs) as\"\n    define as2 where \"as2 \\<equiv> dropWhile (\\<lambda>x. x < hd bs) as\"\n    define bs1 where \"bs1 \\<equiv> if as2=[] then bs else takeWhile (\\<lambda>x. x < hd as2) bs\"\n    define bs2 where \"bs2 \\<equiv> if as2=[] then [] else dropWhile (\\<lambda>x. x < hd as2) bs\"\n\n    have as1: \"as1 = takeWhile (\\<lambda>x. last x < hd (hd bs)) as\"\n      using less.prems by (auto simp: as1_def less_list_def cong: takeWhile_cong)\n    have as2: \"as2 = dropWhile (\\<lambda>x. last x < hd (hd bs)) as\"\n      using less.prems by (auto simp: as2_def less_list_def cong: dropWhile_cong)\n\n    have hd_as2: \"as2 \\<noteq> [] \\<Longrightarrow> \\<not> hd as2 < hd bs\"\n      using as2_def hd_dropWhile by metis\n    have hd_bs2: \"bs2 \\<noteq> [] \\<Longrightarrow> \\<not> hd bs2 < hd as2\"\n      using bs2_def hd_dropWhile by metis\n    show \"as1 \\<noteq> []\"\n      by (simp add: as1_def less.prems takeWhile_eq_Nil_iff)\n    show \"bs1 \\<noteq> []\"\n      by (metis as2 bs1_def hd_as2 hd_in_set less.prems(7) less.prems(8) set_dropWhileD takeWhile_eq_Nil_iff)\n    show \"bs2 = [] \\<or> (as2 \\<noteq> [] \\<and> hd as2 < hd bs2)\"\n      by (metis as2_def bs2_def hd_bs2 less.prems(8) list.set_sel(1) set_dropWhileD)\n    have AB: \"list.set A \\<lless> list.set B\"\n      if \"A \\<in> list.set as1\" \"B \\<in> list.set bs\" for A B\n    proof -\n      have \"A \\<in> list.set as\"\n        using that by (metis as1 set_takeWhileD)\n      then have \"sorted A\"\n        by (metis concat.simps(2) concat_append less.prems(1) sorted_append split_list_last strict_sorted_imp_sorted)\n      moreover have \"sorted (hd bs)\"\n        by (metis concat.simps(2) hd_Cons_tl less.prems(2) less.prems(7) strict_sorted_append_iff strict_sorted_imp_sorted)\n      ultimately show ?thesis\n        using that less.prems\n       apply (clarsimp simp add: as1_def set_takeWhile less_list_iff_less_sets less_sets_def)\n        by (metis (full_types) UN_I hd_concat less_le_trans list.set_sel(1) set_concat sorted_hd_le strict_sorted_imp_sorted)\n    qed\n    show \"as = as1@as2\"\n      by (simp add: as1_def as2_def)\n    show \"bs = bs1@bs2\"\n      by (simp add: bs1_def bs2_def)\n    have \"list.set (concat as1) \\<lless> list.set (concat bs1)\"\n      using AB set_takeWhileD by (fastforce simp: as1_def bs1_def less_sets_UN1 less_sets_UN2)\n    then show \"concat as1 < concat bs1\"\n      by (rule less_sets_imp_list_less)\n    have \"list.set (concat bs1) \\<lless> list.set (concat as2)\" if \"as2 \\<noteq> []\"\n    proof (clarsimp simp add: bs1_def less_sets_UN1 less_sets_UN2 set_takeWhile less.prems)\n      fix A B\n      assume \"A \\<in> list.set as2\" \"B \\<in> list.set bs\" \"B < hd as2\"\n      with that show \"list.set B \\<lless> list.set A\"\n        using hd_as2 less.prems(1,2)\n        apply (clarsimp simp add: less_sets_def less_list_def)\n        apply (auto simp: as2_def)\n        apply (simp flip: as2_def)\n        by (smt (verit, ccfv_SIG) UN_I \\<open>as = as1 @ as2\\<close> concat.simps(2) concat_append hd_concat in_set_conv_decomp_first le_less_trans less_le_trans set_concat sorted_append sorted_hd_le sorted_le_last strict_sorted_imp_sorted that)\n    qed\n    then show \"concat bs1 < concat as2\"\n      by (simp add: bs1_def less_sets_imp_list_less)\n  qed\n  obtain cs ds where \"merge as2 bs2 cs ds\"\n  proof (cases \"as2 = [] \\<or> bs2 = []\")\n    case True\n    then show thesis\n      using that C NullNull Null by metis\n  next\n    have \\<dagger>: \"length as2 + length bs2 < length as + length bs\"\n      by (simp add: A B)\n    case False\n    moreover have \"strict_sorted (concat as2)\" \"strict_sorted (concat bs2)\"\n      \"as2 \\<in> lists (- {[]})\" \"bs2 \\<in> lists (- {[]})\"\n      \"\\<And>a b. \\<lbrakk>a \\<in> list.set as2; b \\<in> list.set bs2\\<rbrakk> \\<Longrightarrow> a < b \\<or> b < a\"\n      using B less.prems strict_sorted_append_iff by auto\n    ultimately show ?thesis\n      using C less.hyps [OF \\<dagger>] False that by force\n  qed\n  then obtain cs where \"merge (as1 @ as2) (bs1 @ bs2) (concat as1 # cs) (concat bs1 # ds)\"\n    using A merge.App by blast\n  then show ?case\n    using B by blast\nqed\n\nsubsubsection \\<open>Actual proof of Larson's Lemma 3.8\\<close>\n\nproposition lemma_3_8:\n  assumes \"infinite N\"\n  obtains X where \"X \\<subseteq> WW\" \"ordertype X (lenlex less_than) = \\<omega>\\<up>\\<omega>\"\n            \"\\<And>u. u \\<in> [X]\\<^bsup>2\\<^esup> \\<Longrightarrow>\n                   \\<exists>l. Form l u \\<and> (l > 0 \\<longrightarrow> [enum N l] < inter_scheme l u \\<and> List.set (inter_scheme l u) \\<subseteq> N)\"\nproof -\n  let ?LL = \"lenlex less_than\"\n  define bf where \"bf \\<equiv> \\<lambda>M q. wfrec pair_less (\\<lambda>f (j,i).\n                                  let R = (case prev j i of None \\<Rightarrow> M | Some u \\<Rightarrow> snd (f u))\n                                  in grab R (q j i))\"\n\n  have bf_rec: \"bf M q (j,i) =\n                 (let R = (case prev j i of None \\<Rightarrow> M | Some u \\<Rightarrow> snd (bf M q u))\n                  in  grab R (q j i))\" for M q j i\n    by (subst (1) bf_def) (simp add: Let_def wfrec bf_def cut_apply prev_pair_less cong: conj_cong split: option.split)\n\n  have \"infinite (snd (bf M q u)) = infinite M \\<and> fst (bf M q u) \\<subseteq> M \\<and> snd (bf M q u) \\<subseteq> M\" for M q u\n    using wf_pair_less\n  proof (induction u rule: wf_induct_rule)\n    case (less u)\n    then show ?case\n    proof (cases u)\n      case (Pair j i)\n      with less.IH prev_pair_less show ?thesis\n        apply (simp add: bf_rec [of M q j i] split: option.split)\n        using fst_grab_subset snd_grab_subset by blast\n    qed\n  qed\n  then have infinite_bf [simp]: \"infinite (snd (bf M q u)) = infinite M\"\n       and  bf_subset: \"fst (bf M q u) \\<subseteq> M \\<and> snd (bf M q u) \\<subseteq> M\" for M q u\n    by auto\n\n  have bf_less_sets: \"fst (bf M q ij) \\<lless> snd (bf M q ij)\" if \"infinite M\" for M q ij\n    using wf_pair_less\n  proof (induction ij rule: wf_induct_rule)\n    case (less u)\n    then show ?case\n    proof (cases u)\n      case (Pair j i)\n      with less_sets_grab show ?thesis\n        by (simp add: bf_rec [of M q j i] less.IH prev_pair_less that split: option.split)\n    qed\n  qed\n\n  have card_fst_bf: \"finite (fst (bf M q (j,i))) \\<and> card (fst (bf M q (j,i))) = q j i\" if \"infinite M\" for M q j i\n    by (simp add: that bf_rec [of M q j i] split: option.split)\n\n  have bf_cong: \"bf M q u = bf M q' u\"\n    if \"snd u \\<le> fst u\" and eq: \"\\<And>y x. \\<lbrakk>x\\<le>y; y\\<le>fst u\\<rbrakk> \\<Longrightarrow> q' y x = q y x\" for M q q' u\n    using wf_pair_less that\n  proof (induction u rule: wf_induct_rule)\n    case (less u)\n    show ?case\n    proof (cases u)\n      case (Pair j i)\n      with less.prems show ?thesis\n      proof (clarsimp simp add: bf_rec [of M _ j i] split: option.split)\n        fix j' i'\n        assume *: \"prev j i = Some (j',i')\"\n        then have **: \"((j', i'), u) \\<in> pair_less\"\n          by (simp add: Pair prev_pair_less)\n        moreover have \"i' < j'\"\n          using Pair less.prems by (simp add: prev_Some_less [OF *])\n        moreover have \"\\<And>x y. \\<lbrakk>x \\<le> y; y \\<le> j'\\<rbrakk> \\<Longrightarrow> q' y x = q y x\"\n          using ** less.prems by (auto simp: pair_less_def Pair)\n        ultimately show \"grab (snd (bf M q (j',i'))) (q j i) = grab (snd (bf M q' (j',i'))) (q j i)\"\n          using less.IH by auto\n      qed\n    qed\n  qed\n\n  define ediff where \"ediff \\<equiv> \\<lambda>D:: nat \\<Rightarrow> nat set. \\<lambda>j i. enum (D j) (Suc i) - enum (D j) i\"\n  define F where \"F \\<equiv> \\<lambda>l (dl,a0::nat set,b0::nat \\<times> nat \\<Rightarrow> nat set,M).\n          let (d,Md) = grab (nxt M (enum N (Suc (2 * Suc l)))) (Suc l) in\n          let (a,Ma) = grab Md (Min d) in\n          let Gb = bf Ma (ediff (dl(l := d))) in\n          let dl' = dl(l := d) in\n          (dl', a, fst \\<circ> Gb, snd (Gb(l, l-1)))\"\n  define DF where \"DF \\<equiv> rec_nat (\\<lambda>i\\<in>{..<0}. {}, {}, \\<lambda>p. {}, N) F\"\n  have DF_simps: \"DF 0 = (\\<lambda>i\\<in>{..<0}. {}, {}, \\<lambda>p. {}, N)\"\n                 \"DF (Suc l) = F l (DF l)\" for l\n    by (auto simp: DF_def)\n  note cut_apply [simp]\n\n  have inf [rule_format]: \"\\<forall>dl al bl L. DF l = (dl,al,bl,L) \\<longrightarrow> infinite L\" for l\n    by (induction l) (auto simp: DF_simps F_def Let_def grab_eqD infinite_nxtN assms split: prod.split)\n\n  define \\<Psi> where\n    \"\\<Psi> \\<equiv> \\<lambda>(dl, a, b, M). \\<lambda>l::nat.\n           dl l \\<lless> a \\<and> card a > 0 \\<and>\n           (\\<forall>j\\<le>l. card (dl j) = Suc j) \\<and> a \\<lless> \\<Union>(range b) \\<and> range b \\<subseteq> Collect finite \\<and>\n           a \\<subseteq> N \\<and> \\<Union>(range b) \\<subseteq> N \\<and> infinite M \\<and> b(l,l-1) \\<lless> M \\<and> M \\<subseteq> N\"\n  have \\<Psi>_DF: \"\\<Psi> (DF (Suc l)) l\" for l\n  proof (induction l)\n    case 0\n    show ?case\n      using assms\n      apply (clarsimp simp add: bf_rec F_def DF_simps \\<Psi>_def split: prod.split)\n      apply (drule grab_eqD, blast dest: grab_eqD infinite_nxtN)+\n      apply (auto simp: less_sets_UN2 less_sets_grab card_fst_bf elim!: less_sets_weaken2)\n      apply (metis card_1_singleton_iff Min_singleton greaterThan_iff insertI1 le0 nxt_subset_greaterThan subsetD)\n      using nxt_subset snd_grab_subset bf_subset by blast+\n  next\n    case (Suc l)\n    then show ?case\n      using assms\n      unfolding Let_def DF_simps(2)[of \"Suc l\"] F_def \\<Psi>_def\n      apply (clarsimp simp add: bf_rec DF_simps split: prod.split)\n      apply (drule grab_eqD, metis grab_eqD infinite_nxtN)+\n      apply (safe, simp_all add: less_sets_UN2 less_sets_grab card_fst_bf card_Suc_eq_finite)\n             apply (meson less_sets_weaken2)\n            apply (metis Min_in gr0I greaterThan_iff insert_not_empty le_inf_iff less_asym nxt_def subsetD)\n           apply (meson bf_subset less_sets_weaken2)\n          apply (meson nxt_subset subset_eq)\n         apply (meson bf_subset nxt_subset subset_eq)\n        using bf_rec infinite_bf apply force\n       using bf_less_sets bf_rec apply force\n      by (metis bf_rec bf_subset nxt_subset subsetD)\n  qed\n\n  define d where \"d \\<equiv> \\<lambda>k. let (dk,ak,bk,M) = DF(Suc k) in dk k\"\n  define a where \"a \\<equiv> \\<lambda>k. let (dk,ak,bk,M) = DF(Suc k) in ak\"\n  define b where \"b \\<equiv> \\<lambda>k. let (dk,ak,bk,M) = DF(Suc k) in bk\"\n  define M where \"M \\<equiv> \\<lambda>k. let (dk,ak,bk,M) = DF k in M\"\n\n  have infinite_M [simp]: \"infinite (M k)\" for k\n    by (auto simp: M_def inf split: prod.split)\n\n  have M_Suc_subset: \"M (Suc k) \\<subseteq> M k\" for k\n    apply (clarsimp simp add: Let_def M_def F_def DF_simps split: prod.split)\n    apply (drule grab_eqD, blast dest: infinite_nxtN local.inf)+\n    using bf_subset nxt_subset by blast\n\n  have Inf_M_Suc_ge: \"Inf (M k) \\<le> Inf (M (Suc k))\" for k\n    by (simp add: M_Suc_subset cInf_superset_mono infinite_imp_nonempty)\n\n  have Inf_M_telescoping: \"{Inf (M k)..} \\<subseteq> {Inf (M k')..}\" if k': \"k'\\<le>k\" for k k'\n    using that Inf_nat_def1 infinite_M unfolding Inf_nat_def atLeast_subset_iff\n    by (metis M_Suc_subset finite.emptyI le_less_linear lift_Suc_antimono_le not_less_Least subsetD)\n\n  have d_eq: \"d k = fst (grab (nxt (M k) (enum N (Suc (2 * Suc k)))) (Suc k))\" for k\n    by (simp add: d_def M_def Let_def DF_simps F_def split: prod.split)\n  then have finite_d [simp]: \"finite (d k)\" for k\n    by simp\n  then have d_ne [simp]: \"d k \\<noteq> {}\" for k\n    by (metis card.empty card_grab d_eq infinite_M infinite_nxtN nat.distinct(1))\n  have a_eq: \"\\<exists>M. a k = fst (grab M (Min (d k))) \\<and> infinite M\" for k\n    apply (simp add: a_def d_def M_def Let_def DF_simps F_def split: prod.split)\n    by (metis fst_conv grab_eqD infinite_nxtN local.inf)\n  then have card_a: \"card (a k) = Inf (d k)\" for k\n    by (metis cInf_eq_Min card_grab d_ne finite_d)\n\n  have d_eq_dl: \"d k = dl k\" if \"(dl,a,b,P) = DF l\" \"k < l\" for k l dl a b P\n    using that\n    by (induction l arbitrary: dl a b P) (simp_all add: d_def DF_simps F_def Let_def split: prod.split_asm prod.split)\n\n  have card_d [simp]: \"card (d k) = Suc k\" for k\n    by (auto simp: d_eq infinite_nxtN)\n\n  have d_ne [simp]: \"d j \\<noteq> {}\" and a_ne [simp]: \"a j \\<noteq> {}\"\n    and finite_d [simp]: \"finite (d j)\" and finite_a [simp]: \"finite (a j)\" for j\n    using \\<Psi>_DF [of \"j\"]  by (auto simp: \\<Psi>_def a_def d_def card_gt_0_iff split: prod.split_asm)\n\n  have da: \"d k \\<lless> a k\" for k\n    using \\<Psi>_DF [of \"k\"] by (simp add: \\<Psi>_def a_def d_def split: prod.split_asm)\n\n  have ab_same: \"a k \\<lless> \\<Union>(range(b k))\" for k\n    using \\<Psi>_DF [of \"k\"] by (simp add: \\<Psi>_def a_def b_def M_def split: prod.split_asm)\n\n  have snd_bf_subset: \"snd (bf M r (j,i)) \\<subseteq> snd (bf M r (j',i'))\"\n    if ji: \"((j',i'), (j,i)) \\<in> pair_less\" \"(j',i') \\<in> IJ k\"\n    for M r k j i j' i'\n    using wf_pair_less ji\n  proof (induction rule: wf_induct_rule [where a= \"(j,i)\"])\n    case (less u)\n    show ?case\n    proof (cases u)\n      case (Pair j i)\n      then consider \"prev j i = Some (j', i')\" | x where \"((j', i'), x) \\<in> pair_less\" \"prev j i = Some x\"\n        using less.prems pair_less_prev by blast\n      then show ?thesis\n      proof cases\n        case 2 with less.IH show ?thesis\n          unfolding bf_rec Pair\n          by (metis in_mono option.simps(5) prev_pair_less snd_grab_subset subsetI that(2)) \n      qed (simp add: Pair bf_rec snd_grab_subset)\n    qed\n  qed\n\n  have less_bf: \"fst (bf M r (j',i')) \\<lless> fst (bf M r (j,i))\"\n    if ji: \"((j',i'), (j,i)) \\<in> pair_less\" \"(j',i') \\<in> IJ k\" and \"infinite M\"\n    for M r k j i j' i'\n  proof -\n    consider \"prev j i = Some (j', i')\" | j'' i'' where \"((j', i'), (j'',i'')) \\<in> pair_less\" \"prev j i = Some (j'',i'')\"\n      by (metis pair_less_prev ji prod.exhaust_sel)\n    then show ?thesis\n    proof cases\n      case 1\n      then show ?thesis\n        using bf_less_sets bf_rec less_sets_fst_grab \\<open>infinite M\\<close> by force\n    next\n      case 2\n      then have \"fst (bf M r (j',i')) \\<lless> snd (bf M r (j'',i''))\"\n        by (meson bf_less_sets snd_bf_subset less_sets_weaken2 that)\n      with 2 show ?thesis\n        using bf_rec bf_subset less_sets_fst_grab \\<open>infinite M\\<close> by auto\n    qed\n  qed\n\n  have aM: \"a k \\<lless> M (Suc k)\" for k\n    apply (clarsimp simp add: a_def M_def DF_simps F_def Let_def split: prod.split)\n    by (meson bf_subset grab_eqD infinite_nxtN less_sets_weaken2 local.inf)\n  then have \"a k \\<lless> a (Suc k)\" for k\n    by (metis IntE card_d card.empty d_eq da fst_grab_subset less_sets_trans less_sets_weaken2 nat.distinct(1) nxt_def subsetI)\n  then have aa: \"a j \\<lless> a k\" if \"j<k\" for k j\n    by (meson UNIV_I a_ne less_sets_imp_strict_mono_sets strict_mono_sets_def that)\n  then have ab: \"a k' \\<lless> b k (j,i)\" if \"k'\\<le>k\" for k k' j i\n    by (metis a_ne ab_same le_less less_sets_UN2 less_sets_trans rangeI that)\n  have db: \"d j \\<lless> b k (j,i)\" if \"j\\<le>k\" for k j i\n    by (meson a_ne ab da less_sets_trans that)\n\n  have bMkk: \"b k (k,k-1) \\<lless> M (Suc k)\" for k\n    using \\<Psi>_DF [of k]\n    by (simp add: \\<Psi>_def b_def d_def M_def split: prod.split_asm)\n\n  have b: \"\\<exists>P \\<subseteq> M k. infinite P \\<and> (\\<forall>j i. i\\<le>j \\<longrightarrow> j\\<le>k \\<longrightarrow> b k (j,i) = fst (bf P (ediff d) (j,i)))\" for k\n  proof (clarsimp simp: b_def DF_simps F_def Let_def split: prod.split)\n    fix a a' d' dl bb P M' M''\n    assume gr: \"grab M'' (Min d') = (a', M')\" \"grab (nxt P (enum N (Suc (Suc (Suc (2 * k)))))) (Suc k) = (d', M'')\"\n      and DF: \"DF k = (dl, a, bb, P)\"\n    have deq: \"d j = (if j = k then d' else dl j)\" if \"j\\<le>k\" for j\n    proof (cases \"j < k\")\n      case True\n      then show ?thesis by (metis DF d_eq_dl less_not_refl)\n    next\n      case False\n      then show ?thesis\n        using that DF gr by (auto simp: d_def DF_simps F_def Let_def split: prod.split)\n    qed\n    have \"M' \\<subseteq> P\"\n      by (metis gr in_mono nxt_subset snd_conv snd_grab_subset subsetI)\n    also have \"P \\<subseteq> M k\"\n      using DF by (simp add: M_def)\n    finally have \"M' \\<subseteq> M k\" .\n    moreover have \"infinite M'\"\n      using DF by (metis (mono_tags) finite_grab_iff gr infinite_nxtN local.inf snd_conv)\n    moreover\n    have \"ediff (dl(k := d')) j i = ediff d j i\" if \"j\\<le>k\" for j i\n      by (simp add: deq that ediff_def)\n    then have \"bf M' (ediff (dl(k := d'))) (j,i)\n             = bf M' (ediff d) (j,i)\" if \"i \\<le> j\" \"j\\<le>k\" for j i\n      using bf_cong that by fastforce\n    ultimately show \"\\<exists>P\\<subseteq>M k. infinite P \\<and>\n                           (\\<forall>j i. i \\<le> j \\<longrightarrow> j \\<le> k\n                                        \\<longrightarrow> fst (bf M' (ediff (dl(k := d'))) (j,i))\n                         = fst (bf P (ediff d) (j,i)))\"\n      by auto\n  qed\n\n  have card_b: \"card (b k (j,i)) = enum (d j) (Suc i) - enum (d j) i\" if \"j\\<le>k\" for k j i\n    \\<comment>\\<open>there's a short proof of this from the previous result but it would need @{term\"i\\<le>j\"}\\<close>\n  proof (clarsimp simp: b_def DF_simps F_def Let_def split: prod.split)\n    fix dl\n      and a a' d':: \"nat set\"\n      and bb M M' M''\n    assume gr: \"grab M'' (Min d') = (a', M')\" \"grab (nxt M (enum N (Suc (Suc (Suc (2 * k)))))) (Suc k) = (d',M'')\"\n      and DF: \"DF k = (dl, a, bb, M)\"\n    have \"d j = (if j = k then d' else dl j)\"\n    proof (cases \"j < k\")\n      case True\n      then show ?thesis by (metis DF d_eq_dl less_not_refl)\n    next\n      case False\n      then show ?thesis\n        using that DF gr by (auto simp: d_def DF_simps F_def Let_def split: prod.split)\n    qed\n    then show \"card (fst (bf M' (ediff (dl(k := d'))) (j,i)))\n             = enum (d j) (Suc i) - enum (d j) i\"\n      using DF gr card_fst_bf grab_eqD infinite_nxtN local.inf ediff_def by auto\n  qed\n\n  have card_b_pos: \"card (b k (j,i)) > 0\" if \"i < j\" \"j\\<le>k\" for k j i\n    by (simp add: card_b that finite_enumerate_step)\n  have b_ne [simp]: \"b k (j,i) \\<noteq> {}\" if \"i < j\" \"j\\<le>k\" for k j i\n    using card_b_pos [OF that] less_imp_neq by fastforce+\n\n  have card_b_finite [simp]: \"finite (b k u)\" for k u\n    using \\<Psi>_DF [of k] by (fastforce simp: \\<Psi>_def b_def)\n\n  have bM: \"b k (j,i) \\<lless> M (Suc k)\" if \"i<j\" \"j\\<le>k\" for i j k\n  proof -\n    obtain M' where \"M' \\<subseteq> M k\" \"infinite M'\"\n      and bk: \"\\<And>j i. i\\<le>j \\<Longrightarrow> j\\<le>k \\<Longrightarrow> b k (j,i) = fst (bf M' (ediff d) (j,i))\"\n      using b by (metis (no_types, lifting))\n    show ?thesis\n    proof (cases \"j=k \\<and> i = k-1\")\n      case False\n      show ?thesis\n      proof (rule less_sets_trans [OF _ bMkk])\n        show \"b k (j,i) \\<lless> b k (k, k-1)\"\n          using that \\<open>infinite M'\\<close> False\n            by (force simp: bk pair_less_def IJ_def intro: less_bf)\n        show \"b k (k, k-1) \\<noteq> {}\"\n          using b_ne that by auto\n      qed\n    qed (use bMkk in auto)\n  qed\n\n  have b_InfM: \"\\<Union> (range (b k)) \\<subseteq> {\\<Sqinter>(M k)..}\" for k\n  proof (clarsimp simp add: \\<Psi>_def b_def M_def DF_simps F_def Let_def split: prod.split)\n    fix r dl :: \"nat \\<Rightarrow> nat set\"\n      and a b and d' a' M'' M' P and x j' i' :: nat\n    assume gr: \"grab M'' (Min d') = (a', M')\"\n               \"grab (nxt P (enum N (Suc (Suc (Suc (2 * k)))))) (Suc k) = (d', M'')\"\n      and DF: \"DF k = (dl, a, b, P)\"\n      and x: \"x \\<in> fst (bf M' (ediff (dl(k := d'))) (j', i'))\"\n    have \"infinite P\"\n      using DF local.inf by blast\n    then have \"M' \\<subseteq> P\"\n      by (meson gr grab_eqD infinite_nxtN nxt_subset order.trans)\n    with bf_subset show \"\\<Sqinter> P \\<le> x\"\n      using Inf_nat_def x le_less_linear not_less_Least by fastforce\n  qed\n\n  have b_Inf_M_Suc: \"b k (j,i) \\<lless> {Inf(M (Suc k))}\" if \"i<j\" \"j\\<le>k\" for k j i\n    using bMkk [of k] that\n    by (metis Inf_nat_def1 bM finite.emptyI infinite_M less_setsD less_sets_singleton2)\n\n  have bb_same: \"b k (j',i') \\<lless> b k (j,i)\"\n    if \"((j',i'), (j,i)) \\<in> pair_less\" \"(j',i') \\<in> IJ k\" for k j i j' i'\n    using that\n    unfolding b_def DF_simps F_def Let_def\n    by (auto simp: less_bf grab_eqD infinite_nxtN local.inf split: prod.split)\n\n  have bb: \"b k' (j',i') \\<lless> b k (j,i)\"\n    if j: \"i' < j'\" \"j'\\<le>k'\" and k: \"k'<k\" for i i' j j' k' k\n  proof (rule atLeast_less_sets)\n    show \"b k' (j', i') \\<lless> {Inf(M (Suc k'))}\"\n      using Suc_lessD b_Inf_M_Suc nat_less_le j by blast\n    show \"b k (j,i) \\<subseteq> {Inf(M (Suc k'))..}\"\n      by (meson Inf_M_telescoping Suc_leI UnionI b_InfM rangeI subset_eq k)\n  qed\n\n  have M_subset_N: \"M k \\<subseteq> N\" for k\n  proof (cases k)\n    case (Suc k')\n    with \\<Psi>_DF [of k'] show ?thesis\n      by (auto simp: M_def Let_def \\<Psi>_def split: prod.split)\n  qed (auto simp: M_def DF_simps)\n  have a_subset_N: \"a k \\<subseteq> N\" for k\n    using \\<Psi>_DF [of k] by (simp add: a_def \\<Psi>_def split: prod.split prod.split_asm)\n  have d_subset_N: \"d k \\<subseteq> N\" for k\n    using M_subset_N [of k] d_eq fst_grab_subset nxt_subset by blast\n  have b_subset_N: \"b k (j,i) \\<subseteq> N\" for k j i\n    using \\<Psi>_DF [of k] by (force simp: b_def \\<Psi>_def)\n\n  define \\<K>:: \"[nat,nat] \\<Rightarrow> nat set set\"\n    where \"\\<K> \\<equiv> \\<lambda>j0 j. nsets {j0<..} j\"\n  have \\<K>_finite: \"finite K\" and \\<K>_card: \"card K = j\" if \"K \\<in> \\<K> j0 j\" for K j0 j\n    using that by (auto simp add: \\<K>_def nsets_def)\n  have \\<K>_enum: \"j0 < enum K i\" if \"K \\<in> \\<K> j0 j\" \"i < card K\" for K j0 j i\n    using that by (auto simp: \\<K>_def nsets_def finite_enumerate_in_set subset_eq)\n  have \\<K>_0 [simp]: \"\\<K> k 0 = {{}}\" for k\n    by (auto simp: \\<K>_def)\n\n  have \\<K>_Suc: \"\\<K> j0 (Suc j) = USigma (\\<K> j0 j) (\\<lambda>K. {Max (insert j0 K)<..})\" (is \"?lhs = ?rhs\")\n    for j j0\n  proof\n    show \"\\<K> j0 (Suc j) \\<subseteq> USigma (\\<K> j0 j) (\\<lambda>K. {Max (insert j0 K)<..})\"\n      unfolding \\<K>_def nsets_def USigma_def\n    proof clarsimp\n      fix K\n      assume K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K = Suc j\"\n      then have \"Max K \\<in> K\"\n        by (metis Max_in card_0_eq nat.distinct(1))\n      then obtain i where \"Max (insert j0 (K - {Max K})) < i\" \"K = insert i (K - {Max K})\"\n        using K \n        by (simp add: subset_iff) (metis DiffE Max.coboundedI insertCI insert_Diff le_neq_implies_less)\n      then  show \"\\<exists>L\\<subseteq>{j0<..}. finite L \\<and> card L = j \\<and> (\\<exists>i\\<in>{Max (insert j0 L)<..}. K = insert i L)\"\n        using K\n        by (metis \\<open>Max K \\<in> K\\<close> card_Diff_singleton_if diff_Suc_1 finite_Diff greaterThan_iff insert_subset)\n    qed\n    show \"?rhs \\<subseteq> \\<K> j0 (Suc j)\"\n      by (force simp:  \\<K>_def nsets_def USigma_def)\n  qed\n\n  define BB where \"BB \\<equiv> \\<lambda>j0 j K. list_of (a j0 \\<union> (\\<Union>i<j. b (enum K i) (j0,i)))\"\n  define XX where \"XX \\<equiv> \\<lambda>j. BB j j ` \\<K> j j\"\n\n  have less_list_of:  \"BB j i K < list_of (b l (j,i))\"\n    if K: \"K \\<in> \\<K> j i\" \"\\<forall>j\\<in>K. j < l\" and \"i \\<le> j\" \"j \\<le> l\" for j i K l\n    unfolding BB_def\n  proof (rule less_sets_imp_sorted_list_of_set)\n    have \"\\<And>i. i < card K \\<Longrightarrow> b (enum K i) (j,i) \\<lless> b l (j, card K)\"\n      using that by (metis \\<K>_card \\<K>_enum \\<K>_finite bb finite_enumerate_in_set nat_less_le less_le_trans)\n    then show \"a j \\<union> (\\<Union>i<i. b (enum K i) (j,i)) \\<lless> b l (j,i)\"\n      using that unfolding \\<K>_def nsets_def\n      by (auto simp: less_sets_Un1 less_sets_UN1 ab finite_enumerate_in_set subset_eq)\n  qed auto\n  have BB_Suc: \"BB j0 (Suc j) K = usplit (\\<lambda>L k. BB j0 j L @ list_of (b k (j0, j))) K\"\n    if j: \"j \\<le> j0\" and K: \"K \\<in> \\<K> j0 (Suc j)\" for j0 j K\n    \\<comment>\\<open>towards the ordertype proof\\<close>\n  proof -\n    have Kj: \"K \\<subseteq> {j0<..}\" and [simp]: \"finite K\" and cardK: \"card K = Suc j\"\n      using K by (auto simp: \\<K>_def nsets_def)\n    have KMK: \"K - {Max K} \\<in> \\<K> j0 j\"\n      using that by (simp add: \\<K>_Suc USigma_iff \\<K>_finite less_sets_def usplit_def)\n    have \"j0 < Max K\"\n      by (metis Kj Max_in cardK card_gt_0_iff greaterThan_iff subsetD zero_less_Suc)\n    have MaxK: \"Max K = enum K j\"\n    proof (rule Max_eqI)\n      fix k\n      assume \"k \\<in> K\" \n      with K cardK show \"k \\<le> enum K j\" \n        by (metis \\<open>finite K\\<close> finite_enumerate_Ex finite_enumerate_mono_iff leI lessI not_less_eq)\n    qed (auto simp: cardK finite_enumerate_in_set)\n    have ene: \"i<j \\<Longrightarrow> enum (K - {enum K j}) i = enum K i\" for i\n      using finite_enumerate_Diff_singleton [OF \\<open>finite K\\<close>] by (simp add: cardK)\n    have \"BB j0 (Suc j) K = list_of ((a j0 \\<union> (\\<Union>x<j. b (enum K x) (j0, x))) \\<union> b (enum K j) (j0, j))\"\n      by (simp add: BB_def lessThan_Suc Un_ac)\n    also have \"\\<dots> = list_of ((a j0 \\<union> (\\<Union>i<j. b (enum K i) (j0, i)))) @ list_of (b (enum K j) (j0, j))\"\n    proof (rule sorted_list_of_set_Un)\n      have \"b (enum K i) (j0, i) \\<lless> b (enum K j) (j0, j)\" if \"i<j\" for i\n      proof (rule bb)\n        show \"i < j0\"\n          using j that by linarith\n        show \"j0 \\<le> enum K i\"\n          using that K by (metis \\<K>_enum cardK less_SucI less_imp_le_nat)\n        show \"enum K i < enum K j\"\n          by (simp add: cardK finite_enumerate_mono that)\n      qed\n      moreover have \"a j0 \\<lless> b (enum K j) (j0, j)\"\n        using MaxK \\<open>j0 < Max K\\<close> ab by auto\n      ultimately show \"a j0 \\<union> (\\<Union>x<j. b (enum K x) (j0, x)) \\<lless> b (enum K j) (j0, j)\"\n        by (simp add: less_sets_Un1 less_sets_UN1)\n    qed (auto simp: finite_UnI)\n    also have \"\\<dots> = BB j0 j (K - {Max K}) @ list_of (b (Max K) (j0, j))\"\n      by (simp add: BB_def MaxK ene)\n    also have \"\\<dots> = usplit (\\<lambda>L k. BB j0 j L @ list_of (b k (j0, j))) K\"\n      by (simp add: usplit_def)\n    finally show ?thesis .\n  qed\n\n  have enum_d_0: \"enum (d j) 0 = Inf (d j)\" for j\n    using enum_0_eq_Inf_finite by auto\n\n  have Inf_b_less: \"\\<Sqinter>(b k' (j',i')) < \\<Sqinter>(b k (j,i))\"\n    if j: \"i' < j'\" \"i < j\" \"j'\\<le>k'\" \"j\\<le>k\" and k: \"k'<k\" for i i' j j' k' k\n    using bb [of i' j' k' k j i] that b_ne [of i' j' k'] b_ne [of i j k]\n    by (simp add: less_sets_def Inf_nat_def1)\n\n  have b_ge_k: \"\\<Sqinter> (b k (k, k-1)) \\<ge> k-1\" for k\n  proof (induction k)\n    case (Suc k)\n    show ?case\n    proof (cases \"k=0\")\n      case False\n      then have \"\\<Sqinter> (b k (k, k - 1)) < \\<Sqinter> (b (Suc k) (Suc k, k))\"\n        using Inf_b_less by auto\n      with Suc show ?thesis\n        by simp\n    qed auto\n  qed auto\n\n  have b_ge: \"\\<Sqinter> (b k (j,i)) \\<ge> k-1\" if \"k \\<ge> j\" \"j > i\" for k j i\n  proof -\n    have \"\\<not> Suc (\\<Sqinter> (b k (j, i))) < k\"\n      by (metis (no_types) Inf_b_less Suc_leI b_ge_k diff_Suc_1 lessI not_less that)\n    then show ?thesis\n      by simp\n  qed\n\n  have hd_b: \"hd (list_of (b k (j,i))) = \\<Sqinter> (b k (j,i))\"\n    if \"i < j\" \"j \\<le> k\" for k j i\n    using that by (simp add: hd_list_of cInf_eq_Min)\n\n  have b_disjoint_less: \"b (enum K i) (j0, i) \\<inter> b (enum K i') (j0, i') = {}\"\n    if K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K \\<ge> j0\" \"i' < j\" \"i < i'\" \"j \\<le> j0\" for i i' j j0 K\n  proof (intro bb less_sets_imp_disjnt [unfolded disjnt_def])\n    show \"i < j0\"\n      using that by linarith\n    then show \"j0 \\<le> enum K i\"\n      by (meson K finite_enumerate_in_set greaterThan_iff less_imp_le_nat less_le_trans subsetD)\n    show \"enum K i < enum K i'\"\n      using K \\<open>j \\<le> j0\\<close> that by auto\n  qed\n\n  have b_disjoint: \"b (enum K i) (j0, i) \\<inter> b (enum K i') (j0, i') = {}\"\n    if K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K \\<ge> j0\" \"i < j\" \"i' < j\" \"i \\<noteq> i'\" \"j \\<le> j0\" for i i' j j0 K\n    using that b_disjoint_less inf_commute neq_iff by metis\n\n  have ot\\<omega>: \"ordertype ((\\<lambda>k. list_of (b k (j,i))) ` {Max (insert j K)<..}) ?LL = \\<omega>\"\n             (is \"?lhs = _\")\n    if K: \"K \\<in> \\<K> j i\" \"j > i\" for j i K\n  proof -\n    have Sucj: \"Suc (Max (insert j K)) \\<ge> j\"\n      using \\<K>_finite that(1) le_Suc_eq by auto\n    let ?N = \"{Inf(b k (j,i))| k. Max (insert j K) < k}\"\n    have infN: \"infinite ?N\"\n    proof (clarsimp simp add: infinite_nat_iff_unbounded_le)\n      fix m\n      show \"\\<exists>n\\<ge>m. \\<exists>k. n = \\<Sqinter> (b k (j,i)) \\<and> Max (insert j K) < k\"\n        using b_ge \\<open>j > i\\<close> Sucj\n        by (metis (no_types, lifting) diff_Suc_1 le_SucI le_trans less_Suc_eq_le nat_le_linear)\n    qed\n    have [simp]: \"Max (insert j K) < k \\<longleftrightarrow> j < k \\<and> (\\<forall>a\\<in>K. a < k)\" for k\n      using that by (auto simp: \\<K>_finite)\n    have \"?lhs = ordertype ?N less_than\"\n    proof (intro ordertype_eqI strip)\n      have \"list_of (b k (j,i)) = list_of (b k' (j,i))\"\n        if \"j \\<le> k\" \"j \\<le> k'\"  \"hd (list_of (b k (j,i))) = hd (list_of (b k' (j,i)))\"\n        for k k'\n        by (metis Inf_b_less \\<open>i < j\\<close> hd_b nat_less_le not_le that)\n      moreover have \"\\<exists>k' j' i'. hd (list_of (b k (j,i))) = \\<Sqinter> (b k' (j', i')) \\<and> i' < j' \\<and> j' \\<le> k'\"\n        if \"j \\<le> k\" for k\n        using that \\<open>i < j\\<close> hd_b less_imp_le_nat by blast\n      moreover have \"\\<exists>k'. hd (list_of (b k (j,i))) = \\<Sqinter> (b k' (j,i)) \\<and> j < k' \\<and> (\\<forall>a\\<in>K. a < k')\"\n         if \"j < k\" \"\\<forall>a\\<in>K. a < k\" for k\n        using that K hd_b less_imp_le_nat by blast\n      moreover have \"\\<Sqinter> (b k (j,i)) \\<in> hd ` (\\<lambda>k. list_of (b k (j,i))) ` {Max (insert j K)<..}\"\n        if \"j < k\" \"\\<forall>a\\<in>K. a < k\" for k\n        using that K by (auto simp: hd_b image_iff)\n      ultimately\n      show \"bij_betw hd ((\\<lambda>k. list_of (b k (j,i))) ` {Max (insert j K)<..}) {\\<Sqinter> (b k (j,i)) |k. Max (insert j K) < k}\"\n        by (auto simp: bij_betw_def inj_on_def)\n    next\n      fix ms ns\n      assume \"ms \\<in> (\\<lambda>k. list_of (b k (j,i))) ` {Max (insert j K)<..}\"\n        and \"ns \\<in> (\\<lambda>k. list_of (b k (j,i))) ` {Max (insert j K)<..}\"\n      with that obtain k k' where\n        ms: \"ms = list_of (b k (j,i))\" and ns: \"ns = list_of (b k' (j,i))\"\n        and \"j < k\" \"j < k'\" and lt_k: \"\\<forall>a\\<in>K. a < k\" and lt_k': \"\\<forall>a\\<in>K. a < k'\"\n        by (auto simp: \\<K>_finite)\n      then have len_eq [simp]: \"length ns = length ms\"\n        by (simp add: card_b)\n      have nz: \"length ns \\<noteq> 0\"\n        using b_ne \\<open>i < j\\<close> \\<open>j < k'\\<close> ns by auto\n      show \"(hd ms, hd ns) \\<in> less_than \\<longleftrightarrow> (ms, ns) \\<in> ?LL\"\n      proof\n        assume \"(hd ms, hd ns) \\<in> less_than\"\n        then show \"(ms, ns) \\<in> ?LL\"\n          using that nz\n          by (fastforce simp: lenlex_def \\<K>_finite card_b intro: hd_lex)\n      next\n        assume \\<section>: \"(ms, ns) \\<in> ?LL\"\n        then have \"(list_of (b k' (j,i)), list_of (b k (j,i))) \\<notin> ?LL\"\n          using less_asym ms ns omega_sum_1_less by blast\n        then show \"(hd ms, hd ns) \\<in> less_than\"\n          using \\<open>j < k\\<close> \\<open>j < k'\\<close> Inf_b_less [of i j i j] ms ns\n          by (metis Cons_lenlex_iff \\<section> len_eq b_ne card_b_finite diff_Suc_1 hd_Cons_tl hd_b length_Cons less_or_eq_imp_le less_than_iff linorder_neqE_nat sorted_list_of_set_eq_Nil_iff that(2))\n      qed\n    qed auto\n    also have \"\\<dots> = \\<omega>\"\n      using infN ordertype_nat_\\<omega> by blast\n    finally show ?thesis .\n  qed\n\n  have ot\\<omega>j: \"ordertype (BB j0 j ` \\<K> j0 j) ?LL = \\<omega>\\<up>j\" if \"j \\<le> j0\" for j j0\n    using that\n  proof (induction j) \\<comment>\\<open>a difficult proof, but no hints in Larson's text\\<close>\n    case 0\n    then show ?case\n      by (auto simp: XX_def)\n  next\n    case (Suc j)\n    then have ih: \"ordertype (BB j0 j ` \\<K> j0 j) ?LL = \\<omega> \\<up> j\"\n      by simp\n    have \"j \\<le> j0\"\n      by (simp add: Suc.prems Suc_leD)\n    have inj_BB: \"inj_on (BB j0 j) ([{j0<..}]\\<^bsup>j\\<^esup>)\"\n    proof (clarsimp simp: inj_on_def BB_def nsets_def  sorted_list_of_set_Un less_sets_UN2)\n      fix X Y\n      assume X: \"X \\<subseteq> {j0<..}\" and Y: \"Y \\<subseteq> {j0<..}\"\n        and \"finite X\" \"finite Y\"\n        and jeq: \"j = card X\"\n        and \"card Y = card X\"\n        and eq: \"list_of (a j0 \\<union> (\\<Union>i<card X. b (enum X i) (j0,i)))\n               = list_of (a j0 \\<union> (\\<Union>i<card X. b (enum Y i) (j0,i)))\"\n      have enumX: \"\\<And>n. \\<lbrakk>n < card X\\<rbrakk> \\<Longrightarrow> j0 \\<le> enum X n\"\n        using X \\<open>finite X\\<close> finite_enumerate_in_set less_imp_le_nat by blast\n      have enumY: \"\\<And>n. \\<lbrakk>n < card X\\<rbrakk> \\<Longrightarrow> j0 \\<le> enum Y n\"\n        using subsetD [OF Y] \n        by (metis \\<open>card Y = card X\\<close> \\<open>finite Y\\<close> finite_enumerate_in_set greaterThan_iff less_imp_le_nat)\n      have smX: \"strict_mono_sets {..<card X} (\\<lambda>i. b (enum X i) (j0, i))\"\n        and smY: \"strict_mono_sets {..<card X} (\\<lambda>i. b (enum Y i) (j0, i))\"\n        using Suc.prems \\<open>card Y = card X\\<close> \\<open>finite X\\<close> \\<open>finite Y\\<close> bb enumX enumY jeq\n        by (auto simp: strict_mono_sets_def)\n\n      have len_eq: \"length ms = length ns\"\n        if \"(ms, ns) \\<in> list.set (zip (map (list_of \\<circ> (\\<lambda>i. b (enum X i) (j0,i))) (list_of {..<n}))\n                                     (map (list_of \\<circ> (\\<lambda>i. b (enum Y i) (j0,i))) (list_of {..<n})))\"\n          \"n \\<le> card X\"\n        for ms ns n\n        using that\n      by (induction n rule: nat.induct) (auto simp: card_b enumX enumY)\n      have \"concat (map (list_of \\<circ> (\\<lambda>i. b (enum X i) (j0, i))) (list_of {..<card X}))\n          = concat (map (list_of \\<circ> (\\<lambda>i. b (enum Y i) (j0, i))) (list_of {..<card X}))\"\n        using eq\n        by (simp add: sorted_list_of_set_Un less_sets_UN2 sorted_list_of_set_UN_lessThan ab enumX enumY smX smY)\n      then have map_eq: \"map (list_of \\<circ> (\\<lambda>i. b (enum X i) (j0, i))) (list_of {..<card X})\n                       = map (list_of \\<circ> (\\<lambda>i. b (enum Y i) (j0, i))) (list_of {..<card X})\"\n        by (rule concat_injective) (auto simp: len_eq split: prod.split)\n      have \"enum X i = enum Y i\" if \"i < card X\" for i\n      proof -\n        have \"Inf (b (enum X i) (j0,i)) = Inf (b (enum Y i) (j0,i))\"\n          using iffD1 [OF map_eq_conv, OF map_eq] Suc.prems that\n          by (metis (mono_tags, lifting) card_b_finite comp_apply finite_lessThan lessThan_iff set_sorted_list_of_set)\n        moreover have \"Inf (b (enum X i) (j0,i)) \\<in> (b (enum X i) (j0,i))\"\n          \"Inf (b (enum Y i) (j0,i)) \\<in> (b (enum Y i) (j0,i))\" \"i < j0\"\n          using Inf_nat_def1 Suc.prems b_ne enumX enumY jeq that by auto\n        ultimately show ?thesis\n          by (metis Inf_b_less enumX enumY leI nat_less_le that)\n      qed\n      then show \"X = Y\"\n        by (simp add: \\<open>card Y = card X\\<close> \\<open>finite X\\<close> \\<open>finite Y\\<close> finite_enum_ext)\n    qed\n    have BB_Suc': \"BB j0 (Suc j) X = usplit (\\<lambda>L k. BB j0 j L @ list_of (b k (j0, j))) X\"\n      if \"X \\<in> USigma (\\<K> j0 j) (\\<lambda>K. {Max (insert j0 K)<..})\" for X\n      using that\n      by (simp add: USigma_iff \\<K>_finite less_sets_def usplit_def \\<K>_Suc BB_Suc \\<open>j \\<le> j0\\<close>)\n    have \"ordertype (BB j0 (Suc j) ` \\<K> j0 (Suc j)) ?LL\n        = ordertype\n           (usplit (\\<lambda>L k. BB j0 j L @ list_of (b k (j0, j))) ` USigma (\\<K> j0 j) (\\<lambda>K. {Max (insert j0 K)<..})) ?LL\"\n      by (simp add: BB_Suc' \\<K>_Suc)\n    also have \"\\<dots> = \\<omega> * ordertype (BB j0 j ` \\<K> j0 j) ?LL\"\n    proof (intro ordertype_append_image_IJ)\n      fix L k\n      assume \"L \\<in> \\<K> j0 j\" and \"k \\<in> {Max (insert j0 L)<..}\"\n      then have \"j0 < k\" and L: \"\\<And>a. a \\<in> L \\<Longrightarrow> a < k\"\n        by (simp_all add: \\<K>_finite)\n      then show \"BB j0 j L < list_of (b k (j0, j))\"\n        by (simp add: \\<open>L \\<in> \\<K> j0 j\\<close> \\<open>j \\<le> j0\\<close> \\<K>_finite less_list_of)\n    next\n      show \"inj_on (BB j0 j) (\\<K> j0 j)\"\n        by (simp add: \\<K>_def inj_BB)\n    next\n      fix L\n      assume L: \"L \\<in> \\<K> j0 j\"\n      then show \"L \\<lless> {Max (insert j0 L)<..} \\<and> finite L\"\n        by (simp add: \\<K>_finite less_sets_def)\n      show \"ordertype ((\\<lambda>i. list_of (b i (j0, j))) ` {Max (insert j0 L)<..}) ?LL = \\<omega>\"\n        using L Suc.prems Suc_le_lessD ot\\<omega> by blast\n    qed (auto simp: \\<K>_finite card_b)\n    also have \"\\<dots> = \\<omega> \\<up> ord_of_nat (Suc j)\"\n      by (simp add: oexp_mult_commute ih)\n    finally show ?case .\n  qed\n\n  define seqs where \"seqs \\<equiv> \\<lambda>j0 j K. list_of (a j0) # (map (list_of \\<circ> (\\<lambda>i. b (enum K i) (j0,i))) (list_of {..<j}))\"\n\n  have length_seqs [simp]: \"length (seqs j0 j K) = Suc j\" for j0 j K\n    by (simp add: seqs_def)\n\n  have BB_eq_concat_seqs: \"BB j0 j K = concat (seqs j0 j K)\"\n          and seqs_ne: \"seqs j0 j K \\<in> lists (- {[]})\"\n      if K: \"K \\<in> \\<K> j0 j\" and \"j \\<le> j0\" for K j j0\n  proof -\n    have j0: \"\\<And>i. i < card K \\<Longrightarrow> j0 \\<le> enum K i\" and le_j0: \"card K \\<le> j0\"\n      using finite_enumerate_in_set that unfolding \\<K>_def nsets_def by fastforce+\n    show \"BB j0 j K = concat (seqs j0 j K)\"\n      using that unfolding BB_def \\<K>_def nsets_def seqs_def\n      by (fastforce simp: j0 ab bb less_sets_UN2 sorted_list_of_set_Un\n          strict_mono_sets_def sorted_list_of_set_UN_lessThan)\n    have \"b (enum K i) (j0, i) \\<noteq> {}\" if \"i < card K\" for i\n      using j0 le_j0 less_le_trans that by simp\n    moreover have \"card K = j\"\n      using K \\<K>_card by blast\n    ultimately show \"seqs j0 j K \\<in> lists (- {[]})\"\n      by (clarsimp simp: seqs_def) (metis card_b_finite sorted_list_of_set_eq_Nil_iff)\n  qed\n\n  have BB_decomp: \"\\<exists>cs. BB j0 j K = concat cs \\<and> cs \\<in> lists (- {[]})\"\n    if K: \"K \\<in> \\<K> j0 j\" and \"j \\<le> j0\" for K j j0\n    using BB_eq_concat_seqs seqs_ne K that(2) by blast\n\n  have a_subset_M: \"a k \\<subseteq> M k\" for k\n    apply (clarsimp simp: a_def M_def DF_simps F_def Let_def split: prod.split_asm)\n    by (metis (no_types) fst_conv fst_grab_subset nxt_subset snd_conv snd_grab_subset subsetD)\n  have ba_Suc: \"b k (j,i) \\<lless> a (Suc k)\" if \"i < j\" \"j \\<le> k\" for i j k\n    by (meson a_subset_M bM less_sets_weaken2 nat_less_le that)\n  have ba: \"b k (j,i) \\<lless> a r\" if \"i < j\" \"j \\<le> k\" \"k < r\" for i j k r\n    by (metis Suc_lessI a_ne aa ba_Suc less_sets_trans that)\n\n  have disjnt_ba: \"disjnt (b k (j,i)) (a r)\" if \"i < j\" \"j \\<le> k\" for i j k r\n    by (meson ab ba disjnt_sym less_sets_imp_disjnt not_le that)\n\n  have bb_disjnt: \"disjnt (b k (j,i)) (b l (r,q))\"\n    if \"q < r\" \"i < j\" \"j \\<le> k\" \"r \\<le> l\" \"j < r\" for i j q r k l\n  proof (cases \"k=l\")\n    case True\n    with that show ?thesis\n      by (force simp: pair_less_def IJ_def intro: bb_same less_sets_imp_disjnt)\n  next\n    case False\n    with that show ?thesis\n      by (metis bb less_sets_imp_disjnt disjnt_sym nat_neq_iff)\n  qed\n\n  have sum_card_b: \"(\\<Sum>i<j. card (b (enum K i) (j0, i))) = enum (d j0) j - enum (d j0) 0\"\n    if K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K \\<ge> j0\" and \"j \\<le> j0\" for j0 j K\n    using \\<open>j \\<le> j0\\<close>\n  proof (induction j)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (Suc j)\n    then have \"j < card K\"\n      using that(3) by linarith\n    have dis: \"disjnt (b (enum K j) (j0, j)) (\\<Union>i<j. b (enum K i) (j0, i))\"\n      unfolding disjoint_UN_iff\n      by (meson Suc.prems b_disjoint_less disjnt_def disjnt_sym lessThan_iff less_Suc_eq that)\n    have j0_less: \"j0 < enum K j\"\n      using K \\<open>j < card K\\<close> by (force simp: finite_enumerate_in_set)\n    have \"(\\<Sum>i<Suc j. card (b (enum K i) (j0, i)))\n          = card (b (enum K j) (j0, j)) + (\\<Sum>i<j. card (b (enum K i) (j0, i)))\"\n      by (simp add: lessThan_Suc card_Un_disjnt [OF _ _ dis])\n    also have \"\\<dots> = card (b (enum K j) (j0, j)) + enum (d j0) j - enum (d j0) 0\"\n      using \\<open>Suc j \\<le> j0\\<close> by (simp add: Suc.IH split: nat_diff_split)\n    also have \"\\<dots> = enum (d j0) (Suc j) - enum (d j0) 0\"\n      using j0_less Suc.prems card_b less_or_eq_imp_le by force\n    finally show ?case .\n  qed\n\n  have card_UN_b: \"card (\\<Union>i<j. b (enum K i) (j0, i)) = enum (d j0) j - enum (d j0) 0\"\n    if K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K \\<ge> j0\" and \"j \\<le> j0\" for j0 j K\n    using that by (simp add: card_UN_disjoint sum_card_b b_disjoint)\n\n  have len_BB: \"length (BB j j K) = enum (d j) j\"\n    if K: \"K \\<in> \\<K> j j\" and \"j \\<le> j\" for j K\n  proof -\n    have dis_ab: \"\\<And>i. i < j \\<Longrightarrow> disjnt (a j) (b (enum K i) (j,i))\"\n      using K \\<K>_card \\<K>_enum ab less_sets_imp_disjnt nat_less_le by blast\n    show ?thesis\n      using K unfolding BB_def \\<K>_def nsets_def\n      by (simp add: card_UN_b card_Un_disjnt dis_ab card_a cInf_le_finite finite_enumerate_in_set enum_0_eq_Inf_finite)\n  qed\n\n  have \"d k \\<lless> d (Suc k)\" for k\n    by (metis aM a_ne d_eq da less_sets_fst_grab less_sets_trans less_sets_weaken2 nxt_subset)\n  then have dd: \"d k' \\<lless> d k\" if \"k' < k\" for k' k\n    by (meson UNIV_I d_ne less_sets_imp_strict_mono_sets strict_mono_sets_def that)\n\n  show thesis\n  proof\n    show \"(\\<Union> (range XX)) \\<subseteq> WW\"\n      by (auto simp: XX_def BB_def WW_def)\n    show \"ordertype (\\<Union> (range XX)) (?LL) = \\<omega> \\<up> \\<omega>\"\n      using ot\\<omega>j by (simp add: XX_def ordertype_\\<omega>\\<omega>)\n  next\n    fix U\n    assume U: \"U \\<in> [\\<Union> (range XX)]\\<^bsup>2\\<^esup>\"\n    then obtain x y where Ueq: \"U = {x,y}\" and len_xy: \"length x \\<le> length y\"\n      by (auto simp: lenlex_nsets_2_eq lenlex_length)\n\n    show \"\\<exists>l. Form l U \\<and> (0 < l \\<longrightarrow> [enum N l] < inter_scheme l U \\<and> list.set (inter_scheme l U) \\<subseteq> N)\"\n    proof (cases \"length x = length y\")\n      case True\n      then show ?thesis\n        using Form.intros(1) U Ueq by fastforce\n    next\n      case False\n      then have xy: \"length x < length y\"\n        using len_xy by auto\n      obtain j r K L where K: \"K \\<in> \\<K> j j\" and xeq: \"x = BB j j K\" and ne: \"BB j j K \\<noteq> BB r r L\"\n        and L: \"L \\<in> \\<K> r r\" and yeq: \"y = BB r r L\"\n        using U by (auto simp: Ueq XX_def)\n      then have \"length x = enum (d j) j\" \"length y = enum (d r) r\"\n        by (auto simp: len_BB)\n      then have \"j < r\"\n        using xy dd\n        by (metis card_d finite_enumerate_in_set finite_d lessI less_asym less_setsD linorder_neqE_nat)\n      then have aj_ar: \"a j \\<lless> a r\"\n        using aa by auto\n      have Ksub: \"K \\<subseteq> {j<..}\" and \"finite K\" \"card K \\<ge> j\"\n        using K by (auto simp: \\<K>_def nsets_def)\n      have Lsub: \"L \\<subseteq> {r<..}\" and \"finite L\" \"card L \\<ge> r\"\n        using L by (auto simp: \\<K>_def nsets_def)\n      have enumK: \"enum K i > j\" if \"i < j\" for i\n        using K \\<K>_card \\<K>_enum that by blast\n      have enumL: \"enum L i > r\" if \"i < r\" for i\n        using L \\<K>_card \\<K>_enum that by blast\n      have \"list.set (acc_lengths w (seqs j0 j K)) \\<subseteq> (+) w ` d j0\"\n        if K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K \\<ge> j0\" and \"j \\<le> j0\" for j0 j K w\n        using \\<open>j \\<le> j0\\<close>\n      proof (induction j arbitrary: w)\n        case 0\n        then show ?case\n          by (simp add: seqs_def Inf_nat_def1 card_a)\n      next\n        case (Suc j)\n        let ?db = \"\\<Sqinter> (d j0) + ((\\<Sum>i<j. card (b (enum K i) (j0,i))) + card (b (enum K j) (j0,j)))\"\n        have \"j0 < enum K j\"\n          by (meson Suc.prems Suc_le_lessD finite_enumerate_in_set greaterThan_iff le_trans subsetD K)\n        then have \"enum (d j0) j \\<ge> \\<Sqinter> (d j0)\"\n          using Suc.prems card_d by (simp add: cInf_le_finite finite_enumerate_in_set)\n        then have \"?db = enum (d j0) (Suc j)\"\n          using Suc.prems that\n          by (simp add: cInf_le_finite finite_enumerate_in_set sum_card_b card_b enum_d_0 \\<open>j0 < enum K j\\<close> less_or_eq_imp_le)\n        then have \"?db \\<in> d j0\"\n          using Suc.prems finite_enumerate_in_set by (auto simp: finite_enumerate_in_set)\n        moreover have \"list.set (acc_lengths w (seqs j0 j K)) \\<subseteq> (+) w ` d j0\"\n          by (simp add: Suc Suc_leD)\n        then have \"list.set (acc_lengths (w + \\<Sqinter> (d j0))\n                             (map (list_of \\<circ> (\\<lambda>i. b (enum K i) (j0,i))) (list_of {..<j})))\n                   \\<subseteq> (+) w ` d j0\"\n          by (simp add: seqs_def card_a subset_insertI)\n        ultimately show ?case\n          by (simp add: seqs_def acc_lengths_append image_iff Inf_nat_def1\n                        sum_sorted_list_of_set_map card_a)\n      qed\n      then have acc_lengths_subset_d: \"list.set (acc_lengths 0 (seqs j0 j K)) \\<subseteq> d j0\"\n        if K: \"K \\<subseteq> {j0<..}\" \"finite K\" \"card K \\<ge> j0\" and \"j \\<le> j0\" for j0 j K\n        by (metis image_add_0 that)\n\n      have \"strict_sorted x\" \"strict_sorted y\"\n        by (auto simp: xeq yeq BB_def)\n      have disjnt_xy: \"disjnt (list.set x) (list.set y)\"\n      proof -\n        have \"disjnt (a j) (a r)\"\n          using \\<open>j < r\\<close> aa less_sets_imp_disjnt by blast\n        moreover have \"disjnt (b (enum K i) (j,i)) (a r)\" if \"i < j\" for i\n          by (simp add: disjnt_ba enumK less_imp_le_nat that)\n        moreover have \"disjnt (a j) (b (enum L q) (r,q))\" if \"q < r\" for q\n          by (meson disjnt_ba disjnt_sym enumL less_imp_le_nat that)\n        moreover have \"disjnt (b (enum K i) (j,i)) (b (enum L q) (r,q))\" if \"i < j\" \"q < r\" for i q\n        by (meson \\<open>j < r\\<close> bb_disjnt enumK enumL less_imp_le that)\n      ultimately show ?thesis\n        by (simp add: xeq yeq BB_def)\n      qed\n      have \"\\<exists>us vs. merge (seqs j j K) (seqs r r L) us vs\"\n      proof (rule merge_exists)\n        show \"strict_sorted (concat (seqs j j K))\"\n          using BB_eq_concat_seqs K \\<open>strict_sorted x\\<close> xeq by auto\n        show \"strict_sorted (concat (seqs r r L))\"\n          using BB_eq_concat_seqs L \\<open>strict_sorted y\\<close> yeq by auto\n        show \"seqs j j K \\<in> lists (- {[]})\" \"seqs r r L \\<in> lists (- {[]})\"\n          by (auto simp: K L seqs_ne)\n        show \"hd (seqs j j K) < hd (seqs r r L)\"\n          by (simp add: aj_ar less_sets_imp_list_less seqs_def)\n        show \"seqs j j K \\<noteq> []\" \"seqs r r L \\<noteq> []\"\n          using seqs_def by blast+\n        have less_bb: \"b (enum K i) (j,i) \\<lless> b (enum L p) (r, p)\"\n          if \"\\<not> b (enum L p) (r, p) \\<lless> b (enum K i) (j,i)\" and \"i < j\" \"p < r\"\n          for i p\n          by (metis IJ_iff \\<open>j < r\\<close> bb bb_same enumK enumL less_imp_le_nat linorder_neqE_nat pair_lessI1 that)\n        show \"u < v \\<or> v < u\"\n          if \"u \\<in> list.set (seqs j j K)\" and \"v \\<in> list.set (seqs r r L)\" for u v\n          using that enumK enumL unfolding seqs_def\n          apply (auto simp: seqs_def aj_ar intro!: less_bb less_sets_imp_list_less)\n          apply (meson ab ba less_imp_le_nat not_le)+\n          done\n      qed\n      then obtain uus vvs where merge: \"merge (seqs j j K) (seqs r r L) uus vvs\"\n        by metis\n      then have \"uus \\<noteq> []\"\n        using merge_length1_gt_0 by (auto simp: seqs_def)\n      then obtain u1 us where us: \"u1#us = uus\"\n        by (metis neq_Nil_conv)\n      define ku where \"ku \\<equiv> length (u1#us)\"\n      define ps where \"ps \\<equiv> acc_lengths 0 (u1#us)\"\n      have us_ne: \"u1#us \\<in> lists (- {[]})\"\n        using merge_length1_nonempty seqs_ne us merge us K by auto\n      have xu_eq: \"x = concat (u1#us)\"\n        using BB_eq_concat_seqs K merge merge_preserves us xeq by auto\n      then have \"strict_sorted u1\"\n        using \\<open>strict_sorted x\\<close> strict_sorted_append_iff by auto\n      have u_sub: \"list.set ps \\<subseteq> list.set (acc_lengths 0 (seqs j j K))\"\n        using acc_lengths_merge1 merge ps_def us by blast\n      have \"vvs \\<noteq> []\"\n        using merge BB_eq_concat_seqs L merge_preserves xy yeq by auto\n      then obtain v1 vs where vs: \"v1#vs = vvs\"\n        by (metis neq_Nil_conv)\n      define kv where \"kv \\<equiv> length (v1#vs)\"\n      define qs where \"qs \\<equiv> acc_lengths 0 (v1#vs)\"\n      have vs_ne: \"v1#vs \\<in> lists (- {[]})\"\n        using L merge merge_length2_nonempty seqs_ne vs by auto\n      have yv_eq: \"y = concat (v1#vs)\"\n        using BB_eq_concat_seqs L merge merge_preserves vs yeq by auto\n      then have \"strict_sorted v1\"\n        using \\<open>strict_sorted y\\<close> strict_sorted_append_iff by auto\n      have v_sub: \"list.set qs \\<subseteq> list.set (acc_lengths 0 (seqs r r L))\"\n        using acc_lengths_merge2 merge qs_def vs by blast\n\n      have ss_concat_jj: \"strict_sorted (concat (seqs j j K))\"\n        using BB_eq_concat_seqs K \\<open>strict_sorted x\\<close> xeq by auto\n      then obtain k: \"0 < kv\" \"kv \\<le> ku\" \"ku \\<le> Suc kv\" \"kv \\<le> Suc j\"\n        using us vs merge_length_le merge_length_le_Suc merge_length_less2 merge\n        unfolding ku_def kv_def by fastforce\n\n      define zs where \"zs \\<equiv> concat [ps,u1,qs,v1] @ interact us vs\"\n      have ss: \"strict_sorted zs\"\n      proof -\n        have ssp: \"strict_sorted ps\"\n          unfolding ps_def by (meson strict_sorted_acc_lengths us_ne)\n        have ssq: \"strict_sorted qs\"\n          unfolding qs_def by (meson strict_sorted_acc_lengths vs_ne)\n\n        have \"d j \\<lless> list.set x\"\n          using da [of j] db [of j]  K \\<K>_card \\<K>_enum nat_less_le\n          by (auto simp: xeq BB_def less_sets_Un2 less_sets_UN2)\n        then have ac_x: \"acc_lengths 0 (seqs j j K) < x\"\n          by (meson Ksub \\<open>finite K\\<close> \\<open>j \\<le> card K\\<close> acc_lengths_subset_d le_refl less_sets_imp_list_less less_sets_weaken1)\n        then have \"ps < x\"\n          by (meson Ksub \\<open>d j \\<lless> list.set x\\<close> \\<open>finite K\\<close> \\<open>j \\<le> card K\\<close> acc_lengths_subset_d le_refl less_sets_imp_list_less less_sets_weaken1 u_sub)\n        then have \"ps < u1\"\n          by (metis Nil_is_append_conv concat.simps(2) hd_append2 less_list_def xu_eq)\n\n        have \"d r \\<lless> list.set y\"\n          using da [of r] db [of r]  L \\<K>_card \\<K>_enum nat_less_le\n          by (auto simp: yeq BB_def less_sets_Un2 less_sets_UN2)\n        then have \"acc_lengths 0 (seqs r r L) < y\"\n          by (meson Lsub \\<open>finite L\\<close> \\<open>r \\<le> card L\\<close> acc_lengths_subset_d le_refl less_sets_imp_list_less less_sets_weaken1)\n        then have \"qs < y\"\n          by (metis L Lsub \\<K>_card \\<open>d r \\<lless> list.set y\\<close> \\<open>finite L\\<close> acc_lengths_subset_d less_sets_imp_list_less less_sets_weaken1 order_refl v_sub)\n        then have \"qs < v1\"\n          by (metis concat.simps(2) gr_implies_not0 hd_append2 less_list_def list.size(3) xy yv_eq)\n\n        have carda_v1: \"card (a r) \\<le> length v1\"\n          using length_hd_merge2 [OF merge] unfolding vs [symmetric] by (simp add: seqs_def)\n        have ab_enumK: \"\\<And>i. i < j \\<Longrightarrow> a j \\<lless> b (enum K i) (j,i)\"\n          by (meson ab enumK le_trans less_imp_le_nat)\n\n        have ab_enumL: \"\\<And>q. q < r \\<Longrightarrow> a j \\<lless> b (enum L q) (r,q)\"\n          by (meson \\<open>j < r\\<close> ab enumL le_trans less_imp_le_nat)\n        then have ay: \"a j \\<lless> list.set y\"\n          by (auto simp: yeq BB_def less_sets_Un2 less_sets_UN2 aj_ar)\n\n        have disjnt_hd_last_K_y: \"disjnt {hd l..last l} (list.set y)\"\n          if l: \"l \\<in> list.set (seqs j j K)\" for l\n        proof (clarsimp simp add: yeq BB_def disjnt_iff Ball_def, intro conjI strip)\n          fix u\n          assume u: \"u \\<le> last l\" and \"hd l \\<le> u\"\n          with l consider \"u \\<le> last (list_of (a j))\" \"hd (list_of (a j)) \\<le> u\"\n            | i where \"i<j\" \"u \\<le> last (list_of (b (enum K i) (j,i)))\" \"hd (list_of (b (enum K i) (j,i))) \\<le> u\"\n            by (force simp: seqs_def)\n          note l_cases = this\n          then show \"u \\<notin> a r\"\n          proof cases\n            case 1\n            then show ?thesis\n              by (metis a_ne aj_ar finite_a last_in_set leD less_setsD set_sorted_list_of_set sorted_list_of_set_eq_Nil_iff)\n          next\n            case 2\n            then show ?thesis\n              by (metis enumK ab ba Inf_nat_def1 b_ne card_b_finite hd_b last_in_set less_asym less_setsD not_le set_sorted_list_of_set sorted_list_of_set_eq_Nil_iff)\n          qed\n          fix q\n          assume \"q < r\"\n          show \"u \\<notin> b (enum L q) (r,q)\" \n            using l_cases\n          proof cases\n            case 1\n            then show ?thesis\n              by (metis \\<open>q < r\\<close> a_ne ab_enumL finite_a last_in_set leD less_setsD set_sorted_list_of_set sorted_list_of_set_eq_Nil_iff)\n          next\n            case 2\n            show ?thesis\n            proof (cases \"enum K i = enum L q\")\n              case True\n              then show ?thesis\n                using 2 bb_same [of concl: \"enum L q\" j i r q] \\<open>j < r\\<close> u\n                by (metis IJ_iff b_ne card_b_finite enumK last_in_set leD less_imp_le_nat less_setsD pair_lessI1 set_sorted_list_of_set sorted_list_of_set_eq_Nil_iff)\n            next\n              case False\n              with 2 bb enumK enumL show ?thesis\n                unfolding less_sets_def\n                by (metis \\<open>q < r\\<close> b_ne card_b_finite last_in_set leD less_imp_le_nat list.set_sel(1) nat_neq_iff set_sorted_list_of_set sorted_list_of_set_eq_Nil_iff)\n            qed\n          qed\n        qed\n\n        have u1_y: \"list.set u1 \\<lless> list.set y\"\n          using vs yv_eq L \\<open>strict_sorted y\\<close> merge merge_less_sets_hd merge_preserves seqs_ne ss_concat_jj us by fastforce\n        have u1_subset_seqs: \"list.set u1 \\<subseteq> list.set (concat (seqs j j K))\"\n          using merge_preserves [OF merge] us by auto\n\n        have \"b k (j,i) \\<lless> d (Suc k)\" if \"j\\<le>k\" \"i<j\" for k j i\n          by (metis bM d_eq less_sets_fst_grab less_sets_weaken2 nxt_subset that)\n        then have bd: \"b k (j,i) \\<lless> d k'\" if \"j\\<le>k\" \"i<j\" \"k < k'\" for k k' j i\n          by (metis Suc_lessI d_ne dd less_sets_trans that)\n\n        have \"a k \\<lless> d (Suc k)\" for k\n          by (metis aM d_eq less_sets_fst_grab less_sets_weaken2 nxt_subset)\n        then have ad: \"a k \\<lless> d k'\" if \"k<k'\" for k k'\n          by (metis Suc_lessI d_ne dd less_sets_trans that)\n\n        have \"u1 < y\"\n          by (simp add: u1_y less_sets_imp_list_less)\n        have \"n < Inf (d r)\" if n: \"n \\<in> list.set u1\" for n\n        proof -\n          obtain l where l: \"l \\<in> list.set (seqs j j K)\" and n: \"n \\<in> list.set l\"\n            using n u1_subset_seqs by auto\n          then consider \"l = list_of (a j)\" | i where \"l = list_of (b (enum K i) (j,i))\" \"i < j\"\n            by (force simp: seqs_def)\n          then show ?thesis\n          proof cases\n            case 1\n            then show ?thesis\n              by (metis Inf_nat_def1 \\<open>j < r\\<close> ad d_ne finite_a less_setsD n set_sorted_list_of_set)\n          next\n            case 2\n            then have \"hd (list_of (b (enum K i) (j,i))) = Min (b (enum K i) (j,i))\"\n              by (meson b_ne card_b_finite enumK hd_list_of less_imp_le_nat)\n            also have \"\\<dots> \\<le> n\"\n              using 2 n by (simp add: less_list_def disjnt_iff less_sets_def)\n            also have f8: \"n < hd y\"\n              using less_setsD that u1_y\n              by (metis gr_implies_not0 list.set_sel(1) list.size(3) xy)\n            finally have \"l < y\"\n              using 2 disjnt_hd_last_K_y [OF l]\n              by (simp add: disjnt_iff) (metis leI less_imp_le_nat less_list_def list.set_sel(1))\n            moreover have \"last (list_of (b (enum K i) (j,i))) < hd (list_of (a r))\"\n              using \\<open>l < y\\<close> L n by (auto simp:  2yeq BB_eq_concat_seqs seqs_def less_list_def)\n            then have \"enum K i < r\"\n              by (metis \"2\"(1) a_ne ab card_b_finite empty_iff finite.emptyI finite_a last_in_set leI less_asym less_setsD list.set_sel(1) n set_sorted_list_of_set)\n            moreover have \"j \\<le> enum K i\"\n              by (simp add: \"2\"(2) enumK less_imp_le_nat)\n            ultimately show ?thesis\n              using 2 n bd [of j \"enum K i\" i r] Inf_nat_def1 less_setsD by force\n          qed\n        qed\n        then have \"last u1 < Inf (d r)\"\n          using \\<open>uus \\<noteq> []\\<close> us_ne by auto\n        also have \"\\<dots> \\<le> length v1\"\n          using card_a carda_v1 by auto\n        finally have \"last u1 < length v1\" .\n        then have \"u1 < qs\"\n          by (simp add: qs_def less_list_def)\n\n        have \"strict_sorted (interact (u1#us) (v1#vs))\"\n          using L \\<open>strict_sorted x\\<close> \\<open>strict_sorted y\\<close> merge merge_interact merge_preserves seqs_ne us vs xu_eq yv_eq by auto\n        then have \"strict_sorted (interact us vs)\" \"v1 < interact us vs\"\n          by (auto simp: strict_sorted_append_iff)\n        moreover have \"ps < u1 @ qs @ v1 @ interact us vs\"\n          using \\<open>ps < u1\\<close> us_ne unfolding less_list_def by auto\n        moreover have \"u1 < qs @ v1 @ interact us vs\"\n          by (metis \\<open>u1 < qs\\<close> \\<open>vvs \\<noteq> []\\<close> acc_lengths_eq_Nil_iff hd_append less_list_def qs_def vs)\n        moreover have \"qs < v1 @ interact us vs\"\n          using \\<open>qs < v1\\<close> us_ne \\<open>last u1 < length v1\\<close> vs_ne by (auto simp: less_list_def)\n        ultimately show ?thesis\n          by (simp add: zs_def strict_sorted_append_iff ssp ssq \\<open>strict_sorted u1\\<close> \\<open>strict_sorted v1\\<close>)\n      qed\n      have ps_subset_d: \"list.set ps \\<subseteq> d j\"\n          using K Ksub \\<K>_card \\<open>finite K\\<close> acc_lengths_subset_d u_sub by blast\n      have ps_less_u1: \"ps < u1\"\n      proof -\n        have \"hd u1 = hd x\"\n          using us_ne by (auto simp: xu_eq)\n        then have \"hd u1 \\<in> a j\"\n          by (simp add: xeq BB_eq_concat_seqs K seqs_def hd_append hd_list_of)\n        then have \"list.set ps \\<lless> {hd u1}\"\n          by (metis da ps_subset_d less_sets_def singletonD subset_iff)\n        then show ?thesis\n          by (metis less_hd_imp_less list.set(2) empty_set less_sets_imp_list_less)\n      qed\n      have qs_subset_d: \"list.set qs \\<subseteq> d r\"\n        using L Lsub \\<K>_card \\<open>finite L\\<close> acc_lengths_subset_d v_sub by blast\n      have qs_less_v1: \"qs < v1\"\n      proof -\n        have \"hd v1 = hd y\"\n          using vs_ne by (auto simp: yv_eq)\n        then have \"hd v1 \\<in> a r\"\n          by (simp add: yeq BB_eq_concat_seqs L seqs_def hd_append hd_list_of)\n        then have \"list.set qs \\<lless> {hd v1}\"\n          by (metis da qs_subset_d less_sets_def singletonD subset_iff)\n        then show ?thesis\n          by (metis less_hd_imp_less list.set(2) empty_set less_sets_imp_list_less)\n      qed\n      have FB: \"Form_Body ku kv x y zs\"\n        unfolding Form_Body.simps\n        using ku_def kv_def ps_def qs_def ss us_ne vs_ne xu_eq xy yv_eq zs_def by blast\n      then have \"zs = (inter_scheme ((ku+kv) - Suc 0) {x,y})\"\n        by (simp add: Form_Body_imp_inter_scheme k)\n      obtain l where \"l \\<le> 2 * (Suc j)\" and l: \"Form l U\" and zs_eq_interact: \"zs = inter_scheme l {x,y}\"\n      proof\n        show \"ku+kv-1 \\<le> 2 * (Suc j)\"\n          using k by auto\n        show \"Form (ku+kv-1) U\"\n        proof (cases \"ku=kv\")\n          case True\n          then show ?thesis\n            using FB Form.simps Ueq \\<open>0 < kv\\<close> by (auto simp: mult_2)\n        next\n          case False\n          then have \"ku = Suc kv\"\n            using k by auto\n          then show ?thesis\n            using FB Form.simps Ueq \\<open>0 < kv\\<close> by auto\n        qed\n        show \"zs = inter_scheme (ku + kv - 1) {x, y}\"\n          using Form_Body_imp_inter_scheme by (simp add: FB k)\n      qed\n      then have \"enum N l \\<le> enum N (Suc (2 * Suc j))\"\n        by (simp add: assms less_imp_le_nat)\n      also have \"\\<dots> < Min (d j)\"\n        by (smt (verit, best) Min_gr_iff d_eq d_ne finite_d fst_grab_subset greaterThan_iff in_mono le_inf_iff nxt_def)\n      finally have ls: \"{enum N l} \\<lless> d j\"\n        by simp\n      have \"l > 0\"\n        by (metis l False Form_0_cases_raw Set.doubleton_eq_iff Ueq gr0I)\n      show ?thesis\n        unfolding Ueq\n      proof (intro exI conjI impI)\n        have zs_subset: \"list.set zs \\<subseteq> list.set (acc_lengths 0 (seqs j j K)) \\<union> list.set (acc_lengths 0 (seqs r r L)) \\<union> list.set x \\<union> list.set y\"\n          using u_sub v_sub by (auto simp: zs_def xu_eq yv_eq)\n        also have \"\\<dots> \\<subseteq> N\"\n        proof (simp, intro conjI)\n          show \"list.set (acc_lengths 0 (seqs j j K)) \\<subseteq> N\"\n            using d_subset_N Ksub \\<open>finite K\\<close> \\<open>j \\<le> card K\\<close> acc_lengths_subset_d by blast\n          show \"list.set (acc_lengths 0 (seqs r r L)) \\<subseteq> N\"\n            using d_subset_N Lsub \\<open>finite L\\<close> \\<open>r \\<le> card L\\<close> acc_lengths_subset_d by blast\n          show \"list.set x \\<subseteq> N\" \"list.set y \\<subseteq> N\"\n            by (simp_all add: xeq yeq BB_def a_subset_N UN_least b_subset_N)\n        qed\n        finally show \"list.set (inter_scheme l {x, y}) \\<subseteq> N\"\n          using zs_eq_interact by blast\n        have \"[enum N l] < ps\"\n          using ps_subset_d ls\n          by (metis empty_set less_sets_imp_list_less less_sets_weaken2 list.simps(15))\n        then show \"[enum N l] < inter_scheme l {x, y}\"\n          by (simp add: zs_def less_list_def ps_def flip: zs_eq_interact)\n      qed (use Ueq l in blast)\n    qed\n  qed\nqed\n\n\nsubsection \\<open>The main partition theorem for @{term \"\\<omega>\\<up>\\<omega>\"}\\<close>\n\ndefinition iso_ll where \"iso_ll A B \\<equiv> iso (lenlex less_than \\<inter> (A\\<times>A)) (lenlex less_than \\<inter> (B\\<times>B))\"\n\ncorollary ordertype_eq_ordertype_iso_ll:\n  assumes \"Field (Restr (lenlex less_than) A) = A\" \"Field (Restr (lenlex less_than) B) = B\"\n  shows \"(ordertype A (lenlex less_than) = ordertype B (lenlex less_than))\n         \\<longleftrightarrow> (\\<exists>f. iso_ll A B f)\"\nproof -\n  have \"total_on A (lenlex less_than) \\<and> total_on B (lenlex less_than)\"\n    by (meson UNIV_I total_lenlex total_on_def total_on_less_than)\n  then show ?thesis\n    by (simp add: assms wf_lenlex lenlex_transI iso_ll_def ordertype_eq_ordertype_iso_Restr)\nqed\n\ntheorem partition_\\<omega>\\<omega>_aux:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\"\n  shows \"partn_lst (lenlex less_than) WW [\\<omega>\\<up>\\<omega>,\\<alpha>] 2\" (is \"partn_lst ?R WW [\\<omega>\\<up>\\<omega>,\\<alpha>] 2\")\nproof (cases \"\\<alpha> \\<le> 1\")\n  case True\n  then show ?thesis\n    using strict_sorted_into_WW unfolding WW_def by (auto intro!: partn_lst_triv1[where i=1])\nnext\n  case False\n  obtain m where m: \"\\<alpha> = ord_of_nat m\"\n    using assms elts_\\<omega> by auto\n  then have \"m>1\"\n    using False by auto\n  show ?thesis\n    unfolding partn_lst_def\n  proof clarsimp\n    fix f\n    assume f: \"f \\<in> [WW]\\<^bsup>2\\<^esup> \\<rightarrow> {..<Suc (Suc 0)}\"\n    let ?P0 = \"\\<exists>X \\<subseteq> WW. ordertype X ?R = \\<omega>\\<up>\\<omega> \\<and> f ` [X]\\<^bsup>2\\<^esup> \\<subseteq> {0}\"\n    let ?P1 = \"\\<exists>M \\<subseteq> WW. ordertype M ?R = \\<alpha> \\<and> f ` [M]\\<^bsup>2\\<^esup> \\<subseteq> {1}\"\n    have \\<dagger>: \"?P0 \\<or> ?P1\"\n    proof (rule disjCI)\n      assume not1: \"\\<not> ?P1\"\n      have \"\\<exists>W'. ordertype W' ?R = \\<omega>\\<up>n \\<and> f ` [W']\\<^bsup>2\\<^esup> \\<subseteq> {0} \\<and> W' \\<subseteq> WW_seg (n*m)\" for n::nat\n      proof -\n        have fnm: \"f \\<in> [WW_seg (n*m)]\\<^bsup>2\\<^esup> \\<rightarrow> {..<Suc (Suc 0)}\"\n          using f WW_seg_subset_WW [of \"n*m\"] by (meson in_mono nsets_Pi_contra)\n        have *: \"partn_lst ?R (WW_seg (n*m)) [\\<omega>\\<up>n, ord_of_nat m] 2\"\n          using ordertype_WW_seg [of \"n*m\"]\n          by (simp add: partn_lst_VWF_imp_partn_lst [OF Theorem_3_2])\n        show ?thesis\n          using partn_lst_E [OF * fnm, simplified]\n          by (metis One_nat_def WW_seg_subset_WW less_2_cases m not1 nth_Cons_0 nth_Cons_Suc numeral_2_eq_2 subset_trans)\n      qed\n      then obtain W':: \"nat \\<Rightarrow> nat list set\"\n          where otW': \"\\<And>n. ordertype (W' n) ?R = \\<omega>\\<up>n\"\n          and f_W': \"\\<And>n. f ` [W' n]\\<^bsup>2\\<^esup> \\<subseteq> {0}\"\n          and seg_W': \"\\<And>n. W' n \\<subseteq> WW_seg (n*m)\"\n        by metis\n      define WW' where \"WW' \\<equiv> (\\<Union>n. W' n)\"\n      have \"WW' \\<subseteq> WW\"\n        using seg_W' WW_seg_subset_WW by (force simp: WW'_def)\n      with f have f': \"f \\<in> [WW']\\<^bsup>2\\<^esup> \\<rightarrow> {..<Suc (Suc 0)}\"\n        using nsets_mono by fastforce\n      have ot': \"ordertype WW' ?R = \\<omega>\\<up>\\<omega>\"\n      proof (rule antisym)\n        have \"ordertype WW' ?R \\<le> ordertype WW ?R\"\n          by (simp add: \\<open>WW' \\<subseteq> WW\\<close> lenlex_transI ordertype_mono wf_lenlex)\n        with ordertype_WW\n        show \"ordertype WW' ?R \\<le> \\<omega> \\<up> \\<omega>\"\n          by simp\n        have \"\\<omega> \\<up> n \\<le> ordertype (\\<Union> (range W')) ?R\" for n::nat\n          using oexp_Limit ordertype_\\<omega>\\<omega> otW' by auto\n        then show \"\\<omega> \\<up> \\<omega> \\<le> ordertype WW' ?R\"\n          by (auto simp: elts_\\<omega> oexp_Limit ZFC_in_HOL.SUP_le_iff WW'_def)\n      qed\n      have FR_WW: \"Field (Restr (lenlex less_than) WW) = WW\"\n        by (simp add: Limit_omega_oexp Limit_ordertype_imp_Field_Restr ordertype_WW)\n      have FR_WW': \"Field (Restr (lenlex less_than) WW') = WW'\"\n        by (simp add: Limit_omega_oexp Limit_ordertype_imp_Field_Restr ot')\n      have FR_W: \"Field (Restr (lenlex less_than) (WW_seg n)) = WW_seg n\" if \"n>0\" for n\n        by (simp add: Limit_omega_oexp ordertype_WW_seg that Limit_ordertype_imp_Field_Restr)\n      have FR_W': \"Field (Restr (lenlex less_than) (W' n)) = W' n\" if \"n>0\" for n\n        by (simp add: Limit_omega_oexp otW' that Limit_ordertype_imp_Field_Restr)\n      have \"\\<exists>h. iso_ll (WW_seg n) (W' n) h\" if \"n>0\" for n\n      proof (subst ordertype_eq_ordertype_iso_ll [symmetric])\n        show \"ordertype (WW_seg n) (lenlex less_than) = ordertype (W' n) (lenlex less_than)\"\n          by (simp add: ordertype_WW_seg otW')\n      qed (auto simp: FR_W FR_W' that)\n      then obtain h_seg where h_seg: \"\\<And>n. n > 0 \\<Longrightarrow> iso_ll (WW_seg n) (W' n) (h_seg n)\"\n        by metis\n      define h where \"h \\<equiv> \\<lambda>l. if l=[] then [] else h_seg (length l) l\"\n\n      have bij_h_seg: \"\\<And>n. n > 0 \\<Longrightarrow> bij_betw (h_seg n) (WW_seg n) (W' n)\"\n        using h_seg by (simp add: iso_ll_def iso_iff2 FR_W FR_W')\n      have len_h_seg: \"length (h_seg (length l) l) = length l * m\"\n        if \"length l > 0\" \"l \\<in> WW\" for l\n        using bij_betwE [OF bij_h_seg] seg_W' that by (simp add: WW_seg_def subset_iff)\n      have hlen: \"length (h x) = length (h y) \\<longleftrightarrow> length x = length y\" if \"x \\<in> WW\" \"y \\<in> WW\" for x y\n        using that \\<open>1 < m\\<close> h_def len_h_seg by force\n\n      have h: \"iso_ll WW WW' h\"\n        unfolding iso_ll_def iso_iff2 FR_WW FR_WW'\n      proof (intro conjI strip)\n        have W'_ne: \"W' n \\<noteq> {}\" for n\n          using otW' [of n] by auto\n        then have \"[] \\<in> WW'\"\n          using seg_W' [of 0] by (auto simp: WW'_def WW_seg_def)\n        let ?g = \"\\<lambda>l. if l=[] then l else inv_into (WW_seg (length l div m)) (h_seg (length l div m)) l\"\n        have h_seg_iff: \"\\<And>n a b. \\<lbrakk>a \\<in> WW_seg n; b \\<in> WW_seg n; n>0\\<rbrakk> \\<Longrightarrow>\n                          (a, b) \\<in> lenlex less_than \\<longleftrightarrow>\n                          (h_seg n a, h_seg n b) \\<in> lenlex less_than \\<and> h_seg n a \\<in> W' n \\<and> h_seg n b \\<in> W' n\"\n          using h_seg by (auto simp: iso_ll_def iso_iff2 FR_W FR_W')\n\n        show \"bij_betw h WW WW'\"\n          unfolding bij_betw_iff_bijections\n        proof (intro exI conjI ballI)\n          fix l\n          assume \"l \\<in> WW\"\n          then have l: \"l \\<in> WW_seg (length l)\"\n            by (simp add: WW_seg_def)\n          have \"h l \\<in> W' (length l)\"\n          proof (cases \"l=[]\")\n            case True\n            with seg_W' [of 0] W'_ne show ?thesis\n              by (auto simp: WW_seg_def h_def)\n          next\n            case False\n            then show ?thesis\n              using bij_betwE bij_h_seg h_def l by fastforce\n          qed\n          show \"h l \\<in> WW'\"\n            using WW'_def \\<open>h l \\<in> W' (length l)\\<close> by blast\n          show \"?g (h l) = l\"\n          proof (cases \"l=[]\")\n            case False\n            then have \"length l > 0\"\n              by auto\n            then have \"h_seg (length l) l \\<noteq> []\"\n              using \\<open>1 < m\\<close> \\<open>l \\<in> WW\\<close> len_h_seg by fastforce\n            moreover have \"bij_betw (h_seg (length l)) (WW_seg (length l)) (W' (length l))\"\n              using \\<open>0 < length l\\<close> bij_h_seg by presburger\n            ultimately show ?thesis\n              using \\<open>l \\<in> WW\\<close> bij_betw_inv_into_left h_def l len_h_seg by fastforce\n          qed (auto simp: h_def)\n        next\n          fix l\n          assume \"l \\<in> WW'\"\n          then have l: \"l \\<in> W' (length l div m)\"\n            using WW_seg_def \\<open>1 < m\\<close> seg_W' by (fastforce simp: WW'_def)\n          show \"?g l \\<in> WW\"\n          proof (cases \"l=[]\")\n            case False\n            then have \"l \\<notin> W' 0\"\n              using WW_seg_def seg_W' by fastforce\n            with l have \"inv_into (WW_seg (length l div m)) (h_seg (length l div m)) l \\<in> WW_seg (length l div m)\"\n              by (metis Nat.neq0_conv bij_betwE bij_betw_inv_into bij_h_seg)\n            then show ?thesis\n              using False WW_seg_subset_WW by auto\n          qed (auto simp: WW_def)\n\n          show \"h (?g l) = l\"\n          proof (cases \"l=[]\")\n            case False\n            then have \"0 < length l div m\"\n              using WW_seg_def l seg_W' by fastforce\n            then have \"inv_into (WW_seg (length l div m)) (h_seg (length l div m)) l \\<in> WW_seg (length l div m)\"\n              by (metis bij_betw_imp_surj_on bij_h_seg inv_into_into l)\n            then show ?thesis\n              using bij_h_seg [of \"length l div m\"] WW_seg_def \\<open>0 < length l div m\\<close> bij_betw_inv_into_right l\n              by (fastforce simp: h_def)\n          qed (auto simp: h_def)\n        qed\n        fix a b\n        assume \"a \\<in> WW\" \"b \\<in> WW\"\n        show \"(a, b) \\<in> Restr (lenlex less_than) WW \\<longleftrightarrow> (h a, h b) \\<in> Restr (lenlex less_than) WW'\"\n          (is \"?lhs = ?rhs\")\n        proof\n          assume L: ?lhs\n          then consider \"length a < length b\" | \"length a = length b\" \"(a, b) \\<in> lex less_than\"\n            by (auto simp: lenlex_conv)\n          then show ?rhs\n          proof cases\n            case 1\n            then have \"length (h a) < length (h b)\"\n              using \\<open>1 < m\\<close> \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> h_def len_h_seg by auto\n            then have \"(h a, h b) \\<in> lenlex less_than\"\n              by (auto simp: lenlex_conv)\n            then show ?thesis\n              using \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> \\<open>bij_betw h WW WW'\\<close> bij_betwE by fastforce\n          next\n            case 2\n            then have ab: \"a \\<in> WW_seg (length a)\" \"b \\<in> WW_seg (length a)\"\n              using \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> by (auto simp: WW_seg_def)\n            have \"length (h a) = length (h b)\"\n              using 2 \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> h_def len_h_seg by force\n            moreover have \"(a, b) \\<in> lenlex less_than\"\n              using L by blast\n            then have \"(h_seg (length a) a, h_seg (length a) b) \\<in> lenlex less_than\"\n              using 2 ab h_seg_iff by blast\n            ultimately show ?thesis\n              using 2 \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> \\<open>bij_betw h WW WW'\\<close> bij_betwE h_def by fastforce\n          qed\n        next\n          assume R: ?rhs\n          then have R': \"(h a, h b) \\<in> lenlex less_than\"\n            by blast\n          then consider \"length a < length b\"\n            | \"length a = length b\" \"(h a, h b) \\<in> lex less_than\"\n            using  \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> \\<open>m > 1\\<close>\n            by (auto simp: lenlex_conv h_def len_h_seg split: if_split_asm)\n          then show ?lhs\n          proof cases\n            case 1\n            then show ?thesis\n              using omega_sum_less_iff \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> by auto\n          next\n            case 2\n            then have ab: \"a \\<in> WW_seg (length a)\" \"b \\<in> WW_seg (length a)\"\n              using \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> by (auto simp: WW_seg_def)\n            then have \"(a, b) \\<in> lenlex less_than\"\n              using bij_betwE [OF bij_h_seg] \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> R' 2\n              by (simp add: h_def h_seg_iff split: if_split_asm)\n            then show ?thesis\n              using \\<open>a \\<in> WW\\<close> \\<open>b \\<in> WW\\<close> by blast\n          qed\n        qed\n      qed\n\n      let ?fh = \"f \\<circ> image h\"\n      have \"bij_betw h WW WW'\" \n        using h unfolding iso_ll_def iso_iff2 by (fastforce simp: FR_WW FR_WW')\n      moreover have \"{..<Suc (Suc 0)} = {0,1}\"\n        by auto\n      ultimately have fh: \"?fh \\<in> [WW]\\<^bsup>2\\<^esup> \\<rightarrow> {0,1}\"\n        unfolding Pi_iff using bij_betwE f' bij_betw_nsets by (metis PiE comp_apply)\n      have \"f{x,y} = 0\" if \"x \\<in> WW'\" \"y \\<in> WW'\" \"length x = length y\" \"x \\<noteq> y\" for x y\n      proof -\n        obtain p q where \"x \\<in> W' p\" and \"y \\<in> W' q\"\n          using WW'_def \\<open>x \\<in> WW'\\<close> \\<open>y \\<in> WW'\\<close> by blast\n        then obtain n where \"{x,y} \\<in> [W' n]\\<^bsup>2\\<^esup>\"\n          using seg_W' \\<open>1 < m\\<close> \\<open>length x = length y\\<close> \\<open>x \\<noteq> y\\<close>\n          by (auto simp: WW'_def WW_seg_def subset_iff)\n        then show \"f{x,y} = 0\"\n          using f_W' by blast\n      qed\n      then have fh_eq_0_eqlen: \"?fh{x,y} = 0\" if \"x \\<in> WW\" \"y \\<in> WW\" \"length x = length y\" \"x\\<noteq>y\" for x y\n        using \\<open>bij_betw h WW WW'\\<close> that hlen by (simp add: bij_betw_iff_bijections) metis\n      have m_f_0: \"\\<exists>x\\<in>[M]\\<^bsup>2\\<^esup>. f x = 0\" if \"M \\<subseteq> WW\" \"card M = m\" for M\n      proof -\n        have \"finite M\"\n          using False m that by auto\n        with not1 [simplified, rule_format, of M] f\n        show ?thesis\n          using that \\<open>1 < m\\<close>\n          apply (simp add: Pi_iff image_subset_iff finite_ordertype_eq_card m)\n          by (metis less_2_cases nsets_mono numeral_2_eq_2 subset_iff)\n      qed\n      have m_fh_0: \"\\<exists>x\\<in>[M]\\<^bsup>2\\<^esup>. ?fh x = 0\" if \"M \\<subseteq> WW\" \"card M = m\" for M\n      proof -\n        have \"h ` M \\<subseteq> WW\"\n          using \\<open>WW' \\<subseteq> WW\\<close> \\<open>bij_betw h WW WW'\\<close> bij_betwE that(1) by fastforce\n        moreover have \"card (h ` M) = m\"\n          by (metis \\<open>bij_betw h WW WW'\\<close> bij_betw_def bij_betw_subset card_image that)\n        ultimately have \"\\<exists>x \\<in> [h ` M]\\<^bsup>2\\<^esup>. f x = 0\"\n          by (metis m_f_0)\n        then obtain Y where Y: \"f (h ` Y) = 0\" \"Y \\<subseteq> M\" and \"finite (h ` Y)\" \"card (h ` Y) = 2\"\n          by (auto simp: nsets_def subset_image_iff)\n        then have \"card Y = 2\"\n          using \\<open>bij_betw h WW WW'\\<close> \\<open>M \\<subseteq> WW\\<close>\n          by (metis bij_betw_def card_image inj_on_subset)\n        with Y card.infinite[of Y] show ?thesis\n          by (auto simp: nsets_def)\n      qed\n\n      obtain N j where \"infinite N\"\n        and N: \"\\<And>k u. \\<lbrakk>k > 0; u \\<in> [WW]\\<^bsup>2\\<^esup>; Form k u; [enum N k] < inter_scheme k u; List.set (inter_scheme k u) \\<subseteq> N\\<rbrakk> \\<Longrightarrow> ?fh u = j k\"\n        using lemma_3_6 [OF fh] by blast\n\n      have infN': \"infinite (enum N ` {k<..})\" for k\n        by (simp add: \\<open>infinite N\\<close> enum_works finite_image_iff infinite_Ioi strict_mono_imp_inj_on)\n      have j_0: \"j k = 0\" if \"k>0\" for k\n      proof -\n        obtain M where M: \"M \\<in> [WW]\\<^bsup>m\\<^esup>\"\n                 and MF: \"\\<And>u. u \\<in> [M]\\<^bsup>2\\<^esup> \\<Longrightarrow> Form k u\"\n                 and Mi: \"\\<And>u. u \\<in> [M]\\<^bsup>2\\<^esup> \\<Longrightarrow> List.set (inter_scheme k u) \\<subseteq> enum N ` {k<..}\"\n          using lemma_3_7 [OF infN' \\<open>k > 0\\<close>] by metis\n        obtain u where u: \"u \\<in> [M]\\<^bsup>2\\<^esup>\" \"?fh u = 0\"\n          using m_fh_0 [of M] M [unfolded nsets_def] by force\n        moreover\n        have \\<section>: \"Form k u\" \"List.set (inter_scheme k u) \\<subseteq> enum N ` {k<..}\"\n          by (simp_all add: MF Mi \\<open>u \\<in> [M]\\<^bsup>2\\<^esup>\\<close>)\n        then have \"hd (inter_scheme k u) \\<in> enum N ` {k<..}\"\n          using hd_in_set inter_scheme_simple that by blast\n        then have \"[enum N k] < inter_scheme k u\"\n          using strict_mono_enum [OF \\<open>infinite N\\<close>] by (auto simp: less_list_def strict_mono_def)\n        moreover have \"u \\<in> [WW]\\<^bsup>2\\<^esup>\"\n          using M u by (auto simp: nsets_def)\n        moreover have \"enum N ` {k<..} \\<subseteq> N\"\n          using \\<open>infinite N\\<close> range_enum by auto\n        ultimately show ?thesis\n          using N \\<section> that by auto\n      qed\n      obtain X where \"X \\<subseteq> WW\" and otX: \"ordertype X (lenlex less_than) = \\<omega>\\<up>\\<omega>\"\n            and X: \"\\<And>u. u \\<in> [X]\\<^bsup>2\\<^esup> \\<Longrightarrow>\n                   \\<exists>l. Form l u \\<and> (l > 0 \\<longrightarrow> [enum N l] < inter_scheme l u \\<and> List.set (inter_scheme l u) \\<subseteq> N)\"\n        using lemma_3_8 [OF \\<open>infinite N\\<close>] ot' by blast\n      have 0: \"?fh ` [X]\\<^bsup>2\\<^esup> \\<subseteq> {0}\"\n      proof clarsimp\n        fix u\n        assume u: \"u \\<in> [X]\\<^bsup>2\\<^esup>\"\n        obtain l where \"Form l u\" and l: \"l > 0 \\<longrightarrow> [enum N l] < inter_scheme l u \\<and> List.set (inter_scheme l u) \\<subseteq> N\"\n          using u X by blast\n        have \"?fh u = 0\"\n        proof (cases \"l = 0\")\n          case True\n          then show ?thesis\n            by (metis Form_0_cases_raw \\<open>Form l u\\<close> \\<open>X \\<subseteq> WW\\<close> doubleton_in_nsets_2 fh_eq_0_eqlen subset_iff u)\n        next\n          case False\n          then obtain \"[enum N l] < inter_scheme l u\" \"List.set (inter_scheme l u) \\<subseteq> N\" \"j l = 0\"\n            using Nat.neq0_conv j_0 l by blast\n          with False show ?thesis\n            using \\<open>X \\<subseteq> WW\\<close> N inter_scheme \\<open>Form l u\\<close> doubleton_in_nsets_2 u by (auto simp: nsets_def)\n        qed\n        then show \"f (h ` u) = 0\"\n          by auto\n      qed\n      show ?P0\n      proof (intro exI conjI)\n        show \"h ` X \\<subseteq> WW\"\n          using \\<open>WW' \\<subseteq> WW\\<close> \\<open>X \\<subseteq> WW\\<close> \\<open>bij_betw h WW WW'\\<close> bij_betw_imp_surj_on by fastforce\n        show \"ordertype (h ` X) (lenlex less_than) = \\<omega> \\<up> \\<omega>\"\n        proof (subst ordertype_inc_eq)\n          show \"(h x, h y) \\<in> lenlex less_than\"\n            if \"x \\<in> X\" \"y \\<in> X\" \"(x, y) \\<in> lenlex less_than\" for x y\n            using that h \\<open>X \\<subseteq> WW\\<close> by (auto simp: FR_WW FR_WW' iso_iff2 iso_ll_def)\n        qed (use otX in auto)\n        show \"f ` [h ` X]\\<^bsup>2\\<^esup> \\<subseteq> {0}\"\n        proof (clarsimp simp: image_subset_iff nsets_def)\n          fix Y\n          assume \"Y \\<subseteq> h ` X\" and \"finite Y\" and \"card Y = 2\"\n          have \"inv_into WW h ` Y \\<subseteq> X\"\n            using \\<open>X \\<subseteq> WW\\<close> \\<open>Y \\<subseteq> h ` X\\<close> \\<open>bij_betw h WW WW'\\<close> bij_betw_inv_into_LEFT by blast\n          moreover have \"finite (inv_into WW h ` Y)\"\n            using \\<open>finite Y\\<close> by blast\n          moreover have \"card (inv_into WW h ` Y) = 2\"\n            by (metis \\<open>X \\<subseteq> WW\\<close> \\<open>Y \\<subseteq> h ` X\\<close> \\<open>card Y = 2\\<close> card_image inj_on_inv_into subset_image_iff subset_trans)\n          ultimately have \"f (h ` inv_into WW h ` Y) = 0\"\n            using 0 by (auto simp: image_subset_iff nsets_def)\n          then show \"f Y = 0\"\n            by (metis \\<open>X \\<subseteq> WW\\<close> \\<open>Y \\<subseteq> h ` X\\<close> image_inv_into_cancel image_mono order_trans)\n        qed\n      qed\n    qed\n    then show \"\\<exists>i<Suc (Suc 0). \\<exists>H\\<subseteq>WW. ordertype H ?R = [\\<omega>\\<up>\\<omega>, \\<alpha>] ! i \\<and> f ` [H]\\<^bsup>2\\<^esup> \\<subseteq> {i}\"\n      by (metis One_nat_def lessI nth_Cons_0 nth_Cons_Suc zero_less_Suc)\n  qed\nqed\n\ntext \\<open>Theorem 3.1 of Jean A. Larson, ibid.\\<close>\ntheorem partition_\\<omega>\\<omega>: \"\\<alpha> \\<in> elts \\<omega> \\<Longrightarrow> partn_lst_VWF (\\<omega>\\<up>\\<omega>) [\\<omega>\\<up>\\<omega>,\\<alpha>] 2\"\n  using partn_lst_imp_partn_lst_VWF_eq [OF partition_\\<omega>\\<omega>_aux] ordertype_WW by auto\n\nend\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Ordinal_Partitions/Omega_Omega.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7946122276163311}}
{"text": "(*  Title:      HOL/Library/Formal_Power_Series.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection \\<open>A formalization of formal power series\\<close>\n\ntheory Formal_Power_Series\nimports Complex_Main \"~~/src/HOL/Number_Theory/Euclidean_Algorithm\"\nbegin\n\n\nsubsection \\<open>The type of formal power series\\<close>\n\ntypedef 'a fps = \"{f :: nat \\<Rightarrow> 'a. True}\"\n  morphisms fps_nth Abs_fps\n  by simp\n\nnotation fps_nth (infixl \"$\" 75)\n\nlemma expand_fps_eq: \"p = q \\<longleftrightarrow> (\\<forall>n. p $ n = q $ n)\"\n  by (simp add: fps_nth_inject [symmetric] fun_eq_iff)\n\nlemma fps_ext: \"(\\<And>n. p $ n = q $ n) \\<Longrightarrow> p = q\"\n  by (simp add: expand_fps_eq)\n\nlemma fps_nth_Abs_fps [simp]: \"Abs_fps f $ n = f n\"\n  by (simp add: Abs_fps_inverse)\n\ntext \\<open>Definition of the basic elements 0 and 1 and the basic operations of addition,\n  negation and multiplication.\\<close>\n\ninstantiation fps :: (zero) zero\nbegin\n  definition fps_zero_def: \"0 = Abs_fps (\\<lambda>n. 0)\"\n  instance ..\nend\n\nlemma fps_zero_nth [simp]: \"0 $ n = 0\"\n  unfolding fps_zero_def by simp\n\ninstantiation fps :: (\"{one, zero}\") one\nbegin\n  definition fps_one_def: \"1 = Abs_fps (\\<lambda>n. if n = 0 then 1 else 0)\"\n  instance ..\nend\n\nlemma fps_one_nth [simp]: \"1 $ n = (if n = 0 then 1 else 0)\"\n  unfolding fps_one_def by simp\n\ninstantiation fps :: (plus) plus\nbegin\n  definition fps_plus_def: \"op + = (\\<lambda>f g. Abs_fps (\\<lambda>n. f $ n + g $ n))\"\n  instance ..\nend\n\nlemma fps_add_nth [simp]: \"(f + g) $ n = f $ n + g $ n\"\n  unfolding fps_plus_def by simp\n\ninstantiation fps :: (minus) minus\nbegin\n  definition fps_minus_def: \"op - = (\\<lambda>f g. Abs_fps (\\<lambda>n. f $ n - g $ n))\"\n  instance ..\nend\n\nlemma fps_sub_nth [simp]: \"(f - g) $ n = f $ n - g $ n\"\n  unfolding fps_minus_def by simp\n\ninstantiation fps :: (uminus) uminus\nbegin\n  definition fps_uminus_def: \"uminus = (\\<lambda>f. Abs_fps (\\<lambda>n. - (f $ n)))\"\n  instance ..\nend\n\nlemma fps_neg_nth [simp]: \"(- f) $ n = - (f $ n)\"\n  unfolding fps_uminus_def by simp\n\ninstantiation fps :: (\"{comm_monoid_add, times}\") times\nbegin\n  definition fps_times_def: \"op * = (\\<lambda>f g. Abs_fps (\\<lambda>n. \\<Sum>i=0..n. f $ i * g $ (n - i)))\"\n  instance ..\nend\n\nlemma fps_mult_nth: \"(f * g) $ n = (\\<Sum>i=0..n. f$i * g$(n - i))\"\n  unfolding fps_times_def by simp\n\nlemma fps_mult_nth_0 [simp]: \"(f * g) $ 0 = f $ 0 * g $ 0\"\n  unfolding fps_times_def by simp\n\ndeclare atLeastAtMost_iff [presburger]\ndeclare Bex_def [presburger]\ndeclare Ball_def [presburger]\n\nlemma mult_delta_left:\n  fixes x y :: \"'a::mult_zero\"\n  shows \"(if b then x else 0) * y = (if b then x * y else 0)\"\n  by simp\n\nlemma mult_delta_right:\n  fixes x y :: \"'a::mult_zero\"\n  shows \"x * (if b then y else 0) = (if b then x * y else 0)\"\n  by simp\n\nlemma cond_value_iff: \"f (if b then x else y) = (if b then f x else f y)\"\n  by auto\n\nlemma cond_application_beta: \"(if b then f else g) x = (if b then f x else g x)\"\n  by auto\n\n\nsubsection \\<open>Formal power series form a commutative ring with unity, if the range of sequences\n  they represent is a commutative ring with unity\\<close>\n\ninstance fps :: (semigroup_add) semigroup_add\nproof\n  fix a b c :: \"'a fps\"\n  show \"a + b + c = a + (b + c)\"\n    by (simp add: fps_ext add.assoc)\nqed\n\ninstance fps :: (ab_semigroup_add) ab_semigroup_add\nproof\n  fix a b :: \"'a fps\"\n  show \"a + b = b + a\"\n    by (simp add: fps_ext add.commute)\nqed\n\nlemma fps_mult_assoc_lemma:\n  fixes k :: nat\n    and f :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a::comm_monoid_add\"\n  shows \"(\\<Sum>j=0..k. \\<Sum>i=0..j. f i (j - i) (n - j)) =\n         (\\<Sum>j=0..k. \\<Sum>i=0..k - j. f j i (n - j - i))\"\n  by (induct k) (simp_all add: Suc_diff_le sum.distrib add.assoc)\n\ninstance fps :: (semiring_0) semigroup_mult\nproof\n  fix a b c :: \"'a fps\"\n  show \"(a * b) * c = a * (b * c)\"\n  proof (rule fps_ext)\n    fix n :: nat\n    have \"(\\<Sum>j=0..n. \\<Sum>i=0..j. a$i * b$(j - i) * c$(n - j)) =\n          (\\<Sum>j=0..n. \\<Sum>i=0..n - j. a$j * b$i * c$(n - j - i))\"\n      by (rule fps_mult_assoc_lemma)\n    then show \"((a * b) * c) $ n = (a * (b * c)) $ n\"\n      by (simp add: fps_mult_nth sum_distrib_left sum_distrib_right mult.assoc)\n  qed\nqed\n\nlemma fps_mult_commute_lemma:\n  fixes n :: nat\n    and f :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a::comm_monoid_add\"\n  shows \"(\\<Sum>i=0..n. f i (n - i)) = (\\<Sum>i=0..n. f (n - i) i)\"\n  by (rule sum.reindex_bij_witness[where i=\"op - n\" and j=\"op - n\"]) auto\n\ninstance fps :: (comm_semiring_0) ab_semigroup_mult\nproof\n  fix a b :: \"'a fps\"\n  show \"a * b = b * a\"\n  proof (rule fps_ext)\n    fix n :: nat\n    have \"(\\<Sum>i=0..n. a$i * b$(n - i)) = (\\<Sum>i=0..n. a$(n - i) * b$i)\"\n      by (rule fps_mult_commute_lemma)\n    then show \"(a * b) $ n = (b * a) $ n\"\n      by (simp add: fps_mult_nth mult.commute)\n  qed\nqed\n\ninstance fps :: (monoid_add) monoid_add\nproof\n  fix a :: \"'a fps\"\n  show \"0 + a = a\" by (simp add: fps_ext)\n  show \"a + 0 = a\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (comm_monoid_add) comm_monoid_add\nproof\n  fix a :: \"'a fps\"\n  show \"0 + a = a\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (semiring_1) monoid_mult\nproof\n  fix a :: \"'a fps\"\n  show \"1 * a = a\"\n    by (simp add: fps_ext fps_mult_nth mult_delta_left sum.delta)\n  show \"a * 1 = a\"\n    by (simp add: fps_ext fps_mult_nth mult_delta_right sum.delta')\nqed\n\ninstance fps :: (cancel_semigroup_add) cancel_semigroup_add\nproof\n  fix a b c :: \"'a fps\"\n  show \"b = c\" if \"a + b = a + c\"\n    using that by (simp add: expand_fps_eq)\n  show \"b = c\" if \"b + a = c + a\"\n    using that by (simp add: expand_fps_eq)\nqed\n\ninstance fps :: (cancel_ab_semigroup_add) cancel_ab_semigroup_add\nproof\n  fix a b c :: \"'a fps\"\n  show \"a + b - a = b\"\n    by (simp add: expand_fps_eq)\n  show \"a - b - c = a - (b + c)\"\n    by (simp add: expand_fps_eq diff_diff_eq)\nqed\n\ninstance fps :: (cancel_comm_monoid_add) cancel_comm_monoid_add ..\n\ninstance fps :: (group_add) group_add\nproof\n  fix a b :: \"'a fps\"\n  show \"- a + a = 0\" by (simp add: fps_ext)\n  show \"a + - b = a - b\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (ab_group_add) ab_group_add\nproof\n  fix a b :: \"'a fps\"\n  show \"- a + a = 0\" by (simp add: fps_ext)\n  show \"a - b = a + - b\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (zero_neq_one) zero_neq_one\n  by standard (simp add: expand_fps_eq)\n\ninstance fps :: (semiring_0) semiring\nproof\n  fix a b c :: \"'a fps\"\n  show \"(a + b) * c = a * c + b * c\"\n    by (simp add: expand_fps_eq fps_mult_nth distrib_right sum.distrib)\n  show \"a * (b + c) = a * b + a * c\"\n    by (simp add: expand_fps_eq fps_mult_nth distrib_left sum.distrib)\nqed\n\ninstance fps :: (semiring_0) semiring_0\nproof\n  fix a :: \"'a fps\"\n  show \"0 * a = 0\"\n    by (simp add: fps_ext fps_mult_nth)\n  show \"a * 0 = 0\"\n    by (simp add: fps_ext fps_mult_nth)\nqed\n\ninstance fps :: (semiring_0_cancel) semiring_0_cancel ..\n\ninstance fps :: (semiring_1) semiring_1 ..\n\n\nsubsection \\<open>Selection of the nth power of the implicit variable in the infinite sum\\<close>\n\nlemma fps_square_nth: \"(f^2) $ n = (\\<Sum>k\\<le>n. f $ k * f $ (n - k))\"\n  by (simp add: power2_eq_square fps_mult_nth atLeast0AtMost)\n\nlemma fps_nonzero_nth: \"f \\<noteq> 0 \\<longleftrightarrow> (\\<exists> n. f $n \\<noteq> 0)\"\n  by (simp add: expand_fps_eq)\n\nlemma fps_nonzero_nth_minimal: \"f \\<noteq> 0 \\<longleftrightarrow> (\\<exists>n. f $ n \\<noteq> 0 \\<and> (\\<forall>m < n. f $ m = 0))\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  let ?n = \"LEAST n. f $ n \\<noteq> 0\"\n  show ?rhs if ?lhs\n  proof -\n    from that have \"\\<exists>n. f $ n \\<noteq> 0\"\n      by (simp add: fps_nonzero_nth)\n    then have \"f $ ?n \\<noteq> 0\"\n      by (rule LeastI_ex)\n    moreover have \"\\<forall>m<?n. f $ m = 0\"\n      by (auto dest: not_less_Least)\n    ultimately have \"f $ ?n \\<noteq> 0 \\<and> (\\<forall>m<?n. f $ m = 0)\" ..\n    then show ?thesis ..\n  qed\n  show ?lhs if ?rhs\n    using that by (auto simp add: expand_fps_eq)\nqed\n\nlemma fps_eq_iff: \"f = g \\<longleftrightarrow> (\\<forall>n. f $ n = g $n)\"\n  by (rule expand_fps_eq)\n\nlemma fps_sum_nth: \"sum f S $ n = sum (\\<lambda>k. (f k) $ n) S\"\nproof (cases \"finite S\")\n  case True\n  then show ?thesis by (induct set: finite) auto\nnext\n  case False\n  then show ?thesis by simp\nqed\n\n\nsubsection \\<open>Injection of the basic ring elements and multiplication by scalars\\<close>\n\ndefinition \"fps_const c = Abs_fps (\\<lambda>n. if n = 0 then c else 0)\"\n\nlemma fps_nth_fps_const [simp]: \"fps_const c $ n = (if n = 0 then c else 0)\"\n  unfolding fps_const_def by simp\n\nlemma fps_const_0_eq_0 [simp]: \"fps_const 0 = 0\"\n  by (simp add: fps_ext)\n\nlemma fps_const_1_eq_1 [simp]: \"fps_const 1 = 1\"\n  by (simp add: fps_ext)\n\nlemma fps_const_neg [simp]: \"- (fps_const (c::'a::ring)) = fps_const (- c)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_add [simp]: \"fps_const (c::'a::monoid_add) + fps_const d = fps_const (c + d)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_sub [simp]: \"fps_const (c::'a::group_add) - fps_const d = fps_const (c - d)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_mult[simp]: \"fps_const (c::'a::ring) * fps_const d = fps_const (c * d)\"\n  by (simp add: fps_eq_iff fps_mult_nth sum.neutral)\n\nlemma fps_const_add_left: \"fps_const (c::'a::monoid_add) + f =\n    Abs_fps (\\<lambda>n. if n = 0 then c + f$0 else f$n)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_add_right: \"f + fps_const (c::'a::monoid_add) =\n    Abs_fps (\\<lambda>n. if n = 0 then f$0 + c else f$n)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_mult_left: \"fps_const (c::'a::semiring_0) * f = Abs_fps (\\<lambda>n. c * f$n)\"\n  unfolding fps_eq_iff fps_mult_nth\n  by (simp add: fps_const_def mult_delta_left sum.delta)\n\nlemma fps_const_mult_right: \"f * fps_const (c::'a::semiring_0) = Abs_fps (\\<lambda>n. f$n * c)\"\n  unfolding fps_eq_iff fps_mult_nth\n  by (simp add: fps_const_def mult_delta_right sum.delta')\n\nlemma fps_mult_left_const_nth [simp]: \"(fps_const (c::'a::semiring_1) * f)$n = c* f$n\"\n  by (simp add: fps_mult_nth mult_delta_left sum.delta)\n\nlemma fps_mult_right_const_nth [simp]: \"(f * fps_const (c::'a::semiring_1))$n = f$n * c\"\n  by (simp add: fps_mult_nth mult_delta_right sum.delta')\n\n\nsubsection \\<open>Formal power series form an integral domain\\<close>\n\ninstance fps :: (ring) ring ..\n\ninstance fps :: (ring_1) ring_1\n  by (intro_classes, auto simp add: distrib_right)\n\ninstance fps :: (comm_ring_1) comm_ring_1\n  by (intro_classes, auto simp add: distrib_right)\n\ninstance fps :: (ring_no_zero_divisors) ring_no_zero_divisors\nproof\n  fix a b :: \"'a fps\"\n  assume \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  then obtain i j where i: \"a $ i \\<noteq> 0\" \"\\<forall>k<i. a $ k = 0\" and j: \"b $ j \\<noteq> 0\" \"\\<forall>k<j. b $ k =0\"\n    unfolding fps_nonzero_nth_minimal\n    by blast+\n  have \"(a * b) $ (i + j) = (\\<Sum>k=0..i+j. a $ k * b $ (i + j - k))\"\n    by (rule fps_mult_nth)\n  also have \"\\<dots> = (a $ i * b $ (i + j - i)) + (\\<Sum>k\\<in>{0..i+j} - {i}. a $ k * b $ (i + j - k))\"\n    by (rule sum.remove) simp_all\n  also have \"(\\<Sum>k\\<in>{0..i+j}-{i}. a $ k * b $ (i + j - k)) = 0\"\n  proof (rule sum.neutral [rule_format])\n    fix k assume \"k \\<in> {0..i+j} - {i}\"\n    then have \"k < i \\<or> i+j-k < j\"\n      by auto\n    then show \"a $ k * b $ (i + j - k) = 0\"\n      using i j by auto\n  qed\n  also have \"a $ i * b $ (i + j - i) + 0 = a $ i * b $ j\"\n    by simp\n  also have \"a $ i * b $ j \\<noteq> 0\"\n    using i j by simp\n  finally have \"(a*b) $ (i+j) \\<noteq> 0\" .\n  then show \"a * b \\<noteq> 0\"\n    unfolding fps_nonzero_nth by blast\nqed\n\ninstance fps :: (ring_1_no_zero_divisors) ring_1_no_zero_divisors ..\n\ninstance fps :: (idom) idom ..\n\nlemma numeral_fps_const: \"numeral k = fps_const (numeral k)\"\n  by (induct k) (simp_all only: numeral.simps fps_const_1_eq_1\n    fps_const_add [symmetric])\n\nlemma neg_numeral_fps_const:\n  \"(- numeral k :: 'a :: ring_1 fps) = fps_const (- numeral k)\"\n  by (simp add: numeral_fps_const)\n\nlemma fps_numeral_nth: \"numeral n $ i = (if i = 0 then numeral n else 0)\"\n  by (simp add: numeral_fps_const)\n\nlemma fps_numeral_nth_0 [simp]: \"numeral n $ 0 = numeral n\"\n  by (simp add: numeral_fps_const)\n\nlemma fps_of_nat: \"fps_const (of_nat c) = of_nat c\"\n  by (induction c) (simp_all add: fps_const_add [symmetric] del: fps_const_add)\n\n\n\nsubsection \\<open>The eXtractor series X\\<close>\n\nlemma minus_one_power_iff: \"(- (1::'a::comm_ring_1)) ^ n = (if even n then 1 else - 1)\"\n  by (induct n) auto\n\ndefinition \"X = Abs_fps (\\<lambda>n. if n = 1 then 1 else 0)\"\n\nlemma X_mult_nth [simp]:\n  \"(X * (f :: 'a::semiring_1 fps)) $n = (if n = 0 then 0 else f $ (n - 1))\"\nproof (cases \"n = 0\")\n  case False\n  have \"(X * f) $n = (\\<Sum>i = 0..n. X $ i * f $ (n - i))\"\n    by (simp add: fps_mult_nth)\n  also have \"\\<dots> = f $ (n - 1)\"\n    using False by (simp add: X_def mult_delta_left sum.delta)\n  finally show ?thesis\n    using False by simp\nnext\n  case True\n  then show ?thesis\n    by (simp add: fps_mult_nth X_def)\nqed\n\nlemma X_mult_right_nth[simp]:\n  \"((a::'a::semiring_1 fps) * X) $ n = (if n = 0 then 0 else a $ (n - 1))\"\nproof -\n  have \"(a * X) $ n = (\\<Sum>i = 0..n. a $ i * (if n - i = Suc 0 then 1 else 0))\"\n    by (simp add: fps_times_def X_def)\n  also have \"\\<dots> = (\\<Sum>i = 0..n. if i = n - 1 then if n = 0 then 0 else a $ i else 0)\"\n    by (intro sum.cong) auto\n  also have \"\\<dots> = (if n = 0 then 0 else a $ (n - 1))\" by (simp add: sum.delta)\n  finally show ?thesis .\nqed\n\nlemma fps_mult_X_commute: \"X * (a :: 'a :: semiring_1 fps) = a * X\" \n  by (simp add: fps_eq_iff)\n\nlemma X_power_iff: \"X^k = Abs_fps (\\<lambda>n. if n = k then 1::'a::comm_ring_1 else 0)\"\nproof (induct k)\n  case 0\n  then show ?case by (simp add: X_def fps_eq_iff)\nnext\n  case (Suc k)\n  have \"(X^Suc k) $ m = (if m = Suc k then 1::'a else 0)\" for m\n  proof -\n    have \"(X^Suc k) $ m = (if m = 0 then 0 else (X^k) $ (m - 1))\"\n      by (simp del: One_nat_def)\n    then show ?thesis\n      using Suc.hyps by (auto cong del: if_weak_cong)\n  qed\n  then show ?case\n    by (simp add: fps_eq_iff)\nqed\n\nlemma X_nth[simp]: \"X$n = (if n = 1 then 1 else 0)\"\n  by (simp add: X_def)\n\nlemma X_power_nth[simp]: \"(X^k) $n = (if n = k then 1 else 0::'a::comm_ring_1)\"\n  by (simp add: X_power_iff)\n\nlemma X_power_mult_nth: \"(X^k * (f :: 'a::comm_ring_1 fps)) $n = (if n < k then 0 else f $ (n - k))\"\n  apply (induct k arbitrary: n)\n  apply simp\n  unfolding power_Suc mult.assoc\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma X_power_mult_right_nth:\n    \"((f :: 'a::comm_ring_1 fps) * X^k) $n = (if n < k then 0 else f $ (n - k))\"\n  by (metis X_power_mult_nth mult.commute)\n\n\nlemma X_neq_fps_const [simp]: \"(X :: 'a :: zero_neq_one fps) \\<noteq> fps_const c\"\nproof\n  assume \"(X::'a fps) = fps_const (c::'a)\"\n  hence \"X$1 = (fps_const (c::'a))$1\" by (simp only:)\n  thus False by auto\nqed\n\nlemma X_neq_zero [simp]: \"(X :: 'a :: zero_neq_one fps) \\<noteq> 0\"\n  by (simp only: fps_const_0_eq_0[symmetric] X_neq_fps_const) simp\n\nlemma X_neq_one [simp]: \"(X :: 'a :: zero_neq_one fps) \\<noteq> 1\"\n  by (simp only: fps_const_1_eq_1[symmetric] X_neq_fps_const) simp\n\nlemma X_neq_numeral [simp]: \"(X :: 'a :: {semiring_1,zero_neq_one} fps) \\<noteq> numeral c\"\n  by (simp only: numeral_fps_const X_neq_fps_const) simp\n\nlemma X_pow_eq_X_pow_iff [simp]:\n  \"(X :: ('a :: {comm_ring_1}) fps) ^ m = X ^ n \\<longleftrightarrow> m = n\"\nproof\n  assume \"(X :: 'a fps) ^ m = X ^ n\"\n  hence \"(X :: 'a fps) ^ m $ m = X ^ n $ m\" by (simp only:)\n  thus \"m = n\" by (simp split: if_split_asm)\nqed simp_all\n\n\nsubsection \\<open>Subdegrees\\<close>\n\ndefinition subdegree :: \"('a::zero) fps \\<Rightarrow> nat\" where\n  \"subdegree f = (if f = 0 then 0 else LEAST n. f$n \\<noteq> 0)\"\n\nlemma subdegreeI:\n  assumes \"f $ d \\<noteq> 0\" and \"\\<And>i. i < d \\<Longrightarrow> f $ i = 0\"\n  shows   \"subdegree f = d\"\nproof-\n  from assms(1) have \"f \\<noteq> 0\" by auto\n  moreover from assms(1) have \"(LEAST i. f $ i \\<noteq> 0) = d\"\n  proof (rule Least_equality)\n    fix e assume \"f $ e \\<noteq> 0\"\n    with assms(2) have \"\\<not>(e < d)\" by blast\n    thus \"e \\<ge> d\" by simp\n  qed\n  ultimately show ?thesis unfolding subdegree_def by simp\nqed\n\nlemma nth_subdegree_nonzero [simp,intro]: \"f \\<noteq> 0 \\<Longrightarrow> f $ subdegree f \\<noteq> 0\"\nproof-\n  assume \"f \\<noteq> 0\"\n  hence \"subdegree f = (LEAST n. f $ n \\<noteq> 0)\" by (simp add: subdegree_def)\n  also from \\<open>f \\<noteq> 0\\<close> have \"\\<exists>n. f$n \\<noteq> 0\" using fps_nonzero_nth by blast\n  from LeastI_ex[OF this] have \"f $ (LEAST n. f $ n \\<noteq> 0) \\<noteq> 0\" .\n  finally show ?thesis .\nqed\n\nlemma nth_less_subdegree_zero [dest]: \"n < subdegree f \\<Longrightarrow> f $ n = 0\"\nproof (cases \"f = 0\")\n  assume \"f \\<noteq> 0\" and less: \"n < subdegree f\"\n  note less\n  also from \\<open>f \\<noteq> 0\\<close> have \"subdegree f = (LEAST n. f $ n \\<noteq> 0)\" by (simp add: subdegree_def)\n  finally show \"f $ n = 0\" using not_less_Least by blast\nqed simp_all\n\nlemma subdegree_geI:\n  assumes \"f \\<noteq> 0\" \"\\<And>i. i < n \\<Longrightarrow> f$i = 0\"\n  shows   \"subdegree f \\<ge> n\"\nproof (rule ccontr)\n  assume \"\\<not>(subdegree f \\<ge> n)\"\n  with assms(2) have \"f $ subdegree f = 0\" by simp\n  moreover from assms(1) have \"f $ subdegree f \\<noteq> 0\" by simp\n  ultimately show False by contradiction\nqed\n\nlemma subdegree_greaterI:\n  assumes \"f \\<noteq> 0\" \"\\<And>i. i \\<le> n \\<Longrightarrow> f$i = 0\"\n  shows   \"subdegree f > n\"\nproof (rule ccontr)\n  assume \"\\<not>(subdegree f > n)\"\n  with assms(2) have \"f $ subdegree f = 0\" by simp\n  moreover from assms(1) have \"f $ subdegree f \\<noteq> 0\" by simp\n  ultimately show False by contradiction\nqed\n\nlemma subdegree_leI:\n  \"f $ n \\<noteq> 0 \\<Longrightarrow> subdegree f \\<le> n\"\n  by (rule leI) auto\n\n\nlemma subdegree_0 [simp]: \"subdegree 0 = 0\"\n  by (simp add: subdegree_def)\n\nlemma subdegree_1 [simp]: \"subdegree (1 :: ('a :: zero_neq_one) fps) = 0\"\n  by (auto intro!: subdegreeI)\n\nlemma subdegree_X [simp]: \"subdegree (X :: ('a :: zero_neq_one) fps) = 1\"\n  by (auto intro!: subdegreeI simp: X_def)\n\nlemma subdegree_fps_const [simp]: \"subdegree (fps_const c) = 0\"\n  by (cases \"c = 0\") (auto intro!: subdegreeI)\n\nlemma subdegree_numeral [simp]: \"subdegree (numeral n) = 0\"\n  by (simp add: numeral_fps_const)\n\nlemma subdegree_eq_0_iff: \"subdegree f = 0 \\<longleftrightarrow> f = 0 \\<or> f $ 0 \\<noteq> 0\"\nproof (cases \"f = 0\")\n  assume \"f \\<noteq> 0\"\n  thus ?thesis\n    using nth_subdegree_nonzero[OF \\<open>f \\<noteq> 0\\<close>] by (fastforce intro!: subdegreeI)\nqed simp_all\n\nlemma subdegree_eq_0 [simp]: \"f $ 0 \\<noteq> 0 \\<Longrightarrow> subdegree f = 0\"\n  by (simp add: subdegree_eq_0_iff)\n\nlemma nth_subdegree_mult [simp]:\n  fixes f g :: \"('a :: {mult_zero,comm_monoid_add}) fps\"\n  shows \"(f * g) $ (subdegree f + subdegree g) = f $ subdegree f * g $ subdegree g\"\nproof-\n  let ?n = \"subdegree f + subdegree g\"\n  have \"(f * g) $ ?n = (\\<Sum>i=0..?n. f$i * g$(?n-i))\"\n    by (simp add: fps_mult_nth)\n  also have \"... = (\\<Sum>i=0..?n. if i = subdegree f then f$i * g$(?n-i) else 0)\"\n  proof (intro sum.cong)\n    fix x assume x: \"x \\<in> {0..?n}\"\n    hence \"x = subdegree f \\<or> x < subdegree f \\<or> ?n - x < subdegree g\" by auto\n    thus \"f $ x * g $ (?n - x) = (if x = subdegree f then f $ x * g $ (?n - x) else 0)\"\n      by (elim disjE conjE) auto\n  qed auto\n  also have \"... = f $ subdegree f * g $ subdegree g\" by (simp add: sum.delta)\n  finally show ?thesis .\nqed\n\nlemma subdegree_mult [simp]:\n  assumes \"f \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows \"subdegree ((f :: ('a :: {ring_no_zero_divisors}) fps) * g) = subdegree f + subdegree g\"\nproof (rule subdegreeI)\n  let ?n = \"subdegree f + subdegree g\"\n  have \"(f * g) $ ?n = (\\<Sum>i=0..?n. f$i * g$(?n-i))\" by (simp add: fps_mult_nth)\n  also have \"... = (\\<Sum>i=0..?n. if i = subdegree f then f$i * g$(?n-i) else 0)\"\n  proof (intro sum.cong)\n    fix x assume x: \"x \\<in> {0..?n}\"\n    hence \"x = subdegree f \\<or> x < subdegree f \\<or> ?n - x < subdegree g\" by auto\n    thus \"f $ x * g $ (?n - x) = (if x = subdegree f then f $ x * g $ (?n - x) else 0)\"\n      by (elim disjE conjE) auto\n  qed auto\n  also have \"... = f $ subdegree f * g $ subdegree g\" by (simp add: sum.delta)\n  also from assms have \"... \\<noteq> 0\" by auto\n  finally show \"(f * g) $ (subdegree f + subdegree g) \\<noteq> 0\" .\nnext\n  fix m assume m: \"m < subdegree f + subdegree g\"\n  have \"(f * g) $ m = (\\<Sum>i=0..m. f$i * g$(m-i))\" by (simp add: fps_mult_nth)\n  also have \"... = (\\<Sum>i=0..m. 0)\"\n  proof (rule sum.cong)\n    fix i assume \"i \\<in> {0..m}\"\n    with m have \"i < subdegree f \\<or> m - i < subdegree g\" by auto\n    thus \"f$i * g$(m-i) = 0\" by (elim disjE) auto\n  qed auto\n  finally show \"(f * g) $ m = 0\" by simp\nqed\n\nlemma subdegree_power [simp]:\n  \"subdegree ((f :: ('a :: ring_1_no_zero_divisors) fps) ^ n) = n * subdegree f\"\n  by (cases \"f = 0\"; induction n) simp_all\n\nlemma subdegree_uminus [simp]:\n  \"subdegree (-(f::('a::group_add) fps)) = subdegree f\"\n  by (simp add: subdegree_def)\n\nlemma subdegree_minus_commute [simp]:\n  \"subdegree (f-(g::('a::group_add) fps)) = subdegree (g - f)\"\nproof -\n  have \"f - g = -(g - f)\" by simp\n  also have \"subdegree ... = subdegree (g - f)\" by (simp only: subdegree_uminus)\n  finally show ?thesis .\nqed\n\nlemma subdegree_add_ge:\n  assumes \"f \\<noteq> -(g :: ('a :: {group_add}) fps)\"\n  shows   \"subdegree (f + g) \\<ge> min (subdegree f) (subdegree g)\"\nproof (rule subdegree_geI)\n  from assms show \"f + g \\<noteq> 0\" by (subst (asm) eq_neg_iff_add_eq_0)\nnext\n  fix i assume \"i < min (subdegree f) (subdegree g)\"\n  hence \"f $ i = 0\" and \"g $ i = 0\" by auto\n  thus \"(f + g) $ i = 0\" by force\nqed\n\nlemma subdegree_add_eq1:\n  assumes \"f \\<noteq> 0\"\n  assumes \"subdegree f < subdegree (g :: ('a :: {group_add}) fps)\"\n  shows   \"subdegree (f + g) = subdegree f\"\nproof (rule antisym[OF subdegree_leI])\n  from assms show \"subdegree (f + g) \\<ge> subdegree f\"\n    by (intro order.trans[OF min.boundedI subdegree_add_ge]) auto\n  from assms have \"f $ subdegree f \\<noteq> 0\" \"g $ subdegree f = 0\" by auto\n  thus \"(f + g) $ subdegree f \\<noteq> 0\" by simp\nqed\n\nlemma subdegree_add_eq2:\n  assumes \"g \\<noteq> 0\"\n  assumes \"subdegree g < subdegree (f :: ('a :: {ab_group_add}) fps)\"\n  shows   \"subdegree (f + g) = subdegree g\"\n  using subdegree_add_eq1[OF assms] by (simp add: add.commute)\n\nlemma subdegree_diff_eq1:\n  assumes \"f \\<noteq> 0\"\n  assumes \"subdegree f < subdegree (g :: ('a :: {ab_group_add}) fps)\"\n  shows   \"subdegree (f - g) = subdegree f\"\n  using subdegree_add_eq1[of f \"-g\"] assms by (simp add: add.commute)\n\nlemma subdegree_diff_eq2:\n  assumes \"g \\<noteq> 0\"\n  assumes \"subdegree g < subdegree (f :: ('a :: {ab_group_add}) fps)\"\n  shows   \"subdegree (f - g) = subdegree g\"\n  using subdegree_add_eq2[of \"-g\" f] assms by (simp add: add.commute)\n\nlemma subdegree_diff_ge [simp]:\n  assumes \"f \\<noteq> (g :: ('a :: {group_add}) fps)\"\n  shows   \"subdegree (f - g) \\<ge> min (subdegree f) (subdegree g)\"\n  using assms subdegree_add_ge[of f \"-g\"] by simp\n\n\n\n\nsubsection \\<open>Shifting and slicing\\<close>\n\ndefinition fps_shift :: \"nat \\<Rightarrow> 'a fps \\<Rightarrow> 'a fps\" where\n  \"fps_shift n f = Abs_fps (\\<lambda>i. f $ (i + n))\"\n\nlemma fps_shift_nth [simp]: \"fps_shift n f $ i = f $ (i + n)\"\n  by (simp add: fps_shift_def)\n\nlemma fps_shift_0 [simp]: \"fps_shift 0 f = f\"\n  by (intro fps_ext) (simp add: fps_shift_def)\n\nlemma fps_shift_zero [simp]: \"fps_shift n 0 = 0\"\n  by (intro fps_ext) (simp add: fps_shift_def)\n\nlemma fps_shift_one: \"fps_shift n 1 = (if n = 0 then 1 else 0)\"\n  by (intro fps_ext) (simp add: fps_shift_def)\n\nlemma fps_shift_fps_const: \"fps_shift n (fps_const c) = (if n = 0 then fps_const c else 0)\"\n  by (intro fps_ext) (simp add: fps_shift_def)\n\nlemma fps_shift_numeral: \"fps_shift n (numeral c) = (if n = 0 then numeral c else 0)\"\n  by (simp add: numeral_fps_const fps_shift_fps_const)\n\nlemma fps_shift_X_power [simp]:\n  \"n \\<le> m \\<Longrightarrow> fps_shift n (X ^ m) = (X ^ (m - n) ::'a::comm_ring_1 fps)\"\n  by (intro fps_ext) (auto simp: fps_shift_def )\n\nlemma fps_shift_times_X_power:\n  \"n \\<le> subdegree f \\<Longrightarrow> fps_shift n f * X ^ n = (f :: 'a :: comm_ring_1 fps)\"\n  by (intro fps_ext) (auto simp: X_power_mult_right_nth nth_less_subdegree_zero)\n\nlemma fps_shift_times_X_power' [simp]:\n  \"fps_shift n (f * X^n) = (f :: 'a :: comm_ring_1 fps)\"\n  by (intro fps_ext) (auto simp: X_power_mult_right_nth nth_less_subdegree_zero)\n\nlemma fps_shift_times_X_power'':\n  \"m \\<le> n \\<Longrightarrow> fps_shift n (f * X^m) = fps_shift (n - m) (f :: 'a :: comm_ring_1 fps)\"\n  by (intro fps_ext) (auto simp: X_power_mult_right_nth nth_less_subdegree_zero)\n\nlemma fps_shift_subdegree [simp]:\n  \"n \\<le> subdegree f \\<Longrightarrow> subdegree (fps_shift n f) = subdegree (f :: 'a :: comm_ring_1 fps) - n\"\n  by (cases \"f = 0\") (force intro: nth_less_subdegree_zero subdegreeI)+\n\nlemma subdegree_decompose:\n  \"f = fps_shift (subdegree f) f * X ^ subdegree (f :: ('a :: comm_ring_1) fps)\"\n  by (rule fps_ext) (auto simp: X_power_mult_right_nth)\n\nlemma subdegree_decompose':\n  \"n \\<le> subdegree (f :: ('a :: comm_ring_1) fps) \\<Longrightarrow> f = fps_shift n f * X^n\"\n  by (rule fps_ext) (auto simp: X_power_mult_right_nth intro!: nth_less_subdegree_zero)\n\nlemma fps_shift_fps_shift:\n  \"fps_shift (m + n) f = fps_shift m (fps_shift n f)\"\n  by (rule fps_ext) (simp add: add_ac)\n\nlemma fps_shift_add:\n  \"fps_shift n (f + g) = fps_shift n f + fps_shift n g\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_shift_mult:\n  assumes \"n \\<le> subdegree (g :: 'b :: {comm_ring_1} fps)\"\n  shows   \"fps_shift n (h*g) = h * fps_shift n g\"\nproof -\n  from assms have \"g = fps_shift n g * X^n\" by (rule subdegree_decompose')\n  also have \"h * ... = (h * fps_shift n g) * X^n\" by simp\n  also have \"fps_shift n ... = h * fps_shift n g\" by simp\n  finally show ?thesis .\nqed\n\nlemma fps_shift_mult_right:\n  assumes \"n \\<le> subdegree (g :: 'b :: {comm_ring_1} fps)\"\n  shows   \"fps_shift n (g*h) = h * fps_shift n g\"\n  by (subst mult.commute, subst fps_shift_mult) (simp_all add: assms)\n\nlemma nth_subdegree_zero_iff [simp]: \"f $ subdegree f = 0 \\<longleftrightarrow> f = 0\"\n  by (cases \"f = 0\") auto\n\nlemma fps_shift_subdegree_zero_iff [simp]:\n  \"fps_shift (subdegree f) f = 0 \\<longleftrightarrow> f = 0\"\n  by (subst (1) nth_subdegree_zero_iff[symmetric], cases \"f = 0\")\n     (simp_all del: nth_subdegree_zero_iff)\n\n\ndefinition \"fps_cutoff n f = Abs_fps (\\<lambda>i. if i < n then f$i else 0)\"\n\nlemma fps_cutoff_nth [simp]: \"fps_cutoff n f $ i = (if i < n then f$i else 0)\"\n  unfolding fps_cutoff_def by simp\n\nlemma fps_cutoff_zero_iff: \"fps_cutoff n f = 0 \\<longleftrightarrow> (f = 0 \\<or> n \\<le> subdegree f)\"\nproof\n  assume A: \"fps_cutoff n f = 0\"\n  thus \"f = 0 \\<or> n \\<le> subdegree f\"\n  proof (cases \"f = 0\")\n    assume \"f \\<noteq> 0\"\n    with A have \"n \\<le> subdegree f\"\n      by (intro subdegree_geI) (auto simp: fps_eq_iff split: if_split_asm)\n    thus ?thesis ..\n  qed simp\nqed (auto simp: fps_eq_iff intro: nth_less_subdegree_zero)\n\nlemma fps_cutoff_0 [simp]: \"fps_cutoff 0 f = 0\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_cutoff_zero [simp]: \"fps_cutoff n 0 = 0\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_cutoff_one: \"fps_cutoff n 1 = (if n = 0 then 0 else 1)\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_cutoff_fps_const: \"fps_cutoff n (fps_const c) = (if n = 0 then 0 else fps_const c)\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_cutoff_numeral: \"fps_cutoff n (numeral c) = (if n = 0 then 0 else numeral c)\"\n  by (simp add: numeral_fps_const fps_cutoff_fps_const)\n\nlemma fps_shift_cutoff:\n  \"fps_shift n (f :: ('a :: comm_ring_1) fps) * X^n + fps_cutoff n f = f\"\n  by (simp add: fps_eq_iff X_power_mult_right_nth)\n\n\nsubsection \\<open>Formal Power series form a metric space\\<close>\n\ndefinition (in dist) \"ball x r = {y. dist y x < r}\"\n\ninstantiation fps :: (comm_ring_1) dist\nbegin\n\ndefinition\n  dist_fps_def: \"dist (a :: 'a fps) b = (if a = b then 0 else inverse (2 ^ subdegree (a - b)))\"\n\nlemma dist_fps_ge0: \"dist (a :: 'a fps) b \\<ge> 0\"\n  by (simp add: dist_fps_def)\n\nlemma dist_fps_sym: \"dist (a :: 'a fps) b = dist b a\"\n  by (simp add: dist_fps_def)\n\ninstance ..\n\nend\n\ninstantiation fps :: (comm_ring_1) metric_space\nbegin\n\ndefinition uniformity_fps_def [code del]:\n  \"(uniformity :: ('a fps \\<times> 'a fps) filter) = (INF e:{0 <..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_fps_def' [code del]:\n  \"open (U :: 'a fps set) \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n\ninstance\nproof\n  show th: \"dist a b = 0 \\<longleftrightarrow> a = b\" for a b :: \"'a fps\"\n    by (simp add: dist_fps_def split: if_split_asm)\n  then have th'[simp]: \"dist a a = 0\" for a :: \"'a fps\" by simp\n\n  fix a b c :: \"'a fps\"\n  consider \"a = b\" | \"c = a \\<or> c = b\" | \"a \\<noteq> b\" \"a \\<noteq> c\" \"b \\<noteq> c\" by blast\n  then show \"dist a b \\<le> dist a c + dist b c\"\n  proof cases\n    case 1\n    then show ?thesis by (simp add: dist_fps_def)\n  next\n    case 2\n    then show ?thesis\n      by (cases \"c = a\") (simp_all add: th dist_fps_sym)\n  next\n    case neq: 3\n    have False if \"dist a b > dist a c + dist b c\"\n    proof -\n      let ?n = \"subdegree (a - b)\"\n      from neq have \"dist a b > 0\" \"dist b c > 0\" and \"dist a c > 0\" by (simp_all add: dist_fps_def)\n      with that have \"dist a b > dist a c\" and \"dist a b > dist b c\" by simp_all\n      with neq have \"?n < subdegree (a - c)\" and \"?n < subdegree (b - c)\"\n        by (simp_all add: dist_fps_def field_simps)\n      hence \"(a - c) $ ?n = 0\" and \"(b - c) $ ?n = 0\"\n        by (simp_all only: nth_less_subdegree_zero)\n      hence \"(a - b) $ ?n = 0\" by simp\n      moreover from neq have \"(a - b) $ ?n \\<noteq> 0\" by (intro nth_subdegree_nonzero) simp_all\n      ultimately show False by contradiction\n    qed\n    thus ?thesis by (auto simp add: not_le[symmetric])\n  qed\nqed (rule open_fps_def' uniformity_fps_def)+\n\nend\n\ndeclare uniformity_Abort[where 'a=\"'a :: comm_ring_1 fps\", code]\n\nlemma open_fps_def: \"open (S :: 'a::comm_ring_1 fps set) = (\\<forall>a \\<in> S. \\<exists>r. r >0 \\<and> ball a r \\<subseteq> S)\"\n  unfolding open_dist ball_def subset_eq by simp\n\ntext \\<open>The infinite sums and justification of the notation in textbooks.\\<close>\n\nlemma reals_power_lt_ex:\n  fixes x y :: real\n  assumes xp: \"x > 0\"\n    and y1: \"y > 1\"\n  shows \"\\<exists>k>0. (1/y)^k < x\"\nproof -\n  have yp: \"y > 0\"\n    using y1 by simp\n  from reals_Archimedean2[of \"max 0 (- log y x) + 1\"]\n  obtain k :: nat where k: \"real k > max 0 (- log y x) + 1\"\n    by blast\n  from k have kp: \"k > 0\"\n    by simp\n  from k have \"real k > - log y x\"\n    by simp\n  then have \"ln y * real k > - ln x\"\n    unfolding log_def\n    using ln_gt_zero_iff[OF yp] y1\n    by (simp add: minus_divide_left field_simps del: minus_divide_left[symmetric])\n  then have \"ln y * real k + ln x > 0\"\n    by simp\n  then have \"exp (real k * ln y + ln x) > exp 0\"\n    by (simp add: ac_simps)\n  then have \"y ^ k * x > 1\"\n    unfolding exp_zero exp_add exp_real_of_nat_mult exp_ln [OF xp] exp_ln [OF yp]\n    by simp\n  then have \"x > (1 / y)^k\" using yp\n    by (simp add: field_simps)\n  then show ?thesis\n    using kp by blast\nqed\n\nlemma fps_sum_rep_nth: \"(sum (\\<lambda>i. fps_const(a$i)*X^i) {0..m})$n =\n    (if n \\<le> m then a$n else 0::'a::comm_ring_1)\"\n  apply (auto simp add: fps_sum_nth cond_value_iff cong del: if_weak_cong)\n  apply (simp add: sum.delta')\n  done\n\nlemma fps_notation: \"(\\<lambda>n. sum (\\<lambda>i. fps_const(a$i) * X^i) {0..n}) \\<longlonglongrightarrow> a\"\n  (is \"?s \\<longlonglongrightarrow> a\")\nproof -\n  have \"\\<exists>n0. \\<forall>n \\<ge> n0. dist (?s n) a < r\" if \"r > 0\" for r\n  proof -\n    obtain n0 where n0: \"(1/2)^n0 < r\" \"n0 > 0\"\n      using reals_power_lt_ex[OF \\<open>r > 0\\<close>, of 2] by auto\n    show ?thesis\n    proof -\n      have \"dist (?s n) a < r\" if nn0: \"n \\<ge> n0\" for n\n      proof -\n        from that have thnn0: \"(1/2)^n \\<le> (1/2 :: real)^n0\"\n          by (simp add: divide_simps)\n        show ?thesis\n        proof (cases \"?s n = a\")\n          case True\n          then show ?thesis\n            unfolding dist_eq_0_iff[of \"?s n\" a, symmetric]\n            using \\<open>r > 0\\<close> by (simp del: dist_eq_0_iff)\n        next\n          case False\n          from False have dth: \"dist (?s n) a = (1/2)^subdegree (?s n - a)\"\n            by (simp add: dist_fps_def field_simps)\n          from False have kn: \"subdegree (?s n - a) > n\"\n            by (intro subdegree_greaterI) (simp_all add: fps_sum_rep_nth)\n          then have \"dist (?s n) a < (1/2)^n\"\n            by (simp add: field_simps dist_fps_def)\n          also have \"\\<dots> \\<le> (1/2)^n0\"\n            using nn0 by (simp add: divide_simps)\n          also have \"\\<dots> < r\"\n            using n0 by simp\n          finally show ?thesis .\n        qed\n      qed\n      then show ?thesis by blast\n    qed\n  qed\n  then show ?thesis\n    unfolding lim_sequentially by blast\nqed\n\n\nsubsection \\<open>Inverses of formal power series\\<close>\n\ndeclare sum.cong[fundef_cong]\n\ninstantiation fps :: (\"{comm_monoid_add,inverse,times,uminus}\") inverse\nbegin\n\nfun natfun_inverse:: \"'a fps \\<Rightarrow> nat \\<Rightarrow> 'a\"\nwhere\n  \"natfun_inverse f 0 = inverse (f$0)\"\n| \"natfun_inverse f n = - inverse (f$0) * sum (\\<lambda>i. f$i * natfun_inverse f (n - i)) {1..n}\"\n\ndefinition fps_inverse_def: \"inverse f = (if f $ 0 = 0 then 0 else Abs_fps (natfun_inverse f))\"\n\ndefinition fps_divide_def:\n  \"f div g = (if g = 0 then 0 else\n     let n = subdegree g; h = fps_shift n g\n     in  fps_shift n (f * inverse h))\"\n\ninstance ..\n\nend\n\nlemma fps_inverse_zero [simp]:\n  \"inverse (0 :: 'a::{comm_monoid_add,inverse,times,uminus} fps) = 0\"\n  by (simp add: fps_ext fps_inverse_def)\n\nlemma fps_inverse_one [simp]: \"inverse (1 :: 'a::{division_ring,zero_neq_one} fps) = 1\"\n  apply (auto simp add: expand_fps_eq fps_inverse_def)\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma inverse_mult_eq_1 [intro]:\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n  shows \"inverse f * f = 1\"\nproof -\n  have c: \"inverse f * f = f * inverse f\"\n    by (simp add: mult.commute)\n  from f0 have ifn: \"\\<And>n. inverse f $ n = natfun_inverse f n\"\n    by (simp add: fps_inverse_def)\n  from f0 have th0: \"(inverse f * f) $ 0 = 1\"\n    by (simp add: fps_mult_nth fps_inverse_def)\n  have \"(inverse f * f)$n = 0\" if np: \"n > 0\" for n\n  proof -\n    from np have eq: \"{0..n} = {0} \\<union> {1 .. n}\"\n      by auto\n    have d: \"{0} \\<inter> {1 .. n} = {}\"\n      by auto\n    from f0 np have th0: \"- (inverse f $ n) =\n      (sum (\\<lambda>i. f$i * natfun_inverse f (n - i)) {1..n}) / (f$0)\"\n      by (cases n) (simp_all add: divide_inverse fps_inverse_def)\n    from th0[symmetric, unfolded nonzero_divide_eq_eq[OF f0]]\n    have th1: \"sum (\\<lambda>i. f$i * natfun_inverse f (n - i)) {1..n} = - (f$0) * (inverse f)$n\"\n      by (simp add: field_simps)\n    have \"(f * inverse f) $ n = (\\<Sum>i = 0..n. f $i * natfun_inverse f (n - i))\"\n      unfolding fps_mult_nth ifn ..\n    also have \"\\<dots> = f$0 * natfun_inverse f n + (\\<Sum>i = 1..n. f$i * natfun_inverse f (n-i))\"\n      by (simp add: eq)\n    also have \"\\<dots> = 0\"\n      unfolding th1 ifn by simp\n    finally show ?thesis unfolding c .\n  qed\n  with th0 show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\nlemma fps_inverse_0_iff[simp]: \"(inverse f) $ 0 = (0::'a::division_ring) \\<longleftrightarrow> f $ 0 = 0\"\n  by (simp add: fps_inverse_def nonzero_imp_inverse_nonzero)\n\nlemma fps_inverse_nth_0 [simp]: \"inverse f $ 0 = inverse (f $ 0 :: 'a :: division_ring)\"\n  by (simp add: fps_inverse_def)\n\nlemma fps_inverse_eq_0_iff[simp]: \"inverse f = (0:: ('a::division_ring) fps) \\<longleftrightarrow> f $ 0 = 0\"\nproof\n  assume A: \"inverse f = 0\"\n  have \"0 = inverse f $ 0\" by (subst A) simp\n  thus \"f $ 0 = 0\" by simp\nqed (simp add: fps_inverse_def)\n\nlemma fps_inverse_idempotent[intro, simp]:\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n  shows \"inverse (inverse f) = f\"\nproof -\n  from f0 have if0: \"inverse f $ 0 \\<noteq> 0\" by simp\n  from inverse_mult_eq_1[OF f0] inverse_mult_eq_1[OF if0]\n  have \"inverse f * f = inverse f * inverse (inverse f)\"\n    by (simp add: ac_simps)\n  then show ?thesis\n    using f0 unfolding mult_cancel_left by simp\nqed\n\nlemma fps_inverse_unique:\n  assumes fg: \"(f :: 'a :: field fps) * g = 1\"\n  shows   \"inverse f = g\"\nproof -\n  have f0: \"f $ 0 \\<noteq> 0\"\n  proof\n    assume \"f $ 0 = 0\"\n    hence \"0 = (f * g) $ 0\" by simp\n    also from fg have \"(f * g) $ 0 = 1\" by simp\n    finally show False by simp\n  qed\n  from inverse_mult_eq_1[OF this] fg\n  have th0: \"inverse f * f = g * f\"\n    by (simp add: ac_simps)\n  then show ?thesis\n    using f0\n    unfolding mult_cancel_right\n    by (auto simp add: expand_fps_eq)\nqed\n\nlemma fps_inverse_eq_0: \"f$0 = 0 \\<Longrightarrow> inverse (f :: 'a :: division_ring fps) = 0\"\n  by simp\n  \nlemma sum_zero_lemma:\n  fixes n::nat\n  assumes \"0 < n\"\n  shows \"(\\<Sum>i = 0..n. if n = i then 1 else if n - i = 1 then - 1 else 0) = (0::'a::field)\"\nproof -\n  let ?f = \"\\<lambda>i. if n = i then 1 else if n - i = 1 then - 1 else 0\"\n  let ?g = \"\\<lambda>i. if i = n then 1 else if i = n - 1 then - 1 else 0\"\n  let ?h = \"\\<lambda>i. if i=n - 1 then - 1 else 0\"\n  have th1: \"sum ?f {0..n} = sum ?g {0..n}\"\n    by (rule sum.cong) auto\n  have th2: \"sum ?g {0..n - 1} = sum ?h {0..n - 1}\"\n    apply (rule sum.cong)\n    using assms\n    apply auto\n    done\n  have eq: \"{0 .. n} = {0.. n - 1} \\<union> {n}\"\n    by auto\n  from assms have d: \"{0.. n - 1} \\<inter> {n} = {}\"\n    by auto\n  have f: \"finite {0.. n - 1}\" \"finite {n}\"\n    by auto\n  show ?thesis\n    unfolding th1\n    apply (simp add: sum.union_disjoint[OF f d, unfolded eq[symmetric]] del: One_nat_def)\n    unfolding th2\n    apply (simp add: sum.delta)\n    done\nqed\n\nlemma fps_inverse_mult: \"inverse (f * g :: 'a::field fps) = inverse f * inverse g\"\nproof (cases \"f$0 = 0 \\<or> g$0 = 0\")\n  assume \"\\<not>(f$0 = 0 \\<or> g$0 = 0)\"\n  hence [simp]: \"f$0 \\<noteq> 0\" \"g$0 \\<noteq> 0\" by simp_all\n  show ?thesis\n  proof (rule fps_inverse_unique)\n    have \"f * g * (inverse f * inverse g) = (inverse f * f) * (inverse g * g)\" by simp\n    also have \"... = 1\" by (subst (1 2) inverse_mult_eq_1) simp_all\n    finally show \"f * g * (inverse f * inverse g) = 1\" .\n  qed\nnext\n  assume A: \"f$0 = 0 \\<or> g$0 = 0\"\n  hence \"inverse (f * g) = 0\" by simp\n  also from A have \"... = inverse f * inverse g\" by auto\n  finally show \"inverse (f * g) = inverse f * inverse g\" .\nqed\n\n\nlemma fps_inverse_gp: \"inverse (Abs_fps(\\<lambda>n. (1::'a::field))) =\n    Abs_fps (\\<lambda>n. if n= 0 then 1 else if n=1 then - 1 else 0)\"\n  apply (rule fps_inverse_unique)\n  apply (simp_all add: fps_eq_iff fps_mult_nth sum_zero_lemma)\n  done\n\nlemma subdegree_inverse [simp]: \"subdegree (inverse (f::'a::field fps)) = 0\"\nproof (cases \"f$0 = 0\")\n  assume nz: \"f$0 \\<noteq> 0\"\n  hence \"subdegree (inverse f) + subdegree f = subdegree (inverse f * f)\"\n    by (subst subdegree_mult) auto\n  also from nz have \"subdegree f = 0\" by (simp add: subdegree_eq_0_iff)\n  also from nz have \"inverse f * f = 1\" by (rule inverse_mult_eq_1)\n  finally show \"subdegree (inverse f) = 0\" by simp\nqed (simp_all add: fps_inverse_def)\n\nlemma fps_is_unit_iff [simp]: \"(f :: 'a :: field fps) dvd 1 \\<longleftrightarrow> f $ 0 \\<noteq> 0\"\nproof\n  assume \"f dvd 1\"\n  then obtain g where \"1 = f * g\" by (elim dvdE)\n  from this[symmetric] have \"(f*g) $ 0 = 1\" by simp\n  thus \"f $ 0 \\<noteq> 0\" by auto\nnext\n  assume A: \"f $ 0 \\<noteq> 0\"\n  thus \"f dvd 1\" by (simp add: inverse_mult_eq_1[OF A, symmetric])\nqed\n\nlemma subdegree_eq_0' [simp]: \"(f :: 'a :: field fps) dvd 1 \\<Longrightarrow> subdegree f = 0\"\n  by simp\n\nlemma fps_unit_dvd [simp]: \"(f $ 0 :: 'a :: field) \\<noteq> 0 \\<Longrightarrow> f dvd g\"\n  by (rule dvd_trans, subst fps_is_unit_iff) simp_all\n\n\n\ninstantiation fps :: (field) ring_div\nbegin\n\ndefinition fps_mod_def:\n  \"f mod g = (if g = 0 then f else\n     let n = subdegree g; h = fps_shift n g\n     in  fps_cutoff n (f * inverse h) * h)\"\n\nlemma fps_mod_eq_zero:\n  assumes \"g \\<noteq> 0\" and \"subdegree f \\<ge> subdegree g\"\n  shows   \"f mod g = 0\"\n  using assms by (cases \"f = 0\") (auto simp: fps_cutoff_zero_iff fps_mod_def Let_def)\n\nlemma fps_times_divide_eq:\n  assumes \"g \\<noteq> 0\" and \"subdegree f \\<ge> subdegree (g :: 'a fps)\"\n  shows   \"f div g * g = f\"\nproof (cases \"f = 0\")\n  assume nz: \"f \\<noteq> 0\"\n  define n where \"n = subdegree g\"\n  define h where \"h = fps_shift n g\"\n  from assms have [simp]: \"h $ 0 \\<noteq> 0\" unfolding h_def by (simp add: n_def)\n\n  from assms nz have \"f div g * g = fps_shift n (f * inverse h) * g\"\n    by (simp add: fps_divide_def Let_def h_def n_def)\n  also have \"... = fps_shift n (f * inverse h) * X^n * h\" unfolding h_def n_def\n    by (subst subdegree_decompose[of g]) simp\n  also have \"fps_shift n (f * inverse h) * X^n = f * inverse h\"\n    by (rule fps_shift_times_X_power) (simp_all add: nz assms n_def)\n  also have \"... * h = f * (inverse h * h)\" by simp\n  also have \"inverse h * h = 1\" by (rule inverse_mult_eq_1) simp\n  finally show ?thesis by simp\nqed (simp_all add: fps_divide_def Let_def)\n\nlemma\n  assumes \"g$0 \\<noteq> 0\"\n  shows   fps_divide_unit: \"f div g = f * inverse g\" and fps_mod_unit [simp]: \"f mod g = 0\"\nproof -\n  from assms have [simp]: \"subdegree g = 0\" by (simp add: subdegree_eq_0_iff)\n  from assms show \"f div g = f * inverse g\"\n    by (auto simp: fps_divide_def Let_def subdegree_eq_0_iff)\n  from assms show \"f mod g = 0\" by (intro fps_mod_eq_zero) auto\nqed\n\ncontext\nbegin\nprivate lemma fps_divide_cancel_aux1:\n  assumes \"h$0 \\<noteq> (0 :: 'a :: field)\"\n  shows   \"(h * f) div (h * g) = f div g\"\nproof (cases \"g = 0\")\n  assume \"g \\<noteq> 0\"\n  from assms have \"h \\<noteq> 0\" by auto\n  note nz [simp] = \\<open>g \\<noteq> 0\\<close> \\<open>h \\<noteq> 0\\<close>\n  from assms have [simp]: \"subdegree h = 0\" by (simp add: subdegree_eq_0_iff)\n\n  have \"(h * f) div (h * g) =\n          fps_shift (subdegree g) (h * f * inverse (fps_shift (subdegree g) (h*g)))\"\n    by (simp add: fps_divide_def Let_def)\n  also have \"h * f * inverse (fps_shift (subdegree g) (h*g)) =\n               (inverse h * h) * f * inverse (fps_shift (subdegree g) g)\"\n    by (subst fps_shift_mult) (simp_all add: algebra_simps fps_inverse_mult)\n  also from assms have \"inverse h * h = 1\" by (rule inverse_mult_eq_1)\n  finally show \"(h * f) div (h * g) = f div g\" by (simp_all add: fps_divide_def Let_def)\nqed (simp_all add: fps_divide_def)\n\nprivate lemma fps_divide_cancel_aux2:\n  \"(f * X^m) div (g * X^m) = f div (g :: 'a :: field fps)\"\nproof (cases \"g = 0\")\n  assume [simp]: \"g \\<noteq> 0\"\n  have \"(f * X^m) div (g * X^m) =\n          fps_shift (subdegree g + m) (f*inverse (fps_shift (subdegree g + m) (g*X^m))*X^m)\"\n    by (simp add: fps_divide_def Let_def algebra_simps)\n  also have \"... = f div g\"\n    by (simp add: fps_shift_times_X_power'' fps_divide_def Let_def)\n  finally show ?thesis .\nqed (simp_all add: fps_divide_def)\n\ninstance proof\n  fix f g :: \"'a fps\"\n  define n where \"n = subdegree g\"\n  define h where \"h = fps_shift n g\"\n\n  show \"f div g * g + f mod g = f\"\n  proof (cases \"g = 0 \\<or> f = 0\")\n    assume \"\\<not>(g = 0 \\<or> f = 0)\"\n    hence nz [simp]: \"f \\<noteq> 0\" \"g \\<noteq> 0\" by simp_all\n    show ?thesis\n    proof (rule disjE[OF le_less_linear])\n      assume \"subdegree f \\<ge> subdegree g\"\n      with nz show ?thesis by (simp add: fps_mod_eq_zero fps_times_divide_eq)\n    next\n      assume \"subdegree f < subdegree g\"\n      have g_decomp: \"g = h * X^n\" unfolding h_def n_def by (rule subdegree_decompose)\n      have \"f div g * g + f mod g =\n              fps_shift n (f * inverse h) * g + fps_cutoff n (f * inverse h) * h\"\n        by (simp add: fps_mod_def fps_divide_def Let_def n_def h_def)\n      also have \"... = h * (fps_shift n (f * inverse h) * X^n + fps_cutoff n (f * inverse h))\"\n        by (subst g_decomp) (simp add: algebra_simps)\n      also have \"... = f * (inverse h * h)\"\n        by (subst fps_shift_cutoff) simp\n      also have \"inverse h * h = 1\" by (rule inverse_mult_eq_1) (simp add: h_def n_def)\n      finally show ?thesis by simp\n    qed\n  qed (auto simp: fps_mod_def fps_divide_def Let_def)\nnext\n\n  fix f g h :: \"'a fps\"\n  assume \"h \\<noteq> 0\"\n  show \"(h * f) div (h * g) = f div g\"\n  proof -\n    define m where \"m = subdegree h\"\n    define h' where \"h' = fps_shift m h\"\n    have h_decomp: \"h = h' * X ^ m\" unfolding h'_def m_def by (rule subdegree_decompose)\n    from \\<open>h \\<noteq> 0\\<close> have [simp]: \"h'$0 \\<noteq> 0\" by (simp add: h'_def m_def)\n    have \"(h * f) div (h * g) = (h' * f * X^m) div (h' * g * X^m)\"\n      by (simp add: h_decomp algebra_simps)\n    also have \"... = f div g\" by (simp add: fps_divide_cancel_aux1 fps_divide_cancel_aux2)\n    finally show ?thesis .\n  qed\n\nnext\n  fix f g h :: \"'a fps\"\n  assume [simp]: \"h \\<noteq> 0\"\n  define n h' where dfs: \"n = subdegree h\" \"h' = fps_shift n h\"\n  have \"(f + g * h) div h = fps_shift n (f * inverse h') + fps_shift n (g * (h * inverse h'))\"\n    by (simp add: fps_divide_def Let_def dfs[symmetric] algebra_simps fps_shift_add)\n  also have \"h * inverse h' = (inverse h' * h') * X^n\"\n    by (subst subdegree_decompose) (simp_all add: dfs)\n  also have \"... = X^n\" by (subst inverse_mult_eq_1) (simp_all add: dfs)\n  also have \"fps_shift n (g * X^n) = g\" by simp\n  also have \"fps_shift n (f * inverse h') = f div h\"\n    by (simp add: fps_divide_def Let_def dfs)\n  finally show \"(f + g * h) div h = g + f div h\" by simp\nqed (auto simp: fps_divide_def fps_mod_def Let_def)\n\nend\nend\n\nlemma subdegree_mod:\n  assumes \"f \\<noteq> 0\" \"subdegree f < subdegree g\"\n  shows   \"subdegree (f mod g) = subdegree f\"\nproof (cases \"f div g * g = 0\")\n  assume \"f div g * g \\<noteq> 0\"\n  hence [simp]: \"f div g \\<noteq> 0\" \"g \\<noteq> 0\" by auto\n  from div_mult_mod_eq[of f g] have \"f mod g = f - f div g * g\" by (simp add: algebra_simps)\n  also from assms have \"subdegree ... = subdegree f\"\n    by (intro subdegree_diff_eq1) simp_all\n  finally show ?thesis .\nnext\n  assume zero: \"f div g * g = 0\"\n  from div_mult_mod_eq[of f g] have \"f mod g = f - f div g * g\" by (simp add: algebra_simps)\n  also note zero\n  finally show ?thesis by simp\nqed\n\nlemma fps_divide_nth_0 [simp]: \"g $ 0 \\<noteq> 0 \\<Longrightarrow> (f div g) $ 0 = f $ 0 / (g $ 0 :: _ :: field)\"\n  by (simp add: fps_divide_unit divide_inverse)\n\n\nlemma dvd_imp_subdegree_le:\n  \"(f :: 'a :: idom fps) dvd g \\<Longrightarrow> g \\<noteq> 0 \\<Longrightarrow> subdegree f \\<le> subdegree g\"\n  by (auto elim: dvdE)\n\nlemma fps_dvd_iff:\n  assumes \"(f :: 'a :: field fps) \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows   \"f dvd g \\<longleftrightarrow> subdegree f \\<le> subdegree g\"\nproof\n  assume \"subdegree f \\<le> subdegree g\"\n  with assms have \"g mod f = 0\"\n    by (simp add: fps_mod_def Let_def fps_cutoff_zero_iff)\n  thus \"f dvd g\" by (simp add: dvd_eq_mod_eq_0)\nqed (simp add: assms dvd_imp_subdegree_le)\n\nlemma fps_shift_altdef:\n  \"fps_shift n f = (f :: 'a :: field fps) div X^n\"\n  by (simp add: fps_divide_def)\n  \nlemma fps_div_X_power_nth: \"((f :: 'a :: field fps) div X^n) $ k = f $ (k + n)\"\n  by (simp add: fps_shift_altdef [symmetric])\n\nlemma fps_div_X_nth: \"((f :: 'a :: field fps) div X) $ k = f $ Suc k\"\n  using fps_div_X_power_nth[of f 1] by simp\n\nlemma fps_const_inverse: \"inverse (fps_const (a::'a::field)) = fps_const (inverse a)\"\n  by (cases \"a \\<noteq> 0\", rule fps_inverse_unique) (auto simp: fps_eq_iff)\n\nlemma fps_const_divide: \"fps_const (x :: _ :: field) / fps_const y = fps_const (x / y)\"\n  by (cases \"y = 0\") (simp_all add: fps_divide_unit fps_const_inverse divide_inverse)\n\nlemma inverse_fps_numeral:\n  \"inverse (numeral n :: ('a :: field_char_0) fps) = fps_const (inverse (numeral n))\"\n  by (intro fps_inverse_unique fps_ext) (simp_all add: fps_numeral_nth)\n\nlemma fps_numeral_divide_divide:\n  \"x / numeral b / numeral c = (x / numeral (b * c) :: 'a :: field fps)\"\n  by (cases \"numeral b = (0::'a)\"; cases \"numeral c = (0::'a)\")\n      (simp_all add: fps_divide_unit fps_inverse_mult [symmetric] numeral_fps_const numeral_mult \n                del: numeral_mult [symmetric])\n\nlemma fps_numeral_mult_divide:\n  \"numeral b * x / numeral c = (numeral b / numeral c * x :: 'a :: field fps)\"\n  by (cases \"numeral c = (0::'a)\") (simp_all add: fps_divide_unit numeral_fps_const)\n\nlemmas fps_numeral_simps = \n  fps_numeral_divide_divide fps_numeral_mult_divide inverse_fps_numeral neg_numeral_fps_const\n\n\n\ninstantiation fps :: (field) normalization_semidom\nbegin\n\ndefinition fps_unit_factor_def [simp]:\n  \"unit_factor f = fps_shift (subdegree f) f\"\n\ndefinition fps_normalize_def [simp]:\n  \"normalize f = (if f = 0 then 0 else X ^ subdegree f)\"\n\ninstance proof\n  fix f :: \"'a fps\"\n  show \"unit_factor f * normalize f = f\"\n    by (simp add: fps_shift_times_X_power)\nnext\n  fix f g :: \"'a fps\"\n  show \"unit_factor (f * g) = unit_factor f * unit_factor g\"\n  proof (cases \"f = 0 \\<or> g = 0\")\n    assume \"\\<not>(f = 0 \\<or> g = 0)\"\n    thus \"unit_factor (f * g) = unit_factor f * unit_factor g\"\n    unfolding fps_unit_factor_def\n      by (auto simp: fps_shift_fps_shift fps_shift_mult fps_shift_mult_right)\n  qed auto\nqed auto\n\nend\n\ninstance fps :: (field) algebraic_semidom ..\n\n\nsubsection \\<open>Formal power series form a Euclidean ring\\<close>\n\ninstantiation fps :: (field) euclidean_ring\nbegin\n\ndefinition fps_euclidean_size_def:\n  \"euclidean_size f = (if f = 0 then 0 else 2 ^ subdegree f)\"\n\ninstance proof\n  fix f g :: \"'a fps\" assume [simp]: \"g \\<noteq> 0\"\n  show \"euclidean_size f \\<le> euclidean_size (f * g)\"\n    by (cases \"f = 0\") (auto simp: fps_euclidean_size_def)\n  show \"euclidean_size (f mod g) < euclidean_size g\"\n    apply (cases \"f = 0\", simp add: fps_euclidean_size_def)\n    apply (rule disjE[OF le_less_linear[of \"subdegree g\" \"subdegree f\"]])\n    apply (simp_all add: fps_mod_eq_zero fps_euclidean_size_def subdegree_mod)\n    done\nqed (simp_all add: fps_euclidean_size_def)\n\nend\n\ninstantiation fps :: (field) euclidean_ring_gcd\nbegin\ndefinition fps_gcd_def: \"(gcd :: 'a fps \\<Rightarrow> _) = gcd_eucl\"\ndefinition fps_lcm_def: \"(lcm :: 'a fps \\<Rightarrow> _) = lcm_eucl\"\ndefinition fps_Gcd_def: \"(Gcd :: 'a fps set \\<Rightarrow> _) = Gcd_eucl\"\ndefinition fps_Lcm_def: \"(Lcm :: 'a fps set \\<Rightarrow> _) = Lcm_eucl\"\ninstance by standard (simp_all add: fps_gcd_def fps_lcm_def fps_Gcd_def fps_Lcm_def)\nend\n\nlemma fps_gcd:\n  assumes [simp]: \"f \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows   \"gcd f g = X ^ min (subdegree f) (subdegree g)\"\nproof -\n  let ?m = \"min (subdegree f) (subdegree g)\"\n  show \"gcd f g = X ^ ?m\"\n  proof (rule sym, rule gcdI)\n    fix d assume \"d dvd f\" \"d dvd g\"\n    thus \"d dvd X ^ ?m\" by (cases \"d = 0\") (auto simp: fps_dvd_iff)\n  qed (simp_all add: fps_dvd_iff)\nqed\n\nlemma fps_gcd_altdef: \"gcd (f :: 'a :: field fps) g =\n  (if f = 0 \\<and> g = 0 then 0 else\n   if f = 0 then X ^ subdegree g else\n   if g = 0 then X ^ subdegree f else\n     X ^ min (subdegree f) (subdegree g))\"\n  by (simp add: fps_gcd)\n\nlemma fps_lcm:\n  assumes [simp]: \"f \\<noteq> 0\" \"g \\<noteq> 0\"\n  shows   \"lcm f g = X ^ max (subdegree f) (subdegree g)\"\nproof -\n  let ?m = \"max (subdegree f) (subdegree g)\"\n  show \"lcm f g = X ^ ?m\"\n  proof (rule sym, rule lcmI)\n    fix d assume \"f dvd d\" \"g dvd d\"\n    thus \"X ^ ?m dvd d\" by (cases \"d = 0\") (auto simp: fps_dvd_iff)\n  qed (simp_all add: fps_dvd_iff)\nqed\n\nlemma fps_lcm_altdef: \"lcm (f :: 'a :: field fps) g =\n  (if f = 0 \\<or> g = 0 then 0 else X ^ max (subdegree f) (subdegree g))\"\n  by (simp add: fps_lcm)\n\nlemma fps_Gcd:\n  assumes \"A - {0} \\<noteq> {}\"\n  shows   \"Gcd A = X ^ (INF f:A-{0}. subdegree f)\"\nproof (rule sym, rule GcdI)\n  fix f assume \"f \\<in> A\"\n  thus \"X ^ (INF f:A - {0}. subdegree f) dvd f\"\n    by (cases \"f = 0\") (auto simp: fps_dvd_iff intro!: cINF_lower)\nnext\n  fix d assume d: \"\\<And>f. f \\<in> A \\<Longrightarrow> d dvd f\"\n  from assms obtain f where \"f \\<in> A - {0}\" by auto\n  with d[of f] have [simp]: \"d \\<noteq> 0\" by auto\n  from d assms have \"subdegree d \\<le> (INF f:A-{0}. subdegree f)\"\n    by (intro cINF_greatest) (auto simp: fps_dvd_iff[symmetric])\n  with d assms show \"d dvd X ^ (INF f:A-{0}. subdegree f)\" by (simp add: fps_dvd_iff)\nqed simp_all\n\nlemma fps_Gcd_altdef: \"Gcd (A :: 'a :: field fps set) =\n  (if A \\<subseteq> {0} then 0 else X ^ (INF f:A-{0}. subdegree f))\"\n  using fps_Gcd by auto\n\nlemma fps_Lcm:\n  assumes \"A \\<noteq> {}\" \"0 \\<notin> A\" \"bdd_above (subdegree`A)\"\n  shows   \"Lcm A = X ^ (SUP f:A. subdegree f)\"\nproof (rule sym, rule LcmI)\n  fix f assume \"f \\<in> A\"\n  moreover from assms(3) have \"bdd_above (subdegree ` A)\" by auto\n  ultimately show \"f dvd X ^ (SUP f:A. subdegree f)\" using assms(2)\n    by (cases \"f = 0\") (auto simp: fps_dvd_iff intro!: cSUP_upper)\nnext\n  fix d assume d: \"\\<And>f. f \\<in> A \\<Longrightarrow> f dvd d\"\n  from assms obtain f where f: \"f \\<in> A\" \"f \\<noteq> 0\" by auto\n  show \"X ^ (SUP f:A. subdegree f) dvd d\"\n  proof (cases \"d = 0\")\n    assume \"d \\<noteq> 0\"\n    moreover from d have \"\\<And>f. f \\<in> A \\<Longrightarrow> f \\<noteq> 0 \\<Longrightarrow> f dvd d\" by blast\n    ultimately have \"subdegree d \\<ge> (SUP f:A. subdegree f)\" using assms\n      by (intro cSUP_least) (auto simp: fps_dvd_iff)\n    with \\<open>d \\<noteq> 0\\<close> show ?thesis by (simp add: fps_dvd_iff)\n  qed simp_all\nqed simp_all\n\nlemma fps_Lcm_altdef:\n  \"Lcm (A :: 'a :: field fps set) =\n     (if 0 \\<in> A \\<or> \\<not>bdd_above (subdegree`A) then 0 else\n      if A = {} then 1 else X ^ (SUP f:A. subdegree f))\"\nproof (cases \"bdd_above (subdegree`A)\")\n  assume unbounded: \"\\<not>bdd_above (subdegree`A)\"\n  have \"Lcm A = 0\"\n  proof (rule ccontr)\n    assume \"Lcm A \\<noteq> 0\"\n    from unbounded obtain f where f: \"f \\<in> A\" \"subdegree (Lcm A) < subdegree f\"\n      unfolding bdd_above_def by (auto simp: not_le)\n    moreover from f and \\<open>Lcm A \\<noteq> 0\\<close> have \"subdegree f \\<le> subdegree (Lcm A)\"\n      by (intro dvd_imp_subdegree_le dvd_Lcm) simp_all\n    ultimately show False by simp\n  qed\n  with unbounded show ?thesis by simp\nqed (simp_all add: fps_Lcm Lcm_eq_0_I)\n\n\n\nsubsection \\<open>Formal Derivatives, and the MacLaurin theorem around 0\\<close>\n\ndefinition \"fps_deriv f = Abs_fps (\\<lambda>n. of_nat (n + 1) * f $ (n + 1))\"\n\nlemma fps_deriv_nth[simp]: \"fps_deriv f $ n = of_nat (n +1) * f $ (n + 1)\"\n  by (simp add: fps_deriv_def)\n\nlemma fps_deriv_linear[simp]:\n  \"fps_deriv (fps_const (a::'a::comm_semiring_1) * f + fps_const b * g) =\n    fps_const a * fps_deriv f + fps_const b * fps_deriv g\"\n  unfolding fps_eq_iff fps_add_nth  fps_const_mult_left fps_deriv_nth by (simp add: field_simps)\n\nlemma fps_deriv_mult[simp]:\n  fixes f :: \"'a::comm_ring_1 fps\"\n  shows \"fps_deriv (f * g) = f * fps_deriv g + fps_deriv f * g\"\nproof -\n  let ?D = \"fps_deriv\"\n  have \"(f * ?D g + ?D f * g) $ n = ?D (f*g) $ n\" for n\n  proof -\n    let ?Zn = \"{0 ..n}\"\n    let ?Zn1 = \"{0 .. n + 1}\"\n    let ?g = \"\\<lambda>i. of_nat (i+1) * g $ (i+1) * f $ (n - i) +\n        of_nat (i+1)* f $ (i+1) * g $ (n - i)\"\n    let ?h = \"\\<lambda>i. of_nat i * g $ i * f $ ((n+1) - i) +\n        of_nat i* f $ i * g $ ((n + 1) - i)\"\n    have s0: \"sum (\\<lambda>i. of_nat i * f $ i * g $ (n + 1 - i)) ?Zn1 =\n      sum (\\<lambda>i. of_nat (n + 1 - i) * f $ (n + 1 - i) * g $ i) ?Zn1\"\n       by (rule sum.reindex_bij_witness[where i=\"op - (n + 1)\" and j=\"op - (n + 1)\"]) auto\n    have s1: \"sum (\\<lambda>i. f $ i * g $ (n + 1 - i)) ?Zn1 =\n      sum (\\<lambda>i. f $ (n + 1 - i) * g $ i) ?Zn1\"\n       by (rule sum.reindex_bij_witness[where i=\"op - (n + 1)\" and j=\"op - (n + 1)\"]) auto\n    have \"(f * ?D g + ?D f * g)$n = (?D g * f + ?D f * g)$n\"\n      by (simp only: mult.commute)\n    also have \"\\<dots> = (\\<Sum>i = 0..n. ?g i)\"\n      by (simp add: fps_mult_nth sum.distrib[symmetric])\n    also have \"\\<dots> = sum ?h {0..n+1}\"\n      by (rule sum.reindex_bij_witness_not_neutral\n            [where S'=\"{}\" and T'=\"{0}\" and j=\"Suc\" and i=\"\\<lambda>i. i - 1\"]) auto\n    also have \"\\<dots> = (fps_deriv (f * g)) $ n\"\n      apply (simp only: fps_deriv_nth fps_mult_nth sum.distrib)\n      unfolding s0 s1\n      unfolding sum.distrib[symmetric] sum_distrib_left\n      apply (rule sum.cong)\n      apply (auto simp add: of_nat_diff field_simps)\n      done\n    finally show ?thesis .\n  qed\n  then show ?thesis\n    unfolding fps_eq_iff by auto\nqed\n\nlemma fps_deriv_X[simp]: \"fps_deriv X = 1\"\n  by (simp add: fps_deriv_def X_def fps_eq_iff)\n\nlemma fps_deriv_neg[simp]:\n  \"fps_deriv (- (f:: 'a::comm_ring_1 fps)) = - (fps_deriv f)\"\n  by (simp add: fps_eq_iff fps_deriv_def)\n\nlemma fps_deriv_add[simp]:\n  \"fps_deriv ((f:: 'a::comm_ring_1 fps) + g) = fps_deriv f + fps_deriv g\"\n  using fps_deriv_linear[of 1 f 1 g] by simp\n\nlemma fps_deriv_sub[simp]:\n  \"fps_deriv ((f:: 'a::comm_ring_1 fps) - g) = fps_deriv f - fps_deriv g\"\n  using fps_deriv_add [of f \"- g\"] by simp\n\nlemma fps_deriv_const[simp]: \"fps_deriv (fps_const c) = 0\"\n  by (simp add: fps_ext fps_deriv_def fps_const_def)\n\nlemma fps_deriv_mult_const_left[simp]:\n  \"fps_deriv (fps_const (c::'a::comm_ring_1) * f) = fps_const c * fps_deriv f\"\n  by simp\n\nlemma fps_deriv_0[simp]: \"fps_deriv 0 = 0\"\n  by (simp add: fps_deriv_def fps_eq_iff)\n\nlemma fps_deriv_1[simp]: \"fps_deriv 1 = 0\"\n  by (simp add: fps_deriv_def fps_eq_iff )\n\nlemma fps_deriv_mult_const_right[simp]:\n  \"fps_deriv (f * fps_const (c::'a::comm_ring_1)) = fps_deriv f * fps_const c\"\n  by simp\n\nlemma fps_deriv_sum:\n  \"fps_deriv (sum f S) = sum (\\<lambda>i. fps_deriv (f i :: 'a::comm_ring_1 fps)) S\"\nproof (cases \"finite S\")\n  case False\n  then show ?thesis by simp\nnext\n  case True\n  show ?thesis by (induct rule: finite_induct [OF True]) simp_all\nqed\n\nlemma fps_deriv_eq_0_iff [simp]:\n  \"fps_deriv f = 0 \\<longleftrightarrow> f = fps_const (f$0 :: 'a::{idom,semiring_char_0})\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?lhs if ?rhs\n  proof -\n    from that have \"fps_deriv f = fps_deriv (fps_const (f$0))\"\n      by simp\n    then show ?thesis\n      by simp\n  qed\n  show ?rhs if ?lhs\n  proof -\n    from that have \"\\<forall>n. (fps_deriv f)$n = 0\"\n      by simp\n    then have \"\\<forall>n. f$(n+1) = 0\"\n      by (simp del: of_nat_Suc of_nat_add One_nat_def)\n    then show ?thesis\n      apply (clarsimp simp add: fps_eq_iff fps_const_def)\n      apply (erule_tac x=\"n - 1\" in allE)\n      apply simp\n      done\n  qed\nqed\n\nlemma fps_deriv_eq_iff:\n  fixes f :: \"'a::{idom,semiring_char_0} fps\"\n  shows \"fps_deriv f = fps_deriv g \\<longleftrightarrow> (f = fps_const(f$0 - g$0) + g)\"\nproof -\n  have \"fps_deriv f = fps_deriv g \\<longleftrightarrow> fps_deriv (f - g) = 0\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> f - g = fps_const ((f - g) $ 0)\"\n    unfolding fps_deriv_eq_0_iff ..\n  finally show ?thesis\n    by (simp add: field_simps)\nqed\n\nlemma fps_deriv_eq_iff_ex:\n  \"(fps_deriv f = fps_deriv g) \\<longleftrightarrow> (\\<exists>c::'a::{idom,semiring_char_0}. f = fps_const c + g)\"\n  by (auto simp: fps_deriv_eq_iff)\n\n\nfun fps_nth_deriv :: \"nat \\<Rightarrow> 'a::semiring_1 fps \\<Rightarrow> 'a fps\"\nwhere\n  \"fps_nth_deriv 0 f = f\"\n| \"fps_nth_deriv (Suc n) f = fps_nth_deriv n (fps_deriv f)\"\n\nlemma fps_nth_deriv_commute: \"fps_nth_deriv (Suc n) f = fps_deriv (fps_nth_deriv n f)\"\n  by (induct n arbitrary: f) auto\n\nlemma fps_nth_deriv_linear[simp]:\n  \"fps_nth_deriv n (fps_const (a::'a::comm_semiring_1) * f + fps_const b * g) =\n    fps_const a * fps_nth_deriv n f + fps_const b * fps_nth_deriv n g\"\n  by (induct n arbitrary: f g) (auto simp add: fps_nth_deriv_commute)\n\nlemma fps_nth_deriv_neg[simp]:\n  \"fps_nth_deriv n (- (f :: 'a::comm_ring_1 fps)) = - (fps_nth_deriv n f)\"\n  by (induct n arbitrary: f) simp_all\n\nlemma fps_nth_deriv_add[simp]:\n  \"fps_nth_deriv n ((f :: 'a::comm_ring_1 fps) + g) = fps_nth_deriv n f + fps_nth_deriv n g\"\n  using fps_nth_deriv_linear[of n 1 f 1 g] by simp\n\nlemma fps_nth_deriv_sub[simp]:\n  \"fps_nth_deriv n ((f :: 'a::comm_ring_1 fps) - g) = fps_nth_deriv n f - fps_nth_deriv n g\"\n  using fps_nth_deriv_add [of n f \"- g\"] by simp\n\nlemma fps_nth_deriv_0[simp]: \"fps_nth_deriv n 0 = 0\"\n  by (induct n) simp_all\n\nlemma fps_nth_deriv_1[simp]: \"fps_nth_deriv n 1 = (if n = 0 then 1 else 0)\"\n  by (induct n) simp_all\n\nlemma fps_nth_deriv_const[simp]:\n  \"fps_nth_deriv n (fps_const c) = (if n = 0 then fps_const c else 0)\"\n  by (cases n) simp_all\n\nlemma fps_nth_deriv_mult_const_left[simp]:\n  \"fps_nth_deriv n (fps_const (c::'a::comm_ring_1) * f) = fps_const c * fps_nth_deriv n f\"\n  using fps_nth_deriv_linear[of n \"c\" f 0 0 ] by simp\n\nlemma fps_nth_deriv_mult_const_right[simp]:\n  \"fps_nth_deriv n (f * fps_const (c::'a::comm_ring_1)) = fps_nth_deriv n f * fps_const c\"\n  using fps_nth_deriv_linear[of n \"c\" f 0 0] by (simp add: mult.commute)\n\nlemma fps_nth_deriv_sum:\n  \"fps_nth_deriv n (sum f S) = sum (\\<lambda>i. fps_nth_deriv n (f i :: 'a::comm_ring_1 fps)) S\"\nproof (cases \"finite S\")\n  case True\n  show ?thesis by (induct rule: finite_induct [OF True]) simp_all\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma fps_deriv_maclauren_0:\n  \"(fps_nth_deriv k (f :: 'a::comm_semiring_1 fps)) $ 0 = of_nat (fact k) * f $ k\"\n  by (induct k arbitrary: f) (auto simp add: field_simps)\n\n\nsubsection \\<open>Powers\\<close>\n\nlemma fps_power_zeroth_eq_one: \"a$0 =1 \\<Longrightarrow> a^n $ 0 = (1::'a::semiring_1)\"\n  by (induct n) (auto simp add: expand_fps_eq fps_mult_nth)\n\nlemma fps_power_first_eq: \"(a :: 'a::comm_ring_1 fps) $ 0 =1 \\<Longrightarrow> a^n $ 1 = of_nat n * a$1\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case unfolding power_Suc fps_mult_nth\n    using Suc.hyps[OF \\<open>a$0 = 1\\<close>] \\<open>a$0 = 1\\<close> fps_power_zeroth_eq_one[OF \\<open>a$0=1\\<close>]\n    by (simp add: field_simps)\nqed\n\nlemma startsby_one_power:\"a $ 0 = (1::'a::comm_ring_1) \\<Longrightarrow> a^n $ 0 = 1\"\n  by (induct n) (auto simp add: fps_mult_nth)\n\nlemma startsby_zero_power:\"a $0 = (0::'a::comm_ring_1) \\<Longrightarrow> n > 0 \\<Longrightarrow> a^n $0 = 0\"\n  by (induct n) (auto simp add: fps_mult_nth)\n\nlemma startsby_power:\"a $0 = (v::'a::comm_ring_1) \\<Longrightarrow> a^n $0 = v^n\"\n  by (induct n) (auto simp add: fps_mult_nth)\n\nlemma startsby_zero_power_iff[simp]: \"a^n $0 = (0::'a::idom) \\<longleftrightarrow> n \\<noteq> 0 \\<and> a$0 = 0\"\n  apply (rule iffI)\n  apply (induct n)\n  apply (auto simp add: fps_mult_nth)\n  apply (rule startsby_zero_power, simp_all)\n  done\n\nlemma startsby_zero_power_prefix:\n  assumes a0: \"a $ 0 = (0::'a::idom)\"\n  shows \"\\<forall>n < k. a ^ k $ n = 0\"\n  using a0\nproof (induct k rule: nat_less_induct)\n  fix k\n  assume H: \"\\<forall>m<k. a $0 =  0 \\<longrightarrow> (\\<forall>n<m. a ^ m $ n = 0)\" and a0: \"a $ 0 = 0\"\n  show \"\\<forall>m<k. a ^ k $ m = 0\"\n  proof (cases k)\n    case 0\n    then show ?thesis by simp\n  next\n    case (Suc l)\n    have \"a^k $ m = 0\" if mk: \"m < k\" for m\n    proof (cases \"m = 0\")\n      case True\n      then show ?thesis\n        using startsby_zero_power[of a k] Suc a0 by simp\n    next\n      case False\n      have \"a ^k $ m = (a^l * a) $m\"\n        by (simp add: Suc mult.commute)\n      also have \"\\<dots> = (\\<Sum>i = 0..m. a ^ l $ i * a $ (m - i))\"\n        by (simp add: fps_mult_nth)\n      also have \"\\<dots> = 0\"\n        apply (rule sum.neutral)\n        apply auto\n        apply (case_tac \"x = m\")\n        using a0 apply simp\n        apply (rule H[rule_format])\n        using a0 Suc mk apply auto\n        done\n      finally show ?thesis .\n    qed\n    then show ?thesis by blast\n  qed\nqed\n\nlemma startsby_zero_sum_depends:\n  assumes a0: \"a $0 = (0::'a::idom)\"\n    and kn: \"n \\<ge> k\"\n  shows \"sum (\\<lambda>i. (a ^ i)$k) {0 .. n} = sum (\\<lambda>i. (a ^ i)$k) {0 .. k}\"\n  apply (rule sum.mono_neutral_right)\n  using kn\n  apply auto\n  apply (rule startsby_zero_power_prefix[rule_format, OF a0])\n  apply arith\n  done\n\nlemma startsby_zero_power_nth_same:\n  assumes a0: \"a$0 = (0::'a::idom)\"\n  shows \"a^n $ n = (a$1) ^ n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"a ^ Suc n $ (Suc n) = (a^n * a)$(Suc n)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = sum (\\<lambda>i. a^n$i * a $ (Suc n - i)) {0.. Suc n}\"\n    by (simp add: fps_mult_nth)\n  also have \"\\<dots> = sum (\\<lambda>i. a^n$i * a $ (Suc n - i)) {n .. Suc n}\"\n    apply (rule sum.mono_neutral_right)\n    apply simp\n    apply clarsimp\n    apply clarsimp\n    apply (rule startsby_zero_power_prefix[rule_format, OF a0])\n    apply arith\n    done\n  also have \"\\<dots> = a^n $ n * a$1\"\n    using a0 by simp\n  finally show ?case\n    using Suc.hyps by simp\nqed\n\nlemma fps_inverse_power:\n  fixes a :: \"'a::field fps\"\n  shows \"inverse (a^n) = inverse a ^ n\"\n  by (induction n) (simp_all add: fps_inverse_mult)\n\nlemma fps_deriv_power:\n  \"fps_deriv (a ^ n) = fps_const (of_nat n :: 'a::comm_ring_1) * fps_deriv a * a ^ (n - 1)\"\n  apply (induct n)\n  apply (auto simp add: field_simps fps_const_add[symmetric] simp del: fps_const_add)\n  apply (case_tac n)\n  apply (auto simp add: field_simps)\n  done\n\nlemma fps_inverse_deriv:\n  fixes a :: \"'a::field fps\"\n  assumes a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_deriv (inverse a) = - fps_deriv a * (inverse a)\\<^sup>2\"\nproof -\n  from inverse_mult_eq_1[OF a0]\n  have \"fps_deriv (inverse a * a) = 0\" by simp\n  then have \"inverse a * fps_deriv a + fps_deriv (inverse a) * a = 0\"\n    by simp\n  then have \"inverse a * (inverse a * fps_deriv a + fps_deriv (inverse a) * a) = 0\"\n    by simp\n  with inverse_mult_eq_1[OF a0]\n  have \"(inverse a)\\<^sup>2 * fps_deriv a + fps_deriv (inverse a) = 0\"\n    unfolding power2_eq_square\n    apply (simp add: field_simps)\n    apply (simp add: mult.assoc[symmetric])\n    done\n  then have \"(inverse a)\\<^sup>2 * fps_deriv a + fps_deriv (inverse a) - fps_deriv a * (inverse a)\\<^sup>2 =\n      0 - fps_deriv a * (inverse a)\\<^sup>2\"\n    by simp\n  then show \"fps_deriv (inverse a) = - fps_deriv a * (inverse a)\\<^sup>2\"\n    by (simp add: field_simps)\nqed\n\nlemma fps_inverse_deriv':\n  fixes a :: \"'a::field fps\"\n  assumes a0: \"a $ 0 \\<noteq> 0\"\n  shows \"fps_deriv (inverse a) = - fps_deriv a / a\\<^sup>2\"\n  using fps_inverse_deriv[OF a0] a0\n  by (simp add: fps_divide_unit power2_eq_square fps_inverse_mult)\n\nlemma inverse_mult_eq_1':\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n  shows \"f * inverse f = 1\"\n  by (metis mult.commute inverse_mult_eq_1 f0)\n\nlemma fps_inverse_minus [simp]: \"inverse (-f) = -inverse (f :: 'a :: field fps)\"\n  by (cases \"f$0 = 0\") (auto intro: fps_inverse_unique simp: inverse_mult_eq_1' fps_inverse_eq_0)\n  \nlemma divide_fps_const [simp]: \"f / fps_const (c :: 'a :: field) = fps_const (inverse c) * f\"\n  by (cases \"c = 0\") (simp_all add: fps_divide_unit fps_const_inverse)\n\n(* FIXME: The last part of this proof should go through by simp once we have a proper\n   theorem collection for simplifying division on rings *)\nlemma fps_divide_deriv:\n  assumes \"b dvd (a :: 'a :: field fps)\"\n  shows   \"fps_deriv (a / b) = (fps_deriv a * b - a * fps_deriv b) / b^2\"\nproof -\n  have eq_divide_imp: \"c \\<noteq> 0 \\<Longrightarrow> a * c = b \\<Longrightarrow> a = b div c\" for a b c :: \"'a :: field fps\"\n    by (drule sym) (simp add: mult.assoc)\n  from assms have \"a = a / b * b\" by simp\n  also have \"fps_deriv (a / b * b) = fps_deriv (a / b) * b + a / b * fps_deriv b\" by simp\n  finally have \"fps_deriv (a / b) * b^2 = fps_deriv a * b - a * fps_deriv b\" using assms\n    by (simp add: power2_eq_square algebra_simps)\n  thus ?thesis by (cases \"b = 0\") (auto simp: eq_divide_imp)\nqed\n\nlemma fps_inverse_gp': \"inverse (Abs_fps (\\<lambda>n. 1::'a::field)) = 1 - X\"\n  by (simp add: fps_inverse_gp fps_eq_iff X_def)\n\nlemma fps_one_over_one_minus_X_squared:\n  \"inverse ((1 - X)^2 :: 'a :: field fps) = Abs_fps (\\<lambda>n. of_nat (n+1))\"\nproof -\n  have \"inverse ((1 - X)^2 :: 'a fps) = fps_deriv (inverse (1 - X))\"\n    by (subst fps_inverse_deriv) (simp_all add: fps_inverse_power)\n  also have \"inverse (1 - X :: 'a fps) = Abs_fps (\\<lambda>_. 1)\"\n    by (subst fps_inverse_gp' [symmetric]) simp\n  also have \"fps_deriv \\<dots> = Abs_fps (\\<lambda>n. of_nat (n + 1))\"\n    by (simp add: fps_deriv_def)\n  finally show ?thesis .\nqed\n\nlemma fps_nth_deriv_X[simp]: \"fps_nth_deriv n X = (if n = 0 then X else if n=1 then 1 else 0)\"\n  by (cases n) simp_all\n\nlemma fps_inverse_X_plus1: \"inverse (1 + X) = Abs_fps (\\<lambda>n. (- (1::'a::field)) ^ n)\"\n  (is \"_ = ?r\")\nproof -\n  have eq: \"(1 + X) * ?r = 1\"\n    unfolding minus_one_power_iff\n    by (auto simp add: field_simps fps_eq_iff)\n  show ?thesis\n    by (auto simp add: eq intro: fps_inverse_unique)\nqed\n\n\nsubsection \\<open>Integration\\<close>\n\ndefinition fps_integral :: \"'a::field_char_0 fps \\<Rightarrow> 'a \\<Rightarrow> 'a fps\"\n  where \"fps_integral a a0 = Abs_fps (\\<lambda>n. if n = 0 then a0 else (a$(n - 1) / of_nat n))\"\n\nlemma fps_deriv_fps_integral: \"fps_deriv (fps_integral a a0) = a\"\n  unfolding fps_integral_def fps_deriv_def\n  by (simp add: fps_eq_iff del: of_nat_Suc)\n\nlemma fps_integral_linear:\n  \"fps_integral (fps_const a * f + fps_const b * g) (a*a0 + b*b0) =\n    fps_const a * fps_integral f a0 + fps_const b * fps_integral g b0\"\n  (is \"?l = ?r\")\nproof -\n  have \"fps_deriv ?l = fps_deriv ?r\"\n    by (simp add: fps_deriv_fps_integral)\n  moreover have \"?l$0 = ?r$0\"\n    by (simp add: fps_integral_def)\n  ultimately show ?thesis\n    unfolding fps_deriv_eq_iff by auto\nqed\n\n\nsubsection \\<open>Composition of FPSs\\<close>\n\ndefinition fps_compose :: \"'a::semiring_1 fps \\<Rightarrow> 'a fps \\<Rightarrow> 'a fps\"  (infixl \"oo\" 55)\n  where \"a oo b = Abs_fps (\\<lambda>n. sum (\\<lambda>i. a$i * (b^i$n)) {0..n})\"\n\nlemma fps_compose_nth: \"(a oo b)$n = sum (\\<lambda>i. a$i * (b^i$n)) {0..n}\"\n  by (simp add: fps_compose_def)\n\nlemma fps_compose_nth_0 [simp]: \"(f oo g) $ 0 = f $ 0\"\n  by (simp add: fps_compose_nth)\n\nlemma fps_compose_X[simp]: \"a oo X = (a :: 'a::comm_ring_1 fps)\"\n  by (simp add: fps_ext fps_compose_def mult_delta_right sum.delta')\n\nlemma fps_const_compose[simp]: \"fps_const (a::'a::comm_ring_1) oo b = fps_const a\"\n  by (simp add: fps_eq_iff fps_compose_nth mult_delta_left sum.delta)\n\nlemma numeral_compose[simp]: \"(numeral k :: 'a::comm_ring_1 fps) oo b = numeral k\"\n  unfolding numeral_fps_const by simp\n\nlemma neg_numeral_compose[simp]: \"(- numeral k :: 'a::comm_ring_1 fps) oo b = - numeral k\"\n  unfolding neg_numeral_fps_const by simp\n\nlemma X_fps_compose_startby0[simp]: \"a$0 = 0 \\<Longrightarrow> X oo a = (a :: 'a::comm_ring_1 fps)\"\n  by (simp add: fps_eq_iff fps_compose_def mult_delta_left sum.delta not_le)\n\n\nsubsection \\<open>Rules from Herbert Wilf's Generatingfunctionology\\<close>\n\nsubsubsection \\<open>Rule 1\\<close>\n  (* {a_{n+k}}_0^infty Corresponds to (f - sum (\\<lambda>i. a_i * x^i))/x^h, for h>0*)\n\nlemma fps_power_mult_eq_shift:\n  \"X^Suc k * Abs_fps (\\<lambda>n. a (n + Suc k)) =\n    Abs_fps a - sum (\\<lambda>i. fps_const (a i :: 'a::comm_ring_1) * X^i) {0 .. k}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs $ n = ?rhs $ n\" for n :: nat\n  proof -\n    have \"?lhs $ n = (if n < Suc k then 0 else a n)\"\n      unfolding X_power_mult_nth by auto\n    also have \"\\<dots> = ?rhs $ n\"\n    proof (induct k)\n      case 0\n      then show ?case\n        by (simp add: fps_sum_nth)\n    next\n      case (Suc k)\n      have \"(Abs_fps a - sum (\\<lambda>i. fps_const (a i :: 'a) * X^i) {0 .. Suc k})$n =\n        (Abs_fps a - sum (\\<lambda>i. fps_const (a i :: 'a) * X^i) {0 .. k} -\n          fps_const (a (Suc k)) * X^ Suc k) $ n\"\n        by (simp add: field_simps)\n      also have \"\\<dots> = (if n < Suc k then 0 else a n) - (fps_const (a (Suc k)) * X^ Suc k)$n\"\n        using Suc.hyps[symmetric] unfolding fps_sub_nth by simp\n      also have \"\\<dots> = (if n < Suc (Suc k) then 0 else a n)\"\n        unfolding X_power_mult_right_nth\n        apply (auto simp add: not_less fps_const_def)\n        apply (rule cong[of a a, OF refl])\n        apply arith\n        done\n      finally show ?case\n        by simp\n    qed\n    finally show ?thesis .\n  qed\n  then show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\n\nsubsubsection \\<open>Rule 2\\<close>\n\n  (* We can not reach the form of Wilf, but still near to it using rewrite rules*)\n  (* If f reprents {a_n} and P is a polynomial, then\n        P(xD) f represents {P(n) a_n}*)\n\ndefinition \"XD = op * X \\<circ> fps_deriv\"\n\nlemma XD_add[simp]:\"XD (a + b) = XD a + XD (b :: 'a::comm_ring_1 fps)\"\n  by (simp add: XD_def field_simps)\n\nlemma XD_mult_const[simp]:\"XD (fps_const (c::'a::comm_ring_1) * a) = fps_const c * XD a\"\n  by (simp add: XD_def field_simps)\n\nlemma XD_linear[simp]: \"XD (fps_const c * a + fps_const d * b) =\n    fps_const c * XD a + fps_const d * XD (b :: 'a::comm_ring_1 fps)\"\n  by simp\n\nlemma XDN_linear:\n  \"(XD ^^ n) (fps_const c * a + fps_const d * b) =\n    fps_const c * (XD ^^ n) a + fps_const d * (XD ^^ n) (b :: 'a::comm_ring_1 fps)\"\n  by (induct n) simp_all\n\nlemma fps_mult_X_deriv_shift: \"X* fps_deriv a = Abs_fps (\\<lambda>n. of_nat n* a$n)\"\n  by (simp add: fps_eq_iff)\n\nlemma fps_mult_XD_shift:\n  \"(XD ^^ k) (a :: 'a::comm_ring_1 fps) = Abs_fps (\\<lambda>n. (of_nat n ^ k) * a$n)\"\n  by (induct k arbitrary: a) (simp_all add: XD_def fps_eq_iff field_simps del: One_nat_def)\n\n\nsubsubsection \\<open>Rule 3\\<close>\n\ntext \\<open>Rule 3 is trivial and is given by \\<open>fps_times_def\\<close>.\\<close>\n\n\nsubsubsection \\<open>Rule 5 --- summation and \"division\" by (1 - X)\\<close>\n\nlemma fps_divide_X_minus1_sum_lemma:\n  \"a = ((1::'a::comm_ring_1 fps) - X) * Abs_fps (\\<lambda>n. sum (\\<lambda>i. a $ i) {0..n})\"\nproof -\n  let ?sa = \"Abs_fps (\\<lambda>n. sum (\\<lambda>i. a $ i) {0..n})\"\n  have th0: \"\\<And>i. (1 - (X::'a fps)) $ i = (if i = 0 then 1 else if i = 1 then - 1 else 0)\"\n    by simp\n  have \"a$n = ((1 - X) * ?sa) $ n\" for n\n  proof (cases \"n = 0\")\n    case True\n    then show ?thesis\n      by (simp add: fps_mult_nth)\n  next\n    case False\n    then have u: \"{0} \\<union> ({1} \\<union> {2..n}) = {0..n}\" \"{1} \\<union> {2..n} = {1..n}\"\n      \"{0..n - 1} \\<union> {n} = {0..n}\"\n      by (auto simp: set_eq_iff)\n    have d: \"{0} \\<inter> ({1} \\<union> {2..n}) = {}\" \"{1} \\<inter> {2..n} = {}\" \"{0..n - 1} \\<inter> {n} = {}\"\n      using False by simp_all\n    have f: \"finite {0}\" \"finite {1}\" \"finite {2 .. n}\"\n      \"finite {0 .. n - 1}\" \"finite {n}\" by simp_all\n    have \"((1 - X) * ?sa) $ n = sum (\\<lambda>i. (1 - X)$ i * ?sa $ (n - i)) {0 .. n}\"\n      by (simp add: fps_mult_nth)\n    also have \"\\<dots> = a$n\"\n      unfolding th0\n      unfolding sum.union_disjoint[OF f(1) finite_UnI[OF f(2,3)] d(1), unfolded u(1)]\n      unfolding sum.union_disjoint[OF f(2) f(3) d(2)]\n      apply (simp)\n      unfolding sum.union_disjoint[OF f(4,5) d(3), unfolded u(3)]\n      apply simp\n      done\n    finally show ?thesis\n      by simp\n  qed\n  then show ?thesis\n    unfolding fps_eq_iff by blast\nqed\n\nlemma fps_divide_X_minus1_sum:\n  \"a /((1::'a::field fps) - X) = Abs_fps (\\<lambda>n. sum (\\<lambda>i. a $ i) {0..n})\"\nproof -\n  let ?X = \"1 - (X::'a fps)\"\n  have th0: \"?X $ 0 \\<noteq> 0\"\n    by simp\n  have \"a /?X = ?X *  Abs_fps (\\<lambda>n::nat. sum (op $ a) {0..n}) * inverse ?X\"\n    using fps_divide_X_minus1_sum_lemma[of a, symmetric] th0\n    by (simp add: fps_divide_def mult.assoc)\n  also have \"\\<dots> = (inverse ?X * ?X) * Abs_fps (\\<lambda>n::nat. sum (op $ a) {0..n}) \"\n    by (simp add: ac_simps)\n  finally show ?thesis\n    by (simp add: inverse_mult_eq_1[OF th0])\nqed\n\n\nsubsubsection \\<open>Rule 4 in its more general form: generalizes Rule 3 for an arbitrary\n  finite product of FPS, also the relvant instance of powers of a FPS\\<close>\n\ndefinition \"natpermute n k = {l :: nat list. length l = k \\<and> sum_list l = n}\"\n\nlemma natlist_trivial_1: \"natpermute n 1 = {[n]}\"\n  apply (auto simp add: natpermute_def)\n  apply (case_tac x)\n  apply auto\n  done\n\nlemma append_natpermute_less_eq:\n  assumes \"xs @ ys \\<in> natpermute n k\"\n  shows \"sum_list xs \\<le> n\"\n    and \"sum_list ys \\<le> n\"\nproof -\n  from assms have \"sum_list (xs @ ys) = n\"\n    by (simp add: natpermute_def)\n  then have \"sum_list xs + sum_list ys = n\"\n    by simp\n  then show \"sum_list xs \\<le> n\" and \"sum_list ys \\<le> n\"\n    by simp_all\nqed\n\nlemma natpermute_split:\n  assumes \"h \\<le> k\"\n  shows \"natpermute n k =\n    (\\<Union>m \\<in>{0..n}. {l1 @ l2 |l1 l2. l1 \\<in> natpermute m h \\<and> l2 \\<in> natpermute (n - m) (k - h)})\"\n  (is \"?L = ?R\" is \"_ = (\\<Union>m \\<in>{0..n}. ?S m)\")\nproof\n  show \"?R \\<subseteq> ?L\"\n  proof\n    fix l\n    assume l: \"l \\<in> ?R\"\n    from l obtain m xs ys where h: \"m \\<in> {0..n}\"\n      and xs: \"xs \\<in> natpermute m h\"\n      and ys: \"ys \\<in> natpermute (n - m) (k - h)\"\n      and leq: \"l = xs@ys\" by blast\n    from xs have xs': \"sum_list xs = m\"\n      by (simp add: natpermute_def)\n    from ys have ys': \"sum_list ys = n - m\"\n      by (simp add: natpermute_def)\n    show \"l \\<in> ?L\" using leq xs ys h\n      apply (clarsimp simp add: natpermute_def)\n      unfolding xs' ys'\n      using assms xs ys\n      unfolding natpermute_def\n      apply simp\n      done\n  qed\n  show \"?L \\<subseteq> ?R\"\n  proof\n    fix l\n    assume l: \"l \\<in> natpermute n k\"\n    let ?xs = \"take h l\"\n    let ?ys = \"drop h l\"\n    let ?m = \"sum_list ?xs\"\n    from l have ls: \"sum_list (?xs @ ?ys) = n\"\n      by (simp add: natpermute_def)\n    have xs: \"?xs \\<in> natpermute ?m h\" using l assms\n      by (simp add: natpermute_def)\n    have l_take_drop: \"sum_list l = sum_list (take h l @ drop h l)\"\n      by simp\n    then have ys: \"?ys \\<in> natpermute (n - ?m) (k - h)\"\n      using l assms ls by (auto simp add: natpermute_def simp del: append_take_drop_id)\n    from ls have m: \"?m \\<in> {0..n}\"\n      by (simp add: l_take_drop del: append_take_drop_id)\n    from xs ys ls show \"l \\<in> ?R\"\n      apply auto\n      apply (rule bexI [where x = \"?m\"])\n      apply (rule exI [where x = \"?xs\"])\n      apply (rule exI [where x = \"?ys\"])\n      using ls l\n      apply (auto simp add: natpermute_def l_take_drop simp del: append_take_drop_id)\n      apply simp\n      done\n  qed\nqed\n\nlemma natpermute_0: \"natpermute n 0 = (if n = 0 then {[]} else {})\"\n  by (auto simp add: natpermute_def)\n\nlemma natpermute_0'[simp]: \"natpermute 0 k = (if k = 0 then {[]} else {replicate k 0})\"\n  apply (auto simp add: set_replicate_conv_if natpermute_def)\n  apply (rule nth_equalityI)\n  apply simp_all\n  done\n\nlemma natpermute_finite: \"finite (natpermute n k)\"\nproof (induct k arbitrary: n)\n  case 0\n  then show ?case\n    apply (subst natpermute_split[of 0 0, simplified])\n    apply (simp add: natpermute_0)\n    done\nnext\n  case (Suc k)\n  then show ?case unfolding natpermute_split [of k \"Suc k\", simplified]\n    apply -\n    apply (rule finite_UN_I)\n    apply simp\n    unfolding One_nat_def[symmetric] natlist_trivial_1\n    apply simp\n    done\nqed\n\nlemma natpermute_contain_maximal:\n  \"{xs \\<in> natpermute n (k + 1). n \\<in> set xs} = (\\<Union>i\\<in>{0 .. k}. {(replicate (k + 1) 0) [i:=n]})\"\n  (is \"?A = ?B\")\nproof\n  show \"?A \\<subseteq> ?B\"\n  proof\n    fix xs\n    assume \"xs \\<in> ?A\"\n    then have H: \"xs \\<in> natpermute n (k + 1)\" and n: \"n \\<in> set xs\"\n      by blast+\n    then obtain i where i: \"i \\<in> {0.. k}\" \"xs!i = n\"\n      unfolding in_set_conv_nth by (auto simp add: less_Suc_eq_le natpermute_def)\n    have eqs: \"({0..k} - {i}) \\<union> {i} = {0..k}\"\n      using i by auto\n    have f: \"finite({0..k} - {i})\" \"finite {i}\"\n      by auto\n    have d: \"({0..k} - {i}) \\<inter> {i} = {}\"\n      using i by auto\n    from H have \"n = sum (nth xs) {0..k}\"\n      apply (simp add: natpermute_def)\n      apply (auto simp add: atLeastLessThanSuc_atLeastAtMost sum_list_sum_nth)\n      done\n    also have \"\\<dots> = n + sum (nth xs) ({0..k} - {i})\"\n      unfolding sum.union_disjoint[OF f d, unfolded eqs] using i by simp\n    finally have zxs: \"\\<forall> j\\<in> {0..k} - {i}. xs!j = 0\"\n      by auto\n    from H have xsl: \"length xs = k+1\"\n      by (simp add: natpermute_def)\n    from i have i': \"i < length (replicate (k+1) 0)\"   \"i < k+1\"\n      unfolding length_replicate by presburger+\n    have \"xs = replicate (k+1) 0 [i := n]\"\n      apply (rule nth_equalityI)\n      unfolding xsl length_list_update length_replicate\n      apply simp\n      apply clarify\n      unfolding nth_list_update[OF i'(1)]\n      using i zxs\n      apply (case_tac \"ia = i\")\n      apply (auto simp del: replicate.simps)\n      done\n    then show \"xs \\<in> ?B\" using i by blast\n  qed\n  show \"?B \\<subseteq> ?A\"\n  proof\n    fix xs\n    assume \"xs \\<in> ?B\"\n    then obtain i where i: \"i \\<in> {0..k}\" and xs: \"xs = replicate (k + 1) 0 [i:=n]\"\n      by auto\n    have nxs: \"n \\<in> set xs\"\n      unfolding xs\n      apply (rule set_update_memI)\n      using i apply simp\n      done\n    have xsl: \"length xs = k + 1\"\n      by (simp only: xs length_replicate length_list_update)\n    have \"sum_list xs = sum (nth xs) {0..<k+1}\"\n      unfolding sum_list_sum_nth xsl ..\n    also have \"\\<dots> = sum (\\<lambda>j. if j = i then n else 0) {0..< k+1}\"\n      by (rule sum.cong) (simp_all add: xs del: replicate.simps)\n    also have \"\\<dots> = n\" using i by (simp add: sum.delta)\n    finally have \"xs \\<in> natpermute n (k + 1)\"\n      using xsl unfolding natpermute_def mem_Collect_eq by blast\n    then show \"xs \\<in> ?A\"\n      using nxs by blast\n  qed\nqed\n\ntext \\<open>The general form.\\<close>\nlemma fps_prod_nth:\n  fixes m :: nat\n    and a :: \"nat \\<Rightarrow> 'a::comm_ring_1 fps\"\n  shows \"(prod a {0 .. m}) $ n =\n    sum (\\<lambda>v. prod (\\<lambda>j. (a j) $ (v!j)) {0..m}) (natpermute n (m+1))\"\n  (is \"?P m n\")\nproof (induct m arbitrary: n rule: nat_less_induct)\n  fix m n assume H: \"\\<forall>m' < m. \\<forall>n. ?P m' n\"\n  show \"?P m n\"\n  proof (cases m)\n    case 0\n    then show ?thesis\n      apply simp\n      unfolding natlist_trivial_1[where n = n, unfolded One_nat_def]\n      apply simp\n      done\n  next\n    case (Suc k)\n    then have km: \"k < m\" by arith\n    have u0: \"{0 .. k} \\<union> {m} = {0..m}\"\n      using Suc by (simp add: set_eq_iff) presburger\n    have f0: \"finite {0 .. k}\" \"finite {m}\" by auto\n    have d0: \"{0 .. k} \\<inter> {m} = {}\" using Suc by auto\n    have \"(prod a {0 .. m}) $ n = (prod a {0 .. k} * a m) $ n\"\n      unfolding prod.union_disjoint[OF f0 d0, unfolded u0] by simp\n    also have \"\\<dots> = (\\<Sum>i = 0..n. (\\<Sum>v\\<in>natpermute i (k + 1). \\<Prod>j\\<in>{0..k}. a j $ v ! j) * a m $ (n - i))\"\n      unfolding fps_mult_nth H[rule_format, OF km] ..\n    also have \"\\<dots> = (\\<Sum>v\\<in>natpermute n (m + 1). \\<Prod>j\\<in>{0..m}. a j $ v ! j)\"\n      apply (simp add: Suc)\n      unfolding natpermute_split[of m \"m + 1\", simplified, of n,\n        unfolded natlist_trivial_1[unfolded One_nat_def] Suc]\n      apply (subst sum.UNION_disjoint)\n      apply simp\n      apply simp\n      unfolding image_Collect[symmetric]\n      apply clarsimp\n      apply (rule finite_imageI)\n      apply (rule natpermute_finite)\n      apply (clarsimp simp add: set_eq_iff)\n      apply auto\n      apply (rule sum.cong)\n      apply (rule refl)\n      unfolding sum_distrib_right\n      apply (rule sym)\n      apply (rule_tac l = \"\\<lambda>xs. xs @ [n - x]\" in sum.reindex_cong)\n      apply (simp add: inj_on_def)\n      apply auto\n      unfolding prod.union_disjoint[OF f0 d0, unfolded u0, unfolded Suc]\n      apply (clarsimp simp add: natpermute_def nth_append)\n      done\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>The special form for powers.\\<close>\nlemma fps_power_nth_Suc:\n  fixes m :: nat\n    and a :: \"'a::comm_ring_1 fps\"\n  shows \"(a ^ Suc m)$n = sum (\\<lambda>v. prod (\\<lambda>j. a $ (v!j)) {0..m}) (natpermute n (m+1))\"\nproof -\n  have th0: \"a^Suc m = prod (\\<lambda>i. a) {0..m}\"\n    by (simp add: prod_constant)\n  show ?thesis unfolding th0 fps_prod_nth ..\nqed\n\nlemma fps_power_nth:\n  fixes m :: nat\n    and a :: \"'a::comm_ring_1 fps\"\n  shows \"(a ^m)$n =\n    (if m=0 then 1$n else sum (\\<lambda>v. prod (\\<lambda>j. a $ (v!j)) {0..m - 1}) (natpermute n m))\"\n  by (cases m) (simp_all add: fps_power_nth_Suc del: power_Suc)\n\nlemma fps_nth_power_0:\n  fixes m :: nat\n    and a :: \"'a::comm_ring_1 fps\"\n  shows \"(a ^m)$0 = (a$0) ^ m\"\nproof (cases m)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc n)\n  then have c: \"m = card {0..n}\" by simp\n  have \"(a ^m)$0 = prod (\\<lambda>i. a$0) {0..n}\"\n    by (simp add: Suc fps_power_nth del: replicate.simps power_Suc)\n  also have \"\\<dots> = (a$0) ^ m\"\n   unfolding c by (rule prod_constant)\n finally show ?thesis .\nqed\n\nlemma natpermute_max_card:\n  assumes n0: \"n \\<noteq> 0\"\n  shows \"card {xs \\<in> natpermute n (k + 1). n \\<in> set xs} = k + 1\"\n  unfolding natpermute_contain_maximal\nproof -\n  let ?A = \"\\<lambda>i. {replicate (k + 1) 0[i := n]}\"\n  let ?K = \"{0 ..k}\"\n  have fK: \"finite ?K\"\n    by simp\n  have fAK: \"\\<forall>i\\<in>?K. finite (?A i)\"\n    by auto\n  have d: \"\\<forall>i\\<in> ?K. \\<forall>j\\<in> ?K. i \\<noteq> j \\<longrightarrow>\n    {replicate (k + 1) 0[i := n]} \\<inter> {replicate (k + 1) 0[j := n]} = {}\"\n  proof clarify\n    fix i j\n    assume i: \"i \\<in> ?K\" and j: \"j \\<in> ?K\" and ij: \"i \\<noteq> j\"\n    have False if eq: \"replicate (k+1) 0 [i:=n] = replicate (k+1) 0 [j:= n]\"\n    proof -\n      have \"(replicate (k+1) 0 [i:=n] ! i) = n\"\n        using i by (simp del: replicate.simps)\n      moreover\n      have \"(replicate (k+1) 0 [j:=n] ! i) = 0\"\n        using i ij by (simp del: replicate.simps)\n      ultimately show ?thesis\n        using eq n0 by (simp del: replicate.simps)\n    qed\n    then show \"{replicate (k + 1) 0[i := n]} \\<inter> {replicate (k + 1) 0[j := n]} = {}\"\n      by auto\n  qed\n  from card_UN_disjoint[OF fK fAK d]\n  show \"card (\\<Union>i\\<in>{0..k}. {replicate (k + 1) 0[i := n]}) = k + 1\"\n    by simp\nqed\n\nlemma fps_power_Suc_nth:\n  fixes f :: \"'a :: comm_ring_1 fps\"\n  assumes k: \"k > 0\"\n  shows \"(f ^ Suc m) $ k = \n           of_nat (Suc m) * (f $ k * (f $ 0) ^ m) +\n           (\\<Sum>v\\<in>{v\\<in>natpermute k (m+1). k \\<notin> set v}. \\<Prod>j = 0..m. f $ v ! j)\"\nproof -\n  define A B \n    where \"A = {v\\<in>natpermute k (m+1). k \\<in> set v}\" \n      and  \"B = {v\\<in>natpermute k (m+1). k \\<notin> set v}\"\n  have [simp]: \"finite A\" \"finite B\" \"A \\<inter> B = {}\" by (auto simp: A_def B_def natpermute_finite)\n\n  from natpermute_max_card[of k m] k have card_A: \"card A = m + 1\" by (simp add: A_def)\n  {\n    fix v assume v: \"v \\<in> A\"\n    from v have [simp]: \"length v = Suc m\" by (simp add: A_def natpermute_def)\n    from v have \"\\<exists>j. j \\<le> m \\<and> v ! j = k\" \n      by (auto simp: set_conv_nth A_def natpermute_def less_Suc_eq_le)\n    then guess j by (elim exE conjE) note j = this\n    \n    from v have \"k = sum_list v\" by (simp add: A_def natpermute_def)\n    also have \"\\<dots> = (\\<Sum>i=0..m. v ! i)\"\n      by (simp add: sum_list_sum_nth atLeastLessThanSuc_atLeastAtMost del: sum_op_ivl_Suc)\n    also from j have \"{0..m} = insert j ({0..m}-{j})\" by auto\n    also from j have \"(\\<Sum>i\\<in>\\<dots>. v ! i) = k + (\\<Sum>i\\<in>{0..m}-{j}. v ! i)\"\n      by (subst sum.insert) simp_all\n    finally have \"(\\<Sum>i\\<in>{0..m}-{j}. v ! i) = 0\" by simp\n    hence zero: \"v ! i = 0\" if \"i \\<in> {0..m}-{j}\" for i using that\n      by (subst (asm) sum_eq_0_iff) auto\n      \n    from j have \"{0..m} = insert j ({0..m} - {j})\" by auto\n    also from j have \"(\\<Prod>i\\<in>\\<dots>. f $ (v ! i)) = f $ k * (\\<Prod>i\\<in>{0..m} - {j}. f $ (v ! i))\"\n      by (subst prod.insert) auto\n    also have \"(\\<Prod>i\\<in>{0..m} - {j}. f $ (v ! i)) = (\\<Prod>i\\<in>{0..m} - {j}. f $ 0)\"\n      by (intro prod.cong) (simp_all add: zero)\n    also from j have \"\\<dots> = (f $ 0) ^ m\" by (subst prod_constant) simp_all\n    finally have \"(\\<Prod>j = 0..m. f $ (v ! j)) = f $ k * (f $ 0) ^ m\" .\n  } note A = this\n  \n  have \"(f ^ Suc m) $ k = (\\<Sum>v\\<in>natpermute k (m + 1). \\<Prod>j = 0..m. f $ v ! j)\"\n    by (rule fps_power_nth_Suc)\n  also have \"natpermute k (m+1) = A \\<union> B\" unfolding A_def B_def by blast\n  also have \"(\\<Sum>v\\<in>\\<dots>. \\<Prod>j = 0..m. f $ (v ! j)) = \n               (\\<Sum>v\\<in>A. \\<Prod>j = 0..m. f $ (v ! j)) + (\\<Sum>v\\<in>B. \\<Prod>j = 0..m. f $ (v ! j))\"\n    by (intro sum.union_disjoint) simp_all   \n  also have \"(\\<Sum>v\\<in>A. \\<Prod>j = 0..m. f $ (v ! j)) = of_nat (Suc m) * (f $ k * (f $ 0) ^ m)\"\n    by (simp add: A card_A)\n  finally show ?thesis by (simp add: B_def)\nqed \n  \nlemma fps_power_Suc_eqD:\n  fixes f g :: \"'a :: {idom,semiring_char_0} fps\"\n  assumes \"f ^ Suc m = g ^ Suc m\" \"f $ 0 = g $ 0\" \"f $ 0 \\<noteq> 0\"\n  shows   \"f = g\"\nproof (rule fps_ext)\n  fix k :: nat\n  show \"f $ k = g $ k\"\n  proof (induction k rule: less_induct)\n    case (less k)\n    show ?case\n    proof (cases \"k = 0\")\n      case False\n      let ?h = \"\\<lambda>f. (\\<Sum>v | v \\<in> natpermute k (m + 1) \\<and> k \\<notin> set v. \\<Prod>j = 0..m. f $ v ! j)\"\n      from False fps_power_Suc_nth[of k f m] fps_power_Suc_nth[of k g m]\n        have \"f $ k * (of_nat (Suc m) * (f $ 0) ^ m) + ?h f =\n                g $ k * (of_nat (Suc m) * (f $ 0) ^ m) + ?h g\" using assms \n        by (simp add: mult_ac del: power_Suc of_nat_Suc)\n      also have \"v ! i < k\" if \"v \\<in> {v\\<in>natpermute k (m+1). k \\<notin> set v}\" \"i \\<le> m\" for v i\n        using that elem_le_sum_list_nat[of i v] unfolding natpermute_def\n        by (auto simp: set_conv_nth dest!: spec[of _ i])\n      hence \"?h f = ?h g\"\n        by (intro sum.cong refl prod.cong less lessI) (auto simp: natpermute_def)\n      finally have \"f $ k * (of_nat (Suc m) * (f $ 0) ^ m) = g $ k * (of_nat (Suc m) * (f $ 0) ^ m)\"\n        by simp\n      with assms show \"f $ k = g $ k\" \n        by (subst (asm) mult_right_cancel) (auto simp del: of_nat_Suc)\n    qed (simp_all add: assms)\n  qed\nqed\n\nlemma fps_power_Suc_eqD':\n  fixes f g :: \"'a :: {idom,semiring_char_0} fps\"\n  assumes \"f ^ Suc m = g ^ Suc m\" \"f $ subdegree f = g $ subdegree g\"\n  shows   \"f = g\"\nproof (cases \"f = 0\")\n  case False\n  have \"Suc m * subdegree f = subdegree (f ^ Suc m)\"\n    by (rule subdegree_power [symmetric])\n  also have \"f ^ Suc m = g ^ Suc m\" by fact\n  also have \"subdegree \\<dots> = Suc m * subdegree g\" by (rule subdegree_power)\n  finally have [simp]: \"subdegree f = subdegree g\"\n    by (subst (asm) Suc_mult_cancel1)\n  have \"fps_shift (subdegree f) f * X ^ subdegree f = f\"\n    by (rule subdegree_decompose [symmetric])\n  also have \"\\<dots> ^ Suc m = g ^ Suc m\" by fact\n  also have \"g = fps_shift (subdegree g) g * X ^ subdegree g\"\n    by (rule subdegree_decompose)\n  also have \"subdegree f = subdegree g\" by fact\n  finally have \"fps_shift (subdegree g) f ^ Suc m = fps_shift (subdegree g) g ^ Suc m\"\n    by (simp add: algebra_simps power_mult_distrib del: power_Suc)\n  hence \"fps_shift (subdegree g) f = fps_shift (subdegree g) g\"\n    by (rule fps_power_Suc_eqD) (insert assms False, auto)\n  with subdegree_decompose[of f] subdegree_decompose[of g] show ?thesis by simp\nqed (insert assms, simp_all)\n\nlemma fps_power_eqD':\n  fixes f g :: \"'a :: {idom,semiring_char_0} fps\"\n  assumes \"f ^ m = g ^ m\" \"f $ subdegree f = g $ subdegree g\" \"m > 0\"\n  shows   \"f = g\"\n  using fps_power_Suc_eqD'[of f \"m-1\" g] assms by simp\n\nlemma fps_power_eqD:\n  fixes f g :: \"'a :: {idom,semiring_char_0} fps\"\n  assumes \"f ^ m = g ^ m\" \"f $ 0 = g $ 0\" \"f $ 0 \\<noteq> 0\" \"m > 0\"\n  shows   \"f = g\"\n  by (rule fps_power_eqD'[of f m g]) (insert assms, simp_all)\n\nlemma fps_compose_inj_right:\n  assumes a0: \"a$0 = (0::'a::idom)\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"(b oo a = c oo a) \\<longleftrightarrow> b = c\"\n  (is \"?lhs \\<longleftrightarrow>?rhs\")\nproof\n  show ?lhs if ?rhs using that by simp\n  show ?rhs if ?lhs\n  proof -\n    have \"b$n = c$n\" for n\n    proof (induct n rule: nat_less_induct)\n      fix n\n      assume H: \"\\<forall>m<n. b$m = c$m\"\n      show \"b$n = c$n\"\n      proof (cases n)\n        case 0\n        from \\<open>?lhs\\<close> have \"(b oo a)$n = (c oo a)$n\"\n          by simp\n        then show ?thesis\n          using 0 by (simp add: fps_compose_nth)\n      next\n        case (Suc n1)\n        have f: \"finite {0 .. n1}\" \"finite {n}\" by simp_all\n        have eq: \"{0 .. n1} \\<union> {n} = {0 .. n}\" using Suc by auto\n        have d: \"{0 .. n1} \\<inter> {n} = {}\" using Suc by auto\n        have seq: \"(\\<Sum>i = 0..n1. b $ i * a ^ i $ n) = (\\<Sum>i = 0..n1. c $ i * a ^ i $ n)\"\n          apply (rule sum.cong)\n          using H Suc\n          apply auto\n          done\n        have th0: \"(b oo a) $n = (\\<Sum>i = 0..n1. c $ i * a ^ i $ n) + b$n * (a$1)^n\"\n          unfolding fps_compose_nth sum.union_disjoint[OF f d, unfolded eq] seq\n          using startsby_zero_power_nth_same[OF a0]\n          by simp\n        have th1: \"(c oo a) $n = (\\<Sum>i = 0..n1. c $ i * a ^ i $ n) + c$n * (a$1)^n\"\n          unfolding fps_compose_nth sum.union_disjoint[OF f d, unfolded eq]\n          using startsby_zero_power_nth_same[OF a0]\n          by simp\n        from \\<open>?lhs\\<close>[unfolded fps_eq_iff, rule_format, of n] th0 th1 a1\n        show ?thesis by auto\n      qed\n    qed\n    then show ?rhs by (simp add: fps_eq_iff)\n  qed\nqed\n\n\nsubsection \\<open>Radicals\\<close>\n\ndeclare prod.cong [fundef_cong]\n\nfunction radical :: \"(nat \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a::field fps \\<Rightarrow> nat \\<Rightarrow> 'a\"\nwhere\n  \"radical r 0 a 0 = 1\"\n| \"radical r 0 a (Suc n) = 0\"\n| \"radical r (Suc k) a 0 = r (Suc k) (a$0)\"\n| \"radical r (Suc k) a (Suc n) =\n    (a$ Suc n - sum (\\<lambda>xs. prod (\\<lambda>j. radical r (Suc k) a (xs ! j)) {0..k})\n      {xs. xs \\<in> natpermute (Suc n) (Suc k) \\<and> Suc n \\<notin> set xs}) /\n    (of_nat (Suc k) * (radical r (Suc k) a 0)^k)\"\n  by pat_completeness auto\n\ntermination radical\nproof\n  let ?R = \"measure (\\<lambda>(r, k, a, n). n)\"\n  {\n    show \"wf ?R\" by auto\n  next\n    fix r k a n xs i\n    assume xs: \"xs \\<in> {xs \\<in> natpermute (Suc n) (Suc k). Suc n \\<notin> set xs}\" and i: \"i \\<in> {0..k}\"\n    have False if c: \"Suc n \\<le> xs ! i\"\n    proof -\n      from xs i have \"xs !i \\<noteq> Suc n\"\n        by (auto simp add: in_set_conv_nth natpermute_def)\n      with c have c': \"Suc n < xs!i\" by arith\n      have fths: \"finite {0 ..< i}\" \"finite {i}\" \"finite {i+1..<Suc k}\"\n        by simp_all\n      have d: \"{0 ..< i} \\<inter> ({i} \\<union> {i+1 ..< Suc k}) = {}\" \"{i} \\<inter> {i+1..< Suc k} = {}\"\n        by auto\n      have eqs: \"{0..<Suc k} = {0 ..< i} \\<union> ({i} \\<union> {i+1 ..< Suc k})\"\n        using i by auto\n      from xs have \"Suc n = sum_list xs\"\n        by (simp add: natpermute_def)\n      also have \"\\<dots> = sum (nth xs) {0..<Suc k}\" using xs\n        by (simp add: natpermute_def sum_list_sum_nth)\n      also have \"\\<dots> = xs!i + sum (nth xs) {0..<i} + sum (nth xs) {i+1..<Suc k}\"\n        unfolding eqs  sum.union_disjoint[OF fths(1) finite_UnI[OF fths(2,3)] d(1)]\n        unfolding sum.union_disjoint[OF fths(2) fths(3) d(2)]\n        by simp\n      finally show ?thesis using c' by simp\n    qed\n    then show \"((r, Suc k, a, xs!i), r, Suc k, a, Suc n) \\<in> ?R\"\n      apply auto\n      apply (metis not_less)\n      done\n  next\n    fix r k a n\n    show \"((r, Suc k, a, 0), r, Suc k, a, Suc n) \\<in> ?R\" by simp\n  }\nqed\n\ndefinition \"fps_radical r n a = Abs_fps (radical r n a)\"\n\nlemma fps_radical0[simp]: \"fps_radical r 0 a = 1\"\n  apply (auto simp add: fps_eq_iff fps_radical_def)\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma fps_radical_nth_0[simp]: \"fps_radical r n a $ 0 = (if n = 0 then 1 else r n (a$0))\"\n  by (cases n) (simp_all add: fps_radical_def)\n\nlemma fps_radical_power_nth[simp]:\n  assumes r: \"(r k (a$0)) ^ k = a$0\"\n  shows \"fps_radical r k a ^ k $ 0 = (if k = 0 then 1 else a$0)\"\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc h)\n  have eq1: \"fps_radical r k a ^ k $ 0 = (\\<Prod>j\\<in>{0..h}. fps_radical r k a $ (replicate k 0) ! j)\"\n    unfolding fps_power_nth Suc by simp\n  also have \"\\<dots> = (\\<Prod>j\\<in>{0..h}. r k (a$0))\"\n    apply (rule prod.cong)\n    apply simp\n    using Suc\n    apply (subgoal_tac \"replicate k 0 ! x = 0\")\n    apply (auto intro: nth_replicate simp del: replicate.simps)\n    done\n  also have \"\\<dots> = a$0\"\n    using r Suc by (simp add: prod_constant)\n  finally show ?thesis\n    using Suc by simp\nqed\n\nlemma power_radical:\n  fixes a:: \"'a::field_char_0 fps\"\n  assumes a0: \"a$0 \\<noteq> 0\"\n  shows \"(r (Suc k) (a$0)) ^ Suc k = a$0 \\<longleftrightarrow> (fps_radical r (Suc k) a) ^ (Suc k) = a\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  let ?r = \"fps_radical r (Suc k) a\"\n  show ?rhs if r0: ?lhs\n  proof -\n    from a0 r0 have r00: \"r (Suc k) (a$0) \\<noteq> 0\" by auto\n    have \"?r ^ Suc k $ z = a$z\" for z\n    proof (induct z rule: nat_less_induct)\n      fix n\n      assume H: \"\\<forall>m<n. ?r ^ Suc k $ m = a$m\"\n      show \"?r ^ Suc k $ n = a $n\"\n      proof (cases n)\n        case 0\n        then show ?thesis\n          using fps_radical_power_nth[of r \"Suc k\" a, OF r0] by simp\n      next\n        case (Suc n1)\n        then have \"n \\<noteq> 0\" by simp\n        let ?Pnk = \"natpermute n (k + 1)\"\n        let ?Pnkn = \"{xs \\<in> ?Pnk. n \\<in> set xs}\"\n        let ?Pnknn = \"{xs \\<in> ?Pnk. n \\<notin> set xs}\"\n        have eq: \"?Pnkn \\<union> ?Pnknn = ?Pnk\" by blast\n        have d: \"?Pnkn \\<inter> ?Pnknn = {}\" by blast\n        have f: \"finite ?Pnkn\" \"finite ?Pnknn\"\n          using finite_Un[of ?Pnkn ?Pnknn, unfolded eq]\n          by (metis natpermute_finite)+\n        let ?f = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. ?r $ v ! j\"\n        have \"sum ?f ?Pnkn = sum (\\<lambda>v. ?r $ n * r (Suc k) (a $ 0) ^ k) ?Pnkn\"\n        proof (rule sum.cong)\n          fix v assume v: \"v \\<in> {xs \\<in> natpermute n (k + 1). n \\<in> set xs}\"\n          let ?ths = \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) =\n            fps_radical r (Suc k) a $ n * r (Suc k) (a $ 0) ^ k\"\n          from v obtain i where i: \"i \\<in> {0..k}\" \"v = replicate (k+1) 0 [i:= n]\"\n            unfolding natpermute_contain_maximal by auto\n          have \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) =\n              (\\<Prod>j\\<in>{0..k}. if j = i then fps_radical r (Suc k) a $ n else r (Suc k) (a$0))\"\n            apply (rule prod.cong, simp)\n            using i r0\n            apply (simp del: replicate.simps)\n            done\n          also have \"\\<dots> = (fps_radical r (Suc k) a $ n) * r (Suc k) (a$0) ^ k\"\n            using i r0 by (simp add: prod_gen_delta)\n          finally show ?ths .\n        qed rule\n        then have \"sum ?f ?Pnkn = of_nat (k+1) * ?r $ n * r (Suc k) (a $ 0) ^ k\"\n          by (simp add: natpermute_max_card[OF \\<open>n \\<noteq> 0\\<close>, simplified])\n        also have \"\\<dots> = a$n - sum ?f ?Pnknn\"\n          unfolding Suc using r00 a0 by (simp add: field_simps fps_radical_def del: of_nat_Suc)\n        finally have fn: \"sum ?f ?Pnkn = a$n - sum ?f ?Pnknn\" .\n        have \"(?r ^ Suc k)$n = sum ?f ?Pnkn + sum ?f ?Pnknn\"\n          unfolding fps_power_nth_Suc sum.union_disjoint[OF f d, unfolded eq] ..\n        also have \"\\<dots> = a$n\" unfolding fn by simp\n        finally show ?thesis .\n      qed\n    qed\n    then show ?thesis using r0 by (simp add: fps_eq_iff)\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that have \"((fps_radical r (Suc k) a) ^ (Suc k))$0 = a$0\"\n      by simp\n    then show ?thesis\n      unfolding fps_power_nth_Suc\n      by (simp add: prod_constant del: replicate.simps)\n  qed\nqed\n\n(*\nlemma power_radical:\n  fixes a:: \"'a::field_char_0 fps\"\n  assumes r0: \"(r (Suc k) (a$0)) ^ Suc k = a$0\" and a0: \"a$0 \\<noteq> 0\"\n  shows \"(fps_radical r (Suc k) a) ^ (Suc k) = a\"\nproof-\n  let ?r = \"fps_radical r (Suc k) a\"\n  from a0 r0 have r00: \"r (Suc k) (a$0) \\<noteq> 0\" by auto\n  {fix z have \"?r ^ Suc k $ z = a$z\"\n    proof(induct z rule: nat_less_induct)\n      fix n assume H: \"\\<forall>m<n. ?r ^ Suc k $ m = a$m\"\n      {assume \"n = 0\" then have \"?r ^ Suc k $ n = a $n\"\n          using fps_radical_power_nth[of r \"Suc k\" a, OF r0] by simp}\n      moreover\n      {fix n1 assume n1: \"n = Suc n1\"\n        have fK: \"finite {0..k}\" by simp\n        have nz: \"n \\<noteq> 0\" using n1 by arith\n        let ?Pnk = \"natpermute n (k + 1)\"\n        let ?Pnkn = \"{xs \\<in> ?Pnk. n \\<in> set xs}\"\n        let ?Pnknn = \"{xs \\<in> ?Pnk. n \\<notin> set xs}\"\n        have eq: \"?Pnkn \\<union> ?Pnknn = ?Pnk\" by blast\n        have d: \"?Pnkn \\<inter> ?Pnknn = {}\" by blast\n        have f: \"finite ?Pnkn\" \"finite ?Pnknn\"\n          using finite_Un[of ?Pnkn ?Pnknn, unfolded eq]\n          by (metis natpermute_finite)+\n        let ?f = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. ?r $ v ! j\"\n        have \"sum ?f ?Pnkn = sum (\\<lambda>v. ?r $ n * r (Suc k) (a $ 0) ^ k) ?Pnkn\"\n        proof(rule sum.cong2)\n          fix v assume v: \"v \\<in> {xs \\<in> natpermute n (k + 1). n \\<in> set xs}\"\n          let ?ths = \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) = fps_radical r (Suc k) a $ n * r (Suc k) (a $ 0) ^ k\"\n          from v obtain i where i: \"i \\<in> {0..k}\" \"v = replicate (k+1) 0 [i:= n]\"\n            unfolding natpermute_contain_maximal by auto\n          have \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) = (\\<Prod>j\\<in>{0..k}. if j = i then fps_radical r (Suc k) a $ n else r (Suc k) (a$0))\"\n            apply (rule prod.cong, simp)\n            using i r0 by (simp del: replicate.simps)\n          also have \"\\<dots> = (fps_radical r (Suc k) a $ n) * r (Suc k) (a$0) ^ k\"\n            unfolding prod_gen_delta[OF fK] using i r0 by simp\n          finally show ?ths .\n        qed\n        then have \"sum ?f ?Pnkn = of_nat (k+1) * ?r $ n * r (Suc k) (a $ 0) ^ k\"\n          by (simp add: natpermute_max_card[OF nz, simplified])\n        also have \"\\<dots> = a$n - sum ?f ?Pnknn\"\n          unfolding n1 using r00 a0 by (simp add: field_simps fps_radical_def del: of_nat_Suc )\n        finally have fn: \"sum ?f ?Pnkn = a$n - sum ?f ?Pnknn\" .\n        have \"(?r ^ Suc k)$n = sum ?f ?Pnkn + sum ?f ?Pnknn\"\n          unfolding fps_power_nth_Suc sum.union_disjoint[OF f d, unfolded eq] ..\n        also have \"\\<dots> = a$n\" unfolding fn by simp\n        finally have \"?r ^ Suc k $ n = a $n\" .}\n      ultimately  show \"?r ^ Suc k $ n = a $n\" by (cases n, auto)\n  qed }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\n*)\nlemma eq_divide_imp':\n  fixes c :: \"'a::field\"\n  shows \"c \\<noteq> 0 \\<Longrightarrow> a * c = b \\<Longrightarrow> a = b / c\"\n  by (simp add: field_simps)\n\nlemma radical_unique:\n  assumes r0: \"(r (Suc k) (b$0)) ^ Suc k = b$0\"\n    and a0: \"r (Suc k) (b$0 ::'a::field_char_0) = a$0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"a^(Suc k) = b \\<longleftrightarrow> a = fps_radical r (Suc k) b\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\" is \"_ \\<longleftrightarrow> a = ?r\")\nproof\n  show ?lhs if ?rhs\n    using that using power_radical[OF b0, of r k, unfolded r0] by simp\n  show ?rhs if ?lhs\n  proof -\n    have r00: \"r (Suc k) (b$0) \\<noteq> 0\" using b0 r0 by auto\n    have ceq: \"card {0..k} = Suc k\" by simp\n    from a0 have a0r0: \"a$0 = ?r$0\" by simp\n    have \"a $ n = ?r $ n\" for n\n    proof (induct n rule: nat_less_induct)\n      fix n\n      assume h: \"\\<forall>m<n. a$m = ?r $m\"\n      show \"a$n = ?r $ n\"\n      proof (cases n)\n        case 0\n        then show ?thesis using a0 by simp\n      next\n        case (Suc n1)\n        have fK: \"finite {0..k}\" by simp\n        have nz: \"n \\<noteq> 0\" using Suc by simp\n        let ?Pnk = \"natpermute n (Suc k)\"\n        let ?Pnkn = \"{xs \\<in> ?Pnk. n \\<in> set xs}\"\n        let ?Pnknn = \"{xs \\<in> ?Pnk. n \\<notin> set xs}\"\n        have eq: \"?Pnkn \\<union> ?Pnknn = ?Pnk\" by blast\n        have d: \"?Pnkn \\<inter> ?Pnknn = {}\" by blast\n        have f: \"finite ?Pnkn\" \"finite ?Pnknn\"\n          using finite_Un[of ?Pnkn ?Pnknn, unfolded eq]\n          by (metis natpermute_finite)+\n        let ?f = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. ?r $ v ! j\"\n        let ?g = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. a $ v ! j\"\n        have \"sum ?g ?Pnkn = sum (\\<lambda>v. a $ n * (?r$0)^k) ?Pnkn\"\n        proof (rule sum.cong)\n          fix v\n          assume v: \"v \\<in> {xs \\<in> natpermute n (Suc k). n \\<in> set xs}\"\n          let ?ths = \"(\\<Prod>j\\<in>{0..k}. a $ v ! j) = a $ n * (?r$0)^k\"\n          from v obtain i where i: \"i \\<in> {0..k}\" \"v = replicate (k+1) 0 [i:= n]\"\n            unfolding Suc_eq_plus1 natpermute_contain_maximal\n            by (auto simp del: replicate.simps)\n          have \"(\\<Prod>j\\<in>{0..k}. a $ v ! j) = (\\<Prod>j\\<in>{0..k}. if j = i then a $ n else r (Suc k) (b$0))\"\n            apply (rule prod.cong, simp)\n            using i a0\n            apply (simp del: replicate.simps)\n            done\n          also have \"\\<dots> = a $ n * (?r $ 0)^k\"\n            using i by (simp add: prod_gen_delta)\n          finally show ?ths .\n        qed rule\n        then have th0: \"sum ?g ?Pnkn = of_nat (k+1) * a $ n * (?r $ 0)^k\"\n          by (simp add: natpermute_max_card[OF nz, simplified])\n        have th1: \"sum ?g ?Pnknn = sum ?f ?Pnknn\"\n        proof (rule sum.cong, rule refl, rule prod.cong, simp)\n          fix xs i\n          assume xs: \"xs \\<in> ?Pnknn\" and i: \"i \\<in> {0..k}\"\n          have False if c: \"n \\<le> xs ! i\"\n          proof -\n            from xs i have \"xs ! i \\<noteq> n\"\n              by (auto simp add: in_set_conv_nth natpermute_def)\n            with c have c': \"n < xs!i\" by arith\n            have fths: \"finite {0 ..< i}\" \"finite {i}\" \"finite {i+1..<Suc k}\"\n              by simp_all\n            have d: \"{0 ..< i} \\<inter> ({i} \\<union> {i+1 ..< Suc k}) = {}\" \"{i} \\<inter> {i+1..< Suc k} = {}\"\n              by auto\n            have eqs: \"{0..<Suc k} = {0 ..< i} \\<union> ({i} \\<union> {i+1 ..< Suc k})\"\n              using i by auto\n            from xs have \"n = sum_list xs\"\n              by (simp add: natpermute_def)\n            also have \"\\<dots> = sum (nth xs) {0..<Suc k}\"\n              using xs by (simp add: natpermute_def sum_list_sum_nth)\n            also have \"\\<dots> = xs!i + sum (nth xs) {0..<i} + sum (nth xs) {i+1..<Suc k}\"\n              unfolding eqs  sum.union_disjoint[OF fths(1) finite_UnI[OF fths(2,3)] d(1)]\n              unfolding sum.union_disjoint[OF fths(2) fths(3) d(2)]\n              by simp\n            finally show ?thesis using c' by simp\n          qed\n          then have thn: \"xs!i < n\" by presburger\n          from h[rule_format, OF thn] show \"a$(xs !i) = ?r$(xs!i)\" .\n        qed\n        have th00: \"\\<And>x::'a. of_nat (Suc k) * (x * inverse (of_nat (Suc k))) = x\"\n          by (simp add: field_simps del: of_nat_Suc)\n        from \\<open>?lhs\\<close> have \"b$n = a^Suc k $ n\"\n          by (simp add: fps_eq_iff)\n        also have \"a ^ Suc k$n = sum ?g ?Pnkn + sum ?g ?Pnknn\"\n          unfolding fps_power_nth_Suc\n          using sum.union_disjoint[OF f d, unfolded Suc_eq_plus1[symmetric],\n            unfolded eq, of ?g] by simp\n        also have \"\\<dots> = of_nat (k+1) * a $ n * (?r $ 0)^k + sum ?f ?Pnknn\"\n          unfolding th0 th1 ..\n        finally have \"of_nat (k+1) * a $ n * (?r $ 0)^k = b$n - sum ?f ?Pnknn\"\n          by simp\n        then have \"a$n = (b$n - sum ?f ?Pnknn) / (of_nat (k+1) * (?r $ 0)^k)\"\n          apply -\n          apply (rule eq_divide_imp')\n          using r00\n          apply (simp del: of_nat_Suc)\n          apply (simp add: ac_simps)\n          done\n        then show ?thesis\n          apply (simp del: of_nat_Suc)\n          unfolding fps_radical_def Suc\n          apply (simp add: field_simps Suc th00 del: of_nat_Suc)\n          done\n      qed\n    qed\n    then show ?rhs by (simp add: fps_eq_iff)\n  qed\nqed\n\n\nlemma radical_power:\n  assumes r0: \"r (Suc k) ((a$0) ^ Suc k) = a$0\"\n    and a0: \"(a$0 :: 'a::field_char_0) \\<noteq> 0\"\n  shows \"(fps_radical r (Suc k) (a ^ Suc k)) = a\"\nproof -\n  let ?ak = \"a^ Suc k\"\n  have ak0: \"?ak $ 0 = (a$0) ^ Suc k\"\n    by (simp add: fps_nth_power_0 del: power_Suc)\n  from r0 have th0: \"r (Suc k) (a ^ Suc k $ 0) ^ Suc k = a ^ Suc k $ 0\"\n    using ak0 by auto\n  from r0 ak0 have th1: \"r (Suc k) (a ^ Suc k $ 0) = a $ 0\"\n    by auto\n  from ak0 a0 have ak00: \"?ak $ 0 \\<noteq>0 \"\n    by auto\n  from radical_unique[of r k ?ak a, OF th0 th1 ak00] show ?thesis\n    by metis\nqed\n\nlemma fps_deriv_radical:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes r0: \"(r (Suc k) (a$0)) ^ Suc k = a$0\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_deriv (fps_radical r (Suc k) a) =\n    fps_deriv a / (fps_const (of_nat (Suc k)) * (fps_radical r (Suc k) a) ^ k)\"\nproof -\n  let ?r = \"fps_radical r (Suc k) a\"\n  let ?w = \"(fps_const (of_nat (Suc k)) * ?r ^ k)\"\n  from a0 r0 have r0': \"r (Suc k) (a$0) \\<noteq> 0\"\n    by auto\n  from r0' have w0: \"?w $ 0 \\<noteq> 0\"\n    by (simp del: of_nat_Suc)\n  note th0 = inverse_mult_eq_1[OF w0]\n  let ?iw = \"inverse ?w\"\n  from iffD1[OF power_radical[of a r], OF a0 r0]\n  have \"fps_deriv (?r ^ Suc k) = fps_deriv a\"\n    by simp\n  then have \"fps_deriv ?r * ?w = fps_deriv a\"\n    by (simp add: fps_deriv_power ac_simps del: power_Suc)\n  then have \"?iw * fps_deriv ?r * ?w = ?iw * fps_deriv a\"\n    by simp\n  with a0 r0 have \"fps_deriv ?r * (?iw * ?w) = fps_deriv a / ?w\"\n    by (subst fps_divide_unit) (auto simp del: of_nat_Suc)\n  then show ?thesis unfolding th0 by simp\nqed\n\nlemma radical_mult_distrib:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes k: \"k > 0\"\n    and ra0: \"r k (a $ 0) ^ k = a $ 0\"\n    and rb0: \"r k (b $ 0) ^ k = b $ 0\"\n    and a0: \"a $ 0 \\<noteq> 0\"\n    and b0: \"b $ 0 \\<noteq> 0\"\n  shows \"r k ((a * b) $ 0) = r k (a $ 0) * r k (b $ 0) \\<longleftrightarrow>\n    fps_radical r k (a * b) = fps_radical r k a * fps_radical r k b\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if r0': ?lhs\n  proof -\n    from r0' have r0: \"(r k ((a * b) $ 0)) ^ k = (a * b) $ 0\"\n      by (simp add: fps_mult_nth ra0 rb0 power_mult_distrib)\n    show ?thesis\n    proof (cases k)\n      case 0\n      then show ?thesis using r0' by simp\n    next\n      case (Suc h)\n      let ?ra = \"fps_radical r (Suc h) a\"\n      let ?rb = \"fps_radical r (Suc h) b\"\n      have th0: \"r (Suc h) ((a * b) $ 0) = (fps_radical r (Suc h) a * fps_radical r (Suc h) b) $ 0\"\n        using r0' Suc by (simp add: fps_mult_nth)\n      have ab0: \"(a*b) $ 0 \\<noteq> 0\"\n        using a0 b0 by (simp add: fps_mult_nth)\n      from radical_unique[of r h \"a*b\" \"fps_radical r (Suc h) a * fps_radical r (Suc h) b\", OF r0[unfolded Suc] th0 ab0, symmetric]\n        iffD1[OF power_radical[of _ r], OF a0 ra0[unfolded Suc]] iffD1[OF power_radical[of _ r], OF b0 rb0[unfolded Suc]] Suc r0'\n      show ?thesis\n        by (auto simp add: power_mult_distrib simp del: power_Suc)\n    qed\n  qed\n  show ?lhs if ?rhs\n  proof -\n    from that have \"(fps_radical r k (a * b)) $ 0 = (fps_radical r k a * fps_radical r k b) $ 0\"\n      by simp\n    then show ?thesis\n      using k by (simp add: fps_mult_nth)\n  qed\nqed\n\n(*\nlemma radical_mult_distrib:\n  fixes a:: \"'a::field_char_0 fps\"\n  assumes\n  ra0: \"r k (a $ 0) ^ k = a $ 0\"\n  and rb0: \"r k (b $ 0) ^ k = b $ 0\"\n  and r0': \"r k ((a * b) $ 0) = r k (a $ 0) * r k (b $ 0)\"\n  and a0: \"a$0 \\<noteq> 0\"\n  and b0: \"b$0 \\<noteq> 0\"\n  shows \"fps_radical r (k) (a*b) = fps_radical r (k) a * fps_radical r (k) (b)\"\nproof-\n  from r0' have r0: \"(r (k) ((a*b)$0)) ^ k = (a*b)$0\"\n    by (simp add: fps_mult_nth ra0 rb0 power_mult_distrib)\n  {assume \"k=0\" then have ?thesis by simp}\n  moreover\n  {fix h assume k: \"k = Suc h\"\n  let ?ra = \"fps_radical r (Suc h) a\"\n  let ?rb = \"fps_radical r (Suc h) b\"\n  have th0: \"r (Suc h) ((a * b) $ 0) = (fps_radical r (Suc h) a * fps_radical r (Suc h) b) $ 0\"\n    using r0' k by (simp add: fps_mult_nth)\n  have ab0: \"(a*b) $ 0 \\<noteq> 0\" using a0 b0 by (simp add: fps_mult_nth)\n  from radical_unique[of r h \"a*b\" \"fps_radical r (Suc h) a * fps_radical r (Suc h) b\", OF r0[unfolded k] th0 ab0, symmetric]\n    power_radical[of r, OF ra0[unfolded k] a0] power_radical[of r, OF rb0[unfolded k] b0] k\n  have ?thesis by (auto simp add: power_mult_distrib simp del: power_Suc)}\nultimately show ?thesis by (cases k, auto)\nqed\n*)\n\nlemma fps_divide_1 [simp]: \"(a :: 'a::field fps) / 1 = a\"\n  by (fact div_by_1)\n\nlemma radical_divide:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes kp: \"k > 0\"\n    and ra0: \"(r k (a $ 0)) ^ k = a $ 0\"\n    and rb0: \"(r k (b $ 0)) ^ k = b $ 0\"\n    and a0: \"a$0 \\<noteq> 0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"r k ((a $ 0) / (b$0)) = r k (a$0) / r k (b $ 0) \\<longleftrightarrow>\n    fps_radical r k (a/b) = fps_radical r k a / fps_radical r k b\"\n  (is \"?lhs = ?rhs\")\nproof\n  let ?r = \"fps_radical r k\"\n  from kp obtain h where k: \"k = Suc h\"\n    by (cases k) auto\n  have ra0': \"r k (a$0) \\<noteq> 0\" using a0 ra0 k by auto\n  have rb0': \"r k (b$0) \\<noteq> 0\" using b0 rb0 k by auto\n\n  show ?lhs if ?rhs\n  proof -\n    from that have \"?r (a/b) $ 0 = (?r a / ?r b)$0\"\n      by simp\n    then show ?thesis\n      using k a0 b0 rb0' by (simp add: fps_divide_unit fps_mult_nth fps_inverse_def divide_inverse)\n  qed\n  show ?rhs if ?lhs\n  proof -\n    from a0 b0 have ab0[simp]: \"(a/b)$0 = a$0 / b$0\"\n      by (simp add: fps_divide_def fps_mult_nth divide_inverse fps_inverse_def)\n    have th0: \"r k ((a/b)$0) ^ k = (a/b)$0\"\n      by (simp add: \\<open>?lhs\\<close> power_divide ra0 rb0)\n    from a0 b0 ra0' rb0' kp \\<open>?lhs\\<close>\n    have th1: \"r k ((a / b) $ 0) = (fps_radical r k a / fps_radical r k b) $ 0\"\n      by (simp add: fps_divide_unit fps_mult_nth fps_inverse_def divide_inverse)\n    from a0 b0 ra0' rb0' kp have ab0': \"(a / b) $ 0 \\<noteq> 0\"\n      by (simp add: fps_divide_unit fps_mult_nth fps_inverse_def nonzero_imp_inverse_nonzero)\n    note tha[simp] = iffD1[OF power_radical[where r=r and k=h], OF a0 ra0[unfolded k], unfolded k[symmetric]]\n    note thb[simp] = iffD1[OF power_radical[where r=r and k=h], OF b0 rb0[unfolded k], unfolded k[symmetric]]\n    from b0 rb0' have th2: \"(?r a / ?r b)^k = a/b\"\n      by (simp add: fps_divide_unit power_mult_distrib fps_inverse_power[symmetric])\n\n    from iffD1[OF radical_unique[where r=r and a=\"?r a / ?r b\" and b=\"a/b\" and k=h], symmetric, unfolded k[symmetric], OF th0 th1 ab0' th2]\n    show ?thesis .\n  qed\nqed\n\nlemma radical_inverse:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes k: \"k > 0\"\n    and ra0: \"r k (a $ 0) ^ k = a $ 0\"\n    and r1: \"(r k 1)^k = 1\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"r k (inverse (a $ 0)) = r k 1 / (r k (a $ 0)) \\<longleftrightarrow>\n    fps_radical r k (inverse a) = fps_radical r k 1 / fps_radical r k a\"\n  using radical_divide[where k=k and r=r and a=1 and b=a, OF k ] ra0 r1 a0\n  by (simp add: divide_inverse fps_divide_def)\n\n\nsubsection \\<open>Derivative of composition\\<close>\n\nlemma fps_compose_deriv:\n  fixes a :: \"'a::idom fps\"\n  assumes b0: \"b$0 = 0\"\n  shows \"fps_deriv (a oo b) = ((fps_deriv a) oo b) * fps_deriv b\"\nproof -\n  have \"(fps_deriv (a oo b))$n = (((fps_deriv a) oo b) * (fps_deriv b)) $n\" for n\n  proof -\n    have \"(fps_deriv (a oo b))$n = sum (\\<lambda>i. a $ i * (fps_deriv (b^i))$n) {0.. Suc n}\"\n      by (simp add: fps_compose_def field_simps sum_distrib_left del: of_nat_Suc)\n    also have \"\\<dots> = sum (\\<lambda>i. a$i * ((fps_const (of_nat i)) * (fps_deriv b * (b^(i - 1))))$n) {0.. Suc n}\"\n      by (simp add: field_simps fps_deriv_power del: fps_mult_left_const_nth of_nat_Suc)\n    also have \"\\<dots> = sum (\\<lambda>i. of_nat i * a$i * (((b^(i - 1)) * fps_deriv b))$n) {0.. Suc n}\"\n      unfolding fps_mult_left_const_nth  by (simp add: field_simps)\n    also have \"\\<dots> = sum (\\<lambda>i. of_nat i * a$i * (sum (\\<lambda>j. (b^ (i - 1))$j * (fps_deriv b)$(n - j)) {0..n})) {0.. Suc n}\"\n      unfolding fps_mult_nth ..\n    also have \"\\<dots> = sum (\\<lambda>i. of_nat i * a$i * (sum (\\<lambda>j. (b^ (i - 1))$j * (fps_deriv b)$(n - j)) {0..n})) {1.. Suc n}\"\n      apply (rule sum.mono_neutral_right)\n      apply (auto simp add: mult_delta_left sum.delta not_le)\n      done\n    also have \"\\<dots> = sum (\\<lambda>i. of_nat (i + 1) * a$(i+1) * (sum (\\<lambda>j. (b^ i)$j * of_nat (n - j + 1) * b$(n - j + 1)) {0..n})) {0.. n}\"\n      unfolding fps_deriv_nth\n      by (rule sum.reindex_cong [of Suc]) (auto simp add: mult.assoc)\n    finally have th0: \"(fps_deriv (a oo b))$n =\n      sum (\\<lambda>i. of_nat (i + 1) * a$(i+1) * (sum (\\<lambda>j. (b^ i)$j * of_nat (n - j + 1) * b$(n - j + 1)) {0..n})) {0.. n}\" .\n\n    have \"(((fps_deriv a) oo b) * (fps_deriv b))$n = sum (\\<lambda>i. (fps_deriv b)$ (n - i) * ((fps_deriv a) oo b)$i) {0..n}\"\n      unfolding fps_mult_nth by (simp add: ac_simps)\n    also have \"\\<dots> = sum (\\<lambda>i. sum (\\<lambda>j. of_nat (n - i +1) * b$(n - i + 1) * of_nat (j + 1) * a$(j+1) * (b^j)$i) {0..n}) {0..n}\"\n      unfolding fps_deriv_nth fps_compose_nth sum_distrib_left mult.assoc\n      apply (rule sum.cong)\n      apply (rule refl)\n      apply (rule sum.mono_neutral_left)\n      apply (simp_all add: subset_eq)\n      apply clarify\n      apply (subgoal_tac \"b^i$x = 0\")\n      apply simp\n      apply (rule startsby_zero_power_prefix[OF b0, rule_format])\n      apply simp\n      done\n    also have \"\\<dots> = sum (\\<lambda>i. of_nat (i + 1) * a$(i+1) * (sum (\\<lambda>j. (b^ i)$j * of_nat (n - j + 1) * b$(n - j + 1)) {0..n})) {0.. n}\"\n      unfolding sum_distrib_left\n      apply (subst sum.commute)\n      apply (rule sum.cong, rule refl)+\n      apply simp\n      done\n    finally show ?thesis\n      unfolding th0 by simp\n  qed\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\nlemma fps_mult_X_plus_1_nth:\n  \"((1+X)*a) $n = (if n = 0 then (a$n :: 'a::comm_ring_1) else a$n + a$(n - 1))\"\nproof (cases n)\n  case 0\n  then show ?thesis\n    by (simp add: fps_mult_nth)\nnext\n  case (Suc m)\n  have \"((1 + X)*a) $ n = sum (\\<lambda>i. (1 + X) $ i * a $ (n - i)) {0..n}\"\n    by (simp add: fps_mult_nth)\n  also have \"\\<dots> = sum (\\<lambda>i. (1+X)$i * a$(n-i)) {0.. 1}\"\n    unfolding Suc by (rule sum.mono_neutral_right) auto\n  also have \"\\<dots> = (if n = 0 then (a$n :: 'a::comm_ring_1) else a$n + a$(n - 1))\"\n    by (simp add: Suc)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Finite FPS (i.e. polynomials) and X\\<close>\n\nlemma fps_poly_sum_X:\n  assumes \"\\<forall>i > n. a$i = (0::'a::comm_ring_1)\"\n  shows \"a = sum (\\<lambda>i. fps_const (a$i) * X^i) {0..n}\" (is \"a = ?r\")\nproof -\n  have \"a$i = ?r$i\" for i\n    unfolding fps_sum_nth fps_mult_left_const_nth X_power_nth\n    by (simp add: mult_delta_right sum.delta' assms)\n  then show ?thesis\n    unfolding fps_eq_iff by blast\nqed\n\n\nsubsection \\<open>Compositional inverses\\<close>\n\nfun compinv :: \"'a fps \\<Rightarrow> nat \\<Rightarrow> 'a::field\"\nwhere\n  \"compinv a 0 = X$0\"\n| \"compinv a (Suc n) =\n    (X$ Suc n - sum (\\<lambda>i. (compinv a i) * (a^i)$Suc n) {0 .. n}) / (a$1) ^ Suc n\"\n\ndefinition \"fps_inv a = Abs_fps (compinv a)\"\n\nlemma fps_inv:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_inv a oo a = X\"\nproof -\n  let ?i = \"fps_inv a oo a\"\n  have \"?i $n = X$n\" for n\n  proof (induct n rule: nat_less_induct)\n    fix n\n    assume h: \"\\<forall>m<n. ?i$m = X$m\"\n    show \"?i $ n = X$n\"\n    proof (cases n)\n      case 0\n      then show ?thesis using a0\n        by (simp add: fps_compose_nth fps_inv_def)\n    next\n      case (Suc n1)\n      have \"?i $ n = sum (\\<lambda>i. (fps_inv a $ i) * (a^i)$n) {0 .. n1} + fps_inv a $ Suc n1 * (a $ 1)^ Suc n1\"\n        by (simp only: fps_compose_nth) (simp add: Suc startsby_zero_power_nth_same [OF a0] del: power_Suc)\n      also have \"\\<dots> = sum (\\<lambda>i. (fps_inv a $ i) * (a^i)$n) {0 .. n1} +\n        (X$ Suc n1 - sum (\\<lambda>i. (fps_inv a $ i) * (a^i)$n) {0 .. n1})\"\n        using a0 a1 Suc by (simp add: fps_inv_def)\n      also have \"\\<dots> = X$n\" using Suc by simp\n      finally show ?thesis .\n    qed\n  qed\n  then show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\n\nfun gcompinv :: \"'a fps \\<Rightarrow> 'a fps \\<Rightarrow> nat \\<Rightarrow> 'a::field\"\nwhere\n  \"gcompinv b a 0 = b$0\"\n| \"gcompinv b a (Suc n) =\n    (b$ Suc n - sum (\\<lambda>i. (gcompinv b a i) * (a^i)$Suc n) {0 .. n}) / (a$1) ^ Suc n\"\n\ndefinition \"fps_ginv b a = Abs_fps (gcompinv b a)\"\n\nlemma fps_ginv:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_ginv b a oo a = b\"\nproof -\n  let ?i = \"fps_ginv b a oo a\"\n  have \"?i $n = b$n\" for n\n  proof (induct n rule: nat_less_induct)\n    fix n\n    assume h: \"\\<forall>m<n. ?i$m = b$m\"\n    show \"?i $ n = b$n\"\n    proof (cases n)\n      case 0\n      then show ?thesis using a0\n        by (simp add: fps_compose_nth fps_ginv_def)\n    next\n      case (Suc n1)\n      have \"?i $ n = sum (\\<lambda>i. (fps_ginv b a $ i) * (a^i)$n) {0 .. n1} + fps_ginv b a $ Suc n1 * (a $ 1)^ Suc n1\"\n        by (simp only: fps_compose_nth) (simp add: Suc startsby_zero_power_nth_same [OF a0] del: power_Suc)\n      also have \"\\<dots> = sum (\\<lambda>i. (fps_ginv b a $ i) * (a^i)$n) {0 .. n1} +\n        (b$ Suc n1 - sum (\\<lambda>i. (fps_ginv b a $ i) * (a^i)$n) {0 .. n1})\"\n        using a0 a1 Suc by (simp add: fps_ginv_def)\n      also have \"\\<dots> = b$n\" using Suc by simp\n      finally show ?thesis .\n    qed\n  qed\n  then show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\nlemma fps_inv_ginv: \"fps_inv = fps_ginv X\"\n  apply (auto simp add: fun_eq_iff fps_eq_iff fps_inv_def fps_ginv_def)\n  apply (induct_tac n rule: nat_less_induct)\n  apply auto\n  apply (case_tac na)\n  apply simp\n  apply simp\n  done\n\nlemma fps_compose_1[simp]: \"1 oo a = 1\"\n  by (simp add: fps_eq_iff fps_compose_nth mult_delta_left sum.delta)\n\nlemma fps_compose_0[simp]: \"0 oo a = 0\"\n  by (simp add: fps_eq_iff fps_compose_nth)\n\nlemma fps_compose_0_right[simp]: \"a oo 0 = fps_const (a $ 0)\"\n  by (auto simp add: fps_eq_iff fps_compose_nth power_0_left sum.neutral)\n\nlemma fps_compose_add_distrib: \"(a + b) oo c = (a oo c) + (b oo c)\"\n  by (simp add: fps_eq_iff fps_compose_nth field_simps sum.distrib)\n\nlemma fps_compose_sum_distrib: \"(sum f S) oo a = sum (\\<lambda>i. f i oo a) S\"\nproof (cases \"finite S\")\n  case True\n  show ?thesis\n  proof (rule finite_induct[OF True])\n    show \"sum f {} oo a = (\\<Sum>i\\<in>{}. f i oo a)\"\n      by simp\n  next\n    fix x F\n    assume fF: \"finite F\"\n      and xF: \"x \\<notin> F\"\n      and h: \"sum f F oo a = sum (\\<lambda>i. f i oo a) F\"\n    show \"sum f (insert x F) oo a  = sum (\\<lambda>i. f i oo a) (insert x F)\"\n      using fF xF h by (simp add: fps_compose_add_distrib)\n  qed\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma convolution_eq:\n  \"sum (\\<lambda>i. a (i :: nat) * b (n - i)) {0 .. n} =\n    sum (\\<lambda>(i,j). a i * b j) {(i,j). i \\<le> n \\<and> j \\<le> n \\<and> i + j = n}\"\n  by (rule sum.reindex_bij_witness[where i=fst and j=\"\\<lambda>i. (i, n - i)\"]) auto\n\nlemma product_composition_lemma:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n    and d0: \"d$0 = 0\"\n  shows \"((a oo c) * (b oo d))$n =\n    sum (\\<lambda>(k,m). a$k * b$m * (c^k * d^m) $ n) {(k,m). k + m \\<le> n}\"  (is \"?l = ?r\")\nproof -\n  let ?S = \"{(k::nat, m::nat). k + m \\<le> n}\"\n  have s: \"?S \\<subseteq> {0..n} \\<times> {0..n}\" by (auto simp add: subset_eq)\n  have f: \"finite {(k::nat, m::nat). k + m \\<le> n}\"\n    apply (rule finite_subset[OF s])\n    apply auto\n    done\n  have \"?r =  sum (\\<lambda>i. sum (\\<lambda>(k,m). a$k * (c^k)$i * b$m * (d^m) $ (n - i)) {(k,m). k + m \\<le> n}) {0..n}\"\n    apply (simp add: fps_mult_nth sum_distrib_left)\n    apply (subst sum.commute)\n    apply (rule sum.cong)\n    apply (auto simp add: field_simps)\n    done\n  also have \"\\<dots> = ?l\"\n    apply (simp add: fps_mult_nth fps_compose_nth sum_product)\n    apply (rule sum.cong)\n    apply (rule refl)\n    apply (simp add: sum.cartesian_product mult.assoc)\n    apply (rule sum.mono_neutral_right[OF f])\n    apply (simp add: subset_eq)\n    apply presburger\n    apply clarsimp\n    apply (rule ccontr)\n    apply (clarsimp simp add: not_le)\n    apply (case_tac \"x < aa\")\n    apply simp\n    apply (frule_tac startsby_zero_power_prefix[rule_format, OF c0])\n    apply blast\n    apply simp\n    apply (frule_tac startsby_zero_power_prefix[rule_format, OF d0])\n    apply blast\n    done\n  finally show ?thesis by simp\nqed\n\nlemma product_composition_lemma':\n  assumes c0: \"c$0 = (0::'a::idom)\"\n    and d0: \"d$0 = 0\"\n  shows \"((a oo c) * (b oo d))$n =\n    sum (\\<lambda>k. sum (\\<lambda>m. a$k * b$m * (c^k * d^m) $ n) {0..n}) {0..n}\"  (is \"?l = ?r\")\n  unfolding product_composition_lemma[OF c0 d0]\n  unfolding sum.cartesian_product\n  apply (rule sum.mono_neutral_left)\n  apply simp\n  apply (clarsimp simp add: subset_eq)\n  apply clarsimp\n  apply (rule ccontr)\n  apply (subgoal_tac \"(c^aa * d^ba) $ n = 0\")\n  apply simp\n  unfolding fps_mult_nth\n  apply (rule sum.neutral)\n  apply (clarsimp simp add: not_le)\n  apply (case_tac \"x < aa\")\n  apply (rule startsby_zero_power_prefix[OF c0, rule_format])\n  apply simp\n  apply (subgoal_tac \"n - x < ba\")\n  apply (frule_tac k = \"ba\" in startsby_zero_power_prefix[OF d0, rule_format])\n  apply simp\n  apply arith\n  done\n\n\nlemma sum_pair_less_iff:\n  \"sum (\\<lambda>((k::nat),m). a k * b m * c (k + m)) {(k,m). k + m \\<le> n} =\n    sum (\\<lambda>s. sum (\\<lambda>i. a i * b (s - i) * c s) {0..s}) {0..n}\"\n  (is \"?l = ?r\")\nproof -\n  let ?KM = \"{(k,m). k + m \\<le> n}\"\n  let ?f = \"\\<lambda>s. UNION {(0::nat)..s} (\\<lambda>i. {(i,s - i)})\"\n  have th0: \"?KM = UNION {0..n} ?f\"\n    by auto\n  show \"?l = ?r \"\n    unfolding th0\n    apply (subst sum.UNION_disjoint)\n    apply auto\n    apply (subst sum.UNION_disjoint)\n    apply auto\n    done\nqed\n\nlemma fps_compose_mult_distrib_lemma:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n  shows \"((a oo c) * (b oo c))$n = sum (\\<lambda>s. sum (\\<lambda>i. a$i * b$(s - i) * (c^s) $ n) {0..s}) {0..n}\"\n  unfolding product_composition_lemma[OF c0 c0] power_add[symmetric]\n  unfolding sum_pair_less_iff[where a = \"\\<lambda>k. a$k\" and b=\"\\<lambda>m. b$m\" and c=\"\\<lambda>s. (c ^ s)$n\" and n = n] ..\n\nlemma fps_compose_mult_distrib:\n  assumes c0: \"c $ 0 = (0::'a::idom)\"\n  shows \"(a * b) oo c = (a oo c) * (b oo c)\"\n  apply (simp add: fps_eq_iff fps_compose_mult_distrib_lemma [OF c0])\n  apply (simp add: fps_compose_nth fps_mult_nth sum_distrib_right)\n  done\n\nlemma fps_compose_prod_distrib:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n  shows \"prod a S oo c = prod (\\<lambda>k. a k oo c) S\"\n  apply (cases \"finite S\")\n  apply simp_all\n  apply (induct S rule: finite_induct)\n  apply simp\n  apply (simp add: fps_compose_mult_distrib[OF c0])\n  done\n\nlemma fps_compose_divide:\n  assumes [simp]: \"g dvd f\" \"h $ 0 = 0\"\n  shows   \"fps_compose f h = fps_compose (f / g :: 'a :: field fps) h * fps_compose g h\"\nproof -\n  have \"f = (f / g) * g\" by simp\n  also have \"fps_compose \\<dots> h = fps_compose (f / g) h * fps_compose g h\"\n    by (subst fps_compose_mult_distrib) simp_all\n  finally show ?thesis .\nqed\n\nlemma fps_compose_divide_distrib:\n  assumes \"g dvd f\" \"h $ 0 = 0\" \"fps_compose g h \\<noteq> 0\"\n  shows   \"fps_compose (f / g :: 'a :: field fps) h = fps_compose f h / fps_compose g h\"\n  using fps_compose_divide[OF assms(1,2)] assms(3) by simp\n\nlemma fps_compose_power:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n  shows \"(a oo c)^n = a^n oo c\"\nproof (cases n)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc m)\n  have th0: \"a^n = prod (\\<lambda>k. a) {0..m}\" \"(a oo c) ^ n = prod (\\<lambda>k. a oo c) {0..m}\"\n    by (simp_all add: prod_constant Suc)\n  then show ?thesis\n    by (simp add: fps_compose_prod_distrib[OF c0])\nqed\n\nlemma fps_compose_uminus: \"- (a::'a::ring_1 fps) oo c = - (a oo c)\"\n  by (simp add: fps_eq_iff fps_compose_nth field_simps sum_negf[symmetric])\n\nlemma fps_compose_sub_distrib: \"(a - b) oo (c::'a::ring_1 fps) = (a oo c) - (b oo c)\"\n  using fps_compose_add_distrib [of a \"- b\" c] by (simp add: fps_compose_uminus)\n\nlemma X_fps_compose: \"X oo a = Abs_fps (\\<lambda>n. if n = 0 then (0::'a::comm_ring_1) else a$n)\"\n  by (simp add: fps_eq_iff fps_compose_nth mult_delta_left sum.delta)\n\nlemma fps_inverse_compose:\n  assumes b0: \"(b$0 :: 'a::field) = 0\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"inverse a oo b = inverse (a oo b)\"\nproof -\n  let ?ia = \"inverse a\"\n  let ?ab = \"a oo b\"\n  let ?iab = \"inverse ?ab\"\n\n  from a0 have ia0: \"?ia $ 0 \\<noteq> 0\" by simp\n  from a0 have ab0: \"?ab $ 0 \\<noteq> 0\" by (simp add: fps_compose_def)\n  have \"(?ia oo b) *  (a oo b) = 1\"\n    unfolding fps_compose_mult_distrib[OF b0, symmetric]\n    unfolding inverse_mult_eq_1[OF a0]\n    fps_compose_1 ..\n\n  then have \"(?ia oo b) *  (a oo b) * ?iab  = 1 * ?iab\" by simp\n  then have \"(?ia oo b) *  (?iab * (a oo b))  = ?iab\" by simp\n  then show ?thesis unfolding inverse_mult_eq_1[OF ab0] by simp\nqed\n\nlemma fps_divide_compose:\n  assumes c0: \"(c$0 :: 'a::field) = 0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"(a/b) oo c = (a oo c) / (b oo c)\"\n    using b0 c0 by (simp add: fps_divide_unit fps_inverse_compose fps_compose_mult_distrib)\n\nlemma gp:\n  assumes a0: \"a$0 = (0::'a::field)\"\n  shows \"(Abs_fps (\\<lambda>n. 1)) oo a = 1/(1 - a)\"\n    (is \"?one oo a = _\")\nproof -\n  have o0: \"?one $ 0 \\<noteq> 0\" by simp\n  have th0: \"(1 - X) $ 0 \\<noteq> (0::'a)\" by simp\n  from fps_inverse_gp[where ?'a = 'a]\n  have \"inverse ?one = 1 - X\" by (simp add: fps_eq_iff)\n  then have \"inverse (inverse ?one) = inverse (1 - X)\" by simp\n  then have th: \"?one = 1/(1 - X)\" unfolding fps_inverse_idempotent[OF o0]\n    by (simp add: fps_divide_def)\n  show ?thesis\n    unfolding th\n    unfolding fps_divide_compose[OF a0 th0]\n    fps_compose_1 fps_compose_sub_distrib X_fps_compose_startby0[OF a0] ..\nqed\n\nlemma fps_const_power [simp]: \"fps_const (c::'a::ring_1) ^ n = fps_const (c^n)\"\n  by (induct n) auto\n\nlemma fps_compose_radical:\n  assumes b0: \"b$0 = (0::'a::field_char_0)\"\n    and ra0: \"r (Suc k) (a$0) ^ Suc k = a$0\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_radical r (Suc k)  a oo b = fps_radical r (Suc k) (a oo b)\"\nproof -\n  let ?r = \"fps_radical r (Suc k)\"\n  let ?ab = \"a oo b\"\n  have ab0: \"?ab $ 0 = a$0\"\n    by (simp add: fps_compose_def)\n  from ab0 a0 ra0 have rab0: \"?ab $ 0 \\<noteq> 0\" \"r (Suc k) (?ab $ 0) ^ Suc k = ?ab $ 0\"\n    by simp_all\n  have th00: \"r (Suc k) ((a oo b) $ 0) = (fps_radical r (Suc k) a oo b) $ 0\"\n    by (simp add: ab0 fps_compose_def)\n  have th0: \"(?r a oo b) ^ (Suc k) = a  oo b\"\n    unfolding fps_compose_power[OF b0]\n    unfolding iffD1[OF power_radical[of a r k], OF a0 ra0]  ..\n  from iffD1[OF radical_unique[where r=r and k=k and b= ?ab and a = \"?r a oo b\", OF rab0(2) th00 rab0(1)], OF th0]\n  show ?thesis  .\nqed\n\nlemma fps_const_mult_apply_left: \"fps_const c * (a oo b) = (fps_const c * a) oo b\"\n  by (simp add: fps_eq_iff fps_compose_nth sum_distrib_left mult.assoc)\n\nlemma fps_const_mult_apply_right:\n  \"(a oo b) * fps_const (c::'a::comm_semiring_1) = (fps_const c * a) oo b\"\n  by (auto simp add: fps_const_mult_apply_left mult.commute)\n\nlemma fps_compose_assoc:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n    and b0: \"b$0 = 0\"\n  shows \"a oo (b oo c) = a oo b oo c\" (is \"?l = ?r\")\nproof -\n  have \"?l$n = ?r$n\" for n\n  proof -\n    have \"?l$n = (sum (\\<lambda>i. (fps_const (a$i) * b^i) oo c) {0..n})$n\"\n      by (simp add: fps_compose_nth fps_compose_power[OF c0] fps_const_mult_apply_left\n        sum_distrib_left mult.assoc fps_sum_nth)\n    also have \"\\<dots> = ((sum (\\<lambda>i. fps_const (a$i) * b^i) {0..n}) oo c)$n\"\n      by (simp add: fps_compose_sum_distrib)\n    also have \"\\<dots> = ?r$n\"\n      apply (simp add: fps_compose_nth fps_sum_nth sum_distrib_right mult.assoc)\n      apply (rule sum.cong)\n      apply (rule refl)\n      apply (rule sum.mono_neutral_right)\n      apply (auto simp add: not_le)\n      apply (erule startsby_zero_power_prefix[OF b0, rule_format])\n      done\n    finally show ?thesis .\n  qed\n  then show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\n\nlemma fps_X_power_compose:\n  assumes a0: \"a$0=0\"\n  shows \"X^k oo a = (a::'a::idom fps)^k\"\n  (is \"?l = ?r\")\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc h)\n  have \"?l $ n = ?r $n\" for n\n  proof -\n    consider \"k > n\" | \"k \\<le> n\" by arith\n    then show ?thesis\n    proof cases\n      case 1\n      then show ?thesis\n        using a0 startsby_zero_power_prefix[OF a0] Suc\n        by (simp add: fps_compose_nth del: power_Suc)\n    next\n      case 2\n      then show ?thesis\n        by (simp add: fps_compose_nth mult_delta_left sum.delta)\n    qed\n  qed\n  then show ?thesis\n    unfolding fps_eq_iff by blast\nqed\n\nlemma fps_inv_right:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"a oo fps_inv a = X\"\nproof -\n  let ?ia = \"fps_inv a\"\n  let ?iaa = \"a oo fps_inv a\"\n  have th0: \"?ia $ 0 = 0\"\n    by (simp add: fps_inv_def)\n  have th1: \"?iaa $ 0 = 0\"\n    using a0 a1 by (simp add: fps_inv_def fps_compose_nth)\n  have th2: \"X$0 = 0\"\n    by simp\n  from fps_inv[OF a0 a1] have \"a oo (fps_inv a oo a) = a oo X\"\n    by simp\n  then have \"(a oo fps_inv a) oo a = X oo a\"\n    by (simp add: fps_compose_assoc[OF a0 th0] X_fps_compose_startby0[OF a0])\n  with fps_compose_inj_right[OF a0 a1] show ?thesis\n    by simp\nqed\n\nlemma fps_inv_deriv:\n  assumes a0: \"a$0 = (0::'a::field)\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_deriv (fps_inv a) = inverse (fps_deriv a oo fps_inv a)\"\nproof -\n  let ?ia = \"fps_inv a\"\n  let ?d = \"fps_deriv a oo ?ia\"\n  let ?dia = \"fps_deriv ?ia\"\n  have ia0: \"?ia$0 = 0\"\n    by (simp add: fps_inv_def)\n  have th0: \"?d$0 \\<noteq> 0\"\n    using a1 by (simp add: fps_compose_nth)\n  from fps_inv_right[OF a0 a1] have \"?d * ?dia = 1\"\n    by (simp add: fps_compose_deriv[OF ia0, of a, symmetric] )\n  then have \"inverse ?d * ?d * ?dia = inverse ?d * 1\"\n    by simp\n  with inverse_mult_eq_1 [OF th0] show \"?dia = inverse ?d\"\n    by simp\nqed\n\nlemma fps_inv_idempotent:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_inv (fps_inv a) = a\"\nproof -\n  let ?r = \"fps_inv\"\n  have ra0: \"?r a $ 0 = 0\"\n    by (simp add: fps_inv_def)\n  from a1 have ra1: \"?r a $ 1 \\<noteq> 0\"\n    by (simp add: fps_inv_def field_simps)\n  have X0: \"X$0 = 0\"\n    by simp\n  from fps_inv[OF ra0 ra1] have \"?r (?r a) oo ?r a = X\" .\n  then have \"?r (?r a) oo ?r a oo a = X oo a\"\n    by simp\n  then have \"?r (?r a) oo (?r a oo a) = a\"\n    unfolding X_fps_compose_startby0[OF a0]\n    unfolding fps_compose_assoc[OF a0 ra0, symmetric] .\n  then show ?thesis\n    unfolding fps_inv[OF a0 a1] by simp\nqed\n\nlemma fps_ginv_ginv:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n    and c0: \"c$0 = 0\"\n    and  c1: \"c$1 \\<noteq> 0\"\n  shows \"fps_ginv b (fps_ginv c a) = b oo a oo fps_inv c\"\nproof -\n  let ?r = \"fps_ginv\"\n  from c0 have rca0: \"?r c a $0 = 0\"\n    by (simp add: fps_ginv_def)\n  from a1 c1 have rca1: \"?r c a $ 1 \\<noteq> 0\"\n    by (simp add: fps_ginv_def field_simps)\n  from fps_ginv[OF rca0 rca1]\n  have \"?r b (?r c a) oo ?r c a = b\" .\n  then have \"?r b (?r c a) oo ?r c a oo a = b oo a\"\n    by simp\n  then have \"?r b (?r c a) oo (?r c a oo a) = b oo a\"\n    apply (subst fps_compose_assoc)\n    using a0 c0\n    apply (auto simp add: fps_ginv_def)\n    done\n  then have \"?r b (?r c a) oo c = b oo a\"\n    unfolding fps_ginv[OF a0 a1] .\n  then have \"?r b (?r c a) oo c oo fps_inv c= b oo a oo fps_inv c\"\n    by simp\n  then have \"?r b (?r c a) oo (c oo fps_inv c) = b oo a oo fps_inv c\"\n    apply (subst fps_compose_assoc)\n    using a0 c0\n    apply (auto simp add: fps_inv_def)\n    done\n  then show ?thesis\n    unfolding fps_inv_right[OF c0 c1] by simp\nqed\n\nlemma fps_ginv_deriv:\n  assumes a0:\"a$0 = (0::'a::field)\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_deriv (fps_ginv b a) = (fps_deriv b / fps_deriv a) oo fps_ginv X a\"\nproof -\n  let ?ia = \"fps_ginv b a\"\n  let ?iXa = \"fps_ginv X a\"\n  let ?d = \"fps_deriv\"\n  let ?dia = \"?d ?ia\"\n  have iXa0: \"?iXa $ 0 = 0\"\n    by (simp add: fps_ginv_def)\n  have da0: \"?d a $ 0 \\<noteq> 0\"\n    using a1 by simp\n  from fps_ginv[OF a0 a1, of b] have \"?d (?ia oo a) = fps_deriv b\"\n    by simp\n  then have \"(?d ?ia oo a) * ?d a = ?d b\"\n    unfolding fps_compose_deriv[OF a0] .\n  then have \"(?d ?ia oo a) * ?d a * inverse (?d a) = ?d b * inverse (?d a)\"\n    by simp\n  with a1 have \"(?d ?ia oo a) * (inverse (?d a) * ?d a) = ?d b / ?d a\"\n    by (simp add: fps_divide_unit)\n  then have \"(?d ?ia oo a) oo ?iXa =  (?d b / ?d a) oo ?iXa\"\n    unfolding inverse_mult_eq_1[OF da0] by simp\n  then have \"?d ?ia oo (a oo ?iXa) =  (?d b / ?d a) oo ?iXa\"\n    unfolding fps_compose_assoc[OF iXa0 a0] .\n  then show ?thesis unfolding fps_inv_ginv[symmetric]\n    unfolding fps_inv_right[OF a0 a1] by simp\nqed\n\nlemma fps_compose_linear:\n  \"fps_compose (f :: 'a :: comm_ring_1 fps) (fps_const c * X) = Abs_fps (\\<lambda>n. c^n * f $ n)\"\n  by (simp add: fps_eq_iff fps_compose_def power_mult_distrib\n                if_distrib sum.delta' cong: if_cong)\n\nsubsection \\<open>Elementary series\\<close>\n\nsubsubsection \\<open>Exponential series\\<close>\n\ndefinition \"E x = Abs_fps (\\<lambda>n. x^n / of_nat (fact n))\"\n\nlemma E_deriv[simp]: \"fps_deriv (E a) = fps_const (a::'a::field_char_0) * E a\" (is \"?l = ?r\")\nproof -\n  have \"?l$n = ?r $ n\" for n\n    apply (auto simp add: E_def field_simps power_Suc[symmetric]\n      simp del: fact_Suc of_nat_Suc power_Suc)\n    apply (simp add: field_simps)\n    done\n  then show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\nlemma E_unique_ODE:\n  \"fps_deriv a = fps_const c * a \\<longleftrightarrow> a = fps_const (a$0) * E (c::'a::field_char_0)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    from that have th: \"\\<And>n. a $ Suc n = c * a$n / of_nat (Suc n)\"\n      by (simp add: fps_deriv_def fps_eq_iff field_simps del: of_nat_Suc)\n    have th': \"a$n = a$0 * c ^ n/ (fact n)\" for n\n    proof (induct n)\n      case 0\n      then show ?case by simp\n    next\n      case Suc\n      then show ?case\n        unfolding th\n        using fact_gt_zero\n        apply (simp add: field_simps del: of_nat_Suc fact_Suc)\n        apply simp\n        done\n    qed\n    show ?thesis\n      by (auto simp add: fps_eq_iff fps_const_mult_left E_def intro: th')\n  qed\n  show ?lhs if ?rhs\n    using that by (metis E_deriv fps_deriv_mult_const_left mult.left_commute)\nqed\n\nlemma E_add_mult: \"E (a + b) = E (a::'a::field_char_0) * E b\" (is \"?l = ?r\")\nproof -\n  have \"fps_deriv ?r = fps_const (a + b) * ?r\"\n    by (simp add: fps_const_add[symmetric] field_simps del: fps_const_add)\n  then have \"?r = ?l\"\n    by (simp only: E_unique_ODE) (simp add: fps_mult_nth E_def)\n  then show ?thesis ..\nqed\n\nlemma E_nth[simp]: \"E a $ n = a^n / of_nat (fact n)\"\n  by (simp add: E_def)\n\nlemma E0[simp]: \"E (0::'a::field) = 1\"\n  by (simp add: fps_eq_iff power_0_left)\n\nlemma E_neg: \"E (- a) = inverse (E (a::'a::field_char_0))\"\nproof -\n  from E_add_mult[of a \"- a\"] have th0: \"E a * E (- a) = 1\" by simp\n  from fps_inverse_unique[OF th0] show ?thesis by simp\nqed\n\nlemma E_nth_deriv[simp]: \"fps_nth_deriv n (E (a::'a::field_char_0)) = (fps_const a)^n * (E a)\"\n  by (induct n) auto\n\nlemma X_compose_E[simp]: \"X oo E (a::'a::field) = E a - 1\"\n  by (simp add: fps_eq_iff X_fps_compose)\n\nlemma LE_compose:\n  assumes a: \"a \\<noteq> 0\"\n  shows \"fps_inv (E a - 1) oo (E a - 1) = X\"\n    and \"(E a - 1) oo fps_inv (E a - 1) = X\"\nproof -\n  let ?b = \"E a - 1\"\n  have b0: \"?b $ 0 = 0\"\n    by simp\n  have b1: \"?b $ 1 \\<noteq> 0\"\n    by (simp add: a)\n  from fps_inv[OF b0 b1] show \"fps_inv (E a - 1) oo (E a - 1) = X\" .\n  from fps_inv_right[OF b0 b1] show \"(E a - 1) oo fps_inv (E a - 1) = X\" .\nqed\n\nlemma E_power_mult: \"(E (c::'a::field_char_0))^n = E (of_nat n * c)\"\n  by (induct n) (auto simp add: field_simps E_add_mult)\n\nlemma radical_E:\n  assumes r: \"r (Suc k) 1 = 1\"\n  shows \"fps_radical r (Suc k) (E (c::'a::field_char_0)) = E (c / of_nat (Suc k))\"\nproof -\n  let ?ck = \"(c / of_nat (Suc k))\"\n  let ?r = \"fps_radical r (Suc k)\"\n  have eq0[simp]: \"?ck * of_nat (Suc k) = c\" \"of_nat (Suc k) * ?ck = c\"\n    by (simp_all del: of_nat_Suc)\n  have th0: \"E ?ck ^ (Suc k) = E c\" unfolding E_power_mult eq0 ..\n  have th: \"r (Suc k) (E c $0) ^ Suc k = E c $ 0\"\n    \"r (Suc k) (E c $ 0) = E ?ck $ 0\" \"E c $ 0 \\<noteq> 0\" using r by simp_all\n  from th0 radical_unique[where r=r and k=k, OF th] show ?thesis\n    by auto\nqed\n\nlemma Ec_E1_eq: \"E (1::'a::field_char_0) oo (fps_const c * X) = E c\"\n  apply (auto simp add: fps_eq_iff E_def fps_compose_def power_mult_distrib)\n  apply (simp add: cond_value_iff cond_application_beta sum.delta' cong del: if_weak_cong)\n  done\n\n\nsubsubsection \\<open>Logarithmic series\\<close>\n\nlemma Abs_fps_if_0:\n  \"Abs_fps (\\<lambda>n. if n = 0 then (v::'a::ring_1) else f n) =\n    fps_const v + X * Abs_fps (\\<lambda>n. f (Suc n))\"\n  by (auto simp add: fps_eq_iff)\n\ndefinition L :: \"'a::field_char_0 \\<Rightarrow> 'a fps\"\n  where \"L c = fps_const (1/c) * Abs_fps (\\<lambda>n. if n = 0 then 0 else (- 1) ^ (n - 1) / of_nat n)\"\n\nlemma fps_deriv_L: \"fps_deriv (L c) = fps_const (1/c) * inverse (1 + X)\"\n  unfolding fps_inverse_X_plus1\n  by (simp add: L_def fps_eq_iff del: of_nat_Suc)\n\nlemma L_nth: \"L c $ n = (if n = 0 then 0 else 1/c * ((- 1) ^ (n - 1) / of_nat n))\"\n  by (simp add: L_def field_simps)\n\nlemma L_0[simp]: \"L c $ 0 = 0\" by (simp add: L_def)\n\nlemma L_E_inv:\n  fixes a :: \"'a::field_char_0\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"L a = fps_inv (E a - 1)\"  (is \"?l = ?r\")\nproof -\n  let ?b = \"E a - 1\"\n  have b0: \"?b $ 0 = 0\" by simp\n  have b1: \"?b $ 1 \\<noteq> 0\" by (simp add: a)\n  have \"fps_deriv (E a - 1) oo fps_inv (E a - 1) =\n    (fps_const a * (E a - 1) + fps_const a) oo fps_inv (E a - 1)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = fps_const a * (X + 1)\"\n    apply (simp add: fps_compose_add_distrib fps_const_mult_apply_left[symmetric] fps_inv_right[OF b0 b1])\n    apply (simp add: field_simps)\n    done\n  finally have eq: \"fps_deriv (E a - 1) oo fps_inv (E a - 1) = fps_const a * (X + 1)\" .\n  from fps_inv_deriv[OF b0 b1, unfolded eq]\n  have \"fps_deriv (fps_inv ?b) = fps_const (inverse a) / (X + 1)\"\n    using a\n    by (simp add: fps_const_inverse eq fps_divide_def fps_inverse_mult)\n  then have \"fps_deriv ?l = fps_deriv ?r\"\n    by (simp add: fps_deriv_L add.commute fps_divide_def divide_inverse)\n  then show ?thesis unfolding fps_deriv_eq_iff\n    by (simp add: L_nth fps_inv_def)\nqed\n\nlemma L_mult_add:\n  assumes c0: \"c\\<noteq>0\"\n    and d0: \"d\\<noteq>0\"\n  shows \"L c + L d = fps_const (c+d) * L (c*d)\"\n  (is \"?r = ?l\")\nproof-\n  from c0 d0 have eq: \"1/c + 1/d = (c+d)/(c*d)\" by (simp add: field_simps)\n  have \"fps_deriv ?r = fps_const (1/c + 1/d) * inverse (1 + X)\"\n    by (simp add: fps_deriv_L fps_const_add[symmetric] algebra_simps del: fps_const_add)\n  also have \"\\<dots> = fps_deriv ?l\"\n    apply (simp add: fps_deriv_L)\n    apply (simp add: fps_eq_iff eq)\n    done\n  finally show ?thesis\n    unfolding fps_deriv_eq_iff by simp\nqed\n\n\nsubsubsection \\<open>Binomial series\\<close>\n\ndefinition \"fps_binomial a = Abs_fps (\\<lambda>n. a gchoose n)\"\n\nlemma fps_binomial_nth[simp]: \"fps_binomial a $ n = a gchoose n\"\n  by (simp add: fps_binomial_def)\n\nlemma fps_binomial_ODE_unique:\n  fixes c :: \"'a::field_char_0\"\n  shows \"fps_deriv a = (fps_const c * a) / (1 + X) \\<longleftrightarrow> a = fps_const (a$0) * fps_binomial c\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  let ?da = \"fps_deriv a\"\n  let ?x1 = \"(1 + X):: 'a fps\"\n  let ?l = \"?x1 * ?da\"\n  let ?r = \"fps_const c * a\"\n\n  have eq: \"?l = ?r \\<longleftrightarrow> ?lhs\"\n  proof -\n    have x10: \"?x1 $ 0 \\<noteq> 0\" by simp\n    have \"?l = ?r \\<longleftrightarrow> inverse ?x1 * ?l = inverse ?x1 * ?r\" by simp\n    also have \"\\<dots> \\<longleftrightarrow> ?da = (fps_const c * a) / ?x1\"\n      apply (simp only: fps_divide_def  mult.assoc[symmetric] inverse_mult_eq_1[OF x10])\n      apply (simp add: field_simps)\n      done\n    finally show ?thesis .\n  qed\n\n  show ?rhs if ?lhs\n  proof -\n    from eq that have h: \"?l = ?r\" ..\n    have th0: \"a$ Suc n = ((c - of_nat n) / of_nat (Suc n)) * a $n\" for n\n    proof -\n      from h have \"?l $ n = ?r $ n\" by simp\n      then show ?thesis\n        apply (simp add: field_simps del: of_nat_Suc)\n        apply (cases n)\n        apply (simp_all add: field_simps del: of_nat_Suc)\n        done\n    qed\n    have th1: \"a $ n = (c gchoose n) * a $ 0\" for n\n    proof (induct n)\n      case 0\n      then show ?case by simp\n    next\n      case (Suc m)\n      then show ?case\n        unfolding th0\n        apply (simp add: field_simps del: of_nat_Suc)\n        unfolding mult.assoc[symmetric] gbinomial_mult_1\n        apply (simp add: field_simps)\n        done\n    qed\n    show ?thesis\n      apply (simp add: fps_eq_iff)\n      apply (subst th1)\n      apply (simp add: field_simps)\n      done\n  qed\n\n  show ?lhs if ?rhs\n  proof -\n    have th00: \"x * (a $ 0 * y) = a $ 0 * (x * y)\" for x y\n      by (simp add: mult.commute)\n    have \"?l = ?r\"\n      apply (subst \\<open>?rhs\\<close>)\n      apply (subst (2) \\<open>?rhs\\<close>)\n      apply (clarsimp simp add: fps_eq_iff field_simps)\n      unfolding mult.assoc[symmetric] th00 gbinomial_mult_1\n      apply (simp add: field_simps gbinomial_mult_1)\n      done\n    with eq show ?thesis ..\n  qed\nqed\n\nlemma fps_binomial_ODE_unique':\n  \"(fps_deriv a = fps_const c * a / (1 + X) \\<and> a $ 0 = 1) \\<longleftrightarrow> (a = fps_binomial c)\"\n  by (subst fps_binomial_ODE_unique) auto\n\nlemma fps_binomial_deriv: \"fps_deriv (fps_binomial c) = fps_const c * fps_binomial c / (1 + X)\"\nproof -\n  let ?a = \"fps_binomial c\"\n  have th0: \"?a = fps_const (?a$0) * ?a\" by (simp)\n  from iffD2[OF fps_binomial_ODE_unique, OF th0] show ?thesis .\nqed\n\nlemma fps_binomial_add_mult: \"fps_binomial (c+d) = fps_binomial c * fps_binomial d\" (is \"?l = ?r\")\nproof -\n  let ?P = \"?r - ?l\"\n  let ?b = \"fps_binomial\"\n  let ?db = \"\\<lambda>x. fps_deriv (?b x)\"\n  have \"fps_deriv ?P = ?db c * ?b d + ?b c * ?db d - ?db (c + d)\"  by simp\n  also have \"\\<dots> = inverse (1 + X) *\n      (fps_const c * ?b c * ?b d + fps_const d * ?b c * ?b d - fps_const (c+d) * ?b (c + d))\"\n    unfolding fps_binomial_deriv\n    by (simp add: fps_divide_def field_simps)\n  also have \"\\<dots> = (fps_const (c + d)/ (1 + X)) * ?P\"\n    by (simp add: field_simps fps_divide_unit fps_const_add[symmetric] del: fps_const_add)\n  finally have th0: \"fps_deriv ?P = fps_const (c+d) * ?P / (1 + X)\"\n    by (simp add: fps_divide_def)\n  have \"?P = fps_const (?P$0) * ?b (c + d)\"\n    unfolding fps_binomial_ODE_unique[symmetric]\n    using th0 by simp\n  then have \"?P = 0\" by (simp add: fps_mult_nth)\n  then show ?thesis by simp\nqed\n\nlemma fps_binomial_minus_one: \"fps_binomial (- 1) = inverse (1 + X)\"\n  (is \"?l = inverse ?r\")\nproof-\n  have th: \"?r$0 \\<noteq> 0\" by simp\n  have th': \"fps_deriv (inverse ?r) = fps_const (- 1) * inverse ?r / (1 + X)\"\n    by (simp add: fps_inverse_deriv[OF th] fps_divide_def\n      power2_eq_square mult.commute fps_const_neg[symmetric] del: fps_const_neg)\n  have eq: \"inverse ?r $ 0 = 1\"\n    by (simp add: fps_inverse_def)\n  from iffD1[OF fps_binomial_ODE_unique[of \"inverse (1 + X)\" \"- 1\"] th'] eq\n  show ?thesis by (simp add: fps_inverse_def)\nqed\n\nlemma fps_binomial_of_nat: \"fps_binomial (of_nat n) = (1 + X :: 'a :: field_char_0 fps) ^ n\"\nproof (cases \"n = 0\")\n  case [simp]: True\n  have \"fps_deriv ((1 + X) ^ n :: 'a fps) = 0\" by simp\n  also have \"\\<dots> = fps_const (of_nat n) * (1 + X) ^ n / (1 + X)\" by (simp add: fps_binomial_def)\n  finally show ?thesis by (subst sym, subst fps_binomial_ODE_unique' [symmetric]) simp_all\nnext\n  case False\n  have \"fps_deriv ((1 + X) ^ n :: 'a fps) = fps_const (of_nat n) * (1 + X) ^ (n - 1)\"\n    by (simp add: fps_deriv_power)\n  also have \"(1 + X :: 'a fps) $ 0 \\<noteq> 0\" by simp\n  hence \"(1 + X :: 'a fps) \\<noteq> 0\" by (intro notI) (simp only: , simp)\n  with False have \"(1 + X :: 'a fps) ^ (n - 1) = (1 + X) ^ n / (1 + X)\"\n    by (cases n) (simp_all )\n  also have \"fps_const (of_nat n :: 'a) * ((1 + X) ^ n / (1 + X)) =\n               fps_const (of_nat n) * (1 + X) ^ n / (1 + X)\"\n    by (simp add: unit_div_mult_swap)\n  finally show ?thesis\n    by (subst sym, subst fps_binomial_ODE_unique' [symmetric]) (simp_all add: fps_power_nth)\nqed\n\nlemma fps_binomial_0 [simp]: \"fps_binomial 0 = 1\"\n  using fps_binomial_of_nat[of 0] by simp\n  \nlemma fps_binomial_power: \"fps_binomial a ^ n = fps_binomial (of_nat n * a)\"\n  by (induction n) (simp_all add: fps_binomial_add_mult ring_distribs)\n\nlemma fps_binomial_1: \"fps_binomial 1 = 1 + X\"\n  using fps_binomial_of_nat[of 1] by simp\n\nlemma fps_binomial_minus_of_nat:\n  \"fps_binomial (- of_nat n) = inverse ((1 + X :: 'a :: field_char_0 fps) ^ n)\"\n  by (rule sym, rule fps_inverse_unique)\n     (simp add: fps_binomial_of_nat [symmetric] fps_binomial_add_mult [symmetric])\n\nlemma one_minus_const_X_power:\n  \"c \\<noteq> 0 \\<Longrightarrow> (1 - fps_const c * X) ^ n =\n     fps_compose (fps_binomial (of_nat n)) (-fps_const c * X)\"\n  by (subst fps_binomial_of_nat)\n     (simp add: fps_compose_power [symmetric] fps_compose_add_distrib fps_const_neg [symmetric] \n           del: fps_const_neg)\n\nlemma one_minus_X_const_neg_power:\n  \"inverse ((1 - fps_const c * X) ^ n) = \n       fps_compose (fps_binomial (-of_nat n)) (-fps_const c * X)\"\nproof (cases \"c = 0\")\n  case False\n  thus ?thesis\n  by (subst fps_binomial_minus_of_nat)\n     (simp add: fps_compose_power [symmetric] fps_inverse_compose fps_compose_add_distrib\n                fps_const_neg [symmetric] del: fps_const_neg)\nqed simp\n\nlemma X_plus_const_power:\n  \"c \\<noteq> 0 \\<Longrightarrow> (X + fps_const c) ^ n =\n     fps_const (c^n) * fps_compose (fps_binomial (of_nat n)) (fps_const (inverse c) * X)\"\n  by (subst fps_binomial_of_nat)\n     (simp add: fps_compose_power [symmetric] fps_binomial_of_nat fps_compose_add_distrib\n                fps_const_power [symmetric] power_mult_distrib [symmetric] \n                algebra_simps inverse_mult_eq_1' del: fps_const_power)\n\nlemma X_plus_const_neg_power:\n  \"c \\<noteq> 0 \\<Longrightarrow> inverse ((X + fps_const c) ^ n) =\n     fps_const (inverse c^n) * fps_compose (fps_binomial (-of_nat n)) (fps_const (inverse c) * X)\"\n  by (subst fps_binomial_minus_of_nat)\n     (simp add: fps_compose_power [symmetric] fps_binomial_of_nat fps_compose_add_distrib\n                fps_const_power [symmetric] power_mult_distrib [symmetric] fps_inverse_compose \n                algebra_simps fps_const_inverse [symmetric] fps_inverse_mult [symmetric]\n                fps_inverse_power [symmetric] inverse_mult_eq_1'\n           del: fps_const_power)\n\n\nlemma one_minus_const_X_neg_power':\n  \"n > 0 \\<Longrightarrow> inverse ((1 - fps_const (c :: 'a :: field_char_0) * X) ^ n) =\n       Abs_fps (\\<lambda>k. of_nat ((n + k - 1) choose k) * c^k)\"\n  apply (rule fps_ext)\n  apply (subst one_minus_X_const_neg_power, subst fps_const_neg, subst fps_compose_linear)\n  apply (simp add: power_mult_distrib [symmetric] mult.assoc [symmetric] \n                   gbinomial_minus binomial_gbinomial of_nat_diff)\n  done\n\ntext \\<open>Vandermonde's Identity as a consequence.\\<close>\nlemma gbinomial_Vandermonde:\n  \"sum (\\<lambda>k. (a gchoose k) * (b gchoose (n - k))) {0..n} = (a + b) gchoose n\"\nproof -\n  let ?ba = \"fps_binomial a\"\n  let ?bb = \"fps_binomial b\"\n  let ?bab = \"fps_binomial (a + b)\"\n  from fps_binomial_add_mult[of a b] have \"?bab $ n = (?ba * ?bb)$n\" by simp\n  then show ?thesis by (simp add: fps_mult_nth)\nqed\n\nlemma binomial_Vandermonde:\n  \"sum (\\<lambda>k. (a choose k) * (b choose (n - k))) {0..n} = (a + b) choose n\"\n  using gbinomial_Vandermonde[of \"(of_nat a)\" \"of_nat b\" n]\n  by (simp only: binomial_gbinomial[symmetric] of_nat_mult[symmetric]\n                 of_nat_sum[symmetric] of_nat_add[symmetric] of_nat_eq_iff)\n\nlemma binomial_Vandermonde_same: \"sum (\\<lambda>k. (n choose k)\\<^sup>2) {0..n} = (2 * n) choose n\"\n  using binomial_Vandermonde[of n n n, symmetric]\n  unfolding mult_2\n  apply (simp add: power2_eq_square)\n  apply (rule sum.cong)\n  apply (auto intro:  binomial_symmetric)\n  done\n\nlemma Vandermonde_pochhammer_lemma:\n  fixes a :: \"'a::field_char_0\"\n  assumes b: \"\\<forall>j\\<in>{0 ..<n}. b \\<noteq> of_nat j\"\n  shows \"sum (\\<lambda>k. (pochhammer (- a) k * pochhammer (- (of_nat n)) k) /\n      (of_nat (fact k) * pochhammer (b - of_nat n + 1) k)) {0..n} =\n    pochhammer (- (a + b)) n / pochhammer (- b) n\"\n  (is \"?l = ?r\")\nproof -\n  let ?m1 = \"\\<lambda>m. (- 1 :: 'a) ^ m\"\n  let ?f = \"\\<lambda>m. of_nat (fact m)\"\n  let ?p = \"\\<lambda>(x::'a). pochhammer (- x)\"\n  from b have bn0: \"?p b n \\<noteq> 0\"\n    unfolding pochhammer_eq_0_iff by simp\n  have th00:\n    \"b gchoose (n - k) =\n        (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n      (is ?gchoose)\n    \"pochhammer (1 + b - of_nat n) k \\<noteq> 0\"\n      (is ?pochhammer)\n    if kn: \"k \\<in> {0..n}\" for k\n  proof -\n    from kn have \"k \\<le> n\" by simp\n    have nz: \"pochhammer (1 + b - of_nat n) n \\<noteq> 0\"\n    proof\n      assume \"pochhammer (1 + b - of_nat n) n = 0\"\n      then have c: \"pochhammer (b - of_nat n + 1) n = 0\"\n        by (simp add: algebra_simps)\n      then obtain j where j: \"j < n\" \"b - of_nat n + 1 = - of_nat j\"\n        unfolding pochhammer_eq_0_iff by blast\n      from j have \"b = of_nat n - of_nat j - of_nat 1\"\n        by (simp add: algebra_simps)\n      then have \"b = of_nat (n - j - 1)\"\n        using j kn by (simp add: of_nat_diff)\n      with b show False using j by auto\n    qed\n\n    from nz kn [simplified] have nz': \"pochhammer (1 + b - of_nat n) k \\<noteq> 0\"\n      by (rule pochhammer_neq_0_mono)\n\n    consider \"k = 0 \\<or> n = 0\" | \"k \\<noteq> 0\" \"n \\<noteq> 0\"\n      by blast\n    then have \"b gchoose (n - k) =\n      (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n    proof cases\n      case 1\n      then show ?thesis\n        using kn by (cases \"k = 0\") (simp_all add: gbinomial_pochhammer)\n    next\n      case neq: 2\n      then obtain m where m: \"n = Suc m\"\n        by (cases n) auto\n      from neq(1) obtain h where h: \"k = Suc h\"\n        by (cases k) auto\n      show ?thesis\n      proof (cases \"k = n\")\n        case True\n        then show ?thesis\n          using pochhammer_minus'[where k=k and b=b]\n          apply (simp add: pochhammer_same)\n          using bn0\n          apply (simp add: field_simps power_add[symmetric])\n          done\n      next\n        case False\n        with kn have kn': \"k < n\"\n          by simp\n        have m1nk: \"?m1 n = prod (\\<lambda>i. - 1) {..m}\" \"?m1 k = prod (\\<lambda>i. - 1) {0..h}\"\n          by (simp_all add: prod_constant m h)\n        have bnz0: \"pochhammer (b - of_nat n + 1) k \\<noteq> 0\"\n          using bn0 kn\n          unfolding pochhammer_eq_0_iff\n          apply auto\n          apply (erule_tac x= \"n - ka - 1\" in allE)\n          apply (auto simp add: algebra_simps of_nat_diff)\n          done\n        have eq1: \"prod (\\<lambda>k. (1::'a) + of_nat m - of_nat k) {..h} =\n          prod of_nat {Suc (m - h) .. Suc m}\"\n          using kn' h m\n          by (intro prod.reindex_bij_witness[where i=\"\\<lambda>k. Suc m - k\" and j=\"\\<lambda>k. Suc m - k\"])\n             (auto simp: of_nat_diff)\n        have th1: \"(?m1 k * ?p (of_nat n) k) / ?f n = 1 / of_nat(fact (n - k))\"\n          apply (simp add: pochhammer_minus field_simps)\n          using \\<open>k \\<le> n\\<close> apply (simp add: fact_split [of k n])\n          apply (simp add: pochhammer_prod)\n          using prod.atLeast_lessThan_shift_bounds [where ?'a = 'a, of \"\\<lambda>i. 1 + of_nat i\" 0 \"n - k\" k]\n          apply (auto simp add: of_nat_diff field_simps)\n          done\n        have th20: \"?m1 n * ?p b n = prod (\\<lambda>i. b - of_nat i) {0..m}\"\n          apply (simp add: pochhammer_minus field_simps m)\n          apply (auto simp add: pochhammer_prod_rev of_nat_diff prod.atLeast_Suc_atMost_Suc_shift)\n          done\n        have th21:\"pochhammer (b - of_nat n + 1) k = prod (\\<lambda>i. b - of_nat i) {n - k .. n - 1}\"\n          using kn apply (simp add: pochhammer_prod_rev m h prod.atLeast_Suc_atMost_Suc_shift)\n          using prod.atLeast_atMost_shift_0 [of \"m - h\" m, where ?'a = 'a]\n          apply (auto simp add: of_nat_diff field_simps)\n          done\n        have \"?m1 n * ?p b n =\n          prod (\\<lambda>i. b - of_nat i) {0.. n - k - 1} * pochhammer (b - of_nat n + 1) k\"\n          using kn' m h unfolding th20 th21 apply simp\n          apply (subst prod.union_disjoint [symmetric])\n          apply auto\n          apply (rule prod.cong)\n          apply auto\n          done\n        then have th2: \"(?m1 n * ?p b n)/pochhammer (b - of_nat n + 1) k =\n          prod (\\<lambda>i. b - of_nat i) {0.. n - k - 1}\"\n          using nz' by (simp add: field_simps)\n        have \"(?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k) =\n          ((?m1 k * ?p (of_nat n) k) / ?f n) * ((?m1 n * ?p b n)/pochhammer (b - of_nat n + 1) k)\"\n          using bnz0\n          by (simp add: field_simps)\n        also have \"\\<dots> = b gchoose (n - k)\"\n          unfolding th1 th2\n          using kn' m h\n          apply (simp add: field_simps gbinomial_mult_fact)\n          apply (rule prod.cong)\n          apply auto\n          done\n        finally show ?thesis by simp\n      qed\n    qed\n    then show ?gchoose and ?pochhammer\n      apply (cases \"n = 0\")\n      using nz'\n      apply auto\n      done\n  qed\n  have \"?r = ((a + b) gchoose n) * (of_nat (fact n) / (?m1 n * pochhammer (- b) n))\"\n    unfolding gbinomial_pochhammer\n    using bn0 by (auto simp add: field_simps)\n  also have \"\\<dots> = ?l\"\n    unfolding gbinomial_Vandermonde[symmetric]\n    apply (simp add: th00)\n    unfolding gbinomial_pochhammer\n    using bn0\n    apply (simp add: sum_distrib_right sum_distrib_left field_simps)\n    done\n  finally show ?thesis by simp\nqed\n\nlemma Vandermonde_pochhammer:\n  fixes a :: \"'a::field_char_0\"\n  assumes c: \"\\<forall>i \\<in> {0..< n}. c \\<noteq> - of_nat i\"\n  shows \"sum (\\<lambda>k. (pochhammer a k * pochhammer (- (of_nat n)) k) /\n    (of_nat (fact k) * pochhammer c k)) {0..n} = pochhammer (c - a) n / pochhammer c n\"\nproof -\n  let ?a = \"- a\"\n  let ?b = \"c + of_nat n - 1\"\n  have h: \"\\<forall> j \\<in>{0..< n}. ?b \\<noteq> of_nat j\"\n    using c\n    apply (auto simp add: algebra_simps of_nat_diff)\n    apply (erule_tac x = \"n - j - 1\" in ballE)\n    apply (auto simp add: of_nat_diff algebra_simps)\n    done\n  have th0: \"pochhammer (- (?a + ?b)) n = (- 1)^n * pochhammer (c - a) n\"\n    unfolding pochhammer_minus\n    by (simp add: algebra_simps)\n  have th1: \"pochhammer (- ?b) n = (- 1)^n * pochhammer c n\"\n    unfolding pochhammer_minus\n    by simp\n  have nz: \"pochhammer c n \\<noteq> 0\" using c\n    by (simp add: pochhammer_eq_0_iff)\n  from Vandermonde_pochhammer_lemma[where a = \"?a\" and b=\"?b\" and n=n, OF h, unfolded th0 th1]\n  show ?thesis\n    using nz by (simp add: field_simps sum_distrib_left)\nqed\n\n\nsubsubsection \\<open>Formal trigonometric functions\\<close>\n\ndefinition \"fps_sin (c::'a::field_char_0) =\n  Abs_fps (\\<lambda>n. if even n then 0 else (- 1) ^((n - 1) div 2) * c^n /(of_nat (fact n)))\"\n\ndefinition \"fps_cos (c::'a::field_char_0) =\n  Abs_fps (\\<lambda>n. if even n then (- 1) ^ (n div 2) * c^n / (of_nat (fact n)) else 0)\"\n\nlemma fps_sin_deriv:\n  \"fps_deriv (fps_sin c) = fps_const c * fps_cos c\"\n  (is \"?lhs = ?rhs\")\nproof (rule fps_ext)\n  fix n :: nat\n  show \"?lhs $ n = ?rhs $ n\"\n  proof (cases \"even n\")\n    case True\n    have \"?lhs$n = of_nat (n+1) * (fps_sin c $ (n+1))\" by simp\n    also have \"\\<dots> = of_nat (n+1) * ((- 1)^(n div 2) * c^Suc n / of_nat (fact (Suc n)))\"\n      using True by (simp add: fps_sin_def)\n    also have \"\\<dots> = (- 1)^(n div 2) * c^Suc n * (of_nat (n+1) / (of_nat (Suc n) * of_nat (fact n)))\"\n      unfolding fact_Suc of_nat_mult\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    also have \"\\<dots> = (- 1)^(n div 2) *c^Suc n / of_nat (fact n)\"\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    finally show ?thesis\n      using True by (simp add: fps_cos_def field_simps)\n  next\n    case False\n    then show ?thesis\n      by (simp_all add: fps_deriv_def fps_sin_def fps_cos_def)\n  qed\nqed\n\nlemma fps_cos_deriv: \"fps_deriv (fps_cos c) = fps_const (- c)* (fps_sin c)\"\n  (is \"?lhs = ?rhs\")\nproof (rule fps_ext)\n  have th0: \"- ((- 1::'a) ^ n) = (- 1)^Suc n\" for n\n    by simp\n  show \"?lhs $ n = ?rhs $ n\" for n\n  proof (cases \"even n\")\n    case False\n    then have n0: \"n \\<noteq> 0\" by presburger\n    from False have th1: \"Suc ((n - 1) div 2) = Suc n div 2\"\n      by (cases n) simp_all\n    have \"?lhs$n = of_nat (n+1) * (fps_cos c $ (n+1))\" by simp\n    also have \"\\<dots> = of_nat (n+1) * ((- 1)^((n + 1) div 2) * c^Suc n / of_nat (fact (Suc n)))\"\n      using False by (simp add: fps_cos_def)\n    also have \"\\<dots> = (- 1)^((n + 1) div 2)*c^Suc n * (of_nat (n+1) / (of_nat (Suc n) * of_nat (fact n)))\"\n      unfolding fact_Suc of_nat_mult\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    also have \"\\<dots> = (- 1)^((n + 1) div 2) * c^Suc n / of_nat (fact n)\"\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    also have \"\\<dots> = (- ((- 1)^((n - 1) div 2))) * c^Suc n / of_nat (fact n)\"\n      unfolding th0 unfolding th1 by simp\n    finally show ?thesis\n      using False by (simp add: fps_sin_def field_simps)\n  next\n    case True\n    then show ?thesis\n      by (simp_all add: fps_deriv_def fps_sin_def fps_cos_def)\n  qed\nqed\n\nlemma fps_sin_cos_sum_of_squares: \"(fps_cos c)\\<^sup>2 + (fps_sin c)\\<^sup>2 = 1\"\n  (is \"?lhs = _\")\nproof -\n  have \"fps_deriv ?lhs = 0\"\n    apply (simp add:  fps_deriv_power fps_sin_deriv fps_cos_deriv)\n    apply (simp add: field_simps fps_const_neg[symmetric] del: fps_const_neg)\n    done\n  then have \"?lhs = fps_const (?lhs $ 0)\"\n    unfolding fps_deriv_eq_0_iff .\n  also have \"\\<dots> = 1\"\n    by (auto simp add: fps_eq_iff numeral_2_eq_2 fps_mult_nth fps_cos_def fps_sin_def)\n  finally show ?thesis .\nqed\n\nlemma fps_sin_nth_0 [simp]: \"fps_sin c $ 0 = 0\"\n  unfolding fps_sin_def by simp\n\nlemma fps_sin_nth_1 [simp]: \"fps_sin c $ 1 = c\"\n  unfolding fps_sin_def by simp\n\nlemma fps_sin_nth_add_2:\n    \"fps_sin c $ (n + 2) = - (c * c * fps_sin c $ n / (of_nat (n + 1) * of_nat (n + 2)))\"\n  unfolding fps_sin_def\n  apply (cases n)\n  apply simp\n  apply (simp add: nonzero_divide_eq_eq nonzero_eq_divide_eq del: of_nat_Suc fact_Suc)\n  apply simp\n  done\n\nlemma fps_cos_nth_0 [simp]: \"fps_cos c $ 0 = 1\"\n  unfolding fps_cos_def by simp\n\nlemma fps_cos_nth_1 [simp]: \"fps_cos c $ 1 = 0\"\n  unfolding fps_cos_def by simp\n\nlemma fps_cos_nth_add_2:\n  \"fps_cos c $ (n + 2) = - (c * c * fps_cos c $ n / (of_nat (n + 1) * of_nat (n + 2)))\"\n  unfolding fps_cos_def\n  apply (simp add: nonzero_divide_eq_eq nonzero_eq_divide_eq del: of_nat_Suc fact_Suc)\n  apply simp\n  done\n\nlemma nat_induct2: \"P 0 \\<Longrightarrow> P 1 \\<Longrightarrow> (\\<And>n. P n \\<Longrightarrow> P (n + 2)) \\<Longrightarrow> P (n::nat)\"\n  unfolding One_nat_def numeral_2_eq_2\n  apply (induct n rule: nat_less_induct)\n  apply (case_tac n)\n  apply simp\n  apply (rename_tac m)\n  apply (case_tac m)\n  apply simp\n  apply (rename_tac k)\n  apply (case_tac k)\n  apply simp_all\n  done\n\nlemma nat_add_1_add_1: \"(n::nat) + 1 + 1 = n + 2\"\n  by simp\n\nlemma eq_fps_sin:\n  assumes 0: \"a $ 0 = 0\"\n    and 1: \"a $ 1 = c\"\n    and 2: \"fps_deriv (fps_deriv a) = - (fps_const c * fps_const c * a)\"\n  shows \"a = fps_sin c\"\n  apply (rule fps_ext)\n  apply (induct_tac n rule: nat_induct2)\n  apply (simp add: 0)\n  apply (simp add: 1 del: One_nat_def)\n  apply (rename_tac m, cut_tac f=\"\\<lambda>a. a $ m\" in arg_cong [OF 2])\n  apply (simp add: nat_add_1_add_1 fps_sin_nth_add_2\n              del: One_nat_def of_nat_Suc of_nat_add add_2_eq_Suc')\n  apply (subst minus_divide_left)\n  apply (subst nonzero_eq_divide_eq)\n  apply (simp del: of_nat_add of_nat_Suc)\n  apply (simp only: ac_simps)\n  done\n\nlemma eq_fps_cos:\n  assumes 0: \"a $ 0 = 1\"\n    and 1: \"a $ 1 = 0\"\n    and 2: \"fps_deriv (fps_deriv a) = - (fps_const c * fps_const c * a)\"\n  shows \"a = fps_cos c\"\n  apply (rule fps_ext)\n  apply (induct_tac n rule: nat_induct2)\n  apply (simp add: 0)\n  apply (simp add: 1 del: One_nat_def)\n  apply (rename_tac m, cut_tac f=\"\\<lambda>a. a $ m\" in arg_cong [OF 2])\n  apply (simp add: nat_add_1_add_1 fps_cos_nth_add_2\n              del: One_nat_def of_nat_Suc of_nat_add add_2_eq_Suc')\n  apply (subst minus_divide_left)\n  apply (subst nonzero_eq_divide_eq)\n  apply (simp del: of_nat_add of_nat_Suc)\n  apply (simp only: ac_simps)\n  done\n\nlemma mult_nth_0 [simp]: \"(a * b) $ 0 = a $ 0 * b $ 0\"\n  by (simp add: fps_mult_nth)\n\nlemma mult_nth_1 [simp]: \"(a * b) $ 1 = a $ 0 * b $ 1 + a $ 1 * b $ 0\"\n  by (simp add: fps_mult_nth)\n\nlemma fps_sin_add: \"fps_sin (a + b) = fps_sin a * fps_cos b + fps_cos a * fps_sin b\"\n  apply (rule eq_fps_sin [symmetric], simp, simp del: One_nat_def)\n  apply (simp del: fps_const_neg fps_const_add fps_const_mult\n              add: fps_const_add [symmetric] fps_const_neg [symmetric]\n                   fps_sin_deriv fps_cos_deriv algebra_simps)\n  done\n\nlemma fps_cos_add: \"fps_cos (a + b) = fps_cos a * fps_cos b - fps_sin a * fps_sin b\"\n  apply (rule eq_fps_cos [symmetric], simp, simp del: One_nat_def)\n  apply (simp del: fps_const_neg fps_const_add fps_const_mult\n              add: fps_const_add [symmetric] fps_const_neg [symmetric]\n                   fps_sin_deriv fps_cos_deriv algebra_simps)\n  done\n\nlemma fps_sin_even: \"fps_sin (- c) = - fps_sin c\"\n  by (auto simp add: fps_eq_iff fps_sin_def)\n\nlemma fps_cos_odd: \"fps_cos (- c) = fps_cos c\"\n  by (auto simp add: fps_eq_iff fps_cos_def)\n\ndefinition \"fps_tan c = fps_sin c / fps_cos c\"\n\nlemma fps_tan_deriv: \"fps_deriv (fps_tan c) = fps_const c / (fps_cos c)\\<^sup>2\"\nproof -\n  have th0: \"fps_cos c $ 0 \\<noteq> 0\" by (simp add: fps_cos_def)\n  from this have \"fps_cos c \\<noteq> 0\" by (intro notI) simp\n  hence \"fps_deriv (fps_tan c) =\n           fps_const c * (fps_cos c^2 + fps_sin c^2) / (fps_cos c^2)\"\n    by (simp add: fps_tan_def fps_divide_deriv power2_eq_square algebra_simps\n                  fps_sin_deriv fps_cos_deriv fps_const_neg[symmetric] div_mult_swap\n             del: fps_const_neg)\n  also note fps_sin_cos_sum_of_squares\n  finally show ?thesis by simp\nqed\n\ntext \\<open>Connection to E c over the complex numbers --- Euler and de Moivre.\\<close>\n\nlemma Eii_sin_cos: \"E (\\<i> * c) = fps_cos c + fps_const \\<i> * fps_sin c\"\n  (is \"?l = ?r\")\nproof -\n  have \"?l $ n = ?r $ n\" for n\n  proof (cases \"even n\")\n    case True\n    then obtain m where m: \"n = 2 * m\" ..\n    show ?thesis\n      by (simp add: m fps_sin_def fps_cos_def power_mult_distrib power_mult power_minus [of \"c ^ 2\"])\n  next\n    case False\n    then obtain m where m: \"n = 2 * m + 1\" ..\n    show ?thesis\n      by (simp add: m fps_sin_def fps_cos_def power_mult_distrib\n        power_mult power_minus [of \"c ^ 2\"])\n  qed\n  then show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\nlemma E_minus_ii_sin_cos: \"E (- (\\<i> * c)) = fps_cos c - fps_const \\<i> * fps_sin c\"\n  unfolding minus_mult_right Eii_sin_cos by (simp add: fps_sin_even fps_cos_odd)\n\nlemma fps_const_minus: \"fps_const (c::'a::group_add) - fps_const d = fps_const (c - d)\"\n  by (fact fps_const_sub)\n\nlemma fps_of_int: \"fps_const (of_int c) = of_int c\"\n  by (induction c) (simp_all add: fps_const_minus [symmetric] fps_of_nat fps_const_neg [symmetric] \n                             del: fps_const_minus fps_const_neg)\n\nlemma fps_numeral_fps_const: \"numeral i = fps_const (numeral i :: 'a::comm_ring_1)\"\n  by (fact numeral_fps_const) (* FIXME: duplicate *)\n\nlemma fps_cos_Eii: \"fps_cos c = (E (\\<i> * c) + E (- \\<i> * c)) / fps_const 2\"\nproof -\n  have th: \"fps_cos c + fps_cos c = fps_cos c * fps_const 2\"\n    by (simp add: numeral_fps_const)\n  show ?thesis\n    unfolding Eii_sin_cos minus_mult_commute\n    by (simp add: fps_sin_even fps_cos_odd numeral_fps_const fps_divide_unit fps_const_inverse th)\nqed\n\nlemma fps_sin_Eii: \"fps_sin c = (E (\\<i> * c) - E (- \\<i> * c)) / fps_const (2*\\<i>)\"\nproof -\n  have th: \"fps_const \\<i> * fps_sin c + fps_const \\<i> * fps_sin c = fps_sin c * fps_const (2 * \\<i>)\"\n    by (simp add: fps_eq_iff numeral_fps_const)\n  show ?thesis\n    unfolding Eii_sin_cos minus_mult_commute\n    by (simp add: fps_sin_even fps_cos_odd fps_divide_unit fps_const_inverse th)\nqed\n\nlemma fps_tan_Eii:\n  \"fps_tan c = (E (\\<i> * c) - E (- \\<i> * c)) / (fps_const \\<i> * (E (\\<i> * c) + E (- \\<i> * c)))\"\n  unfolding fps_tan_def fps_sin_Eii fps_cos_Eii mult_minus_left E_neg\n  apply (simp add: fps_divide_unit fps_inverse_mult fps_const_mult[symmetric] fps_const_inverse del: fps_const_mult)\n  apply simp\n  done\n\nlemma fps_demoivre:\n  \"(fps_cos a + fps_const \\<i> * fps_sin a)^n =\n    fps_cos (of_nat n * a) + fps_const \\<i> * fps_sin (of_nat n * a)\"\n  unfolding Eii_sin_cos[symmetric] E_power_mult\n  by (simp add: ac_simps)\n\n\nsubsection \\<open>Hypergeometric series\\<close>\n\n(* TODO: Rename this *)\ndefinition \"F as bs (c::'a::{field_char_0,field}) =\n  Abs_fps (\\<lambda>n. (foldl (\\<lambda>r a. r* pochhammer a n) 1 as * c^n) /\n    (foldl (\\<lambda>r b. r * pochhammer b n) 1 bs * of_nat (fact n)))\"\n\nlemma F_nth[simp]: \"F as bs c $ n =\n  (foldl (\\<lambda>r a. r* pochhammer a n) 1 as * c^n) /\n    (foldl (\\<lambda>r b. r * pochhammer b n) 1 bs * of_nat (fact n))\"\n  by (simp add: F_def)\n\nlemma foldl_mult_start:\n  fixes v :: \"'a::comm_ring_1\"\n  shows \"foldl (\\<lambda>r x. r * f x) v as * x = foldl (\\<lambda>r x. r * f x) (v * x) as \"\n  by (induct as arbitrary: x v) (auto simp add: algebra_simps)\n\nlemma foldr_mult_foldl:\n  fixes v :: \"'a::comm_ring_1\"\n  shows \"foldr (\\<lambda>x r. r * f x) as v = foldl (\\<lambda>r x. r * f x) v as\"\n  by (induct as arbitrary: v) (auto simp add: foldl_mult_start)\n\nlemma F_nth_alt:\n  \"F as bs c $ n = foldr (\\<lambda>a r. r * pochhammer a n) as (c ^ n) /\n    foldr (\\<lambda>b r. r * pochhammer b n) bs (of_nat (fact n))\"\n  by (simp add: foldl_mult_start foldr_mult_foldl)\n\nlemma F_E[simp]: \"F [] [] c = E c\"\n  by (simp add: fps_eq_iff)\n\nlemma F_1_0[simp]: \"F [1] [] c = 1/(1 - fps_const c * X)\"\nproof -\n  let ?a = \"(Abs_fps (\\<lambda>n. 1)) oo (fps_const c * X)\"\n  have th0: \"(fps_const c * X) $ 0 = 0\" by simp\n  show ?thesis unfolding gp[OF th0, symmetric]\n    by (auto simp add: fps_eq_iff pochhammer_fact[symmetric]\n      fps_compose_nth power_mult_distrib cond_value_iff sum.delta' cong del: if_weak_cong)\nqed\n\nlemma F_B[simp]: \"F [-a] [] (- 1) = fps_binomial a\"\n  by (simp add: fps_eq_iff gbinomial_pochhammer algebra_simps)\n\nlemma F_0[simp]: \"F as bs c $ 0 = 1\"\n  apply simp\n  apply (subgoal_tac \"\\<forall>as. foldl (\\<lambda>(r::'a) (a::'a). r) 1 as = 1\")\n  apply auto\n  apply (induct_tac as)\n  apply auto\n  done\n\nlemma foldl_prod_prod:\n  \"foldl (\\<lambda>(r::'b::comm_ring_1) (x::'a::comm_ring_1). r * f x) v as * foldl (\\<lambda>r x. r * g x) w as =\n    foldl (\\<lambda>r x. r * f x * g x) (v * w) as\"\n  by (induct as arbitrary: v w) (auto simp add: algebra_simps)\n\n\nlemma F_rec:\n  \"F as bs c $ Suc n = ((foldl (\\<lambda>r a. r* (a + of_nat n)) c as) /\n    (foldl (\\<lambda>r b. r * (b + of_nat n)) (of_nat (Suc n)) bs )) * F as bs c $ n\"\n  apply (simp del: of_nat_Suc of_nat_add fact_Suc)\n  apply (simp add: foldl_mult_start del: fact_Suc of_nat_Suc)\n  unfolding foldl_prod_prod[unfolded foldl_mult_start] pochhammer_Suc\n  apply (simp add: algebra_simps)\n  done\n\nlemma XD_nth[simp]: \"XD a $ n = (if n = 0 then 0 else of_nat n * a$n)\"\n  by (simp add: XD_def)\n\nlemma XD_0th[simp]: \"XD a $ 0 = 0\"\n  by simp\nlemma XD_Suc[simp]:\" XD a $ Suc n = of_nat (Suc n) * a $ Suc n\"\n  by simp\n\ndefinition \"XDp c a = XD a + fps_const c * a\"\n\nlemma XDp_nth[simp]: \"XDp c a $ n = (c + of_nat n) * a$n\"\n  by (simp add: XDp_def algebra_simps)\n\nlemma XDp_commute: \"XDp b \\<circ> XDp (c::'a::comm_ring_1) = XDp c \\<circ> XDp b\"\n  by (auto simp add: XDp_def fun_eq_iff fps_eq_iff algebra_simps)\n\nlemma XDp0 [simp]: \"XDp 0 = XD\"\n  by (simp add: fun_eq_iff fps_eq_iff)\n\nlemma XDp_fps_integral [simp]: \"XDp 0 (fps_integral a c) = X * a\"\n  by (simp add: fps_eq_iff fps_integral_def)\n\nlemma F_minus_nat:\n  \"F [- of_nat n] [- of_nat (n + m)] (c::'a::{field_char_0,field}) $ k =\n    (if k \\<le> n then\n      pochhammer (- of_nat n) k * c ^ k / (pochhammer (- of_nat (n + m)) k * of_nat (fact k))\n     else 0)\"\n  \"F [- of_nat m] [- of_nat (m + n)] (c::'a::{field_char_0,field}) $ k =\n    (if k \\<le> m then\n      pochhammer (- of_nat m) k * c ^ k / (pochhammer (- of_nat (m + n)) k * of_nat (fact k))\n     else 0)\"\n  by (auto simp add: pochhammer_eq_0_iff)\n\nlemma sum_eq_if: \"sum f {(n::nat) .. m} = (if m < n then 0 else f n + sum f {n+1 .. m})\"\n  apply simp\n  apply (subst sum.insert[symmetric])\n  apply (auto simp add: not_less sum_head_Suc)\n  done\n\nlemma pochhammer_rec_if: \"pochhammer a n = (if n = 0 then 1 else a * pochhammer (a + 1) (n - 1))\"\n  by (cases n) (simp_all add: pochhammer_rec)\n\nlemma XDp_foldr_nth [simp]: \"foldr (\\<lambda>c r. XDp c \\<circ> r) cs (\\<lambda>c. XDp c a) c0 $ n =\n    foldr (\\<lambda>c r. (c + of_nat n) * r) cs (c0 + of_nat n) * a$n\"\n  by (induct cs arbitrary: c0) (auto simp add: algebra_simps)\n\nlemma genric_XDp_foldr_nth:\n  assumes f: \"\\<forall>n c a. f c a $ n = (of_nat n + k c) * a$n\"\n  shows \"foldr (\\<lambda>c r. f c \\<circ> r) cs (\\<lambda>c. g c a) c0 $ n =\n    foldr (\\<lambda>c r. (k c + of_nat n) * r) cs (g c0 a $ n)\"\n  by (induct cs arbitrary: c0) (auto simp add: algebra_simps f)\n\nlemma dist_less_imp_nth_equal:\n  assumes \"dist f g < inverse (2 ^ i)\"\n    and\"j \\<le> i\"\n  shows \"f $ j = g $ j\"\nproof (rule ccontr)\n  assume \"f $ j \\<noteq> g $ j\"\n  hence \"f \\<noteq> g\" by auto\n  with assms have \"i < subdegree (f - g)\"\n    by (simp add: if_split_asm dist_fps_def)\n  also have \"\\<dots> \\<le> j\"\n    using \\<open>f $ j \\<noteq> g $ j\\<close> by (intro subdegree_leI) simp_all\n  finally show False using \\<open>j \\<le> i\\<close> by simp\nqed\n\nlemma nth_equal_imp_dist_less:\n  assumes \"\\<And>j. j \\<le> i \\<Longrightarrow> f $ j = g $ j\"\n  shows \"dist f g < inverse (2 ^ i)\"\nproof (cases \"f = g\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  with assms have \"dist f g = inverse (2 ^ subdegree (f - g))\"\n    by (simp add: if_split_asm dist_fps_def)\n  moreover\n  from assms and False have \"i < subdegree (f - g)\"\n    by (intro subdegree_greaterI) simp_all\n  ultimately show ?thesis by simp\nqed\n\nlemma dist_less_eq_nth_equal: \"dist f g < inverse (2 ^ i) \\<longleftrightarrow> (\\<forall>j \\<le> i. f $ j = g $ j)\"\n  using dist_less_imp_nth_equal nth_equal_imp_dist_less by blast\n\ninstance fps :: (comm_ring_1) complete_space\nproof\n  fix X :: \"nat \\<Rightarrow> 'a fps\"\n  assume \"Cauchy X\"\n  obtain M where M: \"\\<forall>i. \\<forall>m \\<ge> M i. \\<forall>j \\<le> i. X (M i) $ j = X m $ j\"\n  proof -\n    have \"\\<exists>M. \\<forall>m \\<ge> M. \\<forall>j\\<le>i. X M $ j = X m $ j\" for i\n    proof -\n      have \"0 < inverse ((2::real)^i)\" by simp\n      from metric_CauchyD[OF \\<open>Cauchy X\\<close> this] dist_less_imp_nth_equal\n      show ?thesis by blast\n    qed\n    then show ?thesis using that by metis\n  qed\n\n  show \"convergent X\"\n  proof (rule convergentI)\n    show \"X \\<longlonglongrightarrow> Abs_fps (\\<lambda>i. X (M i) $ i)\"\n      unfolding tendsto_iff\n    proof safe\n      fix e::real assume e: \"0 < e\"\n      have \"(\\<lambda>n. inverse (2 ^ n) :: real) \\<longlonglongrightarrow> 0\" by (rule LIMSEQ_inverse_realpow_zero) simp_all\n      from this and e have \"eventually (\\<lambda>i. inverse (2 ^ i) < e) sequentially\"\n        by (rule order_tendstoD)\n      then obtain i where \"inverse (2 ^ i) < e\"\n        by (auto simp: eventually_sequentially)\n      have \"eventually (\\<lambda>x. M i \\<le> x) sequentially\"\n        by (auto simp: eventually_sequentially)\n      then show \"eventually (\\<lambda>x. dist (X x) (Abs_fps (\\<lambda>i. X (M i) $ i)) < e) sequentially\"\n      proof eventually_elim\n        fix x\n        assume x: \"M i \\<le> x\"\n        have \"X (M i) $ j = X (M j) $ j\" if \"j \\<le> i\" for j\n          using M that by (metis nat_le_linear)\n        with x have \"dist (X x) (Abs_fps (\\<lambda>j. X (M j) $ j)) < inverse (2 ^ i)\"\n          using M by (force simp: dist_less_eq_nth_equal)\n        also note \\<open>inverse (2 ^ i) < e\\<close>\n        finally show \"dist (X x) (Abs_fps (\\<lambda>j. X (M j) $ j)) < e\" .\n      qed\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/Formal_Power_Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355092, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7946122232263985}}
{"text": "theory Binary_Euclidean_Algorithm \n  imports \"HOL-Computational_Algebra.Primes\" \nbegin\n\nsubsection \\<open>The binary GCD algorithm\\<close>\n\ninductive_set  bgcd :: \"(nat \\<times> nat \\<times> nat) set\" where\n  bgcdZero: \"(u, 0, u) \\<in> bgcd\"\n| bgcdEven: \"\\<lbrakk> (u, v, g) \\<in> bgcd \\<rbrakk> \\<Longrightarrow> (2*u, 2*v, 2*g) \\<in> bgcd\"\n| bgcdOdd:  \"\\<lbrakk> (u, v, g) \\<in> bgcd; \\<not> 2 dvd v \\<rbrakk> \\<Longrightarrow> (2*u, v, g) \\<in> bgcd\"\n| bgcdStep: \"\\<lbrakk> (u - v, v, g) \\<in> bgcd; v \\<le> u \\<rbrakk> \\<Longrightarrow> (u, v, g) \\<in> bgcd\"\n| bgcdSwap: \"\\<lbrakk> (v, u, g) \\<in> bgcd \\<rbrakk> \\<Longrightarrow> (u, v, g) \\<in> bgcd\"\n\nsubsection \\<open>Proving that the algorithm is correct\\<close>\n\ntext \\<open>Show that the bgcd of @{text x} und @{text y} is\nreally a divisor of both numbers\\<close>\nlemma bgcd_divides: \"(x,y,g) \\<in> bgcd \\<Longrightarrow> g dvd x \\<and> g dvd y\"\nproof (induct rule: bgcd.induct)\n  case (bgcdStep u v g)\n  with dvd_diffD show ?case\n    by blast\nqed auto\n\ntext \\<open>The bgcd of @{text x} und @{text y} really is the greatest common divisor\n of both numbers, with respect to the divides relation.\\<close>\nlemma bgcd_greatest:\n  \"(x,y,g) \\<in> bgcd \\<Longrightarrow> d dvd x \\<Longrightarrow> d dvd y \\<Longrightarrow> d dvd g\"\nproof (induct arbitrary: d rule: bgcd.induct)\n  case (bgcdEven u v g d) \n  show ?case\n    proof (cases \"2 dvd d\") \n      case True thus ?thesis using bgcdEven by (force simp add: dvd_def) \n    next\n      case False\n      thus ?thesis using bgcdEven\n        by (simp add: coprime_dvd_mult_right_iff)\n    qed\nnext\n  case (bgcdOdd u v g d)\n  hence \"coprime d 2\"\n    by fastforce\n  thus ?case using bgcdOdd\n    by (simp add: coprime_dvd_mult_right_iff)\nqed auto\n\nsubsection \\<open>Proving uniqueness and existence\\<close>\n\ntext \\<open>despite its apparent non-determinism, the relation @{text bgcd} is deterministic \n  and therefore defines a function\\<close>\nlemma bgcd_unique: \n  \"(x,y,g) \\<in> bgcd \\<Longrightarrow> (x,y,g') \\<in> bgcd \\<Longrightarrow> g = g'\"\n  by (meson bgcd_divides bgcd_greatest gcd_nat.strict_iff_not)\n\nlemma bgcd_defined_aux: \"a+b \\<le> n \\<Longrightarrow> \\<exists>g. (a, b, g) \\<in> bgcd\"\nproof (induction n arbitrary: a b rule: less_induct)\n  case (less n a b)\n  show ?case\n  proof (cases b)\n    case 0\n    thus ?thesis by (metis bgcdZero) \n  next\n    case (Suc b')\n    then have *: \"a + b' < n\"\n      using Suc_le_eq add_Suc_right less.prems by presburger\n    show ?thesis\n    proof (cases \"b \\<le> a\")\n      case True\n      thus ?thesis\n        by (metis bgcd.simps le_add1 le_add_diff_inverse less.IH [OF *])\n    next\n      case False\n      then show ?thesis\n        by (metis less.IH [OF *] Suc Suc_leI bgcd.simps le_add_diff_inverse \n            less_add_same_cancel2 nle_le zero_less_iff_neq_zero)\n    qed\n  qed\nqed\n\ntheorem bgcd_defined: \"\\<exists>!g. (a, b, g) \\<in> bgcd\"\n  using bgcd_defined_aux bgcd_unique by auto\n\ntext \\<open>Alternative proof suggested by YawarRaza7349\\<close>\nlemma bgcd_defined_aux': \"a+b = n \\<Longrightarrow> \\<exists>g. (a, b, g) \\<in> bgcd\"\nproof (induction n arbitrary: a b rule: less_induct)\n  case (less n a b)\n  then show ?case\n  proof (cases \"b \\<le> a\")\n    case True\n    with less obtain g where \"(a-b, b, g) \\<in> bgcd\"\n      by (metis add_cancel_right_right bgcd.simps le_add1 le_add_diff_inverse nat_less_le)\n    thus ?thesis\n      using True bgcd.bgcdStep by blast\n  next\n    case False\n    with less show ?thesis\n      by (metis bgcd.simps le_add_diff_inverse less_add_same_cancel2 nle_le zero_less_iff_neq_zero)\n  qed\nqed\n\nend \n\n", "meta": {"author": "lawrencecpaulson", "repo": "lawrencecpaulson.github.io", "sha": "325aed7ca359736ebed88a820f88763d248cd2c8", "save_path": "github-repos/isabelle/lawrencecpaulson-lawrencecpaulson.github.io", "path": "github-repos/isabelle/lawrencecpaulson-lawrencecpaulson.github.io/lawrencecpaulson.github.io-325aed7ca359736ebed88a820f88763d248cd2c8/Isabelle-Examples/Binary_Euclidean_Algorithm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088084787998, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7945797384708505}}
{"text": "(*  Title:      CCL/Trancl.thy\n    Author:     Martin Coen, Cambridge University Computer Laboratory\n    Copyright   1993  University of Cambridge\n*)\n\nsection {* Transitive closure of a relation *}\n\ntheory Trancl\nimports CCL\nbegin\n\ndefinition trans :: \"i set \\<Rightarrow> o\"  (*transitivity predicate*)\n  where \"trans(r) == (ALL x y z. <x,y>:r \\<longrightarrow> <y,z>:r \\<longrightarrow> <x,z>:r)\"\n\ndefinition id :: \"i set\"  (*the identity relation*)\n  where \"id == {p. EX x. p = <x,x>}\"\n\ndefinition relcomp :: \"[i set,i set] \\<Rightarrow> i set\"  (infixr \"O\" 60)  (*composition of relations*)\n  where \"r O s == {xz. EX x y z. xz = <x,z> \\<and> <x,y>:s \\<and> <y,z>:r}\"\n\ndefinition rtrancl :: \"i set \\<Rightarrow> i set\"  (\"(_^*)\" [100] 100)\n  where \"r^* == lfp(\\<lambda>s. id Un (r O s))\"\n\ndefinition trancl :: \"i set \\<Rightarrow> i set\"  (\"(_^+)\" [100] 100)\n  where \"r^+ == r O rtrancl(r)\"\n\n\nsubsection {* Natural deduction for @{text \"trans(r)\"} *}\n\nlemma transI: \"(\\<And>x y z. \\<lbrakk><x,y>:r; <y,z>:r\\<rbrakk> \\<Longrightarrow> <x,z>:r) \\<Longrightarrow> trans(r)\"\n  unfolding trans_def by blast\n\nlemma transD: \"\\<lbrakk>trans(r); <a,b>:r; <b,c>:r\\<rbrakk> \\<Longrightarrow> <a,c>:r\"\n  unfolding trans_def by blast\n\n\nsubsection {* Identity relation *}\n\nlemma idI: \"<a,a> : id\"\n  apply (unfold id_def)\n  apply (rule CollectI)\n  apply (rule exI)\n  apply (rule refl)\n  done\n\nlemma idE: \"\\<lbrakk>p: id;  \\<And>x. p = <x,x> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  apply (unfold id_def)\n  apply (erule CollectE)\n  apply blast\n  done\n\n\nsubsection {* Composition of two relations *}\n\nlemma compI: \"\\<lbrakk><a,b>:s; <b,c>:r\\<rbrakk> \\<Longrightarrow> <a,c> : r O s\"\n  unfolding relcomp_def by blast\n\n(*proof requires higher-level assumptions or a delaying of hyp_subst_tac*)\nlemma compE: \"\\<lbrakk>xz : r O s; \\<And>x y z. \\<lbrakk>xz = <x,z>; <x,y>:s; <y,z>:r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  unfolding relcomp_def by blast\n\nlemma compEpair: \"\\<lbrakk><a,c> : r O s; \\<And>y. \\<lbrakk><a,y>:s; <y,c>:r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  apply (erule compE)\n  apply (simp add: pair_inject)\n  done\n\nlemmas [intro] = compI idI\n  and [elim] = compE idE\n  and [elim!] = pair_inject\n\nlemma comp_mono: \"\\<lbrakk>r'<=r; s'<=s\\<rbrakk> \\<Longrightarrow> (r' O s') <= (r O s)\"\n  by blast\n\n\nsubsection {* The relation rtrancl *}\n\nlemma rtrancl_fun_mono: \"mono(\\<lambda>s. id Un (r O s))\"\n  apply (rule monoI)\n  apply (rule monoI subset_refl comp_mono Un_mono)+\n  apply assumption\n  done\n\nlemma rtrancl_unfold: \"r^* = id Un (r O r^*)\"\n  by (rule rtrancl_fun_mono [THEN rtrancl_def [THEN def_lfp_Tarski]])\n\n(*Reflexivity of rtrancl*)\nlemma rtrancl_refl: \"<a,a> : r^*\"\n  apply (subst rtrancl_unfold)\n  apply blast\n  done\n\n(*Closure under composition with r*)\nlemma rtrancl_into_rtrancl: \"\\<lbrakk><a,b> : r^*; <b,c> : r\\<rbrakk> \\<Longrightarrow> <a,c> : r^*\"\n  apply (subst rtrancl_unfold)\n  apply blast\n  done\n\n(*rtrancl of r contains r*)\nlemma r_into_rtrancl: \"<a,b> : r \\<Longrightarrow> <a,b> : r^*\"\n  apply (rule rtrancl_refl [THEN rtrancl_into_rtrancl])\n  apply assumption\n  done\n\n\nsubsection {* standard induction rule *}\n\nlemma rtrancl_full_induct:\n  \"\\<lbrakk><a,b> : r^*;\n      \\<And>x. P(<x,x>);\n      \\<And>x y z. \\<lbrakk>P(<x,y>); <x,y>: r^*; <y,z>: r\\<rbrakk>  \\<Longrightarrow> P(<x,z>)\\<rbrakk>\n   \\<Longrightarrow>  P(<a,b>)\"\n  apply (erule def_induct [OF rtrancl_def])\n   apply (rule rtrancl_fun_mono)\n  apply blast\n  done\n\n(*nice induction rule*)\nlemma rtrancl_induct:\n  \"\\<lbrakk><a,b> : r^*;\n      P(a);\n      \\<And>y z. \\<lbrakk><a,y> : r^*; <y,z> : r;  P(y)\\<rbrakk> \\<Longrightarrow> P(z) \\<rbrakk>\n    \\<Longrightarrow> P(b)\"\n(*by induction on this formula*)\n  apply (subgoal_tac \"ALL y. <a,b> = <a,y> \\<longrightarrow> P(y)\")\n(*now solve first subgoal: this formula is sufficient*)\n  apply blast\n(*now do the induction*)\n  apply (erule rtrancl_full_induct)\n   apply blast\n  apply blast\n  done\n\n(*transitivity of transitive closure!! -- by induction.*)\nlemma trans_rtrancl: \"trans(r^*)\"\n  apply (rule transI)\n  apply (rule_tac b = z in rtrancl_induct)\n    apply (fast elim: rtrancl_into_rtrancl)+\n  done\n\n(*elimination of rtrancl -- by induction on a special formula*)\nlemma rtranclE:\n  \"\\<lbrakk><a,b> : r^*; a = b \\<Longrightarrow> P; \\<And>y. \\<lbrakk><a,y> : r^*; <y,b> : r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  apply (subgoal_tac \"a = b | (EX y. <a,y> : r^* \\<and> <y,b> : r)\")\n   prefer 2\n   apply (erule rtrancl_induct)\n    apply blast\n   apply blast\n  apply blast\n  done\n\n\nsubsection {* The relation trancl *}\n\nsubsubsection {* Conversions between trancl and rtrancl *}\n\nlemma trancl_into_rtrancl: \"<a,b> : r^+ \\<Longrightarrow> <a,b> : r^*\"\n  apply (unfold trancl_def)\n  apply (erule compEpair)\n  apply (erule rtrancl_into_rtrancl)\n  apply assumption\n  done\n\n(*r^+ contains r*)\nlemma r_into_trancl: \"<a,b> : r \\<Longrightarrow> <a,b> : r^+\"\n  unfolding trancl_def by (blast intro: rtrancl_refl)\n\n(*intro rule by definition: from rtrancl and r*)\nlemma rtrancl_into_trancl1: \"\\<lbrakk><a,b> : r^*; <b,c> : r\\<rbrakk> \\<Longrightarrow> <a,c> : r^+\"\n  unfolding trancl_def by blast\n\n(*intro rule from r and rtrancl*)\nlemma rtrancl_into_trancl2: \"\\<lbrakk><a,b> : r; <b,c> : r^*\\<rbrakk> \\<Longrightarrow> <a,c> : r^+\"\n  apply (erule rtranclE)\n   apply (erule subst)\n   apply (erule r_into_trancl)\n  apply (rule trans_rtrancl [THEN transD, THEN rtrancl_into_trancl1])\n    apply (assumption | rule r_into_rtrancl)+\n  done\n\n(*elimination of r^+ -- NOT an induction rule*)\nlemma tranclE:\n  \"\\<lbrakk><a,b> : r^+;\n    <a,b> : r \\<Longrightarrow> P;\n    \\<And>y. \\<lbrakk><a,y> : r^+; <y,b> : r\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  apply (subgoal_tac \"<a,b> : r | (EX y. <a,y> : r^+ \\<and> <y,b> : r)\")\n   apply blast\n  apply (unfold trancl_def)\n  apply (erule compEpair)\n  apply (erule rtranclE)\n   apply blast\n  apply (blast intro!: rtrancl_into_trancl1)\n  done\n\n(*Transitivity of r^+.\n  Proved by unfolding since it uses transitivity of rtrancl. *)\nlemma trans_trancl: \"trans(r^+)\"\n  apply (unfold trancl_def)\n  apply (rule transI)\n  apply (erule compEpair)+\n  apply (erule rtrancl_into_rtrancl [THEN trans_rtrancl [THEN transD, THEN compI]])\n    apply assumption+\n  done\n\nlemma trancl_into_trancl2: \"\\<lbrakk><a,b> : r; <b,c> : r^+\\<rbrakk> \\<Longrightarrow> <a,c> : r^+\"\n  apply (rule r_into_trancl [THEN trans_trancl [THEN transD]])\n   apply assumption+\n  done\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/CCL/Trancl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8807970654616711, "lm_q1q2_score": 0.794409085166424}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection {* Bubblesort *}\n\ntheory Bubblesort\nimports \"~~/src/HOL/Library/Multiset\"\nbegin\n\ntext{* This is \\emph{a} version of bubblesort. *}\n\ncontext linorder\nbegin\n\nfun bubble_min where\n\"bubble_min [] = []\" |\n\"bubble_min [x] = [x]\" |\n\"bubble_min (x#xs) =\n  (case bubble_min xs of y#ys \\<Rightarrow> if x>y then y#x#ys else x#y#ys)\"\n\nlemma size_bubble_min: \"size(bubble_min xs) = size xs\"\nby(induction xs rule: bubble_min.induct) (auto split: list.split)\n\nlemma bubble_min_eq_Nil_iff[simp]: \"bubble_min xs = [] \\<longleftrightarrow> xs = []\"\nby (metis length_0_conv size_bubble_min)\n\nlemma bubble_minD_size: \"bubble_min (xs) = ys \\<Longrightarrow> size xs = size ys\"\nby(auto simp: size_bubble_min)\n\nfunction (sequential) bubblesort where\n\"bubblesort []  = []\" |\n\"bubblesort [x] = [x]\" |\n\"bubblesort xs  = (case bubble_min xs of y#ys \\<Rightarrow> y # bubblesort ys)\"\nby pat_completeness auto\n\ntermination\nproof\n  show \"wf(measure size)\" by simp\nnext\n  fix x1 x2 y :: 'a fix xs ys :: \"'a list\"\n  show \"bubble_min(x1#x2#xs) = y#ys \\<Longrightarrow> (ys, x1#x2#xs) \\<in> measure size\"\n    by(auto simp: size_bubble_min dest!: bubble_minD_size split: list.splits if_splits)\nqed\n\nlemma mset_bubble_min: \"multiset_of (bubble_min xs) = multiset_of xs\"\napply(induction xs rule: bubble_min.induct)\n  apply simp\n apply simp\napply (auto simp: add_eq_conv_ex split: list.split)\ndone\n\nlemma bubble_minD_mset:\n  \"bubble_min (xs) = ys \\<Longrightarrow> multiset_of xs = multiset_of ys\"\nby(auto simp: mset_bubble_min)\n\nlemma mset_bubblesort:\n  \"multiset_of (bubblesort xs) = multiset_of xs\"\napply(induction xs rule: bubblesort.induct)\n  apply simp\n apply simp\nby(auto split: list.splits if_splits dest: bubble_minD_mset)\n  (metis add_eq_conv_ex mset_bubble_min multiset_of.simps(2))\n\nlemma set_bubblesort: \"set (bubblesort xs) = set xs\"\nby(rule mset_bubblesort[THEN multiset_of_eq_setD])\n\nlemma bubble_min_min: \"bubble_min xs = y#ys \\<Longrightarrow> z \\<in> set ys \\<Longrightarrow> y \\<le> z\"\napply(induction xs arbitrary: y ys z rule: bubble_min.induct)\n  apply simp\n apply simp\napply (fastforce split: list.splits if_splits dest!: sym[of \"a#b\" for a b])\ndone\n\nlemma sorted_bubblesort: \"sorted(bubblesort xs)\"\napply(induction xs rule: bubblesort.induct)\n  apply simp\n apply simp\napply (fastforce simp: set_bubblesort split: list.split if_splits\n  intro!: sorted.Cons dest: bubble_min_min)\ndone\n\nend\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/ex/Bubblesort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.8807970748488297, "lm_q1q2_score": 0.7944090843446915}}
{"text": "theory CS_Chap4\n\nimports Main \"~~/src/HOL/IMP/Star\"\n\nbegin\n\n(* EXERCISE 4.1 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n  \"set Tip = {}\" |\n  \"set (Node l x r) = set l \\<union> {x} \\<union> set r\"\n\nvalue \"set (tree (Node (Node Tip 1 Tip) 2 (Node Tip 1 Tip)))\"\n\n(*\n  A tree is ordered if all elements on the left \n  of the topmost element are smaller than it and\n  all elements on his right are bigger than it.\n*)\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\" |\n  \"ord (Node l x r) = (\n    (\\<forall> a \\<in> (set l). (a < x)) \\<and> \n    (\\<forall> b \\<in> (set r). (b > x))\n  )\"\n\nvalue \"ord ((Node (Node Tip 1 Tip) 2 (Node Tip 1 Tip)))\"\nvalue \"ord ((Node (Node Tip 1 Tip) 2 (Node Tip 3 Tip)))\" \n(* It works! *)\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n  \"ins n Tip = (Node Tip n Tip)\" |\n  \"ins n (Node l x r ) = (\n    if n < x then Node (ins n l) x r\n    else if n > x then Node l x (ins n r)\n    else Node l x r\n  )\"\n\nvalue \"ins 1 ((Node (Node Tip 2 Tip) 3 (Node Tip 4 Tip)))\"\nvalue \"ins 3 ((Node (Node Tip 2 Tip) 3 (Node Tip 4 Tip)))\"\nvalue \"ins 5 ((Node (Node Tip 2 Tip) 3 (Node Tip 4 Tip)))\" \n(* It works! *)\n\ntheorem ins_correctness_1 [simp] : \"set(ins x t) = {x} \\<union> set t\"\n  apply (induction t)\n  apply (auto)\n  done\n\ntheorem ins_correctness_2 : \"ord t \\<Longrightarrow> ord (ins n t)\"\n  apply (induction t)\n  apply (auto)\n  done\n\n\n(* EXERCISE 4.2 *)\n(* Very trivial. Just follow exercise commands. *)\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n  empt': \"palindrome []\" |\n  sing': \"palindrome [x]\" |\n  step': \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\ntheorem palindrome_reverse: \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction rule: palindrome.induct)\n  apply(simp_all)\n  done\n\n\n(* EXERCISE 4.3 *)\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl' : \"star' r x x\" |\n  step' : \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\n(* These two next lemmas are not required, but let's play a little with the definitions*)\nlemma \"star r x x \\<Longrightarrow> star' r x x\"\n  apply (induction)\n  apply (rule refl')\n  apply (simp_all)\n  done\n\nlemma \"star' r x x \\<Longrightarrow> star r x x\"\n  apply (induction)\n  apply (simp_all)\n  done\n\n(*\n  Ok, now let's prove the first formula. \n  The lemma below is required for the subgoal left\n  after we apply the reflection rule of star\n*)\nlemma star_trans: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n  apply (auto intro: star.refl star.step)\n  done\n\ntheorem  \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: star'.induct)\n  apply (rule star.refl)\n  apply (auto simp add: star_trans)\n  done\n\n(* As above, the theorem left a subgoal and we need this lemma *)\nlemma star'_trans: \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply (induction rule: star'.induct)\n  apply (auto intro: star'.refl' star'.step')\n  done\n\ntheorem \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n  apply (auto simp add: star'_trans intro: star'.refl')\n  done\n\n\n(* EXERCISE 4.4 *)\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  izero: \"iter r 0 x x\" |\n  istep: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (n+1) x z\"\n\ntheorem \"star r x y \\<Longrightarrow> \\<exists> n. iter r n x y\"\n  apply (induction rule: star.induct)\n  apply (auto intro: izero istep)\n  done\n\n\n(* EXERCISE 4.5 *)\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\n  s1: \"S []\" |\n  s2: \"S w \\<Longrightarrow> S (a # w @ [b])\" |\n  s3: \"\\<lbrakk>S w1; S w2\\<rbrakk> \\<Longrightarrow> S (w1 @ w2)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\n  t1: \"T []\" |\n  t2: \"\\<lbrakk>T w1; T w2\\<rbrakk> \\<Longrightarrow> T(w1 @ a # w2 @ [b])\"\n\nlemma T_to_s3 : \"\\<lbrakk>T w2; T w1\\<rbrakk> \\<Longrightarrow> T (w1 @ w2)\"\n  apply (induction rule: T.induct)\n  apply (simp)\n  apply (metis t2 append_assoc)\n  done\n\n(* \n  Here, the subgoals are complexer.\n  \n  We use t1 rule to kill the subgoal concerning the empty string\n  The lemma above kills the subgoal about the appending operation. \n  However, this raises the problem of s2. For that, we use Metis in\n  rules t1 and t2, in addition to Nil constant.\n  \n  We are basically saying that T can produce strings that S also can. \n*)\ntheorem S_to_T: \"S w \\<Longrightarrow> T w\"\n  apply (induction rule: S.induct)\n    apply (simp add: t1)\n  apply (metis t1 t2 append_Nil)\n  apply (auto intro: T_to_s3)\n  done\n\n(* \n  All subgoals here claims for S rules.\n  Hence, this theorem goes easily with them. \n*)\ntheorem T_to_S : \"T w \\<Longrightarrow> S w\"\n  apply (induction rule: T.induct)\n  apply (auto intro: s1 s2 s3)\n  done\n\n(* If we proved that T w \\<Longrightarrow> S w and S w \\<Longrightarrow> T w, then T w = S w! *)\ncorollary \"S w = T w\"\n  apply (auto simp add: T_to_S S_to_T)\n  done\n\nend", "meta": {"author": "rodopoulos", "repo": "isabelling", "sha": "9a92853c98c76802ffc6acc6e535efe3ea7f4176", "save_path": "github-repos/isabelle/rodopoulos-isabelling", "path": "github-repos/isabelle/rodopoulos-isabelling/isabelling-9a92853c98c76802ffc6acc6e535efe3ea7f4176/concrete-semantics/CS_Chap4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.794364420708324}}
{"text": "theory BExp imports AExp begin\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\n\nvalue \"bval (Less (V ''x'') (Plus (N 3) (V ''y'')))\n            <''x'' := 3, ''y'' := 1>\"\n\n\nsubsection \"Constant Folding\"\n\ntext \\<open>Optimizing constructors:\\<close>\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\" |\n\"less a\\<^sub>1 a\\<^sub>2 = Less a\\<^sub>1 a\\<^sub>2\"\n\n\n\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply auto\ndone\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc v) = Bc(\\<not> v)\" |\n\"not b = Not b\"\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction )\napply auto\ndone\n\ntext \\<open>Now the overall optimizer:\\<close>\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\nvalue \"bsimp (And (Less (N 0) (N 1)) b)\"\n\nvalue \"bsimp (And (Less (N 1) (N 0)) (Bc True))\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply auto\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Complete/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605946, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.7942998087069464}}
{"text": "theory P9 imports Main begin\n\nfun pow :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"pow x 0 = 1\" | \"pow x (Suc n) = (x * (pow x n))\"\n\nlemma pow_mul [simp]: \"pow x m * pow x n = (pow x (m+n))\"\n  apply (induct n)\n   apply auto\n  done\n\ntheorem pow_mult: \"pow x (m * n) = pow (pow x m) n\"\nproof (induct n)\ncase 0\n  thus ?case by simp\nnext\n  case (Suc a)\n  thus ?case\n  proof -\n    assume 1: \"pow x (m * a) = pow (pow x m) a\"\n    have \"pow (pow x m) (Suc a) = pow (pow x m) 1 * pow (pow x m) a\" by simp\n    also have \"... = pow x (m * 1) * pow x (m * a)\" using 1 by simp\n    finally have \"... = pow x (m * 1 + m * a)\" by simp\n    thus \"pow x (m * Suc a) = pow (pow x m) (Suc a)\" using 1 by simp\n  qed\nqed\n\nfun sum :: \"nat list \\<Rightarrow> nat\" where\n\"sum Nil = 0\" | \"sum (x # xs) = (x + sum xs)\"\n\n\n\ntheorem sum_rev: \"sum (rev ns) = sum ns\"\n  apply (induct ns)\n   apply auto\n  done\n\nfun Sum :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"Sum f 0 = 0\" | \"Sum f (Suc n::nat) = f n + Sum f n\"\n\ntheorem \"Sum (\\<lambda>i. f i + g i) k = Sum f k + Sum g k\"\n  apply (induct k)\n   apply auto\n  done\n\ntheorem \"Sum f (k + l) = Sum f k + (if (l=0) then 0 else Sum (\\<lambda>x. f (k+x)) l)\"\n  apply (induct l)\n  apply auto\n  done\n\ntheorem \"Sum f k = sum (map f [0..<k])\"\n  apply (induct k)\n   apply auto\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P9.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545348152283, "lm_q2_score": 0.837619959279793, "lm_q1q2_score": 0.7941931628428827}}
{"text": "(* ---------------------------------------------------------------------------- *)\nsection \\<open>Riemann sphere\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>The extended complex plane $\\mathbb{C}P^1$ can be identified with a Riemann (unit) sphere\n$\\Sigma$ by means of stereographic projection. The sphere is projected from its north pole $N$ to\nthe $xOy$ plane (identified with $\\mathbb{C}$). This projection establishes a bijective map $sp$\nbetween $\\Sigma \\setminus \\{N\\}$ and the finite complex plane $\\mathbb{C}$. The infinite point is\ndefined as the image of $N$.\\<close>\n\ntheory Riemann_Sphere\nimports Homogeneous_Coordinates Circlines \"HOL-Analysis.Product_Vector\"\nbegin\n\ntext \\<open>Coordinates in $\\mathbb{R}^3$\\<close>\ntype_synonym R3 = \"real \\<times> real \\<times> real\"\n\ntext \\<open>Type of points of $\\Sigma$\\<close>\nabbreviation unit_sphere where\n  \"unit_sphere \\<equiv> {(x::real, y::real, z::real). x*x + y*y + z*z = 1}\"\n\ntypedef riemann_sphere = \"unit_sphere\"\n  by (rule_tac x=\"(1, 0, 0)\" in exI) simp\n\nsetup_lifting type_definition_riemann_sphere\n\nlemma sphere_bounds':\n  assumes \"x*x + y*y + z*z = (1::real)\"\n  shows \"-1 \\<le> x \\<and> x \\<le> 1\"\nproof-\n  from assms have \"x*x \\<le> 1\"\n    by (smt real_minus_mult_self_le)\n  hence \"x\\<^sup>2 \\<le> 1\\<^sup>2\" \"(- x)\\<^sup>2 \\<le> 1\\<^sup>2\"\n    by (auto simp add: power2_eq_square)\n  show \"-1 \\<le> x \\<and> x \\<le> 1\"\n  proof (cases \"x \\<ge> 0\")\n    case True\n    thus ?thesis\n      using \\<open>x\\<^sup>2 \\<le> 1\\<^sup>2\\<close>\n      by (smt power2_le_imp_le)      \n  next\n    case False\n    thus ?thesis\n      using \\<open>(-x)\\<^sup>2 \\<le> 1\\<^sup>2\\<close>\n      by (smt power2_le_imp_le)      \n  qed\nqed\n\nlemma sphere_bounds:\n  assumes \"x*x + y*y + z*z = (1::real)\"\n  shows \"-1 \\<le> x \\<and> x \\<le> 1\"  \"-1 \\<le> y \\<and> y \\<le> 1\"  \"-1 \\<le> z \\<and> z \\<le> 1\"\n  using assms\n  using sphere_bounds'[of x y z] sphere_bounds'[of y x z] sphere_bounds'[of z x y]\n  by (auto simp add: field_simps)\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Parametrization of the unit sphere in polar coordinates\\<close>\n(* ---------------------------------------------------------------------------- *)\n\nlemma sphere_params_on_sphere:\n  fixes \\<alpha> \\<beta> :: real\n  assumes \"x = cos \\<alpha> * cos \\<beta>\" and \"y = cos \\<alpha> * sin \\<beta>\" \"z = sin \\<alpha>\"\n  shows \"x*x + y*y + z*z = 1\"\nproof-\n  have \"x*x + y*y = (cos \\<alpha> * cos \\<alpha>) * (cos \\<beta> * cos \\<beta>) + (cos \\<alpha> * cos \\<alpha>) * (sin \\<beta> * sin \\<beta>)\"\n    using assms\n    by simp\n  hence \"x*x + y*y = cos \\<alpha> * cos \\<alpha>\"\n    using sin_cos_squared_add3[of \\<beta>]\n    by (subst (asm) distrib_left[symmetric]) (simp add: field_simps)\n  thus ?thesis\n    using assms\n    using sin_cos_squared_add3[of \\<alpha>]\n    by simp\nqed\n\nlemma sphere_params:\n  fixes x y z :: real\n  assumes \"x*x + y*y + z*z = 1\"\n  shows \"x = cos (arcsin z) * cos (atan2 y x) \\<and> y = cos (arcsin z) * sin (atan2 y x) \\<and> z = sin (arcsin z)\"\nproof (cases \"z=1 \\<or> z = -1\")\n  case True\n  hence \"x = 0 \\<and> y = 0\"\n    using assms\n    by auto\n  thus ?thesis\n    using \\<open>z = 1 \\<or> z = -1\\<close>\n    by (auto simp add: cos_arcsin)\nnext\n  case False\n  hence \"x \\<noteq> 0 \\<or> y \\<noteq> 0\"\n    using assms\n    by (auto simp add: square_eq_1_iff)\n  thus ?thesis\n    using real_sqrt_unique[of y \"1 - z*z\"]\n    using real_sqrt_unique[of \"-y\" \"1 - z*z\"]\n    using sphere_bounds[OF assms] assms\n    by (auto simp add: cos_arcsin cos_arctan sin_arctan power2_eq_square field_simps real_sqrt_divide atan2_def)\nqed\n\nlemma ex_sphere_params:\n  assumes \"x*x + y*y + z*z = 1\"\n  shows \"\\<exists> \\<alpha> \\<beta>. x = cos \\<alpha> * cos \\<beta> \\<and> y = cos \\<alpha> * sin \\<beta> \\<and> z = sin \\<alpha> \\<and> -pi / 2 \\<le> \\<alpha> \\<and> \\<alpha> \\<le> pi / 2 \\<and> -pi \\<le> \\<beta> \\<and> \\<beta> < pi\"\nusing assms arcsin_bounded[of z] sphere_bounds[of x y z]\nby (rule_tac x=\"arcsin z\" in exI, rule_tac x=\"atan2 y x\" in exI) (simp add: sphere_params arcsin_bounded atan2_bounded)\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Stereographic and inverse stereographic projection\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Stereographic projection\\<close>\n\ndefinition stereographic_r3_cvec :: \"R3 \\<Rightarrow> complex_vec\" where\n[simp]: \"stereographic_r3_cvec M = (let (x, y, z) =  M in\n     (if (x, y, z) \\<noteq> (0, 0, 1) then\n           (x + \\<i> * y, cor (1 - z))\n      else\n           (1, 0)\n     ))\"\n\n\nlift_definition stereographic_r3_hcoords :: \"R3 \\<Rightarrow> complex_homo_coords\" is stereographic_r3_cvec\n  by (auto split: if_split_asm simp add: cor_eq_0)\n\nlift_definition stereographic :: \"riemann_sphere \\<Rightarrow> complex_homo\" is stereographic_r3_hcoords\n  done\n\ntext \\<open>Inverse stereographic projection\\<close>\n\ndefinition inv_stereographic_cvec_r3 :: \"complex_vec \\<Rightarrow> R3\" where [simp]:\n  \"inv_stereographic_cvec_r3 z = (\n     let (z1, z2) = z\n       in if z2 = 0 then\n              (0, 0, 1)\n          else\n             let z = z1/z2;\n                 X = Re (2*z / (1 + z*cnj z));\n                 Y = Im (2*z / (1 + z*cnj z));\n                 Z = ((cmod z)\\<^sup>2 - 1) / (1 + (cmod z)\\<^sup>2)\n               in (X, Y, Z))\"\n\nlemma Re_stereographic:\n  shows \"Re (2 * z / (1 + z * cnj z)) = 2 * Re z / (1 + (cmod z)\\<^sup>2)\"\n  using one_plus_square_neq_zero\n  by (subst complex_mult_cnj_cmod, subst Re_divide_real) (auto simp add: power2_eq_square)\n\nlemma Im_stereographic: \n  shows \"Im (2 * z / (1 + z * cnj z)) = 2 * Im z / (1 + (cmod z)\\<^sup>2)\"\n  using one_plus_square_neq_zero\n  by (subst complex_mult_cnj_cmod, subst Im_divide_real) (auto simp add: power2_eq_square)\n\nlemma inv_stereographic_on_sphere:\n  assumes \"X = Re (2*z / (1 + z*cnj z))\" and \"Y = Im (2*z / (1 + z*cnj z))\" and \"Z = ((cmod z)\\<^sup>2 - 1) / (1 + (cmod z)\\<^sup>2)\"\n  shows \"X*X + Y*Y + Z*Z = 1\"\nproof-\n  have \"1 + (cmod z)\\<^sup>2 \\<noteq> 0\"\n    by (smt power2_less_0)\n  thus ?thesis\n    using assms\n    by (simp add: Re_stereographic Im_stereographic)\n       (cases z, simp add: power2_eq_square real_sqrt_mult[symmetric] add_divide_distrib[symmetric], simp add: complex_norm power2_eq_square field_simps)\nqed\n\nlift_definition inv_stereographic_hcoords_r3 :: \"complex_homo_coords \\<Rightarrow> R3\" is inv_stereographic_cvec_r3\n  done\n\nlift_definition inv_stereographic :: \"complex_homo \\<Rightarrow> riemann_sphere\" is inv_stereographic_hcoords_r3\nproof transfer\n  fix v v'\n  assume 1: \"v \\<noteq> vec_zero\" \"v' \\<noteq> vec_zero\" \"v \\<approx>\\<^sub>v v'\"\n  obtain v1 v2 v'1 v'2 where *: \"v = (v1, v2)\" \"v' = (v'1, v'2)\"\n    by (cases v, cases v', auto)\n  obtain x y z where\n    **: \"inv_stereographic_cvec_r3 v = (x, y, z)\"\n    by (cases \"inv_stereographic_cvec_r3 v\", blast)\n  have \"inv_stereographic_cvec_r3 v \\<in> unit_sphere\"\n  proof (cases \"v2 = 0\")\n    case True\n    thus ?thesis\n      using *\n      by simp\n  next\n    case False\n    thus ?thesis\n      using * ** inv_stereographic_on_sphere[of x \"v1 / v2\" y z]\n      by simp\n  qed\n  moreover\n  have \"inv_stereographic_cvec_r3 v = inv_stereographic_cvec_r3 v'\"\n    using 1 * **\n    by (auto split: if_split if_split_asm)\n  ultimately\n  show \"inv_stereographic_cvec_r3 v \\<in> unit_sphere \\<and>\n        inv_stereographic_cvec_r3 v = inv_stereographic_cvec_r3 v'\"\n    by simp\nqed\n\ntext \\<open>North pole\\<close>\ndefinition North_R3 :: R3 where\n  [simp]: \"North_R3 = (0, 0, 1)\"\nlift_definition North :: \"riemann_sphere\" is North_R3\n  by simp\n\nlemma stereographic_North: \n  shows \"stereographic x = \\<infinity>\\<^sub>h \\<longleftrightarrow> x = North\"\n  by (transfer, transfer, auto split: if_split_asm)\n\ntext \\<open>Stereographic and inverse stereographic projection are mutually inverse.\\<close>\n\nlemma stereographic_inv_stereographic':\n  assumes\n  z: \"z = z1/z2\" and \"z2 \\<noteq> 0\" and\n  X: \"X = Re (2*z / (1 + z*cnj z))\" and Y: \"Y = Im (2*z / (1 + z*cnj z))\" and Z: \"Z = ((cmod z)\\<^sup>2 - 1) / (1 + (cmod z)\\<^sup>2)\"\n  shows \"\\<exists> k. k \\<noteq> 0 \\<and> (X + \\<i>*Y, complex_of_real (1 - Z)) = k *\\<^sub>s\\<^sub>v (z1, z2)\"\nproof-\n  have \"1 + (cmod z)\\<^sup>2 \\<noteq> 0\"\n    by (metis one_power2 sum_power2_eq_zero_iff zero_neq_one)\n  hence \"(1 - Z) = 2 / (1 + (cmod z)\\<^sup>2)\"\n    using Z\n    by (auto simp add: field_simps)\n  hence \"cor (1 - Z) = 2 / cor (1 + (cmod z)\\<^sup>2)\"\n    by auto\n  moreover\n  have \"X = 2 * Re(z) / (1 + (cmod z)\\<^sup>2)\"\n    using X\n    by (simp add: Re_stereographic)\n  have \"Y = 2 * Im(z) / (1 + (cmod z)\\<^sup>2)\"\n    using Y\n    by (simp add: Im_stereographic)\n  have \"X + \\<i>*Y = 2 * z / cor (1 + (cmod z)\\<^sup>2)\"\n    using \\<open>1 + (cmod z)\\<^sup>2 \\<noteq> 0\\<close>\n    unfolding Complex_eq[of X Y, symmetric]\n    by (subst \\<open>X = 2*Re(z) / (1 + (cmod z)\\<^sup>2)\\<close>, subst \\<open>Y = 2*Im(z) / (1 + (cmod z)\\<^sup>2)\\<close>, simp add: Complex_scale4 Complex_scale1)\n  moreover\n  have \"1 + (cor (cmod (z1 / z2)))\\<^sup>2 \\<noteq> 0\"\n    by (rule one_plus_square_neq_zero)\n  ultimately\n  show ?thesis\n    using \\<open>z2 \\<noteq> 0\\<close> \\<open>1 + (cmod z)\\<^sup>2 \\<noteq> 0\\<close>\n    by (simp, subst z)+\n       (rule_tac x=\"(2 / (1 + (cor (cmod (z1 / z2)))\\<^sup>2)) / z2\" in exI, auto)\nqed\n\nlemma stereographic_inv_stereographic [simp]:\n  shows \"stereographic (inv_stereographic w) = w\"\nproof-\n  have \"w = stereographic (inv_stereographic w)\"\n  proof (transfer, transfer)\n    fix w\n    assume \"w \\<noteq> vec_zero\"\n    obtain w1 w2 where *: \"w = (w1, w2)\"\n      by (cases w, auto)\n    obtain x y z where **: \"inv_stereographic_cvec_r3 w = (x, y, z)\"\n      by (cases \"inv_stereographic_cvec_r3 w\", blast)\n    show \"w \\<approx>\\<^sub>v stereographic_r3_cvec (inv_stereographic_cvec_r3 w)\"\n      using \\<open>w \\<noteq> vec_zero\\<close> stereographic_inv_stereographic'[of \"w1/w2\" w1 w2 x y z] * **\n      by (auto simp add: split_def Let_def split: if_split_asm)\n  qed\n  thus ?thesis\n    by simp\nqed\n\ntext \\<open>Stereographic projection is bijective function\\<close>\n\nlemma bij_stereographic:\n  shows \"bij stereographic\"\n  unfolding bij_def inj_on_def surj_def\nproof (safe)\n  fix a b\n  assume \"stereographic a = stereographic b\"\n  thus \"a = b\"\n  proof (transfer, transfer)\n    fix a b :: R3\n    obtain xa ya za xb yb zb where\n      *: \"a = (xa, ya, za)\" \"b = (xb, yb, zb)\"\n      by (cases a, cases b, auto)\n    assume **: \"a \\<in> unit_sphere\" \"b \\<in> unit_sphere\" \"stereographic_r3_cvec a \\<approx>\\<^sub>v stereographic_r3_cvec b\"\n    show \"a = b\"\n    proof (cases \"a = (0, 0, 1) \\<or> b = (0, 0, 1)\")\n      case True\n      thus ?thesis\n        using * **\n        by (simp split: if_split_asm) force+\n    next\n      case False\n      then obtain k where ++: \"k \\<noteq> 0\" \"cor xb + \\<i> * cor yb = k * (cor xa + \\<i> * cor ya)\" \"1 - cor zb = k * (1 - cor za)\"\n        using * **\n        by (auto split: if_split_asm)\n\n      {\n          assume \"xb + xa*zb = xa + xb*za\"\n                 \"yb + ya*zb = ya + yb*za\"\n                 \"xa*xa + ya*ya + za*za = 1\" \"xb*xb + yb*yb + zb*zb = 1\"\n                 \"za \\<noteq> 1\" \"zb \\<noteq> 1\"\n          hence \"xa = xb \\<and> ya = yb \\<and> za = zb\"\n            by algebra\n      } note *** = this\n\n      have \"za \\<noteq> 1\" \"zb \\<noteq> 1\"\n        using False * **\n        by auto\n      have \"k = (1 - cor zb) / (1 - cor za)\"\n        using \\<open>1 - cor zb = k * (1 - cor za)\\<close> \\<open>za \\<noteq> 1\\<close>\n        by simp\n      hence \"(1 - cor za) * (cor xb + \\<i> * cor yb) = (1 - cor zb) * (cor xa + \\<i> * cor ya)\"\n        using \\<open>za \\<noteq> 1\\<close> ++(2)\n        by simp\n      hence \"xb + xa*zb = xa + xb*za\"\n            \"yb + ya*zb = ya + yb*za\"\n            \"xa*xa + ya*ya + za*za = 1\" \"xb*xb + yb*yb + zb*zb = 1\"\n        using * ** \\<open>za \\<noteq> 1\\<close>\n        apply (simp_all add: field_simps)\n        unfolding complex_of_real_def imaginary_unit.ctr\n        by (simp_all add: legacy_Complex_simps)\n      thus ?thesis\n          using * ** *** \\<open>za \\<noteq> 1\\<close> \\<open>zb \\<noteq> 1\\<close>\n          by simp\n      qed\n  qed\nnext\n  fix y\n  show \"\\<exists> x. y = stereographic x\"\n    by (rule_tac x=\"inv_stereographic y\" in exI, simp)\nqed\n\n\nlemma inv_stereographic_stereographic [simp]: \n  shows \"inv_stereographic (stereographic x) = x\"\n  using stereographic_inv_stereographic[of \"stereographic x\"]\n  using bij_stereographic\n  unfolding bij_def inj_on_def\n  by simp\n\nlemma inv_stereographic_is_inv:\n  shows \"inv_stereographic = inv stereographic\"\n  by (rule inv_equality[symmetric], simp_all)\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Circles on the sphere\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Circlines in the plane correspond to circles on the Riemann sphere, and we formally establish\nthis connection. Every circle in three--dimensional space can be obtained as the intersection of a\nsphere and a plane. We establish a one-to-one correspondence between circles on the Riemann sphere\nand planes in space. Note that the plane need not intersect the sphere, but we will still say that\nit defines a single imaginary circle. However, for one special circline (the one with the identity\nrepresentative matrix), there does not exist a plane in $\\mathbb{R}^3$ that would correspond to it\n--- in order to have this, instead of considering planes in $\\mathbb{R}^3$, we must consider three\ndimensional projective space and consider the infinite (hyper)plane.\\<close>\n\ntext \\<open>Planes in $R^3$ are given by equations $ax+by+cz=d$. Two four-tuples of coefficients $(a, b, c,\nd)$ give the same plane iff they are proportional.\\<close>\n\ntype_synonym R4 = \"real \\<times> real \\<times> real \\<times> real\"\n\nfun mult_sv :: \"real \\<Rightarrow> R4 \\<Rightarrow> R4\" (infixl \"*\\<^sub>s\\<^sub>v\\<^sub>4\" 100) where\n  \"k *\\<^sub>s\\<^sub>v\\<^sub>4 (a, b, c, d) = (k*a, k*b, k*c, k*d)\"\n\nabbreviation plane_vectors where\n  \"plane_vectors \\<equiv> {(a::real, b::real, c::real, d::real). a \\<noteq> 0 \\<or> b \\<noteq> 0 \\<or> c \\<noteq> 0 \\<or> d \\<noteq> 0}\"\n\ntypedef plane_vec = \"plane_vectors\"\n  by (rule_tac x=\"(1, 1, 1, 1)\" in exI) simp\n\nsetup_lifting type_definition_plane_vec\n\ndefinition plane_vec_eq_r4 :: \"R4 \\<Rightarrow> R4 \\<Rightarrow> bool\" where\n  [simp]: \"plane_vec_eq_r4 v1 v2 \\<longleftrightarrow> (\\<exists> k. k \\<noteq> 0 \\<and> v2 = k *\\<^sub>s\\<^sub>v\\<^sub>4 v1)\"\n\nlift_definition plane_vec_eq :: \"plane_vec \\<Rightarrow> plane_vec \\<Rightarrow> bool\" is plane_vec_eq_r4\n  done\n\nlemma mult_sv_one [simp]:\n  shows \"1 *\\<^sub>s\\<^sub>v\\<^sub>4 x = x\"\n  by (cases x) simp\n\nlemma mult_sv_distb [simp]:\n  shows \"x *\\<^sub>s\\<^sub>v\\<^sub>4 (y *\\<^sub>s\\<^sub>v\\<^sub>4 v) = (x*y) *\\<^sub>s\\<^sub>v\\<^sub>4 v\"\n  by (cases v) simp\n\nquotient_type plane = plane_vec / plane_vec_eq\nproof (rule equivpI)\n  show \"reflp plane_vec_eq\"\n    unfolding reflp_def\n    by (auto simp add: plane_vec_eq_def) (rule_tac x=\"1\" in exI, simp)\nnext\n  show \"symp plane_vec_eq\"\n    unfolding symp_def\n    by (auto simp add: plane_vec_eq_def) (rule_tac x=\"1/k\" in exI, simp)\nnext\n  show \"transp plane_vec_eq\"\n    unfolding transp_def\n    by (auto simp add: plane_vec_eq_def) (rule_tac x=\"ka*k\" in exI, simp)\nqed\n\ntext \\<open>Plane coefficients give a linear equation and the point on the Riemann sphere lies on the\ncircle determined by the plane iff its representation satisfies that linear equation.\\<close>\n\ndefinition on_sphere_circle_r4_r3 :: \"R4 \\<Rightarrow> R3 \\<Rightarrow> bool\" where\n  [simp]: \"on_sphere_circle_r4_r3 \\<alpha> A \\<longleftrightarrow>\n      (let (X, Y, Z) = A;\n           (a, b, c, d) = \\<alpha>\n        in a*X + b*Y + c*Z + d = 0)\"\n\nlift_definition on_sphere_circle_vec :: \"plane_vec \\<Rightarrow> R3 \\<Rightarrow> bool\" is on_sphere_circle_r4_r3\n  done\n\nlift_definition on_sphere_circle :: \"plane \\<Rightarrow> riemann_sphere \\<Rightarrow> bool\" is on_sphere_circle_vec\nproof (transfer)\n  fix pv1 pv2 :: R4 and w :: R3\n  obtain a1 b1 c1 d1 a2 b2 c2 d2 x y z where\n    *: \"pv1 = (a1, b1, c1, d1)\" \"pv2 = (a2, b2, c2, d2)\" \"w = (x, y, z)\"\n    by (cases pv1, cases pv2, cases w, auto)\n  assume \"pv1 \\<in> plane_vectors\" \"pv2 \\<in> plane_vectors\" \"w \\<in> unit_sphere\" \"plane_vec_eq_r4 pv1 pv2\"\n  then obtain k where **: \"a2 = k*a1\" \"b2 = k*b1\" \"c2 = k*c1\" \"d2 = k*d1\" \"k \\<noteq> 0\"\n    using *\n    by auto\n  have \"k * a1 * x + k * b1 * y + k * c1 * z + k * d1 = k*(a1*x + b1*y + c1*z + d1)\"\n    by (simp add: field_simps)\n  thus \"on_sphere_circle_r4_r3 pv1 w = on_sphere_circle_r4_r3 pv2 w\"\n    using * **\n    by simp\nqed\n\ndefinition sphere_circle_set where\n  \"sphere_circle_set \\<alpha> = {A. on_sphere_circle \\<alpha> A}\"\n\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Connections of circlines in the plane and circles on the Riemann sphere\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>We introduce stereographic and inverse stereographic projection between circles on the Riemann\nsphere and circlines in the extended complex plane.\\<close>\n\ndefinition inv_stereographic_circline_cmat_r4 :: \"complex_mat \\<Rightarrow> R4\" where\n  [simp]: \"inv_stereographic_circline_cmat_r4 H  =\n            (let (A, B, C, D) = H\n              in (Re (B+C), Re(\\<i>*(C-B)), Re(A-D), Re(D+A)))\"\n\nlift_definition inv_stereographic_circline_clmat_pv :: \"circline_mat \\<Rightarrow> plane_vec\" is inv_stereographic_circline_cmat_r4\n  by (auto simp add: hermitean_def mat_adj_def mat_cnj_def real_imag_0 eq_cnj_iff_real)\n\nlift_definition inv_stereographic_circline :: \"circline \\<Rightarrow> plane\" is inv_stereographic_circline_clmat_pv\n  apply transfer\n  apply simp\n  apply (erule exE)\n  apply (rule_tac x=\"k\" in exI)\n  apply (case_tac \"circline_mat1\", case_tac \"circline_mat2\")\n  apply (simp add: field_simps)\n  done\n\ndefinition stereographic_circline_r4_cmat :: \"R4 \\<Rightarrow> complex_mat\" where\n[simp]: \"stereographic_circline_r4_cmat \\<alpha> =\n         (let (a, b, c, d) = \\<alpha>\n           in (cor ((c+d)/2) , ((cor a + \\<i> * cor b)/2), ((cor a - \\<i> * cor b)/2), cor ((d-c)/2)))\"\n\nlift_definition stereographic_circline_pv_clmat :: \"plane_vec \\<Rightarrow> circline_mat\" is stereographic_circline_r4_cmat\n  by (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\n\nlift_definition stereographic_circline :: \"plane \\<Rightarrow> circline\" is stereographic_circline_pv_clmat\n  apply transfer\n  apply transfer\n  apply (case_tac plane_vec1, case_tac plane_vec2, simp, erule exE, rule_tac x=k in exI, simp add: field_simps)\n  done\n\ntext \\<open>Stereographic and inverse stereographic projection of circlines are mutually inverse.\\<close>\n\nlemma stereographic_circline_inv_stereographic_circline:\n  shows \"stereographic_circline \\<circ> inv_stereographic_circline = id\"\nproof (rule ext, simp)\n  fix H\n  show \"stereographic_circline (inv_stereographic_circline H) = H\"\n  proof (transfer, transfer)\n    fix H\n    assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\"\n    obtain A B C D where HH: \"H = (A, B, C, D)\"\n      by (cases \"H\") auto\n    have \"is_real A\" \"is_real D\" \"C = cnj B\"\n      using HH hh hermitean_elems[of A B C D]\n      by auto\n    thus \"circline_eq_cmat (stereographic_circline_r4_cmat (inv_stereographic_circline_cmat_r4 H)) H\"\n      using HH\n      apply simp\n      apply (rule_tac x=1 in exI, cases B)\n      by (smt add_uminus_conv_diff complex_cnj_add complex_cnj_complex_of_real complex_cnj_i complex_cnj_mult complex_cnj_one complex_eq distrib_left_numeral mult.commute mult.left_commute mult.left_neutral mult_cancel_right2 mult_minus_left of_real_1 one_add_one)\n  qed\nqed\n\ntext \\<open>Stereographic and inverse stereographic projection of circlines are mutually inverse.\\<close>\nlemma inv_stereographic_circline_stereographic_circline:\n  \"inv_stereographic_circline \\<circ> stereographic_circline = id\"\nproof (rule ext, simp)\n  fix \\<alpha>\n  show \"inv_stereographic_circline (stereographic_circline \\<alpha>) = \\<alpha>\"\n  proof (transfer, transfer)\n    fix \\<alpha>\n    assume aa: \"\\<alpha> \\<in> plane_vectors\"\n    obtain a b c d where AA: \"\\<alpha> = (a, b, c, d)\"\n      by (cases \"\\<alpha>\") auto\n    thus \"plane_vec_eq_r4 (inv_stereographic_circline_cmat_r4 (stereographic_circline_r4_cmat \\<alpha>)) \\<alpha>\"\n      using AA\n      by simp (rule_tac x=1 in exI, auto simp add: field_simps complex_of_real_def)\n  qed\nqed\n\nlemma stereographic_sphere_circle_set'':\n  shows \"on_sphere_circle (inv_stereographic_circline H) z \\<longleftrightarrow>\n         on_circline H (stereographic z)\"\nproof (transfer, transfer)\n  fix M :: R3 and H :: complex_mat\n  assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\" \"M \\<in> unit_sphere\"\n  obtain A B C D where HH: \"H = (A, B, C, D)\"\n    by (cases \"H\") auto\n  have *: \"is_real A\" \"is_real D\" \"C = cnj B\"\n    using hh HH hermitean_elems[of A B C D]\n    by auto\n  obtain x y z where MM: \"M = (x, y, z)\"\n    by (cases \"M\") auto\n  show \"on_sphere_circle_r4_r3 (inv_stereographic_circline_cmat_r4 H) M \\<longleftrightarrow>\n        on_circline_cmat_cvec H (stereographic_r3_cvec M)\" (is \"?lhs = ?rhs\")\n  proof\n    assume ?lhs\n    show ?rhs\n    proof (cases \"z=1\")\n      case True\n      hence \"x = 0\" \"y = 0\"\n        using MM hh\n        by auto\n      thus ?thesis\n        using * \\<open>?lhs\\<close> HH MM \\<open>z=1\\<close>\n        by (cases A, simp add: vec_cnj_def Complex_eq Let_def)\n    next\n      case False\n      hence \"Re A*(1+z) + 2*Re B*x + 2*Im B*y + Re D*(1-z) = 0\"\n        using * \\<open>?lhs\\<close> HH MM\n        by (simp add: Let_def field_simps)\n      hence \"(Re A*(1+z) + 2*Re B*x + 2*Im B*y + Re D*(1-z))*(1-z) = 0\"\n        by simp\n      hence \"Re A*(1+z)*(1-z) + 2*Re B*x*(1-z) + 2*Im B*y*(1-z) + Re D*(1-z)*(1-z) = 0\"\n        by (simp add: field_simps)\n      moreover\n      have \"x*x+y*y = (1+z)*(1-z)\"\n        using MM hh\n        by (simp add: field_simps)\n      ultimately\n      have \"Re A*(x*x+y*y) + 2*Re B*x*(1-z) + 2*Im B*y*(1-z) + Re D*(1-z)*(1-z) = 0\"\n        by simp\n      hence \"(x * Re A + (1 - z) * Re B) * x - (- (y * Re A) + - ((1 - z) * Im B)) * y + (x * Re B + y * Im B + (1 - z) * Re D) * (1 - z) = 0\"\n        by (simp add: field_simps)\n      thus ?thesis\n        using \\<open>z \\<noteq> 1\\<close> HH MM * \\<open>Re A*(1+z) + 2*Re B*x + 2*Im B*y + Re D*(1-z) = 0\\<close>\n        apply (simp add: Let_def vec_cnj_def)\n        apply (subst complex_eq_iff)\n        apply (simp add: field_simps)\n        done\n    qed\n  next\n    assume ?rhs\n    show ?lhs\n    proof (cases \"z=1\")\n      case True\n      hence \"x = 0\" \"y = 0\"\n        using MM hh\n        by auto\n      thus ?thesis\n        using HH MM \\<open>?rhs\\<close> \\<open>z = 1\\<close>\n        by (simp add: Let_def vec_cnj_def)\n    next\n      case False\n      hence \"(x * Re A + (1 - z) * Re B) * x - (- (y * Re A) + - ((1 - z) * Im B)) * y + (x * Re B + y * Im B + (1 - z) * Re D) * (1 - z) = 0\"\n        using HH MM * \\<open>?rhs\\<close>\n        by (simp add: Let_def vec_cnj_def complex_eq_iff)\n      hence \"Re A*(x*x+y*y) + 2*Re B*x*(1-z) + 2*Im B*y*(1-z) + Re D*(1-z)*(1-z) = 0\"\n        by (simp add: field_simps)\n      moreover\n      have \"x*x + y*y = (1+z)*(1-z)\"\n        using MM hh\n        by (simp add: field_simps)\n      ultimately\n      have \"Re A*(1+z)*(1-z) + 2*Re B*x*(1-z) + 2*Im B*y*(1-z) + Re D*(1-z)*(1-z) = 0\"\n        by simp\n      hence \"(Re A*(1+z) + 2*Re B*x + 2*Im B*y + Re D*(1-z))*(1-z) = 0\"\n        by (simp add: field_simps)\n      hence \"Re A*(1+z) + 2*Re B*x + 2*Im B*y + Re D*(1-z) = 0\"\n        using \\<open>z \\<noteq> 1\\<close>\n        by simp\n      thus ?thesis\n        using MM HH *\n        by (simp add: field_simps)\n    qed\n  qed\nqed\n\nlemma stereographic_sphere_circle_set' [simp]:\n  shows \"stereographic ` sphere_circle_set (inv_stereographic_circline H) =\n         circline_set H\"\nunfolding sphere_circle_set_def circline_set_def\napply safe\nproof-\n  fix x\n  assume \"on_sphere_circle (inv_stereographic_circline H) x\"\n  thus \"on_circline H (stereographic x)\"\n    using stereographic_sphere_circle_set''\n    by simp\nnext\n  fix x\n  assume \"on_circline H x\"\n  show \"x \\<in> stereographic ` {z. on_sphere_circle (inv_stereographic_circline H) z}\"\n  proof\n    show \"x = stereographic (inv_stereographic x)\"\n      by simp\n  next\n    show \"inv_stereographic x \\<in> {z. on_sphere_circle (inv_stereographic_circline H) z}\"\n      using stereographic_sphere_circle_set''[of H \"inv_stereographic x\"] \\<open>on_circline H x\\<close>\n      by simp\n  qed\nqed\n\ntext \\<open>The projection of the set of points on a circle on the Riemann sphere is exactly the set of\npoints on the circline obtained by the just introduced circle stereographic projection.\\<close>\nlemma stereographic_sphere_circle_set:\n  shows \"stereographic ` sphere_circle_set H = circline_set (stereographic_circline H)\"\nusing stereographic_sphere_circle_set'[of \"stereographic_circline H\"]\nusing inv_stereographic_circline_stereographic_circline\nunfolding comp_def\nby (metis id_apply)\n\ntext \\<open>Stereographic projection of circlines is bijective.\\<close>\nlemma bij_stereographic_circline:\n  shows \"bij stereographic_circline\"\n  using stereographic_circline_inv_stereographic_circline inv_stereographic_circline_stereographic_circline\n  using o_bij by blast\n\ntext \\<open>Inverse stereographic projection is bijective.\\<close>\nlemma bij_inv_stereographic_circline:\n  shows \"bij inv_stereographic_circline\"\n  using stereographic_circline_inv_stereographic_circline inv_stereographic_circline_stereographic_circline\n  using o_bij by blast\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/Riemann_Sphere.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.7941281762133651}}
{"text": "section \\<open>Continued fraction expansions for square roots of naturals\\<close>\ntheory Sqrt_Nat_Cfrac\nimports\n  Quadratic_Irrationals\n  \"HOL-Library.While_Combinator\"\n  \"HOL-Library.IArray\"\nbegin\n\nlemma butlast_nth [simp]: \"n < length xs - 1 \\<Longrightarrow> butlast xs ! n = xs ! n\"\n  by (induction xs arbitrary: n) (auto simp: nth_Cons split: nat.splits)\n\ntext \\<open>\n  The following is the length of the period in the continued fraction expansion of\n  $\\sqrt{D}$ for a natural number $D$.\n\\<close>\ndefinition sqrt_nat_period_length :: \"nat \\<Rightarrow> nat\" where\n  \"sqrt_nat_period_length D =\n     (if is_square D then 0\n      else (LEAST l. l > 0 \\<and> (\\<forall>n. cfrac_nth (cfrac_of_real (sqrt D)) (Suc n + l) =\n                                  cfrac_nth (cfrac_of_real (sqrt D)) (Suc n))))\"\n\ntext \\<open>  \n  Next, we define a more workable representation for the continued fraction expansion of\n  $\\sqrt{D}$ consisting of the period length, the natural number $\\lfloor\\sqrt{D}\\rfloor$, and\n  the content of the period.\n\\<close>\ndefinition sqrt_cfrac_info :: \"nat \\<Rightarrow> nat \\<times> nat \\<times> nat list\" where\n  \"sqrt_cfrac_info D =\n     (sqrt_nat_period_length D, Discrete.sqrt D, \n      map (\\<lambda>n. nat (cfrac_nth (cfrac_of_real (sqrt D)) (Suc n))) [0..<sqrt_nat_period_length D])\"\n\nlemma sqrt_nat_period_length_square [simp]: \"is_square D \\<Longrightarrow> sqrt_nat_period_length D = 0\"\n  by (auto simp: sqrt_nat_period_length_def)\n\ndefinition sqrt_cfrac :: \"nat \\<Rightarrow> cfrac\"\n  where \"sqrt_cfrac D = cfrac_of_real (sqrt (real D))\"\n\ncontext\n  fixes D D' :: nat\n  defines \"D' \\<equiv> nat \\<lfloor>sqrt D\\<rfloor>\"\nbegin\n\ntext \\<open>\n  A number $\\alpha = \\frac{\\sqrt D + p}{q}$ for \\<open>p, q \\<in> \\<nat>\\<close> is called a \\<^emph>\\<open>reduced quadratic surd\\<close>\n  if $\\alpha > 1$ and $bar\\alpha \\in (-1;0)$, where $\\bar\\alpha$ denotes the conjugate\n  $\\frac{-\\sqrt D + p}{q}$.\n\n  It is furthermore called \\<^emph>\\<open>associated\\<close> to $D$ if \\<open>q\\<close> divides \\<open>D - p\\<^sup>2\\<close>.\n\\<close>\ndefinition red_assoc :: \"nat \\<times> nat \\<Rightarrow> bool\" where\n  \"red_assoc = (\\<lambda>(p, q).\n     q > 0 \\<and> q dvd (D - p\\<^sup>2) \\<and> (sqrt D + p) / q > 1 \\<and> (-sqrt D + p) / q \\<in> {-1<..<0})\"\n\ntext \\<open>\n  The following two functions convert between a surd represented as a pair of natural numbers\n  and the actual real number and its conjugate:\n\\<close>\ndefinition surd_to_real :: \"nat \\<times> nat \\<Rightarrow> real\"\n  where \"surd_to_real = (\\<lambda>(p, q). (sqrt D + p) / q)\"\n\ndefinition surd_to_real_cnj :: \"nat \\<times> nat \\<Rightarrow> real\"\n  where \"surd_to_real_cnj = (\\<lambda>(p, q). (-sqrt D + p) / q)\"\n\ntext \\<open>\n  The next function performs a single step in the continued fraction expansion of $\\sqrt{D}$.\n\\<close>\ndefinition sqrt_remainder_step :: \"nat \\<times> nat \\<Rightarrow> nat \\<times> nat\" where\n  \"sqrt_remainder_step = (\\<lambda>(p, q). let X = (p + D') div q; p' = X * q - p in (p', (D - p'\\<^sup>2) div q))\"\n\ntext \\<open>\n  If we iterate this step function starting from the surd\n   $\\frac{1}{\\sqrt{D} - \\lfloor\\sqrt{D}\\rfloor}$, we get the entire expansion.\n\\<close>\ndefinition sqrt_remainder_surd :: \"nat \\<Rightarrow> nat \\<times> nat\"\n  where \"sqrt_remainder_surd = (\\<lambda>n. (sqrt_remainder_step ^^ n) (D', D - D'\\<^sup>2))\"\n\ncontext\n  fixes sqrt_cfrac_nth :: \"nat \\<Rightarrow> nat\" and l\n  assumes nonsquare: \"\\<not>is_square D\"\n  defines \"sqrt_cfrac_nth \\<equiv> (\\<lambda>n. case sqrt_remainder_surd n of (p, q) \\<Rightarrow> (D' + p) div q)\"\n  defines \"l \\<equiv> sqrt_nat_period_length D\"\nbegin\n\nlemma D'_pos: \"D' > 0\"\n  using nonsquare by (auto simp: D'_def of_nat_ge_1_iff intro: Nat.gr0I)\n\nlemma D'_sqr_less_D: \"D'\\<^sup>2 < D\"\nproof -\n  have \"D' \\<le> sqrt D\" by (auto simp: D'_def)\n  hence \"real D' ^ 2 \\<le> sqrt D ^ 2\" by (intro power_mono) auto\n  also have \"\\<dots> = D\" by simp\n  finally have \"D'\\<^sup>2 \\<le> D\" by simp\n  moreover from nonsquare have \"D \\<noteq> D'\\<^sup>2\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma red_assoc_imp_irrat:\n  assumes \"red_assoc pq\"\n  shows   \"surd_to_real pq \\<notin> \\<rat>\"\nproof \n  assume rat: \"surd_to_real pq \\<in> \\<rat>\"\n  with assms rat show False using irrat_sqrt_nonsquare[OF nonsquare]\n    by (auto simp: field_simps red_assoc_def surd_to_real_def divide_in_Rats_iff2 add_in_Rats_iff1)\nqed\n\nlemma surd_to_real_cnj_irrat:\n  assumes \"red_assoc pq\"\n  shows   \"surd_to_real_cnj pq \\<notin> \\<rat>\"\nproof \n  assume rat: \"surd_to_real_cnj pq \\<in> \\<rat>\"\n  with assms rat show False using irrat_sqrt_nonsquare[OF nonsquare]\n    by (auto simp: field_simps red_assoc_def surd_to_real_cnj_def divide_in_Rats_iff2 diff_in_Rats_iff1)\nqed\n\nlemma surd_to_real_nonneg [intro]: \"surd_to_real pq \\<ge> 0\"\n  by (auto simp: surd_to_real_def case_prod_unfold divide_simps intro!: divide_nonneg_nonneg)\n\nlemma surd_to_real_pos [intro]: \"red_assoc pq \\<Longrightarrow> surd_to_real pq > 0\"\n  by (auto simp: surd_to_real_def case_prod_unfold divide_simps red_assoc_def\n           intro!: divide_nonneg_nonneg)\n\nlemma surd_to_real_nz [simp]: \"red_assoc pq \\<Longrightarrow> surd_to_real pq \\<noteq> 0\"\n  by (auto simp: surd_to_real_def case_prod_unfold divide_simps red_assoc_def\n           intro!: divide_nonneg_nonneg)\n\nlemma surd_to_real_cnj_nz [simp]: \"red_assoc pq \\<Longrightarrow> surd_to_real_cnj pq \\<noteq> 0\"\n  using surd_to_real_cnj_irrat[of pq] by auto\n\nlemma red_assoc_step:\n  assumes \"red_assoc pq\"\n  defines \"X \\<equiv> (D' + fst pq) div snd pq\"\n  defines \"pq' \\<equiv> sqrt_remainder_step pq\"\n  shows   \"red_assoc pq'\"\n          \"surd_to_real pq' = 1 / frac (surd_to_real pq)\"\n          \"surd_to_real_cnj pq' = 1 / (surd_to_real_cnj pq - X)\"\n          \"X > 0\" \"X * snd pq \\<le> 2 * D'\" \"X = nat \\<lfloor>surd_to_real pq\\<rfloor>\"\n          \"X = nat \\<lfloor>-1 / surd_to_real_cnj pq'\\<rfloor>\"\nproof -\n  obtain p q where [simp]: \"pq = (p, q)\" by (cases pq)\n  obtain p' q' where [simp]: \"pq' = (p', q')\" by (cases pq')\n  define \\<alpha> where \"\\<alpha> = (sqrt D + p) / q\"\n  define \\<alpha>' where \"\\<alpha>' = 1 / frac \\<alpha>\"\n  define cnj_\\<alpha>' where \"cnj_\\<alpha>' = (-sqrt D + (X * q - int p)) / ((D - (X * q - int p)\\<^sup>2) div q)\"\n  from assms(1) have \"\\<alpha> > 0\" \"q > 0\"\n    by (auto simp: \\<alpha>_def red_assoc_def)\n  from assms(1) nonsquare have \"\\<alpha> \\<notin> \\<rat>\"\n    by (auto simp: \\<alpha>_def red_assoc_def divide_in_Rats_iff2 add_in_Rats_iff2 irrat_sqrt_nonsquare)\n  hence \\<alpha>'_pos: \"frac \\<alpha> > 0\" using Ints_subset_Rats by auto\n  from \\<open>pq' = (p', q')\\<close> have p'_def: \"p' = X * q - p\" and q'_def: \"q' = (D - p'\\<^sup>2) div q\"\n    unfolding pq'_def sqrt_remainder_step_def X_def by (auto simp: Let_def add_ac)\n\n  have \"D' + p = \\<lfloor>sqrt D + p\\<rfloor>\"\n    by (auto simp: D'_def)\n  also have \"\\<dots> div int q = \\<lfloor>(sqrt D + p) / q\\<rfloor>\"\n    by (subst floor_divide_real_eq_div [symmetric]) auto\n  finally have X_altdef: \"X = nat \\<lfloor>(sqrt D + p) / q\\<rfloor>\"\n    unfolding X_def zdiv_int [symmetric] by auto\n\n  have nz: \"sqrt (real D) + (X * q - real p) \\<noteq> 0\"\n  proof\n    assume \"sqrt (real D) + (X * q - real p) = 0\"\n    hence \"sqrt (real D) = real p - X * q\" by (simp add: algebra_simps)\n    also have \"\\<dots> \\<in> \\<rat>\" by auto\n    finally show False using irrat_sqrt_nonsquare nonsquare by blast\n  qed\n\n  from assms(1) have \"real (p ^ 2) \\<le> sqrt D ^ 2\"\n    unfolding of_nat_power by (intro power_mono) (auto simp: red_assoc_def field_simps)\n  also have \"sqrt D ^ 2 = D\" by simp\n  finally have \"p\\<^sup>2 \\<le> D\" by (subst (asm) of_nat_le_iff)\n\n  have \"frac \\<alpha> = \\<alpha> - X\"\n    by (simp add: X_altdef frac_def \\<alpha>_def)\n  also have \"\\<dots> = (sqrt D - (X * q - int p)) / q\"\n    using \\<open>q > 0\\<close> by (simp add: field_simps \\<alpha>_def)\n  finally have \"1 / frac \\<alpha> = q / (sqrt D - (X * q - int p))\"\n    by simp\n  also have \"\\<dots> = q * (sqrt D + (X * q - int p)) /\n                    ((sqrt D - (X * q - int p)) * (sqrt D + (X * q - int p)))\" (is \"_ = ?A / ?B\")\n    using nz by (subst mult_divide_mult_cancel_right) auto\n  also have \"?B = real_of_int (D - int p ^ 2 + 2 * X * p * q - int X ^ 2 * q ^ 2)\"\n    by (auto simp: algebra_simps power2_eq_square)\n  also have \"q dvd (D - p ^ 2)\" using assms(1) by (auto simp: red_assoc_def)\n  with \\<open>p\\<^sup>2 \\<le> D\\<close> have \"int q dvd (int D - int p ^ 2)\" \n    unfolding of_nat_power [symmetric] by (subst of_nat_diff [symmetric]) auto\n  hence \"D - int p ^ 2 + 2 * X * p * q - int X ^ 2 * q ^ 2 = q * ((D - (X * q - int p)\\<^sup>2) div q)\"\n    by (auto simp: power2_eq_square algebra_simps)\n  also have \"?A / \\<dots> = (sqrt D + (X * q - int p)) / ((D - (X * q - int p)\\<^sup>2) div q)\"\n    unfolding of_int_mult of_int_of_nat_eq\n    by (rule mult_divide_mult_cancel_left) (insert \\<open>q > 0\\<close>, auto)\n  finally have \\<alpha>': \"\\<alpha>' = \\<dots>\" by (simp add: \\<alpha>'_def)\n\n  have dvd: \"q dvd (D - (X * q - int p)\\<^sup>2)\"\n    using assms(1) \\<open>int q dvd (int D - int p ^ 2)\\<close>\n    by (auto simp: power2_eq_square algebra_simps)\n\n  have \"X \\<le> (sqrt D + p) / q\" unfolding X_altdef by simp\n  moreover have \"X \\<noteq> (sqrt D + p) / q\"\n  proof\n    assume \"X = (sqrt D + p) / q\"\n    hence \"sqrt D = q * X - real p\" using \\<open>q > 0\\<close> by (auto simp: field_simps)\n    also have \"\\<dots> \\<in> \\<rat>\" by auto\n    finally show False using irrat_sqrt_nonsquare[OF nonsquare] by simp\n  qed\n  ultimately have \"X < (sqrt D + p) / q\" by simp\n  hence *: \"(X * q - int p) < sqrt D\"\n    using \\<open>q > 0\\<close> by (simp add: field_simps)\n  moreover\n  have pos: \"real_of_int (int D - (int X * int q - int p)\\<^sup>2) > 0\"\n  proof (cases \"X * q \\<ge> p\")\n    case True\n    hence \"real p \\<le> real X * real q\" unfolding of_nat_mult [symmetric] of_nat_le_iff .\n    hence \"real_of_int ((X * q - int p) ^ 2) < sqrt D ^ 2\" using *\n      unfolding of_int_power by (intro power_strict_mono) auto\n    also have \"\\<dots> = D\" by simp\n    finally show ?thesis by simp\n  next\n    case False\n    hence less: \"real X * real q < real p\"\n      unfolding of_nat_mult [symmetric] of_nat_less_iff by auto\n    have \"(real X * real q - real p)\\<^sup>2 = (real p - real X * real q)\\<^sup>2\"\n      by (simp add: power2_eq_square algebra_simps)\n    also have \"\\<dots> \\<le> real p ^ 2\" using less by (intro power_mono) auto\n    also have \"\\<dots> < sqrt D ^ 2\" \n      using \\<open>q > 0\\<close> assms(1) unfolding of_int_power\n      by (intro power_strict_mono) (auto simp: red_assoc_def field_simps)\n    also have \"\\<dots> = D\" by simp\n    finally show ?thesis by simp\n  qed\n  hence pos': \"int D - (int X * int q - int p)\\<^sup>2 > 0\"\n    by (subst (asm) of_int_0_less_iff)\n  from pos have \"real_of_int ((int D - (int X * int q - int p)\\<^sup>2) div q) > 0\"\n    using \\<open>q > 0\\<close> dvd by (subst real_of_int_div) (auto intro!: divide_pos_pos)\n  ultimately have cnj_neg: \"cnj_\\<alpha>' < 0\" unfolding cnj_\\<alpha>'_def using dvd\n    unfolding of_int_0_less_iff by (intro divide_neg_pos) auto\n\n  have \"(p - sqrt D) / q < 0\"\n    using assms(1) by (auto simp: red_assoc_def X_altdef le_nat_iff)\n  also have \"X \\<ge> 1\"\n    using assms(1) by (auto simp: red_assoc_def X_altdef le_nat_iff)\n  hence \"0 \\<le> real X - 1\" by simp\n  finally have \"q < sqrt D + int q * X - p\"\n    using \\<open>q > 0\\<close> by (simp add: field_simps)\n  hence \"q * (sqrt D - (int q * X - p)) < (sqrt D + (int q * X - p)) * (sqrt D - (int q * X - p))\"\n    using * by (intro mult_strict_right_mono) (auto simp: red_assoc_def X_altdef field_simps)\n  also have \"\\<dots> = D - (int q * X - p) ^ 2\"\n    by (simp add: power2_eq_square algebra_simps)\n  finally have \"cnj_\\<alpha>' > -1\"\n    using dvd pos \\<open>q > 0\\<close> by (simp add: real_of_int_div field_simps cnj_\\<alpha>'_def)\n\n  from cnj_neg and this have \"cnj_\\<alpha>' \\<in> {-1<..<0}\" by auto\n  have \"\\<alpha>' > 1\" using \\<open>frac \\<alpha> > 0\\<close>\n    by (auto simp: \\<alpha>'_def field_simps frac_lt_1)\n\n  have \"0 = 1 + (-1 :: real)\"\n    by simp\n  also have \"1 + -1 < \\<alpha>' + cnj_\\<alpha>'\"\n    using \\<open>cnj_\\<alpha>' > -1\\<close> and \\<open>\\<alpha>' > 1\\<close> by (intro add_strict_mono)\n  also have \"\\<alpha>' + cnj_\\<alpha>' = 2 * (real X * q - real p) / ((int D - (int X * q - int p)\\<^sup>2) div int q)\"\n    by (simp add: \\<alpha>' cnj_\\<alpha>'_def add_divide_distrib [symmetric])\n  finally have \"real X * q - real p > 0\" using pos dvd \\<open>q > 0\\<close>\n    by (subst (asm) zero_less_divide_iff, subst (asm) (1 2 3) real_of_int_div)\n       (auto simp: field_simps)\n  hence \"real (X * q) > real p\" unfolding of_nat_mult by simp\n  hence p_less_Xq: \"p < X * q\" by (simp only: of_nat_less_iff)\n\n  from pos' and p_less_Xq have \"int D > int ((X * q - p)\\<^sup>2)\"\n    by (subst of_nat_power) (auto simp: of_nat_diff)\n  hence pos'': \"D > (X * q - p)\\<^sup>2\" unfolding of_nat_less_iff .\n\n  from dvd have \"int q dvd int (D - (X * q - p)\\<^sup>2)\"\n    using p_less_Xq pos'' by (subst of_nat_diff) (auto simp: of_nat_diff)\n  with dvd have dvd': \"q dvd (D - (X * q - p)\\<^sup>2)\"\n    by simp\n\n  have \\<alpha>'_altdef: \"\\<alpha>' = (sqrt D + p') / q'\"\n    using dvd dvd' pos'' p_less_Xq \\<alpha>'\n    by (simp add: real_of_int_div p'_def q'_def real_of_nat_div mult_ac of_nat_diff)\n  have cnj_\\<alpha>'_altdef: \"cnj_\\<alpha>' = (-sqrt D + p') / q'\"\n    using dvd dvd' pos'' p_less_Xq unfolding cnj_\\<alpha>'_def\n    by (simp add: real_of_int_div p'_def q'_def real_of_nat_div mult_ac of_nat_diff)\n  from dvd' have dvd'': \"q' dvd (D - p'\\<^sup>2)\"\n    by (auto simp: mult_ac p'_def q'_def)\n  have \"real ((D - p'\\<^sup>2) div q) > 0\" unfolding p'_def\n    by (subst real_of_nat_div[OF dvd'], rule divide_pos_pos) (insert \\<open>q > 0\\<close> pos'', auto)\n  hence \"q' > 0\" unfolding q'_def of_nat_0_less_iff .\n\n  show \"red_assoc pq'\" using \\<open>\\<alpha>' > 1\\<close> and \\<open>cnj_\\<alpha>' \\<in> _\\<close> and dvd'' and \\<open>q' > 0\\<close>\n    by (auto simp: red_assoc_def \\<alpha>'_altdef cnj_\\<alpha>'_altdef)\n\n  from assms(1) have \"real p < sqrt D\"\n    by (auto simp add: field_simps red_assoc_def)\n  hence \"p \\<le> D'\" unfolding D'_def by linarith\n  with * have \"real (X * q) < sqrt (real D) + D'\"\n    by simp\n  thus \"X * snd pq \\<le> 2 * D'\" unfolding D'_def \\<open>pq = (p, q)\\<close> snd_conv by linarith\n\n  have \"(sqrt D + p') / q' = \\<alpha>'\"\n    by (rule \\<alpha>'_altdef [symmetric])\n  also have \"\\<alpha>' = 1 / frac ((sqrt D + p) / q)\"\n    by (simp add: \\<alpha>'_def \\<alpha>_def)\n  finally show \"surd_to_real pq' = 1 / frac (surd_to_real pq)\" by (simp add: surd_to_real_def)\n  from \\<open>X \\<ge> 1\\<close> show \"X > 0\" by simp\n  from X_altdef show \"X = nat \\<lfloor>surd_to_real pq\\<rfloor>\" by (simp add: surd_to_real_def)\n\n  have \"sqrt (real D) < real p + 1 * real q\"\n    using assms(1) by (auto simp: red_assoc_def field_simps)\n  also have \"\\<dots> \\<le> real p + real X * real q\"\n    using \\<open>X > 0\\<close> by (intro add_left_mono mult_right_mono) (auto simp: of_nat_ge_1_iff)\n  finally have \"sqrt (real D) < \\<dots>\" .\n\n  have \"real p < sqrt D\"\n    using assms(1) by (auto simp add: field_simps red_assoc_def)\n  also have \"\\<dots> \\<le> sqrt D + q * X\"\n    by linarith\n  finally have less: \"real p < sqrt D + X * q\" by (simp add: algebra_simps)\n  moreover have \"D + p * p' + X * q * sqrt D = q * q' + p * sqrt D + p' * sqrt D + X * p' * q\"\n    using dvd' pos'' p_less_Xq \\<open>q > 0\\<close> unfolding p'_def q'_def of_nat_mult of_nat_add\n    by (simp add:  power2_eq_square field_simps of_nat_diff real_of_nat_div)\n  ultimately show *: \"surd_to_real_cnj pq' = 1 / (surd_to_real_cnj pq - X)\"\n    using \\<open>q > 0\\<close> \\<open>q' > 0\\<close> by (auto simp: surd_to_real_cnj_def field_simps)\n\n  have **: \"a = nat \\<lfloor>y\\<rfloor>\" if \"x \\<ge> 0\" \"x < 1\" \"real a + x = y\" for a :: nat and x y :: real\n    using that by linarith\n  from assms(1) have surd_to_real_cnj: \"surd_to_real_cnj (p, q) \\<in> {-1<..<0}\"\n    by (auto simp: surd_to_real_cnj_def red_assoc_def)\n  have \"surd_to_real_cnj (p, q) < X\"\n    using assms(1) less by (auto simp: surd_to_real_cnj_def field_simps red_assoc_def)\n  hence \"real X = surd_to_real_cnj (p, q) - 1 / surd_to_real_cnj (p', q')\" using *\n    using surd_to_real_cnj_irrat assms(1) \\<open>red_assoc pq'\\<close> by (auto simp: field_simps)\n  thus \"X = nat \\<lfloor>-1 / surd_to_real_cnj pq'\\<rfloor>\" using surd_to_real_cnj\n    by (intro **[of \"-surd_to_real_cnj (p, q)\"]) auto\nqed\n\nlemma red_assoc_denom_2D:\n  assumes \"red_assoc (p, q)\"\n  defines \"X \\<equiv> (D' + p) div q\"\n  assumes \"X > D'\"\n  shows  \"q = 1\"\nproof -\n  have \"X * q \\<le> 2 * D'\" \"X > 0\"\n    using red_assoc_step(4,5)[OF assms(1)] by (simp_all add: X_def)\n  note this(1)\n  also have \"2 * D' < 2 * X\"\n    by (intro mult_strict_left_mono assms) auto\n  finally have \"q < 2\" using \\<open>X > 0\\<close> by simp\n  moreover from assms(1) have \"q > 0\" by (auto simp: red_assoc_def)\n  ultimately show ?thesis by simp\nqed\n\nlemma red_assoc_denom_1:\n  assumes \"red_assoc (p, 1)\"\n  shows   \"p = D'\" \nproof -\n  from assms have \"sqrt D > p\" \"sqrt D < real p + 1\"\n    by (auto simp: red_assoc_def)\n  thus \"p = D'\" unfolding D'_def\n    by linarith\nqed\n\nlemma red_assoc_begin:\n  \"red_assoc (D', D - D'\\<^sup>2)\"\n  \"surd_to_real (D', D - D'\\<^sup>2) = 1 / frac (sqrt D)\"\n  \"surd_to_real_cnj (D', D - D'\\<^sup>2) = -1 / (sqrt D + D')\"\nproof -\n  have pos: \"D > 0\" \"D' > 0\"\n    using nonsquare by (auto simp: D'_def of_nat_ge_1_iff intro!: Nat.gr0I)\n\n  have \"sqrt D \\<noteq> D'\"\n    using irrat_sqrt_nonsquare[OF nonsquare] by auto\n  moreover have \"sqrt D \\<ge> 0\" by simp\n  hence \"D' \\<le> sqrt D\" unfolding D'_def by linarith\n  ultimately have less: \"D' < sqrt D\" by simp\n\n  have \"sqrt D \\<noteq> D' + 1\"\n    using irrat_sqrt_nonsquare[OF nonsquare] by auto\n  moreover have \"sqrt D \\<ge> 0\" by simp\n  hence \"D' \\<ge> sqrt D - 1\" unfolding D'_def by linarith\n  ultimately have gt: \"D' > sqrt D - 1\" by simp\n\n  from less have \"real D' ^ 2 < sqrt D ^ 2\" by (intro power_strict_mono) auto\n  also have \"\\<dots> = D\" by simp\n  finally have less': \"D'\\<^sup>2 < D\" unfolding of_nat_power [symmetric] of_nat_less_iff .\n\n  moreover have \"real D' * (real D' - 1) < sqrt D * (sqrt D - 1)\"\n    using less pos\n    by (intro mult_strict_mono diff_strict_right_mono) (auto simp: of_nat_ge_1_iff)\n  hence \"D'\\<^sup>2 + sqrt D < D' + D\"\n    by (simp add: field_simps power2_eq_square)\n  moreover have \"(sqrt D - 1) * sqrt D < real D' * (real D' + 1)\"\n    using pos gt by (intro mult_strict_mono) auto\n  hence \"D < sqrt D + D'\\<^sup>2 + D'\" by (simp add: power2_eq_square field_simps)\n  ultimately show \"red_assoc (D', D - D'\\<^sup>2)\"\n    by (auto simp: red_assoc_def field_simps of_nat_diff less)\n\n  have frac: \"frac (sqrt D) = sqrt D - D'\" unfolding frac_def D'_def\n    by auto\n  show \"surd_to_real (D', D - D'\\<^sup>2) = 1 / frac (sqrt D)\" unfolding surd_to_real_def\n    using less less' pos by (subst frac) (auto simp: of_nat_diff power2_eq_square field_simps)\n\n  have \"surd_to_real_cnj (D', D - D'\\<^sup>2) = -((sqrt D - D') / (D - D'\\<^sup>2))\"\n    using less less' pos by (auto simp: surd_to_real_cnj_def field_simps)\n  also have \"real (D - D'\\<^sup>2) = (sqrt D - D') * (sqrt D + D')\"\n    using less' by (simp add: power2_eq_square algebra_simps of_nat_diff)\n  also have \"(sqrt D - D') / \\<dots> = 1 / (sqrt D + D')\"\n    using less by (subst nonzero_divide_mult_cancel_left) auto\n  finally show \"surd_to_real_cnj (D', D - D'\\<^sup>2) = -1 / (sqrt D + D')\" by simp\nqed\n\nlemma cfrac_remainder_surd_to_real:\n  assumes \"red_assoc pq\"\n  shows   \"cfrac_remainder (cfrac_of_real (surd_to_real pq)) n =\n             surd_to_real ((sqrt_remainder_step ^^ n) pq)\"\n  using assms(1)\nproof (induction n arbitrary: pq)\n  case 0\n  hence \"cfrac_lim (cfrac_of_real (surd_to_real pq)) = surd_to_real pq\"\n    by (intro cfrac_lim_of_real red_assoc_imp_irrat 0)\n  thus ?case using 0\n    by auto\nnext\n  case (Suc n)\n  obtain p q where [simp]: \"pq = (p, q)\" by (cases pq)\n  have \"surd_to_real ((sqrt_remainder_step ^^ Suc n) pq) = \n          surd_to_real ((sqrt_remainder_step ^^ n) (sqrt_remainder_step (p, q)))\"\n    by (subst funpow_Suc_right) auto\n  also have \"\\<dots> = cfrac_remainder (cfrac_of_real (surd_to_real (sqrt_remainder_step (p, q)))) n\"\n    using red_assoc_step(1)[of \"(p, q)\"] Suc.prems\n    by (intro Suc.IH [symmetric]) (auto simp: sqrt_remainder_step_def Let_def add_ac)\n  also have \"surd_to_real (sqrt_remainder_step (p, q)) = 1 / frac (surd_to_real (p, q))\"\n    using red_assoc_step(2)[of \"(p, q)\"] Suc.prems\n    by (auto simp: sqrt_remainder_step_def Let_def add_ac surd_to_real_def)\n  also have \"cfrac_of_real \\<dots> = cfrac_tl (cfrac_of_real (surd_to_real (p, q)))\"\n    using Suc.prems Ints_subset_Rats red_assoc_imp_irrat by (subst cfrac_tl_of_real) auto\n  also have \"cfrac_remainder \\<dots> n = cfrac_remainder (cfrac_of_real (surd_to_real (p, q))) (Suc n)\"\n    by (simp add: cfrac_drop_Suc_right cfrac_remainder_def)\n  finally show ?case by simp\nqed\n\nlemma red_assoc_step' [intro]: \"red_assoc pq \\<Longrightarrow> red_assoc (sqrt_remainder_step pq)\"\n  using red_assoc_step(1)[of pq]\n  by (simp add: sqrt_remainder_step_def case_prod_unfold add_ac Let_def)\n\nlemma red_assoc_steps [intro]: \"red_assoc pq \\<Longrightarrow> red_assoc ((sqrt_remainder_step ^^ n) pq)\"\n  by (induction n) auto\n\nlemma floor_sqrt_less_sqrt: \"D' < sqrt D\"\nproof -\n  have \"D' \\<le> sqrt D\" unfolding D'_def by auto\n  moreover have \"sqrt D \\<noteq> D'\"\n    using irrat_sqrt_nonsquare[OF nonsquare] by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma red_assoc_bounds: \n  assumes \"red_assoc pq\"\n  shows   \"pq \\<in> (SIGMA p:{0<..D'}. {Suc D' - p..D' + p})\"\nproof -\n  obtain p q where [simp]: \"pq = (p, q)\" by (cases pq)\n  from assms have *: \"p < sqrt D\"\n    by (auto simp: red_assoc_def field_simps)\n  hence p: \"p \\<le> D'\" unfolding D'_def by linarith\n  from assms have \"p > 0\" by (auto intro!: Nat.gr0I simp: red_assoc_def)\n\n  have \"q > sqrt D - p\" \"q < sqrt D + p\" \n    using assms by (auto simp: red_assoc_def field_simps)\n  hence \"q \\<ge> D' + 1 - p\" \"q \\<le> D' + p\"\n    unfolding D'_def by linarith+\n  with p \\<open>p > 0\\<close> show ?thesis by simp\nqed\n\nlemma surd_to_real_cnj_eq_iff: \n  assumes \"red_assoc pq\" \"red_assoc pq'\"\n  shows   \"surd_to_real_cnj pq = surd_to_real_cnj pq' \\<longleftrightarrow> pq = pq'\"\nproof\n  assume eq: \"surd_to_real_cnj pq = surd_to_real_cnj pq'\"\n  from assms have pos: \"snd pq > 0\" \"snd pq' > 0\" by (auto simp: red_assoc_def)\n  have \"snd pq = snd pq'\"\n  proof (rule ccontr)\n    assume \"snd pq \\<noteq> snd pq'\"\n    with eq have \"sqrt D = (real (fst pq' * snd pq) - fst pq * snd pq') / (real (snd pq) - snd pq')\"\n      using pos by (auto simp: field_simps surd_to_real_cnj_def case_prod_unfold)\n    also have \"\\<dots> \\<in> \\<rat>\" by auto\n    finally show False using irrat_sqrt_nonsquare[OF nonsquare] by auto\n  qed\n  moreover from this eq pos have \"fst pq = fst pq'\"\n    by (auto simp: surd_to_real_cnj_def case_prod_unfold)\n  ultimately show \"pq = pq'\" by (simp add: prod_eq_iff)\nqed auto\n\nlemma red_assoc_sqrt_remainder_surd [intro]: \"red_assoc (sqrt_remainder_surd n)\"\n  by (auto simp: sqrt_remainder_surd_def intro!: red_assoc_begin)\n\nlemma surd_to_real_sqrt_remainder_surd:\n  \"surd_to_real (sqrt_remainder_surd n) = cfrac_remainder (cfrac_of_real (sqrt D)) (Suc n)\"\nproof (induction n)\n  case 0\n  from nonsquare have \"D > 0\" by (auto intro!: Nat.gr0I)\n  with red_assoc_begin show ?case using nonsquare irrat_sqrt_nonsquare[OF nonsquare]\n    using Ints_subset_Rats cfrac_drop_Suc_right cfrac_remainder_def cfrac_tl_of_real\n          sqrt_remainder_surd_def by fastforce\nnext\n  case (Suc n)\n  have \"surd_to_real (sqrt_remainder_surd (Suc n)) =\n          surd_to_real (sqrt_remainder_step (sqrt_remainder_surd n))\"\n    by (simp add: sqrt_remainder_surd_def)\n  also have \"\\<dots> = 1 / frac (surd_to_real (sqrt_remainder_surd n))\"\n    using red_assoc_step[OF red_assoc_sqrt_remainder_surd[of n]] by simp\n  also have \"surd_to_real (sqrt_remainder_surd n) =\n               cfrac_remainder (cfrac_of_real (sqrt D)) (Suc n)\" (is \"_ = ?X\")\n    by (rule Suc.IH)\n  also have \"\\<lfloor>cfrac_remainder (cfrac_of_real (sqrt (real D))) (Suc n)\\<rfloor> =\n               cfrac_nth (cfrac_of_real (sqrt (real D))) (Suc n)\"\n    using irrat_sqrt_nonsquare[OF nonsquare] by (intro floor_cfrac_remainder) auto\n  hence \"1 / frac ?X = cfrac_remainder (cfrac_of_real (sqrt D)) (Suc (Suc n))\"\n    using irrat_sqrt_nonsquare[OF nonsquare]\n    by (subst cfrac_remainder_Suc[of \"Suc n\"])\n       (simp_all add: frac_def cfrac_length_of_real_irrational)\n  finally show ?case .\nqed\n\nlemma sqrt_cfrac: \"sqrt_cfrac_nth n = cfrac_nth (cfrac_of_real (sqrt D)) (Suc n)\"\nproof -\n  have \"cfrac_nth (cfrac_of_real (sqrt D)) (Suc n) =\n          \\<lfloor>cfrac_remainder (cfrac_of_real (sqrt D)) (Suc n)\\<rfloor>\"\n    using irrat_sqrt_nonsquare[OF nonsquare] by (subst floor_cfrac_remainder) auto\n  also have \"cfrac_remainder (cfrac_of_real (sqrt D)) (Suc n) = surd_to_real (sqrt_remainder_surd n)\"\n    by (rule surd_to_real_sqrt_remainder_surd [symmetric])\n  also have \"nat \\<lfloor>surd_to_real (sqrt_remainder_surd n)\\<rfloor> = sqrt_cfrac_nth n\"\n    unfolding sqrt_cfrac_nth_def using red_assoc_step(6)[OF red_assoc_sqrt_remainder_surd[of n]]\n    by (simp add: case_prod_unfold)\n  finally show ?thesis\n    by (simp add: nat_eq_iff)\nqed\n\nlemma sqrt_cfrac_pos: \"sqrt_cfrac_nth k > 0\"\n  using red_assoc_step(4)[OF red_assoc_sqrt_remainder_surd[of k]]\n  by (simp add: sqrt_cfrac_nth_def case_prod_unfold)\n\nlemma snd_sqrt_remainder_surd_pos: \"snd (sqrt_remainder_surd n) > 0\"\n  using red_assoc_sqrt_remainder_surd[of n] by (auto simp: red_assoc_def)\n\n\nlemma\n  shows period_nonempty:      \"l > 0\"\n    and period_length_le_aux: \"l \\<le> D' * (D' + 1)\"\n    and sqrt_remainder_surd_periodic:   \"\\<And>n. sqrt_remainder_surd n = sqrt_remainder_surd (n mod l)\"\n    and sqrt_cfrac_periodic: \"\\<And>n. sqrt_cfrac_nth n = sqrt_cfrac_nth (n mod l)\"\n    and sqrt_remainder_surd_smallest_period:\n          \"\\<And>n. n \\<in> {0<..<l} \\<Longrightarrow> sqrt_remainder_surd n \\<noteq> sqrt_remainder_surd 0\"\n    and snd_sqrt_remainder_surd_gt_1:   \"\\<And>n. n < l - 1 \\<Longrightarrow> snd (sqrt_remainder_surd n) > 1\"\n    and sqrt_cfrac_le:       \"\\<And>n. n < l - 1 \\<Longrightarrow> sqrt_cfrac_nth n \\<le> D'\"\n    and sqrt_remainder_surd_last:       \"sqrt_remainder_surd (l - 1) = (D', 1)\"\n    and sqrt_cfrac_last:     \"sqrt_cfrac_nth (l - 1) = 2 * D'\"\n    and sqrt_cfrac_palindrome: \"\\<And>n. n < l - 1 \\<Longrightarrow> sqrt_cfrac_nth (l - n - 2) = sqrt_cfrac_nth n\"\n    and sqrt_cfrac_smallest_period:\n          \"\\<And>l'. l' > 0 \\<Longrightarrow> (\\<And>k. sqrt_cfrac_nth (k + l') = sqrt_cfrac_nth k) \\<Longrightarrow> l' \\<ge> l\"\nproof -\n  note [simp] = sqrt_remainder_surd_def\n  define f where \"f = sqrt_remainder_surd\"\n  have *[intro]: \"red_assoc (f n)\" for n\n    unfolding f_def by (rule red_assoc_sqrt_remainder_surd)\n\n  define S where \"S = (SIGMA p:{0<..D'}. {Suc D' - p..D' + p})\"\n  have [intro]: \"finite S\" by (simp add: S_def)\n  have \"card S = (\\<Sum>p=1..D'. 2 * p)\" unfolding S_def\n    by (subst card_SigmaI) (auto intro!: sum.cong)\n  also have \"\\<dots> = D' * (D' + 1)\"\n    by (induction D') (auto simp: power2_eq_square)\n  finally have [simp]: \"card S = D' * (D' + 1)\" .\n  \n  have \"D' * (D' + 1) + 1 = card {..D' * (D' + 1)}\" by simp\n  define k1 where\n    \"k1 = (LEAST k1. k1 \\<le> D' * (D' + 1) \\<and> (\\<exists>k2. k2 \\<le> D' * (D' + 1) \\<and> k1 \\<noteq> k2 \\<and> f k1 = f k2))\"\n  define k2 where\n    \"k2 = (LEAST k2. k2 \\<le> D' * (D' + 1) \\<and> k1 \\<noteq> k2 \\<and> f k1 = f k2)\"\n  \n  have \"f ` {..D' * (D' + 1)} \\<subseteq> S\" unfolding S_def\n    using red_assoc_bounds[OF *] by blast\n  hence \"card (f ` {..D' * (D' + 1)}) \\<le> card S\"\n    by (intro card_mono) auto\n  also have \"card S = D' * (D' + 1)\" by simp\n  also have \"\\<dots> < card {..D' * (D' + 1)}\" by simp\n  finally have \"\\<not>inj_on f {..D' * (D' + 1)}\"\n    by (rule pigeonhole)\n  hence \"\\<exists>k1. k1 \\<le> D' * (D' + 1) \\<and> (\\<exists>k2. k2 \\<le> D' * (D' + 1) \\<and> k1 \\<noteq> k2 \\<and> f k1 = f k2)\"\n    by (auto simp: inj_on_def)\n  from LeastI_ex[OF this, folded k1_def]\n    have \"k1 \\<le> D' * (D' + 1)\" \"\\<exists>k2\\<le>D' * (D' + 1). k1 \\<noteq> k2 \\<and> f k1 = f k2\" by auto\n  moreover from LeastI_ex[OF this(2), folded k2_def]\n    have \"k2 \\<le> D' * (D' + 1)\" \"k1 \\<noteq> k2\" \"f k1 = f k2\" by auto\n  moreover have \"k1 \\<le> k2\"\n  proof (rule ccontr)\n    assume \"\\<not>(k1 \\<le> k2)\"\n    hence \"k2 \\<le> D' * (D' + 1) \\<and> (\\<exists>k2'. k2' \\<le> D' * (D' + 1) \\<and> k2 \\<noteq> k2' \\<and> f k2 = f k2')\"\n      using \\<open>k1 \\<le> D' * (D' + 1)\\<close> and \\<open>k1 \\<noteq> k2\\<close> and \\<open>f k1 = f k2\\<close> by auto\n    hence \"k1 \\<le> k2\" unfolding k1_def by (rule Least_le)\n    with \\<open>\\<not>(k1 \\<le> k2)\\<close> show False by simp\n  qed\n  ultimately have k12: \"k1 < k2\" \"k2 \\<le> D' * (D' + 1)\" \"f k1 = f k2\" by auto\n\n  have [simp]: \"k1 = 0\"\n  proof (cases k1)\n    case (Suc k1')\n    define k2' where \"k2' = k2 - 1\"\n    have Suc': \"k2 = Suc k2'\" using k12 by (simp add: k2'_def)\n    have nz: \"surd_to_real_cnj (sqrt_remainder_step (f k1')) \\<noteq> 0\"\n             \"surd_to_real_cnj (sqrt_remainder_step (f k2')) \\<noteq> 0\"\n      using surd_to_real_cnj_nz[OF *[of k2]] surd_to_real_cnj_nz[OF *[of k1]] \n      by (simp_all add: f_def Suc Suc')\n\n    define a where \"a = (D' + fst (f k1)) div snd (f k1)\"\n    define a' where \"a' = (D' + fst (f k1')) div snd (f k1')\"\n    define a'' where \"a'' = (D' + fst (f k2')) div snd (f k2')\"\n    have \"a' = nat \\<lfloor>- 1 / surd_to_real_cnj (sqrt_remainder_step (f k1'))\\<rfloor>\"\n      using red_assoc_step[OF *[of k1']] by (simp add: a'_def)\n    also have \"sqrt_remainder_step (f k1') = f k1\"\n      by (simp add: Suc f_def)\n    also have \"f k1 = f k2\" by fact\n    also have \"f k2 = sqrt_remainder_step (f k2')\" by (simp add: Suc' f_def)\n    also have \"nat \\<lfloor>- 1 / surd_to_real_cnj (sqrt_remainder_step (f k2'))\\<rfloor> = a''\"\n      using red_assoc_step[OF *[of k2']] by (simp add: a''_def)\n    finally have a'_a'': \"a' = a''\" .\n\n    have \"surd_to_real_cnj (f k2') \\<noteq> a''\"\n      using surd_to_real_cnj_irrat[OF *[of k2']] by auto\n    hence \"surd_to_real_cnj (f k2') = 1 / surd_to_real_cnj (sqrt_remainder_step (f k2')) + a''\"\n      using red_assoc_step(3)[OF *[of k2'], folded a''_def] nz\n      by (simp add: field_simps)\n    also have \"\\<dots> = 1 / surd_to_real_cnj (sqrt_remainder_step (f k1')) + a'\"\n      using k12 by (simp add: a'_a'' k12 Suc Suc' f_def)\n    also have nz': \"surd_to_real_cnj (f k1') \\<noteq> a'\"\n      using surd_to_real_cnj_irrat[OF *[of k1']] by auto\n    hence \"1 / surd_to_real_cnj (sqrt_remainder_step (f k1')) + a' = surd_to_real_cnj (f k1')\"\n      using red_assoc_step(3)[OF *[of k1'], folded a'_def] nz nz'\n      by (simp add: field_simps)\n    finally have \"f k1' = f k2'\"\n      by (subst (asm) surd_to_real_cnj_eq_iff) auto\n    with k12 have \"k1' \\<le> D' * (D' + 1) \\<and> (\\<exists>k2\\<le>D' * (D' + 1). k1' \\<noteq> k2 \\<and> f k1' = f k2)\"\n      by (auto simp: Suc Suc' intro!: exI[of _ k2'])\n    hence \"k1 \\<le> k1'\" unfolding k1_def by (rule Least_le)\n    thus \"k1 = 0\" by (simp add: Suc)\n  qed auto\n\n  have smallest_period: \"f k \\<noteq> f 0\" if \"k \\<in> {0<..<k2}\" for k\n  proof\n    assume \"f k = f 0\"\n    hence \"k \\<le> D' * (D' + 1) \\<and> k1 \\<noteq> k \\<and> f k1 = f k\"\n      using k12 that by auto\n    hence \"k2 \\<le> k\" unfolding k2_def by (rule Least_le)\n    with that show False by auto\n  qed\n\n  have snd_f_gt_1: \"snd (f k) > 1\" if \"k < k2 - 1\" for k\n  proof -\n    have \"snd (f k) \\<noteq> 1\"\n    proof\n      assume \"snd (f k) = 1\"\n      hence \"f k = (D', 1)\" using red_assoc_denom_1[of \"fst (f k)\"] *[of k]\n        by (cases \"f k\") auto\n      hence \"sqrt_remainder_step (f k) = (D', D - D'\\<^sup>2)\" by (auto simp: sqrt_remainder_step_def)\n      hence \"f (Suc k) = f 0\" by (simp add: f_def)\n      moreover have \"f (Suc k) \\<noteq> f 0\"\n        using that by (intro smallest_period) auto\n      ultimately show False by contradiction\n    qed\n    moreover have \"snd (f k) > 0\" using *[of k] by (auto simp: red_assoc_def)\n    ultimately show ?thesis by simp\n  qed\n\n  have sqrt_cfrac_le: \"sqrt_cfrac_nth k \\<le> D'\" if \"k < k2 - 1\" for k\n  proof -\n    define p and q where \"p = fst (f k)\" and \"q = snd (f k)\"\n    have \"q \\<ge> 2\" using snd_f_gt_1[of k] that by (auto simp: q_def)\n    also have \"sqrt_cfrac_nth k * q \\<le> D' * 2\"\n      using red_assoc_step(5)[OF *[of k]]\n      by (simp add: sqrt_cfrac_nth_def p_def q_def case_prod_unfold f_def)\n    finally show ?thesis by simp\n  qed \n\n  have last: \"f (k2 - 1) = (D', 1)\"\n  proof -\n    define p and q where \"p = fst (f (k2 - 1))\" and \"q = snd (f (k2 - 1))\"\n    have pq: \"f (k2 - 1) = (p, q)\" by (simp add: p_def q_def)\n    have \"sqrt_remainder_step (f (k2 - 1)) = f (Suc (k2 - 1))\"\n      by (simp add: f_def)\n    also from k12 have \"Suc (k2 - 1) = k2\" by simp\n    also have \"f k2 = f 0\"\n      using k12 by simp\n    also have \"f 0 = (D', D - D'\\<^sup>2)\" by (simp add: f_def)\n    finally have eq: \"sqrt_remainder_step (f (k2 - 1)) = (D', D - D'\\<^sup>2)\" .\n\n    hence \"(D - D'\\<^sup>2) div q = D - D'\\<^sup>2\" unfolding sqrt_remainder_step_def Let_def pq\n      by auto\n    moreover have \"q > 0\" using *[of \"k2 - 1\"]\n      by (auto simp: red_assoc_def q_def)\n    ultimately have \"q = 1\" using D'_sqr_less_D\n      by (subst (asm) div_eq_dividend_iff) auto\n    hence \"p = D'\"\n      using red_assoc_denom_1[of p] *[of \"k2 - 1\"] unfolding pq by auto\n    with \\<open>q = 1\\<close> show \"f (k2 - 1) = (D', 1)\" unfolding pq by simp\n  qed\n\n  have period: \"sqrt_remainder_surd n = sqrt_remainder_surd (n mod k2)\" for n\n    unfolding sqrt_remainder_surd_def using k12 by (intro funpow_cycle) (auto simp: f_def)\n  have period': \"sqrt_cfrac_nth k = sqrt_cfrac_nth (k mod k2)\" for k\n    using period[of k] by (simp add: sqrt_cfrac_nth_def)\n\n  have k2_le: \"l \\<ge> k2\" if \"l > 0\" \"\\<And>k. sqrt_cfrac_nth (k + l) = sqrt_cfrac_nth k\" for l\n  proof (rule ccontr)\n    assume *: \"\\<not>(l \\<ge> k2)\"\n    hence \"sqrt_cfrac_nth (k2 - Suc l) = sqrt_cfrac_nth (k2 - 1)\"\n      using that(2)[of \"k2 - Suc l\"] by simp\n    also have \"\\<dots> = 2 * D'\"\n      using last by (simp add: sqrt_cfrac_nth_def f_def)\n    finally have \"2 * D' = sqrt_cfrac_nth (k2 - Suc l)\" ..\n    also have \"\\<dots> \\<le> D'\" using k12 that *\n      by (intro sqrt_cfrac_le diff_less_mono2) auto\n    finally show False using D'_pos by simp\n  qed\n\n  have \"l = (LEAST l. 0 < l \\<and> (\\<forall>n. int (sqrt_cfrac_nth (n + l)) = int (sqrt_cfrac_nth n)))\"\n    using nonsquare unfolding sqrt_cfrac_def\n    by (simp add: l_def sqrt_nat_period_length_def sqrt_cfrac)\n  hence l_altdef: \"l = (LEAST l. 0 < l \\<and> (\\<forall>n. sqrt_cfrac_nth (n + l) = sqrt_cfrac_nth n))\"\n    by simp\n\n  have [simp]: \"D \\<noteq> 0\" using nonsquare by (auto intro!: Nat.gr0I)\n  have \"\\<exists>l. l > 0 \\<and> (\\<forall>k. sqrt_cfrac_nth (k + l) = sqrt_cfrac_nth k)\"\n  proof (rule exI, safe)\n    fix k show \"sqrt_cfrac_nth (k + k2) = sqrt_cfrac_nth k\"\n      using period'[of k] period'[of \"k + k2\"] k12 by simp\n  qed (insert k12, auto)\n  from LeastI_ex[OF this, folded l_altdef]\n  have l: \"l > 0\" \"\\<And>k. sqrt_cfrac_nth (k + l) = sqrt_cfrac_nth k\"\n    by (simp_all add: sqrt_cfrac)\n\n  have \"l \\<le> k2\" unfolding l_altdef\n    by (rule Least_le) (subst (1 2) period', insert k12, auto)\n  moreover have \"k2 \\<le> l\" using k2_le l by blast\n  ultimately have [simp]: \"l = k2\" by auto\n\n  define x' where \"x' = (\\<lambda>k. -1 / surd_to_real_cnj (f k))\"\n  {\n    fix k :: nat\n    have nz: \"surd_to_real_cnj (f k) \\<noteq> 0\" \"surd_to_real_cnj (f (Suc k)) \\<noteq> 0\"\n      using surd_to_real_cnj_nz[OF *, of k] surd_to_real_cnj_nz[OF *, of \"Suc k\"]\n      by (simp_all add: f_def)\n\n    have \"surd_to_real_cnj (f k) \\<noteq> sqrt_cfrac_nth k\"\n      using surd_to_real_cnj_irrat[OF *[of k]] by auto\n    hence \"x' (Suc k) = sqrt_cfrac_nth k + 1 / x' k\"\n      using red_assoc_step(3)[OF *[of k]] nz\n      by (simp add: field_simps sqrt_cfrac_nth_def case_prod_unfold f_def x'_def)\n  } note x'_Suc = this\n\n  have x'_nz: \"x' k \\<noteq> 0\" for k\n    using surd_to_real_cnj_nz[OF *[of k]] by (auto simp: x'_def)\n  have x'_0: \"x' 0 = real D' + sqrt D\"\n    using red_assoc_begin by (simp add: x'_def f_def)\n\n  define c' where \"c' = cfrac (\\<lambda>n. sqrt_cfrac_nth (l - Suc n))\"\n  define c'' where \"c'' = cfrac (\\<lambda>n. if n = 0 then 2 * D' else sqrt_cfrac_nth (n - 1))\"\n  have nth_c' [simp]: \"cfrac_nth c' n = sqrt_cfrac_nth (l - Suc n)\" for n\n    unfolding c'_def by (subst cfrac_nth_cfrac) (auto simp: is_cfrac_def intro!: sqrt_cfrac_pos)\n  have nth_c'' [simp]: \"cfrac_nth c'' n = (if n = 0 then 2 * D' else sqrt_cfrac_nth (n - 1))\" for n\n    unfolding c''_def by (subst cfrac_nth_cfrac) (auto simp: is_cfrac_def intro!: sqrt_cfrac_pos)\n\n  have \"conv' c' n (x' (l - n)) = x' l\" if \"n \\<le> l\" for n\n    using that\n  proof (induction n)\n    case (Suc n)\n    have \"x' l = conv' c' n (x' (l - n))\"\n      using Suc.prems by (intro Suc.IH [symmetric]) auto\n    also have \"l - n = Suc (l - Suc n)\"\n      using Suc.prems by simp\n    also have \"x' \\<dots> = cfrac_nth c' n + 1 / x' (l - Suc n)\"\n      by (subst x'_Suc) simp\n    also have \"conv' c' n \\<dots> = conv' c' (Suc n) (x' (l - Suc n))\"\n      by (simp add: conv'_Suc_right)\n    finally show ?case ..\n  qed simp_all\n  from this[of l] have conv'_x'_0: \"conv' c' l (x' 0) = x' 0\"\n    using k12 by (simp add: x'_def)\n\n  have \"cfrac_nth (cfrac_of_real (x' 0)) n = cfrac_nth c'' n\" for n\n  proof (cases n)\n    case 0\n    thus ?thesis by (simp add: x'_0 D'_def)\n  next\n    case (Suc n')\n    have \"sqrt D \\<notin> \\<int>\"\n      using red_assoc_begin(1) red_assoc_begin(2) by auto\n    hence \"cfrac_nth (cfrac_of_real (real D' + sqrt (real D))) (Suc n') =\n          cfrac_nth (cfrac_of_real (sqrt (real D))) (Suc n')\"\n      by (simp add: cfrac_tl_of_real frac_add_of_nat Ints_add_left_cancel flip: cfrac_nth_tl)\n    thus ?thesis using x'_nz[of 0]\n      by (simp add: x'_0 sqrt_cfrac Suc)\n  qed\n\n  show \"sqrt_cfrac_nth (l - n - 2) = sqrt_cfrac_nth n\" if \"n < l - 1\" for n\n  proof -\n    have \"D > 1\" using nonsquare by (cases D) (auto intro!: Nat.gr0I)\n    hence \"D' + sqrt D > 0 + 1\" using D'_pos by (intro add_strict_mono) auto\n    hence \"x' 0 > 1\" by (auto simp: x'_0)\n    hence \"cfrac_nth c' (Suc n) = cfrac_nth (cfrac_of_real (conv' c' l (x' 0))) (Suc n)\"\n      using \\<open>n < l - 1\\<close> using cfrac_of_real_conv' by auto\n    also have \"\\<dots> = cfrac_nth (cfrac_of_real (x' 0)) (Suc n)\"\n      by (subst conv'_x'_0) auto\n    also have \"\\<dots> = cfrac_nth c'' (Suc n)\" by fact\n    finally show \"sqrt_cfrac_nth (l - n - 2) = sqrt_cfrac_nth n\"\n      by simp\n  qed\n\n  show \"l > 0\" \"l \\<le> D' * (D' + 1)\" using k12 by simp_all\n  show \"sqrt_remainder_surd n = sqrt_remainder_surd (n mod l)\"\n       \"sqrt_cfrac_nth n = sqrt_cfrac_nth (n mod l)\" for n\n    using period[of n] period'[of n] by simp_all\n  show \"sqrt_remainder_surd n \\<noteq> sqrt_remainder_surd 0\" if \"n \\<in> {0<..<l}\" for n\n    using smallest_period[of n] that by (auto simp: f_def)\n  show \"snd (sqrt_remainder_surd n) > 1\" if \"n < l - 1\" for n\n    using that snd_f_gt_1[of n] by (simp add: f_def)\n  show \"f (l - 1) = (D', 1)\" and \"sqrt_cfrac_nth (l - 1) = 2 * D'\"\n    using last by (simp_all add: sqrt_cfrac_nth_def f_def)\n  show \"sqrt_cfrac_nth k \\<le> D'\" if \"k < l - 1\" for k\n    using sqrt_cfrac_le[of k] that by simp\n  show \"l' \\<ge> l\" if \"l' > 0\" \"\\<And>k. sqrt_cfrac_nth (k + l') = sqrt_cfrac_nth k\" for l'\n    using k2_le[of l'] that by auto\nqed\n\ntheorem cfrac_sqrt_periodic:\n  \"cfrac_nth (cfrac_of_real (sqrt D)) (Suc n) =\n   cfrac_nth (cfrac_of_real (sqrt D)) (Suc (n mod l))\"\n  using sqrt_cfrac_periodic[of n] by (metis sqrt_cfrac)\n\ntheorem cfrac_sqrt_le: \"n \\<in> {0<..<l} \\<Longrightarrow> cfrac_nth (cfrac_of_real (sqrt D)) n \\<le> D'\"\n  using sqrt_cfrac_le[of \"n - 1\"]\n  by (metis Suc_less_eq Suc_pred add.right_neutral greaterThanLessThan_iff of_nat_mono\n            period_nonempty plus_1_eq_Suc sqrt_cfrac)\n\ntheorem cfrac_sqrt_last: \"cfrac_nth (cfrac_of_real (sqrt D)) l = 2 * D'\"\n  using sqrt_cfrac_last by (metis One_nat_def Suc_pred period_nonempty sqrt_cfrac)\n\ntheorem cfrac_sqrt_palindrome:\n  assumes \"n \\<in> {0<..<l}\"\n  shows   \"cfrac_nth (cfrac_of_real (sqrt D)) (l - n) = cfrac_nth (cfrac_of_real (sqrt D)) n\"\nproof -\n  have \"cfrac_nth (cfrac_of_real (sqrt D)) (l - n) = sqrt_cfrac_nth (l - n - 1)\"\n    using assms by (subst sqrt_cfrac) (auto simp: Suc_diff_Suc)\n  also have \"\\<dots> = sqrt_cfrac_nth (n - 1)\"\n    using assms by (subst sqrt_cfrac_palindrome [symmetric]) auto\n  also have \"\\<dots> = cfrac_nth (cfrac_of_real (sqrt D)) n\"\n    using assms by (subst sqrt_cfrac) auto\n  finally show ?thesis .\nqed\n\nlemma sqrt_cfrac_info_palindrome:\n  assumes \"sqrt_cfrac_info D = (a, b, cs)\"\n  shows   \"rev (butlast cs) = butlast cs\"\nproof (rule List.nth_equalityI; safe?)\n  fix i assume \"i < length (rev (butlast cs))\"\n  with period_nonempty have \"Suc i < length cs\" by simp\n  thus \"rev (butlast cs) ! i = butlast cs ! i\"\n    using assms cfrac_sqrt_palindrome[of \"Suc i\"] period_nonempty unfolding l_def\n    by (auto simp: sqrt_cfrac_info_def rev_nth algebra_simps Suc_diff_Suc simp del: cfrac.simps)\nqed simp_all\n\nlemma sqrt_cfrac_info_last:\n  assumes \"sqrt_cfrac_info D = (a, b, cs)\"\n  shows   \"last cs = 2 * Discrete.sqrt D\"\nproof -\n  from assms show ?thesis using period_nonempty cfrac_sqrt_last\n    by (auto simp: sqrt_cfrac_info_def last_map l_def D'_def Discrete_sqrt_altdef)\nqed\n\ntext \\<open>\n  The following lemmas allow us to compute the period of the expansion of the square root:\n\\<close>\nlemma while_option_sqrt_cfrac:\n  defines \"step' \\<equiv> (\\<lambda>(as, pq). ((D' + fst pq) div snd pq # as, sqrt_remainder_step pq))\"\n  defines \"b \\<equiv> (\\<lambda>(_, pq). snd pq \\<noteq> 1)\"\n  defines \"initial \\<equiv> ([] :: nat list, (D', D - D'\\<^sup>2))\"\n  shows \"while_option b step' initial =\n           Some (rev (map sqrt_cfrac_nth [0..<l -1]), (D', 1))\"\nproof -\n  define P where \n    \"P = (\\<lambda>(as, pq). let n = length as\n                     in  n < l \\<and> pq = sqrt_remainder_surd n \\<and> as = rev (map sqrt_cfrac_nth [0..<n]))\"\n  define \\<mu> :: \"nat list \\<times> (nat \\<times> nat) \\<Rightarrow> nat\" where \"\\<mu> = (\\<lambda>(as, _). l - length as)\"\n  have [simp]: \"P initial\" using period_nonempty\n    by (auto simp: initial_def P_def sqrt_remainder_surd_def)\n  have step': \"P (step' s) \\<and> Suc (length (fst s)) < l\" if \"P s\" \"b s\" for s\n  proof (cases s)\n    case (fields as p q)\n    define n where \"n = length as\"\n    from that fields sqrt_remainder_surd_last have \"Suc n \\<le> l\"\n      by (auto simp: b_def P_def Let_def n_def [symmetric])\n    moreover from that fields sqrt_remainder_surd_last have \"Suc n \\<noteq> l\"\n      by (auto simp: b_def P_def Let_def n_def [symmetric])\n    ultimately have \"Suc n < l\" by auto\n    with that fields sqrt_remainder_surd_last show \"P (step' s) \\<and> Suc (length (fst s)) < l\"\n      by (simp add: b_def P_def Let_def n_def step'_def sqrt_cfrac_nth_def \n                    sqrt_remainder_surd_def case_prod_unfold)\n  qed\n  have [simp]: \"length (fst (step' s)) = Suc (length (fst s))\" for s\n    by (simp add: step'_def case_prod_unfold)\n\n  have \"\\<exists>x. while_option b step' initial = Some x\"\n  proof (rule measure_while_option_Some)\n    fix s assume *: \"P s\" \"b s\"\n    from step'[OF *] show \"P (step' s) \\<and> \\<mu> (step' s) < \\<mu> s\"\n      by (auto simp: b_def \\<mu>_def case_prod_unfold intro!: diff_less_mono2)\n  qed auto\n  then obtain x where x: \"while_option b step' initial = Some x\" ..\n  have \"P x\" by (rule while_option_rule[OF _ x]) (insert step', auto)\n  have \"\\<not>b x\" using while_option_stop[OF x] by auto\n\n  obtain as p q where [simp]: \"x = (as, (p, q))\" by (cases x)\n  define n where \"n = length as\"\n  have [simp]: \"q = 1\" using \\<open>\\<not>b x\\<close> by (auto simp: b_def)\n  have [simp]: \"p = D'\" using \\<open>P x\\<close>\n    using red_assoc_denom_1[of p] by (auto simp: P_def Let_def)\n  have \"n < l\" \"sqrt_remainder_surd (length as) = (D', Suc 0)\"\n       and as: \"as = rev (map sqrt_cfrac_nth [0..<n])\" using \\<open>P x\\<close>\n    by (auto simp: P_def Let_def n_def)\n  hence \"\\<not>(n < l - 1)\"\n    using snd_sqrt_remainder_surd_gt_1[of n] by (intro notI) auto\n  with \\<open>n < l\\<close> have [simp]: \"n = l - 1\"  by auto\n  show ?thesis by (simp add: as x)\nqed\n\nlemma while_option_sqrt_cfrac_info:\n  defines \"step' \\<equiv> (\\<lambda>(as, pq). ((D' + fst pq) div snd pq # as, sqrt_remainder_step pq))\"\n  defines \"b \\<equiv> (\\<lambda>(_, pq). snd pq \\<noteq> 1)\"\n  defines \"initial \\<equiv> ([], (D', D - D'\\<^sup>2))\"\n  shows \"sqrt_cfrac_info D =\n           (case while_option b step' initial of\n             Some (as, _) \\<Rightarrow> (Suc (length as), D', rev ((2 * D') # as)))\"\nproof -\n  have \"nat (cfrac_nth (cfrac_of_real (sqrt (real D))) (Suc k)) = sqrt_cfrac_nth k\" for k\n    by (metis nat_int sqrt_cfrac)\n  thus ?thesis unfolding assms while_option_sqrt_cfrac\n    using period_nonempty sqrt_cfrac_last\n    by (cases l) (auto simp: sqrt_cfrac_info_def D'_def l_def Discrete_sqrt_altdef)\nqed\n\nend\nend\n\nlemma sqrt_nat_period_length_le: \"sqrt_nat_period_length D \\<le> nat \\<lfloor>sqrt D\\<rfloor> * (nat \\<lfloor>sqrt D\\<rfloor> + 1)\"\n  by (cases \"is_square D\") (use period_length_le_aux[of D] in auto)\n\nlemma sqrt_nat_period_length_0_iff [simp]:\n  \"sqrt_nat_period_length D = 0 \\<longleftrightarrow> is_square D\"\n  using period_nonempty[of D] by (cases \"is_square D\") auto\n\nlemma sqrt_nat_period_length_pos_iff [simp]:\n  \"sqrt_nat_period_length D > 0 \\<longleftrightarrow> \\<not>is_square D\"\n  using period_nonempty[of D] by (cases \"is_square D\") auto\n\nlemma sqrt_cfrac_info_code [code]:\n  \"sqrt_cfrac_info D =\n     (let D' = Discrete.sqrt D\n      in  if D'\\<^sup>2 = D then (0, D', [])\n          else\n            case while_option\n                   (\\<lambda>(_, pq). snd pq \\<noteq> 1)\n                   (\\<lambda>(as, (p, q)). let X = (p + D') div q; p' = X * q - p\n                                   in  (X # as, p', (D - p'\\<^sup>2) div q))\n                   ([], D', D - D'\\<^sup>2)\n            of Some (as, _) \\<Rightarrow> (Suc (length as), D', rev ((2 * D') # as)))\"\nproof -\n  define D' where \"D' = Discrete.sqrt D\"\n  show ?thesis\n  proof (cases \"is_square D\")\n    case True\n    hence \"D' ^ 2 = D\" by (auto simp: D'_def elim!: is_nth_powerE)\n    thus ?thesis using True\n      by (simp add: D'_def Let_def sqrt_cfrac_info_def sqrt_nat_period_length_def)\n  next\n    case False\n    hence \"D' ^ 2 \\<noteq> D\" by (subst eq_commute) auto\n    thus ?thesis using while_option_sqrt_cfrac_info[OF False]\n      by (simp add: sqrt_cfrac_info_def D'_def Let_def\n                    case_prod_unfold Discrete_sqrt_altdef add_ac sqrt_remainder_step_def)\n  qed\nqed\n\nlemma sqrt_nat_period_length_code [code]:\n  \"sqrt_nat_period_length D = fst (sqrt_cfrac_info D)\"\n  by (simp add: sqrt_cfrac_info_def)\n\ntext \\<open>\n  For efficiency reasons, it is often better to use an array instead of a list:\n\\<close>\ndefinition sqrt_cfrac_info_array where\n  \"sqrt_cfrac_info_array D = (case sqrt_cfrac_info D of (a, b, c) \\<Rightarrow> (a, b, IArray c))\"\n\nlemma fst_sqrt_cfrac_info_array [simp]: \"fst (sqrt_cfrac_info_array D) = sqrt_nat_period_length D\"\n  by (simp add: sqrt_cfrac_info_array_def sqrt_cfrac_info_def)\n\nlemma snd_sqrt_cfrac_info_array [simp]: \"fst (snd (sqrt_cfrac_info_array D)) = Discrete.sqrt D\"\n  by (simp add: sqrt_cfrac_info_array_def sqrt_cfrac_info_def)\n\n\ndefinition cfrac_sqrt_nth :: \"nat \\<times> nat \\<times> nat iarray \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"cfrac_sqrt_nth info n =\n     (case info of (l, a0, as) \\<Rightarrow> if n = 0 then a0 else as !! ((n - 1) mod l))\"\n\nlemma cfrac_sqrt_nth:\n  assumes \"\\<not>is_square D\"\n  shows   \"cfrac_nth (cfrac_of_real (sqrt D)) n =\n             int (cfrac_sqrt_nth (sqrt_cfrac_info_array D) n)\" (is \"?lhs = ?rhs\")\nproof (cases n)\n  case (Suc n')\n  define l where \"l = sqrt_nat_period_length D\"\n  from period_nonempty[OF assms] have \"l > 0\" by (simp add: l_def)\n  have \"cfrac_nth (cfrac_of_real (sqrt D)) (Suc n') =\n        cfrac_nth (cfrac_of_real (sqrt D)) (Suc (n' mod l))\" unfolding l_def\n    using cfrac_sqrt_periodic[OF assms, of n'] by simp\n  also have \"\\<dots> = map (\\<lambda>n. nat (cfrac_nth (cfrac_of_real (sqrt D)) (Suc n))) [0..<l] ! (n' mod l)\"\n    using \\<open>l > 0\\<close> by (subst nth_map) auto\n  finally show ?thesis using Suc\n    by (simp add: sqrt_cfrac_info_array_def sqrt_cfrac_info_def l_def cfrac_sqrt_nth_def)\nqed (simp_all add: sqrt_cfrac_info_def sqrt_cfrac_info_array_def\n                   Discrete_sqrt_altdef cfrac_sqrt_nth_def)\n\nlemma sqrt_cfrac_code [code]:\n  \"sqrt_cfrac D =\n     (let info = sqrt_cfrac_info_array D;\n          (l, a0, _) = info\n      in  if l = 0 then cfrac_of_int (int a0) else cfrac (cfrac_sqrt_nth info))\"\nproof (cases \"is_square D\")\n  case True\n  hence \"sqrt (real D) = of_int (Discrete.sqrt D)\"\n    using is_nth_powerE by fastforce\n  thus ?thesis using True\n    by (auto simp: Let_def sqrt_cfrac_info_array_def sqrt_cfrac_info_def sqrt_cfrac_def)\nnext\n  case False\n  have \"cfrac_sqrt_nth (sqrt_cfrac_info_array D) n > 0\" if \"n > 0\" for n\n  proof -\n    have \"int (cfrac_sqrt_nth (sqrt_cfrac_info_array D) n) > 0\"\n      using False that by (subst cfrac_sqrt_nth [symmetric]) auto\n    thus ?thesis by simp\n  qed\n  moreover have \"sqrt D \\<notin> \\<rat>\"\n    using False irrat_sqrt_nonsquare by blast\n  ultimately have \"sqrt_cfrac D = cfrac (cfrac_sqrt_nth (sqrt_cfrac_info_array D))\"\n    using cfrac_sqrt_nth[OF False]\n    by (intro cfrac_eqI) (auto simp: sqrt_cfrac_def is_cfrac_def)\n  thus ?thesis\n    using False by (simp add: Let_def sqrt_cfrac_info_array_def sqrt_cfrac_info_def)\nqed\n\nvalue \"let info = sqrt_cfrac_info_array 129 in info\"\n\nend", "meta": {"author": "pruvisto", "repo": "Continued_Fractions", "sha": "91dd908de0c054cf0db52913f2ae925477d564f7", "save_path": "github-repos/isabelle/pruvisto-Continued_Fractions", "path": "github-repos/isabelle/pruvisto-Continued_Fractions/Continued_Fractions-91dd908de0c054cf0db52913f2ae925477d564f7/Sqrt_Nat_Cfrac.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9362849986365572, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7939394861007198}}
{"text": "section \\<open>Graphs\\<close>\n\ntheory Graph imports Main begin\n\ntext \\<open>\n  Let us now define digraphs, graphs, walks, paths, and related concepts.\n\\<close>\n\ntext \\<open>@{typ 'a} is the vertex type.\\<close>\ntype_synonym 'a Edge = \"'a \\<times> 'a\"\ntype_synonym 'a Walk = \"'a list\"\n\nrecord 'a Graph =\n  verts :: \"'a set\" (\"V\\<index>\")\n  arcs :: \"'a Edge set\" (\"E\\<index>\")\nabbreviation is_arc :: \"('a, 'b) Graph_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<rightarrow>\\<index>\" 60) where\n  \"v \\<rightarrow>\\<^bsub>G\\<^esub> w \\<equiv> (v,w) \\<in> E\\<^bsub>G\\<^esub>\"\n\ntext \\<open>\n  We consider directed and undirected finite graphs.  Our graphs do not have multi-edges.\n\\<close>\nlocale Digraph =\n  fixes G :: \"('a, 'b) Graph_scheme\" (structure)\n  assumes finite_vertex_set: \"finite V\"\n      and valid_edge_set: \"E \\<subseteq> V \\<times> V\"\n\ncontext Digraph begin\n\nlemma finite_edge_set [simp]: \"finite E\" using finite_vertex_set valid_edge_set\n  by (simp add: finite_subset)\nlemma edges_are_in_V: assumes \"v\\<rightarrow>w\" shows \"v \\<in> V\" \"w \\<in> V\"\n  using assms valid_edge_set by blast+\n\nsubsection \\<open>Walks\\<close>\n\ntext \\<open>A walk is sequence of vertices connected by edges.\\<close>\ninductive walk :: \"'a Walk \\<Rightarrow> bool\" where\nNil [simp]: \"walk []\"\n| Singleton [simp]: \"v \\<in> V \\<Longrightarrow> walk [v]\"\n| Cons: \"v\\<rightarrow>w \\<Longrightarrow> walk (w # vs) \\<Longrightarrow> walk (v # w # vs)\"\n\ntext \\<open>\n  Show a few composition/decomposition lemmas for walks.  These will greatly simplify the proofs\n  that follow.\\<close>\nlemma walk_2 [simp]: \"v\\<rightarrow>w \\<Longrightarrow> walk [v,w]\" by (simp add: edges_are_in_V(2) walk.intros(3))\nlemma walk_comp: \"\\<lbrakk> walk xs; walk ys; xs = Nil \\<or> ys = Nil \\<or> last xs\\<rightarrow>hd ys \\<rbrakk> \\<Longrightarrow> walk (xs @ ys)\"\n  by (induct rule: walk.induct, simp_all add: walk.intros(3))\n     (metis list.exhaust_sel walk.intros(2) walk.intros(3))\nlemma walk_tl: \"walk xs \\<Longrightarrow> walk (tl xs)\" by (induct rule: walk.induct) simp_all\nlemma walk_drop: \"walk xs \\<Longrightarrow> walk (drop n xs)\" by (induct n, simp) (metis drop_Suc tl_drop walk_tl)\nlemma walk_take: \"walk xs \\<Longrightarrow> walk (take n xs)\"\n  by (induct arbitrary: n rule: walk.induct)\n     (simp, metis Digraph.walk.simps Digraph_axioms take_Cons' take_eq_Nil,\n      metis Digraph.walk.simps Digraph_axioms edges_are_in_V(1) take_Cons')\nlemma walk_decomp: assumes \"walk (xs @ ys)\" shows \"walk xs\" \"walk ys\"\n  using assms append_eq_conv_conj[of xs ys \"xs @ ys\"] walk_take walk_drop by metis+\nlemma walk_in_V: \"walk xs \\<Longrightarrow> set xs \\<subseteq> V\" by (induct rule: walk.induct; simp add: edges_are_in_V)\nlemma walk_first_edge: \"walk (v # w # xs) \\<Longrightarrow> v\\<rightarrow>w\" using walk.cases by fastforce\nlemma walk_first_edge': \"\\<lbrakk> walk (v # xs); xs \\<noteq> Nil \\<rbrakk> \\<Longrightarrow> v\\<rightarrow>hd xs\"\n  using walk_first_edge by (metis list.exhaust_sel)\nlemma walk_middle_edge: \"walk (xs @ v # w # ys) \\<Longrightarrow> v\\<rightarrow>w\"\n  by (induct \"xs @ v # w # ys\" arbitrary: xs rule: walk.induct, simp, simp)\n     (metis list.sel(1,3) self_append_conv2 tl_append2)\nlemma walk_last_edge: \"\\<lbrakk> walk (xs @ ys); xs \\<noteq> Nil; ys \\<noteq> Nil \\<rbrakk> \\<Longrightarrow> last xs\\<rightarrow>hd ys\"\n  using walk_middle_edge[of \"butlast xs\" \"last xs\" \"hd ys\" \"tl ys\"]\n  by (metis Cons_eq_appendI append_butlast_last_id append_eq_append_conv2 list.exhaust_sel self_append_conv)\n\n\nsubsection \\<open>Paths\\<close>\n\ntext \\<open>\n  A path is a walk without repeated vertices.  This is simple enough, so most of the above lemmas\n  transfer directly to paths.\n\\<close>\n\nabbreviation path :: \"'a Walk \\<Rightarrow> bool\" where \"path xs \\<equiv> walk xs \\<and> distinct xs\"\n\nlemma path_singleton [simp]: \"v \\<in> V \\<Longrightarrow> path [v]\" by simp\nlemma path_2 [simp]: \"\\<lbrakk> v\\<rightarrow>w; v \\<noteq> w \\<rbrakk> \\<Longrightarrow> path [v,w]\" by simp\nlemma path_cons: \"\\<lbrakk> path xs; xs \\<noteq> Nil; v\\<rightarrow>hd xs; v \\<notin> set xs \\<rbrakk> \\<Longrightarrow> path (v # xs)\"\n  by (metis distinct.simps(2) list.exhaust_sel walk.Cons)\nlemma path_comp: \"\\<lbrakk> walk xs; walk ys; xs = Nil \\<or> ys = Nil \\<or> last xs\\<rightarrow>hd ys; distinct (xs @ ys) \\<rbrakk>\n  \\<Longrightarrow> path (xs @ ys)\" using walk_comp by blast\n\n\nsubsection \\<open>The Set of All Paths\\<close>\n\ndefinition all_paths where \"all_paths \\<equiv> { xs | xs. path xs }\"\n\ntext \\<open>\n  Because paths have no repeated vertices, every graph has at most finitely many distinct paths.\n  This will be useful later to easily derive that any set of paths is finite.\n\\<close>\n\nlemma finitely_many_paths: \"finite all_paths\" proof-\n  have \"all_paths \\<subseteq> {xs. set xs \\<subseteq> V \\<and> length xs \\<le> card V}\"\n    unfolding all_paths_def using path_length by (simp add: Collect_mono path_in_V)\n  thus ?thesis using finite_lists_length_le[OF finite_vertex_set] walk_in_V infinite_super by blast\nqed\n\nend \\<comment> \\<open>context Digraph\\<close>\n\ntext \\<open>We introduce shorthand notation for a path connecting two vertices.\\<close>\n\ndefinition path_from_to :: \"('a, 'b) Graph_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a Walk \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  (\"_ \\<leadsto>_\\<leadsto>\\<index> _\" [71, 71, 71] 70) where\n  \"path_from_to G v xs w \\<equiv> Digraph.path G xs \\<and> xs \\<noteq> Nil \\<and> hd xs = v \\<and> last xs = w\"\n\ncontext Digraph begin\n\nlemma path_from_toI [intro]: \"\\<lbrakk> path xs; xs \\<noteq> Nil; hd xs = v; last xs = w \\<rbrakk> \\<Longrightarrow> v \\<leadsto>xs\\<leadsto> w\"\n  and path_from_toE [dest]: \"v \\<leadsto>xs\\<leadsto> w \\<Longrightarrow> path xs \\<and> xs \\<noteq> Nil \\<and> hd xs = v \\<and> last xs = w\"\n  unfolding path_from_to_def by blast+\n\nlemma path_from_to_ends: \"v \\<leadsto>(xs @ w # ys)\\<leadsto> w \\<Longrightarrow> ys = Nil\"\n  by (metis path_from_toE distinct.simps(2) last.simps last_appendR last_in_set list.discI path_decomp(2))\n\nlemma path_from_to_combine:\n  assumes \"v \\<leadsto>(xs @ x # xs')\\<leadsto> w\" \"v' \\<leadsto>(ys @ x # ys')\\<leadsto> w'\" \"set xs \\<inter> set ys' = {}\"\n  shows \"v \\<leadsto>(xs @ x # ys') \\<leadsto> w'\"\nproof\n  show \"path (xs @ x # ys')\"\n    by (metis path_from_toE assms(1,2,3) disjoint_insert(1) distinct_append list.sel(1) list.set(2)\n        list.simps(3) path_decomp(2) walk_comp walk_decomp(1) walk_last_edge)\n  show \"hd (xs @ x # ys') = v\" by (metis path_from_toE assms(1) hd_append list.sel(1))\n  show \"last (xs @ x # ys') = w'\" using assms(2) by auto\nqed simp\n\nlemma path_from_to_first: \"v \\<leadsto>xs\\<leadsto> w \\<Longrightarrow> v \\<notin> set (tl xs)\"\n  by (metis path_from_toE list.collapse path_first_vertex)\n\nlemma path_from_to_first': \"v \\<leadsto>(xs @ x # xs')\\<leadsto> w \\<Longrightarrow> v \\<notin> set xs'\"\n  by (metis path_from_toE append_eq_append_conv2 distinct.simps(2) hd_append list.exhaust_sel\n      list.sel(3) list.set_sel(1,2) list.simps(3) path_disjoint self_append_conv)\n\nlemma path_from_to_last: \"v \\<leadsto>xs\\<leadsto> w \\<Longrightarrow> w \\<notin> set (butlast xs)\"\n  by (metis path_from_toE append_butlast_last_id distinct_append not_distinct_conv_prefix)\n\nlemma path_from_to_last': \"v \\<leadsto>(xs @ x # xs')\\<leadsto> w \\<Longrightarrow> w \\<notin> set xs\"\n  by (metis path_from_toE bex_empty last_appendR last_in_set list.set(1) list.simps(3) path_disjoint)\n\ntext \\<open>Every walk contains a path connecting the same vertices.\\<close>\n\nlemma walk_to_path:\n  assumes \"walk xs\" \"xs \\<noteq> Nil\" \"hd xs = v\" \"last xs = w\"\n  shows \"\\<exists>ys. v \\<leadsto>ys\\<leadsto> w \\<and> set ys \\<subseteq> set xs\"\nproof-\n  text \\<open>We prove this by removing loops from @{term xs} until @{term xs} is a path.\n    We want to perform induction over @{term \"length xs\"}, but @{term xs} in\n    @{term \"set ys \\<subseteq> set xs\"} should not be part of the induction hypothesis. To accomplish this,\n    we hide @{term \"set xs\"} behind a definition for this specific part of the goal.\\<close>\n  define target_set where \"target_set \\<equiv> set xs\"\n  hence \"set xs \\<subseteq> target_set\" by simp\n  thus \"\\<exists>ys. v \\<leadsto>ys\\<leadsto> w \\<and> set ys \\<subseteq> target_set\"\n  using assms proof (induct \"length xs\" arbitrary: xs rule: infinite_descent0)\n    case (smaller n)\n    then obtain xs where\n      xs: \"n = length xs\" \"walk xs\" \"xs \\<noteq> Nil\" \"hd xs = v\" \"last xs = w\" \"set xs \\<subseteq> target_set\" and\n      hyp: \"\\<not>(\\<exists>ys. v \\<leadsto>ys\\<leadsto> w \\<and> set ys \\<subseteq> target_set)\" by blast\n    text \\<open>If @{term xs} is not a path, then @{term xs} is not distinct and we can decompose it.\\<close>\n    then obtain ys rest u\n      where xs_decomp: \"u \\<in> set ys\" \"distinct ys\" \"xs = ys @ u # rest\"\n      using not_distinct_conv_prefix by (metis path_from_toI)\n    text \\<open>@{term u} appears in @{term ys}, so we have a loop in @{term xs} starting from an\n      occurrence of @{term u} in @{term ys} ending in the vertex @{term u} in @{term \"u # rest\"}.\n      We define @{term zs} as @{term xs} without this loop.\\<close>\n    obtain ys' ys_suffix where\n      ys_decomp: \"ys = ys' @ u # ys_suffix\" by (meson split_list xs_decomp(1))\n    define zs where \"zs \\<equiv> ys' @ u # rest\"\n    have \"walk zs\" unfolding zs_def using xs(2) xs_decomp(3) ys_decomp\n      by (metis walk_decomp list.sel(1) list.simps(3) walk_comp walk_last_edge)\n    moreover have \"length zs < n\" unfolding zs_def by (simp add: xs(1) xs_decomp(3) ys_decomp)\n    moreover have \"hd zs = v\" unfolding zs_def\n      by (metis append_is_Nil_conv hd_append list.sel(1) xs(4) xs_decomp(3) ys_decomp)\n    moreover have \"last zs = w\" unfolding zs_def using xs(5) xs_decomp(3) by auto\n    moreover have \"set zs \\<subseteq> target_set\" unfolding zs_def using xs(6) xs_decomp(3) ys_decomp by auto\n    ultimately show ?case using zs_def hyp by blast\n  qed simp\nqed\n\nsubsection \\<open>Edges of Walks\\<close>\n\ntext \\<open>The set of edges on a walk.  Note that this is empty for walks of length 0 or 1.\\<close>\n\ndefinition edges_of_walk :: \"'a Walk \\<Rightarrow> 'a Edge set\" where\n  \"edges_of_walk xs = { (v,w) | v w xs_pre xs_post. xs = xs_pre @ v # w # xs_post }\"\n\nlemma edges_of_walkE: \"(v,w) \\<in> edges_of_walk xs \\<Longrightarrow> \\<exists>xs_pre xs_post. xs = xs_pre @ v # w # xs_post\"\n  unfolding edges_of_walk_def by blast\n\nlemma edges_of_walk_in_E: \"walk xs \\<Longrightarrow> edges_of_walk xs \\<subseteq> E\"\n  unfolding edges_of_walk_def using walk_middle_edge by auto\n\nlemma edges_of_walk_finite: \"walk xs \\<Longrightarrow> finite (edges_of_walk xs)\"\n  using edges_of_walk_in_E finite_edge_set finite_subset by blast\n\nlemma edges_of_walk_empty: \"edges_of_walk [] = {}\" \"edges_of_walk [v] = {}\"\n  unfolding edges_of_walk_def by simp_all\n\nlemma edges_of_walk_2: \"edges_of_walk [v,w] = {(v,w)}\" proof\n  {\n    fix v' w' assume \"(v', w') \\<in> edges_of_walk [v,w]\"\n    then obtain xs_pre xs_post where xs_decomp: \"[v,w] = xs_pre @ v' # w' # xs_post\"\n      using edges_of_walkE[of v' w' \"[v,w]\"] by blast\n    then have \"xs_pre = Nil\"\n      by (metis Nil_is_append_conv butlast.simps(2) butlast_append list.discI)\n    then have \"(v',w') \\<in> {(v,w)}\" using xs_decomp by simp\n  }\n  then show \"edges_of_walk [v, w] \\<subseteq> {(v, w)}\" by (simp add: subrelI)\n  show \"{(v, w)} \\<subseteq> edges_of_walk [v, w]\" unfolding edges_of_walk_def by blast\nqed\n\nlemma edges_of_walk_edge: \"\\<lbrakk> walk xs; (v,w) \\<in> edges_of_walk xs \\<rbrakk> \\<Longrightarrow> v\\<rightarrow>w\"\n  using edges_of_walkE walk_middle_edge by fastforce\n\nlemma edges_of_walk_middle [simp]: \"(v,w) \\<in> edges_of_walk (xs @ v # w # xs')\"\n  unfolding edges_of_walk_def by blast\n\nlemma edges_of_comp1: \"edges_of_walk xs \\<subseteq> edges_of_walk (xs @ ys)\"\n  unfolding edges_of_walk_def by force\nlemma edges_of_comp2: \"edges_of_walk ys \\<subseteq> edges_of_walk (xs @ ys)\" proof-\n  {\n    fix v w assume \"(v,w) \\<in> edges_of_walk ys\"\n    then have \"\\<exists>ys_pre ys_post. ys = ys_pre @ v # w # ys_post\" by (meson edges_of_walkE)\n    then have \"(v,w) \\<in> edges_of_walk (xs @ ys)\"\n      by (metis (mono_tags, lifting) append.assoc edges_of_walk_def mem_Collect_eq)\n  }\n  then show ?thesis by (simp add: subrelI)\nqed\n\nlemma walk_edges_decomp_simple:\n  \"edges_of_walk (v # w # xs) = {(v,w)} \\<union> edges_of_walk (w # xs)\" (is \"?A = ?B\")\nproof\n  have \"edges_of_walk (w # xs) \\<subseteq> ?A\" using edges_of_comp2[of \"w # xs\" \"[v]\"] by simp\n  moreover have \"(v,w) \\<in> ?A\" by (metis append_eq_Cons_conv edges_of_walk_middle)\n  ultimately show \"?B \\<subseteq> ?A\" by blast\n  {\n    fix v' w' assume \"(v',w') \\<in> ?A\"\n    then obtain xs_pre xs_post where xs_decomp: \"v # w # xs = xs_pre @ v' # w' # xs_post\"\n      using edges_of_walkE by blast\n    have \"(v',w') \\<in> ?B\" proof (cases)\n      assume \"xs_pre = Nil\" then show ?thesis using xs_decomp by auto\n    next\n      assume \"xs_pre \\<noteq> Nil\" then show ?thesis\n        by (metis Cons_eq_append_conv UnI2 edges_of_walk_middle xs_decomp)\n    qed\n  }\n  then show \"?A \\<subseteq> ?B\" by auto\nqed\n\nlemma walk_edges_decomp:\n  \"edges_of_walk (xs @ x # xs') = edges_of_walk (xs @ [x]) \\<union> edges_of_walk (x # xs')\"\nproof (induct xs)\n  case (Cons v xs)\n  show ?case proof (cases)\n    assume \"xs = Nil\"\n    then show ?thesis using edges_of_walk_2 walk_edges_decomp_simple by auto\n  next\n    assume \"xs \\<noteq> Nil\"\n    then obtain w xs_post where \"xs = w # xs_post\" using list.exhaust_sel by blast\n    then show ?thesis using Cons.hyps walk_edges_decomp_simple by auto\n  qed\nqed (simp add: edges_of_walk_empty(2))\n\n\n\nlemma walk_edges_vertices: assumes \"(v, w) \\<in> edges_of_walk xs\" shows \"v \\<in> set xs\" \"w \\<in> set xs\"\n  using assms edges_of_walkE by force+\n\nlemma walk_edges_subset:\n  assumes edges_subsets: \"edges_of_walk xs \\<subseteq> edges_of_walk ys\"\n    and non_trivial: \"tl xs \\<noteq> Nil\"\n  shows \"set xs \\<subseteq> set ys\"\nproof\n  fix v assume \"v \\<in> set xs\"\n  then obtain xs_pre xs_post where\n    xs_decomp: \"xs = xs_pre @ v # xs_post\" by (meson split_list)\n  show \"v \\<in> set ys\" proof (cases)\n    assume \"xs_pre = Nil\"\n    then have \"xs_post \\<noteq> Nil\" using xs_decomp non_trivial by auto\n    then have \"xs = xs_pre @ v # hd xs_post # tl xs_post\" by (simp add: xs_decomp)\n    then have \"(v, hd xs_post) \\<in> edges_of_walk xs\" using edges_of_walk_def by auto\n    then show ?thesis using walk_edges_vertices(1) edges_subsets by fastforce\n  next\n    assume \"xs_pre \\<noteq> Nil\"\n    then have \"xs = butlast xs_pre @ last xs_pre # v # xs_post\" by (simp add: xs_decomp)\n    then have \"(last xs_pre, v) \\<in> edges_of_walk xs\" using edges_of_walk_def by auto\n    then show ?thesis using walk_edges_vertices(2) edges_subsets by fastforce\n  qed\nqed\n\ntext \\<open>\n  A path has no repeated vertices, so if we split a path at an edge we find that the two pieces\n  do not contain this edge any more.\n\\<close>\n\nlemma path_edges:\n  assumes \"path xs\" \"(v,w) \\<in> edges_of_walk xs\"\n  shows \"\\<exists>xs_pre xs_post. xs = xs_pre @ v # w # xs_post\n    \\<and> (v,w) \\<notin> edges_of_walk (xs_pre @ [v])\n    \\<and> (v,w) \\<notin> edges_of_walk (w # xs_post)\"\nproof-\n  obtain xs_pre xs_post where\n    xs_decomp: \"xs = xs_pre @ v # w # xs_post\" by (meson assms(2) edges_of_walkE)\n  then have \"(v,w) \\<notin> edges_of_walk (xs_pre @ [v])\" using assms(1) edges_of_walkE\n    by (metis path_from_to_ends list.discI path_decomp' path_from_toI snoc_eq_iff_butlast)\n  moreover have \"(v,w) \\<notin> edges_of_walk (w # xs_post)\" using  assms(1)\n    by (metis edges_of_walkE in_set_conv_decomp path_decomp(2) path_first_vertex xs_decomp)\n  ultimately show ?thesis using xs_decomp by blast\nqed\n\nlemma path_edges_remove_prefix:\n  assumes \"path (xs @ x # xs')\"\n  shows \"edges_of_walk (xs @ [x]) = edges_of_walk (xs @ x # xs') - edges_of_walk (x # xs')\"\nproof-\n  {\n    fix v w assume *: \"(v,w) \\<in> edges_of_walk (xs @ [x])\"\n    then have 1: \"(v,w) \\<in> edges_of_walk (xs @ x # xs')\"\n      using walk_edges_decomp[of xs x xs'] by force\n    moreover have \"(v,w) \\<notin> edges_of_walk (x # xs')\" proof\n      assume contra: \"(v,w) \\<in> edges_of_walk (x # xs')\"\n      then have \"w \\<in> set (x # xs')\" by (meson walk_edges_vertices(2))\n      moreover have \"w \\<noteq> x\" using assms contra * 1\n        by (metis path_decomp(2) UnE edges_of_walkE edges_of_walk_edge list.set_intros(1)\n            path_2 path_disjoint path_first_vertex self_append_conv2 set_append walk_edges_vertices(1))\n      moreover have \"w \\<in> set (xs @ [x])\" by (meson * walk_edges_vertices(2))\n      ultimately show False using assms by auto\n    qed\n    ultimately have \"(v,w) \\<in> edges_of_walk (xs @ x # xs') - edges_of_walk (x # xs')\" by blast\n  }\n  then show ?thesis using walk_edges_decomp[of xs x xs'] by auto\nqed\n\nsubsection \\<open>The First Edge of a Walk\\<close>\n\ntext \\<open>\n  In the proof of Menger's Theorem, we will often talk about the first edge of a path.  Let us\n  define this concept.\n\\<close>\n\nfun first_edge_of_walk where\n  \"first_edge_of_walk (v # w # xs) = (v, w)\"\n| \"first_edge_of_walk [v] = undefined\"\n| \"first_edge_of_walk [] = undefined\"\n\nlemma first_edge_in_edges: \"tl xs \\<noteq> Nil \\<Longrightarrow> first_edge_of_walk xs \\<in> edges_of_walk xs\"\n  unfolding edges_of_walk_def by (induct rule: first_edge_of_walk.induct) auto\n\nlemma first_edge_hd_tl: \"\\<lbrakk> v \\<leadsto>xs\\<leadsto> w; tl xs \\<noteq> Nil \\<rbrakk> \\<Longrightarrow> first_edge_of_walk xs = (v, hd (tl xs))\"\n  by (induct \"xs\" rule: first_edge_of_walk.induct) auto\n\nlemma first_edge_first:\n  assumes \"v \\<leadsto>xs\\<leadsto> w\" \"(v,w') \\<in> edges_of_walk xs\"\n  shows \"first_edge_of_walk xs = (v,w')\"\nusing assms proof (induct rule: first_edge_of_walk.induct)\n  case (1 v w xs)\n  then show ?case\n    by (metis path_decomp(1) append_self_conv2 edges_of_walkE first_edge_of_walk.simps(1)\n        hd_append hd_in_set not_distinct_conv_prefix path_from_toE)\nnext\n  case (2 v)\n  then show ?case using path_edges by fastforce\nqed blast\n\nsubsection \\<open>Distance\\<close>\n\ntext \\<open>\n  The distance between two vertices is the minimum length of a path.  Note that this is not a\n  symmetric function because we are on digraphs.\n\\<close>\ndefinition distance :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"distance v w \\<equiv> Min { length xs | xs. v\\<leadsto>xs\\<leadsto>w }\"\n\ntext \\<open>\n  The @{const Min} operator applies only to finite sets, so let us prove that this is the case.\n\\<close>\nlemma distance_lengths_finite: \"finite { length xs | xs. v\\<leadsto>xs\\<leadsto>w }\" proof-\n  have \"{ length xs | xs. v\\<leadsto>xs\\<leadsto>w } \\<subseteq> { n | n. n \\<le> card V }\" using path_length by blast\n  then show ?thesis using finite_Collect_le_nat by (meson finite_subset)\nqed\n\ntext \\<open>\n  If we have a concrete path from @{term v} to @{term w}, then the length of this path bounds the\n  distance from @{term v} to @{term w}.\n\\<close>\n\nlemma distance_upper_bound: \"v\\<leadsto>xs\\<leadsto>w \\<Longrightarrow> distance v w \\<le> length xs\"\n  unfolding distance_def using Min_le[OF distance_lengths_finite] by blast\n\ntext \\<open>\n  Another characterization of @{const distance}: If we have a concrete minimal path from @{term v}\n  to @{term w}, this defines the distance.\n\\<close>\n\nlemma distance_witness:\n  assumes xs: \"v \\<leadsto>xs\\<leadsto> w\"\n      and xs_min: \"\\<And>xs'. v \\<leadsto>xs'\\<leadsto> w \\<Longrightarrow> length xs \\<le> length xs'\"\n  shows \"distance v w = length xs\"\nproof-\n  have \"\\<And>d. d \\<in> {length xs | xs. v \\<leadsto>xs\\<leadsto> w} \\<Longrightarrow> length xs \\<le> d\" using xs_min by blast\n  then show ?thesis unfolding distance_def using Min_eqI\n    by (metis (mono_tags, lifting) distance_lengths_finite xs mem_Collect_eq)\nqed\n\nsubsection \\<open>Subgraphs\\<close>\n\ntext \\<open>We only need one kind of subgraph: The subgraph obtained by removing a single vertex.\\<close>\n\ndefinition remove_vertex :: \"'a \\<Rightarrow> ('a, 'b) Graph_scheme\" where\n  \"remove_vertex x \\<equiv> G\\<lparr> verts := V - {x}, arcs := Restr E (V - {x}) \\<rparr>\"\n\nlemma remove_vertex_V: \"V\\<^bsub>remove_vertex x\\<^esub> = V - {x}\" unfolding remove_vertex_def by auto\nlemma remove_vertex_V': \"V\\<^bsub>remove_vertex x\\<^esub> \\<subseteq> V\" unfolding remove_vertex_def by auto\nlemma remove_vertex_E: \"E\\<^bsub>remove_vertex x\\<^esub> = Restr E (V - {x})\" unfolding remove_vertex_def by simp\nlemma remove_vertex_E': \"v \\<rightarrow>\\<^bsub>remove_vertex x\\<^esub> w \\<Longrightarrow> v\\<rightarrow>w\" by (simp add: remove_vertex_E)\nlemma remove_vertex_E'': \"\\<lbrakk> v\\<rightarrow>w; v \\<noteq> x; w \\<noteq> x \\<rbrakk> \\<Longrightarrow> v \\<rightarrow>\\<^bsub>remove_vertex x\\<^esub> w\"\n  by (simp add: edges_are_in_V remove_vertex_E)\n\ntext \\<open>Of course, this is still a digraph.\\<close>\nlemma remove_vertex_Digraph: \"Digraph (remove_vertex v)\" proof\n  let ?V = \"V\\<^bsub>remove_vertex v\\<^esub>\" let ?E = \"E\\<^bsub>remove_vertex v\\<^esub>\"\n  show \"finite ?V\" unfolding remove_vertex_def using finite_vertex_set by simp\n  show \"?E \\<subseteq> ?V \\<times> ?V\" proof\n    fix e assume \"e \\<in> ?E\"\n    then have \"e \\<in> (V - {v}) \\<times> (V - {v})\" by (metis Int_iff remove_vertex_E)\n    then show \"e \\<in> ?V \\<times> ?V\" using remove_vertex_V by auto\n  qed\n  have \"\\<And>x y. \\<lbrakk> (x,y) \\<in> ?E; (x,y) \\<notin> E \\<rbrakk> \\<Longrightarrow> (y,x) \\<in> ?E\" unfolding remove_vertex_def by simp\nqed\n\ntext \\<open>\n  We are also going to need a few lemmas about how walks and paths behave when we remove a vertex.\n\n  First, if we remove a vertex that is not on a walk @{term xs}, then @{term xs} is still a walk\n  after removing this vertex.\n\\<close>\n\nlemma remove_vertex_walk:\n  assumes \"walk xs\" \"x \\<notin> set xs\"\n  shows \"Digraph.walk (remove_vertex x) xs\"\nproof-\n  interpret H: Digraph \"remove_vertex x\" using remove_vertex_Digraph by blast\n  show ?thesis using assms proof (induct rule: walk.induct)\n    case (Singleton v)\n    then have \"v \\<in> V - {x}\" by simp\n    then show ?case using remove_vertex_V by simp\n  next\n    case (Cons v w vs)\n    then have \"v \\<rightarrow>\\<^bsub>remove_vertex x\\<^esub> w\" using remove_vertex_E'' by auto\n    then show ?case\n      by (meson Cons.hyps(3) Cons.prems(1) H.Cons assms(2) list.set_intros(2))\n  qed simp\nqed\n\ntext \\<open>The same holds for paths.\\<close>\n\nlemma remove_vertex_path_from_to:\n  \"\\<lbrakk> v \\<leadsto>xs\\<leadsto> w; x \\<in> V; x \\<notin> set xs \\<rbrakk> \\<Longrightarrow> v \\<leadsto>xs\\<leadsto>\\<^bsub>remove_vertex x\\<^esub> w\"\n  using path_from_to_def remove_vertex_walk by fastforce\n\ntext \\<open>\n  Conversely, if something was a walk or a path in the subgraph, then it is also a walk or a path\n  in the supergraph.\n\\<close>\nlemma remove_vertex_walk_add:\n  assumes \"Digraph.walk (remove_vertex x) xs\"\n  shows \"walk xs\"\nproof-\n  interpret H: Digraph \"remove_vertex x\" using remove_vertex_Digraph by blast\n  show ?thesis using assms proof (induct rule: H.walk.induct)\n    case (Singleton v)\n    then show ?case by (meson Digraph.Singleton Digraph_axioms remove_vertex_V' subsetD)\n  next\n    case (Cons v w vs)\n    then show ?case by (meson Digraph.Cons Digraph_axioms remove_vertex_E')\n  qed simp\nqed\n\nlemma remove_vertex_path_from_to_add: \"v \\<leadsto>xs\\<leadsto>\\<^bsub>remove_vertex x\\<^esub> w \\<Longrightarrow> v \\<leadsto>xs\\<leadsto> w\"\n  using path_from_to_def remove_vertex_walk_add by fastforce\n\nend \\<comment> \\<open>context Digraph\\<close>\n\nsubsection \\<open>Two Distinguished Distinct Non-adjacent Vertices.\\<close>\n\ntext \\<open>\n  The setup for Menger's Theorem requires two distinguished distinct non-adjacent vertices\n  @{term v0} and @{term v1}.  Let us pin down this concept with the following locale.\n\\<close>\n\nlocale v0_v1_Digraph = Digraph +\n  fixes v0 v1 :: \"'a\"\n  assumes v0_V: \"v0 \\<in> V\" and v1_V: \"v1 \\<in> V\"\n    and v0_nonadj_v1: \"\\<not>v0\\<rightarrow>v1\"\n    and v0_neq_v1: \"v0 \\<noteq> v1\"\n\ntext \\<open>\n  The only lemma we need about @{locale v0_v1_Digraph} for now is that it is closed under removing\n  a vertex that is not @{term v0} or @{term v1}.\n\\<close>\nlemma (in v0_v1_Digraph) remove_vertices_v0_v1_Digraph:\n  assumes \"v \\<noteq> v0\" \"v \\<noteq> v1\"\n  shows \"v0_v1_Digraph (remove_vertex v) v0 v1\"\nproof (rule v0_v1_Digraph.intro)\n  show \"v0_v1_Digraph_axioms (remove_vertex v) v0 v1\"\n    using assms v0_nonadj_v1 v0_neq_v1 v0_V v1_V remove_vertex_V remove_vertex_E'\n    by unfold_locales blast+\nqed (simp add: remove_vertex_Digraph)\n\nsubsection \\<open>Undirected Graphs\\<close>\n\ntext \\<open>\n  We represent undirecteded graphs as a special case of digraphs where every undirected edge\n  is represented as an edge in both directions.  We also exclude loops because loops are uncommon\n  in undirected graphs.\n\n  As we will explain in the next paragraph, all of this has no bearing on the validity of\n  Menger's Theorem for undirected graphs.\n\\<close>\n\nlocale Graph = Digraph +\n  assumes undirected: \"v\\<rightarrow>w = w\\<rightarrow>v\"\n      and no_loops: \"\\<not>v\\<rightarrow>v\"\n\ntext \\<open>\n  We observe that this makes @{locale Digraph} a sublocale of @{locale Graph}, meaning that every\n  theorem we prove for digraphs automatically holds for undirected graphs, although it may not make\n  sense because for example ``connectedness'' (if we were to define it) would need different\n  definitions for directed and undirected graphs.\n\n  Fortunately, the notions of ``separator'' and ``internally vertex-disjoint paths'' on directed\n  graphs are the same for undirected graphs.  So Menger's Theorem, when we eventually prove it in\n  the @{locale Digraph} locale, will apply automatically to the @{locale Graph} locale without\n  any additional work.\n\n  For this reason we will not use the @{term Graph} locale again in this proof development and it\n  exists merely to show that undirected graphs are covered as a special case by our definitions.\n\\<close>\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Menger/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.8872045892435128, "lm_q1q2_score": 0.7938613282004279}}
{"text": "(*\n  File:   Master_Theorem_Examples.thy\n  Author: Manuel Eberl <manuel@pruvisto.org>\n\n  Examples for the application of the Master theorem and related proof methods.\n*)\n\nsection \\<open>Examples\\<close>\ntheory Master_Theorem_Examples\nimports\n  Complex_Main\n  Akra_Bazzi_Method\n  Akra_Bazzi_Approximation\nbegin\n\nsubsection \\<open>Merge sort\\<close>\n\n(* A merge sort cost function that is parametrised with the recombination costs *)\nfunction merge_sort_cost :: \"(nat \\<Rightarrow> real) \\<Rightarrow> nat \\<Rightarrow> real\" where\n  \"merge_sort_cost t 0 = 0\"\n| \"merge_sort_cost t 1 = 1\"\n| \"n \\<ge> 2 \\<Longrightarrow> merge_sort_cost t n = \n     merge_sort_cost t (nat \\<lfloor>real n / 2\\<rfloor>) + merge_sort_cost t (nat \\<lceil>real n / 2\\<rceil>) + t n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma merge_sort_nonneg[simp]: \"(\\<And>n. t n \\<ge> 0) \\<Longrightarrow> merge_sort_cost t x \\<ge> 0\"\n  by (induction t x rule: merge_sort_cost.induct) (simp_all del: One_nat_def)\n\nlemma \"t \\<in> \\<Theta>(\\<lambda>n. real n) \\<Longrightarrow> (\\<And>n. t n \\<ge> 0) \\<Longrightarrow> merge_sort_cost t \\<in> \\<Theta>(\\<lambda>n. real n * ln (real n))\"\n  by (master_theorem 2.3) simp_all\n\nsubsection \\<open>Karatsuba multiplication\\<close>\n\nfunction karatsuba_cost :: \"nat \\<Rightarrow> real\" where\n  \"karatsuba_cost 0 = 0\"\n| \"karatsuba_cost 1 = 1\"\n| \"n \\<ge> 2 \\<Longrightarrow> karatsuba_cost n = \n     3 * karatsuba_cost (nat \\<lceil>real n / 2\\<rceil>) + real n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma karatsuba_cost_nonneg[simp]: \"karatsuba_cost n \\<ge> 0\"\n  by (induction n rule: karatsuba_cost.induct) (simp_all del: One_nat_def)\n\nlemma \"karatsuba_cost \\<in> O(\\<lambda>n. real n powr log 2 3)\"\n   by (master_theorem 1 p': 1) (simp_all add: powr_divide)\n\nlemma karatsuba_cost_pos: \"n \\<ge> 1 \\<Longrightarrow> karatsuba_cost n > 0\"\n  by (induction n rule: karatsuba_cost.induct) (auto intro!: add_nonneg_pos simp del: One_nat_def)\n\nlemma \"karatsuba_cost \\<in> \\<Theta>(\\<lambda>n. real n powr log 2 3)\"\n  using karatsuba_cost_pos\n  by (master_theorem 1 p': 1) (auto simp add: powr_divide eventually_at_top_linorder)\n\n\nsubsection \\<open>Strassen matrix multiplication\\<close>\n\nfunction strassen_cost :: \"nat \\<Rightarrow> real\" where\n  \"strassen_cost 0 = 0\"\n| \"strassen_cost 1 = 1\"\n| \"n \\<ge> 2 \\<Longrightarrow> strassen_cost n = 7 * strassen_cost (nat \\<lceil>real n / 2\\<rceil>) + real (n^2)\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma strassen_cost_nonneg[simp]: \"strassen_cost n \\<ge> 0\"\n  by (induction n rule: strassen_cost.induct) (simp_all del: One_nat_def)\n\nlemma \"strassen_cost \\<in> O(\\<lambda>n. real n powr log 2 7)\"\n  by (master_theorem 1 p': 2) (auto simp: powr_divide eventually_at_top_linorder)\n\nlemma strassen_cost_pos: \"n \\<ge> 1 \\<Longrightarrow> strassen_cost n > 0\"\n  by (cases n rule: strassen_cost.cases) (simp_all add: add_nonneg_pos del: One_nat_def)\n\nlemma \"strassen_cost \\<in> \\<Theta>(\\<lambda>n. real n powr log 2 7)\"\n  using strassen_cost_pos\n  by (master_theorem 1 p': 2) (auto simp: powr_divide eventually_at_top_linorder)\n\n\nsubsection \\<open>Deterministic select\\<close>\n\n(* This is not possible with the standard Master theorem from literature *)\nfunction select_cost :: \"nat \\<Rightarrow> real\" where\n  \"n \\<le> 20 \\<Longrightarrow> select_cost n = 0\"\n| \"n > 20 \\<Longrightarrow> select_cost n = \n     select_cost (nat \\<lfloor>real n / 5\\<rfloor>) + select_cost (nat \\<lfloor>7 * real n / 10\\<rfloor> + 6) + 12 * real n / 5\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"select_cost \\<in> \\<Theta>(\\<lambda>n. real n)\"\n  by (master_theorem 3) auto\n\n\nsubsection \\<open>Decreasing function\\<close>\n\nfunction dec_cost :: \"nat \\<Rightarrow> real\" where\n  \"n \\<le> 2 \\<Longrightarrow> dec_cost n = 1\"\n| \"n > 2 \\<Longrightarrow> dec_cost n = 0.5*dec_cost (nat \\<lfloor>real n / 2\\<rfloor>) + 1 / real n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"dec_cost \\<in> \\<Theta>(\\<lambda>x::nat. ln x / x)\"\n  by (master_theorem 2.3) simp_all\n\n\nsubsection \\<open>Example taken from Drmota and Szpakowski\\<close>\n\nfunction drmota1 :: \"nat \\<Rightarrow> real\" where\n  \"n < 20 \\<Longrightarrow> drmota1 n = 1\"\n| \"n \\<ge> 20 \\<Longrightarrow> drmota1 n = 2 * drmota1 (nat \\<lfloor>real n/2\\<rfloor>) + 8/9 * drmota1 (nat \\<lfloor>3*real n/4\\<rfloor>) + real n^2 / ln (real n)\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"drmota1 \\<in> \\<Theta>(\\<lambda>n::real. n^2 * ln (ln n))\"\n  by (master_theorem 2.2) (simp_all add: power_divide)\n\n\nfunction drmota2 :: \"nat \\<Rightarrow> real\" where\n  \"n < 20 \\<Longrightarrow> drmota2 n = 1\"\n| \"n \\<ge> 20 \\<Longrightarrow> drmota2 n = 1/3 * drmota2 (nat \\<lfloor>real n/3 + 1/2\\<rfloor>) + 2/3 * drmota2 (nat \\<lfloor>2*real n/3 - 1/2\\<rfloor>) + 1\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"drmota2 \\<in> \\<Theta>(\\<lambda>x. ln (real x))\"\n  by master_theorem simp_all\n\n(* Average phrase length of Boncelet arithmetic coding. See Drmota and Szpankowski. *)\nlemma boncelet_phrase_length:\n  fixes p \\<delta> :: real assumes p: \"p > 0\" \"p < 1\" and \\<delta>: \"\\<delta> > 0\" \"\\<delta> < 1\" \"2*p + \\<delta> < 2\"\n  fixes d :: \"nat \\<Rightarrow> real\"\n  defines \"q \\<equiv> 1 - p\"\n  assumes d_nonneg: \"\\<And>n. d n \\<ge> 0\"\n  assumes d_rec: \"\\<And>n. n \\<ge> 2 \\<Longrightarrow> d n = 1 + p * d (nat \\<lfloor>p * real n + \\<delta>\\<rfloor>) + q * d (nat \\<lfloor>q * real n - \\<delta>\\<rfloor>)\"\n  shows   \"d \\<in> \\<Theta>(\\<lambda>x. ln x)\"\n  using assms by (master_theorem recursion: d_rec, simp_all)\n\n\n\nsubsection \\<open>Transcendental exponents\\<close>\n\n(* Certain number-theoretic conjectures would imply that if all the parameters are rational,\n   the Akra-Bazzi parameter is either rational or transcendental. That makes this case \n   probably transcendental *)\nfunction foo_cost :: \"nat \\<Rightarrow> real\" where\n  \"n < 200 \\<Longrightarrow> foo_cost n = 0\"\n| \"n \\<ge> 200 \\<Longrightarrow> foo_cost n = \n     foo_cost (nat \\<lfloor>real n / 3\\<rfloor>) + foo_cost (nat \\<lfloor>3 * real n / 4\\<rfloor> + 42) + real n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma foo_cost_nonneg [simp]: \"foo_cost n \\<ge> 0\"\n  by (induction n rule: foo_cost.induct) simp_all\n\nlemma \"foo_cost \\<in> \\<Theta>(\\<lambda>n. real n powr akra_bazzi_exponent [1,1] [1/3,3/4])\"\nproof (master_theorem 1 p': 1) \n  have \"\\<forall>n\\<ge>200. foo_cost n > 0\" by (simp add: add_nonneg_pos)\n  thus \"eventually (\\<lambda>n. foo_cost n > 0) at_top\" unfolding eventually_at_top_linorder by blast\nqed simp_all\n\nlemma \"akra_bazzi_exponent [1,1] [1/3,3/4] \\<in> {1.1519623..1.1519624}\"\n  by (akra_bazzi_approximate 29)\n\n\nsubsection \\<open>Functions in locale contexts\\<close>\n\nlocale det_select =\n  fixes b :: real\n  assumes b: \"b > 0\" \"b < 7/10\"\nbegin\n\nfunction select_cost' :: \"nat \\<Rightarrow> real\" where\n  \"n \\<le> 20 \\<Longrightarrow> select_cost' n = 0\"\n| \"n > 20 \\<Longrightarrow> select_cost' n = \n     select_cost' (nat \\<lfloor>real n / 5\\<rfloor>) + select_cost' (nat \\<lfloor>b * real n\\<rfloor> + 6) + 6 * real n + 5\"\nby force simp_all\ntermination using b by akra_bazzi_termination simp_all\n\nlemma \"a \\<ge> 0 \\<Longrightarrow> select_cost' \\<in> \\<Theta>(\\<lambda>n. real n)\"\n  using b by (master_theorem 3, force+)\n\nend\n\n\nsubsection \\<open>Non-curried functions\\<close>\n\n(* Note: either a or b could be seen as recursion variables. *)\nfunction baz_cost :: \"nat \\<times> nat \\<Rightarrow> real\" where\n  \"n \\<le> 2 \\<Longrightarrow> baz_cost (a, n) = 0\"\n| \"n > 2 \\<Longrightarrow> baz_cost (a, n) = 3 * baz_cost (a, nat \\<lfloor>real n / 2\\<rfloor>) + real a\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma baz_cost_nonneg [simp]: \"a \\<ge> 0 \\<Longrightarrow> baz_cost (a, n) \\<ge> 0\"\n  by (induction a n rule: baz_cost.induct[split_format (complete)]) simp_all\n\nlemma\n  assumes \"a > 0\"\n  shows   \"(\\<lambda>x. baz_cost (a, x)) \\<in> \\<Theta>(\\<lambda>x. x powr log 2 3)\"\nproof (master_theorem 1 p': 0)\n  from assms have \"\\<forall>x\\<ge>3. baz_cost (a, x) > 0\" by (auto intro: add_nonneg_pos)\n  thus \"eventually (\\<lambda>x. baz_cost (a, x) > 0) at_top\" by (force simp: eventually_at_top_linorder)\nqed (insert assms, simp_all add: powr_divide)\n\n(* Non-\"Akra-Bazzi\" variables may even be modified without impacting the termination proof.\n   However, the Akra-Bazzi theorem and the Master theorem itself do not apply anymore, \n   because bar_cost cannot be seen as a recursive function with one parameter *)\nfunction bar_cost :: \"nat \\<times> nat \\<Rightarrow> real\" where\n  \"n \\<le> 2 \\<Longrightarrow> bar_cost (a, n) = 0\"\n| \"n > 2 \\<Longrightarrow> bar_cost (a, n) = 3 * bar_cost (2 * a, nat \\<lfloor>real n / 2\\<rfloor>) + real a\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\n\nsubsection \\<open>Ham-sandwich trees\\<close>\n(* f(n) = f(n/4) + f(n/2) + 1 *)\nfunction ham_sandwich_cost :: \"nat \\<Rightarrow> real\" where\n  \"n < 4 \\<Longrightarrow> ham_sandwich_cost n = 1\"\n| \"n \\<ge> 4 \\<Longrightarrow> ham_sandwich_cost n = \n      ham_sandwich_cost (nat \\<lfloor>n/4\\<rfloor>) + ham_sandwich_cost (nat \\<lfloor>n/2\\<rfloor>) + 1\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma ham_sandwich_cost_pos [simp]: \"ham_sandwich_cost n > 0\"\n  by (induction n rule: ham_sandwich_cost.induct) simp_all\n\n\ntext \\<open>The golden ratio\\<close>\n\ndefinition \"\\<phi> = ((1 + sqrt 5) / 2 :: real)\"\n\nlemma \\<phi>_pos [simp]: \"\\<phi> > 0\" and \\<phi>_nonneg [simp]: \"\\<phi> \\<ge> 0\" and \\<phi>_nonzero [simp]: \"\\<phi> \\<noteq> 0\"\nproof-\n  show \"\\<phi> > 0\" unfolding \\<phi>_def by (simp add: add_pos_nonneg)\n  thus \"\\<phi> \\<ge> 0\" \"\\<phi> \\<noteq> 0\" by simp_all\nqed\n\n\nlemma \"ham_sandwich_cost \\<in> \\<Theta>(\\<lambda>n. n powr (log 2 \\<phi>))\"\nproof (master_theorem 1 p': 0)\n  have \"(1 / 4) powr log 2 \\<phi> + (1 / 2) powr log 2 \\<phi> =\n            inverse (2 powr log 2 \\<phi>)^2 + inverse (2 powr log 2 \\<phi>)\"\n        by (simp add: powr_divide field_simps powr_powr power2_eq_square powr_mult[symmetric]\n                 del: powr_log_cancel)\n  also have \"... = inverse (\\<phi>^2) + inverse \\<phi>\" by (simp add: power2_eq_square)\n  also have \"\\<phi> + 1 = \\<phi>*\\<phi>\" by (simp add: \\<phi>_def field_simps)\n  hence \"inverse (\\<phi>^2) + inverse \\<phi> = 1\" by (simp add: field_simps power2_eq_square)\n  finally show \"(1 / 4) powr log 2 \\<phi> + (1 / 2) powr log 2 \\<phi> = 1\" by simp\nqed simp_all\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Akra_Bazzi/Master_Theorem_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.7938266253386519}}
{"text": "theory Indexing\n  imports Complex_Main\nbegin\n\nsection \\<open>Indexing\\<close>\n\nsubsection \\<open>Sqrt Floor and Ceiling\\<close>\n\ndefinition lg :: \"real \\<Rightarrow> real\" where\n  \"lg \\<equiv> log 2\"\n\ndefinition sqrt_ceiling :: \"nat \\<Rightarrow> nat\" (\"sqrt\\<up> _\" [1000]) where \n  \"sqrt\\<up> u = 2^(nat \\<lceil>lg u / 2\\<rceil>)\"\n\ndefinition sqrt_floor :: \"nat \\<Rightarrow> nat\" (\"sqrt\\<down> _\" [1000]) where\n  \"sqrt\\<down> u = 2^(nat \\<lfloor>lg u / 2\\<rfloor>)\"\n\nlemma odd_ceiling_div2_add1:\n  fixes k :: nat\n  assumes \"odd k\"\n  shows \"nat \\<lceil>k / 2\\<rceil> = k div 2 + 1\"\nproof -\n  have 0: \"k / 2 = k div 2 + 1/2\"\n    using odd_two_times_div_two_succ[OF assms] by simp\n  have \"k / 2 \\<noteq> of_int \\<lfloor>k / 2\\<rfloor>\"\n    by (simp add: 0)\n  thus ?thesis\n    unfolding ceiling_altdef by (auto, linarith)\nqed\n\nlemma sqrt_floor_div2:\n  \"sqrt\\<down> (2^k) = 2^(k div 2)\"\nproof -\n  have \"(2::nat)^nat \\<lfloor>log 2 (2 ^ k) / 2\\<rfloor> = 2^nat \\<lfloor>k / 2\\<rfloor>\"\n    by simp\n  also have \"... = 2^(k div 2)\"\n    by (metis floor_divide_of_nat_eq nat_int of_nat_numeral)\n  finally show ?thesis\n    unfolding sqrt_floor_def lg_def by simp\nqed\n\nlemma sqrt_ceiling_div2:\n  \"even k \\<Longrightarrow> sqrt\\<up> (2^k) = 2^(k div 2)\"\n  unfolding sqrt_ceiling_def lg_def by auto\n\nlemma sqrt_ceiling_div2_add1:\n  \"odd k \\<Longrightarrow> sqrt\\<up> (2^k) = 2^(k div 2 + 1)\"\n  unfolding sqrt_ceiling_def lg_def using odd_ceiling_div2_add1 by auto\n\nlemma sqrt_ceiling_mul_floor:\n  assumes \"u = 2^k\"\n  shows \"u = sqrt\\<up> u * sqrt\\<down> u\"\nproof -\n  have 0: \"sqrt\\<up> u * sqrt\\<down> u = 2^(nat \\<lceil>k / 2\\<rceil>) * 2^(nat \\<lfloor>k / 2\\<rfloor>)\"\n    using assms unfolding lg_def sqrt_ceiling_def sqrt_floor_def by simp\n  show ?thesis\n  proof (cases \"even k\")\n    case True\n    hence \"(2::nat)^(nat \\<lceil>k / 2\\<rceil>) * 2^(nat \\<lfloor>k / 2\\<rfloor>) = 2^(k div 2 + k div 2)\"\n      by (auto simp: power_add)\n    thus ?thesis\n      using 0 True assms by auto\n  next\n    case False\n    hence \"(2::nat)^(nat \\<lceil>k / 2\\<rceil>) * 2^(nat \\<lfloor>k / 2\\<rfloor>) = 2^(k div 2 + 1) * 2^(k div 2)\"\n      using odd_ceiling_div2_add1 by (metis floor_divide_of_nat_eq nat_int of_nat_numeral)\n    also have \"... = 2^(k div 2 + 1 + k div 2)\"\n      by (auto simp: power_add)\n    finally show ?thesis\n      using 0 assms False by (metis False add.commute left_add_twice odd_two_times_div_two_succ)\n  qed\nqed\n\nsubsection \"Index, High and Low\"\n\ndefinition high :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"high i u = i div (sqrt\\<down> u)\"\n\ndefinition low :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"low i u = i mod (sqrt\\<down> u)\"\n\ndefinition index :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"index i j u = i * sqrt\\<down> u + j\"\n\nlemma index_high_low:\n  \"index (high i u) (low i u) u = i\"\n  unfolding index_def high_def low_def by simp\n\nlemma index_eq_high_low:\n  assumes \"l < sqrt\\<down> u\" \"i = index h l u\"\n  shows \"h = high i u\" \"l = low i u\"\n  using assms unfolding index_def high_def low_def by auto\n\nlemma index_low_mono:\n  \"j < k \\<longleftrightarrow> index i j u < index i k u\"\n  unfolding index_def by simp\n\nlemma index_high_mono:\n  \"i < k \\<Longrightarrow> j < sqrt\\<down> u \\<Longrightarrow> index i j u < index k l u\"\n  unfolding index_def using mult_le_mono1[of \"i+1\" k \"sqrt\\<down> u\"] discrete by simp\n\nlemma high_mono:\n  \"i \\<le> j \\<Longrightarrow> high i u \\<le> high j u\"\n  unfolding high_def using div_le_mono by blast\n\nlemma high_lt_sqrt_ceiling:\n  \"i < sqrt\\<down> u \\<Longrightarrow> high i u < sqrt\\<up> u\"\n  unfolding high_def sqrt_ceiling_def by simp\n\nlemma high_lt_k:\n  \"i < k * sqrt\\<down> u \\<Longrightarrow> high i u < k\"\n  using less_mult_imp_div_less unfolding high_def by blast\n\nlemma high_geq_index_h0:\n  \"index h 0 u \\<le> i \\<Longrightarrow> h \\<le> high i u\"\n  unfolding index_def high_def sqrt_floor_def using nat_le_iff_add by auto\n\nlemma low_lt_sqrt_floor:\n  \"low i u < sqrt\\<down> u\"\n  unfolding low_def sqrt_floor_def by simp\n\nlemma index_lt_u:\n  assumes \"u = 2^k\" \"i < sqrt\\<up> u\" \"j < sqrt\\<down> u\"\n  shows \"index i j u < u\"\nproof -\n  have 0: \"sqrt\\<down> u = 2^(k div 2)\"\n    by (simp add: assms(1) sqrt_floor_div2)\n  show ?thesis\n  proof (cases \"even k\")\n    case True\n    have \"index i j u \\<le> (sqrt\\<up> u - 1) * sqrt\\<down> u + j\"\n      using assms(2) index_def by auto\n    also have \"... \\<le> (sqrt\\<up> u - 1) * sqrt\\<down> u + (sqrt\\<down> u - 1)\"\n      using assms(3) by linarith\n    also have \"... = (2^(k div 2) - 1) * 2^(k div 2) + (2^(k div 2) - 1)\"\n      using 0 True assms(1) sqrt_ceiling_div2 by simp\n    also have \"... = 2^(k div 2 + k div 2) - 1\"\n      by (simp add: add.commute mult_eq_if power_add)\n    also have \"... = u - 1\"\n      using True assms(1) by (metis even_two_times_div_two mult_2)\n    finally have \"index i j u \\<le> u - 1\" .\n    thus ?thesis\n      using assms(1) by (simp add: Nat.le_diff_conv2)\n  next\n    case False\n    have \"index i j u \\<le> (sqrt\\<up> u - 1) * sqrt\\<down> u + j\"\n      using assms(2) index_def by auto\n    also have \"... \\<le> (sqrt\\<up> u - 1) * sqrt\\<down> u + (sqrt\\<down> u - 1)\"\n      using assms(3) by linarith\n    also have \"... = (2^(k div 2 + 1) - 1) * 2^(k div 2) + (2^(k div 2) - 1)\"\n      using 0 False assms(1) sqrt_ceiling_div2_add1 by simp\n    also have \"... = 2^(k div 2 + 1) * 2^(k div 2) - 1\"\n      by (simp add: add.commute mult_eq_if)\n    also have \"... = u - 1\"\n      using False assms(1) 0 sqrt_ceiling_div2_add1 sqrt_ceiling_mul_floor by force\n    finally have \"index i j u \\<le> u - 1\" .\n    thus ?thesis\n      using assms(1) by (simp add: Nat.le_diff_conv2)\n  qed\nqed\n\nend", "meta": {"author": "pacellie", "repo": "van_emde_boas", "sha": "ea74d6fe44092f983775a4aa71df078f0400257c", "save_path": "github-repos/isabelle/pacellie-van_emde_boas", "path": "github-repos/isabelle/pacellie-van_emde_boas/van_emde_boas-ea74d6fe44092f983775a4aa71df078f0400257c/Indexing.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7938098429147694}}
{"text": "(*  Title       : Series.thy\n    Author      : Jacques D. Fleuriot\n    Copyright   : 1998  University of Cambridge\n\nConverted to Isar and polished by lcp\nConverted to sum and polished yet more by TNN\nAdditional contributions by Jeremy Avigad\n*)\n\nsection \\<open>Infinite Series\\<close>\n\ntheory Series\nimports Limits Inequalities\nbegin\n\nsubsection \\<open>Definition of infinite summability\\<close>\n\ndefinition sums :: \"(nat \\<Rightarrow> 'a::{topological_space, comm_monoid_add}) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    (infixr \"sums\" 80)\n  where \"f sums s \\<longleftrightarrow> (\\<lambda>n. \\<Sum>i<n. f i) \\<longlonglongrightarrow> s\"\n\ndefinition summable :: \"(nat \\<Rightarrow> 'a::{topological_space, comm_monoid_add}) \\<Rightarrow> bool\"\n  where \"summable f \\<longleftrightarrow> (\\<exists>s. f sums s)\"\n\ndefinition suminf :: \"(nat \\<Rightarrow> 'a::{topological_space, comm_monoid_add}) \\<Rightarrow> 'a\"\n    (binder \"\\<Sum>\" 10)\n  where \"suminf f = (THE s. f sums s)\"\n\ntext\\<open>Variants of the definition\\<close>\nlemma sums_def': \"f sums s \\<longleftrightarrow> (\\<lambda>n. \\<Sum>i = 0..n. f i) \\<longlonglongrightarrow> s\"\n  apply (simp add: sums_def)\n  apply (subst LIMSEQ_Suc_iff [symmetric])\n  apply (simp only: lessThan_Suc_atMost atLeast0AtMost)\n  done\n\nlemma sums_def_le: \"f sums s \\<longleftrightarrow> (\\<lambda>n. \\<Sum>i\\<le>n. f i) \\<longlonglongrightarrow> s\"\n  by (simp add: sums_def' atMost_atLeast0)\n\n\nsubsection \\<open>Infinite summability on topological monoids\\<close>\n\nlemma sums_subst[trans]: \"f = g \\<Longrightarrow> g sums z \\<Longrightarrow> f sums z\"\n  by simp\n\nlemma sums_cong: \"(\\<And>n. f n = g n) \\<Longrightarrow> f sums c \\<longleftrightarrow> g sums c\"\n  by (drule ext) simp\n\nlemma sums_summable: \"f sums l \\<Longrightarrow> summable f\"\n  by (simp add: sums_def summable_def, blast)\n\nlemma summable_iff_convergent: \"summable f \\<longleftrightarrow> convergent (\\<lambda>n. \\<Sum>i<n. f i)\"\n  by (simp add: summable_def sums_def convergent_def)\n\nlemma summable_iff_convergent': \"summable f \\<longleftrightarrow> convergent (\\<lambda>n. sum f {..n})\"\n  by (simp_all only: summable_iff_convergent convergent_def\n        lessThan_Suc_atMost [symmetric] LIMSEQ_Suc_iff[of \"\\<lambda>n. sum f {..<n}\"])\n\nlemma suminf_eq_lim: \"suminf f = lim (\\<lambda>n. \\<Sum>i<n. f i)\"\n  by (simp add: suminf_def sums_def lim_def)\n\nlemma sums_zero[simp, intro]: \"(\\<lambda>n. 0) sums 0\"\n  unfolding sums_def by simp\n\nlemma summable_zero[simp, intro]: \"summable (\\<lambda>n. 0)\"\n  by (rule sums_zero [THEN sums_summable])\n\nlemma sums_group: \"f sums s \\<Longrightarrow> 0 < k \\<Longrightarrow> (\\<lambda>n. sum f {n * k ..< n * k + k}) sums s\"\n  apply (simp only: sums_def sum_nat_group tendsto_def eventually_sequentially)\n  apply safe\n  apply (erule_tac x=S in allE)\n  apply safe\n  apply (rule_tac x=\"N\" in exI, safe)\n  apply (drule_tac x=\"n*k\" in spec)\n  apply (erule mp)\n  apply (erule order_trans)\n  apply simp\n  done\n\nlemma suminf_cong: \"(\\<And>n. f n = g n) \\<Longrightarrow> suminf f = suminf g\"\n  by (rule arg_cong[of f g], rule ext) simp\n\nlemma summable_cong:\n  fixes f g :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"eventually (\\<lambda>x. f x = g x) sequentially\"\n  shows \"summable f = summable g\"\nproof -\n  from assms obtain N where N: \"\\<forall>n\\<ge>N. f n = g n\"\n    by (auto simp: eventually_at_top_linorder)\n  define C where \"C = (\\<Sum>k<N. f k - g k)\"\n  from eventually_ge_at_top[of N]\n  have \"eventually (\\<lambda>n. sum f {..<n} = C + sum g {..<n}) sequentially\"\n  proof eventually_elim\n    case (elim n)\n    then have \"{..<n} = {..<N} \\<union> {N..<n}\"\n      by auto\n    also have \"sum f ... = sum f {..<N} + sum f {N..<n}\"\n      by (intro sum.union_disjoint) auto\n    also from N have \"sum f {N..<n} = sum g {N..<n}\"\n      by (intro sum.cong) simp_all\n    also have \"sum f {..<N} + sum g {N..<n} = C + (sum g {..<N} + sum g {N..<n})\"\n      unfolding C_def by (simp add: algebra_simps sum_subtractf)\n    also have \"sum g {..<N} + sum g {N..<n} = sum g ({..<N} \\<union> {N..<n})\"\n      by (intro sum.union_disjoint [symmetric]) auto\n    also from elim have \"{..<N} \\<union> {N..<n} = {..<n}\"\n      by auto\n    finally show \"sum f {..<n} = C + sum g {..<n}\" .\n  qed\n  from convergent_cong[OF this] show ?thesis\n    by (simp add: summable_iff_convergent convergent_add_const_iff)\nqed\n\nlemma sums_finite:\n  assumes [simp]: \"finite N\"\n    and f: \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 0\"\n  shows \"f sums (\\<Sum>n\\<in>N. f n)\"\nproof -\n  have eq: \"sum f {..<n + Suc (Max N)} = sum f N\" for n\n  proof (cases \"N = {}\")\n    case True\n    with f have \"f = (\\<lambda>x. 0)\" by auto\n    then show ?thesis by simp\n  next\n    case [simp]: False\n    show ?thesis\n    proof (safe intro!: sum.mono_neutral_right f)\n      fix i\n      assume \"i \\<in> N\"\n      then have \"i \\<le> Max N\" by simp\n      then show \"i < n + Suc (Max N)\" by simp\n    qed\n  qed\n  show ?thesis\n    unfolding sums_def\n    by (rule LIMSEQ_offset[of _ \"Suc (Max N)\"])\n       (simp add: eq atLeast0LessThan del: add_Suc_right)\nqed\n\ncorollary sums_0: \"(\\<And>n. f n = 0) \\<Longrightarrow> (f sums 0)\"\n    by (metis (no_types) finite.emptyI sum.empty sums_finite)\n\nlemma summable_finite: \"finite N \\<Longrightarrow> (\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 0) \\<Longrightarrow> summable f\"\n  by (rule sums_summable) (rule sums_finite)\n\nlemma sums_If_finite_set: \"finite A \\<Longrightarrow> (\\<lambda>r. if r \\<in> A then f r else 0) sums (\\<Sum>r\\<in>A. f r)\"\n  using sums_finite[of A \"(\\<lambda>r. if r \\<in> A then f r else 0)\"] by simp\n\nlemma summable_If_finite_set[simp, intro]: \"finite A \\<Longrightarrow> summable (\\<lambda>r. if r \\<in> A then f r else 0)\"\n  by (rule sums_summable) (rule sums_If_finite_set)\n\nlemma sums_If_finite: \"finite {r. P r} \\<Longrightarrow> (\\<lambda>r. if P r then f r else 0) sums (\\<Sum>r | P r. f r)\"\n  using sums_If_finite_set[of \"{r. P r}\"] by simp\n\nlemma summable_If_finite[simp, intro]: \"finite {r. P r} \\<Longrightarrow> summable (\\<lambda>r. if P r then f r else 0)\"\n  by (rule sums_summable) (rule sums_If_finite)\n\nlemma sums_single: \"(\\<lambda>r. if r = i then f r else 0) sums f i\"\n  using sums_If_finite[of \"\\<lambda>r. r = i\"] by simp\n\nlemma summable_single[simp, intro]: \"summable (\\<lambda>r. if r = i then f r else 0)\"\n  by (rule sums_summable) (rule sums_single)\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::{t2_space,comm_monoid_add}\"\nbegin\n\nlemma summable_sums[intro]: \"summable f \\<Longrightarrow> f sums (suminf f)\"\n  by (simp add: summable_def sums_def suminf_def)\n     (metis convergent_LIMSEQ_iff convergent_def lim_def)\n\nlemma summable_LIMSEQ: \"summable f \\<Longrightarrow> (\\<lambda>n. \\<Sum>i<n. f i) \\<longlonglongrightarrow> suminf f\"\n  by (rule summable_sums [unfolded sums_def])\n\nlemma sums_unique: \"f sums s \\<Longrightarrow> s = suminf f\"\n  by (metis limI suminf_eq_lim sums_def)\n\nlemma sums_iff: \"f sums x \\<longleftrightarrow> summable f \\<and> suminf f = x\"\n  by (metis summable_sums sums_summable sums_unique)\n\nlemma summable_sums_iff: \"summable f \\<longleftrightarrow> f sums suminf f\"\n  by (auto simp: sums_iff summable_sums)\n\nlemma sums_unique2: \"f sums a \\<Longrightarrow> f sums b \\<Longrightarrow> a = b\"\n  for a b :: 'a\n  by (simp add: sums_iff)\n\nlemma suminf_finite:\n  assumes N: \"finite N\"\n    and f: \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 0\"\n  shows \"suminf f = (\\<Sum>n\\<in>N. f n)\"\n  using sums_finite[OF assms, THEN sums_unique] by simp\n\nend\n\nlemma suminf_zero[simp]: \"suminf (\\<lambda>n. 0::'a::{t2_space, comm_monoid_add}) = 0\"\n  by (rule sums_zero [THEN sums_unique, symmetric])\n\n\nsubsection \\<open>Infinite summability on ordered, topological monoids\\<close>\n\nlemma sums_le: \"\\<forall>n. f n \\<le> g n \\<Longrightarrow> f sums s \\<Longrightarrow> g sums t \\<Longrightarrow> s \\<le> t\"\n  for f g :: \"nat \\<Rightarrow> 'a::{ordered_comm_monoid_add,linorder_topology}\"\n  by (rule LIMSEQ_le) (auto intro: sum_mono simp: sums_def)\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::{ordered_comm_monoid_add,linorder_topology}\"\nbegin\n\nlemma suminf_le: \"\\<forall>n. f n \\<le> g n \\<Longrightarrow> summable f \\<Longrightarrow> summable g \\<Longrightarrow> suminf f \\<le> suminf g\"\n  by (auto dest: sums_summable intro: sums_le)\n\nlemma sum_le_suminf: \"summable f \\<Longrightarrow> \\<forall>m\\<ge>n. 0 \\<le> f m \\<Longrightarrow> sum f {..<n} \\<le> suminf f\"\n  by (rule sums_le[OF _ sums_If_finite_set summable_sums]) auto\n\nlemma suminf_nonneg: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> 0 \\<le> suminf f\"\n  using sum_le_suminf[of 0] by simp\n\nlemma suminf_le_const: \"summable f \\<Longrightarrow> (\\<And>n. sum f {..<n} \\<le> x) \\<Longrightarrow> suminf f \\<le> x\"\n  by (metis LIMSEQ_le_const2 summable_LIMSEQ)\n\nlemma suminf_eq_zero_iff: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> suminf f = 0 \\<longleftrightarrow> (\\<forall>n. f n = 0)\"\nproof\n  assume \"summable f\" \"suminf f = 0\" and pos: \"\\<forall>n. 0 \\<le> f n\"\n  then have f: \"(\\<lambda>n. \\<Sum>i<n. f i) \\<longlonglongrightarrow> 0\"\n    using summable_LIMSEQ[of f] by simp\n  then have \"\\<And>i. (\\<Sum>n\\<in>{i}. f n) \\<le> 0\"\n  proof (rule LIMSEQ_le_const)\n    show \"\\<exists>N. \\<forall>n\\<ge>N. (\\<Sum>n\\<in>{i}. f n) \\<le> sum f {..<n}\" for i\n      using pos by (intro exI[of _ \"Suc i\"] allI impI sum_mono2) auto\n  qed\n  with pos show \"\\<forall>n. f n = 0\"\n    by (auto intro!: antisym)\nqed (metis suminf_zero fun_eq_iff)\n\nlemma suminf_pos_iff: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> 0 < suminf f \\<longleftrightarrow> (\\<exists>i. 0 < f i)\"\n  using sum_le_suminf[of 0] suminf_eq_zero_iff by (simp add: less_le)\n\nlemma suminf_pos2:\n  assumes \"summable f\" \"\\<forall>n. 0 \\<le> f n\" \"0 < f i\"\n  shows \"0 < suminf f\"\nproof -\n  have \"0 < (\\<Sum>n<Suc i. f n)\"\n    using assms by (intro sum_pos2[where i=i]) auto\n  also have \"\\<dots> \\<le> suminf f\"\n    using assms by (intro sum_le_suminf) auto\n  finally show ?thesis .\nqed\n\nlemma suminf_pos: \"summable f \\<Longrightarrow> \\<forall>n. 0 < f n \\<Longrightarrow> 0 < suminf f\"\n  by (intro suminf_pos2[where i=0]) (auto intro: less_imp_le)\n\nend\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::{ordered_cancel_comm_monoid_add,linorder_topology}\"\nbegin\n\nlemma sum_less_suminf2:\n  \"summable f \\<Longrightarrow> \\<forall>m\\<ge>n. 0 \\<le> f m \\<Longrightarrow> n \\<le> i \\<Longrightarrow> 0 < f i \\<Longrightarrow> sum f {..<n} < suminf f\"\n  using sum_le_suminf[of f \"Suc i\"]\n    and add_strict_increasing[of \"f i\" \"sum f {..<n}\" \"sum f {..<i}\"]\n    and sum_mono2[of \"{..<i}\" \"{..<n}\" f]\n  by (auto simp: less_imp_le ac_simps)\n\nlemma sum_less_suminf: \"summable f \\<Longrightarrow> \\<forall>m\\<ge>n. 0 < f m \\<Longrightarrow> sum f {..<n} < suminf f\"\n  using sum_less_suminf2[of n n] by (simp add: less_imp_le)\n\nend\n\nlemma summableI_nonneg_bounded:\n  fixes f :: \"nat \\<Rightarrow> 'a::{ordered_comm_monoid_add,linorder_topology,conditionally_complete_linorder}\"\n  assumes pos[simp]: \"\\<And>n. 0 \\<le> f n\"\n    and le: \"\\<And>n. (\\<Sum>i<n. f i) \\<le> x\"\n  shows \"summable f\"\n  unfolding summable_def sums_def [abs_def]\nproof (rule exI LIMSEQ_incseq_SUP)+\n  show \"bdd_above (range (\\<lambda>n. sum f {..<n}))\"\n    using le by (auto simp: bdd_above_def)\n  show \"incseq (\\<lambda>n. sum f {..<n})\"\n    by (auto simp: mono_def intro!: sum_mono2)\nqed\n\nlemma summableI[intro, simp]: \"summable f\"\n  for f :: \"nat \\<Rightarrow> 'a::{canonically_ordered_monoid_add,linorder_topology,complete_linorder}\"\n  by (intro summableI_nonneg_bounded[where x=top] zero_le top_greatest)\n\n\nsubsection \\<open>Infinite summability on topological monoids\\<close>\n\ncontext\n  fixes f g :: \"nat \\<Rightarrow> 'a::{t2_space,topological_comm_monoid_add}\"\nbegin\n\nlemma sums_Suc:\n  assumes \"(\\<lambda>n. f (Suc n)) sums l\"\n  shows \"f sums (l + f 0)\"\nproof  -\n  have \"(\\<lambda>n. (\\<Sum>i<n. f (Suc i)) + f 0) \\<longlonglongrightarrow> l + f 0\"\n    using assms by (auto intro!: tendsto_add simp: sums_def)\n  moreover have \"(\\<Sum>i<n. f (Suc i)) + f 0 = (\\<Sum>i<Suc n. f i)\" for n\n    unfolding lessThan_Suc_eq_insert_0\n    by (simp add: ac_simps sum_atLeast1_atMost_eq image_Suc_lessThan)\n  ultimately show ?thesis\n    by (auto simp: sums_def simp del: sum_lessThan_Suc intro: LIMSEQ_Suc_iff[THEN iffD1])\nqed\n\nlemma sums_add: \"f sums a \\<Longrightarrow> g sums b \\<Longrightarrow> (\\<lambda>n. f n + g n) sums (a + b)\"\n  unfolding sums_def by (simp add: sum.distrib tendsto_add)\n\nlemma summable_add: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. f n + g n)\"\n  unfolding summable_def by (auto intro: sums_add)\n\nlemma suminf_add: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> suminf f + suminf g = (\\<Sum>n. f n + g n)\"\n  by (intro sums_unique sums_add summable_sums)\n\nend\n\ncontext\n  fixes f :: \"'i \\<Rightarrow> nat \\<Rightarrow> 'a::{t2_space,topological_comm_monoid_add}\"\n    and I :: \"'i set\"\nbegin\n\nlemma sums_sum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) sums (x i)) \\<Longrightarrow> (\\<lambda>n. \\<Sum>i\\<in>I. f i n) sums (\\<Sum>i\\<in>I. x i)\"\n  by (induct I rule: infinite_finite_induct) (auto intro!: sums_add)\n\nlemma suminf_sum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> summable (f i)) \\<Longrightarrow> (\\<Sum>n. \\<Sum>i\\<in>I. f i n) = (\\<Sum>i\\<in>I. \\<Sum>n. f i n)\"\n  using sums_unique[OF sums_sum, OF summable_sums] by simp\n\nlemma summable_sum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> summable (f i)) \\<Longrightarrow> summable (\\<lambda>n. \\<Sum>i\\<in>I. f i n)\"\n  using sums_summable[OF sums_sum[OF summable_sums]] .\n\nend\n\nsubsection \\<open>Infinite summability on real normed vector spaces\\<close>\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\nbegin\n\nlemma sums_Suc_iff: \"(\\<lambda>n. f (Suc n)) sums s \\<longleftrightarrow> f sums (s + f 0)\"\nproof -\n  have \"f sums (s + f 0) \\<longleftrightarrow> (\\<lambda>i. \\<Sum>j<Suc i. f j) \\<longlonglongrightarrow> s + f 0\"\n    by (subst LIMSEQ_Suc_iff) (simp add: sums_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>i. (\\<Sum>j<i. f (Suc j)) + f 0) \\<longlonglongrightarrow> s + f 0\"\n    by (simp add: ac_simps lessThan_Suc_eq_insert_0 image_Suc_lessThan sum_atLeast1_atMost_eq)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>n. f (Suc n)) sums s\"\n  proof\n    assume \"(\\<lambda>i. (\\<Sum>j<i. f (Suc j)) + f 0) \\<longlonglongrightarrow> s + f 0\"\n    with tendsto_add[OF this tendsto_const, of \"- f 0\"] show \"(\\<lambda>i. f (Suc i)) sums s\"\n      by (simp add: sums_def)\n  qed (auto intro: tendsto_add simp: sums_def)\n  finally show ?thesis ..\nqed\n\nlemma summable_Suc_iff: \"summable (\\<lambda>n. f (Suc n)) = summable f\"\nproof\n  assume \"summable f\"\n  then have \"f sums suminf f\"\n    by (rule summable_sums)\n  then have \"(\\<lambda>n. f (Suc n)) sums (suminf f - f 0)\"\n    by (simp add: sums_Suc_iff)\n  then show \"summable (\\<lambda>n. f (Suc n))\"\n    unfolding summable_def by blast\nqed (auto simp: sums_Suc_iff summable_def)\n\nlemma sums_Suc_imp: \"f 0 = 0 \\<Longrightarrow> (\\<lambda>n. f (Suc n)) sums s \\<Longrightarrow> (\\<lambda>n. f n) sums s\"\n  using sums_Suc_iff by simp\n\nend\n\ncontext (* Separate contexts are necessary to allow general use of the results above, here. *)\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\nbegin\n\nlemma sums_diff: \"f sums a \\<Longrightarrow> g sums b \\<Longrightarrow> (\\<lambda>n. f n - g n) sums (a - b)\"\n  unfolding sums_def by (simp add: sum_subtractf tendsto_diff)\n\nlemma summable_diff: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. f n - g n)\"\n  unfolding summable_def by (auto intro: sums_diff)\n\nlemma suminf_diff: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> suminf f - suminf g = (\\<Sum>n. f n - g n)\"\n  by (intro sums_unique sums_diff summable_sums)\n\nlemma sums_minus: \"f sums a \\<Longrightarrow> (\\<lambda>n. - f n) sums (- a)\"\n  unfolding sums_def by (simp add: sum_negf tendsto_minus)\n\nlemma summable_minus: \"summable f \\<Longrightarrow> summable (\\<lambda>n. - f n)\"\n  unfolding summable_def by (auto intro: sums_minus)\n\nlemma suminf_minus: \"summable f \\<Longrightarrow> (\\<Sum>n. - f n) = - (\\<Sum>n. f n)\"\n  by (intro sums_unique [symmetric] sums_minus summable_sums)\n\nlemma sums_iff_shift: \"(\\<lambda>i. f (i + n)) sums s \\<longleftrightarrow> f sums (s + (\\<Sum>i<n. f i))\"\nproof (induct n arbitrary: s)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have \"(\\<lambda>i. f (Suc i + n)) sums s \\<longleftrightarrow> (\\<lambda>i. f (i + n)) sums (s + f n)\"\n    by (subst sums_Suc_iff) simp\n  with Suc show ?case\n    by (simp add: ac_simps)\nqed\n\ncorollary sums_iff_shift': \"(\\<lambda>i. f (i + n)) sums (s - (\\<Sum>i<n. f i)) \\<longleftrightarrow> f sums s\"\n  by (simp add: sums_iff_shift)\n\nlemma sums_zero_iff_shift:\n  assumes \"\\<And>i. i < n \\<Longrightarrow> f i = 0\"\n  shows \"(\\<lambda>i. f (i+n)) sums s \\<longleftrightarrow> (\\<lambda>i. f i) sums s\"\n  by (simp add: assms sums_iff_shift)\n\nlemma summable_iff_shift: \"summable (\\<lambda>n. f (n + k)) \\<longleftrightarrow> summable f\"\n  by (metis diff_add_cancel summable_def sums_iff_shift [abs_def])\n\nlemma sums_split_initial_segment: \"f sums s \\<Longrightarrow> (\\<lambda>i. f (i + n)) sums (s - (\\<Sum>i<n. f i))\"\n  by (simp add: sums_iff_shift)\n\nlemma summable_ignore_initial_segment: \"summable f \\<Longrightarrow> summable (\\<lambda>n. f(n + k))\"\n  by (simp add: summable_iff_shift)\n\nlemma suminf_minus_initial_segment: \"summable f \\<Longrightarrow> (\\<Sum>n. f (n + k)) = (\\<Sum>n. f n) - (\\<Sum>i<k. f i)\"\n  by (rule sums_unique[symmetric]) (auto simp: sums_iff_shift)\n\nlemma suminf_split_initial_segment: \"summable f \\<Longrightarrow> suminf f = (\\<Sum>n. f(n + k)) + (\\<Sum>i<k. f i)\"\n  by (auto simp add: suminf_minus_initial_segment)\n\nlemma suminf_split_head: \"summable f \\<Longrightarrow> (\\<Sum>n. f (Suc n)) = suminf f - f 0\"\n  using suminf_split_initial_segment[of 1] by simp\n\nlemma suminf_exist_split:\n  fixes r :: real\n  assumes \"0 < r\" and \"summable f\"\n  shows \"\\<exists>N. \\<forall>n\\<ge>N. norm (\\<Sum>i. f (i + n)) < r\"\nproof -\n  from LIMSEQ_D[OF summable_LIMSEQ[OF \\<open>summable f\\<close>] \\<open>0 < r\\<close>]\n  obtain N :: nat where \"\\<forall> n \\<ge> N. norm (sum f {..<n} - suminf f) < r\"\n    by auto\n  then show ?thesis\n    by (auto simp: norm_minus_commute suminf_minus_initial_segment[OF \\<open>summable f\\<close>])\nqed\n\nlemma summable_LIMSEQ_zero: \"summable f \\<Longrightarrow> f \\<longlonglongrightarrow> 0\"\n  apply (drule summable_iff_convergent [THEN iffD1])\n  apply (drule convergent_Cauchy)\n  apply (simp only: Cauchy_iff LIMSEQ_iff)\n  apply safe\n  apply (drule_tac x=\"r\" in spec)\n  apply safe\n  apply (rule_tac x=\"M\" in exI)\n  apply safe\n  apply (drule_tac x=\"Suc n\" in spec)\n  apply simp\n  apply (drule_tac x=\"n\" in spec)\n  apply simp\n  done\n\nlemma summable_imp_convergent: \"summable f \\<Longrightarrow> convergent f\"\n  by (force dest!: summable_LIMSEQ_zero simp: convergent_def)\n\nlemma summable_imp_Bseq: \"summable f \\<Longrightarrow> Bseq f\"\n  by (simp add: convergent_imp_Bseq summable_imp_convergent)\n\nend\n\nlemma summable_minus_iff: \"summable (\\<lambda>n. - f n) \\<longleftrightarrow> summable f\"\n  for f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  by (auto dest: summable_minus)  (* used two ways, hence must be outside the context above *)\n\nlemma (in bounded_linear) sums: \"(\\<lambda>n. X n) sums a \\<Longrightarrow> (\\<lambda>n. f (X n)) sums (f a)\"\n  unfolding sums_def by (drule tendsto) (simp only: sum)\n\nlemma (in bounded_linear) summable: \"summable (\\<lambda>n. X n) \\<Longrightarrow> summable (\\<lambda>n. f (X n))\"\n  unfolding summable_def by (auto intro: sums)\n\nlemma (in bounded_linear) suminf: \"summable (\\<lambda>n. X n) \\<Longrightarrow> f (\\<Sum>n. X n) = (\\<Sum>n. f (X n))\"\n  by (intro sums_unique sums summable_sums)\n\nlemmas sums_of_real = bounded_linear.sums [OF bounded_linear_of_real]\nlemmas summable_of_real = bounded_linear.summable [OF bounded_linear_of_real]\nlemmas suminf_of_real = bounded_linear.suminf [OF bounded_linear_of_real]\n\nlemmas sums_scaleR_left = bounded_linear.sums[OF bounded_linear_scaleR_left]\nlemmas summable_scaleR_left = bounded_linear.summable[OF bounded_linear_scaleR_left]\nlemmas suminf_scaleR_left = bounded_linear.suminf[OF bounded_linear_scaleR_left]\n\nlemmas sums_scaleR_right = bounded_linear.sums[OF bounded_linear_scaleR_right]\nlemmas summable_scaleR_right = bounded_linear.summable[OF bounded_linear_scaleR_right]\nlemmas suminf_scaleR_right = bounded_linear.suminf[OF bounded_linear_scaleR_right]\n\nlemma summable_const_iff: \"summable (\\<lambda>_. c) \\<longleftrightarrow> c = 0\"\n  for c :: \"'a::real_normed_vector\"\nproof -\n  have \"\\<not> summable (\\<lambda>_. c)\" if \"c \\<noteq> 0\"\n  proof -\n    from that have \"filterlim (\\<lambda>n. of_nat n * norm c) at_top sequentially\"\n      by (subst mult.commute)\n        (auto intro!: filterlim_tendsto_pos_mult_at_top filterlim_real_sequentially)\n    then have \"\\<not> convergent (\\<lambda>n. norm (\\<Sum>k<n. c))\"\n      by (intro filterlim_at_infinity_imp_not_convergent filterlim_at_top_imp_at_infinity)\n        (simp_all add: sum_constant_scaleR)\n    then show ?thesis\n      unfolding summable_iff_convergent using convergent_norm by blast\n  qed\n  then show ?thesis by auto\nqed\n\n\nsubsection \\<open>Infinite summability on real normed algebras\\<close>\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_algebra\"\nbegin\n\nlemma sums_mult: \"f sums a \\<Longrightarrow> (\\<lambda>n. c * f n) sums (c * a)\"\n  by (rule bounded_linear.sums [OF bounded_linear_mult_right])\n\nlemma summable_mult: \"summable f \\<Longrightarrow> summable (\\<lambda>n. c * f n)\"\n  by (rule bounded_linear.summable [OF bounded_linear_mult_right])\n\nlemma suminf_mult: \"summable f \\<Longrightarrow> suminf (\\<lambda>n. c * f n) = c * suminf f\"\n  by (rule bounded_linear.suminf [OF bounded_linear_mult_right, symmetric])\n\nlemma sums_mult2: \"f sums a \\<Longrightarrow> (\\<lambda>n. f n * c) sums (a * c)\"\n  by (rule bounded_linear.sums [OF bounded_linear_mult_left])\n\nlemma summable_mult2: \"summable f \\<Longrightarrow> summable (\\<lambda>n. f n * c)\"\n  by (rule bounded_linear.summable [OF bounded_linear_mult_left])\n\nlemma suminf_mult2: \"summable f \\<Longrightarrow> suminf f * c = (\\<Sum>n. f n * c)\"\n  by (rule bounded_linear.suminf [OF bounded_linear_mult_left])\n\nend\n\nlemma sums_mult_iff:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,field}\"\n  assumes \"c \\<noteq> 0\"\n  shows \"(\\<lambda>n. c * f n) sums (c * d) \\<longleftrightarrow> f sums d\"\n  using sums_mult[of f d c] sums_mult[of \"\\<lambda>n. c * f n\" \"c * d\" \"inverse c\"]\n  by (force simp: field_simps assms)\n\nlemma sums_mult2_iff:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,field}\"\n  assumes \"c \\<noteq> 0\"\n  shows   \"(\\<lambda>n. f n * c) sums (d * c) \\<longleftrightarrow> f sums d\"\n  using sums_mult_iff[OF assms, of f d] by (simp add: mult.commute)\n\nlemma sums_of_real_iff:\n  \"(\\<lambda>n. of_real (f n) :: 'a::real_normed_div_algebra) sums of_real c \\<longleftrightarrow> f sums c\"\n  by (simp add: sums_def of_real_sum[symmetric] tendsto_of_real_iff del: of_real_sum)\n\n\nsubsection \\<open>Infinite summability on real normed fields\\<close>\n\ncontext\n  fixes c :: \"'a::real_normed_field\"\nbegin\n\nlemma sums_divide: \"f sums a \\<Longrightarrow> (\\<lambda>n. f n / c) sums (a / c)\"\n  by (rule bounded_linear.sums [OF bounded_linear_divide])\n\nlemma summable_divide: \"summable f \\<Longrightarrow> summable (\\<lambda>n. f n / c)\"\n  by (rule bounded_linear.summable [OF bounded_linear_divide])\n\nlemma suminf_divide: \"summable f \\<Longrightarrow> suminf (\\<lambda>n. f n / c) = suminf f / c\"\n  by (rule bounded_linear.suminf [OF bounded_linear_divide, symmetric])\n\nlemma sums_mult_D: \"(\\<lambda>n. c * f n) sums a \\<Longrightarrow> c \\<noteq> 0 \\<Longrightarrow> f sums (a/c)\"\n  using sums_mult_iff by fastforce\n\nlemma summable_mult_D: \"summable (\\<lambda>n. c * f n) \\<Longrightarrow> c \\<noteq> 0 \\<Longrightarrow> summable f\"\n  by (auto dest: summable_divide)\n\n\ntext \\<open>Sum of a geometric progression.\\<close>\n\nlemma geometric_sums:\n  assumes less_1: \"norm c < 1\"\n  shows \"(\\<lambda>n. c^n) sums (1 / (1 - c))\"\nproof -\n  from less_1 have neq_1: \"c \\<noteq> 1\" by auto\n  then have neq_0: \"c - 1 \\<noteq> 0\" by simp\n  from less_1 have lim_0: \"(\\<lambda>n. c^n) \\<longlonglongrightarrow> 0\"\n    by (rule LIMSEQ_power_zero)\n  then have \"(\\<lambda>n. c ^ n / (c - 1) - 1 / (c - 1)) \\<longlonglongrightarrow> 0 / (c - 1) - 1 / (c - 1)\"\n    using neq_0 by (intro tendsto_intros)\n  then have \"(\\<lambda>n. (c ^ n - 1) / (c - 1)) \\<longlonglongrightarrow> 1 / (1 - c)\"\n    by (simp add: nonzero_minus_divide_right [OF neq_0] diff_divide_distrib)\n  then show \"(\\<lambda>n. c ^ n) sums (1 / (1 - c))\"\n    by (simp add: sums_def geometric_sum neq_1)\nqed\n\nlemma summable_geometric: \"norm c < 1 \\<Longrightarrow> summable (\\<lambda>n. c^n)\"\n  by (rule geometric_sums [THEN sums_summable])\n\nlemma suminf_geometric: \"norm c < 1 \\<Longrightarrow> suminf (\\<lambda>n. c^n) = 1 / (1 - c)\"\n  by (rule sums_unique[symmetric]) (rule geometric_sums)\n\nlemma summable_geometric_iff: \"summable (\\<lambda>n. c ^ n) \\<longleftrightarrow> norm c < 1\"\nproof\n  assume \"summable (\\<lambda>n. c ^ n :: 'a :: real_normed_field)\"\n  then have \"(\\<lambda>n. norm c ^ n) \\<longlonglongrightarrow> 0\"\n    by (simp add: norm_power [symmetric] tendsto_norm_zero_iff summable_LIMSEQ_zero)\n  from order_tendstoD(2)[OF this zero_less_one] obtain n where \"norm c ^ n < 1\"\n    by (auto simp: eventually_at_top_linorder)\n  then show \"norm c < 1\" using one_le_power[of \"norm c\" n]\n    by (cases \"norm c \\<ge> 1\") (linarith, simp)\nqed (rule summable_geometric)\n\nend\n\nlemma power_half_series: \"(\\<lambda>n. (1/2::real)^Suc n) sums 1\"\nproof -\n  have 2: \"(\\<lambda>n. (1/2::real)^n) sums 2\"\n    using geometric_sums [of \"1/2::real\"] by auto\n  have \"(\\<lambda>n. (1/2::real)^Suc n) = (\\<lambda>n. (1 / 2) ^ n / 2)\"\n    by (simp add: mult.commute)\n  then show ?thesis\n    using sums_divide [OF 2, of 2] by simp\nqed\n\n\nsubsection \\<open>Telescoping\\<close>\n\nlemma telescope_sums:\n  fixes c :: \"'a::real_normed_vector\"\n  assumes \"f \\<longlonglongrightarrow> c\"\n  shows \"(\\<lambda>n. f (Suc n) - f n) sums (c - f 0)\"\n  unfolding sums_def\nproof (subst LIMSEQ_Suc_iff [symmetric])\n  have \"(\\<lambda>n. \\<Sum>k<Suc n. f (Suc k) - f k) = (\\<lambda>n. f (Suc n) - f 0)\"\n    by (simp add: lessThan_Suc_atMost atLeast0AtMost [symmetric] sum_Suc_diff)\n  also have \"\\<dots> \\<longlonglongrightarrow> c - f 0\"\n    by (intro tendsto_diff LIMSEQ_Suc[OF assms] tendsto_const)\n  finally show \"(\\<lambda>n. \\<Sum>n<Suc n. f (Suc n) - f n) \\<longlonglongrightarrow> c - f 0\" .\nqed\n\nlemma telescope_sums':\n  fixes c :: \"'a::real_normed_vector\"\n  assumes \"f \\<longlonglongrightarrow> c\"\n  shows \"(\\<lambda>n. f n - f (Suc n)) sums (f 0 - c)\"\n  using sums_minus[OF telescope_sums[OF assms]] by (simp add: algebra_simps)\n\nlemma telescope_summable:\n  fixes c :: \"'a::real_normed_vector\"\n  assumes \"f \\<longlonglongrightarrow> c\"\n  shows \"summable (\\<lambda>n. f (Suc n) - f n)\"\n  using telescope_sums[OF assms] by (simp add: sums_iff)\n\nlemma telescope_summable':\n  fixes c :: \"'a::real_normed_vector\"\n  assumes \"f \\<longlonglongrightarrow> c\"\n  shows \"summable (\\<lambda>n. f n - f (Suc n))\"\n  using summable_minus[OF telescope_summable[OF assms]] by (simp add: algebra_simps)\n\n\nsubsection \\<open>Infinite summability on Banach spaces\\<close>\n\ntext \\<open>Cauchy-type criterion for convergence of series (c.f. Harrison).\\<close>\n\nlemma summable_Cauchy: \"summable f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>N. \\<forall>m\\<ge>N. \\<forall>n. norm (sum f {m..<n}) < e)\"\n  for f :: \"nat \\<Rightarrow> 'a::banach\"\n  apply (simp only: summable_iff_convergent Cauchy_convergent_iff [symmetric] Cauchy_iff)\n  apply safe\n   apply (drule spec)\n   apply (drule (1) mp)\n   apply (erule exE)\n   apply (rule_tac x=\"M\" in exI)\n   apply clarify\n   apply (rule_tac x=\"m\" and y=\"n\" in linorder_le_cases)\n    apply (frule (1) order_trans)\n    apply (drule_tac x=\"n\" in spec)\n    apply (drule (1) mp)\n    apply (drule_tac x=\"m\" in spec)\n    apply (drule (1) mp)\n    apply (simp_all add: sum_diff [symmetric])\n  apply (drule spec)\n  apply (drule (1) mp)\n  apply (erule exE)\n  apply (rule_tac x=\"N\" in exI)\n  apply clarify\n  apply (rule_tac x=\"m\" and y=\"n\" in linorder_le_cases)\n   apply (subst norm_minus_commute)\n   apply (simp_all add: sum_diff [symmetric])\n  done\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::banach\"\nbegin\n\ntext \\<open>Absolute convergence imples normal convergence.\\<close>\n\nlemma summable_norm_cancel: \"summable (\\<lambda>n. norm (f n)) \\<Longrightarrow> summable f\"\n  apply (simp only: summable_Cauchy)\n  apply safe\n  apply (drule_tac x=\"e\" in spec)\n  apply safe\n  apply (rule_tac x=\"N\" in exI)\n  apply safe\n  apply (drule_tac x=\"m\" in spec)\n  apply safe\n  apply (rule order_le_less_trans [OF norm_sum])\n  apply (rule order_le_less_trans [OF abs_ge_self])\n  apply simp\n  done\n\nlemma summable_norm: \"summable (\\<lambda>n. norm (f n)) \\<Longrightarrow> norm (suminf f) \\<le> (\\<Sum>n. norm (f n))\"\n  by (auto intro: LIMSEQ_le tendsto_norm summable_norm_cancel summable_LIMSEQ norm_sum)\n\ntext \\<open>Comparison tests.\\<close>\n\nlemma summable_comparison_test: \"\\<exists>N. \\<forall>n\\<ge>N. norm (f n) \\<le> g n \\<Longrightarrow> summable g \\<Longrightarrow> summable f\"\n  apply (simp add: summable_Cauchy)\n  apply safe\n  apply (drule_tac x=\"e\" in spec)\n  apply safe\n  apply (rule_tac x = \"N + Na\" in exI)\n  apply safe\n  apply (rotate_tac 2)\n  apply (drule_tac x = m in spec)\n  apply auto\n  apply (rotate_tac 2)\n  apply (drule_tac x = n in spec)\n  apply (rule_tac y = \"\\<Sum>k=m..<n. norm (f k)\" in order_le_less_trans)\n   apply (rule norm_sum)\n  apply (rule_tac y = \"sum g {m..<n}\" in order_le_less_trans)\n   apply (auto intro: sum_mono simp add: abs_less_iff)\n  done\n\nlemma summable_comparison_test_ev:\n  \"eventually (\\<lambda>n. norm (f n) \\<le> g n) sequentially \\<Longrightarrow> summable g \\<Longrightarrow> summable f\"\n  by (rule summable_comparison_test) (auto simp: eventually_at_top_linorder)\n\ntext \\<open>A better argument order.\\<close>\nlemma summable_comparison_test': \"summable g \\<Longrightarrow> (\\<And>n. n \\<ge> N \\<Longrightarrow> norm (f n) \\<le> g n) \\<Longrightarrow> summable f\"\n  by (rule summable_comparison_test) auto\n\n\nsubsection \\<open>The Ratio Test\\<close>\n\nlemma summable_ratio_test:\n  assumes \"c < 1\" \"\\<And>n. n \\<ge> N \\<Longrightarrow> norm (f (Suc n)) \\<le> c * norm (f n)\"\n  shows \"summable f\"\nproof (cases \"0 < c\")\n  case True\n  show \"summable f\"\n  proof (rule summable_comparison_test)\n    show \"\\<exists>N'. \\<forall>n\\<ge>N'. norm (f n) \\<le> (norm (f N) / (c ^ N)) * c ^ n\"\n    proof (intro exI allI impI)\n      fix n\n      assume \"N \\<le> n\"\n      then show \"norm (f n) \\<le> (norm (f N) / (c ^ N)) * c ^ n\"\n      proof (induct rule: inc_induct)\n        case base\n        with True show ?case by simp\n      next\n        case (step m)\n        have \"norm (f (Suc m)) / c ^ Suc m * c ^ n \\<le> norm (f m) / c ^ m * c ^ n\"\n          using \\<open>0 < c\\<close> \\<open>c < 1\\<close> assms(2)[OF \\<open>N \\<le> m\\<close>] by (simp add: field_simps)\n        with step show ?case by simp\n      qed\n    qed\n    show \"summable (\\<lambda>n. norm (f N) / c ^ N * c ^ n)\"\n      using \\<open>0 < c\\<close> \\<open>c < 1\\<close> by (intro summable_mult summable_geometric) simp\n  qed\nnext\n  case False\n  have \"f (Suc n) = 0\" if \"n \\<ge> N\" for n\n  proof -\n    from that have \"norm (f (Suc n)) \\<le> c * norm (f n)\"\n      by (rule assms(2))\n    also have \"\\<dots> \\<le> 0\"\n      using False by (simp add: not_less mult_nonpos_nonneg)\n    finally show ?thesis\n      by auto\n  qed\n  then show \"summable f\"\n    by (intro sums_summable[OF sums_finite, of \"{.. Suc N}\"]) (auto simp: not_le Suc_less_eq2)\nqed\n\nend\n\n\ntext \\<open>Relations among convergence and absolute convergence for power series.\\<close>\n\nlemma Abel_lemma:\n  fixes a :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes r: \"0 \\<le> r\"\n    and r0: \"r < r0\"\n    and M: \"\\<And>n. norm (a n) * r0^n \\<le> M\"\n  shows \"summable (\\<lambda>n. norm (a n) * r^n)\"\nproof (rule summable_comparison_test')\n  show \"summable (\\<lambda>n. M * (r / r0) ^ n)\"\n    using assms\n    by (auto simp add: summable_mult summable_geometric)\n  show \"norm (norm (a n) * r ^ n) \\<le> M * (r / r0) ^ n\" for n\n    using r r0 M [of n]\n    apply (auto simp add: abs_mult field_simps)\n    apply (cases \"r = 0\")\n     apply simp\n     apply (cases n)\n      apply auto\n    done\nqed\n\n\ntext \\<open>Summability of geometric series for real algebras.\\<close>\n\nlemma complete_algebra_summable_geometric:\n  fixes x :: \"'a::{real_normed_algebra_1,banach}\"\n  assumes \"norm x < 1\"\n  shows \"summable (\\<lambda>n. x ^ n)\"\nproof (rule summable_comparison_test)\n  show \"\\<exists>N. \\<forall>n\\<ge>N. norm (x ^ n) \\<le> norm x ^ n\"\n    by (simp add: norm_power_ineq)\n  from assms show \"summable (\\<lambda>n. norm x ^ n)\"\n    by (simp add: summable_geometric)\nqed\n\n\nsubsection \\<open>Cauchy Product Formula\\<close>\n\ntext \\<open>\n  Proof based on Analysis WebNotes: Chapter 07, Class 41\n  \\<^url>\\<open>http://www.math.unl.edu/~webnotes/classes/class41/prp77.htm\\<close>\n\\<close>\n\nlemma Cauchy_product_sums:\n  fixes a b :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,banach}\"\n  assumes a: \"summable (\\<lambda>k. norm (a k))\"\n    and b: \"summable (\\<lambda>k. norm (b k))\"\n  shows \"(\\<lambda>k. \\<Sum>i\\<le>k. a i * b (k - i)) sums ((\\<Sum>k. a k) * (\\<Sum>k. b k))\"\nproof -\n  let ?S1 = \"\\<lambda>n::nat. {..<n} \\<times> {..<n}\"\n  let ?S2 = \"\\<lambda>n::nat. {(i,j). i + j < n}\"\n  have S1_mono: \"\\<And>m n. m \\<le> n \\<Longrightarrow> ?S1 m \\<subseteq> ?S1 n\" by auto\n  have S2_le_S1: \"\\<And>n. ?S2 n \\<subseteq> ?S1 n\" by auto\n  have S1_le_S2: \"\\<And>n. ?S1 (n div 2) \\<subseteq> ?S2 n\" by auto\n  have finite_S1: \"\\<And>n. finite (?S1 n)\" by simp\n  with S2_le_S1 have finite_S2: \"\\<And>n. finite (?S2 n)\" by (rule finite_subset)\n\n  let ?g = \"\\<lambda>(i,j). a i * b j\"\n  let ?f = \"\\<lambda>(i,j). norm (a i) * norm (b j)\"\n  have f_nonneg: \"\\<And>x. 0 \\<le> ?f x\" by auto\n  then have norm_sum_f: \"\\<And>A. norm (sum ?f A) = sum ?f A\"\n    unfolding real_norm_def\n    by (simp only: abs_of_nonneg sum_nonneg [rule_format])\n\n  have \"(\\<lambda>n. (\\<Sum>k<n. a k) * (\\<Sum>k<n. b k)) \\<longlonglongrightarrow> (\\<Sum>k. a k) * (\\<Sum>k. b k)\"\n    by (intro tendsto_mult summable_LIMSEQ summable_norm_cancel [OF a] summable_norm_cancel [OF b])\n  then have 1: \"(\\<lambda>n. sum ?g (?S1 n)) \\<longlonglongrightarrow> (\\<Sum>k. a k) * (\\<Sum>k. b k)\"\n    by (simp only: sum_product sum.Sigma [rule_format] finite_lessThan)\n\n  have \"(\\<lambda>n. (\\<Sum>k<n. norm (a k)) * (\\<Sum>k<n. norm (b k))) \\<longlonglongrightarrow> (\\<Sum>k. norm (a k)) * (\\<Sum>k. norm (b k))\"\n    using a b by (intro tendsto_mult summable_LIMSEQ)\n  then have \"(\\<lambda>n. sum ?f (?S1 n)) \\<longlonglongrightarrow> (\\<Sum>k. norm (a k)) * (\\<Sum>k. norm (b k))\"\n    by (simp only: sum_product sum.Sigma [rule_format] finite_lessThan)\n  then have \"convergent (\\<lambda>n. sum ?f (?S1 n))\"\n    by (rule convergentI)\n  then have Cauchy: \"Cauchy (\\<lambda>n. sum ?f (?S1 n))\"\n    by (rule convergent_Cauchy)\n  have \"Zfun (\\<lambda>n. sum ?f (?S1 n - ?S2 n)) sequentially\"\n  proof (rule ZfunI, simp only: eventually_sequentially norm_sum_f)\n    fix r :: real\n    assume r: \"0 < r\"\n    from CauchyD [OF Cauchy r] obtain N\n      where \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. norm (sum ?f (?S1 m) - sum ?f (?S1 n)) < r\" ..\n    then have \"\\<And>m n. N \\<le> n \\<Longrightarrow> n \\<le> m \\<Longrightarrow> norm (sum ?f (?S1 m - ?S1 n)) < r\"\n      by (simp only: sum_diff finite_S1 S1_mono)\n    then have N: \"\\<And>m n. N \\<le> n \\<Longrightarrow> n \\<le> m \\<Longrightarrow> sum ?f (?S1 m - ?S1 n) < r\"\n      by (simp only: norm_sum_f)\n    show \"\\<exists>N. \\<forall>n\\<ge>N. sum ?f (?S1 n - ?S2 n) < r\"\n    proof (intro exI allI impI)\n      fix n\n      assume \"2 * N \\<le> n\"\n      then have n: \"N \\<le> n div 2\" by simp\n      have \"sum ?f (?S1 n - ?S2 n) \\<le> sum ?f (?S1 n - ?S1 (n div 2))\"\n        by (intro sum_mono2 finite_Diff finite_S1 f_nonneg Diff_mono subset_refl S1_le_S2)\n      also have \"\\<dots> < r\"\n        using n div_le_dividend by (rule N)\n      finally show \"sum ?f (?S1 n - ?S2 n) < r\" .\n    qed\n  qed\n  then have \"Zfun (\\<lambda>n. sum ?g (?S1 n - ?S2 n)) sequentially\"\n    apply (rule Zfun_le [rule_format])\n    apply (simp only: norm_sum_f)\n    apply (rule order_trans [OF norm_sum sum_mono])\n    apply (auto simp add: norm_mult_ineq)\n    done\n  then have 2: \"(\\<lambda>n. sum ?g (?S1 n) - sum ?g (?S2 n)) \\<longlonglongrightarrow> 0\"\n    unfolding tendsto_Zfun_iff diff_0_right\n    by (simp only: sum_diff finite_S1 S2_le_S1)\n  with 1 have \"(\\<lambda>n. sum ?g (?S2 n)) \\<longlonglongrightarrow> (\\<Sum>k. a k) * (\\<Sum>k. b k)\"\n    by (rule Lim_transform2)\n  then show ?thesis\n    by (simp only: sums_def sum_triangle_reindex)\nqed\n\nlemma Cauchy_product:\n  fixes a b :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,banach}\"\n  assumes \"summable (\\<lambda>k. norm (a k))\"\n    and \"summable (\\<lambda>k. norm (b k))\"\n  shows \"(\\<Sum>k. a k) * (\\<Sum>k. b k) = (\\<Sum>k. \\<Sum>i\\<le>k. a i * b (k - i))\"\n  using assms by (rule Cauchy_product_sums [THEN sums_unique])\n\nlemma summable_Cauchy_product:\n  fixes a b :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,banach}\"\n  assumes \"summable (\\<lambda>k. norm (a k))\"\n    and \"summable (\\<lambda>k. norm (b k))\"\n  shows \"summable (\\<lambda>k. \\<Sum>i\\<le>k. a i * b (k - i))\"\n  using Cauchy_product_sums[OF assms] by (simp add: sums_iff)\n\n\nsubsection \\<open>Series on @{typ real}s\\<close>\n\nlemma summable_norm_comparison_test:\n  \"\\<exists>N. \\<forall>n\\<ge>N. norm (f n) \\<le> g n \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. norm (f n))\"\n  by (rule summable_comparison_test) auto\n\nlemma summable_rabs_comparison_test: \"\\<exists>N. \\<forall>n\\<ge>N. \\<bar>f n\\<bar> \\<le> g n \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. \\<bar>f n\\<bar>)\"\n  for f :: \"nat \\<Rightarrow> real\"\n  by (rule summable_comparison_test) auto\n\nlemma summable_rabs_cancel: \"summable (\\<lambda>n. \\<bar>f n\\<bar>) \\<Longrightarrow> summable f\"\n  for f :: \"nat \\<Rightarrow> real\"\n  by (rule summable_norm_cancel) simp\n\nlemma summable_rabs: \"summable (\\<lambda>n. \\<bar>f n\\<bar>) \\<Longrightarrow> \\<bar>suminf f\\<bar> \\<le> (\\<Sum>n. \\<bar>f n\\<bar>)\"\n  for f :: \"nat \\<Rightarrow> real\"\n  by (fold real_norm_def) (rule summable_norm)\n\nlemma summable_zero_power [simp]: \"summable (\\<lambda>n. 0 ^ n :: 'a::{comm_ring_1,topological_space})\"\nproof -\n  have \"(\\<lambda>n. 0 ^ n :: 'a) = (\\<lambda>n. if n = 0 then 0^0 else 0)\"\n    by (intro ext) (simp add: zero_power)\n  moreover have \"summable \\<dots>\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma summable_zero_power' [simp]: \"summable (\\<lambda>n. f n * 0 ^ n :: 'a::{ring_1,topological_space})\"\nproof -\n  have \"(\\<lambda>n. f n * 0 ^ n :: 'a) = (\\<lambda>n. if n = 0 then f 0 * 0^0 else 0)\"\n    by (intro ext) (simp add: zero_power)\n  moreover have \"summable \\<dots>\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma summable_power_series:\n  fixes z :: real\n  assumes le_1: \"\\<And>i. f i \\<le> 1\"\n    and nonneg: \"\\<And>i. 0 \\<le> f i\"\n    and z: \"0 \\<le> z\" \"z < 1\"\n  shows \"summable (\\<lambda>i. f i * z^i)\"\nproof (rule summable_comparison_test[OF _ summable_geometric])\n  show \"norm z < 1\"\n    using z by (auto simp: less_imp_le)\n  show \"\\<And>n. \\<exists>N. \\<forall>na\\<ge>N. norm (f na * z ^ na) \\<le> z ^ na\"\n    using z\n    by (auto intro!: exI[of _ 0] mult_left_le_one_le simp: abs_mult nonneg power_abs less_imp_le le_1)\nqed\n\nlemma summable_0_powser: \"summable (\\<lambda>n. f n * 0 ^ n :: 'a::real_normed_div_algebra)\"\nproof -\n  have A: \"(\\<lambda>n. f n * 0 ^ n) = (\\<lambda>n. if n = 0 then f n else 0)\"\n    by (intro ext) auto\n  then show ?thesis\n    by (subst A) simp_all\nqed\n\nlemma summable_powser_split_head:\n  \"summable (\\<lambda>n. f (Suc n) * z ^ n :: 'a::real_normed_div_algebra) = summable (\\<lambda>n. f n * z ^ n)\"\nproof -\n  have \"summable (\\<lambda>n. f (Suc n) * z ^ n) \\<longleftrightarrow> summable (\\<lambda>n. f (Suc n) * z ^ Suc n)\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\n  proof\n    show ?rhs if ?lhs\n      using summable_mult2[OF that, of z]\n      by (simp add: power_commutes algebra_simps)\n    show ?lhs if ?rhs\n      using summable_mult2[OF that, of \"inverse z\"]\n      by (cases \"z \\<noteq> 0\", subst (asm) power_Suc2) (simp_all add: algebra_simps)\n  qed\n  also have \"\\<dots> \\<longleftrightarrow> summable (\\<lambda>n. f n * z ^ n)\" by (rule summable_Suc_iff)\n  finally show ?thesis .\nqed\n\nlemma powser_split_head:\n  fixes f :: \"nat \\<Rightarrow> 'a::{real_normed_div_algebra,banach}\"\n  assumes \"summable (\\<lambda>n. f n * z ^ n)\"\n  shows \"suminf (\\<lambda>n. f n * z ^ n) = f 0 + suminf (\\<lambda>n. f (Suc n) * z ^ n) * z\"\n    and \"suminf (\\<lambda>n. f (Suc n) * z ^ n) * z = suminf (\\<lambda>n. f n * z ^ n) - f 0\"\n    and \"summable (\\<lambda>n. f (Suc n) * z ^ n)\"\nproof -\n  from assms show \"summable (\\<lambda>n. f (Suc n) * z ^ n)\"\n    by (subst summable_powser_split_head)\n  from suminf_mult2[OF this, of z]\n    have \"(\\<Sum>n. f (Suc n) * z ^ n) * z = (\\<Sum>n. f (Suc n) * z ^ Suc n)\"\n    by (simp add: power_commutes algebra_simps)\n  also from assms have \"\\<dots> = suminf (\\<lambda>n. f n * z ^ n) - f 0\"\n    by (subst suminf_split_head) simp_all\n  finally show \"suminf (\\<lambda>n. f n * z ^ n) = f 0 + suminf (\\<lambda>n. f (Suc n) * z ^ n) * z\"\n    by simp\n  then show \"suminf (\\<lambda>n. f (Suc n) * z ^ n) * z = suminf (\\<lambda>n. f n * z ^ n) - f 0\"\n    by simp\nqed\n\nlemma summable_partial_sum_bound:\n  fixes f :: \"nat \\<Rightarrow> 'a :: banach\"\n    and e :: real\n  assumes summable: \"summable f\"\n    and e: \"e > 0\"\n  obtains N where \"\\<And>m n. m \\<ge> N \\<Longrightarrow> norm (\\<Sum>k=m..n. f k) < e\"\nproof -\n  from summable have \"Cauchy (\\<lambda>n. \\<Sum>k<n. f k)\"\n    by (simp add: Cauchy_convergent_iff summable_iff_convergent)\n  from CauchyD [OF this e] obtain N\n    where N: \"\\<And>m n. m \\<ge> N \\<Longrightarrow> n \\<ge> N \\<Longrightarrow> norm ((\\<Sum>k<m. f k) - (\\<Sum>k<n. f k)) < e\"\n    by blast\n  have \"norm (\\<Sum>k=m..n. f k) < e\" if m: \"m \\<ge> N\" for m n\n  proof (cases \"n \\<ge> m\")\n    case True\n    with m have \"norm ((\\<Sum>k<Suc n. f k) - (\\<Sum>k<m. f k)) < e\"\n      by (intro N) simp_all\n    also from True have \"(\\<Sum>k<Suc n. f k) - (\\<Sum>k<m. f k) = (\\<Sum>k=m..n. f k)\"\n      by (subst sum_diff [symmetric]) (simp_all add: sum_last_plus)\n    finally show ?thesis .\n  next\n    case False\n    with e show ?thesis by simp_all\n  qed\n  then show ?thesis by (rule that)\nqed\n\nlemma powser_sums_if:\n  \"(\\<lambda>n. (if n = m then (1 :: 'a::{ring_1,topological_space}) else 0) * z^n) sums z^m\"\nproof -\n  have \"(\\<lambda>n. (if n = m then 1 else 0) * z^n) = (\\<lambda>n. if n = m then z^n else 0)\"\n    by (intro ext) auto\n  then show ?thesis\n    by (simp add: sums_single)\nqed\n\nlemma\n  fixes f :: \"nat \\<Rightarrow> real\"\n  assumes \"summable f\"\n    and \"inj g\"\n    and pos: \"\\<And>x. 0 \\<le> f x\"\n  shows summable_reindex: \"summable (f \\<circ> g)\"\n    and suminf_reindex_mono: \"suminf (f \\<circ> g) \\<le> suminf f\"\n    and suminf_reindex: \"(\\<And>x. x \\<notin> range g \\<Longrightarrow> f x = 0) \\<Longrightarrow> suminf (f \\<circ> g) = suminf f\"\nproof -\n  from \\<open>inj g\\<close> have [simp]: \"\\<And>A. inj_on g A\"\n    by (rule subset_inj_on) simp\n\n  have smaller: \"\\<forall>n. (\\<Sum>i<n. (f \\<circ> g) i) \\<le> suminf f\"\n  proof\n    fix n\n    have \"\\<forall> n' \\<in> (g ` {..<n}). n' < Suc (Max (g ` {..<n}))\"\n      by (metis Max_ge finite_imageI finite_lessThan not_le not_less_eq)\n    then obtain m where n: \"\\<And>n'. n' < n \\<Longrightarrow> g n' < m\"\n      by blast\n\n    have \"(\\<Sum>i<n. f (g i)) = sum f (g ` {..<n})\"\n      by (simp add: sum.reindex)\n    also have \"\\<dots> \\<le> (\\<Sum>i<m. f i)\"\n      by (rule sum_mono3) (auto simp add: pos n[rule_format])\n    also have \"\\<dots> \\<le> suminf f\"\n      using \\<open>summable f\\<close> by (rule sum_le_suminf) (simp add: pos)\n    finally show \"(\\<Sum>i<n. (f \\<circ>  g) i) \\<le> suminf f\"\n      by simp\n  qed\n\n  have \"incseq (\\<lambda>n. \\<Sum>i<n. (f \\<circ> g) i)\"\n    by (rule incseq_SucI) (auto simp add: pos)\n  then obtain  L where L: \"(\\<lambda> n. \\<Sum>i<n. (f \\<circ> g) i) \\<longlonglongrightarrow> L\"\n    using smaller by(rule incseq_convergent)\n  then have \"(f \\<circ> g) sums L\"\n    by (simp add: sums_def)\n  then show \"summable (f \\<circ> g)\"\n    by (auto simp add: sums_iff)\n\n  then have \"(\\<lambda>n. \\<Sum>i<n. (f \\<circ> g) i) \\<longlonglongrightarrow> suminf (f \\<circ> g)\"\n    by (rule summable_LIMSEQ)\n  then show le: \"suminf (f \\<circ> g) \\<le> suminf f\"\n    by(rule LIMSEQ_le_const2)(blast intro: smaller[rule_format])\n\n  assume f: \"\\<And>x. x \\<notin> range g \\<Longrightarrow> f x = 0\"\n\n  from \\<open>summable f\\<close> have \"suminf f \\<le> suminf (f \\<circ> g)\"\n  proof (rule suminf_le_const)\n    fix n\n    have \"\\<forall> n' \\<in> (g -` {..<n}). n' < Suc (Max (g -` {..<n}))\"\n      by(auto intro: Max_ge simp add: finite_vimageI less_Suc_eq_le)\n    then obtain m where n: \"\\<And>n'. g n' < n \\<Longrightarrow> n' < m\"\n      by blast\n    have \"(\\<Sum>i<n. f i) = (\\<Sum>i\\<in>{..<n} \\<inter> range g. f i)\"\n      using f by(auto intro: sum.mono_neutral_cong_right)\n    also have \"\\<dots> = (\\<Sum>i\\<in>g -` {..<n}. (f \\<circ> g) i)\"\n      by (rule sum.reindex_cong[where l=g])(auto)\n    also have \"\\<dots> \\<le> (\\<Sum>i<m. (f \\<circ> g) i)\"\n      by (rule sum_mono3)(auto simp add: pos n)\n    also have \"\\<dots> \\<le> suminf (f \\<circ> g)\"\n      using \\<open>summable (f \\<circ> g)\\<close> by (rule sum_le_suminf) (simp add: pos)\n    finally show \"sum f {..<n} \\<le> suminf (f \\<circ> g)\" .\n  qed\n  with le show \"suminf (f \\<circ> g) = suminf f\"\n    by (rule antisym)\nqed\n\nlemma sums_mono_reindex:\n  assumes subseq: \"subseq g\"\n    and zero: \"\\<And>n. n \\<notin> range g \\<Longrightarrow> f n = 0\"\n  shows \"(\\<lambda>n. f (g n)) sums c \\<longleftrightarrow> f sums c\"\n  unfolding sums_def\nproof\n  assume lim: \"(\\<lambda>n. \\<Sum>k<n. f k) \\<longlonglongrightarrow> c\"\n  have \"(\\<lambda>n. \\<Sum>k<n. f (g k)) = (\\<lambda>n. \\<Sum>k<g n. f k)\"\n  proof\n    fix n :: nat\n    from subseq have \"(\\<Sum>k<n. f (g k)) = (\\<Sum>k\\<in>g`{..<n}. f k)\"\n      by (subst sum.reindex) (auto intro: subseq_imp_inj_on)\n    also from subseq have \"\\<dots> = (\\<Sum>k<g n. f k)\"\n      by (intro sum.mono_neutral_left ballI zero)\n        (auto dest: subseq_strict_mono simp: strict_mono_less strict_mono_less_eq)\n    finally show \"(\\<Sum>k<n. f (g k)) = (\\<Sum>k<g n. f k)\" .\n  qed\n  also from LIMSEQ_subseq_LIMSEQ[OF lim subseq] have \"\\<dots> \\<longlonglongrightarrow> c\"\n    by (simp only: o_def)\n  finally show \"(\\<lambda>n. \\<Sum>k<n. f (g k)) \\<longlonglongrightarrow> c\" .\nnext\n  assume lim: \"(\\<lambda>n. \\<Sum>k<n. f (g k)) \\<longlonglongrightarrow> c\"\n  define g_inv where \"g_inv n = (LEAST m. g m \\<ge> n)\" for n\n  from filterlim_subseq[OF subseq] have g_inv_ex: \"\\<exists>m. g m \\<ge> n\" for n\n    by (auto simp: filterlim_at_top eventually_at_top_linorder)\n  then have g_inv: \"g (g_inv n) \\<ge> n\" for n\n    unfolding g_inv_def by (rule LeastI_ex)\n  have g_inv_least: \"m \\<ge> g_inv n\" if \"g m \\<ge> n\" for m n\n    using that unfolding g_inv_def by (rule Least_le)\n  have g_inv_least': \"g m < n\" if \"m < g_inv n\" for m n\n    using that g_inv_least[of n m] by linarith\n  have \"(\\<lambda>n. \\<Sum>k<n. f k) = (\\<lambda>n. \\<Sum>k<g_inv n. f (g k))\"\n  proof\n    fix n :: nat\n    {\n      fix k\n      assume k: \"k \\<in> {..<n} - g`{..<g_inv n}\"\n      have \"k \\<notin> range g\"\n      proof (rule notI, elim imageE)\n        fix l\n        assume l: \"k = g l\"\n        have \"g l < g (g_inv n)\"\n          by (rule less_le_trans[OF _ g_inv]) (use k l in simp_all)\n        with subseq have \"l < g_inv n\"\n          by (simp add: subseq_strict_mono strict_mono_less)\n        with k l show False\n          by simp\n      qed\n      then have \"f k = 0\"\n        by (rule zero)\n    }\n    with g_inv_least' g_inv have \"(\\<Sum>k<n. f k) = (\\<Sum>k\\<in>g`{..<g_inv n}. f k)\"\n      by (intro sum.mono_neutral_right) auto\n    also from subseq have \"\\<dots> = (\\<Sum>k<g_inv n. f (g k))\"\n      using subseq_imp_inj_on by (subst sum.reindex) simp_all\n    finally show \"(\\<Sum>k<n. f k) = (\\<Sum>k<g_inv n. f (g k))\" .\n  qed\n  also {\n    fix K n :: nat\n    assume \"g K \\<le> n\"\n    also have \"n \\<le> g (g_inv n)\"\n      by (rule g_inv)\n    finally have \"K \\<le> g_inv n\"\n      using subseq by (simp add: strict_mono_less_eq subseq_strict_mono)\n  }\n  then have \"filterlim g_inv at_top sequentially\"\n    by (auto simp: filterlim_at_top eventually_at_top_linorder)\n  with lim have \"(\\<lambda>n. \\<Sum>k<g_inv n. f (g k)) \\<longlonglongrightarrow> c\"\n    by (rule filterlim_compose)\n  finally show \"(\\<lambda>n. \\<Sum>k<n. f k) \\<longlonglongrightarrow> c\" .\nqed\n\nlemma summable_mono_reindex:\n  assumes subseq: \"subseq g\"\n    and zero: \"\\<And>n. n \\<notin> range g \\<Longrightarrow> f n = 0\"\n  shows \"summable (\\<lambda>n. f (g n)) \\<longleftrightarrow> summable f\"\n  using sums_mono_reindex[of g f, OF assms] by (simp add: summable_def)\n\nlemma suminf_mono_reindex:\n  fixes f :: \"nat \\<Rightarrow> 'a::{t2_space,comm_monoid_add}\"\n  assumes \"subseq g\" \"\\<And>n. n \\<notin> range g \\<Longrightarrow> f n = 0\"\n  shows   \"suminf (\\<lambda>n. f (g n)) = suminf f\"\nproof (cases \"summable f\")\n  case True\n  with sums_mono_reindex [of g f, OF assms]\n    and summable_mono_reindex [of g f, OF assms]\n  show ?thesis\n    by (simp add: sums_iff)\nnext\n  case False\n  then have \"\\<not>(\\<exists>c. f sums c)\"\n    unfolding summable_def by blast\n  then have \"suminf f = The (\\<lambda>_. False)\"\n    by (simp add: suminf_def)\n  moreover from False have \"\\<not> summable (\\<lambda>n. f (g n))\"\n    using summable_mono_reindex[of g f, OF assms] by simp\n  then have \"\\<not>(\\<exists>c. (\\<lambda>n. f (g n)) sums c)\"\n    unfolding summable_def by blast\n  then have \"suminf (\\<lambda>n. f (g n)) = The (\\<lambda>_. False)\"\n    by (simp add: suminf_def)\n  ultimately show ?thesis by simp\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7938098416290505}}
{"text": "(*\n   File:     HOL/Analysis/Ball_Volume.thy\n   Author:   Manuel Eberl, TU München\n*)\n\nsection \\<open>The Volume of an \\<open>n\\<close>-Dimensional Ball\\<close>\n\ntheory Ball_Volume\n  imports Gamma_Function Lebesgue_Integral_Substitution\nbegin\n\ntext \\<open>\n  We define the volume of the unit ball in terms of the Gamma function. Note that the\n  dimension need not be an integer; we also allow fractional dimensions, although we do\n  not use this case or prove anything about it for now.\n\\<close>\ndefinition\\<^marker>\\<open>tag important\\<close> unit_ball_vol :: \"real \\<Rightarrow> real\" where\n  \"unit_ball_vol n = pi powr (n / 2) / Gamma (n / 2 + 1)\"\n\nlemma unit_ball_vol_pos [simp]: \"n \\<ge> 0 \\<Longrightarrow> unit_ball_vol n > 0\"\n  by (force simp: unit_ball_vol_def intro: divide_nonneg_pos)\n\nlemma unit_ball_vol_nonneg [simp]: \"n \\<ge> 0 \\<Longrightarrow> unit_ball_vol n \\<ge> 0\"\n  by (simp add: dual_order.strict_implies_order)\n\ntext \\<open>\n  We first need the value of the following integral, which is at the core of\n  computing the measure of an \\<open>n + 1\\<close>-dimensional ball in terms of the measure of an\n  \\<open>n\\<close>-dimensional one.\n\\<close>\nlemma emeasure_cball_aux_integral:\n  \"(\\<integral>\\<^sup>+x. indicator {-1..1} x * sqrt (1 - x\\<^sup>2) ^ n \\<partial>lborel) =\n      ennreal (Beta (1 / 2) (real n / 2 + 1))\"\nproof -\n  have \"((\\<lambda>t. t powr (-1 / 2) * (1 - t) powr (real n / 2)) has_integral\n          Beta (1 / 2) (real n / 2 + 1)) {0..1}\"\n    using has_integral_Beta_real[of \"1/2\" \"n / 2 + 1\"] by simp\n  from nn_integral_has_integral_lebesgue[OF _ this] have\n     \"ennreal (Beta (1 / 2) (real n / 2 + 1)) =\n        nn_integral lborel (\\<lambda>t. ennreal (t powr (-1 / 2) * (1 - t) powr (real n / 2) *\n                                indicator {0^2..1^2} t))\"\n    by (simp add: mult_ac ennreal_mult' ennreal_indicator)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal (x\\<^sup>2 powr - (1 / 2) * (1 - x\\<^sup>2) powr (real n / 2) * (2 * x) *\n                          indicator {0..1} x) \\<partial>lborel)\"\n    by (subst nn_integral_substitution[where g = \"\\<lambda>x. x ^ 2\" and g' = \"\\<lambda>x. 2 * x\"])\n       (auto intro!: derivative_eq_intros continuous_intros simp: set_borel_measurable_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. 2 * ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {0..1} x) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{0}\"])\n       (auto simp: indicator_def powr_minus powr_half_sqrt field_split_simps ennreal_mult')\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {0..1} x) \\<partial>lborel) +\n                    (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {0..1} x) \\<partial>lborel)\"\n    (is \"_ = ?I + _\") by (simp add: mult_2 nn_integral_add)\n  also have \"?I = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {-1..0} x) \\<partial>lborel)\"\n    by (subst nn_integral_real_affine[of _ \"-1\" 0])\n       (auto simp: indicator_def intro!: nn_integral_cong)\n  hence \"?I + ?I = \\<dots> + ?I\" by simp\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) *\n                    (indicator {-1..0} x + indicator{0..1} x)) \\<partial>lborel)\"\n    by (subst nn_integral_add [symmetric]) (auto simp: algebra_simps)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {-1..1} x) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{0}\"]) (auto simp: indicator_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal (indicator {-1..1} x * sqrt (1 - x\\<^sup>2) ^ n) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{1, -1}\"])\n       (auto simp: powr_half_sqrt [symmetric] indicator_def abs_square_le_1\n          abs_square_eq_1 powr_def exp_of_nat_mult [symmetric] emeasure_lborel_countable)\n  finally show ?thesis ..\nqed\n\nlemma real_sqrt_le_iff': \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> sqrt x \\<le> y \\<longleftrightarrow> x \\<le> y ^ 2\"\n  using real_le_lsqrt sqrt_le_D by blast\n\ntext \\<open>\n  Isabelle's type system makes it very difficult to do an induction over the dimension\n  of a Euclidean space type, because the type would change in the inductive step. To avoid\n  this problem, we instead formulate the problem in a more concrete way by unfolding the\n  definition of the Euclidean norm.\n\\<close>\nlemma emeasure_cball_aux:\n  assumes \"finite A\" \"r > 0\"\n  shows   \"emeasure (Pi\\<^sub>M A (\\<lambda>_. lborel))\n             ({f. sqrt (\\<Sum>i\\<in>A. (f i)\\<^sup>2) \\<le> r} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) =\n             ennreal (unit_ball_vol (real (card A)) * r ^ card A)\"\n  using assms\nproof (induction arbitrary: r)\n  case (empty r)\n  thus ?case\n    by (simp add: unit_ball_vol_def space_PiM)\nnext\n  case (insert i A r)\n  interpret product_sigma_finite \"\\<lambda>_. lborel\"\n    by standard\n  have \"emeasure (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))\n            ({f. sqrt (\\<Sum>i\\<in>insert i A. (f i)\\<^sup>2) \\<le> r} \\<inter> space (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))) =\n        nn_integral (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))\n          (indicator ({f. sqrt (\\<Sum>i\\<in>insert i A. (f i)\\<^sup>2) \\<le> r} \\<inter>\n          space (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))))\"\n    by (subst nn_integral_indicator) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ y. \\<integral>\\<^sup>+ x. indicator ({f. sqrt ((f i)\\<^sup>2 + (\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \\<le> r} \\<inter>\n                                space (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))) (x(i := y))\n                   \\<partial>Pi\\<^sub>M A (\\<lambda>_. lborel) \\<partial>lborel)\"\n    using insert.prems insert.hyps by (subst product_nn_integral_insert_rev) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). \\<integral>\\<^sup>+ x. indicator {-r..r} y * indicator ({f. sqrt ((\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \\<le>\n               sqrt (r ^ 2 - y ^ 2)} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) x \\<partial>Pi\\<^sub>M A (\\<lambda>_. lborel) \\<partial>lborel)\"\n  proof (intro nn_integral_cong, goal_cases)\n    case (1 y f)\n    have *: \"y \\<in> {-r..r}\" if \"y ^ 2 + c \\<le> r ^ 2\" \"c \\<ge> 0\" for c\n    proof -\n      have \"y ^ 2 \\<le> y ^ 2 + c\" using that by simp\n      also have \"\\<dots> \\<le> r ^ 2\" by fact\n      finally show ?thesis\n        using \\<open>r > 0\\<close> by (simp add: power2_le_iff_abs_le abs_if split: if_splits)\n    qed\n    have \"(\\<Sum>x\\<in>A. (if x = i then y else f x)\\<^sup>2) = (\\<Sum>x\\<in>A. (f x)\\<^sup>2)\"\n      using insert.hyps by (intro sum.cong) auto\n    thus ?case using 1 \\<open>r > 0\\<close>\n      by (auto simp: sum_nonneg real_sqrt_le_iff' indicator_def PiE_def space_PiM dest!: *)\n  qed\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * (\\<integral>\\<^sup>+ x. indicator ({f. sqrt ((\\<Sum>i\\<in>A. (f i)\\<^sup>2))\n                                   \\<le> sqrt (r ^ 2 - y ^ 2)} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) x\n                  \\<partial>Pi\\<^sub>M A (\\<lambda>_. lborel)) \\<partial>lborel)\" by (subst nn_integral_cmult) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * emeasure (PiM A (\\<lambda>_. lborel))\n      ({f. sqrt ((\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \\<le> sqrt (r ^ 2 - y ^ 2)} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) \\<partial>lborel)\"\n    using \\<open>finite A\\<close> by (intro nn_integral_cong, subst nn_integral_indicator) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * ennreal (unit_ball_vol (real (card A)) *\n                                  (sqrt (r ^ 2 - y ^ 2)) ^ card A) \\<partial>lborel)\"\n  proof (intro nn_integral_cong_AE, goal_cases)\n    case 1\n    have \"AE y in lborel. y \\<notin> {-r,r}\"\n      by (intro AE_not_in countable_imp_null_set_lborel) auto\n    thus ?case\n    proof eventually_elim\n      case (elim y)\n      show ?case\n      proof (cases \"y \\<in> {-r<..<r}\")\n        case True\n        hence \"y\\<^sup>2 < r\\<^sup>2\" by (subst real_sqrt_less_iff [symmetric]) auto\n        thus ?thesis by (subst insert.IH) (auto)\n      qed (insert elim, auto)\n    qed\n  qed\n  also have \"\\<dots> = ennreal (unit_ball_vol (real (card A))) *\n                    (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * (sqrt (r ^ 2 - y ^ 2)) ^ card A \\<partial>lborel)\"\n    by (subst nn_integral_cmult [symmetric])\n       (auto simp: mult_ac ennreal_mult' [symmetric] indicator_def intro!: nn_integral_cong)\n  also have \"(\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * (sqrt (r ^ 2 - y ^ 2)) ^ card A \\<partial>lborel) =\n               (\\<integral>\\<^sup>+ (y::real). r ^ card A * indicator {-1..1} y * (sqrt (1 - y ^ 2)) ^ card A\n               \\<partial>(distr lborel borel ((*) (1/r))))\" using \\<open>r > 0\\<close>\n    by (subst nn_integral_distr)\n       (auto simp: indicator_def field_simps real_sqrt_divide intro!: nn_integral_cong)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal (r ^ Suc (card A)) *\n               (indicator {- 1..1} x * sqrt (1 - x\\<^sup>2) ^ card A) \\<partial>lborel)\" using \\<open>r > 0\\<close>\n    by (subst lborel_distr_mult) (auto simp: nn_integral_density ennreal_mult' [symmetric] mult_ac)\n  also have \"\\<dots> = ennreal (r ^ Suc (card A)) * (\\<integral>\\<^sup>+ x. indicator {- 1..1} x *\n                    sqrt (1 - x\\<^sup>2) ^ card A \\<partial>lborel)\"\n    by (subst nn_integral_cmult) auto\n  also note emeasure_cball_aux_integral\n  also have \"ennreal (unit_ball_vol (real (card A))) * (ennreal (r ^ Suc (card A)) *\n                 ennreal (Beta (1/2) (card A / 2 + 1))) =\n               ennreal (unit_ball_vol (card A) * Beta (1/2) (card A / 2 + 1) * r ^ Suc (card A))\"\n    using \\<open>r > 0\\<close> by (simp add: ennreal_mult' [symmetric] mult_ac)\n  also have \"unit_ball_vol (card A) * Beta (1/2) (card A / 2 + 1) = unit_ball_vol (Suc (card A))\"\n    by (auto simp: unit_ball_vol_def Beta_def Gamma_eq_zero_iff field_simps\n          Gamma_one_half_real powr_half_sqrt [symmetric] powr_add [symmetric])\n  also have \"Suc (card A) = card (insert i A)\" using insert.hyps by simp\n  finally show ?case .\nqed\n\n\ntext \\<open>\n  We now get the main theorem very easily by just applying the above lemma.\n\\<close>\ncontext\n  fixes c :: \"'a :: euclidean_space\" and r :: real\n  assumes r: \"r \\<ge> 0\"\nbegin\n\ntheorem\\<^marker>\\<open>tag unimportant\\<close> emeasure_cball:\n  \"emeasure lborel (cball c r) = ennreal (unit_ball_vol (DIM('a)) * r ^ DIM('a))\"\nproof (cases \"r = 0\")\n  case False\n  with r have r: \"r > 0\" by simp\n  have \"(lborel :: 'a measure) =\n          distr (Pi\\<^sub>M Basis (\\<lambda>_. lborel)) borel (\\<lambda>f. \\<Sum>b\\<in>Basis. f b *\\<^sub>R b)\"\n    by (rule lborel_eq)\n  also have \"emeasure \\<dots> (cball 0 r) =\n               emeasure (Pi\\<^sub>M Basis (\\<lambda>_. lborel))\n               ({y. dist 0 (\\<Sum>b\\<in>Basis. y b *\\<^sub>R b :: 'a) \\<le> r} \\<inter> space (Pi\\<^sub>M Basis (\\<lambda>_. lborel)))\"\n    by (subst emeasure_distr) (auto simp: cball_def)\n  also have \"{f. dist 0 (\\<Sum>b\\<in>Basis. f b *\\<^sub>R b :: 'a) \\<le> r} = {f. sqrt (\\<Sum>i\\<in>Basis. (f i)\\<^sup>2) \\<le> r}\"\n    by (subst euclidean_dist_l2) (auto simp: L2_set_def)\n  also have \"emeasure (Pi\\<^sub>M Basis (\\<lambda>_. lborel)) (\\<dots> \\<inter> space (Pi\\<^sub>M Basis (\\<lambda>_. lborel))) =\n               ennreal (unit_ball_vol (real DIM('a)) * r ^ DIM('a))\"\n    using r by (subst emeasure_cball_aux) simp_all\n  also have \"emeasure lborel (cball 0 r :: 'a set) =\n               emeasure (distr lborel borel (\\<lambda>x. c + x)) (cball c r)\"\n    by (subst emeasure_distr) (auto simp: cball_def dist_norm norm_minus_commute)\n  also have \"distr lborel borel (\\<lambda>x. c + x) = lborel\"\n    using lborel_affine[of 1 c] by (simp add: density_1)\n  finally show ?thesis .\nqed auto\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_cball:\n  \"content (cball c r) = unit_ball_vol (DIM('a)) * r ^ DIM('a)\"\n  by (simp add: measure_def emeasure_cball r)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> emeasure_ball:\n  \"emeasure lborel (ball c r) = ennreal (unit_ball_vol (DIM('a)) * r ^ DIM('a))\"\nproof -\n  from negligible_sphere[of c r] have \"sphere c r \\<in> null_sets lborel\"\n    by (auto simp: null_sets_completion_iff negligible_iff_null_sets negligible_convex_frontier)\n  hence \"emeasure lborel (ball c r \\<union> sphere c r :: 'a set) = emeasure lborel (ball c r :: 'a set)\"\n    by (intro emeasure_Un_null_set) auto\n  also have \"ball c r \\<union> sphere c r = (cball c r :: 'a set)\" by auto\n  also have \"emeasure lborel \\<dots> = ennreal (unit_ball_vol (real DIM('a)) * r ^ DIM('a))\"\n    by (rule emeasure_cball)\n  finally show ?thesis ..\nqed\n\ncorollary\\<^marker>\\<open>tag important\\<close> content_ball:\n  \"content (ball c r) = unit_ball_vol (DIM('a)) * r ^ DIM('a)\"\n  by (simp add: measure_def r emeasure_ball)\n\nend\n\n\ntext \\<open>\n  Lastly, we now prove some nicer explicit formulas for the volume of the unit balls in\n  the cases of even and odd integer dimensions.\n\\<close>\nlemma unit_ball_vol_even:\n  \"unit_ball_vol (real (2 * n)) = pi ^ n / fact n\"\n  by (simp add: unit_ball_vol_def add_ac powr_realpow Gamma_fact)\n\nlemma unit_ball_vol_odd':\n        \"unit_ball_vol (real (2 * n + 1)) = pi ^ n / pochhammer (1 / 2) (Suc n)\"\n  and unit_ball_vol_odd:\n        \"unit_ball_vol (real (2 * n + 1)) =\n           (2 ^ (2 * Suc n) * fact (Suc n)) / fact (2 * Suc n) * pi ^ n\"\nproof -\n  have \"unit_ball_vol (real (2 * n + 1)) =\n          pi powr (real n + 1 / 2) / Gamma (1 / 2 + real (Suc n))\"\n    by (simp add: unit_ball_vol_def field_simps)\n  also have \"pochhammer (1 / 2) (Suc n) = Gamma (1 / 2 + real (Suc n)) / Gamma (1 / 2)\"\n    by (intro pochhammer_Gamma) auto\n  hence \"Gamma (1 / 2 + real (Suc n)) = sqrt pi * pochhammer (1 / 2) (Suc n)\"\n    by (simp add: Gamma_one_half_real)\n  also have \"pi powr (real n + 1 / 2) / \\<dots> = pi ^ n / pochhammer (1 / 2) (Suc n)\"\n    by (simp add: powr_add powr_half_sqrt powr_realpow)\n  finally show \"unit_ball_vol (real (2 * n + 1)) = \\<dots>\" .\n  also have \"pochhammer (1 / 2 :: real) (Suc n) =\n               fact (2 * Suc n) / (2 ^ (2 * Suc n) * fact (Suc n))\"\n    using fact_double[of \"Suc n\", where ?'a = real] by (simp add: divide_simps mult_ac)\n  also have \"pi ^n / \\<dots> = (2 ^ (2 * Suc n) * fact (Suc n)) / fact (2 * Suc n) * pi ^ n\"\n    by simp\n  finally show \"unit_ball_vol (real (2 * n + 1)) = \\<dots>\" .\nqed\n\nlemma unit_ball_vol_numeral:\n  \"unit_ball_vol (numeral (Num.Bit0 n)) = pi ^ numeral n / fact (numeral n)\" (is ?th1)\n  \"unit_ball_vol (numeral (Num.Bit1 n)) = 2 ^ (2 * Suc (numeral n)) * fact (Suc (numeral n)) /\n    fact (2 * Suc (numeral n)) * pi ^ numeral n\" (is ?th2)\nproof -\n  have \"numeral (Num.Bit0 n) = (2 * numeral n :: nat)\"\n    by (simp only: numeral_Bit0 mult_2 ring_distribs)\n  also have \"unit_ball_vol \\<dots> = pi ^ numeral n / fact (numeral n)\"\n    by (rule unit_ball_vol_even)\n  finally show ?th1 by simp\nnext\n  have \"numeral (Num.Bit1 n) = (2 * numeral n + 1 :: nat)\"\n    by (simp only: numeral_Bit1 mult_2)\n  also have \"unit_ball_vol \\<dots> = 2 ^ (2 * Suc (numeral n)) * fact (Suc (numeral n)) /\n                                  fact (2 * Suc (numeral n)) * pi ^ numeral n\"\n    by (rule unit_ball_vol_odd)\n  finally show ?th2 by simp\nqed\n\nlemmas eval_unit_ball_vol = unit_ball_vol_numeral fact_numeral\n\n\ntext \\<open>\n  Just for fun, we compute the volume of unit balls for a few dimensions.\n\\<close>\nlemma unit_ball_vol_0 [simp]: \"unit_ball_vol 0 = 1\"\n  using unit_ball_vol_even[of 0] by simp\n\nlemma unit_ball_vol_1 [simp]: \"unit_ball_vol 1 = 2\"\n  using unit_ball_vol_odd[of 0] by simp\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close>\n          unit_ball_vol_2: \"unit_ball_vol 2 = pi\"\n      and unit_ball_vol_3: \"unit_ball_vol 3 = 4 / 3 * pi\"\n      and unit_ball_vol_4: \"unit_ball_vol 4 = pi\\<^sup>2 / 2\"\n      and unit_ball_vol_5: \"unit_ball_vol 5 = 8 / 15 * pi\\<^sup>2\"\n  by (simp_all add: eval_unit_ball_vol)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> circle_area:\n  \"r \\<ge> 0 \\<Longrightarrow> content (ball c r :: (real ^ 2) set) = r ^ 2 * pi\"\n  by (simp add: content_ball unit_ball_vol_2)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> sphere_volume:\n  \"r \\<ge> 0 \\<Longrightarrow> content (ball c r :: (real ^ 3) set) = 4 / 3 * r ^ 3 * pi\"\n  by (simp add: content_ball unit_ball_vol_3)\n\ntext \\<open>\n  Useful equivalent forms\n\\<close>\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_ball_eq_0_iff [simp]: \"content (ball c r) = 0 \\<longleftrightarrow> r \\<le> 0\"\nproof -\n  have \"r > 0 \\<Longrightarrow> content (ball c r) > 0\"\n    by (simp add: content_ball unit_ball_vol_def)\n  then show ?thesis\n    by (fastforce simp: ball_empty)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_ball_gt_0_iff [simp]: \"0 < content (ball z r) \\<longleftrightarrow> 0 < r\"\n  by (auto simp: zero_less_measure_iff)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_cball_eq_0_iff [simp]: \"content (cball c r) = 0 \\<longleftrightarrow> r \\<le> 0\"\nproof (cases \"r = 0\")\n  case False\n  moreover have \"r > 0 \\<Longrightarrow> content (cball c r) > 0\"\n    by (simp add: content_cball unit_ball_vol_def)\n  ultimately show ?thesis\n    by fastforce\nqed auto\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_cball_gt_0_iff [simp]: \"0 < content (cball z r) \\<longleftrightarrow> 0 < r\"\n  by (auto simp: zero_less_measure_iff)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/Ball_Volume.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8774767810736692, "lm_q1q2_score": 0.7938098350254652}}
{"text": "(*  Title:      HOL/Decision_Procs/Polynomial_List.thy\n    Author:     Amine Chaieb\n*)\n\nsection \\<open>Univariate Polynomials as lists\\<close>\n\ntheory Polynomial_List\nimports Complex_Main\nbegin\n\ntext \\<open>Application of polynomial as a function.\\<close>\n\nprimrec (in semiring_0) poly :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  poly_Nil: \"poly [] x = 0\"\n| poly_Cons: \"poly (h # t) x = h + x * poly t x\"\n\n\nsubsection \\<open>Arithmetic Operations on Polynomials\\<close>\n\ntext \\<open>Addition\\<close>\nprimrec (in semiring_0) padd :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixl \"+++\" 65)\nwhere\n  padd_Nil: \"[] +++ l2 = l2\"\n| padd_Cons: \"(h # t) +++ l2 = (if l2 = [] then h # t else (h + hd l2) # (t +++ tl l2))\"\n\ntext \\<open>Multiplication by a constant\\<close>\nprimrec (in semiring_0) cmult :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixl \"%*\" 70) where\n  cmult_Nil: \"c %* [] = []\"\n| cmult_Cons: \"c %* (h#t) = (c * h)#(c %* t)\"\n\ntext \\<open>Multiplication by a polynomial\\<close>\nprimrec (in semiring_0) pmult :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixl \"***\" 70)\nwhere\n  pmult_Nil: \"[] *** l2 = []\"\n| pmult_Cons: \"(h # t) *** l2 = (if t = [] then h %* l2 else (h %* l2) +++ (0 # (t *** l2)))\"\n\ntext \\<open>Repeated multiplication by a polynomial\\<close>\nprimrec (in semiring_0) mulexp :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a  list \\<Rightarrow> 'a list\"\nwhere\n  mulexp_zero: \"mulexp 0 p q = q\"\n| mulexp_Suc: \"mulexp (Suc n) p q = p *** mulexp n p q\"\n\ntext \\<open>Exponential\\<close>\nprimrec (in semiring_1) pexp :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\"  (infixl \"%^\" 80)\nwhere\n  pexp_0: \"p %^ 0 = [1]\"\n| pexp_Suc: \"p %^ (Suc n) = p *** (p %^ n)\"\n\ntext \\<open>Quotient related value of dividing a polynomial by x + a.\n  Useful for divisor properties in inductive proofs.\\<close>\nprimrec (in field) \"pquot\" :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\nwhere\n  pquot_Nil: \"pquot [] a = []\"\n| pquot_Cons: \"pquot (h # t) a =\n    (if t = [] then [h] else (inverse a * (h - hd( pquot t a))) # pquot t a)\"\n\ntext \\<open>Normalization of polynomials (remove extra 0 coeff).\\<close>\nprimrec (in semiring_0) pnormalize :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  pnormalize_Nil: \"pnormalize [] = []\"\n| pnormalize_Cons: \"pnormalize (h # p) =\n    (if pnormalize p = [] then (if h = 0 then [] else [h]) else h # pnormalize p)\"\n\ndefinition (in semiring_0) \"pnormal p \\<longleftrightarrow> pnormalize p = p \\<and> p \\<noteq> []\"\ndefinition (in semiring_0) \"nonconstant p \\<longleftrightarrow> pnormal p \\<and> (\\<forall>x. p \\<noteq> [x])\"\n\ntext \\<open>Other definitions.\\<close>\n\ndefinition (in ring_1) poly_minus :: \"'a list \\<Rightarrow> 'a list\" (\"-- _\" [80] 80)\n  where \"-- p = (- 1) %* p\"\n\ndefinition (in semiring_0) divides :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"  (infixl \"divides\" 70)\n  where \"p1 divides p2 \\<longleftrightarrow> (\\<exists>q. poly p2 = poly(p1 *** q))\"\n\nlemma (in semiring_0) dividesI: \"poly p2 = poly (p1 *** q) \\<Longrightarrow> p1 divides p2\"\n  by (auto simp add: divides_def)\n\nlemma (in semiring_0) dividesE:\n  assumes \"p1 divides p2\"\n  obtains q where \"poly p2 = poly (p1 *** q)\"\n  using assms by (auto simp add: divides_def)\n\n\\<comment> \\<open>order of a polynomial\\<close>\ndefinition (in ring_1) order :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n  where \"order a p = (SOME n. ([-a, 1] %^ n) divides p \\<and> \\<not> (([-a, 1] %^ (Suc n)) divides p))\"\n\n\\<comment> \\<open>degree of a polynomial\\<close>\ndefinition (in semiring_0) degree :: \"'a list \\<Rightarrow> nat\"\n  where \"degree p = length (pnormalize p) - 1\"\n\n\\<comment> \\<open>squarefree polynomials --- NB with respect to real roots only\\<close>\ndefinition (in ring_1) rsquarefree :: \"'a list \\<Rightarrow> bool\"\n  where \"rsquarefree p \\<longleftrightarrow> poly p \\<noteq> poly [] \\<and> (\\<forall>a. order a p = 0 \\<or> order a p = 1)\"\n\ncontext semiring_0\nbegin\n\nlemma padd_Nil2[simp]: \"p +++ [] = p\"\n  by (induct p) auto\n\nlemma padd_Cons_Cons: \"(h1 # p1) +++ (h2 # p2) = (h1 + h2) # (p1 +++ p2)\"\n  by auto\n\nlemma pminus_Nil: \"-- [] = []\"\n  by (simp add: poly_minus_def)\n\nlemma pmult_singleton: \"[h1] *** p1 = h1 %* p1\" by simp\n\nend\n\nlemma (in semiring_1) poly_ident_mult[simp]: \"1 %* t = t\"\n  by (induct t) auto\n\nlemma (in semiring_0) poly_simple_add_Cons[simp]: \"[a] +++ (0 # t) = a # t\"\n  by simp\n\n\ntext \\<open>Handy general properties.\\<close>\n\nlemma (in comm_semiring_0) padd_commut: \"b +++ a = a +++ b\"\nproof (induct b arbitrary: a)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons b bs a)\n  then show ?case\n    by (cases a) (simp_all add: add.commute)\nqed\n\nlemma (in comm_semiring_0) padd_assoc: \"(a +++ b) +++ c = a +++ (b +++ c)\"\nproof (induct a arbitrary: b c)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case Cons\n  then show ?case\n    by (cases b) (simp_all add: ac_simps)\nqed\n\nlemma (in semiring_0) poly_cmult_distr: \"a %* (p +++ q) = a %* p +++ a %* q\"\nproof (induct p arbitrary: q)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case Cons\n  then show ?case\n    by (cases q) (simp_all add: distrib_left)\nqed\n\nlemma (in ring_1) pmult_by_x[simp]: \"[0, 1] *** t = 0 # t\"\nproof (induct t)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a t)\n  then show ?case\n    by (cases t) (auto simp add: padd_commut)\nqed\n\ntext \\<open>Properties of evaluation of polynomials.\\<close>\n\nlemma (in semiring_0) poly_add: \"poly (p1 +++ p2) x = poly p1 x + poly p2 x\"\nproof (induct p1 arbitrary: p2)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a as p2)\n  then show ?case\n    by (cases p2) (simp_all add: ac_simps distrib_left)\nqed\n\nlemma (in comm_semiring_0) poly_cmult: \"poly (c %* p) x = c * poly p x\"\nproof (induct p)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case Cons\n  then show ?case\n    by (cases \"x = zero\") (auto simp add: distrib_left ac_simps)\nqed\n\nlemma (in comm_semiring_0) poly_cmult_map: \"poly (map (op * c) p) x = c * poly p x\"\n  by (induct p) (auto simp add: distrib_left ac_simps)\n\nlemma (in comm_ring_1) poly_minus: \"poly (-- p) x = - (poly p x)\"\n  by (simp add: poly_minus_def) (auto simp add: poly_cmult)\n\nlemma (in comm_semiring_0) poly_mult: \"poly (p1 *** p2) x = poly p1 x * poly p2 x\"\nproof (induct p1 arbitrary: p2)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a as)\n  then show ?case\n    by (cases as) (simp_all add: poly_cmult poly_add distrib_right distrib_left ac_simps)\nqed\n\nclass idom_char_0 = idom + ring_char_0\n\nsubclass (in field_char_0) idom_char_0 ..\n\nlemma (in comm_ring_1) poly_exp: \"poly (p %^ n) x = (poly p x) ^ n\"\n  by (induct n) (auto simp add: poly_cmult poly_mult)\n\n\ntext \\<open>More Polynomial Evaluation lemmas.\\<close>\n\nlemma (in semiring_0) poly_add_rzero[simp]: \"poly (a +++ []) x = poly a x\"\n  by simp\n\nlemma (in comm_semiring_0) poly_mult_assoc: \"poly ((a *** b) *** c) x = poly (a *** (b *** c)) x\"\n  by (simp add: poly_mult mult.assoc)\n\nlemma (in semiring_0) poly_mult_Nil2[simp]: \"poly (p *** []) x = 0\"\n  by (induct p) auto\n\nlemma (in comm_semiring_1) poly_exp_add: \"poly (p %^ (n + d)) x = poly (p %^ n *** p %^ d) x\"\n  by (induct n) (auto simp add: poly_mult mult.assoc)\n\n\nsubsection \\<open>Key Property: if @{term \"f a = 0\"} then @{term \"(x - a)\"} divides @{term \"p(x)\"}.\\<close>\n\nlemma (in comm_ring_1) lemma_poly_linear_rem: \"\\<exists>q r. h#t = [r] +++ [-a, 1] *** q\"\nproof (induct t arbitrary: h)\n  case Nil\n  have \"[h] = [h] +++ [- a, 1] *** []\" by simp\n  then show ?case by blast\nnext\n  case (Cons  x xs)\n  have \"\\<exists>q r. h # x # xs = [r] +++ [-a, 1] *** q\"\n  proof -\n    from Cons obtain q r where qr: \"x # xs = [r] +++ [- a, 1] *** q\"\n      by blast\n    have \"h # x # xs = [a * r + h] +++ [-a, 1] *** (r # q)\"\n      using qr by (cases q) (simp_all add: algebra_simps)\n    then show ?thesis by blast\n  qed\n  then show ?case by blast\nqed\n\nlemma (in comm_ring_1) poly_linear_rem: \"\\<exists>q r. h#t = [r] +++ [-a, 1] *** q\"\n  using lemma_poly_linear_rem [where t = t and a = a] by auto\n\nlemma (in comm_ring_1) poly_linear_divides: \"poly p a = 0 \\<longleftrightarrow> p = [] \\<or> (\\<exists>q. p = [-a, 1] *** q)\"\nproof (cases p)\n  case Nil\n  then show ?thesis by simp\nnext\n  case (Cons x xs)\n  have \"poly p a = 0\" if \"p = [-a, 1] *** q\" for q\n    using that by (simp add: poly_add poly_cmult)\n  moreover\n  have \"\\<exists>q. p = [- a, 1] *** q\" if p0: \"poly p a = 0\"\n  proof -\n    from poly_linear_rem[of x xs a] obtain q r where qr: \"x#xs = [r] +++ [- a, 1] *** q\"\n      by blast\n    have \"r = 0\"\n      using p0 by (simp only: Cons qr poly_mult poly_add) simp\n    with Cons qr show ?thesis\n      apply -\n      apply (rule exI[where x = q])\n      apply auto\n      apply (cases q)\n      apply auto\n      done\n  qed\n  ultimately show ?thesis using Cons by blast\nqed\n\nlemma (in semiring_0) lemma_poly_length_mult[simp]:\n  \"length (k %* p +++  (h # (a %* p))) = Suc (length p)\"\n  by (induct p arbitrary: h k a) auto\n\nlemma (in semiring_0) lemma_poly_length_mult2[simp]:\n  \"length (k %* p +++  (h # p)) = Suc (length p)\"\n  by (induct p arbitrary: h k) auto\n\nlemma (in ring_1) poly_length_mult[simp]: \"length([-a,1] *** q) = Suc (length q)\"\n  by auto\n\n\nsubsection \\<open>Polynomial length\\<close>\n\nlemma (in semiring_0) poly_cmult_length[simp]: \"length (a %* p) = length p\"\n  by (induct p) auto\n\nlemma (in semiring_0) poly_add_length: \"length (p1 +++ p2) = max (length p1) (length p2)\"\n  by (induct p1 arbitrary: p2) auto\n\nlemma (in semiring_0) poly_root_mult_length[simp]: \"length ([a, b] *** p) = Suc (length p)\"\n  by (simp add: poly_add_length)\n\nlemma (in idom) poly_mult_not_eq_poly_Nil[simp]:\n  \"poly (p *** q) x \\<noteq> poly [] x \\<longleftrightarrow> poly p x \\<noteq> poly [] x \\<and> poly q x \\<noteq> poly [] x\"\n  by (auto simp add: poly_mult)\n\nlemma (in idom) poly_mult_eq_zero_disj: \"poly (p *** q) x = 0 \\<longleftrightarrow> poly p x = 0 \\<or> poly q x = 0\"\n  by (auto simp add: poly_mult)\n\n\ntext \\<open>Normalisation Properties.\\<close>\n\nlemma (in semiring_0) poly_normalized_nil: \"pnormalize p = [] \\<longrightarrow> poly p x = 0\"\n  by (induct p) auto\n\ntext \\<open>A nontrivial polynomial of degree n has no more than n roots.\\<close>\nlemma (in idom) poly_roots_index_lemma:\n  assumes \"poly p x \\<noteq> poly [] x\"\n    and \"length p = n\"\n  shows \"\\<exists>i. \\<forall>x. poly p x = 0 \\<longrightarrow> (\\<exists>m\\<le>n. x = i m)\"\n  using assms\nproof (induct n arbitrary: p x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have False if C: \"\\<And>i. \\<exists>x. poly p x = 0 \\<and> (\\<forall>m\\<le>Suc n. x \\<noteq> i m)\"\n  proof -\n    from Suc.prems have p0: \"poly p x \\<noteq> 0\" \"p \\<noteq> []\"\n      by auto\n    from p0(1)[unfolded poly_linear_divides[of p x]]\n    have \"\\<forall>q. p \\<noteq> [- x, 1] *** q\"\n      by blast\n    from C obtain a where a: \"poly p a = 0\"\n      by blast\n    from a[unfolded poly_linear_divides[of p a]] p0(2) obtain q where q: \"p = [-a, 1] *** q\"\n      by blast\n    have lg: \"length q = n\"\n      using q Suc.prems(2) by simp\n    from q p0 have qx: \"poly q x \\<noteq> poly [] x\"\n      by (auto simp add: poly_mult poly_add poly_cmult)\n    from Suc.hyps[OF qx lg] obtain i where i: \"\\<And>x. poly q x = 0 \\<longrightarrow> (\\<exists>m\\<le>n. x = i m)\"\n      by blast\n    let ?i = \"\\<lambda>m. if m = Suc n then a else i m\"\n    from C[of ?i] obtain y where y: \"poly p y = 0\" \"\\<forall>m\\<le> Suc n. y \\<noteq> ?i m\"\n      by blast\n    from y have \"y = a \\<or> poly q y = 0\"\n      by (simp only: q poly_mult_eq_zero_disj poly_add) (simp add: algebra_simps)\n    with i[of y] y(1) y(2) show ?thesis\n      apply auto\n      apply (erule_tac x = \"m\" in allE)\n      apply auto\n      done\n  qed\n  then show ?case by blast\nqed\n\n\nlemma (in idom) poly_roots_index_length:\n  \"poly p x \\<noteq> poly [] x \\<Longrightarrow> \\<exists>i. \\<forall>x. poly p x = 0 \\<longrightarrow> (\\<exists>n. n \\<le> length p \\<and> x = i n)\"\n  by (blast intro: poly_roots_index_lemma)\n\nlemma (in idom) poly_roots_finite_lemma1:\n  \"poly p x \\<noteq> poly [] x \\<Longrightarrow> \\<exists>N i. \\<forall>x. poly p x = 0 \\<longrightarrow> (\\<exists>n::nat. n < N \\<and> x = i n)\"\n  apply (drule poly_roots_index_length)\n  apply safe\n  apply (rule_tac x = \"Suc (length p)\" in exI)\n  apply (rule_tac x = i in exI)\n  apply (simp add: less_Suc_eq_le)\n  done\n\nlemma (in idom) idom_finite_lemma:\n  assumes \"\\<forall>x. P x \\<longrightarrow> (\\<exists>n. n < length j \\<and> x = j!n)\"\n  shows \"finite {x. P x}\"\nproof -\n  from assms have \"{x. P x} \\<subseteq> set j\"\n    by auto\n  then show ?thesis\n    using finite_subset by auto\nqed\n\nlemma (in idom) poly_roots_finite_lemma2:\n  \"poly p x \\<noteq> poly [] x \\<Longrightarrow> \\<exists>i. \\<forall>x. poly p x = 0 \\<longrightarrow> x \\<in> set i\"\n  apply (drule poly_roots_index_length)\n  apply safe\n  apply (rule_tac x = \"map (\\<lambda>n. i n) [0 ..< Suc (length p)]\" in exI)\n  apply (auto simp add: image_iff)\n  apply (erule_tac x=\"x\" in allE)\n  apply clarsimp\n  apply (case_tac \"n = length p\")\n  apply (auto simp add: order_le_less)\n  done\n\nlemma (in ring_char_0) UNIV_ring_char_0_infinte: \"\\<not> finite (UNIV :: 'a set)\"\nproof\n  assume F: \"finite (UNIV :: 'a set)\"\n  have \"finite (UNIV :: nat set)\"\n  proof (rule finite_imageD)\n    have \"of_nat ` UNIV \\<subseteq> UNIV\"\n      by simp\n    then show \"finite (of_nat ` UNIV :: 'a set)\"\n      using F by (rule finite_subset)\n    show \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n      by (simp add: inj_on_def)\n  qed\n  with infinite_UNIV_nat show False ..\nqed\n\nlemma (in idom_char_0) poly_roots_finite: \"poly p \\<noteq> poly [] \\<longleftrightarrow> finite {x. poly p x = 0}\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n    using that\n    apply -\n    apply (erule contrapos_np)\n    apply (rule ext)\n    apply (rule ccontr)\n    apply (clarify dest!: poly_roots_finite_lemma2)\n    using finite_subset\n  proof -\n    fix x i\n    assume F: \"\\<not> finite {x. poly p x = 0}\"\n      and P: \"\\<forall>x. poly p x = 0 \\<longrightarrow> x \\<in> set i\"\n    from P have \"{x. poly p x = 0} \\<subseteq> set i\"\n      by auto\n    with finite_subset F show False\n      by auto\n  qed\n  show ?lhs if ?rhs\n    using UNIV_ring_char_0_infinte that by auto\nqed\n\n\ntext \\<open>Entirety and Cancellation for polynomials\\<close>\n\nlemma (in idom_char_0) poly_entire_lemma2:\n  assumes p0: \"poly p \\<noteq> poly []\"\n    and q0: \"poly q \\<noteq> poly []\"\n  shows \"poly (p***q) \\<noteq> poly []\"\nproof -\n  let ?S = \"\\<lambda>p. {x. poly p x = 0}\"\n  have \"?S (p *** q) = ?S p \\<union> ?S q\"\n    by (auto simp add: poly_mult)\n  with p0 q0 show ?thesis\n    unfolding poly_roots_finite by auto\nqed\n\nlemma (in idom_char_0) poly_entire:\n  \"poly (p *** q) = poly [] \\<longleftrightarrow> poly p = poly [] \\<or> poly q = poly []\"\n  using poly_entire_lemma2[of p q]\n  by (auto simp add: fun_eq_iff poly_mult)\n\nlemma (in idom_char_0) poly_entire_neg:\n  \"poly (p *** q) \\<noteq> poly [] \\<longleftrightarrow> poly p \\<noteq> poly [] \\<and> poly q \\<noteq> poly []\"\n  by (simp add: poly_entire)\n\nlemma (in comm_ring_1) poly_add_minus_zero_iff:\n  \"poly (p +++ -- q) = poly [] \\<longleftrightarrow> poly p = poly q\"\n  by (auto simp add: algebra_simps poly_add poly_minus_def fun_eq_iff poly_cmult)\n\nlemma (in comm_ring_1) poly_add_minus_mult_eq:\n  \"poly (p *** q +++ --(p *** r)) = poly (p *** (q +++ -- r))\"\n  by (auto simp add: poly_add poly_minus_def fun_eq_iff poly_mult poly_cmult algebra_simps)\n\nsubclass (in idom_char_0) comm_ring_1 ..\n\nlemma (in idom_char_0) poly_mult_left_cancel:\n  \"poly (p *** q) = poly (p *** r) \\<longleftrightarrow> poly p = poly [] \\<or> poly q = poly r\"\nproof -\n  have \"poly (p *** q) = poly (p *** r) \\<longleftrightarrow> poly (p *** q +++ -- (p *** r)) = poly []\"\n    by (simp only: poly_add_minus_zero_iff)\n  also have \"\\<dots> \\<longleftrightarrow> poly p = poly [] \\<or> poly q = poly r\"\n    by (auto intro: simp add: poly_add_minus_mult_eq poly_entire poly_add_minus_zero_iff)\n  finally show ?thesis .\nqed\n\nlemma (in idom) poly_exp_eq_zero[simp]: \"poly (p %^ n) = poly [] \\<longleftrightarrow> poly p = poly [] \\<and> n \\<noteq> 0\"\n  apply (simp only: fun_eq_iff add: HOL.all_simps [symmetric])\n  apply (rule arg_cong [where f = All])\n  apply (rule ext)\n  apply (induct n)\n  apply (auto simp add: poly_exp poly_mult)\n  done\n\nlemma (in comm_ring_1) poly_prime_eq_zero[simp]: \"poly [a, 1] \\<noteq> poly []\"\n  apply (simp add: fun_eq_iff)\n  apply (rule_tac x = \"minus one a\" in exI)\n  apply (simp add: add.commute [of a])\n  done\n\nlemma (in idom) poly_exp_prime_eq_zero: \"poly ([a, 1] %^ n) \\<noteq> poly []\"\n  by auto\n\n\ntext \\<open>A more constructive notion of polynomials being trivial.\\<close>\n\nlemma (in idom_char_0) poly_zero_lemma': \"poly (h # t) = poly [] \\<Longrightarrow> h = 0 \\<and> poly t = poly []\"\n  apply (simp add: fun_eq_iff)\n  apply (case_tac \"h = zero\")\n  apply (drule_tac [2] x = zero in spec)\n  apply auto\n  apply (cases \"poly t = poly []\")\n  apply simp\nproof -\n  fix x\n  assume H: \"\\<forall>x. x = 0 \\<or> poly t x = 0\"\n  assume pnz: \"poly t \\<noteq> poly []\"\n  let ?S = \"{x. poly t x = 0}\"\n  from H have \"\\<forall>x. x \\<noteq> 0 \\<longrightarrow> poly t x = 0\"\n    by blast\n  then have th: \"?S \\<supseteq> UNIV - {0}\"\n    by auto\n  from poly_roots_finite pnz have th': \"finite ?S\"\n    by blast\n  from finite_subset[OF th th'] UNIV_ring_char_0_infinte show \"poly t x = 0\"\n    by simp\nqed\n\nlemma (in idom_char_0) poly_zero: \"poly p = poly [] \\<longleftrightarrow> (\\<forall>c \\<in> set p. c = 0)\"\nproof (induct p)\n  case Nil\n  then show ?case by simp\nnext\n  case Cons\n  show ?case\n    apply (rule iffI)\n    apply (drule poly_zero_lemma')\n    using Cons\n    apply auto\n    done\nqed\n\nlemma (in idom_char_0) poly_0: \"\\<forall>c \\<in> set p. c = 0 \\<Longrightarrow> poly p x = 0\"\n  unfolding poly_zero[symmetric] by simp\n\n\ntext \\<open>Basics of divisibility.\\<close>\n\nlemma (in idom) poly_primes: \"[a, 1] divides (p *** q) \\<longleftrightarrow> [a, 1] divides p \\<or> [a, 1] divides q\"\n  apply (auto simp add: divides_def fun_eq_iff poly_mult poly_add poly_cmult distrib_right [symmetric])\n  apply (drule_tac x = \"uminus a\" in spec)\n  apply (simp add: poly_linear_divides poly_add poly_cmult distrib_right [symmetric])\n  apply (cases \"p = []\")\n  apply (rule exI[where x=\"[]\"])\n  apply simp\n  apply (cases \"q = []\")\n  apply (erule allE[where x=\"[]\"])\n  apply simp\n\n  apply clarsimp\n  apply (cases \"\\<exists>q. p = a %* q +++ (0 # q)\")\n  apply (clarsimp simp add: poly_add poly_cmult)\n  apply (rule_tac x = qa in exI)\n  apply (simp add: distrib_right [symmetric])\n  apply clarsimp\n\n  apply (auto simp add: poly_linear_divides poly_add poly_cmult distrib_right [symmetric])\n  apply (rule_tac x = \"pmult qa q\" in exI)\n  apply (rule_tac [2] x = \"pmult p qa\" in exI)\n  apply (auto simp add: poly_add poly_mult poly_cmult ac_simps)\n  done\n\nlemma (in comm_semiring_1) poly_divides_refl[simp]: \"p divides p\"\n  apply (simp add: divides_def)\n  apply (rule_tac x = \"[one]\" in exI)\n  apply (auto simp add: poly_mult fun_eq_iff)\n  done\n\nlemma (in comm_semiring_1) poly_divides_trans: \"p divides q \\<Longrightarrow> q divides r \\<Longrightarrow> p divides r\"\n  apply (simp add: divides_def)\n  apply safe\n  apply (rule_tac x = \"pmult qa qaa\" in exI)\n  apply (auto simp add: poly_mult fun_eq_iff mult.assoc)\n  done\n\nlemma (in comm_semiring_1) poly_divides_exp: \"m \\<le> n \\<Longrightarrow> (p %^ m) divides (p %^ n)\"\n  by (auto simp: le_iff_add divides_def poly_exp_add fun_eq_iff)\n\nlemma (in comm_semiring_1) poly_exp_divides: \"(p %^ n) divides q \\<Longrightarrow> m \\<le> n \\<Longrightarrow> (p %^ m) divides q\"\n  by (blast intro: poly_divides_exp poly_divides_trans)\n\nlemma (in comm_semiring_0) poly_divides_add: \"p divides q \\<Longrightarrow> p divides r \\<Longrightarrow> p divides (q +++ r)\"\n  apply (auto simp add: divides_def)\n  apply (rule_tac x = \"padd qa qaa\" in exI)\n  apply (auto simp add: poly_add fun_eq_iff poly_mult distrib_left)\n  done\n\nlemma (in comm_ring_1) poly_divides_diff: \"p divides q \\<Longrightarrow> p divides (q +++ r) \\<Longrightarrow> p divides r\"\n  apply (auto simp add: divides_def)\n  apply (rule_tac x = \"padd qaa (poly_minus qa)\" in exI)\n  apply (auto simp add: poly_add fun_eq_iff poly_mult poly_minus algebra_simps)\n  done\n\nlemma (in comm_ring_1) poly_divides_diff2: \"p divides r \\<Longrightarrow> p divides (q +++ r) \\<Longrightarrow> p divides q\"\n  apply (erule poly_divides_diff)\n  apply (auto simp add: poly_add fun_eq_iff poly_mult divides_def ac_simps)\n  done\n\nlemma (in semiring_0) poly_divides_zero: \"poly p = poly [] \\<Longrightarrow> q divides p\"\n  apply (simp add: divides_def)\n  apply (rule exI[where x = \"[]\"])\n  apply (auto simp add: fun_eq_iff poly_mult)\n  done\n\nlemma (in semiring_0) poly_divides_zero2 [simp]: \"q divides []\"\n  apply (simp add: divides_def)\n  apply (rule_tac x = \"[]\" in exI)\n  apply (auto simp add: fun_eq_iff)\n  done\n\n\ntext \\<open>At last, we can consider the order of a root.\\<close>\n\nlemma (in idom_char_0) poly_order_exists_lemma:\n  assumes \"length p = d\"\n    and \"poly p \\<noteq> poly []\"\n  shows \"\\<exists>n q. p = mulexp n [-a, 1] q \\<and> poly q a \\<noteq> 0\"\n  using assms\nproof (induct d arbitrary: p)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n p)\n  show ?case\n  proof (cases \"poly p a = 0\")\n    case True\n    from Suc.prems have h: \"length p = Suc n\" \"poly p \\<noteq> poly []\"\n      by auto\n    then have pN: \"p \\<noteq> []\"\n      by auto\n    from True[unfolded poly_linear_divides] pN obtain q where q: \"p = [-a, 1] *** q\"\n      by blast\n    from q h True have qh: \"length q = n\" \"poly q \\<noteq> poly []\"\n      apply simp_all\n      apply (simp only: fun_eq_iff)\n      apply (rule ccontr)\n      apply (simp add: fun_eq_iff poly_add poly_cmult)\n      done\n    from Suc.hyps[OF qh] obtain m r where mr: \"q = mulexp m [-a,1] r\" \"poly r a \\<noteq> 0\"\n      by blast\n    from mr q have \"p = mulexp (Suc m) [-a,1] r \\<and> poly r a \\<noteq> 0\"\n      by simp\n    then show ?thesis by blast\n  next\n    case False\n    then show ?thesis\n      using Suc.prems\n      apply simp\n      apply (rule exI[where x=\"0::nat\"])\n      apply simp\n      done\n  qed\nqed\n\n\nlemma (in comm_semiring_1) poly_mulexp: \"poly (mulexp n p q) x = (poly p x) ^ n * poly q x\"\n  by (induct n) (auto simp add: poly_mult ac_simps)\n\nlemma (in comm_semiring_1) divides_left_mult:\n  assumes \"(p *** q) divides r\"\n  shows \"p divides r \\<and> q divides r\"\nproof-\n  from assms obtain t where \"poly r = poly (p *** q *** t)\"\n    unfolding divides_def by blast\n  then have \"poly r = poly (p *** (q *** t))\" and \"poly r = poly (q *** (p *** t))\"\n    by (auto simp add: fun_eq_iff poly_mult ac_simps)\n  then show ?thesis\n    unfolding divides_def by blast\nqed\n\n\n(* FIXME: Tidy up *)\n\nlemma (in semiring_1) zero_power_iff: \"0 ^ n = (if n = 0 then 1 else 0)\"\n  by (induct n) simp_all\n\nlemma (in idom_char_0) poly_order_exists:\n  assumes \"length p = d\"\n    and \"poly p \\<noteq> poly []\"\n  shows \"\\<exists>n. [- a, 1] %^ n divides p \\<and> \\<not> [- a, 1] %^ Suc n divides p\"\nproof -\n  from assms have \"\\<exists>n q. p = mulexp n [- a, 1] q \\<and> poly q a \\<noteq> 0\"\n    by (rule poly_order_exists_lemma)\n  then obtain n q where p: \"p = mulexp n [- a, 1] q\" and \"poly q a \\<noteq> 0\"\n    by blast\n  have \"[- a, 1] %^ n divides mulexp n [- a, 1] q\"\n  proof (rule dividesI)\n    show \"poly (mulexp n [- a, 1] q) = poly ([- a, 1] %^ n *** q)\"\n      by (induct n) (simp_all add: poly_add poly_cmult poly_mult algebra_simps)\n  qed\n  moreover have \"\\<not> [- a, 1] %^ Suc n divides mulexp n [- a, 1] q\"\n  proof\n    assume \"[- a, 1] %^ Suc n divides mulexp n [- a, 1] q\"\n    then obtain m where \"poly (mulexp n [- a, 1] q) = poly ([- a, 1] %^ Suc n *** m)\"\n      by (rule dividesE)\n    moreover have \"poly (mulexp n [- a, 1] q) \\<noteq> poly ([- a, 1] %^ Suc n *** m)\"\n    proof (induct n)\n      case 0\n      show ?case\n      proof (rule ccontr)\n        assume \"\\<not> ?thesis\"\n        then have \"poly q a = 0\"\n          by (simp add: poly_add poly_cmult)\n        with \\<open>poly q a \\<noteq> 0\\<close> show False\n          by simp\n      qed\n    next\n      case (Suc n)\n      show ?case\n        by (rule pexp_Suc [THEN ssubst])\n          (simp add: poly_mult_left_cancel poly_mult_assoc Suc del: pmult_Cons pexp_Suc)\n    qed\n    ultimately show False by simp\n  qed\n  ultimately show ?thesis\n    by (auto simp add: p)\nqed\n\nlemma (in semiring_1) poly_one_divides[simp]: \"[1] divides p\"\n  by (auto simp add: divides_def)\n\nlemma (in idom_char_0) poly_order:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> \\<exists>!n. ([-a, 1] %^ n) divides p \\<and> \\<not> (([-a, 1] %^ Suc n) divides p)\"\n  apply (auto intro: poly_order_exists simp add: less_linear simp del: pmult_Cons pexp_Suc)\n  apply (cut_tac x = y and y = n in less_linear)\n  apply (drule_tac m = n in poly_exp_divides)\n  apply (auto dest: Suc_le_eq [THEN iffD2, THEN [2] poly_exp_divides]\n    simp del: pmult_Cons pexp_Suc)\n  done\n\n\ntext \\<open>Order\\<close>\n\nlemma some1_equalityD: \"n = (SOME n. P n) \\<Longrightarrow> \\<exists>!n. P n \\<Longrightarrow> P n\"\n  by (blast intro: someI2)\n\nlemma (in idom_char_0) order:\n  \"([-a, 1] %^ n) divides p \\<and> \\<not> (([-a, 1] %^ Suc n) divides p) \\<longleftrightarrow>\n    n = order a p \\<and> poly p \\<noteq> poly []\"\n  unfolding order_def\n  apply (rule iffI)\n  apply (blast dest: poly_divides_zero intro!: some1_equality [symmetric] poly_order)\n  apply (blast intro!: poly_order [THEN [2] some1_equalityD])\n  done\n\nlemma (in idom_char_0) order2:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow>\n    ([-a, 1] %^ (order a p)) divides p \\<and> \\<not> ([-a, 1] %^ Suc (order a p)) divides p\"\n  by (simp add: order del: pexp_Suc)\n\nlemma (in idom_char_0) order_unique:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> ([-a, 1] %^ n) divides p \\<Longrightarrow> \\<not> ([-a, 1] %^ (Suc n)) divides p \\<Longrightarrow>\n    n = order a p\"\n  using order [of a n p] by auto\n\nlemma (in idom_char_0) order_unique_lemma:\n  \"poly p \\<noteq> poly [] \\<and> ([-a, 1] %^ n) divides p \\<and> \\<not> ([-a, 1] %^ (Suc n)) divides p \\<Longrightarrow>\n    n = order a p\"\n  by (blast intro: order_unique)\n\nlemma (in ring_1) order_poly: \"poly p = poly q \\<Longrightarrow> order a p = order a q\"\n  by (auto simp add: fun_eq_iff divides_def poly_mult order_def)\n\nlemma (in semiring_1) pexp_one[simp]: \"p %^ (Suc 0) = p\"\n  by (induct p) auto\n\nlemma (in comm_ring_1) lemma_order_root:\n  \"0 < n \\<and> [- a, 1] %^ n divides p \\<and> \\<not> [- a, 1] %^ (Suc n) divides p \\<Longrightarrow> poly p a = 0\"\n  by (induct n arbitrary: a p) (auto simp add: divides_def poly_mult simp del: pmult_Cons)\n\nlemma (in idom_char_0) order_root: \"poly p a = 0 \\<longleftrightarrow> poly p = poly [] \\<or> order a p \\<noteq> 0\"\n  apply (cases \"poly p = poly []\")\n  apply auto\n  apply (simp add: poly_linear_divides del: pmult_Cons)\n  apply safe\n  apply (drule_tac [!] a = a in order2)\n  apply (rule ccontr)\n  apply (simp add: divides_def poly_mult fun_eq_iff del: pmult_Cons)\n  apply blast\n  using neq0_conv apply (blast intro: lemma_order_root)\n  done\n\nlemma (in idom_char_0) order_divides:\n  \"([-a, 1] %^ n) divides p \\<longleftrightarrow> poly p = poly [] \\<or> n \\<le> order a p\"\n  apply (cases \"poly p = poly []\")\n  apply auto\n  apply (simp add: divides_def fun_eq_iff poly_mult)\n  apply (rule_tac x = \"[]\" in exI)\n  apply (auto dest!: order2 [where a=a] intro: poly_exp_divides simp del: pexp_Suc)\n  done\n\nlemma (in idom_char_0) order_decomp:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> \\<exists>q. poly p = poly (([-a, 1] %^ order a p) *** q) \\<and> \\<not> [-a, 1] divides q\"\n  unfolding divides_def\n  apply (drule order2 [where a = a])\n  apply (simp add: divides_def del: pexp_Suc pmult_Cons)\n  apply safe\n  apply (rule_tac x = q in exI)\n  apply safe\n  apply (drule_tac x = qa in spec)\n  apply (auto simp add: poly_mult fun_eq_iff poly_exp ac_simps simp del: pmult_Cons)\n  done\n\ntext \\<open>Important composition properties of orders.\\<close>\nlemma order_mult:\n  fixes a :: \"'a::idom_char_0\"\n  shows \"poly (p *** q) \\<noteq> poly [] \\<Longrightarrow> order a (p *** q) = order a p + order a q\"\n  apply (cut_tac a = a and p = \"p *** q\" and n = \"order a p + order a q\" in order)\n  apply (auto simp add: poly_entire simp del: pmult_Cons)\n  apply (drule_tac a = a in order2)+\n  apply safe\n  apply (simp add: divides_def fun_eq_iff poly_exp_add poly_mult del: pmult_Cons, safe)\n  apply (rule_tac x = \"qa *** qaa\" in exI)\n  apply (simp add: poly_mult ac_simps del: pmult_Cons)\n  apply (drule_tac a = a in order_decomp)+\n  apply safe\n  apply (subgoal_tac \"[-a, 1] divides (qa *** qaa) \")\n  apply (simp add: poly_primes del: pmult_Cons)\n  apply (auto simp add: divides_def simp del: pmult_Cons)\n  apply (rule_tac x = qb in exI)\n  apply (subgoal_tac \"poly ([-a, 1] %^ (order a p) *** (qa *** qaa)) =\n    poly ([-a, 1] %^ (order a p) *** ([-a, 1] *** qb))\")\n  apply (drule poly_mult_left_cancel [THEN iffD1])\n  apply force\n  apply (subgoal_tac \"poly ([-a, 1] %^ (order a q) *** ([-a, 1] %^ (order a p) *** (qa *** qaa))) =\n    poly ([-a, 1] %^ (order a q) *** ([-a, 1] %^ (order a p) *** ([-a, 1] *** qb))) \")\n  apply (drule poly_mult_left_cancel [THEN iffD1])\n  apply force\n  apply (simp add: fun_eq_iff poly_exp_add poly_mult ac_simps del: pmult_Cons)\n  done\n\nlemma (in idom_char_0) order_mult:\n  assumes \"poly (p *** q) \\<noteq> poly []\"\n  shows \"order a (p *** q) = order a p + order a q\"\n  using assms\n  apply (cut_tac a = a and p = \"pmult p q\" and n = \"order a p + order a q\" in order)\n  apply (auto simp add: poly_entire simp del: pmult_Cons)\n  apply (drule_tac a = a in order2)+\n  apply safe\n  apply (simp add: divides_def fun_eq_iff poly_exp_add poly_mult del: pmult_Cons)\n  apply safe\n  apply (rule_tac x = \"pmult qa qaa\" in exI)\n  apply (simp add: poly_mult ac_simps del: pmult_Cons)\n  apply (drule_tac a = a in order_decomp)+\n  apply safe\n  apply (subgoal_tac \"[uminus a, one] divides pmult qa qaa\")\n  apply (simp add: poly_primes del: pmult_Cons)\n  apply (auto simp add: divides_def simp del: pmult_Cons)\n  apply (rule_tac x = qb in exI)\n  apply (subgoal_tac \"poly (pmult (pexp [uminus a, one] (order a p)) (pmult qa qaa)) =\n    poly (pmult (pexp [uminus a, one] (order a p)) (pmult [uminus a, one] qb))\")\n  apply (drule poly_mult_left_cancel [THEN iffD1], force)\n  apply (subgoal_tac \"poly (pmult (pexp [uminus a, one] (order a q))\n      (pmult (pexp [uminus a, one] (order a p)) (pmult qa qaa))) =\n    poly (pmult (pexp [uminus a, one] (order a q))\n      (pmult (pexp [uminus a, one] (order a p)) (pmult [uminus a, one] qb)))\")\n  apply (drule poly_mult_left_cancel [THEN iffD1], force)\n  apply (simp add: fun_eq_iff poly_exp_add poly_mult ac_simps del: pmult_Cons)\n  done\n\nlemma (in idom_char_0) order_root2: \"poly p \\<noteq> poly [] \\<Longrightarrow> poly p a = 0 \\<longleftrightarrow> order a p \\<noteq> 0\"\n  by (rule order_root [THEN ssubst]) auto\n\nlemma (in semiring_1) pmult_one[simp]: \"[1] *** p = p\"\n  by auto\n\nlemma (in semiring_0) poly_Nil_zero: \"poly [] = poly [0]\"\n  by (simp add: fun_eq_iff)\n\nlemma (in idom_char_0) rsquarefree_decomp:\n  \"rsquarefree p \\<Longrightarrow> poly p a = 0 \\<Longrightarrow> \\<exists>q. poly p = poly ([-a, 1] *** q) \\<and> poly q a \\<noteq> 0\"\n  apply (simp add: rsquarefree_def)\n  apply safe\n  apply (frule_tac a = a in order_decomp)\n  apply (drule_tac x = a in spec)\n  apply (drule_tac a = a in order_root2 [symmetric])\n  apply (auto simp del: pmult_Cons)\n  apply (rule_tac x = q in exI, safe)\n  apply (simp add: poly_mult fun_eq_iff)\n  apply (drule_tac p1 = q in poly_linear_divides [THEN iffD1])\n  apply (simp add: divides_def del: pmult_Cons, safe)\n  apply (drule_tac x = \"[]\" in spec)\n  apply (auto simp add: fun_eq_iff)\n  done\n\n\ntext \\<open>Normalization of a polynomial.\\<close>\n\nlemma (in semiring_0) poly_normalize[simp]: \"poly (pnormalize p) = poly p\"\n  by (induct p) (auto simp add: fun_eq_iff)\n\ntext \\<open>The degree of a polynomial.\\<close>\n\nlemma (in semiring_0) lemma_degree_zero: \"(\\<forall>c \\<in> set p. c = 0) \\<longleftrightarrow> pnormalize p = []\"\n  by (induct p) auto\n\nlemma (in idom_char_0) degree_zero:\n  assumes \"poly p = poly []\"\n  shows \"degree p = 0\"\n  using assms\n  by (cases \"pnormalize p = []\") (auto simp add: degree_def poly_zero lemma_degree_zero)\n\nlemma (in semiring_0) pnormalize_sing: \"pnormalize [x] = [x] \\<longleftrightarrow> x \\<noteq> 0\"\n  by simp\n\nlemma (in semiring_0) pnormalize_pair: \"y \\<noteq> 0 \\<longleftrightarrow> pnormalize [x, y] = [x, y]\"\n  by simp\n\nlemma (in semiring_0) pnormal_cons: \"pnormal p \\<Longrightarrow> pnormal (c # p)\"\n  unfolding pnormal_def by simp\n\nlemma (in semiring_0) pnormal_tail: \"p \\<noteq> [] \\<Longrightarrow> pnormal (c # p) \\<Longrightarrow> pnormal p\"\n  unfolding pnormal_def by (auto split: if_split_asm)\n\nlemma (in semiring_0) pnormal_last_nonzero: \"pnormal p \\<Longrightarrow> last p \\<noteq> 0\"\n  by (induct p) (simp_all add: pnormal_def split: if_split_asm)\n\nlemma (in semiring_0) pnormal_length: \"pnormal p \\<Longrightarrow> 0 < length p\"\n  unfolding pnormal_def length_greater_0_conv by blast\n\nlemma (in semiring_0) pnormal_last_length: \"0 < length p \\<Longrightarrow> last p \\<noteq> 0 \\<Longrightarrow> pnormal p\"\n  by (induct p) (auto simp: pnormal_def  split: if_split_asm)\n\nlemma (in semiring_0) pnormal_id: \"pnormal p \\<longleftrightarrow> 0 < length p \\<and> last p \\<noteq> 0\"\n  using pnormal_last_length pnormal_length pnormal_last_nonzero by blast\n\nlemma (in idom_char_0) poly_Cons_eq: \"poly (c # cs) = poly (d # ds) \\<longleftrightarrow> c = d \\<and> poly cs = poly ds\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    from that have \"poly ((c # cs) +++ -- (d # ds)) x = 0\" for x\n      by (simp only: poly_minus poly_add algebra_simps) (simp add: algebra_simps)\n    then have \"poly ((c # cs) +++ -- (d # ds)) = poly []\"\n      by (simp add: fun_eq_iff)\n    then have \"c = d\" and \"\\<forall>x \\<in> set (cs +++ -- ds). x = 0\"\n      unfolding poly_zero by (simp_all add: poly_minus_def algebra_simps)\n    from this(2) have \"poly (cs +++ -- ds) x = 0\" for x\n      unfolding poly_zero[symmetric] by simp\n    with \\<open>c = d\\<close> show ?thesis\n      by (simp add: poly_minus poly_add algebra_simps fun_eq_iff)\n  qed\n  show ?lhs if ?rhs\n    using that by (simp add:fun_eq_iff)\nqed\n\nlemma (in idom_char_0) pnormalize_unique: \"poly p = poly q \\<Longrightarrow> pnormalize p = pnormalize q\"\nproof (induct q arbitrary: p)\n  case Nil\n  then show ?case\n    by (simp only: poly_zero lemma_degree_zero) simp\nnext\n  case (Cons c cs p)\n  then show ?case\n  proof (induct p)\n    case Nil\n    then have \"poly [] = poly (c # cs)\"\n      by blast\n    then have \"poly (c#cs) = poly []\"\n      by simp\n    then show ?case\n      by (simp only: poly_zero lemma_degree_zero) simp\n  next\n    case (Cons d ds)\n    then have eq: \"poly (d # ds) = poly (c # cs)\"\n      by blast\n    then have eq': \"\\<And>x. poly (d # ds) x = poly (c # cs) x\"\n      by simp\n    then have \"poly (d # ds) 0 = poly (c # cs) 0\"\n      by blast\n    then have dc: \"d = c\"\n      by auto\n    with eq have \"poly ds = poly cs\"\n      unfolding  poly_Cons_eq by simp\n    with Cons.prems have \"pnormalize ds = pnormalize cs\"\n      by blast\n    with dc show ?case\n      by simp\n  qed\nqed\n\nlemma (in idom_char_0) degree_unique:\n  assumes pq: \"poly p = poly q\"\n  shows \"degree p = degree q\"\n  using pnormalize_unique[OF pq] unfolding degree_def by simp\n\nlemma (in semiring_0) pnormalize_length: \"length (pnormalize p) \\<le> length p\"\n  by (induct p) auto\n\nlemma (in semiring_0) last_linear_mul_lemma:\n  \"last ((a %* p) +++ (x # (b %* p))) = (if p = [] then x else b * last p)\"\n  apply (induct p arbitrary: a x b)\n  apply auto\n  subgoal for a p c x b\n    apply (subgoal_tac \"padd (cmult c p) (times b a # cmult b p) \\<noteq> []\")\n    apply simp\n    apply (induct p)\n    apply auto\n    done\n  done\n\nlemma (in semiring_1) last_linear_mul:\n  assumes p: \"p \\<noteq> []\"\n  shows \"last ([a, 1] *** p) = last p\"\nproof -\n  from p obtain c cs where cs: \"p = c # cs\"\n    by (cases p) auto\n  from cs have eq: \"[a, 1] *** p = (a %* (c # cs)) +++ (0 # (1 %* (c # cs)))\"\n    by (simp add: poly_cmult_distr)\n  show ?thesis\n    using cs unfolding eq last_linear_mul_lemma by simp\nqed\n\nlemma (in semiring_0) pnormalize_eq: \"last p \\<noteq> 0 \\<Longrightarrow> pnormalize p = p\"\n  by (induct p) (auto split: if_split_asm)\n\nlemma (in semiring_0) last_pnormalize: \"pnormalize p \\<noteq> [] \\<Longrightarrow> last (pnormalize p) \\<noteq> 0\"\n  by (induct p) auto\n\nlemma (in semiring_0) pnormal_degree: \"last p \\<noteq> 0 \\<Longrightarrow> degree p = length p - 1\"\n  using pnormalize_eq[of p] unfolding degree_def by simp\n\nlemma (in semiring_0) poly_Nil_ext: \"poly [] = (\\<lambda>x. 0)\"\n  by auto\n\nlemma (in idom_char_0) linear_mul_degree:\n  assumes p: \"poly p \\<noteq> poly []\"\n  shows \"degree ([a, 1] *** p) = degree p + 1\"\nproof -\n  from p have pnz: \"pnormalize p \\<noteq> []\"\n    unfolding poly_zero lemma_degree_zero .\n\n  from last_linear_mul[OF pnz, of a] last_pnormalize[OF pnz]\n  have l0: \"last ([a, 1] *** pnormalize p) \\<noteq> 0\" by simp\n\n  from last_pnormalize[OF pnz] last_linear_mul[OF pnz, of a]\n    pnormal_degree[OF l0] pnormal_degree[OF last_pnormalize[OF pnz]] pnz\n  have th: \"degree ([a,1] *** pnormalize p) = degree (pnormalize p) + 1\"\n    by simp\n\n  have eqs: \"poly ([a,1] *** pnormalize p) = poly ([a,1] *** p)\"\n    by (rule ext) (simp add: poly_mult poly_add poly_cmult)\n  from degree_unique[OF eqs] th show ?thesis\n    by (simp add: degree_unique[OF poly_normalize])\nqed\n\nlemma (in idom_char_0) linear_pow_mul_degree:\n  \"degree([a,1] %^n *** p) = (if poly p = poly [] then 0 else degree p + n)\"\nproof (induct n arbitrary: a p)\n  case (0 a p)\n  show ?case\n  proof (cases \"poly p = poly []\")\n    case True\n    then show ?thesis\n      using degree_unique[OF True] by (simp add: degree_def)\n  next\n    case False\n    then show ?thesis\n      by (auto simp add: poly_Nil_ext)\n  qed\nnext\n  case (Suc n a p)\n  have eq: \"poly ([a, 1] %^(Suc n) *** p) = poly ([a, 1] %^ n *** ([a, 1] *** p))\"\n    apply (rule ext)\n    apply (simp add: poly_mult poly_add poly_cmult)\n    apply (simp add: ac_simps distrib_left)\n    done\n  note deq = degree_unique[OF eq]\n  show ?case\n  proof (cases \"poly p = poly []\")\n    case True\n    with eq have eq': \"poly ([a, 1] %^(Suc n) *** p) = poly []\"\n      by (auto simp add: poly_mult poly_cmult poly_add)\n    from degree_unique[OF eq'] True show ?thesis\n      by (simp add: degree_def)\n  next\n    case False\n    then have ap: \"poly ([a,1] *** p) \\<noteq> poly []\"\n      using poly_mult_not_eq_poly_Nil unfolding poly_entire by auto\n    have eq: \"poly ([a, 1] %^(Suc n) *** p) = poly ([a, 1]%^n *** ([a, 1] *** p))\"\n      by (auto simp add: poly_mult poly_add poly_exp poly_cmult algebra_simps)\n    from ap have ap': \"poly ([a, 1] *** p) = poly [] \\<longleftrightarrow> False\"\n      by blast\n    have th0: \"degree ([a, 1]%^n *** ([a, 1] *** p)) = degree ([a, 1] *** p) + n\"\n      apply (simp only: Suc.hyps[of a \"pmult [a,one] p\"] ap')\n      apply simp\n      done\n    from degree_unique[OF eq] ap False th0 linear_mul_degree[OF False, of a]\n    show ?thesis\n      by (auto simp del: poly.simps)\n  qed\nqed\n\nlemma (in idom_char_0) order_degree:\n  assumes p0: \"poly p \\<noteq> poly []\"\n  shows \"order a p \\<le> degree p\"\nproof -\n  from order2[OF p0, unfolded divides_def]\n  obtain q where q: \"poly p = poly ([- a, 1]%^ (order a p) *** q)\"\n    by blast\n  with q p0 have \"poly q \\<noteq> poly []\"\n    by (simp add: poly_mult poly_entire)\n  with degree_unique[OF q, unfolded linear_pow_mul_degree] show ?thesis\n    by auto\nqed\n\n\ntext \\<open>Tidier versions of finiteness of roots.\\<close>\nlemma (in idom_char_0) poly_roots_finite_set:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> finite {x. poly p x = 0}\"\n  unfolding poly_roots_finite .\n\n\ntext \\<open>Bound for polynomial.\\<close>\nlemma poly_mono:\n  fixes x :: \"'a::linordered_idom\"\n  shows \"\\<bar>x\\<bar> \\<le> k \\<Longrightarrow> \\<bar>poly p x\\<bar> \\<le> poly (map abs p) k\"\nproof (induct p)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a p)\n  then show ?case\n    apply auto\n    apply (rule_tac y = \"\\<bar>a\\<bar> + \\<bar>x * poly p x\\<bar>\" in order_trans)\n    apply (rule abs_triangle_ineq)\n    apply (auto intro!: mult_mono simp add: abs_mult)\n    done\nqed\n\nlemma (in semiring_0) poly_Sing: \"poly [c] x = c\"\n  by simp\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Decision_Procs/Polynomial_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8652240791017535, "lm_q1q2_score": 0.7936723508537075}}
{"text": "theory auxiliary0\nimports axioms_base\nbegin\n\n\ntext{* Proving rules for proofs about class equality. *}\n\nlemma equalityI: \"\\<lbrakk>X \\<subseteq> Y; Y \\<subseteq> X\\<rbrakk> \\<Longrightarrow> X = Y\"\nby (simp add: Prop4_1_a)\n\nlemma equalityE: \"X = Y \\<Longrightarrow> X \\<subseteq> Y\"\nby (simp add: Prop4_1_a)\n\nlemma Ex_Set: \"\\<lbrakk>\\<And>u :: Set. u \\<in> X \\<longleftrightarrow> u \\<in> Y\\<rbrakk> \\<Longrightarrow> X = Y\"\nby (metis Abs_Set_inverse extensionality mem_Collect_eq set_predicate_def universe)\n\n\ntext{* Two proving rules and a lemma about subclasses *} \n\nlemma subsetI: \"(\\<And>x::Set. x \\<in> X \\<Longrightarrow> x \\<in> Y) \\<Longrightarrow> X \\<subseteq> Y\"\nby (metis Abs_Set_inverse CollectI set_predicate_def subclass'_def universe)\n\nlemma subclassI: \"(\\<And>x. x \\<in> X \\<Longrightarrow> x \\<in> Y) \\<Longrightarrow> X \\<subseteq> Y\" \nusing subclass'_def by blast\n\n\n\n\ntext{* The empty class is unique. *}\n\nlemma empty_is_unique: \"\\<lbrakk>\\<forall>y. y \\<notin> x\\<rbrakk> \\<Longrightarrow> x = \\<emptyset>\" \nusing empty_set extensionality by blast\n\ntext{* Lemmas/proving rules about singletons. *}\n\nlemma singletonE: \"x \\<in> {y} \\<Longrightarrow> x = y\"\n  using pairing by simp\n\nlemma singletonE2: \"x \\<in> {x}\"\n  using pairing by simp\n\nlemma singletonI: \"\\<forall>x. x \\<in> {y} \\<longleftrightarrow> x = y\"\n  using pairing by simp\n\nlemma subset_of_singleton:  \n    fixes b c\n  assumes \"b \\<subseteq> {c}\"\n    shows \"b=\\<emptyset> \\<or> b={c}\"\nproof -\n  {assume \"b \\<noteq> \\<emptyset>\"\n   then obtain d where \"d\\<in>b\" by (metis empty_is_unique) \n   hence \"d\\<in>{c}\"using assms using subclass'_def by blast \n   hence \"d=c\" using singletonE by blast\n   hence \"b={c}\" by (metis \\<open>d\\<in>b\\<close> assms equalityI pairing subsetI)}\n  thus ?thesis by auto\nqed\n\nend", "meta": {"author": "ioannad", "repo": "NBG_HOL", "sha": "ba792985c5f63727c5a6f9cd2e78e01a41f79f2a", "save_path": "github-repos/isabelle/ioannad-NBG_HOL", "path": "github-repos/isabelle/ioannad-NBG_HOL/NBG_HOL-ba792985c5f63727c5a6f9cd2e78e01a41f79f2a/auxiliary0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7936327538759326}}
{"text": "(*  Title:      HOL/Number_Theory/Eratosthenes.thy\n    Author:     Florian Haftmann, TU Muenchen\n*)\n\nsection {* The sieve of Eratosthenes *}\n\ntheory Eratosthenes\nimports Main Primes\nbegin\n\n\nsubsection {* Preliminary: strict divisibility *}\n\ncontext dvd\nbegin\n\nabbreviation dvd_strict :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"dvd'_strict\" 50)\nwhere\n  \"b dvd_strict a \\<equiv> b dvd a \\<and> \\<not> a dvd b\"\n\nend\n\nsubsection {* Main corpus *}\n\ntext {* The sieve is modelled as a list of booleans, where @{const False} means \\emph{marked out}. *}\n\ntype_synonym marks = \"bool list\"\n\ndefinition numbers_of_marks :: \"nat \\<Rightarrow> marks \\<Rightarrow> nat set\"\nwhere\n  \"numbers_of_marks n bs = fst ` {x \\<in> set (enumerate n bs). snd x}\"\n\nlemma numbers_of_marks_simps [simp, code]:\n  \"numbers_of_marks n [] = {}\"\n  \"numbers_of_marks n (True # bs) = insert n (numbers_of_marks (Suc n) bs)\"\n  \"numbers_of_marks n (False # bs) = numbers_of_marks (Suc n) bs\"\n  by (auto simp add: numbers_of_marks_def intro!: image_eqI)\n\nlemma numbers_of_marks_Suc:\n  \"numbers_of_marks (Suc n) bs = Suc ` numbers_of_marks n bs\"\n  by (auto simp add: numbers_of_marks_def enumerate_Suc_eq image_iff Bex_def)\n\nlemma numbers_of_marks_replicate_False [simp]:\n  \"numbers_of_marks n (replicate m False) = {}\"\n  by (auto simp add: numbers_of_marks_def enumerate_replicate_eq)\n\nlemma numbers_of_marks_replicate_True [simp]:\n  \"numbers_of_marks n (replicate m True) = {n..<n+m}\"\n  by (auto simp add: numbers_of_marks_def enumerate_replicate_eq image_def)\n\nlemma in_numbers_of_marks_eq:\n  \"m \\<in> numbers_of_marks n bs \\<longleftrightarrow> m \\<in> {n..<n + length bs} \\<and> bs ! (m - n)\"\n  by (simp add: numbers_of_marks_def in_set_enumerate_eq image_iff add.commute)\n\nlemma sorted_list_of_set_numbers_of_marks:\n  \"sorted_list_of_set (numbers_of_marks n bs) = map fst (filter snd (enumerate n bs))\"\n  by (auto simp add: numbers_of_marks_def distinct_map\n    intro!: sorted_filter distinct_filter inj_onI sorted_distinct_set_unique)\n\n\ntext {* Marking out multiples in a sieve  *}\n \ndefinition mark_out :: \"nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"mark_out n bs = map (\\<lambda>(q, b). b \\<and> \\<not> Suc n dvd Suc (Suc q)) (enumerate n bs)\"\n\nlemma mark_out_Nil [simp]:\n  \"mark_out n [] = []\"\n  by (simp add: mark_out_def)\n  \nlemma length_mark_out [simp]:\n  \"length (mark_out n bs) = length bs\"\n  by (simp add: mark_out_def)\n\nlemma numbers_of_marks_mark_out:\n  \"numbers_of_marks n (mark_out m bs) = {q \\<in> numbers_of_marks n bs. \\<not> Suc m dvd Suc q - n}\"\n  by (auto simp add: numbers_of_marks_def mark_out_def in_set_enumerate_eq image_iff\n    nth_enumerate_eq less_eq_dvd_minus)\n\n\ntext {* Auxiliary operation for efficient implementation  *}\n\ndefinition mark_out_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"mark_out_aux n m bs =\n    map (\\<lambda>(q, b). b \\<and> (q < m + n \\<or> \\<not> Suc n dvd Suc (Suc q) + (n - m mod Suc n))) (enumerate n bs)\"\n\nlemma mark_out_code [code]:\n  \"mark_out n bs = mark_out_aux n n bs\"\nproof -\n  { fix a\n    assume A: \"Suc n dvd Suc (Suc a)\"\n      and B: \"a < n + n\"\n      and C: \"n \\<le> a\"\n    have False\n    proof (cases \"n = 0\")\n      case True with A B C show False by simp\n    next\n      def m \\<equiv> \"Suc n\" then have \"m > 0\" by simp\n      case False then have \"n > 0\" by simp\n      from A obtain q where q: \"Suc (Suc a) = Suc n * q\" by (rule dvdE)\n      have \"q > 0\"\n      proof (rule ccontr)\n        assume \"\\<not> q > 0\"\n        with q show False by simp\n      qed\n      with `n > 0` have \"Suc n * q \\<ge> 2\" by (auto simp add: gr0_conv_Suc)\n      with q have a: \"a = Suc n * q - 2\" by simp\n      with B have \"q + n * q < n + n + 2\"\n        by auto\n      then have \"m * q < m * 2\" by (simp add: m_def)\n      with `m > 0` have \"q < 2\" by simp\n      with `q > 0` have \"q = 1\" by simp\n      with a have \"a = n - 1\" by simp\n      with `n > 0` C show False by simp\n    qed\n  } note aux = this \n  show ?thesis\n    by (auto simp add: mark_out_def mark_out_aux_def in_set_enumerate_eq intro: aux)\nqed\n\nlemma mark_out_aux_simps [simp, code]:\n  \"mark_out_aux n m [] = []\" (is ?thesis1)\n  \"mark_out_aux n 0 (b # bs) = False # mark_out_aux n n bs\" (is ?thesis2)\n  \"mark_out_aux n (Suc m) (b # bs) = b # mark_out_aux n m bs\" (is ?thesis3)\nproof -\n  show ?thesis1\n    by (simp add: mark_out_aux_def)\n  show ?thesis2\n    by (auto simp add: mark_out_code [symmetric] mark_out_aux_def mark_out_def\n      enumerate_Suc_eq in_set_enumerate_eq less_eq_dvd_minus)\n  { def v \\<equiv> \"Suc m\" and w \\<equiv> \"Suc n\"\n    fix q\n    assume \"m + n \\<le> q\"\n    then obtain r where q: \"q = m + n + r\" by (auto simp add: le_iff_add)\n    { fix u\n      from w_def have \"u mod w < w\" by simp\n      then have \"u + (w - u mod w) = w + (u - u mod w)\"\n        by simp\n      then have \"u + (w - u mod w) = w + u div w * w\"\n        by (simp add: div_mod_equality' [symmetric])\n    }\n    then have \"w dvd v + w + r + (w - v mod w) \\<longleftrightarrow> w dvd m + w + r + (w - m mod w)\"\n      by (simp add: add.assoc add.left_commute [of m] add.left_commute [of v]\n        dvd_add_left_iff dvd_add_right_iff)\n    moreover from q have \"Suc q = m + w + r\" by (simp add: w_def)\n    moreover from q have \"Suc (Suc q) = v + w + r\" by (simp add: v_def w_def)\n    ultimately have \"w dvd Suc (Suc (q + (w - v mod w))) \\<longleftrightarrow> w dvd Suc (q + (w - m mod w))\"\n      by (simp only: add_Suc [symmetric])\n    then have \"Suc n dvd Suc (Suc (Suc (q + n) - Suc m mod Suc n)) \\<longleftrightarrow>\n      Suc n dvd Suc (Suc (q + n - m mod Suc n))\"\n      by (simp add: v_def w_def Suc_diff_le trans_le_add2)\n  }\n  then show ?thesis3\n    by (auto simp add: mark_out_aux_def\n      enumerate_Suc_eq in_set_enumerate_eq not_less)\nqed\n\n\ntext {* Main entry point to sieve *}\n\nfun sieve :: \"nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"sieve n [] = []\"\n| \"sieve n (False # bs) = False # sieve (Suc n) bs\"\n| \"sieve n (True # bs) = True # sieve (Suc n) (mark_out n bs)\"\n\ntext {*\n  There are the following possible optimisations here:\n\n  \\begin{itemize}\n\n    \\item @{const sieve} can abort as soon as @{term n} is too big to let\n      @{const mark_out} have any effect.\n\n    \\item Search for further primes can be given up as soon as the search\n      position exceeds the square root of the maximum candidate.\n\n  \\end{itemize}\n\n  This is left as an constructive exercise to the reader.\n*}\n\nlemma numbers_of_marks_sieve:\n  \"numbers_of_marks (Suc n) (sieve n bs) =\n    {q \\<in> numbers_of_marks (Suc n) bs. \\<forall>m \\<in> numbers_of_marks (Suc n) bs. \\<not> m dvd_strict q}\"\nproof (induct n bs rule: sieve.induct)\n  case 1 show ?case by simp\nnext\n  case 2 then show ?case by simp\nnext\n  case (3 n bs)\n  have aux: \"\\<And>M n. n \\<in> Suc ` M \\<longleftrightarrow> n > 0 \\<and> n - 1 \\<in> M\"\n  proof\n    fix M and n\n    assume \"n \\<in> Suc ` M\" then show \"n > 0 \\<and> n - 1 \\<in> M\" by auto\n  next\n    fix M and n :: nat\n    assume \"n > 0 \\<and> n - 1 \\<in> M\"\n    then have \"n > 0\" and \"n - 1 \\<in> M\" by auto\n    then have \"Suc (n - 1) \\<in> Suc ` M\" by blast\n    with `n > 0` show \"n \\<in> Suc ` M\" by simp\n  qed\n  { fix m :: nat\n    assume \"Suc (Suc n) \\<le> m\" and \"m dvd Suc n\"\n    from `m dvd Suc n` obtain q where \"Suc n = m * q\" ..\n    with `Suc (Suc n) \\<le> m` have \"Suc (m * q) \\<le> m\" by simp\n    then have \"m * q < m\" by arith\n    then have \"q = 0\" by simp\n    with `Suc n = m * q` have False by simp\n  } note aux1 = this\n  { fix m q :: nat\n    assume \"\\<forall>q>0. 1 < q \\<longrightarrow> Suc n < q \\<longrightarrow> q \\<le> Suc (n + length bs)\n      \\<longrightarrow> bs ! (q - Suc (Suc n)) \\<longrightarrow> \\<not> Suc n dvd q \\<longrightarrow> q dvd m \\<longrightarrow> m dvd q\"\n    then have *: \"\\<And>q. Suc n < q \\<Longrightarrow> q \\<le> Suc (n + length bs)\n      \\<Longrightarrow> bs ! (q - Suc (Suc n)) \\<Longrightarrow> \\<not> Suc n dvd q \\<Longrightarrow> q dvd m \\<Longrightarrow> m dvd q\"\n      by auto\n    assume \"\\<not> Suc n dvd m\" and \"q dvd m\"\n    then have \"\\<not> Suc n dvd q\" by (auto elim: dvdE)\n    moreover assume \"Suc n < q\" and \"q \\<le> Suc (n + length bs)\"\n      and \"bs ! (q - Suc (Suc n))\"\n    moreover note `q dvd m`\n    ultimately have \"m dvd q\" by (auto intro: *)\n  } note aux2 = this\n  from 3 show ?case\n    apply (simp_all add: numbers_of_marks_mark_out numbers_of_marks_Suc Compr_image_eq inj_image_eq_iff\n      in_numbers_of_marks_eq Ball_def imp_conjL aux)\n    apply safe\n    apply (simp_all add: less_diff_conv2 le_diff_conv2 dvd_minus_self not_less)\n    apply (clarsimp dest!: aux1)\n    apply (simp add: Suc_le_eq less_Suc_eq_le)\n    apply (rule aux2) apply (clarsimp dest!: aux1)+\n    done\nqed\n\n\ntext {* Relation of the sieve algorithm to actual primes *}\n\ndefinition primes_upto :: \"nat \\<Rightarrow> nat list\"\nwhere\n  \"primes_upto n = sorted_list_of_set {m. m \\<le> n \\<and> prime m}\"\n\nlemma set_primes_upto:\n  \"set (primes_upto n) = {m. m \\<le> n \\<and> prime m}\"\n  by (simp add: primes_upto_def)\n\nlemma sorted_primes_upto [iff]:\n  \"sorted (primes_upto n)\"\n  by (simp add: primes_upto_def)\n\nlemma distinct_primes_upto [iff]:\n  \"distinct (primes_upto n)\"\n  by (simp add: primes_upto_def)\n\nlemma set_primes_upto_sieve:\n  \"set (primes_upto n) = numbers_of_marks 2 (sieve 1 (replicate (n - 1) True))\"\nproof (cases \"n > 1\")\n  case False then have \"n = 0 \\<or> n = 1\" by arith\n  then show ?thesis\n    by (auto simp add: numbers_of_marks_sieve numeral_2_eq_2 set_primes_upto dest: prime_gt_Suc_0_nat)\nnext\n  { fix m q\n    assume \"Suc (Suc 0) \\<le> q\"\n      and \"q < Suc n\"\n      and \"m dvd q\"\n    then have \"m < Suc n\" by (auto dest: dvd_imp_le)\n    assume *: \"\\<forall>m\\<in>{Suc (Suc 0)..<Suc n}. m dvd q \\<longrightarrow> q dvd m\"\n      and \"m dvd q\" and \"m \\<noteq> 1\"\n    have \"m = q\" proof (cases \"m = 0\")\n      case True with `m dvd q` show ?thesis by simp\n    next\n      case False with `m \\<noteq> 1` have \"Suc (Suc 0) \\<le> m\" by arith\n      with `m < Suc n` * `m dvd q` have \"q dvd m\" by simp\n      with `m dvd q` show ?thesis by (simp add: dvd.eq_iff)\n    qed\n  }\n  then have aux: \"\\<And>m q. Suc (Suc 0) \\<le> q \\<Longrightarrow>\n    q < Suc n \\<Longrightarrow>\n    m dvd q \\<Longrightarrow>\n    \\<forall>m\\<in>{Suc (Suc 0)..<Suc n}. m dvd q \\<longrightarrow> q dvd m \\<Longrightarrow>\n    m dvd q \\<Longrightarrow> m \\<noteq> q \\<Longrightarrow> m = 1\" by auto\n  case True then show ?thesis\n    apply (auto simp add: One_nat_def numbers_of_marks_sieve numeral_2_eq_2 set_primes_upto\n        dest: prime_gt_Suc_0_nat)\n    apply (metis One_nat_def Suc_le_eq less_not_refl prime_nat_def)\n    apply (metis One_nat_def Suc_le_eq aux prime_nat_def)\n    done\nqed\n\nlemma primes_upto_sieve [code]:\n  \"primes_upto n = map fst (filter snd (enumerate 2 (sieve 1 (replicate (n - 1) True))))\"\nproof -\n  have \"primes_upto n = sorted_list_of_set (numbers_of_marks 2 (sieve 1 (replicate (n - 1) True)))\"\n    apply (rule sorted_distinct_set_unique)\n    apply (simp_all only: set_primes_upto_sieve numbers_of_marks_def)\n    apply auto\n    done\n  then show ?thesis by (simp add: sorted_list_of_set_numbers_of_marks)\nqed\n\nlemma prime_in_primes_upto:\n  \"prime n \\<longleftrightarrow> n \\<in> set (primes_upto n)\"\n  by (simp add: set_primes_upto)\n\n\nsubsection {* Application: smallest prime beyond a certain number *}\n\ndefinition smallest_prime_beyond :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"smallest_prime_beyond n = (LEAST p. prime p \\<and> p \\<ge> n)\"\n\nlemma\n  prime_smallest_prime_beyond [iff]: \"prime (smallest_prime_beyond n)\" (is ?P)\n  and smallest_prime_beyond_le [iff]: \"smallest_prime_beyond n \\<ge> n\" (is ?Q)\nproof -\n  let ?least = \"LEAST p. prime p \\<and> p \\<ge> n\"\n  from primes_infinite obtain q where \"prime q \\<and> q \\<ge> n\"\n    by (metis finite_nat_set_iff_bounded_le mem_Collect_eq nat_le_linear)\n  then have \"prime ?least \\<and> ?least \\<ge> n\" by (rule LeastI)\n  then show ?P and ?Q by (simp_all add: smallest_prime_beyond_def)\nqed\n\nlemma smallest_prime_beyond_smallest:\n  \"prime p \\<Longrightarrow> p \\<ge> n \\<Longrightarrow> smallest_prime_beyond n \\<le> p\"\n  by (simp only: smallest_prime_beyond_def) (auto intro: Least_le)\n\nlemma smallest_prime_beyond_eq:\n  \"prime p \\<Longrightarrow> p \\<ge> n \\<Longrightarrow> (\\<And>q. prime q \\<Longrightarrow> q \\<ge> n \\<Longrightarrow> q \\<ge> p) \\<Longrightarrow> smallest_prime_beyond n = p\"\n  by (simp only: smallest_prime_beyond_def) (auto intro: Least_equality)\n\ndefinition smallest_prime_between :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat option\"\nwhere\n  \"smallest_prime_between m n =\n    (if (\\<exists>p. prime p \\<and> m \\<le> p \\<and> p \\<le> n) then Some (smallest_prime_beyond m) else None)\"\n\nlemma smallest_prime_between_None:\n  \"smallest_prime_between m n = None \\<longleftrightarrow> (\\<forall>q. m \\<le> q \\<and> q \\<le> n \\<longrightarrow> \\<not> prime q)\"\n  by (auto simp add: smallest_prime_between_def)\n\nlemma smallest_prime_betwen_Some:\n  \"smallest_prime_between m n = Some p \\<longleftrightarrow> smallest_prime_beyond m = p \\<and> p \\<le> n\"\n  by (auto simp add: smallest_prime_between_def dest: smallest_prime_beyond_smallest [of _ m])\n\n\n\ndefinition smallest_prime_beyond_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"smallest_prime_beyond_aux k n = smallest_prime_beyond n\"\n\nlemma [code]:\n  \"smallest_prime_beyond_aux k n =\n    (case smallest_prime_between n (k * n)\n     of Some p \\<Rightarrow> p\n      | None \\<Rightarrow> smallest_prime_beyond_aux (Suc k) n)\"\n  by (simp add: smallest_prime_beyond_aux_def smallest_prime_betwen_Some split: option.split)\n\nlemma [code]:\n  \"smallest_prime_beyond n = smallest_prime_beyond_aux 2 n\"\n  by (simp add: smallest_prime_beyond_aux_def)\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Number_Theory/Eratosthenes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7936327520210372}}
{"text": "theory tmpl02_aexp\n  imports Main\nbegin\n\ntype_synonym vname = string\ntype_synonym state = \"string \\<Rightarrow> int\"\ntype_synonym val = \"int\"\n\ndeclare algebra_simps[simp]\n\ndatatype aexp = N int | V vname | Plus aexp aexp | Mult int aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\" |\n\"aval (Mult i a) s = i * aval a s\"\n\ntext \\<open>\n  \\textbf{Step A} Implement the function @{text normal} which returns @{const True} only when the\n  arithmetic expression is normalized.\n\\<close>\n\nfun normal :: \"aexp \\<Rightarrow> bool\" where\n  \"normal a = undefined\"\n\ntext \\<open>\n  \\textbf{Step B} Implement the function @{text normallize} which translates an arbitrary arithmetic\n  expression intro a normalized arithmetic expression.\n\\<close>\n\nfun normalize :: \"aexp \\<Rightarrow> aexp\" where\n  \"normalize a = undefined\"\n\ntext \\<open>\n  \\textbf{Step C} Prove that @{const normalize} does not change the result of the arithmetic\n  expression.\n\\<close>\n\nlemma \"aval (normalize a) s = aval a s\"\n  oops\n\ntext \\<open>\n  \\textbf{Step D} Prove that @{const normalize} does indeed return a normalized arithmetic\n  expression.\n\\<close>\n\nlemma \"normal (normalize a)\"\n  oops\n\nend\n\n", "meta": {"author": "glimonta", "repo": "Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "save_path": "github-repos/isabelle/glimonta-Semantics", "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise2/tmpl02_aexp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625069680097, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7935620979917957}}
{"text": "theory HSV_tasks_2021 imports Complex_Main begin\n\nsection \\<open>Task 1: Factorising circuits.\\<close>\n\n(* Datatype for representing simple circuits. *)\ndatatype \"circuit\" = \n  NOT \"circuit\"\n| AND \"circuit\" \"circuit\"\n| OR \"circuit\" \"circuit\"\n| TRUE\n| FALSE\n| INPUT \"int\"\n\n(* Simulates a circuit given a valuation for each input wire. *)\nfun simulate where\n  \"simulate (AND c1 c2) \\<rho> = ((simulate c1 \\<rho>) \\<and> (simulate c2 \\<rho>))\"\n| \"simulate (OR c1 c2) \\<rho> = ((simulate c1 \\<rho>) \\<or> (simulate c2 \\<rho>))\"\n| \"simulate (NOT c) \\<rho> = (\\<not> (simulate c \\<rho>))\"\n| \"simulate TRUE \\<rho> = True\"\n| \"simulate FALSE \\<rho> = False\"\n| \"simulate (INPUT i) \\<rho> = \\<rho> i\"\n\n(* Equivalence between circuits. *)\nfun circuits_equiv (infix \"\\<sim>\" 50) (* the \"50\" indicates the operator precedence *) where\n  \"c1 \\<sim> c2 = (\\<forall>\\<rho>. simulate c1 \\<rho> = simulate c2 \\<rho>)\"\n\n(* An optimisation that exploits the following Boolean identities:\n  `(a | b) & (a | c) = a | (b & c)`\n  `(a | b) & (c | a) = a | (b & c)`\n  `(a | b) & (b | c) = b | (a & c)`\n  `(a | b) & (c | b) = b | (a & c)`\n *)\nfun factorise where\n  \"factorise (NOT c) = NOT (factorise c)\"\n| \"factorise (AND (OR c1 c2) (OR c3 c4)) = (\n    let c1' = factorise c1; c2' = factorise c2; c3' = factorise c3; c4' = factorise c4 in\n    if c1' = c3' then OR c1' (AND c2' c4') \n    else if c1' = c4' then OR c1' (AND c2' c3') \n    else if c2' = c3' then OR c2' (AND c1' c4') \n    else if c2' = c4' then OR c2' (AND c1' c3') \n    else AND (OR c1' c2') (OR c3' c4'))\"\n| \"factorise (AND c1 c2) = AND (factorise c1) (factorise c2)\"\n| \"factorise (OR c1 c2) = OR (factorise c1) (factorise c2)\"\n| \"factorise TRUE = TRUE\"\n| \"factorise FALSE = FALSE\"\n| \"factorise (INPUT i) = INPUT i\"\n\nlemma (* test case *)\n \"factorise (AND TRUE TRUE) = AND TRUE TRUE\"\n  by eval\nlemma (* test case *)\n  \"factorise (AND (OR (INPUT 1) FALSE) (OR TRUE (INPUT 1))) = \n  OR (INPUT 1) (AND FALSE TRUE)\"\n  by eval\nlemma (* test case *)\n  \"factorise (NOT (AND (OR FALSE (INPUT 2)) (OR TRUE (INPUT 2)))) =\n  NOT (OR (INPUT 2) (AND FALSE TRUE))\"\n  by eval\n\ntheorem factorise_is_sound: \"factorise c \\<sim> c\"\n  sorry\n\nfun factorise2 where \"factorise2 c = c\" (* dummy definition *)\n\nlemma (* test case *)\n  \"factorise2 (OR (AND (INPUT 1) (INPUT 2)) (AND TRUE (INPUT 1))) = \n  AND (INPUT 1) (OR (INPUT 2) TRUE)\"\n  sorry\n\ntheorem factorise2_is_sound: \"factorise2 c \\<sim> c\"\n  sorry\n\nsection \\<open>Task 2: A theorem about divisibility.\\<close>\n\n(* NB: Without the \"::int\" annotation, Isabelle will try to prove a \n   slightly more general theorem where \"a\" and \"b\" can be either ints\n   or nats. That more general theorem is a little harder to prove. *)\ntheorem plus_dvd_odd_power:\n  \"(a::int) + b dvd a ^ (2 * n + 1) + b ^ (2 * n + 1)\"\n  sorry\n\n\nsection \\<open>Task 3: Proving that the shift-and-add-3 algorithm is correct.\\<close>\n\nsubsection \\<open>Binary and its conversion to nat\\<close>\n\ntype_synonym bit = \"bool\"\n\nabbreviation B0 where \"B0 == False\"\nabbreviation B1 where \"B1 == True\"\n\n\nfun binary_to_nat :: \"bit list \\<Rightarrow> nat\"\nwhere\n  \"binary_to_nat [] = 0\"\n| \"binary_to_nat (b # bs) = (if b then 2 ^ length bs else 0) + binary_to_nat bs\"\n\n\nlemma (* test case *) \"binary_to_nat [B0, B1, B0, B1] = 5\" by eval\nlemma (* test case *) \"binary_to_nat [B0, B0, B1, B0, B1] = 5\" by eval\nlemma (* test case *) \"binary_to_nat [B1] = 1\" by eval\nlemma (* test case *) \"binary_to_nat [B0] = 0\" by eval\n\nsubsection \\<open>BCD and its conversion to nat\\<close>\n\ntype_synonym nibble = \"bit * bit * bit * bit\"\n\nfun nibble_to_nat :: \"nibble \\<Rightarrow> nat\"\nwhere\n  \"nibble_to_nat (B0,B0,B0,B0) = 0\"\n| \"nibble_to_nat (B0,B0,B0,B1) = 1\"\n| \"nibble_to_nat (B0,B0,B1,B0) = 2\"\n| \"nibble_to_nat (B0,B0,B1,B1) = 3\"\n| \"nibble_to_nat (B0,B1,B0,B0) = 4\"\n| \"nibble_to_nat (B0,B1,B0,B1) = 5\"\n| \"nibble_to_nat (B0,B1,B1,B0) = 6\"\n| \"nibble_to_nat (B0,B1,B1,B1) = 7\"\n| \"nibble_to_nat (B1,B0,B0,B0) = 8\"\n| \"nibble_to_nat (B1,B0,B0,B1) = 9\"\n| \"nibble_to_nat (B1,B0,B1,B0) = 10\"\n| \"nibble_to_nat (B1,B0,B1,B1) = 11\"\n| \"nibble_to_nat (B1,B1,B0,B0) = 12\"\n| \"nibble_to_nat (B1,B1,B0,B1) = 13\"\n| \"nibble_to_nat (B1,B1,B1,B0) = 14\"\n| \"nibble_to_nat (B1,B1,B1,B1) = 15\"\n\nfun bcd_to_nat :: \"nibble list \\<Rightarrow> nat\"\nwhere\n  \"bcd_to_nat [] = 0\"\n| \"bcd_to_nat (n # ns) = bcd_to_nat ns + nibble_to_nat n * 10 ^ length ns\"\n\nlemma (* test case *) \"bcd_to_nat [(B0,B1,B1,B0)] = 6\" by eval\nlemma (* test case *) \"bcd_to_nat [(B0,B1,B1,B0),(B1,B0,B0,B1)] = 69\" by eval\nlemma (* test case *) \"bcd_to_nat [(B0,B0,B0,B0),(B1,B0,B0,B1)] = 9\" by eval\nlemma (* test case *) \"bcd_to_nat [(B0,B0,B1,B1),(B0,B0,B0,B0)] = 30\" by eval\n\n\nsubsection \\<open>Converting binary to BCD\\<close>\n\nfun binary_to_bcd :: \"bit list \\<Rightarrow> nibble list\"\nwhere\n  \"binary_to_bcd bs = []\" (* dummy definition *)  \n\nlemma (* test case *)\n  \"binary_to_bcd [B1,B0,B1,B0,B1,B0,B1] = [(B1,B0,B0,B0), (B0,B1,B0,B1)]\" \n  sorry\n\nsubsection \\<open>Checking that nibbles correspond to valid BCD digits\\<close>\n\nfun valid_nibble :: \"nibble \\<Rightarrow> bool\"\nwhere\n  \"valid_nibble (B0,B0,B0,B0) = True\"\n| \"valid_nibble (B0,B0,B0,B1) = True\"\n| \"valid_nibble (B0,B0,B1,B0) = True\"\n| \"valid_nibble (B0,B0,B1,B1) = True\"\n| \"valid_nibble (B0,B1,B0,B0) = True\"\n| \"valid_nibble (B0,B1,B0,B1) = True\"\n| \"valid_nibble (B0,B1,B1,B0) = True\"\n| \"valid_nibble (B0,B1,B1,B1) = True\"\n| \"valid_nibble (B1,B0,B0,B0) = True\"\n| \"valid_nibble (B1,B0,B0,B1) = True\"\n| \"valid_nibble (B1,B0,B1,B0) = False\"\n| \"valid_nibble (B1,B0,B1,B1) = False\"\n| \"valid_nibble (B1,B1,B0,B0) = False\"\n| \"valid_nibble (B1,B1,B0,B1) = False\"\n| \"valid_nibble (B1,B1,B1,B0) = False\"\n| \"valid_nibble (B1,B1,B1,B1) = False\"\n\ntheorem binary_to_bcd_valid:\n  \"list_all valid_nibble (binary_to_bcd bs)\"\n  sorry\n  \nsubsection \\<open>Proof that the binary_to_bcd translation is correct.\\<close>\n\ntheorem binary_to_bcd_correct:\n  \"bcd_to_nat (binary_to_bcd bs) = binary_to_nat bs\"\n  sorry\n\nend", "meta": {"author": "johnwickerson", "repo": "HSV", "sha": "54be339e0fac44ee7af8ebba9dab10d778164ea3", "save_path": "github-repos/isabelle/johnwickerson-HSV", "path": "github-repos/isabelle/johnwickerson-HSV/HSV-54be339e0fac44ee7af8ebba9dab10d778164ea3/isabelle/2021/HSV_tasks_2021.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7934097459118844}}
{"text": "(*  Title:      HOL/Number_Theory/Fib.thy\n    Author:     Lawrence C. Paulson\n    Author:     Jeremy Avigad\n    Author:     Manuel Eberl\n*)\n\nsection \\<open>The fibonacci function\\<close>\n\ntheory Fib\n  imports Complex_Main\nbegin\n\n\nsubsection \\<open>Fibonacci numbers\\<close>\n\nfun fib :: \"nat \\<Rightarrow> nat\"\n  where\n    fib0: \"fib 0 = 0\"\n  | fib1: \"fib (Suc 0) = 1\"\n  | fib2: \"fib (Suc (Suc n)) = fib (Suc n) + fib n\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma fib_1 [simp]: \"fib 1 = 1\"\n  by (metis One_nat_def fib1)\n\nlemma fib_2 [simp]: \"fib 2 = 1\"\n  using fib.simps(3) [of 0] by (simp add: numeral_2_eq_2)\n\nlemma fib_plus_2: \"fib (n + 2) = fib (n + 1) + fib n\"\n  by (metis Suc_eq_plus1 add_2_eq_Suc' fib.simps(3))\n\nlemma fib_add: \"fib (Suc (n + k)) = fib (Suc k) * fib (Suc n) + fib k * fib n\"\n  by (induct n rule: fib.induct) (auto simp add: field_simps)\n\nlemma fib_neq_0_nat: \"n > 0 \\<Longrightarrow> fib n > 0\"\n  by (induct n rule: fib.induct) auto\n\nlemma fib_Suc_mono: \"fib m \\<le> fib (Suc m)\"\nby(induction m) auto\n\nlemma fib_mono: \"m \\<le> n \\<Longrightarrow> fib m \\<le> fib n\"\nby (simp add: fib_Suc_mono lift_Suc_mono_le)\n\nsubsection \\<open>More efficient code\\<close>\n\ntext \\<open>\n  The naive approach is very inefficient since the branching recursion leads to many\n  values of \\<^term>\\<open>fib\\<close> being computed multiple times. We can avoid this by ``remembering''\n  the last two values in the sequence, yielding a tail-recursive version.\n  This is far from optimal (it takes roughly $O(n\\cdot M(n))$ time where $M(n)$ is the\n  time required to multiply two $n$-bit integers), but much better than the naive version,\n  which is exponential.\n\\<close>\n\nfun gen_fib :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"gen_fib a b 0 = a\"\n  | \"gen_fib a b (Suc 0) = b\"\n  | \"gen_fib a b (Suc (Suc n)) = gen_fib b (a + b) (Suc n)\"\n\nlemma gen_fib_recurrence: \"gen_fib a b (Suc (Suc n)) = gen_fib a b n + gen_fib a b (Suc n)\"\n  by (induct a b n rule: gen_fib.induct) simp_all\n\nlemma gen_fib_fib: \"gen_fib (fib n) (fib (Suc n)) m = fib (n + m)\"\n  by (induct m rule: fib.induct) (simp_all del: gen_fib.simps(3) add: gen_fib_recurrence)\n\nlemma fib_conv_gen_fib: \"fib n = gen_fib 0 1 n\"\n  using gen_fib_fib[of 0 n] by simp\n\ndeclare fib_conv_gen_fib [code]\n\n\nsubsection \\<open>A Few Elementary Results\\<close>\n\ntext \\<open>\n  \\<^medskip> Concrete Mathematics, page 278: Cassini's identity.  The proof is\n  much easier using integers, not natural numbers!\n\\<close>\n\nlemma fib_Cassini_int: \"int (fib (Suc (Suc n)) * fib n) - int((fib (Suc n))\\<^sup>2) = - ((-1)^n)\"\n  by (induct n rule: fib.induct) (auto simp add: field_simps power2_eq_square power_add)\n\nlemma fib_Cassini_nat:\n  \"fib (Suc (Suc n)) * fib n =\n     (if even n then (fib (Suc n))\\<^sup>2 - 1 else (fib (Suc n))\\<^sup>2 + 1)\"\n  using fib_Cassini_int [of n] by (auto simp del: of_nat_mult of_nat_power)\n\n\nsubsection \\<open>Law 6.111 of Concrete Mathematics\\<close>\n\nlemma coprime_fib_Suc_nat: \"coprime (fib n) (fib (Suc n))\"\n  apply (induct n rule: fib.induct)\n    apply (simp_all add: coprime_iff_gcd_eq_1 algebra_simps)\n  apply (simp add: add.assoc [symmetric])\n  done\n\nlemma gcd_fib_add:\n  \"gcd (fib m) (fib (n + m)) = gcd (fib m) (fib n)\"\nproof (cases m)\n  case 0\n  then show ?thesis\n    by simp\nnext\n  case (Suc q)\n  from coprime_fib_Suc_nat [of q]\n  have \"coprime (fib (Suc q)) (fib q)\"\n    by (simp add: ac_simps)\n  have \"gcd (fib q) (fib (Suc q)) = Suc 0\"\n    using coprime_fib_Suc_nat [of q] by simp\n  then have *: \"gcd (fib n * fib q) (fib n * fib (Suc q)) = fib n\"\n    by (simp add: gcd_mult_distrib_nat [symmetric])\n  moreover have \"gcd (fib (Suc q)) (fib n * fib q + fib (Suc n) * fib (Suc q)) =\n    gcd (fib (Suc q)) (fib n * fib q)\"\n    using gcd_add_mult [of \"fib (Suc q)\"] by (simp add: ac_simps)\n  moreover have \"gcd (fib (Suc q)) (fib n * fib (Suc q)) = fib (Suc q)\"\n    by simp\n  ultimately show ?thesis\n    using Suc \\<open>coprime (fib (Suc q)) (fib q)\\<close>\n    by (auto simp add: fib_add algebra_simps gcd_mult_right_right_cancel)\nqed\n\nlemma gcd_fib_diff: \"m \\<le> n \\<Longrightarrow> gcd (fib m) (fib (n - m)) = gcd (fib m) (fib n)\"\n  by (simp add: gcd_fib_add [symmetric, of _ \"n-m\"])\n\nlemma gcd_fib_mod: \"0 < m \\<Longrightarrow> gcd (fib m) (fib (n mod m)) = gcd (fib m) (fib n)\"\nproof (induct n rule: less_induct)\n  case (less n)\n  show \"gcd (fib m) (fib (n mod m)) = gcd (fib m) (fib n)\"\n  proof (cases \"m < n\")\n    case True\n    then have \"m \\<le> n\" by auto\n    with \\<open>0 < m\\<close> have \"0 < n\" by auto\n    with \\<open>0 < m\\<close> \\<open>m < n\\<close> have *: \"n - m < n\" by auto\n    have \"gcd (fib m) (fib (n mod m)) = gcd (fib m) (fib ((n - m) mod m))\"\n      by (simp add: mod_if [of n]) (use \\<open>m < n\\<close> in auto)\n    also have \"\\<dots> = gcd (fib m)  (fib (n - m))\"\n      by (simp add: less.hyps * \\<open>0 < m\\<close>)\n    also have \"\\<dots> = gcd (fib m) (fib n)\"\n      by (simp add: gcd_fib_diff \\<open>m \\<le> n\\<close>)\n    finally show \"gcd (fib m) (fib (n mod m)) = gcd (fib m) (fib n)\" .\n  next\n    case False\n    then show \"gcd (fib m) (fib (n mod m)) = gcd (fib m) (fib n)\"\n      by (cases \"m = n\") auto\n  qed\nqed\n\nlemma fib_gcd: \"fib (gcd m n) = gcd (fib m) (fib n)\"  \\<comment> \\<open>Law 6.111\\<close>\n  by (induct m n rule: gcd_nat_induct) (simp_all add: gcd_non_0_nat gcd.commute gcd_fib_mod)\n\ntheorem fib_mult_eq_sum_nat: \"fib (Suc n) * fib n = (\\<Sum>k \\<in> {..n}. fib k * fib k)\"\n  by (induct n rule: nat.induct) (auto simp add:  field_simps)\n\n\nsubsection \\<open>Closed form\\<close>\n\nlemma fib_closed_form:\n  fixes \\<phi> \\<psi> :: real\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n    and \"\\<psi> \\<equiv> (1 - sqrt 5) / 2\"\n  shows \"of_nat (fib n) = (\\<phi> ^ n - \\<psi> ^ n) / sqrt 5\"\nproof (induct n rule: fib.induct)\n  fix n :: nat\n  assume IH1: \"of_nat (fib n) = (\\<phi> ^ n - \\<psi> ^ n) / sqrt 5\"\n  assume IH2: \"of_nat (fib (Suc n)) = (\\<phi> ^ Suc n - \\<psi> ^ Suc n) / sqrt 5\"\n  have \"of_nat (fib (Suc (Suc n))) = of_nat (fib (Suc n)) + of_nat (fib n)\" by simp\n  also have \"\\<dots> = (\\<phi>^n * (\\<phi> + 1) - \\<psi>^n * (\\<psi> + 1)) / sqrt 5\"\n    by (simp add: IH1 IH2 field_simps)\n  also have \"\\<phi> + 1 = \\<phi>\\<^sup>2\" by (simp add: \\<phi>_def field_simps power2_eq_square)\n  also have \"\\<psi> + 1 = \\<psi>\\<^sup>2\" by (simp add: \\<psi>_def field_simps power2_eq_square)\n  also have \"\\<phi>^n * \\<phi>\\<^sup>2 - \\<psi>^n * \\<psi>\\<^sup>2 = \\<phi> ^ Suc (Suc n) - \\<psi> ^ Suc (Suc n)\"\n    by (simp add: power2_eq_square)\n  finally show \"of_nat (fib (Suc (Suc n))) = (\\<phi> ^ Suc (Suc n) - \\<psi> ^ Suc (Suc n)) / sqrt 5\" .\nqed (simp_all add: \\<phi>_def \\<psi>_def field_simps)\n\nlemma fib_closed_form':\n  fixes \\<phi> \\<psi> :: real\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n    and \"\\<psi> \\<equiv> (1 - sqrt 5) / 2\"\n  assumes \"n > 0\"\n  shows \"fib n = round (\\<phi> ^ n / sqrt 5)\"\nproof (rule sym, rule round_unique')\n  have \"\\<bar>\\<phi> ^ n / sqrt 5 - of_int (int (fib n))\\<bar> = \\<bar>\\<psi>\\<bar> ^ n / sqrt 5\"\n    by (simp add: fib_closed_form[folded \\<phi>_def \\<psi>_def] field_simps power_abs)\n  also {\n    from assms have \"\\<bar>\\<psi>\\<bar>^n \\<le> \\<bar>\\<psi>\\<bar>^1\"\n      by (intro power_decreasing) (simp_all add: algebra_simps real_le_lsqrt)\n    also have \"\\<dots> < sqrt 5 / 2\" by (simp add: \\<psi>_def field_simps)\n    finally have \"\\<bar>\\<psi>\\<bar>^n / sqrt 5 < 1/2\" by (simp add: field_simps)\n  }\n  finally show \"\\<bar>\\<phi> ^ n / sqrt 5 - of_int (int (fib n))\\<bar> < 1/2\" .\nqed\n\nlemma fib_asymptotics:\n  fixes \\<phi> :: real\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n  shows \"(\\<lambda>n. real (fib n) / (\\<phi> ^ n / sqrt 5)) \\<longlonglongrightarrow> 1\"\nproof -\n  define \\<psi> :: real where \"\\<psi> \\<equiv> (1 - sqrt 5) / 2\"\n  have \"\\<phi> > 1\" by (simp add: \\<phi>_def)\n  then have *: \"\\<phi> \\<noteq> 0\" by auto\n  have \"(\\<lambda>n. (\\<psi> / \\<phi>) ^ n) \\<longlonglongrightarrow> 0\"\n    by (rule LIMSEQ_power_zero) (simp_all add: \\<phi>_def \\<psi>_def field_simps add_pos_pos)\n  then have \"(\\<lambda>n. 1 - (\\<psi> / \\<phi>) ^ n) \\<longlonglongrightarrow> 1 - 0\"\n    by (intro tendsto_diff tendsto_const)\n  with * have \"(\\<lambda>n. (\\<phi> ^ n - \\<psi> ^ n) / \\<phi> ^ n) \\<longlonglongrightarrow> 1\"\n    by (simp add: field_simps)\n  then show ?thesis\n    by (simp add: fib_closed_form \\<phi>_def \\<psi>_def)\nqed\n\n\nsubsection \\<open>Divide-and-Conquer recurrence\\<close>\n\ntext \\<open>\n  The following divide-and-conquer recurrence allows for a more efficient computation\n  of Fibonacci numbers; however, it requires memoisation of values to be reasonably\n  efficient, cutting the number of values to be computed to logarithmically many instead of\n  linearly many. The vast majority of the computation time is then actually spent on the\n  multiplication, since the output number is exponential in the input number.\n\\<close>\n\nlemma fib_rec_odd:\n  fixes \\<phi> \\<psi> :: real\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n    and \"\\<psi> \\<equiv> (1 - sqrt 5) / 2\"\n  shows \"fib (Suc (2 * n)) = fib n^2 + fib (Suc n)^2\"\nproof -\n  have \"of_nat (fib n^2 + fib (Suc n)^2) = ((\\<phi> ^ n - \\<psi> ^ n)\\<^sup>2 + (\\<phi> * \\<phi> ^ n - \\<psi> * \\<psi> ^ n)\\<^sup>2)/5\"\n    by (simp add: fib_closed_form[folded \\<phi>_def \\<psi>_def] field_simps power2_eq_square)\n  also\n  let ?A = \"\\<phi>^(2 * n) + \\<psi>^(2 * n) - 2*(\\<phi> * \\<psi>)^n + \\<phi>^(2 * n + 2) + \\<psi>^(2 * n + 2) - 2*(\\<phi> * \\<psi>)^(n + 1)\"\n  have \"(\\<phi> ^ n - \\<psi> ^ n)\\<^sup>2 + (\\<phi> * \\<phi> ^ n - \\<psi> * \\<psi> ^ n)\\<^sup>2 = ?A\"\n    by (simp add: power2_eq_square algebra_simps power_mult power_mult_distrib)\n  also have \"\\<phi> * \\<psi> = -1\"\n    by (simp add: \\<phi>_def \\<psi>_def field_simps)\n  then have \"?A = \\<phi>^(2 * n + 1) * (\\<phi> + inverse \\<phi>) + \\<psi>^(2 * n + 1) * (\\<psi> + inverse \\<psi>)\"\n    by (auto simp: field_simps power2_eq_square)\n  also have \"1 + sqrt 5 > 0\"\n    by (auto intro: add_pos_pos)\n  then have \"\\<phi> + inverse \\<phi> = sqrt 5\"\n    by (simp add: \\<phi>_def field_simps)\n  also have \"\\<psi> + inverse \\<psi> = -sqrt 5\"\n    by (simp add: \\<psi>_def field_simps)\n  also have \"(\\<phi> ^ (2 * n + 1) * sqrt 5 + \\<psi> ^ (2 * n + 1) * - sqrt 5) / 5 =\n    (\\<phi> ^ (2 * n + 1) - \\<psi> ^ (2 * n + 1)) * (sqrt 5 / 5)\"\n    by (simp add: field_simps)\n  also have \"sqrt 5 / 5 = inverse (sqrt 5)\"\n    by (simp add: field_simps)\n  also have \"(\\<phi> ^ (2 * n + 1) - \\<psi> ^ (2 * n + 1)) * \\<dots> = of_nat (fib (Suc (2 * n)))\"\n    by (simp add: fib_closed_form[folded \\<phi>_def \\<psi>_def] divide_inverse)\n  finally show ?thesis\n    by (simp only: of_nat_eq_iff)\nqed\n\nlemma fib_rec_even: \"fib (2 * n) = (fib (n - 1) + fib (n + 1)) * fib n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  let ?rfib = \"\\<lambda>x. real (fib x)\"\n  have \"2 * (Suc n) = Suc (Suc (2 * n))\" by simp\n  also have \"real (fib \\<dots>) = ?rfib n^2 + ?rfib (Suc n)^2 + (?rfib (n - 1) + ?rfib (n + 1)) * ?rfib n\"\n    by (simp add: fib_rec_odd Suc)\n  also have \"(?rfib (n - 1) + ?rfib (n + 1)) * ?rfib n = (2 * ?rfib (n + 1) - ?rfib n) * ?rfib n\"\n    by (cases n) simp_all\n  also have \"?rfib n^2 + ?rfib (Suc n)^2 + \\<dots> = (?rfib (Suc n) + 2 * ?rfib n) * ?rfib (Suc n)\"\n    by (simp add: algebra_simps power2_eq_square)\n  also have \"\\<dots> = real ((fib (Suc n - 1) + fib (Suc n + 1)) * fib (Suc n))\" by simp\n  finally show ?case by (simp only: of_nat_eq_iff)\nqed\n\nlemma fib_rec_even': \"fib (2 * n) = (2 * fib (n - 1) + fib n) * fib n\"\n  by (subst fib_rec_even, cases n) simp_all\n\nlemma fib_rec:\n  \"fib n =\n    (if n = 0 then 0 else if n = 1 then 1\n     else if even n then let n' = n div 2; fn = fib n' in (2 * fib (n' - 1) + fn) * fn\n     else let n' = n div 2 in fib n' ^ 2 + fib (Suc n') ^ 2)\"\n  by (auto elim: evenE oddE simp: fib_rec_odd fib_rec_even' Let_def)\n\n\nsubsection \\<open>Fibonacci and Binomial Coefficients\\<close>\n\nlemma sum_drop_zero: \"(\\<Sum>k = 0..Suc n. if 0<k then (f (k - 1)) else 0) = (\\<Sum>j = 0..n. f j)\"\n  by (induct n) auto\n\nlemma sum_choose_drop_zero:\n  \"(\\<Sum>k = 0..Suc n. if k = 0 then 0 else (Suc n - k) choose (k - 1)) =\n    (\\<Sum>j = 0..n. (n-j) choose j)\"\n  by (rule trans [OF sum.cong sum_drop_zero]) auto\n\nlemma ne_diagonal_fib: \"(\\<Sum>k = 0..n. (n-k) choose k) = fib (Suc n)\"\nproof (induct n rule: fib.induct)\n  case 1\n  show ?case by simp\nnext\n  case 2\n  show ?case by simp\nnext\n  case (3 n)\n  have \"(\\<Sum>k = 0..Suc n. Suc (Suc n) - k choose k) =\n     (\\<Sum>k = 0..Suc n. (Suc n - k choose k) + (if k = 0 then 0 else (Suc n - k choose (k - 1))))\"\n    by (rule sum.cong) (simp_all add: choose_reduce_nat)\n  also have \"\\<dots> =\n    (\\<Sum>k = 0..Suc n. Suc n - k choose k) +\n    (\\<Sum>k = 0..Suc n. if k=0 then 0 else (Suc n - k choose (k - 1)))\"\n    by (simp add: sum.distrib)\n  also have \"\\<dots> = (\\<Sum>k = 0..Suc n. Suc n - k choose k) + (\\<Sum>j = 0..n. n - j choose j)\"\n    by (metis sum_choose_drop_zero)\n  finally show ?case using 3\n    by simp\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Number_Theory/Fib.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.9207896758909756, "lm_q1q2_score": 0.7932955017237753}}
{"text": "theory FiniteGraph\nimports Main \nbegin\n\n(*Lots of this theory is based on a work by Benedikt Nordhoff and Peter Lammich*)\n\nsection {*Specification of a finite directed graph*}\n\ntext{* A graph @{text \"G=(V,E)\"} consits of a set of vertices @{text V}, also called nodes, \n       and a set of edges @{text E}. The edges are tuples of vertices. Both, \n       the set of vertices and edges is finite. *}\n\n(* Inspired by\nTitle: Dijkstra's Shortest Path Algorithm\nAuthor: Benedikt Nordhoff and Peter Lammich\nhttp://isa-afp.org/entries/Dijkstra_Shortest_Path.shtml\n*)\n\nsection {* Graph  *}\nsubsection{*Definitions*}\n  text {* A graph is represented by a record. *}\n  record 'v graph =\n    nodes :: \"'v set\"\n    edges :: \"('v \\<times>'v) set\"\n\n  text {* In a well-formed graph, edges only go from nodes to nodes. *}\n  locale wf_graph = \n    fixes G :: \"'v graph\"\n    -- \"Edges only reference to existing nodes\"\n    assumes E_wf: \"fst ` (edges G) \\<subseteq> (nodes G)\"\n                     \"snd ` (edges G) \\<subseteq> (nodes G)\"\n    and finiteE: \"finite (edges G)\" (*implied by finiteV*)\n    and finiteV: \"finite (nodes G)\"\n  begin\n    abbreviation \"V \\<equiv> (nodes G)\"\n    abbreviation \"E \\<equiv> (edges G)\"\n\n    \n\n    lemma E_wfD2: \"\\<forall>e \\<in> E. fst e \\<in> V \\<and> snd e \\<in> V\"\n    by (auto simp add: E_wfD)\n  end\n\nsubsection {* Basic operations on Graphs *}\n  text {* The empty graph. *}\n  definition empty :: \"'v graph\" where \n    \"empty \\<equiv> \\<lparr> nodes = {}, edges = {} \\<rparr>\"\n\n  text {* Adds a node to a graph. *}\n  definition add_node :: \"'v \\<Rightarrow> 'v graph \\<Rightarrow> 'v graph\" where \n    \"add_node v G \\<equiv> \\<lparr> nodes = ({v} \\<union> (nodes G)), edges=edges G \\<rparr>\"\n\n  text {* Deletes a node from a graph. Also deletes all adjacent edges. *}\n  definition delete_node where \"delete_node v G \\<equiv> \\<lparr> \n      nodes = (nodes G) - {v},   \n      edges = {(e1, e2). (e1, e2) \\<in> edges G \\<and> e1 \\<noteq> v \\<and> e2 \\<noteq> v}\n    \\<rparr>\"\n\n  text {* Adds an edge to a graph. *}\n  definition add_edge where \n  \"add_edge v v' G = \\<lparr>nodes = nodes G \\<union> {v,v'}, edges = {(v, v')} \\<union> edges G \\<rparr>\"\n\n  text {* Deletes an edge from a graph. *}\n  definition delete_edge where \"delete_edge v v' G \\<equiv> \\<lparr>\n      nodes = nodes G, \n      edges = {(e1,e2). (e1, e2) \\<in> edges G \\<and> (e1,e2) \\<noteq> (v,v')}\n    \\<rparr>\"\n  \n  definition delete_edges::\"'v graph \\<Rightarrow> ('v \\<times> 'v) set \\<Rightarrow> 'v graph\" where \n    \"delete_edges G es \\<equiv> \\<lparr>\n      nodes = nodes G, \n      edges = {(e1,e2). (e1, e2) \\<in> edges G \\<and> (e1,e2) \\<notin> es}\n    \\<rparr>\"\n\n  fun delete_edges_list::\"'v graph \\<Rightarrow> ('v \\<times> 'v) list \\<Rightarrow> 'v graph\" where \n    \"delete_edges_list G [] = G\"|\n    \"delete_edges_list G ((v,v')#es) = delete_edges_list (delete_edge v v' G) es\"\n\n  definition fully_connected :: \"'v graph \\<Rightarrow> 'v graph\" where\n    \"fully_connected G \\<equiv> \\<lparr>nodes = nodes G, edges = nodes G \\<times> nodes G \\<rparr>\"\n\n\ntext {* Extended graph operations *}\n  text {* Reflexive transitive successors of a node. Or: All reachable nodes for @{text v} including @{text v}. *}\n  definition succ_rtran :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> 'v set\" where\n    \"succ_rtran G v = {e2. (v,e2) \\<in> (edges G)\\<^sup>*}\"\n\n  text {* Transitive successors of a node. Or: All reachable nodes for @{text v}. *}\n  definition succ_tran :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> 'v set\" where\n    \"succ_tran G v = {e2. (v,e2) \\<in> (edges G)\\<^sup>+}\"\n\n  --\"succ_tran is always finite\"\n  lemma succ_tran_finite: \"wf_graph G \\<Longrightarrow> finite (succ_tran G v)\"\n  proof -\n    assume \"wf_graph G\"\n    from wf_graph.finiteE[OF this] have \"finite ((edges G)\\<^sup>+)\" using finite_trancl[symmetric, of \"edges G\"] by metis\n    from this have \"finite {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by simp\n    from this have finite: \"finite (snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+})\" by (metis finite_imageI)\n    have \"{(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+ \\<and> e1 = v} \\<subseteq> {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by blast\n    have 1: \"snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+ \\<and> e1 = v} \\<subseteq> snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by blast\n    have 2: \"snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+ \\<and> e1 = v} = {e2. (v,e2) \\<in> (edges G)\\<^sup>+}\" by force\n    from 1 2 have \"{e2. (v,e2) \\<in> (edges G)\\<^sup>+} \\<subseteq> snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by blast\n    from this finite have \"finite {e2. (v, e2) \\<in> (edges G)\\<^sup>+}\" by (metis finite_subset)\n    thus \"finite (succ_tran G v)\" using succ_tran_def by metis\n  qed\n  \n  text{* If there is no edge leaving from @{text v}, then @{text v} has no successors *}\n  lemma succ_tran_empty: \"\\<lbrakk> wf_graph G; v \\<notin> (fst ` edges G) \\<rbrakk> \\<Longrightarrow> succ_tran G v = {}\"\n    unfolding succ_tran_def using image_iff tranclD by fastforce\n\n  text{* @{const succ_tran} is subset of nodes *}\n  lemma succ_tran_subseteq_nodes: \"\\<lbrakk> wf_graph G \\<rbrakk> \\<Longrightarrow> succ_tran G v \\<subseteq> nodes G\"\n    unfolding succ_tran_def using tranclD2 wf_graph.E_wfD(2) by fastforce\n\n  text {* The number of reachable nodes from @{text v} *}\n  definition num_reachable :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n    \"num_reachable G v = card (succ_tran G v)\"\n\n  definition num_reachable_norefl :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n    \"num_reachable_norefl G v = card (succ_tran G v - {v})\"\n\n  text{*@{const card} returns @{term 0} for infinite sets.\n        Here, for a well-formed graph, if @{const num_reachable} is zero, there are actually no nodes reachable.*}\n  lemma num_reachable_zero: \"\\<lbrakk>wf_graph G; num_reachable G v = 0\\<rbrakk> \\<Longrightarrow> succ_tran G v = {}\"\n  unfolding num_reachable_def\n  apply(subgoal_tac \"finite (succ_tran G v)\")\n   apply(simp)\n  apply(blast intro: succ_tran_finite)\n  done\n  lemma num_succtran_zero: \"\\<lbrakk>succ_tran G v = {}\\<rbrakk> \\<Longrightarrow> num_reachable G v = 0\"\n    unfolding num_reachable_def by simp\n  lemma num_reachable_zero_iff: \"\\<lbrakk>wf_graph G\\<rbrakk> \\<Longrightarrow> (num_reachable G v = 0) \\<longleftrightarrow> (succ_tran G v = {})\"\n  by(metis num_succtran_zero num_reachable_zero)\n\n\nsection{*Undirected Graph*}\n\nsubsection{*undirected graph simulation*}\n  text {* Create undirected graph from directed graph by adding backward links *}\n\n  definition backflows :: \"('v \\<times> 'v) set \\<Rightarrow> ('v \\<times> 'v) set\" where\n    \"backflows E \\<equiv> {(r,s). (s,r) \\<in> E}\"\n\n  definition undirected :: \"'v graph \\<Rightarrow> 'v graph\"\n    where \"undirected G = \\<lparr> nodes = nodes G, edges = (edges G) \\<union> {(b,a). (a,b) \\<in> edges G} \\<rparr>\"\n\nsection {*Graph Lemmas*}\n\n  lemma graph_eq_intro: \"(nodes (G::'a graph) = nodes G') \\<Longrightarrow> (edges G = edges G') \\<Longrightarrow> G = G'\" by simp\n\n  -- \"finite\"\n  lemma wf_graph_finite_filterE: \"wf_graph G \\<Longrightarrow> finite {(e1, e2). (e1, e2) \\<in> edges G \\<and> P e1 e2}\"\n  by(simp add: wf_graph.finiteE split_def)\n  lemma wf_graph_finite_filterV: \"wf_graph G \\<Longrightarrow> finite {n. n \\<in> nodes G \\<and> P n}\"\n  by(simp add: wf_graph.finiteV)\n\n  -- \"empty\"\n  lemma empty_wf[simp]: \"wf_graph empty\"\n    unfolding empty_def by unfold_locales auto\n  lemma nodes_empty[simp]: \"nodes empty = {}\" unfolding empty_def by simp\n  lemma edges_empty[simp]: \"edges empty = {}\" unfolding empty_def by simp\n\n  -- \"add node\"\n  lemma add_node_wf[simp]: \"wf_graph g \\<Longrightarrow> wf_graph (add_node v g)\"\n    unfolding add_node_def wf_graph_def by (auto)\n\n  lemma delete_node_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_node v G)\"\n    by(auto simp add: delete_node_def wf_graph_def wf_graph_finite_filterE)\n\n  -- \"add edgde\"\n  lemma add_edge_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (add_edge v v' G)\"\n    by(auto simp add: add_edge_def add_node_def wf_graph_def)\n\n  -- \"delete edge\"\n  lemma delete_edge_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_edge v v' G)\"\n    by(auto simp add: delete_edge_def add_node_def wf_graph_def split_def)\n \n  -- \"delte edges\"\n  lemma delete_edges_list_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_edges_list G E)\"\n    by(induction E arbitrary: G, simp, force)\n  lemma delete_edges_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_edges G E)\"\n    by(auto simp add: delete_edges_def add_node_def wf_graph_def split_def)\n  lemma delete_edges_list_set: \"delete_edges_list G E = delete_edges G (set E)\"\n    proof(induction E arbitrary: G)\n    case Nil thus ?case by (simp add: delete_edges_def)\n    next\n    case (Cons e E) thus ?case by(cases e)(simp add: delete_edge_def delete_edges_def)\n    qed\n  lemma delete_edges_list_union: \"delete_edges_list G (ff @ keeps) = delete_edges G (set ff \\<union> set keeps)\"\n   by(simp add: delete_edges_list_set)\n  lemma add_edge_delete_edges_list: \n    \"(add_edge (fst a) (snd a) (delete_edges_list G (a # ff))) = (add_edge (fst a) (snd a) (delete_edges G (set ff)))\"\n   by(auto simp add: delete_edges_list_set delete_edges_def add_edge_def add_node_def)\n  lemma delete_edges_empty[simp]: \"delete_edges G {} = G\"\n   by(simp add: delete_edges_def)\n  lemma delete_edges_simp2: \"delete_edges G E = \\<lparr> nodes = nodes G, edges = edges G - E\\<rparr>\"\n   by(auto simp add: delete_edges_def)\n  lemma delete_edges_set_nodes: \"nodes (delete_edges G E) = nodes G\"\n   by(simp add: delete_edges_simp2)\n  lemma delete_edges_edges_mono: \"E' \\<subseteq> E \\<Longrightarrow> edges (delete_edges G E) \\<subseteq> edges (delete_edges G E')\"\n    by(simp add: delete_edges_def, fast)\n  lemma delete_edges_edges_empty: \"(delete_edges G (edges G)) = G\\<lparr>edges := {}\\<rparr>\"\n    by(simp add: delete_edges_simp2)\n\n --\"add delete\"\n  lemma add_delete_edge: \"wf_graph (G::'a graph) \\<Longrightarrow> (a,b) \\<in> edges G \\<Longrightarrow> add_edge a b (delete_edge a b G) = G\"\n   apply(simp add: delete_edge_def add_edge_def wf_graph_def)\n   apply(intro graph_eq_intro)\n    by auto\n\n  lemma add_delete_edges: \"wf_graph (G::'v graph) \\<Longrightarrow> (a,b) \\<in> edges G \\<Longrightarrow> (a,b) \\<notin> fs \\<Longrightarrow>\n    add_edge a b (delete_edges G (insert (a, b) fs)) = (delete_edges G fs)\"\n    by(auto simp add: delete_edges_simp2 add_edge_def wf_graph_def)\n\n\n --\"fully_connected\"\n  lemma fully_connected_simp: \"fully_connected \\<lparr>nodes = N, edges = ignore \\<rparr>\\<equiv> \\<lparr>nodes = N, edges = N \\<times> N \\<rparr>\"\n    by(simp add: fully_connected_def)\n  lemma fully_connected_wf: \"wf_graph G \\<Longrightarrow> wf_graph (fully_connected G)\"\n    by(simp add: fully_connected_def wf_graph_def)\n\n --\"succ_tran\"\n lemma succ_tran_mono: \n  \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> E' \\<subseteq> E \\<Longrightarrow> succ_tran \\<lparr>nodes=N, edges=E'\\<rparr> v \\<subseteq> succ_tran \\<lparr>nodes=N, edges=E\\<rparr> v\"\n   apply(drule wf_graph.finiteE)\n   apply(frule_tac A=\"E'\" in rev_finite_subset, simp)\n   apply(simp add: num_reachable_def)\n   apply(simp add: succ_tran_def)\n   apply(metis (lifting, full_types) Collect_mono trancl_mono)\n  done\n\n  --\"num_reachable\"\n  lemma num_reachable_mono:\n  \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> E' \\<subseteq> E \\<Longrightarrow> num_reachable \\<lparr>nodes=N, edges=E'\\<rparr> v \\<le> num_reachable \\<lparr>nodes=N, edges=E\\<rparr> v\"\n   apply(simp add: num_reachable_def)\n   apply(frule_tac E'=\"E'\" and v=\"v\" in succ_tran_mono, simp)\n   apply(frule_tac v=\"v\" in succ_tran_finite)\n   apply(simp add: card_mono)\n  done\n\n  --\"num_reachable_norefl\"\n  lemma num_reachable_norefl_mono:\n  \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> E' \\<subseteq> E \\<Longrightarrow> num_reachable_norefl \\<lparr>nodes=N, edges=E'\\<rparr> v \\<le> num_reachable_norefl \\<lparr>nodes=N, edges=E\\<rparr> v\"\n   apply(simp add: num_reachable_norefl_def)\n   apply(frule_tac E'=\"E'\" and v=\"v\" in succ_tran_mono, simp)\n   apply(frule_tac v=\"v\" in succ_tran_finite)\n   using card_mono by (metis Diff_mono finite_Diff subset_refl)\n\n  --\"backflows\"\n  lemma backflows_wf: \n    \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> wf_graph \\<lparr>nodes=N, edges=backflows E\\<rparr>\"\n    using [[simproc add: finite_Collect]] by(auto simp add: wf_graph_def backflows_def)\n  lemma undirected_backflows: \n    \"undirected G = \\<lparr> nodes = nodes G, edges = (edges G) \\<union> backflows (edges G) \\<rparr>\"\n    by(simp add: backflows_def undirected_def)\n  lemma backflows_id: \n    \"backflows (backflows E) = E\"\n    by(simp add: backflows_def)\n  \n\n\nlemmas graph_ops=add_node_def delete_node_def add_edge_def delete_edge_def delete_edges_simp2\n\n\n  --\"wf_graph\"\n  lemma wf_graph_remove_edges: \"wf_graph \\<lparr> nodes = V, edges = E \\<rparr> \\<Longrightarrow> wf_graph \\<lparr> nodes = V, edges=E - X\\<rparr>\"\n    by (metis delete_edges_simp2 delete_edges_wf select_convs(1) select_convs(2))\n\n  lemma wf_graph_remove_edges_union: \n    \"wf_graph \\<lparr> nodes = V, edges = E \\<union> E' \\<rparr> \\<Longrightarrow> wf_graph \\<lparr> nodes = V, edges=E\\<rparr>\"\n    by(auto simp add: wf_graph_def)\n\n  lemma wf_graph_union_edges: \"\\<lbrakk> wf_graph \\<lparr> nodes = V, edges = E \\<rparr>; wf_graph \\<lparr> nodes = V, edges=E'\\<rparr> \\<rbrakk> \\<Longrightarrow>\n     wf_graph \\<lparr> nodes = V, edges=E \\<union> E'\\<rparr>\"\n    by(auto simp add: wf_graph_def)\n\n  lemma wf_graph_add_subset_edges: \"\\<lbrakk> wf_graph \\<lparr> nodes = V, edges = E \\<rparr>; E' \\<subseteq> E \\<rbrakk> \\<Longrightarrow>\n     wf_graph \\<lparr> nodes = V, edges= E \\<union> E'\\<rparr>\"\n    by(auto simp add: wf_graph_def) (metis rev_finite_subset)\n\n\n(*Inspired by \nBenedikt Nordhoff and Peter Lammich\nDijkstra's Shortest Path Algorithm\nhttp://isa-afp.org/entries/Dijkstra_Shortest_Path.shtml*)\n(*more a literal copy of http://isa-afp.org/browser_info/current/AFP/Dijkstra_Shortest_Path/Graph.html*)\n\n  text {* Successors of a node. *}\n  definition succ :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> 'v set\"\n    where \"succ G v \\<equiv> {v'. (v,v')\\<in>edges G}\"\n\n\n  lemma succ_finite[simp, intro]: \"finite (edges G) \\<Longrightarrow> finite (succ G v)\"\n    unfolding succ_def\n    by (rule finite_subset[where B=\"snd`edges G\"]) force+\n\n  lemma succ_empty: \"succ empty v = {}\" unfolding empty_def succ_def by auto\n\n  lemma (in wf_graph) succ_subset: \"succ G v \\<subseteq> V\"\n    unfolding succ_def using E_wf\n    by (force)\n\n\nend\n\n", "meta": {"author": "diekmann", "repo": "topoS", "sha": "4303ebd95a501283c02fd513c109e645a48ad080", "save_path": "github-repos/isabelle/diekmann-topoS", "path": "github-repos/isabelle/diekmann-topoS/topoS-4303ebd95a501283c02fd513c109e645a48ad080/thy/Network_Security_Policy_Verification/Lib/FiniteGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.7932705728648967}}
{"text": "theory Solver\n  imports Main \nbegin\n\ndatatype formula = Var string | Const bool | Not formula | And formula formula | Or formula formula\n\ntype_synonym state = \"string \\<Rightarrow> bool\"\n\nfun eval :: \"formula \\<Rightarrow> state \\<Rightarrow> bool\"\n  where\n    \"eval (Const b) s = b\"\n  | \"eval (Var x) s = s x\"\n  | \"eval (Not F) s = (\\<not>(eval F s))\"\n  | \"eval (And F G) s = (eval F s \\<and> eval G s)\"\n  | \"eval (Or F G) s = (eval F s \\<or> eval G s)\"\n\ndefinition satisfiable :: \"formula \\<Rightarrow> bool\"\n  where \"satisfiable F \\<equiv> (\\<exists>s. eval F s = True)\"\n\nlemma \"satisfiable (Const True)\"\nproof -\n  have \"eval (Const True) (\\<lambda>x. True)\" by simp\n  thus ?thesis using satisfiable_def by simp\nqed\n\nlemma \"\\<not>satisfiable (Const False)\"\nproof -\n  have \"\\<forall>s. eval (Const False) s = False\" by simp\n  thus ?thesis using satisfiable_def by simp\nqed\n\ndatatype literal = P string | N string\n\ntype_synonym clauseCNF = \"literal list\"\n\ntype_synonym formulaCNF = \"clauseCNF list\"\n\nfun leval :: \"literal \\<Rightarrow> state \\<Rightarrow> bool\"\n  where\n    \"leval (P x) s = s x\"\n  | \"leval (N x) s = (\\<not>s x)\"\n\nfun ceval :: \"clauseCNF \\<Rightarrow> state \\<Rightarrow> bool\"\n  where\n    \"ceval [] s = False\"\n  | \"ceval (l # ls) s = (leval l s \\<or> ceval ls s)\"\n\nfun evalCNF :: \"formulaCNF \\<Rightarrow> state \\<Rightarrow> bool\"\n  where\n    \"evalCNF [] s = True\"\n  | \"evalCNF (c # cs) s = (ceval c s \\<and> evalCNF cs s)\"\n\nfun literal_to_formula :: \"literal \\<Rightarrow> formula\"\n  where\n    \"literal_to_formula (P x) = Var x\"\n  | \"literal_to_formula (N x) = Not (Var x)\"\n\nfun clause_to_formula :: \"clauseCNF \\<Rightarrow> formula\"\n  where\n    \"clause_to_formula [] = Const False\"\n  | \"clause_to_formula (l # ls) = Or (literal_to_formula l) (clause_to_formula ls)\"\n\nfun toFormula :: \"formulaCNF \\<Rightarrow> formula\"\n  where\n    \"toFormula [] = Const True\"\n  | \"toFormula (c # cs) = And (clause_to_formula c) (toFormula cs)\"\n\n\nlemma ltf_eval: \"leval l s \\<longleftrightarrow> eval (literal_to_formula l) s\"\n  by (induction l) auto\n\nlemma ctf_eval: \"ceval c s \\<longleftrightarrow> eval (clause_to_formula c) s\"\n  by (induction c) (auto simp: ltf_eval)\n\nlemma toFormula_eval: \"evalCNF cs s \\<longleftrightarrow> eval (toFormula cs) s\"\n  by (induction cs) (auto simp: ctf_eval)\n\nfun toCNF :: \"formula \\<Rightarrow> formulaCNF\"\n  where\n    \"toCNF (Var x) = [[P x]]\"\n  | \"toCNF (Const b) = (if b then [] else [[]])\"\n(*| \"toCNF (Not F) = (case F of (Var x) \\<Rightarrow> [[N x]] \n                                | Const b \\<Rightarrow> toCNF (Const (\\<not>b)) \n                                | Not G \\<Rightarrow> toCNF G\n                                | And G H \\<Rightarrow> [c1@c2 . c1 \\<leftarrow> toCNF (Not G), c2 \\<leftarrow> toCNF (Not H)]\n                                | Or G H \\<Rightarrow> toCNF (Not G) @ toCNF (Not H))\"*)\n  | \"toCNF (Not (Var x)) = [[N x]]\"\n  | \"toCNF (Not (Const b)) = toCNF (Const (\\<not>b))\"\n  | \"toCNF (Not (Not G)) = toCNF G\"\n  | \"toCNF (Not (And F G)) = [c1@c2 . c1 \\<leftarrow> toCNF (Not F), c2 \\<leftarrow> toCNF (Not G)]\"\n  | \"toCNF (Not (Or F G)) = toCNF (Not F) @ toCNF (Not G)\"\n  | \"toCNF (And F G) = (toCNF F) @ (toCNF G)\"\n  | \"toCNF (Or F G) = [c1@c2 . c1 \\<leftarrow> toCNF F, c2 \\<leftarrow> toCNF G]\"\n\n\nlemma evalCNF_app: \"evalCNF (cs1 @ cs2) s = (evalCNF cs1 s \\<and> evalCNF cs2 s)\"\n  by (induction cs1) auto\n\nlemma evalCNF_fold_aux: \"(b \\<and> evalCNF cs s) = fold (\\<lambda>c b. ceval c s \\<and> b) cs b\"\n  by (induction cs arbitrary: b) (simp_all, metis)\n\nlemma evalCNF_is_fold: \"evalCNF cs s = fold (\\<lambda>c b. ceval c s \\<and> b) cs True\"\n  using evalCNF_fold_aux by auto\n\nlemma ceval_app: \"ceval (c1 @ c2) s = (ceval c1 s \\<or> ceval c2 s)\"\n  by (induction c1) auto\n\nlemma cnf_or_distr: \"evalCNF (map ((@) a) cs) s = (ceval a s \\<or> evalCNF cs s)\"\n  by (induction cs) (auto simp: ceval_app)\n\nlemma cnf_or: \"evalCNF [c1@c2 . c1 \\<leftarrow> cs1, c2 \\<leftarrow> cs2] s = (evalCNF cs1 s \\<or> evalCNF cs2 s)\"\n  by (induction cs1) (auto simp: evalCNF_app cnf_or_distr)\n  \nlemma deMorgan_NAND: \"eval (Not (And F G)) = eval (Or (Not F) (Not G))\"\n  by (induction F) auto\n\nlemma deMorgan_NOR: \"eval (Not (Or F G)) = eval (And (Not F) (Not G))\"\n  by (induction F) auto\n\nlemma evalCNF_not: \"evalCNF (toCNF (formula.Not F)) s = (\\<not>evalCNF (toCNF F) s)\"\n  by (induction F) (auto split: if_splits simp: evalCNF_app cnf_or)\n\nlemma toCNF_eval: \"eval F s \\<longleftrightarrow> evalCNF (toCNF F) s\"\n  by (induction F) (auto simp: evalCNF_app cnf_or evalCNF_not)\n\nfun literal_var :: \"literal \\<Rightarrow> string\"\n  where\n    \"literal_var (P x) = x\"\n  | \"literal_var (N x) = x\"\n\nfun clause_vars :: \"clauseCNF \\<Rightarrow> string list\"\n  where\n    \"clause_vars [] = []\"\n  | \"clause_vars (l # ls) = literal_var l # clause_vars ls\"\n\nfun cnf_vars :: \"formulaCNF \\<Rightarrow> string list\"\n  where\n    \"cnf_vars [] = []\"\n  | \"cnf_vars (c # cs) = clause_vars c @ cnf_vars cs\"\n\nfun vals :: \"string list \\<Rightarrow> state list\"\n  where\n    \"vals [] = [\\<lambda>s. False]\"\n  | \"vals (x # xs) = [s(x:=False) . s \\<leftarrow> vals xs] @ [s(x:=True) . s \\<leftarrow> vals xs]\"\n\ndefinition solver_bruteforce :: \"formulaCNF \\<Rightarrow> bool\"\n  where\n    \"solver_bruteforce cs = fold (\\<or>) [evalCNF cs s . s \\<leftarrow> vals (cnf_vars cs)] (False)\"\n\nlemma not_foldOrFalse_if_not_contains_True: \"True \\<notin> set ls \\<Longrightarrow> fold (\\<or>) ls (False) = False\"\n  by (induction ls) auto\n\nlemma foldOr_true: \"fold (\\<or>) ls True = True\"\n  by (induction ls) auto\n\nlemma foldOrFalse_weaker: \"fold (\\<or>) ls False \\<Longrightarrow> fold (\\<or>) ls b\"\nproof (induction ls)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a ls)\n  have \"fold (\\<or>) (a # ls) False = fold (\\<or>) ls a\" by simp\n  then show ?case using Cons by (cases a, auto)\nqed\n\nlemma fold_or_False_if_contains_True: \"True \\<in> set ls \\<Longrightarrow> fold (\\<or>) ls False\"\nproof (induction ls)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a ls)\n  then have \"a = True \\<or> True \\<in> set ls\" by simp\n  then show ?case \n  proof (rule disjE)\n    assume \"a = True\"\n    then show \"fold (\\<or>) (a # ls) False\" using foldOr_true \\<open>a = True\\<close> by auto\n  next\n    assume \"True \\<in> set ls\"\n    then have \"fold (\\<or>) ls False\" using Cons by simp\n    then show \"fold (\\<or>) (a # ls) False\" using foldOrFalse_weaker by simp\n  qed\nqed\n\nlemma foldOr_iff_contains_True: \"fold (\\<or>) ls False = (True \\<in> set ls)\"\n  using not_foldOrFalse_if_not_contains_True fold_or_False_if_contains_True by auto\n  \nlemma solver_bruteforce_alt_def:\"solver_bruteforce cs = (\\<exists>s \\<in> set (vals (cnf_vars cs)). evalCNF cs s)\"\n  unfolding solver_bruteforce_def\n  using foldOr_iff_contains_True by auto\n \nlemma solver_bruteforce_correct: \"solver_bruteforce cs \\<Longrightarrow> satisfiable (toFormula cs)\"\n  unfolding satisfiable_def\n  using solver_bruteforce_alt_def toFormula_eval by blast\n\nlemma vals_false_everywhere_else: \"(\\<And>x. x \\<notin> set cs \\<Longrightarrow> t x = False) \\<Longrightarrow> (t \\<in> set (vals cs))\"\n  apply (induction cs arbitrary: t)\n   apply auto\n  by (smt (z3) fun_upd_def fun_upd_triv fun_upd_upd image_iff)\n  \n\nlemma vals_contains_aux: \"\\<forall>s. \\<exists>t \\<in> set (vals (cnf_vars cs)). \\<forall>x \\<in> set (cnf_vars cs). (s x = t x)\"\nproof\n  fix s\n  let ?t = \"(\\<lambda>x. (if x \\<in> set (cnf_vars cs) then s x else False))\"\n  have *: \"?t \\<in> set (vals (cnf_vars cs))\" using vals_false_everywhere_else by simp\n  have \"\\<forall>x \\<in> set (cnf_vars cs). (s x = ?t x)\" by simp\n  then show \"\\<exists>t \\<in> set (vals (cnf_vars cs)). \\<forall>x \\<in> set (cnf_vars cs). (s x = t x)\" using * \n    by (metis (no_types, lifting))\nqed\n\nlemma leval_state_inj: \"s (literal_var l) = t (literal_var l) \\<Longrightarrow> leval l s = leval l t\"\n  apply (induction l)\n  apply auto\n  done\n\nlemma ceval_state_inj: \"(\\<forall>x \\<in> set (clause_vars ls). s x = t x) \\<Longrightarrow> (ceval ls s = ceval ls t)\"\n  apply (induction ls)\n   apply (auto)\n  using leval_state_inj \n     apply blast\n  using leval_state_inj apply blast\n  using leval_state_inj apply metis\n  using leval_state_inj apply metis\n  done\n\nlemma evalCNF_state_inj: \"(\\<forall>x \\<in> set (cnf_vars cs). s x = t x) \\<Longrightarrow> (evalCNF cs s = evalCNF cs t)\"\n  apply (induction cs)\n   apply auto\n  using ceval_state_inj apply blast+\n  done\n\nlemma vals_contains: \"\\<forall>s. \\<exists>t \\<in> set (vals (cnf_vars cs)). evalCNF cs s = evalCNF cs t\"\nproof \n  fix s\n  have \"\\<exists>t \\<in> set (vals (cnf_vars cs)). \\<forall>x \\<in> set (cnf_vars cs). (s x = t x)\" using vals_contains_aux by simp\n  then show \"\\<exists>t \\<in> set (vals (cnf_vars cs)). evalCNF cs s = evalCNF cs t\" using evalCNF_state_inj by blast\nqed\n\nlemma solver_bruteforce_complete: \"satisfiable (toFormula cs) \\<Longrightarrow> solver_bruteforce cs\"\n  unfolding satisfiable_def\n  apply (simp add: toFormula_eval[symmetric])\nproof -\n  assume assm: \"\\<exists>s. evalCNF cs s\"\n  then obtain s where s_def: \"evalCNF cs s\" by blast\n  then have \"\\<exists>t \\<in> set (vals (cnf_vars cs)). evalCNF cs s = evalCNF cs t\" using assm vals_contains by auto\n  then have \"\\<exists>t \\<in> set (vals (cnf_vars cs)). evalCNF cs t\" using s_def by simp\n  then obtain t where \"t \\<in> set (vals (cnf_vars cs)) \\<and> evalCNF cs t\" by blast\n  then show ?thesis using solver_bruteforce_alt_def[symmetric] by auto\nqed\n\nlemma solver_bruteforce_runtime: \"length (vals cs) = 2 ^ (length cs)\"\n  by (induction cs) auto\n\nfun contains :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where\n    \"contains x [] = False\"\n  | \"contains x (y # ys) = (if x = y then True else contains x ys)\"\n\nfun not :: \"literal \\<Rightarrow> literal\"\n  where\n    \"not (P x) = N x\"\n  | \"not (N x) = P x\"\n\n\n\nfun unit_clauses :: \"formulaCNF \\<Rightarrow> clauseCNF list\"\n  where\n    \"unit_clauses [] = []\"\n  | \"unit_clauses (c # cs) = (if length c = 1 then c # unit_clauses cs else unit_clauses cs)\"\n\nfun delete :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where\n    \"delete x [] = []\" \n  | \"delete x (y # ys) = (if x = y then delete x ys else y # (delete x ys))\"\n\nfun unit_propagate :: \"clauseCNF \\<Rightarrow> formulaCNF \\<Rightarrow> formulaCNF\"\n  where \n    \"unit_propagate c [] = []\"\n  | \"unit_propagate c (c' # cs) = (let l = hd c \n                                   in\n                                     (if contains l c' \n                                      then unit_propagate c cs\n                                      else if contains (not l) c' then removeAll (not l) c' # unit_propagate c cs\n                                      else c' # unit_propagate c cs)\n                                   )\" \n\n\ndefinition literals :: \"formulaCNF \\<Rightarrow> literal list\"\n  where\n    \"literals cs \\<equiv> concat cs\"\n\ndeclare literals_def[simp]\n\ndefinition pure_literal :: \"literal \\<Rightarrow> formulaCNF \\<Rightarrow> bool\"\n  where\n    \"pure_literal l cs = (l \\<in> set (literals cs) \\<and> (not l) \\<notin> set (literals cs))\"\n\nvalue \"1 \\<notin> ({}::nat set)\"\nfun pure_literall :: \"literal \\<Rightarrow> formulaCNF \\<Rightarrow> bool\"\n  where\n    \"pure_literall l [] = False\"\n  | \"pure_literall l (c # cs) = (contains l c \\<and> \\<not>contains (not l) c \\<and> pure_literall l cs)\"\n\ndefinition pure_literals :: \"formulaCNF \\<Rightarrow> literal list\"\n  where\n    \"pure_literals cs = filter (\\<lambda>l. pure_literall l cs ) (literals cs)\"\n\ndeclare pure_literals_def[simp]\n\nfun pure_literal_assign :: \"literal \\<Rightarrow> formulaCNF \\<Rightarrow> formulaCNF\"\n  where\n    \"pure_literal_assign l [] = []\"\n  | \"pure_literal_assign l (c # cs) = (if contains l c then pure_literal_assign l cs else c # (pure_literal_assign l cs))\"\n\n\n\nfun pure_literal_elimm :: \"formulaCNF \\<Rightarrow> literal list \\<Rightarrow> formulaCNF\"\n  where\n    \"pure_literal_elimm cs [] = cs\"\n  | \"pure_literal_elimm cs (l # ls) = pure_literal_elimm (pure_literal_assign l cs) ls\"\n\nfun pure_literal_elim :: \"formulaCNF \\<Rightarrow> formulaCNF\"\n  where\n    \"pure_literal_elim cs = fold (\\<lambda>l cs. pure_literal_assign l cs) (pure_literals cs) cs\"\n\n\nfun falt :: \"('b \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'b list \\<Rightarrow> 'a\"\n  where\n    \"falt f a [] = a\"\n  | \"falt f a (x # xs) = falt f (f x a) xs\"\n\nfun unit_propagate_all :: \"formulaCNF \\<Rightarrow> clauseCNF list \\<Rightarrow> formulaCNF\"\n  where\n    \"unit_propagate_all cs [] = cs\"\n  | \"unit_propagate_all cs (uc # ucs) = unit_propagate_all (unit_propagate uc cs) ucs\"\n\nlemma \"unit_propagate_all cs ucs = fold (\\<lambda>uc. unit_propagate uc) ucs cs\"\n  apply (induction ucs arbitrary: cs)\n  apply auto\n  done\n\ndefinition uprog :: \"formulaCNF \\<Rightarrow> formulaCNF\" where \"uprog cs \\<equiv> fold (\\<lambda>uc. unit_propagate uc) (unit_clauses cs) cs\"\n\ntext\\<open>\nuprog cs (u # uc) = uprog (uprog cs u) uc\"\n\\<close>\n\nfun choose_literal :: \"formulaCNF \\<Rightarrow> literal\"\n  where\n    \"choose_literal cs = (if (literals cs) = [] then undefined else (hd (literals cs)))\"\n\nfun subst :: \"formulaCNF \\<Rightarrow> literal \\<Rightarrow> bool \\<Rightarrow> formulaCNF\"\n  where\n    \"subst [] l b = []\"\n  | \"subst (c # cs) l b = (case b of False \\<Rightarrow> removeAll l c # subst cs l b |\n                                     True \\<Rightarrow> (if contains l c then subst cs l b else c # subst cs l b)) \"\n\ndefinition consistent :: \"formulaCNF \\<Rightarrow> bool\"\n  where\n    \"consistent cs = (\\<forall>l \\<in> set (literals cs). (not l) \\<notin> set (literals cs))\"\n\ndeclare consistent_def[simp]\n\ntext\n\\<open>\nhttp://poincare.matf.bg.ac.rs/~filip/phd/classic-dpll-verification.pdf\n\nTermination proof can be made manually ! \n\n\n\\<close>\n\nvalue \"solver_bruteforce [[P ''x'', P ''y''], [P ''z'', P ''y''], [N ''y'']]\"\nvalue \"pure_literal_elim (uprog [[P ''x'', P ''y''], [P ''z'', P ''y''], [N ''y'']])\"\nvalue \"consistent (subst (pure_literal_elim (uprog [[P ''x'', P ''y''], [P ''z'', P ''y''], [N ''y'']])) (P ''x'') True)\"\nvalue \"subst (pure_literal_elim (uprog [[P ''x'', P ''y''], [P ''z'', P ''y''], [N ''y'']])) (P ''z'') True\"\n\nfun size :: \"formulaCNF \\<Rightarrow> nat\"\n  where\n    \"size []  = 0\"\n  | \"size (c # cs) = length c + size cs\"\n\n\nlemma size_unit_propagate: \"size (unit_propagate c cs) \\<le> size cs\"\n  apply (induction cs arbitrary: c)\n   apply auto\n  by (smt add_mono_thms_linordered_semiring(1) le_add1 le_add_same_cancel1 length_removeAll_less_eq list.inject nat_add_left_cancel_le size.elims trans_le_add2)\n\n\ndeclare uprog_def[simp]\n\nlemma size_unit_propagate_all: \"size (unit_propagate_all cs ucs) \\<le> size cs\"\n  apply (induction ucs arbitrary: cs)\n   apply auto\n  using le_trans size_unit_propagate by blast\n\nlemma size_pure_literal_assign: \"size (pure_literal_assign l cs) \\<le> size cs\"\n  apply (induction cs)\n   apply auto\n  done\nlemma size_pure_literal_elim: \"size (pure_literal_elimm cs ls) \\<le> size cs\"\n  apply (induction ls arbitrary: cs)\n   apply auto\n  using size_pure_literal_assign le_trans by blast\n\nlemma size_subst_weak: \"size (subst cs l b) \\<le> size cs\"\n  apply (induction cs)\n   apply (auto split: bool.split)\n  by (simp add: add_mono_thms_linordered_semiring(1))\n\n\n\nlemma size_subst_False:\"l \\<in> set (literals cs) \\<Longrightarrow> size (subst cs l False) < size cs\"\n  apply (induction cs)\n   apply auto\n   apply (simp add: add_less_le_mono length_removeAll_less size_subst_weak)\n  by (meson add_le_less_mono length_removeAll_less_eq)\n\n\n\nlemma contains_iff_elem: \"contains l c \\<longleftrightarrow> l \\<in> set c\"\n  apply (induction c)\n   apply auto\n  done\n\n\nlemma size_partition_filter: \"size cs = size (filter (\\<lambda>x. K x) cs) + size (filter (\\<lambda>x. \\<not>K x) cs)\"\n  apply (induction cs)\n   apply auto\n  done\nlemma subst_True_filter_def: \"subst cs l True = filter (\\<lambda>c. \\<not>contains l c) cs\"\n  apply (induction cs)\n  apply auto\n  done\n\nlemma contains_size: \"contains c cs \\<Longrightarrow> size [c] \\<le> size cs\"\n  apply (induction cs)\n   apply (auto split: if_splits)\n  done\n\nlemma size_subst_True: \"l \\<in> set (literals cs) \\<Longrightarrow> size (subst cs l True) < size cs\"\nproof-\n  assume assm: \"l \\<in> set (literals cs)\"\n  then have \"\\<exists>c \\<in> set cs. contains l c\" using contains_iff_elem[symmetric] by force\n  then obtain c where cdef:\"c \\<in> set cs \\<and> contains l c\" by blast\n  then have \"length c > 0\" using assm by auto\n\n\n  have \"contains c (filter (\\<lambda>c. contains l c) cs)\" using cdef by (simp add: contains_iff_elem)\n  then have \"size (filter (\\<lambda>c. contains l c) cs) \\<ge> size [c]\" using contains_size cdef by blast\n  then have *: \"size (filter (\\<lambda>c. contains l c) cs) > 0\" using \\<open>length c > 0\\<close> \n    using gr_zeroI by fastforce\n\n   \n  have \"size cs = size (filter (\\<lambda>c. contains l c) cs) + size (subst cs l True)\" using size_partition_filter subst_True_filter_def by auto\n  \n  then show \"size (subst cs l True) < size cs\" using subst_True_filter_def * by simp\nqed\n  \nlemma size_subst_strong: \"l \\<in> set (literals cs) \\<Longrightarrow> size (subst cs l b) < size cs\"\n  using size_subst_True size_subst_False by (cases b) auto\n\n\nlemma size_subst_main: \"literals cs \\<noteq> [] \\<Longrightarrow> l = choose_literal cs \\<Longrightarrow> size (subst cs l b) < size cs\"\nproof -\n  assume assms: \"literals cs \\<noteq> []\" \"l = choose_literal cs\"\n  then have \" l = hd (literals cs)\" by auto\n  then have \" l \\<in> set (literals cs)\" using assms \n    using list.set_sel(1) by blast\n  then show ?thesis using size_subst_strong by simp\nqed\n\n\n\nfunction solver_dpll :: \"formulaCNF \\<Rightarrow> bool\"\n  where\n    \"solver_dpll cs = (if consistent cs then True\n                       else if contains [] cs then False\n                       else\n                         let cs\\<^sub>1 = unit_propagate_all cs (unit_clauses cs); cs\\<^sub>2 = pure_literal_elimm cs\\<^sub>1 (pure_literals cs\\<^sub>1); l = choose_literal cs\\<^sub>2\n                         in \n                           (if literals cs\\<^sub>2 = [] then (if contains [] cs\\<^sub>2 then False else True)\n                            else\n                              solver_dpll (subst cs\\<^sub>2 l True) \\<or> (solver_dpll (subst cs\\<^sub>2 l False))\n                           )\n                       )\"\n  by pat_completeness auto\ntermination \n  apply (relation \"measure (\\<lambda>cs. (size cs))\") \n    apply (auto simp: size_pure_literal_elim size_unit_propagate_all size_subst_main split: if_splits)\n   apply (smt Nil_eq_concat_conv le_trans list.set_sel(1) literals_def not_le size_pure_literal_elim size_subst_strong size_unit_propagate_all)\n  by (smt Nil_eq_concat_conv antisym leI le_trans list.set_sel(1) literals_def size_pure_literal_elim size_subst_weak size_subst_strong size_unit_propagate_all)\n  \n  \n\nend", "meta": {"author": "ujkan", "repo": "sat_solver", "sha": "604b9b6a17ec2b63df36e4b7de1c5be6a390dc70", "save_path": "github-repos/isabelle/ujkan-sat_solver", "path": "github-repos/isabelle/ujkan-sat_solver/sat_solver-604b9b6a17ec2b63df36e4b7de1c5be6a390dc70/Solver.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8807970764133561, "lm_q1q2_score": 0.7931840028357849}}
{"text": "theory InduccionGeneral\nimports Main\nbegin\n\nsection {* La función mitad *}\n\ntext {* (mitad x) es la mitad del número natural x. Por ejemplo, \n     mitad (Suc (Suc (Suc (Suc 0)))) = Suc (Suc 0) \n     mitad (Suc (Suc (Suc 0)))       = Suc 0 \n*}\nfun mitad :: \"nat \\<Rightarrow> nat\" \nwhere\n  \"mitad 0             = 0\" \n| \"mitad (Suc 0)       = 0\" \n| \"mitad (Suc (Suc n)) = 1 + mitad n\"\n\nvalue \"mitad (Suc (Suc (Suc (Suc 0))))\"\nlemma \"mitad (Suc (Suc (Suc (Suc 0)))) = Suc (Suc 0)\" by simp \nvalue \"mitad (Suc (Suc (Suc 0)))\"\nlemma \"mitad (Suc (Suc (Suc 0))) = Suc 0\" by simp \n\ntext {* El esquema de inducción correspondiente a la función mitad es\n     \\<lbrakk>P 0; P (Suc 0); \\<And>n. P n \\<Longrightarrow> P (Suc (Suc n))\\<rbrakk> \\<Longrightarrow> P a\n  es decir, para demostrar que todo número a tiene la propiedad P basta\n  demostrar que:\n  · 0 tiene la propiedad P\n  · (Suc 0) tiene la propiedad P\n  · si n tiene la propiedad P, entonces (Suc (Suc n)) también la tiene.\n*}\nthm mitad.induct [no_vars]\n\ntext {* Prop.: Para todo n, 2 * mitad n \\<le> n *}\nlemma \"2 * mitad n \\<le> n\"\napply (induction n rule: mitad.induct)\napply auto\ndone\n\nsection {* La función intercala *}\n\ntext {* (intercala x ys) es la lista obtenida intercalando x entre los\n  elementos de ys. Por ejemplo, \n     intercala a [x,y,z] = [x, a, y, a, z]\" by simp\n*} \nfun intercala :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" \nwhere\n  \"intercala a []       = []\" \n| \"intercala a [x]      = [x]\" \n| \"intercala a (x#y#zs) = x # a # intercala a (y#zs)\"\n\nvalue \"intercala a [x,y,z]\"\nlemma \"intercala a [x,y,z] = [x, a, y, a, z]\" by simp\n\ntext {* El esquema de inducción correspondiente a la función intercala es\n     \\<lbrakk>\\<And>a. P a []; \n      \\<And>a x. P a [x]; \n      \\<And>a x y zs. P a (y # zs) \\<Longrightarrow> P a (x # y # zs)\\<rbrakk> \n     \\<Longrightarrow> P b xs\n  es decir, para demostrar que para todo b y xs el par (b,xs) se tiene\n  la propiedad P basta demostrar que:\n  · para todo a, el par (a,[]) tiene la propiedad P\n  · para todo a, el par (a,[x]) tiene la propiedad P\n  · para todo a, x, y, zs, si el par (a,y#zs) tiene la propiedad P\n    entonces el par (a,x#y#zs) tiene la propiedad P.\n*}\nthm intercala.induct [no_vars]\n\ntext {* Prop.: Aplicar la función f al resultado de intercalar a en xs\n  es lo mismo que intercalar (f a) en las imágenes de xs mediante f. *} \nlemma \"map f (intercala a xs) = intercala (f a) (map f xs)\"\napply (induction a xs rule: intercala.induct)\napply auto\ndone\n\nend\n", "meta": {"author": "jaalonso", "repo": "AFV", "sha": "4605a58a1ad82f2255ac8bbe8d931942fd3d095c", "save_path": "github-repos/isabelle/jaalonso-AFV", "path": "github-repos/isabelle/jaalonso-AFV/AFV-4605a58a1ad82f2255ac8bbe8d931942fd3d095c/Temas/Ejemplos/InduccionGeneral.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.874077230244524, "lm_q1q2_score": 0.7930609621766244}}
{"text": "(* Title: Resolvable_Designs.thy\n   Author: Chelsea Edmonds\n*)\n\nsection \\<open>Resolvable Designs\\<close>\ntext \\<open>Resolvable designs have further structure, and can be \"resolved\" into a set of resolution \nclasses. A resolution class is a subset of blocks which exactly partitions the point set. \nDefinitions based off the handbook \\<^cite>\\<open>\"colbournHandbookCombinatorialDesigns2007\"\\<close>\n and Stinson \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>.\nThis theory includes a proof of an alternate statement of Bose's theorem\\<close>\n\ntheory Resolvable_Designs imports BIBD\nbegin\n\nsubsection \\<open>Resolutions and Resolution Classes\\<close>\ntext \\<open>A resolution class is a partition of the point set using a set of blocks from the design \nA resolution is a group of resolution classes partitioning the block collection\\<close>\n\ncontext incidence_system\nbegin \n\ndefinition resolution_class :: \"'a set set \\<Rightarrow> bool\" where\n\"resolution_class S \\<longleftrightarrow> partition_on \\<V> S \\<and> (\\<forall> bl \\<in> S . bl \\<in># \\<B>)\"\n\nlemma resolution_classI [intro]: \"partition_on \\<V>  S \\<Longrightarrow> (\\<And> bl . bl \\<in> S \\<Longrightarrow> bl \\<in># \\<B>) \n    \\<Longrightarrow> resolution_class S\"\n  by (simp add: resolution_class_def)\n\nlemma resolution_classD1: \"resolution_class S \\<Longrightarrow> partition_on \\<V> S\"\n  by (simp add: resolution_class_def)\n\nlemma resolution_classD2: \"resolution_class S \\<Longrightarrow>  bl \\<in> S \\<Longrightarrow> bl \\<in># \\<B>\"\n  by (simp add: resolution_class_def)\n\nlemma resolution_class_empty_iff: \"resolution_class {} \\<longleftrightarrow> \\<V>  = {}\"\n  by (auto simp add: resolution_class_def partition_on_def)\n\nlemma resolution_class_complete: \"\\<V>  \\<noteq> {} \\<Longrightarrow> \\<V>  \\<in># \\<B> \\<Longrightarrow> resolution_class {\\<V>}\"\n  by (auto simp add: resolution_class_def partition_on_space)\n\nlemma resolution_class_union: \"resolution_class S \\<Longrightarrow> \\<Union>S = \\<V> \"\n  by (simp add: resolution_class_def partition_on_def)\n\nlemma (in finite_incidence_system) resolution_class_finite: \"resolution_class S \\<Longrightarrow> finite S\"\n  using finite_elements finite_sets by (auto simp add: resolution_class_def)\n\nlemma (in design) resolution_class_sum_card: \"resolution_class S \\<Longrightarrow> (\\<Sum>bl \\<in> S . card bl) = \\<v>\"\n  using resolution_class_union finite_blocks\n  by (auto simp add: resolution_class_def partition_on_def card_Union_disjoint)\n\ndefinition resolution:: \"'a set multiset multiset \\<Rightarrow> bool\" where\n\"resolution P \\<longleftrightarrow> partition_on_mset \\<B> P \\<and> (\\<forall> S \\<in># P . distinct_mset S \\<and> resolution_class (set_mset S))\"\n\nlemma resolutionI : \"partition_on_mset \\<B> P \\<Longrightarrow> (\\<And> S . S \\<in>#P \\<Longrightarrow> distinct_mset S) \\<Longrightarrow> \n    (\\<And> S . S\\<in># P \\<Longrightarrow> resolution_class (set_mset S)) \\<Longrightarrow> resolution P\"\n  by (simp add: resolution_def)\n\nlemma (in proper_design) resolution_blocks: \"distinct_mset \\<B> \\<Longrightarrow> disjoint (set_mset \\<B>) \\<Longrightarrow> \n    \\<Union>(set_mset \\<B>) = \\<V> \\<Longrightarrow> resolution {#\\<B>#}\"\n  unfolding resolution_def resolution_class_def partition_on_mset_def partition_on_def\n  using design_blocks_nempty blocks_nempty by auto\n\nend\n\nsubsection \\<open>Resolvable Design Locale\\<close>\ntext \\<open>A resolvable design is one with a resolution P\\<close>\nlocale resolvable_design = design + \n  fixes partition :: \"'a set multiset multiset\" (\"\\<P>\")\n  assumes resolvable: \"resolution \\<P>\"\nbegin\n\nlemma resolutionD1: \"partition_on_mset \\<B> \\<P>\"\n  using resolvable by (simp add: resolution_def)\n\nlemma resolutionD2: \"S \\<in>#\\<P> \\<Longrightarrow> distinct_mset S\" \n  using resolvable by (simp  add: resolution_def)\n\nlemma resolutionD3: \" S\\<in># \\<P> \\<Longrightarrow> resolution_class (set_mset S)\"\n  using resolvable by (simp add: resolution_def)\n\nlemma resolution_class_blocks_disjoint: \"S \\<in># \\<P> \\<Longrightarrow> disjoint (set_mset S)\"\n  using resolutionD3 by (simp add: partition_on_def resolution_class_def) \n\nlemma resolution_not_empty: \"\\<B> \\<noteq> {#} \\<Longrightarrow> \\<P> \\<noteq> {#}\"\n  using partition_on_mset_not_empty resolutionD1 by auto \n\nlemma resolution_blocks_subset: \"S \\<in># \\<P> \\<Longrightarrow> S \\<subseteq># \\<B>\"\n  using partition_on_mset_subsets resolutionD1 by auto\n\nend\n\nlemma (in incidence_system) resolvable_designI [intro]: \"resolution \\<P> \\<Longrightarrow> design \\<V> \\<B> \\<Longrightarrow> \n    resolvable_design \\<V> \\<B> \\<P>\"\n  by (simp add: resolvable_design.intro resolvable_design_axioms.intro)\n\nsubsection \\<open>Resolvable Block Designs\\<close>\ntext \\<open>An RBIBD is a resolvable BIBD - a common subclass of interest for block designs\\<close>\nlocale r_block_design = resolvable_design + block_design\nbegin\nlemma resolution_class_blocks_constant_size: \"S \\<in># \\<P> \\<Longrightarrow> bl \\<in># S \\<Longrightarrow> card bl = \\<k>\"\n  by (metis resolutionD3 resolution_classD2 uniform_alt_def_all)\n\nlemma resolution_class_size1: \n  assumes \"S \\<in># \\<P>\"\n  shows \"\\<v> = \\<k> * size S\"\nproof - \n  have \"(\\<Sum>bl \\<in># S . card bl) = (\\<Sum>bl \\<in> (set_mset S) . card bl)\" using resolutionD2 assms\n    by (simp add:  sum_unfold_sum_mset)\n  then have eqv: \"(\\<Sum>bl \\<in># S . card bl) = \\<v>\" using resolutionD3 assms resolution_class_sum_card\n    by presburger \n  have \"(\\<Sum>bl \\<in># S . card bl) = (\\<Sum>bl \\<in># S . \\<k>)\" using resolution_class_blocks_constant_size assms \n    by auto\n  thus ?thesis using eqv by auto\nqed\n\nlemma resolution_class_size2: \n  assumes \"S \\<in># \\<P>\"\n  shows \"size S = \\<v> div \\<k>\"\n  using resolution_class_size1 assms\n  by (metis nonzero_mult_div_cancel_left not_one_le_zero k_non_zero)\n\nlemma resolvable_necessary_cond_v: \"\\<k> dvd \\<v>\"\nproof -\n  obtain S where s_in: \"S \\<in>#\\<P>\" using resolution_not_empty design_blocks_nempty by blast\n  then have \"\\<k> * size S = \\<v>\" using resolution_class_size1 by simp \n  thus ?thesis by (metis dvd_triv_left) \nqed\n\nend\n\nlocale rbibd = r_block_design + bibd\n \nbegin\n\nlemma resolvable_design_num_res_classes: \"size \\<P> = \\<r>\"\nproof - \n  have k_ne0: \"\\<k> \\<noteq> 0\" using k_non_zero by auto \n  have f1: \"\\<b> = (\\<Sum>S \\<in># \\<P> . size S)\"\n    by (metis partition_on_msetD1 resolutionD1 size_big_union_sum)\n  then have \"\\<b> = (\\<Sum>S \\<in># \\<P> . \\<v> div \\<k>)\" using resolution_class_size2 f1 by auto\n  then have f2: \"\\<b> = (size \\<P>) * (\\<v> div \\<k>)\" by simp\n  then have \"size \\<P> = \\<b> div (\\<v> div \\<k>)\"\n    using b_non_zero by auto \n  then have \"size \\<P> = (\\<b> * \\<k>) div \\<v>\" using f2 resolvable_necessary_cond_v\n    by (metis div_div_div_same div_dvd_div dvd_triv_right k_ne0 nonzero_mult_div_cancel_right)\n  thus ?thesis using necessary_condition_two\n    by (metis nonzero_mult_div_cancel_left not_one_less_zero t_design_min_v) \nqed\n\nlemma resolvable_necessary_cond_b: \"\\<r> dvd \\<b>\"\nproof -\n  have f1: \"\\<b> = (\\<Sum>S \\<in># \\<P> . size S)\"\n    by (metis partition_on_msetD1 resolutionD1 size_big_union_sum)\n  then have \"\\<b> = (\\<Sum>S \\<in># \\<P> . \\<v> div \\<k>)\" using resolution_class_size2 f1 by auto\n  thus ?thesis using resolvable_design_num_res_classes by simp\nqed\n\nsubsubsection \\<open>Bose's Inequality\\<close>\ntext \\<open>Boses inequality is an important theorem on RBIBD's. This is a proof \nof an alternate statement of the thm, which does not require a linear algebraic approach, \ntaken directly from Stinson \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>\\<close>\ntheorem bose_inequality_alternate: \"\\<b> \\<ge> \\<v> + \\<r> - 1 \\<longleftrightarrow> \\<r> \\<ge> \\<k> + \\<Lambda>\"\nproof - \n  from necessary_condition_two v_non_zero have r: \\<open>\\<r> = \\<b> * \\<k> div \\<v>\\<close>\n    by (metis div_mult_self1_is_m)\n  define k b v l r where intdefs: \"k \\<equiv> (int \\<k>)\" \"b \\<equiv> int \\<b>\" \"v = int \\<v>\" \"l \\<equiv> int \\<Lambda>\" \"r \\<equiv> int \\<r>\"\n  have kdvd: \"k dvd (v * (r - k))\"\n    using intdefs\n    by (simp add: resolvable_necessary_cond_v)\n  have necess1_alt: \"l * v - l = r * (k - 1)\" using necessary_condition_one intdefs \n    by (smt (verit) diff_diff_cancel int_ops(2) int_ops(6) k_non_zero nat_mult_1_right of_nat_0_less_iff \n        of_nat_mult right_diff_distrib' v_non_zero)\n  then have v_eq: \"v = (r * (k - 1) + l) div l\" \n    using necessary_condition_one index_not_zero intdefs\n    by (metis diff_add_cancel nonzero_mult_div_cancel_left not_one_le_zero of_nat_mult \n        unique_euclidean_semiring_with_nat_class.of_nat_div) \n  have ldvd: \" \\<And> x. l dvd (x * (r * (k - 1) + l))\" \n    by (metis necess1_alt diff_add_cancel dvd_mult dvd_triv_left) \n  have \"(b \\<ge> v + r - 1) \\<longleftrightarrow> ((\\<v> * r) div k \\<ge> v + r - 1)\"\n    using necessary_condition_two k_non_zero intdefs\n    by (metis (no_types, lifting) nonzero_mult_div_cancel_right not_one_le_zero of_nat_eq_0_iff of_nat_mult)\n  also have  \"... \\<longleftrightarrow> (((v * r) - (v * k)) div k \\<ge> r - 1)\"\n    using k_non_zero k_non_zero r intdefs\n    by (simp add: of_nat_div algebra_simps)\n      (smt (verit, ccfv_threshold) One_nat_def div_mult_self4 of_nat_1 of_nat_mono)\n  also have f2: \" ... \\<longleftrightarrow> ((v * ( r - k)) div k \\<ge> ( r - 1))\"\n    using int_distrib(3) by (simp add: mult.commute)\n  also have f2: \" ... \\<longleftrightarrow> ((v * ( r - k)) \\<ge> k * ( r - 1))\" \n    using k_non_zero kdvd intdefs by auto\n  also have \"... \\<longleftrightarrow> ((((r * (k - 1) + l ) div l) * (r - k)) \\<ge> k * (r - 1))\"\n    using v_eq by presburger \n  also have \"... \\<longleftrightarrow> ( (r - k) * ((r * (k - 1) + l ) div l) \\<ge> (k * (r - 1)))\" \n    by (simp add: mult.commute)\n  also have \" ... \\<longleftrightarrow> ( ((r - k) * (r * (k - 1) + l )) div l \\<ge> (k * (r - 1)))\"\n    using div_mult_swap necessary_condition_one intdefs\n    by (metis diff_add_cancel dvd_triv_left necess1_alt) \n  also have \" ... \\<longleftrightarrow> (((r - k) * (r * (k - 1) + l ))  \\<ge>  l * (k * (r - 1)))\" \n    using ldvd[of \"(r - k)\"] dvd_mult_div_cancel index_not_zero mult_strict_left_mono intdefs\n    by (smt (verit) b_non_zero bibd_block_number bot_nat_0.extremum_strict div_0 less_eq_nat.simps(1) \n      mult_eq_0_iff mult_left_le_imp_le mult_left_mono of_nat_0 of_nat_le_0_iff of_nat_le_iff of_nat_less_iff)\n  also have 1: \"... \\<longleftrightarrow> (((r - k) * (r * (k - 1))) + ((r - k) * l )  \\<ge>  l * (k * (r - 1)))\" \n    by (simp add: distrib_left) \n  also have \"... \\<longleftrightarrow> (((r - k) * r * (k - 1)) \\<ge> l * k * (r - 1) - ((r - k) * l ))\" \n    using mult.assoc by linarith \n  also have \"... \\<longleftrightarrow> (((r - k) * r * (k - 1)) \\<ge> (l * k * r) - (l * k) - ((r * l) -(k * l )))\" \n    using distrib_right by (simp add: distrib_left right_diff_distrib' left_diff_distrib') \n  also have \"... \\<longleftrightarrow> (((r - k) * r * (k - 1)) \\<ge> (l * k * r)  - ( l * r))\" \n    by (simp add: mult.commute) \n  also have \"... \\<longleftrightarrow> (((r - k) * r * (k - 1)) \\<ge> (l  * (k * r))  - ( l * r))\" \n    by linarith  \n  also have \"... \\<longleftrightarrow> (((r - k) * r * (k - 1)) \\<ge> (l  * (r * k))  - ( l * r))\" \n    by (simp add: mult.commute)\n  also have \"... \\<longleftrightarrow> (((r - k) * r * (k - 1)) \\<ge> l * r * (k - 1))\"\n    by (simp add:  mult.assoc int_distrib(4)) \n  finally have \"(b \\<ge> v + r - 1) \\<longleftrightarrow> (r \\<ge> k + l)\"\n    using index_lt_replication mult_right_le_imp_le r_gzero mult_cancel_right k_non_zero intdefs\n    by (smt (z3) of_nat_0_less_iff of_nat_1 of_nat_le_iff of_nat_less_iff)\n  then have \"\\<b> \\<ge> \\<v> + \\<r> - 1 \\<longleftrightarrow> \\<r> \\<ge> \\<k> + \\<Lambda>\"\n    using k_non_zero le_add_diff_inverse of_nat_1 of_nat_le_iff intdefs by linarith \n  thus ?thesis by simp\nqed\nend\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Design_Theory/Resolvable_Designs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7930081363057685}}
{"text": "theory Matching\nimports Main\nbegin\n\ntype_synonym label = nat\n\nsection {* Definitions *}\n\ndefinition finite_graph :: \"'v set => ('v * 'v) set \\<Rightarrow> bool\" where\n  \"finite_graph V E = (finite V \\<and> finite E \\<and> \n  (\\<forall> e \\<in> E. fst e \\<in> V \\<and> snd e \\<in> V \\<and> fst e ~= snd e))\"\n\ndefinition degree :: \"('v * 'v) set \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n  \"degree E v = card {e \\<in> E. fst e = v \\<or> snd e = v}\"\n\ndefinition edge_as_set :: \"('v * 'v) \\<Rightarrow> 'v set\" where\n  \"edge_as_set e = {fst e, snd e}\"\n\ndefinition N :: \"'v set \\<Rightarrow> ('v \\<Rightarrow> label) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"N V L i = card {v \\<in> V. L v = i}\"\n\ndefinition weight:: \"label set \\<Rightarrow> (label \\<Rightarrow> nat) \\<Rightarrow> nat\" where\n  \"weight LV f = f 1 + (\\<Sum>i\\<in>LV. (f i) div 2)\"\n\ndefinition OSC :: \"('v \\<Rightarrow> label) \\<Rightarrow> ('v * 'v) set \\<Rightarrow> bool\" where\n  \"OSC L E = (\\<forall>e \\<in> E. L (fst e) = 1 \\<or> L (snd e) = 1 \\<or> \n                     L (fst e) = L (snd e) \\<and> L (fst e) > 1)\"\n\ndefinition disjoint_edges :: \"('v * 'v) \\<Rightarrow> ('v * 'v) \\<Rightarrow> bool\" where\n  \"disjoint_edges e1 e2 = (fst e1 \\<noteq> fst e2 \\<and> fst e1 \\<noteq> snd e2 \\<and> \n                          snd e1 \\<noteq> fst e2 \\<and> snd e1 \\<noteq> snd e2)\"\n\ndefinition matching :: \"'v set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> bool\" where\n  \"matching V E M = (M \\<subseteq> E \\<and> finite_graph V E \\<and> \n  (\\<forall>e1 \\<in> M. \\<forall> e2 \\<in> M. e1 \\<noteq> e2 \\<longrightarrow> disjoint_edges e1 e2))\"\n\ndefinition matching_i :: \"nat \\<Rightarrow> 'v set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> ('v * 'v) set \\<Rightarrow>\n  ('v \\<Rightarrow> label) \\<Rightarrow> ('v * 'v) set\" where\n  \"matching_i i V E M L = {e \\<in> M. i=1 \\<and> (L (fst e) = i \\<or> L (snd e) = i) \n  \\<or> i>1 \\<and> L (fst e) = i \\<and> L (snd e) = i}\"\n\ndefinition V_i:: \"nat \\<Rightarrow> 'v set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> \n                  ('v \\<Rightarrow> label) \\<Rightarrow> 'v set\" where\n  \"V_i i V E M L = \\<Union> (edge_as_set ` matching_i i V E M L)\"\n\ndefinition endpoint_inV :: \"'v set \\<Rightarrow> ('v * 'v) \\<Rightarrow> 'v\" where \n  \"endpoint_inV V e = (if fst e \\<in> V then fst e else snd e)\" \n\ndefinition relevant_endpoint :: \"('v \\<Rightarrow> label) \\<Rightarrow> 'v set \\<Rightarrow> \n                                 ('v * 'v) \\<Rightarrow> 'v\" where \n  \"relevant_endpoint L V e = (if L (fst e) = 1 then fst e else snd e)\"\n\nsection {* Lemmas *}\n\nlemma definition_of_range:\n  \"endpoint_inV V1 ` matching_i 1 V E M L = \n  { v. \\<exists> e \\<in> matching_i 1 V E M L. endpoint_inV V1 e = v }\" by auto\n\nlemma matching_i_edges_as_sets:\n  \"edge_as_set ` matching_i i V E M L = \n  { e1. \\<exists> (u, v) \\<in> matching_i i V E M L. edge_as_set (u, v) = e1}\" by auto\n\nlemma matching_disjointness:\n  assumes \"matching V E M\"\n  assumes \"e1 \\<in> M\"\n  assumes \"e2 \\<in> M\"\n  assumes \"e1 \\<noteq> e2\"\n  shows  \"edge_as_set e1 \\<inter> edge_as_set e2 = {}\"\n  using assms \n  by (auto simp add: edge_as_set_def disjoint_edges_def matching_def)\n\nlemma expand_set_containment:\n  assumes \"matching V E M\"\n  assumes \"e \\<in> M\"\n  shows \"e \\<in> E\"\n  using assms\n  by (auto simp add:matching_def)\n\ntheorem injectivity:\n  assumes is_osc: \"OSC L E\"\n  assumes is_m: \"matching V E M\"\n  assumes e1_in_M1: \"e1 \\<in> matching_i 1 V E M L\"\n      and e2_in_M1: \"e2 \\<in> matching_i 1 V E M L\"\n  assumes diff: \"(e1 \\<noteq> e2)\"\n  shows \"endpoint_inV {v \\<in> V. L v = 1} e1 \\<noteq> endpoint_inV {v \\<in> V. L v = 1} e2\"\nproof -\n  from e1_in_M1 have \"e1 \\<in> M\" by (auto simp add: matching_i_def)\n  moreover\n  from e2_in_M1 have \"e2 \\<in> M\" by (auto simp add: matching_i_def)\n  ultimately\n  have disjoint_edge_sets: \"edge_as_set e1 \\<inter> edge_as_set e2 = {}\" \n    using diff is_m matching_disjointness by fast\n  then show ?thesis by (auto simp add: edge_as_set_def endpoint_inV_def)\nqed\n\nsubsection {* @{text \"|M1| \\<le> n1\"} *}\n\nlemma card_M1_le_NVL1: \n  assumes \"matching V E M\"\n  assumes \"OSC L E\"\n  shows \"card (matching_i 1 V E M L) \\<le> ( N V L 1)\"\nproof -\n  let ?f = \"endpoint_inV {v \\<in> V. L v = 1}\"\n  let ?A = \"matching_i 1 V E M L\"\n  let ?B = \"{v \\<in> V. L v = 1}\"\n  have \"inj_on ?f ?A\" using assms injectivity\n    unfolding inj_on_def by blast\n  moreover have \"?f ` ?A \\<subseteq> ?B\"\n  proof -\n    {\n      fix e assume \"e \\<in> matching_i 1 V E M L\"\n      then have \"endpoint_inV {v \\<in> V. L v = 1} e \\<in> {v \\<in> V. L v = 1}\"\n        using assms\n        by (auto simp add: endpoint_inV_def matching_def\n          matching_i_def OSC_def finite_graph_def definition_of_range)\n    }\n    then show ?thesis using assms definition_of_range by blast\n  qed\n  moreover have \"finite ?B\" using assms\n    by (simp add: matching_def finite_graph_def)\n  ultimately show ?thesis unfolding N_def by (rule card_inj_on_le)\nqed\n\nlemma edge_as_set_inj_on_Mi: \n  assumes \"matching V E M\"\n  shows \"inj_on edge_as_set (matching_i i V E M L)\"\n  using assms\n  unfolding inj_on_def edge_as_set_def matching_def\n    disjoint_edges_def matching_i_def \n  by blast\n\nlemma card_Mi_eq_card_edge_as_set_Mi:\n  assumes \"matching V E M\"\n  shows \"card (matching_i i V E M L) = card (edge_as_set` matching_i i V E M L)\"\n  (is \"card ?Mi = card (?f ` _)\")\nproof -\n  from assms have \"bij_betw ?f ?Mi (?f ` ?Mi)\"\n    by (simp add: bij_betw_def matching_i_edges_as_sets edge_as_set_inj_on_Mi)\n  then show ?thesis by (rule bij_betw_same_card)\nqed\n\nlemma card_edge_as_set_Mi_twice_card_partitions:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"2 * card (edge_as_set`matching_i i V E M L) \n  = card (V_i i V E M L)\" (is \"2 * card ?C = card ?Vi\")\nproof -\n  from assms have 1: \"finite (\\<Union> ?C)\" \n    by (auto simp add: matching_def finite_graph_def \n      matching_i_def edge_as_set_def finite_subset)\n  show ?thesis unfolding V_i_def\n  proof (rule card_partition)\n    show \"finite ?C\" using 1 by (rule finite_UnionD)\n  next\n    show \"finite (\\<Union> ?C)\" using 1 .\n  next\n    fix c assume \"c \\<in> ?C\" then show \"card c = 2\"\n    proof (rule imageE)\n      fix x \n      assume 2: \"c = edge_as_set x\" and 3: \"x \\<in> matching_i i V E M L\"\n      with assms have \"x \\<in> E\" \n        unfolding matching_i_def matching_def by blast\n      then have \"fst x \\<noteq> snd x\" using assms 3 \n        by (auto simp add: matching_def finite_graph_def)\n      with 2 show ?thesis by (auto simp add: edge_as_set_def)\n    qed\n  next\n    fix x1 x2\n    assume 4: \"x1 \\<in> ?C\" and 5: \"x2 \\<in> ?C\" and 6: \"x1 \\<noteq> x2\"\n    {\n      fix e1 e2\n      assume 7: \"x1 = edge_as_set e1\" \"e1 \\<in> matching_i i V E M L\"\n        \"x2 = edge_as_set e2\" \"e2 \\<in> matching_i i V E M L\"\n      from assms have \"matching V E M\" by simp\n      moreover\n      from 7 assms have \"e1 \\<in> M\" and \"e2 \\<in> M\"\n        by (simp_all add: matching_i_def)\n      moreover from 6 7 have \"e1 \\<noteq> e2\" by blast\n      ultimately have \"x1 \\<inter> x2 = {}\" unfolding 7 \n        by (rule matching_disjointness)\n    }\n    with 4 5 show \"x1 \\<inter> x2 = {}\" by clarsimp\n  qed\nqed\n\nlemma card_Mi_twice_card_Vi:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"2 * card (matching_i i V E M L) = card (V_i i V E M L)\"\nproof -\n  from assms have \"finite (V_i i V E M L)\"\n    by (auto simp add: edge_as_set_def finite_subset\n      matching_def finite_graph_def V_i_def matching_i_def )\n  with assms show ?thesis \n    by (simp add: card_Mi_eq_card_edge_as_set_Mi \n      card_edge_as_set_Mi_twice_card_partitions V_i_def)\nqed\n\nlemma card_Mi_le_floor_div_2_Vi:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"card (matching_i i V E M L) \\<le> (card (V_i i V E M L)) div 2\"\n  using card_Mi_twice_card_Vi[OF assms]\n  by arith\n\nlemma card_Vi_le_NVLi:\n  assumes \"i>1 \\<and> matching V E M\"\n  shows \"card (V_i i V E M L) \\<le> N V L i\"\n  unfolding N_def\nproof (rule card_mono)\n  show \"finite {v \\<in> V. L v = i}\" using assms \n    by (simp add: matching_def finite_graph_def)\nnext\n  let ?A = \"edge_as_set ` matching_i i V E M L\"\n  let ?C = \"{v \\<in> V. L v = i}\" \n  show \"V_i i V E M L \\<subseteq> ?C\" using assms unfolding V_i_def\n  proof (intro Union_least)\n    fix X assume \"X \\<in> ?A\"\n    with assms have \"\\<exists>x \\<in> matching_i i V E M L. edge_as_set x = X\"\n      by (simp add: matching_i_edges_as_sets)\n    with assms show \"X \\<subseteq> ?C\" \n      unfolding finite_graph_def matching_def\n        matching_i_def edge_as_set_def by blast\n  qed\nqed\n\nsubsection {* @{text \"|Mi| \\<le> \\<lfloor>ni/2\\<rfloor>\"} *}\n\nlemma card_Mi_le_floor_div_2_NVLi:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"card (matching_i i V E M L) \\<le> (N V L i) div 2\"\nproof -  \n  from assms have \"card (V_i i V E M L) \\<le> (N V L i)\"\n    by (simp add: card_Vi_le_NVLi) \n  then have \"card (V_i i V E M L) div 2 \\<le> (N V L i) div 2\"\n    by simp\n  moreover from assms have \n    \"card (matching_i i V E M L) \\<le> card (V_i i V E M L) div 2\"\n    by (intro card_Mi_le_floor_div_2_Vi)\n  ultimately show ?thesis by auto\nqed\nsubsection {* @{text \"|M| \\<le> \\<Sum>|Mi|\"} *}\nlemma card_M_le_sum_card_Mi: \nassumes \"matching V E M\" and \"OSC L E\"\nshows \"card M \\<le> (\\<Sum> i \\<in> L`V. card (matching_i i V E M L))\"\n  (is \"card _ \\<le> ?CardMi\")\nproof -\n  let ?UnMi = \"\\<Union>x \\<in> L`V. matching_i x V E M L\"\n  from assms have 1: \"finite ?UnMi\"\n    by (auto simp add: matching_def \n      finite_graph_def matching_i_def finite_subset)\n  {\n    fix e assume e_inM: \"e \\<in> M\"\n    let ?v = \"relevant_endpoint L V e\"\n    have 1: \"e \\<in> matching_i (L ?v) V E M L\" using assms e_inM\n      proof cases\n        assume \"L (fst e) = 1\"\n        thus ?thesis using assms e_inM \n          by (simp add: relevant_endpoint_def matching_i_def)\n      next\n        assume a: \"L (fst e) \\<noteq> 1\" \n        have \"L (fst e) = 1 \\<or> L (snd e) = 1 \n          \\<or>  (L (fst e) = L (snd e) \\<and> L (fst e) >1)\"\n          using assms e_inM unfolding OSC_def \n          by (blast intro: expand_set_containment)\n        thus ?thesis using assms e_inM a \n          by (auto simp add: relevant_endpoint_def matching_i_def)\n      qed\n      have 2: \"?v \\<in> V\" using assms e_inM \n        by (auto simp add: matching_def \n          relevant_endpoint_def matching_i_def finite_graph_def)\n      then have \"\\<exists> v \\<in> V. e \\<in> matching_i (L v) V E M L\" using assms 1 2\n        by (intro bexI) \n    }\n    with assms have \"M \\<subseteq> ?UnMi\" by (auto)\n    with assms and 1 have \"card M \\<le> card ?UnMi\" by (intro card_mono)\n    moreover from assms have \"card ?UnMi = ?CardMi\"\n    proof (intro card_UN_disjoint) \n      show \"finite (L`V)\" using assms \n        by (simp add: matching_def finite_graph_def)\n    next \n      show \"\\<forall>i\\<in>L`V. finite (matching_i i V E M L)\" using assms\n        unfolding matching_def finite_graph_def matching_i_def\n        by (blast intro: finite_subset)\n    next \n      show \"\\<forall>i \\<in> L`V. \\<forall>j \\<in> L`V. i \\<noteq> j \\<longrightarrow> \n        matching_i i V E M L \\<inter> matching_i j V E M L = {}\" using assms\n        by (auto simp add: matching_i_def)\n    qed\n  ultimately show ?thesis by simp\nqed\n\ntheorem card_M_le_weight_NVLi:\n  assumes \"matching V E M\" and \"OSC L E\"\n  shows \"card M \\<le> weight {i \\<in> L ` V. i > 1} (N V L)\" (is \"_ \\<le> ?W\")\nproof -\n  let ?M01 = \"\\<Sum>i| i \\<in> L`V \\<and> (i=1 \\<or> i=0). card (matching_i i V E M L)\"\n  let ?Mgr1 = \"\\<Sum>i| i \\<in> L`V \\<and> 1 < i. card (matching_i i V E M L)\"\n  let ?Mi = \"\\<Sum> i\\<in>L`V. card (matching_i i V E M L)\"\n  have \"card M \\<le> ?Mi\" using assms by (rule card_M_le_sum_card_Mi) \n  moreover\n  have \"?Mi \\<le> ?W\"\n  proof -\n    let ?A = \"{i \\<in> L ` V. i = 1 \\<or> i = 0}\"\n    let ?B = \"{i \\<in> L ` V. 1 < i}\"\n    let ?g = \"\\<lambda> i. card (matching_i i V E M L)\"\n    let ?set01 = \"{ i. i : L ` V & (i = 1 | i = 0)}\"\n    have a: \"L ` V = ?A \\<union> ?B\" using assms by auto\n    have \"finite V\" using assms \n      by (simp add: matching_def finite_graph_def)\n    have b: \"setsum ?g (?A \\<union> ?B) = setsum ?g ?A + setsum ?g ?B\"\n      using assms `finite V` by (auto intro: setsum.union_disjoint)    \n    have 1: \"?Mi = ?M01+ ?Mgr1\" using assms a b \n      by (simp add: matching_def finite_graph_def)\n    moreover\n    have 0: \"card (matching_i 0 V E M L) = 0\" using assms\n      by (simp add: matching_i_def)\n      have 2: \"?M01 \\<le> N V L 1\" \n      proof cases\n        assume a: \"1 \\<in> L`V\"\n        have \"?M01 = card (matching_i 1 V E M L)\" \n        proof cases\n          assume b: \"0 \\<in> L`V\"\n          with a assms have  \"?set01 = {0, 1}\" by blast\n          thus ?thesis using assms 0 by simp\n        next\n          assume b: \"0 \\<notin> L`V\"\n          with a have \"?set01 = {1}\" by (auto simp del:One_nat_def)\n          thus ?thesis by simp\n        qed\n        thus ?thesis using assms a \n          by (simp del: One_nat_def, intro card_M1_le_NVL1)\n      next\n        assume a: \"1 \\<notin> L`V\"\n        show ?thesis\n        proof cases\n          assume b: \"0 \\<in> L`V\"\n          with a assms have  \"?set01 = {0}\" by (auto simp del:One_nat_def)\n          thus ?thesis using assms 0 by auto\n        next\n          assume b: \"0 \\<notin> L`V\"\n          with a have \"?set01 = {}\" by (auto simp del:One_nat_def)\n            then have \"?M01 = (\\<Sum>i\\<in>{}. card (matching_i i V E M L))\" by auto\n            thus ?thesis by simp\n          qed\n        qed\n      moreover\n      have 3: \"?Mgr1 \\<le> (\\<Sum>i|i\\<in>L`V \\<and> 1 < i. N V L i div 2)\" using assms \n        by (intro setsum_mono card_Mi_le_floor_div_2_NVLi, simp)\n    ultimately\n    show ?thesis using 1 2 3 assms by (simp add: weight_def)\n  qed\n  ultimately show ?thesis by simp\nqed\n\nsection {* Final Theorem *}\ntext{* The following theorem is due to Edmond~\\cite{Edmonds:matching}: *}\n\ntheorem maximum_cardinality_matching:\n  assumes \"matching V E M\" and \"OSC L E\"\n  and \"card M = weight {i \\<in> L ` V. i > 1} (N V L)\"\n  and \"matching V E M'\"\n  shows \"card M' \\<le> card M\"\n  using assms card_M_le_weight_NVLi\n  by simp\n\ntext{* The widely used algorithmic library LEDA has a certifying algorithm for maximum cardinality matching.\nThis Isabelle proof is part of the work done to verify the checker of this certifying algorithm. For more information see \\cite{VerificationofCertifyingComputations}. *}\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Max-Card-Matching/Matching.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.879146761176671, "lm_q1q2_score": 0.7929206462446177}}
{"text": "theory Concrete_Semantics_3_2\n  imports Main\nbegin \n(* from 3.1 *) \ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\" \n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a b) s = aval a s + aval b s\" \n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i1) (N i2) = N(i1+i2)\" |                       \n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a1 a2 = Plus a1 a2\"\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x ) = V x\" |\n\"asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)\"\n\n(* from 3.1 *)\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b1 b2) s = (bval b1 s \\<and> bval b2 s)\" |\n\"bval (Less a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b =  Not b\"\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b1 b2 = And b1 b2\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n1) (N n2) = Bc(n1 < n2)\" |\n\"less a1 a2 = Less a1 a2\"\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b1 b2) = and (bsimp b1) (bsimp b2)\" |\n\"bsimp (Less a1 a2) = less (asimp a1) (asimp a2)\"\n\nfun Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a b = And (Not(Less a b))  (Not(Less b a))\"\n\nfun Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a b = Not (And (Not (Less a b))  (Not(Eq a b)))\"\n\nlemma \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply(auto)\n  done\n\nlemma \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply(auto)\n  done\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 v) s = v\" |\n\"ifval (If a b c) s = (if (ifval a s) then (ifval b s) else (ifval c s))\" |\n\"ifval (Less2 a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc v) = Bc2 v\" |\n\"b2ifexp (Not b) = If (b2ifexp b) (Bc2 False) (Bc2 True)\" |\n\"b2ifexp (And b1 b2) = If (b2ifexp b1)  (b2ifexp  b2) (Bc2 False)\" |\n\"b2ifexp (Less a1 a2) = Less2  a1 a2\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 v) = Bc v\" |\n\"if2bexp (Less2 a b) = Less a b\" |\n\"if2bexp (If a b c) = And (Not (And (if2bexp a) (Not (if2bexp b))))(Not (And (Not (if2bexp a)) (Not (if2bexp c))))\"\n\nlemma \"bval b s = ifval (b2ifexp b) s\"\n  apply(induction b)\n  apply(auto)\n  done\n\nlemma \"ifval i s = bval (if2bexp i) s\"\n  apply(induction i)\n  apply(auto)\n  done\n\ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where     \n\"pbval (VAR x ) s = s x\" |\n\"pbval (NOT b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b1 b2) s = (pbval b1 s \\<and> pbval b2 s)\" |\n\"pbval (OR b1 b2) s = (pbval b1 s \\<or> pbval b2 s)\"\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (NOT (VAR x)) = True\" |\n\"is_nnf (NOT y) = False\" |\n\"is_nnf (OR a b) = (is_nnf a \\<and> is_nnf b)\" |\n\"is_nnf (AND a b) = (is_nnf a \\<and> is_nnf b)\"\n\n(* pushing NOT inwards as much as possible *)\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = VAR x\" |\n\"nnf (NOT (VAR x)) = NOT (VAR x)\" |\n\"nnf (NOT (NOT a)) = nnf a\" |\n\"nnf (NOT (OR  a b)) = AND (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (NOT (AND  a b)) = OR (nnf (NOT a)) (nnf (NOT b))\" |\n\"nnf (AND  a  b) = AND (nnf a) (nnf b)\" |\n\"nnf (OR  a  b) = OR (nnf a) (nnf b)\"\n                                      \nlemma nnf_preserv : \"pbval (nnf b) s = pbval b s\"\n  apply(induction b rule: nnf.induct)                  \n  apply(auto)                                 \n  done                                           \n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf (VAR x) = True\"|  \n\"is_dnf (NOT y) = True\" |\n\"is_dnf (OR a b) = (is_dnf a \\<and> is_dnf b)\" |\n\"is_dnf (AND (OR a b) c) = False\" | \n\"is_dnf (AND a (OR b c)) = False\" |\n\"is_dnf (AND a b) =  (is_dnf a \\<and> is_dnf b)\"\n                                        \nfun mk_dnf_conj :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"mk_dnf_conj e (OR a b) = OR (mk_dnf_conj e a) (mk_dnf_conj e b)\" |\n\"mk_dnf_conj (OR a b) e  = OR (mk_dnf_conj a e) (mk_dnf_conj b e)\" |\n\"mk_dnf_conj x  y  = AND x y\"\n             \nlemma mk_dnf_preserv : \"pbval (mk_dnf_conj a b) s = (pbval a s \\<and> pbval b s)\"\n  apply(induction a b rule: mk_dnf_conj.induct)\n  apply(auto)\n  done\n\n\nlemma mk_dnf_is_nnf: \"is_nnf a \\<Longrightarrow>\n           is_nnf b \\<Longrightarrow>\n           is_nnf (mk_dnf_conj  a  b)\"\n  apply(induction a b rule:  mk_dnf_conj.induct)\n  apply(auto)\n  done \n\n\n(* many counter examples occurs this way, TODO: make function for 'AND' *)\n                                        \nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where            \n\"dnf_of_nnf (VAR x) = VAR x\" |\n\"dnf_of_nnf (NOT y) = NOT y\" |\n\"dnf_of_nnf (OR a b) = OR (dnf_of_nnf a) (dnf_of_nnf b)\" |                                                       \n\"dnf_of_nnf (AND a b) =  mk_dnf_conj (dnf_of_nnf a) (dnf_of_nnf b)\"                                                  \n                                                  \nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply(induction b rule: dnf_of_nnf.induct )      \n  apply(simp_all add: mk_dnf_preserv)                                           \n  done                                             \n                               \nvalue \"is_dnf(dnf_of_nnf(AND (OR (VAR []) (VAR [])) (OR (VAR []) (VAR []))))\"\n\nlemma mk_dnf_is_dnf: \"is_dnf a \\<Longrightarrow>\n           is_dnf b \\<Longrightarrow>\n           is_dnf (mk_dnf_conj  a  b)\"\n  apply(induction a b rule:  mk_dnf_conj.induct)\n  apply(auto)\n  done \n                                  \nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"     \n  apply(induction b rule: dnf_of_nnf.induct)\n  apply(auto simp add:  mk_dnf_is_dnf)                                                                                \n  done                                      \nend                                                    \n", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/previous_studied_result/Concrete_Semantics_3_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990283, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7926400884249745}}
{"text": "(*  Title:      RealInt.thy\n    Author:     Sven Linker\n\nClosed, non-empty intervals based on real numbers. Defines functions left, right\nto refer to the left (resp. right) border of an interval. \n\nDefines a length function as the difference between left and right border\nand a function to shift an interval by a real value (i.e., the value is added\nto both borders).\n\nInstantiates \"order\", as a notion of sub-intervals.\n\nAlso contains a \"chopping\" predicate R_Chop(r,s,t): r can be divided into\nsub-intervals s and t.\n*)\n\nsection \\<open>Closed Real-valued Intervals\\<close>\n\ntext\\<open>We define a type for real-valued intervals. It consists of pairs of real numbers, where\nthe first is lesser or equal to the second. Both endpoints are understood to be part of\nthe interval, i.e., the intervals are closed. This also implies that we do not\nconsider empty intervals. \n\nWe define a measure on these intervals as the difference between the left and\nright endpoint. In addition, we introduce a notion of shifting an interval by\na real value \\(x\\). Finally, an interval \\(r\\) can be chopped into \\(s\\) and\n\\(t\\), if the left endpoint of \\(r\\) and \\(s\\) as well as the right endpoint\nof \\(r\\) and \\(t\\) coincides, and if the right endpoint of \\(s\\) is \nthe left endpoint of \\(t\\).\n\\<close>\n\ntheory RealInt\n  imports HOL.Real\nbegin\n  \ntypedef real_int = \"{r::(real*real) . fst r \\<le> snd r}\"\n  by auto\nprint_theorems\nsetup_lifting type_definition_real_int\nprint_theorems\nprint_quot_maps\n  \nlift_definition left::\"real_int \\<Rightarrow> real\" is fst proof - qed\nlift_definition right::\"real_int \\<Rightarrow> real\" is snd proof - qed\n  \nlemmas[simp] = left.rep_eq right.rep_eq  \n  \nlocale real_int\ninterpretation real_int_class?: real_int .\n\ncontext real_int\nbegin\n  \ndefinition length :: \"real_int \\<Rightarrow> real\" (\"\\<parallel>_\\<parallel>\" 70)\n  where \"\\<parallel>r\\<parallel> = right r - left r\"\nprint_theorems\n\ndefinition shift::\"real_int \\<Rightarrow> real \\<Rightarrow> real_int\" (\" shift _ _\")\n  where \"(shift r x) = Abs_real_int(left r +x, right r +x)\"\n\ndefinition R_Chop :: \"real_int \\<Rightarrow> real_int \\<Rightarrow> real_int \\<Rightarrow> bool\" (\"R'_Chop'(_,_,_')\" 51)\n  where rchop_def :\n    \"R_Chop(r,s,t) ==  left r  = left s \\<and> right s = left t \\<and> right r =  right t\"\n\ndefinition combine :: \"real_int \\<Rightarrow> real_int \\<Rightarrow> real_int\" \n  where \"combine r s == Abs_real_int (left r, right s)\" \n\ntext{*Create an interval of length x starting at r  *}\n\ndefinition stretch :: \"real \\<Rightarrow> real \\<Rightarrow> real_int \"\n  where \"stretch r x == Abs_real_int(r, r+x)\" \n\ndefinition mk_empty:: \"real \\<Rightarrow> real_int\"\n  where \"mk_empty x == Abs_real_int(x,x)\"\n\n(* TODO: prove properties of this definition  and use it to define length *)\ndefinition intersect :: \"real_int \\<Rightarrow> real_int \\<Rightarrow> real_int\" \n  where \"intersect r s == \n    if (left s > right r)  \n      then   mk_empty (right r) \n    else\n      if (right (s) < left r) \n        then  mk_empty (left r )\n      else  \n       Abs_real_int (max (left (r)) (left (s)), \n                      min (right (r)) (right (s)))\"\n\nend\n\ntext \\<open>The intervals defined in this way allow for the definition of an order: \nthe subinterval relation.\\<close>\n  \ninstantiation real_int :: order\nbegin\ndefinition \"less_eq_real_int r s \\<equiv> (left r \\<ge> left s) \\<and> (right r \\<le> right s)\"\ndefinition \"less_real_int r s \\<equiv> (left r \\<ge> left s) \\<and> (right r \\<le> right s) \n                                  \\<and>  \\<not>((left s \\<ge> left r) \\<and> (right s \\<le> right r))\"\ninstance   \nproof \n  fix r s t :: real_int\n  show \"(r < s) = (r \\<le> s \\<and> \\<not> s \\<le> r)\" using less_eq_real_int_def less_real_int_def by auto\n  show \"r \\<le> r\" using less_eq_real_int_def by auto\n  show \"r \\<le> s \\<Longrightarrow> s \\<le> t \\<Longrightarrow> r \\<le> t\" using less_eq_real_int_def by auto\n  show \"r \\<le> s \\<Longrightarrow> s \\<le> r \\<Longrightarrow> r = s\"\n    by (metis Rep_real_int_inject left.rep_eq less_le less_eq_real_int_def \n        not_le prod.collapse right.rep_eq)\nqed\nend\n  \ncontext real_int\nbegin\n  \nlemma left_leq_right: \"left r \\<le> right r\" \n  using Rep_real_int left.rep_eq right.rep_eq by auto\n\nlemma left_right_eq: \"r = s \\<longleftrightarrow> left r = left s \\<and> right r = right s\" \n  by (metis Rep_real_int_inject left.rep_eq prod.expand right.rep_eq)\n\n    \nlemma length_ge_zero :\" \\<parallel>r\\<parallel> \\<ge> 0\" using left_leq_right \n  by (simp add: length_def)\n\nlemma length_leq: \"t \\<le> r \\<longrightarrow> \\<parallel>t\\<parallel> \\<le> \\<parallel>r\\<parallel> \" \n  by (simp add: length_def less_eq_real_int_def)\n\nlemma consec_add:\n  \"left r = left s \\<and> right r = right t \\<and> right s = left t \\<Longrightarrow> \\<parallel>r\\<parallel> = \\<parallel>s\\<parallel> + \\<parallel>t\\<parallel>\"\n  by (simp add:length_def)\n    \nlemma length_zero_iff_borders_eq:\"\\<parallel>r\\<parallel> = 0 \\<longleftrightarrow> left r = right r\"\n  using length_def by auto\n\n\n\nlemma shift_left_eq_right:\"left (shift r x) \\<le> right (shift r x)\"\n  using left_leq_right .\n    \n\n\nlemma shift_inj: \"(shift r x) = (shift s x) \\<longrightarrow> r = s\"  \nproof\n  assume 1:\"(shift r x) = (shift s x)\" \n  have 2:\"left r + x = left s + x\" \n    using \"1\" Abs_real_int_inject left_leq_right real_int_class.shift_def by auto\n  have 3: \"right r + x = right s + x\" \n    using \"1\" Abs_real_int_inject left_leq_right real_int_class.shift_def by auto\n  show \"r = s\" using 2 3 \n    by (metis Rep_real_int_inverse add_diff_cancel_left' left.rep_eq linordered_field_class.sign_simps(27) prod.collapse right.rep_eq)\nqed\n\nlemma shift_inj_amount: \"(shift r x) = (shift r y) \\<longrightarrow> x = y\" \n  using Abs_real_int_inject left_leq_right real_int_class.shift_def by auto\n\n\nlemma shift_additivity:\"(shift r (x+y)) = shift (shift r x) y\" \nproof -\n  have 1:\"(shift r (x+y)) = Abs_real_int ((left r) +(x+y), (right r)+(x+y))\"\n    using shift_def by auto\n  have 2:\"(left r) +(x+y) \\<le> (right r)+(x+y)\" using left_leq_right by auto\n  hence left:\"left (shift r (x+y)) = (left r) +(x+y)\" \n    by (simp add: Abs_real_int_inverse 1)\n  from 2 have right:\"right (shift r (x+y)) = (right r) +(x+y)\" \n    by (simp add: Abs_real_int_inverse 1)\n  have 3:\"(shift (shift r x) y) = Abs_real_int(left (shift r x) +y, right(shift r x)+y)\"\n    using shift_def by auto\n  have l1:\"left (shift r x) = left r + x\"\n    using shift_def  Abs_real_int_inverse \"2\" fstI mem_Collect_eq prod.sel(2) left.rep_eq\n    by auto\n  have r1:\"right (shift r x) = right r + x\" \n    using shift_def Abs_real_int_inverse \"2\" fstI mem_Collect_eq prod.sel(2) right.rep_eq\n    by auto\n  from 3 and l1 and r1 have \n    \"(shift (shift r x) y) = Abs_real_int(left  r+x+y, right  r+x+y)\"\n    by auto\n  with 1 show ?thesis by (simp add: add.assoc)\nqed\n\nlemma stretch_left_leq_right : \"left (stretch r x) \\<le> right (stretch r x)\" \n  using left_leq_right by auto\n\nlemma stretch_left : \"x \\<ge> 0 \\<longrightarrow> left (stretch r x) = r \" \n  by (simp add: Abs_real_int_inverse local.stretch_def)\n\nlemma stretch_right: \"x\\<ge> 0 \\<longrightarrow> right (stretch r x) = r+x\"\n  by (simp add: Abs_real_int_inverse local.stretch_def)\n\nlemma stretch_length: \"x \\<ge> 0 \\<longrightarrow> \\<parallel>stretch r x\\<parallel> = x\" \n  using stretch_left stretch_right length_def\n  by (simp)\n\nlemma empty_stretch: \"mk_empty r = stretch r 0\" \n  by (simp add: mk_empty_def stretch_def)\n\nlemma empty_length: \"\\<parallel>mk_empty r\\<parallel> = 0\" \n  by (simp add: empty_stretch stretch_length)\n\nlemma empty_left: \"left (mk_empty r) = r\" \n  using empty_stretch stretch_left by auto\n\nlemma empty_right: \"right (mk_empty r) = r\" \n  using empty_stretch stretch_right by auto\n\n\nlemma chop_combine: \"R_Chop(r,s,t) \\<longrightarrow> r = combine s t\" \n  by (metis Rep_real_int_inverse combine_def left.rep_eq prod.collapse rchop_def right.rep_eq)\n\nlemma combine_leq_left: \"right s = left t \\<longrightarrow> s \\<le> combine s t\"  \nproof\n  assume 1:\"right s = left t\" \n  have 2: \"left s \\<ge> left (combine s t)\" using 1\n    by (metis Rep_real_int_cases Rep_real_int_inverse left.rep_eq left_leq_right local.combine_def mem_Collect_eq order_refl order_trans prod.sel(1) prod.sel(2))\n  have 3: \"right s \\<le> right (combine s t)\" using 1 left_leq_right \n    by (metis (no_types, lifting) CollectI Rep_real_int_cases Rep_real_int_inverse combine_def  dual_order.trans left.rep_eq   prod.sel(1) prod.sel(2) right.rep_eq)\n  show \"s \\<le> combine s t\"  using 2 3 \n    by (simp add: less_eq_real_int_def)\nqed\n\nlemma combine_leq_right: \"right s = left t \\<longrightarrow> t \\<le> combine s t\"  \nproof\n  assume 1:\"right s = left t\" \n  have 2: \"left t \\<ge> left (combine s t)\" using 1\n    by (metis Rep_real_int_cases Rep_real_int_inverse left.rep_eq left_leq_right local.combine_def mem_Collect_eq  order_trans prod.sel(1) prod.sel(2))\n  have 3: \"right t \\<le> right (combine s t)\" using 1 left_leq_right \n    by (metis Abs_real_int_inverse CollectI combine_def dual_order.refl order_trans prod.sel(1) prod.sel(2) right.rep_eq)\n  show \"t \\<le> combine s t\"  using 2 3 \n    by (simp add: less_eq_real_int_def)\nqed\n\nlemma shift_combine_comm: \"(right r = left s) \\<longrightarrow> combine (shift r x) (shift s x) = shift (combine r s) x\" \nproof \n  assume assm: \"right r = left s\" \n  have 0:\"combine (shift r x) (shift s x) = Abs_real_int (left (shift r x), right (shift s x))\" \n    by (simp add: combine_def)\n  have 1:\"left (shift r x) = left r + x\" \n    using Abs_real_int_inverse left_leq_right real_int_class.shift_def by auto\n  have 2:\"right (shift s x) = right s + x\" \n    using Abs_real_int_inverse length_def length_ge_zero real_int_class.shift_def by auto\n  have 3: \"left (combine r s) = left r\" using combine_def assm Abs_real_int_inverse  \n    by (metis fst_conv left.rep_eq left_leq_right mem_Collect_eq order_trans snd_conv)\n  have 4: \"right (combine r s) = right s\"  using combine_def assm Abs_real_int_inverse \n    by (metis fst_conv right.rep_eq left_leq_right mem_Collect_eq order_trans snd_conv)\n  have \"(shift (combine r s) x) = Abs_real_int ((left (combine r s)) + x ,( right (combine r s)) + x)\" \n    by (simp add: real_int_class.shift_def)\n  then have \"(shift (combine r s) x) = Abs_real_int ((left r + x), (right s + x))\" using 3 4 \n    by auto\n  then have \"(shift (combine r s) x) = Abs_real_int ((left (shift r x)), (right (shift s  x)))\" using 1 2 \n    by simp\n  then show \"combine (shift r x) (shift s x) = shift (combine r s) x\" using 0 \n    by simp\nqed\n\nlemma shift_combine:\"(left t = right s) \\<longrightarrow> (r = combine s t) \\<longleftrightarrow> (shift r x) = combine (shift s x) (shift t x)\" \nproof\n  assume 1:\"(left t = right s)\"\n   show \" (r = combine s t) \\<longleftrightarrow> (shift r x) = combine (shift s x)  (shift t x)\"\n  proof\n    assume 2:\"(r = combine s t)\" \n    have 3:\"left r = left s\" using combine_def Abs_real_int_inverse Rep_real_int 2 \n      by (metis \"1\" fst_conv left.rep_eq left_leq_right mem_Collect_eq order_trans snd_conv)\n    have 4: \"right r = right t\" \n      by (metis \"1\" \"2\" Rep_real_int_cases Rep_real_int_inverse left_leq_right local.combine_def mem_Collect_eq order_trans prod.sel(1) prod.sel(2) right.rep_eq)\n    show  \"(shift r x) = combine (shift s x) (shift t x)\" using 3 4 \n      using Abs_real_int_inverse combine_def length_def length_ge_zero real_int_class.shift_def by auto\n  next\n    assume 2:\"(shift r x) = combine (shift s x) (shift t x)\"\n    have \"combine (shift s x) (shift t x) = shift (combine s t) x\" using shift_combine_comm 1 by auto\n    then show \"r=combine s t\" \n      using \"2\" shift_inj by auto\n  qed\nqed\n\n\n\nlemma chop_always_possible': \"\\<exists> s t. R_Chop(r,s,t)\" \n  using chop_always_possible by blast \n(*proof -\n  fix x\n  obtain s where l:\"left x \\<le> s  \\<and> s \\<le> right x\" \n    using left_leq_right by auto\n  obtain x1  where x1_def:\"x1 = Abs_real_int(left x,s)\"  by simp\n  obtain x2 where x2_def:\"x2 = Abs_real_int(s, right x)\" by simp\n  have x1_in_type:\"(left x, s) \\<in> {r :: real*real . fst r \\<le> snd r }\" using l by auto \n  have x2_in_type:\"(s, right x) \\<in> {r :: real*real . fst r \\<le> snd r }\" using l by auto \n  have 1:\"left x = left x1\" using x1_in_type l Abs_real_int_inverse \n    by (simp add:  x1_def)\n  have 2:\"right x1 = s\" \n    using Abs_real_int_inverse x1_def x1_in_type right.rep_eq by auto\n  have 3:\"right x1 = left x2\" \n    using Abs_real_int_inverse x1_def x1_in_type x2_def x2_in_type left.rep_eq by auto\n  from 1 and 2 and 3 have \"R_Chop(x,x1,x2)\" \n    using Abs_real_int_inverse rchop_def snd_conv x2_def x2_in_type by auto \n  then show \"\\<exists>x1 x2. R_Chop(x,x1,x2)\" by blast\nqed\n*)\n\nlemma chop_singleton_right:\n  obtains s where \"R_Chop(r,r,s)\"\nproof -\n  obtain y where  \"y =  Abs_real_int(right r, right r)\" by simp\n  then have \"R_Chop(r,r,y)\" \n    by (simp add: Abs_real_int_inverse real_int.rchop_def)\n  then show ?thesis using that by blast\nqed\n\nlemma chop_singleton_right': \"\\<exists> s. R_Chop(r,r,s)\" \n  using chop_singleton_right by blast\n(*proof -\n  fix x \n  obtain y where  \"y =  Abs_real_int(right x, right x)\" by simp\n  then have \"R_Chop(x,x,y)\" \n    by (simp add: Abs_real_int_inverse real_int.rchop_def)\n  then show \"\\<exists>y. R_Chop(x,x,y)\" by blast\nqed\n*)\n\nlemma chop_singleton_left: \n  obtains s where \"R_Chop(r,s,r)\"  \nproof  -\n  obtain y where  \"y =  Abs_real_int(left r, left r)\" by simp\n  then have \"R_Chop(r,y,r)\" \n    by (simp add: Abs_real_int_inverse real_int.rchop_def)\n  then show ?thesis using that by blast\nqed\n\nlemma chop_singleton_left': \"\\<exists> s. R_Chop(r,s,r)\"  \n  using chop_singleton_left by blast\n(*proof -\n  fix x \n  obtain y where  \"y =  Abs_real_int(left x, left x)\" by simp\n  then have \"R_Chop(x,y,x)\" \n    by (simp add: Abs_real_int_inverse real_int.rchop_def)\n  then show \"\\<exists>y. R_Chop(x,y,x)\" by blast\nqed\n*)\n  \nlemma chop_add_length:\"R_Chop(r,s,t) \\<Longrightarrow> \\<parallel>r\\<parallel> = \\<parallel>s\\<parallel> + \\<parallel>t\\<parallel>\"\n  using consec_add by (simp add: rchop_def)\n    \nlemma chop_add_length_ge_0:\"R_Chop(r,s,t) \\<and> \\<parallel>s\\<parallel> > 0 \\<and> \\<parallel>t\\<parallel>>0 \\<longrightarrow> \\<parallel>r\\<parallel>>0\"\n  using chop_add_length by auto\n\nlemma chop_dense:\n  assumes r:\"\\<parallel>r\\<parallel> > 0\" \n  obtains s and t where \"R_Chop(r,s,t)\" and \"\\<parallel>s\\<parallel>> 0\" and \"\\<parallel>t\\<parallel> > 0\" \nproof -\n  have ff1: \" left r < right r\"\n    using Rep_real_int \\<open>0 < \\<parallel>r\\<parallel>\\<close> length_def by auto\n  have l_in_type:\"(left r, right r) \\<in> {r :: real*real . fst r \\<le> snd r }\" \n    using Rep_real_int by auto      \n  obtain x where  x_def:\" x  = (left r + right r) / 2\" \n    by blast\n  have x_gr:\"x > left r\" using ff1 field_less_half_sum x_def by blast\n  have x_le:\"x < right r\" using ff1 x_def by (simp add: field_sum_of_halves)\n  obtain s where s_def:\"s = Abs_real_int(left r, x)\"  by simp\n  obtain t where t_def:\"t = Abs_real_int(x, right r)\"  by simp\n  have s_in_type:\"(left r, x) \\<in> {r :: real*real . fst r \\<le> snd r }\" \n    using x_def x_le by auto\n  have t_in_type:\"(x, right r) \\<in> {r :: real*real . fst r \\<le> snd r }\" \n    using x_def x_gr by auto\n  have s_gr_0:\"\\<parallel>s\\<parallel> > 0\" \n    using Abs_real_int_inverse s_def length_def x_gr by auto\n  have t_gr_0:\"\\<parallel>t\\<parallel> > 0\" \n    using Abs_real_int_inverse t_def length_def x_le by auto\n  have \"R_Chop(r,s,t)\" \n    using Abs_real_int_inverse s_def s_in_type t_def t_in_type rchop_def by auto\n  hence \"R_Chop(r,s,t) \\<and> \\<parallel>s\\<parallel>>0 \\<and> \\<parallel>t\\<parallel>>0\" \n    using s_gr_0 t_gr_0 by blast\n  then show ?thesis using that by blast\nqed\n\n(*lemma chop_dense' : \"\\<parallel>r\\<parallel> > 0 \\<longrightarrow> (\\<exists> s t. R_Chop(r,s,t) \\<and> \\<parallel>s\\<parallel>>0 \\<and> \\<parallel>t\\<parallel>>0)\"\n  using chop_dense by blast\n*)\n(*\nproof\n  assume \"\\<parallel>r\\<parallel> > 0\"\n  have ff1: \" left r < right r\"\n    using Rep_real_int \\<open>0 < \\<parallel>r\\<parallel>\\<close> length_def by auto\n  have l_in_type:\"(left r, right r) \\<in> {r :: real*real . fst r \\<le> snd r }\" \n    using Rep_real_int by auto      \n  obtain x where  x_def:\" x  = (left r + right r) / 2\" \n    by blast\n  have x_gr:\"x > left r\" using ff1 field_less_half_sum x_def by blast\n  have x_le:\"x < right r\" using ff1 x_def by (simp add: field_sum_of_halves)\n  obtain s where s_def:\"s = Abs_real_int(left r, x)\"  by simp\n  obtain t where t_def:\"t = Abs_real_int(x, right r)\"  by simp\n  have s_in_type:\"(left r, x) \\<in> {r :: real*real . fst r \\<le> snd r }\" \n    using x_def x_le by auto\n  have t_in_type:\"(x, right r) \\<in> {r :: real*real . fst r \\<le> snd r }\" \n    using x_def x_gr by auto\n  have s_gr_0:\"\\<parallel>s\\<parallel> > 0\" \n    using Abs_real_int_inverse s_def length_def x_gr by auto\n  have t_gr_0:\"\\<parallel>t\\<parallel> > 0\" \n    using Abs_real_int_inverse t_def length_def x_le by auto\n  have \"R_Chop(r,s,t)\" \n    using Abs_real_int_inverse s_def s_in_type t_def t_in_type rchop_def by auto\n  hence \"R_Chop(r,s,t) \\<and> \\<parallel>s\\<parallel>>0 \\<and> \\<parallel>t\\<parallel>>0\" \n    using s_gr_0 t_gr_0 by blast\n  thus \"\\<exists> s t. R_Chop(r,s,t) \\<and> \\<parallel>s\\<parallel>>0 \\<and> \\<parallel>t\\<parallel>>0\" by blast\nqed  \n*)\n\nlemma chop_assoc1:\n  \"R_Chop(r,r1,r2) \\<and> R_Chop(r2,r3,r4) \n     \\<longrightarrow> R_Chop(r, combine r1 r3, r4) \n        \\<and> R_Chop(combine r1 r3, r1,r3)\"\nproof\n  assume assm: \"R_Chop(r,r1,r2) \\<and> R_Chop(r2,r3,r4)\"\n  have 1:\"R_Chop(combine r1 r3, r1,r3)\" \n    by (metis (no_types, lifting) assm  combine_def eq_onp_same_args left.abs_eq left.rep_eq left_leq_right order_trans prod.sel(1) prod.sel(2) rchop_def right.abs_eq right.rep_eq)\n  have 2:\" R_Chop(r, combine r1 r3, r4)\" \n    using \"1\" assm rchop_def by fastforce\n  show \" R_Chop(r, combine r1 r3, r4) \n        \\<and> R_Chop(combine r1 r3, r1,r3)\" using 1 2 by blast\nqed\n\n(*\nlemma chop_assoc1':\n  \"R_Chop(r,r1,r2) \\<and> R_Chop(r2,r3,r4) \n     \\<longrightarrow> R_Chop(r, Abs_real_int(left r1, right r3), r4) \n        \\<and> R_Chop(Abs_real_int(left r1, right r3), r1,r3)\"\nproof \n  assume assm: \"R_Chop(r,r1,r2) \\<and> R_Chop(r2,r3,r4)\"\n  let ?y1 = \" Abs_real_int(left r1, right r3)\" \n  have l1:\"left r1 = left ?y1\" \n    by (metis  Abs_real_int_inverse assm fst_conv left.rep_eq mem_Collect_eq\n        order_trans real_int.left_leq_right real_int.rchop_def snd_conv)\n  have r1:\"right ?y1 = right r3\" \n    by (metis  Rep_real_int_cases Rep_real_int_inverse assm fst_conv mem_Collect_eq\n        order_trans real_int.left_leq_right real_int.rchop_def right.rep_eq snd_conv)    \n  have g1:\"R_Chop(r, ?y1, r4)\" using assm  rchop_def r1 l1 by simp\n  have g2:\"R_Chop(?y1, r1,r3)\" using assm  rchop_def r1 l1 by simp\n  show \"R_Chop(r, ?y1, r4) \\<and> R_Chop(?y1, r1,r3)\" using g1 g2 by simp\nqed\n*)\n\nlemma chop_assoc2: \n  \"R_Chop(r,r1,r2) \\<and> R_Chop(r1,r3,r4) \n    \\<longrightarrow> R_Chop(r,r3,  combine  r4 r2) \n      \\<and> R_Chop(combine r4 r2, r4,r2)\"\nproof\n  assume 0:\"R_Chop(r,r1,r2) \\<and> R_Chop(r1,r3,r4)\"\n  then have 1:\"R_Chop(combine r4 r2, r4,r2)\" \n    by (metis (no_types, lifting) Abs_real_int_inverse left.rep_eq left_leq_right local.combine_def mem_Collect_eq order_trans prod.sel(1) prod.sel(2) rchop_def right.rep_eq)\n  then have 2:\"R_Chop(r,r3,  combine  r4 r2)\" using 0 \n    by (simp add: rchop_def)\n  from 1 and 2 show \" R_Chop(r,r3,  combine  r4 r2) \n      \\<and> R_Chop(combine r4 r2, r4,r2)\" by blast\nqed\n\n(*\nlemma chop_assoc2': \n  \"R_Chop(r,r1,r2) \\<and> R_Chop(r1,r3,r4) \n    \\<longrightarrow> R_Chop(r,r3, Abs_real_int(left r4, right r2)) \n      \\<and> R_Chop(Abs_real_int(left r4, right r2), r4,r2)\"\nproof \n  assume assm: \"R_Chop(r,r1,r2) \\<and> R_Chop(r1,r3,r4)\"\n  let ?y1 = \" Abs_real_int(left r4, right r2)\" \n  have \"left ?y1 \\<le> right ?y1\"\n    using real_int.left_leq_right by blast\n  have f1: \"left r4 = right r3\"\n    using assm real_int.rchop_def by force\n  then have right:\"right r3 \\<le> right r2\"\n    by (metis (no_types) assm order_trans real_int.left_leq_right real_int.rchop_def)\n  then have l1:\"left ?y1 = left r4\" using f1 by (simp add: Abs_real_int_inverse)\n  have r1:\"right ?y1 = right r2\" \n    using Abs_real_int_inverse right f1 by auto\n  have g1:\"R_Chop(r, r3, ?y1)\" using assm  rchop_def r1 l1 by simp\n  have g2:\"R_Chop(?y1, r4,r2)\" using assm  rchop_def r1 l1 by simp\n  show \"R_Chop(r, r3, ?y1) \\<and> R_Chop(?y1, r4,r2)\" using g1 g2 by simp\nqed\n*)\n\nlemma chop_leq1:\"R_Chop(r,s,t) \\<longrightarrow> s \\<le> r\" \n  by (metis (full_types) less_eq_real_int_def order_refl real_int.left_leq_right real_int.rchop_def)\n    \nlemma chop_leq2:\"R_Chop(r,s,t) \\<longrightarrow> t \\<le> r\"\n  by (metis (full_types) less_eq_real_int_def order_refl real_int.left_leq_right real_int.rchop_def)\n    \nlemma chop_empty1:\"R_Chop(r,s,t) \\<and> \\<parallel>s\\<parallel> = 0 \\<longrightarrow> r = t \" \n  by (metis (no_types, hide_lams) Rep_real_int_inject left.rep_eq prod.collapse\n      real_int.length_zero_iff_borders_eq real_int.rchop_def right.rep_eq)\n\nlemma chop_empty2:\"R_Chop(r,s,t) \\<and> \\<parallel>t\\<parallel> = 0 \\<longrightarrow> r = s \" \n  by (metis (no_types, hide_lams) Rep_real_int_inject left.rep_eq prod.collapse\n      real_int.length_zero_iff_borders_eq real_int.rchop_def right.rep_eq)\n\nlemma intersect_left : \"left (intersect r s) \\<ge> left r\" using Abs_real_int_inverse \n  using empty_left left_leq_right local.intersect_def by auto\n\nlemma intersect_right : \"right (intersect r s) \\<le> right r\" using Abs_real_int_inverse \n  using empty_right left_leq_right local.intersect_def by auto\n\nlemma intersect_leq : \"intersect r s \\<le> r\" \n  using intersect_left intersect_right less_eq_real_int_def by auto\n\nlemma intersect_left': \"left (s) \\<le> right (r) \\<longrightarrow> left (intersect r s) \\<ge> left (s)\" \nproof\n  assume assm:\"left (s) \\<le> right (r)\"\n  then show \"left (intersect r s) \\<ge> left (s)\" \n  proof (cases \"right (s) < left (r)\" )\n    case True\n    then show ?thesis using   real_int.left_leq_right  \n      by (meson intersect_left less_imp_triv not_le order_trans)\n  next\n    case False\n    then have \"intersect r s = \n    Abs_real_int (max (left r) (left s), \n                   min (right r) (right s))\"\n      using intersect_def assm \n      by simp\n    then have \"left (intersect r s) = max (left (r)) (left (s))\" \n      using Abs_real_int_inverse False assm real_int.left_leq_right \n      by auto\n    then show ?thesis  by linarith\n  qed\nqed\n\nlemma intersect_right': \n  \"right s \\<ge> left r \\<longrightarrow> right (intersect r s) \\<le> right s\" \nproof\n  assume assm:\"right (s) \\<ge> left (r)\"\n  then show \"right (intersect r s) \\<le> right (s)\" \n  proof (cases \"left (s) > right (r)\" )\n    case True\n    then show ?thesis using  intersect_right real_int.left_leq_right \n      by (meson le_less_trans not_less order.asym)\n  next\n    case False\n    then have \"intersect r s = \n      Abs_real_int (max (left (r)) (left (s)), \n                     min (right (r)) (right (s)))\"\n      using intersect_def assm by auto\n    then have \"right (intersect r s) = min (right (r)) (right (s))\" \n      using Abs_real_int_inverse False assm real_int.left_leq_right\n      by auto\n    then show ?thesis  by linarith\n  qed\nqed    \n\nlemma intersect_with_zero: \"\\<parallel>s\\<parallel> = 0 \\<longrightarrow> \\<parallel>intersect r s\\<parallel> = 0\" \nproof\n  assume \"\\<parallel>s\\<parallel> = 0\"\n  then obtain x where \"s = mk_empty x\" \n    using empty_left empty_right left_right_eq length_zero_iff_borders_eq by auto\n  consider (1) \"x < left r\" | (2) \"x > right r\" | (3) \"left r \\<le> x \\<and> x \\<le> right r\" \n    using not_less by blast\n  then show \"\\<parallel>intersect r s \\<parallel> = 0\" \n  proof (cases)\n    case 1 \n    show ?thesis \n      using \"1\" \\<open>s = mk_empty x\\<close> empty_left empty_length length_def local.intersect_def by auto\n  next\n    case 2\n    show ?thesis \n      using \"2\" \\<open>s = mk_empty x\\<close> empty_length empty_right length_zero_iff_borders_eq local.intersect_def by auto\n  next\n    case 3\n    have a:\"max (left r) x = x\" using 3\n      by (simp add: max.commute max.order_iff)\n    have b:\"min (right r) x = x\" using 3 \n      by (simp add: min.commute min.order_iff)\n    show ?thesis using 3 a b \n      using \\<open>\\<parallel>s\\<parallel> = 0\\<close> \\<open>s = mk_empty x\\<close> empty_left empty_stretch intersect_def length_def stretch_def by auto\n  qed\nqed\n\nlemma rchop_intersect_leq_left : \"intersect r s = r \\<and> t \\<le> r \\<longrightarrow> left (intersect t s) = left t\" \nproof\n  assume a:\"intersect r s = r \\<and> t \\<le> r\"\n  consider (1) \"(left s > right r)\" | (2) \"(right s < left r)\" | (3) \"(left s \\<le> right r) \\<and> (right s\\<ge> left r)\"    \n    using not_less by blast\n  then show \"left (intersect t s) = left t\"\n  proof (cases)\n    case 1\n    have \"intersect r s = mk_empty (right r)\" using 1 intersect_def \n      by simp\n    then have \"left r = right r\" \n      by (metis a empty_left)\n    then show ?thesis\n      by (metis a chop_leq1 chop_singleton_left' dual_order.order_iff_strict less_real_int_def order_trans rchop_def)   \n  next\n    case 2\n    then have \"left s \\<le> right r \" using left_leq_right \n      by (meson left_leq_right less_eq_real_def order_trans)\n    then have \"intersect r s = mk_empty (left r)\" using 2 intersect_def \n      by simp\n    then show ?thesis \n      by (metis  a chop_leq1 chop_singleton_left dual_order.antisym empty_right less_eq_real_int_def order_trans rchop_def) \n  next \n    case 3\n    then have 4:\"(left s \\<le> right t) \\<and> (right s\\<ge> left t)\" \n      by (metis a intersect_left' intersect_right' left_leq_right less_eq_real_int_def order_trans)\n    have \"max (left t) (left s) = left t\" \n      using \"3\" a intersect_left' less_eq_real_int_def by fastforce \n    then show ?thesis using 4 intersect_right' \n      by (metis a add_0_right less_eq_real_int_def local.intersect_def min_def not_le order_trans real_int_class.shift_def shift_zero)\n  qed\nqed\n\nlemma rchop_intersect_leq_right : \"intersect r s = r \\<and> t \\<le> r \\<longrightarrow> right (intersect t s) = right t\" \nproof\n  assume a:\"intersect r s = r \\<and> t \\<le> r\"\n  consider (1) \"(left s > right r)\" | (2) \"(right s < left r)\" | (3) \"(left s \\<le> right r) \\<and> (right s\\<ge> left r)\"    \n    using not_less by blast\n  then show \"right (intersect t s) = right t\"\n  proof (cases)\n    case 1\n    have \"intersect r s = mk_empty (right r)\" using 1 intersect_def \n      by simp\n    then have \"left r = right r\" \n      by (metis a empty_left)\n    then show ?thesis\n      by (metis a chop_leq1 chop_singleton_left' dual_order.order_iff_strict less_real_int_def order_trans rchop_def)   \n  next\n    case 2\n    then have \"left s \\<le> right r \" using left_leq_right \n      by (meson left_leq_right less_eq_real_def order_trans)\n    then have \"intersect r s = mk_empty (left r)\" using 2 intersect_def \n      by simp\n    then show ?thesis \n      by (metis  a chop_leq1 chop_singleton_left dual_order.antisym empty_right less_eq_real_int_def order_trans rchop_def) \n  next \n    case 3\n    then have 4:\"(left s \\<le> right t) \\<and> (right s\\<ge> left t)\" \n      by (metis a intersect_left' intersect_right' left_leq_right less_eq_real_int_def order_trans)\n    have \"max (left t) (left s) = left t\" \n      using \"3\" a intersect_left' less_eq_real_int_def by fastforce \n    then show ?thesis using 4 intersect_right' \n      by (metis a add_0_right less_eq_real_int_def local.intersect_def min_def not_le order_trans real_int_class.shift_def shift_zero)\n  qed\nqed\n\nlemma rchop_intersect_left:\" (intersect r s) = r \\<and> R_Chop(r, r1, r2) \\<longrightarrow> intersect r1 s = r1\"   \n  using chop_leq1 left_right_eq rchop_intersect_leq_left rchop_intersect_leq_right by blast\n\nlemma rchop_intersect_right:\" (intersect r s) = r \\<and> R_Chop(r, r1, r2) \\<longrightarrow> intersect r2 s = r2\"   \n  using chop_leq2 left_right_eq rchop_intersect_leq_left rchop_intersect_leq_right by blast\n\nlemma rchop_intersect_compose:\n  \"R_Chop(r,r1,r2) \\<and> ( intersect r1 s = r1) \\<and> (intersect r2 s = r2)\n     \\<longrightarrow> (intersect r s = r)\" \nproof\n  assume a:\"R_Chop(r,r1,r2) \\<and> ( intersect r1 s = r1) \\<and> (intersect r2 s = r2)\"\n  consider (1) \"\\<parallel>r1\\<parallel> = 0 \\<and> \\<parallel>r2\\<parallel> = 0 \" | (2) \"\\<parallel>r1\\<parallel> \\<noteq> 0 \\<and> \\<parallel>r2\\<parallel> = 0\"  | (3) \"\\<parallel>r1\\<parallel> = 0 \\<and> \\<parallel>r2\\<parallel> \\<noteq> 0 \" | (4) \"\\<parallel>r1\\<parallel> \\<noteq> 0 \\<and> \\<parallel>r2\\<parallel> \\<noteq> 0 \"  \n    by blast\n  then show \"(intersect r s = r)\" \n  proof (cases)\n    case 1\n    then show ?thesis \n      using a chop_empty1 by blast\n  next\n    case 2\n    then show ?thesis \n      using a chop_empty2 by blast\n  next\n    case 3\n    then show ?thesis \n      using a chop_empty1 by blast\n  next\n    case 4\n    have \"right (intersect r2 s ) \\<le> right s\" \n      by (metis \"4\" a empty_length intersect_right' leI local.intersect_def)\n    then have 5:\"left (r) \\<le> right s\" \n      by (metis a left_leq_right order_trans rchop_def)\n    have \"left (intersect r1 s) \\<ge> left s\" \n      by (metis \"4\" a empty_length intersect_left' leI local.intersect_def)\n    then have 6: \"left (s) \\<le> right r\" \n      by (metis a left_leq_right order_trans rchop_def)\n    have 7:\"max (left s) (left r) = left r\" \n      using \\<open>left s \\<le> left (intersect r1 s)\\<close> a rchop_def by auto\n    have 8:\"min (right s) (right r) = right r\" \n      using \\<open>right (intersect r2 s) \\<le> right s\\<close> a rchop_def by auto\n    have 9:\"left (intersect r s) = left r\" \n      by (metis \"8\" \\<open>left s \\<le> left (intersect r1 s)\\<close> a add.right_neutral intersect_def left_leq_right less_eq_real_int_def linear max.idem min_def not_le rchop_def rchop_intersect_leq_left real_int_class.shift_def shift_zero)\n    have 10:\"right (intersect r s) = right r\" \n      by (metis \\<open>left s \\<le> left (intersect r1 s)\\<close> \\<open>right (intersect r2 s) \\<le> right s\\<close> a add.right_neutral intersect_def left_leq_right less_eq_real_int_def max.idem min.idem not_le rchop_def rchop_intersect_leq_right real_int_class.shift_def shift_zero)\n    then show ?thesis using 9 10 \n      by (simp add: left_right_eq)\n  qed\nqed    \n\nlemma leq_intersect_leq: \"t \\<le> r \\<longrightarrow> \\<parallel>intersect t s\\<parallel> = 0 \\<or>  intersect t s \\<le> intersect r s\" \nproof\n  assume a:\"t \\<le> r\" \n  consider  (1) \"(left s > right r)\" | (2) \"(right s < left r)\" | (3) \"(left s \\<le> right r) \\<and> (right s\\<ge> left r)\" \n    using not_le by blast\n  then show \" \\<parallel>intersect t s\\<parallel> = 0 \\<or>  intersect t s \\<le> intersect r s\" \n  proof (cases)\n    case 1\n    then show ?thesis \n      using a empty_length less_eq_real_int_def local.intersect_def by auto  \n  next\n    case 2\n    then show ?thesis \n      using a empty_length less_eq_real_int_def local.intersect_def by auto  \n  next\n    case 3\n    consider (4) \"(left s > right t \\<or> right s < left t)\" | (5) \"(left s \\<le> right t) \\<and> (right s\\<ge> left t)\" using not_le by blast\n    then show ?thesis \n    proof (cases)\n      case 4\n      then show ?thesis \n        using empty_length local.intersect_def by auto\n    next\n      case 5\n      then show ?thesis using less_eq_real_int_def \n        using Abs_real_int_inverse a left_leq_right local.intersect_def by auto\n    qed\n  qed\nqed  \n\nlemma leq_intersect_length: \"t \\<le> r \\<longrightarrow> \\<parallel>intersect t s\\<parallel> \\<le> \\<parallel>intersect r s\\<parallel>\" \n  by (metis length_ge_zero length_leq leq_intersect_leq)\n\nlemma rchop_intersect_empty_left: \"\\<parallel>intersect r s\\<parallel> = 0 \\<and> R_Chop(r,r1,r2) \\<longrightarrow> \\<parallel>intersect r1 s\\<parallel> = 0\" \n  by (metis chop_leq1 length_ge_zero leq_intersect_length order_class.order.antisym)\n\nlemma rchop_intersect_empty_right: \"\\<parallel>intersect r s\\<parallel> = 0 \\<and> R_Chop(r,r1,r2) \\<longrightarrow> \\<parallel>intersect r2 s\\<parallel> = 0\" \n  by (metis chop_leq2 dual_order.antisym length_ge_zero leq_intersect_length)\n\nlemma rchop_intersect_add: \"R_Chop(r,r1,r2) \\<longrightarrow> \\<parallel>intersect r s\\<parallel> = \\<parallel>intersect r1 s\\<parallel>  + \\<parallel>intersect r2 s\\<parallel>\" \nproof\n  assume a:\"R_Chop(r,r1,r2)\" \n  consider (1) \"(left s > right r \\<or> right s < left r)\" | (2) \"(left s \\<le> right r) \\<and> (right s\\<ge> left r)\" using not_le by blast\n  then show \"\\<parallel>intersect r s\\<parallel> = \\<parallel>intersect r1 s\\<parallel>  + \\<parallel>intersect r2 s\\<parallel>\"\n  proof (cases)\n    case 1\n    then have \"\\<parallel>intersect r s\\<parallel> = 0\" \n      using empty_length local.intersect_def by auto\n    then show ?thesis \n      by (metis a add.right_neutral rchop_intersect_empty_left rchop_intersect_empty_right)\n  next\n    case 2\n    consider (z) \"\\<parallel>r\\<parallel> = 0 \\<or> \\<parallel>s\\<parallel> = 0 \" | (nz) \"\\<parallel>r\\<parallel> \\<noteq> 0 \\<and> \\<parallel>s\\<parallel> \\<noteq> 0\" by blast\n    then show ?thesis \n    proof (cases)\n      case z\n      then show ?thesis \n      proof \n        assume \"\\<parallel>r\\<parallel> = 0\"\n        then have \"\\<parallel>intersect r s\\<parallel> = 0 \" using length_leq \n          by (metis chop_leq1 dual_order.antisym empty_left empty_length empty_right intersect_leq rchop_def)\n        then show ?thesis \n          by (metis a add.left_neutral  rchop_intersect_empty_left rchop_intersect_empty_right)\n      next\n        assume \"\\<parallel>s\\<parallel> = 0\" \n        then show ?thesis \n          by (simp add: intersect_with_zero)\n      qed\n    next\n      case nz\n      then have \"(left s < right r) \\<or> (right s > left r)\" \n        by (metis \"2\" dual_order.order_iff_strict left_leq_right length_zero_iff_borders_eq not_le)\n      have 3:\"left (intersect r s) = max (left r) (left s) \" \n        using \"2\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n      have 4:\"right (intersect r s) = min (right r) (right s)\" \n        using \"2\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n      show ?thesis\n      proof (cases \"left s \\<le> right r1\")\n        case False\n        then have empty:\"\\<parallel>intersect r1 s\\<parallel> = 0\" \n          by (simp add: empty_length local.intersect_def)\n        have 5:\"left s \\<le> right r2 \\<and> right s \\<ge> left r2\" \n          by (metis \"2\" False a dual_order.order_iff_strict leI left_leq_right less_trans rchop_def)\n        have 6:\"left (intersect r2 s) = max (left r2) (left s) \" \n           using \"5\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n        have 7:\"right (intersect r2 s) = min (right r2) (right s) \" \n           using \"5\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n        have 8:\"left (intersect r2 s) = left (intersect r s)\" \n          by (metis \"3\" \"6\" False a left_leq_right max.order_iff max_def max_less_iff_conj not_le rchop_def)\n        have 9:\"right (intersect r2 s) = right (intersect r s)\" \n          using \"4\" \"7\" a rchop_def by auto\n        show ?thesis using 8 9 empty \n          by (simp add: length_def)\n      next  \n        case True\n        have 5:\"left s \\<le> right r1 \\<and> right s \\<ge> left r1\" \n          by (metis \"2\" True a rchop_def)\n        then have 6:\"left (intersect r1 s) = max (left r1) (left s) \" \n          using Abs_real_int_inverse Rep_real_int local.intersect_def by auto        \n        then have 7:\"left (intersect r1 s) = left (intersect r s)\"  \n          using \"3\" a rchop_def by auto\n        have 8:\"right (intersect r1 s) = min (right r1) (right s) \" \n           using \"5\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n        show ?thesis \n        proof (cases \"right s \\<ge> left r2\")\n          case False\n          then have \"\\<parallel>intersect r2 s\\<parallel> = 0\" \n            by (simp add: empty_length intersect_def)\n          then have \"right (intersect r1 s) = right (intersect r s)\" \n            by (metis \"4\" \"8\" False a chop_leq1 dual_order.order_iff_strict less_real_int_def min_def order_trans rchop_def) \n          then show ?thesis \n            using \"7\" \\<open>\\<parallel>intersect r2 s\\<parallel> = 0\\<close> length_def by auto\n        next\n          case True\n          have 9:\"left s \\<le> right r2 \\<and> right s \\<ge> left r2\" \n            using \"2\" True a rchop_def by auto \n          then have 10:\"right (intersect r1 s) = right r1\" \n            using \"8\" a rchop_def by auto\n          have 11:\"left (intersect r2 s) = max (left r2) (left s) \" \n           using \"9\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n          have 12:\"right (intersect r2 s) = min (right r2) (right s) \" \n            using \"9\" Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n          then show ?thesis \n            using \"10\" \"11\" \"4\" \"5\" \"7\" a length_def rchop_def by auto\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma intersect_length_not_empty:\"\\<parallel>intersect r s\\<parallel> > 0 \\<longrightarrow> (left s < right r) \\<and> (right s > left r)\" \nproof\n  assume a:\"\\<parallel>intersect r s\\<parallel> > 0\"\n  then have 1:\"left s \\<le> right r \\<and> right s \\<ge> left r\" \n    by (metis empty_length leI less_irrefl local.intersect_def)\n  have 2:\"left s < right r\" \n    by (metis \"1\" a diff_gt_0_iff_gt intersect_left' intersect_right le_less_trans length_def not_le)\n  have 3: \"right s > left r\"\n    by (metis \"1\" a diff_gt_0_iff_gt intersect_right' intersect_left le_less_trans length_def not_le)\n  show \"(left s < right r) \\<and> (right s > left r)\" using 2 3 by blast\nqed\n\nlemma intersect_fills_leq:\n  assumes a:\"\\<parallel>intersect r s\\<parallel> > 0\"\n  obtains t where \" t \\<le> r \\<and> intersect t s = t \\<and> \\<parallel>intersect r s\\<parallel> = \\<parallel>intersect t s\\<parallel>\" \nproof -\n  obtain y where y:\"y =  \\<parallel>intersect r s\\<parallel>\" by blast\n  obtain x where x:\"intersect r s = stretch x y\" \n    by (metis Groups.add_ac(2) Rep_real_int_inverse \\<open>y = \\<parallel>intersect r s\\<parallel>\\<close> diff_add_cancel left.rep_eq length_def prod.collapse real_int.stretch_def right.rep_eq)\n  let ?t = \"stretch x y\" \n  have 1:\"?t \\<le> r\" using x\n    by (metis intersect_leq)\n  have h1:\"(left s < right r) \\<and> (right s > left r)\" using intersect_length_not_empty a by blast\n  then have h2:\"(left s < right ?t) \\<and> (right s > left ?t)\" using 1 \n    by (metis assms diff_gt_0_iff_gt  dual_order.strict_trans1 dual_order.strict_trans2 intersect_left' intersect_right' le_less_trans length_def less_eq_real_def linear not_le x)\n  have lr:\"left (intersect r s) = max (left r) (left s)\" using h1 \n    using Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n  have rr:\"right (intersect r s) = min (right r) (right s)\"  \n    using h1 Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n  have lt:\"left (intersect ?t s) = max (left ?t) (left s)\"  \n    using h2 Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n  have rt:\"right (intersect ?t s) = min (right ?t) (right s)\"  \n    using h2 Abs_real_int_inverse Rep_real_int local.intersect_def by auto\n  have 2:\"intersect (stretch x y) s =  stretch x y\" using lt rt \n    using left_right_eq lr rr x by auto\n  show ?thesis using 1 2 x \n    using that by fastforce \nqed\n\nlemma intersect_fills_chop:\" \\<parallel>intersect r s\\<parallel> > 0 \\<longrightarrow> ( \\<exists>r1 r2 r3 t. R_Chop(r,r1,r2) \\<and> R_Chop(r2,t,r3)  \\<and> intersect t s = t \\<and> \\<parallel>intersect r s\\<parallel> = \\<parallel>intersect t s\\<parallel>)\"\nproof\n  assume a:\"\\<parallel>intersect r s\\<parallel> > 0\"\n  then obtain t where t:\"t \\<le> r \\<and> intersect t s = t \\<and> \\<parallel>intersect r s\\<parallel> = \\<parallel>intersect t s\\<parallel>\" using intersect_fills_leq by blast\n  obtain r1 where r1:\"left r1 = left r \\<and> right r1 = left t\" \n    by (metis add.commute diff_add_cancel diff_ge_0_iff_ge less_eq_real_int_def stretch_left stretch_right t) \n  obtain r2 where r2:\"left r2 = right r1 \\<and> right r2 = right r\" using Abs_real_int_inverse \n    by (metis diff_add_cancel diff_ge_0_iff_ge left_leq_right less_eq_real_int_def linordered_field_class.sign_simps(27) min.bounded_iff min_def  r1 stretch_left stretch_right t)\n  obtain r3 where r3:\"left r3 = right t \\<and> right r3 = right r\" \n    by (metis add_minus_cancel add_uminus_conv_diff diff_ge_0_iff_ge less_eq_real_int_def linordered_field_class.sign_simps(27) stretch_left stretch_right t)  \n  then have \"R_Chop(r,r1,r2) \\<and> R_Chop(r2,t,r3)\" using r1 r2 r3 \n    by (simp add: rchop_def)\n  then show  \"\\<exists>r1 r2 r3 t. R_Chop(r,r1,r2) \\<and> R_Chop(r2,t,r3)  \\<and> intersect t s = t \\<and> \\<parallel>intersect r s\\<parallel> = \\<parallel>intersect t s\\<parallel>\" \n    using t by blast\nqed\nend\n(*lemmas[simp] = length_dict *)\n  \nend\n", "meta": {"author": "svenlinker", "repo": "HMLSL", "sha": "ef3a68683db42f2eebd5f0f45cbebdf73da78571", "save_path": "github-repos/isabelle/svenlinker-HMLSL", "path": "github-repos/isabelle/svenlinker-HMLSL/HMLSL-ef3a68683db42f2eebd5f0f45cbebdf73da78571/RealInt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7925584387215384}}
{"text": "theory four_logic\n  imports base \"HOL-Eisbach.Eisbach\"\nbegin\n\nsection \\<open>bilattice-based 4-valued-logic (FOUR)\\<close>\n\ntype_synonym \\<tau> = \"(bool)Pair\" (* type for 4-valued truth values*)\n\n(*The 4 possible values of type \\<tau> *)\ndefinition Tval (\"\\<^bold>T\") where \"\\<^bold>T \\<equiv> \\<langle>False,True\\<rangle>\"\ndefinition Fval (\"\\<^bold>F\") where \"\\<^bold>F \\<equiv> \\<langle>True,False\\<rangle>\"\ndefinition Bval (\"\\<^bold>B\") where \"\\<^bold>B \\<equiv> \\<langle>True,True\\<rangle>\"\ndefinition Nval (\"\\<^bold>N\") where \"\\<^bold>N \\<equiv> \\<langle>False,False\\<rangle>\"\n\nnamed_theorems val4\ndeclare Tval_def[val4] Fval_def[val4] Bval_def[val4] Nval_def[val4]\n\n(*Observe that pairs of booleans have an alternative, simpler representation *)\nlemma mkPair_booldef: \"\\<langle>a,b\\<rangle> = (\\<lambda>X. (a \\<and> \\<not>X) \\<or> (b \\<and> X))\" by (metis mkPair_def)\n\nlemma Tval_def2: \"\\<^bold>T = (\\<lambda>x. x)\" by (simp add: Tval_def mkPair_booldef)\nlemma Fval_def2: \"\\<^bold>F = (\\<lambda>x. \\<not>x)\" by (simp add: Fval_def mkPair_booldef)\nlemma Bval_def2: \"\\<^bold>B = (\\<lambda>x. True)\" by (simp add: Bval_def mkPair_booldef)\nlemma Nval_def2: \"\\<^bold>N = (\\<lambda>x. False)\" by (simp add: Nval_def mkPair_booldef)\n\n(*The set FOUR := {\\<^bold>T,\\<^bold>F,\\<^bold>B,\\<^bold>N} is a bilattice. It has two sets of lattice operations.*)\nnamed_theorems conn4\n\n(*The first set of operations form a so-called 'approximation lattice' A4 *)\ndefinition meetA4::\"\\<tau> \\<Rightarrow> \\<tau> \\<Rightarrow> \\<tau>\" (infixr \"\\<sqinter>\\<^sup>4\" 80)\n  where \"a \\<sqinter>\\<^sup>4 b \\<equiv> \\<langle>fst a \\<and> fst b, snd a \\<and> snd b\\<rangle>\"\ndefinition joinA4::\"\\<tau> \\<Rightarrow> \\<tau> \\<Rightarrow> \\<tau>\" (infixr \"\\<squnion>\\<^sup>4\" 80)\n  where \"a \\<squnion>\\<^sup>4 b \\<equiv> \\<langle>fst a \\<or> fst b, snd a \\<or> snd b\\<rangle>\"\ndefinition cmplA4::\"\\<tau> \\<Rightarrow> \\<tau>\" (\"\\<midarrow>\\<^sup>4_\" 90)\n  where \"\\<midarrow>\\<^sup>4a \\<equiv> \\<langle>\\<not>(fst a), \\<not>(snd a)\\<rangle>\"\n\ndefinition orderA4::\"\\<tau> Rel\" (infixr \"\\<sqsubseteq>\\<^sup>4\" 80)\n  where \"a \\<sqsubseteq>\\<^sup>4 b \\<equiv> (fst a \\<longrightarrow> fst b) \\<and> (snd a \\<longrightarrow> snd b)\"\n\ndeclare meetA4_def[conn4] joinA4_def[conn4] cmplA4_def[conn4] orderA4_def[conn4]\n\n(*We introduce two custom solvers:\n (s1) is fast and works well for goals involving meets & joins with complement\n (s2) is slower and works well for (most of) the rest *)\nmethod s1 = unfold conn4; auto simp add: mkPair_def fst_def snd_def val4\nmethod s2 = unfold conn4; (smt (verit, del_insts) fst_prop snd_prop mkPair_prop val4)\n\nlemma orderA4_def2:  \"(a \\<sqsubseteq>\\<^sup>4 b) = (a = a \\<sqinter>\\<^sup>4 b)\" by s2\nlemma orderA4_def3:  \"(a \\<sqsubseteq>\\<^sup>4 b) = (b = a \\<squnion>\\<^sup>4 b)\" by s2\n\n(*We verify the intended 'Hasse diagram' for A4*)\nlemma \"\\<^bold>T \\<sqinter>\\<^sup>4 \\<^bold>F = \\<^bold>N\" by s1\nlemma \"\\<^bold>B \\<sqinter>\\<^sup>4 \\<^bold>N = \\<^bold>N\" by s1\nlemma \"\\<^bold>B \\<sqinter>\\<^sup>4 \\<^bold>T = \\<^bold>T\" by s1\nlemma \"\\<^bold>B \\<sqinter>\\<^sup>4 \\<^bold>F = \\<^bold>F\" by s1\nlemma \"\\<^bold>T \\<sqinter>\\<^sup>4 \\<^bold>N = \\<^bold>N\" by s1\nlemma \"\\<^bold>F \\<sqinter>\\<^sup>4 \\<^bold>N = \\<^bold>N\" by s1\n\nlemma \"\\<^bold>B \\<squnion>\\<^sup>4 \\<^bold>N = \\<^bold>B\" by s1\nlemma \"\\<^bold>B \\<squnion>\\<^sup>4 \\<^bold>T = \\<^bold>B\" by s1\nlemma \"\\<^bold>B \\<squnion>\\<^sup>4 \\<^bold>F = \\<^bold>B\" by s1\nlemma \"\\<^bold>T \\<squnion>\\<^sup>4 \\<^bold>F = \\<^bold>B\" by s1\nlemma \"\\<^bold>T \\<squnion>\\<^sup>4 \\<^bold>N = \\<^bold>T\" by s1\nlemma \"\\<^bold>F \\<squnion>\\<^sup>4 \\<^bold>N = \\<^bold>F\" by s1\n\nlemma \"\\<midarrow>\\<^sup>4\\<^bold>T = \\<^bold>F\" by s1\nlemma \"\\<midarrow>\\<^sup>4\\<^bold>B = \\<^bold>N\" by s1\n\n(*Distributivity*)\nlemma A4_distr1: \"(a \\<sqinter>\\<^sup>4 (b \\<squnion>\\<^sup>4 c)) = ((a \\<sqinter>\\<^sup>4 b) \\<squnion>\\<^sup>4 (a \\<sqinter>\\<^sup>4 c))\" by s1\nlemma A4_distr2: \"(a \\<squnion>\\<^sup>4 (b \\<sqinter>\\<^sup>4 c)) = ((a \\<squnion>\\<^sup>4 b) \\<sqinter>\\<^sup>4 (a \\<squnion>\\<^sup>4 c))\" by s1\n\n(*Negation properties: involutivity, de Morgan law, contraposition*)\nlemma cmplA4_invol: \"\\<midarrow>\\<^sup>4\\<midarrow>\\<^sup>4a = a\" by s2\nlemma cmplA4_DM1: \"\\<midarrow>\\<^sup>4(a \\<squnion>\\<^sup>4 b) = ((\\<midarrow>\\<^sup>4a) \\<sqinter>\\<^sup>4 (\\<midarrow>\\<^sup>4b))\" by s1\nlemma cmplA4_DM2: \"\\<midarrow>\\<^sup>4(a \\<sqinter>\\<^sup>4 b) = ((\\<midarrow>\\<^sup>4a) \\<squnion>\\<^sup>4 (\\<midarrow>\\<^sup>4b))\" by s1\nlemma cmplA4_cp1: \"a \\<sqsubseteq>\\<^sup>4 b \\<longleftrightarrow> \\<midarrow>\\<^sup>4b \\<sqsubseteq>\\<^sup>4 \\<midarrow>\\<^sup>4a\" by s2\nlemma cmplA4_cp2: \"a \\<sqsubseteq>\\<^sup>4 \\<midarrow>\\<^sup>4b \\<longleftrightarrow> b \\<sqsubseteq>\\<^sup>4 \\<midarrow>\\<^sup>4a\" by s1\n\n(*The second set of operations form a so-called 'logical lattice' L4 *)\ndefinition meetL4::\"\\<tau> \\<Rightarrow> \\<tau> \\<Rightarrow> \\<tau>\" (infixr \"\\<and>\\<^sup>4\" 80)\n  where \"A \\<and>\\<^sup>4 B \\<equiv> \\<langle>fst A \\<or> fst B, snd A \\<and> snd B\\<rangle>\"\ndefinition joinL4::\"\\<tau> \\<Rightarrow> \\<tau> \\<Rightarrow> \\<tau>\" (infixr \"\\<or>\\<^sup>4\" 80)\n  where \"A \\<or>\\<^sup>4 B \\<equiv> \\<langle>fst A \\<and> fst B, snd A \\<or> snd B\\<rangle>\"\ndefinition cmplL4::\"\\<tau> \\<Rightarrow> \\<tau>\" (\"\\<sim>\\<^sup>4_\" 90)\n  where \"\\<sim>\\<^sup>4A \\<equiv> A\\<Zcat>\"\n\ndefinition orderL4::\"\\<tau> Rel\" (infixr \"\\<preceq>\\<^sup>4\" 80)\n  where \"A \\<preceq>\\<^sup>4 B \\<equiv> (fst B \\<longrightarrow> fst A) \\<and> (snd A \\<longrightarrow> snd B)\"\n\ndeclare meetL4_def[conn4] joinL4_def[conn4] cmplL4_def[conn4] orderL4_def[conn4]\n\nlemma orderL4_def2:  \"(A \\<preceq>\\<^sup>4 B) = (A = A \\<and>\\<^sup>4 B)\" by s2\nlemma orderL4_def3:  \"(A \\<preceq>\\<^sup>4 B) = (B = A \\<or>\\<^sup>4 B)\" by s2\n\n(*We verify the intended 'Hasse diagram' for L4*)\nlemma \"(\\<^bold>T \\<and>\\<^sup>4 \\<^bold>F) = \\<^bold>F\" by s1\nlemma \"(\\<^bold>N \\<and>\\<^sup>4 \\<^bold>B) = \\<^bold>F\" by s1\nlemma \"(\\<^bold>T \\<and>\\<^sup>4 \\<^bold>N) = \\<^bold>N\" by s1\nlemma \"(\\<^bold>T \\<and>\\<^sup>4 \\<^bold>B) = \\<^bold>B\" by s1\nlemma \"(\\<^bold>N \\<and>\\<^sup>4 \\<^bold>F) = \\<^bold>F\" by s1\nlemma \"(\\<^bold>B \\<and>\\<^sup>4 \\<^bold>F) = \\<^bold>F\" by s1\n\nlemma \"(\\<^bold>T \\<or>\\<^sup>4 \\<^bold>F) = \\<^bold>T\" by s1\nlemma \"(\\<^bold>T \\<or>\\<^sup>4 \\<^bold>N) = \\<^bold>T\" by s1\nlemma \"(\\<^bold>T \\<or>\\<^sup>4 \\<^bold>B) = \\<^bold>T\" by s1\nlemma \"(\\<^bold>N \\<or>\\<^sup>4 \\<^bold>B) = \\<^bold>T\" by s1\nlemma \"(\\<^bold>N \\<or>\\<^sup>4 \\<^bold>F) = \\<^bold>N\" by s1\nlemma \"(\\<^bold>B \\<or>\\<^sup>4 \\<^bold>F) = \\<^bold>B\" by s1\n\nlemma \"\\<sim>\\<^sup>4\\<^bold>F = \\<^bold>T\" by s1\nlemma \"\\<sim>\\<^sup>4\\<^bold>N = \\<^bold>N\" by s1\nlemma \"\\<sim>\\<^sup>4\\<^bold>B = \\<^bold>B\" by s1\n\n(*Distributivity*)\nlemma L4_distr1: \"(a \\<and>\\<^sup>4 (b \\<or>\\<^sup>4 c)) = ((a \\<and>\\<^sup>4 b) \\<or>\\<^sup>4 (a \\<and>\\<^sup>4 c))\" by s1\nlemma L4_distr2: \"(a \\<or>\\<^sup>4 (b \\<and>\\<^sup>4 c)) = ((a \\<or>\\<^sup>4 b) \\<and>\\<^sup>4 (a \\<or>\\<^sup>4 c))\" by s1\n\n(*Negation properties: involutivity, de Morgan law, contraposition*)\nlemma cmplL4_invol: \"\\<sim>\\<^sup>4\\<sim>\\<^sup>4a = a\" by s2\nlemma cmplL4_DM1: \"\\<sim>\\<^sup>4(a \\<or>\\<^sup>4 b) = ((\\<sim>\\<^sup>4a) \\<and>\\<^sup>4 (\\<sim>\\<^sup>4b))\" by s1\nlemma cmplL4_DM2: \"\\<sim>\\<^sup>4(a \\<and>\\<^sup>4 b) = ((\\<sim>\\<^sup>4a) \\<or>\\<^sup>4 (\\<sim>\\<^sup>4b))\" by s1\nlemma cmplL4_cp1: \"a \\<preceq>\\<^sup>4 b \\<longleftrightarrow> \\<sim>\\<^sup>4b \\<preceq>\\<^sup>4 \\<sim>\\<^sup>4a\" by s1\nlemma cmplL4_cp2: \"a \\<preceq>\\<^sup>4 \\<sim>\\<^sup>4b \\<longleftrightarrow> b \\<preceq>\\<^sup>4 \\<sim>\\<^sup>4a\" by s1\n\nend", "meta": {"author": "davfuenmayor", "repo": "structured-argumentation", "sha": "master", "save_path": "github-repos/isabelle/davfuenmayor-structured-argumentation", "path": "github-repos/isabelle/davfuenmayor-structured-argumentation/structured-argumentation-master/isabelle/four_logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8872045952083047, "lm_q1q2_score": 0.7925482049542034}}
{"text": "theory Ch4\nimports Main \"~~/src/Doc/Prog_Prove/Logic\" \"~~/src/HOL/IMP/AExp\"\nbegin\n\n(* 4.1 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n  \"set Tip = {}\" |\n  \"set (Node l x r) = {x} \\<union> set l \\<union> set r\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\" |\n  \"ord (Node l x r) = ((\\<forall> y \\<in> set l. y < x) \\<and> (\\<forall> y \\<in> set r. x < y) \\<and> ord l \\<and> ord r)\"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n  \"ins x Tip = Node Tip x Tip\" |\n  \"ins x (Node l x' r) = (\n    if x < x' then (Node (ins x l) x' r)\n    else (\n      if x > x' then (Node l x' (ins x r))\n      else (Node l x' r)\n    )\n  )\"\n\ntheorem ins_set_correct [simp]: \"set (ins x t) = {x} \\<union> set t\"\n  apply(induction t)\n  apply(auto)\ndone\n\ntheorem ins_ord_correct: \"ord t \\<Longrightarrow> ord (ins i t)\"\n  apply(induction t arbitrary: i)\n  apply(auto)\ndone\n\n(* 4.2 *)\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n  palin_empty: \"palindrome []\" |\n  palin_step: \"palindrome xs \\<Longrightarrow> palindrome (x # xs @ [x])\"\n\ntheorem palin_rev: \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction xs rule: palindrome.induct)\n  apply(auto)\ndone\n\n(* 4.3 *)\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl': \"star' r x x\" |\n  step': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma r_star: \"r x y \\<Longrightarrow> star r x y\"\n  by(blast intro: Logic.star.step Logic.star.refl)\n\ntheorem star'_star: \"star' r x y \\<Longrightarrow> star r x y\"\n  apply(induction rule: star'.induct)\n  apply(rule Logic.star.refl)\n  apply(rule Logic.star_trans)\n  apply(assumption)\n  apply(rule r_star)\n  apply(assumption)\ndone\n\nlemma r_star' [simp]: \"r x y \\<Longrightarrow> star' r x y\"\n  by(blast intro: refl' step')\n\nlemma step'_r_star': \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply(induction rule: star'.induct)\n  apply(simp_all add: step')\ndone\n\nlemma star'_trans: \"star' r x y \\<Longrightarrow> star' r y z \\<Longrightarrow> star' r x z\"\n  apply(induction rule: star'.induct)\n  apply(simp)\n  apply(metis step'_r_star')\ndone\n\ntheorem star_star': \"star r x y \\<Longrightarrow> star' r x y\"\n  apply(induction rule: star.induct)\n  apply(simp_all add: refl')\n  apply(metis step'_r_star')\ndone\n\n(* 4.4 *)\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  iter0: \"iter r 0 x x\" |\n  iterS: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (S n) x z\"\n\ntheorem star_iter: \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\n  apply(induction rule: star.induct)\n  apply(metis iter0)\n  apply(metis iterS)\ndone\n\n(* 4.5 *)\ndatatype alpha = A | B\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\n  S_empty: \"S []\" |\n  S_surround: \"S w \\<Longrightarrow> S (A # w @ [B])\" |\n  S_double: \"S w1 \\<Longrightarrow> S w2 \\<Longrightarrow> S (w1 @ w2)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\n  T_empty: \"T []\" |\n  T_step: \"T w1 \\<Longrightarrow> T w2 \\<Longrightarrow> T (w1 @ [A] @ w2 @ [B])\"\n\ndeclare S.intros[simp,intro]\n\ndeclare T.intros[simp,intro]\n\ntheorem T_S: \"T w \\<Longrightarrow> S w\"\n  by(simp add: T.induct)\n\nlemma T_app [simp]: \"\\<lbrakk> T w2 ; T w1 \\<rbrakk> \\<Longrightarrow> T (w1 @ w2)\"\n  apply(induction rule: T.induct)\n  apply(simp)\n  apply(metis T_step append_assoc)\ndone\n\ntheorem S_T: \"S w \\<Longrightarrow> T w\"\n  by (metis S.induct T.simps T_app append_Cons append_Nil)\n\ntheorem S_T_equiv: \"S w = T w\"\n  by(metis T_S S_T)\n\n(* 4.6 *)\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n  aval_rel_N: \"aval_rel (N n) _ n\" |\n  aval_rel_V: \"aval_rel (V v) s (s v)\" |\n  aval_rel_Plus: \"aval_rel e1 s x \\<Longrightarrow> aval_rel e2 s y \\<Longrightarrow> aval_rel (Plus e1 e2) s (x + y)\"\n\ntheorem aval_ind_rec: \"aval_rel e s v \\<Longrightarrow> aval e s = v\"\n  apply(induction rule: aval_rel.induct)\n  apply(simp_all)\ndone\n\ntheorem aval_rec_ind: \"aval e s = v \\<Longrightarrow> aval_rel e s v\"\n  apply(induction e arbitrary: v)\n  apply(auto simp add: aval_rel.intros)\ndone\n\ntheorem aval_rel_aval_equiv: \"aval_rel e s v \\<longleftrightarrow> aval e s = v\"\n  by(metis aval_ind_rec aval_rec_ind)\n\n(* 4.7 *)\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk  =  n # stk\" |\n\"exec1 (LOAD x) s stk  =  s(x) # stk\" |\n\"exec1  ADD _ (j # i # stk)  =  (i + j) # stk\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i#is) s stk = exec is s (exec1 i s stk)\"\n\nlemma exec_append[simp]:\n  \"exec (is1@is2) s stk = exec is2 s (exec is1 s stk)\"\napply(induction is1 arbitrary: stk)\napply (auto split: option.split)\ndone\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [] @ [LOADI n]\" |\n\"comp (V x) = [] @ [LOAD x]\" |\n\"comp (Plus e\\<^sub>1 e\\<^sub>2) = comp e\\<^sub>1 @ comp e\\<^sub>2 @ [ADD]\"\n\ntheorem exec_comp: \"exec (comp a) s stk = aval a s # stk\"\napply(induction a arbitrary: stk)\napply (auto)\ndone\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  ok_Nil: \"ok n [] n\" |\n  ok_LOADI: \"ok n is n' \\<Longrightarrow> ok n (is @ [LOADI _]) (Suc n')\" |\n  ok_LOAD: \"ok n is n' \\<Longrightarrow> ok n (is @ [LOAD _]) (Suc n')\" |\n  ok_ADD: \"ok n is (Suc (Suc n')) \\<Longrightarrow> ok n (is @ [ADD]) (Suc n')\"\n\ndeclare ok.intros[simp,intro]\n\ntheorem ok_correct: \"\\<lbrakk>ok n is n'; length stk = n\\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"\n  apply(induction rule: ok.induct)\n  apply(auto)\n  apply(smt (verit, best) exec1.simps(3) length_Suc_conv)\ndone\n\nlemma ok_append: \"ok n' b n'' \\<Longrightarrow> ok n a n' \\<Longrightarrow> ok n (a @ b) n''\"\n  apply(induction rule: ok.induct)\n  apply(simp)\n  apply(metis append_assoc ok_LOADI)\n  apply(metis append_assoc ok_LOAD)\n  apply(metis append_assoc ok_ADD)\ndone\n\ntheorem \"ok n (comp a) (Suc n)\"\n  apply(induction a arbitrary: n)\n  apply(auto simp del: append_Nil)\n  apply(auto intro: ok_append)\ndone\n\nend\n", "meta": {"author": "lemmarathon", "repo": "isabelle-exercises", "sha": "6a4a5c030b23a0152c1245424d25232958d9c2f8", "save_path": "github-repos/isabelle/lemmarathon-isabelle-exercises", "path": "github-repos/isabelle/lemmarathon-isabelle-exercises/isabelle-exercises-6a4a5c030b23a0152c1245424d25232958d9c2f8/concrete-semantics/Ch4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7925427894183482}}
{"text": "theory Chap2_5\nimports Main\nbegin\n\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 0\"\n| \"nodes (Node l r) = nodes l + nodes r\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\"\n| \"explode (Suc n) t = explode n (Node t t)\"\n\nlemma \"nodes (explode n t) = nodes t * 2^n\"\n  apply (induction n arbitrary: t)\n  by auto\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\"\n| \"eval (Const a) x = a\"\n| \"eval (Add e1 e2) x = eval e1 x + eval e2 x\"\n| \"eval (Mult e1 e2) x = eval e1 x * eval e2 x\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] a = 0\"\n| \"evalp (x#xs) a = x + a * evalp xs a\"\n\nfun padd :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"padd [] q = q\"\n| \"padd p [] = p\"\n| \"padd (p0#p) (q0#q) = (p0+q0)#(padd p q)\"\n\nfun cmul :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"cmul c p = map ((*) c) p\"\n\nfun xmul :: \"int list \\<Rightarrow> int list\" where\n\"xmul p = 0#p\"\n\nfun pmul :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"pmul [] q = []\"\n| \"pmul (p0#p) q = padd (cmul p0 q) (xmul (pmul p q))\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0, 1]\"\n| \"coeffs (Const a) = [a]\"\n| \"coeffs (Add e1 e2) = padd (coeffs e1) (coeffs e2)\"\n| \"coeffs (Mult e1 e2) = pmul (coeffs e1) (coeffs e2)\"\n\nlemma evalp_add: \"evalp (padd p q) x = evalp p x + evalp q x\"\n  apply (induction rule: padd.induct)\n  by (simp add: algebra_simps)+\n\nlemma evalp_cmul: \"evalp (cmul c p) x = c * evalp p x\"\n  apply (induction p)\n  by (simp add: algebra_simps)+\n\nlemma evalp_xmul: \"evalp (xmul p) x = x * evalp p x\"\n  apply (induction p)\n  by (simp add: algebra_simps)+\n\nlemma evalp_mul: \"evalp (pmul p q) x = evalp p x * evalp q x\"\n  apply (induction rule: pmul.induct)\n   apply simp\n  apply (simp only: pmul.simps)\n  apply (simp only: evalp_add)\n  apply (simp only: evalp_cmul evalp_xmul evalp.simps)\n  by (simp only: algebra_simps)\n\nlemma \"evalp (coeffs e) x = eval e x\"\n  apply (induction e)\n     apply simp+\n  using evalp_add evalp_mul by auto\n\nend", "meta": {"author": "1000teslas", "repo": "concrete_semantics", "sha": "690bb968718a3162b1c4ada4ef40370a4ff99c9c", "save_path": "github-repos/isabelle/1000teslas-concrete_semantics", "path": "github-repos/isabelle/1000teslas-concrete_semantics/concrete_semantics-690bb968718a3162b1c4ada4ef40370a4ff99c9c/Chap2_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7925427838858197}}
{"text": "theory Chapter4 imports Main begin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\" |\n\"set (Node l x r) = (set l) \\<union> (set r) \\<union> {x}\" \n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node l v r) = ((ord l) \\<and> (ord r) \\<and> (\\<forall>e \\<in> set l. e \\<le> v) \\<and> (\\<forall>e \\<in> set r. v \\<le> e))\" \n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins val Tip = Node Tip val Tip\" |\n\"ins val (Node l x r) = \n  (if x = val then  \n    (Node l x r) \n  else if x > val then\n    (Node (ins val l) x r)\n  else\n    (Node l x (ins val r)))\"\n\n\n\ntheorem \"ord t \\<Longrightarrow> ord (ins i t)\" \n  apply(induction t arbitrary:s)\n  apply(auto)\n  done\n\n(* Exercise 4.2 *)\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n\"palindrome []\" |\n\"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction xs rule:palindrome.induct)\n  apply(auto)\n  done\n\n(* Exercise 4.3 *)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\n\n\ntheorem \"star' r x y \\<Longrightarrow> star r x y\" \n  apply(induction rule:star'.induct)\n  apply(auto intro: refl)\n  done\n\nlemma [simp]: \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply (induction rule:star'.induct)\n  apply (auto intro: refl' step')\n  done\n\ntheorem \"star r x y \\<Longrightarrow> star' r x y\"\n  apply(induction rule:star.induct)\n  apply(auto intro: refl')\n  done\n\n(* Exercise 4.4 *)\n\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> int \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  where\niter_refl: \"iter r 0 x x\" |\niter_step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (n + 1) x z\"\n\ntheorem \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\n  apply(induction rule:star.induct)\n  apply(auto intro: iter_refl iter_step)\n  done\n\n(* Exercise 4.5 *)\n\ndatatype alpha = alpha | beta\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS_1: \"S []\" |\nS_2: \"S w \\<Longrightarrow> S (alpha # w @ [beta])\" |\nS_3: \"S w \\<Longrightarrow> S x \\<Longrightarrow> S (w @ x)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nT_1: \"T []\" |\nT_2: \"T w \\<Longrightarrow> T x \\<Longrightarrow> T (w @ [alpha] @ x @ [beta])\"\n\ntheorem T_implies_S: \"T w \\<Longrightarrow> S w\" \n  apply(induction rule:T.induct)\n  apply(auto intro:S_1 S_2 S_3)\n  done\n\nlemma TT: \"T w \\<Longrightarrow> T x \\<Longrightarrow> T (x @ w)\"\n  apply(induction rule: T.induct)\n  apply(simp)\n  apply(metis T.simps append.assoc)\n  done\n\ntheorem S_implies_T: \"S w \\<Longrightarrow> T w\" \n  apply(induction rule:S.induct)\n  apply(auto intro: T_1 T_2)\n  apply(metis T.simps T_1 append.left_neutral append_Cons)\n  apply(auto intro: TT)\n  done\n\ntheorem \"S w = T w\"\n  apply(auto intro: T_implies_S S_implies_T)\n  done\n\n(* Exercise 4.6 *)\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N a) s = a\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a b) s = aval a s + aval b s\"\n\ninductive rel_aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nra_N: \"rel_aval (N a) s a\" |\nra_V: \"rel_aval (V x) s (s x)\" |\nra_P: \"rel_aval p s px \\<Longrightarrow> rel_aval q s qx \\<Longrightarrow> rel_aval (Plus p q) s (px + qx)\"\n\ntheorem RA_A: \"rel_aval a s v \\<Longrightarrow> aval a s = v\"\n  apply(induction rule:rel_aval.induct)\n  apply(auto)\n  done\n\ntheorem A_RA: \"aval a s = v \\<Longrightarrow> rel_aval a s v\" \n  apply(induction a arbitrary: v)\n  apply(auto intro: ra_N ra_V ra_P)\n  done\n\ntheorem \"(aval a s = v) = rel_aval a s v\"\n  apply(auto intro: RA_A A_RA)\n  done\n\n(* Exercise 4.7 *)\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nabbreviation hd2 where \n\"hd2 xs \\<equiv> hd (tl xs)\"\n\nabbreviation tl2 where \n\"tl2 xs \\<equiv> tl (tl xs)\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk = (n # stk)\" |\n\"exec1 (LOAD x) s stk = (s(x) # stk)\" |\n\"exec1 ADD _ stk = (hd2 stk + hd stk) # tl2 stk\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i#is) s stk = exec is s (exec1 i s stk)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\nok_1: \"ok n [] n\" |\nok_2: \"ok n ((LOADI _) # xs) n' \\<Longrightarrow> ok (n + 1) xs n'\" |\nok_3: \"ok n ((LOAD _) # xs) n' \\<Longrightarrow> ok (n + 1) xs n'\" |\nok_4: \"ok n ((ADD) # xs) n' \\<Longrightarrow> ok (n - 1) xs n'\"\n\ntheorem \"\\<lbrakk> ok n is n'; length stk = n \\<rbrakk> \\<Longrightarrow> (length (exec is s stk) = n')\"\n  apply(induction arbitrary: stk rule: ok.induct)\n  apply(auto intro: ok_1 ok_2 ok_3 ok_4)\n  sorry\n  \nend", "meta": {"author": "kethomassen", "repo": "concrete-semantics", "sha": "c6cebd0ea2b7fd2d8a676acc6b7e7bf9368ab935", "save_path": "github-repos/isabelle/kethomassen-concrete-semantics", "path": "github-repos/isabelle/kethomassen-concrete-semantics/concrete-semantics-c6cebd0ea2b7fd2d8a676acc6b7e7bf9368ab935/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7925427783532908}}
{"text": "(*  Title:      HOL/Decision_Procs/Polynomial_List.thy\n    Author:     Amine Chaieb\n*)\n\nsection {* Univariate Polynomials as lists *}\n\ntheory Polynomial_List\nimports Complex_Main\nbegin\n\ntext{* Application of polynomial as a function. *}\n\nprimrec (in semiring_0) poly :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  poly_Nil:  \"poly [] x = 0\"\n| poly_Cons: \"poly (h#t) x = h + x * poly t x\"\n\n\nsubsection{*Arithmetic Operations on Polynomials*}\n\ntext{*addition*}\n\nprimrec (in semiring_0) padd :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixl \"+++\" 65)\nwhere\n  padd_Nil:  \"[] +++ l2 = l2\"\n| padd_Cons: \"(h#t) +++ l2 = (if l2 = [] then h#t else (h + hd l2)#(t +++ tl l2))\"\n\ntext{*Multiplication by a constant*}\nprimrec (in semiring_0) cmult :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixl \"%*\" 70) where\n  cmult_Nil:  \"c %* [] = []\"\n| cmult_Cons: \"c %* (h#t) = (c * h)#(c %* t)\"\n\ntext{*Multiplication by a polynomial*}\nprimrec (in semiring_0) pmult :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"  (infixl \"***\" 70)\nwhere\n  pmult_Nil:  \"[] *** l2 = []\"\n| pmult_Cons: \"(h#t) *** l2 = (if t = [] then h %* l2\n                              else (h %* l2) +++ ((0) # (t *** l2)))\"\n\ntext{*Repeated multiplication by a polynomial*}\nprimrec (in semiring_0) mulexp :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a  list \\<Rightarrow> 'a list\" where\n  mulexp_zero:  \"mulexp 0 p q = q\"\n| mulexp_Suc:   \"mulexp (Suc n) p q = p *** mulexp n p q\"\n\ntext{*Exponential*}\nprimrec (in semiring_1) pexp :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list\"  (infixl \"%^\" 80) where\n  pexp_0:   \"p %^ 0 = [1]\"\n| pexp_Suc: \"p %^ (Suc n) = p *** (p %^ n)\"\n\ntext{*Quotient related value of dividing a polynomial by x + a*}\n(* Useful for divisor properties in inductive proofs *)\nprimrec (in field) \"pquot\" :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\nwhere\n  pquot_Nil:  \"pquot [] a= []\"\n| pquot_Cons: \"pquot (h#t) a =\n    (if t = [] then [h] else (inverse(a) * (h - hd( pquot t a)))#(pquot t a))\"\n\ntext{*normalization of polynomials (remove extra 0 coeff)*}\nprimrec (in semiring_0) pnormalize :: \"'a list \\<Rightarrow> 'a list\" where\n  pnormalize_Nil:  \"pnormalize [] = []\"\n| pnormalize_Cons: \"pnormalize (h#p) =\n    (if pnormalize p = [] then (if h = 0 then [] else [h]) else h # pnormalize p)\"\n\ndefinition (in semiring_0) \"pnormal p = ((pnormalize p = p) \\<and> p \\<noteq> [])\"\ndefinition (in semiring_0) \"nonconstant p = (pnormal p \\<and> (\\<forall>x. p \\<noteq> [x]))\"\ntext{*Other definitions*}\n\ndefinition (in ring_1) poly_minus :: \"'a list \\<Rightarrow> 'a list\" (\"-- _\" [80] 80)\n  where \"-- p = (- 1) %* p\"\n\ndefinition (in semiring_0) divides :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"  (infixl \"divides\" 70)\n  where \"p1 divides p2 = (\\<exists>q. poly p2 = poly(p1 *** q))\"\n\nlemma (in semiring_0) dividesI:\n  \"poly p2 = poly (p1 *** q) \\<Longrightarrow> p1 divides p2\"\n  by (auto simp add: divides_def)\n\nlemma (in semiring_0) dividesE:\n  assumes \"p1 divides p2\"\n  obtains q where \"poly p2 = poly (p1 *** q)\"\n  using assms by (auto simp add: divides_def)\n\n    --{*order of a polynomial*}\ndefinition (in ring_1) order :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"order a p = (SOME n. ([-a, 1] %^ n) divides p \\<and> ~ (([-a, 1] %^ (Suc n)) divides p))\"\n\n     --{*degree of a polynomial*}\ndefinition (in semiring_0) degree :: \"'a list \\<Rightarrow> nat\"\n  where \"degree p = length (pnormalize p) - 1\"\n\n     --{*squarefree polynomials --- NB with respect to real roots only.*}\ndefinition (in ring_1) rsquarefree :: \"'a list \\<Rightarrow> bool\"\n  where \"rsquarefree p \\<longleftrightarrow> poly p \\<noteq> poly [] \\<and> (\\<forall>a. order a p = 0 \\<or> order a p = 1)\"\n\ncontext semiring_0\nbegin\n\nlemma padd_Nil2[simp]: \"p +++ [] = p\"\n  by (induct p) auto\n\nlemma padd_Cons_Cons: \"(h1 # p1) +++ (h2 # p2) = (h1 + h2) # (p1 +++ p2)\"\n  by auto\n\nlemma pminus_Nil: \"-- [] = []\"\n  by (simp add: poly_minus_def)\n\nlemma pmult_singleton: \"[h1] *** p1 = h1 %* p1\" by simp\n\nend\n\nlemma (in semiring_1) poly_ident_mult[simp]: \"1 %* t = t\" by (induct t) auto\n\nlemma (in semiring_0) poly_simple_add_Cons[simp]: \"[a] +++ ((0)#t) = (a#t)\"\n  by simp\n\ntext{*Handy general properties*}\n\nlemma (in comm_semiring_0) padd_commut: \"b +++ a = a +++ b\"\nproof (induct b arbitrary: a)\n  case Nil\n  thus ?case by auto\nnext\n  case (Cons b bs a)\n  thus ?case by (cases a) (simp_all add: add.commute)\nqed\n\nlemma (in comm_semiring_0) padd_assoc: \"\\<forall>b c. (a +++ b) +++ c = a +++ (b +++ c)\"\n  apply (induct a)\n  apply (simp, clarify)\n  apply (case_tac b, simp_all add: ac_simps)\n  done\n\nlemma (in semiring_0) poly_cmult_distr: \"a %* ( p +++ q) = (a %* p +++ a %* q)\"\n  apply (induct p arbitrary: q)\n  apply simp\n  apply (case_tac q, simp_all add: distrib_left)\n  done\n\nlemma (in ring_1) pmult_by_x[simp]: \"[0, 1] *** t = ((0)#t)\"\n  apply (induct t)\n  apply simp\n  apply (auto simp add: padd_commut)\n  apply (case_tac t, auto)\n  done\n\ntext{*properties of evaluation of polynomials.*}\n\nlemma (in semiring_0) poly_add: \"poly (p1 +++ p2) x = poly p1 x + poly p2 x\"\nproof(induct p1 arbitrary: p2)\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons a as p2)\n  thus ?case\n    by (cases p2) (simp_all  add: ac_simps distrib_left)\nqed\n\nlemma (in comm_semiring_0) poly_cmult: \"poly (c %* p) x = c * poly p x\"\n  apply (induct p)\n  apply (case_tac [2] \"x = zero\")\n  apply (auto simp add: distrib_left ac_simps)\n  done\n\nlemma (in comm_semiring_0) poly_cmult_map: \"poly (map (op * c) p) x = c*poly p x\"\n  by (induct p) (auto simp add: distrib_left ac_simps)\n\nlemma (in comm_ring_1) poly_minus: \"poly (-- p) x = - (poly p x)\"\n  apply (simp add: poly_minus_def)\n  apply (auto simp add: poly_cmult)\n  done\n\nlemma (in comm_semiring_0) poly_mult: \"poly (p1 *** p2) x = poly p1 x * poly p2 x\"\nproof (induct p1 arbitrary: p2)\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons a as p2)\n  thus ?case by (cases as)\n    (simp_all add: poly_cmult poly_add distrib_right distrib_left ac_simps)\nqed\n\nclass idom_char_0 = idom + ring_char_0\n\nsubclass (in field_char_0) idom_char_0 ..\n\nlemma (in comm_ring_1) poly_exp: \"poly (p %^ n) x = (poly p x) ^ n\"\n  by (induct n) (auto simp add: poly_cmult poly_mult)\n\ntext{*More Polynomial Evaluation Lemmas*}\n\nlemma (in semiring_0) poly_add_rzero[simp]: \"poly (a +++ []) x = poly a x\"\n  by simp\n\nlemma (in comm_semiring_0) poly_mult_assoc: \"poly ((a *** b) *** c) x = poly (a *** (b *** c)) x\"\n  by (simp add: poly_mult mult.assoc)\n\nlemma (in semiring_0) poly_mult_Nil2[simp]: \"poly (p *** []) x = 0\"\n  by (induct p) auto\n\nlemma (in comm_semiring_1) poly_exp_add: \"poly (p %^ (n + d)) x = poly( p %^ n *** p %^ d) x\"\n  by (induct n) (auto simp add: poly_mult mult.assoc)\n\nsubsection{*Key Property: if @{term \"f(a) = 0\"} then @{term \"(x - a)\"} divides\n @{term \"p(x)\"} *}\n\nlemma (in comm_ring_1) lemma_poly_linear_rem: \"\\<forall>h. \\<exists>q r. h#t = [r] +++ [-a, 1] *** q\"\nproof(induct t)\n  case Nil\n  { fix h have \"[h] = [h] +++ [- a, 1] *** []\" by simp }\n  thus ?case by blast\nnext\n  case (Cons  x xs)\n  { fix h\n    from Cons.hyps[rule_format, of x]\n    obtain q r where qr: \"x#xs = [r] +++ [- a, 1] *** q\" by blast\n    have \"h#x#xs = [a*r + h] +++ [-a, 1] *** (r#q)\"\n      using qr by (cases q) (simp_all add: algebra_simps)\n    hence \"\\<exists>q r. h#x#xs = [r] +++ [-a, 1] *** q\" by blast}\n  thus ?case by blast\nqed\n\nlemma (in comm_ring_1) poly_linear_rem: \"\\<exists>q r. h#t = [r] +++ [-a, 1] *** q\"\n  using lemma_poly_linear_rem [where t = t and a = a] by auto\n\n\nlemma (in comm_ring_1) poly_linear_divides: \"(poly p a = 0) = ((p = []) | (\\<exists>q. p = [-a, 1] *** q))\"\nproof -\n  { assume p: \"p = []\" hence ?thesis by simp }\n  moreover\n  {\n    fix x xs assume p: \"p = x#xs\"\n    {\n      fix q assume \"p = [-a, 1] *** q\"\n      hence \"poly p a = 0\" by (simp add: poly_add poly_cmult)\n    }\n    moreover\n    { assume p0: \"poly p a = 0\"\n      from poly_linear_rem[of x xs a] obtain q r\n      where qr: \"x#xs = [r] +++ [- a, 1] *** q\" by blast\n      have \"r = 0\" using p0 by (simp only: p qr poly_mult poly_add) simp\n      hence \"\\<exists>q. p = [- a, 1] *** q\"\n        using p qr\n        apply -\n        apply (rule exI[where x=q])\n        apply auto\n        apply (cases q)\n        apply auto\n        done\n    }\n    ultimately have ?thesis using p by blast\n  }\n  ultimately show ?thesis by (cases p) auto\nqed\n\nlemma (in semiring_0) lemma_poly_length_mult[simp]: \"\\<forall>h k a. length (k %* p +++  (h # (a %* p))) = Suc (length p)\"\n  by (induct p) auto\n\nlemma (in semiring_0) lemma_poly_length_mult2[simp]: \"\\<forall>h k. length (k %* p +++  (h # p)) = Suc (length p)\"\n  by (induct p) auto\n\nlemma (in ring_1) poly_length_mult[simp]: \"length([-a,1] *** q) = Suc (length q)\"\n  by auto\n\nsubsection{*Polynomial length*}\n\nlemma (in semiring_0) poly_cmult_length[simp]: \"length (a %* p) = length p\"\n  by (induct p) auto\n\nlemma (in semiring_0) poly_add_length: \"length (p1 +++ p2) = max (length p1) (length p2)\"\n  by (induct p1 arbitrary: p2) (simp_all, arith)\n\nlemma (in semiring_0) poly_root_mult_length[simp]: \"length([a,b] *** p) = Suc (length p)\"\n  by (simp add: poly_add_length)\n\nlemma (in idom) poly_mult_not_eq_poly_Nil[simp]:\n  \"poly (p *** q) x \\<noteq> poly [] x \\<longleftrightarrow> poly p x \\<noteq> poly [] x \\<and> poly q x \\<noteq> poly [] x\"\n  by (auto simp add: poly_mult)\n\nlemma (in idom) poly_mult_eq_zero_disj: \"poly (p *** q) x = 0 \\<longleftrightarrow> poly p x = 0 \\<or> poly q x = 0\"\n  by (auto simp add: poly_mult)\n\ntext{*Normalisation Properties*}\n\nlemma (in semiring_0) poly_normalized_nil: \"(pnormalize p = []) --> (poly p x = 0)\"\n  by (induct p) auto\n\ntext{*A nontrivial polynomial of degree n has no more than n roots*}\nlemma (in idom) poly_roots_index_lemma:\n   assumes p: \"poly p x \\<noteq> poly [] x\" and n: \"length p = n\"\n  shows \"\\<exists>i. \\<forall>x. poly p x = 0 \\<longrightarrow> (\\<exists>m\\<le>n. x = i m)\"\n  using p n\nproof (induct n arbitrary: p x)\n  case 0\n  thus ?case by simp\nnext\n  case (Suc n p x)\n  {\n    assume C: \"\\<And>i. \\<exists>x. poly p x = 0 \\<and> (\\<forall>m\\<le>Suc n. x \\<noteq> i m)\"\n    from Suc.prems have p0: \"poly p x \\<noteq> 0\" \"p\\<noteq> []\" by auto\n    from p0(1)[unfolded poly_linear_divides[of p x]]\n    have \"\\<forall>q. p \\<noteq> [- x, 1] *** q\" by blast\n    from C obtain a where a: \"poly p a = 0\" by blast\n    from a[unfolded poly_linear_divides[of p a]] p0(2)\n    obtain q where q: \"p = [-a, 1] *** q\" by blast\n    have lg: \"length q = n\" using q Suc.prems(2) by simp\n    from q p0 have qx: \"poly q x \\<noteq> poly [] x\"\n      by (auto simp add: poly_mult poly_add poly_cmult)\n    from Suc.hyps[OF qx lg] obtain i where\n      i: \"\\<forall>x. poly q x = 0 \\<longrightarrow> (\\<exists>m\\<le>n. x = i m)\" by blast\n    let ?i = \"\\<lambda>m. if m = Suc n then a else i m\"\n    from C[of ?i] obtain y where y: \"poly p y = 0\" \"\\<forall>m\\<le> Suc n. y \\<noteq> ?i m\"\n      by blast\n    from y have \"y = a \\<or> poly q y = 0\"\n      by (simp only: q poly_mult_eq_zero_disj poly_add) (simp add: algebra_simps)\n    with i[rule_format, of y] y(1) y(2) have False\n      apply auto\n      apply (erule_tac x = \"m\" in allE)\n      apply auto\n      done\n  }\n  thus ?case by blast\nqed\n\n\nlemma (in idom) poly_roots_index_length:\n  \"poly p x \\<noteq> poly [] x \\<Longrightarrow> \\<exists>i. \\<forall>x. (poly p x = 0) \\<longrightarrow> (\\<exists>n. n \\<le> length p \\<and> x = i n)\"\n  by (blast intro: poly_roots_index_lemma)\n\nlemma (in idom) poly_roots_finite_lemma1:\n  \"poly p x \\<noteq> poly [] x \\<Longrightarrow> \\<exists>N i. \\<forall>x. (poly p x = 0) \\<longrightarrow> (\\<exists>n. (n::nat) < N \\<and> x = i n)\"\n  apply (drule poly_roots_index_length, safe)\n  apply (rule_tac x = \"Suc (length p)\" in exI)\n  apply (rule_tac x = i in exI)\n  apply (simp add: less_Suc_eq_le)\n  done\n\nlemma (in idom) idom_finite_lemma:\n  assumes P: \"\\<forall>x. P x --> (\\<exists>n. n < length j \\<and> x = j!n)\"\n  shows \"finite {x. P x}\"\nproof -\n  let ?M = \"{x. P x}\"\n  let ?N = \"set j\"\n  have \"?M \\<subseteq> ?N\" using P by auto\n  thus ?thesis using finite_subset by auto\nqed\n\nlemma (in idom) poly_roots_finite_lemma2:\n  \"poly p x \\<noteq> poly [] x \\<Longrightarrow> \\<exists>i. \\<forall>x. poly p x = 0 \\<longrightarrow> x \\<in> set i\"\n  apply (drule poly_roots_index_length, safe)\n  apply (rule_tac x=\"map (\\<lambda>n. i n) [0 ..< Suc (length p)]\" in exI)\n  apply (auto simp add: image_iff)\n  apply (erule_tac x=\"x\" in allE, clarsimp)\n  apply (case_tac \"n = length p\")\n  apply (auto simp add: order_le_less)\n  done\n\nlemma (in ring_char_0) UNIV_ring_char_0_infinte: \"\\<not> (finite (UNIV:: 'a set))\"\nproof\n  assume F: \"finite (UNIV :: 'a set)\"\n  have \"finite (UNIV :: nat set)\"\n  proof (rule finite_imageD)\n    have \"of_nat ` UNIV \\<subseteq> UNIV\" by simp\n    then show \"finite (of_nat ` UNIV :: 'a set)\" using F by (rule finite_subset)\n    show \"inj (of_nat :: nat \\<Rightarrow> 'a)\" by (simp add: inj_on_def)\n  qed\n  with infinite_UNIV_nat show False ..\nqed\n\nlemma (in idom_char_0) poly_roots_finite: \"poly p \\<noteq> poly [] \\<longleftrightarrow> finite {x. poly p x = 0}\"\nproof\n  assume H: \"poly p \\<noteq> poly []\"\n  show \"finite {x. poly p x = (0::'a)}\"\n    using H\n    apply -\n    apply (erule contrapos_np, rule ext)\n    apply (rule ccontr)\n    apply (clarify dest!: poly_roots_finite_lemma2)\n    using finite_subset\n  proof -\n    fix x i\n    assume F: \"\\<not> finite {x. poly p x = (0\\<Colon>'a)}\"\n      and P: \"\\<forall>x. poly p x = (0\\<Colon>'a) \\<longrightarrow> x \\<in> set i\"\n    let ?M= \"{x. poly p x = (0\\<Colon>'a)}\"\n    from P have \"?M \\<subseteq> set i\" by auto\n    with finite_subset F show False by auto\n  qed\nnext\n  assume F: \"finite {x. poly p x = (0\\<Colon>'a)}\"\n  show \"poly p \\<noteq> poly []\" using F UNIV_ring_char_0_infinte by auto\nqed\n\ntext{*Entirety and Cancellation for polynomials*}\n\nlemma (in idom_char_0) poly_entire_lemma2:\n  assumes p0: \"poly p \\<noteq> poly []\"\n    and q0: \"poly q \\<noteq> poly []\"\n  shows \"poly (p***q) \\<noteq> poly []\"\nproof -\n  let ?S = \"\\<lambda>p. {x. poly p x = 0}\"\n  have \"?S (p *** q) = ?S p \\<union> ?S q\" by (auto simp add: poly_mult)\n  with p0 q0 show ?thesis  unfolding poly_roots_finite by auto\nqed\n\nlemma (in idom_char_0) poly_entire:\n  \"poly (p *** q) = poly [] \\<longleftrightarrow> poly p = poly [] \\<or> poly q = poly []\"\n  using poly_entire_lemma2[of p q]\n  by (auto simp add: fun_eq_iff poly_mult)\n\nlemma (in idom_char_0) poly_entire_neg:\n  \"poly (p *** q) \\<noteq> poly [] \\<longleftrightarrow> poly p \\<noteq> poly [] \\<and> poly q \\<noteq> poly []\"\n  by (simp add: poly_entire)\n\nlemma fun_eq: \"f = g \\<longleftrightarrow> (\\<forall>x. f x = g x)\"\n  by auto\n\nlemma (in comm_ring_1) poly_add_minus_zero_iff:\n  \"poly (p +++ -- q) = poly [] \\<longleftrightarrow> poly p = poly q\"\n  by (auto simp add: algebra_simps poly_add poly_minus_def fun_eq poly_cmult)\n\nlemma (in comm_ring_1) poly_add_minus_mult_eq:\n  \"poly (p *** q +++ --(p *** r)) = poly (p *** (q +++ -- r))\"\n  by (auto simp add: poly_add poly_minus_def fun_eq poly_mult poly_cmult algebra_simps)\n\nsubclass (in idom_char_0) comm_ring_1 ..\n\nlemma (in idom_char_0) poly_mult_left_cancel:\n  \"poly (p *** q) = poly (p *** r) \\<longleftrightarrow> poly p = poly [] \\<or> poly q = poly r\"\nproof -\n  have \"poly (p *** q) = poly (p *** r) \\<longleftrightarrow> poly (p *** q +++ -- (p *** r)) = poly []\"\n    by (simp only: poly_add_minus_zero_iff)\n  also have \"\\<dots> \\<longleftrightarrow> poly p = poly [] \\<or> poly q = poly r\"\n    by (auto intro: simp add: poly_add_minus_mult_eq poly_entire poly_add_minus_zero_iff)\n  finally show ?thesis .\nqed\n\nlemma (in idom) poly_exp_eq_zero[simp]:\n  \"poly (p %^ n) = poly [] \\<longleftrightarrow> poly p = poly [] \\<and> n \\<noteq> 0\"\n  apply (simp only: fun_eq add: HOL.all_simps [symmetric])\n  apply (rule arg_cong [where f = All])\n  apply (rule ext)\n  apply (induct n)\n  apply (auto simp add: poly_exp poly_mult)\n  done\n\nlemma (in comm_ring_1) poly_prime_eq_zero[simp]: \"poly [a,1] \\<noteq> poly []\"\n  apply (simp add: fun_eq)\n  apply (rule_tac x = \"minus one a\" in exI)\n  apply (simp add: add.commute [of a])\n  done\n\nlemma (in idom) poly_exp_prime_eq_zero: \"poly ([a, 1] %^ n) \\<noteq> poly []\"\n  by auto\n\ntext{*A more constructive notion of polynomials being trivial*}\n\nlemma (in idom_char_0) poly_zero_lemma': \"poly (h # t) = poly [] \\<Longrightarrow> h = 0 \\<and> poly t = poly []\"\n  apply (simp add: fun_eq)\n  apply (case_tac \"h = zero\")\n  apply (drule_tac [2] x = zero in spec, auto)\n  apply (cases \"poly t = poly []\", simp)\nproof -\n  fix x\n  assume H: \"\\<forall>x. x = (0\\<Colon>'a) \\<or> poly t x = (0\\<Colon>'a)\"\n    and pnz: \"poly t \\<noteq> poly []\"\n  let ?S = \"{x. poly t x = 0}\"\n  from H have \"\\<forall>x. x \\<noteq>0 \\<longrightarrow> poly t x = 0\" by blast\n  hence th: \"?S \\<supseteq> UNIV - {0}\" by auto\n  from poly_roots_finite pnz have th': \"finite ?S\" by blast\n  from finite_subset[OF th th'] UNIV_ring_char_0_infinte show \"poly t x = (0\\<Colon>'a)\"\n    by simp\nqed\n\nlemma (in idom_char_0) poly_zero: \"(poly p = poly []) = list_all (%c. c = 0) p\"\n  apply (induct p)\n  apply simp\n  apply (rule iffI)\n  apply (drule poly_zero_lemma', auto)\n  done\n\nlemma (in idom_char_0) poly_0: \"list_all (\\<lambda>c. c = 0) p \\<Longrightarrow> poly p x = 0\"\n  unfolding poly_zero[symmetric] by simp\n\n\n\ntext{*Basics of divisibility.*}\n\nlemma (in idom) poly_primes:\n  \"[a, 1] divides (p *** q) \\<longleftrightarrow> [a, 1] divides p \\<or> [a, 1] divides q\"\n  apply (auto simp add: divides_def fun_eq poly_mult poly_add poly_cmult distrib_right [symmetric])\n  apply (drule_tac x = \"uminus a\" in spec)\n  apply (simp add: poly_linear_divides poly_add poly_cmult distrib_right [symmetric])\n  apply (cases \"p = []\")\n  apply (rule exI[where x=\"[]\"])\n  apply simp\n  apply (cases \"q = []\")\n  apply (erule allE[where x=\"[]\"], simp)\n\n  apply clarsimp\n  apply (cases \"\\<exists>q\\<Colon>'a list. p = a %* q +++ ((0\\<Colon>'a) # q)\")\n  apply (clarsimp simp add: poly_add poly_cmult)\n  apply (rule_tac x=\"qa\" in exI)\n  apply (simp add: distrib_right [symmetric])\n  apply clarsimp\n\n  apply (auto simp add: poly_linear_divides poly_add poly_cmult distrib_right [symmetric])\n  apply (rule_tac x = \"pmult qa q\" in exI)\n  apply (rule_tac [2] x = \"pmult p qa\" in exI)\n  apply (auto simp add: poly_add poly_mult poly_cmult ac_simps)\n  done\n\nlemma (in comm_semiring_1) poly_divides_refl[simp]: \"p divides p\"\n  apply (simp add: divides_def)\n  apply (rule_tac x = \"[one]\" in exI)\n  apply (auto simp add: poly_mult fun_eq)\n  done\n\nlemma (in comm_semiring_1) poly_divides_trans: \"p divides q \\<Longrightarrow> q divides r \\<Longrightarrow> p divides r\"\n  apply (simp add: divides_def, safe)\n  apply (rule_tac x = \"pmult qa qaa\" in exI)\n  apply (auto simp add: poly_mult fun_eq mult.assoc)\n  done\n\nlemma (in comm_semiring_1) poly_divides_exp: \"m \\<le> n \\<Longrightarrow> (p %^ m) divides (p %^ n)\"\n  apply (auto simp add: le_iff_add)\n  apply (induct_tac k)\n  apply (rule_tac [2] poly_divides_trans)\n  apply (auto simp add: divides_def)\n  apply (rule_tac x = p in exI)\n  apply (auto simp add: poly_mult fun_eq ac_simps)\n  done\n\nlemma (in comm_semiring_1) poly_exp_divides:\n  \"(p %^ n) divides q \\<Longrightarrow> m \\<le> n \\<Longrightarrow> (p %^ m) divides q\"\n  by (blast intro: poly_divides_exp poly_divides_trans)\n\nlemma (in comm_semiring_0) poly_divides_add:\n  \"p divides q \\<Longrightarrow> p divides r \\<Longrightarrow> p divides (q +++ r)\"\n  apply (simp add: divides_def, auto)\n  apply (rule_tac x = \"padd qa qaa\" in exI)\n  apply (auto simp add: poly_add fun_eq poly_mult distrib_left)\n  done\n\nlemma (in comm_ring_1) poly_divides_diff:\n  \"p divides q \\<Longrightarrow> p divides (q +++ r) \\<Longrightarrow> p divides r\"\n  apply (simp add: divides_def, auto)\n  apply (rule_tac x = \"padd qaa (poly_minus qa)\" in exI)\n  apply (auto simp add: poly_add fun_eq poly_mult poly_minus algebra_simps)\n  done\n\nlemma (in comm_ring_1) poly_divides_diff2:\n  \"p divides r \\<Longrightarrow> p divides (q +++ r) \\<Longrightarrow> p divides q\"\n  apply (erule poly_divides_diff)\n  apply (auto simp add: poly_add fun_eq poly_mult divides_def ac_simps)\n  done\n\nlemma (in semiring_0) poly_divides_zero: \"poly p = poly [] \\<Longrightarrow> q divides p\"\n  apply (simp add: divides_def)\n  apply (rule exI[where x=\"[]\"])\n  apply (auto simp add: fun_eq poly_mult)\n  done\n\nlemma (in semiring_0) poly_divides_zero2 [simp]: \"q divides []\"\n  apply (simp add: divides_def)\n  apply (rule_tac x = \"[]\" in exI)\n  apply (auto simp add: fun_eq)\n  done\n\ntext{*At last, we can consider the order of a root.*}\n\nlemma (in idom_char_0) poly_order_exists_lemma:\n  assumes lp: \"length p = d\"\n    and p: \"poly p \\<noteq> poly []\"\n  shows \"\\<exists>n q. p = mulexp n [-a, 1] q \\<and> poly q a \\<noteq> 0\"\n  using lp p\nproof (induct d arbitrary: p)\n  case 0\n  thus ?case by simp\nnext\n  case (Suc n p)\n  show ?case\n  proof (cases \"poly p a = 0\")\n    case True\n    from Suc.prems have h: \"length p = Suc n\" \"poly p \\<noteq> poly []\" by auto\n    hence pN: \"p \\<noteq> []\" by auto\n    from True[unfolded poly_linear_divides] pN obtain q where q: \"p = [-a, 1] *** q\"\n      by blast\n    from q h True have qh: \"length q = n\" \"poly q \\<noteq> poly []\"\n      apply -\n      apply simp\n      apply (simp only: fun_eq)\n      apply (rule ccontr)\n      apply (simp add: fun_eq poly_add poly_cmult)\n      done\n    from Suc.hyps[OF qh] obtain m r where mr: \"q = mulexp m [-a,1] r\" \"poly r a \\<noteq> 0\"\n      by blast\n    from mr q have \"p = mulexp (Suc m) [-a,1] r \\<and> poly r a \\<noteq> 0\" by simp\n    then show ?thesis by blast\n  next\n    case False\n    then show ?thesis\n      using Suc.prems\n      apply simp\n      apply (rule exI[where x=\"0::nat\"])\n      apply simp\n      done\n  qed\nqed\n\n\nlemma (in comm_semiring_1) poly_mulexp: \"poly (mulexp n p q) x = (poly p x) ^ n * poly q x\"\n  by (induct n) (auto simp add: poly_mult ac_simps)\n\nlemma (in comm_semiring_1) divides_left_mult:\n  assumes d:\"(p***q) divides r\" shows \"p divides r \\<and> q divides r\"\nproof-\n  from d obtain t where r:\"poly r = poly (p***q *** t)\"\n    unfolding divides_def by blast\n  hence \"poly r = poly (p *** (q *** t))\"\n    \"poly r = poly (q *** (p***t))\" by(auto simp add: fun_eq poly_mult ac_simps)\n  thus ?thesis unfolding divides_def by blast\nqed\n\n\n(* FIXME: Tidy up *)\n\nlemma (in semiring_1) zero_power_iff: \"0 ^ n = (if n = 0 then 1 else 0)\"\n  by (induct n) simp_all\n\nlemma (in idom_char_0) poly_order_exists:\n  assumes \"length p = d\" and \"poly p \\<noteq> poly []\"\n  shows \"\\<exists>n. [- a, 1] %^ n divides p \\<and> \\<not> [- a, 1] %^ Suc n divides p\"\nproof -\n  from assms have \"\\<exists>n q. p = mulexp n [- a, 1] q \\<and> poly q a \\<noteq> 0\"\n    by (rule poly_order_exists_lemma)\n  then obtain n q where p: \"p = mulexp n [- a, 1] q\" and \"poly q a \\<noteq> 0\" by blast\n  have \"[- a, 1] %^ n divides mulexp n [- a, 1] q\"\n  proof (rule dividesI)\n    show \"poly (mulexp n [- a, 1] q) = poly ([- a, 1] %^ n *** q)\"\n      by (induct n) (simp_all add: poly_add poly_cmult poly_mult algebra_simps)\n  qed\n  moreover have \"\\<not> [- a, 1] %^ Suc n divides mulexp n [- a, 1] q\"\n  proof\n    assume \"[- a, 1] %^ Suc n divides mulexp n [- a, 1] q\"\n    then obtain m where \"poly (mulexp n [- a, 1] q) = poly ([- a, 1] %^ Suc n *** m)\"\n      by (rule dividesE)\n    moreover have \"poly (mulexp n [- a, 1] q) \\<noteq> poly ([- a, 1] %^ Suc n *** m)\"\n    proof (induct n)\n      case 0 show ?case\n      proof (rule ccontr)\n        assume \"\\<not> poly (mulexp 0 [- a, 1] q) \\<noteq> poly ([- a, 1] %^ Suc 0 *** m)\"\n        then have \"poly q a = 0\"\n          by (simp add: poly_add poly_cmult)\n        with `poly q a \\<noteq> 0` show False by simp\n      qed\n    next\n      case (Suc n) show ?case\n        by (rule pexp_Suc [THEN ssubst], rule ccontr)\n          (simp add: poly_mult_left_cancel poly_mult_assoc Suc del: pmult_Cons pexp_Suc)\n    qed\n    ultimately show False by simp\n  qed\n  ultimately show ?thesis by (auto simp add: p)\nqed\n\nlemma (in semiring_1) poly_one_divides[simp]: \"[1] divides p\"\n  by (auto simp add: divides_def)\n\nlemma (in idom_char_0) poly_order:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> \\<exists>!n. ([-a, 1] %^ n) divides p \\<and> \\<not> (([-a, 1] %^ Suc n) divides p)\"\n  apply (auto intro: poly_order_exists simp add: less_linear simp del: pmult_Cons pexp_Suc)\n  apply (cut_tac x = y and y = n in less_linear)\n  apply (drule_tac m = n in poly_exp_divides)\n  apply (auto dest: Suc_le_eq [THEN iffD2, THEN [2] poly_exp_divides]\n              simp del: pmult_Cons pexp_Suc)\n  done\n\ntext{*Order*}\n\nlemma some1_equalityD: \"n = (SOME n. P n) \\<Longrightarrow> \\<exists>!n. P n \\<Longrightarrow> P n\"\n  by (blast intro: someI2)\n\nlemma (in idom_char_0) order:\n      \"(([-a, 1] %^ n) divides p \\<and>\n        ~(([-a, 1] %^ (Suc n)) divides p)) =\n        ((n = order a p) \\<and> ~(poly p = poly []))\"\n  apply (unfold order_def)\n  apply (rule iffI)\n  apply (blast dest: poly_divides_zero intro!: some1_equality [symmetric] poly_order)\n  apply (blast intro!: poly_order [THEN [2] some1_equalityD])\n  done\n\nlemma (in idom_char_0) order2:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow>\n    ([-a, 1] %^ (order a p)) divides p \\<and> \\<not> (([-a, 1] %^ (Suc (order a p))) divides p)\"\n  by (simp add: order del: pexp_Suc)\n\nlemma (in idom_char_0) order_unique:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> ([-a, 1] %^ n) divides p \\<Longrightarrow> ~(([-a, 1] %^ (Suc n)) divides p) \\<Longrightarrow>\n    n = order a p\"\n  using order [of a n p] by auto\n\nlemma (in idom_char_0) order_unique_lemma:\n  \"poly p \\<noteq> poly [] \\<and> ([-a, 1] %^ n) divides p \\<and> ~(([-a, 1] %^ (Suc n)) divides p) \\<Longrightarrow>\n    n = order a p\"\n  by (blast intro: order_unique)\n\nlemma (in ring_1) order_poly: \"poly p = poly q \\<Longrightarrow> order a p = order a q\"\n  by (auto simp add: fun_eq divides_def poly_mult order_def)\n\nlemma (in semiring_1) pexp_one[simp]: \"p %^ (Suc 0) = p\"\n  by (induct \"p\") auto\n\nlemma (in comm_ring_1) lemma_order_root:\n  \"0 < n \\<and> [- a, 1] %^ n divides p \\<and> ~ [- a, 1] %^ (Suc n) divides p \\<Longrightarrow> poly p a = 0\"\n  by (induct n arbitrary: a p) (auto simp add: divides_def poly_mult simp del: pmult_Cons)\n\nlemma (in idom_char_0) order_root:\n  \"poly p a = 0 \\<longleftrightarrow> poly p = poly [] \\<or> order a p \\<noteq> 0\"\n  apply (cases \"poly p = poly []\")\n  apply auto\n  apply (simp add: poly_linear_divides del: pmult_Cons, safe)\n  apply (drule_tac [!] a = a in order2)\n  apply (rule ccontr)\n  apply (simp add: divides_def poly_mult fun_eq del: pmult_Cons, blast)\n  using neq0_conv\n  apply (blast intro: lemma_order_root)\n  done\n\nlemma (in idom_char_0) order_divides:\n  \"([-a, 1] %^ n) divides p \\<longleftrightarrow> poly p = poly [] \\<or> n \\<le> order a p\"\n  apply (cases \"poly p = poly []\")\n  apply auto\n  apply (simp add: divides_def fun_eq poly_mult)\n  apply (rule_tac x = \"[]\" in exI)\n  apply (auto dest!: order2 [where a=a] intro: poly_exp_divides simp del: pexp_Suc)\n  done\n\nlemma (in idom_char_0) order_decomp:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> \\<exists>q. poly p = poly (([-a, 1] %^ (order a p)) *** q) \\<and> ~([-a, 1] divides q)\"\n  apply (unfold divides_def)\n  apply (drule order2 [where a = a])\n  apply (simp add: divides_def del: pexp_Suc pmult_Cons, safe)\n  apply (rule_tac x = q in exI, safe)\n  apply (drule_tac x = qa in spec)\n  apply (auto simp add: poly_mult fun_eq poly_exp ac_simps simp del: pmult_Cons)\n  done\n\ntext{*Important composition properties of orders.*}\nlemma order_mult:\n  \"poly (p *** q) \\<noteq> poly [] \\<Longrightarrow>\n    order a (p *** q) = order a p + order (a::'a::{idom_char_0}) q\"\n  apply (cut_tac a = a and p = \"p *** q\" and n = \"order a p + order a q\" in order)\n  apply (auto simp add: poly_entire simp del: pmult_Cons)\n  apply (drule_tac a = a in order2)+\n  apply safe\n  apply (simp add: divides_def fun_eq poly_exp_add poly_mult del: pmult_Cons, safe)\n  apply (rule_tac x = \"qa *** qaa\" in exI)\n  apply (simp add: poly_mult ac_simps del: pmult_Cons)\n  apply (drule_tac a = a in order_decomp)+\n  apply safe\n  apply (subgoal_tac \"[-a,1] divides (qa *** qaa) \")\n  apply (simp add: poly_primes del: pmult_Cons)\n  apply (auto simp add: divides_def simp del: pmult_Cons)\n  apply (rule_tac x = qb in exI)\n  apply (subgoal_tac \"poly ([-a, 1] %^ (order a p) *** (qa *** qaa)) = poly ([-a, 1] %^ (order a p) *** ([-a, 1] *** qb))\")\n  apply (drule poly_mult_left_cancel [THEN iffD1], force)\n  apply (subgoal_tac \"poly ([-a, 1] %^ (order a q) *** ([-a, 1] %^ (order a p) *** (qa *** qaa))) = poly ([-a, 1] %^ (order a q) *** ([-a, 1] %^ (order a p) *** ([-a, 1] *** qb))) \")\n  apply (drule poly_mult_left_cancel [THEN iffD1], force)\n  apply (simp add: fun_eq poly_exp_add poly_mult ac_simps del: pmult_Cons)\n  done\n\nlemma (in idom_char_0) order_mult:\n  assumes \"poly (p *** q) \\<noteq> poly []\"\n  shows \"order a (p *** q) = order a p + order a q\"\n  using assms\n  apply (cut_tac a = a and p = \"pmult p q\" and n = \"order a p + order a q\" in order)\n  apply (auto simp add: poly_entire simp del: pmult_Cons)\n  apply (drule_tac a = a in order2)+\n  apply safe\n  apply (simp add: divides_def fun_eq poly_exp_add poly_mult del: pmult_Cons, safe)\n  apply (rule_tac x = \"pmult qa qaa\" in exI)\n  apply (simp add: poly_mult ac_simps del: pmult_Cons)\n  apply (drule_tac a = a in order_decomp)+\n  apply safe\n  apply (subgoal_tac \"[uminus a, one] divides pmult qa qaa\")\n  apply (simp add: poly_primes del: pmult_Cons)\n  apply (auto simp add: divides_def simp del: pmult_Cons)\n  apply (rule_tac x = qb in exI)\n  apply (subgoal_tac \"poly (pmult (pexp [uminus a, one] (order a p)) (pmult qa qaa)) =\n    poly (pmult (pexp [uminus a, one] (?order a p)) (pmult [uminus a, one] qb))\")\n  apply (drule poly_mult_left_cancel [THEN iffD1], force)\n  apply (subgoal_tac \"poly (pmult (pexp [uminus a, one] (order a q))\n      (pmult (pexp [uminus a, one] (order a p)) (pmult qa qaa))) =\n    poly (pmult (pexp [uminus a, one] (order a q))\n      (pmult (pexp [uminus a, one] (order a p)) (pmult [uminus a, one] qb)))\")\n  apply (drule poly_mult_left_cancel [THEN iffD1], force)\n  apply (simp add: fun_eq poly_exp_add poly_mult ac_simps del: pmult_Cons)\n  done\n\nlemma (in idom_char_0) order_root2: \"poly p \\<noteq> poly [] \\<Longrightarrow> poly p a = 0 \\<longleftrightarrow> order a p \\<noteq> 0\"\n  by (rule order_root [THEN ssubst]) auto\n\nlemma (in semiring_1) pmult_one[simp]: \"[1] *** p = p\" by auto\n\nlemma (in semiring_0) poly_Nil_zero: \"poly [] = poly [0]\"\n  by (simp add: fun_eq)\n\nlemma (in idom_char_0) rsquarefree_decomp:\n  \"rsquarefree p \\<Longrightarrow> poly p a = 0 \\<Longrightarrow>\n    \\<exists>q. poly p = poly ([-a, 1] *** q) \\<and> poly q a \\<noteq> 0\"\n  apply (simp add: rsquarefree_def, safe)\n  apply (frule_tac a = a in order_decomp)\n  apply (drule_tac x = a in spec)\n  apply (drule_tac a = a in order_root2 [symmetric])\n  apply (auto simp del: pmult_Cons)\n  apply (rule_tac x = q in exI, safe)\n  apply (simp add: poly_mult fun_eq)\n  apply (drule_tac p1 = q in poly_linear_divides [THEN iffD1])\n  apply (simp add: divides_def del: pmult_Cons, safe)\n  apply (drule_tac x = \"[]\" in spec)\n  apply (auto simp add: fun_eq)\n  done\n\n\ntext{*Normalization of a polynomial.*}\n\nlemma (in semiring_0) poly_normalize[simp]: \"poly (pnormalize p) = poly p\"\n  by (induct p) (auto simp add: fun_eq)\n\ntext{*The degree of a polynomial.*}\n\nlemma (in semiring_0) lemma_degree_zero: \"list_all (%c. c = 0) p \\<longleftrightarrow> pnormalize p = []\"\n  by (induct p) auto\n\nlemma (in idom_char_0) degree_zero:\n  assumes \"poly p = poly []\"\n  shows \"degree p = 0\"\n  using assms\n  by (cases \"pnormalize p = []\") (auto simp add: degree_def poly_zero lemma_degree_zero)\n\nlemma (in semiring_0) pnormalize_sing: \"(pnormalize [x] = [x]) \\<longleftrightarrow> x \\<noteq> 0\"\n  by simp\n\nlemma (in semiring_0) pnormalize_pair: \"y \\<noteq> 0 \\<longleftrightarrow> (pnormalize [x, y] = [x, y])\"\n  by simp\n\nlemma (in semiring_0) pnormal_cons: \"pnormal p \\<Longrightarrow> pnormal (c#p)\"\n  unfolding pnormal_def by simp\n\nlemma (in semiring_0) pnormal_tail: \"p\\<noteq>[] \\<Longrightarrow> pnormal (c#p) \\<Longrightarrow> pnormal p\"\n  unfolding pnormal_def by(auto split: split_if_asm)\n\n\nlemma (in semiring_0) pnormal_last_nonzero: \"pnormal p \\<Longrightarrow> last p \\<noteq> 0\"\n  by (induct p) (simp_all add: pnormal_def split: split_if_asm)\n\nlemma (in semiring_0) pnormal_length: \"pnormal p \\<Longrightarrow> 0 < length p\"\n  unfolding pnormal_def length_greater_0_conv by blast\n\nlemma (in semiring_0) pnormal_last_length: \"0 < length p \\<Longrightarrow> last p \\<noteq> 0 \\<Longrightarrow> pnormal p\"\n  by (induct p) (auto simp: pnormal_def  split: split_if_asm)\n\n\nlemma (in semiring_0) pnormal_id: \"pnormal p \\<longleftrightarrow> 0 < length p \\<and> last p \\<noteq> 0\"\n  using pnormal_last_length pnormal_length pnormal_last_nonzero by blast\n\nlemma (in idom_char_0) poly_Cons_eq:\n  \"poly (c # cs) = poly (d # ds) \\<longleftrightarrow> c = d \\<and> poly cs = poly ds\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume eq: ?lhs\n  hence \"\\<And>x. poly ((c#cs) +++ -- (d#ds)) x = 0\"\n    by (simp only: poly_minus poly_add algebra_simps) (simp add: algebra_simps)\n  hence \"poly ((c#cs) +++ -- (d#ds)) = poly []\" by(simp add: fun_eq_iff)\n  hence \"c = d \\<and> list_all (\\<lambda>x. x=0) ((cs +++ -- ds))\"\n    unfolding poly_zero by (simp add: poly_minus_def algebra_simps)\n  hence \"c = d \\<and> (\\<forall>x. poly (cs +++ -- ds) x = 0)\"\n    unfolding poly_zero[symmetric] by simp\n  then show ?rhs by (simp add: poly_minus poly_add algebra_simps fun_eq_iff)\nnext\n  assume ?rhs\n  then show ?lhs by(simp add:fun_eq_iff)\nqed\n\nlemma (in idom_char_0) pnormalize_unique: \"poly p = poly q \\<Longrightarrow> pnormalize p = pnormalize q\"\nproof (induct q arbitrary: p)\n  case Nil\n  thus ?case by (simp only: poly_zero lemma_degree_zero) simp\nnext\n  case (Cons c cs p)\n  thus ?case\n  proof (induct p)\n    case Nil\n    hence \"poly [] = poly (c#cs)\" by blast\n    then have \"poly (c#cs) = poly [] \" by simp\n    thus ?case by (simp only: poly_zero lemma_degree_zero) simp\n  next\n    case (Cons d ds)\n    hence eq: \"poly (d # ds) = poly (c # cs)\" by blast\n    hence eq': \"\\<And>x. poly (d # ds) x = poly (c # cs) x\" by simp\n    hence \"poly (d # ds) 0 = poly (c # cs) 0\" by blast\n    hence dc: \"d = c\" by auto\n    with eq have \"poly ds = poly cs\"\n      unfolding  poly_Cons_eq by simp\n    with Cons.prems have \"pnormalize ds = pnormalize cs\" by blast\n    with dc show ?case by simp\n  qed\nqed\n\nlemma (in idom_char_0) degree_unique:\n  assumes pq: \"poly p = poly q\"\n  shows \"degree p = degree q\"\n  using pnormalize_unique[OF pq] unfolding degree_def by simp\n\nlemma (in semiring_0) pnormalize_length:\n  \"length (pnormalize p) \\<le> length p\" by (induct p) auto\n\nlemma (in semiring_0) last_linear_mul_lemma:\n  \"last ((a %* p) +++ (x#(b %* p))) = (if p = [] then x else b * last p)\"\n  apply (induct p arbitrary: a x b)\n  apply auto\n  apply (rename_tac a p aa x b)\n  apply (subgoal_tac \"padd (cmult aa p) (times b a # cmult b p) \\<noteq> []\")\n  apply simp\n  apply (induct_tac p)\n  apply auto\n  done\n\nlemma (in semiring_1) last_linear_mul:\n  assumes p: \"p \\<noteq> []\"\n  shows \"last ([a,1] *** p) = last p\"\nproof -\n  from p obtain c cs where cs: \"p = c#cs\" by (cases p) auto\n  from cs have eq: \"[a,1] *** p = (a %* (c#cs)) +++ (0#(1 %* (c#cs)))\"\n    by (simp add: poly_cmult_distr)\n  show ?thesis using cs\n    unfolding eq last_linear_mul_lemma by simp\nqed\n\nlemma (in semiring_0) pnormalize_eq: \"last p \\<noteq> 0 \\<Longrightarrow> pnormalize p = p\"\n  by (induct p) (auto split: split_if_asm)\n\nlemma (in semiring_0) last_pnormalize: \"pnormalize p \\<noteq> [] \\<Longrightarrow> last (pnormalize p) \\<noteq> 0\"\n  by (induct p) auto\n\nlemma (in semiring_0) pnormal_degree: \"last p \\<noteq> 0 \\<Longrightarrow> degree p = length p - 1\"\n  using pnormalize_eq[of p] unfolding degree_def by simp\n\nlemma (in semiring_0) poly_Nil_ext: \"poly [] = (\\<lambda>x. 0)\"\n  by (rule ext) simp\n\nlemma (in idom_char_0) linear_mul_degree:\n  assumes p: \"poly p \\<noteq> poly []\"\n  shows \"degree ([a,1] *** p) = degree p + 1\"\nproof -\n  from p have pnz: \"pnormalize p \\<noteq> []\"\n    unfolding poly_zero lemma_degree_zero .\n\n  from last_linear_mul[OF pnz, of a] last_pnormalize[OF pnz]\n  have l0: \"last ([a, 1] *** pnormalize p) \\<noteq> 0\" by simp\n  from last_pnormalize[OF pnz] last_linear_mul[OF pnz, of a]\n    pnormal_degree[OF l0] pnormal_degree[OF last_pnormalize[OF pnz]] pnz\n\n  have th: \"degree ([a,1] *** pnormalize p) = degree (pnormalize p) + 1\"\n    by simp\n\n  have eqs: \"poly ([a,1] *** pnormalize p) = poly ([a,1] *** p)\"\n    by (rule ext) (simp add: poly_mult poly_add poly_cmult)\n  from degree_unique[OF eqs] th\n  show ?thesis by (simp add: degree_unique[OF poly_normalize])\nqed\n\nlemma (in idom_char_0) linear_pow_mul_degree:\n  \"degree([a,1] %^n *** p) = (if poly p = poly [] then 0 else degree p + n)\"\nproof (induct n arbitrary: a p)\n  case (0 a p)\n  show ?case\n  proof (cases \"poly p = poly []\")\n    case True\n    then show ?thesis\n      using degree_unique[OF True] by (simp add: degree_def)\n  next\n    case False\n    then show ?thesis by (auto simp add: poly_Nil_ext)\n  qed\nnext\n  case (Suc n a p)\n  have eq: \"poly ([a,1] %^(Suc n) *** p) = poly ([a,1] %^ n *** ([a,1] *** p))\"\n    apply (rule ext)\n    apply (simp add: poly_mult poly_add poly_cmult)\n    apply (simp add: ac_simps ac_simps distrib_left)\n    done\n  note deq = degree_unique[OF eq]\n  show ?case\n  proof (cases \"poly p = poly []\")\n    case True\n    with eq have eq': \"poly ([a,1] %^(Suc n) *** p) = poly []\"\n      apply -\n      apply (rule ext)\n      apply (simp add: poly_mult poly_cmult poly_add)\n      done\n    from degree_unique[OF eq'] True show ?thesis\n      by (simp add: degree_def)\n  next\n    case False\n    then have ap: \"poly ([a,1] *** p) \\<noteq> poly []\"\n      using poly_mult_not_eq_poly_Nil unfolding poly_entire by auto\n    have eq: \"poly ([a,1] %^(Suc n) *** p) = poly ([a,1]%^n *** ([a,1] *** p))\"\n      by (rule ext, simp add: poly_mult poly_add poly_exp poly_cmult algebra_simps)\n    from ap have ap': \"(poly ([a,1] *** p) = poly []) = False\"\n      by blast\n    have th0: \"degree ([a,1]%^n *** ([a,1] *** p)) = degree ([a,1] *** p) + n\"\n      apply (simp only: Suc.hyps[of a \"pmult [a,one] p\"] ap')\n      apply simp\n      done\n    from degree_unique[OF eq] ap False th0 linear_mul_degree[OF False, of a]\n    show ?thesis by (auto simp del: poly.simps)\n  qed\nqed\n\nlemma (in idom_char_0) order_degree:\n  assumes p0: \"poly p \\<noteq> poly []\"\n  shows \"order a p \\<le> degree p\"\nproof -\n  from order2[OF p0, unfolded divides_def]\n  obtain q where q: \"poly p = poly ([- a, 1]%^ (order a p) *** q)\" by blast\n  {\n    assume \"poly q = poly []\"\n    with q p0 have False by (simp add: poly_mult poly_entire)\n  }\n  with degree_unique[OF q, unfolded linear_pow_mul_degree] show ?thesis\n    by auto\nqed\n\ntext{*Tidier versions of finiteness of roots.*}\n\nlemma (in idom_char_0) poly_roots_finite_set:\n  \"poly p \\<noteq> poly [] \\<Longrightarrow> finite {x. poly p x = 0}\"\n  unfolding poly_roots_finite .\n\ntext{*bound for polynomial.*}\n\nlemma poly_mono: \"abs(x) \\<le> k \\<Longrightarrow> abs(poly p (x::'a::{linordered_idom})) \\<le> poly (map abs p) k\"\n  apply (induct p)\n  apply auto\n  apply (rename_tac a p)\n  apply (rule_tac y = \"abs a + abs (x * poly p x)\" in order_trans)\n  apply (rule abs_triangle_ineq)\n  apply (auto intro!: mult_mono simp add: abs_mult)\n  done\n\nlemma (in semiring_0) poly_Sing: \"poly [c] x = c\" by simp\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Decision_Procs/Polynomial_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8856314828740729, "lm_q1q2_score": 0.7924537217244946}}
{"text": "(*  Title:      Binomial_Lemmas.thy\n    Author:     Ata Keskin, TU München\n*)\n\nsection \\<open>Lemmas involving the binomial coefficient\\<close>\n\ntext \\<open>In this section, we prove lemmas that use the term for the binomial coefficient @{term choose}.\\<close>\n\ntheory Binomial_Lemmas\n  imports Main\nbegin\n\nlemma choose_mono:\n  assumes \"x \\<le> y\"\n  shows \"x choose n \\<le> y choose n\"\nproof -\n  have \"finite {0..<y}\" by blast\n  with finite_Pow_iff[of \"{0..<y}\"] have finiteness: \"finite {K \\<in> Pow {0..<y}. card K = n}\" by simp\n  from assms have \"Pow {0..<x} \\<subseteq> Pow {0..<y}\" by force\n  then have \"{K \\<in> Pow {0..<x}. card K = n} \\<subseteq> {K \\<in> Pow {0..<y}. card K = n}\" by blast\n  from card_mono[OF finiteness this] show ?thesis unfolding binomial_def .\nqed\n\nlemma choose_row_sum_set:\n  assumes \"finite (\\<Union>F)\"\n  shows \"card {S. S \\<subseteq> \\<Union>F \\<and> card S \\<le> k} = (\\<Sum>i\\<le>k. card (\\<Union> F) choose i)\"\nproof (induction k)\n  case 0\n  from rev_finite_subset[OF assms] have \"S \\<subseteq> \\<Union>F \\<and> card S \\<le> 0 \\<longleftrightarrow> S = {}\" for S by fastforce\n  then show ?case by simp\nnext\n  case (Suc k)\n  let ?FS = \"{S. S \\<subseteq> \\<Union> F \\<and> card S \\<le> Suc k}\"\n  and ?F_Asm = \"{S. S \\<subseteq> \\<Union> F \\<and> card S \\<le> k}\" \n  and ?F_Step = \"{S. S \\<subseteq> \\<Union> F \\<and> card S = Suc k}\"\n\n  from finite_Pow_iff[of \"\\<Union>F\"] assms have finite_Pow_Un_F: \"finite (Pow (\\<Union> F))\" ..\n  have \"?F_Asm \\<subseteq> Pow (\\<Union> F)\" and \"?F_Step \\<subseteq> Pow (\\<Union> F)\" by fast+\n  with rev_finite_subset[OF finite_Pow_Un_F] have finite_F_Asm: \"finite ?F_Asm\" and finite_F_Step: \"finite ?F_Step\" by presburger+\n\n  have F_Un: \"?FS = ?F_Asm \\<union> ?F_Step\"  and F_disjoint: \"?F_Asm \\<inter> ?F_Step = {}\" by fastforce+\n  from card_Un_disjoint[OF finite_F_Asm finite_F_Step F_disjoint] F_Un have \"card ?FS = card ?F_Asm + card ?F_Step\" by argo\n  also from Suc have \"... = (\\<Sum>i\\<le>k. card (\\<Union> F) choose i) + card ?F_Step\" by argo\n  also from n_subsets[OF assms, of \"Suc k\"] have \"... = (\\<Sum>i\\<le>Suc k. card (\\<Union> F) choose i)\" by force\n  finally show ?case by blast\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Sauer_Shelah_Lemma/Binomial_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8947894618940992, "lm_q1q2_score": 0.7924537206984016}}
{"text": "(*  \n  Title:    Set_Permutations.thy\n  Author:   Manuel Eberl, TU München\n\n  The set of permutations of a finite set, i.e. the set of all \n  lists that contain every element of the set once.\n*)\n\nsection \\<open>Set Permutations\\<close>\n\ntheory Set_Permutations\nimports \n  Complex_Main\n  \"~~/src/HOL/Library/Disjoint_Sets\"\n  \"~~/src/HOL/Library/Permutations\"\nbegin\n\n(* TODO: Move? *)\nlemma UN_cong: \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x) \\<Longrightarrow> UNION A f = UNION B g\"\n  by auto\n\nlemma list_bind_cong [fundef_cong]:\n  \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> f x = g x) \\<Longrightarrow> List.bind xs f = List.bind xs g\"\n  by (induction xs) simp_all\n\nlemma set_list_bind: \"set (List.bind xs f) = (\\<Union>x\\<in>set xs. set (f x))\"\n  by (induction xs) simp_all\n\nlemma distinct_list_bind: \n  assumes \"distinct xs\" \"\\<And>x. x \\<in> set xs \\<Longrightarrow> distinct (f x)\" \n          \"disjoint_family_on (set \\<circ> f) (set xs)\"\n  shows   \"distinct (List.bind xs f)\"\n  using assms\n  by (induction xs)\n     (auto simp: disjoint_family_on_def distinct_map inj_on_def set_list_bind)\n\nlemma permutes_inj_on: \"\\<sigma> permutes A \\<Longrightarrow> inj_on \\<sigma> B\"\n  by (drule permutes_inj) (unfold inj_on_def, blast)\n\nlemma remove_induct [case_names empty infinite remove]:\n  \"P ({} :: 'a set) \\<Longrightarrow> (\\<And>A. infinite A \\<Longrightarrow> P A) \\<Longrightarrow> (\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow>\n     (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A) \\<Longrightarrow> P a0\"\nproof (induction_schema)\n  fix A and x :: 'a assume \"finite A\" \"x \\<in> A\" \"A \\<noteq> {}\"\n  moreover from this have \"card A > 0\" by (simp add: card_gt_0_iff)\n  ultimately show \"(A - {x}, A) \\<in> Wellfounded.measure card\" by simp\nqed auto\n\nlemma finite_remove_induct [consumes 1, case_names empty remove]:\n  \"finite a0 \\<Longrightarrow> P {} \\<Longrightarrow> (\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow>\n     (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A) \\<Longrightarrow> P a0\"\n  by (induction a0 rule: remove_induct) simp_all\n\n(* END TODO *)\n\n\nsubsection \\<open>Definition and general facts\\<close>\n\ndefinition permutations_of_set :: \"'a set \\<Rightarrow> 'a list set\" where\n  \"permutations_of_set A = {xs. set xs = A \\<and> distinct xs}\"\n\nlemma permutations_of_setI [intro]:\n  assumes \"set xs = A\" \"distinct xs\"\n  shows   \"xs \\<in> permutations_of_set A\"\n  using assms unfolding permutations_of_set_def by simp\n  \nlemma permutations_of_setD:\n  assumes \"xs \\<in> permutations_of_set A\"\n  shows   \"set xs = A\" \"distinct xs\"\n  using assms unfolding permutations_of_set_def by simp_all\n  \nlemma permutations_of_set_lists: \"permutations_of_set A \\<subseteq> lists A\"\n  unfolding permutations_of_set_def by auto\n\nlemma permutations_of_set_empty [simp]: \"permutations_of_set {} = {[]}\"\n  by (auto simp: permutations_of_set_def)\n  \nlemma UN_set_permutations_of_set [simp]:\n  \"finite A \\<Longrightarrow> (\\<Union>xs\\<in>permutations_of_set A. set xs) = A\"\n  using finite_distinct_list by (auto simp: permutations_of_set_def)\n\nlemma permutations_of_set_nonempty:\n  assumes \"A \\<noteq> {}\"\n  shows \"permutations_of_set A = \n           (\\<Union>x\\<in>A. (\\<lambda>xs. x # xs) ` permutations_of_set (A - {x}))\" (is \"?lhs = ?rhs\")\nproof (intro equalityI subsetI)\n  fix ys assume ys: \"ys \\<in> permutations_of_set A\"\n  with assms have \"ys \\<noteq> []\" by (auto simp: permutations_of_set_def)\n  then obtain x xs where xs: \"ys = x # xs\" by (cases ys) simp_all\n  from xs ys have \"x \\<in> A\" \"xs \\<in> permutations_of_set (A - {x})\"\n    by (auto simp: permutations_of_set_def)\n  with xs show \"ys \\<in> ?rhs\" by auto\nnext\n  fix ys assume ys: \"ys \\<in> ?rhs\"\n  then obtain x xs where xs: \"ys = x # xs\" \"x \\<in> A\" \"xs \\<in> permutations_of_set (A - {x})\"\n    by auto\n  with ys show \"ys \\<in> ?lhs\" by (auto simp: permutations_of_set_def)\nqed\n\nlemma permutations_of_set_singleton [simp]: \"permutations_of_set {x} = {[x]}\"\n  by (subst permutations_of_set_nonempty) auto\n\nlemma permutations_of_set_doubleton: \n  \"x \\<noteq> y \\<Longrightarrow> permutations_of_set {x,y} = {[x,y], [y,x]}\"\n  by (subst permutations_of_set_nonempty) \n     (simp_all add: insert_Diff_if insert_commute)\n\nlemma rev_permutations_of_set [simp]:\n  \"rev ` permutations_of_set A = permutations_of_set A\"\nproof\n  have \"rev ` rev ` permutations_of_set A \\<subseteq> rev ` permutations_of_set A\"\n    unfolding permutations_of_set_def by auto\n  also have \"rev ` rev ` permutations_of_set A = permutations_of_set A\"\n    by (simp add: image_image)\n  finally show \"permutations_of_set A \\<subseteq> rev ` permutations_of_set A\" .\nnext\n  show \"rev ` permutations_of_set A \\<subseteq> permutations_of_set A\"\n    unfolding permutations_of_set_def by auto\nqed\n\nlemma length_finite_permutations_of_set:\n  \"xs \\<in> permutations_of_set A \\<Longrightarrow> length xs = card A\"\n  by (auto simp: permutations_of_set_def distinct_card)\n\nlemma permutations_of_set_infinite:\n  \"\\<not>finite A \\<Longrightarrow> permutations_of_set A = {}\"\n  by (auto simp: permutations_of_set_def)\n\nlemma finite_permutations_of_set [simp]: \"finite (permutations_of_set A)\"\nproof (cases \"finite A\")\n  assume fin: \"finite A\"\n  have \"permutations_of_set A \\<subseteq> {xs. set xs \\<subseteq> A \\<and> length xs = card A}\"\n    unfolding permutations_of_set_def by (auto simp: distinct_card)\n  moreover from fin have \"finite \\<dots>\" using finite_lists_length_eq by blast\n  ultimately show ?thesis by (rule finite_subset)\nqed (simp_all add: permutations_of_set_infinite)\n\nlemma permutations_of_set_empty_iff [simp]:\n  \"permutations_of_set A = {} \\<longleftrightarrow> \\<not>finite A\"\n  unfolding permutations_of_set_def using finite_distinct_list[of A] by auto\n\nlemma card_permutations_of_set [simp]:\n  \"finite A \\<Longrightarrow> card (permutations_of_set A) = fact (card A)\"\nproof (induction A rule: finite_remove_induct)\n  case (remove A)\n  hence \"card (permutations_of_set A) = \n           card (\\<Union>x\\<in>A. op # x ` permutations_of_set (A - {x}))\"\n    by (simp add: permutations_of_set_nonempty)\n  also from remove.hyps have \"\\<dots> = (\\<Sum>i\\<in>A. card (op # i ` permutations_of_set (A - {i})))\"\n    by (intro card_UN_disjoint) auto\n  also have \"\\<dots> = (\\<Sum>i\\<in>A. card (permutations_of_set (A - {i})))\"\n    by (intro setsum.cong) (simp_all add: card_image)\n  also from remove have \"\\<dots> = card A * fact (card A - 1)\" by simp\n  also from remove.hyps have \"\\<dots> = fact (card A)\"\n    by (cases \"card A\") simp_all\n  finally show ?case .\nqed simp_all\n\nlemma permutations_of_set_image_inj:\n  assumes inj: \"inj_on f A\"\n  shows   \"permutations_of_set (f ` A) = map f ` permutations_of_set A\"\nproof (cases \"finite A\")\n  assume \"\\<not>finite A\"\n  with inj show ?thesis\n    by (auto simp add: permutations_of_set_infinite dest: finite_imageD)\nnext\n  assume finite: \"finite A\"\n  show ?thesis\n  proof (rule sym, rule card_seteq)\n    from inj show \"map f ` permutations_of_set A \\<subseteq> permutations_of_set (f ` A)\" \n      by (auto simp: permutations_of_set_def distinct_map)\n  \n    from inj have \"card (map f ` permutations_of_set A) = card (permutations_of_set A)\"\n      by (intro card_image inj_on_mapI) (auto simp: permutations_of_set_def)\n    also from finite inj have \"\\<dots> = card (permutations_of_set (f ` A))\" \n      by (simp add: card_image)\n    finally show \"card (permutations_of_set (f ` A)) \\<le>\n                    card (map f ` permutations_of_set A)\" by simp\n  qed simp_all\nqed\n\nlemma permutations_of_set_image_permutes:\n  \"\\<sigma> permutes A \\<Longrightarrow> map \\<sigma> ` permutations_of_set A = permutations_of_set A\"\n  by (subst permutations_of_set_image_inj [symmetric])\n     (simp_all add: assms permutes_inj_on permutes_image)\n\n\nsubsection \\<open>Code generation\\<close>\n\ntext \\<open>\n  We define an auxiliary version with an accumulator to avoid\n  having to map over the results.\n\\<close>\nfunction permutations_of_set_aux where\n  \"permutations_of_set_aux acc A = \n     (if \\<not>finite A then {} else if A = {} then {acc} else \n        (\\<Union>x\\<in>A. permutations_of_set_aux (x#acc) (A - {x})))\"\nby auto\ntermination by (relation \"Wellfounded.measure (card \\<circ> snd)\") (simp_all add: card_gt_0_iff)\n\nlemma permutations_of_set_aux_altdef:\n  \"permutations_of_set_aux acc A = (\\<lambda>xs. rev xs @ acc) ` permutations_of_set A\"\nproof (cases \"finite A\")\n  assume \"finite A\"\n  thus ?thesis\n  proof (induction A arbitrary: acc rule: finite_psubset_induct)\n    case (psubset A acc)\n    show ?case\n    proof (cases \"A = {}\")\n      case False\n      note [simp del] = permutations_of_set_aux.simps\n      from psubset.hyps False \n        have \"permutations_of_set_aux acc A = \n                (\\<Union>y\\<in>A. permutations_of_set_aux (y#acc) (A - {y}))\"\n        by (subst permutations_of_set_aux.simps) simp_all\n      also have \"\\<dots> = (\\<Union>y\\<in>A. (\\<lambda>xs. rev xs @ acc) ` (\\<lambda>xs. y # xs) ` permutations_of_set (A - {y}))\"\n        by (intro UN_cong refl, subst psubset) (auto simp: image_image)\n      also from False have \"\\<dots> = (\\<lambda>xs. rev xs @ acc) ` permutations_of_set A\"\n        by (subst (2) permutations_of_set_nonempty) (simp_all add: image_UN)\n      finally show ?thesis .\n    qed simp_all\n  qed\nqed (simp_all add: permutations_of_set_infinite)\n\ndeclare permutations_of_set_aux.simps [simp del]\n\nlemma permutations_of_set_aux_correct:\n  \"permutations_of_set_aux [] A = permutations_of_set A\"\n  by (simp add: permutations_of_set_aux_altdef)\n\n\ntext \\<open>\n  In another refinement step, we define a version on lists.\n\\<close>\ndeclare length_remove1 [termination_simp]\n\nfun permutations_of_set_aux_list where\n  \"permutations_of_set_aux_list acc xs = \n     (if xs = [] then [acc] else \n        List.bind xs (\\<lambda>x. permutations_of_set_aux_list (x#acc) (List.remove1 x xs)))\"\n\ndefinition permutations_of_set_list where\n  \"permutations_of_set_list xs = permutations_of_set_aux_list [] xs\"\n\ndeclare permutations_of_set_aux_list.simps [simp del]\n\nlemma permutations_of_set_aux_list_refine:\n  assumes \"distinct xs\"\n  shows   \"set (permutations_of_set_aux_list acc xs) = permutations_of_set_aux acc (set xs)\"\n  using assms\n  by (induction acc xs rule: permutations_of_set_aux_list.induct)\n     (subst permutations_of_set_aux_list.simps,\n      subst permutations_of_set_aux.simps,\n      simp_all add: set_list_bind cong: UN_cong)\n\n\ntext \\<open>\n  The permutation lists contain no duplicates if the inputs contain no duplicates.\n  Therefore, these functions can easily be used when working with a representation of\n  sets by distinct lists.\n  The same approach should generalise to any kind of set implementation that supports\n  a monadic bind operation, and since the results are disjoint, merging should be cheap.\n\\<close>\nlemma distinct_permutations_of_set_aux_list:\n  \"distinct xs \\<Longrightarrow> distinct (permutations_of_set_aux_list acc xs)\"\n  by (induction acc xs rule: permutations_of_set_aux_list.induct)\n     (subst permutations_of_set_aux_list.simps,\n      auto intro!: distinct_list_bind simp: disjoint_family_on_def \n         permutations_of_set_aux_list_refine permutations_of_set_aux_altdef)\n\nlemma distinct_permutations_of_set_list:\n    \"distinct xs \\<Longrightarrow> distinct (permutations_of_set_list xs)\"\n  by (simp add: permutations_of_set_list_def distinct_permutations_of_set_aux_list)\n\nlemma permutations_of_list:\n    \"permutations_of_set (set xs) = set (permutations_of_set_list (remdups xs))\"\n  by (simp add: permutations_of_set_aux_correct [symmetric] \n        permutations_of_set_aux_list_refine permutations_of_set_list_def)\n\nlemma permutations_of_list_code [code]:\n  \"permutations_of_set (set xs) = set (permutations_of_set_list (remdups xs))\"\n  \"permutations_of_set (List.coset xs) = \n     Code.abort (STR ''Permutation of set complement not supported'') \n       (\\<lambda>_. permutations_of_set (List.coset xs))\"\n  by (simp_all add: permutations_of_list)\n\nvalue [code] \"permutations_of_set (set ''abcd'')\"\n\nend", "meta": {"author": "pruvisto", "repo": "SDS", "sha": "e0b280bff615c917314285b374d77416c51ed39c", "save_path": "github-repos/isabelle/pruvisto-SDS", "path": "github-repos/isabelle/pruvisto-SDS/SDS-e0b280bff615c917314285b374d77416c51ed39c/thys/Randomised_Social_Choice/Set_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.7923214198805774}}
{"text": "(*  Title:      HOL/Isar_Examples/Group.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Basic group theory\\<close>\n\ntheory Group\n  imports Main\nbegin\n\nsubsection \\<open>Groups and calculational reasoning\\<close> \n\ntext \\<open>\n  Groups over signature \\<open>(* :: \\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> \\<alpha>, 1 :: \\<alpha>, inverse :: \\<alpha> \\<Rightarrow> \\<alpha>)\\<close> are\n  defined as an axiomatic type class as follows. Note that the parent classes\n  \\<^class>\\<open>times\\<close>, \\<^class>\\<open>one\\<close>, \\<^class>\\<open>inverse\\<close> is provided by the basic HOL theory.\n\\<close>\n\nclass group = times + one + inverse +\n  assumes group_assoc: \"(x * y) * z = x * (y * z)\"\n    and group_left_one: \"1 * x = x\"\n    and group_left_inverse: \"inverse x * x = 1\"\n\ntext \\<open>\n  The group axioms only state the properties of left one and inverse, the\n  right versions may be derived as follows.\n\\<close>\n\ntheorem (in group) group_right_inverse: \"x * inverse x = 1\"\nproof -\n  have \"x * inverse x = 1 * (x * inverse x)\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1 * x * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x * x * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (inverse x * x) * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * 1 * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (1 * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1\"\n    by (simp only: group_left_inverse)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  With \\<open>group_right_inverse\\<close> already available, \\<open>group_right_one\\<close>\n  is now established much easier.\n\\<close>\n\ntheorem (in group) group_right_one: \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  \\<^medskip>\n  The calculational proof style above follows typical presentations given in\n  any introductory course on algebra. The basic technique is to form a\n  transitive chain of equations, which in turn are established by simplifying\n  with appropriate rules. The low-level logical details of equational\n  reasoning are left implicit.\n\n  Note that ``\\<open>\\<dots>\\<close>'' is just a special term variable that is bound\n  automatically to the argument\\<^footnote>\\<open>The argument of a curried infix expression\n  happens to be its right-hand side.\\<close> of the last fact achieved by any local\n  assumption or proven statement. In contrast to \\<open>?thesis\\<close>, the ``\\<open>\\<dots>\\<close>''\n  variable is bound \\<^emph>\\<open>after\\<close> the proof is finished.\n\n  There are only two separate Isar language elements for calculational proofs:\n  ``\\<^theory_text>\\<open>also\\<close>'' for initial or intermediate calculational steps, and\n  ``\\<^theory_text>\\<open>finally\\<close>'' for exhibiting the result of a calculation. These constructs\n  are not hardwired into Isabelle/Isar, but defined on top of the basic\n  Isar/VM interpreter. Expanding the \\<^theory_text>\\<open>also\\<close> and \\<^theory_text>\\<open>finally\\<close> derived language\n  elements, calculations may be simulated by hand as demonstrated below.\n\\<close>\n\ntheorem (in group) \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n\n  note calculation = this\n    \\<comment> \\<open>first calculational step: init calculation register\\<close>\n\n  have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>final calculational step: compose with transitivity rule \\dots\\<close>\n  from calculation\n    \\<comment> \\<open>\\dots\\ and pick up the final result\\<close>\n\n  show ?thesis .\nqed\n\ntext \\<open>\n  Note that this scheme of calculations is not restricted to plain\n  transitivity. Rules like anti-symmetry, or even forward and backward\n  substitution work as well. For the actual implementation of \\<^theory_text>\\<open>also\\<close> and\n  \\<^theory_text>\\<open>finally\\<close>, Isabelle/Isar maintains separate context information of\n  ``transitivity'' rules. Rule selection takes place automatically by\n  higher-order unification.\n\\<close>\n\n\nsubsection \\<open>Groups as monoids\\<close>\n\ntext \\<open>\n  Monoids over signature \\<open>(* :: \\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> \\<alpha>, 1 :: \\<alpha>)\\<close> are defined like this.\n\\<close>\n\nclass monoid = times + one +\n  assumes monoid_assoc: \"(x * y) * z = x * (y * z)\"\n    and monoid_left_one: \"1 * x = x\"\n    and monoid_right_one: \"x * 1 = x\"\n\ntext \\<open>\n  Groups are \\<^emph>\\<open>not\\<close> yet monoids directly from the definition. For monoids,\n  \\<open>right_one\\<close> had to be included as an axiom, but for groups both \\<open>right_one\\<close>\n  and \\<open>right_inverse\\<close> are derivable from the other axioms. With\n  \\<open>group_right_one\\<close> derived as a theorem of group theory (see @{thm\n  group_right_one}), we may still instantiate \\<open>group \\<subseteq> monoid\\<close> properly as\n  follows.\n\\<close>\n\ninstance group \\<subseteq> monoid\n  by intro_classes\n    (rule group_assoc,\n      rule group_left_one,\n      rule group_right_one)\n\ntext \\<open>\n  The \\<^theory_text>\\<open>instance\\<close> command actually is a version of \\<^theory_text>\\<open>theorem\\<close>, setting up a\n  goal that reflects the intended class relation (or type constructor arity).\n  Thus any Isar proof language element may be involved to establish this\n  statement. When concluding the proof, the result is transformed into the\n  intended type signature extension behind the scenes.\n\\<close>\n\n\nsubsection \\<open>More theorems of group theory\\<close>\n\ntext \\<open>\n  The one element is already uniquely determined by preserving an \\<^emph>\\<open>arbitrary\\<close>\n  group element.\n\\<close>\n\ntheorem (in group) group_one_equality:\n  assumes eq: \"e * x = x\"\n  shows \"1 = e\"\nproof -\n  have \"1 = x * inverse x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = (e * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = e * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = e * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Likewise, the inverse is already determined by the cancel property.\n\\<close>\n\ntheorem (in group) group_inverse_equality:\n  assumes eq: \"x' * x = 1\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = 1 * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = (x' * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = x' * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = x' * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The inverse operation has some further characteristic properties.\n\\<close>\n\ntheorem (in group) group_inverse_times: \"inverse (x * y) = inverse y * inverse x\"\nproof (rule group_inverse_equality)\n  show \"(inverse y * inverse x) * (x * y) = 1\"\n  proof -\n    have \"(inverse y * inverse x) * (x * y) =\n        (inverse y * (inverse x * x)) * y\"\n      by (simp only: group_assoc)\n    also have \"\\<dots> = (inverse y * 1) * y\"\n      by (simp only: group_left_inverse)\n    also have \"\\<dots> = inverse y * y\"\n      by (simp only: group_right_one)\n    also have \"\\<dots> = 1\"\n      by (simp only: group_left_inverse)\n    finally show ?thesis .\n  qed\nqed\n\ntheorem (in group) inverse_inverse: \"inverse (inverse x) = x\"\nproof (rule group_inverse_equality)\n  show \"x * inverse x = one\"\n    by (simp only: group_right_inverse)\nqed\n\ntheorem (in group) inverse_inject:\n  assumes eq: \"inverse x = inverse y\"\n  shows \"x = y\"\nproof -\n  have \"x = x * 1\"\n    by (simp only: group_right_one)\n  also have \"\\<dots> = x * (inverse y * y)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * (inverse x * y)\"\n    by (simp only: eq)\n  also have \"\\<dots> = (x * inverse x) * y\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * y\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = y\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Isar_Examples/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8840392725805822, "lm_q1q2_score": 0.792321419303848}}
{"text": "theorem sqrt2_not_rational:\n\"sqrt 2 ∉ Q\"\nproof\nlet ?x = \"sqrt 2\"\nassume \"?x ∈ Q\"\nthen obtain m n :: nat where\nsqrt_rat: \"¦?x¦ = m / n\" and lowest_terms: \"coprime m n\"\nby (rule Rats_abs_nat_div_natE)\nhence \"m^2 = ?x^2 * n^2\" by (auto simp add: power2_eq_square)\nhence eq: \"m^2 = 2 * n^2\" using of_nat_eq_iff power2_eq_square by fastforce\nhence \"2 dvd m^2\" by simp\nhence \"2 dvd m\" by simp\nhave \"2 dvd n\" proof -\nfrom ‹2 dvd m› obtain k where \"m = 2 * k\" ..\nwith eq have \"2 * n^2 = 2^2 * k^2\" by simp\nhence \"2 dvd n^2\" by simp\nthus \"2 dvd n\" by simp\nqed\nwith ‹2 dvd m› have \"2 dvd gcd m n\" by (rule gcd_greatest)\nwith lowest_terms have \"2 dvd 1\" by simp\nthus False using odd_one by blast\nqed\n(* End of Isabelle syntax identification sample *)\n\n(* Project language file 1\nFor: seanpm2001/Learn-Isabelle\nAbout:\nI chose Isabelle as the first project language file for this project (Seanpm2001/Learn-Isabelle) as this project is about learning th Isabelle programming language, and showing my knowledge for the language. Its project language file should represent what language is being showcased and studied here.\n*)\n\n(* File info\nFile type: Isabelle source file (*.thy)\nFile version: 1 (2022, Thursday, April 21st at 6:56 pm PST)\nLine count (including blank lines and compiler line): 36\n*)\n", "meta": {"author": "seanpm2001", "repo": "Learn-Isabelle", "sha": "9ae6d313c067633d085781b4f9f8f59f55962081", "save_path": "github-repos/isabelle/seanpm2001-Learn-Isabelle", "path": "github-repos/isabelle/seanpm2001-Learn-Isabelle/Learn-Isabelle-9ae6d313c067633d085781b4f9f8f59f55962081/PROJECT_LANG_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7921625579453665}}
{"text": "(*\n  File:   Master_Theorem_Examples.thy\n  Author: Manuel Eberl <eberlm@in.tum.de>\n\n  Examples for the application of the Master theorem and related proof methods.\n*)\n\nsection \\<open>Examples\\<close>\ntheory Master_Theorem_Examples\nimports\n  Complex_Main\n  Akra_Bazzi_Method\n  Akra_Bazzi_Approximation\nbegin\n\nsubsection \\<open>Merge sort\\<close>\n\n(* A merge sort cost function that is parametrised with the recombination costs *)\nfunction merge_sort_cost :: \"(nat \\<Rightarrow> real) \\<Rightarrow> nat \\<Rightarrow> real\" where\n  \"merge_sort_cost t 0 = 0\"\n| \"merge_sort_cost t 1 = 1\"\n| \"n \\<ge> 2 \\<Longrightarrow> merge_sort_cost t n = \n     merge_sort_cost t (nat \\<lfloor>real n / 2\\<rfloor>) + merge_sort_cost t (nat \\<lceil>real n / 2\\<rceil>) + t n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma merge_sort_nonneg[simp]: \"(\\<And>n. t n \\<ge> 0) \\<Longrightarrow> merge_sort_cost t x \\<ge> 0\"\n  by (induction t x rule: merge_sort_cost.induct) (simp_all del: One_nat_def)\n\nlemma \"t \\<in> \\<Theta>(\\<lambda>n. real n) \\<Longrightarrow> (\\<And>n. t n \\<ge> 0) \\<Longrightarrow> merge_sort_cost t \\<in> \\<Theta>(\\<lambda>n. real n * ln (real n))\"\n  by (master_theorem 2.3) simp_all\n\nsubsection \\<open>Karatsuba multiplication\\<close>\n\nfunction karatsuba_cost :: \"nat \\<Rightarrow> real\" where\n  \"karatsuba_cost 0 = 0\"\n| \"karatsuba_cost 1 = 1\"\n| \"n \\<ge> 2 \\<Longrightarrow> karatsuba_cost n = \n     3 * karatsuba_cost (nat \\<lceil>real n / 2\\<rceil>) + real n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma karatsuba_cost_nonneg[simp]: \"karatsuba_cost n \\<ge> 0\"\n  by (induction n rule: karatsuba_cost.induct) (simp_all del: One_nat_def)\n\nlemma \"karatsuba_cost \\<in> O(\\<lambda>n. real n powr log 2 3)\"\n   by (master_theorem 1 p': 1) (simp_all add: powr_divide)\n\nlemma karatsuba_cost_pos: \"n \\<ge> 1 \\<Longrightarrow> karatsuba_cost n > 0\"\n  by (induction n rule: karatsuba_cost.induct) (auto intro!: add_nonneg_pos simp del: One_nat_def)\n\nlemma \"karatsuba_cost \\<in> \\<Theta>(\\<lambda>n. real n powr log 2 3)\"\n  using karatsuba_cost_pos\n  by (master_theorem 1 p': 1) (auto simp add: powr_divide eventually_at_top_linorder)\n\n\nsubsection \\<open>Strassen matrix multiplication\\<close>\n\nfunction strassen_cost :: \"nat \\<Rightarrow> real\" where\n  \"strassen_cost 0 = 0\"\n| \"strassen_cost 1 = 1\"\n| \"n \\<ge> 2 \\<Longrightarrow> strassen_cost n = 7 * strassen_cost (nat \\<lceil>real n / 2\\<rceil>) + real (n^2)\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma strassen_cost_nonneg[simp]: \"strassen_cost n \\<ge> 0\"\n  by (induction n rule: strassen_cost.induct) (simp_all del: One_nat_def)\n\nlemma \"strassen_cost \\<in> O(\\<lambda>n. real n powr log 2 7)\"\n  by (master_theorem 1 p': 2) (auto simp: powr_divide eventually_at_top_linorder)\n\nlemma strassen_cost_pos: \"n \\<ge> 1 \\<Longrightarrow> strassen_cost n > 0\"\n  by (cases n rule: strassen_cost.cases) (simp_all add: add_nonneg_pos del: One_nat_def)\n\nlemma \"strassen_cost \\<in> \\<Theta>(\\<lambda>n. real n powr log 2 7)\"\n  using strassen_cost_pos\n  by (master_theorem 1 p': 2) (auto simp: powr_divide eventually_at_top_linorder)\n\n\nsubsection \\<open>Deterministic select\\<close>\n\n(* This is not possible with the standard Master theorem from literature *)\nfunction select_cost :: \"nat \\<Rightarrow> real\" where\n  \"n \\<le> 20 \\<Longrightarrow> select_cost n = 0\"\n| \"n > 20 \\<Longrightarrow> select_cost n = \n     select_cost (nat \\<lfloor>real n / 5\\<rfloor>) + select_cost (nat \\<lfloor>7 * real n / 10\\<rfloor> + 6) + 12 * real n / 5\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"select_cost \\<in> \\<Theta>(\\<lambda>n. real n)\"\n  by (master_theorem 3) auto\n\n\nsubsection \\<open>Decreasing function\\<close>\n\nfunction dec_cost :: \"nat \\<Rightarrow> real\" where\n  \"n \\<le> 2 \\<Longrightarrow> dec_cost n = 1\"\n| \"n > 2 \\<Longrightarrow> dec_cost n = 0.5*dec_cost (nat \\<lfloor>real n / 2\\<rfloor>) + 1 / real n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"dec_cost \\<in> \\<Theta>(\\<lambda>x::nat. ln x / x)\"\n  by (master_theorem 2.3) simp_all\n\n\nsubsection \\<open>Example taken from Drmota and Szpakowski\\<close>\n\nfunction drmota1 :: \"nat \\<Rightarrow> real\" where\n  \"n < 20 \\<Longrightarrow> drmota1 n = 1\"\n| \"n \\<ge> 20 \\<Longrightarrow> drmota1 n = 2 * drmota1 (nat \\<lfloor>real n/2\\<rfloor>) + 8/9 * drmota1 (nat \\<lfloor>3*real n/4\\<rfloor>) + real n^2 / ln (real n)\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"drmota1 \\<in> \\<Theta>(\\<lambda>n::real. n^2 * ln (ln n))\"\n  by (master_theorem 2.2) (simp_all add: power_divide)\n\n\nfunction drmota2 :: \"nat \\<Rightarrow> real\" where\n  \"n < 20 \\<Longrightarrow> drmota2 n = 1\"\n| \"n \\<ge> 20 \\<Longrightarrow> drmota2 n = 1/3 * drmota2 (nat \\<lfloor>real n/3 + 1/2\\<rfloor>) + 2/3 * drmota2 (nat \\<lfloor>2*real n/3 - 1/2\\<rfloor>) + 1\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma \"drmota2 \\<in> \\<Theta>(\\<lambda>x. ln (real x))\"\n  by master_theorem simp_all\n\n(* Average phrase length of Boncelet arithmetic coding. See Drmota and Szpankowski. *)\nlemma boncelet_phrase_length:\n  fixes p \\<delta> :: real assumes p: \"p > 0\" \"p < 1\" and \\<delta>: \"\\<delta> > 0\" \"\\<delta> < 1\" \"2*p + \\<delta> < 2\"\n  fixes d :: \"nat \\<Rightarrow> real\"\n  defines \"q \\<equiv> 1 - p\"\n  assumes d_nonneg: \"\\<And>n. d n \\<ge> 0\"\n  assumes d_rec: \"\\<And>n. n \\<ge> 2 \\<Longrightarrow> d n = 1 + p * d (nat \\<lfloor>p * real n + \\<delta>\\<rfloor>) + q * d (nat \\<lfloor>q * real n - \\<delta>\\<rfloor>)\"\n  shows   \"d \\<in> \\<Theta>(\\<lambda>x. ln x)\"\n  using assms by (master_theorem recursion: d_rec, simp_all)\n\n\n\nsubsection \\<open>Transcendental exponents\\<close>\n\n(* Certain number-theoretic conjectures would imply that if all the parameters are rational,\n   the Akra-Bazzi parameter is either rational or transcendental. That makes this case \n   probably transcendental *)\nfunction foo_cost :: \"nat \\<Rightarrow> real\" where\n  \"n < 200 \\<Longrightarrow> foo_cost n = 0\"\n| \"n \\<ge> 200 \\<Longrightarrow> foo_cost n = \n     foo_cost (nat \\<lfloor>real n / 3\\<rfloor>) + foo_cost (nat \\<lfloor>3 * real n / 4\\<rfloor> + 42) + real n\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma foo_cost_nonneg [simp]: \"foo_cost n \\<ge> 0\"\n  by (induction n rule: foo_cost.induct) simp_all\n\nlemma \"foo_cost \\<in> \\<Theta>(\\<lambda>n. real n powr akra_bazzi_exponent [1,1] [1/3,3/4])\"\nproof (master_theorem 1 p': 1) \n  have \"\\<forall>n\\<ge>200. foo_cost n > 0\" by (simp add: add_nonneg_pos)\n  thus \"eventually (\\<lambda>n. foo_cost n > 0) at_top\" unfolding eventually_at_top_linorder by blast\nqed simp_all\n\nlemma \"akra_bazzi_exponent [1,1] [1/3,3/4] \\<in> {1.1519623..1.1519624}\"\n  by (akra_bazzi_approximate 29)\n\n\nsubsection \\<open>Functions in locale contexts\\<close>\n\nlocale det_select =\n  fixes b :: real\n  assumes b: \"b > 0\" \"b < 7/10\"\nbegin\n\nfunction select_cost' :: \"nat \\<Rightarrow> real\" where\n  \"n \\<le> 20 \\<Longrightarrow> select_cost' n = 0\"\n| \"n > 20 \\<Longrightarrow> select_cost' n = \n     select_cost' (nat \\<lfloor>real n / 5\\<rfloor>) + select_cost' (nat \\<lfloor>b * real n\\<rfloor> + 6) + 6 * real n + 5\"\nby force simp_all\ntermination using b by akra_bazzi_termination simp_all\n\nlemma \"a \\<ge> 0 \\<Longrightarrow> select_cost' \\<in> \\<Theta>(\\<lambda>n. real n)\"\n  using b by (master_theorem 3, force+)\n\nend\n\n\nsubsection \\<open>Non-curried functions\\<close>\n\n(* Note: either a or b could be seen as recursion variables. *)\nfunction baz_cost :: \"nat \\<times> nat \\<Rightarrow> real\" where\n  \"n \\<le> 2 \\<Longrightarrow> baz_cost (a, n) = 0\"\n| \"n > 2 \\<Longrightarrow> baz_cost (a, n) = 3 * baz_cost (a, nat \\<lfloor>real n / 2\\<rfloor>) + real a\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma baz_cost_nonneg [simp]: \"a \\<ge> 0 \\<Longrightarrow> baz_cost (a, n) \\<ge> 0\"\n  by (induction a n rule: baz_cost.induct[split_format (complete)]) simp_all\n\nlemma\n  assumes \"a > 0\"\n  shows   \"(\\<lambda>x. baz_cost (a, x)) \\<in> \\<Theta>(\\<lambda>x. x powr log 2 3)\"\nproof (master_theorem 1 p': 0)\n  from assms have \"\\<forall>x\\<ge>3. baz_cost (a, x) > 0\" by (auto intro: add_nonneg_pos)\n  thus \"eventually (\\<lambda>x. baz_cost (a, x) > 0) at_top\" by (force simp: eventually_at_top_linorder)\nqed (insert assms, simp_all add: powr_divide)\n\n(* Non-\"Akra-Bazzi\" variables may even be modified without impacting the termination proof.\n   However, the Akra-Bazzi theorem and the Master theorem itself do not apply anymore, \n   because bar_cost cannot be seen as a recursive function with one parameter *)\nfunction bar_cost :: \"nat \\<times> nat \\<Rightarrow> real\" where\n  \"n \\<le> 2 \\<Longrightarrow> bar_cost (a, n) = 0\"\n| \"n > 2 \\<Longrightarrow> bar_cost (a, n) = 3 * bar_cost (2 * a, nat \\<lfloor>real n / 2\\<rfloor>) + real a\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\n\nsubsection \\<open>Ham-sandwich trees\\<close>\n(* f(n) = f(n/4) + f(n/2) + 1 *)\nfunction ham_sandwich_cost :: \"nat \\<Rightarrow> real\" where\n  \"n < 4 \\<Longrightarrow> ham_sandwich_cost n = 1\"\n| \"n \\<ge> 4 \\<Longrightarrow> ham_sandwich_cost n = \n      ham_sandwich_cost (nat \\<lfloor>n/4\\<rfloor>) + ham_sandwich_cost (nat \\<lfloor>n/2\\<rfloor>) + 1\"\nby force simp_all\ntermination by akra_bazzi_termination simp_all\n\nlemma ham_sandwich_cost_pos [simp]: \"ham_sandwich_cost n > 0\"\n  by (induction n rule: ham_sandwich_cost.induct) simp_all\n\n\ntext \\<open>The golden ratio\\<close>\n\ndefinition \"\\<phi> = ((1 + sqrt 5) / 2 :: real)\"\n\nlemma \\<phi>_pos [simp]: \"\\<phi> > 0\" and \\<phi>_nonneg [simp]: \"\\<phi> \\<ge> 0\" and \\<phi>_nonzero [simp]: \"\\<phi> \\<noteq> 0\"\nproof-\n  show \"\\<phi> > 0\" unfolding \\<phi>_def by (simp add: add_pos_nonneg)\n  thus \"\\<phi> \\<ge> 0\" \"\\<phi> \\<noteq> 0\" by simp_all\nqed\n\n\nlemma \"ham_sandwich_cost \\<in> \\<Theta>(\\<lambda>n. n powr (log 2 \\<phi>))\"\nproof (master_theorem 1 p': 0)\n  have \"(1 / 4) powr log 2 \\<phi> + (1 / 2) powr log 2 \\<phi> =\n            inverse (2 powr log 2 \\<phi>)^2 + inverse (2 powr log 2 \\<phi>)\"\n        by (simp add: powr_divide field_simps powr_powr power2_eq_square powr_mult[symmetric]\n                 del: powr_log_cancel)\n  also have \"... = inverse (\\<phi>^2) + inverse \\<phi>\" by (simp add: power2_eq_square)\n  also have \"\\<phi> + 1 = \\<phi>*\\<phi>\" by (simp add: \\<phi>_def field_simps)\n  hence \"inverse (\\<phi>^2) + inverse \\<phi> = 1\" by (simp add: field_simps power2_eq_square)\n  finally show \"(1 / 4) powr log 2 \\<phi> + (1 / 2) powr log 2 \\<phi> = 1\" by simp\nqed simp_all\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Akra_Bazzi/Master_Theorem_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7921625579453665}}
{"text": "(*  Title:      HOL/Library/Indicator_Function.thy\n    Author:     Johannes Hoelzl (TU Muenchen)\n*)\n\nsection \\<open>Indicator Function\\<close>\n\ntheory Indicator_Function\nimports Complex_Main Disjoint_Sets\nbegin\n\ndefinition \"indicator S x = (if x \\<in> S then 1 else 0)\"\n\ntext\\<open>Type constrained version\\<close>\nabbreviation indicat_real :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> real\" where \"indicat_real S \\<equiv> indicator S\"\n\nlemma indicator_simps[simp]:\n  \"x \\<in> S \\<Longrightarrow> indicator S x = 1\"\n  \"x \\<notin> S \\<Longrightarrow> indicator S x = 0\"\n  unfolding indicator_def by auto\n\nlemma indicator_pos_le[intro, simp]: \"(0::'a::linordered_semidom) \\<le> indicator S x\"\n  and indicator_le_1[intro, simp]: \"indicator S x \\<le> (1::'a::linordered_semidom)\"\n  unfolding indicator_def by auto\n\nlemma indicator_abs_le_1: \"\\<bar>indicator S x\\<bar> \\<le> (1::'a::linordered_idom)\"\n  unfolding indicator_def by auto\n\nlemma indicator_eq_0_iff: \"indicator A x = (0::'a::zero_neq_one) \\<longleftrightarrow> x \\<notin> A\"\n  by (auto simp: indicator_def)\n\nlemma indicator_eq_1_iff: \"indicator A x = (1::'a::zero_neq_one) \\<longleftrightarrow> x \\<in> A\"\n  by (auto simp: indicator_def)\n\nlemma indicator_UNIV [simp]: \"indicator UNIV = (\\<lambda>x. 1)\"\n  by auto\n\nlemma indicator_leI:\n  \"(x \\<in> A \\<Longrightarrow> y \\<in> B) \\<Longrightarrow> (indicator A x :: 'a::linordered_nonzero_semiring) \\<le> indicator B y\"\n  by (auto simp: indicator_def)\n\nlemma split_indicator: \"P (indicator S x) \\<longleftrightarrow> ((x \\<in> S \\<longrightarrow> P 1) \\<and> (x \\<notin> S \\<longrightarrow> P 0))\"\n  unfolding indicator_def by auto\n\nlemma split_indicator_asm: \"P (indicator S x) \\<longleftrightarrow> (\\<not> (x \\<in> S \\<and> \\<not> P 1 \\<or> x \\<notin> S \\<and> \\<not> P 0))\"\n  unfolding indicator_def by auto\n\nlemma indicator_inter_arith: \"indicator (A \\<inter> B) x = indicator A x * (indicator B x::'a::semiring_1)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_union_arith:\n  \"indicator (A \\<union> B) x = indicator A x + indicator B x - indicator A x * (indicator B x :: 'a::ring_1)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_inter_min: \"indicator (A \\<inter> B) x = min (indicator A x) (indicator B x::'a::linordered_semidom)\"\n  and indicator_union_max: \"indicator (A \\<union> B) x = max (indicator A x) (indicator B x::'a::linordered_semidom)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_disj_union:\n  \"A \\<inter> B = {} \\<Longrightarrow> indicator (A \\<union> B) x = (indicator A x + indicator B x :: 'a::linordered_semidom)\"\n  by (auto split: split_indicator)\n\nlemma indicator_compl: \"indicator (- A) x = 1 - (indicator A x :: 'a::ring_1)\"\n  and indicator_diff: \"indicator (A - B) x = indicator A x * (1 - indicator B x ::'a::ring_1)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_times:\n  \"indicator (A \\<times> B) x = indicator A (fst x) * (indicator B (snd x) :: 'a::semiring_1)\"\n  unfolding indicator_def by (cases x) auto\n\nlemma indicator_sum:\n  \"indicator (A <+> B) x = (case x of Inl x \\<Rightarrow> indicator A x | Inr x \\<Rightarrow> indicator B x)\"\n  unfolding indicator_def by (cases x) auto\n\nlemma indicator_image: \"inj f \\<Longrightarrow> indicator (f ` X) (f x) = (indicator X x::_::zero_neq_one)\"\n  by (auto simp: indicator_def inj_def)\n\nlemma indicator_vimage: \"indicator (f -` A) x = indicator A (f x)\"\n  by (auto split: split_indicator)\n\nlemma  (* FIXME unnamed!? *)\n  fixes f :: \"'a \\<Rightarrow> 'b::semiring_1\"\n  assumes \"finite A\"\n  shows sum_mult_indicator[simp]: \"(\\<Sum>x \\<in> A. f x * indicator B x) = (\\<Sum>x \\<in> A \\<inter> B. f x)\"\n    and sum_indicator_mult[simp]: \"(\\<Sum>x \\<in> A. indicator B x * f x) = (\\<Sum>x \\<in> A \\<inter> B. f x)\"\n  unfolding indicator_def\n  using assms by (auto intro!: sum.mono_neutral_cong_right split: if_split_asm)\n\nlemma sum_indicator_eq_card:\n  assumes \"finite A\"\n  shows \"(\\<Sum>x \\<in> A. indicator B x) = card (A Int B)\"\n  using sum_mult_indicator [OF assms, of \"\\<lambda>x. 1::nat\"]\n  unfolding card_eq_sum by simp\n\nlemma sum_indicator_scaleR[simp]:\n  \"finite A \\<Longrightarrow>\n    (\\<Sum>x \\<in> A. indicator (B x) (g x) *\\<^sub>R f x) = (\\<Sum>x \\<in> {x\\<in>A. g x \\<in> B x}. f x :: 'a::real_vector)\"\n  by (auto intro!: sum.mono_neutral_cong_right split: if_split_asm simp: indicator_def)\n\nlemma LIMSEQ_indicator_incseq:\n  assumes \"incseq A\"\n  shows \"(\\<lambda>i. indicator (A i) x :: 'a::{topological_space,one,zero}) \\<longlonglongrightarrow> indicator (\\<Union>i. A i) x\"\nproof (cases \"\\<exists>i. x \\<in> A i\")\n  case True\n  then obtain i where \"x \\<in> A i\"\n    by auto\n  then have *:\n    \"\\<And>n. (indicator (A (n + i)) x :: 'a) = 1\"\n    \"(indicator (\\<Union>i. A i) x :: 'a) = 1\"\n    using incseqD[OF \\<open>incseq A\\<close>, of i \"n + i\" for n] \\<open>x \\<in> A i\\<close> by (auto simp: indicator_def)\n  show ?thesis\n    by (rule LIMSEQ_offset[of _ i]) (use * in simp)\nnext\n  case False\n  then show ?thesis by (simp add: indicator_def)\nqed\n\nlemma LIMSEQ_indicator_UN:\n  \"(\\<lambda>k. indicator (\\<Union>i<k. A i) x :: 'a::{topological_space,one,zero}) \\<longlonglongrightarrow> indicator (\\<Union>i. A i) x\"\nproof -\n  have \"(\\<lambda>k. indicator (\\<Union>i<k. A i) x::'a) \\<longlonglongrightarrow> indicator (\\<Union>k. \\<Union>i<k. A i) x\"\n    by (intro LIMSEQ_indicator_incseq) (auto simp: incseq_def intro: less_le_trans)\n  also have \"(\\<Union>k. \\<Union>i<k. A i) = (\\<Union>i. A i)\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma LIMSEQ_indicator_decseq:\n  assumes \"decseq A\"\n  shows \"(\\<lambda>i. indicator (A i) x :: 'a::{topological_space,one,zero}) \\<longlonglongrightarrow> indicator (\\<Inter>i. A i) x\"\nproof (cases \"\\<exists>i. x \\<notin> A i\")\n  case True\n  then obtain i where \"x \\<notin> A i\"\n    by auto\n  then have *:\n    \"\\<And>n. (indicator (A (n + i)) x :: 'a) = 0\"\n    \"(indicator (\\<Inter>i. A i) x :: 'a) = 0\"\n    using decseqD[OF \\<open>decseq A\\<close>, of i \"n + i\" for n] \\<open>x \\<notin> A i\\<close> by (auto simp: indicator_def)\n  show ?thesis\n    by (rule LIMSEQ_offset[of _ i]) (use * in simp)\nnext\n  case False\n  then show ?thesis by (simp add: indicator_def)\nqed\n\nlemma LIMSEQ_indicator_INT:\n  \"(\\<lambda>k. indicator (\\<Inter>i<k. A i) x :: 'a::{topological_space,one,zero}) \\<longlonglongrightarrow> indicator (\\<Inter>i. A i) x\"\nproof -\n  have \"(\\<lambda>k. indicator (\\<Inter>i<k. A i) x::'a) \\<longlonglongrightarrow> indicator (\\<Inter>k. \\<Inter>i<k. A i) x\"\n    by (intro LIMSEQ_indicator_decseq) (auto simp: decseq_def intro: less_le_trans)\n  also have \"(\\<Inter>k. \\<Inter>i<k. A i) = (\\<Inter>i. A i)\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma indicator_add:\n  \"A \\<inter> B = {} \\<Longrightarrow> (indicator A x::_::monoid_add) + indicator B x = indicator (A \\<union> B) x\"\n  unfolding indicator_def by auto\n\nlemma of_real_indicator: \"of_real (indicator A x) = indicator A x\"\n  by (simp split: split_indicator)\n\nlemma real_of_nat_indicator: \"real (indicator A x :: nat) = indicator A x\"\n  by (simp split: split_indicator)\n\nlemma abs_indicator: \"\\<bar>indicator A x :: 'a::linordered_idom\\<bar> = indicator A x\"\n  by (simp split: split_indicator)\n\nlemma mult_indicator_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> indicator A x * indicator B x = (indicator A x :: 'a::comm_semiring_1)\"\n  by (auto split: split_indicator simp: fun_eq_iff)\n\nlemma indicator_times_eq_if:\n  fixes f :: \"'a \\<Rightarrow> 'b::comm_ring_1\"\n  shows \"indicator S x * f x = (if x \\<in> S then f x else 0)\" \"f x * indicator S x = (if x \\<in> S then f x else 0)\"\n  by auto\n\nlemma indicator_scaleR_eq_if:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_vector\"\n  shows \"indicator S x *\\<^sub>R f x = (if x \\<in> S then f x else 0)\"\n  by simp\n\nlemma indicator_sums:\n  assumes \"\\<And>i j. i \\<noteq> j \\<Longrightarrow> A i \\<inter> A j = {}\"\n  shows \"(\\<lambda>i. indicator (A i) x::real) sums indicator (\\<Union>i. A i) x\"\nproof (cases \"\\<exists>i. x \\<in> A i\")\n  case True\n  then obtain i where i: \"x \\<in> A i\" ..\n  with assms have \"(\\<lambda>i. indicator (A i) x::real) sums (\\<Sum>i\\<in>{i}. indicator (A i) x)\"\n    by (intro sums_finite) (auto split: split_indicator)\n  also have \"(\\<Sum>i\\<in>{i}. indicator (A i) x) = indicator (\\<Union>i. A i) x\"\n    using i by (auto split: split_indicator)\n  finally show ?thesis .\nnext\n  case False\n  then show ?thesis by simp\nqed\n\ntext \\<open>\n  The indicator function of the union of a disjoint family of sets is the\n  sum over all the individual indicators.\n\\<close>\n\nlemma indicator_UN_disjoint:\n  \"finite A \\<Longrightarrow> disjoint_family_on f A \\<Longrightarrow> indicator (\\<Union>(f ` A)) x = (\\<Sum>y\\<in>A. indicator (f y) x)\"\n  by (induct A rule: finite_induct)\n    (auto simp: disjoint_family_on_def indicator_def split: if_splits)\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Library/Indicator_Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8976952845805988, "lm_q1q2_score": 0.7921513319230781}}
{"text": "theory Integral_Test\nimports\n  Complex_Main\n  \"~~/src/HOL/Multivariate_Analysis/Integration\"\nbegin\n\nsubsubsection \\<open>Integral test\\<close>\n\nlocale antimono_fun_sum_integral_diff =\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes dec: \"\\<And>x y. x \\<ge> 0 \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  assumes nonneg: \"\\<And>x. x \\<ge> 0 \\<Longrightarrow> f x \\<ge> 0\"\n  assumes cont: \"continuous_on {0..} f\"\nbegin\n\ndefinition \"sum_integral_diff_series n = (\\<Sum>k\\<le>n. f (of_nat k)) - (integral {0..of_nat n} f)\"\n\nlemma sum_integral_diff_series_nonneg:\n  \"sum_integral_diff_series n \\<ge> 0\"\nproof -\n  note int = integrable_continuous_real[OF continuous_on_subset[OF cont]]\n  let ?int = \"\\<lambda>a b. integral {of_nat a..of_nat b} f\"\n  have \"-sum_integral_diff_series n = ?int 0 n - (\\<Sum>k\\<le>n. f (of_nat k))\" \n    by (simp add: sum_integral_diff_series_def)\n  also have \"?int 0 n = (\\<Sum>k<n. ?int k (Suc k))\"\n  proof (induction n)\n    case (Suc n)\n    have \"?int 0 (Suc n) = ?int 0 n + ?int n (Suc n)\"\n      by (intro integral_combine[symmetric] int) simp_all\n    with Suc show ?case by simp\n  qed simp_all\n  also have \"... \\<le> (\\<Sum>k<n. integral {of_nat k..of_nat (Suc k)} (\\<lambda>_::real. f (of_nat k)))\"\n    by (intro setsum_mono integral_le int) (auto intro: dec)\n  also have \"... = (\\<Sum>k<n. f (of_nat k))\" by simp\n  also have \"\\<dots> - (\\<Sum>k\\<le>n. f (of_nat k)) = -(\\<Sum>k\\<in>{..n} - {..<n}. f (of_nat k))\"\n    by (subst setsum_diff) auto\n  also have \"\\<dots> \\<le> 0\" by (auto intro!: setsum_nonneg nonneg)\n  finally show \"sum_integral_diff_series n \\<ge> 0\" by simp\nqed\n\nlemma sum_integral_diff_series_antimono:\n  assumes \"m \\<le> n\"\n  shows   \"sum_integral_diff_series m \\<ge> sum_integral_diff_series n\"\nproof -\n  let ?int = \"\\<lambda>a b. integral {of_nat a..of_nat b} f\"\n  note int = integrable_continuous_real[OF continuous_on_subset[OF cont]]\n  have d_mono: \"sum_integral_diff_series (Suc n) \\<le> sum_integral_diff_series n\" for n\n  proof -\n    fix n :: nat\n    have \"sum_integral_diff_series (Suc n) - sum_integral_diff_series n = \n            f (of_nat (Suc n)) + (?int 0 n - ?int 0 (Suc n))\"\n      unfolding sum_integral_diff_series_def by (simp add: algebra_simps)\n    also have \"?int 0 n - ?int 0 (Suc n) = -?int n (Suc n)\"\n      by (subst integral_combine [symmetric, of \"of_nat 0\" \"of_nat n\" \"of_nat (Suc n)\"])\n         (auto intro!: int simp: algebra_simps)\n    also have \"?int n (Suc n) \\<ge> integral {of_nat n..of_nat (Suc n)} (\\<lambda>_::real. f (of_nat (Suc n)))\"\n      by (intro integral_le int) (auto intro: dec)\n    hence \"f (of_nat (Suc n)) + -?int n (Suc n) \\<le> 0\" by (simp add: algebra_simps)\n    finally show \"sum_integral_diff_series (Suc n) \\<le> sum_integral_diff_series n\" by simp\n  qed\n  with assms show ?thesis\n    by (induction rule: inc_induct) (auto intro: order.trans[OF _ d_mono])\nqed\n\nlemma sum_integral_diff_series_Bseq: \"Bseq sum_integral_diff_series\"\nproof -\n  from sum_integral_diff_series_nonneg and sum_integral_diff_series_antimono \n    have \"norm (sum_integral_diff_series n) \\<le> sum_integral_diff_series 0\" for n by simp\n  thus \"Bseq sum_integral_diff_series\" by (rule BseqI')\nqed\n\nlemma sum_integral_diff_series_monoseq: \"monoseq sum_integral_diff_series\"\n  using sum_integral_diff_series_antimono unfolding monoseq_def by blast\n\nlemma sum_integral_diff_series_convergent: \"convergent sum_integral_diff_series\"\n  using sum_integral_diff_series_Bseq sum_integral_diff_series_monoseq\n  by (blast intro!: Bseq_monoseq_convergent)\n\nlemma integral_test:\n  \"summable (\\<lambda>n. f (of_nat n)) \\<longleftrightarrow> convergent (\\<lambda>n. integral {0..of_nat n} f)\"\nproof -\n  have \"summable (\\<lambda>n. f (of_nat n)) \\<longleftrightarrow> convergent (\\<lambda>n. \\<Sum>k\\<le>n. f (of_nat k))\"\n    by (simp add: summable_iff_convergent')\n  also have \"... \\<longleftrightarrow> convergent (\\<lambda>n. integral {0..of_nat n} f)\"\n  proof\n    assume \"convergent (\\<lambda>n. \\<Sum>k\\<le>n. f (of_nat k))\"\n    from convergent_diff[OF this sum_integral_diff_series_convergent] \n      show \"convergent (\\<lambda>n. integral {0..of_nat n} f)\" \n        unfolding sum_integral_diff_series_def by simp\n  next\n    assume \"convergent (\\<lambda>n. integral {0..of_nat n} f)\"\n    from convergent_add[OF this sum_integral_diff_series_convergent] \n      show \"convergent (\\<lambda>n. \\<Sum>k\\<le>n. f (of_nat k))\" unfolding sum_integral_diff_series_def by simp\n  qed\n  finally show ?thesis by simp\nqed\n\nend\n\nend", "meta": {"author": "pruvisto", "repo": "isabelle_summation", "sha": "1a93fd20d83fa8fae14c1d89d3535624b6afebbf", "save_path": "github-repos/isabelle/pruvisto-isabelle_summation", "path": "github-repos/isabelle/pruvisto-isabelle_summation/isabelle_summation-1a93fd20d83fa8fae14c1d89d3535624b6afebbf/Integral_Test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.8824278571786139, "lm_q1q2_score": 0.7921513257680027}}
{"text": "section \\<open> Integer Powers \\<close>\n\ntheory Power_int\n  imports \"HOL.Real\"\nbegin\n\ntext \\<open> The standard HOL power operator is only for natural powers. This operator allows integers. \\<close>\n\ndefinition intpow :: \"'a::{linordered_field} \\<Rightarrow> int \\<Rightarrow> 'a\" (infixr \"^\\<^sub>Z\" 80) where\n\"intpow x n = (if (n < 0) then inverse (x ^ nat (-n)) else (x ^ nat n))\"\n\nlemma intpow_zero [simp]: \"x ^\\<^sub>Z 0 = 1\"\n  by (simp add: intpow_def)\n\nlemma intpow_spos [simp]: \"x > 0 \\<Longrightarrow> x ^\\<^sub>Z n > 0\"\n  by (simp add: intpow_def)\n\nlemma intpow_one [simp]: \"x ^\\<^sub>Z 1 = x\"\n  by (simp add: intpow_def)\n\n\n\nlemma intpow_plus: \"x > 0 \\<Longrightarrow> x ^\\<^sub>Z (m + n) = x ^\\<^sub>Z m * x ^\\<^sub>Z n\"\n  apply (simp add: intpow_def field_simps power_add)\n  apply (metis (no_types, opaque_lifting) abs_ge_zero add.commute add_diff_cancel_right' nat_add_distrib power_add uminus_add_conv_diff zabs_def)\n  done\n\nlemma intpow_mult_combine: \"x > 0 \\<Longrightarrow> x ^\\<^sub>Z m * (x ^\\<^sub>Z n * y) = x ^\\<^sub>Z (m + n) * y\"\n  by (simp add: intpow_plus)\n\nlemma intpow_pos [simp]: \"n \\<ge> 0 \\<Longrightarrow> x ^\\<^sub>Z n = x ^ nat n\"\n  by (simp add: intpow_def)\n\nlemma intpow_uminus: \"x ^\\<^sub>Z -n = inverse (x ^\\<^sub>Z n)\"\n  by (simp add: intpow_def)\n\nlemma intpow_uminus_nat: \"n \\<ge> 0 \\<Longrightarrow> x ^\\<^sub>Z -n = inverse (x ^ nat n)\"\n  by (simp add: intpow_def)\n\nlemma intpow_inverse: \"inverse a ^\\<^sub>Z n = inverse (a ^\\<^sub>Z n)\"\n  by (simp add: intpow_def power_inverse)\n\nlemma intpow_mult_distrib: \"(x * y) ^\\<^sub>Z m = x ^\\<^sub>Z m * y ^\\<^sub>Z m\"\n  by (simp add: intpow_def power_mult_distrib)\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Physical_Quantities/Power_int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249611, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7919914229776146}}
{"text": "(*  \n  Title:    Random_Serial_Dictatorship.thy\n  Author:   Manuel Eberl, TU München\n\n  Definition and basic properties of Random Serial Dictatorship\n*)\n\nsection \\<open>Random Serial Dictatorship\\<close>\n\ntheory Random_Serial_Dictatorship\nimports\n  Complex_Main\n  Social_Decision_Schemes\n  Random_Dictatorship\nbegin\n\ntext \\<open>\n  Random Serial Dictatorship is an anonymous, neutral, strongly strategy-proof, \n  and ex-post efficient Social Decision Scheme that extends Random Dictatorship\n  to the domain of weak preferences.\n  \n  We define RSD using a fold over a random permutation. Effectively, we choose a random\n  order of the agents (in the form of a list) and then traverse that list from left to right,\n  where each agent in turn removes all the alternatives that are not top-ranked among the \n  remaining ones.\n\\<close>\ndefinition random_serial_dictatorship :: \n    \"'agent set \\<Rightarrow> 'alt set \\<Rightarrow> ('agent, 'alt) pref_profile \\<Rightarrow> 'alt lottery\" where\n  \"random_serial_dictatorship agents alts R = \n     fold_bind_random_permutation (\\<lambda>i alts. Max_wrt_among (R i) alts) pmf_of_set alts agents\"\n\ntext \\<open>\n  The following two facts correspond give an alternative recursive definition to\n  the above definition, which uses random permutations and list folding.\n\\<close>\nlemma random_serial_dictatorship_empty [simp]:\n  \"random_serial_dictatorship {} alts R = pmf_of_set alts\"\n  by (simp add: random_serial_dictatorship_def)\n\nlemma random_serial_dictatorship_nonempty:\n  \"finite agents \\<Longrightarrow> agents \\<noteq> {} \\<Longrightarrow> \n    random_serial_dictatorship agents alts R =\n      do {\n        i \\<leftarrow> pmf_of_set agents;\n        random_serial_dictatorship (agents - {i}) (Max_wrt_among (R i) alts) R\n      }\"\n  by (simp add: random_serial_dictatorship_def)\n     \n     \ntext \\<open>\n  We define the RSD winners w.r.t. a given set of alternatives and a fixed permutation \n  (i.e. list) of agents. In contrast to the above definition, the RSD winners are \n  determined by traversing the list of agents from right to left.\n    This may seem strange, but it makes induction much easier, since induction over @{term foldr}\n  does not require generalisation over the set of alternatives and is therefore much \n  easier than over @{term foldl}. \n\\<close>\ndefinition rsd_winners where\n  \"rsd_winners R alts agents = foldr (\\<lambda>i alts. Max_wrt_among (R i) alts) agents alts\"\n\nlemma rsd_winners_empty [simp]: \"rsd_winners R alts [] = alts\"\n  by (simp add: rsd_winners_def)\n\nlemma rsd_winners_Cons [simp]:\n  \"rsd_winners R alts (i # agents) = Max_wrt_among (R i) (rsd_winners R alts agents)\"\n  by (simp add: rsd_winners_def)\n\nlemma rsd_winners_map [simp]: \n  \"rsd_winners R alts (map f agents) = rsd_winners (R \\<circ> f) alts agents\"\n  by (simp add: rsd_winners_def foldr_map o_def)\n\n  \ntext \\<open>\n  There is now another alternative definition of RSD in terms of the\n  RSD winners. This will mostly be used for induction.\n\\<close>\nlemma random_serial_dictatorship_altdef:\n  assumes \"finite agents\"\n  shows   \"random_serial_dictatorship agents alts R =\n             do {\n               agents' \\<leftarrow> pmf_of_set (permutations_of_set agents);\n               pmf_of_set (rsd_winners R alts agents')\n             }\"\n   by (simp add: random_serial_dictatorship_def \n         fold_bind_random_permutation_foldr assms rsd_winners_def)\n   \ntext \\<open>\n  The following lemma shows that folding from left to right yields the same\n  distribution. This is probably the most commonly used definition in the literature,\n  along with the recursive one.\n\\<close>\nlemma random_serial_dictatorship_foldl:\n  assumes \"finite agents\"\n  shows   \"random_serial_dictatorship agents alts R =\n             do {\n               agents' \\<leftarrow> pmf_of_set (permutations_of_set agents);\n               pmf_of_set (foldl (\\<lambda>alts i. Max_wrt_among (R i) alts) alts agents')\n             }\"\n   by (simp add: random_serial_dictatorship_def fold_bind_random_permutation_foldl assms)\n\n\n   \nsubsection \\<open>Auxiliary facts about RSD\\<close>\n\n\nsubsubsection \\<open>Pareto-equivalence classes\\<close>\n\ntext \\<open>\n  First of all, we introduce the auxiliary notion of a Pareto-equivalence class.\n  A non-empty set of alternatives is a Pareto equivalence class if all agents are \n  indifferent between all alternatives in it, and if some alternative @{term \"x::'alt\"} \n  is contained in the set, any other alternative @{term \"y::'alt\"} is contained in it\n  if and only if, to all agents, @{term y} is at least as good as @{term x}.\n    The importance of this notion lies in the fact that the set of RSD winners is always\n  a Pareto-equivalence class, which we will later use to show ex-post efficiency and\n  strategy-proofness.\n\\<close>\n\ndefinition RSD_pareto_eqclass where\n  \"RSD_pareto_eqclass agents alts R A \\<longleftrightarrow>\n     A \\<noteq> {} \\<and> A \\<subseteq> alts \\<and> (\\<forall>x\\<in>A. \\<forall>y\\<in>alts. y \\<in> A \\<longleftrightarrow> (\\<forall>i\\<in>agents. R i x y))\"\n\nlemma RSD_pareto_eqclassI:\n  assumes \"A \\<noteq> {}\" \"A \\<subseteq> alts\" \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> alts \\<Longrightarrow> y \\<in> A \\<longleftrightarrow> (\\<forall>i\\<in>agents. R i x y)\"\n  shows   \"RSD_pareto_eqclass agents alts R A\"\n  using assms unfolding RSD_pareto_eqclass_def by simp_all\n\nlemma RSD_pareto_eqclassD:\n  assumes \"RSD_pareto_eqclass agents alts R A\"\n  shows   \"A \\<noteq> {}\" \"A \\<subseteq> alts\" \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> alts \\<Longrightarrow> y \\<in> A \\<longleftrightarrow> (\\<forall>i\\<in>agents. R i x y)\"\n  using assms unfolding RSD_pareto_eqclass_def by simp_all\n\nlemma RSD_pareto_eqclass_indiff_set:\n  assumes \"RSD_pareto_eqclass agents alts R A\" \"i \\<in> agents\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"R i x y\"\n  using assms unfolding RSD_pareto_eqclass_def by blast\n\nlemma RSD_pareto_eqclass_empty [simp, intro!]:\n  \"alts \\<noteq> {} \\<Longrightarrow> RSD_pareto_eqclass {} alts R alts\"\n  by (auto intro!: RSD_pareto_eqclassI)\n\nlemma (in pref_profile_wf) RSD_pareto_eqclass_insert:\n  assumes \"RSD_pareto_eqclass agents' alts R A\" \"finite alts\"\n          \"i \\<in> agents\" \"agents' \\<subseteq> agents\"\n  shows   \"RSD_pareto_eqclass (insert i agents') alts R (Max_wrt_among (R i) A)\"\nproof -\n  from assms interpret total_preorder_on alts \"R i\" by simp\n  show ?thesis\n  proof (intro RSD_pareto_eqclassI Max_wrt_among_nonempty Max_wrt_among_subset, goal_cases)\n    case (3 x y)\n    with RSD_pareto_eqclassD[OF assms(1)] \n      show ?case unfolding Max_wrt_among_total_preorder \n      by (blast intro: trans)\n  qed (insert RSD_pareto_eqclassD[OF assms(1)] assms(2), \n       simp_all add: Int_absorb1 Int_absorb2 finite_subset)[2]\nqed\n\n\nsubsubsection \\<open>Facts about RSD winners\\<close>\n\ncontext pref_profile_wf\nbegin\n\ntext \\<open>\n  Any RSD winner is a valid alternative.  \n\\<close>\nlemma rsd_winners_subset:\n  assumes \"set agents' \\<subseteq> agents\" \n  shows   \"rsd_winners R alts' agents' \\<subseteq> alts'\"\nproof -\n  {\n    fix i assume \"i \\<in> agents\"\n    then interpret total_preorder_on alts \"R i\" by simp\n    have \"Max_wrt_among (R i) A \\<subseteq> A\" for A\n      using Max_wrt_among_subset by blast\n  } note A = this\n\n  from \\<open>set agents' \\<subseteq> agents\\<close> show \"rsd_winners R alts' agents' \\<subseteq> alts'\"\n    using A by (induction agents') auto\nqed\n\ntext \\<open>\n  There is always at least one RSD winner.  \n\\<close>\nlemma rsd_winners_nonempty:\n  assumes finite: \"finite alts\"  and \"alts' \\<noteq> {}\"  \"set agents' \\<subseteq> agents\" \"alts' \\<subseteq> alts\" \n  shows   \"rsd_winners R alts' agents' \\<noteq> {}\"\nproof -\n  {\n    fix i assume \"i \\<in> agents\"\n    then interpret total_preorder_on alts \"R i\" by simp\n    have \"Max_wrt_among (R i) A \\<noteq> {}\" if \"A \\<subseteq> alts\" \"A \\<noteq> {}\" for A\n      using that assms by (intro Max_wrt_among_nonempty) (auto simp: Int_absorb)\n  } note B = this\n\n  with \\<open>set agents' \\<subseteq> agents\\<close> \\<open>alts' \\<subseteq> alts\\<close> \\<open>alts' \\<noteq> {}\\<close> \n    show \"rsd_winners R alts' agents' \\<noteq> {}\"\n  proof (induction agents')\n    case (Cons i agents')\n    with B[of i \"rsd_winners R alts' agents'\"] rsd_winners_subset[of agents' alts'] finite wf\n      show ?case by auto\n  qed simp\nqed\n\ntext \\<open>\n  Obviously, the set of RSD winners is always finite.\n\\<close>\nlemma rsd_winners_finite: \n  assumes \"set agents' \\<subseteq> agents\" \"finite alts\" \"alts' \\<subseteq> alts\"\n  shows   \"finite (rsd_winners R alts' agents')\"\n  by (rule finite_subset[OF subset_trans[OF rsd_winners_subset]]) fact+\n\nlemmas rsd_winners_wf = \n  rsd_winners_subset rsd_winners_nonempty rsd_winners_finite\n\n\ntext \\<open>\n  The set of RSD winners is a Pareto-equivalence class.\n\\<close>\nlemma RSD_pareto_eqclass_rsd_winners_aux:\n  assumes finite: \"finite alts\" and \"alts \\<noteq> {}\" and \"set agents' \\<subseteq> agents\"\n  shows   \"RSD_pareto_eqclass (set agents') alts R (rsd_winners R alts agents')\"\n  using \\<open>set agents' \\<subseteq> agents\\<close>\nproof (induction agents')\n  case (Cons i agents')\n  from Cons.prems show ?case\n    by (simp only: set_simps rsd_winners_Cons,\n        intro RSD_pareto_eqclass_insert[OF Cons.IH finite]) simp_all\nqed (insert assms, simp_all)\n\nlemma RSD_pareto_eqclass_rsd_winners:\n  assumes finite: \"finite alts\" and \"alts \\<noteq> {}\" and \"set agents' = agents\"\n  shows   \"RSD_pareto_eqclass agents alts R (rsd_winners R alts agents')\"\n  using RSD_pareto_eqclass_rsd_winners_aux[of agents'] assms by simp\n\n\ntext \\<open>\n  For the proof of strategy-proofness, we need to define indifference sets\n  and lift preference relations to sets in a specific way.\n\\<close>\ncontext\nbegin\n\ntext \\<open>\n  An indifference set for a given preference relation is a non-empty set of alternatives \n  such that the agent is indifferent over all of them.\n\\<close>\nprivate definition indiff_set where\n  \"indiff_set S A \\<longleftrightarrow> A \\<noteq> {} \\<and> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. S x y)\"\n  \nprivate lemma indiff_set_mono: \"indiff_set S A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> indiff_set S B\"\n  unfolding indiff_set_def by blast\n\n  \ntext \\<open>\n  Given an arbitrary set of alternatives @{term A} and an indifference set @{term B},\n  we say that @{term B} is set-preferred over @{term A} w.r.t. the preference \n  relation @{term R} if all (or, equivalently, any) of the alternatives in @{term B} \n  are preferred over all alternatives in @{term A}.\n\\<close>\nprivate definition RSD_set_rel where\n  \"RSD_set_rel S A B \\<longleftrightarrow> indiff_set S B \\<and> (\\<forall>x\\<in>A. \\<forall>y\\<in>B. S x y)\" \n\ntext \\<open>\n  The most-preferred alternatives (w.r.t. @{term R}) among any non-empty set of alternatives \n  form an indifference set w.r.t. @{term R}.\n\\<close>\nprivate lemma indiff_set_Max_wrt_among:\n  assumes \"finite carrier\" \"A \\<subseteq> carrier\" \"A \\<noteq> {}\" \"total_preorder_on carrier S\" \n  shows   \"indiff_set S (Max_wrt_among S A)\"\n  unfolding indiff_set_def\nproof\n  from assms(4) interpret total_preorder_on carrier S .\n  from assms(1-3) \n    show \"Max_wrt_among S A \\<noteq> {}\" by (intro Max_wrt_among_nonempty) auto\n  from assms(1-3) show \"\\<forall>x\\<in>Max_wrt_among S A. \\<forall>y\\<in>Max_wrt_among S A. S x y\"\n    by (auto simp: indiff_set_def Max_wrt_among_total_preorder)\nqed\n\n\ntext \\<open>\n  We now consider the set of RSD winners in the setting of a preference profile @{term R}\n  and a manipulated profile @{term \"R(i := Ri')\"}.\n    This theorem shows that the set of RSD winners in the outcome is either the same\n  in both cases or the outcome for the truthful profile is an indifference set that is\n  set-preferred over the outcome for the manipulated profile.\n\\<close>\nlemma rsd_winners_manipulation_aux:\n  assumes wf: \"total_preorder_on alts Ri'\"\n      and i: \"i \\<in> agents\" and \"set agents' \\<subseteq> agents\" \"finite agents\" \n      and finite: \"finite alts\" and \"alts \\<noteq> {}\"\n  defines [simp]: \"w' \\<equiv> rsd_winners (R(i := Ri')) alts\" and [simp]: \"w \\<equiv> rsd_winners R alts\"\n  shows   \"w' agents' = w agents' \\<or> RSD_set_rel (R i) (w' agents') (w agents')\"\nusing \\<open>set agents' \\<subseteq> agents\\<close>\nproof (induction agents')\n  case (Cons j agents')\n  from wf i interpret Ri: total_preorder_on alts \"R i\" by simp\n  from wf Cons.prems interpret Rj: total_preorder_on alts \"R j\" by simp\n  from wf interpret Ri': total_preorder_on alts \"Ri'\" .\n  from wf assms Cons.prems \n    have indiff_set: \"indiff_set (R i) (Max_wrt_among (R i) (rsd_winners R alts agents'))\"\n    by (intro indiff_set_Max_wrt_among[OF finite] rsd_winners_wf) simp_all\n        \n  show ?case\n  proof (cases \"j = i\")\n    assume j [simp]: \"j = i\"\n    from indiff_set Cons have \"RSD_set_rel (R i) (w' (j # agents')) (w (j # agents'))\"\n      unfolding RSD_set_rel_def\n      by (auto simp: Ri.Max_wrt_among_total_preorder Ri'.Max_wrt_among_total_preorder)\n    thus ?case ..\n  next\n    assume j [simp]: \"j \\<noteq> i\"\n    from Cons have \"w' agents' = w agents' \\<or> RSD_set_rel (R i) (w' agents') (w agents')\" by simp\n    thus ?case\n    proof\n      assume rel: \"RSD_set_rel (R i) (w' agents') (w agents')\"\n      hence indiff_set: \"indiff_set (R i) (w agents')\" by (simp add: RSD_set_rel_def)\n      moreover from Cons.prems finite \\<open>alts \\<noteq> {}\\<close> \n        have \"w agents' \\<subseteq> alts\" \"w agents' \\<noteq> {}\" unfolding w_def\n        by (intro rsd_winners_wf; simp)+\n      with finite have \"Max_wrt_among (R j) (w agents') \\<noteq> {}\"\n        by (intro Rj.Max_wrt_among_nonempty) auto\n      ultimately have \"indiff_set (R i) (w (j # agents'))\"\n        by (intro indiff_set_mono[OF indiff_set] Rj.Max_wrt_among_subset)\n           (simp_all add: Rj.Max_wrt_among_subset)\n      moreover from rel have \"\\<forall>x\\<in>w' (j # agents'). \\<forall>y\\<in>w (j # agents'). R i x y\"\n        by (auto simp: RSD_set_rel_def Rj.Max_wrt_among_total_preorder)\n      ultimately have \"RSD_set_rel (R i) (w' (j # agents')) (w (j # agents'))\"\n        unfolding RSD_set_rel_def ..\n      thus ?case ..\n    qed simp_all\n  qed\nqed simp_all\n\n\ntext \\<open>\n  The following variant of the previous theorem is slightly easier to use.\n  We eliminate the case where the two outcomes are the same by observing that\n  the original outcome is then also set-preferred to the manipulated one.\n    In essence, this means that no matter what manipulation is done, the \n  original outcome is always set-preferred to the manipulated one.\n\\<close>\nlemma rsd_winners_manipulation:\n  assumes wf: \"total_preorder_on alts Ri'\"\n      and i: \"i \\<in> agents\" and \"set agents' = agents\" \"finite agents\" \n      and finite: \"finite alts\" and \"alts \\<noteq> {}\"\n  defines [simp]: \"w' \\<equiv> rsd_winners (R(i := Ri')) alts\" and [simp]: \"w \\<equiv> rsd_winners R alts\"\n  shows   \"\\<forall>x\\<in>w' agents'. \\<forall>y\\<in>w agents'. x \\<preceq>[R i] y\"\nproof -\n  have \"w' agents' = w agents' \\<or> RSD_set_rel (R i) (w' agents') (w agents')\"\n    using rsd_winners_manipulation_aux[OF assms(1-2) _ assms(4-6)] assms(3) by simp\n  thus ?thesis\n  proof\n    assume eq: \"w' agents' = w agents'\"\n    from assms have \"RSD_pareto_eqclass (set agents') alts R (w agents')\" unfolding w_def\n      by (intro RSD_pareto_eqclass_rsd_winners_aux) simp_all\n    from RSD_pareto_eqclass_indiff_set[OF this, of i] i eq assms(3) show ?thesis by auto\n  qed (auto simp: RSD_set_rel_def)\nqed\n\nend\n\n\ntext \\<open>\n  The lottery that RSD yields is well-defined.\n\\<close>\nlemma random_serial_dictatorship_support:\n  assumes \"finite agents\" \"finite alts\" \"agents' \\<subseteq> agents\" \"alts' \\<noteq> {}\" \"alts' \\<subseteq> alts\"\n  shows   \"set_pmf (random_serial_dictatorship agents' alts' R) \\<subseteq> alts'\"\nproof -\n  from assms have [simp]: \"finite agents'\" by (auto intro: finite_subset)\n  have A: \"set_pmf (pmf_of_set (rsd_winners R alts' agents'')) \\<subseteq> alts'\"\n    if \"agents'' \\<in> permutations_of_set agents'\" for agents''\n    using that assms rsd_winners_wf[where alts' = alts' and agents' = agents'']\n    by (auto simp: permutations_of_set_def)\n  from assms show ?thesis\n    by (auto dest!: A simp add: random_serial_dictatorship_altdef)\nqed\n\ntext \\<open>\n  Permutation of alternatives commutes with RSD winners.\n\\<close>\nlemma rsd_winners_permute_profile:\n  assumes perm: \"\\<sigma> permutes alts\" and \"set agents' \\<subseteq> agents\" \n  shows   \"rsd_winners (permute_profile \\<sigma> R) alts agents' = \\<sigma> ` rsd_winners R alts agents'\"\n  using \\<open>set agents' \\<subseteq> agents\\<close>\nproof (induction agents')\n  case Nil\n  from perm show ?case by (simp add: permutes_image)\nnext\n  case (Cons i agents')\n  from wf Cons interpret total_preorder_on alts \"R i\" by simp\n  from perm Cons show ?case\n    by (simp add: permute_profile_map_relation Max_wrt_among_map_relation_bij permutes_bij)\nqed\n\nlemma random_serial_dictatorship_singleton:\n  assumes \"finite agents\" \"finite alts\" \"agents' \\<subseteq> agents\" \"x \\<in> alts\"\n  shows   \"random_serial_dictatorship agents' {x} R = return_pmf x\" (is \"?d = _\")\nproof -\n  from assms have \"set_pmf ?d \\<subseteq> {x}\" \n    by (intro random_serial_dictatorship_support) simp_all\n  thus ?thesis by (simp add: set_pmf_subset_singleton)\nqed\n\nend\n\n\nsubsection \\<open>Proofs of properties\\<close>\n\ntext \\<open>\n  With all the facts that we have proven about the RSD winners, the hard work is\n  mostly done. We can now simply fix some arbitrary order of the agents, apply the \n  theorems about the RSD winners, and show the properties we want to show without \n  doing much reasoning about probabilities.\n\\<close>\n\ncontext election\nbegin     \n\nabbreviation \"RSD \\<equiv> random_serial_dictatorship agents alts\"\n\nsubsubsection \\<open>Well-definedness\\<close>\n\nsublocale RSD: social_decision_scheme agents alts RSD\n  using pref_profile_wf.random_serial_dictatorship_support[of agents alts]\n  by unfold_locales (simp_all add: lotteries_on_def)\n\n\nsubsubsection \\<open>RD extension\\<close>\n\nlemma RSD_extends_RD:\n  assumes wf: \"is_pref_profile R\" and unique: \"has_unique_favorites R\"\n  shows   \"RSD R = RD R\"\nproof -\n  from wf interpret pref_profile_wf agents alts R .\n  from unique interpret pref_profile_unique_favorites by unfold_locales\n  have \"RSD R = pmf_of_set agents \\<bind> \n                  (\\<lambda>i. random_serial_dictatorship (agents - {i}) (favorites R i) R)\"\n    by (simp add: random_serial_dictatorship_nonempty favorites_altdef Max_wrt_def)\n  also from assms have \"\\<dots> = pmf_of_set agents \\<bind> (\\<lambda>i. return_pmf (favorite R i))\"\n    by (intro bind_pmf_cong refl, subst random_serial_dictatorship_singleton [symmetric])\n       (auto simp: unique_favorites favorite_in_alts)\n  also from assms have \"\\<dots> = RD R\"\n    by (simp add: random_dictatorship_unique_favorites map_pmf_def)\n  finally show ?thesis .\nqed\n  \n\nsubsubsection \\<open>Anonymity\\<close>\n\ntext \\<open>\n  Anonymity is a direct consequence of the fact that we randomise over all\n  permutations in a uniform way.\n\\<close>\n\nsublocale RSD: anonymous_sds agents alts RSD\nproof\n  fix \\<pi> R assume perm: \"\\<pi> permutes agents\" and wf: \"is_pref_profile R\"\n  let ?f = \"\\<lambda>agents'. pmf_of_set (rsd_winners R alts agents')\"\n  from perm wf have \"RSD (R \\<circ> \\<pi>) = map_pmf (map \\<pi>) (pmf_of_set (permutations_of_set agents)) \\<bind> ?f\"\n    by (simp add: random_serial_dictatorship_altdef bind_map_pmf)\n  also from perm have \"\\<dots> = RSD R\"\n    by (simp add: map_pmf_of_set_inj permutes_inj_on inj_on_mapI\n                  permutations_of_set_image_permutes random_serial_dictatorship_altdef)\n  finally show \"RSD (R \\<circ> \\<pi>) = RSD R\" .\nqed\n\n\nsubsubsection \\<open>Neutrality\\<close>\n\ntext \\<open>\n  Neutrality follows from the fact that the RSD winners of a permuted profile \n  are simply the image of the original RSD winners under the permutation.\n\\<close>\n\nsublocale RSD: neutral_sds agents alts RSD\nproof\n  fix \\<sigma> R assume perm: \"\\<sigma> permutes alts\" and wf: \"is_pref_profile R\"\n  from wf interpret pref_profile_wf agents alts R .\n  from perm show \"RSD (permute_profile \\<sigma> R) = map_pmf \\<sigma> (RSD R)\"\n    by (auto intro!: bind_pmf_cong dest!: permutations_of_setD(1) \n             simp: random_serial_dictatorship_altdef rsd_winners_permute_profile\n                   map_bind_pmf map_pmf_of_set_inj permutes_inj_on rsd_winners_wf)\nqed\n\n\nsubsubsection \\<open>Ex-post efficiency\\<close>\n\ntext \\<open>\n  Ex-post efficiency follows from the fact that the set of RSD winners \n  is a Pareto-equivalence class.\n\\<close>\n\nsublocale RSD: ex_post_efficient_sds agents alts RSD\nproof\n  fix R assume wf: \"is_pref_profile R\"\n  then interpret pref_profile_wf agents alts R .\n  {\n    fix x assume x: \"x \\<in> set_pmf (RSD R)\" \"x \\<in> pareto_losers R\"\n    from x(2) obtain y where [simp]: \"y \\<in> alts\" and pareto: \"y \\<succ>[Pareto(R)] x\" \n      by (cases rule: pareto_losersE)\n    from x have [simp]: \"x \\<in> alts\" using pareto_loser_in_alts by simp\n\n    from x(1) obtain agents' where agents': \"set agents' = agents\" and \n        \"x \\<in> set_pmf (pmf_of_set (rsd_winners R alts agents'))\"\n      by (auto simp: random_serial_dictatorship_altdef dest: permutations_of_setD)\n    with wf have x': \"x \\<in> rsd_winners R alts agents'\"\n      using rsd_winners_wf[where alts' = alts and agents' = agents']\n      by (subst (asm) set_pmf_of_set) (auto simp: permutations_of_setD)\n\n    from wf agents' \n      have \"RSD_pareto_eqclass agents alts R (rsd_winners R alts agents')\"\n      by (intro RSD_pareto_eqclass_rsd_winners) simp_all\n    hence winner_iff: \"y \\<in> rsd_winners R alts agents' \\<longleftrightarrow> (\\<forall>i\\<in>agents. x \\<preceq>[R i] y)\"\n      if \"x \\<in> rsd_winners R alts agents'\" \"y \\<in> alts\" for x y\n      using that unfolding RSD_pareto_eqclass_def by blast\n    from x' pareto winner_iff[of x y] winner_iff[of y x] have False\n      by (force simp: strongly_preferred_def Pareto_iff)\n  }\n  thus \"set_pmf (RSD R) \\<inter> pareto_losers R = {}\" by blast\nqed\n\n\nsubsubsection \\<open>Strong strategy-proofness\\<close>\n\ntext \\<open>\n  Strong strategy-proofness is slightly more difficult to show. We have already shown\n  that the set of RSD winners for the truthful profile is always set-preferred (by the\n  manipulating agent) to the RSD winners for the manipulated profile.\n    This can now be used to show strategy-proofness: We recall that the set of RSD \n  winners is always an indifference class. Therefore, given any fixed alternative @{term \"x::'alt\"}\n  and considering a fixed order of the agents, either all of the RSD winners in the original\n  profile are at least as good as @{term \"x::'alt\"} or none of them are, and, since the original \n  RSD winners are set-preferred to the manipulated ones, none of the RSD winners in the\n  manipulated case are at least as good than @{term \"x::'alt\"} either in that case.\n    This means that for a fixed order of agents, either the probability that the original  \n  outcome is at least as good as @{term \"x::'alt\"} is 1 or the probability that the manipulated\n  outcome is at least as good as @{term \"x::'alt\"} is 0.\n    Therefore, the original lottery is clearly SD-preferred to the manipulated one.\n\\<close>\n\nsublocale RSD: strongly_strategyproof_sds agents alts RSD\nproof (unfold_locales, rule)\n  fix R i Ri' x\n  assume wf: \"is_pref_profile R\" and i [simp]: \"i \\<in> agents\" and x: \"x \\<in> alts\" and\n         wf': \"total_preorder_on alts Ri'\"\n  interpret R: pref_profile_wf agents alts R by fact\n  define R' where \"R' = R (i := Ri')\"\n  from wf wf' have \"is_pref_profile R'\" by (simp add: R'_def R.wf_update)\n  then interpret R': pref_profile_wf agents alts R' .\n  note wf = wf wf'\n  let ?A = \"preferred_alts (R i) x\"\n  from wf interpret Ri: total_preorder_on alts \"R i\" by simp\n\n  {\n    fix agents' assume agents': \"agents' \\<in> permutations_of_set agents\"\n    from agents' have [simp]: \"set agents' = agents\"\n      by (simp add: permutations_of_set_def)\n      \n    let ?W = \"rsd_winners R alts agents'\" and ?W' = \"rsd_winners R' alts agents'\"\n    have indiff_set: \"RSD_pareto_eqclass agents alts R ?W\"\n      by (rule R.RSD_pareto_eqclass_rsd_winners; simp add: wf)+\n    from R.rsd_winners_wf R'.rsd_winners_wf\n      have winners: \"?W \\<subseteq> alts\" \"?W \\<noteq> {}\" \"finite ?W\" \"?W' \\<subseteq> alts\" \"?W' \\<noteq> {}\" \"finite ?W'\"\n      by simp_all\n    \n    from \\<open>?W \\<noteq> {}\\<close> obtain y where y: \"y \\<in> ?W\" by blast\n    with winners have [simp]: \"y \\<in> alts\" by blast\n    from wf' i have mono: \"\\<forall>x\\<in>?W'. \\<forall>y\\<in>?W. R i x y\" unfolding R'_def\n      by (intro R.rsd_winners_manipulation) simp_all\n    \n    have \"lottery_prob (pmf_of_set ?W) ?A \\<ge> lottery_prob (pmf_of_set ?W') ?A\"\n    proof (cases \"y \\<succeq>[R i] x\")\n      case True\n      with y RSD_pareto_eqclass_indiff_set[OF indiff_set(1), of i]  winners\n        have \"?W \\<subseteq> preferred_alts (R i) x\"\n        by (auto intro: Ri.trans simp: preferred_alts_def)\n      with winners show ?thesis\n        by (subst (2) measure_pmf_of_set) (simp_all add: Int_absorb2)\n    next\n      case False\n      with y mono have \"?W' \\<inter> preferred_alts (R i) x = {}\" \n        by (auto intro: Ri.trans simp: preferred_alts_def)\n      with winners show ?thesis\n        by (subst (1) measure_pmf_of_set)\n           (simp_all add: Int_absorb2 one_ereal_def measure_nonneg)\n    qed\n    hence \"emeasure (measure_pmf (pmf_of_set ?W)) ?A \\<ge> emeasure (measure_pmf (pmf_of_set ?W')) ?A\"\n      by (simp add: measure_pmf.emeasure_eq_measure)\n  }\n  hence \"emeasure (measure_pmf (RSD R)) ?A \\<ge> emeasure (measure_pmf (RSD R')) ?A\"\n    by (auto simp: random_serial_dictatorship_altdef AE_measure_pmf_iff\n             intro!: nn_integral_mono_AE)\n  thus \"lottery_prob (RSD R) ?A \\<ge> lottery_prob (RSD R') ?A\" \n    by (simp add: measure_pmf.emeasure_eq_measure)\nqed\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Randomised_Social_Choice/Random_Serial_Dictatorship.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8633916134888614, "lm_q1q2_score": 0.7919914155096565}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Bubblesort\\<close>\n\ntheory Bubblesort\nimports \"HOL-Library.Multiset\"\nbegin\n\ntext\\<open>This is \\emph{a} version of bubblesort.\\<close>\n\ncontext linorder\nbegin\n\nfun bubble_min where\n\"bubble_min [] = []\" |\n\"bubble_min [x] = [x]\" |\n\"bubble_min (x#xs) =\n  (case bubble_min xs of y#ys \\<Rightarrow> if x>y then y#x#ys else x#y#ys)\"\n\nlemma size_bubble_min: \"size(bubble_min xs) = size xs\"\nby(induction xs rule: bubble_min.induct) (auto split: list.split)\n\nlemma bubble_min_eq_Nil_iff[simp]: \"bubble_min xs = [] \\<longleftrightarrow> xs = []\"\nby (metis length_0_conv size_bubble_min)\n\nlemma bubble_minD_size: \"bubble_min (xs) = ys \\<Longrightarrow> size xs = size ys\"\nby(auto simp: size_bubble_min)\n\nfunction (sequential) bubblesort where\n\"bubblesort []  = []\" |\n\"bubblesort [x] = [x]\" |\n\"bubblesort xs  = (case bubble_min xs of y#ys \\<Rightarrow> y # bubblesort ys)\"\nby pat_completeness auto\n\ntermination\nproof\n  show \"wf(measure size)\" by simp\nnext\n  fix x1 x2 y :: 'a fix xs ys :: \"'a list\"\n  show \"bubble_min(x1#x2#xs) = y#ys \\<Longrightarrow> (ys, x1#x2#xs) \\<in> measure size\"\n    by(auto simp: size_bubble_min dest!: bubble_minD_size split: list.splits if_splits)\nqed\n\nlemma mset_bubble_min: \"mset (bubble_min xs) = mset xs\"\napply(induction xs rule: bubble_min.induct)\n  apply simp\n apply simp\napply (auto split: list.split)\ndone\n\nlemma bubble_minD_mset:\n  \"bubble_min (xs) = ys \\<Longrightarrow> mset xs = mset ys\"\nby(auto simp: mset_bubble_min)\n\nlemma mset_bubblesort:\n  \"mset (bubblesort xs) = mset xs\"\napply(induction xs rule: bubblesort.induct)\n  apply simp\n apply simp\nby(auto split: list.splits if_splits dest: bubble_minD_mset)\n\nlemma set_bubblesort: \"set (bubblesort xs) = set xs\"\nby(rule mset_bubblesort[THEN mset_eq_setD])\n\nlemma bubble_min_min: \"bubble_min xs = y#ys \\<Longrightarrow> z \\<in> set ys \\<Longrightarrow> y \\<le> z\"\napply(induction xs arbitrary: y ys z rule: bubble_min.induct)\n  apply simp\n apply simp\napply (fastforce split: list.splits if_splits dest!: sym[of \"a#b\" for a b])\ndone\n\nlemma sorted_bubblesort: \"sorted(bubblesort xs)\"\napply(induction xs rule: bubblesort.induct)\n  apply simp\n apply simp\napply (fastforce simp: set_bubblesort split: list.split if_splits dest: bubble_min_min)\ndone\n\nend\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/Bubblesort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7919434786009316}}
{"text": "(*  Title:      HOL/Lattice/Orders.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection {* Orders *}\n\ntheory Orders imports Main begin\n\nsubsection {* Ordered structures *}\n\ntext {*\n  We define several classes of ordered structures over some type @{typ\n  'a} with relation @{text \"\\<sqsubseteq> \\<Colon> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"}.  For a\n  \\emph{quasi-order} that relation is required to be reflexive and\n  transitive, for a \\emph{partial order} it also has to be\n  anti-symmetric, while for a \\emph{linear order} all elements are\n  required to be related (in either direction).\n*}\n\nclass leq =\n  fixes leq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infixl \"[=\" 50)\n\nnotation (xsymbols)\n  leq  (infixl \"\\<sqsubseteq>\" 50)\n\nclass quasi_order = leq +\n  assumes leq_refl [intro?]: \"x \\<sqsubseteq> x\"\n  assumes leq_trans [trans]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n\nclass partial_order = quasi_order +\n  assumes leq_antisym [trans]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\n\nclass linear_order = partial_order +\n  assumes leq_linear: \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n\nlemma linear_order_cases:\n    \"((x::'a::linear_order) \\<sqsubseteq> y \\<Longrightarrow> C) \\<Longrightarrow> (y \\<sqsubseteq> x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (insert leq_linear) blast\n\n\nsubsection {* Duality *}\n\ntext {*\n  The \\emph{dual} of an ordered structure is an isomorphic copy of the\n  underlying type, with the @{text \\<sqsubseteq>} relation defined as the inverse\n  of the original one.\n*}\n\ndatatype 'a dual = dual 'a\n\nprimrec undual :: \"'a dual \\<Rightarrow> 'a\" where\n  undual_dual: \"undual (dual x) = x\"\n\ninstantiation dual :: (leq) leq\nbegin\n\ndefinition\n  leq_dual_def: \"x' \\<sqsubseteq> y' \\<equiv> undual y' \\<sqsubseteq> undual x'\"\n\ninstance ..\n\nend\n\nlemma undual_leq [iff?]: \"(undual x' \\<sqsubseteq> undual y') = (y' \\<sqsubseteq> x')\"\n  by (simp add: leq_dual_def)\n\nlemma dual_leq [iff?]: \"(dual x \\<sqsubseteq> dual y) = (y \\<sqsubseteq> x)\"\n  by (simp add: leq_dual_def)\n\ntext {*\n  \\medskip Functions @{term dual} and @{term undual} are inverse to\n  each other; this entails the following fundamental properties.\n*}\n\nlemma dual_undual [simp]: \"dual (undual x') = x'\"\n  by (cases x') simp\n\nlemma undual_dual_id [simp]: \"undual o dual = id\"\n  by (rule ext) simp\n\nlemma dual_undual_id [simp]: \"dual o undual = id\"\n  by (rule ext) simp\n\ntext {*\n  \\medskip Since @{term dual} (and @{term undual}) are both injective\n  and surjective, the basic logical connectives (equality,\n  quantification etc.) are transferred as follows.\n*}\n\nlemma undual_equality [iff?]: \"(undual x' = undual y') = (x' = y')\"\n  by (cases x', cases y') simp\n\nlemma dual_equality [iff?]: \"(dual x = dual y) = (x = y)\"\n  by simp\n\nlemma dual_ball [iff?]: \"(\\<forall>x \\<in> A. P (dual x)) = (\\<forall>x' \\<in> dual ` A. P x')\"\nproof\n  assume a: \"\\<forall>x \\<in> A. P (dual x)\"\n  show \"\\<forall>x' \\<in> dual ` A. P x'\"\n  proof\n    fix x' assume x': \"x' \\<in> dual ` A\"\n    have \"undual x' \\<in> A\"\n    proof -\n      from x' have \"undual x' \\<in> undual ` dual ` A\" by simp\n      thus \"undual x' \\<in> A\" by (simp add: image_comp)\n    qed\n    with a have \"P (dual (undual x'))\" ..\n    also have \"\\<dots> = x'\" by simp\n    finally show \"P x'\" .\n  qed\nnext\n  assume a: \"\\<forall>x' \\<in> dual ` A. P x'\"\n  show \"\\<forall>x \\<in> A. P (dual x)\"\n  proof\n    fix x assume \"x \\<in> A\"\n    hence \"dual x \\<in> dual ` A\" by simp\n    with a show \"P (dual x)\" ..\n  qed\nqed\n\nlemma range_dual [simp]: \"surj dual\"\nproof -\n  have \"\\<And>x'. dual (undual x') = x'\" by simp\n  thus \"surj dual\" by (rule surjI)\nqed\n\nlemma dual_all [iff?]: \"(\\<forall>x. P (dual x)) = (\\<forall>x'. P x')\"\nproof -\n  have \"(\\<forall>x \\<in> UNIV. P (dual x)) = (\\<forall>x' \\<in> dual ` UNIV. P x')\"\n    by (rule dual_ball)\n  thus ?thesis by simp\nqed\n\nlemma dual_ex: \"(\\<exists>x. P (dual x)) = (\\<exists>x'. P x')\"\nproof -\n  have \"(\\<forall>x. \\<not> P (dual x)) = (\\<forall>x'. \\<not> P x')\"\n    by (rule dual_all)\n  thus ?thesis by blast\nqed\n\nlemma dual_Collect: \"{dual x| x. P (dual x)} = {x'. P x'}\"\nproof -\n  have \"{dual x| x. P (dual x)} = {x'. \\<exists>x''. x' = x'' \\<and> P x''}\"\n    by (simp only: dual_ex [symmetric])\n  thus ?thesis by blast\nqed\n\n\nsubsection {* Transforming orders *}\n\nsubsubsection {* Duals *}\n\ntext {*\n  The classes of quasi, partial, and linear orders are all closed\n  under formation of dual structures.\n*}\n\ninstance dual :: (quasi_order) quasi_order\nproof\n  fix x' y' z' :: \"'a::quasi_order dual\"\n  have \"undual x' \\<sqsubseteq> undual x'\" .. thus \"x' \\<sqsubseteq> x'\" ..\n  assume \"y' \\<sqsubseteq> z'\" hence \"undual z' \\<sqsubseteq> undual y'\" ..\n  also assume \"x' \\<sqsubseteq> y'\" hence \"undual y' \\<sqsubseteq> undual x'\" ..\n  finally show \"x' \\<sqsubseteq> z'\" ..\nqed\n\ninstance dual :: (partial_order) partial_order\nproof\n  fix x' y' :: \"'a::partial_order dual\"\n  assume \"y' \\<sqsubseteq> x'\" hence \"undual x' \\<sqsubseteq> undual y'\" ..\n  also assume \"x' \\<sqsubseteq> y'\" hence \"undual y' \\<sqsubseteq> undual x'\" ..\n  finally show \"x' = y'\" ..\nqed\n\ninstance dual :: (linear_order) linear_order\nproof\n  fix x' y' :: \"'a::linear_order dual\"\n  show \"x' \\<sqsubseteq> y' \\<or> y' \\<sqsubseteq> x'\"\n  proof (rule linear_order_cases)\n    assume \"undual y' \\<sqsubseteq> undual x'\"\n    hence \"x' \\<sqsubseteq> y'\" .. thus ?thesis ..\n  next\n    assume \"undual x' \\<sqsubseteq> undual y'\"\n    hence \"y' \\<sqsubseteq> x'\" .. thus ?thesis ..\n  qed\nqed\n\n\nsubsubsection {* Binary products \\label{sec:prod-order} *}\n\ntext {*\n  The classes of quasi and partial orders are closed under binary\n  products.  Note that the direct product of linear orders need\n  \\emph{not} be linear in general.\n*}\n\ninstantiation prod :: (leq, leq) leq\nbegin\n\ndefinition\n  leq_prod_def: \"p \\<sqsubseteq> q \\<equiv> fst p \\<sqsubseteq> fst q \\<and> snd p \\<sqsubseteq> snd q\"\n\ninstance ..\n\nend\n\nlemma leq_prodI [intro?]:\n    \"fst p \\<sqsubseteq> fst q \\<Longrightarrow> snd p \\<sqsubseteq> snd q \\<Longrightarrow> p \\<sqsubseteq> q\"\n  by (unfold leq_prod_def) blast\n\nlemma leq_prodE [elim?]:\n    \"p \\<sqsubseteq> q \\<Longrightarrow> (fst p \\<sqsubseteq> fst q \\<Longrightarrow> snd p \\<sqsubseteq> snd q \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (unfold leq_prod_def) blast\n\ninstance prod :: (quasi_order, quasi_order) quasi_order\nproof\n  fix p q r :: \"'a::quasi_order \\<times> 'b::quasi_order\"\n  show \"p \\<sqsubseteq> p\"\n  proof\n    show \"fst p \\<sqsubseteq> fst p\" ..\n    show \"snd p \\<sqsubseteq> snd p\" ..\n  qed\n  assume pq: \"p \\<sqsubseteq> q\" and qr: \"q \\<sqsubseteq> r\"\n  show \"p \\<sqsubseteq> r\"\n  proof\n    from pq have \"fst p \\<sqsubseteq> fst q\" ..\n    also from qr have \"\\<dots> \\<sqsubseteq> fst r\" ..\n    finally show \"fst p \\<sqsubseteq> fst r\" .\n    from pq have \"snd p \\<sqsubseteq> snd q\" ..\n    also from qr have \"\\<dots> \\<sqsubseteq> snd r\" ..\n    finally show \"snd p \\<sqsubseteq> snd r\" .\n  qed\nqed\n\ninstance prod :: (partial_order, partial_order) partial_order\nproof\n  fix p q :: \"'a::partial_order \\<times> 'b::partial_order\"\n  assume pq: \"p \\<sqsubseteq> q\" and qp: \"q \\<sqsubseteq> p\"\n  show \"p = q\"\n  proof\n    from pq have \"fst p \\<sqsubseteq> fst q\" ..\n    also from qp have \"\\<dots> \\<sqsubseteq> fst p\" ..\n    finally show \"fst p = fst q\" .\n    from pq have \"snd p \\<sqsubseteq> snd q\" ..\n    also from qp have \"\\<dots> \\<sqsubseteq> snd p\" ..\n    finally show \"snd p = snd q\" .\n  qed\nqed\n\n\nsubsubsection {* General products \\label{sec:fun-order} *}\n\ntext {*\n  The classes of quasi and partial orders are closed under general\n  products (function spaces).  Note that the direct product of linear\n  orders need \\emph{not} be linear in general.\n*}\n\ninstantiation \"fun\" :: (type, leq) leq\nbegin\n\ndefinition\n  leq_fun_def: \"f \\<sqsubseteq> g \\<equiv> \\<forall>x. f x \\<sqsubseteq> g x\"\n\ninstance ..\n\nend\n\nlemma leq_funI [intro?]: \"(\\<And>x. f x \\<sqsubseteq> g x) \\<Longrightarrow> f \\<sqsubseteq> g\"\n  by (unfold leq_fun_def) blast\n\nlemma leq_funD [dest?]: \"f \\<sqsubseteq> g \\<Longrightarrow> f x \\<sqsubseteq> g x\"\n  by (unfold leq_fun_def) blast\n\ninstance \"fun\" :: (type, quasi_order) quasi_order\nproof\n  fix f g h :: \"'a \\<Rightarrow> 'b::quasi_order\"\n  show \"f \\<sqsubseteq> f\"\n  proof\n    fix x show \"f x \\<sqsubseteq> f x\" ..\n  qed\n  assume fg: \"f \\<sqsubseteq> g\" and gh: \"g \\<sqsubseteq> h\"\n  show \"f \\<sqsubseteq> h\"\n  proof\n    fix x from fg have \"f x \\<sqsubseteq> g x\" ..\n    also from gh have \"\\<dots> \\<sqsubseteq> h x\" ..\n    finally show \"f x \\<sqsubseteq> h x\" .\n  qed\nqed\n\ninstance \"fun\" :: (type, partial_order) partial_order\nproof\n  fix f g :: \"'a \\<Rightarrow> 'b::partial_order\"\n  assume fg: \"f \\<sqsubseteq> g\" and gf: \"g \\<sqsubseteq> f\"\n  show \"f = g\"\n  proof\n    fix x from fg have \"f x \\<sqsubseteq> g x\" ..\n    also from gf have \"\\<dots> \\<sqsubseteq> f x\" ..\n    finally show \"f x = g x\" .\n  qed\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Lattice/Orders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8807970654616712, "lm_q1q2_score": 0.7919434729741348}}
{"text": "(*  \n  Title:    Random_Permutations.thy\n  Author:   Manuel Eberl, TU München\n\n  Random permutations and folding over them.\n  This provides the basic theory for the concept of doing something\n  in a random order, e.g. inserting elements from a fixed set into a \n  data structure in random order.\n*)\n\nsection \\<open>Random Permutations\\<close>\n\ntheory Random_Permutations\nimports \n  \"~~/src/HOL/Probability/Probability_Mass_Function\" \n  \"~~/src/HOL/Library/Multiset_Permutations\"\nbegin\n\ntext \\<open>\n  Choosing a set permutation (i.e. a distinct list with the same elements as the set)\n  uniformly at random is the same as first choosing the first element of the list\n  and then choosing the rest of the list as a permutation of the remaining set.\n\\<close>\nlemma random_permutation_of_set:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   \"pmf_of_set (permutations_of_set A) = \n             do {\n               x \\<leftarrow> pmf_of_set A;\n               xs \\<leftarrow> pmf_of_set (permutations_of_set (A - {x})); \n               return_pmf (x#xs)\n             }\" (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"permutations_of_set A = (\\<Union>x\\<in>A. op # x ` permutations_of_set (A - {x}))\"\n    by (simp add: permutations_of_set_nonempty)\n  also from assms have \"pmf_of_set \\<dots> = ?rhs\"\n    by (subst pmf_of_set_UN[where n = \"fact (card A - 1)\"])\n       (auto simp: card_image disjoint_family_on_def map_pmf_def [symmetric] map_pmf_of_set_inj)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  A generic fold function that takes a function, an initial state, and a set \n  and chooses a random order in which it then traverses the set in the same \n  fashion as a left fold over a list.\n    We first give a recursive definition.\n\\<close>\nfunction fold_random_permutation :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b pmf\" where\n  \"fold_random_permutation f x {} = return_pmf x\"\n| \"\\<not>finite A \\<Longrightarrow> fold_random_permutation f x A = return_pmf x\"\n| \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \n     fold_random_permutation f x A = \n       pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}))\"\nby (force, simp_all)\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(_,_,A). card A)\")\n  fix A :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and x :: 'b and y :: 'a\n  assume A: \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  then have \"card A > 0\" by (simp add: card_gt_0_iff)\n  with A show \"((f, f y x, A - {y}), f, x, A) \\<in> Wellfounded.measure (\\<lambda>(_, _, A). card A)\"\n    by simp\nqed simp_all\n\n\ntext \\<open>\n  We can now show that the above recursive definition is equivalent to \n  choosing a random set permutation and folding over it (in any direction).\n\\<close>\nlemma fold_random_permutation_foldl:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set A))\"\nusing assms\nproof (induction f x A rule: fold_random_permutation.induct [case_names empty infinite remove])\n  case (remove A f x)\n  from remove \n    have \"fold_random_permutation f x A = \n            pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}))\" by simp\n  also from remove\n    have \"\\<dots> = pmf_of_set A \\<bind> (\\<lambda>a. map_pmf (foldl (\\<lambda>x y. f y x) x)\n                 (map_pmf (op # a) (pmf_of_set (permutations_of_set (A - {a})))))\"\n      by (intro bind_pmf_cong) (simp_all add: pmf.map_comp o_def)\n  also from remove have \"\\<dots> = map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set A))\"\n    by (simp_all add: random_permutation_of_set map_bind_pmf map_pmf_def [symmetric])\n  finally show ?case .\nqed (simp_all add: pmf_of_set_singleton)\n\nlemma fold_random_permutation_foldr:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (\\<lambda>xs. foldr f xs x) (pmf_of_set (permutations_of_set A))\"\nproof -\n  have \"fold_random_permutation f x A =\n          map_pmf (foldl (\\<lambda>x y. f y x) x \\<circ> rev) (pmf_of_set (permutations_of_set A))\"\n    using assms by (subst fold_random_permutation_foldl [OF assms])\n                   (simp_all add: pmf.map_comp [symmetric] map_pmf_of_set_inj)\n  also have \"foldl (\\<lambda>x y. f y x) x \\<circ> rev = (\\<lambda>xs. foldr f xs x)\"\n    by (intro ext) (simp add: foldl_conv_foldr)\n  finally show ?thesis .\nqed\n\nlemma fold_random_permutation_fold:\n  assumes \"finite A\"\n  shows   \"fold_random_permutation f x A =\n             map_pmf (\\<lambda>xs. fold f xs x) (pmf_of_set (permutations_of_set A))\"\n  by (subst fold_random_permutation_foldl [OF assms], intro map_pmf_cong)\n     (simp_all add: foldl_conv_fold)\n     \nlemma fold_random_permutation_code [code]: \n  \"fold_random_permutation f x (set xs) =\n     map_pmf (foldl (\\<lambda>x y. f y x) x) (pmf_of_set (permutations_of_set (set xs)))\"\n  by (simp add: fold_random_permutation_foldl)\n\ntext \\<open>\n  We now introduce a slightly generalised version of the above fold \n  operation that does not simply return the result in the end, but applies\n  a monadic bind to it.\n    This may seem somewhat arbitrary, but it is a common use case, e.g. \n  in the Social Decision Scheme of Random Serial Dictatorship, where \n  voters narrow down a set of possible winners in a random order and \n  the winner is chosen from the remaining set uniformly at random.\n\\<close>\nfunction fold_bind_random_permutation \n    :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'c pmf) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'c pmf\" where\n  \"fold_bind_random_permutation f g x {} = g x\"\n| \"\\<not>finite A \\<Longrightarrow> fold_bind_random_permutation f g x A = g x\"\n| \"finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \n     fold_bind_random_permutation f g x A = \n       pmf_of_set A \\<bind> (\\<lambda>a. fold_bind_random_permutation f g (f a x) (A - {a}))\"\nby (force, simp_all)\ntermination proof (relation \"Wellfounded.measure (\\<lambda>(_,_,_,A). card A)\")\n  fix A :: \"'a set\" and f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and x :: 'b \n    and y :: 'a and g :: \"'b \\<Rightarrow> 'c pmf\"\n  assume A: \"finite A\" \"A \\<noteq> {}\" \"y \\<in> set_pmf (pmf_of_set A)\"\n  then have \"card A > 0\" by (simp add: card_gt_0_iff)\n  with A show \"((f, g, f y x, A - {y}), f, g, x, A) \\<in> Wellfounded.measure (\\<lambda>(_, _, _, A). card A)\"\n    by simp\nqed simp_all\n\ntext \\<open>\n  We now show that the recursive definition is equivalent to \n  a random fold followed by a monadic bind.\n\\<close>\nlemma fold_bind_random_permutation_altdef [code]:\n  \"fold_bind_random_permutation f g x A = fold_random_permutation f x A \\<bind> g\"\nproof (induction f x A rule: fold_random_permutation.induct [case_names empty infinite remove])\n  case (remove A f x)\n  from remove have \"pmf_of_set A \\<bind> (\\<lambda>a. fold_bind_random_permutation f g (f a x) (A - {a})) =\n                      pmf_of_set A \\<bind> (\\<lambda>a. fold_random_permutation f (f a x) (A - {a}) \\<bind> g)\"\n    by (intro bind_pmf_cong) simp_all\n  with remove show ?case by (simp add: bind_return_pmf bind_assoc_pmf)\nqed (simp_all add: bind_return_pmf)\n\n\ntext \\<open>\n  We can now derive the following nice monadic representations of the \n  combined fold-and-bind:\n\\<close>\nlemma fold_bind_random_permutation_foldl:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (foldl (\\<lambda>x y. f y x) x xs)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_foldl bind_return_pmf map_pmf_def)\n\nlemma fold_bind_random_permutation_foldr:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (foldr f xs x)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_foldr bind_return_pmf map_pmf_def)\n\nlemma fold_bind_random_permutation_fold:\n  assumes \"finite A\"\n  shows   \"fold_bind_random_permutation f g x A =\n             do {xs \\<leftarrow> pmf_of_set (permutations_of_set A); g (fold f xs x)}\"\n  using assms by (simp add: fold_bind_random_permutation_altdef bind_assoc_pmf\n                            fold_random_permutation_fold bind_return_pmf map_pmf_def)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Probability/Random_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297967961707, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.7916978670280258}}
{"text": "(* EXTRACT from HOL/ex/Primes.thy*)\n\n(*Euclid's algorithm \n  This material now appears AFTER that of Forward.thy *)\ntheory TPrimes imports Main begin\n\nfun gcd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"gcd m n = (if n=0 then m else gcd n (m mod n))\"\n\n\ntext \\<open>Now in Basic.thy!\n@{thm[display]\"dvd_def\"}\n\\rulename{dvd_def}\n\\<close>\n\n\n(*** Euclid's Algorithm ***)\n\nlemma gcd_0 [simp]: \"gcd m 0 = m\"\napply (simp)\ndone\n\nlemma gcd_non_0 [simp]: \"0<n \\<Longrightarrow> gcd m n = gcd n (m mod n)\"\napply (simp)\ndone\n\ndeclare gcd.simps [simp del]\n\n(*gcd(m,n) divides m and n.  The conjunctions don't seem provable separately*)\nlemma gcd_dvd_both: \"(gcd m n dvd m) \\<and> (gcd m n dvd n)\"\napply (induct_tac m n rule: gcd.induct)\n  \\<comment> \\<open>@{subgoals[display,indent=0,margin=65]}\\<close>\napply (case_tac \"n=0\")\ntxt\\<open>subgoals after the case tac\n@{subgoals[display,indent=0,margin=65]}\n\\<close>\napply (simp_all) \n  \\<comment> \\<open>@{subgoals[display,indent=0,margin=65]}\\<close>\nby (blast dest: dvd_mod_imp_dvd)\n\n\n\ntext \\<open>\n@{thm[display] dvd_mod_imp_dvd}\n\\rulename{dvd_mod_imp_dvd}\n\n@{thm[display] dvd_trans}\n\\rulename{dvd_trans}\n\\<close>\n\nlemmas gcd_dvd1 [iff] = gcd_dvd_both [THEN conjunct1]\nlemmas gcd_dvd2 [iff] = gcd_dvd_both [THEN conjunct2]\n\n\ntext \\<open>\n\\begin{quote}\n@{thm[display] gcd_dvd1}\n\\rulename{gcd_dvd1}\n\n@{thm[display] gcd_dvd2}\n\\rulename{gcd_dvd2}\n\\end{quote}\n\\<close>\n\n(*Maximality: for all m,n,k naturals, \n                if k divides m and k divides n then k divides gcd(m,n)*)\nlemma gcd_greatest [rule_format]:\n      \"k dvd m \\<longrightarrow> k dvd n \\<longrightarrow> k dvd gcd m n\"\napply (induct_tac m n rule: gcd.induct)\napply (case_tac \"n=0\")\ntxt\\<open>subgoals after the case tac\n@{subgoals[display,indent=0,margin=65]}\n\\<close>\napply (simp_all add: dvd_mod)\ndone\n\ntext \\<open>\n@{thm[display] dvd_mod}\n\\rulename{dvd_mod}\n\\<close>\n\n(*just checking the claim that case_tac \"n\" works too*)\nlemma \"k dvd m \\<longrightarrow> k dvd n \\<longrightarrow> k dvd gcd m n\"\napply (induct_tac m n rule: gcd.induct)\napply (case_tac \"n\")\napply (simp_all add: dvd_mod)\ndone\n\n\ntheorem gcd_greatest_iff [iff]: \n        \"(k dvd gcd m n) = (k dvd m \\<and> k dvd n)\"\nby (blast intro!: gcd_greatest intro: dvd_trans)\n\n\n(**** The material below was omitted from the book ****)\n\ndefinition is_gcd :: \"[nat,nat,nat] \\<Rightarrow> bool\" where        (*gcd as a relation*)\n    \"is_gcd p m n == p dvd m  \\<and>  p dvd n  \\<and>\n                     (\\<forall>d. d dvd m \\<and> d dvd n \\<longrightarrow> d dvd p)\"\n\n(*Function gcd yields the Greatest Common Divisor*)\nlemma is_gcd: \"is_gcd (gcd m n) m n\"\napply (simp add: is_gcd_def gcd_greatest)\ndone\n\n(*uniqueness of GCDs*)\nlemma is_gcd_unique: \"\\<lbrakk> is_gcd m a b; is_gcd n a b \\<rbrakk> \\<Longrightarrow> m=n\"\napply (simp add: is_gcd_def)\napply (blast intro: dvd_antisym)\ndone\n\n\ntext \\<open>\n@{thm[display] dvd_antisym}\n\\rulename{dvd_antisym}\n\n\\begin{isabelle}\nproof\\ (prove):\\ step\\ 1\\isanewline\n\\isanewline\ngoal\\ (lemma\\ is_gcd_unique):\\isanewline\n\\isasymlbrakk is_gcd\\ m\\ a\\ b;\\ is_gcd\\ n\\ a\\ b\\isasymrbrakk \\ \\isasymLongrightarrow \\ m\\ =\\ n\\isanewline\n\\ 1.\\ \\isasymlbrakk m\\ dvd\\ a\\ \\isasymand \\ m\\ dvd\\ b\\ \\isasymand \\ (\\isasymforall d.\\ d\\ dvd\\ a\\ \\isasymand \\ d\\ dvd\\ b\\ \\isasymlongrightarrow \\ d\\ dvd\\ m);\\isanewline\n\\ \\ \\ \\ \\ \\ \\ n\\ dvd\\ a\\ \\isasymand \\ n\\ dvd\\ b\\ \\isasymand \\ (\\isasymforall d.\\ d\\ dvd\\ a\\ \\isasymand \\ d\\ dvd\\ b\\ \\isasymlongrightarrow \\ d\\ dvd\\ n)\\isasymrbrakk \\isanewline\n\\ \\ \\ \\ \\isasymLongrightarrow \\ m\\ =\\ n\n\\end{isabelle}\n\\<close>\n\nlemma gcd_assoc: \"gcd (gcd k m) n = gcd k (gcd m n)\"\n  apply (rule is_gcd_unique)\n  apply (rule is_gcd)\n  apply (simp add: is_gcd_def)\n  apply (blast intro: dvd_trans)\n  done\n\ntext\\<open>\n\\begin{isabelle}\nproof\\ (prove):\\ step\\ 3\\isanewline\n\\isanewline\ngoal\\ (lemma\\ gcd_assoc):\\isanewline\ngcd\\ (gcd\\ (k,\\ m),\\ n)\\ =\\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\isanewline\n\\ 1.\\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\ dvd\\ k\\ \\isasymand \\isanewline\n\\ \\ \\ \\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\ dvd\\ m\\ \\isasymand \\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\ dvd\\ n\n\\end{isabelle}\n\\<close>\n\n\nlemma gcd_dvd_gcd_mult: \"gcd m n dvd gcd (k*m) n\"\n  apply (auto intro: dvd_trans [of _ m])\n  done\n\n(*This is half of the proof (by dvd_antisym) of*)\nlemma gcd_mult_cancel: \"gcd k n = 1 \\<Longrightarrow> gcd (k*m) n = gcd m n\"\n  oops\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/Rules/TPrimes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.7916573346654138}}
{"text": "(*  Title:      HOL/Library/Formal_Power_Series.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection{* A formalization of formal power series *}\n\ntheory Formal_Power_Series\nimports \"~~/src/HOL/Number_Theory/Binomial\"\nbegin\n\n\nsubsection {* The type of formal power series*}\n\ntypedef 'a fps = \"{f :: nat \\<Rightarrow> 'a. True}\"\n  morphisms fps_nth Abs_fps\n  by simp\n\nnotation fps_nth (infixl \"$\" 75)\n\nlemma expand_fps_eq: \"p = q \\<longleftrightarrow> (\\<forall>n. p $ n = q $ n)\"\n  by (simp add: fps_nth_inject [symmetric] fun_eq_iff)\n\nlemma fps_ext: \"(\\<And>n. p $ n = q $ n) \\<Longrightarrow> p = q\"\n  by (simp add: expand_fps_eq)\n\nlemma fps_nth_Abs_fps [simp]: \"Abs_fps f $ n = f n\"\n  by (simp add: Abs_fps_inverse)\n\ntext{* Definition of the basic elements 0 and 1 and the basic operations of addition,\n  negation and multiplication *}\n\ninstantiation fps :: (zero) zero\nbegin\n\ndefinition fps_zero_def:\n  \"0 = Abs_fps (\\<lambda>n. 0)\"\n\ninstance ..\nend\n\nlemma fps_zero_nth [simp]: \"0 $ n = 0\"\n  unfolding fps_zero_def by simp\n\ninstantiation fps :: (\"{one, zero}\") one\nbegin\n\ndefinition fps_one_def:\n  \"1 = Abs_fps (\\<lambda>n. if n = 0 then 1 else 0)\"\n\ninstance ..\nend\n\nlemma fps_one_nth [simp]: \"1 $ n = (if n = 0 then 1 else 0)\"\n  unfolding fps_one_def by simp\n\ninstantiation fps :: (plus) plus\nbegin\n\ndefinition fps_plus_def:\n  \"op + = (\\<lambda>f g. Abs_fps (\\<lambda>n. f $ n + g $ n))\"\n\ninstance ..\nend\n\nlemma fps_add_nth [simp]: \"(f + g) $ n = f $ n + g $ n\"\n  unfolding fps_plus_def by simp\n\ninstantiation fps :: (minus) minus\nbegin\n\ndefinition fps_minus_def:\n  \"op - = (\\<lambda>f g. Abs_fps (\\<lambda>n. f $ n - g $ n))\"\n\ninstance ..\nend\n\nlemma fps_sub_nth [simp]: \"(f - g) $ n = f $ n - g $ n\"\n  unfolding fps_minus_def by simp\n\ninstantiation fps :: (uminus) uminus\nbegin\n\ndefinition fps_uminus_def:\n  \"uminus = (\\<lambda>f. Abs_fps (\\<lambda>n. - (f $ n)))\"\n\ninstance ..\nend\n\nlemma fps_neg_nth [simp]: \"(- f) $ n = - (f $ n)\"\n  unfolding fps_uminus_def by simp\n\ninstantiation fps :: (\"{comm_monoid_add, times}\") times\nbegin\n\ndefinition fps_times_def:\n  \"op * = (\\<lambda>f g. Abs_fps (\\<lambda>n. \\<Sum>i=0..n. f $ i * g $ (n - i)))\"\n\ninstance ..\nend\n\nlemma fps_mult_nth: \"(f * g) $ n = (\\<Sum>i=0..n. f$i * g$(n - i))\"\n  unfolding fps_times_def by simp\n\ndeclare atLeastAtMost_iff [presburger]\ndeclare Bex_def [presburger]\ndeclare Ball_def [presburger]\n\nlemma mult_delta_left:\n  fixes x y :: \"'a::mult_zero\"\n  shows \"(if b then x else 0) * y = (if b then x * y else 0)\"\n  by simp\n\nlemma mult_delta_right:\n  fixes x y :: \"'a::mult_zero\"\n  shows \"x * (if b then y else 0) = (if b then x * y else 0)\"\n  by simp\n\nlemma cond_value_iff: \"f (if b then x else y) = (if b then f x else f y)\"\n  by auto\n\nlemma cond_application_beta: \"(if b then f else g) x = (if b then f x else g x)\"\n  by auto\n\nsubsection{* Formal power series form a commutative ring with unity, if the range of sequences\n  they represent is a commutative ring with unity*}\n\ninstance fps :: (semigroup_add) semigroup_add\nproof\n  fix a b c :: \"'a fps\"\n  show \"a + b + c = a + (b + c)\"\n    by (simp add: fps_ext add.assoc)\nqed\n\ninstance fps :: (ab_semigroup_add) ab_semigroup_add\nproof\n  fix a b :: \"'a fps\"\n  show \"a + b = b + a\"\n    by (simp add: fps_ext add.commute)\nqed\n\nlemma fps_mult_assoc_lemma:\n  fixes k :: nat\n    and f :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a::comm_monoid_add\"\n  shows \"(\\<Sum>j=0..k. \\<Sum>i=0..j. f i (j - i) (n - j)) =\n         (\\<Sum>j=0..k. \\<Sum>i=0..k - j. f j i (n - j - i))\"\n  by (induct k) (simp_all add: Suc_diff_le setsum.distrib add.assoc)\n\ninstance fps :: (semiring_0) semigroup_mult\nproof\n  fix a b c :: \"'a fps\"\n  show \"(a * b) * c = a * (b * c)\"\n  proof (rule fps_ext)\n    fix n :: nat\n    have \"(\\<Sum>j=0..n. \\<Sum>i=0..j. a$i * b$(j - i) * c$(n - j)) =\n          (\\<Sum>j=0..n. \\<Sum>i=0..n - j. a$j * b$i * c$(n - j - i))\"\n      by (rule fps_mult_assoc_lemma)\n    then show \"((a * b) * c) $ n = (a * (b * c)) $ n\"\n      by (simp add: fps_mult_nth setsum_right_distrib setsum_left_distrib mult.assoc)\n  qed\nqed\n\nlemma fps_mult_commute_lemma:\n  fixes n :: nat\n    and f :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a::comm_monoid_add\"\n  shows \"(\\<Sum>i=0..n. f i (n - i)) = (\\<Sum>i=0..n. f (n - i) i)\"\n  by (rule setsum.reindex_bij_witness[where i=\"op - n\" and j=\"op - n\"]) auto\n\ninstance fps :: (comm_semiring_0) ab_semigroup_mult\nproof\n  fix a b :: \"'a fps\"\n  show \"a * b = b * a\"\n  proof (rule fps_ext)\n    fix n :: nat\n    have \"(\\<Sum>i=0..n. a$i * b$(n - i)) = (\\<Sum>i=0..n. a$(n - i) * b$i)\"\n      by (rule fps_mult_commute_lemma)\n    then show \"(a * b) $ n = (b * a) $ n\"\n      by (simp add: fps_mult_nth mult.commute)\n  qed\nqed\n\ninstance fps :: (monoid_add) monoid_add\nproof\n  fix a :: \"'a fps\"\n  show \"0 + a = a\" by (simp add: fps_ext)\n  show \"a + 0 = a\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (comm_monoid_add) comm_monoid_add\nproof\n  fix a :: \"'a fps\"\n  show \"0 + a = a\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (semiring_1) monoid_mult\nproof\n  fix a :: \"'a fps\"\n  show \"1 * a = a\" by (simp add: fps_ext fps_mult_nth mult_delta_left setsum.delta)\n  show \"a * 1 = a\" by (simp add: fps_ext fps_mult_nth mult_delta_right setsum.delta')\nqed\n\ninstance fps :: (cancel_semigroup_add) cancel_semigroup_add\nproof\n  fix a b c :: \"'a fps\"\n  { assume \"a + b = a + c\" then show \"b = c\" by (simp add: expand_fps_eq) }\n  { assume \"b + a = c + a\" then show \"b = c\" by (simp add: expand_fps_eq) }\nqed\n\ninstance fps :: (cancel_ab_semigroup_add) cancel_ab_semigroup_add\nproof\n  fix a b c :: \"'a fps\"\n  assume \"a + b = a + c\"\n  then show \"b = c\" by (simp add: expand_fps_eq)\nqed\n\ninstance fps :: (cancel_comm_monoid_add) cancel_comm_monoid_add ..\n\ninstance fps :: (group_add) group_add\nproof\n  fix a b :: \"'a fps\"\n  show \"- a + a = 0\" by (simp add: fps_ext)\n  show \"a + - b = a - b\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (ab_group_add) ab_group_add\nproof\n  fix a b :: \"'a fps\"\n  show \"- a + a = 0\" by (simp add: fps_ext)\n  show \"a - b = a + - b\" by (simp add: fps_ext)\nqed\n\ninstance fps :: (zero_neq_one) zero_neq_one\n  by default (simp add: expand_fps_eq)\n\ninstance fps :: (semiring_0) semiring\nproof\n  fix a b c :: \"'a fps\"\n  show \"(a + b) * c = a * c + b * c\"\n    by (simp add: expand_fps_eq fps_mult_nth distrib_right setsum.distrib)\n  show \"a * (b + c) = a * b + a * c\"\n    by (simp add: expand_fps_eq fps_mult_nth distrib_left setsum.distrib)\nqed\n\ninstance fps :: (semiring_0) semiring_0\nproof\n  fix a :: \"'a fps\"\n  show \"0 * a = 0\" by (simp add: fps_ext fps_mult_nth)\n  show \"a * 0 = 0\" by (simp add: fps_ext fps_mult_nth)\nqed\n\ninstance fps :: (semiring_0_cancel) semiring_0_cancel ..\n\nsubsection {* Selection of the nth power of the implicit variable in the infinite sum*}\n\nlemma fps_nonzero_nth: \"f \\<noteq> 0 \\<longleftrightarrow> (\\<exists> n. f $n \\<noteq> 0)\"\n  by (simp add: expand_fps_eq)\n\nlemma fps_nonzero_nth_minimal: \"f \\<noteq> 0 \\<longleftrightarrow> (\\<exists>n. f $ n \\<noteq> 0 \\<and> (\\<forall>m < n. f $ m = 0))\"\nproof\n  let ?n = \"LEAST n. f $ n \\<noteq> 0\"\n  assume \"f \\<noteq> 0\"\n  then have \"\\<exists>n. f $ n \\<noteq> 0\"\n    by (simp add: fps_nonzero_nth)\n  then have \"f $ ?n \\<noteq> 0\"\n    by (rule LeastI_ex)\n  moreover have \"\\<forall>m<?n. f $ m = 0\"\n    by (auto dest: not_less_Least)\n  ultimately have \"f $ ?n \\<noteq> 0 \\<and> (\\<forall>m<?n. f $ m = 0)\" ..\n  then show \"\\<exists>n. f $ n \\<noteq> 0 \\<and> (\\<forall>m<n. f $ m = 0)\" ..\nnext\n  assume \"\\<exists>n. f $ n \\<noteq> 0 \\<and> (\\<forall>m<n. f $ m = 0)\"\n  then show \"f \\<noteq> 0\" by (auto simp add: expand_fps_eq)\nqed\n\nlemma fps_eq_iff: \"f = g \\<longleftrightarrow> (\\<forall>n. f $ n = g $n)\"\n  by (rule expand_fps_eq)\n\nlemma fps_setsum_nth: \"setsum f S $ n = setsum (\\<lambda>k. (f k) $ n) S\"\nproof (cases \"finite S\")\n  case True\n  then show ?thesis by (induct set: finite) auto\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nsubsection{* Injection of the basic ring elements and multiplication by scalars *}\n\ndefinition \"fps_const c = Abs_fps (\\<lambda>n. if n = 0 then c else 0)\"\n\nlemma fps_nth_fps_const [simp]: \"fps_const c $ n = (if n = 0 then c else 0)\"\n  unfolding fps_const_def by simp\n\nlemma fps_const_0_eq_0 [simp]: \"fps_const 0 = 0\"\n  by (simp add: fps_ext)\n\nlemma fps_const_1_eq_1 [simp]: \"fps_const 1 = 1\"\n  by (simp add: fps_ext)\n\nlemma fps_const_neg [simp]: \"- (fps_const (c::'a::ring)) = fps_const (- c)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_add [simp]: \"fps_const (c::'a::monoid_add) + fps_const d = fps_const (c + d)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_sub [simp]: \"fps_const (c::'a::group_add) - fps_const d = fps_const (c - d)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_mult[simp]: \"fps_const (c::'a::ring) * fps_const d = fps_const (c * d)\"\n  by (simp add: fps_eq_iff fps_mult_nth setsum.neutral)\n\nlemma fps_const_add_left: \"fps_const (c::'a::monoid_add) + f =\n    Abs_fps (\\<lambda>n. if n = 0 then c + f$0 else f$n)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_add_right: \"f + fps_const (c::'a::monoid_add) =\n    Abs_fps (\\<lambda>n. if n = 0 then f$0 + c else f$n)\"\n  by (simp add: fps_ext)\n\nlemma fps_const_mult_left: \"fps_const (c::'a::semiring_0) * f = Abs_fps (\\<lambda>n. c * f$n)\"\n  unfolding fps_eq_iff fps_mult_nth\n  by (simp add: fps_const_def mult_delta_left setsum.delta)\n\nlemma fps_const_mult_right: \"f * fps_const (c::'a::semiring_0) = Abs_fps (\\<lambda>n. f$n * c)\"\n  unfolding fps_eq_iff fps_mult_nth\n  by (simp add: fps_const_def mult_delta_right setsum.delta')\n\nlemma fps_mult_left_const_nth [simp]: \"(fps_const (c::'a::semiring_1) * f)$n = c* f$n\"\n  by (simp add: fps_mult_nth mult_delta_left setsum.delta)\n\nlemma fps_mult_right_const_nth [simp]: \"(f * fps_const (c::'a::semiring_1))$n = f$n * c\"\n  by (simp add: fps_mult_nth mult_delta_right setsum.delta')\n\nsubsection {* Formal power series form an integral domain*}\n\ninstance fps :: (ring) ring ..\n\ninstance fps :: (ring_1) ring_1\n  by (intro_classes, auto simp add: distrib_right)\n\ninstance fps :: (comm_ring_1) comm_ring_1\n  by (intro_classes, auto simp add: distrib_right)\n\ninstance fps :: (ring_no_zero_divisors) ring_no_zero_divisors\nproof\n  fix a b :: \"'a fps\"\n  assume a0: \"a \\<noteq> 0\" and b0: \"b \\<noteq> 0\"\n  then obtain i j where i: \"a$i\\<noteq>0\" \"\\<forall>k<i. a$k=0\" and j: \"b$j \\<noteq>0\" \"\\<forall>k<j. b$k =0\"\n    unfolding fps_nonzero_nth_minimal\n    by blast+\n  have \"(a * b) $ (i+j) = (\\<Sum>k=0..i+j. a$k * b$(i+j-k))\"\n    by (rule fps_mult_nth)\n  also have \"\\<dots> = (a$i * b$(i+j-i)) + (\\<Sum>k\\<in>{0..i+j}-{i}. a$k * b$(i+j-k))\"\n    by (rule setsum.remove) simp_all\n  also have \"(\\<Sum>k\\<in>{0..i+j}-{i}. a$k * b$(i+j-k)) = 0\"\n    proof (rule setsum.neutral [rule_format])\n      fix k assume \"k \\<in> {0..i+j} - {i}\"\n      then have \"k < i \\<or> i+j-k < j\" by auto\n      then show \"a$k * b$(i+j-k) = 0\" using i j by auto\n    qed\n  also have \"a$i * b$(i+j-i) + 0 = a$i * b$j\" by simp\n  also have \"a$i * b$j \\<noteq> 0\" using i j by simp\n  finally have \"(a*b) $ (i+j) \\<noteq> 0\" .\n  then show \"a*b \\<noteq> 0\" unfolding fps_nonzero_nth by blast\nqed\n\ninstance fps :: (ring_1_no_zero_divisors) ring_1_no_zero_divisors ..\n\ninstance fps :: (idom) idom ..\n\nlemma numeral_fps_const: \"numeral k = fps_const (numeral k)\"\n  by (induct k) (simp_all only: numeral.simps fps_const_1_eq_1\n    fps_const_add [symmetric])\n\nlemma neg_numeral_fps_const: \"- numeral k = fps_const (- numeral k)\"\n  by (simp only: numeral_fps_const fps_const_neg)\n\nsubsection{* The eXtractor series X*}\n\nlemma minus_one_power_iff: \"(- (1::'a::comm_ring_1)) ^ n = (if even n then 1 else - 1)\"\n  by (induct n) auto\n\ndefinition \"X = Abs_fps (\\<lambda>n. if n = 1 then 1 else 0)\"\n\nlemma X_mult_nth [simp]:\n  \"(X * (f :: 'a::semiring_1 fps)) $n = (if n = 0 then 0 else f $ (n - 1))\"\nproof (cases \"n = 0\")\n  case False\n  have \"(X * f) $n = (\\<Sum>i = 0..n. X $ i * f $ (n - i))\"\n    by (simp add: fps_mult_nth)\n  also have \"\\<dots> = f $ (n - 1)\"\n    using False by (simp add: X_def mult_delta_left setsum.delta)\n  finally show ?thesis using False by simp\nnext\n  case True\n  then show ?thesis by (simp add: fps_mult_nth X_def)\nqed\n\nlemma X_mult_right_nth[simp]:\n    \"((f :: 'a::comm_semiring_1 fps) * X) $n = (if n = 0 then 0 else f $ (n - 1))\"\n  by (metis X_mult_nth mult.commute)\n\nlemma X_power_iff: \"X^k = Abs_fps (\\<lambda>n. if n = k then 1::'a::comm_ring_1 else 0)\"\nproof (induct k)\n  case 0\n  then show ?case by (simp add: X_def fps_eq_iff)\nnext\n  case (Suc k)\n  {\n    fix m\n    have \"(X^Suc k) $ m = (if m = 0 then 0::'a else (X^k) $ (m - 1))\"\n      by (simp del: One_nat_def)\n    then have \"(X^Suc k) $ m = (if m = Suc k then 1::'a else 0)\"\n      using Suc.hyps by (auto cong del: if_weak_cong)\n  }\n  then show ?case by (simp add: fps_eq_iff)\nqed\n\nlemma X_power_mult_nth:\n    \"(X^k * (f :: 'a::comm_ring_1 fps)) $n = (if n < k then 0 else f $ (n - k))\"\n  apply (induct k arbitrary: n)\n  apply simp\n  unfolding power_Suc mult.assoc\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma X_power_mult_right_nth:\n    \"((f :: 'a::comm_ring_1 fps) * X^k) $n = (if n < k then 0 else f $ (n - k))\"\n  by (metis X_power_mult_nth mult.commute)\n\n\nsubsection{* Formal Power series form a metric space *}\n\ndefinition (in dist) \"ball x r = {y. dist y x < r}\"\n\ninstantiation fps :: (comm_ring_1) dist\nbegin\n\ndefinition\n  dist_fps_def: \"dist (a :: 'a fps) b =\n    (if (\\<exists>n. a$n \\<noteq> b$n) then inverse (2 ^ (LEAST n. a$n \\<noteq> b$n)) else 0)\"\n\nlemma dist_fps_ge0: \"dist (a :: 'a fps) b \\<ge> 0\"\n  by (simp add: dist_fps_def)\n\nlemma dist_fps_sym: \"dist (a :: 'a fps) b = dist b a\"\n  apply (auto simp add: dist_fps_def)\n  apply (rule cong[OF refl, where x=\"(\\<lambda>n. a $ n \\<noteq> b $ n)\"])\n  apply (rule ext)\n  apply auto\n  done\n\ninstance ..\n\nend\n\ninstantiation fps :: (comm_ring_1) metric_space\nbegin\n\ndefinition open_fps_def: \"open (S :: 'a fps set) = (\\<forall>a \\<in> S. \\<exists>r. r >0 \\<and> ball a r \\<subseteq> S)\"\n\ninstance\nproof\n  fix S :: \"'a fps set\"\n  show \"open S = (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S)\"\n    by (auto simp add: open_fps_def ball_def subset_eq)\nnext\n  {\n    fix a b :: \"'a fps\"\n    {\n      assume \"a = b\"\n      then have \"\\<not> (\\<exists>n. a $ n \\<noteq> b $ n)\" by simp\n      then have \"dist a b = 0\" by (simp add: dist_fps_def)\n    }\n    moreover\n    {\n      assume d: \"dist a b = 0\"\n      then have \"\\<forall>n. a$n = b$n\"\n        by - (rule ccontr, simp add: dist_fps_def)\n      then have \"a = b\" by (simp add: fps_eq_iff)\n    }\n    ultimately show \"dist a b =0 \\<longleftrightarrow> a = b\" by blast\n  }\n  note th = this\n  from th have th'[simp]: \"\\<And>a::'a fps. dist a a = 0\" by simp\n  fix a b c :: \"'a fps\"\n  {\n    assume \"a = b\"\n    then have \"dist a b = 0\" unfolding th .\n    then have \"dist a b \\<le> dist a c + dist b c\"\n      using dist_fps_ge0 [of a c] dist_fps_ge0 [of b c] by simp\n  }\n  moreover\n  {\n    assume \"c = a \\<or> c = b\"\n    then have \"dist a b \\<le> dist a c + dist b c\"\n      by (cases \"c = a\") (simp_all add: th dist_fps_sym)\n  }\n  moreover\n  {\n    assume ab: \"a \\<noteq> b\" and ac: \"a \\<noteq> c\" and bc: \"b \\<noteq> c\"\n    def n \\<equiv> \"\\<lambda>a b::'a fps. LEAST n. a$n \\<noteq> b$n\"\n    then have n': \"\\<And>m a b. m < n a b \\<Longrightarrow> a$m = b$m\"\n      by (auto dest: not_less_Least)\n\n    from ab ac bc\n    have dab: \"dist a b = inverse (2 ^ n a b)\"\n      and dac: \"dist a c = inverse (2 ^ n a c)\"\n      and dbc: \"dist b c = inverse (2 ^ n b c)\"\n      by (simp_all add: dist_fps_def n_def fps_eq_iff)\n    from ab ac bc have nz: \"dist a b \\<noteq> 0\" \"dist a c \\<noteq> 0\" \"dist b c \\<noteq> 0\"\n      unfolding th by simp_all\n    from nz have pos: \"dist a b > 0\" \"dist a c > 0\" \"dist b c > 0\"\n      using dist_fps_ge0[of a b] dist_fps_ge0[of a c] dist_fps_ge0[of b c]\n      by auto\n    have th1: \"\\<And>n. (2::real)^n >0\" by auto\n    {\n      assume h: \"dist a b > dist a c + dist b c\"\n      then have gt: \"dist a b > dist a c\" \"dist a b > dist b c\"\n        using pos by auto\n      from gt have gtn: \"n a b < n b c\" \"n a b < n a c\"\n        unfolding dab dbc dac by (auto simp add: th1)\n      from n'[OF gtn(2)] n'(1)[OF gtn(1)]\n      have \"a $ n a b = b $ n a b\" by simp\n      moreover have \"a $ n a b \\<noteq> b $ n a b\"\n         unfolding n_def by (rule LeastI_ex) (insert ab, simp add: fps_eq_iff)\n      ultimately have False by contradiction\n    }\n    then have \"dist a b \\<le> dist a c + dist b c\"\n      by (auto simp add: not_le[symmetric])\n  }\n  ultimately show \"dist a b \\<le> dist a c + dist b c\" by blast\nqed\n\nend\n\ntext{* The infinite sums and justification of the notation in textbooks*}\n\nlemma reals_power_lt_ex:\n  fixes x y :: real\n  assumes xp: \"x > 0\"\n    and y1: \"y > 1\"\n  shows \"\\<exists>k>0. (1/y)^k < x\"\nproof -\n  have yp: \"y > 0\"\n    using y1 by simp\n  from reals_Archimedean2[of \"max 0 (- log y x) + 1\"]\n  obtain k :: nat where k: \"real k > max 0 (- log y x) + 1\"\n    by blast\n  from k have kp: \"k > 0\"\n    by simp\n  from k have \"real k > - log y x\"\n    by simp\n  then have \"ln y * real k > - ln x\"\n    unfolding log_def\n    using ln_gt_zero_iff[OF yp] y1\n    by (simp add: minus_divide_left field_simps del: minus_divide_left[symmetric])\n  then have \"ln y * real k + ln x > 0\"\n    by simp\n  then have \"exp (real k * ln y + ln x) > exp 0\"\n    by (simp add: ac_simps)\n  then have \"y ^ k * x > 1\"\n    unfolding exp_zero exp_add exp_real_of_nat_mult exp_ln [OF xp] exp_ln [OF yp]\n    by simp\n  then have \"x > (1 / y)^k\" using yp\n    by (simp add: field_simps nonzero_power_divide)\n  then show ?thesis\n    using kp by blast\nqed\n\nlemma X_nth[simp]: \"X$n = (if n = 1 then 1 else 0)\"\n  by (simp add: X_def)\n\nlemma X_power_nth[simp]: \"(X^k) $n = (if n = k then 1 else 0::'a::comm_ring_1)\"\n  by (simp add: X_power_iff)\n\nlemma fps_sum_rep_nth: \"(setsum (\\<lambda>i. fps_const(a$i)*X^i) {0..m})$n =\n    (if n \\<le> m then a$n else 0::'a::comm_ring_1)\"\n  apply (auto simp add: fps_setsum_nth cond_value_iff cong del: if_weak_cong)\n  apply (simp add: setsum.delta')\n  done\n\nlemma fps_notation: \"(\\<lambda>n. setsum (\\<lambda>i. fps_const(a$i) * X^i) {0..n}) ----> a\"\n  (is \"?s ----> a\")\nproof -\n  {\n    fix r :: real\n    assume rp: \"r > 0\"\n    have th0: \"(2::real) > 1\" by simp\n    from reals_power_lt_ex[OF rp th0]\n    obtain n0 where n0: \"(1/2)^n0 < r\" \"n0 > 0\" by blast\n    {\n      fix n :: nat\n      assume nn0: \"n \\<ge> n0\"\n      then have thnn0: \"(1/2)^n \\<le> (1/2 :: real)^n0\"\n        by (auto intro: power_decreasing)\n      {\n        assume \"?s n = a\"\n        then have \"dist (?s n) a < r\"\n          unfolding dist_eq_0_iff[of \"?s n\" a, symmetric]\n          using rp by (simp del: dist_eq_0_iff)\n      }\n      moreover\n      {\n        assume neq: \"?s n \\<noteq> a\"\n        def k \\<equiv> \"LEAST i. ?s n $ i \\<noteq> a $ i\"\n        from neq have dth: \"dist (?s n) a = (1/2)^k\"\n          by (auto simp add: dist_fps_def inverse_eq_divide power_divide k_def fps_eq_iff)\n\n        from neq have kn: \"k > n\"\n          by (auto simp: fps_sum_rep_nth not_le k_def fps_eq_iff\n              split: split_if_asm intro: LeastI2_ex)\n        then have \"dist (?s n) a < (1/2)^n\"\n          unfolding dth by (auto intro: power_strict_decreasing)\n        also have \"\\<dots> \\<le> (1/2)^n0\"\n          using nn0 by (auto intro: power_decreasing)\n        also have \"\\<dots> < r\"\n          using n0 by simp\n        finally have \"dist (?s n) a < r\" .\n      }\n      ultimately have \"dist (?s n) a < r\"\n        by blast\n    }\n    then have \"\\<exists>n0. \\<forall> n \\<ge> n0. dist (?s n) a < r\"\n      by blast\n  }\n  then show ?thesis\n    unfolding LIMSEQ_def by blast\nqed\n\n\nsubsection{* Inverses of formal power series *}\n\ndeclare setsum.cong[fundef_cong]\n\ninstantiation fps :: (\"{comm_monoid_add, inverse, times, uminus}\") inverse\nbegin\n\nfun natfun_inverse:: \"'a fps \\<Rightarrow> nat \\<Rightarrow> 'a\"\nwhere\n  \"natfun_inverse f 0 = inverse (f$0)\"\n| \"natfun_inverse f n = - inverse (f$0) * setsum (\\<lambda>i. f$i * natfun_inverse f (n - i)) {1..n}\"\n\ndefinition\n  fps_inverse_def: \"inverse f = (if f $ 0 = 0 then 0 else Abs_fps (natfun_inverse f))\"\n\ndefinition\n  fps_divide_def: \"divide = (\\<lambda>(f::'a fps) g. f * inverse g)\"\n\ninstance ..\n\nend\n\nlemma fps_inverse_zero [simp]:\n  \"inverse (0 :: 'a::{comm_monoid_add,inverse,times,uminus} fps) = 0\"\n  by (simp add: fps_ext fps_inverse_def)\n\nlemma fps_inverse_one [simp]: \"inverse (1 :: 'a::{division_ring,zero_neq_one} fps) = 1\"\n  apply (auto simp add: expand_fps_eq fps_inverse_def)\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma inverse_mult_eq_1 [intro]:\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n  shows \"inverse f * f = 1\"\nproof -\n  have c: \"inverse f * f = f * inverse f\"\n    by (simp add: mult.commute)\n  from f0 have ifn: \"\\<And>n. inverse f $ n = natfun_inverse f n\"\n    by (simp add: fps_inverse_def)\n  from f0 have th0: \"(inverse f * f) $ 0 = 1\"\n    by (simp add: fps_mult_nth fps_inverse_def)\n  {\n    fix n :: nat\n    assume np: \"n > 0\"\n    from np have eq: \"{0..n} = {0} \\<union> {1 .. n}\"\n      by auto\n    have d: \"{0} \\<inter> {1 .. n} = {}\"\n      by auto\n    from f0 np have th0: \"- (inverse f $ n) =\n      (setsum (\\<lambda>i. f$i * natfun_inverse f (n - i)) {1..n}) / (f$0)\"\n      by (cases n) (simp_all add: divide_inverse fps_inverse_def)\n    from th0[symmetric, unfolded nonzero_divide_eq_eq[OF f0]]\n    have th1: \"setsum (\\<lambda>i. f$i * natfun_inverse f (n - i)) {1..n} = - (f$0) * (inverse f)$n\"\n      by (simp add: field_simps)\n    have \"(f * inverse f) $ n = (\\<Sum>i = 0..n. f $i * natfun_inverse f (n - i))\"\n      unfolding fps_mult_nth ifn ..\n    also have \"\\<dots> = f$0 * natfun_inverse f n + (\\<Sum>i = 1..n. f$i * natfun_inverse f (n-i))\"\n      by (simp add: eq)\n    also have \"\\<dots> = 0\"\n      unfolding th1 ifn by simp\n    finally have \"(inverse f * f)$n = 0\"\n      unfolding c .\n  }\n  with th0 show ?thesis\n    by (simp add: fps_eq_iff)\nqed\n\nlemma fps_inverse_0_iff[simp]: \"(inverse f)$0 = (0::'a::division_ring) \\<longleftrightarrow> f$0 = 0\"\n  by (simp add: fps_inverse_def nonzero_imp_inverse_nonzero)\n\nlemma fps_inverse_eq_0_iff[simp]: \"inverse f = (0:: ('a::field) fps) \\<longleftrightarrow> f $0 = 0\"\nproof -\n  {\n    assume \"f $ 0 = 0\"\n    then have \"inverse f = 0\"\n      by (simp add: fps_inverse_def)\n  }\n  moreover\n  {\n    assume h: \"inverse f = 0\"\n    assume c: \"f $0 \\<noteq> 0\"\n    from inverse_mult_eq_1[OF c] h have False\n      by simp\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma fps_inverse_idempotent[intro]:\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n  shows \"inverse (inverse f) = f\"\nproof -\n  from f0 have if0: \"inverse f $ 0 \\<noteq> 0\" by simp\n  from inverse_mult_eq_1[OF f0] inverse_mult_eq_1[OF if0]\n  have \"inverse f * f = inverse f * inverse (inverse f)\"\n    by (simp add: ac_simps)\n  then show ?thesis\n    using f0 unfolding mult_cancel_left by simp\nqed\n\nlemma fps_inverse_unique:\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n    and fg: \"f*g = 1\"\n  shows \"inverse f = g\"\nproof -\n  from inverse_mult_eq_1[OF f0] fg\n  have th0: \"inverse f * f = g * f\"\n    by (simp add: ac_simps)\n  then show ?thesis\n    using f0\n    unfolding mult_cancel_right\n    by (auto simp add: expand_fps_eq)\nqed\n\nlemma fps_inverse_gp: \"inverse (Abs_fps(\\<lambda>n. (1::'a::field)))\n    = Abs_fps (\\<lambda>n. if n= 0 then 1 else if n=1 then - 1 else 0)\"\n  apply (rule fps_inverse_unique)\n  apply simp\n  apply (simp add: fps_eq_iff fps_mult_nth)\n  apply clarsimp\nproof -\n  fix n :: nat\n  assume n: \"n > 0\"\n  let ?f = \"\\<lambda>i. if n = i then (1::'a) else if n - i = 1 then - 1 else 0\"\n  let ?g = \"\\<lambda>i. if i = n then 1 else if i=n - 1 then - 1 else 0\"\n  let ?h = \"\\<lambda>i. if i=n - 1 then - 1 else 0\"\n  have th1: \"setsum ?f {0..n} = setsum ?g {0..n}\"\n    by (rule setsum.cong) auto\n  have th2: \"setsum ?g {0..n - 1} = setsum ?h {0..n - 1}\"\n    apply (insert n)\n    apply (rule setsum.cong)\n    apply auto\n    done\n  have eq: \"{0 .. n} = {0.. n - 1} \\<union> {n}\"\n    by auto\n  from n have d: \"{0.. n - 1} \\<inter> {n} = {}\"\n    by auto\n  have f: \"finite {0.. n - 1}\" \"finite {n}\"\n    by auto\n  show \"setsum ?f {0..n} = 0\"\n    unfolding th1\n    apply (simp add: setsum.union_disjoint[OF f d, unfolded eq[symmetric]] del: One_nat_def)\n    unfolding th2\n    apply (simp add: setsum.delta)\n    done\nqed\n\n\nsubsection {* Formal Derivatives, and the MacLaurin theorem around 0 *}\n\ndefinition \"fps_deriv f = Abs_fps (\\<lambda>n. of_nat (n + 1) * f $ (n + 1))\"\n\nlemma fps_deriv_nth[simp]: \"fps_deriv f $ n = of_nat (n +1) * f $ (n + 1)\"\n  by (simp add: fps_deriv_def)\n\nlemma fps_deriv_linear[simp]:\n  \"fps_deriv (fps_const (a::'a::comm_semiring_1) * f + fps_const b * g) =\n    fps_const a * fps_deriv f + fps_const b * fps_deriv g\"\n  unfolding fps_eq_iff fps_add_nth  fps_const_mult_left fps_deriv_nth by (simp add: field_simps)\n\nlemma fps_deriv_mult[simp]:\n  fixes f :: \"'a::comm_ring_1 fps\"\n  shows \"fps_deriv (f * g) = f * fps_deriv g + fps_deriv f * g\"\nproof -\n  let ?D = \"fps_deriv\"\n  {\n    fix n :: nat\n    let ?Zn = \"{0 ..n}\"\n    let ?Zn1 = \"{0 .. n + 1}\"\n    let ?g = \"\\<lambda>i. of_nat (i+1) * g $ (i+1) * f $ (n - i) +\n        of_nat (i+1)* f $ (i+1) * g $ (n - i)\"\n    let ?h = \"\\<lambda>i. of_nat i * g $ i * f $ ((n+1) - i) +\n        of_nat i* f $ i * g $ ((n + 1) - i)\"\n    have s0: \"setsum (\\<lambda>i. of_nat i * f $ i * g $ (n + 1 - i)) ?Zn1 =\n      setsum (\\<lambda>i. of_nat (n + 1 - i) * f $ (n + 1 - i) * g $ i) ?Zn1\"\n       by (rule setsum.reindex_bij_witness[where i=\"op - (n + 1)\" and j=\"op - (n + 1)\"]) auto\n    have s1: \"setsum (\\<lambda>i. f $ i * g $ (n + 1 - i)) ?Zn1 =\n      setsum (\\<lambda>i. f $ (n + 1 - i) * g $ i) ?Zn1\"\n       by (rule setsum.reindex_bij_witness[where i=\"op - (n + 1)\" and j=\"op - (n + 1)\"]) auto\n    have \"(f * ?D g + ?D f * g)$n = (?D g * f + ?D f * g)$n\"\n      by (simp only: mult.commute)\n    also have \"\\<dots> = (\\<Sum>i = 0..n. ?g i)\"\n      by (simp add: fps_mult_nth setsum.distrib[symmetric])\n    also have \"\\<dots> = setsum ?h {0..n+1}\"\n      by (rule setsum.reindex_bij_witness_not_neutral\n            [where S'=\"{}\" and T'=\"{0}\" and j=\"Suc\" and i=\"\\<lambda>i. i - 1\"]) auto\n    also have \"\\<dots> = (fps_deriv (f * g)) $ n\"\n      apply (simp only: fps_deriv_nth fps_mult_nth setsum.distrib)\n      unfolding s0 s1\n      unfolding setsum.distrib[symmetric] setsum_right_distrib\n      apply (rule setsum.cong)\n      apply (auto simp add: of_nat_diff field_simps)\n      done\n    finally have \"(f * ?D g + ?D f * g) $ n = ?D (f*g) $ n\" .\n  }\n  then show ?thesis unfolding fps_eq_iff by auto\nqed\n\nlemma fps_deriv_X[simp]: \"fps_deriv X = 1\"\n  by (simp add: fps_deriv_def X_def fps_eq_iff)\n\nlemma fps_deriv_neg[simp]:\n  \"fps_deriv (- (f:: 'a::comm_ring_1 fps)) = - (fps_deriv f)\"\n  by (simp add: fps_eq_iff fps_deriv_def)\n\nlemma fps_deriv_add[simp]:\n  \"fps_deriv ((f:: 'a::comm_ring_1 fps) + g) = fps_deriv f + fps_deriv g\"\n  using fps_deriv_linear[of 1 f 1 g] by simp\n\nlemma fps_deriv_sub[simp]:\n  \"fps_deriv ((f:: 'a::comm_ring_1 fps) - g) = fps_deriv f - fps_deriv g\"\n  using fps_deriv_add [of f \"- g\"] by simp\n\nlemma fps_deriv_const[simp]: \"fps_deriv (fps_const c) = 0\"\n  by (simp add: fps_ext fps_deriv_def fps_const_def)\n\nlemma fps_deriv_mult_const_left[simp]:\n  \"fps_deriv (fps_const (c::'a::comm_ring_1) * f) = fps_const c * fps_deriv f\"\n  by simp\n\nlemma fps_deriv_0[simp]: \"fps_deriv 0 = 0\"\n  by (simp add: fps_deriv_def fps_eq_iff)\n\nlemma fps_deriv_1[simp]: \"fps_deriv 1 = 0\"\n  by (simp add: fps_deriv_def fps_eq_iff )\n\nlemma fps_deriv_mult_const_right[simp]:\n  \"fps_deriv (f * fps_const (c::'a::comm_ring_1)) = fps_deriv f * fps_const c\"\n  by simp\n\nlemma fps_deriv_setsum:\n  \"fps_deriv (setsum f S) = setsum (\\<lambda>i. fps_deriv (f i :: 'a::comm_ring_1 fps)) S\"\nproof (cases \"finite S\")\n  case False\n  then show ?thesis by simp\nnext\n  case True\n  show ?thesis by (induct rule: finite_induct [OF True]) simp_all\nqed\n\nlemma fps_deriv_eq_0_iff [simp]:\n  \"fps_deriv f = 0 \\<longleftrightarrow> f = fps_const (f$0 :: 'a::{idom,semiring_char_0})\"\nproof -\n  {\n    assume \"f = fps_const (f$0)\"\n    then have \"fps_deriv f = fps_deriv (fps_const (f$0))\" by simp\n    then have \"fps_deriv f = 0\" by simp\n  }\n  moreover\n  {\n    assume z: \"fps_deriv f = 0\"\n    then have \"\\<forall>n. (fps_deriv f)$n = 0\" by simp\n    then have \"\\<forall>n. f$(n+1) = 0\" by (simp del: of_nat_Suc of_nat_add One_nat_def)\n    then have \"f = fps_const (f$0)\"\n      apply (clarsimp simp add: fps_eq_iff fps_const_def)\n      apply (erule_tac x=\"n - 1\" in allE)\n      apply simp\n      done\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma fps_deriv_eq_iff:\n  fixes f :: \"'a::{idom,semiring_char_0} fps\"\n  shows \"fps_deriv f = fps_deriv g \\<longleftrightarrow> (f = fps_const(f$0 - g$0) + g)\"\nproof -\n  have \"fps_deriv f = fps_deriv g \\<longleftrightarrow> fps_deriv (f - g) = 0\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> f - g = fps_const ((f - g) $ 0)\"\n    unfolding fps_deriv_eq_0_iff ..\n  finally show ?thesis by (simp add: field_simps)\nqed\n\nlemma fps_deriv_eq_iff_ex:\n  \"(fps_deriv f = fps_deriv g) \\<longleftrightarrow> (\\<exists>c::'a::{idom,semiring_char_0}. f = fps_const c + g)\"\n  by (auto simp: fps_deriv_eq_iff)\n\n\nfun fps_nth_deriv :: \"nat \\<Rightarrow> 'a::semiring_1 fps \\<Rightarrow> 'a fps\"\nwhere\n  \"fps_nth_deriv 0 f = f\"\n| \"fps_nth_deriv (Suc n) f = fps_nth_deriv n (fps_deriv f)\"\n\nlemma fps_nth_deriv_commute: \"fps_nth_deriv (Suc n) f = fps_deriv (fps_nth_deriv n f)\"\n  by (induct n arbitrary: f) auto\n\nlemma fps_nth_deriv_linear[simp]:\n  \"fps_nth_deriv n (fps_const (a::'a::comm_semiring_1) * f + fps_const b * g) =\n    fps_const a * fps_nth_deriv n f + fps_const b * fps_nth_deriv n g\"\n  by (induct n arbitrary: f g) (auto simp add: fps_nth_deriv_commute)\n\nlemma fps_nth_deriv_neg[simp]:\n  \"fps_nth_deriv n (- (f :: 'a::comm_ring_1 fps)) = - (fps_nth_deriv n f)\"\n  by (induct n arbitrary: f) simp_all\n\nlemma fps_nth_deriv_add[simp]:\n  \"fps_nth_deriv n ((f :: 'a::comm_ring_1 fps) + g) = fps_nth_deriv n f + fps_nth_deriv n g\"\n  using fps_nth_deriv_linear[of n 1 f 1 g] by simp\n\nlemma fps_nth_deriv_sub[simp]:\n  \"fps_nth_deriv n ((f :: 'a::comm_ring_1 fps) - g) = fps_nth_deriv n f - fps_nth_deriv n g\"\n  using fps_nth_deriv_add [of n f \"- g\"] by simp\n\nlemma fps_nth_deriv_0[simp]: \"fps_nth_deriv n 0 = 0\"\n  by (induct n) simp_all\n\nlemma fps_nth_deriv_1[simp]: \"fps_nth_deriv n 1 = (if n = 0 then 1 else 0)\"\n  by (induct n) simp_all\n\nlemma fps_nth_deriv_const[simp]:\n  \"fps_nth_deriv n (fps_const c) = (if n = 0 then fps_const c else 0)\"\n  by (cases n) simp_all\n\nlemma fps_nth_deriv_mult_const_left[simp]:\n  \"fps_nth_deriv n (fps_const (c::'a::comm_ring_1) * f) = fps_const c * fps_nth_deriv n f\"\n  using fps_nth_deriv_linear[of n \"c\" f 0 0 ] by simp\n\nlemma fps_nth_deriv_mult_const_right[simp]:\n  \"fps_nth_deriv n (f * fps_const (c::'a::comm_ring_1)) = fps_nth_deriv n f * fps_const c\"\n  using fps_nth_deriv_linear[of n \"c\" f 0 0] by (simp add: mult.commute)\n\nlemma fps_nth_deriv_setsum:\n  \"fps_nth_deriv n (setsum f S) = setsum (\\<lambda>i. fps_nth_deriv n (f i :: 'a::comm_ring_1 fps)) S\"\nproof (cases \"finite S\")\n  case True\n  show ?thesis by (induct rule: finite_induct [OF True]) simp_all\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma fps_deriv_maclauren_0:\n  \"(fps_nth_deriv k (f :: 'a::comm_semiring_1 fps)) $ 0 = of_nat (fact k) * f $ k\"\n  by (induct k arbitrary: f) (auto simp add: field_simps of_nat_mult)\n\n\nsubsection {* Powers *}\n\nlemma fps_power_zeroth_eq_one: \"a$0 =1 \\<Longrightarrow> a^n $ 0 = (1::'a::semiring_1)\"\n  by (induct n) (auto simp add: expand_fps_eq fps_mult_nth)\n\nlemma fps_power_first_eq: \"(a :: 'a::comm_ring_1 fps) $ 0 =1 \\<Longrightarrow> a^n $ 1 = of_nat n * a$1\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  note h = Suc.hyps[OF `a$0 = 1`]\n  show ?case unfolding power_Suc fps_mult_nth\n    using h `a$0 = 1` fps_power_zeroth_eq_one[OF `a$0=1`]\n    by (simp add: field_simps)\nqed\n\nlemma startsby_one_power:\"a $ 0 = (1::'a::comm_ring_1) \\<Longrightarrow> a^n $ 0 = 1\"\n  by (induct n) (auto simp add: fps_mult_nth)\n\nlemma startsby_zero_power:\"a $0 = (0::'a::comm_ring_1) \\<Longrightarrow> n > 0 \\<Longrightarrow> a^n $0 = 0\"\n  by (induct n) (auto simp add: fps_mult_nth)\n\nlemma startsby_power:\"a $0 = (v::'a::comm_ring_1) \\<Longrightarrow> a^n $0 = v^n\"\n  by (induct n) (auto simp add: fps_mult_nth)\n\nlemma startsby_zero_power_iff[simp]: \"a^n $0 = (0::'a::idom) \\<longleftrightarrow> n \\<noteq> 0 \\<and> a$0 = 0\"\n  apply (rule iffI)\n  apply (induct n)\n  apply (auto simp add: fps_mult_nth)\n  apply (rule startsby_zero_power, simp_all)\n  done\n\nlemma startsby_zero_power_prefix:\n  assumes a0: \"a $0 = (0::'a::idom)\"\n  shows \"\\<forall>n < k. a ^ k $ n = 0\"\n  using a0\nproof (induct k rule: nat_less_induct)\n  fix k\n  assume H: \"\\<forall>m<k. a $0 =  0 \\<longrightarrow> (\\<forall>n<m. a ^ m $ n = 0)\" and a0: \"a $ 0 = 0\"\n  let ?ths = \"\\<forall>m<k. a ^ k $ m = 0\"\n  {\n    assume \"k = 0\"\n    then have ?ths by simp\n  }\n  moreover\n  {\n    fix l\n    assume k: \"k = Suc l\"\n    {\n      fix m\n      assume mk: \"m < k\"\n      {\n        assume \"m = 0\"\n        then have \"a^k $ m = 0\"\n          using startsby_zero_power[of a k] k a0 by simp\n      }\n      moreover\n      {\n        assume m0: \"m \\<noteq> 0\"\n        have \"a ^k $ m = (a^l * a) $m\"\n          by (simp add: k mult.commute)\n        also have \"\\<dots> = (\\<Sum>i = 0..m. a ^ l $ i * a $ (m - i))\"\n          by (simp add: fps_mult_nth)\n        also have \"\\<dots> = 0\"\n          apply (rule setsum.neutral)\n          apply auto\n          apply (case_tac \"x = m\")\n          using a0 apply simp\n          apply (rule H[rule_format])\n          using a0 k mk apply auto\n          done\n        finally have \"a^k $ m = 0\" .\n      }\n      ultimately have \"a^k $ m = 0\"\n        by blast\n    }\n    then have ?ths by blast\n  }\n  ultimately show ?ths\n    by (cases k) auto\nqed\n\nlemma startsby_zero_setsum_depends:\n  assumes a0: \"a $0 = (0::'a::idom)\"\n    and kn: \"n \\<ge> k\"\n  shows \"setsum (\\<lambda>i. (a ^ i)$k) {0 .. n} = setsum (\\<lambda>i. (a ^ i)$k) {0 .. k}\"\n  apply (rule setsum.mono_neutral_right)\n  using kn\n  apply auto\n  apply (rule startsby_zero_power_prefix[rule_format, OF a0])\n  apply arith\n  done\n\nlemma startsby_zero_power_nth_same:\n  assumes a0: \"a$0 = (0::'a::idom)\"\n  shows \"a^n $ n = (a$1) ^ n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"a ^ Suc n $ (Suc n) = (a^n * a)$(Suc n)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = setsum (\\<lambda>i. a^n$i * a $ (Suc n - i)) {0.. Suc n}\"\n    by (simp add: fps_mult_nth)\n  also have \"\\<dots> = setsum (\\<lambda>i. a^n$i * a $ (Suc n - i)) {n .. Suc n}\"\n    apply (rule setsum.mono_neutral_right)\n    apply simp\n    apply clarsimp\n    apply clarsimp\n    apply (rule startsby_zero_power_prefix[rule_format, OF a0])\n    apply arith\n    done\n  also have \"\\<dots> = a^n $ n * a$1\"\n    using a0 by simp\n  finally show ?case\n    using Suc.hyps by simp\nqed\n\nlemma fps_inverse_power:\n  fixes a :: \"'a::field fps\"\n  shows \"inverse (a^n) = inverse a ^ n\"\nproof -\n  {\n    assume a0: \"a$0 = 0\"\n    then have eq: \"inverse a = 0\"\n      by (simp add: fps_inverse_def)\n    {\n      assume \"n = 0\"\n      then have ?thesis by simp\n    }\n    moreover\n    {\n      assume n: \"n > 0\"\n      from startsby_zero_power[OF a0 n] eq a0 n have ?thesis\n        by (simp add: fps_inverse_def)\n    }\n    ultimately have ?thesis by blast\n  }\n  moreover\n  {\n    assume a0: \"a$0 \\<noteq> 0\"\n    have ?thesis\n      apply (rule fps_inverse_unique)\n      apply (simp add: a0)\n      unfolding power_mult_distrib[symmetric]\n      apply (rule ssubst[where t = \"a * inverse a\" and s= 1])\n      apply simp_all\n      apply (subst mult.commute)\n      apply (rule inverse_mult_eq_1[OF a0])\n      done\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma fps_deriv_power:\n  \"fps_deriv (a ^ n) = fps_const (of_nat n :: 'a::comm_ring_1) * fps_deriv a * a ^ (n - 1)\"\n  apply (induct n)\n  apply (auto simp add: field_simps fps_const_add[symmetric] simp del: fps_const_add)\n  apply (case_tac n)\n  apply (auto simp add: field_simps)\n  done\n\nlemma fps_inverse_deriv:\n  fixes a :: \"'a::field fps\"\n  assumes a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_deriv (inverse a) = - fps_deriv a * (inverse a)\\<^sup>2\"\nproof -\n  from inverse_mult_eq_1[OF a0]\n  have \"fps_deriv (inverse a * a) = 0\" by simp\n  then have \"inverse a * fps_deriv a + fps_deriv (inverse a) * a = 0\"\n    by simp\n  then have \"inverse a * (inverse a * fps_deriv a + fps_deriv (inverse a) * a) = 0\"\n    by simp\n  with inverse_mult_eq_1[OF a0]\n  have \"(inverse a)\\<^sup>2 * fps_deriv a + fps_deriv (inverse a) = 0\"\n    unfolding power2_eq_square\n    apply (simp add: field_simps)\n    apply (simp add: mult.assoc[symmetric])\n    done\n  then have \"(inverse a)\\<^sup>2 * fps_deriv a + fps_deriv (inverse a) - fps_deriv a * (inverse a)\\<^sup>2 =\n      0 - fps_deriv a * (inverse a)\\<^sup>2\"\n    by simp\n  then show \"fps_deriv (inverse a) = - fps_deriv a * (inverse a)\\<^sup>2\"\n    by (simp add: field_simps)\nqed\n\nlemma fps_inverse_mult:\n  fixes a :: \"'a::field fps\"\n  shows \"inverse (a * b) = inverse a * inverse b\"\nproof -\n  {\n    assume a0: \"a$0 = 0\"\n    then have ab0: \"(a*b)$0 = 0\" by (simp add: fps_mult_nth)\n    from a0 ab0 have th: \"inverse a = 0\" \"inverse (a*b) = 0\" by simp_all\n    have ?thesis unfolding th by simp\n  }\n  moreover\n  {\n    assume b0: \"b$0 = 0\"\n    then have ab0: \"(a*b)$0 = 0\" by (simp add: fps_mult_nth)\n    from b0 ab0 have th: \"inverse b = 0\" \"inverse (a*b) = 0\" by simp_all\n    have ?thesis unfolding th by simp\n  }\n  moreover\n  {\n    assume a0: \"a$0 \\<noteq> 0\" and b0: \"b$0 \\<noteq> 0\"\n    from a0 b0 have ab0:\"(a*b) $ 0 \\<noteq> 0\" by (simp  add: fps_mult_nth)\n    from inverse_mult_eq_1[OF ab0]\n    have \"inverse (a*b) * (a*b) * inverse a * inverse b = 1 * inverse a * inverse b\" by simp\n    then have \"inverse (a*b) * (inverse a * a) * (inverse b * b) = inverse a * inverse b\"\n      by (simp add: field_simps)\n    then have ?thesis using inverse_mult_eq_1[OF a0] inverse_mult_eq_1[OF b0] by simp\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma fps_inverse_deriv':\n  fixes a :: \"'a::field fps\"\n  assumes a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_deriv (inverse a) = - fps_deriv a / a\\<^sup>2\"\n  using fps_inverse_deriv[OF a0]\n  unfolding power2_eq_square fps_divide_def fps_inverse_mult\n  by simp\n\nlemma inverse_mult_eq_1':\n  assumes f0: \"f$0 \\<noteq> (0::'a::field)\"\n  shows \"f * inverse f= 1\"\n  by (metis mult.commute inverse_mult_eq_1 f0)\n\nlemma fps_divide_deriv:\n  fixes a :: \"'a::field fps\"\n  assumes a0: \"b$0 \\<noteq> 0\"\n  shows \"fps_deriv (a / b) = (fps_deriv a * b - a * fps_deriv b) / b\\<^sup>2\"\n  using fps_inverse_deriv[OF a0]\n  by (simp add: fps_divide_def field_simps\n    power2_eq_square fps_inverse_mult inverse_mult_eq_1'[OF a0])\n\n\nlemma fps_inverse_gp': \"inverse (Abs_fps (\\<lambda>n. 1::'a::field)) = 1 - X\"\n  by (simp add: fps_inverse_gp fps_eq_iff X_def)\n\nlemma fps_nth_deriv_X[simp]: \"fps_nth_deriv n X = (if n = 0 then X else if n=1 then 1 else 0)\"\n  by (cases n) simp_all\n\n\nlemma fps_inverse_X_plus1:\n  \"inverse (1 + X) = Abs_fps (\\<lambda>n. (- (1::'a::field)) ^ n)\" (is \"_ = ?r\")\nproof -\n  have eq: \"(1 + X) * ?r = 1\"\n    unfolding minus_one_power_iff\n    by (auto simp add: field_simps fps_eq_iff)\n  show ?thesis\n    by (auto simp add: eq intro: fps_inverse_unique)\nqed\n\n\nsubsection{* Integration *}\n\ndefinition fps_integral :: \"'a::field_char_0 fps \\<Rightarrow> 'a \\<Rightarrow> 'a fps\"\n  where \"fps_integral a a0 = Abs_fps (\\<lambda>n. if n = 0 then a0 else (a$(n - 1) / of_nat n))\"\n\nlemma fps_deriv_fps_integral: \"fps_deriv (fps_integral a a0) = a\"\n  unfolding fps_integral_def fps_deriv_def\n  by (simp add: fps_eq_iff del: of_nat_Suc)\n\nlemma fps_integral_linear:\n  \"fps_integral (fps_const a * f + fps_const b * g) (a*a0 + b*b0) =\n    fps_const a * fps_integral f a0 + fps_const b * fps_integral g b0\"\n  (is \"?l = ?r\")\nproof -\n  have \"fps_deriv ?l = fps_deriv ?r\"\n    by (simp add: fps_deriv_fps_integral)\n  moreover have \"?l$0 = ?r$0\"\n    by (simp add: fps_integral_def)\n  ultimately show ?thesis\n    unfolding fps_deriv_eq_iff by auto\nqed\n\n\nsubsection {* Composition of FPSs *}\n\ndefinition fps_compose :: \"'a::semiring_1 fps \\<Rightarrow> 'a fps \\<Rightarrow> 'a fps\" (infixl \"oo\" 55)\n  where \"a oo b = Abs_fps (\\<lambda>n. setsum (\\<lambda>i. a$i * (b^i$n)) {0..n})\"\n\nlemma fps_compose_nth: \"(a oo b)$n = setsum (\\<lambda>i. a$i * (b^i$n)) {0..n}\"\n  by (simp add: fps_compose_def)\n\nlemma fps_compose_X[simp]: \"a oo X = (a :: 'a::comm_ring_1 fps)\"\n  by (simp add: fps_ext fps_compose_def mult_delta_right setsum.delta')\n\nlemma fps_const_compose[simp]:\n  \"fps_const (a::'a::comm_ring_1) oo b = fps_const a\"\n  by (simp add: fps_eq_iff fps_compose_nth mult_delta_left setsum.delta)\n\nlemma numeral_compose[simp]: \"(numeral k :: 'a::comm_ring_1 fps) oo b = numeral k\"\n  unfolding numeral_fps_const by simp\n\nlemma neg_numeral_compose[simp]: \"(- numeral k :: 'a::comm_ring_1 fps) oo b = - numeral k\"\n  unfolding neg_numeral_fps_const by simp\n\nlemma X_fps_compose_startby0[simp]: \"a$0 = 0 \\<Longrightarrow> X oo a = (a :: 'a::comm_ring_1 fps)\"\n  by (simp add: fps_eq_iff fps_compose_def mult_delta_left setsum.delta not_le)\n\n\nsubsection {* Rules from Herbert Wilf's Generatingfunctionology*}\n\nsubsubsection {* Rule 1 *}\n  (* {a_{n+k}}_0^infty Corresponds to (f - setsum (\\<lambda>i. a_i * x^i))/x^h, for h>0*)\n\nlemma fps_power_mult_eq_shift:\n  \"X^Suc k * Abs_fps (\\<lambda>n. a (n + Suc k)) =\n    Abs_fps a - setsum (\\<lambda>i. fps_const (a i :: 'a::comm_ring_1) * X^i) {0 .. k}\"\n  (is \"?lhs = ?rhs\")\nproof -\n  { fix n :: nat\n    have \"?lhs $ n = (if n < Suc k then 0 else a n)\"\n      unfolding X_power_mult_nth by auto\n    also have \"\\<dots> = ?rhs $ n\"\n    proof (induct k)\n      case 0\n      then show ?case by (simp add: fps_setsum_nth)\n    next\n      case (Suc k)\n      note th = Suc.hyps[symmetric]\n      have \"(Abs_fps a - setsum (\\<lambda>i. fps_const (a i :: 'a) * X^i) {0 .. Suc k})$n =\n        (Abs_fps a - setsum (\\<lambda>i. fps_const (a i :: 'a) * X^i) {0 .. k} -\n          fps_const (a (Suc k)) * X^ Suc k) $ n\"\n        by (simp add: field_simps)\n      also have \"\\<dots> = (if n < Suc k then 0 else a n) - (fps_const (a (Suc k)) * X^ Suc k)$n\"\n        using th unfolding fps_sub_nth by simp\n      also have \"\\<dots> = (if n < Suc (Suc k) then 0 else a n)\"\n        unfolding X_power_mult_right_nth\n        apply (auto simp add: not_less fps_const_def)\n        apply (rule cong[of a a, OF refl])\n        apply arith\n        done\n      finally show ?case by simp\n    qed\n    finally have \"?lhs $ n = ?rhs $ n\" .\n  }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\n\nsubsubsection {* Rule 2*}\n\n  (* We can not reach the form of Wilf, but still near to it using rewrite rules*)\n  (* If f reprents {a_n} and P is a polynomial, then\n        P(xD) f represents {P(n) a_n}*)\n\ndefinition \"XD = op * X \\<circ> fps_deriv\"\n\nlemma XD_add[simp]:\"XD (a + b) = XD a + XD (b :: 'a::comm_ring_1 fps)\"\n  by (simp add: XD_def field_simps)\n\nlemma XD_mult_const[simp]:\"XD (fps_const (c::'a::comm_ring_1) * a) = fps_const c * XD a\"\n  by (simp add: XD_def field_simps)\n\nlemma XD_linear[simp]: \"XD (fps_const c * a + fps_const d * b) =\n    fps_const c * XD a + fps_const d * XD (b :: 'a::comm_ring_1 fps)\"\n  by simp\n\nlemma XDN_linear:\n  \"(XD ^^ n) (fps_const c * a + fps_const d * b) =\n    fps_const c * (XD ^^ n) a + fps_const d * (XD ^^ n) (b :: 'a::comm_ring_1 fps)\"\n  by (induct n) simp_all\n\nlemma fps_mult_X_deriv_shift: \"X* fps_deriv a = Abs_fps (\\<lambda>n. of_nat n* a$n)\"\n  by (simp add: fps_eq_iff)\n\n\nlemma fps_mult_XD_shift:\n  \"(XD ^^ k) (a :: 'a::comm_ring_1 fps) = Abs_fps (\\<lambda>n. (of_nat n ^ k) * a$n)\"\n  by (induct k arbitrary: a) (simp_all add: XD_def fps_eq_iff field_simps del: One_nat_def)\n\n\nsubsubsection {* Rule 3 is trivial and is given by @{text fps_times_def} *}\n\nsubsubsection {* Rule 5 --- summation and \"division\" by (1 - X) *}\n\nlemma fps_divide_X_minus1_setsum_lemma:\n  \"a = ((1::'a::comm_ring_1 fps) - X) * Abs_fps (\\<lambda>n. setsum (\\<lambda>i. a $ i) {0..n})\"\nproof -\n  let ?sa = \"Abs_fps (\\<lambda>n. setsum (\\<lambda>i. a $ i) {0..n})\"\n  have th0: \"\\<And>i. (1 - (X::'a fps)) $ i = (if i = 0 then 1 else if i = 1 then - 1 else 0)\"\n    by simp\n  {\n    fix n :: nat\n    {\n      assume \"n = 0\"\n      then have \"a $ n = ((1 - X) * ?sa) $ n\"\n        by (simp add: fps_mult_nth)\n    }\n    moreover\n    {\n      assume n0: \"n \\<noteq> 0\"\n      then have u: \"{0} \\<union> ({1} \\<union> {2..n}) = {0..n}\" \"{1} \\<union> {2..n} = {1..n}\"\n        \"{0..n - 1} \\<union> {n} = {0..n}\"\n        by (auto simp: set_eq_iff)\n      have d: \"{0} \\<inter> ({1} \\<union> {2..n}) = {}\" \"{1} \\<inter> {2..n} = {}\" \"{0..n - 1} \\<inter> {n} = {}\"\n        using n0 by simp_all\n      have f: \"finite {0}\" \"finite {1}\" \"finite {2 .. n}\"\n        \"finite {0 .. n - 1}\" \"finite {n}\" by simp_all\n      have \"((1 - X) * ?sa) $ n = setsum (\\<lambda>i. (1 - X)$ i * ?sa $ (n - i)) {0 .. n}\"\n        by (simp add: fps_mult_nth)\n      also have \"\\<dots> = a$n\"\n        unfolding th0\n        unfolding setsum.union_disjoint[OF f(1) finite_UnI[OF f(2,3)] d(1), unfolded u(1)]\n        unfolding setsum.union_disjoint[OF f(2) f(3) d(2)]\n        apply (simp)\n        unfolding setsum.union_disjoint[OF f(4,5) d(3), unfolded u(3)]\n        apply simp\n        done\n      finally have \"a$n = ((1 - X) * ?sa) $ n\"\n        by simp\n    }\n    ultimately have \"a$n = ((1 - X) * ?sa) $ n\"\n      by blast\n  }\n  then show ?thesis\n    unfolding fps_eq_iff by blast\nqed\n\nlemma fps_divide_X_minus1_setsum:\n  \"a /((1::'a::field fps) - X) = Abs_fps (\\<lambda>n. setsum (\\<lambda>i. a $ i) {0..n})\"\nproof -\n  let ?X = \"1 - (X::'a fps)\"\n  have th0: \"?X $ 0 \\<noteq> 0\"\n    by simp\n  have \"a /?X = ?X *  Abs_fps (\\<lambda>n::nat. setsum (op $ a) {0..n}) * inverse ?X\"\n    using fps_divide_X_minus1_setsum_lemma[of a, symmetric] th0\n    by (simp add: fps_divide_def mult.assoc)\n  also have \"\\<dots> = (inverse ?X * ?X) * Abs_fps (\\<lambda>n::nat. setsum (op $ a) {0..n}) \"\n    by (simp add: ac_simps)\n  finally show ?thesis\n    by (simp add: inverse_mult_eq_1[OF th0])\nqed\n\n\nsubsubsection{* Rule 4 in its more general form: generalizes Rule 3 for an arbitrary\n  finite product of FPS, also the relvant instance of powers of a FPS*}\n\ndefinition \"natpermute n k = {l :: nat list. length l = k \\<and> listsum l = n}\"\n\nlemma natlist_trivial_1: \"natpermute n 1 = {[n]}\"\n  apply (auto simp add: natpermute_def)\n  apply (case_tac x)\n  apply auto\n  done\n\nlemma append_natpermute_less_eq:\n  assumes \"xs @ ys \\<in> natpermute n k\"\n  shows \"listsum xs \\<le> n\"\n    and \"listsum ys \\<le> n\"\nproof -\n  from assms have \"listsum (xs @ ys) = n\"\n    by (simp add: natpermute_def)\n  then have \"listsum xs + listsum ys = n\"\n    by simp\n  then show \"listsum xs \\<le> n\" and \"listsum ys \\<le> n\"\n    by simp_all\nqed\n\nlemma natpermute_split:\n  assumes \"h \\<le> k\"\n  shows \"natpermute n k =\n    (\\<Union>m \\<in>{0..n}. {l1 @ l2 |l1 l2. l1 \\<in> natpermute m h \\<and> l2 \\<in> natpermute (n - m) (k - h)})\"\n  (is \"?L = ?R\" is \"?L = (\\<Union>m \\<in>{0..n}. ?S m)\")\nproof -\n  {\n    fix l\n    assume l: \"l \\<in> ?R\"\n    from l obtain m xs ys where h: \"m \\<in> {0..n}\"\n      and xs: \"xs \\<in> natpermute m h\"\n      and ys: \"ys \\<in> natpermute (n - m) (k - h)\"\n      and leq: \"l = xs@ys\" by blast\n    from xs have xs': \"listsum xs = m\"\n      by (simp add: natpermute_def)\n    from ys have ys': \"listsum ys = n - m\"\n      by (simp add: natpermute_def)\n    have \"l \\<in> ?L\" using leq xs ys h\n      apply (clarsimp simp add: natpermute_def)\n      unfolding xs' ys'\n      using assms xs ys\n      unfolding natpermute_def\n      apply simp\n      done\n  }\n  moreover\n  {\n    fix l\n    assume l: \"l \\<in> natpermute n k\"\n    let ?xs = \"take h l\"\n    let ?ys = \"drop h l\"\n    let ?m = \"listsum ?xs\"\n    from l have ls: \"listsum (?xs @ ?ys) = n\"\n      by (simp add: natpermute_def)\n    have xs: \"?xs \\<in> natpermute ?m h\" using l assms\n      by (simp add: natpermute_def)\n    have l_take_drop: \"listsum l = listsum (take h l @ drop h l)\"\n      by simp\n    then have ys: \"?ys \\<in> natpermute (n - ?m) (k - h)\"\n      using l assms ls by (auto simp add: natpermute_def simp del: append_take_drop_id)\n    from ls have m: \"?m \\<in> {0..n}\"\n      by (simp add: l_take_drop del: append_take_drop_id)\n    from xs ys ls have \"l \\<in> ?R\"\n      apply auto\n      apply (rule bexI [where x = \"?m\"])\n      apply (rule exI [where x = \"?xs\"])\n      apply (rule exI [where x = \"?ys\"])\n      using ls l\n      apply (auto simp add: natpermute_def l_take_drop simp del: append_take_drop_id)\n      apply simp\n      done\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma natpermute_0: \"natpermute n 0 = (if n = 0 then {[]} else {})\"\n  by (auto simp add: natpermute_def)\n\nlemma natpermute_0'[simp]: \"natpermute 0 k = (if k = 0 then {[]} else {replicate k 0})\"\n  apply (auto simp add: set_replicate_conv_if natpermute_def)\n  apply (rule nth_equalityI)\n  apply simp_all\n  done\n\nlemma natpermute_finite: \"finite (natpermute n k)\"\nproof (induct k arbitrary: n)\n  case 0\n  then show ?case\n    apply (subst natpermute_split[of 0 0, simplified])\n    apply (simp add: natpermute_0)\n    done\nnext\n  case (Suc k)\n  then show ?case unfolding natpermute_split [of k \"Suc k\", simplified]\n    apply -\n    apply (rule finite_UN_I)\n    apply simp\n    unfolding One_nat_def[symmetric] natlist_trivial_1\n    apply simp\n    done\nqed\n\nlemma natpermute_contain_maximal:\n  \"{xs \\<in> natpermute n (k+1). n \\<in> set xs} = UNION {0 .. k} (\\<lambda>i. {(replicate (k+1) 0) [i:=n]})\"\n  (is \"?A = ?B\")\nproof -\n  {\n    fix xs\n    assume H: \"xs \\<in> natpermute n (k+1)\" and n: \"n \\<in> set xs\"\n    from n obtain i where i: \"i \\<in> {0.. k}\" \"xs!i = n\" using H\n      unfolding in_set_conv_nth by (auto simp add: less_Suc_eq_le natpermute_def)\n    have eqs: \"({0..k} - {i}) \\<union> {i} = {0..k}\"\n      using i by auto\n    have f: \"finite({0..k} - {i})\" \"finite {i}\"\n      by auto\n    have d: \"({0..k} - {i}) \\<inter> {i} = {}\"\n      using i by auto\n    from H have \"n = setsum (nth xs) {0..k}\"\n      apply (simp add: natpermute_def)\n      apply (auto simp add: atLeastLessThanSuc_atLeastAtMost listsum_setsum_nth)\n      done\n    also have \"\\<dots> = n + setsum (nth xs) ({0..k} - {i})\"\n      unfolding setsum.union_disjoint[OF f d, unfolded eqs] using i by simp\n    finally have zxs: \"\\<forall> j\\<in> {0..k} - {i}. xs!j = 0\"\n      by auto\n    from H have xsl: \"length xs = k+1\"\n      by (simp add: natpermute_def)\n    from i have i': \"i < length (replicate (k+1) 0)\"   \"i < k+1\"\n      unfolding length_replicate by presburger+\n    have \"xs = replicate (k+1) 0 [i := n]\"\n      apply (rule nth_equalityI)\n      unfolding xsl length_list_update length_replicate\n      apply simp\n      apply clarify\n      unfolding nth_list_update[OF i'(1)]\n      using i zxs\n      apply (case_tac \"ia = i\")\n      apply (auto simp del: replicate.simps)\n      done\n    then have \"xs \\<in> ?B\" using i by blast\n  }\n  moreover\n  {\n    fix i\n    assume i: \"i \\<in> {0..k}\"\n    let ?xs = \"replicate (k+1) 0 [i:=n]\"\n    have nxs: \"n \\<in> set ?xs\"\n      apply (rule set_update_memI)\n      using i apply simp\n      done\n    have xsl: \"length ?xs = k+1\"\n      by (simp only: length_replicate length_list_update)\n    have \"listsum ?xs = setsum (nth ?xs) {0..<k+1}\"\n      unfolding listsum_setsum_nth xsl ..\n    also have \"\\<dots> = setsum (\\<lambda>j. if j = i then n else 0) {0..< k+1}\"\n      by (rule setsum.cong) (simp_all del: replicate.simps)\n    also have \"\\<dots> = n\" using i by (simp add: setsum.delta)\n    finally have \"?xs \\<in> natpermute n (k+1)\"\n      using xsl unfolding natpermute_def mem_Collect_eq by blast\n    then have \"?xs \\<in> ?A\"\n      using nxs  by blast\n  }\n  ultimately show ?thesis by auto\nqed\n\ntext {* The general form *}\nlemma fps_setprod_nth:\n  fixes m :: nat\n    and a :: \"nat \\<Rightarrow> 'a::comm_ring_1 fps\"\n  shows \"(setprod a {0 .. m}) $ n =\n    setsum (\\<lambda>v. setprod (\\<lambda>j. (a j) $ (v!j)) {0..m}) (natpermute n (m+1))\"\n  (is \"?P m n\")\nproof (induct m arbitrary: n rule: nat_less_induct)\n  fix m n assume H: \"\\<forall>m' < m. \\<forall>n. ?P m' n\"\n  show \"?P m n\"\n  proof (cases m)\n    case 0\n    then show ?thesis\n      apply simp\n      unfolding natlist_trivial_1[where n = n, unfolded One_nat_def]\n      apply simp\n      done\n  next\n    case (Suc k)\n    then have km: \"k < m\" by arith\n    have u0: \"{0 .. k} \\<union> {m} = {0..m}\"\n      using Suc by (simp add: set_eq_iff) presburger\n    have f0: \"finite {0 .. k}\" \"finite {m}\" by auto\n    have d0: \"{0 .. k} \\<inter> {m} = {}\" using Suc by auto\n    have \"(setprod a {0 .. m}) $ n = (setprod a {0 .. k} * a m) $ n\"\n      unfolding setprod.union_disjoint[OF f0 d0, unfolded u0] by simp\n    also have \"\\<dots> = (\\<Sum>i = 0..n. (\\<Sum>v\\<in>natpermute i (k + 1). \\<Prod>j\\<in>{0..k}. a j $ v ! j) * a m $ (n - i))\"\n      unfolding fps_mult_nth H[rule_format, OF km] ..\n    also have \"\\<dots> = (\\<Sum>v\\<in>natpermute n (m + 1). \\<Prod>j\\<in>{0..m}. a j $ v ! j)\"\n      apply (simp add: Suc)\n      unfolding natpermute_split[of m \"m + 1\", simplified, of n,\n        unfolded natlist_trivial_1[unfolded One_nat_def] Suc]\n      apply (subst setsum.UNION_disjoint)\n      apply simp\n      apply simp\n      unfolding image_Collect[symmetric]\n      apply clarsimp\n      apply (rule finite_imageI)\n      apply (rule natpermute_finite)\n      apply (clarsimp simp add: set_eq_iff)\n      apply auto\n      apply (rule setsum.cong)\n      apply (rule refl)\n      unfolding setsum_left_distrib\n      apply (rule sym)\n      apply (rule_tac l = \"\\<lambda>xs. xs @ [n - x]\" in setsum.reindex_cong)\n      apply (simp add: inj_on_def)\n      apply auto\n      unfolding setprod.union_disjoint[OF f0 d0, unfolded u0, unfolded Suc]\n      apply (clarsimp simp add: natpermute_def nth_append)\n      done\n    finally show ?thesis .\n  qed\nqed\n\ntext{* The special form for powers *}\nlemma fps_power_nth_Suc:\n  fixes m :: nat\n    and a :: \"'a::comm_ring_1 fps\"\n  shows \"(a ^ Suc m)$n = setsum (\\<lambda>v. setprod (\\<lambda>j. a $ (v!j)) {0..m}) (natpermute n (m+1))\"\nproof -\n  have th0: \"a^Suc m = setprod (\\<lambda>i. a) {0..m}\"\n    by (simp add: setprod_constant)\n  show ?thesis unfolding th0 fps_setprod_nth ..\nqed\n\nlemma fps_power_nth:\n  fixes m :: nat\n    and a :: \"'a::comm_ring_1 fps\"\n  shows \"(a ^m)$n =\n    (if m=0 then 1$n else setsum (\\<lambda>v. setprod (\\<lambda>j. a $ (v!j)) {0..m - 1}) (natpermute n m))\"\n  by (cases m) (simp_all add: fps_power_nth_Suc del: power_Suc)\n\nlemma fps_nth_power_0:\n  fixes m :: nat\n    and a :: \"'a::comm_ring_1 fps\"\n  shows \"(a ^m)$0 = (a$0) ^ m\"\nproof (cases m)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc n)\n  then have c: \"m = card {0..n}\" by simp\n  have \"(a ^m)$0 = setprod (\\<lambda>i. a$0) {0..n}\"\n    by (simp add: Suc fps_power_nth del: replicate.simps power_Suc)\n  also have \"\\<dots> = (a$0) ^ m\"\n   unfolding c by (rule setprod_constant) simp\n finally show ?thesis .\nqed\n\nlemma fps_compose_inj_right:\n  assumes a0: \"a$0 = (0::'a::idom)\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"(b oo a = c oo a) \\<longleftrightarrow> b = c\"\n  (is \"?lhs \\<longleftrightarrow>?rhs\")\nproof\n  assume ?rhs\n  then show \"?lhs\" by simp\nnext\n  assume h: ?lhs\n  {\n    fix n\n    have \"b$n = c$n\"\n    proof (induct n rule: nat_less_induct)\n      fix n\n      assume H: \"\\<forall>m<n. b$m = c$m\"\n      {\n        assume n0: \"n=0\"\n        from h have \"(b oo a)$n = (c oo a)$n\" by simp\n        then have \"b$n = c$n\" using n0 by (simp add: fps_compose_nth)\n      }\n      moreover\n      {\n        fix n1 assume n1: \"n = Suc n1\"\n        have f: \"finite {0 .. n1}\" \"finite {n}\" by simp_all\n        have eq: \"{0 .. n1} \\<union> {n} = {0 .. n}\" using n1 by auto\n        have d: \"{0 .. n1} \\<inter> {n} = {}\" using n1 by auto\n        have seq: \"(\\<Sum>i = 0..n1. b $ i * a ^ i $ n) = (\\<Sum>i = 0..n1. c $ i * a ^ i $ n)\"\n          apply (rule setsum.cong)\n          using H n1\n          apply auto\n          done\n        have th0: \"(b oo a) $n = (\\<Sum>i = 0..n1. c $ i * a ^ i $ n) + b$n * (a$1)^n\"\n          unfolding fps_compose_nth setsum.union_disjoint[OF f d, unfolded eq] seq\n          using startsby_zero_power_nth_same[OF a0]\n          by simp\n        have th1: \"(c oo a) $n = (\\<Sum>i = 0..n1. c $ i * a ^ i $ n) + c$n * (a$1)^n\"\n          unfolding fps_compose_nth setsum.union_disjoint[OF f d, unfolded eq]\n          using startsby_zero_power_nth_same[OF a0]\n          by simp\n        from h[unfolded fps_eq_iff, rule_format, of n] th0 th1 a1\n        have \"b$n = c$n\" by auto\n      }\n      ultimately show \"b$n = c$n\" by (cases n) auto\n    qed}\n  then show ?rhs by (simp add: fps_eq_iff)\nqed\n\n\nsubsection {* Radicals *}\n\ndeclare setprod.cong [fundef_cong]\n\nfunction radical :: \"(nat \\<Rightarrow> 'a \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a::field fps \\<Rightarrow> nat \\<Rightarrow> 'a\"\nwhere\n  \"radical r 0 a 0 = 1\"\n| \"radical r 0 a (Suc n) = 0\"\n| \"radical r (Suc k) a 0 = r (Suc k) (a$0)\"\n| \"radical r (Suc k) a (Suc n) =\n    (a$ Suc n - setsum (\\<lambda>xs. setprod (\\<lambda>j. radical r (Suc k) a (xs ! j)) {0..k})\n      {xs. xs \\<in> natpermute (Suc n) (Suc k) \\<and> Suc n \\<notin> set xs}) /\n    (of_nat (Suc k) * (radical r (Suc k) a 0)^k)\"\n  by pat_completeness auto\n\ntermination radical\nproof\n  let ?R = \"measure (\\<lambda>(r, k, a, n). n)\"\n  {\n    show \"wf ?R\" by auto\n  next\n    fix r k a n xs i\n    assume xs: \"xs \\<in> {xs \\<in> natpermute (Suc n) (Suc k). Suc n \\<notin> set xs}\" and i: \"i \\<in> {0..k}\"\n    {\n      assume c: \"Suc n \\<le> xs ! i\"\n      from xs i have \"xs !i \\<noteq> Suc n\"\n        by (auto simp add: in_set_conv_nth natpermute_def)\n      with c have c': \"Suc n < xs!i\" by arith\n      have fths: \"finite {0 ..< i}\" \"finite {i}\" \"finite {i+1..<Suc k}\"\n        by simp_all\n      have d: \"{0 ..< i} \\<inter> ({i} \\<union> {i+1 ..< Suc k}) = {}\" \"{i} \\<inter> {i+1..< Suc k} = {}\"\n        by auto\n      have eqs: \"{0..<Suc k} = {0 ..< i} \\<union> ({i} \\<union> {i+1 ..< Suc k})\"\n        using i by auto\n      from xs have \"Suc n = listsum xs\"\n        by (simp add: natpermute_def)\n      also have \"\\<dots> = setsum (nth xs) {0..<Suc k}\" using xs\n        by (simp add: natpermute_def listsum_setsum_nth)\n      also have \"\\<dots> = xs!i + setsum (nth xs) {0..<i} + setsum (nth xs) {i+1..<Suc k}\"\n        unfolding eqs  setsum.union_disjoint[OF fths(1) finite_UnI[OF fths(2,3)] d(1)]\n        unfolding setsum.union_disjoint[OF fths(2) fths(3) d(2)]\n        by simp\n      finally have False using c' by simp\n    }\n    then show \"((r, Suc k, a, xs!i), r, Suc k, a, Suc n) \\<in> ?R\"\n      apply auto\n      apply (metis not_less)\n      done\n  next\n    fix r k a n\n    show \"((r, Suc k, a, 0), r, Suc k, a, Suc n) \\<in> ?R\" by simp\n  }\nqed\n\ndefinition \"fps_radical r n a = Abs_fps (radical r n a)\"\n\nlemma fps_radical0[simp]: \"fps_radical r 0 a = 1\"\n  apply (auto simp add: fps_eq_iff fps_radical_def)\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma fps_radical_nth_0[simp]: \"fps_radical r n a $ 0 = (if n=0 then 1 else r n (a$0))\"\n  by (cases n) (simp_all add: fps_radical_def)\n\nlemma fps_radical_power_nth[simp]:\n  assumes r: \"(r k (a$0)) ^ k = a$0\"\n  shows \"fps_radical r k a ^ k $ 0 = (if k = 0 then 1 else a$0)\"\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc h)\n  have eq1: \"fps_radical r k a ^ k $ 0 = (\\<Prod>j\\<in>{0..h}. fps_radical r k a $ (replicate k 0) ! j)\"\n    unfolding fps_power_nth Suc by simp\n  also have \"\\<dots> = (\\<Prod>j\\<in>{0..h}. r k (a$0))\"\n    apply (rule setprod.cong)\n    apply simp\n    using Suc\n    apply (subgoal_tac \"replicate k 0 ! x = 0\")\n    apply (auto intro: nth_replicate simp del: replicate.simps)\n    done\n  also have \"\\<dots> = a$0\" using r Suc by (simp add: setprod_constant)\n  finally show ?thesis using Suc by simp\nqed\n\nlemma natpermute_max_card:\n  assumes n0: \"n \\<noteq> 0\"\n  shows \"card {xs \\<in> natpermute n (k+1). n \\<in> set xs} = k + 1\"\n  unfolding natpermute_contain_maximal\nproof -\n  let ?A= \"\\<lambda>i. {replicate (k + 1) 0[i := n]}\"\n  let ?K = \"{0 ..k}\"\n  have fK: \"finite ?K\" by simp\n  have fAK: \"\\<forall>i\\<in>?K. finite (?A i)\" by auto\n  have d: \"\\<forall>i\\<in> ?K. \\<forall>j\\<in> ?K. i \\<noteq> j \\<longrightarrow>\n    {replicate (k + 1) 0[i := n]} \\<inter> {replicate (k + 1) 0[j := n]} = {}\"\n  proof clarify\n    fix i j\n    assume i: \"i \\<in> ?K\" and j: \"j\\<in> ?K\" and ij: \"i\\<noteq>j\"\n    {\n      assume eq: \"replicate (k+1) 0 [i:=n] = replicate (k+1) 0 [j:= n]\"\n      have \"(replicate (k+1) 0 [i:=n] ! i) = n\"\n        using i by (simp del: replicate.simps)\n      moreover\n      have \"(replicate (k+1) 0 [j:=n] ! i) = 0\"\n        using i ij by (simp del: replicate.simps)\n      ultimately have False\n        using eq n0 by (simp del: replicate.simps)\n    }\n    then show \"{replicate (k + 1) 0[i := n]} \\<inter> {replicate (k + 1) 0[j := n]} = {}\"\n      by auto\n  qed\n  from card_UN_disjoint[OF fK fAK d]\n  show \"card (\\<Union>i\\<in>{0..k}. {replicate (k + 1) 0[i := n]}) = k + 1\"\n    by simp\nqed\n\nlemma power_radical:\n  fixes a:: \"'a::field_char_0 fps\"\n  assumes a0: \"a$0 \\<noteq> 0\"\n  shows \"(r (Suc k) (a$0)) ^ Suc k = a$0 \\<longleftrightarrow> (fps_radical r (Suc k) a) ^ (Suc k) = a\"\nproof -\n  let ?r = \"fps_radical r (Suc k) a\"\n  {\n    assume r0: \"(r (Suc k) (a$0)) ^ Suc k = a$0\"\n    from a0 r0 have r00: \"r (Suc k) (a$0) \\<noteq> 0\" by auto\n    {\n      fix z\n      have \"?r ^ Suc k $ z = a$z\"\n      proof (induct z rule: nat_less_induct)\n        fix n\n        assume H: \"\\<forall>m<n. ?r ^ Suc k $ m = a$m\"\n        {\n          assume \"n = 0\"\n          then have \"?r ^ Suc k $ n = a $n\"\n            using fps_radical_power_nth[of r \"Suc k\" a, OF r0] by simp\n        }\n        moreover\n        {\n          fix n1 assume n1: \"n = Suc n1\"\n          have nz: \"n \\<noteq> 0\" using n1 by arith\n          let ?Pnk = \"natpermute n (k + 1)\"\n          let ?Pnkn = \"{xs \\<in> ?Pnk. n \\<in> set xs}\"\n          let ?Pnknn = \"{xs \\<in> ?Pnk. n \\<notin> set xs}\"\n          have eq: \"?Pnkn \\<union> ?Pnknn = ?Pnk\" by blast\n          have d: \"?Pnkn \\<inter> ?Pnknn = {}\" by blast\n          have f: \"finite ?Pnkn\" \"finite ?Pnknn\"\n            using finite_Un[of ?Pnkn ?Pnknn, unfolded eq]\n            by (metis natpermute_finite)+\n          let ?f = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. ?r $ v ! j\"\n          have \"setsum ?f ?Pnkn = setsum (\\<lambda>v. ?r $ n * r (Suc k) (a $ 0) ^ k) ?Pnkn\"\n          proof (rule setsum.cong)\n            fix v assume v: \"v \\<in> {xs \\<in> natpermute n (k + 1). n \\<in> set xs}\"\n            let ?ths = \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) =\n              fps_radical r (Suc k) a $ n * r (Suc k) (a $ 0) ^ k\"\n            from v obtain i where i: \"i \\<in> {0..k}\" \"v = replicate (k+1) 0 [i:= n]\"\n              unfolding natpermute_contain_maximal by auto\n            have \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) =\n                (\\<Prod>j\\<in>{0..k}. if j = i then fps_radical r (Suc k) a $ n else r (Suc k) (a$0))\"\n              apply (rule setprod.cong, simp)\n              using i r0\n              apply (simp del: replicate.simps)\n              done\n            also have \"\\<dots> = (fps_radical r (Suc k) a $ n) * r (Suc k) (a$0) ^ k\"\n              using i r0 by (simp add: setprod_gen_delta)\n            finally show ?ths .\n          qed rule\n          then have \"setsum ?f ?Pnkn = of_nat (k+1) * ?r $ n * r (Suc k) (a $ 0) ^ k\"\n            by (simp add: natpermute_max_card[OF nz, simplified])\n          also have \"\\<dots> = a$n - setsum ?f ?Pnknn\"\n            unfolding n1 using r00 a0 by (simp add: field_simps fps_radical_def del: of_nat_Suc)\n          finally have fn: \"setsum ?f ?Pnkn = a$n - setsum ?f ?Pnknn\" .\n          have \"(?r ^ Suc k)$n = setsum ?f ?Pnkn + setsum ?f ?Pnknn\"\n            unfolding fps_power_nth_Suc setsum.union_disjoint[OF f d, unfolded eq] ..\n          also have \"\\<dots> = a$n\" unfolding fn by simp\n          finally have \"?r ^ Suc k $ n = a $n\" .\n        }\n        ultimately  show \"?r ^ Suc k $ n = a $n\" by (cases n) auto\n      qed\n    }\n    then have ?thesis using r0 by (simp add: fps_eq_iff)\n  }\n  moreover\n  {\n    assume h: \"(fps_radical r (Suc k) a) ^ (Suc k) = a\"\n    then have \"((fps_radical r (Suc k) a) ^ (Suc k))$0 = a$0\" by simp\n    then have \"(r (Suc k) (a$0)) ^ Suc k = a$0\"\n      unfolding fps_power_nth_Suc\n      by (simp add: setprod_constant del: replicate.simps)\n  }\n  ultimately show ?thesis by blast\nqed\n\n(*\nlemma power_radical:\n  fixes a:: \"'a::field_char_0 fps\"\n  assumes r0: \"(r (Suc k) (a$0)) ^ Suc k = a$0\" and a0: \"a$0 \\<noteq> 0\"\n  shows \"(fps_radical r (Suc k) a) ^ (Suc k) = a\"\nproof-\n  let ?r = \"fps_radical r (Suc k) a\"\n  from a0 r0 have r00: \"r (Suc k) (a$0) \\<noteq> 0\" by auto\n  {fix z have \"?r ^ Suc k $ z = a$z\"\n    proof(induct z rule: nat_less_induct)\n      fix n assume H: \"\\<forall>m<n. ?r ^ Suc k $ m = a$m\"\n      {assume \"n = 0\" then have \"?r ^ Suc k $ n = a $n\"\n          using fps_radical_power_nth[of r \"Suc k\" a, OF r0] by simp}\n      moreover\n      {fix n1 assume n1: \"n = Suc n1\"\n        have fK: \"finite {0..k}\" by simp\n        have nz: \"n \\<noteq> 0\" using n1 by arith\n        let ?Pnk = \"natpermute n (k + 1)\"\n        let ?Pnkn = \"{xs \\<in> ?Pnk. n \\<in> set xs}\"\n        let ?Pnknn = \"{xs \\<in> ?Pnk. n \\<notin> set xs}\"\n        have eq: \"?Pnkn \\<union> ?Pnknn = ?Pnk\" by blast\n        have d: \"?Pnkn \\<inter> ?Pnknn = {}\" by blast\n        have f: \"finite ?Pnkn\" \"finite ?Pnknn\"\n          using finite_Un[of ?Pnkn ?Pnknn, unfolded eq]\n          by (metis natpermute_finite)+\n        let ?f = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. ?r $ v ! j\"\n        have \"setsum ?f ?Pnkn = setsum (\\<lambda>v. ?r $ n * r (Suc k) (a $ 0) ^ k) ?Pnkn\"\n        proof(rule setsum.cong2)\n          fix v assume v: \"v \\<in> {xs \\<in> natpermute n (k + 1). n \\<in> set xs}\"\n          let ?ths = \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) = fps_radical r (Suc k) a $ n * r (Suc k) (a $ 0) ^ k\"\n          from v obtain i where i: \"i \\<in> {0..k}\" \"v = replicate (k+1) 0 [i:= n]\"\n            unfolding natpermute_contain_maximal by auto\n          have \"(\\<Prod>j\\<in>{0..k}. fps_radical r (Suc k) a $ v ! j) = (\\<Prod>j\\<in>{0..k}. if j = i then fps_radical r (Suc k) a $ n else r (Suc k) (a$0))\"\n            apply (rule setprod.cong, simp)\n            using i r0 by (simp del: replicate.simps)\n          also have \"\\<dots> = (fps_radical r (Suc k) a $ n) * r (Suc k) (a$0) ^ k\"\n            unfolding setprod_gen_delta[OF fK] using i r0 by simp\n          finally show ?ths .\n        qed\n        then have \"setsum ?f ?Pnkn = of_nat (k+1) * ?r $ n * r (Suc k) (a $ 0) ^ k\"\n          by (simp add: natpermute_max_card[OF nz, simplified])\n        also have \"\\<dots> = a$n - setsum ?f ?Pnknn\"\n          unfolding n1 using r00 a0 by (simp add: field_simps fps_radical_def del: of_nat_Suc )\n        finally have fn: \"setsum ?f ?Pnkn = a$n - setsum ?f ?Pnknn\" .\n        have \"(?r ^ Suc k)$n = setsum ?f ?Pnkn + setsum ?f ?Pnknn\"\n          unfolding fps_power_nth_Suc setsum.union_disjoint[OF f d, unfolded eq] ..\n        also have \"\\<dots> = a$n\" unfolding fn by simp\n        finally have \"?r ^ Suc k $ n = a $n\" .}\n      ultimately  show \"?r ^ Suc k $ n = a $n\" by (cases n, auto)\n  qed }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\n*)\nlemma eq_divide_imp':\n  fixes c :: \"'a::field\" shows \"c \\<noteq> 0 \\<Longrightarrow> a * c = b \\<Longrightarrow> a = b / c\"\n  by (simp add: field_simps)\n\nlemma radical_unique:\n  assumes r0: \"(r (Suc k) (b$0)) ^ Suc k = b$0\"\n    and a0: \"r (Suc k) (b$0 ::'a::field_char_0) = a$0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"a^(Suc k) = b \\<longleftrightarrow> a = fps_radical r (Suc k) b\"\nproof -\n  let ?r = \"fps_radical r (Suc k) b\"\n  have r00: \"r (Suc k) (b$0) \\<noteq> 0\" using b0 r0 by auto\n  {\n    assume H: \"a = ?r\"\n    from H have \"a^Suc k = b\"\n      using power_radical[OF b0, of r k, unfolded r0] by simp\n  }\n  moreover\n  {\n    assume H: \"a^Suc k = b\"\n    have ceq: \"card {0..k} = Suc k\" by simp\n    from a0 have a0r0: \"a$0 = ?r$0\" by simp\n    {\n      fix n\n      have \"a $ n = ?r $ n\"\n      proof (induct n rule: nat_less_induct)\n        fix n\n        assume h: \"\\<forall>m<n. a$m = ?r $m\"\n        {\n          assume \"n = 0\"\n          then have \"a$n = ?r $n\" using a0 by simp\n        }\n        moreover\n        {\n          fix n1\n          assume n1: \"n = Suc n1\"\n          have fK: \"finite {0..k}\" by simp\n        have nz: \"n \\<noteq> 0\" using n1 by arith\n        let ?Pnk = \"natpermute n (Suc k)\"\n        let ?Pnkn = \"{xs \\<in> ?Pnk. n \\<in> set xs}\"\n        let ?Pnknn = \"{xs \\<in> ?Pnk. n \\<notin> set xs}\"\n        have eq: \"?Pnkn \\<union> ?Pnknn = ?Pnk\" by blast\n        have d: \"?Pnkn \\<inter> ?Pnknn = {}\" by blast\n        have f: \"finite ?Pnkn\" \"finite ?Pnknn\"\n          using finite_Un[of ?Pnkn ?Pnknn, unfolded eq]\n          by (metis natpermute_finite)+\n        let ?f = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. ?r $ v ! j\"\n        let ?g = \"\\<lambda>v. \\<Prod>j\\<in>{0..k}. a $ v ! j\"\n        have \"setsum ?g ?Pnkn = setsum (\\<lambda>v. a $ n * (?r$0)^k) ?Pnkn\"\n        proof (rule setsum.cong)\n          fix v\n          assume v: \"v \\<in> {xs \\<in> natpermute n (Suc k). n \\<in> set xs}\"\n          let ?ths = \"(\\<Prod>j\\<in>{0..k}. a $ v ! j) = a $ n * (?r$0)^k\"\n          from v obtain i where i: \"i \\<in> {0..k}\" \"v = replicate (k+1) 0 [i:= n]\"\n            unfolding Suc_eq_plus1 natpermute_contain_maximal\n            by (auto simp del: replicate.simps)\n          have \"(\\<Prod>j\\<in>{0..k}. a $ v ! j) = (\\<Prod>j\\<in>{0..k}. if j = i then a $ n else r (Suc k) (b$0))\"\n            apply (rule setprod.cong, simp)\n            using i a0\n            apply (simp del: replicate.simps)\n            done\n          also have \"\\<dots> = a $ n * (?r $ 0)^k\"\n            using i by (simp add: setprod_gen_delta)\n          finally show ?ths .\n        qed rule\n        then have th0: \"setsum ?g ?Pnkn = of_nat (k+1) * a $ n * (?r $ 0)^k\"\n          by (simp add: natpermute_max_card[OF nz, simplified])\n        have th1: \"setsum ?g ?Pnknn = setsum ?f ?Pnknn\"\n        proof (rule setsum.cong, rule refl, rule setprod.cong, simp)\n          fix xs i\n          assume xs: \"xs \\<in> ?Pnknn\" and i: \"i \\<in> {0..k}\"\n          {\n            assume c: \"n \\<le> xs ! i\"\n            from xs i have \"xs !i \\<noteq> n\"\n              by (auto simp add: in_set_conv_nth natpermute_def)\n            with c have c': \"n < xs!i\" by arith\n            have fths: \"finite {0 ..< i}\" \"finite {i}\" \"finite {i+1..<Suc k}\"\n              by simp_all\n            have d: \"{0 ..< i} \\<inter> ({i} \\<union> {i+1 ..< Suc k}) = {}\" \"{i} \\<inter> {i+1..< Suc k} = {}\"\n              by auto\n            have eqs: \"{0..<Suc k} = {0 ..< i} \\<union> ({i} \\<union> {i+1 ..< Suc k})\"\n              using i by auto\n            from xs have \"n = listsum xs\"\n              by (simp add: natpermute_def)\n            also have \"\\<dots> = setsum (nth xs) {0..<Suc k}\"\n              using xs by (simp add: natpermute_def listsum_setsum_nth)\n            also have \"\\<dots> = xs!i + setsum (nth xs) {0..<i} + setsum (nth xs) {i+1..<Suc k}\"\n              unfolding eqs  setsum.union_disjoint[OF fths(1) finite_UnI[OF fths(2,3)] d(1)]\n              unfolding setsum.union_disjoint[OF fths(2) fths(3) d(2)]\n              by simp\n            finally have False using c' by simp\n          }\n          then have thn: \"xs!i < n\" by presburger\n          from h[rule_format, OF thn] show \"a$(xs !i) = ?r$(xs!i)\" .\n        qed\n        have th00: \"\\<And>x::'a. of_nat (Suc k) * (x * inverse (of_nat (Suc k))) = x\"\n          by (simp add: field_simps del: of_nat_Suc)\n        from H have \"b$n = a^Suc k $ n\"\n          by (simp add: fps_eq_iff)\n        also have \"a ^ Suc k$n = setsum ?g ?Pnkn + setsum ?g ?Pnknn\"\n          unfolding fps_power_nth_Suc\n          using setsum.union_disjoint[OF f d, unfolded Suc_eq_plus1[symmetric],\n            unfolded eq, of ?g] by simp\n        also have \"\\<dots> = of_nat (k+1) * a $ n * (?r $ 0)^k + setsum ?f ?Pnknn\"\n          unfolding th0 th1 ..\n        finally have \"of_nat (k+1) * a $ n * (?r $ 0)^k = b$n - setsum ?f ?Pnknn\"\n          by simp\n        then have \"a$n = (b$n - setsum ?f ?Pnknn) / (of_nat (k+1) * (?r $ 0)^k)\"\n          apply -\n          apply (rule eq_divide_imp')\n          using r00\n          apply (simp del: of_nat_Suc)\n          apply (simp add: ac_simps)\n          done\n        then have \"a$n = ?r $n\"\n          apply (simp del: of_nat_Suc)\n          unfolding fps_radical_def n1\n          apply (simp add: field_simps n1 th00 del: of_nat_Suc)\n          done\n        }\n        ultimately show \"a$n = ?r $ n\" by (cases n) auto\n      qed\n    }\n    then have \"a = ?r\" by (simp add: fps_eq_iff)\n  }\n  ultimately show ?thesis by blast\nqed\n\n\nlemma radical_power:\n  assumes r0: \"r (Suc k) ((a$0) ^ Suc k) = a$0\"\n    and a0: \"(a$0 :: 'a::field_char_0) \\<noteq> 0\"\n  shows \"(fps_radical r (Suc k) (a ^ Suc k)) = a\"\nproof -\n  let ?ak = \"a^ Suc k\"\n  have ak0: \"?ak $ 0 = (a$0) ^ Suc k\"\n    by (simp add: fps_nth_power_0 del: power_Suc)\n  from r0 have th0: \"r (Suc k) (a ^ Suc k $ 0) ^ Suc k = a ^ Suc k $ 0\"\n    using ak0 by auto\n  from r0 ak0 have th1: \"r (Suc k) (a ^ Suc k $ 0) = a $ 0\"\n    by auto\n  from ak0 a0 have ak00: \"?ak $ 0 \\<noteq>0 \"\n    by auto\n  from radical_unique[of r k ?ak a, OF th0 th1 ak00] show ?thesis\n    by metis\nqed\n\nlemma fps_deriv_radical:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes r0: \"(r (Suc k) (a$0)) ^ Suc k = a$0\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_deriv (fps_radical r (Suc k) a) =\n    fps_deriv a / (fps_const (of_nat (Suc k)) * (fps_radical r (Suc k) a) ^ k)\"\nproof -\n  let ?r = \"fps_radical r (Suc k) a\"\n  let ?w = \"(fps_const (of_nat (Suc k)) * ?r ^ k)\"\n  from a0 r0 have r0': \"r (Suc k) (a$0) \\<noteq> 0\"\n    by auto\n  from r0' have w0: \"?w $ 0 \\<noteq> 0\"\n    by (simp del: of_nat_Suc)\n  note th0 = inverse_mult_eq_1[OF w0]\n  let ?iw = \"inverse ?w\"\n  from iffD1[OF power_radical[of a r], OF a0 r0]\n  have \"fps_deriv (?r ^ Suc k) = fps_deriv a\"\n    by simp\n  then have \"fps_deriv ?r * ?w = fps_deriv a\"\n    by (simp add: fps_deriv_power ac_simps del: power_Suc)\n  then have \"?iw * fps_deriv ?r * ?w = ?iw * fps_deriv a\"\n    by simp\n  then have \"fps_deriv ?r * (?iw * ?w) = fps_deriv a / ?w\"\n    by (simp add: fps_divide_def)\n  then show ?thesis unfolding th0 by simp\nqed\n\nlemma radical_mult_distrib:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes k: \"k > 0\"\n    and ra0: \"r k (a $ 0) ^ k = a $ 0\"\n    and rb0: \"r k (b $ 0) ^ k = b $ 0\"\n    and a0: \"a$0 \\<noteq> 0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"r k ((a * b) $ 0) = r k (a $ 0) * r k (b $ 0) \\<longleftrightarrow>\n    fps_radical r (k) (a*b) = fps_radical r (k) a * fps_radical r (k) (b)\"\nproof -\n  {\n    assume  r0': \"r k ((a * b) $ 0) = r k (a $ 0) * r k (b $ 0)\"\n    from r0' have r0: \"(r (k) ((a*b)$0)) ^ k = (a*b)$0\"\n      by (simp add: fps_mult_nth ra0 rb0 power_mult_distrib)\n    {\n      assume \"k = 0\"\n      then have ?thesis using r0' by simp\n    }\n    moreover\n    {\n      fix h assume k: \"k = Suc h\"\n      let ?ra = \"fps_radical r (Suc h) a\"\n      let ?rb = \"fps_radical r (Suc h) b\"\n      have th0: \"r (Suc h) ((a * b) $ 0) = (fps_radical r (Suc h) a * fps_radical r (Suc h) b) $ 0\"\n        using r0' k by (simp add: fps_mult_nth)\n      have ab0: \"(a*b) $ 0 \\<noteq> 0\"\n        using a0 b0 by (simp add: fps_mult_nth)\n      from radical_unique[of r h \"a*b\" \"fps_radical r (Suc h) a * fps_radical r (Suc h) b\", OF r0[unfolded k] th0 ab0, symmetric]\n        iffD1[OF power_radical[of _ r], OF a0 ra0[unfolded k]] iffD1[OF power_radical[of _ r], OF b0 rb0[unfolded k]] k r0'\n      have ?thesis by (auto simp add: power_mult_distrib simp del: power_Suc)\n    }\n    ultimately have ?thesis by (cases k) auto\n  }\n  moreover\n  {\n    assume h: \"fps_radical r k (a*b) = fps_radical r k a * fps_radical r k b\"\n    then have \"(fps_radical r k (a*b))$0 = (fps_radical r k a * fps_radical r k b)$0\"\n      by simp\n    then have \"r k ((a * b) $ 0) = r k (a $ 0) * r k (b $ 0)\"\n      using k by (simp add: fps_mult_nth)\n  }\n  ultimately show ?thesis by blast\nqed\n\n(*\nlemma radical_mult_distrib:\n  fixes a:: \"'a::field_char_0 fps\"\n  assumes\n  ra0: \"r k (a $ 0) ^ k = a $ 0\"\n  and rb0: \"r k (b $ 0) ^ k = b $ 0\"\n  and r0': \"r k ((a * b) $ 0) = r k (a $ 0) * r k (b $ 0)\"\n  and a0: \"a$0 \\<noteq> 0\"\n  and b0: \"b$0 \\<noteq> 0\"\n  shows \"fps_radical r (k) (a*b) = fps_radical r (k) a * fps_radical r (k) (b)\"\nproof-\n  from r0' have r0: \"(r (k) ((a*b)$0)) ^ k = (a*b)$0\"\n    by (simp add: fps_mult_nth ra0 rb0 power_mult_distrib)\n  {assume \"k=0\" then have ?thesis by simp}\n  moreover\n  {fix h assume k: \"k = Suc h\"\n  let ?ra = \"fps_radical r (Suc h) a\"\n  let ?rb = \"fps_radical r (Suc h) b\"\n  have th0: \"r (Suc h) ((a * b) $ 0) = (fps_radical r (Suc h) a * fps_radical r (Suc h) b) $ 0\"\n    using r0' k by (simp add: fps_mult_nth)\n  have ab0: \"(a*b) $ 0 \\<noteq> 0\" using a0 b0 by (simp add: fps_mult_nth)\n  from radical_unique[of r h \"a*b\" \"fps_radical r (Suc h) a * fps_radical r (Suc h) b\", OF r0[unfolded k] th0 ab0, symmetric]\n    power_radical[of r, OF ra0[unfolded k] a0] power_radical[of r, OF rb0[unfolded k] b0] k\n  have ?thesis by (auto simp add: power_mult_distrib simp del: power_Suc)}\nultimately show ?thesis by (cases k, auto)\nqed\n*)\n\nlemma fps_divide_1[simp]: \"(a :: 'a::field fps) / 1 = a\"\n  by (simp add: fps_divide_def)\n\nlemma radical_divide:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes kp: \"k > 0\"\n    and ra0: \"(r k (a $ 0)) ^ k = a $ 0\"\n    and rb0: \"(r k (b $ 0)) ^ k = b $ 0\"\n    and a0: \"a$0 \\<noteq> 0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"r k ((a $ 0) / (b$0)) = r k (a$0) / r k (b $ 0) \\<longleftrightarrow>\n    fps_radical r k (a/b) = fps_radical r k a / fps_radical r k b\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?r = \"fps_radical r k\"\n  from kp obtain h where k: \"k = Suc h\" by (cases k) auto\n  have ra0': \"r k (a$0) \\<noteq> 0\" using a0 ra0 k by auto\n  have rb0': \"r k (b$0) \\<noteq> 0\" using b0 rb0 k by auto\n\n  {\n    assume ?rhs\n    then have \"?r (a/b) $ 0 = (?r a / ?r b)$0\" by simp\n    then have ?lhs using k a0 b0 rb0'\n      by (simp add: fps_divide_def fps_mult_nth fps_inverse_def divide_inverse)\n  }\n  moreover\n  {\n    assume h: ?lhs\n    from a0 b0 have ab0[simp]: \"(a/b)$0 = a$0 / b$0\"\n      by (simp add: fps_divide_def fps_mult_nth divide_inverse fps_inverse_def)\n    have th0: \"r k ((a/b)$0) ^ k = (a/b)$0\"\n      by (simp add: h nonzero_power_divide[OF rb0'] ra0 rb0)\n    from a0 b0 ra0' rb0' kp h\n    have th1: \"r k ((a / b) $ 0) = (fps_radical r k a / fps_radical r k b) $ 0\"\n      by (simp add: fps_divide_def fps_mult_nth fps_inverse_def divide_inverse)\n    from a0 b0 ra0' rb0' kp have ab0': \"(a / b) $ 0 \\<noteq> 0\"\n      by (simp add: fps_divide_def fps_mult_nth fps_inverse_def nonzero_imp_inverse_nonzero)\n    note tha[simp] = iffD1[OF power_radical[where r=r and k=h], OF a0 ra0[unfolded k], unfolded k[symmetric]]\n    note thb[simp] = iffD1[OF power_radical[where r=r and k=h], OF b0 rb0[unfolded k], unfolded k[symmetric]]\n    have th2: \"(?r a / ?r b)^k = a/b\"\n      by (simp add: fps_divide_def power_mult_distrib fps_inverse_power[symmetric])\n    from iffD1[OF radical_unique[where r=r and a=\"?r a / ?r b\" and b=\"a/b\" and k=h], symmetric, unfolded k[symmetric], OF th0 th1 ab0' th2]\n    have ?rhs .\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma radical_inverse:\n  fixes a :: \"'a::field_char_0 fps\"\n  assumes k: \"k > 0\"\n    and ra0: \"r k (a $ 0) ^ k = a $ 0\"\n    and r1: \"(r k 1)^k = 1\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"r k (inverse (a $ 0)) = r k 1 / (r k (a $ 0)) \\<longleftrightarrow>\n    fps_radical r k (inverse a) = fps_radical r k 1 / fps_radical r k a\"\n  using radical_divide[where k=k and r=r and a=1 and b=a, OF k ] ra0 r1 a0\n  by (simp add: divide_inverse fps_divide_def)\n\nsubsection{* Derivative of composition *}\n\nlemma fps_compose_deriv:\n  fixes a :: \"'a::idom fps\"\n  assumes b0: \"b$0 = 0\"\n  shows \"fps_deriv (a oo b) = ((fps_deriv a) oo b) * fps_deriv b\"\nproof -\n  {\n    fix n\n    have \"(fps_deriv (a oo b))$n = setsum (\\<lambda>i. a $ i * (fps_deriv (b^i))$n) {0.. Suc n}\"\n      by (simp add: fps_compose_def field_simps setsum_right_distrib del: of_nat_Suc)\n    also have \"\\<dots> = setsum (\\<lambda>i. a$i * ((fps_const (of_nat i)) * (fps_deriv b * (b^(i - 1))))$n) {0.. Suc n}\"\n      by (simp add: field_simps fps_deriv_power del: fps_mult_left_const_nth of_nat_Suc)\n    also have \"\\<dots> = setsum (\\<lambda>i. of_nat i * a$i * (((b^(i - 1)) * fps_deriv b))$n) {0.. Suc n}\"\n      unfolding fps_mult_left_const_nth  by (simp add: field_simps)\n    also have \"\\<dots> = setsum (\\<lambda>i. of_nat i * a$i * (setsum (\\<lambda>j. (b^ (i - 1))$j * (fps_deriv b)$(n - j)) {0..n})) {0.. Suc n}\"\n      unfolding fps_mult_nth ..\n    also have \"\\<dots> = setsum (\\<lambda>i. of_nat i * a$i * (setsum (\\<lambda>j. (b^ (i - 1))$j * (fps_deriv b)$(n - j)) {0..n})) {1.. Suc n}\"\n      apply (rule setsum.mono_neutral_right)\n      apply (auto simp add: mult_delta_left setsum.delta not_le)\n      done\n    also have \"\\<dots> = setsum (\\<lambda>i. of_nat (i + 1) * a$(i+1) * (setsum (\\<lambda>j. (b^ i)$j * of_nat (n - j + 1) * b$(n - j + 1)) {0..n})) {0.. n}\"\n      unfolding fps_deriv_nth\n      by (rule setsum.reindex_cong [of Suc]) (auto simp add: mult.assoc)\n    finally have th0: \"(fps_deriv (a oo b))$n =\n      setsum (\\<lambda>i. of_nat (i + 1) * a$(i+1) * (setsum (\\<lambda>j. (b^ i)$j * of_nat (n - j + 1) * b$(n - j + 1)) {0..n})) {0.. n}\" .\n\n    have \"(((fps_deriv a) oo b) * (fps_deriv b))$n = setsum (\\<lambda>i. (fps_deriv b)$ (n - i) * ((fps_deriv a) oo b)$i) {0..n}\"\n      unfolding fps_mult_nth by (simp add: ac_simps)\n    also have \"\\<dots> = setsum (\\<lambda>i. setsum (\\<lambda>j. of_nat (n - i +1) * b$(n - i + 1) * of_nat (j + 1) * a$(j+1) * (b^j)$i) {0..n}) {0..n}\"\n      unfolding fps_deriv_nth fps_compose_nth setsum_right_distrib mult.assoc\n      apply (rule setsum.cong)\n      apply (rule refl)\n      apply (rule setsum.mono_neutral_left)\n      apply (simp_all add: subset_eq)\n      apply clarify\n      apply (subgoal_tac \"b^i$x = 0\")\n      apply simp\n      apply (rule startsby_zero_power_prefix[OF b0, rule_format])\n      apply simp\n      done\n    also have \"\\<dots> = setsum (\\<lambda>i. of_nat (i + 1) * a$(i+1) * (setsum (\\<lambda>j. (b^ i)$j * of_nat (n - j + 1) * b$(n - j + 1)) {0..n})) {0.. n}\"\n      unfolding setsum_right_distrib\n      apply (subst setsum.commute)\n      apply (rule setsum.cong, rule refl)+\n      apply simp\n      done\n    finally have \"(fps_deriv (a oo b))$n = (((fps_deriv a) oo b) * (fps_deriv b)) $n\"\n      unfolding th0 by simp\n  }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\nlemma fps_mult_X_plus_1_nth:\n  \"((1+X)*a) $n = (if n = 0 then (a$n :: 'a::comm_ring_1) else a$n + a$(n - 1))\"\nproof (cases n)\n  case 0\n  then show ?thesis\n    by (simp add: fps_mult_nth )\nnext\n  case (Suc m)\n  have \"((1+X)*a) $n = setsum (\\<lambda>i. (1+X)$i * a$(n-i)) {0..n}\"\n    by (simp add: fps_mult_nth)\n  also have \"\\<dots> = setsum (\\<lambda>i. (1+X)$i * a$(n-i)) {0.. 1}\"\n    unfolding Suc by (rule setsum.mono_neutral_right) auto\n  also have \"\\<dots> = (if n = 0 then (a$n :: 'a::comm_ring_1) else a$n + a$(n - 1))\"\n    by (simp add: Suc)\n  finally show ?thesis .\nqed\n\n\nsubsection {* Finite FPS (i.e. polynomials) and X *}\n\nlemma fps_poly_sum_X:\n  assumes z: \"\\<forall>i > n. a$i = (0::'a::comm_ring_1)\"\n  shows \"a = setsum (\\<lambda>i. fps_const (a$i) * X^i) {0..n}\" (is \"a = ?r\")\nproof -\n  {\n    fix i\n    have \"a$i = ?r$i\"\n      unfolding fps_setsum_nth fps_mult_left_const_nth X_power_nth\n      by (simp add: mult_delta_right setsum.delta' z)\n  }\n  then show ?thesis unfolding fps_eq_iff by blast\nqed\n\n\nsubsection{* Compositional inverses *}\n\nfun compinv :: \"'a fps \\<Rightarrow> nat \\<Rightarrow> 'a::field\"\nwhere\n  \"compinv a 0 = X$0\"\n| \"compinv a (Suc n) =\n    (X$ Suc n - setsum (\\<lambda>i. (compinv a i) * (a^i)$Suc n) {0 .. n}) / (a$1) ^ Suc n\"\n\ndefinition \"fps_inv a = Abs_fps (compinv a)\"\n\nlemma fps_inv:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_inv a oo a = X\"\nproof -\n  let ?i = \"fps_inv a oo a\"\n  {\n    fix n\n    have \"?i $n = X$n\"\n    proof (induct n rule: nat_less_induct)\n      fix n\n      assume h: \"\\<forall>m<n. ?i$m = X$m\"\n      show \"?i $ n = X$n\"\n      proof (cases n)\n        case 0\n        then show ?thesis using a0\n          by (simp add: fps_compose_nth fps_inv_def)\n      next\n        case (Suc n1)\n        have \"?i $ n = setsum (\\<lambda>i. (fps_inv a $ i) * (a^i)$n) {0 .. n1} + fps_inv a $ Suc n1 * (a $ 1)^ Suc n1\"\n          by (simp only: fps_compose_nth) (simp add: Suc startsby_zero_power_nth_same [OF a0] del: power_Suc)\n        also have \"\\<dots> = setsum (\\<lambda>i. (fps_inv a $ i) * (a^i)$n) {0 .. n1} +\n          (X$ Suc n1 - setsum (\\<lambda>i. (fps_inv a $ i) * (a^i)$n) {0 .. n1})\"\n          using a0 a1 Suc by (simp add: fps_inv_def)\n        also have \"\\<dots> = X$n\" using Suc by simp\n        finally show ?thesis .\n      qed\n    qed\n  }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\n\nfun gcompinv :: \"'a fps \\<Rightarrow> 'a fps \\<Rightarrow> nat \\<Rightarrow> 'a::field\"\nwhere\n  \"gcompinv b a 0 = b$0\"\n| \"gcompinv b a (Suc n) =\n    (b$ Suc n - setsum (\\<lambda>i. (gcompinv b a i) * (a^i)$Suc n) {0 .. n}) / (a$1) ^ Suc n\"\n\ndefinition \"fps_ginv b a = Abs_fps (gcompinv b a)\"\n\nlemma fps_ginv:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_ginv b a oo a = b\"\nproof -\n  let ?i = \"fps_ginv b a oo a\"\n  {\n    fix n\n    have \"?i $n = b$n\"\n    proof (induct n rule: nat_less_induct)\n      fix n\n      assume h: \"\\<forall>m<n. ?i$m = b$m\"\n      show \"?i $ n = b$n\"\n      proof (cases n)\n        case 0\n        then show ?thesis using a0\n          by (simp add: fps_compose_nth fps_ginv_def)\n      next\n        case (Suc n1)\n        have \"?i $ n = setsum (\\<lambda>i. (fps_ginv b a $ i) * (a^i)$n) {0 .. n1} + fps_ginv b a $ Suc n1 * (a $ 1)^ Suc n1\"\n          by (simp only: fps_compose_nth) (simp add: Suc startsby_zero_power_nth_same [OF a0] del: power_Suc)\n        also have \"\\<dots> = setsum (\\<lambda>i. (fps_ginv b a $ i) * (a^i)$n) {0 .. n1} +\n          (b$ Suc n1 - setsum (\\<lambda>i. (fps_ginv b a $ i) * (a^i)$n) {0 .. n1})\"\n          using a0 a1 Suc by (simp add: fps_ginv_def)\n        also have \"\\<dots> = b$n\" using Suc by simp\n        finally show ?thesis .\n      qed\n    qed\n  }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\nlemma fps_inv_ginv: \"fps_inv = fps_ginv X\"\n  apply (auto simp add: fun_eq_iff fps_eq_iff fps_inv_def fps_ginv_def)\n  apply (induct_tac n rule: nat_less_induct)\n  apply auto\n  apply (case_tac na)\n  apply simp\n  apply simp\n  done\n\nlemma fps_compose_1[simp]: \"1 oo a = 1\"\n  by (simp add: fps_eq_iff fps_compose_nth mult_delta_left setsum.delta)\n\nlemma fps_compose_0[simp]: \"0 oo a = 0\"\n  by (simp add: fps_eq_iff fps_compose_nth)\n\nlemma fps_compose_0_right[simp]: \"a oo 0 = fps_const (a$0)\"\n  by (auto simp add: fps_eq_iff fps_compose_nth power_0_left setsum.neutral)\n\nlemma fps_compose_add_distrib: \"(a + b) oo c = (a oo c) + (b oo c)\"\n  by (simp add: fps_eq_iff fps_compose_nth field_simps setsum.distrib)\n\nlemma fps_compose_setsum_distrib: \"(setsum f S) oo a = setsum (\\<lambda>i. f i oo a) S\"\nproof (cases \"finite S\")\n  case True\n  show ?thesis\n  proof (rule finite_induct[OF True])\n    show \"setsum f {} oo a = (\\<Sum>i\\<in>{}. f i oo a)\" by simp\n  next\n    fix x F\n    assume fF: \"finite F\"\n      and xF: \"x \\<notin> F\"\n      and h: \"setsum f F oo a = setsum (\\<lambda>i. f i oo a) F\"\n    show \"setsum f (insert x F) oo a  = setsum (\\<lambda>i. f i oo a) (insert x F)\"\n      using fF xF h by (simp add: fps_compose_add_distrib)\n  qed\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma convolution_eq:\n  \"setsum (\\<lambda>i. a (i :: nat) * b (n - i)) {0 .. n} =\n    setsum (\\<lambda>(i,j). a i * b j) {(i,j). i \\<le> n \\<and> j \\<le> n \\<and> i + j = n}\"\n  by (rule setsum.reindex_bij_witness[where i=fst and j=\"\\<lambda>i. (i, n - i)\"]) auto\n\nlemma product_composition_lemma:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n    and d0: \"d$0 = 0\"\n  shows \"((a oo c) * (b oo d))$n =\n    setsum (\\<lambda>(k,m). a$k * b$m * (c^k * d^m) $ n) {(k,m). k + m \\<le> n}\"  (is \"?l = ?r\")\nproof -\n  let ?S = \"{(k::nat, m::nat). k + m \\<le> n}\"\n  have s: \"?S \\<subseteq> {0..n} <*> {0..n}\" by (auto simp add: subset_eq)\n  have f: \"finite {(k::nat, m::nat). k + m \\<le> n}\"\n    apply (rule finite_subset[OF s])\n    apply auto\n    done\n  have \"?r =  setsum (\\<lambda>i. setsum (\\<lambda>(k,m). a$k * (c^k)$i * b$m * (d^m) $ (n - i)) {(k,m). k + m \\<le> n}) {0..n}\"\n    apply (simp add: fps_mult_nth setsum_right_distrib)\n    apply (subst setsum.commute)\n    apply (rule setsum.cong)\n    apply (auto simp add: field_simps)\n    done\n  also have \"\\<dots> = ?l\"\n    apply (simp add: fps_mult_nth fps_compose_nth setsum_product)\n    apply (rule setsum.cong)\n    apply (rule refl)\n    apply (simp add: setsum.cartesian_product mult.assoc)\n    apply (rule setsum.mono_neutral_right[OF f])\n    apply (simp add: subset_eq)\n    apply presburger\n    apply clarsimp\n    apply (rule ccontr)\n    apply (clarsimp simp add: not_le)\n    apply (case_tac \"x < aa\")\n    apply simp\n    apply (frule_tac startsby_zero_power_prefix[rule_format, OF c0])\n    apply blast\n    apply simp\n    apply (frule_tac startsby_zero_power_prefix[rule_format, OF d0])\n    apply blast\n    done\n  finally show ?thesis by simp\nqed\n\nlemma product_composition_lemma':\n  assumes c0: \"c$0 = (0::'a::idom)\"\n    and d0: \"d$0 = 0\"\n  shows \"((a oo c) * (b oo d))$n =\n    setsum (\\<lambda>k. setsum (\\<lambda>m. a$k * b$m * (c^k * d^m) $ n) {0..n}) {0..n}\"  (is \"?l = ?r\")\n  unfolding product_composition_lemma[OF c0 d0]\n  unfolding setsum.cartesian_product\n  apply (rule setsum.mono_neutral_left)\n  apply simp\n  apply (clarsimp simp add: subset_eq)\n  apply clarsimp\n  apply (rule ccontr)\n  apply (subgoal_tac \"(c^aa * d^ba) $ n = 0\")\n  apply simp\n  unfolding fps_mult_nth\n  apply (rule setsum.neutral)\n  apply (clarsimp simp add: not_le)\n  apply (case_tac \"x < aa\")\n  apply (rule startsby_zero_power_prefix[OF c0, rule_format])\n  apply simp\n  apply (subgoal_tac \"n - x < ba\")\n  apply (frule_tac k = \"ba\" in startsby_zero_power_prefix[OF d0, rule_format])\n  apply simp\n  apply arith\n  done\n\n\nlemma setsum_pair_less_iff:\n  \"setsum (\\<lambda>((k::nat),m). a k * b m * c (k + m)) {(k,m). k + m \\<le> n} =\n    setsum (\\<lambda>s. setsum (\\<lambda>i. a i * b (s - i) * c s) {0..s}) {0..n}\"\n  (is \"?l = ?r\")\nproof -\n  let ?KM = \"{(k,m). k + m \\<le> n}\"\n  let ?f = \"\\<lambda>s. UNION {(0::nat)..s} (\\<lambda>i. {(i,s - i)})\"\n  have th0: \"?KM = UNION {0..n} ?f\"\n    apply (simp add: set_eq_iff)\n    apply presburger (* FIXME: slow! *)\n    done\n  show \"?l = ?r \"\n    unfolding th0\n    apply (subst setsum.UNION_disjoint)\n    apply auto\n    apply (subst setsum.UNION_disjoint)\n    apply auto\n    done\nqed\n\nlemma fps_compose_mult_distrib_lemma:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n  shows \"((a oo c) * (b oo c))$n =\n    setsum (\\<lambda>s. setsum (\\<lambda>i. a$i * b$(s - i) * (c^s) $ n) {0..s}) {0..n}\"\n    (is \"?l = ?r\")\n  unfolding product_composition_lemma[OF c0 c0] power_add[symmetric]\n  unfolding setsum_pair_less_iff[where a = \"\\<lambda>k. a$k\" and b=\"\\<lambda>m. b$m\" and c=\"\\<lambda>s. (c ^ s)$n\" and n = n] ..\n\n\nlemma fps_compose_mult_distrib:\n  assumes c0: \"c $ 0 = (0::'a::idom)\"\n  shows \"(a * b) oo c = (a oo c) * (b oo c)\"\n  apply (simp add: fps_eq_iff fps_compose_mult_distrib_lemma [OF c0])\n  apply (simp add: fps_compose_nth fps_mult_nth setsum_left_distrib)\n  done\n\nlemma fps_compose_setprod_distrib:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n  shows \"setprod a S oo c = setprod (\\<lambda>k. a k oo c) S\"\n  apply (cases \"finite S\")\n  apply simp_all\n  apply (induct S rule: finite_induct)\n  apply simp\n  apply (simp add: fps_compose_mult_distrib[OF c0])\n  done\n\nlemma fps_compose_power:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n  shows \"(a oo c)^n = a^n oo c\"\n  (is \"?l = ?r\")\nproof (cases n)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc m)\n  have th0: \"a^n = setprod (\\<lambda>k. a) {0..m}\" \"(a oo c) ^ n = setprod (\\<lambda>k. a oo c) {0..m}\"\n    by (simp_all add: setprod_constant Suc)\n  then show ?thesis\n    by (simp add: fps_compose_setprod_distrib[OF c0])\nqed\n\nlemma fps_compose_uminus: \"- (a::'a::ring_1 fps) oo c = - (a oo c)\"\n  by (simp add: fps_eq_iff fps_compose_nth field_simps setsum_negf[symmetric])\n\nlemma fps_compose_sub_distrib: \"(a - b) oo (c::'a::ring_1 fps) = (a oo c) - (b oo c)\"\n  using fps_compose_add_distrib [of a \"- b\" c] by (simp add: fps_compose_uminus)\n\nlemma X_fps_compose: \"X oo a = Abs_fps (\\<lambda>n. if n = 0 then (0::'a::comm_ring_1) else a$n)\"\n  by (simp add: fps_eq_iff fps_compose_nth mult_delta_left setsum.delta)\n\nlemma fps_inverse_compose:\n  assumes b0: \"(b$0 :: 'a::field) = 0\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"inverse a oo b = inverse (a oo b)\"\nproof -\n  let ?ia = \"inverse a\"\n  let ?ab = \"a oo b\"\n  let ?iab = \"inverse ?ab\"\n\n  from a0 have ia0: \"?ia $ 0 \\<noteq> 0\" by simp\n  from a0 have ab0: \"?ab $ 0 \\<noteq> 0\" by (simp add: fps_compose_def)\n  have \"(?ia oo b) *  (a oo b) = 1\"\n    unfolding fps_compose_mult_distrib[OF b0, symmetric]\n    unfolding inverse_mult_eq_1[OF a0]\n    fps_compose_1 ..\n\n  then have \"(?ia oo b) *  (a oo b) * ?iab  = 1 * ?iab\" by simp\n  then have \"(?ia oo b) *  (?iab * (a oo b))  = ?iab\" by simp\n  then show ?thesis unfolding inverse_mult_eq_1[OF ab0] by simp\nqed\n\nlemma fps_divide_compose:\n  assumes c0: \"(c$0 :: 'a::field) = 0\"\n    and b0: \"b$0 \\<noteq> 0\"\n  shows \"(a/b) oo c = (a oo c) / (b oo c)\"\n    unfolding fps_divide_def fps_compose_mult_distrib[OF c0]\n    fps_inverse_compose[OF c0 b0] ..\n\nlemma gp:\n  assumes a0: \"a$0 = (0::'a::field)\"\n  shows \"(Abs_fps (\\<lambda>n. 1)) oo a = 1/(1 - a)\"\n    (is \"?one oo a = _\")\nproof -\n  have o0: \"?one $ 0 \\<noteq> 0\" by simp\n  have th0: \"(1 - X) $ 0 \\<noteq> (0::'a)\" by simp\n  from fps_inverse_gp[where ?'a = 'a]\n  have \"inverse ?one = 1 - X\" by (simp add: fps_eq_iff)\n  then have \"inverse (inverse ?one) = inverse (1 - X)\" by simp\n  then have th: \"?one = 1/(1 - X)\" unfolding fps_inverse_idempotent[OF o0]\n    by (simp add: fps_divide_def)\n  show ?thesis\n    unfolding th\n    unfolding fps_divide_compose[OF a0 th0]\n    fps_compose_1 fps_compose_sub_distrib X_fps_compose_startby0[OF a0] ..\nqed\n\nlemma fps_const_power [simp]: \"fps_const (c::'a::ring_1) ^ n = fps_const (c^n)\"\n  by (induct n) auto\n\nlemma fps_compose_radical:\n  assumes b0: \"b$0 = (0::'a::field_char_0)\"\n    and ra0: \"r (Suc k) (a$0) ^ Suc k = a$0\"\n    and a0: \"a$0 \\<noteq> 0\"\n  shows \"fps_radical r (Suc k)  a oo b = fps_radical r (Suc k) (a oo b)\"\nproof -\n  let ?r = \"fps_radical r (Suc k)\"\n  let ?ab = \"a oo b\"\n  have ab0: \"?ab $ 0 = a$0\"\n    by (simp add: fps_compose_def)\n  from ab0 a0 ra0 have rab0: \"?ab $ 0 \\<noteq> 0\" \"r (Suc k) (?ab $ 0) ^ Suc k = ?ab $ 0\"\n    by simp_all\n  have th00: \"r (Suc k) ((a oo b) $ 0) = (fps_radical r (Suc k) a oo b) $ 0\"\n    by (simp add: ab0 fps_compose_def)\n  have th0: \"(?r a oo b) ^ (Suc k) = a  oo b\"\n    unfolding fps_compose_power[OF b0]\n    unfolding iffD1[OF power_radical[of a r k], OF a0 ra0]  ..\n  from iffD1[OF radical_unique[where r=r and k=k and b= ?ab and a = \"?r a oo b\", OF rab0(2) th00 rab0(1)], OF th0]\n  show ?thesis  .\nqed\n\nlemma fps_const_mult_apply_left: \"fps_const c * (a oo b) = (fps_const c * a) oo b\"\n  by (simp add: fps_eq_iff fps_compose_nth setsum_right_distrib mult.assoc)\n\nlemma fps_const_mult_apply_right:\n  \"(a oo b) * fps_const (c::'a::comm_semiring_1) = (fps_const c * a) oo b\"\n  by (auto simp add: fps_const_mult_apply_left mult.commute)\n\nlemma fps_compose_assoc:\n  assumes c0: \"c$0 = (0::'a::idom)\"\n    and b0: \"b$0 = 0\"\n  shows \"a oo (b oo c) = a oo b oo c\" (is \"?l = ?r\")\nproof -\n  {\n    fix n\n    have \"?l$n = (setsum (\\<lambda>i. (fps_const (a$i) * b^i) oo c) {0..n})$n\"\n      by (simp add: fps_compose_nth fps_compose_power[OF c0] fps_const_mult_apply_left\n        setsum_right_distrib mult.assoc fps_setsum_nth)\n    also have \"\\<dots> = ((setsum (\\<lambda>i. fps_const (a$i) * b^i) {0..n}) oo c)$n\"\n      by (simp add: fps_compose_setsum_distrib)\n    also have \"\\<dots> = ?r$n\"\n      apply (simp add: fps_compose_nth fps_setsum_nth setsum_left_distrib mult.assoc)\n      apply (rule setsum.cong)\n      apply (rule refl)\n      apply (rule setsum.mono_neutral_right)\n      apply (auto simp add: not_le)\n      apply (erule startsby_zero_power_prefix[OF b0, rule_format])\n      done\n    finally have \"?l$n = ?r$n\" .\n  }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\n\nlemma fps_X_power_compose:\n  assumes a0: \"a$0=0\"\n  shows \"X^k oo a = (a::'a::idom fps)^k\"\n  (is \"?l = ?r\")\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc h)\n  {\n    fix n\n    {\n      assume kn: \"k>n\"\n      then have \"?l $ n = ?r $n\" using a0 startsby_zero_power_prefix[OF a0] Suc\n        by (simp add: fps_compose_nth del: power_Suc)\n    }\n    moreover\n    {\n      assume kn: \"k \\<le> n\"\n      then have \"?l$n = ?r$n\"\n        by (simp add: fps_compose_nth mult_delta_left setsum.delta)\n    }\n    moreover have \"k >n \\<or> k\\<le> n\"  by arith\n    ultimately have \"?l$n = ?r$n\"  by blast\n  }\n  then show ?thesis unfolding fps_eq_iff by blast\nqed\n\nlemma fps_inv_right:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"a oo fps_inv a = X\"\nproof -\n  let ?ia = \"fps_inv a\"\n  let ?iaa = \"a oo fps_inv a\"\n  have th0: \"?ia $ 0 = 0\" by (simp add: fps_inv_def)\n  have th1: \"?iaa $ 0 = 0\" using a0 a1\n    by (simp add: fps_inv_def fps_compose_nth)\n  have th2: \"X$0 = 0\" by simp\n  from fps_inv[OF a0 a1] have \"a oo (fps_inv a oo a) = a oo X\" by simp\n  then have \"(a oo fps_inv a) oo a = X oo a\"\n    by (simp add: fps_compose_assoc[OF a0 th0] X_fps_compose_startby0[OF a0])\n  with fps_compose_inj_right[OF a0 a1]\n  show ?thesis by simp\nqed\n\nlemma fps_inv_deriv:\n  assumes a0:\"a$0 = (0::'a::field)\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_deriv (fps_inv a) = inverse (fps_deriv a oo fps_inv a)\"\nproof -\n  let ?ia = \"fps_inv a\"\n  let ?d = \"fps_deriv a oo ?ia\"\n  let ?dia = \"fps_deriv ?ia\"\n  have ia0: \"?ia$0 = 0\" by (simp add: fps_inv_def)\n  have th0: \"?d$0 \\<noteq> 0\" using a1 by (simp add: fps_compose_nth)\n  from fps_inv_right[OF a0 a1] have \"?d * ?dia = 1\"\n    by (simp add: fps_compose_deriv[OF ia0, of a, symmetric] )\n  then have \"inverse ?d * ?d * ?dia = inverse ?d * 1\" by simp\n  with inverse_mult_eq_1 [OF th0]\n  show \"?dia = inverse ?d\" by simp\nqed\n\nlemma fps_inv_idempotent:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_inv (fps_inv a) = a\"\nproof -\n  let ?r = \"fps_inv\"\n  have ra0: \"?r a $ 0 = 0\" by (simp add: fps_inv_def)\n  from a1 have ra1: \"?r a $ 1 \\<noteq> 0\" by (simp add: fps_inv_def field_simps)\n  have X0: \"X$0 = 0\" by simp\n  from fps_inv[OF ra0 ra1] have \"?r (?r a) oo ?r a = X\" .\n  then have \"?r (?r a) oo ?r a oo a = X oo a\" by simp\n  then have \"?r (?r a) oo (?r a oo a) = a\"\n    unfolding X_fps_compose_startby0[OF a0]\n    unfolding fps_compose_assoc[OF a0 ra0, symmetric] .\n  then show ?thesis unfolding fps_inv[OF a0 a1] by simp\nqed\n\nlemma fps_ginv_ginv:\n  assumes a0: \"a$0 = 0\"\n    and a1: \"a$1 \\<noteq> 0\"\n    and c0: \"c$0 = 0\"\n    and  c1: \"c$1 \\<noteq> 0\"\n  shows \"fps_ginv b (fps_ginv c a) = b oo a oo fps_inv c\"\nproof -\n  let ?r = \"fps_ginv\"\n  from c0 have rca0: \"?r c a $0 = 0\" by (simp add: fps_ginv_def)\n  from a1 c1 have rca1: \"?r c a $ 1 \\<noteq> 0\" by (simp add: fps_ginv_def field_simps)\n  from fps_ginv[OF rca0 rca1]\n  have \"?r b (?r c a) oo ?r c a = b\" .\n  then have \"?r b (?r c a) oo ?r c a oo a = b oo a\" by simp\n  then have \"?r b (?r c a) oo (?r c a oo a) = b oo a\"\n    apply (subst fps_compose_assoc)\n    using a0 c0\n    apply (auto simp add: fps_ginv_def)\n    done\n  then have \"?r b (?r c a) oo c = b oo a\"\n    unfolding fps_ginv[OF a0 a1] .\n  then have \"?r b (?r c a) oo c oo fps_inv c= b oo a oo fps_inv c\" by simp\n  then have \"?r b (?r c a) oo (c oo fps_inv c) = b oo a oo fps_inv c\"\n    apply (subst fps_compose_assoc)\n    using a0 c0\n    apply (auto simp add: fps_inv_def)\n    done\n  then show ?thesis unfolding fps_inv_right[OF c0 c1] by simp\nqed\n\nlemma fps_ginv_deriv:\n  assumes a0:\"a$0 = (0::'a::field)\"\n    and a1: \"a$1 \\<noteq> 0\"\n  shows \"fps_deriv (fps_ginv b a) = (fps_deriv b / fps_deriv a) oo fps_ginv X a\"\nproof -\n  let ?ia = \"fps_ginv b a\"\n  let ?iXa = \"fps_ginv X a\"\n  let ?d = \"fps_deriv\"\n  let ?dia = \"?d ?ia\"\n  have iXa0: \"?iXa $ 0 = 0\" by (simp add: fps_ginv_def)\n  have da0: \"?d a $ 0 \\<noteq> 0\" using a1 by simp\n  from fps_ginv[OF a0 a1, of b] have \"?d (?ia oo a) = fps_deriv b\" by simp\n  then have \"(?d ?ia oo a) * ?d a = ?d b\" unfolding fps_compose_deriv[OF a0] .\n  then have \"(?d ?ia oo a) * ?d a * inverse (?d a) = ?d b * inverse (?d a)\" by simp\n  then have \"(?d ?ia oo a) * (inverse (?d a) * ?d a) = ?d b / ?d a\"\n    by (simp add: fps_divide_def)\n  then have \"(?d ?ia oo a) oo ?iXa =  (?d b / ?d a) oo ?iXa \"\n    unfolding inverse_mult_eq_1[OF da0] by simp\n  then have \"?d ?ia oo (a oo ?iXa) =  (?d b / ?d a) oo ?iXa\"\n    unfolding fps_compose_assoc[OF iXa0 a0] .\n  then show ?thesis unfolding fps_inv_ginv[symmetric]\n    unfolding fps_inv_right[OF a0 a1] by simp\nqed\n\nsubsection{* Elementary series *}\n\nsubsubsection{* Exponential series *}\n\ndefinition \"E x = Abs_fps (\\<lambda>n. x^n / of_nat (fact n))\"\n\nlemma E_deriv[simp]: \"fps_deriv (E a) = fps_const (a::'a::field_char_0) * E a\" (is \"?l = ?r\")\nproof -\n  {\n    fix n\n    have \"?l$n = ?r $ n\"\n      apply (auto simp add: E_def field_simps power_Suc[symmetric]\n        simp del: fact_Suc of_nat_Suc power_Suc)\n      apply (simp add: of_nat_mult field_simps)\n      done\n  }\n  then show ?thesis by (simp add: fps_eq_iff)\nqed\n\nlemma E_unique_ODE:\n  \"fps_deriv a = fps_const c * a \\<longleftrightarrow> a = fps_const (a$0) * E (c::'a::field_char_0)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume d: ?lhs\n  from d have th: \"\\<And>n. a $ Suc n = c * a$n / of_nat (Suc n)\"\n    by (simp add: fps_deriv_def fps_eq_iff field_simps del: of_nat_Suc)\n  {\n    fix n\n    have \"a$n = a$0 * c ^ n/ (of_nat (fact n))\"\n      apply (induct n)\n      apply simp\n      unfolding th\n      using fact_gt_zero_nat\n      apply (simp add: field_simps del: of_nat_Suc fact_Suc)\n      apply (drule sym)\n      apply (simp add: field_simps of_nat_mult)\n      done\n  }\n  note th' = this\n  show ?rhs by (auto simp add: fps_eq_iff fps_const_mult_left E_def intro: th')\nnext\n  assume h: ?rhs\n  show ?lhs\n    apply (subst h)\n    apply simp\n    apply (simp only: h[symmetric])\n    apply simp\n    done\nqed\n\nlemma E_add_mult: \"E (a + b) = E (a::'a::field_char_0) * E b\" (is \"?l = ?r\")\nproof -\n  have \"fps_deriv (?r) = fps_const (a+b) * ?r\"\n    by (simp add: fps_const_add[symmetric] field_simps del: fps_const_add)\n  then have \"?r = ?l\" apply (simp only: E_unique_ODE)\n    by (simp add: fps_mult_nth E_def)\n  then show ?thesis ..\nqed\n\nlemma E_nth[simp]: \"E a $ n = a^n / of_nat (fact n)\"\n  by (simp add: E_def)\n\nlemma E0[simp]: \"E (0::'a::field) = 1\"\n  by (simp add: fps_eq_iff power_0_left)\n\nlemma E_neg: \"E (- a) = inverse (E (a::'a::field_char_0))\"\nproof -\n  from E_add_mult[of a \"- a\"] have th0: \"E a * E (- a) = 1\"\n    by (simp )\n  have th1: \"E a $ 0 \\<noteq> 0\" by simp\n  from fps_inverse_unique[OF th1 th0] show ?thesis by simp\nqed\n\nlemma E_nth_deriv[simp]: \"fps_nth_deriv n (E (a::'a::field_char_0)) = (fps_const a)^n * (E a)\"\n  by (induct n) auto\n\nlemma X_compose_E[simp]: \"X oo E (a::'a::field) = E a - 1\"\n  by (simp add: fps_eq_iff X_fps_compose)\n\nlemma LE_compose:\n  assumes a: \"a\\<noteq>0\"\n  shows \"fps_inv (E a - 1) oo (E a - 1) = X\"\n    and \"(E a - 1) oo fps_inv (E a - 1) = X\"\nproof -\n  let ?b = \"E a - 1\"\n  have b0: \"?b $ 0 = 0\" by simp\n  have b1: \"?b $ 1 \\<noteq> 0\" by (simp add: a)\n  from fps_inv[OF b0 b1] show \"fps_inv (E a - 1) oo (E a - 1) = X\" .\n  from fps_inv_right[OF b0 b1] show \"(E a - 1) oo fps_inv (E a - 1) = X\" .\nqed\n\nlemma fps_const_inverse:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (fps_const (a::'a::field)) = fps_const (inverse a)\"\n  apply (auto simp add: fps_eq_iff fps_inverse_def)\n  apply (case_tac n)\n  apply auto\n  done\n\nlemma inverse_one_plus_X:\n  \"inverse (1 + X) = Abs_fps (\\<lambda>n. (- 1 ::'a::field)^n)\"\n  (is \"inverse ?l = ?r\")\nproof -\n  have th: \"?l * ?r = 1\"\n    by (auto simp add: field_simps fps_eq_iff minus_one_power_iff)\n  have th': \"?l $ 0 \\<noteq> 0\" by (simp add: )\n  from fps_inverse_unique[OF th' th] show ?thesis .\nqed\n\nlemma E_power_mult: \"(E (c::'a::field_char_0))^n = E (of_nat n * c)\"\n  by (induct n) (auto simp add: field_simps E_add_mult)\n\nlemma radical_E:\n  assumes r: \"r (Suc k) 1 = 1\"\n  shows \"fps_radical r (Suc k) (E (c::'a::field_char_0)) = E (c / of_nat (Suc k))\"\nproof -\n  let ?ck = \"(c / of_nat (Suc k))\"\n  let ?r = \"fps_radical r (Suc k)\"\n  have eq0[simp]: \"?ck * of_nat (Suc k) = c\" \"of_nat (Suc k) * ?ck = c\"\n    by (simp_all del: of_nat_Suc)\n  have th0: \"E ?ck ^ (Suc k) = E c\" unfolding E_power_mult eq0 ..\n  have th: \"r (Suc k) (E c $0) ^ Suc k = E c $ 0\"\n    \"r (Suc k) (E c $ 0) = E ?ck $ 0\" \"E c $ 0 \\<noteq> 0\" using r by simp_all\n  from th0 radical_unique[where r=r and k=k, OF th]\n  show ?thesis by auto\nqed\n\nlemma Ec_E1_eq: \"E (1::'a::field_char_0) oo (fps_const c * X) = E c\"\n  apply (auto simp add: fps_eq_iff E_def fps_compose_def power_mult_distrib)\n  apply (simp add: cond_value_iff cond_application_beta setsum.delta' cong del: if_weak_cong)\n  done\n\ntext{* The generalized binomial theorem as a  consequence of @{thm E_add_mult} *}\n\nlemma gbinomial_theorem:\n  \"((a::'a::{field_char_0,field_inverse_zero})+b) ^ n =\n    (\\<Sum>k=0..n. of_nat (n choose k) * a^k * b^(n-k))\"\nproof -\n  from E_add_mult[of a b]\n  have \"(E (a + b)) $ n = (E a * E b)$n\" by simp\n  then have \"(a + b) ^ n =\n    (\\<Sum>i::nat = 0::nat..n. a ^ i * b ^ (n - i)  * (of_nat (fact n) / of_nat (fact i * fact (n - i))))\"\n    by (simp add: field_simps fps_mult_nth of_nat_mult[symmetric] setsum_right_distrib)\n  then show ?thesis\n    apply simp\n    apply (rule setsum.cong)\n    apply simp_all\n    apply (frule binomial_fact[where ?'a = 'a, symmetric])\n    apply (simp add: field_simps of_nat_mult)\n    done\nqed\n\ntext{* And the nat-form -- also available from Binomial.thy *}\nlemma binomial_theorem: \"(a+b) ^ n = (\\<Sum>k=0..n. (n choose k) * a^k * b^(n-k))\"\n  using gbinomial_theorem[of \"of_nat a\" \"of_nat b\" n]\n  unfolding of_nat_add[symmetric] of_nat_power[symmetric] of_nat_mult[symmetric]\n    of_nat_setsum[symmetric]\n  by simp\n\n\nsubsubsection{* Logarithmic series *}\n\nlemma Abs_fps_if_0:\n  \"Abs_fps(\\<lambda>n. if n=0 then (v::'a::ring_1) else f n) = fps_const v + X * Abs_fps (\\<lambda>n. f (Suc n))\"\n  by (auto simp add: fps_eq_iff)\n\ndefinition L :: \"'a::field_char_0 \\<Rightarrow> 'a fps\"\n  where \"L c = fps_const (1/c) * Abs_fps (\\<lambda>n. if n = 0 then 0 else (- 1) ^ (n - 1) / of_nat n)\"\n\nlemma fps_deriv_L: \"fps_deriv (L c) = fps_const (1/c) * inverse (1 + X)\"\n  unfolding inverse_one_plus_X\n  by (simp add: L_def fps_eq_iff del: of_nat_Suc)\n\nlemma L_nth: \"L c $ n = (if n=0 then 0 else 1/c * ((- 1) ^ (n - 1) / of_nat n))\"\n  by (simp add: L_def field_simps)\n\nlemma L_0[simp]: \"L c $ 0 = 0\" by (simp add: L_def)\n\nlemma L_E_inv:\n  fixes a :: \"'a::field_char_0\"\n  assumes a: \"a \\<noteq> 0\"\n  shows \"L a = fps_inv (E a - 1)\"  (is \"?l = ?r\")\nproof -\n  let ?b = \"E a - 1\"\n  have b0: \"?b $ 0 = 0\" by simp\n  have b1: \"?b $ 1 \\<noteq> 0\" by (simp add: a)\n  have \"fps_deriv (E a - 1) oo fps_inv (E a - 1) =\n    (fps_const a * (E a - 1) + fps_const a) oo fps_inv (E a - 1)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = fps_const a * (X + 1)\"\n    apply (simp add: fps_compose_add_distrib fps_const_mult_apply_left[symmetric] fps_inv_right[OF b0 b1])\n    apply (simp add: field_simps)\n    done\n  finally have eq: \"fps_deriv (E a - 1) oo fps_inv (E a - 1) = fps_const a * (X + 1)\" .\n  from fps_inv_deriv[OF b0 b1, unfolded eq]\n  have \"fps_deriv (fps_inv ?b) = fps_const (inverse a) / (X + 1)\"\n    using a\n    by (simp add: fps_const_inverse eq fps_divide_def fps_inverse_mult)\n  then have \"fps_deriv ?l = fps_deriv ?r\"\n    by (simp add: fps_deriv_L add.commute fps_divide_def divide_inverse)\n  then show ?thesis unfolding fps_deriv_eq_iff\n    by (simp add: L_nth fps_inv_def)\nqed\n\nlemma L_mult_add:\n  assumes c0: \"c\\<noteq>0\"\n    and d0: \"d\\<noteq>0\"\n  shows \"L c + L d = fps_const (c+d) * L (c*d)\"\n  (is \"?r = ?l\")\nproof-\n  from c0 d0 have eq: \"1/c + 1/d = (c+d)/(c*d)\" by (simp add: field_simps)\n  have \"fps_deriv ?r = fps_const (1/c + 1/d) * inverse (1 + X)\"\n    by (simp add: fps_deriv_L fps_const_add[symmetric] algebra_simps del: fps_const_add)\n  also have \"\\<dots> = fps_deriv ?l\"\n    apply (simp add: fps_deriv_L)\n    apply (simp add: fps_eq_iff eq)\n    done\n  finally show ?thesis\n    unfolding fps_deriv_eq_iff by simp\nqed\n\n\nsubsubsection{* Binomial series *}\n\ndefinition \"fps_binomial a = Abs_fps (\\<lambda>n. a gchoose n)\"\n\nlemma fps_binomial_nth[simp]: \"fps_binomial a $ n = a gchoose n\"\n  by (simp add: fps_binomial_def)\n\nlemma fps_binomial_ODE_unique:\n  fixes c :: \"'a::field_char_0\"\n  shows \"fps_deriv a = (fps_const c * a) / (1 + X) \\<longleftrightarrow> a = fps_const (a$0) * fps_binomial c\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  let ?da = \"fps_deriv a\"\n  let ?x1 = \"(1 + X):: 'a fps\"\n  let ?l = \"?x1 * ?da\"\n  let ?r = \"fps_const c * a\"\n  have x10: \"?x1 $ 0 \\<noteq> 0\" by simp\n  have \"?l = ?r \\<longleftrightarrow> inverse ?x1 * ?l = inverse ?x1 * ?r\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> ?da = (fps_const c * a) / ?x1\"\n    apply (simp only: fps_divide_def  mult.assoc[symmetric] inverse_mult_eq_1[OF x10])\n    apply (simp add: field_simps)\n    done\n  finally have eq: \"?l = ?r \\<longleftrightarrow> ?lhs\" by simp\n  moreover\n  {assume h: \"?l = ?r\"\n    {fix n\n      from h have lrn: \"?l $ n = ?r$n\" by simp\n\n      from lrn\n      have \"a$ Suc n = ((c - of_nat n) / of_nat (Suc n)) * a $n\"\n        apply (simp add: field_simps del: of_nat_Suc)\n        by (cases n, simp_all add: field_simps del: of_nat_Suc)\n    }\n    note th0 = this\n    {\n      fix n\n      have \"a$n = (c gchoose n) * a$0\"\n      proof (induct n)\n        case 0\n        then show ?case by simp\n      next\n        case (Suc m)\n        then show ?case unfolding th0\n          apply (simp add: field_simps del: of_nat_Suc)\n          unfolding mult.assoc[symmetric] gbinomial_mult_1\n          apply (simp add: field_simps)\n          done\n      qed\n    }\n    note th1 = this\n    have ?rhs\n      apply (simp add: fps_eq_iff)\n      apply (subst th1)\n      apply (simp add: field_simps)\n      done\n  }\n  moreover\n  {\n    assume h: ?rhs\n    have th00: \"\\<And>x y. x * (a$0 * y) = a$0 * (x*y)\"\n      by (simp add: mult.commute)\n    have \"?l = ?r\"\n      apply (subst h)\n      apply (subst (2) h)\n      apply (clarsimp simp add: fps_eq_iff field_simps)\n      unfolding mult.assoc[symmetric] th00 gbinomial_mult_1\n      apply (simp add: field_simps gbinomial_mult_1)\n      done\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma fps_binomial_deriv: \"fps_deriv (fps_binomial c) = fps_const c * fps_binomial c / (1 + X)\"\nproof -\n  let ?a = \"fps_binomial c\"\n  have th0: \"?a = fps_const (?a$0) * ?a\" by (simp)\n  from iffD2[OF fps_binomial_ODE_unique, OF th0] show ?thesis .\nqed\n\nlemma fps_binomial_add_mult: \"fps_binomial (c+d) = fps_binomial c * fps_binomial d\" (is \"?l = ?r\")\nproof -\n  let ?P = \"?r - ?l\"\n  let ?b = \"fps_binomial\"\n  let ?db = \"\\<lambda>x. fps_deriv (?b x)\"\n  have \"fps_deriv ?P = ?db c * ?b d + ?b c * ?db d - ?db (c + d)\"  by simp\n  also have \"\\<dots> = inverse (1 + X) *\n      (fps_const c * ?b c * ?b d + fps_const d * ?b c * ?b d - fps_const (c+d) * ?b (c + d))\"\n    unfolding fps_binomial_deriv\n    by (simp add: fps_divide_def field_simps)\n  also have \"\\<dots> = (fps_const (c + d)/ (1 + X)) * ?P\"\n    by (simp add: field_simps fps_divide_def fps_const_add[symmetric] del: fps_const_add)\n  finally have th0: \"fps_deriv ?P = fps_const (c+d) * ?P / (1 + X)\"\n    by (simp add: fps_divide_def)\n  have \"?P = fps_const (?P$0) * ?b (c + d)\"\n    unfolding fps_binomial_ODE_unique[symmetric]\n    using th0 by simp\n  then have \"?P = 0\" by (simp add: fps_mult_nth)\n  then show ?thesis by simp\nqed\n\nlemma fps_minomial_minus_one: \"fps_binomial (- 1) = inverse (1 + X)\"\n  (is \"?l = inverse ?r\")\nproof-\n  have th: \"?r$0 \\<noteq> 0\" by simp\n  have th': \"fps_deriv (inverse ?r) = fps_const (- 1) * inverse ?r / (1 + X)\"\n    by (simp add: fps_inverse_deriv[OF th] fps_divide_def\n      power2_eq_square mult.commute fps_const_neg[symmetric] del: fps_const_neg)\n  have eq: \"inverse ?r $ 0 = 1\"\n    by (simp add: fps_inverse_def)\n  from iffD1[OF fps_binomial_ODE_unique[of \"inverse (1 + X)\" \"- 1\"] th'] eq\n  show ?thesis by (simp add: fps_inverse_def)\nqed\n\ntext{* Vandermonde's Identity as a consequence *}\nlemma gbinomial_Vandermonde:\n  \"setsum (\\<lambda>k. (a gchoose k) * (b gchoose (n - k))) {0..n} = (a + b) gchoose n\"\nproof -\n  let ?ba = \"fps_binomial a\"\n  let ?bb = \"fps_binomial b\"\n  let ?bab = \"fps_binomial (a + b)\"\n  from fps_binomial_add_mult[of a b] have \"?bab $ n = (?ba * ?bb)$n\" by simp\n  then show ?thesis by (simp add: fps_mult_nth)\nqed\n\nlemma binomial_Vandermonde:\n  \"setsum (\\<lambda>k. (a choose k) * (b choose (n - k))) {0..n} = (a + b) choose n\"\n  using gbinomial_Vandermonde[of \"(of_nat a)\" \"of_nat b\" n]\n  apply (simp only: binomial_gbinomial[symmetric] of_nat_mult[symmetric]\n    of_nat_setsum[symmetric] of_nat_add[symmetric])\n  apply simp\n  done\n\nlemma binomial_Vandermonde_same: \"setsum (\\<lambda>k. (n choose k)\\<^sup>2) {0..n} = (2*n) choose n\"\n  using binomial_Vandermonde[of n n n,symmetric]\n  unfolding mult_2\n  apply (simp add: power2_eq_square)\n  apply (rule setsum.cong)\n  apply (auto intro:  binomial_symmetric)\n  done\n\nlemma Vandermonde_pochhammer_lemma:\n  fixes a :: \"'a::field_char_0\"\n  assumes b: \"\\<forall> j\\<in>{0 ..<n}. b \\<noteq> of_nat j\"\n  shows \"setsum (\\<lambda>k. (pochhammer (- a) k * pochhammer (- (of_nat n)) k) /\n      (of_nat (fact k) * pochhammer (b - of_nat n + 1) k)) {0..n} =\n    pochhammer (- (a + b)) n / pochhammer (- b) n\"\n  (is \"?l = ?r\")\nproof -\n  let ?m1 = \"\\<lambda>m. (- 1 :: 'a) ^ m\"\n  let ?f = \"\\<lambda>m. of_nat (fact m)\"\n  let ?p = \"\\<lambda>(x::'a). pochhammer (- x)\"\n  from b have bn0: \"?p b n \\<noteq> 0\" unfolding pochhammer_eq_0_iff by simp\n  {\n    fix k\n    assume kn: \"k \\<in> {0..n}\"\n    {\n      assume c:\"pochhammer (b - of_nat n + 1) n = 0\"\n      then obtain j where j: \"j < n\" \"b - of_nat n + 1 = - of_nat j\"\n        unfolding pochhammer_eq_0_iff by blast\n      from j have \"b = of_nat n - of_nat j - of_nat 1\"\n        by (simp add: algebra_simps)\n      then have \"b = of_nat (n - j - 1)\"\n        using j kn by (simp add: of_nat_diff)\n      with b have False using j by auto\n    }\n    then have nz: \"pochhammer (1 + b - of_nat n) n \\<noteq> 0\"\n      by (auto simp add: algebra_simps)\n\n    from nz kn [simplified] have nz': \"pochhammer (1 + b - of_nat n) k \\<noteq> 0\"\n      by (rule pochhammer_neq_0_mono)\n    {\n      assume k0: \"k = 0 \\<or> n =0\"\n      then have \"b gchoose (n - k) =\n        (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n        using kn\n        by (cases \"k = 0\") (simp_all add: gbinomial_pochhammer)\n    }\n    moreover\n    {\n      assume n0: \"n \\<noteq> 0\" and k0: \"k \\<noteq> 0\"\n      then obtain m where m: \"n = Suc m\" by (cases n) auto\n      from k0 obtain h where h: \"k = Suc h\" by (cases k) auto\n      {\n        assume kn: \"k = n\"\n        then have \"b gchoose (n - k) =\n          (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n          using kn pochhammer_minus'[where k=k and n=n and b=b]\n          apply (simp add:  pochhammer_same)\n          using bn0\n          apply (simp add: field_simps power_add[symmetric])\n          done\n      }\n      moreover\n      {\n        assume nk: \"k \\<noteq> n\"\n        have m1nk: \"?m1 n = setprod (\\<lambda>i. - 1) {0..m}\" \"?m1 k = setprod (\\<lambda>i. - 1) {0..h}\"\n          by (simp_all add: setprod_constant m h)\n        from kn nk have kn': \"k < n\" by simp\n        have bnz0: \"pochhammer (b - of_nat n + 1) k \\<noteq> 0\"\n          using bn0 kn\n          unfolding pochhammer_eq_0_iff\n          apply auto\n          apply (erule_tac x= \"n - ka - 1\" in allE)\n          apply (auto simp add: algebra_simps of_nat_diff)\n          done\n        have eq1: \"setprod (\\<lambda>k. (1::'a) + of_nat m - of_nat k) {0 .. h} =\n          setprod of_nat {Suc (m - h) .. Suc m}\"\n          using kn' h m\n          by (intro setprod.reindex_bij_witness[where i=\"\\<lambda>k. Suc m - k\" and j=\"\\<lambda>k. Suc m - k\"])\n             (auto simp: of_nat_diff)\n\n        have th1: \"(?m1 k * ?p (of_nat n) k) / ?f n = 1 / of_nat(fact (n - k))\"\n          unfolding m1nk\n          unfolding m h pochhammer_Suc_setprod\n          apply (simp add: field_simps del: fact_Suc)\n          unfolding fact_altdef_nat id_def\n          unfolding of_nat_setprod\n          unfolding setprod.distrib[symmetric]\n          apply auto\n          unfolding eq1\n          apply (subst setprod.union_disjoint[symmetric])\n          apply (auto)\n          apply (rule setprod.cong)\n          apply auto\n          done\n        have th20: \"?m1 n * ?p b n = setprod (\\<lambda>i. b - of_nat i) {0..m}\"\n          unfolding m1nk\n          unfolding m h pochhammer_Suc_setprod\n          unfolding setprod.distrib[symmetric]\n          apply (rule setprod.cong)\n          apply auto\n          done\n        have th21:\"pochhammer (b - of_nat n + 1) k = setprod (\\<lambda>i. b - of_nat i) {n - k .. n - 1}\"\n          unfolding h m\n          unfolding pochhammer_Suc_setprod\n          using kn m h\n          by (intro setprod.reindex_bij_witness[where i=\"\\<lambda>k. n - 1 - k\" and j=\"\\<lambda>i. m-i\"])\n             (auto simp: of_nat_diff)\n\n        have \"?m1 n * ?p b n =\n          pochhammer (b - of_nat n + 1) k * setprod (\\<lambda>i. b - of_nat i) {0.. n - k - 1}\"\n          unfolding th20 th21\n          unfolding h m\n          apply (subst setprod.union_disjoint[symmetric])\n          using kn' h m\n          apply auto\n          apply (rule setprod.cong)\n          apply auto\n          done\n        then have th2: \"(?m1 n * ?p b n)/pochhammer (b - of_nat n + 1) k =\n          setprod (\\<lambda>i. b - of_nat i) {0.. n - k - 1}\"\n          using nz' by (simp add: field_simps)\n        have \"(?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k) =\n          ((?m1 k * ?p (of_nat n) k) / ?f n) * ((?m1 n * ?p b n)/pochhammer (b - of_nat n + 1) k)\"\n          using bnz0\n          by (simp add: field_simps)\n        also have \"\\<dots> = b gchoose (n - k)\"\n          unfolding th1 th2\n          using kn' by (simp add: gbinomial_def)\n        finally have \"b gchoose (n - k) =\n          (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n          by simp\n      }\n      ultimately\n      have \"b gchoose (n - k) =\n        (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n        by (cases \"k = n\") auto\n    }\n    ultimately have \"b gchoose (n - k) =\n        (?m1 n * ?p b n * ?m1 k * ?p (of_nat n) k) / (?f n * pochhammer (b - of_nat n + 1) k)\"\n      \"pochhammer (1 + b - of_nat n) k \\<noteq> 0 \"\n      apply (cases \"n = 0\")\n      using nz'\n      apply auto\n      apply (cases k)\n      apply auto\n      done\n  }\n  note th00 = this\n  have \"?r = ((a + b) gchoose n) * (of_nat (fact n)/ (?m1 n * pochhammer (- b) n))\"\n    unfolding gbinomial_pochhammer\n    using bn0 by (auto simp add: field_simps)\n  also have \"\\<dots> = ?l\"\n    unfolding gbinomial_Vandermonde[symmetric]\n    apply (simp add: th00)\n    unfolding gbinomial_pochhammer\n    using bn0\n    apply (simp add: setsum_left_distrib setsum_right_distrib field_simps)\n    apply (rule setsum.cong)\n    apply (rule refl)\n    apply (drule th00(2))\n    apply (simp add: field_simps power_add[symmetric])\n    done\n  finally show ?thesis by simp\nqed\n\nlemma Vandermonde_pochhammer:\n  fixes a :: \"'a::field_char_0\"\n  assumes c: \"\\<forall>i \\<in> {0..< n}. c \\<noteq> - of_nat i\"\n  shows \"setsum (\\<lambda>k. (pochhammer a k * pochhammer (- (of_nat n)) k) /\n    (of_nat (fact k) * pochhammer c k)) {0..n} = pochhammer (c - a) n / pochhammer c n\"\nproof -\n  let ?a = \"- a\"\n  let ?b = \"c + of_nat n - 1\"\n  have h: \"\\<forall> j \\<in>{0..< n}. ?b \\<noteq> of_nat j\" using c\n    apply (auto simp add: algebra_simps of_nat_diff)\n    apply (erule_tac x= \"n - j - 1\" in ballE)\n    apply (auto simp add: of_nat_diff algebra_simps)\n    done\n  have th0: \"pochhammer (- (?a + ?b)) n = (- 1)^n * pochhammer (c - a) n\"\n    unfolding pochhammer_minus[OF le_refl]\n    by (simp add: algebra_simps)\n  have th1: \"pochhammer (- ?b) n = (- 1)^n * pochhammer c n\"\n    unfolding pochhammer_minus[OF le_refl]\n    by simp\n  have nz: \"pochhammer c n \\<noteq> 0\" using c\n    by (simp add: pochhammer_eq_0_iff)\n  from Vandermonde_pochhammer_lemma[where a = \"?a\" and b=\"?b\" and n=n, OF h, unfolded th0 th1]\n  show ?thesis using nz by (simp add: field_simps setsum_right_distrib)\nqed\n\n\nsubsubsection{* Formal trigonometric functions  *}\n\ndefinition \"fps_sin (c::'a::field_char_0) =\n  Abs_fps (\\<lambda>n. if even n then 0 else (- 1) ^((n - 1) div 2) * c^n /(of_nat (fact n)))\"\n\ndefinition \"fps_cos (c::'a::field_char_0) =\n  Abs_fps (\\<lambda>n. if even n then (- 1) ^ (n div 2) * c^n / (of_nat (fact n)) else 0)\"\n\nlemma fps_sin_deriv:\n  \"fps_deriv (fps_sin c) = fps_const c * fps_cos c\"\n  (is \"?lhs = ?rhs\")\nproof (rule fps_ext)\n  fix n :: nat\n  {\n    assume en: \"even n\"\n    have \"?lhs$n = of_nat (n+1) * (fps_sin c $ (n+1))\" by simp\n    also have \"\\<dots> = of_nat (n+1) * ((- 1)^(n div 2) * c^Suc n / of_nat (fact (Suc n)))\"\n      using en by (simp add: fps_sin_def)\n    also have \"\\<dots> = (- 1)^(n div 2) * c^Suc n * (of_nat (n+1) / (of_nat (Suc n) * of_nat (fact n)))\"\n      unfolding fact_Suc of_nat_mult\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    also have \"\\<dots> = (- 1)^(n div 2) *c^Suc n / of_nat (fact n)\"\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    finally have \"?lhs $n = ?rhs$n\" using en\n      by (simp add: fps_cos_def field_simps)\n  }\n  then show \"?lhs $ n = ?rhs $ n\"\n    by (cases \"even n\") (simp_all add: fps_deriv_def fps_sin_def fps_cos_def)\nqed\n\nlemma fps_cos_deriv: \"fps_deriv (fps_cos c) = fps_const (- c)* (fps_sin c)\"\n  (is \"?lhs = ?rhs\")\nproof (rule fps_ext)\n  have th0: \"\\<And>n. - ((- 1::'a) ^ n) = (- 1)^Suc n\" by simp\n  have th1: \"\\<And>n. odd n \\<Longrightarrow> Suc ((n - 1) div 2) = Suc n div 2\"\n    by (case_tac n, simp_all)\n  fix n::nat\n  {\n    assume en: \"odd n\"\n    from en have n0: \"n \\<noteq>0 \" by presburger\n    have \"?lhs$n = of_nat (n+1) * (fps_cos c $ (n+1))\" by simp\n    also have \"\\<dots> = of_nat (n+1) * ((- 1)^((n + 1) div 2) * c^Suc n / of_nat (fact (Suc n)))\"\n      using en by (simp add: fps_cos_def)\n    also have \"\\<dots> = (- 1)^((n + 1) div 2)*c^Suc n * (of_nat (n+1) / (of_nat (Suc n) * of_nat (fact n)))\"\n      unfolding fact_Suc of_nat_mult\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    also have \"\\<dots> = (- 1)^((n + 1) div 2) * c^Suc n / of_nat (fact n)\"\n      by (simp add: field_simps del: of_nat_add of_nat_Suc)\n    also have \"\\<dots> = (- ((- 1)^((n - 1) div 2))) * c^Suc n / of_nat (fact n)\"\n      unfolding th0 unfolding th1[OF en] by simp\n    finally have \"?lhs $n = ?rhs$n\" using en\n      by (simp add: fps_sin_def field_simps)\n  }\n  then show \"?lhs $ n = ?rhs $ n\"\n    by (cases \"even n\") (simp_all add: fps_deriv_def fps_sin_def fps_cos_def)\nqed\n\nlemma fps_sin_cos_sum_of_squares:\n  \"(fps_cos c)\\<^sup>2 + (fps_sin c)\\<^sup>2 = 1\" (is \"?lhs = 1\")\nproof -\n  have \"fps_deriv ?lhs = 0\"\n    apply (simp add:  fps_deriv_power fps_sin_deriv fps_cos_deriv)\n    apply (simp add: field_simps fps_const_neg[symmetric] del: fps_const_neg)\n    done\n  then have \"?lhs = fps_const (?lhs $ 0)\"\n    unfolding fps_deriv_eq_0_iff .\n  also have \"\\<dots> = 1\"\n    by (auto simp add: fps_eq_iff numeral_2_eq_2 fps_mult_nth fps_cos_def fps_sin_def)\n  finally show ?thesis .\nqed\n\nlemma divide_eq_iff: \"a \\<noteq> (0::'a::field) \\<Longrightarrow> x / a = y \\<longleftrightarrow> x = y * a\"\n  by auto\n\nlemma eq_divide_iff: \"a \\<noteq> (0::'a::field) \\<Longrightarrow> x = y / a \\<longleftrightarrow> x * a = y\"\n  by auto\n\nlemma fps_sin_nth_0 [simp]: \"fps_sin c $ 0 = 0\"\n  unfolding fps_sin_def by simp\n\nlemma fps_sin_nth_1 [simp]: \"fps_sin c $ 1 = c\"\n  unfolding fps_sin_def by simp\n\nlemma fps_sin_nth_add_2:\n  \"fps_sin c $ (n + 2) = - (c * c * fps_sin c $ n / (of_nat(n+1) * of_nat(n+2)))\"\n  unfolding fps_sin_def\n  apply (cases n, simp)\n  apply (simp add: divide_eq_iff eq_divide_iff del: of_nat_Suc fact_Suc)\n  apply (simp add: of_nat_mult del: of_nat_Suc mult_Suc)\n  done\n\nlemma fps_cos_nth_0 [simp]: \"fps_cos c $ 0 = 1\"\n  unfolding fps_cos_def by simp\n\nlemma fps_cos_nth_1 [simp]: \"fps_cos c $ 1 = 0\"\n  unfolding fps_cos_def by simp\n\nlemma fps_cos_nth_add_2:\n  \"fps_cos c $ (n + 2) = - (c * c * fps_cos c $ n / (of_nat(n+1) * of_nat(n+2)))\"\n  unfolding fps_cos_def\n  apply (simp add: divide_eq_iff eq_divide_iff del: of_nat_Suc fact_Suc)\n  apply (simp add: of_nat_mult del: of_nat_Suc mult_Suc)\n  done\n\nlemma nat_induct2: \"P 0 \\<Longrightarrow> P 1 \\<Longrightarrow> (\\<And>n. P n \\<Longrightarrow> P (n + 2)) \\<Longrightarrow> P (n::nat)\"\n  unfolding One_nat_def numeral_2_eq_2\n  apply (induct n rule: nat_less_induct)\n  apply (case_tac n)\n  apply simp\n  apply (rename_tac m)\n  apply (case_tac m)\n  apply simp\n  apply (rename_tac k)\n  apply (case_tac k)\n  apply simp_all\n  done\n\nlemma nat_add_1_add_1: \"(n::nat) + 1 + 1 = n + 2\"\n  by simp\n\nlemma eq_fps_sin:\n  assumes 0: \"a $ 0 = 0\"\n    and 1: \"a $ 1 = c\"\n    and 2: \"fps_deriv (fps_deriv a) = - (fps_const c * fps_const c * a)\"\n  shows \"a = fps_sin c\"\n  apply (rule fps_ext)\n  apply (induct_tac n rule: nat_induct2)\n  apply (simp add: 0)\n  apply (simp add: 1 del: One_nat_def)\n  apply (rename_tac m, cut_tac f=\"\\<lambda>a. a $ m\" in arg_cong [OF 2])\n  apply (simp add: nat_add_1_add_1 fps_sin_nth_add_2\n              del: One_nat_def of_nat_Suc of_nat_add add_2_eq_Suc')\n  apply (subst minus_divide_left)\n  apply (subst eq_divide_iff)\n  apply (simp del: of_nat_add of_nat_Suc)\n  apply (simp only: ac_simps)\n  done\n\nlemma eq_fps_cos:\n  assumes 0: \"a $ 0 = 1\"\n    and 1: \"a $ 1 = 0\"\n    and 2: \"fps_deriv (fps_deriv a) = - (fps_const c * fps_const c * a)\"\n  shows \"a = fps_cos c\"\n  apply (rule fps_ext)\n  apply (induct_tac n rule: nat_induct2)\n  apply (simp add: 0)\n  apply (simp add: 1 del: One_nat_def)\n  apply (rename_tac m, cut_tac f=\"\\<lambda>a. a $ m\" in arg_cong [OF 2])\n  apply (simp add: nat_add_1_add_1 fps_cos_nth_add_2\n              del: One_nat_def of_nat_Suc of_nat_add add_2_eq_Suc')\n  apply (subst minus_divide_left)\n  apply (subst eq_divide_iff)\n  apply (simp del: of_nat_add of_nat_Suc)\n  apply (simp only: ac_simps)\n  done\n\nlemma mult_nth_0 [simp]: \"(a * b) $ 0 = a $ 0 * b $ 0\"\n  by (simp add: fps_mult_nth)\n\nlemma mult_nth_1 [simp]: \"(a * b) $ 1 = a $ 0 * b $ 1 + a $ 1 * b $ 0\"\n  by (simp add: fps_mult_nth)\n\nlemma fps_sin_add: \"fps_sin (a + b) = fps_sin a * fps_cos b + fps_cos a * fps_sin b\"\n  apply (rule eq_fps_sin [symmetric], simp, simp del: One_nat_def)\n  apply (simp del: fps_const_neg fps_const_add fps_const_mult\n              add: fps_const_add [symmetric] fps_const_neg [symmetric]\n                   fps_sin_deriv fps_cos_deriv algebra_simps)\n  done\n\nlemma fps_cos_add: \"fps_cos (a + b) = fps_cos a * fps_cos b - fps_sin a * fps_sin b\"\n  apply (rule eq_fps_cos [symmetric], simp, simp del: One_nat_def)\n  apply (simp del: fps_const_neg fps_const_add fps_const_mult\n              add: fps_const_add [symmetric] fps_const_neg [symmetric]\n                   fps_sin_deriv fps_cos_deriv algebra_simps)\n  done\n\nlemma fps_sin_even: \"fps_sin (- c) = - fps_sin c\"\n  by (auto simp add: fps_eq_iff fps_sin_def)\n\nlemma fps_cos_odd: \"fps_cos (- c) = fps_cos c\"\n  by (auto simp add: fps_eq_iff fps_cos_def)\n\ndefinition \"fps_tan c = fps_sin c / fps_cos c\"\n\nlemma fps_tan_deriv: \"fps_deriv (fps_tan c) = fps_const c / (fps_cos c)\\<^sup>2\"\nproof -\n  have th0: \"fps_cos c $ 0 \\<noteq> 0\" by (simp add: fps_cos_def)\n  show ?thesis\n    using fps_sin_cos_sum_of_squares[of c]\n    apply (simp add: fps_tan_def fps_divide_deriv[OF th0] fps_sin_deriv fps_cos_deriv\n      fps_const_neg[symmetric] field_simps power2_eq_square del: fps_const_neg)\n    unfolding distrib_left[symmetric]\n    apply simp\n    done\nqed\n\ntext {* Connection to E c over the complex numbers --- Euler and De Moivre*}\nlemma Eii_sin_cos: \"E (ii * c) = fps_cos c + fps_const ii * fps_sin c \"\n  (is \"?l = ?r\")\nproof -\n  { fix n :: nat\n    {\n      assume en: \"even n\"\n      from en obtain m where m: \"n = 2 * m\" ..\n\n      have \"?l $n = ?r$n\"\n        by (simp add: m fps_sin_def fps_cos_def power_mult_distrib power_mult power_minus [of \"c ^ 2\"])\n    }\n    moreover\n    {\n      assume \"odd n\"\n      then obtain m where m: \"n = 2 * m + 1\" ..\n      have \"?l $n = ?r$n\"\n        by (simp add: m fps_sin_def fps_cos_def power_mult_distrib\n          power_mult power_minus [of \"c ^ 2\"])\n    }\n    ultimately have \"?l $n = ?r$n\"  by blast\n  } then show ?thesis by (simp add: fps_eq_iff)\nqed\n\nlemma E_minus_ii_sin_cos: \"E (- (ii * c)) = fps_cos c - fps_const ii * fps_sin c\"\n  unfolding minus_mult_right Eii_sin_cos by (simp add: fps_sin_even fps_cos_odd)\n\nlemma fps_const_minus: \"fps_const (c::'a::group_add) - fps_const d = fps_const (c - d)\"\n  by (simp add: fps_eq_iff fps_const_def)\n\nlemma fps_numeral_fps_const: \"numeral i = fps_const (numeral i :: 'a::comm_ring_1)\"\n  by (fact numeral_fps_const) (* FIXME: duplicate *)\n\nlemma fps_cos_Eii: \"fps_cos c = (E (ii * c) + E (- ii * c)) / fps_const 2\"\nproof -\n  have th: \"fps_cos c + fps_cos c = fps_cos c * fps_const 2\"\n    by (simp add: numeral_fps_const)\n  show ?thesis\n  unfolding Eii_sin_cos minus_mult_commute\n  by (simp add: fps_sin_even fps_cos_odd numeral_fps_const fps_divide_def fps_const_inverse th)\nqed\n\nlemma fps_sin_Eii: \"fps_sin c = (E (ii * c) - E (- ii * c)) / fps_const (2*ii)\"\nproof -\n  have th: \"fps_const \\<i> * fps_sin c + fps_const \\<i> * fps_sin c = fps_sin c * fps_const (2 * ii)\"\n    by (simp add: fps_eq_iff numeral_fps_const)\n  show ?thesis\n    unfolding Eii_sin_cos minus_mult_commute\n    by (simp add: fps_sin_even fps_cos_odd fps_divide_def fps_const_inverse th)\nqed\n\nlemma fps_tan_Eii:\n  \"fps_tan c = (E (ii * c) - E (- ii * c)) / (fps_const ii * (E (ii * c) + E (- ii * c)))\"\n  unfolding fps_tan_def fps_sin_Eii fps_cos_Eii mult_minus_left E_neg\n  apply (simp add: fps_divide_def fps_inverse_mult fps_const_mult[symmetric] fps_const_inverse del: fps_const_mult)\n  apply simp\n  done\n\nlemma fps_demoivre: \"(fps_cos a + fps_const ii * fps_sin a)^n = fps_cos (of_nat n * a) + fps_const ii * fps_sin (of_nat n * a)\"\n  unfolding Eii_sin_cos[symmetric] E_power_mult\n  by (simp add: ac_simps)\n\n\nsubsection {* Hypergeometric series *}\n\ndefinition \"F as bs (c::'a::{field_char_0,field_inverse_zero}) =\n  Abs_fps (\\<lambda>n. (foldl (\\<lambda>r a. r* pochhammer a n) 1 as * c^n) /\n    (foldl (\\<lambda>r b. r * pochhammer b n) 1 bs * of_nat (fact n)))\"\n\nlemma F_nth[simp]: \"F as bs c $ n =\n  (foldl (\\<lambda>r a. r* pochhammer a n) 1 as * c^n) /\n    (foldl (\\<lambda>r b. r * pochhammer b n) 1 bs * of_nat (fact n))\"\n  by (simp add: F_def)\n\nlemma foldl_mult_start:\n  fixes v :: \"'a::comm_ring_1\"\n  shows \"foldl (\\<lambda>r x. r * f x) v as * x = foldl (\\<lambda>r x. r * f x) (v * x) as \"\n  by (induct as arbitrary: x v) (auto simp add: algebra_simps)\n\nlemma foldr_mult_foldl:\n  fixes v :: \"'a::comm_ring_1\"\n  shows \"foldr (\\<lambda>x r. r * f x) as v = foldl (\\<lambda>r x. r * f x) v as\"\n  by (induct as arbitrary: v) (auto simp add: foldl_mult_start)\n\nlemma F_nth_alt:\n  \"F as bs c $ n = foldr (\\<lambda>a r. r * pochhammer a n) as (c ^ n) /\n    foldr (\\<lambda>b r. r * pochhammer b n) bs (of_nat (fact n))\"\n  by (simp add: foldl_mult_start foldr_mult_foldl)\n\nlemma F_E[simp]: \"F [] [] c = E c\"\n  by (simp add: fps_eq_iff)\n\nlemma F_1_0[simp]: \"F [1] [] c = 1/(1 - fps_const c * X)\"\nproof -\n  let ?a = \"(Abs_fps (\\<lambda>n. 1)) oo (fps_const c * X)\"\n  have th0: \"(fps_const c * X) $ 0 = 0\" by simp\n  show ?thesis unfolding gp[OF th0, symmetric]\n    by (auto simp add: fps_eq_iff pochhammer_fact[symmetric]\n      fps_compose_nth power_mult_distrib cond_value_iff setsum.delta' cong del: if_weak_cong)\nqed\n\nlemma F_B[simp]: \"F [-a] [] (- 1) = fps_binomial a\"\n  by (simp add: fps_eq_iff gbinomial_pochhammer algebra_simps)\n\nlemma F_0[simp]: \"F as bs c $0 = 1\"\n  apply simp\n  apply (subgoal_tac \"\\<forall>as. foldl (\\<lambda>(r::'a) (a::'a). r) 1 as = 1\")\n  apply auto\n  apply (induct_tac as)\n  apply auto\n  done\n\nlemma foldl_prod_prod:\n  \"foldl (\\<lambda>(r::'b::comm_ring_1) (x::'a::comm_ring_1). r * f x) v as * foldl (\\<lambda>r x. r * g x) w as =\n    foldl (\\<lambda>r x. r * f x * g x) (v * w) as\"\n  by (induct as arbitrary: v w) (auto simp add: algebra_simps)\n\n\nlemma F_rec:\n  \"F as bs c $ Suc n = ((foldl (\\<lambda>r a. r* (a + of_nat n)) c as) /\n    (foldl (\\<lambda>r b. r * (b + of_nat n)) (of_nat (Suc n)) bs )) * F as bs c $ n\"\n  apply (simp del: of_nat_Suc of_nat_add fact_Suc)\n  apply (simp add: foldl_mult_start del: fact_Suc of_nat_Suc)\n  unfolding foldl_prod_prod[unfolded foldl_mult_start] pochhammer_Suc\n  apply (simp add: algebra_simps of_nat_mult)\n  done\n\nlemma XD_nth[simp]: \"XD a $ n = (if n = 0 then 0 else of_nat n * a$n)\"\n  by (simp add: XD_def)\n\nlemma XD_0th[simp]: \"XD a $ 0 = 0\" by simp\nlemma XD_Suc[simp]:\" XD a $ Suc n = of_nat (Suc n) * a $ Suc n\" by simp\n\ndefinition \"XDp c a = XD a + fps_const c * a\"\n\nlemma XDp_nth[simp]: \"XDp c a $ n = (c + of_nat n) * a$n\"\n  by (simp add: XDp_def algebra_simps)\n\nlemma XDp_commute: \"XDp b \\<circ> XDp (c::'a::comm_ring_1) = XDp c \\<circ> XDp b\"\n  by (auto simp add: XDp_def fun_eq_iff fps_eq_iff algebra_simps)\n\nlemma XDp0 [simp]: \"XDp 0 = XD\"\n  by (simp add: fun_eq_iff fps_eq_iff)\n\nlemma XDp_fps_integral [simp]: \"XDp 0 (fps_integral a c) = X * a\"\n  by (simp add: fps_eq_iff fps_integral_def)\n\nlemma F_minus_nat:\n  \"F [- of_nat n] [- of_nat (n + m)] (c::'a::{field_char_0,field_inverse_zero}) $ k =\n    (if k \\<le> n then\n      pochhammer (- of_nat n) k * c ^ k / (pochhammer (- of_nat (n + m)) k * of_nat (fact k))\n     else 0)\"\n  \"F [- of_nat m] [- of_nat (m + n)] (c::'a::{field_char_0,field_inverse_zero}) $ k =\n    (if k \\<le> m then\n      pochhammer (- of_nat m) k * c ^ k / (pochhammer (- of_nat (m + n)) k * of_nat (fact k))\n     else 0)\"\n  by (auto simp add: pochhammer_eq_0_iff)\n\nlemma setsum_eq_if: \"setsum f {(n::nat) .. m} = (if m < n then 0 else f n + setsum f {n+1 .. m})\"\n  apply simp\n  apply (subst setsum.insert[symmetric])\n  apply (auto simp add: not_less setsum_head_Suc)\n  done\n\nlemma pochhammer_rec_if: \"pochhammer a n = (if n = 0 then 1 else a * pochhammer (a + 1) (n - 1))\"\n  by (cases n) (simp_all add: pochhammer_rec)\n\nlemma XDp_foldr_nth [simp]: \"foldr (\\<lambda>c r. XDp c \\<circ> r) cs (\\<lambda>c. XDp c a) c0 $ n =\n    foldr (\\<lambda>c r. (c + of_nat n) * r) cs (c0 + of_nat n) * a$n\"\n  by (induct cs arbitrary: c0) (auto simp add: algebra_simps)\n\nlemma genric_XDp_foldr_nth:\n  assumes f: \"\\<forall>n c a. f c a $ n = (of_nat n + k c) * a$n\"\n  shows \"foldr (\\<lambda>c r. f c \\<circ> r) cs (\\<lambda>c. g c a) c0 $ n =\n    foldr (\\<lambda>c r. (k c + of_nat n) * r) cs (g c0 a $ n)\"\n  by (induct cs arbitrary: c0) (auto simp add: algebra_simps f)\n\nlemma dist_less_imp_nth_equal:\n  assumes \"dist f g < inverse (2 ^ i)\"\n    and\"j \\<le> i\"\n  shows \"f $ j = g $ j\"\nproof (rule ccontr)\n  assume \"f $ j \\<noteq> g $ j\"\n  then have \"\\<exists>n. f $ n \\<noteq> g $ n\" by auto\n  with assms have \"i < (LEAST n. f $ n \\<noteq> g $ n)\"\n    by (simp add: split_if_asm dist_fps_def)\n  also have \"\\<dots> \\<le> j\"\n    using `f $ j \\<noteq> g $ j` by (auto intro: Least_le)\n  finally show False using `j \\<le> i` by simp\nqed\n\nlemma nth_equal_imp_dist_less:\n  assumes \"\\<And>j. j \\<le> i \\<Longrightarrow> f $ j = g $ j\"\n  shows \"dist f g < inverse (2 ^ i)\"\nproof (cases \"f = g\")\n  case False\n  then have \"\\<exists>n. f $ n \\<noteq> g $ n\" by (simp add: fps_eq_iff)\n  with assms have \"dist f g = inverse (2 ^ (LEAST n. f $ n \\<noteq> g $ n))\"\n    by (simp add: split_if_asm dist_fps_def)\n  moreover\n  from assms `\\<exists>n. f $ n \\<noteq> g $ n` have \"i < (LEAST n. f $ n \\<noteq> g $ n)\"\n    by (metis (mono_tags) LeastI not_less)\n  ultimately show ?thesis by simp\nqed simp\n\nlemma dist_less_eq_nth_equal: \"dist f g < inverse (2 ^ i) \\<longleftrightarrow> (\\<forall>j \\<le> i. f $ j = g $ j)\"\n  using dist_less_imp_nth_equal nth_equal_imp_dist_less by blast\n\ninstance fps :: (comm_ring_1) complete_space\nproof\n  fix X :: \"nat \\<Rightarrow> 'a fps\"\n  assume \"Cauchy X\"\n  {\n    fix i\n    have \"0 < inverse ((2::real)^i)\" by simp\n    from metric_CauchyD[OF `Cauchy X` this] dist_less_imp_nth_equal\n    have \"\\<exists>M. \\<forall>m \\<ge> M. \\<forall>j\\<le>i. X M $ j = X m $ j\" by blast\n  }\n  then obtain M where M: \"\\<forall>i. \\<forall>m \\<ge> M i. \\<forall>j \\<le> i. X (M i) $ j = X m $ j\" by metis\n  then have \"\\<forall>i. \\<forall>m \\<ge> M i. \\<forall>j \\<le> i. X (M i) $ j = X m $ j\" by metis\n  show \"convergent X\"\n  proof (rule convergentI)\n    show \"X ----> Abs_fps (\\<lambda>i. X (M i) $ i)\"\n      unfolding tendsto_iff\n    proof safe\n      fix e::real assume \"0 < e\"\n      with LIMSEQ_inverse_realpow_zero[of 2, simplified, simplified filterlim_iff,\n        THEN spec, of \"\\<lambda>x. x < e\"]\n      have \"eventually (\\<lambda>i. inverse (2 ^ i) < e) sequentially\"\n        apply safe\n        apply (auto simp: eventually_nhds)\n        done\n      then obtain i where \"inverse (2 ^ i) < e\" by (auto simp: eventually_sequentially)\n      have \"eventually (\\<lambda>x. M i \\<le> x) sequentially\" by (auto simp: eventually_sequentially)\n      then show \"eventually (\\<lambda>x. dist (X x) (Abs_fps (\\<lambda>i. X (M i) $ i)) < e) sequentially\"\n      proof eventually_elim\n        fix x\n        assume \"M i \\<le> x\"\n        moreover\n        have \"\\<And>j. j \\<le> i \\<Longrightarrow> X (M i) $ j = X (M j) $ j\"\n          using M by (metis nat_le_linear)\n        ultimately have \"dist (X x) (Abs_fps (\\<lambda>j. X (M j) $ j)) < inverse (2 ^ i)\"\n          using M by (force simp: dist_less_eq_nth_equal)\n        also note `inverse (2 ^ i) < e`\n        finally show \"dist (X x) (Abs_fps (\\<lambda>j. X (M j) $ j)) < e\" .\n      qed\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Formal_Power_Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258009, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7915192292888634}}
{"text": "chapter \\<open>Homework 2\\<close>\ntheory Homework2\nimports Main\nbegin\n  \n  (*\n    This file is intended to be viewed within the Isabelle/jEdit IDE.\n    In a standard text-editor, it is pretty unreadable!\n  *)\n\n  (*\n    HOMEWORK #2\n    RELEASED: Tue, Aug 19 2017\n    DUE:      Tue, Aug 26, 2017, 11:59pm\n\n    To be submitted via canvas.\n  *)\n  \n\nsection \\<open>General Hints\\<close>  \n(*\n  The best way to work on this homework is to fill in the missing gaps in this file.\n\n  Try to go for simple function definitions, as simple definitions mean simple proofs!\n  In particular, do not go for a more complicated definition only b/c it may be more efficient!\n\n\n  The proofs should work with induction (structural/computations), \n  and some generalizations, followed by auto to solve the subgoals.\n  You may have to add some simp-lemmas to auto, which we will hint at.\n \n  We indicate were auxiliary lemmas are likely to be needed.\n  However, as proofs depend on your definitions, we cannot predict every corner \n  case that you may run into. Changing the definition to something simpler might \n  help to get a simpler proof.\n\n\n*)  \n  \n\nsection \\<open>For all elements in list\\<close>    \n  (* Define a function that checks wether a predicate P holds for all elements in a list.\n     Note: A predicate is just a function of type \"'a \\<Rightarrow> bool\". It must evaluate to True for all elements in the list.\n  *)\n  \n  fun listall :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n    \"listall P [] \\<longleftrightarrow> True\" (* Return True for the empty list. *)\n    (* Add your equation(s) here *)\n\n  (* Show: P holds for all elements of xs@ys, if and only if it holds for all elements of xs and for all elements of ys: *)  \n  lemma \"listall P (xs@ys) \\<longleftrightarrow> listall P xs \\<and> listall P ys\"  \n    oops\n\n  (* Show: When checking P for a  mapped list, we can also apply the function before we evaluate P *)    \n  lemma \"listall P (map f xs) = listall (\\<lambda>x. P (f x)) xs\"\n    oops\n  \n  (* Specify and show: If we filter the list with P, all elements in the result will satisfy P.\n    Note: In this exercise, you have to come up with both, the formula and the proof!\n  *)    \n  lemma \"add your formula here and prove it\" oops\n  \n  \nsection \\<open>Sum of elements in a list\\<close>  \n  \n(* Specify a function to sum up all elements in a list of integers. The empty list has sum 0. *)  \n  \n  fun listsum :: \"int list \\<Rightarrow> int\" where\n    \"listsum _ = undefined\"\n    (* Replace by your equation(s) *)\n  \n  (* Show the following lemmas: *)\n\n  (* Instead of summing over xs@ys, we can also add the results from summing over xs and summing over ys *)  \n  lemma listsum_append: \"listsum (xs@ys) = listsum xs + listsum ys\"\n    oops    \n      \n  (* Filtering out zeroes does not affect the sum *)    \n  lemma listsum_filter_z: \"listsum (filter (op\\<noteq>0) l) = listsum l\"  \n    oops\n\n  (* Reversing a list does not affect the sum. HINT: You'll need an auxiliary lemma. (that you already have proved) *)\n  lemma listsum_rev: \"listsum (rev xs) = listsum xs\"    \n    oops\n    \n  (* Specify and prove: If summing up a list with only non-negative numbers, the result will be non-negative: *)  \n      \n  lemma \"add formula and prove it\" oops\n    \n    \nsection \\<open>Bonus: Delta-Encoding\\<close>      \n  (*\n    We want to encode a list of integers as follows: \n      The first element is unchanged, and every next element \n      only indicates the difference to its predecessor.\n\n      For example: (Hint: Use this as test cases for your spec!)\n        enc [1,2,4,8] = [1,1,2,4]\n        enc [3,4,5] = [3,1,1]\n        enc [5] = [5]\n        enc [] = []\n      \n\n      Background: This algorithm may be used in lossless data compression, \n        when the difference between two adjacent values is expected to be \n        small, e.g., audio data, image data, sensor data.\n\n        It typically requires much less space to store the small deltas, than \n        the absolute values. \n\n        Disadvantage: If the stream gets corrupted, recovery is only possible \n          when the next absolute value is transmitted. For this reason, in \n          practice, one will submit the current absolute value from time to \n          time. (This is not modeled in this exercise!)\n\n\n\n  *)\n      \n  \n  (* Specify a function to encode a list with delta-encoding. \n    The first argument is used to represent the previous value, and can be initialized to 0.\n  *)\n  fun denc :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n    \"denc _ _ = undefined\"\n    (* Replace by your equation(s) *)\n  \n  (* Specify the decoder. Again, the first argument represents the previous \n      decoded value, and can be initialized to 0. *)  \n  fun ddec :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n    \"ddec _ _ = undefined\"\n    (* Replace by your equation(s) *)\n  \n  (* Show that encoding and then decoding yields the same list. HINT: The lemma will need generalization. *)  \n  lemma \"ddec 0 (denc 0 l) = l\" \n    oops\n      \n      \nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Homeworks/Homework2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.8902942144788076, "lm_q1q2_score": 0.7912568197831332}}
{"text": "section \\<open>Formalization of Bit Vectors\\<close>\n\ntheory BitVector imports Main begin\n\ntype_synonym bit_vector = \"bool list\"\n\nfun bv_leqs :: \"bit_vector \\<Rightarrow> bit_vector \\<Rightarrow> bool\" (\"_ \\<preceq>\\<^sub>b _\" 99)\n  where bv_Nils:\"[] \\<preceq>\\<^sub>b [] = True\"\n  | bv_Cons:\"(x#xs) \\<preceq>\\<^sub>b (y#ys) = ((x \\<longrightarrow> y) \\<and> xs \\<preceq>\\<^sub>b ys)\"\n  | bv_rest:\"xs \\<preceq>\\<^sub>b ys = False\"\n\n\nsubsection \\<open>Some basic properties\\<close>\n\nlemma bv_length: \"xs \\<preceq>\\<^sub>b ys \\<Longrightarrow> length xs = length ys\"\nby(induct rule:bv_leqs.induct)auto\n\n\nlemma [dest!]: \"xs \\<preceq>\\<^sub>b [] \\<Longrightarrow> xs = []\"\nby(induct xs) auto\n\n\nlemma bv_leqs_AppendI:\n  \"\\<lbrakk>xs \\<preceq>\\<^sub>b ys; xs' \\<preceq>\\<^sub>b ys'\\<rbrakk> \\<Longrightarrow> (xs@xs') \\<preceq>\\<^sub>b (ys@ys')\"\nby(induct xs ys rule:bv_leqs.induct,auto)\n\n\nlemma bv_leqs_AppendD:\n  \"\\<lbrakk>(xs@xs') \\<preceq>\\<^sub>b (ys@ys'); length xs = length ys\\<rbrakk>\n  \\<Longrightarrow> xs \\<preceq>\\<^sub>b ys \\<and> xs' \\<preceq>\\<^sub>b ys'\"\nby(induct xs ys rule:bv_leqs.induct,auto)\n\n\nlemma bv_leqs_eq:\n  \"xs \\<preceq>\\<^sub>b ys = ((\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i) \\<and> length xs = length ys)\"\nproof(induct xs ys rule:bv_leqs.induct)\n  case (2 x xs y ys)\n  note eq = \\<open>xs \\<preceq>\\<^sub>b ys = \n    ((\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i) \\<and> length xs = length ys)\\<close>\n  show ?case\n  proof\n    assume leqs:\"x#xs \\<preceq>\\<^sub>b y#ys\"\n    with eq have \"x \\<longrightarrow> y\" and \"\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i\"\n      and \"length xs = length ys\" by simp_all\n    from \\<open>x \\<longrightarrow> y\\<close> have \"(x#xs) ! 0 \\<longrightarrow> (y#ys) ! 0\" by simp\n    { fix i assume \"i > 0\" and \"i < length (x#xs)\"\n      then obtain j where \"i = Suc j\" and \"j < length xs\" by(cases i) auto\n      with \\<open>\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i\\<close> \n      have \"(x#xs) ! i \\<longrightarrow> (y#ys) ! i\" by auto }\n    hence \"\\<forall>i < length (x#xs). i > 0 \\<longrightarrow> (x#xs) ! i \\<longrightarrow> (y#ys) ! i\" by simp\n    with \\<open>(x#xs) ! 0 \\<longrightarrow> (y#ys) ! 0\\<close> \\<open>length xs = length ys\\<close>\n    show \"(\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i) \\<and> \n      length (x#xs) = length (y#ys)\"\n      by clarsimp(case_tac \"i>0\",auto)\n  next\n    assume \"(\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i) \\<and> \n      length (x#xs) = length (y#ys)\"\n    hence \"\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i\" \n      and \"length (x#xs) = length (y#ys)\" by simp_all\n    from \\<open>\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i\\<close>\n    have \"\\<forall>i < length xs. xs ! i \\<longrightarrow> ys ! i\"\n      by clarsimp(erule_tac x=\"Suc i\" in allE,auto)\n    with eq \\<open>length (x#xs) = length (y#ys)\\<close> have \"xs \\<preceq>\\<^sub>b ys\" by simp\n    from \\<open>\\<forall>i < length (x#xs). (x#xs) ! i \\<longrightarrow> (y#ys) ! i\\<close>\n    have \"x \\<longrightarrow> y\" by(erule_tac x=\"0\" in allE) simp\n    with \\<open>xs \\<preceq>\\<^sub>b ys\\<close> show \"x#xs \\<preceq>\\<^sub>b y#ys\" by simp\n  qed\nqed simp_all\n\n\nsubsection \\<open>$\\preceq_b$ is an order on bit vectors with minimal and \n  maximal element\\<close>\n\nlemma minimal_element:\n  \"replicate (length xs) False \\<preceq>\\<^sub>b xs\"\nby(induct xs) auto\n\nlemma maximal_element:\n  \"xs \\<preceq>\\<^sub>b replicate (length xs) True\"\nby(induct xs) auto\n\nlemma bv_leqs_refl:\"xs \\<preceq>\\<^sub>b xs\"\n  by(induct xs) auto\n\n\nlemma bv_leqs_trans:\"\\<lbrakk>xs \\<preceq>\\<^sub>b ys; ys \\<preceq>\\<^sub>b zs\\<rbrakk> \\<Longrightarrow> xs \\<preceq>\\<^sub>b zs\"\nproof(induct xs ys arbitrary:zs rule:bv_leqs.induct)\n  case (2 x xs y ys)\n  note IH = \\<open>\\<And>zs. \\<lbrakk>xs \\<preceq>\\<^sub>b ys; ys \\<preceq>\\<^sub>b zs\\<rbrakk> \\<Longrightarrow> xs \\<preceq>\\<^sub>b zs\\<close>\n  from \\<open>(x#xs) \\<preceq>\\<^sub>b (y#ys)\\<close> have \"xs \\<preceq>\\<^sub>b ys\" and \"x \\<longrightarrow> y\" by simp_all\n  from \\<open>(y#ys) \\<preceq>\\<^sub>b zs\\<close> obtain z zs' where \"zs = z#zs'\" by(cases zs) auto\n  with \\<open>(y#ys) \\<preceq>\\<^sub>b zs\\<close> have \"ys \\<preceq>\\<^sub>b zs'\" and \"y \\<longrightarrow> z\" by simp_all\n  from IH[OF \\<open>xs \\<preceq>\\<^sub>b ys\\<close> \\<open>ys \\<preceq>\\<^sub>b zs'\\<close>] have \"xs \\<preceq>\\<^sub>b zs'\" .\n  with \\<open>x \\<longrightarrow> y\\<close> \\<open>y \\<longrightarrow> z\\<close> \\<open>zs = z#zs'\\<close> show ?case by simp\nqed simp_all\n\n\nlemma bv_leqs_antisym:\"\\<lbrakk>xs \\<preceq>\\<^sub>b ys; ys \\<preceq>\\<^sub>b xs\\<rbrakk> \\<Longrightarrow> xs = ys\"\n  by(induct xs ys rule:bv_leqs.induct)auto\n\n\ndefinition bv_less :: \"bit_vector \\<Rightarrow> bit_vector \\<Rightarrow> bool\" (\"_ \\<prec>\\<^sub>b _\" 99)\n  where \"xs \\<prec>\\<^sub>b ys \\<equiv> xs \\<preceq>\\<^sub>b ys \\<and> xs \\<noteq> ys\"\n\n\ninterpretation order \"bv_leqs\" \"bv_less\"\nby(unfold_locales,\n   auto intro:bv_leqs_refl bv_leqs_trans bv_leqs_antisym simp:bv_less_def)\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Slicing/Dynamic/BitVector.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8918110425624792, "lm_q1q2_score": 0.7912188643280079}}
{"text": "theory Lecture8\nimports Main\nbegin\ntext{* An \"abstract\" notion of a finite graph *} \n\nlocale finitegraph =\n  fixes edges :: \"('a\\<times>'a)set\" and vertices::\"'a set\" \n  assumes finite_vertex_set : \"finite vertices\"\n  and is_graph : \"(u, v) \\<in> edges \\<Longrightarrow>  u \\<in> vertices \\<and> v \\<in> vertices\" \nbegin\n\n(* Note that we can tell Isabelle's simplifier about 2 of the rules using [simp]. \n   More on this later in the course. *)\ninductive walk:: \"'a list \\<Rightarrow> bool\" where\nNil[simp] : \"walk []\"\n|Singleton [simp] : \"v \\<in> vertices \\<Longrightarrow> walk [v]\"\n|Cons : \"(v,w)\\<in>edges \\<Longrightarrow> walk(w#vs) \\<Longrightarrow> walk(v#w#vs)\"\n\n\nlemma walk_edge: assumes \"(v,w) \\<in> edges\" shows \"walk [v,w]\"\nproof -\n  have \"w \\<in> vertices\"\n    using assms is_graph by presburger\n  then show ?thesis\n    by (simp add: assms walk.Cons)\nqed\n\n\ndefinition connected :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<rightarrow>\\<^sup>*\" 60) where\n  \"connected v w \\<equiv> \\<exists>xs. walk xs \\<and> xs \\<noteq> Nil \\<and> hd xs = v \\<and> last xs = w\"\n\nend\n\n(* We can examine the definition of the locale and any lemma proven (whether explicitly or implicitly) \n   inside it. For example: *)\n\nthm finitegraph_def\nthm \"finitegraph.walk_edge\"\nthm \"finitegraph.walk.Singleton\"\n(* An induction principle was proven automatically for our finite graphs*)\nthm \"finitegraph.walk.induct\"\n\ntext{* Extending the finite graphs locale to one about weighted finite graphs*} \n\nlocale weighted_finitegraph = finitegraph + \n  fixes weight :: \"('a \\<times> 'a) \\<Rightarrow> nat\"\n  assumes edges_weighted: \"\\<forall>e\\<in>edges. \\<exists>w. weight e = w\"\n\nthm finitegraph_def\nthm weighted_finitegraph_def [unfolded weighted_finitegraph_axioms_def]\n\ntext{* We can define a concrete graph and show that it is an instance of our finite graph. In this \n   case, we just go for the graph with a single vertex \"1\" and an edge \"(1,1)\" to itself.\n*}\ninterpretation singleton_finitegraph: finitegraph \"{(1,1)}\" \"{1}\"\nproof \n show \"finite {1}\" by simp \n next fix u v assume \"(u, v) \\<in> {(1::'a, 1::'a)}\" then show \"u \\<in> {1} \\<and> v \\<in> {1}\" by blast\nqed\n\n(* We can \"peek\" into our instance: *)\nterm singleton_finitegraph.connected \nterm singleton_finitegraph.walk\n\n(* The definitions and theorems are now  available for the locale instance. For example: *)\nthm singleton_finitegraph.connected_def\nthm singleton_finitegraph.walk_edge\nthm singleton_finitegraph.walk.Singleton\nthm singleton_finitegraph.walk.induct\n\n\ntext{* We can make the concrete singleton_finitegraph an instance of the weighted_finitegraph locale \n   by providing a weight function e.g. the one that associates a weight \"1\" to any edge. \n*}\n\ninterpretation singleton_finitegraph: weighted_finitegraph \"{(1,1)}\" \"{1}\" \"\\<lambda>(u,v). 1\"\nby (unfold_locales) simp\n\n(* The walk_edge theorem is still available *)\nthm singleton_finitegraph.walk_edge\n(* The weighted edges assumption instantiated with our single edge graph (yielding a trivial property)*)\nthm singleton_finitegraph.edges_weighted\n\n", "meta": {"author": "celinadongye", "repo": "Isabelle-exercises", "sha": "f94a03f43d23a8055d9c195acf1390107fed3395", "save_path": "github-repos/isabelle/celinadongye-Isabelle-exercises", "path": "github-repos/isabelle/celinadongye-Isabelle-exercises/Isabelle-exercises-f94a03f43d23a8055d9c195acf1390107fed3395/Lecture8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.7911429401476048}}
{"text": "(*  Author:     L C Paulson, University of Cambridge [ported from HOL Light]\n*)\n\nsection \\<open>Operators involving abstract topology\\<close>\n\ntheory Abstract_Topology\n  imports\n    Complex_Main\n    \"HOL-Library.Set_Idioms\"\n    \"HOL-Library.FuncSet\"\nbegin\n\nsubsection \\<open>General notion of a topology as a value\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> istopology :: \"('a set \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"istopology L \\<equiv> (\\<forall>S T. L S \\<longrightarrow> L T \\<longrightarrow> L (S \\<inter> T)) \\<and> (\\<forall>\\<K>. (\\<forall>K\\<in>\\<K>. L K) \\<longrightarrow> L (\\<Union>\\<K>))\"\n\ntypedef\\<^marker>\\<open>tag important\\<close> 'a topology = \"{L::('a set) \\<Rightarrow> bool. istopology L}\"\n  morphisms \"openin\" \"topology\"\n  unfolding istopology_def by blast\n\nlemma istopology_openin[iff]: \"istopology(openin U)\"\n  using openin[of U] by blast\n\nlemma istopology_open[iff]: \"istopology open\"\n  by (auto simp: istopology_def)\n\nlemma topology_inverse' [simp]: \"istopology U \\<Longrightarrow> openin (topology U) = U\"\n  using topology_inverse[unfolded mem_Collect_eq] .\n\nlemma topology_inverse_iff: \"istopology U \\<longleftrightarrow> openin (topology U) = U\"\n  by (metis istopology_openin topology_inverse')\n\nlemma topology_eq: \"T1 = T2 \\<longleftrightarrow> (\\<forall>S. openin T1 S \\<longleftrightarrow> openin T2 S)\"\nproof\n  assume \"T1 = T2\"\n  then show \"\\<forall>S. openin T1 S \\<longleftrightarrow> openin T2 S\" by simp\nnext\n  assume H: \"\\<forall>S. openin T1 S \\<longleftrightarrow> openin T2 S\"\n  then have \"openin T1 = openin T2\" by (simp add: fun_eq_iff)\n  then have \"topology (openin T1) = topology (openin T2)\" by simp\n  then show \"T1 = T2\" unfolding openin_inverse .\nqed\n\n\ntext\\<open>The \"universe\": the union of all sets in the topology.\\<close>\ndefinition \"topspace T = \\<Union>{S. openin T S}\"\n\nsubsubsection \\<open>Main properties of open sets\\<close>\n\nproposition openin_clauses:\n  fixes U :: \"'a topology\"\n  shows\n    \"openin U {}\"\n    \"\\<And>S T. openin U S \\<Longrightarrow> openin U T \\<Longrightarrow> openin U (S\\<inter>T)\"\n    \"\\<And>K. (\\<forall>S \\<in> K. openin U S) \\<Longrightarrow> openin U (\\<Union>K)\"\n  using openin[of U] unfolding istopology_def by auto\n\nlemma openin_subset: \"openin U S \\<Longrightarrow> S \\<subseteq> topspace U\"\n  unfolding topspace_def by blast\n\nlemma openin_empty[simp]: \"openin U {}\"\n  by (rule openin_clauses)\n\nlemma openin_Int[intro]: \"openin U S \\<Longrightarrow> openin U T \\<Longrightarrow> openin U (S \\<inter> T)\"\n  by (rule openin_clauses)\n\nlemma openin_Union[intro]: \"(\\<And>S. S \\<in> K \\<Longrightarrow> openin U S) \\<Longrightarrow> openin U (\\<Union>K)\"\n  using openin_clauses by blast\n\nlemma openin_Un[intro]: \"openin U S \\<Longrightarrow> openin U T \\<Longrightarrow> openin U (S \\<union> T)\"\n  using openin_Union[of \"{S,T}\" U] by auto\n\nlemma openin_topspace[intro, simp]: \"openin U (topspace U)\"\n  by (force simp: openin_Union topspace_def)\n\nlemma openin_subopen: \"openin U S \\<longleftrightarrow> (\\<forall>x \\<in> S. \\<exists>T. openin U T \\<and> x \\<in> T \\<and> T \\<subseteq> S)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs by auto\nnext\n  assume H: ?rhs\n  let ?t = \"\\<Union>{T. openin U T \\<and> T \\<subseteq> S}\"\n  have \"openin U ?t\" by (force simp: openin_Union)\n  also have \"?t = S\" using H by auto\n  finally show \"openin U S\" .\nqed\n\nlemma openin_INT [intro]:\n  assumes \"finite I\"\n          \"\\<And>i. i \\<in> I \\<Longrightarrow> openin T (U i)\"\n  shows \"openin T ((\\<Inter>i \\<in> I. U i) \\<inter> topspace T)\"\nusing assms by (induct, auto simp: inf_sup_aci(2) openin_Int)\n\nlemma openin_INT2 [intro]:\n  assumes \"finite I\" \"I \\<noteq> {}\"\n          \"\\<And>i. i \\<in> I \\<Longrightarrow> openin T (U i)\"\n  shows \"openin T (\\<Inter>i \\<in> I. U i)\"\nproof -\n  have \"(\\<Inter>i \\<in> I. U i) \\<subseteq> topspace T\"\n    using \\<open>I \\<noteq> {}\\<close> openin_subset[OF assms(3)] by auto\n  then show ?thesis\n    using openin_INT[of _ _ U, OF assms(1) assms(3)] by (simp add: inf.absorb2 inf_commute)\nqed\n\nlemma openin_Inter [intro]:\n  assumes \"finite \\<F>\" \"\\<F> \\<noteq> {}\" \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> openin T X\" shows \"openin T (\\<Inter>\\<F>)\"\n  by (metis (full_types) assms openin_INT2 image_ident)\n\nlemma openin_Int_Inter:\n  assumes \"finite \\<F>\" \"openin T U\" \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> openin T X\" shows \"openin T (U \\<inter> \\<Inter>\\<F>)\"\n  using openin_Inter [of \"insert U \\<F>\"] assms by auto\n\n\nsubsubsection \\<open>Closed sets\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> closedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"closedin U S \\<longleftrightarrow> S \\<subseteq> topspace U \\<and> openin U (topspace U - S)\"\n\nlemma closedin_subset: \"closedin U S \\<Longrightarrow> S \\<subseteq> topspace U\"\n  by (metis closedin_def)\n\nlemma closedin_empty[simp]: \"closedin U {}\"\n  by (simp add: closedin_def)\n\nlemma closedin_topspace[intro, simp]: \"closedin U (topspace U)\"\n  by (simp add: closedin_def)\n\nlemma closedin_Un[intro]: \"closedin U S \\<Longrightarrow> closedin U T \\<Longrightarrow> closedin U (S \\<union> T)\"\n  by (auto simp: Diff_Un closedin_def)\n\nlemma Diff_Inter[intro]: \"A - \\<Inter>S = \\<Union>{A - s|s. s\\<in>S}\"\n  by auto\n\nlemma closedin_Union:\n  assumes \"finite S\" \"\\<And>T. T \\<in> S \\<Longrightarrow> closedin U T\"\n    shows \"closedin U (\\<Union>S)\"\n  using assms by induction auto\n\nlemma closedin_Inter[intro]:\n  assumes Ke: \"K \\<noteq> {}\"\n    and Kc: \"\\<And>S. S \\<in>K \\<Longrightarrow> closedin U S\"\n  shows \"closedin U (\\<Inter>K)\"\n  using Ke Kc unfolding closedin_def Diff_Inter by auto\n\nlemma closedin_INT[intro]:\n  assumes \"A \\<noteq> {}\" \"\\<And>x. x \\<in> A \\<Longrightarrow> closedin U (B x)\"\n  shows \"closedin U (\\<Inter>x\\<in>A. B x)\"\n  using assms by blast\n\nlemma closedin_Int[intro]: \"closedin U S \\<Longrightarrow> closedin U T \\<Longrightarrow> closedin U (S \\<inter> T)\"\n  using closedin_Inter[of \"{S,T}\" U] by auto\n\nlemma openin_closedin_eq: \"openin U S \\<longleftrightarrow> S \\<subseteq> topspace U \\<and> closedin U (topspace U - S)\"\n  by (metis Diff_subset closedin_def double_diff equalityD1 openin_subset)\n\nlemma topology_finer_closedin:\n  \"topspace X = topspace Y \\<Longrightarrow> (\\<forall>S. openin Y S \\<longrightarrow> openin X S) \\<longleftrightarrow> (\\<forall>S. closedin Y S \\<longrightarrow> closedin X S)\"\n  by (metis closedin_def openin_closedin_eq)\n\nlemma openin_closedin: \"S \\<subseteq> topspace U \\<Longrightarrow> (openin U S \\<longleftrightarrow> closedin U (topspace U - S))\"\n  by (simp add: openin_closedin_eq)\n\nlemma openin_diff[intro]:\n  assumes oS: \"openin U S\"\n    and cT: \"closedin U T\"\n  shows \"openin U (S - T)\"\n  by (metis Int_Diff cT closedin_def inf.orderE oS openin_Int openin_subset)\n\nlemma closedin_diff[intro]:\n  assumes oS: \"closedin U S\"\n    and cT: \"openin U T\"\n  shows \"closedin U (S - T)\"\n  by (metis Int_Diff cT closedin_Int closedin_subset inf.orderE oS openin_closedin_eq)\n\n\nsubsection\\<open>The discrete topology\\<close>\n\ndefinition discrete_topology where \"discrete_topology U \\<equiv> topology (\\<lambda>S. S \\<subseteq> U)\"\n\nlemma openin_discrete_topology [simp]: \"openin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U\"\nproof -\n  have \"istopology (\\<lambda>S. S \\<subseteq> U)\"\n    by (auto simp: istopology_def)\n  then show ?thesis\n    by (simp add: discrete_topology_def topology_inverse')\nqed\n\nlemma topspace_discrete_topology [simp]: \"topspace(discrete_topology U) = U\"\n  by (meson openin_discrete_topology openin_subset openin_topspace order_refl subset_antisym)\n\nlemma closedin_discrete_topology [simp]: \"closedin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U\"\n  by (simp add: closedin_def)\n\nlemma discrete_topology_unique:\n   \"discrete_topology U = X \\<longleftrightarrow> topspace X = U \\<and> (\\<forall>x \\<in> U. openin X {x})\" (is \"?lhs = ?rhs\")\nproof\n  assume R: ?rhs\n  then have \"openin X S\" if \"S \\<subseteq> U\" for S\n    using openin_subopen subsetD that by fastforce\n  then show ?lhs\n    by (metis R openin_discrete_topology openin_subset topology_eq)\nqed auto\n\nlemma discrete_topology_unique_alt:\n  \"discrete_topology U = X \\<longleftrightarrow> topspace X \\<subseteq> U \\<and> (\\<forall>x \\<in> U. openin X {x})\"\n  using openin_subset\n  by (auto simp: discrete_topology_unique)\n\nlemma subtopology_eq_discrete_topology_empty:\n   \"X = discrete_topology {} \\<longleftrightarrow> topspace X = {}\"\n  using discrete_topology_unique [of \"{}\" X] by auto\n\nlemma subtopology_eq_discrete_topology_sing:\n   \"X = discrete_topology {a} \\<longleftrightarrow> topspace X = {a}\"\n  by (metis discrete_topology_unique openin_topspace singletonD)\n\n\nsubsection \\<open>Subspace topology\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> subtopology :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a topology\" \n  where \"subtopology U V = topology (\\<lambda>T. \\<exists>S. T = S \\<inter> V \\<and> openin U S)\"\n\nlemma istopology_subtopology: \"istopology (\\<lambda>T. \\<exists>S. T = S \\<inter> V \\<and> openin U S)\"\n  (is \"istopology ?L\")\nproof -\n  have \"?L {}\" by blast\n  {\n    fix A B\n    assume A: \"?L A\" and B: \"?L B\"\n    from A B obtain Sa and Sb where Sa: \"openin U Sa\" \"A = Sa \\<inter> V\" and Sb: \"openin U Sb\" \"B = Sb \\<inter> V\"\n      by blast\n    have \"A \\<inter> B = (Sa \\<inter> Sb) \\<inter> V\" \"openin U (Sa \\<inter> Sb)\"\n      using Sa Sb by blast+\n    then have \"?L (A \\<inter> B)\" by blast\n  }\n  moreover\n  {\n    fix K\n    assume K: \"K \\<subseteq> Collect ?L\"\n    have th0: \"Collect ?L = (\\<lambda>S. S \\<inter> V) ` Collect (openin U)\"\n      by blast\n    from K[unfolded th0 subset_image_iff]\n    obtain Sk where Sk: \"Sk \\<subseteq> Collect (openin U)\" \"K = (\\<lambda>S. S \\<inter> V) ` Sk\"\n      by blast\n    have \"\\<Union>K = (\\<Union>Sk) \\<inter> V\"\n      using Sk by auto\n    moreover have \"openin U (\\<Union>Sk)\"\n      using Sk by (auto simp: subset_eq)\n    ultimately have \"?L (\\<Union>K)\" by blast\n  }\n  ultimately show ?thesis\n    unfolding subset_eq mem_Collect_eq istopology_def by auto\nqed\n\nlemma openin_subtopology: \"openin (subtopology U V) S \\<longleftrightarrow> (\\<exists>T. openin U T \\<and> S = T \\<inter> V)\"\n  unfolding subtopology_def topology_inverse'[OF istopology_subtopology]\n  by auto\n\nlemma openin_subtopology_Int:\n   \"openin X S \\<Longrightarrow> openin (subtopology X T) (S \\<inter> T)\"\n  using openin_subtopology by auto\n\nlemma openin_subtopology_Int2:\n   \"openin X T \\<Longrightarrow> openin (subtopology X S) (S \\<inter> T)\"\n  using openin_subtopology by auto\n\nlemma openin_subtopology_diff_closed:\n   \"\\<lbrakk>S \\<subseteq> topspace X; closedin X T\\<rbrakk> \\<Longrightarrow> openin (subtopology X S) (S - T)\"\n  unfolding closedin_def openin_subtopology\n  by (rule_tac x=\"topspace X - T\" in exI) auto\n\nlemma openin_relative_to: \"(openin X relative_to S) = openin (subtopology X S)\"\n  by (force simp: relative_to_def openin_subtopology)\n\nlemma topspace_subtopology [simp]: \"topspace (subtopology U V) = topspace U \\<inter> V\"\n  by (auto simp: topspace_def openin_subtopology)\n\nlemma topspace_subtopology_subset:\n   \"S \\<subseteq> topspace X \\<Longrightarrow> topspace(subtopology X S) = S\"\n  by (simp add: inf.absorb_iff2)\n\nlemma closedin_subtopology: \"closedin (subtopology U V) S \\<longleftrightarrow> (\\<exists>T. closedin U T \\<and> S = T \\<inter> V)\"\n  unfolding closedin_def topspace_subtopology\n  by (auto simp: openin_subtopology)\n\nlemma openin_subtopology_refl: \"openin (subtopology U V) V \\<longleftrightarrow> V \\<subseteq> topspace U\"\n  unfolding openin_subtopology\n  by auto (metis IntD1 in_mono openin_subset)\n\nlemma subtopology_subtopology:\n   \"subtopology (subtopology X S) T = subtopology X (S \\<inter> T)\"\nproof -\n  have eq: \"\\<And>T'. (\\<exists>S'. T' = S' \\<inter> T \\<and> (\\<exists>T. openin X T \\<and> S' = T \\<inter> S)) = (\\<exists>Sa. T' = Sa \\<inter> (S \\<inter> T) \\<and> openin X Sa)\"\n    by (metis inf_assoc)\n  have \"subtopology (subtopology X S) T = topology (\\<lambda>Ta. \\<exists>Sa. Ta = Sa \\<inter> T \\<and> openin (subtopology X S) Sa)\"\n    by (simp add: subtopology_def)\n  also have \"\\<dots> = subtopology X (S \\<inter> T)\"\n    by (simp add: openin_subtopology eq) (simp add: subtopology_def)\n  finally show ?thesis .\nqed\n\nlemma openin_subtopology_alt:\n     \"openin (subtopology X U) S \\<longleftrightarrow> S \\<in> (\\<lambda>T. U \\<inter> T) ` Collect (openin X)\"\n  by (simp add: image_iff inf_commute openin_subtopology)\n\nlemma closedin_subtopology_alt:\n     \"closedin (subtopology X U) S \\<longleftrightarrow> S \\<in> (\\<lambda>T. U \\<inter> T) ` Collect (closedin X)\"\n  by (simp add: image_iff inf_commute closedin_subtopology)\n\nlemma subtopology_superset:\n  assumes UV: \"topspace U \\<subseteq> V\"\n  shows \"subtopology U V = U\"\nproof -\n  { fix S\n    have \"openin U S\" if \"openin U T\" \"S = T \\<inter> V\" for T\n      by (metis Int_subset_iff assms inf.orderE openin_subset that)\n    then have \"(\\<exists>T. openin U T \\<and> S = T \\<inter> V) \\<longleftrightarrow> openin U S\"\n      by (metis assms inf.orderE inf_assoc openin_subset)\n  }\n  then show ?thesis\n    unfolding topology_eq openin_subtopology by blast\nqed\n\nlemma subtopology_topspace[simp]: \"subtopology U (topspace U) = U\"\n  by (simp add: subtopology_superset)\n\nlemma subtopology_UNIV[simp]: \"subtopology U UNIV = U\"\n  by (simp add: subtopology_superset)\n\nlemma subtopology_restrict:\n   \"subtopology X (topspace X \\<inter> S) = subtopology X S\"\n  by (metis subtopology_subtopology subtopology_topspace)\n\nlemma openin_subtopology_empty:\n  \"openin (subtopology U {}) S \\<longleftrightarrow> S = {}\"\n  by (metis Int_empty_right openin_empty openin_subtopology)\n\nlemma closedin_subtopology_empty:\n  \"closedin (subtopology U {}) S \\<longleftrightarrow> S = {}\"\n  by (metis Int_empty_right closedin_empty closedin_subtopology)\n\nlemma closedin_subtopology_refl [simp]:\n  \"closedin (subtopology U X) X \\<longleftrightarrow> X \\<subseteq> topspace U\"\n  by (metis closedin_def closedin_topspace inf.absorb_iff2 le_inf_iff topspace_subtopology)\n\nlemma closedin_topspace_empty: \"topspace T = {} \\<Longrightarrow> (closedin T S \\<longleftrightarrow> S = {})\"\n  by (simp add: closedin_def)\n\nlemma open_in_topspace_empty:\n   \"topspace X = {} \\<Longrightarrow> openin X S \\<longleftrightarrow> S = {}\"\n  by (simp add: openin_closedin_eq)\n\nlemma openin_imp_subset:\n  \"openin (subtopology U S) T \\<Longrightarrow> T \\<subseteq> S\"\n  by (metis Int_iff openin_subtopology subsetI)\n\nlemma closedin_imp_subset:\n  \"closedin (subtopology U S) T \\<Longrightarrow> T \\<subseteq> S\"\n  by (simp add: closedin_def)\n\nlemma openin_open_subtopology:\n     \"openin X S \\<Longrightarrow> openin (subtopology X S) T \\<longleftrightarrow> openin X T \\<and> T \\<subseteq> S\"\n  by (metis inf.orderE openin_Int openin_imp_subset openin_subtopology)\n\nlemma closedin_closed_subtopology:\n     \"closedin X S \\<Longrightarrow> (closedin (subtopology X S) T \\<longleftrightarrow> closedin X T \\<and> T \\<subseteq> S)\"\n  by (metis closedin_Int closedin_imp_subset closedin_subtopology inf.orderE)\n\nlemma openin_subtopology_Un:\n    \"\\<lbrakk>openin (subtopology X T) S; openin (subtopology X U) S\\<rbrakk>\n     \\<Longrightarrow> openin (subtopology X (T \\<union> U)) S\"\nby (simp add: openin_subtopology) blast\n\nlemma closedin_subtopology_Un:\n    \"\\<lbrakk>closedin (subtopology X T) S; closedin (subtopology X U) S\\<rbrakk>\n     \\<Longrightarrow> closedin (subtopology X (T \\<union> U)) S\"\nby (simp add: closedin_subtopology) blast\n\nlemma openin_trans_full:\n   \"\\<lbrakk>openin (subtopology X U) S; openin X U\\<rbrakk> \\<Longrightarrow> openin X S\"\n  by (simp add: openin_open_subtopology)\n\n\nsubsection \\<open>The canonical topology from the underlying type class\\<close>\n\nabbreviation\\<^marker>\\<open>tag important\\<close> euclidean :: \"'a::topological_space topology\"\n  where \"euclidean \\<equiv> topology open\"\n\nabbreviation top_of_set :: \"'a::topological_space set \\<Rightarrow> 'a topology\"\n  where \"top_of_set \\<equiv> subtopology (topology open)\"\n\nlemma open_openin: \"open S \\<longleftrightarrow> openin euclidean S\"\n  by simp\n\ndeclare open_openin [symmetric, simp]\n\nlemma topspace_euclidean [simp]: \"topspace euclidean = UNIV\"\n  by (force simp: topspace_def)\n\nlemma topspace_euclidean_subtopology[simp]: \"topspace (top_of_set S) = S\"\n  by (simp)\n\nlemma closed_closedin: \"closed S \\<longleftrightarrow> closedin euclidean S\"\n  by (simp add: closed_def closedin_def Compl_eq_Diff_UNIV)\n\ndeclare closed_closedin [symmetric, simp]\n\nlemma openin_subtopology_self [simp]: \"openin (top_of_set S) S\"\n  by (metis openin_topspace topspace_euclidean_subtopology)\n\nsubsubsection\\<open>The most basic facts about the usual topology and metric on R\\<close>\n\nabbreviation euclideanreal :: \"real topology\"\n  where \"euclideanreal \\<equiv> topology open\"\n\nsubsection \\<open>Basic \"localization\" results are handy for connectedness.\\<close>\n\nlemma openin_open: \"openin (top_of_set U) S \\<longleftrightarrow> (\\<exists>T. open T \\<and> (S = U \\<inter> T))\"\n  by (auto simp: openin_subtopology)\n\nlemma openin_Int_open:\n   \"\\<lbrakk>openin (top_of_set U) S; open T\\<rbrakk>\n        \\<Longrightarrow> openin (top_of_set U) (S \\<inter> T)\"\nby (metis open_Int Int_assoc openin_open)\n\nlemma openin_open_Int[intro]: \"open S \\<Longrightarrow> openin (top_of_set U) (U \\<inter> S)\"\n  by (auto simp: openin_open)\n\nlemma open_openin_trans[trans]:\n  \"open S \\<Longrightarrow> open T \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> openin (top_of_set S) T\"\n  by (metis Int_absorb1  openin_open_Int)\n\nlemma open_subset: \"S \\<subseteq> T \\<Longrightarrow> open S \\<Longrightarrow> openin (top_of_set T) S\"\n  by (auto simp: openin_open)\n\nlemma closedin_closed: \"closedin (top_of_set U) S \\<longleftrightarrow> (\\<exists>T. closed T \\<and> S = U \\<inter> T)\"\n  by (simp add: closedin_subtopology Int_ac)\n\nlemma closedin_closed_Int: \"closed S \\<Longrightarrow> closedin (top_of_set U) (U \\<inter> S)\"\n  by (metis closedin_closed)\n\nlemma closed_subset: \"S \\<subseteq> T \\<Longrightarrow> closed S \\<Longrightarrow> closedin (top_of_set T) S\"\n  by (auto simp: closedin_closed)\n\nlemma closedin_closed_subset:\n \"\\<lbrakk>closedin (top_of_set U) V; T \\<subseteq> U; S = V \\<inter> T\\<rbrakk>\n             \\<Longrightarrow> closedin (top_of_set T) S\"\n  by (metis (no_types, lifting) Int_assoc Int_commute closedin_closed inf.orderE)\n\nlemma finite_imp_closedin:\n  fixes S :: \"'a::t1_space set\"\n  shows \"\\<lbrakk>finite S; S \\<subseteq> T\\<rbrakk> \\<Longrightarrow> closedin (top_of_set T) S\"\n    by (simp add: finite_imp_closed closed_subset)\n\nlemma closedin_singleton [simp]:\n  fixes a :: \"'a::t1_space\"\n  shows \"closedin (top_of_set U) {a} \\<longleftrightarrow> a \\<in> U\"\nusing closedin_subset  by (force intro: closed_subset)\n\nlemma openin_euclidean_subtopology_iff:\n  fixes S U :: \"'a::metric_space set\"\n  shows \"openin (top_of_set U) S \\<longleftrightarrow>\n    S \\<subseteq> U \\<and> (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>x'\\<in>U. dist x' x < e \\<longrightarrow> x'\\<in> S)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding openin_open open_dist by blast\nnext\n  define T where \"T = {x. \\<exists>a\\<in>S. \\<exists>d>0. (\\<forall>y\\<in>U. dist y a < d \\<longrightarrow> y \\<in> S) \\<and> dist x a < d}\"\n  have 1: \"\\<forall>x\\<in>T. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> T\"\n    unfolding T_def\n    apply clarsimp\n    apply (rule_tac x=\"d - dist x a\" in exI)\n    by (metis add_0_left dist_commute dist_triangle_lt less_diff_eq)\n  assume ?rhs then have 2: \"S = U \\<inter> T\"\n    unfolding T_def\n    by auto (metis dist_self)\n  from 1 2 show ?lhs\n    unfolding openin_open open_dist by fast\nqed\n\nlemma connected_openin:\n      \"connected S \\<longleftrightarrow>\n       \\<not>(\\<exists>E1 E2. openin (top_of_set S) E1 \\<and>\n                 openin (top_of_set S) E2 \\<and>\n                 S \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  unfolding connected_def openin_open disjoint_iff_not_equal by blast\n\nlemma connected_openin_eq:\n      \"connected S \\<longleftrightarrow>\n       \\<not>(\\<exists>E1 E2. openin (top_of_set S) E1 \\<and>\n                 openin (top_of_set S) E2 \\<and>\n                 E1 \\<union> E2 = S \\<and> E1 \\<inter> E2 = {} \\<and>\n                 E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  unfolding connected_openin\n  by (metis (no_types, lifting) Un_subset_iff openin_imp_subset subset_antisym)\n\nlemma connected_closedin:\n      \"connected S \\<longleftrightarrow>\n       (\\<nexists>E1 E2.\n        closedin (top_of_set S) E1 \\<and>\n        closedin (top_of_set S) E2 \\<and>\n        S \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n       (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs \n    by (auto simp add: connected_closed closedin_closed)\nnext\n  assume R: ?rhs\n  then show ?lhs \n  proof (clarsimp simp add: connected_closed closedin_closed)\n    fix A B \n    assume s_sub: \"S \\<subseteq> A \\<union> B\" \"B \\<inter> S \\<noteq> {}\"\n      and disj: \"A \\<inter> B \\<inter> S = {}\"\n      and cl: \"closed A\" \"closed B\"\n    have \"S - A = B \\<inter> S\"\n      using Diff_subset_conv Un_Diff_Int disj s_sub(1) by auto\n    then show \"A \\<inter> S = {}\"\n      by (metis Int_Diff_Un Int_Diff_disjoint R cl closedin_closed_Int dual_order.refl inf_commute s_sub(2))\n  qed\nqed\n\nlemma connected_closedin_eq:\n      \"connected S \\<longleftrightarrow>\n           \\<not>(\\<exists>E1 E2.\n                 closedin (top_of_set S) E1 \\<and>\n                 closedin (top_of_set S) E2 \\<and>\n                 E1 \\<union> E2 = S \\<and> E1 \\<inter> E2 = {} \\<and>\n                 E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  unfolding connected_closedin\n  by (metis Un_subset_iff closedin_imp_subset subset_antisym)\n\ntext \\<open>These \"transitivity\" results are handy too\\<close>\n\nlemma openin_trans[trans]:\n  \"openin (top_of_set T) S \\<Longrightarrow> openin (top_of_set U) T \\<Longrightarrow>\n    openin (top_of_set U) S\"\n  by (metis openin_Int_open openin_open)\n\nlemma openin_open_trans: \"openin (top_of_set T) S \\<Longrightarrow> open T \\<Longrightarrow> open S\"\n  by (auto simp: openin_open intro: openin_trans)\n\nlemma closedin_trans[trans]:\n  \"closedin (top_of_set T) S \\<Longrightarrow> closedin (top_of_set U) T \\<Longrightarrow>\n    closedin (top_of_set U) S\"\n  by (auto simp: closedin_closed closed_Inter Int_assoc)\n\nlemma closedin_closed_trans: \"closedin (top_of_set T) S \\<Longrightarrow> closed T \\<Longrightarrow> closed S\"\n  by (auto simp: closedin_closed intro: closedin_trans)\n\nlemma openin_subtopology_Int_subset:\n   \"\\<lbrakk>openin (top_of_set u) (u \\<inter> S); v \\<subseteq> u\\<rbrakk> \\<Longrightarrow> openin (top_of_set v) (v \\<inter> S)\"\n  by (auto simp: openin_subtopology)\n\nlemma openin_open_eq: \"open s \\<Longrightarrow> (openin (top_of_set s) t \\<longleftrightarrow> open t \\<and> t \\<subseteq> s)\"\n  using open_subset openin_open_trans openin_subset by fastforce\n\n\nsubsection\\<open>Derived set (set of limit points)\\<close>\n\ndefinition derived_set_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixl \"derived'_set'_of\" 80)\n  where \"X derived_set_of S \\<equiv>\n         {x \\<in> topspace X.\n                (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y\\<noteq>x. y \\<in> S \\<and> y \\<in> T))}\"\n\nlemma derived_set_of_restrict [simp]:\n   \"X derived_set_of (topspace X \\<inter> S) = X derived_set_of S\"\n  by (simp add: derived_set_of_def) (metis openin_subset subset_iff)\n\nlemma in_derived_set_of:\n   \"x \\<in> X derived_set_of S \\<longleftrightarrow> x \\<in> topspace X \\<and> (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y\\<noteq>x. y \\<in> S \\<and> y \\<in> T))\"\n  by (simp add: derived_set_of_def)\n\nlemma derived_set_of_subset_topspace:\n   \"X derived_set_of S \\<subseteq> topspace X\"\n  by (auto simp add: derived_set_of_def)\n\nlemma derived_set_of_subtopology:\n   \"(subtopology X U) derived_set_of S = U \\<inter> (X derived_set_of (U \\<inter> S))\"\n  by (simp add: derived_set_of_def openin_subtopology) blast\n\nlemma derived_set_of_subset_subtopology:\n   \"(subtopology X S) derived_set_of T \\<subseteq> S\"\n  by (simp add: derived_set_of_subtopology)\n\nlemma derived_set_of_empty [simp]: \"X derived_set_of {} = {}\"\n  by (auto simp: derived_set_of_def)\n\nlemma derived_set_of_mono:\n   \"S \\<subseteq> T \\<Longrightarrow> X derived_set_of S \\<subseteq> X derived_set_of T\"\n  unfolding derived_set_of_def by blast\n\nlemma derived_set_of_Un:\n   \"X derived_set_of (S \\<union> T) = X derived_set_of S \\<union> X derived_set_of T\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    by (clarsimp simp: in_derived_set_of) (metis IntE IntI openin_Int)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (simp add: derived_set_of_mono)\nqed\n\nlemma derived_set_of_Union:\n   \"finite \\<F> \\<Longrightarrow> X derived_set_of (\\<Union>\\<F>) = (\\<Union>S \\<in> \\<F>. X derived_set_of S)\"\nproof (induction \\<F> rule: finite_induct)\n  case (insert S \\<F>)\n  then show ?case\n    by (simp add: derived_set_of_Un)\nqed auto\n\nlemma derived_set_of_topspace:\n  \"X derived_set_of (topspace X) = {x \\<in> topspace X. \\<not> openin X {x}}\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    by (auto simp: in_derived_set_of)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (clarsimp simp: in_derived_set_of) (metis openin_closedin_eq openin_subopen singletonD subset_eq)\nqed\n\nlemma discrete_topology_unique_derived_set:\n     \"discrete_topology U = X \\<longleftrightarrow> topspace X = U \\<and> X derived_set_of U = {}\"\n  by (auto simp: discrete_topology_unique derived_set_of_topspace)\n\nlemma subtopology_eq_discrete_topology_eq:\n   \"subtopology X U = discrete_topology U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> U \\<inter> X derived_set_of U = {}\"\n  using discrete_topology_unique_derived_set [of U \"subtopology X U\"]\n  by (auto simp: eq_commute derived_set_of_subtopology)\n\nlemma subtopology_eq_discrete_topology:\n   \"S \\<subseteq> topspace X \\<and> S \\<inter> X derived_set_of S = {}\n        \\<Longrightarrow> subtopology X S = discrete_topology S\"\n  by (simp add: subtopology_eq_discrete_topology_eq)\n\nlemma subtopology_eq_discrete_topology_gen:\n  assumes \"S \\<inter> X derived_set_of S = {}\"\n  shows \"subtopology X S = discrete_topology(topspace X \\<inter> S)\"\nproof -\n  have \"subtopology X S = subtopology X (topspace X \\<inter> S)\"\n    by (simp add: subtopology_restrict)\n  then show ?thesis\n    using assms by (simp add: inf.assoc subtopology_eq_discrete_topology_eq)\nqed\n\nlemma subtopology_discrete_topology [simp]: \n  \"subtopology (discrete_topology U) S = discrete_topology(U \\<inter> S)\"\nproof -\n  have \"(\\<lambda>T. \\<exists>Sa. T = Sa \\<inter> S \\<and> Sa \\<subseteq> U) = (\\<lambda>Sa. Sa \\<subseteq> U \\<and> Sa \\<subseteq> S)\"\n    by force\n  then show ?thesis\n    by (simp add: subtopology_def) (simp add: discrete_topology_def)\nqed\n\nlemma openin_Int_derived_set_of_subset:\n   \"openin X S \\<Longrightarrow> S \\<inter> X derived_set_of T \\<subseteq> X derived_set_of (S \\<inter> T)\"\n  by (auto simp: derived_set_of_def)\n\nlemma openin_Int_derived_set_of_eq:\n  assumes \"openin X S\"\n  shows \"S \\<inter> X derived_set_of T = S \\<inter> X derived_set_of (S \\<inter> T)\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    by (simp add: assms openin_Int_derived_set_of_subset)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (metis derived_set_of_mono inf_commute inf_le1 inf_mono order_refl)\nqed\n\n\nsubsection\\<open> Closure with respect to a topological space\\<close>\n\ndefinition closure_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixr \"closure'_of\" 80)\n  where \"X closure_of S \\<equiv> {x \\<in> topspace X. \\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y \\<in> S. y \\<in> T)}\"\n\nlemma closure_of_restrict: \"X closure_of S = X closure_of (topspace X \\<inter> S)\"\n  unfolding closure_of_def\n  using openin_subset by blast\n\nlemma in_closure_of:\n   \"x \\<in> X closure_of S \\<longleftrightarrow>\n    x \\<in> topspace X \\<and> (\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y. y \\<in> S \\<and> y \\<in> T))\"\n  by (auto simp: closure_of_def)\n\nlemma closure_of: \"X closure_of S = topspace X \\<inter> (S \\<union> X derived_set_of S)\"\n  by (fastforce simp: in_closure_of in_derived_set_of)\n\nlemma closure_of_alt: \"X closure_of S = topspace X \\<inter> S \\<union> X derived_set_of S\"\n  using derived_set_of_subset_topspace [of X S]\n  unfolding closure_of_def in_derived_set_of\n  by safe (auto simp: in_derived_set_of)\n\nlemma derived_set_of_subset_closure_of:\n   \"X derived_set_of S \\<subseteq> X closure_of S\"\n  by (fastforce simp: closure_of_def in_derived_set_of)\n\nlemma closure_of_subtopology:\n  \"(subtopology X U) closure_of S = U \\<inter> (X closure_of (U \\<inter> S))\"\n  unfolding closure_of_def topspace_subtopology openin_subtopology\n  by safe (metis (full_types) IntI Int_iff inf.commute)+\n\nlemma closure_of_empty [simp]: \"X closure_of {} = {}\"\n  by (simp add: closure_of_alt)\n\nlemma closure_of_topspace [simp]: \"X closure_of topspace X = topspace X\"\n  by (simp add: closure_of)\n\nlemma closure_of_UNIV [simp]: \"X closure_of UNIV = topspace X\"\n  by (simp add: closure_of)\n\nlemma closure_of_subset_topspace: \"X closure_of S \\<subseteq> topspace X\"\n  by (simp add: closure_of)\n\nlemma closure_of_subset_subtopology: \"(subtopology X S) closure_of T \\<subseteq> S\"\n  by (simp add: closure_of_subtopology)\n\nlemma closure_of_mono: \"S \\<subseteq> T \\<Longrightarrow> X closure_of S \\<subseteq> X closure_of T\"\n  by (fastforce simp add: closure_of_def)\n\nlemma closure_of_subtopology_subset:\n   \"(subtopology X U) closure_of S \\<subseteq> (X closure_of S)\"\n  unfolding closure_of_subtopology\n  by clarsimp (meson closure_of_mono contra_subsetD inf.cobounded2)\n\nlemma closure_of_subtopology_mono:\n   \"T \\<subseteq> U \\<Longrightarrow> (subtopology X T) closure_of S \\<subseteq> (subtopology X U) closure_of S\"\n  unfolding closure_of_subtopology\n  by auto (meson closure_of_mono inf_mono subset_iff)\n\nlemma closure_of_Un [simp]: \"X closure_of (S \\<union> T) = X closure_of S \\<union> X closure_of T\"\n  by (simp add: Un_assoc Un_left_commute closure_of_alt derived_set_of_Un inf_sup_distrib1)\n\nlemma closure_of_Union:\n   \"finite \\<F> \\<Longrightarrow> X closure_of (\\<Union>\\<F>) = (\\<Union>S \\<in> \\<F>. X closure_of S)\"\nby (induction \\<F> rule: finite_induct) auto\n\nlemma closure_of_subset: \"S \\<subseteq> topspace X \\<Longrightarrow> S \\<subseteq> X closure_of S\"\n  by (auto simp: closure_of_def)\n\nlemma closure_of_subset_Int: \"topspace X \\<inter> S \\<subseteq> X closure_of S\"\n  by (auto simp: closure_of_def)\n\nlemma closure_of_subset_eq: \"S \\<subseteq> topspace X \\<and> X closure_of S \\<subseteq> S \\<longleftrightarrow> closedin X S\"\nproof -\n  have \"openin X (topspace X - S)\"\n    if \"\\<And>x. \\<lbrakk>x \\<in> topspace X; \\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> S \\<inter> T \\<noteq> {}\\<rbrakk> \\<Longrightarrow> x \\<in> S\"\n    apply (subst openin_subopen)\n    by (metis Diff_iff Diff_mono Diff_triv inf.commute openin_subset order_refl that)\n  then show ?thesis\n    by (auto simp: closedin_def closure_of_def disjoint_iff_not_equal)\nqed\n\nlemma closure_of_eq: \"X closure_of S = S \\<longleftrightarrow> closedin X S\"\n  by (metis closure_of_subset closure_of_subset_eq closure_of_subset_topspace subset_antisym)\n\nlemma closedin_contains_derived_set:\n   \"closedin X S \\<longleftrightarrow> X derived_set_of S \\<subseteq> S \\<and> S \\<subseteq> topspace X\"\nproof (intro iffI conjI)\n  show \"closedin X S \\<Longrightarrow> X derived_set_of S \\<subseteq> S\"\n    using closure_of_eq derived_set_of_subset_closure_of by fastforce\n  show \"closedin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n    using closedin_subset by blast\n  show \"X derived_set_of S \\<subseteq> S \\<and> S \\<subseteq> topspace X \\<Longrightarrow> closedin X S\"\n    by (metis closure_of closure_of_eq inf.absorb_iff2 sup.orderE)\nqed\n\nlemma derived_set_subset_gen:\n   \"X derived_set_of S \\<subseteq> S \\<longleftrightarrow> closedin X (topspace X \\<inter> S)\"\n  by (simp add: closedin_contains_derived_set derived_set_of_subset_topspace)\n\nlemma derived_set_subset: \"S \\<subseteq> topspace X \\<Longrightarrow> (X derived_set_of S \\<subseteq> S \\<longleftrightarrow> closedin X S)\"\n  by (simp add: closedin_contains_derived_set)\n\nlemma closedin_derived_set:\n     \"closedin (subtopology X T) S \\<longleftrightarrow>\n      S \\<subseteq> topspace X \\<and> S \\<subseteq> T \\<and> (\\<forall>x. x \\<in> X derived_set_of S \\<and> x \\<in> T \\<longrightarrow> x \\<in> S)\"\n  by (auto simp: closedin_contains_derived_set derived_set_of_subtopology Int_absorb1)\n\nlemma closedin_Int_closure_of:\n     \"closedin (subtopology X S) T \\<longleftrightarrow> S \\<inter> X closure_of T = T\"\n  by (metis Int_left_absorb closure_of_eq closure_of_subtopology)\n\nlemma closure_of_closedin: \"closedin X S \\<Longrightarrow> X closure_of S = S\"\n  by (simp add: closure_of_eq)\n\nlemma closure_of_eq_diff: \"X closure_of S = topspace X - \\<Union>{T. openin X T \\<and> disjnt S T}\"\n  by (auto simp: closure_of_def disjnt_iff)\n\nlemma closedin_closure_of [simp]: \"closedin X (X closure_of S)\"\n  unfolding closure_of_eq_diff by blast\n\nlemma closure_of_closure_of [simp]: \"X closure_of (X closure_of S) = X closure_of S\"\n  by (simp add: closure_of_eq)\n\nlemma closure_of_hull:\n  assumes \"S \\<subseteq> topspace X\" shows \"X closure_of S = (closedin X) hull S\"\n  by (metis assms closedin_closure_of closure_of_eq closure_of_mono closure_of_subset hull_unique)\n\nlemma closure_of_minimal:\n   \"\\<lbrakk>S \\<subseteq> T; closedin X T\\<rbrakk> \\<Longrightarrow> (X closure_of S) \\<subseteq> T\"\n  by (metis closure_of_eq closure_of_mono)\n\nlemma closure_of_minimal_eq:\n   \"\\<lbrakk>S \\<subseteq> topspace X; closedin X T\\<rbrakk> \\<Longrightarrow> (X closure_of S) \\<subseteq> T \\<longleftrightarrow> S \\<subseteq> T\"\n  by (meson closure_of_minimal closure_of_subset subset_trans)\n\nlemma closure_of_unique:\n   \"\\<lbrakk>S \\<subseteq> T; closedin X T;\n     \\<And>T'. \\<lbrakk>S \\<subseteq> T'; closedin X T'\\<rbrakk> \\<Longrightarrow> T \\<subseteq> T'\\<rbrakk>\n    \\<Longrightarrow> X closure_of S = T\"\n  by (meson closedin_closure_of closedin_subset closure_of_minimal closure_of_subset eq_iff order.trans)\n\nlemma closure_of_eq_empty_gen: \"X closure_of S = {} \\<longleftrightarrow> disjnt (topspace X) S\"\n  unfolding disjnt_def closure_of_restrict [where S=S]\n  using closure_of by fastforce\n\nlemma closure_of_eq_empty: \"S \\<subseteq> topspace X \\<Longrightarrow> X closure_of S = {} \\<longleftrightarrow> S = {}\"\n  using closure_of_subset by fastforce\n\nlemma openin_Int_closure_of_subset:\n  assumes \"openin X S\"\n  shows \"S \\<inter> X closure_of T \\<subseteq> X closure_of (S \\<inter> T)\"\nproof -\n  have \"S \\<inter> X derived_set_of T = S \\<inter> X derived_set_of (S \\<inter> T)\"\n    by (meson assms openin_Int_derived_set_of_eq)\n  moreover have \"S \\<inter> (S \\<inter> T) = S \\<inter> T\"\n    by fastforce\n  ultimately show ?thesis\n    by (metis closure_of_alt inf.cobounded2 inf_left_commute inf_sup_distrib1)\nqed\n\nlemma closure_of_openin_Int_closure_of:\n  assumes \"openin X S\"\n  shows \"X closure_of (S \\<inter> X closure_of T) = X closure_of (S \\<inter> T)\"\nproof\n  show \"X closure_of (S \\<inter> X closure_of T) \\<subseteq> X closure_of (S \\<inter> T)\"\n    by (simp add: assms closure_of_minimal openin_Int_closure_of_subset)\nnext\n  show \"X closure_of (S \\<inter> T) \\<subseteq> X closure_of (S \\<inter> X closure_of T)\"\n    by (metis Int_subset_iff assms closure_of_alt closure_of_mono inf_mono openin_subset subset_refl sup.coboundedI1)\nqed\n\nlemma openin_Int_closure_of_eq:\n  assumes \"openin X S\" shows \"S \\<inter> X closure_of T = S \\<inter> X closure_of (S \\<inter> T)\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    by (simp add: assms openin_Int_closure_of_subset)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (metis closure_of_mono inf_commute inf_le1 inf_mono order_refl)\nqed\n\nlemma openin_Int_closure_of_eq_empty:\n  assumes \"openin X S\" shows \"S \\<inter> X closure_of T = {} \\<longleftrightarrow> S \\<inter> T = {}\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<Longrightarrow> ?rhs\"\n    unfolding disjoint_iff\n    by (meson assms in_closure_of in_mono openin_subset)\n  show \"?rhs \\<Longrightarrow> ?lhs\"\n    by (simp add: assms openin_Int_closure_of_eq)\nqed\n\nlemma closure_of_openin_Int_superset:\n   \"openin X S \\<and> S \\<subseteq> X closure_of T\n        \\<Longrightarrow> X closure_of (S \\<inter> T) = X closure_of S\"\n  by (metis closure_of_openin_Int_closure_of inf.orderE)\n\nlemma closure_of_openin_subtopology_Int_closure_of:\n  assumes S: \"openin (subtopology X U) S\" and \"T \\<subseteq> U\"\n  shows \"X closure_of (S \\<inter> X closure_of T) = X closure_of (S \\<inter> T)\" (is \"?lhs = ?rhs\")\nproof\n  obtain S0 where S0: \"openin X S0\" \"S = S0 \\<inter> U\"\n    using assms by (auto simp: openin_subtopology)\n  then show \"?lhs \\<subseteq> ?rhs\"\n  proof -\n    have \"S0 \\<inter> X closure_of T = S0 \\<inter> X closure_of (S0 \\<inter> T)\"\n      by (meson S0(1) openin_Int_closure_of_eq)\n    moreover have \"S0 \\<inter> T = S0 \\<inter> U \\<inter> T\"\n      using \\<open>T \\<subseteq> U\\<close> by fastforce\n    ultimately have \"S \\<inter> X closure_of T \\<subseteq> X closure_of (S \\<inter> T)\"\n      using S0(2) by auto\n    then show ?thesis\n      by (meson closedin_closure_of closure_of_minimal)\n  qed\nnext\n  show \"?rhs \\<subseteq> ?lhs\"\n  proof -\n    have \"T \\<inter> S \\<subseteq> T \\<union> X derived_set_of T\"\n      by force\n    then show ?thesis\n      by (smt (verit, del_insts) Int_iff in_closure_of inf.orderE openin_subset subsetI)\n  qed\nqed\n\nlemma closure_of_subtopology_open:\n     \"openin X U \\<or> S \\<subseteq> U \\<Longrightarrow> (subtopology X U) closure_of S = U \\<inter> X closure_of S\"\n  by (metis closure_of_subtopology inf_absorb2 openin_Int_closure_of_eq)\n\nlemma discrete_topology_closure_of:\n     \"(discrete_topology U) closure_of S = U \\<inter> S\"\n  by (metis closedin_discrete_topology closure_of_restrict closure_of_unique discrete_topology_unique inf_sup_ord(1) order_refl)\n\n\ntext\\<open> Interior with respect to a topological space.                             \\<close>\n\ndefinition interior_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixr \"interior'_of\" 80)\n  where \"X interior_of S \\<equiv> {x. \\<exists>T. openin X T \\<and> x \\<in> T \\<and> T \\<subseteq> S}\"\n\nlemma interior_of_restrict:\n   \"X interior_of S = X interior_of (topspace X \\<inter> S)\"\n  using openin_subset by (auto simp: interior_of_def)\n\nlemma interior_of_eq: \"(X interior_of S = S) \\<longleftrightarrow> openin X S\"\n  unfolding interior_of_def  using openin_subopen by blast\n\nlemma interior_of_openin: \"openin X S \\<Longrightarrow> X interior_of S = S\"\n  by (simp add: interior_of_eq)\n\nlemma interior_of_empty [simp]: \"X interior_of {} = {}\"\n  by (simp add: interior_of_eq)\n\nlemma interior_of_topspace [simp]: \"X interior_of (topspace X) = topspace X\"\n  by (simp add: interior_of_eq)\n\nlemma openin_interior_of [simp]: \"openin X (X interior_of S)\"\n  unfolding interior_of_def\n  using openin_subopen by fastforce\n\nlemma interior_of_interior_of [simp]:\n   \"X interior_of X interior_of S = X interior_of S\"\n  by (simp add: interior_of_eq)\n\nlemma interior_of_subset: \"X interior_of S \\<subseteq> S\"\n  by (auto simp: interior_of_def)\n\nlemma interior_of_subset_closure_of: \"X interior_of S \\<subseteq> X closure_of S\"\n  by (metis closure_of_subset_Int dual_order.trans interior_of_restrict interior_of_subset)\n\nlemma subset_interior_of_eq: \"S \\<subseteq> X interior_of S \\<longleftrightarrow> openin X S\"\n  by (metis interior_of_eq interior_of_subset subset_antisym)\n\nlemma interior_of_mono: \"S \\<subseteq> T \\<Longrightarrow> X interior_of S \\<subseteq> X interior_of T\"\n  by (auto simp: interior_of_def)\n\nlemma interior_of_maximal: \"\\<lbrakk>T \\<subseteq> S; openin X T\\<rbrakk> \\<Longrightarrow> T \\<subseteq> X interior_of S\"\n  by (auto simp: interior_of_def)\n\nlemma interior_of_maximal_eq: \"openin X T \\<Longrightarrow> T \\<subseteq> X interior_of S \\<longleftrightarrow> T \\<subseteq> S\"\n  by (meson interior_of_maximal interior_of_subset order_trans)\n\nlemma interior_of_unique:\n   \"\\<lbrakk>T \\<subseteq> S; openin X T; \\<And>T'. \\<lbrakk>T' \\<subseteq> S; openin X T'\\<rbrakk> \\<Longrightarrow> T' \\<subseteq> T\\<rbrakk> \\<Longrightarrow> X interior_of S = T\"\n  by (simp add: interior_of_maximal_eq interior_of_subset subset_antisym)\n\nlemma interior_of_subset_topspace: \"X interior_of S \\<subseteq> topspace X\"\n  by (simp add: openin_subset)\n\nlemma interior_of_subset_subtopology: \"(subtopology X S) interior_of T \\<subseteq> S\"\n  by (meson openin_imp_subset openin_interior_of)\n\nlemma interior_of_Int: \"X interior_of (S \\<inter> T) = X interior_of S \\<inter> X interior_of T\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    by (simp add: interior_of_mono)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (meson inf_mono interior_of_maximal interior_of_subset openin_Int openin_interior_of)\nqed\n\nlemma interior_of_Inter_subset: \"X interior_of (\\<Inter>\\<F>) \\<subseteq> (\\<Inter>S \\<in> \\<F>. X interior_of S)\"\n  by (simp add: INT_greatest Inf_lower interior_of_mono)\n\nlemma union_interior_of_subset:\n   \"X interior_of S \\<union> X interior_of T \\<subseteq> X interior_of (S \\<union> T)\"\n  by (simp add: interior_of_mono)\n\nlemma interior_of_eq_empty:\n   \"X interior_of S = {} \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<subseteq> S \\<longrightarrow> T = {})\"\n  by (metis bot.extremum_uniqueI interior_of_maximal interior_of_subset openin_interior_of)\n\nlemma interior_of_eq_empty_alt:\n   \"X interior_of S = {} \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<noteq> {} \\<longrightarrow> T - S \\<noteq> {})\"\n  by (auto simp: interior_of_eq_empty)\n\nlemma interior_of_Union_openin_subsets:\n   \"\\<Union>{T. openin X T \\<and> T \\<subseteq> S} = X interior_of S\"\n  by (rule interior_of_unique [symmetric]) auto\n\nlemma interior_of_complement:\n   \"X interior_of (topspace X - S) = topspace X - X closure_of S\"\n  by (auto simp: interior_of_def closure_of_def)\n\nlemma interior_of_closure_of:\n   \"X interior_of S = topspace X - X closure_of (topspace X - S)\"\n  unfolding interior_of_complement [symmetric]\n  by (metis Diff_Diff_Int interior_of_restrict)\n\nlemma closure_of_interior_of:\n   \"X closure_of S = topspace X - X interior_of (topspace X - S)\"\n  by (simp add: interior_of_complement Diff_Diff_Int closure_of)\n\nlemma closure_of_complement: \"X closure_of (topspace X - S) = topspace X - X interior_of S\"\n  unfolding interior_of_def closure_of_def\n  by (blast dest: openin_subset)\n\nlemma interior_of_eq_empty_complement:\n  \"X interior_of S = {} \\<longleftrightarrow> X closure_of (topspace X - S) = topspace X\"\n  using interior_of_subset_topspace [of X S] closure_of_complement by fastforce\n\nlemma closure_of_eq_topspace:\n   \"X closure_of S = topspace X \\<longleftrightarrow> X interior_of (topspace X - S) = {}\"\n  using closure_of_subset_topspace [of X S] interior_of_complement by fastforce\n\nlemma interior_of_subtopology_subset:\n     \"U \\<inter> X interior_of S \\<subseteq> (subtopology X U) interior_of S\"\n  by (auto simp: interior_of_def openin_subtopology)\n\nlemma interior_of_subtopology_subsets:\n   \"T \\<subseteq> U \\<Longrightarrow> T \\<inter> (subtopology X U) interior_of S \\<subseteq> (subtopology X T) interior_of S\"\n  by (metis inf.absorb_iff2 interior_of_subtopology_subset subtopology_subtopology)\n\nlemma interior_of_subtopology_mono:\n   \"\\<lbrakk>S \\<subseteq> T; T \\<subseteq> U\\<rbrakk> \\<Longrightarrow> (subtopology X U) interior_of S \\<subseteq> (subtopology X T) interior_of S\"\n  by (metis dual_order.trans inf.orderE inf_commute interior_of_subset interior_of_subtopology_subsets)\n\nlemma interior_of_subtopology_open:\n  assumes \"openin X U\"\n  shows \"(subtopology X U) interior_of S = U \\<inter> X interior_of S\" (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    by (meson assms interior_of_maximal interior_of_subset le_infI openin_interior_of openin_open_subtopology)\n  show \"?rhs \\<subseteq> ?lhs\"\n    by (simp add: interior_of_subtopology_subset)\nqed\n\nlemma dense_intersects_open:\n   \"X closure_of S = topspace X \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<noteq> {} \\<longrightarrow> S \\<inter> T \\<noteq> {})\"\nproof -\n  have \"X closure_of S = topspace X \\<longleftrightarrow> (topspace X - X interior_of (topspace X - S) = topspace X)\"\n    by (simp add: closure_of_interior_of)\n  also have \"\\<dots> \\<longleftrightarrow> X interior_of (topspace X - S) = {}\"\n    by (simp add: closure_of_complement interior_of_eq_empty_complement)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<forall>T. openin X T \\<and> T \\<noteq> {} \\<longrightarrow> S \\<inter> T \\<noteq> {})\"\n    unfolding interior_of_eq_empty_alt\n    using openin_subset by fastforce\n  finally show ?thesis .\nqed\n\nlemma interior_of_closedin_union_empty_interior_of:\n  assumes \"closedin X S\" and disj: \"X interior_of T = {}\"\n  shows \"X interior_of (S \\<union> T) = X interior_of S\"\nproof -\n  have \"X closure_of (topspace X - T) = topspace X\"\n    by (metis Diff_Diff_Int disj closure_of_eq_topspace closure_of_restrict interior_of_closure_of)\n  then show ?thesis\n    unfolding interior_of_closure_of\n    by (metis Diff_Un Diff_subset assms(1) closedin_def closure_of_openin_Int_superset)\nqed\n\nlemma interior_of_union_eq_empty:\n   \"closedin X S\n        \\<Longrightarrow> (X interior_of (S \\<union> T) = {} \\<longleftrightarrow>\n             X interior_of S = {} \\<and> X interior_of T = {})\"\n  by (metis interior_of_closedin_union_empty_interior_of le_sup_iff subset_empty union_interior_of_subset)\n\nlemma discrete_topology_interior_of [simp]:\n    \"(discrete_topology U) interior_of S = U \\<inter> S\"\n  by (simp add: interior_of_restrict [of _ S] interior_of_eq)\n\n\nsubsection \\<open>Frontier with respect to topological space \\<close>\n\ndefinition frontier_of :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (infixr \"frontier'_of\" 80)\n  where \"X frontier_of S \\<equiv> X closure_of S - X interior_of S\"\n\nlemma frontier_of_closures:\n     \"X frontier_of S = X closure_of S \\<inter> X closure_of (topspace X - S)\"\n  by (metis Diff_Diff_Int closure_of_complement closure_of_subset_topspace double_diff frontier_of_def interior_of_subset_closure_of)\n\n\nlemma interior_of_union_frontier_of [simp]:\n     \"X interior_of S \\<union> X frontier_of S = X closure_of S\"\n  by (simp add: frontier_of_def interior_of_subset_closure_of subset_antisym)\n\nlemma frontier_of_restrict: \"X frontier_of S = X frontier_of (topspace X \\<inter> S)\"\n  by (metis closure_of_restrict frontier_of_def interior_of_restrict)\n\nlemma closedin_frontier_of: \"closedin X (X frontier_of S)\"\n  by (simp add: closedin_Int frontier_of_closures)\n\nlemma frontier_of_subset_topspace: \"X frontier_of S \\<subseteq> topspace X\"\n  by (simp add: closedin_frontier_of closedin_subset)\n\nlemma frontier_of_subset_subtopology: \"(subtopology X S) frontier_of T \\<subseteq> S\"\n  by (metis (no_types) closedin_derived_set closedin_frontier_of)\n\nlemma frontier_of_subtopology_subset:\n  \"U \\<inter> (subtopology X U) frontier_of S \\<subseteq> (X frontier_of S)\"\nproof -\n  have \"U \\<inter> X interior_of S - subtopology X U interior_of S = {}\"\n    by (simp add: interior_of_subtopology_subset)\n  moreover have \"X closure_of S \\<inter> subtopology X U closure_of S = subtopology X U closure_of S\"\n    by (meson closure_of_subtopology_subset inf.absorb_iff2)\n  ultimately show ?thesis\n    unfolding frontier_of_def\n    by blast\nqed\n\nlemma frontier_of_subtopology_mono:\n   \"\\<lbrakk>S \\<subseteq> T; T \\<subseteq> U\\<rbrakk> \\<Longrightarrow> (subtopology X T) frontier_of S \\<subseteq> (subtopology X U) frontier_of S\"\n    by (simp add: frontier_of_def Diff_mono closure_of_subtopology_mono interior_of_subtopology_mono)\n\nlemma clopenin_eq_frontier_of:\n   \"closedin X S \\<and> openin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> X frontier_of S = {}\"\nproof (cases \"S \\<subseteq> topspace X\")\n  case True\n  then show ?thesis\n    by (metis Diff_eq_empty_iff closure_of_eq closure_of_subset_eq frontier_of_def interior_of_eq interior_of_subset interior_of_union_frontier_of sup_bot_right)\nnext\n  case False\n  then show ?thesis\n    by (simp add: frontier_of_closures openin_closedin_eq)\nqed\n\nlemma frontier_of_eq_empty:\n     \"S \\<subseteq> topspace X \\<Longrightarrow> (X frontier_of S = {} \\<longleftrightarrow> closedin X S \\<and> openin X S)\"\n  by (simp add: clopenin_eq_frontier_of)\n\nlemma frontier_of_openin:\n     \"openin X S \\<Longrightarrow> X frontier_of S = X closure_of S - S\"\n  by (metis (no_types) frontier_of_def interior_of_eq)\n\nlemma frontier_of_openin_straddle_Int:\n  assumes \"openin X U\" \"U \\<inter> X frontier_of S \\<noteq> {}\"\n  shows \"U \\<inter> S \\<noteq> {}\" \"U - S \\<noteq> {}\"\nproof -\n  have \"U \\<inter> (X closure_of S \\<inter> X closure_of (topspace X - S)) \\<noteq> {}\"\n    using assms by (simp add: frontier_of_closures)\n  then show \"U \\<inter> S \\<noteq> {}\"\n    using assms openin_Int_closure_of_eq_empty by fastforce\n  show \"U - S \\<noteq> {}\"\n  proof -\n    have \"\\<exists>A. X closure_of (A - S) \\<inter> U \\<noteq> {}\"\n      using \\<open>U \\<inter> (X closure_of S \\<inter> X closure_of (topspace X - S)) \\<noteq> {}\\<close> by blast\n    then have \"\\<not> U \\<subseteq> S\"\n      by (metis Diff_disjoint Diff_eq_empty_iff Int_Diff assms(1) inf_commute openin_Int_closure_of_eq_empty)\n    then show ?thesis\n      by blast\n  qed\nqed\n\nlemma frontier_of_subset_closedin: \"closedin X S \\<Longrightarrow> (X frontier_of S) \\<subseteq> S\"\n  using closure_of_eq frontier_of_def by fastforce\n\nlemma frontier_of_empty [simp]: \"X frontier_of {} = {}\"\n  by (simp add: frontier_of_def)\n\nlemma frontier_of_topspace [simp]: \"X frontier_of topspace X = {}\"\n  by (simp add: frontier_of_def)\n\nlemma frontier_of_subset_eq:\n  assumes \"S \\<subseteq> topspace X\"\n  shows \"(X frontier_of S) \\<subseteq> S \\<longleftrightarrow> closedin X S\"\nproof\n  show \"X frontier_of S \\<subseteq> S \\<Longrightarrow> closedin X S\"\n    by (metis assms closure_of_subset_eq interior_of_subset interior_of_union_frontier_of le_sup_iff)\n  show \"closedin X S \\<Longrightarrow> X frontier_of S \\<subseteq> S\"\n    by (simp add: frontier_of_subset_closedin)\nqed\n\nlemma frontier_of_complement: \"X frontier_of (topspace X - S) = X frontier_of S\"\n  by (metis Diff_Diff_Int closure_of_restrict frontier_of_closures inf_commute)\n\nlemma frontier_of_disjoint_eq:\n  assumes \"S \\<subseteq> topspace X\"\n  shows \"((X frontier_of S) \\<inter> S = {} \\<longleftrightarrow> openin X S)\"\nproof\n  assume \"X frontier_of S \\<inter> S = {}\"\n  then have \"closedin X (topspace X - S)\"\n    using assms closure_of_subset frontier_of_def interior_of_eq interior_of_subset by fastforce\n  then show \"openin X S\"\n    using assms by (simp add: openin_closedin)\nnext\n  show \"openin X S \\<Longrightarrow> X frontier_of S \\<inter> S = {}\"\n    by (simp add: Diff_Diff_Int closedin_def frontier_of_openin inf.absorb_iff2 inf_commute)\nqed\n\nlemma frontier_of_disjoint_eq_alt:\n  \"S \\<subseteq> (topspace X - X frontier_of S) \\<longleftrightarrow> openin X S\"\nproof (cases \"S \\<subseteq> topspace X\")\n  case True\n  show ?thesis\n    using True frontier_of_disjoint_eq by auto\nnext\n  case False\n  then show ?thesis\n    by (meson Diff_subset openin_subset subset_trans)\nqed\n\nlemma frontier_of_Int:\n     \"X frontier_of (S \\<inter> T) =\n      X closure_of (S \\<inter> T) \\<inter> (X frontier_of S \\<union> X frontier_of T)\"\nproof -\n  have *: \"U \\<subseteq> S \\<and> U \\<subseteq> T \\<Longrightarrow> U \\<inter> (S \\<inter> A \\<union> T \\<inter> B) = U \\<inter> (A \\<union> B)\" for U S T A B :: \"'a set\"\n    by blast\n  show ?thesis\n    by (simp add: frontier_of_closures closure_of_mono Diff_Int * flip: closure_of_Un)\nqed\n\nlemma frontier_of_Int_subset: \"X frontier_of (S \\<inter> T) \\<subseteq> X frontier_of S \\<union> X frontier_of T\"\n  by (simp add: frontier_of_Int)\n\nlemma frontier_of_Int_closedin:\n  assumes \"closedin X S\" \"closedin X T\" \n  shows \"X frontier_of(S \\<inter> T) = X frontier_of S \\<inter> T \\<union> S \\<inter> X frontier_of T\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\"\n    using assms by (force simp add: frontier_of_Int closedin_Int closure_of_closedin)\n  show \"?rhs \\<subseteq> ?lhs\"\n    using assms frontier_of_subset_closedin\n    by (auto simp add: frontier_of_Int closedin_Int closure_of_closedin)\nqed\n\nlemma frontier_of_Un_subset: \"X frontier_of(S \\<union> T) \\<subseteq> X frontier_of S \\<union> X frontier_of T\"\n  by (metis Diff_Un frontier_of_Int_subset frontier_of_complement)\n\nlemma frontier_of_Union_subset:\n   \"finite \\<F> \\<Longrightarrow> X frontier_of (\\<Union>\\<F>) \\<subseteq> (\\<Union>T \\<in> \\<F>. X frontier_of T)\"\nproof (induction \\<F> rule: finite_induct)\n  case (insert A \\<F>)\n  then show ?case\n    using frontier_of_Un_subset by fastforce\nqed simp\n\nlemma frontier_of_frontier_of_subset:\n     \"X frontier_of (X frontier_of S) \\<subseteq> X frontier_of S\"\n  by (simp add: closedin_frontier_of frontier_of_subset_closedin)\n\nlemma frontier_of_subtopology_open:\n     \"openin X U \\<Longrightarrow> (subtopology X U) frontier_of S = U \\<inter> X frontier_of S\"\n  by (simp add: Diff_Int_distrib closure_of_subtopology_open frontier_of_def interior_of_subtopology_open)\n\nlemma discrete_topology_frontier_of [simp]:\n     \"(discrete_topology U) frontier_of S = {}\"\n  by (simp add: Diff_eq discrete_topology_closure_of frontier_of_closures)\n\n\nsubsection\\<open>Locally finite collections\\<close>\n\ndefinition locally_finite_in\n  where\n \"locally_finite_in X \\<A> \\<longleftrightarrow>\n        (\\<Union>\\<A> \\<subseteq> topspace X) \\<and>\n        (\\<forall>x \\<in> topspace X. \\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}})\"\n\nlemma finite_imp_locally_finite_in:\n   \"\\<lbrakk>finite \\<A>; \\<Union>\\<A> \\<subseteq> topspace X\\<rbrakk> \\<Longrightarrow> locally_finite_in X \\<A>\"\n  by (auto simp: locally_finite_in_def)\n\nlemma locally_finite_in_subset:\n  assumes \"locally_finite_in X \\<A>\" \"\\<B> \\<subseteq> \\<A>\"\n  shows \"locally_finite_in X \\<B>\"\nproof -\n  have \"finite (\\<A> \\<inter> {U. U \\<inter> V \\<noteq> {}}) \\<Longrightarrow> finite (\\<B> \\<inter> {U. U \\<inter> V \\<noteq> {}})\" for V\n    by (meson \\<open>\\<B> \\<subseteq> \\<A>\\<close> finite_subset inf_le1 inf_le2 le_inf_iff subset_trans)\n  then show ?thesis\n    using assms unfolding locally_finite_in_def Int_def by fastforce\nqed\n\nlemma locally_finite_in_refinement:\n  assumes \\<A>: \"locally_finite_in X \\<A>\" and f: \"\\<And>S. S \\<in> \\<A> \\<Longrightarrow> f S \\<subseteq> S\"\n  shows \"locally_finite_in X (f ` \\<A>)\"\nproof -\n  show ?thesis\n    unfolding locally_finite_in_def\n  proof safe\n    fix x\n    assume \"x \\<in> topspace X\"\n    then obtain V where \"openin X V\" \"x \\<in> V\" \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n      using \\<A> unfolding locally_finite_in_def by blast\n    moreover have \"{U \\<in> \\<A>. f U \\<inter> V \\<noteq> {}} \\<subseteq> {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\" for V\n      using f by blast\n    ultimately have \"finite {U \\<in> \\<A>. f U \\<inter> V \\<noteq> {}}\"\n      using finite_subset by blast\n    moreover have \"f ` {U \\<in> \\<A>. f U \\<inter> V \\<noteq> {}} = {U \\<in> f ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n      by blast\n    ultimately have \"finite {U \\<in> f ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n      by (metis (no_types, lifting) finite_imageI)\n    then show \"\\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {U \\<in> f ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n      using \\<open>openin X V\\<close> \\<open>x \\<in> V\\<close> by blast\n  next\n    show \"\\<And>x xa. \\<lbrakk>xa \\<in> \\<A>; x \\<in> f xa\\<rbrakk> \\<Longrightarrow> x \\<in> topspace X\"\n      by (meson Sup_upper \\<A> f locally_finite_in_def subset_iff)\n  qed\nqed\n\nlemma locally_finite_in_subtopology:\n  assumes \\<A>: \"locally_finite_in X \\<A>\" \"\\<Union>\\<A> \\<subseteq> S\"\n  shows \"locally_finite_in (subtopology X S) \\<A>\"\n  unfolding locally_finite_in_def\nproof safe\n  fix x\n  assume x: \"x \\<in> topspace (subtopology X S)\"\n  then obtain V where \"openin X V\" \"x \\<in> V\" and fin: \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n    using \\<A> unfolding locally_finite_in_def topspace_subtopology by blast\n  show \"\\<exists>V. openin (subtopology X S) V \\<and> x \\<in> V \\<and> finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n  proof (intro exI conjI)\n    show \"openin (subtopology X S) (S \\<inter> V)\"\n      by (simp add: \\<open>openin X V\\<close> openin_subtopology_Int2)\n    have \"{U \\<in> \\<A>. U \\<inter> (S \\<inter> V) \\<noteq> {}} \\<subseteq> {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n      by auto\n    with fin show \"finite {U \\<in> \\<A>. U \\<inter> (S \\<inter> V) \\<noteq> {}}\"\n      using finite_subset by auto\n    show \"x \\<in> S \\<inter> V\"\n      using x \\<open>x \\<in> V\\<close> by (simp)\n  qed\nnext\n  show \"\\<And>x A. \\<lbrakk>x \\<in> A; A \\<in> \\<A>\\<rbrakk> \\<Longrightarrow> x \\<in> topspace (subtopology X S)\"\n    using assms unfolding locally_finite_in_def topspace_subtopology by blast\nqed\n\n\nlemma closedin_locally_finite_Union:\n  assumes clo: \"\\<And>S. S \\<in> \\<A> \\<Longrightarrow> closedin X S\" and \\<A>: \"locally_finite_in X \\<A>\"\n  shows \"closedin X (\\<Union>\\<A>)\"\n  using \\<A> unfolding locally_finite_in_def closedin_def\nproof clarify\n  show \"openin X (topspace X - \\<Union>\\<A>)\"\n  proof (subst openin_subopen, clarify)\n    fix x\n    assume \"x \\<in> topspace X\" and \"x \\<notin> \\<Union>\\<A>\"\n    then obtain V where \"openin X V\" \"x \\<in> V\" and fin: \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n      using \\<A> unfolding locally_finite_in_def by blast\n    let ?T = \"V - \\<Union>{S \\<in> \\<A>. S \\<inter> V \\<noteq> {}}\"\n    show \"\\<exists>T. openin X T \\<and> x \\<in> T \\<and> T \\<subseteq> topspace X - \\<Union>\\<A>\"\n    proof (intro exI conjI)\n      show \"openin X ?T\"\n        by (metis (no_types, lifting) fin \\<open>openin X V\\<close> clo closedin_Union mem_Collect_eq openin_diff)\n      show \"x \\<in> ?T\"\n        using \\<open>x \\<notin> \\<Union>\\<A>\\<close> \\<open>x \\<in> V\\<close> by auto\n      show \"?T \\<subseteq> topspace X - \\<Union>\\<A>\"\n        using \\<open>openin X V\\<close> openin_subset by auto\n    qed\n  qed\nqed\n\nlemma locally_finite_in_closure:\n  assumes \\<A>: \"locally_finite_in X \\<A>\"\n  shows \"locally_finite_in X ((\\<lambda>S. X closure_of S) ` \\<A>)\"\n  using \\<A> unfolding locally_finite_in_def\nproof (intro conjI; clarsimp)\n  fix x A\n  assume \"x \\<in> X closure_of A\"\n  then show \"x \\<in> topspace X\"\n    by (meson in_closure_of)\nnext\n  fix x\n  assume \"x \\<in> topspace X\" and \"\\<Union>\\<A> \\<subseteq> topspace X\"\n  then obtain V where V: \"openin X V\" \"x \\<in> V\" and fin: \"finite {U \\<in> \\<A>. U \\<inter> V \\<noteq> {}}\"\n    using \\<A> unfolding locally_finite_in_def by blast\n  have eq: \"{y \\<in> f ` \\<A>. Q y} = f ` {x. x \\<in> \\<A> \\<and> Q(f x)}\" for f and Q :: \"'a set \\<Rightarrow> bool\"\n    by blast\n  have eq2: \"{A \\<in> \\<A>. X closure_of A \\<inter> V \\<noteq> {}} = {A \\<in> \\<A>. A \\<inter> V \\<noteq> {}}\"\n    using openin_Int_closure_of_eq_empty V  by blast\n  have \"finite {U \\<in> (closure_of) X ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n    by (simp add: eq eq2 fin)\n  with V show \"\\<exists>V. openin X V \\<and> x \\<in> V \\<and> finite {U \\<in> (closure_of) X ` \\<A>. U \\<inter> V \\<noteq> {}}\"\n    by blast\nqed\n\nlemma closedin_Union_locally_finite_closure:\n   \"locally_finite_in X \\<A> \\<Longrightarrow> closedin X (\\<Union>((\\<lambda>S. X closure_of S) ` \\<A>))\"\n  by (metis (mono_tags) closedin_closure_of closedin_locally_finite_Union imageE locally_finite_in_closure)\n\nlemma closure_of_Union_subset: \"\\<Union>((\\<lambda>S. X closure_of S) ` \\<A>) \\<subseteq> X closure_of (\\<Union>\\<A>)\"\n  by clarify (meson Union_upper closure_of_mono subsetD)\n\nlemma closure_of_locally_finite_Union:\n  assumes \"locally_finite_in X \\<A>\" \n  shows \"X closure_of (\\<Union>\\<A>) = \\<Union>((\\<lambda>S. X closure_of S) ` \\<A>)\"  \nproof (rule closure_of_unique)\n  show \"\\<Union> \\<A> \\<subseteq> \\<Union> ((closure_of) X ` \\<A>)\"\n    using assms by (simp add: SUP_upper2 Sup_le_iff closure_of_subset locally_finite_in_def)\n  show \"closedin X (\\<Union> ((closure_of) X ` \\<A>))\"\n    using assms by (simp add: closedin_Union_locally_finite_closure)\n  show \"\\<And>T'. \\<lbrakk>\\<Union> \\<A> \\<subseteq> T'; closedin X T'\\<rbrakk> \\<Longrightarrow> \\<Union> ((closure_of) X ` \\<A>) \\<subseteq> T'\"\n    by (simp add: Sup_le_iff closure_of_minimal)\nqed\n\n\nsubsection\\<^marker>\\<open>tag important\\<close> \\<open>Continuous maps\\<close>\n\ntext \\<open>We will need to deal with continuous maps in terms of topologies and not in terms\nof type classes, as defined below.\\<close>\n\ndefinition continuous_map where\n  \"continuous_map X Y f \\<equiv>\n     (\\<forall>x \\<in> topspace X. f x \\<in> topspace Y) \\<and>\n     (\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U})\"\n\nlemma continuous_map:\n   \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and> (\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U})\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_image_subset_topspace:\n   \"continuous_map X Y f \\<Longrightarrow> f ` (topspace X) \\<subseteq> topspace Y\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_on_empty: \"topspace X = {} \\<Longrightarrow> continuous_map X Y f\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_closedin:\n   \"continuous_map X Y f \\<longleftrightarrow>\n         (\\<forall>x \\<in> topspace X. f x \\<in> topspace Y) \\<and>\n         (\\<forall>C. closedin Y C \\<longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C})\"\nproof -\n  have \"(\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}) =\n        (\\<forall>C. closedin Y C \\<longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C})\"\n    if \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y\"\n  proof -\n    have eq: \"{x \\<in> topspace X. f x \\<in> topspace Y \\<and> f x \\<notin> C} = (topspace X - {x \\<in> topspace X. f x \\<in> C})\" for C\n      using that by blast\n    show ?thesis\n    proof (intro iffI allI impI)\n      fix C\n      assume \"\\<forall>U. openin Y U \\<longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}\" and \"closedin Y C\"\n      then show \"closedin X {x \\<in> topspace X. f x \\<in> C}\"\n        by (auto simp add: closedin_def eq)\n    next\n      fix U\n      assume \"\\<forall>C. closedin Y C \\<longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C}\" and \"openin Y U\"\n      then show \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n        by (auto simp add: openin_closedin_eq eq)\n    qed\n  qed\n  then show ?thesis\n    by (auto simp: continuous_map_def)\nqed\n\nlemma openin_continuous_map_preimage:\n   \"\\<lbrakk>continuous_map X Y f; openin Y U\\<rbrakk> \\<Longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}\"\n  by (simp add: continuous_map_def)\n\nlemma closedin_continuous_map_preimage:\n   \"\\<lbrakk>continuous_map X Y f; closedin Y C\\<rbrakk> \\<Longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> C}\"\n  by (simp add: continuous_map_closedin)\n\nlemma openin_continuous_map_preimage_gen:\n  assumes \"continuous_map X Y f\" \"openin X U\" \"openin Y V\"\n  shows \"openin X {x \\<in> U. f x \\<in> V}\"\nproof -\n  have eq: \"{x \\<in> U. f x \\<in> V} = U \\<inter> {x \\<in> topspace X. f x \\<in> V}\"\n    using assms(2) openin_closedin_eq by fastforce\n  show ?thesis\n    unfolding eq\n    using assms openin_continuous_map_preimage by fastforce\nqed\n\nlemma closedin_continuous_map_preimage_gen:\n  assumes \"continuous_map X Y f\" \"closedin X U\" \"closedin Y V\"\n  shows \"closedin X {x \\<in> U. f x \\<in> V}\"\nproof -\n  have eq: \"{x \\<in> U. f x \\<in> V} = U \\<inter> {x \\<in> topspace X. f x \\<in> V}\"\n    using assms(2) closedin_def by fastforce\n  show ?thesis\n    unfolding eq\n    using assms closedin_continuous_map_preimage by fastforce\nqed\n\nlemma continuous_map_image_closure_subset:\n  assumes \"continuous_map X Y f\"\n  shows \"f ` (X closure_of S) \\<subseteq> Y closure_of f ` S\"\nproof -\n  have *: \"f ` (topspace X) \\<subseteq> topspace Y\"\n    by (meson assms continuous_map)\n  have \"X closure_of T \\<subseteq> {x \\<in> X closure_of T. f x \\<in> Y closure_of (f ` T)}\"\n    if \"T \\<subseteq> topspace X\" for T\n  proof (rule closure_of_minimal)\n    show \"T \\<subseteq> {x \\<in> X closure_of T. f x \\<in> Y closure_of f ` T}\"\n      using closure_of_subset * that  by (fastforce simp: in_closure_of)\n  next\n    show \"closedin X {x \\<in> X closure_of T. f x \\<in> Y closure_of f ` T}\"\n      using assms closedin_continuous_map_preimage_gen by fastforce\n  qed\n  then show ?thesis\n    by (smt (verit, ccfv_threshold) assms continuous_map image_eqI image_subset_iff in_closure_of mem_Collect_eq)\nqed\n\nlemma continuous_map_subset_aux1: \"continuous_map X Y f \\<Longrightarrow>\n       (\\<forall>S. f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_image_closure_subset by blast\n\nlemma continuous_map_subset_aux2:\n  assumes \"\\<forall>S. S \\<subseteq> topspace X \\<longrightarrow> f ` (X closure_of S) \\<subseteq> Y closure_of f ` S\"\n  shows \"continuous_map X Y f\"\n  unfolding continuous_map_closedin\nproof (intro conjI ballI allI impI)\n  fix x\n  assume \"x \\<in> topspace X\"\n  then show \"f x \\<in> topspace Y\"\n    using assms closure_of_subset_topspace by fastforce\nnext\n  fix C\n  assume \"closedin Y C\"\n  then show \"closedin X {x \\<in> topspace X. f x \\<in> C}\"\n  proof (clarsimp simp flip: closure_of_subset_eq, intro conjI)\n    fix x\n    assume x: \"x \\<in> X closure_of {x \\<in> topspace X. f x \\<in> C}\"\n      and \"C \\<subseteq> topspace Y\" and \"Y closure_of C \\<subseteq> C\"\n    show \"x \\<in> topspace X\"\n      by (meson x in_closure_of)\n    have \"{a \\<in> topspace X. f a \\<in> C} \\<subseteq> topspace X\"\n      by simp\n    moreover have \"Y closure_of f ` {a \\<in> topspace X. f a \\<in> C} \\<subseteq> C\"\n      by (simp add: \\<open>closedin Y C\\<close> closure_of_minimal image_subset_iff)\n    ultimately show \"f x \\<in> C\"\n      using x assms by blast\n  qed\nqed\n\nlemma continuous_map_eq_image_closure_subset:\n     \"continuous_map X Y f \\<longleftrightarrow> (\\<forall>S. f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_subset_aux1 continuous_map_subset_aux2 by metis\n\nlemma continuous_map_eq_image_closure_subset_alt:\n     \"continuous_map X Y f \\<longleftrightarrow> (\\<forall>S. S \\<subseteq> topspace X \\<longrightarrow> f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_subset_aux1 continuous_map_subset_aux2 by metis\n\nlemma continuous_map_eq_image_closure_subset_gen:\n     \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and>\n        (\\<forall>S. f ` (X closure_of S) \\<subseteq> Y closure_of f ` S)\"\n  using continuous_map_subset_aux1 continuous_map_subset_aux2 continuous_map_image_subset_topspace by metis\n\nlemma continuous_map_closure_preimage_subset:\n   \"continuous_map X Y f\n        \\<Longrightarrow> X closure_of {x \\<in> topspace X. f x \\<in> T}\n            \\<subseteq> {x \\<in> topspace X. f x \\<in> Y closure_of T}\"\n  unfolding continuous_map_closedin\n  by (rule closure_of_minimal) (use in_closure_of in \\<open>fastforce+\\<close>)\n\n\nlemma continuous_map_frontier_frontier_preimage_subset:\n  assumes \"continuous_map X Y f\"\n  shows \"X frontier_of {x \\<in> topspace X. f x \\<in> T} \\<subseteq> {x \\<in> topspace X. f x \\<in> Y frontier_of T}\"\nproof -\n  have eq: \"topspace X - {x \\<in> topspace X. f x \\<in> T} = {x \\<in> topspace X. f x \\<in> topspace Y - T}\"\n    using assms unfolding continuous_map_def by blast\n  have \"X closure_of {x \\<in> topspace X. f x \\<in> T} \\<subseteq> {x \\<in> topspace X. f x \\<in> Y closure_of T}\"\n    by (simp add: assms continuous_map_closure_preimage_subset)\n  moreover\n  have \"X closure_of (topspace X - {x \\<in> topspace X. f x \\<in> T}) \\<subseteq> {x \\<in> topspace X. f x \\<in> Y closure_of (topspace Y - T)}\"\n    using continuous_map_closure_preimage_subset [OF assms] eq by presburger\n  ultimately show ?thesis\n    by (auto simp: frontier_of_closures)\nqed\n\nlemma topology_finer_continuous_id:\n  assumes \"topspace X = topspace Y\" \n  shows \"(\\<forall>S. openin X S \\<longrightarrow> openin Y S) \\<longleftrightarrow> continuous_map Y X id\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<Longrightarrow> ?rhs\"\n    unfolding continuous_map_def\n    using assms openin_subopen openin_subset by fastforce\n  show \"?rhs \\<Longrightarrow> ?lhs\"\n    unfolding continuous_map_def\n    using assms openin_subopen topspace_def by fastforce\nqed\n\nlemma continuous_map_const [simp]:\n   \"continuous_map X Y (\\<lambda>x. C) \\<longleftrightarrow> topspace X = {} \\<or> C \\<in> topspace Y\"\nproof (cases \"topspace X = {}\")\n  case False\n  show ?thesis\n  proof (cases \"C \\<in> topspace Y\")\n    case True\n    with openin_subopen show ?thesis\n      by (auto simp: continuous_map_def)\n  next\n    case False\n    then show ?thesis\n      unfolding continuous_map_def by fastforce\n  qed\nqed (auto simp: continuous_map_on_empty)\n\ndeclare continuous_map_const [THEN iffD2, continuous_intros]\n\nlemma continuous_map_compose [continuous_intros]:\n  assumes f: \"continuous_map X X' f\" and g: \"continuous_map X' X'' g\"\n  shows \"continuous_map X X'' (g \\<circ> f)\"\n  unfolding continuous_map_def\nproof (intro conjI ballI allI impI)\n  fix x\n  assume \"x \\<in> topspace X\"\n  then show \"(g \\<circ> f) x \\<in> topspace X''\"\n    using assms unfolding continuous_map_def by force\nnext\n  fix U\n  assume \"openin X'' U\"\n  have eq: \"{x \\<in> topspace X. (g \\<circ> f) x \\<in> U} = {x \\<in> topspace X. f x \\<in> {y. y \\<in> topspace X' \\<and> g y \\<in> U}}\"\n    by auto (meson f continuous_map_def)\n  show \"openin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> U}\"\n    unfolding eq\n    using assms unfolding continuous_map_def\n    using \\<open>openin X'' U\\<close> by blast\nqed\n\nlemma continuous_map_eq:\n  assumes \"continuous_map X X' f\" and \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\" \n  shows \"continuous_map X X' g\"\nproof -\n  have eq: \"{x \\<in> topspace X. f x \\<in> U} = {x \\<in> topspace X. g x \\<in> U}\" for U\n    using assms by auto\n  show ?thesis\n    using assms by (simp add: continuous_map_def eq)\nqed\n\nlemma restrict_continuous_map [simp]:\n     \"topspace X \\<subseteq> S \\<Longrightarrow> continuous_map X X' (restrict f S) \\<longleftrightarrow> continuous_map X X' f\"\n  by (auto simp: elim!: continuous_map_eq)\n\nlemma continuous_map_in_subtopology:\n  \"continuous_map X (subtopology X' S) f \\<longleftrightarrow> continuous_map X X' f \\<and> f ` (topspace X) \\<subseteq> S\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  show ?rhs\n  proof -\n    have \"\\<And>A. f ` (X closure_of A) \\<subseteq> subtopology X' S closure_of f ` A\"\n      by (meson L continuous_map_image_closure_subset)\n    then show ?thesis\n      by (metis (no_types) closure_of_subset_subtopology closure_of_subtopology_subset closure_of_topspace continuous_map_eq_image_closure_subset order.trans)\n  qed\nnext\n  assume R: ?rhs\n  then have eq: \"{x \\<in> topspace X. f x \\<in> U} = {x \\<in> topspace X. f x \\<in> U \\<and> f x \\<in> S}\" for U\n    by auto\n  show ?lhs\n    using R\n    unfolding continuous_map\n    by (auto simp: openin_subtopology eq)\nqed\n\n\nlemma continuous_map_from_subtopology:\n     \"continuous_map X X' f \\<Longrightarrow> continuous_map (subtopology X S) X' f\"\n  by (auto simp: continuous_map openin_subtopology)\n\nlemma continuous_map_into_fulltopology:\n   \"continuous_map X (subtopology X' T) f \\<Longrightarrow> continuous_map X X' f\"\n  by (auto simp: continuous_map_in_subtopology)\n\nlemma continuous_map_into_subtopology:\n   \"\\<lbrakk>continuous_map X X' f; f ` topspace X \\<subseteq> T\\<rbrakk> \\<Longrightarrow> continuous_map X (subtopology X' T) f\"\n  by (auto simp: continuous_map_in_subtopology)\n\nlemma continuous_map_from_subtopology_mono:\n     \"\\<lbrakk>continuous_map (subtopology X T) X' f; S \\<subseteq> T\\<rbrakk>\n      \\<Longrightarrow> continuous_map (subtopology X S) X' f\"\n  by (metis inf.absorb_iff2 continuous_map_from_subtopology subtopology_subtopology)\n\nlemma continuous_map_from_discrete_topology [simp]:\n  \"continuous_map (discrete_topology U) X f \\<longleftrightarrow> f ` U \\<subseteq> topspace X\"\n  by (auto simp: continuous_map_def)\n\nlemma continuous_map_iff_continuous [simp]: \"continuous_map (top_of_set S) euclidean g = continuous_on S g\"\n  by (fastforce simp add: continuous_map openin_subtopology continuous_on_open_invariant)\n\nlemma continuous_map_iff_continuous2 [simp]: \"continuous_map euclidean euclidean g = continuous_on UNIV g\"\n  by (metis continuous_map_iff_continuous subtopology_UNIV)\n\nlemma continuous_map_openin_preimage_eq:\n   \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and> (\\<forall>U. openin Y U \\<longrightarrow> openin X (topspace X \\<inter> f -` U))\"\n  by (auto simp: continuous_map_def vimage_def Int_def)\n\nlemma continuous_map_closedin_preimage_eq:\n   \"continuous_map X Y f \\<longleftrightarrow>\n        f ` (topspace X) \\<subseteq> topspace Y \\<and> (\\<forall>U. closedin Y U \\<longrightarrow> closedin X (topspace X \\<inter> f -` U))\"\n  by (auto simp: continuous_map_closedin vimage_def Int_def)\n\nlemma continuous_map_square_root: \"continuous_map euclideanreal euclideanreal sqrt\"\n  by (simp add: continuous_at_imp_continuous_on isCont_real_sqrt)\n\nlemma continuous_map_sqrt [continuous_intros]:\n   \"continuous_map X euclideanreal f \\<Longrightarrow> continuous_map X euclideanreal (\\<lambda>x. sqrt(f x))\"\n  by (meson continuous_map_compose continuous_map_eq continuous_map_square_root o_apply)\n\nlemma continuous_map_id [simp, continuous_intros]: \"continuous_map X X id\"\n  unfolding continuous_map_def  using openin_subopen topspace_def by fastforce\n\ndeclare continuous_map_id [unfolded id_def, simp, continuous_intros]\n\nlemma continuous_map_id_subt [simp]: \"continuous_map (subtopology X S) X id\"\n  by (simp add: continuous_map_from_subtopology)\n\ndeclare continuous_map_id_subt [unfolded id_def, simp]\n\n\nlemma\\<^marker>\\<open>tag important\\<close> continuous_map_alt:\n   \"continuous_map T1 T2 f \n    = ((\\<forall>U. openin T2 U \\<longrightarrow> openin T1 (f -` U \\<inter> topspace T1)) \\<and> f ` topspace T1 \\<subseteq> topspace T2)\"\n  by (auto simp: continuous_map_def vimage_def image_def Collect_conj_eq inf_commute)\n\nlemma continuous_map_open [intro]:\n  \"continuous_map T1 T2 f \\<Longrightarrow> openin T2 U \\<Longrightarrow> openin T1 (f-`U \\<inter> topspace(T1))\"\n  unfolding continuous_map_alt by auto\n\nlemma continuous_map_preimage_topspace [intro]:\n  assumes \"continuous_map T1 T2 f\"\n  shows \"f-`(topspace T2) \\<inter> topspace T1 = topspace T1\"\nusing assms unfolding continuous_map_def by auto\n\n\n\nsubsection\\<open>Open and closed maps (not a priori assumed continuous)\\<close>\n\ndefinition open_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"open_map X1 X2 f \\<equiv> \\<forall>U. openin X1 U \\<longrightarrow> openin X2 (f ` U)\"\n\ndefinition closed_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"closed_map X1 X2 f \\<equiv> \\<forall>U. closedin X1 U \\<longrightarrow> closedin X2 (f ` U)\"\n\nlemma open_map_imp_subset_topspace:\n     \"open_map X1 X2 f \\<Longrightarrow> f ` (topspace X1) \\<subseteq> topspace X2\"\n  unfolding open_map_def by (simp add: openin_subset)\n\nlemma open_map_on_empty:\n   \"topspace X = {} \\<Longrightarrow> open_map X Y f\"\n  by (metis empty_iff imageE in_mono open_map_def openin_subopen openin_subset)\n\nlemma closed_map_on_empty:\n   \"topspace X = {} \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: closed_map_def closedin_topspace_empty)\n\nlemma closed_map_const:\n   \"closed_map X Y (\\<lambda>x. c) \\<longleftrightarrow> topspace X = {} \\<or> closedin Y {c}\"\n  by (metis closed_map_def closed_map_on_empty closedin_empty closedin_topspace image_constant_conv)\n\nlemma open_map_imp_subset:\n    \"\\<lbrakk>open_map X1 X2 f; S \\<subseteq> topspace X1\\<rbrakk> \\<Longrightarrow> f ` S \\<subseteq> topspace X2\"\n  by (meson order_trans open_map_imp_subset_topspace subset_image_iff)\n\nlemma topology_finer_open_id:\n     \"(\\<forall>S. openin X S \\<longrightarrow> openin X' S) \\<longleftrightarrow> open_map X X' id\"\n  unfolding open_map_def by auto\n\nlemma open_map_id: \"open_map X X id\"\n  unfolding open_map_def by auto\n\nlemma open_map_eq:\n     \"\\<lbrakk>open_map X X' f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> open_map X X' g\"\n  unfolding open_map_def\n  by (metis image_cong openin_subset subset_iff)\n\nlemma open_map_inclusion_eq:\n  \"open_map (subtopology X S) X id \\<longleftrightarrow> openin X (topspace X \\<inter> S)\"\n  by (metis openin_topspace openin_trans_full subtopology_restrict topology_finer_open_id topspace_subtopology)\n\nlemma open_map_inclusion:\n     \"openin X S \\<Longrightarrow> open_map (subtopology X S) X id\"\n  by (simp add: open_map_inclusion_eq openin_Int)\n\nlemma open_map_compose:\n     \"\\<lbrakk>open_map X X' f; open_map X' X'' g\\<rbrakk> \\<Longrightarrow> open_map X X'' (g \\<circ> f)\"\n  by (metis (no_types, lifting) image_comp open_map_def)\n\nlemma closed_map_imp_subset_topspace:\n     \"closed_map X1 X2 f \\<Longrightarrow> f ` (topspace X1) \\<subseteq> topspace X2\"\n  by (simp add: closed_map_def closedin_subset)\n\nlemma closed_map_imp_subset:\n     \"\\<lbrakk>closed_map X1 X2 f; S \\<subseteq> topspace X1\\<rbrakk> \\<Longrightarrow> f ` S \\<subseteq> topspace X2\"\n  using closed_map_imp_subset_topspace by blast\n\nlemma topology_finer_closed_id:\n    \"(\\<forall>S. closedin X S \\<longrightarrow> closedin X' S) \\<longleftrightarrow> closed_map X X' id\"\n  by (simp add: closed_map_def)\n\nlemma closed_map_id: \"closed_map X X id\"\n  by (simp add: closed_map_def)\n\nlemma closed_map_eq:\n   \"\\<lbrakk>closed_map X X' f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> closed_map X X' g\"\n  unfolding closed_map_def\n  by (metis image_cong closedin_subset subset_iff)\n\nlemma closed_map_compose:\n    \"\\<lbrakk>closed_map X X' f; closed_map X' X'' g\\<rbrakk> \\<Longrightarrow> closed_map X X'' (g \\<circ> f)\"\n  by (metis (no_types, lifting) closed_map_def image_comp)\n\nlemma closed_map_inclusion_eq:\n   \"closed_map (subtopology X S) X id \\<longleftrightarrow>\n        closedin X (topspace X \\<inter> S)\"\nproof -\n  have *: \"closedin X (T \\<inter> S)\" if \"closedin X (S \\<inter> topspace X)\" \"closedin X T\" for T\n    by (smt (verit, best) closedin_Int closure_of_subset_eq inf_sup_aci le_iff_inf that)\n  then show ?thesis\n    by (fastforce simp add: closed_map_def Int_commute closedin_subtopology_alt intro: *)\nqed\n\nlemma closed_map_inclusion: \"closedin X S \\<Longrightarrow> closed_map (subtopology X S) X id\"\n  by (simp add: closed_map_inclusion_eq closedin_Int)\n\nlemma open_map_into_subtopology:\n    \"\\<lbrakk>open_map X X' f; f ` topspace X \\<subseteq> S\\<rbrakk> \\<Longrightarrow> open_map X (subtopology X' S) f\"\n  unfolding open_map_def openin_subtopology\n  using openin_subset by fastforce\n\nlemma closed_map_into_subtopology:\n    \"\\<lbrakk>closed_map X X' f; f ` topspace X \\<subseteq> S\\<rbrakk> \\<Longrightarrow> closed_map X (subtopology X' S) f\"\n  unfolding closed_map_def closedin_subtopology\n  using closedin_subset by fastforce\n\nlemma open_map_into_discrete_topology:\n    \"open_map X (discrete_topology U) f \\<longleftrightarrow> f ` (topspace X) \\<subseteq> U\"\n  unfolding open_map_def openin_discrete_topology using openin_subset by blast\n\nlemma closed_map_into_discrete_topology:\n    \"closed_map X (discrete_topology U) f \\<longleftrightarrow> f ` (topspace X) \\<subseteq> U\"\n  unfolding closed_map_def closedin_discrete_topology using closedin_subset by blast\n\nlemma bijective_open_imp_closed_map:\n     \"\\<lbrakk>open_map X X' f; f ` (topspace X) = topspace X'; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> closed_map X X' f\"\n  unfolding open_map_def closed_map_def closedin_def\n  by auto (metis Diff_subset inj_on_image_set_diff)\n\nlemma bijective_closed_imp_open_map:\n     \"\\<lbrakk>closed_map X X' f; f ` (topspace X) = topspace X'; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> open_map X X' f\"\n  unfolding closed_map_def open_map_def openin_closedin_eq\n  by auto (metis Diff_subset inj_on_image_set_diff)\n\nlemma open_map_from_subtopology:\n     \"\\<lbrakk>open_map X X' f; openin X U\\<rbrakk> \\<Longrightarrow> open_map (subtopology X U) X' f\"\n  unfolding open_map_def openin_subtopology_alt by blast\n\nlemma closed_map_from_subtopology:\n     \"\\<lbrakk>closed_map X X' f; closedin X U\\<rbrakk> \\<Longrightarrow> closed_map (subtopology X U) X' f\"\n  unfolding closed_map_def closedin_subtopology_alt by blast\n\nlemma open_map_restriction:\n  assumes f: \"open_map X X' f\" and U: \"{x \\<in> topspace X. f x \\<in> V} = U\"\n  shows \"open_map (subtopology X U) (subtopology X' V) f\"\n  unfolding open_map_def\nproof clarsimp\n  fix W\n  assume \"openin (subtopology X U) W\"\n  then obtain T where \"openin X T\" \"W = T \\<inter> U\"\n    by (meson openin_subtopology)\n  with f U have \"f ` W = (f ` T) \\<inter> V\"\n    unfolding open_map_def openin_closedin_eq by auto\n  then show \"openin (subtopology X' V) (f ` W)\"\n    by (metis \\<open>openin X T\\<close> f open_map_def openin_subtopology_Int)\nqed\n\nlemma closed_map_restriction:\n  assumes f: \"closed_map X X' f\" and U: \"{x \\<in> topspace X. f x \\<in> V} = U\"\n  shows \"closed_map (subtopology X U) (subtopology X' V) f\"\n  unfolding closed_map_def\nproof clarsimp\n  fix W\n  assume \"closedin (subtopology X U) W\"\n  then obtain T where \"closedin X T\" \"W = T \\<inter> U\"\n    by (meson closedin_subtopology)\n  with f U have \"f ` W = (f ` T) \\<inter> V\"\n    unfolding closed_map_def closedin_def by auto\n  then show \"closedin (subtopology X' V) (f ` W)\"\n    by (metis \\<open>closedin X T\\<close> closed_map_def closedin_subtopology f)\nqed\n\nsubsection\\<open>Quotient maps\\<close>\n                                      \ndefinition quotient_map where\n \"quotient_map X X' f \\<longleftrightarrow>\n        f ` (topspace X) = topspace X' \\<and>\n        (\\<forall>U. U \\<subseteq> topspace X' \\<longrightarrow> (openin X {x. x \\<in> topspace X \\<and> f x \\<in> U} \\<longleftrightarrow> openin X' U))\"\n\nlemma quotient_map_eq:\n  assumes \"quotient_map X X' f\" \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\"\n  shows \"quotient_map X X' g\"\n  by (smt (verit) Collect_cong assms image_cong quotient_map_def)\n\nlemma quotient_map_compose:\n  assumes f: \"quotient_map X X' f\" and g: \"quotient_map X' X'' g\"\n  shows \"quotient_map X X'' (g \\<circ> f)\"\n  unfolding quotient_map_def\nproof (intro conjI allI impI)\n  show \"(g \\<circ> f) ` topspace X = topspace X''\"\n    using assms by (simp only: image_comp [symmetric]) (simp add: quotient_map_def)\nnext\n  fix U''\n  assume U'': \"U'' \\<subseteq> topspace X''\"\n  define U' where \"U' \\<equiv> {y \\<in> topspace X'. g y \\<in> U''}\"\n  have \"U' \\<subseteq> topspace X'\"\n    by (auto simp add: U'_def)\n  then have U': \"openin X {x \\<in> topspace X. f x \\<in> U'} = openin X' U'\"\n    using assms unfolding quotient_map_def by simp\n  have \"{x \\<in> topspace X. f x \\<in> topspace X' \\<and> g (f x) \\<in> U''} = {x \\<in> topspace X. (g \\<circ> f) x \\<in> U''}\"\n    using f quotient_map_def by fastforce\n  then show \"openin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> U''} = openin X'' U''\"\n    by (smt (verit, best) Collect_cong U' U'_def U'' g mem_Collect_eq quotient_map_def)\nqed\n\nlemma quotient_map_from_composition:\n  assumes f: \"continuous_map X X' f\" and g: \"continuous_map X' X'' g\" and gf: \"quotient_map X X'' (g \\<circ> f)\"\n  shows  \"quotient_map X' X'' g\"\n  unfolding quotient_map_def\nproof (intro conjI allI impI)\n  show \"g ` topspace X' = topspace X''\"\n    using assms unfolding continuous_map_def quotient_map_def by fastforce\nnext\n  fix U'' :: \"'c set\"\n  assume U'': \"U'' \\<subseteq> topspace X''\"\n  have eq: \"{x \\<in> topspace X. g (f x) \\<in> U''} = {x \\<in> topspace X. f x \\<in> {y. y \\<in> topspace X' \\<and> g y \\<in> U''}}\"\n    using continuous_map_def f by fastforce\n  show \"openin X' {x \\<in> topspace X'. g x \\<in> U''} = openin X'' U''\"\n    using assms unfolding continuous_map_def quotient_map_def\n    by (metis (mono_tags, lifting) Collect_cong U'' comp_apply eq)\nqed\n\nlemma quotient_imp_continuous_map:\n    \"quotient_map X X' f \\<Longrightarrow> continuous_map X X' f\"\n  by (simp add: continuous_map openin_subset quotient_map_def)\n\nlemma quotient_imp_surjective_map:\n    \"quotient_map X X' f \\<Longrightarrow> f ` (topspace X) = topspace X'\"\n  by (simp add: quotient_map_def)\n\nlemma quotient_map_closedin:\n  \"quotient_map X X' f \\<longleftrightarrow>\n        f ` (topspace X) = topspace X' \\<and>\n        (\\<forall>U. U \\<subseteq> topspace X' \\<longrightarrow> (closedin X {x. x \\<in> topspace X \\<and> f x \\<in> U} \\<longleftrightarrow> closedin X' U))\"\nproof -\n  have eq: \"(topspace X - {x \\<in> topspace X. f x \\<in> U'}) = {x \\<in> topspace X. f x \\<in> topspace X' \\<and> f x \\<notin> U'}\"\n    if \"f ` topspace X = topspace X'\" \"U' \\<subseteq> topspace X'\" for U'\n      using that by auto\n  have \"(\\<forall>U\\<subseteq>topspace X'. openin X {x \\<in> topspace X. f x \\<in> U} = openin X' U) =\n          (\\<forall>U\\<subseteq>topspace X'. closedin X {x \\<in> topspace X. f x \\<in> U} = closedin X' U)\"\n    if \"f ` topspace X = topspace X'\"\n  proof (rule iffI; intro allI impI subsetI)\n    fix U'\n    assume *[rule_format]: \"\\<forall>U\\<subseteq>topspace X'. openin X {x \\<in> topspace X. f x \\<in> U} = openin X' U\"\n      and U': \"U' \\<subseteq> topspace X'\"\n    show \"closedin X {x \\<in> topspace X. f x \\<in> U'} = closedin X' U'\"\n      using U'  by (auto simp add: closedin_def simp flip: * [of \"topspace X' - U'\"] eq [OF that])\n  next\n    fix U' :: \"'b set\"\n    assume *[rule_format]: \"\\<forall>U\\<subseteq>topspace X'. closedin X {x \\<in> topspace X. f x \\<in> U} = closedin X' U\"\n      and U': \"U' \\<subseteq> topspace X'\"\n    show \"openin X {x \\<in> topspace X. f x \\<in> U'} = openin X' U'\"\n      using U'  by (auto simp add: openin_closedin_eq simp flip: * [of \"topspace X' - U'\"] eq [OF that])\n  qed\n  then show ?thesis\n    unfolding quotient_map_def by force\nqed\n\nlemma continuous_open_imp_quotient_map:\n  assumes \"continuous_map X X' f\" and om: \"open_map X X' f\" and feq: \"f ` (topspace X) = topspace X'\"\n  shows \"quotient_map X X' f\"\nproof -\n  { fix U\n    assume U: \"U \\<subseteq> topspace X'\" and \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n    then have ope: \"openin X' (f ` {x \\<in> topspace X. f x \\<in> U})\"\n      using om unfolding open_map_def by blast\n    then have \"openin X' U\"\n      using U feq by (subst openin_subopen) force\n  }\n  moreover have \"openin X {x \\<in> topspace X. f x \\<in> U}\" if \"U \\<subseteq> topspace X'\" and \"openin X' U\" for U\n    using that assms unfolding continuous_map_def by blast\n  ultimately show ?thesis\n    unfolding quotient_map_def using assms by blast\nqed\n\nlemma continuous_closed_imp_quotient_map:\n  assumes \"continuous_map X X' f\" and om: \"closed_map X X' f\" and feq: \"f ` (topspace X) = topspace X'\"\n  shows \"quotient_map X X' f\"\nproof -\n  have \"f ` {x \\<in> topspace X. f x \\<in> U} = U\" if \"U \\<subseteq> topspace X'\" for U\n    using that feq by auto\n  with assms show ?thesis\n    unfolding quotient_map_closedin closed_map_def continuous_map_closedin by auto\nqed\n\nlemma continuous_open_quotient_map:\n   \"\\<lbrakk>continuous_map X X' f; open_map X X' f\\<rbrakk> \\<Longrightarrow> quotient_map X X' f \\<longleftrightarrow> f ` (topspace X) = topspace X'\"\n  by (meson continuous_open_imp_quotient_map quotient_map_def)\n\nlemma continuous_closed_quotient_map:\n     \"\\<lbrakk>continuous_map X X' f; closed_map X X' f\\<rbrakk> \\<Longrightarrow> quotient_map X X' f \\<longleftrightarrow> f ` (topspace X) = topspace X'\"\n  by (meson continuous_closed_imp_quotient_map quotient_map_def)\n\nlemma injective_quotient_map:\n  assumes \"inj_on f (topspace X)\"\n  shows \"quotient_map X X' f \\<longleftrightarrow>\n         continuous_map X X' f \\<and> open_map X X' f \\<and> closed_map X X' f \\<and> f ` (topspace X) = topspace X'\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  have om: \"open_map X X' f\"\n  proof (clarsimp simp add: open_map_def)\n    fix U\n    assume \"openin X U\"\n    then have \"U \\<subseteq> topspace X\"\n      by (simp add: openin_subset)\n    moreover have \"{x \\<in> topspace X. f x \\<in> f ` U} = U\"\n      using \\<open>U \\<subseteq> topspace X\\<close> assms inj_onD by fastforce\n    ultimately show \"openin X' (f ` U)\"\n      using L unfolding quotient_map_def\n      by (metis (no_types, lifting) Collect_cong \\<open>openin X U\\<close> image_mono)\n  qed\n  then have \"closed_map X X' f\"\n    by (simp add: L assms bijective_open_imp_closed_map quotient_imp_surjective_map)\n  then show ?rhs\n    using L om by (simp add: quotient_imp_continuous_map quotient_imp_surjective_map)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (simp add: continuous_closed_imp_quotient_map)\nqed\n\nlemma continuous_compose_quotient_map:\n  assumes f: \"quotient_map X X' f\" and g: \"continuous_map X X'' (g \\<circ> f)\"\n  shows \"continuous_map X' X'' g\"\n  unfolding quotient_map_def continuous_map_def\nproof (intro conjI ballI allI impI)\n  show \"\\<And>x'. x' \\<in> topspace X' \\<Longrightarrow> g x' \\<in> topspace X''\"\n    using assms unfolding quotient_map_def\n    by (metis (no_types, opaque_lifting) continuous_map_image_subset_topspace image_comp image_subset_iff)\nnext\n  fix U'' :: \"'c set\"\n  assume U'': \"openin X'' U''\"\n  have \"f ` topspace X = topspace X'\"\n    by (simp add: f quotient_imp_surjective_map)\n  then have eq: \"{x \\<in> topspace X. f x \\<in> topspace X' \\<and> g (f x) \\<in> U} = {x \\<in> topspace X. g (f x) \\<in> U}\" for U\n    by auto\n  have \"openin X {x \\<in> topspace X. f x \\<in> topspace X' \\<and> g (f x) \\<in> U''}\"\n    unfolding eq using U'' g openin_continuous_map_preimage by fastforce\n  then have *: \"openin X {x \\<in> topspace X. f x \\<in> {x \\<in> topspace X'. g x \\<in> U''}}\"\n    by auto\n  show \"openin X' {x \\<in> topspace X'. g x \\<in> U''}\"\n    using f unfolding quotient_map_def\n    by (metis (no_types) Collect_subset *)\nqed\n\nlemma continuous_compose_quotient_map_eq:\n   \"quotient_map X X' f \\<Longrightarrow> continuous_map X X'' (g \\<circ> f) \\<longleftrightarrow> continuous_map X' X'' g\"\n  using continuous_compose_quotient_map continuous_map_compose quotient_imp_continuous_map by blast\n\nlemma quotient_map_compose_eq:\n   \"quotient_map X X' f \\<Longrightarrow> quotient_map X X'' (g \\<circ> f) \\<longleftrightarrow> quotient_map X' X'' g\"\n  by (meson continuous_compose_quotient_map_eq quotient_imp_continuous_map quotient_map_compose quotient_map_from_composition)\n\nlemma quotient_map_restriction:\n  assumes quo: \"quotient_map X Y f\" and U: \"{x \\<in> topspace X. f x \\<in> V} = U\" and disj: \"openin Y V \\<or> closedin Y V\"\n shows \"quotient_map (subtopology X U) (subtopology Y V) f\"\n  using disj\nproof\n  assume V: \"openin Y V\"\n  with U have sub: \"U \\<subseteq> topspace X\" \"V \\<subseteq> topspace Y\"\n    by (auto simp: openin_subset)\n  have fim: \"f ` topspace X = topspace Y\"\n     and Y: \"\\<And>U. U \\<subseteq> topspace Y \\<Longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U} = openin Y U\"\n    using quo unfolding quotient_map_def by auto\n  have \"openin X U\"\n    using U V Y sub(2) by blast\n  show ?thesis\n    unfolding quotient_map_def\n  proof (intro conjI allI impI)\n    show \"f ` topspace (subtopology X U) = topspace (subtopology Y V)\"\n      using sub U fim by (auto)\n  next\n    fix Y' :: \"'b set\"\n    assume \"Y' \\<subseteq> topspace (subtopology Y V)\"\n    then have \"Y' \\<subseteq> topspace Y\" \"Y' \\<subseteq> V\"\n      by (simp_all)\n    then have eq: \"{x \\<in> topspace X. x \\<in> U \\<and> f x \\<in> Y'} = {x \\<in> topspace X. f x \\<in> Y'}\"\n      using U by blast\n    then show \"openin (subtopology X U) {x \\<in> topspace (subtopology X U). f x \\<in> Y'} = openin (subtopology Y V) Y'\"\n      using U V Y \\<open>openin X U\\<close>  \\<open>Y' \\<subseteq> topspace Y\\<close> \\<open>Y' \\<subseteq> V\\<close>\n      by (simp add: openin_open_subtopology eq) (auto simp: openin_closedin_eq)\n  qed\nnext\n  assume V: \"closedin Y V\"\n  with U have sub: \"U \\<subseteq> topspace X\" \"V \\<subseteq> topspace Y\"\n    by (auto simp: closedin_subset)\n  have fim: \"f ` topspace X = topspace Y\"\n     and Y: \"\\<And>U. U \\<subseteq> topspace Y \\<Longrightarrow> closedin X {x \\<in> topspace X. f x \\<in> U} = closedin Y U\"\n    using quo unfolding quotient_map_closedin by auto\n  have \"closedin X U\"\n    using U V Y sub(2) by blast\n  show ?thesis\n    unfolding quotient_map_closedin\n  proof (intro conjI allI impI)\n    show \"f ` topspace (subtopology X U) = topspace (subtopology Y V)\"\n      using sub U fim by (auto)\n  next\n    fix Y' :: \"'b set\"\n    assume \"Y' \\<subseteq> topspace (subtopology Y V)\"\n    then have \"Y' \\<subseteq> topspace Y\" \"Y' \\<subseteq> V\"\n      by (simp_all)\n    then have eq: \"{x \\<in> topspace X. x \\<in> U \\<and> f x \\<in> Y'} = {x \\<in> topspace X. f x \\<in> Y'}\"\n      using U by blast\n    then show \"closedin (subtopology X U) {x \\<in> topspace (subtopology X U). f x \\<in> Y'} = closedin (subtopology Y V) Y'\"\n      using U V Y \\<open>closedin X U\\<close>  \\<open>Y' \\<subseteq> topspace Y\\<close> \\<open>Y' \\<subseteq> V\\<close>\n      by (simp add: closedin_closed_subtopology eq) (auto simp: closedin_def)\n  qed\nqed\n\nlemma quotient_map_saturated_open:\n     \"quotient_map X Y f \\<longleftrightarrow>\n        continuous_map X Y f \\<and> f ` (topspace X) = topspace Y \\<and>\n        (\\<forall>U. openin X U \\<and> {x \\<in> topspace X. f x \\<in> f ` U} \\<subseteq> U \\<longrightarrow> openin Y (f ` U))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have fim: \"f ` topspace X = topspace Y\"\n    and Y: \"\\<And>U. U \\<subseteq> topspace Y \\<Longrightarrow> openin Y U = openin X {x \\<in> topspace X. f x \\<in> U}\"\n    unfolding quotient_map_def by auto\n  show ?rhs\n  proof (intro conjI allI impI)\n    show \"continuous_map X Y f\"\n      by (simp add: L quotient_imp_continuous_map)\n    show \"f ` topspace X = topspace Y\"\n      by (simp add: fim)\n  next\n    fix U :: \"'a set\"\n    assume U: \"openin X U \\<and> {x \\<in> topspace X. f x \\<in> f ` U} \\<subseteq> U\"\n    then have sub:  \"f ` U \\<subseteq> topspace Y\" and eq: \"{x \\<in> topspace X. f x \\<in> f ` U} = U\"\n      using fim openin_subset by fastforce+\n    show \"openin Y (f ` U)\"\n      by (simp add: sub Y eq U)\n  qed\nnext\n  assume ?rhs\n  then have YX: \"\\<And>U. openin Y U \\<Longrightarrow> openin X {x \\<in> topspace X. f x \\<in> U}\"\n       and fim: \"f ` topspace X = topspace Y\"\n       and XY: \"\\<And>U. \\<lbrakk>openin X U; {x \\<in> topspace X. f x \\<in> f ` U} \\<subseteq> U\\<rbrakk> \\<Longrightarrow> openin Y (f ` U)\"\n    by (auto simp: quotient_map_def continuous_map_def)\n  show ?lhs\n  proof (simp add: quotient_map_def fim, intro allI impI iffI)\n    fix U :: \"'b set\"\n    assume \"U \\<subseteq> topspace Y\" and X: \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n    have feq: \"f ` {x \\<in> topspace X. f x \\<in> U} = U\"\n      using \\<open>U \\<subseteq> topspace Y\\<close> fim by auto\n    show \"openin Y U\"\n      using XY [OF X] by (simp add: feq)\n  next\n    fix U :: \"'b set\"\n    assume \"U \\<subseteq> topspace Y\" and Y: \"openin Y U\"\n    show \"openin X {x \\<in> topspace X. f x \\<in> U}\"\n      by (metis YX [OF Y])\n  qed\nqed\n\nsubsection\\<open> Separated Sets\\<close>\n\ndefinition separatedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"separatedin X S T \\<equiv>\n           S \\<subseteq> topspace X \\<and> T \\<subseteq> topspace X \\<and>\n           S \\<inter> X closure_of T = {} \\<and> T \\<inter> X closure_of S = {}\"\n\nlemma separatedin_empty [simp]:\n     \"separatedin X S {} \\<longleftrightarrow> S \\<subseteq> topspace X\"\n     \"separatedin X {} S \\<longleftrightarrow> S \\<subseteq> topspace X\"\n  by (simp_all add: separatedin_def)\n\nlemma separatedin_refl [simp]:\n     \"separatedin X S S \\<longleftrightarrow> S = {}\"\n  by (metis closure_of_subset empty_subsetI inf.orderE separatedin_def)\n\nlemma separatedin_sym:\n     \"separatedin X S T \\<longleftrightarrow> separatedin X T S\"\n  by (auto simp: separatedin_def)\n\nlemma separatedin_imp_disjoint:\n     \"separatedin X S T \\<Longrightarrow> disjnt S T\"\n  by (meson closure_of_subset disjnt_def disjnt_subset2 separatedin_def)\n\nlemma separatedin_mono:\n   \"\\<lbrakk>separatedin X S T; S' \\<subseteq> S; T' \\<subseteq> T\\<rbrakk> \\<Longrightarrow> separatedin X S' T'\"\n  unfolding separatedin_def\n  using closure_of_mono by blast\n\nlemma separatedin_open_sets:\n     \"\\<lbrakk>openin X S; openin X T\\<rbrakk> \\<Longrightarrow> separatedin X S T \\<longleftrightarrow> disjnt S T\"\n  unfolding disjnt_def separatedin_def\n  by (auto simp: openin_Int_closure_of_eq_empty openin_subset)\n\nlemma separatedin_closed_sets:\n     \"\\<lbrakk>closedin X S; closedin X T\\<rbrakk> \\<Longrightarrow> separatedin X S T \\<longleftrightarrow> disjnt S T\"\n  unfolding closure_of_eq disjnt_def separatedin_def\n  by (metis closedin_def closure_of_eq inf_commute)\n\nlemma separatedin_subtopology:\n     \"separatedin (subtopology X U) S T \\<longleftrightarrow> S \\<subseteq> U \\<and> T \\<subseteq> U \\<and> separatedin X S T\"\n  by (auto simp: separatedin_def closure_of_subtopology Int_ac disjoint_iff elim!: inf.orderE)\n\nlemma separatedin_discrete_topology:\n     \"separatedin (discrete_topology U) S T \\<longleftrightarrow> S \\<subseteq> U \\<and> T \\<subseteq> U \\<and> disjnt S T\"\n  by (metis openin_discrete_topology separatedin_def separatedin_open_sets topspace_discrete_topology)\n\nlemma separated_eq_distinguishable:\n   \"separatedin X {x} {y} \\<longleftrightarrow>\n        x \\<in> topspace X \\<and> y \\<in> topspace X \\<and>\n        (\\<exists>U. openin X U \\<and> x \\<in> U \\<and> (y \\<notin> U)) \\<and>\n        (\\<exists>v. openin X v \\<and> y \\<in> v \\<and> (x \\<notin> v))\"\n  by (force simp: separatedin_def closure_of_def)\n\nlemma separatedin_Un [simp]:\n   \"separatedin X S (T \\<union> U) \\<longleftrightarrow> separatedin X S T \\<and> separatedin X S U\"\n   \"separatedin X (S \\<union> T) U \\<longleftrightarrow> separatedin X S U \\<and> separatedin X T U\"\n  by (auto simp: separatedin_def)\n\nlemma separatedin_Union:\n  \"finite \\<F> \\<Longrightarrow> separatedin X S (\\<Union>\\<F>) \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> (\\<forall>T \\<in> \\<F>. separatedin X S T)\"\n  \"finite \\<F> \\<Longrightarrow> separatedin X (\\<Union>\\<F>) S \\<longleftrightarrow> (\\<forall>T \\<in> \\<F>. separatedin X S T) \\<and> S \\<subseteq> topspace X\"\n  by (auto simp: separatedin_def closure_of_Union)\n\nlemma separatedin_openin_diff:\n   \"\\<lbrakk>openin X S; openin X T\\<rbrakk> \\<Longrightarrow> separatedin X (S - T) (T - S)\"\n  unfolding separatedin_def\n  by (metis Diff_Int_distrib2 Diff_disjoint Diff_empty Diff_mono empty_Diff empty_subsetI openin_Int_closure_of_eq_empty openin_subset)\n\nlemma separatedin_closedin_diff:\n  assumes \"closedin X S\" \"closedin X T\"\n  shows \"separatedin X (S - T) (T - S)\"\nproof -\n  have \"S - T \\<subseteq> topspace X\" \"T - S \\<subseteq> topspace X\"\n    using assms closedin_subset by auto\n  with assms show ?thesis\n    by (simp add: separatedin_def Diff_Int_distrib2 closure_of_minimal inf_absorb2)\nqed\n\nlemma separation_closedin_Un_gen:\n     \"separatedin X S T \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and> T \\<subseteq> topspace X \\<and> disjnt S T \\<and>\n        closedin (subtopology X (S \\<union> T)) S \\<and>\n        closedin (subtopology X (S \\<union> T)) T\"\n  by (auto simp add: separatedin_def closedin_Int_closure_of disjnt_iff dest: closure_of_subset)\n\nlemma separation_openin_Un_gen:\n     \"separatedin X S T \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and> T \\<subseteq> topspace X \\<and> disjnt S T \\<and>\n        openin (subtopology X (S \\<union> T)) S \\<and>\n        openin (subtopology X (S \\<union> T)) T\"\n  unfolding openin_closedin_eq topspace_subtopology separation_closedin_Un_gen disjnt_def\n  by (auto simp: Diff_triv Int_commute Un_Diff inf_absorb1 topspace_def)\n\n\nsubsection\\<open>Homeomorphisms\\<close>\ntext\\<open>(1-way and 2-way versions may be useful in places)\\<close>\n\ndefinition homeomorphic_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where\n \"homeomorphic_map X Y f \\<equiv> quotient_map X Y f \\<and> inj_on f (topspace X)\"\n\ndefinition homeomorphic_maps :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where\n \"homeomorphic_maps X Y f g \\<equiv>\n    continuous_map X Y f \\<and> continuous_map Y X g \\<and>\n     (\\<forall>x \\<in> topspace X. g(f x) = x) \\<and> (\\<forall>y \\<in> topspace Y. f(g y) = y)\"\n\n\nlemma homeomorphic_map_eq:\n   \"\\<lbrakk>homeomorphic_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> homeomorphic_map X Y g\"\n  by (meson homeomorphic_map_def inj_on_cong quotient_map_eq)\n\nlemma homeomorphic_maps_eq:\n     \"\\<lbrakk>homeomorphic_maps X Y f g;\n       \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = f' x; \\<And>y. y \\<in> topspace Y \\<Longrightarrow> g y = g' y\\<rbrakk>\n      \\<Longrightarrow> homeomorphic_maps X Y f' g'\"\n  unfolding homeomorphic_maps_def\n  by (metis continuous_map_eq continuous_map_eq_image_closure_subset_gen image_subset_iff)\n\nlemma homeomorphic_maps_sym:\n     \"homeomorphic_maps X Y f g \\<longleftrightarrow> homeomorphic_maps Y X g f\"\n  by (auto simp: homeomorphic_maps_def)\n\nlemma homeomorphic_maps_id:\n     \"homeomorphic_maps X Y id id \\<longleftrightarrow> Y = X\"  (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have \"topspace X = topspace Y\"\n    by (auto simp: homeomorphic_maps_def continuous_map_def)\n  with L show ?rhs\n    unfolding homeomorphic_maps_def\n    by (metis topology_finer_continuous_id topology_eq)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding homeomorphic_maps_def by auto\nqed\n\nlemma homeomorphic_map_id [simp]: \"homeomorphic_map X Y id \\<longleftrightarrow> Y = X\"\n       (is \"?lhs = ?rhs\")\nproof\n  assume L: ?lhs\n  then have eq: \"topspace X = topspace Y\"\n    by (auto simp: homeomorphic_map_def continuous_map_def quotient_map_def)\n  then have \"\\<And>S. openin X S \\<longrightarrow> openin Y S\"\n    by (meson L homeomorphic_map_def injective_quotient_map topology_finer_open_id)\n  then show ?rhs\n    using L unfolding homeomorphic_map_def\n    by (metis eq quotient_imp_continuous_map topology_eq topology_finer_continuous_id)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding homeomorphic_map_def\n    by (simp add: closed_map_id continuous_closed_imp_quotient_map)\nqed\n\nlemma homeomorphic_map_compose:\n  assumes \"homeomorphic_map X Y f\" \"homeomorphic_map Y X'' g\"\n  shows \"homeomorphic_map X X'' (g \\<circ> f)\"\nproof -\n  have \"inj_on g (f ` topspace X)\"\n    by (metis (no_types) assms homeomorphic_map_def quotient_imp_surjective_map)\n  then show ?thesis\n    using assms by (meson comp_inj_on homeomorphic_map_def quotient_map_compose_eq)\nqed\n\nlemma homeomorphic_maps_compose:\n   \"homeomorphic_maps X Y f h \\<and>\n        homeomorphic_maps Y X'' g k\n        \\<Longrightarrow> homeomorphic_maps X X'' (g \\<circ> f) (h \\<circ> k)\"\n  unfolding homeomorphic_maps_def\n  by (auto simp: continuous_map_compose; simp add: continuous_map_def)\n\nlemma homeomorphic_eq_everything_map:\n   \"homeomorphic_map X Y f \\<longleftrightarrow>\n        continuous_map X Y f \\<and> open_map X Y f \\<and> closed_map X Y f \\<and>\n        f ` (topspace X) = topspace Y \\<and> inj_on f (topspace X)\"\n  unfolding homeomorphic_map_def\n  by (force simp: injective_quotient_map intro: injective_quotient_map)\n\nlemma homeomorphic_imp_continuous_map:\n     \"homeomorphic_map X Y f \\<Longrightarrow> continuous_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_open_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> open_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_closed_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_surjective_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> f ` (topspace X) = topspace Y\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma homeomorphic_imp_injective_map:\n    \"homeomorphic_map X Y f \\<Longrightarrow> inj_on f (topspace X)\"\n  by (simp add: homeomorphic_eq_everything_map)\n\nlemma bijective_open_imp_homeomorphic_map:\n   \"\\<lbrakk>continuous_map X Y f; open_map X Y f; f ` (topspace X) = topspace Y; inj_on f (topspace X)\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map X Y f\"\n  by (simp add: homeomorphic_map_def continuous_open_imp_quotient_map)\n\nlemma bijective_closed_imp_homeomorphic_map:\n   \"\\<lbrakk>continuous_map X Y f; closed_map X Y f; f ` (topspace X) = topspace Y; inj_on f (topspace X)\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map X Y f\"\n  by (simp add: continuous_closed_quotient_map homeomorphic_map_def)\n\nlemma open_eq_continuous_inverse_map:\n  assumes X: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y \\<and> g(f x) = x\"\n    and Y: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> g y \\<in> topspace X \\<and> f(g y) = y\"\n  shows \"open_map X Y f \\<longleftrightarrow> continuous_map Y X g\"\nproof -\n  have eq: \"{x \\<in> topspace Y. g x \\<in> U} = f ` U\" if \"openin X U\" for U\n    using openin_subset [OF that] by (force simp: X Y image_iff)\n  show ?thesis\n    by (auto simp: Y open_map_def continuous_map_def eq)\nqed\n\nlemma closed_eq_continuous_inverse_map:\n  assumes X: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y \\<and> g(f x) = x\"\n    and Y: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> g y \\<in> topspace X \\<and> f(g y) = y\"\n  shows \"closed_map X Y f \\<longleftrightarrow> continuous_map Y X g\"\nproof -\n  have eq: \"{x \\<in> topspace Y. g x \\<in> U} = f ` U\" if \"closedin X U\" for U\n    using closedin_subset [OF that] by (force simp: X Y image_iff)\n  show ?thesis\n    by (auto simp: Y closed_map_def continuous_map_closedin eq)\nqed\n\nlemma homeomorphic_maps_map:\n  \"homeomorphic_maps X Y f g \\<longleftrightarrow>\n        homeomorphic_map X Y f \\<and> homeomorphic_map Y X g \\<and>\n        (\\<forall>x \\<in> topspace X. g(f x) = x) \\<and> (\\<forall>y \\<in> topspace Y. f(g y) = y)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have L: \"continuous_map X Y f\" \"continuous_map Y X g\" \"\\<forall>x\\<in>topspace X. g (f x) = x\" \"\\<forall>x'\\<in>topspace Y. f (g x') = x'\"\n    by (auto simp: homeomorphic_maps_def)\n  show ?rhs\n  proof (intro conjI bijective_open_imp_homeomorphic_map L)\n    show \"open_map X Y f\"\n      using L using open_eq_continuous_inverse_map [of concl: X Y f g] by (simp add: continuous_map_def)\n    show \"open_map Y X g\"\n      using L using open_eq_continuous_inverse_map [of concl: Y X g f] by (simp add: continuous_map_def)\n    show \"f ` topspace X = topspace Y\" \"g ` topspace Y = topspace X\"\n      using L by (force simp: continuous_map_closedin)+\n    show \"inj_on f (topspace X)\" \"inj_on g (topspace Y)\"\n      using L unfolding inj_on_def by metis+\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by (auto simp: homeomorphic_maps_def homeomorphic_imp_continuous_map)\nqed\n\nlemma homeomorphic_maps_imp_map:\n    \"homeomorphic_maps X Y f g \\<Longrightarrow> homeomorphic_map X Y f\"\n  using homeomorphic_maps_map by blast\n\nlemma homeomorphic_map_maps:\n     \"homeomorphic_map X Y f \\<longleftrightarrow> (\\<exists>g. homeomorphic_maps X Y f g)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have L: \"continuous_map X Y f\" \"open_map X Y f\" \"closed_map X Y f\"\n    \"f ` (topspace X) = topspace Y\" \"inj_on f (topspace X)\"\n    by (auto simp: homeomorphic_eq_everything_map)\n  have X: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> f x \\<in> topspace Y \\<and> inv_into (topspace X) f (f x) = x\"\n    using L by auto\n  have Y: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> inv_into (topspace X) f y \\<in> topspace X \\<and> f (inv_into (topspace X) f y) = y\"\n    by (simp add: L f_inv_into_f inv_into_into)\n  have \"homeomorphic_maps X Y f (inv_into (topspace X) f)\"\n    unfolding homeomorphic_maps_def\n  proof (intro conjI L)\n    show \"continuous_map Y X (inv_into (topspace X) f)\"\n      by (simp add: L X Y flip: open_eq_continuous_inverse_map [where f=f])\n  next\n    show \"\\<forall>x\\<in>topspace X. inv_into (topspace X) f (f x) = x\"\n         \"\\<forall>y\\<in>topspace Y. f (inv_into (topspace X) f y) = y\"\n      using X Y by auto\n  qed\n  then show ?rhs\n    by metis\nnext\n  assume ?rhs\n  then show ?lhs\n    using homeomorphic_maps_map by blast\nqed\n\nlemma homeomorphic_maps_involution:\n   \"\\<lbrakk>continuous_map X X f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f(f x) = x\\<rbrakk> \\<Longrightarrow> homeomorphic_maps X X f f\"\n  by (auto simp: homeomorphic_maps_def)\n\nlemma homeomorphic_map_involution:\n   \"\\<lbrakk>continuous_map X X f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f(f x) = x\\<rbrakk> \\<Longrightarrow> homeomorphic_map X X f\"\n  using homeomorphic_maps_involution homeomorphic_maps_map by blast\n\nlemma homeomorphic_map_openness:\n  assumes hom: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"openin Y (f ` U) \\<longleftrightarrow> openin X U\"\nproof -\n  obtain g where \"homeomorphic_maps X Y f g\"\n    using assms by (auto simp: homeomorphic_map_maps)\n  then have g: \"homeomorphic_map Y X g\" and gf: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> g(f x) = x\"\n    by (auto simp: homeomorphic_maps_map)\n  then have \"openin X U \\<Longrightarrow> openin Y (f ` U)\"\n    using hom homeomorphic_imp_open_map open_map_def by blast\n  show \"openin Y (f ` U) = openin X U\"\n  proof\n    assume L: \"openin Y (f ` U)\"\n    have \"U = g ` (f ` U)\"\n      using U gf by force\n    then show \"openin X U\"\n      by (metis L homeomorphic_imp_open_map open_map_def g)\n  next\n    assume \"openin X U\"\n    then show \"openin Y (f ` U)\"\n      using hom homeomorphic_imp_open_map open_map_def by blast\n  qed\nqed\n\n\nlemma homeomorphic_map_closedness:\n  assumes hom: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"closedin Y (f ` U) \\<longleftrightarrow> closedin X U\"\nproof -\n  obtain g where \"homeomorphic_maps X Y f g\"\n    using assms by (auto simp: homeomorphic_map_maps)\n  then have g: \"homeomorphic_map Y X g\" and gf: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> g(f x) = x\"\n    by (auto simp: homeomorphic_maps_map)\n  then have \"closedin X U \\<Longrightarrow> closedin Y (f ` U)\"\n    using hom homeomorphic_imp_closed_map closed_map_def by blast\n  show \"closedin Y (f ` U) = closedin X U\"\n  proof\n    assume L: \"closedin Y (f ` U)\"\n    have \"U = g ` (f ` U)\"\n      using U gf by force\n    then show \"closedin X U\"\n      by (metis L homeomorphic_imp_closed_map closed_map_def g)\n  next\n    assume \"closedin X U\"\n    then show \"closedin Y (f ` U)\"\n      using hom homeomorphic_imp_closed_map closed_map_def by blast\n  qed\nqed\n\nlemma homeomorphic_map_openness_eq:\n     \"homeomorphic_map X Y f \\<Longrightarrow> openin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> openin Y (f ` U)\"\n  by (meson homeomorphic_map_openness openin_closedin_eq)\n\nlemma homeomorphic_map_closedness_eq:\n    \"homeomorphic_map X Y f \\<Longrightarrow> closedin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> closedin Y (f ` U)\"\n  by (meson closedin_subset homeomorphic_map_closedness)\n\nlemma all_openin_homeomorphic_image:\n  assumes \"homeomorphic_map X Y f\"\n  shows \"(\\<forall>V. openin Y V \\<longrightarrow> P V) \\<longleftrightarrow> (\\<forall>U. openin X U \\<longrightarrow> P(f ` U))\" \n  by (metis (no_types, lifting) assms homeomorphic_imp_surjective_map homeomorphic_map_openness openin_subset subset_image_iff)\n\nlemma all_closedin_homeomorphic_image:\n  assumes \"homeomorphic_map X Y f\"\n  shows \"(\\<forall>V. closedin Y V \\<longrightarrow> P V) \\<longleftrightarrow> (\\<forall>U. closedin X U \\<longrightarrow> P(f ` U))\"  (is \"?lhs = ?rhs\")\n  by (metis (no_types, lifting) assms homeomorphic_imp_surjective_map homeomorphic_map_closedness closedin_subset subset_image_iff)\n\n\nlemma homeomorphic_map_derived_set_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y derived_set_of (f ` S) = f ` (X derived_set_of S)\"\nproof -\n  have fim: \"f ` (topspace X) = topspace Y\" and inj: \"inj_on f (topspace X)\"\n    using hom by (auto simp: homeomorphic_eq_everything_map)\n  have iff: \"(\\<forall>T. x \\<in> T \\<and> openin X T \\<longrightarrow> (\\<exists>y. y \\<noteq> x \\<and> y \\<in> S \\<and> y \\<in> T)) =\n            (\\<forall>T. T \\<subseteq> topspace Y \\<longrightarrow> f x \\<in> T \\<longrightarrow> openin Y T \\<longrightarrow> (\\<exists>y. y \\<noteq> f x \\<and> y \\<in> f ` S \\<and> y \\<in> T))\"\n    if \"x \\<in> topspace X\" for x\n  proof -\n    have \\<section>: \"(x \\<in> T \\<and> openin X T) = (T \\<subseteq> topspace X \\<and> f x \\<in> f ` T \\<and> openin Y (f ` T))\" for T\n      by (meson hom homeomorphic_map_openness_eq inj inj_on_image_mem_iff that)\n    moreover have \"(\\<exists>y. y \\<noteq> x \\<and> y \\<in> S \\<and> y \\<in> T) = (\\<exists>y. y \\<noteq> f x \\<and> y \\<in> f ` S \\<and> y \\<in> f ` T)\"  (is \"?lhs = ?rhs\")\n      if \"T \\<subseteq> topspace X \\<and> f x \\<in> f ` T \\<and> openin Y (f ` T)\" for T\n      by (smt (verit, del_insts) S \\<open>x \\<in> topspace X\\<close> image_iff inj inj_on_def subsetD that)\n    ultimately show ?thesis\n      by (auto simp flip: fim simp: all_subset_image)\n  qed\n  have *: \"\\<lbrakk>T = f ` S; \\<And>x. x \\<in> S \\<Longrightarrow> P x \\<longleftrightarrow> Q(f x)\\<rbrakk> \\<Longrightarrow> {y. y \\<in> T \\<and> Q y} = f ` {x \\<in> S. P x}\" for T S P Q\n    by auto\n  show ?thesis\n    unfolding derived_set_of_def\n    by (rule *) (use fim iff openin_subset in force)+\nqed\n\n\nlemma homeomorphic_map_closure_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y closure_of (f ` S) = f ` (X closure_of S)\"\n  unfolding closure_of\n  using homeomorphic_imp_surjective_map [OF hom] S\n  by (auto simp: in_derived_set_of homeomorphic_map_derived_set_of [OF assms])\n\nlemma homeomorphic_map_interior_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y interior_of (f ` S) = f ` (X interior_of S)\"\nproof -\n  { fix y\n    assume \"y \\<in> topspace Y\" and \"y \\<notin> Y closure_of (topspace Y - f ` S)\"\n    then have \"y \\<in> f ` (topspace X - X closure_of (topspace X - S))\"\n      using homeomorphic_eq_everything_map [THEN iffD1, OF hom] homeomorphic_map_closure_of [OF hom]\n      by (metis DiffI Diff_subset S closure_of_subset_topspace inj_on_image_set_diff) }\n  moreover\n  { fix x\n    assume \"x \\<in> topspace X\"\n    then have \"f x \\<in> topspace Y\"\n      using hom homeomorphic_imp_surjective_map by blast }\n  moreover\n  { fix x\n    assume \"x \\<in> topspace X\" and \"x \\<notin> X closure_of (topspace X - S)\" and \"f x \\<in> Y closure_of (topspace Y - f ` S)\"\n    then have \"False\"\n      using homeomorphic_map_closure_of [OF hom] hom\n      unfolding homeomorphic_eq_everything_map\n      by (metis Diff_subset S closure_of_subset_topspace inj_on_image_mem_iff inj_on_image_set_diff)\n  }\n  ultimately  show ?thesis\n    by (auto simp: interior_of_closure_of)\nqed\n\nlemma homeomorphic_map_frontier_of:\n  assumes hom: \"homeomorphic_map X Y f\" and S: \"S \\<subseteq> topspace X\"\n  shows \"Y frontier_of (f ` S) = f ` (X frontier_of S)\"\n  unfolding frontier_of_def\nproof (intro equalityI subsetI DiffI)\n  fix y\n  assume \"y \\<in> Y closure_of f ` S - Y interior_of f ` S\"\n  then show \"y \\<in> f ` (X closure_of S - X interior_of S)\"\n    using S hom homeomorphic_map_closure_of homeomorphic_map_interior_of by fastforce\nnext\n  fix y\n  assume \"y \\<in> f ` (X closure_of S - X interior_of S)\"\n  then show \"y \\<in> Y closure_of f ` S\"\n    using S hom homeomorphic_map_closure_of by fastforce\nnext\n  fix x\n  assume \"x \\<in> f ` (X closure_of S - X interior_of S)\"\n  then obtain y where y: \"x = f y\" \"y \\<in> X closure_of S\" \"y \\<notin> X interior_of S\"\n    by blast\n  then show \"x \\<notin> Y interior_of f ` S\"\n    using S hom homeomorphic_map_interior_of y(1)\n    unfolding homeomorphic_map_def\n    by (smt (verit, ccfv_SIG) in_closure_of inj_on_image_mem_iff interior_of_subset_topspace) \nqed\n\nlemma homeomorphic_maps_subtopologies:\n   \"\\<lbrakk>homeomorphic_maps X Y f g;  f ` (topspace X \\<inter> S) = topspace Y \\<inter> T\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_maps (subtopology X S) (subtopology Y T) f g\"\n  unfolding homeomorphic_maps_def\n  by (force simp: continuous_map_from_subtopology continuous_map_in_subtopology)\n\nlemma homeomorphic_maps_subtopologies_alt:\n     \"\\<lbrakk>homeomorphic_maps X Y f g; f ` (topspace X \\<inter> S) \\<subseteq> T; g ` (topspace Y \\<inter> T) \\<subseteq> S\\<rbrakk>\n      \\<Longrightarrow> homeomorphic_maps (subtopology X S) (subtopology Y T) f g\"\n  unfolding homeomorphic_maps_def\n  by (force simp: continuous_map_from_subtopology continuous_map_in_subtopology)\n\nlemma homeomorphic_map_subtopologies:\n   \"\\<lbrakk>homeomorphic_map X Y f; f ` (topspace X \\<inter> S) = topspace Y \\<inter> T\\<rbrakk>\n        \\<Longrightarrow> homeomorphic_map (subtopology X S) (subtopology Y T) f\"\n  by (meson homeomorphic_map_maps homeomorphic_maps_subtopologies)\n\nlemma homeomorphic_map_subtopologies_alt:\n  assumes hom: \"homeomorphic_map X Y f\" \n      and S: \"\\<And>x. \\<lbrakk>x \\<in> topspace X; f x \\<in> topspace Y\\<rbrakk> \\<Longrightarrow> f x \\<in> T \\<longleftrightarrow> x \\<in> S\"\n    shows \"homeomorphic_map (subtopology X S) (subtopology Y T) f\"\nproof -\n  have \"homeomorphic_maps (subtopology X S) (subtopology Y T) f g\" \n    if \"homeomorphic_maps X Y f g\" for g\n  proof (rule homeomorphic_maps_subtopologies [OF that])\n    have \"f ` (topspace X \\<inter> S) \\<subseteq> topspace Y \\<inter> T\"\n      using S hom homeomorphic_imp_surjective_map by fastforce\n    then show \"f ` (topspace X \\<inter> S) = topspace Y \\<inter> T\"\n      using that unfolding homeomorphic_maps_def continuous_map_def\n      by (smt (verit, del_insts) Int_iff S image_iff subsetI subset_antisym)\n  qed\n  then show ?thesis\n    using hom by (meson homeomorphic_map_maps)\nqed\n\n\nsubsection\\<open>Relation of homeomorphism between topological spaces\\<close>\n\ndefinition homeomorphic_space (infixr \"homeomorphic'_space\" 50)\n  where \"X homeomorphic_space Y \\<equiv> \\<exists>f g. homeomorphic_maps X Y f g\"\n\nlemma homeomorphic_space_refl: \"X homeomorphic_space X\"\n  by (meson homeomorphic_maps_id homeomorphic_space_def)\n\nlemma homeomorphic_space_sym:\n   \"X homeomorphic_space Y \\<longleftrightarrow> Y homeomorphic_space X\"\n  unfolding homeomorphic_space_def by (metis homeomorphic_maps_sym)\n\nlemma homeomorphic_space_trans [trans]:\n     \"\\<lbrakk>X1 homeomorphic_space X2; X2 homeomorphic_space X3\\<rbrakk> \\<Longrightarrow> X1 homeomorphic_space X3\"\n  unfolding homeomorphic_space_def by (metis homeomorphic_maps_compose)\n\nlemma homeomorphic_space:\n     \"X homeomorphic_space Y \\<longleftrightarrow> (\\<exists>f. homeomorphic_map X Y f)\"\n  by (simp add: homeomorphic_map_maps homeomorphic_space_def)\n\nlemma homeomorphic_maps_imp_homeomorphic_space:\n     \"homeomorphic_maps X Y f g \\<Longrightarrow> X homeomorphic_space Y\"\n  unfolding homeomorphic_space_def by metis\n\nlemma homeomorphic_map_imp_homeomorphic_space:\n     \"homeomorphic_map X Y f \\<Longrightarrow> X homeomorphic_space Y\"\n  unfolding homeomorphic_map_maps\n  using homeomorphic_space_def by blast\n\nlemma homeomorphic_empty_space:\n     \"X homeomorphic_space Y \\<Longrightarrow> topspace X = {} \\<longleftrightarrow> topspace Y = {}\"\n  by (metis homeomorphic_imp_surjective_map homeomorphic_space image_is_empty)\n\nlemma homeomorphic_empty_space_eq:\n  assumes \"topspace X = {}\"\n  shows \"X homeomorphic_space Y \\<longleftrightarrow> topspace Y = {}\"\n  unfolding homeomorphic_maps_def homeomorphic_space_def\n  by (metis assms continuous_map_on_empty continuous_map_closedin ex_in_conv)\n\nsubsection\\<open>Connected topological spaces\\<close>\n\ndefinition connected_space :: \"'a topology \\<Rightarrow> bool\" where\n  \"connected_space X \\<equiv>\n        \\<not>(\\<exists>E1 E2. openin X E1 \\<and> openin X E2 \\<and>\n                  topspace X \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n\ndefinition connectedin :: \"'a topology \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"connectedin X S \\<equiv> S \\<subseteq> topspace X \\<and> connected_space (subtopology X S)\"\n\nlemma connected_spaceD:\n  \"\\<lbrakk>connected_space X;\n    openin X U; openin X V; topspace X \\<subseteq> U \\<union> V; U \\<inter> V = {}; U \\<noteq> {}; V \\<noteq> {}\\<rbrakk> \\<Longrightarrow> False\"\n  by (auto simp: connected_space_def)\n\nlemma connectedin_subset_topspace: \"connectedin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n  by (simp add: connectedin_def)\n\nlemma connectedin_topspace:\n     \"connectedin X (topspace X) \\<longleftrightarrow> connected_space X\"\n  by (simp add: connectedin_def)\n\nlemma connected_space_subtopology:\n     \"connectedin X S \\<Longrightarrow> connected_space (subtopology X S)\"\n  by (simp add: connectedin_def)\n\nlemma connectedin_subtopology:\n     \"connectedin (subtopology X S) T \\<longleftrightarrow> connectedin X T \\<and> T \\<subseteq> S\"\n  by (force simp: connectedin_def subtopology_subtopology inf_absorb2)\n\nlemma connected_space_eq:\n     \"connected_space X \\<longleftrightarrow>\n      (\\<nexists>E1 E2. openin X E1 \\<and> openin X E2 \\<and> E1 \\<union> E2 = topspace X \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  unfolding connected_space_def\n  by (metis openin_Un openin_subset subset_antisym)\n\nlemma connected_space_closedin:\n     \"connected_space X \\<longleftrightarrow>\n      (\\<nexists>E1 E2. closedin X E1 \\<and> closedin X E2 \\<and> topspace X \\<subseteq> E1 \\<union> E2 \\<and>\n               E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"\\<And>E1 E2. \\<lbrakk>openin X E1; E1 \\<inter> E2 = {}; topspace X \\<subseteq> E1 \\<union> E2; openin X E2\\<rbrakk> \\<Longrightarrow> E1 = {} \\<or> E2 = {}\"\n    by (simp add: connected_space_def)\n  then show ?rhs\n    unfolding connected_space_def\n    by (metis disjnt_def separatedin_closed_sets separation_openin_Un_gen subtopology_superset)\nnext\n  assume R: ?rhs\n  then show ?lhs\n    unfolding connected_space_def\n    by (metis Diff_triv Int_commute separatedin_openin_diff separation_closedin_Un_gen subtopology_superset)\nqed\n\nlemma connected_space_closedin_eq:\n     \"connected_space X \\<longleftrightarrow>\n       (\\<nexists>E1 E2. closedin X E1 \\<and> closedin X E2 \\<and>\n                E1 \\<union> E2 = topspace X \\<and> E1 \\<inter> E2 = {} \\<and> E1 \\<noteq> {} \\<and> E2 \\<noteq> {})\"\n  by (metis closedin_Un closedin_def connected_space_closedin subset_antisym)\n\nlemma connected_space_clopen_in:\n     \"connected_space X \\<longleftrightarrow>\n        (\\<forall>T. openin X T \\<and> closedin X T \\<longrightarrow> T = {} \\<or> T = topspace X)\"\nproof -\n  have eq: \"openin X E1 \\<and> openin X E2 \\<and> E1 \\<union> E2 = topspace X \\<and> E1 \\<inter> E2 = {} \\<and> P\n        \\<longleftrightarrow> E2 = topspace X - E1 \\<and> openin X E1 \\<and> openin X E2 \\<and> P\" for E1 E2 P\n    using openin_subset by blast\n  show ?thesis\n    unfolding connected_space_eq eq closedin_def\n    by (auto simp: openin_closedin_eq)\nqed\n\nlemma connectedin:\n     \"connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n         (\\<nexists>E1 E2.\n             openin X E1 \\<and> openin X E2 \\<and>\n             S \\<subseteq> E1 \\<union> E2 \\<and> E1 \\<inter> E2 \\<inter> S = {} \\<and> E1 \\<inter> S \\<noteq> {} \\<and> E2 \\<inter> S \\<noteq> {})\"  (is \"?lhs = ?rhs\")\nproof -\n  have *: \"(\\<exists>E1:: 'a set. \\<exists>E2:: 'a set. (\\<exists>T1:: 'a set. P1 T1 \\<and> E1 = f1 T1) \\<and> (\\<exists>T2:: 'a set. P2 T2 \\<and> E2 = f2 T2) \\<and>\n             R E1 E2) \\<longleftrightarrow> (\\<exists>T1 T2. P1 T1 \\<and> P2 T2 \\<and> R(f1 T1) (f2 T2))\" for P1 f1 P2 f2 R\n    by auto\n  show ?thesis \n    unfolding connectedin_def connected_space_def openin_subtopology topspace_subtopology *\n    by (intro conj_cong arg_cong [where f=Not] ex_cong1; blast dest!: openin_subset)\nqed\n\nlemma connectedin_iff_connected [simp]: \"connectedin euclidean S \\<longleftrightarrow> connected S\"\n  by (simp add: connected_def connectedin)\n\nlemma connectedin_closedin:\n   \"connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n        \\<not>(\\<exists>E1 E2. closedin X E1 \\<and> closedin X E2 \\<and>\n                  S \\<subseteq> (E1 \\<union> E2) \\<and>\n                  (E1 \\<inter> E2 \\<inter> S = {}) \\<and>\n                  \\<not>(E1 \\<inter> S = {}) \\<and> \\<not>(E2 \\<inter> S = {}))\"\nproof -\n  have *: \"(\\<exists>E1:: 'a set. \\<exists>E2:: 'a set. (\\<exists>T1:: 'a set. P1 T1 \\<and> E1 = f1 T1) \\<and> (\\<exists>T2:: 'a set. P2 T2 \\<and> E2 = f2 T2) \\<and>\n             R E1 E2) \\<longleftrightarrow> (\\<exists>T1 T2. P1 T1 \\<and> P2 T2 \\<and> R(f1 T1) (f2 T2))\" for P1 f1 P2 f2 R\n    by auto\n  show ?thesis\n    unfolding connectedin_def connected_space_closedin closedin_subtopology topspace_subtopology *\n    by (intro conj_cong arg_cong [where f=Not] ex_cong1; blast dest!: openin_subset)\nqed\n\nlemma connectedin_empty [simp]: \"connectedin X {}\"\n  by (simp add: connectedin)\n\nlemma connected_space_topspace_empty:\n     \"topspace X = {} \\<Longrightarrow> connected_space X\"\n  using connectedin_topspace by fastforce\n\nlemma connectedin_sing [simp]: \"connectedin X {a} \\<longleftrightarrow> a \\<in> topspace X\"\n  by (simp add: connectedin)\n\nlemma connectedin_absolute [simp]:\n  \"connectedin (subtopology X S) S \\<longleftrightarrow> connectedin X S\"\n  by (simp add: connectedin_subtopology)\n\nlemma connectedin_Union:\n  assumes \\<U>: \"\\<And>S. S \\<in> \\<U> \\<Longrightarrow> connectedin X S\" and ne: \"\\<Inter>\\<U> \\<noteq> {}\"\n  shows \"connectedin X (\\<Union>\\<U>)\"\nproof -\n  have \"\\<Union>\\<U> \\<subseteq> topspace X\"\n    using \\<U> by (simp add: Union_least connectedin_def)\n  moreover have False\n    if \"openin X E1\" \"openin X E2\" and cover: \"\\<Union>\\<U> \\<subseteq> E1 \\<union> E2\" and disj: \"E1 \\<inter> E2 \\<inter> \\<Union>\\<U> = {}\"\n       and overlap1: \"E1 \\<inter> \\<Union>\\<U> \\<noteq> {}\" and overlap2: \"E2 \\<inter> \\<Union>\\<U> \\<noteq> {}\"\n      for E1 E2\n  proof -\n    have disjS: \"E1 \\<inter> E2 \\<inter> S = {}\" if \"S \\<in> \\<U>\" for S\n      using Diff_triv that disj by auto\n    have coverS: \"S \\<subseteq> E1 \\<union> E2\" if \"S \\<in> \\<U>\" for S\n      using that cover by blast\n    have \"\\<U> \\<noteq> {}\"\n      using overlap1 by blast\n    obtain a where a: \"\\<And>U. U \\<in> \\<U> \\<Longrightarrow> a \\<in> U\"\n      using ne by force\n    with \\<open>\\<U> \\<noteq> {}\\<close> have \"a \\<in> \\<Union>\\<U>\"\n      by blast\n    then consider \"a \\<in> E1\" | \"a \\<in> E2\"\n      using \\<open>\\<Union>\\<U> \\<subseteq> E1 \\<union> E2\\<close> by auto\n    then show False\n    proof cases\n      case 1\n      then obtain b S where \"b \\<in> E2\" \"b \\<in> S\" \"S \\<in> \\<U>\"\n        using overlap2 by blast\n      then show ?thesis\n        using \"1\" \\<open>openin X E1\\<close> \\<open>openin X E2\\<close> disjS coverS a [OF \\<open>S \\<in> \\<U>\\<close>]  \\<U>[OF \\<open>S \\<in> \\<U>\\<close>]\n        unfolding connectedin\n        by (meson disjoint_iff_not_equal)\n    next\n      case 2\n      then obtain b S where \"b \\<in> E1\" \"b \\<in> S\" \"S \\<in> \\<U>\"\n        using overlap1 by blast\n      then show ?thesis\n        using \"2\" \\<open>openin X E1\\<close> \\<open>openin X E2\\<close> disjS coverS a [OF \\<open>S \\<in> \\<U>\\<close>]  \\<U>[OF \\<open>S \\<in> \\<U>\\<close>]\n        unfolding connectedin\n        by (meson disjoint_iff_not_equal)\n    qed\n  qed\n  ultimately show ?thesis\n    unfolding connectedin by blast\nqed\n\nlemma connectedin_Un:\n     \"\\<lbrakk>connectedin X S; connectedin X T; S \\<inter> T \\<noteq> {}\\<rbrakk> \\<Longrightarrow> connectedin X (S \\<union> T)\"\n  using connectedin_Union [of \"{S,T}\"] by auto\n\nlemma connected_space_subconnected:\n  \"connected_space X \\<longleftrightarrow> (\\<forall>x \\<in> topspace X. \\<forall>y \\<in> topspace X. \\<exists>S. connectedin X S \\<and> x \\<in> S \\<and> y \\<in> S)\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    using connectedin_topspace by blast\nnext\n  assume R [rule_format]: ?rhs\n  have False if \"openin X U\" \"openin X V\" and disj: \"U \\<inter> V = {}\" and cover: \"topspace X \\<subseteq> U \\<union> V\"\n    and \"U \\<noteq> {}\" \"V \\<noteq> {}\" for U V\n  proof -\n    obtain u v where \"u \\<in> U\" \"v \\<in> V\"\n      using \\<open>U \\<noteq> {}\\<close> \\<open>V \\<noteq> {}\\<close> by auto\n    then obtain T where \"u \\<in> T\" \"v \\<in> T\" and T: \"connectedin X T\"\n      using R [of u v] that\n      by (meson \\<open>openin X U\\<close> \\<open>openin X V\\<close> subsetD openin_subset)\n    then show False\n      using that unfolding connectedin\n      by (metis IntI \\<open>u \\<in> U\\<close> \\<open>v \\<in> V\\<close> empty_iff inf_bot_left subset_trans)\n  qed\n  then show ?lhs\n    by (auto simp: connected_space_def)\nqed\n\nlemma connectedin_intermediate_closure_of:\n  assumes \"connectedin X S\" \"S \\<subseteq> T\" \"T \\<subseteq> X closure_of S\"\n  shows \"connectedin X T\"\nproof -\n  have S: \"S \\<subseteq> topspace X\" and T: \"T \\<subseteq> topspace X\"\n    using assms by (meson closure_of_subset_topspace dual_order.trans)+\n  have \\<section>: \"\\<And>E1 E2. \\<lbrakk>openin X E1; openin X E2; E1 \\<inter> S = {} \\<or> E2 \\<inter> S = {}\\<rbrakk> \\<Longrightarrow> E1 \\<inter> T = {} \\<or> E2 \\<inter> T = {}\"\n    using assms unfolding disjoint_iff by (meson in_closure_of subsetD)\n  then show ?thesis\n    using assms\n    unfolding connectedin closure_of_subset_topspace S T\n    by (metis Int_empty_right T dual_order.trans inf.orderE inf_left_commute)\nqed\n\nlemma connectedin_closure_of:\n     \"connectedin X S \\<Longrightarrow> connectedin X (X closure_of S)\"\n  by (meson closure_of_subset connectedin_def connectedin_intermediate_closure_of subset_refl)\n\nlemma connectedin_separation:\n  \"connectedin X S \\<longleftrightarrow>\n        S \\<subseteq> topspace X \\<and>\n        (\\<nexists>C1 C2. C1 \\<union> C2 = S \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> C1 \\<inter> X closure_of C2 = {} \\<and> C2 \\<inter> X closure_of C1 = {})\" \n  unfolding connectedin_def connected_space_closedin_eq closedin_Int_closure_of topspace_subtopology\n  apply (intro conj_cong refl arg_cong [where f=Not])\n  apply (intro ex_cong1 iffI, blast)\n  using closure_of_subset_Int by force\n\nlemma connectedin_eq_not_separated:\n   \"connectedin X S \\<longleftrightarrow>\n         S \\<subseteq> topspace X \\<and>\n         (\\<nexists>C1 C2. C1 \\<union> C2 = S \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\n  unfolding separatedin_def by (metis connectedin_separation sup.boundedE)\n\nlemma connectedin_eq_not_separated_subset:\n  \"connectedin X S \\<longleftrightarrow>\n      S \\<subseteq> topspace X \\<and> (\\<nexists>C1 C2. S \\<subseteq> C1 \\<union> C2 \\<and> S \\<inter> C1 \\<noteq> {} \\<and> S \\<inter> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\nproof -\n  have \"\\<forall>C1 C2. S \\<subseteq> C1 \\<union> C2 \\<longrightarrow> S \\<inter> C1 = {} \\<or> S \\<inter> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n    if \"\\<And>C1 C2. C1 \\<union> C2 = S \\<longrightarrow> C1 = {} \\<or> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n  proof (intro allI)\n    fix C1 C2\n    show \"S \\<subseteq> C1 \\<union> C2 \\<longrightarrow> S \\<inter> C1 = {} \\<or> S \\<inter> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n      using that [of \"S \\<inter> C1\" \"S \\<inter> C2\"]\n      by (auto simp: separatedin_mono)\n  qed\n  then show ?thesis\n    by (metis Un_Int_eq(1) Un_Int_eq(2) connectedin_eq_not_separated order_refl)\nqed\n\nlemma connected_space_eq_not_separated:\n     \"connected_space X \\<longleftrightarrow>\n      (\\<nexists>C1 C2. C1 \\<union> C2 = topspace X \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\n  by (simp add: connectedin_eq_not_separated flip: connectedin_topspace)\n\nlemma connected_space_eq_not_separated_subset:\n  \"connected_space X \\<longleftrightarrow>\n    (\\<nexists>C1 C2. topspace X \\<subseteq> C1 \\<union> C2 \\<and> C1 \\<noteq> {} \\<and> C2 \\<noteq> {} \\<and> separatedin X C1 C2)\"\n  by (metis connected_space_eq_not_separated le_sup_iff separatedin_def subset_antisym)\n\nlemma connectedin_subset_separated_union:\n     \"\\<lbrakk>connectedin X C; separatedin X S T; C \\<subseteq> S \\<union> T\\<rbrakk> \\<Longrightarrow> C \\<subseteq> S \\<or> C \\<subseteq> T\"\n  unfolding connectedin_eq_not_separated_subset  by blast\n\nlemma connectedin_nonseparated_union:\n  assumes \"connectedin X S\" \"connectedin X T\" \"\\<not>separatedin X S T\"\n  shows \"connectedin X (S \\<union> T)\"\nproof -\n  have \"\\<And>C1 C2. \\<lbrakk>T \\<subseteq> C1 \\<union> C2; S \\<subseteq> C1 \\<union> C2\\<rbrakk> \\<Longrightarrow>\n           S \\<inter> C1 = {} \\<and> T \\<inter> C1 = {} \\<or> S \\<inter> C2 = {} \\<and> T \\<inter> C2 = {} \\<or> \\<not> separatedin X C1 C2\"\n    using assms\n    unfolding connectedin_eq_not_separated_subset\n    by (metis (no_types, lifting) assms connectedin_subset_separated_union inf.orderE separatedin_empty(1) separatedin_mono separatedin_sym)\n  then show ?thesis\n    unfolding connectedin_eq_not_separated_subset\n    by (simp add: assms connectedin_subset_topspace Int_Un_distrib2)\nqed\n\nlemma connected_space_closures:\n     \"connected_space X \\<longleftrightarrow>\n        (\\<nexists>e1 e2. e1 \\<union> e2 = topspace X \\<and> X closure_of e1 \\<inter> X closure_of e2 = {} \\<and> e1 \\<noteq> {} \\<and> e2 \\<noteq> {})\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    unfolding connected_space_closedin_eq\n    by (metis Un_upper1 Un_upper2 closedin_closure_of closure_of_Un closure_of_eq_empty closure_of_topspace)\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding connected_space_closedin_eq\n    by (metis closure_of_eq)\nqed\n\nlemma connectedin_inter_frontier_of:\n  assumes \"connectedin X S\" \"S \\<inter> T \\<noteq> {}\" \"S - T \\<noteq> {}\"\n  shows \"S \\<inter> X frontier_of T \\<noteq> {}\"\nproof -\n  have \"S \\<subseteq> topspace X\" and *:\n    \"\\<And>E1 E2. openin X E1 \\<longrightarrow> openin X E2 \\<longrightarrow> E1 \\<inter> E2 \\<inter> S = {} \\<longrightarrow> S \\<subseteq> E1 \\<union> E2 \\<longrightarrow> E1 \\<inter> S = {} \\<or> E2 \\<inter> S = {}\"\n    using \\<open>connectedin X S\\<close> by (auto simp: connectedin)\n  moreover\n  have \"S - (topspace X \\<inter> T) \\<noteq> {}\"\n    using assms(3) by blast\n  moreover\n  have \"S \\<inter> topspace X \\<inter> T \\<noteq> {}\"\n    using assms connectedin by fastforce\n  moreover\n  have False if \"S \\<inter> T \\<noteq> {}\" \"S - T \\<noteq> {}\" \"T \\<subseteq> topspace X\" \"S \\<inter> X frontier_of T = {}\" for T\n  proof -\n    have null: \"S \\<inter> (X closure_of T - X interior_of T) = {}\"\n      using that unfolding frontier_of_def by blast\n    have \"X interior_of T \\<inter> (topspace X - X closure_of T) \\<inter> S = {}\"\n      by (metis Diff_disjoint inf_bot_left interior_of_Int interior_of_complement interior_of_empty)\n    moreover have \"S \\<subseteq> X interior_of T \\<union> (topspace X - X closure_of T)\"\n      using that \\<open>S \\<subseteq> topspace X\\<close> null by auto\n    moreover have \"S \\<inter> X interior_of T \\<noteq> {}\"\n      using closure_of_subset that(1) that(3) null by fastforce\n    ultimately have \"S \\<inter> X interior_of (topspace X - T) = {}\"\n      by (metis \"*\" inf_commute interior_of_complement openin_interior_of)\n    then have \"topspace (subtopology X S) \\<inter> X interior_of T = S\"\n      using \\<open>S \\<subseteq> topspace X\\<close> interior_of_complement null by fastforce\n    then show ?thesis\n      using that by (metis Diff_eq_empty_iff inf_le2 interior_of_subset subset_trans)\n  qed\n  ultimately show ?thesis\n    by (metis Int_lower1 frontier_of_restrict inf_assoc)\nqed\n\nlemma connectedin_continuous_map_image:\n  assumes f: \"continuous_map X Y f\" and \"connectedin X S\"\n  shows \"connectedin Y (f ` S)\"\nproof -\n  have \"S \\<subseteq> topspace X\" and *:\n    \"\\<And>E1 E2. openin X E1 \\<longrightarrow> openin X E2 \\<longrightarrow> E1 \\<inter> E2 \\<inter> S = {} \\<longrightarrow> S \\<subseteq> E1 \\<union> E2 \\<longrightarrow> E1 \\<inter> S = {} \\<or> E2 \\<inter> S = {}\"\n    using \\<open>connectedin X S\\<close> by (auto simp: connectedin)\n  show ?thesis\n    unfolding connectedin connected_space_def\n  proof (intro conjI notI; clarify)\n    show \"f x \\<in> topspace Y\" if  \"x \\<in> S\" for x\n      using \\<open>S \\<subseteq> topspace X\\<close> continuous_map_image_subset_topspace f that by blast\n  next\n    fix U V\n    let ?U = \"{x \\<in> topspace X. f x \\<in> U}\"\n    let ?V = \"{x \\<in> topspace X. f x \\<in> V}\"\n    assume UV: \"openin Y U\" \"openin Y V\" \"f ` S \\<subseteq> U \\<union> V\" \"U \\<inter> V \\<inter> f ` S = {}\" \"U \\<inter> f ` S \\<noteq> {}\" \"V \\<inter> f ` S \\<noteq> {}\"\n    then have 1: \"?U \\<inter> ?V \\<inter> S = {}\"\n      by auto\n    have 2: \"openin X ?U\" \"openin X ?V\"\n      using \\<open>openin Y U\\<close> \\<open>openin Y V\\<close> continuous_map f by fastforce+\n    show \"False\"\n      using * [of ?U ?V] UV \\<open>S \\<subseteq> topspace X\\<close>\n      by (auto simp: 1 2)\n  qed\nqed\n\nlemma homeomorphic_connected_space:\n     \"X homeomorphic_space Y \\<Longrightarrow> connected_space X \\<longleftrightarrow> connected_space Y\"\n  unfolding homeomorphic_space_def homeomorphic_maps_def\n  by (metis connected_space_subconnected connectedin_continuous_map_image connectedin_topspace continuous_map_image_subset_topspace image_eqI image_subset_iff)\n\nlemma homeomorphic_map_connectedness:\n  assumes f: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"connectedin Y (f ` U) \\<longleftrightarrow> connectedin X U\"\nproof -\n  have 1: \"f ` U \\<subseteq> topspace Y \\<longleftrightarrow> U \\<subseteq> topspace X\"\n    using U f homeomorphic_imp_surjective_map by blast\n  moreover have \"connected_space (subtopology Y (f ` U)) \\<longleftrightarrow> connected_space (subtopology X U)\"\n  proof (rule homeomorphic_connected_space)\n    have \"f ` U \\<subseteq> topspace Y\"\n      by (simp add: U 1)\n    then have \"topspace Y \\<inter> f ` U = f ` U\"\n      by (simp add: subset_antisym)\n    then show \"subtopology Y (f ` U) homeomorphic_space subtopology X U\"\n      by (metis U f homeomorphic_map_imp_homeomorphic_space homeomorphic_map_subtopologies homeomorphic_space_sym inf.absorb_iff2)\n  qed\n  ultimately show ?thesis\n    by (auto simp: connectedin_def)\nqed\n\nlemma homeomorphic_map_connectedness_eq:\n   \"homeomorphic_map X Y f\n        \\<Longrightarrow> connectedin X U \\<longleftrightarrow>\n             U \\<subseteq> topspace X \\<and> connectedin Y (f ` U)\"\n  using homeomorphic_map_connectedness connectedin_subset_topspace by metis\n\nlemma connectedin_discrete_topology:\n   \"connectedin (discrete_topology U) S \\<longleftrightarrow> S \\<subseteq> U \\<and> (\\<exists>a. S \\<subseteq> {a})\"\nproof (cases \"S \\<subseteq> U\")\n  case True\n  show ?thesis\n  proof (cases \"S = {}\")\n    case False\n    moreover have \"connectedin (discrete_topology U) S \\<longleftrightarrow> (\\<exists>a. S = {a})\"\n    proof\n      show \"connectedin (discrete_topology U) S \\<Longrightarrow> \\<exists>a. S = {a}\"\n        using False connectedin_inter_frontier_of insert_Diff by fastforce\n    qed (use True in auto)\n    ultimately show ?thesis\n      by auto\n  qed simp\nnext\n  case False\n  then show ?thesis\n    by (simp add: connectedin_def)\nqed\n\nlemma connected_space_discrete_topology:\n     \"connected_space (discrete_topology U) \\<longleftrightarrow> (\\<exists>a. U \\<subseteq> {a})\"\n  by (metis connectedin_discrete_topology connectedin_topspace order_refl topspace_discrete_topology)\n\n\nsubsection\\<open>Compact sets\\<close>\n\ndefinition compactin where\n \"compactin X S \\<longleftrightarrow>\n     S \\<subseteq> topspace X \\<and>\n     (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> S \\<subseteq> \\<Union>\\<U>\n          \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>))\"\n\ndefinition compact_space where\n   \"compact_space X \\<equiv> compactin X (topspace X)\"\n\nlemma compact_space_alt:\n   \"compact_space X \\<longleftrightarrow>\n        (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> topspace X \\<subseteq> \\<Union>\\<U>\n            \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> topspace X \\<subseteq> \\<Union>\\<F>))\"\n  by (simp add: compact_space_def compactin_def)\n\nlemma compact_space:\n   \"compact_space X \\<longleftrightarrow>\n        (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> \\<Union>\\<U> = topspace X\n            \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> \\<Union>\\<F> = topspace X))\"\n  unfolding compact_space_alt\n  using openin_subset by fastforce\n\nlemma compactinD:\n  \"\\<lbrakk>compactin X S; \\<And>U. U \\<in> \\<U> \\<Longrightarrow> openin X U; S \\<subseteq> \\<Union>\\<U>\\<rbrakk> \\<Longrightarrow> \\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>\"\n  by (auto simp: compactin_def)\n\nlemma compactin_euclidean_iff [simp]: \"compactin euclidean S \\<longleftrightarrow> compact S\"\n  by (simp add: compact_eq_Heine_Borel compactin_def) meson\n\nlemma compactin_absolute [simp]:\n   \"compactin (subtopology X S) S \\<longleftrightarrow> compactin X S\"\nproof -\n  have eq: \"(\\<forall>U \\<in> \\<U>. \\<exists>Y. openin X Y \\<and> U = Y \\<inter> S) \\<longleftrightarrow> \\<U> \\<subseteq> (\\<lambda>Y. Y \\<inter> S) ` {y. openin X y}\" for \\<U>\n    by auto\n  show ?thesis\n    by (auto simp: compactin_def openin_subtopology eq imp_conjL all_subset_image ex_finite_subset_image)\nqed\n\nlemma compactin_subspace: \"compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> compact_space (subtopology X S)\"\n  unfolding compact_space_def topspace_subtopology\n  by (metis compactin_absolute compactin_def inf.absorb2)\n\nlemma compact_space_subtopology: \"compactin X S \\<Longrightarrow> compact_space (subtopology X S)\"\n  by (simp add: compactin_subspace)\n\nlemma compactin_subtopology: \"compactin (subtopology X S) T \\<longleftrightarrow> compactin X T \\<and> T \\<subseteq> S\"\n  by (metis compactin_subspace inf.absorb_iff2 le_inf_iff subtopology_subtopology topspace_subtopology)\n\nlemma compactin_subset_topspace: \"compactin X S \\<Longrightarrow> S \\<subseteq> topspace X\"\n  by (simp add: compactin_subspace)\n\nlemma compactin_contractive:\n   \"\\<lbrakk>compactin X' S; topspace X' = topspace X;\n     \\<And>U. openin X U \\<Longrightarrow> openin X' U\\<rbrakk> \\<Longrightarrow> compactin X S\"\n  by (simp add: compactin_def)\n\nlemma finite_imp_compactin:\n   \"\\<lbrakk>S \\<subseteq> topspace X; finite S\\<rbrakk> \\<Longrightarrow> compactin X S\"\n  by (metis compactin_subspace compact_space finite_UnionD inf.absorb_iff2 order_refl topspace_subtopology)\n\nlemma compactin_empty [iff]: \"compactin X {}\"\n  by (simp add: finite_imp_compactin)\n\nlemma compact_space_topspace_empty:\n   \"topspace X = {} \\<Longrightarrow> compact_space X\"\n  by (simp add: compact_space_def)\n\nlemma finite_imp_compactin_eq:\n   \"finite S \\<Longrightarrow> (compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X)\"\n  using compactin_subset_topspace finite_imp_compactin by blast\n\nlemma compactin_sing [simp]: \"compactin X {a} \\<longleftrightarrow> a \\<in> topspace X\"\n  by (simp add: finite_imp_compactin_eq)\n\nlemma closed_compactin:\n  assumes XK: \"compactin X K\" and \"C \\<subseteq> K\" and XC: \"closedin X C\"\n  shows \"compactin X C\"\n  unfolding compactin_def\nproof (intro conjI allI impI)\n  show \"C \\<subseteq> topspace X\"\n    by (simp add: XC closedin_subset)\nnext\n  fix \\<U> :: \"'a set set\"\n  assume \\<U>: \"Ball \\<U> (openin X) \\<and> C \\<subseteq> \\<Union>\\<U>\"\n  have \"(\\<forall>U\\<in>insert (topspace X - C) \\<U>. openin X U)\"\n    using XC \\<U> by blast\n  moreover have \"K \\<subseteq> \\<Union>(insert (topspace X - C) \\<U>)\"\n    using \\<U> XK compactin_subset_topspace by fastforce\n  ultimately obtain \\<F> where \"finite \\<F>\" \"\\<F> \\<subseteq> insert (topspace X - C) \\<U>\" \"K \\<subseteq> \\<Union>\\<F>\"\n    using assms unfolding compactin_def by metis\n  moreover have \"openin X (topspace X - C)\"\n    using XC by auto\n  ultimately show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> C \\<subseteq> \\<Union>\\<F>\"\n    using \\<open>C \\<subseteq> K\\<close>\n    by (rule_tac x=\"\\<F> - {topspace X - C}\" in exI) auto\nqed\n\nlemma closedin_compact_space:\n   \"\\<lbrakk>compact_space X; closedin X S\\<rbrakk> \\<Longrightarrow> compactin X S\"\n  by (simp add: closed_compactin closedin_subset compact_space_def)\n\nlemma compact_Int_closedin:\n  assumes \"compactin X S\" \"closedin X T\" shows \"compactin X (S \\<inter> T)\"\nproof -\n  have \"compactin (subtopology X S) (S \\<inter> T)\"\n    by (metis assms closedin_compact_space closedin_subtopology compactin_subspace inf_commute)\n  then show ?thesis\n    by (simp add: compactin_subtopology)\nqed\n\nlemma closed_Int_compactin: \"\\<lbrakk>closedin X S; compactin X T\\<rbrakk> \\<Longrightarrow> compactin X (S \\<inter> T)\"\n  by (metis compact_Int_closedin inf_commute)\n\nlemma compactin_Un:\n  assumes S: \"compactin X S\" and T: \"compactin X T\" shows \"compactin X (S \\<union> T)\"\n  unfolding compactin_def\nproof (intro conjI allI impI)\n  show \"S \\<union> T \\<subseteq> topspace X\"\n    using assms by (auto simp: compactin_def)\nnext\n  fix \\<U> :: \"'a set set\"\n  assume \\<U>: \"Ball \\<U> (openin X) \\<and> S \\<union> T \\<subseteq> \\<Union>\\<U>\"\n  with S obtain \\<F> where \\<V>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<U>\" \"S \\<subseteq> \\<Union>\\<F>\"\n    unfolding compactin_def by (meson sup.bounded_iff)\n  obtain \\<W> where \"finite \\<W>\" \"\\<W> \\<subseteq> \\<U>\" \"T \\<subseteq> \\<Union>\\<W>\"\n    using \\<U> T\n    unfolding compactin_def by (meson sup.bounded_iff)\n  with \\<V> show \"\\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> S \\<union> T \\<subseteq> \\<Union>\\<V>\"\n    by (rule_tac x=\"\\<F> \\<union> \\<W>\" in exI) auto\nqed\n\nlemma compactin_Union:\n   \"\\<lbrakk>finite \\<F>; \\<And>S. S \\<in> \\<F> \\<Longrightarrow> compactin X S\\<rbrakk> \\<Longrightarrow> compactin X (\\<Union>\\<F>)\"\nby (induction rule: finite_induct) (simp_all add: compactin_Un)\n\nlemma compactin_subtopology_imp_compact:\n  assumes \"compactin (subtopology X S) K\" shows \"compactin X K\"\n  using assms\nproof (clarsimp simp add: compactin_def)\n  fix \\<U>\n  define \\<V> where \"\\<V> \\<equiv> (\\<lambda>U. U \\<inter> S) ` \\<U>\"\n  assume \"K \\<subseteq> topspace X\" and \"K \\<subseteq> S\" and \"\\<forall>x\\<in>\\<U>. openin X x\" and \"K \\<subseteq> \\<Union>\\<U>\"\n  then have \"\\<forall>V \\<in> \\<V>. openin (subtopology X S) V\" \"K \\<subseteq> \\<Union>\\<V>\"\n    unfolding \\<V>_def by (auto simp: openin_subtopology)\n  moreover\n  assume \"\\<forall>\\<U>. (\\<forall>x\\<in>\\<U>. openin (subtopology X S) x) \\<and> K \\<subseteq> \\<Union>\\<U> \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>)\"\n  ultimately obtain \\<F> where \"finite \\<F>\" \"\\<F> \\<subseteq> \\<V>\" \"K \\<subseteq> \\<Union>\\<F>\"\n    by meson\n  then have \\<F>: \"\\<exists>U. U \\<in> \\<U> \\<and> V = U \\<inter> S\" if \"V \\<in> \\<F>\" for V\n    unfolding \\<V>_def using that by blast\n  let ?\\<F> = \"(\\<lambda>F. @U. U \\<in> \\<U> \\<and> F = U \\<inter> S) ` \\<F>\"\n  show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>\"\n  proof (intro exI conjI)\n    show \"finite ?\\<F>\"\n      using \\<open>finite \\<F>\\<close> by blast\n    show \"?\\<F> \\<subseteq> \\<U>\"\n      using someI_ex [OF \\<F>] by blast\n    show \"K \\<subseteq> \\<Union>?\\<F>\"\n    proof clarsimp\n      fix x\n      assume \"x \\<in> K\"\n      then show \"\\<exists>V \\<in> \\<F>. x \\<in> (SOME U. U \\<in> \\<U> \\<and> V = U \\<inter> S)\"\n        using \\<open>K \\<subseteq> \\<Union>\\<F>\\<close> someI_ex [OF \\<F>]\n        by (metis (no_types, lifting) IntD1 Union_iff subsetCE)\n    qed\n  qed\nqed\n\nlemma compact_imp_compactin_subtopology:\n  assumes \"compactin X K\" \"K \\<subseteq> S\" shows \"compactin (subtopology X S) K\"\n  using assms\nproof (clarsimp simp add: compactin_def)\n  fix \\<U> :: \"'a set set\"\n  define \\<V> where \"\\<V> \\<equiv> {V. openin X V \\<and> (\\<exists>U \\<in> \\<U>. U = V \\<inter> S)}\"\n  assume \"K \\<subseteq> S\" and \"K \\<subseteq> topspace X\" and \"\\<forall>U\\<in>\\<U>. openin (subtopology X S) U\" and \"K \\<subseteq> \\<Union>\\<U>\"\n  then have \"\\<forall>V \\<in> \\<V>. openin X V\" \"K \\<subseteq> \\<Union>\\<V>\"\n    unfolding \\<V>_def by (fastforce simp: subset_eq openin_subtopology)+\n  moreover\n  assume \"\\<forall>\\<U>. (\\<forall>U\\<in>\\<U>. openin X U) \\<and> K \\<subseteq> \\<Union>\\<U> \\<longrightarrow> (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>)\"\n  ultimately obtain \\<F> where \"finite \\<F>\" \"\\<F> \\<subseteq> \\<V>\" \"K \\<subseteq> \\<Union>\\<F>\"\n    by meson\n  let ?\\<F> = \"(\\<lambda>F. F \\<inter> S) ` \\<F>\"\n  show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> K \\<subseteq> \\<Union>\\<F>\"\n  proof (intro exI conjI)\n    show \"finite ?\\<F>\"\n      using \\<open>finite \\<F>\\<close> by blast\n    show \"?\\<F> \\<subseteq> \\<U>\"\n      using \\<V>_def \\<open>\\<F> \\<subseteq> \\<V>\\<close> by blast\n    show \"K \\<subseteq> \\<Union>?\\<F>\"\n      using \\<open>K \\<subseteq> \\<Union>\\<F>\\<close> assms(2) by auto\n  qed\nqed\n\n\nproposition compact_space_fip:\n   \"compact_space X \\<longleftrightarrow>\n    (\\<forall>\\<U>. (\\<forall>C\\<in>\\<U>. closedin X C) \\<and> (\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> \\<Inter>\\<U> \\<noteq> {})\"\n   (is \"_ = ?rhs\")\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    unfolding compact_space_def\n    by (metis Sup_bot_conv(1) closedin_topspace_empty compactin_empty finite.emptyI finite_UnionD order_refl)\nnext\n  case False\n  show ?thesis\n  proof safe\n    fix \\<U> :: \"'a set set\"\n    assume * [rule_format]: \"\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}\"\n    define \\<V> where \"\\<V> \\<equiv> (\\<lambda>S. topspace X - S) ` \\<U>\"\n    assume clo: \"\\<forall>C\\<in>\\<U>. closedin X C\" and [simp]: \"\\<Inter>\\<U> = {}\"\n    then have \"\\<forall>V \\<in> \\<V>. openin X V\" \"topspace X \\<subseteq> \\<Union>\\<V>\"\n      by (auto simp: \\<V>_def)\n    moreover assume [unfolded compact_space_alt, rule_format, of \\<V>]: \"compact_space X\"\n    ultimately obtain \\<F> where \\<F>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<U>\" \"topspace X \\<subseteq> topspace X - \\<Inter>\\<F>\"\n      by (auto simp: ex_finite_subset_image \\<V>_def)\n    moreover have \"\\<F> \\<noteq> {}\"\n      using \\<F> \\<open>topspace X \\<noteq> {}\\<close> by blast\n    ultimately show \"False\"\n      using * [of \\<F>]\n      by auto (metis Diff_iff Inter_iff clo closedin_def subsetD)\n  next\n    assume R [rule_format]: ?rhs\n    show \"compact_space X\"\n      unfolding compact_space_alt\n    proof clarify\n      fix \\<U> :: \"'a set set\"\n      define \\<V> where \"\\<V> \\<equiv> (\\<lambda>S. topspace X - S) ` \\<U>\"\n      assume \"\\<forall>C\\<in>\\<U>. openin X C\" and \"topspace X \\<subseteq> \\<Union>\\<U>\"\n      with \\<open>topspace X \\<noteq> {}\\<close> have *: \"\\<forall>V \\<in> \\<V>. closedin X V\" \"\\<U> \\<noteq> {}\"\n        by (auto simp: \\<V>_def)\n      show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> topspace X \\<subseteq> \\<Union>\\<F>\"\n      proof (rule ccontr; simp)\n        assume \"\\<forall>\\<F>\\<subseteq>\\<U>. finite \\<F> \\<longrightarrow> \\<not> topspace X \\<subseteq> \\<Union>\\<F>\"\n        then have \"\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<V> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}\"\n          by (simp add: \\<V>_def all_finite_subset_image)\n        with \\<open>topspace X \\<subseteq> \\<Union>\\<U>\\<close> show False\n          using R [of \\<V>] * by (simp add: \\<V>_def)\n      qed\n    qed\n  qed\nqed\n\ncorollary compactin_fip:\n  \"compactin X S \\<longleftrightarrow>\n    S \\<subseteq> topspace X \\<and>\n    (\\<forall>\\<U>. (\\<forall>C\\<in>\\<U>. closedin X C) \\<and> (\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> S \\<inter> \\<Inter>\\<U> \\<noteq> {})\"\nproof (cases \"S = {}\")\n  case False\n  show ?thesis\n  proof (cases \"S \\<subseteq> topspace X\")\n    case True\n    then have \"compactin X S \\<longleftrightarrow>\n          (\\<forall>\\<U>. \\<U> \\<subseteq> (\\<lambda>T. S \\<inter> T) ` {T. closedin X T} \\<longrightarrow>\n           (\\<forall>\\<F>. finite \\<F> \\<longrightarrow> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> \\<Inter>\\<U> \\<noteq> {})\"\n      by (simp add: compact_space_fip compactin_subspace closedin_subtopology image_def subset_eq Int_commute imp_conjL)\n    also have \"\\<dots> = (\\<forall>\\<U>\\<subseteq>Collect (closedin X). (\\<forall>\\<F>. finite \\<F> \\<longrightarrow> \\<F> \\<subseteq> (\\<inter>) S ` \\<U> \\<longrightarrow> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> \\<Inter> ((\\<inter>) S ` \\<U>) \\<noteq> {})\"\n      by (simp add: all_subset_image)\n    also have \"\\<dots> = (\\<forall>\\<U>. (\\<forall>C\\<in>\\<U>. closedin X C) \\<and> (\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> S \\<inter> \\<Inter>\\<U> \\<noteq> {})\"\n    proof -\n      have eq: \"((\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> \\<Inter> ((\\<inter>) S ` \\<F>) \\<noteq> {}) \\<longrightarrow> \\<Inter> ((\\<inter>) S ` \\<U>) \\<noteq> {}) \\<longleftrightarrow>\n                ((\\<forall>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<longrightarrow> S \\<inter> \\<Inter>\\<F> \\<noteq> {}) \\<longrightarrow> S \\<inter> \\<Inter>\\<U> \\<noteq> {})\"  for \\<U>\n        by simp (use \\<open>S \\<noteq> {}\\<close> in blast)\n      show ?thesis\n        unfolding imp_conjL [symmetric] all_finite_subset_image eq by blast\n    qed\n    finally show ?thesis\n      using True by simp\n  qed (simp add: compactin_subspace)\nqed force\n\ncorollary compact_space_imp_nest:\n  fixes C :: \"nat \\<Rightarrow> 'a set\"\n  assumes \"compact_space X\" and clo: \"\\<And>n. closedin X (C n)\"\n    and ne: \"\\<And>n. C n \\<noteq> {}\" and inc: \"\\<And>m n. m \\<le> n \\<Longrightarrow> C n \\<subseteq> C m\"\n  shows \"(\\<Inter>n. C n) \\<noteq> {}\"\nproof -\n  let ?\\<U> = \"range (\\<lambda>n. \\<Inter>m \\<le> n. C m)\"\n  have \"closedin X A\" if \"A \\<in> ?\\<U>\" for A\n    using that clo by auto\n  moreover have \"(\\<Inter>n\\<in>K. \\<Inter>m \\<le> n. C m) \\<noteq> {}\" if \"finite K\" for K\n  proof -\n    obtain n where \"\\<And>k. k \\<in> K \\<Longrightarrow> k \\<le> n\"\n      using Max.coboundedI \\<open>finite K\\<close> by blast\n    with inc have \"C n \\<subseteq> (\\<Inter>n\\<in>K. \\<Inter>m \\<le> n. C m)\"\n    by blast\n  with ne [of n] show ?thesis\n    by blast\n  qed\n  ultimately show ?thesis\n    using \\<open>compact_space X\\<close> [unfolded compact_space_fip, rule_format, of ?\\<U>]\n    by (simp add: all_finite_subset_image INT_extend_simps UN_atMost_UNIV del: INT_simps)\nqed\n\nlemma compactin_discrete_topology:\n   \"compactin (discrete_topology X) S \\<longleftrightarrow> S \\<subseteq> X \\<and> finite S\" (is \"?lhs = ?rhs\")\nproof (intro iffI conjI)\n  assume L: ?lhs\n  then show \"S \\<subseteq> X\"\n    by (auto simp: compactin_def)\n  have *: \"\\<And>\\<U>. Ball \\<U> (openin (discrete_topology X)) \\<and> S \\<subseteq> \\<Union>\\<U> \\<Longrightarrow>\n        (\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>)\"\n    using L by (auto simp: compactin_def)\n  show \"finite S\"\n    using * [of \"(\\<lambda>x. {x}) ` X\"] \\<open>S \\<subseteq> X\\<close>\n    by clarsimp (metis UN_singleton finite_subset_image infinite_super)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (simp add: finite_imp_compactin)\nqed\n\nlemma compact_space_discrete_topology: \"compact_space(discrete_topology X) \\<longleftrightarrow> finite X\"\n  by (simp add: compactin_discrete_topology compact_space_def)\n\nlemma compact_space_imp_Bolzano_Weierstrass:\n  assumes \"compact_space X\" \"infinite S\" \"S \\<subseteq> topspace X\"\n  shows \"X derived_set_of S \\<noteq> {}\"\nproof\n  assume X: \"X derived_set_of S = {}\"\n  then have \"closedin X S\"\n    by (simp add: closedin_contains_derived_set assms)\n  then have \"compactin X S\"\n    by (rule closedin_compact_space [OF \\<open>compact_space X\\<close>])\n  with X show False\n    by (metis \\<open>infinite S\\<close> compactin_subspace compact_space_discrete_topology inf_bot_right subtopology_eq_discrete_topology_eq)\nqed\n\nlemma compactin_imp_Bolzano_Weierstrass:\n   \"\\<lbrakk>compactin X S; infinite T \\<and> T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> S \\<inter> X derived_set_of T \\<noteq> {}\"\n  using compact_space_imp_Bolzano_Weierstrass [of \"subtopology X S\"]\n  by (simp add: compactin_subspace derived_set_of_subtopology inf_absorb2)\n\nlemma compact_closure_of_imp_Bolzano_Weierstrass:\n   \"\\<lbrakk>compactin X (X closure_of S); infinite T; T \\<subseteq> S; T \\<subseteq> topspace X\\<rbrakk> \\<Longrightarrow> X derived_set_of T \\<noteq> {}\"\n  using closure_of_mono closure_of_subset compactin_imp_Bolzano_Weierstrass by fastforce\n\nlemma discrete_compactin_eq_finite:\n   \"S \\<inter> X derived_set_of S = {} \\<Longrightarrow> compactin X S \\<longleftrightarrow> S \\<subseteq> topspace X \\<and> finite S\"\n  by (meson compactin_imp_Bolzano_Weierstrass finite_imp_compactin_eq order_refl)\n\nlemma discrete_compact_space_eq_finite:\n   \"X derived_set_of (topspace X) = {} \\<Longrightarrow> (compact_space X \\<longleftrightarrow> finite(topspace X))\"\n  by (metis compact_space_discrete_topology discrete_topology_unique_derived_set)\n\nlemma image_compactin:\n  assumes cpt: \"compactin X S\" and cont: \"continuous_map X Y f\"\n  shows \"compactin Y (f ` S)\"\n  unfolding compactin_def\nproof (intro conjI allI impI)\n  show \"f ` S \\<subseteq> topspace Y\"\n    using compactin_subset_topspace cont continuous_map_image_subset_topspace cpt by blast\nnext\n  fix \\<U> :: \"'b set set\"\n  assume \\<U>: \"Ball \\<U> (openin Y) \\<and> f ` S \\<subseteq> \\<Union>\\<U>\"\n  define \\<V> where \"\\<V> \\<equiv> (\\<lambda>U. {x \\<in> topspace X. f x \\<in> U}) ` \\<U>\"\n  have \"S \\<subseteq> topspace X\"\n    and *: \"\\<And>\\<U>. \\<lbrakk>\\<forall>U\\<in>\\<U>. openin X U; S \\<subseteq> \\<Union>\\<U>\\<rbrakk> \\<Longrightarrow> \\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>\\<F>\"\n    using cpt by (auto simp: compactin_def)\n  obtain \\<F> where \\<F>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<V>\" \"S \\<subseteq> \\<Union>\\<F>\"\n  proof -\n    have 1: \"\\<forall>U\\<in>\\<V>. openin X U\"\n      unfolding \\<V>_def using \\<U> cont[unfolded continuous_map] by blast\n    have 2: \"S \\<subseteq> \\<Union>\\<V>\"\n      unfolding \\<V>_def using compactin_subset_topspace cpt \\<U> by fastforce\n    show thesis\n      using * [OF 1 2] that by metis\n  qed\n  have \"\\<forall>v \\<in> \\<V>. \\<exists>U. U \\<in> \\<U> \\<and> v = {x \\<in> topspace X. f x \\<in> U}\"\n    using \\<V>_def by blast\n  then obtain U where U: \"\\<forall>v \\<in> \\<V>. U v \\<in> \\<U> \\<and> v = {x \\<in> topspace X. f x \\<in> U v}\"\n    by metis\n  show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> f ` S \\<subseteq> \\<Union>\\<F>\"\n  proof (intro conjI exI)\n    show \"finite (U ` \\<F>)\"\n      by (simp add: \\<open>finite \\<F>\\<close>)\n  next\n    show \"U ` \\<F> \\<subseteq> \\<U>\"\n      using \\<open>\\<F> \\<subseteq> \\<V>\\<close> U by auto\n  next\n    show \"f ` S \\<subseteq> \\<Union> (U ` \\<F>)\"\n      using \\<F>(2-3) U UnionE subset_eq U by fastforce\n  qed\nqed\n\n\nlemma homeomorphic_compact_space:\n  assumes \"X homeomorphic_space Y\"\n  shows \"compact_space X \\<longleftrightarrow> compact_space Y\"\n    using homeomorphic_space_sym\n    by (metis assms compact_space_def homeomorphic_eq_everything_map homeomorphic_space image_compactin)\n\nlemma homeomorphic_map_compactness:\n  assumes hom: \"homeomorphic_map X Y f\" and U: \"U \\<subseteq> topspace X\"\n  shows \"compactin Y (f ` U) \\<longleftrightarrow> compactin X U\"\nproof -\n  have \"f ` U \\<subseteq> topspace Y\"\n    using hom U homeomorphic_imp_surjective_map by blast\n  moreover have \"homeomorphic_map (subtopology X U) (subtopology Y (f ` U)) f\"\n    using U hom homeomorphic_imp_surjective_map by (blast intro: homeomorphic_map_subtopologies)\n  then have \"compact_space (subtopology Y (f ` U)) = compact_space (subtopology X U)\"\n    using homeomorphic_compact_space homeomorphic_map_imp_homeomorphic_space by blast\n  ultimately show ?thesis\n    by (simp add: compactin_subspace U)\nqed\n\nlemma homeomorphic_map_compactness_eq:\n   \"homeomorphic_map X Y f\n        \\<Longrightarrow> compactin X U \\<longleftrightarrow> U \\<subseteq> topspace X \\<and> compactin Y (f ` U)\"\n  by (meson compactin_subset_topspace homeomorphic_map_compactness)\n\n\nsubsection\\<open>Embedding maps\\<close>\n\ndefinition embedding_map\n  where \"embedding_map X Y f \\<equiv> homeomorphic_map X (subtopology Y (f ` (topspace X))) f\"\n\nlemma embedding_map_eq:\n   \"\\<lbrakk>embedding_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> embedding_map X Y g\"\n  unfolding embedding_map_def\n  by (metis homeomorphic_map_eq image_cong)\n\nlemma embedding_map_compose:\n  assumes \"embedding_map X X' f\" \"embedding_map X' X'' g\"\n  shows \"embedding_map X X'' (g \\<circ> f)\"\nproof -\n  have hm: \"homeomorphic_map X (subtopology X' (f ` topspace X)) f\" \"homeomorphic_map X' (subtopology X'' (g ` topspace X')) g\"\n    using assms by (auto simp: embedding_map_def)\n  then obtain C where \"g ` topspace X' \\<inter> C = (g \\<circ> f) ` topspace X\"\n    by (metis homeomorphic_imp_surjective_map image_comp image_mono inf.absorb_iff2 topspace_subtopology)\n  then have \"homeomorphic_map (subtopology X' (f ` topspace X)) (subtopology X'' ((g \\<circ> f) ` topspace X)) g\"\n    by (metis hm homeomorphic_imp_surjective_map homeomorphic_map_subtopologies image_comp subtopology_subtopology topspace_subtopology)\n  then show ?thesis\n  unfolding embedding_map_def\n  using hm(1) homeomorphic_map_compose by blast\nqed\n\nlemma surjective_embedding_map:\n   \"embedding_map X Y f \\<and> f ` (topspace X) = topspace Y \\<longleftrightarrow> homeomorphic_map X Y f\"\n  by (force simp: embedding_map_def homeomorphic_eq_everything_map)\n\nlemma embedding_map_in_subtopology:\n   \"embedding_map X (subtopology Y S) f \\<longleftrightarrow> embedding_map X Y f \\<and> f ` (topspace X) \\<subseteq> S\"  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<Longrightarrow> ?rhs\"\n    unfolding embedding_map_def\n    by (metis continuous_map_in_subtopology homeomorphic_imp_continuous_map inf_absorb2 subtopology_subtopology)\nqed (simp add: embedding_map_def inf.absorb_iff2 subtopology_subtopology)\n\nlemma injective_open_imp_embedding_map:\n   \"\\<lbrakk>continuous_map X Y f; open_map X Y f; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> embedding_map X Y f\"\n  unfolding embedding_map_def\n  by (simp add: continuous_map_in_subtopology continuous_open_quotient_map eq_iff homeomorphic_map_def open_map_imp_subset open_map_into_subtopology)\n\nlemma injective_closed_imp_embedding_map:\n  \"\\<lbrakk>continuous_map X Y f; closed_map X Y f; inj_on f (topspace X)\\<rbrakk> \\<Longrightarrow> embedding_map X Y f\"\n  unfolding embedding_map_def\n  by (simp add: closed_map_imp_subset closed_map_into_subtopology continuous_closed_quotient_map \n                continuous_map_in_subtopology dual_order.eq_iff homeomorphic_map_def)\n\nlemma embedding_map_imp_homeomorphic_space:\n   \"embedding_map X Y f \\<Longrightarrow> X homeomorphic_space (subtopology Y (f ` (topspace X)))\"\n  unfolding embedding_map_def\n  using homeomorphic_space by blast\n\nlemma embedding_imp_closed_map:\n   \"\\<lbrakk>embedding_map X Y f; closedin Y (f ` topspace X)\\<rbrakk> \\<Longrightarrow> closed_map X Y f\"\n  unfolding closed_map_def\n  by (auto simp: closedin_closed_subtopology embedding_map_def homeomorphic_map_closedness_eq)\n\n\nsubsection\\<open>Retraction and section maps\\<close>\n\ndefinition retraction_maps :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"retraction_maps X Y f g \\<equiv>\n           continuous_map X Y f \\<and> continuous_map Y X g \\<and> (\\<forall>x \\<in> topspace Y. f(g x) = x)\"\n\ndefinition section_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"section_map X Y f \\<equiv> \\<exists>g. retraction_maps Y X g f\"\n\ndefinition retraction_map :: \"'a topology \\<Rightarrow> 'b topology \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"retraction_map X Y f \\<equiv> \\<exists>g. retraction_maps X Y f g\"\n\nlemma retraction_maps_eq:\n   \"\\<lbrakk>retraction_maps X Y f g; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = f' x; \\<And>x. x \\<in> topspace Y \\<Longrightarrow> g x = g' x\\<rbrakk>\n        \\<Longrightarrow> retraction_maps X Y f' g'\"\n  unfolding retraction_maps_def by (metis (no_types, lifting) continuous_map_def continuous_map_eq)\n\nlemma section_map_eq:\n   \"\\<lbrakk>section_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> section_map X Y g\"\n  unfolding section_map_def using retraction_maps_eq by blast\n\nlemma retraction_map_eq:\n   \"\\<lbrakk>retraction_map X Y f; \\<And>x. x \\<in> topspace X \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> retraction_map X Y g\"\n  unfolding retraction_map_def using retraction_maps_eq by blast\n\nlemma homeomorphic_imp_retraction_maps:\n   \"homeomorphic_maps X Y f g \\<Longrightarrow> retraction_maps X Y f g\"\n  by (simp add: homeomorphic_maps_def retraction_maps_def)\n\nlemma section_and_retraction_eq_homeomorphic_map:\n   \"section_map X Y f \\<and> retraction_map X Y f \\<longleftrightarrow> homeomorphic_map X Y f\"  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain g where \"homeomorphic_maps X Y f g\"\n    unfolding homeomorphic_maps_def retraction_map_def section_map_def\n    by (smt (verit, best) continuous_map_def retraction_maps_def)\n  then show ?rhs\n    using homeomorphic_map_maps by blast\nnext\n  assume ?rhs\n  then show ?lhs\n    unfolding retraction_map_def section_map_def\n    by (meson homeomorphic_imp_retraction_maps homeomorphic_map_maps homeomorphic_maps_sym)\nqed\n\nlemma section_imp_embedding_map:\n   \"section_map X Y f \\<Longrightarrow> embedding_map X Y f\"\n  unfolding section_map_def embedding_map_def homeomorphic_map_maps retraction_maps_def homeomorphic_maps_def\n  by (force simp: continuous_map_in_subtopology continuous_map_from_subtopology)\n\nlemma retraction_imp_quotient_map:\n  assumes \"retraction_map X Y f\"\n  shows \"quotient_map X Y f\"\n  unfolding quotient_map_def\nproof (intro conjI subsetI allI impI)\n  show \"f ` topspace X = topspace Y\"\n    using assms by (force simp: retraction_map_def retraction_maps_def continuous_map_def)\nnext\n  fix U\n  assume U: \"U \\<subseteq> topspace Y\"\n  have \"openin Y U\"\n    if \"\\<forall>x\\<in>topspace Y. g x \\<in> topspace X\" \"\\<forall>x\\<in>topspace Y. f (g x) = x\"\n       \"openin Y {x \\<in> topspace Y. g x \\<in> {x \\<in> topspace X. f x \\<in> U}}\" for g\n    using openin_subopen U that by fastforce\n  then show \"openin X {x \\<in> topspace X. f x \\<in> U} = openin Y U\"\n    using assms by (auto simp: retraction_map_def retraction_maps_def continuous_map_def)\nqed\n\nlemma retraction_maps_compose:\n   \"\\<lbrakk>retraction_maps X Y f f'; retraction_maps Y Z g g'\\<rbrakk> \\<Longrightarrow> retraction_maps X Z (g \\<circ> f) (f' \\<circ> g')\"\n  by (clarsimp simp: retraction_maps_def continuous_map_compose) (simp add: continuous_map_def)\n\nlemma retraction_map_compose:\n   \"\\<lbrakk>retraction_map X Y f; retraction_map Y Z g\\<rbrakk> \\<Longrightarrow> retraction_map X Z (g \\<circ> f)\"\n  by (meson retraction_map_def retraction_maps_compose)\n\nlemma section_map_compose:\n   \"\\<lbrakk>section_map X Y f; section_map Y Z g\\<rbrakk> \\<Longrightarrow> section_map X Z (g \\<circ> f)\"\n  by (meson retraction_maps_compose section_map_def)\n\nlemma surjective_section_eq_homeomorphic_map:\n   \"section_map X Y f \\<and> f ` (topspace X) = topspace Y \\<longleftrightarrow> homeomorphic_map X Y f\"\n  by (meson section_and_retraction_eq_homeomorphic_map section_imp_embedding_map surjective_embedding_map)\n\nlemma surjective_retraction_or_section_map:\n   \"f ` (topspace X) = topspace Y \\<Longrightarrow> retraction_map X Y f \\<or> section_map X Y f \\<longleftrightarrow> retraction_map X Y f\"\n  using section_and_retraction_eq_homeomorphic_map surjective_section_eq_homeomorphic_map by fastforce\n\nlemma retraction_imp_surjective_map:\n   \"retraction_map X Y f \\<Longrightarrow> f ` (topspace X) = topspace Y\"\n  by (simp add: retraction_imp_quotient_map quotient_imp_surjective_map)\n\nlemma section_imp_injective_map:\n   \"\\<lbrakk>section_map X Y f; x \\<in> topspace X; y \\<in> topspace X\\<rbrakk> \\<Longrightarrow> f x = f y \\<longleftrightarrow> x = y\"\n  by (metis (mono_tags, opaque_lifting) retraction_maps_def section_map_def)\n\nlemma retraction_maps_to_retract_maps:\n   \"retraction_maps X Y r s\n        \\<Longrightarrow> retraction_maps X (subtopology X (s ` (topspace Y))) (s \\<circ> r) id\"\n  unfolding retraction_maps_def\n  by (auto simp: continuous_map_compose continuous_map_into_subtopology continuous_map_from_subtopology)\nsubsection \\<open>Continuity\\<close>\n\nlemma continuous_on_open:\n  \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. openin (top_of_set (f ` S)) T \\<longrightarrow>\n      openin (top_of_set S) (S \\<inter> f -` T))\"\n  unfolding continuous_on_open_invariant openin_open Int_def vimage_def Int_commute\n  by (simp add: imp_ex imageI conj_commute eq_commute cong: conj_cong)\n\nlemma continuous_on_closed:\n  \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. closedin (top_of_set (f ` S)) T \\<longrightarrow>\n      closedin (top_of_set S) (S \\<inter> f -` T))\"\n  unfolding continuous_on_closed_invariant closedin_closed Int_def vimage_def Int_commute\n  by (simp add: imp_ex imageI conj_commute eq_commute cong: conj_cong)\n\nlemma continuous_on_imp_closedin:\n  assumes \"continuous_on S f\" \"closedin (top_of_set (f ` S)) T\"\n  shows \"closedin (top_of_set S) (S \\<inter> f -` T)\"\n  using assms continuous_on_closed by blast\n\nlemma continuous_map_subtopology_eu [simp]:\n  \"continuous_map (top_of_set S) (subtopology euclidean T) h \\<longleftrightarrow> continuous_on S h \\<and> h ` S \\<subseteq> T\"\n  by (simp add: continuous_map_in_subtopology)\n\nlemma continuous_map_euclidean_top_of_set:\n  assumes eq: \"f -` S = UNIV\" and cont: \"continuous_on UNIV f\"\n  shows \"continuous_map euclidean (top_of_set S) f\"\n  by (simp add: cont continuous_map_into_subtopology eq image_subset_iff_subset_vimage)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Half-global and completely global cases\\<close>\n\nlemma continuous_openin_preimage_gen:\n  assumes \"continuous_on S f\"  \"open T\"\n  shows \"openin (top_of_set S) (S \\<inter> f -` T)\"\nproof -\n  have *: \"(S \\<inter> f -` T) = (S \\<inter> f -` (T \\<inter> f ` S))\"\n    by auto\n  have \"openin (top_of_set (f ` S)) (T \\<inter> f ` S)\"\n    using openin_open_Int[of T \"f ` S\", OF assms(2)] unfolding openin_open by auto\n  then show ?thesis\n    using assms(1)[unfolded continuous_on_open, THEN spec[where x=\"T \\<inter> f ` S\"]]\n    using * by auto\nqed\n\nlemma continuous_closedin_preimage:\n  assumes \"continuous_on S f\" and \"closed T\"\n  shows \"closedin (top_of_set S) (S \\<inter> f -` T)\"\nproof -\n  have *: \"(S \\<inter> f -` T) = (S \\<inter> f -` (T \\<inter> f ` S))\"\n    by auto\n  have \"closedin (top_of_set (f ` S)) (T \\<inter> f ` S)\"\n    using closedin_closed_Int[of T \"f ` S\", OF assms(2)]\n    by (simp add: Int_commute)\n  then show ?thesis\n    using assms(1)[unfolded continuous_on_closed, THEN spec[where x=\"T \\<inter> f ` S\"]]\n    using * by auto\nqed\n\nlemma continuous_openin_preimage_eq:\n   \"continuous_on S f \\<longleftrightarrow> (\\<forall>T. open T \\<longrightarrow> openin (top_of_set S) (S \\<inter> f -` T))\"\n  by (metis Int_commute continuous_on_open_invariant open_openin openin_subtopology)\n\nlemma continuous_closedin_preimage_eq:\n   \"continuous_on S f \\<longleftrightarrow>\n    (\\<forall>T. closed T \\<longrightarrow> closedin (top_of_set S) (S \\<inter> f -` T))\"\n  by (metis Int_commute closedin_closed continuous_on_closed_invariant)\n\nlemma continuous_open_preimage:\n  assumes contf: \"continuous_on S f\" and \"open S\" \"open T\"\n  shows \"open (S \\<inter> f -` T)\"\nproof-\n  obtain U where \"open U\" \"(S \\<inter> f -` T) = S \\<inter> U\"\n    using continuous_openin_preimage_gen[OF contf \\<open>open T\\<close>]\n    unfolding openin_open by auto\n  then show ?thesis\n    using open_Int[of S U, OF \\<open>open S\\<close>] by auto\nqed\n\nlemma continuous_closed_preimage:\n  assumes contf: \"continuous_on S f\" and \"closed S\" \"closed T\"\n  shows \"closed (S \\<inter> f -` T)\"\nproof-\n  obtain U where \"closed U\" \"(S \\<inter> f -` T) = S \\<inter> U\"\n    using continuous_closedin_preimage[OF contf \\<open>closed T\\<close>]\n    unfolding closedin_closed by auto\n  then show ?thesis using closed_Int[of S U, OF \\<open>closed S\\<close>] by auto\nqed\n\nlemma continuous_open_vimage: \"open S \\<Longrightarrow> (\\<And>x. continuous (at x) f) \\<Longrightarrow> open (f -` S)\"\n  by (metis continuous_on_eq_continuous_within open_vimage) \n \nlemma continuous_closed_vimage: \"closed S \\<Longrightarrow> (\\<And>x. continuous (at x) f) \\<Longrightarrow> closed (f -` S)\"\n  by (simp add: closed_vimage continuous_on_eq_continuous_within)\n\nlemma Times_in_interior_subtopology:\n  assumes \"(x, y) \\<in> U\" \"openin (top_of_set (S \\<times> T)) U\"\n  obtains V W where \"openin (top_of_set S) V\" \"x \\<in> V\"\n                    \"openin (top_of_set T) W\" \"y \\<in> W\" \"(V \\<times> W) \\<subseteq> U\"\nproof -\n  from assms obtain E where \"open E\" \"U = S \\<times> T \\<inter> E\" \"(x, y) \\<in> E\" \"x \\<in> S\" \"y \\<in> T\"\n    by (auto simp: openin_open)\n  from open_prod_elim[OF \\<open>open E\\<close> \\<open>(x, y) \\<in> E\\<close>]\n  obtain E1 E2 where \"open E1\" \"open E2\" \"(x, y) \\<in> E1 \\<times> E2\" \"E1 \\<times> E2 \\<subseteq> E\"\n    by blast\n  show ?thesis\n  proof\n    show \"openin (top_of_set S) (E1 \\<inter> S)\" \"openin (top_of_set T) (E2 \\<inter> T)\"\n      using \\<open>open E1\\<close> \\<open>open E2\\<close> by (auto simp: openin_open)\n    show \"x \\<in> E1 \\<inter> S\" \"y \\<in> E2 \\<inter> T\"\n      using \\<open>(x, y) \\<in> E1 \\<times> E2\\<close> \\<open>x \\<in> S\\<close> \\<open>y \\<in> T\\<close> by auto\n    show \"(E1 \\<inter> S) \\<times> (E2 \\<inter> T) \\<subseteq> U\"\n      using \\<open>E1 \\<times> E2 \\<subseteq> E\\<close> \\<open>U = _\\<close> by auto\n  qed\nqed\n\nlemma closedin_Times:\n  \"closedin (top_of_set S) S' \\<Longrightarrow> closedin (top_of_set T) T' \\<Longrightarrow>\n    closedin (top_of_set (S \\<times> T)) (S' \\<times> T')\"\n  unfolding closedin_closed using closed_Times by blast\n\nlemma openin_Times:\n  \"openin (top_of_set S) S' \\<Longrightarrow> openin (top_of_set T) T' \\<Longrightarrow>\n    openin (top_of_set (S \\<times> T)) (S' \\<times> T')\"\n  unfolding openin_open using open_Times by blast\n\nlemma openin_Times_eq:\n  fixes S :: \"'a::topological_space set\" and T :: \"'b::topological_space set\"\n  shows\n    \"openin (top_of_set (S \\<times> T)) (S' \\<times> T') \\<longleftrightarrow>\n      S' = {} \\<or> T' = {} \\<or> openin (top_of_set S) S' \\<and> openin (top_of_set T) T'\"\n    (is \"?lhs = ?rhs\")\nproof (cases \"S' = {} \\<or> T' = {}\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then obtain x y where \"x \\<in> S'\" \"y \\<in> T'\"\n    by blast\n  show ?thesis\n  proof\n    assume ?lhs\n    have \"openin (top_of_set S) S'\"\n    proof (subst openin_subopen, clarify)\n      show \"\\<exists>U. openin (top_of_set S) U \\<and> x \\<in> U \\<and> U \\<subseteq> S'\" if \"x \\<in> S'\" for x\n        using that \\<open>y \\<in> T'\\<close> Times_in_interior_subtopology [OF _ \\<open>?lhs\\<close>, of x y]\n        by simp (metis mem_Sigma_iff subsetD subsetI)\n    qed\n    moreover have \"openin (top_of_set T) T'\"\n    proof (subst openin_subopen, clarify)\n      show \"\\<exists>U. openin (top_of_set T) U \\<and> y \\<in> U \\<and> U \\<subseteq> T'\" if \"y \\<in> T'\" for y\n        using that \\<open>x \\<in> S'\\<close> Times_in_interior_subtopology [OF _ \\<open>?lhs\\<close>, of x y]\n        by simp (metis mem_Sigma_iff subsetD subsetI)\n    qed\n    ultimately show ?rhs\n      by simp\n  next\n    assume ?rhs\n    with False show ?lhs\n      by (simp add: openin_Times)\n  qed\nqed\n\nlemma Lim_transform_within_openin:\n  assumes f: \"(f \\<longlongrightarrow> l) (at a within T)\"\n    and \"openin (top_of_set T) S\" \"a \\<in> S\"\n    and eq: \"\\<And>x. \\<lbrakk>x \\<in> S; x \\<noteq> a\\<rbrakk> \\<Longrightarrow> f x = g x\"\n  shows \"(g \\<longlongrightarrow> l) (at a within T)\"\nproof -\n  have \"\\<forall>\\<^sub>F x in at a within T. x \\<in> T \\<and> x \\<noteq> a\"\n    by (simp add: eventually_at_filter)\n  moreover\n  from \\<open>openin _ _\\<close> obtain U where \"open U\" \"S = T \\<inter> U\"\n    by (auto simp: openin_open)\n  then have \"a \\<in> U\" using \\<open>a \\<in> S\\<close> by auto\n  from topological_tendstoD[OF tendsto_ident_at \\<open>open U\\<close> \\<open>a \\<in> U\\<close>]\n  have \"\\<forall>\\<^sub>F x in at a within T. x \\<in> U\" by auto\n  ultimately\n  have \"\\<forall>\\<^sub>F x in at a within T. f x = g x\"\n    by eventually_elim (auto simp: \\<open>S = _\\<close> eq)\n  with f show ?thesis\n    by (rule Lim_transform_eventually)\nqed\n\nlemma continuous_on_open_gen:\n  assumes \"f ` S \\<subseteq> T\"\n    shows \"continuous_on S f \\<longleftrightarrow>\n             (\\<forall>U. openin (top_of_set T) U\n                  \\<longrightarrow> openin (top_of_set S) (S \\<inter> f -` U))\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (clarsimp simp add: continuous_openin_preimage_eq openin_open)\n      (metis Int_assoc assms image_subset_iff_subset_vimage inf.absorb_iff1)\nnext\n  assume R [rule_format]: ?rhs\n  show ?lhs\n  proof (clarsimp simp add: continuous_openin_preimage_eq)\n    fix U::\"'a set\"\n    assume \"open U\"\n    then have \"openin (top_of_set S) (S \\<inter> f -` (U \\<inter> T))\"\n      by (metis R inf_commute openin_open)\n    then show \"openin (top_of_set S) (S \\<inter> f -` U)\"\n      by (metis Int_assoc Int_commute assms image_subset_iff_subset_vimage inf.absorb_iff2 vimage_Int)\n  qed\nqed\n\nlemma continuous_openin_preimage:\n  \"\\<lbrakk>continuous_on S f; f ` S \\<subseteq> T; openin (top_of_set T) U\\<rbrakk>\n        \\<Longrightarrow> openin (top_of_set S) (S \\<inter> f -` U)\"\n  by (simp add: continuous_on_open_gen)\n\nlemma continuous_on_closed_gen:\n  assumes \"f ` S \\<subseteq> T\"\n  shows \"continuous_on S f \\<longleftrightarrow>\n             (\\<forall>U. closedin (top_of_set T) U\n                  \\<longrightarrow> closedin (top_of_set S) (S \\<inter> f -` U))\"\nproof -\n  have *: \"U \\<subseteq> T \\<Longrightarrow> S \\<inter> f -` (T - U) = S - (S \\<inter> f -` U)\" for U\n    using assms by blast\n  then show ?thesis\n      unfolding continuous_on_open_gen [OF assms]\n      by (metis closedin_def inf.cobounded1 openin_closedin_eq topspace_euclidean_subtopology)\nqed\n\nlemma continuous_closedin_preimage_gen:\n  assumes \"continuous_on S f\" \"f ` S \\<subseteq> T\" \"closedin (top_of_set T) U\"\n    shows \"closedin (top_of_set S) (S \\<inter> f -` U)\"\nusing assms continuous_on_closed_gen by blast\n\nlemma continuous_transform_within_openin:\n  assumes \"continuous (at a within T) f\"\n    and \"openin (top_of_set T) S\" \"a \\<in> S\"\n    and eq: \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  shows \"continuous (at a within T) g\"\n  using assms by (simp add: Lim_transform_within_openin continuous_within)\n\n\nsubsection\\<^marker>\\<open>tag important\\<close> \\<open>The topology generated by some (open) subsets\\<close>\n\ntext \\<open>In the definition below of a generated topology, the \\<open>Empty\\<close> case is not necessary,\nas it follows from \\<open>UN\\<close> taking for \\<open>K\\<close> the empty set. However, it is convenient to have,\nand is never a problem in proofs, so I prefer to write it down explicitly.\n\nWe do not require \\<open>UNIV\\<close> to be an open set, as this will not be the case in applications. (We are\nthinking of a topology on a subset of \\<open>UNIV\\<close>, the remaining part of \\<open>UNIV\\<close> being irrelevant.)\\<close>\n\ninductive generate_topology_on for S where\n  Empty: \"generate_topology_on S {}\"\n| Int: \"generate_topology_on S a \\<Longrightarrow> generate_topology_on S b \\<Longrightarrow> generate_topology_on S (a \\<inter> b)\"\n| UN: \"(\\<And>k. k \\<in> K \\<Longrightarrow> generate_topology_on S k) \\<Longrightarrow> generate_topology_on S (\\<Union>K)\"\n| Basis: \"s \\<in> S \\<Longrightarrow> generate_topology_on S s\"\n\nlemma istopology_generate_topology_on:\n  \"istopology (generate_topology_on S)\"\nunfolding istopology_def by (auto intro: generate_topology_on.intros)\n\ntext \\<open>The basic property of the topology generated by a set \\<open>S\\<close> is that it is the\nsmallest topology containing all the elements of \\<open>S\\<close>:\\<close>\n\nlemma generate_topology_on_coarsest:\n  assumes T: \"istopology T\" \"\\<And>s. s \\<in> S \\<Longrightarrow> T s\"\n          and gen: \"generate_topology_on S s0\"\n  shows \"T s0\"\n  using gen \nby (induct rule: generate_topology_on.induct) (use T in \\<open>auto simp: istopology_def\\<close>)\n\nabbreviation\\<^marker>\\<open>tag unimportant\\<close> topology_generated_by::\"('a set set) \\<Rightarrow> ('a topology)\"\n  where \"topology_generated_by S \\<equiv> topology (generate_topology_on S)\"\n\nlemma openin_topology_generated_by_iff:\n  \"openin (topology_generated_by S) s \\<longleftrightarrow> generate_topology_on S s\"\n  using topology_inverse'[OF istopology_generate_topology_on[of S]] by simp\n\nlemma openin_topology_generated_by:\n  \"openin (topology_generated_by S) s \\<Longrightarrow> generate_topology_on S s\"\nusing openin_topology_generated_by_iff by auto\n\nlemma topology_generated_by_topspace [simp]:\n  \"topspace (topology_generated_by S) = (\\<Union>S)\"\nproof\n  {\n    fix s assume \"openin (topology_generated_by S) s\"\n    then have \"generate_topology_on S s\" by (rule openin_topology_generated_by)\n    then have \"s \\<subseteq> (\\<Union>S)\" by (induct, auto)\n  }\n  then show \"topspace (topology_generated_by S) \\<subseteq> (\\<Union>S)\"\n    unfolding topspace_def by auto\nnext\n  have \"generate_topology_on S (\\<Union>S)\"\n    using generate_topology_on.UN[OF generate_topology_on.Basis, of S S] by simp\n  then show \"(\\<Union>S) \\<subseteq> topspace (topology_generated_by S)\"\n    unfolding topspace_def using openin_topology_generated_by_iff by auto\nqed\n\nlemma topology_generated_by_Basis:\n  \"s \\<in> S \\<Longrightarrow> openin (topology_generated_by S) s\"\n  by (simp add: Basis openin_topology_generated_by_iff)\n\nlemma generate_topology_on_Inter:\n  \"\\<lbrakk>finite \\<F>; \\<And>K. K \\<in> \\<F> \\<Longrightarrow> generate_topology_on \\<S> K; \\<F> \\<noteq> {}\\<rbrakk> \\<Longrightarrow> generate_topology_on \\<S> (\\<Inter>\\<F>)\"\n  by (induction \\<F> rule: finite_induct; force intro: generate_topology_on.intros)\n\nsubsection\\<open>Topology bases and sub-bases\\<close>\n\nlemma istopology_base_alt:\n   \"istopology (arbitrary union_of P) \\<longleftrightarrow>\n    (\\<forall>S T. (arbitrary union_of P) S \\<and> (arbitrary union_of P) T\n           \\<longrightarrow> (arbitrary union_of P) (S \\<inter> T))\"\n  by (simp add: istopology_def) (blast intro: arbitrary_union_of_Union)\n\nlemma istopology_base_eq:\n   \"istopology (arbitrary union_of P) \\<longleftrightarrow>\n    (\\<forall>S T. P S \\<and> P T \\<longrightarrow> (arbitrary union_of P) (S \\<inter> T))\"\n  by (simp add: istopology_base_alt arbitrary_union_of_Int_eq)\n\nlemma istopology_base:\n   \"(\\<And>S T. \\<lbrakk>P S; P T\\<rbrakk> \\<Longrightarrow> P(S \\<inter> T)) \\<Longrightarrow> istopology (arbitrary union_of P)\"\n  by (simp add: arbitrary_def istopology_base_eq union_of_inc)\n\nlemma openin_topology_base_unique:\n   \"openin X = arbitrary union_of P \\<longleftrightarrow>\n        (\\<forall>V. P V \\<longrightarrow> openin X V) \\<and> (\\<forall>U x. openin X U \\<and> x \\<in> U \\<longrightarrow> (\\<exists>V. P V \\<and> x \\<in> V \\<and> V \\<subseteq> U))\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (auto simp: union_of_def arbitrary_def)\nnext\n  assume R: ?rhs\n  then have *: \"\\<exists>\\<U>\\<subseteq>Collect P. \\<Union>\\<U> = S\" if \"openin X S\" for S\n    using that by (rule_tac x=\"{V. P V \\<and> V \\<subseteq> S}\" in exI) fastforce\n  from R show ?lhs\n    by (fastforce simp add: union_of_def arbitrary_def intro: *)\nqed\n\nlemma topology_base_unique:\n  assumes \"\\<And>S. P S \\<Longrightarrow> openin X S\"\n          \"\\<And>U x. \\<lbrakk>openin X U; x \\<in> U\\<rbrakk> \\<Longrightarrow> \\<exists>B. P B \\<and> x \\<in> B \\<and> B \\<subseteq> U\"\n  shows   \"topology (arbitrary union_of P) = X\"\nproof -\n  have \"X = topology (openin X)\"\n    by (simp add: openin_inverse)\n  also from assms have \"openin X = arbitrary union_of P\"\n    by (subst openin_topology_base_unique) auto\n  finally show ?thesis ..\nqed\n\nlemma topology_bases_eq_aux:\n   \"\\<lbrakk>(arbitrary union_of P) S;\n     \\<And>U x. \\<lbrakk>P U; x \\<in> U\\<rbrakk> \\<Longrightarrow> \\<exists>V. Q V \\<and> x \\<in> V \\<and> V \\<subseteq> U\\<rbrakk>\n        \\<Longrightarrow> (arbitrary union_of Q) S\"\n  by (metis arbitrary_union_of_alt arbitrary_union_of_idempot)\n\nlemma topology_bases_eq:\n   \"\\<lbrakk>\\<And>U x. \\<lbrakk>P U; x \\<in> U\\<rbrakk> \\<Longrightarrow> \\<exists>V. Q V \\<and> x \\<in> V \\<and> V \\<subseteq> U;\n    \\<And>V x. \\<lbrakk>Q V; x \\<in> V\\<rbrakk> \\<Longrightarrow> \\<exists>U. P U \\<and> x \\<in> U \\<and> U \\<subseteq> V\\<rbrakk>\n        \\<Longrightarrow> topology (arbitrary union_of P) =\n            topology (arbitrary union_of Q)\"\n  by (fastforce intro:  arg_cong [where f=topology]  elim: topology_bases_eq_aux)\n\nlemma istopology_subbase:\n   \"istopology (arbitrary union_of (finite intersection_of P relative_to S))\"\n  by (simp add: finite_intersection_of_Int istopology_base relative_to_Int)\n\nlemma openin_subbase:\n  \"openin (topology (arbitrary union_of (finite intersection_of B relative_to U))) S\n   \\<longleftrightarrow> (arbitrary union_of (finite intersection_of B relative_to U)) S\"\n  by (simp add: istopology_subbase topology_inverse')\n\nlemma topspace_subbase [simp]:\n   \"topspace(topology (arbitrary union_of (finite intersection_of B relative_to U))) = U\" (is \"?lhs = _\")\nproof\n  show \"?lhs \\<subseteq> U\"\n    by (metis arbitrary_union_of_relative_to openin_subbase openin_topspace relative_to_imp_subset)\n  show \"U \\<subseteq> ?lhs\"\n    by (metis arbitrary_union_of_inc finite_intersection_of_empty inf.orderE istopology_subbase \n              openin_subset relative_to_inc subset_UNIV topology_inverse')\nqed\n\nlemma minimal_topology_subbase:\n  assumes X: \"\\<And>S. P S \\<Longrightarrow> openin X S\" and \"openin X U\"\n  and S: \"openin(topology(arbitrary union_of (finite intersection_of P relative_to U))) S\"\nshows \"openin X S\"\nproof -\n  have \"(arbitrary union_of (finite intersection_of P relative_to U)) S\"\n    using S openin_subbase by blast\n  with X \\<open>openin X U\\<close> show ?thesis\n    by (force simp add: union_of_def intersection_of_def relative_to_def intro: openin_Int_Inter)\nqed\n\nlemma istopology_subbase_UNIV:\n   \"istopology (arbitrary union_of (finite intersection_of P))\"\n  by (simp add: istopology_base finite_intersection_of_Int)\n\n\nlemma generate_topology_on_eq:\n  \"generate_topology_on S = arbitrary union_of finite' intersection_of (\\<lambda>x. x \\<in> S)\" (is \"?lhs = ?rhs\")\nproof (intro ext iffI)\n  fix A\n  assume \"?lhs A\"\n  then show \"?rhs A\"\n  proof induction\n    case (Int a b)\n    then show ?case\n      by (metis (mono_tags, lifting) istopology_base_alt finite'_intersection_of_Int istopology_base)\n  next\n    case (UN K)\n    then show ?case\n      by (simp add: arbitrary_union_of_Union)\n  next\n    case (Basis s)\n    then show ?case\n      by (simp add: Sup_upper arbitrary_union_of_inc finite'_intersection_of_inc relative_to_subset)\n  qed auto\nnext\n  fix A\n  assume \"?rhs A\"\n  then obtain \\<U> where \\<U>: \"\\<And>T. T \\<in> \\<U> \\<Longrightarrow> \\<exists>\\<F>. finite' \\<F> \\<and> \\<F> \\<subseteq> S \\<and> \\<Inter>\\<F> = T\" and eq: \"A = \\<Union>\\<U>\"\n    unfolding union_of_def intersection_of_def by auto\n  show \"?lhs A\"\n    unfolding eq\n  proof (rule generate_topology_on.UN)\n    fix T\n    assume \"T \\<in> \\<U>\"\n    with \\<U> obtain \\<F> where \"finite' \\<F>\" \"\\<F> \\<subseteq> S\" \"\\<Inter>\\<F> = T\"\n      by blast\n    have \"generate_topology_on S (\\<Inter>\\<F>)\"\n    proof (rule generate_topology_on_Inter)\n      show \"finite \\<F>\" \"\\<F> \\<noteq> {}\"\n        by (auto simp: \\<open>finite' \\<F>\\<close>)\n      show \"\\<And>K. K \\<in> \\<F> \\<Longrightarrow> generate_topology_on S K\"\n        by (metis \\<open>\\<F> \\<subseteq> S\\<close> generate_topology_on.simps subset_iff)\n    qed\n    then show \"generate_topology_on S T\"\n      using \\<open>\\<Inter>\\<F> = T\\<close> by blast\n  qed\nqed\n\nlemma continuous_on_generated_topo_iff:\n  \"continuous_map T1 (topology_generated_by S) f \\<longleftrightarrow>\n      ((\\<forall>U. U \\<in> S \\<longrightarrow> openin T1 (f-`U \\<inter> topspace(T1))) \\<and> (f`(topspace T1) \\<subseteq> (\\<Union> S)))\"\nunfolding continuous_map_alt topology_generated_by_topspace\nproof (auto simp add: topology_generated_by_Basis)\n  assume H: \"\\<forall>U. U \\<in> S \\<longrightarrow> openin T1 (f -` U \\<inter> topspace T1)\"\n  fix U assume \"openin (topology_generated_by S) U\"\n  then have \"generate_topology_on S U\" by (rule openin_topology_generated_by)\n  then show \"openin T1 (f -` U \\<inter> topspace T1)\"\n  proof (induct)\n    fix a b\n    assume H: \"openin T1 (f -` a \\<inter> topspace T1)\" \"openin T1 (f -` b \\<inter> topspace T1)\"\n    have \"f -` (a \\<inter> b) \\<inter> topspace T1 = (f-`a \\<inter> topspace T1) \\<inter> (f-`b \\<inter> topspace T1)\"\n      by auto\n    then show \"openin T1 (f -` (a \\<inter> b) \\<inter> topspace T1)\" using H by auto\n  next\n    fix K\n    assume H: \"openin T1 (f -` k \\<inter> topspace T1)\" if \"k\\<in> K\" for k\n    define L where \"L = {f -` k \\<inter> topspace T1|k. k \\<in> K}\"\n    have *: \"openin T1 l\" if \"l \\<in>L\" for l using that H unfolding L_def by auto\n    have \"openin T1 (\\<Union>L)\" using openin_Union[OF *] by simp\n    moreover have \"(\\<Union>L) = (f -` \\<Union>K \\<inter> topspace T1)\" unfolding L_def by auto\n    ultimately show \"openin T1 (f -` \\<Union>K \\<inter> topspace T1)\" by simp\n  qed (auto simp add: H)\nqed\n\nlemma continuous_on_generated_topo:\n  assumes \"\\<And>U. U \\<in>S \\<Longrightarrow> openin T1 (f-`U \\<inter> topspace(T1))\"\n          \"f`(topspace T1) \\<subseteq> (\\<Union> S)\"\n  shows \"continuous_map T1 (topology_generated_by S) f\"\n  using assms continuous_on_generated_topo_iff by blast\n\n\nsubsection\\<^marker>\\<open>tag important\\<close> \\<open>Pullback topology\\<close>\n\ntext \\<open>Pulling back a topology by map gives again a topology. \\<open>subtopology\\<close> is\na special case of this notion, pulling back by the identity. We introduce the general notion as\nwe will need it to define the strong operator topology on the space of continuous linear operators,\nby pulling back the product topology on the space of all functions.\\<close>\n\ntext \\<open>\\<open>pullback_topology A f T\\<close> is the pullback of the topology \\<open>T\\<close> by the map \\<open>f\\<close> on\nthe set \\<open>A\\<close>.\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> pullback_topology::\"('a set) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b topology) \\<Rightarrow> ('a topology)\"\n  where \"pullback_topology A f T = topology (\\<lambda>S. \\<exists>U. openin T U \\<and> S = f-`U \\<inter> A)\"\n\nlemma istopology_pullback_topology:\n  \"istopology (\\<lambda>S. \\<exists>U. openin T U \\<and> S = f-`U \\<inter> A)\"\n  unfolding istopology_def proof (auto)\n  fix K assume \"\\<forall>S\\<in>K. \\<exists>U. openin T U \\<and> S = f -` U \\<inter> A\"\n  then have \"\\<exists>U. \\<forall>S\\<in>K. openin T (U S) \\<and> S = f-`(U S) \\<inter> A\"\n    by (rule bchoice)\n  then obtain U where U: \"\\<forall>S\\<in>K. openin T (U S) \\<and> S = f-`(U S) \\<inter> A\"\n    by blast\n  define V where \"V = (\\<Union>S\\<in>K. U S)\"\n  have \"openin T V\" \"\\<Union>K = f -` V \\<inter> A\" unfolding V_def using U by auto\n  then show \"\\<exists>V. openin T V \\<and> \\<Union>K = f -` V \\<inter> A\" by auto\nqed\n\nlemma openin_pullback_topology:\n  \"openin (pullback_topology A f T) S \\<longleftrightarrow> (\\<exists>U. openin T U \\<and> S = f-`U \\<inter> A)\"\nunfolding pullback_topology_def topology_inverse'[OF istopology_pullback_topology] by auto\n\nlemma topspace_pullback_topology:\n  \"topspace (pullback_topology A f T) = f-`(topspace T) \\<inter> A\"\nby (auto simp add: topspace_def openin_pullback_topology)\n\nproposition continuous_map_pullback [intro]:\n  assumes \"continuous_map T1 T2 g\"\n  shows \"continuous_map (pullback_topology A f T1) T2 (g o f)\"\nunfolding continuous_map_alt\nproof (auto)\n  fix U::\"'b set\" assume \"openin T2 U\"\n  then have \"openin T1 (g-`U \\<inter> topspace T1)\"\n    using assms unfolding continuous_map_alt by auto\n  have \"(g o f)-`U \\<inter> topspace (pullback_topology A f T1) = (g o f)-`U \\<inter> A \\<inter> f-`(topspace T1)\"\n    unfolding topspace_pullback_topology by auto\n  also have \"... = f-`(g-`U \\<inter> topspace T1) \\<inter> A \"\n    by auto\n  also have \"openin (pullback_topology A f T1) (...)\"\n    unfolding openin_pullback_topology using \\<open>openin T1 (g-`U \\<inter> topspace T1)\\<close> by auto\n  finally show \"openin (pullback_topology A f T1) ((g \\<circ> f) -` U \\<inter> topspace (pullback_topology A f T1))\"\n    by auto\nnext\n  fix x assume \"x \\<in> topspace (pullback_topology A f T1)\"\n  then have \"f x \\<in> topspace T1\"\n    unfolding topspace_pullback_topology by auto\n  then show \"g (f x) \\<in> topspace T2\"\n    using assms unfolding continuous_map_def by auto\nqed\n\nproposition continuous_map_pullback' [intro]:\n  assumes \"continuous_map T1 T2 (f o g)\" \"topspace T1 \\<subseteq> g-`A\"\n  shows \"continuous_map T1 (pullback_topology A f T2) g\"\nunfolding continuous_map_alt\nproof (auto)\n  fix U assume \"openin (pullback_topology A f T2) U\"\n  then have \"\\<exists>V. openin T2 V \\<and> U = f-`V \\<inter> A\"\n    unfolding openin_pullback_topology by auto\n  then obtain V where \"openin T2 V\" \"U = f-`V \\<inter> A\"\n    by blast\n  then have \"g -` U \\<inter> topspace T1 = g-`(f-`V \\<inter> A) \\<inter> topspace T1\"\n    by blast\n  also have \"... = (f o g)-`V \\<inter> (g-`A \\<inter> topspace T1)\"\n    by auto\n  also have \"... = (f o g)-`V \\<inter> topspace T1\"\n    using assms(2) by auto\n  also have \"openin T1 (...)\"\n    using assms(1) \\<open>openin T2 V\\<close> by auto\n  finally show \"openin T1 (g -` U \\<inter> topspace T1)\" by simp\nnext\n  fix x assume \"x \\<in> topspace T1\"\n  have \"(f o g) x \\<in> topspace T2\"\n    using assms(1) \\<open>x \\<in> topspace T1\\<close> unfolding continuous_map_def by auto\n  then have \"g x \\<in> f-`(topspace T2)\"\n    unfolding comp_def by blast\n  moreover have \"g x \\<in> A\" using assms(2) \\<open>x \\<in> topspace T1\\<close> by blast\n  ultimately show \"g x \\<in> topspace (pullback_topology A f T2)\"\n    unfolding topspace_pullback_topology by blast\nqed\nsubsection\\<open>Proper maps (not a priori assumed continuous) \\<close>\n\ndefinition proper_map\n  where\n \"proper_map X Y f \\<equiv>\n        closed_map X Y f \\<and> (\\<forall>y \\<in> topspace Y. compactin X {x \\<in> topspace X. f x = y})\"\n\nlemma proper_imp_closed_map:\n   \"proper_map X Y f \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: proper_map_def)\n\nlemma proper_map_imp_subset_topspace:\n   \"proper_map X Y f \\<Longrightarrow> f ` (topspace X) \\<subseteq> topspace Y\"\n  by (simp add: closed_map_imp_subset_topspace proper_map_def)\n\nlemma closed_injective_imp_proper_map:\n  assumes f: \"closed_map X Y f\" and inj: \"inj_on f (topspace X)\"\n  shows \"proper_map X Y f\"\n  unfolding proper_map_def\nproof (clarsimp simp: f)\n  show \"compactin X {x \\<in> topspace X. f x = y}\"\n    if \"y \\<in> topspace Y\" for y\nusing inj_on_eq_iff [OF inj] that\n  proof -\n    have \"{x \\<in> topspace X. f x = y} = {} \\<or> (\\<exists>a \\<in> topspace X. {x \\<in> topspace X. f x = y} = {a})\"\n      using inj_on_eq_iff [OF inj] by auto\n    then show ?thesis\n      using that by (metis (no_types, lifting) compactin_empty compactin_sing)\n  qed\nqed\n\nlemma injective_imp_proper_eq_closed_map:\n   \"inj_on f (topspace X) \\<Longrightarrow> (proper_map X Y f \\<longleftrightarrow> closed_map X Y f)\"\n  using closed_injective_imp_proper_map proper_imp_closed_map by blast\n\nlemma homeomorphic_imp_proper_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> proper_map X Y f\"\n  by (simp add: closed_injective_imp_proper_map homeomorphic_eq_everything_map)\n\nlemma compactin_proper_map_preimage:\n  assumes f: \"proper_map X Y f\" and \"compactin Y K\"\n  shows \"compactin X {x. x \\<in> topspace X \\<and> f x \\<in> K}\"\nproof -\n  have \"f ` (topspace X) \\<subseteq> topspace Y\"\n    by (simp add: f proper_map_imp_subset_topspace)\n  have *: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> compactin X {x \\<in> topspace X. f x = y}\"\n    using f by (auto simp: proper_map_def)\n  show ?thesis\n    unfolding compactin_def\n  proof clarsimp\n    show \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> \\<U> \\<and> {x \\<in> topspace X. f x \\<in> K} \\<subseteq> \\<Union>\\<F>\"\n      if \\<U>: \"\\<forall>U\\<in>\\<U>. openin X U\" and sub: \"{x \\<in> topspace X. f x \\<in> K} \\<subseteq> \\<Union>\\<U>\"\n      for \\<U>\n    proof -\n      have \"\\<forall>y \\<in> K. \\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U>  \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>\\<V>\"\n      proof\n        fix y\n        assume \"y \\<in> K\"\n        then have \"compactin X {x \\<in> topspace X. f x = y}\"\n          by (metis \"*\" \\<open>compactin Y K\\<close> compactin_subspace subsetD)\n        with \\<open>y \\<in> K\\<close> show \"\\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U>  \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>\\<V>\"\n          unfolding compactin_def using \\<U> sub by fastforce\n      qed\n      then obtain \\<V> where \\<V>: \"\\<And>y. y \\<in> K \\<Longrightarrow> finite (\\<V> y) \\<and> \\<V> y \\<subseteq> \\<U>  \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>(\\<V> y)\"\n        by (metis (full_types))\n      define F where \"F \\<equiv> \\<lambda>y. topspace Y - f ` (topspace X - \\<Union>(\\<V> y))\"\n      have \"\\<exists>\\<F>. finite \\<F> \\<and> \\<F> \\<subseteq> F ` K \\<and> K \\<subseteq> \\<Union>\\<F>\"\n      proof (rule compactinD [OF \\<open>compactin Y K\\<close>])\n        have \"\\<And>x. x \\<in> K \\<Longrightarrow> closedin Y (f ` (topspace X - \\<Union>(\\<V> x)))\"\n          using f unfolding proper_map_def closed_map_def\n          by (meson \\<U> \\<V> openin_Union openin_closedin_eq subsetD)\n        then show \"openin Y U\" if \"U \\<in> F ` K\" for U\n          using that by (auto simp: F_def)\n        show \"K \\<subseteq> \\<Union>(F ` K)\"\n          using \\<V> \\<open>compactin Y K\\<close> unfolding F_def compactin_def by fastforce\n      qed\n      then obtain J where \"finite J\" \"J \\<subseteq> K\" and J: \"K \\<subseteq> \\<Union>(F ` J)\"\n        by (auto simp: ex_finite_subset_image)\n      show ?thesis\n        unfolding F_def\n      proof (intro exI conjI)\n        show \"finite (\\<Union>(\\<V> ` J))\"\n          using \\<V> \\<open>J \\<subseteq> K\\<close> \\<open>finite J\\<close> by blast\n        show \"\\<Union>(\\<V> ` J) \\<subseteq> \\<U>\"\n          using \\<V> \\<open>J \\<subseteq> K\\<close> by blast\n        show \"{x \\<in> topspace X. f x \\<in> K} \\<subseteq> \\<Union>(\\<Union>(\\<V> ` J))\"\n          using J \\<open>J \\<subseteq> K\\<close> unfolding F_def by auto\n      qed\n    qed\n  qed\nqed\n\n\nlemma compact_space_proper_map_preimage:\n  assumes f: \"proper_map X Y f\" and fim: \"f ` (topspace X) = topspace Y\" and \"compact_space Y\"\n  shows \"compact_space X\"\nproof -\n  have eq: \"topspace X = {x \\<in> topspace X. f x \\<in> topspace Y}\"\n    using fim by blast\n  moreover have \"compactin Y (topspace Y)\"\n    using \\<open>compact_space Y\\<close> compact_space_def by auto\n  ultimately show ?thesis\n    unfolding compact_space_def\n    using eq f compactin_proper_map_preimage by fastforce\nqed\n\nlemma proper_map_alt:\n   \"proper_map X Y f \\<longleftrightarrow>\n    closed_map X Y f \\<and> (\\<forall>K. compactin Y K \\<longrightarrow> compactin X {x. x \\<in> topspace X \\<and> f x \\<in> K})\"\n  proof (intro iffI conjI allI impI)\n  show \"compactin X {x \\<in> topspace X. f x \\<in> K}\"\n    if \"proper_map X Y f\" and \"compactin Y K\" for K\n    using that by (simp add: compactin_proper_map_preimage)\n  show \"proper_map X Y f\"\n    if f: \"closed_map X Y f \\<and> (\\<forall>K. compactin Y K \\<longrightarrow> compactin X {x \\<in> topspace X. f x \\<in> K})\"\n  proof -\n    have \"compactin X {x \\<in> topspace X. f x = y}\" if \"y \\<in> topspace Y\" for y\n    proof -\n      have \"compactin X {x \\<in> topspace X. f x \\<in> {y}}\"\n        using f compactin_sing that by fastforce\n      then show ?thesis\n        by auto\n    qed\n    with f show ?thesis\n      by (auto simp: proper_map_def)\n  qed\nqed (simp add: proper_imp_closed_map)\n\nlemma proper_map_on_empty:\n   \"topspace X = {} \\<Longrightarrow> proper_map X Y f\"\n  by (auto simp: proper_map_def closed_map_on_empty)\n\nlemma proper_map_id [simp]:\n   \"proper_map X X id\"\nproof (clarsimp simp: proper_map_alt closed_map_id)\n  fix K\n  assume K: \"compactin X K\"\n  then have \"{a \\<in> topspace X. a \\<in> K} = K\"\n    by (simp add: compactin_subspace subset_antisym subset_iff)\n  then show \"compactin X {a \\<in> topspace X. a \\<in> K}\"\n    using K by auto\nqed\n\nlemma proper_map_compose:\n  assumes \"proper_map X Y f\" \"proper_map Y Z g\"\n  shows \"proper_map X Z (g \\<circ> f)\"\nproof -\n  have \"closed_map X Y f\" and f: \"\\<And>K. compactin Y K \\<Longrightarrow> compactin X {x \\<in> topspace X. f x \\<in> K}\"\n    and \"closed_map Y Z g\" and g: \"\\<And>K. compactin Z K \\<Longrightarrow> compactin Y {x \\<in> topspace Y. g x \\<in> K}\"\n    using assms by (auto simp: proper_map_alt)\n  show ?thesis\n    unfolding proper_map_alt\n  proof (intro conjI allI impI)\n    show \"closed_map X Z (g \\<circ> f)\"\n      using \\<open>closed_map X Y f\\<close> \\<open>closed_map Y Z g\\<close> closed_map_compose by blast\n    have \"{x \\<in> topspace X. g (f x) \\<in> K} = {x \\<in> topspace X. f x \\<in> {b \\<in> topspace Y. g b \\<in> K}}\" for K\n      using \\<open>closed_map X Y f\\<close> closed_map_imp_subset_topspace by blast\n    then show \"compactin X {x \\<in> topspace X. (g \\<circ> f) x \\<in> K}\"\n      if \"compactin Z K\" for K\n      using f [OF g [OF that]] by auto\n  qed\nqed\n\nlemma proper_map_const:\n   \"proper_map X Y (\\<lambda>x. c) \\<longleftrightarrow> compact_space X \\<and> (topspace X = {} \\<or> closedin Y {c})\"\nproof (cases \"topspace X = {}\")\n  case True\n  then show ?thesis\n    by (simp add: compact_space_topspace_empty proper_map_on_empty)\nnext\n  case False\n  have *: \"compactin X {x \\<in> topspace X. c = y}\" if \"compact_space X\" for y\n    using that unfolding compact_space_def\n    by (metis (mono_tags, lifting) compactin_empty empty_subsetI mem_Collect_eq subsetI subset_antisym)\n  then show ?thesis\n    using closed_compactin closedin_subset\n    by (force simp: False proper_map_def closed_map_const compact_space_def)\nqed\n\nlemma proper_map_inclusion:\n   \"S \\<subseteq> topspace X \\<Longrightarrow> proper_map (subtopology X S) X id \\<longleftrightarrow> closedin X S \\<and> (\\<forall>k. compactin X k \\<longrightarrow> compactin X (S \\<inter> k))\"\n  by (metis closed_Int_compactin closed_map_inclusion_eq inf.absorb_iff2 inj_on_id injective_imp_proper_eq_closed_map)\n\n\nsubsection\\<open>Perfect maps (proper, continuous and surjective)\\<close>\n\ndefinition perfect_map \n  where \"perfect_map X Y f \\<equiv> continuous_map X Y f \\<and> proper_map X Y f \\<and> f ` (topspace X) = topspace Y\"\n\nlemma homeomorphic_imp_perfect_map:\n   \"homeomorphic_map X Y f \\<Longrightarrow> perfect_map X Y f\"\n  by (simp add: homeomorphic_eq_everything_map homeomorphic_imp_proper_map perfect_map_def)\n\nlemma perfect_imp_quotient_map:\n   \"perfect_map X Y f \\<Longrightarrow> quotient_map X Y f\"\n  by (simp add: continuous_closed_imp_quotient_map perfect_map_def proper_map_def)\n\nlemma homeomorphic_eq_injective_perfect_map:\n   \"homeomorphic_map X Y f \\<longleftrightarrow> perfect_map X Y f \\<and> inj_on f (topspace X)\"\n  using homeomorphic_imp_perfect_map homeomorphic_map_def perfect_imp_quotient_map by blast\n\nlemma perfect_injective_eq_homeomorphic_map:\n   \"perfect_map X Y f \\<and> inj_on f (topspace X) \\<longleftrightarrow> homeomorphic_map X Y f\"\n  by (simp add: homeomorphic_eq_injective_perfect_map)\n\nlemma perfect_map_id [simp]: \"perfect_map X X id\"\n  by (simp add: homeomorphic_imp_perfect_map)\n\nlemma perfect_map_compose:\n   \"\\<lbrakk>perfect_map X Y f; perfect_map Y Z g\\<rbrakk> \\<Longrightarrow> perfect_map X Z (g \\<circ> f)\"\n  by (meson continuous_map_compose perfect_imp_quotient_map perfect_map_def proper_map_compose quotient_map_compose_eq quotient_map_def)\n\nlemma perfect_imp_continuous_map:\n   \"perfect_map X Y f \\<Longrightarrow> continuous_map X Y f\"\n  using perfect_map_def by blast\n\nlemma perfect_imp_closed_map:\n   \"perfect_map X Y f \\<Longrightarrow> closed_map X Y f\"\n  by (simp add: perfect_map_def proper_map_def)\n\nlemma perfect_imp_proper_map:\n   \"perfect_map X Y f \\<Longrightarrow> proper_map X Y f\"\n  by (simp add: perfect_map_def)\n\nlemma perfect_imp_surjective_map:\n   \"perfect_map X Y f \\<Longrightarrow> f ` (topspace X) = topspace Y\"\n  by (simp add: perfect_map_def)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/Abstract_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8856314632529871, "lm_q1q2_score": 0.7911429214526491}}
{"text": "theory Chapter13_7\nimports \"HOL-IMP.Abs_Int2\"\nbegin\n\ntext\\<open>\n\\setcounter{exercise}{15}\n\\exercise\nGive a readable proof that if @{text \"\\<gamma> ::\"} \\noquotes{@{typ[source]\"'a::lattice \\<Rightarrow> 'b::lattice\"}}\nis a monotone function, then @{prop \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"}:\n\\<close>\n\nlemma fixes \\<gamma> :: \"'a::lattice \\<Rightarrow> 'b :: lattice\"\nassumes mono: \"\\<And>x y. x \\<le> y \\<Longrightarrow> \\<gamma> x \\<le> \\<gamma> y\"\nshows \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\" (is \"\\<gamma> ?m \\<le> _\")\nproof -\n  have \"\\<gamma> ?m \\<le> \\<gamma> a\\<^sub>1\" by (intro mono, auto)\n  moreover \n  have \"\\<gamma> ?m \\<le> \\<gamma> a\\<^sub>2\" by (intro mono, auto)\n  ultimately show ?thesis by simp\nqed\n\ntext\\<open>\nGive an example of two lattices and a monotone @{text \\<gamma>}\nwhere @{prop\"\\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2 \\<le> \\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2)\"} does not hold.\n\nConsider {a, c, t, b} of unique elements with order generated by t being top and b being bottom.\nLet f be identity with codomain {a, c, d, t, b} of unique elements, with order generated by t\nbeing top, b being bottom, and \"d \\<le> a\", \"d \\<le> c\".\nthen \\<gamma> (a \\<sqinter> c) = b < d = \\<gamma> a \\<sqinter> \\<gamma> c.\n\\<close>\n\ntext\\<open>\n\\endexercise\n\n\\exercise\nConsider a simple sign analysis based on this abstract domain:\n\\<close>\n\ndatatype sign = None | Neg | Pos0 | Any\n\nfun \\<gamma> :: \"sign \\<Rightarrow> val set\" where\n\"\\<gamma> None = {}\" |\n\"\\<gamma> Neg = {i. i < 0}\" |\n\"\\<gamma> Pos0 = {i. i \\<ge> 0}\" |\n\"\\<gamma> Any = UNIV\"\n\ntext\\<open>\nDefine inverse analyses for ``@{text\"+\"}'' and ``@{text\"<\"}''\nand prove the required correctness properties:\n\\<close>\n\nfun inv_plus' :: \"sign \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n  \"inv_plus' None _ _ = (None, None)\" |\n  \"inv_plus' _ None _ = (None, None)\" |\n  \"inv_plus' _ _ None = (None, None)\" |\n  \"inv_plus' Neg Pos0 Pos0 = (None, None)\" |\n  \"inv_plus' Pos0 Neg Neg = (None, None)\" |\n  \"inv_plus' Neg Pos0 Any = (Pos0, Neg)\" |\n  \"inv_plus' Neg Any Pos0 = (Neg, Pos0)\" |\n  \"inv_plus' Pos0 Neg Any = (Neg, Pos0)\" |\n  \"inv_plus' Pos0 Any Neg = (Pos0, Neg)\" |\n  \"inv_plus' _ a b = (a, b)\"\n\nlemma\n  \"\\<lbrakk> inv_plus' a a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; i1+i2 \\<in> \\<gamma> a \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2' \"\n  by (cases a; cases a1; cases a2) auto\n\nfun inv_less' :: \"bool \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n  \"inv_less' _ None _ = (None, None)\" |\n  \"inv_less' _ _ None = (None, None)\" |\n  \"inv_less' True Pos0 Neg = (None, None)\" |\n  \"inv_less' False Neg Pos0 = (None, None)\" |\n  \"inv_less' True Pos0 Any = (Pos0, Pos0)\" |\n  \"inv_less' True Any Neg = (Neg, Neg)\" |\n  \"inv_less' False Neg Any = (Neg, Neg)\" |\n  \"inv_less' False Any Pos0 = (Pos0, Pos0)\" |\n  \"inv_less' _ a b = (a, b)\"\n\nlemma\n  \"\\<lbrakk> inv_less' bv a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; (i1<i2) = bv \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2'\"\n  by (cases bv; cases a1; cases a2) auto\n\ntext\\<open>\n\\indent\nFor the ambitious: turn the above fragment into a full-blown abstract interpreter\nby replacing the interval analysis in theory @{theory \"HOL-IMP.Abs_Int2\"}@{text\"_ivl\"}\nby a sign analysis.\n\\endexercise\n\\<close>\n\nend\n\n", "meta": {"author": "jhanschoo", "repo": "concrete-semantics-solutions-2019", "sha": "a074695cf316eda4775cc8cfef90c85d44af04a1", "save_path": "github-repos/isabelle/jhanschoo-concrete-semantics-solutions-2019", "path": "github-repos/isabelle/jhanschoo-concrete-semantics-solutions-2019/concrete-semantics-solutions-2019-a074695cf316eda4775cc8cfef90c85d44af04a1/Chapter13_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8757869981319862, "lm_q1q2_score": 0.7910933217192037}}
{"text": "(*  Title:      HOL/Library/Permutation.thy\n    Author:     Lawrence C Paulson and Thomas M Rasmussen and Norbert Voelker\n*)\n\nsection \\<open>Permutations\\<close>\n\ntheory Permutation\nimports Main\nbegin\n\ninductive perm :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"  (infixr \\<open><~~>\\<close> 50)\nwhere\n  Nil [intro!]: \"[] <~~> []\"\n| swap [intro!]: \"y # x # l <~~> x # y # l\"\n| Cons [intro!]: \"xs <~~> ys \\<Longrightarrow> z # xs <~~> z # ys\"\n| trans [intro]: \"xs <~~> ys \\<Longrightarrow> ys <~~> zs \\<Longrightarrow> xs <~~> zs\"\n\nproposition perm_refl [iff]: \"l <~~> l\"\n  by (induct l) auto\n\n\nsubsection \\<open>Some examples of rule induction on permutations\\<close>\n\nproposition perm_empty_imp: \"[] <~~> ys \\<Longrightarrow> ys = []\"\n  by (induction \"[] :: 'a list\" ys pred: perm) simp_all\n\n\ntext \\<open>\\medskip This more general theorem is easier to understand!\\<close>\n\nproposition perm_length: \"xs <~~> ys \\<Longrightarrow> length xs = length ys\"\n  by (induct pred: perm) simp_all\n\nproposition perm_sym: \"xs <~~> ys \\<Longrightarrow> ys <~~> xs\"\n  by (induct pred: perm) auto\n\n\nsubsection \\<open>Ways of making new permutations\\<close>\n\ntext \\<open>We can insert the head anywhere in the list.\\<close>\n\nproposition perm_append_Cons: \"a # xs @ ys <~~> xs @ a # ys\"\n  by (induct xs) auto\n\nproposition perm_append_swap: \"xs @ ys <~~> ys @ xs\"\n  by (induct xs) (auto intro: perm_append_Cons)\n\nproposition perm_append_single: \"a # xs <~~> xs @ [a]\"\n  by (rule perm.trans [OF _ perm_append_swap]) simp\n\nproposition perm_rev: \"rev xs <~~> xs\"\n  by (induct xs) (auto intro!: perm_append_single intro: perm_sym)\n\nproposition perm_append1: \"xs <~~> ys \\<Longrightarrow> l @ xs <~~> l @ ys\"\n  by (induct l) auto\n\nproposition perm_append2: \"xs <~~> ys \\<Longrightarrow> xs @ l <~~> ys @ l\"\n  by (blast intro!: perm_append_swap perm_append1)\n\n\nsubsection \\<open>Further results\\<close>\n\nproposition perm_empty [iff]: \"[] <~~> xs \\<longleftrightarrow> xs = []\"\n  by (blast intro: perm_empty_imp)\n\nproposition perm_empty2 [iff]: \"xs <~~> [] \\<longleftrightarrow> xs = []\"\n  using perm_sym by auto\n\nproposition perm_sing_imp: \"ys <~~> xs \\<Longrightarrow> xs = [y] \\<Longrightarrow> ys = [y]\"\n  by (induct pred: perm) auto\n\nproposition perm_sing_eq [iff]: \"ys <~~> [y] \\<longleftrightarrow> ys = [y]\"\n  by (blast intro: perm_sing_imp)\n\nproposition perm_sing_eq2 [iff]: \"[y] <~~> ys \\<longleftrightarrow> ys = [y]\"\n  by (blast dest: perm_sym)\n\n\nsubsection \\<open>Removing elements\\<close>\n\nproposition perm_remove: \"x \\<in> set ys \\<Longrightarrow> ys <~~> x # remove1 x ys\"\n  by (induct ys) auto\n\n\n\ntext \\<open>\\medskip Congruence rule\\<close>\n\nproposition perm_remove_perm: \"xs <~~> ys \\<Longrightarrow> remove1 z xs <~~> remove1 z ys\"\n  by (induct pred: perm) auto\n\nproposition remove_hd [simp]: \"remove1 z (z # xs) = xs\"\n  by auto\n\nproposition cons_perm_imp_perm: \"z # xs <~~> z # ys \\<Longrightarrow> xs <~~> ys\"\n  by (drule perm_remove_perm [where z = z]) auto\n\nproposition cons_perm_eq [iff]: \"z#xs <~~> z#ys \\<longleftrightarrow> xs <~~> ys\"\n  by (meson cons_perm_imp_perm perm.Cons)\n\nproposition append_perm_imp_perm: \"zs @ xs <~~> zs @ ys \\<Longrightarrow> xs <~~> ys\"\n  by (induct zs arbitrary: xs ys rule: rev_induct) auto\n\nproposition perm_append1_eq [iff]: \"zs @ xs <~~> zs @ ys \\<longleftrightarrow> xs <~~> ys\"\n  by (blast intro: append_perm_imp_perm perm_append1)\n\nproposition perm_append2_eq [iff]: \"xs @ zs <~~> ys @ zs \\<longleftrightarrow> xs <~~> ys\"\n  by (meson perm.trans perm_append1_eq perm_append_swap)\n\nproposition prem_seteq: \"xs <~~> ys \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> x \\<in> set ys\"\nproof(induct xs arbitrary:ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case\n  proof(cases \"x = a\")\n    case True\n    then show ?thesis using Cons \n      by (metis (no_types, opaque_lifting) dual_order.refl impossible_Cons perm_length \n          perm_remove_perm remove1_idem remove_hd)\n  next\n    case False\n    have 1: \"x \\<in> set xs\"\n      using False Cons by simp\n    have 2: \"xs <~~> remove1 a ys\"\n      using Cons(2) perm_remove_perm by (metis remove_hd)\n    then show ?thesis using 1 Cons(1) by (metis notin_set_remove1)\n  qed\nqed\n\nproposition distinct_perm: \"xs <~~> ys \\<Longrightarrow> distinct xs \\<Longrightarrow> distinct ys\"\nproof(induct xs arbitrary:ys)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  have tmp1: \"xs <~~> remove1 x ys\"\n    using Cons(2) perm_remove_perm by (metis remove_hd)\n  have tmp2: \"distinct (remove1 x ys)\"\n    using Cons(1,3) tmp1 by auto\n  have tmp3: \"x \\<notin> set xs\"\n    using Cons by simp\n  have tmp4: \"x \\<notin> set (remove1 x ys)\"\n    using Cons tmp1 by (meson perm_sym prem_seteq tmp3)\n  have tmp5: \"x \\<in> set ys\"\n    using Cons(2) by (simp add: prem_seteq)\n  have tmp6: \"set (x#(remove1 x ys)) = set ys\"\n    using tmp4 tmp5 \n    by (metis (mono_tags, opaque_lifting) equalityI insert_subset list.set(2) \n        perm_remove prem_seteq set_remove1_subset subsetI)\n  then show ?case using tmp2 tmp3 tmp4 tmp5\n    by (metis Cons.prems(1) card_distinct distinct.simps(2) distinct_card length_Cons perm_length tmp1)\n    \nqed\n\nlemma perm_remove2: \"x \\<in> set ys \\<Longrightarrow> xs <~~> remove1 x ys \\<Longrightarrow> x#xs <~~> ys\"\nproof(induct ys arbitrary:xs)\n  case Nil\n  then show ?case using perm_remove by fastforce\nnext\n  case (Cons a ys)\n  then show ?case\n  proof(cases \"x = a\")\n    case True\n    then show ?thesis using Cons(3) unfolding remove1.simps by auto\n  next\n    case False\n    then show ?thesis using Cons by (meson perm.Cons perm.trans perm_remove perm_sym)\n  qed\nqed\n\nlemma perm_remove3: \"x \\<in> set ys \\<Longrightarrow> ys@xs <~~> (remove1 x ys)@xs@[x]\"\nproof(induct ys)\n  case Nil\n  then show ?case using perm_remove by fastforce\nnext\n  case (Cons a ys)\n  then show ?case\n  proof(cases \"x = a\")\n    case True\n    then show ?thesis unfolding remove1.simps by (metis (mono_tags, lifting) append_Cons \n          append_eq_appendI perm_append_single)\n  next\n    case False\n    then show ?thesis using Cons by simp\n  qed\nqed\n\nend\n", "meta": {"author": "bzhan", "repo": "mars", "sha": "d10e489a8ddf128a4cbac13291efdece458d732d", "save_path": "github-repos/isabelle/bzhan-mars", "path": "github-repos/isabelle/bzhan-mars/mars-d10e489a8ddf128a4cbac13291efdece458d732d/Semantics_Simulink/Permutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.908617893221035, "lm_q1q2_score": 0.7910402467132477}}
{"text": "section \\<open>Basic Randomized Algorithms\\label{sec:basic_randomized_algorithms}\\<close>\n\ntext \\<open>This section introduces a few randomized algorithms for well-known distributions. These both\nserve as building blocks for more complex algorithms and as examples describing how to use the\nframework.\\<close>\n\ntheory Basic_Randomized_Algorithms\n  imports\n    Randomized_Algorithm\n    Probabilistic_While.Bernoulli\n    Probabilistic_While.Geometric\n    Permuted_Congruential_Generator\nbegin\n\ntext \\<open>A simple example: Here we define a randomized algorithm that can sample uniformly from\n@{term \"pmf_of_set {..<(2::nat)^n}\"}. (The same problem for general ranges is discussed in\nSection~\\ref{sec:dice_roll}).\\<close>\n\nfun binary_dice_roll :: \"nat \\<Rightarrow> nat random_alg\"\n  where\n    \"binary_dice_roll 0 = return_ra 0\" |\n    \"binary_dice_roll (Suc n) =\n      do { h \\<leftarrow> binary_dice_roll n;\n           c \\<leftarrow> coin_ra;\n           return_ra (of_bool c + 2 * h)\n        }\"\n\ntext \\<open>Because the algorithm terminates unconditionally it is easy to verify that\n@{term \"binary_dice_roll\"} terminates almost surely:\\<close>\n\nlemma binary_dice_roll_terminates: \"terminates_almost_surely (binary_dice_roll n)\"\n  by (induction n) (auto intro:terminates_almost_surely_intros)\n\ntext \\<open>The corresponding PMF can be written as:\\<close>\n\nfun binary_dice_roll_pmf :: \"nat \\<Rightarrow> nat pmf\"\n  where\n    \"binary_dice_roll_pmf 0 = return_pmf 0\" |\n    \"binary_dice_roll_pmf (Suc n) =\n      do { h \\<leftarrow> binary_dice_roll_pmf n;\n           c \\<leftarrow> coin_pmf;\n           return_pmf (of_bool c + 2 * h)\n        }\"\n\ntext \\<open>To verify that the distribution of the result of @{term \"binary_dice_roll\"} is\n@{term \"binary_dice_roll_pmf\"} we can rely on the @{thm [source] pmf_of_ra_simps} simp rules\nand the @{thm [source] \"terminates_almost_surely_intros\"} introduction rules:\\<close>\n\nlemma \"pmf_of_ra (binary_dice_roll n) = binary_dice_roll_pmf n\"\n  using binary_dice_roll_terminates\n  by (induction n) (simp_all add:terminates_almost_surely_intros pmf_of_ra_simps)\n\ntext \\<open>Let us now consider an algorithm that does not terminate unconditionally but just almost\nsurely:\\<close>\n\npartial_function (random_alg) binary_geometric :: \"nat \\<Rightarrow> nat random_alg\"\n  where\n    \"binary_geometric n =\n      do { c \\<leftarrow> coin_ra;\n           if c then (return_ra n) else binary_geometric (n+1)\n        }\"\n\ntext \\<open>This is necessary for running randomized algorithms defined with the\n@{command \"partial_function\"} directive:\\<close>\ndeclare binary_geometric.simps[code]\n\ntext \\<open>In this case, we need to map to an SPMF:\\<close>\n\npartial_function (spmf) binary_geometric_spmf :: \"nat \\<Rightarrow> nat spmf\"\n  where\n    \"binary_geometric_spmf n =\n      do { c \\<leftarrow> coin_spmf;\n           if c then (return_spmf n) else binary_geometric_spmf (n+1)\n        }\"\n\ntext \\<open>We use the transfer rules for @{term \"spmf_of_ra\"} to show the correspondence:\\<close>\n\nlemma binary_geometric_ra_correct:\n  \"spmf_of_ra (binary_geometric x) = binary_geometric_spmf x\"\nproof -\n  include lifting_syntax\n  have \"((=) ===> rel_spmf_of_ra) binary_geometric_spmf binary_geometric\"\n    unfolding binary_geometric_def binary_geometric_spmf_def\n    apply (rule fixp_ra_parametric[OF binary_geometric_spmf.mono binary_geometric.mono])\n    by transfer_prover\n  thus ?thesis\n    unfolding rel_fun_def rel_spmf_of_ra_def by auto\nqed\n\ntext \\<open>Bernoulli distribution: For this example we show correspondence with the already existing\ndefinition of @{term \"bernoulli\"} SPMF.\\<close>\n\npartial_function (random_alg) bernoulli_ra :: \"real \\<Rightarrow> bool random_alg\" where\n  \"bernoulli_ra p = do {\n     b \\<leftarrow> coin_ra;\n     if b then return_ra (p \\<ge> 1 / 2)\n     else if p < 1 / 2 then bernoulli_ra (2 * p)\n     else bernoulli_ra (2 * p - 1)\n   }\"\n\ndeclare bernoulli_ra.simps[code]\n\ntext \\<open>The following is a different technique to show equivalence of an SPMF with a randomized\nalgorithm. It only works if the SPMF has weight $1$. First we show that the SPMF is a lower\nbound:\\<close>\n\nlemma bernoulli_ra_correct_aux: \"ord_spmf (=) (bernoulli x) (spmf_of_ra (bernoulli_ra x))\"\nproof (induction arbitrary:x rule:bernoulli.fixp_induct)\n  case 1\n  thus ?case by simp\nnext\n  case 2\n  thus ?case by simp\nnext\n  case (3 p)\n  thus ?case by (subst bernoulli_ra.simps)\n      (auto intro:ord_spmf_bind_reflI simp:spmf_of_ra_simps)\nqed\n\ntext \\<open>Then relying on the fact that the SPMF has weight one, we can derive equivalence:\\<close>\n\nlemma bernoulli_ra_correct: \"bernoulli x = spmf_of_ra (bernoulli_ra x)\"\n  using lossless_bernoulli weight_spmf_le_1 unfolding lossless_spmf_def\n  by (intro eq_iff_ord_spmf[OF _ bernoulli_ra_correct_aux]) auto\n\ntext \\<open>Because @{term \"bernoulli p\"} is a lossless SPMF equivalent to\n@{term \"spmf_of_pmf (bernoulli_pmf p)\"} it is also possible to express the above, without referring\nto SPMFs:\\<close>\n\nlemma\n  \"terminates_almost_surely (bernoulli_ra p)\"\n  \"bernoulli_pmf p = pmf_of_ra (bernoulli_ra p)\"\n  unfolding terminates_almost_surely_def pmf_of_ra_def bernoulli_ra_correct[symmetric]\n  by (simp_all add: bernoulli_eq_bernoulli_pmf pmf_of_spmf)\n\ncontext\n  includes lifting_syntax\nbegin\n\nlemma bernoulli_ra_transfer [transfer_rule]:\n  \"((=) ===> rel_spmf_of_ra) bernoulli bernoulli_ra\"\n  unfolding rel_fun_def rel_spmf_of_ra_def bernoulli_ra_correct by simp\n\nend\n\ntext \\<open>Using the randomized algorithm for the Bernoulli distribution, we can introduce one for the\ngeneral geometric distribution:\\<close>\n\npartial_function (random_alg) geometric_ra :: \"real \\<Rightarrow> nat random_alg\" where\n  \"geometric_ra p = do {\n     b \\<leftarrow> bernoulli_ra p;\n     if b then return_ra 0 else map_ra ((+) 1) (geometric_ra p)\n  }\"\ndeclare geometric_ra.simps[code]\n\nlemma geometric_ra_correct: \"spmf_of_ra (geometric_ra x) = geometric_spmf x\"\nproof -\n  include lifting_syntax\n  have \"((=) ===> rel_spmf_of_ra) geometric_spmf geometric_ra\"\n    unfolding geometric_ra_def geometric_spmf_def\n    apply (rule fixp_ra_parametric[OF geometric_spmf.mono geometric_ra.mono])\n    by transfer_prover\n  thus ?thesis\n    unfolding rel_fun_def rel_spmf_of_ra_def by auto\nqed\n\ntext \\<open>Replication of a distribution\\<close>\n\nfun replicate_ra :: \"nat \\<Rightarrow> 'a random_alg \\<Rightarrow> 'a list random_alg\"\n  where\n    \"replicate_ra 0 f = return_ra []\" |\n    \"replicate_ra (Suc n) f = do { xh \\<leftarrow> f; xt \\<leftarrow> replicate_ra n f; return_ra (xh#xt) }\"\n\nfun replicate_spmf :: \"nat \\<Rightarrow> 'a spmf \\<Rightarrow> 'a list spmf\"\n  where\n    \"replicate_spmf 0 f = return_spmf []\" |\n    \"replicate_spmf (Suc n) f = do { xh \\<leftarrow> f; xt \\<leftarrow> replicate_spmf n f; return_spmf (xh#xt) }\"\n\nlemma replicate_ra_correct: \"spmf_of_ra (replicate_ra n f) = replicate_spmf n (spmf_of_ra f)\"\n  by (induction n) (auto simp :spmf_of_ra_simps)\n\nlemma replicate_spmf_of_pmf: \"replicate_spmf n (spmf_of_pmf f) = spmf_of_pmf (replicate_pmf n f)\"\n  by (induction n) (simp_all add:spmf_of_pmf_bind)\n\ntext \\<open>Binomial distribution\\<close>\n\ndefinition binomial_ra :: \"nat \\<Rightarrow> real \\<Rightarrow> nat random_alg\"\n  where \"binomial_ra n p = map_ra (length \\<circ> filter id) (replicate_ra n (bernoulli_ra p))\"\n\nlemma\n  assumes \"p \\<in> {0..1}\"\n  shows \"spmf_of_ra (binomial_ra n p) = spmf_of_pmf (binomial_pmf n p)\"\nproof -\n  have \"spmf_of_ra (replicate_ra n (bernoulli_ra p))=spmf_of_pmf(replicate_pmf n (bernoulli_pmf p))\"\n    unfolding replicate_ra_correct bernoulli_ra_correct[symmetric] bernoulli_eq_bernoulli_pmf\n    by (simp add:replicate_spmf_of_pmf)\n\n  thus ?thesis\n    unfolding binomial_pmf_altdef[OF assms] binomial_ra_def\n    by (simp flip:map_spmf_of_pmf add:spmf_of_ra_map)\nqed\n\ntext \\<open>Running randomized algorithms: Here we use the PRG introduced in\nSection~\\ref{sec:permuted_congruential_generator}.\\<close>\n\nvalue \"run_ra (binomial_ra 10 0.5) (random_coins 42)\"\n\nvalue \"run_ra (replicate_ra 20 (bernoulli_ra 0.3)) (random_coins 42)\"\n\nend", "meta": {"author": "ekarayel", "repo": "random_code_gen", "sha": "master", "save_path": "github-repos/isabelle/ekarayel-random_code_gen", "path": "github-repos/isabelle/ekarayel-random_code_gen/random_code_gen-main/Random_Code_Generation/Basic_Randomized_Algorithms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.8947894661025424, "lm_q1q2_score": 0.7910290341934919}}
{"text": "section \\<open>Maximum Segment Sum\\<close>\n\ntheory Maximum_Segment_Sum\n  imports Main\nbegin\n\ntext \\<open>The \\emph{maximum segment sum} problem is to compute, given a list of numbers,\nthe largest of the sums of the contiguous segments of that list. It is also known\nas the \\emph{maximum sum subarray} problem and has been considered many times in the literature;\nthe Wikipedia article ``Maximum subarray problem''\n\\<^url>\\<open>https://en.wikipedia.org/wiki/Maximum_subarray_problem\\<close> is a good starting point.\n\nWe assume that the elements of the list are not necessarily numbers but just elements\nof some linearly ordered group.\\<close>\n\nclass linordered_group_add = linorder + group_add +\nassumes add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\nassumes add_right_mono: \"a \\<le> b \\<Longrightarrow> a + c \\<le> b + c\"\nbegin\n\nlemma max_add_distrib_left: \"max y z + x = max (y+x) (z+x)\"\nby (metis add_right_mono max.absorb_iff1 max_def)\n\nlemma max_add_distrib_right: \"x + max y z = max (x+y) (x+z)\"\nby (metis add_left_mono max.absorb1 max.cobounded2 max_def)\n\nsubsection \\<open>Naive Solution\\<close>\n\nfun mss_rec_naive_aux :: \"'a list \\<Rightarrow> 'a\" where\n  \"mss_rec_naive_aux [] = 0\"\n| \"mss_rec_naive_aux (x#xs) = max 0 (x + mss_rec_naive_aux xs)\"\n\nfun mss_rec_naive :: \"'a list \\<Rightarrow> 'a\" where\n  \"mss_rec_naive [] = 0\"\n| \"mss_rec_naive (x#xs) = max (mss_rec_naive_aux (x#xs)) (mss_rec_naive xs)\"\n\ndefinition fronts :: \"'a list \\<Rightarrow> 'a list set\" where\n  \"fronts xs = {as. \\<exists>bs. xs = as @ bs}\"\n\ndefinition \"front_sums xs \\<equiv> sum_list ` fronts xs\"\n\nlemma fronts_cons: \"fronts (x#xs) = ((#) x) ` fronts xs \\<union> {[]}\" (is \"?l = ?r\")\nproof\n  show \"?l \\<subseteq> ?r\"\n  proof\n    fix as assume \"as \\<in> ?l\"\n    then show \"as \\<in> ?r\" by (cases as) (auto simp: fronts_def)\n  qed\n  show \"?r \\<subseteq> ?l\" unfolding fronts_def by auto\nqed\n\nlemma front_sums_cons: \"front_sums (x#xs) = (+) x ` front_sums xs \\<union> {0}\"\nproof -\n  have \"sum_list ` ((#) x) ` fronts xs = (+) x ` front_sums xs\" unfolding front_sums_def by force\n  then show ?thesis by (simp add: front_sums_def fronts_cons)\nqed\n\nlemma finite_fronts: \"finite (fronts xs)\"\n  by (induction xs) (simp add: fronts_def, simp add: fronts_cons)\n\nlemma finite_front_sums: \"finite (front_sums xs)\"\n  using front_sums_def finite_fronts by simp\n\nlemma front_sums_not_empty: \"front_sums xs \\<noteq> {}\"\n  unfolding front_sums_def fronts_def using image_iff by fastforce\n\nlemma max_front_sum: \"Max (front_sums (x#xs)) = max 0 (x + Max (front_sums xs))\"\nusing finite_front_sums front_sums_not_empty\nby (auto simp add: front_sums_cons hom_Max_commute max_add_distrib_right)\n\nlemma mss_rec_naive_aux_front_sums: \"mss_rec_naive_aux xs = Max (front_sums xs)\"\nby (induction xs) (simp add: front_sums_def fronts_def, auto simp: max_front_sum)\n\nlemma front_sums: \"front_sums xs = {s. \\<exists>as bs. xs = as @ bs \\<and> s = sum_list as}\"\nunfolding front_sums_def fronts_def by auto\n\nlemma mss_rec_naive_aux: \"mss_rec_naive_aux xs = Max {s. \\<exists>as bs. xs = as @ bs \\<and> s = sum_list as}\"\nusing front_sums mss_rec_naive_aux_front_sums by simp\n  \n\ndefinition mids :: \"'a list \\<Rightarrow> 'a list set\" where\n  \"mids xs \\<equiv> {bs. \\<exists>as cs. xs = as @ bs @ cs}\"\n\ndefinition \"mid_sums xs \\<equiv> sum_list ` mids xs\"\n\nlemma fronts_mids: \"bs \\<in> fronts xs \\<Longrightarrow> bs \\<in> mids xs\"\nunfolding fronts_def mids_def by auto\n\nlemma mids_mids_cons: \"bs \\<in> mids xs \\<Longrightarrow> bs \\<in> mids (x#xs)\"\nproof-\n  fix bs assume \"bs \\<in> mids xs\"\n  then obtain as cs where \"xs = as @ bs @ cs\" unfolding mids_def by blast\n  then have \"x # xs = (x#as) @ bs @ cs\" by simp\n  then show \"bs \\<in> mids (x#xs)\" unfolding mids_def by blast\nqed\n\nlemma mids_cons: \"mids (x#xs) = fronts (x#xs) \\<union> mids xs\" (is \"?l = ?r\")\nproof\n  show \"?l \\<subseteq> ?r\"\n  proof\n    fix bs assume \"bs \\<in> ?l\"\n    then obtain as cs where as_bs_cs: \"(x#xs) = as @ bs @ cs\" unfolding mids_def by blast\n    then show \"bs \\<in> ?r\"\n    proof (cases as)\n      case Nil\n      then have \"bs \\<in> fronts (x#xs)\" by (simp add: fronts_def as_bs_cs)\n      then show ?thesis by simp\n    next\n      case (Cons a as')\n      then have \"xs = as' @ bs @ cs\" using as_bs_cs by simp\n      then show ?thesis unfolding mids_def by auto\n    qed\n  qed\n  show \"?r \\<subseteq> ?l\" using fronts_mids mids_mids_cons by auto\nqed\n\nlemma mid_sums_cons: \"mid_sums (x#xs) = front_sums (x#xs) \\<union> mid_sums xs\"\n  unfolding mid_sums_def by (auto simp: mids_cons front_sums_def)\n\nlemma finite_mids: \"finite (mids xs)\"\n  by (induction xs) (simp add: mids_def, simp add: mids_cons finite_fronts)\n\nlemma finite_mid_sums: \"finite (mid_sums xs)\"\n  by (simp add: mid_sums_def finite_mids)\n\nlemma mid_sums_not_empty: \"mid_sums xs \\<noteq> {}\"\n  unfolding mid_sums_def mids_def by blast\n\nlemma max_mid_sums_cons: \"Max (mid_sums (x#xs)) = max (Max (front_sums (x#xs))) (Max (mid_sums xs))\"\n  by (auto simp: mid_sums_cons Max_Un finite_front_sums finite_mid_sums front_sums_not_empty mid_sums_not_empty)\n\nlemma mss_rec_naive_max_mid_sum: \"mss_rec_naive xs = Max (mid_sums xs)\"\n  by (induction xs) (simp add: mid_sums_def mids_def, auto simp: max_mid_sums_cons mss_rec_naive_aux front_sums)\n\nlemma mid_sums: \"mid_sums xs = {s. \\<exists>as bs cs. xs = as @ bs @ cs \\<and> s = sum_list bs}\"\n  by (auto simp: mid_sums_def mids_def)\n\ntheorem mss_rec_naive: \"mss_rec_naive xs = Max {s. \\<exists>as bs cs. xs = as @ bs @ cs \\<and> s = sum_list bs}\"\n  unfolding mss_rec_naive_max_mid_sum mid_sums by simp\n\n\nsubsection \\<open>Kadane's Algorithms\\<close>\n\nfun kadane :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"kadane [] cur m = m\"\n| \"kadane (x#xs) cur m =\n    (let cur' = max (cur + x) x in\n      kadane xs cur' (max m cur'))\"\n\ndefinition \"mss_kadane xs \\<equiv> kadane xs 0 0\"\n\nlemma Max_front_sums_geq_0: \"Max (front_sums xs) \\<ge> 0\"\nproof-\n  have \"[] \\<in> fronts xs\" unfolding fronts_def by blast\n  then have \"0 \\<in> front_sums xs\" unfolding front_sums_def by force\n  then show ?thesis using finite_front_sums Max_ge by simp\nqed\n\nlemma Max_mid_sums_geq_0: \"Max (mid_sums xs) \\<ge> 0\"\nproof-\n  have \"0 \\<in> mid_sums xs\" unfolding mid_sums_def mids_def by force\n  then show ?thesis using finite_mid_sums Max_ge by simp\nqed\n\nlemma kadane: \"m \\<ge> cur \\<Longrightarrow> m \\<ge> 0 \\<Longrightarrow> kadane xs cur m = max m (max (cur + Max (front_sums xs)) (Max (mid_sums xs)))\"\nproof (induction xs cur m rule: kadane.induct)\n  case (1 cur m)\n  then show ?case unfolding front_sums_def fronts_def mid_sums_def mids_def by auto\nnext\n  case (2 x xs cur m)\n  then show ?case\n    apply (auto simp: max_front_sum max_mid_sums_cons Let_def)\n    by (smt (verit, ccfv_threshold) Max_front_sums_geq_0 add_assoc add_0_right max.assoc max.coboundedI1 max.left_commute max.orderE max_add_distrib_left max_add_distrib_right)\nqed\n\nlemma Max_front_sums_leq_Max_mid_sums: \"Max (front_sums xs) \\<le> Max (mid_sums xs)\"\nproof-\n  have \"front_sums xs \\<subseteq> mid_sums xs\" unfolding front_sums_def mid_sums_def using fronts_mids subset_iff by blast\n  then show ?thesis using front_sums_not_empty finite_mid_sums Max_mono by blast\nqed\n\nlemma mss_kadane_mid_sums: \"mss_kadane xs = Max (mid_sums xs)\"\n  unfolding mss_kadane_def using kadane Max_mid_sums_geq_0 Max_front_sums_leq_Max_mid_sums by auto\n\ntheorem mss_kadane: \"mss_kadane xs = Max {s. \\<exists>as bs cs. xs = as @ bs @ cs \\<and> s = sum_list bs}\"\n  using mss_kadane_mid_sums mid_sums by auto\n\nend\n\nend", "meta": {"author": "22slin22", "repo": "verified-maximum-segment-sum", "sha": "4dcb8ca1aa72c68f737a40dd598d9dc2c8ec0323", "save_path": "github-repos/isabelle/22slin22-verified-maximum-segment-sum", "path": "github-repos/isabelle/22slin22-verified-maximum-segment-sum/verified-maximum-segment-sum-4dcb8ca1aa72c68f737a40dd598d9dc2c8ec0323/Maximum_Segment_Sum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8962513710552469, "lm_q1q2_score": 0.7908771907095388}}
{"text": "header {* Generators *}\n\ntheory \"Generators\"\nimports\n   \"~~/src/HOL/Algebra/Group\"\n   \"~~/src/HOL/Algebra/Lattice\"\nbegin\n\n\ntext {* This theory is not specific to Free Groups and could be moved to a more \ngeneral place. It defines the subgroup generated by a set of generators and\nthat homomorphisms agree on the generated subgroup if they agree on the\ngenerators. *}\n\nnotation subgroup (infix \"\\<le>\" 80)\n\nsubsection {* The subgroup generated by a set *}\n\ntext {* The span of a set of subgroup generators, i.e. the generated subgroup, can\nbe defined inductively or as the intersection of all subgroups containing the\ngenerators. Here, we define it inductively and proof the equivalence *}\n\ninductive_set gen_span :: \"('a,'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" (\"\\<langle>_\\<rangle>\\<index>\")\n  for G and gens\nwhere gen_one [intro!, simp]: \"\\<one>\\<^bsub>G\\<^esub> \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    | gen_gens: \"x \\<in> gens \\<Longrightarrow> x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    | gen_inv: \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> inv\\<^bsub>G\\<^esub> x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    | gen_mult: \"\\<lbrakk> x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>; y \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<rbrakk> \\<Longrightarrow>  x \\<otimes>\\<^bsub>G\\<^esub> y \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n\nlemma (in group) gen_span_closed:\n  assumes \"gens \\<subseteq> carrier G\"\n  shows \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\"\nproof (* How can I do this in one \"by\" line? *)\n  fix x\n  from assms show \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> x \\<in> carrier G\"\n    by -(induct rule:gen_span.induct, auto)\nqed\n\nlemma (in group) gen_subgroup_is_subgroup: \n      \"gens \\<subseteq> carrier G \\<Longrightarrow> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<le> G\"\nby(rule subgroupI)(auto intro:gen_span.intros simp add:gen_span_closed)\n\nlemma (in group) gen_subgroup_is_smallest_containing:\n  assumes \"gens \\<subseteq> carrier G\"\n    shows \"\\<Inter>{H. H \\<le> G \\<and> gens \\<subseteq> H} = \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\nproof\n  show \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> \\<Inter>{H. H \\<le> G \\<and> gens \\<subseteq> H}\"\n  proof(rule Inf_greatest)\n    fix H\n    assume \"H \\<in> {H. H \\<le> G \\<and> gens \\<subseteq> H}\"\n    hence \"H \\<le> G\" and \"gens \\<subseteq> H\" by auto\n    show \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> H\"\n    proof\n      fix x\n      from `H \\<le> G` and `gens \\<subseteq> H`\n      show \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> x \\<in> H\"\n       unfolding subgroup_def\n       by -(induct rule:gen_span.induct, auto)\n    qed\n  qed\nnext\n  from `gens \\<subseteq> carrier G`\n  have \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<le> G\" by (rule gen_subgroup_is_subgroup)\n  moreover\n  have \"gens \\<subseteq> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\" by (auto intro:gen_span.intros)\n  ultimately\n  show \"\\<Inter>{H. H \\<le> G \\<and> gens \\<subseteq> H} \\<subseteq> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n    by(auto intro:Inter_lower)\nqed\n\nsubsection {* Generators and homomorphisms *}\n\ntext {* Two homorphisms agreeing on some elements agree on the span of those elements.*}\n\nlemma hom_unique_on_span:\n  assumes \"group G\"\n      and \"group H\"\n      and \"gens \\<subseteq> carrier G\"\n      and \"h \\<in> hom G H\"\n      and \"h' \\<in> hom G H\"\n      and \"\\<forall>g \\<in> gens. h g = h' g\"\n  shows \"\\<forall>x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>. h x = h' x\"\nproof\n  interpret G: group G by fact\n  interpret H: group H by fact\n  interpret h: group_hom G H h by unfold_locales fact\n  interpret h': group_hom G H h' by unfold_locales fact\n\n  fix x\n  from `gens \\<subseteq> carrier G` have \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\" by (rule G.gen_span_closed)\n  with assms show \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<Longrightarrow> h x = h' x\" apply -\n  proof(induct rule:gen_span.induct)\n    case (gen_mult x y)\n      hence x: \"x \\<in> carrier G\" and y: \"y \\<in> carrier G\" and\n            hx: \"h x = h' x\" and hy: \"h y = h' y\" by auto\n      thus \"h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h' (x \\<otimes>\\<^bsub>G\\<^esub> y)\" by simp\n  qed auto\nqed\n\nsubsection {* Sets of generators *}\n\ntext {* There is no definition for ``@{text gens} is a generating set of\n@{text G}''. This is easily expressed by @{text \"\\<langle>gens\\<rangle> = carrier G\"}. *}\n\ntext {* The following is an application of @{text hom_unique_on_span} on a\ngenerating set of the whole group. *}\n\nlemma (in group) hom_unique_by_gens:\n  assumes \"group H\"\n      and gens: \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> = carrier G\"\n      and \"h \\<in> hom G H\"\n      and \"h' \\<in> hom G H\"\n      and \"\\<forall>g \\<in> gens. h g = h' g\"\n  shows \"\\<forall>x \\<in> carrier G. h x = h' x\"\nproof\n  fix x\n\n  from gens have \"gens \\<subseteq> carrier G\" by (auto intro:gen_span.gen_gens)\n  with assms and group_axioms have r: \"\\<forall>x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>. h x = h' x\"\n    by -(erule hom_unique_on_span, auto)\n  with gens show \"x \\<in> carrier G \\<Longrightarrow> h x = h' x\" by auto\nqed\n\nlemma (in group_hom) hom_span:\n  assumes \"gens \\<subseteq> carrier G\"\n  shows \"h ` (\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>) = \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\nproof(rule Set.set_eqI, rule iffI)\n  from `gens \\<subseteq> carrier G`\n  have \"\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G\" by (rule G.gen_span_closed)\n\n  fix y\n  assume \"y \\<in> h ` \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\"\n  then obtain x where \"x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>\" and \"y = h x\" by auto\n  from `x \\<in> \\<langle>gens\\<rangle>\\<^bsub>G\\<^esub>`\n  have \"h x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n  proof(induct x)\n    case (gen_inv x)\n    hence \"x \\<in> carrier G\" and \"h x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n      using `\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G`\n      by auto\n    thus ?case by (auto intro:gen_span.intros)\n  next\n    case (gen_mult x y)\n    hence \"x \\<in> carrier G\" and \"h x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n    and   \"y \\<in> carrier G\" and \"h y \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\"\n      using `\\<langle>gens\\<rangle>\\<^bsub>G\\<^esub> \\<subseteq> carrier G`\n      by auto\n    thus ?case by (auto intro:gen_span.intros)\n  qed(auto intro: gen_span.intros)\n  with `y = h x`\n  show \"y \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub>\" by simp\nnext\n  fix x\n  show \"x \\<in> \\<langle>h ` gens\\<rangle>\\<^bsub>H\\<^esub> \\<Longrightarrow> x \\<in> h ` \\<langle>gens\\<rangle>\"\n  proof(induct x rule:gen_span.induct)\n    case (gen_inv y)\n      then  obtain x where \"y = h x\" and \"x \\<in> \\<langle>gens\\<rangle>\" by auto\n      moreover\n      hence \"x \\<in> carrier G\"  using `gens \\<subseteq> carrier G` \n        by (auto dest:G.gen_span_closed)\n      ultimately show ?case \n        by (auto intro:hom_inv[THEN sym] rev_image_eqI gen_span.gen_inv simp del:group_hom.hom_inv hom_inv)\n  next\n   case (gen_mult y y')\n      then  obtain x and x'\n        where \"y = h x\" and \"x \\<in> \\<langle>gens\\<rangle>\"\n        and \"y' = h x'\" and \"x' \\<in> \\<langle>gens\\<rangle>\" by auto\n      moreover\n      hence \"x \\<in> carrier G\" and \"x' \\<in> carrier G\" using `gens \\<subseteq> carrier G` \n        by (auto dest:G.gen_span_closed)\n      ultimately show ?case\n        by (auto intro:hom_mult[THEN sym] rev_image_eqI gen_span.gen_mult simp del:group_hom.hom_mult hom_mult)\n  qed(auto intro:rev_image_eqI intro:gen_span.intros)\nqed\n\n\nsubsection {* Product of a list of group elements *}\n\ntext {* Not strictly related to generators of groups, this is still a general\ngroup concept and not related to Free Groups. *}\n\nabbreviation (in monoid) m_concat\n  where \"m_concat l \\<equiv> foldr (op \\<otimes>) l \\<one>\"\n\nlemma (in monoid) m_concat_closed[simp]:\n \"set l \\<subseteq> carrier G \\<Longrightarrow> m_concat l \\<in> carrier G\"\n  by (induct l, auto)\n\nlemma (in monoid) m_concat_append[simp]:\n  assumes \"set a \\<subseteq> carrier G\"\n      and \"set b \\<subseteq> carrier G\"\n  shows \"m_concat (a@b) = m_concat a \\<otimes> m_concat b\"\nusing assms\nby(induct a)(auto simp add: m_assoc)\n\nlemma (in monoid) m_concat_cons[simp]:\n  \"\\<lbrakk> x \\<in> carrier G ; set xs \\<subseteq> carrier G \\<rbrakk> \\<Longrightarrow> m_concat (x#xs) = x \\<otimes> m_concat xs\"\nby(induct xs)(auto simp add: m_assoc)\n\n\n\n\nlemma (in monoid) m_concat_power[simp]: \"x \\<in> carrier G \\<Longrightarrow> m_concat (replicate n x) = x (^) n\"\nby(induct n, auto simp add:nat_pow_mult1l)\n\n\nsubsection {* Isomorphisms *}\n\ntext {* A nicer way of proving that something is a group homomorphism or\nisomorphism. *}\n\nlemma group_homI[intro]:\n  assumes range: \"h ` (carrier g1) \\<subseteq> carrier g2\"\n      and hom: \"\\<forall>x\\<in>carrier g1. \\<forall>y\\<in>carrier g1. h (x \\<otimes>\\<^bsub>g1\\<^esub> y) = h x \\<otimes>\\<^bsub>g2\\<^esub> h y\"\n  shows \"h \\<in> hom g1 g2\"\nproof-\n  have \"h \\<in> carrier g1 \\<rightarrow> carrier g2\" using range  by auto\n  thus \"h \\<in> hom g1 g2\" using hom unfolding hom_def by auto\nqed\n\nlemma (in group_hom) hom_injI:\n  assumes \"\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\n  shows \"inj_on h (carrier G)\"\nunfolding inj_on_def\nproof(rule ballI, rule ballI, rule impI)\n  fix x\n  fix y\n  assume x: \"x\\<in>carrier G\"\n     and y: \"y\\<in>carrier G\"\n     and \"h x = h y\"\n  hence \"h (x \\<otimes> inv y) = \\<one>\\<^bsub>H\\<^esub>\" and \"x \\<otimes> inv y \\<in> carrier G\"\n    by auto\n  with assms\n  have \"x \\<otimes> inv y = \\<one>\" by auto\n  thus \"x = y\" using x and y \n    by(auto dest: G.inv_equality)\nqed\n\nlemma (in group_hom) group_hom_isoI:\n  assumes inj1: \"\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\n      and surj: \"h ` (carrier G) = carrier H\"\n  shows \"h \\<in> G \\<cong> H\"\nproof-\n  from inj1\n  have \"inj_on h (carrier G)\" \n    by(auto intro: hom_injI)\n  hence bij: \"bij_betw h (carrier G) (carrier H)\"\n    using surj  unfolding bij_betw_def by auto\n  thus \"h \\<in> G \\<cong> H\"\n    unfolding iso_def by auto\nqed\n\nlemma group_isoI[intro]:\n  assumes G: \"group G\"\n      and H: \"group H\"\n      and inj1: \"\\<forall>x\\<in>carrier G. h x = \\<one>\\<^bsub>H\\<^esub> \\<longrightarrow> x = \\<one>\\<^bsub>G\\<^esub>\"\n      and surj: \"h ` (carrier G) = carrier H\"\n      and hom: \"\\<forall>x\\<in>carrier G. \\<forall>y\\<in>carrier G. h (x \\<otimes>\\<^bsub>G\\<^esub> y) = h x \\<otimes>\\<^bsub>H\\<^esub> h y\"\n  shows \"h \\<in> G \\<cong> H\"\nproof-\n  from surj\n  have \"h \\<in> carrier G \\<rightarrow> carrier H\"\n    by auto\n  then interpret group_hom G H h using G and H and hom\n    by (auto intro!: group_hom.intro group_hom_axioms.intro)\n  show ?thesis\n  using assms unfolding hom_def by (auto intro: group_hom_isoI)\nqed\nend", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Free-Groups/Generators.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.7908771793393305}}
{"text": "section \\<open>Weak and Strong Duality of Linear Programming\\<close>\n\ntheory LP_Duality\n  imports \n    Linear_Inequalities.Farkas_Lemma \n    Minimum_Maximum\nbegin\n\nlemma weak_duality_theorem: \n  fixes A :: \"'a :: linordered_comm_semiring_strict mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and x: \"x \\<in> carrier_vec nc\" \n    and Axb: \"A *\\<^sub>v x \\<le> b\"   \n    and y0: \"y \\<ge> 0\\<^sub>v nr\" \n    and yA: \"A\\<^sup>T *\\<^sub>v y = c\"\n  shows \"c \\<bullet> x \\<le> b \\<bullet> y\" \nproof -\n  from y0 have y: \"y \\<in> carrier_vec nr\" unfolding less_eq_vec_def by auto\n  have \"c \\<bullet> x = (A\\<^sup>T *\\<^sub>v y) \\<bullet> x\" unfolding yA by simp\n  also have \"\\<dots> = y \\<bullet> (A *\\<^sub>v x)\" using x y A by (metis transpose_vec_mult_scalar)\n  also have \"\\<dots> \\<le> y \\<bullet> b\" \n    unfolding scalar_prod_def using A b Axb y0\n    by (auto intro!: sum_mono mult_left_mono simp: less_eq_vec_def)\n  also have \"\\<dots> = b \\<bullet> y\" using y b by (metis comm_scalar_prod)\n  finally show ?thesis . \nqed\n\ncorollary unbounded_primal_solutions:\n  fixes A :: \"'a :: linordered_idom mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and unbounded: \"\\<forall> v. \\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b \\<and> c \\<bullet> x \\<ge> v\" \n  shows \"\\<not> (\\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c)\" \nproof \n  assume \"(\\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c)\" \n  then obtain y where y: \"y \\<ge> 0\\<^sub>v nr\" and Ayc: \"A\\<^sup>T *\\<^sub>v y = c\" \n    by auto\n  from unbounded[rule_format, of \"b \\<bullet> y + 1\"]\n  obtain x where x: \"x \\<in> carrier_vec nc\" and Axb: \"A *\\<^sub>v x \\<le> b\" \n    and le: \"b \\<bullet> y + 1 \\<le> c \\<bullet> x\" by auto\n  from weak_duality_theorem[OF A b c x Axb y Ayc]\n  have \"c \\<bullet> x \\<le> b \\<bullet> y\" by auto\n  with le show False by  auto\nqed\n\ncorollary unbounded_dual_solutions:\n  fixes A :: \"'a :: linordered_idom mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and unbounded: \"\\<forall> v. \\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c \\<and> b \\<bullet> y \\<le> v\"\n  shows \"\\<not> (\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b)\" \nproof\n  assume \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n  then obtain x where x: \"x \\<in> carrier_vec nc\" and Axb: \"A *\\<^sub>v x \\<le> b\" by auto\n  from unbounded[rule_format, of \"c \\<bullet> x - 1\"]\n  obtain y where y: \"y\\<ge>0\\<^sub>v nr\" and Ayc: \"A\\<^sup>T *\\<^sub>v y = c\" and le: \"b \\<bullet> y \\<le> c \\<bullet> x - 1\" by auto\n  from weak_duality_theorem[OF A b c x Axb y Ayc]\n  have \"c \\<bullet> x \\<le> b \\<bullet> y\" by auto\n  with le show False by auto\nqed\n\ntext \\<open>A version of the strong duality theorem which demands\n  that both primal and dual problem are solvable. At this point\n  we do not use min- or max-operations\\<close>\ntheorem strong_duality_theorem_both_sat:\n  fixes A :: \"'a :: trivial_conjugatable_linordered_field mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and primal: \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n    and dual: \"\\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c\"\n  shows \"\\<exists> x y. \n       x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b \\<and> \n       y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c \\<and>\n       c \\<bullet> x = b \\<bullet> y\" \nproof -\n  define M_up where \"M_up = four_block_mat A (0\\<^sub>m nr nr) (mat_of_row (- c)) (mat_of_row b)\" \n  define M_low where \"M_low = four_block_mat (0\\<^sub>m nc nc) (A\\<^sup>T) (0\\<^sub>m nc nc) (- (A\\<^sup>T))\" \n  define M_last where \"M_last = append_cols (0\\<^sub>m nr nc) (- 1\\<^sub>m nr :: 'a mat)\" \n  define M where \"M = (M_up  @\\<^sub>r M_low) @\\<^sub>r M_last\"\n  define bc where \"bc = ((b @\\<^sub>v 0\\<^sub>v 1) @\\<^sub>v (c @\\<^sub>v -c)) @\\<^sub>v (0\\<^sub>v nr)\" \n    (* M = ( A   0) bc = (  b)\n           (-c   b)      (  0)\n           ( 0  At)      (  c)\n           ( 0 -At)      ( -c)\n           ( 0  -I)      (  0) *)\n  let ?nr = \"((nr + 1) + (nc + nc)) + nr\" \n  let ?nc = \"nc + nr\" \n  have M_up: \"M_up \\<in> carrier_mat (nr + 1) ?nc\" \n    unfolding M_up_def using A b c by auto\n  have M_low: \"M_low \\<in> carrier_mat (nc + nc) ?nc\" \n    unfolding M_low_def using A by auto\n  have M_last: \"M_last \\<in> carrier_mat nr ?nc\" \n    unfolding M_last_def by auto\n  have M: \"M \\<in> carrier_mat ?nr ?nc\" \n    using carrier_append_rows[OF carrier_append_rows[OF M_up M_low] M_last]\n    unfolding M_def by auto\n  have bc: \"bc \\<in> carrier_vec ?nr\" unfolding bc_def\n    by (intro append_carrier_vec, insert b c, auto)\n  have \"(\\<exists>xy. xy \\<in> carrier_vec ?nc \\<and> M *\\<^sub>v xy \\<le> bc)\" \n  proof (subst gram_schmidt.Farkas_Lemma'[OF M bc], intro allI impI, elim conjE)\n    fix ulv\n    assume ulv0: \"0\\<^sub>v ?nr \\<le> ulv\" and Mulv: \"M\\<^sup>T *\\<^sub>v ulv = 0\\<^sub>v ?nc\" \n    from ulv0[unfolded less_eq_vec_def]\n    have ulv: \"ulv \\<in> carrier_vec ?nr\" by auto\n    define u1 where \"u1 = vec_first ulv ((nr + 1) + (nc + nc))\" \n    define u2 where \"u2 = vec_first u1 (nr + 1)\" \n    define u3 where \"u3 = vec_last u1 (nc + nc)\" \n    define t where \"t = vec_last ulv nr\" \n    have ulvid: \"ulv = u1 @\\<^sub>v t\" using ulv\n      unfolding u1_def t_def by auto\n    have t: \"t \\<in> carrier_vec nr\" unfolding t_def by auto\n    have u1: \"u1 \\<in> carrier_vec ((nr + 1) + (nc + nc))\" \n      unfolding u1_def by auto\n    have u1id: \"u1 = u2 @\\<^sub>v u3\" using u1\n      unfolding u2_def u3_def by auto\n    have u2: \"u2 \\<in> carrier_vec (nr + 1)\" unfolding u2_def by auto\n    have u3: \"u3 \\<in> carrier_vec (nc + nc)\" unfolding u3_def by auto  \n    define v where \"v = vec_first u3 nc\" \n    define w where \"w = vec_last u3 nc\" \n    have u3id: \"u3 = v @\\<^sub>v w\" using u3\n      unfolding v_def w_def by auto\n    have v: \"v \\<in> carrier_vec nc\" unfolding v_def by auto\n    have w: \"w \\<in> carrier_vec nc\" unfolding w_def by auto  \n\n    define u where \"u = vec_first u2 nr\" \n    define L where \"L = vec_last u2 1\" \n    have u2id: \"u2 = u @\\<^sub>v L\" using u2\n      unfolding u_def L_def by auto\n    have u: \"u \\<in> carrier_vec nr\" unfolding u_def by auto\n    have L: \"L \\<in> carrier_vec 1\" unfolding L_def by auto  \n    define vec1 where \"vec1 = A\\<^sup>T *\\<^sub>v u + mat_of_col (- c) *\\<^sub>v L\" \n    have vec1: \"vec1 \\<in> carrier_vec nc\" \n      unfolding vec1_def mat_of_col_def using A u c L\n      by (meson add_carrier_vec mat_of_row_carrier(1) mult_mat_vec_carrier transpose_carrier_mat uminus_carrier_vec)\n    define vec2 where \"vec2 = A *\\<^sub>v (v - w)\" \n    have vec2: \"vec2 \\<in> carrier_vec nr\"\n      unfolding vec2_def using A v w by auto  \n    define vec3 where \"vec3 = mat_of_col b *\\<^sub>v L\"\n    have vec3: \"vec3 \\<in> carrier_vec nr\" \n      using A b L unfolding mat_of_col_def vec3_def\n      by (meson add_carrier_vec mat_of_row_carrier(1) mult_mat_vec_carrier transpose_carrier_mat uminus_carrier_vec)\n    have Mt: \"M\\<^sup>T = (M_up\\<^sup>T @\\<^sub>c M_low\\<^sup>T) @\\<^sub>c M_last\\<^sup>T\" \n      unfolding M_def append_cols_def by simp\n    have \"M\\<^sup>T *\\<^sub>v ulv = (M_up\\<^sup>T @\\<^sub>c M_low\\<^sup>T) *\\<^sub>v u1 + M_last\\<^sup>T *\\<^sub>v t\" \n      unfolding Mt ulvid\n      by (subst mat_mult_append_cols[OF carrier_append_cols _ u1 t],\n          insert M_up M_low M_last, auto)\n    also have \"M_last\\<^sup>T = 0\\<^sub>m nc nr @\\<^sub>r - 1\\<^sub>m nr\" unfolding M_last_def\n      unfolding append_cols_def by (simp, subst transpose_uminus, auto)\n    also have \"\\<dots> *\\<^sub>v t = 0\\<^sub>v nc @\\<^sub>v - t\" \n      by (subst mat_mult_append[OF _ _ t], insert t, auto)\n    also have \"(M_up\\<^sup>T @\\<^sub>c M_low\\<^sup>T) *\\<^sub>v u1 = (M_up\\<^sup>T *\\<^sub>v u2) + (M_low\\<^sup>T *\\<^sub>v u3)\" \n      unfolding u1id\n      by (rule mat_mult_append_cols[OF _ _ u2 u3], insert M_up M_low, auto)\n    also have \"M_low\\<^sup>T = four_block_mat (0\\<^sub>m nc nc) (0\\<^sub>m nc nc) A (- A)\" \n      unfolding M_low_def\n      by (subst transpose_four_block_mat, insert A, auto)\n    also have \"\\<dots> *\\<^sub>v u3 = (0\\<^sub>m nc nc *\\<^sub>v v + 0\\<^sub>m nc nc *\\<^sub>v w) @\\<^sub>v (A *\\<^sub>v v + - A *\\<^sub>v w)\" unfolding u3id\n      by (subst four_block_mat_mult_vec[OF _ _ A _ v w], insert A, auto)\n    also have \"0\\<^sub>m nc nc *\\<^sub>v v + 0\\<^sub>m nc nc *\\<^sub>v w = 0\\<^sub>v nc\" \n      using v w by auto\n    also have \"A *\\<^sub>v v + - A *\\<^sub>v w = vec2\" unfolding vec2_def using A v w\n      by (metis (full_types) carrier_matD(2) carrier_vecD minus_add_uminus_vec mult_mat_vec_carrier mult_minus_distrib_mat_vec uminus_mult_mat_vec)\n    also have \"M_up\\<^sup>T  = four_block_mat A\\<^sup>T (mat_of_col (- c)) (0\\<^sub>m nr nr) (mat_of_col b)\" \n      unfolding M_up_def mat_of_col_def\n      by (subst transpose_four_block_mat[OF A], insert b c, auto)\n    also have \"\\<dots> *\\<^sub>v u2 = vec1 @\\<^sub>v vec3\" \n      unfolding u2id vec1_def vec3_def\n      by (subst four_block_mat_mult_vec[OF _ _ _ _ u L], insert A b c u, auto)\n    also have \"(vec1 @\\<^sub>v vec3)\n      + (0\\<^sub>v nc @\\<^sub>v vec2) + (0\\<^sub>v nc @\\<^sub>v - t) = \n      (vec1 @\\<^sub>v (vec3 + vec2 - t))\" \n      apply (subst append_vec_add[of _ nc _ _ nr, OF vec1 _ vec3 vec2])\n      subgoal by force\n      apply (subst append_vec_add[of _ nc _ _ nr])\n      subgoal using vec1 by auto\n      subgoal by auto\n      subgoal using vec2 vec3 by auto\n      subgoal using t by auto\n      subgoal using vec1 by auto\n      done\n    finally have \"vec1 @\\<^sub>v (vec3 + vec2 - t) = 0\\<^sub>v ?nc\"\n      unfolding Mulv by simp\n    also have \"\\<dots> = 0\\<^sub>v nc @\\<^sub>v 0\\<^sub>v nr\" by auto\n    finally have \"vec1 = 0\\<^sub>v nc \\<and> vec3 + vec2 - t = 0\\<^sub>v nr\" \n      by (subst (asm) append_vec_eq[OF vec1], auto)\n    hence 01: \"vec1 = 0\\<^sub>v nc\" and 02: \"vec3 + vec2 - t = 0\\<^sub>v nr\" by auto\n    from 01 have \"vec1 + mat_of_col c *\\<^sub>v L = mat_of_col c *\\<^sub>v L\"\n      using c L vec1 unfolding mat_of_col_def  by auto\n    also have \"vec1 + mat_of_col c *\\<^sub>v L = A\\<^sup>T *\\<^sub>v u\" \n      unfolding vec1_def\n      using A u c L unfolding mat_of_col_def mat_of_row_uminus transpose_uminus\n      by (subst uminus_mult_mat_vec, auto)\n    finally have As: \"A\\<^sup>T *\\<^sub>v u = mat_of_col c *\\<^sub>v L\" .\n    from 02 have \"(vec3 + vec2 - t) + t = 0\\<^sub>v nr + t\"\n      by simp \n    also have \"(vec3 + vec2 - t) + t = vec2 + vec3\" \n      using vec3 vec2 t by auto\n    finally have t23: \"t = vec2 + vec3\" using t by auto\n    have id0: \"0\\<^sub>v ?nr = ((0\\<^sub>v nr @\\<^sub>v 0\\<^sub>v 1) @\\<^sub>v (0\\<^sub>v nc @\\<^sub>v 0\\<^sub>v nc)) @\\<^sub>v 0\\<^sub>v nr\" \n      by auto\n    from ulv0[unfolded id0 ulvid u1id u2id u3id]\n    have \"0\\<^sub>v nr \\<le> u \\<and> 0\\<^sub>v 1 \\<le> L \\<and> 0\\<^sub>v nc \\<le> v \\<and> 0\\<^sub>v nc \\<le> w \\<and> 0\\<^sub>v nr \\<le> t\" \n      apply (subst (asm) append_vec_le[of _ \"(nr + 1) + (nc + nc)\"])\n      subgoal by (intro append_carrier_vec, auto)\n      subgoal by (intro append_carrier_vec u L v w)\n      apply (subst (asm) append_vec_le[of _ \"(nr + 1)\"])\n      subgoal by (intro append_carrier_vec, auto)\n      subgoal by (intro append_carrier_vec u L v w)\n      apply (subst (asm) append_vec_le[OF _ u], force)\n      apply (subst (asm) append_vec_le[OF _ v], force)\n      by auto\n    hence ineqs: \"0\\<^sub>v nr \\<le> u\" \"0\\<^sub>v 1 \\<le> L\" \"0\\<^sub>v nc \\<le> v\" \"0\\<^sub>v nc \\<le> w\" \"0\\<^sub>v nr \\<le> t\"\n      by auto\n    have \"ulv \\<bullet> bc = u \\<bullet> b + (v \\<bullet> c + w \\<bullet> (-c))\" \n      unfolding ulvid u1id u2id u3id bc_def\n      apply (subst scalar_prod_append[OF _ t])\n         apply (rule append_carrier_vec[OF append_carrier_vec[OF u L] append_carrier_vec[OF v w]])\n        apply (rule append_carrier_vec[OF append_carrier_vec[OF b] append_carrier_vec]; use c in force)\n       apply force\n      apply (subst scalar_prod_append)\n          apply (rule append_carrier_vec[OF u L])\n         apply (rule append_carrier_vec[OF v w])\n      subgoal by (rule append_carrier_vec, insert b, auto)\n      subgoal by (rule append_carrier_vec, insert c, auto)\n      apply (subst scalar_prod_append[OF u L b], force)\n      apply (subst scalar_prod_append[OF v w c], use c in force)\n      apply (insert L t, auto)\n      done\n    also have \"v \\<bullet> c + w \\<bullet> (-c) = c \\<bullet> v + (-c) \\<bullet> w\" \n      by (subst (1 2) comm_scalar_prod, insert w c v, auto)\n    also have \"\\<dots> = c \\<bullet> v - (c \\<bullet> w)\" using c w by simp\n    also have \"\\<dots> = c \\<bullet> (v - w)\" using c v w\n      by (simp add: scalar_prod_minus_distrib)\n    finally have ulvbc: \"ulv \\<bullet> bc = u \\<bullet> b + c \\<bullet> (v - w)\" .\n    define lam where \"lam = L $ 0\" \n    from ineqs(2) L have lam0: \"lam \\<ge> 0\" unfolding less_eq_vec_def lam_def by auto\n    have As: \"A\\<^sup>T *\\<^sub>v u = lam \\<cdot>\\<^sub>v c\" unfolding As using c L\n      unfolding lam_def mat_of_col_def\n      by (intro eq_vecI, auto simp: scalar_prod_def)\n    have vec3: \"vec3 = lam \\<cdot>\\<^sub>v b\" unfolding vec3_def using b L\n      unfolding lam_def mat_of_col_def\n      by (intro eq_vecI, auto simp: scalar_prod_def)\n    note preconds = lam0 ineqs(1,3-)[unfolded t23[unfolded vec2_def vec3]] As\n    have \"0 \\<le> u \\<bullet> b + c \\<bullet> (v - w)\"\n    proof (cases \"lam > 0\")\n      case True\n      hence \"u \\<bullet> b = inverse lam * (lam * (b \\<bullet> u))\" \n        using comm_scalar_prod[OF b u] by simp\n      also have \"\\<dots> = inverse lam * ((lam \\<cdot>\\<^sub>v b) \\<bullet> u)\"\n        using b u by simp\n      also have \"\\<dots> \\<ge> inverse lam * (-(A *\\<^sub>v (v - w)) \\<bullet> u)\" \n      proof (intro mult_left_mono)\n        show \"0 \\<le> inverse lam\" using preconds by auto\n        show \"-(A *\\<^sub>v (v - w)) \\<bullet> u \\<le> (lam \\<cdot>\\<^sub>v b) \\<bullet> u\" \n          unfolding scalar_prod_def\n          apply (rule sum_mono)\n          subgoal for i\n            using lesseq_vecD[OF _ preconds(2), of nr i] lesseq_vecD[OF _ preconds(5), of nr i] u v w b A\n            by (intro mult_right_mono, auto)\n          done\n      qed\n      also have \"inverse lam * (-(A *\\<^sub>v (v - w)) \\<bullet> u) =\n         - (inverse lam * ((A *\\<^sub>v (v - w)) \\<bullet> u))\" \n        by (subst scalar_prod_uminus_left, insert A u v w, auto)\n      also have \"(A *\\<^sub>v (v - w)) \\<bullet> u = (A\\<^sup>T *\\<^sub>v u) \\<bullet> (v - w)\" \n        apply (subst transpose_vec_mult_scalar[OF A _ u])\n        subgoal using v w by force\n        by (rule comm_scalar_prod[OF _ u], insert A v w, auto)\n      also have \"inverse lam * \\<dots> = c \\<bullet> (v - w)\" unfolding preconds(6)\n        using True\n        by (subst scalar_prod_smult_left, insert c v w, auto)\n      finally show ?thesis by simp\n    next\n      case False\n      with preconds have lam: \"lam = 0\" by auto\n      from primal obtain x0 where x0: \"x0 \\<in> carrier_vec nc\"\n        and Ax0b: \"A *\\<^sub>v x0 \\<le> b\" by auto\n      from dual obtain y0 where y00: \"y0 \\<ge> 0\\<^sub>v nr\" \n        and Ay0c: \"A\\<^sup>T *\\<^sub>v y0 = c\" by auto\n      from y00 have y0: \"y0 \\<in> carrier_vec nr\" \n        unfolding less_eq_vec_def by auto\n      have Au: \"A\\<^sup>T *\\<^sub>v u = 0\\<^sub>v nc\" \n        unfolding preconds lam using c by auto\n      have \"0 = (A\\<^sup>T *\\<^sub>v u) \\<bullet> x0\" unfolding Au using x0 by auto\n      also have \"\\<dots> = u \\<bullet> (A *\\<^sub>v x0)\"\n        by (rule transpose_vec_mult_scalar[OF A x0 u])\n      also have \"\\<dots> \\<le> u \\<bullet> b\" \n        unfolding scalar_prod_def \n        apply (use A x0 b in simp) \n        apply (intro sum_mono)\n        subgoal for i\n          using lesseq_vecD[OF _ preconds(2), of nr i] lesseq_vecD[OF _ Ax0b, of nr i] u v w b A x0\n          by (intro mult_left_mono, auto)\n        done\n      finally have ub: \"0 \\<le> u \\<bullet> b\" .\n      have \"c \\<bullet> (v - w) = (A\\<^sup>T *\\<^sub>v y0) \\<bullet> (v - w)\" unfolding Ay0c by simp\n      also have \"\\<dots> = y0 \\<bullet> (A *\\<^sub>v (v - w))\" \n        by (subst transpose_vec_mult_scalar[OF A _ y0], insert v w, auto)\n      also have \"\\<dots> \\<ge> 0\"\n        unfolding scalar_prod_def\n        apply (use A v w in simp)\n        apply (intro sum_nonneg)\n        subgoal for i\n          using lesseq_vecD[OF _ y00, of nr i] lesseq_vecD[OF _ preconds(5)[unfolded lam], of nr i] A y0 v w b\n          by (intro mult_nonneg_nonneg, auto)\n        done\n      finally show ?thesis using ub by auto\n    qed\n    thus \"0 \\<le> ulv \\<bullet> bc\" unfolding ulvbc .\n  qed\n  then obtain xy where xy: \"xy \\<in> carrier_vec ?nc\" and le: \"M *\\<^sub>v xy \\<le> bc\" by auto\n  define x where \"x = vec_first xy nc\" \n  define y where \"y = vec_last xy nr\" \n  have xyid: \"xy = x @\\<^sub>v y\" using xy\n    unfolding x_def y_def by auto\n  have x: \"x \\<in> carrier_vec nc\" unfolding x_def by auto\n  have y: \"y \\<in> carrier_vec nr\" unfolding y_def by auto\n  have At: \"A\\<^sup>T \\<in> carrier_mat nc nr\" using A by auto\n  have Ax1: \"A *\\<^sub>v x @\\<^sub>v vec 1 (\\<lambda>_. b \\<bullet> y - c \\<bullet> x) \\<in> carrier_vec (nr + 1)\" \n    using A x by fastforce\n  have b0cc: \"(b @\\<^sub>v 0\\<^sub>v 1) @\\<^sub>v c @\\<^sub>v - c \\<in> carrier_vec ((nr + 1) + (nc + nc))\" \n    using b c \n    by (intro append_carrier_vec, auto)\n  have \"M *\\<^sub>v xy = (M_up *\\<^sub>v xy @\\<^sub>v M_low *\\<^sub>v xy) @\\<^sub>v (M_last *\\<^sub>v xy)\" \n    unfolding M_def\n    unfolding mat_mult_append[OF carrier_append_rows[OF M_up M_low] M_last xy]\n    by (simp add: mat_mult_append[OF M_up M_low xy])\n  also have \"M_low *\\<^sub>v xy = (0\\<^sub>m nc nc *\\<^sub>v x + A\\<^sup>T *\\<^sub>v y) @\\<^sub>v (0\\<^sub>m nc nc *\\<^sub>v x + - A\\<^sup>T *\\<^sub>v y)\" \n    unfolding M_low_def xyid\n    by (rule four_block_mat_mult_vec[OF _ At _ _ x y], insert A, auto)\n  also have \"0\\<^sub>m nc nc *\\<^sub>v x + A\\<^sup>T *\\<^sub>v y = A\\<^sup>T *\\<^sub>v y\" using A x y by auto\n  also have \"0\\<^sub>m nc nc *\\<^sub>v x + - A\\<^sup>T *\\<^sub>v y = - A\\<^sup>T *\\<^sub>v y\" using A x y by auto\n  also have \"M_up *\\<^sub>v xy = (A *\\<^sub>v x + 0\\<^sub>m nr nr *\\<^sub>v y) @\\<^sub>v\n               (mat_of_row (- c) *\\<^sub>v x + mat_of_row b *\\<^sub>v y)\" \n    unfolding M_up_def xyid\n    by (rule four_block_mat_mult_vec[OF A _ _ _ x y], insert b c, auto)\n  also have \"A *\\<^sub>v x + 0\\<^sub>m nr nr *\\<^sub>v y = A *\\<^sub>v x\" using A x y by auto\n  also have \"mat_of_row (- c) *\\<^sub>v x + mat_of_row b *\\<^sub>v y = \n    vec 1 (\\<lambda> _. b \\<bullet> y - c \\<bullet> x)\" \n    unfolding mult_mat_vec_def using c x by (intro eq_vecI, auto)\n  also have \"M_last *\\<^sub>v xy = - y\" \n    unfolding M_last_def xyid using x y\n    by (subst mat_mult_append_cols[OF _ _ x y], auto)\n  finally have \"((A *\\<^sub>v x @\\<^sub>v vec 1 (\\<lambda>_. b \\<bullet> y - c \\<bullet> x)) @\\<^sub>v (A\\<^sup>T *\\<^sub>v y @\\<^sub>v - A\\<^sup>T *\\<^sub>v y)) @\\<^sub>v -y\n    = M *\\<^sub>v xy\" ..\n  also have \"\\<dots> \\<le> bc\" by fact\n  also have \"\\<dots> = ((b @\\<^sub>v 0\\<^sub>v 1) @\\<^sub>v (c @\\<^sub>v -c)) @\\<^sub>v 0\\<^sub>v nr\" unfolding bc_def by auto\n  finally have ineqs: \"A *\\<^sub>v x \\<le> b \\<and> vec 1 (\\<lambda>_. b \\<bullet> y - c \\<bullet> x) \\<le> 0\\<^sub>v 1\n             \\<and> A\\<^sup>T *\\<^sub>v y \\<le> c \\<and> - A\\<^sup>T *\\<^sub>v y \\<le> -c \\<and> -y \\<le> 0\\<^sub>v nr\"\n    apply (subst (asm) append_vec_le[OF _ b0cc])\n    subgoal using A x y by (intro append_carrier_vec, auto)\n    apply (subst (asm) append_vec_le[OF Ax1], use b in fastforce)\n    apply (subst (asm) append_vec_le[OF _ b], use A x in force)\n    apply (subst (asm) append_vec_le[OF _ c], use A y in force)\n    by auto\n  show ?thesis\n  proof (intro exI conjI)\n    from ineqs show Axb: \"A *\\<^sub>v x \\<le> b\" by auto\n    from ineqs have \"- A\\<^sup>T *\\<^sub>v y \\<le> -c\" \"A\\<^sup>T *\\<^sub>v y \\<le> c\" by auto\n    hence \"A\\<^sup>T *\\<^sub>v y \\<ge> c\" \"A\\<^sup>T *\\<^sub>v y \\<le> c\" unfolding less_eq_vec_def using A y by auto\n    then show Aty: \"A\\<^sup>T *\\<^sub>v y = c\" by simp\n    from ineqs have \"- y \\<le> 0\\<^sub>v nr\" by simp\n    then show y0: \"0\\<^sub>v nr \\<le> y\" unfolding less_eq_vec_def by auto\n    from ineqs have \"b \\<bullet> y \\<le> c \\<bullet> x\" unfolding less_eq_vec_def by auto\n    with weak_duality_theorem[OF A b c x Axb y0 Aty]\n    show \"c \\<bullet> x = b \\<bullet> y\" by auto\n  qed (insert x)\nqed\n\ntext \\<open>A version of the strong duality theorem which demands\n  that the primal problem is solvable and the objective function\n  is bounded.\\<close>\ntheorem strong_duality_theorem_primal_sat_bounded:\n  fixes bound :: \"'a :: trivial_conjugatable_linordered_field\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and sat: \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n    and bounded: \"\\<forall> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b \\<longrightarrow> c \\<bullet> x \\<le> bound\" \n  shows \"\\<exists> x y. \n       x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b \\<and> \n       y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c \\<and>\n       c \\<bullet> x = b \\<bullet> y\" \nproof (rule strong_duality_theorem_both_sat[OF A b c sat])\n  show \"\\<exists>y\\<ge>0\\<^sub>v nr. A\\<^sup>T *\\<^sub>v y = c\" \n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\" \n    hence \"\\<exists>y. y \\<in> carrier_vec nc \\<and> 0\\<^sub>v nr \\<le> A *\\<^sub>v y \\<and> 0 > y \\<bullet> c\" \n      by (subst (asm) gram_schmidt.Farkas_Lemma[OF _ c], insert A, auto)\n    then obtain y where y: \"y \\<in> carrier_vec nc\" \n      and Ay0: \"A *\\<^sub>v y \\<ge> 0\\<^sub>v nr\" and yc0: \"y \\<bullet> c < 0\" by auto\n    from sat obtain x where x: \"x \\<in> carrier_vec nc\" \n      and Axb: \"A *\\<^sub>v x \\<le> b\" by auto\n    define diff where \"diff = bound + 1 - c \\<bullet> x\" \n    from x Axb bounded have \"c \\<bullet> x < bound + 1\" by auto\n    hence diff: \"diff > 0\" unfolding diff_def by auto\n    from yc0 have inv: \"inverse (- (y \\<bullet> c)) > 0\" by auto\n    define fact where \"fact = diff * (inverse (- (y \\<bullet> c)))\"\n    have fact: \"fact > 0\" unfolding fact_def using diff inv by (metis mult_pos_pos)\n    define z where \"z = x - fact \\<cdot>\\<^sub>v y\" \n    have \"A *\\<^sub>v z = A *\\<^sub>v x - A *\\<^sub>v (fact \\<cdot>\\<^sub>v y)\" \n      unfolding z_def using A x y by (meson mult_minus_distrib_mat_vec smult_carrier_vec)\n    also have \"\\<dots> = A *\\<^sub>v x - fact \\<cdot>\\<^sub>v (A *\\<^sub>v y)\" using A y by auto\n    also have \"\\<dots> \\<le> b\"\n    proof (intro lesseq_vecI[OF _ b])\n      show \"A *\\<^sub>v x - fact \\<cdot>\\<^sub>v (A *\\<^sub>v y) \\<in> carrier_vec nr\" using A x y by auto\n      fix i \n      assume i: \"i < nr\" \n      have \"(A *\\<^sub>v x - fact \\<cdot>\\<^sub>v (A *\\<^sub>v y)) $ i\n        = (A *\\<^sub>v x) $ i - fact * (A *\\<^sub>v y) $ i\" \n        using i A x y by auto\n      also have \"\\<dots> \\<le> b $ i - fact * (A *\\<^sub>v y) $ i\" \n        using lesseq_vecD[OF b Axb i] by auto\n      also have \"\\<dots> \\<le> b $ i - 0 * 0\" using lesseq_vecD[OF _ Ay0 i] fact A y i\n        by (intro diff_left_mono mult_monom, auto)\n      finally show \"(A *\\<^sub>v x - fact \\<cdot>\\<^sub>v (A *\\<^sub>v y)) $ i \\<le> b $ i\" by simp\n    qed\n    finally have Azb: \"A *\\<^sub>v z \\<le> b\" .\n    have z: \"z \\<in> carrier_vec nc\" using x y unfolding z_def by auto\n    have \"c \\<bullet> z = c \\<bullet> x - fact * (c \\<bullet> y)\" unfolding z_def\n      using c x y by (simp add: scalar_prod_minus_distrib)\n    also have \"\\<dots> = c \\<bullet> x + diff\" \n      unfolding comm_scalar_prod[OF c y] fact_def using yc0 by simp\n    also have \"\\<dots> = bound + 1\" unfolding diff_def by simp\n    also have \"\\<dots> > c \\<bullet> z\" using bounded Azb z by auto\n    finally show False by simp\n  qed\nqed\n\ntext \\<open>A version of the strong duality theorem which demands\n  that the dual problem is solvable and the objective function\n  is bounded.\\<close>\ntheorem strong_duality_theorem_dual_sat_bounded:\n  fixes bound :: \"'a :: trivial_conjugatable_linordered_field\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and sat: \"\\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c\"\n    and bounded: \"\\<forall> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c \\<longrightarrow> bound \\<le> b \\<bullet> y\" \n  shows \"\\<exists> x y. \n       x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b \\<and> \n       y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c \\<and>\n       c \\<bullet> x = b \\<bullet> y\" \nproof (rule strong_duality_theorem_both_sat[OF A b c _ sat])\n  show \"\\<exists>x\\<in>carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence \"\\<not> (\\<exists>x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b)\" by auto\n    then obtain y where y0: \"y \\<ge> 0\\<^sub>v nr\" and Ay0: \"A\\<^sup>T *\\<^sub>v y = 0\\<^sub>v nc\" and yb: \"y \\<bullet> b < 0\"  \n      by (subst (asm) gram_schmidt.Farkas_Lemma'[OF A b], auto)\n    from sat obtain x where x0: \"x \\<ge> 0\\<^sub>v nr\" and Axc: \"A\\<^sup>T *\\<^sub>v x = c\" by auto\n    define diff where \"diff = b \\<bullet> x - (bound - 1)\" \n    from x0 Axc bounded have \"bound \\<le> b \\<bullet> x\" by auto\n    hence diff: \"diff > 0\" unfolding diff_def by auto\n    define fact where \"fact = - inverse (y \\<bullet> b) * diff\" \n    have fact: \"fact > 0\" unfolding fact_def using diff yb by (auto intro: mult_neg_pos)\n    define z where \"z = x + fact \\<cdot>\\<^sub>v y\" \n    from x0 have x: \"x \\<in> carrier_vec nr\" \n      unfolding less_eq_vec_def by auto\n    from y0 have y: \"y \\<in> carrier_vec nr\" \n      unfolding less_eq_vec_def by auto\n    have \"A\\<^sup>T *\\<^sub>v z = A\\<^sup>T *\\<^sub>v x + A\\<^sup>T *\\<^sub>v (fact \\<cdot>\\<^sub>v y)\" \n      unfolding z_def using A x y by (simp add: mult_add_distrib_mat_vec)\n    also have \"\\<dots> = A\\<^sup>T *\\<^sub>v x + fact \\<cdot>\\<^sub>v (A\\<^sup>T *\\<^sub>v y)\" using A y by auto\n    also have \"\\<dots> = c\" unfolding Ay0 Axc using c by auto\n    finally have Azc: \"A\\<^sup>T *\\<^sub>v z = c\" .\n    have z0: \"z \\<ge> 0\\<^sub>v nr\" unfolding z_def\n      by (intro lesseq_vecI[of _ nr], insert x y lesseq_vecD[OF _ x0, of nr] lesseq_vecD[OF _ y0, of nr] fact, \n          auto intro!: add_nonneg_nonneg)\n    from bounded Azc z0 have bz: \"bound \\<le> b \\<bullet> z\" by auto\n    also have \"\\<dots> = b \\<bullet> x + fact * (b \\<bullet> y)\" unfolding z_def using b x y\n      by (simp add: scalar_prod_add_distrib)\n    also have \"\\<dots> = diff + (bound - 1) + fact * (b \\<bullet> y)\" \n      unfolding diff_def by auto\n    also have \"fact * (b \\<bullet> y) = - diff\" using yb \n      unfolding fact_def comm_scalar_prod[OF y b] by auto\n    finally show False by simp\n  qed\nqed\n\n\ntext \\<open>Now the previous three duality theorems are formulated via min/max.\\<close>\ncorollary strong_duality_theorem_min_max:\n  fixes A :: \"'a :: trivial_conjugatable_linordered_field mat\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and primal: \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n    and dual: \"\\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c\"\n  shows \"Maximum {c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\n       = Minimum {b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \n    and \"has_Maximum {c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\" \n    and \"has_Minimum {b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \nproof -\n  let ?Prim = \"{c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\" \n  let ?Dual = \"{b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \n  define Prim where \"Prim = ?Prim\" \n  define Dual where \"Dual = ?Dual\" \n  from strong_duality_theorem_both_sat[OF assms]\n  obtain x y where x: \"x \\<in> carrier_vec nc\" and Axb: \"A *\\<^sub>v x \\<le> b\"  \n    and y: \"y \\<ge> 0\\<^sub>v nr\" and Ayc: \"A\\<^sup>T *\\<^sub>v y = c\" \n    and eq: \"c \\<bullet> x = b \\<bullet> y\" by auto\n  have cxP: \"c \\<bullet> x \\<in> Prim\" unfolding Prim_def using x Axb by auto\n  have cxD: \"c \\<bullet> x \\<in> Dual\" unfolding eq Dual_def using y Ayc by auto\n  {\n    fix z\n    assume \"z \\<in> Prim\"\n    from this[unfolded Prim_def] obtain x' where x': \"x' \\<in> carrier_vec nc\" \n      and Axb': \"A *\\<^sub>v x' \\<le> b\" and z: \"z = c \\<bullet> x'\" by auto\n    from weak_duality_theorem[OF A b c x' Axb' y Ayc, folded eq]\n    have \"z \\<le> c \\<bullet> x\" unfolding z .\n  } note cxMax = this\n  have max: \"Maximum Prim = c \\<bullet> x\"     \n    by (intro eqMaximumI cxP cxMax)\n  show \"has_Maximum ?Prim\" \n    unfolding Prim_def[symmetric] has_Maximum_def using cxP cxMax by auto\n  {\n    fix z\n    assume \"z \\<in> Dual\"\n    from this[unfolded Dual_def] obtain y' where y': \"y' \\<ge> 0\\<^sub>v nr\"  \n      and Ayc': \"A\\<^sup>T *\\<^sub>v y' = c\" and z: \"z = b \\<bullet> y'\" by auto\n    from weak_duality_theorem[OF A b c x Axb y' Ayc', folded z]\n    have \"c \\<bullet> x \\<le> z\" .\n  } note cxMin = this\n  show \"has_Minimum ?Dual\" \n    unfolding Dual_def[symmetric] has_Minimum_def using cxD cxMin by auto\n  have min: \"Minimum Dual = c \\<bullet> x\" \n    by (intro eqMinimumI cxD cxMin)\n  from min max show \"Maximum ?Prim = Minimum ?Dual\"  \n    unfolding Dual_def Prim_def by auto\nqed\n\ncorollary strong_duality_theorem_primal_sat_bounded_min_max:\n  fixes bound :: \"'a :: trivial_conjugatable_linordered_field\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and sat: \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" \n    and bounded: \"\\<forall> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b \\<longrightarrow> c \\<bullet> x \\<le> bound\" \n  shows \"Maximum {c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\n       = Minimum {b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\"\n    and \"has_Maximum {c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\" \n    and \"has_Minimum {b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \nproof -\n  let ?Prim = \"{c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\" \n  let ?Dual = \"{b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \n  from strong_duality_theorem_primal_sat_bounded[OF assms]\n  have \"\\<exists>y\\<ge>0\\<^sub>v nr. A\\<^sup>T *\\<^sub>v y = c\" by blast\n  from strong_duality_theorem_min_max[OF A b c sat this]\n  show \"Maximum ?Prim = Minimum ?Dual\" \"has_Maximum ?Prim\"  \"has_Minimum ?Dual\"\n    by blast+\nqed\n\ncorollary strong_duality_theorem_dual_sat_bounded_min_max:\n  fixes bound :: \"'a :: trivial_conjugatable_linordered_field\" \n  assumes A: \"A \\<in> carrier_mat nr nc\" \n    and b: \"b \\<in> carrier_vec nr\" \n    and c: \"c \\<in> carrier_vec nc\"\n    and sat: \"\\<exists> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c\"\n    and bounded: \"\\<forall> y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c \\<longrightarrow> bound \\<le> b \\<bullet> y\" \n  shows \"Maximum {c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\n       = Minimum {b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\"\n    and \"has_Maximum {c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\" \n    and \"has_Minimum {b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \nproof - \n  let ?Prim = \"{c \\<bullet> x | x. x \\<in> carrier_vec nc \\<and> A *\\<^sub>v x \\<le> b}\" \n  let ?Dual = \"{b \\<bullet> y | y. y \\<ge> 0\\<^sub>v nr \\<and> A\\<^sup>T *\\<^sub>v y = c}\" \n  from strong_duality_theorem_dual_sat_bounded[OF assms]\n  have \"\\<exists> x \\<in> carrier_vec nc. A *\\<^sub>v x \\<le> b\" by blast\n  from strong_duality_theorem_min_max[OF A b c this sat]\n  show \"Maximum ?Prim = Minimum ?Dual\" \"has_Maximum ?Prim\"  \"has_Minimum ?Dual\"\n    by blast+\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/LP_Duality/LP_Duality.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218391455085, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.7907951472368067}}
{"text": "theory Concrete\nimports Main\n\nbegin\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\ntheorem add_02[simp]: \"add m 0 = m\"\n  apply(induction m)\n  apply(auto)\n  done\n\ntheorem add_associative[simp]: \"add (add x y) z = add x (add y z)\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma add_comm_sub[simp]: \"Suc (add y x) = add y (Suc x)\"\n  apply(induction y)\n  apply(auto)\n  done\n\ntheorem add_commutative: \"add x y = add y x\"\n  apply(induction x)\n  apply(auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double x = 2 * x\"\n\ntheorem double_two_additions: \"double x = add x x\"\n  apply(induction x)\n  apply(auto)\n  done\n  \nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\n(*\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n*)\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\nlemma app_Nil2 [simp]: \"app xs Nil = xs\"\napply(induction xs)\napply(auto)\n  done\n\nlemma app_assoc [simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply(induction xs)\napply(auto)\ndone\n\nlemma rev_app[simp]: \"rev(app xs ys) = app (rev ys) (rev xs)\"\n  apply(induction xs)\n  apply(auto)\n  done\n\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nvalue \"1 + (2::nat)\"\n\nvalue \"1 + (2::int)\"\n\nvalue \"1 -(2::nat)\"\n\nvalue \"1 - (2::int)\"\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count _ Nil = 0\" |\n\"count e (Cons x xs) = 1 + count e xs\"\n\ntheorem count_lte_length: \"count x xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] e = [e]\" | \n\"snoc (Cons x xs) e = (Cons x (snoc xs e))\"\n\nfun reverse_snoc :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse_snoc Nil = Nil\" |\n\"reverse_snoc (Cons x xs) = snoc (reverse_snoc xs) x\"\n\ntheorem snoc_prepend[simp]: \"reverse_snoc (snoc xs a) = a # (reverse_snoc xs)\"\n  apply(induction xs)\n  apply(auto)\n  done\n\ntheorem rev_rev_snoc: \"reverse_snoc (reverse_snoc xs) = xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\" |\n\"sum_upto x = x + (sum_upto (x - 1))\"\n\ntheorem sum_formula: \"sum_upto n = n * (n + 1) div 2\"\n  apply(induction n)\n   apply(auto)\n  done\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l v r) = append (contents l) (v # (contents r))\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l v r) = sum_tree l + v + sum_tree r\"\n\ntheorem sum_tree_works: \"sum_tree t = sum_list (contents t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\nvalue \"sum_list [1,2,(3::nat)]\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l a r) = Node (mirror r) a (mirror l)\"\n\nlemma \"mirror(mirror t) = t\"\n  apply(induction t)\n   apply(auto)\n  done\n\nfun pre_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"pre_order Tip = []\" |\n\"pre_order (Node l a r) = (a # (pre_order l)) @ (pre_order r)\"\n\nfun post_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"post_order Tip = []\" |\n\"post_order (Node l a r) = (post_order l) @ (post_order r) @ [a]\"\n\nfun mirror_2 :: \"'a tree \\<Rightarrow> 'a tree\" where\n  \"mirror_2 Tip = Tip\" |\n  \"mirror_2 (Node l a r) = Node (mirror_2 r) a (mirror_2 l)\"  \n\nfun pre_order_2 :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"pre_order_2 Tip = []\" |\n  \"pre_order_2 (Node l a r) = a # (pre_order_2 l @ pre_order_2 r)\"\n\nfun post_order_2 :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"post_order_2 Tip = []\" |\n  \"post_order_2 (Node l a r) = (post_order_2 l) @ (post_order_2 r) @ [a]\"\n\nlemma reversing_stuff: \"pre_order (mirror t) = rev (post_order t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n(* 3 *)\n(* |-- 4 *)\n(* |--  *)\n\nvalue \"rev (post_order ((Node (Node Tip 4 Tip) 3 (Node Tip 7 Tip)) ::nat tree))\" \nvalue \"pre_order (mirror (Node (Node Tip 4 Tip) 3 (Node Tip 7 Tip))::nat tree)\"\n\nvalue \"pre_order (\n(Node \n  (Node Tip 1 Tip) \n  2 \n  (Node Tip 3 Tip)) :: nat tree)\"\n\n\nvalue \"post_order (\n(Node \n  (Node Tip 1 Tip) \n  2 \n  (Node Tip 3 Tip)) :: nat tree)\"\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse a [] = [a]\" |\n\"intersperse a (x # xs) = x # (a # (intersperse a xs))\"\n\ntheorem interspersing: \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n(* 2 *)\nvalue \"Suc(Suc Zero)\"\n(* 3 *)\nvalue \"Suc(Suc (Suc Zero))\"\n\nfun my_add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"my_add 0 n = n\" |\n\"my_add (Suc m) n = Suc(add m n)\"\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 n = n\" |\n\"itadd (Suc m) n = itadd m (Suc n)\"\n\ntheorem tail_rec_add: \"itadd m n = add m n\"\n  apply(induction m arbitrary: n)\n   apply(auto)\n  done\n\nvalue \"intersperse 5 [1,2,3::nat]\"\n\ndatatype tree0 = Tip | Node \"tree0\" \"tree0\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 0\" |\n\"nodes (Node l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\n(*\n  explode 1 t\n   explode 0 (Node t t)\n\n  explode 2 t\n    explode 1 (Node t t)\n     explode 0 (Node (Node t t) (Node t t))\n\n  explode 3 t\n    explode 2 (Node t t)\n      explode 1 (Node (Node t t) (Node t t))\n        explode 0 (Node (Node (Node t t) (Node t t)) (Node (Node t t) (Node t t)))\n*)\n\nvalue \"nodes (Node (Node Tip Tip) (Node Tip Tip))\"\n\nvalue \"nodes (explode 4  (Node (Node Tip Tip) (Node Tip Tip)))\"\n\nvalue \"explode 0 Tip\"\n\n(* by nitpick *)\n(* by quickcheck *)\ntheorem \"nodes (explode n t) = (2 ^ n) * (nodes t) + 2^n - 1\"\n  apply(induction n arbitrary: t)\n   apply(auto simp add: algebra_simps)\n  done\n\nend\n\n\n  ", "meta": {"author": "amw-zero", "repo": "concrete_semantics", "sha": "b486ec4950cdb8ee83d222e9b8abff4663021e77", "save_path": "github-repos/isabelle/amw-zero-concrete_semantics", "path": "github-repos/isabelle/amw-zero-concrete_semantics/concrete_semantics-b486ec4950cdb8ee83d222e9b8abff4663021e77/Concrete.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8976952975813453, "lm_q1q2_score": 0.7906874062598775}}
{"text": "theory Chapter4\nimports \"HOL-IMP.ASM\" Main\nbegin\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  for r where\nrefl:  \"star r x x\" | \nstep:  \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\n(*\n\\section*{Chapter 4}\n\n\\exercise\nStart from the data type of binary trees defined earlier:\n*)\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\n(*\nAn @{typ \"int tree\"} is ordered if for every @{term \"Node l i r\"} in the tree,\n@{text l} and @{text r} are ordered\nand all values in @{text l} are @{text \"< i\"}\nand all values in @{text r} are @{text \"> i\"}.\nDefine a function that returns the elements in a tree and one\nthe tests if a tree is ordered:\n*)\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\"  where\n  \"set Tip = {}\"\n| \"set (Node lt x rt) = (set lt) \\<union> {x} \\<union> (set rt)\"\n\ndefinition temp :: \"int set\" where \n  \"temp = {1,2,3}\"\n\nvalue \"{x. x \\<in> temp}\"\nvalue \"(\\<forall>y \\<in> temp. y \\<ge> 2) = False \"\n\nfun ord :: \"int tree \\<Rightarrow> bool\"  where\n  \"ord Tip = True\"\n| \"ord (Node lt x rt) = (\\<forall>y \\<in> (set lt). y \\<ge> x) \"\n\n(* Hint: use quantifiers.\n\nDefine a function @{text ins} that inserts an element into an ordered @{typ \"int tree\"}\nwhile maintaining the order of the tree. If the element is already in the tree, the\nsame tree should be returned.\n*)\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n  \"ins x Tip = Node Tip x Tip\"\n| \"ins x (Node lt y rt) = \n   (if x < y \n    then (Node (ins x lt) y rt)\n    else (if x = y then (Node lt y rt) \n                   else (Node lt y (ins x rt))))\"\n\ntheorem ins : \"set (ins x t) = {x} \\<union> set t\"\n  apply(induction t arbitrary : x)\n   apply(auto)\n  done\n\n\n\nlemma \"\\<forall>x. \\<exists>y. x=y\"\n  apply(auto)\n  done\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\n  by auto  (* is short for apply proof-method done*)\n\n(* fastforce example*)\nlemma \"(\\<forall> xs \\<in> A. \\<exists> ys. (xs = ys @ ys)) \\<Longrightarrow> us \\<in> A \\<Longrightarrow> \\<exists> n. length us = n + n \"\n  apply fastforce\n  done\n\n\nthm Suc_leD\nlemma \"Suc (Suc (Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\n  apply(rule Suc_leD)\n  apply(rule Suc_leD)\n  apply(rule Suc_leD)\n  apply auto\n  done\n\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n  ev0:  \"ev 0\"\n| evSS: \"ev n \\<Longrightarrow> ev (n + 2)\"\n\n\n\n(*\ntheorem ord_ins: \"ord t \\<Longrightarrow> ord(ins i t)\"\n(* your definition/proof here *)\n*)\n(*\n\\endexercise\n\n\\exercise\nFormalize the following definition of palindromes\n\\begin{itemize}\n\\item The empty list and a singleton list are palindromes.\n\\item If @{text xs} is a palindrome, so is @{term \"a # xs @ [a]\"}.\n\\end{itemize}\nas an inductive predicate\n*)\n\n(*\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\n(* and prove *)\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n(* your definition/proof here *)\n*)\n\n(*\nWe could also have defined @{const star} as follows:\n*)\n\n\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\n(*\nThe single @{text r} step is performer after rather than before the @{text star'}\nsteps. Prove\n*)\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\n\n\n\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n(* your definition/proof here *)\n\n(*\nYou may need lemmas. Note that rule induction fails\nif the assumption about the inductive predicate\nis not the first assumption.\nexe:iter\nAnalogous to @{const star}, give an inductive definition of the @{text n}-fold iteration\nof a relation @{text r}: @{term \"iter r n x y\"} should hold if there are @{text x\\<^sub>0}, \\dots, @{text x\\<^sub>n}\nsuch that @{prop\"x = x\\<^sub>0\"}, @{prop\"x\\<^sub>n = y\"} and @{text\"r x\\<^bsub>i\\<^esub> x\\<^bsub>i+1\\<^esub>\"} for\nall @{prop\"i < n\"}:\n*)\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n(* your definition/proof here *)\n\n(*\nCorrect and prove the following claim:\n*)\n\nlemma \"star r x y \\<Longrightarrow> iter r n x y\"\n(* your definition/proof here *)\n\n(*\n\\endexercise\n\n\\exercise\\label{exe:cfg}\nA context-free grammar can be seen as an inductive definition where each\nnonterminal $A$ is an inductively defined predicate on lists of terminal\nsymbols: $A(w)$ mans that $w$ is in the language generated by $A$.\nFor example, the production $S \\to aSb$ can be viewed as the implication\n@{prop\"S w \\<Longrightarrow> S (a # w @ [b])\"} where @{text a} and @{text b} are terminal symbols,\ni.e., elements of some alphabet. The alphabet can be defined as a datatype:\n*)\n\ndatatype alpha = a | b\n\n(*\nIf you think of @{const a} and @{const b} as ``@{text \"(\"}'' and  ``@{text \")\"}'',\nthe following two grammars both generate strings of balanced parentheses\n(where $\\varepsilon$ is the empty word):\n\\[\n\\begin{array}{r@ {\\quad}c@ {\\quad}l}\nS &\\to& \\varepsilon \\quad\\mid\\quad aSb \\quad\\mid\\quad SS \\\\\nT &\\to& \\varepsilon \\quad\\mid\\quad TaTb\n\\end{array}\n\\]\nDefine them as inductive predicates and prove their equivalence:\n*)\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\nlemma TS: \"T w \\<Longrightarrow> S w\"\n(* your definition/proof here *)\n\n\n\nlemma ST: \"S w \\<Longrightarrow> T w\"\n(* your definition/proof here *)\n\ncorollary SeqT: \"S w \\<longleftrightarrow> T w\"\n(* your definition/proof here *)\n\n(*\n\\endexercise\n*)\n(* your definition/proof here *)\n(*\n\\exercise\nIn Chapter 3 we defined a recursive evaluation function\n@{text \"aval ::\"} @{typ \"aexp \\<Rightarrow> state \\<Rightarrow> val\"}.\nDefine an inductive evaluation predicate and prove that it agrees with\nthe recursive function:\n*)\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\nlemma aval_rel_aval: \"aval_rel a s v \\<Longrightarrow> aval a s = v\"\n(* your definition/proof here *)\n\nlemma aval_aval_rel: \"aval a s = v \\<Longrightarrow> aval_rel a s v\"\n(* your definition/proof here *)\n\ncorollary \"aval_rel a s v \\<longleftrightarrow> aval a s = v\"\n(* your definition/proof here *)\n\n(*\n\\endexercise\n\n\\exercise\nConsider the stack machine from Chapter~3\nand recall the concept of \\concept{stack underflow}\nfrom Exercise~\\ref{exe:stack-underflow}.\nDefine an inductive predicate\n*)\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\n(*\nsuch that @{text \"ok n is n'\"} means that with any initial stack of length\n@{text n} the instructions @{text \"is\"} can be executed\nwithout stack underflow and that the final stack has length @{text n'}.\n\nUsing the introduction rules for @{const ok},\nprove the following special cases: *}\n\nlemma \"ok 0 [LOAD x] (Suc 0)\"\n(* your definition/proof here *)\n\nlemma \"ok 0 [LOAD x, LOADI v, ADD] (Suc 0)\"\n(* your definition/proof here *)\n\nlemma \"ok (Suc (Suc 0)) [LOAD x, ADD, ADD, LOAD y] (Suc (Suc 0))\"\n(* your definition/proof here *)\n\ntext {* Prove that @{text ok} correctly computes the final stack size: *}\n\nlemma \"\\<lbrakk>ok n is n'; length stk = n\\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"\n(* your definition/proof here *)\n\ntext {*\nLemma @{thm [source] length_Suc_conv} may come in handy.\n\nProve that instruction sequences generated by @{text comp}\ncannot cause stack underflow: \\ @{text \"ok n (comp a) ?\"} \\ for\nsome suitable value of @{text \"?\"}.\n\\endexercise\n*)\n\n\nend\n\n", "meta": {"author": "Qdake", "repo": "M2-LMFI_MPRI_programming_exo", "sha": "22c51738c66a79d5ce91be923edd76e7e0c68ca1", "save_path": "github-repos/isabelle/Qdake-M2-LMFI_MPRI_programming_exo", "path": "github-repos/isabelle/Qdake-M2-LMFI_MPRI_programming_exo/M2-LMFI_MPRI_programming_exo-22c51738c66a79d5ce91be923edd76e7e0c68ca1/isabelle/concrete semantics/templates/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8976952989498449, "lm_q1q2_score": 0.7906873906116332}}
{"text": "(*  Title:      HOL/Isar_Examples/Group.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Basic group theory\\<close>\n\ntheory Group\n  imports Main\nbegin\n\nsubsection \\<open>Groups and calculational reasoning\\<close> \n\ntext \\<open>\n  Groups over signature \\<open>(* :: \\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> \\<alpha>, 1 :: \\<alpha>, inverse :: \\<alpha> \\<Rightarrow> \\<alpha>)\\<close> are\n  defined as an axiomatic type class as follows. Note that the parent class\n  \\<open>times\\<close> is provided by the basic HOL theory.\n\\<close>\n\nclass group = times + one + inverse +\n  assumes group_assoc: \"(x * y) * z = x * (y * z)\"\n    and group_left_one: \"1 * x = x\"\n    and group_left_inverse: \"inverse x * x = 1\"\n\ntext \\<open>\n  The group axioms only state the properties of left one and inverse, the\n  right versions may be derived as follows.\n\\<close>\n\ntheorem (in group) group_right_inverse: \"x * inverse x = 1\"\nproof -\n  have \"x * inverse x = 1 * (x * inverse x)\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1 * x * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x * x * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (inverse x * x) * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * 1 * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (1 * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1\"\n    by (simp only: group_left_inverse)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  With \\<open>group_right_inverse\\<close> already available, \\<open>group_right_one\\<close>\n  is now established much easier.\n\\<close>\n\ntheorem (in group) group_right_one: \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  \\<^medskip>\n  The calculational proof style above follows typical presentations given in\n  any introductory course on algebra. The basic technique is to form a\n  transitive chain of equations, which in turn are established by simplifying\n  with appropriate rules. The low-level logical details of equational\n  reasoning are left implicit.\n\n  Note that ``\\<open>\\<dots>\\<close>'' is just a special term variable that is bound\n  automatically to the argument\\<^footnote>\\<open>The argument of a curried infix expression\n  happens to be its right-hand side.\\<close> of the last fact achieved by any local\n  assumption or proven statement. In contrast to \\<open>?thesis\\<close>, the ``\\<open>\\<dots>\\<close>''\n  variable is bound \\<^emph>\\<open>after\\<close> the proof is finished.\n\n  There are only two separate Isar language elements for calculational proofs:\n  ``\\<^theory_text>\\<open>also\\<close>'' for initial or intermediate calculational steps, and\n  ``\\<^theory_text>\\<open>finally\\<close>'' for exhibiting the result of a calculation. These constructs\n  are not hardwired into Isabelle/Isar, but defined on top of the basic\n  Isar/VM interpreter. Expanding the \\<^theory_text>\\<open>also\\<close> and \\<^theory_text>\\<open>finally\\<close> derived language\n  elements, calculations may be simulated by hand as demonstrated below.\n\\<close>\n\ntheorem (in group) \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n\n  note calculation = this\n    \\<comment> \\<open>first calculational step: init calculation register\\<close>\n\n  have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>final calculational step: compose with transitivity rule \\dots\\<close>\n  from calculation\n    \\<comment> \\<open>\\dots\\ and pick up the final result\\<close>\n\n  show ?thesis .\nqed\n\ntext \\<open>\n  Note that this scheme of calculations is not restricted to plain\n  transitivity. Rules like anti-symmetry, or even forward and backward\n  substitution work as well. For the actual implementation of \\<^theory_text>\\<open>also\\<close> and\n  \\<^theory_text>\\<open>finally\\<close>, Isabelle/Isar maintains separate context information of\n  ``transitivity'' rules. Rule selection takes place automatically by\n  higher-order unification.\n\\<close>\n\n\nsubsection \\<open>Groups as monoids\\<close>\n\ntext \\<open>\n  Monoids over signature \\<open>(* :: \\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> \\<alpha>, 1 :: \\<alpha>)\\<close> are defined like this.\n\\<close>\n\nclass monoid = times + one +\n  assumes monoid_assoc: \"(x * y) * z = x * (y * z)\"\n    and monoid_left_one: \"1 * x = x\"\n    and monoid_right_one: \"x * 1 = x\"\n\ntext \\<open>\n  Groups are \\<^emph>\\<open>not\\<close> yet monoids directly from the definition. For monoids,\n  \\<open>right_one\\<close> had to be included as an axiom, but for groups both \\<open>right_one\\<close>\n  and \\<open>right_inverse\\<close> are derivable from the other axioms. With\n  \\<open>group_right_one\\<close> derived as a theorem of group theory (see @{thm\n  group_right_one}), we may still instantiate \\<open>group \\<subseteq> monoid\\<close> properly as\n  follows.\n\\<close>\n\ninstance group \\<subseteq> monoid\n  by intro_classes\n    (rule group_assoc,\n      rule group_left_one,\n      rule group_right_one)\n\ntext \\<open>\n  The \\<^theory_text>\\<open>instance\\<close> command actually is a version of \\<^theory_text>\\<open>theorem\\<close>, setting up a\n  goal that reflects the intended class relation (or type constructor arity).\n  Thus any Isar proof language element may be involved to establish this\n  statement. When concluding the proof, the result is transformed into the\n  intended type signature extension behind the scenes.\n\\<close>\n\n\nsubsection \\<open>More theorems of group theory\\<close>\n\ntext \\<open>\n  The one element is already uniquely determined by preserving an \\<^emph>\\<open>arbitrary\\<close>\n  group element.\n\\<close>\n\ntheorem (in group) group_one_equality:\n  assumes eq: \"e * x = x\"\n  shows \"1 = e\"\nproof -\n  have \"1 = x * inverse x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = (e * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = e * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = e * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Likewise, the inverse is already determined by the cancel property.\n\\<close>\n\ntheorem (in group) group_inverse_equality:\n  assumes eq: \"x' * x = 1\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = 1 * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = (x' * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = x' * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = x' * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The inverse operation has some further characteristic properties.\n\\<close>\n\ntheorem (in group) group_inverse_times: \"inverse (x * y) = inverse y * inverse x\"\nproof (rule group_inverse_equality)\n  show \"(inverse y * inverse x) * (x * y) = 1\"\n  proof -\n    have \"(inverse y * inverse x) * (x * y) =\n        (inverse y * (inverse x * x)) * y\"\n      by (simp only: group_assoc)\n    also have \"\\<dots> = (inverse y * 1) * y\"\n      by (simp only: group_left_inverse)\n    also have \"\\<dots> = inverse y * y\"\n      by (simp only: group_right_one)\n    also have \"\\<dots> = 1\"\n      by (simp only: group_left_inverse)\n    finally show ?thesis .\n  qed\nqed\n\ntheorem (in group) inverse_inverse: \"inverse (inverse x) = x\"\nproof (rule group_inverse_equality)\n  show \"x * inverse x = one\"\n    by (simp only: group_right_inverse)\nqed\n\ntheorem (in group) inverse_inject:\n  assumes eq: \"inverse x = inverse y\"\n  shows \"x = y\"\nproof -\n  have \"x = x * 1\"\n    by (simp only: group_right_one)\n  also have \"\\<dots> = x * (inverse y * y)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * (inverse x * y)\"\n    by (simp only: eq)\n  also have \"\\<dots> = (x * inverse x) * y\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * y\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = y\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Isar_Examples/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.790687384584781}}
{"text": "theory Chapter3\n  imports \"~~/src/HOL/IMP/BExp\"\n          \"~~/src/HOL/IMP/ASM\"          \nbegin\n\n(* Exercise 3.1. To show that asimp_const really folds all subexpressions of\nthe form Plus (N i ) (N j ), define a function optimal :: aexp \\<Rightarrow> bool that\nchecks that its argument does not contain a subexpression of the form Plus\n(N i ) (N j ). Then prove optimal (asimp_const a). *)\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N n) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (Plus a1 a2) = (optimal a1 & optimal a2)\"\n\nlemma \"optimal (asimp_const a)\"\n  apply(induction a)\n   apply(auto split: aexp.split)\n  done\n\n(* Exercise 3.2. In this exercise we verify constant folding for aexp where we\nsum up all constants, even if they are not next to each other. For example, Plus\n(N 1) (Plus (V x ) (N 2)) becomes Plus (V x ) (N 3). This goes beyond asimp.\nDefine a function full_asimp :: aexp \\<Rightarrow> aexp that sums up all constants and\nprove its correctness: aval (full_asimp a) s = aval a s. *)\n\n(* Strategy: Add all the constants first, ignoring variables. Then, add variables\nto result using asimp *)\n\n(* Add all constants, zero out variables *)\nfun addN :: \"aexp \\<Rightarrow> int\" where\n\"addN (N n) = n\" |\n\"addN (V x) = 0\" |\n\"addN (Plus a1 a2) = addN a1 + addN a2\"\n\n(* Manually checking that addN works as expected *)\nvalue \"addN (Plus (N 1) (Plus (V x) (N 2)))\"\nvalue \"addN (Plus (N 1) (Plus (N 2) (V x)))\"\nvalue \"addN (Plus (N 1) (Plus (N 2) (N 2)))\"\nvalue \"addN (Plus (V x) (Plus (N 2) (N 2)))\"\n\n(* Add all variables, zero out constants *)\nfun addV :: \"aexp \\<Rightarrow> aexp\" where\n\"addV (N n) = N 0\" |\n\"addV (V x) = V x\" |\n\"addV (Plus a1 a2) = Plus (addV a1) (addV a2)\"\n\n\n(* Manually checking that addN works as expected *)\nvalue \"addV (Plus (N 1) (Plus (N 2) (N 2)))\"\nvalue \"addV (Plus (V x) (Plus (N 2) (N 2)))\"\nvalue \"addV (Plus (N 1) (Plus (V x) (N 2)))\"\nvalue \"addV (Plus (N 1) (Plus (N 2) (V x)))\"\nvalue \"addV (Plus (V x) (Plus (V y) (N 2)))\"\nvalue \"addV (Plus (V x) (Plus (N 2) (V y)))\"\nvalue \"addV (Plus (N 1) (Plus (V x) (V y)))\"\nvalue \"addV (Plus (V x) (Plus (V y) (V z)))\"\n\n(* Define a function that combines the results of addN and addV *)\ndefinition addNV :: \"aexp \\<Rightarrow> aexp\" where\n\"addNV a = Plus (N (addN a)) (addV a)\"\n\nlemma addNV_equals_simp [simp]: \"aval (addNV a) s = aval a s\"\n  apply(simp add: addNV_def)\n  apply(induction a)\n    apply(auto)\n  done\n\n(* fun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp (N n) = N n\" |\n\"full_asimp (V x) = V x\" |\n\"full_asimp (Plus a1 (Plus a2 a3)) = plus (full_asimp a1) (plus (full_asimp a2) (full_asimp a3))\" |\n\"full_asimp (Plus (Plus a1 a2) a3) = plus (plus (full_asimp a1) (full_asimp a2)) (full_asimp a3)\" |\n\"full_asimp (Plus a1 a2) = plus (full_asimp a1) (full_asimp a2)\"\n*)\n\n(* Use addNV to define full_asimp, simplifying the aexp before passing it to asimp *)\ndefinition full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = asimp (addNV a)\"\n\n(* Manually verify that full_asimp works as expected *)\nvalue \"full_asimp (Plus (N 1) (Plus (V x) (V y)))\"\nvalue \"full_asimp (Plus (N 1) (Plus (V x) (N 2)))\"\nvalue \"full_asimp (Plus (N 1) (Plus (N 2) (V x)))\"\nvalue \"full_asimp (Plus (N 1) (Plus (N 2) (N 3)))\"\nvalue \"full_asimp (Plus (V x) (Plus (N 2) (N 3)))\"\nvalue \"full_asimp (Plus (V x) (Plus (V y) (N 3)))\"\nvalue \"full_asimp (Plus (V x) (Plus (N 2) (V y)))\"\nvalue \"full_asimp (Plus (V x) (Plus (V y) (V z)))\"\n\nlemma \"aval (full_asimp a) s = aval a s\"\n  apply(simp add: full_asimp_def)\n  done\n\n(* Exercise 3.3. Substitution is the process of replacing a variable by an ex-\npression in an expression. Define a substitution function subst :: vname \\<Rightarrow>\naexp \\<Rightarrow> aexp \\<Rightarrow> aexp such that subst x a e is the result of replacing every\noccurrence of variable x by a in e. For example:\n\nsubst ''x'' (N 3) (Plus (V ''x'' ) (V ''y'' )) = Plus (N 3) (V ''y'' )\n\nProve the so-called substitution lemma that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\naval (subst x a e) s = aval e (s(x := aval a s)). As a consequence prove\naval a 1 s = aval a 2 s =\\<Rightarrow> aval (subst x a 1 e) s = aval (subst x a 2 e) s. *)\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst x a (N n) = N n\" |\n\"subst x a (V y) = (if x = y then a else (V y))\" |\n\"subst x a (Plus a1 a2) = Plus (subst x a a1) (subst x a a2)\"\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s (x := aval a s))\"\n  apply(induction e)\n    apply(auto)\n  done\n\nlemma \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply(simp add: subst_lemma)\n  done\n\n(* Exercise 3.4. Take a copy of theory AExp and modify it as follows. Extend\ntype aexp with a binary constructor Times that represents multiplication.\nModify the definition of the functions aval and asimp accordingly. You can\nremove asimp_const. Function asimp should eliminate 0 and 1 from multi-\nplications as well as evaluate constant subterms. Update all proofs concerned. *)\n\n(* See Chapter3AExp.thy *)\n\n(* Exercise 3.5. Define a datatype aexp2 of extended arithmetic expressions\nthat has, in addition to the constructors of aexp, a constructor for modelling\na C-like post-increment operation x++, where x must be a variable. Define an\nevaluation function aval2 :: aexp2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state that returns both\nthe value of the expression and the new state. The latter is required because\npost-increment changes the state.\nExtend aexp2 and aval2 with a division operation. Model partiality of\ndivision by changing the return type of aval2 to (val \\<times> state) option. In\ncase of division by 0 let aval2 return None. Division on int is the infix div. *)\n\ndatatype aexp2 = N2 int | V2 vname | Plus2 aexp2 aexp2 | Increment2 vname | Divide2 aexp2 aexp2\n\n(* Used this to learn how to work with the option syntax: \nhttps://github.com/gsomix/concrete-semantics-solutions/blob/cf1b864744f80091a1f91a85b14b3d8edf7e0f9f/Chapter3.thy#L144 *)\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"aval2 (N2 n) s = Some (n, s)\" |\n\"aval2 (V2 v) s = Some (s v, s)\" |\n\"aval2 (Plus2 a1 a2) s = Option.bind (aval2 a1 s) (\\<lambda> (a1val, s1).\n                        Option.bind (aval2 a2 s1) (\\<lambda> (a2val, s2).\n                        Some (a1val + a2val, s2)))\" |\n\"aval2 (Increment2 x) s = Some ((s x), s (x := (s x) + 1))\" |\n\"aval2 (Divide2 a1 a2) s = Option.bind (aval2 a1 s) (\\<lambda> (a1val, s1).\n                          Option.bind (aval2 a2 s1) (\\<lambda> (a2val, s2).\n                          if a2val = 0 then None else Some ((a1val div a2val), s2)))\"\n\n(* Manually checking that everything works as expected *)\nvalue \"aval2 (Plus2 (Increment2 ''x'') (Divide2 (N2 10) (V2 ''x''))) (<''x'' := -1>)\"\nvalue \"aval2 (Plus2 (Increment2 ''x'') (Divide2 (N2 10) (V2 ''x''))) (<''x'' := 0>)\"\nvalue \"aval2 (Plus2 (Increment2 ''x'') (Divide2 (N2 10) (V2 ''x''))) (<''x'' := 1>)\"\nvalue \"aval2 (Plus2 (Increment2 ''x'') (Divide2 (N2 10) (V2 ''x''))) (<''x'' := 2>)\"\nvalue \"aval2 (Plus2 (Increment2 ''x'') (Divide2 (N2 10) (V2 ''x''))) (<''x'' := 3>)\"\nvalue \"aval2 (Plus2 (Increment2 ''x'') (Divide2 (N2 10) (V2 ''x''))) (<''x'' := 4>)\"\n\n(* Exercise 3.6. The following type adds a LET construct to arithmetic ex-\npressions:\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\nThe LET constructor introduces a local variable: the value of LET x e 1 e 2\nis the value of e 2 in the state where x is bound to the value of e 1 in the\noriginal state. Define a function lval :: lexp \\<Rightarrow> state \\<Rightarrow> int that evaluates\nlexp expressions. Remember s(x := i ).\nDefine a conversion inline :: lexp \\<Rightarrow> aexp. The expression LET x e 1 e 2\nis inlined by substituting the converted form of e 1 for x in the converted form\nof e 2. See Exercise 3.3 for more on substitution. Prove that inline is correct\nw.r.t. evaluation. *)\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n\"lval (Nl n) s = n\" |\n\"lval (Vl v) s = s v\" |\n\"lval (Plusl a1 a2) s = (lval a1 s) + (lval a2 s)\" |\n\"lval (LET x e1 e2) s = lval e2 (s(x := (lval e1 s)))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl n) = N n\" |\n\"inline (Vl v) = V v\" |\n\"inline (Plusl a1 a2) = Plus (inline a1) (inline a2)\" |\n\"inline (LET x e1 e2) = subst x (inline e1) (inline e2)\"\n\nlemma inline_lexp_equals_aexp: \"lval e s = aval (inline e) s\"\n  apply(induction e arbitrary: s)\n     apply(simp_all add: subst_lemma)\n  done\n\n(* Exercise 3.7. Define functions Eq, Le :: aexp \\<Rightarrow> aexp \\<Rightarrow> bexp and prove\nbval (Eq a 1 a 2 ) s = (aval a 1 s = aval a 2 s) and bval (Le a 1 a 2) s =\n(aval a 1 s \\<le> aval a 2 s). *)\n\ndefinition Or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Or b1 b2 = Not (And (Not b1) (Not b2))\"\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq b1 b2 = And (Not (Less b1 b2)) (Not (Less b2 b1))\"\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le b1 b2 = Or (Eq b1 b2) (Less b1 b2)\"\n\nlemma \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply(auto simp add: Eq_def)\n  done\n\nlemma \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply(auto simp add: Le_def Or_def Eq_def)\n  done\n\n(* Exercise 3.8. Consider an alternative type of boolean expressions featuring\na conditional:\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\nFirst define an evaluation function ifval :: ifexp \\<Rightarrow> state \\<Rightarrow> bool analogously\nto bval. Then define two functions b2ifexp :: bexp \\<Rightarrow> ifexp and if2bexp ::\nifexp \\<Rightarrow> bexp and prove their correctness, i.e., that they preserve the value\nof an expression. *)\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 v) s = v\" |\n\"ifval (If i1 i2 i3) s = (if (ifval i1 s) then (ifval i2 s) else (ifval i3 s))\" |\n\"ifval (Less2 a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc v) = (Bc2 v)\" |\n\"b2ifexp (Not b) = (If (b2ifexp b) (Bc2 False) (Bc2 True))\" |\n\"b2ifexp (And b1 b2) = (If (b2ifexp b1) (\n                        (If (b2ifexp b2) (Bc2 True) (Bc2 False))\n                       ) (Bc2 False))\" |\n\"b2ifexp (Less a1 a2) = Less2 a1 a2\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 v) = (Bc v)\" |\n\"if2bexp (If i1 i2 i3) = Or (And (if2bexp i1) (if2bexp i2)) (And (Not (if2bexp i1)) (if2bexp i3))\" |\n\"if2bexp (Less2 a1 a2) = Less a1 a2\"\n\nlemma ifval_b2ifexp: \"ifval (b2ifexp b) s = bval b s\"\n  apply(induction b)\n     apply(simp_all)\n  done\n\nlemma bval_if2bexp: \"bval (if2bexp i) s = ifval i s\"\n  apply(induction i)\n    apply(simp_all add: Or_def)\n  done\n\n(* Exercise 3.9. Define a new type of purely boolean expressions\n\ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\nwhere variables range over values of type bool:\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x ) s = s x\" |\n\"pbval (NOT b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b 1 b 2 ) s = (pbval b1 s \\<and> pbval b 2 s)\" |\n\"pbval (OR b 1 b 2 ) s = (pbval b1 s \\<or> pbval b 2 s)\"\n\nDefine a function is_nnf :: pbexp \\<Rightarrow> bool that checks whether a boolean\nexpression is in NNF (negation normal form), i.e., if NOT is only applied\ndirectly to VARs. Also define a function nnf :: pbexp \\<Rightarrow> pbexp that converts\na pbexp into NNF by pushing NOT inwards as much as possible. Prove that\nnnf preserves the value (pbval (nnf b) s = pbval b s) and returns an NNF\n(is_nnf (nnf b)).\nAn expression is in DNF (disjunctive normal form) if it is in NNF and if\nno OR occurs below an AND. Define a corresponding test is_dnf :: pbexp \\<Rightarrow>\nbool. An NNF can be converted into a DNF in a bottom-up manner. The crit-\nical case is the conversion of AND b 1 b 2 . Having converted b 1 and b 2 , apply\ndistributivity of AND over OR. Define a conversion function dnf_of_nnf ::\npbexp \\<Rightarrow> pbexp from NNF to DNF. Prove that your function preserves the\nvalue (pbval (dnf_of_nnf b) s = pbval b s) and converts an NNF into a\nDNF (is_nnf b =\\<Rightarrow> is_dnf (dnf_of_nnf b)). *)\n\ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\" |\n\"pbval (NOT b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b1 b2 ) s = (pbval b1 s \\<and> pbval b2 s)\" |\n\"pbval (OR b1 b2 ) s = (pbval b1 s \\<or> pbval b2 s)\"\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (NOT (VAR x)) = True\" |\n\"is_nnf (NOT b) = False\" |\n\"is_nnf (AND b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" |\n\"is_nnf (OR b1 b2) = (is_nnf b1 \\<or> is_nnf b2)\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = (VAR x)\" |\n\"nnf (NOT (VAR x)) = (NOT (VAR x))\" |\n\"nnf (NOT (OR b1 b2)) = AND (nnf (NOT b1)) (nnf (NOT b2))\" |\n\"nnf (NOT (AND b1 b2)) = OR (nnf (NOT b1)) (nnf (NOT b2))\" |\n\"nnf (NOT (NOT b)) = nnf b\" |\n\"nnf (AND b1 b2) = AND (nnf b1) (nnf b2)\" |\n\"nnf (OR b1 b2) = OR (nnf b1) (nnf b2)\"\n\nlemma ppbval_nnf [simp]: \"pbval (nnf b) s = pbval b s\"\n  apply(induction b arbitrary: s rule: nnf.induct)\n        apply(simp_all)\n  done\n\nlemma is_nnf_nnf: \"is_nnf (nnf b)\"\n  apply(induction b rule: nnf.induct)\n        apply(simp_all)\n  done\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\"  where\n\"is_dnf (AND (OR _ _) _) = False\" |\n\"is_dnf (AND _ (OR _ _)) = False\" |\n\"is_dnf (AND b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\" |\n\"is_dnf (OR b1 b2) = (is_dnf b1 \\<or> is_dnf b2)\" |\n\"is_dnf b = is_nnf b\"\n\n(* Apply distributivity of AND over OR *)\nfun dnf_dist :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"dnf_dist c (OR b1 b2) = OR (dnf_dist c b1) (dnf_dist c b2)\" |\n\"dnf_dist (OR b1 b2) c = OR (dnf_dist b1 c) (dnf_dist b2 c)\" |\n\"dnf_dist b1 b2 = AND b1 b2\"\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR x) = (VAR x)\" |\n\"dnf_of_nnf (NOT x) = (NOT x)\" |\n\"dnf_of_nnf (AND b1 b2) = dnf_dist (dnf_of_nnf b1) (dnf_of_nnf b2)\" |\n\"dnf_of_nnf (OR b1 b2) = OR (dnf_of_nnf b1) (dnf_of_nnf b2)\"\n\nlemma pbval_dnf_dist: \"pbval (dnf_dist b1 b2) s = pbval (AND b1 b2) s\"\n  apply(induction b1 b2 rule: dnf_dist.induct)\n              apply(auto)\n  done\n\nlemma is_dnf_dnf_dist: \"is_dnf b1 \\<and> is_dnf b2 \\<Longrightarrow> is_dnf (dnf_dist b1 b2)\"\n  apply(induction b1 b2 rule: dnf_dist.induct)\n              apply(auto)\n  done\n\nlemma pbval_dnf_of_nnf [simp]:  \"(pbval (dnf_of_nnf b) s = pbval b s)\"\n  apply(induction b rule:dnf_of_nnf.induct)\n     apply(simp_all add: pbval_dnf_dist)\n  done\n\nlemma is_dnf_dnf_of_nnf: \"(is_nnf b ==> is_dnf (dnf_of_nnf b))\"\n  apply(induction b rule:dnf_of_nnf.induct)\n     apply(auto simp add: is_dnf_dnf_dist)\n  done\n\n(* Exercise 3.11. This exercise is about a register machine and compiler for\naexp. The machine instructions are\n\ndatatype instr = LDI int reg | LD vname reg | ADD reg reg\n\nwhere type reg is a synonym for nat. Instruction LDI i r loads i into register\nr, LD x r loads the value of x into register r, and ADD r 1 r 2 adds register\nr 2 to register r 1 .\nDefine the execution of an instruction given a state and a register state\n(= function from registers to integers); the result is the new register state:\n\nfun exec1 :: instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int ) \\<Rightarrow> reg \\<Rightarrow> int\n\nDefine the execution exec of a list of instructions as for the stack machine.\nThe compiler takes an arithmetic expression a and a register r and pro-\nduces a list of instructions whose execution places the value of a into r. The\nregisters > r should be used in a stack-like fashion for intermediate results,\nthe ones < r should be left alone. Define the compiler and prove it correct:\nt. *)\n\ntype_synonym reg = nat\n\ndatatype instr = LDI int reg | LD vname reg | ADD reg reg\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec1 (LDI i r) _ rs = rs(r := i)\" |\n\"exec1 (LD v r) s rs = rs(r := s v)\" |\n\"exec1 (ADD r1 r2) _ rs = rs(r1 := rs r1 + rs r2)\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec [] _ rs = rs\" |\n\"exec (i#is) s rs = exec is s (exec1 i s rs)\"\n\nlemma reg_exec_append: \"exec (is1@is2) s rs = exec is2 s (exec is1 s rs)\"\n  apply(induction is1 arbitrary: rs)\n  apply(simp_all)\ndone\n\nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n\"comp (N n) r = [LDI n r]\" |\n\"comp (V v) r = [LD v r]\" |\n\"comp (Plus a1 a2) r = comp a1 r @ comp a2 (r+1) @ [ADD r (r+1)]\"\n\nlemma reg_exec_order: \"r2 > r1 \\<Longrightarrow> exec (comp a r2) s rs r1 = rs r1\"\n  apply(induction a arbitrary: r1 r2 rs)\n    apply(auto simp add: reg_exec_append)\n  done\n\ntheorem \"exec (comp a r) s rs r = aval a s\"\n  apply(induction a arbitrary: r rs)\n    apply(auto simp add: reg_exec_append reg_exec_order)\n  done\n\n(* Exercise 3.12. This is a variation on the previous exercise. Let the instruc-\ntion set be\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nAll instructions refer implicitly to register 0 as the source (MV0) or target\n(all others). Define a compiler pretty much as explained above except that\nthe compiled code leaves the value of the expression in register 0. Prove that\nexec (comp a r ) s rs 0 = aval a s. *)\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec01 (LDI0 i) _ rs = rs(0 := i)\" |\n\"exec01 (LD0 v) s rs = rs(0 := s v)\" |\n\"exec01 (MV0 r) s rs = rs(r := rs 0)\" |\n\"exec01 (ADD0 r) _ rs = rs(0 := rs 0 + rs r)\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec0 [] _ rs = rs\" |\n\"exec0 (i#is) s rs = exec0 is s (exec01 i s rs)\"\n\nlemma reg0_exec_append: \"exec0 (is1@is2) s rs = exec0 is2 s (exec0 is1 s rs)\"\n  apply(induction is1 arbitrary: rs)\n  apply(simp_all)\ndone\n\nfun comp0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0 (N n) _ = [LDI0 n]\" |\n\"comp0 (V v) _ = [LD0 v]\" |\n\"comp0 (Plus a1 a2) r = comp0 a1 r @ [MV0 (r+1)] @ comp0 a2 (r+1) @ [ADD0 (r+1)]\"\n\nlemma reg0_exec_order: \"(r1 \\<noteq> 0 \\<and> r2 \\<ge> r1) \\<Longrightarrow> exec0 (comp0 a r2) s rs r1 = rs r1\"\n  apply(induction a arbitrary: r1 r2 rs)\n    apply(auto simp add: reg0_exec_append)\n  done\n\ntheorem \"exec0 (comp0 a r) s rs 0 = aval a s\"\n  apply(induction a arbitrary: r rs)\n    apply(auto simp add: reg0_exec_append reg0_exec_order)\n  done\n\nend\n", "meta": {"author": "rasheedja", "repo": "concrete-semantics", "sha": "65997b65adccf690f076a79291aa643e2d1a9d43", "save_path": "github-repos/isabelle/rasheedja-concrete-semantics", "path": "github-repos/isabelle/rasheedja-concrete-semantics/concrete-semantics-65997b65adccf690f076a79291aa643e2d1a9d43/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.9099070109242131, "lm_q1q2_score": 0.7905515780682834}}
{"text": "(* \n  Title: Galois Connections\n  Author: Georg Struth \n  Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Galois Connections\\<close>\n\ntheory Galois_Connections\n  imports Order_Lattice_Props\n\nbegin\n\nsubsection \\<open>Definitions and Basic Properties\\<close>\n\ntext \\<open>The approach follows the Compendium of Continuous Lattices~\\cite{GierzHKLMS80}, without attempting completeness. \nFirst, left and right adjoints of a Galois connection are defined.\\<close>\n\ndefinition adj :: \"('a::ord \\<Rightarrow> 'b::ord) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\" (infixl \"\\<stileturn>\" 70) where \n  \"(f \\<stileturn> g) = (\\<forall>x y. (f x \\<le> y) = (x \\<le> g y))\"\n\ndefinition \"ladj (g::'a::Inf \\<Rightarrow> 'b::ord) = (\\<lambda>x. \\<Sqinter>{y. x \\<le> g y})\"\n\ndefinition \"radj (f::'a::Sup \\<Rightarrow> 'b::ord)  = (\\<lambda>y. \\<Squnion>{x. f x \\<le> y})\"\n\nlemma ladj_radj_dual:\n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::ord_with_dual\"\n  shows \"ladj f x = \\<partial> (radj (\\<partial>\\<^sub>F f) (\\<partial> x))\"\nproof-\n  have \"ladj f x = \\<partial> (\\<Squnion>(\\<partial> ` {y. \\<partial> (f y) \\<le> \\<partial> x}))\"\n    unfolding ladj_def by (metis (no_types, lifting) Collect_cong Inf_dual_var dual_dual_ord dual_iff)\n  also have \"... =  \\<partial> (\\<Squnion>{\\<partial> y|y. \\<partial> (f y) \\<le> \\<partial> x})\"\n    by (simp add: setcompr_eq_image)\n  ultimately show ?thesis\n    unfolding ladj_def radj_def map_dual_def comp_def\n    by (smt Collect_cong invol_dual_var)\nqed\n\nlemma radj_ladj_dual: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::ord_with_dual\"\n  shows \"radj f x = \\<partial> (ladj (\\<partial>\\<^sub>F f) (\\<partial> x))\"\n  by (metis fun_dual5 invol_dual_var ladj_radj_dual map_dual_def)\n\nlemma ladj_prop: \n  fixes g :: \"'b::Inf \\<Rightarrow> 'a::ord_with_dual\"\n  shows \"ladj g = Inf \\<circ> (-`) g \\<circ> \\<up>\"\n  unfolding ladj_def vimage_def upset_prop fun_eq_iff comp_def by simp\n\nlemma radj_prop: \n  fixes f :: \"'b::Sup \\<Rightarrow> 'a::ord\"\n  shows \"radj f = Sup \\<circ> (-`) f \\<circ> \\<down>\"\n  unfolding radj_def vimage_def downset_prop fun_eq_iff comp_def by simp\n\ntext \\<open>The first set of properties holds without any sort assumptions.\\<close>\n\nlemma adj_iso1: \"f \\<stileturn> g \\<Longrightarrow> mono f\"\n  unfolding adj_def mono_def by (meson dual_order.refl dual_order.trans) \n\nlemma adj_iso2: \"f \\<stileturn> g \\<Longrightarrow> mono g\"\n  unfolding adj_def mono_def by (meson dual_order.refl dual_order.trans) \n\nlemma adj_comp: \"f \\<stileturn> g \\<Longrightarrow> adj h k \\<Longrightarrow> (f \\<circ> h) \\<stileturn> (k \\<circ> g)\"\n  by (simp add: adj_def)\n\nlemma adj_dual: \n  fixes f :: \"'a::ord_with_dual \\<Rightarrow> 'b::ord_with_dual\"\n  shows \"f \\<stileturn> g = (\\<partial>\\<^sub>F g) \\<stileturn> (\\<partial>\\<^sub>F f)\"\n  unfolding adj_def map_dual_def comp_def by (metis (mono_tags, hide_lams) dual_dual_ord invol_dual_var)\n\nsubsection \\<open>Properties for (Pre)Orders\\<close>\n\ntext \\<open>The next set of properties holds in preorders or orders.\\<close>\n\nlemma adj_cancel1: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::ord\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> f \\<circ> g \\<le> id\"\n  by (simp add: adj_def le_funI)\n\nlemma adj_cancel2: \n  fixes f :: \"'a::ord \\<Rightarrow> 'b::preorder\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> id \\<le> g \\<circ> f\"\n  by (simp add: adj_def eq_iff le_funI)\n\nlemma adj_prop: \n  fixes f :: \"'a::preorder \\<Rightarrow>'a\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> f \\<circ> g \\<le> g \\<circ> f\"\n  using adj_cancel1 adj_cancel2 order_trans by blast\n\nlemma adj_cancel_eq1: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\n  unfolding adj_def comp_def fun_eq_iff by (meson eq_iff order_refl order_trans)\n\nlemma adj_cancel_eq2: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::preorder\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\n  unfolding adj_def comp_def fun_eq_iff by (meson eq_iff order_refl order_trans) \n\nlemma adj_idem1: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> (f \\<circ> g) \\<circ> (f \\<circ> g) = f \\<circ> g\"\n  by (simp add: adj_cancel_eq1 rewriteL_comp_comp)\n\nlemma adj_idem2: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::preorder\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> (g \\<circ> f) \\<circ> (g \\<circ> f) = g \\<circ> f\"\n  by (simp add: adj_cancel_eq2 rewriteL_comp_comp)\n\nlemma adj_iso3: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> mono (f \\<circ> g)\"\n   by (simp add: adj_iso1 adj_iso2 monoD monoI)\n\nlemma adj_iso4: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> mono (g \\<circ> f)\"\n  by (simp add: adj_iso1 adj_iso2 monoD monoI)\n\nlemma adj_canc1: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::ord\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((f \\<circ> g) x = (f \\<circ> g) y \\<longrightarrow> g x = g y)\"\n  unfolding adj_def comp_def by (metis eq_iff)\n \nlemma adj_canc2: \n  fixes f :: \"'a::ord \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((g \\<circ> f) x = (g \\<circ> f) y \\<longrightarrow> f x = f y)\"\n  unfolding adj_def comp_def by (metis eq_iff)\n\nlemma adj_sur_inv: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((surj f) = (f \\<circ> g = id))\"\n  unfolding adj_def surj_def comp_def by (metis eq_id_iff eq_iff order_refl order_trans)\n\nlemma adj_surj_inj: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((surj f) = (inj g))\"\n  unfolding adj_def inj_def surj_def by (metis eq_iff order_trans)\n\nlemma adj_inj_inv: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((inj f) = (g \\<circ> f = id))\"\n  by (metis adj_cancel_eq1 eq_id_iff inj_def o_apply)\n\nlemma adj_inj_surj: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\" \n  shows \"f \\<stileturn> g \\<Longrightarrow> ((inj f) = (surj g))\"\n  unfolding adj_def inj_def surj_def by (metis eq_iff order_trans)\n\nlemma surj_id_the_inv: \"surj f \\<Longrightarrow> g \\<circ> f = id \\<Longrightarrow> g = the_inv f\"\n  by (metis comp_apply id_apply inj_on_id inj_on_imageI2 surj_fun_eq the_inv_f_f)\n\nlemma inj_id_the_inv: \"inj f \\<Longrightarrow> f \\<circ> g = id \\<Longrightarrow> f = the_inv g\"\nproof -\n  assume a1: \"inj f\"\n  assume \"f \\<circ> g = id\"\n  hence \"\\<forall>x. the_inv g x = f x\"\n    using a1 by (metis (no_types) comp_apply eq_id_iff inj_on_id inj_on_imageI2 the_inv_f_f)\n  thus ?thesis \n    by presburger\nqed\n\n\nsubsection \\<open>Properties for Complete Lattices\\<close>\n\ntext \\<open>The next laws state that a function between complete lattices preserves infs \n  if and only if it has a lower adjoint.\\<close>\n\nlemma radj_Inf_pres: \n  fixes g :: \"'b::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  shows \"(\\<exists>f. f \\<stileturn> g) \\<Longrightarrow> Inf_pres g\"\n  apply (rule antisym, simp_all add: le_fun_def adj_def, safe)\n  apply (meson INF_greatest Inf_lower dual_order.refl dual_order.trans)\n  by (meson Inf_greatest dual_order.refl le_INF_iff)\n\nlemma ladj_Sup_pres: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows \"(\\<exists>g. f \\<stileturn> g) \\<Longrightarrow> Sup_pres f\"\n  using Sup_pres_map_dual_var adj_dual radj_Inf_pres by blast\n\nlemma radj_adj: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> g = (radj f)\"\n  unfolding adj_def radj_def by (metis (mono_tags, lifting) cSup_eq_maximum eq_iff mem_Collect_eq)\n\nlemma ladj_adj: \n  fixes g :: \"'b::complete_lattice_with_dual \\<Rightarrow> 'a::complete_lattice_with_dual\" \n  shows \"f \\<stileturn> g \\<Longrightarrow> f = (ladj g)\"\n  unfolding adj_def ladj_def by (metis (no_types, lifting) cInf_eq_minimum eq_iff mem_Collect_eq)\n\nlemma Inf_pres_radj_aux: \n  fixes g :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Inf_pres g \\<Longrightarrow> (ladj g) \\<stileturn> g\"\nproof-\n  assume a: \"Inf_pres g\"\n  {fix x y\n   assume b: \"ladj g x \\<le> y\" \n  hence \"g (ladj g x) \\<le> g y\"\n    by (simp add: Inf_subdistl_iso a monoD)\n  hence \"\\<Sqinter>{g y |y. x \\<le> g y} \\<le> g y\"\n    by (metis a comp_eq_dest_lhs setcompr_eq_image ladj_def)\n  hence \"x \\<le> g y\"\n    using dual_order.trans le_Inf_iff by blast  \n  hence \"ladj g x \\<le> y \\<longrightarrow> x \\<le> g y\"\n    by simp}\n  thus ?thesis \n    unfolding adj_def ladj_def by (meson CollectI Inf_lower)\nqed\n\nlemma Sup_pres_ladj_aux: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\" \n  shows \"Sup_pres f \\<Longrightarrow> f \\<stileturn> (radj f)\"\n  by (metis (no_types, hide_lams) Inf_pres_radj_aux Sup_pres_map_dual_var adj_dual fun_dual5 map_dual_def radj_adj)\n\nlemma Inf_pres_radj: \n  fixes g :: \"'b::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  shows \"Inf_pres g \\<Longrightarrow> (\\<exists>f. f \\<stileturn> g)\"\n  using Inf_pres_radj_aux by fastforce\n\nlemma Sup_pres_ladj: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows \"Sup_pres f \\<Longrightarrow> (\\<exists>g. f \\<stileturn> g)\"\n  using Sup_pres_ladj_aux by fastforce\n\nlemma Inf_pres_upper_adj_eq: \n  fixes g :: \"'b::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  shows \"(Inf_pres g) = (\\<exists>f. f \\<stileturn> g)\"\n  using radj_Inf_pres Inf_pres_radj by blast\n\nlemma Sup_pres_ladj_eq:\n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows  \"(Sup_pres f) = (\\<exists>g. f \\<stileturn> g)\"\n  using Sup_pres_ladj ladj_Sup_pres by blast\n\nlemma Sup_downset_adj: \"(Sup::'a::complete_lattice set \\<Rightarrow> 'a) \\<stileturn> \\<down>\"\n  unfolding adj_def downset_prop Sup_le_iff by force\n\nlemma Sup_downset_adj_var: \"(Sup (X::'a::complete_lattice set) \\<le> y) = (X \\<subseteq> \\<down>y)\"\n  using Sup_downset_adj adj_def by auto\n\ntext \\<open>Once again many statements arise by duality, which Isabelle usually picks up.\\<close>\n\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Order_Lattice_Props/Galois_Connections.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765281148513, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7905349358103503}}
{"text": "theory WholeChapter imports Main begin\n  \nsection \"Chapter 5\"\n  \nsubsection \"Exercise 5.1\"\n  \nlemma \n  assumes T : \"\\<forall> x y. T x y \\<or> T y x\"\n    and A: \"\\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n    and TA: \"\\<forall> x y. T x y \\<longrightarrow> A x y\" \n    and axy:\"A b c\"\n  shows \"T b c\"\nproof cases\n  (* NB: the positive case has to come first, negative case comes second *)\n  assume \"A b c \\<and> A c b\"\n  hence \"b = c\" using A by blast\n  thus \"T b c\"\n    using T by blast\nnext\n  assume \"\\<not>(A b c \\<and> A c b)\"\n  hence \"\\<not>A c b\"\n    by (simp add: axy)\n  moreover have \"\\<forall> x y. T y x \\<or> A x y\" using T TA by blast\n  ultimately show \"T b c\" by metis\nqed\n  \nsubsection \"Exercise 5.2\"\n  \nlemma \"(\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs) \n     \\<or> (\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs + 1)\"\nproof cases\n  assume \"even (length xs)\"\n  then obtain halfLength where hl:\"2 * halfLength = length xs\" \n    by (metis evenE)\n  then obtain ys\\<^sub>p where y:\"ys\\<^sub>p = take halfLength xs\" by simp \n  then obtain zs\\<^sub>p where z:\"zs\\<^sub>p = drop halfLength xs\" by simp\n  have \"ys\\<^sub>p @ zs\\<^sub>p = xs\"\n    by (simp add: y z)\n  moreover have \"length ys\\<^sub>p = length zs\\<^sub>p\" using hl y z by fastforce\n  ultimately show ?thesis by fastforce \nnext\n  assume \"\\<not>even (length xs)\"\n  hence \"odd (length xs)\" by simp\n  then obtain halfLength where hl:\"2 * halfLength + 1 = length xs\"\n    by (metis oddE) \n  then obtain ys\\<^sub>p where y:\"ys\\<^sub>p = take (halfLength + 1) xs\" by simp \n  then obtain zs\\<^sub>p where z:\"zs\\<^sub>p = drop (halfLength + 1) xs\" by simp\n  have \"ys\\<^sub>p @ zs\\<^sub>p = xs\"\n    by (simp add: y z)\n  moreover have \"length ys\\<^sub>p = length zs\\<^sub>p + 1\" using hl y z by fastforce\n  ultimately show ?thesis by fastforce \nqed\n  \nsubsection \"unnamed 'simple' Exercise\"\n  \ninductive ev :: \"nat \\<Rightarrow> bool\" where\n  ev0: \"ev 0\" |\n  evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n  \nlemma \"\\<not>ev (Suc(Suc(Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\"\n  hence \"ev (Suc 0)\" \n    using ev.cases by blast\n  thus False by cases\nqed\n  \n  (* I can't reproduce the proof on page 68.   *)\nlemma \"ev (Suc m) \\<Longrightarrow> \\<not>ev m\"\nproof(induction \"Suc m\" arbitrary: m rule:ev.induct)\n  (* case ev0 does not exist *)\n  case (evSS n)\n  then show ?case \n  proof - (* (rule (* classical *) ccontr) *)\n    assume \"ev (Suc n)\"\n      (*     thus False sorry\n  qed\nqed *)\n    oops\n      \nlemma \"ev (Suc m) \\<Longrightarrow> \\<not>ev m\"\nproof(induction \"Suc m\" arbitrary: m rule:ev.induct)\n  case (evSS n)\n  then show ?case\n    using ev.cases by auto\nqed\n  \nsubsection \"Exercise 5.3\"\n  \n  (* rule inversion *)\nlemma\n  assumes a:\"ev(Suc(Suc n))\"\n  shows \"ev n\"\nproof -\n  from a show \"ev n\"\n  proof cases\n    case evSS\n    then show ?thesis by simp \n  qed\nqed\n  \n  (* Can I do the same proof with induction? ... No.  *)\n  (* lemma\n  assumes a:\"ev(Suc(Suc n))\"\n  shows \"ev n\"\nproof(induction rule: ev.induct)\n  (* Failed to apply initial proof method  *)\n *)\n  \nsubsection \"Exercise 5.4\"\n  \nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\"\n  thus False\n  proof cases\n    assume \"ev (Suc 0)\" \n    thus False\n    proof cases\n    qed\n  qed\nqed\n  \nsubsection \"Exercise 5.5\"\n  \ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl: \"star r x x\" |\n  step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  \ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl: \"iter r 0 x x\" |\n  step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n  \nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof(induction rule: iter.induct)\n  case (refl x)\n  then show ?case using star.refl by fast\nnext\n  case (step x y n z)\n  then show ?case by (meson star.step)\nqed\n  \nsubsection \"Exercise 5.6\"\n  \nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n  \"elems [] = {}\" |\n  \"elems (x # xs) = insert x (elems xs)\"\n  \nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ (x # zs) \\<and> x \\<notin> elems ys\"\nproof(induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  fix a xs\n  let \"?case\" = \"\\<exists>ys zs. a # xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\n  assume IH : \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\" \n    and prems : \"x \\<in> elems (a # xs)\"\n  then show ?case\n  proof cases\n    assume xa:\"x = a\"\n    moreover obtain yp :: \"'a list\" where yp:\"yp = []\" by simp\n    moreover obtain zp :: \"'a list\" where zp:\"zp = xs\" by simp\n    ultimately have \"a # xs = yp @ x # zp \\<and> x \\<notin> elems yp\" by simp\n    then show ?thesis by blast \n  next\n    assume \"x \\<noteq> a\"\n    moreover then obtain ys zs where \"xs = ys @ (x # zs) \\<and> x \\<notin> elems ys\"\n      using IH prems by auto\n    moreover obtain ays where \"ays = a # ys\" by simp\n    ultimately have \"a # xs = ays @ x # zs \\<and> x \\<notin> elems ays\" by auto\n    thus ?thesis by blast\n  qed \nqed\n  \nsubsection \"Exercise 5.7\"\n  \n  (* copied from exercise 4.5 *)\n  \ndatatype alpha = a | b\n  \ninductive gram_S :: \"alpha list \\<Rightarrow> bool\" where\n  empty: \"gram_S []\" |\n  aSb: \"gram_S w \\<Longrightarrow> gram_S (a # w @ [b])\" |\n  SS: \"gram_S w\\<^sub>0 \\<Longrightarrow> gram_S w\\<^sub>1 \\<Longrightarrow> gram_S (w\\<^sub>0 @ w\\<^sub>1)\"\n  \n  (* end of copy-pasta *)\n  \n  (* Is the list a balanced list of parens? *)\n  (* n (the first arg) is number of open parens (number of unmatched a's) *)\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n  \"balanced 0 [] = True\" |\n  \"balanced _ [] = False\" |\n  \"balanced n (a # rest) = balanced (Suc n) rest\" |\n  \"balanced 0 (b # rest) = False\" |\n  \"balanced (Suc n) (b # rest) = balanced n rest\"\n  \nvalue \"balanced 0 [a,a,b,b]\"\nvalue \"balanced 0 [a,b,a,b]\"\n  \nvalue \"balanced 0 [a,b,b,b]\"\nvalue \"balanced 0 [a,a,a,b,b]\"\nvalue \"balanced 0 [a,a,b,b,b]\"\nvalue \"balanced 0 [a,a,b]\"\n  \nlemma insert_ab_middle_of_S:  \"gram_S (xs @ ys) \\<Longrightarrow> gram_S (xs @ [a, b] @ ys)\"\nproof(induction \"(xs @ ys)\" arbitrary: xs ys rule: gram_S.induct)\n  case empty\n  then show ?case\n    using aSb gram_S.empty by force \nnext\n  fix w xs ys\n  let \"?case\" = \"gram_S (xs @ [a, b] @ ys)\"\n  assume hyps: \n    \"gram_S w\" \n    \"\\<And>fs gs. w = fs @ gs \\<Longrightarrow> gram_S (fs @ [a, b] @ gs)\" \n    \"a # w @ [b] = xs @ ys\"    \n  then show ?case\n  proof(cases \"length xs > 0\")\n    case x_nontrivial:True\n    then show ?thesis\n    proof(cases \"length ys > 0\")\n      case y_nontrivial:True\n      obtain fs gs where fs:\"fs = drop 1 xs\" and gs:\"gs = butlast ys\" by simp\n      hence \"gram_S (fs @ [a, b] @ gs)\"\n        by (metis One_nat_def butlast_append butlast_snoc drop_0 drop_Suc hyps(2) hyps(3) length_greater_0_conv list.sel(3) tl_append2 x_nontrivial y_nontrivial)\n      hence gram_all:\"gram_S (a # fs @ [a, b] @ gs @ [b])\"\n        by (metis append.assoc gram_S.simps) \n      moreover have \"a # fs = xs\"\n        using fs x_nontrivial\n        by (metis Cons_nth_drop_Suc One_nat_def append_eq_Cons_conv drop_0 hyps(3)\n            length_greater_0_conv nth_Cons_0)\n      moreover have \"gs @ [b] = ys\"\n        using gs y_nontrivial\n        by (metis hyps(3) last.simps last_appendR length_greater_0_conv snoc_eq_iff_butlast)\n      ultimately show ?thesis by auto\n    next\n      case False\n      hence \"length ys = 0\" by simp\n      then show ?thesis \n        by (metis False SS aSb append_Nil append_Nil2 empty hyps(1) hyps(3) length_greater_0_conv) \n    qed\n  next\n    case False\n    hence \"length xs = 0\" by simp\n    then show ?thesis\n      by (metis False SS aSb append_self_conv2 empty hyps(1) hyps(3) length_greater_0_conv) \n  qed\nnext\n  fix w\\<^sub>0 w\\<^sub>1 xs ys\n  let \"?case\" = \"gram_S (xs @ [a, b] @ ys)\"\n  assume hyps: \n    \"gram_S w\\<^sub>0\" \n    \"\\<And>fs gs. w\\<^sub>0 = fs @ gs \\<Longrightarrow> gram_S (fs @ [a, b] @ gs)\" \n    \"gram_S w\\<^sub>1\"\n    \"\\<And>fs gs. w\\<^sub>1 = fs @ gs \\<Longrightarrow> gram_S (fs @ [a, b] @ gs)\" \n    \"w\\<^sub>0 @ w\\<^sub>1 = xs @ ys\"\n    (* We have no proof that w\\<^sub>0=xs, so while we can easily prove\n      gram_S (w\\<^sub>0 @ [a,b] @ w\\<^sub>1)\n      It does us no good, without said proof. *)\n  moreover have sab:\"gram_S [a,b]\"\n    using aSb empty by fastforce\n  ultimately show ?case \n  proof(cases \"length w\\<^sub>0 = length xs\")\n    case True\n    then show ?thesis \n      by (metis SS append_eq_append_conv hyps(1) hyps(3) hyps(5) sab)\n  next\n    case neq:False\n    then show ?thesis \n    proof(cases \"length w\\<^sub>0 < length xs\")\n      case True\n        (* Then if we inserted [a,b] after xs, we'd be inserting it into the middle of w\\<^sub>1. Prove\n        that's ok. *)\n      then obtain len_w1_prefix where lwp:\"len_w1_prefix = length xs - length w\\<^sub>0\" by simp\n      obtain lh rh where lhrh:\"lh = w\\<^sub>0 @ (take len_w1_prefix w\\<^sub>1) \\<and> rh = (drop len_w1_prefix w\\<^sub>1)\" by simp\n      hence \"gram_S (lh @ [a,b] @ rh)\"\n        using SS hyps(1) hyps(4) by auto\n      moreover have \"lh = xs \\<and> rh = ys\"\n        by (metis True append_eq_conv_conj append_self_conv2 drop_all drop_append hyps(5) less_or_eq_imp_le lhrh lwp take_all take_append) \n      ultimately show ?thesis by simp\n    next\n      case False\n      hence \"length w\\<^sub>0 > length xs\" \n        using neq by auto \n          (* Then if we inserted [a,b] after xs, we'd be inserting it into the middle of w\\<^sub>0. Prove\n        that's ok. *)\n      then obtain len_xs where \"len_xs = length xs\" by simp\n      moreover obtain lh rh where \"lh = (take len_xs w\\<^sub>0) \\<and> rh = (drop len_xs w\\<^sub>0) @ w\\<^sub>1\" by simp\n      moreover hence glh:\"gram_S (lh @ [a,b] @ rh)\"\n        by (metis append.assoc append_take_drop_id gram_S.simps hyps(2) hyps(3))\n      ultimately have \"lh = xs \\<and> rh = ys\" \n        by (metis False append_eq_append_conv_if hyps(5) le_neq_implies_less)\n      thus ?thesis using glh by simp\n    qed\n  qed\nqed\n  \n  (* The `a` in `replicate n a` is the first constructor of datatype alpha *)\nlemma balanced_implies_S:\"balanced n string \\<Longrightarrow> gram_S (replicate n a @ string)\"\nproof(induction n string rule: balanced.induct)\n  case 1\n  then show ?case by (simp add: empty)\nnext\n  case (2 v)\n  then show ?case by (simp add: empty)\nnext\n  case (3 n rest)\n  then show ?case \n    by (metis Cons_eq_appendI balanced.simps(3) replicate_Suc replicate_app_Cons_same) \nnext\n  case (4 rest)\n  then show ?case \n    using balanced.simps(4) by blast \nnext\n  case (5 n rest)\n  hence \"balanced n rest\"\n    by simp\n  hence 0:\"gram_S (replicate n a @ rest)\"\n    by (simp add: \"5.IH\")\n  hence \"gram_S (replicate n a @ [a, b] @ rest)\"\n    using insert_ab_middle_of_S by simp \n  hence \"gram_S (replicate (Suc n) a @ b # rest)\"\n    by (simp add: replicate_app_Cons_same)\n  thus ?case\n    by simp \nqed\n  \nlemma balanced_append_b:\"balanced n string \\<Longrightarrow> balanced (Suc n) (string @ [b])\"\nproof(induction \"(Suc n)\" \"(string @ [b])\" arbitrary: n string rule: balanced.induct)\n  case (2 v)\n  then show ?case by simp\nnext\n  case (3 rest)\n  then show ?case \n    by (metis Cons_eq_append_conv alpha.distinct(1) balanced.simps(3) list.inject)\nnext\n  case pop_b:(5 n rest)\n  moreover hence bal_sn:\"balanced (Suc n) (b # string)\"\n    using balanced.simps(5) by simp\n  ultimately show ?case\n  proof(cases n)\n    case 0\n    moreover have \"balanced (Suc n) (b # string)\"\n      by (metis bal_sn)\n    ultimately show ?thesis\n      using pop_b balanced.simps(4) by (metis butlast.simps(2) butlast_snoc)\n  next\n    case (Suc pred_n)\n    then show ?thesis \n      using pop_b bal_sn by (metis Cons_eq_append_conv balanced.simps(5))\n  qed\nqed\n  \nlemma balanced_append_string:\n  \"balanced 0 (drop len_prefix string) \\<Longrightarrow> balanced n (take len_prefix string)\n    \\<Longrightarrow> balanced n string\"  \nproof(induction string arbitrary: n len_prefix)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons x xs)\n  then show ?case\n  proof(induction n)\n    case 0\n    then show ?case \n      by (metis balanced.elims(2) balanced.simps(3) balanced.simps(4) drop_Cons' list.inject\n          list.simps(3) take_Cons')\n  next\n    case (Suc n)\n    then show ?case\n    proof(cases x)\n      case a\n      then show ?thesis\n        by (metis Cons.IH Suc.prems(2) Suc.prems(3) balanced.simps(2) balanced.simps(3) drop_Cons'\n            take_Cons')\n    next\n      case b\n      then show ?thesis \n        by (metis Cons.IH Suc.prems(2) Suc.prems(3) balanced.elims(2) balanced.simps(5) drop_Cons'\n            list.simps(3) take_Cons')\n    qed\n  qed\nqed \n  \nlemma S_implies_balanced:\"gram_S (replicate n a @ string) \\<Longrightarrow> balanced n string\"\nproof(induction \"(replicate n a @ string)\" arbitrary: n string rule: gram_S.induct)\n  case empty\n  then show ?case\n    by simp\nnext\n  case (aSb w)\n  show ?case\n  proof(cases n)\n    case 0\n    then show ?thesis\n      using aSb.hyps(2) aSb.hyps(3) balanced_append_b by auto\n  next\n    case (Suc n_minus_1)\n    moreover have 0:\"string = butlast string @ [b]\"\n      by (metis Suc_neq_Zero aSb.hyps(3) alpha.distinct(1) calculation last_ConsR last_appendL last_appendR last_replicate snoc_eq_iff_butlast)\n    ultimately have \"w = replicate n_minus_1 a @ (butlast string)\"\n      by (metis aSb.hyps(3) butlast_append list.sel(3) replicate_Suc replicate_append_same snoc_eq_iff_butlast tl_append2)\n    hence \"balanced n_minus_1 (butlast string)\"\n      using aSb.hyps(2) by blast\n    hence \"balanced n string\"\n      using 0 Suc balanced_append_b by fastforce\n    thus ?thesis by simp\n  qed\nnext\n  case (SS w\\<^sub>0 w\\<^sub>1)\n  then show ?case\n  proof(cases \"length w\\<^sub>0 = n\")\n    case True\n    then show ?thesis \n      by (metis SS.hyps(2) SS.hyps(4) SS.hyps(5) append.right_neutral append_eq_append_conv\n          append_self_conv2 balanced.simps(2) gr0_conv_Suc length_greater_0_conv length_replicate)\n  next\n    case len_ne:False\n    then show ?thesis \n    proof(cases \"length w\\<^sub>0 < n\")\n      case len_w_lt:True\n      hence \"w\\<^sub>0 = take (length w\\<^sub>0) (replicate n a @ string)\"\n        using SS.hyps(5) append_eq_conv_conj by blast\n      hence \"w\\<^sub>0 = take (length w\\<^sub>0) (replicate n a)\"\n        using len_w_lt by fastforce\n      hence \"w\\<^sub>0 = replicate (length w\\<^sub>0) a\"\n        by (metis length_replicate take_replicate)\n      hence \"w\\<^sub>0 = replicate (length w\\<^sub>0) a @ []\"\n        by simp\n      hence bal:\"balanced (length w\\<^sub>0) []\"\n        using SS.hyps(2) by blast\n          (* Now work on w\\<^sub>1 *)\n      hence \"w\\<^sub>1 = drop (length w\\<^sub>0) (replicate n a @ string)\"\n        using SS.hyps(5) append_eq_conv_conj by blast\n      hence \"w\\<^sub>1 = replicate (n - length w\\<^sub>0) a @ string\"\n        using len_w_lt by simp\n      hence \"balanced (n - length w\\<^sub>0) string\"\n        by (simp add: SS.hyps(4))\n      thus ?thesis \n        by (metis Nitpick.size_list_simp(2) SS.hyps(4) SS.hyps(5) bal balanced.simps(2)\n            self_append_conv2) \n    next\n      case False\n      hence len_w_gt:\"length w\\<^sub>0 > n\"\n        using len_ne by auto\n      hence \"w\\<^sub>0 = take (length w\\<^sub>0) (replicate n a @ string)\"\n        using SS.hyps(5) append_eq_conv_conj by blast\n      hence \"w\\<^sub>0 = replicate n a @ take (length w\\<^sub>0 - n) string\"\n        by (metis len_w_gt length_replicate less_imp_le_nat take_all take_append)\n      hence bal_w0:\"balanced n (take (length w\\<^sub>0 - n) string)\"\n        using SS.hyps(2) by blast\n          (* Now work on w\\<^sub>1 *)\n      hence \"w\\<^sub>1 = drop (length w\\<^sub>0) (replicate n a @ string)\"\n        using SS.hyps(5) append_eq_conv_conj by blast\n      hence \"w\\<^sub>1 = drop (length w\\<^sub>0 - n) string\"\n        using len_w_gt by simp\n      hence \"balanced 0 (drop (length w\\<^sub>0 - n) string)\"\n        by (simp add: SS.hyps(4))\n      then show ?thesis \n        using bal_w0 balanced_append_string by blast\n    qed\n  qed\nqed\n  \ntheorem \"balanced n w = gram_S (replicate n a @ w)\"\n  using S_implies_balanced balanced_implies_S by blast\n    \nend", "meta": {"author": "gittywithexcitement", "repo": "isabelle", "sha": "42c53b2797e1b14c741c316f2585449b818a8f07", "save_path": "github-repos/isabelle/gittywithexcitement-isabelle", "path": "github-repos/isabelle/gittywithexcitement-isabelle/isabelle-42c53b2797e1b14c741c316f2585449b818a8f07/Chapter 5/WholeChapter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762114, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.7904596557549878}}
{"text": "(*  Based on:   HOL/Hoare/Examples.thy\n*)\ntheory Labeled_Hoare_Examples\nimports\n  Labeled_Hoare\n  \"HOL-Hoare.Arith2\"\nbegin\n\n\nsubsubsection \\<open>Multiplication by successive addition\\<close>\n\nlemma multiply_by_add: \"VARS m s a b\n  {a=A \\<and> b=B}\n  m := 0; s := 0;\n  WHILE m\\<noteq>a\n  INV {s=m*b \\<and> a=A \\<and> b=B}\n  DO s := s+b; m := m+(1::nat) OD\n  {s = A*B}\"\nby vcg_simp\n\nlemma \"VARS M N P :: int\n {m=M \\<and> n=N}\n IF M < 0 THEN M := -M; N := -N ELSE SKIP FI;\n P := 0;\n WHILE 0 < M\n INV {0 \\<le> M \\<and> (\\<exists>p. p = (if m<0 then -m else m) \\<and> p*N = m*n \\<and> P = (p-M)*N)}\n DO P := P+N; M := M - 1 OD\n {P = m*n}\"\nproof casified_vcg_simp\n  case while\n  { case postcondition\n    then show ?case by auto\n  next\n    case invariant\n    { case basic\n      then show ?case by (auto simp: int_distrib)\n    }\n  }\nqed\n\n\nsubsubsection \\<open>Euclid's algorithm for GCD\\<close>\n\nlemma Euclid_GCD: \"VARS a b\n {0<A \\<and> 0<B}\n a := A; b := B;\n WHILE  a \\<noteq> b\n INV {0<a \\<and> 0<b \\<and> gcd A B = gcd a b}\n DO IF a<b THEN b := b-a ELSE a := a-b FI OD\n {a = gcd A B}\"\nproof casified_vcg_simp\n  case while\n  { case postcondition\n    then show ?case by (auto elim: gcd_nnn)\n  next\n    case invariant\n    { case cond\n      { case vc\n        then show ?case\n          by (simp_all add: linorder_not_less gcd_diff_l gcd_diff_r less_imp_le)\n      }\n    }\n  }\nqed\n\n\nsubsubsection \\<open>Dijkstra's extension of Euclid's algorithm for simultaneous GCD and SCM\\<close>\n\ntext\\<open>\n  From E.W. Disjkstra. Selected Writings on Computing, p 98 (EWD474),\n  where it is given without the invariant. Instead of defining scm\n  explicitly we have used the theorem scm x y = x*y/gcd x y and avoided\n  division by mupltiplying with gcd x y.\n\\<close>\n\nlemmas distribs =\n  diff_mult_distrib diff_mult_distrib2 add_mult_distrib add_mult_distrib2\n\nlemma gcd_scm: \"VARS a b x y\n {0<A \\<and> 0<B \\<and> a=A \\<and> b=B \\<and> x=B \\<and> y=A}\n WHILE  a \\<noteq> b\n INV {0<a \\<and> 0<b \\<and> gcd A B = gcd a b \\<and> 2*A*B = a*x + b*y}\n DO IF a<b THEN (b := b-a; x := x+y) ELSE (a := a-b; y := y+x) FI OD\n {a = gcd A B \\<and> 2*A*B = a*(x+y)}\"\nproof casified_vcg\n  case while {\n    case precondition then show ?case by simp\n  next\n    case invariant\n    case cond\n    case vc\n    then show ?case\n      by (simp add: distribs gcd_diff_r linorder_not_less gcd_diff_l)\n  next\n    case postcondition then show ?case\n      by (simp add: distribs gcd_nnn)\n  }\nqed\n\n\nsubsubsection \\<open>Power by iterated squaring and multiplication\\<close>\n\nlemma power_by_mult: \"VARS a b c\n {a=A \\<and> b=B}\n c := (1::nat);\n WHILE b \\<noteq> 0\n INV {A^B = c * a^b}\n DO  WHILE b mod 2 = 0\n     INV {A^B = c * a^b}\n     DO  a := a*a; b := b div 2 OD;\n     c := c*a; b := b - 1\n OD\n {c = A^B}\"\nproof casified_vcg_simp\n  case while\n  case invariant\n  case while\n  case postcondition\n  then show ?case by (cases b) simp_all\nqed\n\n\nsubsubsection \\<open>Factorial\\<close>\n\nlemma factorial: \"VARS a b\n {a=A}\n b := 1;\n WHILE a \\<noteq> 0\n INV {fac A = b * fac a}\n DO b := b*a; a := a - 1 OD\n {b = fac A}\"\n  apply vcg_simp\n  apply(clarsimp split: nat_diff_split)\n  done\n\nlemma \"VARS i f\n {True}\n i := (1::nat); f := 1;\n WHILE i \\<le> n INV {f = fac(i - 1) \\<and> 1 \\<le> i \\<and> i \\<le> n+1}\n DO f := f*i; i := i+1 OD\n {f = fac n}\"\nproof casified_vcg_simp\n  case while\n  { case invariant\n    { case basic\n      then show ?case by (induct i) simp_all\n    }\n  next\n    case postcondition\n    then have \"i = Suc n\" by simp\n    then show ?case by simp\n  }\nqed\n\n\nsubsubsection \\<open>Quicksort\\<close>\n\ntext \\<open>\n  The `partition' procedure for quicksort.\n  `A' is the array to be sorted (modelled as a list).\n  Elements of A must be of class order to infer at the end\n  that the elements between u and l are equal to pivot.\n\n  Ambiguity warnings of parser are due to := being used\n  both for assignment and list update.\n\\<close>\n\nlemma Partition:\n  fixes pivot\n  defines \"leq \\<equiv> \\<lambda>A i. \\<forall>k. k<i \\<longrightarrow> A!k \\<le> pivot\"\n  defines \"geq \\<equiv> \\<lambda>A i. \\<forall>k. i<k \\<and> k<length A \\<longrightarrow> pivot \\<le> A!k\"\n  shows \"\n   VARS A u l\n   {0 < length(A::('a::order)list)}\n   l := 0; u := length A - Suc 0;\n   WHILE l \\<le> u\n    INV {leq A l \\<and> geq A u \\<and> u<length A \\<and> l\\<le>length A}\n    DO WHILE l < length A \\<and> A!l \\<le> pivot\n        INV {leq A l \\<and> geq A u \\<and> u<length A \\<and> l\\<le>length A}\n        DO l := l+1 OD;\n       WHILE 0 < u \\<and> pivot \\<le> A!u\n        INV {leq A l \\<and> geq A u  \\<and> u<length A \\<and> l\\<le>length A}\n        DO u := u - 1 OD;\n       IF l \\<le> u THEN A := A[l := A!u, u := A!l] ELSE SKIP FI\n    OD\n   {leq A u \\<and> (\\<forall>k. u<k \\<and> k<l \\<longrightarrow> A!k = pivot) \\<and> geq A l}\"\n  unfolding leq_def geq_def\nproof casified_vcg_simp\n  case basic\n  then show ?case by auto\nnext\n  case while\n  { case postcondition\n    then show ?case by (force simp: nth_list_update)\n  next\n    case invariant\n    { case while\n      { case invariant\n        { case basic\n          then show ?case by (blast elim!: less_SucE intro: Suc_leI)\n        }\n      }\n    next\n      case whilea\n      { case invariant\n        { case basic\n          have lem: \"\\<And>m n. m - Suc 0 < n \\<Longrightarrow> m < Suc n\" by linarith\n          from basic show ?case by (blast elim!: less_SucE intro: less_imp_diff_less dest: lem)\n        }\n      }\n    }\n  }\nqed\n\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Case_Labeling/Examples/Hoare/Labeled_Hoare_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473647220787, "lm_q2_score": 0.9059898241909247, "lm_q1q2_score": 0.7903378355979725}}
{"text": "theory Sum\nimports Main  \nbegin\n\nprimrec sum :: \"nat list => nat\" where\n\"sum [] = 0\"| \n\"sum (x#l) = x + sum l\"\n\nprimrec sum_till :: \"nat \\<Rightarrow> nat\" where\n \"sum_till 0 = 0\"|\n \"sum_till (Suc k) = sum_till (k) + Suc(k)\" \n\nlemma sum_2_list [simp]: \"sum (l1 @ l2) = sum l1 + sum l2\"\n  apply(induct l1)\n  apply(auto)\n  done\n\ntheorem sum_rev_list: \"sum (rev l) = sum l\"\n  apply (induct l)\n  apply (auto simp: sum_2_list)\n  done    \ntext \\<open>\n  The sum of natural numbers \\<open>0 + \\<cdots> + n\\<close> equals \\<open>n \\<times> (n + 1)/2\\<close>. Avoiding\n  formal reasoning about division we prove this equation multiplied by \\<open>2\\<close>.\n\\<close>\n    \ntheorem sum_formula: \"2*sum_till n = n*(n+1)\"\n  apply (induct n)\n  apply (auto) \n  done  \n    \nend  ", "meta": {"author": "Perseus14", "repo": "Isabelle-Simulink", "sha": "0c306046c007c7e437435a85df8dc0d580fcc3f1", "save_path": "github-repos/isabelle/Perseus14-Isabelle-Simulink", "path": "github-repos/isabelle/Perseus14-Isabelle-Simulink/Isabelle-Simulink-0c306046c007c7e437435a85df8dc0d580fcc3f1/Codes/Scratch.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.95598134762883, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7903210611186204}}
{"text": "(*  \n  Title:    Random_Serial_Dictatorship.thy\n  Author:   Manuel Eberl, TU München\n\n  Definition and basic properties of Random Serial Dictatorship\n*)\n\nsection \\<open>Random Serial Dictatorship\\<close>\n\ntheory Random_Serial_Dictatorship\nimports\n  Complex_Main\n  Social_Decision_Schemes\n  Random_Permutations\n  Random_Dictatorship\nbegin\n\ntext \\<open>\n  Random Serial Dictatorship is an anonymous, neutral, strongly strategy-proof, \n  and ex-post efficient Social Decision Scheme that extends Random Dictatorship\n  to the domain of weak preferences.\n  \n  We define RSD using a fold over a random permutation. Effectively, we choose a random\n  order of the agents (in the form of a list) and then traverse that list from left to right,\n  where each agent in turn removes all the alternatives that are not top-ranked among the \n  remaining ones.\n\\<close>\ndefinition random_serial_dictatorship :: \n    \"'agent set \\<Rightarrow> 'alt set \\<Rightarrow> ('agent, 'alt) pref_profile \\<Rightarrow> 'alt lottery\" where\n  \"random_serial_dictatorship agents alts R = \n     fold_bind_random_permutation (\\<lambda>i alts. Max_wrt_among (R i) alts) pmf_of_set alts agents\"\n\ntext \\<open>\n  The following two facts correspond give an alternative recursive definition to\n  the above definition, which uses random permutations and list folding.\n\\<close>\nlemma random_serial_dictatorship_empty [simp]:\n  \"random_serial_dictatorship {} alts R = pmf_of_set alts\"\n  by (simp add: random_serial_dictatorship_def)\n\nlemma random_serial_dictatorship_nonempty:\n  \"finite agents \\<Longrightarrow> agents \\<noteq> {} \\<Longrightarrow> \n    random_serial_dictatorship agents alts R =\n      do {\n        i \\<leftarrow> pmf_of_set agents;\n        random_serial_dictatorship (agents - {i}) (Max_wrt_among (R i) alts) R\n      }\"\n  by (simp add: random_serial_dictatorship_def)\n     \n     \ntext \\<open>\n  We define the RSD winners w.r.t. a given set of alternatives and a fixed permutation \n  (i.e. list) of agents. In contrast to the above definition, the RSD winners are \n  determined by traversing the list of agents from right to left.\n    This may seem strange, but it makes induction much easier, since induction over @{term foldr}\n  does not require generalisation over the set of alternatives and is therefore much \n  easier than over @{term foldl}. \n\\<close>\ndefinition rsd_winners where\n  \"rsd_winners R alts agents = foldr (\\<lambda>i alts. Max_wrt_among (R i) alts) agents alts\"\n\nlemma rsd_winners_empty [simp]: \"rsd_winners R alts [] = alts\"\n  by (simp add: rsd_winners_def)\n\nlemma rsd_winners_Cons [simp]:\n  \"rsd_winners R alts (i # agents) = Max_wrt_among (R i) (rsd_winners R alts agents)\"\n  by (simp add: rsd_winners_def)\n\nlemma rsd_winners_map [simp]: \n  \"rsd_winners R alts (map f agents) = rsd_winners (R \\<circ> f) alts agents\"\n  by (simp add: rsd_winners_def foldr_map o_def)\n\n  \ntext \\<open>\n  There is now another alternative definition of RSD in terms of the\n  RSD winners. This will mostly be used for induction.\n\\<close>\nlemma random_serial_dictatorship_altdef:\n  assumes \"finite agents\"\n  shows   \"random_serial_dictatorship agents alts R =\n             do {\n               agents' \\<leftarrow> pmf_of_set (permutations_of_set agents);\n               pmf_of_set (rsd_winners R alts agents')\n             }\"\n   by (simp add: random_serial_dictatorship_def \n         fold_bind_random_permutation_foldr assms rsd_winners_def)\n   \ntext \\<open>\n  The following lemma shows that folding from left to right yields the same\n  distribution. This is probably the most commonly used definition in the literature,\n  along with the recursive one.\n\\<close>\nlemma random_serial_dictatorship_foldl:\n  assumes \"finite agents\"\n  shows   \"random_serial_dictatorship agents alts R =\n             do {\n               agents' \\<leftarrow> pmf_of_set (permutations_of_set agents);\n               pmf_of_set (foldl (\\<lambda>alts i. Max_wrt_among (R i) alts) alts agents')\n             }\"\n   by (simp add: random_serial_dictatorship_def fold_bind_random_permutation_foldl assms)\n\n\n   \nsubsection \\<open>Auxiliary facts about RSD\\<close>\n\n\nsubsubsection \\<open>Pareto-equivalence classes\\<close>\n\ntext \\<open>\n  First of all, we introduce the auxiliary notion of a Pareto-equivalence class.\n  A non-empty set of alternatives is a Pareto equivalence class if all agents are \n  indifferent between all alternatives in it, and if some alternative @{term \"x::'alt\"} \n  is contained in the set, any other alternative @{term \"y::'alt\"} is contained in it\n  if and only if, to all agents, @{term y} is at least as good as @{term x}.\n    The importance of this notion lies in the fact that the set of RSD winners is always\n  a Pareto-equivalence class, which we will later use to show ex-post efficiency and\n  strategy-proofness.\n\\<close>\n\ndefinition RSD_pareto_eqclass where\n  \"RSD_pareto_eqclass agents alts R A \\<longleftrightarrow>\n     A \\<noteq> {} \\<and> A \\<subseteq> alts \\<and> (\\<forall>x\\<in>A. \\<forall>y\\<in>alts. y \\<in> A \\<longleftrightarrow> (\\<forall>i\\<in>agents. R i x y))\"\n\nlemma RSD_pareto_eqclassI:\n  assumes \"A \\<noteq> {}\" \"A \\<subseteq> alts\" \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> alts \\<Longrightarrow> y \\<in> A \\<longleftrightarrow> (\\<forall>i\\<in>agents. R i x y)\"\n  shows   \"RSD_pareto_eqclass agents alts R A\"\n  using assms unfolding RSD_pareto_eqclass_def by simp_all\n\nlemma RSD_pareto_eqclassD:\n  assumes \"RSD_pareto_eqclass agents alts R A\"\n  shows   \"A \\<noteq> {}\" \"A \\<subseteq> alts\" \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> alts \\<Longrightarrow> y \\<in> A \\<longleftrightarrow> (\\<forall>i\\<in>agents. R i x y)\"\n  using assms unfolding RSD_pareto_eqclass_def by simp_all\n\nlemma RSD_pareto_eqclass_indiff_set:\n  assumes \"RSD_pareto_eqclass agents alts R A\" \"i \\<in> agents\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"R i x y\"\n  using assms unfolding RSD_pareto_eqclass_def by blast\n\nlemma RSD_pareto_eqclass_empty [simp, intro!]:\n  \"alts \\<noteq> {} \\<Longrightarrow> RSD_pareto_eqclass {} alts R alts\"\n  using assms by (auto intro!: RSD_pareto_eqclassI)\n\nlemma (in pref_profile_wf) RSD_pareto_eqclass_insert:\n  assumes \"RSD_pareto_eqclass agents' alts R A\" \"finite alts\"\n          \"i \\<in> agents\" \"agents' \\<subseteq> agents\"\n  shows   \"RSD_pareto_eqclass (insert i agents') alts R (Max_wrt_among (R i) A)\"\nproof -\n  from assms interpret total_preorder_on alts \"R i\" by simp\n  show ?thesis\n  proof (intro RSD_pareto_eqclassI Max_wrt_among_nonempty Max_wrt_among_subset, goal_cases)\n    case (3 x y)\n    with RSD_pareto_eqclassD[OF assms(1)] \n      show ?case unfolding Max_wrt_among_total_preorder \n      by (blast intro: trans)\n  qed (insert RSD_pareto_eqclassD[OF assms(1)] assms(2), \n       simp_all add: Int_absorb1 Int_absorb2 finite_subset)[2]\nqed\n\n\nsubsubsection \\<open>Facts about RSD winners\\<close>\n\ncontext pref_profile_wf\nbegin\n\ntext \\<open>\n  Any RSD winner is a valid alternative.  \n\\<close>\nlemma rsd_winners_subset:\n  assumes \"set agents' \\<subseteq> agents\" \n  shows   \"rsd_winners R alts' agents' \\<subseteq> alts'\"\nproof -\n  {\n    fix i assume \"i \\<in> agents\"\n    then interpret total_preorder_on alts \"R i\" by simp\n    have \"Max_wrt_among (R i) A \\<subseteq> A\" for A\n      using Max_wrt_among_subset by blast\n  } note A = this\n\n  from \\<open>set agents' \\<subseteq> agents\\<close> show \"rsd_winners R alts' agents' \\<subseteq> alts'\"\n    using A by (induction agents') auto\nqed\n\ntext \\<open>\n  There is always at least one RSD winner.  \n\\<close>\nlemma rsd_winners_nonempty:\n  assumes finite: \"finite alts\"  and \"alts' \\<noteq> {}\"  \"set agents' \\<subseteq> agents\" \"alts' \\<subseteq> alts\" \n  shows   \"rsd_winners R alts' agents' \\<noteq> {}\"\nproof -\n  {\n    fix i assume \"i \\<in> agents\"\n    then interpret total_preorder_on alts \"R i\" by simp\n    have \"Max_wrt_among (R i) A \\<noteq> {}\" if \"A \\<subseteq> alts\" \"A \\<noteq> {}\" for A\n      using that assms by (intro Max_wrt_among_nonempty) (auto simp: Int_absorb)\n  } note B = this\n\n  with \\<open>set agents' \\<subseteq> agents\\<close> \\<open>alts' \\<subseteq> alts\\<close> \\<open>alts' \\<noteq> {}\\<close> \n    show \"rsd_winners R alts' agents' \\<noteq> {}\"\n  proof (induction agents')\n    case (Cons i agents')\n    with B[of i \"rsd_winners R alts' agents'\"] rsd_winners_subset[of agents' alts'] finite wf\n      show ?case by auto\n  qed simp\nqed\n\ntext \\<open>\n  Obviously, the set of RSD winners is always finite.\n\\<close>\nlemma rsd_winners_finite: \n  assumes \"set agents' \\<subseteq> agents\" \"finite alts\" \"alts' \\<subseteq> alts\"\n  shows   \"finite (rsd_winners R alts' agents')\"\n  by (rule finite_subset[OF subset_trans[OF rsd_winners_subset]]) fact+\n\nlemmas rsd_winners_wf = \n  rsd_winners_subset rsd_winners_nonempty rsd_winners_finite\n\n\ntext \\<open>\n  The set of RSD winners is a Pareto-equivalence class.\n\\<close>\nlemma RSD_pareto_eqclass_rsd_winners_aux:\n  assumes finite: \"finite alts\" and \"alts \\<noteq> {}\" and \"set agents' \\<subseteq> agents\"\n  shows   \"RSD_pareto_eqclass (set agents') alts R (rsd_winners R alts agents')\"\n  using \\<open>set agents' \\<subseteq> agents\\<close>\nproof (induction agents')\n  case (Cons i agents')\n  from Cons.prems show ?case\n    by (simp only: set_simps rsd_winners_Cons,\n        intro RSD_pareto_eqclass_insert[OF Cons.IH finite]) simp_all\nqed (insert assms, simp_all)\n\nlemma RSD_pareto_eqclass_rsd_winners:\n  assumes finite: \"finite alts\" and \"alts \\<noteq> {}\" and \"set agents' = agents\"\n  shows   \"RSD_pareto_eqclass agents alts R (rsd_winners R alts agents')\"\n  using RSD_pareto_eqclass_rsd_winners_aux[of agents'] assms by simp\n\n\ntext \\<open>\n  For the proof of strategy-proofness, we need to define indifference sets\n  and lift preference relations to sets in a specific way.\n\\<close>\ncontext\nbegin\n\ntext \\<open>\n  An indifference set for a given preference relation is a non-empty set of alternatives \n  such that the agent is indifferent over all of them.\n\\<close>\nprivate definition indiff_set where\n  \"indiff_set S A \\<longleftrightarrow> A \\<noteq> {} \\<and> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. S x y)\"\n  \nprivate lemma indiff_set_mono: \"indiff_set S A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> indiff_set S B\"\n  unfolding indiff_set_def by blast\n\n  \ntext \\<open>\n  Given an arbitrary set of alternatives @{term A} and an indifference set @{term B},\n  we say that @{term B} is set-preferred over @{term A} w.r.t. the preference \n  relation @{term R} if all (or, equivalently, any) of the alternatives in @{term B} \n  are preferred over all alternatives in @{term A}.\n\\<close>\nprivate definition RSD_set_rel where\n  \"RSD_set_rel S A B \\<longleftrightarrow> indiff_set S B \\<and> (\\<forall>x\\<in>A. \\<forall>y\\<in>B. S x y)\" \n\ntext \\<open>\n  The most-preferred alternatives (w.r.t. @{term R}) among any non-empty set of alternatives \n  form an indifference set w.r.t. @{term R}.\n\\<close>\nprivate lemma indiff_set_Max_wrt_among:\n  assumes \"finite carrier\" \"A \\<subseteq> carrier\" \"A \\<noteq> {}\" \"total_preorder_on carrier S\" \n  shows   \"indiff_set S (Max_wrt_among S A)\"\n  unfolding indiff_set_def\nproof\n  from assms(4) interpret total_preorder_on carrier S .\n  from assms(1-3) \n    show \"Max_wrt_among S A \\<noteq> {}\" by (intro Max_wrt_among_nonempty) auto\n  from assms(1-3) show \"\\<forall>x\\<in>Max_wrt_among S A. \\<forall>y\\<in>Max_wrt_among S A. S x y\"\n    by (auto simp: indiff_set_def Max_wrt_among_total_preorder)\nqed\n\n\ntext \\<open>\n  We now consider the set of RSD winners in the setting of a preference profile @{term R}\n  and a manipulated profile @{term \"R(i := Ri')\"}.\n    This theorem shows that the set of RSD winners in the outcome is either the same\n  in both cases or the outcome for the truthful profile is an indifference set that is\n  set-preferred over the outcome for the manipulated profile.\n\\<close>\nlemma rsd_winners_manipulation_aux:\n  assumes wf: \"total_preorder_on alts Ri'\"\n      and i: \"i \\<in> agents\" and \"set agents' \\<subseteq> agents\" \"finite agents\" \n      and finite: \"finite alts\" and \"alts \\<noteq> {}\"\n  defines [simp]: \"w' \\<equiv> rsd_winners (R(i := Ri')) alts\" and [simp]: \"w \\<equiv> rsd_winners R alts\"\n  shows   \"w' agents' = w agents' \\<or> RSD_set_rel (R i) (w' agents') (w agents')\"\nusing \\<open>set agents' \\<subseteq> agents\\<close>\nproof (induction agents')\n  case (Cons j agents')\n  from wf i interpret Ri: total_preorder_on alts \"R i\" by simp\n  from wf Cons.prems interpret Rj: total_preorder_on alts \"R j\" by simp\n  from wf interpret Ri': total_preorder_on alts \"Ri'\" .\n  from wf assms Cons.prems \n    have indiff_set: \"indiff_set (R i) (Max_wrt_among (R i) (rsd_winners R alts agents'))\"\n    by (intro indiff_set_Max_wrt_among[OF finite] rsd_winners_wf) simp_all\n        \n  show ?case\n  proof (cases \"j = i\")\n    assume j [simp]: \"j = i\"\n    from indiff_set Cons have \"RSD_set_rel (R i) (w' (j # agents')) (w (j # agents'))\"\n      unfolding RSD_set_rel_def\n      by (auto simp: Ri.Max_wrt_among_total_preorder Ri'.Max_wrt_among_total_preorder)\n    thus ?case ..\n  next\n    assume j [simp]: \"j \\<noteq> i\"\n    from Cons have \"w' agents' = w agents' \\<or> RSD_set_rel (R i) (w' agents') (w agents')\" by simp\n    thus ?case\n    proof\n      assume rel: \"RSD_set_rel (R i) (w' agents') (w agents')\"\n      hence indiff_set: \"indiff_set (R i) (w agents')\" by (simp add: RSD_set_rel_def)\n      moreover from Cons.prems finite \\<open>alts \\<noteq> {}\\<close> \n        have \"w agents' \\<subseteq> alts\" \"w agents' \\<noteq> {}\" unfolding w_def\n        by (intro rsd_winners_wf; simp)+\n      with finite have \"Max_wrt_among (R j) (w agents') \\<noteq> {}\"\n        by (intro Rj.Max_wrt_among_nonempty) auto\n      ultimately have \"indiff_set (R i) (w (j # agents'))\"\n        by (intro indiff_set_mono[OF indiff_set] Rj.Max_wrt_among_subset)\n           (simp_all add: Rj.Max_wrt_among_subset)\n      moreover from rel have \"\\<forall>x\\<in>w' (j # agents'). \\<forall>y\\<in>w (j # agents'). R i x y\"\n        by (auto simp: RSD_set_rel_def Rj.Max_wrt_among_total_preorder)\n      ultimately have \"RSD_set_rel (R i) (w' (j # agents')) (w (j # agents'))\"\n        unfolding RSD_set_rel_def ..\n      thus ?case ..\n    qed simp_all\n  qed\nqed simp_all\n\n\ntext \\<open>\n  The following variant of the previous theorem is slightly easier to use.\n  We eliminate the case where the two outcomes are the same by observing that\n  the original outcome is then also set-preferred to the manipulated one.\n    In essence, this means that no matter what manipulation is done, the \n  original outcome is always set-preferred to the manipulated one.\n\\<close>\nlemma rsd_winners_manipulation:\n  assumes wf: \"total_preorder_on alts Ri'\"\n      and i: \"i \\<in> agents\" and \"set agents' = agents\" \"finite agents\" \n      and finite: \"finite alts\" and \"alts \\<noteq> {}\"\n  defines [simp]: \"w' \\<equiv> rsd_winners (R(i := Ri')) alts\" and [simp]: \"w \\<equiv> rsd_winners R alts\"\n  shows   \"\\<forall>x\\<in>w' agents'. \\<forall>y\\<in>w agents'. x \\<preceq>[R i] y\"\nproof -\n  have \"w' agents' = w agents' \\<or> RSD_set_rel (R i) (w' agents') (w agents')\"\n    using rsd_winners_manipulation_aux[OF assms(1-2) _ assms(4-6)] assms(3) by simp\n  thus ?thesis\n  proof\n    assume eq: \"w' agents' = w agents'\"\n    from assms have \"RSD_pareto_eqclass (set agents') alts R (w agents')\" unfolding w_def\n      by (intro RSD_pareto_eqclass_rsd_winners_aux) simp_all\n    from RSD_pareto_eqclass_indiff_set[OF this, of i] i eq assms(3) show ?thesis by auto\n  qed (auto simp: RSD_set_rel_def)\nqed\n\nend\n\n\ntext \\<open>\n  The lottery that RSD yields is well-defined.\n\\<close>\nlemma random_serial_dictatorship_support:\n  assumes \"finite agents\" \"finite alts\" \"agents' \\<subseteq> agents\" \"alts' \\<noteq> {}\" \"alts' \\<subseteq> alts\"\n  shows   \"set_pmf (random_serial_dictatorship agents' alts' R) \\<subseteq> alts'\"\nproof -\n  from assms have [simp]: \"finite agents'\" by (auto intro: finite_subset)\n  have A: \"set_pmf (pmf_of_set (rsd_winners R alts' agents'')) \\<subseteq> alts'\"\n    if \"agents'' \\<in> permutations_of_set agents'\" for agents''\n    using that assms rsd_winners_wf[where alts' = alts' and agents' = agents'']\n    by (auto simp: permutations_of_set_def)\n  from assms show ?thesis\n    by (auto dest!: A simp add: random_serial_dictatorship_altdef)\nqed\n\ntext \\<open>\n  Permutation of alternatives commutes with RSD winners.\n\\<close>\nlemma rsd_winners_permute_profile:\n  assumes perm: \"\\<sigma> permutes alts\" and \"set agents' \\<subseteq> agents\" \n  shows   \"rsd_winners (permute_profile \\<sigma> R) alts agents' = \\<sigma> ` rsd_winners R alts agents'\"\n  using \\<open>set agents' \\<subseteq> agents\\<close>\nproof (induction agents')\n  case Nil\n  from perm show ?case by (simp add: permutes_image)\nnext\n  case (Cons i agents')\n  from wf Cons interpret total_preorder_on alts \"R i\" by simp\n  from perm Cons show ?case\n    by (simp add: permute_profile_map_relation Max_wrt_among_map_relation_bij permutes_bij)\nqed\n\nlemma random_serial_dictatorship_singleton:\n  assumes \"finite agents\" \"finite alts\" \"agents' \\<subseteq> agents\" \"x \\<in> alts\"\n  shows   \"random_serial_dictatorship agents' {x} R = return_pmf x\" (is \"?d = _\")\nproof -\n  from assms have \"set_pmf ?d \\<subseteq> {x}\" \n    by (intro random_serial_dictatorship_support) simp_all\n  thus ?thesis by (simp add: set_pmf_subset_singleton)\nqed\n\nend\n\n\nsubsection \\<open>Proofs of properties\\<close>\n\ntext \\<open>\n  With all the facts that we have proven about the RSD winners, the hard work is\n  mostly done. We can now simply fix some arbitrary order of the agents, apply the \n  theorems about the RSD winners, and show the properties we want to show without \n  doing much reasoning about probabilities.\n\\<close>\n\ncontext election\nbegin     \n\nabbreviation \"RSD \\<equiv> random_serial_dictatorship agents alts\"\n\nsubsubsection \\<open>Well-definedness\\<close>\n\nsublocale RSD: social_decision_scheme agents alts RSD\n  using pref_profile_wf.random_serial_dictatorship_support[of agents alts]\n  by unfold_locales (simp_all add: lotteries_on_def)\n\n\nsubsubsection \\<open>RD extension\\<close>\n\nlemma RSD_extends_RD:\n  assumes wf: \"is_pref_profile R\" and unique: \"has_unique_favorites R\"\n  shows   \"RSD R = RD R\"\nproof -\n  from wf interpret pref_profile_wf agents alts R .\n  from unique interpret pref_profile_unique_favorites by unfold_locales\n  have \"RSD R = pmf_of_set agents \\<bind> \n                  (\\<lambda>i. random_serial_dictatorship (agents - {i}) (favorites R i) R)\"\n    by (simp add: random_serial_dictatorship_nonempty favorites_altdef Max_wrt_def)\n  also from assms have \"\\<dots> = pmf_of_set agents \\<bind> (\\<lambda>i. return_pmf (favorite R i))\"\n    by (intro bind_pmf_cong refl, subst random_serial_dictatorship_singleton [symmetric])\n       (auto simp: unique_favorites favorite_in_alts)\n  also from assms have \"\\<dots> = RD R\"\n    by (simp add: random_dictatorship_unique_favorites map_pmf_def)\n  finally show ?thesis .\nqed\n  \n\nsubsubsection \\<open>Anonymity\\<close>\n\ntext \\<open>\n  Anonymity is a direct consequence of the fact that we randomise over all\n  permutations in a uniform way.\n\\<close>\n\nsublocale RSD: anonymous_sds agents alts RSD\nproof\n  fix \\<pi> R assume perm: \"\\<pi> permutes agents\" and wf: \"is_pref_profile R\"\n  let ?f = \"\\<lambda>agents'. pmf_of_set (rsd_winners R alts agents')\"\n  from perm wf have \"RSD (R \\<circ> \\<pi>) = map_pmf (map \\<pi>) (pmf_of_set (permutations_of_set agents)) \\<bind> ?f\"\n    by (simp add: random_serial_dictatorship_altdef bind_map_pmf)\n  also from perm have \"\\<dots> = RSD R\"\n    by (simp add: map_pmf_of_set_inj permutes_inj_on inj_on_mapI\n                  permutations_of_set_image_permutes random_serial_dictatorship_altdef)\n  finally show \"RSD (R \\<circ> \\<pi>) = RSD R\" .\nqed\n\n\nsubsubsection \\<open>Neutrality\\<close>\n\ntext \\<open>\n  Neutrality follows from the fact that the RSD winners of a permuted profile \n  are simply the image of the original RSD winners under the permutation.\n\\<close>\n\nsublocale RSD: neutral_sds agents alts RSD\nproof\n  fix \\<sigma> R assume perm: \"\\<sigma> permutes alts\" and wf: \"is_pref_profile R\"\n  from wf interpret pref_profile_wf agents alts R .\n  from perm show \"RSD (permute_profile \\<sigma> R) = map_pmf \\<sigma> (RSD R)\"\n    by (auto intro!: bind_pmf_cong dest!: permutations_of_setD(1) \n             simp: random_serial_dictatorship_altdef rsd_winners_permute_profile\n                   map_bind_pmf map_pmf_of_set_inj permutes_inj_on rsd_winners_wf)\nqed\n\n\nsubsubsection \\<open>Ex-post efficiency\\<close>\n\ntext \\<open>\n  Ex-post efficiency follows from the fact that the set of RSD winners \n  is a Pareto-equivalence class.\n\\<close>\n\nsublocale RSD: ex_post_efficient_sds agents alts RSD\nproof\n  fix R assume wf: \"is_pref_profile R\"\n  then interpret pref_profile_wf agents alts R .\n  {\n    fix x assume x: \"x \\<in> set_pmf (RSD R)\" \"x \\<in> pareto_losers R\"\n    from x(2) obtain y where [simp]: \"y \\<in> alts\" and pareto: \"y \\<succ>[Pareto(R)] x\" \n      by (cases rule: pareto_losersE)\n    from x have [simp]: \"x \\<in> alts\" using pareto_loser_in_alts by simp\n\n    from x(1) obtain agents' where agents': \"set agents' = agents\" and \n        \"x \\<in> set_pmf (pmf_of_set (rsd_winners R alts agents'))\"\n      by (auto simp: random_serial_dictatorship_altdef dest: permutations_of_setD)\n    with wf have x': \"x \\<in> rsd_winners R alts agents'\"\n      using rsd_winners_wf[where alts' = alts and agents' = agents']\n      by (subst (asm) set_pmf_of_set) (auto simp: permutations_of_setD)\n\n    from wf agents' \n      have \"RSD_pareto_eqclass agents alts R (rsd_winners R alts agents')\"\n      by (intro RSD_pareto_eqclass_rsd_winners) simp_all\n    hence winner_iff: \"y \\<in> rsd_winners R alts agents' \\<longleftrightarrow> (\\<forall>i\\<in>agents. x \\<preceq>[R i] y)\"\n      if \"x \\<in> rsd_winners R alts agents'\" \"y \\<in> alts\" for x y\n      using that unfolding RSD_pareto_eqclass_def by blast\n    from x' pareto winner_iff[of x y] winner_iff[of y x] have False\n      by (force simp: strongly_preferred_def Pareto_iff)\n  }\n  thus \"set_pmf (RSD R) \\<inter> pareto_losers R = {}\" by blast\nqed\n\n\nsubsubsection \\<open>Strong strategy-proofness\\<close>\n\ntext \\<open>\n  Strong strategy-proofness is slightly more difficult to show. We have already shown\n  that the set of RSD winners for the truthful profile is always set-preferred (by the\n  manipulating agent) to the RSD winners for the manipulated profile.\n    This can now be used to show strategy-proofness: We recall that the set of RSD \n  winners is always an indifference class. Therefore, given any fixed alternative @{term \"x::'alt\"}\n  and considering a fixed order of the agents, either all of the RSD winners in the original\n  profile are at least as good as @{term \"x::'alt\"} or none of them are, and, since the original \n  RSD winners are set-preferred to the manipulated ones, none of the RSD winners in the\n  manipulated case are at least as good than @{term \"x::'alt\"} either in that case.\n    This means that for a fixed order of agents, either the probability that the original  \n  outcome is at least as good as @{term \"x::'alt\"} is 1 or the probability that the manipulated\n  outcome is at least as good as @{term \"x::'alt\"} is 0.\n    Therefore, the original lottery is clearly SD-preferred to the manipulated one.\n\\<close>\n\nsublocale RSD: strongly_strategyproof_sds agents alts RSD\nproof (unfold_locales, rule)\n  fix R i Ri' x\n  assume wf: \"is_pref_profile R\" and i [simp]: \"i \\<in> agents\" and x: \"x \\<in> alts\" and\n         wf': \"total_preorder_on alts Ri'\"\n  interpret R: pref_profile_wf agents alts R by fact\n  def R' \\<equiv> \"R (i := Ri')\"\n  from wf wf' have \"is_pref_profile R'\" by (simp add: R'_def R.wf_update)\n  then interpret R': pref_profile_wf agents alts R' .\n  note wf = wf wf'\n  let ?A = \"preferred_alts (R i) x\"\n  from wf interpret Ri: total_preorder_on alts \"R i\" by simp\n\n  {\n    fix agents' assume agents': \"agents' \\<in> permutations_of_set agents\"\n    from agents' have [simp]: \"set agents' = agents\"\n      by (simp add: permutations_of_set_def)\n      \n    let ?W = \"rsd_winners R alts agents'\" and ?W' = \"rsd_winners R' alts agents'\"\n    have indiff_set: \"RSD_pareto_eqclass agents alts R ?W\"\n      by (rule R.RSD_pareto_eqclass_rsd_winners; simp add: wf)+\n    from R.rsd_winners_wf R'.rsd_winners_wf\n      have winners: \"?W \\<subseteq> alts\" \"?W \\<noteq> {}\" \"finite ?W\" \"?W' \\<subseteq> alts\" \"?W' \\<noteq> {}\" \"finite ?W'\"\n      by simp_all\n    \n    from \\<open>?W \\<noteq> {}\\<close> obtain y where y: \"y \\<in> ?W\" by blast\n    with winners have [simp]: \"y \\<in> alts\" by blast\n    from wf' i have mono: \"\\<forall>x\\<in>?W'. \\<forall>y\\<in>?W. R i x y\" unfolding R'_def\n      by (intro R.rsd_winners_manipulation) simp_all\n    \n    have \"lottery_prob (pmf_of_set ?W) ?A \\<ge> lottery_prob (pmf_of_set ?W') ?A\"\n    proof (cases \"y \\<succeq>[R i] x\")\n      case True\n      with y RSD_pareto_eqclass_indiff_set[OF indiff_set(1), of i]  winners\n        have \"?W \\<subseteq> preferred_alts (R i) x\"\n        by (auto intro: Ri.trans simp: preferred_alts_def)\n      with winners show ?thesis\n        by (subst (2) measure_pmf_of_set) (simp_all add: Int_absorb2)\n    next\n      case False\n      with y mono have \"?W' \\<inter> preferred_alts (R i) x = {}\" \n        by (auto intro: Ri.trans simp: preferred_alts_def)\n      with winners show ?thesis\n        by (subst (1) measure_pmf_of_set)\n           (simp_all add: Int_absorb2 one_ereal_def measure_nonneg)\n    qed\n    hence \"emeasure (measure_pmf (pmf_of_set ?W)) ?A \\<ge> emeasure (measure_pmf (pmf_of_set ?W')) ?A\"\n      by (simp add: measure_pmf.emeasure_eq_measure)\n  }\n  hence \"emeasure (measure_pmf (RSD R)) ?A \\<ge> emeasure (measure_pmf (RSD R')) ?A\"\n    by (auto simp: random_serial_dictatorship_altdef AE_measure_pmf_iff\n             intro!: nn_integral_mono_AE)\n  thus \"lottery_prob (RSD R) ?A \\<ge> lottery_prob (RSD R') ?A\" \n    by (simp add: measure_pmf.emeasure_eq_measure)\nqed\n\nend\n\nend\n", "meta": {"author": "pruvisto", "repo": "SDS", "sha": "e0b280bff615c917314285b374d77416c51ed39c", "save_path": "github-repos/isabelle/pruvisto-SDS", "path": "github-repos/isabelle/pruvisto-SDS/SDS-e0b280bff615c917314285b374d77416c51ed39c/thys/Randomised_Social_Choice/Random_Serial_Dictatorship.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.8615382165412809, "lm_q1q2_score": 0.7902912876294025}}
{"text": "(*  Title:      Pure/Examples/First_Order_Logic.thy\n    Author:     Makarius\n*)\n\nsection \\<open>A simple formulation of First-Order Logic\\<close>\n\ntext \\<open>\n  The subsequent theory development illustrates single-sorted intuitionistic\n  first-order logic with equality, formulated within the Pure framework.\n\\<close>\n\ntheory First_Order_Logic\n  imports Pure\nbegin\n\nsubsection \\<open>Abstract syntax\\<close>\n\ntypedecl i\ntypedecl o\n\njudgment Trueprop :: \"o \\<Rightarrow> prop\"  (\"_\" 5)\n\n\nsubsection \\<open>Propositional logic\\<close>\n\naxiomatization false :: o  (\"\\<bottom>\")\n  where falseE [elim]: \"\\<bottom> \\<Longrightarrow> A\"\n\n\naxiomatization imp :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longrightarrow>\" 25)\n  where impI [intro]: \"(A \\<Longrightarrow> B) \\<Longrightarrow> A \\<longrightarrow> B\"\n    and mp [dest]: \"A \\<longrightarrow> B \\<Longrightarrow> A \\<Longrightarrow> B\"\n\n\naxiomatization conj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<and>\" 35)\n  where conjI [intro]: \"A \\<Longrightarrow> B \\<Longrightarrow> A \\<and> B\"\n    and conjD1: \"A \\<and> B \\<Longrightarrow> A\"\n    and conjD2: \"A \\<and> B \\<Longrightarrow> B\"\n\ntheorem conjE [elim]:\n  assumes \"A \\<and> B\"\n  obtains A and B\nproof\n  from \\<open>A \\<and> B\\<close> show A\n    by (rule conjD1)\n  from \\<open>A \\<and> B\\<close> show B\n    by (rule conjD2)\nqed\n\n\naxiomatization disj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<or>\" 30)\n  where disjE [elim]: \"A \\<or> B \\<Longrightarrow> (A \\<Longrightarrow> C) \\<Longrightarrow> (B \\<Longrightarrow> C) \\<Longrightarrow> C\"\n    and disjI1 [intro]: \"A \\<Longrightarrow> A \\<or> B\"\n    and disjI2 [intro]: \"B \\<Longrightarrow> A \\<or> B\"\n\n\ndefinition true :: o  (\"\\<top>\")\n  where \"\\<top> \\<equiv> \\<bottom> \\<longrightarrow> \\<bottom>\"\n\ntheorem trueI [intro]: \\<top>\n  unfolding true_def ..\n\n\ndefinition not :: \"o \\<Rightarrow> o\"  (\"\\<not> _\" [40] 40)\n  where \"\\<not> A \\<equiv> A \\<longrightarrow> \\<bottom>\"\n\ntheorem notI [intro]: \"(A \\<Longrightarrow> \\<bottom>) \\<Longrightarrow> \\<not> A\"\n  unfolding not_def ..\n\ntheorem notE [elim]: \"\\<not> A \\<Longrightarrow> A \\<Longrightarrow> B\"\n  unfolding not_def\nproof -\n  assume \"A \\<longrightarrow> \\<bottom>\" and A\n  then have \\<bottom> ..\n  then show B ..\nqed\n\n\ndefinition iff :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longleftrightarrow>\" 25)\n  where \"A \\<longleftrightarrow> B \\<equiv> (A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n\ntheorem iffI [intro]:\n  assumes \"A \\<Longrightarrow> B\"\n    and \"B \\<Longrightarrow> A\"\n  shows \"A \\<longleftrightarrow> B\"\n  unfolding iff_def\nproof\n  from \\<open>A \\<Longrightarrow> B\\<close> show \"A \\<longrightarrow> B\" ..\n  from \\<open>B \\<Longrightarrow> A\\<close> show \"B \\<longrightarrow> A\" ..\nqed\n\ntheorem iff1 [elim]:\n  assumes \"A \\<longleftrightarrow> B\" and A\n  shows B\nproof -\n  from \\<open>A \\<longleftrightarrow> B\\<close> have \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n    unfolding iff_def .\n  then have \"A \\<longrightarrow> B\" ..\n  from this and \\<open>A\\<close> show B ..\nqed\n\ntheorem iff2 [elim]:\n  assumes \"A \\<longleftrightarrow> B\" and B\n  shows A\nproof -\n  from \\<open>A \\<longleftrightarrow> B\\<close> have \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n    unfolding iff_def .\n  then have \"B \\<longrightarrow> A\" ..\n  from this and \\<open>B\\<close> show A ..\nqed\n\n\nsubsection \\<open>Equality\\<close>\n\naxiomatization equal :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infixl \"=\" 50)\n  where refl [intro]: \"x = x\"\n    and subst: \"x = y \\<Longrightarrow> P x \\<Longrightarrow> P y\"\n\ntheorem trans [trans]: \"x = y \\<Longrightarrow> y = z \\<Longrightarrow> x = z\"\n  by (rule subst)\n\ntheorem sym [sym]: \"x = y \\<Longrightarrow> y = x\"\nproof -\n  assume \"x = y\"\n  from this and refl show \"y = x\"\n    by (rule subst)\nqed\n\n\nsubsection \\<open>Quantifiers\\<close>\n\naxiomatization All :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<forall>\" 10)\n  where allI [intro]: \"(\\<And>x. P x) \\<Longrightarrow> \\<forall>x. P x\"\n    and allD [dest]: \"\\<forall>x. P x \\<Longrightarrow> P a\"\n\naxiomatization Ex :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<exists>\" 10)\n  where exI [intro]: \"P a \\<Longrightarrow> \\<exists>x. P x\"\n    and exE [elim]: \"\\<exists>x. P x \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\n\nlemma \"(\\<exists>x. P (f x)) \\<longrightarrow> (\\<exists>y. P y)\"\nproof\n  assume \"\\<exists>x. P (f x)\"\n  then obtain x where \"P (f x)\" ..\n  then show \"\\<exists>y. P y\" ..\nqed\n\nlemma \"(\\<exists>x. \\<forall>y. R x y) \\<longrightarrow> (\\<forall>y. \\<exists>x. R x y)\"\nproof\n  assume \"\\<exists>x. \\<forall>y. R x y\"\n  then obtain x where \"\\<forall>y. R x y\" ..\n  show \"\\<forall>y. \\<exists>x. R x y\"\n  proof\n    fix y\n    from \\<open>\\<forall>y. R x y\\<close> have \"R x y\" ..\n    then show \"\\<exists>x. R x y\" ..\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Pure/Examples/First_Order_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9273633016692238, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7900697580708188}}
{"text": "theory Trees2_4\nimports Main\nbegin\n\ndatatype bdd = Leaf bool | Branch bdd bdd\n\n(* eval accepts:\n     - a function that can tell if a given variable\n       number is true or false\n     - a starting variable number. variables are numbered\n       starting from 0 at root and increases gradually as\n       we come down (ordered bdd).\n     - a binary decision tree\n   responds with the final truth value *)\nprimrec eval :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> bdd \\<Rightarrow> bool\"\nwhere\n  \"eval f n (Leaf b) = b\"\n| \"eval f n (Branch l r) = (if f n then eval f (Suc n) r else eval f (Suc n) l)\"\n\nprimrec bdd_unop :: \"(bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd\"\nwhere\n  \"bdd_unop f (Leaf a) = Leaf (f a)\"\n| \"bdd_unop f (Branch l r) = Branch (bdd_unop f l) (bdd_unop f r)\"\n\nprimrec bdd_binop :: \"(bool \\<Rightarrow> bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\nwhere\n  \"bdd_binop f (Leaf a) b = bdd_unop (f a) b\"\n| \"bdd_binop f (Branch l r) b = (case b of\n    Leaf a \\<Rightarrow> Branch (bdd_binop f l b) (bdd_binop f r b)\n  | Branch l' r' \\<Rightarrow> Branch (bdd_binop f l l') (bdd_binop f r r'))\"\n\ntheorem [simp]: \"eval e n (bdd_unop f b) = f (eval e n b)\"\n  apply (induct b arbitrary:n)\n  apply simp+\ndone\n\ntheorem [simp]:\"eval e n (bdd_binop f b1 b2) = f (eval e n b1) (eval e n b2)\"\n  apply (induct b1 arbitrary:n b2)\n  apply simp\n  apply simp\n  apply (case_tac b2)\n  apply auto\ndone\n\n(*\nfun bdd_and :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\nwhere\n  \"bdd_and b1 b2 = bdd_binop (\\<lambda> x y. x \\<and> y) b1 b2\"\n*)\n\ndefinition bdd_and: \"bdd_and \\<equiv> bdd_binop op \\<and>\"\ndefinition bdd_or: \"bdd_or \\<equiv> bdd_binop op \\<or>\"\ndefinition bdd_not: \"bdd_not \\<equiv> bdd_unop Not\"\ndefinition bdd_xor: \"bdd_xor b1 b2 \\<equiv> bdd_or (bdd_and (bdd_not b1) b2) (bdd_and b1 (bdd_not b2))\"\n\ntheorem [simp]: \"eval e n (bdd_and b1 b2) = (eval e n b1 \\<and> eval e n b2)\"\n  by (auto simp add:bdd_and)\n\ntheorem [simp]: \"eval e n (bdd_or b1 b2) = (eval e n b1 \\<or> eval e n b2)\"\n  by (auto simp add:bdd_or)\n\ntheorem [simp]: \"eval e n (bdd_not b) = Not (eval e n b)\"\n  by (auto simp add:bdd_not)\n\ntheorem [simp]:\"eval e n (bdd_xor b1 b2) = (let x = (eval e n b1) in let y = (eval e n b2) in (\\<not>x \\<and> y) \\<or> (x \\<and> \\<not>y) )\"\n  by (auto simp add:bdd_xor bdd_and bdd_or bdd_not)\n\nprimrec bdd_var :: \"nat \\<Rightarrow> bdd\"\nwhere\n  \"bdd_var 0 = Branch (Leaf False) (Leaf True)\"\n| \"bdd_var (Suc n) = Branch (bdd_var n) (bdd_var n)\"\n\nvalue \"bdd_var 0\"\nvalue \"bdd_var 1\"\nvalue \"bdd_var 2\"\n\ntheorem \"\\<forall> i . e i \\<longrightarrow> eval e 0 (bdd_var i)\"\n(*Unsure about this one *)\noops\n\n(* Solution copied from text *)\ntheorem [simp]: \"\\<forall> j. eval e j (bdd_var i) = e (i + j)\"\n  apply (induct i)\n  apply auto\ndone\n\ndatatype form = T | Var nat | And form form | Xor form form\n\ndefinition xor : \"xor x y \\<equiv> (\\<not>x \\<and> y) \\<or> (x \\<and> \\<not>y)\"\n\nprimrec evalf :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\"\nwhere\n  \"evalf f T = True\"\n| \"evalf f (Var n) = f n\"\n| \"evalf f (And f1 f2) = (evalf f f1 \\<and> evalf f f2)\"\n| \"evalf f (Xor f1 f2) = xor (evalf f f1) (evalf f f2)\"\n\nfun mk_bdd :: \"form \\<Rightarrow> bdd\"\nwhere\n  \"mk_bdd T = Leaf True\"\n| \"mk_bdd (Var n) = bdd_var n\"\n| \"mk_bdd (And f1 f2) = bdd_and (mk_bdd f1) (mk_bdd f2)\"\n| \"mk_bdd (Xor f1 f2) = bdd_xor (mk_bdd f1) (mk_bdd f2)\"\n\nvalue \"mk_bdd T\"\nvalue \"mk_bdd (Var 1)\"\n\ntheorem \"eval e 0 (mk_bdd f) = evalf e f\"\n  apply (induct f)\n  apply (auto simp add:xor)\ndone\n\nend\n\n", "meta": {"author": "jineshkj", "repo": "cis700_assured_systems", "sha": "9fb270e519a3644f9713bee8cef082aefbc8228f", "save_path": "github-repos/isabelle/jineshkj-cis700_assured_systems", "path": "github-repos/isabelle/jineshkj-cis700_assured_systems/cis700_assured_systems-9fb270e519a3644f9713bee8cef082aefbc8228f/Isabelle_HOL_Exercies/Trees2_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.8519528057272543, "lm_q1q2_score": 0.7900697548135021}}
{"text": "theory Ex5_1 \n  imports Main \nbegin \n  \nprimrec insort :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list \" where \n  \"insort val [] = [val]\"|\n  \"insort val (x#xs) = (if val \\<le> x then val#x#xs else x # insort val xs)\"\n  \nprimrec le :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where \n  \"le _ [] =  True\"|\n  \"le val (x#xs) = ((val \\<le> x)  \\<and>   le val xs)\"\n\nprimrec sorted :: \"nat list \\<Rightarrow> bool\" where \n\"sorted [] = True\"|\n\"sorted (x#xs) = (le  x xs \\<and> sorted xs)\"\n\nprimrec sort :: \"nat list \\<Rightarrow> nat list\" where \n  \"sort [] = [] \"|\n  \"sort (x#xs) = insort x (sort xs)\"\n\n\n\nlemma lem1 [simp]: \"x \\<le> y \\<Longrightarrow> le y xs \\<longrightarrow> le x xs\" \nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (cases \"y \\<le> a\"; simp)\nqed\n\nlemma helper:\"le x xs \\<Longrightarrow> insort x xs = x # xs\" by (induction xs ; simp)\n\nlemma helper2: \"le a xs \\<Longrightarrow> a \\<le> x \\<Longrightarrow> le a (insort x xs)\"\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons aa xs)\n  then show ?case by (cases \"a \\<le> aa\" ; simp)\nqed\n\nlemma helper3:\"\\<not> le a xs \\<Longrightarrow> le  a (insort x xs) = False\" by (induction xs; simp)\n\n\nlemma helper4:\"sorted (insort x xs) = sorted xs\"\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume hyp:\"sorted (Ex5_1.insort x xs) = sorted xs\"\n  then show ?case \n  proof (cases \"x \\<le> a\")\n    case True\n    then show ?thesis by (cases \"le a xs\"; simp)\n  next\n    case False\n    assume c1:\"\\<not> x \\<le> a\"\n    hence tmp:\"x > a\" by simp\n    then show ?thesis \n    proof (cases \"le x xs\")\n      case True\n      assume c2:\"le x xs\"\n      have tmp2:\"a \\<le> x\" using tmp by simp\n      have \"sorted (Ex5_1.insort x (a # xs)) = sorted (a # Ex5_1.insort x  xs)\" using c1 by simp\n      also have \"\\<dots> = sorted (a # x # xs)\" using helper c2 by simp\n      also have \"\\<dots> = (le a (x#xs)  \\<and> sorted (x # xs))\" by simp\n      also have \"\\<dots> = ((a \\<le> x \\<and> le a xs) \\<and> sorted (x #xs))\" by simp\n      also have \"\\<dots> = (le a xs \\<and> sorted (x#xs))\" using c1 by simp\n      also have \"\\<dots> = sorted xs\" using c2 tmp2 by simp\n      finally have a:\"sorted (Ex5_1.insort x (a # xs)) = sorted xs\" by assumption\n\n      have  \"Ex5_1.sorted (a # xs) = (le a xs \\<and> sorted xs)\" by simp\n      also have \"\\<dots> = sorted xs\" using tmp2 c2 by simp\n      \n      finally show ?thesis using a by simp\n    next\n      case False\n      assume c2:\"\\<not> le x xs\"\n      show ?thesis  \n      proof  (cases \"le a xs\")\n        case True\n        then show ?thesis using c1 hyp helper2 by simp\n      next\n        case False\n        assume c3:\"\\<not>le a xs\"\n        have f1:\"sorted (a # xs)  =  (le a xs \\<and> sorted xs)\" by simp\n        also have \"\\<dots> = (False \\<and> sorted xs)\" using c3 by simp\n        also have \"\\<dots> = False\" by simp\n        finally have res1:\"sorted (a # xs) = False\" by assumption\n\n        have \"sorted (insort x (a # xs)) = sorted (a # insort x xs)\" using c1 by simp\n        also have \"\\<dots> =False\" using c3 helper3 by simp\n        finally show ?thesis using res1 by simp\n      qed\n    qed\n  qed\nqed\n\n\n\ntheorem \"sorted (sort xs)\" \nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume \"sorted (sort xs)\"\n  have \"sorted (sort (a#xs)) = sorted (insort a (sort xs))\" by simp\n  then show ?case using helper4 Cons.IH by simp\nqed\n\nprimrec count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where \n  \"count [] _ = 0\"|\n  \"count (x#xs) val = (if val = x then 1 else 0) + count xs val\"\n\nlemma helper5: \"count (insort x xs) y= count (x# xs) y\" by (induction xs ; auto)\n\ntheorem \"count (sort xs) x = count xs x\" by (induction xs ; auto simp add : helper5)\n\n\ndatatype bintree = leaf | node nat (l:\"bintree\") (r:\"bintree\")\n\nprimrec tge :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bool\" where \n\"tge _ leaf = True\"|\n\"tge val (node val2 lft rgt) = (val \\<ge> val2 \\<and> tge val lft \\<and> tge val rgt)\"\n\nprimrec tle :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bool\" where \n\"tle _ leaf = True\"|\n\"tle val (node val2 lft rgt) = (val \\<le> val2 \\<and> tle val lft \\<and> tle val rgt)\"\n\nprimrec tsorted :: \"bintree \\<Rightarrow> bool\" where \n\"tsorted leaf = True\"|\n\"tsorted (node val lft rgt) =  (tsorted lft \\<and> tsorted rgt \\<and> tge val lft \\<and>  tle val rgt)\"\n\nprimrec ins :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bintree\" where \n\"ins val leaf = node val leaf leaf\"|\n\"ins val (node val2 lft rgt) = (if val < val2 then node val2 (ins val lft ) rgt else node val2 lft (ins val rgt))\"\n\nprimrec tree_of :: \"nat list \\<Rightarrow> bintree\" where \n\"tree_of [] = leaf\"|\n\"tree_of (x#xs) = ins x (tree_of xs)\"\n\nlemma helper6:\"x < y \\<Longrightarrow> tge y t \\<Longrightarrow> tge y (ins x t)\" by (induction t ; simp)\n\nlemma helper7:\"x \\<ge> y \\<Longrightarrow> tle y t \\<Longrightarrow> tle y (ins x t)\" by (induction t; simp)\n\nlemma helper8:\"\\<not>tge x t \\<Longrightarrow>  \\<not>tge x (ins y t)\" by (induction t ; auto)\n\nlemma helper9:\"\\<not>tle x t \\<Longrightarrow> \\<not>tle x (ins y t)\" by (induction t; auto)\n\nlemma helper10: \"tsorted (ins x t) = tsorted t\" \nproof (induction t)\n  case leaf\n  then show ?case by simp\nnext\n  case (node x1 t1 t2)\n  assume hyp1:\"tsorted (ins x t1) = tsorted t1\"\n     and hyp2:\"tsorted (ins x t2) = tsorted t2\"\n  show ?case  \n  proof (cases \"x < x1\")\n    case True\n    assume c1:\"x < x1\"\n    have tmp:\"tsorted (ins x (node x1 t1 t2)) = tsorted  (node x1 (ins x t1) t2)\" by (simp add : True)\n    show ?thesis \n    proof (cases \"tge x1 t1\")\n      case True\n      then show ?thesis using hyp1 helper6[of x x1 t1] c1 by (cases \"tle x1 t1\" ; simp) \n    next\n      case False\n      then show ?thesis using helper8[of x1 t1 x] c1 by (cases \"tle x1 t2\" ; simp)\n    qed\n  next\n    case False\n    assume \"\\<not> x < x1\"\n    hence c1:\"x1 \\<le> x\" by simp\n    then show ?thesis using helper7[of x1 x t2] helper9[of x1 t2 x] hyp2 by (cases \"tge x1 t1\" ; cases \"tle x1 t2\" ; auto) \n  qed\nqed\n\ntheorem [simp] : \"tsorted (tree_of xs)\" \nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case using helper10 by simp\nqed\n\nprimrec tcount :: \"bintree \\<Rightarrow> nat  \\<Rightarrow> nat\" where \n\"tcount leaf _  = 0\"|\n\"tcount (node val2 lft rgt) val = (if val = val2 then 1 else 0) + tcount lft val + tcount rgt val\"\n\nlemma helper11: \"tcount (ins x t) y = (if y = x then 1 else 0) + tcount t y\" by (induction t ; auto)\n\ntheorem \"tcount (tree_of xs) x = count xs x\" using helper11 by (induction xs ; simp)\n\nprimrec list_of :: \"bintree \\<Rightarrow> nat list\" where \n\"list_of leaf = []\"|\n\"list_of (node val lft rgt) = list_of lft @ val # list_of rgt\"\n\nprimrec ge :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"ge _ [] = True\"|\n\"ge val (x#xs) = (val \\<ge> x  \\<and> ge val xs)\"\n\n\n\nlemma lem3:\"ge x (xs @ ys) = (ge x xs \\<and> ge x ys)\" by (induction xs ; simp)\n\nlemma helper12 : \"sorted (a @ x # b) = (sorted a \\<and> sorted b \\<and> ge x a \\<and> le x b)\" \nproof (induction a)\n  case Nil\n  then show ?case by (cases \"le x b\" ; simp)\nnext\n  case (Cons a1 a2)\n  assume hyp:\"sorted (a2 @ x # b) = (sorted a2 \\<and> sorted b \\<and> ge x a2 \\<and> le x b)\"\n\n  from hyp show ?case by (cases \"sorted (a1 # a2) \"; cases \"sorted b\" ; cases \" ge x (a1 # a2)\" ; cases \"le x b\" ; auto simp add : lem2)\nqed\n\nlemma lem4:\"x < y \\<Longrightarrow> ge y (list_of (ins x t)) = ge y (list_of t)\" by (induction t ; simp add : lem3)\n\nlemma lem5:\"y \\<le> x \\<Longrightarrow> le y (list_of (ins x t)) = le y (list_of t)\" by (induction t;  simp add : lem2)\n\nlemma lem6:\"sorted (list_of (ins x t)) = sorted (list_of t)\" \nproof (induction t)\n  case leaf\n  then show ?case by simp\nnext\n  case (node x1 t1 t2)\n  assume hyp1:\"sorted (list_of (ins x t1)) = sorted (list_of t1)\"\n     and hyp2:\"sorted (list_of (ins x t2)) = sorted (list_of t2)\"\n  show ?case \n  proof (cases \"x < x1\")\n    case True\n    then show ?thesis by (simp add : hyp1 lem4[of x x1 t1] helper12)\n  next\n    case False\n    then show ?thesis by (simp add : hyp2 lem5 helper12)\n  qed\nqed\n\n\ntheorem \"sorted (list_of (tree_of xs))\" using lem6 by (induction xs ; simp)\n\nlemma lem7:\"count (xs @ ys) x = count xs x + count ys x\" by (induction xs ; simp)\n\nlemma lem8:\"count (list_of (ins x t)) = count (x # list_of t)\"  by (induction t ; auto simp add : lem7)\n\ntheorem \"count (list_of (tree_of xs)) n = count xs n\" by (induction xs ; simp add : lem8)", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/5. Advanced/Ex5_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542184, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7900697546502239}}
{"text": "theory P13 imports Main begin\n\nfun list_union :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"list_union Nil xs = xs\" | \n\"list_union (y # ys) xs = \n(if (y \\<in> (set xs)) \n  then (list_union ys xs) \n  else (y # list_union ys xs))\"\n\n\n\nlemma [simp]: \"a \\<notin> set xs \\<Longrightarrow> a \\<notin> set ys \\<Longrightarrow> a \\<notin> set (list_union xs ys)\"\n  by simp\n\nlemma [rule_format]:\n\"distinct xs \\<longrightarrow>  distinct ys \\<longrightarrow> (distinct (list_union xs ys))\"\nproof (induct xs)\ncase Nil\n  then show ?case by simp\nnext\n  case (Cons a xs) \n  have 1:\"distinct (a # xs) \\<Longrightarrow> a \\<notin> (set xs)\" by simp\n  have 2: \"distinct (a # xs) \\<Longrightarrow> distinct xs\" by simp\n  then show ?case\n  proof (cases \"a \\<in> set ys\")\n  case True\n    then show ?thesis\n      using Cons.hyps by auto\n  next\n    case False\n    hence \"list_union (a # xs) ys = a # list_union xs ys\" by simp \n    then show ?thesis using Cons.hyps False 1 by auto\n  qed\nqed\n\nlemma \"((\\<forall> x \\<in> A. P x) \\<and> (\\<forall> x \\<in> B. P x)) \\<longrightarrow> (\\<forall> x \\<in> (A \\<union> B). P x)\"\n  by auto\n\nlemma \"\\<forall> x \\<in> A. Q (f x) \\<Longrightarrow> \\<forall> y \\<in> f ` A. Q y\"\n  by auto\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P13.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7900656563341102}}
{"text": "(*  Title:      CoW/Arithmetical_Hints.thy\n    Author:     Štěpán Holub, Charles University\n    Author:     Martin Raška, Charles University\n    Author:     Štěpán Starosta, CTU in Prague\n\nPart of Combinatorics on Words Formalized. See https://gitlab.com/formalcow/combinatorics-on-words-formalized/\n*)\n\ntheory Arithmetical_Hints\n  imports Main\nbegin\n\nsection \"Arithmetical hints\"\n\ntext\\<open>In this section we give some specific auxiliary lemmas on natural numbers.\\<close>\n\nlemma zero_diff_eq: \"i \\<le> j \\<Longrightarrow> (0::nat) = j - i  \\<Longrightarrow> j = i\"\n  by simp\n\nlemma zero_less_diff': \"i < j \\<Longrightarrow> j - i \\<noteq> (0::nat)\" \n   by simp\n\nlemma nat_prod_le: \"m \\<noteq> (0 :: nat) \\<Longrightarrow> m*n \\<le> k \\<Longrightarrow> n \\<le> k\"\n  using le_trans[of n \"m*n\" k] by auto\n\nlemma get_div: \"(p :: nat) < a \\<Longrightarrow> m = (m * a + p) div a\"\n  by simp\n\nlemma get_mod: \"(p :: nat) < a \\<Longrightarrow> p = (m * a + p) mod a\"\n  by simp\n\nlemma plus_one_between:  \"(a :: nat) < b \\<Longrightarrow> \\<not> b < a + 1\"\n  by auto\n\nlemma quotient_smaller: \"k \\<noteq> (0 :: nat) \\<Longrightarrow>  b \\<le> k * b\" \n  by simp\n\nlemma mult_cancel_le: \"b \\<noteq> 0 \\<Longrightarrow> a*b \\<le> c*b \\<Longrightarrow> a \\<le> (c::nat)\" \n  by simp\n\nlemma add_lessD2: \"k + m < (n::nat) \\<Longrightarrow> m < n\"\nunfolding add.commute[of k] using add_lessD1.\n\nlemma mod_offset:  assumes \"M \\<noteq> (0 :: nat)\"\n  obtains k where \"n mod M = (l + k) mod M\"\nproof-\n  have \"(l + (M - l mod M)) mod M = 0\"\n    using mod_add_left_eq[of l M \"(M - l mod M)\", unfolded le_add_diff_inverse[OF mod_le_divisor[OF assms[unfolded neq0_conv]], of l] mod_self, symmetric].\n  from mod_add_left_eq[of \"(l + (M - l mod M))\" M n, symmetric, unfolded this add.commute[of 0] add.comm_neutral]\n  have \"((l + (M - l mod M)) + n) mod M = n mod M\".\n  from that[OF this[unfolded add.assoc, symmetric]]\n  show thesis.\nqed\n\nlemma assumes \"q \\<noteq> (0::nat)\" shows \"p \\<le> p + q - gcd p q\"\n  using gcd_le2_nat[OF \\<open>q \\<noteq> 0\\<close>, of p]\n  by linarith\n\nlemma less_mult_one: assumes \"(m-1)*k < k\" obtains \"m = 0\" | \"m = (1::nat)\"\n  using assms by fastforce\n\nlemma per_lemma_len_le: assumes le: \"p + q - gcd p q \\<le> (n :: nat)\" and \"q \\<noteq> 0\" shows \"p \\<le> n\"\n  using le unfolding add_diff_assoc[OF gcd_le2_nat[OF \\<open>q \\<noteq> 0\\<close>], symmetric] by (rule add_leD1)\n\nlemma predE: assumes \"k \\<noteq> 0\" obtains pred where \"k = Suc pred\"\n  using assms not0_implies_Suc by auto\n\nlemma Suc_less_iff_Suc_le: \"Suc n < k \\<longleftrightarrow> Suc n \\<le> k - 1\"\n   by auto\n\nlemma nat_induct_pair: \"P 0 0 \\<Longrightarrow> (\\<And> m n. P m n \\<Longrightarrow> P m (Suc n)) \\<Longrightarrow> (\\<And> m n. P m n \\<Longrightarrow> P (Suc m) n) \\<Longrightarrow> P m n\"\n  by (induction m arbitrary: n) (metis nat_induct, simp)\n\nlemma One_less_Two_le_iff: \"1 < k \\<longleftrightarrow> 2 \\<le> (k :: nat)\"\n  by fastforce \n\nlemma at_least2_Suc: assumes \"2 \\<le> k\"\n  obtains k' where \"k = Suc(Suc k')\"\n  using Suc3_eq_add_3  less_eqE[OF assms] by auto\n\nlemma at_least3_Suc: assumes \"3 \\<le> k\"\n  obtains k' where \"k = Suc(Suc(Suc k'))\"\n  using Suc3_eq_add_3  less_eqE[OF assms] by auto\n\nlemma two_three_add_le_mult: assumes \"2 \\<le> (l::nat)\" and  \"3 \\<le> k\" shows \"l + k + 1 \\<le> l*k\" \nproof-\n  obtain l' where l: \"l = Suc (Suc l')\"\n     using  \\<open>2 \\<le> l\\<close> at_least2_Suc[OF \\<open>2 \\<le> l\\<close>] by blast\n  obtain k' where k: \"k = Suc (Suc (Suc k'))\"\n    using  \\<open>3 \\<le> k\\<close> at_least3_Suc[OF \\<open>3 \\<le> k\\<close>] by blast\n  show \"l + k + 1 \\<le> l*k\"\n    unfolding l k\n  by (induct l' k' rule: nat_induct_pair, simp, simp add: add.commute[of \"Suc (Suc l')\"] mult.commute[of \"Suc (Suc l')\"], simp_all)\nqed\n\nlemmas not0_SucE = not0_implies_Suc[THEN exE] \n\nlemma le1_SucE: assumes \"1 \\<le> n\"\n  obtains k where \"n = Suc k\" using Suc_le_D[OF assms[unfolded One_nat_def]] by blast   \n\nlemma Suc_minus:  \"k \\<noteq> 0 \\<Longrightarrow> Suc (k - 1) = k\"\n   by simp \n\nlemma Suc_minus': \"1 \\<le> k \\<Longrightarrow> Suc(k - 1) = k\"\n  by simp\n\nlemmas Suc_minus'' = Suc_diff_1\n\nlemma Suc_minus2: \"2 \\<le> k \\<Longrightarrow> Suc (Suc(k - 2)) = k\"\n  by auto\n\nlemma almost_equal_equal: assumes \"(a:: nat) \\<noteq> 0\" and \"b \\<noteq> 0\" and eq: \"k*(a+b) + a = m*(a+b) + b\" \n  shows \"k = m\" and \"a = b\" \nproof- \n  show \"k = m\"\n  proof (rule linorder_cases[of k m])\n    assume \"k < m\" \n    from add_le_mono1[OF mult_le_mono1[OF Suc_leI[OF this]]]\n    have \"(Suc k)*(a + b) + b \\<le> m*(a+b) + b\".\n    hence False \n      using  \\<open>b \\<noteq> 0\\<close> unfolding mult_Suc eq[symmetric] by force\n    thus ?thesis by blast\n  next\n    assume \"m < k\" \n    from add_le_mono1[OF mult_le_mono1[OF Suc_leI[OF this]]]\n    have \"(Suc m)*(a + b) + a \\<le> k*(a+b) + a\".\n    hence False \n      using  \\<open>a \\<noteq> 0\\<close> unfolding mult_Suc eq by force\n    thus ?thesis by blast\n  qed (simp) \n  thus \"a = b\"\n    using eq by auto\nqed\n\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Combinatorics_Words/Arithmetical_Hints.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.789917810132392}}
{"text": "(*  Title:      ZF/ex/Primes.thy\n    Author:     Christophe Tabacznyj and Lawrence C Paulson\n    Copyright   1996  University of Cambridge\n*)\n\nsection{*The Divides Relation and Euclid's algorithm for the GCD*}\n\ntheory Primes imports Main begin\n\ndefinition\n  divides :: \"[i,i]=>o\"              (infixl \"dvd\" 50)  where\n    \"m dvd n == m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\n\ndefinition\n  is_gcd  :: \"[i,i,i]=>o\"     --{*definition of great common divisor*}  where\n    \"is_gcd(p,m,n) == ((p dvd m) & (p dvd n))   &\n                       (\\<forall>d\\<in>nat. (d dvd m) & (d dvd n) \\<longrightarrow> d dvd p)\"\n\ndefinition\n  gcd     :: \"[i,i]=>i\"       --{*Euclid's algorithm for the gcd*}  where\n    \"gcd(m,n) == transrec(natify(n),\n                        %n f. \\<lambda>m \\<in> nat.\n                                if n=0 then m else f`(m mod n)`n) ` natify(m)\"\n\ndefinition\n  coprime :: \"[i,i]=>o\"       --{*the coprime relation*}  where\n    \"coprime(m,n) == gcd(m,n) = 1\"\n  \ndefinition\n  prime   :: i                --{*the set of prime numbers*}  where\n   \"prime == {p \\<in> nat. 1<p & (\\<forall>m \\<in> nat. m dvd p \\<longrightarrow> m=1 | m=p)}\"\n\n\nsubsection{*The Divides Relation*}\n\nlemma dvdD: \"m dvd n ==> m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\nby (unfold divides_def, assumption)\n\nlemma dvdE:\n     \"[|m dvd n;  !!k. [|m \\<in> nat; n \\<in> nat; k \\<in> nat; n = m#*k|] ==> P|] ==> P\"\nby (blast dest!: dvdD)\n\nlemmas dvd_imp_nat1 = dvdD [THEN conjunct1]\nlemmas dvd_imp_nat2 = dvdD [THEN conjunct2, THEN conjunct1]\n\n\nlemma dvd_0_right [simp]: \"m \\<in> nat ==> m dvd 0\"\napply (simp add: divides_def)\napply (fast intro: nat_0I mult_0_right [symmetric])\ndone\n\nlemma dvd_0_left: \"0 dvd m ==> m = 0\"\nby (simp add: divides_def)\n\nlemma dvd_refl [simp]: \"m \\<in> nat ==> m dvd m\"\napply (simp add: divides_def)\napply (fast intro: nat_1I mult_1_right [symmetric])\ndone\n\nlemma dvd_trans: \"[| m dvd n; n dvd p |] ==> m dvd p\"\nby (auto simp add: divides_def intro: mult_assoc mult_type)\n\nlemma dvd_anti_sym: \"[| m dvd n; n dvd m |] ==> m=n\"\napply (simp add: divides_def)\napply (force dest: mult_eq_self_implies_10\n             simp add: mult_assoc mult_eq_1_iff)\ndone\n\nlemma dvd_mult_left: \"[|(i#*j) dvd k; i \\<in> nat|] ==> i dvd k\"\nby (auto simp add: divides_def mult_assoc)\n\nlemma dvd_mult_right: \"[|(i#*j) dvd k; j \\<in> nat|] ==> j dvd k\"\napply (simp add: divides_def, clarify)\napply (rule_tac x = \"i#*ka\" in bexI)\napply (simp add: mult_ac)\napply (rule mult_type)\ndone\n\n\nsubsection{*Euclid's Algorithm for the GCD*}\n\nlemma gcd_0 [simp]: \"gcd(m,0) = natify(m)\"\napply (simp add: gcd_def)\napply (subst transrec, simp)\ndone\n\nlemma gcd_natify1 [simp]: \"gcd(natify(m),n) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_natify2 [simp]: \"gcd(m, natify(n)) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_non_0_raw: \n    \"[| 0<n;  n \\<in> nat |] ==> gcd(m,n) = gcd(n, m mod n)\"\napply (simp add: gcd_def)\napply (rule_tac P = \"%z. ?left (z) = ?right\" in transrec [THEN ssubst])\napply (simp add: ltD [THEN mem_imp_not_eq, THEN not_sym] \n                 mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_non_0: \"0 < natify(n) ==> gcd(m,n) = gcd(n, m mod n)\"\napply (cut_tac m = m and n = \"natify (n) \" in gcd_non_0_raw)\napply auto\ndone\n\nlemma gcd_1 [simp]: \"gcd(m,1) = 1\"\nby (simp (no_asm_simp) add: gcd_non_0)\n\nlemma dvd_add: \"[| k dvd a; k dvd b |] ==> k dvd (a #+ b)\"\napply (simp add: divides_def)\napply (fast intro: add_mult_distrib_left [symmetric] add_type)\ndone\n\nlemma dvd_mult: \"k dvd n ==> k dvd (m #* n)\"\napply (simp add: divides_def)\napply (fast intro: mult_left_commute mult_type)\ndone\n\nlemma dvd_mult2: \"k dvd m ==> k dvd (m #* n)\"\napply (subst mult_commute)\napply (blast intro: dvd_mult)\ndone\n\n(* k dvd (m*k) *)\nlemmas dvdI1 [simp] = dvd_refl [THEN dvd_mult]\nlemmas dvdI2 [simp] = dvd_refl [THEN dvd_mult2]\n\nlemma dvd_mod_imp_dvd_raw:\n     \"[| a \\<in> nat; b \\<in> nat; k dvd b; k dvd (a mod b) |] ==> k dvd a\"\napply (case_tac \"b=0\") \n apply (simp add: DIVISION_BY_ZERO_MOD)\napply (blast intro: mod_div_equality [THEN subst]\n             elim: dvdE \n             intro!: dvd_add dvd_mult mult_type mod_type div_type)\ndone\n\nlemma dvd_mod_imp_dvd: \"[| k dvd (a mod b); k dvd b; a \\<in> nat |] ==> k dvd a\"\napply (cut_tac b = \"natify (b)\" in dvd_mod_imp_dvd_raw)\napply auto\napply (simp add: divides_def)\ndone\n\n(*Imitating TFL*)\nlemma gcd_induct_lemma [rule_format (no_asm)]: \"[| n \\<in> nat;  \n         \\<forall>m \\<in> nat. P(m,0);  \n         \\<forall>m \\<in> nat. \\<forall>n \\<in> nat. 0<n \\<longrightarrow> P(n, m mod n) \\<longrightarrow> P(m,n) |]  \n      ==> \\<forall>m \\<in> nat. P (m,n)\"\napply (erule_tac i = n in complete_induct)\napply (case_tac \"x=0\")\napply (simp (no_asm_simp))\napply clarify\napply (drule_tac x1 = m and x = x in bspec [THEN bspec])\napply (simp_all add: Ord_0_lt_iff)\napply (blast intro: mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_induct: \"!!P. [| m \\<in> nat; n \\<in> nat;  \n         !!m. m \\<in> nat ==> P(m,0);  \n         !!m n. [|m \\<in> nat; n \\<in> nat; 0<n; P(n, m mod n)|] ==> P(m,n) |]  \n      ==> P (m,n)\"\nby (blast intro: gcd_induct_lemma)\n\n\nsubsection{*Basic Properties of @{term gcd}*}\n\ntext{*type of gcd*}\nlemma gcd_type [simp,TC]: \"gcd(m, n) \\<in> nat\"\napply (subgoal_tac \"gcd (natify (m), natify (n)) \\<in> nat\")\napply simp\napply (rule_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_induct)\napply auto\napply (simp add: gcd_non_0)\ndone\n\n\ntext{* Property 1: gcd(a,b) divides a and b *}\n\nlemma gcd_dvd_both:\n     \"[| m \\<in> nat; n \\<in> nat |] ==> gcd (m, n) dvd m & gcd (m, n) dvd n\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0)\napply (blast intro: dvd_mod_imp_dvd_raw nat_into_Ord [THEN Ord_0_lt])\ndone\n\nlemma gcd_dvd1 [simp]: \"m \\<in> nat ==> gcd(m,n) dvd m\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\nlemma gcd_dvd2 [simp]: \"n \\<in> nat ==> gcd(m,n) dvd n\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\ntext{* if f divides a and b then f divides gcd(a,b) *}\n\nlemma dvd_mod: \"[| f dvd a; f dvd b |] ==> f dvd (a mod b)\"\napply (simp add: divides_def)\napply (case_tac \"b=0\")\n apply (simp add: DIVISION_BY_ZERO_MOD, auto)\napply (blast intro: mod_mult_distrib2 [symmetric])\ndone\n\ntext{* Property 2: for all a,b,f naturals, \n               if f divides a and f divides b then f divides gcd(a,b)*}\n\nlemma gcd_greatest_raw [rule_format]:\n     \"[| m \\<in> nat; n \\<in> nat; f \\<in> nat |]    \n      ==> (f dvd m) \\<longrightarrow> (f dvd n) \\<longrightarrow> f dvd gcd(m,n)\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0 dvd_mod)\ndone\n\nlemma gcd_greatest: \"[| f dvd m;  f dvd n;  f \\<in> nat |] ==> f dvd gcd(m,n)\"\napply (rule gcd_greatest_raw)\napply (auto simp add: divides_def)\ndone\n\nlemma gcd_greatest_iff [simp]: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> (k dvd gcd (m, n)) \\<longleftrightarrow> (k dvd m & k dvd n)\"\nby (blast intro!: gcd_greatest gcd_dvd1 gcd_dvd2 intro: dvd_trans)\n\n\nsubsection{*The Greatest Common Divisor*}\n\ntext{*The GCD exists and function gcd computes it.*}\n\nlemma is_gcd: \"[| m \\<in> nat; n \\<in> nat |] ==> is_gcd(gcd(m,n), m, n)\"\nby (simp add: is_gcd_def)\n\ntext{*The GCD is unique*}\n\nlemma is_gcd_unique: \"[|is_gcd(m,a,b); is_gcd(n,a,b); m\\<in>nat; n\\<in>nat|] ==> m=n\"\napply (simp add: is_gcd_def)\napply (blast intro: dvd_anti_sym)\ndone\n\nlemma is_gcd_commute: \"is_gcd(k,m,n) \\<longleftrightarrow> is_gcd(k,n,m)\"\nby (simp add: is_gcd_def, blast)\n\nlemma gcd_commute_raw: \"[| m \\<in> nat; n \\<in> nat |] ==> gcd(m,n) = gcd(n,m)\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (rule_tac [3] is_gcd_commute [THEN iffD1])\napply (rule_tac [3] is_gcd, auto)\ndone\n\nlemma gcd_commute: \"gcd(m,n) = gcd(n,m)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_commute_raw)\napply auto\ndone\n\nlemma gcd_assoc_raw: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (simp_all add: is_gcd_def)\napply (blast intro: gcd_dvd1 gcd_dvd2 gcd_type intro: dvd_trans)\ndone\n\nlemma gcd_assoc: \"gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_assoc_raw)\napply auto\ndone\n\nlemma gcd_0_left [simp]: \"gcd (0, m) = natify(m)\"\nby (simp add: gcd_commute [of 0])\n\nlemma gcd_1_left [simp]: \"gcd (1, m) = 1\"\nby (simp add: gcd_commute [of 1])\n\n\nsubsection{*Addition laws*}\n\nlemma gcd_add1 [simp]: \"gcd (m #+ n, n) = gcd (m, n)\"\napply (subgoal_tac \"gcd (m #+ natify (n), natify (n)) = gcd (m, natify (n))\")\napply simp\napply (case_tac \"natify (n) = 0\")\napply (auto simp add: Ord_0_lt_iff gcd_non_0)\ndone\n\nlemma gcd_add2 [simp]: \"gcd (m, m #+ n) = gcd (m, n)\"\napply (rule gcd_commute [THEN trans])\napply (subst add_commute, simp)\napply (rule gcd_commute)\ndone\n\nlemma gcd_add2' [simp]: \"gcd (m, n #+ m) = gcd (m, n)\"\nby (subst add_commute, rule gcd_add2)\n\nlemma gcd_add_mult_raw: \"k \\<in> nat ==> gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (erule nat_induct)\napply (auto simp add: gcd_add2 add_assoc)\ndone\n\nlemma gcd_add_mult: \"gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (cut_tac k = \"natify (k)\" in gcd_add_mult_raw)\napply auto\ndone\n\n\nsubsection{* Multiplication Laws*}\n\nlemma gcd_mult_distrib2_raw:\n     \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (erule_tac m = m and n = n in gcd_induct, assumption)\napply simp\napply (case_tac \"k = 0\", simp)\napply (simp add: mod_geq gcd_non_0 mod_mult_distrib2 Ord_0_lt_iff)\ndone\n\nlemma gcd_mult_distrib2: \"k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_mult_distrib2_raw)\napply auto\ndone\n\nlemma gcd_mult [simp]: \"gcd (k, k #* n) = natify(k)\"\nby (cut_tac k = k and m = 1 and n = n in gcd_mult_distrib2, auto)\n\nlemma gcd_self [simp]: \"gcd (k, k) = natify(k)\"\nby (cut_tac k = k and n = 1 in gcd_mult, auto)\n\nlemma relprime_dvd_mult:\n     \"[| gcd (k,n) = 1;  k dvd (m #* n);  m \\<in> nat |] ==> k dvd m\"\napply (cut_tac k = m and m = k and n = n in gcd_mult_distrib2, auto)\napply (erule_tac b = m in ssubst)\napply (simp add: dvd_imp_nat1)\ndone\n\nlemma relprime_dvd_mult_iff:\n     \"[| gcd (k,n) = 1;  m \\<in> nat |] ==> k dvd (m #* n) \\<longleftrightarrow> k dvd m\"\nby (blast intro: dvdI2 relprime_dvd_mult dvd_trans)\n\nlemma prime_imp_relprime: \n     \"[| p \\<in> prime;  ~ (p dvd n);  n \\<in> nat |] ==> gcd (p, n) = 1\"\napply (simp add: prime_def, clarify)\napply (drule_tac x = \"gcd (p,n)\" in bspec)\napply auto\napply (cut_tac m = p and n = n in gcd_dvd2, auto)\ndone\n\nlemma prime_into_nat: \"p \\<in> prime ==> p \\<in> nat\"\nby (simp add: prime_def)\n\nlemma prime_nonzero: \"p \\<in> prime \\<Longrightarrow> p\\<noteq>0\"\nby (auto simp add: prime_def)\n\n\ntext{*This theorem leads immediately to a proof of the uniqueness of\n  factorization.  If @{term p} divides a product of primes then it is\n  one of those primes.*}\n\nlemma prime_dvd_mult:\n     \"[|p dvd m #* n; p \\<in> prime; m \\<in> nat; n \\<in> nat |] ==> p dvd m \\<or> p dvd n\"\nby (blast intro: relprime_dvd_mult prime_imp_relprime prime_into_nat)\n\n\nlemma gcd_mult_cancel_raw:\n     \"[|gcd (k,n) = 1; m \\<in> nat; n \\<in> nat|] ==> gcd (k #* m, n) = gcd (m, n)\"\napply (rule dvd_anti_sym)\n apply (rule gcd_greatest)\n  apply (rule relprime_dvd_mult [of _ k])\napply (simp add: gcd_assoc)\napply (simp add: gcd_commute)\napply (simp_all add: mult_commute)\napply (blast intro: dvdI1 gcd_dvd1 dvd_trans)\ndone\n\nlemma gcd_mult_cancel: \"gcd (k,n) = 1 ==> gcd (k #* m, n) = gcd (m, n)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_mult_cancel_raw)\napply auto\ndone\n\n\nsubsection{*The Square Root of a Prime is Irrational: Key Lemma*}\n\nlemma prime_dvd_other_side:\n     \"\\<lbrakk>n#*n = p#*(k#*k); p \\<in> prime; n \\<in> nat\\<rbrakk> \\<Longrightarrow> p dvd n\"\napply (subgoal_tac \"p dvd n#*n\")\n apply (blast dest: prime_dvd_mult)\napply (rule_tac j = \"k#*k\" in dvd_mult_left)\n apply (auto simp add: prime_def)\ndone\n\nlemma reduction:\n     \"\\<lbrakk>k#*k = p#*(j#*j); p \\<in> prime; 0 < k; j \\<in> nat; k \\<in> nat\\<rbrakk>  \n      \\<Longrightarrow> k < p#*j & 0 < j\"\napply (rule ccontr)\napply (simp add: not_lt_iff_le prime_into_nat)\napply (erule disjE)\n apply (frule mult_le_mono, assumption+)\napply (simp add: mult_ac)\napply (auto dest!: natify_eqE \n            simp add: not_lt_iff_le prime_into_nat mult_le_cancel_le1)\napply (simp add: prime_def)\napply (blast dest: lt_trans1)\ndone\n\nlemma rearrange: \"j #* (p#*j) = k#*k \\<Longrightarrow> k#*k = p#*(j#*j)\"\nby (simp add: mult_ac)\n\nlemma prime_not_square:\n     \"\\<lbrakk>m \\<in> nat; p \\<in> prime\\<rbrakk> \\<Longrightarrow> \\<forall>k \\<in> nat. 0<k \\<longrightarrow> m#*m \\<noteq> p#*(k#*k)\"\napply (erule complete_induct, clarify)\napply (frule prime_dvd_other_side, assumption)\napply assumption\napply (erule dvdE)\napply (simp add: mult_assoc mult_cancel1 prime_nonzero prime_into_nat)\napply (blast dest: rearrange reduction ltD)\ndone\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/ZF/ex/Primes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7899035413046029}}
{"text": "theory Set_Mult\n  imports \"HOL-Algebra.Algebra\"\nbegin\n\nlemma (in group) set_mult_union:\n  \"A <#> (B \\<union> C) = (A <#> B) \\<union> (A <#> C)\"\n  unfolding set_mult_def by auto\n\nlemma (in group) card_set_mult_single_el_eq:\n  assumes \"J \\<subseteq> carrier G\" \"x \\<in> carrier G\"\n  shows \"card (l_coset G x J) = card J\" unfolding l_coset_def\nproof -\n  have \"card ((\\<otimes>) x ` J) = card J\" using inj_on_cmult[of x] card_image[of \"(\\<otimes>) x\" J] assms inj_on_subset[of \"(\\<otimes>) x\" \"carrier G\" J] by blast\n  moreover have \"(\\<Union>y\\<in>J. {x \\<otimes> y}) = (\\<otimes>) x ` J\" using image_def[of \"(\\<otimes>) x\" J] by blast\n  ultimately show \"card (\\<Union>h\\<in>J. {x \\<otimes> h}) = card J\" by presburger\nqed\n\nlemma (in group) set_mult_card_le:\n  assumes \"finite H\" \"H \\<subseteq> carrier G\" \"J \\<subseteq> carrier G\"\n  shows \"card (H <#> J) \\<le> card H * card J\"\n  using assms\nproof (induction \"card H\" arbitrary: H)\n  case 0\n  then have \"H = {}\" by force\n  then show ?case using set_mult_def[of G H J] by simp\nnext\n  case (Suc n)\n  then obtain a where a_def: \"a \\<in> H\" by fastforce\n  then have c_n:\"card (H - {a}) = n\" using Suc.hyps(2) Suc.prems(1) by force\n  then have \"card ((H - {a}) <#> J) \\<le> card (H - {a}) * card J\" using Suc by blast\n  moreover have \"card ({a} <#> J) = card J\"\n    using Suc(4, 5) a_def card_set_mult_single_el_eq[of J a] l_coset_eq_set_mult[of G a J] by auto\n  moreover have \"H <#> J = (H - {a} <#> J) \\<union> ({a} <#> J)\" using set_mult_def[of G _ J] a_def by auto\n  moreover have \"card (H - {a}) * card J + card J = Suc n * card J\" using c_n mult_Suc by presburger\n  ultimately show ?case using card_Un_le[of \"H - {a} <#> J\" \"{a} <#> J\"] c_n \\<open>Suc n = card H\\<close> by auto\nqed\n\nlemma (in group) set_mult_finite:\n  assumes \"finite H\" \"finite J\" \"H \\<subseteq> carrier G\" \"J \\<subseteq> carrier G\"\n  shows \"finite (H <#> J)\"\n  using assms set_mult_def[of G H J] by auto\n\nlemma (in group) set_mult_card_eq_impl_empty_inter:\n  \"\\<lbrakk>finite H; finite J; H \\<subseteq> carrier G; J \\<subseteq> carrier G; card (H <#> J) = card H * card J\\<rbrakk> \\<Longrightarrow> (\\<And>a b.\\<lbrakk>a \\<in> H; b \\<in> H; a \\<noteq> b\\<rbrakk> \\<Longrightarrow> ((\\<otimes>) a ` J) \\<inter> ((\\<otimes>) b ` J) = {}) \"\nproof (induction H rule: finite_induct)\n  case empty\n  then show ?case by fast\nnext\n  case step: (insert x H)\n  \n  from step.prems(2) have x_c: \"x \\<in> carrier G\" by simp\n  from step.prems(2) have H_c: \"H \\<subseteq> carrier G\" by simp\n  from card_set_mult_single_el_eq[of J x] have card_x: \"card ({x} <#> J) = card J\" using \\<open>J \\<subseteq> carrier G\\<close> x_c l_coset_eq_set_mult by metis\n  moreover have ins: \"(insert x H) <#> J = (H <#> J) \\<union> ({x} <#> J)\" using set_mult_def[of G _ J] by auto\n  ultimately have \"card (H <#> J) \\<ge> card H * card J\" using card_Un_le[of \"H <#> J\" \"{x} <#> J\"] \\<open>card (insert x H <#> J) = card (insert x H) * card J\\<close>\n    by (simp add: step.hyps(1) step.hyps(2))\n  then have card_eq:\"card (H <#> J) = card H * card J\" using set_mult_card_le[of H J] step.hyps(1) step.prems(1, 3) H_c by linarith\n  then have ih:\"(\\<And>a b.\\<lbrakk>a \\<in> H; b \\<in> H; a \\<noteq> b\\<rbrakk> \\<Longrightarrow> ((\\<otimes>) a ` J) \\<inter> ((\\<otimes>) b ` J) = {})\" using step.IH step.hyps(1) step.prems(1, 3) H_c by presburger\n\n  have \"card (insert x H) * card J = card H * card J + card J\" using \\<open>x \\<notin> H\\<close> using step.hyps(1) by simp\n  then have \"({x} <#> J) \\<inter> (H <#> J) = {}\" using card_eq card_x ins card_Un_Int[of \"H <#> J\" \"{x} <#> J\"] step.prems(3, 4) \\<open>finite H\\<close> \\<open>finite J\\<close> set_mult_finite H_c x_c by auto\n  then have \"\\<And>a. a \\<in> H \\<Longrightarrow> (\\<Union>y\\<in>J. {a \\<otimes> y}) \\<inter> (\\<Union>y\\<in>J. {x \\<otimes> y}) = {}\" using set_mult_def[of G _ J] by blast\n  then have \"\\<And>a b.\\<lbrakk>a \\<in> (insert x H); b \\<in> (insert x H); a \\<noteq> b\\<rbrakk> \\<Longrightarrow> ((\\<otimes>) a ` J) \\<inter> ((\\<otimes>) b ` J) = {}\" using \\<open>x \\<notin> H\\<close> ih by blast (* slow *)\n  then show ?case using step by algebra\nqed\n\nlemma (in group) set_mult_card_eq_impl_empty_inter':\n  \"\\<lbrakk>finite H; finite J; H \\<subseteq> carrier G; J \\<subseteq> carrier G; card (H <#> J) = card H * card J\\<rbrakk> \\<Longrightarrow> (\\<And>a b.\\<lbrakk>a \\<in> H; b \\<in> H; a \\<noteq> b\\<rbrakk> \\<Longrightarrow> (l_coset G a J) \\<inter> (l_coset G b J) = {})\"\n  unfolding l_coset_def\n  using set_mult_card_eq_impl_empty_inter image_def[of \"(\\<otimes>) _\" J] by blast\n\nlemma (in comm_group) set_mult_comm:\n  assumes \"H \\<subseteq> carrier G\" \"J \\<subseteq> carrier G\"\n  shows \"(H <#> J) = (J <#> H)\"\n  unfolding set_mult_def\nproof -\n  have 1:\"\\<And>a b. \\<lbrakk>a \\<in> carrier G; b \\<in> carrier G\\<rbrakk> \\<Longrightarrow> {a \\<otimes> b} = {b \\<otimes> a}\" using m_comm by simp\n  then have \"\\<And>a b.\\<lbrakk>a \\<in> H; b \\<in> J\\<rbrakk> \\<Longrightarrow> {a \\<otimes> b} = {b \\<otimes> a}\" using assms by auto\n  moreover have \"\\<And>a b.\\<lbrakk>b \\<in> H; a \\<in> J\\<rbrakk> \\<Longrightarrow> {a \\<otimes> b} = {b \\<otimes> a}\" using assms 1 by auto\n  ultimately show \"(\\<Union>h\\<in>H. \\<Union>k\\<in>J. {h \\<otimes> k}) = (\\<Union>k\\<in>J. \\<Union>h\\<in>H. {k \\<otimes> h})\"  by fast\nqed\n\nlemma (in group) one_imp_set_mult_inc:\n  assumes \"\\<one> \\<in> A\" \"A \\<subseteq> carrier G\" \"B \\<subseteq> carrier G\"\n  shows \"B \\<subseteq> (B <#> A)\"\nproof\n  fix x\n  assume \"x \\<in> B\"\n  thus \"x \\<in> (B <#> A)\" using assms unfolding set_mult_def by force\nqed\n\nlemma (in group) set_mult_subset_generate:\n  assumes \"A \\<subseteq> carrier G\" \"B \\<subseteq> carrier G\"\n  shows \"A <#> B \\<subseteq> generate G (A \\<union> B)\"\nproof\n  fix x\n  assume \"x \\<in> A <#> B\"\n  then obtain a b where ab: \"a \\<in> A\" \"b \\<in> B\" \"x = a \\<otimes> b\" unfolding set_mult_def by blast\n  then have \"a \\<in> generate G (A \\<union> B)\" \"b \\<in> generate G (A \\<union> B)\" using generate.incl[of _ \"A \\<union> B\" G] by simp+\n  thus \"x \\<in> generate G (A \\<union> B)\" using ab generate.eng by metis\nqed\n\nlemma (in comm_group) generate_subgroup_eq_set_mult:\n  assumes \"subgroup H G\" \"subgroup J G\"\n  shows \"generate G (H \\<union> J) = H <#> J\" (is \"?L = ?R\")\nproof\n  show \"?L \\<subseteq> ?R\"\n  proof\n    fix x\n    assume \"x \\<in> ?L\"\n    then show \"x \\<in> ?R\"\n    proof(induction rule: generate.induct)\n      case one\n      moreover have \"\\<one> \\<in> H\" using assms subgroup.one_closed by auto\n      moreover have \"\\<one> \\<in> J\" using assms subgroup.one_closed by auto\n      moreover have \"\\<one> \\<otimes> \\<one> = \\<one>\" using nat_pow_one[of 2] by simp\n      ultimately show ?case using assms set_mult_def[of G H J] by fastforce\n    next\n      case (incl x)\n      have H1:\"\\<one> \\<in> H\" using assms subgroup.one_closed by auto\n      have J1:\"\\<one> \\<in> J\" using assms subgroup.one_closed by auto\n      have lx:\"x \\<otimes> \\<one> = x\" using r_one[of x] incl subgroup.subset[of J G] subgroup.subset[of H G] assms by blast\n      have rx:\"\\<one> \\<otimes> x = x\" using l_one[of x] incl subgroup.subset[of J G] subgroup.subset[of H G] assms by blast\n      show ?case\n      proof (cases \"x \\<in> H\")\n        case True\n        then show ?thesis using set_mult_def[of G H J] J1 lx by fastforce\n      next\n        case False\n        then show ?thesis using set_mult_def[of G H J] H1 rx incl by fastforce\n      qed\n    next\n      case (inv h)\n      then have inv_in:\"(inv h) \\<in> H \\<union> J\" (is \"?iv \\<in> H \\<union> J\") using assms subgroup.m_inv_closed[of _ G h] by (cases \"h \\<in> H\"; blast)\n      have H1:\"\\<one> \\<in> H\" using assms subgroup.one_closed by auto\n      have J1:\"\\<one> \\<in> J\" using assms subgroup.one_closed by auto\n      have lx:\"?iv \\<otimes> \\<one> = ?iv\" using r_one[of \"?iv\"] subgroup.subset[of J G] subgroup.subset[of H G] inv_in assms by blast\n      have rx:\"\\<one> \\<otimes> ?iv = ?iv\" using l_one[of \"?iv\"] incl subgroup.subset[of J G] subgroup.subset[of H G] inv_in assms by blast\n      show ?case \n      proof (cases \"?iv \\<in> H\")\n        case True\n        then show ?thesis using set_mult_def[of G H J] J1 lx by fastforce\n      next\n        case False\n        then show ?thesis using set_mult_def[of G H J] H1 rx inv_in by fastforce\n      qed\n    next\n      case (eng h g)\n      from eng(3) have \"\\<exists>a \\<in> H. \\<exists>b \\<in> J. h = a \\<otimes> b\" using set_mult_def[of G H J] by blast\n      then obtain a b where aH: \"a \\<in> H\" and bJ: \"b \\<in> J\" and h_def: \"h = a \\<otimes> b\" by blast\n      have a_carr: \"a \\<in> carrier G\" by (metis subgroup.mem_carrier assms(1) aH)\n      have b_carr: \"b \\<in> carrier G\" by (metis subgroup.mem_carrier assms(2) bJ)\n      from eng(4) have \"\\<exists>c \\<in> H. \\<exists>d \\<in> J. g = c \\<otimes> d\" using set_mult_def[of G H J] by blast\n      then obtain c d where cH: \"c \\<in> H\" and dJ: \"d \\<in> J\" and g_def: \"g = c \\<otimes> d\" by blast\n      have c_carr: \"c \\<in> carrier G\" by (metis subgroup.mem_carrier assms(1) cH)\n      have d_carr: \"d \\<in> carrier G\" by (metis subgroup.mem_carrier assms(2) dJ)\n      then have \"h \\<otimes> g = (a \\<otimes> c) \\<otimes> (b \\<otimes> d)\" using a_carr b_carr c_carr d_carr g_def h_def m_assoc m_comm by force\n      moreover have \"a \\<otimes> c \\<in> H\" using assms(1) aH cH subgroup.m_closed[of H G a c] by blast\n      moreover have \"b \\<otimes> d \\<in> J\" using assms(2) bJ dJ subgroup.m_closed[of J G b d] by blast\n      ultimately show ?case using set_mult_def by fast\n    qed\n  qed\nnext\n  show \"?R \\<subseteq> ?L\" using set_mult_subset_generate[of H J] subgroup.subset assms by blast\nqed\n\nend", "meta": {"author": "jthomme1", "repo": "group-theory-isabelle", "sha": "ca78c5c929c1fb40e9828a686b83c84d8d295f0e", "save_path": "github-repos/isabelle/jthomme1-group-theory-isabelle", "path": "github-repos/isabelle/jthomme1-group-theory-isabelle/group-theory-isabelle-ca78c5c929c1fb40e9828a686b83c84d8d295f0e/Set_Mult.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312213841788, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7899035303948064}}
{"text": "(*  Title:      HOL/ex/Primrec.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n*)\n\nsection \\<open>Ackermann's Function and the Primitive Recursive Functions\\<close>\n\ntheory Primrec imports Main begin\n\ntext \\<open>\n  Proof adopted from\n\n  Nora Szasz, A Machine Checked Proof that Ackermann's Function is not\n  Primitive Recursive, In: Huet \\& Plotkin, eds., Logical Environments\n  (CUP, 1993), 317-338.\n\n  See also E. Mendelson, Introduction to Mathematical Logic.  (Van\n  Nostrand, 1964), page 250, exercise 11.\n  \\medskip\n\\<close>\n\n\nsubsection\\<open>Ackermann's Function\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n =  Suc n\"\n| \"ack (Suc m) 0 = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\n\ntext \\<open>PROPERTY A 4\\<close>\n\nlemma less_ack2 [iff]: \"j < ack i j\"\n  by (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc2 [iff]: \"ack i j < ack i (Suc j)\"\n  by (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5, monotonicity for \\<open><\\<close>\\<close>\n\nlemma ack_less_mono2: \"j < k \\<Longrightarrow> ack i j < ack i k\"\n  by (simp add: lift_Suc_mono_less)\n\n\ntext \\<open>PROPERTY A 5', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono2: \"j \\<le> k \\<Longrightarrow> ack i j \\<le> ack i k\"\n  by (simp add: ack_less_mono2 less_mono_imp_le_mono)\n\n\ntext \\<open>PROPERTY A 6\\<close>\n\nlemma ack2_le_ack1 [iff]: \"ack i (Suc j) \\<le> ack (Suc i) j\"\nproof (induct j)\n  case 0 show ?case by simp\nnext\n  case (Suc j) show ?case\n    by (metis Suc ack.simps(3) ack_le_mono2 le_trans less_ack2 less_eq_Suc_le) \nqed\n\n\ntext \\<open>PROPERTY A 7-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc1 [iff]: \"ack i j < ack (Suc i) j\"\n  by (blast intro: ack_less_mono2 less_le_trans)\n\n\ntext \\<open>PROPERTY A 4'? Extra lemma needed for \\<^term>\\<open>CONSTANT\\<close> case, constant functions\\<close>\n\nlemma less_ack1 [iff]: \"i < ack i j\"\nproof (induct i)\n  case 0\n  then show ?case \n    by simp\nnext\n  case (Suc i)\n  then show ?case\n    using less_trans_Suc by blast\nqed\n\n\ntext \\<open>PROPERTY A 8\\<close>\n\nlemma ack_1 [simp]: \"ack (Suc 0) j = j + 2\"\n  by (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 9.  The unary \\<open>1\\<close> and \\<open>2\\<close> in \\<^term>\\<open>ack\\<close> is essential for the rewriting.\\<close>\n\nlemma ack_2 [simp]: \"ack (Suc (Suc 0)) j = 2 * j + 3\"\n  by (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 7, monotonicity for \\<open><\\<close> [not clear why\n  @{thm [source] ack_1} is now needed first!]\\<close>\n\nlemma ack_less_mono1_aux: \"ack i k < ack (Suc (i +i')) k\"\nproof (induct i k rule: ack.induct)\n  case (1 n) show ?case\n    using less_le_trans by auto\nnext\n  case (2 m) thus ?case by simp\nnext\n  case (3 m n) thus ?case\n    using ack_less_mono2 less_trans by fastforce\nqed\n\nlemma ack_less_mono1: \"i < j \\<Longrightarrow> ack i k < ack j k\"\n  using ack_less_mono1_aux less_iff_Suc_add by auto\n\n\ntext \\<open>PROPERTY A 7', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono1: \"i \\<le> j \\<Longrightarrow> ack i k \\<le> ack j k\"\n  using ack_less_mono1 le_eq_less_or_eq by auto\n\n\ntext \\<open>PROPERTY A 10\\<close>\n\nlemma ack_nest_bound: \"ack i1 (ack i2 j) < ack (2 + (i1 + i2)) j\"\nproof -\n  have \"ack i1 (ack i2 j) < ack (i1 + i2) (ack (Suc (i1 + i2)) j)\"\n    by (meson ack_le_mono1 ack_less_mono1 ack_less_mono2 le_add1 le_trans less_add_Suc2 not_less)\n  also have \"... = ack (Suc (i1 + i2)) (Suc j)\"\n    by simp\n  also have \"... \\<le> ack (2 + (i1 + i2)) j\"\n    using ack2_le_ack1 add_2_eq_Suc by presburger\n  finally show ?thesis .\nqed\n\n\n\ntext \\<open>PROPERTY A 11\\<close>\n\nlemma ack_add_bound: \"ack i1 j + ack i2 j < ack (4 + (i1 + i2)) j\"\nproof -\n  have \"ack i1 j \\<le> ack (i1 + i2) j\" \"ack i2 j \\<le> ack (i1 + i2) j\"\n    by (simp_all add: ack_le_mono1)\n  then have \"ack i1 j + ack i2 j < ack (Suc (Suc 0)) (ack (i1 + i2) j)\"\n    by simp\n  also have \"... < ack (4 + (i1 + i2)) j\"\n    by (metis ack_nest_bound add.assoc numeral_2_eq_2 numeral_Bit0)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>PROPERTY A 12.  Article uses existential quantifier but the ALF proof\n  used \\<open>k + 4\\<close>.  Quantified version must be nested \\<open>\\<exists>k'. \\<forall>i j. ...\\<close>\\<close>\n\nlemma ack_add_bound2: \n  assumes \"i < ack k j\" shows \"i + j < ack (4 + k) j\"\nproof -\n  have \"i + j < ack k j + ack 0 j\"\n    using assms by auto\n  also have \"... < ack (4 + k) j\"\n    by (metis ack_add_bound add.right_neutral)\n  finally show ?thesis .\nqed\n\n\nsubsection\\<open>Primitive Recursive Functions\\<close>\n\nprimrec hd0 :: \"nat list \\<Rightarrow> nat\" where\n  \"hd0 [] = 0\" \n| \"hd0 (m # ms) = m\"\n\n\ntext \\<open>Inductive definition of the set of primitive recursive functions of type \\<^typ>\\<open>nat list \\<Rightarrow> nat\\<close>.\\<close>\n\ndefinition SC :: \"nat list \\<Rightarrow> nat\" \n  where \"SC l = Suc (hd0 l)\"\n\ndefinition CONSTANT :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\" \n  where \"CONSTANT k l = k\"\n\ndefinition PROJ :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\" \n  where \"PROJ i l = hd0 (drop i l)\"\n\ndefinition COMP :: \"[nat list \\<Rightarrow> nat, (nat list \\<Rightarrow> nat) list, nat list] \\<Rightarrow> nat\"\n  where \"COMP g fs l = g (map (\\<lambda>f. f l) fs)\"\n\nfun PREC :: \"[nat list \\<Rightarrow> nat, nat list \\<Rightarrow> nat, nat list] \\<Rightarrow> nat\"\n  where\n    \"PREC f g [] = 0\"\n  | \"PREC f g (x # l) = rec_nat (f l) (\\<lambda>y r. g (r # y # l)) x\"\n    \\<comment> \\<open>Note that \\<^term>\\<open>g\\<close> is applied first to \\<^term>\\<open>PREC f g y\\<close> and then to \\<^term>\\<open>y\\<close>!\\<close>\n\ninductive PRIMREC :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n  SC: \"PRIMREC SC\"\n| CONSTANT: \"PRIMREC (CONSTANT k)\"\n| PROJ: \"PRIMREC (PROJ i)\"\n| COMP: \"PRIMREC g \\<Longrightarrow> \\<forall>f \\<in> set fs. PRIMREC f \\<Longrightarrow> PRIMREC (COMP g fs)\"\n| PREC: \"PRIMREC f \\<Longrightarrow> PRIMREC g \\<Longrightarrow> PRIMREC (PREC f g)\"\n\n\ntext \\<open>Useful special cases of evaluation\\<close>\n\nlemma SC [simp]: \"SC (x # l) = Suc x\"\n  by (simp add: SC_def)\n\nlemma PROJ_0 [simp]: \"PROJ 0 (x # l) = x\"\n  by (simp add: PROJ_def)\n\nlemma COMP_1 [simp]: \"COMP g [f] l = g [f l]\"\n  by (simp add: COMP_def)\n\nlemma PREC_0: \"PREC f g (0 # l) = f l\"\n  by simp\n\nlemma PREC_Suc [simp]: \"PREC f g (Suc x # l) = g (PREC f g (x # l) # x # l)\"\n  by auto\n\n\nsubsection \\<open>MAIN RESULT\\<close>\n\nlemma SC_case: \"SC l < ack 1 (sum_list l)\"\n  unfolding SC_def\n  by (induct l) (simp_all add: le_add1 le_imp_less_Suc)\n\nlemma CONSTANT_case: \"CONSTANT k l < ack k (sum_list l)\"\n  by (simp add: CONSTANT_def)\n\nlemma PROJ_case: \"PROJ i l < ack 0 (sum_list l)\"\n  unfolding PROJ_def\nproof (induct l arbitrary: i)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a l)\n  then show ?case\n    by (metis ack.simps(1) add.commute drop_Cons' hd0.simps(2) leD leI lessI not_less_eq sum_list.Cons trans_le_add2)\nqed\n\n\ntext \\<open>\\<^term>\\<open>COMP\\<close> case\\<close>\n\nlemma COMP_map_aux: \"\\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (sum_list l))\n  \\<Longrightarrow> \\<exists>k. \\<forall>l. sum_list (map (\\<lambda>f. f l) fs) < ack k (sum_list l)\"\nproof (induct fs)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons a fs)\n  then show ?case\n    by simp (blast intro: add_less_mono ack_add_bound less_trans)\nqed\n\nlemma COMP_case:\n  assumes 1: \"\\<forall>l. g l < ack kg (sum_list l)\" \n      and 2: \"\\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (sum_list l))\"\n  shows \"\\<exists>k. \\<forall>l. COMP g fs  l < ack k (sum_list l)\"\n  unfolding COMP_def\n  using 1 COMP_map_aux [OF 2] by (meson ack_less_mono2 ack_nest_bound less_trans)\n\ntext \\<open>\\<^term>\\<open>PREC\\<close> case\\<close>\n\nlemma PREC_case_aux:\n  assumes f: \"\\<And>l. f l + sum_list l < ack kf (sum_list l)\"\n      and g: \"\\<And>l. g l + sum_list l < ack kg (sum_list l)\"\n  shows \"PREC f g l + sum_list l < ack (Suc (kf + kg)) (sum_list l)\"\nproof (cases l)\n  case Nil\n  then show ?thesis\n    by (simp add: Suc_lessD)\nnext\n  case (Cons m l)\n  have \"rec_nat (f l) (\\<lambda>y r. g (r # y # l)) m + (m + sum_list l) < ack (Suc (kf + kg)) (m + sum_list l)\"\n  proof (induct m)\n    case 0\n    then show ?case\n      using ack_less_mono1_aux f less_trans by fastforce\n  next\n    case (Suc m)\n    let ?r = \"rec_nat (f l) (\\<lambda>y r. g (r # y # l)) m\"\n    have \"\\<not> g (?r # m # l) + sum_list (?r # m # l) < g (?r # m # l) + (m + sum_list l)\"\n      by force\n    then have \"g (?r # m # l) + (m + sum_list l) < ack kg (sum_list (?r # m # l))\"\n      by (meson assms(2) leI less_le_trans)\n    moreover \n    have \"... < ack (kf + kg) (ack (Suc (kf + kg)) (m + sum_list l))\"\n      using Suc.hyps by simp (meson ack_le_mono1 ack_less_mono2 le_add2 le_less_trans)\n    ultimately show ?case\n      by auto\n  qed\n  then show ?thesis\n    by (simp add: local.Cons)\nqed\n\nproposition PREC_case:\n  \"\\<lbrakk>\\<And>l. f l < ack kf (sum_list l); \\<And>l. g l < ack kg (sum_list l)\\<rbrakk> \n  \\<Longrightarrow> \\<exists>k. \\<forall>l. PREC f g l < ack k (sum_list l)\"\n  by (metis le_less_trans [OF le_add1 PREC_case_aux] ack_add_bound2)\n\nlemma ack_bounds_PRIMREC: \"PRIMREC f \\<Longrightarrow> \\<exists>k. \\<forall>l. f l < ack k (sum_list l)\"\n  by (erule PRIMREC.induct) (blast intro: SC_case CONSTANT_case PROJ_case COMP_case PREC_case)+\n\ntheorem ack_not_PRIMREC:\n  \"\\<not> PRIMREC (\\<lambda>l. case l of [] \\<Rightarrow> 0 | x # l' \\<Rightarrow> ack x x)\"\nproof\n  assume *: \"PRIMREC (\\<lambda>l. case l of [] \\<Rightarrow> 0 | x # l' \\<Rightarrow> ack x x)\"\n  then obtain m where m: \"\\<And>l. (case l of [] \\<Rightarrow> 0 | x # l' \\<Rightarrow> ack x x) < ack m (sum_list l)\"\n    using ack_bounds_PRIMREC by metis\n  show False\n    using m [of \"[m]\"] by simp\nqed\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/ex/Primrec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7899035280073688}}
{"text": "(*<*)theory PDL imports Base begin(*>*)\n\nsubsection{*Propositional Dynamic Logic --- PDL*}\n\ntext{*\\index{PDL|(}\nThe formulae of PDL are built up from atomic propositions via\nnegation and conjunction and the two temporal\nconnectives @{text AX} and @{text EF}\\@. Since formulae are essentially\nsyntax trees, they are naturally modelled as a datatype:%\n\\footnote{The customary definition of PDL\n@{cite \"HarelKT-DL\"} looks quite different from ours, but the two are easily\nshown to be equivalent.}\n*}\n\ndatatype formula = Atom \"atom\"\n                  | Neg formula\n                  | And formula formula\n                  | AX formula\n                  | EF formula\n\ntext{*\\noindent\nThis resembles the boolean expression case study in\n\\S\\ref{sec:boolex}.\nA validity relation between states and formulae specifies the semantics.\nThe syntax annotation allows us to write @{text\"s \\<Turnstile> f\"} instead of\n\\hbox{@{text\"valid s f\"}}. The definition is by recursion over the syntax:\n*}\n\nprimrec valid :: \"state \\<Rightarrow> formula \\<Rightarrow> bool\"   (\"(_ \\<Turnstile> _)\" [80,80] 80)\nwhere\n\"s \\<Turnstile> Atom a  = (a \\<in> L s)\" |\n\"s \\<Turnstile> Neg f   = (\\<not>(s \\<Turnstile> f))\" |\n\"s \\<Turnstile> And f g = (s \\<Turnstile> f \\<and> s \\<Turnstile> g)\" |\n\"s \\<Turnstile> AX f    = (\\<forall>t. (s,t) \\<in> M \\<longrightarrow> t \\<Turnstile> f)\" |\n\"s \\<Turnstile> EF f    = (\\<exists>t. (s,t) \\<in> M\\<^sup>* \\<and> t \\<Turnstile> f)\"\n\ntext{*\\noindent\nThe first three equations should be self-explanatory. The temporal formula\n@{term\"AX f\"} means that @{term f} is true in \\emph{A}ll ne\\emph{X}t states whereas\n@{term\"EF f\"} means that there \\emph{E}xists some \\emph{F}uture state in which @{term f} is\ntrue. The future is expressed via @{text\"\\<^sup>*\"}, the reflexive transitive\nclosure. Because of reflexivity, the future includes the present.\n\nNow we come to the model checker itself. It maps a formula into the\nset of states where the formula is true.  It too is defined by\nrecursion over the syntax: *}\n\nprimrec mc :: \"formula \\<Rightarrow> state set\" where\n\"mc(Atom a)  = {s. a \\<in> L s}\" |\n\"mc(Neg f)   = -mc f\" |\n\"mc(And f g) = mc f \\<inter> mc g\" |\n\"mc(AX f)    = {s. \\<forall>t. (s,t) \\<in> M  \\<longrightarrow> t \\<in> mc f}\" |\n\"mc(EF f)    = lfp(\\<lambda>T. mc f \\<union> (M\\<inverse> `` T))\"\n\ntext{*\\noindent\nOnly the equation for @{term EF} deserves some comments. Remember that the\npostfix @{text\"\\<inverse>\"} and the infix @{text\"``\"} are predefined and denote the\nconverse of a relation and the image of a set under a relation.  Thus\n@{term \"M\\<inverse> `` T\"} is the set of all predecessors of @{term T} and the least\nfixed point (@{term lfp}) of @{term\"\\<lambda>T. mc f \\<union> M\\<inverse> `` T\"} is the least set\n@{term T} containing @{term\"mc f\"} and all predecessors of @{term T}. If you\nfind it hard to see that @{term\"mc(EF f)\"} contains exactly those states from\nwhich there is a path to a state where @{term f} is true, do not worry --- this\nwill be proved in a moment.\n\nFirst we prove monotonicity of the function inside @{term lfp}\nin order to make sure it really has a least fixed point.\n*}\n\nlemma mono_ef: \"mono(\\<lambda>T. A \\<union> (M\\<inverse> `` T))\"\napply(rule monoI)\napply blast\ndone\n\ntext{*\\noindent\nNow we can relate model checking and semantics. For the @{text EF} case we need\na separate lemma:\n*}\n\nlemma EF_lemma:\n  \"lfp(\\<lambda>T. A \\<union> (M\\<inverse> `` T)) = {s. \\<exists>t. (s,t) \\<in> M\\<^sup>* \\<and> t \\<in> A}\"\n\ntxt{*\\noindent\nThe equality is proved in the canonical fashion by proving that each set\nincludes the other; the inclusion is shown pointwise:\n*}\n\napply(rule equalityI)\n apply(rule subsetI)\n apply(simp)(*<*)apply(rename_tac s)(*>*)\n\ntxt{*\\noindent\nSimplification leaves us with the following first subgoal\n@{subgoals[display,indent=0,goals_limit=1]}\nwhich is proved by @{term lfp}-induction:\n*}\n\n apply(erule lfp_induct_set)\n  apply(rule mono_ef)\n apply(simp)\ntxt{*\\noindent\nHaving disposed of the monotonicity subgoal,\nsimplification leaves us with the following goal:\n\\begin{isabelle}\n\\ {\\isadigit{1}}{\\isachardot}\\ {\\isasymAnd}x{\\isachardot}\\ x\\ {\\isasymin}\\ A\\ {\\isasymor}\\isanewline\n\\ \\ \\ \\ \\ \\ \\ \\ \\ x\\ {\\isasymin}\\ M{\\isasyminverse}\\ {\\isacharbackquote}{\\isacharbackquote}\\ {\\isacharparenleft}lfp\\ {\\isacharparenleft}\\dots{\\isacharparenright}\\ {\\isasyminter}\\ {\\isacharbraceleft}x{\\isachardot}\\ {\\isasymexists}t{\\isachardot}\\ {\\isacharparenleft}x{\\isacharcomma}\\ t{\\isacharparenright}\\ {\\isasymin}\\ M\\isactrlsup {\\isacharasterisk}\\ {\\isasymand}\\ t\\ {\\isasymin}\\ A{\\isacharbraceright}{\\isacharparenright}\\isanewline\n\\ \\ \\ \\ \\ \\ \\ \\ {\\isasymLongrightarrow}\\ {\\isasymexists}t{\\isachardot}\\ {\\isacharparenleft}x{\\isacharcomma}\\ t{\\isacharparenright}\\ {\\isasymin}\\ M\\isactrlsup {\\isacharasterisk}\\ {\\isasymand}\\ t\\ {\\isasymin}\\ A\n\\end{isabelle}\nIt is proved by @{text blast}, using the transitivity of \n\\isa{M\\isactrlsup {\\isacharasterisk}}.\n*}\n\n apply(blast intro: rtrancl_trans)\n\ntxt{*\nWe now return to the second set inclusion subgoal, which is again proved\npointwise:\n*}\n\napply(rule subsetI)\napply(simp, clarify)\n\ntxt{*\\noindent\nAfter simplification and clarification we are left with\n@{subgoals[display,indent=0,goals_limit=1]}\nThis goal is proved by induction on @{term\"(s,t)\\<in>M\\<^sup>*\"}. But since the model\nchecker works backwards (from @{term t} to @{term s}), we cannot use the\ninduction theorem @{thm[source]rtrancl_induct}: it works in the\nforward direction. Fortunately the converse induction theorem\n@{thm[source]converse_rtrancl_induct} already exists:\n@{thm[display,margin=60]converse_rtrancl_induct[no_vars]}\nIt says that if @{prop\"(a,b):r\\<^sup>*\"} and we know @{prop\"P b\"} then we can infer\n@{prop\"P a\"} provided each step backwards from a predecessor @{term z} of\n@{term b} preserves @{term P}.\n*}\n\napply(erule converse_rtrancl_induct)\n\ntxt{*\\noindent\nThe base case\n@{subgoals[display,indent=0,goals_limit=1]}\nis solved by unrolling @{term lfp} once\n*}\n\n apply(subst lfp_unfold[OF mono_ef])\n\ntxt{*\n@{subgoals[display,indent=0,goals_limit=1]}\nand disposing of the resulting trivial subgoal automatically:\n*}\n\n apply(blast)\n\ntxt{*\\noindent\nThe proof of the induction step is identical to the one for the base case:\n*}\n\napply(subst lfp_unfold[OF mono_ef])\napply(blast)\ndone\n\ntext{*\nThe main theorem is proved in the familiar manner: induction followed by\n@{text auto} augmented with the lemma as a simplification rule.\n*}\n\ntheorem \"mc f = {s. s \\<Turnstile> f}\"\napply(induct_tac f)\napply(auto simp add: EF_lemma)\ndone\n\ntext{*\n\\begin{exercise}\n@{term AX} has a dual operator @{term EN} \n(``there exists a next state such that'')%\n\\footnote{We cannot use the customary @{text EX}: it is reserved\nas the \\textsc{ascii}-equivalent of @{text\"\\<exists>\"}.}\nwith the intended semantics\n@{prop[display]\"(s \\<Turnstile> EN f) = (EX t. (s,t) : M & t \\<Turnstile> f)\"}\nFortunately, @{term\"EN f\"} can already be expressed as a PDL formula. How?\n\nShow that the semantics for @{term EF} satisfies the following recursion equation:\n@{prop[display]\"(s \\<Turnstile> EF f) = (s \\<Turnstile> f | s \\<Turnstile> EN(EF f))\"}\n\\end{exercise}\n\\index{PDL|)}\n*}\n(*<*)\ntheorem main: \"mc f = {s. s \\<Turnstile> f}\"\napply(induct_tac f)\napply(auto simp add: EF_lemma)\ndone\n\nlemma aux: \"s \\<Turnstile> f = (s : mc f)\"\napply(simp add: main)\ndone\n\nlemma \"(s \\<Turnstile> EF f) = (s \\<Turnstile> f | s \\<Turnstile> Neg(AX(Neg(EF f))))\"\napply(simp only: aux)\napply(simp)\napply(subst lfp_unfold[OF mono_ef], fast)\ndone\n\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/CTL/PDL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8856314692902446, "lm_q1q2_score": 0.7898159265004627}}
{"text": "section \\<open>Dimension of Spans\\<close>\n\ntext \\<open>We define the notion of dimension of a span of vectors and prove some natural results about them.\n  The definition is made as a function, so that no interpretation of locales like subspace is required.\\<close>\ntheory Dim_Span\n  imports Missing_VS_Connect\nbegin\n\ncontext vec_space\nbegin\ndefinition \"dim_span W = Max (card ` {V. V \\<subseteq> carrier_vec n \\<and> V \\<subseteq> span W \\<and> lin_indpt V})\"\n\nlemma fixes V W :: \"'a vec set\"\n  shows\n    card_le_dim_span:\n    \"V \\<subseteq> carrier_vec n \\<Longrightarrow> V \\<subseteq> span W \\<Longrightarrow> lin_indpt V \\<Longrightarrow> card V \\<le> dim_span W\" and\n    card_eq_dim_span_imp_same_span:\n    \"W \\<subseteq> carrier_vec n \\<Longrightarrow> V \\<subseteq> span W \\<Longrightarrow> lin_indpt V \\<Longrightarrow> card V = dim_span W \\<Longrightarrow> span V = span W\" and\n    same_span_imp_card_eq_dim_span:\n    \"V \\<subseteq> carrier_vec n \\<Longrightarrow> W \\<subseteq> carrier_vec n \\<Longrightarrow> span V = span W \\<Longrightarrow> lin_indpt V \\<Longrightarrow> card V = dim_span W\" and\n    dim_span_cong:\n    \"span V = span W \\<Longrightarrow> dim_span V = dim_span W\" and\n    ex_basis_span:\n    \"V \\<subseteq> carrier_vec n \\<Longrightarrow> \\<exists> W. W \\<subseteq> carrier_vec n \\<and> lin_indpt W \\<and> span V = span W \\<and> dim_span V = card W\"\nproof -\n  show cong: \"\\<And> V W. span V = span W \\<Longrightarrow> dim_span V = dim_span W\" unfolding dim_span_def by auto\n  {\n    fix W :: \"'a vec set\"\n    let ?M = \"{V. V \\<subseteq> carrier_vec n \\<and> V \\<subseteq> span W \\<and> lin_indpt V}\"\n    have \"card ` ?M \\<subseteq> {0 .. n}\"\n    proof\n      fix k\n      assume \"k \\<in> card ` ?M\"\n      then obtain V where V: \"V \\<subseteq> carrier_vec n \\<and> V \\<subseteq> span W \\<and> lin_indpt V\"\n        and k: \"k = card V\"\n        by auto\n      from V have \"card V \\<le> n\" using dim_is_n li_le_dim by auto\n      with k show \"k \\<in> {0 .. n}\" by auto\n    qed\n    from finite_subset[OF this]\n    have fin: \"finite (card ` ?M)\" by auto\n    have \"{} \\<in> ?M\" by (auto simp: span_empty span_zero)\n    from imageI[OF this, of card]\n    have \"0 \\<in> card ` ?M\" by auto\n    hence Mempty: \"card ` ?M \\<noteq> {}\" by auto\n    from Max_ge[OF fin, folded dim_span_def]\n    show \"\\<And> V :: 'a vec set. V \\<subseteq> carrier_vec n \\<Longrightarrow> V \\<subseteq> span W \\<Longrightarrow> lin_indpt V \\<Longrightarrow> card V \\<le> dim_span W\"\n      by auto\n    note this fin Mempty\n  } note part1 = this\n  {\n    fix V W :: \"'a vec set\"\n    assume  W: \"W \\<subseteq> carrier_vec n\"\n      and VsW: \"V \\<subseteq> span W\" and linV: \"lin_indpt V\" and card: \"card V = dim_span W\"\n    from W VsW have V: \"V \\<subseteq> carrier_vec n\" using span_mem[OF W] by auto\n    from Max_in[OF part1(2,3), folded dim_span_def, of W]\n    obtain WW where WW: \"WW \\<subseteq> carrier_vec n\" \"WW \\<subseteq> span W\" \"lin_indpt WW\"\n      and id: \"dim_span W = card WW\" by auto\n    show \"span V = span W\"\n    proof (rule ccontr)\n      from VsW V W have sub: \"span V \\<subseteq> span W\" using span_subsetI by metis\n      assume \"span V \\<noteq> span W\"\n      with sub obtain w where wW: \"w \\<in> span W\" and wsV: \"w \\<notin> span V\" by auto\n      from wW W have w: \"w \\<in> carrier_vec n\" by auto\n      from linV V have finV: \"finite V\" using fin_dim fin_dim_li_fin by blast\n      from wsV span_mem[OF V, of w] have wV: \"w \\<notin> V\" by auto\n      let ?X = \"insert w V\"\n      have \"card ?X = Suc (card V)\" using wV finV by simp\n      hence gt: \"card ?X > dim_span W\" unfolding card by simp\n      have linX: \"lin_indpt ?X\" using lin_dep_iff_in_span[OF V linV w wV] wsV by auto\n      have XW: \"?X \\<subseteq> span W\" using wW VsW by auto\n      from part1(1)[OF _ XW linX] w V have \"card ?X \\<le> dim_span W\" by auto\n      with gt show False by auto\n    qed\n  } note card_dim_span = this\n  {\n    fix V :: \"'a vec set\"\n    assume V: \"V \\<subseteq> carrier_vec n\"\n    from Max_in[OF part1(2,3), folded dim_span_def, of V]\n    obtain W where W: \"W \\<subseteq> carrier_vec n\" \"W \\<subseteq> span V\" \"lin_indpt W\"\n      and idW: \"card W = dim_span V\" by auto\n    show \"\\<exists> W. W \\<subseteq> carrier_vec n \\<and> lin_indpt W \\<and> span V = span W \\<and> dim_span V = card W\"\n    proof (intro exI[of _ W] conjI W idW[symmetric])\n      from card_dim_span[OF V(1) W(2-3) idW] show \"span V = span W\"  by auto\n    qed\n  }\n  {\n    fix V W\n    assume V: \"V \\<subseteq> carrier_vec n\"\n      and W: \"W \\<subseteq> carrier_vec n\"\n      and span: \"span V = span W\"\n      and lin: \"lin_indpt V\"\n    from Max_in[OF part1(2,3), folded dim_span_def, of W]\n    obtain WW where WW: \"WW \\<subseteq> carrier_vec n\" \"WW \\<subseteq> span W\" \"lin_indpt WW\"\n      and idWW: \"card WW = dim_span W\" by auto\n    from card_dim_span[OF W WW(2-3) idWW] span\n    have spanWW: \"span WW = span V\" by auto\n    from span have \"V \\<subseteq> span W\" using span_mem[OF V] by auto\n    from part1(1)[OF V this lin] have VW: \"card V \\<le> dim_span W\" .\n    have finWW: \"finite WW\" using WW by (simp add: fin_dim_li_fin)\n    have finV: \"finite V\" using lin V by (simp add: fin_dim_li_fin)\n    from replacement[OF finWW finV V WW(3) WW(2)[folded span], unfolded idWW]\n    obtain C :: \"'a vec set\"\n      where le: \"int (card C) \\<le> int (card V) - int (dim_span W)\" by auto\n    from le have \"int (dim_span W) + int (card C) \\<le> int (card V)\" by linarith\n    hence \"dim_span W + card C \\<le> card V\" by linarith\n    with VW show \"card V = dim_span W\" by auto\n  }\nqed\n\nlemma dim_span_le_n: assumes W: \"W \\<subseteq> carrier_vec n\" shows \"dim_span W \\<le> n\"\nproof -\n  from ex_basis_span[OF W] obtain V where\n    V: \"V \\<subseteq> carrier_vec n\"\n    and lin: \"lin_indpt V\"\n    and dim: \"dim_span W = card V\"\n    by auto\n  show ?thesis unfolding dim using lin V\n    using dim_is_n li_le_dim by auto\nqed\n\nlemma dim_span_insert: assumes W: \"W \\<subseteq> carrier_vec n\"\n  and v: \"v \\<in> carrier_vec n\" and vs: \"v \\<notin> span W\"\nshows \"dim_span (insert v W) = Suc (dim_span W)\"\nproof -\n  from ex_basis_span[OF W] obtain V where\n    V: \"V \\<subseteq> carrier_vec n\"\n    and lin: \"lin_indpt V\"\n    and span: \"span W = span V\"\n    and dim: \"dim_span W = card V\"\n    by auto\n  from V vs[unfolded span] have vV: \"v \\<notin> V\" using span_mem[OF V] by blast\n  from lin_dep_iff_in_span[OF V lin v vV] vs span\n  have lin': \"lin_indpt (insert v V)\" by auto\n  have finV: \"finite V\" using lin V using fin_dim fin_dim_li_fin by blast\n  have \"card (insert v V) = Suc (card V)\" using finV vV by auto\n  hence cvV: \"card (insert v V) = Suc (dim_span W)\" using dim by auto\n  have \"span (insert v V) = span (insert v W)\"\n    using span V W v by (metis bot_least insert_subset insert_union span_union_is_sum)\n  from same_span_imp_card_eq_dim_span[OF _ _ this lin'] cvV v V W\n  show ?thesis by auto\nqed\nend\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Linear_Inequalities/Dim_Span.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392939666336, "lm_q2_score": 0.8933094145755219, "lm_q1q2_score": 0.7897206241550913}}
{"text": "theory SumTail\n  imports Main\nbegin\n\ntext \\<open>\n\\begin{description}\n\\item[\\bf (a)] Define a primitive recursive function @{term ListSum} that\ncomputes the sum of all elements of a list of natural numbers.\n\nProve the following equations.  Note that @{term  \"[0..n]\"} und @{term\n\"replicate n a\"} are already defined in a theory {\\tt List.thy}.\n\\end{description}\n\\<close>\n\nprimrec ListSum :: \"nat list \\<Rightarrow> nat\"\n  where\n\"ListSum [] = 0\" |\n\"ListSum (x#xs) = x + ListSum xs\"\n\nlemma ListSum_append[simp]:\"ListSum (xs @ ys) = ListSum xs + ListSum ys\"\n  apply (induction xs) by auto\n\ntheorem \"2 * ListSum [0..<n+1] = n * (n + 1)\"\n  apply (induction n) by auto\n\ntheorem \"ListSum (replicate n a) = n * a\"\n  apply (induction n) by auto\n\n\ntext \\<open> \n\\begin{description}\n\\item[\\bf (b)] Define an equivalent function @{term ListSumT} using a\ntail-recursive function @{term ListSumTAux}.  Prove that @{term ListSum}\nand @{term ListSumT} are in fact equivalent.\n\\end{description}\n\\<close>\n\nprimrec ListSumTAux :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n\"ListSumTAux [] n = n\" |\n\"ListSumTAux (x#xs) n = ListSumTAux xs (x + n)\"\n\nlemma ListSumTAux_sum_accum[simp]:\"\\<forall> a b. ListSumTAux xs (a + b) = a + ListSumTAux xs b\"\n  apply (induction xs) by auto\n\nlemma ListSumTAux_append[simp]:\"ListSumTAux (xs @ ys) 0 = ListSumTAux xs 0 + ListSumTAux ys 0\"\n  apply (induction xs)\n   apply auto\n  by (metis ListSumTAux_sum_accum Nat.add_0_right)\n\ndefinition ListSumT :: \"nat list \\<Rightarrow> nat\"\n  where\n\"ListSumT xs = ListSumTAux xs 0\"\n\nlemma ListSumT_append[simp]:\"ListSumT (xs @ ys) = ListSumT xs + ListSumT ys\"\n  apply (induction xs)\n   apply (auto simp add: ListSumT_def)\n  by (metis ListSumTAux_append ListSumTAux_sum_accum add.commute add.left_neutral)\n\ntheorem \"ListSum xs = ListSumT xs\"\n  apply (induction xs)\n   apply (auto simp add: ListSumT_def)\n  by (metis ListSumTAux_sum_accum Nat.add_0_right)\n\nend\n", "meta": {"author": "tomssem", "repo": "isabelle_exercises", "sha": "000b8edcb2050d4931e3177e9a339101d777dfe7", "save_path": "github-repos/isabelle/tomssem-isabelle_exercises", "path": "github-repos/isabelle/tomssem-isabelle_exercises/isabelle_exercises-000b8edcb2050d4931e3177e9a339101d777dfe7/lists/SumTail.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.8740772351648677, "lm_q1q2_score": 0.7895489004606433}}
{"text": "theory \"Mono-Nat-Fun\"\nimports \"Library/Infinite_Set\"\nbegin\n\ntext {*\nThe following lemma proves that a monotonous function from and the natural numbers is either eventually\nconstant or unbounded.\n*}\n\nlemma nat_mono_characterization:\n  fixes f :: \"nat \\<Rightarrow> nat\"\n  assumes \"mono f\"\n  obtains n where \"\\<And>m . n \\<le> m \\<Longrightarrow> f n = f m\" | \"\\<And> m . \\<exists> n . m \\<le> f n\"\nproof (cases \"finite (range f)\")\n  case True\n  from Max_in[OF True]\n  obtain n where Max: \"f n = Max (range f)\" by auto\n  show thesis\n  proof(rule that(1))\n    fix m\n    assume \"n \\<le> m\"\n    hence \"f n \\<le> f m\" using `mono f` by (metis monoD)\n    also\n    have \"f m \\<le> f n\" unfolding Max by (rule Max_ge[OF True rangeI])\n    finally\n    show \"f n = f m\".\n  qed\nnext\n  case False\n  thus thesis by (fastforce intro: that(2) simp add: infinite_nat_iff_unbounded_le)\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Launchbury/Mono-Nat-Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9473810525948928, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7894759361814927}}
{"text": "theory P23 imports Main begin\n\ndatatype form = T | Var nat | And form form | Xor form form\n\ndefinition\nxor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"xor x y \\<equiv> (\\<not> (x=y))\"\n\nprimrec evalf :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\" where\n\"evalf p T = True\" |\n\"evalf p (Var n) = p n\" |\n\"evalf p (And f1 f2) = ((evalf p f1) \\<and> (evalf p f2))\" |\n\"evalf p (Xor f1 f2) = (xor (evalf p f1) (evalf p f2))\"\n\nprimrec evalm :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"evalm p Nil = True\" |\n\"evalm p (x # xs) = ((p x) \\<and> (evalm p xs))\"\n\nprimrec evalp :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat list list \\<Rightarrow> bool\" where\n\"evalp p Nil = False\" |\n\"evalp p (xs # xss) = (\\<not>((evalm p xs) = (evalp p xss)))\"\n\nlemma \"evalm (\\<lambda>x. False) Nil = True\"\n  apply simp\n  done\n\nlemma \"evalm (\\<lambda>x. False) [1] = False\"\n  apply simp\n  done\n\nlemma \"evalp (\\<lambda>x. False) [] = False\"\n  apply simp\n  done\n\nlemma \"evalp (\\<lambda>x. False) [[1], [2]] = False\"\n  apply simp\n  done\n\nlemma \"evalp (\\<lambda>x. True) [[1], [2], [3]] = True\"\n  apply simp\n  done\n\nprimrec mulpp :: \"nat list list \\<Rightarrow> nat list list \\<Rightarrow> nat list list\" where\n\"mulpp Nil qs = Nil\" | \n\"mulpp (p # ps) qs = (map (\\<lambda>x. x @ p) qs @ (mulpp ps qs))\"\n\nprimrec poly :: \"form \\<Rightarrow> nat list list\" where\n\"poly T = [[]]\" |\n\"poly (Var n) = [[n]]\" |\n\"poly (And f1 f2) = mulpp (poly f1) (poly f2)\" |\n\"poly (Xor f1 f2) = (poly f1 @ poly f2)\"\n\nlemma evalm_app: \"evalm e (xs @ ys) = (evalm e xs \\<and> evalm e ys)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma evalp_app: \"evalp e (xs @ ys) = (xor (evalp e xs) (evalp e ys))\"\n  apply (induct xs)\n   apply (auto simp add: xor_def)\ndone\n\ntheorem mulmp_correct: \"evalp e (map (\\<lambda>x. x @ m) p) = (evalm e m \\<and> evalp e p)\"\n  apply (induct p)\n  apply (auto simp add: xor_def evalm_app)\n  done\n\ntheorem mulpp_correct: \"evalp e (mulpp p q) = (evalp e p \\<and> evalp e q)\"\n  apply (induct p)\n   apply (auto simp add: xor_def mulmp_correct evalp_app)\ndone\n\ntheorem poly_correct: \"evalf e f = evalp e (poly f)\"\n  apply (induct f)\n  apply simp\n  apply simp\n  apply (simp add: mulpp_correct)\n  apply (simp add: evalp_app)\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P23.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810436809829, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7894759209101624}}
{"text": "(*\n  Copyright (c) 2014-2019 by Clemens Ballarin\n  This file is licensed under the 3-clause BSD license.\n*)\n\ntheory Group_Theory imports Set_Theory begin\n\nhide_const monoid\nhide_const group\nhide_const inverse\n\nno_notation quotient (infixl \"'/'/\" 90)\n\n\nsection \\<open>Monoids and Groups\\<close>\n\nsubsection \\<open>Monoids of Transformations and Abstract Monoids\\<close>\n\ntext \\<open>Def 1.1\\<close>\ntext \\<open>p 28, ll 28--30\\<close>\nlocale monoid =\n  fixes M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n  assumes composition_closed [intro, simp]: \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> a \\<cdot> b \\<in> M\"\n    and unit_closed [intro, simp]: \"\\<one> \\<in> M\"\n    and associative [intro]: \"\\<lbrakk> a \\<in> M; b \\<in> M; c \\<in> M \\<rbrakk> \\<Longrightarrow> (a \\<cdot> b) \\<cdot> c = a \\<cdot> (b \\<cdot> c)\"\n    and left_unit [intro, simp]: \"a \\<in> M \\<Longrightarrow> \\<one> \\<cdot> a = a\"\n    and right_unit [intro, simp]: \"a \\<in> M \\<Longrightarrow> a \\<cdot> \\<one> = a\"\n\ntext \\<open>p 29, ll 27--28\\<close>\nlocale submonoid = monoid M \"(\\<cdot>)\" \\<one>\n  for N and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes subset [intro, simp]: \"N \\<subseteq> M\"\n    and sub_composition_closed: \"\\<lbrakk> a \\<in> N; b \\<in> N \\<rbrakk> \\<Longrightarrow> a \\<cdot> b \\<in> N\"\n    and sub_unit_closed: \"\\<one> \\<in> N\"\nbegin\n\ntext \\<open>p 29, ll 27--28\\<close>\nlemma sub [intro, simp]:\n  \"a \\<in> N \\<Longrightarrow> a \\<in> M\"\n  using subset by blast\n\ntext \\<open>p 29, ll 32--33\\<close>\nsublocale sub: monoid N \"(\\<cdot>)\" \\<one>\n  by unfold_locales (auto simp: sub_composition_closed sub_unit_closed)\n\nend (* submonoid *)\n\ntext \\<open>p 29, ll 33--34\\<close>\ntheorem submonoid_transitive:\n  assumes \"submonoid K N composition unit\"\n    and \"submonoid N M composition unit\"\n  shows \"submonoid K M composition unit\"\nproof -\n  interpret K: submonoid K N composition unit by fact\n  interpret M: submonoid N M composition unit by fact\n  show ?thesis by unfold_locales auto\nqed\n\ntext \\<open>p 28, l 23\\<close>\nlocale transformations =\n  fixes S :: \"'a set\"\n\n(*  assumes non_vacuous: \"S \\<noteq> {}\" *) (* Jacobson requires this but we don't need it, strange. *)\n\ntext \\<open>Monoid of all transformations\\<close>\ntext \\<open>p 28, ll 23--24\\<close>\nsublocale transformations \\<subseteq> monoid \"S \\<rightarrow>\\<^sub>E S\" \"compose S\" \"identity S\"\n  by unfold_locales (auto simp: PiE_def compose_eq compose_assoc Id_compose compose_Id)\n\ntext \\<open>@{term N} is a monoid of transformations of the set @{term S}.\\<close>\ntext \\<open>p 29, ll 34--36\\<close>\nlocale transformation_monoid =\n  transformations S + submonoid M \"S \\<rightarrow>\\<^sub>E S\" \"compose S\" \"identity S\" for M and S\nbegin\n\ntext \\<open>p 29, ll 34--36\\<close>\nlemma transformation_closed [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> M; x \\<in> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x \\<in> S\"\n  by (metis PiE_iff sub)\n\ntext \\<open>p 29, ll 34--36\\<close>\nlemma transformation_undefined [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> M; x \\<notin> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x = undefined\"\n  by (metis PiE_arb sub)\n\nend (* transformation_monoid *)\n\n\nsubsection \\<open>Groups of Transformations and Abstract Groups\\<close>\n\ncontext monoid begin\n\ntext \\<open>Invertible elements\\<close>\n\ntext \\<open>p 31, ll 3--5\\<close>\ndefinition invertible where \"u \\<in> M \\<Longrightarrow> invertible u \\<longleftrightarrow> (\\<exists>v \\<in> M. u \\<cdot> v = \\<one> \\<and> v \\<cdot> u = \\<one>)\"\n\ntext \\<open>p 31, ll 3--5\\<close>\nlemma invertibleI [intro]:\n  \"\\<lbrakk> u \\<cdot> v = \\<one>; v \\<cdot> u = \\<one>; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> invertible u\"\n  unfolding invertible_def by fast\n\ntext \\<open>p 31, ll 3--5\\<close>\nlemma invertibleE [elim]:\n  \"\\<lbrakk> invertible u; \\<And>v. \\<lbrakk> u \\<cdot> v = \\<one> \\<and> v \\<cdot> u = \\<one>; v \\<in> M \\<rbrakk> \\<Longrightarrow> P; u \\<in> M \\<rbrakk> \\<Longrightarrow> P\"\n  unfolding invertible_def by fast\n\ntext \\<open>p 31, ll 6--7\\<close>\ntheorem inverse_unique:\n  \"\\<lbrakk> u \\<cdot> v' = \\<one>; v \\<cdot> u = \\<one>; u \\<in> M;  v \\<in> M; v' \\<in> M \\<rbrakk> \\<Longrightarrow> v = v'\"\n  by (metis associative left_unit right_unit)\n\ntext \\<open>p 31, l 7\\<close>\ndefinition inverse where \"inverse = (\\<lambda>u \\<in> M. THE v. v \\<in> M \\<and> u \\<cdot> v = \\<one> \\<and> v \\<cdot> u = \\<one>)\"\n\ntext \\<open>p 31, l 7\\<close>\ntheorem inverse_equality:\n  \"\\<lbrakk> u \\<cdot> v = \\<one>; v \\<cdot> u = \\<one>; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u = v\"\n  unfolding inverse_def using inverse_unique by simp blast\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_inverse_closed [intro, simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u \\<in> M\"\n  using inverse_equality by auto\n\ntext \\<open>p 31, l 7\\<close>\nlemma inverse_undefined [intro, simp]:\n  \"u \\<notin> M \\<Longrightarrow> inverse u = undefined\"\n  by (simp add: inverse_def)\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_left_inverse [simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u \\<cdot> u = \\<one>\"\n  using inverse_equality by auto\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_right_inverse [simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> u \\<cdot> inverse u = \\<one>\"\n  using inverse_equality by auto\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_left_cancel [simp]:\n  \"\\<lbrakk> invertible x; x \\<in> M; y \\<in> M; z \\<in> M \\<rbrakk> \\<Longrightarrow> x \\<cdot> y = x \\<cdot> z \\<longleftrightarrow> y = z\"\n  by (metis associative invertible_def left_unit)\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_right_cancel [simp]:\n  \"\\<lbrakk> invertible x; x \\<in> M; y \\<in> M; z \\<in> M \\<rbrakk> \\<Longrightarrow> y \\<cdot> x = z \\<cdot> x \\<longleftrightarrow> y = z\"\n  by (metis associative invertible_def right_unit)\n\ntext \\<open>p 31, l 7\\<close>\nlemma inverse_unit [simp]: \"inverse \\<one> = \\<one>\"\n  using inverse_equality by blast\n\ntext \\<open>p 31, ll 7--8\\<close>\ntheorem invertible_inverse_invertible [intro, simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> invertible (inverse u)\"\n  using invertible_left_inverse invertible_right_inverse by blast\n\ntext \\<open>p 31, l 8\\<close>\ntheorem invertible_inverse_inverse [simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> inverse (inverse u) = u\"\n  by (simp add: inverse_equality)\n\nend (* monoid *)\n\ncontext submonoid begin\n\ntext \\<open>Reasoning about @{term invertible} and @{term inverse} in submonoids.\\<close>\n\ntext \\<open>p 31, l 7\\<close>\nlemma submonoid_invertible [intro, simp]:\n  \"\\<lbrakk> sub.invertible u; u \\<in> N \\<rbrakk> \\<Longrightarrow> invertible u\"\n  using invertibleI by blast\n\ntext \\<open>p 31, l 7\\<close>\nlemma submonoid_inverse_closed [intro, simp]:\n  \"\\<lbrakk> sub.invertible u; u \\<in> N \\<rbrakk> \\<Longrightarrow> inverse u \\<in> N\"\n  using inverse_equality by auto\n\nend (* submonoid *)\n\ntext \\<open>Def 1.2\\<close>\ntext \\<open>p 31, ll 9--10\\<close>\nlocale group =\n  monoid G \"(\\<cdot>)\" \\<one> for G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes invertible [simp, intro]: \"u \\<in> G \\<Longrightarrow> invertible u\"\n\ntext \\<open>p 31, ll 11--12\\<close>\nlocale subgroup = submonoid G M \"(\\<cdot>)\" \\<one> + sub: group G \"(\\<cdot>)\" \\<one>\n  for G and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\nbegin\n\ntext \\<open>Reasoning about @{term invertible} and @{term inverse} in subgroups.\\<close>\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma subgroup_inverse_equality [simp]:\n  \"u \\<in> G \\<Longrightarrow> inverse u = sub.inverse u\"\n  by (simp add: inverse_equality)\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma subgroup_inverse_iff [simp]:\n  \"\\<lbrakk> invertible x; x \\<in> M \\<rbrakk> \\<Longrightarrow> inverse x \\<in> G \\<longleftrightarrow> x \\<in> G\"\n  using invertible_inverse_inverse sub.invertible_inverse_closed by fastforce\n\nend (* subgroup *)\n\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma subgroup_transitive [trans]:\n  assumes \"subgroup K H composition unit\"\n    and \"subgroup H G composition unit\"\n  shows \"subgroup K G composition unit\"\nproof -\n  interpret K: subgroup K H composition unit by fact\n  interpret H: subgroup H G composition unit by fact\n  show ?thesis by unfold_locales auto\nqed\n\ncontext monoid begin\n\ntext \\<open>Jacobson states both directions, but the other one is trivial.\\<close>\ntext \\<open>p 31, ll 12--15\\<close>\ntheorem subgroupI:\n  fixes G\n  assumes subset [THEN subsetD, intro]: \"G \\<subseteq> M\"\n    and [intro]: \"\\<one> \\<in> G\"\n    and [intro]: \"\\<And>g h. \\<lbrakk> g \\<in> G; h \\<in> G \\<rbrakk> \\<Longrightarrow> g \\<cdot> h \\<in> G\"\n    and [intro]: \"\\<And>g. g \\<in> G \\<Longrightarrow> invertible g\"\n    and [intro]: \"\\<And>g. g \\<in> G \\<Longrightarrow> inverse g \\<in> G\"\n  shows \"subgroup G M (\\<cdot>) \\<one>\"\nproof -\n  interpret sub: monoid G \"(\\<cdot>)\" \\<one> by unfold_locales auto\n  show ?thesis\n  proof unfold_locales\n    fix u assume [intro]: \"u \\<in> G\" show \"sub.invertible u\"\n    using invertible_left_inverse invertible_right_inverse by blast\n  qed auto\nqed\n\ntext \\<open>p 31, l 16\\<close>\ndefinition \"Units = {u \\<in> M. invertible u}\"\n\ntext \\<open>p 31, l 16\\<close>\n\n\ntext \\<open>p 31, l 16\\<close>\nlemma mem_UnitsD:\n  \"\\<lbrakk> u \\<in> Units \\<rbrakk> \\<Longrightarrow> invertible u \\<and> u \\<in> M\"\n  unfolding Units_def by clarify\n\ntext \\<open>p 31, ll 16--21\\<close>\ninterpretation units: subgroup Units M\nproof (rule subgroupI)\n  fix u1 u2\n  assume Units [THEN mem_UnitsD, simp]: \"u1 \\<in> Units\" \"u2 \\<in> Units\"\n  have \"(u1 \\<cdot> u2) \\<cdot> (inverse u2 \\<cdot> inverse u1) = (u1 \\<cdot> (u2 \\<cdot> inverse u2)) \\<cdot> inverse u1\"\n    by (simp add: associative del: invertible_left_inverse invertible_right_inverse)\n  also have \"\\<dots> = \\<one>\" by simp\n  finally have inv1: \"(u1 \\<cdot> u2) \\<cdot> (inverse u2 \\<cdot> inverse u1) = \\<one>\" by simp  \\<comment> \\<open>ll 16--18\\<close>\n  have \"(inverse u2 \\<cdot> inverse u1) \\<cdot> (u1 \\<cdot> u2) = (inverse u2 \\<cdot> (inverse u1 \\<cdot> u1)) \\<cdot> u2\"\n    by (simp add: associative del: invertible_left_inverse invertible_right_inverse)\n  also have \"\\<dots> = \\<one>\" by simp\n  finally have inv2: \"(inverse u2 \\<cdot> inverse u1) \\<cdot> (u1 \\<cdot> u2) = \\<one>\" by simp  \\<comment> \\<open>l 9, “and similarly”\\<close>\n  show \"u1 \\<cdot> u2 \\<in> Units\" using inv1 inv2 invertibleI mem_UnitsI by auto\nqed (auto simp: Units_def)\n\ntext \\<open>p 31, ll 21--22\\<close>\ntheorem group_of_Units [intro, simp]:\n  \"group Units (\\<cdot>) \\<one>\"\n  ..\n\ntext \\<open>p 31, l 19\\<close>\nlemma composition_invertible [simp, intro]:\n  \"\\<lbrakk> invertible x; invertible y; x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> invertible (x \\<cdot> y)\"\n  using mem_UnitsD mem_UnitsI by blast\n\ntext \\<open>p 31, l 20\\<close>\nlemma unit_invertible:\n  \"invertible \\<one>\"\n  by fast\n\ntext \\<open>Useful simplification rules\\<close>\ntext \\<open>p 31, l 22\\<close>\nlemma invertible_right_inverse2:\n  \"\\<lbrakk> invertible u; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> u \\<cdot> (inverse u \\<cdot> v) = v\"\n  by (simp add: associative [THEN sym])\n\ntext \\<open>p 31, l 22\\<close>\nlemma invertible_left_inverse2:\n  \"\\<lbrakk> invertible u; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u \\<cdot> (u \\<cdot> v) = v\"\n  by (simp add: associative [THEN sym])\n\ntext \\<open>p 31, l 22\\<close>\nlemma inverse_composition_commute:\n  assumes [simp]: \"invertible x\" \"invertible y\" \"x \\<in> M\" \"y \\<in> M\"\n  shows \"inverse (x \\<cdot> y) = inverse y \\<cdot> inverse x\"\nproof -\n  have \"inverse (x \\<cdot> y) \\<cdot> (x \\<cdot> y) = (inverse y \\<cdot> inverse x) \\<cdot> (x \\<cdot> y)\"\n  by (simp add: invertible_left_inverse2 associative)\n  then show ?thesis by (simp del: invertible_left_inverse)\nqed\n\nend (* monoid *)\n\ntext \\<open>p 31, l 24\\<close>\ncontext transformations begin\n\ntext \\<open>p 31, ll 25--26\\<close>\ntheorem invertible_is_bijective:\n  assumes dom: \"\\<alpha> \\<in> S \\<rightarrow>\\<^sub>E S\"\n  shows \"invertible \\<alpha> \\<longleftrightarrow> bij_betw \\<alpha> S S\"\nproof -\n  from dom interpret map \\<alpha> S S by unfold_locales\n  show ?thesis by (auto simp add: bij_betw_iff_has_inverse invertible_def)\nqed\n\ntext \\<open>p 31, ll 26--27\\<close>\ntheorem Units_bijective:\n  \"Units = {\\<alpha> \\<in> S \\<rightarrow>\\<^sub>E S. bij_betw \\<alpha> S S}\"\n  unfolding Units_def by (auto simp add: invertible_is_bijective)\n\ntext \\<open>p 31, ll 26--27\\<close>\nlemma Units_bij_betwI [intro, simp]:\n  \"\\<alpha> \\<in> Units \\<Longrightarrow> bij_betw \\<alpha> S S\"\n  by (simp add: Units_bijective)\n\ntext \\<open>p 31, ll 26--27\\<close>\nlemma Units_bij_betwD [dest, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> S \\<rightarrow>\\<^sub>E S; bij_betw \\<alpha> S S \\<rbrakk> \\<Longrightarrow> \\<alpha> \\<in> Units\"\n  unfolding Units_bijective by simp\n\ntext \\<open>p 31, ll 28--29\\<close>\nabbreviation \"Sym \\<equiv> Units\"\n\ntext \\<open>p 31, ll 26--28\\<close>\nsublocale symmetric: group \"Sym\" \"compose S\" \"identity S\"\n  by (fact group_of_Units)\n\nend (* transformations *)\n\ntext \\<open>p 32, ll 18--19\\<close>\nlocale transformation_group =\n  transformations S + symmetric: subgroup G Sym \"compose S\" \"identity S\" for G and S\nbegin\n\ntext \\<open>p 32, ll 18--19\\<close>\nlemma transformation_group_closed [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> G; x \\<in> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x \\<in> S\"\n  using bij_betwE by blast\n\ntext \\<open>p 32, ll 18--19\\<close>\nlemma transformation_group_undefined [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> G; x \\<notin> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x = undefined\"\n  by (metis compose_def symmetric.sub.right_unit restrict_apply)\n\nend (* transformation_group *)\n\n\nsubsection \\<open>Isomorphisms.  Cayley's Theorem\\<close>\n\ntext \\<open>Def 1.3\\<close>\ntext \\<open>p 37, ll 7--11\\<close>\nlocale monoid_isomorphism =\n  bijective_map \\<eta> M M' +  source: monoid M \"(\\<cdot>)\" \\<one> + target: monoid M' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and M' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\") +\n  assumes commutes_with_composition: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> x \\<cdot>' \\<eta> y = \\<eta> (x \\<cdot> y)\"\n    and commutes_with_unit: \"\\<eta> \\<one> = \\<one>'\"\n\ntext \\<open>p 37, l 10\\<close>\ndefinition isomorphic_as_monoids (infixl \"\\<cong>\\<^sub>M\" 50)\n  where \"\\<M> \\<cong>\\<^sub>M \\<M>' \\<longleftrightarrow> (let (M, composition, unit) = \\<M>; (M', composition', unit') = \\<M>' in\n  (\\<exists>\\<eta>. monoid_isomorphism \\<eta> M composition unit M' composition' unit'))\"\n\ntext \\<open>p 37, ll 11--12\\<close>\nlocale monoid_isomorphism' =\n  bijective_map \\<eta> M M' +  source: monoid M \"(\\<cdot>)\" \\<one> + target: monoid M' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and M' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\") +\n  assumes commutes_with_composition: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> x \\<cdot>' \\<eta> y = \\<eta> (x \\<cdot> y)\"\n\ntext \\<open>p 37, ll 11--12\\<close>\nsublocale monoid_isomorphism \\<subseteq> monoid_isomorphism'\n  by unfold_locales (simp add: commutes_with_composition)\n\ntext \\<open>Both definitions are equivalent.\\<close>\ntext \\<open>p 37, ll 12--15\\<close>\nsublocale monoid_isomorphism' \\<subseteq> monoid_isomorphism\nproof unfold_locales\n  {\n    fix y assume \"y \\<in> M'\"\n    then obtain x where \"\\<eta> x = y\" \"x \\<in> M\" by (metis image_iff surjective)\n    then have \"y \\<cdot>' \\<eta> \\<one> = y\" using commutes_with_composition by auto\n  }\n  then show \"\\<eta> \\<one> = \\<one>'\" by fastforce\nqed (simp add: commutes_with_composition)\n\ncontext monoid_isomorphism begin\n\ntext \\<open>p 37, ll 30--33\\<close>\n\n\nend (* monoid_isomorphism *)\n\ntext \\<open>We only need that @{term \\<eta>} is symmetric.\\<close>\ntext \\<open>p 37, ll 28--29\\<close>\ntheorem isomorphic_as_monoids_symmetric:\n  \"(M, composition, unit) \\<cong>\\<^sub>M (M', composition', unit') \\<Longrightarrow> (M', composition', unit') \\<cong>\\<^sub>M (M, composition, unit)\"\n  by (simp add: isomorphic_as_monoids_def) (meson monoid_isomorphism.inverse_monoid_isomorphism)\n\ntext \\<open>p 38, l 4\\<close>\nlocale left_translations_of_monoid = monoid begin\n\n(*\n  We take the liberty of omitting \"left_\" from the name of the translation operation.  The derived\n  transformation monoid and group won't be qualified with \"left\" either.  This avoids qualifications\n  such as \"left.left_...\".  In contexts where left and right translations are used simultaneously,\n  notably subgroup_of_group, qualifiers are needed.\n*)\n\ntext \\<open>p 38, ll 5--7\\<close>\ndefinition translation (\"'(_')\\<^sub>L\") where \"translation = (\\<lambda>a \\<in> M. \\<lambda>x \\<in> M. a \\<cdot> x)\"\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemma translation_map [intro, simp]:\n  \"a \\<in> M \\<Longrightarrow> (a)\\<^sub>L \\<in> M \\<rightarrow>\\<^sub>E M\"\n  unfolding translation_def by simp\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemma Translations_maps [intro, simp]:\n  \"translation ` M \\<subseteq> M \\<rightarrow>\\<^sub>E M\"\n  by (simp add: image_subsetI)\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemma translation_apply:\n  \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> (a)\\<^sub>L b = a \\<cdot> b\"\n  unfolding translation_def by auto\n\ntext \\<open>p 38, ll 5--7\\<close>\n\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemmas Translations_E [elim] = translation_exist [THEN bexE]\n\ntext \\<open>p 38, l 10\\<close>\ntheorem translation_unit_eq [simp]:\n  \"identity M = (\\<one>)\\<^sub>L\"\n  unfolding translation_def by auto\n\ntext \\<open>p 38, ll 10--11\\<close>\ntheorem translation_composition_eq [simp]:\n  assumes [simp]: \"a \\<in> M\" \"b \\<in> M\"\n  shows \"compose M (a)\\<^sub>L (b)\\<^sub>L = (a \\<cdot> b)\\<^sub>L\"\n  unfolding translation_def by rule (simp add: associative compose_def)\n\n(* Activate @{locale monoid} to simplify subsequent proof. *)\ntext \\<open>p 38, ll 7--9\\<close>\nsublocale transformation: transformations M .\n\ntext \\<open>p 38, ll 7--9\\<close>\ntheorem Translations_transformation_monoid:\n  \"transformation_monoid (translation ` M) M\"\n  by unfold_locales auto\n\ntext \\<open>p 38, ll 7--9\\<close>\nsublocale transformation: transformation_monoid \"translation ` M\" M\n  by (fact Translations_transformation_monoid)\n\ntext \\<open>p 38, l 12\\<close>\nsublocale map translation M \"translation ` M\"\n  by unfold_locales (simp add: translation_def)\n\ntext \\<open>p 38, ll 12--16\\<close>\ntheorem translation_isomorphism [intro]:\n  \"monoid_isomorphism translation M (\\<cdot>) \\<one> (translation ` M) (compose M) (identity M)\"\nproof unfold_locales\n  have \"inj_on translation M\"\n  proof (rule inj_onI)\n    fix a b\n    assume [simp]: \"a \\<in> M\" \"b \\<in> M\" \"(a)\\<^sub>L = (b)\\<^sub>L\"\n    have \"(a)\\<^sub>L \\<one> = (b)\\<^sub>L \\<one>\" by simp\n    then show \"a = b\" by (simp add: translation_def)\n  qed\n  then show \"bij_betw translation M (translation ` M)\"\n    by (simp add: inj_on_imp_bij_betw)\nqed simp_all\n\ntext \\<open>p 38, ll 12--16\\<close>\nsublocale monoid_isomorphism translation M \"(\\<cdot>)\" \\<one> \"translation ` M\" \"compose M\" \"identity M\" ..\n\nend (* left_translations_of_monoid *)\n\ncontext monoid begin\n\ntext \\<open>p 38, ll 1--2\\<close>\ninterpretation left_translations_of_monoid ..\n\ntext \\<open>p 38, ll 1--2\\<close>\ntheorem cayley_monoid:\n  \"\\<exists>M' composition' unit'. transformation_monoid M' M \\<and> (M, (\\<cdot>), \\<one>) \\<cong>\\<^sub>M (M', composition', unit')\"\n  by (simp add: isomorphic_as_monoids_def) (fast intro: Translations_transformation_monoid)\n\nend (* monoid *)\n\ntext \\<open>p 38, l 17\\<close>\nlocale left_translations_of_group = group begin\n\ntext \\<open>p 38, ll 17--18\\<close>\nsublocale left_translations_of_monoid where M = G ..\n\ntext \\<open>p 38, ll 17--18\\<close>\nnotation translation (\"'(_')\\<^sub>L\")\n\ntext \\<open>\n  The group of left translations is a subgroup of the symmetric group,\n  hence @{term transformation.sub.invertible}.\n\\<close>\ntext \\<open>p 38, ll 20--22\\<close>\ntheorem translation_invertible [intro, simp]:\n  assumes [simp]: \"a \\<in> G\"\n  shows \"transformation.sub.invertible (a)\\<^sub>L\"\nproof\n  show \"compose G (a)\\<^sub>L (inverse a)\\<^sub>L = identity G\" by simp\nnext\n  show \"compose G (inverse a)\\<^sub>L (a)\\<^sub>L = identity G\" by simp\nqed auto\n\ntext \\<open>p 38, ll 19--20\\<close>\ntheorem translation_bijective [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> bij_betw (a)\\<^sub>L G G\"\n  by (blast intro: transformation.invertible_is_bijective [THEN iffD1])\n\ntext \\<open>p 38, ll 18--20\\<close>\ntheorem Translations_transformation_group:\n  \"transformation_group (translation ` G) G\"\nproof unfold_locales\n  show \"(translation ` G) \\<subseteq> transformation.Sym\"\n    unfolding transformation.Units_bijective by auto\nnext\n  fix \\<alpha>\n  assume \\<alpha>: \"\\<alpha> \\<in> translation ` G\"\n  then obtain a where a: \"a \\<in> G\" and eq: \"\\<alpha> = (a)\\<^sub>L\" ..\n  with translation_invertible show \"transformation.sub.invertible \\<alpha>\" by simp\nqed auto\n\ntext \\<open>p 38, ll 18--20\\<close>\nsublocale transformation: transformation_group \"translation ` G\" G\n  by (fact Translations_transformation_group)\n\nend (* left_translations_of_group *)\n\ncontext group begin\n\ntext \\<open>p 38, ll 2--3\\<close>\ninterpretation left_translations_of_group ..\n\ntext \\<open>p 38, ll 2--3\\<close>\ntheorem cayley_group:\n  \"\\<exists>G' composition' unit'. transformation_group G' G \\<and> (G, (\\<cdot>), \\<one>) \\<cong>\\<^sub>M (G', composition', unit')\"\n  by (simp add: isomorphic_as_monoids_def) (fast intro: Translations_transformation_group)\n\nend (* group *)\n\ntext \\<open>Exercise 3\\<close>\n\ntext \\<open>p 39, ll 9--10\\<close>\nlocale right_translations_of_group = group begin\n\ntext \\<open>p 39, ll 9--10\\<close>\ndefinition translation (\"'(_')\\<^sub>R\") where \"translation = (\\<lambda>a \\<in> G. \\<lambda>x \\<in> G. x \\<cdot> a)\"\n\ntext \\<open>p 39, ll 9--10\\<close>\nabbreviation \"Translations \\<equiv> translation ` G\"\n\ntext \\<open>The isomorphism that will be established is a map different from @{term translation}.\\<close>\ntext \\<open>p 39, ll 9--10\\<close>\ninterpretation aux: map translation G Translations\n  by unfold_locales (simp add: translation_def)\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_map [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> (a)\\<^sub>R \\<in> G \\<rightarrow>\\<^sub>E G\"\n  unfolding translation_def by simp\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma Translation_maps [intro, simp]:\n  \"Translations \\<subseteq> G \\<rightarrow>\\<^sub>E G\"\n  by (simp add: image_subsetI)\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_apply:\n  \"\\<lbrakk> a \\<in> G; b \\<in> G \\<rbrakk> \\<Longrightarrow> (a)\\<^sub>R b = b \\<cdot> a\"\n  unfolding translation_def by auto\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_exist:\n  \"f \\<in> Translations \\<Longrightarrow> \\<exists>a \\<in> G. f = (a)\\<^sub>R\"\n  by auto\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemmas Translations_E [elim] = translation_exist [THEN bexE]\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_unit_eq [simp]:\n  \"identity G = (\\<one>)\\<^sub>R\"\n  unfolding translation_def by auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_composition_eq [simp]:\n  assumes [simp]: \"a \\<in> G\" \"b \\<in> G\"\n  shows \"compose G (a)\\<^sub>R (b)\\<^sub>R = (b \\<cdot> a)\\<^sub>R\"\n  unfolding translation_def by rule (simp add: associative compose_def)\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale transformation: transformations G .\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma Translations_transformation_monoid:\n  \"transformation_monoid Translations G\"\n  by unfold_locales auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale transformation: transformation_monoid Translations G\n  by (fact Translations_transformation_monoid)\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_invertible [intro, simp]:\n  assumes [simp]: \"a \\<in> G\"\n  shows \"transformation.sub.invertible (a)\\<^sub>R\"\nproof\n  show \"compose G (a)\\<^sub>R (inverse a)\\<^sub>R = identity G\" by simp\nnext\n  show \"compose G (inverse a)\\<^sub>R (a)\\<^sub>R = identity G\" by simp\nqed auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_bijective [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> bij_betw (a)\\<^sub>R G G\"\n  by (blast intro: transformation.invertible_is_bijective [THEN iffD1])\n\ntext \\<open>p 39, ll 10--11\\<close>\ntheorem Translations_transformation_group:\n  \"transformation_group Translations G\"\nproof unfold_locales\n  show \"Translations \\<subseteq> transformation.Sym\"\n  unfolding transformation.Units_bijective by auto\nnext\n  fix \\<alpha>\n  assume \\<alpha>: \"\\<alpha> \\<in> Translations\"\n  then obtain a where a: \"a \\<in> G\" and eq: \"\\<alpha> = (a)\\<^sub>R\" ..\n  with translation_invertible show \"transformation.sub.invertible \\<alpha>\" by simp\nqed auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale transformation: transformation_group Translations G\n  by (rule Translations_transformation_group)\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_inverse_eq [simp]:\n  assumes [simp]: \"a \\<in> G\"\n  shows \"transformation.sub.inverse (a)\\<^sub>R = (inverse a)\\<^sub>R\"\nproof (rule transformation.sub.inverse_equality)\n  show \"compose G (a)\\<^sub>R (inverse a)\\<^sub>R = identity G\" by simp\nnext\n  show \"compose G (inverse a)\\<^sub>R (a)\\<^sub>R = identity G\" by simp\nqed auto\n\ntext \\<open>p 39, ll 10--11\\<close>\ntheorem translation_inverse_monoid_isomorphism [intro]:\n  \"monoid_isomorphism (\\<lambda>a\\<in>G. transformation.symmetric.inverse (a)\\<^sub>R) G (\\<cdot>) \\<one> Translations (compose G) (identity G)\"\n  (is \"monoid_isomorphism ?inv _ _ _ _ _ _\")\nproof unfold_locales\n  show \"?inv \\<in> G \\<rightarrow>\\<^sub>E Translations\" by (simp del: translation_unit_eq)\nnext\n  note bij_betw_compose [trans]\n  have \"bij_betw inverse G G\"\n    by (rule bij_betwI [where g = inverse]) auto\n  also have \"bij_betw translation G Translations\"\n    by (rule bij_betwI [where g = \"\\<lambda>\\<alpha>\\<in>Translations. \\<alpha> \\<one>\"]) (auto simp: translation_apply)\n  finally show \"bij_betw ?inv G Translations\"\n    by (simp cong: bij_betw_cong add: compose_eq del: translation_unit_eq)\nnext\n  fix x and y\n  assume [simp]: \"x \\<in> G\" \"y \\<in> G\"\n  show \"compose G (?inv x) (?inv y) = (?inv (x \\<cdot> y))\" by (simp add: inverse_composition_commute del: translation_unit_eq)\nnext\n  show \"?inv \\<one> = identity G\" by (simp del: translation_unit_eq) simp\nqed\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale monoid_isomorphism\n  \"\\<lambda>a\\<in>G. transformation.symmetric.inverse (a)\\<^sub>R\" G \"(\\<cdot>)\" \\<one> Translations \"compose G\" \"identity G\" ..\n\nend (* right_translations_of_group *)\n\n\nsubsection \\<open>Generalized Associativity.  Commutativity\\<close>\n\ntext \\<open>p 40, l 27; p 41, ll 1--2\\<close>\nlocale commutative_monoid = monoid +\n  assumes commutative: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> x \\<cdot> y = y \\<cdot> x\"\n  \ntext \\<open>p 41, l 2\\<close>\nlocale abelian_group = group + commutative_monoid G \"(\\<cdot>)\" \\<one>\n\n\nsubsection \\<open>Orbits.  Cosets of a Subgroup\\<close>\n\ncontext transformation_group begin\n\ntext \\<open>p 51, ll 18--20\\<close>\ndefinition Orbit_Relation\n  where \"Orbit_Relation = {(x, y). x \\<in> S \\<and> y \\<in> S \\<and> (\\<exists>\\<alpha> \\<in> G. y = \\<alpha> x)}\"\n\ntext \\<open>p 51, ll 18--20\\<close>\nlemma Orbit_Relation_memI [intro]:\n  \"\\<lbrakk> \\<exists>\\<alpha> \\<in> G. y = \\<alpha> x; x \\<in> S \\<rbrakk> \\<Longrightarrow> (x, y) \\<in> Orbit_Relation\"\n  unfolding Orbit_Relation_def by auto\n\ntext \\<open>p 51, ll 18--20\\<close>\nlemma Orbit_Relation_memE [elim]:\n  \"\\<lbrakk> (x, y) \\<in> Orbit_Relation; \\<And>\\<alpha>. \\<lbrakk> \\<alpha> \\<in> G; x \\<in> S; y = \\<alpha> x \\<rbrakk> \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> Q\"\n  unfolding Orbit_Relation_def by auto\n\ntext \\<open>p 51, ll 20--23, 26--27\\<close>\nsublocale orbit: equivalence S Orbit_Relation\nproof (unfold_locales, auto simp: Orbit_Relation_def)\n  fix x\n  assume x: \"x \\<in> S\"\n  then have id: \"x = identity S x\" by simp\n  with x show \"\\<exists>\\<alpha> \\<in> G. x = \\<alpha> x\" by fast\n  fix \\<alpha>\n  assume \\<alpha>: \"\\<alpha> \\<in> G\"\n  with x id have y: \"x = compose S (symmetric.inverse \\<alpha>) \\<alpha> x\" by auto\n  with x \\<alpha> show \"\\<exists>\\<alpha>' \\<in> G. x = \\<alpha>' (\\<alpha> x)\"\n    by (metis compose_eq symmetric.sub.invertible symmetric.submonoid_inverse_closed)\n  fix \\<beta>\n  assume \\<beta>: \"\\<beta> \\<in> G\"\n  with x have \"\\<beta> (\\<alpha> x) = compose S \\<beta> \\<alpha> x\" by (simp add: compose_eq)\n  with \\<alpha> \\<beta> show \"\\<exists>\\<gamma> \\<in> G. \\<beta> (\\<alpha> x) = \\<gamma> x\" by fast\nqed\n\ntext \\<open>p 51, ll 23--24\\<close>\ntheorem orbit_equality:\n  \"x \\<in> S \\<Longrightarrow> orbit.Class x = {\\<alpha> x | \\<alpha>. \\<alpha> \\<in> G}\"\nby (simp add: orbit.Class_def) (blast intro: orbit.symmetric dest: orbit.symmetric)\n\nend (* transformation_group *)\n\ncontext monoid_isomorphism begin\n\ntext \\<open>p 52, ll 16--17\\<close>\ntheorem image_subgroup:\n  assumes \"subgroup G M (\\<cdot>) \\<one>\"\n  shows \"subgroup (\\<eta> ` G) M' (\\<cdot>') \\<one>'\"\nproof -\n  interpret subgroup G M \"(\\<cdot>)\" \\<one> by fact\n  interpret image: monoid \"\\<eta> ` G\" \"(\\<cdot>')\" \"\\<one>'\"\n    by unfold_locales (auto simp add: commutes_with_composition commutes_with_unit [symmetric])\n  show ?thesis\n  proof (unfold_locales, auto)\n    fix x\n    assume x: \"x \\<in> G\"\n    show \"image.invertible (\\<eta> x)\"\n    proof\n      show \"\\<eta> (sub.inverse x) \\<in> \\<eta> ` G\" using x by simp\n    qed (auto simp: x commutes_with_composition commutes_with_unit)\n  qed\nqed\n\nend (* monoid_isomorphism *)\n\ntext \\<open>\n  Technical device to achieve Jacobson's notation for @{text Right_Coset} and @{text Left_Coset}.  The\n  definitions are pulled out of @{text subgroup_of_group} to a context where @{text H} is not a parameter.\n\\<close>\ntext \\<open>p 52, l 20\\<close>\nlocale coset_notation = fixes composition (infixl \"\\<cdot>\" 70)  begin\n\ntext \\<open>Equation 23\\<close>\ntext \\<open>p 52, l 20\\<close>\ndefinition Right_Coset (infixl \"|\\<cdot>\" 70) where \"H |\\<cdot> x = {h \\<cdot> x | h. h \\<in> H}\"\n\ntext \\<open>p 53, ll 8--9\\<close>\ndefinition Left_Coset (infixl \"\\<cdot>|\" 70) where \"x \\<cdot>| H = {x \\<cdot> h | h. h \\<in> H}\"\n\ntext \\<open>p 52, l 20\\<close>\nlemma Right_Coset_memI [intro]:\n  \"h \\<in> H \\<Longrightarrow> h \\<cdot> x \\<in> H |\\<cdot> x\"\n  unfolding Right_Coset_def by blast\n\ntext \\<open>p 52, l 20\\<close>\nlemma Right_Coset_memE [elim]:\n  \"\\<lbrakk> a \\<in> H |\\<cdot> x; \\<And>h. \\<lbrakk> h \\<in> H; a = h \\<cdot> x \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  unfolding Right_Coset_def by blast\n\ntext \\<open>p 53, ll 8--9\\<close>\nlemma Left_Coset_memI [intro]:\n  \"h \\<in> H \\<Longrightarrow> x \\<cdot> h \\<in> x \\<cdot>| H\"\n  unfolding Left_Coset_def by blast\n\ntext \\<open>p 53, ll 8--9\\<close>\nlemma Left_Coset_memE [elim]:\n  \"\\<lbrakk> a \\<in> x \\<cdot>| H; \\<And>h. \\<lbrakk> h \\<in> H; a = x \\<cdot> h \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  unfolding Left_Coset_def by blast\n\nend (* coset_notation *)\n\ntext \\<open>p 52, l 12\\<close>\nlocale subgroup_of_group = subgroup H G \"(\\<cdot>)\" \\<one> + coset_notation \"(\\<cdot>)\" + group G \"(\\<cdot>)\" \\<one>\n  for H and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\nbegin\n\ntext \\<open>p 52, ll 12--14\\<close>\ninterpretation left: left_translations_of_group ..\ninterpretation right: right_translations_of_group ..\n\ntext \\<open>\n  @{term \"left.translation ` H\"} denotes Jacobson's @{text \"H\\<^sub>L(G)\"} and\n  @{term \"left.translation ` G\"} denotes Jacobson's @{text \"G\\<^sub>L\"}.\n\\<close>\n\ntext \\<open>p 52, ll 16--18\\<close>\ntheorem left_translations_of_subgroup_are_transformation_group [intro]:\n  \"transformation_group (left.translation ` H) G\"\nproof -\n  have \"subgroup (left.translation ` H) (left.translation ` G) (compose G) (identity G)\"\n    by (rule left.image_subgroup) unfold_locales\n  also have \"subgroup (left.translation ` G) left.transformation.Sym (compose G) (identity G)\" ..\n  finally interpret right_coset: subgroup \"left.translation ` H\" left.transformation.Sym \"compose G\" \"identity G\" .\n  show ?thesis ..\nqed\n\ntext \\<open>p 52, l 18\\<close>\ninterpretation transformation_group \"left.translation ` H\" G ..\n\ntext \\<open>p 52, ll 19--20\\<close>\ntheorem Right_Coset_is_orbit:\n  \"x \\<in> G \\<Longrightarrow> H |\\<cdot> x = orbit.Class x\"\n  using left.translation_apply by (auto simp: orbit_equality Right_Coset_def) (metis imageI sub)\n\ntext \\<open>p 52, ll 24--25\\<close>\ntheorem Right_Coset_Union:\n  \"(\\<Union>x\\<in>G. H |\\<cdot> x) = G\"\n  by (simp add: Right_Coset_is_orbit)\n\ntext \\<open>p 52, l 26\\<close>\ntheorem Right_Coset_bij:\n  assumes G [simp]: \"x \\<in> G\" \"y \\<in> G\"\n  shows \"bij_betw (inverse x \\<cdot> y)\\<^sub>R (H |\\<cdot> x) (H |\\<cdot> y)\"\nproof (rule bij_betw_imageI)\n  show \"inj_on (inverse x \\<cdot> y)\\<^sub>R (H |\\<cdot> x)\"\n    by (fastforce intro: inj_onI simp add: Right_Coset_is_orbit right.translation_apply orbit.block_closed)\nnext\n  show \"(inverse x \\<cdot> y)\\<^sub>R ` (H |\\<cdot> x) = H |\\<cdot> y\"\n    by (force simp add: right.translation_apply associative invertible_right_inverse2)\nqed\n\ntext \\<open>p 52, ll 25--26\\<close>\ntheorem Right_Cosets_cardinality:\n  \"\\<lbrakk> x \\<in> G; y \\<in> G \\<rbrakk> \\<Longrightarrow> card (H |\\<cdot> x) = card (H |\\<cdot> y)\"\n  by (fast intro: bij_betw_same_card Right_Coset_bij)\n\ntext \\<open>p 52, l 27\\<close>\ntheorem Right_Coset_unit:\n  \"H |\\<cdot> \\<one> = H\"\n  by (force simp add: Right_Coset_def)\n\ntext \\<open>p 52, l 27\\<close>\ntheorem Right_Coset_cardinality:\n  \"x \\<in> G \\<Longrightarrow> card (H |\\<cdot> x) = card H\"\n  using Right_Coset_unit Right_Cosets_cardinality unit_closed by presburger\n\ntext \\<open>p 52, ll 31--32\\<close>\ndefinition \"index = card orbit.Partition\"\n\ntext \\<open>Theorem 1.5\\<close>\ntext \\<open>p 52, ll 33--35; p 53, ll 1--2\\<close>\ntheorem lagrange:\n  \"finite G \\<Longrightarrow> card G = card H * index\"\n  unfolding index_def\n  apply (subst card_partition)\n      apply (auto simp: finite_UnionD orbit.complete orbit.disjoint)\n  apply (metis Right_Coset_cardinality Right_Coset_is_orbit orbit.Block_self orbit.element_exists)\n  done\n\nend (* subgroup_of_group *)\n\ntext \\<open>Left cosets\\<close>\n\ncontext subgroup begin\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma image_of_inverse [intro, simp]:\n  \"x \\<in> G \\<Longrightarrow> x \\<in> inverse ` G\"\n  by (metis image_eqI sub.invertible sub.invertible_inverse_closed sub.invertible_inverse_inverse subgroup_inverse_equality)\n\nend (* subgroup *)\n\ncontext group begin\n\n(* Does Jacobson show this somewhere? *)\ntext \\<open>p 53, ll 6--7\\<close>\nlemma inverse_subgroupI:\n  assumes sub: \"subgroup H G (\\<cdot>) \\<one>\"\n  shows \"subgroup (inverse ` H) G (\\<cdot>) \\<one>\"\nproof -\n  from sub interpret subgroup H G \"(\\<cdot>)\" \\<one> .\n  interpret inv: monoid \"inverse ` H\" \"(\\<cdot>)\" \\<one>\n    by unfold_locales (auto simp del: subgroup_inverse_equality)\n  interpret inv: group \"inverse ` H\" \"(\\<cdot>)\" \\<one>\n    by unfold_locales (force simp del: subgroup_inverse_equality)\n  show ?thesis\n    by unfold_locales (auto simp del: subgroup_inverse_equality)\nqed\n\ntext \\<open>p 53, ll 6--7\\<close>\nlemma inverse_subgroupD:\n  assumes sub: \"subgroup (inverse ` H) G (\\<cdot>) \\<one>\"\n    and inv: \"H \\<subseteq> Units\"\n  shows \"subgroup H G (\\<cdot>) \\<one>\"\nproof -\n  from sub have \"subgroup (inverse ` inverse ` H) G (\\<cdot>) \\<one>\" by (rule inverse_subgroupI)\n  moreover from inv [THEN subsetD, simplified Units_def] have \"inverse ` inverse ` H = H\"\n    by (simp cong: image_cong add: image_comp)\n  ultimately show ?thesis by simp\nqed\n\nend (* group *)\n\ncontext subgroup_of_group begin\n\ntext \\<open>p 53, l 6\\<close>\ninterpretation right_translations_of_group ..\n\ntext \\<open>\n  @{term \"translation ` H\"} denotes Jacobson's @{text \"H\\<^sub>R(G)\"} and\n  @{term \"Translations\"} denotes Jacobson's @{text \"G\\<^sub>R\"}.\n\\<close>\n\ntext \\<open>p 53, ll 6--7\\<close>\ntheorem right_translations_of_subgroup_are_transformation_group [intro]:\n  \"transformation_group (translation ` H) G\"\nproof -\n  have \"subgroup ((\\<lambda>a\\<in>G. transformation.symmetric.inverse (a)\\<^sub>R) ` H) Translations (compose G) (identity G)\"\n    by (rule image_subgroup) unfold_locales\n  also have \"subgroup Translations transformation.Sym (compose G) (identity G)\" ..\n  finally interpret left_coset: subgroup \"translation ` H\" transformation.Sym \"compose G\" \"identity G\"\n    by (auto intro: transformation.symmetric.inverse_subgroupD cong: image_cong\n      simp: image_image transformation.symmetric.Units_def simp del: translation_unit_eq)\n  show ?thesis ..\nqed\n\ntext \\<open>p 53, ll 6--7\\<close>\ninterpretation transformation_group \"translation ` H\" G ..\n\ntext \\<open>Equation 23 for left cosets\\<close>\ntext \\<open>p 53, ll 7--8\\<close>\ntheorem Left_Coset_is_orbit:\n  \"x \\<in> G \\<Longrightarrow> x \\<cdot>| H = orbit.Class x\"\n  using translation_apply\n  by (auto simp: orbit_equality Left_Coset_def) (metis imageI sub)\n\nend (* subgroup_of_group *)\n\n\nsubsection \\<open>Congruences.  Quotient Monoids and Groups\\<close>\n\ntext \\<open>Def 1.4\\<close>\ntext \\<open>p 54, ll 19--22\\<close>\nlocale monoid_congruence = monoid + equivalence where S = M +\n  assumes cong: \"\\<lbrakk> (a, a') \\<in> E; (b, b') \\<in> E \\<rbrakk> \\<Longrightarrow> (a \\<cdot> b, a' \\<cdot> b') \\<in> E\"\nbegin\n\ntext \\<open>p 54, ll 26--28\\<close>\ntheorem Class_cong:\n  \"\\<lbrakk> Class a = Class a'; Class b = Class b'; a \\<in> M; a' \\<in> M; b \\<in> M; b' \\<in> M \\<rbrakk> \\<Longrightarrow> Class (a \\<cdot> b) = Class (a' \\<cdot> b')\"\n  by (simp add: Class_equivalence cong)\n\ntext \\<open>p 54, ll 28--30\\<close>\ndefinition quotient_composition (infixl \"[\\<cdot>]\" 70)\n  where \"quotient_composition = (\\<lambda>A \\<in> M / E. \\<lambda>B \\<in> M / E. THE C. \\<exists>a \\<in> A. \\<exists>b \\<in> B. C = Class (a \\<cdot> b))\"\n\ntext \\<open>p 54, ll 28--30\\<close>\ntheorem Class_commutes_with_composition:\n  \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> Class a [\\<cdot>] Class b = Class (a \\<cdot> b)\"\n  by (auto simp: quotient_composition_def intro: Class_cong [OF Class_eq Class_eq] del: equalityI)\n\ntext \\<open>p 54, ll 30--31\\<close>\ntheorem quotient_composition_closed [intro, simp]:\n  \"\\<lbrakk> A \\<in> M / E; B \\<in> M / E \\<rbrakk> \\<Longrightarrow> A [\\<cdot>] B \\<in> M / E\"\n  by (erule quotient_ClassE)+ (simp add: Class_commutes_with_composition)\n\ntext \\<open>p 54, l 32; p 55, ll 1--3\\<close>\nsublocale quotient: monoid \"M / E\" \"([\\<cdot>])\" \"Class \\<one>\"\n  by unfold_locales (auto simp: Class_commutes_with_composition associative elim!: quotient_ClassE)\n\nend (* monoid_congruence *)\n\ntext \\<open>p 55, ll 16--17\\<close>\nlocale group_congruence = group + monoid_congruence where M = G begin\n\ntext \\<open>p 55, ll 16--17\\<close>\nnotation quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_right_inverse:\n  \"a \\<in> G \\<Longrightarrow> Class a [\\<cdot>] Class (inverse a) = Class \\<one>\"\n  by (simp add: Class_commutes_with_composition)\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_left_inverse:\n  \"a \\<in> G \\<Longrightarrow> Class (inverse a) [\\<cdot>] Class a = Class \\<one>\"\n  by (simp add: Class_commutes_with_composition)\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_invertible:\n  \"a \\<in> G \\<Longrightarrow> quotient.invertible (Class a)\"\n  by (blast intro!: Class_right_inverse Class_left_inverse)+\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_commutes_with_inverse:\n  \"a \\<in> G \\<Longrightarrow> quotient.inverse (Class a) = Class (inverse a)\"\n  by (rule quotient.inverse_equality) (auto simp: Class_right_inverse Class_left_inverse)\n\ntext \\<open>p 55, l 17\\<close>\nsublocale quotient: group \"G / E\" \"([\\<cdot>])\" \"Class \\<one>\"\n  by unfold_locales (metis Block_self Class_invertible element_exists)\n\nend (* group_congruence *)\n\ntext \\<open>Def 1.5\\<close>\ntext \\<open>p 55, ll 22--25\\<close>\nlocale normal_subgroup =\n  subgroup_of_group K G \"(\\<cdot>)\" \\<one> for K and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes normal: \"\\<lbrakk> g \\<in> G; k \\<in> K \\<rbrakk> \\<Longrightarrow> inverse g \\<cdot> k \\<cdot> g \\<in> K\"\n\ntext \\<open>Lemmas from the proof of Thm 1.6\\<close>\n\ncontext subgroup_of_group begin\n\ntext \\<open>We use @{term H} for @{term K}.\\<close>\ntext \\<open>p 56, ll 14--16\\<close>\ntheorem Left_equals_Right_coset_implies_normality:\n  assumes [simp]: \"\\<And>g. g \\<in> G \\<Longrightarrow> g \\<cdot>| H = H |\\<cdot> g\"\n  shows \"normal_subgroup H G (\\<cdot>) \\<one>\"\nproof\n  fix g k\n  assume [simp]: \"g \\<in> G\" \"k \\<in> H\"\n  have \"k \\<cdot> g \\<in> g \\<cdot>| H\" by auto\n  then obtain k' where \"k \\<cdot> g = g \\<cdot> k'\" and \"k' \\<in> H\" by blast\n  then show \"inverse g \\<cdot> k \\<cdot> g \\<in> H\" by (simp add: associative invertible_left_inverse2)\nqed\n\nend (* subgroup_of_group *)\n\ntext \\<open>Thm 1.6, first part\\<close>\n\ncontext group_congruence begin\n\ntext \\<open>Jacobson's $K$\\<close>\ntext \\<open>p 56, l 29\\<close>\ndefinition \"Normal = Class \\<one>\"\n\ntext \\<open>p 56, ll 3--6\\<close>\ninterpretation subgroup \"Normal\" G \"(\\<cdot>)\" \\<one>\n  unfolding Normal_def\nproof (rule subgroupI)\n  fix k1 and k2\n  assume K: \"k1 \\<in> Class \\<one>\" \"k2 \\<in> Class \\<one>\"\n  then have \"k1 \\<cdot> k2 \\<in> Class (k1 \\<cdot> k2)\" by blast\n  also have \"\\<dots> = Class k1 [\\<cdot>] Class k2\" using K by (auto simp add: Class_commutes_with_composition Class_closed)\n  also have \"\\<dots> = Class \\<one> [\\<cdot>] Class \\<one>\" using K by (metis ClassD Class_eq unit_closed)\n  also have \"\\<dots> = Class \\<one>\" by simp\n  finally show \"k1 \\<cdot> k2 \\<in> Class \\<one>\" .\nnext\n  fix k\n  assume K: \"k \\<in> Class \\<one>\"\n  then have \"inverse k \\<in> Class (inverse k)\" by blast\n  also have \"\\<dots> = quotient.inverse (Class k)\" using Class_commutes_with_inverse K by blast\n  also have \"\\<dots> = quotient.inverse (Class \\<one>)\" using Block_self K by auto\n  also have \"\\<dots> = Class \\<one>\" using quotient.inverse_unit by blast\n  finally show \"inverse k \\<in> Class \\<one>\" .\nqed auto\n\ntext \\<open>Coset notation\\<close>\ntext \\<open>p 56, ll 5--6\\<close>\ninterpretation subgroup_of_group \"Normal\" G \"(\\<cdot>)\" \\<one> ..\n\ntext \\<open>Equation 25 for right cosets\\<close>\ntext \\<open>p 55, ll 29--30; p 56, ll 6--11\\<close>\ntheorem Right_Coset_Class_unit:\n  assumes g: \"g \\<in> G\" shows \"Normal |\\<cdot> g = Class g\"\n  unfolding Normal_def\nproof auto\n  fix a  \\<comment> \\<open>ll 6--8\\<close>\n  assume a: \"a \\<in> Class g\"\n  from a g have \"a \\<cdot> inverse g \\<in> Class (a \\<cdot> inverse g)\" by blast\n  also from a g have \"\\<dots> = Class a [\\<cdot>] Class (inverse g)\"\n    by (simp add: Class_commutes_with_composition block_closed)\n  also from a g have \"\\<dots> = Class g [\\<cdot>] quotient.inverse (Class g)\"\n    using Block_self Class_commutes_with_inverse by auto\n  also from g have \"\\<dots> = Class \\<one>\" by simp\n  finally show \"a \\<in> Class \\<one> |\\<cdot> g\"\n    unfolding Right_Coset_def\n    by simp (metis Class_closed a associative g inverse_equality invertible invertible_def right_unit) \nnext\n  fix a  \\<comment> \\<open>ll 8--9\\<close>\n  assume a: \"a \\<in> Class \\<one> |\\<cdot> g\"\n  then obtain k where eq: \"a = k \\<cdot> g\" and k: \"k \\<in> Class \\<one>\" by blast\n  with g have \"Class a = Class k [\\<cdot>] Class g\" using Class_commutes_with_composition by auto\n  also from k have \"\\<dots> = Class \\<one> [\\<cdot>] Class g\" using Block_self by auto\n  also from g have \"\\<dots> = Class g\" by simp\n  finally show \"a \\<in> Class g\" using g eq k composition_closed quotient.unit_closed by blast\nqed\n\ntext \\<open>Equation 25 for left cosets\\<close>\ntext \\<open>p 55, ll 29--30; p 56, ll 6--11\\<close>\ntheorem Left_Coset_Class_unit:\n  assumes g: \"g \\<in> G\" shows \"g \\<cdot>| Normal = Class g\"\n  unfolding Normal_def\nproof auto\n  fix a  \\<comment> \\<open>ll 6--8\\<close>\n  assume a: \"a \\<in> Class g\"\n  from a g have \"inverse g \\<cdot> a \\<in> Class (inverse g \\<cdot> a)\" by blast\n  also from a g have \"\\<dots> = Class (inverse g) [\\<cdot>] Class a\"\n    by (simp add: Class_commutes_with_composition block_closed)\n  also from a g have \"\\<dots> = quotient.inverse (Class g) [\\<cdot>] Class g\"\n    using Block_self Class_commutes_with_inverse by auto\n  also from g have \"\\<dots> = Class \\<one>\" by simp\n  finally show \"a \\<in> g \\<cdot>| Class \\<one>\"\n    unfolding Left_Coset_def\n    by simp (metis Class_closed a associative g inverse_equality invertible invertible_def right_unit) \nnext\n  fix a  \\<comment> \\<open>ll 8--9, ``the same thing holds''\\<close>\n  assume a: \"a \\<in> g \\<cdot>| Class \\<one>\"\n  then obtain k where eq: \"a = g \\<cdot> k\" and k: \"k \\<in> Class \\<one>\" by blast\n  with g have \"Class a = Class g [\\<cdot>] Class k\" using Class_commutes_with_composition by auto\n  also from k have \"\\<dots> = Class g [\\<cdot>] Class \\<one>\" using Block_self by auto\n  also from g have \"\\<dots> = Class g\" by simp\n  finally show \"a \\<in> Class g\" using g eq k composition_closed quotient.unit_closed by blast\nqed\n\ntext \\<open>Thm 1.6, statement of first part\\<close>\ntext \\<open>p 55, ll 28--29; p 56, ll 12--16\\<close>\ntheorem Class_unit_is_normal:\n  \"normal_subgroup Normal G (\\<cdot>) \\<one>\"\nproof -\n  {\n    fix g\n    assume \"g \\<in> G\"\n    then have \"g \\<cdot>| Normal = Normal |\\<cdot> g\" by (simp add: Right_Coset_Class_unit Left_Coset_Class_unit)\n  }\n  then show ?thesis by (rule Left_equals_Right_coset_implies_normality)\nqed\n\nsublocale normal: normal_subgroup Normal G \"(\\<cdot>)\" \\<one>\n  by (fact Class_unit_is_normal)\n\nend (* group_congruence *)\n\ncontext normal_subgroup begin\n\ntext \\<open>p 56, ll 16--19\\<close>\ntheorem Left_equals_Right_coset:\n  \"g \\<in> G \\<Longrightarrow> g \\<cdot>| K = K |\\<cdot> g\"\nproof\n  assume [simp]: \"g \\<in> G\"\n  show \"K |\\<cdot> g \\<subseteq> g \\<cdot>| K\"\n  proof\n    fix x\n    assume x: \"x \\<in> K |\\<cdot> g\"\n    then obtain k where \"x = k \\<cdot> g\" and [simp]: \"k \\<in> K\" by (auto simp add: Right_Coset_def)\n    then have \"x = g \\<cdot> (inverse g \\<cdot> k \\<cdot> g)\" by (simp add: associative invertible_right_inverse2)\n    also from normal have \"\\<dots> \\<in> g \\<cdot>| K\" by (auto simp add: Left_Coset_def)\n    finally show \"x \\<in> g \\<cdot>| K\" .\n  qed\nnext\n  assume [simp]: \"g \\<in> G\"\n  show \"g \\<cdot>| K \\<subseteq> K |\\<cdot> g\"\n  proof\n    fix x\n    assume x: \"x \\<in> g \\<cdot>| K\"\n    then obtain k where \"x = g \\<cdot> k\" and [simp]: \"k \\<in> K\" by (auto simp add: Left_Coset_def)\n    then have \"x = (inverse (inverse g) \\<cdot> k \\<cdot> inverse g) \\<cdot> g\" by (simp add: associative del: invertible_right_inverse)\n    also from normal [where g = \"inverse g\"] have \"\\<dots> \\<in> K |\\<cdot> g\" by (auto simp add: Right_Coset_def)\n    finally show \"x \\<in> K |\\<cdot> g\" .\n  qed\nqed\n\ntext \\<open>Thm 1.6, second part\\<close>\n\ntext \\<open>p 55, ll 31--32; p 56, ll 20--21\\<close>\ndefinition \"Congruence = {(a, b). a \\<in> G \\<and> b \\<in> G \\<and> inverse a \\<cdot> b \\<in> K}\"\n\ntext \\<open>p 56, ll 21--22\\<close>\ninterpretation right_translations_of_group ..\n\ntext \\<open>p 56, ll 21--22\\<close>\ninterpretation transformation_group \"translation ` K\" G rewrites \"Orbit_Relation = Congruence\"\nproof -\n  interpret transformation_group \"translation ` K\" G ..\n  show \"Orbit_Relation = Congruence\"\n    unfolding Orbit_Relation_def Congruence_def\n    by (force simp: invertible_left_inverse2 invertible_right_inverse2 translation_apply simp del: restrict_apply)\nqed rule\n\ntext \\<open>p 56, ll 20--21\\<close>\nlemma CongruenceI: \"\\<lbrakk> a = b \\<cdot> k; a \\<in> G; b \\<in> G; k \\<in> K \\<rbrakk> \\<Longrightarrow> (a, b) \\<in> Congruence\"\n  by (clarsimp simp: Congruence_def associative inverse_composition_commute)\n\ntext \\<open>p 56, ll 20--21\\<close>\nlemma CongruenceD: \"(a, b) \\<in> Congruence \\<Longrightarrow> \\<exists>k\\<in>K. a = b \\<cdot> k\"\n  by (drule orbit.symmetric) (force simp: Congruence_def invertible_right_inverse2)\n\ntext \\<open>\n  ``We showed in the last section that the relation we are considering is an equivalence relation in\n  @{term G} for any subgroup @{term K} of @{term G}.  We now proceed to show that normality of @{term K}\n  ensures that [...] $a \\equiv b \\pmod{K}$ is a congruence.''\n\\<close>\ntext \\<open>p 55, ll 30--32; p 56, ll 1, 22--28\\<close>\nsublocale group_congruence where E = Congruence rewrites \"Normal = K\"\nproof -\n  show \"group_congruence G (\\<cdot>) \\<one> Congruence\"\n  proof unfold_locales\n    note CongruenceI [intro] CongruenceD [dest]\n    fix a g b h\n    assume 1: \"(a, g) \\<in> Congruence\" and 2: \"(b, h) \\<in> Congruence\"\n    then have G: \"a \\<in> G\" \"g \\<in> G\" \"b \\<in> G\" \"h \\<in> G\" unfolding Congruence_def by clarify+\n    from 1 obtain k1 where a: \"a = g \\<cdot> k1\" and k1: \"k1 \\<in> K\" by blast\n    from 2 obtain k2 where b: \"b = h \\<cdot> k2\" and k2: \"k2 \\<in> K\" by blast\n    from G Left_equals_Right_coset have \"K |\\<cdot> h = h \\<cdot>| K\" by blast\n    with k1 obtain k3 where c: \"k1 \\<cdot> h = h \\<cdot> k3\" and k3: \"k3 \\<in> K\"\n      unfolding Left_Coset_def Right_Coset_def by blast\n    from G k1 k2 a b have \"a \\<cdot> b = g \\<cdot> k1 \\<cdot> h \\<cdot> k2\" by (simp add: associative)\n    also from G k1 k3 c have \"\\<dots> = g \\<cdot> h \\<cdot> k3 \\<cdot> k2\" by (simp add: associative)\n    also have \"\\<dots> = (g \\<cdot> h) \\<cdot> (k3 \\<cdot> k2)\" using G k2 k3 by (simp add: associative)\n    finally show \"(a \\<cdot> b, g \\<cdot> h) \\<in> Congruence\" using G k2 k3 by blast\n  qed\n  then interpret group_congruence where E = Congruence .\n  show \"Normal = K\"\n    unfolding Normal_def orbit.Class_def unfolding Congruence_def\n    using invertible_inverse_inverse submonoid_inverse_closed by fastforce \nqed\n\nend (* normal_subgroup *)  (* deletes translations and orbits, recovers Class for congruence class *)\n\ncontext group begin\n\ntext \\<open>Pulled out of @{locale normal_subgroup} to achieve standard notation.\\<close>\ntext \\<open>p 56, ll 31--32\\<close>\nabbreviation Factor_Group (infixl \"'/'/\" 75)\n  where \"S // K \\<equiv> S / (normal_subgroup.Congruence K G (\\<cdot>) \\<one>)\"\n\nend (* group *)\n\ncontext normal_subgroup begin\n\ntext \\<open>p 56, ll 28--29\\<close>\ntheorem Class_unit_normal_subgroup: \"Class \\<one> = K\"\n  unfolding Class_def unfolding Congruence_def\n  using invertible_inverse_inverse submonoid_inverse_closed by fastforce\n\ntext \\<open>p 56, ll 1--2; p 56, l 29\\<close>\ntheorem Class_is_Left_Coset:\n  \"g \\<in> G \\<Longrightarrow> Class g = g \\<cdot>| K\"\n  using Left_Coset_Class_unit Class_unit_normal_subgroup by simp\n\ntext \\<open>p 56, l 29\\<close>\nlemma Left_CosetE: \"\\<lbrakk> A \\<in> G // K; \\<And>a. a \\<in> G \\<Longrightarrow> P (a \\<cdot>| K) \\<rbrakk> \\<Longrightarrow> P A\"\n  by (metis Class_is_Left_Coset quotient_ClassE)\n\ntext \\<open>Equation 26\\<close>\ntext \\<open>p 56, ll 32--34\\<close>\ntheorem factor_composition [simp]:\n  \"\\<lbrakk> g \\<in> G; h \\<in> G \\<rbrakk> \\<Longrightarrow> (g \\<cdot>| K) [\\<cdot>] (h \\<cdot>| K) = g \\<cdot> h \\<cdot>| K\"\n  using Class_commutes_with_composition Class_is_Left_Coset by auto\n\ntext \\<open>p 56, l 35\\<close>\ntheorem factor_unit:\n  \"K = \\<one> \\<cdot>| K\"\n  using Class_is_Left_Coset Class_unit_normal_subgroup by blast\n\ntext \\<open>p 56, l 35\\<close>\ntheorem factor_inverse [simp]:\n  \"g \\<in> G \\<Longrightarrow> quotient.inverse (g \\<cdot>| K) = (inverse g \\<cdot>| K)\"\n  using Class_commutes_with_inverse Class_is_Left_Coset by auto\n\nend (* normal_subgroup *)\n\ntext \\<open>p 57, ll 4--5\\<close>\nlocale subgroup_of_abelian_group = subgroup_of_group H G \"(\\<cdot>)\" \\<one> + abelian_group G \"(\\<cdot>)\" \\<one>\n  for H and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n\ntext \\<open>p 57, ll 4--5\\<close>\nsublocale subgroup_of_abelian_group \\<subseteq> normal_subgroup H G \"(\\<cdot>)\" \\<one>\n  using commutative invertible_right_inverse2 by unfold_locales auto\n\n\nsubsection \\<open>Homomorphims\\<close>\n\ntext \\<open>Def 1.6\\<close>\ntext \\<open>p 58, l 33; p 59, ll 1--2\\<close>\nlocale monoid_homomorphism =\n  map \\<eta> M M'+  source: monoid M \"(\\<cdot>)\" \\<one> + target: monoid M' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and M' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\") +\n  assumes commutes_with_composition: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> (x \\<cdot> y) = \\<eta> x \\<cdot>' \\<eta> y\"\n    and commutes_with_unit: \"\\<eta> \\<one> = \\<one>'\"\nbegin\n\ntext \\<open>Jacobson notes that @{thm [source] commutes_with_unit} is not necessary for groups, but doesn't make use of that later.\\<close>\n\ntext \\<open>p 58, l 33; p 59, ll 1--2\\<close>\nnotation source.invertible (\"invertible _\" [100] 100)\nnotation source.inverse (\"inverse _\" [100] 100)\nnotation target.invertible (\"invertible'' _\" [100] 100)\nnotation target.inverse (\"inverse'' _\" [100] 100)\n\nend (* monoid_homomorphism *)\n\ntext \\<open>p 59, ll 29--30\\<close>\nlocale monoid_epimorphism = monoid_homomorphism + surjective_map \\<eta> M M'\n\ntext \\<open>p 59, l 30\\<close>\nlocale monoid_monomorphism = monoid_homomorphism + injective_map \\<eta> M M'\n\ntext \\<open>p 59, ll 30--31\\<close>\nsublocale monoid_isomorphism \\<subseteq> monoid_epimorphism\n  by unfold_locales (auto simp: commutes_with_composition commutes_with_unit)\n\ntext \\<open>p 59, ll 30--31\\<close>\nsublocale monoid_isomorphism \\<subseteq> monoid_monomorphism\n  by unfold_locales (auto simp: commutes_with_composition commutes_with_unit)\n\ncontext monoid_homomorphism begin\n\ntext \\<open>p 59, ll 33--34\\<close>\ntheorem invertible_image_lemma:\n  assumes \"invertible a\" \"a \\<in> M\"\n  shows \"\\<eta> a \\<cdot>' \\<eta> (inverse a) = \\<one>'\" and \"\\<eta> (inverse a) \\<cdot>' \\<eta> a = \\<one>'\"\n  using assms commutes_with_composition commutes_with_unit source.inverse_equality\n  by auto (metis source.invertible_inverse_closed source.invertible_left_inverse)\n\ntext \\<open>p 59, l 34; p 60, l 1\\<close>\ntheorem invertible_target_invertible [intro, simp]:\n  \"\\<lbrakk> invertible a; a \\<in> M \\<rbrakk> \\<Longrightarrow> invertible' (\\<eta> a)\"\n  using invertible_image_lemma by blast\n\ntext \\<open>p 60, l 1\\<close>\ntheorem invertible_commutes_with_inverse:\n  \"\\<lbrakk> invertible a; a \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> (inverse a) = inverse' (\\<eta> a)\"\n  using invertible_image_lemma target.inverse_equality by fastforce\n\nend (* monoid_homomorphism *)\n\ntext \\<open>p 60, ll 32--34; p 61, l 1\\<close>\nsublocale monoid_congruence \\<subseteq> natural: monoid_homomorphism Class M \"(\\<cdot>)\" \\<one> \"M / E\" \"([\\<cdot>])\" \"Class \\<one>\"\n  by unfold_locales (auto simp: PiE_I Class_commutes_with_composition)\n\ntext \\<open>Fundamental Theorem of Homomorphisms of Monoids\\<close>\n\ntext \\<open>p 61, ll 5, 14--16\\<close>\nsublocale monoid_homomorphism \\<subseteq> image: submonoid \"\\<eta> ` M\" M' \"(\\<cdot>')\" \"\\<one>'\"\n  by unfold_locales (auto simp: commutes_with_composition [symmetric] commutes_with_unit [symmetric])\n\ntext \\<open>p 61, l 4\\<close>\nlocale monoid_homomorphism_fundamental = monoid_homomorphism begin\n\ntext \\<open>p 61, ll 17--18\\<close>\nsublocale fiber_relation \\<eta> M M' ..\nnotation Fiber_Relation (\"E'(_')\")\n\ntext \\<open>p 61, ll 6--7, 18--20\\<close>\nsublocale monoid_congruence where E = \"E(\\<eta>)\"\n  using Class_eq\n  by unfold_locales (rule Class_equivalence [THEN iffD1],\n    auto simp: left_closed right_closed commutes_with_composition Fiber_equality)\n\ntext \\<open>p 61, ll 7--9\\<close>\ntext \\<open>\n  @{term induced} denotes Jacobson's $\\bar{\\eta}$.  We have the commutativity of the diagram, where\n  @{term induced} is unique: @{thm [display] factorization} @{thm [display] uniqueness}.\n\\<close>\n\ntext \\<open>p 61, l 20\\<close>\nnotation quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>p 61, ll 7--8, 22--25\\<close>\nsublocale induced: monoid_homomorphism induced \"M / E(\\<eta>)\" \"([\\<cdot>])\" \"Class \\<one>\" \"M'\" \"(\\<cdot>')\" \"\\<one>'\"\n  apply unfold_locales\n    apply (auto simp: commutes_with_unit)\n  apply (fastforce simp: commutes_with_composition commutes_with_unit Class_commutes_with_composition)\n  done\n\ntext \\<open>p 61, ll 9, 26\\<close>\nsublocale natural: monoid_epimorphism Class M \"(\\<cdot>)\" \\<one> \"M / E(\\<eta>)\" \"([\\<cdot>])\" \"Class \\<one>\" ..\n\ntext \\<open>p 61, ll 9, 26--27\\<close>\nsublocale induced: monoid_monomorphism induced \"M / E(\\<eta>)\" \"([\\<cdot>])\" \"Class \\<one>\" \"M'\" \"(\\<cdot>')\" \"\\<one>'\" ..\n\nend (* monoid_homomorphism_fundamental *)\n\ntext \\<open>p 62, ll 12--13\\<close>\nlocale group_homomorphism =\n  monoid_homomorphism \\<eta> G \"(\\<cdot>)\" \\<one> G' \"(\\<cdot>')\" \"\\<one>'\" +\n  source: group G \"(\\<cdot>)\" \\<one> + target: group G' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and G' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\")\nbegin\n\ntext \\<open>p 62, l 13\\<close>\nsublocale image: subgroup \"\\<eta> ` G\" G' \"(\\<cdot>')\" \"\\<one>'\"\n  using invertible_image_lemma by unfold_locales auto\n\ntext \\<open>p 62, ll 13--14\\<close>\ndefinition \"Ker = \\<eta> -` {\\<one>'} \\<inter> G\"\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_equality:\n  \"Ker = {a | a. a \\<in> G \\<and> \\<eta> a = \\<one>'}\"\n  unfolding Ker_def by auto\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_closed [intro, simp]:\n  \"a \\<in> Ker \\<Longrightarrow> a \\<in> G\"\n  unfolding Ker_def by simp\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_image [intro]: (* loops as a simprule *)\n  \"a \\<in> Ker \\<Longrightarrow> \\<eta> a = \\<one>'\"\n  unfolding Ker_def by simp\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_memI [intro]: (* loops as a simprule *)\n  \"\\<lbrakk> \\<eta> a = \\<one>'; a \\<in> G \\<rbrakk> \\<Longrightarrow> a \\<in> Ker\"\n  unfolding Ker_def by simp\n\ntext \\<open>p 62, ll 15--16\\<close>\nsublocale kernel: normal_subgroup Ker G\nproof -\n  interpret kernel: submonoid Ker G\n    unfolding Ker_def by unfold_locales (auto simp: commutes_with_composition commutes_with_unit)\n  interpret kernel: subgroup Ker G\n    by unfold_locales (force intro: source.invertible_right_inverse simp: Ker_image invertible_commutes_with_inverse)\n  show \"normal_subgroup Ker G (\\<cdot>) \\<one>\"\n    apply unfold_locales\n    unfolding Ker_def\n    by (auto simp: commutes_with_composition invertible_image_lemma(2))\nqed\n\ntext \\<open>p 62, ll 17--20\\<close>\ntheorem injective_iff_kernel_unit:\n  \"inj_on \\<eta> G \\<longleftrightarrow> Ker = {\\<one>}\"\nproof (rule Not_eq_iff [THEN iffD1, OF iffI])\n  assume \"Ker \\<noteq> {\\<one>}\"\n  then obtain b where b: \"b \\<in> Ker\" \"b \\<noteq> \\<one>\" by blast\n  then have \"\\<eta> b = \\<eta> \\<one>\" by (simp add: Ker_image)\n  with b show \"\\<not> inj_on \\<eta> G\"  by (meson inj_onD kernel.sub source.unit_closed)\nnext\n  assume \"\\<not> inj_on \\<eta> G\"\n  then obtain a b where \"a \\<noteq> b\" and ab: \"a \\<in> G\" \"b \\<in> G\" \"\\<eta> a = \\<eta> b\" by (meson inj_onI)\n  then have \"inverse a \\<cdot> b \\<noteq> \\<one>\" \"\\<eta> (inverse a \\<cdot> b) = \\<one>'\"\n    using ab source.invertible_right_inverse2\n    by force (metis ab commutes_with_composition invertible_image_lemma(2) source.invertible source.invertible_inverse_closed)\n  then have \"inverse a \\<cdot> b \\<in> Ker\" using Ker_memI ab by blast\n  then show \"Ker \\<noteq> {\\<one>}\" using \\<open>inverse a \\<cdot> b \\<noteq> \\<one>\\<close> by blast\nqed\n\nend (* group_homomorphism *)\n\ntext \\<open>p 62, l 24\\<close>\nlocale group_epimorphism = group_homomorphism + monoid_epimorphism \\<eta> G \"(\\<cdot>)\" \\<one> G' \"(\\<cdot>')\" \"\\<one>'\"\n\ntext \\<open>p 62, l 21\\<close>\nlocale normal_subgroup_in_kernel =\n  group_homomorphism + contained: normal_subgroup L G \"(\\<cdot>)\" \\<one> for L +\n  assumes subset: \"L \\<subseteq> Ker\"\nbegin\n\ntext \\<open>p 62, l 21\\<close>\nnotation contained.quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>\"homomorphism onto @{term \"G // L\"}\"\\<close>\ntext \\<open>p 62, ll 23--24\\<close>\nsublocale natural: group_epimorphism contained.Class G \"(\\<cdot>)\" \\<one> \"G // L\" \"([\\<cdot>])\" \"contained.Class \\<one>\" ..\n\ntext \\<open>p 62, ll 25--26\\<close>\ntheorem left_coset_equality:\n  assumes eq: \"a \\<cdot>| L = b \\<cdot>| L\" and [simp]: \"a \\<in> G\" and b: \"b \\<in> G\"\n  shows \"\\<eta> a = \\<eta> b\"\nproof -\n  obtain l where l: \"b = a \\<cdot> l\" \"l \\<in> L\"\n    by (metis b contained.Class_is_Left_Coset contained.Class_self eq kernel.Left_Coset_memE)\n  then have \"\\<eta> a = \\<eta> a \\<cdot>' \\<eta> l\" using Ker_image monoid_homomorphism.commutes_with_composition subset by auto\n  also have \"\\<dots> = \\<eta> b\" by (simp add: commutes_with_composition l)\n  finally show ?thesis .\nqed\n\ntext \\<open>$\\bar{\\eta}$\\<close>\ntext \\<open>p 62, ll 26--27\\<close>\ndefinition \"induced = (\\<lambda>A \\<in> G // L. THE b. \\<exists>a \\<in> G. a \\<cdot>| L = A \\<and> b = \\<eta> a)\"\n\ntext \\<open>p 62, ll 26--27\\<close>\nlemma induced_closed [intro, simp]:\n  assumes [simp]: \"A \\<in> G // L\" shows \"induced A \\<in> G'\"\nproof -\n  obtain a where a: \"a \\<in> G\" \"a \\<cdot>| L = A\" using contained.Class_is_Left_Coset contained.Partition_def assms by auto\n  have \"(THE b. \\<exists>a \\<in> G. a \\<cdot>| L = A \\<and> b = \\<eta> a) \\<in> G'\"\n    apply (rule theI2)\n    using a by (auto intro: left_coset_equality)\n  then show ?thesis unfolding induced_def by simp\nqed\n\ntext \\<open>p 62, ll 26--27\\<close>\nlemma induced_undefined [intro, simp]:\n  \"A \\<notin> G // L \\<Longrightarrow> induced A = undefined\"\n  unfolding induced_def by simp\n\ntext \\<open>p 62, ll 26--27\\<close>\ntheorem induced_left_coset_closed [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> induced (a \\<cdot>| L) \\<in> G'\"\n  using contained.Class_is_Left_Coset contained.Class_in_Partition by auto \n\ntext \\<open>p 62, ll 26--27\\<close>\ntheorem induced_left_coset_equality [simp]:\n  assumes [simp]: \"a \\<in> G\" shows \"induced (a \\<cdot>| L) = \\<eta> a\"\nproof -\n  have \"(THE b. \\<exists>a' \\<in> G. a' \\<cdot>| L = a \\<cdot>| L \\<and> b = \\<eta> a') = \\<eta> a\"\n    by (rule the_equality) (auto intro: left_coset_equality)\n  then show ?thesis unfolding induced_def\n    using contained.Class_is_Left_Coset contained.Class_in_Partition by auto \nqed\n\ntext \\<open>p 62, l 27\\<close>\ntheorem induced_Left_Coset_commutes_with_composition [simp]:\n  \"\\<lbrakk> a \\<in> G; b \\<in> G \\<rbrakk> \\<Longrightarrow> induced ((a \\<cdot>| L) [\\<cdot>] (b \\<cdot>| L)) = induced (a \\<cdot>| L) \\<cdot>' induced (b \\<cdot>| L)\"\n  by (simp add: commutes_with_composition)\n\ntext \\<open>p 62, ll 27--28\\<close>\ntheorem induced_group_homomorphism:\n  \"group_homomorphism induced (G // L) ([\\<cdot>]) (contained.Class \\<one>) G' (\\<cdot>') \\<one>'\"\n  apply unfold_locales\n    apply (auto elim!: contained.Left_CosetE simp: commutes_with_composition commutes_with_unit)\n  using contained.factor_unit induced_left_coset_equality apply (fastforce simp: contained.Class_unit_normal_subgroup)\n  done\n\ntext \\<open>p 62, l 28\\<close>\nsublocale induced: group_homomorphism induced \"G // L\" \"([\\<cdot>])\" \"contained.Class \\<one>\" G' \"(\\<cdot>')\" \"\\<one>'\"\n  by (fact induced_group_homomorphism)\n\ntext \\<open>p 62, ll 28--29\\<close>\ntheorem factorization_lemma: \"a \\<in> G \\<Longrightarrow> compose G induced contained.Class a = \\<eta> a\"\n  unfolding compose_def by (simp add: contained.Class_is_Left_Coset)\n\ntext \\<open>p 62, ll 29--30\\<close>\ntheorem factorization [simp]: \"compose G induced contained.Class = \\<eta>\"\n  by rule (simp add: compose_def contained.Class_is_Left_Coset)\n\ntext \\<open>\n  Jacobson does not state the uniqueness of @{term induced} explicitly but he uses it later,\n  for rings, on p 107.\n\\<close>\ntext \\<open>p 62, l 30\\<close>\ntheorem uniqueness:\n  assumes map: \"\\<beta> \\<in> G // L \\<rightarrow>\\<^sub>E G'\"\n    and factorization: \"compose G \\<beta> contained.Class = \\<eta>\"\n  shows \"\\<beta> = induced\"\nproof\n  fix A\n  show \"\\<beta> A = induced A\"\n  proof (cases \"A \\<in> G // L\")\n    case True\n    then obtain a where [simp]: \"A = contained.Class a\" \"a \\<in> G\" by fast\n    then have \"\\<beta> (contained.Class a) = \\<eta> a\" by (metis compose_eq factorization)\n    also have \"\\<dots> = induced (contained.Class a)\" by (simp add: contained.Class_is_Left_Coset)\n    finally show ?thesis by simp\n  qed (simp add: induced_def PiE_arb [OF map])\nqed\n\ntext \\<open>p 62, l 31\\<close>\ntheorem induced_image:\n  \"induced ` (G // L) = \\<eta> ` G\"\n  by (metis factorization contained.natural.surjective surj_compose)\n\ntext \\<open>p 62, l 33\\<close>\ninterpretation L: normal_subgroup L Ker\n  by unfold_locales (auto simp: subset, metis kernel.sub kernel.subgroup_inverse_equality contained.normal)\n\ntext \\<open>p 62, ll 31--33\\<close>\ntheorem induced_kernel:\n  \"induced.Ker = Ker / L.Congruence\" (* Ker // L is apparently not the right thing *)\nproof -\n  have \"induced.Ker = { a \\<cdot>| L | a. a \\<in> G \\<and> a \\<in> Ker }\"\n    unfolding induced.Ker_equality\n    by simp (metis (hide_lams) contained.Class_is_Left_Coset Ker_image Ker_memI\n        induced_left_coset_equality contained.Class_in_Partition contained.representant_exists)\n  also have \"\\<dots> = Ker / L.Congruence\"\n    using L.Class_is_Left_Coset L.Class_in_Partition\n    by auto (metis L.Class_is_Left_Coset L.representant_exists kernel.sub)\n  finally show ?thesis .\nqed\n\ntext \\<open>p 62, ll 34--35\\<close>\ntheorem induced_inj_on:\n  \"inj_on induced (G // L) \\<longleftrightarrow> L = Ker\"\n  apply (simp add: induced.injective_iff_kernel_unit induced_kernel contained.Class_unit_normal_subgroup)\n  apply rule\n  using L.block_exists apply auto [1]\n  using L.Block_self L.Class_unit_normal_subgroup L.quotient.unit_closed L.representant_exists\n  apply auto\n  done\n\nend (* normal_subgroup_in_kernel *)\n\ntext \\<open>Fundamental Theorem of Homomorphisms of Groups\\<close>\n\ntext \\<open>p 63, l 1\\<close>\nlocale group_homomorphism_fundamental = group_homomorphism begin\n\ntext \\<open>p 63, l 1\\<close>\nnotation kernel.quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>p 63, l 1\\<close>\nsublocale normal_subgroup_in_kernel where L = Ker by unfold_locales rule\n\ntext \\<open>p 62, ll 36--37; p 63, l 1\\<close>\ntext \\<open>\n  @{term induced} denotes Jacobson's $\\bar{\\eta}$.  We have the commutativity of the diagram, where\n  @{term induced} is unique: @{thm [display] factorization} @{thm [display] uniqueness}\n\\<close>\n\nend (* group_homomorphism_fundamental *)\n\ntext \\<open>p 63, l 5\\<close>\nlocale group_isomorphism = group_homomorphism + bijective_map \\<eta> G G' begin\n\ntext \\<open>p 63, l 5\\<close>\nsublocale monoid_isomorphism \\<eta> G \"(\\<cdot>)\" \\<one> G' \"(\\<cdot>')\" \"\\<one>'\" \n  by unfold_locales (auto simp: commutes_with_composition)\n\ntext \\<open>p 63, l 6\\<close>\nlemma inverse_group_isomorphism:\n  \"group_isomorphism (restrict (inv_into G \\<eta>) G') G' (\\<cdot>') \\<one>' G (\\<cdot>) \\<one>\"\n  using commutes_with_composition commutes_with_unit surjective by unfold_locales auto\n\nend (* group_isomorphism *)\n\ntext \\<open>p 63, l 6\\<close>\ndefinition isomorphic_as_groups (infixl \"\\<cong>\\<^sub>G\" 50)\n  where \"\\<G> \\<cong>\\<^sub>G \\<G>' \\<longleftrightarrow> (let (G, composition, unit) = \\<G>; (G', composition', unit') = \\<G>' in\n  (\\<exists>\\<eta>. group_isomorphism \\<eta> G composition unit G' composition' unit'))\"\n\ntext \\<open>p 63, l 6\\<close>\nlemma isomorphic_as_groups_symmetric:\n  \"(G, composition, unit) \\<cong>\\<^sub>G (G', composition', unit') \\<Longrightarrow> (G', composition', unit') \\<cong>\\<^sub>G (G, composition, unit)\"\n  by (simp add: isomorphic_as_groups_def) (meson group_isomorphism.inverse_group_isomorphism)\n\ntext \\<open>p 63, l 1\\<close>\nsublocale group_isomorphism \\<subseteq> group_epimorphism ..\n\ntext \\<open>p 63, l 1\\<close>\nlocale group_epimorphism_fundamental = group_homomorphism_fundamental + group_epimorphism begin\n\ntext \\<open>p 63, ll 1--2\\<close>\ninterpretation image: group_homomorphism induced \"G // Ker\" \"([\\<cdot>])\" \"kernel.Class \\<one>\" \"(\\<eta> ` G)\" \"(\\<cdot>')\" \"\\<one>'\"\n  by (simp add: surjective group_homomorphism_fundamental.intro induced_group_homomorphism)\n\ntext \\<open>p 63, ll 1--2\\<close>\nsublocale image: group_isomorphism induced \"G // Ker\" \"([\\<cdot>])\" \"kernel.Class \\<one>\" \"(\\<eta> ` G)\" \"(\\<cdot>')\" \"\\<one>'\"\n  using induced_group_homomorphism\n  by unfold_locales (auto simp: bij_betw_def induced_image induced_inj_on induced.commutes_with_composition)\n\nend (* group_epimorphism_fundamental *)\n\ncontext group_homomorphism begin\n\ntext \\<open>p 63, ll 5--7\\<close>\ntheorem image_isomorphic_to_factor_group:\n  \"\\<exists>K composition unit. normal_subgroup K G (\\<cdot>) \\<one> \\<and> (\\<eta> ` G, (\\<cdot>'), \\<one>') \\<cong>\\<^sub>G (G // K, composition, unit)\"\nproof -\n  interpret image: group_epimorphism_fundamental where G' = \"\\<eta> ` G\"\n    by unfold_locales (auto simp: commutes_with_composition)\n  have \"group_isomorphism image.induced (G // Ker) ([\\<cdot>]) (kernel.Class \\<one>) (\\<eta> ` G) (\\<cdot>') \\<one>'\" ..\n  then have \"(\\<eta> ` G, (\\<cdot>'), \\<one>') \\<cong>\\<^sub>G (G // Ker, ([\\<cdot>]), kernel.Class \\<one>)\"\n    by (simp add: isomorphic_as_groups_def) (meson group_isomorphism.inverse_group_isomorphism)\n  moreover have \"normal_subgroup Ker G (\\<cdot>) \\<one>\" ..\n  ultimately show ?thesis by blast\nqed\n\nend (* group_homomorphism *)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Jacobson_Basic_Algebra/Group_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7892634449662297}}
{"text": "theory Ch2\n  imports Main\nbegin\n\n(* 2.1 *)\n\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(*\nExercise 2.2. Start from the definition of add given above. Prove that add\nis associative and commutative. Define a recursive function double :: nat \\<Rightarrow>\nnat and prove double m = add m m.\n*)\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\n(*Ассоциативность*)\nlemma \"add (add a b) c = add a (add b c)\"\n  apply (induction a)\n  apply (auto)\n  done\n\n(*1 доказалась сразу, добавить [simp]*)\n\n\n(*2 добавить [simp]*)\nlemma [simp]: \"add b (Suc a) = add (Suc b) a\"\n  apply (induction b)\n  apply (auto)\n  done\n\n(*Коммутативность*)\nlemma \"add a b = add b a\"\n  apply (induction a)\n  apply (auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc n) = Suc (Suc (double n))\"\n\nlemma \"double a = add a a\"\n  apply(induction a)\n  apply(auto)\n  done\n\n(*\nExercise 2.3. Define a function count :: 0 a \\<Rightarrow> 0 a list \\<Rightarrow> nat that counts the\nnumber of occurrences of an element in a list. Prove count x xs \\<le> length xs.\n*)\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count a Nil = 0\" |\n\"count a (Cons x xs) = (if a = x then 1 else 0) + (count a xs)\"\n\n(* value \"count 0 [0,4,5,0]\" *)\nvalue \"count (0::nat) [0,4,5,0]\"\nvalue \"count 0 [0::nat,4,5,0]\"\nvalue \"count 0 ([0,4,5,0]::nat list)\"\n\nlemma \"count x xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(*\nExercise 2.4. Define a recursive function snoc :: 0 a list \\<Rightarrow> 0 a \\<Rightarrow> 0 a list\nthat appends an element to the end of a list. With the help of snoc define\na recursive function reverse :: 0 a list \\<Rightarrow> 0 a list that reverses a list. Prove\nreverse (reverse xs) = xs.\n*)\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc Nil a = (Cons a Nil)\" |\n\"snoc (Cons x xs) a = Cons x (snoc xs a)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse Nil = Nil\" |\n\"reverse (Cons x xs) = snoc (reverse xs) x\"\n\nlemma rev_snoc [simp]: \"reverse (snoc xs a) = Cons a (reverse xs)\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nlemma \"reverse (reverse m) = m\" \n  apply(induction m)\n  apply(auto)\n  done\n\n(*\nExercise 2.5. Define a recursive function sum_upto :: nat \\<Rightarrow> nat such that\nsum_upto n = 0 + ... + n and prove sum_upto n = n \\<^emph> (n + 1) div 2.\n*)\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\" |\n\"sum_upto (Suc n) = n + 1 + (sum_upto n)\"\n\nlemma \"sum_upto n = n * (n + 1) div 2\" \n  apply(induction n)\n  apply(auto)\n  done\n\n(*\nExercise 2.6. Starting from the type 0 a tree defined in the text, define a\nfunction contents :: 0 a tree \\<Rightarrow> 0 a list that collects all values in a tree in a\nlist, in any order, without removing duplicates. Then define a function sum_tree\n:: nat tree \\<Rightarrow> nat that sums up all values in a tree of natural numbers and\nprove sum_tree t = sum_list (contents t ) (where sum_list is predefined).\n*)\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = Nil\" |\n\"contents (Node l a r) = (contents l) @ [a] @ (contents r)\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l a r) = a + (sum_tree l) + (sum_tree r)\"\n\nlemma \"sum_tree t = sum_list (contents t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\n(*\nExercise 2.7. Define a new type 0 a tree2 of binary trees where values are\nalso stored in the leaves of the tree. Also reformulate the mirror function\naccordingly. Define two functions pre_order and post_order of type 0 a tree2\n\\<Rightarrow> 0 a list that traverse a tree and collect all stored values in the respective\norder in a list. Prove pre_order (mirror t ) = rev (post_order t ).\n*)\n\ndatatype 'a tree2 = Leaf2 'a | Node2 \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror2 :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror2 (Leaf2 a) = Leaf2 a\" |\n\"mirror2 (Node2 l a r) = Node2 (mirror2 r) a (mirror2 l)\"\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order (Leaf2 a) = [a]\" |\n\"pre_order (Node2 l a r) = (pre_order l) @ [a] @ (pre_order r)\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Leaf2 a) = [a]\" |\n\"post_order (Node2 l a r) = (post_order r) @ [a] @ (post_order l)\"\n\nlemma \"pre_order (mirror2 t) = post_order t\"\n  apply(induction t)\n  apply(auto)\n  done\n\n(*\nExercise 2.8. Define a function intersperse :: 0 a \\<Rightarrow> 0 a list \\<Rightarrow> 0 a list such\nthat intersperse a [x 1 , ..., x n ] = [x 1 , a, x 2 , a, ..., a, x n ]. Now prove that\nmap f (intersperse a xs) = intersperse (f a) (map f xs).\n*)\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse a Nil = Nil\" |\n\"intersperse a (Cons x Nil) = Cons x Nil\" |\n\"intersperse a (Cons x xs) = Cons x (Cons a (intersperse a xs))\"\n\nvalue \"intersperse (9::nat) []\"\nvalue \"intersperse (9::nat) [5]\"\nvalue \"intersperse (9::nat) [1,2,3,4]\"\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction xs rule: intersperse.induct)\n  apply(auto)\n  done\n\n(*\nExercise 2.9. Write a tail-recursive variant of the add function on nat :\nitadd. Tail-recursive means that in the recursive case, itadd needs to call\nitself directly: itadd (Suc m) n = itadd . . .. Prove itadd m n = add m n.\n*)\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 m = m\" |\n\"itadd (Suc n) m = itadd n (Suc m)\"\n\nlemma \"itadd m n = add m n\"\n  apply(induction m arbitrary: n)\n  apply(auto)\n  done\n\n(*\nExercise 2.10. Define a datatype tree0 of binary tree skeletons which do not\nstore any information, neither in the inner nodes nor in the leaves. Define a\nfunction nodes :: tree0 \\<Rightarrow> nat that counts the number of all nodes (inner\nnodes and leaves) in such a tree. Consider the following recursive function:\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t )\"\nFind an equation expressing the size of a tree after exploding it (nodes\n(explode n t )) as a function of nodes t and n. Prove your equation. You\nmay use the usual arithmetic operators, including the exponentiation opera-\ntor “^”. For example, 2 ^ 2 = 4.\nHint: simplifying with the list of theorems algebra_simps takes care of\ncommon algebraic properties of the arithmetic operators.\n*)\n\ndatatype tree0 = Leaf0 | Node0 tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Leaf0 = 1\" |\n\"nodes (Node0 l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node0 t t)\"\n\nfun nexplode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> nat\" where\n\"nexplode n t = 2 ^ n * nodes t + 2 ^ n - 1\"\n\nlemma \"nodes (explode n t) = nexplode n t\"\n  apply(induction n arbitrary: t)\n  apply(auto simp add: algebra_simps)\n  done\n\n(* Как доказать это?\nlemma \"nexplode n t = nodes (explode n t)\"\n  apply(induction n arbitrary: t)\n  apply(auto)\n  done\n*)\n\n(*\nExercise 2.11. Define arithmetic expressions in one variable over integers\n(type int ) as a data type:\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\nDefine a function eval :: exp \\<Rightarrow> int \\<Rightarrow> int such that eval e x evaluates e at\nthe value x.\nA polynomial can be represented as a list of coefficients, starting with the\nconstant. For example, [4, 2, − 1, 3] represents the polynomial 4+2x−x 2 +3x 3 .\nDefine a function evalp :: int list \\<Rightarrow> int \\<Rightarrow> int that evaluates a polynomial at\nthe given value. Define a function coeffs :: exp \\<Rightarrow> int list that transforms an\nexpression into a polynomial. This may require auxiliary functions. Prove that\ncoeffs preserves the value of the expression: evalp (coeffs e) x = eval e x.\nHint: consider the hint in Exercise 2.10.\n*)\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\" |\n\"eval (Const i) _ = i\" | \n\"eval (Add e1 e2) x = eval e1 x + eval e2 x\" |\n\"eval (Mult e1 e2) x = eval e1 x * eval e2 x\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] x = 0\" |\n\"evalp (Cons k ks) x = k + x * evalp ks x\"\n\nfun poly_add :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"poly_add [] ys = ys\" |\n\"poly_add xs [] = xs\" |\n\"poly_add (Cons x xs) (Cons y ys) = Cons (x + y) (poly_add xs ys)\"\n\nfun poly_sc_mul :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"poly_sc_mul k [] = []\" |\n\"poly_sc_mul k (x # xs) = k * x # poly_sc_mul k xs\"\n\nfun poly_mul :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"poly_mul [] ys = []\" |\n\"poly_mul (x # xs) ys = poly_add (poly_sc_mul x ys) (0 # poly_mul xs ys)\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0, 1]\" |\n\"coeffs (Const i) = [i]\" |\n\"coeffs (Add e1 e2) = poly_add (coeffs e1) (coeffs e2)\" |\n\"coeffs (Mult e1 e2) = poly_mul (coeffs e1) (coeffs e2)\"\n\nlemma evalp_additive [simp]: \"evalp (poly_add as bs) x = evalp as x + evalp bs x\"\n  apply(induction rule:poly_add.induct)\n  apply(auto simp add:Int.int_distrib)\n  done\n\nlemma evalp_preserves_mul [simp]: \"evalp (poly_sc_mul k as) x = k * evalp as x\"\n  apply(induction as)\n  apply(auto simp add:Int.int_distrib)\n  done\n\nlemma evalp_multiplicative [simp]: \"evalp (poly_mul as bs) x = evalp as x * evalp bs x\"\n  apply(induction as)\n  apply(auto simp add:Int.int_distrib)\n  done\n\nlemma \"evalp (coeffs e) x = eval e x\"\n  apply(induction e)\n  apply(auto)\n  done\n\nend", "meta": {"author": "user7", "repo": "concrete-semantics", "sha": "5ddbd752550b3037d0d461d67a39d4f61c4548e5", "save_path": "github-repos/isabelle/user7-concrete-semantics", "path": "github-repos/isabelle/user7-concrete-semantics/concrete-semantics-5ddbd752550b3037d0d461d67a39d4f61c4548e5/Ch2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.789205916783371}}
{"text": "theory Ex1_3 \nimports Main\nbegin \n\n\nfun alls :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where   \n\"alls _ [] = True\"|\n\"alls cond (x#xs) =  (cond x \\<and> alls cond xs)\"\n\n\nfun exs :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where \n\"exs cond [] = False\"|\n\"exs cond (x#xs) = (if cond x then True else exs cond xs)\"\n\n\n\nlemma \"alls (\\<lambda>x . P x \\<and> Q x) xs = (alls P xs \\<and> alls Q xs)\" \nproof (induct xs)\n  show \"alls (\\<lambda>x. P x \\<and> Q x) [] = (alls P [] \\<and> alls Q [])\" by simp\n next \n  fix a xs \n  assume \"alls (\\<lambda>x. P x \\<and> Q x) xs = (alls P xs \\<and> alls Q xs)\"\n  thus \"alls (\\<lambda>x. P x \\<and> Q x) (a # xs) = (alls P (a # xs) \\<and> alls Q (a # xs))\" by auto\nqed\n\nlemma tmp [simp] : \"alls P (xs @ [x]) = (alls P xs \\<and> P x)\" \nproof (induct xs)\n  case Nil \n  show ?case by simp\n next \n  fix a xs \n  case (Cons a xs)\n  assume \" alls P (xs @ [x]) = (alls P xs \\<and> P x)\"\n  thus ?case by simp\nqed\n\nlemma \"alls P (rev xs) = alls P xs \"\nproof (induct xs) \n  case Nil \n  show ?case by simp\n next \n  fix a xs\n  case (Cons a xs)\n\n  assume \" alls P (rev xs) = alls P xs\"\n  thus ?case by auto\nqed\n\n(*\nlemma \"exs (\\<lambda>x . P x \\<and> Q x) xs = (exs P xs \\<and> exs Q xs)\"\nquickcheck\n*)\n\nlemma \"exs P (map f xs) = exs (P \\<circ> f) xs\"\nproof (induct xs)\n  case Nil \n  show ?case by simp\n next \n  fix a xs \n  case (Cons a xs)\n  assume a:\"exs P (map f xs) = exs (P \\<circ> f) xs\"\n\n  show \"exs P (map f (a # xs)) = exs (P \\<circ> f) (a # xs)\" \n  proof (cases \"P (f a)\")\n    assume \"P (f a)\"\n    thus \" exs P (map f (a # xs)) = exs (P \\<circ> f) (a # xs)\" by simp\n   next \n    assume \"\\<not> P (f a)\"\n    with a show  \"exs P (map f (a # xs)) = exs (P \\<circ> f) (a # xs) \"  by simp \n  qed\nqed\n\n\nlemma exs_cons_append [simp] :  \"exs P (a#xs) = exs P (xs @ [a])\" \nproof (induct xs) \n  case Nil \n  show ?case by simp\n next \n  fix aa xs \n  case (Cons aa xs)\n  assume a:\"exs P (a # xs) = exs P (xs @ [a])\"\n  show \"exs P (a # aa # xs) = exs P ((aa # xs) @ [a])\" \n  proof (cases \"P aa\")\n  assume \"P aa\"\n  thus \" exs P (a # aa # xs) = exs P ((aa # xs) @ [a])\" by simp\n next \n  assume \"\\<not>P aa\"\n  from a show  \" exs P (a # aa # xs) = exs P ((aa # xs) @ [a])\" by auto\n qed\nqed\n  \n\nlemma \"exs P (rev xs) = exs P xs\"\nproof (induct xs)\n  case Nil \n  show ?case by simp\n next \n  fix a xs \n  case (Cons a xs)\n  assume a:\"exs P (rev xs) = exs P xs\"\n  show ?case \n  proof (cases \"P a\")\n    assume \"P a\"\n    with exs_cons_append show  \"exs P (rev (a # xs)) = exs P (a # xs)\" by fastforce\n   next \n    assume \"\\<not>P a\"\n    with exs_cons_append and a show \"exs P (rev (a # xs)) = exs P (a # xs)\" by force\n  qed\nqed\n  \n\nlemma \"exs (\\<lambda> x . P x \\<or> Q x) xs = exs P xs \\<or> exs Q xs\"\nproof (induction xs)\n  case Nil\n  show ?case by simp\n next \n  fix a xs \n  case (Cons a xs)\n  assume hyp:\"exs (\\<lambda>x. P x \\<or> Q x) xs = exs P xs \\<or> exs Q xs\" \n  show ?case \n  proof (cases \"P a\")\n    assume a:\"P a\"\n    show \"exs (\\<lambda>x. P x \\<or> Q x) (a # xs) = exs P (a # xs) \\<or> exs Q (a # xs)\" \n    proof (cases \"Q a\")\n      assume \"Q a\" \n      with a show \"exs (\\<lambda>x. P x \\<or> Q x) (a # xs) = exs P (a # xs) \\<or> exs Q (a # xs)\" by simp\n     next \n      assume \"\\<not>(Q a)\"\n      with a and hyp show \" exs (\\<lambda>x. P x \\<or> Q x) (a # xs) = exs P (a # xs) \\<or> exs Q (a # xs)\" by simp\n     qed\n    next\n     assume \"\\<not>P a\"\n     with hyp show \" exs (\\<lambda>x. P x \\<or> Q x) (a # xs) = exs P (a # xs) \\<or> exs Q (a # xs)\" by force\n   qed\nqed\n\n\nlemma \"exs P xs = (\\<not>(alls (\\<lambda> x .\\<not> P x) xs))\" \nproof (induct xs)\n  case Nil \n  show ?case by simp\n next \n  fix a xs \n  case (Cons a xs)\n  assume a:\"exs P xs = (\\<not> alls (\\<lambda>x. \\<not> P x) xs)\" \n  show ?case \n  proof (cases \"P a\")\n    assume \"P a\"\n    thus  \"exs P (a # xs) = (\\<not> alls (\\<lambda>x. \\<not> P x) (a # xs))\" by simp\n   next \n    assume \"\\<not>P a\" \n    with a show \"exs P (a # xs) = (\\<not> alls (\\<lambda>x. \\<not> P x) (a # xs))\" by simp\n  qed\nqed\n\nprimrec is_in :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"is_in [] _  = False \"|\n\"is_in (x#xs) val = (if  x = val then True else is_in xs val)\"\n\nlemma \"is_in ls a = exs (\\<lambda>x . x = a) ls\"\napply (induction ls)\napply simp_all\ndone\n\nprimrec nodups :: \"'a list \\<Rightarrow> bool\" where \n\"nodups [] = True\"|\n\"nodups (x#xs)   = (if x \\<in> set xs then False else nodups xs)\"\n\n\nprimrec deldups :: \"'a list \\<Rightarrow> 'a list\" where \n\"deldups [] =  []\"|\n\"deldups (x#xs) = (let tmp =  deldups xs in (if  x \\<in> set tmp then tmp else x#tmp) )\"\n\n\nfun deldups2 :: \"'a list \\<Rightarrow> 'a list\" where \n\"deldups2 [] =  []\"|\n\"deldups2 (x#xs) =  x # deldups2 (filter (\\<lambda>y . y \\<noteq> x) xs)\"\n    \nlemma \"length (deldups xs ) \\<le> length xs\"\nproof (induct xs)\n  case Nil \n  show ?case by simp\n next \n  fix a xs \n  case (Cons a xs) \n  assume a:\"length (deldups xs) \\<le> length xs\"\n  show \"length (deldups (a # xs)) \\<le> length (a # xs) \" \n  proof (cases \"a \\<in> set (deldups xs)\")\n    assume \"a \\<in> set (deldups xs)\"\n    with a show \"length (deldups (a # xs)) \\<le> length (a # xs)\" by simp\n   next \n    assume \"a \\<notin> set (deldups xs)\"\n    with a show \"length (deldups (a # xs)) \\<le> length (a # xs)\" by simp\n  qed\nqed\n\nlemma \"length (deldups2 xs ) \\<le> length xs\" \nproof (induct xs)\n  case Nil \n  show ?case by simp \n next \n  fix a xs \n  case (Cons a xs)\n  assume hyp:\"length (deldups2 xs) \\<le> length xs\"\n  show \"length (deldups2 (a # xs)) \\<le> length (a # xs)\" \n  proof(cases \"a \\<in> set xs\")\n    assume \"a \\<in> set xs\"\n    with hyp show  \"length (deldups2 (a # xs)) \\<le> length (a # xs)\" \n    \n    ", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions", "sha": "1a71e30f3369d34c4691a4d010257b8c8afc566c", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions/ExerciseSolutions-1a71e30f3369d34c4691a4d010257b8c8afc566c/src/isabelle/Lists/Ex1_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8791467659263148, "lm_q1q2_score": 0.789205903218556}}
{"text": "theory Chap2 \n  imports Main\nbegin\n\ndatatype cbool = Ctrue | Cfalse\n\nfun conj :: \"cbool \\<Rightarrow> cbool \\<Rightarrow> cbool\" where\n  \"conj Ctrue Ctrue = Ctrue\" |\n  \"conj _ _ = Cfalse\"\n\ndatatype cnat = C | Csuc cnat\n\nfun add :: \"cnat \\<Rightarrow> cnat \\<Rightarrow> cnat\" where \n  \"add C m = m\" |\n  \"add (Csuc n) m = Csuc (add n m)\"\n\nlemma add_n_0 [simp] : \"add m C = m\"\nproof (induction m)\n  case C thus ?case by simp\n  case (Csuc n) thus ?case by simp\nqed\n \ndatatype 'a clist = Cnil | Ccons 'a \"'a clist\"\n\nfun app :: \"'a clist \\<Rightarrow> 'a clist \\<Rightarrow> 'a clist\" where\n \"app Cnil ys = ys\" |\n \"app (Ccons x xs) ys = Ccons x (app xs ys)\" \n\nfun revt :: \"'a clist \\<Rightarrow> 'a clist\" where\n  \"revt Cnil = Cnil\" |\n  \"revt (Ccons x xs) = app (revt xs) (Ccons x Cnil)\" \n\ntheorem app_nil [simp] : \"app xs  Cnil = xs\"\n  apply (induction xs)\n   apply auto\n  done\n\ntheorem app_assoc [simp] : \"app xs (app ys zs) = app (app xs ys) zs\"\n  apply (induction xs)\n   apply auto\n  done \n\ntheorem rev_app [simp] : \"revt (app xs ys) = app (revt ys) (revt xs)\" \n  apply (induction xs)\n   apply auto\n  done\n\ntheorem rev_rev : \"revt (revt xs) = xs\"\n  apply (induction xs)\n   apply auto\n  done\n\nvalue \"1 + (2 :: nat)\"\nvalue \"1 + (2 :: int)\"\nvalue \"1 - (2 :: nat)\"\nvalue \"1 - (2 :: int)\"\n\ntheorem add_suc [simp] : \"add n (Csuc m) = Csuc (add n m)\"\n  apply (induction n)\n   apply auto\n  done\n\ntheorem add_commutative : \"add m n = add n m\"\n  apply (induction m)\n   apply auto\n  done\n\ntheorem add_assoc : \"add m (add n p) = add (add m n) p\"\n  apply (induction m)\n   apply auto\n  done\n\nfun double :: \"cnat \\<Rightarrow> cnat\" where\n \"double C = C\" |\n \"double (Csuc n) = Csuc (Csuc (double n))\"\n\ntheorem double_correct : \"double m = add m m\"\n  apply (induction m)\n   apply auto\n  done\n\n(* From here onwards, use the datatype given by Isabelle *)\nfun count :: \"'a \\<Rightarrow>  'a list \\<Rightarrow> nat\" where\n  \"count _ Nil = 0\" |\n  \"count x (y # ys) =\n   (if x = y then Suc (count x ys)\n    else count x ys)\" \n\nfun length :: \"'a list \\<Rightarrow> nat\" where\n \"length Nil = 0\" |\n \"length (_ # xs) = Suc (length xs)\"\n\ntheorem count_correct : \"count x xs \\<le> length xs\" \n  apply (induction xs)\n   apply auto\n  done  \n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc Nil x = [x]\" |\n  \"snoc (y # ys) x = y # (snoc ys x)\" \n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n \"reverse Nil = Nil\" |\n \"reverse (x # xs) = snoc (reverse xs) x\" \n\ntheorem rev_snoc [simp] :  \"reverse (snoc xs a) = a # reverse xs\"\n  apply (induction xs)\n   apply auto\n  done\n\n\ntheorem reverse_reverse : \"reverse (reverse xs) = xs\"\n  apply (induction xs)\n   apply auto\n  done\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n \"sum_upto 0 = 0\" | \n \"sum_upto (Suc n) = Suc n + sum_upto n\"\n\ntheorem sum_upto_n : \"sum_upto n = n * (n + 1) div 2\"\n  apply (induction n)\n   apply auto \n  done\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where \n \"mirror Tip = Tip\" |\n \"mirror (Node l v r) = Node (mirror r) v (mirror l)\"\n\ntheorem mirror_correct : \"mirror (mirror t) = t\"\n  apply (induction t rule : mirror.induct)\n   apply auto\n  done\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where \n  \"div2 0 = 0\" | \n  \"div2 (Suc 0) = 0\" |\n  \"div2 (Suc (Suc n)) = Suc (div2 n)\"\n\ntheorem div_2 : \"div2 n = n div 2\"\n  apply (induction n rule: div2.induct)\n    apply auto\n  done\n\nfun content :: \"'a tree \\<Rightarrow> 'a list\" where\n \"content Tip = Nil\" |\n \"content (Node l v r) = content l @ [v] @ content r\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n \"sum_tree Tip = 0\" |\n \"sum_tree (Node l v r) = sum_tree l + v + sum_tree r\"\n\nfun sum_list :: \"nat list \\<Rightarrow> nat\" where \n \"sum_list [] = 0\" |\n \"sum_list (x # xs) = x + sum_list xs\"\n\ntheorem sum_list_dist [simp] : \"sum_list t1 + x2 + sum_list t2 =\n       sum_list (t1 @ x2 # t2)\" \nproof (induction t1)\n  case Nil thus ?case by simp\n  case (Cons x xs) thus ?case by simp\nqed\n\ntheorem sum_tree_correct : \"sum_tree t = sum_list (content t)\"\nproof (induction t)\n  case Tip thus ?case by simp\n  case (Node l v r) thus ?case by simp\nqed\n\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2\" \"'a tree2\" \n\nfun mirror2 ::\"'a tree2 \\<Rightarrow> 'a tree2\" where\n  \"mirror2 (Tip x) = Tip x\" |\n  \"mirror2 (Node x y) = Node (mirror2 y) (mirror2 x)\" \n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n \"pre_order (Tip x) = [x]\" |\n \"pre_order (Node x y) = pre_order x @ pre_order y\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n \"post_order (Tip x) = [x]\" |\n \"post_order (Node x y) = post_order x @ post_order y\"\n\ntheorem pre_post_tree2 : \"pre_order (mirror2 t) = rev (post_order t)\"\nproof (induction t)\n  case (Tip x) \n  then show ?case by simp\n  case (Node x y) \n  then show ?case by auto\nqed\n\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intersperse _ [] = []\" |\n  \"intersperse _ [x] = [x]\" |\n  \"intersperse t (x # xs) = x # t # intersperse t xs\"\n\ntheorem map_intersperse : \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\nproof (induction xs rule: intersperse.induct)\n  case (1 uu)\n  then show ?case by simp  \n  case (2 uu x) \n  then show ?case by simp\n  case (3 t x v va) \n  then show ?case by auto\nqed\n\n\n\n\n\n  \n \n\n\n\n\n \n\n  \n\n\n  \n \n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mukeshtiwari", "repo": "Isabelle", "sha": "45d4666785264d34d6a5f1de0de862356940dbe5", "save_path": "github-repos/isabelle/mukeshtiwari-Isabelle", "path": "github-repos/isabelle/mukeshtiwari-Isabelle/Isabelle-45d4666785264d34d6a5f1de0de862356940dbe5/Concretesemantics/Chap2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037384317887, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7891670723945307}}
{"text": "theory \"ch3\"\nimports Main\nbegin\n  type_synonym uname = string\n  datatype aexp = N int | V uname | Plus aexp aexp\n\n  type_synonym val = int\n  type_synonym state = \"uname => val\"\n\n  fun aval :: \"aexp => state => val\" where\n    \"aval (N x) _ = x\" |\n    \"aval (V n) s = s n\" |\n    \"aval (Plus e f) s = aval e s + aval f s\"\n\n  fun asimp_const :: \"aexp => aexp\" where\n    \"asimp_const (N x) = N x\" |\n    \"asimp_const (V x) = V x\" |\n    \"asimp_const (Plus e f) =\n      (case (asimp_const e, asimp_const f) of\n        (N ne, N nf) => N (ne + nf) |\n        (e, f) => Plus e f)\"\n\n  lemma \"aval (asimp_const e) s = aval e s\"\n    apply(induction e)\n    apply(auto split: aexp.split)\n    done\n\n  fun plus :: \"aexp => aexp => aexp\" where\n    \"plus (N n1) (N n2) = N (n1 + n2)\" |\n    \"plus (N i) a = (if i = 0 then a else Plus (N i) a)\" |\n    \"plus a (N i) = (if i = 0 then a else Plus a (N i))\" |\n    \"plus e f = Plus e f\"\n\n  lemma aval_plus : \"aval (plus e f) s = aval e s + aval f s\"\n    apply(induction rule: plus.induct)\n    apply(auto)\n    done\n\n  lemma plus_assoc : \"aval (plus (plus e f) g) s = aval (plus e (plus f g)) s\"\n    apply(auto simp add: aval_plus)\n    done\n\n  fun asimp :: \"aexp => aexp\" where\n    \"asimp (N n) = N n\" |\n    \"asimp (V v) = V v\" |\n    \"asimp (Plus e f) = plus e f\"\n\n  lemma \"aval (asimp e) s = aval e s\"\n    apply(induction e)\n    apply(auto simp add: aval_plus)\n    done\n\n  fun no_plus_nums :: \"aexp => bool\" where\n    \"no_plus_nums (N x) = True\" |\n    \"no_plus_nums (V x) = True\" |\n    \"no_plus_nums (Plus (N n1) (N n2)) = False\" |\n    \"no_plus_nums (Plus e f) = conj (no_plus_nums e) (no_plus_nums f)\"\n\n  lemma \"no_plus_nums (asimp_const e)\"\n    apply(induction e)\n    apply(auto split: aexp.split)\n    done\n  \n  (* Sum a list of terms *)\n  fun sum_terms :: \"aexp list => aexp => aexp\" where\n    \"sum_terms [] x = x\" |\n    \"sum_terms (t # ts) x = Plus t (sum_terms ts x)\"\n  \n  lemma \"aval (sum_terms xs x) s = sum_list (map (\\<lambda> e. aval e s) xs) + aval x s\"\n    apply(induction xs)\n    apply(auto simp add: aval_plus)\n    done\n\n  lemma sumterms_app : \"aval (sum_terms (x @ y) (N (z1 + z2))) s = aval (sum_terms x (N z1)) s + aval (sum_terms y (N z2)) s\"\n    apply(induction x)\n    apply(auto simp add: aval_plus)\n    apply(induction y)\n    apply(auto)\n    done\n  \n  (* Split a term into a list of non-constant terms + a total constant *)\n  fun split :: \"aexp => aexp list*int\" where\n    \"split (N x) = ([], x)\" |\n    \"split (V x) = ([V x], 0)\" |\n    \"split (Plus e f) =\n      (case (split e, split f) of\n        ((es, en),(fs, fn)) => (es @ fs, en + fn))\"\n\n  fun is_var :: \"aexp => bool\" where\n    \"is_var (V _) = True\" |\n    \"is_var _ = False\"\n\n  fun all_vars :: \"aexp list => bool\" where\n    \"all_vars xs = list_all is_var xs\"\n\n  lemma split_allvars : \"all_vars (fst (split e))\"\n    apply(induction e)\n    apply(auto split: prod.split)\n    done\n\n  lemma \"aval (sum_terms (fst (split e)) (N (snd (split e)))) s  = aval e s\"\n    apply(induction e)\n    apply(auto split: prod.split simp add: sumterms_app)\n    done\n  \n  fun full_asimp :: \"aexp => aexp\" where\n    \"full_asimp exp =\n      sum_terms (fst (split exp)) (N (snd (split exp)))\"\n\n  lemma \"aval (full_asimp x) s = aval x s\"\n    apply(induction x)\n    apply(auto split: prod.split list.split simp add: aval_plus sumterms_app)\n    done\n\n  (* So.. full_simp is valid in the sense of preserving value. That's cool, but does it get ALL constants? *)\n\n  fun number_of_consts :: \"aexp => nat\" where\n    \"number_of_consts (N i) = 1\" |\n    \"number_of_consts (V _) = 0\" |\n    \"number_of_consts (Plus x y) = number_of_consts x + number_of_consts y\"\n\n  lemma var_zero_consts : \"is_var a --> number_of_consts a = 0\"\n    apply(induction a)\n    apply(auto)\n    done\n\n  lemma all_vars_consts : \"all_vars xs ==> number_of_consts (sum_terms xs (N n)) = Suc 0\"\n    apply(induction xs)\n    apply(auto simp add: var_zero_consts)\n    done\n\n  lemma split_consts : \"number_of_consts (sum_terms (fst (split e)) (N (snd (split e)))) = Suc 0\"\n    apply(rule all_vars_consts)\n    apply(rule split_allvars)\n    done\n\n  lemma \"number_of_consts (full_asimp e) = 1\"\n    apply(simp)\n    apply(rule split_consts)\n    done\nend", "meta": {"author": "rvb", "repo": "isabelle-concrete-semantics", "sha": "88837f88c56f127a2d988395a89b46e4bea3ad13", "save_path": "github-repos/isabelle/rvb-isabelle-concrete-semantics", "path": "github-repos/isabelle/rvb-isabelle-concrete-semantics/isabelle-concrete-semantics-88837f88c56f127a2d988395a89b46e4bea3ad13/ch3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.789136483765625}}
{"text": "(*\n  Author:   Benedikt Seidl\n  License:  GPL-3.0-or-later\n*)\n\ntheory Graph\n  imports Main\nbegin\n\ntype_synonym 'a graph = \"'a set \\<times> 'a set set\"\n\nlocale graph =\n  fixes\n    G :: \"'a graph\"\n  fixes\n    V :: \"'a set\"\n  fixes\n    E :: \"'a set set\"\n  defines\n    \"V \\<equiv> fst G\"\n  defines\n    \"E \\<equiv> snd G\"\n  assumes\n    finite_vertices: \"finite V\"\n  assumes\n    nonempty_vertices: \"V \\<noteq> {}\"\n  assumes\n    edges: \"E \\<subseteq> {e. e \\<subseteq> V \\<and> card e = 2}\"\nbegin\n\nlemma finite_edges: \"finite E\"\nproof -\n  from finite_vertices have \"finite {e. e \\<subseteq> V}\"\n    by fast\n  hence \"finite {e. e \\<subseteq> V \\<and> card e = 2}\"\n    by fast\n  with edges show \"finite E\"\n    by (rule Finite_Set.finite_subset)\nqed\n\nlemma edge_vertices: \"e \\<in> E \\<Longrightarrow> \\<exists>v w. e = {v, w}\"\nproof -\n  fix e assume \"e \\<in> E\"\n\n  then have \"card e = Suc (Suc 0)\" using edges by auto\n\n  then obtain v e' where \"e = insert v e'\" and \"card e' = Suc 0\"\n    using card_eq_SucD by metis\n\n  then show \"\\<exists>v w. e = {v, w}\"\n    using card_eq_SucD\n    by blast\nqed\n\nsubsection \\<open>Adjacency and Neighborhood\\<close>\n\ndefinition adjacent :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"adjacent v w \\<equiv> {v, w} \\<in> E\"\n\ndefinition neighborhood :: \"'a \\<Rightarrow> 'a set\" where\n  \"neighborhood v \\<equiv> {w \\<in> V. {v, w} \\<in> E}\"\n\ndefinition deg :: \"'a \\<Rightarrow> nat\" where\n  \"deg v \\<equiv> card {e \\<in> E. v \\<in> e}\"\n\ndefinition isolated :: \"'a \\<Rightarrow> bool\" where\n  \"isolated v \\<equiv> deg v = 0\"\n\ndefinition leaf :: \"'a \\<Rightarrow> bool\" where\n  \"leaf v \\<equiv> deg v = 1\"\n\ndefinition \\<delta> :: nat where\n  \"\\<delta> \\<equiv> Min {deg v | v. v \\<in> V}\"\n\ndefinition \\<Delta> :: nat where\n  \"\\<Delta> \\<equiv> Max {deg v | v. v \\<in> V}\"\n\nlemma adjacent_comm: \"adjacent v w \\<longleftrightarrow> adjacent w v\"\nproof -\n  have \"{v, w} = {w, v}\"\n    by fast\n  thus \"adjacent v w \\<longleftrightarrow> adjacent w v\"\n    unfolding adjacent_def by simp\nqed\n\nlemma deg_card_neighborhood: \"deg v = card (neighborhood v)\"\nproof -\n\n  define f :: \"'a \\<Rightarrow> 'a set\" where \"f \\<equiv> \\<lambda>w. {v, w}\"\n\n  have \"bij_betw f {w \\<in> V. {v, w} \\<in> E} {e \\<in> E. v \\<in> e}\"\n    unfolding bij_betw_def\n  proof\n    show \"inj_on f {w \\<in> V. {v, w} \\<in> E}\"\n      unfolding inj_on_def f_def\n      by (simp add: doubleton_eq_iff) \n  next\n    show \"f ` {w \\<in> V. {v, w} \\<in> E} = {e \\<in> E. v \\<in> e}\"\n      unfolding f_def image_def\n    proof auto\n      fix e\n      assume \"e \\<in> E\" and \"v \\<in> e\"\n\n      then obtain w where \"e = {v, w}\"\n        using edge_vertices by blast\n\n      then show \"\\<exists>w. w \\<in> V \\<and> {v, w} \\<in> E \\<and> e = {v, w}\"\n        using edges \\<open>e \\<in> E\\<close> by blast\n    qed\n  qed\n\n  then have \"card {w \\<in> V. {v, w} \\<in> E} = card {e \\<in> E. v \\<in> e}\"\n    using bij_betw_same_card by auto\n\n  then show ?thesis\n    unfolding deg_def neighborhood_def by simp\nqed\n\nlemma sum_deg: \"(\\<Sum>v \\<in> V. deg v) = 2 * card E\"\n  oops\n\nlemma even_edges_odd: \"even (card {v \\<in> V. odd (deg v)})\"\n  oops\n\nlemma same_deg: \"card V \\<ge> 2 \\<Longrightarrow> \\<exists>v \\<in> V. \\<exists>w \\<in> V. v \\<noteq> w \\<and> deg v = deg w\"\n  oops\n\nsubsection \\<open>Subgraphs and Isomorphism\\<close>\n\ndefinition subgraph :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\" where\n  \"subgraph W F \\<equiv> graph (W, F) \\<and> W \\<subseteq> V \\<and> F \\<subseteq> E\"\n\ndefinition induced_subgraph :: \"'a set \\<Rightarrow> 'a set \\<times> 'a set set\" where\n  \"induced_subgraph W \\<equiv> (V \\<inter> W, {e \\<in> E. e \\<subseteq> W})\"\n\ndefinition isomorphic :: \"'b set \\<Rightarrow> 'b set set \\<Rightarrow> bool\" where\n  \"isomorphic W F \\<equiv> graph (W, F) \\<and> (\\<exists>f. \\<forall>v \\<in> V. \\<forall>w \\<in> V. {v, w} \\<in> E \\<longleftrightarrow> {f v, f w} \\<in> F)\"\n\nend\n\nsubsection \\<open>Notation\\<close>\n\nabbreviation supgraph :: \"'a graph \\<Rightarrow> 'a graph \\<Rightarrow> bool\" (infix \"\\<subseteq>\\<^sub>G\" 50) where\n  \"G \\<subseteq>\\<^sub>G H \\<equiv> graph.subgraph H (fst G) (snd G)\"\n\nabbreviation induced_subgraph :: \"'a graph \\<Rightarrow> 'a set \\<Rightarrow> 'a graph\" (\"_[_](\\<^sub>G)\" 51) where\n  \"G[V]\\<^sub>G \\<equiv> graph.induced_subgraph G V\"\n\nabbreviation isomorphic :: \"'a graph \\<Rightarrow> 'b graph \\<Rightarrow> bool\" (infix \"\\<sim>\\<^sub>G\" 50) where\n  \"G \\<sim>\\<^sub>G H \\<equiv> graph.isomorphic G (fst H) (snd H)\"\n\n\nlemma \"G[V]\\<^sub>G \\<subseteq>\\<^sub>G G\"\n  oops\n\nlemma isomorphic_comm: \"G \\<sim>\\<^sub>G H \\<longleftrightarrow> H \\<sim>\\<^sub>G G\"\n  oops\n\nlemma isomorphic_card:\n  assumes\n    \"graph (V, E)\"\n  assumes\n    \"graph (W, F)\"\n  assumes\n    \"(V, E) \\<sim>\\<^sub>G (W, F)\"\n  shows\n    \"card V = card W\" and \"card E = card F\"\nproof -\n  show \"card V = card W\" sorry\nnext\n  show \"card E = card F\" sorry\nqed\n\nsubsection \\<open>Special graphs\\<close>\n\ndefinition path :: \"nat \\<Rightarrow> nat graph\" (\"P\\<^sub>G _\" 1) where\n  \"path n = ({1..n}, {{i, i + 1} | i. i \\<in> {1..n-1}})\"\n\ndefinition circle :: \"nat \\<Rightarrow> nat graph\" (\"C\\<^sub>G _\") where\n  \"circle n \\<equiv> ({1..n}, {{i, i + 1} | i. i \\<in> {1..n-1}} \\<union> {{1, n}})\"\n\ndefinition complete :: \"nat \\<Rightarrow> nat graph\" (\"K\\<^sub>G _\") where\n  \"complete n = ({1..n}, {{v, w} | v w. v \\<in> {1..n} \\<and> w \\<in> {1..n} \\<and> v \\<noteq> w})\"\n\n\n\nlemma[simp]: \"graph (C\\<^sub>G n)\"\n  sorry\n\nlemma[simp]: \"graph (K\\<^sub>G n)\"\n  sorry\n\nlemma empty_edges[simp]: \"finite V \\<Longrightarrow> V \\<noteq> {} \\<Longrightarrow> graph (V, {})\"\n  unfolding graph_def by simp\n\ncontext graph\nbegin\n\ndefinition path :: bool where\n  \"path \\<equiv> \\<exists>n. G \\<sim>\\<^sub>G (P\\<^sub>G n)\"\n\ndefinition circle :: bool where\n  \"circle \\<equiv> \\<exists>n \\<ge> 3. G \\<sim>\\<^sub>G (C\\<^sub>G n)\"\n\ndefinition complete :: bool where\n  \"complete \\<equiv> \\<exists>n. G \\<sim>\\<^sub>G (K\\<^sub>G n)\"\n\ndefinition acyclic :: bool where\n  \"acyclic \\<equiv> \\<forall>H. H \\<subseteq>\\<^sub>G G \\<longrightarrow> \\<not> graph.circle H\"\n\ndefinition connected :: bool where\n  \"connected \\<equiv> undefined\"\n\ndefinition tree :: bool where\n  \"tree \\<equiv> acyclic \\<and> connected\"\n\ndefinition spanning_tree :: \"'a graph \\<Rightarrow> bool\" where\n  \"spanning_tree T \\<equiv> T \\<subseteq>\\<^sub>G G \\<and> graph.tree T \\<and> V = fst T\"\n\nlemma connected_spanning_tree: \"connected \\<longleftrightarrow> (\\<exists>T. spanning_tree T)\"\n  oops\n\nend\n\n\nend", "meta": {"author": "Benestar", "repo": "isabelle-adm", "sha": "e464252c9ac80b7aa55f5970b8e48a4311a376d8", "save_path": "github-repos/isabelle/Benestar-isabelle-adm", "path": "github-repos/isabelle/Benestar-isabelle-adm/isabelle-adm-e464252c9ac80b7aa55f5970b8e48a4311a376d8/src/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7890278583623878}}
{"text": "\n(* Author: Florian Haftmann, TU Muenchen *)\n\nsection {* Comparing growth of functions on natural numbers by a preorder relation *}\n\ntheory Function_Growth\nimports Main Preorder Discrete\nbegin\n\nsubsection {* Motivation *}\n\ntext {*\n  When comparing growth of functions in computer science, it is common to adhere\n  on Landau Symbols (``O-Notation'').  However these come at the cost of notational\n  oddities, particularly writing @{text \"f = O(g)\"} for @{text \"f \\<in> O(g)\"} etc.\n  \n  Here we suggest a different way, following Hardy (G.~H.~Hardy and J.~E.~Littlewood,\n  Some problems of Diophantine approximation, Acta Mathematica 37 (1914), p.~225).\n  We establish a quasi order relation @{text \"\\<lesssim>\"} on functions such that\n  @{text \"f \\<lesssim> g \\<longleftrightarrow> f \\<in> O(g)\"}.  From a didactic point of view, this does not only\n  avoid the notational oddities mentioned above but also emphasizes the key insight\n  of a growth hierarchy of functions:\n  @{text \"(\\<lambda>n. 0) \\<lesssim> (\\<lambda>n. k) \\<lesssim> Discrete.log \\<lesssim> Discrete.sqrt \\<lesssim> id \\<lesssim> \\<dots>\"}.\n*}\n\nsubsection {* Model *}\n\ntext {*\n  Our growth functions are of type @{text \"\\<nat> \\<Rightarrow> \\<nat>\"}.  This is different\n  to the usual conventions for Landau symbols for which @{text \"\\<real> \\<Rightarrow> \\<real>\"}\n  would be appropriate, but we argue that @{text \"\\<real> \\<Rightarrow> \\<real>\"} is more\n  appropriate for analysis, whereas our setting is discrete.\n\n  Note that we also restrict the additional coefficients to @{text \\<nat>}, something\n  we discuss at the particular definitions.\n*}\n\nsubsection {* The @{text \"\\<lesssim>\"} relation *}\n\ndefinition less_eq_fun :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" (infix \"\\<lesssim>\" 50)\nwhere\n  \"f \\<lesssim> g \\<longleftrightarrow> (\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m)\"\n\ntext {*\n  This yields @{text \"f \\<lesssim> g \\<longleftrightarrow> f \\<in> O(g)\"}.  Note that @{text c} is restricted to\n  @{text \\<nat>}.  This does not pose any problems since if @{text \"f \\<in> O(g)\"} holds for\n  a @{text \"c \\<in> \\<real>\"}, it also holds for @{text \"\\<lceil>c\\<rceil> \\<in> \\<nat>\"} by transitivity.\n*}\n\nlemma less_eq_funI [intro?]:\n  assumes \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\"\n  shows \"f \\<lesssim> g\"\n  unfolding less_eq_fun_def by (rule assms)\n\nlemma not_less_eq_funI:\n  assumes \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * g m < f m\"\n  shows \"\\<not> f \\<lesssim> g\"\n  using assms unfolding less_eq_fun_def linorder_not_le [symmetric] by blast\n\nlemma less_eq_funE [elim?]:\n  assumes \"f \\<lesssim> g\"\n  obtains n c where \"c > 0\" and \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c * g m\"\n  using assms unfolding less_eq_fun_def by blast\n\nlemma not_less_eq_funE:\n  assumes \"\\<not> f \\<lesssim> g\" and \"c > 0\"\n  obtains m where \"m > n\" and \"c * g m < f m\"\n  using assms unfolding less_eq_fun_def linorder_not_le [symmetric] by blast\n\n\nsubsection {* The @{text \"\\<approx>\"} relation, the equivalence relation induced by @{text \"\\<lesssim>\"} *}\n\ndefinition equiv_fun :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" (infix \"\\<cong>\" 50)\nwhere\n  \"f \\<cong> g \\<longleftrightarrow>\n    (\\<exists>c\\<^sub>1>0. \\<exists>c\\<^sub>2>0. \\<exists>n. \\<forall>m>n. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m)\"\n\ntext {*\n  This yields @{text \"f \\<cong> g \\<longleftrightarrow> f \\<in> \\<Theta>(g)\"}.  Concerning @{text \"c\\<^sub>1\"} and @{text \"c\\<^sub>2\"}\n  restricted to @{typ nat}, see note above on @{text \"(\\<lesssim>)\"}.\n*}\n\nlemma equiv_funI [intro?]:\n  assumes \"\\<exists>c\\<^sub>1>0. \\<exists>c\\<^sub>2>0. \\<exists>n. \\<forall>m>n. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n  shows \"f \\<cong> g\"\n  unfolding equiv_fun_def by (rule assms)\n\nlemma not_equiv_funI:\n  assumes \"\\<And>c\\<^sub>1 c\\<^sub>2 n. c\\<^sub>1 > 0 \\<Longrightarrow> c\\<^sub>2 > 0 \\<Longrightarrow>\n    \\<exists>m>n. c\\<^sub>1 * f m < g m \\<or> c\\<^sub>2 * g m < f m\"\n  shows \"\\<not> f \\<cong> g\"\n  using assms unfolding equiv_fun_def linorder_not_le [symmetric] by blast\n\nlemma equiv_funE [elim?]:\n  assumes \"f \\<cong> g\"\n  obtains n c\\<^sub>1 c\\<^sub>2 where \"c\\<^sub>1 > 0\" and \"c\\<^sub>2 > 0\"\n    and \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n  using assms unfolding equiv_fun_def by blast\n\nlemma not_equiv_funE:\n  fixes n c\\<^sub>1 c\\<^sub>2\n  assumes \"\\<not> f \\<cong> g\" and \"c\\<^sub>1 > 0\" and \"c\\<^sub>2 > 0\"\n  obtains m where \"m > n\"\n    and \"c\\<^sub>1 * f m < g m \\<or> c\\<^sub>2 * g m < f m\"\n  using assms unfolding equiv_fun_def linorder_not_le [symmetric] by blast\n\n\nsubsection {* The @{text \"\\<prec>\"} relation, the strict part of @{text \"\\<lesssim>\"} *}\n\ndefinition less_fun :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" (infix \"\\<prec>\" 50)\nwhere\n  \"f \\<prec> g \\<longleftrightarrow> f \\<lesssim> g \\<and> \\<not> g \\<lesssim> f\"\n\nlemma less_funI:\n  assumes \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\"\n    and \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * f m < g m\"\n  shows \"f \\<prec> g\"\n  using assms unfolding less_fun_def less_eq_fun_def linorder_not_less [symmetric] by blast\n\nlemma not_less_funI:\n  assumes \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * g m < f m\"\n    and \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. g m \\<le> c * f m\"\n  shows \"\\<not> f \\<prec> g\"\n  using assms unfolding less_fun_def less_eq_fun_def linorder_not_less [symmetric] by blast\n\nlemma less_funE [elim?]:\n  assumes \"f \\<prec> g\"\n  obtains n c where \"c > 0\" and \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c * g m\"\n    and \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * f m < g m\"\nproof -\n  from assms have \"f \\<lesssim> g\" and \"\\<not> g \\<lesssim> f\" by (simp_all add: less_fun_def)\n  from `f \\<lesssim> g` obtain n c where *:\"c > 0\" \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c * g m\"\n    by (rule less_eq_funE) blast\n  { fix c n :: nat\n    assume \"c > 0\"\n    with `\\<not> g \\<lesssim> f` obtain m where \"m > n\" \"c * f m < g m\"\n      by (rule not_less_eq_funE) blast\n    then have **: \"\\<exists>m>n. c * f m < g m\" by blast\n  } note ** = this\n  from * ** show thesis by (rule that)\nqed\n\nlemma not_less_funE:\n  assumes \"\\<not> f \\<prec> g\" and \"c > 0\"\n  obtains m where \"m > n\" and \"c * g m < f m\"\n    | d q where \"\\<And>m. d > 0 \\<Longrightarrow> m > q \\<Longrightarrow> g q \\<le> d * f q\"\n  using assms unfolding less_fun_def linorder_not_less [symmetric] by blast\n\ntext {*\n  I did not find a proof for @{text \"f \\<prec> g \\<longleftrightarrow> f \\<in> o(g)\"}.  Maybe this only\n  holds if @{text f} and/or @{text g} are of a certain class of functions.\n  However @{text \"f \\<in> o(g) \\<longrightarrow> f \\<prec> g\"} is provable, and this yields a\n  handy introduction rule.\n\n  Note that D. Knuth ignores @{text o} altogether.  So what \\dots\n\n  Something still has to be said about the coefficient @{text c} in\n  the definition of @{text \"(\\<prec>)\"}.  In the typical definition of @{text o},\n  it occurs on the \\emph{right} hand side of the @{text \"(>)\"}.  The reason\n  is that the situation is dual to the definition of @{text O}: the definition\n  works since @{text c} may become arbitrary small.  Since this is not possible\n  within @{term \\<nat>}, we push the coefficient to the left hand side instead such\n  that it become arbitrary big instead.\n*}\n\nlemma less_fun_strongI:\n  assumes \"\\<And>c. c > 0 \\<Longrightarrow> \\<exists>n. \\<forall>m>n. c * f m < g m\"\n  shows \"f \\<prec> g\"\nproof (rule less_funI)\n  have \"1 > (0::nat)\" by simp\n  from assms `1 > 0` have \"\\<exists>n. \\<forall>m>n. 1 * f m < g m\" .\n  then obtain n where *: \"\\<And>m. m > n \\<Longrightarrow> 1 * f m < g m\" by blast\n  have \"\\<forall>m>n. f m \\<le> 1 * g m\"\n  proof (rule allI, rule impI)\n    fix m\n    assume \"m > n\"\n    with * have \"1 * f m < g m\" by simp\n    then show \"f m \\<le> 1 * g m\" by simp\n  qed\n  with `1 > 0` show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\" by blast\n  fix c n :: nat\n  assume \"c > 0\"\n  with assms obtain q where \"\\<And>m. m > q \\<Longrightarrow> c * f m < g m\" by blast\n  then have \"c * f (Suc (q + n)) < g (Suc (q + n))\" by simp\n  moreover have \"Suc (q + n) > n\" by simp\n  ultimately show \"\\<exists>m>n. c * f m < g m\" by blast\nqed\n\n\nsubsection {* @{text \"\\<lesssim>\"} is a preorder *}\n\ntext {* This yields all lemmas relating @{text \"\\<lesssim>\"}, @{text \"\\<prec>\"} and @{text \"\\<cong>\"}. *}\n\ninterpretation fun_order: preorder_equiv less_eq_fun less_fun\n  where \"preorder_equiv.equiv less_eq_fun = equiv_fun\"\nproof -\n  interpret preorder: preorder_equiv less_eq_fun less_fun\n  proof\n    fix f g h\n    show \"f \\<lesssim> f\"\n    proof\n      have \"\\<exists>n. \\<forall>m>n. f m \\<le> 1 * f m\" by auto\n      then show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * f m\" by blast\n    qed\n    show \"f \\<prec> g \\<longleftrightarrow> f \\<lesssim> g \\<and> \\<not> g \\<lesssim> f\"\n      by (fact less_fun_def)\n    assume \"f \\<lesssim> g\" and \"g \\<lesssim> h\"\n    show \"f \\<lesssim> h\"\n    proof\n      from `f \\<lesssim> g` obtain n\\<^sub>1 c\\<^sub>1\n        where \"c\\<^sub>1 > 0\" and P\\<^sub>1: \"\\<And>m. m > n\\<^sub>1 \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m\"\n        by rule blast\n      from `g \\<lesssim> h` obtain n\\<^sub>2 c\\<^sub>2\n        where \"c\\<^sub>2 > 0\" and P\\<^sub>2: \"\\<And>m. m > n\\<^sub>2 \\<Longrightarrow> g m \\<le> c\\<^sub>2 * h m\"\n        by rule blast\n      have \"\\<forall>m>max n\\<^sub>1 n\\<^sub>2. f m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume Q: \"m > max n\\<^sub>1 n\\<^sub>2\"\n        from P\\<^sub>1 Q have *: \"f m \\<le> c\\<^sub>1 * g m\" by simp\n        from P\\<^sub>2 Q have \"g m \\<le> c\\<^sub>2 * h m\" by simp\n        with `c\\<^sub>1 > 0` have \"c\\<^sub>1 * g m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\" by simp\n        with * show \"f m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\" by (rule order_trans)\n      qed\n      then have \"\\<exists>n. \\<forall>m>n. f m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\" by rule\n      moreover from `c\\<^sub>1 > 0` `c\\<^sub>2 > 0` have \"c\\<^sub>1 * c\\<^sub>2 > 0\" by simp\n      ultimately show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * h m\" by blast\n    qed\n  qed\n  from preorder.preorder_equiv_axioms show \"class.preorder_equiv less_eq_fun less_fun\" .\n  show \"preorder_equiv.equiv less_eq_fun = equiv_fun\"\n  proof (rule ext, rule ext, unfold preorder.equiv_def)\n    fix f g\n    show \"f \\<lesssim> g \\<and> g \\<lesssim> f \\<longleftrightarrow> f \\<cong> g\"\n    proof\n      assume \"f \\<cong> g\"\n      then obtain n c\\<^sub>1 c\\<^sub>2 where \"c\\<^sub>1 > 0\" and \"c\\<^sub>2 > 0\"\n        and *: \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n        by rule blast\n      have \"\\<forall>m>n. f m \\<le> c\\<^sub>1 * g m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume \"m > n\"\n        with * show \"f m \\<le> c\\<^sub>1 * g m\" by simp\n      qed\n      with `c\\<^sub>1 > 0` have \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\" by blast\n      then have \"f \\<lesssim> g\" ..\n      have \"\\<forall>m>n. g m \\<le> c\\<^sub>2 * f m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume \"m > n\"\n        with * show \"g m \\<le> c\\<^sub>2 * f m\" by simp\n      qed\n      with `c\\<^sub>2 > 0` have \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. g m \\<le> c * f m\" by blast\n      then have \"g \\<lesssim> f\" ..\n      from `f \\<lesssim> g` and `g \\<lesssim> f` show \"f \\<lesssim> g \\<and> g \\<lesssim> f\" ..\n    next\n      assume \"f \\<lesssim> g \\<and> g \\<lesssim> f\"\n      then have \"f \\<lesssim> g\" and \"g \\<lesssim> f\" by auto\n      from `f \\<lesssim> g` obtain n\\<^sub>1 c\\<^sub>1 where \"c\\<^sub>1 > 0\"\n        and P\\<^sub>1: \"\\<And>m. m > n\\<^sub>1 \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m\" by rule blast\n      from `g \\<lesssim> f` obtain n\\<^sub>2 c\\<^sub>2 where \"c\\<^sub>2 > 0\"\n        and P\\<^sub>2: \"\\<And>m. m > n\\<^sub>2 \\<Longrightarrow> g m \\<le> c\\<^sub>2 * f m\" by rule blast\n      have \"\\<forall>m>max n\\<^sub>1 n\\<^sub>2. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume Q: \"m > max n\\<^sub>1 n\\<^sub>2\"\n        from P\\<^sub>1 Q have \"f m \\<le> c\\<^sub>1 * g m\" by simp\n        moreover from P\\<^sub>2 Q have \"g m \\<le> c\\<^sub>2 * f m\" by simp\n        ultimately show \"f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\" ..\n      qed\n      with `c\\<^sub>1 > 0` `c\\<^sub>2 > 0` have \"\\<exists>c\\<^sub>1>0. \\<exists>c\\<^sub>2>0. \\<exists>n.\n        \\<forall>m>n. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\" by blast\n      then show \"f \\<cong> g\" ..\n    qed\n  qed\nqed\n\n\nsubsection {* Simple examples *}\n\ntext {*\n  Most of these are left as constructive exercises for the reader.  Note that additional\n  preconditions to the functions may be necessary.  The list here is by no means to be\n  intended as complete construction set for typical functions, here surely something\n  has to be added yet.\n*}\n\ntext {* @{prop \"(\\<lambda>n. f n + k) \\<cong> f\"} *}\n\ntext {* @{prop \"(\\<lambda>n. Suc k * f n) \\<cong> f\"} *}\n\nlemma \"f \\<lesssim> (\\<lambda>n. f n + g n)\"\n  by rule auto\n\nlemma \"(\\<lambda>_. 0) \\<prec> (\\<lambda>n. Suc k)\"\n  by (rule less_fun_strongI) auto\n\nlemma \"(\\<lambda>_. k) \\<prec> Discrete.log\"\nproof (rule less_fun_strongI)\n  fix c :: nat\n  have \"\\<forall>m>2 ^ (Suc (c * k)). c * k < Discrete.log m\"\n  proof (rule allI, rule impI)\n    fix m :: nat\n    assume \"2 ^ Suc (c * k) < m\"\n    then have \"2 ^ Suc (c * k) \\<le> m\" by simp\n    with log_mono have \"Discrete.log (2 ^ (Suc (c * k))) \\<le> Discrete.log m\"\n      by (blast dest: monoD)\n    moreover have \"c * k < Discrete.log (2 ^ (Suc (c * k)))\" by simp\n    ultimately show \"c * k < Discrete.log m\" by auto\n  qed\n  then show \"\\<exists>n. \\<forall>m>n. c * k < Discrete.log m\" ..\nqed\n  \ntext {* @{prop \"Discrete.log \\<prec> Discrete.sqrt\"} *}\n\nlemma \"Discrete.sqrt \\<prec> id\"\nproof (rule less_fun_strongI)\n  fix c :: nat\n  assume \"0 < c\"\n  have \"\\<forall>m>(Suc c)\\<^sup>2. c * Discrete.sqrt m < id m\"\n  proof (rule allI, rule impI)\n    fix m\n    assume \"(Suc c)\\<^sup>2 < m\"\n    then have \"(Suc c)\\<^sup>2 \\<le> m\" by simp\n    with mono_sqrt have \"Discrete.sqrt ((Suc c)\\<^sup>2) \\<le> Discrete.sqrt m\" by (rule monoE)\n    then have \"Suc c \\<le> Discrete.sqrt m\" by simp\n    then have \"c < Discrete.sqrt m\" by simp\n    moreover from `(Suc c)\\<^sup>2 < m` have \"Discrete.sqrt m > 0\" by simp\n    ultimately have \"c * Discrete.sqrt m < Discrete.sqrt m * Discrete.sqrt m\" by simp\n    also have \"\\<dots> \\<le> m\" by (simp add: power2_eq_square [symmetric])\n    finally show \"c * Discrete.sqrt m < id m\" by simp\n  qed\n  then show \"\\<exists>n. \\<forall>m>n. c * Discrete.sqrt m < id m\" ..\nqed\n\nlemma \"id \\<prec> (\\<lambda>n. n\\<^sup>2)\"\n  by (rule less_fun_strongI) (auto simp add: power2_eq_square)\n\nlemma \"(\\<lambda>n. n ^ k) \\<prec> (\\<lambda>n. n ^ Suc k)\"\n  by (rule less_fun_strongI) auto\n\ntext {* @{prop \"(\\<lambda>n. n ^ k) \\<prec> (\\<lambda>n. 2 ^ n)\"} *}\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Function_Growth.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7889581409865217}}
{"text": "theory Homework04\n  imports \"BST_Demo\"\nbegin\n\n\ndatatype 'a rtree = Leaf|Node \"'a rtree\" nat 'a \"'a rtree\"\n\nfun num_nodes :: \"'a rtree \\<Rightarrow> nat\" where\n  \"num_nodes Leaf = 0\"|\n  \"num_nodes (Node l a b r) = num_nodes l + num_nodes r + 1\"\n\n\nfun rbst :: \"'a::linorder rtree \\<Rightarrow> bool\" where\n  \"rbst Leaf = True\"|\n  \"rbst (Node l a b r) = \n    ((rbst l)\\<and>\n    (\\<forall>x\\<in>set_rtree l. x<b)\\<and>\n    (a = num_nodes l)\\<and>\n    (\\<forall>x\\<in>set_rtree r. b<x)\\<and>\n    (rbst r))\"\n  \n\nvalue \"rbst (Node (Node Leaf (0::nat) (1::nat) Leaf) (1::nat) 2 (Node Leaf (0::nat) 3 Leaf))\"\nvalue \"set_rtree(Node (Node Leaf (0::nat) (1::nat) Leaf) (1::nat) 2 (Node Leaf (0::nat) 3 Leaf))\"\n\nfun rins :: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> 'a rtree\" where\n  \"rins x Leaf = (Node Leaf 0 x Leaf)\"|\n  \"rins x (Node l a b r) = (if x<b then (Node (rins x l) (Suc a) b r) else (Node l a b (rins x r)))\"\n\nvalue \"rins 5 (Node (Node Leaf (0::nat) (1::nat) Leaf) (1::nat) 2 (Node Leaf (0::nat) 3 Leaf))\"\n\nlemma rins_set[simp]: \"set_rtree (rins x t) = insert x (set_rtree t)\"\n  apply(induction t)\n   apply auto\n  done\n\nlemma aux1[simp]:  \"(x\\<notin>set_rtree t) \\<Longrightarrow>num_nodes (rins x t) = Suc(num_nodes t)\"\n  apply(induction t arbitrary:x)\n   apply auto\n  done\n\nlemma aux[simp]: \"rbst(Node l a b r) \\<Longrightarrow> (num_nodes l = a) \"\n  apply auto\n  done\n\n\nlemma \"x\\<notin>set_rtree t \\<Longrightarrow> rbst t \\<Longrightarrow> rbst (rins x t)\"\n  apply(induction t arbitrary: x rule:rbst.induct)\n   apply auto\n  done\n\nfun risin:: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> bool\" where\n  \"risin _ Leaf = False\"|\n  \"risin x (Node l a b r) = ((x=b)\\<or>(risin x l)\\<or>(risin x r))\"\n\nlemma \"rbst t \\<Longrightarrow> risin x t \\<longleftrightarrow> x\\<in>set_rtree t\"\n  apply(induction t)\n   apply auto\n  done\n\nfun inorder :: \"'a rtree \\<Rightarrow> 'a list\" where\n  \"inorder Leaf = []\"|\n  \"inorder (Node l a b r) = inorder l @ b # inorder r\"\n\nfun rank:: \"'a::linorder \\<Rightarrow> _\" where\n\n\n\n\n\nend\n", "meta": {"author": "amartyads", "repo": "functional-data-structures-HW", "sha": "df9edfd02bda931a0633f0e66bf8e32d7347902b", "save_path": "github-repos/isabelle/amartyads-functional-data-structures-HW", "path": "github-repos/isabelle/amartyads-functional-data-structures-HW/functional-data-structures-HW-df9edfd02bda931a0633f0e66bf8e32d7347902b/04/Homework04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7888400324740384}}
{"text": "theory HSV_chapter4 imports Complex_Main begin\n\n(* Triangle numbers *)\nfun triangle :: \"nat \\<Rightarrow> nat\" where\n  \"triangle n = (if n = 0 then 0 else n + triangle (n-1))\"\n\nvalue \"triangle 1\"\nvalue \"triangle 2\"\nvalue \"triangle 3\"\n\ntheorem triangle_closed_form: \"triangle n = (n+1) * n div 2\" \n  apply (induct n)\n  apply simp+\n  done\n\n(* Tetrahedral numbers *)\nfun tet :: \"nat \\<Rightarrow> nat\" where\n  \"tet n = (if n = 0 then 0 else triangle n + tet (n-1))\"\n\nvalue \"tet 1\" (* 1 *)\nvalue \"tet 2\" (* 4 *)\nvalue \"tet 3\" (* 10 *)\nvalue \"tet 4\" (* 20 *)\nvalue \"tet 5\" (* 35 *)\nvalue \"tet 6\" (* 56 *)\n\nfind_theorems \"_ div ?x + _ div ?x\"\nthm div_add\n\n(* Proving that closed form is equivalent to recursive definition *)\ntheorem \"tet n = ((n + 2) * (n + 1) * n) div 6\"\nproof (induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc k) \n\n  (* induction hypothesis *)\n  assume IH: \"tet k = (k + 2) * (k + 1) * k div 6\"\n\n  (* establish a useful fact and label it \"*\" *)\n  have \"2 dvd (k + 2) * (k + 1)\" by simp\n  hence *: \"6 dvd (k + 2) * (k + 1) * 3\" by presburger\n\n  (* establish another useful fact and label it \"**\" *)\n  have \"2 dvd (k + 2) * (k + 1) * k\" by simp\n  moreover have \"3 dvd (k + 2) * (k + 1) * k\"\n  proof - \n    {\n      assume \"k mod 3 = 0\"\n      hence \"3 dvd k\" by presburger\n      hence \"3 dvd (k + 2) * (k + 1) * k\" by fastforce\n    } moreover { \n      assume \"k mod 3 = 1\"\n      hence \"3 dvd (k + 2)\" by presburger\n      hence \"3 dvd (k + 2) * (k + 1) * k\" by fastforce\n    } moreover { \n      assume \"k mod 3 = 2\"\n      hence \"3 dvd (k + 1)\" by presburger\n      hence \"3 dvd (k + 2) * (k + 1) * k\" by fastforce\n    } ultimately\n    show \"3 dvd (k + 2) * (k + 1) * k\" by linarith\n  qed\n  ultimately have **: \"6 dvd (k + 2) * (k + 1) * k\" by presburger\n\n  (* the actual proof *)\n  have \"tet (Suc k) = triangle (Suc k) + tet k\" \n    by simp\n  also have \"... = (k + 2) * (k + 1) div 2 + tet k\" \n    using triangle_closed_form by simp\n  also have \"... = (k + 2) * (k + 1) div 2 + (k + 2) * (k + 1) * k div 6\" \n    using IH by simp\n  also have \"... = ((k + 2) * (k + 1) * 3 + (k + 2) * (k + 1) * k) div 6\" \n    using div_add[OF * **] by simp\n  also have \"... = (k + 2) * (k + 1) * (k + 3) div 6\" \n    by (simp add: distrib_left)\n  also have \"... = (Suc k + 2) * (Suc k + 1) * Suc k div 6\"\n    by (metis One_nat_def Suc_1 add.commute add_Suc_shift mult.assoc \n        mult.commute numeral_3_eq_3 plus_1_eq_Suc)\n  finally show ?case by assumption\nqed\n\nend", "meta": {"author": "johnwickerson", "repo": "HSV", "sha": "54be339e0fac44ee7af8ebba9dab10d778164ea3", "save_path": "github-repos/isabelle/johnwickerson-HSV", "path": "github-repos/isabelle/johnwickerson-HSV/HSV-54be339e0fac44ee7af8ebba9dab10d778164ea3/isabelle/HSV_chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.78853150768582}}
{"text": "(*\n  Author: Fred Kurz\n*)\ntheory List_Supplement\nimports Main\nbegin\n\nlemma list_foot: \n  assumes \"l \\<noteq> []\" \n  obtains y ys where \"l = ys @ [y]\"\nproof -\n  {\n    assume a: \"l \\<noteq> []\"\n    have \"\\<exists>y ys. l = ys @ [y]\" \n      using a \n      proof (induction l)\n        case (Cons a l)\n        then show ?case \n          proof (cases \"l = []\")\n            case True\n            have \"[] @ [a] = a # l\" \n              using True\n              by simp\n            thus ?thesis \n              using Cons.prems(1)\n              by simp\n          next\n            case False\n            thm Cons\n            then obtain y ys where \"l = ys @ [y]\" \n              using Cons.IH\n              by blast\n            then have \"a # l = a # ys @ [y]\" \n              by blast\n            thus ?thesis\n              by fastforce\n          qed\n      qed simp\n  }\n  thus ?thesis \n    using assms that \n    by blast\nqed\n\nlemma list_ex_intersection: \"list_ex (\\<lambda>v. list_ex ((=) v) ys) xs \\<longleftrightarrow> set xs \\<inter> set ys \\<noteq> {}\"\nproof -\n  {\n    assume \"list_ex (\\<lambda>v. list_ex ((=) v) ys) xs\"\n    then have \"\\<exists>v \\<in> set xs. list_ex ((=) v) ys\" \n      using list_ex_iff\n      by fast\n    moreover have \"\\<forall>v. list_ex ((=) v) ys = (\\<exists>v' \\<in> set ys. v = v')\" \n      using list_ex_iff\n      by blast\n    ultimately have \"\\<exists>v \\<in> set xs. (\\<exists>v' \\<in> set ys. v = v')\"\n      by blast\n    then obtain v v' where \"v \\<in> set xs\" and \"v' \\<in> set ys\" and \"v = v'\"\n      by blast\n    then have \"set xs \\<inter> set ys \\<noteq> {}\"\n      by blast\n  } moreover {\n    assume  \"set xs \\<inter> set ys \\<noteq> {}\"\n    then obtain v v' where \"v \\<in> set xs\" and \"v' \\<in> set ys\" and \"v = v'\"\n      by blast\n    then have \"list_ex (\\<lambda>v. \\<exists>v' \\<in> set ys. v = v') xs\" \n      using list_ex_iff \n      by fast\n    moreover have \"\\<forall>v. (\\<exists>v' \\<in> set ys. v = v') = list_ex ((=) v) ys\" \n      using list_ex_iff\n      by blast\n    ultimately have \"list_ex (\\<lambda>v. list_ex ((=) v) ys) xs\" \n      by force\n  } ultimately show ?thesis\n    by blast\nqed\n\nlemma length_map_upt: \"length (map f [a..<b]) = b - a\" \nproof -\n  have \"length [a..<b] = b - a\" \n    using length_upt\n    by blast\n  moreover have \"length (map f [a..<b]) = length [a..<b]\"\n    by simp\n  ultimately show ?thesis\n    by argo\nqed\n\nlemma not_list_ex_equals_list_all_not: \"(\\<not>list_ex P xs) = list_all (\\<lambda>x. \\<not>P x) xs\" \nproof -\n  have \"(\\<not>list_ex P xs) = (\\<not>Bex (set xs) P)\"\n    using list_ex_iff \n    by blast\n  also have \"\\<dots> = Ball (set xs) (\\<lambda>x. \\<not>P x)\"\n    by blast \n  finally show ?thesis\n    by (simp add: Ball_set_list_all)\nqed\n\nlemma element_of_subseqs_then_subset:\n  assumes \"l \\<in> set (subseqs l')\" \n  shows\"set l \\<subseteq> set l'\" \n  using assms\nproof (induction l' arbitrary: l)\n  case (Cons x l')\n  have \"set (subseqs (x # l')) = (Cons x) ` set (subseqs l') \\<union> set (subseqs l')\"\n    unfolding subseqs.simps(2) Let_def set_map set_append..\n  then consider (A) \"l \\<in> (Cons x) ` set (subseqs l')\"\n    | (B) \"l \\<in> set (subseqs l')\" \n    using Cons.prems\n    by blast\n  thus ?case \n    proof (cases)\n      case A\n      then obtain l'' where \"l'' \\<in> set (subseqs l')\" and \"l = x # l''\" \n        by blast\n      moreover have \"set l'' \\<subseteq> set l'\" \n        using Cons.IH[of l'', OF calculation(1)].\n      ultimately show ?thesis \n        by auto\n    next\n      case B\n      then show ?thesis \n        using Cons.IH\n        by auto\n    qed\nqed simp\n\n(* TODO rewrite using list comprehension \\<open>embed xs = [[x]. x \\<leftarrow> xs]\\<close> *)\ntext \\<open> Embed a list into a list of singleton lists. \\<close>\nprimrec embed :: \"'a list \\<Rightarrow> 'a list list\" \n  where \"embed [] = []\" \n  | \"embed (x # xs) = [x] # embed xs\"\n\nlemma set_of_embed_is: \"set (embed xs) = { [x] | x. x \\<in> set xs }\" \n  by (induction xs; force+)\n\nlemma concat_is_inverse_of_embed:\n  \"concat (embed xs) = xs\"\n  by (induction xs; simp)\n\nlemma embed_append[simp]: \"embed (xs @ ys) = embed xs @ embed ys\"\nproof (induction xs)\n  case (Cons x xs)\n  have \"embed (x # xs @ ys) = [x] # embed (xs @ ys)\" \n    try0\n    by simp\n  also have \"\\<dots> = [x] # (embed xs @ embed ys)\" \n    using Cons.IH \n    by simp\n  finally show ?case \n    by fastforce\nqed simp\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Verified_SAT_Based_AI_Planning/List_Supplement.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.8902942304882371, "lm_q1q2_score": 0.7884725995415289}}
{"text": "theory CS_Ch4\nimports Main \"./CS_Ch3\"\nbegin\n\n(* 4.1 *)\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\" |\n\"set (Node l v r) = (set l) \\<union> {v} \\<union> (set r)\"\n\n(* the hint says to use quantifiers. I initially tried doing this with a recursive definition for\n   the \"treele\" and \"treege\" but ran into issues trying to do the proof. I needed more lemmas than\n   I thought necessary. The set-based definition seems to work around this, probably by having all\n   the properties that need to be proved about custom functions implied by the quantifier and the\n   fanciness that 'auto' does. *)\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node l v r) = ((ord l) \\<and> (ord r) \\<and> (\\<forall>x\\<in>(set l). x \\<le> v) \\<and> (\\<forall>x\\<in>(set r). x \\<ge> v))\"\n\nfun ins :: \"int tree \\<Rightarrow> int \\<Rightarrow> int tree\" where\n\"ins Tip a = Node Tip a Tip\" |\n\"ins (Node l v r) a = (if a \\<le> v then Node (ins l a) v r else Node l v (ins r a))\"\n\nlemma ins_lem: \"set (ins t x) = {x} \\<union> set t\"\napply(induction t)\napply(auto)\ndone\n\nvalue \"ins (Node Tip (-1) Tip) 0\"\n\nlemma \"ord t \\<Longrightarrow> ord (ins t x)\"\napply(induction t arbitrary: x)\napply(auto simp add: ins_lem)\ndone\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0 : \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev(Suc(Suc(Suc(Suc 0))))\"\napply(rule evSS)\napply(rule evSS)\napply(rule ev0)\ndone\n\nlemma \"ev m \\<Longrightarrow> evn m\"\napply(induction rule: ev.induct)\nby(simp_all)\n\ndeclare ev.intros[simp, intro]\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\nby(simp_all)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\napply(induction rule: star.induct)\napply(assumption)\napply(metis step)\ndone\n\n(* 4.2 *)\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\nempty: \"palindrome []\" |\nsingleton: \"palindrome [a]\" |\nstep: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma palindrome_invariant_under_rev: \"palindrome xs \\<Longrightarrow> rev xs = xs\"\napply(induction xs rule: palindrome.induct)\napply(auto)\ndone\n\n(* 4.3 *)\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\n(* this lemma is required to prove the right-hand side of a subgoal, but we need to separate it\n   out to apply the rule induction *)\nlemma star'_rightmost_bit: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\napply(induction rule: star.induct)\napply(auto intro: star.refl star.step)\ndone\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\napply(induction rule: star'.induct)\napply(rule star.refl)\napply(auto simp add: star'_rightmost_bit)\ndone\n\n(* this lemma is required to reorder the implications to allow induction to proceed *)\nlemma star_reordered_bit: \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\napply(induction rule: star'.induct)\napply(auto intro: refl' step')\ndone\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\napply(induction rule: star.induct)\napply(auto simp add: star_reordered_bit intro: star'.refl')\ndone\n\n(* 4.4 *)\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\niter0: \"iter r 0 x x\" |\niterstep: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (n+1) x z\"\n\n(* the \"correction\" is the introduction of the existential. not sure what the \"implicit\"\n   meaning of a free variable is. I expect it to be a meta-\\<forall> though. *)\nlemma \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\napply(induction rule: star.induct)\napply(auto intro: iter0 iterstep)\ndone\n\n(* 4.5 *)\n\ndatatype alpha = a | b | c\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nempty: \"S []\" |\nfst: \"S s \\<Longrightarrow> S (a # s @ [b])\" |\nsnd: \"S s\\<^sub>1 \\<Longrightarrow> S s\\<^sub>2 \\<Longrightarrow> S (s\\<^sub>1 @ s\\<^sub>2)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nempty: \"T []\" |\nfst: \"T t\\<^sub>1 \\<Longrightarrow> T t\\<^sub>2 \\<Longrightarrow> T (t\\<^sub>1 @ [a] @ t\\<^sub>2 @ [b])\"\n\nlemma t_implies_s: \"T w \\<Longrightarrow> S w\"\napply(induction w rule: T.induct)\napply(auto intro: S.empty S.fst S.snd T.fst)\ndone\n\nlemma t_same_form_as_s: \"T s \\<Longrightarrow> T (a # s @ [b])\"\napply(induction s)\n(* thanks try! *)\napply(metis T.empty T.fst append_Nil append_Cons)\napply(metis T.empty T.fst append_Nil append_Cons)\ndone\n\nlemma t_append: \"T t\\<^sub>1 \\<Longrightarrow> T t\\<^sub>2 \\<Longrightarrow> T (t\\<^sub>2 @ t\\<^sub>1)\"\napply(induction t\\<^sub>1 rule: T.induct)\napply(simp)\n(* simplifying this subgoal causes metis to not terminate. additionally, trying to prove T (t\\<^sub>1 @ t\\<^sub>2)\n   also causes non-termintation. (at least, I assume it won't terminate, I left it running in the\n   background and forgot about it for a few hours... I'd be curious to dig deeper into the cause\n   of the non-termination. In fact, it's even sensitive to the order of the antecedents! *)\napply (metis append_assoc T.fst)\ndone\n\n(* but, this consequence is a straightforward unification with t_append! *)\nlemma \"T t\\<^sub>1 \\<Longrightarrow> T t\\<^sub>2 \\<Longrightarrow> T (t\\<^sub>1 @ t\\<^sub>2)\"\napply(rule t_append)\napply(simp_all)\ndone\n\nlemma s_implies_t: \"S w \\<Longrightarrow> T w\"\napply(induction w rule: S.induct)\napply(auto simp add: T.empty t_same_form_as_s t_append)\ndone\n\nlemma s_equiv_t: \"S w = T w\"\napply(auto simp add: s_implies_t t_implies_s)\ndone\n\n(* 4.6 *)\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\ninN: \"aval_rel (N n) s n\" |\ninV: \"s x = n \\<Longrightarrow> aval_rel (V x) s n\" |\ninPlus: \"aval_rel e\\<^sub>1 s v\\<^sub>1 \\<Longrightarrow> aval_rel e\\<^sub>2 s v\\<^sub>2 \\<Longrightarrow> aval_rel (Plus e\\<^sub>1 e\\<^sub>2) s (v\\<^sub>1 + v\\<^sub>2)\"\n\nlemma aval_rel_is_aval: \"aval_rel e s v \\<Longrightarrow> aval e s = v\"\napply(induction rule: aval_rel.induct)\napply(auto)\ndone\n\nlemma aval_is_aval_rel: \"aval e s = v \\<Longrightarrow> aval_rel e s v\"\napply(induction e arbitrary: v)\n(* The third subgoal here has a very interesting structure - the v is quantified in each antecedent,\n   separately from the v generated by the induction. This makes sense, but initially surprised me. *)\napply(auto intro: inN inV inPlus)\ndone\n\nlemma \"aval_rel e s v \\<longleftrightarrow> aval e s = v\"\napply(auto) (* split the \\<longleftrightarrow> *)\n(* if you try to do both of these at once, it will not terminate for obvious reasons *)\napply(auto simp add: aval_rel_is_aval)\napply(auto simp add: aval_is_aval_rel)\ndone\n\n(* 4.7 *)\n\n(* copying defn's to tear out the option *)\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk = n # stk\" |\n\"exec1 (LOAD x) s stk = (s x) # stk\" |\n\"exec1 ADD _ stk = (hd stk + hd2 stk) # tl2 stk\"\n\n(* I tried using Option.bind etc but I can't seem to get anything proven when I'm using it.\n   Expanding it manually works, though. Oh well. *)\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i # is) s stk = (exec is s (exec1 i s stk))\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e\\<^sub>1 e\\<^sub>2) = comp e\\<^sub>1 @ comp e\\<^sub>2 @ [ADD]\"\n\n(* I originally tried to formulate these lemmas like,\n\"case (exec is\\<^sub>1 s stk) of Some stk' \\<Rightarrow> exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s stk' \n                        | None \\<Rightarrow> exec (is\\<^sub>1 @ is\\<^sub>2) s stk = None\"\nbut was unable to prove them. *)\nlemma exec_append: \"exec is\\<^sub>1 s stk = stk' \\<Longrightarrow> exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s stk'\"\napply(induction is\\<^sub>1 arbitrary: stk)\napply(auto)\ndone\n\nlemma \"exec (comp e) s stk =  aval e s # stk\"\napply(induction e arbitrary: stk)\napply(auto simp add: exec_append)\ndone\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\nokempty: \"ok n [] n\" |\nokLOADI: \"ok n is n' \\<Longrightarrow> ok n (is @ [LOADI _]) (Suc n')\" |\nokLOAD: \"ok n is n' \\<Longrightarrow> ok n (is @ [LOAD _]) (Suc n')\" |\n(* protip: unbound variables are universally quantified. So if you say, for example is @ [PLUS], you\n   gotta prove that sucker for all values of PLUS. Pay attention to the quantifiers when things\n   don't work as expected! *)\nokADD: \"ok n is (Suc (Suc n')) \\<Longrightarrow> ok n (is @ [ADD]) (Suc n')\"\n\nlemma \"\\<lbrakk>ok n is n'; length stk = n\\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"\napply(induction rule: ok.induct)\napply(auto simp add: exec_append intro: okempty okLOADI okLOAD okADD)\ndone\n\nlemma ok_append: \"ok n (e2) n' \\<Longrightarrow> ok n'' (e1) n \\<Longrightarrow> ok n'' (e1 @ e2) n'\"\napply(induction rule: ok.induct)\napply(simp)\napply (metis append_assoc ok.simps)\napply (metis append_assoc ok.simps)\napply (metis append_assoc ok.simps)\ndone\n\n(* if we start with any stack, executing the result of compiling an aexp will leave one more elt\n   on the stack. *)\nlemma \"ok n (comp e) (Suc n)\"\napply(induction e arbitrary: n)\nusing okLOADI okempty apply fastforce\nusing okLOAD okempty apply fastforce\nusing okADD ok_append apply fastforce\ndone\n\nend", "meta": {"author": "emberian", "repo": "ConcreteSemantics", "sha": "99843c9250212f926829e70affde8f8cacaf57f9", "save_path": "github-repos/isabelle/emberian-ConcreteSemantics", "path": "github-repos/isabelle/emberian-ConcreteSemantics/ConcreteSemantics-99843c9250212f926829e70affde8f8cacaf57f9/CS_Ch4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8902942203004186, "lm_q1q2_score": 0.7884725905188763}}
{"text": "header {* Matrices\\label{sec.mat} *}\n\ntheory Matrices\nimports\n  Main\n  Determinants_extension \nbegin\n\ntext{* This theory contains a number of notions and results about matrices, in\n   particular the adjugate matrix and its fundamental property. *}\n\n(* ------------------------------------------------------------------------- *)\nsubsection {* Minors *}\n(* ------------------------------------------------------------------------- *)\n\ntext{* Kronecker - Delta *}\ndefinition \"\\<delta> i j = (if i = j then 1 else 0)\"\n\nlemma delta_comm: \"\\<delta> i j = \\<delta> j i\"\n by(simp add: \\<delta>_def)\n\ntext{* unit vector *}\ndefinition \"e i = (\\<chi> j. \\<delta> i j)\"\n\ntext{* the minor-matrix *}\ndefinition \"minorM A i j =\n  (\\<chi> k l. if k = i \\<and> l = j then 1 else\n          if k = i \\<or> l = j then 0 else\n          A$k$l                         \n  )\"\n\nlemma minorM_rows:\n  fixes A :: \"'a::comm_ring_1^'n^'n\" and i j k :: 'n\n  assumes \"k \\<noteq> i\"\n  shows \"row i (minorM A i j) = e j\"\n        \"row k (minorM A i j) = (\\<chi> c. if c = j then 0 else (row k A) $ c)\"\nproof-\n  show \"row i (minorM A i j) = e j\"\n  by(simp_all add: minorM_def row_def e_def \\<delta>_def vec_eq_iff)\nnext\n  { fix l :: 'n\n    have \"(row k (minorM A i j)) $ l = (\\<chi> c. if c = j then 0 else (row k A) $ c) $ l\"\n    proof cases\n      assume caseass: \"l = j\"\n      hence \"(row k (minorM A i j)) $ l = 0\"\n        unfolding row_def minorM_def using assms by auto\n      thus ?thesis\n        using caseass by simp\n    next\n      assume caseass: \"l \\<noteq> j\"\n      hence \"(row k (minorM A i j)) $ l = (row k A) $ l\"\n        unfolding row_def minorM_def using assms by simp\n      thus ?thesis using caseass\n        by simp\n    qed\n  }\n  thus \"row k (minorM A i j) = (\\<chi> c. if c = j then 0 else (row k A) $ c)\" \n    unfolding vec_eq_iff minorM_def by force \nqed\n\ntext{* more general than minorM\\_zeros below *}\nlemma minorM_eq:\n  fixes A B :: \"'a::comm_ring_1^'n^'n\" and i j :: 'n\n  assumes \"\\<And> k l. k \\<noteq> i \\<longrightarrow> l \\<noteq> j \\<longrightarrow> ( A $ k $ l ) = ( B $ k $ l )\"\n  shows \"minorM A i j = minorM B i j\"\nproof-\n  { fix k l :: 'n\n    have \"(minorM A i j) $ k $ l = (minorM B i j) $ k $ l\"\n    proof cases\n      assume \"k = i \\<or> l = j\"\n      thus ?thesis\n        unfolding minorM_def by simp\n    next\n      assume \"\\<not> ( k = i \\<or> l = j)\"\n      thus ?thesis \n        using assms unfolding minorM_def by auto\n    qed }\n  thus ?thesis unfolding vec_eq_iff\n    by blast\nqed\n\nlemma minorM_zeros:\n  fixes A :: \"'a::comm_ring_1^'n^'n\" and i j :: 'n\n  assumes \"row i A = e j\" \"column j A = e i\"\n  shows \"A = minorM A i j\"\nproof-\n  { fix k l :: 'n\n    have \"A $ k $ l = (minorM A i j) $ k $ l\"\n    proof cases\n      assume caseass: \"k = i \\<and> l = j\"\n      then have \"A $ k $ l = 1\"\n        using assms e_def \\<delta>_def row_def \n        by (metis vec_lambda_beta vec_nth_inverse)\n      then show ?thesis\n        using caseass minorM_def[of A i j] \n        by auto\n    next\n      assume caseass: \"\\<not> (k = i \\<and> l = j)\"\n      show ?thesis\n      proof cases\n        assume caseass2: \"k = i \\<or> l = j\"\n        then have \"(minorM A i j) $ k $ l = 0\" \n          using caseass minorM_def[of A i j] by auto\n        also have \"A $ k $ l = 0\"\n          apply(cases \"k = i\")\n          apply(metis vec_lambda_beta assms(1) e_def \\<delta>_def caseass row_def[of i A]) \n          apply(metis (no_types) \\<delta>_def assms(2) caseass2 column_def e_def vec_lambda_beta)\n          done\n        finally show ?thesis \n          by auto\n      next\n        assume caseass2: \"\\<not> (k = i \\<or> l = j)\"\n        thus ?thesis\n          using caseass minorM_def[of A i j] by auto\n      qed\n    qed\n  }\n  thus ?thesis \n    unfolding vec_eq_iff by fast\nqed\n\n(* ------------------------------------------------------------------------- *)\nsubsection {* Cofactors *}\n(* ------------------------------------------------------------------------- *)\n  \ntext{* the cofactors of A *}\ndefinition \"cofactor A i j = det (minorM A i j)\"\n\ntext{* the cofactor-matrix *}\ndefinition \"cofactorM A = (\\<chi> i j. cofactor A i j)\"\n\ntext{* the number of rows in A (except the i-th row) where the j-th element different from 0 *}\ndefinition \"nonzerorows A i j = card { k . k \\<noteq> i \\<and> ( A $ k $ j ) \\<noteq> 0 }\"\n\nlemma aux_det_minorM_row:\n  fixes B :: \"'a::comm_ring_1^'n^'n\" and i j :: 'n\n  assumes \"row i B = e j\"\n  shows \"det B = det (minorM B i j)\"\nproof-\n  { fix n::nat\n    have \"\\<forall> (B::'a^'n^'n) i j . nonzerorows B i j = n \\<longrightarrow> row i B = e j\n      \\<longrightarrow> det B = det (minorM B i j)\"\n    proof (induct n)\n      case 0\n      { fix B :: \"'a^'n^'n\" and i j \n        let ?nzB = \"{ k . k \\<noteq> i \\<and> B $ k $ j \\<noteq> 0 }\"\n        assume caseass: \"nonzerorows B i j = 0\" \"row i B = e j\"\n        hence \"\\<forall> k. k \\<noteq> i \\<longrightarrow> (B $ k $ j) = 0\" \n          using nonzerorows_def[of B i j] by auto\n        then have \"column j B = e i\"\n          by(simp add: column_def[of j B] vec_eq_iff)\n            (metis \\<delta>_def caseass(2) e_def row_def vec_lambda_beta)\n        hence \"B = (minorM B i j)\"\n          using caseass minorM_zeros[of i B j] by blast } \n      thus ?case by force\n    next\n      case (Suc n)\n      { txt{* Suc.hyps is @{term \"\\<forall> B i j. nonzerorows B i j = n \\<longrightarrow> row i B = e j\n          \\<longrightarrow> det B = det (minorM B i j)\"} *}\n        fix B:: \"'a^'n^'n\" and i j \n        let ?nzB = \"{ k . k \\<noteq> i \\<and> B $ k $ j \\<noteq> 0 }\"\n        assume caseass: \"nonzerorows B i j = Suc n\" \"row i B = e j\"\n        hence \"card ?nzB \\<noteq> 0\" \n          using nonzerorows_def[of B i j] by simp\n        then obtain r where rcond: \"r \\<noteq> i \\<and> ( B $ r $ j ) \\<noteq> 0\"\n          using caseass by auto\n        hence \"r \\<noteq> i\"\n          by auto\n\n        let ?B' = \"(\\<chi> l. if l = r then row r B + (- (B $ r $ j)) *s row i B else row l B)\"\n\n        have \"nonzerorows ?B' i j = n\"\n        proof-\n          let ?nzB' = \"{ k . k \\<noteq> i \\<and> ?B'$ k $ j \\<noteq> 0 }\"\n          have \"?nzB' = ?nzB - { r }\"\n            using caseass by (auto simp add: row_def e_def \\<delta>_def)\n          thus ?thesis\n            using rcond caseass(1) by(simp add: nonzerorows_def)\n        qed\n        moreover have \"row i ?B' = e j\"\n          using caseass `r \\<noteq> i`  \n          by(simp add: nonzerorows_def row_def)  \n            (metis vec_lambda_eta )\n        ultimately have \"det ?B' = det (minorM ?B' i j)\" \n          using Suc.hyps by(simp add: nonzerorows_def row_def)  \n        \n        moreover have \"(minorM B i j) = (minorM ?B' i j)\"\n          using minorM_eq[of i j B ?B'] `row i B = e j`\n          by (simp add: e_def \\<delta>_def row_def)\n        ultimately have \"det B = det (minorM B i j)\" \n          using `r \\<noteq> i` my_det_row_operation[of r i B \"- B $ r $ j\"] by simp\n      }\n      txt{* finished induction step *}\n      thus ?case by fast \n    qed\n  }\n  thus ?thesis using assms by blast\nqed\n\nlemma det_minorM_row:\n  fixes A :: \"'a::comm_ring_1^'n^'n\" and i j\n  shows \"det (minorM A i j) = det (\\<chi> k. if k = i then (e j) else row k A)\"\nproof-\n  let ?B = \"(\\<chi> k. if k = i then (e j) else row k A)\"\n  \n  have \"(minorM ?B i j) = (minorM A i j)\"\n    using minorM_eq[of i j ?B A] by(simp add: row_def)\n  moreover have \"det ?B = det (minorM ?B i j)\"\n    by(simp add: aux_det_minorM_row row_def[of i ?B] vec_lambda_eta)\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma minorM_transpose: \"minorM (transpose A) i j = transpose (minorM A j i)\"\n  by(simp add: minorM_def transpose_def conj_commute disj_commute cong del: if_cong)\n\nlemma det_minorM_column:\n  fixes A :: \"'a::comm_ring_1^'n^'n\" and i j \n  shows \"det( minorM A i j ) = det (\\<chi> r c. if c = j then \\<delta> r i else A $ r $ c)\"\n  (is \"?lm = det( ?B )\" )\nproof-\n  have \"(\\<chi> r c . if r = j then (\\<delta> c i) else (A $ c $ r) ) =\n  (\\<chi> r . if r = j then (e i) else row r (transpose A))\"\n    by(simp add: e_def delta_comm row_transpose column_def vec_eq_iff cong del: if_cong)\n    \n  hence \"det( \\<chi> r . if r = j then (e i) else row r (transpose A) ) = \n  det( transpose( \\<chi> r c . if c = j then (\\<delta> r i) else (A $ r $ c) ) )\"\n    by (simp add: transpose_def)\n   \n  thus ?thesis\n    by (metis (no_types) det_minorM_row det_transpose minorM_transpose)\nqed\n\nlemma cofactorM_transpose: \"cofactorM (transpose A) = transpose (cofactorM A)\"\n  (is \"?lhs = ?rhs\")\n  by(simp only: cofactorM_def cofactor_def minorM_transpose det_transpose)\n    (simp add: transpose_def)\n\n(* ------------------------------------------------------------------------- *)\nsubsection {* Scalar-matrix multiplication *}                                                             \n(* ------------------------------------------------------------------------- *)\n\ndefinition scalar_matrix_mult :: \"('a\\<Colon>ab_semigroup_mult) \\<Rightarrow> ('a^'n^'m) \\<Rightarrow> ('a^'n^'m)\" \n  (infixl \"*ss\" 70) where \"c *ss A = (\\<chi> i j. c * (A $ i $ j))\"\n    \nlemma scalar_matrix_mult_monom: \n  fixes A :: \"'a\\<Colon>comm_ring_1 poly^'n^'n\"\n  shows \"monom 1 0 *ss A = A\"\n  by (simp add: monom_0 one_poly_def scalar_matrix_mult_def vec_eq_iff)\n\nlemma scalar_minus_left:\n  fixes x :: \"'a\\<Colon>comm_ring_1\"\n  shows \"- x *ss A = - (x *ss A)\" \n  by (simp add: vec_eq_iff scalar_matrix_mult_def )\n\nlemma one_scalar_mult_mat: \n  shows \"1 *ss (A::'a\\<Colon>comm_ring_1^'n^'n) = A\"\n  unfolding scalar_matrix_mult_def\n  by(simp add: vec_lambda_eta) \n\nlemma scalar_mat_matrix_mult_left:\n  \"mat y ** A = y *ss A\"\n  by (simp add: vec_eq_iff mat_def scalar_matrix_mult_def matrix_matrix_mult_def\n     if_distrib[where f=\"\\<lambda>x. x * y\" for y] setsum.If_cases)\n\nlemma scalar_scalar_mult_assoc: \"x1 *ss (x2 *ss A) = (x1 * x2) *ss A \"\n  unfolding scalar_matrix_mult_def \n  by(simp add: mult.assoc)\n\nlemma matrix_scalar_assoc:\n  fixes A B :: \"'a\\<Colon>comm_ring_1^'n\\<Colon>finite^'n\"\n  shows \"A ** (a *ss B) = a *ss (A ** B)\"\n  unfolding scalar_matrix_mult_def matrix_matrix_mult_def vec_eq_iff\n  by(auto simp add: setsum_right_distrib intro!: Cartesian_Euclidean_Space.setsum_cong_aux)\n\nlemma matrix_scalar_mat_one:\n  fixes x1 and A :: \"'a\\<Colon>comm_ring_1^'n\\<Colon>finite^'n\"\n  shows \"A ** (x1 *ss mat 1) = x1 *ss A\"\n  by(simp add: matrix_scalar_assoc matrix_mul_rid)\n\nlemma scalar_minus_ldistrib:\n  fixes A and B :: \"'a::comm_ring_1^'n\\<Colon>finite^'n\"\n  and x1 :: \"('a::comm_ring_1)\"\n  shows \"x1 *ss (A - B) = (x1 *ss A) - (x1 *ss B)\"\n  unfolding scalar_matrix_mult_def vec_eq_iff\n  by (simp add: mult_diff_mult)     \n\n(* ------------------------------------------------------------------------- *)\nsubsection {* Adjugates *}                                                             \n(* ------------------------------------------------------------------------- *)\n\ndefinition \"adjugate A = transpose (cofactorM A)\"\n\nlemma adjugate_transpose: \"adjugate (transpose A) = transpose (adjugate A)\"\n  by (simp add: adjugate_def cofactorM_transpose)\n\nlemma delta_id_matrix: \"(\\<chi> i j. (\\<delta> i j) * c) = c *ss (mat 1)\"\n  by (simp add: scalar_matrix_mult_def mat_def \\<delta>_def mult.commute)\n\nlemma if_c_is_k: \"(if c = k then A $ r $ k else A $ r $ c) = A $ r $ c\"\n  by simp\n\ntheorem adjugate_det:\n  fixes A :: \"'a::comm_ring_1^'n^'n\"\n  shows \"adjugate A ** A = det A *ss mat 1\"\nproof-\n  let ?U = \"UNIV\\<Colon>'n\\<Colon>finite set\"\n  have adjprod: \"adjugate A ** A = (\\<chi> i k. (\\<Sum> j\\<in>?U. (cofactor A j i) * A $ j $ k))\"\n    by (simp add: cofactorM_def transpose_def adjugate_def matrix_matrix_mult_def)\n\n  { fix i k :: 'n \n    \n    have \"(\\<Sum>j\\<in>?U. (cofactor A j i) * (A $ j $ k)) = \n    (\\<Sum>j\\<in>?U. (A $ j $ k) * det (\\<chi> r c. if c = i then \\<delta> r j else (A $ r $ c)))\" \n      by (simp add: det_minorM_column cofactor_def comm_semiring_1_class.normalizing_semiring_rules)\n      \n    also have \"\\<dots> = (\\<Sum>j\\<in>?U. det (\\<chi> r c. if c = i then \\<delta> r j * A $ r $ k else A $ r $ c))\"\n    proof-\n      { fix j \n        have \"(A $ j $ k) * det (\\<chi> r c. if c = i then \\<delta> r j else (A $ r $ c)) =\n        det (\\<chi> r c. if c = i then \\<delta> r j * (A $ r $ k) else A $ r $ c)\"\n        using det_col_mul[of i _ \"\\<chi> r c. if c = i then \\<delta> r j else A $ r $ c\", symmetric]\n        by(simp add: \\<delta>_def comm_semiring_1_class.normalizing_semiring_rules(7) cong: if_cong)\n          (simp add: if_distrib[where x=1 and y = 0] cong: if_cong) }\n      thus ?thesis\n      by auto\n    qed\n    \n    also have \"\\<dots> = det (\\<chi> r c. if c = i then (\\<Sum> j \\<in> ?U. \\<delta> r j * A $ r $ k) else A $ r $ c)\"\n      using det_linear_column_setsum[of ?U i \"\\<lambda>j. \\<chi> r. \\<delta> r j * A $ r $ k\"]\n      by(simp only: vec_lambda_beta finite[of ?U])\n      \n    also have \"\\<dots> = det (\\<chi> r c. if c = i then A $ r $ k else A $ r $ c)\"\n    proof-\n      { fix r and a :: \"'a::comm_ring_1\"\n      have \"(\\<Sum>j\\<in>?U. \\<delta> r j * a) = a\"\n        by(subst setsum.remove)(auto simp add: \\<delta>_def) }\n      thus ?thesis\n        by presburger\n    qed\n    \n    also have \"\\<dots> = \\<delta> i k * det A\"\n    by(cases \"i=k\")\n      (auto simp add: \\<delta>_def vec_lambda_eta if_c_is_k column_def \n               intro!: my_det_identical_columns[of i k])\n\n    finally have \"(\\<Sum> j \\<in> ?U. cofactor A j i * A $ j $ k) = \\<delta> i k * det A\"\n      by(simp add: cofactor_def \\<delta>_def)\n  }\n  thus ?thesis\n    using adjprod delta_id_matrix[of \"det A\"] by auto\nqed\n\nlemma adjugate_det_symmetric:  \n  shows \"A ** adjugate A = det A *ss mat 1\"\nproof-\n  have \"transpose (A ** adjugate A) = det A *ss mat 1\" \n    using matrix_transpose_mul[of A \"adjugate A\"] det_transpose[of A]\n    adjugate_det[of \"transpose A\"] adjugate_transpose[of A]\n    by auto\n    \n  also have \"transpose (det A *ss mat 1) = det A *ss transpose (mat 1)\"\n    by(simp add: transpose_def scalar_matrix_mult_def)\n  \n  finally show ?thesis\n    by(subst transpose_transpose[of \"A ** adjugate A\", symmetric])\n      (simp add: transpose_mat)\nqed\n\n(* ------------------------------------------------------------------------- *)\nsubsection {* Matrix multiplication *}\n(* ------------------------------------------------------------------------- *)\n\nlemma matrix_mult_left_distributes_minus:\n  fixes A B C :: \"'a::comm_ring_1^'n^'n\"\n  shows \"A ** (B - C) = A ** B - A ** C\"  \n  by (metis (hide_lams, no_types) add_diff_cancel diff_add_cancel matrix_add_ldistrib)\n\nlemma matrix_mult_right_distributes_minus:\n  fixes A B C :: \"'a::comm_ring_1^'n^'n\" \n  shows \"(A - B) ** C = A ** C - B ** C\"\n  unfolding matrix_matrix_mult_def vec_eq_iff\n  using finite[of UNIV]\n  by(induct rule: finite_induct)\n    (auto simp add: left_diff_distrib)\n\nlemma matrix_sum_mult:\n  fixes A :: \"('a::comm_ring_1)^'n\\<Colon>finite^'n\\<Colon>finite\"\n      and f :: \"nat \\<Rightarrow> ('a::comm_ring_1)^'n\\<Colon>finite^'n\\<Colon>finite\" and n :: nat\n  shows \"A ** (\\<Sum> k \\<le> n. (f k)) = (\\<Sum> k \\<le> n. A ** (f k))\"\n  by (induct n) (simp_all add: matrix_add_ldistrib)\n\n(* ------------------------------------------------------------------------- *)\nsubsection {* Powers *}\n(* ------------------------------------------------------------------------- *)\n\nprimrec matpow :: \"'a\\<Colon>semiring_1^'n^'n \\<Rightarrow> nat \\<Rightarrow> 'a^'n^'n\" where\n  matpow_0:   \"matpow A 0 = mat 1\" |\n  matpow_Suc: \"matpow A (Suc n) = A ** (matpow A n)\"\n\nlemma matrix_mult_one_comm: \"A ** mat 1 = mat 1 ** A\"\n  by (simp add: matrix_mul_lid matrix_mul_rid) \n\nlemma matpow_one: \"matpow A 1 = A\"\n  by(simp add: matrix_mul_rid)\n\nlemma matpow_comm: \"A ** matpow A n = matpow A n ** A\"\n  by(induct n) (simp_all add: matrix_mult_one_comm matrix_mul_assoc)\n\nlemma matpow_suc: \"matpow A n ** A = matpow A (Suc n)\"\n  by(simp add: matpow_comm)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Cayley_Hamilton/Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8918110468756548, "lm_q1q2_score": 0.7883959891592816}}
{"text": "(* \nAuthors: \n  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk \n  Hanna Lachnitt, TU Wien, lachnitt@student.tuwien.ac.at\n*)\n\nsection \\<open>Binary Representation of Natural Numbers\\<close>\n\ntheory Binary_Nat\nimports\n  HOL.Nat\n  HOL.List\n  Basics\nbegin \n\n\nprimrec bin_rep_aux:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list\" where\n  \"bin_rep_aux 0 m = [m]\"\n| \"bin_rep_aux (Suc n) m = m div 2^n # bin_rep_aux n (m mod 2^n)\"\n\nlemma length_of_bin_rep_aux:\n  fixes n m:: nat\n  assumes \"m < 2^n\"\n  shows \"length (bin_rep_aux n m) = n+1\" \n  using assms\nproof(induction n arbitrary: m)\n  case 0\n  then show \"length (bin_rep_aux 0 m) = 0 + 1\" by simp\nnext\n  case (Suc n)\n  assume a0:\"\\<And>m. m < 2^n \\<Longrightarrow> length (bin_rep_aux n m) = n + 1\" and \"m < 2^(Suc n)\"\n  then show \"length (bin_rep_aux (Suc n) m) = Suc n + 1\" \n    using a0 by simp\nqed\n\nlemma bin_rep_aux_neq_nil:\n  fixes n m:: nat\n  shows \"bin_rep_aux n m \\<noteq> []\" \n  using bin_rep_aux.simps by (metis list.distinct(1) old.nat.exhaust)\n\nlemma last_of_bin_rep_aux:\n  fixes n m:: nat \n  assumes \"m < 2^n\" and \"m \\<ge> 0\"\n  shows \"last (bin_rep_aux n m) = 0\"\n  using assms\nproof(induction n arbitrary: m)\n  case 0\n  assume \"m < 2^0\" and \"m \\<ge> 0\"\n  then show \"last (bin_rep_aux 0 m) = 0\" by simp\nnext\n  case (Suc n)\n  assume a0:\"\\<And>m. m < 2^n \\<Longrightarrow> m \\<ge> 0 \\<Longrightarrow> last (bin_rep_aux n m) = 0\" and \"m < 2^(Suc n)\"\nand \"m \\<ge> 0\"\n  then show \"last (bin_rep_aux (Suc n) m) = 0\" \n    using bin_rep_aux_neq_nil by simp\nqed\n\nlemma mod_mod_power_cancel:\n  fixes m n p:: nat\n  assumes \"m \\<le> n\"\n  shows \"p mod 2^n mod 2^m = p mod 2^m\" \n  using assms by (simp add: dvd_power_le mod_mod_cancel)\n    \nlemma bin_rep_aux_index:\n  fixes n m i:: nat\n  assumes \"n \\<ge> 1\" and \"m < 2^n\" and \"m \\<ge> 0\" and \"i \\<le> n\"\n  shows \"bin_rep_aux n m ! i = (m mod 2^(n-i)) div 2^(n-1-i)\"\n  using assms\nproof(induction n arbitrary: m i rule: nat_induct_at_least)\n  case base\n  assume \"m < 2^1\" and \"i \\<le> 1\"\n  then show \"bin_rep_aux 1 m ! i = m mod 2^(1-i) div 2^(1-1-i)\" \n    using bin_rep_aux.simps\n    by (metis One_nat_def base.prems(2) diff_is_0_eq' diff_zero div_by_1 le_Suc_eq le_numeral_extra(3) \nnth_Cons' power_0 unique_euclidean_semiring_numeral_class.mod_less)\nnext\n  case (Suc n)\n  assume a0:\"\\<And>m i. m < 2^n \\<Longrightarrow> m \\<ge> 0 \\<Longrightarrow> i \\<le> n \\<Longrightarrow> bin_rep_aux n m ! i = m mod 2 ^ (n-i) div 2^(n-1-i)\"\nand a1:\"m < 2^(Suc n)\" and a2:\"i \\<le> Suc n\" and a3:\"m \\<ge> 0\"\n  then show \"bin_rep_aux (Suc n) m ! i = m mod 2^(Suc n - i) div 2^(Suc n - 1 - i)\"\n  proof-\n    have \"bin_rep_aux (Suc n) m = m div 2^n # bin_rep_aux n (m mod 2^n)\" by simp\n    then have f0:\"bin_rep_aux (Suc n) m ! i = (m div 2^n # bin_rep_aux n (m mod 2^n)) ! i\" by simp\n    then have \"bin_rep_aux (Suc n) m ! i = m div 2^n\" if \"i = 0\" using that by simp\n    then have f1:\"bin_rep_aux (Suc n) m ! i = m mod 2^(Suc n - i) div 2^(Suc n - 1 - i)\" if \"i = 0\"\n    proof-\n      have \"m mod 2^(Suc n - i) = m\" \n        using that a1 by (simp add: Suc.prems(2))\n      then have \"m mod 2^(Suc n - i) div 2^(Suc n - 1 - i) = m div 2^n\" \n        using that by simp\n      thus ?thesis by (simp add: that)\n    qed\n    then have \"bin_rep_aux (Suc n) m ! i = bin_rep_aux n (m mod 2^n) ! (i-1)\" if \"i \\<ge> 1\"\n      using that f0 by simp\n    then have f2:\"bin_rep_aux (Suc n) m ! i = ((m mod 2^n) mod 2^(n - (i - 1))) div 2^(n - 1 - (i - 1))\" if \"i \\<ge> 1\"\n      using that a0 a1 a2 a3 Suc.prems(2) by simp\n    then have f3:\"bin_rep_aux (Suc n) m ! i = ((m mod 2^n) mod 2^(Suc n - i)) div 2^(Suc n - 1 - i)\" if \"i \\<ge> 1\"\n      using that by simp\n    then have \"bin_rep_aux (Suc n) m ! i = m mod 2^(Suc n - i) div 2^(Suc n - 1 - i)\" if \"i \\<ge> 1\" \n    proof-\n      have \"Suc n - i \\<le> n\" using that by simp\n      then have \"m mod 2^n mod 2^(Suc n - i) = m mod 2^(Suc n - i)\" \n        using mod_mod_power_cancel[of \"Suc n - i\" \"n\" \"m\"] by simp\n      thus ?thesis \n        using that f3 by simp\n    qed\n    thus ?thesis using f1 f2\n      using linorder_not_less by blast\n  qed\nqed\n\nlemma bin_rep_aux_coeff:\n  fixes n m i:: nat\n  assumes \"m < 2^n\" and \"i \\<le> n\" and \"m \\<ge> 0\"\n  shows \"bin_rep_aux n m ! i = 0 \\<or> bin_rep_aux n m ! i = 1\"\n  using assms\nproof(induction n arbitrary: m i)\n  case 0\n  assume \"m < 2^0\" and \"i \\<le> 0\" and \"m \\<ge> 0\"\n  then show \"bin_rep_aux 0 m ! i = 0 \\<or> bin_rep_aux 0 m ! i = 1\" by simp\nnext\n  case (Suc n)\n  assume a0:\"\\<And>m i. m < 2 ^ n \\<Longrightarrow> i \\<le> n \\<Longrightarrow> m \\<ge> 0 \\<Longrightarrow> bin_rep_aux n m ! i = 0 \\<or> bin_rep_aux n m ! i = 1\" \nand a1:\"m < 2^Suc n\" and a2:\"i \\<le> Suc n\" and a3:\"m \\<ge> 0\"\n  then show \"bin_rep_aux (Suc n) m ! i = 0 \\<or> bin_rep_aux (Suc n) m ! i = 1\"\n  proof-\n    have \"bin_rep_aux (Suc n) m ! i = (m div 2^n # bin_rep_aux n (m mod 2^n)) ! i\" by simp\n    moreover have \"\\<dots> = bin_rep_aux n (m mod 2^n) ! (i - 1)\" if \"i \\<ge> 1\"\n      using that by simp\n    moreover have \"m mod 2^n < 2^n\" by simp\n    ultimately have \"bin_rep_aux (Suc n) m ! i = 0 \\<or> bin_rep_aux (Suc n) m ! i = 1\" if \"i\\<ge>1\"\n      using that a0[of \"m mod 2^n\" \"i-1\"] a2 by simp\n    moreover have \"m div 2^n = 0 \\<or> m div 2^n = 1\" \n      using a1 a3 less_mult_imp_div_less by(simp add: less_2_cases)\n    ultimately show ?thesis by (simp add: nth_Cons')\n  qed\nqed\n\ndefinition bin_rep:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list\" where\n\"bin_rep n m = butlast (bin_rep_aux n m)\"\n\nlemma length_of_bin_rep:\n  fixes n m:: nat\n  assumes \"m < 2^n\"\n  shows \"length (bin_rep n m) = n\"\n  using assms length_of_bin_rep_aux bin_rep_def by simp\n\nlemma bin_rep_coeff:\n  fixes n m i:: nat\n  assumes \"m < 2^n\" and \"i < n\" and \"m \\<ge> 0\"\n  shows \"bin_rep n m ! i = 0 \\<or> bin_rep n m ! i = 1\" \n  using assms bin_rep_def bin_rep_aux_coeff length_of_bin_rep by(simp add: nth_butlast)\n\nlemma bin_rep_index:\n  fixes n m i:: nat\n  assumes \"n \\<ge> 1\" and \"m < 2^n\" and \"i < n\" and \"m \\<ge> 0\"\n  shows \"bin_rep n m ! i = (m mod 2^(n-i)) div 2^(n-1-i)\"\nproof-\n  have \"bin_rep n m ! i = bin_rep_aux n m ! i\"\n    using bin_rep_def length_of_bin_rep nth_butlast assms(3)\n    by (simp add: nth_butlast assms(2))\n  thus ?thesis\n    using assms bin_rep_aux_index by simp\nqed\n\nlemma bin_rep_eq:\n  fixes n m:: nat \n  assumes \"n \\<ge> 1\" and \"m \\<ge> 0\" and \"m < 2^n\" and \"m \\<ge> 0\"\n  shows \"m = (\\<Sum>i<n. bin_rep n m ! i * 2^(n-1-i))\"\nproof-\n  {\n    fix i:: nat\n    assume \"i < n\"\n    then have \"bin_rep n m ! i * 2^(n-1-i) = (m mod 2^(n-i)) div 2^(n-1-i) * 2^(n-1-i)\"\n      using assms bin_rep_index by simp\n    moreover have \"\\<dots> = m mod 2^(n-i) - m mod 2^(n-i) mod 2^(n-1-i)\"\n      by (simp add: minus_mod_eq_div_mult)\n    moreover have \"\\<dots> = int(m mod 2^(n-i)) - m mod 2^(n-i) mod 2^(n-1-i)\" \n      using mod_less_eq_dividend of_nat_diff by blast\n    moreover have \"\\<dots> = int(m mod 2^(n-i)) - m mod 2^(n-1-i)\" \n      using mod_mod_power_cancel[of \"n-1-i\" \"n-i\"] by (simp add: dvd_power_le mod_mod_cancel)\n    ultimately have \"bin_rep n m ! i * 2^(n-1-i) = int (m mod 2^(n-i)) - m mod 2^(n-1-i)\" \n      by presburger\n  }\n  then have f0:\"(\\<Sum>i<n. bin_rep n m ! i * 2^(n-1-i)) = (\\<Sum>i<n. int (m mod 2^(n-i)) - m mod 2^(n-1-i))\" \n    by auto\n  thus ?thesis\n  proof-\n     have \"(\\<Sum>i<n. int ((m::nat) mod 2^(n - i)) - (m mod 2^(n - 1 - i))) = \n          (\\<Sum>i<n. ( m mod 2^(n - i))) -  (\\<Sum>i<n. int (m mod 2^(n - 1 - i)))\" \n      using sum_subtractf[of \"(\\<lambda>i. (m mod 2^(n-i)))::nat\\<Rightarrow>nat\" \"(\\<lambda>i. (m mod 2^(n-1-i)))::nat\\<Rightarrow>nat\" \"{..<(n::nat)}\"] \n      by auto\n    moreover have \"\\<dots> = m mod 2^n + (\\<Sum>i\\<in>{1..<n}. (m mod 2^(n-i))) - (\\<Sum>i<n-1. int (m mod 2^(n-1-i)))- m mod 2^0\" \n      using sum.atLeast_Suc_atMost sum.lessThan_Suc assms(1) \n      by (smt One_nat_def Suc_le_eq diff_self_eq_0 le_add_diff_inverse lessThan_atLeast0 minus_nat.diff_0 \n          plus_1_eq_Suc sum.atLeast_Suc_lessThan)\n    moreover have \"\\<dots> = m mod 2^n + (\\<Sum>i<n-1. m mod 2^(n-i-1)) - (\\<Sum>i<n-1. int ( m mod 2^(n-1-i))) - m mod 2^0\" \n      apply (auto simp add: sum_of_index_diff[of \"\\<lambda>i. m mod 2 ^ (n - 1 - i)\" \"1\" \"n-1\"])\n      by (smt One_nat_def assms(1) le_add_diff_inverse lessThan_atLeast0 plus_1_eq_Suc sum.cong sum.shift_bounds_Suc_ivl)\n    moreover have \"\\<dots> = m mod 2^n - m mod 2^0\" by simp\n    moreover have \"\\<dots> = m\" using assms by auto\n    ultimately show \"m = (\\<Sum>i<n. bin_rep n m ! i * 2^(n-1-i))\"\n      using assms f0 by linarith\n  qed\nqed\n\nlemma bin_rep_index_0:\n  fixes n m:: nat\n  assumes \"m < 2^n\" and \"k > n\"\n  shows \"(bin_rep k m) ! 0 = 0\"\nproof-\n  have \"m < 2^(k-1)\" \n    using assms by(smt Suc_diff_1 Suc_leI gr0I le_trans less_or_eq_imp_le linorder_neqE_nat not_less \none_less_numeral_iff power_strict_increasing semiring_norm(76))\n  then have f:\"m div 2^(k-1) = 0\" \n    by auto\n  have \"k \\<ge> 1\" \n    using assms(2) by simp\n  moreover have \"bin_rep_aux k m = (m div 2^(k-1)) # (bin_rep_aux (k-1) (m mod 2^(k-1)))\"\n    using bin_rep_aux.simps(2) by(metis Suc_diff_1 assms(2) diff_0_eq_0 neq0_conv zero_less_diff)\n  moreover have \"bin_rep k m = butlast ((m div 2^(k-1)) # (bin_rep_aux (k-1) (m mod 2^(k-1))))\" \n    using bin_rep_def by (simp add: calculation(2))\n  moreover have \"\\<dots> = butlast (0 # (bin_rep_aux (k-1) (m mod 2^(k-1))))\" \n    using f by simp\n  moreover have \"\\<dots> = 0 # butlast (bin_rep_aux (k-1) (m mod 2^(k-1)))\" \n    by(simp add: bin_rep_aux_neq_nil)\n  ultimately show ?thesis \n    by simp\nqed\n\nlemma bin_rep_index_0_geq:\n  fixes n m:: nat\n  assumes \"m \\<ge> 2^n\" and \"m < 2^(n+1)\"\n  shows \"bin_rep (n+1) m ! 0 = 1\"\nproof-\n  have \"bin_rep (Suc n) m =  butlast (bin_rep_aux (Suc n) m)\" \n    using bin_rep_def by simp\n  moreover have \"\\<dots> = butlast (1 # (bin_rep_aux n (m mod 2^n)))\" \n    using assms bin_rep_aux_def by simp\n  moreover have \"\\<dots> = 1 # butlast (bin_rep_aux n (m mod 2^n))\"\n    by (simp add: bin_rep_aux_neq_nil)\n  ultimately show ?thesis\n    by (simp add: bin_rep_aux_neq_nil)\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Isabelle_Marries_Dirac/Binary_Nat.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7883746250602429}}
{"text": "(*<*)\ntheory Brent\nimports\n  Basis\nbegin\n(*>*)\nsection\\<open> Brent's algorithm \\label{sec:brent} \\<close>\n\ntext\\<open>\n\n\\<^cite>\\<open>\"Brent:1980\"\\<close> improved on the Tortoise and Hare algorithm and\nused it to factor large primes. In practice it makes significantly\nfewer calls to the function \\<open>f\\<close> before detecting a loop.\n\nWe begin by defining the base-2 logarithm.\n\n\\<close>\n\nfun lg :: \"nat \\<Rightarrow> nat\" where\n[simp del]: \"lg x = (if x \\<le> 1 then 0 else 1 + lg (x div 2))\"\n\nlemma lg_safe:\n  \"lg 0 = 0\"\n  \"lg (Suc 0) = 0\"\n  \"lg (Suc (Suc 0)) = 1\"\n  \"0 < x \\<Longrightarrow> lg (x + x) = 1 + lg x\"\nby (simp_all add: lg.simps)\n\nlemma lg_inv:\n  \"0 < x \\<Longrightarrow> lg (2 ^ x) = x\"\nproof(induct x)\n  case (Suc x) then show ?case\n    by (cases x, simp_all add: lg.simps Suc_lessI not_le)\nqed simp\n\nlemma lg_inv2:\n  \\<open>2 ^ lg x = x\\<close> if \\<open>2 ^ i = x\\<close> for x\nproof -\n  have \\<open>2 ^ lg (2 ^ i) = (2::nat) ^ i\\<close>\n    by (induction i) (simp_all add: lg_safe mult_2)\n  with that show ?thesis\n    by simp\nqed\n\nlemmas lg_simps = lg_safe lg_inv lg_inv2\n\nsubsection\\<open> Finding \\<open>lambda\\<close> \\<close>\n\ntext (in properties) \\<open>\n\nImagine now that the Tortoise carries an unbounded number of carrots,\nwhich he passes to the Hare when they meet, and the Hare has a\nteleporter. The Hare eats a carrot each time she waits for the\nfunction @{term \"f\"} to execute, and initially has just one. If she\nruns out of carrots before meeting the Tortoise again, she teleports\nhim to her position, and he gives her twice as many carrots as the\nlast time they met (tracked by the variable \\<open>carrots\\<close>). By\ncounting how many carrots she has eaten from when she last teleported\nthe Tortoise (recorded in \\<open>l\\<close>) until she finally has surplus\ncarrots when she meets him again, the Hare directly discovers @{term\n\"lambda\"}.\n\n\\<close>\n\nrecord 'a state =\n  m :: nat  \\<comment> \\<open>\\<open>\\<mu>\\<close>\\<close>\n  l :: nat  \\<comment> \\<open>\\<open>\\<lambda>\\<close>\\<close>\n  carrots :: nat\n  hare :: \"'a\"\n  tortoise :: \"'a\"\n\ncontext properties\nbegin\n\ndefinition (in fx0) find_lambda :: \"'a state \\<Rightarrow> 'a state\" where\n  \"find_lambda \\<equiv>\n    (\\<lambda>s. s\\<lparr> carrots := 1, l := 1, tortoise := x0, hare := f x0 \\<rparr>) ;;\n    while (hare \\<^bold>\\<noteq> tortoise)\n          ( ( \\<^bold>if carrots \\<^bold>= l \\<^bold>then (\\<lambda>s. s\\<lparr> tortoise := hare s, carrots := 2 * carrots s, l := 0 \\<rparr>)\n                             \\<^bold>else SKIP ) ;;\n            (\\<lambda>s. s\\<lparr> hare := f (hare s), l := l s + 1 \\<rparr>) )\"\n\ntext\\<open>\n\nThe termination argument goes intuitively as follows. The Hare eats as\nmany carrots as it takes to teleport the Tortoise into the\nloop. Afterwards she continues the teleportation dance until the\nTortoise has given her enough carrots to make it all the way around\nthe loop and back to him.\n\nWe can calculate the Tortoise's position as a function of \\<open>carrots\\<close>.\n\n\\<close>\n\ndefinition carrots_total :: \"nat \\<Rightarrow> nat\" where\n  \"carrots_total c \\<equiv> \\<Sum>i<lg c. 2 ^ i\"\n\nlemma carrots_total_simps:\n  \"carrots_total (Suc 0) = 0\"\n  \"carrots_total (Suc (Suc 0)) = 1\"\n  \"2 ^ i = c \\<Longrightarrow> carrots_total (c + c) = c + carrots_total c\"\nby (auto simp: carrots_total_def lg_simps)\n\ndefinition find_lambda_measures :: \"( (nat \\<times> nat) \\<times> (nat \\<times> nat) ) set\" where\n  \"find_lambda_measures \\<equiv>\n    measures [\\<lambda>(l, c). mu - carrots_total c,\n              \\<lambda>(l, c). LEAST i. lambda \\<le> c * 2^i,\n              \\<lambda>(l, c). c - l]\"\n\nlemma find_lambda_measures_wellfounded:\n  \"wf find_lambda_measures\"\nby (simp add: find_lambda_measures_def)\n\nlemma find_lambda_measures_decreases1:\n  assumes \"c = 2 ^ i\"\n  assumes \"mu \\<le> carrots_total c \\<longrightarrow> c \\<le> lambda\"\n  assumes \"seq (carrots_total c) \\<noteq> seq (carrots_total c + c)\"\n  shows \"( (c', 2 * c), (c, c) ) \\<in> find_lambda_measures\"\nproof(cases \"mu \\<le> carrots_total c\")\n  case False with assms show ?thesis\n    by (auto simp: find_lambda_measures_def carrots_total_simps mult_2 field_simps diff_less_mono2)\nnext\n  case True\n  { fix x assume x: \"(0::nat) < x\" have \"\\<exists>n. lambda \\<le> x * 2 ^ n\"\n    proof(induct lambda)\n      case (Suc i)\n      then obtain n where \"i \\<le> x * 2 ^ n\" by blast\n      with x show ?case\n        by (clarsimp intro!: exI[where x=\"Suc n\"] simp: field_simps mult_2)\n           (metis Nat.add_0_right Suc_leI linorder_neqE_nat mult_eq_0_iff add_left_cancel not_le numeral_2_eq_2 old.nat.distinct(2) power_not_zero trans_le_add2)\n    qed simp } note ex = this\n  have \"(LEAST j. lambda \\<le> 2 ^ (i + 1) * 2 ^ j) < (LEAST j. lambda \\<le> 2 ^ i * 2 ^ j)\"\n  proof(rule LeastI2_wellorder_ex[OF ex, rotated], rule LeastI2_wellorder_ex[OF ex, rotated])\n    fix x y\n    assume \"lambda \\<le> 2 ^ i * 2 ^ y\"\n           \"lambda \\<le> 2 ^ (i + 1) * 2 ^ x\"\n           \"\\<forall>z. lambda \\<le> 2 ^ (i + 1) * 2 ^ z \\<longrightarrow> x \\<le> z\"\n    with True assms properties_loop[where i=\"carrots_total c\" and j=1]\n    show \"x < y\" by (cases y, auto simp: less_Suc_eq_le)\n  qed simp_all\n  with True \\<open>c = 2 ^ i\\<close> show ?thesis\n    by (clarsimp simp: find_lambda_measures_def mult_2 carrots_total_simps field_simps power_add)\nqed\n\nlemma find_lambda_measures_decreases2:\n  assumes \"ls < c\"\n  shows \"( (Suc ls, c), (ls, c) ) \\<in> find_lambda_measures\"\nusing assms by (simp add: find_lambda_measures_def)\n\nlemma find_lambda:\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> find_lambda \\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle>\\<rbrace>\"\napply (simp add: find_lambda_def)\napply (rule hoare_pre)\napply (rule whileI[where I=\"\\<langle>0\\<rangle> \\<^bold>< l \\<^bold>\\<and> l \\<^bold>\\<le> carrots \\<^bold>\\<and> (\\<langle>mu\\<rangle> \\<^bold>\\<le> carrots_total \\<circ> carrots \\<^bold>\\<longrightarrow> l \\<^bold>\\<le> \\<langle>lambda\\<rangle>) \\<^bold>\\<and> (\\<^bold>\\<exists>i. carrots \\<^bold>= \\<langle>2^i\\<rangle>)\n                           \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> carrots_total \\<circ> carrots \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (l \\<^bold>+ (carrots_total \\<circ> carrots))\"\n                      and r=\"inv_image find_lambda_measures (l \\<^bold>\\<bowtie> carrots)\"]\n            wp_intro)+\n   using properties_lambda_gt_0\n   apply (clarsimp simp: field_simps mult_2_right carrots_total_simps)\n   apply (intro conjI impI)\n      apply (metis mult_2 power_Suc)\n     apply (case_tac \"mu \\<le> carrots_total (l s)\")\n      apply (cut_tac i=\"carrots_total (l s)\" and j=\"l s\" in properties_distinct_contrapos, simp_all add: field_simps)[1]\n     apply (cut_tac i=\"carrots_total (l s)\" and j=\"l s\" in properties_loops_ge_mu, simp_all add: field_simps)[1]\n    apply (cut_tac i=\"carrots_total (2 ^ x)\" and j=1 in properties_loop, simp)\n    apply (fastforce simp: le_eq_less_or_eq field_simps)\n   apply (cut_tac i=\"carrots_total (2 ^ x)\" and j=\"l s\" in properties_loops_ge_mu, simp_all add: field_simps)[1]\n   apply (cut_tac i=\"carrots_total (2 ^ x)\" and j=\"l s\" in properties_distinct_contrapos, simp_all add: field_simps)[1]\n  apply (simp add: find_lambda_measures_wellfounded)\n apply (clarsimp simp: add.commute find_lambda_measures_decreases1 find_lambda_measures_decreases2)\napply (rule wp_intro)\nusing properties_lambda_gt_0\napply (simp add: carrots_total_simps exI[where x=0])\ndone\n\nsubsection\\<open> Finding \\<open>mu\\<close> \\<close>\n\ntext\\<open>\n\nWith @{term \"lambda\"} in hand, we can find \\<open>mu\\<close> using the same\napproach as for the Tortoise and Hare (\\S\\ref{sec:th-finding-mu}),\nafter we first move the Hare to @{term \"lambda\"}.\n\n\\<close>\n\ndefinition (in fx0) find_mu :: \"'a state \\<Rightarrow> 'a state\" where\n  \"find_mu \\<equiv>\n    (\\<lambda>s. s\\<lparr> m := 0, tortoise := x0, hare := seq (l s) \\<rparr>) ;;\n    while (hare \\<^bold>\\<noteq> tortoise)\n          (\\<lambda>s. s\\<lparr> tortoise := f (tortoise s), hare := f (hare s), m := m s + 1 \\<rparr>)\"\n\nlemma find_mu:\n  \"\\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle>\\<rbrace> find_mu \\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\napply (simp add: find_mu_def)\napply (rule hoare_pre)\napply (rule whileI[where I=\"l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>\\<le> \\<langle>mu\\<rangle> \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> m \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (m \\<^bold>+ l)\"\n                      and r=\"measure (\\<langle>mu\\<rangle> \\<^bold>- m)\"]\n            wp_intro)+\n   using properties_lambda_gt_0 properties_loop[where i=mu and j=1]\n   apply (fastforce simp: le_less dest: properties_loops_ge_mu)\n  apply simp\n using properties_loop[where i=mu and j=1, simplified]\n apply (fastforce simp: le_eq_less_or_eq)\napply (rule wp_intro)\napply simp\ndone\n\n\nsubsection\\<open> Top level \\<close>\n\ndefinition (in fx0) brent :: \"'a state \\<Rightarrow> 'a state\" where\n  \"brent \\<equiv> find_lambda ;; find_mu\"\n\ntheorem brent:\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> brent \\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\nunfolding brent_def\nby (rule find_lambda find_mu wp_intro)+\n\nend\n\ncorollary brent_correct:\n  assumes s': \"s' = fx0.brent f x arbitrary\"\n  shows \"fx0.properties f x (l s') (m s')\"\nusing assms properties.brent[where f=f and ?x0.0=x]\nby (fastforce intro: fx0.properties_existence[where f=f and ?x0.0=x]\n               simp:  Basis.properties_def valid_def)\n\nschematic_goal brent_code[code]:\n  \"fx0.brent f x = ?code\"\nunfolding fx0.brent_def fx0.find_lambda_def fx0.find_mu_def fcomp_assoc[symmetric] fcomp_comp\nby (rule refl)\n\nexport_code fx0.brent in SML\n(*<*)\n\nend\n(*>*)\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/TortoiseHare/Brent.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7883746128973504}}
{"text": "(* \n  Title: Lucas_Theorem.thy\n  Author: Chelsea Edmonds, University of Cambridge\n*)\n\ntheory Lucas_Theorem\n  imports Main \"HOL-Computational_Algebra.Computational_Algebra\"\nbegin\n\nnotation fps_nth (infixl \"$\" 75)\n\nsection \\<open>Extensions on Formal Power Series (FPS) Library\\<close>\n\ntext \\<open>This section presents a few extensions on the Formal Power Series (FPS) library, described in \\cite{Chaieb2011} \\<close>\n\nsubsection \\<open>FPS Equivalence Relation \\<close>\n\ntext \\<open> This proof requires reasoning around the equivalence of coefficients mod some prime number. \nThis section defines an equivalence relation on FPS using the pattern described by Paulson \nin \\cite{paulsonDefiningFunctionsEquivalence2006}, as well as some basic lemmas for reasoning around \nhow the equivalence holds after common operations are applied \\<close>\n\ndefinition \"fpsmodrel p \\<equiv> { (f, g). \\<forall> n. (f $ n) mod p = (g $ n) mod p }\"\n\nlemma fpsrel_iff [simp]: \"(f, g) \\<in> fpsmodrel p \\<longleftrightarrow> (\\<forall>n. (f $ n) mod p = (g $ n) mod p)\"\n  by (simp add: fpsmodrel_def)\n\nlemma fps_equiv: \"equiv UNIV (fpsmodrel p)\" \nproof (rule equivI)\n  show \"refl (fpsmodrel p)\" by (simp add: refl_on_def fpsmodrel_def)\n  show \"sym (fpsmodrel p)\" by (simp add: sym_def fpsmodrel_def)\n  show \"trans (fpsmodrel p)\" by (intro transI) (simp add: fpsmodrel_def)\nqed\n\ntext \\<open> Equivalence relation over multiplication \\<close>\n\nlemma fps_mult_equiv_coeff: \n  fixes f g :: \"('a :: {euclidean_ring_cancel}) fps\"\n  assumes \"(f, g) \\<in> fpsmodrel p\"\n  shows \"(f*h)$n mod p = (g*h)$n mod p\" \nproof -\n  have \"((f*h) $ n) mod p =(\\<Sum>i=0..n. (f$i mod p * h$(n - i) mod p) mod p) mod p\"\n    using mod_sum_eq mod_mult_left_eq\n    by (simp add: fps_mult_nth mod_sum_eq mod_mult_left_eq)\n  also have \"... = (\\<Sum>i=0..n. (g$i mod p * h$(n - i) mod p) mod p) mod p\"\n    using assms by auto \n  also have \"... = ((g*h) $ n) mod p\"\n    by (simp add: mod_mult_left_eq mod_sum_eq fps_mult_nth)\n  thus ?thesis by (simp add: calculation)  \nqed\n\nlemma fps_mult_equiv: \n  fixes f g :: \"('a :: {euclidean_ring_cancel}) fps\"\n  assumes \"(f, g) \\<in> fpsmodrel p\"\n  shows \"(f*h, g*h) \\<in> fpsmodrel p\"\n  using fpsmodrel_def fps_mult_equiv_coeff assms by blast \n\n\ntext \\<open> Equivalence relation over power operator \\<close>\nlemma fps_power_equiv: \n  fixes f g :: \"('a :: {euclidean_ring_cancel}) fps\"\n  fixes x :: nat\n  assumes \"(f, g) \\<in> fpsmodrel p\"\n  shows \"(f^x, g^x) \\<in> fpsmodrel p\"\n  using assms\nproof (induct x)\n  case 0\n  thus ?case by (simp add: fpsmodrel_def)\nnext\n  case (Suc x)\n  then have hyp: \" \\<forall>n. f^x $ n mod p = g ^x $ n mod p\" \n    using fpsrel_iff by blast \n  thus ?case \n  proof -\n    have fact: \"\\<forall>n h. (g * h) $ n mod p = (f * h) $ n mod p\"\n      by (metis assms fps_mult_equiv_coeff)\n    have \"\\<forall>n h. (g ^ x * h) $ n mod p = (f ^ x * h) $ n mod p\"\n      by (simp add: fps_mult_equiv_coeff hyp)\n    then have \"\\<forall>n h. (h * g ^ x) $ n mod p = (h * f ^ x) $ n mod p\"\n      by (simp add: mult.commute)\n    thus ?thesis\n      using fact by force\n  qed\nqed\n\nsubsection \\<open>Binomial Coefficients \\<close>\n\ntext \\<open>The @{term \"fps_binomial\"} definition in the formal power series uses the @{term \"n gchoose k\"} operator. It's \ndefined as being of type @{typ \"'a :: field_char_0 fps\"}, however the equivalence relation requires a type @{typ 'a} \nthat supports the modulo operator. \nThe proof of the binomial theorem based on FPS coefficients below uses the choose operator and does\nnot put bounds on the type of @{term \"fps_X\"}.\\<close> \n\nlemma binomial_coeffs_induct: \n  fixes n k :: nat\n  shows \"(1 + fps_X)^n $ k = of_nat(n choose k)\"\nproof (induct n arbitrary: k)\n  case 0\n  thus ?case\n    by (metis binomial_eq_0_iff binomial_n_0 fps_nth_of_nat not_gr_zero of_nat_0 of_nat_1 power_0) \nnext\n  case h: (Suc n)\n  fix k \n  have start: \"(1 + fps_X)^(n + 1) = (1 + fps_X) * (1 + fps_X)^n\" by auto\n  show ?case \n    using One_nat_def Suc_eq_plus1 Suc_pred add.commute binomial_Suc_Suc binomial_n_0 \n        fps_mult_fps_X_plus_1_nth h.hyps neq0_conv start by (smt of_nat_add)  \nqed\n\nsubsection \\<open>Freshman's Dream Lemma on FPS \\<close>\ntext \\<open> The Freshman's dream lemma modulo a prime number $p$ is a well known proof that $(1 + x^p) \\equiv (1 + x)^p \\mod p$\\<close>\n\ntext \\<open> First prove that $\\binom{p^n}{k} \\equiv 0 \\mod p$ for $k \\ge 1$ and $k < p^n$. The eventual\nproof only ended up requiring this with $n = 1$\\<close>\n\nlemma pn_choose_k_modp_0:\n  fixes n k::nat\n  assumes \"prime p\"\n          \"k \\<ge> 1 \\<and> k \\<le> p^n - 1\"\n          \"n > 0\"\n  shows \"(p^n choose k) mod p = 0\"\nproof - \n  have inequality: \"k \\<le> p^n\" using assms (2) by arith\n  have choose_take_1: \"((p^n - 1) choose ( k - 1))= fact (p^n - 1) div (fact (k - 1) * fact (p^n - k))\"\n    using binomial_altdef_nat diff_le_mono inequality assms(2) by auto\n  have \"k * (p^n choose k) = k * ((fact (p^n)) div (fact k * fact((p^n) - k)))\" \n    using assms binomial_fact'[OF inequality] by auto\n  also have \"... = k * fact (p^n) div (fact k * fact((p^n) - k))\"\n    using binomial_fact_lemma div_mult_self_is_m fact_gt_zero inequality mult.assoc mult.commute \n          nat_0_less_mult_iff by smt\n  also have \"... = k * fact (p^n) div (k * fact (k - 1) * fact((p^n) - k))\" \n    by (metis assms(2) fact_nonzero fact_num_eq_if le0 le_antisym of_nat_id)\n  also have \"... = fact (p^n) div (fact (k - 1) * fact((p^n) - k))\" \n    using assms by auto\n  also have \"... = ((p^n) * fact (p^n - 1)) div (fact (k - 1) * fact((p^n) - k))\"\n    by (metis assms(2) fact_nonzero fact_num_eq_if inequality le0 le_antisym of_nat_id)\n  also have \"... = (p^n) * (fact (p^n - 1) div (fact (k - 1) * fact((p^n) - k)))\"\n    by (metis assms(2) calculation choose_take_1 neq0_conv not_one_le_zero times_binomial_minus1_eq)\n  finally have equality: \"k * (p^n choose k) = p^n * ((p^n - 1) choose (k - 1))\"\n    using assms(2) times_binomial_minus1_eq by auto\n  then have dvd_result: \"p^n dvd (k * (p^n choose k))\" by simp \n  have \"\\<not> (p^n dvd k)\" \n    using assms (2) binomial_n_0 diff_diff_cancel nat_dvd_not_less neq0_conv by auto  \n  then have \"p dvd (p^n choose k)\" \n    using mult.commute prime_imp_prime_elem prime_power_dvd_multD assms dvd_result by metis\n  thus \"?thesis\" by simp \nqed\n\ntext \\<open> Applying the above lemma to the coefficients of $(1 + X)^p$, it is easy to show that all \ncoefficients other than the $0$th and $p$th will be $0$ \\<close>\n\nlemma fps_middle_coeffs:\n  assumes \"prime p\"\n          \"n \\<noteq> 0 \\<and> n \\<noteq> p\"\n  shows \"((1 + fps_X :: int fps) ^p) $ n mod p = 0 mod p\"\nproof -\n  let ?f = \"(1 + fps_X :: int fps)^p\"\n  have \"\\<forall> n. n > 0 \\<and> n < p \\<longrightarrow> (p choose n) mod p = 0\" using pn_choose_k_modp_0\n    by (metis (no_types, lifting) add_le_imp_le_diff assms(1) diff_diff_cancel diff_is_0_eq' \n        discrete le_add_diff_inverse le_numeral_extra(4) power_one_right zero_le_one zero_less_one)\n  then have middle_0: \"\\<forall> n. n > 0 \\<and> n < p \\<longrightarrow> (?f $ n) mod p = 0\" \n    using binomial_coeffs_induct by (metis of_nat_0 zmod_int) \n  have \"\\<forall> n. n > p \\<longrightarrow> ?f $ n mod p = 0\" \n    using binomial_eq_0_iff binomial_coeffs_induct mod_0 by (metis of_nat_eq_0_iff) \n  thus ?thesis using middle_0 assms(2) nat_neq_iff by auto\nqed\n\ntext \\<open>It follows that $(1+ X)^p$ is equivalent to $(1 + X^p)$ under our equivalence relation, \nas required to prove the freshmans dream lemma. \\<close>\n\nlemma fps_freshmans_dream:\n  assumes \"prime p\"\n  shows \"(((1 + fps_X :: int fps ) ^p), (1 + (fps_X)^(p))) \\<in> fpsmodrel p\"\nproof -\n  let ?f = \"(1 + fps_X :: int fps)^p\"\n  let ?g = \"(1 + (fps_X :: int fps)^p)\"\n  have all_f_coeffs: \"\\<forall> n. n \\<noteq> 0 \\<and> n \\<noteq> p \\<longrightarrow> ?f $ n mod p = 0 mod p\" \n    using fps_middle_coeffs assms by blast \n  have \"?g $ 0 = 1\" using assms by auto \n  then have \"?g $ 0 mod p = 1 mod p\" \n    using int_ops(2) zmod_int assms by presburger \n  then have \"?g $ p mod p = 1 mod p\" using assms by auto \n  then have \"\\<forall> n . ?f $ n mod p = ?g $ n mod p\" \n    using all_f_coeffs by (simp add: binomial_coeffs_induct)\n  thus ?thesis using fpsrel_iff by blast\nqed\n\nsection \\<open>Lucas's Theorem Proof\\<close>\n\ntext \\<open>A formalisation of Lucas's theorem based on a generating function proof using the existing formal power series (FPS) Isabelle library\\<close>\n\nsubsection \\<open>Reasoning about Coefficients Helpers\\<close>\n\ntext \\<open>A generating function proof of Lucas's theorem relies on direct comparison between coefficients of FPS which requires a number \nof helper lemmas to prove formally. In particular it compares the coefficients of \n$(1 + X)^n \\mod p$ to $(1 + X^p)^N * (1 + X) ^rn \\mod p$, where $N = n / p$, and $rn = n \\mod p$.\nThis section proves that the $k$th coefficient of $(1 + X^p)^N * (1 + X) ^rn = (N choose K) * (rn choose rk)$\\<close>\n\ntext \\<open>Applying the @{term \"fps_compose\"} operator enables reasoning about the coefficients of $(1 + X^p)^n$ \nusing the existing binomial theorem proof with $X^p$ instead of $X$.\\<close>\n\nlemma fps_binomial_p_compose: \n  assumes \"p \\<noteq> 0\" \n  shows \"(1 + (fps_X:: ('a :: {idom} fps))^p)^n = ((1 + fps_X)^n) oo (fps_X^p)\"\nproof -\n  have \"(1::'a fps) + fps_X ^ p = 1 + fps_X oo fps_X ^ p\"\n    by (simp add: assms fps_compose_add_distrib)\n  then show ?thesis\n    by (simp add: assms fps_compose_power)\nqed\n\ntext \\<open> Next the proof determines the value of the $k$th coefficient of $(1 + X^p)^N$. \\<close> \n\nlemma fps_X_pow_binomial_coeffs: \n  assumes \"prime p\"\n  shows \"(1 + (fps_X ::int fps)^p)^N $k = (if p dvd k then (N choose (k div p)) else 0)\"\nproof -\n  let ?fx = \"(fps_X :: int fps)\"\n  have \"(1 + ?fx^p)^N $ k  = (((1 + ?fx)^N) oo (?fx^p)) $k\"\n    by (metis assms fps_binomial_p_compose not_prime_0)\n  also have \"... = (\\<Sum>i=0..k.((1 + ?fx)^N)$i * ((?fx^p)^i$k))\"\n    by (simp add: fps_compose_nth) \n  finally have coeffs: \"(1 + ?fx^p)^N $ k = (\\<Sum>i=0..k. (N choose i) * ((?fx^(p*i))$k))\"\n    using binomial_coeffs_induct sum.cong by (metis (no_types, lifting) power_mult) \n  thus ?thesis \n  proof (cases \"p dvd k\")\n    case False \\<comment> \\<open>$p$ does not divide $k$ implies the $k$th term has a coefficient of 0\\<close> \n    have \"\\<forall> i. \\<not>(p dvd k) \\<longrightarrow> (?fx^(p*i)) $ k = 0\"\n      by auto \n    thus ?thesis using coeffs by (simp add: False) \n  next\n    case True \\<comment> \\<open>$p$ divides $k$ implies the $k$th term has a non-zero coefficient\\<close>\n    have contained: \"k div p \\<in> {0.. k}\" by simp\n    have \"\\<forall> i. i \\<noteq> k div p \\<longrightarrow> (?fx^(p*i)) $ k = 0\" using assms by auto\n    then have notdivpis0: \"\\<forall> i \\<in> ({0 .. k} - {k div p}). (?fx^(p*i)) $ k = 0\" by simp\n    have \"(1 + ?fx^p)^N $ k = (N choose (k div p)) * (?fx^(p * (k div p))) $ k + (\\<Sum>i\\<in>({0..k} -{k div p}). (N choose i) * ((?fx^(p*i))$k))\"\n      using contained coeffs sum.remove by (metis (no_types, lifting) finite_atLeastAtMost)\n    thus ?thesis using notdivpis0 True by simp \n  qed\nqed\n\ntext \\<open> The final helper lemma proves the $k$th coefficient is equivalent to $\\binom{?N}{?K}*\\binom{?rn}{?rk}$ as required.\\<close>\nlemma fps_div_rep_coeffs: \n  assumes \"prime p\"\n  shows \"((1 + (fps_X::int fps)^p)^(n div p) * (1 + fps_X)^(n mod p)) $ k = \n          ((n div p) choose (k div p)) * ((n mod p) choose (k mod p))\"\n    (is \"((1 + (fps_X::int fps)^p)^?N * (1 + fps_X)^?rn) $ k = (?N choose ?K) * (?rn choose ?rk)\")\nproof -\n  \\<comment> \\<open>Initial facts with results around representation and 0 valued terms\\<close>\n  let ?fx = \"fps_X :: int fps\"\n  have krep: \"k - ?rk = ?K*p\"\n    by (simp add: minus_mod_eq_mult_div)\n  have rk_in_range: \"?rk \\<in> {0..k}\" by simp\n  have \"\\<forall> i \\<ge> p. (?rn choose i) = 0\" \n    using binomial_eq_0_iff \n    by (metis assms(1) leD le_less_trans linorder_cases mod_le_divisor mod_less_divisor prime_gt_0_nat)\n  then have ptok0: \"\\<forall> i \\<in> {p..k}. ((?rn choose i) * (1 + ?fx^p)^?N $ (k - i)) = 0\" \n    by simp\n  then have notrkis0: \"\\<forall>i \\<in> {0.. k}. i \\<noteq> ?rk \\<longrightarrow> (?rn choose i) * (1 + ?fx^p)^?N $ (k - i) = 0\" \n  proof (cases \"k < p\")\n    case True \\<comment> \\<open>When $k < p$, it presents a side case with regards to range of reasoning\\<close>\n    then have k_value: \"k = ?rk\" by simp\n    then have \"\\<forall> i < k. \\<not> (p dvd (k - i))\" \n       using True by (metis diff_diff_cancel diff_is_0_eq dvd_imp_mod_0 less_imp_diff_less less_irrefl_nat mod_less)\n    then show ?thesis using fps_X_pow_binomial_coeffs assms(1) k_value by simp\n  next\n    case False\n    then have \"\\<forall> i < p. i \\<noteq> ?rk \\<longrightarrow> \\<not>(p dvd (k - i))\"\n      using mod_nat_eqI by auto \n    then have \"\\<forall> i \\<in> {0..<p}. i \\<noteq> ?rk \\<longrightarrow> (1 + ?fx^p)^?N $ (k - i) = 0\" \n      using assms fps_X_pow_binomial_coeffs by simp\n    then show ?thesis using ptok0 by auto \n  qed\n  \\<comment> \\<open>Main body of the proof, using helper facts above\\<close>\n  have \"((1 + fps_X^p)^?N * (1 + fps_X)^?rn) $ k = (((1 + fps_X)^?rn) * (1 + fps_X^p)^?N) $ k\"\n    by (metis (no_types, hide_lams) distrib_left distrib_right fps_mult_fps_X_commute fps_one_mult(1) \n        fps_one_mult(2) power_commuting_commutes)\n  also have \"... = (\\<Sum>i=0..k.(of_nat(?rn choose i)) * ((1 + (fps_X)^p)^?N $ (k - i)))\" \n    by (simp add: fps_mult_nth binomial_coeffs_induct) \n  also have \"... =  ((?rn choose ?rk) * (1 + ?fx^p)^?N $ (k - ?rk)) + (\\<Sum>i\\<in>({0..k} - {?rk}). (?rn choose i) * (1 + ?fx^p)^?N $ (k - i))\" \n    using rk_in_range sum.remove by (metis (no_types, lifting) finite_atLeastAtMost)\n  finally have \"((1 + ?fx^p)^?N * (1 + ?fx)^?rn) $ k = ((?rn choose ?rk) * (1 + ?fx^p)^?N $ (k - ?rk))\" \n    using notrkis0 by simp\n  thus ?thesis using fps_X_pow_binomial_coeffs assms krep by auto \nqed\n\n(* Lucas theorem proof *) \nsubsection \\<open>Lucas Theorem Proof\\<close>\n\ntext \\<open> The proof of Lucas's theorem combines a generating function approach, based off \\cite{Fine} with induction.\nFor formalisation purposes, it was easier to first prove a well known corollary of the main theorem (also \noften presented as an alternative statement for Lucas's theorem), which can itself be used to backwards \nprove the the original statement by induction.\nThis approach was adapted from P. Cameron's lecture notes on combinatorics \\cite{petercameronNotesCombinatorics2007} \\<close>\n\nsubsubsection \\<open> Proof of the Corollary \\<close>\ntext \\<open> This step makes use of the coefficient equivalence arguments proved in the previous sections \\<close>\ncorollary lucas_corollary: \n  fixes n k :: nat\n  assumes \"prime p\" \n  shows \"(n choose k) mod p = (((n div p) choose (k div p)) * ((n mod p) choose (k mod p))) mod p\" \n    (is \"(n choose k) mod p = ((?N choose ?K) * (?rn choose ?rk)) mod p\")\nproof -\n  let ?fx = \"fps_X :: int fps\"\n  have n_rep: \"n = ?N * p  + ?rn\"\n    by simp\n  have k_rep: \"k =?K * p + ?rk\" by simp\n  have rhs_coeffs: \"((1 + ?fx^p)^(?N) * (1 + ?fx)^(?rn)) $ k = (?N choose ?K) * (?rn choose ?rk)\" \n    using assms fps_div_rep_coeffs k_rep n_rep by blast \\<comment> \\<open>Application of coefficient reasoning\\<close>\n  have \"((((1 + ?fx)^p)^(?N) * (1 + ?fx)^(?rn)), \n          ((1 + ?fx^p)^(?N) * (1 + ?fx)^(?rn))) \\<in> fpsmodrel p\"\n    using fps_freshmans_dream assms fps_mult_equiv fps_power_equiv by blast \\<comment> \\<open>Application of equivalence facts and freshmans dream lemma\\<close>\n  then have modrel2: \"((1 + ?fx)^n, ((1 + ?fx^p)^(?N) * (1 + ?fx)^(?rn))) \n                          \\<in> fpsmodrel p\"\n    by (metis (mono_tags, hide_lams) mult_div_mod_eq power_add power_mult)\n  thus ?thesis\n    using fpsrel_iff binomial_coeffs_induct rhs_coeffs by (metis of_nat_eq_iff zmod_int) \nqed\n\nsubsubsection \\<open> Proof of the Theorem \\<close>\n\ntext \\<open>The theorem statement requires a formalised way of referring to the base $p$ representation of a number. \nWe use a definition that specifies the $i$th digit of the base $p$ representation. This definition is originally \nfrom the Hilbert's 10th Problem Formalisation project \\cite{bayerDPRMTheoremIsabelle2019} which this work contributes to.\\<close>\ndefinition nth_digit_general :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"nth_digit_general num i base = (num div (base ^ i)) mod base\"\n\ntext \\<open>Applying induction on $d$, where $d$ is the highest power required in either $n$ or $k$'s base $p$\nrepresentation, @{thm lucas_corollary} can be used to prove the original theorem.\\<close>\n\ntheorem lucas_theorem:\n  fixes n k d::nat\nassumes \"n < p ^ (Suc d)\"\nassumes \"k < p ^ (Suc d)\"\nassumes \"prime p\"\nshows \"(n choose k) mod p = (\\<Prod>i\\<le>d. ((nth_digit_general n i p) choose (nth_digit_general k i p))) mod p\"\n  using assms\nproof (induct d arbitrary: n k)\n  case 0\n  thus ?case using nth_digit_general_def assms by simp\nnext\n  case (Suc d)\n  \\<comment> \\<open>Representation Variables\\<close>\n  let ?N = \"n div p\"   \n  let ?K = \"k div p\"\n  let ?nr = \"n mod p\"\n  let ?kr = \"k mod p\"\n  \\<comment> \\<open>Required assumption facts\\<close>\n  have Mlessthan: \"?N < p ^ (Suc d)\" \n    using less_mult_imp_div_less power_Suc2 assms(3) prime_ge_2_nat Suc.prems(1) by metis \n  have Nlessthan: \"?K < p ^ (Suc d)\" \n    using less_mult_imp_div_less power_Suc2 prime_ge_2_nat Suc.prems(2) assms(3) by metis\n  have shift_bounds_fact: \"(\\<Prod>i=(Suc 0)..(Suc (d )). ((nth_digit_general n i p) choose (nth_digit_general k i p))) = \n                            (\\<Prod>i=0..(d).  (nth_digit_general n (Suc i) p) choose (nth_digit_general k (Suc i) p))\"\n    using prod.shift_bounds_cl_Suc_ivl by blast \\<comment> \\<open>Product manipulation helper fact\\<close>\n  have \"(n choose k ) mod p = ((?N choose ?K) * (?nr choose ?kr)) mod p\" \n    using lucas_corollary assms(3) by blast \\<comment> \\<open>Application of corollary\\<close>\n  also have \"...= ((\\<Prod>i\\<le>d. ((nth_digit_general ?N i p) choose (nth_digit_general ?K i p))) * (?nr choose ?kr)) mod p\"\n    using Mlessthan Nlessthan Suc.hyps mod_mult_cong assms(3) by blast \\<comment> \\<open>Using Inductive Hypothesis\\<close>\n  \\<comment> \\<open>Product manipulation steps\\<close>\n  also have \"... = ((\\<Prod>i=0..(d). (nth_digit_general n (Suc i) p) choose (nth_digit_general k (Suc i) p)) * (?nr choose ?kr)) mod p\"\n    using  atMost_atLeast0 nth_digit_general_def div_mult2_eq by auto\n  also have \"... = ((\\<Prod>i=1..(d+1). (nth_digit_general n i p) choose (nth_digit_general k i p)) * \n                            ((nth_digit_general n 0 p) choose (nth_digit_general k 0 p))) mod p\" \n    using nth_digit_general_def shift_bounds_fact by simp\n  finally have \"(n choose k ) mod p = ((\\<Prod>i=0..(d+1). (nth_digit_general n i p) choose (nth_digit_general k i p))) mod p\" \n    using One_nat_def atMost_atLeast0 mult.commute prod.atLeast1_atMost_eq prod.atMost_shift\n    by (smt Suc_eq_plus1 shift_bounds_fact)\n  thus ?case\n    using Suc_eq_plus1 atMost_atLeast0 by presburger\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Lucas_Theorem/Lucas_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7882971563120624}}
{"text": "(*  Title:      HOL/Order_Relation.thy\n    Author:     Tobias Nipkow\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection \\<open>Orders as Relations\\<close>\n\ntheory Order_Relation\nimports Wfrec\nbegin\n\nsubsection \\<open>Orders on a set\\<close>\n\ndefinition \"preorder_on A r \\<equiv> refl_on A r \\<and> trans r\"\n\ndefinition \"partial_order_on A r \\<equiv> preorder_on A r \\<and> antisym r\"\n\ndefinition \"linear_order_on A r \\<equiv> partial_order_on A r \\<and> total_on A r\"\n\ndefinition \"strict_linear_order_on A r \\<equiv> trans r \\<and> irrefl r \\<and> total_on A r\"\n\ndefinition \"well_order_on A r \\<equiv> linear_order_on A r \\<and> wf(r - Id)\"\n\nlemmas order_on_defs =\n  preorder_on_def partial_order_on_def linear_order_on_def\n  strict_linear_order_on_def well_order_on_def\n\nlemma partial_order_onD:\n  assumes \"partial_order_on A r\" shows \"refl_on A r\" and \"trans r\" and \"antisym r\"\n  using assms unfolding partial_order_on_def preorder_on_def by auto\n\nlemma preorder_on_empty[simp]: \"preorder_on {} {}\"\n  by (simp add: preorder_on_def trans_def)\n\nlemma partial_order_on_empty[simp]: \"partial_order_on {} {}\"\n  by (simp add: partial_order_on_def)\n\nlemma lnear_order_on_empty[simp]: \"linear_order_on {} {}\"\n  by (simp add: linear_order_on_def)\n\nlemma well_order_on_empty[simp]: \"well_order_on {} {}\"\n  by (simp add: well_order_on_def)\n\n\nlemma preorder_on_converse[simp]: \"preorder_on A (r\\<inverse>) = preorder_on A r\"\n  by (simp add: preorder_on_def)\n\nlemma partial_order_on_converse[simp]: \"partial_order_on A (r\\<inverse>) = partial_order_on A r\"\n  by (simp add: partial_order_on_def)\n\nlemma linear_order_on_converse[simp]: \"linear_order_on A (r\\<inverse>) = linear_order_on A r\"\n  by (simp add: linear_order_on_def)\n\n\nlemma partial_order_on_acyclic:\n  \"partial_order_on A r \\<Longrightarrow> acyclic (r - Id)\"\n  by (simp add: acyclic_irrefl partial_order_on_def preorder_on_def trans_diff_Id)\n\nlemma partial_order_on_well_order_on:               \n  \"finite r \\<Longrightarrow> partial_order_on A r \\<Longrightarrow> wf (r - Id)\" \n  by (simp add: finite_acyclic_wf partial_order_on_acyclic) \n\nlemma strict_linear_order_on_diff_Id: \"linear_order_on A r \\<Longrightarrow> strict_linear_order_on A (r - Id)\"\n  by (simp add: order_on_defs trans_diff_Id)\n\nlemma linear_order_on_singleton [simp]: \"linear_order_on {x} {(x, x)}\"\n  by (simp add: order_on_defs)\n\nlemma linear_order_on_acyclic:\n  assumes \"linear_order_on A r\"\n  shows \"acyclic (r - Id)\"\n  using strict_linear_order_on_diff_Id[OF assms]\n  by (auto simp add: acyclic_irrefl strict_linear_order_on_def)\n\nlemma linear_order_on_well_order_on:\n  assumes \"finite r\"\n  shows \"linear_order_on A r \\<longleftrightarrow> well_order_on A r\"\n  unfolding well_order_on_def\n  using assms finite_acyclic_wf[OF _ linear_order_on_acyclic, of r] by blast\n\n\nsubsection \\<open>Orders on the field\\<close>\n\nabbreviation \"Refl r \\<equiv> refl_on (Field r) r\"\n\nabbreviation \"Preorder r \\<equiv> preorder_on (Field r) r\"\n\nabbreviation \"Partial_order r \\<equiv> partial_order_on (Field r) r\"\n\nabbreviation \"Total r \\<equiv> total_on (Field r) r\"\n\nabbreviation \"Linear_order r \\<equiv> linear_order_on (Field r) r\"\n\nabbreviation \"Well_order r \\<equiv> well_order_on (Field r) r\"\n\n\nlemma subset_Image_Image_iff:\n  \"Preorder r \\<Longrightarrow> A \\<subseteq> Field r \\<Longrightarrow> B \\<subseteq> Field r \\<Longrightarrow>\n    r `` A \\<subseteq> r `` B \\<longleftrightarrow> (\\<forall>a\\<in>A.\\<exists>b\\<in>B. (b, a) \\<in> r)\"\n  apply (simp add: preorder_on_def refl_on_def Image_def subset_eq)\n  apply (simp only: trans_def)\n  apply fast\n  done\n\nlemma subset_Image1_Image1_iff:\n  \"Preorder r \\<Longrightarrow> a \\<in> Field r \\<Longrightarrow> b \\<in> Field r \\<Longrightarrow> r `` {a} \\<subseteq> r `` {b} \\<longleftrightarrow> (b, a) \\<in> r\"\n  by (simp add: subset_Image_Image_iff)\n\nlemma Refl_antisym_eq_Image1_Image1_iff:\n  assumes \"Refl r\"\n    and as: \"antisym r\"\n    and abf: \"a \\<in> Field r\" \"b \\<in> Field r\"\n  shows \"r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then have *: \"\\<And>x. (a, x) \\<in> r \\<longleftrightarrow> (b, x) \\<in> r\"\n    by (simp add: set_eq_iff)\n  have \"(a, a) \\<in> r\" \"(b, b) \\<in> r\" using \\<open>Refl r\\<close> abf by (simp_all add: refl_on_def)\n  then have \"(a, b) \\<in> r\" \"(b, a) \\<in> r\" using *[of a] *[of b] by simp_all\n  then show ?rhs\n    using \\<open>antisym r\\<close>[unfolded antisym_def] by blast\nnext\n  assume ?rhs\n  then show ?lhs by fast\nqed\n\nlemma Partial_order_eq_Image1_Image1_iff:\n  \"Partial_order r \\<Longrightarrow> a \\<in> Field r \\<Longrightarrow> b \\<in> Field r \\<Longrightarrow> r `` {a} = r `` {b} \\<longleftrightarrow> a = b\"\n  by (auto simp: order_on_defs Refl_antisym_eq_Image1_Image1_iff)\n\nlemma Total_Id_Field:\n  assumes \"Total r\"\n    and not_Id: \"\\<not> r \\<subseteq> Id\"\n  shows \"Field r = Field (r - Id)\"\nproof -\n  have \"Field r \\<subseteq> Field (r - Id)\"\n  proof (rule subsetI)\n    fix a assume *: \"a \\<in> Field r\"\n    from not_Id have \"r \\<noteq> {}\" by fast\n    with not_Id obtain b and c where \"b \\<noteq> c \\<and> (b,c) \\<in> r\" by auto\n    then have \"b \\<noteq> c \\<and> {b, c} \\<subseteq> Field r\" by (auto simp: Field_def)\n    with * obtain d where \"d \\<in> Field r\" \"d \\<noteq> a\" by auto\n    with * \\<open>Total r\\<close> have \"(a, d) \\<in> r \\<or> (d, a) \\<in> r\" by (simp add: total_on_def)\n    with \\<open>d \\<noteq> a\\<close> show \"a \\<in> Field (r - Id)\" unfolding Field_def by blast\n  qed\n  then show ?thesis\n    using mono_Field[of \"r - Id\" r] Diff_subset[of r Id] by auto\nqed\n\nsubsection\\<open>Relations given by a predicate and the field\\<close>\n\ndefinition relation_of :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<times> 'a) set\"\n  where \"relation_of P A \\<equiv> { (a, b) \\<in> A \\<times> A. P a b }\"\n\nlemma Field_relation_of:\n  assumes \"refl_on A (relation_of P A)\" shows \"Field (relation_of P A) = A\"\n  using assms unfolding refl_on_def Field_def by auto\n\nlemma partial_order_on_relation_ofI:\n  assumes refl: \"\\<And>a. a \\<in> A \\<Longrightarrow> P a a\"\n    and trans: \"\\<And>a b c. \\<lbrakk> a \\<in> A; b \\<in> A; c \\<in> A \\<rbrakk> \\<Longrightarrow> P a b \\<Longrightarrow> P b c \\<Longrightarrow> P a c\"\n    and antisym: \"\\<And>a b. \\<lbrakk> a \\<in> A; b \\<in> A \\<rbrakk> \\<Longrightarrow> P a b \\<Longrightarrow> P b a \\<Longrightarrow> a = b\"\n  shows \"partial_order_on A (relation_of P A)\"\nproof -\n  from refl have \"refl_on A (relation_of P A)\"\n    unfolding refl_on_def relation_of_def by auto\n  moreover have \"trans (relation_of P A)\" and \"antisym (relation_of P A)\"\n    unfolding relation_of_def\n    by (auto intro: transI dest: trans, auto intro: antisymI dest: antisym)\n  ultimately show ?thesis\n    unfolding partial_order_on_def preorder_on_def by simp\nqed\n\nlemma Partial_order_relation_ofI:\n  assumes \"partial_order_on A (relation_of P A)\" shows \"Partial_order (relation_of P A)\"\n  using Field_relation_of assms partial_order_on_def preorder_on_def by fastforce\n\n\nsubsection \\<open>Orders on a type\\<close>\n\nabbreviation \"strict_linear_order \\<equiv> strict_linear_order_on UNIV\"\n\nabbreviation \"linear_order \\<equiv> linear_order_on UNIV\"\n\nabbreviation \"well_order \\<equiv> well_order_on UNIV\"\n\n\nsubsection \\<open>Order-like relations\\<close>\n\ntext \\<open>\n  In this subsection, we develop basic concepts and results pertaining\n  to order-like relations, i.e., to reflexive and/or transitive and/or symmetric and/or\n  total relations. We also further define upper and lower bounds operators.\n\\<close>\n\n\nsubsubsection \\<open>Auxiliaries\\<close>\n\nlemma refl_on_domain: \"refl_on A r \\<Longrightarrow> (a, b) \\<in> r \\<Longrightarrow> a \\<in> A \\<and> b \\<in> A\"\n  by (auto simp add: refl_on_def)\n\ncorollary well_order_on_domain: \"well_order_on A r \\<Longrightarrow> (a, b) \\<in> r \\<Longrightarrow> a \\<in> A \\<and> b \\<in> A\"\n  by (auto simp add: refl_on_domain order_on_defs)\n\nlemma well_order_on_Field: \"well_order_on A r \\<Longrightarrow> A = Field r\"\n  by (auto simp add: refl_on_def Field_def order_on_defs)\n\nlemma well_order_on_Well_order: \"well_order_on A r \\<Longrightarrow> A = Field r \\<and> Well_order r\"\n  using well_order_on_Field [of A] by auto\n\nlemma Total_subset_Id:\n  assumes \"Total r\"\n    and \"r \\<subseteq> Id\"\n  shows \"r = {} \\<or> (\\<exists>a. r = {(a, a)})\"\nproof -\n  have \"\\<exists>a. r = {(a, a)}\" if \"r \\<noteq> {}\"\n  proof -\n    from that obtain a b where ab: \"(a, b) \\<in> r\" by fast\n    with \\<open>r \\<subseteq> Id\\<close> have \"a = b\" by blast\n    with ab have aa: \"(a, a) \\<in> r\" by simp\n    have \"a = c \\<and> a = d\" if \"(c, d) \\<in> r\" for c d\n    proof -\n      from that have \"{a, c, d} \\<subseteq> Field r\"\n        using ab unfolding Field_def by blast\n      then have \"((a, c) \\<in> r \\<or> (c, a) \\<in> r \\<or> a = c) \\<and> ((a, d) \\<in> r \\<or> (d, a) \\<in> r \\<or> a = d)\"\n        using \\<open>Total r\\<close> unfolding total_on_def by blast\n      with \\<open>r \\<subseteq> Id\\<close> show ?thesis by blast\n    qed\n    then have \"r \\<subseteq> {(a, a)}\" by auto\n    with aa show ?thesis by blast\n  qed\n  then show ?thesis by blast\nqed\n\nlemma Linear_order_in_diff_Id:\n  assumes \"Linear_order r\"\n    and \"a \\<in> Field r\"\n    and \"b \\<in> Field r\"\n  shows \"(a, b) \\<in> r \\<longleftrightarrow> (b, a) \\<notin> r - Id\"\n  using assms unfolding order_on_defs total_on_def antisym_def Id_def refl_on_def by force\n\n\nsubsubsection \\<open>The upper and lower bounds operators\\<close>\n\ntext \\<open>\n  Here we define upper (``above\") and lower (``below\") bounds operators. We\n  think of \\<open>r\\<close> as a \\<^emph>\\<open>non-strict\\<close> relation. The suffix \\<open>S\\<close> at the names of\n  some operators indicates that the bounds are strict -- e.g., \\<open>underS a\\<close> is\n  the set of all strict lower bounds of \\<open>a\\<close> (w.r.t. \\<open>r\\<close>). Capitalization of\n  the first letter in the name reminds that the operator acts on sets, rather\n  than on individual elements.\n\\<close>\n\ndefinition under :: \"'a rel \\<Rightarrow> 'a \\<Rightarrow> 'a set\"\n  where \"under r a \\<equiv> {b. (b, a) \\<in> r}\"\n\ndefinition underS :: \"'a rel \\<Rightarrow> 'a \\<Rightarrow> 'a set\"\n  where \"underS r a \\<equiv> {b. b \\<noteq> a \\<and> (b, a) \\<in> r}\"\n\ndefinition Under :: \"'a rel \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"Under r A \\<equiv> {b \\<in> Field r. \\<forall>a \\<in> A. (b, a) \\<in> r}\"\n\ndefinition UnderS :: \"'a rel \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"UnderS r A \\<equiv> {b \\<in> Field r. \\<forall>a \\<in> A. b \\<noteq> a \\<and> (b, a) \\<in> r}\"\n\ndefinition above :: \"'a rel \\<Rightarrow> 'a \\<Rightarrow> 'a set\"\n  where \"above r a \\<equiv> {b. (a, b) \\<in> r}\"\n\ndefinition aboveS :: \"'a rel \\<Rightarrow> 'a \\<Rightarrow> 'a set\"\n  where \"aboveS r a \\<equiv> {b. b \\<noteq> a \\<and> (a, b) \\<in> r}\"\n\ndefinition Above :: \"'a rel \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"Above r A \\<equiv> {b \\<in> Field r. \\<forall>a \\<in> A. (a, b) \\<in> r}\"\n\ndefinition AboveS :: \"'a rel \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"AboveS r A \\<equiv> {b \\<in> Field r. \\<forall>a \\<in> A. b \\<noteq> a \\<and> (a, b) \\<in> r}\"\n\ndefinition ofilter :: \"'a rel \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"ofilter r A \\<equiv> A \\<subseteq> Field r \\<and> (\\<forall>a \\<in> A. under r a \\<subseteq> A)\"\n\ntext \\<open>\n  Note: In the definitions of \\<open>Above[S]\\<close> and \\<open>Under[S]\\<close>, we bounded\n  comprehension by \\<open>Field r\\<close> in order to properly cover the case of \\<open>A\\<close> being\n  empty.\n\\<close>\n\nlemma underS_subset_under: \"underS r a \\<subseteq> under r a\"\n  by (auto simp add: underS_def under_def)\n\nlemma underS_notIn: \"a \\<notin> underS r a\"\n  by (simp add: underS_def)\n\nlemma Refl_under_in: \"Refl r \\<Longrightarrow> a \\<in> Field r \\<Longrightarrow> a \\<in> under r a\"\n  by (simp add: refl_on_def under_def)\n\nlemma AboveS_disjoint: \"A \\<inter> (AboveS r A) = {}\"\n  by (auto simp add: AboveS_def)\n\nlemma in_AboveS_underS: \"a \\<in> Field r \\<Longrightarrow> a \\<in> AboveS r (underS r a)\"\n  by (auto simp add: AboveS_def underS_def)\n\nlemma Refl_under_underS: \"Refl r \\<Longrightarrow> a \\<in> Field r \\<Longrightarrow> under r a = underS r a \\<union> {a}\"\n  unfolding under_def underS_def\n  using refl_on_def[of _ r] by fastforce\n\nlemma underS_empty: \"a \\<notin> Field r \\<Longrightarrow> underS r a = {}\"\n  by (auto simp: Field_def underS_def)\n\nlemma under_Field: \"under r a \\<subseteq> Field r\"\n  by (auto simp: under_def Field_def)\n\nlemma underS_Field: \"underS r a \\<subseteq> Field r\"\n  by (auto simp: underS_def Field_def)\n\nlemma underS_Field2: \"a \\<in> Field r \\<Longrightarrow> underS r a \\<subset> Field r\"\n  using underS_notIn underS_Field by fast\n\nlemma underS_Field3: \"Field r \\<noteq> {} \\<Longrightarrow> underS r a \\<subset> Field r\"\n  by (cases \"a \\<in> Field r\") (auto simp: underS_Field2 underS_empty)\n\nlemma AboveS_Field: \"AboveS r A \\<subseteq> Field r\"\n  by (auto simp: AboveS_def Field_def)\n\nlemma under_incr:\n  assumes \"trans r\"\n    and \"(a, b) \\<in> r\"\n  shows \"under r a \\<subseteq> under r b\"\n  unfolding under_def\nproof safe\n  fix x assume \"(x, a) \\<in> r\"\n  with assms trans_def[of r] show \"(x, b) \\<in> r\" by blast\nqed\n\nlemma underS_incr:\n  assumes \"trans r\"\n    and \"antisym r\"\n    and ab: \"(a, b) \\<in> r\"\n  shows \"underS r a \\<subseteq> underS r b\"\n  unfolding underS_def\nproof safe\n  assume *: \"b \\<noteq> a\" and **: \"(b, a) \\<in> r\"\n  with \\<open>antisym r\\<close> antisym_def[of r] ab show False\n    by blast\nnext\n  fix x assume \"x \\<noteq> a\" \"(x, a) \\<in> r\"\n  with ab \\<open>trans r\\<close> trans_def[of r] show \"(x, b) \\<in> r\"\n    by blast\nqed\n\nlemma underS_incl_iff:\n  assumes LO: \"Linear_order r\"\n    and INa: \"a \\<in> Field r\"\n    and INb: \"b \\<in> Field r\"\n  shows \"underS r a \\<subseteq> underS r b \\<longleftrightarrow> (a, b) \\<in> r\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs\n  with \\<open>Linear_order r\\<close> show ?lhs\n    by (simp add: order_on_defs underS_incr)\nnext\n  assume *: ?lhs\n  have \"(a, b) \\<in> r\" if \"a = b\"\n    using assms that by (simp add: order_on_defs refl_on_def)\n  moreover have False if \"a \\<noteq> b\" \"(b, a) \\<in> r\"\n  proof -\n    from that have \"b \\<in> underS r a\" unfolding underS_def by blast\n    with * have \"b \\<in> underS r b\" by blast\n    then show ?thesis by (simp add: underS_notIn)\n  qed\n  ultimately show \"(a,b) \\<in> r\"\n    using assms order_on_defs[of \"Field r\" r] total_on_def[of \"Field r\" r] by blast\nqed\n\nlemma finite_Partial_order_induct[consumes 3, case_names step]:\n  assumes \"Partial_order r\"\n    and \"x \\<in> Field r\"\n    and \"finite r\"\n    and step: \"\\<And>x. x \\<in> Field r \\<Longrightarrow> (\\<And>y. y \\<in> aboveS r x \\<Longrightarrow> P y) \\<Longrightarrow> P x\"\n  shows \"P x\"\n  using assms(2)\nproof (induct rule: wf_induct[of \"r\\<inverse> - Id\"])\n  case 1\n  from assms(1,3) show \"wf (r\\<inverse> - Id)\"\n    using partial_order_on_well_order_on partial_order_on_converse by blast\nnext\n  case prems: (2 x)\n  show ?case\n    by (rule step) (use prems in \\<open>auto simp: aboveS_def intro: FieldI2\\<close>)\nqed\n\nlemma finite_Linear_order_induct[consumes 3, case_names step]:\n  assumes \"Linear_order r\"\n    and \"x \\<in> Field r\"\n    and \"finite r\"\n    and step: \"\\<And>x. x \\<in> Field r \\<Longrightarrow> (\\<And>y. y \\<in> aboveS r x \\<Longrightarrow> P y) \\<Longrightarrow> P x\"\n  shows \"P x\"\n  using assms(2)\nproof (induct rule: wf_induct[of \"r\\<inverse> - Id\"])\n  case 1\n  from assms(1,3) show \"wf (r\\<inverse> - Id)\"\n    using linear_order_on_well_order_on linear_order_on_converse\n    unfolding well_order_on_def by blast\nnext\n  case prems: (2 x)\n  show ?case\n    by (rule step) (use prems in \\<open>auto simp: aboveS_def intro: FieldI2\\<close>)\nqed\n\n\nsubsection \\<open>Variations on Well-Founded Relations\\<close>\n\ntext \\<open>\n  This subsection contains some variations of the results from \\<^theory>\\<open>HOL.Wellfounded\\<close>:\n    \\<^item> means for slightly more direct definitions by well-founded recursion;\n    \\<^item> variations of well-founded induction;\n    \\<^item> means for proving a linear order to be a well-order.\n\\<close>\n\n\nsubsubsection \\<open>Characterizations of well-foundedness\\<close>\n\ntext \\<open>\n  A transitive relation is well-founded iff it is ``locally'' well-founded,\n  i.e., iff its restriction to the lower bounds of of any element is\n  well-founded.\n\\<close>\n\nlemma trans_wf_iff:\n  assumes \"trans r\"\n  shows \"wf r \\<longleftrightarrow> (\\<forall>a. wf (r \\<inter> (r\\<inverse>``{a} \\<times> r\\<inverse>``{a})))\"\nproof -\n  define R where \"R a = r \\<inter> (r\\<inverse>``{a} \\<times> r\\<inverse>``{a})\" for a\n  have \"wf (R a)\" if \"wf r\" for a\n    using that R_def wf_subset[of r \"R a\"] by auto\n  moreover\n  have \"wf r\" if *: \"\\<forall>a. wf(R a)\"\n    unfolding wf_def\n  proof clarify\n    fix phi a\n    assume **: \"\\<forall>a. (\\<forall>b. (b, a) \\<in> r \\<longrightarrow> phi b) \\<longrightarrow> phi a\"\n    define chi where \"chi b \\<longleftrightarrow> (b, a) \\<in> r \\<longrightarrow> phi b\" for b\n    with * have \"wf (R a)\" by auto\n    then have \"(\\<forall>b. (\\<forall>c. (c, b) \\<in> R a \\<longrightarrow> chi c) \\<longrightarrow> chi b) \\<longrightarrow> (\\<forall>b. chi b)\"\n      unfolding wf_def by blast\n    also have \"\\<forall>b. (\\<forall>c. (c, b) \\<in> R a \\<longrightarrow> chi c) \\<longrightarrow> chi b\"\n    proof safe\n      fix b\n      assume \"\\<forall>c. (c, b) \\<in> R a \\<longrightarrow> chi c\"\n      moreover have \"(b, a) \\<in> r \\<Longrightarrow> \\<forall>c. (c, b) \\<in> r \\<and> (c, a) \\<in> r \\<longrightarrow> phi c \\<Longrightarrow> phi b\"\n      proof -\n        assume \"(b, a) \\<in> r\" and \"\\<forall>c. (c, b) \\<in> r \\<and> (c, a) \\<in> r \\<longrightarrow> phi c\"\n        then have \"\\<forall>c. (c, b) \\<in> r \\<longrightarrow> phi c\"\n          using assms trans_def[of r] by blast\n        with ** show \"phi b\" by blast\n      qed\n      ultimately show \"chi b\"\n        by (auto simp add: chi_def R_def)\n    qed\n    finally have  \"\\<forall>b. chi b\" .\n    with ** chi_def show \"phi a\" by blast\n  qed\n  ultimately show ?thesis unfolding R_def by blast\nqed\n\ntext\\<open>A transitive relation is well-founded if all initial segments are finite.\\<close>\ncorollary wf_finite_segments:\n  assumes \"irrefl r\" and \"trans r\" and \"\\<And>x. finite {y. (y, x) \\<in> r}\"\n  shows \"wf r\"\nproof -\n  have \"\\<And>a. acyclic (r \\<inter> {x. (x, a) \\<in> r} \\<times> {x. (x, a) \\<in> r})\"\n  proof -\n    fix a\n    have \"trans (r \\<inter> ({x. (x, a) \\<in> r} \\<times> {x. (x, a) \\<in> r}))\"\n      using assms unfolding trans_def Field_def by blast\n    then show \"acyclic (r \\<inter> {x. (x, a) \\<in> r} \\<times> {x. (x, a) \\<in> r})\"\n      using assms acyclic_def assms irrefl_def by fastforce\n  qed\n  then show ?thesis\n    by (clarsimp simp: trans_wf_iff wf_iff_acyclic_if_finite converse_def assms)\nqed\n\ntext \\<open>The next lemma is a variation of \\<open>wf_eq_minimal\\<close> from Wellfounded,\n  allowing one to assume the set included in the field.\\<close>\n\nlemma wf_eq_minimal2: \"wf r \\<longleftrightarrow> (\\<forall>A. A \\<subseteq> Field r \\<and> A \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a', a) \\<notin> r))\"\nproof-\n  let ?phi = \"\\<lambda>A. A \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a',a) \\<notin> r)\"\n  have \"wf r \\<longleftrightarrow> (\\<forall>A. ?phi A)\"\n  proof\n    assume \"wf r\"\n    show  \"\\<forall>A. ?phi A\"\n    proof clarify\n      fix A:: \"'a set\"\n      assume \"A \\<noteq> {}\"\n      then obtain x where \"x \\<in> A\"\n        by auto\n      show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a', a) \\<notin> r\"\n        apply (rule wfE_min[of r x A])\n          apply fact+\n        by blast\n    qed\n  next\n    assume *: \"\\<forall>A. ?phi A\"\n    then show \"wf r\"\n      apply (clarsimp simp: ex_in_conv [THEN sym])\n      apply (rule wfI_min)\n      by fast\n  qed\n  also have \"(\\<forall>A. ?phi A) \\<longleftrightarrow> (\\<forall>B \\<subseteq> Field r. ?phi B)\"\n  proof\n    assume \"\\<forall>A. ?phi A\"\n    then show \"\\<forall>B \\<subseteq> Field r. ?phi B\" by simp\n  next\n    assume *: \"\\<forall>B \\<subseteq> Field r. ?phi B\"\n    show \"\\<forall>A. ?phi A\"\n    proof clarify\n      fix A :: \"'a set\"\n      assume **: \"A \\<noteq> {}\"\n      define B where \"B = A \\<inter> Field r\"\n      show \"\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a', a) \\<notin> r\"\n      proof (cases \"B = {}\")\n        case True\n        with ** obtain a where a: \"a \\<in> A\" \"a \\<notin> Field r\"\n          unfolding B_def by blast\n        with a have \"\\<forall>a' \\<in> A. (a',a) \\<notin> r\"\n          unfolding Field_def by blast\n        with a show ?thesis by blast\n      next\n        case False\n        have \"B \\<subseteq> Field r\" unfolding B_def by blast\n        with False * obtain a where a: \"a \\<in> B\" \"\\<forall>a' \\<in> B. (a', a) \\<notin> r\"\n          by blast\n        have \"(a', a) \\<notin> r\" if \"a' \\<in> A\" for a'\n        proof\n          assume a'a: \"(a', a) \\<in> r\"\n          with that have \"a' \\<in> B\" unfolding B_def Field_def by blast\n          with a a'a show False by blast\n        qed\n        with a show ?thesis unfolding B_def by blast\n      qed\n    qed\n  qed\n  finally show ?thesis by blast\nqed\n\n\nsubsubsection \\<open>Characterizations of well-foundedness\\<close>\n\ntext \\<open>\n  The next lemma and its corollary enable one to prove that a linear order is\n  a well-order in a way which is more standard than via well-foundedness of\n  the strict version of the relation.\n\\<close>\n\nlemma Linear_order_wf_diff_Id:\n  assumes \"Linear_order r\"\n  shows \"wf (r - Id) \\<longleftrightarrow> (\\<forall>A \\<subseteq> Field r. A \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r))\"\nproof (cases \"r \\<subseteq> Id\")\n  case True\n  then have *: \"r - Id = {}\" by blast\n  have \"wf (r - Id)\" by (simp add: *)\n  moreover have \"\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r\"\n    if *: \"A \\<subseteq> Field r\" and **: \"A \\<noteq> {}\" for A\n  proof -\n    from \\<open>Linear_order r\\<close> True\n    obtain a where a: \"r = {} \\<or> r = {(a, a)}\"\n      unfolding order_on_defs using Total_subset_Id [of r] by blast\n    with * ** have \"A = {a} \\<and> r = {(a, a)}\"\n      unfolding Field_def by blast\n    with a show ?thesis by blast\n  qed\n  ultimately show ?thesis by blast\nnext\n  case False\n  with \\<open>Linear_order r\\<close> have Field: \"Field r = Field (r - Id)\"\n    unfolding order_on_defs using Total_Id_Field [of r] by blast\n  show ?thesis\n  proof\n    assume *: \"wf (r - Id)\"\n    show \"\\<forall>A \\<subseteq> Field r. A \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r)\"\n    proof clarify\n      fix A\n      assume **: \"A \\<subseteq> Field r\" and ***: \"A \\<noteq> {}\"\n      then have \"\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a',a) \\<notin> r - Id\"\n        using Field * unfolding wf_eq_minimal2 by simp\n      moreover have \"\\<forall>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r \\<longleftrightarrow> (a', a) \\<notin> r - Id\"\n        using Linear_order_in_diff_Id [OF \\<open>Linear_order r\\<close>] ** by blast\n      ultimately show \"\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r\" by blast\n    qed\n  next\n    assume *: \"\\<forall>A \\<subseteq> Field r. A \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r)\"\n    show \"wf (r - Id)\"\n      unfolding wf_eq_minimal2\n    proof clarify\n      fix A\n      assume **: \"A \\<subseteq> Field(r - Id)\" and ***: \"A \\<noteq> {}\"\n      then have \"\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a,a') \\<in> r\"\n        using Field * by simp\n      moreover have \"\\<forall>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r \\<longleftrightarrow> (a', a) \\<notin> r - Id\"\n        using Linear_order_in_diff_Id [OF \\<open>Linear_order r\\<close>] ** mono_Field[of \"r - Id\" r] by blast\n      ultimately show \"\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a',a) \\<notin> r - Id\"\n        by blast\n    qed\n  qed\nqed\n\ncorollary Linear_order_Well_order_iff:\n  \"Linear_order r \\<Longrightarrow>\n    Well_order r \\<longleftrightarrow> (\\<forall>A \\<subseteq> Field r. A \\<noteq> {} \\<longrightarrow> (\\<exists>a \\<in> A. \\<forall>a' \\<in> A. (a, a') \\<in> r))\"\n  unfolding well_order_on_def using Linear_order_wf_diff_Id[of r] by blast\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Order_Relation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.8933094096048376, "lm_q1q2_score": 0.7882811219254701}}
{"text": "theory leftpad\n  imports Main \n  \"~~/src/HOL/Library/Code_Target_Nat\"\nbegin\n\nsection \\<open>define leftpad\\<close>\n  \n(* left pad. Takes a padding character, a string, and a total length, returns\nthe string padded to that length with that character. If length is less than\nthe length of the string, does nothing. \n\ninspired by https://www.hillelwayne.com/post/theorem-prover-showdown/\n*)\n\nfun rightPad :: \"'a => 'a list => nat => 'a list\" where\n  \"rightPad p [] 0 = []\" |\n  \"rightPad p [] (Suc n) = p # (rightPad p [] n)\" |\n  \"rightPad p (x # xs) 0 = (x # xs)\" |\n  \"rightPad p (x # xs) (Suc n) = x # (rightPad p xs n)\"\n\nfun leftPad :: \"'a => 'a list => nat => 'a list\" where\n  \"leftPad p xs n = rev (rightPad p (rev xs) n)\"\n  \nvalue \"leftPad 0 [1,2] 1 :: nat list\"\nvalue \"leftPad 0 [1,2] 4 :: nat list\"\nvalue \"leftPad 9 [1,1] 3 :: nat list\"\n  \n(* Prove: \n\nYou have to specify it’s the right length,\n\nthat the added characters are all the padding character,\n\nand that the suffix is the original string. *)\n\nsection \\<open>Proofs\\<close>\n\nsubsection \\<open>right pad\\<close>\n\nlemma rightpad_empty_is_replicate:\"\\<lbrakk>padTo = n\\<rbrakk> \\<Longrightarrow> rightPad p [] padTo = replicate n p\"\nproof(induction padTo arbitrary: n)\n  case 0\n  then show ?case \n    by simp \nnext\n  case (Suc padTo)\n  then show ?case \n    by auto\nqed\n\ntext \"additional characters are padding\"\nlemma right_pad_adds_padding_character:\n  fixes lst :: \"'a list\"\n    and p :: \"'a\"\n    and padTo :: nat\n  assumes \"length lst < padTo\"\n    and \"length lst + n = padTo\"\n  shows \"\\<lbrakk>length lst < padTo; length lst + n = padTo\\<rbrakk> \n      \\<Longrightarrow> drop (length lst) (rightPad p lst padTo) = replicate n p\"\nproof(induction lst arbitrary: padTo)\n  case Nil\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc padTo)\n    then show ?case \n      by (simp add: rightpad_empty_is_replicate)\n  qed\nnext\n  case (Cons l ls)\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc padT)\n    then show ?case by simp\n  qed\nqed\n\ntext \"prefix of result is the list\"\nlemma right_pad_prefix_is_list:\n  fixes lst :: \"'a list\"\n    and p :: \"'a\"\n    and padTo :: nat\n  shows \"take (length lst) (rightPad p lst padTo) = lst\"\nproof(induction lst arbitrary: padTo)\n  case Nil\n  then show ?case \n    by simp\nnext\n  case (Cons a lst)\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case \n      by simp\n  next\n    case (Suc padTo)\n    then show ?case \n      by simp\n  qed\nqed\n\ntext \"length is correct\"\nlemma right_pad_length_is_correct:\n  shows \"length (rightPad p lst padTo) = max (length lst) padTo\"\nproof(induction lst arbitrary: padTo)\n  case Nil\n  then show ?case \n    by (simp add: rightpad_empty_is_replicate)\nnext\n  case (Cons a lst)\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case \n      by simp\n  next\n    case (Suc padTo)\n    then show ?case \n      by simp\n  qed\nqed\n\nsubsection \\<open>left pad\\<close> \n\ntext \"length is correct\"\ntheorem left_pad_length_is_correct:\n  shows \"length (leftPad p lst padTo) = max (length lst) padTo\"\n  by (simp add: right_pad_length_is_correct)\n\ntext \"suffix of result is the list\"\ntheorem left_pad_suffix_is_list:\n  fixes lst :: \"'a list\"\n    and p :: \"'a\"\n    and padTo :: nat\n  assumes \"length lst < padTo\"\n    and \"length lst + n = padTo\"\n  shows \"\\<lbrakk>length lst + n = padTo\\<rbrakk> \\<Longrightarrow> drop n (leftPad p lst padTo) = lst\"\nproof(induction lst)\n  case Nil\n  then show ?case \n    by (simp add: rightpad_empty_is_replicate) \nnext\n  case (Cons l ls)\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case \n      by simp \n  next\n    case (Suc padTo\\<^sub>p)\n    have \"drop n (leftPad p ls padTo\\<^sub>p) = ls\" \n      apply auto\n    proof -\n      have \"length ls \\<le> padTo\\<^sub>p\"\n        by (metis (no_types) Suc.prems(2) Suc_inject add.commute add_Suc_right le_add1 length_Cons)\n      then have \"length (rightPad p (rev ls) padTo\\<^sub>p) = padTo\\<^sub>p\"\n        by (simp add: right_pad_length_is_correct)\n      then have \"length (rightPad p (rev ls) padTo\\<^sub>p) - n = length ls\"\n        by (metis (no_types) Suc.prems(2) add.commute add_Suc_right add_diff_cancel_left' length_Cons)\n      then show \"drop n (rev (rightPad p (rev ls) padTo\\<^sub>p)) = ls\"\n        by (metis (no_types) drop_rev length_rev rev_rev_ident right_pad_prefix_is_list)\n    qed\n    then show ?case\n      apply auto\n      proof -\n        have \"length (rightPad p (rev ls @ [l]) (Suc padTo\\<^sub>p)) - n = length (l # ls)\"\n          by (metis Suc.prems(2) add_diff_cancel_right' le_add1 length_rev max_def_raw rev.simps(2) right_pad_length_is_correct)\n        then show \"drop n (rev (rightPad p (rev ls @ [l]) (Suc padTo\\<^sub>p))) = l # ls\"\n          by (metis drop_rev length_rev rev.simps(2) rev_swap right_pad_prefix_is_list)\n      qed\n  qed    \nqed\n\ntext \"additional characters are padding\"\ntheorem left_pad_adds_padding_character:\n  fixes lst :: \"'a list\"\n    and p :: \"'a\"\n    and padTo :: nat\n    and n :: nat\n  assumes \"length lst < padTo\"\n    and \"length lst + n = padTo\"\n  shows \"\\<lbrakk>length lst < padTo; length lst + n = padTo\\<rbrakk> \n      \\<Longrightarrow> take n (leftPad p lst padTo) = replicate n p\"\nproof(induction lst arbitrary: padTo)\n  case Nil\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc padTo)\n    then show ?case \n      apply auto \n      by (simp add: replicate_append_same rightpad_empty_is_replicate)\n  qed\nnext\n  case (Cons l ls)\n  then show ?case \n  proof(induction padTo)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc padTo\\<^sub>p)\n    then show ?case \n      apply auto\n    proof -\n      assume a1: \"padTo\\<^sub>p = length ls + n\"\n      have f2: \"length (rightPad p (rev ls @ [l]) (Suc (length ls + n))) = length (l # ls) + n\"\n        by (simp add: right_pad_length_is_correct)\n      have f3: \"length (rev ls @ [l]) + n = Suc padTo\\<^sub>p\"\n        using Suc.prems(3) by auto\n      have \"length (rev ls @ [l]) < Suc padTo\\<^sub>p\"\n        using Suc.prems(2) by force\n      then have \"drop (length (rev ls @ [l])) (rightPad p (rev ls @ [l]) (Suc padTo\\<^sub>p)) = replicate n p\"\n        using f3 by (metis (full_types) right_pad_adds_padding_character)\n      then show \"take n (rev (rightPad p (rev ls @ [l]) (Suc (length ls + n)))) = replicate n p\"\n        using f2 a1 by (simp add: take_rev)\n    qed \n  qed\nqed", "meta": {"author": "gittywithexcitement", "repo": "isabelle", "sha": "42c53b2797e1b14c741c316f2585449b818a8f07", "save_path": "github-repos/isabelle/gittywithexcitement-isabelle", "path": "github-repos/isabelle/gittywithexcitement-isabelle/isabelle-42c53b2797e1b14c741c316f2585449b818a8f07/theorem-prover-showdown/leftpad.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.893309411735131, "lm_q2_score": 0.8824278587245936, "lm_q1q2_score": 0.788281111375958}}
{"text": "(*\n    Authors:    Jose Divasón\n                Maximilian Haslbeck\n                Sebastiaan Joosten\n                René Thiemann\n                Akihisa Yamada\n    License:    BSD\n*)\n\nsection \\<open>Norms\\<close>\n\ntext \\<open>In this theory we provide the basic definitions and properties of several \n  norms of vectors and polynomials.\n\\<close> \n\ntheory Norms\n  imports \"HOL-Computational_Algebra.Polynomial\" \n    \"HOL-Library.Adhoc_Overloading\"\n    \"Jordan_Normal_Form.Conjugate\"\n    \"Algebraic_Numbers.Resultant\" (* only for poly_of_vec *)\n    Missing_Lemmas\nbegin\n\nsubsection \\<open>L-\\<open>\\<infinity>\\<close> Norms\\<close>\n\nconsts linf_norm :: \"'a \\<Rightarrow> 'b\" (\"\\<parallel>(_)\\<parallel>\\<^sub>\\<infinity>\")\n\ndefinition linf_norm_vec where \"linf_norm_vec v \\<equiv> max_list (map abs (list_of_vec v) @ [0])\"\nadhoc_overloading linf_norm linf_norm_vec\n\ndefinition linf_norm_poly where \"linf_norm_poly f \\<equiv> max_list (map abs (coeffs f) @ [0])\"\nadhoc_overloading linf_norm linf_norm_poly\n\nlemma linf_norm_vec: \"\\<parallel>vec n f\\<parallel>\\<^sub>\\<infinity> = max_list (map (abs \\<circ> f) [0..<n] @ [0])\"\n  by (simp add: linf_norm_vec_def)\n\nlemma linf_norm_vec_vCons[simp]: \"\\<parallel>vCons a v\\<parallel>\\<^sub>\\<infinity> = max \\<bar>a\\<bar> \\<parallel>v\\<parallel>\\<^sub>\\<infinity>\"\n  by (auto simp: linf_norm_vec_def max_list_Cons)\n\nlemma linf_norm_vec_0 [simp]: \"\\<parallel>vec 0 f\\<parallel>\\<^sub>\\<infinity> = 0\" by (simp add: linf_norm_vec_def)\n\nlemma linf_norm_zero_vec [simp]: \"\\<parallel>0\\<^sub>v n :: 'a :: ordered_ab_group_add_abs vec\\<parallel>\\<^sub>\\<infinity> = 0\"\n  by (induct n, simp add: zero_vec_def, auto simp: zero_vec_Suc)\n\nlemma linf_norm_vec_ge_0 [intro!]:\n  fixes v :: \"'a :: ordered_ab_group_add_abs vec\"\n  shows \"\\<parallel>v\\<parallel>\\<^sub>\\<infinity> \\<ge> 0\"\n  by (induct v, auto simp: max_def)\n\nlemma linf_norm_vec_eq_0 [simp]:\n  fixes v :: \"'a :: ordered_ab_group_add_abs vec\"\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"\\<parallel>v\\<parallel>\\<^sub>\\<infinity> = 0 \\<longleftrightarrow> v = 0\\<^sub>v n\"\n  by (insert assms, induct rule: carrier_vec_induct, auto simp: zero_vec_Suc max_def)\n\nlemma linf_norm_vec_greater_0 [simp]:\n  fixes v :: \"'a :: ordered_ab_group_add_abs vec\"\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"\\<parallel>v\\<parallel>\\<^sub>\\<infinity> > 0 \\<longleftrightarrow> v \\<noteq> 0\\<^sub>v n\"\n  by (insert assms, induct rule: carrier_vec_induct, auto simp: zero_vec_Suc max_def)\n\nlemma linf_norm_poly_0 [simp]: \"\\<parallel>0::_ poly\\<parallel>\\<^sub>\\<infinity> = 0\"\n  by (simp add: linf_norm_poly_def)\n\nlemma linf_norm_pCons [simp]:\n  fixes p :: \"'a :: ordered_ab_group_add_abs poly\"\n  shows \"\\<parallel>pCons a p\\<parallel>\\<^sub>\\<infinity> = max \\<bar>a\\<bar> \\<parallel>p\\<parallel>\\<^sub>\\<infinity>\"\n  by (cases \"p = 0\", cases \"a = 0\", auto simp: linf_norm_poly_def max_list_Cons)\n\nlemma linf_norm_poly_ge_0 [intro!]:\n  fixes f :: \"'a :: ordered_ab_group_add_abs poly\"\n  shows \"\\<parallel>f\\<parallel>\\<^sub>\\<infinity> \\<ge> 0\"\n  by (induct f, auto simp: max_def)\n\nlemma linf_norm_poly_eq_0 [simp]:\n  fixes f :: \"'a :: ordered_ab_group_add_abs poly\"\n  shows \"\\<parallel>f\\<parallel>\\<^sub>\\<infinity> = 0 \\<longleftrightarrow> f = 0\"\n  by (induct f, auto simp: max_def)\n\nlemma linf_norm_poly_greater_0 [simp]:\n  fixes f :: \"'a :: ordered_ab_group_add_abs poly\"\n  shows \"\\<parallel>f\\<parallel>\\<^sub>\\<infinity> > 0 \\<longleftrightarrow> f \\<noteq> 0\"\n  by (induct f, auto simp: max_def)\n\nsubsection \\<open>Square Norms\\<close>\n\nconsts sq_norm :: \"'a \\<Rightarrow> 'b\" (\"\\<parallel>(_)\\<parallel>\\<^sup>2\")\n\nabbreviation \"sq_norm_conjugate x \\<equiv> x * conjugate x\"\nadhoc_overloading sq_norm sq_norm_conjugate\n\nsubsubsection \\<open>Square norms for vectors\\<close>\n\ntext \\<open>We prefer sum\\_list over sum because it is not essentially dependent on commutativity,\n  and easier for proving.\n\\<close>\ndefinition \"sq_norm_vec v \\<equiv> \\<Sum>x \\<leftarrow> list_of_vec v. \\<parallel>x\\<parallel>\\<^sup>2\"\nadhoc_overloading sq_norm sq_norm_vec\n\nlemma sq_norm_vec_vCons[simp]: \"\\<parallel>vCons a v\\<parallel>\\<^sup>2 = \\<parallel>a\\<parallel>\\<^sup>2 + \\<parallel>v\\<parallel>\\<^sup>2\"\n  by (simp add: sq_norm_vec_def)\n\nlemma sq_norm_vec_0[simp]: \"\\<parallel>vec 0 f\\<parallel>\\<^sup>2 = 0\"\n  by (simp add: sq_norm_vec_def)\n\nlemma sq_norm_vec_as_cscalar_prod:\n  fixes v :: \"'a :: conjugatable_ring vec\"\n  shows \"\\<parallel>v\\<parallel>\\<^sup>2 = v \\<bullet>c v\"\n  by (induct v, simp_all add: sq_norm_vec_def)\n\nlemma sq_norm_zero_vec[simp]: \"\\<parallel>0\\<^sub>v n :: 'a :: conjugatable_ring vec\\<parallel>\\<^sup>2 = 0\"\n  by (simp add: sq_norm_vec_as_cscalar_prod)\n\nlemmas sq_norm_vec_ge_0 [intro!] = conjugate_square_ge_0_vec[folded sq_norm_vec_as_cscalar_prod]\n\nlemmas sq_norm_vec_eq_0 [simp] = conjugate_square_eq_0_vec[folded sq_norm_vec_as_cscalar_prod]\n\nlemmas sq_norm_vec_greater_0 [simp] = conjugate_square_greater_0_vec[folded sq_norm_vec_as_cscalar_prod]\n\nsubsubsection \\<open>Square norm for polynomials\\<close>\n\ndefinition sq_norm_poly where \"sq_norm_poly p \\<equiv> \\<Sum>a\\<leftarrow>coeffs p. \\<parallel>a\\<parallel>\\<^sup>2\"\n\nadhoc_overloading sq_norm sq_norm_poly\n\nlemma sq_norm_poly_0 [simp]: \"\\<parallel>0::_poly\\<parallel>\\<^sup>2 = 0\"\n  by (auto simp: sq_norm_poly_def)\n\nlemma sq_norm_poly_pCons [simp]:\n  fixes a :: \"'a :: conjugatable_ring\"\n  shows \"\\<parallel>pCons a p\\<parallel>\\<^sup>2 = \\<parallel>a\\<parallel>\\<^sup>2 + \\<parallel>p\\<parallel>\\<^sup>2\"\n  by (cases \"p = 0\"; cases \"a = 0\", auto simp: sq_norm_poly_def)\n\n\n\nlemma sq_norm_poly_eq_0 [simp]:\n  fixes p :: \"'a :: {conjugatable_ordered_ring,ring_no_zero_divisors} poly\"\n  shows \"\\<parallel>p\\<parallel>\\<^sup>2 = 0 \\<longleftrightarrow> p = 0\"\nproof (induct p)\n  case IH: (pCons a p)\n  show ?case\n  proof (cases \"a = 0\")\n    case True\n    with IH show ?thesis by simp\n  next\n    case False\n    then have \"\\<parallel>a\\<parallel>\\<^sup>2 + \\<parallel>p\\<parallel>\\<^sup>2 > 0\" by (intro add_pos_nonneg, auto)\n    then show ?thesis by auto\n  qed\nqed simp\n\nlemma sq_norm_poly_pos [simp]:\n  fixes p :: \"'a :: {conjugatable_ordered_ring,ring_no_zero_divisors} poly\"\n  shows \"\\<parallel>p\\<parallel>\\<^sup>2 > 0 \\<longleftrightarrow> p \\<noteq> 0\"\n  by (auto simp: less_le)\n\nlemma sq_norm_vec_of_poly [simp]:\n  fixes p :: \"'a :: conjugatable_ring poly\"\n  shows \"\\<parallel>vec_of_poly p\\<parallel>\\<^sup>2 = \\<parallel>p\\<parallel>\\<^sup>2\"\n  apply (unfold sq_norm_poly_def sq_norm_vec_def)\n  apply (fold sum_mset_sum_list)\n  apply auto.\n\nlemma sq_norm_poly_of_vec [simp]:\n  fixes v :: \"'a :: conjugatable_ring vec\"\n  shows \"\\<parallel>poly_of_vec v\\<parallel>\\<^sup>2 = \\<parallel>v\\<parallel>\\<^sup>2\"\n  apply (unfold sq_norm_poly_def sq_norm_vec_def coeffs_poly_of_vec)\n  apply (fold rev_map)\n  apply (fold sum_mset_sum_list)\n  apply (unfold mset_rev)\n  apply (unfold sum_mset_sum_list)\n  by (auto intro: sum_list_map_dropWhile0)\n\nsubsection \\<open>Relating Norms\\<close>\n\ntext \\<open>A class where ordering around 0 is linear.\\<close>\nabbreviation (in ordered_semiring) is_real where \"is_real a \\<equiv> a < 0 \\<or> a = 0 \\<or> 0 < a\"\n\nclass semiring_real_line = ordered_semiring_strict + ordered_semiring_0 +\n  assumes add_pos_neg_is_real: \"a > 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> is_real (a + b)\"\n      and mult_neg_neg: \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> 0 < a * b\"\n      and pos_pos_linear: \"0 < a \\<Longrightarrow> 0 < b \\<Longrightarrow> a < b \\<or> a = b \\<or> b < a\"\n      and neg_neg_linear: \"a < 0 \\<Longrightarrow> b < 0 \\<Longrightarrow> a < b \\<or> a = b \\<or> b < a\"\nbegin\n\nlemma add_neg_pos_is_real: \"a < 0 \\<Longrightarrow> b > 0 \\<Longrightarrow> is_real (a + b)\"\n  using add_pos_neg_is_real[of b a] by (simp add: ac_simps)\n\nlemma nonneg_linorder_cases [consumes 2, case_names less eq greater]:\n  assumes \"0 \\<le> a\" and \"0 \\<le> b\"\n      and \"a < b \\<Longrightarrow> thesis\" \"a = b \\<Longrightarrow> thesis\" \"b < a \\<Longrightarrow> thesis\"\n  shows thesis\n  using assms pos_pos_linear by (auto simp: le_less)\n\nlemma nonpos_linorder_cases [consumes 2, case_names less eq greater]:\n  assumes \"a \\<le> 0\" \"b \\<le> 0\"\n      and \"a < b \\<Longrightarrow> thesis\" \"a = b \\<Longrightarrow> thesis\" \"b < a \\<Longrightarrow> thesis\"\n  shows thesis\n  using assms neg_neg_linear by (auto simp: le_less)\n\nlemma real_linear:\n  assumes \"is_real a\" and \"is_real b\" shows \"a < b \\<or> a = b \\<or> b < a\"\n  using pos_pos_linear neg_neg_linear assms by (auto dest: less_trans[of _ 0])\n\nlemma real_linorder_cases [consumes 2, case_names less eq greater]:\n  assumes real: \"is_real a\" \"is_real b\"\n      and cases: \"a < b \\<Longrightarrow> thesis\" \"a = b \\<Longrightarrow> thesis\" \"b < a \\<Longrightarrow> thesis\"\n  shows thesis\n  using real_linear[OF real] cases by auto\n\nlemma\n  assumes a: \"is_real a\" and b: \"is_real b\"\n  shows real_add_le_cancel_left_pos: \"c + a \\<le> c + b \\<longleftrightarrow> a \\<le> b\"\n    and real_add_less_cancel_left_pos: \"c + a < c + b \\<longleftrightarrow> a < b\"\n    and real_add_le_cancel_right_pos: \"a + c \\<le> b + c \\<longleftrightarrow> a \\<le> b\"\n    and real_add_less_cancel_right_pos: \"a + c < b + c \\<longleftrightarrow> a < b\"\n  using add_strict_left_mono[of b a c] add_strict_left_mono[of a b c]\n  using add_strict_right_mono[of b a c] add_strict_right_mono[of a b c]\n  by (atomize(full), cases rule: real_linorder_cases[OF a b], auto)\n\nlemma\n  assumes a: \"is_real a\" and b: \"is_real b\" and c: \"0 < c\"\n  shows real_mult_le_cancel_left_pos: \"c * a \\<le> c * b \\<longleftrightarrow> a \\<le> b\"\n    and real_mult_less_cancel_left_pos: \"c * a < c * b \\<longleftrightarrow> a < b\"\n    and real_mult_le_cancel_right_pos: \"a * c \\<le> b * c \\<longleftrightarrow> a \\<le> b\"\n    and real_mult_less_cancel_right_pos: \"a * c < b * c \\<longleftrightarrow> a < b\"\n  using mult_strict_left_mono[of b a c] mult_strict_left_mono[of a b c] c\n  using mult_strict_right_mono[of b a c] mult_strict_right_mono[of a b c] c\n  by (atomize(full), cases rule: real_linorder_cases[OF a b], auto)\n\nlemma\n  assumes a: \"is_real a\" and b: \"is_real b\"\n  shows not_le_real: \"\\<not> a \\<ge> b \\<longleftrightarrow> a < b\"\n    and not_less_real: \"\\<not> a > b \\<longleftrightarrow> a \\<le> b\"\n  by (atomize(full), cases rule: real_linorder_cases[OF a b], auto simp: less_imp_le)\n\nlemma real_mult_eq_0_iff:\n  assumes a: \"is_real a\" and b: \"is_real b\"\n  shows \"a * b = 0 \\<longleftrightarrow> a = 0 \\<or> b = 0\"\nproof-\n  { assume l: \"a * b = 0\" and \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n    with a b have \"a < 0 \\<or> 0 < a\" and \"b < 0 \\<or> 0 < b\" by auto\n    then have \"False\" using mult_pos_pos[of a b] mult_pos_neg[of a b] mult_neg_pos[of a b] mult_neg_neg[of a b]\n      by (auto simp:l)\n  } then show ?thesis by auto\nqed\n\nend\n\nlemma real_pos_mult_max:\n  fixes a b c :: \"'a :: semiring_real_line\"\n  assumes c: \"c > 0\" and a: \"is_real a\" and b: \"is_real b\"\n  shows \"c * max a b = max (c * a) (c * b)\"\n  by (rule hom_max, simp add: real_mult_le_cancel_left_pos[OF a b c])\n\nclass ring_abs_real_line = ordered_ring_abs + semiring_real_line\n\nclass semiring_1_real_line = semiring_real_line + monoid_mult + zero_less_one\nbegin\n\nsubclass ordered_semiring_1 by (unfold_locales, auto)\n\nlemma power_both_mono: \"1 \\<le> a \\<Longrightarrow> m \\<le> n \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a ^ m \\<le> b ^ n\"\n  using power_mono[of a b n] power_increasing[of m n a]\n  by (auto simp: order.trans[OF zero_le_one])\n\nlemma power_pos:\n  assumes a0: \"0 < a\" shows \"0 < a ^ n\"\n  by (induct n, insert mult_strict_mono[OF a0] a0, auto)\n\nlemma power_neg:\n  assumes a0: \"a < 0\" shows \"odd n \\<Longrightarrow> a ^ n < 0\" and \"even n \\<Longrightarrow> a ^ n > 0\"\n  by (atomize(full), induct n, insert a0, auto simp add: mult_pos_neg2 mult_neg_neg)\n\nlemma power_ge_0_iff:\n  assumes a: \"is_real a\"\n  shows \"0 \\<le> a ^ n \\<longleftrightarrow> 0 \\<le> a \\<or> even n\"\nusing a proof (elim disjE)\n  assume \"a < 0\"\n  with power_neg[OF this, of n] show ?thesis by(cases \"even n\", auto)\nnext\n  assume \"0 < a\"\n  with power_pos[OF this] show ?thesis by auto\nnext\n  assume \"a = 0\"\n  then show ?thesis by (auto simp:power_0_left)\nqed\n\nlemma nonneg_power_less:\n  assumes \"0 \\<le> a\" and \"0 \\<le> b\" shows \"a^n < b^n \\<longleftrightarrow> n > 0 \\<and> a < b\"\nproof (insert assms, induct n arbitrary: a b)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n)\n  note a = \\<open>0 \\<le> a\\<close>\n  note b = \\<open>0 \\<le> b\\<close>\n  show ?case\n  proof (cases \"n > 0\")\n    case True\n    from a b show ?thesis\n    proof (cases rule: nonneg_linorder_cases)\n      case less\n      then show ?thesis by (auto simp: Suc.hyps[OF a b] True intro!:mult_strict_mono' a b zero_le_power)\n    next\n      case eq\n      then show ?thesis by simp\n    next\n      case greater\n      with Suc.hyps[OF b a] True have \"b ^ n < a ^ n\" by auto\n      with mult_strict_mono'[OF greater this] b greater\n      show ?thesis by auto\n    qed\n  qed auto\nqed\n\nlemma power_strict_mono:\n  shows \"a < b \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 < n \\<Longrightarrow> a ^ n < b ^ n\"\n  by (subst nonneg_power_less, auto)\n\nlemma nonneg_power_le:\n  assumes \"0 \\<le> a\" and \"0 \\<le> b\" shows \"a^n \\<le> b^n \\<longleftrightarrow> n = 0 \\<or> a \\<le> b\"\nusing assms proof (cases rule: nonneg_linorder_cases)\n  case less\n  with power_strict_mono[OF this, of n] assms show ?thesis by (cases n, auto)\nnext\n  case eq\n  then show ?thesis by auto\nnext\n  case greater\n  with power_strict_mono[OF this, of n] assms show ?thesis by (cases n, auto)\nqed\n\nend\n\nsubclass (in linordered_idom) semiring_1_real_line\n  apply unfold_locales\n  by (auto simp: mult_strict_left_mono mult_strict_right_mono mult_neg_neg)\n\nclass ring_1_abs_real_line = ring_abs_real_line + semiring_1_real_line\nbegin\n\nsubclass ring_1..\n\nlemma abs_cases:\n  assumes \"a = 0 \\<Longrightarrow> thesis\" and \"\\<bar>a\\<bar> > 0 \\<Longrightarrow> thesis\" shows thesis\n  using assms by auto\n\nlemma abs_linorder_cases[case_names less eq greater]:\n  assumes \"\\<bar>a\\<bar> < \\<bar>b\\<bar> \\<Longrightarrow> thesis\" and \"\\<bar>a\\<bar> = \\<bar>b\\<bar> \\<Longrightarrow> thesis\" and \"\\<bar>b\\<bar> < \\<bar>a\\<bar> \\<Longrightarrow> thesis\"\n  shows thesis\n  apply (cases rule: nonneg_linorder_cases[of \"\\<bar>a\\<bar>\" \"\\<bar>b\\<bar>\"])\n  using assms by auto\n\n\n\nlemma abs_power_less [simp]: \"\\<bar>a\\<bar>^n < \\<bar>b\\<bar>^n \\<longleftrightarrow> n > 0 \\<and> \\<bar>a\\<bar> < \\<bar>b\\<bar>\"\n  by (subst nonneg_power_less, auto)\n\nlemma abs_power_le [simp]: \"\\<bar>a\\<bar>^n \\<le> \\<bar>b\\<bar>^n \\<longleftrightarrow> n = 0 \\<or> \\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\n  by (subst nonneg_power_le, auto)\n\nlemma abs_power_pos [simp]: \"\\<bar>a\\<bar>^n > 0 \\<longleftrightarrow> a \\<noteq> 0 \\<or> n = 0\"\n  using power_pos[of \"\\<bar>a\\<bar>\"] by (cases \"n\", auto)\n\nlemma abs_power_nonneg [intro!]: \"\\<bar>a\\<bar>^n \\<ge> 0\" by auto\n\nlemma abs_power_eq_0 [simp]: \"\\<bar>a\\<bar>^n = 0 \\<longleftrightarrow> a = 0 \\<and> n \\<noteq> 0\"\n  apply (induct n, force)\n  apply (unfold power_Suc)\n  apply (subst real_mult_eq_0_iff, auto).\n\nend\n\ninstance nat :: semiring_1_real_line by (intro_classes, auto)\ninstance int :: ring_1_abs_real_line..\n\nlemma vec_index_vec_of_list [simp]: \"vec_of_list xs $ i = xs ! i\"\n  by transfer (auto simp: mk_vec_def undef_vec_def dest: empty_nth)\n\nlemma vec_of_list_append: \"vec_of_list (xs @ ys) = vec_of_list xs @\\<^sub>v vec_of_list ys\"\n  by (auto simp: nth_append)\n\nlemma linf_norm_vec_of_list:\n  \"\\<parallel>vec_of_list xs\\<parallel>\\<^sub>\\<infinity> = max_list (map abs xs @ [0])\"\n  by (simp add: linf_norm_vec_def)\n\nlemma linf_norm_vec_as_Greatest:\n  fixes v :: \"'a :: ring_1_abs_real_line vec\"\n  shows \"\\<parallel>v\\<parallel>\\<^sub>\\<infinity> = (GREATEST a. a \\<in> abs ` set (list_of_vec v) \\<union> {0})\"\n  unfolding linf_norm_vec_of_list[of \"list_of_vec v\", simplified]\n  by (subst max_list_as_Greatest, auto)\n\nlemma vec_of_poly_pCons:\n  assumes \"f \\<noteq> 0\"\n  shows \"vec_of_poly (pCons a f) = vec_of_poly f @\\<^sub>v vec_of_list [a]\"\n  using assms\n  by (auto simp: vec_eq_iff Suc_diff_le)\n\nlemma vec_of_poly_as_vec_of_list:\n  assumes \"f \\<noteq> 0\"\n  shows \"vec_of_poly f = vec_of_list (rev (coeffs f))\"\nproof (insert assms, induct f)\n  case 0\n  then show ?case by auto\nnext\n  case (pCons a f)\n  then show ?case\n    by (cases \"f = 0\", auto simp: vec_of_list_append vec_of_poly_pCons)\nqed\n\nlemma linf_norm_vec_of_poly [simp]:\n  fixes f :: \"'a :: ring_1_abs_real_line poly\"\n  shows \"\\<parallel>vec_of_poly f\\<parallel>\\<^sub>\\<infinity> = \\<parallel>f\\<parallel>\\<^sub>\\<infinity>\"\nproof (cases \"f = 0\")\n  case False\n  then show ?thesis\n    apply (unfold vec_of_poly_as_vec_of_list linf_norm_vec_of_list linf_norm_poly_def)\n    apply (subst (1 2) max_list_as_Greatest, auto).\nqed simp\n\nlemma linf_norm_poly_as_Greatest:\n  fixes f :: \"'a :: ring_1_abs_real_line poly\"\n  shows \"\\<parallel>f\\<parallel>\\<^sub>\\<infinity> = (GREATEST a. a \\<in> abs ` set (coeffs f) \\<union> {0})\"\n  using linf_norm_vec_as_Greatest[of \"vec_of_poly f\"]\n  by simp\n\nlemma vec_index_le_linf_norm:\n  fixes v :: \"'a :: ring_1_abs_real_line vec\"\n  assumes \"i < dim_vec v\"\n  shows \"\\<bar>v$i\\<bar> \\<le> \\<parallel>v\\<parallel>\\<^sub>\\<infinity>\"\napply (unfold linf_norm_vec_def, rule le_max_list) using assms\napply (auto simp:  in_set_conv_nth intro!: imageI exI[of _ i]).\n\nlemma coeff_le_linf_norm:\n  fixes f :: \"'a :: ring_1_abs_real_line poly\"\n  shows \"\\<bar>coeff f i\\<bar> \\<le> \\<parallel>f\\<parallel>\\<^sub>\\<infinity>\"\n  using vec_index_le_linf_norm[of \"degree f - i\" \"vec_of_poly f\"]\n  by (cases \"i \\<le> degree f\", auto simp: coeff_eq_0)\n\nclass conjugatable_ring_1_abs_real_line = conjugatable_ring + ring_1_abs_real_line + power +\n  assumes sq_norm_as_sq_abs [simp]: \"\\<parallel>a\\<parallel>\\<^sup>2 = \\<bar>a\\<bar>\\<^sup>2\"\nbegin\nsubclass conjugatable_ordered_ring by (unfold_locales, simp)\nend\n\ninstance int :: conjugatable_ring_1_abs_real_line\n  by (intro_classes, simp add: numeral_2_eq_2)\n\ninstance rat :: conjugatable_ring_1_abs_real_line\n  by (intro_classes, simp add: numeral_2_eq_2)\n\ninstance real :: conjugatable_ring_1_abs_real_line\n  by (intro_classes, simp add: numeral_2_eq_2)\n\ninstance complex :: semiring_1_real_line\n  apply intro_classes\n  by (auto simp: complex_eq_iff mult_le_cancel_left mult_le_cancel_right mult_neg_neg)\n\ntext \\<open>\n  Due to the assumption @{thm abs_ge_self} from Groups.thy,\n  @{type complex} cannot be @{class ring_1_abs_real_line}!\n\\<close>\ninstance complex :: ordered_ab_group_add_abs oops\n\nlemma sq_norm_as_sq_abs [simp]: \"(sq_norm :: 'a :: conjugatable_ring_1_abs_real_line \\<Rightarrow> 'a) = power2 \\<circ> abs\"\n  by auto\n\nlemma sq_norm_vec_le_linf_norm:\n  fixes v :: \"'a :: {conjugatable_ring_1_abs_real_line} vec\"\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"\\<parallel>v\\<parallel>\\<^sup>2 \\<le> of_nat n * \\<parallel>v\\<parallel>\\<^sub>\\<infinity>\\<^sup>2\"\nproof (insert assms, induct rule: carrier_vec_induct)\n  case (Suc n a v)\n  have [dest!]: \"\\<not> \\<bar>a\\<bar> \\<le> \\<parallel>v\\<parallel>\\<^sub>\\<infinity> \\<Longrightarrow> of_nat n * \\<parallel>v\\<parallel>\\<^sub>\\<infinity>\\<^sup>2 \\<le> of_nat n * \\<bar>a\\<bar>\\<^sup>2\"\n    by (rule real_linorder_cases[of \"\\<bar>a\\<bar>\" \"\\<parallel>v\\<parallel>\\<^sub>\\<infinity>\"], insert Suc, auto simp: less_le intro!: power_mono mult_left_mono)\n  from Suc show ?case\n    by (auto simp: ring_distribs max_def intro!:add_mono power_mono)\nqed simp\n \nlemma sq_norm_poly_le_linf_norm:\n  fixes p :: \"'a :: {conjugatable_ring_1_abs_real_line} poly\"\n  shows \"\\<parallel>p\\<parallel>\\<^sup>2 \\<le> of_nat (degree p + 1) * \\<parallel>p\\<parallel>\\<^sub>\\<infinity>\\<^sup>2\"\n  using sq_norm_vec_le_linf_norm[of \"vec_of_poly p\" \"degree p + 1\"]\n    by (auto simp: carrier_dim_vec)\n\nlemma coeff_le_sq_norm:\n  fixes f :: \"'a :: {conjugatable_ring_1_abs_real_line} poly\"\n  shows \"\\<bar>coeff f i\\<bar>\\<^sup>2 \\<le> \\<parallel>f\\<parallel>\\<^sup>2\"\nproof (induct f arbitrary: i)\n  case (pCons a f)\n  show ?case\n  proof (cases i)\n    case (Suc ii)\n    note pCons(2)[of ii]\n    also have \"\\<parallel>f\\<parallel>\\<^sup>2 \\<le> \\<bar>a\\<bar>\\<^sup>2 + \\<parallel>f\\<parallel>\\<^sup>2\" by auto\n    finally show ?thesis unfolding Suc by auto\n  qed auto\nqed simp\n\nlemma max_norm_witness:\n  fixes f :: \"'a :: ordered_ring_abs poly\"\n  shows \"\\<exists> i. \\<parallel>f\\<parallel>\\<^sub>\\<infinity> = \\<bar>coeff f i\\<bar>\"\n  by (induct f, auto simp add: max_def intro: exI[of _ \"Suc _\"] exI[of _ 0])\n\nlemma max_norm_le_sq_norm:\n  fixes f ::  \"'a :: conjugatable_ring_1_abs_real_line poly\"\nshows \"\\<parallel>f\\<parallel>\\<^sub>\\<infinity>\\<^sup>2 \\<le> \\<parallel>f\\<parallel>\\<^sup>2\" \nproof -\n  from max_norm_witness[of f] obtain i where id: \"\\<parallel>f\\<parallel>\\<^sub>\\<infinity> = \\<bar>coeff f i\\<bar>\" by auto\n  show ?thesis unfolding id using coeff_le_sq_norm[of f i] by auto\nqed\n\n(*TODO MOVE*)\nlemma (in conjugatable_ring) conjugate_minus: \"conjugate (x - y) = conjugate x - conjugate y\"\n  by (unfold diff_conv_add_uminus conjugate_dist_add conjugate_neg, rule)\n\nlemma conjugate_1[simp]: \"(conjugate 1 :: 'a :: {conjugatable_ring, ring_1}) = 1\"\nproof-\n  have \"conjugate 1 * 1 = (conjugate 1 :: 'a)\" by simp\n  also have \"conjugate \\<dots> = 1\" by simp\n  finally show ?thesis by (unfold conjugate_dist_mul, simp)\nqed\n\nlemma conjugate_of_int [simp]:\n  \"(conjugate (of_int x) :: 'a :: {conjugatable_ring,ring_1}) = of_int x\"\nproof (induct x)\n  case (nonneg n)\n  then show ?case by (induct n, auto simp: conjugate_dist_add)\nnext\n  case (neg n)\n  then show ?case apply (induct n, auto simp: conjugate_minus conjugate_neg)\n    by (metis conjugate_1 conjugate_dist_add one_add_one)\nqed\n\n\nlemma sq_norm_of_int: \"\\<parallel>map_vec of_int v :: 'a :: {conjugatable_ring,ring_1} vec\\<parallel>\\<^sup>2 = of_int \\<parallel>v\\<parallel>\\<^sup>2\" \n  unfolding sq_norm_vec_as_cscalar_prod scalar_prod_def\n  unfolding hom_distribs\n  by (rule sum.cong, auto)\n\ndefinition \"norm1 p = sum_list (map abs (coeffs p))\"\n\nlemma norm1_ge_0: \"norm1 (f :: 'a :: {abs,ordered_semiring_0,ordered_ab_group_add_abs}poly) \\<ge> 0\" \n  unfolding norm1_def by (rule sum_list_nonneg, auto)\n\nlemma norm2_norm1_main_equality: fixes f :: \"nat \\<Rightarrow> 'a :: linordered_idom\" \n  shows \"(\\<Sum>i = 0..<n. \\<bar>f i\\<bar>)\\<^sup>2 = (\\<Sum>i = 0..<n. f i * f i)\n      + (\\<Sum>i = 0..<n. \\<Sum>j = 0..<n. if i = j then 0 else \\<bar>f i\\<bar> * \\<bar>f j\\<bar>)\"  \nproof (induct n)\n  case (Suc n)\n  have id: \"{0 ..< Suc n} = insert n {0 ..< n}\" by auto\n  have id: \"sum f {0 ..< Suc n} = f n + sum f {0 ..< n}\" for f :: \"nat \\<Rightarrow> 'a\" \n    unfolding id by (rule sum.insert, auto)\n  show ?case unfolding id power2_sum unfolding Suc\n    by (auto simp: power2_eq_square sum_distrib_left sum.distrib ac_simps)\nqed auto\n\nlemma norm2_norm1_main_inequality: fixes f :: \"nat \\<Rightarrow> 'a :: linordered_idom\" \n  shows \"(\\<Sum>i = 0..<n. f i * f i) \\<le> (\\<Sum>i = 0..<n. \\<bar>f i\\<bar>)\\<^sup>2\"  \n  unfolding norm2_norm1_main_equality \n  by (auto intro!: sum_nonneg)  \n\nlemma norm2_le_norm1_int: \"\\<parallel>f :: int poly\\<parallel>\\<^sup>2 \\<le> (norm1 f)^2\" \nproof -\n  define F where \"F = (!) (coeffs f)\" \n  define n where \"n = length (coeffs f)\" \n  have 1: \"\\<parallel>f\\<parallel>\\<^sup>2 = (\\<Sum>i = 0..<n. F i * F i)\" \n    unfolding norm1_def sq_norm_poly_def sum_list_sum_nth F_def n_def\n    by (subst sum.cong, auto simp: power2_eq_square)\n  have 2: \"norm1 f = (\\<Sum>i = 0..<n. \\<bar>F i\\<bar>)\" \n    unfolding norm1_def sq_norm_poly_def sum_list_sum_nth F_def n_def\n    by (subst sum.cong, auto)\n  show ?thesis unfolding 1 2 by (rule norm2_norm1_main_inequality)\nqed\n\nlemma sq_norm_smult_vec: \"sq_norm ((c :: 'a :: {conjugatable_ring,comm_semiring_0}) \\<cdot>\\<^sub>v v) = (c * conjugate c) * sq_norm v\" \n  unfolding sq_norm_vec_as_cscalar_prod \n  by (subst scalar_prod_smult_left, force, unfold conjugate_smult_vec, \n    subst scalar_prod_smult_right, force, simp add: ac_simps)\n\nlemma vec_le_sq_norm:\n  fixes v :: \"'a :: conjugatable_ring_1_abs_real_line vec\"\n  assumes \"v \\<in> carrier_vec n\" \"i < n\"\n  shows \"\\<bar>v $ i\\<bar>\\<^sup>2 \\<le> \\<parallel>v\\<parallel>\\<^sup>2\"\nusing assms proof (induction v arbitrary: i)\n  case (Suc n a v i)\n  note IH = Suc\n  show ?case \n  proof (cases i)\n    case (Suc ii)\n    then show ?thesis\n      using IH IH(2)[of ii] le_add_same_cancel2 order_trans by fastforce\n  qed auto\nqed auto\n\nclass trivial_conjugatable =\n  conjugate +\n  assumes conjugate_id [simp]: \"conjugate x = x\"\n\nclass trivial_conjugatable_ordered_field = \n  conjugatable_ordered_field + trivial_conjugatable\n\nclass trivial_conjugatable_linordered_field = \n  trivial_conjugatable_ordered_field + linordered_field\nbegin\nsubclass conjugatable_ring_1_abs_real_line\n  by (standard) (auto simp add: semiring_normalization_rules)\nend\n\ninstance rat :: trivial_conjugatable_linordered_field \n  by (standard, auto)\n\ninstance real :: trivial_conjugatable_linordered_field \n  by (standard, auto)\n\nlemma scalar_prod_ge_0: \"(x :: 'a :: linordered_idom vec) \\<bullet> x \\<ge> 0\" \n  unfolding scalar_prod_def\n  by (rule sum_nonneg, auto)\n\nlemma cscalar_prod_is_scalar_prod[simp]: \"(x :: 'a :: trivial_conjugatable_ordered_field vec) \\<bullet>c y = x \\<bullet> y\"\n  unfolding conjugate_id\n  by (rule arg_cong[of _ _ \"scalar_prod x\"], auto)\n\n\nlemma scalar_prod_Cauchy:\n  fixes u v::\"'a :: {trivial_conjugatable_linordered_field} Matrix.vec\"\n  assumes \"u \\<in> carrier_vec n\" \"v \\<in> carrier_vec n\"\n  shows \"(u \\<bullet> v)\\<^sup>2 \\<le> \\<parallel>u\\<parallel>\\<^sup>2 * \\<parallel>v\\<parallel>\\<^sup>2 \"\nproof -\n  { assume v_0: \"v \\<noteq> 0\\<^sub>v n\"\n    have \"0 \\<le> (u - r \\<cdot>\\<^sub>v v) \\<bullet> (u - r \\<cdot>\\<^sub>v v)\" for r\n      by (simp add: scalar_prod_ge_0)\n    also have \"(u - r \\<cdot>\\<^sub>v v) \\<bullet> (u - r \\<cdot>\\<^sub>v v) = u \\<bullet> u - r * (u \\<bullet> v) - r * (u \\<bullet> v) + r * r * (v \\<bullet> v)\" for r::'a\n    proof -\n      have \"(u - r \\<cdot>\\<^sub>v v) \\<bullet> (u - r \\<cdot>\\<^sub>v v) = (u - r \\<cdot>\\<^sub>v v) \\<bullet> u - (u - r \\<cdot>\\<^sub>v v) \\<bullet> (r \\<cdot>\\<^sub>v v)\"\n        using assms by (subst scalar_prod_minus_distrib) auto\n      also have \"\\<dots> = u \\<bullet> u - (r \\<cdot>\\<^sub>v v) \\<bullet> u - r * ((u - r \\<cdot>\\<^sub>v v) \\<bullet> v)\"\n        using assms by (subst minus_scalar_prod_distrib) auto\n      also have \"\\<dots> = u \\<bullet> u - r * (v \\<bullet> u) - r * (u \\<bullet> v - r * (v \\<bullet> v))\"\n        using assms by (subst minus_scalar_prod_distrib) auto\n      also have \"\\<dots> = u \\<bullet> u - r * (u \\<bullet> v) - r * (u \\<bullet> v) + r * r * (v \\<bullet> v)\"\n        using assms comm_scalar_prod by (auto simp add: field_simps)\n      finally show ?thesis\n        by simp\n    qed\n    also have \"u \\<bullet> u - r * (u \\<bullet> v) - r * (u \\<bullet> v) + r * r * (v \\<bullet> v) = sq_norm u - (u \\<bullet> v)\\<^sup>2 / sq_norm v\"\n      if \"r = (u \\<bullet> v) / (v \\<bullet> v)\" for r\n      unfolding that by (auto simp add: sq_norm_vec_as_cscalar_prod power2_eq_square)\n    finally have \"0 \\<le> \\<parallel>u\\<parallel>\\<^sup>2 - (u \\<bullet> v)\\<^sup>2 / \\<parallel>v\\<parallel>\\<^sup>2\"\n      by auto\n    then have \"(u \\<bullet> v)\\<^sup>2 / \\<parallel>v\\<parallel>\\<^sup>2 \\<le> \\<parallel>u\\<parallel>\\<^sup>2\"\n      by auto\n    then have \"(u \\<bullet> v)\\<^sup>2 \\<le> \\<parallel>u\\<parallel>\\<^sup>2 * \\<parallel>v\\<parallel>\\<^sup>2\"\n      using pos_divide_le_eq[of \"\\<parallel>v\\<parallel>\\<^sup>2\"] v_0 assms by (auto)\n  }\n  then show ?thesis\n    by (fastforce simp add: assms)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/LLL_Basis_Reduction/Norms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.7882811105061918}}
{"text": "theory BExp imports AExp begin\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ntext_raw{*\\snip{BExpbvaldef}{1}{2}{% *}\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\ntext_raw{*}%endsnip*}\n\nvalue \"bval (Less (V ''x'') (Plus (N 3) (V ''y'')))\n            <''x'' := 3, ''y'' := 1>\"\n\n\nsubsection \"Constant Folding\"\n\ntext{* Optimizing constructors: *}\n\ntext_raw{*\\snip{BExplessdef}{0}{2}{% *}\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\" |\n\"less a\\<^sub>1 a\\<^sub>2 = Less a\\<^sub>1 a\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\n\n\ntext_raw{*\\snip{BExpanddef}{2}{2}{% *}\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply simp_all\ndone\n\ntext_raw{*\\snip{BExpnotdef}{2}{2}{% *}\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\ntext_raw{*}%endsnip*}\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction b rule: not.induct)\napply simp_all\ndone\n\ntext{* Now the overall optimizer: *}\n\ntext_raw{*\\snip{BExpbsimpdef}{0}{2}{% *}\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\nvalue \"bsimp (And (Less (N 0) (N 1)) b)\"\n\nvalue \"bsimp (And (Less (N 1) (N 0)) (Bc True))\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply simp_all\ndone\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/IMP/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467158, "lm_q2_score": 0.8499711699569786, "lm_q1q2_score": 0.7882320653759985}}
{"text": "header {* Proof of Sturm's Theorem *}\n(* Author: Manuel Eberl <eberlm@in.tum.de> *)\ntheory Sturm_Theorem\nimports \"~~/src/HOL/Library/Poly_Deriv\" \"Lib/Sturm_Library\"\nbegin\n\nsubsection {* Sign changes of polynomial sequences *}\n\ntext {*\n  For a given sequence of polynomials, this function computes the number of sign changes \n  of the sequence of polynomials evaluated at a given position $x$. A sign change is a \n  change from a negative value to a positive one or vice versa; zeros in the sequence are \n  ignored.\n*}\n\ndefinition sign_changes where\n\"sign_changes ps (x::real) = \n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map (\\<lambda>p. sgn (poly p x)) ps))) - 1\"\n\ntext {*\n  The number of sign changes of a sequence distributes over a list in the sense that \n  the number of sign changes of a sequence $p_1, \\ldots, p_i, \\ldots, p_n$ at $x$ is the same \n  as the sum of the sign changes of the sequence $p_1, \\ldots, p_i$ and $p_i, \\ldots, p_n$ \n  as long as $p_i(x)\\neq 0$.\n*}\n\nlemma sign_changes_distrib:\n  \"poly p x \\<noteq> 0 \\<Longrightarrow> \n      sign_changes (ps\\<^sub>1 @ [p] @ ps\\<^sub>2) x = \n      sign_changes (ps\\<^sub>1 @ [p]) x + sign_changes ([p] @ ps\\<^sub>2) x\"\n  by (simp add: sign_changes_def sgn_zero_iff, subst remdups_adj_append, simp)\n\ntext {*\n  The following two congruences state that the number of sign changes is the same \n  if all the involved signs are the same.\n*}\n\nlemma sign_changes_cong:\n  assumes \"length ps = length ps'\"\n  assumes \"\\<forall>i < length ps. sgn (poly (ps!i) x) = sgn (poly (ps'!i) y)\"\n  shows \"sign_changes ps x = sign_changes ps' y\"\nproof-\n from assms(2) have A: \"map (\\<lambda>p. sgn (poly p x)) ps = map (\\<lambda>p. sgn (poly p y)) ps'\"\n  proof (induction rule: list_induct2[OF assms(1)], simp)\n    case (goal1 p ps p' ps')\n      from goal1(3)\n      have \"\\<forall>i<length ps. sgn (poly (ps ! i) x) = \n                         sgn (poly (ps' ! i) y)\" by auto\n      from goal1(2)[OF this] goal1(3) show ?case by auto\n  qed\n  show ?thesis unfolding sign_changes_def by (simp add: A)\nqed\n\nlemma sign_changes_cong':\n  assumes \"\\<forall>p \\<in> set ps. sgn (poly p x) = sgn (poly p y)\"\n  shows \"sign_changes ps x = sign_changes ps y\"\nusing assms by (intro sign_changes_cong, simp_all)\n\ntext {*\n  For a sequence of polynomials of length 3, if the first and the third \n  polynomial have opposite and nonzero sign at some $x$, the number of \n  sign changes is always 1, irrespective of the sign of the second \n  polynomial.  \n*}\n\nlemma sign_changes_sturm_triple:\n  assumes \"poly p x \\<noteq> 0\" and \"sgn (poly r x) = - sgn (poly p x)\"\n  shows \"sign_changes [p,q,r] x = 1\"\nunfolding sign_changes_def by (insert assms, auto simp: sgn_real_def)\n\ntext {*\n  Finally, we define two additional functions that count the sign changes ``at infinity''.\n*}\n\ndefinition sign_changes_inf where\n\"sign_changes_inf ps = \n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map poly_inf ps))) - 1\"\n\ndefinition sign_changes_neg_inf where\n\"sign_changes_neg_inf ps = \n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map poly_neg_inf ps))) - 1\"\n\n\n\nsubsection {* Definition of Sturm sequences locale *}\n\ntext {*\n  We first define the notion of a ``Quasi-Sturm sequence'', which is a weakening of \n  a Sturm sequence that captures the properties that are fulfilled by a nonempty \n  suffix of a Sturm sequence:\n  \\begin{itemize}\n    \\item The sequence is nonempty.\n    \\item The last polynomial does not change its sign.\n    \\item If the middle one of three adjacent polynomials has a root at $x$, the other \n          two have opposite and nonzero signs at $x$.\n  \\end{itemize}\n*}\n\nlocale quasi_sturm_seq =\n  fixes ps :: \"(real poly) list\"\n  assumes last_ps_sgn_const[simp]: \n      \"\\<And>x y. sgn (poly (last ps) x) = sgn (poly (last ps) y)\"\n  assumes ps_not_Nil[simp]: \"ps \\<noteq> []\"\n  assumes signs: \"\\<And>i x. \\<lbrakk>i < length ps - 2; poly (ps ! (i+1)) x = 0\\<rbrakk>\n                     \\<Longrightarrow> (poly (ps ! (i+2)) x) * (poly (ps ! i) x) < 0\"\n\n\ntext {*\n  Now we define a Sturm sequence $p_1,\\ldots,p_n$ of a polynomial $p$ in the following way:\n  \\begin{itemize}\n    \\item The sequence contains at least two elements.\n    \\item $p$ is the first polynomial, i.\\,e. $p_1 = p$.\n    \\item At any root $x$ of $p$, $p_2$ and $p$ have opposite sign left of $x$ and \n          the same sign right of $x$ in some neighbourhood around $x$.\n    \\item The first two polynomials in the sequence have no common roots.\n    \\item If the middle one of three adjacent polynomials has a root at $x$, the other \n          two have opposite and nonzero signs at $x$.\n  \\end{itemize}\n*}\n\nlocale sturm_seq = quasi_sturm_seq + \n  fixes p :: \"real poly\"\n  assumes hd_ps_p[simp]: \"hd ps = p\"\n  assumes length_ps_ge_2[simp]: \"length ps \\<ge> 2\"\n  assumes deriv: \"\\<And>x\\<^sub>0. poly p x\\<^sub>0 = 0 \\<Longrightarrow> \n      eventually (\\<lambda>x. sgn (poly (p * ps!1) x) = \n                      (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\n  assumes p_squarefree: \"\\<And>x. \\<not>(poly p x = 0 \\<and> poly (ps!1) x = 0)\"\nbegin\n\n  text {*\n    Any Sturm sequence is obviously a Quasi-Sturm sequence.\n  *}\n  lemma quasi_sturm_seq: \"quasi_sturm_seq ps\" ..\n\n(*<*)\n  lemma ps_first_two:\n    obtains q ps' where \"ps = p # q # ps'\"\n    using hd_ps_p length_ps_ge_2\n      by (cases ps, simp, clarsimp, rename_tac ps', case_tac ps', auto)\n\n  lemma ps_first: \"ps ! 0 = p\" by (rule ps_first_two, simp)\n\n  \n\n(*<*)\nlemma [simp]: \"\\<not>quasi_sturm_seq []\" by (simp add: quasi_sturm_seq_def)\n(*>*)\n\ntext {*\n  Any suffix of a Quasi-Sturm sequence is again a Quasi-Sturm sequence.\n*}\n\nlemma quasi_sturm_seq_Cons:\n  assumes \"quasi_sturm_seq (p#ps)\" and \"ps \\<noteq> []\"\n  shows \"quasi_sturm_seq ps\"\nproof (unfold_locales)\n  show \"ps \\<noteq> []\" by fact\nnext\n  from assms(1) interpret quasi_sturm_seq \"p#ps\" .\n  fix x y\n  from last_ps_sgn_const and `ps \\<noteq> []` \n      show \"sgn (poly (last ps) x) = sgn (poly (last ps) y)\" by simp_all\nnext\n  from assms(1) interpret quasi_sturm_seq \"p#ps\" .\n  fix i x\n  assume \"i < length ps - 2\" and \"poly (ps ! (i+1)) x = 0\"\n  with signs[of \"i+1\"] \n      show \"poly (ps ! (i+2)) x * poly (ps ! i) x < 0\" by simp\nqed\n\n\n\nsubsection {* Auxiliary lemmas about roots and sign changes *}\n\nlemma sturm_adjacent_root_aux:\n  assumes \"i < length (ps :: real poly list) - 1\"\n  assumes \"poly (ps ! i) x = 0\" and \"poly (ps ! (i + 1)) x = 0\"\n  assumes \"\\<And>i x. \\<lbrakk>i < length ps - 2; poly (ps ! (i+1)) x = 0\\<rbrakk>\n                   \\<Longrightarrow> sgn (poly (ps ! (i+2)) x) = - sgn (poly (ps ! i) x)\"\n  shows \"\\<forall>j\\<le>i+1. poly (ps ! j) x = 0\"\nusing assms\nproof (induction i)\n  case 0 thus ?case by (clarsimp, rename_tac j, case_tac j, simp_all)\nnext\n  case (Suc i)\n    from Suc.prems(1,2) \n        have \"sgn (poly (ps ! (i + 2)) x) = - sgn (poly (ps ! i) x)\"\n        by (intro assms(4)) simp_all\n    with Suc.prems(3) have \"poly (ps ! i) x = 0\" by (simp add: sgn_zero_iff)\n    with Suc.prems have \"\\<forall>j\\<le>i+1. poly (ps ! j) x = 0\"\n        by (intro Suc.IH, simp_all)\n    with Suc.prems(3) show ?case\n      by (clarsimp, rename_tac j, case_tac \"j = Suc (Suc i)\", simp_all)\nqed\n\ntext {* \n  This function splits the sign list of a Sturm sequence at a \n  position @{term x} that is not a root of @{term p} into a \n  list of sublists such that the number of sign changes within \n  every sublist is constant in the neighbourhood of @{term x},\n  thus proving that the total number is also constant.\n*}\nfun split_sign_changes where\n\"split_sign_changes [p] (x :: real) = [[p]]\" |\n\"split_sign_changes [p,q] x = [[p,q]]\" |\n\"split_sign_changes (p#q#r#ps) x =\n    (if poly p x \\<noteq> 0 \\<and> poly q x = 0 then \n       [p,q,r] # split_sign_changes (r#ps) x\n     else\n       [p,q] # split_sign_changes (q#r#ps) x)\"\n\nlemma (in quasi_sturm_seq) split_sign_changes_subset[dest]:\n  \"ps' \\<in> set (split_sign_changes ps x) \\<Longrightarrow> set ps' \\<subseteq> set ps\"\napply (insert ps_not_Nil)\napply (induction ps x rule: split_sign_changes.induct)\napply (simp, simp, rename_tac p q r ps x, \n       case_tac \"poly p x \\<noteq> 0 \\<and> poly q x = 0\", auto)\ndone\n\ntext {* \n  A custom induction rule for @{term split_sign_changes} that \n  uses the fact that all the intermediate parameters in calls \n  of @{term split_sign_changes} are quasi-Sturm sequences.\n*}\nlemma (in quasi_sturm_seq) split_sign_changes_induct:\n  \"\\<lbrakk>\\<And>p x. P [p] x; \\<And>p q x. quasi_sturm_seq [p,q] \\<Longrightarrow> P [p,q] x;\n    \\<And>p q r ps x. quasi_sturm_seq (p#q#r#ps) \\<Longrightarrow>\n       \\<lbrakk>poly p x \\<noteq> 0 \\<Longrightarrow> poly q x = 0 \\<Longrightarrow> P (r#ps) x; \n        poly q x \\<noteq> 0 \\<Longrightarrow> P (q#r#ps) x;\n        poly p x = 0 \\<Longrightarrow> P (q#r#ps) x\\<rbrakk> \n           \\<Longrightarrow> P (p#q#r#ps) x\\<rbrakk> \\<Longrightarrow> P ps x\"\nproof-\n  case goal1\n  have \"quasi_sturm_seq ps\" ..\n  with goal1 show ?thesis\n  proof (induction ps x rule: split_sign_changes.induct)\n    case (goal3 p q r ps x)\n      show ?case\n      proof (rule goal3(5)[OF goal3(6)])\n        assume A: \"poly p x \\<noteq> 0\" \"poly q x = 0\"\n        from goal3(6) have \"quasi_sturm_seq (r#ps)\" \n            by (force dest: quasi_sturm_seq_Cons)\n        with goal3 A show \"P (r # ps) x\" by blast\n      next\n        assume A: \"poly q x \\<noteq> 0\"\n        from goal3(6) have \"quasi_sturm_seq (q#r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with goal3 A show \"P (q # r # ps) x\" by blast\n      next\n        assume A: \"poly p x = 0\"\n        from goal3(6) have \"quasi_sturm_seq (q#r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with goal3 A show \"P (q # r # ps) x\" by blast\n      qed\n  qed simp_all  \nqed\n\ntext {* \n  The total number of sign changes in the split list is the same\n  as the number of sign changes in the original list.\n*}\nlemma (in quasi_sturm_seq) split_sign_changes_correct:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  defines \"sign_changes' \\<equiv> \\<lambda>ps x. \n               \\<Sum>ps'\\<leftarrow>split_sign_changes ps x. sign_changes ps' x\"\n  shows \"sign_changes' ps x\\<^sub>0 = sign_changes ps x\\<^sub>0\"\nusing assms(1)\nproof (induction x\\<^sub>0 rule: split_sign_changes_induct)\ncase (goal3 p q r ps x\\<^sub>0)\n  hence \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n  note IH = goal3(2,3,4)\n  show ?case\n  proof (cases \"poly q x\\<^sub>0 = 0\")\n    case True\n      from goal3 interpret quasi_sturm_seq \"p#q#r#ps\" by simp\n      from signs[of 0] and True have \n           sgn_r_x0: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n      with goal3 have \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n      from sign_changes_distrib[OF this, of \"[p,q]\" ps]\n        have \"sign_changes (p#q#r#ps) x\\<^sub>0 =\n                  sign_changes ([p, q, r]) x\\<^sub>0 + sign_changes (r # ps) x\\<^sub>0\" by simp\n      also have \"sign_changes (r#ps) x\\<^sub>0 = sign_changes' (r#ps) x\\<^sub>0\"\n          using `poly q x\\<^sub>0 = 0` `poly p x\\<^sub>0 \\<noteq> 0` goal3(5)`poly r x\\<^sub>0 \\<noteq> 0`\n          by (intro IH(1)[symmetric], simp_all)\n      finally show ?thesis unfolding sign_changes'_def \n          using True `poly p x\\<^sub>0 \\<noteq> 0` by simp\n  next\n    case False\n      from sign_changes_distrib[OF this, of \"[p]\" \"r#ps\"]\n          have \"sign_changes (p#q#r#ps) x\\<^sub>0 = \n                  sign_changes ([p,q]) x\\<^sub>0 + sign_changes (q#r#ps) x\\<^sub>0\" by simp\n      also have \"sign_changes (q#r#ps) x\\<^sub>0 = sign_changes' (q#r#ps) x\\<^sub>0\"\n          using `poly q x\\<^sub>0 \\<noteq> 0` `poly p x\\<^sub>0 \\<noteq> 0` goal3(5)\n          by (intro IH(2)[symmetric], simp_all)\n      finally show ?thesis unfolding sign_changes'_def \n          using False by simp\n    qed\nqed (simp_all add: sign_changes_def sign_changes'_def)\n\n\ntext {* \n  We now prove that if $p(x)\\neq 0$, the number of sign changes of a Sturm sequence of $p$ \n  at $x$ is constant in a neighbourhood of $x$.\n*}      \n\nlemma (in quasi_sturm_seq) split_sign_changes_correct_nbh:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  defines \"sign_changes' \\<equiv> \\<lambda>x\\<^sub>0 ps x. \n               \\<Sum>ps'\\<leftarrow>split_sign_changes ps x\\<^sub>0. sign_changes ps' x\"\n  shows \"eventually (\\<lambda>x. sign_changes' x\\<^sub>0 ps x = sign_changes ps x) (at x\\<^sub>0)\"\nproof (rule eventually_mono)\n  case goal1\n  let ?ps_nz = \"{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}\"\n  show \"eventually (\\<lambda>x. \\<forall>p\\<in>?ps_nz. sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\"\n      by (rule eventually_Ball_finite, auto intro: poly_neighbourhood_same_sign)\n\n  show \"\\<forall>x. (\\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)) \\<longrightarrow>\n        sign_changes' x\\<^sub>0 ps x = sign_changes ps x\"\n  proof (clarify)\n    fix x assume nbh: \"\\<forall>p\\<in>?ps_nz. sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n    thus \"sign_changes' x\\<^sub>0 ps x = sign_changes ps x\" using assms(1)\n    proof (induction x\\<^sub>0 rule: split_sign_changes_induct)\n    case (goal3 p q r ps x\\<^sub>0)\n      hence \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n      note IH = goal3(2,3,4)\n      show ?case\n      proof (cases \"poly q x\\<^sub>0 = 0\")\n        case True\n          from goal3 interpret quasi_sturm_seq \"p#q#r#ps\" by simp\n          from signs[of 0] and True have \n               sgn_r_x0: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n          with goal3 have \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n          with nbh goal3(5) have \"poly r x \\<noteq> 0\" by (auto simp: sgn_zero_iff)\n          from sign_changes_distrib[OF this, of \"[p,q]\" ps]\n            have \"sign_changes (p#q#r#ps) x =\n                      sign_changes ([p, q, r]) x + sign_changes (r # ps) x\" by simp\n          also have \"sign_changes (r#ps) x = sign_changes' x\\<^sub>0 (r#ps) x\"\n              using `poly q x\\<^sub>0 = 0` nbh `poly p x\\<^sub>0 \\<noteq> 0` goal3(5)`poly r x\\<^sub>0 \\<noteq> 0`\n              by (intro IH(1)[symmetric], simp_all)\n          finally show ?thesis unfolding sign_changes'_def \n              using True `poly p x\\<^sub>0 \\<noteq> 0`by simp\n      next\n        case False\n          with nbh goal3(5) have \"poly q x \\<noteq> 0\" by (auto simp: sgn_zero_iff)\n          from sign_changes_distrib[OF this, of \"[p]\" \"r#ps\"]\n              have \"sign_changes (p#q#r#ps) x = \n                      sign_changes ([p,q]) x + sign_changes (q#r#ps) x\" by simp\n          also have \"sign_changes (q#r#ps) x = sign_changes' x\\<^sub>0 (q#r#ps) x\"\n              using `poly q x\\<^sub>0 \\<noteq> 0` nbh `poly p x\\<^sub>0 \\<noteq> 0` goal3(5)\n              by (intro IH(2)[symmetric], simp_all)\n          finally show ?thesis unfolding sign_changes'_def \n              using False by simp\n        qed\n    qed (simp_all add: sign_changes_def sign_changes'_def)\n  qed\nqed\n\n\n\nlemma (in quasi_sturm_seq) hd_nonzero_imp_sign_changes_const_aux:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\" and \"ps' \\<in> set (split_sign_changes ps x\\<^sub>0)\"\n  shows \"eventually (\\<lambda>x. sign_changes ps' x = sign_changes ps' x\\<^sub>0) (at x\\<^sub>0)\"\nusing assms\nproof (induction x\\<^sub>0 rule: split_sign_changes_induct)\n  case (goal1 p x)\n    thus ?case by (simp add: sign_changes_def)\nnext\n  case (goal2 p q x\\<^sub>0)\n    hence [simp]: \"ps' = [p,q]\" by simp\n    from goal2 have \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n    from goal2(1) interpret quasi_sturm_seq \"[p,q]\" .\n    from poly_neighbourhood_same_sign[OF `poly p x\\<^sub>0 \\<noteq> 0`]\n        have \"eventually (\\<lambda>x. sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\" .\n    moreover from last_ps_sgn_const\n        have sgn_q: \"\\<And>x. sgn (poly q x) = sgn (poly q x\\<^sub>0)\" by simp\n    ultimately have A:  \"eventually (\\<lambda>x. \\<forall>p\\<in>set[p,q]. sgn (poly p x) = \n                           sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\" by simp\n    thus ?case by (force intro: eventually_mono[OF _ A] \n                                sign_changes_cong')\nnext\n  case (goal3 p q r ps'' x\\<^sub>0)\n    hence p_not_0: \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n    note sturm = goal3(1)\n    note IH = goal3(2,3)\n    note ps''_props = goal3(6)\n    show ?case\n    proof (cases \"poly q x\\<^sub>0 = 0\")\n      case True\n        note q_0 = this\n        from sturm interpret quasi_sturm_seq \"p#q#r#ps''\" .\n        from signs[of 0] and q_0 \n            have signs': \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n        with p_not_0 have r_not_0: \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n        show ?thesis\n        proof (cases \"ps' \\<in> set (split_sign_changes (r # ps'') x\\<^sub>0)\")\n          case True\n            show ?thesis by (rule IH(1), fact, fact, simp add: r_not_0, fact)\n        next\n          case False\n            with ps''_props p_not_0 q_0 have ps'_props: \"ps' = [p,q,r]\" by simp\n            from signs[of 0] and q_0 \n                have sgn_r: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n            from p_not_0 sgn_r\n              have A: \"eventually (\\<lambda>x. sgn (poly p x) = sgn (poly p x\\<^sub>0) \\<and>\n                                     sgn (poly r x) = sgn (poly r x\\<^sub>0)) (at x\\<^sub>0)\"\n                  by (intro eventually_conj poly_neighbourhood_same_sign, \n                      simp_all add: r_not_0)\n            show ?thesis\n            proof (rule eventually_mono[OF _ A], clarify,\n                   subst ps'_props, subst sign_changes_sturm_triple)\n              fix x assume A: \"sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n                       and B: \"sgn (poly r x) = sgn (poly r x\\<^sub>0)\"\n              have prod_neg: \"\\<And>a (b::real). \\<lbrakk>a>0; b>0; a*b<0\\<rbrakk> \\<Longrightarrow> False\"\n                             \"\\<And>a (b::real). \\<lbrakk>a<0; b<0; a*b<0\\<rbrakk> \\<Longrightarrow> False\"\n                  by (drule mult_pos_pos, simp, simp, \n                      drule mult_neg_neg, simp, simp)\n              from A and `poly p x\\<^sub>0 \\<noteq> 0` show \"poly p x \\<noteq> 0\" \n                  by (force simp: sgn_zero_iff)\n\n              with sgn_r p_not_0 r_not_0 A B\n                  have \"poly r x * poly p x < 0\" \"poly r x \\<noteq> 0\"\n                  by (metis sgn_less sgn_times, metis sgn_0_0)\n              with sgn_r show sgn_r': \"sgn (poly r x) = - sgn (poly p x)\"\n                  apply (simp add: sgn_real_def not_le not_less \n                             split: split_if_asm, intro conjI impI)\n                  using prod_neg[of \"poly r x\" \"poly p x\"] apply force+\n                  done\n\n              show \"1 = sign_changes ps' x\\<^sub>0\"\n                  by (subst ps'_props, subst sign_changes_sturm_triple, \n                      fact, metis A B sgn_r', simp)\n            qed\n        qed\n    next\n      case False\n        note q_not_0 = this\n        show ?thesis\n        proof (cases \"ps' \\<in> set (split_sign_changes (q # r # ps'') x\\<^sub>0)\")\n          case True\n            show ?thesis by (rule IH(2), fact, simp add: q_not_0, fact)\n        next\n          case False\n            with ps''_props and q_not_0 have \"ps' = [p, q]\" by simp\n            hence [simp]: \"\\<forall>p\\<in>set ps'. poly p x\\<^sub>0 \\<noteq> 0\" \n                using q_not_0 p_not_0 by simp\n            show ?thesis\n            proof (rule eventually_mono, clarify)\n              fix x assume \"\\<forall>p\\<in>set ps'. sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n              thus \"sign_changes ps' x = sign_changes ps' x\\<^sub>0\"\n                  by (rule sign_changes_cong')\n            next\n              show \"eventually (\\<lambda>x. \\<forall>p\\<in>set ps'. \n                        sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\"\n                  by (force intro: eventually_Ball_finite \n                                   poly_neighbourhood_same_sign)\n            qed\n    qed\n  qed\nqed\n\n\nlemma (in quasi_sturm_seq) hd_nonzero_imp_sign_changes_const:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  shows \"eventually (\\<lambda>x. sign_changes ps x = sign_changes ps x\\<^sub>0) (at x\\<^sub>0)\"\nproof-\n  let ?pss = \"split_sign_changes ps x\\<^sub>0\"\n  let ?f = \"\\<lambda>pss x. \\<Sum>ps'\\<leftarrow>pss. sign_changes ps' x\"\n  {\n    fix pss assume \"\\<And>ps'. ps'\\<in>set pss \\<Longrightarrow> \n        eventually (\\<lambda>x. sign_changes ps' x = sign_changes ps' x\\<^sub>0) (at x\\<^sub>0)\"\n    hence \"eventually (\\<lambda>x. ?f pss x = ?f pss x\\<^sub>0) (at x\\<^sub>0)\"\n    proof (induction pss)\n      case (Cons ps' pss)\n        have \"\\<forall>x. ?f pss x = ?f pss x\\<^sub>0 \\<and> sign_changes ps' x = sign_changes ps' x\\<^sub>0 \n                      \\<longrightarrow> ?f (ps'#pss) x = ?f (ps'#pss) x\\<^sub>0\" by simp\n        note A = eventually_mono[OF this eventually_conj]\n        show ?case by (rule A, simp_all add: Cons)\n    qed simp\n  }\n  note A = this[of ?pss]\n  have B: \"eventually (\\<lambda>x. ?f ?pss x = ?f ?pss x\\<^sub>0) (at x\\<^sub>0)\"\n      by (rule A, rule hd_nonzero_imp_sign_changes_const_aux[OF assms], simp)\n  note C = split_sign_changes_correct_nbh[OF assms]\n  note D = split_sign_changes_correct[OF assms]\n  note E = eventually_conj[OF B C]\n  show ?thesis by (rule eventually_mono[OF _ E], auto simp: D)\nqed\n\n(*<*)\nhide_fact quasi_sturm_seq.split_sign_changes_correct_nbh\nhide_fact quasi_sturm_seq.hd_nonzero_imp_sign_changes_const_aux\n(*>*)\n\nlemma (in sturm_seq) p_nonzero_imp_sign_changes_const:\n  \"poly p x\\<^sub>0 \\<noteq> 0 \\<Longrightarrow> \n       eventually (\\<lambda>x. sign_changes ps x = sign_changes ps x\\<^sub>0) (at x\\<^sub>0)\"\n  using hd_nonzero_imp_sign_changes_const by simp\n\n\ntext {*\n  If $x$ is a root of $p$ and $p$ is not the zero polynomial, the \n  number of sign changes of a Sturm chain of $p$ decreases by 1 at $x$.\n*}\nlemma (in sturm_seq) p_zero:\n  assumes \"poly p x\\<^sub>0 = 0\" \"p \\<noteq> 0\"\n  shows \"eventually (\\<lambda>x. sign_changes ps x = \n      sign_changes ps x\\<^sub>0 + (if x<x\\<^sub>0 then 1 else 0)) (at x\\<^sub>0)\"\nproof-\n  from ps_first_two obtain q ps' where [simp]: \"ps = p#q#ps'\" .\n  hence \"ps!1 = q\" by simp\n  have \"eventually (\\<lambda>x. x \\<noteq> x\\<^sub>0) (at x\\<^sub>0)\"\n      by (simp add: eventually_at, rule exI[of _ 1], simp)\n  moreover from p_squarefree and assms(1) have \"poly q x\\<^sub>0 \\<noteq> 0\" by simp\n  {\n      have A: \"quasi_sturm_seq ps\" ..\n      with quasi_sturm_seq_Cons[of p \"q#ps'\"]\n          interpret quasi_sturm_seq \"q#ps'\" by simp\n      from `poly q x\\<^sub>0 \\<noteq> 0` have \"eventually (\\<lambda>x. sign_changes (q#ps') x = \n                                     sign_changes (q#ps') x\\<^sub>0) (at x\\<^sub>0)\"\n      using hd_nonzero_imp_sign_changes_const[where x\\<^sub>0=x\\<^sub>0] by simp\n  }   \n  moreover note poly_neighbourhood_without_roots[OF assms(2)] deriv[OF assms(1)]\n  ultimately\n      have A: \"eventually (\\<lambda>x. x \\<noteq> x\\<^sub>0 \\<and> poly p x \\<noteq> 0 \\<and>\n                   sgn (poly (p*ps!1) x) = (if x > x\\<^sub>0 then 1 else -1) \\<and>\n                   sign_changes (q#ps') x = sign_changes (q#ps') x\\<^sub>0) (at x\\<^sub>0)\" \n           by (simp only: `ps!1 = q`, intro eventually_conj)\n  show ?thesis\n  proof (rule eventually_mono[OF _ A], clarify)\n    case (goal1 x)\n    from zero_less_mult_pos have zero_less_mult_pos':\n        \"\\<And>a b. \\<lbrakk>(0::real) < a*b; 0 < b\\<rbrakk> \\<Longrightarrow> 0 < a\"\n        by (subgoal_tac \"a*b = b*a\", auto)\n    from goal1 have \"poly q x \\<noteq> 0\" and q_sgn: \"sgn (poly q x) = \n              (if x < x\\<^sub>0 then -sgn (poly p x) else sgn (poly p x))\"\n        by (auto simp add: sgn_real_def elim: linorder_neqE_linordered_idom\n                 dest: mult_neg_neg zero_less_mult_pos \n                 zero_less_mult_pos' split: split_if_asm)\n     from sign_changes_distrib[OF `poly q x \\<noteq> 0`, of \"[p]\" ps']\n        have \"sign_changes ps x = sign_changes [p,q] x + sign_changes (q#ps') x\"\n            by simp\n    also from q_sgn and `poly p x \\<noteq> 0` \n        have \"sign_changes [p,q] x = (if x<x\\<^sub>0 then 1 else 0)\"\n        by (simp add: sign_changes_def sgn_zero_iff split: split_if_asm)\n    also note goal1(4)\n    also from assms(1) have \"sign_changes (q#ps') x\\<^sub>0 = sign_changes ps x\\<^sub>0\"\n        by (simp add: sign_changes_def)\n    finally show ?case by simp\n  qed\nqed\n    \ntext {*\n  With these two results, we can now show that if $p$ is nonzero, the number \n  of roots in an interval of the form $(a;b]$ is the difference of the sign changes \n  of a Sturm sequence of $p$ at $a$ and $b$.\\\\\n  First, however, we prove the following auxiliary lemma that shows that \n  if a function $f: \\RR\\to\\NN$ is locally constant at any $x\\in(a;b]$, it is constant \n  across the entire interval $(a;b]$:\n*}\n\nlemma count_roots_between_aux:\n  assumes \"a \\<le> b\"\n  assumes \"\\<forall>x::real. a < x \\<and> x \\<le> b \\<longrightarrow> eventually (\\<lambda>\\<xi>. f \\<xi> = (f x::nat)) (at x)\"\n  shows \"\\<forall>x. a < x \\<and> x \\<le> b \\<longrightarrow> f x = f b\"\nproof (clarify)\n  fix x assume \"x > a\" \"x \\<le> b\"\n  with assms have \"\\<forall>x'. x \\<le> x' \\<and> x' \\<le> b \\<longrightarrow> \n                       eventually (\\<lambda>\\<xi>. f \\<xi> = f x') (at x')\" by auto\n  from fun_eq_in_ivl[OF `x \\<le> b` this] show \"f x = f b\" .\nqed\n\ntext {*\n  Now we can prove the actual root-counting theorem:\n*}\n\n\n              show \"sign_changes ps a = sign_changes ps b\"\n              proof (cases \"a = b\")\n                case False\n                  def x \\<equiv> \"min (a+\\<delta>/2) b\"\n                  with False have \"a < x\" \"x < a+\\<delta>\" \"x \\<le> b\"\n                     using `\\<delta> > 0` `a \\<le> b` by simp_all\n                  from \\<delta>_props `a < x` `x < a+\\<delta>` \n                      have \"sign_changes ps a = sign_changes ps x\" by simp\n                  also from A `a < x` `x \\<le> b` have \"... = sign_changes ps b\"\n                      by blast\n                  finally show ?thesis .\n              qed simp\n          qed\n\n      next\n        case True\n          from poly_roots_finite[OF assms(1)]\n            have fin: \"finite {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0}\" \n            by (force intro: finite_subset)\n          from True have \"{x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} \\<noteq> {}\" by blast\n          with fin have card_greater_0:\n              \"card {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} > 0\" by fastforce\n              \n          def x\\<^sub>2 \\<equiv> \"Min {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0}\"\n          from Min_in[OF fin] and True\n              have x\\<^sub>2_props: \"x\\<^sub>2 > a\" \"x\\<^sub>2 \\<le> b\" \"poly p x\\<^sub>2 = 0\" \n              unfolding x\\<^sub>2_def by blast+\n          from Min_le[OF fin] x\\<^sub>2_props \n              have x\\<^sub>2_le: \"\\<And>x'. \\<lbrakk>x' > a; x' \\<le> b; poly p x' = 0\\<rbrakk> \\<Longrightarrow> x\\<^sub>2 \\<le> x'\"\n              unfolding x\\<^sub>2_def by simp\n\n          have left: \"{x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} = {x\\<^sub>2}\"\n              using x\\<^sub>2_props x\\<^sub>2_le by force\n          hence [simp]: \"card {x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} = 1\" by simp\n\n          from p_zero[OF `poly p x\\<^sub>2 = 0` `p \\<noteq> 0`, \n              unfolded eventually_at dist_real_def] guess \\<epsilon> ..\n          hence \\<epsilon>_props: \"\\<epsilon> > 0\"\n              \"\\<forall>x. x \\<noteq> x\\<^sub>2 \\<and> \\<bar>x - x\\<^sub>2\\<bar> < \\<epsilon> \\<longrightarrow> \n                   sign_changes ps x = sign_changes ps x\\<^sub>2 + \n                       (if x < x\\<^sub>2 then 1 else 0)\" by auto\n          def x\\<^sub>1 \\<equiv> \"max (x\\<^sub>2 - \\<epsilon> / 2) a\"\n          have \"\\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar> < \\<epsilon>\" using `\\<epsilon> > 0` x\\<^sub>2_props by (simp add: x\\<^sub>1_def)\n          hence \"sign_changes ps x\\<^sub>1 = \n              (if x\\<^sub>1 < x\\<^sub>2 then sign_changes ps x\\<^sub>2 + 1 else sign_changes ps x\\<^sub>2)\"\n              using \\<epsilon>_props(2) by (cases \"x\\<^sub>1 = x\\<^sub>2\", auto)\n          hence \"sign_changes ps x\\<^sub>1 - sign_changes ps x\\<^sub>2 = 1\"\n              unfolding x\\<^sub>1_def using x\\<^sub>2_props `\\<epsilon> > 0` by simp\n\n          also have \"x\\<^sub>2 \\<notin> {x. a < x \\<and> x \\<le> x\\<^sub>1 \\<and> poly p x = 0}\"\n              unfolding x\\<^sub>1_def using `\\<epsilon> > 0` by force\n          with left have \"{x. a < x \\<and> x \\<le> x\\<^sub>1 \\<and> poly p x = 0} = {}\" by force\n          with less(1)[of a x\\<^sub>1] have \"sign_changes ps x\\<^sub>1 = sign_changes ps a\"\n              unfolding x\\<^sub>1_def `\\<epsilon> > 0` by (force simp: card_greater_0)\n\n          finally have signs_left: \n              \"sign_changes ps a - int (sign_changes ps x\\<^sub>2) = 1\" by simp\n\n          have \"{x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} = \n                {x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} \\<union>\n                {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0}\" using x\\<^sub>2_props by auto\n          also note left\n          finally have A: \"card {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0} + 1 = \n              card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" using fin by simp\n          hence \"card {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0} < \n                 card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by simp\n          from less(1)[OF this x\\<^sub>2_props(2)] and A\n              have signs_right: \"sign_changes ps x\\<^sub>2 - int (sign_changes ps b) + 1 =\n                  card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by simp\n          \n          from signs_left and signs_right show ?thesis by simp\n        qed\n  qed\n  thus ?thesis by simp\nqed\n\ntext {*\n  By applying this result to a sufficiently large upper bound, we can effectively count \n  the number of roots ``between $a$ and infinity'', i.\\,e. the roots greater than $a$:\n*}\nlemma (in sturm_seq) count_roots_above:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes ps a - sign_changes_inf ps = \n             card {x. x > a \\<and> poly p x = 0}\"\nproof-\n  have \"p \\<in> set ps\" using hd_in_set[OF ps_not_Nil] by simp\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n  let ?u = \"max a u\"\n  {fix x assume \"poly p x = 0\" hence \"x \\<le> ?u\"\n   using lu_props(3)[OF `p \\<in> set ps`, of x] `p \\<noteq> 0`\n       by (cases \"u \\<le> x\", auto simp: sgn_zero_iff)\n  } note [simp] = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p ?u)) ps = map poly_inf ps\" by simp\n  hence \"sign_changes ps a - sign_changes_inf ps =\n             sign_changes ps a - sign_changes ps ?u\"\n      by (simp_all only: sign_changes_def sign_changes_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. a < x \\<and> x \\<le> ?u \\<and> poly p x = 0}\" by simp\n  also have \"{x. a < x \\<and> x \\<le> ?u \\<and> poly p x = 0} = {x. a < x \\<and> poly p x = 0}\"\n      using lu_props by auto\n  finally show ?thesis .\nqed\n\ntext {*\n  The same works analogously for the number of roots below $a$ and the \n  total number of roots.\n*}\n\nlemma (in sturm_seq) count_roots_below:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes_neg_inf ps - sign_changes ps a = \n             card {x. x \\<le> a \\<and> poly p x = 0}\"\nproof-\n  have \"p \\<in> set ps\" using hd_in_set[OF ps_not_Nil] by simp\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n  let ?l = \"min a l\"\n  {fix x assume \"poly p x = 0\" hence \"x > ?l\"\n   using lu_props(4)[OF `p \\<in> set ps`, of x] `p \\<noteq> 0`\n       by (cases \"l < x\", auto simp: sgn_zero_iff)\n  } note [simp] = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p ?l)) ps = map poly_neg_inf ps\" by simp\n  hence \"sign_changes_neg_inf ps - sign_changes ps a =\n             sign_changes ps ?l - sign_changes ps a\"\n      by (simp_all only: sign_changes_def sign_changes_neg_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. ?l < x \\<and> x \\<le> a \\<and> poly p x = 0}\" by simp\n  also have \"{x. ?l < x \\<and> x \\<le> a \\<and> poly p x = 0} = {x. a \\<ge> x \\<and> poly p x = 0}\"\n      using lu_props by auto\n  finally show ?thesis .\nqed\n\nlemma (in sturm_seq) count_roots:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes_neg_inf ps - sign_changes_inf ps = \n             card {x. poly p x = 0}\"\nproof-\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p l)) ps = map poly_neg_inf ps\"\n         \"map (\\<lambda>p. sgn (poly p u)) ps = map poly_inf ps\" by simp_all\n  hence \"sign_changes_neg_inf ps - sign_changes_inf ps =\n             sign_changes ps l - sign_changes ps u\"\n      by (simp_all only: sign_changes_def sign_changes_inf_def \n                         sign_changes_neg_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. l < x \\<and> x \\<le> u \\<and> poly p x = 0}\" by simp\n  also have \"{x. l < x \\<and> x \\<le> u \\<and> poly p x = 0} = {x. poly p x = 0}\"\n      using lu_props assms by simp\n  finally show ?thesis .\nqed\n\n\n\nsubsection {* Constructing Sturm sequences *}\n\nsubsection {* The canonical Sturm sequence *}\n\ntext {*\n  In this subsection, we will present the canonical Sturm sequence construction for\n  a polynomial $p$ without multiple roots that is very similar to the Euclidean \n  algorithm:\n  $$p_i = \\begin{cases}\n    p & \\text{for}\\ i = 1\\\\\n    p' & \\text{for}\\ i = 2\\\\\n    -p_{i-2}\\ \\text{mod}\\ p_{i-1} & \\text{otherwise}\n  \\end{cases}$$\n  We break off the sequence at the first constant polynomial.\n*}\n\n(*<*)\nlemma degree_mod_less': \"degree q \\<noteq> 0 \\<Longrightarrow> degree (p mod q) < degree q\"\n  using assms degree_mod_less by force\n(*>*)\n\nfunction sturm_aux where\n\"sturm_aux (p :: real poly) q = \n    (if degree q = 0 then [p,q] else p # sturm_aux q (-(p mod q)))\"\n  by (pat_completeness, simp_all)\ntermination by (relation \"measure (degree \\<circ> snd)\", \n                simp_all add: o_def degree_mod_less')\n\n(*<*)\ndeclare sturm_aux.simps[simp del]\n(*>*)\n\ndefinition sturm where \"sturm p = sturm_aux p (pderiv p)\"\n\ntext {* Next, we show some simple facts about this construction: *}\n\nlemma sturm_0[simp]: \"sturm 0 = [0,0]\"\n    by (unfold sturm_def, subst sturm_aux.simps, simp)\n\nlemma [simp]: \"sturm_aux p q = [] \\<longleftrightarrow> False\"\n    by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, auto)\n\nlemma sturm_neq_Nil[simp]: \"sturm p \\<noteq> []\" unfolding sturm_def by simp\n\nlemma [simp]: \"hd (sturm p) = p\"\n  unfolding sturm_def by (subst sturm_aux.simps, simp)\n\nlemma [simp]: \"p \\<in> set (sturm p)\" \n  using hd_in_set[OF sturm_neq_Nil] by simp\n\nlemma [simp]: \"length (sturm p) \\<ge> 2\"\nproof-\n  {fix q have \"length (sturm_aux p q) \\<ge> 2\"\n           by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, auto)\n  }\n  thus ?thesis unfolding sturm_def .\nqed\n\nlemma [simp]: \"degree (last (sturm p)) = 0\"\nproof-\n  {fix q have \"degree (last (sturm_aux p q)) = 0\"\n           by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, simp)\n  }\n  thus ?thesis unfolding sturm_def .\nqed\n\nlemma [simp]: \"sturm_aux p q ! 0 = p\"\n    by (subst sturm_aux.simps, simp)\nlemma [simp]: \"sturm_aux p q ! Suc 0 = q\"\n    by (subst sturm_aux.simps, simp)\n\nlemma [simp]: \"sturm p ! 0 = p\" \n    unfolding sturm_def by simp\nlemma [simp]: \"sturm p ! Suc 0 = pderiv p\" \n    unfolding sturm_def by simp\n\n\nlemma sturm_indices:\n  assumes \"i < length (sturm p) - 2\"\n  shows \"sturm p!(i+2) = -(sturm p!i mod sturm p!(i+1))\"\nproof-\n {fix ps q\n  have \"\\<lbrakk>ps = sturm_aux p q; i < length ps - 2\\<rbrakk>\n            \\<Longrightarrow> ps!(i+2) = -(ps!i mod ps!(i+1))\"\n  proof (induction p q arbitrary: ps i rule: sturm_aux.induct)\n    case (goal1 p q)\n      show ?case\n      proof (cases \"i = 0\")\n        case False\n          then obtain i' where [simp]: \"i = Suc i'\" by (cases i, simp_all)\n          hence \"length ps \\<ge> 4\" using goal1 by simp\n          with goal1(2) have deg: \"degree q \\<noteq> 0\" \n              by (subst (asm) sturm_aux.simps, simp split: split_if_asm)\n          with goal1(2) obtain ps' where [simp]: \"ps = p # ps'\" \n              by (subst (asm) sturm_aux.simps, simp)\n          with goal1(2) deg have ps': \"ps' = sturm_aux q (-(p mod q))\"\n              by (subst (asm) sturm_aux.simps, simp)\n          from `length ps \\<ge> 4` and `ps = p # ps'`goal1(3) False\n              have \"i - 1 < length ps' - 2\" by simp\n          from goal1(1)[OF deg ps' this]\n              show ?thesis by simp\n      next\n        case True\n          with goal1(3) have \"length ps \\<ge> 3\" by simp\n          with goal1(2) have \"degree q \\<noteq> 0\"\n              by (subst (asm) sturm_aux.simps, simp split: split_if_asm)\n          with goal1(2) have [simp]: \"sturm_aux p q ! Suc (Suc 0) = -(p mod q)\"\n              by (subst sturm_aux.simps, simp)\n          from True have \"ps!i = p\" \"ps!(i+1) = q\" \"ps!(i+2) = -(p mod q)\" \n              by (simp_all add: goal1(2))\n          thus ?thesis by simp\n      qed\n    qed}\n  from this[OF sturm_def assms] show ?thesis .\nqed\n\ntext {*\n  If the Sturm sequence construction is applied to polynomials $p$ and $q$, \n  the greatest common divisor of $p$ and $q$ a divisor of every element in the \n  sequence. This is obvious from the similarity to Euclid's algorithm for \n  computing the GCD.\n*}\n\nlemma sturm_aux_gcd: \"r \\<in> set (sturm_aux p q) \\<Longrightarrow> gcd p q dvd r\"\nproof (induction p q rule: sturm_aux.induct)\n  case (goal1 p q)\n    show ?case\n    proof (cases \"r = p\")\n      case False\n        with goal1(2) have r: \"r \\<in> set (sturm_aux q (-(p mod q)))\" \n          by (subst (asm) sturm_aux.simps, simp split: split_if_asm,\n              subst sturm_aux.simps, simp)\n        show ?thesis\n        proof (cases \"degree q = 0\")\n          case False\n            hence \"q \\<noteq> 0\" by force\n            from goal1(1)[OF False r] show ?thesis \n                by (subst gcd_poly.simps(2)[OF `q \\<noteq> 0`], simp)\n        next\n          case True\n            with goal1(2) and `r \\<noteq> p` have \"r = q\"\n                by (subst (asm) sturm_aux.simps, simp)\n            thus ?thesis by simp\n        qed\n    qed simp\nqed\n\nlemma sturm_gcd: \"r \\<in> set (sturm p) \\<Longrightarrow> gcd p (pderiv p) dvd r\"\n    unfolding sturm_def by (rule sturm_aux_gcd)\n\ntext {*\n  If two adjacent polynomials in the result of the canonical Sturm chain construction\n  both have a root at some $x$, this $x$ is a root of all polynomials in the sequence.\n*}\n\nlemma sturm_adjacent_root_propagate_left:\n  assumes \"i < length (sturm (p :: real poly)) - 1\"\n  assumes \"poly (sturm p ! i) x = 0\"\n      and \"poly (sturm p ! (i + 1)) x = 0\"\n  shows \"\\<forall>j\\<le>i+1. poly (sturm p ! j) x = 0\"\nusing assms(2)\nproof (intro sturm_adjacent_root_aux[OF assms(1,2,3)])\n  case (goal1 i x)\n    let ?p = \"sturm p ! i\"\n    let ?q = \"sturm p ! (i + 1)\"\n    let ?r = \"sturm p ! (i + 2)\"\n    from sturm_indices[OF goal1(2)] have \"?p = ?p div ?q * ?q - ?r\" \n        by (simp add: mod_div_equality)\n    hence \"poly ?p x = poly (?p div ?q * ?q - ?r) x\" by simp\n    hence \"poly ?p x = -poly ?r x\" using goal1(3) by simp\n    thus ?case by (simp add: sgn_minus)\nqed\n\ntext {*\n  Consequently, if this is the case in the canonical Sturm chain of $p$, \n  $p$ must have multiple roots.\n*}\nlemma sturm_adjacent_root_not_squarefree:\n  assumes \"i < length (sturm (p :: real poly)) - 1\"\n          \"poly (sturm p ! i) x = 0\" \"poly (sturm p ! (i + 1)) x = 0\"\n  shows \"\\<not>rsquarefree p\"\nproof-\n  from sturm_adjacent_root_propagate_left[OF assms]\n      have \"poly p x = 0\" \"poly (pderiv p) x = 0\" by auto\n  thus ?thesis by (auto simp: rsquarefree_roots)\nqed\n\n\ntext {*\n  Since the second element of the sequence is chosen to be the derivative of $p$,\n  $p_1$ and $p_2$ fulfil the property demanded by the definition of a Sturm sequence \n  that they locally have opposite sign left of a root $x$ of $p$ and the same sign \n  to the right of $x$.\n*}\n\nlemma sturm_firsttwo_signs_aux:\n  assumes \"(p :: real poly) \\<noteq> 0\" \"q \\<noteq> 0\"\n  assumes q_pderiv: \n      \"eventually (\\<lambda>x. sgn (poly q x) = sgn (poly (pderiv p) x)) (at x\\<^sub>0)\"\n  assumes p_0: \"poly p (x\\<^sub>0::real) = 0\"\n  shows \"eventually (\\<lambda>x. sgn (poly (p*q) x) = (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\nproof-\n  have A: \"eventually (\\<lambda>x. poly p x \\<noteq> 0 \\<and> poly q x \\<noteq> 0 \\<and>\n               sgn (poly q x) = sgn (poly (pderiv p) x)) (at x\\<^sub>0)\"\n      using `p \\<noteq> 0`  `q \\<noteq> 0`\n      by (intro poly_neighbourhood_same_sign q_pderiv\n                poly_neighbourhood_without_roots eventually_conj)\n  then obtain \\<epsilon> where \\<epsilon>_props: \"\\<epsilon> > 0\" \"\\<forall>x. x \\<noteq> x\\<^sub>0 \\<and> \\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon> \\<longrightarrow> \n      poly p x \\<noteq> 0 \\<and> poly q x \\<noteq> 0 \\<and> sgn (poly (pderiv p) x) = sgn (poly q x)\"\n      by (auto simp: eventually_at dist_real_def)\n  have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> sgn x * sgn x = 1\" \n      by (auto simp: sgn_real_def)\n\n  show ?thesis\n  proof (simp only: eventually_at dist_real_def, rule exI[of _ \\<epsilon>],\n         intro conjI, fact `\\<epsilon> > 0`, clarify)\n    fix x assume \"x \\<noteq> x\\<^sub>0\" \"\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\"\n    with \\<epsilon>_props have [simp]: \"poly p x \\<noteq> 0\" \"poly q x \\<noteq> 0\"\n        \"sgn (poly (pderiv p) x) = sgn (poly q x)\" by auto\n    show \"sgn (poly (p*q) x) = (if x > x\\<^sub>0 then 1 else -1)\"\n    proof (cases \"x \\<ge> x\\<^sub>0\")\n      case True\n        with `x \\<noteq> x\\<^sub>0` have \"x > x\\<^sub>0\" by simp\n        from poly_MVT[OF this, of p] guess \\<xi> ..\n        note \\<xi>_props = this\n        with `\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>` `poly p x\\<^sub>0 = 0` `x > x\\<^sub>0` \\<epsilon>_props\n            have \"\\<bar>\\<xi> - x\\<^sub>0\\<bar> < \\<epsilon>\" \"sgn (poly p x) = sgn (x - x\\<^sub>0) * sgn (poly q \\<xi>)\" \n            by (auto simp add: q_pderiv sgn_mult) \n        moreover from \\<xi>_props \\<epsilon>_props `\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>` \n            have \"\\<forall>t. \\<xi> \\<le> t \\<and> t \\<le> x \\<longrightarrow> poly q t \\<noteq> 0\" by auto\n        hence \"sgn (poly q \\<xi>) = sgn (poly q x)\" using \\<xi>_props \\<epsilon>_props\n            by (intro no_roots_inbetween_imp_same_sign, simp_all)\n        ultimately show ?thesis using True `x \\<noteq> x\\<^sub>0` \\<epsilon>_props \\<xi>_props\n            by (auto simp: sgn_mult sqr_pos)\n    next\n      case False\n        hence \"x < x\\<^sub>0\" by simp\n        hence sgn: \"sgn (x - x\\<^sub>0) = -1\" by simp\n        from poly_MVT[OF `x < x\\<^sub>0`, of p] guess \\<xi> ..\n        note \\<xi>_props = this\n        with `\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>` `poly p x\\<^sub>0 = 0` `x < x\\<^sub>0` \\<epsilon>_props\n            have \"\\<bar>\\<xi> - x\\<^sub>0\\<bar> < \\<epsilon>\" \"poly p x = (x - x\\<^sub>0) * poly (pderiv p) \\<xi>\" \n                 \"poly p \\<xi> \\<noteq> 0\" by (auto simp: field_simps)\n        hence \"sgn (poly p x) = sgn (x - x\\<^sub>0) * sgn (poly q \\<xi>)\" \n            using \\<epsilon>_props \\<xi>_props by (auto simp: q_pderiv sgn_mult)\n        moreover from \\<xi>_props \\<epsilon>_props `\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>` \n            have \"\\<forall>t. x \\<le> t \\<and> t \\<le> \\<xi> \\<longrightarrow> poly q t \\<noteq> 0\" by auto\n        hence \"sgn (poly q \\<xi>) = sgn (poly q x)\" using \\<xi>_props \\<epsilon>_props\n            by (rule_tac sym, intro no_roots_inbetween_imp_same_sign, simp_all)\n        ultimately show ?thesis using False `x \\<noteq> x\\<^sub>0` \n            by (auto simp: sgn_mult sqr_pos) \n    qed\n  qed\nqed\n\nlemma sturm_firsttwo_signs:\n  fixes ps :: \"real poly list\"\n  assumes squarefree: \"rsquarefree p\"\n  assumes p_0: \"poly p (x\\<^sub>0::real) = 0\"\n  shows \"eventually (\\<lambda>x. sgn (poly (p * sturm p ! 1) x) =\n             (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\nproof-\n  from assms have [simp]: \"p \\<noteq> 0\" by (auto simp add: rsquarefree_roots)\n  with squarefree p_0 have [simp]: \"pderiv p \\<noteq> 0\"\n      by (auto simp  add:rsquarefree_roots)\n  from assms show ?thesis\n      by (intro sturm_firsttwo_signs_aux, \n          simp_all add: rsquarefree_roots)\nqed\n\n\ntext {*\n  The construction also obviously fulfils the property about three \n  adjacent polynomials in the sequence.\n*}\n\nlemma sturm_signs:\n  assumes squarefree: \"rsquarefree p\"\n  assumes i_in_range: \"i < length (sturm (p :: real poly)) - 2\" \n  assumes q_0: \"poly (sturm p ! (i+1)) x = 0\" (is \"poly ?q x = 0\")\n  shows \"poly (sturm p ! (i+2)) x * poly (sturm p ! i) x < 0\"\n            (is \"poly ?p x * poly ?r x < 0\")\nproof-\n  from sturm_indices[OF i_in_range] \n      have \"sturm p ! (i+2) = - (sturm p ! i mod sturm p ! (i+1))\"\n           (is \"?r = - (?p mod ?q)\") .\n  hence \"-?r = ?p mod ?q\" by simp\n  with mod_div_equality[of ?p ?q] have \"?p div ?q * ?q - ?r = ?p\" by simp\n  hence \"poly (?p div ?q) x * poly ?q x - poly ?r x = poly ?p x\"\n      by (metis poly_diff poly_mult)\n  with q_0 have r_x: \"poly ?r x = -poly ?p x\" by simp\n  moreover have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> x * x > 0\" apply (case_tac \"x \\<ge> 0\")\n      by (simp_all add: mult_neg_neg)\n  from sturm_adjacent_root_not_squarefree[of i p] assms r_x\n      have \"poly ?p x * poly ?p x > 0\" by (force intro: sqr_pos)\n  ultimately show \"poly ?r x * poly ?p x < 0\" by simp\nqed\n\n\ntext {*\n  Finally, if $p$ contains no multiple roots, @{term \"sturm p\"}, i.e. \n  the canonical Sturm sequence for $p$, is a Sturm sequence \n  and can be used to determine the number of roots of $p$.\n*}\nlemma sturm_seq_sturm[simp]: \n   assumes \"rsquarefree p\"\n   shows \"sturm_seq (sturm p) p\"\nproof\n  show \"sturm p \\<noteq> []\" by simp\n  show \"hd (sturm p) = p\" by simp\n  show \"length (sturm p) \\<ge> 2\" by simp\n  from assms show \"\\<And>x. \\<not>(poly p x = 0 \\<and> poly (sturm p ! 1) x = 0)\"\n      by (simp add: rsquarefree_roots)\nnext\n  fix x :: real and y :: real\n  have \"degree (last (sturm p)) = 0\" by simp\n  then obtain c where \"last (sturm p) = [:c:]\" \n      by (cases \"last (sturm p)\", simp split: split_if_asm)\n  thus \"\\<And>x y. sgn (poly (last (sturm p)) x) =\n            sgn (poly (last (sturm p)) y)\" by simp\nnext\n  from sturm_firsttwo_signs[OF assms] \n    show \"\\<And>x\\<^sub>0. poly p x\\<^sub>0 = 0 \\<Longrightarrow>\n         eventually (\\<lambda>x. sgn (poly (p*sturm p ! 1) x) = \n                         (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\" by simp\nnext\n  from sturm_signs[OF assms]\n    show \"\\<And>i x. \\<lbrakk>i < length (sturm p) - 2; poly (sturm p ! (i + 1)) x = 0\\<rbrakk>\n          \\<Longrightarrow> poly (sturm p ! (i + 2)) x * poly (sturm p ! i) x < 0\" by simp\nqed\n\n\nsubsubsection {* Canonical squarefree Sturm sequence *}\n\ntext {*\n  The previous construction does not work for polynomials with multiple roots,\n  but we can simply ``divide away'' multiple roots by dividing $p$ by the \n  GCD of $p$ and $p'$. The resulting polynomial has the same roots as $p$, \n  but with multiplicity 1, allowing us to again use the canonical construction.\n*}\ndefinition sturm_squarefree where\n  \"sturm_squarefree p = sturm (p div (gcd p (pderiv p)))\"\n\nlemma sturm_squarefree_not_Nil[simp]: \"sturm_squarefree p \\<noteq> []\"\n  by (simp add: sturm_squarefree_def)\n\n\nlemma sturm_seq_sturm_squarefree:\n  assumes [simp]: \"p \\<noteq> 0\"\n  defines [simp]: \"p' \\<equiv> p div gcd p (pderiv p)\"\n  shows \"sturm_seq (sturm_squarefree p) p'\"\nproof\n  have \"rsquarefree p'\" \n  proof (subst rsquarefree_roots, clarify)\n    fix x assume \"poly p' x = 0\" \"poly (pderiv p') x = 0\"\n    hence \"[:-x,1:] dvd gcd p' (pderiv p')\" by (simp add: poly_eq_0_iff_dvd)\n    also from poly_div_gcd_squarefree(1)[OF assms(1)]\n        have \"gcd p' (pderiv p') = 1\" by simp\n    finally show False by (simp add: poly_eq_0_iff_dvd[symmetric])\n  qed\n\n  from sturm_seq_sturm[OF `rsquarefree p'`] \n      interpret sturm_seq: sturm_seq \"sturm_squarefree p\" p' \n      by (simp add: sturm_squarefree_def)\n\n  show \"\\<And>x y. sgn (poly (last (sturm_squarefree p)) x) = \n      sgn (poly (last (sturm_squarefree p)) y)\" by simp\n  show \"sturm_squarefree p \\<noteq> []\" by simp\n  show \"hd (sturm_squarefree p) = p'\" by (simp add: sturm_squarefree_def)\n  show \"length (sturm_squarefree p) \\<ge> 2\" by simp\n\n  have [simp]: \"sturm_squarefree p ! 0 = p'\" \n               \"sturm_squarefree p ! Suc 0 = pderiv p'\" \n      by (simp_all add: sturm_squarefree_def) \n\n  from `rsquarefree p'` \n      show \"\\<And>x. \\<not> (poly p' x = 0 \\<and> poly (sturm_squarefree p ! 1) x = 0)\"\n      by (simp add: rsquarefree_roots)\n\n  from sturm_seq.signs show \"\\<And>i x. \\<lbrakk>i < length (sturm_squarefree p) - 2;\n                                 poly (sturm_squarefree p ! (i + 1)) x = 0\\<rbrakk>\n                                 \\<Longrightarrow> poly (sturm_squarefree p ! (i + 2)) x *\n                                         poly (sturm_squarefree p ! i) x < 0\" .\n\n  from sturm_seq.deriv show \"\\<And>x\\<^sub>0. poly p' x\\<^sub>0 = 0 \\<Longrightarrow>\n         eventually (\\<lambda>x. sgn (poly (p' * sturm_squarefree p ! 1) x) =\n                         (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\" .\nqed\n\n\nsubsubsection {* Optimisation for multiple roots *}\n\ntext {*\n  We can also define the following non-canonical Sturm sequence that \n  is obtained by taking the canonical Sturm sequence of $p$\n  (possibly with multiple roots) and then dividing the entire \n  sequence by the GCD of $p$ and its derivative.\n*}\ndefinition sturm_squarefree' where\n\"sturm_squarefree' p = (let d = gcd p (pderiv p)\n                         in map (\\<lambda>p'. p' div d) (sturm p))\"\n\ntext {*\n  This construction also has all the desired properties:\n*}\n\nlemma sturm_squarefree'_adjacent_root_propagate_left:\n  assumes \"p \\<noteq> 0\"\n  assumes \"i < length (sturm_squarefree' (p :: real poly)) - 1\"\n  assumes \"poly (sturm_squarefree' p ! i) x = 0\"\n      and \"poly (sturm_squarefree' p ! (i + 1)) x = 0\"\n  shows \"\\<forall>j\\<le>i+1. poly (sturm_squarefree' p ! j) x = 0\"\nproof (intro sturm_adjacent_root_aux[OF assms(2,3,4)])\n  case (goal1 i x)\n    def q \\<equiv> \"sturm p ! i\" \n    def r \\<equiv> \"sturm p ! (Suc i)\"\n    def s \\<equiv> \"sturm p ! (Suc (Suc i))\"\n    def d \\<equiv> \"gcd p (pderiv p)\"\n    def q' \\<equiv> \"q div d\" and r' \\<equiv> \"r div d\" and s' \\<equiv> \"s div d\"\n    from `p \\<noteq> 0` have \"d \\<noteq> 0\" unfolding d_def by simp\n    from goal1(1) have i_in_range: \"i < length (sturm p) - 2\"\n        unfolding sturm_squarefree'_def Let_def by simp\n    have [simp]: \"d dvd q\" \"d dvd r\" \"d dvd s\" unfolding q_def r_def s_def d_def\n        using i_in_range by (auto intro: sturm_gcd)\n    hence qrs_simps: \"q = q' * d\" \"r = r' * d\" \"s = s' * d\" \n        unfolding q'_def r'_def s'_def by (simp_all add: dvd_div_mult_self)\n    with goal1(2) i_in_range have r'_0: \"poly r' x = 0\" \n        unfolding r'_def r_def d_def sturm_squarefree'_def Let_def by simp\n    hence r_0: \"poly r x = 0\" by (simp add: `r = r' * d`)\n    from sturm_indices[OF i_in_range] have \"q = q div r * r - s\"\n        unfolding q_def r_def s_def by (simp add: mod_div_equality)\n    hence \"q' = (q div r * r - s) div d\" by (simp add: q'_def)\n    also have \"... = (q div r * r) div d - s'\" \n        unfolding s'_def by (rule div_diff[symmetric], simp_all)\n    also have \"... = q div r * r' - s'\"\n        using dvd_div_mult[OF `d dvd r`, of \"q div r\"] \n        by (simp add: algebra_simps r'_def)\n    also have \"q div r = q' div r'\" by (simp add: qrs_simps `d \\<noteq> 0`)\n    finally have \"poly q' x = poly (q' div r' * r' - s') x\" by simp\n    also from r'_0 have \"... = -poly s' x\" by simp\n    finally have \"poly s' x = -poly q' x\" by simp\n    thus ?case using i_in_range\n        unfolding q'_def s'_def q_def s_def sturm_squarefree'_def Let_def\n        by (simp add: d_def sgn_minus)\nqed\n\nlemma sturm_squarefree'_adjacent_roots:\n  assumes \"p \\<noteq> 0\"\n           \"i < length (sturm_squarefree' (p :: real poly)) - 1\"\n          \"poly (sturm_squarefree' p ! i) x = 0\" \n          \"poly (sturm_squarefree' p ! (i + 1)) x = 0\"\n  shows False\nproof-\n  def d \\<equiv> \"gcd p (pderiv p)\"\n  from sturm_squarefree'_adjacent_root_propagate_left[OF assms]\n      have \"poly (sturm_squarefree' p ! 0) x = 0\" \n           \"poly (sturm_squarefree' p ! 1) x = 0\" by auto\n  hence \"poly (p div d) x = 0\" \"poly (pderiv p div d) x = 0\"\n      using assms(2)\n      unfolding sturm_squarefree'_def Let_def d_def by auto\n  moreover from div_gcd_coprime_poly assms(1) \n      have \"coprime (p div d) (pderiv p div d)\" unfolding d_def by auto\n  ultimately show False using coprime_imp_no_common_roots by auto\nqed\n\nlemma sturm_squarefree'_signs:\n  assumes \"p \\<noteq> 0\"\n  assumes i_in_range: \"i < length (sturm_squarefree' (p :: real poly)) - 2\" \n  assumes q_0: \"poly (sturm_squarefree' p ! (i+1)) x = 0\" (is \"poly ?q x = 0\")\n  shows \"poly (sturm_squarefree' p ! (i+2)) x * \n         poly (sturm_squarefree' p ! i) x < 0\"\n            (is \"poly ?r x * poly ?p x < 0\")\nproof-\n  def d \\<equiv> \"gcd p (pderiv p)\"\n  with `p \\<noteq> 0` have [simp]: \"d \\<noteq> 0\" by simp\n\n  from i_in_range have i_in_range': \"i < length (sturm p) - 2\"\n      unfolding sturm_squarefree'_def by simp\n  hence \"d dvd (sturm p ! i)\" (is \"d dvd ?p'\")\n        \"d dvd (sturm p ! (Suc i))\" (is \"d dvd ?q'\")\n        \"d dvd (sturm p ! (Suc (Suc i)))\" (is \"d dvd ?r'\")\n      unfolding d_def by (auto intro: sturm_gcd)\n  hence pqr_simps: \"?p' = ?p * d\" \"?q' = ?q * d\" \"?r' = ?r * d\"\n    unfolding sturm_squarefree'_def Let_def d_def using i_in_range'\n    by (auto simp: dvd_div_mult_self) \n  with q_0 have q'_0: \"poly ?q' x = 0\" by simp\n  from sturm_indices[OF i_in_range'] \n      have \"sturm p ! (i+2) = - (sturm p ! i mod sturm p ! (i+1))\" .\n  hence \"-?r' = ?p' mod ?q'\" by simp\n  with mod_div_equality[of ?p' ?q'] have \"?p' div ?q' * ?q' - ?r' = ?p'\" by simp\n  hence \"d*(?p div ?q * ?q - ?r) = d* ?p\" by (simp add: pqr_simps algebra_simps)\n  hence \"?p div ?q * ?q - ?r = ?p\" by simp\n  hence \"poly (?p div ?q) x * poly ?q x - poly ?r x = poly ?p x\" \n      by (metis poly_diff poly_mult)\n  with q_0 have r_x: \"poly ?r x = -poly ?p x\" by simp\n\n  from sturm_squarefree'_adjacent_roots[OF `p \\<noteq> 0`] i_in_range q_0\n      have \"poly ?p x \\<noteq> 0\" by force\n  moreover have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> x * x > 0\" apply (case_tac \"x \\<ge> 0\")\n      by (simp_all add: mult_neg_neg)\n  ultimately show ?thesis using r_x by simp\nqed\n\n\ntext {*\n  This approach indeed also yields a valid squarefree Sturm sequence\n  for the polynomial $p/\\text{gcd}(p,p')$.\n*}\nlemma sturm_seq_sturm_squarefree':\n  assumes \"(p :: real poly) \\<noteq> 0\"\n  defines \"d \\<equiv> gcd p (pderiv p)\"\n  shows \"sturm_seq (sturm_squarefree' p) (p div d)\"\n      (is \"sturm_seq ?ps' ?p'\")\nproof\n  show \"?ps' \\<noteq> []\" \"hd ?ps' = ?p'\" \"2 \\<le> length ?ps'\"\n      by (simp_all add: sturm_squarefree'_def d_def hd_map)\n\n  from assms have \"d \\<noteq> 0\" by simp\n  {\n    have \"d dvd last (sturm p)\" unfolding d_def\n        by (rule sturm_gcd, simp)\n    hence \"last (sturm p) = last ?ps' * d\"\n        by (simp add: sturm_squarefree'_def last_map d_def dvd_div_mult_self)\n    moreover from this have \"last ?ps' dvd last (sturm p)\" by simp\n    moreover note dvd_imp_degree_le[OF this]\n    ultimately have \"degree (last ?ps') \\<le> degree (last (sturm p))\" \n        using `d \\<noteq> 0` by (cases \"last ?ps' = 0\", auto)\n    hence \"degree (last ?ps') = 0\" by simp\n    then obtain c where \"last ?ps' = [:c:]\" \n        by (cases \"last ?ps'\", simp split: split_if_asm)\n    thus \"\\<And>x y. sgn (poly (last ?ps') x) = sgn (poly (last ?ps') y)\" by simp\n  }\n\n  have squarefree: \"rsquarefree ?p'\" using `p \\<noteq> 0`\n    by (subst rsquarefree_roots, unfold d_def, \n        intro allI coprime_imp_no_common_roots poly_div_gcd_squarefree)\n  have [simp]: \"sturm_squarefree' p ! Suc 0 = pderiv p div d\"\n      unfolding sturm_squarefree'_def Let_def sturm_def d_def\n          by (subst sturm_aux.simps, simp)\n  have coprime: \"coprime ?p' (pderiv p div d)\" \n      unfolding d_def using div_gcd_coprime_poly `p \\<noteq> 0` by blast\n  thus squarefree':\n      \"\\<And>x. \\<not> (poly (p div d) x = 0 \\<and> poly (sturm_squarefree' p ! 1) x = 0)\"\n      using coprime_imp_no_common_roots by simp\n\n  from sturm_squarefree'_signs[OF `p \\<noteq> 0`]\n      show \"\\<And>i x. \\<lbrakk>i < length ?ps' - 2; poly (?ps' ! (i + 1)) x = 0\\<rbrakk>\n                \\<Longrightarrow> poly (?ps' ! (i + 2)) x * poly (?ps' ! i) x < 0\" .\n\n  have [simp]: \"?p' \\<noteq> 0\" using squarefree by (simp add: rsquarefree_def)\n  have A: \"?p' = ?ps' ! 0\" \"pderiv p div d = ?ps' ! 1\"\n      by (simp_all add: sturm_squarefree'_def Let_def d_def sturm_def,\n          subst sturm_aux.simps, simp)\n  have [simp]: \"?ps' ! 0 \\<noteq> 0\" using squarefree\n      by (auto simp: A rsquarefree_def)\n\n  fix x\\<^sub>0 :: real\n  assume \"poly ?p' x\\<^sub>0 = 0\"\n  hence \"poly p x\\<^sub>0 = 0\" using poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`] \n      unfolding d_def by simp\n  hence \"pderiv p \\<noteq> 0\" using `p \\<noteq> 0` by (auto dest: pderiv_iszero)\n  with `p \\<noteq> 0` `poly p x\\<^sub>0 = 0`\n      have A: \"eventually (\\<lambda>x. sgn (poly (p * pderiv p) x) = \n                              (if x\\<^sub>0 < x then 1 else -1)) (at x\\<^sub>0)\"\n      by (intro sturm_firsttwo_signs_aux, simp_all)\n  note ev = eventually_conj[OF A poly_neighbourhood_without_roots[OF `d \\<noteq> 0`]]\n\n  show \"eventually (\\<lambda>x. sgn (poly (p div d * sturm_squarefree' p ! 1) x) =\n                        (if x\\<^sub>0 < x then 1 else -1)) (at x\\<^sub>0)\"\n  proof (rule eventually_mono[OF _ ev], clarify)\n      have [intro]:\n          \"\\<And>a (b::real). b \\<noteq> 0 \\<Longrightarrow> a < 0 \\<Longrightarrow> a / (b * b) < 0\"\n          \"\\<And>a (b::real). b \\<noteq> 0 \\<Longrightarrow> a > 0 \\<Longrightarrow> a / (b * b) > 0\"\n          by ((case_tac \"b > 0\", \n              auto simp: mult_neg_neg field_simps) [])+\n    case (goal1 x)\n      hence  [simp]: \"poly d x * poly d x > 0\" \n           by (cases \"poly d x > 0\", auto simp: mult_neg_neg)\n      from poly_div_gcd_squarefree_aux(2)[OF `pderiv p \\<noteq> 0`]\n          have \"poly (p div d) x = 0 \\<longleftrightarrow> poly p x = 0\" by (simp add: d_def)\n      moreover have \"d dvd p\" \"d dvd pderiv p\" unfolding d_def by simp_all\n      ultimately show ?case using goal1\n          by (auto simp: sgn_real_def poly_div not_less[symmetric] \n                         zero_less_divide_iff split: split_if_asm)\n  qed\nqed\n\n\ntext {*\n  This construction is obviously more expensive to compute than the one that \\emph{first} \n  divides $p$ by $\\text{gcd}(p,p')$ and \\emph{then} applies the canonical construction.\n  In this construction, we \\emph{first} compute the canonical Sturm sequence of $p$ as if \n  it had no multiple roots and \\emph{then} divide by the GCD.\n  However, it can be seen quite easily that unless $x$ is a multiple root of $p$, \n  i.\\,e. as long as $\\text{gcd}(P,P')\\neq 0$, the number of sign changes in a sequence of \n  polynomials does not actually change when we divide the polynomials by $\\text{gcd}(p,p')$.\\\\\n  There\\-fore we can use the ca\\-no\\-ni\\-cal Sturm se\\-quence even in the non-square\\-free \n  case as long as the borders of the interval we are interested in are not multiple roots \n  of the polynomial.\n*}\n\nlemma sign_changes_mult_aux:\n  assumes \"d \\<noteq> (0::real)\"\n  shows \"length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map (op *d \\<circ> f) xs))) =\n         length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map f xs)))\"\nproof-\n  from assms have inj: \"inj (op *d)\" by (auto intro: injI)\n  from assms have [simp]: \"filter (\\<lambda>x. (op* d \\<circ> f) x \\<noteq> 0) = filter (\\<lambda>x. f x \\<noteq> 0)\"\n                          \"filter ((\\<lambda>x. x \\<noteq> 0) \\<circ> f) = filter (\\<lambda>x. f x \\<noteq> 0)\"\n      by (simp_all add: o_def)\n  have \"filter (\\<lambda>x. x \\<noteq> 0) (map (op* d \\<circ> f) xs) = \n        map (op* d \\<circ> f) (filter (\\<lambda>x. (op* d \\<circ> f) x \\<noteq> 0) xs)\" \n      by (simp add: filter_map o_def)\n  thus ?thesis using remdups_adj_map_injective[OF inj] assms\n      by (simp add: filter_map map_map[symmetric] del: map_map)\nqed\n\nlemma sturm_sturm_squarefree'_same_sign_changes:\n  fixes p :: \"real poly\"\n  defines \"ps \\<equiv> sturm p\" and \"ps' \\<equiv> sturm_squarefree' p\"\n  shows \"poly p x \\<noteq> 0 \\<or> poly (pderiv p) x \\<noteq> 0 \\<Longrightarrow>\n             sign_changes ps' x = sign_changes ps x\"\n        \"p \\<noteq> 0 \\<Longrightarrow> sign_changes_inf ps' = sign_changes_inf ps\"\n        \"p \\<noteq> 0 \\<Longrightarrow> sign_changes_neg_inf ps' = sign_changes_neg_inf ps\"\nproof-\n  def d \\<equiv> \"gcd p (pderiv p)\"\n  def p' \\<equiv> \"p div d\"\n  def s' \\<equiv> \"poly_inf d\"\n  def s'' \\<equiv> \"poly_neg_inf d\"\n\n  {\n    fix x :: real and q :: \"real poly\"\n    assume \"q \\<in> set ps\"\n    hence \"d dvd q\" unfolding d_def ps_def using sturm_gcd by simp\n    hence q_prod: \"q = (q div d) * d\" unfolding p'_def d_def\n        by (simp add: algebra_simps dvd_mult_div_cancel)\n\n    have \"poly q x = poly d x * poly (q div d) x\"  by (subst q_prod, simp)\n    hence s1: \"sgn (poly q x) = sgn (poly d x) * sgn (poly (q div d) x)\" \n        by (subst q_prod, simp add: sgn_mult)\n    from poly_inf_mult have s2: \"poly_inf q = s' * poly_inf (q div d)\"\n        unfolding s'_def by (subst q_prod, simp)\n    from poly_inf_mult have s3: \"poly_neg_inf q = s'' * poly_neg_inf (q div d)\"\n        unfolding s''_def by (subst q_prod, simp)\n    note s1 s2 s3\n  }\n  note signs = this\n\n  {\n    fix f :: \"real poly \\<Rightarrow> real\" and s :: real\n    assume f: \"\\<And>q. q \\<in> set ps \\<Longrightarrow> f q = s * f (q div d)\" and s: \"s \\<noteq> 0\"\n    hence \"inverse s \\<noteq> 0\" by simp\n    {fix q assume \"q \\<in> set ps\"\n     hence \"f (q div d) = inverse s * f q\" \n         by (subst f[of q], simp_all add: s)\n    } note f' = this\n    have \"length (remdups_adj [x\\<leftarrow>map f (map (\\<lambda>q. q div d) ps). x \\<noteq> 0]) - 1 = \n           length (remdups_adj [x\\<leftarrow>map (\\<lambda>q. f (q div d)) ps . x \\<noteq> 0]) - 1\"\n        by (simp only: sign_changes_def o_def map_map)\n    also have \"map (\\<lambda>q. q div d) ps = ps'\" \n        by (simp add: ps_def ps'_def sturm_squarefree'_def Let_def d_def)\n    also from f' have \"map (\\<lambda>q. f (q div d)) ps = \n                      map (\\<lambda>x. (op*(inverse s) \\<circ> f) x) ps\" by (simp add: o_def)\n    also note sign_changes_mult_aux[OF `inverse s \\<noteq> 0`, of f ps]\n    finally have \n        \"length (remdups_adj [x\\<leftarrow>map f ps' . x \\<noteq> 0]) - 1 =\n         length (remdups_adj [x\\<leftarrow>map f ps . x \\<noteq> 0]) - 1\" by simp\n  }\n  note length_remdups_adj = this\n\n  {\n    fix x assume A: \"poly p x \\<noteq> 0 \\<or> poly (pderiv p) x \\<noteq> 0\"\n    have \"d dvd p\" \"d dvd pderiv p\" unfolding d_def by simp_all\n    with A have \"sgn (poly d x) \\<noteq> 0\" \n        by (auto simp add: sgn_zero_iff elim: dvdE) \n    thus \"sign_changes ps' x = sign_changes ps x\" using signs(1)\n        unfolding sign_changes_def\n        by (intro length_remdups_adj[of \"\\<lambda>q. sgn (poly q x)\"], simp_all)\n  }\n\n  assume \"p \\<noteq> 0\"\n  hence \"d \\<noteq> 0\" unfolding d_def by simp\n  hence \"s' \\<noteq> 0\" \"s'' \\<noteq> 0\" unfolding s'_def s''_def by simp_all\n  from length_remdups_adj[of poly_inf s', OF signs(2) `s' \\<noteq> 0`]\n      show \"sign_changes_inf ps' = sign_changes_inf ps\"\n      unfolding sign_changes_inf_def .\n  from length_remdups_adj[of poly_neg_inf s'', OF signs(3) `s'' \\<noteq> 0`]\n      show \"sign_changes_neg_inf ps' = sign_changes_neg_inf ps\"\n      unfolding sign_changes_neg_inf_def .\nqed\n\n \n\nsubsection {* Root-counting functions *}\n\ntext {*\n  With all these results, we can now define functions that count roots \n  in bounded and unbounded intervals:\n*}\n\ndefinition count_roots_between where\n\"count_roots_between p a b = (if a \\<le> b \\<and> p \\<noteq> 0 then \n  (let ps = sturm_squarefree p\n    in sign_changes ps a - sign_changes ps b) else 0)\"\n\ndefinition count_roots where\n\"count_roots p = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes_neg_inf ps - sign_changes_inf ps))\"\n\ndefinition count_roots_above where\n\"count_roots_above p a = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes ps a - sign_changes_inf ps))\"\n\ndefinition count_roots_below where\n\"count_roots_below p a = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes_neg_inf ps - sign_changes ps a))\"\n\n\nlemma count_roots_between_correct:\n  \"count_roots_between p a b = card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\"\nproof (cases \"p \\<noteq> 0 \\<and> a \\<le> b\")\n  case False\n    note False' = this\n    hence \"card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0} = 0\"\n    proof (cases \"a < b\")\n      case True\n        with False have [simp]: \"p = 0\" by simp\n        have subset: \"{a<..<b} \\<subseteq> {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by auto\n        from infinite_Ioo[OF True] have \"\\<not>finite {a<..<b}\" .\n        hence \"\\<not>finite {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\"\n            using finite_subset[OF subset] by blast\n        thus ?thesis by simp\n    next\n      case False\n        with False' show ?thesis by (auto simp: not_less card_eq_0_iff)\n    qed\n    thus ?thesis unfolding count_roots_between_def Let_def using False by auto\nnext\n  case True\n  hence \"p \\<noteq> 0\" \"a \\<le> b\" by simp_all\n  def p' \\<equiv> \"p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF `p \\<noteq> 0`]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from poly_roots_finite[OF `p' \\<noteq> 0`] \n      have \"finite {x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0}\" by fast\n  have \"count_roots_between p a b = card {x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0}\"\n      unfolding count_roots_between_def Let_def\n      using True count_roots_between[OF `p' \\<noteq> 0` `a \\<le> b`] by simp\n  also from poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`]\n      have \"{x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0} = \n            {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots p = card {x. poly p x = 0}\" (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with infinite_Ioo[of 0 1] finite_subset[of \"{0<..<1}\" ?S]\n        have \"\\<not>finite {x. poly p x = 0}\" by force\n    thus ?thesis by (simp add: count_roots_def True)\nnext\n  case False\n  def p' \\<equiv> \"p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF `p \\<noteq> 0`]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots[OF `p' \\<noteq> 0`]\n      have \"count_roots p = card {x. poly p' x = 0}\"\n      unfolding count_roots_def Let_def by (simp add: `p \\<noteq> 0`)\n  also from poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`]\n      have \"{x. poly p' x = 0} = {x. poly p x = 0}\" unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_above_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots_above p a = card {x. x > a \\<and> poly p x = 0}\" \n         (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with infinite_Ioo[of a \"a+1\"] finite_subset[of \"{a<..<a+1}\" ?S]\n        have \"\\<not>finite {x. x > a \\<and> poly p x = 0}\" by force\n    thus ?thesis by (simp add: count_roots_above_def True)\nnext\n  case False\n  def p' \\<equiv> \"p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF `p \\<noteq> 0`]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots_above[OF `p' \\<noteq> 0`]\n      have \"count_roots_above p a = card {x. x > a \\<and> poly p' x = 0}\"\n      unfolding count_roots_above_def Let_def by (simp add: `p \\<noteq> 0`)\n  also from poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`]\n      have \"{x. x > a \\<and> poly p' x = 0} = {x. x > a \\<and> poly p x = 0}\" \n      unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_below_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots_below p a = card {x. x \\<le> a \\<and> poly p x = 0}\" \n         (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with infinite_Ioo[of \"a - 1\" a] \n         finite_subset[of \"{a - 1<..<a}\" ?S]\n        have \"\\<not>finite {x. x \\<le> a \\<and> poly p x = 0}\" by force\n    thus ?thesis by (simp add: count_roots_below_def True)\nnext\n  case False\n  def p' \\<equiv> \"p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF `p \\<noteq> 0`]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots_below[OF `p' \\<noteq> 0`]\n      have \"count_roots_below p a = card {x. x \\<le> a \\<and> poly p' x = 0}\"\n      unfolding count_roots_below_def Let_def by (simp add: `p \\<noteq> 0`)\n  also from poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`]\n      have \"{x. x \\<le> a \\<and> poly p' x = 0} = {x. x \\<le> a \\<and> poly p x = 0}\" \n      unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\ntext {*\n  The optimisation explained above can be used to prove more efficient code equations that \n  use the more efficient construction in the case that the interval borders are not \n  multiple roots:\n*}\n\nlemma count_roots_between[code]:\n  \"count_roots_between p a b =\n     (let q = pderiv p\n       in if a > b \\<or> p = 0 then 0\n       else if (poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0) \\<and> (poly p b \\<noteq> 0 \\<or> poly q b \\<noteq> 0)\n            then (let ps = sturm p \n                   in sign_changes ps a - sign_changes ps b)\n            else (let ps = sturm_squarefree p\n                   in sign_changes ps a - sign_changes ps b))\"\nproof (cases \"a > b \\<or> p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_between_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"a \\<le> b\" \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0) \\<and> \n                  (poly p b \\<noteq> 0 \\<or> poly (pderiv p) b \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1 \n          by (auto simp add: Let_def count_roots_between_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" and \n            B: \"poly p b \\<noteq> 0 \\<or> poly (pderiv p) b \\<noteq> 0\" by auto\n      def d \\<equiv> \"gcd p (pderiv p)\"\n      from `p \\<noteq> 0` have [simp]: \"p div d \\<noteq> 0\" \n          using poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF `p \\<noteq> 0`]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_between_correct\n      also have \"{x. a < x \\<and> x \\<le> b \\<and> poly p x = 0} = \n                 {x. a < x \\<and> x \\<le> b \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`] by simp\n      also note count_roots_between[OF `p div d \\<noteq> 0` `a \\<le> b`, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF B]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\n\nlemma count_roots_code[code]: \n  \"count_roots (p::real poly) =\n    (if p = 0 then 0 \n     else let ps = sturm p \n           in sign_changes_neg_inf ps - sign_changes_inf ps)\"\nproof (cases \"p = 0\", simp add: count_roots_def)\n  case False\n    def d \\<equiv> \"gcd p (pderiv p)\"\n    from `p \\<noteq> 0` have [simp]: \"p div d \\<noteq> 0\" \n        using poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] by (auto simp add: d_def)\n    from sturm_seq_sturm_squarefree'[OF `p \\<noteq> 0`]\n        interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n        unfolding sturm_squarefree'_def Let_def d_def .\n\n    note count_roots_correct\n    also have \"{x. poly p x = 0} = {x. poly (p div d) x = 0}\"\n        unfolding d_def using poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`] by simp\n    also note count_roots[OF `p div d \\<noteq> 0`, symmetric]\n    also note sturm_sturm_squarefree'_same_sign_changes(2)[OF `p \\<noteq> 0`]\n    also note sturm_sturm_squarefree'_same_sign_changes(3)[OF `p \\<noteq> 0`]\n    finally show ?thesis using False unfolding Let_def by simp\nqed\n\n\nlemma count_roots_above_code[code]:\n  \"count_roots_above p a =\n     (let q = pderiv p\n       in if p = 0 then 0\n       else if poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0\n            then (let ps = sturm p \n                   in sign_changes ps a - sign_changes_inf ps)\n            else (let ps = sturm_squarefree p\n                   in sign_changes ps a - sign_changes_inf ps))\"\nproof (cases \"p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_above_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1 \n          by (auto simp add: Let_def count_roots_above_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" by simp\n      def d \\<equiv> \"gcd p (pderiv p)\"\n      from `p \\<noteq> 0` have [simp]: \"p div d \\<noteq> 0\" \n          using poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF `p \\<noteq> 0`]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_above_correct\n      also have \"{x. a < x \\<and> poly p x = 0} = \n                 {x. a < x \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`] by simp\n      also note count_roots_above[OF `p div d \\<noteq> 0`, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(2)[OF `p \\<noteq> 0`]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\nlemma count_roots_below_code[code]:\n  \"count_roots_below p a =\n     (let q = pderiv p\n       in if p = 0 then 0\n       else if poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0\n            then (let ps = sturm p \n                   in sign_changes_neg_inf ps - sign_changes ps a)\n            else (let ps = sturm_squarefree p\n                   in sign_changes_neg_inf ps - sign_changes ps a))\"\nproof (cases \"p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_below_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1 \n          by (auto simp add: Let_def count_roots_below_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" by simp\n      def d \\<equiv> \"gcd p (pderiv p)\"\n      from `p \\<noteq> 0` have [simp]: \"p div d \\<noteq> 0\" \n          using poly_div_gcd_squarefree(1)[OF `p \\<noteq> 0`] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF `p \\<noteq> 0`]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_below_correct\n      also have \"{x. x \\<le> a \\<and> poly p x = 0} = \n                 {x. x \\<le> a \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF `p \\<noteq> 0`] by simp\n      also note count_roots_below[OF `p div d \\<noteq> 0`, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(3)[OF `p \\<noteq> 0`]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\nend\n", "meta": {"author": "pruvisto", "repo": "sturm", "sha": "359aa63abd1ca94bf0ec036704d8d0c6014c4730", "save_path": "github-repos/isabelle/pruvisto-sturm", "path": "github-repos/isabelle/pruvisto-sturm/sturm-359aa63abd1ca94bf0ec036704d8d0c6014c4730/Sturm_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8947894541786198, "lm_q1q2_score": 0.7881279366459526}}
{"text": "header {*\\isaheader{Implementing Priority Queues by Annotated Lists}*}\ntheory PrioByAnnotatedList\nimports \n  \"../spec/AnnotatedListSpec\"\n  \"../spec/PrioSpec\"\nbegin\n\ntext {*\n  In this theory, we implement priority queues by annotated lists.\n\n  The implementation is realized as a generic adapter from the\n  AnnotatedList to the priority queue interface.\n\n  Priority queues are realized as a sequence of pairs of\n  elements and associated priority. The monoids operation\n  takes the element with minimum priority.\n\n  The element with minimum priority is extracted from the\n  sum over all elements.\n  Deleting the element with minimum priority is done by\n  splitting the sequence at the point where the minimum priority\n  of the elements read so far becomes equal to the minimum priority of \n  all elements.\n*}\n\nsubsection \"Definitions\"\nsubsubsection \"Monoid\"\ndatatype ('e, 'a) Prio = Infty | Prio 'e 'a\n\nfun p_unwrap :: \"('e,'a) Prio \\<Rightarrow> ('e \\<times> 'a)\" where\n\"p_unwrap (Prio e a) = (e , a)\"\n\nfun p_min :: \"('e, 'a::linorder) Prio \\<Rightarrow> ('e, 'a) Prio \\<Rightarrow> ('e, 'a) Prio\"  where\n  \"p_min Infty Infty = Infty\"|\n  \"p_min Infty (Prio e a) = Prio e a\"|\n  \"p_min (Prio e a) Infty = Prio e a\"|\n  \"p_min (Prio e1 a) (Prio e2 b) = (if a \\<le> b then Prio e1 a else Prio e2 b)\"\n\n\nlemma p_min_re_neut[simp]: \"p_min a Infty = a\" by (induct a) auto\nlemma p_min_le_neut[simp]: \"p_min Infty a = a\" by (induct a) auto\nlemma p_min_asso: \"p_min (p_min a b) c = p_min a (p_min b c)\"\n  apply(induct a b  rule: p_min.induct )\n  apply auto \n  apply (induct c)\n  apply auto\n  apply (induct c)\n  apply auto\n  done\nlemma lp_mono: \"class.monoid_add p_min Infty\" \n  by unfold_locales (auto simp add: p_min_asso)\n\ninstantiation Prio :: (type,linorder) monoid_add\nbegin\ndefinition zero_def: \"0 == Infty\" \ndefinition plus_def: \"a+b == p_min a b\"\n  \ninstance by \n  intro_classes \n(auto simp add: p_min_asso zero_def plus_def)\nend\n\nfun p_less_eq :: \"('e, 'a::linorder) Prio \\<Rightarrow> ('e, 'a) Prio \\<Rightarrow> bool\" where\n  \"p_less_eq (Prio e a) (Prio f b) = (a \\<le> b)\"|\n  \"p_less_eq  _ Infty = True\"|\n  \"p_less_eq Infty (Prio e a) = False\"\n\nfun p_less :: \"('e, 'a::linorder) Prio \\<Rightarrow> ('e, 'a) Prio \\<Rightarrow> bool\" where\n  \"p_less (Prio e a) (Prio f b) = (a < b)\"|\n  \"p_less (Prio e a) Infty = True\"|\n  \"p_less Infty _ = False\"\n\nlemma p_less_le_not_le : \"p_less x y \\<longleftrightarrow> p_less_eq x y \\<and> \\<not> (p_less_eq y x)\"\n  by (induct x y rule: p_less.induct) auto\n\nlemma p_order_refl : \"p_less_eq x x\"\n  by (induct x) auto\n\nlemma p_le_inf : \"p_less_eq Infty x \\<Longrightarrow> x = Infty\"\n  by (induct x) auto\n\nlemma p_order_trans : \"\\<lbrakk>p_less_eq x y; p_less_eq y z\\<rbrakk> \\<Longrightarrow> p_less_eq x z\"\n  apply (induct y z rule: p_less.induct)\n  apply auto\n  apply (induct x)\n  apply auto\n  apply (cases x)\n  apply auto\n  apply(induct x)\n  apply (auto simp add: p_le_inf)\n  apply (metis p_le_inf p_less_eq.simps(2))\n  done\n\nlemma p_linear2 : \"p_less_eq x y \\<or> p_less_eq y x\"\n  apply (induct x y rule: p_less_eq.induct)\n  apply auto\n  done\n\ninstantiation Prio :: (type, linorder) preorder\nbegin\ndefinition plesseq_def: \"less_eq = p_less_eq\"\ndefinition pless_def: \"less = p_less\"\n\ninstance \n  apply (intro_classes)\n  apply (simp only: p_less_le_not_le pless_def plesseq_def)\n  apply (simp only: p_order_refl plesseq_def pless_def)\n  apply (simp only: plesseq_def)\n  apply (metis p_order_trans)\n  done\n\nend\n\n\nsubsubsection \"Operations\"\ndefinition alprio_\\<alpha> :: \"('s \\<Rightarrow> (unit \\<times> ('e,'a::linorder) Prio) list) \n  \\<Rightarrow> 's \\<Rightarrow> ('e \\<times> 'a::linorder) multiset\"\n  where \n  \"alprio_\\<alpha> \\<alpha> al == (multiset_of (map p_unwrap (map snd (\\<alpha> al))))\"\n\ndefinition alprio_invar :: \"('s \\<Rightarrow> (unit \\<times> ('c, 'd::linorder) Prio) list) \n  \\<Rightarrow> ('s \\<Rightarrow> bool) \\<Rightarrow> 's \\<Rightarrow> bool\" \n  where\n  \"alprio_invar \\<alpha> invar al == invar al \\<and> (\\<forall> x\\<in>set (\\<alpha> al). snd x\\<noteq>Infty)\"\n\ndefinition alprio_empty  where \n  \"alprio_empty empt = empt\"\n\ndefinition alprio_isEmpty  where \n  \"alprio_isEmpty isEmpty = isEmpty\"\n\ndefinition alprio_insert :: \"(unit \\<Rightarrow> ('e,'a) Prio \\<Rightarrow> 's \\<Rightarrow> 's) \n  \\<Rightarrow> 'e \\<Rightarrow> 'a::linorder \\<Rightarrow> 's  \\<Rightarrow> 's\"  \n  where\n  \"alprio_insert consl e a s = consl () (Prio e a) s\"\n\ndefinition alprio_find :: \"('s \\<Rightarrow> ('e,'a::linorder) Prio) \\<Rightarrow> 's \\<Rightarrow> ('e \\<times> 'a)\" \nwhere\n\"alprio_find annot s = p_unwrap (annot s)\"\n\ndefinition alprio_delete :: \"((('e,'a::linorder) Prio \\<Rightarrow> bool) \n  \\<Rightarrow> ('e,'a) Prio \\<Rightarrow> 's \\<Rightarrow> ('s \\<times> (unit \\<times> ('e,'a) Prio) \\<times> 's)) \n                      \\<Rightarrow> ('s \\<Rightarrow> ('e,'a) Prio) \\<Rightarrow> ('s \\<Rightarrow> 's \\<Rightarrow> 's) \\<Rightarrow> 's \\<Rightarrow> 's\" \n  where\n  \"alprio_delete splits annot app s = (let (l, _ , r) \n    = splits (\\<lambda> x. x\\<le>(annot s)) Infty s in app l r) \"\n\ndefinition alprio_meld where\n  \"alprio_meld app = app\"\n\nlemmas alprio_defs =\n  alprio_invar_def\n  alprio_\\<alpha>_def\n  alprio_empty_def\n  alprio_isEmpty_def\n  alprio_insert_def\n  alprio_find_def\n  alprio_delete_def\n  alprio_meld_def\n\nsubsection \"Correctness\"\n\nsubsubsection \"Auxiliary Lemmas\"\nlemma listsum_split: \"listsum (l @ (a::'a::monoid_add) # r) = (listsum l) + a + (listsum r)\"\n  by (induct l) (auto simp add: add.assoc)\n\n\nlemma p_linear: \"(x::('e, 'a::linorder) Prio) \\<le> y \\<or> y \\<le> x\"\n  by (unfold plesseq_def) (simp only: p_linear2)\n\n\nlemma p_min_mon: \"(x::(('e,'a::linorder) Prio)) \\<le> y \\<Longrightarrow> (z + x) \\<le> y\"\napply (unfold plus_def plesseq_def)\napply (induct x y rule: p_less_eq.induct)\napply (auto)\napply (induct z)\napply (auto)\ndone\n\nlemma p_min_mon2: \"p_less_eq x y \\<Longrightarrow> p_less_eq (p_min z x) y\"\napply (induct x y rule: p_less_eq.induct)\napply (auto)\napply (induct z)\napply (auto)\ndone\n\nlemma ls_min: \" \\<forall>x \\<in> set (xs:: ('e,'a::linorder) Prio list) . listsum xs \\<le> x\"\nproof (induct xs)\ncase Nil thus ?case by auto\nnext\ncase (Cons a ins) thus ?case\n  apply (auto simp add: plus_def plesseq_def)\n  apply (cases a)\n  apply auto\n  apply (cases \"listsum ins\")\n  apply auto\n  apply (case_tac x)\n  apply auto\n  apply (cases a)\n  apply auto\n  apply (cases \"listsum ins\")\n  apply auto\n  done\nqed    \n\nlemma infadd: \"x \\<noteq> Infty \\<Longrightarrow>x + y \\<noteq> Infty\"\napply (unfold plus_def)\napply (induct x y rule: p_min.induct)\napply auto\ndone\n\n\nlemma prio_selects_one: \"a+b = a \\<or> a+b=(b::('e,'a::linorder) Prio)\"\n  apply (simp add: plus_def)\n  apply (cases \"(a,b)\" rule: p_min.cases)\n  apply simp_all\n  done\n\n\nlemma listsum_in_set: \"(l::('x \\<times> ('e,'a::linorder) Prio) list)\\<noteq>[] \\<Longrightarrow> \n  listsum (map snd l) \\<in> set (map snd l)\"\n  apply (induct l)\n  apply simp\n  apply (case_tac l)\n  apply simp\n  using prio_selects_one\n  apply auto\n  apply force\n  apply force\n  done\n\nlemma p_unwrap_less_sum: \"snd (p_unwrap ((Prio e aa) + b)) \\<le> aa\"\n  apply (cases b)\n  apply (auto simp add: plus_def)\ndone\n\nlemma prio_add_alb: \"\\<not> b \\<le> (a::('e,'a::linorder)Prio)  \\<Longrightarrow> b + a = a\"\n  by (auto simp add: plus_def, cases \"(a,b)\" rule: p_min.cases) (auto simp add: plesseq_def)\n\nlemma prio_add_alb2: \" (a::('e,'a::linorder)Prio)  \\<le> a + b \\<Longrightarrow>  a + b = a\"\n  by (auto simp add: plus_def, cases \"(a,b)\" rule: p_min.cases) (auto simp add: plesseq_def)\n\nlemma prio_add_abc:\n  assumes \"(l::('e,'a::linorder)Prio) + a \\<le> c\" \n  and \"\\<not> l \\<le> c\"\n  shows  \"\\<not> l \\<le> a\"\nproof (rule ccontr)\n  assume \"\\<not> \\<not> l \\<le> a\"\n  with assms have \"l + a = l\"\n    apply (auto simp add: plus_def plesseq_def)\n    apply (cases \"(l,a)\" rule: p_less_eq.cases)\n    apply auto\n    done\n  with assms show False by simp\nqed\n\nlemma prio_add_abc2:\n  assumes \"(a::('e,'a::linorder)Prio) \\<le> a + b\" \n  shows \"a \\<le> b\"\nproof (rule ccontr)\n  assume ann: \"\\<not> a \\<le> b\"\n  hence \"a + b = b\" \n    apply (auto simp add: plus_def plesseq_def)\n    apply (cases \"(a,b)\" rule: p_min.cases)\n    apply auto\n    done\n  thus False using assms ann by simp\nqed\n\n\nsubsubsection \"Empty\"\nlemma alprio_empty_correct: \n  assumes \"al_empty \\<alpha> invar empt\"\n  shows \"prio_empty (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_empty empt)\"\nproof -\n  interpret al_empty \\<alpha> invar empt by fact\n  show ?thesis\n    apply (unfold_locales)\n    apply (unfold alprio_invar_def)\n    apply auto\n    apply (unfold alprio_empty_def)\n    apply (auto simp add: empty_correct)\n    apply (unfold alprio_\\<alpha>_def)\n    apply auto\n    apply (simp only: empty_correct)\n    done\nqed\n\n\nsubsubsection \"Is Empty\"\n\nlemma alprio_isEmpty_correct: \n  assumes \"al_isEmpty \\<alpha> invar isEmpty\"\n  shows \"prio_isEmpty (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_isEmpty isEmpty)\"\nproof -\n  interpret al_isEmpty \\<alpha> invar isEmpty by fact\n  show ?thesis by (unfold_locales) (auto simp add: alprio_defs isEmpty_correct)\nqed\n\n\nsubsubsection \"Insert\"\nlemma alprio_insert_correct: \n  assumes \"al_consl \\<alpha> invar consl\"\n  shows \"prio_insert (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_insert consl)\"\nproof -\n  interpret al_consl \\<alpha> invar consl by fact\n  show ?thesis by unfold_locales (auto simp add: alprio_defs consl_correct)\nqed\n\n\nsubsubsection \"Meld\"\n\nlemma alprio_meld_correct: \n  assumes \"al_app \\<alpha> invar app\"\n  shows \"prio_meld (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_meld app)\"\nproof -\n  interpret al_app \\<alpha> invar app by fact\n  show ?thesis by unfold_locales (auto simp add: alprio_defs app_correct)\nqed\n\nsubsubsection \"Find\"\n\nlemma annot_not_inf :\n  assumes \"(alprio_invar \\<alpha> invar) s\" \n  and \"(alprio_\\<alpha> \\<alpha>) s \\<noteq> {#}\"\n  and \"al_annot \\<alpha> invar annot\"\n  shows \"annot s \\<noteq> Infty\"\nproof -\n  interpret al_annot \\<alpha> invar annot by fact\n  show ?thesis\n  proof -\n    from assms(1) have invs: \"invar s\" by (simp add: alprio_defs)\n    from assms(2) have sne: \"set (\\<alpha> s) \\<noteq> {}\"\n    proof (cases \"set (\\<alpha> s) = {}\")\n      case True \n      hence \"\\<alpha> s = []\" by simp\n      hence \"(alprio_\\<alpha> \\<alpha>) s = {#}\" by (simp add: alprio_defs)\n      from this assms(2) show ?thesis by simp\n    next\n      case False thus ?thesis by simp\n    qed\n    hence \"(\\<alpha> s) \\<noteq> []\" by simp\n    hence \" \\<exists>x xs. (\\<alpha> s) = x # xs\" by (cases \"\\<alpha> s\") auto\n    from this obtain x xs where [simp]: \"(\\<alpha> s) = x # xs\" by blast\n    from this assms(1) have \"snd x \\<noteq> Infty\" by (auto simp add: alprio_defs)\n    hence \"listsum (map snd (\\<alpha> s)) \\<noteq> Infty\" by (auto simp add: infadd)\n    thus \"annot s \\<noteq> Infty\" using annot_correct invs by simp\n  qed\nqed\n\nlemma annot_in_set: \n  assumes \"(alprio_invar \\<alpha> invar) s\" \n  and \"(alprio_\\<alpha> \\<alpha>) s \\<noteq> {#}\"\n  and \"al_annot \\<alpha> invar annot\"\n  shows \"p_unwrap (annot s) \\<in># ((alprio_\\<alpha> \\<alpha>) s)\"         \nproof - \n  interpret al_annot \\<alpha> invar annot by fact\n  from assms(2) have snn: \"\\<alpha> s \\<noteq> []\" by (auto simp add: alprio_defs)\n  from assms(1) have invs: \"invar s\" by (simp add: alprio_defs)\n  hence ans: \"annot s = listsum (map snd (\\<alpha> s))\" by (simp add: annot_correct)\n  let ?P = \"map snd (\\<alpha> s)\"\n  have \"annot s \\<in> set ?P\"\n    by (unfold ans) (rule listsum_in_set[OF snn])\n  hence \"p_unwrap (annot s) \\<in> set (map p_unwrap ?P)\"\n    by (metis image_iff in_set_conv_decomp set_map split_list_last)\n  thus ?thesis\n    by (metis mem_set_multiset_eq alprio_\\<alpha>_def)\nqed\n\nlemma  listsum_less_elems: \"\\<forall>x\\<in>set xs. snd x \\<noteq> Infty \\<Longrightarrow>\n   \\<forall>y\\<in>set_of (multiset_of (map p_unwrap (map snd xs))).\n              snd (p_unwrap (listsum (map snd xs))) \\<le> snd y\"          \n    proof (induct xs)\n    case Nil thus ?case by simp\n    next\n    case (Cons a as) thus ?case\n      apply auto\n      apply (cases \"(snd a)\" rule: p_unwrap.cases)\n      apply auto\n      apply (cases \"listsum (map snd as)\")\n      apply auto\n      apply (metis linorder_linear p_min_re_neut \n        p_unwrap.simps plus_def [abs_def] snd_eqD)\n      apply (auto simp add: p_unwrap_less_sum)\n      apply (unfold plus_def)\n      apply (cases \"(snd a, listsum (map snd as))\" rule: p_min.cases)\n      apply auto\n      apply (cases \"map snd as\")\n      apply (auto simp add: infadd)\n      done\nqed  \n  \nlemma alprio_find_correct: \n  assumes  \"al_annot \\<alpha> invar annot\"\n  shows \"prio_find (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_find annot)\"\nproof -\n  interpret al_annot \\<alpha> invar annot by fact\n  show ?thesis\n    apply unfold_locales\n    apply (rule conjI)\n    apply (insert assms)\n    apply (unfold alprio_find_def)\n    apply (simp add:annot_in_set)\n    apply (unfold alprio_defs)\n    apply (simp add: annot_correct)\n    apply (auto simp add: listsum_less_elems)\n    done\nqed\n\n\nsubsubsection \"Delete\"\n\nlemma delpred_mon: \n  \"\\<forall>(a:: ('e, 'a::linorder) Prio) b. ((\\<lambda> x. x \\<le> y) a \n    \\<longrightarrow> (\\<lambda> x. x \\<le> y) (a + b)) \"\nproof (intro impI allI) \n  fix a b \n  show \"a \\<le> y \\<Longrightarrow> a + b \\<le> y\"\n    apply (induct a b rule: p_less.induct)\n    apply (auto simp add: p_less_eq_def plus_def)\n    apply (metis linorder_linear order_trans \n      p_linear p_min.simps(4) p_min_mon plus_def prio_selects_one)\n    apply (metis order_trans p_linear p_min_mon p_min_re_neut plus_def)\n    done \nqed\n\n(* alprio_delete erhält die Invariante *)\nlemma alpriodel_invar: \n  assumes \"alprio_invar \\<alpha> invar s\"\n  and \"al_annot \\<alpha> invar annot\"\n  and \"alprio_\\<alpha> \\<alpha> s \\<noteq> {#}\"\n  and \"al_splits \\<alpha> invar splits\"\n  and \"al_app \\<alpha> invar app\"\n  shows \"alprio_invar \\<alpha> invar (alprio_delete splits annot app s)\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  let ?P = \"\\<lambda>x. x \\<le> annot s\"\n  obtain l p r where \n    [simp]:\"splits ?P Infty s = (l, p, r)\" \n    by (cases \"splits ?P Infty s\")  auto\n  obtain e a where \n    \"p = (e, a)\" \n    by (cases p, blast)\n  hence \n    lear:\"splits ?P Infty s = (l, (e,a), r)\" \n    by simp\n  from annot_not_inf[OF assms(1) assms(3) assms(2)] have \n    \"annot s \\<noteq> Infty\" .\n  hence \n    sv1: \"\\<not> Infty \\<le> annot s\" \n    by (simp add: plesseq_def, cases \"annot s\", auto)\n  from assms(1) have \n    invs: \"invar s\" \n    unfolding alprio_invar_def by simp\n  interpret al_annot \\<alpha> invar annot by fact\n  from invs have \n    sv2: \"Infty + listsum (map snd (\\<alpha> s)) \\<le> annot s\" \n    by (auto simp add: annot_correct plus_def \n      plesseq_def p_min_le_neut p_order_refl)\n  note sp = splits_correct[of s \"?P\" Infty l e a r]\n  note dp = delpred_mon[of \"annot s\"]\n  from sp[OF invs dp sv1 sv2 lear] have \n    invlr: \"invar l \\<and> invar r\" and \n    alr: \"\\<alpha> s = \\<alpha> l @ (e, a) # \\<alpha> r\" \n    by auto\n  interpret al_app \\<alpha> invar app by fact\n  from invlr app_correct have \n    invapplr: \"invar (app l r)\" \n    by simp\n  from invlr app_correct have \n    sr: \"\\<alpha> (app l r) = (\\<alpha> l) @ (\\<alpha> r)\" \n    by simp\n  from alr have  \n    \"set (\\<alpha> s) \\<supseteq> (set (\\<alpha> l) Un set (\\<alpha> r))\" \n    by auto\n  with app_correct[of l r] invlr have \n    \"set (\\<alpha> s) \\<supseteq> set (\\<alpha> (app l r))\" by auto\n  with invapplr assms(1) \n  show ?thesis \n    unfolding alprio_defs by auto\nqed\n\n\nlemma listsum_elem:\n  assumes \" ins = l @ (a::('e,'a::linorder)Prio) # r\"  \n  and \"\\<not> listsum l \\<le> listsum ins\"  \n  and \"listsum l + a \\<le> listsum ins \"\n  shows \" a = listsum ins\"\nproof -\n  have \"\\<not> listsum l \\<le> a\" using assms prio_add_abc by simp\n  hence lpa: \"listsum l + a = a\" using prio_add_alb by auto\n  hence als: \"a \\<le> listsum ins\" using assms(3) by simp\n  have \"listsum ins = a + listsum r\" \n    using lpa listsum_split[of l a r] assms(1) by auto\n  thus ?thesis using prio_add_alb2[of a \"listsum r\"] prio_add_abc2 als  \n    by auto\nqed\n\nlemma alpriodel_right:\n  assumes \"alprio_invar \\<alpha> invar s\"\n  and \"al_annot \\<alpha> invar annot\"\n  and \"alprio_\\<alpha> \\<alpha> s \\<noteq> {#}\"\n  and \"al_splits \\<alpha> invar splits\"\n  and \"al_app \\<alpha> invar app\"\n  shows \"alprio_\\<alpha> \\<alpha> (alprio_delete splits annot app s) = \n          alprio_\\<alpha> \\<alpha> s - {#p_unwrap (annot s)#}\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  let ?P = \"\\<lambda>x. x \\<le> annot s\"\n  obtain l p r where \n    [simp]:\"splits ?P Infty s = (l, p, r)\" \n    by (cases \"splits ?P Infty s\")  auto\n  obtain e a where \n    \"p = (e, a)\" \n    by (cases p, blast)\n  hence \n    lear:\"splits ?P Infty s = (l, (e,a), r)\" \n    by simp\n  from annot_not_inf[OF assms(1) assms(3) assms(2)] have \n    \"annot s \\<noteq> Infty\" .\n  hence \n    sv1: \"\\<not> Infty \\<le> annot s\" \n    by (simp add: plesseq_def, cases \"annot s\", auto)\n  from assms(1) have \n    invs: \"invar s\" \n    unfolding alprio_invar_def by simp\n  interpret al_annot \\<alpha> invar annot by fact\n  from invs have \n    sv2: \"Infty + listsum (map snd (\\<alpha> s)) \\<le> annot s\" \n    by (auto simp add: annot_correct plus_def \n      plesseq_def p_min_le_neut p_order_refl)\n  note sp = splits_correct[of s \"?P\" Infty l e a r]\n  note dp = delpred_mon[of \"annot s\"]\n  \n  from sp[OF invs dp sv1 sv2 lear] have \n    invlr: \"invar l \\<and> invar r\" and \n    alr: \"\\<alpha> s = \\<alpha> l @ (e, a) # \\<alpha> r\" and\n    anlel: \"\\<not> listsum (map snd (\\<alpha> l)) \\<le> annot s\" and \n    aneqa: \"(listsum (map snd (\\<alpha> l)) + a) \\<le> annot s\"\n    by (auto simp add: plus_def zero_def)\n  have mapalr: \"map snd (\\<alpha> s) = (map snd (\\<alpha> l)) @ a # (map snd (\\<alpha> r))\" \n    using alr by simp\n  note lsa = listsum_elem[of \"map snd (\\<alpha> s)\" \"map snd (\\<alpha> l)\" a \"map snd (\\<alpha> r)\"]\n  note lsa2 = lsa[OF mapalr]\n  hence a_is_annot: \"a = annot s\" \n    using annot_correct[OF invs] anlel aneqa by auto\n  have \"map p_unwrap (map snd (\\<alpha> s)) = \n    (map p_unwrap (map snd (\\<alpha> l))) @ (p_unwrap a) \n      # (map p_unwrap (map snd (\\<alpha> r)))\" \n    using alr by simp\n  hence alpriolst: \"(alprio_\\<alpha> \\<alpha> s) = (alprio_\\<alpha> \\<alpha> l) +{# p_unwrap a #}+ (alprio_\\<alpha> \\<alpha> r)\" \n    unfolding alprio_defs\n    by (simp add: algebra_simps)\n  interpret al_app \\<alpha> invar app by fact\n  from alpriolst show ?thesis using app_correct[of l r] invlr a_is_annot \n    by (auto simp add: alprio_defs algebra_simps)\nqed  \n\nlemma alprio_delete_correct: \n  assumes \"al_annot \\<alpha> invar annot\"\n  and \"al_splits \\<alpha> invar splits\"\n  and \"al_app \\<alpha> invar app\"\n  shows \"prio_delete (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) \n           (alprio_find annot) (alprio_delete splits annot app)\"\nproof-\n  interpret al_annot \\<alpha> invar annot by fact\n  interpret al_splits \\<alpha> invar splits by fact\n  interpret al_app \\<alpha> invar app by fact\n  show ?thesis\n    apply intro_locales\n    apply (rule alprio_find_correct,simp add: assms) \n    apply unfold_locales\n    apply (insert assms)\n    apply (simp add: alpriodel_invar)\n    apply (simp add: alpriodel_right alprio_find_def)   \n    done\nqed  \n\nlemmas alprio_correct =\n  alprio_empty_correct\n  alprio_isEmpty_correct\n  alprio_insert_correct\n  alprio_delete_correct\n  alprio_find_correct\n  alprio_meld_correct\n\nlocale alprio_defs = StdALDefs ops \n  for ops :: \"(unit,('e,'a::linorder) Prio,'s) alist_ops\"\nbegin\n  definition [icf_rec_def]: \"alprio_ops \\<equiv> \\<lparr>\n    prio_op_\\<alpha> = alprio_\\<alpha> \\<alpha>,\n    prio_op_invar = alprio_invar \\<alpha> invar,\n    prio_op_empty = alprio_empty empty,\n    prio_op_isEmpty = alprio_isEmpty isEmpty,\n    prio_op_insert = alprio_insert consl,\n    prio_op_find = alprio_find annot,\n    prio_op_delete = alprio_delete splits annot app,\n    prio_op_meld = alprio_meld app\n    \\<rparr>\"\n  \nend\n\nlocale alprio = alprio_defs ops + StdAL ops \n  for ops :: \"(unit,('e,'a::linorder) Prio,'s) alist_ops\"\nbegin\n  lemma alprio_ops_impl: \"StdPrio alprio_ops\"\n    apply (rule StdPrio.intro)\n    apply (simp_all add: icf_rec_unf)\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    done\nend\n    \nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Collections/ICF/gen_algo/PrioByAnnotatedList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7880588878749489}}
{"text": "(*  \n    Title:      Linear_Maps.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n    Maintainer: Jose Divasón <jose.divasonm at unirioja.es>\n*)\n\nheader{*Linear Maps*}\n\ntheory Linear_Maps\nimports\n    Gauss_Jordan\nbegin\n\nsubsection{*Properties about ranks and linear maps*}\n\nlemma rank_matrix_dim_range:\nassumes lf: \"linear (op *s) (op *s) f\"\nshows \"rank (matrix f::'a::{field}^'cols::{mod_type}^'rows::{mod_type}) = vec.dim (range f)\"\nunfolding rank_col_rank[of \"matrix f\"] col_rank_def\nunfolding col_space_eq' using matrix_works[OF lf] by metis\n\ntext{*The following two lemmas are the demonstration of theorem 2.11 that appears the book \"Advanced Linear Algebra\" by Steven Roman.*}\n\nlemma linear_injective_rank_eq_ncols:\nassumes lf: \"linear (op *s) (op *s) f\"\nshows \"inj f \\<longleftrightarrow> rank (matrix f::'a::{field}^'cols::{mod_type}^'rows::{mod_type}) = ncols (matrix f)\"\nproof (rule)\ninterpret lf: linear \"(op *s)\" \"(op *s)\" f using lf by simp\nassume inj: \"inj f\"\nhence \"{x. f x = 0} = {0}\" using lf.linear_injective_ker_0 by blast\nhence \"vec.dim {x. f x = 0} = 0\" using vec.dim_zero_eq' by blast\nthus \"rank (matrix f) = ncols (matrix f)\" using vec.rank_nullity_theorem unfolding ncols_def\nusing rank_matrix_dim_range[OF lf]\nby (metis Generalizations.matrix_vector_mul lf plus_nat.add_0 vec.dim_univ_eq_dimension vec_dim_card)\nnext\nassume eq: \"rank (matrix f::'a::{field}^'cols::{mod_type}^'rows::{mod_type}) = ncols (matrix f)\"\nhave \"vec.dim {x. f x = 0} = 0\"  using vec.rank_nullity_theorem[of \"matrix f\"] \n   unfolding ncols_def\nusing rank_matrix_dim_range[OF lf] eq unfolding matrix_vector_mul[OF lf, symmetric] \n  by (metis add_implies_diff monoid_add_class.add.left_neutral ncols_def \n    vec.dim_univ_eq_dimension vec_dim_card)\nhence \"{x. f x = 0} = {0}\" using vec.dim_zero_eq linear.linear_0[OF lf] by auto\nthus \"inj f\" using vec.linear_injective_ker_0[of \"matrix f\"] \n  unfolding matrix_vector_mul[OF lf, symmetric] by simp\nqed\n\nlemma linear_surjective_rank_eq_ncols:\nassumes lf: \"linear (op *s) (op *s) f\"\nshows \"surj f \\<longleftrightarrow> rank (matrix f::'a::{field}^'cols::{mod_type}^'rows::{mod_type}) = nrows (matrix f)\"\nproof (rule)\nassume surj: \"surj f\"\nhave \"nrows (matrix f) = CARD ('rows)\" unfolding nrows_def ..\nalso have \"... = vec.dim (range f)\" by (metis surj vec_dim_card)\nalso have \"... = rank (matrix f)\" unfolding rank_matrix_dim_range[OF lf] ..\nfinally show \"rank (matrix f) = nrows (matrix f)\" ..\nnext\nassume \"rank (matrix f) = nrows (matrix f)\"\nhence \"vec.dim (range f) = CARD ('rows)\" unfolding rank_matrix_dim_range[OF lf] nrows_def .\nthus \"surj f\" \nusing vec.basis_exists vec.dim_UNIV vec.dim_subset_UNIV independent_is_basis is_basis_def lf \n  vec.subspace_UNIV vec.subspace_dim_equal vec.subspace_linear_image top_le \nby (metis (mono_tags, hide_lams) dimension_vector top_greatest)\nqed\n\nlemma linear_bij_rank_eq_ncols:\nfixes f::\"('a::{field}^'n::{mod_type})=>('a::{field}^'n::{mod_type})\"\nassumes lf: \"linear (op *s) (op *s) f\"\nshows \"bij f \\<longleftrightarrow> rank (matrix f) = ncols (matrix f)\" \nunfolding bij_def\nusing vec.linear_injective_imp_surjective[OF lf]\nusing vec.linear_surjective_imp_injective[OF lf]\nusing linear_injective_rank_eq_ncols[OF lf]\nby auto\n\n\nsubsection{*Invertible linear maps*}\n\ntext{*We could get rid of the property @{text \"linear (op *c) (op *b) g\"} using \n  @{thm \"finite_dimensional_vector_space.left_inverse_linear\"}*}\n\nlocale invertible_lf = linear + \n  assumes invertible_lf: \"(\\<exists>g. linear (op *c) (op *b) g \\<and> (g \\<circ> f = id) \\<and> (f \\<circ> g = id))\"\n\ncontext linear_between_finite_dimensional_vector_spaces\nbegin\n\nlemma invertible_lf_intro[intro]:\n  assumes \"(g \\<circ> f = id)\"  and \"(f \\<circ> g = id)\"\n  shows \"invertible_lf (op *b) (op *c) f\"\n  by (unfold_locales, metis assms(1) assms(2) inj_on_id inj_on_imageI2  left_right_inverse_eq linear_injective_left_inverse)\nend  \n\nlemma invertible_imp_bijective:\n  assumes \"invertible_lf scaleB scaleC f\"\n  shows \"bij f\" \n  using assms unfolding invertible_lf_def invertible_lf_axioms_def\n  by (metis  bij_betw_comp_iff bij_betw_imp_surj inj_on_imageI2 inj_on_imp_bij_betw inv_id surj_id surj_imp_inj_inv)\n\n\nlemma invertible_matrix_imp_invertible_lf:\n  fixes A::\"'a::{field}^'n^'n\"\n  assumes invertible_A: \"invertible A\"\n  shows \"invertible_lf (op *s) (op *s) (\\<lambda>x. A *v x)\"\nproof -\n  obtain B where AB: \"A**B=mat 1\" and BA: \"B**A=mat 1\" using invertible_A unfolding invertible_def by blast\n  show ?thesis \n  proof (rule vec.invertible_lf_intro [of \"(\\<lambda>x. B *v x)\"]) \n    show id1: \"op *v B \\<circ> op *v A = id\" by (metis (hide_lams, no_types) AB BA isomorphism_expand matrix_vector_mul_assoc matrix_vector_mul_lid) \n    show \"op *v A \\<circ> op *v B = id\" by (metis (hide_lams, no_types) AB BA isomorphism_expand matrix_vector_mul_assoc matrix_vector_mul_lid) \n  qed\nqed\n\nlemma invertible_lf_imp_invertible_matrix:\n  fixes f::\"'a::{field}^'n\\<Rightarrow>'a^'n\"\n  assumes invertible_f: \"invertible_lf (op *s) (op *s) f\"\n  shows \"invertible (matrix f)\" \nproof -\n  interpret i: invertible_lf \"(op *s)\" \"(op *s)\" f using invertible_f .\n  obtain g where linear_g: \"linear (op *s) (op *s)  g\" and gf: \"(g \\<circ> f = id)\" and fg: \"(f \\<circ> g = id)\"\n    by (metis invertible_f invertible_lf.invertible_lf)\n  show ?thesis proof (unfold invertible_def, rule exI[of _ \"matrix g\"], rule conjI)\n    show \"matrix f ** matrix g = mat 1\"\n      by (metis fg id_def vec.left_inverse_linear linear_g vec.linear_id matrix_compose \n          matrix_eq matrix_mul_rid matrix_vector_mul matrix_vector_mul_assoc)       \n    show \"matrix g ** matrix f = mat 1\"\n      by (metis `matrix f ** matrix g = mat 1` matrix_left_right_inverse)\n  qed\nqed\n\nlemma invertible_matrix_iff_invertible_lf:\n  fixes A::\"'a::{field}^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> invertible_lf (op *s) (op *s) (\\<lambda>x. A *v x)\" \n  by (metis invertible_lf_imp_invertible_matrix invertible_matrix_imp_invertible_lf matrix_of_matrix_vector_mul)\n\nlemma invertible_matrix_iff_invertible_lf':\n  fixes  f::\"'a::{field}^'n\\<Rightarrow>'a^'n\"\n  assumes linear_f: \"linear (op *s) (op *s) f\"\n  shows \"invertible (matrix f) \\<longleftrightarrow> invertible_lf (op *s) (op *s) f\"\n  by (metis (lifting) assms invertible_matrix_iff_invertible_lf matrix_vector_mul) \n\n\nlemma invertible_matrix_mult_right_rank:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\" \n    and Q::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\n  assumes invertible_Q: \"invertible Q\"\n  shows \"rank (A**Q) = rank A\"\nproof -\n  def TQ==\"(\\<lambda>x. Q *v x)\"\n  def TA\\<equiv>\"(\\<lambda>x. A *v x)\"\n  def TAQ==\"(\\<lambda>x. (A**Q) *v x)\"\n  have \"invertible_lf (op *s) (op *s) TQ\" using invertible_matrix_imp_invertible_lf[OF invertible_Q] unfolding TQ_def .\n  hence bij_TQ: \"bij TQ\" using invertible_imp_bijective by auto\n  have \"range TAQ = range (TA \\<circ> TQ)\" unfolding TQ_def TA_def TAQ_def o_def matrix_vector_mul_assoc ..\n  also have \"... = TA `(range TQ)\" unfolding fun.set_map ..\n  also have \"... = TA ` (UNIV)\" using bij_is_surj[OF bij_TQ] by simp\n  finally have \"range TAQ = range TA\" .\n  thus ?thesis unfolding rank_eq_dim_image using TAQ_def TA_def by auto\nqed\n\n\n\nlemma subspace_image_invertible_mat:\n  fixes P::\"'a::{field}^'m^'m\"\n  assumes inv_P: \"invertible P\"\n  and sub_W: \"vec.subspace W\"\n  shows \"vec.subspace ((\\<lambda>x. P *v x)` W)\"\n  by (metis (lifting) matrix_vector_mul_linear sub_W vec.subspace_linear_image)\n\n\n\n\n\nlemma invertible_matrix_mult_left_rank:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\" \n  and P::\"'a::{field}^'m::{mod_type}^'m::{mod_type}\"\n  assumes invertible_P: \"invertible P\"\n  shows \"rank (P**A) = rank A\"\nproof -\n  def TP==\"(\\<lambda>x. P *v x)\"\n  def TA\\<equiv>\"(\\<lambda>x. A *v x)\"\n  def TPA==\"(\\<lambda>x. (P**A) *v x)\"\n  have sub: \"vec.subspace (range (op *v A))\"\n    by (metis matrix_vector_mul_linear vec.subspace_UNIV vec.subspace_linear_image)\n  have \"vec.dim (range TPA) = vec.dim (range (TP \\<circ> TA))\" \n    unfolding TP_def TA_def TPA_def o_def matrix_vector_mul_assoc ..\n  also have \"... = vec.dim (range TA)\" using dim_image_invertible_mat[OF invertible_P sub] \n    unfolding TP_def TA_def o_def fun.set_map[symmetric] .\n  finally show ?thesis unfolding rank_eq_dim_image TPA_def TA_def . \nqed\n\ncorollary invertible_matrices_mult_rank:\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\" \n  and P::\"'a^'m::{mod_type}^'m::{mod_type}\" and Q::\"'a^'n::{mod_type}^'n::{mod_type}\"\n  assumes invertible_P: \"invertible P\" \n  and invertible_Q: \"invertible Q\"\n  shows \"rank (P**A**Q) = rank A\"\n  using invertible_matrix_mult_right_rank[OF invertible_Q] using invertible_matrix_mult_left_rank[OF invertible_P] by metis\n\n\nlemma invertible_matrix_mult_left_rank':\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\" and P::\"'a^'m::{mod_type}^'m::{mod_type}\"\n  assumes invertible_P: \"invertible P\" and B_eq_PA: \"B=P**A\"\n  shows \"rank B = rank A\"\nproof -\n  have \"rank B = rank (P**A)\" using B_eq_PA by auto\n  also have \"... = rank A\" using invertible_matrix_mult_left_rank[OF invertible_P] by auto\n  finally show ?thesis .\nqed\n\n\n\nlemma invertible_matrices_rank':\n  fixes A::\"'a::{field}^'n::{mod_type}^'m::{mod_type}\" \n  and P::\"'a^'m::{mod_type}^'m::{mod_type}\" and Q::\"'a^'n::{mod_type}^'n::{mod_type}\"\n  assumes invertible_P: \"invertible P\" and invertible_Q: \"invertible Q\" and B_eq_PA: \"B = P**A**Q\"\n  shows \"rank B = rank A\" by (metis B_eq_PA invertible_P invertible_Q invertible_matrices_mult_rank)\n\nsubsection{*Definition and properties of the set of a vector*}\n\ntext{*Some definitions:*}\n\ntext{*In the file @{text \"Generalizations.thy\"} there exists the following definition: \n  @{thm \"cart_basis_def\"}.*}\n  \ntext{*@{text \"cart_basis\"} returns a set which is a basis and it works properly in my development.\n  But in this file, I need to know the order of the elements of the basis, because is very important\n  for the coordenates of a vector and the matrices of change of bases. So, I have defined a new\n  @{text \"cart_basis'\"}, which will be a matrix. The columns of this matrix are the elements of\n  the basis.*}\n\ndefinition set_of_vector :: \"'a^'n \\<Rightarrow> 'a set\"\n  where \"set_of_vector A = {A $ i |i. i \\<in> UNIV}\"\n\ndefinition cart_basis' :: \" 'a::{field}^'n^'n\"\n  where \"cart_basis' = (\\<chi> i. axis i 1)\"\n\nlemma cart_basis_eq_set_of_vector_cart_basis': \n  \"cart_basis = set_of_vector (cart_basis')\"\n  unfolding cart_basis_def cart_basis'_def set_of_vector_def by auto\n\nlemma basis_image_linear:\n  fixes f::\"'b::{field}^'n => 'b^'n\"\n  assumes invertible_lf: \"invertible_lf (op *s) (op *s) f\"\n  and basis_X: \"is_basis (set_of_vector X)\"\n  shows \"is_basis (f` (set_of_vector X))\"\nproof (rule iffD1[OF independent_is_basis], rule conjI)\n    have \"card (f ` set_of_vector X) = card (set_of_vector X)\"\n    by (rule card_image[of f \"set_of_vector X\"], metis invertible_imp_bijective[OF invertible_lf] bij_def inj_eq inj_on_def)\n  also have \"... = card (UNIV::'n set)\" using basis_X unfolding independent_is_basis[symmetric] by auto\n  finally show \"card (f ` set_of_vector X) = card (UNIV::'n set)\" .\n  show \"vec.independent (f ` set_of_vector X)\"\n  proof (rule linear.independent_injective_image)\n    show \"linear (op *s) (op *s) f\" using invertible_lf unfolding invertible_lf_def by simp\n    show \"vec.independent (set_of_vector X)\" using basis_X unfolding is_basis_def by simp\n    show \"inj f\"  using invertible_imp_bijective[OF invertible_lf] unfolding bij_def by simp\n  qed\nqed\n\n\ntext{*Properties about @{thm \"cart_basis'_def\"}*}\n\nlemma set_of_vector_cart_basis': \n  shows \"(set_of_vector cart_basis') = {axis i 1 :: 'a::{field}^'n | i. i \\<in> (UNIV :: 'n set)}\"\n  unfolding set_of_vector_def cart_basis'_def by auto\n\nlemma cart_basis'_i: \"cart_basis' $ i = axis i 1\" unfolding cart_basis'_def by simp\n\nlemma finite_cart_basis':\n  shows \"finite (set_of_vector cart_basis')\"\nunfolding set_of_vector_def using finite_Atleast_Atmost_nat[of \"\\<lambda>i. (cart_basis'::'a^'n^'n) $ i\"] .\n\nlemma is_basis_cart_basis': \"is_basis (set_of_vector cart_basis')\"\n  unfolding cart_basis_eq_set_of_vector_cart_basis'[symmetric]\n  by (metis Miscellaneous.is_basis_def independent_cart_basis span_cart_basis)\n  \nlemma basis_expansion_cart_basis':\"setsum (\\<lambda>i. x$i *s cart_basis' $ i) UNIV = x\" \n  unfolding cart_basis'_def using basis_expansion by auto\n\nlemma basis_expansion_unique:\n  \"setsum (\\<lambda>i. f i *s axis (i::'n::finite) 1) UNIV = (x::('a::comm_ring_1) ^'n) <-> (\\<forall>i. f i = x$i)\"\nproof (auto simp add: basis_expansion)\n  fix i::\"'n\" \n  have univ_rw: \"UNIV = (UNIV - {i}) \\<union> {i}\" by fastforce\n  have \"(\\<Sum>x\\<in>UNIV. f x * axis x 1 $ i) = setsum (\\<lambda>x.  f x * axis x 1 $ i) (UNIV - {i} \\<union> {i})\" using univ_rw by simp\n  also have \"... = setsum (\\<lambda>x.  f x * axis x 1 $ i) (UNIV - {i}) +  setsum (\\<lambda>x.  f x * axis x 1 $ i) {i}\" by (rule setsum.union_disjoint, auto)\n  also have \"... = f i\" unfolding axis_def by auto\n  finally show \"f i = (\\<Sum>x\\<in>UNIV. f x * axis x 1 $ i)\" ..\nqed\n\n\nlemma basis_expansion_cart_basis'_unique: \"setsum (\\<lambda>i. f (cart_basis' $ i) *s cart_basis' $ i) UNIV = x <-> (\\<forall>i. f (cart_basis' $ i) = x$i)\"\n  using basis_expansion_unique unfolding cart_basis'_def\n  by (simp add: vec_eq_iff if_distrib cong del: if_weak_cong)\n\nlemma basis_expansion_cart_basis'_unique': \"setsum (\\<lambda>i. f i *s cart_basis' $ i) UNIV = x <-> (\\<forall>i. f i = x$i)\"\n  using basis_expansion_unique unfolding cart_basis'_def\n  by (simp add: vec_eq_iff if_distrib cong del: if_weak_cong)\n\ntext{*Properties of @{thm \"is_basis_def\"}.*}\n\nlemma setsum_basis_eq:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes is_basis:\"is_basis  (set_of_vector X)\"\n  shows \"setsum (\\<lambda>x. f x *s x) (set_of_vector X) = setsum (\\<lambda>i. f (X$i) *s (X$i)) UNIV\" find_theorems \"_ \\<Longrightarrow> setsum ?a ?B = setsum ?b ?c\"\nproof -\nhave card_set_of_vector:\"card(set_of_vector X) = CARD('n)\" \n  using independent_is_basis[of \"set_of_vector X\"] using is_basis by auto\nhave fact_1: \"set_of_vector X = range (op $ X)\" unfolding set_of_vector_def by auto\nhave inj: \"inj (op $ X)\"\n  proof (rule eq_card_imp_inj_on) \n    show \"finite (UNIV::'n set)\" using finite_class.finite_UNIV .\n    show \"card (range (op $ X)) = card (UNIV::'n set)\" \n      using card_set_of_vector using fact_1 unfolding set_of_vector_def by simp\n  qed\nshow ?thesis using setsum.reindex[OF inj, of \"(\\<lambda>x. f x *s x)\", unfolded o_def] unfolding fact_1 .\nqed\n\ncorollary setsum_basis_eq2:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes is_basis:\"is_basis  (set_of_vector X)\"\n  shows \"setsum (\\<lambda>x. f x *s x) (set_of_vector X) = setsum (\\<lambda>i. (f \\<circ> op $ X) i *s (X$i)) UNIV\" \n  using setsum_basis_eq[OF is_basis] by simp\n\nlemma inj_op_nth:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes is_basis: \"is_basis (set_of_vector X)\"\n  shows \"inj (op $ X)\"\nproof -\n  have fact_1: \"set_of_vector X = range (op $ X)\" unfolding set_of_vector_def by auto\n  have card_set_of_vector:\"card(set_of_vector X) = CARD('n)\" using independent_is_basis[of \"set_of_vector X\"] using is_basis by auto\n  show \"inj (op $ X)\"\n  proof (rule eq_card_imp_inj_on) \n    show \"finite (UNIV::'n set)\" using finite_class.finite_UNIV .\n    show \"card (range (op $ X)) = card (UNIV::'n set)\" using card_set_of_vector using fact_1 unfolding set_of_vector_def by simp\n  qed\nqed\n\nlemma basis_UNIV: \n  fixes X::\"'a::{field}^'n^'n\"\n  assumes is_basis: \"is_basis (set_of_vector X)\"\n  shows \"UNIV = {x. \\<exists>g. (\\<Sum>i\\<in>UNIV. g i *s X$i) = x}\"\nproof -\n  have \"UNIV = {x. \\<exists>g. (\\<Sum>i\\<in>(set_of_vector X). g i *s i) = x}\"\n    using is_basis unfolding is_basis_def\n    using vec.span_finite[OF basis_finite[OF is_basis]] by auto\n  also have \"... \\<subseteq> {x. \\<exists>g. (\\<Sum>i\\<in>UNIV. g i *s X$i) = x}\"\n  proof (clarify)\n    fix f\n    show \"\\<exists>g. (\\<Sum>i\\<in>UNIV. g i *s X $ i) = (\\<Sum>i\\<in>set_of_vector X. f i *s i)\"\n    proof (rule exI[of _ \"(\\<lambda>i. (f \\<circ> op $ X) i)\"], unfold o_def)\n      have fact_1: \"set_of_vector X = range (op $ X)\" unfolding set_of_vector_def by auto\n      have card_set_of_vector:\"card(set_of_vector X) = CARD('n)\" using independent_is_basis[of \"set_of_vector X\"] using is_basis by auto\n      have inj: \"inj (op $ X)\" using inj_op_nth[OF is_basis] .\n      show \" (\\<Sum>i\\<in>UNIV. f (X $ i) *s X $ i) = (\\<Sum>i\\<in>set_of_vector X. f i *s i)\" \n        using setsum.reindex[symmetric, OF inj, of \"\\<lambda>i. f i *s i\"] unfolding fact_1 by simp\n    qed\n  qed\n  finally show ?thesis by auto\nqed\n\nlemma scalars_zero_if_basis:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes is_basis: \"is_basis (set_of_vector X)\" and setsum: \"(\\<Sum>i\\<in>(UNIV::'n set). f i *s X$i) = 0\"\n  shows \"\\<forall>i\\<in>(UNIV::'n set). f i = 0\" \nproof -\n  have ind_X: \"vec.independent (set_of_vector X)\" using is_basis unfolding is_basis_def by simp\n  have finite_X:\"finite (set_of_vector X)\" using basis_finite[OF is_basis] .\n  have 1: \"(\\<forall>g. (\\<Sum>v\\<in>(set_of_vector X). g v *s v) = 0 \\<longrightarrow> (\\<forall>v\\<in>(set_of_vector X). g v = 0))\"\n    using ind_X unfolding vec.independent_explicit using finite_X by auto\n  def g\\<equiv>\"\\<lambda>v. f (THE i. X $ i = v)\"\n  have \"(\\<Sum>v\\<in>(set_of_vector X). g v *s v) = 0\"\n  proof -\n    have \"(\\<Sum>v\\<in>(set_of_vector X). g v *s v)  = (\\<Sum>i\\<in>(UNIV::'n set). f i *s X$i)\"\n    proof -\n      have inj: \"inj (op $ X)\" using inj_op_nth[OF is_basis] .\n      have rw: \"set_of_vector X = range (op $ X)\" unfolding set_of_vector_def by auto\n      {\n        fix a\n        have \"f a = g (X $ a)\"\n          unfolding g_def using inj_op_nth[OF is_basis]\n          by (metis (lifting, mono_tags) injD the_equality) \n       }\n      thus ?thesis using setsum.reindex[OF inj, of \"\\<lambda>v. g v *s v\"] unfolding rw o_def by auto\n    qed\n    thus ?thesis unfolding setsum .\n  qed\n  hence 2: \"\\<forall>v\\<in>(set_of_vector X). g v = 0\" using 1 by auto\n  show ?thesis\n  proof (clarify)\n    fix a\n    have \"g (X$a) = 0\" using 2 unfolding set_of_vector_def by auto\n    thus \"f a = 0\" unfolding g_def using inj_op_nth[OF is_basis]\n      by (metis (lifting, mono_tags) injD the_equality)\n  qed\nqed\n\nlemma basis_combination_unique:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and setsum_eq: \"(\\<Sum>i\\<in>UNIV. g i *s X$i) = (\\<Sum>i\\<in>UNIV. f i *s X$i)\"\n  shows \"f=g\"\nproof (rule ccontr)\n  assume \"f\\<noteq>g\"\n  from this obtain x where fx_gx: \"f x \\<noteq> g x\" by fast\n  have \"0=(\\<Sum>i\\<in>UNIV. g i *s X$i) - (\\<Sum>i\\<in>UNIV. f i *s X$i)\" using setsum_eq by simp\n  also have \"... = (\\<Sum>i\\<in>UNIV. g i *s X$i - f i *s X$i)\" unfolding setsum_subtractf[symmetric] ..\n  also have \"... = (\\<Sum>i\\<in>UNIV. (g i - f i) *s X$i)\"  by (rule setsum.cong, auto simp add: scaleR_diff_left) \n  also have \"... = (\\<Sum>i\\<in>UNIV. (g - f) i *s X$i)\" by simp\n  finally have setsum_eq_1: \"0 = (\\<Sum>i\\<in>UNIV. (g - f) i *s X$i)\" by simp\n  have \"\\<forall>i\\<in>UNIV. (g - f) i = 0\" by (rule scalars_zero_if_basis[OF basis_X setsum_eq_1[symmetric]])\n  hence \"(g - f) x = 0\" by simp\n  hence \"f x = g x\" by simp\n  thus False using fx_gx by contradiction\nqed\n\n\nsubsection{*Coordinates of a vector*}\n\ntext{*Definition and properties of the coordinates of a vector (in terms of a particular ordered basis).*}\n\ndefinition coord :: \"'a::{field}^'n^'n\\<Rightarrow>'a::{field}^'n\\<Rightarrow>'a::{field}^'n\"\nwhere \"coord X v = (\\<chi> i. (THE f. v = setsum (\\<lambda>x. f x *s X$x) UNIV) i)\"\n\ntext{*@{term \"coord X v\"} are the coordinates of vector @{term \"v\"} with respect to the basis @{term \"X\"}*}\n\nlemma bij_coord:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\"\n  shows \"bij (coord X)\"\nproof (unfold bij_def, auto)\n  show inj: \"inj (coord X)\"\n  proof (unfold inj_on_def, auto)\n    fix x y assume coord_eq: \"coord X x = coord X y\"\n    obtain f where f: \"(\\<Sum>x\\<in>UNIV. f x *s X $ x) = x\"  using basis_UNIV[OF basis_X] by blast\n    obtain g where g:  \"(\\<Sum>x\\<in>UNIV. g x *s X $ x) = y\" using basis_UNIV[OF basis_X] by blast    \n    have the_f: \"(THE f. x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) = f\"\n    proof (rule the_equality)\n      show \"x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)\" using f by simp\n      show \"\\<And>fa. x = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) \\<Longrightarrow> fa = f\" using basis_combination_unique[OF basis_X] f by simp\n    qed\n    have the_g: \"(THE g. y = (\\<Sum>x\\<in>UNIV. g x *s X $ x)) = g\"\n    proof (rule the_equality)\n      show \"y = (\\<Sum>x\\<in>UNIV. g x *s X $ x)\" using g by simp\n      show \"\\<And>ga. y = (\\<Sum>x\\<in>UNIV. ga x *s X $ x) \\<Longrightarrow> ga = g\" using basis_combination_unique[OF basis_X] g by simp\n    qed    \n    have \"(THE f. x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) = (THE g. y = (\\<Sum>x\\<in>UNIV. g x *s X $ x))\" \n      using coord_eq unfolding coord_def \n      using vec_lambda_inject[of \"(THE f. x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) \"  \"(THE f. y = (\\<Sum>x\\<in>UNIV. f x *s X $ x))\"]\n      by auto\n    hence \"f = g\" unfolding the_f the_g .\n    thus \"x=y\" using f g by simp\n  qed\nnext\n  fix x::\"('a, 'n) vec\"\n  show \"x \\<in> range (coord X)\"\n  proof (unfold image_def, auto, rule exI[of _ \"setsum (\\<lambda>i. x$i *s X$i) UNIV\"], unfold coord_def)\n    def f\\<equiv>\"\\<lambda>i. x$i\"\n    have the_f: \" (THE f. (\\<Sum>i\\<in>UNIV. x $ i *s X $ i) = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) = f\"\n    proof (rule the_equality)\n      show \"(\\<Sum>i\\<in>UNIV. x $ i *s X $ i) = (\\<Sum>x\\<in>UNIV. f x *s X $ x)\" unfolding f_def ..\n      fix g assume setsum_eq:\"(\\<Sum>i\\<in>UNIV. x $ i *s X $ i) = (\\<Sum>x\\<in>UNIV. g x *s X $ x)\"\n      show \"g = f\" using  basis_combination_unique[OF basis_X] using setsum_eq unfolding f_def by simp\n    qed\n    show \" x = vec_lambda (THE f. (\\<Sum>i\\<in>UNIV. x $ i *s X $ i) = (\\<Sum>x\\<in>UNIV. f x *s X $ x))\" unfolding the_f unfolding f_def using vec_lambda_eta[of x] by simp\n  qed\nqed\n\nlemma linear_coord:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\"\n  shows \"linear (op *s) (op *s) (coord X)\"\nproof (unfold linear_def additive_def linear_axioms_def coord_def, auto)\n  fix x y::\"('a, 'n) vec\" \n  show  \"vec_lambda (THE f. x + y = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) \n    = vec_lambda (THE f. x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) + vec_lambda (THE f. y = (\\<Sum>x\\<in>UNIV. f x *s X $ x))\"\n  proof -\n    obtain f where f: \"(\\<Sum>a\\<in>(UNIV::'n set). f a *s X $ a) = x + y\" using basis_UNIV[OF basis_X] by blast\n    obtain g where g: \" (\\<Sum>x\\<in>UNIV. g x *s X $ x) = x\" using basis_UNIV[OF basis_X] by blast\n    obtain h where h: \"(\\<Sum>x\\<in>UNIV. h x *s X $ x) = y\" using basis_UNIV[OF basis_X] by blast\n    def t\\<equiv>\"\\<lambda>i. g i + h i\"\n    have the_f: \"(THE f. x + y = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) = f\"\n    proof (rule the_equality)\n      show \" x + y = (\\<Sum>x\\<in>UNIV. f x *s X $ x)\" using f by simp\n      show \"\\<And>fa. x + y = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) \\<Longrightarrow> fa = f\" using basis_combination_unique[OF basis_X] f by simp\n    qed\n    have the_g: \"(THE g. x = (\\<Sum>x\\<in>UNIV. g x *s X $ x)) = g\"\n    proof (rule the_equality)\n      show \"x = (\\<Sum>x\\<in>UNIV. g x *s X $ x)\" using g by simp\n      show \"\\<And>ga. x = (\\<Sum>x\\<in>UNIV. ga x *s X $ x) \\<Longrightarrow> ga = g\"  using basis_combination_unique[OF basis_X] g by simp\n    qed\n    have the_h: \"(THE h. y = (\\<Sum>x\\<in>UNIV. h x *s X $ x)) = h\" \n    proof (rule the_equality)\n      show \"y = (\\<Sum>x\\<in>UNIV. h x *s X $ x)\" using h ..\n      show \"\\<And>ha. y = (\\<Sum>x\\<in>UNIV. ha x *s X $ x) \\<Longrightarrow> ha = h\"  using basis_combination_unique[OF basis_X] h by simp\n    qed    \n    have \"(\\<Sum>a\\<in>(UNIV::'n set). f a *s X $ a) =  (\\<Sum>x\\<in>UNIV. g x *s X $ x) + (\\<Sum>x\\<in>UNIV. h x *s X $ x)\" using f g h by simp\n    also have \"... = (\\<Sum>x\\<in>UNIV. g x *s X $ x + h x *s X $ x)\" unfolding setsum.distrib[symmetric] ..\n    also have \"... = (\\<Sum>x\\<in>UNIV. (g x + h x) *s X $ x)\" by (rule setsum.cong, auto simp add: scaleR_left_distrib)\n    also have \"... = (\\<Sum>x\\<in>UNIV. t x *s X $ x)\" unfolding t_def ..\n    finally have \"(\\<Sum>a\\<in>UNIV. f a *s X $ a) = (\\<Sum>x\\<in>UNIV. t x *s X $ x)\" .    \n    hence \"f=t\" using basis_combination_unique[OF basis_X] by auto\n    thus ?thesis\n      by (unfold the_f the_g the_h, vector, auto, unfold f g h t_def, simp)      \n  qed\nnext\n  fix c::'a and x::\"'a^'n\"\n  show \"vec_lambda (THE f. c *s x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) = c *s vec_lambda (THE f. x = (\\<Sum>x\\<in>UNIV. f x *s X $ x))\"\n  proof -\n    obtain f where f: \"(\\<Sum>x\\<in>UNIV. f x *s X $ x) = c *s x\" using basis_UNIV[OF basis_X] by blast\n    obtain g where g: \"(\\<Sum>x\\<in>UNIV. g x *s X $ x) = x\" using basis_UNIV[OF basis_X] by blast\n    def t\\<equiv>\"\\<lambda>i. c * g i\"\n    have the_f: \"(THE f. c *s x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)) = f\"\n    proof (rule the_equality)\n      show \" c *s x = (\\<Sum>x\\<in>UNIV. f x *s X $ x)\" using f ..\n      show \"\\<And>fa. c *s x = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) \\<Longrightarrow> fa = f\" using basis_combination_unique[OF basis_X] f by simp\n    qed\n    have the_g: \"(THE g. x = (\\<Sum>x\\<in>UNIV. g x *s X $ x)) = g\"proof (rule the_equality)\n      show \" x = (\\<Sum>x\\<in>UNIV. g x *s X $ x)\" using g ..\n      show \"\\<And>ga. x = (\\<Sum>x\\<in>UNIV. ga x *s X $ x) \\<Longrightarrow> ga = g\" using basis_combination_unique[OF basis_X] g by simp\n    qed    \n    have \"(\\<Sum>x\\<in>UNIV. f x *s X $ x) = c *s (\\<Sum>x\\<in>UNIV. g x *s X $ x)\" using f g by simp\n    also have \"... = (\\<Sum>x\\<in>UNIV. c *s (g x *s X $ x))\" by (rule vec.scale_setsum_right)\n    also have \"... =  (\\<Sum>x\\<in>UNIV. t x *s X $ x)\" unfolding t_def by simp\n    finally have \" (\\<Sum>x\\<in>UNIV. f x *s X $ x) = (\\<Sum>x\\<in>UNIV. t x *s X $ x)\" .\n    hence \"f=t\" using basis_combination_unique[OF basis_X] by auto    \n    thus ?thesis\n      by (unfold the_f the_g, vector, auto, unfold t_def, auto)    \n  qed\n  show \"vector_space op *s\" by unfold_locales\nqed\n\n\nlemma coord_eq:\n  assumes basis_X:\"is_basis (set_of_vector X)\"\n  and coord_eq: \"coord X v = coord X w\"\n  shows \"v = w\"\nproof -\n  have \"\\<forall>i. (THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) i = (THE f. \\<forall>i. w $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) i\"  using coord_eq\n    unfolding coord_eq coord_def vec_eq_iff by simp\n  hence the_eq: \"(THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) = (THE f. \\<forall>i. w $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i))\" by auto\n  obtain f where  f: \"(\\<Sum>x\\<in>UNIV. f x *s X $ x)= v\" using basis_UNIV[OF basis_X] by blast\n  obtain g where  g: \"(\\<Sum>x\\<in>UNIV. g x *s X $ x)= w\" using basis_UNIV[OF basis_X] by blast\n  have the_f: \"(THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) = f\"\n  proof (rule the_equality)\n    show \" \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)\" using f by auto\n    fix fa assume \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x * X $ x $ i)\"\n    hence \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) $ i\" unfolding setsum_component by simp\n    hence fa:\" v = (\\<Sum>x\\<in>UNIV. fa x *s X $ x)\"  unfolding vec_eq_iff .\n    show \"fa = f\" using basis_combination_unique[OF basis_X] f fa by simp\n  qed\n  have the_g: \"(THE g. \\<forall>i. w $ i = (\\<Sum>x\\<in>UNIV. g x * X $ x $ i)) = g\" \n  proof (rule the_equality)\n    show \" \\<forall>i. w $ i = (\\<Sum>x\\<in>UNIV. g x * X $ x $ i)\" using g by auto\n    fix fa assume \"\\<forall>i. w $ i = (\\<Sum>x\\<in>UNIV. fa x * X $ x $ i)\"\n    hence \"\\<forall>i. w $ i = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) $ i\" unfolding setsum_component by simp\n    hence fa:\" w = (\\<Sum>x\\<in>UNIV. fa x *s X $ x)\"  unfolding vec_eq_iff .\n    show \"fa = g\" using basis_combination_unique[OF basis_X] g fa by simp\n  qed\n  have \"f=g\" using the_eq unfolding the_f the_g .\n  thus \"v=w\" using f g by blast\nqed\n\n\nsubsection{*Matrix of change of basis and coordinate matrix of a linear map*}\n\ntext{*Definitions of matrix of change of basis and matrix of a linear transformation with respect to two bases:*}\n\ndefinition matrix_change_of_basis :: \"'a::{field}^'n^'n \\<Rightarrow>'a^'n^'n\\<Rightarrow>'a^'n^'n\"\n  where \"matrix_change_of_basis X Y = (\\<chi> i j. (coord Y (X$j)) $ i)\"\n\ntext{*There exists in the library the definition @{thm \"matrix_def\"}, which is the coordinate matrix of a linear map with respect to the standard bases.\n      Now we generalise that concept to the coordinate matrix of a linear map with respect to any two bases.*}\n\ndefinition matrix' :: \"'a::{field}^'n^'n \\<Rightarrow> 'a^'m^'m \\<Rightarrow> ('a^'n => 'a^'m) \\<Rightarrow> 'a^'n^'m\"\n  where \"matrix' X Y f= (\\<chi> i j. (coord Y (f(X$j))) $ i)\"\n\ntext{*Properties of @{thm \"matrix'_def\"}*}\n\nlemma matrix'_eq_matrix:\n  defines cart_basis_Rn: \"cart_basis_Rn == (cart_basis')::'a::{field}^'n^'n\" \n  and cart_basis_Rm:\"cart_basis_Rm == (cart_basis')::'a^'m^'m\"  \n  shows \"matrix' (cart_basis_Rn) (cart_basis_Rm) f = matrix f\"\nproof (unfold matrix_def matrix'_def coord_def, vector, auto)\n  fix i j\n  have basis_Rn:\"is_basis (set_of_vector cart_basis_Rn)\" using is_basis_cart_basis' unfolding cart_basis_Rn .  \n  have basis_Rm:\"is_basis (set_of_vector cart_basis_Rm)\" using is_basis_cart_basis' unfolding cart_basis_Rm .\n  obtain g where setsum_g: \"(\\<Sum>x\\<in>UNIV. g x *s (cart_basis_Rm $ x)) = f (cart_basis_Rn $ j)\" using basis_UNIV[OF basis_Rm] by blast  \n  have the_g: \"(THE g. \\<forall>a. f (cart_basis_Rn $ j) $ a = (\\<Sum>x\\<in>UNIV. g x * cart_basis_Rm $ x $ a)) = g\"\n  proof (rule the_equality, clarify)\n    fix a \n    have \"f (cart_basis_Rn $ j) $ a = (\\<Sum>i\\<in>UNIV. g i *s (cart_basis_Rm $ i)) $ a\" using setsum_g by simp\n    also have \"... = (\\<Sum>x\\<in>UNIV. g x * cart_basis_Rm $ x $ a)\" unfolding setsum_component by simp\n    finally show \"f (cart_basis_Rn $ j) $ a = (\\<Sum>x\\<in>UNIV. g x * cart_basis_Rm $ x $ a)\" .  \n    fix ga assume \"\\<forall>a. f (cart_basis_Rn $ j) $ a = (\\<Sum>x\\<in>UNIV. ga x * cart_basis_Rm $ x $ a)\"\n    hence setsum_ga: \"f (cart_basis_Rn $ j) = (\\<Sum>i\\<in>UNIV. ga i *s cart_basis_Rm $ i)\" by (vector, auto)\n    show \"ga = g\" \n    proof (rule basis_combination_unique)\n      show \"is_basis (set_of_vector (cart_basis_Rm))\" using basis_Rm .\n      show \" (\\<Sum>i\\<in>UNIV. g i *s cart_basis_Rm $ i) = (\\<Sum>i\\<in>UNIV. ga i *s cart_basis_Rm $ i)\" using setsum_g setsum_ga by simp\n    qed\n  qed\n  show \" (THE fa. \\<forall>i. f (cart_basis_Rn $ j) $ i = (\\<Sum>x\\<in>UNIV. fa x * cart_basis_Rm $ x $ i)) i = f (axis j 1) $ i\"\n    unfolding the_g using setsum_g unfolding cart_basis_Rm cart_basis_Rn cart_basis'_def   using basis_expansion_unique[of g \"f (axis j 1)\"]\n    unfolding scalar_mult_eq_scaleR by auto\nqed\n\nlemma matrix':\n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"f (X$i) = setsum (\\<lambda>j. (matrix' X Y f) $ j $ i *s (Y$j)) UNIV\" \nproof (unfold matrix'_def coord_def matrix_mult_vsum column_def, vector, auto)\n  fix j\n  obtain g where  g: \"(\\<Sum>x\\<in>UNIV. g x *s Y $ x) = f (X $ i)\" using basis_UNIV[OF basis_Y] by blast\n  have the_g: \"(THE fa. \\<forall>ia. f (X $ i) $ ia = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ ia)) = g\"\n  proof (rule the_equality, clarify)\n    fix a\n    have \"f (X $ i) $ a = (\\<Sum>x\\<in>UNIV. g x *s Y $ x) $ a\" using g by simp\n    also have \"... = (\\<Sum>x\\<in>UNIV. g x * Y $ x $ a)\" unfolding setsum_component by auto\n    finally show \"f (X $ i) $ a = (\\<Sum>x\\<in>UNIV. g x * Y $ x $ a)\" .\n    fix fa\n    assume  \"\\<forall>ia. f (X $ i) $ ia = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ ia)\" \n    hence \" \\<forall>ia. f (X $ i) $ ia =  (\\<Sum>x\\<in>UNIV. fa x *s Y $ x) $ ia\" unfolding setsum_component by simp\n    hence fa:\"f (X $ i) = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)\" unfolding vec_eq_iff .\n    show \"fa = g\" by (rule basis_combination_unique[OF basis_Y], simp add: fa g)\n  qed\n  show \" f (X $ i) $ j = (\\<Sum>x\\<in>UNIV. (THE fa. \\<forall>j. f (X $ i) $ j = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ j)) x * Y $ x $ j)\"\n    unfolding the_g unfolding g[symmetric] setsum_component by simp\nqed\n\n\ncorollary matrix'2:\n  assumes  basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  and eq_f: \"\\<forall>i. f (X$i) = setsum (\\<lambda>j. A $ j $ i *s (Y$j)) UNIV\"\n  shows \"matrix' X Y f = A\"\nproof -\n  have eq_f': \"\\<forall>i. f (X$i) = setsum (\\<lambda>j. (matrix' X Y f) $ j $ i *s (Y$j)) UNIV\" using matrix'[OF basis_X basis_Y] by auto\n  show ?thesis\n  proof (vector, auto)\n    fix i j\n    def a\\<equiv>\"\\<lambda>x. (matrix' X Y f) $ x $ i\"\n    def b\\<equiv>\"\\<lambda>x. A $ x $ i\"    \n    have  fxi_1:\"f (X$i) = setsum (\\<lambda>j. a j *s (Y$j)) UNIV\" using eq_f' unfolding a_def by simp\n    have  fxi_2: \"f (X$i) = setsum (\\<lambda>j. b j *s(Y$j)) UNIV\" using eq_f unfolding b_def by simp    \n    have \"a=b\" using basis_combination_unique[OF basis_Y] fxi_1 fxi_2  by auto    \n    thus \"(matrix' X Y f) $ j $ i = A $ j $ i\" unfolding a_def b_def by metis\n  qed\nqed\n\ntext{*This is the theorem 2.14 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\nlemma coord_matrix':\n  fixes X::\"'a::{field}^'n^'n\" and Y::\"'a^'m^'m\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  and linear_f: \"linear (op *s) (op *s) f\"\n  shows \"coord Y (f v) = (matrix' X Y f) *v (coord X v)\"  \nproof (unfold matrix_mult_vsum matrix'_def column_def coord_def, vector, auto)\n  fix i \n  obtain g where g: \"(\\<Sum>x\\<in>UNIV. g x *s Y $ x) = f v\" using basis_UNIV[OF basis_Y] by auto\n  obtain s where s: \"(\\<Sum>x\\<in>UNIV. s x *s X $ x) = v\" using basis_UNIV[OF basis_X] by auto\n  have the_g: \"(THE fa. \\<forall>a. f v $ a = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ a)) = g\"\n  proof (rule the_equality)\n    have \"\\<forall>a. f v $ a = (\\<Sum>x\\<in>UNIV. g x  *s Y $ x) $ a\" using g by simp\n    thus \" \\<forall>a. f v $ a = (\\<Sum>x\\<in>UNIV. g x * Y $ x $ a)\" unfolding setsum_component by simp\n    fix fa assume \" \\<forall>a. f v $ a = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ a)\" \n    hence  fa: \"f v = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)\" by (vector, auto)\n    show \"fa=g\" by (rule basis_combination_unique[OF basis_Y], simp add: fa g)\n  qed\n  have the_s: \"(THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i))=s\"\n  proof (rule the_equality)\n    have \" \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. s x *s X $ x) $ i\" using s by simp\n    thus \" \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. s x * X $ x $ i)\"unfolding setsum_component by simp\n    fix fa assume \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x * X $ x $ i)\"\n    hence fa: \"v=(\\<Sum>x\\<in>UNIV. fa x *s X $ x)\" by (vector, auto)\n    show \"fa=s\"by (rule basis_combination_unique[OF basis_X], simp add: fa s)\n  qed\n  def t\\<equiv>\"\\<lambda>x. (\\<Sum>i\\<in>UNIV. (s i * (THE fa. f (X $ i) = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)) x))\"\n  have \"(\\<Sum>x\\<in>UNIV. g x *s Y $ x) = f v\" using g by simp\n  also have \"... = f (\\<Sum>x\\<in>UNIV. s x *s X $ x)\" using s by simp\n  also have \"... = (\\<Sum>x\\<in>UNIV. s x *s f (X $ x))\" by (rule linear.linear_setsum_mul[OF linear_f], simp)\n  also have \"... = (\\<Sum>i\\<in>UNIV. s i *s setsum (\\<lambda>j. (matrix' X Y f)$j$i *s (Y$j)) UNIV)\" using matrix'[OF basis_X basis_Y] by auto\n  also have \"... =  (\\<Sum>i\\<in>UNIV. \\<Sum>x\\<in>UNIV. s i *s (matrix' X Y f $ x $ i *s Y $ x))\" unfolding vec.scale_setsum_right ..\n  also have \"... = (\\<Sum>i\\<in>UNIV. \\<Sum>x\\<in>UNIV. (s i * (THE fa. f (X $ i) = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)) x) *s Y $ x)\" unfolding matrix'_def unfolding coord_def by auto\n  also have \"... = (\\<Sum>x\\<in>UNIV. (\\<Sum>i\\<in>UNIV. (s i * (THE fa. f (X $ i) = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)) x) *s Y $ x))\"\n    by (rule setsum.commute)\n  also have \"... =  (\\<Sum>x\\<in>UNIV. (\\<Sum>i\\<in>UNIV. (s i * (THE fa. f (X $ i) = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)) x)) *s Y $ x)\" unfolding vec.scale_setsum_left ..\n  also have \"... =  (\\<Sum>x\\<in>UNIV. t x *s Y $ x)\" unfolding t_def ..\n  finally have \"(\\<Sum>x\\<in>UNIV. g x *s Y $ x) = (\\<Sum>x\\<in>UNIV. t x *s Y $ x)\" .  \n  hence \"g=t\" using basis_combination_unique[OF basis_Y] by simp\n  thus \"(THE fa. \\<forall>i. f v $ i = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ i)) i =\n    (\\<Sum>x\\<in>UNIV. (THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) x * (THE fa. \\<forall>i. f (X $ x) $ i = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ i)) i)\"\n  proof (unfold  the_g the_s t_def, auto)\n    have \" (\\<Sum>x\\<in>UNIV. s x * (THE fa. \\<forall>i. f (X $ x) $ i = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ i)) i) = \n      (\\<Sum>x\\<in>UNIV. s x * (THE fa. \\<forall>i. f (X $ x) $ i = (\\<Sum>x\\<in>UNIV. fa x  *s Y $ x) $ i) i)\" unfolding setsum_component by simp\n    also have \"... = (\\<Sum>x\\<in>UNIV. s x * (THE fa. f (X $ x) = (\\<Sum>x\\<in>UNIV. fa x  *s Y $ x)) i)\" by (rule setsum.cong, auto simp add: vec_eq_iff) \n    finally show \" (\\<Sum>ia\\<in>UNIV. s ia * (THE fa. f (X $ ia) = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)) i) = (\\<Sum>x\\<in>UNIV. s x * (THE fa. \\<forall>i. f (X $ x) $ i = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ i)) i)\"\n      by auto\n  qed\nqed\n\ntext{*This is the second part of the theorem 2.15 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\nlemma matrix'_compose:\n  fixes X::\"'a::{field}^'n^'n\" and Y::\"'a^'m^'m\" and Z::\"'a^'p^'p\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"  and basis_Z: \"is_basis (set_of_vector Z)\"\n  and linear_f: \"linear (op *s) (op *s) f\" and linear_g: \"linear (op *s) (op *s) g\"\n  shows \"matrix' X Z (g \\<circ> f) = (matrix' Y Z g) ** (matrix' X Y f)\"\nproof (unfold matrix_eq, clarify)\n  fix a::\"('a, 'n) vec\"\n  obtain v where v: \"a = coord X v\" using bij_coord[OF basis_X] unfolding bij_iff by metis\n  have linear_gf: \"linear (op *s) (op *s) (g \\<circ> f)\" using linear_compose[OF linear_f linear_g] .\n  have \"matrix' X Z (g \\<circ> f) *v a = matrix' X Z (g \\<circ> f) *v (coord X v)\" unfolding v ..\n  also have \"... = coord Z ((g \\<circ> f) v)\" unfolding coord_matrix'[OF basis_X basis_Z linear_gf, symmetric] ..\n  also have \"... = coord Z (g (f v))\" unfolding o_def ..\n  also have \"... = (matrix' Y Z g) *v (coord Y (f v))\" unfolding coord_matrix'[OF basis_Y basis_Z linear_g] ..\n  also have \"... = (matrix' Y Z g) *v ((matrix' X Y f) *v (coord X v))\" unfolding coord_matrix'[OF basis_X basis_Y linear_f] ..\n  also have \"... = ((matrix' Y Z g) ** (matrix' X Y f)) *v (coord X v)\" unfolding matrix_vector_mul_assoc ..\n  finally show \"matrix' X Z (g \\<circ> f) *v a = matrix' Y Z g ** matrix' X Y f *v a\" unfolding v .\nqed\n\n\nlemma exists_linear_eq_matrix':\n  fixes A::\"'a::{field}^'m^'n\" and X::\"'a^'m^'m\" and Y::\"'a^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"\\<exists>f. matrix' X Y f = A \\<and> linear (op *s) (op *s) f\" \nproof -\n  def f == \"\\<lambda>v. setsum (\\<lambda>j. A $ j $ (THE k. v = X $ k) *s Y $ j) UNIV\"\n  obtain g where linear_g: \"linear (op *s) (op *s) g\" and f_eq_g: \"(\\<forall>x \\<in> (set_of_vector X). g x = f x)\" \n    using vec.linear_independent_extend using basis_X unfolding is_basis_def by blast  \n  show ?thesis\n  proof (rule exI[of _ g], rule conjI)\n    show \"matrix' X Y g = A\"\n    proof (rule matrix'2)\n      show \"is_basis (set_of_vector X)\" using basis_X .\n      show \"is_basis (set_of_vector Y)\" using basis_Y .\n      show \"\\<forall>i. g (X $ i) = (\\<Sum>j\\<in>UNIV. A $ j $ i *s Y $ j)\" \n      proof (clarify)\n        fix i\n        have the_k_eq_i: \"(THE k. X $ i = X $ k) = i\"\n        proof (rule the_equality)\n          show \"X $ i = X $ i\" ..\n          fix k assume Xi_Xk: \"X $ i = X $ k\"  show \"k = i\" using Xi_Xk basis_X inj_eq inj_op_nth by metis\n        qed      \n        have Xi_in_X:\"X$i \\<in> (set_of_vector X)\" unfolding set_of_vector_def by auto\n        have \"g (X$i) = f (X$i)\" using f_eq_g Xi_in_X by simp\n        also have \"... = (\\<Sum>j\\<in>UNIV. A $ j $ (THE k. X $ i = X $ k) *s Y $ j)\" unfolding f_def ..\n        also have \"... = (\\<Sum>j\\<in>UNIV. A $ j $ i *s Y $ j)\" unfolding the_k_eq_i ..\n        finally show \"g (X $ i) = (\\<Sum>j\\<in>UNIV. A $ j $ i *s  Y $ j)\" .\n      qed\n    qed\n    show \"linear (op *s) (op *s) g\" using linear_g .\n  qed\nqed\n\n\nlemma matrix'_surj: \n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"surj (matrix' X Y)\"\nproof (unfold surj_def, clarify)\n  fix A\n  show \"\\<exists>f. A = matrix' X Y f\"\n    using exists_linear_eq_matrix'[OF basis_X basis_Y, of A] unfolding matrix'_def by auto\nqed\n\n\ntext{*Properties of @{thm \"matrix_change_of_basis_def\"}.*}\n\ntext{*This is the first part of the theorem 2.12 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\n\nlemma matrix_change_of_basis_works:\n  fixes X::\"'a::{field}^'n^'n\" and Y::\"'a^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" \n  and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"(matrix_change_of_basis X Y) *v (coord X v) = (coord Y v)\"\nproof (unfold matrix_mult_vsum matrix_change_of_basis_def column_def coord_def, vector, auto)\n  fix i\n  obtain f where f: \"(\\<Sum>x\\<in>UNIV. f x *s Y $ x) = v\" using basis_UNIV[OF basis_Y] by blast\n  obtain g where g: \"(\\<Sum>x\\<in>UNIV. g x *s X $ x) = v\" using basis_UNIV[OF basis_X] by blast\n  def t\\<equiv>\"\\<lambda>x. (THE f. X $ x= (\\<Sum>a\\<in>UNIV. f a *s Y $ a))\"\n  def w\\<equiv>\"\\<lambda>i. (\\<Sum>x\\<in>UNIV. g x * t x i)\"\n  have the_f:\"(THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * Y $ x $ i)) = f\"\n  proof (rule the_equality)\n    show \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * Y $ x $ i)\" using f by auto\n    fix fa assume \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x * Y $ x $ i)\"\n    hence \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x) $ i\" unfolding setsum_component by simp\n    hence fa: \" v = (\\<Sum>x\\<in>UNIV. fa x *s Y $ x)\" unfolding vec_eq_iff .\n    show \"fa = f\"\n      using basis_combination_unique[OF basis_Y] fa f by simp\n  qed\n  have the_g: \"(THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) = g\"\n  proof (rule the_equality)\n    show \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. g x * X $ x $ i)\" using g by auto\n    fix fa assume \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x * X $ x $ i)\"\n    hence \"\\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) $ i\" unfolding setsum_component by simp\n    hence fa: \" v = (\\<Sum>x\\<in>UNIV. fa x *s X $ x)\" unfolding vec_eq_iff .\n    show \"fa = g\"\n      using basis_combination_unique[OF basis_X] fa g by simp\n  qed  \n  have \"(\\<Sum>x\\<in>UNIV. f x *s Y $ x) = (\\<Sum>x\\<in>UNIV. g x *s X $ x)\" unfolding f g ..\n  also have \"... = (\\<Sum>x\\<in>UNIV. g x *s (setsum  (\\<lambda>i. (t x i) *s Y $ i) UNIV))\" unfolding t_def\n  proof (rule setsum.cong)\n    fix x\n    obtain h where h: \"(\\<Sum>a\\<in>UNIV. h a *s Y $ a) = X$x\" using basis_UNIV[OF basis_Y] by blast\n    have the_h: \"(THE f. X $ x = (\\<Sum>a\\<in>UNIV. f a *s Y $ a))=h\" \n    proof (rule the_equality)\n      show \" X $ x = (\\<Sum>a\\<in>UNIV. h a *s Y $ a)\" using h by simp\n      fix f assume f: \"X $ x = (\\<Sum>a\\<in>UNIV. f a *s Y $ a)\"\n      show \"f = h\" using basis_combination_unique[OF basis_Y] f h by simp\n    qed\n    show \" g x *s X $ x = g x *s (\\<Sum>i\\<in>UNIV. (THE f. X $ x = (\\<Sum>a\\<in>UNIV. f a *s Y $ a)) i *s Y $ i)\" unfolding the_h h ..\n  qed rule\n  also have \"... = (\\<Sum>x\\<in>UNIV. (setsum  (\\<lambda>i. g x *s ((t x i) *s Y $ i)) UNIV))\" unfolding vec.scale_setsum_right ..\n  also have \"... = (\\<Sum>i\\<in>UNIV. \\<Sum>x\\<in>UNIV. g x *s (t x i *s Y $ i))\" by (rule setsum.commute)\n  also have \"... =  (\\<Sum>i\\<in>UNIV. (\\<Sum>x\\<in>UNIV. g x * t x i) *s Y $ i)\" unfolding vec.scale_setsum_left by auto\n  finally have \"(\\<Sum>x\\<in>UNIV. f x *s Y $ x) = (\\<Sum>i\\<in>UNIV. (\\<Sum>x\\<in>UNIV. g x * t x i) *s Y $ i) \" .  \n  hence \"f=w\" using basis_combination_unique[OF basis_Y] unfolding w_def by auto  \n  thus \"(\\<Sum>x\\<in>UNIV. (THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) x * (THE f. \\<forall>i. X $ x $ i = (\\<Sum>x\\<in>UNIV. f x * Y $ x $ i)) i) =\n    (THE f. \\<forall>i. v $ i = (\\<Sum>x\\<in>UNIV. f x * Y $ x $ i)) i\" unfolding the_f the_g unfolding w_def t_def unfolding vec_eq_iff by auto\nqed\n\n\n\nlemma matrix_change_of_basis_mat_1:\n  fixes X::\"'a::{field}^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\"\n  shows \"matrix_change_of_basis X X = mat 1\"\nproof (unfold matrix_change_of_basis_def coord_def mat_def, vector, auto)\n  fix j::\"'n\" \n  def f\\<equiv>\"\\<lambda>i. if i=j then 1::'a else 0\"\n  have UNIV_rw: \"UNIV = insert j (UNIV-{j})\" by auto\n  have \"(\\<Sum>x\\<in>UNIV. f x *s X $ x) = (\\<Sum>x\\<in>(insert j (UNIV-{j})). f x *s X $ x)\" using UNIV_rw by simp\n  also have \"... = (\\<lambda>x. f x *s X $ x) j + (\\<Sum>x\\<in>(UNIV-{j}). f x *s X $ x)\" by (rule setsum.insert, simp+)\n  also have \"... = X$j + (\\<Sum>x\\<in>(UNIV-{j}). f x *s X $ x)\" unfolding f_def by simp\n  also have \"... = X$j + 0\" unfolding add_left_cancel f_def by (rule setsum.neutral, simp)\n  finally have f: \"(\\<Sum>x\\<in>UNIV. f x *s X $ x) = X$j\" by simp\n  have the_f: \"(THE f. \\<forall>i. X $ j $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) = f\"\n  proof (rule the_equality)\n    show \"\\<forall>i. X $ j $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)\"  using f unfolding vec_eq_iff unfolding setsum_component by simp\n    fix fa assume \"\\<forall>i. X $ j $ i = (\\<Sum>x\\<in>UNIV. fa x * X $ x $ i)\"\n    hence \"\\<forall>i. X $ j $ i = (\\<Sum>x\\<in>UNIV. fa x *s X $ x) $ i\" unfolding setsum_component by simp\n    hence fa: \"X $ j =  (\\<Sum>x\\<in>UNIV. fa x *s X $ x)\" unfolding vec_eq_iff .\n    show \"fa = f\" using basis_combination_unique[OF basis_X] fa f by simp\n  qed\n  show \"(THE f. \\<forall>i. X $ j $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) j = 1\" unfolding the_f f_def by simp\n  fix i assume i_not_j: \"i \\<noteq> j\"\n  show \"(THE f. \\<forall>i. X $ j $ i = (\\<Sum>x\\<in>UNIV. f x * X $ x $ i)) i = 0\" unfolding the_f f_def using i_not_j by simp\nqed\n\n\ntext{*Relationships between @{thm \"matrix'_def\"} and @{thm \"matrix_change_of_basis_def\"}.\n      This is the theorem 2.16 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\n\nlemma matrix'_matrix_change_of_basis:\n  fixes B::\"'a::{field}^'n^'n\" and B'::\"'a^'n^'n\" and C::\"'a^'m^'m\" and C'::\"'a^'m^'m\"\n  assumes basis_B: \"is_basis (set_of_vector B)\" and basis_B': \"is_basis (set_of_vector B')\"\n  and basis_C: \"is_basis (set_of_vector C)\" and basis_C': \"is_basis (set_of_vector C')\"\n  and linear_f: \"linear (op *s) (op *s) f\"\n  shows \"matrix' B' C' f = matrix_change_of_basis C C' ** matrix' B C f ** matrix_change_of_basis B' B\"\nproof (unfold matrix_eq, clarify)\n  fix x\n  obtain v where v: \"x=coord B' v\" using bij_coord[OF basis_B'] unfolding bij_iff by metis\n  have \"matrix_change_of_basis C C' ** matrix' B C f** matrix_change_of_basis B' B *v (coord B' v) \n    = matrix_change_of_basis C C' ** matrix' B C f *v (matrix_change_of_basis B' B *v (coord B' v)) \" unfolding matrix_vector_mul_assoc .. \n  also have \"... = matrix_change_of_basis C C' ** matrix' B C f *v (coord B v)\" unfolding matrix_change_of_basis_works[OF basis_B' basis_B] ..\n  also have \"... = matrix_change_of_basis C C' *v (matrix' B C f *v (coord B v))\" unfolding matrix_vector_mul_assoc ..\n  also have \"... = matrix_change_of_basis C C' *v (coord C (f v))\" unfolding coord_matrix'[OF basis_B basis_C linear_f] ..\n  also have \"... = coord C' (f v)\" unfolding matrix_change_of_basis_works[OF basis_C basis_C'] ..\n  also have \"... = matrix' B' C' f *v coord B' v\"  unfolding coord_matrix'[OF basis_B' basis_C' linear_f] ..\n  finally show \" matrix' B' C' f *v x = matrix_change_of_basis C C' ** matrix' B C f ** matrix_change_of_basis B' B *v x\" unfolding v ..\nqed\n\nlemma matrix'_id_eq_matrix_change_of_basis:\n  fixes X::\"'a::{field}^'n^'n\" and Y::\"'a^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"matrix' X Y (id) = matrix_change_of_basis X Y\"\n  unfolding matrix'_def matrix_change_of_basis_def unfolding id_def ..\n\ntext{*Relationships among @{thm \"invertible_lf_def\"}, @{thm \"matrix_change_of_basis_def\"}, @{thm \"matrix'_def\"} and @{thm \"invertible_def\"}.*}\n\ntext{*This is the second part of the theorem 2.12 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\n\nlemma matrix_inv_matrix_change_of_basis:\n  fixes X::\"'a::{field}^'n^'n\" and Y::\"'a^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows\"matrix_change_of_basis Y X = matrix_inv (matrix_change_of_basis X Y)\"\nproof (rule matrix_inv_unique[symmetric])\n  have linear_id: \"linear (op *s) (op *s) id\" by (metis vec.linear_id)  \n  have \"(matrix_change_of_basis Y X) ** (matrix_change_of_basis X Y) = (matrix' Y X id) ** (matrix' X Y id)\"\n    unfolding matrix'_id_eq_matrix_change_of_basis[OF basis_X basis_Y]\n    unfolding matrix'_id_eq_matrix_change_of_basis[OF basis_Y basis_X] ..\n  also have \"... = matrix' X X (id \\<circ> id)\" using matrix'_compose[OF basis_X basis_Y basis_X linear_id linear_id] ..\n  also have \"... = matrix_change_of_basis X X\" using  matrix'_id_eq_matrix_change_of_basis[OF basis_X basis_X] unfolding o_def id_def .\n  also have \"... = mat 1\" using matrix_change_of_basis_mat_1[OF basis_X] .\n  finally show \"matrix_change_of_basis Y X ** matrix_change_of_basis X Y = mat 1\" .  \n  have \"(matrix_change_of_basis X Y) ** (matrix_change_of_basis Y X) = (matrix' X Y id) ** (matrix' Y X id)\"\n    unfolding matrix'_id_eq_matrix_change_of_basis[OF basis_X basis_Y]\n    unfolding matrix'_id_eq_matrix_change_of_basis[OF basis_Y basis_X] ..\n  also have \"... = matrix' Y Y (id \\<circ> id)\" using matrix'_compose[OF basis_Y basis_X basis_Y linear_id linear_id] ..\n  also have \"... = matrix_change_of_basis Y Y\" using  matrix'_id_eq_matrix_change_of_basis[OF basis_Y basis_Y] unfolding o_def id_def .\n  also have \"... = mat 1\" using matrix_change_of_basis_mat_1[OF basis_Y] . \n  finally show \"matrix_change_of_basis X Y ** matrix_change_of_basis Y X = mat 1\" .\nqed\n\ntext{*The following four lemmas are the proof of the theorem 2.13 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\n\ncorollary invertible_matrix_change_of_basis:\n  fixes X::\"'a::{field}^'n^'n\" and Y::\"'a^'n^'n\"\n  assumes basis_X: \"is_basis (set_of_vector X)\" and  basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"invertible (matrix_change_of_basis X Y)\"\n  by (metis basis_X basis_Y invertible_left_inverse vec.linear_id \n    matrix'_id_eq_matrix_change_of_basis matrix'_matrix_change_of_basis \n    matrix_change_of_basis_mat_1)\n\nlemma invertible_lf_imp_invertible_matrix':\nfixes f:: \"'a::{field}^'b \\<Rightarrow> 'a^'b\"\nassumes \"invertible_lf (op *s) (op *s) f\" and basis_X: \"is_basis (set_of_vector X)\" and basis_Y: \"is_basis (set_of_vector Y)\"\nshows \"invertible (matrix' X Y f)\"\n  by (metis (lifting) assms(1) basis_X basis_Y invertible_lf_def invertible_lf_imp_invertible_matrix\n    invertible_matrix_change_of_basis invertible_mult is_basis_cart_basis' matrix'_eq_matrix matrix'_matrix_change_of_basis)\n\nlemma invertible_matrix'_imp_invertible_lf:\nfixes f:: \"'a::{field}^'b \\<Rightarrow> 'a^'b\"\n  assumes \"invertible (matrix' X Y f)\"  and basis_X: \"is_basis (set_of_vector X)\" \n  and linear_f: \"linear (op *s) (op *s) f\" and basis_Y: \"is_basis (set_of_vector Y)\"\n  shows \"invertible_lf (op *s) (op *s) f\"\n  unfolding invertible_matrix_iff_invertible_lf'[OF linear_f, symmetric]\n  by (metis assms(1) basis_X basis_Y id_o invertible_matrix_change_of_basis \n     invertible_mult is_basis_cart_basis' linear_f vec.linear_id \n    matrix'_compose matrix'_eq_matrix matrix'_id_eq_matrix_change_of_basis matrix'_matrix_change_of_basis)\n   \nlemma invertible_matrix_is_change_of_basis:\n  assumes invertible_P: \"invertible P\" and basis_X: \"is_basis (set_of_vector X)\" \n  shows \"\\<exists>!Y. matrix_change_of_basis Y X = P \\<and> is_basis (set_of_vector Y)\"\nproof (auto)\n  show \"\\<exists>Y. matrix_change_of_basis Y X = P \\<and> is_basis (set_of_vector Y)\"\n  proof -\n    fix i j\n    obtain f where P: \"P = matrix' X X f\" and linear_f: \"linear (op *s) (op *s) f\"\n      using exists_linear_eq_matrix'[OF basis_X basis_X, of P] by blast\n    show ?thesis    \n    proof (rule exI[of _ \"\\<chi> j. f (X$j)\"], rule conjI) \n      show \"matrix_change_of_basis (\\<chi> j. f (X $ j)) X = P\" unfolding matrix_change_of_basis_def P matrix'_def by vector\n      have invertible_f: \"invertible_lf (op *s) (op *s) f\" using invertible_matrix'_imp_invertible_lf[OF _ basis_X linear_f basis_X] using invertible_P unfolding P by simp\n      have rw: \"set_of_vector (\\<chi> j. f (X $ j)) = f`(set_of_vector X)\" unfolding set_of_vector_def by auto\n      show \"is_basis (set_of_vector (\\<chi> j. f (X $ j)))\" unfolding rw using basis_image_linear[OF invertible_f basis_X] .\n    qed\n  qed \n  fix Y Z\n  assume basis_Y:\"is_basis (set_of_vector Y)\" and eq: \"matrix_change_of_basis Z X = matrix_change_of_basis Y X\" and basis_Z: \"is_basis (set_of_vector Z)\"\n  have ZY_coord: \"\\<forall>i. coord X (Z$i) = coord X (Y$i)\" using eq unfolding matrix_change_of_basis_def unfolding vec_eq_iff by vector\n  show \"Y=Z\" by (vector, metis ZY_coord coord_eq[OF basis_X])\nqed\n\n\nsubsection{*Equivalent Matrices*}\n\ntext{*Next definition follows the one presented in Modern Algebra by Seth Warner.*}\n\ndefinition \"equivalent_matrices A B = (\\<exists>P Q. invertible P \\<and> invertible Q \\<and> B = (matrix_inv P)**A**Q)\"\n\nlemma exists_basis: \"\\<exists>X::'a::{field}^'n^'n. is_basis (set_of_vector X)\"\n  using is_basis_cart_basis' by auto\n\nlemma equivalent_implies_exist_matrix':\n  assumes equivalent: \"equivalent_matrices A B\"\n  shows \"\\<exists>X Y X' Y' f::'a::{field}^'n\\<Rightarrow>'a^'m. \n  linear (op *s) (op *s) f \\<and> matrix' X Y f = A \\<and> matrix' X' Y' f = B \\<and> is_basis (set_of_vector X) \n  \\<and> is_basis (set_of_vector Y) \\<and> is_basis (set_of_vector X') \\<and> is_basis (set_of_vector Y')\"\nproof -\n  obtain X::\"'a^'n^'n\" where X: \"is_basis (set_of_vector X)\" using exists_basis by blast\n  obtain Y::\"'a^'m^'m\" where Y: \"is_basis (set_of_vector Y)\" using exists_basis by blast\n  obtain P Q where B_PAQ: \"B=(matrix_inv P)**A**Q\" and inv_P: \"invertible P\" and inv_Q: \"invertible Q\" \n    using equivalent unfolding equivalent_matrices_def by auto\n  obtain f where f_A: \"matrix' X Y f = A\" and linear_f: \"linear (op *s) (op *s) f\" \n    using exists_linear_eq_matrix'[OF X Y] by auto   \n  obtain X'::\"'a^'n^'n\" where X': \"is_basis (set_of_vector X')\" and Q:\"matrix_change_of_basis X' X = Q\" \n    using invertible_matrix_is_change_of_basis[OF inv_Q X] by fast\n  obtain Y'::\"'a^'m^'m\" where Y': \"is_basis (set_of_vector Y')\" and P: \"matrix_change_of_basis Y' Y = P\" \n    using invertible_matrix_is_change_of_basis[OF inv_P Y] by fast\n  have matrix_inv_P: \"matrix_change_of_basis Y Y' = matrix_inv P\"\n    using matrix_inv_matrix_change_of_basis[OF Y' Y] P by simp\n  have \"matrix' X' Y' f = matrix_change_of_basis Y Y' ** matrix' X Y f ** matrix_change_of_basis X' X\" \n    using matrix'_matrix_change_of_basis[OF X X' Y Y' linear_f] .\n  also have \"... = (matrix_inv P) ** A ** Q\" unfolding matrix_inv_P f_A Q ..\n  also have \"... = B\" using B_PAQ ..\n  finally show ?thesis using f_A X X' Y Y' linear_f by fast\nqed\n\n\nlemma exist_matrix'_implies_equivalent:\n  assumes A: \"matrix' X Y f = A\"\n  and B: \"matrix' X' Y' f = B\"\n  and X: \"is_basis (set_of_vector X)\"\n  and Y: \"is_basis (set_of_vector Y)\" \n  and X': \"is_basis (set_of_vector X')\"\n  and Y': \"is_basis (set_of_vector Y')\"\n  and linear_f: \"linear (op *s) (op *s) f\"\n  shows \"equivalent_matrices A B\"\nproof (unfold equivalent_matrices_def, rule exI[of _ \"matrix_change_of_basis Y' Y\"], rule exI[of _ \"matrix_change_of_basis X' X\"], auto)\n  have inv: \"matrix_change_of_basis Y Y' = matrix_inv (matrix_change_of_basis Y' Y)\" using matrix_inv_matrix_change_of_basis[OF Y' Y] .\n  show \"invertible (matrix_change_of_basis Y' Y)\" using invertible_matrix_change_of_basis[OF Y' Y] .\n  show \"invertible (matrix_change_of_basis X' X)\" using invertible_matrix_change_of_basis[OF X' X] .\n  have \"B = matrix' X' Y' f\" using B ..\n  also have \"... =  matrix_change_of_basis Y Y' ** matrix' X Y f ** matrix_change_of_basis X' X\" using matrix'_matrix_change_of_basis[OF X X' Y Y' linear_f] .\n  finally show \"B = matrix_inv (matrix_change_of_basis Y' Y) ** A ** matrix_change_of_basis X' X\" unfolding inv unfolding A .\nqed\n\ntext{*This is the proof of the theorem 2.18 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\ncorollary equivalent_iff_exist_matrix':\n  shows \"equivalent_matrices A B \\<longleftrightarrow> (\\<exists>X Y X' Y' f::'a::{field}^'n\\<Rightarrow>'a^'m. \n  linear (op *s) (op *s) f \\<and> matrix' X Y f = A \\<and> matrix' X' Y' f = B \n  \\<and> is_basis (set_of_vector X) \\<and> is_basis (set_of_vector Y) \n  \\<and> is_basis (set_of_vector X') \\<and> is_basis (set_of_vector Y'))\"\n  by (rule, auto simp add: exist_matrix'_implies_equivalent equivalent_implies_exist_matrix')\n\n\nsubsection{*Similar matrices*}\n\ndefinition similar_matrices :: \"'a::{semiring_1}^'n^'n \\<Rightarrow> 'a::{semiring_1}^'n^'n \\<Rightarrow> bool\"\n  where \"similar_matrices A B = (\\<exists>P. invertible P \\<and> B=(matrix_inv P)**A**P)\"\n\nlemma similar_implies_exist_matrix':\n  fixes A B::\"'a::{field}^'n^'n\"\n  assumes similar: \"similar_matrices A B\"\n  shows \"\\<exists>X Y f. linear (op *s) (op *s) f \\<and> matrix' X X f = A \\<and> matrix' Y Y f = B \n    \\<and> is_basis (set_of_vector X) \\<and> is_basis (set_of_vector Y)\"\nproof -\n obtain P where inv_P: \"invertible P\" and B_PAP: \"B=(matrix_inv P)**A**P\" using similar unfolding similar_matrices_def by blast\n obtain X::\"'a^'n^'n\" where X: \"is_basis (set_of_vector X)\" using exists_basis by blast\n obtain f where linear_f: \"linear (op *s) (op *s) f\" and A: \"matrix' X X f = A\" using exists_linear_eq_matrix'[OF X X] by blast\n obtain Y::\"'a^'n^'n\" where Y: \"is_basis (set_of_vector Y)\" and P: \"P = matrix_change_of_basis Y X\"\n  using invertible_matrix_is_change_of_basis[OF inv_P X] by fast \n have P': \"matrix_inv P = matrix_change_of_basis X Y\" by (metis (lifting) P X Y matrix_inv_matrix_change_of_basis)\n have \"B = (matrix_inv P)**A**P\" using B_PAP .\n also have \"... =  matrix_change_of_basis X Y ** matrix' X X f ** P \" unfolding P' A ..\n also have \"... = matrix_change_of_basis X Y ** matrix' X X f ** matrix_change_of_basis Y X\" unfolding P ..\n also have \"... = matrix' Y Y f\" using matrix'_matrix_change_of_basis[OF X Y X Y linear_f] by simp\n finally show ?thesis using X Y A linear_f by fast\nqed\n\n\nlemma exist_matrix'_implies_similar:\n  fixes A B::\"'a::{field}^'n^'n\"\n  assumes linear_f: \"linear (op *s) (op *s) f\" and A: \"matrix' X X f = A\" and B: \"matrix' Y Y f = B\"\n  and X: \"is_basis (set_of_vector X)\" and Y: \"is_basis (set_of_vector Y)\"\n  shows \"similar_matrices A B\"\nproof (unfold similar_matrices_def, rule exI[of _ \"matrix_change_of_basis Y X\"], rule conjI)\n  have \"B=matrix' Y Y f\" using B ..\n  also have \"... = matrix_change_of_basis X Y ** matrix' X X f ** matrix_change_of_basis Y X\" using matrix'_matrix_change_of_basis[OF X Y X Y linear_f] by simp\n  also have \"... =  matrix_inv (matrix_change_of_basis Y X) ** A ** matrix_change_of_basis Y X\" unfolding A matrix_inv_matrix_change_of_basis[OF Y X] ..\n  finally show \"B = matrix_inv (matrix_change_of_basis Y X) ** A ** matrix_change_of_basis Y X\" .\n  show \"invertible (matrix_change_of_basis Y X)\" using invertible_matrix_change_of_basis[OF Y X] .\nqed\n\ntext{*This is the proof of the theorem 2.19 in the book \"Advanced Linear Algebra\" by Steven Roman.*}\ncorollary similar_iff_exist_matrix':\n  fixes A B::\"'a::{field}^'n^'n\"\n  shows \"similar_matrices A B \\<longleftrightarrow> (\\<exists>X Y f. linear (op *s) (op *s) f \\<and> matrix' X X f = A \n    \\<and> matrix' Y Y f = B \\<and> is_basis (set_of_vector X) \\<and> is_basis (set_of_vector Y))\"\n  by (rule, auto simp add: exist_matrix'_implies_similar similar_implies_exist_matrix')\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Gauss_Jordan/Linear_Maps.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7879863402723644}}
{"text": "theorem sqrt2_not_rational:\n\"sqrt 2 ∉ Q\"\nproof\nlet ?x = \"sqrt 2\"\nassume \"?x ∈ Q\"\nthen obtain m n :: nat where\nsqrt_rat: \"¦?x¦ = m / n\" and lowest_terms: \"coprime m n\"\nby (rule Rats_abs_nat_div_natE)\nhence \"m^2 = ?x^2 * n^2\" by (auto simp add: power2_eq_square)\nhence eq: \"m^2 = 2 * n^2\" using of_nat_eq_iff power2_eq_square by fastforce\nhence \"2 dvd m^2\" by simp\nhence \"2 dvd m\" by simp\nhave \"2 dvd n\" proof -\nfrom ‹2 dvd m› obtain k where \"m = 2 * k\" ..\nwith eq have \"2 * n^2 = 2^2 * k^2\" by simp\nhence \"2 dvd n^2\" by simp\nthus \"2 dvd n\" by simp\nqed\nwith ‹2 dvd m› have \"2 dvd gcd m n\" by (rule gcd_greatest)\nwith lowest_terms have \"2 dvd 1\" by simp\nthus False using odd_one by blast\nqed\n(* End of Isabelle syntax identification sample *)\n\n(* Project language file 1\nFor: SNU/2D/ProgrammingTools/IDE/Isabelle\nAbout:\nI decided to make Isabelle the main project language file for this project (SNU / 2D / Programming Tools / IDE / Isabelle) as this is a Isabelle IDE, and it needs its main language to be represented here.\n*)\n\n(* File info\nFile type: Isabelle source file (*.thy)\nFile version: 1 (2022, Monday, October 3rd at 7:44 pm PST)\nLine count (including blank lines and compiler line): 36\n*)\n", "meta": {"author": "seanpm2001", "repo": "SNU_2D_ProgrammingTools_IDE_IsabelleProofAssistant", "sha": "465ba0fa21ca35780093197121be2d27089176c1", "save_path": "github-repos/isabelle/seanpm2001-SNU_2D_ProgrammingTools_IDE_IsabelleProofAssistant", "path": "github-repos/isabelle/seanpm2001-SNU_2D_ProgrammingTools_IDE_IsabelleProofAssistant/SNU_2D_ProgrammingTools_IDE_IsabelleProofAssistant-465ba0fa21ca35780093197121be2d27089176c1/PROJECT_LANG_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.7879636636054195}}
{"text": "(*\n  File:    Skip_List.thy\n  Authors: Max W. Haslbeck, Manuel Eberl\n*)\n\nsection \\<open>Randomized Skip Lists\\<close>\ntheory Skip_List\n  imports Geometric_PMF\n          Misc\n          \"Monad_Normalisation.Monad_Normalisation\"\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\nlemma bind_pmf_if': \"(do {c \\<leftarrow> C;\n                         ab \\<leftarrow> (if c then A else B);\n                         D ab}::'a pmf) =\n                     do {c \\<leftarrow> C;\n                         (if c then (A \\<bind> D) else (B \\<bind> D))}\"\n  by (metis (mono_tags, lifting))\n\nabbreviation (input) Max\\<^sub>0 where \"Max\\<^sub>0 \\<equiv> (\\<lambda>A. Max (A \\<union> {0}))\"\n\n\nsubsection \\<open>Definition of a Randomised Skip List\\<close>\n\ntext \\<open>\n  Given a set A we assign a geometric random variable (counting the number of failed Bernoulli\n  trials before the first success) to every element in A. That means an arbitrary element of A is\n  on level n with probability $(1-p)^{n}p$. We define he height of the skip list as the maximum\n  assigned level. So a skip list with only one level has height 0 but the calculation of the\n  expected height is cleaner this way.\n\\<close>\n\nlocale random_skip_list =\n  fixes p::real\nbegin\n\ndefinition q where \"q = 1 - p\"\n\ndefinition SL :: \"('a::linorder) set \\<Rightarrow> ('a \\<Rightarrow> nat) pmf\" where \"SL A = Pi_pmf A 0 (\\<lambda>_. geometric_pmf p)\"\ndefinition SL\\<^sub>N :: \"nat \\<Rightarrow> (nat \\<Rightarrow> nat) pmf\" where \"SL\\<^sub>N n = SL {..<n}\"\n\nsubsection \\<open>Height of Skip List\\<close>\n\ndefinition H where \"H A = map_pmf (\\<lambda>f. Max\\<^sub>0 (f ` A)) (SL A)\"\ndefinition H\\<^sub>N :: \"nat \\<Rightarrow> nat pmf\" where \"H\\<^sub>N n = H {..<n}\"\n\ncontext includes monad_normalisation\nbegin\n\ntext \\<open>\n  The height of a skip list is independent of the values in a set A. For simplicity we can\n  therefore work on the skip list over the set @{term \"{..< card A}\"}\n\\<close>\n\nlemma\n  assumes \"finite A\"\n  shows \"H A = H\\<^sub>N (card A)\"\nproof -\n  define f' where \"f' = (\\<lambda>x. if x \\<in> A\n                             then the_inv_into {..<card A} ((!) (sorted_list_of_set A)) x\n                             else card A)\"\n  have bij_f': \"bij_betw f' A {..<card A}\"\n  proof -\n    (* I know the proof looks weird, but for some reason all tools have problems with this proof *)\n    have \"bij_betw (the_inv_into {..<card A} ((!) (sorted_list_of_set A))) A {..<card A}\"\n      unfolding f'_def using sorted_list_of_set_bij_betw assms bij_betw_the_inv_into by blast\n    moreover have \"bij_betw (the_inv_into {..<card A} ((!) (sorted_list_of_set A))) A {..<card A}\n                     = bij_betw f' A {..<card A}\"\n      unfolding f'_def by (rule bij_betw_cong) simp\n    ultimately show ?thesis\n      by blast\n  qed\n  have *: \"Max\\<^sub>0 ((f \\<circ> f') ` A) = Max\\<^sub>0 (f ` {..<card A})\" for f :: \"nat \\<Rightarrow> nat\"\n    using  bij_betw_imp_surj_on bij_f' image_comp by metis\n  have \"H A = map_pmf (\\<lambda>f. Max\\<^sub>0 (f ` A)) (map_pmf (\\<lambda>g. g \\<circ> f') (SL\\<^sub>N (card A)))\"\n    using assms bij_f' unfolding H_def SL_def SL\\<^sub>N_def\n    by (subst Pi_pmf_bij_betw[of _ f' \"{..<card A}\"]) (auto simp add: f'_def)\n  also have \"\\<dots> =  H\\<^sub>N (card A)\"\n    unfolding H\\<^sub>N_def H_def SL\\<^sub>N_def using * by (auto intro!: bind_pmf_cong simp add: map_pmf_def)\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>\n  The cumulative distribution function (CDF) of the height is the CDF of the geometric PMF to the\n  power of n\n\\<close>\n\nlemma prob_Max_IID_geometric_atMost:\n  assumes \"p \\<in> {0..1}\"\n  shows \"measure_pmf.prob (H\\<^sub>N n) {..i}\n       = (measure_pmf.prob (geometric_pmf p) {..i}) ^ n\" (is \"?lhs = ?rhs\")\nproof -\n  note SL_def[simp] SL\\<^sub>N_def[simp] H_def[simp] H\\<^sub>N_def[simp]\n  have \"{f. Max\\<^sub>0 (f ` {..<n}) \\<le> i}  = {..<n} \\<rightarrow> {..i}\"\n    by auto\n  then have \"?lhs = measure_pmf.prob (SL\\<^sub>N n) ({..<n} \\<rightarrow> {..i})\"\n    by (simp add: vimage_def)\n  also have \"\\<dots> = measure_pmf.prob (SL\\<^sub>N n) (PiE_dflt {..<n} 0 (\\<lambda>_. {..i}))\"\n    by (intro measure_prob_cong_0) (auto simp add: PiE_dflt_def pmf_Pi split: if_splits)\n  also have \"\\<dots> = measure_pmf.prob (geometric_pmf p) {..i} ^ n\"\n    using assms by (auto simp add: measure_Pi_pmf_PiE_dflt)\n  finally show ?thesis\n    by simp\nqed\n\nlemma prob_Max_IID_geometric_greaterThan:\n  assumes \"p \\<in> {0<..1}\"\n  shows \"measure_pmf.prob (H\\<^sub>N n) {i<..} =\n         1 - (1 - q ^ (i + 1)) ^ n\"\nproof -\n  have \"UNIV - {..i} = {i<..}\"\n    by auto\n  then have \"measure_pmf.prob (H\\<^sub>N n) {i<..} = measure_pmf.prob (H\\<^sub>N n) (space (measure_pmf (H\\<^sub>N n)) - {..i})\"\n    by (auto)\n  also have \"\\<dots> = 1 - (measure_pmf.prob (geometric_pmf p) {..i}) ^ n\"\n    using assms by (subst measure_pmf.prob_compl) (auto simp add: prob_Max_IID_geometric_atMost)\n  also have \"\\<dots> =   1 - (1 - q ^ (i + 1)) ^ n\"\n    using assms unfolding q_def by (subst geometric_pmf_prob_atMost) auto\n  finally show ?thesis\n    by simp\nqed\n\nend (* context includes monad_normalisation *)\nend (* locale skip_list *)\n\ntext \\<open>\n  An alternative definition of the expected value of a non-negative random variable\n  \\footnote{\\url{https://en.wikipedia.org/w/index.php?title=Expected\\_value&oldid=881384346\\#Formula\\_for\\_non-negative\\_random\\_variables}}\n\\<close>\n\nlemma expectation_prob_atLeast:\n  assumes \"(\\<lambda>i. measure_pmf.prob N {i..}) abs_summable_on {1..}\"\n  shows \"measure_pmf.expectation N real = infsetsum (\\<lambda>i. measure_pmf.prob N {i..}) {1..}\"\n    \"integrable N real\"\nproof -\n  have \"(\\<lambda>(x, y). pmf N y) abs_summable_on Sigma {Suc 0..} atLeast\"\n    using assms by (auto simp add: measure_pmf_conv_infsetsum abs_summable_on_Sigma_iff)\n  then have summable: \"(\\<lambda>(x, y). pmf N x) abs_summable_on Sigma {Suc 0..} (atLeastAtMost (Suc 0))\"\n    by (subst abs_summable_on_reindex_bij_betw[of \"\\<lambda>(x,y). (y,x)\", symmetric])\n      (auto intro!: bij_betw_imageI simp add: inj_on_def case_prod_beta)\n  have \"measure_pmf.expectation N real = (\\<Sum>\\<^sub>ax. pmf N x *\\<^sub>R real x)\"\n    by (auto simp add: infsetsum_def integral_density measure_pmf_eq_density)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ax \\<in> ({0} \\<union> {Suc 0..}). pmf N x *\\<^sub>R real x)\"\n    by (auto intro!: infsetsum_cong)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ax\\<in>{Suc 0..}. pmf N x * real x)\"\n  proof -\n    have \"(\\<lambda>x. pmf N x *\\<^sub>R real x) abs_summable_on {0} \\<union> {Suc 0..}\"\n      using summable by (subst (asm) abs_summable_on_Sigma_iff) (auto simp add: mult.commute)\n    then show ?thesis\n      by (subst infsetsum_Un_Int) auto\n  qed\n  also have \"\\<dots> = (\\<Sum>\\<^sub>a(x, y)\\<in>Sigma {Suc 0..} (atLeastAtMost (Suc 0)). pmf N x)\"\n    using summable by (subst infsetsum_Sigma) (auto simp add: mult.commute)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ax\\<in>Sigma {Suc 0..} atLeast. pmf N (snd x))\"\n    by (subst infsetsum_reindex_bij_betw[of \"\\<lambda>(x,y). (y,x)\", symmetric])\n      (auto intro!: bij_betw_imageI simp add: inj_on_def case_prod_beta)\n  also have \"\\<dots> = infsetsum (\\<lambda>i. measure_pmf.prob N {i..}) {1..}\"\n    using assms\n    by (subst infsetsum_Sigma)\n      (auto simp add: measure_pmf_conv_infsetsum abs_summable_on_Sigma_iff infsetsum_Sigma')\n  finally show \"measure_pmf.expectation N real = infsetsum (\\<lambda>i. measure_pmf.prob N {i..}) {1..}\"\n    by simp\n  have \"(\\<lambda>x. pmf N x *\\<^sub>R real x) abs_summable_on {0} \\<union> {Suc 0..}\"\n    using summable by (subst (asm) abs_summable_on_Sigma_iff) (auto simp add: mult.commute)\n  then have \"(\\<lambda>x. pmf N x *\\<^sub>R real x) abs_summable_on UNIV\"\n    by (simp add: atLeast_Suc)\n  then have \"integrable (count_space UNIV) (\\<lambda>x. pmf N x *\\<^sub>R real x)\"\n    by (subst abs_summable_on_def[symmetric]) blast\n  then show \"integrable N real\"\n    by (subst measure_pmf_eq_density, subst integrable_density) auto\nqed\n\ntext \\<open>\n  The expected height of a skip list has no closed-form expression but we can approximate it. We\n  start by showing how we can calculate an infinite sum over the natural numbers with an integral\n  over the positive reals and the floor function.\n\\<close>\n\nlemma infsetsum_set_nn_integral_reals:\n  assumes \"f abs_summable_on UNIV\" \"\\<And>n. f n \\<ge> 0\"\n  shows \"infsetsum f UNIV = set_nn_integral lborel {0::real..} (\\<lambda>x. f (nat (floor x)))\"\nproof -\n  have \"x < 1 + (floor x)\"for x::real\n    by linarith\n  then have \"\\<exists>n. real n \\<le> x \\<and> x < 1 + real n\" if \"x \\<ge> 0\" for x\n    using that of_nat_floor by (intro exI[of _ \"nat (floor x)\"]) auto\n  then have \"{0..} = (\\<Union>n. {real n..<real (Suc n)})\"\n    by auto\n  then have \"\\<integral>\\<^sup>+x\\<in>{0::real..}. ennreal (f (nat \\<lfloor>x\\<rfloor>))\\<partial>lborel =\n             (\\<Sum>n. \\<integral>\\<^sup>+x\\<in>{real n..<1 + real n}. ennreal (f (nat \\<lfloor>x\\<rfloor>))\\<partial>lborel)\"\n    by (auto simp add: disjoint_family_on_def nn_integral_disjoint_family)\n  also have \"\\<dots> = (\\<Sum>n. \\<integral>\\<^sup>+x\\<in>{real n..<1 + real n}. ennreal (f n)\\<partial>lborel)\"\n    by(subst suminf_cong, rule nn_integral_cong_AE)\n      (auto intro!: eventuallyI  simp add: indicator_def floor_eq4)\n  also have \"\\<dots> = (\\<Sum>n. ennreal (f n))\"\n    by (auto intro!: suminf_cong simp add: nn_integral_cmult)\n  also have \"\\<dots> = infsetsum f {0..}\"\n    using assms suminf_ennreal2 abs_summable_on_nat_iff' summable_norm_cancel\n    by (auto simp add: infsetsum_nat)\n  finally show ?thesis\n    by simp\nqed\n\nlemma nn_integral_nats_reals:\n  shows \"(\\<integral>\\<^sup>+ i. ennreal (f i) \\<partial>count_space UNIV) = \\<integral>\\<^sup>+x\\<in>{0::real..}. ennreal (f (nat \\<lfloor>x\\<rfloor>))\\<partial>lborel\"\nproof -\n  have \"x < 1 + (floor x)\"for x::real\n    by linarith\n  then have \"\\<exists>n. real n \\<le> x \\<and> x < 1 + real n\" if \"x \\<ge> 0\" for x\n    using that of_nat_floor by (intro exI[of _ \"nat (floor x)\"]) auto\n  then have \"{0..} = (\\<Union>n. {real n..<real (Suc n)})\"\n    by auto\n  then have \"\\<integral>\\<^sup>+x\\<in>{0::real..}. f (nat \\<lfloor>x\\<rfloor>)\\<partial>lborel =\n             (\\<Sum>n. \\<integral>\\<^sup>+x\\<in>{real n..<1 + real n}. ennreal (f (nat \\<lfloor>x\\<rfloor>))\\<partial>lborel)\"\n    by (auto simp add: disjoint_family_on_def nn_integral_disjoint_family)\n  also have \"\\<dots> = (\\<Sum>n. \\<integral>\\<^sup>+x\\<in>{real n..<1 + real n}. ennreal (f n)\\<partial>lborel)\"\n    by(subst suminf_cong,rule nn_integral_cong_AE)\n      (auto intro!: eventuallyI  simp add: indicator_def floor_eq4)\n  also have \"\\<dots> = (\\<Sum>n. ennreal (f n))\"\n    by (auto intro!: suminf_cong simp add: nn_integral_cmult)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ i. ennreal (f i) \\<partial>count_space UNIV)\"\n    by (simp add: nn_integral_count_space_nat)\n  finally show ?thesis\n    by simp\nqed\n\nlemma nn_integral_floor_less_eq:\n  assumes \"\\<And>x y. x \\<le> y \\<Longrightarrow> f y \\<le> f x\"\n  shows \"\\<integral>\\<^sup>+x\\<in>{0::real..}. ennreal (f x)\\<partial>lborel \\<le> \\<integral>\\<^sup>+x\\<in>{0::real..}. ennreal (f (nat \\<lfloor>x\\<rfloor>))\\<partial>lborel\"\n  using assms by (auto simp add: indicator_def intro!: nn_integral_mono ennreal_leI)\n\nlemma nn_integral_finite_imp_abs_sumable_on:\n  fixes f :: \"'a \\<Rightarrow> 'b::{banach, second_countable_topology}\"\n  assumes \"nn_integral (count_space A) (\\<lambda>x. norm (f x)) < \\<infinity>\"\n  shows   \"f abs_summable_on A\"\n  using assms unfolding abs_summable_on_def integrable_iff_bounded by auto\n\nlemma nn_integral_finite_imp_abs_sumable_on':\n  assumes \"nn_integral (count_space A) (\\<lambda>x. ennreal (f x)) < \\<infinity>\" \"\\<And>x. f x \\<ge> 0\"\n  shows   \"f abs_summable_on A\"\n  using assms unfolding abs_summable_on_def integrable_iff_bounded by auto\n\ntext \\<open>\n  We now show that $\\int_0^\\infty 1 - (1 - q^x) ^ n\\;dx = \\frac{- H_n}{\\ln q}$ if $0 < q < 1$.\n\\<close>\n\nlemma harm_integral_x_raised_n:\n  \"set_integrable lborel {0::real..1} (\\<lambda>x. (\\<Sum>i\\<in>{..<n}. x ^ i))\" (is ?thesis1)\n  \"LBINT x = 0..1. (\\<Sum>i\\<in>{..<n}. x ^ i) = harm n\" (is ?thesis2)\nproof -\n  have h: \"set_integrable lborel {0::real..1} (\\<lambda>x. (\\<Sum>i\\<in>{..<n}. x ^ i))\" for n\n    by (intro borel_integrable_atLeastAtMost') (auto intro!: continuous_intros)\n  then show ?thesis1\n    by (intro borel_integrable_atLeastAtMost') (auto intro!: continuous_intros)\n  show ?thesis2\n  proof (induction n)\n    case (Suc n)\n    have \"(LBINT x=0..1.(\\<Sum>i\\<in>{..<n}. x ^ i) + x ^ n) =\n          (LBINT x=0..1. (\\<Sum>i\\<in>{..<n}. x ^ i)) + (LBINT x=0..1. x ^ n)\"\n    proof -\n      have \"set_integrable lborel (einterval 0 1) (\\<lambda>x. (\\<Sum>i\\<in>{..<n}. x ^ i))\"\n        by (rule set_integrable_subset) (use h in \\<open>auto simp add: einterval_def\\<close>)\n      moreover have \"set_integrable lborel (einterval 0 1) (\\<lambda>x. (x ^ n))\"\n      proof -\n        have \"set_integrable lborel {0::real..1} (\\<lambda>x. (x ^ n))\"\n          by (rule borel_integrable_atLeastAtMost')\n            (auto intro!: borel_integrable_atLeastAtMost' continuous_intros)\n        then show ?thesis\n          by (rule set_integrable_subset) (auto simp add: einterval_def)\n      qed\n      ultimately show ?thesis\n        by (auto intro!: borel_integrable_atLeastAtMost' simp add:  interval_lebesgue_integrable_def)\n    qed\n    also have \"(LBINT x=0..1. x ^ n) = 1 / (1 + real n)\"\n    proof -\n      have \"(LBINT x=0..1. x ^ n) = LBINT x. x ^ n * indicator {0..1} x \"\n      proof -\n        have \"AE x in lborel. x ^ n * indicator {0..1} x = indicator (einterval 0 1) x * x ^ n\"\n          by(rule eventually_mono[OF eventually_conj[OF  AE_lborel_singleton[of 1]\n                  AE_lborel_singleton[of 0]]])\n            (auto simp add: indicator_def einterval_def)\n        then show ?thesis\n          using integral_cong_AE unfolding interval_lebesgue_integral_def set_lebesgue_integral_def\n          by (auto intro!: integral_cong_AE)\n      qed\n      then show ?thesis\n        by (auto simp add: integral_power)\n    qed\n    finally show ?case\n      using Suc by (auto simp add: harm_def inverse_eq_divide)\n  qed (auto simp add: harm_def)\nqed\n\nlemma harm_integral_0_1_fraction:\n  \"set_integrable lborel {0::real..1} (\\<lambda>x. (1 - x ^ n) / (1 - x))\"\n  \"(LBINT x = 0..1. ((1 - x ^ n) / (1 - x))) = harm n\"\nproof -\n  show \"set_integrable lborel {0::real..1} (\\<lambda>x. (1 - x ^ n) / (1 - x))\"\n  proof -\n    have \"AE x\\<in>{0::real..1} in lborel. (1 - x ^ n) / (1 - x) = sum ((^) x) {..<n}\"\n      by (auto intro!: eventually_mono[OF AE_lborel_singleton[of 1]] simp add: sum_gp_strict)\n    with harm_integral_x_raised_n show ?thesis\n      by (subst set_integrable_cong_AE) auto\n  qed\n  moreover have \"AE x\\<in>{0::real<..<1} in lborel. (1 - x ^ n) / (1 - x) = sum ((^) x) {..<n}\"\n    by (auto simp add: sum_gp_strict)\n  moreover have \"einterval (min 0 1) (max 0 1) = {0::real<..<1}\"\n    by (auto simp add: min_def max_def einterval_iff)\n  ultimately show \"(LBINT x = 0..1. ((1 - x ^ n) / (1 - x))) = harm n\"\n    using harm_integral_x_raised_n by (subst interval_integral_cong_AE) auto\nqed\n\nlemma one_minus_one_minus_q_x_n_integral:\n  assumes \"q \\<in> {0<..<1}\"\n  shows \"set_integrable lborel (einterval 0 \\<infinity>) (\\<lambda>x. (1 - (1 - q powr x) ^ n))\"\n        \"(LBINT x=0..\\<infinity>. 1 - (1 - q powr x) ^ n) = - harm n / ln q\"\nproof -\n  have [simp]: \"q powr (log q (1-x)) = 1 - x\" if \"x \\<in> {0<..<1}\" for x\n    using that assms by (subst powr_log_cancel) auto\n  have 1: \"((ereal \\<circ> (\\<lambda>x. log q (1 - x)) \\<circ> real_of_ereal) \\<longlongrightarrow> 0) (at_right 0)\"\n    using assms unfolding zero_ereal_def ereal_tendsto_simps by (auto intro!: tendsto_eq_intros)\n  have 2: \"((ereal \\<circ> (\\<lambda>x. log q (1-x)) \\<circ> real_of_ereal) \\<longlongrightarrow> \\<infinity>) (at_left 1)\"\n  proof -\n    have \"filterlim ((-) 1) (at_right 0) (at_left (1::real))\"\n      by (intro filterlim_at_withinI eventually_at_leftI[of 0]) (auto intro!: tendsto_eq_intros)\n    then have \"LIM x at_left 1. - inverse (ln q) * - ln (1 - x) :> at_top\"\n      using assms\n      by (intro filterlim_tendsto_pos_mult_at_top [OF tendsto_const])\n        (auto simp: filterlim_uminus_at_top intro!: filterlim_compose[OF ln_at_0])\n    then show ?thesis\n      unfolding one_ereal_def ereal_tendsto_simps log_def by (simp add: field_simps)\n  qed\n  have 3: \"set_integrable lborel (einterval 0 1)\n     (\\<lambda>x. (1 - (1 - q powr (log q (1 - x))) ^ n) * (- 1 / (ln q * (1 - x))))\"\n  proof -\n    have \"set_integrable lborel (einterval 0 1) (\\<lambda>x. - (1 / ln q) * ((1 - x ^ n) / (1 - x)))\"\n      by(intro set_integrable_mult_right)\n        (auto intro!: harm_integral_0_1_fraction intro: set_integrable_subset simp add: einterval_def)\n    then show ?thesis\n      by(subst set_integrable_cong_AE[where g=\"\\<lambda>x. - (1 / ln q) * ((1 - x ^ n) / (1 - x))\"])\n        (auto intro!: eventuallyI simp add: einterval_def)\n  qed\n  have 4: \"LBINT x=0..1. - ((1 - (1 - q powr log q (1 - x)) ^ n) / (ln q * (1 - x))) = - (harm n / ln q)\"\n    (is \"?lhs = ?rhs\")\n  proof -\n    have \"?lhs = LBINT x=0..1. ((1 - x ^ n) / (1 - x)) * (- 1 / ln q)\"\n      using assms\n      by (intro interval_integral_cong_AE)\n      (auto intro!: eventuallyI simp add: max_def einterval_def field_simps)\n    also have \"\\<dots> = harm n * (-1 / ln q)\"\n      using harm_integral_0_1_fraction by (subst interval_lebesgue_integral_mult_left) auto\n    finally show ?thesis\n      by auto\n  qed\n  note sub = interval_integral_substitution_nonneg\n             [where f = \"(\\<lambda>x. (1 - (1 - q powr x) ^ n))\" and g=\"(\\<lambda>x. log q (1-x))\"\n                    and g'=\"(\\<lambda>x. - 1 / (ln q * (1 - x)))\" and a = 0 and b = 1]\n  show \"set_integrable lborel (einterval 0 \\<infinity>) (\\<lambda>x. (1 - (1 - q powr x) ^ n))\"\n    using assms 1 2 3 4\n    by (intro sub) (auto intro!: derivative_eq_intros mult_nonneg_nonpos2 tendsto_intros power_le_one)\n  show \"(LBINT x=0..\\<infinity>. 1 - (1 - q powr x) ^ n) = - harm n / ln q\"\n    using assms 1 2 3 4\n    by (subst sub) (auto intro!: derivative_eq_intros mult_nonneg_nonpos2 tendsto_intros power_le_one)\nqed\n\nlemma one_minus_one_minus_q_x_n_nn_integral:\n  fixes q::real\n  assumes \"q \\<in> {0<..<1}\"\n  shows \"set_nn_integral lborel {0..} (\\<lambda>x. (1 - (1 - q powr x) ^ n)) =\n        LBINT x=0..\\<infinity>. 1 - (1 - q powr x) ^ n\"\nproof -\n  have \"set_nn_integral  lborel {0..} (\\<lambda>x. (1 - (1 - q powr x) ^ n)) =\n        nn_integral lborel (\\<lambda>x. indicator (einterval 0 \\<infinity>) x *  (1 - (1 - q powr x) ^ n))\"\n    using assms by (intro nn_integral_cong_AE eventually_mono[OF AE_lborel_singleton[of 0]])\n      (auto simp add: indicator_def einterval_def)\n  also have \"\\<dots> = ennreal (LBINT x. indicator (einterval 0 \\<infinity>) x * (1 - (1 - q powr x) ^ n))\"\n  using one_minus_one_minus_q_x_n_integral assms\n  by(intro nn_integral_eq_integral)\n    (auto simp add: indicator_def einterval_def set_integrable_def\n      intro!: eventuallyI power_le_one powr_le1)\n  finally show ?thesis\n    by (simp add: interval_lebesgue_integral_def set_lebesgue_integral_def)\nqed\n\ntext \\<open>\n  We can now derive bounds for the expected height.\n\\<close>\n\ncontext random_skip_list\nbegin\n\ndefinition EH\\<^sub>N where \"EH\\<^sub>N n = measure_pmf.expectation (H\\<^sub>N n) real\"\n\nlemma EH\\<^sub>N_bounds':\n  fixes n::nat\n  assumes \"p \\<in> {0<..<1}\" \"0 < n\"\n  shows \"- harm n / ln q - 1 \\<le> EH\\<^sub>N n\"\n     \"EH\\<^sub>N n \\<le> - harm n / ln q\"\n     \"integrable (H\\<^sub>N n) real\"\nproof -\n  define f where \"f = (\\<lambda>x. 1 - (1 - q ^ x) ^ n)\"\n  define f' where \"f' = (\\<lambda>x. 1 - (1 - q powr x) ^ n)\"\n  have q: \"q \\<in> {0<..<1}\"\n    unfolding q_def using assms by auto\n  have f_descending: \"f y \\<le> f x\" if \"x \\<le> y\" for x y\n    unfolding f_def using that q\n    by (auto intro!: power_mono simp add: power_decreasing power_le_one_iff)\n  have f'_descending: \"f' y \\<le> f' x\" if \"x \\<le> y\" \"0 \\<le> x\" for x y\n    unfolding f'_def using that q\n    by (auto intro!: power_mono simp add: ln_powr powr_def mult_nonneg_nonpos)\n  have [simp]: \"harm n / ln q <= 0\"\n    using harm_nonneg ln_ge_zero_imp_ge_one q by (intro divide_nonneg_neg) auto\n  have f_nn_integral_harm:\n    \"- harm n / ln q \\<le> \\<integral>\\<^sup>+ x. (f x) \\<partial>count_space UNIV\"\n    \"(\\<integral>\\<^sup>+ i. f (i + 1) \\<partial>count_space UNIV) \\<le> - harm n / ln q\"\n  proof -\n    have \"(\\<integral>\\<^sup>+ i. f (i + 1) \\<partial>count_space UNIV) = (\\<integral>\\<^sup>+x\\<in>{0::real..}. (f (nat \\<lfloor>x\\<rfloor> + 1))\\<partial>lborel)\"\n      using nn_integral_nats_reals by auto\n    also have \"\\<dots> = \\<integral>\\<^sup>+x\\<in>{0::real..}. ennreal (f' (nat \\<lfloor>x\\<rfloor> + 1))\\<partial>lborel\"\n    proof -\n      have \"0 \\<le> x \\<Longrightarrow> (1 - q * q ^ nat \\<lfloor>x\\<rfloor>) ^ n = (1 - q powr (1 + real_of_int \\<lfloor>x\\<rfloor>)) ^ n\" for x::real\n        using q by (subst powr_realpow [symmetric]) (auto simp: powr_add)\n      then show ?thesis\n        unfolding f_def f'_def using q\n        by (auto intro!: nn_integral_cong ennreal_cong  simp add: powr_real_of_int indicator_def)\n    qed\n    also have \"\\<dots> \\<le> set_nn_integral lborel {0..} f'\"\n    proof -\n      have \"x \\<le> 1 + real_of_int \\<lfloor>x\\<rfloor>\" for x\n        by linarith\n      then show ?thesis\n        by (auto simp add: indicator_def intro!: f'_descending nn_integral_mono ennreal_leI)\n    qed\n    also have harm_integral_f': \"\\<dots> = - harm n / ln q\"\n      unfolding f'_def using q\n      by (auto intro!: ennreal_cong\n          simp add: one_minus_one_minus_q_x_n_nn_integral one_minus_one_minus_q_x_n_integral)\n    finally show \"(\\<integral>\\<^sup>+ i. f (i + 1) \\<partial>count_space UNIV) \\<le> - harm n / ln q\"\n      by simp\n    note harm_integral_f'[symmetric]\n    also have \"set_nn_integral lborel {0..} f' \\<le> \\<integral>\\<^sup>+x\\<in>{0::real..}. f' (nat \\<lfloor>x\\<rfloor>)\\<partial>lborel\"\n      using assms f'_descending\n      by (auto simp add: indicator_def intro!: nn_integral_mono ennreal_leI)\n    also have \"\\<dots> = \\<integral>\\<^sup>+x\\<in>{0::real..}. f (nat \\<lfloor>x\\<rfloor>)\\<partial>lborel\"\n      unfolding f_def f'_def\n      using q by (auto intro!: nn_integral_cong ennreal_cong simp add: powr_real_of_int indicator_def)\n    also have \"\\<dots> = (\\<integral>\\<^sup>+ x. f x \\<partial>count_space UNIV)\"\n      using nn_integral_nats_reals by auto\n    finally show \"- harm n / ln q \\<le> \\<integral>\\<^sup>+ x. f x \\<partial>count_space UNIV\"\n      by simp\n  qed\n  then have f1_abs_summable_on: \"(\\<lambda>i. f (i + 1)) abs_summable_on UNIV\"\n    unfolding f_def using q\n    by (intro nn_integral_finite_imp_abs_sumable_on')\n      (auto simp add: f_def le_less_trans intro!: power_le_one mult_le_one)\n  then have f_abs_summable_on: \"f abs_summable_on {1..}\"\n    using Suc_le_lessD greaterThan_0\n    by (subst abs_summable_on_reindex_bij_betw[symmetric, where g=\"\\<lambda>x. x + 1\" and A=\"UNIV\"]) auto\n  also have \"(f abs_summable_on {1..}) = ((\\<lambda>x. measure_pmf.prob (H\\<^sub>N n) {x..}) abs_summable_on {1..})\"\n  proof -\n    have \"((\\<lambda>x. measure_pmf.prob (H\\<^sub>N n) {x..}) abs_summable_on {1..}) =\n          ((\\<lambda>x. measure_pmf.prob (H\\<^sub>N n) {x - 1<..}) abs_summable_on {1..})\"\n      by (auto intro!: measure_prob_cong_0 abs_summable_on_cong)\n    also have \"\\<dots> = (f abs_summable_on {1..})\"\n      using assms\n      by (intro abs_summable_on_cong) (auto simp add: f_def prob_Max_IID_geometric_greaterThan)\n    finally show ?thesis\n      by simp\n  qed\n  finally have EH\\<^sub>N_sum:\n    \"EH\\<^sub>N n = (\\<Sum>\\<^sub>ai\\<in>{1..}. measure_pmf.prob (H\\<^sub>N n) {i..})\"\n    \"integrable (measure_pmf (H\\<^sub>N n)) real\"\n    unfolding EH\\<^sub>N_def using expectation_prob_atLeast by auto\n  then show \"integrable (measure_pmf (H\\<^sub>N n)) real\"\n    by simp\n  have EH\\<^sub>N_sum': \"EH\\<^sub>N n = infsetsum f {1..}\"\n  proof -\n    have \"EH\\<^sub>N n = (\\<Sum>\\<^sub>ak\\<in>{1..}. measure_pmf.prob (H\\<^sub>N n) {k - 1<..})\"\n      unfolding EH\\<^sub>N_sum by (auto intro!: measure_prob_cong_0 infsetsum_cong)\n    also have \"\\<dots> = infsetsum f {1..}\"\n      using assms\n      by (intro infsetsum_cong) (auto simp add: f_def prob_Max_IID_geometric_greaterThan)\n    finally show ?thesis\n      by simp\n  qed\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ak. f (k + 1))\"\n    using Suc_le_lessD greaterThan_0\n    by (subst infsetsum_reindex_bij_betw[symmetric, where g=\"\\<lambda>x. x + 1\" and A=\"UNIV\"]) auto\n  also have \"ennreal \\<dots> = (\\<integral>\\<^sup>+x\\<in>{0::real..}. f (nat \\<lfloor>x\\<rfloor> + 1)\\<partial>lborel)\"\n    using f1_abs_summable_on q\n    by (intro infsetsum_set_nn_integral_reals) (auto simp add: f_def mult_le_one power_le_one)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ i. f (i + 1) \\<partial>count_space UNIV)\"\n    using nn_integral_nats_reals by auto\n  also have \"\\<dots> \\<le> - harm n / ln q\"\n    using f_nn_integral_harm by auto\n  finally show \"EH\\<^sub>N n \\<le> - harm n / ln q\"\n    by (subst (asm) ennreal_le_iff) (auto)\n  have \"EH\\<^sub>N n + 1 = (\\<Sum>\\<^sub>ax\\<in>{Suc 0..}. f x) + (\\<Sum>\\<^sub>ax\\<in>{0}. f x)\"\n    using assms by (subst EH\\<^sub>N_sum') (auto simp add: f_def)\n  also have \"\\<dots> = infsetsum f UNIV\"\n    using f_abs_summable_on by (subst infsetsum_Un_disjoint[symmetric]) (auto intro!: infsetsum_cong)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+x\\<in>{0::real..}. f (nat \\<lfloor>x\\<rfloor>)\\<partial>lborel)\"\n  proof -\n    have \"f abs_summable_on ({0} \\<union> {1..})\"\n      using f_abs_summable_on by (intro abs_summable_on_union) (auto)\n    also have \"{0::nat} \\<union> {1..} = UNIV\"\n      by auto\n    finally show ?thesis\n      using q\n      by (intro infsetsum_set_nn_integral_reals) (auto simp add: f_def mult_le_one power_le_one)\n  qed\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. f x \\<partial>count_space UNIV)\"\n    using nn_integral_nats_reals by auto\n  also have \"... \\<ge> - harm n / ln q\"\n    using f_nn_integral_harm by auto\n  finally have \"- harm n / ln q \\<le> EH\\<^sub>N n + 1\"\n    by (subst (asm) ennreal_le_iff) (auto simp add: EH\\<^sub>N_def)\n  then show \"- harm n / ln q - 1 \\<le> EH\\<^sub>N n\"\n    by simp\nqed\n\ntheorem EH\\<^sub>N_bounds:\n  fixes n::nat\n  assumes \"p \\<in> {0<..<1}\"\n  shows\n    \"- harm n / ln q - 1 \\<le> EH\\<^sub>N n\"\n    \"EH\\<^sub>N n \\<le> - harm n / ln q\"\n    \"integrable (H\\<^sub>N n) real\"\nproof -\n  show \"- harm n / ln q - 1 \\<le> EH\\<^sub>N n\"\n    using assms EH\\<^sub>N_bounds'\n    by (cases \"n = 0\") (auto simp add: EH\\<^sub>N_def H\\<^sub>N_def H_def SL_def harm_expand)\n  show \"EH\\<^sub>N n \\<le> - harm n / ln q\"\n    using assms EH\\<^sub>N_bounds'\n    by (cases \"n = 0\") (auto simp add: EH\\<^sub>N_def H\\<^sub>N_def H_def SL_def harm_expand)\n  show \"integrable (H\\<^sub>N n) real\"\n    using assms EH\\<^sub>N_bounds'\n    by (cases \"n = 0\") (auto simp add: H\\<^sub>N_def H_def SL_def intro!: integrable_measure_pmf_finite)\nqed\n\nend (* context random_skip_list *)\n\nsubsection \\<open>Expected Length of Search Path\\<close>\n\ntext \\<open>\n  Let @{term \"A::'a::linorder set\"} and @{term \"f::'a \\<Rightarrow> nat\"} where f is an abstract description\n  of a skip list (assign each value its maximum level). steps A f s u l starts on the rightmost element\n  on level s in the skip lists. If possible it moves up, if not it moves to the left. For every step\n  up it adds cost u and for every step to the left it adds cost l. steps A f 0 1 1 therefore walks\n  from the bottom right corner of a skip list to the top left corner of a skip list and counts\n  all steps.\n\\<close>\n\n\\<comment> \\<open>NOTE: You could also define steps with lsteps and then prove that the following recursive\n    definition holds\\<close>\n\nfunction steps :: \"'a :: linorder set \\<Rightarrow> ('a \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"steps A f l up left = (if A = {} \\<or> infinite A\n              then 0\n              else (let m = Max A in (if f m < l then       steps (A - {m}) f l up left\n                                      else (if f m > l then up + steps A f (l + 1) up left\n                                      else                  left + steps (A - {m}) f l up left))))\"\n  by pat_completeness auto\ntermination\nproof (relation \"(\\<lambda>(A,f,l,a,b). card A) <*mlex*> (\\<lambda>(A,f,l,a,b). Max (f ` A) - l) <*mlex*> {}\", goal_cases)\n  case 1\n  then show ?case\n    by(intro wf_mlex wf_empty)\nnext\n  case 2\n  then show ?case\n    by (intro mlex_less) (auto simp: card_gt_0_iff)\nnext\n  case (3 A f l a b x)\n  then have \"Max (f ` A) - Suc l < Max (f ` A) - l\"\n    by (meson Max_gr_iff Max_in diff_less_mono2 finite_imageI imageI image_is_empty lessI)\n   with 3 have \"((A, f, l + 1, a, b), A, f, l, a, b) \\<in> (\\<lambda>(A, f, l, a, b). Max (f ` A) - l) <*mlex*> {}\"\n     by (intro mlex_less) (auto)\n   with 3 show ?case apply - apply(rule mlex_leq) by auto\nnext\n  case 4\n  then show ?case by (intro mlex_less) (auto simp: card_gt_0_iff)\nqed\n\ndeclare steps.simps[simp del]\n\ntext \\<open>\n  lsteps is similar to steps but is using lists instead of sets. This makes the proofs where we use\n  induction easier.\n\\<close>\n\nfunction lsteps :: \"'a list \\<Rightarrow> ('a \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"lsteps [] f l up left = 0\" |\n  \"lsteps (x#xs) f l up left = (if       f x < l then lsteps xs f l up left\n                                 else (if f x > l then up + lsteps (x#xs) f (l + 1) up left\n                                 else                        left + lsteps xs f l up left))\"\n  by pat_completeness auto\ntermination\nproof (relation \"(\\<lambda>(xs,f,l,a,b). length xs) <*mlex*> (\\<lambda>(xs,f,l,a,b).\n                 Max (f ` set xs) - l) <*mlex*> {}\",\n       goal_cases)\n  case 1\n  then show ?case\n    by(intro wf_mlex wf_empty)\nnext\n  case 2\n  then show ?case\n    by (auto intro: mlex_less simp: card_gt_0_iff)\nnext\n  case (3 n f l a b)\n  show ?case\n    by (rule mlex_leq) (use 3 in \\<open>auto intro: mlex_less mlex_leq intro!:  diff_less_mono2 simp add: Max_gr_iff\\<close>)\nnext\n  case 4\n  then show ?case by (intro mlex_less) (auto simp: card_gt_0_iff)\nqed\n\ndeclare lsteps.simps(2)[simp del]\n\n\n\nlemma steps_lsteps: \"steps A f l u v = lsteps (rev (sorted_list_of_set A)) f l u v\"\nproof (cases \"finite A \\<and> A \\<noteq> {}\")\n  case True\n  then show ?thesis\n  proof(induction \"(rev (sorted_list_of_set A))\" f l u v arbitrary: A rule: lsteps.induct)\n    case (2 y ys f l u v A)\n    then have y_ys: \"y = Max A\" \"ys  = rev (sorted_list_of_set (A - {y}))\"\n      by (auto simp add: sorted_list_of_set_Max_snoc)\n    consider (a) \"l < f y\" | (b) \"f y < l\" | (c) \"f y = l\"\n      by fastforce\n    then have \"steps A f l u v = lsteps (y#ys) f l u v\"\n    proof cases\n      case a\n      then show ?thesis\n        by (subst steps.simps, subst lsteps.simps) (use y_ys 2 in auto)\n    next\n      case b\n      then show ?thesis\n        using y_ys 2(1) by (cases \"ys = []\") (auto simp add: steps.simps lsteps.simps)\n    next\n      case c\n      then have \"steps (A - {Max A}) f l u v =\n                 lsteps (rev (sorted_list_of_set (A - {Max A}))) f l u v\"\n        by (cases \"A = {Max A}\") (use y_ys 2 in \\<open>auto intro!: 2(3) simp add: steps.simps\\<close>)\n      then show ?thesis\n        by (subst steps.simps, subst lsteps.simps) (use y_ys 2 in auto)\n    qed\n    then show ?case\n      using 2 by simp\n  qed (auto simp add: steps.simps)\nqed (auto simp add: steps.simps)\n\nlemma lsteps_comp_map: \"lsteps zs (f \\<circ> g) l u v = lsteps (map g zs) f l u v\"\n  by (induction zs \"f \\<circ> g\" l u v rule: lsteps.induct) (auto simp add: lsteps.simps)\n\nlemma steps_image:\n  assumes \"finite A\" \"mono_on g A\" \"inj_on g A\"\n  shows \"steps A (f \\<circ> g) l u v = steps (g ` A) f l u v\"\nproof -\n  have \"(sorted_list_of_set (g ` A)) = map g (sorted_list_of_set A)\"\n    using sorted_list_of_set_image assms by auto\n  also have \"rev \\<dots> = map g (rev (sorted_list_of_set A))\"\n    using rev_map by auto\n  finally show ?thesis\n    by (simp add: steps_lsteps lsteps_comp_map)\nqed\n\nlemma lsteps_cong:\n  assumes \"ys = xs\" \"\\<And>x. x \\<in> set xs \\<Longrightarrow> f x = g x\" \"l = l'\"\n  shows \"lsteps xs f l u v = lsteps ys g l' u v\"\n  using assms proof (induction xs f l u v arbitrary: ys l' rule: lsteps.induct)\n  case (2 x xs f l up left)\n  then show ?case\n    by (subst \\<open>ys = x # xs\\<close>, subst lsteps.simps, subst (2) lsteps.simps) auto\nqed (auto)\n\nlemma steps_cong:\n  assumes \"A = B\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x\" \"l = l'\"\n  shows   \"steps A f l u v = steps B g l' u v\"\n  using assms\n  by (cases \"A = {} \\<or> infinite A\") (auto simp add: steps_lsteps steps.simps intro!: lsteps_cong)\n\nlemma lsteps_f_add':\n  shows \"lsteps xs f l u v = lsteps xs (\\<lambda>x. f x + m) (l + m) u v\"\n  by  (induction xs f l u v rule: lsteps.induct) (auto simp add: lsteps.simps)\n\nlemma steps_f_add':\n  shows \"steps A f l u v = steps A (\\<lambda>x. f x + m) (l + m) u v\"\n  by (cases \"A = {} \\<or> infinite A\") (auto simp add: steps_lsteps steps.simps intro!: lsteps_f_add')\n\nlemma lsteps_smaller_set:\n  assumes \"m \\<le> l\"\n  shows \"lsteps xs f l u v = lsteps [x \\<leftarrow> xs. m \\<le> f x] f l u v\"\n  using assms by (induction xs f l u v rule: lsteps.induct) (auto simp add: lsteps.simps)\n\nlemma steps_smaller_set:\n  assumes \"finite A\" \"m \\<le> l\"\n  shows \"steps A f l u v = steps {x\\<in>A. f x \\<ge> m} f l u v\"\n  using assms\n  by(cases \"A = {} \\<or> infinite A\")\n    (auto simp add: steps_lsteps steps.simps rev_filter sorted_list_of_set_filter\n      intro!: lsteps_smaller_set)\n\nlemma lsteps_level_greater_fun_image:\n  assumes \"\\<And>x. x \\<in> set xs \\<Longrightarrow> f x < l\"\n  shows   \"lsteps xs f l u v = 0\"\n  using assms by (induction xs f l u v rule: lsteps.induct) (auto simp add: lsteps.simps)\n\nlemma lsteps_smaller_card_Max_fun':\n  assumes \"\\<exists>x \\<in> set xs. l \\<le> f x\"\n  shows   \"lsteps xs f l u v + l * u \\<le> v * length xs + u * Max ((f ` (set xs)) \\<union> {0})\"\n  using assms proof (induction xs f l u v rule: lsteps.induct)\n  case (1 f l up left)\n  then show ?case by (simp)\nnext\n  case (2 x xs f l up left)\n  consider \"l = f x\" \"\\<exists>y\\<in>set xs. l \\<le> f y\" | \"f x = l\" \"\\<not> (\\<exists>y\\<in>set xs. l \\<le> f y)\" |\n   \"f x < l\" | \"l < f x\"\n    by fastforce\n  then show ?case\n  proof cases\n    assume a: \"l = f x\" \"\\<exists>y\\<in>set xs. l \\<le> f y\"\n    have \"lsteps (x # xs) f l up left + l * up = lsteps xs f l up left + f x * up + left\"\n      using a by (auto simp add: lsteps.simps)\n    also have \"lsteps xs f l up left + f x * up \\<le> left * length xs + up * Max (f ` set xs \\<union> {0})\"\n      using a 2 by blast\n    also have \"up * Max (f ` set xs \\<union> {0}) \\<le> up * Max (insert (f x) (f ` set xs))\"\n      by simp\n    finally  show ?case\n      by auto\n  next\n    assume a: \"f x = l\" \"\\<not> (\\<exists>y\\<in>set xs. l \\<le> f y)\"\n    have \"lsteps (x # xs) f l up left + l * up = lsteps xs f l up left + f x * up + left\"\n      using a by (auto simp add: lsteps.simps)\n    also have \"lsteps xs f l up left = 0\"\n      using a by (subst lsteps_level_greater_fun_image) auto\n    also have \"f x * up \\<le> up * Max (insert (f x) (f ` set xs))\"\n      by simp\n    finally show ?case\n      by simp\n  next\n    assume a: \"f x < l\"\n    then have \"lsteps (x # xs) f l up left = lsteps xs f l up left\"\n      by (auto simp add: lsteps.simps)\n    also have \"\\<dots> + l * up \\<le> left * length (x # xs) + up * Max (insert 0 (f ` set xs))\"\n      using a 2 by auto\n    also have \"Max (insert 0 (f ` set xs)) \\<le> Max (f ` set (x # xs) \\<union> {0})\"\n      by simp\n    finally show ?case\n      by simp\n  next\n  assume \"f x > l\"\n    then show ?case\n      using 2 by (subst lsteps.simps) auto\n  qed\nqed\n\nlemma steps_smaller_card_Max_fun':\n  assumes \"finite A\" \"\\<exists>x\\<in>A. l \\<le> f x\"\n  shows   \"steps A f l up left + l * up \\<le> left * card A + up * Max\\<^sub>0 (f ` A)\"\nproof -\n  let ?xs = \"rev (sorted_list_of_set A)\"\n  have \"steps A f l up left  = lsteps (rev (sorted_list_of_set A)) f l up left\"\n    using steps_lsteps by blast\n  also have \"\\<dots> + l * up \\<le> left * length ?xs + up * Max (f ` set ?xs \\<union> {0})\"\n    using assms by (intro lsteps_smaller_card_Max_fun') auto\n  also have \"left * length ?xs = left * card A\"\n    using assms sorted_list_of_set_length by (auto)\n  also have \"set ?xs = A\"\n    using assms by (auto)\n  finally show ?thesis\n    by simp\nqed\n\nlemma lsteps_height:\n  assumes  \"\\<exists>x \\<in> set xs. l \\<le> f x\"\n  shows \"lsteps xs f l up 0 + up * l = up * Max\\<^sub>0 (f ` (set xs))\"\n  using assms proof (induction xs f l up \"0::nat\" rule: lsteps.induct)\n  case (2 x xs f l up)\n  consider \"l = f x\" \"\\<exists>y\\<in>set xs. l \\<le> f y\" | \"f x = l\" \"\\<not> (\\<exists>y\\<in>set xs. l \\<le> f y)\" |\n   \"f x < l\" | \"l < f x\"\n    by fastforce\n  then show ?case\n proof cases\n   assume 0: \"l = f x\" \"\\<exists>y\\<in>set xs. l \\<le> f y\"\n    then have 1: \"set xs \\<noteq> {}\"\n      using 2 by auto\n    then have \"\\<exists>xa\\<in>set xs. f x \\<le> f xa\"\n      using 0 2 by force\n    then have \"f x \\<le> Max (f ` set xs)\"\n      using 0 2 by (subst Max_ge_iff) auto\n    then have \"max (f x) (Max (f ` set xs)) = (Max (f ` set xs))\"\n      using 0 2 by (auto intro!: simp add: max_def)\n    then show ?case\n      using 0 1 2 by (subst lsteps.simps) (auto)\n  next\n    assume 0: \"f x = l\" \"\\<not> (\\<exists>y\\<in>set xs. l \\<le> f y)\"\n    then have \"Max (insert l (f ` set xs)) = l\"\n      by (intro Max_eqI) (auto)\n    moreover have \"lsteps xs f l up 0 = 0\"\n      using 0 by (subst lsteps_level_greater_fun_image) auto\n    ultimately show ?case\n       using 0 by (subst lsteps.simps) auto\n  next\n    assume 0: \"f x < l\"\n    then have 1: \"set xs \\<noteq> {}\"\n      using 2 by auto\n    then have \"\\<exists>xa\\<in>set xs. f x \\<le> f xa\"\n      using 0 2 by force\n    then have \" f x \\<le> Max (f ` set xs)\"\n      using 0 2 by (subst Max_ge_iff) auto\n    then have \"max (f x) (Max (f ` set xs)) = Max (f ` set xs)\"\n      using 0 2 by (auto intro!: simp add: max_def)\n    then show ?case\n      using 0 1 2 by (subst lsteps.simps) (auto)\n  next\n  assume \"f x > l\"\n    then show ?case\n      using 2 by (subst lsteps.simps) auto\n  qed\nqed (simp)\n\nlemma steps_height:\n  assumes \"finite A\"\n  shows   \"steps A f 0 up 0 = up * Max\\<^sub>0 (f ` A)\"\nproof -\n  have \"steps A f 0 up 0 = lsteps (rev (sorted_list_of_set A)) f 0 up 0 + up * 0\"\n    by (subst steps_lsteps) simp\n  also have \"\\<dots> = up * Max (f ` A \\<union> {0})\" if \"A \\<noteq> {}\"\n    using assms that by (subst lsteps_height) auto\n  finally show ?thesis\n    using assms by (cases \"A = {}\") (auto)\nqed\n\ncontext random_skip_list\nbegin\n\ntext \\<open>\n  We can now define the pmf describing the length of the search path in a skip list.\n  Like the height it only depends on the number of elements in the skip list's underlying set.\n\\<close>\n\ndefinition R where \"R A u l = map_pmf (\\<lambda>f. steps A f 0 u l) (SL A)\"\ndefinition R\\<^sub>N :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat pmf\" where \"R\\<^sub>N n u l = R {..<n} u l\"\n\n\nlemma R\\<^sub>N_alt_def: \"R\\<^sub>N n u l = map_pmf (\\<lambda>f. steps {..<n} f 0 u l) (SL\\<^sub>N n)\"\n  unfolding SL\\<^sub>N_def R\\<^sub>N_def R_def by simp\n\ncontext includes monad_normalisation\nbegin\n\nlemma R_R\\<^sub>N:\n  assumes \"finite A\" \"p \\<in> {0..1}\"\n  shows \"R A u l = R\\<^sub>N (card A) u l\"\nproof -\n  let ?steps = \"\\<lambda>A f. steps A f 0 u l\"\n  let ?f' = \"bij_mono_map_set_to_nat A\"\n  have \"R A u l = SL A \\<bind> (\\<lambda>f. return_pmf (?steps A f))\"\n    unfolding R_def map_pmf_def by simp\n  also have \"\\<dots> = SL\\<^sub>N (card A) \\<bind> (\\<lambda>f. return_pmf (?steps A (f \\<circ> ?f')))\"\n  proof -\n    have \"?f' x \\<notin> {..<card A}\" if \"x \\<notin> A\" for x\n      using that unfolding bij_mono_map_set_to_nat_def by (auto)\n    then show ?thesis\n      using assms bij_mono_map_set_to_nat unfolding SL_def SL\\<^sub>N_def\n      by (subst Pi_pmf_bij_betw[of _ ?f' \"{..<card A}\"])\n        (auto simp add: map_pmf_def)\n  qed\n  also have \"\\<dots> = SL\\<^sub>N (card A) \\<bind> (\\<lambda>f. return_pmf (?steps {..<card A} f))\"\n    using assms bij_mono_map_set_to_nat bij_betw_def by (subst steps_image) (fastforce)+\n  finally show ?thesis\n    unfolding R\\<^sub>N_def R_def SL\\<^sub>N_def SL_def by (simp add: map_pmf_def)\nqed\n\ntext \\<open>\n  @{const R\\<^sub>N} fulfills a recurrence relation. If we move up or to the left the ``remaining'' length of the\n  search path is again a slightly different probability distribution over the length.\n\\<close>\n\nlemma R\\<^sub>N_recurrence:\n  assumes \"0 < n\" \"p \\<in> {0<..1}\"\n  shows   \"R\\<^sub>N n u l =\n             do {\n               b \\<leftarrow> bernoulli_pmf p;\n               if b then               \\<comment> \\<open>leftwards\\<close>\n                 map_pmf (\\<lambda>n. n + l) (R\\<^sub>N (n - 1) u l)\n               else do {               \\<comment> \\<open>upwards\\<close>\n                 m \\<leftarrow> binomial_pmf (n - 1) (1 - p);\n                 map_pmf (\\<lambda>n. n + u) (R\\<^sub>N (m + 1) u l)\n               }\n             }\"\nproof -\n  define B where \"B = (\\<lambda>b. insert (n-1) {x \\<in> {..<n - 1}. \\<not> b x})\"\n  have \"R\\<^sub>N n u l = map_pmf (\\<lambda>f. steps {..<n} f 0 u l) (SL\\<^sub>N n)\"\n    by (auto simp add: R\\<^sub>N_def R_def SL\\<^sub>N_def)\n  also have \"\\<dots> = map_pmf (\\<lambda>f. steps {..<n} f 0 u l)\n                          (map_pmf (\\<lambda>(y, f). f(n-1 := y)) (pair_pmf (geometric_pmf p) (SL\\<^sub>N (n - 1))))\"\n  proof -\n    have \"{..<n} = insert (n - Suc 0) {..<n - 1}\"\n      using assms by force\n    then have \"(Pi_pmf {..<n} 0 (\\<lambda>_. geometric_pmf p)) =\n                map_pmf (\\<lambda>(y, f). f(n - 1 := y)) (pair_pmf (geometric_pmf p)\n                     (Pi_pmf {..<n-1} 0 (\\<lambda>_. geometric_pmf p)))\"\n      using assms\n      by (subst Pi_pmf_insert[of \"{..<n-1}\" \"n-1\" 0 \"\\<lambda>_. geometric_pmf p\", symmetric])  (auto)\n    then show ?thesis\n      by (simp add: SL\\<^sub>N_def SL_def)\n  qed\n  also have \"\\<dots> =\n        do { g \\<leftarrow> geometric_pmf p;\n             f \\<leftarrow> SL\\<^sub>N (n - 1);\n             return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l)}\"\n    by (simp add: case_prod_beta map_pmf_def pair_pmf_def)\n  also have \"\\<dots> =\n        do { b \\<leftarrow>  bernoulli_pmf p;\n             g \\<leftarrow> if b then return_pmf 0 else map_pmf Suc (geometric_pmf p);\n             f \\<leftarrow> SL\\<^sub>N (n - 1);\n             return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l)}\"\n    using assms by (subst geometric_bind_pmf_unfold) (auto)\n  also have \"\\<dots> =\n        do { b \\<leftarrow> bernoulli_pmf p;\n             if b\n               then do { g \\<leftarrow> return_pmf 0;\n                         f \\<leftarrow> SL\\<^sub>N (n - 1);\n                         return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l) }\n               else do { g \\<leftarrow> map_pmf Suc (geometric_pmf p);\n                         f \\<leftarrow> SL\\<^sub>N (n - 1);\n                         return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l) }}\"\n    by (subst bind_pmf_if') (auto)\n  also have \"do { g \\<leftarrow> return_pmf 0;\n                       f \\<leftarrow> SL\\<^sub>N (n - 1);\n                       return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l) }  =\n              do { f \\<leftarrow> SL\\<^sub>N (n - 1);\n                        return_pmf (steps {..<n} (f(n - 1 := 0)) 0 u l) }\"\n    by (subst bind_return_pmf) auto\n  also have \"\\<dots> = map_pmf (\\<lambda>n. n + l) (map_pmf (\\<lambda>f. steps {..<n - 1} f 0 u l) (SL\\<^sub>N (n - 1)))\"\n  proof -\n    have I: \"{..<n} - {n - Suc 0} = {..<n - Suc 0}\"\n      by fastforce\n    have \"Max {..<n} = n - Suc 0\"\n      using assms by (intro Max_eqI) (auto)\n    then have \"steps {..<n} (f(n - 1 := 0)) 0 u l = l + steps {..<n - 1} f 0 u l\" for f\n      using assms by (subst steps.simps) (auto intro!: steps_cong simp add: I simp add: Let_def)\n    then show ?thesis\n      by (auto simp add: add_ac map_pmf_def)\n  qed\n  also have \"\\<dots> = map_pmf (\\<lambda>n. n + l) (R\\<^sub>N (n - 1) u l)\"\n    unfolding R\\<^sub>N_def R_def SL\\<^sub>N_def by simp\n  also have \"map_pmf Suc (geometric_pmf p) \\<bind>\n             (\\<lambda>g. SL\\<^sub>N (n - 1) \\<bind>\n             (\\<lambda>f. return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l)))\n             =\n             Pi_pmf {..<n - 1} True (\\<lambda>_. bernoulli_pmf p) \\<bind>\n             (\\<lambda>b. map_pmf Suc (geometric_pmf p) \\<bind>\n             (\\<lambda>g. Pi_pmf {x \\<in> {..<n - 1}. \\<not> b x} 0 (\\<lambda>_. map_pmf Suc (geometric_pmf p)) \\<bind>\n             (\\<lambda>f. return_pmf (steps {..<n} (f(n - 1 := g)) 0 u l))))\"\n    using assms unfolding SL\\<^sub>N_def SL_def by (subst Pi_pmf_geometric_filter) (auto)\n  also have \"\\<dots> =\n             do {\n             b \\<leftarrow> Pi_pmf {..<n - 1} True (\\<lambda>_. bernoulli_pmf p);\n             f \\<leftarrow> Pi_pmf (insert (n-1) {x \\<in> {..<n - 1}. \\<not> b x}) 0 (\\<lambda>_. map_pmf Suc (geometric_pmf p));\n             return_pmf (steps {..<n} f 0 u l)}\" (is \"_ = ?rhs\")\n    using assms by (subst Pi_pmf_insert') (auto)\n  also have \"\\<dots> =\n             do {\n               b \\<leftarrow> Pi_pmf {..<n - 1} True (\\<lambda>_. bernoulli_pmf p);\n               f \\<leftarrow> Pi_pmf (B b) 1 (\\<lambda>_. map_pmf Suc (geometric_pmf p));\n               return_pmf (steps {..<n} (\\<lambda>x. if x \\<in> (B b) then f x else 0) 0 u l)}\"\n    by (subst Pi_pmf_default_swap[symmetric, of _ _ _ 1]) (auto simp add: map_pmf_def B_def)\n  also have \"\\<dots> =\n             do {\n               b \\<leftarrow> Pi_pmf {..<n - 1} True (\\<lambda>_. bernoulli_pmf p);\n               f \\<leftarrow> SL (B b);\n               return_pmf (steps {..<n} (\\<lambda>x. if x \\<in> (B b) then Suc (f x) else 0) 0 u l)}\"\n  proof -\n    have *: \"(Suc \\<circ> f) x = Suc (f x)\" for x and f::\"nat \\<Rightarrow> nat\"\n      by simp\n    have \"(\\<lambda>f. return_pmf (steps {..<n} (\\<lambda>x. if x \\<in> B b then (Suc \\<circ> f) x else 0) 0 u l)) =\n          (\\<lambda>f. return_pmf (steps {..<n} (\\<lambda>x. if x \\<in> B b then Suc (f x) else 0) 0 u l))\" for b\n      by (subst *) (simp)\n    then show ?thesis\n      by (subst Pi_pmf_map[of _ _ 0]) (auto simp add: map_pmf_def B_def SL_def)\n  qed\n  also have \"\\<dots> =\n               do {\n               b \\<leftarrow> Pi_pmf {..<n - 1} True (\\<lambda>_. bernoulli_pmf p);\n               r \\<leftarrow> R (B b) u l;\n               return_pmf (u + r)}\"\n  proof -\n    have \"steps {..<n} (\\<lambda>x. if x \\<in> B b then Suc (f x) else 0) 0 u l = u + steps (B b) f 0 u l\"\n      for f b\n    proof -\n      have \"Max {..<n} = n - 1\"\n        using assms by (intro Max_eqI) auto\n      then have \"steps {..<n} (\\<lambda>x. if x \\<in> B b then Suc (f x) else 0) 0 u l =\n              u + (steps {..<n} (\\<lambda>x. if x \\<in> (B b) then Suc (f x) else 0) 1 u l)\"\n        unfolding B_def using assms by (subst steps.simps) (auto simp add: Let_def)\n      also have \"steps {..<n} (\\<lambda>x. if x \\<in> (B b) then Suc (f x) else 0) 1 u l =\n                   steps (B b) (\\<lambda>x. if x \\<in> (B b) then Suc (f x) else 0) 1 u l\"\n      proof -\n        have \"{x \\<in> {..<n}. 1 \\<le> (if x \\<in> B b then Suc (f x) else 0)} = B b\"\n          using assms unfolding B_def by force\n        then show ?thesis\n          by (subst steps_smaller_set[of _ 1]) auto\n      qed\n      also have \"\\<dots> = steps (B b) (\\<lambda>x. f x + 1) 1 u l\"\n        by (rule steps_cong) (auto)\n      also have \"\\<dots> = steps (B b) f 0 u l\"\n        by (subst (2) steps_f_add'[of _ _ _ _ _ 1]) simp\n      finally show ?thesis\n        by auto\n    qed\n    then show ?thesis\n      by (simp add: R_def map_pmf_def)\n  qed\n  also have \"\\<dots> = do {\n                   b \\<leftarrow> Pi_pmf {..<n - 1} False (\\<lambda>_. bernoulli_pmf (1 - p));\n                   let m = 1 + card {x. x < n - 1 \\<and> b x};\n                   r \\<leftarrow> R {..<m} u l;\n                   return_pmf (u + r)}\"\n  proof -\n    have *: \"card (insert (n - Suc 0) {x. x < n - 1 \\<and> b x}) =\n              (Suc (card {x. x < n - 1 \\<and> b x}))\" for b\n      using assms by (auto simp add: card_insert_if)\n    have \"Pi_pmf {..<n - 1} True (\\<lambda>_. bernoulli_pmf p) =\n              Pi_pmf {..<n - 1} True (\\<lambda>_. map_pmf Not (bernoulli_pmf (1 - p)))\"\n      using assms by (subst bernoulli_pmf_Not) auto\n    also have \"\\<dots> = map_pmf ((\\<circ>) Not) (Pi_pmf {..<n - 1}  False (\\<lambda>_. bernoulli_pmf (1 - p)))\"\n      using assms by (subst Pi_pmf_map[of _ _ False]) auto\n    finally show ?thesis\n      unfolding B_def using assms *\n      by (subst R_R\\<^sub>N) (auto simp add: R_R\\<^sub>N map_pmf_def)\n  qed\n  also have \"\\<dots> = binomial_pmf (n - 1) (1 - p) \\<bind> (\\<lambda>m. map_pmf (\\<lambda>n. n + u) (R\\<^sub>N (m + 1) u l))\"\n    using assms\n    by (subst binomial_pmf_altdef'[where A = \"{..<n - 1}\" and dflt = \"False\"])\n      (auto simp add: R\\<^sub>N_def R_def SL_def map_pmf_def ac_simps)\n  finally show ?thesis\n    by simp\nqed\n\nend (* context includes monad_normalisation *)\n\ntext \\<open>\n  The expected height and length of search path defined as non-negative integral. It's easier\n  to prove the recurrence relation of the expected length of the search path using non-negative\n  integrals.\n\\<close>\n\ndefinition NH\\<^sub>N where \"NH\\<^sub>N n = nn_integral (H\\<^sub>N n) real\"\ndefinition NR\\<^sub>N where \"NR\\<^sub>N n u l = nn_integral (R\\<^sub>N n u l) real\"\n\nlemma NH\\<^sub>N_EH\\<^sub>N:\n  assumes \"p \\<in> {0<..<1}\"\n  shows \"NH\\<^sub>N n = EH\\<^sub>N n\"\n  using assms EH\\<^sub>N_bounds unfolding EH\\<^sub>N_def NH\\<^sub>N_def by (subst nn_integral_eq_integral) (auto)\n\nlemma R\\<^sub>N_0 [simp]: \"R\\<^sub>N 0 u l = return_pmf 0\"\n  unfolding R\\<^sub>N_def R_def SL_def by (auto simp add: steps.simps)\n\nlemma NR\\<^sub>N_bounds:\n  fixes u l::nat\n  shows \"NR\\<^sub>N n u l \\<le> l * n + u * NH\\<^sub>N n\"\nproof -\n  have \"NR\\<^sub>N n u l = \\<integral>\\<^sup>+ x. x \\<partial>measure_pmf (R\\<^sub>N n u l)\"\n    unfolding NR\\<^sub>N_def R\\<^sub>N_alt_def\n    by (simp add: ennreal_of_nat_eq_real_of_nat)\n  also have \"\\<dots> \\<le> \\<integral>\\<^sup>+ x. x \\<partial>(measure_pmf (map_pmf (\\<lambda>f. l * n + u * Max\\<^sub>0 (f ` {..<n})) (SL\\<^sub>N n)))\"\n    using of_nat_mono[OF steps_smaller_card_Max_fun'[of \"{..<n}\" 0 _ u l]] unfolding R\\<^sub>N_alt_def\n    by (cases \"n = 0\") (auto intro!: nn_integral_mono)\n  also have \"\\<dots> = l * n + u * NH\\<^sub>N n\"\n    unfolding NH\\<^sub>N_def H\\<^sub>N_def H_def SL\\<^sub>N_def\n    by (auto simp add: nn_integral_add nn_integral_cmult ennreal_of_nat_eq_real_of_nat ennreal_mult)\n  finally show \"NR\\<^sub>N n u l \\<le> l * n + u * NH\\<^sub>N n\"\n    by simp\nqed\n\nlemma NR\\<^sub>N_recurrence:\n  assumes \"0 < n\" \"p \\<in> {0<..<1}\"\n  shows \"NR\\<^sub>N n u l = (p * (l + NR\\<^sub>N (n - 1) u l) +\n                     q * (u + (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u l * (pmf (binomial_pmf (n - 1) q) k))))\n                     / (1 - (q ^ n))\"\nproof -\n  define B where \"B = (\\<lambda>n k. pmf (binomial_pmf n q) k)\"\n  have q: \"q \\<in> {0<..<1}\"\n    using assms unfolding q_def by auto\n  then have \"q ^ n < 1\"\n    using assms power_Suc_less_one by (induction n) (auto)\n  then have qn: \"q ^ n \\<in> {0<..<1}\"\n    using assms q by (auto)\n  have \"NR\\<^sub>N n u l = p * (l + NR\\<^sub>N (n - 1) u l) +\n                    q * (u + \\<integral>\\<^sup>+ k. NR\\<^sub>N (k + 1) u l  \\<partial>measure_pmf (binomial_pmf (n - 1) q))\"\n    using assms unfolding NR\\<^sub>N_def\n    by(subst R\\<^sub>N_recurrence)\n      (auto simp add: field_simps nn_integral_add q_def ennreal_of_nat_eq_real_of_nat)\n  also have \"(\\<integral>\\<^sup>+ m. NR\\<^sub>N (m + 1) u l  \\<partial>measure_pmf (binomial_pmf (n - 1) q)) =\n    (\\<Sum>k\\<le>n - 1. NR\\<^sub>N (k + 1) u l * B (n - 1) k)\"\n    using assms unfolding B_def q_def\n    by (auto simp add: nn_integral_measure_pmf_finite)\n  also have \"\\<dots> = (\\<Sum>k\\<in>{..<n - 1} \\<union> {n - 1}. NR\\<^sub>N (k + 1) u l * B (n - 1) k)\"\n    by (rule sum.cong) (auto)\n  also have \"\\<dots> = (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u l * B (n - 1) k) + NR\\<^sub>N n u l * q ^ (n - 1)\"\n    unfolding B_def q_def using assms by (subst sum.union_disjoint) (auto)\n  finally have \"NR\\<^sub>N n u l = p * (l + NR\\<^sub>N (n - 1) u l) +\n                            q * ((\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u l * B (n - 1) k) + u) +\n                            NR\\<^sub>N n u l * (q ^ (n - 1)) * q\"\n    using assms by (auto simp add: field_simps numerals)\n  also have \"NR\\<^sub>N n u l * (q ^ (n - 1)) * q = (q ^ n) * NR\\<^sub>N n u l\"\n    using q power_minus_mult[of _ q] assms\n    by (subst mult_ac, subst ennreal_mult[symmetric], auto simp add: mult_ac)\n  finally have 1: \"NR\\<^sub>N n u l = p * (l + NR\\<^sub>N (n - 1) u l) +\n                               q * (u + (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u l * (B (n - 1) k))) +\n                               (q ^ n) * NR\\<^sub>N n u l \"\n    by (simp add: add_ac)\n  have \"x - z = y\" if \"x = y + z\" \"z \\<noteq> \\<top>\" for x y z::ennreal\n     using that by (subst that) (auto)\n   have \"NR\\<^sub>N n u l \\<le> l * n + u * NH\\<^sub>N n\"\n     using NR\\<^sub>N_bounds by (auto simp add: ennreal_of_nat_eq_real_of_nat)\n   also have \"NH\\<^sub>N n = EH\\<^sub>N n\"\n     using assms NH\\<^sub>N_EH\\<^sub>N by auto\n   also have \"(l * n) + u * ennreal (EH\\<^sub>N n) < \\<top>\"\n     by (simp add: ennreal_mult_less_top of_nat_less_top)\n   finally have 3: \"NR\\<^sub>N n u l \\<noteq> \\<top>\"\n     by simp\n  have 2: \"x = y / (1 - a)\" if \"x = y + a * x\" and t: \"x \\<noteq> \\<top>\" \"a \\<in> {0<..<1}\" for x y::ennreal\n          and a::real\n  proof -\n    have \"y = x - a * x\"\n      using t by (subst that) (auto simp add: ennreal_mult_eq_top_iff)\n    also have \"\\<dots> = x * (ennreal 1 - ennreal a)\"\n      using that by (auto simp add: mult_ac ennreal_right_diff_distrib)\n    also have \"ennreal 1 - ennreal a = ennreal (1 - a)\"\n      using that by (subst ennreal_minus) (auto)\n    also have \"x * (1 - a) / (1 - a) = x\"\n      using that ennreal_minus_eq_0 not_less by (subst mult_divide_eq_ennreal) auto\n    finally show ?thesis\n      by simp\n  qed\n  have \"NR\\<^sub>N n u l = (p * (l + NR\\<^sub>N (n - 1) u l) +\n                     q * (u + (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u l * (B (n - 1) k))))\n                   / (1 - (q ^ n))\"\n    using 1 3 assms qn by (intro 2) auto\n  then show ?thesis\n    unfolding B_def by simp\nqed\n\nlemma NR\\<^sub>n_NH\\<^sub>N: \"NR\\<^sub>N n u 0 = u * NH\\<^sub>N n\"\nproof -\n  have \"NR\\<^sub>N n u 0 = \\<integral>\\<^sup>+ f. steps {..<n} f 0 u 0 \\<partial>measure_pmf (SL\\<^sub>N n)\"\n    unfolding NR\\<^sub>N_def R\\<^sub>N_alt_def by (auto simp add: ennreal_of_nat_eq_real_of_nat)\n  also have \"\\<dots> = \\<integral>\\<^sup>+ f. of_nat u * of_nat (Max\\<^sub>0 (f ` {..<n})) \\<partial>measure_pmf (SL\\<^sub>N n)\"\n    by (intro nn_integral_cong) (auto simp add: steps_height)\n  also have \"\\<dots> = u * NH\\<^sub>N n\"\n    by (auto simp add: NH\\<^sub>N_def H\\<^sub>N_def H_def SL\\<^sub>N_def  ennreal_of_nat_eq_real_of_nat nn_integral_cmult)\n  finally show ?thesis\n    by simp\nqed\n\nlemma NR\\<^sub>N_recurrence':\n  assumes \"0 < n\" \"p \\<in> {0<..<1}\"\n  shows \"NR\\<^sub>N n u l = (p * l + p * NR\\<^sub>N (n - 1) u l +\n                     q * u + q * (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u l * (pmf (binomial_pmf (n - 1) q) k)))\n                     / (1 - (q ^ n))\"\n  unfolding NR\\<^sub>N_recurrence[OF assms]\n  by (auto simp add: field_simps ennreal_of_nat_eq_real_of_nat ennreal_mult' ennreal_mult'')\n\n\nlemma NR\\<^sub>N_l_0:\n  assumes \"0 < n\" \"p \\<in> {0<..<1}\"\n  shows \"NR\\<^sub>N n u 0 = (p * NR\\<^sub>N (n - 1) u 0 +\n                     q * (u + (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) u 0 * (pmf (binomial_pmf (n - 1) q) k))))\n                     / (1 - (q ^ n))\"\n  unfolding NR\\<^sub>N_recurrence[OF assms] by (simp)\n\nlemma NR\\<^sub>N_u_0:\n  assumes \"0 < n\" \"p \\<in> {0<..<1}\"\n  shows \"NR\\<^sub>N n 0 l = (p * (l + NR\\<^sub>N (n - 1) 0 l) +\n                     q * (\\<Sum>k<n - 1. NR\\<^sub>N (k + 1) 0 l * (pmf (binomial_pmf (n - 1) q) k)))\n                     / (1 - (q ^ n))\"\n  unfolding NR\\<^sub>N_recurrence[OF assms] by (simp)\n\nlemma NR\\<^sub>N_0[simp]: \"NR\\<^sub>N 0 u l = 0\"\n  unfolding NR\\<^sub>N_def R\\<^sub>N_def R_def by (auto)\n\nlemma NR\\<^sub>N_1:\n  assumes \"p \\<in> {0<..<1}\"\n  shows \"NR\\<^sub>N 1 u l = (u * q + l * p) / p\"\nproof -\n  have \"NR\\<^sub>N 1 u l = (ennreal p * of_nat l + ennreal q * of_nat u) / ennreal (1 - q)\"\n    using assms by (subst NR\\<^sub>N_recurrence) auto\n  also have \"(ennreal p * of_nat l + ennreal q * of_nat u) = (u * q + l * p)\"\n    using assms q_def by (subst ennreal_plus)\n      (auto simp add: field_simps ennreal_mult' ennreal_of_nat_eq_real_of_nat)\n  also have \"\\<dots> / ennreal (1 - q) = ennreal ((u * q + l * p) / (1 - q))\"\n     using q_def assms by (intro divide_ennreal) auto\n  finally show ?thesis\n    unfolding q_def by simp\nqed\n\nlemma NR\\<^sub>N_NR\\<^sub>N_l_0:\n  assumes n: \"0 < n\" and p: \"p \\<in> {0<..<1}\" and \"u \\<ge> 1\"\n  shows \"NR\\<^sub>N n u 0 = (u * q / (u * q + l * p)) * NR\\<^sub>N n u l\"\n  using n proof (induction n rule: less_induct)\n  case (less i)\n  have 1: \"0 < u * q\"\n    unfolding q_def using assms by simp\n  moreover have \"0 \\<le> l * p\"\n    using assms by auto\n  ultimately have 2: \"0 < u * q + l * p\"\n    by arith\n  define c where \"c = ennreal (u * q / (u * q + l * p))\"\n  have [simp]: \"c / c = 1\"\n  proof -\n    have \"u * q / (u * q + l * p) \\<noteq> 0\"\n      using assms q_def 2 by auto\n    then show ?thesis\n      unfolding c_def using p q_def by (auto intro!: ennreal_divide_self)\n  qed\n  show ?case\n  proof (cases \"i = 1\")\n    case True\n    have \"c * NR\\<^sub>N i u l = c * ((u * q + l * p) / p)\"\n      unfolding c_def True by (subst NR\\<^sub>N_1[OF p]) auto\n    also have \"\\<dots> = ennreal ((u * q / (u * q + l * p)) * ((u * q + l * p) / p))\"\n      unfolding c_def using assms q_def by (subst ennreal_mult'') auto\n    also have \"(u * q / (u * q + l * p)) * ((u * q + l * p) / p) = u * q / p\"\n    proof -\n      have I: \"(a / b) * (b / c) = a / c\" if \"0 < b\" for a b c::\"real\"\n        using that by (auto)\n      show ?thesis\n        using 2 q_def by (intro I) auto\n    qed\n    also have \"\\<dots> = NR\\<^sub>N i u 0\"\n      unfolding True c_def by (subst NR\\<^sub>N_1[OF p]) (auto)\n    finally show ?thesis\n      unfolding c_def using True by simp\n  next\n    case False\n    then have i: \"i > 1\"\n      using less by auto\n    define c where \"c = ennreal (u * q / (u * q + l * p))\"\n    define B where \"B = (\\<Sum>k<i - 1. NR\\<^sub>N (k + 1) u l * ennreal (pmf (binomial_pmf (i - 1) q) k))\"\n    have \"NR\\<^sub>N i u 0 = (p * NR\\<^sub>N (i - 1) u 0 +\n                     q * (u + (\\<Sum>k<i - 1. NR\\<^sub>N (k + 1) u 0 * (pmf (binomial_pmf (i - 1) q) k))))\n                     / (1 - (q ^ i))\"\n      using less assms by (subst NR\\<^sub>N_l_0) auto\n    also have \"q * (u + (\\<Sum>k<i - 1. NR\\<^sub>N (k + 1) u 0 * (pmf (binomial_pmf (i - 1) q) k))) =\n             q * u + q * (\\<Sum>k<i - 1. NR\\<^sub>N (k + 1) u 0 * (pmf (binomial_pmf (i - 1) q) k))\"\n      using assms q_def\n      by (auto simp add: field_simps ennreal_of_nat_eq_real_of_nat ennreal_mult)\n    also have \"NR\\<^sub>N (i - 1) u 0 = c * NR\\<^sub>N (i - 1) u l\"\n      unfolding c_def using less i by (intro less) (auto)\n    also have \"(\\<Sum>k<i - 1. NR\\<^sub>N (k + 1) u 0 * ennreal (pmf (binomial_pmf (i - 1) q) k)) =\n             (\\<Sum>k<i - 1. c * NR\\<^sub>N (k + 1) u l * ennreal (pmf (binomial_pmf (i - 1) q) k))\"\n      by (auto intro!: sum.cong simp add: less c_def)\n    also have \"\\<dots> = c * B\"\n      unfolding B_def by (subst sum_distrib_left) (auto intro!: sum.cong mult_ac)\n    also have \"q * (c * B) = c * (q * B)\"\n      by (simp add: mult_ac)\n    also have \"ennreal (q * real u) = q * u * ((u * q + l * p) / (u * q + l * p))\"\n      using assms 2 by (auto simp add: field_simps q_def)\n    also have \"\\<dots> = c * (real u * q + real l * p)\"\n      unfolding c_def using 2 by (subst ennreal_mult''[symmetric]) (auto simp add: mult_ac)\n    also have \"c * ennreal (real u * q + real l * p) + c * (ennreal q * B) =\n             c * (ennreal (real u * q + real l * p) + (ennreal q * B))\"\n      by (auto simp add: field_simps)\n    also have \"ennreal p * (c * NR\\<^sub>N (i - 1) u l) = c * (ennreal p * NR\\<^sub>N (i - 1) u l)\"\n      by (simp add: mult_ac)\n    also have \"(c * (ennreal p * NR\\<^sub>N (i - 1) u l) + c * (ennreal (u * q + l * p) + ennreal q * B))\n            = c * ((ennreal p * NR\\<^sub>N (i - 1) u l) + (ennreal (u * q + l * p) + ennreal q * B))\"\n      by (auto simp add: field_simps)\n    also have \" c * (ennreal p * NR\\<^sub>N (i - 1) u l + (ennreal (u * q + l * p) + ennreal q * B)) / ennreal (1 - q ^ i)\n         =  c * ((ennreal p * NR\\<^sub>N (i - 1) u l + (ennreal (u * q + l * p) + ennreal q * B)) / ennreal (1 - q ^ i))\"\n      by (auto simp add: ennreal_times_divide)\n    also have \"(ennreal p * NR\\<^sub>N (i - 1) u l + (ennreal (real u * q + real l * p) + ennreal q * B)) / ennreal (1 - q ^ i)\n        = NR\\<^sub>N i u l\"\n      apply(subst (2) NR\\<^sub>N_recurrence')\n      using i assms q_def by\n        (auto simp add: field_simps B_def ennreal_of_nat_eq_real_of_nat ennreal_mult' ennreal_mult'')\n    finally show ?thesis\n      unfolding c_def by simp\n  qed\nqed\n\ntext \\<open>\n  Assigning 1 as the cost for going up and/or left, we can now show the relation between the\n  expected length of the reverse search path and the expected height.\n\\<close>\n\ndefinition EL\\<^sub>N where \"EL\\<^sub>N n = measure_pmf.expectation (R\\<^sub>N n 1 1) real\"\n\n\ntheorem EH\\<^sub>N_EL\\<^sub>s\\<^sub>p:\n  assumes \"p \\<in> {0<..<1}\"\n  shows \"1 / q * EH\\<^sub>N n = EL\\<^sub>N n\"\nproof -\n  have 1: \"ennreal (1 / y * x) = r\" if \"ennreal x = y * r\" \"x \\<ge> 0\" \"y > 0\"\n    for x y::real and r::ennreal\n  proof -\n    have \"ennreal ((1 / y) * x) = ennreal (1 / y) * ennreal x\"\n      using that apply(subst ennreal_mult'') by auto\n    also note that(1)\n    also have \"ennreal (1 / y) * (ennreal y * r) = ennreal ((1 / y) * y) * r\"\n      using that by (subst ennreal_mult'') (auto simp add: mult_ac)\n    also have \"(1 / y) * y = 1\"\n      using that by (auto)\n    finally show ?thesis\n      by auto\n  qed\n  have \"EH\\<^sub>N n = NH\\<^sub>N n\"\n    using NH\\<^sub>N_EH\\<^sub>N assms by auto\n  also have \"NH\\<^sub>N n = NR\\<^sub>N n 1 0\"\n    using NR\\<^sub>n_NH\\<^sub>N by auto\n  also have \"NR\\<^sub>N n 1 0 = q * NR\\<^sub>N n 1 1\" if \"n > 0\"\n    using NR\\<^sub>N_NR\\<^sub>N_l_0[of _ 1 1] that assms q_def by force\n  finally have \"ennreal (EH\\<^sub>N n) = q * NR\\<^sub>N n 1 1\" if \"n > 0\"\n    using that by blast\n  then have \"1 / q * EH\\<^sub>N n = NR\\<^sub>N n 1 1\" if \"n > 0\"\n    using that assms q_def by (intro 1) (auto simp add: EH\\<^sub>N_def H\\<^sub>N_def H_def)\n  moreover have \"1 / q * EH\\<^sub>N n = NR\\<^sub>N n 1 1\" if \"n = 0\"\n    unfolding that by (auto simp add: EH\\<^sub>N_def H\\<^sub>N_def H_def)\n  ultimately have 2: \"ennreal (1 / q * EH\\<^sub>N n) = NR\\<^sub>N n 1 1\"\n    by blast\n  also have \"NR\\<^sub>N n 1 1 = EL\\<^sub>N n\"\n    using 2 assms EH\\<^sub>N_bounds unfolding EL\\<^sub>N_def NR\\<^sub>N_def\n    by(subst nn_integral_eq_integral)\n      (auto intro!: integrableI_nn_integral_finite[where x=\"EH\\<^sub>N n / q\"])\n  finally show ?thesis\n    using assms q_def ennreal_inj unfolding EL\\<^sub>N_def EH\\<^sub>N_def H\\<^sub>N_def H_def SL_def\n    by (auto)\nqed\n\nend (* context random_skip_list *)\n\nthm random_skip_list.EH\\<^sub>N_EL\\<^sub>s\\<^sub>p[unfolded random_skip_list.q_def]\n    random_skip_list.EH\\<^sub>N_bounds'[unfolded random_skip_list.q_def]\n\n\nend\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Skip_Lists/Skip_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7878430533791013}}
{"text": "theory Example_locale\n  imports Main\nbegin\n(*locale: a functor - maps parameters and a specification \\<longrightarrow> a list of declarations*)\n(*parameter: le - a binary predicate with \\<sqsubseteq>*)\n\nlocale partial_order =\n  fixes le :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubseteq>\" 50) (*declares a local parameter*)\n  assumes refl [intro, simp]: \"x \\<sqsubseteq> x\" (* local premises*)\n  and anti_sym[intro]: \"\\<lbrakk> x \\<sqsubseteq> y; y\\<sqsubseteq> x \\<rbrakk> \\<Longrightarrow> x = y\"\n  and trans[trans]: \"\\<lbrakk> x \\<sqsubseteq> y; y\\<sqsubseteq> z \\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> z\" (*\\<And>x y z.\\<lbrakk> x \\<sqsubseteq> y; y\\<sqsubseteq> z \\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> z *)\nbegin\ndefinition (in partial_order) \n  less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubset>\" 50)\n  where \"(x \\<sqsubset> y) = (x \\<sqsubseteq> y) \\<and> (x \\<noteq> y)\"\nend\nprint_locale! partial_order\nthm partial_order_def\n(*\ndefinition (in partial_order)\n  less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubset>\" 50)\n  where \"(x \\<sqsubset> y) = (x \\<sqsubseteq> y) \\<and> x \\<noteq> y\"\n*)\nlocale total_order = partial_order +\n  assumes total: \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n\nlemma (in total_order) less_total: \"x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x\"\n\n\nend", "meta": {"author": "TrinhLK", "repo": "Isabelle-Code", "sha": "6eb41d730967df6b4dca606376a6825d16968c20", "save_path": "github-repos/isabelle/TrinhLK-Isabelle-Code", "path": "github-repos/isabelle/TrinhLK-Isabelle-Code/Isabelle-Code-6eb41d730967df6b4dca606376a6825d16968c20/Example_locale.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7875462220364668}}
{"text": "(*  Title:      FOL/ex/Natural_Numbers.thy\n    Author:     Markus Wenzel, TU Munich\n*)\n\nsection \\<open>Natural numbers\\<close>\n\ntheory Natural_Numbers\nimports FOL\nbegin\n\ntext \\<open>\n  Theory of the natural numbers: Peano's axioms, primitive recursion.\n  (Modernized version of Larry Paulson's theory \"Nat\".)  \\medskip\n\\<close>\n\ntypedecl nat\ninstance nat :: \\<open>term\\<close> ..\n\naxiomatization\n  Zero :: \\<open>nat\\<close>    (\\<open>0\\<close>) and\n  Suc :: \\<open>nat => nat\\<close> and\n  rec :: \\<open>[nat, 'a, [nat, 'a] => 'a] => 'a\\<close>\nwhere\n  induct [case_names 0 Suc, induct type: nat]:\n    \\<open>P(0) ==> (!!x. P(x) ==> P(Suc(x))) ==> P(n)\\<close> and\n  Suc_inject: \\<open>Suc(m) = Suc(n) ==> m = n\\<close> and\n  Suc_neq_0: \\<open>Suc(m) = 0 ==> R\\<close> and\n  rec_0: \\<open>rec(0, a, f) = a\\<close> and\n  rec_Suc: \\<open>rec(Suc(m), a, f) = f(m, rec(m, a, f))\\<close>\n\nlemma Suc_n_not_n: \\<open>Suc(k) \\<noteq> k\\<close>\nproof (induct \\<open>k\\<close>)\n  show \\<open>Suc(0) \\<noteq> 0\\<close>\n  proof\n    assume \\<open>Suc(0) = 0\\<close>\n    then show \\<open>False\\<close> by (rule Suc_neq_0)\n  qed\nnext\n  fix n assume hyp: \\<open>Suc(n) \\<noteq> n\\<close>\n  show \\<open>Suc(Suc(n)) \\<noteq> Suc(n)\\<close>\n  proof\n    assume \\<open>Suc(Suc(n)) = Suc(n)\\<close>\n    then have \\<open>Suc(n) = n\\<close> by (rule Suc_inject)\n    with hyp show \\<open>False\\<close> by contradiction\n  qed\nqed\n\n\ndefinition add :: \\<open>nat => nat => nat\\<close>    (infixl \\<open>+\\<close> 60)\n  where \\<open>m + n = rec(m, n, \\<lambda>x y. Suc(y))\\<close>\n\nlemma add_0 [simp]: \\<open>0 + n = n\\<close>\n  unfolding add_def by (rule rec_0)\n\nlemma add_Suc [simp]: \\<open>Suc(m) + n = Suc(m + n)\\<close>\n  unfolding add_def by (rule rec_Suc)\n\n\n\nlemma add_0_right: \\<open>m + 0 = m\\<close>\n  by (induct \\<open>m\\<close>) simp_all\n\nlemma add_Suc_right: \\<open>m + Suc(n) = Suc(m + n)\\<close>\n  by (induct \\<open>m\\<close>) simp_all\n\nlemma\n  assumes \\<open>!!n. f(Suc(n)) = Suc(f(n))\\<close>\n  shows \\<open>f(i + j) = i + f(j)\\<close>\n  using assms by (induct \\<open>i\\<close>) simp_all\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/FOL/ex/Natural_Numbers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.916109606718245, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7875462170957805}}
{"text": "(* Author: Tobias Nipkow *)\n\ntheory List_Index imports Main begin\n\ntext {* \\noindent\nThis theory collects functions for index-based manipulation of lists.\n*}\n\nsubsection {* Finding an index *}\n\ntext{*\nThis subsection defines three functions for finding the index of items in a list:\n\\begin{description}\n\\item[@{text \"find_index P xs\"}] finds the index of the first element in\n @{text xs} that satisfies @{text P}.\n\\item[@{text \"index xs x\"}] finds the index of the first occurrence of\n @{text x} in @{text xs}.\n\\item[@{text \"last_index xs x\"}] finds the index of the last occurrence of\n @{text x} in @{text xs}.\n\\end{description}\nAll functions return @{term \"length xs\"} if @{text xs} does not contain a\nsuitable element.\n\nThe argument order of @{text find_index} follows the function of the same\nname in the Haskell standard library. For @{text index} (and @{text\nlast_index}) the order is intentionally reversed: @{text index} maps\nlists to a mapping from elements to their indices, almost the inverse of\nfunction @{text nth}. *}\n\nprimrec find_index :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"find_index _ [] = 0\" |\n\"find_index P (x#xs) = (if P x then 0 else find_index P xs + 1)\"\n\ndefinition index :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n\"index xs = (\\<lambda>a. find_index (\\<lambda>x. x=a) xs)\"\n\ndefinition last_index :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n\"last_index xs x =\n (let i = index (rev xs) x; n = size xs\n  in if i = n then i else n - (i+1))\"\n\nlemma find_index_le_size: \"find_index P xs <= size xs\"\nby(induct xs) simp_all\n\nlemma index_le_size: \"index xs x <= size xs\"\nby(simp add: index_def find_index_le_size)\n\nlemma last_index_le_size: \"last_index xs x <= size xs\"\nby(simp add: last_index_def Let_def index_le_size)\n\nlemma index_Nil[simp]: \"index [] a = 0\"\nby(simp add: index_def)\n\nlemma index_Cons[simp]: \"index (x#xs) a = (if x=a then 0 else index xs a + 1)\"\nby(simp add: index_def)\n\nlemma index_append: \"index (xs @ ys) x =\n  (if x : set xs then index xs x else size xs + index ys x)\"\nby (induct xs) simp_all\n\nlemma index_conv_size_if_notin[simp]: \"x \\<notin> set xs \\<Longrightarrow> index xs x = size xs\"\nby (induct xs) auto\n\nlemma find_index_eq_size_conv:\n  \"size xs = n \\<Longrightarrow> (find_index P xs = n) = (ALL x : set xs. ~ P x)\"\nby(induct xs arbitrary: n) auto\n\nlemma size_eq_find_index_conv:\n  \"size xs = n \\<Longrightarrow> (n = find_index P xs) = (ALL x : set xs. ~ P x)\"\nby(metis find_index_eq_size_conv)\n\nlemma index_size_conv: \"size xs = n \\<Longrightarrow> (index xs x = n) = (x \\<notin> set xs)\"\nby(auto simp: index_def find_index_eq_size_conv)\n\nlemma size_index_conv: \"size xs = n \\<Longrightarrow> (n = index xs x) = (x \\<notin> set xs)\"\nby (metis index_size_conv)\n\nlemma last_index_size_conv:\n  \"size xs = n \\<Longrightarrow> (last_index xs x = n) = (x \\<notin> set xs)\"\napply(auto simp: last_index_def index_size_conv)\napply(drule length_pos_if_in_set)\napply arith\ndone\n\nlemma size_last_index_conv:\n  \"size xs = n \\<Longrightarrow> (n = last_index xs x) = (x \\<notin> set xs)\"\nby (metis last_index_size_conv)\n\nlemma find_index_less_size_conv:\n  \"(find_index P xs < size xs) = (EX x : set xs. P x)\"\nby (induct xs) auto\n\nlemma index_less_size_conv:\n  \"(index xs x < size xs) = (x \\<in> set xs)\"\nby(auto simp: index_def find_index_less_size_conv)\n\nlemma last_index_less_size_conv:\n  \"(last_index xs x < size xs) = (x : set xs)\"\nby(simp add: last_index_def Let_def index_size_conv length_pos_if_in_set\n        del:length_greater_0_conv)\n\nlemma index_less[simp]:\n  \"x : set xs \\<Longrightarrow> size xs <= n \\<Longrightarrow> index xs x < n\"\napply(induct xs) apply auto\napply (metis index_less_size_conv less_eq_Suc_le less_trans_Suc)\ndone\n\nlemma last_index_less[simp]:\n  \"x : set xs \\<Longrightarrow> size xs <= n \\<Longrightarrow> last_index xs x < n\"\nby(simp add: last_index_less_size_conv[symmetric])\n\nlemma last_index_Cons: \"last_index (x#xs) y =\n  (if x=y then\n      if x \\<in> set xs then last_index xs y + 1 else 0\n   else last_index xs y + 1)\"\nusing index_le_size[of \"rev xs\" y]\napply(auto simp add: last_index_def index_append Let_def)\napply(simp add: index_size_conv)\ndone\n\nlemma last_index_append: \"last_index (xs @ ys) x =\n  (if x : set ys then size xs + last_index ys x\n   else if x : set xs then last_index xs x else size xs + size ys)\"\nby (induct xs) (simp_all add: last_index_Cons last_index_size_conv)\n\nlemma last_index_Snoc[simp]:\n  \"last_index (xs @ [x]) y =\n  (if x=y then size xs\n   else if y : set xs then last_index xs y else size xs + 1)\"\nby(simp add: last_index_append last_index_Cons)\n\nlemma nth_find_index: \"find_index P xs < size xs \\<Longrightarrow> P(xs ! find_index P xs)\"\nby (induct xs) auto\n\nlemma nth_index[simp]: \"x \\<in> set xs \\<Longrightarrow> xs ! index xs x = x\"\nby (induct xs) auto\n\nlemma nth_last_index[simp]: \"x \\<in> set xs \\<Longrightarrow> xs ! last_index xs x = x\"\nby(simp add:last_index_def index_size_conv Let_def rev_nth[symmetric])\n\nlemma index_nth_id:\n  \"\\<lbrakk> distinct xs;  n < length xs \\<rbrakk> \\<Longrightarrow> index xs (xs ! n) = n\"\nby (metis in_set_conv_nth index_less_size_conv nth_eq_iff_index_eq nth_index)\n\nlemma index_eq_index_conv[simp]: \"x \\<in> set xs \\<or> y \\<in> set xs \\<Longrightarrow>\n  (index xs x = index xs y) = (x = y)\"\nby (induct xs) auto\n\nlemma last_index_eq_index_conv[simp]: \"x \\<in> set xs \\<or> y \\<in> set xs \\<Longrightarrow>\n  (last_index xs x = last_index xs y) = (x = y)\"\nby (induct xs) (auto simp:last_index_Cons)\n\nlemma inj_on_index: \"inj_on (index xs) (set xs)\"\nby (simp add:inj_on_def)\n\nlemma inj_on_last_index: \"inj_on (last_index xs) (set xs)\"\nby (simp add:inj_on_def)\n\nlemma index_conv_takeWhile: \"index xs x = size(takeWhile (\\<lambda>y. x\\<noteq>y) xs)\"\nby(induct xs) auto\n\nlemma index_take: \"index xs x >= i \\<Longrightarrow> x \\<notin> set(take i xs)\"\napply(subst (asm) index_conv_takeWhile)\napply(subgoal_tac \"set(take i xs) <= set(takeWhile (op \\<noteq> x) xs)\")\n apply(blast dest: set_takeWhileD)\napply(metis set_take_subset_set_take takeWhile_eq_take)\ndone\n\nlemma last_index_drop:\n  \"last_index xs x < i \\<Longrightarrow> x \\<notin> set(drop i xs)\"\napply(subgoal_tac \"set(drop i xs) = set(take (size xs - i) (rev xs))\")\n apply(simp add: last_index_def index_take Let_def split:split_if_asm)\napply (metis rev_drop set_rev)\ndone\n\nlemma set_take_if_index: assumes \"index xs x < i\" and \"i \\<le> length xs\"\nshows \"x \\<in> set (take i xs)\"\nproof -\n  have \"index (take i xs @ drop i xs) x < i\"\n    using append_take_drop_id[of i xs] assms(1) by simp\n  thus ?thesis using assms(2)\n    by(simp add:index_append del:append_take_drop_id split: if_splits)\nqed\n\nlemma index_take_if_index:\nassumes \"index xs x \\<le> n\" shows \"index (take n xs) x = index xs x\"\nproof cases\n  assume \"x : set(take n xs)\" with assms show ?thesis\n    by (metis append_take_drop_id index_append)\nnext\n  assume \"x \\<notin> set(take n xs)\" with assms show ?thesis\n   by (metis order_le_less set_take_if_index le_cases length_take min_def size_index_conv take_all)\nqed\n\nlemma index_take_if_set:\n  \"x : set(take n xs) \\<Longrightarrow> index (take n xs) x = index xs x\"\nby (metis index_take index_take_if_index linear)\n\nlemma index_update_if_diff2:\n  \"n < length xs \\<Longrightarrow> x \\<noteq> xs!n \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> index (xs[n := y]) x = index xs x\"\nby(subst (2) id_take_nth_drop[of n xs])\n  (auto simp: upd_conv_take_nth_drop index_append min_def)\n\nlemma set_drop_if_index: \"distinct xs \\<Longrightarrow> index xs x < i \\<Longrightarrow> x \\<notin> set(drop i xs)\"\nby (metis in_set_dropD index_nth_id last_index_drop last_index_less_size_conv nth_last_index)\n\nlemma index_swap_if_distinct: assumes \"distinct xs\" \"i < size xs\" \"j < size xs\"\nshows \"index (xs[i := xs!j, j := xs!i]) x =\n  (if x = xs!i then j else if x = xs!j then i else index xs x)\"\nproof-\n  have \"distinct(xs[i := xs!j, j := xs!i])\" using assms by simp\n  with assms show ?thesis\n    apply (auto simp: swap_def simp del: distinct_swap)\n    apply (metis index_nth_id list_update_same_conv)\n    apply (metis (erased, hide_lams) index_nth_id length_list_update list_update_swap nth_list_update_eq)\n    apply (metis index_nth_id length_list_update nth_list_update_eq)\n    by (metis index_update_if_diff2 length_list_update nth_list_update)\nqed\n\n\nsubsection {* Map with index *}\n\nprimrec map_index' :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\" where\n  \"map_index' n f [] = []\"\n| \"map_index' n f (x#xs) = f n x # map_index' (Suc n) f xs\"\n\nlemma length_map_index'[simp]: \"length (map_index' n f xs) = length xs\"\n  by (induct xs arbitrary: n) auto\n\nlemma map_index'_map_zip: \"map_index' n f xs = map (split f) (zip [n ..< n + length xs] xs)\"\nproof (induct xs arbitrary: n)\n  case (Cons x xs)\n  hence \"map_index' n f (x#xs) = f n x # map (split f) (zip [Suc n ..< n + length (x # xs)] xs)\" by simp\n  also have \"\\<dots> =  map (split f) (zip (n # [Suc n ..< n + length (x # xs)]) (x # xs))\" by simp\n  also have \"(n # [Suc n ..< n + length (x # xs)]) = [n ..< n + length (x # xs)]\" by (induct xs) auto\n  finally show ?case by simp\nqed simp\n\nabbreviation \"map_index \\<equiv> map_index' 0\"\n\nlemmas map_index = map_index'_map_zip[of 0, simplified]\n\nlemma take_map_index: \"take p (map_index f xs) = map_index f (take p xs)\"\n  unfolding map_index by (auto simp: min_def take_map take_zip)\n\nlemma drop_map_index: \"drop p (map_index f xs) = map_index' p f (drop p xs)\"\n  unfolding map_index'_map_zip by (cases \"p < length xs\") (auto simp: drop_map drop_zip)\n\nlemma map_map_index[simp]: \"map g (map_index f xs) = map_index (\\<lambda>n x. g (f n x)) xs\"\n  unfolding map_index by auto\n\nlemma map_index_map[simp]: \"map_index f (map g xs) = map_index (\\<lambda>n x. f n (g x)) xs\"\n  unfolding map_index by (auto simp: map_zip_map2)\n\nlemma set_map_index[simp]: \"x \\<in> set (map_index f xs) = (\\<exists>i < length xs. f i (xs ! i) = x)\"\n  unfolding map_index by (auto simp: set_zip intro!: image_eqI[of _ \"split f\"])\n\nlemma set_map_index'[simp]: \"x\\<in>set (map_index' n f xs) \n  \\<longleftrightarrow> (\\<exists>i<length xs. f (n+i) (xs!i) = x) \"\n  unfolding map_index'_map_zip \n  by (auto simp: set_zip intro!: image_eqI[of _ \"split f\"])\n\n\nlemma nth_map_index[simp]: \"p < length xs \\<Longrightarrow> map_index f xs ! p = f p (xs ! p)\"\n  unfolding map_index by auto\n\nlemma map_index_cong:\n  \"\\<forall>p < length xs. f p (xs ! p) = g p (xs ! p) \\<Longrightarrow> map_index f xs = map_index g xs\"\n  unfolding map_index by (auto simp: set_zip)\n\nlemma map_index_id: \"map_index (curry snd) xs = xs\"\n  unfolding map_index by auto\n\nlemma map_index_no_index[simp]: \"map_index (\\<lambda>n x. f x) xs = map f xs\"\n  unfolding map_index by (induct xs rule: rev_induct) auto\n\nlemma map_index_congL:\n  \"\\<forall>p < length xs. f p (xs ! p) = xs ! p \\<Longrightarrow> map_index f xs = xs\"\n  by (rule trans[OF map_index_cong map_index_id]) auto\n\nlemma map_index'_is_NilD: \"map_index' n f xs = [] \\<Longrightarrow> xs = []\"\n  by (induct xs) auto\n\ndeclare map_index'_is_NilD[of 0, dest!]\n\nlemma map_index'_is_ConsD:\n  \"map_index' n f xs = y # ys \\<Longrightarrow> \\<exists>z zs. xs = z # zs \\<and> f n z = y \\<and> map_index' (n + 1) f zs = ys\"\n  by (induct xs arbitrary: n) auto\n\nlemma map_index'_eq_imp_length_eq: \"map_index' n f xs = map_index' n g ys \\<Longrightarrow> length xs = length ys\"\nproof (induct ys arbitrary: xs n)\n  case (Cons y ys) thus ?case by (cases xs) auto\nqed (auto dest!: map_index'_is_NilD)\n\nlemmas map_index_eq_imp_length_eq = map_index'_eq_imp_length_eq[of 0]\n\nlemma map_index'_comp[simp]: \"map_index' n f (map_index' n g xs) = map_index' n (\\<lambda>n. f n o g n) xs\"\n  by (induct xs arbitrary: n) auto\n\nlemma map_index'_append[simp]: \"map_index' n f (a @ b) \n  = map_index' n f a @ map_index' (n + length a) f b\"\n  by (induct a arbitrary: n) auto\n\nlemma map_index_append[simp]: \"map_index f (a @ b) \n  = map_index f a @ map_index' (length a) f b\"\n  using map_index'_append[where n=0]\n  by (simp del: map_index'_append)\n\n\nsubsection {* Insert at position *}\n\nprimrec insert_nth :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"insert_nth 0 x xs = x # xs\"\n| \"insert_nth (Suc n) x xs = (case xs of [] \\<Rightarrow> [x] | y # ys \\<Rightarrow> y # insert_nth n x ys)\"\n\nlemma insert_nth_take_drop[simp]: \"insert_nth n x xs = take n xs @ [x] @ drop n xs\"\nproof (induct n arbitrary: xs)\n  case Suc thus ?case by (cases xs) auto\nqed simp\n\nlemma length_insert_nth: \"length (insert_nth n x xs) = Suc (length xs)\"\n  by (induct xs) auto\n\ntext {* Insert several elements at given (ascending) positions *}\n\nlemma length_fold_insert_nth:\n  \"length (fold (\\<lambda>(p, b). insert_nth p b) pxs xs) = length xs + length pxs\"\n  by (induct pxs arbitrary: xs) auto\n\nlemma invar_fold_insert_nth:\n  \"\\<lbrakk>\\<forall>x\\<in>set pxs. p < fst x; p < length xs; xs ! p = b\\<rbrakk> \\<Longrightarrow>\n    fold (\\<lambda>(x, y). insert_nth x y) pxs xs ! p = b\"\n  by (induct pxs arbitrary: xs) (auto simp: nth_append)\n\nlemma nth_fold_insert_nth:\n  \"\\<lbrakk>sorted (map fst pxs); distinct (map fst pxs); \\<forall>(p, b) \\<in> set pxs. p < length xs + length pxs;\n    i < length pxs; pxs ! i = (p, b)\\<rbrakk> \\<Longrightarrow>\n  fold (\\<lambda>(p, b). insert_nth p b) pxs xs ! p = b\"\nproof (induct pxs arbitrary: xs i p b)\n  case (Cons pb pxs)\n  show ?case\n  proof (cases i)\n    case 0\n    with Cons.prems have \"p < Suc (length xs)\"\n    proof (induct pxs rule: rev_induct)\n      case (snoc pb' pxs)\n      then obtain p' b' where \"pb' = (p', b')\" by auto\n      with snoc.prems have \"\\<forall>p \\<in> fst ` set pxs. p < p'\" \"p' \\<le> Suc (length xs + length pxs)\"\n        by (auto simp: image_iff sorted_Cons sorted_append le_eq_less_or_eq)\n      with snoc.prems show ?case by (intro snoc(1)) (auto simp: sorted_Cons sorted_append)\n    qed auto\n    with 0 Cons.prems show ?thesis unfolding fold.simps o_apply\n    by (intro invar_fold_insert_nth) (auto simp: sorted_Cons image_iff le_eq_less_or_eq nth_append)\n  next\n    case (Suc n) with Cons.prems show ?thesis unfolding fold.simps\n      by (auto intro!: Cons(1) simp: sorted_Cons)\n  qed\nqed simp\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/List-Index/List_Index.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.8757869851639066, "lm_q1q2_score": 0.7874388002956634}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Proving Falling Factorial of a Sum with Vandermonde Identity\\<close>\n\ntheory Falling_Factorial_Sum_Vandermonde\nimports\n  \"Discrete_Summation.Factorials\"\nbegin\n\ntext \\<open>Note the potentially special copyright license condition of the following proof.\\<close>\n\nlemma ffact_add_nat:\n  shows \"ffact k (n + m) = (\\<Sum>i\\<le>k. (k choose i) * ffact i n * ffact (k - i) m)\"\nproof -\n  have \"ffact k (n + m) = fact k * ((n + m) choose k)\"\n    by (simp only: ffact_eq_fact_mult_binomial)\n  also have \"\\<dots> = fact k * (\\<Sum>i\\<le>k. (n choose i) * (m choose (k - i)))\"\n    by (simp only: vandermonde)\n  also have \"\\<dots> = (\\<Sum>i\\<le>k. fact k * (n choose i) * (m choose (k - i)))\"\n    by (simp add: sum_distrib_left field_simps)\n  also have \"\\<dots> = (\\<Sum>i\\<le>k. (fact i * fact (k - i) * (k choose i)) * (n choose i) * (m choose (k - i)))\"\n    by (simp add: binomial_fact_lemma)\n  also have \"\\<dots> = (\\<Sum>i\\<le>k. (k choose i) * (fact i * (n choose i)) * (fact (k - i) * (m choose (k - i))))\"\n    by (auto intro: sum.cong)\n  also have \"\\<dots> = (\\<Sum>i\\<le>k. (k choose i) * ffact i n * ffact (k - i) m)\"\n    by (simp only: ffact_eq_fact_mult_binomial)\n  finally show ?thesis .\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Falling_Factorial_Sum/Falling_Factorial_Sum_Vandermonde.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.7873986856033758}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\ntheory AExp imports Main begin\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\n\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>We can now write a series of updates to the function @{term \"\\<lambda>x. 0\"} compactly:\\<close>\n\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In the @{term \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\\<close>\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext \\<open>Note that this \\<open><\\<dots>>\\<close> syntax works for any function space \\<open>\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\\<close> where \\<open>\\<tau>\\<^sub>2\\<close> has a 0.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext \\<open>Evaluate constant subexpressions:\\<close>\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext \\<open>Now we also eliminate all occurrences 0 in additions.\nThe standard method: optimized versions of the constructors:\\<close>\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n\nlemma aval_plus [simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply auto\ndone\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\n\ntext \\<open>Note that in @{const asimp_const} the optimized constructor was inlined.\nMaking it a separate function @{const plus} improves modularity of the code and the proofs.\\<close>\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply auto\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Complete/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8652240877899775, "lm_q1q2_score": 0.7872734613867937}}
{"text": "(*  Title:      ZF/ex/Primes.thy\n    Author:     Christophe Tabacznyj and Lawrence C Paulson\n    Copyright   1996  University of Cambridge\n*)\n\nsection\\<open>The Divides Relation and Euclid's algorithm for the GCD\\<close>\n\ntheory Primes imports Main begin\n\ndefinition\n  divides :: \"[i,i]=>o\"              (infixl \"dvd\" 50)  where\n    \"m dvd n == m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\n\ndefinition\n  is_gcd  :: \"[i,i,i]=>o\"     \\<comment>\\<open>definition of great common divisor\\<close>  where\n    \"is_gcd(p,m,n) == ((p dvd m) & (p dvd n))   &\n                       (\\<forall>d\\<in>nat. (d dvd m) & (d dvd n) \\<longrightarrow> d dvd p)\"\n\ndefinition\n  gcd     :: \"[i,i]=>i\"       \\<comment>\\<open>Euclid's algorithm for the gcd\\<close>  where\n    \"gcd(m,n) == transrec(natify(n),\n                        %n f. \\<lambda>m \\<in> nat.\n                                if n=0 then m else f`(m mod n)`n) ` natify(m)\"\n\ndefinition\n  coprime :: \"[i,i]=>o\"       \\<comment>\\<open>the coprime relation\\<close>  where\n    \"coprime(m,n) == gcd(m,n) = 1\"\n  \ndefinition\n  prime   :: i                \\<comment>\\<open>the set of prime numbers\\<close>  where\n   \"prime == {p \\<in> nat. 1<p & (\\<forall>m \\<in> nat. m dvd p \\<longrightarrow> m=1 | m=p)}\"\n\n\nsubsection\\<open>The Divides Relation\\<close>\n\nlemma dvdD: \"m dvd n ==> m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\nby (unfold divides_def, assumption)\n\nlemma dvdE:\n     \"[|m dvd n;  !!k. [|m \\<in> nat; n \\<in> nat; k \\<in> nat; n = m#*k|] ==> P|] ==> P\"\nby (blast dest!: dvdD)\n\nlemmas dvd_imp_nat1 = dvdD [THEN conjunct1]\nlemmas dvd_imp_nat2 = dvdD [THEN conjunct2, THEN conjunct1]\n\n\nlemma dvd_0_right [simp]: \"m \\<in> nat ==> m dvd 0\"\napply (simp add: divides_def)\napply (fast intro: nat_0I mult_0_right [symmetric])\ndone\n\nlemma dvd_0_left: \"0 dvd m ==> m = 0\"\nby (simp add: divides_def)\n\nlemma dvd_refl [simp]: \"m \\<in> nat ==> m dvd m\"\napply (simp add: divides_def)\napply (fast intro: nat_1I mult_1_right [symmetric])\ndone\n\nlemma dvd_trans: \"[| m dvd n; n dvd p |] ==> m dvd p\"\nby (auto simp add: divides_def intro: mult_assoc mult_type)\n\nlemma dvd_anti_sym: \"[| m dvd n; n dvd m |] ==> m=n\"\napply (simp add: divides_def)\napply (force dest: mult_eq_self_implies_10\n             simp add: mult_assoc mult_eq_1_iff)\ndone\n\nlemma dvd_mult_left: \"[|(i#*j) dvd k; i \\<in> nat|] ==> i dvd k\"\nby (auto simp add: divides_def mult_assoc)\n\nlemma dvd_mult_right: \"[|(i#*j) dvd k; j \\<in> nat|] ==> j dvd k\"\napply (simp add: divides_def, clarify)\napply (rule_tac x = \"i#*ka\" in bexI)\napply (simp add: mult_ac)\napply (rule mult_type)\ndone\n\n\nsubsection\\<open>Euclid's Algorithm for the GCD\\<close>\n\nlemma gcd_0 [simp]: \"gcd(m,0) = natify(m)\"\napply (simp add: gcd_def)\napply (subst transrec, simp)\ndone\n\nlemma gcd_natify1 [simp]: \"gcd(natify(m),n) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_natify2 [simp]: \"gcd(m, natify(n)) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_non_0_raw: \n    \"[| 0<n;  n \\<in> nat |] ==> gcd(m,n) = gcd(n, m mod n)\"\napply (simp add: gcd_def)\napply (rule_tac P = \"%z. left (z) = right\" for left right in transrec [THEN ssubst])\napply (simp add: ltD [THEN mem_imp_not_eq, THEN not_sym] \n                 mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_non_0: \"0 < natify(n) ==> gcd(m,n) = gcd(n, m mod n)\"\napply (cut_tac m = m and n = \"natify (n) \" in gcd_non_0_raw)\napply auto\ndone\n\nlemma gcd_1 [simp]: \"gcd(m,1) = 1\"\nby (simp (no_asm_simp) add: gcd_non_0)\n\nlemma dvd_add: \"[| k dvd a; k dvd b |] ==> k dvd (a #+ b)\"\napply (simp add: divides_def)\napply (fast intro: add_mult_distrib_left [symmetric] add_type)\ndone\n\nlemma dvd_mult: \"k dvd n ==> k dvd (m #* n)\"\napply (simp add: divides_def)\napply (fast intro: mult_left_commute mult_type)\ndone\n\nlemma dvd_mult2: \"k dvd m ==> k dvd (m #* n)\"\napply (subst mult_commute)\napply (blast intro: dvd_mult)\ndone\n\n(* k dvd (m*k) *)\nlemmas dvdI1 [simp] = dvd_refl [THEN dvd_mult]\nlemmas dvdI2 [simp] = dvd_refl [THEN dvd_mult2]\n\nlemma dvd_mod_imp_dvd_raw:\n     \"[| a \\<in> nat; b \\<in> nat; k dvd b; k dvd (a mod b) |] ==> k dvd a\"\napply (case_tac \"b=0\") \n apply (simp add: DIVISION_BY_ZERO_MOD)\napply (blast intro: mod_div_equality [THEN subst]\n             elim: dvdE \n             intro!: dvd_add dvd_mult mult_type mod_type div_type)\ndone\n\nlemma dvd_mod_imp_dvd: \"[| k dvd (a mod b); k dvd b; a \\<in> nat |] ==> k dvd a\"\napply (cut_tac b = \"natify (b)\" in dvd_mod_imp_dvd_raw)\napply auto\napply (simp add: divides_def)\ndone\n\n(*Imitating TFL*)\nlemma gcd_induct_lemma [rule_format (no_asm)]: \"[| n \\<in> nat;  \n         \\<forall>m \\<in> nat. P(m,0);  \n         \\<forall>m \\<in> nat. \\<forall>n \\<in> nat. 0<n \\<longrightarrow> P(n, m mod n) \\<longrightarrow> P(m,n) |]  \n      ==> \\<forall>m \\<in> nat. P (m,n)\"\napply (erule_tac i = n in complete_induct)\napply (case_tac \"x=0\")\napply (simp (no_asm_simp))\napply clarify\napply (drule_tac x1 = m and x = x in bspec [THEN bspec])\napply (simp_all add: Ord_0_lt_iff)\napply (blast intro: mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_induct: \"!!P. [| m \\<in> nat; n \\<in> nat;  \n         !!m. m \\<in> nat ==> P(m,0);  \n         !!m n. [|m \\<in> nat; n \\<in> nat; 0<n; P(n, m mod n)|] ==> P(m,n) |]  \n      ==> P (m,n)\"\nby (blast intro: gcd_induct_lemma)\n\n\nsubsection\\<open>Basic Properties of @{term gcd}\\<close>\n\ntext\\<open>type of gcd\\<close>\nlemma gcd_type [simp,TC]: \"gcd(m, n) \\<in> nat\"\napply (subgoal_tac \"gcd (natify (m), natify (n)) \\<in> nat\")\napply simp\napply (rule_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_induct)\napply auto\napply (simp add: gcd_non_0)\ndone\n\n\ntext\\<open>Property 1: gcd(a,b) divides a and b\\<close>\n\nlemma gcd_dvd_both:\n     \"[| m \\<in> nat; n \\<in> nat |] ==> gcd (m, n) dvd m & gcd (m, n) dvd n\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0)\napply (blast intro: dvd_mod_imp_dvd_raw nat_into_Ord [THEN Ord_0_lt])\ndone\n\nlemma gcd_dvd1 [simp]: \"m \\<in> nat ==> gcd(m,n) dvd m\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\nlemma gcd_dvd2 [simp]: \"n \\<in> nat ==> gcd(m,n) dvd n\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\ntext\\<open>if f divides a and b then f divides gcd(a,b)\\<close>\n\nlemma dvd_mod: \"[| f dvd a; f dvd b |] ==> f dvd (a mod b)\"\napply (simp add: divides_def)\napply (case_tac \"b=0\")\n apply (simp add: DIVISION_BY_ZERO_MOD, auto)\napply (blast intro: mod_mult_distrib2 [symmetric])\ndone\n\ntext\\<open>Property 2: for all a,b,f naturals, \n               if f divides a and f divides b then f divides gcd(a,b)\\<close>\n\nlemma gcd_greatest_raw [rule_format]:\n     \"[| m \\<in> nat; n \\<in> nat; f \\<in> nat |]    \n      ==> (f dvd m) \\<longrightarrow> (f dvd n) \\<longrightarrow> f dvd gcd(m,n)\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0 dvd_mod)\ndone\n\nlemma gcd_greatest: \"[| f dvd m;  f dvd n;  f \\<in> nat |] ==> f dvd gcd(m,n)\"\napply (rule gcd_greatest_raw)\napply (auto simp add: divides_def)\ndone\n\nlemma gcd_greatest_iff [simp]: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> (k dvd gcd (m, n)) \\<longleftrightarrow> (k dvd m & k dvd n)\"\nby (blast intro!: gcd_greatest gcd_dvd1 gcd_dvd2 intro: dvd_trans)\n\n\nsubsection\\<open>The Greatest Common Divisor\\<close>\n\ntext\\<open>The GCD exists and function gcd computes it.\\<close>\n\nlemma is_gcd: \"[| m \\<in> nat; n \\<in> nat |] ==> is_gcd(gcd(m,n), m, n)\"\nby (simp add: is_gcd_def)\n\ntext\\<open>The GCD is unique\\<close>\n\nlemma is_gcd_unique: \"[|is_gcd(m,a,b); is_gcd(n,a,b); m\\<in>nat; n\\<in>nat|] ==> m=n\"\napply (simp add: is_gcd_def)\napply (blast intro: dvd_anti_sym)\ndone\n\nlemma is_gcd_commute: \"is_gcd(k,m,n) \\<longleftrightarrow> is_gcd(k,n,m)\"\nby (simp add: is_gcd_def, blast)\n\nlemma gcd_commute_raw: \"[| m \\<in> nat; n \\<in> nat |] ==> gcd(m,n) = gcd(n,m)\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (rule_tac [3] is_gcd_commute [THEN iffD1])\napply (rule_tac [3] is_gcd, auto)\ndone\n\nlemma gcd_commute: \"gcd(m,n) = gcd(n,m)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_commute_raw)\napply auto\ndone\n\nlemma gcd_assoc_raw: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (simp_all add: is_gcd_def)\napply (blast intro: gcd_dvd1 gcd_dvd2 gcd_type intro: dvd_trans)\ndone\n\nlemma gcd_assoc: \"gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_assoc_raw)\napply auto\ndone\n\nlemma gcd_0_left [simp]: \"gcd (0, m) = natify(m)\"\nby (simp add: gcd_commute [of 0])\n\nlemma gcd_1_left [simp]: \"gcd (1, m) = 1\"\nby (simp add: gcd_commute [of 1])\n\n\nsubsection\\<open>Addition laws\\<close>\n\nlemma gcd_add1 [simp]: \"gcd (m #+ n, n) = gcd (m, n)\"\napply (subgoal_tac \"gcd (m #+ natify (n), natify (n)) = gcd (m, natify (n))\")\napply simp\napply (case_tac \"natify (n) = 0\")\napply (auto simp add: Ord_0_lt_iff gcd_non_0)\ndone\n\nlemma gcd_add2 [simp]: \"gcd (m, m #+ n) = gcd (m, n)\"\napply (rule gcd_commute [THEN trans])\napply (subst add_commute, simp)\napply (rule gcd_commute)\ndone\n\nlemma gcd_add2' [simp]: \"gcd (m, n #+ m) = gcd (m, n)\"\nby (subst add_commute, rule gcd_add2)\n\nlemma gcd_add_mult_raw: \"k \\<in> nat ==> gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (erule nat_induct)\napply (auto simp add: gcd_add2 add_assoc)\ndone\n\nlemma gcd_add_mult: \"gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (cut_tac k = \"natify (k)\" in gcd_add_mult_raw)\napply auto\ndone\n\n\nsubsection\\<open>Multiplication Laws\\<close>\n\nlemma gcd_mult_distrib2_raw:\n     \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (erule_tac m = m and n = n in gcd_induct, assumption)\napply simp\napply (case_tac \"k = 0\", simp)\napply (simp add: mod_geq gcd_non_0 mod_mult_distrib2 Ord_0_lt_iff)\ndone\n\nlemma gcd_mult_distrib2: \"k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_mult_distrib2_raw)\napply auto\ndone\n\nlemma gcd_mult [simp]: \"gcd (k, k #* n) = natify(k)\"\nby (cut_tac k = k and m = 1 and n = n in gcd_mult_distrib2, auto)\n\nlemma gcd_self [simp]: \"gcd (k, k) = natify(k)\"\nby (cut_tac k = k and n = 1 in gcd_mult, auto)\n\nlemma relprime_dvd_mult:\n     \"[| gcd (k,n) = 1;  k dvd (m #* n);  m \\<in> nat |] ==> k dvd m\"\napply (cut_tac k = m and m = k and n = n in gcd_mult_distrib2, auto)\napply (erule_tac b = m in ssubst)\napply (simp add: dvd_imp_nat1)\ndone\n\nlemma relprime_dvd_mult_iff:\n     \"[| gcd (k,n) = 1;  m \\<in> nat |] ==> k dvd (m #* n) \\<longleftrightarrow> k dvd m\"\nby (blast intro: dvdI2 relprime_dvd_mult dvd_trans)\n\nlemma prime_imp_relprime: \n     \"[| p \\<in> prime;  ~ (p dvd n);  n \\<in> nat |] ==> gcd (p, n) = 1\"\napply (simp add: prime_def, clarify)\napply (drule_tac x = \"gcd (p,n)\" in bspec)\napply auto\napply (cut_tac m = p and n = n in gcd_dvd2, auto)\ndone\n\nlemma prime_into_nat: \"p \\<in> prime ==> p \\<in> nat\"\nby (simp add: prime_def)\n\nlemma prime_nonzero: \"p \\<in> prime \\<Longrightarrow> p\\<noteq>0\"\nby (auto simp add: prime_def)\n\n\ntext\\<open>This theorem leads immediately to a proof of the uniqueness of\n  factorization.  If @{term p} divides a product of primes then it is\n  one of those primes.\\<close>\n\nlemma prime_dvd_mult:\n     \"[|p dvd m #* n; p \\<in> prime; m \\<in> nat; n \\<in> nat |] ==> p dvd m \\<or> p dvd n\"\nby (blast intro: relprime_dvd_mult prime_imp_relprime prime_into_nat)\n\n\nlemma gcd_mult_cancel_raw:\n     \"[|gcd (k,n) = 1; m \\<in> nat; n \\<in> nat|] ==> gcd (k #* m, n) = gcd (m, n)\"\napply (rule dvd_anti_sym)\n apply (rule gcd_greatest)\n  apply (rule relprime_dvd_mult [of _ k])\napply (simp add: gcd_assoc)\napply (simp add: gcd_commute)\napply (simp_all add: mult_commute)\napply (blast intro: dvdI1 gcd_dvd1 dvd_trans)\ndone\n\nlemma gcd_mult_cancel: \"gcd (k,n) = 1 ==> gcd (k #* m, n) = gcd (m, n)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_mult_cancel_raw)\napply auto\ndone\n\n\nsubsection\\<open>The Square Root of a Prime is Irrational: Key Lemma\\<close>\n\nlemma prime_dvd_other_side:\n     \"\\<lbrakk>n#*n = p#*(k#*k); p \\<in> prime; n \\<in> nat\\<rbrakk> \\<Longrightarrow> p dvd n\"\napply (subgoal_tac \"p dvd n#*n\")\n apply (blast dest: prime_dvd_mult)\napply (rule_tac j = \"k#*k\" in dvd_mult_left)\n apply (auto simp add: prime_def)\ndone\n\nlemma reduction:\n     \"\\<lbrakk>k#*k = p#*(j#*j); p \\<in> prime; 0 < k; j \\<in> nat; k \\<in> nat\\<rbrakk>  \n      \\<Longrightarrow> k < p#*j & 0 < j\"\napply (rule ccontr)\napply (simp add: not_lt_iff_le prime_into_nat)\napply (erule disjE)\n apply (frule mult_le_mono, assumption+)\napply (simp add: mult_ac)\napply (auto dest!: natify_eqE \n            simp add: not_lt_iff_le prime_into_nat mult_le_cancel_le1)\napply (simp add: prime_def)\napply (blast dest: lt_trans1)\ndone\n\nlemma rearrange: \"j #* (p#*j) = k#*k \\<Longrightarrow> k#*k = p#*(j#*j)\"\nby (simp add: mult_ac)\n\nlemma prime_not_square:\n     \"\\<lbrakk>m \\<in> nat; p \\<in> prime\\<rbrakk> \\<Longrightarrow> \\<forall>k \\<in> nat. 0<k \\<longrightarrow> m#*m \\<noteq> p#*(k#*k)\"\napply (erule complete_induct, clarify)\napply (frule prime_dvd_other_side, assumption)\napply assumption\napply (erule dvdE)\napply (simp add: mult_assoc mult_cancel1 prime_nonzero prime_into_nat)\napply (blast dest: rearrange reduction ltD)\ndone\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/ZF/ex/Primes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8652240860523327, "lm_q1q2_score": 0.7872734492366288}}
{"text": "section \\<open> Defining Runs \\<close>\n\ntheory Run\nimports TESL\n      \nbegin\ntext \\<open>\n  Runs are sequences of instants, and each instant maps a clock to a pair \n  @{term \\<open>(h, t)\\<close>} where @{term \\<open>h\\<close>} indicates whether the clock ticks or not, \n  and @{term \\<open>t\\<close>} is the current time on this clock.\n  The first element of the pair is called the \\<^emph>\\<open>hamlet\\<close> of the clock (to tick or \n  not to tick), the second element is called the \\<^emph>\\<open>time\\<close>.\n\\<close>\n\nabbreviation hamlet where \\<open>hamlet \\<equiv> fst\\<close>\nabbreviation time   where \\<open>time \\<equiv> snd\\<close>\n\ntype_synonym '\\<tau> instant = \\<open>clock \\<Rightarrow> (bool \\<times> '\\<tau> tag_const)\\<close>\n\ntext\\<open>\n  Runs have the additional constraint that time cannot go backwards on any clock\n  in the sequence of instants.\n  Therefore, for any clock, the time projection of a run is monotonous.\n\\<close>\ntypedef (overloaded) '\\<tau>::linordered_field run =\n  \\<open>{ \\<rho>::nat \\<Rightarrow> '\\<tau> instant. \\<forall>c. mono (\\<lambda>n. time (\\<rho> n c)) }\\<close>\nproof\n  show \\<open>(\\<lambda>_ _. (True, \\<tau>\\<^sub>c\\<^sub>s\\<^sub>t 0)) \\<in> {\\<rho>. \\<forall>c. mono (\\<lambda>n. time (\\<rho> n c))}\\<close> \n    unfolding mono_def by blast\nqed\n\nlemma Abs_run_inverse_rewrite:\n  \\<open>\\<forall>c. mono (\\<lambda>n. time (\\<rho> n c)) \\<Longrightarrow> Rep_run (Abs_run \\<rho>) = \\<rho>\\<close>\nby (simp add: Abs_run_inverse)\n\ntext \\<open>\n  A \\<^emph>\\<open>dense\\<close> run is a run in which something happens (at least one clock ticks) \n  at every instant.\n\\<close>\ndefinition \\<open>dense_run \\<rho> \\<equiv> (\\<forall>n. \\<exists>c. hamlet ((Rep_run \\<rho>) n c))\\<close>\n\ntext\\<open>\n  @{term \\<open>run_tick_count \\<rho> K n\\<close>} counts the number of ticks on clock @{term \\<open>K\\<close>} \n  in the interval \\<^verbatim>\\<open>[0, n]\\<close> of run @{term \\<open>\\<rho>\\<close>}.\n\\<close>\nfun run_tick_count :: \\<open>('\\<tau>::linordered_field) run \\<Rightarrow> clock \\<Rightarrow> nat \\<Rightarrow> nat\\<close>\n  (\\<open>#\\<^sub>\\<le> _ _ _\\<close>)\nwhere\n  \\<open>(#\\<^sub>\\<le> \\<rho> K 0)       = (if hamlet ((Rep_run \\<rho>) 0 K)\n                       then 1\n                       else 0)\\<close>\n| \\<open>(#\\<^sub>\\<le> \\<rho> K (Suc n)) = (if hamlet ((Rep_run \\<rho>) (Suc n) K)\n                       then 1 + (#\\<^sub>\\<le> \\<rho> K n)\n                       else (#\\<^sub>\\<le> \\<rho> K n))\\<close>\n\ntext\\<open>\n  @{term \\<open>run_tick_count_strictly \\<rho> K n\\<close>} counts the number of ticks on\n  clock @{term \\<open>K\\<close>} in the interval \\<^verbatim>\\<open>[0, n[\\<close> of run @{term \\<open>\\<rho>\\<close>}.\n\\<close>\nfun run_tick_count_strictly :: \\<open>('\\<tau>::linordered_field) run \\<Rightarrow> clock \\<Rightarrow> nat \\<Rightarrow> nat\\<close>\n  (\\<open>#\\<^sub>< _ _ _\\<close>)\nwhere\n  \\<open>(#\\<^sub>< \\<rho> K 0)       = 0\\<close>\n| \\<open>(#\\<^sub>< \\<rho> K (Suc n)) = #\\<^sub>\\<le> \\<rho> K n\\<close>\n\ntext\\<open>\n  @{term \\<open>first_time \\<rho> K n \\<tau>\\<close>} tells whether instant @{term \\<open>n\\<close>} in run @{term\\<open>\\<rho>\\<close>}\n  is the first one where the time on clock @{term \\<open>K\\<close>} reaches @{term \\<open>\\<tau>\\<close>}.\n\\<close>\ndefinition first_time :: \\<open>'a::linordered_field run \\<Rightarrow> clock \\<Rightarrow> nat \\<Rightarrow> 'a tag_const\n                          \\<Rightarrow> bool\\<close>\nwhere\n  \\<open>first_time \\<rho> K n \\<tau> \\<equiv> (time ((Rep_run \\<rho>) n K) = \\<tau>)\n                      \\<and> (\\<nexists>n'. n' < n \\<and> time ((Rep_run \\<rho>) n' K) = \\<tau>)\\<close>\n\ntext\\<open>\n  The time on a clock is necessarily less than @{term \\<open>\\<tau>\\<close>} before the first instant\n  at which it reaches @{term \\<open>\\<tau>\\<close>}.\n\\<close>\nlemma before_first_time:\n  assumes \\<open>first_time \\<rho> K n \\<tau>\\<close>\n      and \\<open>m < n\\<close>\n    shows \\<open>time ((Rep_run \\<rho>) m K) < \\<tau>\\<close>\nproof -\n  have \\<open>mono (\\<lambda>n. time (Rep_run \\<rho> n K))\\<close> using Rep_run by blast\n  moreover from assms(2) have \\<open>m \\<le> n\\<close> using less_imp_le by simp\n  moreover have \\<open>mono (\\<lambda>n. time (Rep_run \\<rho> n K))\\<close> using Rep_run by blast\n  ultimately have  \\<open>time ((Rep_run \\<rho>) m K) \\<le> time ((Rep_run \\<rho>) n K)\\<close>\n    by (simp add:mono_def)\n  moreover from assms(1) have \\<open>time ((Rep_run \\<rho>) n K) = \\<tau>\\<close>\n    using first_time_def by blast\n  moreover from assms have \\<open>time ((Rep_run \\<rho>) m K) \\<noteq> \\<tau>\\<close>\n    using first_time_def by blast\n  ultimately show ?thesis by simp\nqed\n\ntext\\<open>\n  This leads to an alternate definition of @{term \\<open>first_time\\<close>}:\n\\<close>\nlemma alt_first_time_def:\n  assumes \\<open>\\<forall>m < n. time ((Rep_run \\<rho>) m K) < \\<tau>\\<close>\n      and \\<open>time ((Rep_run \\<rho>) n K) = \\<tau>\\<close>\n    shows \\<open>first_time \\<rho> K n \\<tau>\\<close>\nproof -\n  from assms(1) have \\<open>\\<forall>m < n. time ((Rep_run \\<rho>) m K) \\<noteq> \\<tau>\\<close>\n    by (simp add: less_le)\n  with assms(2) show ?thesis by (simp add: first_time_def)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/TESL_Language/Run.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070035949657, "lm_q2_score": 0.865224072151174, "lm_q1q2_score": 0.7872734429293091}}
{"text": "section \\<open> Integer Powers \\<close>\n\ntheory Power_int\n  imports \"HOL.Real\"\nbegin\n\ntext \\<open> The standard HOL power operator is only for natural powers. This operator allows integers. \\<close>\n\ndefinition intpow :: \"'a::{linordered_field} \\<Rightarrow> int \\<Rightarrow> 'a\" (infixr \"^\\<^sub>Z\" 80) where\n\"intpow x n = (if (n < 0) then inverse (x ^ nat (-n)) else (x ^ nat n))\"\n\nlemma intpow_zero [simp]: \"x ^\\<^sub>Z 0 = 1\"\n  by (simp add: intpow_def)\n\nlemma intpow_spos [simp]: \"x > 0 \\<Longrightarrow> x ^\\<^sub>Z n > 0\"\n  by (simp add: intpow_def)\n\nlemma intpow_one [simp]: \"x ^\\<^sub>Z 1 = x\"\n  by (simp add: intpow_def)\n\n\n\nlemma intpow_plus: \"x > 0 \\<Longrightarrow> x ^\\<^sub>Z (m + n) = x ^\\<^sub>Z m * x ^\\<^sub>Z n\"\n  apply (simp add: intpow_def field_simps power_add)\n  apply (metis (no_types, hide_lams) abs_ge_zero add.commute add_diff_cancel_right' nat_add_distrib power_add uminus_add_conv_diff zabs_def)\n  done\n\nlemma intpow_mult_combine: \"x > 0 \\<Longrightarrow> x ^\\<^sub>Z m * (x ^\\<^sub>Z n * y) = x ^\\<^sub>Z (m + n) * y\"\n  by (simp add: intpow_plus)\n\nlemma intpow_pos [simp]: \"n \\<ge> 0 \\<Longrightarrow> x ^\\<^sub>Z n = x ^ nat n\"\n  by (simp add: intpow_def)\n\nlemma intpow_uminus: \"x ^\\<^sub>Z -n = inverse (x ^\\<^sub>Z n)\"\n  by (simp add: intpow_def)\n\nlemma intpow_uminus_nat: \"n \\<ge> 0 \\<Longrightarrow> x ^\\<^sub>Z -n = inverse (x ^ nat n)\"\n  by (simp add: intpow_def)\n\nlemma intpow_inverse: \"inverse a ^\\<^sub>Z n = inverse (a ^\\<^sub>Z n)\"\n  by (simp add: intpow_def power_inverse)\n\nlemma intpow_mult_distrib: \"(x * y) ^\\<^sub>Z m = x ^\\<^sub>Z m * y ^\\<^sub>Z m\"\n  by (simp add: intpow_def power_mult_distrib)\n\nend", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Physical_Quantities/Power_int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7871672372041725}}
{"text": "(* Samuel Balco and Alexander Kurz, Sept 2018 *)\n\nsection \"Arithmetic Expressions\"\n\ntheory NumExp imports Main \"HOL-Eisbach.Eisbach\" begin\n\nsubsection \"Arithmetic Expressions\"\n\n(* num ::= 1 | num + 1 \n   exp ::= num | exp + exp | exp * exp *)\n\ndatatype num = One (\"\\<one>\") | S num (\"_+\\<one>\")\ndatatype exp = Num num (\"\\<langle>_\\<rangle>\") | Plus exp exp (infix \":+:\" 14) | Mult exp exp (infix \":*:\" 15)\n\nfun eval_num :: \"num \\<Rightarrow> int\" where\n\"eval_num \\<one> = 1\" |\n\"eval_num (num+\\<one>) = (eval_num num) + 1\"\n\nvalue \"eval_num \\<one>\"\nvalue \"eval_num (\\<one>+\\<one>+\\<one>)\"\n\nfun eval_exp :: \"exp \\<Rightarrow> int\" where\n\"eval_exp \\<langle>num\\<rangle> = eval_num num\" |\n\"eval_exp (a\\<^sub>1 :+: a\\<^sub>2) = eval_exp a\\<^sub>1 + (eval_exp a\\<^sub>2)\" |\n\"eval_exp (a\\<^sub>1 :*: a\\<^sub>2) = eval_exp a\\<^sub>1 * (eval_exp a\\<^sub>2)\"\n\nvalue \"eval_exp (Plus (Num (S One)) (Num One))\"\n\nvalue \"eval_exp (\\<langle>\\<one>+\\<one>\\<rangle> :+: \\<langle>\\<one>+\\<one>\\<rangle> :*: \\<langle>\\<one>+\\<one>+\\<one>\\<rangle>)\"\n\nvalue \"eval_exp (Mult (Num (S One)) (Num One))\"\n\n(* the following is easy because addition in integers is commutative *)\n(* so after evaluation, there is not much to prove *)\nlemma \"eval_exp (e\\<^sub>1 :+: e\\<^sub>2) = eval_exp (e\\<^sub>2 :+: e\\<^sub>1)\"\n  by auto\n\n(* but can we prove commutativity on the syntactic side? *)\n(* we need to assume something, that captures that Plus is addition *)\n(* in our simple situation, associativity is enough *)\n\ninductive equal_exp :: \"exp \\<Rightarrow> exp \\<Rightarrow> bool\" (infix \"\\<equiv>ex\" 13) where\nequal_exp_refl:         \"e \\<equiv>ex e\" |\nequal_exp_symm:         \"e\\<^sub>1 \\<equiv>ex e\\<^sub>2 \\<Longrightarrow> e\\<^sub>2 \\<equiv>ex e\\<^sub>1\" |\nequal_exp_trans[trans]: \"e\\<^sub>1 \\<equiv>ex e\\<^sub>2 \\<Longrightarrow> e\\<^sub>2 \\<equiv>ex e\\<^sub>3 \\<Longrightarrow> e\\<^sub>1 \\<equiv>ex e\\<^sub>3\" |\nequal_exp_cong_plus:    \"e\\<^sub>1 \\<equiv>ex e\\<^sub>1' \\<Longrightarrow> e\\<^sub>2 \\<equiv>ex e\\<^sub>2' \\<Longrightarrow> e\\<^sub>1 :+: e\\<^sub>2 \\<equiv>ex e\\<^sub>1' :+: e\\<^sub>2'\" |\nequal_exp_plusone:      \"\\<langle>n+\\<one>\\<rangle> \\<equiv>ex \\<langle>n\\<rangle> :+: \\<langle>\\<one>\\<rangle>\" |\nequal_exp_assoc:        \"(e\\<^sub>1 :+: (e\\<^sub>2 :+: e\\<^sub>3)) \\<equiv>ex ((e\\<^sub>1 :+: e\\<^sub>2) :+: e\\<^sub>3)\" \n\n\nlemma plusone: \"\\<langle>\\<one>\\<rangle> :+: \\<langle>n\\<rangle> \\<equiv>ex \\<langle>n\\<rangle> :+: \\<langle>\\<one>\\<rangle>\"\n(* Show 1+n=n+1 by induction on n:\n   If n=1, then 1+1=1+1\n   If n=Sm, then 1+n = 1+Sm = 1+(m+1) = (1+m)+1 = (m+1)+1 = Sm+1 = n+1\n*)\n  apply (induction n)\n  \n  apply (rule equal_exp_refl)\n\n  apply(rule equal_exp_trans)\n  apply(rule equal_exp_cong_plus)\n  apply(rule equal_exp_refl)\n   apply(rule equal_exp_plusone)\n\n  apply(rule equal_exp_trans)\n  apply(rule equal_exp_assoc)\n  apply(rule equal_exp_trans)\n  apply(rule equal_exp_cong_plus)\n  apply simp\n   apply(rule equal_exp_refl)\n\n  apply(rule equal_exp_cong_plus)\n  apply(rule equal_exp_symm)\n  apply(rule equal_exp_plusone)\n   apply(rule equal_exp_refl)\n  done\n\n(* We want to show that n+m=m+n, or, Plus n m = Plus m n, which again needs to be written as\n   \"equal_exp (Plus (Num n) (Num m)) (Plus (Num m) (Num n))\" to be understood by Isabelle  *)\nlemma commutativity_num: \"\\<langle>n\\<rangle> :+: \\<langle>m\\<rangle> \\<equiv>ex \\<langle>m\\<rangle> :+: \\<langle>n\\<rangle>\"\n(* Induction on m: \n   If n=1, then we need to show 1+m=m+1, which we proved in lemma plusone\n   If n = Sl, then \n    n+m = Sl+m = (l+1)+m = (1+l)+m = 1+(l+m) = 1+(m+l) = (1+m)+l = (m+1)+l \n     = m+(1+l) = m+(l+1) =  m+n\n*)\nproof(induction n)\ncase One\n  then show ?case by (rule plusone)\nnext\n  case (S l)\n  have \"\\<langle>l+\\<one>\\<rangle> :+: \\<langle>m\\<rangle> \\<equiv>ex (\\<langle>l\\<rangle> :+: \\<langle>\\<one>\\<rangle>) :+: \\<langle>m\\<rangle>\"\n    apply(rule equal_exp_cong_plus)\n    apply(rule equal_exp_plusone)\n    by(rule equal_exp_refl)\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>\\<one>\\<rangle> :+: \\<langle>l\\<rangle>) :+: \\<langle>m\\<rangle>\"\n    apply(rule equal_exp_cong_plus)\n    apply(rule equal_exp_symm)\n    apply(rule plusone)\n    by(rule equal_exp_refl)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>\\<one>\\<rangle> :+: (\\<langle>l\\<rangle> :+: \\<langle>m\\<rangle>)\"\n    apply(rule equal_exp_symm)\n    by(rule equal_exp_assoc)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>\\<one>\\<rangle> :+: (\\<langle>m\\<rangle> :+: \\<langle>l\\<rangle>)\"\n    apply(rule equal_exp_cong_plus)\n    apply(rule equal_exp_refl)\n    by(rule S)\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>\\<one>\\<rangle> :+: \\<langle>m\\<rangle>) :+: \\<langle>l\\<rangle>\"\n    by(rule equal_exp_assoc)\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>m\\<rangle> :+: \\<langle>\\<one>\\<rangle>) :+: \\<langle>l\\<rangle>\"\n    apply(rule equal_exp_cong_plus)\n    apply(rule plusone)\n    by(rule equal_exp_refl)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>m\\<rangle> :+: (\\<langle>\\<one>\\<rangle> :+: \\<langle>l\\<rangle>)\"\n    apply(rule equal_exp_symm)\n    by(rule equal_exp_assoc)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>m\\<rangle> :+: (\\<langle>l\\<rangle> :+: \\<langle>\\<one>\\<rangle>)\"\n    apply(rule equal_exp_cong_plus)\n    apply(rule equal_exp_refl)\n    by(rule plusone)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>m\\<rangle> :+: \\<langle>l+\\<one>\\<rangle>\"\n    apply(rule equal_exp_cong_plus)\n    apply(rule equal_exp_refl)\n    apply(rule equal_exp_symm)\n    by(rule equal_exp_plusone)\n  finally show ?case by simp\nqed\n\n\n(*I've added a simple tactic called exp_tac, which simply tries \nall* the rules on a goal in this order:\n\n1) try refl\n2) try plusone\n3) try symmetry and then plusone\n...\n6) try split on n + m and recursively try to solve n and m\n7) try custom derived rule\n8) try symmetry and then custom rule\n\n*this tactic does not apply the trans rule for obvious reasons\n*)\n\n\nmethod exp_tac uses rule = \n    rule equal_exp_refl |\n    rule equal_exp_plusone |\n    (rule equal_exp_symm ; rule equal_exp_plusone) |\n    rule equal_exp_assoc |\n    (rule equal_exp_symm ; rule equal_exp_assoc) |\n    (rule equal_exp_cong_plus ; (exp_tac rule:rule)+) |\n    rule rule  |\n    (rule equal_exp_symm ; rule rule)\n\n\nlemma plusone_isar: \"\\<langle>\\<one>\\<rangle> :+: \\<langle>n\\<rangle> \\<equiv>ex \\<langle>n\\<rangle> :+: \\<langle>\\<one>\\<rangle>\"\n(* Show 1+n=n+1 by induction on n:\n   If n=1, then 1+1=1+1\n   If n=Sm, then 1+n = 1+Sm = 1+(m+1) = (1+m)+1 = (m+1)+1 = Sm+1 = n+1\n*)\nproof (induction n)\n  case One\n  then show ?case by (simp add: equal_exp_refl)\nnext\n  case (S m)\n  have \"\\<langle>\\<one>\\<rangle> :+: \\<langle>m+\\<one>\\<rangle> \\<equiv>ex \\<langle>\\<one>\\<rangle> :+: (\\<langle>m\\<rangle> :+: \\<langle>\\<one>\\<rangle>)\" by exp_tac\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>\\<one>\\<rangle> :+: \\<langle>m\\<rangle>) :+: \\<langle>\\<one>\\<rangle>\" by exp_tac\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>m\\<rangle> :+: \\<langle>\\<one>\\<rangle>) :+: \\<langle>\\<one>\\<rangle>\" by(exp_tac rule:S)\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>m+\\<one>\\<rangle>) :+: \\<langle>\\<one>\\<rangle>\" by exp_tac\n  finally show ?case by simp\nqed\n\nlemma commutativity_num': \"\\<langle>n\\<rangle> :+: \\<langle>m\\<rangle> \\<equiv>ex \\<langle>m\\<rangle> :+: \\<langle>n\\<rangle>\"\n(* Induction on m: \n   If n=1, then we need to show 1+m=m+1, which we proved in lemma plusone\n   If n = Sl, then \n    n+m = Sl+m = (l+1)+m = (1+l)+m = 1+(l+m) = 1+(m+l) = (1+m)+l = (m+1)+l \n     = m+(1+l) = m+(l+1) =  m+n\n*)\nproof(induction n)\ncase One\n  then show ?case by (rule plusone)\nnext\n  case (S l)\n  have \"\\<langle>l+\\<one>\\<rangle> :+: \\<langle>m\\<rangle> \\<equiv>ex (\\<langle>l\\<rangle> :+: \\<langle>\\<one>\\<rangle>) :+: \\<langle>m\\<rangle>\" by exp_tac\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>\\<one>\\<rangle> :+: \\<langle>l\\<rangle>) :+: \\<langle>m\\<rangle>\" by(exp_tac rule:plusone)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>\\<one>\\<rangle> :+: (\\<langle>l\\<rangle> :+: \\<langle>m\\<rangle>)\" by exp_tac\n  also have      \"\\<dots> \\<equiv>ex \\<langle>\\<one>\\<rangle> :+: (\\<langle>m\\<rangle> :+: \\<langle>l\\<rangle>)\" by(exp_tac rule:S)\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>\\<one>\\<rangle> :+: \\<langle>m\\<rangle>) :+: \\<langle>l\\<rangle>\" by exp_tac\n  also have      \"\\<dots> \\<equiv>ex (\\<langle>m\\<rangle> :+: \\<langle>\\<one>\\<rangle>) :+: \\<langle>l\\<rangle>\" by(exp_tac rule:plusone)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>m\\<rangle> :+: (\\<langle>\\<one>\\<rangle> :+: \\<langle>l\\<rangle>)\" by exp_tac\n  also have      \"\\<dots> \\<equiv>ex \\<langle>m\\<rangle> :+: (\\<langle>l\\<rangle> :+: \\<langle>\\<one>\\<rangle>)\" by(exp_tac rule:plusone)\n  also have      \"\\<dots> \\<equiv>ex \\<langle>m\\<rangle> :+: \\<langle>l+\\<one>\\<rangle>\" by exp_tac\n  finally show ?case by simp\nqed\n\nend\n\n", "meta": {"author": "andrewdieken", "repo": "programming-languages", "sha": "ef7a44092b8476624e320ef51e767d12400ee6d0", "save_path": "github-repos/isabelle/andrewdieken-programming-languages", "path": "github-repos/isabelle/andrewdieken-programming-languages/programming-languages-ef7a44092b8476624e320ef51e767d12400ee6d0/NumExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7871141329743191}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Cardinality of Multisets\\<close>\n\ntheory Card_Multisets\nimports\n  \"HOL-Library.Multiset\"\nbegin\n\nsubsection \\<open>Additions to Multiset Theory\\<close>\n\nlemma mset_set_set_mset_subseteq:\n  \"mset_set (set_mset M) \\<subseteq># M\"\nproof (induct M)\n  case empty\n  show ?case by simp\nnext\n  case (add x M)\n  from this show ?case\n  proof (cases \"x \\<in># M\")\n    assume \"x \\<in># M\"\n    from this have \"mset_set (set_mset (M + {#x#})) = mset_set (set_mset M)\"\n      by (simp add: insert_absorb)\n    from this add.hyps show ?thesis\n      using subset_mset.order.trans by fastforce\n  next\n    assume \"\\<not> x \\<in># M\"\n    from this add.hyps have \"{#x#} + mset_set (set_mset M) \\<subseteq># M + {#x#}\"\n      by (simp add: insert_subset_eq_iff)\n    from this \\<open>\\<not> x \\<in># M\\<close> show ?thesis by simp\n  qed\nqed\n\nlemma size_mset_set_eq_card:\n  assumes \"finite A\"\n  shows \"size (mset_set A) = card A\"\nusing assms by (induct A) auto\n\nlemma card_set_mset_leq:\n  \"card (set_mset M) \\<le> size M\"\nby (induct M) (auto simp add: card_insert_le_m1)\n\nsubsection \\<open>Lemma to Enumerate Sets of Multisets\\<close>\n\nlemma set_of_multisets_eq:\n  assumes \"x \\<notin> A\"\n  shows \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k} =\n    {M. set_mset M \\<subseteq> A \\<and> size M = Suc k} \\<union>\n    (\\<lambda>M. M + {#x#}) ` {M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\"\nproof -\n  from \\<open>x \\<notin> A\\<close> have \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k} =\n    {M. set_mset M \\<subseteq> A \\<and> size M = Suc k} \\<union>\n    {M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k \\<and> x \\<in># M}\"\n    by auto\n  moreover have \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k \\<and> x \\<in># M} =\n    (\\<lambda>M. M + {#x#}) ` {M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\" (is \"?S = ?T\")\n  proof\n    show \"?S \\<subseteq> ?T\"\n    proof\n      fix M\n      assume \"M \\<in> ?S\"\n      from this have \"M = M - {#x#} + {#x#}\" by auto\n      moreover have \"M - {#x#} \\<in> {M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\"\n      proof -\n        have \"set_mset (M - {#x#} + {#x#}) \\<subseteq> insert x A\"\n          using \\<open>M \\<in> ?S\\<close> by force\n        moreover have \"size (M - {#x#} + {#x#}) = Suc k \\<and> x \\<in># M - {#x#} + {#x#}\"\n          using \\<open>M \\<in> ?S\\<close> by force\n        ultimately show ?thesis by force\n      qed\n      ultimately show \"M \\<in> ?T\" by auto\n    qed\n  next\n    show \"?T \\<subseteq> ?S\" by force\n  qed\n  ultimately show ?thesis by auto\nqed\n\nsubsection \\<open>Derivation of Suitable Induction Rule\\<close>\n\ncontext\nbegin\n\nprivate inductive R :: \"'a set \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"finite A \\<Longrightarrow> R A 0\"\n| \"R {} k\"\n| \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> R A (Suc k) \\<Longrightarrow> R (insert x A) k \\<Longrightarrow> R (insert x A) (Suc k)\"\n\nprivate lemma R_eq_finite:\n  \"R A k \\<longleftrightarrow> finite A\"\nproof\n  assume \"R A k\"\n  from this show \"finite A\" by cases auto\nnext\n  assume \"finite A\"\n  from this show \"R A k\"\n  proof (induct A)\n    case empty\n    from this show ?case by (rule R.intros(2))\n  next\n    case insert\n    from this show ?case\n    proof (induct k)\n      case 0\n      from this show ?case\n        by (intro R.intros(1) finite.insertI)\n    next\n      case Suc\n      from this show ?case\n        by (metis R.simps Zero_neq_Suc diff_Suc_1)\n    qed\n  qed\nqed\n\nlemma finite_set_and_nat_induct[consumes 1, case_names zero empty step]:\n  assumes \"finite A\"\n  assumes \"\\<And>A. finite A \\<Longrightarrow> P A 0\"\n  assumes \"\\<And>k. P {} k\"\n  assumes \"\\<And>A k x. finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> P A (Suc k) \\<Longrightarrow> P (insert x A) k \\<Longrightarrow> P (insert x A) (Suc k)\"\n  shows \"P A k\"\nproof -\n  from \\<open>finite A\\<close> have \"R A k\" by (subst R_eq_finite)\n  from this assms(2-4) show ?thesis by (induct A k) auto\nqed\n\nend\n\nsubsection \\<open>Finiteness of Sets of Multisets\\<close>\n\nlemma finite_multisets:\n  assumes \"finite A\"\n  shows \"finite {M. set_mset M \\<subseteq> A \\<and> size M = k}\"\nusing assms\nproof (induct A k rule: finite_set_and_nat_induct)\n  case zero\n  from this show ?case by auto\nnext\n  case empty\n  from this show ?case by auto\nnext\n  case (step A k x)\n  from this show ?case\n    using set_of_multisets_eq[OF \\<open>x \\<notin> A\\<close>] by simp\nqed\n\nsubsection \\<open>Cardinality of Multisets\\<close>\n\nlemma card_multisets:\n  assumes \"finite A\"\n  shows \"card {M. set_mset M \\<subseteq> A \\<and> size M = k} = (card A + k - 1) choose k\"\nusing assms\nproof (induct A k rule: finite_set_and_nat_induct)\n  case (zero A)\n  assume \"finite (A :: 'a set)\"\n  have \"{M. set_mset M \\<subseteq> A \\<and> size M = 0} = {{#}}\" by auto\n  from this show \"card {M. set_mset M \\<subseteq> A \\<and> size M = 0} = card A + 0 - 1 choose 0\"\n    by simp\nnext\n  case (empty k)\n  show \"card {M. set_mset M \\<subseteq> {} \\<and> size M = k} = card {} + k - 1 choose k\"\n    by (cases k) (auto simp add: binomial_eq_0)\nnext\n  case (step A k x)\n  let ?S\\<^sub>1 = \"{M. set_mset M \\<subseteq> A \\<and> size M = Suc k}\"\n  and ?S\\<^sub>2 = \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\"\n  assume hyps1: \"card ?S\\<^sub>1 = card A + Suc k - 1 choose Suc k\"\n  assume hyps2: \"card ?S\\<^sub>2 = card (insert x A) + k - 1 choose k\"\n  have finite_sets: \"finite ?S\\<^sub>1\" \"finite ((\\<lambda>M. M + {#x#}) ` ?S\\<^sub>2)\"\n    using \\<open>finite A\\<close> by (auto simp add: finite_multisets)\n  have inj: \"inj_on (\\<lambda>M. M + {#x#}) ?S\\<^sub>2\" by (rule inj_onI) auto\n  have \"card {M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k} =\n    card (?S\\<^sub>1 \\<union> (\\<lambda>M. M + {#x#}) ` ?S\\<^sub>2)\"\n    using set_of_multisets_eq \\<open>x \\<notin> A\\<close> by fastforce\n  also have \"\\<dots> = card ?S\\<^sub>1 + card ((\\<lambda>M. M + {#x#}) ` ?S\\<^sub>2)\"\n    using finite_sets \\<open>x \\<notin> A\\<close> by (subst card_Un_disjoint) auto\n  also have \"\\<dots> = card ?S\\<^sub>1 + card ?S\\<^sub>2\"\n    using inj by (auto intro: card_image)\n  also have \"\\<dots> = card A + Suc k - 1 choose Suc k + (card (insert x A) + k - 1 choose k)\"\n    using hyps1 hyps2 by simp\n  also have \"\\<dots> = card (insert x A) + Suc k - 1 choose Suc k\"\n    using \\<open>x \\<notin> A\\<close> \\<open>finite A\\<close> by simp\n  finally show ?case .\nqed\n\nlemma card_too_small_multisets_covering_set:\n  assumes \"finite A\"\n  assumes \"k < card A\"\n  shows \"card {M. set_mset M = A \\<and> size M = k} = 0\"\nproof -\n  from \\<open>k < card A\\<close> have eq: \"{M. set_mset M = A \\<and> size M = k} = {}\"\n    using card_set_mset_leq Collect_empty_eq leD by auto\n  from this show ?thesis by (metis card_empty)\nqed\n\nlemma card_multisets_covering_set:\n  assumes \"finite A\"\n  assumes \"card A \\<le> k\"\n  shows \"card {M. set_mset M = A \\<and> size M = k} = (k - 1) choose (k - card A)\"\nproof -\n  have \"{M. set_mset M = A \\<and> size M = k} = (\\<lambda>M. M + mset_set A) `\n    {M. set_mset M \\<subseteq> A \\<and> size M = k - card A}\" (is \"?S = ?f ` ?T\")\n  proof\n    show \"?S \\<subseteq> ?f ` ?T\"\n    proof\n      fix M\n      assume \"M \\<in> ?S\"\n      from this have \"M = M - mset_set A + mset_set A\"\n        by (auto simp add: mset_set_set_mset_subseteq subset_mset.diff_add)\n      moreover from \\<open>M \\<in> ?S\\<close> have \"M - mset_set A \\<in> ?T\"\n        by (auto simp add: mset_set_set_mset_subseteq size_Diff_submset size_mset_set_eq_card in_diffD)\n      ultimately show \"M \\<in> ?f ` ?T\" by auto\n    qed\n  next\n    from \\<open>finite A\\<close> \\<open>card A \\<le> k\\<close> show \"?f ` ?T \\<subseteq> ?S\"\n      by (auto simp add: size_mset_set_eq_card)+\n  qed\n  moreover have \"inj_on ?f ?T\" by (rule inj_onI) auto\n  ultimately have \"card ?S = card ?T\" by (simp add: card_image)\n  also have \"\\<dots> = card A + (k - card A) - 1 choose (k - card A)\"\n    using \\<open>finite A\\<close> by (simp only: card_multisets)\n  also have \"\\<dots> = (k - 1) choose (k - card A)\"\n    using \\<open>card A \\<le> k\\<close> by auto\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Card_Multisets/Card_Multisets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8840392756357326, "lm_q1q2_score": 0.7870550653368599}}
{"text": "(*  Author: John Harrison, Marco Maggesi, Graziano Gentili, Gianni Ciolli, Valentina Bruno\n    Ported from \"hol_light/Multivariate/canal.ml\" by L C Paulson (2014)\n*)\n\nsection {* Complex Analysis Basics *}\n\ntheory Complex_Analysis_Basics\nimports  \"~~/src/HOL/Multivariate_Analysis/Cartesian_Euclidean_Space\"\nbegin\n\nsubsection{*General lemmas*}\n\nlemma has_derivative_mult_right:\n  fixes c:: \"'a :: real_normed_algebra\"\n  shows \"((op * c) has_derivative (op * c)) F\"\nby (rule has_derivative_mult_right [OF has_derivative_id])\n\nlemma has_derivative_of_real[derivative_intros, simp]: \n  \"(f has_derivative f') F \\<Longrightarrow> ((\\<lambda>x. of_real (f x)) has_derivative (\\<lambda>x. of_real (f' x))) F\"\n  using bounded_linear.has_derivative[OF bounded_linear_of_real] .\n\nlemma has_vector_derivative_real_complex:\n  \"DERIV f (of_real a) :> f' \\<Longrightarrow> ((\\<lambda>x. f (of_real x)) has_vector_derivative f') (at a)\"\n  using has_derivative_compose[of of_real of_real a UNIV f \"op * f'\"]\n  by (simp add: scaleR_conv_of_real ac_simps has_vector_derivative_def has_field_derivative_def)\n\nlemma fact_cancel:\n  fixes c :: \"'a::real_field\"\n  shows \"of_nat (Suc n) * c / of_nat (fact (Suc n)) = c / of_nat (fact n)\"\n  by (simp add: of_nat_mult del: of_nat_Suc times_nat.simps)\n\nlemma linear_times:\n  fixes c::\"'a::real_algebra\" shows \"linear (\\<lambda>x. c * x)\"\n  by (auto simp: linearI distrib_left)\n\nlemma bilinear_times:\n  fixes c::\"'a::real_algebra\" shows \"bilinear (\\<lambda>x y::'a. x*y)\"\n  by (auto simp: bilinear_def distrib_left distrib_right intro!: linearI)\n\nlemma linear_cnj: \"linear cnj\"\n  using bounded_linear.linear[OF bounded_linear_cnj] .\n\nlemma tendsto_mult_left:\n  fixes c::\"'a::real_normed_algebra\" \n  shows \"(f ---> l) F \\<Longrightarrow> ((\\<lambda>x. c * (f x)) ---> c * l) F\"\nby (rule tendsto_mult [OF tendsto_const])\n\nlemma tendsto_mult_right:\n  fixes c::\"'a::real_normed_algebra\" \n  shows \"(f ---> l) F \\<Longrightarrow> ((\\<lambda>x. (f x) * c) ---> l * c) F\"\nby (rule tendsto_mult [OF _ tendsto_const])\n\nlemma tendsto_Re_upper:\n  assumes \"~ (trivial_limit F)\" \n          \"(f ---> l) F\" \n          \"eventually (\\<lambda>x. Re(f x) \\<le> b) F\"\n    shows  \"Re(l) \\<le> b\"\n  by (metis assms tendsto_le [OF _ tendsto_const]  tendsto_Re)\n\nlemma tendsto_Re_lower:\n  assumes \"~ (trivial_limit F)\" \n          \"(f ---> l) F\" \n          \"eventually (\\<lambda>x. b \\<le> Re(f x)) F\"\n    shows  \"b \\<le> Re(l)\"\n  by (metis assms tendsto_le [OF _ _ tendsto_const]  tendsto_Re)\n\nlemma tendsto_Im_upper:\n  assumes \"~ (trivial_limit F)\" \n          \"(f ---> l) F\" \n          \"eventually (\\<lambda>x. Im(f x) \\<le> b) F\"\n    shows  \"Im(l) \\<le> b\"\n  by (metis assms tendsto_le [OF _ tendsto_const]  tendsto_Im)\n\nlemma tendsto_Im_lower:\n  assumes \"~ (trivial_limit F)\" \n          \"(f ---> l) F\" \n          \"eventually (\\<lambda>x. b \\<le> Im(f x)) F\"\n    shows  \"b \\<le> Im(l)\"\n  by (metis assms tendsto_le [OF _ _ tendsto_const]  tendsto_Im)\n\nlemma lambda_zero: \"(\\<lambda>h::'a::mult_zero. 0) = op * 0\"\n  by auto\n\nlemma lambda_one: \"(\\<lambda>x::'a::monoid_mult. x) = op * 1\"\n  by auto\n\nlemma has_real_derivative:\n  fixes f :: \"real \\<Rightarrow> real\" \n  assumes \"(f has_derivative f') F\"\n  obtains c where \"(f has_real_derivative c) F\"\nproof -\n  obtain c where \"f' = (\\<lambda>x. x * c)\"\n    by (metis assms has_derivative_bounded_linear real_bounded_linear)\n  then show ?thesis\n    by (metis assms that has_field_derivative_def mult_commute_abs)\nqed\n\nlemma has_real_derivative_iff:\n  fixes f :: \"real \\<Rightarrow> real\" \n  shows \"(\\<exists>c. (f has_real_derivative c) F) = (\\<exists>D. (f has_derivative D) F)\"\n  by (metis has_field_derivative_def has_real_derivative)\n\nlemma continuous_mult_left:\n  fixes c::\"'a::real_normed_algebra\" \n  shows \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. c * f x)\"\nby (rule continuous_mult [OF continuous_const])\n\nlemma continuous_mult_right:\n  fixes c::\"'a::real_normed_algebra\" \n  shows \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. f x * c)\"\nby (rule continuous_mult [OF _ continuous_const])\n\nlemma continuous_on_mult_left:\n  fixes c::\"'a::real_normed_algebra\" \n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. c * f x)\"\nby (rule continuous_on_mult [OF continuous_on_const])\n\nlemma continuous_on_mult_right:\n  fixes c::\"'a::real_normed_algebra\" \n  shows \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. f x * c)\"\nby (rule continuous_on_mult [OF _ continuous_on_const])\n\nlemma uniformly_continuous_on_cmul_right [continuous_intros]:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_algebra\"\n  shows \"uniformly_continuous_on s f \\<Longrightarrow> uniformly_continuous_on s (\\<lambda>x. f x * c)\"\n  using bounded_linear.uniformly_continuous_on[OF bounded_linear_mult_left] . \n\nlemma uniformly_continuous_on_cmul_left[continuous_intros]:\n  fixes f :: \"'a::real_normed_vector \\<Rightarrow> 'b::real_normed_algebra\"\n  assumes \"uniformly_continuous_on s f\"\n    shows \"uniformly_continuous_on s (\\<lambda>x. c * f x)\"\nby (metis assms bounded_linear.uniformly_continuous_on bounded_linear_mult_right)\n\nlemma continuous_within_norm_id [continuous_intros]: \"continuous (at x within S) norm\"\n  by (rule continuous_norm [OF continuous_ident])\n\nlemma continuous_on_norm_id [continuous_intros]: \"continuous_on S norm\"\n  by (intro continuous_on_id continuous_on_norm)\n\nsubsection{*DERIV stuff*}\n\nlemma DERIV_zero_connected_constant:\n  fixes f :: \"'a::{real_normed_field,euclidean_space} \\<Rightarrow> 'a\"\n  assumes \"connected s\"\n      and \"open s\"\n      and \"finite k\"\n      and \"continuous_on s f\"\n      and \"\\<forall>x\\<in>(s - k). DERIV f x :> 0\"\n    obtains c where \"\\<And>x. x \\<in> s \\<Longrightarrow> f(x) = c\"\nusing has_derivative_zero_connected_constant [OF assms(1-4)] assms\nby (metis DERIV_const has_derivative_const Diff_iff at_within_open frechet_derivative_at has_field_derivative_def)\n\nlemma DERIV_zero_constant:\n  fixes f :: \"'a::{real_normed_field, real_inner} \\<Rightarrow> 'a\"\n  shows    \"\\<lbrakk>convex s;\n             \\<And>x. x\\<in>s \\<Longrightarrow> (f has_field_derivative 0) (at x within s)\\<rbrakk> \n             \\<Longrightarrow> \\<exists>c. \\<forall>x \\<in> s. f(x) = c\"\n  by (auto simp: has_field_derivative_def lambda_zero intro: has_derivative_zero_constant)\n\nlemma DERIV_zero_unique:\n  fixes f :: \"'a::{real_normed_field, real_inner} \\<Rightarrow> 'a\"\n  assumes \"convex s\"\n      and d0: \"\\<And>x. x\\<in>s \\<Longrightarrow> (f has_field_derivative 0) (at x within s)\"\n      and \"a \\<in> s\"\n      and \"x \\<in> s\"\n    shows \"f x = f a\"\n  by (rule has_derivative_zero_unique [OF assms(1) _ assms(4,3)])\n     (metis d0 has_field_derivative_imp_has_derivative lambda_zero)\n\nlemma DERIV_zero_connected_unique:\n  fixes f :: \"'a::{real_normed_field, real_inner} \\<Rightarrow> 'a\"\n  assumes \"connected s\"\n      and \"open s\"\n      and d0: \"\\<And>x. x\\<in>s \\<Longrightarrow> DERIV f x :> 0\"\n      and \"a \\<in> s\"\n      and \"x \\<in> s\"\n    shows \"f x = f a\" \n    by (rule has_derivative_zero_unique_connected [OF assms(2,1) _ assms(5,4)])\n       (metis has_field_derivative_def lambda_zero d0)\n\nlemma DERIV_transform_within:\n  assumes \"(f has_field_derivative f') (at a within s)\"\n      and \"0 < d\" \"a \\<in> s\"\n      and \"\\<And>x. x\\<in>s \\<Longrightarrow> dist x a < d \\<Longrightarrow> f x = g x\"\n    shows \"(g has_field_derivative f') (at a within s)\"\n  using assms unfolding has_field_derivative_def\n  by (blast intro: has_derivative_transform_within)\n\nlemma DERIV_transform_within_open:\n  assumes \"DERIV f a :> f'\"\n      and \"open s\" \"a \\<in> s\"\n      and \"\\<And>x. x\\<in>s \\<Longrightarrow> f x = g x\"\n    shows \"DERIV g a :> f'\"\n  using assms unfolding has_field_derivative_def\nby (metis has_derivative_transform_within_open)\n\nlemma DERIV_transform_at:\n  assumes \"DERIV f a :> f'\"\n      and \"0 < d\"\n      and \"\\<And>x. dist x a < d \\<Longrightarrow> f x = g x\"\n    shows \"DERIV g a :> f'\"\n  by (blast intro: assms DERIV_transform_within)\n\nsubsection {*Some limit theorems about real part of real series etc.*}\n\n(*MOVE? But not to Finite_Cartesian_Product*)\nlemma sums_vec_nth :\n  assumes \"f sums a\"\n  shows \"(\\<lambda>x. f x $ i) sums a $ i\"\nusing assms unfolding sums_def\nby (auto dest: tendsto_vec_nth [where i=i])\n\nlemma summable_vec_nth :\n  assumes \"summable f\"\n  shows \"summable (\\<lambda>x. f x $ i)\"\nusing assms unfolding summable_def\nby (blast intro: sums_vec_nth)\n\nsubsection {*Complex number lemmas *}\n\nlemma\n  shows open_halfspace_Re_lt: \"open {z. Re(z) < b}\"\n    and open_halfspace_Re_gt: \"open {z. Re(z) > b}\"\n    and closed_halfspace_Re_ge: \"closed {z. Re(z) \\<ge> b}\"\n    and closed_halfspace_Re_le: \"closed {z. Re(z) \\<le> b}\"\n    and closed_halfspace_Re_eq: \"closed {z. Re(z) = b}\"\n    and open_halfspace_Im_lt: \"open {z. Im(z) < b}\"\n    and open_halfspace_Im_gt: \"open {z. Im(z) > b}\"\n    and closed_halfspace_Im_ge: \"closed {z. Im(z) \\<ge> b}\"\n    and closed_halfspace_Im_le: \"closed {z. Im(z) \\<le> b}\"\n    and closed_halfspace_Im_eq: \"closed {z. Im(z) = b}\"\n  by (intro open_Collect_less closed_Collect_le closed_Collect_eq isCont_Re\n            isCont_Im isCont_ident isCont_const)+\n\nlemma closed_complex_Reals: \"closed (Reals :: complex set)\"\nproof -\n  have \"(Reals :: complex set) = {z. Im z = 0}\"\n    by (auto simp: complex_is_Real_iff)\n  then show ?thesis\n    by (metis closed_halfspace_Im_eq)\nqed\n\nlemma real_lim:\n  fixes l::complex\n  assumes \"(f ---> l) F\" and \"~(trivial_limit F)\" and \"eventually P F\" and \"\\<And>a. P a \\<Longrightarrow> f a \\<in> \\<real>\"\n  shows  \"l \\<in> \\<real>\"\nproof (rule Lim_in_closed_set[OF closed_complex_Reals _ assms(2,1)])\n  show \"eventually (\\<lambda>x. f x \\<in> \\<real>) F\"\n    using assms(3, 4) by (auto intro: eventually_mono)\nqed\n\nlemma real_lim_sequentially:\n  fixes l::complex\n  shows \"(f ---> l) sequentially \\<Longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. f n \\<in> \\<real>) \\<Longrightarrow> l \\<in> \\<real>\"\nby (rule real_lim [where F=sequentially]) (auto simp: eventually_sequentially)\n\nlemma real_series: \n  fixes l::complex\n  shows \"f sums l \\<Longrightarrow> (\\<And>n. f n \\<in> \\<real>) \\<Longrightarrow> l \\<in> \\<real>\"\nunfolding sums_def\nby (metis real_lim_sequentially setsum_in_Reals)\n\nlemma Lim_null_comparison_Re:\n  assumes \"eventually (\\<lambda>x. norm(f x) \\<le> Re(g x)) F\" \"(g ---> 0) F\" shows \"(f ---> 0) F\"\n  by (rule Lim_null_comparison[OF assms(1)] tendsto_eq_intros assms(2))+ simp\n\nsubsection{*Holomorphic functions*}\n\ndefinition complex_differentiable :: \"[complex \\<Rightarrow> complex, complex filter] \\<Rightarrow> bool\"\n           (infixr \"(complex'_differentiable)\" 50)  \n  where \"f complex_differentiable F \\<equiv> \\<exists>f'. (f has_field_derivative f') F\"\n\nlemma complex_differentiable_imp_continuous_at:\n    \"f complex_differentiable (at x within s) \\<Longrightarrow> continuous (at x within s) f\"\n  by (metis DERIV_continuous complex_differentiable_def)\n\nlemma complex_differentiable_within_subset:\n    \"\\<lbrakk>f complex_differentiable (at x within s); t \\<subseteq> s\\<rbrakk>\n     \\<Longrightarrow> f complex_differentiable (at x within t)\"\n  by (metis DERIV_subset complex_differentiable_def)\n\nlemma complex_differentiable_at_within:\n    \"\\<lbrakk>f complex_differentiable (at x)\\<rbrakk>\n     \\<Longrightarrow> f complex_differentiable (at x within s)\"\n  unfolding complex_differentiable_def\n  by (metis DERIV_subset top_greatest)\n\nlemma complex_differentiable_linear: \"(op * c) complex_differentiable F\"\nproof -\n  show ?thesis\n    unfolding complex_differentiable_def has_field_derivative_def mult_commute_abs\n    by (force intro: has_derivative_mult_right)\nqed\n\nlemma complex_differentiable_const: \"(\\<lambda>z. c) complex_differentiable F\"\n  unfolding complex_differentiable_def has_field_derivative_def\n  by (rule exI [where x=0])\n     (metis has_derivative_const lambda_zero) \n\nlemma complex_differentiable_ident: \"(\\<lambda>z. z) complex_differentiable F\"\n  unfolding complex_differentiable_def has_field_derivative_def\n  by (rule exI [where x=1])\n     (simp add: lambda_one [symmetric])\n\nlemma complex_differentiable_id: \"id complex_differentiable F\"\n  unfolding id_def by (rule complex_differentiable_ident)\n\nlemma complex_differentiable_minus:\n  \"f complex_differentiable F \\<Longrightarrow> (\\<lambda>z. - (f z)) complex_differentiable F\"\n  using assms unfolding complex_differentiable_def\n  by (metis field_differentiable_minus)\n\nlemma complex_differentiable_add:\n  assumes \"f complex_differentiable F\" \"g complex_differentiable F\"\n    shows \"(\\<lambda>z. f z + g z) complex_differentiable F\"\n  using assms unfolding complex_differentiable_def\n  by (metis field_differentiable_add)\n\nlemma complex_differentiable_setsum:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) complex_differentiable F) \\<Longrightarrow> (\\<lambda>z. \\<Sum>i\\<in>I. f i z) complex_differentiable F\"\n  by (induct I rule: infinite_finite_induct)\n     (auto intro: complex_differentiable_add complex_differentiable_const)\n\nlemma complex_differentiable_diff:\n  assumes \"f complex_differentiable F\" \"g complex_differentiable F\"\n    shows \"(\\<lambda>z. f z - g z) complex_differentiable F\"\n  using assms unfolding complex_differentiable_def\n  by (metis field_differentiable_diff)\n\nlemma complex_differentiable_inverse:\n  assumes \"f complex_differentiable (at a within s)\" \"f a \\<noteq> 0\"\n  shows \"(\\<lambda>z. inverse (f z)) complex_differentiable (at a within s)\"\n  using assms unfolding complex_differentiable_def\n  by (metis DERIV_inverse_fun)\n\nlemma complex_differentiable_mult:\n  assumes \"f complex_differentiable (at a within s)\" \n          \"g complex_differentiable (at a within s)\"\n    shows \"(\\<lambda>z. f z * g z) complex_differentiable (at a within s)\"\n  using assms unfolding complex_differentiable_def\n  by (metis DERIV_mult [of f _ a s g])\n  \nlemma complex_differentiable_divide:\n  assumes \"f complex_differentiable (at a within s)\" \n          \"g complex_differentiable (at a within s)\"\n          \"g a \\<noteq> 0\"\n    shows \"(\\<lambda>z. f z / g z) complex_differentiable (at a within s)\"\n  using assms unfolding complex_differentiable_def\n  by (metis DERIV_divide [of f _ a s g])\n\nlemma complex_differentiable_power:\n  assumes \"f complex_differentiable (at a within s)\" \n    shows \"(\\<lambda>z. f z ^ n) complex_differentiable (at a within s)\"\n  using assms unfolding complex_differentiable_def\n  by (metis DERIV_power)\n\nlemma complex_differentiable_transform_within:\n  \"0 < d \\<Longrightarrow>\n        x \\<in> s \\<Longrightarrow>\n        (\\<And>x'. x' \\<in> s \\<Longrightarrow> dist x' x < d \\<Longrightarrow> f x' = g x') \\<Longrightarrow>\n        f complex_differentiable (at x within s)\n        \\<Longrightarrow> g complex_differentiable (at x within s)\"\n  unfolding complex_differentiable_def has_field_derivative_def\n  by (blast intro: has_derivative_transform_within)\n\nlemma complex_differentiable_compose_within:\n  assumes \"f complex_differentiable (at a within s)\" \n          \"g complex_differentiable (at (f a) within f`s)\"\n    shows \"(g o f) complex_differentiable (at a within s)\"\n  using assms unfolding complex_differentiable_def\n  by (metis DERIV_image_chain)\n\nlemma complex_differentiable_compose:\n  \"f complex_differentiable at z \\<Longrightarrow> g complex_differentiable at (f z)\n          \\<Longrightarrow> (g o f) complex_differentiable at z\"\nby (metis complex_differentiable_at_within complex_differentiable_compose_within)\n\nlemma complex_differentiable_within_open:\n     \"\\<lbrakk>a \\<in> s; open s\\<rbrakk> \\<Longrightarrow> f complex_differentiable at a within s \\<longleftrightarrow> \n                          f complex_differentiable at a\"\n  unfolding complex_differentiable_def\n  by (metis at_within_open)\n\nsubsection{*Caratheodory characterization.*}\n\nlemma complex_differentiable_caratheodory_at:\n  \"f complex_differentiable (at z) \\<longleftrightarrow>\n         (\\<exists>g. (\\<forall>w. f(w) - f(z) = g(w) * (w - z)) \\<and> continuous (at z) g)\"\n  using CARAT_DERIV [of f]\n  by (simp add: complex_differentiable_def has_field_derivative_def)\n\nlemma complex_differentiable_caratheodory_within:\n  \"f complex_differentiable (at z within s) \\<longleftrightarrow>\n         (\\<exists>g. (\\<forall>w. f(w) - f(z) = g(w) * (w - z)) \\<and> continuous (at z within s) g)\"\n  using DERIV_caratheodory_within [of f]\n  by (simp add: complex_differentiable_def has_field_derivative_def)\n\nsubsection{*Holomorphic*}\n\ndefinition holomorphic_on :: \"[complex \\<Rightarrow> complex, complex set] \\<Rightarrow> bool\"\n           (infixl \"(holomorphic'_on)\" 50)\n  where \"f holomorphic_on s \\<equiv> \\<forall>x\\<in>s. f complex_differentiable (at x within s)\"\n  \nlemma holomorphic_on_empty: \"f holomorphic_on {}\"\n  by (simp add: holomorphic_on_def)\n\nlemma holomorphic_on_open:\n    \"open s \\<Longrightarrow> f holomorphic_on s \\<longleftrightarrow> (\\<forall>x \\<in> s. \\<exists>f'. DERIV f x :> f')\"\n  by (auto simp: holomorphic_on_def complex_differentiable_def has_field_derivative_def at_within_open [of _ s])\n\nlemma holomorphic_on_imp_continuous_on: \n    \"f holomorphic_on s \\<Longrightarrow> continuous_on s f\"\n  by (metis complex_differentiable_imp_continuous_at continuous_on_eq_continuous_within holomorphic_on_def) \n\nlemma holomorphic_on_subset:\n    \"f holomorphic_on s \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> f holomorphic_on t\"\n  unfolding holomorphic_on_def\n  by (metis complex_differentiable_within_subset subsetD)\n\nlemma holomorphic_transform: \"\\<lbrakk>f holomorphic_on s; \\<And>x. x \\<in> s \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> g holomorphic_on s\"\n  by (metis complex_differentiable_transform_within linordered_field_no_ub holomorphic_on_def)\n\nlemma holomorphic_cong: \"s = t ==> (\\<And>x. x \\<in> s \\<Longrightarrow> f x = g x) \\<Longrightarrow> f holomorphic_on s \\<longleftrightarrow> g holomorphic_on t\"\n  by (metis holomorphic_transform)\n\nlemma holomorphic_on_linear: \"(op * c) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_linear)\n\nlemma holomorphic_on_const: \"(\\<lambda>z. c) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_const)\n\nlemma holomorphic_on_ident: \"(\\<lambda>x. x) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_ident)\n\nlemma holomorphic_on_id: \"id holomorphic_on s\"\n  unfolding id_def by (rule holomorphic_on_ident)\n\nlemma holomorphic_on_compose:\n  \"f holomorphic_on s \\<Longrightarrow> g holomorphic_on (f ` s) \\<Longrightarrow> (g o f) holomorphic_on s\"\n  using complex_differentiable_compose_within[of f _ s g]\n  by (auto simp: holomorphic_on_def)\n\nlemma holomorphic_on_compose_gen:\n  \"f holomorphic_on s \\<Longrightarrow> g holomorphic_on t \\<Longrightarrow> f ` s \\<subseteq> t \\<Longrightarrow> (g o f) holomorphic_on s\"\n  by (metis holomorphic_on_compose holomorphic_on_subset)\n\nlemma holomorphic_on_minus: \"f holomorphic_on s \\<Longrightarrow> (\\<lambda>z. -(f z)) holomorphic_on s\"\n  by (metis complex_differentiable_minus holomorphic_on_def)\n\nlemma holomorphic_on_add:\n  \"\\<lbrakk>f holomorphic_on s; g holomorphic_on s\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z + g z) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_add)\n\nlemma holomorphic_on_diff:\n  \"\\<lbrakk>f holomorphic_on s; g holomorphic_on s\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z - g z) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_diff)\n\nlemma holomorphic_on_mult:\n  \"\\<lbrakk>f holomorphic_on s; g holomorphic_on s\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z * g z) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_mult)\n\nlemma holomorphic_on_inverse:\n  \"\\<lbrakk>f holomorphic_on s; \\<And>z. z \\<in> s \\<Longrightarrow> f z \\<noteq> 0\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. inverse (f z)) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_inverse)\n\nlemma holomorphic_on_divide:\n  \"\\<lbrakk>f holomorphic_on s; g holomorphic_on s; \\<And>z. z \\<in> s \\<Longrightarrow> g z \\<noteq> 0\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z / g z) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_divide)\n\nlemma holomorphic_on_power:\n  \"f holomorphic_on s \\<Longrightarrow> (\\<lambda>z. (f z)^n) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_power)\n\nlemma holomorphic_on_setsum:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) holomorphic_on s) \\<Longrightarrow> (\\<lambda>x. setsum (\\<lambda>i. f i x) I) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis complex_differentiable_setsum)\n\ndefinition deriv :: \"('a \\<Rightarrow> 'a::real_normed_field) \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"deriv f x \\<equiv> THE D. DERIV f x :> D\"\n\nlemma DERIV_imp_deriv: \"DERIV f x :> f' \\<Longrightarrow> deriv f x = f'\"\n  unfolding deriv_def by (metis the_equality DERIV_unique)\n\nlemma DERIV_deriv_iff_real_differentiable:\n  fixes x :: real\n  shows \"DERIV f x :> deriv f x \\<longleftrightarrow> f differentiable at x\"\n  unfolding differentiable_def by (metis DERIV_imp_deriv has_real_derivative_iff)\n\nlemma real_derivative_chain:\n  fixes x :: real\n  shows \"f differentiable at x \\<Longrightarrow> g differentiable at (f x)\n    \\<Longrightarrow> deriv (g o f) x = deriv g (f x) * deriv f x\"\n  by (metis DERIV_deriv_iff_real_differentiable DERIV_chain DERIV_imp_deriv)\n\nlemma DERIV_deriv_iff_complex_differentiable:\n  \"DERIV f x :> deriv f x \\<longleftrightarrow> f complex_differentiable at x\"\n  unfolding complex_differentiable_def by (metis DERIV_imp_deriv)\n\nlemma complex_derivative_chain:\n  \"f complex_differentiable at x \\<Longrightarrow> g complex_differentiable at (f x)\n    \\<Longrightarrow> deriv (g o f) x = deriv g (f x) * deriv f x\"\n  by (metis DERIV_deriv_iff_complex_differentiable DERIV_chain DERIV_imp_deriv)\n\nlemma complex_derivative_linear: \"deriv (\\<lambda>w. c * w) = (\\<lambda>z. c)\"\n  by (metis DERIV_imp_deriv DERIV_cmult_Id)\n\nlemma complex_derivative_ident: \"deriv (\\<lambda>w. w) = (\\<lambda>z. 1)\"\n  by (metis DERIV_imp_deriv DERIV_ident)\n\nlemma complex_derivative_const: \"deriv (\\<lambda>w. c) = (\\<lambda>z. 0)\"\n  by (metis DERIV_imp_deriv DERIV_const)\n\nlemma complex_derivative_add:\n  \"\\<lbrakk>f complex_differentiable at z; g complex_differentiable at z\\<rbrakk>  \n   \\<Longrightarrow> deriv (\\<lambda>w. f w + g w) z = deriv f z + deriv g z\"\n  unfolding DERIV_deriv_iff_complex_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma complex_derivative_diff:\n  \"\\<lbrakk>f complex_differentiable at z; g complex_differentiable at z\\<rbrakk>  \n   \\<Longrightarrow> deriv (\\<lambda>w. f w - g w) z = deriv f z - deriv g z\"\n  unfolding DERIV_deriv_iff_complex_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_intros)\n\nlemma complex_derivative_mult:\n  \"\\<lbrakk>f complex_differentiable at z; g complex_differentiable at z\\<rbrakk>  \n   \\<Longrightarrow> deriv (\\<lambda>w. f w * g w) z = f z * deriv g z + deriv f z * g z\"\n  unfolding DERIV_deriv_iff_complex_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma complex_derivative_cmult:\n  \"f complex_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. c * f w) z = c * deriv f z\"\n  unfolding DERIV_deriv_iff_complex_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma complex_derivative_cmult_right:\n  \"f complex_differentiable at z \\<Longrightarrow> deriv (\\<lambda>w. f w * c) z = deriv f z * c\"\n  unfolding DERIV_deriv_iff_complex_differentiable[symmetric]\n  by (auto intro!: DERIV_imp_deriv derivative_eq_intros)\n\nlemma complex_derivative_transform_within_open:\n  \"\\<lbrakk>f holomorphic_on s; g holomorphic_on s; open s; z \\<in> s; \\<And>w. w \\<in> s \\<Longrightarrow> f w = g w\\<rbrakk> \n   \\<Longrightarrow> deriv f z = deriv g z\"\n  unfolding holomorphic_on_def\n  by (rule DERIV_imp_deriv)\n     (metis DERIV_deriv_iff_complex_differentiable DERIV_transform_within_open at_within_open)\n\nlemma complex_derivative_compose_linear:\n  \"f complex_differentiable at (c * z) \\<Longrightarrow> deriv (\\<lambda>w. f (c * w)) z = c * deriv f (c * z)\"\napply (rule DERIV_imp_deriv)\napply (simp add: DERIV_deriv_iff_complex_differentiable [symmetric])\napply (metis DERIV_chain' DERIV_cmult_Id comm_semiring_1_class.normalizing_semiring_rules(7))  \ndone\n\nsubsection{*analyticity on a set*}\n\ndefinition analytic_on (infixl \"(analytic'_on)\" 50)  \n  where\n   \"f analytic_on s \\<equiv> \\<forall>x \\<in> s. \\<exists>e. 0 < e \\<and> f holomorphic_on (ball x e)\"\n\nlemma analytic_imp_holomorphic: \"f analytic_on s \\<Longrightarrow> f holomorphic_on s\"\n  by (simp add: at_within_open [OF _ open_ball] analytic_on_def holomorphic_on_def)\n     (metis centre_in_ball complex_differentiable_at_within)\n\nlemma analytic_on_open: \"open s \\<Longrightarrow> f analytic_on s \\<longleftrightarrow> f holomorphic_on s\"\napply (auto simp: analytic_imp_holomorphic)\napply (auto simp: analytic_on_def holomorphic_on_def)\nby (metis holomorphic_on_def holomorphic_on_subset open_contains_ball)\n\nlemma analytic_on_imp_differentiable_at:\n  \"f analytic_on s \\<Longrightarrow> x \\<in> s \\<Longrightarrow> f complex_differentiable (at x)\"\n apply (auto simp: analytic_on_def holomorphic_on_def)\nby (metis Topology_Euclidean_Space.open_ball centre_in_ball complex_differentiable_within_open)\n\nlemma analytic_on_subset: \"f analytic_on s \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> f analytic_on t\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_Un: \"f analytic_on (s \\<union> t) \\<longleftrightarrow> f analytic_on s \\<and> f analytic_on t\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_Union: \"f analytic_on (\\<Union> s) \\<longleftrightarrow> (\\<forall>t \\<in> s. f analytic_on t)\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_UN: \"f analytic_on (\\<Union>i\\<in>I. s i) \\<longleftrightarrow> (\\<forall>i\\<in>I. f analytic_on (s i))\"\n  by (auto simp: analytic_on_def)\n  \nlemma analytic_on_holomorphic:\n  \"f analytic_on s \\<longleftrightarrow> (\\<exists>t. open t \\<and> s \\<subseteq> t \\<and> f holomorphic_on t)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs \\<longleftrightarrow> (\\<exists>t. open t \\<and> s \\<subseteq> t \\<and> f analytic_on t)\"\n  proof safe\n    assume \"f analytic_on s\"\n    then show \"\\<exists>t. open t \\<and> s \\<subseteq> t \\<and> f analytic_on t\"\n      apply (simp add: analytic_on_def)\n      apply (rule exI [where x=\"\\<Union>{u. open u \\<and> f analytic_on u}\"], auto)\n      apply (metis Topology_Euclidean_Space.open_ball analytic_on_open centre_in_ball)\n      by (metis analytic_on_def)\n  next\n    fix t\n    assume \"open t\" \"s \\<subseteq> t\" \"f analytic_on t\" \n    then show \"f analytic_on s\"\n        by (metis analytic_on_subset)\n  qed\n  also have \"... \\<longleftrightarrow> ?rhs\"\n    by (auto simp: analytic_on_open)\n  finally show ?thesis .\nqed\n\nlemma analytic_on_linear: \"(op * c) analytic_on s\"\n  by (auto simp add: analytic_on_holomorphic holomorphic_on_linear)\n\nlemma analytic_on_const: \"(\\<lambda>z. c) analytic_on s\"\n  by (metis analytic_on_def holomorphic_on_const zero_less_one)\n\nlemma analytic_on_ident: \"(\\<lambda>x. x) analytic_on s\"\n  by (simp add: analytic_on_def holomorphic_on_ident gt_ex)\n\nlemma analytic_on_id: \"id analytic_on s\"\n  unfolding id_def by (rule analytic_on_ident)\n\nlemma analytic_on_compose:\n  assumes f: \"f analytic_on s\"\n      and g: \"g analytic_on (f ` s)\"\n    shows \"(g o f) analytic_on s\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix x\n  assume x: \"x \\<in> s\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball x e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball (f x) e'\" using g\n    by (metis analytic_on_def g image_eqI x) \n  have \"isCont f x\"\n    by (metis analytic_on_imp_differentiable_at complex_differentiable_imp_continuous_at f x)\n  with e' obtain d where d: \"0 < d\" and fd: \"f ` ball x d \\<subseteq> ball (f x) e'\"\n     by (auto simp: continuous_at_ball)\n  have \"g \\<circ> f holomorphic_on ball x (min d e)\" \n    apply (rule holomorphic_on_compose)\n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis fd gh holomorphic_on_subset image_mono min.cobounded1 subset_ball)\n  then show \"\\<exists>e>0. g \\<circ> f holomorphic_on ball x e\"\n    by (metis d e min_less_iff_conj) \nqed\n\nlemma analytic_on_compose_gen:\n  \"f analytic_on s \\<Longrightarrow> g analytic_on t \\<Longrightarrow> (\\<And>z. z \\<in> s \\<Longrightarrow> f z \\<in> t)\n             \\<Longrightarrow> g o f analytic_on s\"\nby (metis analytic_on_compose analytic_on_subset image_subset_iff)\n\nlemma analytic_on_neg:\n  \"f analytic_on s \\<Longrightarrow> (\\<lambda>z. -(f z)) analytic_on s\"\nby (metis analytic_on_holomorphic holomorphic_on_minus)\n\nlemma analytic_on_add:\n  assumes f: \"f analytic_on s\"\n      and g: \"g analytic_on s\"\n    shows \"(\\<lambda>z. f z + g z) analytic_on s\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> s\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball z e'\" using g\n    by (metis analytic_on_def g z) \n  have \"(\\<lambda>z. f z + g z) holomorphic_on ball z (min e e')\" \n    apply (rule holomorphic_on_add) \n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis gh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n  then show \"\\<exists>e>0. (\\<lambda>z. f z + g z) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_diff:\n  assumes f: \"f analytic_on s\"\n      and g: \"g analytic_on s\"\n    shows \"(\\<lambda>z. f z - g z) analytic_on s\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> s\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball z e'\" using g\n    by (metis analytic_on_def g z) \n  have \"(\\<lambda>z. f z - g z) holomorphic_on ball z (min e e')\" \n    apply (rule holomorphic_on_diff) \n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis gh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n  then show \"\\<exists>e>0. (\\<lambda>z. f z - g z) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_mult:\n  assumes f: \"f analytic_on s\"\n      and g: \"g analytic_on s\"\n    shows \"(\\<lambda>z. f z * g z) analytic_on s\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> s\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball z e'\" using g\n    by (metis analytic_on_def g z) \n  have \"(\\<lambda>z. f z * g z) holomorphic_on ball z (min e e')\" \n    apply (rule holomorphic_on_mult) \n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis gh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n  then show \"\\<exists>e>0. (\\<lambda>z. f z * g z) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_inverse:\n  assumes f: \"f analytic_on s\"\n      and nz: \"(\\<And>z. z \\<in> s \\<Longrightarrow> f z \\<noteq> 0)\"\n    shows \"(\\<lambda>z. inverse (f z)) analytic_on s\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> s\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  have \"continuous_on (ball z e) f\"\n    by (metis fh holomorphic_on_imp_continuous_on)\n  then obtain e' where e': \"0 < e'\" and nz': \"\\<And>y. dist z y < e' \\<Longrightarrow> f y \\<noteq> 0\" \n    by (metis Topology_Euclidean_Space.open_ball centre_in_ball continuous_on_open_avoid e z nz)  \n  have \"(\\<lambda>z. inverse (f z)) holomorphic_on ball z (min e e')\" \n    apply (rule holomorphic_on_inverse)\n    apply (metis fh holomorphic_on_subset min.cobounded2 min.commute subset_ball)\n    by (metis nz' mem_ball min_less_iff_conj) \n  then show \"\\<exists>e>0. (\\<lambda>z. inverse (f z)) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\n\nlemma analytic_on_divide:\n  assumes f: \"f analytic_on s\"\n      and g: \"g analytic_on s\"\n      and nz: \"(\\<And>z. z \\<in> s \\<Longrightarrow> g z \\<noteq> 0)\"\n    shows \"(\\<lambda>z. f z / g z) analytic_on s\"\nunfolding divide_inverse\nby (metis analytic_on_inverse analytic_on_mult f g nz)\n\nlemma analytic_on_power:\n  \"f analytic_on s \\<Longrightarrow> (\\<lambda>z. (f z) ^ n) analytic_on s\"\nby (induct n) (auto simp: analytic_on_const analytic_on_mult)\n\nlemma analytic_on_setsum:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) analytic_on s) \\<Longrightarrow> (\\<lambda>x. setsum (\\<lambda>i. f i x) I) analytic_on s\"\n  by (induct I rule: infinite_finite_induct) (auto simp: analytic_on_const analytic_on_add)\n\nsubsection{*analyticity at a point.*}\n\nlemma analytic_at_ball:\n  \"f analytic_on {z} \\<longleftrightarrow> (\\<exists>e. 0<e \\<and> f holomorphic_on ball z e)\"\nby (metis analytic_on_def singleton_iff)\n\nlemma analytic_at:\n    \"f analytic_on {z} \\<longleftrightarrow> (\\<exists>s. open s \\<and> z \\<in> s \\<and> f holomorphic_on s)\"\nby (metis analytic_on_holomorphic empty_subsetI insert_subset)\n\nlemma analytic_on_analytic_at:\n    \"f analytic_on s \\<longleftrightarrow> (\\<forall>z \\<in> s. f analytic_on {z})\"\nby (metis analytic_at_ball analytic_on_def)\n\nlemma analytic_at_two:\n  \"f analytic_on {z} \\<and> g analytic_on {z} \\<longleftrightarrow>\n   (\\<exists>s. open s \\<and> z \\<in> s \\<and> f holomorphic_on s \\<and> g holomorphic_on s)\"\n  (is \"?lhs = ?rhs\")\nproof \n  assume ?lhs\n  then obtain s t \n    where st: \"open s\" \"z \\<in> s\" \"f holomorphic_on s\"\n              \"open t\" \"z \\<in> t\" \"g holomorphic_on t\"\n    by (auto simp: analytic_at)\n  show ?rhs\n    apply (rule_tac x=\"s \\<inter> t\" in exI)\n    using st\n    apply (auto simp: Diff_subset holomorphic_on_subset)\n    done\nnext\n  assume ?rhs \n  then show ?lhs\n    by (force simp add: analytic_at)\nqed\n\nsubsection{*Combining theorems for derivative with ``analytic at'' hypotheses*}\n\nlemma \n  assumes \"f analytic_on {z}\" \"g analytic_on {z}\"\n  shows complex_derivative_add_at: \"deriv (\\<lambda>w. f w + g w) z = deriv f z + deriv g z\"\n    and complex_derivative_diff_at: \"deriv (\\<lambda>w. f w - g w) z = deriv f z - deriv g z\"\n    and complex_derivative_mult_at: \"deriv (\\<lambda>w. f w * g w) z =\n           f z * deriv g z + deriv f z * g z\"\nproof -\n  obtain s where s: \"open s\" \"z \\<in> s\" \"f holomorphic_on s\" \"g holomorphic_on s\"\n    using assms by (metis analytic_at_two)\n  show \"deriv (\\<lambda>w. f w + g w) z = deriv f z + deriv g z\"\n    apply (rule DERIV_imp_deriv [OF DERIV_add])\n    using s\n    apply (auto simp: holomorphic_on_open complex_differentiable_def DERIV_deriv_iff_complex_differentiable)\n    done\n  show \"deriv (\\<lambda>w. f w - g w) z = deriv f z - deriv g z\"\n    apply (rule DERIV_imp_deriv [OF DERIV_diff])\n    using s\n    apply (auto simp: holomorphic_on_open complex_differentiable_def DERIV_deriv_iff_complex_differentiable)\n    done\n  show \"deriv (\\<lambda>w. f w * g w) z = f z * deriv g z + deriv f z * g z\"\n    apply (rule DERIV_imp_deriv [OF DERIV_mult'])\n    using s\n    apply (auto simp: holomorphic_on_open complex_differentiable_def DERIV_deriv_iff_complex_differentiable)\n    done\nqed\n\nlemma complex_derivative_cmult_at:\n  \"f analytic_on {z} \\<Longrightarrow>  deriv (\\<lambda>w. c * f w) z = c * deriv f z\"\nby (auto simp: complex_derivative_mult_at complex_derivative_const analytic_on_const)\n\nlemma complex_derivative_cmult_right_at:\n  \"f analytic_on {z} \\<Longrightarrow>  deriv (\\<lambda>w. f w * c) z = deriv f z * c\"\nby (auto simp: complex_derivative_mult_at complex_derivative_const analytic_on_const)\n\nsubsection{*Complex differentiation of sequences and series*}\n\nlemma has_complex_derivative_sequence:\n  fixes s :: \"complex set\"\n  assumes cvs: \"convex s\"\n      and df:  \"\\<And>n x. x \\<in> s \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within s)\"\n      and conv: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>N. \\<forall>n x. n \\<ge> N \\<longrightarrow> x \\<in> s \\<longrightarrow> norm (f' n x - g' x) \\<le> e\"\n      and \"\\<exists>x l. x \\<in> s \\<and> ((\\<lambda>n. f n x) ---> l) sequentially\"\n    shows \"\\<exists>g. \\<forall>x \\<in> s. ((\\<lambda>n. f n x) ---> g x) sequentially \\<and> \n                       (g has_field_derivative (g' x)) (at x within s)\"\nproof -\n  from assms obtain x l where x: \"x \\<in> s\" and tf: \"((\\<lambda>n. f n x) ---> l) sequentially\"\n    by blast\n  { fix e::real assume e: \"e > 0\"\n    then obtain N where N: \"\\<forall>n\\<ge>N. \\<forall>x. x \\<in> s \\<longrightarrow> cmod (f' n x - g' x) \\<le> e\"\n      by (metis conv)    \n    have \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>s. \\<forall>h. cmod (f' n x * h - g' x * h) \\<le> e * cmod h\"\n    proof (rule exI [of _ N], clarify)\n      fix n y h\n      assume \"N \\<le> n\" \"y \\<in> s\"\n      then have \"cmod (f' n y - g' y) \\<le> e\"\n        by (metis N)\n      then have \"cmod h * cmod (f' n y - g' y) \\<le> cmod h * e\"\n        by (auto simp: antisym_conv2 mult_le_cancel_left norm_triangle_ineq2)\n      then show \"cmod (f' n y * h - g' y * h) \\<le> e * cmod h\"\n        by (simp add: norm_mult [symmetric] field_simps)\n    qed\n  } note ** = this\n  show ?thesis\n  unfolding has_field_derivative_def\n  proof (rule has_derivative_sequence [OF cvs _ _ x])\n    show \"\\<forall>n. \\<forall>x\\<in>s. (f n has_derivative (op * (f' n x))) (at x within s)\"\n      by (metis has_field_derivative_def df)\n  next show \"(\\<lambda>n. f n x) ----> l\"\n    by (rule tf)\n  next show \"\\<forall>e>0. \\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>s. \\<forall>h. cmod (f' n x * h - g' x * h) \\<le> e * cmod h\"\n    by (blast intro: **)\n  qed\nqed\n\n\nlemma has_complex_derivative_series:\n  fixes s :: \"complex set\"\n  assumes cvs: \"convex s\"\n      and df:  \"\\<And>n x. x \\<in> s \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within s)\"\n      and conv: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>N. \\<forall>n x. n \\<ge> N \\<longrightarrow> x \\<in> s \n                \\<longrightarrow> cmod ((\\<Sum>i<n. f' i x) - g' x) \\<le> e\"\n      and \"\\<exists>x l. x \\<in> s \\<and> ((\\<lambda>n. f n x) sums l)\"\n    shows \"\\<exists>g. \\<forall>x \\<in> s. ((\\<lambda>n. f n x) sums g x) \\<and> ((g has_field_derivative g' x) (at x within s))\"\nproof -\n  from assms obtain x l where x: \"x \\<in> s\" and sf: \"((\\<lambda>n. f n x) sums l)\"\n    by blast\n  { fix e::real assume e: \"e > 0\"\n    then obtain N where N: \"\\<forall>n x. n \\<ge> N \\<longrightarrow> x \\<in> s \n            \\<longrightarrow> cmod ((\\<Sum>i<n. f' i x) - g' x) \\<le> e\"\n      by (metis conv)    \n    have \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>s. \\<forall>h. cmod ((\\<Sum>i<n. h * f' i x) - g' x * h) \\<le> e * cmod h\"\n    proof (rule exI [of _ N], clarify)\n      fix n y h\n      assume \"N \\<le> n\" \"y \\<in> s\"\n      then have \"cmod ((\\<Sum>i<n. f' i y) - g' y) \\<le> e\"\n        by (metis N)\n      then have \"cmod h * cmod ((\\<Sum>i<n. f' i y) - g' y) \\<le> cmod h * e\"\n        by (auto simp: antisym_conv2 mult_le_cancel_left norm_triangle_ineq2)\n      then show \"cmod ((\\<Sum>i<n. h * f' i y) - g' y * h) \\<le> e * cmod h\"\n        by (simp add: norm_mult [symmetric] field_simps setsum_right_distrib)\n    qed\n  } note ** = this\n  show ?thesis\n  unfolding has_field_derivative_def\n  proof (rule has_derivative_series [OF cvs _ _ x])\n    fix n x\n    assume \"x \\<in> s\"\n    then show \"((f n) has_derivative (\\<lambda>z. z * f' n x)) (at x within s)\"\n      by (metis df has_field_derivative_def mult_commute_abs)\n  next show \" ((\\<lambda>n. f n x) sums l)\"\n    by (rule sf)\n  next show \"\\<forall>e>0. \\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>s. \\<forall>h. cmod ((\\<Sum>i<n. h * f' i x) - g' x * h) \\<le> e * cmod h\"\n    by (blast intro: **)\n  qed\nqed\n\nsubsection{*Bound theorem*}\n\nlemma complex_differentiable_bound:\n  fixes s :: \"complex set\"\n  assumes cvs: \"convex s\"\n      and df:  \"\\<And>z. z \\<in> s \\<Longrightarrow> (f has_field_derivative f' z) (at z within s)\"\n      and dn:  \"\\<And>z. z \\<in> s \\<Longrightarrow> norm (f' z) \\<le> B\"\n      and \"x \\<in> s\"  \"y \\<in> s\"\n    shows \"norm(f x - f y) \\<le> B * norm(x - y)\"\n  apply (rule differentiable_bound [OF cvs])\n  apply (rule ballI, erule df [unfolded has_field_derivative_def])\n  apply (rule ballI, rule onorm_le, simp add: norm_mult mult_right_mono dn)\n  apply fact\n  apply fact\n  done\n\nsubsection{*Inverse function theorem for complex derivatives.*}\n\nlemma has_complex_derivative_inverse_basic:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  shows \"DERIV f (g y) :> f' \\<Longrightarrow>\n        f' \\<noteq> 0 \\<Longrightarrow>\n        continuous (at y) g \\<Longrightarrow>\n        open t \\<Longrightarrow>\n        y \\<in> t \\<Longrightarrow>\n        (\\<And>z. z \\<in> t \\<Longrightarrow> f (g z) = z)\n        \\<Longrightarrow> DERIV g y :> inverse (f')\"\n  unfolding has_field_derivative_def\n  apply (rule has_derivative_inverse_basic)\n  apply (auto simp:  bounded_linear_mult_right)\n  done\n\n(*Used only once, in Multivariate/cauchy.ml. *)\nlemma has_complex_derivative_inverse_strong:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  shows \"DERIV f x :> f' \\<Longrightarrow>\n         f' \\<noteq> 0 \\<Longrightarrow>\n         open s \\<Longrightarrow>\n         x \\<in> s \\<Longrightarrow>\n         continuous_on s f \\<Longrightarrow>\n         (\\<And>z. z \\<in> s \\<Longrightarrow> g (f z) = z)\n         \\<Longrightarrow> DERIV g (f x) :> inverse (f')\"\n  unfolding has_field_derivative_def\n  apply (rule has_derivative_inverse_strong [of s x f g ])\n  using assms \n  by auto\n\nlemma has_complex_derivative_inverse_strong_x:\n  fixes f :: \"complex \\<Rightarrow> complex\"\n  shows  \"DERIV f (g y) :> f' \\<Longrightarrow>\n          f' \\<noteq> 0 \\<Longrightarrow>\n          open s \\<Longrightarrow>\n          continuous_on s f \\<Longrightarrow>\n          g y \\<in> s \\<Longrightarrow> f(g y) = y \\<Longrightarrow>\n          (\\<And>z. z \\<in> s \\<Longrightarrow> g (f z) = z)\n          \\<Longrightarrow> DERIV g y :> inverse (f')\"\n  unfolding has_field_derivative_def\n  apply (rule has_derivative_inverse_strong_x [of s g y f])\n  using assms \n  by auto\n\nsubsection {* Taylor on Complex Numbers *}\n\nlemma setsum_Suc_reindex:\n  fixes f :: \"nat \\<Rightarrow> 'a::ab_group_add\"\n    shows  \"setsum f {0..n} = f 0 - f (Suc n) + setsum (\\<lambda>i. f (Suc i)) {0..n}\"\nby (induct n) auto\n\nlemma complex_taylor:\n  assumes s: \"convex s\" \n      and f: \"\\<And>i x. x \\<in> s \\<Longrightarrow> i \\<le> n \\<Longrightarrow> (f i has_field_derivative f (Suc i) x) (at x within s)\"\n      and B: \"\\<And>x. x \\<in> s \\<Longrightarrow> cmod (f (Suc n) x) \\<le> B\"\n      and w: \"w \\<in> s\"\n      and z: \"z \\<in> s\"\n    shows \"cmod(f 0 z - (\\<Sum>i\\<le>n. f i w * (z-w) ^ i / of_nat (fact i)))\n          \\<le> B * cmod(z - w)^(Suc n) / fact n\"\nproof -\n  have wzs: \"closed_segment w z \\<subseteq> s\" using assms\n    by (metis convex_contains_segment)\n  { fix u\n    assume \"u \\<in> closed_segment w z\"\n    then have \"u \\<in> s\"\n      by (metis wzs subsetD)\n    have \"(\\<Sum>i\\<le>n. f i u * (- of_nat i * (z-u)^(i - 1)) / of_nat (fact i) +\n                      f (Suc i) u * (z-u)^i / of_nat (fact i)) = \n              f (Suc n) u * (z-u) ^ n / of_nat (fact n)\"\n    proof (induction n)\n      case 0 show ?case by simp\n    next\n      case (Suc n)\n      have \"(\\<Sum>i\\<le>Suc n. f i u * (- of_nat i * (z-u) ^ (i - 1)) / of_nat (fact i) +\n                             f (Suc i) u * (z-u) ^ i / of_nat (fact i)) =  \n           f (Suc n) u * (z-u) ^ n / of_nat (fact n) +\n           f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n) / of_nat (fact (Suc n)) -\n           f (Suc n) u * ((1 + of_nat n) * (z-u) ^ n) / of_nat (fact (Suc n))\"\n        using Suc by simp\n      also have \"... = f (Suc (Suc n)) u * (z-u) ^ Suc n / of_nat (fact (Suc n))\"\n      proof -\n        have \"of_nat(fact(Suc n)) *\n             (f(Suc n) u *(z-u) ^ n / of_nat(fact n) +\n               f(Suc(Suc n)) u *((z-u) *(z-u) ^ n) / of_nat(fact(Suc n)) -\n               f(Suc n) u *((1 + of_nat n) *(z-u) ^ n) / of_nat(fact(Suc n))) =\n            (of_nat(fact(Suc n)) *(f(Suc n) u *(z-u) ^ n)) / of_nat(fact n) +\n            (of_nat(fact(Suc n)) *(f(Suc(Suc n)) u *((z-u) *(z-u) ^ n)) / of_nat(fact(Suc n))) -\n            (of_nat(fact(Suc n)) *(f(Suc n) u *(of_nat(Suc n) *(z-u) ^ n))) / of_nat(fact(Suc n))\"\n          by (simp add: algebra_simps del: fact_Suc)\n        also have \"... =\n                   (of_nat (fact (Suc n)) * (f (Suc n) u * (z-u) ^ n)) / of_nat (fact n) +\n                   (f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n)) -\n                   (f (Suc n) u * ((1 + of_nat n) * (z-u) ^ n))\"\n          by (simp del: fact_Suc)\n        also have \"... = \n                   (of_nat (Suc n) * (f (Suc n) u * (z-u) ^ n)) +\n                   (f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n)) -\n                   (f (Suc n) u * ((1 + of_nat n) * (z-u) ^ n))\"\n          by (simp only: fact_Suc of_nat_mult ac_simps) simp\n        also have \"... = f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n)\"\n          by (simp add: algebra_simps)\n        finally show ?thesis\n        by (simp add: mult_left_cancel [where c = \"of_nat (fact (Suc n))\", THEN iffD1] del: fact_Suc)\n      qed\n      finally show ?case .\n    qed\n    then have \"((\\<lambda>v. (\\<Sum>i\\<le>n. f i v * (z - v)^i / of_nat (fact i))) \n                has_field_derivative f (Suc n) u * (z-u) ^ n / of_nat (fact n))\n               (at u within s)\"\n      apply (intro derivative_eq_intros)\n      apply (blast intro: assms `u \\<in> s`)\n      apply (rule refl)+\n      apply (auto simp: field_simps)\n      done\n  } note sum_deriv = this\n  { fix u\n    assume u: \"u \\<in> closed_segment w z\"\n    then have us: \"u \\<in> s\"\n      by (metis wzs subsetD)\n    have \"cmod (f (Suc n) u) * cmod (z - u) ^ n \\<le> cmod (f (Suc n) u) * cmod (u - z) ^ n\"\n      by (metis norm_minus_commute order_refl)\n    also have \"... \\<le> cmod (f (Suc n) u) * cmod (z - w) ^ n\"\n      by (metis mult_left_mono norm_ge_zero power_mono segment_bound [OF u])\n    also have \"... \\<le> B * cmod (z - w) ^ n\"\n      by (metis norm_ge_zero zero_le_power mult_right_mono  B [OF us])\n    finally have \"cmod (f (Suc n) u) * cmod (z - u) ^ n \\<le> B * cmod (z - w) ^ n\" .\n  } note cmod_bound = this\n  have \"(\\<Sum>i\\<le>n. f i z * (z - z) ^ i / of_nat (fact i)) = (\\<Sum>i\\<le>n. (f i z / of_nat (fact i)) * 0 ^ i)\"\n    by simp\n  also have \"\\<dots> = f 0 z / of_nat (fact 0)\"\n    by (subst setsum_zero_power) simp\n  finally have \"cmod (f 0 z - (\\<Sum>i\\<le>n. f i w * (z - w) ^ i / of_nat (fact i))) \n            \\<le> cmod ((\\<Sum>i\\<le>n. f i w * (z - w) ^ i / of_nat (fact i)) -\n                    (\\<Sum>i\\<le>n. f i z * (z - z) ^ i / of_nat (fact i)))\"\n    by (simp add: norm_minus_commute)\n  also have \"... \\<le> B * cmod (z - w) ^ n / real_of_nat (fact n) * cmod (w - z)\"\n    apply (rule complex_differentiable_bound \n      [where f' = \"\\<lambda>w. f (Suc n) w * (z - w)^n / of_nat(fact n)\"\n         and s = \"closed_segment w z\", OF convex_segment])\n    apply (auto simp: ends_in_segment real_of_nat_def DERIV_subset [OF sum_deriv wzs]\n                  norm_divide norm_mult norm_power divide_le_cancel cmod_bound)\n    done\n  also have \"...  \\<le> B * cmod (z - w) ^ Suc n / real (fact n)\"\n    by (simp add: algebra_simps norm_minus_commute real_of_nat_def)\n  finally show ?thesis .\nqed\n\ntext{* Something more like the traditional MVT for real components.*}\n\nlemma complex_mvt_line:\n  assumes \"\\<And>u. u \\<in> closed_segment w z \\<Longrightarrow> (f has_field_derivative f'(u)) (at u)\"\n    shows \"\\<exists>u. u \\<in> open_segment w z \\<and> Re(f z) - Re(f w) = Re(f'(u) * (z - w))\"\nproof -\n  have twz: \"\\<And>t. (1 - t) *\\<^sub>R w + t *\\<^sub>R z = w + t *\\<^sub>R (z - w)\"\n    by (simp add: real_vector.scale_left_diff_distrib real_vector.scale_right_diff_distrib)\n  note assms[unfolded has_field_derivative_def, derivative_intros]\n  show ?thesis\n    apply (cut_tac mvt_simple\n                     [of 0 1 \"Re o f o (\\<lambda>t. (1 - t) *\\<^sub>R w +  t *\\<^sub>R z)\"\n                      \"\\<lambda>u. Re o (\\<lambda>h. f'((1 - u) *\\<^sub>R w + u *\\<^sub>R z) * h) o (\\<lambda>t. t *\\<^sub>R (z - w))\"])\n    apply auto\n    apply (rule_tac x=\"(1 - x) *\\<^sub>R w + x *\\<^sub>R z\" in exI)\n    apply (auto simp add: open_segment_def twz) []\n    apply (intro derivative_eq_intros has_derivative_at_within)\n    apply simp_all\n    apply (simp add: fun_eq_iff real_vector.scale_right_diff_distrib)\n    apply (force simp add: twz closed_segment_def)\n    done\nqed\n\nlemma complex_taylor_mvt:\n  assumes \"\\<And>i x. \\<lbrakk>x \\<in> closed_segment w z; i \\<le> n\\<rbrakk> \\<Longrightarrow> ((f i) has_field_derivative f (Suc i) x) (at x)\"\n    shows \"\\<exists>u. u \\<in> closed_segment w z \\<and>\n            Re (f 0 z) =\n            Re ((\\<Sum>i = 0..n. f i w * (z - w) ^ i / of_nat (fact i)) +\n                (f (Suc n) u * (z-u)^n / of_nat (fact n)) * (z - w))\"\nproof -\n  { fix u\n    assume u: \"u \\<in> closed_segment w z\"\n    have \"(\\<Sum>i = 0..n.\n               (f (Suc i) u * (z-u) ^ i - of_nat i * (f i u * (z-u) ^ (i - Suc 0))) /\n               of_nat (fact i)) =\n          f (Suc 0) u -\n             (f (Suc (Suc n)) u * ((z-u) ^ Suc n) - (of_nat (Suc n)) * (z-u) ^ n * f (Suc n) u) /\n             of_nat (fact (Suc n)) +\n             (\\<Sum>i = 0..n.\n                 (f (Suc (Suc i)) u * ((z-u) ^ Suc i) - of_nat (Suc i) * (f (Suc i) u * (z-u) ^ i)) /\n                 of_nat (fact (Suc i)))\"\n       by (subst setsum_Suc_reindex) simp\n    also have \"... = f (Suc 0) u -\n             (f (Suc (Suc n)) u * ((z-u) ^ Suc n) - (of_nat (Suc n)) * (z-u) ^ n * f (Suc n) u) /\n             of_nat (fact (Suc n)) +\n             (\\<Sum>i = 0..n.\n                 f (Suc (Suc i)) u * ((z-u) ^ Suc i) / of_nat (fact (Suc i))  - \n                 f (Suc i) u * (z-u) ^ i / of_nat (fact i))\"\n      by (simp only: diff_divide_distrib fact_cancel ac_simps)\n    also have \"... = f (Suc 0) u -\n             (f (Suc (Suc n)) u * (z-u) ^ Suc n - of_nat (Suc n) * (z-u) ^ n * f (Suc n) u) /\n             of_nat (fact (Suc n)) +\n             f (Suc (Suc n)) u * (z-u) ^ Suc n / of_nat (fact (Suc n)) - f (Suc 0) u\"\n      by (subst setsum_Suc_diff) auto\n    also have \"... = f (Suc n) u * (z-u) ^ n / of_nat (fact n)\"\n      by (simp only: algebra_simps diff_divide_distrib fact_cancel)\n    finally have \"(\\<Sum>i = 0..n. (f (Suc i) u * (z - u) ^ i \n                             - of_nat i * (f i u * (z-u) ^ (i - Suc 0))) / of_nat (fact i)) =\n                  f (Suc n) u * (z - u) ^ n / of_nat (fact n)\" .\n    then have \"((\\<lambda>u. \\<Sum>i = 0..n. f i u * (z - u) ^ i / of_nat (fact i)) has_field_derivative\n                f (Suc n) u * (z - u) ^ n / of_nat (fact n))  (at u)\"\n      apply (intro derivative_eq_intros)+\n      apply (force intro: u assms)\n      apply (rule refl)+\n      apply (auto simp: ac_simps)\n      done\n  }\n  then show ?thesis\n    apply (cut_tac complex_mvt_line [of w z \"\\<lambda>u. \\<Sum>i = 0..n. f i u * (z-u) ^ i / of_nat (fact i)\"\n               \"\\<lambda>u. (f (Suc n) u * (z-u)^n / of_nat (fact n))\"])\n    apply (auto simp add: intro: open_closed_segment)\n    done\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Multivariate_Analysis/Complex_Analysis_Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.7869589245598182}}
{"text": "(*<*)\ntheory ABexpr imports Main begin\n(*>*)\n\ntext{*\n\\index{datatypes!mutually recursive}%\nSometimes it is necessary to define two datatypes that depend on each\nother. This is called \\textbf{mutual recursion}. As an example consider a\nlanguage of arithmetic and boolean expressions where\n\\begin{itemize}\n\\item arithmetic expressions contain boolean expressions because there are\n  conditional expressions like ``if $m<n$ then $n-m$ else $m-n$'',\n  and\n\\item boolean expressions contain arithmetic expressions because of\n  comparisons like ``$m<n$''.\n\\end{itemize}\nIn Isabelle this becomes\n*}\n\ndatatype 'a aexp = IF   \"'a bexp\" \"'a aexp\" \"'a aexp\"\n                 | Sum  \"'a aexp\" \"'a aexp\"\n                 | Diff \"'a aexp\" \"'a aexp\"\n                 | Var 'a\n                 | Num nat\nand      'a bexp = Less \"'a aexp\" \"'a aexp\"\n                 | And  \"'a bexp\" \"'a bexp\"\n                 | Neg  \"'a bexp\"\n\ntext{*\\noindent\nType @{text\"aexp\"} is similar to @{text\"expr\"} in \\S\\ref{sec:ExprCompiler},\nexcept that we have added an @{text IF} constructor,\nfixed the values to be of type @{typ\"nat\"} and declared the two binary\noperations @{text Sum} and @{term\"Diff\"}.  Boolean\nexpressions can be arithmetic comparisons, conjunctions and negations.\nThe semantics is given by two evaluation functions:\n*}\n\nprimrec evala :: \"'a aexp \\<Rightarrow> ('a \\<Rightarrow> nat) \\<Rightarrow> nat\" and\n         evalb :: \"'a bexp \\<Rightarrow> ('a \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n\"evala (IF b a1 a2) env =\n   (if evalb b env then evala a1 env else evala a2 env)\" |\n\"evala (Sum a1 a2) env = evala a1 env + evala a2 env\" |\n\"evala (Diff a1 a2) env = evala a1 env - evala a2 env\" |\n\"evala (Var v) env = env v\" |\n\"evala (Num n) env = n\" |\n\n\"evalb (Less a1 a2) env = (evala a1 env < evala a2 env)\" |\n\"evalb (And b1 b2) env = (evalb b1 env \\<and> evalb b2 env)\" |\n\"evalb (Neg b) env = (\\<not> evalb b env)\"\n\ntext{*\\noindent\n\nBoth take an expression and an environment (a mapping from variables\n@{typ\"'a\"} to values @{typ\"nat\"}) and return its arithmetic/boolean\nvalue. Since the datatypes are mutually recursive, so are functions\nthat operate on them. Hence they need to be defined in a single\n\\isacommand{primrec} section. Notice the \\isakeyword{and} separating\nthe declarations of @{const evala} and @{const evalb}. Their defining\nequations need not be split into two groups;\nthe empty line is purely for readability.\n\nIn the same fashion we also define two functions that perform substitution:\n*}\n\nprimrec substa :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a aexp \\<Rightarrow> 'b aexp\" and\n         substb :: \"('a \\<Rightarrow> 'b aexp) \\<Rightarrow> 'a bexp \\<Rightarrow> 'b bexp\" where\n\"substa s (IF b a1 a2) =\n   IF (substb s b) (substa s a1) (substa s a2)\" |\n\"substa s (Sum a1 a2) = Sum (substa s a1) (substa s a2)\" |\n\"substa s (Diff a1 a2) = Diff (substa s a1) (substa s a2)\" |\n\"substa s (Var v) = s v\" |\n\"substa s (Num n) = Num n\" |\n\n\"substb s (Less a1 a2) = Less (substa s a1) (substa s a2)\" |\n\"substb s (And b1 b2) = And (substb s b1) (substb s b2)\" |\n\"substb s (Neg b) = Neg (substb s b)\"\n\ntext{*\\noindent\nTheir first argument is a function mapping variables to expressions, the\nsubstitution. It is applied to all variables in the second argument. As a\nresult, the type of variables in the expression may change from @{typ\"'a\"}\nto @{typ\"'b\"}. Note that there are only arithmetic and no boolean variables.\n\nNow we can prove a fundamental theorem about the interaction between\nevaluation and substitution: applying a substitution $s$ to an expression $a$\nand evaluating the result in an environment $env$ yields the same result as\nevaluation $a$ in the environment that maps every variable $x$ to the value\nof $s(x)$ under $env$. If you try to prove this separately for arithmetic or\nboolean expressions (by induction), you find that you always need the other\ntheorem in the induction step. Therefore you need to state and prove both\ntheorems simultaneously:\n*}\n\nlemma \"evala (substa s a) env = evala a (\\<lambda>x. evala (s x) env) \\<and>\n        evalb (substb s b) env = evalb b (\\<lambda>x. evala (s x) env)\"\napply(induct_tac a and b)\n\ntxt{*\\noindent The resulting 8 goals (one for each constructor) are proved in one fell swoop:\n*}\n\napply simp_all\n(*<*)done(*>*)\n\ntext{*\nIn general, given $n$ mutually recursive datatypes $\\tau@1$, \\dots, $\\tau@n$,\nan inductive proof expects a goal of the form\n\\[ P@1(x@1)\\ \\land \\dots \\land P@n(x@n) \\]\nwhere each variable $x@i$ is of type $\\tau@i$. Induction is started by\n\\begin{isabelle}\n\\isacommand{apply}@{text\"(induct_tac\"} $x@1$ \\isacommand{and} \\dots\\ \\isacommand{and} $x@n$@{text \")\"}\n\\end{isabelle}\n\n\\begin{exercise}\n  Define a function @{text\"norma\"} of type @{typ\"'a aexp => 'a aexp\"} that\n  replaces @{term\"IF\"}s with complex boolean conditions by nested\n  @{term\"IF\"}s; it should eliminate the constructors\n  @{term\"And\"} and @{term\"Neg\"}, leaving only @{term\"Less\"}.\n  Prove that @{text\"norma\"}\n  preserves the value of an expression and that the result of @{text\"norma\"}\n  is really normal, i.e.\\ no more @{term\"And\"}s and @{term\"Neg\"}s occur in\n  it.  ({\\em Hint:} proceed as in \\S\\ref{sec:boolex} and read the discussion\n  of type annotations following lemma @{text subst_id} below).\n\\end{exercise}\n*}\n(*<*)\nprimrec norma :: \"'a aexp \\<Rightarrow> 'a aexp\" and\n        normb :: \"'a bexp \\<Rightarrow> 'a aexp \\<Rightarrow> 'a aexp \\<Rightarrow> 'a aexp\" where\n\"norma (IF b t e)   = (normb b (norma t) (norma e))\" |\n\"norma (Sum a1 a2)  = Sum (norma a1) (norma a2)\" |\n\"norma (Diff a1 a2) = Diff (norma a1) (norma a2)\" |\n\"norma (Var v)      = Var v\" |\n\"norma (Num n)      = Num n\" |\n            \n\"normb (Less a1 a2) t e = IF (Less (norma a1) (norma a2)) t e\" |\n\"normb (And b1 b2)  t e = normb b1 (normb b2 t e) e\" |\n\"normb (Neg b)      t e = normb b e t\"\n\nlemma \" evala (norma a) env = evala a env \n      \\<and> (\\<forall> t e. evala (normb b t e) env = evala (IF b t e) env)\"\napply (induct_tac a and b)\napply (simp_all)\ndone\n\nprimrec normala :: \"'a aexp \\<Rightarrow> bool\" and\n        normalb :: \"'a bexp \\<Rightarrow> bool\" where\n\"normala (IF b t e)   = (normalb b \\<and> normala t \\<and> normala e)\" |\n\"normala (Sum a1 a2)  = (normala a1 \\<and> normala a2)\" |\n\"normala (Diff a1 a2) = (normala a1 \\<and> normala a2)\" |\n\"normala (Var v)      = True\" |\n\"normala (Num n)      = True\" |\n\n\"normalb (Less a1 a2) = (normala a1 \\<and> normala a2)\" |\n\"normalb (And b1 b2)  = False\" |\n\"normalb (Neg b)      = False\"\n\nlemma \"normala (norma (a::'a aexp)) \\<and>\n       (\\<forall> (t::'a aexp) e. (normala t \\<and> normala e) \\<longrightarrow> normala (normb b t e))\"\napply (induct_tac a and b)\napply (auto)\ndone\n\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/Datatype/ABexpr.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8824278695464501, "lm_q1q2_score": 0.7869589183264071}}
{"text": "theory TreeTravers \n  imports Main \nbegin\n\n  (*\n    We define a new data type `'a tree` which is for binary tree, \n    where both leafs and nodes have a value\n  *)\n  datatype 'a tree = \n    Tip \"'a\" \n    | Node \"'a\" \"'a tree\" \"'a tree\"\n\n\n\n  (*\n    We define a property called preOrder which takes a tree and\n    returns a list with the value at the start. \n  *)\n  primrec preOrder :: \"'a tree \\<Rightarrow> 'a list\"\n    where\n      \"preOrder (Tip a)      = [a]\"\n    | \"preOrder (Node f x y) = f#((preOrder x)@(preOrder y))\"\n  \n  (*\n    We define a property called postOrder which takes a tree and\n    returns a list with the value at the end. \n  *)\n  primrec postOrder :: \"'a tree \\<Rightarrow> 'a list\"\n    where\n      \"postOrder (Tip a)      = [a]\"\n    | \"postOrder (Node f x y) = (postOrder x)@(postOrder y)@[f]\"\n  \n  (*\n    We define a property called inOrder which takes a tree and\n    returns a list with the value at the in location. \n  *)\n  primrec inOrder :: \"'a tree \\<Rightarrow> 'a list\"\n    where\n      \"inOrder (Tip a)      = [a]\"\n    | \"inOrder (Node f x y) = (inOrder x)@[f]@(inOrder y)\"\n\n  (*\n    We define a property called mirror which takes a tree and\n    returns a tree with ever left leaf swapped with the right leaf. \n  *)\n  primrec mirror :: \"'a tree \\<Rightarrow> 'a tree\"\n    where\n      \"mirror (Tip a)      = (Tip a)\"\n    | \"mirror (Node f x y) = (Node f (mirror y) (mirror x))\"\n\n\n\n  (*\n    Now we will prove that by converting a tree in to a list and then reversing it is the same as\n    mirroing a tree and then converting it into a list. \n  *)\n\n  (*\n    We will do it for preOrder, we will apply induction tactic on the tree using auto\n  *)\n  theorem  \"preOrder (mirror t) = rev (postOrder t)\"\n    apply (induct_tac t)\n    apply auto\n  done\n  \n  (*\n    We will do it for postOrder, we will apply induction tactic on the tree using auto\n  *)\n  theorem \"postOrder (mirror t) = rev (preOrder t)\"\n    apply (induct_tac t)\n    apply auto\n  done\n  \n  (*\n    We will do it for inOrder, we will apply induction tactic on the tree using auto\n  *)\n  theorem \"inOrder (mirror t) = rev (inOrder t)\"\n    apply (induct_tac t)\n    apply auto\n  done\n\nend", "meta": {"author": "SNavleen", "repo": "Isabelle-Examples", "sha": "bd7cc76f8503952af85e6dbdc0edd9b2bbb8a457", "save_path": "github-repos/isabelle/SNavleen-Isabelle-Examples", "path": "github-repos/isabelle/SNavleen-Isabelle-Examples/Isabelle-Examples-bd7cc76f8503952af85e6dbdc0edd9b2bbb8a457/TreeTravers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464795, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.786832960951543}}
{"text": "section \"Vertex Cover\"\n\ntheory Approx_VC_Hoare\nimports \"HOL-Hoare.Hoare_Logic\"\nbegin\n\ntext \\<open>The algorithm is classical, the proof is based on and augments the one\nby Berghammer and M\\\"uller-Olm \\cite{BerghammerM03}.\\<close>\n\nsubsection \"Graph\"\n\ntext \\<open>A graph is simply a set of edges, where an edge is a 2-element set.\\<close>\n\ndefinition vertex_cover :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"vertex_cover E C = (\\<forall>e \\<in> E. e \\<inter> C \\<noteq> {})\"\n\nabbreviation matching :: \"'a set set \\<Rightarrow> bool\" where\n\"matching M \\<equiv> pairwise disjnt M\"\n\nlemma card_matching_vertex_cover:\n  \"\\<lbrakk> finite C;  matching M;  M \\<subseteq> E;  vertex_cover E C \\<rbrakk> \\<Longrightarrow> card M \\<le> card C\"\napply(erule card_le_if_inj_on_rel[where r = \"\\<lambda>e v. v \\<in> e\"])\n apply (meson disjnt_def disjnt_iff vertex_cover_def subsetCE)\nby (meson disjnt_iff pairwise_def)\n\n\nsubsection \"The Approximation Algorithm\"\n\ntext \\<open>Formulated using a simple(!) predefined Hoare-logic.\nThis leads to a streamlined proof based on standard invariant reasoning.\n\nThe nondeterministic selection of an element from a set \\<open>F\\<close> is simulated by @{term \"SOME x. x \\<in> F\"}.\nThe \\<open>SOME\\<close> operator is built into HOL: @{term \"SOME x. P x\"} denotes some \\<open>x\\<close> that satisfies \\<open>P\\<close>\nif such an \\<open>x\\<close> exists; otherwise it denotes an arbitrary element. Note that there is no\nactual nondeterminism involved: @{term \"SOME x. P x\"} is some fixed element\nbut in general we don't know which one. Proofs about \\<open>SOME\\<close> are notoriously tedious.\nTypically it involves showing first that @{prop \"\\<exists>x. P x\"}. Then @{thm someI_ex} implies\n@{prop\"P (SOME x. P x)\"}. There are a number of (more) useful related theorems:\njust click on @{thm someI_ex} to be taken there.\\<close>\n\ntext \\<open>Convenient notation for choosing an arbitrary element from a set:\\<close>\nabbreviation \"some A \\<equiv> SOME x. x \\<in> A\"\n\nlocale Edges =\n  fixes E :: \"'a set set\"\n  assumes finE: \"finite E\"\n  assumes edges2: \"e \\<in> E \\<Longrightarrow> card e = 2\"\nbegin\n\ntext \\<open>The invariant:\\<close>\n\ndefinition \"inv_matching C F M =\n  (matching M \\<and> M \\<subseteq> E \\<and> card C \\<le> 2 * card M \\<and> (\\<forall>e \\<in> M. \\<forall>f \\<in> F. e \\<inter> f = {}))\"\n\ndefinition invar :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\" where\n\"invar C F = (F \\<subseteq> E \\<and> vertex_cover (E-F) C \\<and> finite C \\<and> (\\<exists>M. inv_matching C F M))\"\n\ntext \\<open>Preservation of the invariant by the loop body:\\<close>\n\n\n\n\nlemma approx_vertex_cover:\n\"VARS C F\n  {True}\n  C := {};\n  F := E;\n  WHILE F \\<noteq> {}\n  INV {invar C F}\n  DO C := C \\<union> some F;\n     F := F - {e' \\<in> F. some F \\<inter> e' \\<noteq> {}}\n  OD\n  {vertex_cover E C \\<and> (\\<forall>C'. finite C' \\<and> vertex_cover E C' \\<longrightarrow> card C \\<le> 2 * card C')}\"\nproof (vcg, goal_cases)\n  case (1 C F)\n  have \"inv_matching {} E {}\" by (auto simp add: inv_matching_def)\n  with 1 show ?case by (auto simp add: invar_def vertex_cover_def)\nnext\n  case (2 C F)\n  thus ?case using invar_step[of F C] by(auto simp: Let_def)\nnext\n  case (3 C F)\n  then obtain M :: \"'a set set\" where\n    post: \"vertex_cover E C\" \"matching M\" \"M \\<subseteq> E\" \"card C \\<le> 2 * card M\"\n    by(auto simp: invar_def inv_matching_def)\n\n  have opt: \"card C \\<le> 2 * card C'\" if C': \"finite C'\" \"vertex_cover E C'\" for C'\n  proof -\n    note post(4)\n    also have \"2 * card M \\<le> 2 * card C'\"\n    using card_matching_vertex_cover[OF C'(1) post(2,3) C'(2)] by simp\n    finally show \"card C \\<le> 2 * card C'\" .\n  qed\n\n  show ?case using post(1) opt by auto\nqed\n\nend (* locale Graph *)\n\nsubsection \"Version for Hypergraphs\"\n\ntext \\<open>Almost the same. We assume that the degree of every edge is bounded.\\<close>\n\nlocale Bounded_Hypergraph =\n  fixes E :: \"'a set set\"\n  fixes k :: nat\n  assumes finE: \"finite E\"\n  assumes edge_bnd: \"e \\<in> E \\<Longrightarrow> finite e \\<and> card e \\<le> k\"\n  assumes E1: \"{} \\<notin> E\"\nbegin\n\ndefinition \"inv_matching C F M =\n  (matching M \\<and> M \\<subseteq> E \\<and> card C \\<le> k * card M \\<and> (\\<forall>e \\<in> M. \\<forall>f \\<in> F. e \\<inter> f = {}))\"\n\ndefinition invar :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\" where\n\"invar C F = (F \\<subseteq> E \\<and> vertex_cover (E-F) C \\<and> finite C \\<and> (\\<exists>M. inv_matching C F M))\"\n\nlemma invar_step:\n  assumes \"F \\<noteq> {}\" \"invar C F\"\n  shows \"invar (C \\<union> some F) (F - {e' \\<in> F. some F \\<inter> e' \\<noteq> {}})\"\nproof -\n  from assms(2) obtain M where \"F \\<subseteq> E\" and vc: \"vertex_cover (E-F) C\" and fC: \"finite C\"\n    and m: \"matching M\" \"M \\<subseteq> E\" and card: \"card C \\<le> k * card M\"\n    and disj: \"\\<forall>e \\<in> M. \\<forall>f \\<in> F. e \\<inter> f = {}\"\n  by (auto simp: invar_def inv_matching_def)\n  let ?e = \"SOME e. e \\<in> F\"\n  have \"?e \\<in> F\" using \\<open>F \\<noteq> {}\\<close> by (simp add: some_in_eq)\n  hence fe': \"finite ?e\" using \\<open>F \\<subseteq> E\\<close> assms(2) edge_bnd by blast\n  have \"?e \\<notin> M\" using E1 \\<open>?e \\<in> F\\<close> disj \\<open>F \\<subseteq> E\\<close> by fastforce\n  have card': \"card (C \\<union> ?e) \\<le> k * card (insert ?e M)\"\n    using \\<open>?e \\<in> F\\<close> \\<open>?e \\<notin> M\\<close> card_Un_le[of C ?e] \\<open>F \\<subseteq> E\\<close> edge_bnd card finite_subset[OF m(2) finE]\n    by fastforce\n  let ?M = \"M \\<union> {?e}\"\n  have vc': \"vertex_cover (E - (F - {e' \\<in> F. ?e \\<inter> e' \\<noteq> {}})) (C \\<union> ?e)\"\n    using vc by(auto simp: vertex_cover_def)\n  have m': \"inv_matching (C \\<union> ?e) (F - {e' \\<in> F. ?e \\<inter> e' \\<noteq> {}}) ?M\"\n    using m card' \\<open>F \\<subseteq> E\\<close> \\<open>?e \\<in> F\\<close> disj\n    by(auto simp: inv_matching_def Int_commute disjnt_def pairwise_insert)\n  show ?thesis using \\<open>F \\<subseteq> E\\<close> vc' fC fe' m' by(auto simp add: invar_def Let_def)\nqed\n\n\nlemma approx_vertex_cover_bnd:\n\"VARS C F\n  {True}\n  C := {};\n  F := E;\n  WHILE F \\<noteq> {}\n  INV {invar C F}\n  DO C := C \\<union> some F;\n     F := F - {e' \\<in> F. some F \\<inter> e' \\<noteq> {}}\n  OD\n  {vertex_cover E C \\<and> (\\<forall>C'. finite C' \\<and> vertex_cover E C' \\<longrightarrow> card C \\<le> k * card C')}\"\nproof (vcg, goal_cases)\n  case (1 C F)\n  have \"inv_matching {} E {}\" by (auto simp add: inv_matching_def)\n  with 1 show ?case by (auto simp add: invar_def vertex_cover_def)\nnext\n  case (2 C F)\n  thus ?case using invar_step[of F C] by(auto simp: Let_def)\nnext\n  case (3 C F)\n  then obtain M :: \"'a set set\" where\n    post: \"vertex_cover E C\" \"matching M\" \"M \\<subseteq> E\" \"card C \\<le> k * card M\"\n    by(auto simp: invar_def inv_matching_def)\n\n  have opt: \"card C \\<le> k * card C'\" if C': \"finite C'\" \"vertex_cover E C'\" for C'\n  proof -\n    note post(4)\n    also have \"k * card M \\<le> k * card C'\"\n    using card_matching_vertex_cover[OF C'(1) post(2,3) C'(2)] by simp\n    finally show \"card C \\<le> k * card C'\" .\n  qed\n\n  show ?case using post(1) opt by auto\nqed\n\nend (* locale Bounded_Hypergraph *)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Approximation_Algorithms/Approx_VC_Hoare.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8933094117351309, "lm_q1q2_score": 0.7868243139960198}}
{"text": "(*  Title:      HOL/ex/Functions.thy\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection \\<open>Examples of function definitions\\<close>\n\ntheory Functions\nimports MainRLT \"HOL-Library.Monad_Syntax\"\nbegin\n\nsubsection \\<open>Very basic\\<close>\n\nfun fib :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"fib 0 = 1\"\n| \"fib (Suc 0) = 1\"\n| \"fib (Suc (Suc n)) = fib n + fib (Suc n)\"\n\ntext \\<open>Partial simp and induction rules:\\<close>\nthm fib.psimps\nthm fib.pinduct\n\ntext \\<open>There is also a cases rule to distinguish cases along the definition:\\<close>\nthm fib.cases\n\n\ntext \\<open>Total simp and induction rules:\\<close>\nthm fib.simps\nthm fib.induct\n\ntext \\<open>Elimination rules:\\<close>\nthm fib.elims\n\n\nsubsection \\<open>Currying\\<close>\n\nfun add\nwhere\n  \"add 0 y = y\"\n| \"add (Suc x) y = Suc (add x y)\"\n\nthm add.simps\nthm add.induct  \\<comment> \\<open>Note the curried induction predicate\\<close>\n\n\nsubsection \\<open>Nested recursion\\<close>\n\nfunction nz\nwhere\n  \"nz 0 = 0\"\n| \"nz (Suc x) = nz (nz x)\"\nby pat_completeness auto\n\nlemma nz_is_zero:  \\<comment> \\<open>A lemma we need to prove termination\\<close>\n  assumes trm: \"nz_dom x\"\n  shows \"nz x = 0\"\nusing trm\nby induct (auto simp: nz.psimps)\n\ntermination nz\n  by (relation \"less_than\") (auto simp:nz_is_zero)\n\nthm nz.simps\nthm nz.induct\n\n\nsubsubsection \\<open>Here comes McCarthy's 91-function\\<close>\n\nfunction f91 :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"f91 n = (if 100 < n then n - 10 else f91 (f91 (n + 11)))\"\nby pat_completeness auto\n\ntext \\<open>Prove a lemma before attempting a termination proof:\\<close>\nlemma f91_estimate:\n  assumes trm: \"f91_dom n\"\n  shows \"n < f91 n + 11\"\nusing trm by induct (auto simp: f91.psimps)\n\ntermination\nproof\n  let ?R = \"measure (\\<lambda>x. 101 - x)\"\n  show \"wf ?R\" ..\n\n  fix n :: nat\n  assume \"\\<not> 100 < n\"  \\<comment> \\<open>Inner call\\<close>\n  then show \"(n + 11, n) \\<in> ?R\" by simp\n\n  assume inner_trm: \"f91_dom (n + 11)\"  \\<comment> \\<open>Outer call\\<close>\n  with f91_estimate have \"n + 11 < f91 (n + 11) + 11\" .\n  with \\<open>\\<not> 100 < n\\<close> show \"(f91 (n + 11), n) \\<in> ?R\" by simp\nqed\n\ntext \\<open>Now trivial (even though it does not belong here):\\<close>\nlemma \"f91 n = (if 100 < n then n - 10 else 91)\"\n  by (induct n rule: f91.induct) auto\n\n\nsubsubsection \\<open>Here comes Takeuchi's function\\<close>\n\ndefinition tak_m1 where \"tak_m1 = (\\<lambda>(x,y,z). if x \\<le> y then 0 else 1)\"\ndefinition tak_m2 where \"tak_m2 = (\\<lambda>(x,y,z). nat (Max {x, y, z} - Min {x, y, z}))\"\ndefinition tak_m3 where \"tak_m3 = (\\<lambda>(x,y,z). nat (x - Min {x, y, z}))\"\n\nfunction tak :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"tak x y z = (if x \\<le> y then y else tak (tak (x-1) y z) (tak (y-1) z x) (tak (z-1) x y))\"\n  by auto\n\nlemma tak_pcorrect:\n  \"tak_dom (x, y, z) \\<Longrightarrow> tak x y z = (if x \\<le> y then y else if y \\<le> z then z else x)\"\n  by (induction x y z rule: tak.pinduct) (auto simp: tak.psimps)\n\ntermination\n  by (relation \"tak_m1 <*mlex*> tak_m2 <*mlex*> tak_m3 <*mlex*> {}\")\n     (auto simp: mlex_iff wf_mlex tak_pcorrect tak_m1_def tak_m2_def tak_m3_def min_def max_def)\n\ntheorem tak_correct: \"tak x y z = (if x \\<le> y then y else if y \\<le> z then z else x)\"\n  by (induction x y z rule: tak.induct) auto\n\n\nsubsection \\<open>More general patterns\\<close>\n\nsubsubsection \\<open>Overlapping patterns\\<close>\n\ntext \\<open>\n  Currently, patterns must always be compatible with each other, since\n  no automatic splitting takes place. But the following definition of\n  GCD is OK, although patterns overlap:\n\\<close>\n\nfun gcd2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd2 x 0 = x\"\n| \"gcd2 0 y = y\"\n| \"gcd2 (Suc x) (Suc y) = (if x < y then gcd2 (Suc x) (y - x)\n                                    else gcd2 (x - y) (Suc y))\"\n\nthm gcd2.simps\nthm gcd2.induct\n\n\nsubsubsection \\<open>Guards\\<close>\n\ntext \\<open>We can reformulate the above example using guarded patterns:\\<close>\n\nfunction gcd3 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd3 x 0 = x\"\n| \"gcd3 0 y = y\"\n| \"gcd3 (Suc x) (Suc y) = gcd3 (Suc x) (y - x)\" if \"x < y\"\n| \"gcd3 (Suc x) (Suc y) = gcd3 (x - y) (Suc y)\" if \"\\<not> x < y\"\n  apply (case_tac x, case_tac a, auto)\n  apply (case_tac ba, auto)\n  done\ntermination by lexicographic_order\n\nthm gcd3.simps\nthm gcd3.induct\n\n\ntext \\<open>General patterns allow even strange definitions:\\<close>\n\nfunction ev :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"ev (2 * n) = True\"\n| \"ev (2 * n + 1) = False\"\nproof -  \\<comment> \\<open>completeness is more difficult here \\dots\\<close>\n  fix P :: bool\n  fix x :: nat\n  assume c1: \"\\<And>n. x = 2 * n \\<Longrightarrow> P\"\n    and c2: \"\\<And>n. x = 2 * n + 1 \\<Longrightarrow> P\"\n  have divmod: \"x = 2 * (x div 2) + (x mod 2)\" by auto\n  show P\n  proof (cases \"x mod 2 = 0\")\n    case True\n    with divmod have \"x = 2 * (x div 2)\" by simp\n    with c1 show \"P\" .\n  next\n    case False\n    then have \"x mod 2 = 1\" by simp\n    with divmod have \"x = 2 * (x div 2) + 1\" by simp\n    with c2 show \"P\" .\n  qed\nqed presburger+  \\<comment> \\<open>solve compatibility with presburger\\<close>\ntermination by lexicographic_order\n\nthm ev.simps\nthm ev.induct\nthm ev.cases\n\n\nsubsection \\<open>Mutual Recursion\\<close>\n\nfun evn od :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"evn 0 = True\"\n| \"od 0 = False\"\n| \"evn (Suc n) = od n\"\n| \"od (Suc n) = evn n\"\n\nthm evn.simps\nthm od.simps\n\nthm evn_od.induct\nthm evn_od.termination\n\nthm evn.elims\nthm od.elims\n\n\nsubsection \\<open>Definitions in local contexts\\<close>\n\nlocale my_monoid =\n  fixes opr :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n    and un :: \"'a\"\n  assumes assoc: \"opr (opr x y) z = opr x (opr y z)\"\n    and lunit: \"opr un x = x\"\n    and runit: \"opr x un = x\"\nbegin\n\nfun foldR :: \"'a list \\<Rightarrow> 'a\"\nwhere\n  \"foldR [] = un\"\n| \"foldR (x # xs) = opr x (foldR xs)\"\n\nfun foldL :: \"'a list \\<Rightarrow> 'a\"\nwhere\n  \"foldL [] = un\"\n| \"foldL [x] = x\"\n| \"foldL (x # y # ys) = foldL (opr x y # ys)\"\n\nthm foldL.simps\n\nlemma foldR_foldL: \"foldR xs = foldL xs\"\n  by (induct xs rule: foldL.induct) (auto simp:lunit runit assoc)\n\nthm foldR_foldL\n\nend\n\nthm my_monoid.foldL.simps\nthm my_monoid.foldR_foldL\n\n\nsubsection \\<open>\\<open>fun_cases\\<close>\\<close>\n\nsubsubsection \\<open>Predecessor\\<close>\n\nfun pred :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"pred 0 = 0\"\n| \"pred (Suc n) = n\"\n\nthm pred.elims\n\nlemma\n  assumes \"pred x = y\"\n  obtains \"x = 0\" \"y = 0\" | \"n\" where \"x = Suc n\" \"y = n\"\n  by (fact pred.elims[OF assms])\n\n\ntext \\<open>If the predecessor of a number is 0, that number must be 0 or 1.\\<close>\n\nfun_cases pred0E[elim]: \"pred n = 0\"\n\nlemma \"pred n = 0 \\<Longrightarrow> n = 0 \\<or> n = Suc 0\"\n  by (erule pred0E) metis+\n\ntext \\<open>\n  Other expressions on the right-hand side also work, but whether the\n  generated rule is useful depends on how well the simplifier can\n  simplify it. This example works well:\n\\<close>\n\nfun_cases pred42E[elim]: \"pred n = 42\"\n\nlemma \"pred n = 42 \\<Longrightarrow> n = 43\"\n  by (erule pred42E)\n\n\nsubsubsection \\<open>List to option\\<close>\n\nfun list_to_option :: \"'a list \\<Rightarrow> 'a option\"\nwhere\n  \"list_to_option [x] = Some x\"\n| \"list_to_option _ = None\"\n\nfun_cases list_to_option_NoneE: \"list_to_option xs = None\"\n  and list_to_option_SomeE: \"list_to_option xs = Some x\"\n\nlemma \"list_to_option xs = Some y \\<Longrightarrow> xs = [y]\"\n  by (erule list_to_option_SomeE)\n\n\nsubsubsection \\<open>Boolean Functions\\<close>\n\nfun xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\"\nwhere\n  \"xor False False = False\"\n| \"xor True True = False\"\n| \"xor _ _ = True\"\n\nthm xor.elims\n\ntext \\<open>\n  \\<open>fun_cases\\<close> does not only recognise function equations, but also works with\n  functions that return a boolean, e.g.:\n\\<close>\n\nfun_cases xor_TrueE: \"xor a b\" and xor_FalseE: \"\\<not>xor a b\"\nprint_theorems\n\n\nsubsubsection \\<open>Many parameters\\<close>\n\nfun sum4 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"sum4 a b c d = a + b + c + d\"\n\nfun_cases sum40E: \"sum4 a b c d = 0\"\n\nlemma \"sum4 a b c d = 0 \\<Longrightarrow> a = 0\"\n  by (erule sum40E)\n\n\nsubsection \\<open>Partial Function Definitions\\<close>\n\ntext \\<open>Partial functions in the option monad:\\<close>\n\npartial_function (option)\n  collatz :: \"nat \\<Rightarrow> nat list option\"\nwhere\n  \"collatz n =\n    (if n \\<le> 1 then Some [n]\n     else if even n\n       then do { ns \\<leftarrow> collatz (n div 2); Some (n # ns) }\n       else do { ns \\<leftarrow> collatz (3 * n + 1);  Some (n # ns)})\"\n\ndeclare collatz.simps[code]\nvalue \"collatz 23\"\n\n\ntext \\<open>Tail-recursive functions:\\<close>\n\npartial_function (tailrec) fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"fixpoint f x = (if f x = x then x else fixpoint f (f x))\"\n\n\nsubsection \\<open>Regression tests\\<close>\n\ntext \\<open>\n  The following examples mainly serve as tests for the\n  function package.\n\\<close>\n\nfun listlen :: \"'a list \\<Rightarrow> nat\"\nwhere\n  \"listlen [] = 0\"\n| \"listlen (x#xs) = Suc (listlen xs)\"\n\n\nsubsubsection \\<open>Context recursion\\<close>\n\nfun f :: \"nat \\<Rightarrow> nat\"\nwhere\n  zero: \"f 0 = 0\"\n| succ: \"f (Suc n) = (if f n = 0 then 0 else f n)\"\n\n\nsubsubsection \\<open>A combination of context and nested recursion\\<close>\n\nfunction h :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"h 0 = 0\"\n| \"h (Suc n) = (if h n = 0 then h (h n) else h n)\"\nby pat_completeness auto\n\n\nsubsubsection \\<open>Context, but no recursive call\\<close>\n\nfun i :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"i 0 = 0\"\n| \"i (Suc n) = (if n = 0 then 0 else i n)\"\n\n\nsubsubsection \\<open>Tupled nested recursion\\<close>\n\nfun fa :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"fa 0 y = 0\"\n| \"fa (Suc n) y = (if fa n y = 0 then 0 else fa n y)\"\n\n\nsubsubsection \\<open>Let\\<close>\n\nfun j :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"j 0 = 0\"\n| \"j (Suc n) = (let u = n in Suc (j u))\"\n\n\ntext \\<open>There were some problems with fresh names \\dots\\<close>\nfunction  k :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"k x = (let a = x; b = x in k x)\"\n  by pat_completeness auto\n\n\nfunction f2 :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat)\"\nwhere\n  \"f2 p = (let (x,y) = p in f2 (y,x))\"\n  by pat_completeness auto\n\n\nsubsubsection \\<open>Abbreviations\\<close>\n\nfun f3 :: \"'a set \\<Rightarrow> bool\"\nwhere\n  \"f3 x = finite x\"\n\n\nsubsubsection \\<open>Simple Higher-Order Recursion\\<close>\n\ndatatype 'a tree = Leaf 'a | Branch \"'a tree list\"\n\nfun treemap :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\"\nwhere\n  \"treemap fn (Leaf n) = (Leaf (fn n))\"\n| \"treemap fn (Branch l) = (Branch (map (treemap fn) l))\"\n\nfun tinc :: \"nat tree \\<Rightarrow> nat tree\"\nwhere\n  \"tinc (Leaf n) = Leaf (Suc n)\"\n| \"tinc (Branch l) = Branch (map tinc l)\"\n\nfun testcase :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"testcase (Leaf a) = [a]\"\n| \"testcase (Branch x) =\n    (let xs = concat (map testcase x);\n         ys = concat (map testcase x) in\n     xs @ ys)\"\n\n\nsubsubsection \\<open>Pattern matching on records\\<close>\n\nrecord point =\n  Xcoord :: int\n  Ycoord :: int\n\nfunction swp :: \"point \\<Rightarrow> point\"\nwhere\n  \"swp \\<lparr> Xcoord = x, Ycoord = y \\<rparr> = \\<lparr> Xcoord = y, Ycoord = x \\<rparr>\"\nproof -\n  fix P x\n  assume \"\\<And>xa y. x = \\<lparr>Xcoord = xa, Ycoord = y\\<rparr> \\<Longrightarrow> P\"\n  then show P by (cases x)\nqed auto\ntermination by rule auto\n\n\nsubsubsection \\<open>The diagonal function\\<close>\n\nfun diag :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool \\<Rightarrow> nat\"\nwhere\n  \"diag x True False = 1\"\n| \"diag False y True = 2\"\n| \"diag True False z = 3\"\n| \"diag True True True = 4\"\n| \"diag False False False = 5\"\n\n\nsubsubsection \\<open>Many equations (quadratic blowup)\\<close>\n\ndatatype DT =\n  A | B | C | D | E | F | G | H | I | J | K | L | M | N | P\n| Q | R | S | T | U | V\n\nfun big :: \"DT \\<Rightarrow> nat\"\nwhere\n  \"big A = 0\"\n| \"big B = 0\"\n| \"big C = 0\"\n| \"big D = 0\"\n| \"big E = 0\"\n| \"big F = 0\"\n| \"big G = 0\"\n| \"big H = 0\"\n| \"big I = 0\"\n| \"big J = 0\"\n| \"big K = 0\"\n| \"big L = 0\"\n| \"big M = 0\"\n| \"big N = 0\"\n| \"big P = 0\"\n| \"big Q = 0\"\n| \"big R = 0\"\n| \"big S = 0\"\n| \"big T = 0\"\n| \"big U = 0\"\n| \"big V = 0\"\n\n\nsubsubsection \\<open>Automatic pattern splitting\\<close>\n\nfun f4 :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"f4 0 0 = True\"\n| \"f4 _ _ = False\"\n\n\nsubsubsection \\<open>Polymorphic partial-function\\<close>\n\npartial_function (option) f5 :: \"'a list \\<Rightarrow> 'a option\"\nwhere\n  \"f5 x = f5 x\"\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Examples/Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473713594992, "lm_q2_score": 0.9019206785067699, "lm_q1q2_score": 0.7867881330701567}}
{"text": "theory Chapter13_7\nimports \"HOL-IMP.Abs_Int2\" \"Short_Theory\"\nbegin\n\ntext\\<open>\n\\setcounter{exercise}{15}\n\\exercise\nGive a readable proof that if @{text \"\\<gamma> ::\"} \\noquotes{@{typ[source]\"'a::lattice \\<Rightarrow> 'b::lattice\"}}\nis a monotone function, then @{prop \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"}:\n\\<close>\n\nlemma fixes \\<gamma> :: \"'a::lattice \\<Rightarrow> 'b :: lattice\"\nassumes mono: \"\\<And>x y. x \\<le> y \\<Longrightarrow> \\<gamma> x \\<le> \\<gamma> y\"\nshows \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"\n(* your definition/proof here *)\n\ntext\\<open>\nGive an example of two lattices and a monotone @{text \\<gamma>}\nwhere @{prop\"\\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2 \\<le> \\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2)\"} does not hold.\n\\<close>\n\ntext\\<open>\n\\endexercise\n\n\\exercise\nConsider a simple sign analysis based on this abstract domain:\n\\<close>\n\ndatatype sign = None | Neg | Pos0 | Any\n\nfun \\<gamma> :: \"sign \\<Rightarrow> val set\" where\n\"\\<gamma> None = {}\" |\n\"\\<gamma> Neg = {i. i < 0}\" |\n\"\\<gamma> Pos0 = {i. i \\<ge> 0}\" |\n\"\\<gamma> Any = UNIV\"\n\ntext\\<open>\nDefine inverse analyses for \\<open>\\<close>@{text\"+\"}'' and \\<open>\\<close>@{text\"<\"}''\nand prove the required correctness properties:\n\\<close>\n\nfun inv_plus' :: \"sign \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n(* your definition/proof here *)\n\nlemma\n  \"\\<lbrakk> inv_plus' a a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; i1+i2 \\<in> \\<gamma> a \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2' \"\n(* your definition/proof here *)\n\nfun inv_less' :: \"bool \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n(* your definition/proof here *)\n\nlemma\n  \"\\<lbrakk> inv_less' bv a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; (i1<i2) = bv \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2'\"\n(* your definition/proof here *)\n\ntext\\<open>\n\\indent\nFor the ambitious: turn the above fragment into a full-blown abstract interpreter\nby replacing the interval analysis in theory @{short_theory \"Abs_Int2\"}@{text\"_ivl\"}\nby a sign analysis.\n\\endexercise\n\\<close>\n\nend\n\n", "meta": {"author": "david-wang-0", "repo": "concrete-semantics", "sha": "master", "save_path": "github-repos/isabelle/david-wang-0-concrete-semantics", "path": "github-repos/isabelle/david-wang-0-concrete-semantics/concrete-semantics-main/templates/Chapter13_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7866721383923998}}
{"text": "theory hw1\nimports Main\nbegin\n\n(*1.*)\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(*2.*)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" \n  where \"add 0 n = n \" |\n  \"add (Suc m) n = Suc (add m n)\"\n\nlemma null_add[simp]: \"add y 0 = y\"\n  apply (induction y)\n   apply auto\n  done\n\nlemma ass_add[simp]: \"add (add x y) z = add x (add y z)\"\n  apply (induction x)\n   apply auto\n  done\n\nlemma suc_ass[simp]: \"Suc (add y x) = add y (Suc x)\"\n  apply (induction y)\n   apply auto\n  done\n\nlemma cum_add[simp]: \"add x y = add y x\"\n  apply (induction x)\n   apply auto\n  done\n\nfun double  :: \"nat \\<Rightarrow> nat\"\n  where \"double  0 =  0\" |\n\"double (Suc x) = Suc (Suc (double x))\"\n\nlemma double_prop[simp] : \"double x = add x x\"\n  apply (induction x)\n   apply (auto)\n  done\n\n(*3.*)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n  where  \"count a [] = 0\" |\n\"count a (x#xs) = (if a = x then add 1 (count a xs) else count a xs)\"\n\nvalue \"count (2::nat) [2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1]\"\n\nlemma max_count[simp] : \"count a xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(*4.*)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\"\n  where  \"snoc [] a = [a]\" |\n\"snoc (x#xs) a= x#snoc xs a\"\n\nvalue \"snoc [2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1::int] 0\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\"\n  where \"reverse [] = []\" |\n\"reverse (x#xs) = snoc (reverse xs) x\"\n\nvalue \"reverse [2, 0, 2, 2, 1, 0, 1, 1, 2, 0, 2, 2, 1::int]\"\n\nlemma about_reverse2[simp] : \" reverse(snoc xs a) = (a # reverse(xs)) \"\n  apply (induction xs)\n   apply (auto)\n  done\n\n(*lemma snoc_rev[simp] : \" reverse (a # xs) = snoc (reverse xs) a \"\n  apply(induction xs)\n  apply(auto)\n  done*)\n\nlemma rev_reverse[simp] : \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n  apply auto\n  done\n\n(*5.*)\nfun sum_upto :: \"nat \\<Rightarrow> nat\"\n  where \"sum_upto 0 = 0\" |\n\"sum_upto (Suc a) = Suc a + (sum_upto (a))\"\n\nvalue \"sum_upto 10\"\n\nlemma auto_sum[simp] : \"sum_upto a = ((a * (a + 1)) div 2)\"\n  apply(induction a)\n  apply auto\n  done\n\nend", "meta": {"author": "yaryabtsev", "repo": "my-Isabelle", "sha": "4b1b2af9b559eb50c0927f22cec5a11286b4e0f0", "save_path": "github-repos/isabelle/yaryabtsev-my-Isabelle", "path": "github-repos/isabelle/yaryabtsev-my-Isabelle/my-Isabelle-4b1b2af9b559eb50c0927f22cec5a11286b4e0f0/hw1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7866512727589301}}
{"text": "theory Tree2\nimports Main\nbegin\n\ndatatype ('a,'b) tree =\n  Leaf (\"\\<langle>\\<rangle>\") |\n  Node 'b \"('a,'b)tree\" 'a \"('a,'b) tree\" (\"(1\\<langle>_,/ _,/ _,/ _\\<rangle>)\")\n\nfun inorder :: \"('a,'b)tree \\<Rightarrow> 'a list\" where\n\"inorder Leaf = []\" |\n\"inorder (Node _ l a r) = inorder l @ a # inorder r\"\n\nfun height :: \"('a,'b) tree \\<Rightarrow> nat\" where\n\"height Leaf = 0\" |\n\"height (Node _ l a r) = max (height l) (height r) + 1\"\n\ndefinition size1 :: \"('a,'b) tree \\<Rightarrow> nat\" where\n\"size1 t = size t + 1\"\n\nlemma size1_simps[simp]:\n  \"size1 \\<langle>\\<rangle> = 1\"\n  \"size1 \\<langle>u, l, x, r\\<rangle> = size1 l + size1 r\"\nby (simp_all add: size1_def)\n\nlemma size1_ge0[simp]: \"0 < size1 t\"\nby (simp add: size1_def)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Data_Structures/Tree2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248174286374, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7865459255309567}}
{"text": "theory Chapter3_2\nimports Main\nbegin\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval::\"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a1 a2) s = aval a1 s + aval a2 s\" |\n\"aval (Times a1 a2) s = aval a1 s * aval a2 s\"\n\nfun plus:: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i1) (N i2) = N(i1 + i2)\" |\n\"plus (N i) a = (if i = 0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i = 0 then a else Plus a (N i))\" |\n\"plus a1 a2 = Plus a1 a2\"\n\nlemma aval_plus: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction rule: plus.induct)\n  apply (auto)\n  done\n\nfun times:: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"times (N i1) (N i2) = N(i1 * i2)\" |\n\"times (N i) a = (if (i = 0) then (N 0) else if (i = 1) then a else Times (N i) a)\" |\n\"times a (N i) = (if (i = 0) then (N 0) else if (i = 1) then a else Times a (N i))\" |\n\"times a1 a2 = Times a1 a2\"\n\nlemma aval_times: \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\n  apply (induction rule: times.induct)\n  apply (auto)\n  done\n\nfun asimp::\"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)\" |\n\"asimp (Times a1 a2) = times (asimp a1) (asimp a2)\"\n\nlemma aval_asimp: \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n    apply (auto split: aexp.split)\n  apply (simp_all add: aval_plus aval_times)\n  done\n\nfun subst::\"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where \n\"subst x y (V n) = (if x = n then y else (V n))\" |\n\"subst x y (N n) = N n\" |\n\"subst x y (Plus a1 a2) = Plus (subst x y a1) (subst x y a2)\" |\n\"subst x y (Times a1 a2) = Times (subst x y a1) (subst x y a2)\"\n\nlemma substitution_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply (induction e)\n  apply (auto split: if_splits)\n  done\n\nlemma subst_eq: \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply (induction a1 arbitrary: a2)\n  apply (auto simp add: substitution_lemma)\n  done\n\ndatatype aexp2 = N2 int | V2 vname | \n  Plus2 aexp2 aexp2 | Times2 aexp2 aexp2 | \n  PostInc vname | Div aexp2 aexp2\n\nfun aval2::\"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"aval2 (N2 n) s = Some (n, s)\" |\n\"aval2 (V2 x) s = Some (s x, s)\" |\n\"aval2 (PostInc x) s = Some (s x, s(x := (s x) + 1))\" |\n\"aval2 (Plus2 a1 a2) s = \n(case (aval2 a1 s) of\n  Some (v1, s1) \\<Rightarrow> \n    (case (aval2 a2 s1) of\n      Some (v2, s2) \\<Rightarrow> Some (v1 + v2, s2) |\n      None          \\<Rightarrow> None) |\n  None \\<Rightarrow> None)\" | (*TODO: learn about monads*)\n\"aval2 (Times2 a1 a2) s = (case (aval2 a1 s) of\n  Some (v1, s1) \\<Rightarrow> \n    (case (aval2 a2 s1) of\n      Some (v2, s2) \\<Rightarrow> Some (v1 * v2, s2) |\n      None          \\<Rightarrow> None) |\n  None \\<Rightarrow> None)\" |\n\"aval2 (Div a1 a2) s = (case (aval2 a1 s) of\n  Some (v1, s1) \\<Rightarrow> \n    (case (aval2 a2 s1) of\n      Some (v2, s2) \\<Rightarrow> (if (v2 \\<noteq> 0) then Some (v1 div v2, s2) else None) |\n      None          \\<Rightarrow> None) |\n  None \\<Rightarrow> None)\"\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\nfun lval::\"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n\"lval (Nl i) s = i\" |\n\"lval (Vl x) s = s x\" |\n\"lval (Plusl l1 l2) s = (lval l1 s) + (lval l2 s)\" |\n\"lval (LET x l1 l2) s = lval l2 (s(x := (lval l1 s)))\"\n\nfun inline::\"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl i) = N i\" |\n\"inline (Vl x) = V x\" |\n\"inline (Plusl l1 l2) = Plus (inline l1) (inline l2)\" |\n\"inline (LET x l1 l2) = subst x (inline l1) (inline l2)\"\n\n\nlemma inline_aval: \"aval (inline l) = lval l\"\n  apply (induction l)\n  apply (auto simp add: substitution_lemma)\n  done\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval::\"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b1 b2) s = (bval b1 s \\<and> bval b2 s)\" |\n\"bval (Less a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun not::\"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\n\nfun \"and\"::\"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b1 b2 = And b1 b2\"\n\nfun less::\"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n1) (N n2) = Bc (n1 < n2)\" |\n\"less a1 a2 = Less a1 a2\"\n\nfun bsimp::\"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not (bsimp b)\" |\n\"bsimp (And b1 b2) = and (bsimp b1) (bsimp b2)\" |\n\"bsimp (Less a1 a2) = less (asimp a1) (asimp a2)\"\n\nfun Eq::\"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a1 a2 = And (Not (less a1 a2)) (Not (less a2 a1))\"\n\nfun Le::\"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a1 a2 = Not (less a2 a1)\"\n\nlemma less_corr: \"bval (less a1 a2) s = (aval a1 s < aval a2 s)\"\n  apply (induction rule: less.induct)\n     apply (auto)\n  done\n\nlemma Eq_corr: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply (auto simp add: less_corr)\n  done\n\nlemma Le_corr: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply (auto simp add: less_corr)\n  done\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\nfun ifval::\"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 b) s = b\" |\n\"ifval (If cond e1 e2) s = ((ifval cond s) \\<and> (ifval e1 s) \\<or> \\<not>(ifval cond s) \\<and> (ifval e2 s))\" |\n\"ifval (Less2 a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun b2ifexp::\"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc b) = Bc2 b\" |\n\"b2ifexp (Not b) = If (b2ifexp b) (Bc2 False) (Bc2 True)\" |\n\"b2ifexp (And b1 b2) = If (b2ifexp b1) (b2ifexp b2) (Bc2 False)\" |\n\"b2ifexp (Less a1 a2) = Less2 a1 a2\"\n\nlemma \"bval b = ifval (b2ifexp b)\"\n  apply (induction b)\n     apply (auto)\n  done\n\nfun if2bexp::\"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = Bc b\" |\n\"if2bexp (If cond e1 e2) = \nNot (And \n  (Not (And (if2bexp cond) (if2bexp e1))) \n  (Not (And (Not (if2bexp cond)) (if2bexp e2)))\n)\" |\n\"if2bexp (Less2 e1 e2) = Less e1 e2\"\n\nlemma \"ifval i = bval (if2bexp i)\"\n  apply (induction i)\n  apply (auto)\n  done\n\ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\nfun pbval::\"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\" |\n\"pbval (NOT b) s = (\\<not>pbval b s)\" |\n\"pbval (AND b1 b2) s = (pbval b1 s \\<and> pbval b2 s)\" |\n\"pbval (OR b1 b2) s = (pbval b1 s \\<or> pbval b2 s)\"\n\nfun is_nnf::\"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (NOT (VAR x)) = True\" |\n\"is_nnf (AND b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" |\n\"is_nnf (OR b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" |\n\"is_nnf (NOT b) = False\"\n\nfun nnf::\"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (NOT (VAR x)) = NOT (VAR x)\" |\n\"nnf (NOT (NOT b)) = nnf b\" |\n\"nnf (NOT (AND b1 b2)) = OR (nnf (NOT b1)) (nnf (NOT b2))\" |\n\"nnf (NOT (OR b1 b2)) = AND (nnf (NOT b1)) (nnf (NOT b2))\" |\n\"nnf (VAR x) = VAR x\" |\n\"nnf (AND b1 b2) = AND (nnf b1) (nnf b2)\" |\n\"nnf (OR b1 b2) = OR (nnf b1) (nnf b2)\"\n\nlemma nnf_pbval [simp]: \"pbval (nnf b) = pbval b\"\n  apply (induction rule: nnf.induct)\n  apply (auto)\n  done\n\nlemma nnf_correct [simp]: \"is_nnf (nnf b)\"\n  apply (induction b rule: nnf.induct)\n  apply (auto)\n  done\n\nfun no_or::\"pbexp \\<Rightarrow> bool\" where\n\"no_or (VAR x) = True\" |\n\"no_or (NOT b) = no_or b\" |\n\"no_or (AND b1 b2) = (no_or b1 \\<and> no_or b2)\" |\n\"no_or (OR b1 b2) = False\"\n\nfun dnf_aux::\"pbexp \\<Rightarrow> bool\" where\n\"dnf_aux (VAR x) = True\" |\n\"dnf_aux (NOT b) = dnf_aux b\" |\n\"dnf_aux (AND b1 b2) = (no_or b1 \\<and> no_or b2)\" |\n\"dnf_aux (OR b1 b2) = (dnf_aux b1 \\<and> dnf_aux b2)\"\n\nfun is_dnf::\"pbexp \\<Rightarrow> bool\" where\n\"is_dnf b = (is_nnf b \\<and> dnf_aux b)\"\n\nfun dist_and::\"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"dist_and (OR b1 b2) b3 = OR (dist_and b1 b3) (dist_and b2 b3)\" |\n\"dist_and  b1 (OR b2 b3) = OR (dist_and  b1 b2) (dist_and b1 b3)\" |\n\"dist_and b1 b2 = AND b1 b2\"\n\nfun dnf_of_nnf::\"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR n) = VAR n\" |\n\"dnf_of_nnf (NOT b) = NOT (dnf_of_nnf b)\" |\n\"dnf_of_nnf (OR b1 b2) = OR (dnf_of_nnf b1) (dnf_of_nnf b2)\" |\n\"dnf_of_nnf (AND b1 b2) = dist_and (dnf_of_nnf b1) (dnf_of_nnf b2)\"\n\nlemma dist_and_corr: \"pbval (dist_and b1 b2) s = pbval (AND b1 b2) s\"\n  apply (induction b1 b2 rule: dist_and.induct)\n    apply (auto)\n  done\n\nlemma dnf_of_nnf_pbval: \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply (induction b)\n    apply (auto simp add: dist_and_corr)\n  done\n\nlemma dist_and_pres_nnf: \"is_nnf (AND b1 b2) \\<Longrightarrow> is_nnf (dist_and b1 b2)\"\n  apply (induction b1 b2 rule: dist_and.induct)\n   apply (auto)\n  done\n\n\n\n\nlemma [simp]: \"is_nnf (NOT b) \\<Longrightarrow> dnf_aux (dnf_of_nnf b)\"\n  apply (induction b rule: is_nnf.induct)\n  apply (auto)\n  done\n\nlemma dist_and_pres_dnf: \"dnf_aux b1 \\<Longrightarrow> dnf_aux b2 \\<Longrightarrow> \n    is_nnf b1 \\<Longrightarrow> is_nnf b2 \\<Longrightarrow> dnf_aux (dist_and b1 b2)\"\n  apply (induction b1 b2 rule: dist_and.induct)\n    apply (auto)\n  done\n\n\nlemma dnf_of_nnf_pres_nnf [simp]: \"is_nnf b \\<Longrightarrow> is_nnf (dnf_of_nnf b)\"\n  apply (induction b rule: is_nnf.induct)\n   apply (auto simp add: dist_and_pres_nnf)\n  done\n\nlemma dnf_of_nnf_est_dnf_aux [simp]: \"is_nnf b \\<Longrightarrow> dnf_aux (dnf_of_nnf b)\"\n  apply (induction b)\n  apply (auto simp add: dist_and_pres_nnf dist_and_pres_dnf)\n  done \n\nlemma dnf_converts_correctly: \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply (auto) (*TODO: why does simp add: not work here? the above lemmas needed the [simp] tag*)\n  done\n\ndatatype instr = LOADI val | LOAD vname | ADD | TIMES\n\ntype_synonym stack = \"val list\"\n\nabbreviation hd2::\"'a list \\<Rightarrow> 'a\" where\n\"hd2 l \\<equiv> hd (tl l)\"\n\nabbreviation tl2::\"'a list \\<Rightarrow> 'a list\" where\n\"tl2 l \\<equiv> tl (tl l)\"\n\nfun exec1::\"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> (stack option)\" where\n\"exec1 (LOADI n) _ stk = Some (n # stk)\" |\n\"exec1 (LOAD x) s stk = Some ((s x) # stk)\" |\n\"exec1 ADD _ stk = (if (length stk) \\<ge> 2 then Some ((hd stk + hd2 stk) # (tl2 stk)) else None)\" |\n\"exec1 TIMES _ stk = (if (length stk) \\<ge> 2 then Some ((hd stk * hd2 stk) # (tl2 stk)) else None)\"\n\nfun exec::\"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> (stack option)\" where\n\"exec Nil _ stk = (Some stk)\" |\n\"exec (i#is) s stk = (case (exec1 i s stk) of \n  None \\<Rightarrow> None |\n  (Some stk1) \\<Rightarrow> (exec is s stk1)\n)\"\n\nfun comp::\"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e1 e2) = (comp e1) @ (comp e2) @ [ADD]\" |\n\"comp (Times e1 e2) = (comp e1) @ (comp e2) @ [TIMES]\"\n\nlemma [simp]: \"exec is1 s stk = (Some stk1) \\<Longrightarrow> exec (is1 @ is2) s stk = exec is2 s stk1\"\n  apply (induction is1 arbitrary: s stk stk1 is2)\n  apply (auto split: option.splits)\n  done\n\nlemma \"stk1 = aval a s # stk \\<Longrightarrow> (exec (comp a) s stk) = Some stk1 \"\n  apply (induction a arbitrary: s stk stk1)\n     apply (auto split: option.splits)\n  done\n\n\ntype_synonym reg = \"nat\"\n\ndatatype instr1 = LDI int reg | LD vname reg | ADD reg reg | MULT reg reg\n\nfun exec_reg1::\"instr1 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec_reg1 (LDI i r) s rs = rs(r := i)\"  |\n\"exec_reg1 (LD x r) s rs = rs(r := (s x))\" |\n\"exec_reg1 (ADD r1 r2) s rs = rs(r1 := (rs r1 + rs r2))\" |\n\"exec_reg1 (MULT r1 r2) s rs = rs(r1 := (rs r1 * rs r2))\" \n\nfun exec_reg::\"instr1 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec_reg [] s rs = rs\" |\n\"exec_reg (i#is) s rs = exec_reg is s (exec_reg1 i s rs)\"\n\nfun comp_reg::\"aexp \\<Rightarrow> reg \\<Rightarrow> instr1 list\" where\n\"comp_reg (N n) r = [LDI n r]\" |\n\"comp_reg (V x) r = [LD x r]\" |\n\"comp_reg (Plus a1 a2) r = (comp_reg a1 r) @ (comp_reg a2 (Suc r)) @ [ADD r (Suc r)]\" |\n\"comp_reg (Times a1 a2) r = (comp_reg a1 r) @ (comp_reg a2 (Suc r)) @ [MULT r (Suc r)]\"\n\nlemma [simp]: \"exec_reg (a1s@a2s) s rs = exec_reg a2s s (exec_reg a1s s rs)\"\n  apply (induction a1s arbitrary: s rs)\n  apply (auto)\n  done\n\nlemma [simp]: \"exec_reg (comp_reg a1 r1 @ comp_reg a2 r2) s rs = exec_reg (comp_reg a2 r2) s (exec_reg (comp_reg a1 r1) s rs)\"\n  apply (induction a1 arbitrary: s rs)\n  apply (auto)\n  done\n\nlemma [simp]: \"r2 < r1 \\<Longrightarrow> exec_reg (comp_reg a r1) s rs r2 = rs r2\"\n  apply (induction a arbitrary: r1 r2 rs s)\n  apply (auto)\n  done\n\nlemma [simp]: \"exec_reg (comp_reg a r) s rs r = aval a s\"\n  apply (induction a arbitrary: rs r)\n     apply (auto)\n  done\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg | MULT0 reg\n\ntype_synonym reg_state = \"reg \\<Rightarrow> int\"\n\nfun exec0'::\"instr0 \\<Rightarrow> state \\<Rightarrow> reg_state \\<Rightarrow> reg_state\" where\n\"exec0' (LDI0 v) s rs = rs(0 := v)\" |\n\"exec0' (LD0 n) s rs = rs(0 := (s n))\" |\n\"exec0' (MV0 r) s rs = rs(r := (rs 0))\" |\n\"exec0' (ADD0 r) s rs = rs(0 := (rs 0) + (rs r))\" | \n\"exec0' (MULT0 r) s rs = rs(0 := (rs 0) * (rs r))\"\n\nfun exec0::\"instr0 list \\<Rightarrow> state \\<Rightarrow> reg_state \\<Rightarrow> reg_state\" where\n\"exec0 Nil _ rs = rs\" |\n\"exec0 (i#is) s rs = exec0 is s (exec0' i s rs)\"\n\nfun comp0::\"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0 (N n) _ = [LDI0 n]\" |\n\"comp0 (V x) _ = [LD0 x]\" |\n\"comp0 (Plus a1 a2) r = (comp0 a1 r) @ [MV0 r] @ (comp0 a2 (Suc r)) @ [ADD0 r]\" |\n\"comp0 (Times a1 a2) r = (comp0 a1 r) @ [MV0 r] @ (comp0 a2 (Suc r)) @ [MULT0 r]\"\n\nlemma [simp]: \"exec0 (a1s@a2s) s rs = exec0 a2s s (exec0 a1s s rs)\"\n  apply (induction a1s arbitrary: a2s rs)\n  apply (auto)\n  done\n\nlemma [simp]: \"0 < r1 \\<Longrightarrow> r1 < r2 \\<Longrightarrow> exec0 (comp0 a r2) s rs r1 = rs r1\"\n  apply (induction a arbitrary: rs s r1 r2)\n  apply (auto)\n  done\n\nlemma \"0 < r \\<Longrightarrow> exec0 (comp0 a r) s rs 0 = aval a s\"\n  apply (induction a arbitrary: r s rs)\n  apply (auto)\n  done\n\nend", "meta": {"author": "david-wang-0", "repo": "concrete-semantics", "sha": "master", "save_path": "github-repos/isabelle/david-wang-0-concrete-semantics", "path": "github-repos/isabelle/david-wang-0-concrete-semantics/concrete-semantics-main/Chapter3_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299550303292, "lm_q2_score": 0.8499711832583696, "lm_q1q2_score": 0.786418799663217}}
{"text": "theory Lattice\n  imports Base\nbegin\n\nsection {* Lattices and Orders *}\n\nsubsection {* Partial orders *}\n\nrecord 'a ord = \"'a partial_object\" +\n  le :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubseteq>\\<index>\" 50)\n\nlocale order = fixes A (structure)\n  assumes order_refl [intro, simp]: \"x \\<in> carrier A \\<Longrightarrow> x \\<sqsubseteq> x\"\n  and order_trans: \"\\<lbrakk>x \\<sqsubseteq> y; y \\<sqsubseteq> z; x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> z\"\n  and order_antisym: \"\\<lbrakk>x \\<sqsubseteq> y; y \\<sqsubseteq> x; x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x = y\"\n\nsubsubsection {* Order duality *}\n\ndefinition ord_inv :: \"('a, 'b) ord_scheme \\<Rightarrow> ('a, 'b) ord_scheme\" (\"_\\<sharp>\" [1000] 100) where\n  \"ord_inv ordr \\<equiv> \\<lparr>carrier = carrier ordr, le = \\<lambda>x y. le ordr y x, \\<dots> = ord.more ordr\\<rparr>\"\n\nlemma inv_carrier_id [simp]: \"carrier (ord_inv A) = carrier A\"\n  by (metis ord_inv_def partial_object.simps(1))\n\nlemma ord_to_inv: \"order A \\<Longrightarrow> order (ord_inv A)\"\n  by (default, simp_all add: ord_inv_def, (metis order.order_refl order.order_trans order.order_antisym)+)\n\nlemma inv_inv_id: \"ord_inv (A\\<sharp>) = A\"\n  by (simp add: ord_inv_def)\n\nlemma inv_to_ord: \"order (A\\<sharp>) \\<Longrightarrow> order A\"\n  by (metis inv_inv_id ord_to_inv)\n\nlemma ord_is_inv [simp]: \"order (A\\<sharp>) = order A\"\n  by (metis inv_to_ord ord_to_inv)\n\nlemma inv_flip [simp]: \"(x \\<sqsubseteq>\\<^bsub>A\\<sharp>\\<^esub> y) = (y \\<sqsubseteq>\\<^bsub>A\\<^esub> x)\"\n  by (simp add: ord_inv_def)\n\nlemma dual_carrier_subset: \"X \\<subseteq> carrier A \\<longleftrightarrow> X \\<subseteq> carrier (A\\<sharp>)\"\n  by (metis inv_carrier_id)\n\nsubsubsection {* Isotone functions *}\n\ndefinition isotone :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"isotone A B f \\<equiv> order A \\<and> order B \\<and> (\\<forall>x\\<in>carrier A. \\<forall>y\\<in>carrier A. x \\<sqsubseteq>\\<^bsub>A\\<^esub> y \\<longrightarrow> f x \\<sqsubseteq>\\<^bsub>B\\<^esub> f y)\"\n\nlemma use_iso1: \"\\<lbrakk>isotone A A f; x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubseteq>\\<^bsub>A\\<^esub> y\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq>\\<^bsub>A\\<^esub> f y\"\n  by (simp add: isotone_def)\n\nlemma use_iso2: \"\\<lbrakk>isotone A B f; x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubseteq>\\<^bsub>A\\<^esub> y\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq>\\<^bsub>B\\<^esub> f y\"\n  by (simp add: isotone_def)\n\nlemma iso_compose: \"\\<lbrakk>f \\<in> carrier A \\<rightarrow> carrier B; isotone A B f; g \\<in> carrier B \\<rightarrow> carrier C; isotone B C g\\<rbrakk> \\<Longrightarrow> isotone A C (g \\<circ> f)\"\n  by (simp add: isotone_def, safe, metis (full_types) typed_application)\n\nlemma inv_isotone [simp]: \"isotone (A\\<sharp>) (B\\<sharp>) f = isotone A B f\"\n  by (simp add: isotone_def, auto)\n\ndefinition idempotent :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"idempotent A f \\<equiv> \\<forall>x\\<in>A. (f \\<circ> f) x = f x\"\n\ncontext order\nbegin\n\n  lemma eq_refl: \"\\<lbrakk>x \\<in> carrier A; x = x\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> x\" by (metis order_refl)\n\n  subsection {* Least upper bounds *}\n\n  definition is_ub :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n    \"is_ub x X \\<equiv> (X \\<subseteq> carrier A) \\<and> (x \\<in> carrier A) \\<and> (\\<forall>y\\<in>X. y \\<sqsubseteq> x)\"\n\n  definition is_lub :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n    \"is_lub x X \\<equiv>  is_ub x X \\<and> (\\<forall>y\\<in>carrier A.(\\<forall>z\\<in>X. z \\<sqsubseteq> y) \\<longrightarrow> x \\<sqsubseteq> y)\"\n\n  lemma is_lub_simp: \"is_lub x X = ((X \\<subseteq> carrier A) \\<and> (x \\<in> carrier A) \\<and> (\\<forall>y\\<in>X. y \\<sqsubseteq> x) \\<and> (\\<forall>y\\<in>carrier A.(\\<forall>z\\<in>X. z \\<sqsubseteq> y) \\<longrightarrow> x \\<sqsubseteq> y))\"\n    by (simp add: is_lub_def is_ub_def)\n\n  lemma is_lub_unique: \"is_lub x X \\<longrightarrow> is_lub y X \\<longrightarrow> x = y\"\n    by (smt order_antisym is_lub_def is_ub_def)\n\n  definition lub :: \"'a set \\<Rightarrow> 'a\" (\"\\<Sigma>\") where\n    \"\\<Sigma> X = (THE x. is_lub x X)\"\n\n  lemma lub_simp: \"\\<Sigma> X = (THE x. (X \\<subseteq> carrier A) \\<and> (x \\<in> carrier A) \\<and> (\\<forall>y\\<in>X. y \\<sqsubseteq> x) \\<and> (\\<forall>y\\<in>carrier A.(\\<forall>z\\<in>X. z \\<sqsubseteq> y) \\<longrightarrow> x \\<sqsubseteq> y))\"\n    by (simp add: lub_def is_lub_simp)\n\n  lemma the_lub_leq: \"\\<lbrakk>\\<exists>z. is_lub z X; \\<And>z. is_lub z X \\<longrightarrow> z \\<sqsubseteq> x\\<rbrakk> \\<Longrightarrow> \\<Sigma> X \\<sqsubseteq> x\"\n    by (metis is_lub_unique lub_def the_equality)\n\n  lemma the_lub_geq: \"\\<lbrakk>\\<exists>z. is_lub z X; \\<And>z. is_lub z X \\<Longrightarrow> x \\<sqsubseteq> z\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> \\<Sigma> X\"\n    by (metis is_lub_unique lub_def the_equality)\n\n  lemma lub_is_lub [elim?]: \"is_lub w X \\<Longrightarrow> \\<Sigma> X = w\"\n    by (metis is_lub_unique lub_def the_equality)\n\n  lemma singleton_lub: \"y \\<in> carrier A \\<Longrightarrow> \\<Sigma> {y} = y\"\n    by (unfold lub_def, rule the_equality, simp_all add: is_lub_def is_ub_def, metis order_antisym order_refl)\n\n  lemma surjective_lub: \"\\<forall>y\\<in>carrier A. \\<exists>X\\<subseteq>carrier A. y = \\<Sigma> X\"\n    by (metis bot_least insert_subset singleton_lub)\n\n  lemma lub_subset: \"\\<lbrakk>X \\<subseteq> Y; is_lub x X; is_lub y Y\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> y\"\n    by (metis (no_types) is_lub_def is_ub_def set_rev_mp)\n\n  lemma lub_closed: \"\\<lbrakk>X \\<subseteq> carrier A; \\<exists>x. is_lub x X\\<rbrakk> \\<Longrightarrow> \\<Sigma> X \\<in> carrier A\"\n    by (rule_tac ?P = \"\\<lambda>x. is_lub x X\" in the1I2, metis is_lub_unique, metis is_lub_def is_ub_def lub_is_lub)\n\n  definition join :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<squnion>\" 70) where\n    \"x \\<squnion> y = \\<Sigma> {x,y}\"\n\n  subsection {* Greatest lower bounds *}\n\n  definition is_lb :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n    \"is_lb x X \\<equiv> (X \\<subseteq> carrier A) \\<and> (x \\<in> carrier A) \\<and> (\\<forall>y\\<in>X. x \\<sqsubseteq> y)\"\n\n  definition is_glb :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n    \"is_glb x X \\<longleftrightarrow> is_lb x X \\<and> (\\<forall>y\\<in>carrier A.(\\<forall>z\\<in>X. y \\<sqsubseteq> z) \\<longrightarrow> y \\<sqsubseteq> x)\"\n\n  lemma is_glb_simp: \"is_glb x X = ((X \\<subseteq> carrier A) \\<and> (x \\<in> carrier A) \\<and> (\\<forall>y\\<in>X. x \\<sqsubseteq> y) \\<and> (\\<forall>y\\<in>carrier A.(\\<forall>z\\<in>X. y \\<sqsubseteq> z) \\<longrightarrow> y \\<sqsubseteq> x))\"\n     by (simp add: is_glb_def is_lb_def)\n\n  lemma is_glb_unique: \"is_glb x X \\<longrightarrow> is_glb y X \\<longrightarrow> x = y\"\n    by (smt order_antisym is_glb_def is_lb_def)\n\n  definition glb :: \"'a set \\<Rightarrow> 'a\" (\"\\<Pi>\") where\n    \"\\<Pi> X = (THE x. is_glb x X)\"\n\n  lemma glb_simp: \"\\<Pi> X = (THE x. (X \\<subseteq> carrier A) \\<and> (x \\<in> carrier A) \\<and> (\\<forall>y\\<in>X. x \\<sqsubseteq> y) \\<and> (\\<forall>y\\<in>carrier A.(\\<forall>z\\<in>X. y \\<sqsubseteq> z) \\<longrightarrow> y \\<sqsubseteq> x))\"\n    by (simp add: glb_def is_glb_simp)\n\n  lemma the_glb_geq: \"\\<lbrakk>\\<exists>z. is_glb z X; \\<And>z. is_glb z X \\<longrightarrow> x \\<sqsubseteq> z\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> \\<Pi> X\"\n    by (metis glb_def is_glb_unique the_equality)\n\n  lemma the_glb_leq: \"\\<lbrakk>\\<exists>z. is_glb z X; \\<And>z. is_glb z X \\<longrightarrow> z \\<sqsubseteq> x\\<rbrakk> \\<Longrightarrow> \\<Pi> X \\<sqsubseteq> x\"\n    by (metis glb_def is_glb_unique the_equality)\n\n  lemma glb_is_glb [elim?]: \"is_glb w X \\<Longrightarrow> \\<Pi> X = w\"\n    by (metis is_glb_unique glb_def the_equality)\n\n  lemma singleton_glb: \"y \\<in> carrier A \\<Longrightarrow> \\<Pi> {y} = y\"\n    by (unfold glb_def, rule the_equality, simp_all add: is_glb_def is_lb_def, metis order_antisym order_refl)\n\n  lemma surjective_glb: \"\\<forall>y\\<in>carrier A. \\<exists>X\\<subseteq>carrier A. y = \\<Pi> X\"\n    by (metis bot_least insert_subset singleton_glb)\n\n  lemma glb_subset: \"\\<lbrakk>X \\<subseteq> Y; is_glb x X; is_glb y Y\\<rbrakk> \\<Longrightarrow> y \\<sqsubseteq> x\"\n    by (metis (no_types) in_mono is_glb_def is_lb_def)\n\n  lemma glb_closed: \"\\<lbrakk>X \\<subseteq> carrier A; \\<exists>x. is_glb x X\\<rbrakk> \\<Longrightarrow> \\<Pi> X \\<in> carrier A\"\n    by (rule_tac ?P = \"\\<lambda>x. is_glb x X\" in the1I2, metis is_glb_unique, metis is_glb_def is_lb_def glb_is_glb)\n\n  definition meet :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<sqinter>\" 70) where\n    \"x \\<sqinter> y = \\<Pi> {x,y}\"\n\n  definition less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 50) where\n    \"x \\<sqsubset> y \\<equiv> (x \\<sqsubseteq> y \\<and> x \\<noteq> y)\"\n\n  lemma less_irrefl [iff]: \"x \\<in> carrier A \\<Longrightarrow> \\<not> x \\<sqsubset> x\"\n    by (simp add: less_def)\n\n  lemma less_imp_le: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubset> y\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> y\"\n    by (simp add: less_def)\n\n  lemma less_asym: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubset> y; (\\<not> P \\<Longrightarrow> y \\<sqsubset> x)\\<rbrakk> \\<Longrightarrow> P\"\n    by (metis order_antisym less_def)\n\n  lemma less_trans: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A; x \\<sqsubset> y; y \\<sqsubset> z\\<rbrakk> \\<Longrightarrow> x \\<sqsubset> z\"\n    by (metis less_asym less_def order_trans)\n\n  lemma less_le_trans: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A; x \\<sqsubset> y; y \\<sqsubseteq> z\\<rbrakk> \\<Longrightarrow> x \\<sqsubset> z\"\n    by (metis less_def less_trans)\n\n  lemma less_asym': \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubset> y; y \\<sqsubset> x\\<rbrakk> \\<Longrightarrow> P\"\n    by (metis less_asym)\n\n  lemma le_imp_less_or_eq: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> x \\<sqsubset> y \\<or> x = y\"\n    by (metis less_def)\n\n  lemma less_imp_not_less: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubset> y\\<rbrakk> \\<Longrightarrow> (\\<not> y \\<sqsubset> x) \\<longleftrightarrow> True\"\n    by (metis less_asym)\n\n  lemma less_imp_triv: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubset> y\\<rbrakk> \\<Longrightarrow> (y \\<sqsubset> x \\<longrightarrow> P) \\<longleftrightarrow> True\"\n    by (metis less_asym)\n\n  definition coclosure :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n    \"coclosure m \\<equiv> (m \\<in> carrier A \\<rightarrow> carrier A) \\<and> (\\<forall>x\\<in>carrier A. \\<forall>y\\<in>carrier A. x \\<sqsubseteq> y \\<longrightarrow> m x \\<sqsubseteq> m y)\n                 \\<and> (\\<forall>x\\<in>carrier A. m x \\<sqsubseteq> x)\n                 \\<and> (\\<forall>x\\<in>carrier A. m x \\<sqsubseteq> m (m x))\"\n\n\n  definition is_max :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n    \"is_max x X \\<equiv> x \\<in> X \\<and> (\\<forall>y\\<in>X. y \\<sqsubseteq> x)\"\n\n  definition is_min :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n    \"is_min x X \\<equiv> x \\<in> X \\<and> (\\<forall>y\\<in>X. x \\<sqsubseteq> y)\"\n\n  lemma is_max_equiv: \"X \\<subseteq> carrier A \\<Longrightarrow> is_max x X = (x \\<in> X \\<and> is_lub x X)\"\n    by (simp add: is_lub_simp, safe, (metis is_max_def set_mp)+)\n\n  lemma is_min_equiv: \"X \\<subseteq> carrier A \\<Longrightarrow> is_min x X = (x \\<in> X \\<and> is_glb x X)\"\n    by (simp add: is_glb_simp, safe, (metis is_min_def set_mp)+)\n\n  definition way_below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> prop\" (infixl \"\\<guillemotleft>\" 50) where\n     \"x \\<guillemotleft> y \\<equiv> (\\<And>D. \\<lbrakk>D \\<subseteq> carrier A; \\<forall>a\\<in>D. \\<forall>b\\<in>D. \\<exists>c\\<in>D. a \\<sqsubseteq> c \\<and> b \\<sqsubseteq> c; \\<exists>z. is_lub z D; y \\<sqsubseteq> \\<Sigma> D\\<rbrakk> \\<Longrightarrow> \\<exists>z\\<in>D. x \\<sqsubseteq> z)\"\n\n  lemma way_below_leq:\n    assumes xc: \"x \\<in> carrier A\" and yc: \"y \\<in> carrier A\" and x_below_y: \"x \\<guillemotleft> y\"\n    shows \"x \\<sqsubseteq> y\"\n  proof -\n    have \"\\<And>D. \\<lbrakk>D \\<subseteq> carrier A; \\<forall>a\\<in>D. \\<forall>b\\<in>D. \\<exists>c\\<in>D. a \\<sqsubseteq> c \\<and> b \\<sqsubseteq> c; \\<exists>z. is_lub z D; y \\<sqsubseteq> \\<Sigma> D\\<rbrakk> \\<Longrightarrow> \\<exists>z\\<in>D. x \\<sqsubseteq> z\"\n      by (insert x_below_y, simp add: way_below_def)\n    hence \"\\<lbrakk>{y} \\<subseteq> carrier A; \\<forall>a\\<in>{y}. \\<forall>b\\<in>{y}. \\<exists>c\\<in>{y}. a \\<sqsubseteq> c \\<and> b \\<sqsubseteq> c; \\<exists>z. is_lub z {y}; y \\<sqsubseteq> \\<Sigma> {y}\\<rbrakk> \\<Longrightarrow> \\<exists>z\\<in>{y}. x \\<sqsubseteq> z\"\n      by auto\n    moreover have \"{y} \\<subseteq> carrier A\"\n      by (metis empty_subsetI insert_subset yc)\n    moreover have \"\\<forall>a\\<in>{y}. \\<forall>b\\<in>{y}. \\<exists>c\\<in>{y}. a \\<sqsubseteq> c \\<and> b \\<sqsubseteq> c\"\n      by (metis order_refl singletonE yc)\n    moreover have \"\\<exists>z. is_lub z {y}\"\n      by (rule_tac x = y in exI, simp add: is_lub_simp, metis order_refl yc)\n    moreover have \"y \\<sqsubseteq> \\<Sigma> {y}\"\n      by (metis eq_refl singleton_lub yc)\n    ultimately show \"x \\<sqsubseteq> y\"\n      by (metis singleton_iff)\n  qed\n\n  definition compact :: \"'a \\<Rightarrow> prop\" where\n    \"compact x \\<equiv> x \\<guillemotleft> x\"\n\n  definition covers_op :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"covers\" 50) where\n    \"y covers x \\<equiv> x \\<sqsubset> y \\<and> \\<not> (\\<exists>z. x \\<sqsubset> z \\<and> z \\<sqsubset> y)\"\n\nend\n\ndefinition pointwise_extension :: \"'a ord \\<Rightarrow> ('b \\<Rightarrow> 'a) ord\" (\"\\<up>\") where\n  \"pointwise_extension ord = \\<lparr>carrier = UNIV \\<rightarrow> carrier ord, le = \\<lambda>f g. \\<forall>x. le ord (f x) (g x)\\<rparr>\"\n\nlemma extend_ord: \"order A \\<Longrightarrow> order (\\<up> A)\"\n  apply default\n  apply (simp_all add: pointwise_extension_def)\n  apply (metis UNIV_I ftype_pred order.order_refl)\n  apply (metis UNIV_I ftype_pred order.order_trans)\n  apply default\n  by (metis UNIV_I ftype_pred order.order_antisym)\n\nlemma extend_dual: \"\\<up> (A\\<sharp>) = (\\<up> A)\\<sharp>\"\n  by (simp add: pointwise_extension_def ord_inv_def)\n\nlemma dual_is_max: \"order A \\<Longrightarrow> order.is_max (A\\<sharp>) x X = order.is_min A x X\"\n  by (simp add: order.is_max_def order.is_min_def)\n\nlemma dual_is_min: \"order A \\<Longrightarrow> order.is_min (A\\<sharp>) x X = order.is_max A x X\"\n  by (simp add: order.is_max_def order.is_min_def)\n\nabbreviation less_ext :: \"'a \\<Rightarrow> ('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"_\\<sqsubset>\\<^bsub>_\\<^esub>_\" [51,0,51] 50) where\n  \"x \\<sqsubset>\\<^bsub>A\\<^esub> y \\<equiv> order.less A x y\"\n\nabbreviation lub_ext :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a\" (\"\\<Sigma>\\<^bsub>_\\<^esub>_\" [0,1000] 100) where\n  \"\\<Sigma>\\<^bsub>A\\<^esub>X \\<equiv> order.lub A X\"\n\nabbreviation glb_ext :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a\" (\"\\<Pi>\\<^bsub>_\\<^esub>_\" [0,1000] 100) where\n  \"\\<Pi>\\<^bsub>A\\<^esub>X \\<equiv> order.glb A X\"\n\nabbreviation join_ext :: \"'a \\<Rightarrow> ('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"_ \\<squnion>\\<^bsub>_\\<^esub> _\" [71,0,70] 70) where\n  \"x \\<squnion>\\<^bsub>A\\<^esub> y \\<equiv> order.join A x y\"\n\nabbreviation meet_ext :: \"'a \\<Rightarrow> ('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"_ \\<sqinter>\\<^bsub>_\\<^esub> _\" [70,0,70] 70) where\n  \"x \\<sqinter>\\<^bsub>A\\<^esub> y \\<equiv> order.meet A x y\"\n\nsubsection {* Join and meet preserving functions *}\n\ndefinition ex_join_preserving :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"ex_join_preserving A B f \\<equiv> order A \\<and> order B \\<and> (\\<forall>X\\<subseteq>carrier A. ((\\<exists>x\\<in>carrier A. order.is_lub A x X) \\<longrightarrow> order.lub B (f ` X) = f (order.lub A X)))\"\n\ndefinition ex_meet_preserving :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"ex_meet_preserving A B f \\<equiv> order A \\<and> order B \\<and> (\\<forall>X\\<subseteq>carrier A. ((\\<exists>x\\<in>carrier A. order.is_glb A x X) \\<longrightarrow> order.glb B (f ` X) = f (order.glb A X)))\"\n\ndefinition join_preserving :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"join_preserving A B f \\<equiv> order A \\<and> order B \\<and> (\\<forall>X\\<subseteq>carrier A. order.lub B (f ` X) = f (order.lub A X))\"\n\ndefinition meet_preserving :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"meet_preserving A B g \\<equiv> order A \\<and> order B \\<and> (\\<forall>X\\<subseteq>carrier A. order.glb B (g ` X) = g (order.glb A X))\"\n\ndefinition directed :: \"('a, 'b) ord_scheme \\<Rightarrow> bool\" where\n  \"directed A \\<equiv> order A \\<and> (\\<forall>x\\<in>carrier A. \\<forall>y\\<in>carrier A. \\<exists>z\\<in>carrier A. x \\<sqsubseteq>\\<^bsub>A\\<^esub> z \\<and> y \\<sqsubseteq>\\<^bsub>A\\<^esub> z)\"\n\ndefinition scott_continuous :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"scott_continuous A B f \\<equiv> (\\<forall>D\\<subseteq>carrier A. ((directed \\<lparr>carrier = D, le = op \\<sqsubseteq>\\<^bsub>A\\<^esub>\\<rparr>) \\<longrightarrow> order.lub B (f ` D) = f (order.lub A D)))\"\n\ndefinition scott_ne_continuous :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> prop\" where\n  \"scott_ne_continuous A B f \\<equiv> (\\<And>D. \\<lbrakk>D \\<subseteq> carrier A; directed \\<lparr>carrier = D, le = op \\<sqsubseteq>\\<^bsub>A\\<^esub>, \\<dots> = ord.more A\\<rparr>; D \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<Sigma>\\<^bsub>B\\<^esub>(f ` D) = f (\\<Sigma>\\<^bsub>A\\<^esub>D))\"\n\nlemma dual_is_lub [simp]: \"order A \\<Longrightarrow> order.is_lub (A\\<sharp>) x X = order.is_glb A x X\"\n  by (simp add: order.is_glb_simp order.is_lub_simp)\n\nlemma dual_is_ub [simp]: \"order A \\<Longrightarrow> order.is_ub (A\\<sharp>) x X = order.is_lb A x X\"\n  by (simp add: order.is_lb_def order.is_ub_def)\n\nlemma dual_is_glb [simp]: \"order A \\<Longrightarrow> order.is_glb (A\\<sharp>) x X = order.is_lub A x X\"\n  by (simp add: order.is_glb_simp order.is_lub_simp)\n\nlemma dual_is_lb [simp]: \"order A \\<Longrightarrow> order.is_lb (A\\<sharp>) x X = order.is_ub A x X\"\n  by (simp add: order.is_lb_def order.is_ub_def)\n\nlemma dual_lub [simp]: \"order A \\<Longrightarrow> \\<Sigma>\\<^bsub>A\\<sharp>\\<^esub>X = \\<Pi>\\<^bsub>A\\<^esub>X\"\n  by (simp add: order.glb_simp order.lub_simp)\n\nlemma dual_glb [simp]: \"order A \\<Longrightarrow> \\<Pi>\\<^bsub>A\\<sharp>\\<^esub>X = \\<Sigma>\\<^bsub>A\\<^esub>X\"\n  by (simp add: order.glb_simp order.lub_simp)\n\nlemma common: \"\\<lbrakk>A \\<Longrightarrow> P = Q\\<rbrakk> \\<Longrightarrow> (A \\<and> P) = (A \\<and> Q)\" by metis\n\nlemma dual_ex_join_preserving [simp]: \"ex_join_preserving (A\\<sharp>) (B\\<sharp>) f = ex_meet_preserving A B f\"\n  by (simp add: ex_meet_preserving_def ex_join_preserving_def, (rule common)+, simp)\n\nlemma dual_ex_meet_preserving [simp]: \"ex_meet_preserving (A\\<sharp>) (B\\<sharp>) f = ex_join_preserving A B f\"\n  by (simp add: ex_meet_preserving_def ex_join_preserving_def, (rule common)+, simp)\n\nlemma dual_join_preserving [simp]: \"join_preserving (A\\<sharp>) (B\\<sharp>) f = meet_preserving A B f\"\n  by (simp add: meet_preserving_def join_preserving_def, (rule common)+, simp)\n\nlemma dual_meet_preserving [simp]: \"meet_preserving (A\\<sharp>) (B\\<sharp>) f = join_preserving A B f\"\n  by (simp add: meet_preserving_def join_preserving_def, (rule common)+, simp)\n\nhide_fact common\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Total orders *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale total_order = order +\n  assumes totality: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n\nlemma total_order_is_directed: \"total_order A \\<Longrightarrow> directed A\"\n  apply (simp add: directed_def, safe)\n  apply (simp add: total_order_def)\n  by (metis total_order.totality)\n\nlemma dual_total_order: \"total_order A \\<longleftrightarrow> total_order (A\\<sharp>)\"\n  by (simp add: total_order_def total_order_axioms_def, auto)\n\ncontext total_order\nbegin\n\n  lemma is_max_unique: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; X \\<subseteq> carrier A; is_max x X; is_max y X\\<rbrakk> \\<Longrightarrow> x = y\"\n    by (metis is_max_def order_antisym)\n\n  lemma is_min_unique: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; X \\<subseteq> carrier A; is_min x X; is_min y X\\<rbrakk> \\<Longrightarrow> x = y\"\n    by (metis is_min_def order_antisym)\n\n  lemma no_max_equiv: \"X \\<subseteq> carrier A \\<Longrightarrow> (\\<forall>x\\<in>X. \\<exists>y\\<in>X. x \\<sqsubset> y) \\<longleftrightarrow> (\\<forall>x\\<in>carrier A. \\<not> is_max x X)\"\n    by (smt in_mono is_max_def less_def order_antisym totality)\n\n  lemma no_min_equiv: \"X \\<subseteq> carrier A \\<Longrightarrow> (\\<forall>x\\<in>X. \\<exists>y\\<in>X. y \\<sqsubset> x) \\<longleftrightarrow> (\\<forall>x\\<in>carrier A. \\<not> is_min x X)\"\n    by (smt is_min_def less_def order_antisym subsetD totality)\n\n  lemma finite_max_var: \"\\<lbrakk>X \\<subseteq> carrier A; finite X; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> (\\<exists>x\\<in>(insert y X). is_max x (insert y X))\"\n    apply (rule finite_subset_induct_var[of X \"carrier A\"])\n    apply (metis, metis)\n    apply (rule_tac x = y in bexI)\n    apply (simp add: is_max_def)\n    apply (metis singleton_iff)\n  proof -\n    fix a F assume ac: \"a \\<in> carrier A\" and F_subset: \"F \\<subseteq> carrier A\" and yc: \"y \\<in> carrier A\"\n      and \"\\<exists>x\\<in>insert y F. is_max x (insert y F)\"\n    then obtain x where f: \"is_max x (insert y F)\" by auto\n    thus \"\\<exists>x\\<in>insert y (insert a F). is_max x (insert y (insert a F))\"\n      apply (cases \"x \\<sqsubseteq> a\")\n      apply (rule_tac x = a in bexI)\n      apply (smt ac F_subset yc insert_iff is_max_def order_refl order_trans set_rev_mp)\n      apply (simp add: is_max_def)\n      apply (rule_tac x = x in bexI)\n      apply (smt ac F_subset yc insert_iff is_max_def set_rev_mp totality)\n      by (simp add: is_max_def, auto)\n  qed\n\n  lemma finite_max: \"\\<lbrakk>X \\<subseteq> carrier A; finite X; X \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<exists>x. is_max x X\"\n    by (metis finite_max_var insert_absorb2 insert_subset nonempty_iff)\n\n  lemma finite_min:\n    assumes subset: \"X \\<subseteq> carrier A\" and finite: \"finite X\" and non_empty: \"X \\<noteq> {}\"\n    shows \"\\<exists>x. is_min x X\"\n  proof -\n    have \"total_order A\"\n      by unfold_locales\n    hence \"total_order (A\\<sharp>)\"\n      by (metis (lifting) dual_total_order)\n    hence \"\\<exists>x. order.is_max (A\\<sharp>) x X\"\n      by (metis finite inv_carrier_id non_empty subset total_order.finite_max)\n    thus \"\\<exists>x. is_min x X\"\n      by (metis `total_order (A\\<sharp>)` directed_def dual_is_min inv_inv_id total_order_is_directed)\n  qed\n\nend\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Join semilattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale join_semilattice = order +\n  assumes join_ex: \"\\<lbrakk>x \\<in> carrier A; y\\<in>carrier A\\<rbrakk> \\<Longrightarrow> \\<exists>z\\<in>carrier A. is_lub z {x,y}\"\n\ncontext join_semilattice\nbegin\n\n  lemma leq_def: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> (x \\<sqsubseteq> y) \\<longleftrightarrow> (x \\<squnion> y = y)\"\n    apply (simp add: join_def lub_def)\n  proof\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and xy: \"x \\<sqsubseteq> y\"\n    show \"(THE z. is_lub z {x,y}) = y\"\n      by (rule the_equality, simp_all add: is_lub_def is_ub_def, safe, (metis x_closed y_closed xy order_refl order_antisym)+)\n  next\n    assume \"x \\<in> carrier A\" and \"y \\<in> carrier A\" and \"(THE z. is_lub z {x,y}) = y\"\n    thus \"x \\<sqsubseteq> y\"\n      by (metis insertCI is_lub_def is_ub_def join_ex lub_def lub_is_lub)\n  qed\n\n  lemma leq_def_right: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> (x \\<squnion> y = y)\"\n    by (metis leq_def)\n\n  lemma leq_def_left: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; x \\<squnion> y = y\\<rbrakk> \\<Longrightarrow> (x \\<sqsubseteq> y)\"\n    by (metis leq_def)\n\n  lemma join_idem: \"\\<lbrakk>x \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> x = x\" by (metis leq_def order_refl)\n\n  lemma join_comm: \"x \\<squnion> y = y \\<squnion> x\" by (metis insert_commute join_def)\n\n  lemma bin_lub_var: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> y \\<sqsubseteq> z \\<longleftrightarrow> x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\"\n  proof\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and z_closed: \"z \\<in> carrier A\"\n    and join_le_z: \"x \\<squnion> y \\<sqsubseteq> z\"\n    have \"x \\<sqsubseteq> z\" using join_le_z\n      apply (simp add: join_def lub_def)\n      apply (rule_tac ?P = \"\\<lambda>z. is_lub z {x,y}\" in the1I2)\n      apply (metis join_ex lub_is_lub x_closed y_closed)\n      by (smt insertI1 is_lub_def is_ub_def join_def join_le_z lub_is_lub order_trans x_closed z_closed)\n    moreover have \"y \\<sqsubseteq> z\" using join_le_z\n      apply (simp add: join_def lub_def)\n      apply (rule_tac ?P = \"\\<lambda>z. is_lub z {x,y}\" in the1I2)\n      apply (metis join_ex lub_is_lub x_closed y_closed)\n      by (smt insert_iff is_lub_def is_ub_def join_def join_le_z lub_is_lub order_trans y_closed z_closed)\n    ultimately show \"x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\" by auto\n  next\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and z_closed: \"z \\<in> carrier A\"\n    and xz_and_yz: \"x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\"\n    thus \"x \\<squnion> y \\<sqsubseteq> z\"\n      by (smt emptyE lub_is_lub insertE is_lub_def is_ub_def join_ex join_def ord_le_eq_trans)\n  qed\n\n  lemma join_closed: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> y \\<in> carrier A\"\n    by (metis join_def join_ex lub_is_lub)\n\n  lemma join_assoc: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> (x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n  proof -\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and z_closed: \"z \\<in> carrier A\"\n    hence \"(x \\<squnion> y) \\<squnion> z \\<sqsubseteq> x \\<squnion> (y \\<squnion> z)\"\n      by (metis eq_refl bin_lub_var join_closed)\n    thus ?thesis\n      by (smt join_closed order_antisym bin_lub_var order_refl x_closed y_closed z_closed)\n  qed\n\nend\n\nlemma ex_join_preserving_is_iso:\n  assumes f_closed: \"f \\<in> carrier A \\<rightarrow> carrier B\"\n  and js_A: \"join_semilattice A\" and js_B: \"join_semilattice B\"\n  and join_pres: \"ex_join_preserving A B f\"\n  shows \"isotone A B f\"\nproof -\n\n  have ord_A: \"order A\" and ord_B: \"order B\"\n    by (metis ex_join_preserving_def join_pres)+\n\n  have \"\\<forall>x y. x \\<sqsubseteq>\\<^bsub>A\\<^esub> y \\<and> x \\<in> carrier A \\<and> y \\<in> carrier A \\<longrightarrow> f x \\<sqsubseteq>\\<^bsub>B\\<^esub> f y\"\n  proof clarify\n    fix x y assume xy: \"x \\<sqsubseteq>\\<^bsub>A\\<^esub> y\" and xc: \"x \\<in> carrier A\" and yc: \"y \\<in> carrier A\"\n\n    have xyc: \"{x,y} \\<subseteq> carrier A\"\n      by (metis bot_least insert_subset xc yc)\n\n    have ejp: \"\\<forall>X\\<subseteq>carrier A. ((\\<exists>x\\<in>carrier A. order.is_lub A x X) \\<longrightarrow> \\<Sigma>\\<^bsub>B\\<^esub>(f`X) = f (\\<Sigma>\\<^bsub>A\\<^esub>X))\"\n      by (metis ex_join_preserving_def join_pres)\n\n    have \"\\<exists>z\\<in>carrier A. order.is_lub A z {x,y}\"\n      by (metis join_semilattice.join_ex js_A xc yc)\n\n    hence xy_join_pres: \"f (\\<Sigma>\\<^bsub>A\\<^esub>{x,y}) = \\<Sigma>\\<^bsub>B\\<^esub>{f x, f y}\"\n      by (metis ejp xyc image_empty image_insert)\n\n    have \"f (\\<Sigma>\\<^bsub>A\\<^esub>{x,y}) = f y\"\n      by (rule_tac f = f in arg_cong, metis ord_A order.join_def join_semilattice.leq_def_right js_A xc xy yc)\n\n    hence \"\\<Sigma>\\<^bsub>B\\<^esub>{f x, f y} = f y\"\n      by (metis xy_join_pres)\n\n    thus \"f x \\<sqsubseteq>\\<^bsub>B\\<^esub> f y\"\n      by (smt join_semilattice.leq_def_left js_B typed_application f_closed xc yc ord_B order.join_def)\n  qed\n\n  thus ?thesis by (metis isotone_def ord_A ord_B)\nqed\n\nlemma helper: \"\\<lbrakk>\\<And>x. P x \\<and> Q x\\<rbrakk> \\<Longrightarrow> (\\<forall>x. P x) \\<and> (\\<forall>x. Q x)\" by fast\n\nlemma extend_binlub:\n  assumes js_A: \"join_semilattice A\"\n  and fc: \"f \\<in> carrier (\\<up> A)\" and gc: \"g \\<in> carrier (\\<up> A)\"\n  shows \"order.is_lub (\\<up> A) (\\<lambda>x. f x \\<squnion>\\<^bsub>A\\<^esub> g x) {f, g}\"\nproof -\n  have ord_A_ex: \"order (\\<up> A)\"\n    by (insert js_A, simp add: join_semilattice_def, metis extend_ord)\n\n  let ?L = \"\\<lambda>x. f x \\<squnion>\\<^bsub>A\\<^esub> g x\"\n  have Lc: \"?L \\<in> carrier (\\<up> A)\"\n    apply (simp add: pointwise_extension_def, rule typed_abstraction)\n    by (smt UNIV_I assms fc gc join_semilattice.join_closed partial_object.simps(1) pointwise_extension_def typed_application)\n\n  have \"f \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> ?L \\<and> g \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> ?L\"\n  proof (simp add: pointwise_extension_def, rule helper)\n    fix x\n    have fx: \"f x \\<in> carrier A\" and gx: \"g x \\<in> carrier A\"\n      by (smt UNIV_I fc gc partial_object.simps(1) pointwise_extension_def typed_application)+\n    hence Lx: \"?L x \\<in> carrier A\"\n      by (metis assms join_semilattice.join_closed)\n    show \"f x \\<sqsubseteq>\\<^bsub>A\\<^esub> ?L x \\<and> g x \\<sqsubseteq>\\<^bsub>A\\<^esub> ?L x\"\n      apply (simp add: join_semilattice.leq_def[OF js_A fx Lx] join_semilattice.leq_def[OF js_A gx Lx])\n      apply (intro conjI)\n      by (smt assms fx gx join_semilattice.join_assoc join_semilattice.join_idem join_semilattice.join_comm)+\n  qed\n\n  moreover hence \"\\<forall>h\\<in>carrier (\\<up> A). f \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> h \\<and> g \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> h \\<longrightarrow> ?L \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> h\"\n    apply (simp add: pointwise_extension_def)\n    by (smt UNIV_I assms fc gc join_semilattice.bin_lub_var partial_object.simps(1) pointwise_extension_def typed_application)\n\n  ultimately show ?thesis\n    by (simp add: order.is_lub_simp[OF ord_A_ex], safe, (metis fc gc Lc)+)\nqed\n\nlemma extend_join:\n  assumes js_A: \"join_semilattice A\"\n  and fc: \"f \\<in> carrier (\\<up> A)\" and gc: \"g \\<in> carrier (\\<up> A)\"\n  shows \"f \\<squnion>\\<^bsub>\\<up> A\\<^esub> g = (\\<lambda>x. f x \\<squnion>\\<^bsub>A\\<^esub> g x)\"\nproof -\n  have ord_A_ex: \"order (\\<up> A)\"\n    by (insert js_A, simp add: join_semilattice_def, metis extend_ord)\n\n  show ?thesis\n    apply (insert extend_binlub[OF js_A fc gc])\n    by (simp add: order.join_def[OF ord_A_ex], metis ord_A_ex order.lub_is_lub)\nqed\n\nlemma extend_js:\n  assumes js_A: \"join_semilattice A\"\n  shows \"join_semilattice (\\<up> A)\"\nproof (simp add: join_semilattice_def join_semilattice_axioms_def, safe)\n  show ord_A_ex: \"order (\\<up> A)\"\n    by (insert js_A, simp add: join_semilattice_def, metis extend_ord)\n\n  fix f g :: \"'b \\<Rightarrow> 'a\" assume fc: \"f \\<in> carrier (\\<up> A)\" and gc: \"g \\<in> carrier (\\<up> A)\"\n\n  thus \"\\<exists>h\\<in>carrier (\\<up> A). order.is_lub (\\<up> A) h {f, g}\"\n    by (smt assms extend_binlub ord_A_ex order.is_lub_simp)\nqed\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Meet semilattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale meet_semilattice = order +\n  assumes meet_ex: \"\\<lbrakk>x \\<in> carrier A; y\\<in>carrier A\\<rbrakk> \\<Longrightarrow> \\<exists>z\\<in>carrier A. is_glb z {x,y}\"\n\ncontext meet_semilattice\nbegin\n\n  lemma leq_meet_def: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> (x \\<sqsubseteq> y) \\<longleftrightarrow> (x \\<sqinter> y = x)\"\n    apply (simp add: meet_def glb_def)\n  proof\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and xy: \"x \\<sqsubseteq> y\"\n    show \"(THE z. is_glb z {x,y}) = x\"\n      by (rule the_equality, simp_all add: is_glb_def is_lb_def, safe, (metis x_closed y_closed xy order_refl order_antisym)+)\n  next\n    assume \"x \\<in> carrier A\" and \"y \\<in> carrier A\" and \"(THE z. is_glb z {x,y}) = x\"\n    thus \"x \\<sqsubseteq> y\"\n      by (metis insertCI is_glb_def is_lb_def meet_ex glb_def glb_is_glb)\n  qed\n\n  lemma meet_idem: \"\\<lbrakk>x \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqinter> x = x\" by (metis leq_meet_def order_refl)\n\n  \n\n  lemma bin_glb_var: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> z \\<sqsubseteq> x \\<sqinter> y \\<longleftrightarrow> z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y\"\n  proof\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and z_closed: \"z \\<in> carrier A\"\n    and meet_le_z: \"z \\<sqsubseteq> x \\<sqinter> y\"\n    have \"z \\<sqsubseteq> x\" using meet_le_z\n      apply (simp add: meet_def glb_def)\n      apply (rule_tac ?P = \"\\<lambda>z. is_glb z {x,y}\" in the1I2)\n      apply (metis meet_ex glb_is_glb x_closed y_closed)\n      by (smt insertI1 is_glb_def is_lb_def meet_def meet_le_z glb_is_glb order_trans x_closed z_closed)\n    moreover have \"z \\<sqsubseteq> y\" using meet_le_z\n      apply (simp add: meet_def glb_def)\n      apply (rule_tac ?P = \"\\<lambda>z. is_glb z {x,y}\" in the1I2)\n      apply (metis meet_ex glb_is_glb x_closed y_closed)\n      by (smt insert_iff is_glb_def is_lb_def meet_def meet_le_z glb_is_glb order_trans y_closed z_closed)\n    ultimately show \"z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y\" by auto\n  next\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and z_closed: \"z \\<in> carrier A\"\n    and xz_and_yz: \"z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y\"\n    thus \"z \\<sqsubseteq> x \\<sqinter> y\"\n      by (smt emptyE glb_is_glb insertE is_glb_def is_lb_def meet_ex meet_def ord_le_eq_trans)\n  qed\n\n  lemma meet_closed: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqinter> y \\<in> carrier A\"\n    by (metis meet_def meet_ex glb_is_glb)\n\n  lemma meet_assoc: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> (x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n  proof -\n    assume x_closed: \"x \\<in> carrier A\" and y_closed: \"y \\<in> carrier A\" and z_closed: \"z \\<in> carrier A\"\n    hence \"(x \\<sqinter> y) \\<sqinter> z \\<sqsubseteq> x \\<sqinter> (y \\<sqinter> z)\"\n      by (metis eq_refl bin_glb_var meet_closed)\n    thus ?thesis\n      by (smt meet_closed order_antisym bin_glb_var order_refl x_closed y_closed z_closed)\n  qed\n\nend\n\nlemma inv_meet_semilattice_is_join [simp]: \"meet_semilattice (A\\<sharp>) = join_semilattice A\"\n  by (simp_all add: meet_semilattice_def join_semilattice_def meet_semilattice_axioms_def join_semilattice_axioms_def, safe, simp_all)\n\nlemma inv_join_semilattice_is_meet [simp]: \"join_semilattice (A\\<sharp>) = meet_semilattice A\"\n  by (simp add: meet_semilattice_def join_semilattice_def meet_semilattice_axioms_def join_semilattice_axioms_def, safe, simp_all)\n\nlemma ex_meet_preserving_is_iso:\n  assumes f_closed: \"f \\<in> carrier A \\<rightarrow> carrier B\"\n  and js_A: \"meet_semilattice A\" and js_B: \"meet_semilattice B\"\n  and join_pres: \"ex_meet_preserving A B f\"\n  shows \"isotone A B f\"\nproof -\n  have \"isotone (A\\<sharp>) (B\\<sharp>) f\"\n    by (rule ex_join_preserving_is_iso, simp_all add: f_closed js_A js_B join_pres)\n  thus \"isotone A B f\" by simp\nqed\n\nlemma extend_ms:\n  assumes ms_A: \"meet_semilattice A\"\n  shows \"meet_semilattice (\\<up> A)\"\n  by (metis (lifting) assms extend_dual extend_js inv_join_semilattice_is_meet)\n\nlemma extend_binglb:\n  assumes ms_A: \"meet_semilattice A\"\n  and fc: \"f \\<in> carrier (\\<up> A)\" and gc: \"g \\<in> carrier (\\<up> A)\"\n  shows \"order.is_glb (\\<up> A) (\\<lambda>x. f x \\<sqinter>\\<^bsub>A\\<^esub> g x) {f, g}\"\nproof -\n  have ord_A: \"order A\"\n    by (insert ms_A, simp add: meet_semilattice_def)\n  hence ord_A_ex: \"order (\\<up> A)\"\n    by (metis extend_ord)\n  have \"order.is_lub (\\<up> (A\\<sharp>)) (\\<lambda>x. f x \\<squnion>\\<^bsub>A\\<sharp>\\<^esub> g x) {f, g}\"\n    apply (rule extend_binlub)\n    apply (metis assms(1) inv_join_semilattice_is_meet)\n    apply (metis extend_dual fc inv_carrier_id)\n    by (metis extend_dual gc inv_carrier_id)\n  thus ?thesis using ord_A ord_A_ex\n    by (simp add: extend_dual order.join_def order.meet_def dual_is_lub[OF ord_A_ex])\nqed\n\nlemma extend_meet:\n  assumes ms_A: \"meet_semilattice A\"\n  and fc: \"f \\<in> carrier (\\<up> A)\" and gc: \"g \\<in> carrier (\\<up> A)\"\n  shows \"f \\<sqinter>\\<^bsub>\\<up> A\\<^esub> g = (\\<lambda>x. f x \\<sqinter>\\<^bsub>A\\<^esub> g x)\"\nproof -\n  have ord_A_ex: \"order (\\<up> A)\"\n    by (insert ms_A, simp add: meet_semilattice_def, metis extend_ord)\n  thus ?thesis\n    apply (insert extend_binglb[OF ms_A fc gc])\n    apply (simp add: order.meet_def[OF ord_A_ex])\n    by (metis ord_A_ex order.glb_is_glb)\nqed\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Lattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale lattice = join_semilattice + meet_semilattice\n\nbegin\n\n  lemma absorb1: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> (x \\<sqinter> y) = x\"\n    by (metis join_comm leq_def leq_meet_def meet_assoc meet_closed meet_comm meet_idem)\n\n  lemma absorb2: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqinter> (x \\<squnion> y) = x\"\n    by (metis join_assoc join_closed join_comm join_idem leq_def leq_meet_def)\n\n  lemma order_change: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x\\<sqinter>y = y \\<longleftrightarrow> y\\<squnion>x = x\"\n    by (metis leq_def leq_meet_def meet_comm)\n\n  lemma bin_lub_insert:\n    assumes xc: \"x \\<in> carrier A\" and X_subset: \"X \\<subseteq> carrier A\"\n    and X_lub: \"\\<exists>y. is_lub y X\"\n    shows \"\\<exists>z. is_lub z (insert x X)\"\n  proof -\n    obtain y where y_lub: \"is_lub y X\" and yc: \"y \\<in> carrier A\" by (metis X_lub is_lub_simp)\n    have \"\\<exists>z. is_lub z (insert x X)\"\n    proof (intro exI conjI)\n      have \"\\<Sigma> {x, y} \\<in> carrier A\"\n        by (metis join_closed join_def xc yc)\n      thus \"is_lub (\\<Sigma> {x, y}) (insert x X)\"\n        apply (simp add: is_lub_simp, safe)\n        apply (metis xc)\n        apply (metis X_subset set_mp)\n        apply (metis bin_lub_var join_def order_refl xc yc)\n        apply (metis (full_types) absorb2 bin_glb_var is_lub_simp join_comm join_def set_mp xc y_lub yc)\n        by (metis bin_lub_var is_lub_simp join_def xc y_lub)\n    qed\n    thus \"\\<exists>z. is_lub z (insert x X)\"\n      by metis\n  qed\n\n  lemma set_induct: \"\\<lbrakk>X \\<subseteq> carrier A; finite X; P {}; \\<And>y Y. \\<lbrakk>finite Y; y \\<notin> Y; y \\<in> carrier A; P Y\\<rbrakk> \\<Longrightarrow> P (insert y Y)\\<rbrakk> \\<Longrightarrow> P X\"\n    by (metis (no_types) finite_subset_induct)\n\n  lemma finite_lub_var: \"\\<lbrakk>(insert x X) \\<subseteq> carrier A; finite (insert x X)\\<rbrakk> \\<Longrightarrow> \\<exists>z. is_lub z (insert x X)\"\n    apply (rule_tac X = X and P = \"\\<lambda>X. \\<exists>z. is_lub z (insert x X)\" in set_induct)\n    apply (metis insert_subset)\n    apply (metis finite_insert)\n    apply (metis insert_absorb2 insert_subset join_ex)\n    apply (simp add: insert_commute)\n    apply (rule bin_lub_insert)\n    apply metis\n    apply (metis is_lub_simp)\n    by metis\n\n  lemma finite_lub: \"\\<lbrakk>X \\<subseteq> carrier A; finite X; X \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<exists>x. is_lub x X\"\n    by (metis finite.simps finite_lub_var)\n\nend\n\nlemma inv_lattice [simp]: \"lattice (A\\<sharp>) = lattice A\"\n  by (simp add: lattice_def, auto)\n\ncontext lattice\nbegin\n\n  lemma finite_glb:\n    assumes \"X \\<subseteq> carrier A\" and \"finite X\" and \"X \\<noteq> {}\"\n    shows \"\\<exists>x. is_glb x X\"\n  proof -\n    have ord_Ash: \"order (A\\<sharp>)\"\n      by (simp, unfold_locales)\n\n    have \"\\<exists>x. order.is_lub (A\\<sharp>) x X\"\n      by (rule lattice.finite_lub, simp_all add: assms, unfold_locales)\n    thus \"\\<exists>x. is_glb x X\"\n      by (insert ord_Ash, simp)\n  qed\n\n  lemma finite_lub_carrier:\n    assumes A_finite: \"finite (carrier A)\"\n    and A_non_empty: \"carrier A \\<noteq> {}\"\n    and X_subset: \"X \\<subseteq> carrier A\"\n    shows \"\\<exists>x. is_lub x X\"\n  proof (cases \"X = {}\")\n    assume x_empty: \"X = {}\"\n    show \"\\<exists>x. is_lub x X\"\n    proof (intro exI)\n      show \"is_lub (\\<Pi> (carrier A)) X\"\n        by (metis (lifting) A_finite A_non_empty X_subset x_empty ex_in_conv finite_glb glb_is_glb is_glb_simp is_lub_def is_ub_def set_eq_subset)\n    qed\n  next\n    assume \"X \\<noteq> {}\"\n    thus \"\\<exists>x. is_lub x X\"\n      by (metis A_finite X_subset finite_lub rev_finite_subset)\n  qed\n\n  lemma finite_glb_carrier:\n    assumes A_finite: \"finite (carrier A)\"\n    and A_non_empty: \"carrier A \\<noteq> {}\"\n    and X_subset: \"X \\<subseteq> carrier A\"\n    shows \"\\<exists>x. is_glb x X\"\n  proof -\n    have ord_Ash: \"order (A\\<sharp>)\"\n      by (simp, unfold_locales)\n    have \"\\<exists>x. order.is_lub (A\\<sharp>) x X\"\n      by (rule lattice.finite_lub_carrier, simp_all add: assms, unfold_locales)\n    thus ?thesis by (insert ord_Ash, simp)\n  qed\n\nend\n\nlemma extend_lattice: \"lattice A \\<Longrightarrow> lattice (\\<up> A)\"\n  by (simp add: lattice_def extend_js extend_ms)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Distributive Lattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale distributive_lattice = lattice +\n  assumes dist1: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n  and dist2: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A; z \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n\nlemma extend_distributive:\n  assumes dl_A: \"distributive_lattice A\"\n  shows \"distributive_lattice (\\<up> A)\"\nproof (simp add: distributive_lattice_def distributive_lattice_axioms_def, safe)\n  have \"lattice A\"\n    by (insert dl_A, simp add: distributive_lattice_def)\n  thus \"lattice (\\<up> A)\"\n    by (metis extend_lattice)\n  hence ord_A_ex: \"order (\\<up> A)\"\n    by (simp add: lattice_def join_semilattice_def, auto)\n  from `lattice A` have js_A: \"join_semilattice A\" and ms_A: \"meet_semilattice A\"\n    by (simp add: lattice_def)+\n\n  fix x y z :: \"'d \\<Rightarrow> 'a\"\n  assume xc: \"x \\<in> carrier (\\<up> A)\" and yc: \"y \\<in> carrier (\\<up> A)\" and zc: \"z \\<in> carrier (\\<up> A)\"\n\n  hence yzj: \"y \\<squnion>\\<^bsub>\\<up>A\\<^esub> z \\<in> carrier (\\<up> A)\"\n    by (metis extend_js join_semilattice.join_closed js_A)\n  have xym: \"x \\<sqinter>\\<^bsub>\\<up>A\\<^esub> y \\<in> carrier (\\<up> A)\"\n    by (metis extend_ms meet_semilattice.meet_closed ms_A xc yc)\n  have xzm: \"x \\<sqinter>\\<^bsub>\\<up>A\\<^esub> z \\<in> carrier (\\<up> A)\"\n    by (metis extend_ms meet_semilattice.meet_closed ms_A xc zc)\n\n  from xc yc zc yzj xym xzm\n  show \"x \\<sqinter>\\<^bsub>\\<up> A\\<^esub> (y \\<squnion>\\<^bsub>\\<up> A\\<^esub> z) = (x \\<sqinter>\\<^bsub>\\<up> A\\<^esub> y) \\<squnion>\\<^bsub>\\<up> A\\<^esub> (x \\<sqinter>\\<^bsub>\\<up> A\\<^esub> z)\"\n    apply (simp add: extend_join[OF js_A] extend_meet[OF ms_A])\n    apply (simp add: pointwise_extension_def)\n    by (metis (hide_lams, no_types) UNIV_I assms distributive_lattice.dist1 typed_application)\n\n  hence yzm: \"y \\<sqinter>\\<^bsub>\\<up>A\\<^esub> z \\<in> carrier (\\<up> A)\"\n    by (metis extend_ms meet_semilattice.meet_closed ms_A yc zc)\n  have xyj: \"x \\<squnion>\\<^bsub>\\<up>A\\<^esub> y \\<in> carrier (\\<up> A)\"\n    by (metis extend_js join_semilattice.join_closed js_A xc yc)\n  have xzj: \"x \\<squnion>\\<^bsub>\\<up>A\\<^esub> z \\<in> carrier (\\<up> A)\"\n    by (metis extend_js join_semilattice.join_closed js_A xc zc)\n\n  from xc yc zc yzm xyj xzj\n  show \"x \\<squnion>\\<^bsub>\\<up> A\\<^esub> (y \\<sqinter>\\<^bsub>\\<up> A\\<^esub> z) = (x \\<squnion>\\<^bsub>\\<up> A\\<^esub> y) \\<sqinter>\\<^bsub>\\<up> A\\<^esub> (x \\<squnion>\\<^bsub>\\<up> A\\<^esub> z)\"\n    apply (simp add: extend_join[OF js_A] extend_meet[OF ms_A])\n    apply (simp add: pointwise_extension_def)\n    by (metis (hide_lams, no_types) UNIV_I assms distributive_lattice.dist2 typed_application)\nqed\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Bounded Lattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale bounded_lattice = lattice +\n  assumes bot_ex: \"\\<exists>b\\<in>carrier A. \\<forall>x\\<in>carrier A. b \\<squnion> x = x\"\n  and top_ex: \"\\<exists>t\\<in>carrier A. \\<forall>x\\<in>carrier A. t \\<sqinter> x = x\"\n\ncontext bounded_lattice\nbegin\n\n  definition bot :: \"'a\" (\"\\<bottom>\") where \"\\<bottom> \\<equiv> THE x. x\\<in>carrier A \\<and> (\\<forall>y\\<in>carrier A. x \\<sqsubseteq> y)\"\n\n  lemma bot_closed: \"\\<bottom> \\<in> carrier A\"\n    apply (simp add: bot_def)\n    apply (rule the1I2)\n    apply (metis (no_types) bot_ex leq_def_left order_antisym)\n    by auto\n\n  definition top :: \"'a\" (\"\\<top>\") where \"\\<top> \\<equiv> THE x. x\\<in>carrier A \\<and> (\\<forall>y\\<in>carrier A. y \\<sqsubseteq> x)\"\n\n  lemma top_closed: \"\\<top> \\<in> carrier A\"\n    apply (simp add: top_def)\n    apply (rule the1I2)\n    apply (metis (hide_lams, no_types) leq_meet_def meet_comm top_ex)\n    by auto\n\n  lemma bot_least: \"x \\<in> carrier A \\<Longrightarrow> \\<bottom> \\<sqsubseteq> x\"\n    apply (simp add: bot_def)\n    apply (rule the1I2)\n    apply (metis (no_types) bot_ex leq_def_left order_antisym)\n    by auto\n\n  lemma top_greatest: \"x \\<in> carrier A \\<Longrightarrow> x \\<sqsubseteq> \\<top>\"\n    apply (simp add: top_def)\n    apply (rule the1I2)\n    apply (metis (hide_lams, no_types) leq_meet_def meet_comm top_ex)\n    by auto\n\n  definition atom :: \"'a \\<Rightarrow> bool\" where\n    \"atom x \\<equiv> x covers \\<bottom>\"\n\n  definition atoms :: \"'a set\" where\n    \"atoms \\<equiv> {x. x covers \\<bottom> \\<and> x \\<in> carrier A}\"\n\nend\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Complemented Lattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale complemented_lattice = bounded_lattice +\n  assumes compl: \"x \\<in> carrier A \\<Longrightarrow> \\<exists>y. y \\<in> carrier A \\<and> x \\<squnion> y = \\<top> \\<and> x \\<sqinter> y = \\<bottom>\"\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Boolean algebra *}\n(* +------------------------------------------------------------------------+ *)\n\ndatatype 'a ba_expr = BNand \"'a ba_expr\" \"'a ba_expr\"\n                    | BOne\n                    | BZero\n                    | BAtom 'a\n\nprimrec be_atoms :: \"'a ba_expr \\<Rightarrow> 'a set\" where\n  \"be_atoms (BNand x y) = be_atoms x \\<union> be_atoms y\"\n| \"be_atoms BOne = {}\"\n| \"be_atoms BZero = {}\"\n| \"be_atoms (BAtom x) = {x}\"\n\nlocale boolean_algebra = complemented_lattice + distributive_lattice\n\nbegin\n\n  lemma compl_uniq:\n    assumes xc: \"x \\<in> carrier A\"\n    shows \"\\<exists>!y. y \\<in> carrier A \\<and> x \\<squnion> y = \\<top> \\<and> x \\<sqinter> y = \\<bottom>\"\n    apply safe\n    apply (metis assms compl)\n    by (metis absorb2 assms dist1 join_comm meet_comm)\n\n  definition complement :: \"'a \\<Rightarrow> 'a\" (\"!\") where\n    \"complement x = (THE y. y \\<in> carrier A \\<and> x \\<squnion> y = \\<top> \\<and> x \\<sqinter> y = \\<bottom>)\"\n\n  lemma complement_closed: assumes xc: \"x \\<in> carrier A\" shows \"!x \\<in> carrier A\"\n    by (simp add: complement_def, rule the1I2, rule compl_uniq[OF xc], auto)\n\n  primrec be_unfold :: \"'a ba_expr \\<Rightarrow> 'a\" where\n    \"be_unfold BOne = \\<top>\"\n  | \"be_unfold BZero = \\<bottom>\"\n  | \"be_unfold (BNand x y) = (! (be_unfold x \\<squnion> be_unfold y))\"\n  | \"be_unfold (BAtom x) = x\"\n\n  lemma atoms_closed: \"atoms \\<subseteq> carrier A\"\n    by (auto simp add: atoms_def)\n\n  (*\n  lemma complement1: \"x \\<in> carrier A \\<Longrightarrow> x \\<squnion> !x = \\<top>\" sorry\n\n  lemma complement2: \"x \\<in> carrier A \\<Longrightarrow> x \\<sqinter> !x = \\<bottom>\" sorry\n\n  lemma not_one: \"!\\<top> = \\<bottom>\" sorry\n\n  lemma not_zero: \"!\\<bottom> = \\<top>\" sorry\n\n  lemma double_compl: \"x \\<in> carrier A \\<Longrightarrow> !(!x) = x\" sorry\n\n  lemma de_morgan1: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> !x \\<sqinter> !y = !(x \\<squnion> y)\" sorry\n\n  lemma ba_meet_def: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqinter> y = !(!x \\<squnion> !y)\" sorry\n\n  lemma de_morgan2: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> !x \\<squnion> !y = !(x \\<sqinter> y)\" sorry\n\n  lemma compl_anti: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> y \\<longleftrightarrow> !y \\<sqsubseteq> !x\" sorry\n\n  lemma ba_join_def: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> y = !(!x \\<sqinter> !y)\" sorry\n\n  lemma ba_3: \"\\<lbrakk>x \\<in> carrier A; y \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> !y)\" sorry\n      *)\n\nend\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Complete join semilattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale complete_join_semilattice = order +\n  assumes lub_ex: \"\\<lbrakk>X \\<subseteq> carrier A\\<rbrakk> \\<Longrightarrow> \\<exists>x\\<in>carrier A. is_lub x X\"\n\nsublocale complete_join_semilattice \\<subseteq> join_semilattice\n  by default (metis bot_least insert_subset lub_ex)\n\ncontext complete_join_semilattice\nbegin\n\n  lemma bot_ax: \"\\<exists>!b\\<in>carrier A. \\<forall>x\\<in>carrier A. b \\<sqsubseteq> x\"\n    by (metis (no_types) order_antisym bot_least equals0D is_lub_def lub_ex)\n\n  definition bot :: \"'a\" (\"\\<bottom>\") where \"\\<bottom> \\<equiv> THE x. x\\<in>carrier A \\<and> (\\<forall>y\\<in>carrier A. x \\<sqsubseteq> y)\"\n\n  lemma bot_closed: \"\\<bottom> \\<in> carrier A\" by (smt bot_def the1I2 bot_ax)\n\n  lemma prop_bot: \"\\<forall>x\\<in>carrier A. \\<bottom> \\<sqsubseteq> x\"\n    by (simp only: bot_def, rule the1I2, smt bot_ax, metis)\n\n  lemma is_lub_lub [intro?]: \"X \\<subseteq> carrier A \\<Longrightarrow> is_lub (\\<Sigma> X) X\"\n    by (metis lub_ex lub_is_lub)\n\n  lemma lub_ex_var: \"X \\<subseteq> carrier A \\<Longrightarrow> \\<exists>!x. is_lub x X\"\n    by (metis is_lub_lub lub_is_lub)\n\n  lemma lub_ex_var2: \"X \\<subseteq> carrier A \\<Longrightarrow> \\<exists>x. is_lub x X\"\n    by (metis lub_ex)\n\n  lemma lub_greatest [intro?]: \"\\<lbrakk>x \\<in> carrier A; X \\<subseteq> carrier A; \\<forall>y\\<in>X. y \\<sqsubseteq> x\\<rbrakk> \\<Longrightarrow> \\<Sigma> X \\<sqsubseteq> x\"\n    by (metis is_lub_def is_lub_lub)\n\n  lemma lub_least [intro?]: \"\\<lbrakk>X \\<subseteq> carrier A; x \\<in> X\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> \\<Sigma> X\"\n    by (metis is_lub_def is_lub_lub is_ub_def)\n\n  lemma empty_lub [simp]: \"\\<Sigma> {} = \\<bottom>\"\n    by (metis bot_closed empty_iff empty_subsetI is_lub_def is_ub_def lub_is_lub prop_bot)\n\n  lemma bot_oner [simp]: \"\\<lbrakk>x \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<squnion> \\<bottom> = x\"\n    by (metis join_comm bot_closed leq_def prop_bot)\n\n  lemma bot_onel [simp]: \"\\<lbrakk>x \\<in> carrier A\\<rbrakk> \\<Longrightarrow> \\<bottom> \\<squnion> x = x\"\n    by (metis join_comm bot_oner)\n\n  lemma lub_union: \"\\<lbrakk>X \\<subseteq> carrier A; Y \\<subseteq> carrier A\\<rbrakk> \\<Longrightarrow> \\<Sigma> (X \\<union> Y) = \\<Sigma> X \\<squnion> \\<Sigma> Y\"\n    apply (rule lub_is_lub)\n    apply (simp add: join_def)\n    apply (simp add: is_lub_simp, safe)\n    prefer 4\n    apply (metis UnCI bin_lub_var is_lub_simp join_def lub_ex lub_is_lub)\n    apply (metis is_lub_lub is_lub_simp join_closed join_def)\n    apply (rule the_lub_geq)\n    apply (metis is_lub_lub is_lub_simp join_ex)\n    apply (metis (hide_lams, no_types) insertI1 insert_absorb insert_subset is_lub_simp lub_least order_trans)\n    apply (rule the_lub_geq)\n    apply (metis is_lub_lub is_lub_simp join_ex)\n    by (metis (hide_lams, no_types) insertI1 insertI2 insert_absorb insert_subset is_lub_simp lub_least order_trans)\n\n  lemma lub_subset_var: \"\\<lbrakk>X \\<subseteq> carrier A; Y \\<subseteq> carrier A; X \\<subseteq> Y\\<rbrakk> \\<Longrightarrow> \\<Sigma> X \\<sqsubseteq> \\<Sigma> Y\"\n    by (metis is_lub_lub lub_subset)\n\n  lemma lub_inf_idem_leq: assumes X_set: \"X \\<subseteq> Pow (carrier A)\" shows \"\\<Sigma> (\\<Sigma> ` X) \\<sqsubseteq> \\<Sigma> (\\<Union> X)\"\n  proof -\n    have \"\\<Sigma> ` X \\<in> Pow (carrier A)\"\n      by (metis (lifting) PowD PowI X_set image_subsetI is_lub_lub is_lub_simp set_rev_mp)\n    hence Sup_X_set: \"\\<Sigma> ` X \\<subseteq> carrier A\"\n      by (metis Pow_iff)\n\n    show ?thesis\n      apply (rule the_lub_leq)\n      apply (metis Sup_X_set lub_ex)\n      apply safe\n      apply (rule the_lub_geq)\n      apply (metis Sup_subset_mono Union_Pow_eq X_set lub_ex)\n      apply (simp add: is_lub_simp)\n      apply safe\n      by (metis Sup_le_iff lub_greatest)\n  qed\n\nend\n\nabbreviation bot_ext :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a\" (\"\\<bottom>\\<^bsub>_\\<^esub>\") where\n  \"\\<bottom>\\<^bsub>A\\<^esub> \\<equiv> complete_join_semilattice.bot A\"\n\nlemma extend_lub_closed:\n  assumes cjs_A: \"complete_join_semilattice A\" and X_subset: \"X \\<subseteq> carrier (\\<up> A)\"\n  shows \"(\\<lambda>x. \\<Sigma>\\<^bsub>A\\<^esub>((\\<lambda>f. f x) ` X)) \\<in> carrier (\\<up> A)\"\nproof -\n  have ord_A: \"order A\"\n    by (metis cjs_A complete_join_semilattice_def)\n\n  have X_map: \"\\<forall>x. ((\\<lambda>f. f x) ` X) \\<subseteq> carrier A\"\n    apply (default, rule typed_mapping[of _ \"carrier (\\<up> A)\"])\n    apply (simp add: ftype_pred, simp add: pointwise_extension_def)\n    by (metis UNIV_I typed_application, metis X_subset)\n\n  show ?thesis\n  proof (simp add: pointwise_extension_def, rule typed_abstraction, safe)\n    fix x show \"\\<Sigma>\\<^bsub>A\\<^esub>((\\<lambda>f. f x) ` X) \\<in> carrier A\"\n      by (metis assms X_map complete_join_semilattice.lub_ex ord_A order.lub_closed)\n  qed\nqed\n\nlemma extend_lub:\n  assumes cjs_A: \"complete_join_semilattice A\" and X_subset: \"X \\<subseteq> carrier (\\<up> A)\"\n  shows \"order.is_lub (\\<up> A) (\\<lambda>x. \\<Sigma>\\<^bsub>A\\<^esub>((\\<lambda>f. f x) ` X)) X\"\nproof -\n  have ord_A: \"order A\"\n    by (metis cjs_A complete_join_semilattice_def)\n  hence ord_A_ex: \"order (\\<up> A)\" by (rule extend_ord)\n\n  let ?L = \"\\<lambda>x. \\<Sigma>\\<^bsub>A\\<^esub>((\\<lambda>f. f x) ` X)\"\n\n  have X_map: \"\\<forall>x. ((\\<lambda>f. f x) ` X) \\<subseteq> carrier A\"\n    apply (default, rule typed_mapping[of _ \"carrier (\\<up> A)\"])\n    apply (simp add: ftype_pred, simp add: pointwise_extension_def)\n    by (metis UNIV_I typed_application, metis X_subset)\n\n  have Lc: \"?L \\<in> carrier (\\<up> A)\"\n    by (metis X_subset cjs_A extend_lub_closed)\n\n  have \"\\<forall>h\\<in>X. h \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> ?L\"\n    apply (simp add: pointwise_extension_def)\n    apply (simp add: order.lub_def[OF ord_A])\n    apply safe\n    apply (rule the1I2)\n    apply auto\n    apply (rule complete_join_semilattice.lub_ex_var2[OF cjs_A])\n    apply (metis X_map)\n    apply (metis ord_A order.is_lub_unique)\n    by (metis image_eqI ord_A order.is_lub_simp)\n\n  thus \"order.is_lub (\\<up> A) ?L X\"\n    apply (simp add: order.is_lub_simp[OF ord_A_ex])\n    apply safe\n    apply (metis X_subset set_mp)\n    apply (metis Lc)\n    apply (simp add: pointwise_extension_def)\n    by (smt UNIV_I X_map assms complete_join_semilattice.lub_greatest ftype_pred imageE)\nqed\n\nlemma extend_cjs:\n  assumes cjs_A: \"complete_join_semilattice A\"\n  shows \"complete_join_semilattice (\\<up> A)\"\n  apply (simp add: complete_join_semilattice_def complete_join_semilattice_axioms_def, safe)\n  apply (subgoal_tac \"order A\")\n  apply (rule extend_ord, auto)\n  apply (metis cjs_A complete_join_semilattice_def)\n  apply (rule_tac x = \"\\<lambda>x. \\<Sigma>\\<^bsub>A\\<^esub>((\\<lambda>f. f x) ` X)\" in bexI)\n  apply (metis assms extend_lub)\n  by (metis assms extend_lub_closed)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Complete meet semilattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale complete_meet_semilattice = order +\n  assumes glb_ex: \"\\<lbrakk>X \\<subseteq> carrier A\\<rbrakk> \\<Longrightarrow> \\<exists>x\\<in>carrier A. is_glb x X\"\n\nsublocale complete_meet_semilattice \\<subseteq> meet_semilattice\n  by default (metis bot_least insert_subset glb_ex)\n\ncontext complete_meet_semilattice\nbegin\n\n  lemma top_ax: \"\\<exists>!t\\<in>carrier A. \\<forall>x\\<in>carrier A. x \\<sqsubseteq> t\"\n    by (metis (no_types) order_antisym bot_least equals0D glb_ex is_glb_def)\n\n  definition top :: \"'a\" (\"\\<top>\") where \"\\<top> \\<equiv> THE x. x\\<in>carrier A \\<and> (\\<forall>y\\<in>carrier A. y \\<sqsubseteq> x)\"\n\n  lemma top_closed: \"\\<top> \\<in> carrier A\" by (smt top_def the1I2 top_ax)\n\n  lemma prop_top: \"\\<forall>x\\<in>carrier A. x \\<sqsubseteq> \\<top>\"\n    by (simp only: top_def, rule the1I2, smt top_ax, metis)\n\n  lemma is_glb_glb [intro?]: \"X \\<subseteq> carrier A \\<Longrightarrow> is_glb (\\<Pi> X) X\"\n    by (metis glb_ex glb_is_glb)\n\n  lemma glb_greatest [intro?]: \"\\<lbrakk>x \\<in> carrier A; X \\<subseteq> carrier A; \\<forall>y\\<in>X. x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> \\<Pi> X\"\n    by (metis is_glb_def is_glb_glb)\n\n  lemma glb_least [intro?]: \"\\<lbrakk>X \\<subseteq> carrier A; x \\<in> X\\<rbrakk> \\<Longrightarrow> \\<Pi> X \\<sqsubseteq> x\"\n    by (metis is_glb_def is_glb_glb is_lb_def)\n\n  lemma empty_glb [simp]: \"\\<Pi> {} = \\<top>\"\n    by (metis order_antisym bot_least glb_closed glb_is_glb glb_subset insert_absorb2 is_glb_glb meet_def meet_ex prop_top singleton_glb subset_insertI top_closed)\n\n  lemma top_oner [simp]: \"\\<lbrakk>x \\<in> carrier A\\<rbrakk> \\<Longrightarrow> x \\<sqinter> \\<top> = x\"\n    by (metis meet_comm top_closed leq_meet_def prop_top)\n\n  lemma top_onel [simp]: \"\\<lbrakk>x \\<in> carrier A\\<rbrakk> \\<Longrightarrow> \\<top> \\<sqinter> x = x\"\n    by (metis meet_comm top_oner)\n\n  lemma glb_inf_idem_leq: assumes X_set: \"X \\<subseteq> Pow (carrier A)\" shows \"\\<Pi> (\\<Pi> ` X) \\<sqsubseteq> \\<Pi> (\\<Union> X)\"\n  proof -\n    have \"\\<Pi> ` X \\<in> Pow (carrier A)\"\n      by (metis (lifting) PowD PowI X_set image_subsetI is_glb_glb is_glb_simp set_rev_mp)\n    hence Inf_X_set: \"\\<Pi> ` X \\<subseteq> carrier A\"\n      by (metis Pow_iff)\n\n    show ?thesis\n      apply (rule the_glb_leq)\n      apply (metis Inf_X_set glb_ex)\n      apply safe\n      apply (rule the_glb_geq)\n      apply (metis Sup_subset_mono Union_Pow_eq X_set is_glb_glb)\n      apply (simp add: is_glb_simp)\n      apply safe\n      by (smt Sup_le_iff glb_least imageI order_trans set_rev_mp)\n  qed\n\nend\n\nlemma inv_cms_is_cjs [simp]: \"complete_meet_semilattice (A\\<sharp>) = complete_join_semilattice A\"\n  by (simp add: complete_meet_semilattice_def complete_join_semilattice_def complete_meet_semilattice_axioms_def complete_join_semilattice_axioms_def, safe, simp_all)\n\nlemma inv_cjs_is_cms [simp]: \"complete_join_semilattice (A\\<sharp>) = complete_meet_semilattice A\"\n  by (simp add: complete_meet_semilattice_def complete_join_semilattice_def complete_meet_semilattice_axioms_def complete_join_semilattice_axioms_def, safe, simp_all)\n\nabbreviation top_ext :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a\" (\"\\<top>\\<^bsub>_\\<^esub>\") where\n  \"\\<top>\\<^bsub>A\\<^esub> \\<equiv> complete_meet_semilattice.top A\"\n\nlemma extend_cms: \"complete_meet_semilattice A \\<Longrightarrow> complete_meet_semilattice (\\<up> A)\"\n  by (metis extend_cjs extend_dual inv_cms_is_cjs inv_inv_id)\n\nlemma (in order) is_glb_from_is_lub:\n  \"\\<lbrakk>x \\<in> carrier A; X \\<subseteq> carrier A; is_lub x {b. (\\<forall>a\\<in>X. b \\<sqsubseteq> a) \\<and> b \\<in> carrier A}\\<rbrakk> \\<Longrightarrow> is_glb x X\"\n  by (auto simp add: is_glb_simp is_lub_simp)\n\nlemma (in complete_join_semilattice) is_cms: \"complete_meet_semilattice A\"\nproof\n  fix X assume Xc: \"X \\<subseteq> carrier A\"\n\n  have \"{b. (\\<forall>a\\<in>X. b \\<sqsubseteq> a) \\<and> b \\<in> carrier A} \\<subseteq> carrier A\" by auto\n  then obtain x where \"is_lub x {b. (\\<forall>a\\<in>X. b \\<sqsubseteq> a) \\<and> b \\<in> carrier A}\" and \"x \\<in> carrier A\"\n    by (metis (lifting) lub_ex)\n  hence \"is_glb x X\"\n    by (metis (no_types) Xc is_glb_from_is_lub)\n  thus \"\\<exists>x\\<in>carrier A. is_glb x X\"\n    by (metis `x \\<in> carrier A`)\nqed\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Complete lattices *}\n(* +------------------------------------------------------------------------+ *)\n\nlocale complete_lattice = complete_join_semilattice + complete_meet_semilattice\n\nlemma cl_to_order: \"complete_lattice A \\<Longrightarrow> order A\"\n  by (simp add: complete_lattice_def complete_join_semilattice_def)\n\nlemma cl_to_cjs: \"complete_lattice A \\<Longrightarrow> complete_join_semilattice A\"\n  by (simp add: complete_lattice_def)\n\nlemma cl_to_cms: \"complete_lattice A \\<Longrightarrow> complete_meet_semilattice A\"\n  by (simp add: complete_lattice_def)\n\nlemma inv_complete_lattice [simp]: \"complete_lattice (A\\<sharp>) = complete_lattice A\"\n  by (simp add: complete_lattice_def, auto)\n\nsublocale complete_lattice \\<subseteq> lattice\n  by unfold_locales\n\nlemma cl_to_lattice: \"complete_lattice A \\<Longrightarrow> lattice A\"\n  apply default\n  apply (metis cl_to_order order.order_refl)\n  apply (metis cl_to_order order.order_trans)\n  apply (metis order.order_antisym cl_to_order)\n  apply (metis cl_to_cjs complete_join_semilattice.lub_ex empty_subsetI insert_subset)\n  by (metis cl_to_cms complete_meet_semilattice.glb_ex empty_subsetI insert_subset)\n\nlemma cl_to_js: assumes cl: \"complete_lattice A\" shows \"join_semilattice A\"\nproof -\n  have \"lattice A\" by (metis cl cl_to_lattice)\n  thus ?thesis by (simp add: lattice_def)\nqed\n\nlemma cl_to_ms: assumes cl: \"complete_lattice A\" shows \"meet_semilattice A\"\nproof -\n  have \"lattice A\" by (metis cl cl_to_lattice)\n  thus ?thesis by (simp add: lattice_def)\nqed\n\ncontext complete_lattice\nbegin\n\n  lemma univ_lub: \"\\<Sigma> (carrier A) = \\<top>\"\n    by (metis is_lub_def is_lub_lub is_ub_def prop_top subset_refl top_ax top_closed)\n\n  lemma univ_glb: \"\\<Pi> (carrier A) = \\<bottom>\"\n    by (metis bot_ax bot_closed is_glb_def is_glb_glb is_lb_def prop_bot subset_refl)\n\n  lemma lub_set_leq: \"\\<lbrakk>X \\<subseteq> carrier A; Y \\<subseteq> carrier A; \\<forall>x\\<in>X. \\<exists>y\\<in>Y. x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> \\<Sigma> X \\<sqsubseteq> \\<Sigma> Y\"\n    apply (rule the_lub_leq)\n    apply (metis lub_ex)\n    apply safe\n    apply (rule the_lub_geq)\n    apply (metis lub_ex)\n    apply (simp add: is_lub_simp)\n    apply safe\n    by (metis Un_iff le_iff_sup order_trans)\n\nend\n\nlemma lub_inf_idem_ext:\n  assumes cl_A: \"complete_lattice A\"\n  and X_set: \"X \\<subseteq> Pow (carrier A)\"\n  shows \"\\<Sigma>\\<^bsub>A\\<^esub>((order.lub A) ` X) = \\<Sigma>\\<^bsub>A\\<^esub>(\\<Union> X)\"\nproof -\n  have ord_A: \"order A\"\n    by (metis cl_A cl_to_order)\n\n  have cl_Ash: \"complete_lattice (A\\<sharp>)\"\n    by (metis cl_A inv_complete_lattice)\n\n  have right_closed: \"\\<Sigma>\\<^bsub>A\\<^esub>(\\<Union> X) \\<in> carrier A\"\n    by (metis Sup_subset_mono Union_Pow_eq X_set cl_A cl_to_cjs complete_join_semilattice.lub_ex ord_A order.lub_closed)\n  have left_closed: \"\\<Sigma>\\<^bsub>A\\<^esub>((order.lub A) ` X) \\<in> carrier A\"\n    by (metis (hide_lams, no_types) Sup_le_iff Union_Pow_eq Union_mono X_set cl_Ash cl_to_cms complete_join_semilattice.is_lub_lub image_subsetI inv_cms_is_cjs ord_A order.is_lub_simp)\n\n  have dual: \"\\<Pi>\\<^bsub>A\\<sharp>\\<^esub>(order.glb (A\\<sharp>) ` X) \\<sqsubseteq>\\<^bsub>A\\<sharp>\\<^esub> \\<Pi>\\<^bsub>A\\<sharp>\\<^esub>(\\<Union> X)\"\n    by (metis X_set cl_A cl_to_cjs complete_meet_semilattice.glb_inf_idem_leq inv_carrier_id inv_cms_is_cjs)\n  have \"\\<Sigma>\\<^bsub>A\\<^esub>(\\<Union> X) \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<Sigma>\\<^bsub>A\\<^esub>((order.lub A) ` X)\"\n    by (insert ord_A dual, simp add: image_def)\n  moreover have \"\\<Sigma>\\<^bsub>A\\<^esub>((order.lub A) ` X) \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<Sigma>\\<^bsub>A\\<^esub>(\\<Union> X)\"\n    by (metis X_set cl_A cl_to_cjs complete_join_semilattice.lub_inf_idem_leq)\n  ultimately show ?thesis\n    by (metis order.order_antisym left_closed ord_A right_closed)\nqed\n\nlemma (in complete_lattice) lub_inf_idem: \"X \\<subseteq> Pow (carrier A) \\<Longrightarrow> \\<Sigma> (\\<Sigma> ` X) = \\<Sigma> (\\<Union> X)\"\n  by (rule lub_inf_idem_ext[of A], unfold_locales, simp)\n\nhide_fact lub_inf_idem_ext\n\nlemma glb_inf_idem_ext:\n  assumes cl_A: \"complete_lattice A\"\n  and X_set: \"X \\<subseteq> Pow (carrier A)\"\n  shows \"\\<Pi>\\<^bsub>A\\<^esub>((order.glb A) ` X) = \\<Pi>\\<^bsub>A\\<^esub>(\\<Union> X)\"\nproof -\n  have ord_A: \"order A\"\n    by (metis cl_A cl_to_order)\n\n  have \"\\<Sigma>\\<^bsub>A\\<sharp>\\<^esub>((order.lub (A\\<sharp>)) ` X) = \\<Sigma>\\<^bsub>A\\<sharp>\\<^esub>(\\<Union> X)\"\n    by (rule complete_lattice.lub_inf_idem, simp_all add: X_set cl_A)\n  thus ?thesis using ord_A\n    by (simp add: image_def)\nqed\n\nlemma (in complete_lattice) glb_inf_idem: \"X \\<subseteq> Pow (carrier A) \\<Longrightarrow> \\<Pi> (\\<Pi> ` X) = \\<Pi> (\\<Union> X)\"\n  by (rule glb_inf_idem_ext[of A], unfold_locales, simp)\n\nhide_fact glb_inf_idem_ext\n\ndefinition cl_continuous :: \"('a, 'c) ord_scheme \\<Rightarrow> ('b, 'd) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where\n  \"cl_continuous A B f = (\\<forall>X\\<subseteq>carrier A. complete_lattice \\<lparr>carrier = X, le = op \\<sqsubseteq>\\<^bsub>A\\<^esub>\\<rparr> \\<longrightarrow> order.lub B (f ` X) = f (order.lub A X))\"\n\nlemma glb_in:\n  assumes ord_A: \"order A\" and X_glb: \"\\<exists>x. order.is_glb A x X\"\n  shows \"\\<exists>x\\<in>carrier A. order.is_glb A x X\"\nproof -\n  obtain x where \"order.is_glb A x X\" by (metis X_glb)\n  hence \"x \\<in> carrier A\"\n    by (metis ord_A order.is_glb_simp)\n  thus ?thesis\n    by (metis `order.is_glb A x X`)\nqed\n\nlemma lub_in:\n  assumes ord_A: \"order A\" and X_lub: \"\\<exists>x. order.is_lub A x X\"\n  shows \"\\<exists>x\\<in>carrier A. order.is_lub A x X\"\nproof -\n  obtain x where \"order.is_lub A x X\" by (metis X_lub)\n  hence \"x \\<in> carrier A\"\n    by (metis ord_A order.is_lub_simp)\n  thus ?thesis\n    by (metis `order.is_lub A x X`)\nqed\n\nlemma finite_lattice_is_complete: \"\\<lbrakk>finite (carrier A); carrier A \\<noteq> {}; lattice A\\<rbrakk> \\<Longrightarrow> complete_lattice A\"\n  apply (simp add: complete_lattice_def complete_meet_semilattice_def complete_join_semilattice_def)\n  apply (simp add: complete_join_semilattice_axioms_def complete_meet_semilattice_axioms_def)\n  apply safe\n  prefer 3\n  apply (simp add: lattice_def join_semilattice_def)\n  apply (simp add: lattice_def join_semilattice_def)\n  apply (rule lub_in)\n  apply (simp add: lattice_def join_semilattice_def)\n  apply (metis lattice.finite_lub_carrier)\n  apply (rule glb_in)\n  apply (simp add: lattice_def join_semilattice_def)\n  by (metis lattice.finite_glb_carrier)\n\nlemma extend_cl: \"complete_lattice A \\<Longrightarrow> complete_lattice (\\<up> A)\"\n  by (simp add: complete_lattice_def extend_cjs extend_cms)\n\nlocale complete_boolean_lattice = complete_lattice + distributive_lattice +\n  assumes ccompl_ex: \"x \\<in> carrier A \\<Longrightarrow> \\<exists>y. y \\<in> carrier A \\<and> x \\<squnion> y = \\<top> \\<and> x \\<sqinter> y = \\<bottom>\"\n\nbegin\n\n  lemma ccompl_uniq:\n    assumes xc: \"x \\<in> carrier A\"\n    shows \"\\<exists>!y. y \\<in> carrier A \\<and> x \\<squnion> y = \\<top> \\<and> x \\<sqinter> y = \\<bottom>\"\n    apply safe\n    apply (metis assms ccompl_ex)\n    by (metis (lifting) assms dist1 meet_comm top_oner)\n\n  definition ccompl :: \"'a \\<Rightarrow> 'a\" (\"!\") where\n    \"! x = (THE y. y \\<in> carrier A \\<and> x \\<squnion> y = \\<top> \\<and> x \\<sqinter> y = \\<bottom>)\"\n\n  lemma ccompl_closed: \"x \\<in> carrier A \\<Longrightarrow> ! x \\<in> carrier A\"\n    by (simp add: ccompl_def, rule the1I2, (smt ccompl_uniq)+)\n\n  lemma ccompl_top: \"x \\<in> carrier A \\<Longrightarrow> x \\<squnion> ! x = \\<top>\"\n    apply (simp add: ccompl_def)\n    apply (rule the1I2)\n    apply (metis (lifting) ccompl_uniq)\n    by auto\n\n  lemma ccompl_bot: \"x \\<in> carrier A \\<Longrightarrow> x \\<sqinter> ! x = \\<bottom>\"\n    apply (simp add: ccompl_def)\n    apply (rule the1I2)\n    apply (metis (lifting) ccompl_uniq)\n    by auto\n\nend\n\nabbreviation ccompl_ext :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"!\\<^bsub>_\\<^esub>\") where\n  \"!\\<^bsub>A\\<^esub> x \\<equiv> complete_boolean_lattice.ccompl A x\"\n\nlemma extend_cbl:\n  assumes cbl_A: \"complete_boolean_lattice A\"\n  shows \"complete_boolean_lattice (\\<up> A)\"\nproof (simp add: complete_boolean_lattice_def complete_boolean_lattice_axioms_def, safe)\n  have \"complete_lattice A\"\n    by (insert cbl_A, simp add: complete_boolean_lattice_def)\n  thus \"complete_lattice (\\<up> A)\"\n    by (metis extend_cl)\n  hence cms_A_ex: \"complete_meet_semilattice (\\<up> A)\"\n    by (metis cl_to_cms)\n  from `complete_lattice (\\<up> A)` have cjs_A_ex: \"complete_join_semilattice (\\<up> A)\"\n    by (metis cl_to_cjs)\n  have \"distributive_lattice A\"\n    by (insert cbl_A, simp add: complete_boolean_lattice_def)\n  thus \"distributive_lattice (\\<up> A)\"\n    by (metis extend_distributive)\n  have js_A: \"join_semilattice A\"\n    by (metis `complete_lattice A` cl_to_js)\n  have ms_A: \"meet_semilattice A\"\n    by (metis `complete_lattice A` cl_to_ms)\n\n  let ?INV = \"(\\<lambda>f x. !\\<^bsub>A\\<^esub> (f x))\"\n\n  fix f assume fc: \"f \\<in> carrier (\\<up> A)\"\n\n  hence ifc: \"?INV f \\<in> carrier (\\<up> A)\"\n    apply (simp add: pointwise_extension_def)\n    by (smt assms complete_boolean_lattice.ccompl_closed ftype_pred)\n\n  moreover have \"f \\<squnion>\\<^bsub>\\<up> A\\<^esub> ?INV f = \\<top>\\<^bsub>\\<up> A\\<^esub>\"\n    apply (simp add: extend_join[OF js_A fc ifc])\n    apply (rule sym)\n    apply default\n  proof -\n    fix x :: 'c\n    have fxc: \"f x \\<in> carrier A\"\n      apply (insert fc, simp add: pointwise_extension_def)\n      by (metis UNIV_I ftype_pred)\n    show \"\\<top>\\<^bsub>\\<up> A\\<^esub> x = f x \\<squnion>\\<^bsub>A\\<^esub> !\\<^bsub>A\\<^esub> (f x)\"\n      apply (simp add: complete_boolean_lattice.ccompl_top[OF cbl_A fxc])\n      apply (simp add: complete_meet_semilattice.top_def[OF cms_A_ex])\n      apply (rule_tac P = \"\\<lambda>x. x \\<in> carrier (\\<up> A) \\<and> (\\<forall>y\\<in>carrier (\\<up> A). y \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> x)\" in the1I2)\n      apply (metis (no_types) cms_A_ex complete_meet_semilattice.top_ax)\n    proof safe\n      fix g :: \"'c \\<Rightarrow> 'a\" assume gc: \"g \\<in> carrier (\\<up> A)\" and g_top: \"\\<forall>h\\<in>carrier (\\<up> A). h \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> g\"\n      have \"(\\<lambda>x. \\<top>\\<^bsub>A\\<^esub>) \\<in> carrier (\\<up> A)\"\n        apply (simp add: pointwise_extension_def)\n        by (metis `complete_lattice A` cl_to_cms complete_meet_semilattice.top_closed ftype_pred)\n      hence \"(\\<lambda>x. \\<top>\\<^bsub>A\\<^esub>) \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> g\"\n        by (metis g_top)\n      hence \"(\\<lambda>x. \\<top>\\<^bsub>A\\<^esub>) = g\"\n        apply (simp add: pointwise_extension_def)\n        apply (rule sym)\n        apply default\n      proof -\n        fix y assume \"\\<forall>x. \\<top>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> g x\"\n        hence \"\\<top>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> g y\"\n          by metis\n        moreover have \"g y \\<in> carrier A\"\n          apply (insert gc, simp add: pointwise_extension_def)\n          by (metis UNIV_I ftype_pred)\n        ultimately show \"g y = \\<top>\\<^bsub>A\\<^esub>\"\n          by (metis `complete_lattice A` cl_to_cms cl_to_order complete_meet_semilattice.prop_top complete_meet_semilattice.top_closed order.order_antisym)\n      qed\n      thus \"g x = \\<top>\\<^bsub>A\\<^esub>\" by auto\n    qed\n  qed\n\n  moreover have \"f \\<sqinter>\\<^bsub>\\<up> A\\<^esub> ?INV f = \\<bottom>\\<^bsub>\\<up> A\\<^esub>\"\n    apply (simp add: extend_meet[OF ms_A fc ifc])\n    apply (rule sym)\n    apply default\n  proof -\n    fix x :: 'c\n    have fxc: \"f x \\<in> carrier A\"\n      apply (insert fc, simp add: pointwise_extension_def)\n      by (metis UNIV_I ftype_pred)\n    show \"\\<bottom>\\<^bsub>\\<up> A\\<^esub> x = f x \\<sqinter>\\<^bsub>A\\<^esub> !\\<^bsub>A\\<^esub> (f x)\"\n      apply (simp add: complete_boolean_lattice.ccompl_bot[OF cbl_A fxc])\n      apply (simp add: complete_join_semilattice.bot_def[OF cjs_A_ex])\n      apply (rule_tac P = \"\\<lambda>x. x \\<in> carrier (\\<up> A) \\<and> (\\<forall>y\\<in>carrier (\\<up> A). x \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> y)\" in the1I2)\n      apply (metis (no_types) cjs_A_ex complete_join_semilattice.bot_ax)\n    proof safe\n      fix g :: \"'c \\<Rightarrow> 'a\" assume gc: \"g \\<in> carrier (\\<up> A)\" and g_bot: \"\\<forall>h\\<in>carrier (\\<up> A). g \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> h\"\n      have \"(\\<lambda>x. \\<bottom>\\<^bsub>A\\<^esub>) \\<in> carrier (\\<up> A)\"\n        apply (simp add: pointwise_extension_def)\n        by (metis `complete_lattice A` cl_to_cjs complete_join_semilattice.bot_closed ftype_pred)\n      hence \"g \\<sqsubseteq>\\<^bsub>\\<up> A\\<^esub> (\\<lambda>x. \\<bottom>\\<^bsub>A\\<^esub>) \"\n        by (metis g_bot)\n      hence \"(\\<lambda>x. \\<bottom>\\<^bsub>A\\<^esub>) = g\"\n        apply (simp add: pointwise_extension_def)\n        apply (rule sym)\n        apply default\n      proof -\n        fix y assume \"\\<forall>x. g x \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<bottom>\\<^bsub>A\\<^esub>\"\n        hence \"g y \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<bottom>\\<^bsub>A\\<^esub>\"\n          by metis\n        moreover have \"g y \\<in> carrier A\"\n          apply (insert gc, simp add: pointwise_extension_def)\n          by (metis UNIV_I ftype_pred)\n        ultimately show \"g y = \\<bottom>\\<^bsub>A\\<^esub>\"\n          by (metis `complete_lattice A` cl_to_cjs cl_to_order complete_join_semilattice.prop_bot complete_join_semilattice.bot_closed order.order_antisym)\n      qed\n      thus \"g x = \\<bottom>\\<^bsub>A\\<^esub>\" by auto\n    qed\n  qed\n\n  ultimately show \"\\<exists>y. y \\<in> carrier (\\<up> A) \\<and> f \\<squnion>\\<^bsub>\\<up> A\\<^esub> y = \\<top>\\<^bsub>\\<up> A\\<^esub> \\<and> f \\<sqinter>\\<^bsub>\\<up> A\\<^esub> y = \\<bottom>\\<^bsub>\\<up> A\\<^esub>\"\n    by metis\nqed\n\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Boolean algebra of booleans *}\n(* +------------------------------------------------------------------------+ *)\n\ndefinition BOOL :: \"bool ord\" where\n  \"BOOL = \\<lparr>carrier = {True, False}, le = op \\<longrightarrow>\\<rparr>\"\n\nlemma bool_ord: \"order BOOL\"\n  by (default, simp_all add: BOOL_def, auto)\n\nlemma bool_js: \"join_semilattice BOOL\"\n  apply (simp add: join_semilattice_def join_semilattice_axioms_def)\n  apply safe\n  apply (metis bool_ord)\n  apply (simp add: order.is_lub_simp[OF bool_ord])\n  apply (simp add: BOOL_def)\n  by metis\n\nlemma bool_ms: \"meet_semilattice BOOL\"\n  apply (simp add: meet_semilattice_def meet_semilattice_axioms_def)\n  apply safe\n  apply (metis bool_ord)\n  apply (simp add: order.is_glb_simp[OF bool_ord])\n  apply (simp add: BOOL_def)\n  by metis\n\nlemma bool_lattice: \"lattice BOOL\"\n  by (simp add: lattice_def bool_ms bool_js)\n\nlemma bool_cl: \"complete_lattice BOOL\"\n  apply (rule finite_lattice_is_complete)\n  apply (metis finite_code)\n  apply (simp add: BOOL_def)\n  by (metis bool_lattice)\n\nlemma bool_cjs: \"complete_join_semilattice BOOL\"\n  by (metis bool_cl cl_to_cjs)\n\nlemma bool_cms: \"complete_meet_semilattice BOOL\"\n  by (metis bool_cl cl_to_cms)\n\nlemma bool_meet: \"x \\<squnion>\\<^bsub>BOOL\\<^esub> y \\<longleftrightarrow> x \\<or> y\"\n  apply (simp add: order.join_def[OF bool_ord] order.lub_simp[OF bool_ord])\n  apply (simp add: BOOL_def)\n  by (smt the_equality)\n\nlemma bool_join: \"x \\<sqinter>\\<^bsub>BOOL\\<^esub> y \\<longleftrightarrow> x \\<and> y\"\n  apply (simp add: order.meet_def[OF bool_ord] order.glb_simp[OF bool_ord])\n  apply (simp add: BOOL_def)\n  by (smt the_equality)\n\nlemma bool_distributive: \"distributive_lattice BOOL\"\n  apply (simp add: distributive_lattice_def distributive_lattice_axioms_def)\n  apply safe\n  apply (metis bool_lattice)\n  apply (simp_all add: bool_join bool_meet)\n  by auto+\n\nlemma bool_total: \"total_order BOOL\"\n  apply (simp add: total_order_def total_order_axioms_def)\n  apply safe\n  apply (metis bool_ord)\n  by (simp add: BOOL_def)\n\nlemma bool_top: \"complete_meet_semilattice.top BOOL = True\"\n  apply (simp add: complete_meet_semilattice.top_def[OF bool_cms])\n  apply (simp add: BOOL_def)\n  apply (rule the1I2)\n  by auto+\n\nlemma bool_bot: \"complete_join_semilattice.bot BOOL = False\"\n  apply (simp add: complete_join_semilattice.bot_def[OF bool_cjs])\n  apply (simp add: BOOL_def)\n  apply (rule the1I2)\n  by auto+\n\nlemma bool_cbl: \"complete_boolean_lattice BOOL\"\n  apply (simp add: complete_boolean_lattice_def complete_boolean_lattice_axioms_def)\n  apply safe\n  apply (metis bool_cl)\n  apply (metis bool_distributive)\n  apply (simp add: bool_top bool_bot bool_join bool_meet)\n  apply (simp add: BOOL_def)\n  by auto\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Fixed points *}\n(* +------------------------------------------------------------------------+ *)\n\ndefinition is_pre_fp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_pre_fp A x f \\<equiv> order A \\<and> f \\<in> carrier A \\<rightarrow> carrier A \\<and> x \\<in> carrier A \\<and> f x \\<sqsubseteq>\\<^bsub>A\\<^esub> x\"\n\ndefinition is_post_fp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_post_fp A x f \\<equiv> order A \\<and> f \\<in> carrier A \\<rightarrow> carrier A \\<and> x \\<in> carrier A \\<and> x \\<sqsubseteq>\\<^bsub>A\\<^esub> f x\"\n\nlemma is_pre_fp_dual [simp]: \"is_pre_fp (A\\<sharp>) x f = is_post_fp A x f\"\n  by (simp add: is_pre_fp_def is_post_fp_def)\n\nlemma is_post_fp_dual [simp]: \"is_post_fp (A\\<sharp>) x f = is_pre_fp A x f\"\n  by (simp add: is_pre_fp_def is_post_fp_def)\n\ndefinition is_fp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_fp A x f \\<equiv> order A \\<and> f \\<in> carrier A \\<rightarrow> carrier A \\<and> x \\<in> carrier A \\<and> f x = x\"\n\nlemma is_fp_dual [simp]: \"is_fp (A\\<sharp>) x f = is_fp A x f\"\n  by (simp add: is_fp_def)\n\nlemma is_fp_def_var: \"is_fp A x f = (is_pre_fp A x f \\<and> is_post_fp A x f)\"\n  by (simp add: is_fp_def is_pre_fp_def is_post_fp_def, metis order.order_antisym typed_application order.order_refl)\n\ndefinition is_lpp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lpp A x f \\<equiv> (is_pre_fp A x f) \\<and> (\\<forall>y\\<in>carrier A. f y \\<sqsubseteq>\\<^bsub>A\\<^esub> y \\<longrightarrow> x \\<sqsubseteq>\\<^bsub>A\\<^esub> y)\"\n\ndefinition is_gpp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gpp A x f \\<equiv> (is_post_fp A x f) \\<and> (\\<forall>y\\<in>carrier A. y \\<sqsubseteq>\\<^bsub>A\\<^esub> f y \\<longrightarrow> y \\<sqsubseteq>\\<^bsub>A\\<^esub> x)\"\n\nlemma is_lpp_dual [simp]: \"is_lpp (A\\<sharp>) x f = is_gpp A x f\"\n  by (simp add: is_gpp_def is_lpp_def)\n\nlemma is_gpp_dual [simp]: \"is_gpp (A\\<sharp>) x f = is_lpp A x f\"\n  by (simp add: is_lpp_def is_gpp_def)\n\ndefinition is_lfp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lfp A x f \\<equiv> is_fp A x f \\<and> (\\<forall>y\\<in>carrier A. is_fp A y f \\<longrightarrow> x \\<sqsubseteq>\\<^bsub>A\\<^esub> y)\"\n\nlemma is_lfp_closed: \"is_lfp A x f \\<Longrightarrow> f \\<in> carrier A \\<rightarrow> carrier A\"\n  by (metis (no_types) is_fp_def is_lfp_def)\n\ndefinition is_gfp :: \"('a, 'b) ord_scheme \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gfp A x f \\<equiv> is_fp A x f \\<and> (\\<forall>y\\<in>carrier A. is_fp A y f \\<longrightarrow> y \\<sqsubseteq>\\<^bsub>A\\<^esub> x)\"\n\nlemma is_gfp_closed: \"is_gfp A x f \\<Longrightarrow> f \\<in> carrier A \\<rightarrow> carrier A\"\n  by (metis (no_types) is_fp_def is_gfp_def)\n\nlemma is_lfp_dual [simp]: \"is_lfp (A\\<sharp>) x f = is_gfp A x f\"\n  by (simp add: is_lfp_def is_gfp_def)\n\nlemma is_gfp_dual [simp]: \"is_gfp (A\\<sharp>) x f = is_lfp A x f\"\n  by (simp add: is_gfp_def is_lfp_def)\n\ndefinition least_prefix_point :: \"'a ord \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<mu>\\<^bsub>\\<le>_\\<^esub>_\" [0,1000] 100) where\n  \"least_prefix_point A f \\<equiv> THE x. is_lpp A x f\"\n\ndefinition greatest_postfix_point :: \"'a ord \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<nu>\\<^bsub>\\<le>_\\<^esub>_\" [0,1000] 100) where\n  \"greatest_postfix_point A f \\<equiv> THE x. is_gpp A x f\"\n\nlemma least_prefix_point_dual [simp]: \"\\<mu>\\<^bsub>\\<le>(A\\<sharp>)\\<^esub>f = \\<nu>\\<^bsub>\\<le>A\\<^esub>f\"\n  by (simp add: least_prefix_point_def greatest_postfix_point_def)\n\nlemma greatest_postfix_point_dual [simp]: \"\\<nu>\\<^bsub>\\<le>(A\\<sharp>)\\<^esub>f = \\<mu>\\<^bsub>\\<le>A\\<^esub>f\"\n  by (simp add: least_prefix_point_def greatest_postfix_point_def)\n\ndefinition least_fixpoint :: \"('a, 'b) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<mu>\\<^bsub>_\\<^esub>_\" [0,1000] 100) where\n  \"least_fixpoint A f \\<equiv> THE x. is_lfp A x f\"\n\ndefinition greatest_fixpoint :: \"('a, 'b) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<nu>\\<^bsub>_\\<^esub>_\" [0,1000] 100) where\n  \"greatest_fixpoint A f \\<equiv> THE x. is_gfp A x f\"\n\nlemma least_fixpoint_dual [simp]: \"\\<mu>\\<^bsub>(A\\<sharp>)\\<^esub>f = \\<nu>\\<^bsub>A\\<^esub>f\"\n  by (simp add: least_fixpoint_def greatest_fixpoint_def)\n\nlemma greatest_fixpoint_dual [simp]: \"\\<nu>\\<^bsub>(A\\<sharp>)\\<^esub>f = \\<mu>\\<^bsub>A\\<^esub>f\"\n  by (simp add: least_fixpoint_def greatest_fixpoint_def)\n\nlemma lpp_unique: \"\\<lbrakk>is_lpp A x f; is_lpp A y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (smt order.order_antisym is_lpp_def is_pre_fp_def)\n\nlemma gpp_unique: \"\\<lbrakk>is_gpp A x f; is_gpp A y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (smt order.order_antisym is_gpp_def is_post_fp_def)\n\nlemma lpp_equality [intro?]: \"is_lpp A x f \\<Longrightarrow> \\<mu>\\<^bsub>\\<le>A\\<^esub> f = x\"\n  by (simp add: least_prefix_point_def, rule the_equality, auto, smt order.order_antisym is_lpp_def is_pre_fp_def)\n\nlemma gpp_equality [intro?]: \"is_gpp A x f \\<Longrightarrow> \\<nu>\\<^bsub>\\<le>A\\<^esub> f = x\"\n  by (simp add: greatest_postfix_point_def, rule the_equality, auto, smt order.order_antisym is_gpp_def is_post_fp_def)\n\nlemma lfp_equality: \"is_lfp A x f \\<Longrightarrow> \\<mu>\\<^bsub>A\\<^esub> f = x\"\n  by (simp add: least_fixpoint_def, rule the_equality, auto, smt order.order_antisym is_fp_def is_lfp_def)\n\nlemma lfp_equality_var [intro?]: \"\\<lbrakk>order A; f \\<in> carrier A \\<rightarrow> carrier A; x \\<in> carrier A; f x = x; \\<forall>y \\<in> carrier A. f y = y \\<longrightarrow> x \\<sqsubseteq>\\<^bsub>A\\<^esub> y\\<rbrakk> \\<Longrightarrow> x = \\<mu>\\<^bsub>A\\<^esub> f\"\n  by (smt is_fp_def is_lfp_def lfp_equality)\n\nlemma gfp_equality: \"is_gfp A x f \\<Longrightarrow> \\<nu>\\<^bsub>A\\<^esub> f = x\"\n  by (simp add: greatest_fixpoint_def, rule the_equality, auto, smt order.order_antisym is_gfp_def is_fp_def)\n\nlemma gfp_equality_var [intro?]: \"\\<lbrakk>order A; f \\<in> carrier A \\<rightarrow> carrier A; x \\<in> carrier A; f x = x; \\<forall>y \\<in> carrier A. f y = y \\<longrightarrow> y \\<sqsubseteq>\\<^bsub>A\\<^esub> x\\<rbrakk> \\<Longrightarrow> x = \\<nu>\\<^bsub>A\\<^esub> f\"\n  by (smt gfp_equality is_fp_def is_gfp_def)\n\nlemma lpp_is_lfp: \"\\<lbrakk>isotone A A f; is_lpp A x f\\<rbrakk> \\<Longrightarrow> is_lfp A x f\"\n  by (simp add: isotone_def is_lpp_def is_pre_fp_def is_lfp_def is_fp_def, metis order.order_antisym order.order_refl typed_application)\n\nlemma gpp_is_gfp: \"\\<lbrakk>isotone A A f; is_gpp A x f\\<rbrakk> \\<Longrightarrow> is_gfp A x f\"\n  by (simp add: isotone_def is_gpp_def is_post_fp_def is_gfp_def is_fp_def, smt order.order_antisym order.order_refl typed_application)\n\nlemma least_fixpoint_set: \"\\<lbrakk>\\<exists>x. is_lfp A x f\\<rbrakk> \\<Longrightarrow> \\<mu>\\<^bsub>A\\<^esub> f \\<in> carrier A\"\n  by (simp add: least_fixpoint_def, rule the1I2, metis lfp_equality, metis is_lfp_def is_fp_def)\n\nlemma greatest_fixpoint_set: \"\\<lbrakk>\\<exists>x. is_gfp A x f\\<rbrakk> \\<Longrightarrow> \\<nu>\\<^bsub>A\\<^esub> f \\<in> carrier A\"\n  by (unfold is_lfp_dual[symmetric] least_fixpoint_dual[symmetric], metis inv_carrier_id least_fixpoint_set)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* The Knaster-Tarski theorem *}\n(* +------------------------------------------------------------------------+ *)\n\nsubsubsection {* For least fixed points *}\n\ntheorem knaster_tarski_lpp:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"\\<exists>!x. is_lpp A x f\"\nproof\n  let ?H = \"{u. f u \\<sqsubseteq>\\<^bsub>A\\<^esub> u \\<and> u \\<in> carrier A}\"\n  let ?a = \"\\<Pi>\\<^bsub>A\\<^esub>?H\"\n\n  have H_carrier: \"?H \\<subseteq> carrier A\" by (metis (lifting) mem_Collect_eq subsetI)\n  hence a_carrier: \"?a \\<in> carrier A\"\n    by (smt order.glb_closed complete_meet_semilattice.is_glb_glb cl_A cl_to_cms cl_to_order)\n\n  have \"is_pre_fp A ?a f\"\n  proof -\n    have \"\\<forall>x\\<in>?H. ?a \\<sqsubseteq>\\<^bsub>A\\<^esub> x\" by (smt H_carrier complete_meet_semilattice.glb_least cl_A cl_to_cms)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<sqsubseteq>\\<^bsub>A\\<^esub> f x\" by (safe, rule_tac ?f = f in use_iso1, metis f_iso, metis a_carrier, auto)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<sqsubseteq>\\<^bsub>A\\<^esub> x\" by (smt CollectD a_carrier cl_A cl_to_order typed_application f_closed order.order_trans)\n    hence \"f ?a \\<sqsubseteq>\\<^bsub>A\\<^esub> ?a\" by (smt complete_meet_semilattice.glb_greatest cl_A cl_to_cms a_carrier f_closed H_carrier typed_application)\n    thus ?thesis by (smt a_carrier cl_A cl_to_order f_closed is_pre_fp_def)\n  qed\n  moreover show \"\\<And>x\\<Colon>'a. is_lpp A x f \\<Longrightarrow> x = ?a\"\n    by (smt H_carrier calculation cl_A cl_to_cms complete_meet_semilattice.glb_least is_lpp_def lpp_unique mem_Collect_eq)\n  ultimately show \"is_lpp A ?a f\"\n    by (smt H_carrier cl_A cl_to_cms complete_meet_semilattice.glb_least is_lpp_def mem_Collect_eq)\nqed\n\ncorollary is_lpp_lpp [intro?]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> is_lpp A (\\<mu>\\<^bsub>\\<le>A\\<^esub> f) f\"\n  by (smt knaster_tarski_lpp lpp_equality)\n\ntheorem knaster_tarski:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> \\<exists>!x. is_lfp A x f\"\n  by (metis knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\ncorollary is_lfp_lfp [intro?]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> is_lfp A (\\<mu>\\<^bsub>A\\<^esub> f) f\"\n  by (smt knaster_tarski lfp_equality)\n\nsubsubsection {* For greatest fixed points *}\n\ntheorem knaster_tarski_gpp:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"\\<exists>!x. is_gpp A x f\"\nproof -\n  have dual: \"\\<lbrakk>complete_lattice (A\\<sharp>); f \\<in> carrier (A\\<sharp>) \\<rightarrow> carrier (A\\<sharp>); isotone (A\\<sharp>) (A\\<sharp>) f\\<rbrakk> \\<Longrightarrow> \\<exists>!x. is_lpp (A\\<sharp>) x f\"\n    by (smt knaster_tarski_lpp)\n  thus ?thesis by (simp, metis cl_A f_closed f_iso)\nqed\n\ncorollary is_gpp_gpp [intro?]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> is_gpp A (\\<nu>\\<^bsub>\\<le>A\\<^esub> f) f\"\n  by (smt knaster_tarski_gpp gpp_equality)\n\ntheorem knaster_tarski_greatest:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> \\<exists>!x. is_gfp A x f\"\n  by (metis gfp_equality gpp_is_gfp knaster_tarski_gpp)\n\ncorollary is_gfp_gfp [intro?]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> is_gfp A (\\<nu>\\<^bsub>A\\<^esub> f) f\"\n  by (smt knaster_tarski_greatest gfp_equality)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Fixpoint computation *}\n(* +------------------------------------------------------------------------+ *)\n\nlemma prefix_point_computation [simp]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> f (\\<mu>\\<^bsub>\\<le>A\\<^esub> f) = \\<mu>\\<^bsub>\\<le>A\\<^esub> f\"\n  by (smt is_fp_def is_lfp_def is_lpp_lpp lpp_is_lfp)\n\nlemma fixpoint_computation [simp]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> f (\\<mu>\\<^bsub>A\\<^esub> f) = \\<mu>\\<^bsub>A\\<^esub> f\"\n  by (metis is_fp_def is_lfp_def is_lfp_lfp)\n\nlemma greatest_postfix_point_computation [simp]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> f (\\<nu>\\<^bsub>\\<le>A\\<^esub> f) = \\<nu>\\<^bsub>\\<le>A\\<^esub> f\"\n  by (smt is_gpp_gpp gpp_is_gfp is_gfp_def is_fp_def)\n\nlemma greatest_fixpoint_computation [simp]:\n  \"\\<lbrakk>complete_lattice A; f \\<in> carrier A \\<rightarrow> carrier A; isotone A A f\\<rbrakk> \\<Longrightarrow> f (\\<nu>\\<^bsub>A\\<^esub> f) = \\<nu>\\<^bsub>A\\<^esub> f\"\n  by (metis is_fp_def is_gfp_def is_gfp_gfp)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Fixpoint induction *}\n(* +------------------------------------------------------------------------+ *)\n\nlemma prefix_point_induction [intro?]:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and x_carrier: \"x \\<in> carrier A\" and f_iso: \"isotone A A f\"\n  and pp: \"f x \\<sqsubseteq>\\<^bsub>A\\<^esub> x\" shows \"\\<mu>\\<^bsub>\\<le>A\\<^esub> f \\<sqsubseteq>\\<^bsub>A\\<^esub> x\"\n  by (smt f_closed f_iso cl_A is_lpp_def is_lpp_lpp pp x_carrier)\n\nlemma fixpoint_induction [intro?]:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and x_carrier: \"x \\<in> carrier A\" and f_iso: \"isotone A A f\"\n  and fp: \"f x \\<sqsubseteq>\\<^bsub>A\\<^esub> x\" shows \"\\<mu>\\<^bsub>A\\<^esub> f \\<sqsubseteq>\\<^bsub>A\\<^esub> x\"\n  by (metis cl_A f_closed f_iso fp is_lpp_def knaster_tarski_lpp lfp_equality lpp_is_lfp x_carrier)\n\nlemma greatest_postfix_point_induction [intro?]:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and x_carrier: \"x \\<in> carrier A\" and f_iso: \"isotone A A f\"\n  and pp: \"x \\<sqsubseteq>\\<^bsub>A\\<^esub> f x\" shows \"x \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<nu>\\<^bsub>\\<le>A\\<^esub> f\"\n  by (smt f_closed f_iso is_gpp_def is_gpp_gpp pp x_carrier cl_A)\n\nlemma greatest_fixpoint_induction [intro?]:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and x_carrier: \"x \\<in> carrier A\" and f_iso: \"isotone A A f\"\n  and fp: \"x \\<sqsubseteq>\\<^bsub>A\\<^esub> f x\" shows \"x \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<nu>\\<^bsub>A\\<^esub> f\"\n  by (smt f_closed f_iso fp gfp_equality gpp_is_gfp is_gpp_def knaster_tarski_gpp x_carrier cl_A)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Other simple fixpoint theorems *}\n(* +------------------------------------------------------------------------+ *)\n\nlemma fixpoint_compose:\n  assumes f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and g_closed: \"g \\<in> carrier A \\<rightarrow> carrier A\"\n  and k_closed: \"k \\<in> carrier A \\<rightarrow> carrier A\"\n  and x_carrier: \"x \\<in> carrier A\" and k_iso: \"isotone A A k\"\n  and comp: \"g\\<circ>k = k\\<circ>h\" and fp: \"is_fp A x h\"\n  shows \"is_fp A (k x) g\"\n  using fp and comp by (simp add: is_fp_def o_def, safe, (metis g_closed k_closed typed_application)+)\n\nlemma fixpoint_iso:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\" and g_closed: \"g \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\" and g_iso: \"isotone A A g\"\n  and fg: \"\\<forall>x\\<in>carrier A. f x \\<sqsubseteq>\\<^bsub>A\\<^esub> g x\" shows \"\\<mu>\\<^bsub>A\\<^esub> f \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<mu>\\<^bsub>A\\<^esub> g\"\n  by (smt f_closed f_iso fg fixpoint_computation g_closed g_iso is_lpp_def is_pre_fp_def knaster_tarski_lpp lfp_equality lpp_is_lfp cl_A)\n\nlemma greatest_fixpoint_iso:\n  assumes cl_A: \"complete_lattice A\" and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and g_closed: \"g \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  and g_iso: \"isotone A A g\"\n  and fg: \"\\<forall>x\\<in>carrier A. f x \\<sqsubseteq>\\<^bsub>A\\<^esub> g x\" shows \"\\<nu>\\<^bsub>A\\<^esub> f \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<nu>\\<^bsub>A\\<^esub> g\"\n  by (smt f_closed f_iso fg g_closed g_iso gfp_equality gpp_is_gfp greatest_fixpoint_computation is_gpp_def is_post_fp_def knaster_tarski_gpp cl_A)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Iterated functions *}\n(* +------------------------------------------------------------------------+ *)\n\nprimrec iter :: \"nat \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"iter 0 f x = x\"\n| \"iter (Suc n) f x = f (iter n f x)\"\n\nlemma iter_closed: \"f \\<in> A \\<rightarrow> A \\<Longrightarrow> iter n f \\<in> A \\<rightarrow> A\"\nproof (induct n)\n  case 0 show ?case\n    by (metis (lifting) Lattice.iter.simps(1) ftype_pred)\n  case (Suc m) show ?case\n    by (metis (lifting, full_types) \"0\" Lattice.iter.simps(2) Suc.hyps ftype_pred)\nqed\n\nlemma iter_pointfree: \"iter (Suc n) f = f \\<circ> iter n f\"\n  by (simp add: o_def, metis Lattice.iter.simps(2))\n\nlemma iter_iso:\n  assumes f_type: \"f \\<in> carrier A \\<rightarrow> carrier A\" and f_iso: \"isotone A A f\"\n  shows \"isotone A A (iter n f)\"\n  apply (induct n)\n  apply (metis (lifting) Lattice.iter.simps(1) isotone_def f_iso)\n  apply (simp only: iter_pointfree)\n  apply (rule_tac B = A in iso_compose)\n  apply (metis f_type iter_closed)\n  apply metis\n  apply (metis f_type)\n  by (metis f_iso)\n\nlemma iter_inc:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter (Suc n) f \\<bottom>\\<^bsub>A\\<^esub>\"\nproof (induct n)\n  case 0 show ?case\n    by (simp add: iter_def, metis cl_A cl_to_cjs complete_join_semilattice.bot_closed complete_join_semilattice.prop_bot f_closed ftype_pred)\n  case (Suc m) fix n assume ind_hyp: \"iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter (Suc n) f \\<bottom>\\<^bsub>A\\<^esub>\"\n  hence \"f (iter n f \\<bottom>\\<^bsub>A\\<^esub>) \\<sqsubseteq>\\<^bsub>A\\<^esub> f (iter (Suc n) f \\<bottom>\\<^bsub>A\\<^esub>)\"\n    by (metis (full_types) cl_A cl_to_cjs complete_join_semilattice.bot_closed f_closed f_iso ftype_pred isotone_def iter_closed)\n  thus \"iter (Suc n) f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter (Suc (Suc n)) f \\<bottom>\\<^bsub>A\\<^esub>\"\n    by (metis Lattice.iter.simps(2))\nqed\n\nlemma iter_zero_pointfree [simp]: \"iter 0 f = id\"\n  by (simp add: iter_def id_def)\n\nlemma iter_add: \"iter (n+m) f = iter n f \\<circ> iter m f\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  fix n assume ind_hyp: \"iter (n + m) f = iter n f \\<circ> iter m f\"\n  thus \"iter (Suc n + m) f = iter (Suc n) f \\<circ> iter m f\"\n    by (simp add: iter_pointfree ind_hyp o_assoc)\nqed\n\nlemma iter_add_point: \"\\<forall>x. iter (n+m) f x = iter n f (iter m f x)\"\n  by (metis iter_add o_apply)\n\nlemma iter_chain:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  and nm: \"n \\<le> m\" shows \"iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter m f \\<bottom>\\<^bsub>A\\<^esub>\"\nproof -\n  let ?k = \"m - n\"\n  have \"iter n f (iter 0 f \\<bottom>\\<^bsub>A\\<^esub>) \\<sqsubseteq>\\<^bsub>A\\<^esub> iter n f (iter ?k f \\<bottom>\\<^bsub>A\\<^esub>)\"\n  proof (rule_tac f = \"iter n f\" in use_iso1)\n    show \"isotone A A (iter n f)\"\n      by (metis f_closed f_iso iter_iso)\n    show \"iter 0 f \\<bottom>\\<^bsub>A\\<^esub> \\<in> carrier A\"\n      by (metis Lattice.iter.simps(1) cl_A cl_to_cjs complete_join_semilattice.bot_closed)\n    show \"iter ?k f \\<bottom>\\<^bsub>A\\<^esub> \\<in> carrier A\"\n      by (metis Lattice.iter.simps(1) `iter 0 f \\<bottom>\\<^bsub>A\\<^esub> \\<in> carrier A` f_closed ftype_pred iter_closed)\n    show \"iter 0 f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter ?k f \\<bottom>\\<^bsub>A\\<^esub>\"\n      by (metis Lattice.iter.simps(1) cl_A cl_to_cjs complete_join_semilattice.bot_closed complete_join_semilattice.prop_bot f_closed ftype_pred iter_closed)\n  qed\n  hence \"iter (n+0) f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter (n+?k) f \\<bottom>\\<^bsub>A\\<^esub>\"\n    by (metis iter_add_point)\n  thus \"iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter m f \\<bottom>\\<^bsub>A\\<^esub>\" by (smt nm)\nqed\n\nlemma iter_unfold: \"{x. (\\<exists>i. x = iter i f z)} = {z} \\<union> (f ` {x. (\\<exists>i. x = iter i f z)})\"\nproof -\n  have subset1: \"{x. (\\<exists>i. x = iter i f z)} \\<subseteq> {z} \\<union> {x. (\\<exists>i. x = iter (Suc i) f z)}\"\n  proof\n    fix x assume x_set: \"x \\<in> {x. \\<exists>i. x = iter i f z}\"\n    show \"x \\<in> {z} \\<union> {x. \\<exists>i. x = iter (Suc i) f z}\"\n    proof (cases \"x = z\")\n      assume \"x = z\"\n      thus \"x \\<in> {z} \\<union> {x. \\<exists>i. x = iter (Suc i) f z}\"\n        by (metis insertI1 insert_is_Un)\n    next\n      assume x_not_bot: \"x \\<noteq> z\"\n      obtain j where x_eq: \"x = iter j f z\"\n        by (smt CollectE x_set)\n      hence \"1 \\<le> j\"\n        by (smt Lattice.iter.simps(1) x_not_bot)\n      hence \"\\<exists>i. x = iter (Suc i) f z\"\n        by (metis One_nat_def Suc_le_D x_eq)\n      thus \"x \\<in> {z} \\<union> {x. \\<exists>i. x = iter (Suc i) f z}\"\n        by (smt CollectI Un_def)\n    qed\n  qed\n  have subset2: \"{z} \\<union> {x. (\\<exists>i. x = iter (Suc i) f z)} \\<subseteq> {x. (\\<exists>i. x = iter i f z)}\"\n  proof\n    fix x assume x_set: \"x \\<in> {z} \\<union> {x. \\<exists>i. x = iter (Suc i) f z}\"\n    hence \"\\<exists>i. x = iter i f z\"\n      by (smt Lattice.iter.simps(1) Un_iff empty_iff insert_iff mem_Collect_eq)\n    thus \"x \\<in> {x. \\<exists>i. x = iter i f z}\"\n      by (metis (lifting, full_types) mem_Collect_eq)\n  qed\n  have \"(f ` {x. (\\<exists>i. x = iter i f z)}) = {x. (\\<exists>i. x = iter (Suc i) f z)}\"\n    by (simp add: image_def, smt Collect_cong)\n  thus ?thesis\n    by (metis (lifting) order_antisym subset1 subset2)\nqed\n\nlemma iter_fp: \"f x = x \\<Longrightarrow> iter n f x = x\"\n  by (induct n, simp_all)\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Kleene chains *}\n(* +------------------------------------------------------------------------+ *)\n\ndefinition kleene_chain :: \"('a, 'b) ord_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a, 'b) ord_scheme\" where\n  \"kleene_chain A f = \\<lparr>carrier = {x. (\\<exists>i. x = iter i f \\<bottom>\\<^bsub>A\\<^esub>)}, le = op \\<sqsubseteq>\\<^bsub>A\\<^esub>, \\<dots> = ord.more A\\<rparr>\"\n\nlemma kleene_chain_closed:\n  \"\\<lbrakk>complete_join_semilattice A; f \\<in> carrier A \\<rightarrow> carrier A\\<rbrakk> \\<Longrightarrow> carrier (kleene_chain A f) \\<subseteq> carrier A\"\n  apply (default, simp add: kleene_chain_def)\n  by (metis complete_join_semilattice.bot_closed ftype_pred iter_closed)\n\nlemma kleene_chain_order:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  shows \"order (kleene_chain A f)\"\n  apply (simp add: kleene_chain_def)\n  apply (default, simp_all)\n  apply (metis (full_types) cl_A cl_to_cjs cl_to_order typed_application complete_join_semilattice.bot_closed f_closed iter_closed order.order_refl)\n  apply safe\n  apply simp_all\n  apply (smt cl_A cl_to_cjs cl_to_order typed_application complete_join_semilattice.bot_closed f_closed iter_closed order.order_trans)\n  by (metis order.order_antisym cl_A cl_to_cjs cl_to_order typed_application complete_join_semilattice.bot_closed f_closed iter_closed)\n\nlemma kleene_chain_iso:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"isotone (kleene_chain A f) (kleene_chain A f) f\"\n  apply (simp add: isotone_def)\n  apply safe\n  apply (metis cl_A f_closed kleene_chain_order)\n  using f_iso\n  apply (simp add: isotone_def)\n  apply (simp add: kleene_chain_def)\n  by (metis cl_A cl_to_cjs typed_application complete_join_semilattice.bot_closed f_closed iter_closed)\n\nlemma kleene_chain_total:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"total_order (kleene_chain A f)\"\n  apply (simp add: total_order_def total_order_axioms_def, rule conjI)\n  apply (metis cl_A f_closed kleene_chain_order)\n  apply (simp add: kleene_chain_def)\n  apply clarsimp\nproof -\n  fix n m assume hyp: \"\\<not> iter m f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter n f \\<bottom>\\<^bsub>A\\<^esub>\"\n  show \"iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter m f \\<bottom>\\<^bsub>A\\<^esub>\"\n    apply (cases \"n \\<le> m\")\n    apply (metis cl_A f_closed f_iso iter_chain)\n    by (smt cl_A f_closed f_iso hyp iter_chain)\nqed\n\nlemma kleene_chain_fun:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  shows \"f \\<in> carrier (kleene_chain A f) \\<rightarrow> carrier (kleene_chain A f)\"\n  apply (simp add: kleene_chain_def ftype_pred)\n  by (metis Lattice.iter.simps(2))\n\nlemma kleene_chain_join_semilattice:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"join_semilattice (kleene_chain A f)\"\nproof (simp add: join_semilattice_def join_semilattice_axioms_def, safe)\n  show order: \"order (kleene_chain A f)\"\n    by (metis cl_A f_closed kleene_chain_order)\n  fix x y assume xc: \"x \\<in> carrier (kleene_chain A f)\" and yc: \"y \\<in> carrier (kleene_chain A f)\"\n  thus \"\\<exists>z\\<in>carrier (kleene_chain A f). order.is_lub (kleene_chain A f) z {x, y}\"\n    using order apply (simp add: order.is_lub_simp)\n    apply (simp add: kleene_chain_def)\n    by (metis (lifting) cl_A f_closed f_iso kleene_chain_def kleene_chain_total ord.simps(1) total_order.totality xc yc)\nqed\n\nlemma kleene_chain_meet_semilattice:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"meet_semilattice (kleene_chain A f)\"\nproof (simp add: meet_semilattice_def meet_semilattice_axioms_def, safe)\n  show order: \"order (kleene_chain A f)\"\n    by (metis cl_A f_closed kleene_chain_order)\n  fix x y assume xc: \"x \\<in> carrier (kleene_chain A f)\" and yc: \"y \\<in> carrier (kleene_chain A f)\"\n  thus \"\\<exists>z\\<in>carrier (kleene_chain A f). order.is_glb (kleene_chain A f) z {x, y}\"\n    using order apply (simp add: order.is_glb_simp)\n    apply (simp add: kleene_chain_def)\n    by (metis (lifting) cl_A f_closed f_iso kleene_chain_def kleene_chain_total ord.simps(1) total_order.totality xc yc)\nqed\n\nlemma kleene_chain_lattice:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"lattice (kleene_chain A f)\"\n  apply (simp add: lattice_def)\n  apply (insert kleene_chain_meet_semilattice[of A f] kleene_chain_join_semilattice[of A f] cl_A f_closed f_iso)\n  by simp\n\nlemma kleene_chain_complete_lattice:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  and chain_finite: \"finite (carrier (kleene_chain A f))\"\n  shows \"complete_lattice (kleene_chain A f)\"\n  apply (rule finite_lattice_is_complete)\n  apply (metis chain_finite)\n  apply (simp add: kleene_chain_def)\n  apply metis\n  by (metis cl_A f_closed f_iso kleene_chain_lattice)\n\nlemma kleene_chain_f_lub:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  shows \"\\<Sigma>\\<^bsub>A\\<^esub>(f ` carrier (kleene_chain A f)) = \\<Sigma>\\<^bsub>A\\<^esub>(carrier (kleene_chain A f))\"\nproof -\n  let ?M = \"carrier (kleene_chain A f)\"\n\n  have ord_A: \"order A\"\n    by (metis cl_A cl_to_order)\n\n  have \"\\<Sigma>\\<^bsub>A\\<^esub>(f ` ?M) = order.join A \\<bottom>\\<^bsub>A\\<^esub> (\\<Sigma>\\<^bsub>A\\<^esub>(f ` ?M))\"\n    apply (rule complete_join_semilattice.bot_onel[symmetric])\n    apply (metis cl_A cl_to_cjs)\n    by (smt cl_A cl_to_cjs complete_join_semilattice.is_lub_lub f_closed ftype_pred image_subsetI kleene_chain_closed ord_A order.is_lub_simp subsetD)\n  also have \"... = order.join A (\\<Sigma>\\<^bsub>A\\<^esub>{\\<bottom>\\<^bsub>A\\<^esub>}) (\\<Sigma>\\<^bsub>A\\<^esub>(f ` ?M))\"\n    by (metis (lifting) cl_A cl_to_cjs complete_join_semilattice.bot_closed ord_A order.singleton_lub)\n  also have \"... = \\<Sigma>\\<^bsub>A\\<^esub>({\\<bottom>\\<^bsub>A\\<^esub>} \\<union> (f ` ?M))\"\n    apply (rule complete_join_semilattice.lub_union[symmetric])\n    apply (metis cl_A cl_to_cjs)\n    apply (metis (lifting) bot_least cl_A cl_to_cjs complete_join_semilattice.bot_closed insert_subset)\n    by (metis cl_A cl_to_cjs typed_application f_closed image_mono image_subsetI kleene_chain_closed subset_trans)\n  also have \"... = \\<Sigma>\\<^bsub>A\\<^esub>?M\"\n    apply (simp only: kleene_chain_def partial_object.simps(1))\n    apply (rule_tac f = \"\\<lambda>X. \\<Sigma>\\<^bsub>A\\<^esub>X\" in arg_cong)\n    by (rule iter_unfold[symmetric])\n  finally show ?thesis by metis\nqed\n\nlemma kleene_chain_iter_lub:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_jp: \"join_preserving A A f\"\n  shows \"\\<Sigma>\\<^bsub>A\\<^esub>(iter n f ` carrier (kleene_chain A f)) = \\<Sigma>\\<^bsub>A\\<^esub>(carrier (kleene_chain A f))\"\nproof (induct n, simp, simp only: kleene_chain_def partial_object.simps)\n  let ?M = \"{x. \\<exists>i. x = iter i f \\<bottom>\\<^bsub>A\\<^esub>}\"\n\n  fix n assume ind_hyp: \"\\<Sigma>\\<^bsub>A\\<^esub>(iter n f ` ?M) = \\<Sigma>\\<^bsub>A\\<^esub>?M\"\n\n  have f_iso: \"isotone A A f\"\n    apply (rule ex_join_preserving_is_iso)\n    apply (metis f_closed)\n    apply (metis cl_A cl_to_js)\n    apply (metis cl_A cl_to_js)\n    by (metis (mono_tags) ex_join_preserving_def f_jp join_preserving_def)\n\n  have ord_A: \"order A\"\n    by (metis cl_A cl_to_order)\n\n  have M_subset: \"?M \\<subseteq> carrier A\"\n    by (metis (mono_tags) cl_A cl_to_cjs f_closed kleene_chain_closed kleene_chain_def partial_object.simps(1))\n\n  moreover have \"iter n f \\<in> carrier A \\<rightarrow> carrier A\"\n    by (metis f_closed iter_closed)\n\n  ultimately have iter_M_subset: \"(iter n f ` ?M) \\<subseteq> carrier A\"\n    by (smt ftype_pred image_subsetI set_rev_mp)\n\n  have \"\\<Sigma>\\<^bsub>A\\<^esub>(iter (Suc n) f ` ?M) = \\<Sigma>\\<^bsub>A\\<^esub>(f ` iter n f ` ?M)\"\n    by (smt image_compose iter_pointfree)\n  also have \"... = f (\\<Sigma>\\<^bsub>A\\<^esub>(iter n f ` ?M))\"\n    by (smt iter_M_subset f_jp join_preserving_def)\n  also have \"... = f (\\<Sigma>\\<^bsub>A\\<^esub>?M)\"\n    by (metis ind_hyp)\n  also have \"... = \\<Sigma>\\<^bsub>A\\<^esub>(f ` ?M)\"\n    by (smt M_subset f_jp join_preserving_def)\n  also have \"... = \\<Sigma>\\<^bsub>A\\<^esub>?M\"\n    by (insert kleene_chain_f_lub[of A f] f_closed cl_A f_iso, simp add: kleene_chain_def)\n  finally show \"\\<Sigma>\\<^bsub>A\\<^esub>(iter (Suc n) f ` {x. \\<exists>i. x = iter i f \\<bottom>\\<^bsub>A\\<^esub>}) = \\<Sigma>\\<^bsub>A\\<^esub>{x. \\<exists>i. x = iter i f \\<bottom>\\<^bsub>A\\<^esub>}\"\n    by metis\nqed\n\n(* +------------------------------------------------------------------------+ *)\nsubsection {* Kleene's fixed point theorem *}\n(* +------------------------------------------------------------------------+ *)\n\ntext {* Kleene's fixed point theorem states that for any\n  scott-continuous function $f$ over a complete partial order, the\n  least fixed point of $f$ is also the least upper bound of the\n  ascending kleene chain of $f$ (denoted $C$).\n\n  The chain $C$ is directed, and must therefore have a least upper\n  bound $c$. It can then be shown that $c$ is a fixed point of $f$:\n\n  \\[\n  f(c) = f\\left(\\sum C\\right) = \\sum f(C) = \\sum C = c\n  \\]\n\n  The last step is to show that $c$ is the least fixpoint of\n  $f$. Given an arbitrary fixed point $a$ of $f$, it must be the case\n  that $\\bot \\le a$. As $f^n$ is isotone, $f^n(\\bot) \\le f^n(a) \\le\n  a$, which implies that $\\forall x \\in C. x \\le a$. This can be used\n  to show that $\\sum C \\le \\sum\\{a\\}$, and hence $c \\le a$.\n\n  Here we only prove this theorem for a complete lattice rather than a\n  complete partial order, as we have not formalised complete partial\n  orders. However, the proof could be easily adapted.\n  *}\n\n(* FIXME: Directed is incorrect, as a directed set cannot be empty! *)\n\ntheorem kleene_fixed_point:\n  assumes cl_A: \"complete_lattice A\"\n  and f_closed: \"f \\<in> carrier A \\<rightarrow> carrier A\"\n  and f_iso: \"isotone A A f\"\n  and f_scott_continuous:\n    \"\\<And>D. \\<lbrakk>D\\<subseteq>carrier A; directed \\<lparr>carrier = D, le = op \\<sqsubseteq>\\<^bsub>A\\<^esub>, \\<dots> = ord.more A\\<rparr>; D \\<noteq> {}\\<rbrakk>\n    \\<Longrightarrow> f (\\<Sigma>\\<^bsub>A\\<^esub>D) = \\<Sigma>\\<^bsub>A\\<^esub>(f ` D)\"\n  shows \"\\<mu>\\<^bsub>A\\<^esub>f = \\<Sigma>\\<^bsub>A\\<^esub>(carrier (kleene_chain A f))\"\nproof -\n  let ?C = \"carrier (kleene_chain A f)\"\n\n  have chain_nest [simp]:\n    \"\\<lparr>carrier = carrier (kleene_chain A f), le = op \\<sqsubseteq>\\<^bsub>A\\<^esub>, \\<dots> = ord.more A\\<rparr> = kleene_chain A f\"\n    by (simp add: kleene_chain_def)\n\n  have \"\\<bottom>\\<^bsub>A\\<^esub> \\<in> ?C\"\n    by (simp add: kleene_chain_def, metis Lattice.iter.simps(1))\n  hence chain_non_empty: \"?C \\<noteq> {}\"\n    by (metis empty_iff)\n\n  have chain_directed: \"directed (kleene_chain A f)\"\n    by (metis cl_A f_closed f_iso kleene_chain_total total_order_is_directed)\n\n  have ord_A: \"order A\"\n    by (metis cl_A cl_to_order)\n\n  have ord_kle: \"order (kleene_chain A f)\"\n    by (metis cl_A f_closed kleene_chain_order)\n\n  have \"\\<exists>c::'a. order.is_lub A c ?C\"\n    by (metis cl_A cl_to_cjs complete_join_semilattice.lub_ex f_closed kleene_chain_closed)\n  then obtain c :: 'a where c_lub: \"order.is_lub A c ?C\" by metis\n  have \"f c = f (\\<Sigma>\\<^bsub>A\\<^esub>?C)\"\n    by (metis c_lub ord_A order.lub_is_lub)\n  also have \"... = \\<Sigma>\\<^bsub>A\\<^esub>(f ` ?C)\"\n    by (metis chain_directed chain_nest chain_non_empty cl_A cl_to_cjs f_closed f_scott_continuous kleene_chain_closed)\n  also have \"... = \\<Sigma>\\<^bsub>A\\<^esub>?C\"\n    by (metis cl_A f_closed f_iso kleene_chain_f_lub)\n  also have \"... = c\"\n    by (metis c_lub ord_A order.lub_is_lub)\n  finally have c_is_fixpoint: \"f c = c\" by auto\n\n  have \"\\<forall>a\\<in>carrier A. f a = a \\<longrightarrow> c \\<sqsubseteq>\\<^bsub>A\\<^esub> a\"\n  proof clarify\n    fix a assume a_is_fixpoint: \"f a = a\" and ac: \"a \\<in> carrier A\"\n    have \"\\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> a\"\n      by (metis ac cl_A cl_to_cjs complete_join_semilattice.prop_bot)\n    hence \"\\<forall>n. iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> iter n f a\"\n      by (metis (lifting) ac cl_A cl_to_cjs complete_join_semilattice.bot_closed f_closed f_iso iter_iso use_iso1)\n    hence iter_leq_a: \"\\<forall>n. iter n f \\<bottom>\\<^bsub>A\\<^esub> \\<sqsubseteq>\\<^bsub>A\\<^esub> a\"\n      by (metis a_is_fixpoint iter_fp)\n    have \"\\<Sigma>\\<^bsub>A\\<^esub>?C \\<sqsubseteq>\\<^bsub>A\\<^esub> \\<Sigma>\\<^bsub>A\\<^esub>{a}\"\n    proof (rule complete_lattice.lub_set_leq, simp_all add: cl_A ac)\n      show \"carrier (kleene_chain A f) \\<subseteq> carrier A\"\n        by (metis c_lub ord_A order.is_lub_simp)\n      show \"\\<forall>x\\<in>carrier (kleene_chain A f). x \\<sqsubseteq>\\<^bsub>A\\<^esub> a\"\n        by (simp add: kleene_chain_def, clarsimp, metis iter_leq_a)\n    qed\n    hence \"\\<Sigma>\\<^bsub>A\\<^esub>?C \\<sqsubseteq>\\<^bsub>A\\<^esub> a\"\n      by (smt ac ord_A order.singleton_lub)\n    thus \"c \\<sqsubseteq>\\<^bsub>A\\<^esub> a\"\n      by (metis `\\<Sigma>\\<^bsub>A\\<^esub>?C = c`)\n  qed\n  thus ?thesis\n    by (metis c_is_fixpoint c_lub f_closed lfp_equality_var lub_in ord_A order.lub_is_lub)\nqed\n\nend\n", "meta": {"author": "Alasdair", "repo": "Thesis", "sha": "8face4b62adfd73803b387e95c24f06e09736e30", "save_path": "github-repos/isabelle/Alasdair-Thesis", "path": "github-repos/isabelle/Alasdair-Thesis/Thesis-8face4b62adfd73803b387e95c24f06e09736e30/WorkingSKAT/Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.8652240964782011, "lm_q1q2_score": 0.7861581010586519}}
{"text": "(*\n  File: Primes_Ex.thy\n  Author: Bohua Zhan\n\n  Elementary number theory of primes, up to the proof of infinitude\n  of primes and the unique factorization theorem.\n\n  Follows the development in HOL/Computational_Algebra/Primes.thy.\n*)\n\nsection \\<open>Primes\\<close>\n\ntheory Primes_Ex\n  imports Auto2_Main\nbegin\n\nsubsection \\<open>Basic definition\\<close>\n\ndefinition prime :: \"nat \\<Rightarrow> bool\" where [rewrite]:\n  \"prime p = (1 < p \\<and> (\\<forall>m. m dvd p \\<longrightarrow> m = 1 \\<or> m = p))\"\n\nlemma primeD1 [forward]: \"prime p \\<Longrightarrow> 1 < p\" by auto2\nlemma primeD2: \"prime p \\<Longrightarrow> m dvd p \\<Longrightarrow> m = 1 \\<or> m = p\" by auto2\nsetup \\<open>add_forward_prfstep_cond @{thm primeD2} [with_cond \"?m \\<noteq> 1\", with_cond \"?m \\<noteq> ?p\"]\\<close>\nsetup \\<open>del_prfstep_thm_eqforward @{thm prime_def}\\<close>\n\n(* Exists a prime p. *)\ntheorem exists_prime [resolve]: \"\\<exists>p. prime p\"\n@proof @have \"prime 2\" @qed\n\nlemma prime_odd_nat: \"prime p \\<Longrightarrow> p > 2 \\<Longrightarrow> odd p\" by auto2\n\nlemma prime_imp_coprime_nat [backward2]: \"prime p \\<Longrightarrow> \\<not> p dvd n \\<Longrightarrow> coprime p n\" by auto2\n\nlemma prime_dvd_mult_nat: \"prime p \\<Longrightarrow> p dvd m * n \\<Longrightarrow> p dvd m \\<or> p dvd n\" by auto2\nsetup \\<open>add_forward_prfstep_cond @{thm prime_dvd_mult_nat}\n  (with_conds [\"?m \\<noteq> ?p\", \"?n \\<noteq> ?p\", \"?m \\<noteq> ?p * ?m'\", \"?n \\<noteq> ?p * ?n'\"])\\<close>\n\ntheorem prime_dvd_intro: \"prime p \\<Longrightarrow> p * q = m * n \\<Longrightarrow> p dvd m \\<or> p dvd n\"\n@proof @have \"p dvd m * n\" @qed\nsetup \\<open>add_forward_prfstep_cond @{thm prime_dvd_intro}\n  (with_conds [\"?m \\<noteq> ?p\", \"?n \\<noteq> ?p\", \"?m \\<noteq> ?p * ?m'\", \"?n \\<noteq> ?p * ?n'\"])\\<close>\n\nlemma prime_dvd_mult_eq_nat: \"prime p \\<Longrightarrow> p dvd m * n = (p dvd m \\<or> p dvd n)\" by auto2\n\nlemma not_prime_eq_prod_nat [backward1]: \"n > 1 \\<Longrightarrow> \\<not> prime n \\<Longrightarrow>\n    \\<exists>m k. n = m * k \\<and> 1 < m \\<and> m < n \\<and> 1 < k \\<and> k < n\"\n@proof\n  @obtain m where \"m dvd n \\<and> m \\<noteq> 1 \\<and> m \\<noteq> n\"\n  @obtain k where \"n = m * k\" @have \"m \\<le> m * k\" @have \"k \\<le> m * k\"\n@qed\n\nlemma prime_dvd_power_nat: \"prime p \\<Longrightarrow> p dvd x^n \\<Longrightarrow> p dvd x\" by auto2\nsetup \\<open>add_forward_prfstep_cond @{thm prime_dvd_power_nat} [with_cond \"?p \\<noteq> ?x\"]\\<close>\n\nlemma prime_dvd_power_nat_iff: \"prime p \\<Longrightarrow> n > 0 \\<Longrightarrow> p dvd x^n \\<longleftrightarrow> p dvd x\" by auto2\n\nlemma prime_nat_code: \"prime p = (1 < p \\<and> (\\<forall>x. 1 < x \\<and> x < p \\<longrightarrow> \\<not> x dvd p))\" by auto2\n\nlemma prime_factor_nat [backward]: \"n \\<noteq> 1 \\<Longrightarrow> \\<exists>p. p dvd n \\<and> prime p\"\n@proof\n  @strong_induct n\n  @case \"prime n\" @case \"n = 0\"\n  @obtain k where \"k \\<noteq> 1\" \"k \\<noteq> n\" \"k dvd n\"\n  @apply_induct_hyp k\n@qed\n\nlemma prime_divprod_pow_nat:\n  \"prime p \\<Longrightarrow> coprime a b \\<Longrightarrow> p^n dvd a * b \\<Longrightarrow> p^n dvd a \\<or> p^n dvd b\" by auto2\n\nlemma prime_product [forward]: \"prime (p * q) \\<Longrightarrow> p = 1 \\<or> q = 1\"\n@proof @have \"p dvd q * p\" @qed\n\nlemma prime_exp: \"prime (p ^ n) \\<longleftrightarrow> n = 1 \\<and> prime p\" by auto2\n\nlemma prime_power_mult: \"prime p \\<Longrightarrow> x * y = p ^ k \\<Longrightarrow> \\<exists>i j. x = p ^ i \\<and> y = p ^ j\"\n@proof\n  @induct k arbitrary x y @with\n    @subgoal \"k = Suc k'\"\n      @case \"p dvd x\" @with\n        @obtain x' where \"x = p * x'\" @have \"x * y = p * (x' * y)\"\n        @obtain i j where \"x' = p ^ i\" \"y = p ^ j\" @have \"x = p ^ Suc i\" @end\n      @case \"p dvd y\" @with\n        @obtain y' where \"y = p * y'\" @have \"x * y = p * (x * y')\"\n        @obtain i j where \"x = p ^ i\" \"y' = p ^ j\" @have \"y = p ^ Suc j\" @end\n    @endgoal\n  @end\n@qed\n\nsubsection \\<open>Infinitude of primes\\<close>\n\ntheorem bigger_prime [resolve]: \"\\<exists>p. prime p \\<and> n < p\"\n@proof\n  @obtain p where \"prime p\" \"p dvd fact n + 1\"\n  @case \"n \\<ge> p\" @with @have \"(p::nat) dvd fact n\" @end\n@qed\n\ntheorem primes_infinite: \"\\<not> finite {p. prime p}\"\n@proof\n  @obtain b where \"prime b\" \"Max {p. prime p} < b\"\n@qed\n\nsubsection \\<open>Existence and uniqueness of prime factorization\\<close>\n\ntheorem factorization_exists: \"n > 0 \\<Longrightarrow> \\<exists>M. (\\<forall>p\\<in>#M. prime p) \\<and> n = (\\<Prod>i\\<in>#M. i)\"\n@proof\n  @strong_induct n\n  @case \"n = 1\" @with @have \"n = (\\<Prod>i\\<in># {#}. i)\" @end\n  @case \"prime n\" @with @have \"n = (\\<Prod>i\\<in># {#n#}. i)\" @end\n  @obtain m k where \"n = m * k\" \"1 < m\" \"m < n\" \"1 < k\" \"k < n\"\n  @apply_induct_hyp m\n  @obtain M where \"(\\<forall>p\\<in>#M. prime p)\" \"m = (\\<Prod>i\\<in>#M. i)\"\n  @apply_induct_hyp k\n  @obtain K where \"(\\<forall>p\\<in>#K. prime p)\" \"k = (\\<Prod>i\\<in>#K. i)\"\n  @have \"n = (\\<Prod>i\\<in>#(M+K). i)\"\n@qed\n\ntheorem prime_dvd_multiset [backward1]: \"prime p \\<Longrightarrow> p dvd (\\<Prod>i\\<in>#M. i) \\<Longrightarrow> \\<exists>n. n\\<in>#M \\<and> p dvd n\"\n@proof\n  @strong_induct M\n  @case \"M = {#}\"\n  @obtain M' m where \"M = M' + {#m#}\"\n  @contradiction @apply_induct_hyp M'\n@qed\n  \ntheorem factorization_unique_aux:\n  \"\\<forall>p\\<in>#M. prime p \\<Longrightarrow> \\<forall>p\\<in>#N. prime p \\<Longrightarrow> (\\<Prod>i\\<in>#M. i) dvd (\\<Prod>i\\<in>#N. i) \\<Longrightarrow> M \\<subseteq># N\"\n@proof\n  @strong_induct M arbitrary N\n  @case \"M = {#}\"\n  @obtain M' m where \"M = M' + {#m#}\"\n  @have \"m dvd (\\<Prod>i\\<in>#M. i)\"\n  @obtain n where \"n \\<in># N\" \"m dvd n\"\n  @obtain N' where \"N = N' + {#n#}\"\n  @have \"m = n\"\n  @have \"(\\<Prod>i\\<in>#M'. i) dvd (\\<Prod>i\\<in>#N'. i)\"\n  @apply_induct_hyp M' N'\n@qed\nsetup \\<open>add_forward_prfstep_cond @{thm factorization_unique_aux} [with_cond \"?M \\<noteq> ?N\"]\\<close>\n\ntheorem factorization_unique:\n  \"\\<forall>p\\<in>#M. prime p \\<Longrightarrow> \\<forall>p\\<in>#N. prime p \\<Longrightarrow> (\\<Prod>i\\<in>#M. i) = (\\<Prod>i\\<in>#N. i) \\<Longrightarrow> M = N\"\n@proof @have \"M \\<subseteq># N\" @qed\nsetup \\<open>del_prfstep_thm @{thm factorization_unique_aux}\\<close>\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Auto2_HOL/HOL/Primes_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7860986188278327}}
{"text": "theory \"insertion-sort\"\n  imports Main \"HOL-Library.Multiset\"\nbegin\n\ndeclare[[names_short]]\n\ntext \\<open>non-tail recursive\\<close>\n\nprimrec insert:: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\ninsert_Nil: \"insert x [] = [x]\" |\ninsert_Cons: \"insert x (y#ys) = (if x < y then (x#y#ys) else y#insert x ys)\"\n\nvalue \"insert 1 [2,4,10]\"\n\nprimrec insertion_sort:: \"nat list \\<Rightarrow> nat list\" where\ninsertion_sort_Nil : \"insertion_sort []  = []\" |\ninsertion_sort_Cons: \"insertion_sort (x#xs)  = insert x (insertion_sort(xs))\"\n\nvalue \"insert_sort [2,4,10,0,3]\"\n\nlemma sorted3 : \"\\<lbrakk>sorted(y#ys); \\<not> x < y\\<rbrakk> \\<Longrightarrow> sorted (y#insert x ys) = (y \\<le> x \\<and> sorted(insert x ys))\"\nproof(induction ys  rule: sorted.induct)\n  case 1\n  then show \"sorted (y # insert x []) = (y \\<le> x \\<and> sorted (insert x []))\" by auto\nnext\n  case (2 x ys)\n  then show ?case by (simp del:List.linorder_class.sorted.simps add:sorted2_simps)\nqed\n\nlemma insert_order: \"sorted(ys) \\<Longrightarrow> sorted (insert x ys)\"\nproof (induct ys arbitrary: x)\n  case Nil\n  then show \"sorted (insert x [])\" by simp\nnext\n  case (Cons y ys)\n  then show \"sorted (insert x (y # ys))\" \n  proof (cases \"x < y\")\n    case True\n    then show \"sorted (insert x (y # ys))\"\n    proof (simp only: True insert_Cons if_True)\n      show \"sorted (x # y # ys)\"\n      proof(simp)\n        show \"x \\<le> y \\<and> Ball (set ys) ((\\<le>) x) \\<and> Ball (set ys) ((\\<le>) y) \\<and> sorted ys\"\n        proof(intro conjI)\n          show \"x \\<le> y\"  by (simp add: Orderings.order_class.order.strict_implies_order True)\n        next\n          show \"Ball (set ys) ((\\<le>) x)\" using True local.Cons.prems by auto\n        next\n          show \"Ball (set ys) ((\\<le>) y)\"  using List.linorder_class.sorted.simps(2) local.Cons.prems by simp\n        next\n          show \"sorted ys\" using List.linorder_class.sorted.simps(2) local.Cons.prems by simp\n        qed\n      qed\n    qed\n  next\n    case False\n    then show \"sorted (insert x (y # ys))\" \n    proof(simp only:False insert_Cons if_False)\n      show \"sorted (y # insert x ys)\"\n      proof(simp  del:List.linorder_class.sorted.simps add: False sorted3 \"local.Cons.prems\")\n        show \"y \\<le> x \\<and> sorted (insert x ys)\"\n        proof(rule conjI)\n          show \"y \\<le> x\"  by (simp add: False leI)\n        next\n          have \"sorted ys\" using \"local.Cons.prems\" List.linorder_class.sorted.simps(2) by blast\n          then show \"sorted (insert x ys)\"  by (simp add: local.Cons.hyps)\n        qed\n      qed\n    qed\n  qed\nqed\n\ntheorem insertion_sort_order : \"sorted(insertion_sort(ys))\"\nproof (induct ys)\n  case Nil\n  then show \"sorted (insertion_sort [])\" by simp\nnext\n  case (Cons y ys)\n  show \"sorted (insertion_sort (y # ys))\"\n  proof (simp only: insertion_sort_Cons)\n    show \"sorted (insert y (insertion_sort ys))\" by (simp only: \"local.Cons.hyps\" insert_order)\n  qed\nqed\n\nlemma insert_permutation: \"mset (insert x ys) = mset (x#ys)\"\nproof(induct ys arbitrary: x)\n  case Nil\n  then show \"mset (insert x []) = mset [x]\" by simp\nnext\n  case (Cons y ys)\n  then show \"mset (insert x (y # ys)) = mset (x # y # ys)\"\n  proof (cases \"x < y\")\n    case True\n    then show \"mset (insert x (y # ys)) = mset (x # y # ys)\" by simp\n  next\n    case False\n    have \"mset (insert x (y # ys)) = mset (y#insert x ys)\" using False by simp\n    also have \"... = {#y#} + mset(insert x ys)\" by simp\n    also have \"... = {#y#} + mset (x # ys)\" using \"local.Cons.hyps\" False by simp\n    also have \"... = mset (x # y # ys)\"  by simp\n    finally show \"mset (insert x (y # ys)) = mset (x # y # ys)\" by this\n  qed\nqed\n\ntheorem insertion_sort_permutation: \"mset (insertion_sort ys) = mset ys\"\nproof(induct ys)\n  case Nil\n  then show \"mset (insertion_sort []) = mset []\" by simp\nnext\n  case (Cons x xs)\n  have \"mset (insertion_sort (x # xs)) = mset (insert x (insertion_sort(xs)))\" by simp\n  also have \"... =  mset(x#(insertion_sort(xs)))\" using  insert_permutation by simp\n  also have \"... =  {#x#} + mset(insertion_sort(xs))\" by simp\n  also have \"... =  {#x#} +  mset xs\" using \"local.Cons.hyps\" by simp\n  also have \"... =  mset (x # xs)\" using \"local.Cons.hyps\" by simp\n  finally show \"mset (insertion_sort (x # xs)) = mset (x # xs)\" by this\nqed\n\ntext \\<open>tail recursive\\<close>\n\nfun insertion_sort_tail:: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\ninsertion_sort_tail_Nil : \"insertion_sort_tail [] accum  = accum\" |\ninsertion_sort_tail_Cons: \"insertion_sort_tail (x#xs) accum  = insertion_sort_tail (xs) (insert x accum)\"\n\nvalue \"insert_sort_tail ([2,4,10]) ([])\"\n\ntheorem insert_sort_tail_order: \"sorted(ACCUM) \\<Longrightarrow> sorted(insertion_sort_tail xs ACCUM)\"\nproof(induct xs arbitrary:ACCUM)\n  case Nil\n  then show \"sorted (insertion_sort_tail [] ACCUM)\" by simp\nnext\n  case (Cons a xs)\n  then show \"sorted (insertion_sort_tail (a # xs) ACCUM)\" by (simp add: insert_order)\nqed\n\ntheorem insertion_sort_tail_permutation: \"mset (insertion_sort_tail xs ACCUM) = mset (xs@ACCUM)\"\nproof(induct xs arbitrary:ACCUM)\n  case Nil\n  then show \"mset (insertion_sort_tail [] ACCUM) = mset ([] @ ACCUM)\" by simp\nnext\n  case (Cons a xs)\n  then show ?case by (simp add: insert_permutation)\nqed", "meta": {"author": "marco10507", "repo": "formalization-of-sorting-algorithms", "sha": "de905424e53d55829d54c2cd3c8f5241ac5ca904", "save_path": "github-repos/isabelle/marco10507-formalization-of-sorting-algorithms", "path": "github-repos/isabelle/marco10507-formalization-of-sorting-algorithms/formalization-of-sorting-algorithms-de905424e53d55829d54c2cd3c8f5241ac5ca904/insertion-sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525463, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7860986060898916}}
{"text": "(*  Title:      HOL/Library/Permutation.thy\n    Author:     Lawrence C Paulson and Thomas M Rasmussen and Norbert Voelker\n*)\n\nsection {* Permutations *}\n\ntheory Permutation\nimports Multiset\nbegin\n\ninductive perm :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"  (\"_ <~~> _\"  [50, 50] 50)  (* FIXME proper infix, without ambiguity!? *)\nwhere\n  Nil [intro!]: \"[] <~~> []\"\n| swap [intro!]: \"y # x # l <~~> x # y # l\"\n| Cons [intro!]: \"xs <~~> ys \\<Longrightarrow> z # xs <~~> z # ys\"\n| trans [intro]: \"xs <~~> ys \\<Longrightarrow> ys <~~> zs \\<Longrightarrow> xs <~~> zs\"\n\nlemma perm_refl [iff]: \"l <~~> l\"\n  by (induct l) auto\n\n\nsubsection {* Some examples of rule induction on permutations *}\n\nlemma xperm_empty_imp: \"[] <~~> ys \\<Longrightarrow> ys = []\"\n  by (induct xs == \"[] :: 'a list\" ys pred: perm) simp_all\n\n\ntext {* \\medskip This more general theorem is easier to understand! *}\n\nlemma perm_length: \"xs <~~> ys \\<Longrightarrow> length xs = length ys\"\n  by (induct pred: perm) simp_all\n\nlemma perm_empty_imp: \"[] <~~> xs \\<Longrightarrow> xs = []\"\n  by (drule perm_length) auto\n\nlemma perm_sym: \"xs <~~> ys \\<Longrightarrow> ys <~~> xs\"\n  by (induct pred: perm) auto\n\n\nsubsection {* Ways of making new permutations *}\n\ntext {* We can insert the head anywhere in the list. *}\n\nlemma perm_append_Cons: \"a # xs @ ys <~~> xs @ a # ys\"\n  by (induct xs) auto\n\nlemma perm_append_swap: \"xs @ ys <~~> ys @ xs\"\n  apply (induct xs)\n    apply simp_all\n  apply (blast intro: perm_append_Cons)\n  done\n\nlemma perm_append_single: \"a # xs <~~> xs @ [a]\"\n  by (rule perm.trans [OF _ perm_append_swap]) simp\n\nlemma perm_rev: \"rev xs <~~> xs\"\n  apply (induct xs)\n   apply simp_all\n  apply (blast intro!: perm_append_single intro: perm_sym)\n  done\n\nlemma perm_append1: \"xs <~~> ys \\<Longrightarrow> l @ xs <~~> l @ ys\"\n  by (induct l) auto\n\nlemma perm_append2: \"xs <~~> ys \\<Longrightarrow> xs @ l <~~> ys @ l\"\n  by (blast intro!: perm_append_swap perm_append1)\n\n\nsubsection {* Further results *}\n\nlemma perm_empty [iff]: \"[] <~~> xs \\<longleftrightarrow> xs = []\"\n  by (blast intro: perm_empty_imp)\n\nlemma perm_empty2 [iff]: \"xs <~~> [] \\<longleftrightarrow> xs = []\"\n  apply auto\n  apply (erule perm_sym [THEN perm_empty_imp])\n  done\n\nlemma perm_sing_imp: \"ys <~~> xs \\<Longrightarrow> xs = [y] \\<Longrightarrow> ys = [y]\"\n  by (induct pred: perm) auto\n\nlemma perm_sing_eq [iff]: \"ys <~~> [y] \\<longleftrightarrow> ys = [y]\"\n  by (blast intro: perm_sing_imp)\n\nlemma perm_sing_eq2 [iff]: \"[y] <~~> ys \\<longleftrightarrow> ys = [y]\"\n  by (blast dest: perm_sym)\n\n\nsubsection {* Removing elements *}\n\nlemma perm_remove: \"x \\<in> set ys \\<Longrightarrow> ys <~~> x # remove1 x ys\"\n  by (induct ys) auto\n\n\ntext {* \\medskip Congruence rule *}\n\nlemma perm_remove_perm: \"xs <~~> ys \\<Longrightarrow> remove1 z xs <~~> remove1 z ys\"\n  by (induct pred: perm) auto\n\nlemma remove_hd [simp]: \"remove1 z (z # xs) = xs\"\n  by auto\n\nlemma cons_perm_imp_perm: \"z # xs <~~> z # ys \\<Longrightarrow> xs <~~> ys\"\n  by (drule_tac z = z in perm_remove_perm) auto\n\nlemma cons_perm_eq [iff]: \"z#xs <~~> z#ys \\<longleftrightarrow> xs <~~> ys\"\n  by (blast intro: cons_perm_imp_perm)\n\nlemma append_perm_imp_perm: \"zs @ xs <~~> zs @ ys \\<Longrightarrow> xs <~~> ys\"\n  by (induct zs arbitrary: xs ys rule: rev_induct) auto\n\nlemma perm_append1_eq [iff]: \"zs @ xs <~~> zs @ ys \\<longleftrightarrow> xs <~~> ys\"\n  by (blast intro: append_perm_imp_perm perm_append1)\n\nlemma perm_append2_eq [iff]: \"xs @ zs <~~> ys @ zs \\<longleftrightarrow> xs <~~> ys\"\n  apply (safe intro!: perm_append2)\n  apply (rule append_perm_imp_perm)\n  apply (rule perm_append_swap [THEN perm.trans])\n    -- {* the previous step helps this @{text blast} call succeed quickly *}\n  apply (blast intro: perm_append_swap)\n  done\n\nlemma multiset_of_eq_perm: \"multiset_of xs = multiset_of ys \\<longleftrightarrow> xs <~~> ys\"\n  apply (rule iffI)\n  apply (erule_tac [2] perm.induct)\n  apply (simp_all add: union_ac)\n  apply (erule rev_mp)\n  apply (rule_tac x=ys in spec)\n  apply (induct_tac xs)\n  apply auto\n  apply (erule_tac x = \"remove1 a x\" in allE)\n  apply (drule sym)\n  apply simp\n  apply (subgoal_tac \"a \\<in> set x\")\n  apply (drule_tac z = a in perm.Cons)\n  apply (erule perm.trans)\n  apply (rule perm_sym)\n  apply (erule perm_remove)\n  apply (drule_tac f=set_of in arg_cong)\n  apply simp\n  done\n\nlemma multiset_of_le_perm_append: \"multiset_of xs \\<le> multiset_of ys \\<longleftrightarrow> (\\<exists>zs. xs @ zs <~~> ys)\"\n  apply (auto simp: multiset_of_eq_perm[THEN sym] mset_le_exists_conv)\n  apply (insert surj_multiset_of)\n  apply (drule surjD)\n  apply (blast intro: sym)+\n  done\n\nlemma perm_set_eq: \"xs <~~> ys \\<Longrightarrow> set xs = set ys\"\n  by (metis multiset_of_eq_perm multiset_of_eq_setD)\n\nlemma perm_distinct_iff: \"xs <~~> ys \\<Longrightarrow> distinct xs = distinct ys\"\n  apply (induct pred: perm)\n     apply simp_all\n   apply fastforce\n  apply (metis perm_set_eq)\n  done\n\nlemma eq_set_perm_remdups: \"set xs = set ys \\<Longrightarrow> remdups xs <~~> remdups ys\"\n  apply (induct xs arbitrary: ys rule: length_induct)\n  apply (case_tac \"remdups xs\")\n   apply simp_all\n  apply (subgoal_tac \"a \\<in> set (remdups ys)\")\n   prefer 2 apply (metis list.set(2) insert_iff set_remdups)\n  apply (drule split_list) apply (elim exE conjE)\n  apply (drule_tac x = list in spec) apply (erule impE) prefer 2\n   apply (drule_tac x = \"ysa @ zs\" in spec) apply (erule impE) prefer 2\n    apply simp\n    apply (subgoal_tac \"a # list <~~> a # ysa @ zs\")\n     apply (metis Cons_eq_appendI perm_append_Cons trans)\n    apply (metis Cons Cons_eq_appendI distinct.simps(2)\n      distinct_remdups distinct_remdups_id perm_append_swap perm_distinct_iff)\n   apply (subgoal_tac \"set (a # list) =\n      set (ysa @ a # zs) \\<and> distinct (a # list) \\<and> distinct (ysa @ a # zs)\")\n    apply (fastforce simp add: insert_ident)\n   apply (metis distinct_remdups set_remdups)\n   apply (subgoal_tac \"length (remdups xs) < Suc (length xs)\")\n   apply simp\n   apply (subgoal_tac \"length (remdups xs) \\<le> length xs\")\n   apply simp\n   apply (rule length_remdups_leq)\n  done\n\nlemma perm_remdups_iff_eq_set: \"remdups x <~~> remdups y \\<longleftrightarrow> set x = set y\"\n  by (metis List.set_remdups perm_set_eq eq_set_perm_remdups)\n\nlemma permutation_Ex_bij:\n  assumes \"xs <~~> ys\"\n  shows \"\\<exists>f. bij_betw f {..<length xs} {..<length ys} \\<and> (\\<forall>i<length xs. xs ! i = ys ! (f i))\"\n  using assms\nproof induct\n  case Nil\n  then show ?case\n    unfolding bij_betw_def by simp\nnext\n  case (swap y x l)\n  show ?case\n  proof (intro exI[of _ \"Fun.swap 0 1 id\"] conjI allI impI)\n    show \"bij_betw (Fun.swap 0 1 id) {..<length (y # x # l)} {..<length (x # y # l)}\"\n      by (auto simp: bij_betw_def)\n    fix i\n    assume \"i < length (y # x # l)\"\n    show \"(y # x # l) ! i = (x # y # l) ! (Fun.swap 0 1 id) i\"\n      by (cases i) (auto simp: Fun.swap_def gr0_conv_Suc)\n  qed\nnext\n  case (Cons xs ys z)\n  then obtain f where bij: \"bij_betw f {..<length xs} {..<length ys}\"\n    and perm: \"\\<forall>i<length xs. xs ! i = ys ! (f i)\"\n    by blast\n  let ?f = \"\\<lambda>i. case i of Suc n \\<Rightarrow> Suc (f n) | 0 \\<Rightarrow> 0\"\n  show ?case\n  proof (intro exI[of _ ?f] allI conjI impI)\n    have *: \"{..<length (z#xs)} = {0} \\<union> Suc ` {..<length xs}\"\n            \"{..<length (z#ys)} = {0} \\<union> Suc ` {..<length ys}\"\n      by (simp_all add: lessThan_Suc_eq_insert_0)\n    show \"bij_betw ?f {..<length (z#xs)} {..<length (z#ys)}\"\n      unfolding *\n    proof (rule bij_betw_combine)\n      show \"bij_betw ?f (Suc ` {..<length xs}) (Suc ` {..<length ys})\"\n        using bij unfolding bij_betw_def\n        by (auto intro!: inj_onI imageI dest: inj_onD simp: image_comp comp_def)\n    qed (auto simp: bij_betw_def)\n    fix i\n    assume \"i < length (z # xs)\"\n    then show \"(z # xs) ! i = (z # ys) ! (?f i)\"\n      using perm by (cases i) auto\n  qed\nnext\n  case (trans xs ys zs)\n  then obtain f g\n    where bij: \"bij_betw f {..<length xs} {..<length ys}\" \"bij_betw g {..<length ys} {..<length zs}\"\n    and perm: \"\\<forall>i<length xs. xs ! i = ys ! (f i)\" \"\\<forall>i<length ys. ys ! i = zs ! (g i)\"\n    by blast\n  show ?case\n  proof (intro exI[of _ \"g \\<circ> f\"] conjI allI impI)\n    show \"bij_betw (g \\<circ> f) {..<length xs} {..<length zs}\"\n      using bij by (rule bij_betw_trans)\n    fix i\n    assume \"i < length xs\"\n    with bij have \"f i < length ys\"\n      unfolding bij_betw_def by force\n    with `i < length xs` show \"xs ! i = zs ! (g \\<circ> f) i\"\n      using trans(1,3)[THEN perm_length] perm by auto\n  qed\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Permutation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.9046505434556232, "lm_q1q2_score": 0.7859846214379175}}
{"text": "(*  \n    Title:      Determinants2.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Computing determinants of matrices using the Gauss Jordan algorithm\\<close>\n\ntheory Determinants2\nimports\n  Gauss_Jordan_PA\nbegin\n\nsubsection\\<open>Some previous properties\\<close>\n\nsubsubsection\\<open>Relationships between determinants and elementary row operations\\<close>\n\nlemma det_interchange_rows:\nshows \"det (interchange_rows A i j) = of_int (if i = j then 1 else -1) * det A\"\nproof -\n  have \"(interchange_rows A i j) = (\\<chi> a. A $ (Fun.swap i j id) a)\" unfolding interchange_rows_def Fun.swap_def by vector\n  hence \"det(interchange_rows A i j) = det(\\<chi> a. A$(Fun.swap i j id) a)\" by simp\n  also have \"... = of_int (sign (Fun.swap i j id)) * det A\" by (rule det_permute_rows[of \"Fun.swap i j id\" A], simp add: permutes_swap_id)\n  finally show ?thesis unfolding sign_swap_id .\nqed\n\ncorollary det_interchange_different_rows:\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (interchange_rows A i j) = - det A\" unfolding det_interchange_rows using i_not_j by simp\n\ncorollary det_interchange_same_rows:\nassumes i_eq_j: \"i = j\"\nshows \"det (interchange_rows A i j) = det A\" unfolding det_interchange_rows using i_eq_j by simp\n\nlemma det_mult_row:\nshows \"det (mult_row A a k) = k * det A\"\nproof -\nhave A_rw: \"(\\<chi> i. if i = a then A$a else A$i) = A\" by vector\nhave \"(mult_row A a k) = (\\<chi> i. if i = a then k *s A $ a else A $ i)\" unfolding mult_row_def by vector\nhence \"det(mult_row A a k) = det(\\<chi> i. if i = a then k *s A $ a else A $ i)\" by simp\nalso have \"... =  k * det(\\<chi> i. if i = a then A$a else A$i)\" unfolding det_row_mul ..\nalso have \"... = k * det A\" unfolding A_rw ..\nfinally show ?thesis .\nqed\n\n(*The name det_row_add is already used in the Determinants.thy file of the standard library*)\nlemma det_row_add':\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (row_add A i j q) = det A\"\nproof -\nhave \"(row_add A i j q) = (\\<chi> k. if k = i then row i A + q *s row j A else row k A)\"\nunfolding row_add_def row_def by vector\nhence \"det(row_add A i j q) = det(\\<chi> k. if k = i then row i A + q *s row j A else row k A)\" by simp\nalso have \"... = det A\" unfolding det_row_operation[OF i_not_j] ..\nfinally show ?thesis .\nqed\n\n\nsubsubsection\\<open>Relationships between determinants and elementary column operations\\<close>\n\nlemma det_interchange_columns:\nshows \"det (interchange_columns A i j) = of_int (if i = j then 1 else -1) * det A\"\nproof - \nhave \"(interchange_columns A i j) = (\\<chi> a b. A $ a $ (Fun.swap i j id) b)\" unfolding interchange_columns_def Fun.swap_def by vector\nhence \"det(interchange_columns A i j) = det(\\<chi> a b. A $ a $ (Fun.swap i j id) b)\" by simp\nalso have \"... = of_int (sign (Fun.swap i j id)) * det A\" by (rule det_permute_columns[of \"Fun.swap i j id\" A], simp add: permutes_swap_id)\nfinally show ?thesis unfolding sign_swap_id .\nqed\n\ncorollary det_interchange_different_columns:\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (interchange_columns A i j) = - det A\" unfolding det_interchange_columns using i_not_j by simp\n\ncorollary det_interchange_same_columns:\nassumes i_eq_j: \"i = j\"\nshows \"det (interchange_columns A i j) = det A\" unfolding det_interchange_columns using i_eq_j by simp\n\nlemma det_mult_columns:\nshows \"det (mult_column A a k) = k * det A\"\nproof -\nhave \"mult_column A a k = transpose (mult_row (transpose A) a k)\" unfolding transpose_def mult_row_def mult_column_def by vector\nhence \"det (mult_column A a k) = det (transpose (mult_row (transpose A) a k))\" by simp\nalso have \"... = det (mult_row (transpose A) a k)\" unfolding det_transpose ..\nalso have \"... = k * det (transpose A)\" unfolding det_mult_row ..\nalso have \"... = k * det A\" unfolding det_transpose ..\nfinally show ?thesis .\nqed\n\nlemma det_column_add:\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (column_add A i j q) = det A\"\nproof -\nhave \"(column_add A i j q) = (transpose (row_add (transpose A) i j q))\" unfolding transpose_def column_add_def row_add_def by vector\nhence \"det (column_add A i j q) = det (transpose (row_add (transpose A) i j q))\" by simp\nalso have \"... = det (row_add (transpose A) i j q)\" unfolding det_transpose ..\nalso have \"... = det A\" unfolding det_row_add'[OF i_not_j] det_transpose ..\nfinally show ?thesis .\nqed\n\nsubsection\\<open>Proving that the determinant can be computed by means of the Gauss Jordan algorithm\\<close>\n\nsubsubsection\\<open>Previous properties\\<close>\n\nlemma det_row_add_iterate_upt_n:\nfixes A::\"'a::{comm_ring_1}^'n::{mod_type}^'n::{mod_type}\"\nassumes n: \"n<nrows A\"\nshows \"det (row_add_iterate A n i j) = det A\"\nusing n\nproof (induct n arbitrary: A)\ncase 0\nshow ?case unfolding row_add_iterate.simps using det_row_add'[of 0 i A] by auto\nnext\ncase (Suc n)\nshow ?case  unfolding row_add_iterate.simps\nproof (auto)\nshow \"det (row_add_iterate A n i j) = det A\" using Suc.hyps Suc.prems by simp\nassume Suc_n_not_i: \"Suc n \\<noteq> to_nat i\"\nhave \"det (row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j) \n= det (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\nproof (rule Suc.hyps, unfold nrows_def)\nshow \" n < CARD('n)\" using Suc.prems unfolding nrows_def by auto\nqed\nalso have \"... = det A\"\n  proof (rule det_row_add',rule ccontr, simp)\n    assume \"from_nat (Suc n) = i\"\n      hence \"to_nat (from_nat (Suc n)::'n) = to_nat i\" by simp\n      hence \"(Suc n) = to_nat i\" unfolding to_nat_from_nat_id[OF Suc.prems[unfolded nrows_def]] .\n      thus False using Suc_n_not_i by contradiction\n    qed\nfinally show \"det (row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j) = det A\" .\nqed\nqed\n\n\ncorollary det_row_add_iterate:\nfixes A::\"'a::{comm_ring_1}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det (row_add_iterate A (nrows A - 1) i j) = det A\"\nby (metis det_row_add_iterate_upt_n diff_less neq0_conv nrows_not_0 zero_less_one)\n\n\n\nlemma det_Gauss_Jordan_in_ij:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\ndefines A': \"A'== mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) $ i $ j)\"\nshows \"det (Gauss_Jordan_in_ij A i j) = det A' \"\nproof -\nhave nrows_eq: \"nrows A' = nrows A\" unfolding nrows_def by simp\nhave \"row_add_iterate A' (nrows A - 1) i j  =  Gauss_Jordan_in_ij A i j\" using row_add_iterate_eq_Gauss_Jordan_in_ij  unfolding A' .\nhence \"det (Gauss_Jordan_in_ij A i j) = det (row_add_iterate A' (nrows A - 1) i j)\" by simp\nalso have \"... = det A'\" by (rule det_row_add_iterate[of A', unfolded nrows_eq])\nfinally show ?thesis .\nqed\n\n\nlemma det_Gauss_Jordan_in_ij_1:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\ndefines A': \"A'== mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) $ i $ j)\"\nassumes i: \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) = i\"\nshows \"det (Gauss_Jordan_in_ij A i j) = 1/(A$i$j) * det A\"\nproof -\nhave \"det (Gauss_Jordan_in_ij A i j) = det A' \" using det_Gauss_Jordan_in_ij unfolding A' by auto\nalso have \"... = 1/(A$i$j) * det A\" unfolding A' det_mult_row unfolding i det_interchange_rows by auto\nfinally show ?thesis .\nqed\n\n\nlemma det_Gauss_Jordan_in_ij_2:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\ndefines A': \"A'== mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) $ i $ j)\"\nassumes i: \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) \\<noteq> i\"\nshows \"det (Gauss_Jordan_in_ij A i j) = - 1/(A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) * det A\"\nproof -\nhave \"det (Gauss_Jordan_in_ij A i j) = det A' \" using det_Gauss_Jordan_in_ij unfolding A' by auto\nalso have \"... = - 1/(A$ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $j) * det A\" unfolding A' det_mult_row unfolding det_interchange_rows using i by auto\nfinally show ?thesis .\nqed\n\nsubsubsection\\<open>Definitions\\<close>\n\ntext\\<open>The following definitions allow the computation of the determinant of a matrix using the Gauss-Jordan algorithm. In the first component the determinant of each transformation\nis accumulated and the second component contains the matrix transformed into a reduced row echelon form matrix\\<close>\n\ndefinition Gauss_Jordan_in_ij_det_P :: \"'a::{semiring_1, inverse, one, uminus}^'m^'n::{finite, ord}=> 'n=>'m=>('a \\<times> ('a^'m^'n::{finite, ord}))\"\n  where \"Gauss_Jordan_in_ij_det_P A i j = (let n = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) in (if i = n then 1/(A $ i $ j) else - 1/(A $ n $ j), Gauss_Jordan_in_ij A i j))\"\n\ndefinition Gauss_Jordan_column_k_det_P where \"Gauss_Jordan_column_k_det_P A' k =\n(let det_P= fst A'; i = fst (snd A'); A = snd (snd A'); from_nat_i = from_nat i; from_nat_k = from_nat k\n in if (\\<forall>m\\<ge>from_nat_i. A $ m $ from_nat_k = 0) \\<or> i = nrows A then (det_P, i, A)\n    else let gauss = Gauss_Jordan_in_ij_det_P A (from_nat_i) (from_nat_k) in (fst gauss * det_P, i + 1, snd gauss))\"\n\ndefinition Gauss_Jordan_upt_k_det_P \n  where \"Gauss_Jordan_upt_k_det_P A k = (let foldl = foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k] in (fst foldl, snd (snd foldl)))\"\ndefinition Gauss_Jordan_det_P \n  where \"Gauss_Jordan_det_P A = Gauss_Jordan_upt_k_det_P A (ncols A - 1)\"\n\nsubsubsection\\<open>Proofs\\<close>\n\ntext\\<open>This is an equivalent definition created to achieve a more efficient computation.\\<close>\nlemma Gauss_Jordan_in_ij_det_P_code[code]:\nshows \"Gauss_Jordan_in_ij_det_P A i j = \n    (let n = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n);\n         interchange_A = interchange_rows A i n;\n         A' = mult_row interchange_A i (1 / interchange_A $ i $ j) in (if i = n then 1/(A $ i $ j) else - 1/(A $ n $ j), Gauss_Jordan_wrapper i j A' interchange_A))\"\n         unfolding Gauss_Jordan_in_ij_det_P_def Gauss_Jordan_in_ij_def Gauss_Jordan_wrapper_def Let_def by auto\n\n\nlemma det_Gauss_Jordan_in_ij_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\nshows \"(fst (Gauss_Jordan_in_ij_det_P A i j)) * det A  = det (snd (Gauss_Jordan_in_ij_det_P A i j))\"\nunfolding Gauss_Jordan_in_ij_det_P_def Let_def fst_conv snd_conv\nusing det_Gauss_Jordan_in_ij_1[of A j i]\nusing det_Gauss_Jordan_in_ij_2[of A j i] by auto\n\n\nlemma det_Gauss_Jordan_column_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes det: \"det_P * det B = det A\"\nshows \"(fst (Gauss_Jordan_column_k_det_P (det_P,i,A) k)) * det B = det (snd (snd (Gauss_Jordan_column_k_det_P (det_P,i,A) k)))\"\nproof (unfold Gauss_Jordan_column_k_det_P_def Let_def, auto simp add: assms)\nfix m\nassume i_not_nrows: \"i \\<noteq> nrows A\"\nand i_less_m: \"from_nat i \\<le> m\"\nand Amk_not_0: \"A $ m $ from_nat k \\<noteq> 0\"\nshow  \"fst (Gauss_Jordan_in_ij_det_P A (from_nat i) (from_nat k)) * det_P * det B =\n        det (snd (Gauss_Jordan_in_ij_det_P A (from_nat i) (from_nat k)))\" unfolding mult.assoc det \n        unfolding det_Gauss_Jordan_in_ij_det_P ..\nqed\n\n\nlemma det_Gauss_Jordan_upt_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"(fst (Gauss_Jordan_upt_k_det_P A k)) * det A = det (snd (Gauss_Jordan_upt_k_det_P A k))\"\nproof (induct k)\ncase 0\nshow ?case\nunfolding Gauss_Jordan_upt_k_det_P_def Let_def unfolding fst_conv snd_conv by (simp add:det_Gauss_Jordan_column_k_det_P)\nnext\ncase (Suc k)\nhave suc_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [Suc k]\" by simp\nhave fold_expand: \"(foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k]) \n= (fst (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k]), fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])),\n  snd (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])))\" by simp\nshow ?case unfolding Gauss_Jordan_upt_k_det_P_def Let_def \nunfolding suc_rw foldl_append List.foldl.simps fst_conv snd_conv\nby(subst (1 2) fold_expand, rule det_Gauss_Jordan_column_k_det_P, rule Suc.hyps[unfolded Gauss_Jordan_upt_k_det_P_def Let_def fst_conv snd_conv])\nqed\n\n\nlemma det_Gauss_Jordan_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"(fst (Gauss_Jordan_det_P A)) * det A = det (snd (Gauss_Jordan_det_P A))\"\nusing det_Gauss_Jordan_upt_k_det_P unfolding Gauss_Jordan_det_P_def by simp\n\n\ndefinition upper_triangular_upt_k where \"upper_triangular_upt_k A k = (\\<forall>i j. j<i \\<and> to_nat j < k \\<longrightarrow> A $ i $ j = 0)\"\ndefinition upper_triangular where \"upper_triangular A = (\\<forall>i j. j<i \\<longrightarrow> A $ i $ j = 0)\"\n\nlemma upper_triangular_upt_imp_upper_triangular:\nassumes \"upper_triangular_upt_k A (nrows A)\"\nshows \"upper_triangular A\"\nusing assms unfolding upper_triangular_upt_k_def upper_triangular_def nrows_def\nusing to_nat_less_card[where ?'a='b] by blast\n\nlemma rref_imp_upper_triagular_upt:\nfixes A::\"'a::{one, zero}^'n::{mod_type}^'n::{mod_type}\"\nassumes \"reduced_row_echelon_form A\"\nshows \"upper_triangular_upt_k A k\"\nproof (induct k)\ncase 0\nshow ?case unfolding upper_triangular_upt_k_def by simp\nnext\ncase (Suc k)\nshow ?case unfolding upper_triangular_upt_k_def proof (clarify)\nfix i j::'n\nassume j_less_i: \"j < i\" and j_less_suc_k: \"to_nat j < Suc k\"\nshow \"A $ i $ j = 0\"\n  proof (cases \"to_nat j < k\")\n  case True\n  thus ?thesis using Suc.hyps unfolding upper_triangular_upt_k_def using j_less_i True by auto\n  next\n  case False\n  hence j_eq_k: \"to_nat j = k\" using j_less_suc_k by simp\n  have rref_suc: \"reduced_row_echelon_form_upt_k A (Suc k)\" by (metis assms rref_implies_rref_upt)\n \n  show ?thesis\n    proof (cases \"A $ i $ from_nat k = 0\")\n      case True\n      have \"from_nat k = j\" by (metis from_nat_to_nat_id j_eq_k)\n      thus ?thesis using True by simp\n      next\n      case False\n      have zero_i_k: \"is_zero_row_upt_k i k A\" unfolding is_zero_row_upt_k_def\n      by (metis (hide_lams, mono_tags) Suc.hyps leD le_less_linear less_imp_le j_eq_k j_less_i le_trans to_nat_mono' upper_triangular_upt_k_def)\n      have not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) A\" unfolding is_zero_row_upt_k_def using False by (metis j_eq_k lessI to_nat_from_nat)      \n      have Least_eq: \"(LEAST n. A $ i $ n \\<noteq> 0) = from_nat k\"\n        proof (rule Least_equality)\n           show \"A $ i $ from_nat k \\<noteq> 0\" using False by simp\n           show \"\\<And>y. A $ i $ y \\<noteq> 0 \\<Longrightarrow> from_nat k \\<le> y\" by (metis (full_types) is_zero_row_upt_k_def not_le_imp_less to_nat_le zero_i_k)\n        qed\n      have i_not_k: \"i \\<noteq> from_nat k\" by (metis less_irrefl from_nat_to_nat_id j_eq_k j_less_i)\n      show ?thesis using rref_upt_condition4_explicit[OF rref_suc not_zero_i_suc_k i_not_k] unfolding Least_eq \n      using rref_upt_condition1_explicit[OF rref_suc]\n      using Suc.hyps unfolding upper_triangular_upt_k_def \n      by (metis (mono_tags) leD not_le_imp_less is_zero_row_upt_k_def is_zero_row_upt_k_suc j_eq_k j_less_i not_zero_i_suc_k to_nat_from_nat to_nat_mono')  \nqed\nqed\nqed\nqed\n\nlemma rref_imp_upper_triagular:\nassumes \"reduced_row_echelon_form A\"\nshows \"upper_triangular A\" \nby (metis assms rref_imp_upper_triagular_upt upper_triangular_upt_imp_upper_triangular)\n\n\nlemma det_Gauss_Jordan[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det (Gauss_Jordan A) = prod (\\<lambda>i. (Gauss_Jordan A)$i$i) (UNIV:: 'n set)\"\nusing det_upperdiagonal rref_imp_upper_triagular[OF rref_Gauss_Jordan[of A]] unfolding upper_triangular_def by blast\n\n\nlemma snd_Gauss_Jordan_in_ij_det_P_is_snd_Gauss_Jordan_in_ij_PA:\nshows \"snd (Gauss_Jordan_in_ij_det_P A i j) = snd (Gauss_Jordan_in_ij_PA (P,A) i j)\"\nunfolding Gauss_Jordan_in_ij_det_P_def Gauss_Jordan_in_ij_PA_def \nunfolding  Gauss_Jordan_in_ij_def Let_def snd_conv fst_conv ..\n\n\nlemma snd_Gauss_Jordan_column_k_det_P_is_snd_Gauss_Jordan_column_k_PA:\nshows \"snd (Gauss_Jordan_column_k_det_P (n,i,A) k) = snd (Gauss_Jordan_column_k_PA (P,i,A) k)\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def Let_def snd_conv unfolding fst_conv\nusing snd_Gauss_Jordan_in_ij_det_P_is_snd_Gauss_Jordan_in_ij_PA by auto\n\n\nlemma det_fst_row_add_iterate_PA:\nfixes A::\"'a::{comm_ring_1}^'n::{mod_type}^'n::{mod_type}\"\nassumes n: \"n<nrows A\"\nshows \"det (fst (row_add_iterate_PA (P,A) n i j)) = det P\"\nusing n\nproof (induct n arbitrary: P A)\ncase 0\nshow ?case unfolding row_add_iterate_PA.simps using det_row_add'[of 0 i P] by simp\nnext\ncase (Suc n)\nhave n: \"n<nrows A\" using Suc.prems by simp\nshow ?case\nproof (cases \"Suc n = to_nat i\")\ncase True show ?thesis unfolding row_add_iterate_PA.simps if_P[OF True] using Suc.hyps[OF n] .\nnext\ncase False \ndefine P' where \"P' = row_add P (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\ndefine A' where \"A' = row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\nhave n2: \"n< nrows A'\" using n unfolding nrows_def .\nhave \"det (fst (row_add_iterate_PA (P, A) (Suc n) i j)) = det (fst (row_add_iterate_PA (P', A') n i j))\" unfolding row_add_iterate_PA.simps if_not_P[OF False] P'_def A'_def ..\nalso have \"... = det P'\" using Suc.hyps[OF n2] .\nalso have \"... = det P\" unfolding P'_def \nproof (rule det_row_add', rule ccontr, simp)\n    assume \"from_nat (Suc n) = i\"\n      hence \"to_nat (from_nat (Suc n)::'n) = to_nat i\" by simp\n      hence \"(Suc n) = to_nat i\" unfolding to_nat_from_nat_id[OF Suc.prems[unfolded nrows_def]] .\n      thus False using False by contradiction\n    qed\nfinally show ?thesis .\nqed\nqed\n\n\n\nlemma det_fst_Gauss_Jordan_in_ij_PA_eq_fst_Gauss_Jordan_in_ij_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_in_ij_det_P A i j) * det P = det (fst (Gauss_Jordan_in_ij_PA (P,A) i j))\"\nproof -\ndefine P' where \"P' = mult_row (interchange_rows P i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j)\"\ndefine A' where \"A' = mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j)\"\nhave \"det (fst (Gauss_Jordan_in_ij_PA (P,A) i j)) = det (fst (row_add_iterate_PA (P',A') (nrows A - 1) i j))\"\nunfolding fst_row_add_iterate_PA_eq_fst_Gauss_Jordan_in_ij_PA[symmetric] A'_def P'_def ..\nalso have \"...= det P'\" by (rule det_fst_row_add_iterate_PA, simp add: nrows_def)\nalso have \"... = (if i = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) then 1 / A $ i $ j else - 1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) * det P\"\nproof (cases \"i = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\")\ncase True show ?thesis \nunfolding if_P[OF True] P'_def unfolding True[symmetric] unfolding interchange_same_rows unfolding det_mult_row ..\nnext\ncase False\nshow ?thesis unfolding if_not_P[OF False] P'_def unfolding det_mult_row unfolding det_interchange_different_rows[OF False] by simp\nqed\nalso have \"... = fst (Gauss_Jordan_in_ij_det_P A i j) * det P\"\nunfolding Gauss_Jordan_in_ij_det_P_def by simp\nfinally show ?thesis ..\nqed\n\n\nlemma det_fst_Gauss_Jordan_column_k_PA_eq_fst_Gauss_Jordan_column_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_column_k_det_P (det P,i,A) k) = det (fst (Gauss_Jordan_column_k_PA (P,i,A) k))\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def Let_def snd_conv fst_conv\nusing det_fst_Gauss_Jordan_in_ij_PA_eq_fst_Gauss_Jordan_in_ij_det_P by auto\n\n\nlemma fst_snd_Gauss_Jordan_column_k_det_P_eq_fst_snd_Gauss_Jordan_column_k_PA:\nshows \"fst (snd (Gauss_Jordan_column_k_det_P (n,i,A) k)) = fst (snd (Gauss_Jordan_column_k_PA (P,i,A) k))\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def Let_def snd_conv fst_conv\nby auto\n\n\ntext\\<open>The way of proving the following lemma is very similar to the demonstration of @{thm \"rref_and_index_Gauss_Jordan_upt_k\"}.\\<close>\n\nlemma foldl_Gauss_Jordan_column_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows det_fst_Gauss_Jordan_upt_k_PA_eq_fst_Gauss_Jordan_upt_k_det_P: \"fst (Gauss_Jordan_upt_k_det_P A k) = det (fst (Gauss_Jordan_upt_k_PA A k))\"\nand snd_Gauss_Jordan_upt_k_det_P_is_snd_Gauss_Jordan_upt_k_PA: \"snd (Gauss_Jordan_upt_k_det_P A k) = snd (Gauss_Jordan_upt_k_PA A k)\"\nand fst_snd_foldl_Gauss_det_P_PA: \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k]))\"\nproof (induct k)\ncase 0\nshow \"fst (Gauss_Jordan_upt_k_det_P A 0) = det (fst (Gauss_Jordan_upt_k_PA A 0))\"\nunfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def\nby (simp, metis det_fst_Gauss_Jordan_column_k_PA_eq_fst_Gauss_Jordan_column_k_det_P det_I)\nshow \"snd (Gauss_Jordan_upt_k_det_P A 0) = snd (Gauss_Jordan_upt_k_PA A 0)\"\nunfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def snd_conv\napply auto using snd_Gauss_Jordan_column_k_det_P_is_snd_Gauss_Jordan_column_k_PA by metis\nshow \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc 0])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc 0]))\"\nusing [[unfold_abs_def = false]]\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def apply auto\nusing fst_snd_Gauss_Jordan_column_k_det_P_eq_fst_snd_Gauss_Jordan_column_k_PA by metis\nnext\nfix k\nassume hyp1: \"fst (Gauss_Jordan_upt_k_det_P A k) = det (fst (Gauss_Jordan_upt_k_PA A k))\"\nand hyp2: \"snd (Gauss_Jordan_upt_k_det_P A k) = snd (Gauss_Jordan_upt_k_PA A k)\"\nand hyp3: \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k]))\"\nhave list_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [Suc k]\" by simp\nhave det_mat_nn: \"det (mat 1::'a^'n::{mod_type}^'n::{mod_type}) = 1\" using det_I by simp\ndefine f where \"f = foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k]\"\ndefine g where \"g = foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k]\"\nhave f_rw: \"f = (fst f, fst (snd f), snd(snd f))\" by simp\nhave g_rw: \"g = (fst g, fst (snd g), snd(snd g))\" by simp\nhave fst_snd: \"fst (snd f) = fst (snd g)\" unfolding f_def g_def using hyp3 unfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv .\nhave snd_snd: \"snd (snd f) = snd (snd g)\" unfolding f_def g_def using hyp2 unfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv .\nhave fst_det: \"fst f = det (fst g)\" unfolding f_def g_def using hyp1 unfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def fst_conv by simp\nshow \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k])) \\<Longrightarrow>\n        fst (Gauss_Jordan_upt_k_det_P A (Suc k)) = det (fst (Gauss_Jordan_upt_k_PA A (Suc k)))\"\nunfolding Gauss_Jordan_upt_k_det_P_def  \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw foldl_append unfolding List.foldl.simps\nunfolding f_def[symmetric] g_def[symmetric]\napply (subst f_rw)\napply (subst g_rw)\nunfolding fst_snd snd_snd fst_det\nby (rule det_fst_Gauss_Jordan_column_k_PA_eq_fst_Gauss_Jordan_column_k_det_P)\nshow \"snd (Gauss_Jordan_upt_k_det_P A (Suc k)) = snd (Gauss_Jordan_upt_k_PA A (Suc k))\"\nunfolding Gauss_Jordan_upt_k_det_P_def  \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw foldl_append unfolding List.foldl.simps\nunfolding f_def[symmetric] g_def[symmetric]\napply (subst f_rw)\napply (subst g_rw)\nunfolding fst_snd snd_snd fst_det\nby (metis fst_snd prod.collapse snd_Gauss_Jordan_column_k_det_P_is_snd_Gauss_Jordan_column_k_PA snd_eqD snd_snd)\nshow \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc (Suc k)])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc (Suc k)]))\"\nunfolding Gauss_Jordan_upt_k_det_P_def  \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw foldl_append unfolding List.foldl.simps\nunfolding f_def[symmetric] g_def[symmetric]\napply (subst f_rw)\napply (subst g_rw)\nunfolding fst_snd snd_snd fst_det by (rule fst_snd_Gauss_Jordan_column_k_det_P_eq_fst_snd_Gauss_Jordan_column_k_PA)\nqed\n\n\n\nlemma snd_Gauss_Jordan_det_P_is_Gauss_Jordan:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"snd (Gauss_Jordan_det_P A) = (Gauss_Jordan A)\"\nunfolding Gauss_Jordan_det_P_def Gauss_Jordan_def unfolding snd_Gauss_Jordan_upt_k_det_P_is_snd_Gauss_Jordan_upt_k_PA \nsnd_Gauss_Jordan_upt_k_PA ..\n\n\nlemma det_snd_Gauss_Jordan_det_P[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det (snd (Gauss_Jordan_det_P A)) = prod (\\<lambda>i. (snd (Gauss_Jordan_det_P A))$i$i) (UNIV:: 'n set)\"\nunfolding snd_Gauss_Jordan_det_P_is_Gauss_Jordan det_Gauss_Jordan ..\n\n\nlemma det_fst_Gauss_Jordan_PA_eq_fst_Gauss_Jordan_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_det_P A) = det (fst (Gauss_Jordan_PA A))\"\nby (unfold Gauss_Jordan_det_P_def Gauss_Jordan_PA_def, rule det_fst_Gauss_Jordan_upt_k_PA_eq_fst_Gauss_Jordan_upt_k_det_P)\n\n\nlemma fst_Gauss_Jordan_det_P_not_0:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_det_P A) \\<noteq> 0\"\nunfolding det_fst_Gauss_Jordan_PA_eq_fst_Gauss_Jordan_det_P \nby (metis (mono_tags) det_I det_mul invertible_fst_Gauss_Jordan_PA matrix_inv_right mult_zero_left zero_neq_one)\n\n\nlemma det_code_equation[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det A = (let A' = Gauss_Jordan_det_P A in prod (\\<lambda>i. (snd (A'))$i$i) (UNIV::'n set)/(fst (A')))\"\nunfolding Let_def using det_Gauss_Jordan_det_P[of A]\nunfolding det_snd_Gauss_Jordan_det_P\nby (simp add: fst_Gauss_Jordan_det_P_not_0 nonzero_eq_divide_eq ac_simps)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gauss_Jordan/Determinants2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7859846095701669}}
{"text": "theory Ex1_3\n  imports Main \nbegin \n  \nprimrec alls :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where \n  \"alls _ [] = True\"|\n  \"alls P (x # xs) = (P x \\<and> alls P xs)\"\n  \nprimrec exs :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where \n  \"exs _ [] = False\"|\n  \"exs P (x # xs) = (P x \\<or> exs P xs)\"\n  \n  \nlemma \"alls (\\<lambda>x. P x \\<and> Q x) xs = (alls P xs \\<and> alls Q xs)\" by (induct xs , auto)\n    \nlemma helper : \"alls P (xs @ ys) = (alls P xs \\<and>  alls P ys)\" by (induct xs ; simp)    \n    \nlemma \"alls  P (rev xs) = alls P xs\" by (induct xs, auto simp add : helper)\n    \n(* lemma \"exs (\\<lambda>x . P x \\<and> Q x) xs = (exs  P xs \\<and> exs Q xs)\" quickcheck *)\n    \nlemma \"P a  \\<Longrightarrow> P b = False \\<Longrightarrow> Q b \\<Longrightarrow> Q a = False  \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> exs (\\<lambda>x. P x \\<and> Q x) [a ,b] = (exs P [a,b] \\<and> exs Q [a,b]) \\<Longrightarrow> False\" by simp\n    \nlemma \"exs P (map f xs) = exs (P o f) xs \" by (induct xs; simp)\n\nlemma helper2 : \"exs P (xs @ ys) = (exs P xs \\<or> exs P ys)\" by (induct xs, auto)    \n    \nlemma \"exs P (rev xs) = exs P xs\" \nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume a:\"exs P (rev xs) = exs P xs\" \n  have \"exs P (rev (a # xs)) = exs P (rev xs @ [a])\" by simp\n  also have \"\\<dots> = (exs P (rev xs) \\<or> exs P [a])\" by (simp add : helper2)\n  also have \"\\<dots> = (exs P xs \\<or> exs P [a])\"  by (simp add : a)\n  finally show ?case by auto\nqed\n  \nlemma \"exs (\\<lambda>x . P x \\<or> Q x) xs = exs P xs \\<or> exs Q xs\"  by (induct xs; auto)\n    \n    \nlemma \"exs P xs = (\\<not> (alls (\\<lambda>x . \\<not> (P x)) xs))\" by (induct  xs, simp_all)\n\nprimrec is_in :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where \n  \"is_in _ []= False \"|\n  \"is_in val (x # xs) = ((val = x) \\<or> is_in val xs) \"\n  \nlemma \"is_in a xs = exs (\\<lambda>x . x = a) xs\" by (induct xs, auto)\n    \nprimrec nodups :: \"'a list \\<Rightarrow> bool\" where \n  \"nodups [] = True\"|\n  \"nodups (x#xs) = ((\\<not>(is_in x xs))  \\<and> nodups xs)\"\n  \nprimrec deldups :: \"'a list \\<Rightarrow> 'a list\" where\n  \"deldups [] = []\"|\n  \"deldups (x#xs) = (if is_in x xs  then deldups xs else x # deldups xs)\"\n \nlemma \"length (deldups xs) \\<le> length xs\" by (induct xs, simp_all)\n\nlemma helper3 : \"\\<not> (is_in x xs) \\<Longrightarrow> \\<not> (is_in x (deldups xs))\" by (induct xs, simp_all)    \n    \nlemma \"nodups (deldups xs)\" \nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume hyp:\"nodups (deldups xs)\"\n  show ?case \n  proof (cases \"is_in a xs\")\n    case True\n    assume a:\"is_in a xs\"\n    show ?thesis using hyp a by auto\n  next\n    case False\n    assume a:\"\\<not> is_in a xs\"\n    have \"nodups (deldups (a # xs)) = nodups (a # deldups (xs))\" using a by simp\n    also have \"\\<dots> = ((\\<not>(is_in a (deldups xs))) \\<and>  nodups (deldups xs))\" by (simp only : nodups.simps)\n    also have \"\\<dots> = ((\\<not>(is_in a (deldups xs))) \\<and> True )\" using hyp by simp\n    also have \"\\<dots> = (True \\<and> True)\" using helper3 and a by simp\n    finally show ?thesis using helper3 and a and hyp by simp\n  qed\nqed\n    \n(* lemma \"deldups (rev xs) = rev (deldups xs)\" quickcheck *)\n  \nlemma \"let ls = [x,y,x,x] in deldups (rev ls) = rev (deldups ls) \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> False \" by simp\n  ", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/1. Lists/Ex1_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.785901535481626}}
{"text": "   \ntheory Spec\n  imports Main \"~~/src/HOL/Library/Sublist\"\nbegin\n\nsection {* Sequential Composition of Languages *}\n\ndefinition\n  Sequ :: \"string set \\<Rightarrow> string set \\<Rightarrow> string set\" (\"_ ;; _\" [100,100] 100)\nwhere \n  \"A ;; B = {s1 @ s2 | s1 s2. s1 \\<in> A \\<and> s2 \\<in> B}\"\n\ntext {* Two Simple Properties about Sequential Composition *}\n\nlemma Sequ_empty_string [simp]:\n  shows \"A ;; {[]} = A\"\n  and   \"{[]} ;; A = A\"\nby (simp_all add: Sequ_def)\n\nlemma Sequ_empty [simp]:\n  shows \"A ;; {} = {}\"\n  and   \"{} ;; A = {}\"\nby (simp_all add: Sequ_def)\n\n\nsection {* Semantic Derivative (Left Quotient) of Languages *}\n\ndefinition\n  Der :: \"char \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Der c A \\<equiv> {s. c # s \\<in> A}\"\n\ndefinition\n  Ders :: \"string \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Ders s A \\<equiv> {s'. s @ s' \\<in> A}\"\n\nlemma Der_null [simp]:\n  shows \"Der c {} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_empty [simp]:\n  shows \"Der c {[]} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_char [simp]:\n  shows \"Der c {[d]} = (if c = d then {[]} else {})\"\nunfolding Der_def\nby auto\n\nlemma Der_union [simp]:\n  shows \"Der c (A \\<union> B) = Der c A \\<union> Der c B\"\nunfolding Der_def\nby auto\n\nlemma Der_Sequ [simp]:\n  shows \"Der c (A ;; B) = (Der c A) ;; B \\<union> (if [] \\<in> A then Der c B else {})\"\nunfolding Der_def Sequ_def\nby (auto simp add: Cons_eq_append_conv)\n\n\nsection {* Kleene Star for Languages *}\n\ninductive_set\n  Star :: \"string set \\<Rightarrow> string set\" (\"_\\<star>\" [101] 102)\n  for A :: \"string set\"\nwhere\n  start[intro]: \"[] \\<in> A\\<star>\"\n| step[intro]:  \"\\<lbrakk>s1 \\<in> A; s2 \\<in> A\\<star>\\<rbrakk> \\<Longrightarrow> s1 @ s2 \\<in> A\\<star>\"\n\n(* Arden's lemma *)\n\nlemma Star_cases:\n  shows \"A\\<star> = {[]} \\<union> A ;; A\\<star>\"\nunfolding Sequ_def\nby (auto) (metis Star.simps)\n\nlemma Star_decomp: \n  assumes \"c # x \\<in> A\\<star>\" \n  shows \"\\<exists>s1 s2. x = s1 @ s2 \\<and> c # s1 \\<in> A \\<and> s2 \\<in> A\\<star>\"\nusing assms\nby (induct x\\<equiv>\"c # x\" rule: Star.induct) \n   (auto simp add: append_eq_Cons_conv)\n\nlemma Star_Der_Sequ: \n  shows \"Der c (A\\<star>) \\<subseteq> (Der c A) ;; A\\<star>\"\nunfolding Der_def Sequ_def\nby(auto simp add: Star_decomp)\n\n\nlemma Der_star [simp]:\n  shows \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\"\nproof -    \n  have \"Der c (A\\<star>) = Der c ({[]} \\<union> A ;; A\\<star>)\"  \n    by (simp only: Star_cases[symmetric])\n  also have \"... = Der c (A ;; A\\<star>)\"\n    by (simp only: Der_union Der_empty) (simp)\n  also have \"... = (Der c A) ;; A\\<star> \\<union> (if [] \\<in> A then Der c (A\\<star>) else {})\"\n    by simp\n  also have \"... =  (Der c A) ;; A\\<star>\"\n    using Star_Der_Sequ by auto\n  finally show \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\" .\nqed\n\n\nsection {* Regular Expressions *}\n\ndatatype rexp =\n  ZERO\n| ONE\n| CR char\n| SEQ rexp rexp\n| ALT rexp rexp\n| STAR rexp\n\nsection {* Semantics of Regular Expressions *}\n \nfun\n  L :: \"rexp \\<Rightarrow> string set\"\nwhere\n  \"L (ZERO) = {}\"\n| \"L (ONE) = {[]}\"\n| \"L (CR c) = {[c]}\"\n| \"L (SEQ r1 r2) = (L r1) ;; (L r2)\"\n| \"L (ALT r1 r2) = (L r1) \\<union> (L r2)\"\n| \"L (STAR r) = (L r)\\<star>\"\n\n\nsection {* Nullable, Derivatives *}\n\nfun\n nullable :: \"rexp \\<Rightarrow> bool\"\nwhere\n  \"nullable (ZERO) = False\"\n| \"nullable (ONE) = True\"\n| \"nullable (CR c) = False\"\n| \"nullable (ALT r1 r2) = (nullable r1 \\<or> nullable r2)\"\n| \"nullable (SEQ r1 r2) = (nullable r1 \\<and> nullable r2)\"\n| \"nullable (STAR r) = True\"\n\n\nfun\n der :: \"char \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"der c (ZERO) = ZERO\"\n| \"der c (ONE) = ZERO\"\n| \"der c (CR d) = (if c = d then ONE else ZERO)\"\n| \"der c (ALT r1 r2) = ALT (der c r1) (der c r2)\"\n| \"der c (SEQ r1 r2) = \n     (if nullable r1\n      then ALT (SEQ (der c r1) r2) (der c r2)\n      else SEQ (der c r1) r2)\"\n| \"der c (STAR r) = SEQ (der c r) (STAR r)\"\n\nfun \n ders :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"ders [] r = r\"\n| \"ders (c # s) r = ders s (der c r)\"\n\n\nlemma nullable_correctness:\n  shows \"nullable r  \\<longleftrightarrow> [] \\<in> (L r)\"\n  apply(induct r)\nby (induct r) (auto simp add: Sequ_def) \n\nlemma der_correctness:\n  shows \"L (der c r) = Der c (L r)\"\nby (induct r) (simp_all add: nullable_correctness)\n\nlemma ders_correctness:\n  shows \"L (ders s r) = Ders s (L r)\"\nby (induct s arbitrary: r)\n   (simp_all add: Ders_def der_correctness Der_def)\n\nlemma ders_append:\n  shows \"ders (s1 @ s2) r = ders s2 (ders s1 r)\"\n  apply(induct s1 arbitrary: s2 r)\n  apply(auto)\n  done\n\n\nsection {* Values *}\n\ndatatype val = \n  Void\n| Char char\n| Seq val val\n| Right val\n| Left val\n| Stars \"val list\"\n\n\nsection {* The string behind a value *}\n\nfun \n  flat :: \"val \\<Rightarrow> string\"\nwhere\n  \"flat (Void) = []\"\n| \"flat (Char c) = [c]\"\n| \"flat (Left v) = flat v\"\n| \"flat (Right v) = flat v\"\n| \"flat (Seq v1 v2) = (flat v1) @ (flat v2)\"\n| \"flat (Stars []) = []\"\n| \"flat (Stars (v#vs)) = (flat v) @ (flat (Stars vs))\" \n\nabbreviation\n  \"flats vs \\<equiv> concat (map flat vs)\"\n\nlemma flat_Stars [simp]:\n \"flat (Stars vs) = flats vs\"\nby (induct vs) (auto)\n\nlemma Star_concat:\n  assumes \"\\<forall>s \\<in> set ss. s \\<in> A\"  \n  shows \"concat ss \\<in> A\\<star>\"\nusing assms by (induct ss) (auto)\n\nlemma Star_cstring:\n  assumes \"s \\<in> A\\<star>\"\n  shows \"\\<exists>ss. concat ss = s \\<and> (\\<forall>s \\<in> set ss. s \\<in> A \\<and> s \\<noteq> [])\"\nusing assms\napply(induct rule: Star.induct)\napply(auto)[1]\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(erule exE)\napply(clarify)\napply(case_tac \"s1 = []\")\napply(rule_tac x=\"ss\" in exI)\napply(simp)\napply(rule_tac x=\"s1#ss\" in exI)\napply(simp)\ndone\n\n\nsection {* Lexical Values *}\ninductive \n  Prf3 :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<bbar> _ : _\" [100, 100] 100)\nwhere\n \"\\<lbrakk>\\<bbar> v1 : r1; \\<bbar>   v2 : r2\\<rbrakk> \\<Longrightarrow> \\<bbar>  Seq v1 v2 : SEQ r1 r2\"\n| \"\\<bbar> v1 : r1 \\<Longrightarrow> \\<bbar> Left v1 : ALT r1 r2\"\n| \"\\<bbar> v2 : r2 \\<Longrightarrow> \\<bbar> Right v2 : ALT r1 r2\"\n| \"\\<bbar> Void : ONE\"\n| \"\\<bbar> Char c : CR c\"\n| \"\\<forall>v \\<in> set vs. \\<bbar> v : r \\<and>(flat v = [] \\<longrightarrow> length vs \\<le> 1)  \\<Longrightarrow> \\<bbar> Stars vs : STAR r\"\n\ninductive_cases Prf3_elims:\n  \"\\<bbar> v: ZERO\"\n  \"\\<bbar> v: SEQ r1 r2\"\n  \"\\<bbar> v: ALT r1 r2\"\n  \"\\<bbar> v : ONE\"\n  \"\\<bbar> v : CR c\"\n  \"\\<bbar> vs: STAR r\"\n\n\n\n\ninductive \n  Prf2 :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<turnstile> _ : _\" [100, 100] 100)\nwhere\n \"\\<lbrakk>\\<turnstile> v1 : r1; \\<turnstile>   v2 : r2\\<rbrakk> \\<Longrightarrow> \\<turnstile>  Seq v1 v2 : SEQ r1 r2\"\n| \"\\<turnstile> v1 : r1 \\<Longrightarrow> \\<turnstile> Left v1 : ALT r1 r2\"\n| \"\\<turnstile> v2 : r2 \\<Longrightarrow> \\<turnstile> Right v2 : ALT r1 r2\"\n| \"\\<turnstile> Void : ONE\"\n| \"\\<turnstile> Char c : CR c\"\n| \"\\<forall>v \\<in> set vs. \\<turnstile> v : r  \\<Longrightarrow> \\<turnstile> Stars vs : STAR r\"\n\ninductive_cases Prf2_elims:\n  \"\\<turnstile> v: ZERO\"\n  \"\\<turnstile> v: SEQ r1 r2\"\n  \"\\<turnstile> v: ALT r1 r2\"\n  \"\\<turnstile> v : ONE\"\n  \"\\<turnstile> v : CR c\"\n  \"\\<turnstile> vs: STAR r\"\n\n\n\nlemma Prf2_Stars_appendE:\n  assumes \" \\<turnstile> Stars (vs1@vs2) : STAR r\"\n  shows \"\\<turnstile> Stars vs1 : STAR r \\<and> \\<turnstile> Stars vs2 : STAR r\"\n  using assms\n  apply(rule Prf2_elims)\n  by (auto intro: Prf2.intros elim!: Prf2_elims)\n\nthm Prf2.intros\nthm Prf2_elims\n\n\n\ninductive \n  Prf :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<Turnstile> _ : _\" [100, 100] 100)\nwhere\n \"\\<lbrakk>\\<Turnstile> v1 : r1; \\<Turnstile> v2 : r2\\<rbrakk> \\<Longrightarrow> \\<Turnstile>  Seq v1 v2 : SEQ r1 r2\"\n| \"\\<Turnstile> v1 : r1 \\<Longrightarrow> \\<Turnstile> Left v1 : ALT r1 r2\"\n| \"\\<Turnstile> v2 : r2 \\<Longrightarrow> \\<Turnstile> Right v2 : ALT r1 r2\"\n| \"\\<Turnstile> Void : ONE\"\n| \"\\<Turnstile> Char c : CR c\"\n| \"\\<forall>v \\<in> set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> [] \\<Longrightarrow> \\<Turnstile> Stars vs : STAR r\"\n\ninductive_cases Prf_elims:\n  \"\\<Turnstile> v : ZERO\"\n  \"\\<Turnstile> v : SEQ r1 r2\"\n  \"\\<Turnstile> v : ALT r1 r2\"\n  \"\\<Turnstile> v : ONE\"\n  \"\\<Turnstile> v : CR c\"\n  \"\\<Turnstile> vs : STAR r\"\n\nlemma Prf_Stars_appendE:\n  assumes \"\\<Turnstile> Stars (vs1 @ vs2) : STAR r\"\n  shows \"\\<Turnstile> Stars vs1 : STAR r \\<and> \\<Turnstile> Stars vs2 : STAR r\" \nusing assms\nby (auto intro: Prf.intros elim!: Prf_elims)\n\n\n\nlemma Star_cval:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<Turnstile> v : r\"\n  shows \"\\<exists>vs. flats vs = concat ss \\<and> (\\<forall>v\\<in>set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> [])\"\nusing assms\napply(induct ss)\napply(auto)\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(case_tac \"flat v = []\")\napply(rule_tac x=\"vs\" in exI)\napply(simp)\napply(rule_tac x=\"v#vs\" in exI)\napply(simp)\ndone\n\nlemma Star2_cval:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<turnstile> v : r\"\n  shows \"\\<exists>vs. flats vs = concat ss \\<and> (\\<forall>v\\<in>set vs. \\<turnstile> v : r \\<and> flat v \\<noteq> [])\"\nusing assms\napply(induct ss)\napply(auto)\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(case_tac \"flat v = []\")\napply(rule_tac x=\"vs\" in exI)\napply(simp)\napply(rule_tac x=\"v#vs\" in exI)\napply(simp)\ndone\n\n\nlemma L_flat_Prf1:\n  assumes \"\\<Turnstile> v : r\" \n  shows \"flat v \\<in> L r\"\nusing assms\nby (induct) (auto simp add: Sequ_def Star_concat)\n\n\nlemma L_flat_2Prf1:\n  assumes \"\\<turnstile> v : r\"\n  shows \"flat v \\<in> L r\"\n  using assms\n  by (induct) (auto simp add: Sequ_def Star_concat)\nthm Sequ_def  Star_concat\n\n\nlemma L_flat_Prf2:\n  assumes \"s \\<in> L r\" \n  shows \"\\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\"\nusing assms\nproof(induct r arbitrary: s)\n  case (STAR r s)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (STAR r)\" by fact\n  then obtain ss where \"concat ss = s\" \"\\<forall>s \\<in> set ss. s \\<in> L r \\<and> s \\<noteq> []\"\n  using Star_cstring by auto  \n  then obtain vs where \"flats vs = s\" \"\\<forall>v\\<in>set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\"\n  using IH Star_cval by metis \n  then show \"\\<exists>v. \\<Turnstile> v : STAR r \\<and> flat v = s\"\n  using Prf.intros(6) flat_Stars by blast\nnext \n  case (SEQ r1 r2 s)\n  then show \"\\<exists>v. \\<Turnstile> v : SEQ r1 r2 \\<and> flat v = s\"\n  unfolding Sequ_def L.simps by (fastforce intro: Prf.intros)\nnext\n  case (ALT r1 r2 s)\n  then show \"\\<exists>v. \\<Turnstile> v : ALT r1 r2 \\<and> flat v = s\"\n  unfolding L.simps by (fastforce intro: Prf.intros)\nqed (auto intro: Prf.intros)\n\n\n\nlemma L_flat_2Prf2:\n  assumes \"s \\<in> L r\" \n  shows \"\\<exists>v. \\<turnstile> v : r \\<and> flat v = s\"\nusing assms\nproof(induct r arbitrary: s)\n  case (STAR r s)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (STAR r)\" by fact\n  then obtain ss where \"concat ss = s\" \"\\<forall>s \\<in> set ss. s \\<in> L r \\<and> s \\<noteq> []\"\n  using Star_cstring by auto  \n  then obtain vs where \"flats vs = s\" \"\\<forall>v\\<in>set vs. \\<turnstile> v : r \\<and> flat v \\<noteq> []\"\n  using IH Star2_cval by metis \n  then show \"\\<exists>v. \\<turnstile> v : STAR r \\<and> flat v = s\"\n  using Prf2.intros flat_Stars by blast\nnext \n  case (SEQ r1 r2 s)\n  then show \"\\<exists>v. \\<turnstile> v : SEQ r1 r2 \\<and> flat v = s\"\n  unfolding Sequ_def L.simps by (fastforce intro: Prf2.intros)\nnext\n  case (ALT r1 r2 s)\n  then show \"\\<exists>v. \\<turnstile> v : ALT r1 r2 \\<and> flat v = s\"\n  unfolding L.simps by (fastforce intro: Prf2.intros)\nqed (auto intro: Prf2.intros)\n\n\nlemma L_flat_Prf:\n  shows \"L(r) = {flat v | v. \\<Turnstile> v : r}\"\nusing L_flat_Prf1 L_flat_Prf2 by blast\n\nlemma L_flat_2Prf:\n  shows \"L(r) = {flat v | v. \\<turnstile> v : r}\"\n  using L_flat_2Prf1 L_flat_2Prf2 by blast\n\n(*using L_flat_2Prf1 L_flat_2Prf2 by blast\n*)\n\n\nsection {* Sets of Lexical Values *}\n\ntext {*\n  Shows that lexical values are finite for a given regex and string.\n*}\n\ndefinition\n  LV :: \"rexp \\<Rightarrow> string \\<Rightarrow> val set\"\nwhere  \"LV r s \\<equiv> {v. \\<Turnstile> v : r \\<and> flat v = s}\"\n\ndefinition\n  LV2 :: \"rexp \\<Rightarrow> string \\<Rightarrow> val set\"\n  where \"LV2 r s \\<equiv> {v. \\<turnstile> v : r \\<and> flat v = s}\"\n\nlemma LV_simps:\n  shows \"LV ZERO s = {}\"\n  and   \"LV ONE s = (if s = [] then {Void} else {})\"\n  and   \"LV (CR c) s = (if s = [c] then {Char c} else {})\"\n  and   \"LV (ALT r1 r2) s = Left ` LV r1 s \\<union> Right ` LV r2 s\"\nunfolding LV_def\nby (auto intro: Prf.intros elim: Prf.cases)\n\nlemma LV2_simps:\n  shows \"LV2 ZERO S = {}\"\nand \"LV2 ONE s = (if s = [] then {Void} else {})\"\nand \"LV2 (CR c) s = (if s = [c] then {Char c} else {})\"\nand \"LV2 (ALT r1 r2) s = Left ` LV2 r1 s \\<union> Right ` LV2 r2 s\"\n  unfolding LV2_def\nby (auto intro: Prf2.intros elim: Prf2.cases)\n\n\n\nabbreviation\n  \"Prefixes s \\<equiv> {s'. prefix s' s}\"\n\nabbreviation\n  \"Suffixes s \\<equiv> {s'. suffix s' s}\"\n\nabbreviation\n  \"SSuffixes s \\<equiv> {s'. strict_suffix s' s}\"\n\nlemma Suffixes_cons [simp]:\n  shows \"Suffixes (c # s) = Suffixes s \\<union> {c # s}\"\nby (auto simp add: suffix_def Cons_eq_append_conv)\n\n\nlemma finite_Suffixes: \n  shows \"finite (Suffixes s)\"\nby (induct s) (simp_all)\n\nlemma finite_SSuffixes: \n  shows \"finite (SSuffixes s)\"\nproof -\n  have \"SSuffixes s \\<subseteq> Suffixes s\"\n   unfolding strict_suffix_def suffix_def by auto\n  then show \"finite (SSuffixes s)\"\n   using finite_Suffixes finite_subset by blast\nqed\n\nlemma finite_Prefixes: \n  shows \"finite (Prefixes s)\"\nproof -\n  have \"finite (Suffixes (rev s))\" \n    by (rule finite_Suffixes)\n  then have \"finite (rev ` Suffixes (rev s))\" by simp\n  moreover\n  have \"rev ` (Suffixes (rev s)) = Prefixes s\"\n  unfolding suffix_def prefix_def image_def\n   by (auto)(metis rev_append rev_rev_ident)+\n  ultimately show \"finite (Prefixes s)\" by simp\nqed\n\nlemma LV_STAR_finite:\n  assumes \"\\<forall>s. finite (LV r s)\"\n  shows \"finite (LV (STAR r) s)\"\nproof(induct s rule: length_induct)\n  fix s::\"char list\"\n  assume \"\\<forall>s'. length s' < length s \\<longrightarrow> finite (LV (STAR r) s')\"\n  then have IH: \"\\<forall>s' \\<in> SSuffixes s. finite (LV (STAR r) s')\"\n    by (force simp add: strict_suffix_def suffix_def) \n  define f where \"f \\<equiv> \\<lambda>(v, vs). Stars (v # vs)\"\n  define S1 where \"S1 \\<equiv> \\<Union>s' \\<in> Prefixes s. LV r s'\"\n  define S2 where \"S2 \\<equiv> \\<Union>s2 \\<in> SSuffixes s. Stars -` (LV (STAR r) s2)\"\n  have \"finite S1\" using assms\n    unfolding S1_def by (simp_all add: finite_Prefixes)\n  moreover \n  with IH have \"finite S2\" unfolding S2_def\n    by (auto simp add: finite_SSuffixes inj_on_def finite_vimageI)\n  ultimately \n  have \"finite ({Stars []} \\<union> f ` (S1 \\<times> S2))\" by simp\n  moreover \n  have \"LV (STAR r) s \\<subseteq> {Stars []} \\<union> f ` (S1 \\<times> S2)\" \n  unfolding S1_def S2_def f_def\n  unfolding LV_def image_def prefix_def strict_suffix_def \n  apply(auto)\n  apply(case_tac x)\n  apply(auto elim: Prf_elims)\n  apply(erule Prf_elims)\n  apply(auto)\n  apply(case_tac vs)\n  apply(auto intro: Prf.intros)  \n  apply(rule exI)\n  apply(rule conjI)\n  apply(rule_tac x=\"flat a\" in exI)\n  apply(rule conjI)\n  apply(rule_tac x=\"flats list\" in exI)\n  apply(simp)\n   apply(blast)\n  apply(simp add: suffix_def)\n  using Prf.intros(6) by blast  \n  ultimately\n  show \"finite (LV (STAR r) s)\" by (simp add: finite_subset)\nqed  \n    \n\nlemma LV_finite:\n  shows \"finite (LV r s)\"\nproof(induct r arbitrary: s)\n  case (ZERO s) \n  show \"finite (LV ZERO s)\" by (simp add: LV_simps)\nnext\n  case (ONE s)\n  show \"finite (LV ONE s)\" by (simp add: LV_simps)\nnext\n  case (CR c s)\n  show \"finite (LV (CR c) s)\" by (simp add: LV_simps)\nnext \n  case (ALT r1 r2 s)\n  then show \"finite (LV (ALT r1 r2) s)\" by (simp add: LV_simps)\nnext \n  case (SEQ r1 r2 s)\n  define f where \"f \\<equiv> \\<lambda>(v1, v2). Seq v1 v2\"\n  define S1 where \"S1 \\<equiv> \\<Union>s' \\<in> Prefixes s. LV r1 s'\"\n  define S2 where \"S2 \\<equiv> \\<Union>s' \\<in> Suffixes s. LV r2 s'\"\n  have IHs: \"\\<And>s. finite (LV r1 s)\" \"\\<And>s. finite (LV r2 s)\" by fact+\n  then have \"finite S1\" \"finite S2\" unfolding S1_def S2_def\n    by (simp_all add: finite_Prefixes finite_Suffixes)\n  moreover\n  have \"LV (SEQ r1 r2) s \\<subseteq> f ` (S1 \\<times> S2)\"\n    unfolding f_def S1_def S2_def \n    unfolding LV_def image_def prefix_def suffix_def\n    apply (auto elim!: Prf_elims)\n    by (metis (mono_tags, lifting) mem_Collect_eq)  \n  ultimately \n  show \"finite (LV (SEQ r1 r2) s)\"\n    by (simp add: finite_subset)\nnext\n  case (STAR r s)\n  then show \"finite (LV (STAR r) s)\" by (simp add: LV_STAR_finite)\nqed\n\n\n\nsection {* Our POSIX Definition *}\n\ninductive \n  Posix :: \"string \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ \\<in> _ \\<rightarrow> _\" [100, 100, 100] 100)\nwhere\n  Posix_ONE: \"[] \\<in> ONE \\<rightarrow> Void\"\n| Posix_CHAR: \"[c] \\<in> (CR c) \\<rightarrow> (Char c)\"\n| Posix_ALT1: \"s \\<in> r1 \\<rightarrow> v \\<Longrightarrow> s \\<in> (ALT r1 r2) \\<rightarrow> (Left v)\"\n| Posix_ALT2: \"\\<lbrakk>s \\<in> r2 \\<rightarrow> v; s \\<notin> L(r1)\\<rbrakk> \\<Longrightarrow> s \\<in> (ALT r1 r2) \\<rightarrow> (Right v)\"\n| Posix_SEQ: \"\\<lbrakk>s1 \\<in> r1 \\<rightarrow> v1; s2 \\<in> r2 \\<rightarrow> v2;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\\<rbrakk> \\<Longrightarrow> \n    (s1 @ s2) \\<in> (SEQ r1 r2) \\<rightarrow> (Seq v1 v2)\"\n| Posix_STAR1: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> STAR r \\<rightarrow> Stars vs; flat v \\<noteq> [];\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> STAR r \\<rightarrow> Stars (v # vs)\"\n| Posix_STAR2: \"[] \\<in> STAR r \\<rightarrow> Stars []\"\n\n\ninductive_cases Posix_elims:\n  \"s \\<in> ZERO \\<rightarrow> v\"\n  \"s \\<in> ONE \\<rightarrow> v\"\n  \"s \\<in> CR c \\<rightarrow> v\"\n  \"s \\<in> ALT r1 r2 \\<rightarrow> v\"\n  \"s \\<in> SEQ r1 r2 \\<rightarrow> v\"\n  \"s \\<in> STAR r \\<rightarrow> v\"\n\n(*\ninductive\nPosix_split :: \"string \\<Rightarrow> string \\<Rightarrow>\n*)\n\n\nlemma Posix1:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"s \\<in> L r\" \"flat v = s\"\nusing assms\nby (induct s r v rule: Posix.induct)\n   (auto simp add: Sequ_def)\n\ntext {*\n  Our Posix definition determines a unique value.\n*}\n\nlemma Posix_determ:\n  assumes \"s \\<in> r \\<rightarrow> v1\" \"s \\<in> r \\<rightarrow> v2\"\n  shows \"v1 = v2\"\nusing assms\nproof (induct s r v1 arbitrary: v2 rule: Posix.induct)\n  case (Posix_ONE v2)\n  have \"[] \\<in> ONE \\<rightarrow> v2\" by fact\n  then show \"Void = v2\" by cases auto\nnext \n  case (Posix_CHAR c v2)\n  have \"[c] \\<in> CR c \\<rightarrow> v2\" by fact\n  then show \"Char c = v2\" by cases auto\nnext \n  case (Posix_ALT1 s r1 v r2 v2)\n  have \"s \\<in> ALT r1 r2 \\<rightarrow> v2\" by fact\n  moreover\n  have \"s \\<in> r1 \\<rightarrow> v\" by fact\n  then have \"s \\<in> L r1\" by (simp add: Posix1)\n  ultimately obtain v' where eq: \"v2 = Left v'\" \"s \\<in> r1 \\<rightarrow> v'\" by cases auto \n  moreover\n  have IH: \"\\<And>v2. s \\<in> r1 \\<rightarrow> v2 \\<Longrightarrow> v = v2\" by fact\n  ultimately have \"v = v'\" by simp\n  then show \"Left v = v2\" using eq by simp\nnext \n  case (Posix_ALT2 s r2 v r1 v2)\n  have \"s \\<in> ALT r1 r2 \\<rightarrow> v2\" by fact\n  moreover\n  have \"s \\<notin> L r1\" by fact\n  ultimately obtain v' where eq: \"v2 = Right v'\" \"s \\<in> r2 \\<rightarrow> v'\" \n    by cases (auto simp add: Posix1) \n  moreover\n  have IH: \"\\<And>v2. s \\<in> r2 \\<rightarrow> v2 \\<Longrightarrow> v = v2\" by fact\n  ultimately have \"v = v'\" by simp\n  then show \"Right v = v2\" using eq by simp\nnext\n  case (Posix_SEQ s1 r1 v1 s2 r2 v2 v')\n  have \"(s1 @ s2) \\<in> SEQ r1 r2 \\<rightarrow> v'\" \n       \"s1 \\<in> r1 \\<rightarrow> v1\" \"s2 \\<in> r2 \\<rightarrow> v2\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\" by fact+\n  then obtain v1' v2' where \"v' = Seq v1' v2'\" \"s1 \\<in> r1 \\<rightarrow> v1'\" \"s2 \\<in> r2 \\<rightarrow> v2'\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n  using Posix1(1) by fastforce+\n  moreover\n  have IHs: \"\\<And>v1'. s1 \\<in> r1 \\<rightarrow> v1' \\<Longrightarrow> v1 = v1'\"\n            \"\\<And>v2'. s2 \\<in> r2 \\<rightarrow> v2' \\<Longrightarrow> v2 = v2'\" by fact+\n  ultimately show \"Seq v1 v2 = v'\" by simp\nnext\n  case (Posix_STAR1 s1 r v s2 vs v2)\n  have \"(s1 @ s2) \\<in> STAR r \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> STAR r \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (STAR r) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n  using Posix1(1) apply fastforce\n  apply (metis Posix1(1) Posix_STAR1.hyps(6) append_Nil append_Nil2)\n  using Posix1(2) by blast\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> STAR r \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto\nnext\n  case (Posix_STAR2 r v2)\n  have \"[] \\<in> STAR r \\<rightarrow> v2\" by fact\n  then show \"Stars [] = v2\" by cases (auto simp add: Posix1)\nqed\n\n\ntext {*\n  Our POSIX values are lexical values.\n*}\n\nlemma Posix_LV:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"v \\<in> LV r s\"\n  using assms unfolding LV_def\n  apply(induct rule: Posix.induct)\n  apply(auto simp add: intro!: Prf.intros elim!: Prf_elims)\n  done\n\nlemma Posix_Prf:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"\\<Turnstile> v : r\"\n  using assms Posix_LV LV_def\n  by simp\n\nend", "meta": {"author": "hellotommmy", "repo": "thys", "sha": "f80bc4b0d9aea05c367b676ce4ce9e7aed671144", "save_path": "github-repos/isabelle/hellotommmy-thys", "path": "github-repos/isabelle/hellotommmy-thys/thys-f80bc4b0d9aea05c367b676ce4ce9e7aed671144/Spec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7858096072118129}}
{"text": "section \\<open>Maximum Segment Sum\\<close>\n\ntheory Maximum_Segment_Sum\n  imports Main\nbegin\n\ntext \\<open>The \\emph{maximum segment sum} problem is to compute, given a list of numbers,\nthe largest of the sums of the contiguous segments of that list. It is also known\nas the \\emph{maximum sum subarray} problem and has been considered many times in the literature;\nthe Wikipedia article\n\\href{https://en.wikipedia.org/wiki/Maximum\\_subarray\\_problem}{Maximum subarray problem} is a good starting point.\n\nWe assume that the elements of the list are not necessarily numbers but just elements\nof some linearly ordered group.\\<close>\n\nclass linordered_group_add = linorder + group_add +\nassumes add_left_mono: \"a \\<le> b \\<Longrightarrow> c + a \\<le> c + b\"\nassumes add_right_mono: \"a \\<le> b \\<Longrightarrow> a + c \\<le> b + c\"\nbegin\n\nlemma max_add_distrib_left: \"max y z + x = max (y+x) (z+x)\"\nby (metis add_right_mono max.absorb_iff1 max_def)\n\nlemma max_add_distrib_right: \"x + max y z = max (x+y) (x+z)\"\nby (metis add_left_mono max.absorb1 max.cobounded2 max_def)\n\nsubsection \\<open>Naive Solution\\<close>\n\nfun mss_rec_naive_aux :: \"'a list \\<Rightarrow> 'a\" where\n  \"mss_rec_naive_aux [] = 0\"\n| \"mss_rec_naive_aux (x#xs) = max 0 (x + mss_rec_naive_aux xs)\"\n\nfun mss_rec_naive :: \"'a list \\<Rightarrow> 'a\" where\n  \"mss_rec_naive [] = 0\"\n| \"mss_rec_naive (x#xs) = max (mss_rec_naive_aux (x#xs)) (mss_rec_naive xs)\"\n\ndefinition fronts :: \"'a list \\<Rightarrow> 'a list set\" where\n  \"fronts xs = {as. \\<exists>bs. xs = as @ bs}\"\n\ndefinition \"front_sums xs \\<equiv> sum_list ` fronts xs\"\n\nlemma fronts_cons: \"fronts (x#xs) = ((#) x) ` fronts xs \\<union> {[]}\" (is \"?l = ?r\")\nproof\n  show \"?l \\<subseteq> ?r\"\n  proof\n    fix as assume \"as \\<in> ?l\"\n    then show \"as \\<in> ?r\" by (cases as) (auto simp: fronts_def)\n  qed\n  show \"?r \\<subseteq> ?l\" unfolding fronts_def by auto\nqed\n\nlemma front_sums_cons: \"front_sums (x#xs) = (+) x ` front_sums xs \\<union> {0}\"\nproof -\n  have \"sum_list ` ((#) x) ` fronts xs = (+) x ` front_sums xs\" unfolding front_sums_def by force\n  then show ?thesis by (simp add: front_sums_def fronts_cons)\nqed\n\nlemma finite_fronts: \"finite (fronts xs)\"\n  by (induction xs) (simp add: fronts_def, simp add: fronts_cons)\n\nlemma finite_front_sums: \"finite (front_sums xs)\"\n  using front_sums_def finite_fronts by simp\n\nlemma front_sums_not_empty: \"front_sums xs \\<noteq> {}\"\n  unfolding front_sums_def fronts_def using image_iff by fastforce\n\nlemma max_front_sum: \"Max (front_sums (x#xs)) = max 0 (x + Max (front_sums xs))\"\nusing finite_front_sums front_sums_not_empty\nby (auto simp add: front_sums_cons hom_Max_commute max_add_distrib_right)\n\nlemma mss_rec_naive_aux_front_sums: \"mss_rec_naive_aux xs = Max (front_sums xs)\"\nby (induction xs) (simp add: front_sums_def fronts_def, auto simp: max_front_sum)\n\nlemma front_sums: \"front_sums xs = {s. \\<exists>as bs. xs = as @ bs \\<and> s = sum_list as}\"\nunfolding front_sums_def fronts_def by auto\n\nlemma mss_rec_naive_aux: \"mss_rec_naive_aux xs = Max {s. \\<exists>as bs. xs = as @ bs \\<and> s = sum_list as}\"\nusing front_sums mss_rec_naive_aux_front_sums by simp\n  \n\ndefinition mids :: \"'a list \\<Rightarrow> 'a list set\" where\n  \"mids xs \\<equiv> {bs. \\<exists>as cs. xs = as @ bs @ cs}\"\n\ndefinition \"mid_sums xs \\<equiv> sum_list ` mids xs\"\n\nlemma fronts_mids: \"bs \\<in> fronts xs \\<Longrightarrow> bs \\<in> mids xs\"\nunfolding fronts_def mids_def by auto\n\nlemma mids_mids_cons: \"bs \\<in> mids xs \\<Longrightarrow> bs \\<in> mids (x#xs)\"\nproof-\n  fix bs assume \"bs \\<in> mids xs\"\n  then obtain as cs where \"xs = as @ bs @ cs\" unfolding mids_def by blast\n  then have \"x # xs = (x#as) @ bs @ cs\" by simp\n  then show \"bs \\<in> mids (x#xs)\" unfolding mids_def by blast\nqed\n\nlemma mids_cons: \"mids (x#xs) = fronts (x#xs) \\<union> mids xs\" (is \"?l = ?r\")\nproof\n  show \"?l \\<subseteq> ?r\"\n  proof\n    fix bs assume \"bs \\<in> ?l\"\n    then obtain as cs where as_bs_cs: \"(x#xs) = as @ bs @ cs\" unfolding mids_def by blast\n    then show \"bs \\<in> ?r\"\n    proof (cases as)\n      case Nil\n      then have \"bs \\<in> fronts (x#xs)\" by (simp add: fronts_def as_bs_cs)\n      then show ?thesis by simp\n    next\n      case (Cons a as')\n      then have \"xs = as' @ bs @ cs\" using as_bs_cs by simp\n      then show ?thesis unfolding mids_def by auto\n    qed\n  qed\n  show \"?r \\<subseteq> ?l\" using fronts_mids mids_mids_cons by auto\nqed\n\nlemma mid_sums_cons: \"mid_sums (x#xs) = front_sums (x#xs) \\<union> mid_sums xs\"\n  unfolding mid_sums_def by (auto simp: mids_cons front_sums_def)\n\nlemma finite_mids: \"finite (mids xs)\"\n  by (induction xs) (simp add: mids_def, simp add: mids_cons finite_fronts)\n\nlemma finite_mid_sums: \"finite (mid_sums xs)\"\n  by (simp add: mid_sums_def finite_mids)\n\nlemma mid_sums_not_empty: \"mid_sums xs \\<noteq> {}\"\n  unfolding mid_sums_def mids_def by blast\n\nlemma max_mid_sums_cons: \"Max (mid_sums (x#xs)) = max (Max (front_sums (x#xs))) (Max (mid_sums xs))\"\n  by (auto simp: mid_sums_cons Max_Un finite_front_sums finite_mid_sums front_sums_not_empty mid_sums_not_empty)\n\nlemma mss_rec_naive_max_mid_sum: \"mss_rec_naive xs = Max (mid_sums xs)\"\n  by (induction xs) (simp add: mid_sums_def mids_def, auto simp: max_mid_sums_cons mss_rec_naive_aux front_sums)\n\nlemma mid_sums: \"mid_sums xs = {s. \\<exists>as bs cs. xs = as @ bs @ cs \\<and> s = sum_list bs}\"\n  by (auto simp: mid_sums_def mids_def)\n\ntheorem mss_rec_naive: \"mss_rec_naive xs = Max {s. \\<exists>as bs cs. xs = as @ bs @ cs \\<and> s = sum_list bs}\"\n  unfolding mss_rec_naive_max_mid_sum mid_sums by simp\n\n\nsubsection \\<open>Kadane's Algorithms\\<close>\n\nfun kadane :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"kadane [] cur m = m\"\n| \"kadane (x#xs) cur m =\n    (let cur' = max (cur + x) x in\n      kadane xs cur' (max m cur'))\"\n\ndefinition \"mss_kadane xs \\<equiv> kadane xs 0 0\"\n\nlemma Max_front_sums_geq_0: \"Max (front_sums xs) \\<ge> 0\"\nproof-\n  have \"[] \\<in> fronts xs\" unfolding fronts_def by blast\n  then have \"0 \\<in> front_sums xs\" unfolding front_sums_def by force\n  then show ?thesis using finite_front_sums Max_ge by simp\nqed\n\nlemma Max_mid_sums_geq_0: \"Max (mid_sums xs) \\<ge> 0\"\nproof-\n  have \"0 \\<in> mid_sums xs\" unfolding mid_sums_def mids_def by force\n  then show ?thesis using finite_mid_sums Max_ge by simp\nqed\n\nlemma kadane: \"m \\<ge> cur \\<Longrightarrow> m \\<ge> 0 \\<Longrightarrow> kadane xs cur m = max m (max (cur + Max (front_sums xs)) (Max (mid_sums xs)))\"\nproof (induction xs cur m rule: kadane.induct)\n  case (1 cur m)\n  then show ?case unfolding front_sums_def fronts_def mid_sums_def mids_def by auto\nnext\n  case (2 x xs cur m)\n  then show ?case\n    apply (auto simp: max_front_sum max_mid_sums_cons Let_def)\n    by (smt (verit, ccfv_threshold) Max_front_sums_geq_0 add_assoc add_0_right max.assoc max.coboundedI1 max.left_commute max.orderE max_add_distrib_left max_add_distrib_right)\nqed\n\nlemma Max_front_sums_leq_Max_mid_sums: \"Max (front_sums xs) \\<le> Max (mid_sums xs)\"\nproof-\n  have \"front_sums xs \\<subseteq> mid_sums xs\" unfolding front_sums_def mid_sums_def using fronts_mids subset_iff by blast\n  then show ?thesis using front_sums_not_empty finite_mid_sums Max_mono by blast\nqed\n\nlemma mss_kadane_mid_sums: \"mss_kadane xs = Max (mid_sums xs)\"\n  unfolding mss_kadane_def using kadane Max_mid_sums_geq_0 Max_front_sums_leq_Max_mid_sums by auto\n\ntheorem mss_kadane: \"mss_kadane xs = Max {s. \\<exists>as bs cs. xs = as @ bs @ cs \\<and> s = sum_list bs}\"\n  using mss_kadane_mid_sums mid_sums by auto\n\nend\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Maximum_Segment_Sum/Maximum_Segment_Sum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.7857363119119476}}
{"text": "(*  Title:      HOL/Finite_Set.thy\n    Author:     Tobias Nipkow, Lawrence C Paulson and Markus Wenzel\n                with contributions by Jeremy Avigad and Andrei Popescu\n*)\n\nsection {* Finite sets *}\n\ntheory Finite_Set\nimports Product_Type Sum_Type Nat\nbegin\n\nsubsection {* Predicate for finite sets *}\n\ninductive finite :: \"'a set \\<Rightarrow> bool\"\n  where\n    emptyI [simp, intro!]: \"finite {}\"\n  | insertI [simp, intro!]: \"finite A \\<Longrightarrow> finite (insert a A)\"\n\nsimproc_setup finite_Collect (\"finite (Collect P)\") = {* K Set_Comprehension_Pointfree.simproc *}\n\ndeclare [[simproc del: finite_Collect]]\n\nlemma finite_induct [case_names empty insert, induct set: finite]:\n  -- {* Discharging @{text \"x \\<notin> F\"} entails extra work. *}\n  assumes \"finite F\"\n  assumes \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\nusing `finite F`\nproof induct\n  show \"P {}\" by fact\n  fix x F assume F: \"finite F\" and P: \"P F\"\n  show \"P (insert x F)\"\n  proof cases\n    assume \"x \\<in> F\"\n    hence \"insert x F = F\" by (rule insert_absorb)\n    with P show ?thesis by (simp only:)\n  next\n    assume \"x \\<notin> F\"\n    from F this P show ?thesis by (rule insert)\n  qed\nqed\n\nlemma infinite_finite_induct [case_names infinite empty insert]:\n  assumes infinite: \"\\<And>A. \\<not> finite A \\<Longrightarrow> P A\"\n  assumes empty: \"P {}\"\n  assumes insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P A\"\nproof (cases \"finite A\")\n  case False with infinite show ?thesis .\nnext\n  case True then show ?thesis by (induct A) (fact empty insert)+\nqed\n\n\nsubsubsection {* Choice principles *}\n\nlemma ex_new_if_finite: -- \"does not depend on def of finite at all\"\n  assumes \"\\<not> finite (UNIV :: 'a set)\" and \"finite A\"\n  shows \"\\<exists>a::'a. a \\<notin> A\"\nproof -\n  from assms have \"A \\<noteq> UNIV\" by blast\n  then show ?thesis by blast\nqed\n\ntext {* A finite choice principle. Does not need the SOME choice operator. *}\n\nlemma finite_set_choice:\n  \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. \\<exists>y. P x y \\<Longrightarrow> \\<exists>f. \\<forall>x\\<in>A. P x (f x)\"\nproof (induct rule: finite_induct)\n  case empty then show ?case by simp\nnext\n  case (insert a A)\n  then obtain f b where f: \"ALL x:A. P x (f x)\" and ab: \"P a b\" by auto\n  show ?case (is \"EX f. ?P f\")\n  proof\n    show \"?P(%x. if x = a then b else f x)\" using f ab by auto\n  qed\nqed\n\n\nsubsubsection {* Finite sets are the images of initial segments of natural numbers *}\n\nlemma finite_imp_nat_seg_image_inj_on:\n  assumes \"finite A\" \n  shows \"\\<exists>(n::nat) f. A = f ` {i. i < n} \\<and> inj_on f {i. i < n}\"\nusing assms\nproof induct\n  case empty\n  show ?case\n  proof\n    show \"\\<exists>f. {} = f ` {i::nat. i < 0} \\<and> inj_on f {i. i < 0}\" by simp \n  qed\nnext\n  case (insert a A)\n  have notinA: \"a \\<notin> A\" by fact\n  from insert.hyps obtain n f\n    where \"A = f ` {i::nat. i < n}\" \"inj_on f {i. i < n}\" by blast\n  hence \"insert a A = f(n:=a) ` {i. i < Suc n}\"\n        \"inj_on (f(n:=a)) {i. i < Suc n}\" using notinA\n    by (auto simp add: image_def Ball_def inj_on_def less_Suc_eq)\n  thus ?case by blast\nqed\n\nlemma nat_seg_image_imp_finite:\n  \"A = f ` {i::nat. i < n} \\<Longrightarrow> finite A\"\nproof (induct n arbitrary: A)\n  case 0 thus ?case by simp\nnext\n  case (Suc n)\n  let ?B = \"f ` {i. i < n}\"\n  have finB: \"finite ?B\" by(rule Suc.hyps[OF refl])\n  show ?case\n  proof cases\n    assume \"\\<exists>k<n. f n = f k\"\n    hence \"A = ?B\" using Suc.prems by(auto simp:less_Suc_eq)\n    thus ?thesis using finB by simp\n  next\n    assume \"\\<not>(\\<exists> k<n. f n = f k)\"\n    hence \"A = insert (f n) ?B\" using Suc.prems by(auto simp:less_Suc_eq)\n    thus ?thesis using finB by simp\n  qed\nqed\n\nlemma finite_conv_nat_seg_image:\n  \"finite A \\<longleftrightarrow> (\\<exists>(n::nat) f. A = f ` {i::nat. i < n})\"\n  by (blast intro: nat_seg_image_imp_finite dest: finite_imp_nat_seg_image_inj_on)\n\nlemma finite_imp_inj_to_nat_seg:\n  assumes \"finite A\"\n  shows \"\\<exists>f n::nat. f ` A = {i. i < n} \\<and> inj_on f A\"\nproof -\n  from finite_imp_nat_seg_image_inj_on[OF `finite A`]\n  obtain f and n::nat where bij: \"bij_betw f {i. i<n} A\"\n    by (auto simp:bij_betw_def)\n  let ?f = \"the_inv_into {i. i<n} f\"\n  have \"inj_on ?f A & ?f ` A = {i. i<n}\"\n    by (fold bij_betw_def) (rule bij_betw_the_inv_into[OF bij])\n  thus ?thesis by blast\nqed\n\nlemma finite_Collect_less_nat [iff]:\n  \"finite {n::nat. n < k}\"\n  by (fastforce simp: finite_conv_nat_seg_image)\n\nlemma finite_Collect_le_nat [iff]:\n  \"finite {n::nat. n \\<le> k}\"\n  by (simp add: le_eq_less_or_eq Collect_disj_eq)\n\n\nsubsubsection {* Finiteness and common set operations *}\n\nlemma rev_finite_subset:\n  \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> finite A\"\nproof (induct arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F A)\n  have A: \"A \\<subseteq> insert x F\" and r: \"A - {x} \\<subseteq> F \\<Longrightarrow> finite (A - {x})\" by fact+\n  show \"finite A\"\n  proof cases\n    assume x: \"x \\<in> A\"\n    with A have \"A - {x} \\<subseteq> F\" by (simp add: subset_insert_iff)\n    with r have \"finite (A - {x})\" .\n    hence \"finite (insert x (A - {x}))\" ..\n    also have \"insert x (A - {x}) = A\" using x by (rule insert_Diff)\n    finally show ?thesis .\n  next\n    show \"A \\<subseteq> F ==> ?thesis\" by fact\n    assume \"x \\<notin> A\"\n    with A show \"A \\<subseteq> F\" by (simp add: subset_insert_iff)\n  qed\nqed\n\nlemma finite_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  by (rule rev_finite_subset)\n\nlemma finite_UnI:\n  assumes \"finite F\" and \"finite G\"\n  shows \"finite (F \\<union> G)\"\n  using assms by induct simp_all\n\nlemma finite_Un [iff]:\n  \"finite (F \\<union> G) \\<longleftrightarrow> finite F \\<and> finite G\"\n  by (blast intro: finite_UnI finite_subset [of _ \"F \\<union> G\"])\n\nlemma finite_insert [simp]: \"finite (insert a A) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite {a} \\<and> finite A \\<longleftrightarrow> finite A\" by simp\n  then have \"finite ({a} \\<union> A) \\<longleftrightarrow> finite A\" by (simp only: finite_Un)\n  then show ?thesis by simp\nqed\n\nlemma finite_Int [simp, intro]:\n  \"finite F \\<or> finite G \\<Longrightarrow> finite (F \\<inter> G)\"\n  by (blast intro: finite_subset)\n\nlemma finite_Collect_conjI [simp, intro]:\n  \"finite {x. P x} \\<or> finite {x. Q x} \\<Longrightarrow> finite {x. P x \\<and> Q x}\"\n  by (simp add: Collect_conj_eq)\n\nlemma finite_Collect_disjI [simp]:\n  \"finite {x. P x \\<or> Q x} \\<longleftrightarrow> finite {x. P x} \\<and> finite {x. Q x}\"\n  by (simp add: Collect_disj_eq)\n\nlemma finite_Diff [simp, intro]:\n  \"finite A \\<Longrightarrow> finite (A - B)\"\n  by (rule finite_subset, rule Diff_subset)\n\nlemma finite_Diff2 [simp]:\n  assumes \"finite B\"\n  shows \"finite (A - B) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite A \\<longleftrightarrow> finite((A - B) \\<union> (A \\<inter> B))\" by (simp add: Un_Diff_Int)\n  also have \"\\<dots> \\<longleftrightarrow> finite (A - B)\" using `finite B` by simp\n  finally show ?thesis ..\nqed\n\nlemma finite_Diff_insert [iff]:\n  \"finite (A - insert a B) \\<longleftrightarrow> finite (A - B)\"\nproof -\n  have \"finite (A - B) \\<longleftrightarrow> finite (A - B - {a})\" by simp\n  moreover have \"A - insert a B = A - B - {a}\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma finite_compl[simp]:\n  \"finite (A :: 'a set) \\<Longrightarrow> finite (- A) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Compl_eq_Diff_UNIV)\n\nlemma finite_Collect_not[simp]:\n  \"finite {x :: 'a. P x} \\<Longrightarrow> finite {x. \\<not> P x} \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Collect_neg_eq)\n\nlemma finite_Union [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>M. M \\<in> A \\<Longrightarrow> finite M) \\<Longrightarrow> finite(\\<Union>A)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN_I [intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (\\<Union>a\\<in>A. B a)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN [simp]:\n  \"finite A \\<Longrightarrow> finite (UNION A B) \\<longleftrightarrow> (\\<forall>x\\<in>A. finite (B x))\"\n  by (blast intro: finite_subset)\n\nlemma finite_Inter [intro]:\n  \"\\<exists>A\\<in>M. finite A \\<Longrightarrow> finite (\\<Inter>M)\"\n  by (blast intro: Inter_lower finite_subset)\n\nlemma finite_INT [intro]:\n  \"\\<exists>x\\<in>I. finite (A x) \\<Longrightarrow> finite (\\<Inter>x\\<in>I. A x)\"\n  by (blast intro: INT_lower finite_subset)\n\nlemma finite_imageI [simp, intro]:\n  \"finite F \\<Longrightarrow> finite (h ` F)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_image_set [simp]:\n  \"finite {x. P x} \\<Longrightarrow> finite { f x | x. P x }\"\n  by (simp add: image_Collect [symmetric])\n\nlemma finite_imageD:\n  assumes \"finite (f ` A)\" and \"inj_on f A\"\n  shows \"finite A\"\nusing assms\nproof (induct \"f ` A\" arbitrary: A)\n  case empty then show ?case by simp\nnext\n  case (insert x B)\n  then have B_A: \"insert x B = f ` A\" by simp\n  then obtain y where \"x = f y\" and \"y \\<in> A\" by blast\n  from B_A `x \\<notin> B` have \"B = f ` A - {x}\" by blast\n  with B_A `x \\<notin> B` `x = f y` `inj_on f A` `y \\<in> A` have \"B = f ` (A - {y})\" by (simp add: inj_on_image_set_diff)\n  moreover from `inj_on f A` have \"inj_on f (A - {y})\" by (rule inj_on_diff)\n  ultimately have \"finite (A - {y})\" by (rule insert.hyps)\n  then show \"finite A\" by simp\nqed\n\nlemma finite_surj:\n  \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> finite B\"\n  by (erule finite_subset) (rule finite_imageI)\n\nlemma finite_range_imageI:\n  \"finite (range g) \\<Longrightarrow> finite (range (\\<lambda>x. f (g x)))\"\n  by (drule finite_imageI) (simp add: range_composition)\n\nlemma finite_subset_image:\n  assumes \"finite B\"\n  shows \"B \\<subseteq> f ` A \\<Longrightarrow> \\<exists>C\\<subseteq>A. finite C \\<and> B = f ` C\"\nusing assms\nproof induct\n  case empty then show ?case by simp\nnext\n  case insert then show ?case\n    by (clarsimp simp del: image_insert simp add: image_insert [symmetric])\n       blast\nqed\n\nlemma finite_vimage_IntI:\n  \"finite F \\<Longrightarrow> inj_on h A \\<Longrightarrow> finite (h -` F \\<inter> A)\"\n  apply (induct rule: finite_induct)\n   apply simp_all\n  apply (subst vimage_insert)\n  apply (simp add: finite_subset [OF inj_on_vimage_singleton] Int_Un_distrib2)\n  done\n\nlemma finite_vimageI:\n  \"finite F \\<Longrightarrow> inj h \\<Longrightarrow> finite (h -` F)\"\n  using finite_vimage_IntI[of F h UNIV] by auto\n\nlemma finite_vimageD:\n  assumes fin: \"finite (h -` F)\" and surj: \"surj h\"\n  shows \"finite F\"\nproof -\n  have \"finite (h ` (h -` F))\" using fin by (rule finite_imageI)\n  also have \"h ` (h -` F) = F\" using surj by (rule surj_image_vimage_eq)\n  finally show \"finite F\" .\nqed\n\nlemma finite_vimage_iff: \"bij h \\<Longrightarrow> finite (h -` F) \\<longleftrightarrow> finite F\"\n  unfolding bij_def by (auto elim: finite_vimageD finite_vimageI)\n\nlemma finite_Collect_bex [simp]:\n  assumes \"finite A\"\n  shows \"finite {x. \\<exists>y\\<in>A. Q x y} \\<longleftrightarrow> (\\<forall>y\\<in>A. finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y\\<in>A. Q x y} = (\\<Union>y\\<in>A. {x. Q x y})\" by auto\n  with assms show ?thesis by simp\nqed\n\nlemma finite_Collect_bounded_ex [simp]:\n  assumes \"finite {y. P y}\"\n  shows \"finite {x. \\<exists>y. P y \\<and> Q x y} \\<longleftrightarrow> (\\<forall>y. P y \\<longrightarrow> finite {x. Q x y})\"\nproof -\n  have \"{x. EX y. P y & Q x y} = (\\<Union>y\\<in>{y. P y}. {x. Q x y})\" by auto\n  with assms show ?thesis by simp\nqed\n\nlemma finite_Plus:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A <+> B)\"\n  by (simp add: Plus_def)\n\nlemma finite_PlusD: \n  fixes A :: \"'a set\" and B :: \"'b set\"\n  assumes fin: \"finite (A <+> B)\"\n  shows \"finite A\" \"finite B\"\nproof -\n  have \"Inl ` A \\<subseteq> A <+> B\" by auto\n  then have \"finite (Inl ` A :: ('a + 'b) set)\" using fin by (rule finite_subset)\n  then show \"finite A\" by (rule finite_imageD) (auto intro: inj_onI)\nnext\n  have \"Inr ` B \\<subseteq> A <+> B\" by auto\n  then have \"finite (Inr ` B :: ('a + 'b) set)\" using fin by (rule finite_subset)\n  then show \"finite B\" by (rule finite_imageD) (auto intro: inj_onI)\nqed\n\nlemma finite_Plus_iff [simp]:\n  \"finite (A <+> B) \\<longleftrightarrow> finite A \\<and> finite B\"\n  by (auto intro: finite_PlusD finite_Plus)\n\nlemma finite_Plus_UNIV_iff [simp]:\n  \"finite (UNIV :: ('a + 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  by (subst UNIV_Plus_UNIV [symmetric]) (rule finite_Plus_iff)\n\nlemma finite_SigmaI [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a\\<in>A \\<Longrightarrow> finite (B a)) ==> finite (SIGMA a:A. B a)\"\n  by (unfold Sigma_def) blast\n\nlemma finite_SigmaI2:\n  assumes \"finite {x\\<in>A. B x \\<noteq> {}}\"\n  and \"\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)\"\n  shows \"finite (Sigma A B)\"\nproof -\n  from assms have \"finite (Sigma {x\\<in>A. B x \\<noteq> {}} B)\" by auto\n  also have \"Sigma {x:A. B x \\<noteq> {}} B = Sigma A B\" by auto\n  finally show ?thesis .\nqed\n\nlemma finite_cartesian_product:\n  \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<times> B)\"\n  by (rule finite_SigmaI)\n\nlemma finite_Prod_UNIV:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> finite (UNIV :: 'b set) \\<Longrightarrow> finite (UNIV :: ('a \\<times> 'b) set)\"\n  by (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product)\n\nlemma finite_cartesian_productD1:\n  assumes \"finite (A \\<times> B)\" and \"B \\<noteq> {}\"\n  shows \"finite A\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"fst ` (A \\<times> B) = fst ` f ` {i::nat. i < n}\" by simp\n  with `B \\<noteq> {}` have \"A = (fst \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. A = f ` {i::nat. i < n}\" by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_productD2:\n  assumes \"finite (A \\<times> B)\" and \"A \\<noteq> {}\"\n  shows \"finite B\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"snd ` (A \\<times> B) = snd ` f ` {i::nat. i < n}\" by simp\n  with `A \\<noteq> {}` have \"B = (snd \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. B = f ` {i::nat. i < n}\" by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_product_iff:\n  \"finite (A \\<times> B) \\<longleftrightarrow> (A = {} \\<or> B = {} \\<or> (finite A \\<and> finite B))\"\n  by (auto dest: finite_cartesian_productD1 finite_cartesian_productD2 finite_cartesian_product)\n\nlemma finite_prod: \n  \"finite (UNIV :: ('a \\<times> 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  using finite_cartesian_product_iff[of UNIV UNIV] by simp\n\nlemma finite_Pow_iff [iff]:\n  \"finite (Pow A) \\<longleftrightarrow> finite A\"\nproof\n  assume \"finite (Pow A)\"\n  then have \"finite ((%x. {x}) ` A)\" by (blast intro: finite_subset)\n  then show \"finite A\" by (rule finite_imageD [unfolded inj_on_def]) simp\nnext\n  assume \"finite A\"\n  then show \"finite (Pow A)\"\n    by induct (simp_all add: Pow_insert)\nqed\n\ncorollary finite_Collect_subsets [simp, intro]:\n  \"finite A \\<Longrightarrow> finite {B. B \\<subseteq> A}\"\n  by (simp add: Pow_def [symmetric])\n\nlemma finite_set: \"finite (UNIV :: 'a set set) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\nby(simp only: finite_Pow_iff Pow_UNIV[symmetric])\n\nlemma finite_UnionD: \"finite(\\<Union>A) \\<Longrightarrow> finite A\"\n  by (blast intro: finite_subset [OF subset_Pow_Union])\n\nlemma finite_set_of_finite_funs: assumes \"finite A\" \"finite B\"\nshows \"finite{f. \\<forall>x. (x \\<in> A \\<longrightarrow> f x \\<in> B) \\<and> (x \\<notin> A \\<longrightarrow> f x = d)}\" (is \"finite ?S\")\nproof-\n  let ?F = \"\\<lambda>f. {(a,b). a \\<in> A \\<and> b = f a}\"\n  have \"?F ` ?S \\<subseteq> Pow(A \\<times> B)\" by auto\n  from finite_subset[OF this] assms have 1: \"finite (?F ` ?S)\" by simp\n  have 2: \"inj_on ?F ?S\"\n    by(fastforce simp add: inj_on_def set_eq_iff fun_eq_iff)\n  show ?thesis by(rule finite_imageD[OF 1 2])\nqed\n\nlemma not_finite_existsD:\n  assumes \"\\<not> finite {a. P a}\"\n  shows \"\\<exists>a. P a\"\nproof (rule classical)\n  assume \"\\<not> (\\<exists>a. P a)\"\n  with assms show ?thesis by auto\nqed\n\n\nsubsubsection {* Further induction rules on finite sets *}\n\nlemma finite_ne_induct [case_names singleton insert, consumes 2]:\n  assumes \"finite F\" and \"F \\<noteq> {}\"\n  assumes \"\\<And>x. P {x}\"\n    and \"\\<And>x F. finite F \\<Longrightarrow> F \\<noteq> {} \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F  \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\nusing assms\nproof induct\n  case empty then show ?case by simp\nnext\n  case (insert x F) then show ?case by cases auto\nqed\n\nlemma finite_subset_induct [consumes 2, case_names empty insert]:\n  assumes \"finite F\" and \"F \\<subseteq> A\"\n  assumes empty: \"P {}\"\n    and insert: \"\\<And>a F. finite F \\<Longrightarrow> a \\<in> A \\<Longrightarrow> a \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert a F)\"\n  shows \"P F\"\nusing `finite F` `F \\<subseteq> A`\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume \"finite F\" and \"x \\<notin> F\" and\n    P: \"F \\<subseteq> A \\<Longrightarrow> P F\" and i: \"insert x F \\<subseteq> A\"\n  show \"P (insert x F)\"\n  proof (rule insert)\n    from i show \"x \\<in> A\" by blast\n    from i have \"F \\<subseteq> A\" by blast\n    with P show \"P F\" .\n    show \"finite F\" by fact\n    show \"x \\<notin> F\" by fact\n  qed\nqed\n\nlemma finite_empty_induct:\n  assumes \"finite A\"\n  assumes \"P A\"\n    and remove: \"\\<And>a A. finite A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> P A \\<Longrightarrow> P (A - {a})\"\n  shows \"P {}\"\nproof -\n  have \"\\<And>B. B \\<subseteq> A \\<Longrightarrow> P (A - B)\"\n  proof -\n    fix B :: \"'a set\"\n    assume \"B \\<subseteq> A\"\n    with `finite A` have \"finite B\" by (rule rev_finite_subset)\n    from this `B \\<subseteq> A` show \"P (A - B)\"\n    proof induct\n      case empty\n      from `P A` show ?case by simp\n    next\n      case (insert b B)\n      have \"P (A - B - {b})\"\n      proof (rule remove)\n        from `finite A` show \"finite (A - B)\" by induct auto\n        from insert show \"b \\<in> A - B\" by simp\n        from insert show \"P (A - B)\" by simp\n      qed\n      also have \"A - B - {b} = A - insert b B\" by (rule Diff_insert [symmetric])\n      finally show ?case .\n    qed\n  qed\n  then have \"P (A - A)\" by blast\n  then show ?thesis by simp\nqed\n\nlemma finite_update_induct [consumes 1, case_names const update]:\n  assumes finite: \"finite {a. f a \\<noteq> c}\"\n  assumes const: \"P (\\<lambda>a. c)\"\n  assumes update: \"\\<And>a b f. finite {a. f a \\<noteq> c} \\<Longrightarrow> f a = c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> P f \\<Longrightarrow> P (f(a := b))\"\n  shows \"P f\"\nusing finite proof (induct \"{a. f a \\<noteq> c}\" arbitrary: f)\n  case empty with const show ?case by simp\nnext\n  case (insert a A)\n  then have \"A = {a'. (f(a := c)) a' \\<noteq> c}\" and \"f a \\<noteq> c\"\n    by auto\n  with `finite A` have \"finite {a'. (f(a := c)) a' \\<noteq> c}\"\n    by simp\n  have \"(f(a := c)) a = c\"\n    by simp\n  from insert `A = {a'. (f(a := c)) a' \\<noteq> c}` have \"P (f(a := c))\"\n    by simp\n  with `finite {a'. (f(a := c)) a' \\<noteq> c}` `(f(a := c)) a = c` `f a \\<noteq> c` have \"P ((f(a := c))(a := f a))\"\n    by (rule update)\n  then show ?case by simp\nqed\n\n\nsubsection {* Class @{text finite}  *}\n\nclass finite =\n  assumes finite_UNIV: \"finite (UNIV \\<Colon> 'a set)\"\nbegin\n\nlemma finite [simp]: \"finite (A \\<Colon> 'a set)\"\n  by (rule subset_UNIV finite_UNIV finite_subset)+\n\nlemma finite_code [code]: \"finite (A \\<Colon> 'a set) \\<longleftrightarrow> True\"\n  by simp\n\nend\n\ninstance prod :: (finite, finite) finite\n  by default (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product finite)\n\nlemma inj_graph: \"inj (%f. {(x, y). y = f x})\"\n  by (rule inj_onI, auto simp add: set_eq_iff fun_eq_iff)\n\ninstance \"fun\" :: (finite, finite) finite\nproof\n  show \"finite (UNIV :: ('a => 'b) set)\"\n  proof (rule finite_imageD)\n    let ?graph = \"%f::'a => 'b. {(x, y). y = f x}\"\n    have \"range ?graph \\<subseteq> Pow UNIV\" by simp\n    moreover have \"finite (Pow (UNIV :: ('a * 'b) set))\"\n      by (simp only: finite_Pow_iff finite)\n    ultimately show \"finite (range ?graph)\"\n      by (rule finite_subset)\n    show \"inj ?graph\" by (rule inj_graph)\n  qed\nqed\n\ninstance bool :: finite\n  by default (simp add: UNIV_bool)\n\ninstance set :: (finite) finite\n  by default (simp only: Pow_UNIV [symmetric] finite_Pow_iff finite)\n\ninstance unit :: finite\n  by default (simp add: UNIV_unit)\n\ninstance sum :: (finite, finite) finite\n  by default (simp only: UNIV_Plus_UNIV [symmetric] finite_Plus finite)\n\n\nsubsection {* A basic fold functional for finite sets *}\n\ntext {* The intended behaviour is\n@{text \"fold f z {x\\<^sub>1, ..., x\\<^sub>n} = f x\\<^sub>1 (\\<dots> (f x\\<^sub>n z)\\<dots>)\"}\nif @{text f} is ``left-commutative'':\n*}\n\nlocale comp_fun_commute =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma fun_left_comm: \"f y (f x z) = f x (f y z)\"\n  using comp_fun_commute by (simp add: fun_eq_iff)\n\nlemma commute_left_comp:\n  \"f y \\<circ> (f x \\<circ> g) = f x \\<circ> (f y \\<circ> g)\"\n  by (simp add: o_assoc comp_fun_commute)\n\nend\n\ninductive fold_graph :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> bool\"\nfor f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: 'b where\n  emptyI [intro]: \"fold_graph f z {} z\" |\n  insertI [intro]: \"x \\<notin> A \\<Longrightarrow> fold_graph f z A y\n      \\<Longrightarrow> fold_graph f z (insert x A) (f x y)\"\n\ninductive_cases empty_fold_graphE [elim!]: \"fold_graph f z {} x\"\n\ndefinition fold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b\" where\n  \"fold f z A = (if finite A then (THE y. fold_graph f z A y) else z)\"\n\ntext{*A tempting alternative for the definiens is\n@{term \"if finite A then THE y. fold_graph f z A y else e\"}.\nIt allows the removal of finiteness assumptions from the theorems\n@{text fold_comm}, @{text fold_reindex} and @{text fold_distrib}.\nThe proofs become ugly. It is not worth the effort. (???) *}\n\nlemma finite_imp_fold_graph: \"finite A \\<Longrightarrow> \\<exists>x. fold_graph f z A x\"\nby (induct rule: finite_induct) auto\n\n\nsubsubsection{*From @{const fold_graph} to @{term fold}*}\n\ncontext comp_fun_commute\nbegin\n\n\n\nlemma fold_graph_insertE_aux:\n  \"fold_graph f z A y \\<Longrightarrow> a \\<in> A \\<Longrightarrow> \\<exists>y'. y = f a y' \\<and> fold_graph f z (A - {a}) y'\"\nproof (induct set: fold_graph)\n  case (insertI x A y) show ?case\n  proof (cases \"x = a\")\n    assume \"x = a\" with insertI show ?case by auto\n  next\n    assume \"x \\<noteq> a\"\n    then obtain y' where y: \"y = f a y'\" and y': \"fold_graph f z (A - {a}) y'\"\n      using insertI by auto\n    have \"f x y = f a (f x y')\"\n      unfolding y by (rule fun_left_comm)\n    moreover have \"fold_graph f z (insert x A - {a}) (f x y')\"\n      using y' and `x \\<noteq> a` and `x \\<notin> A`\n      by (simp add: insert_Diff_if fold_graph.insertI)\n    ultimately show ?case by fast\n  qed\nqed simp\n\nlemma fold_graph_insertE:\n  assumes \"fold_graph f z (insert x A) v\" and \"x \\<notin> A\"\n  obtains y where \"v = f x y\" and \"fold_graph f z A y\"\nusing assms by (auto dest: fold_graph_insertE_aux [OF _ insertI1])\n\nlemma fold_graph_determ:\n  \"fold_graph f z A x \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> y = x\"\nproof (induct arbitrary: y set: fold_graph)\n  case (insertI x A y v)\n  from `fold_graph f z (insert x A) v` and `x \\<notin> A`\n  obtain y' where \"v = f x y'\" and \"fold_graph f z A y'\"\n    by (rule fold_graph_insertE)\n  from `fold_graph f z A y'` have \"y' = y\" by (rule insertI)\n  with `v = f x y'` show \"v = f x y\" by simp\nqed fast\n\nlemma fold_equality:\n  \"fold_graph f z A y \\<Longrightarrow> fold f z A = y\"\n  by (cases \"finite A\") (auto simp add: fold_def intro: fold_graph_determ dest: fold_graph_finite)\n\nlemma fold_graph_fold:\n  assumes \"finite A\"\n  shows \"fold_graph f z A (fold f z A)\"\nproof -\n  from assms have \"\\<exists>x. fold_graph f z A x\" by (rule finite_imp_fold_graph)\n  moreover note fold_graph_determ\n  ultimately have \"\\<exists>!x. fold_graph f z A x\" by (rule ex_ex1I)\n  then have \"fold_graph f z A (The (fold_graph f z A))\" by (rule theI')\n  with assms show ?thesis by (simp add: fold_def)\nqed\n\ntext {* The base case for @{text fold}: *}\n\nlemma (in -) fold_infinite [simp]:\n  assumes \"\\<not> finite A\"\n  shows \"fold f z A = z\"\n  using assms by (auto simp add: fold_def)\n\nlemma (in -) fold_empty [simp]:\n  \"fold f z {} = z\"\n  by (auto simp add: fold_def)\n\ntext{* The various recursion equations for @{const fold}: *}\n\nlemma fold_insert [simp]:\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"fold f z (insert x A) = f x (fold f z A)\"\nproof (rule fold_equality)\n  fix z\n  from `finite A` have \"fold_graph f z A (fold f z A)\" by (rule fold_graph_fold)\n  with `x \\<notin> A` have \"fold_graph f z (insert x A) (f x (fold f z A))\" by (rule fold_graph.insertI)\n  then show \"fold_graph f z (insert x A) (f x (fold f z A))\" by simp\nqed\n\ndeclare (in -) empty_fold_graphE [rule del] fold_graph.intros [rule del]\n  -- {* No more proofs involve these. *}\n\nlemma fold_fun_left_comm:\n  \"finite A \\<Longrightarrow> f x (fold f z A) = fold f (f x z) A\"\nproof (induct rule: finite_induct)\n  case empty then show ?case by simp\nnext\n  case (insert y A) then show ?case\n    by (simp add: fun_left_comm [of x])\nqed\n\nlemma fold_insert2:\n  \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> fold f z (insert x A)  = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nlemma fold_rec:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"fold f z A = f x (fold f z (A - {x}))\"\nproof -\n  have A: \"A = insert x (A - {x})\" using `x \\<in> A` by blast\n  then have \"fold f z A = fold f z (insert x (A - {x}))\" by simp\n  also have \"\\<dots> = f x (fold f z (A - {x}))\"\n    by (rule fold_insert) (simp add: `finite A`)+\n  finally show ?thesis .\nqed\n\nlemma fold_insert_remove:\n  assumes \"finite A\"\n  shows \"fold f z (insert x A) = f x (fold f z (A - {x}))\"\nproof -\n  from `finite A` have \"finite (insert x A)\" by auto\n  moreover have \"x \\<in> insert x A\" by auto\n  ultimately have \"fold f z (insert x A) = f x (fold f z (insert x A - {x}))\"\n    by (rule fold_rec)\n  then show ?thesis by simp\nqed\n\nlemma fold_set_union_disj:\n  assumes \"finite A\" \"finite B\" \"A \\<inter> B = {}\"\n  shows \"Finite_Set.fold f z (A \\<union> B) = Finite_Set.fold f (Finite_Set.fold f z A) B\"\nusing assms(2,1,3) by induction simp_all\n\nend\n\ntext{* Other properties of @{const fold}: *}\n\nlemma fold_image:\n  assumes \"inj_on g A\"\n  shows \"fold f z (g ` A) = fold (f \\<circ> g) z A\"\nproof (cases \"finite A\")\n  case False with assms show ?thesis by (auto dest: finite_imageD simp add: fold_def)\nnext\n  case True\n  have \"fold_graph f z (g ` A) = fold_graph (f \\<circ> g) z A\"\n  proof\n    fix w\n    show \"fold_graph f z (g ` A) w \\<longleftrightarrow> fold_graph (f \\<circ> g) z A w\" (is \"?P \\<longleftrightarrow> ?Q\")\n    proof\n      assume ?P then show ?Q using assms\n      proof (induct \"g ` A\" w arbitrary: A)\n        case emptyI then show ?case by (auto intro: fold_graph.emptyI)\n      next\n        case (insertI x A r B)\n        from `inj_on g B` `x \\<notin> A` `insert x A = image g B` obtain x' A' where\n          \"x' \\<notin> A'\" and [simp]: \"B = insert x' A'\" \"x = g x'\" \"A = g ` A'\"\n          by (rule inj_img_insertE)\n        from insertI.prems have \"fold_graph (f o g) z A' r\"\n          by (auto intro: insertI.hyps)\n        with `x' \\<notin> A'` have \"fold_graph (f \\<circ> g) z (insert x' A') ((f \\<circ> g) x' r)\"\n          by (rule fold_graph.insertI)\n        then show ?case by simp\n      qed\n    next\n      assume ?Q then show ?P using assms\n      proof induct\n        case emptyI thus ?case by (auto intro: fold_graph.emptyI)\n      next\n        case (insertI x A r)\n        from `x \\<notin> A` insertI.prems have \"g x \\<notin> g ` A\" by auto\n        moreover from insertI have \"fold_graph f z (g ` A) r\" by simp\n        ultimately have \"fold_graph f z (insert (g x) (g ` A)) (f (g x) r)\"\n          by (rule fold_graph.insertI)\n        then show ?case by simp\n      qed\n    qed\n  qed\n  with True assms show ?thesis by (auto simp add: fold_def)\nqed\n\nlemma fold_cong:\n  assumes \"comp_fun_commute f\" \"comp_fun_commute g\"\n  assumes \"finite A\" and cong: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"fold f s A = fold g t B\"\nproof -\n  have \"fold f s A = fold g s A\"  \n  using `finite A` cong proof (induct A)\n    case empty then show ?case by simp\n  next\n    case (insert x A)\n    interpret f: comp_fun_commute f by (fact `comp_fun_commute f`)\n    interpret g: comp_fun_commute g by (fact `comp_fun_commute g`)\n    from insert show ?case by simp\n  qed\n  with assms show ?thesis by simp\nqed\n\n\ntext {* A simplified version for idempotent functions: *}\n\nlocale comp_fun_idem = comp_fun_commute +\n  assumes comp_fun_idem: \"f x \\<circ> f x = f x\"\nbegin\n\nlemma fun_left_idem: \"f x (f x z) = f x z\"\n  using comp_fun_idem by (simp add: fun_eq_iff)\n\nlemma fold_insert_idem:\n  assumes fin: \"finite A\"\n  shows \"fold f z (insert x A)  = f x (fold f z A)\"\nproof cases\n  assume \"x \\<in> A\"\n  then obtain B where \"A = insert x B\" and \"x \\<notin> B\" by (rule set_insert)\n  then show ?thesis using assms by (simp add: comp_fun_idem fun_left_idem)\nnext\n  assume \"x \\<notin> A\" then show ?thesis using assms by simp\nqed\n\ndeclare fold_insert [simp del] fold_insert_idem [simp]\n\nlemma fold_insert_idem2:\n  \"finite A \\<Longrightarrow> fold f z (insert x A) = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nend\n\n\nsubsubsection {* Liftings to @{text comp_fun_commute} etc. *}\n\nlemma (in comp_fun_commute) comp_comp_fun_commute:\n  \"comp_fun_commute (f \\<circ> g)\"\nproof\nqed (simp_all add: comp_fun_commute)\n\nlemma (in comp_fun_idem) comp_comp_fun_idem:\n  \"comp_fun_idem (f \\<circ> g)\"\n  by (rule comp_fun_idem.intro, rule comp_comp_fun_commute, unfold_locales)\n    (simp_all add: comp_fun_idem)\n\nlemma (in comp_fun_commute) comp_fun_commute_funpow:\n  \"comp_fun_commute (\\<lambda>x. f x ^^ g x)\"\nproof\n  fix y x\n  show \"f y ^^ g y \\<circ> f x ^^ g x = f x ^^ g x \\<circ> f y ^^ g y\"\n  proof (cases \"x = y\")\n    case True then show ?thesis by simp\n  next\n    case False show ?thesis\n    proof (induct \"g x\" arbitrary: g)\n      case 0 then show ?case by simp\n    next\n      case (Suc n g)\n      have hyp1: \"f y ^^ g y \\<circ> f x = f x \\<circ> f y ^^ g y\"\n      proof (induct \"g y\" arbitrary: g)\n        case 0 then show ?case by simp\n      next\n        case (Suc n g)\n        def h \\<equiv> \"\\<lambda>z. g z - 1\"\n        with Suc have \"n = h y\" by simp\n        with Suc have hyp: \"f y ^^ h y \\<circ> f x = f x \\<circ> f y ^^ h y\"\n          by auto\n        from Suc h_def have \"g y = Suc (h y)\" by simp\n        then show ?case by (simp add: comp_assoc hyp)\n          (simp add: o_assoc comp_fun_commute)\n      qed\n      def h \\<equiv> \"\\<lambda>z. if z = x then g x - 1 else g z\"\n      with Suc have \"n = h x\" by simp\n      with Suc have \"f y ^^ h y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ h y\"\n        by auto\n      with False h_def have hyp2: \"f y ^^ g y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ g y\" by simp\n      from Suc h_def have \"g x = Suc (h x)\" by simp\n      then show ?case by (simp del: funpow.simps add: funpow_Suc_right o_assoc hyp2)\n        (simp add: comp_assoc hyp1)\n    qed\n  qed\nqed\n\n\nsubsubsection {* Expressing set operations via @{const fold} *}\n\nlemma comp_fun_commute_const:\n  \"comp_fun_commute (\\<lambda>_. f)\"\nproof\nqed rule\n\nlemma comp_fun_idem_insert:\n  \"comp_fun_idem insert\"\nproof\nqed auto\n\nlemma comp_fun_idem_remove:\n  \"comp_fun_idem Set.remove\"\nproof\nqed auto\n\nlemma (in semilattice_inf) comp_fun_idem_inf:\n  \"comp_fun_idem inf\"\nproof\nqed (auto simp add: inf_left_commute)\n\nlemma (in semilattice_sup) comp_fun_idem_sup:\n  \"comp_fun_idem sup\"\nproof\nqed (auto simp add: sup_left_commute)\n\nlemma union_fold_insert:\n  assumes \"finite A\"\n  shows \"A \\<union> B = fold insert B A\"\nproof -\n  interpret comp_fun_idem insert by (fact comp_fun_idem_insert)\n  from `finite A` show ?thesis by (induct A arbitrary: B) simp_all\nqed\n\nlemma minus_fold_remove:\n  assumes \"finite A\"\n  shows \"B - A = fold Set.remove B A\"\nproof -\n  interpret comp_fun_idem Set.remove by (fact comp_fun_idem_remove)\n  from `finite A` have \"fold Set.remove B A = B - A\" by (induct A arbitrary: B) auto\n  then show ?thesis ..\nqed\n\nlemma comp_fun_commute_filter_fold:\n  \"comp_fun_commute (\\<lambda>x A'. if P x then Set.insert x A' else A')\"\nproof - \n  interpret comp_fun_idem Set.insert by (fact comp_fun_idem_insert)\n  show ?thesis by default (auto simp: fun_eq_iff)\nqed\n\nlemma Set_filter_fold:\n  assumes \"finite A\"\n  shows \"Set.filter P A = fold (\\<lambda>x A'. if P x then Set.insert x A' else A') {} A\"\nusing assms\nby (induct A) \n  (auto simp add: Set.filter_def comp_fun_commute.fold_insert[OF comp_fun_commute_filter_fold])\n\nlemma inter_Set_filter:     \n  assumes \"finite B\"\n  shows \"A \\<inter> B = Set.filter (\\<lambda>x. x \\<in> A) B\"\nusing assms \nby (induct B) (auto simp: Set.filter_def)\n\nlemma image_fold_insert:\n  assumes \"finite A\"\n  shows \"image f A = fold (\\<lambda>k A. Set.insert (f k) A) {} A\"\nusing assms\nproof -\n  interpret comp_fun_commute \"\\<lambda>k A. Set.insert (f k) A\" by default auto\n  show ?thesis using assms by (induct A) auto\nqed\n\nlemma Ball_fold:\n  assumes \"finite A\"\n  shows \"Ball A P = fold (\\<lambda>k s. s \\<and> P k) True A\"\nusing assms\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<and> P k\" by default auto\n  show ?thesis using assms by (induct A) auto\nqed\n\nlemma Bex_fold:\n  assumes \"finite A\"\n  shows \"Bex A P = fold (\\<lambda>k s. s \\<or> P k) False A\"\nusing assms\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<or> P k\" by default auto\n  show ?thesis using assms by (induct A) auto\nqed\n\nlemma comp_fun_commute_Pow_fold: \n  \"comp_fun_commute (\\<lambda>x A. A \\<union> Set.insert x ` A)\" \n  by (clarsimp simp: fun_eq_iff comp_fun_commute_def) blast\n\nlemma Pow_fold:\n  assumes \"finite A\"\n  shows \"Pow A = fold (\\<lambda>x A. A \\<union> Set.insert x ` A) {{}} A\"\nusing assms\nproof -\n  interpret comp_fun_commute \"\\<lambda>x A. A \\<union> Set.insert x ` A\" by (rule comp_fun_commute_Pow_fold)\n  show ?thesis using assms by (induct A) (auto simp: Pow_insert)\nqed\n\nlemma fold_union_pair:\n  assumes \"finite B\"\n  shows \"(\\<Union>y\\<in>B. {(x, y)}) \\<union> A = fold (\\<lambda>y. Set.insert (x, y)) A B\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>y. Set.insert (x, y)\" by default auto\n  show ?thesis using assms  by (induct B arbitrary: A) simp_all\nqed\n\nlemma comp_fun_commute_product_fold: \n  assumes \"finite B\"\n  shows \"comp_fun_commute (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B)\" \nby default (auto simp: fold_union_pair[symmetric] assms)\n\nlemma product_fold:\n  assumes \"finite A\"\n  assumes \"finite B\"\n  shows \"A \\<times> B = fold (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B) {} A\"\nusing assms unfolding Sigma_def \nby (induct A) \n  (simp_all add: comp_fun_commute.fold_insert[OF comp_fun_commute_product_fold] fold_union_pair)\n\n\ncontext complete_lattice\nbegin\n\nlemma inf_Inf_fold_inf:\n  assumes \"finite A\"\n  shows \"inf (Inf A) B = fold inf B A\"\nproof -\n  interpret comp_fun_idem inf by (fact comp_fun_idem_inf)\n  from `finite A` fold_fun_left_comm show ?thesis by (induct A arbitrary: B)\n    (simp_all add: inf_commute fun_eq_iff)\nqed\n\nlemma sup_Sup_fold_sup:\n  assumes \"finite A\"\n  shows \"sup (Sup A) B = fold sup B A\"\nproof -\n  interpret comp_fun_idem sup by (fact comp_fun_idem_sup)\n  from `finite A` fold_fun_left_comm show ?thesis by (induct A arbitrary: B)\n    (simp_all add: sup_commute fun_eq_iff)\nqed\n\nlemma Inf_fold_inf:\n  assumes \"finite A\"\n  shows \"Inf A = fold inf top A\"\n  using assms inf_Inf_fold_inf [of A top] by (simp add: inf_absorb2)\n\nlemma Sup_fold_sup:\n  assumes \"finite A\"\n  shows \"Sup A = fold sup bot A\"\n  using assms sup_Sup_fold_sup [of A bot] by (simp add: sup_absorb2)\n\nlemma inf_INF_fold_inf:\n  assumes \"finite A\"\n  shows \"inf B (INFIMUM A f) = fold (inf \\<circ> f) B A\" (is \"?inf = ?fold\") \nproof (rule sym)\n  interpret comp_fun_idem inf by (fact comp_fun_idem_inf)\n  interpret comp_fun_idem \"inf \\<circ> f\" by (fact comp_comp_fun_idem)\n  from `finite A` show \"?fold = ?inf\"\n    by (induct A arbitrary: B)\n      (simp_all add: inf_left_commute)\nqed\n\nlemma sup_SUP_fold_sup:\n  assumes \"finite A\"\n  shows \"sup B (SUPREMUM A f) = fold (sup \\<circ> f) B A\" (is \"?sup = ?fold\") \nproof (rule sym)\n  interpret comp_fun_idem sup by (fact comp_fun_idem_sup)\n  interpret comp_fun_idem \"sup \\<circ> f\" by (fact comp_comp_fun_idem)\n  from `finite A` show \"?fold = ?sup\"\n    by (induct A arbitrary: B)\n      (simp_all add: sup_left_commute)\nqed\n\nlemma INF_fold_inf:\n  assumes \"finite A\"\n  shows \"INFIMUM A f = fold (inf \\<circ> f) top A\"\n  using assms inf_INF_fold_inf [of A top] by simp\n\nlemma SUP_fold_sup:\n  assumes \"finite A\"\n  shows \"SUPREMUM A f = fold (sup \\<circ> f) bot A\"\n  using assms sup_SUP_fold_sup [of A bot] by simp\n\nend\n\n\nsubsection {* Locales as mini-packages for fold operations *}\n\nsubsubsection {* The natural case *}\n\nlocale folding =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  fixes z :: \"'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\ninterpretation fold?: comp_fun_commute f\n  by default (insert comp_fun_commute, simp add: fun_eq_iff)\n\ndefinition F :: \"'a set \\<Rightarrow> 'b\"\nwhere\n  eq_fold: \"F A = fold f z A\"\n\nlemma empty [simp]:\n  \"F {} = z\"\n  by (simp add: eq_fold)\n\nlemma infinite [simp]:\n  \"\\<not> finite A \\<Longrightarrow> F A = z\"\n  by (simp add: eq_fold)\n \nlemma insert [simp]:\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert assms\n  have \"fold f z (insert x A) = f x (fold f z A)\" by simp\n  with `finite A` show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n \nlemma remove:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"F A = f x (F (A - {x}))\"\nproof -\n  from `x \\<in> A` obtain B where A: \"A = insert x B\" and \"x \\<notin> B\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from `finite A` A have \"finite B\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma insert_remove:\n  assumes \"finite A\"\n  shows \"F (insert x A) = f x (F (A - {x}))\"\n  using assms by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nend\n\n\nsubsubsection {* With idempotency *}\n\nlocale folding_idem = folding +\n  assumes comp_fun_idem: \"f x \\<circ> f x = f x\"\nbegin\n\ndeclare insert [simp del]\n\ninterpretation fold?: comp_fun_idem f\n  by default (insert comp_fun_commute comp_fun_idem, simp add: fun_eq_iff)\n\nlemma insert_idem [simp]:\n  assumes \"finite A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert_idem assms\n  have \"fold f z (insert x A) = f x (fold f z A)\" by simp\n  with `finite A` show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nend\n\n\nsubsection {* Finite cardinality *}\n\ntext {*\n  The traditional definition\n  @{prop \"card A \\<equiv> LEAST n. EX f. A = {f i | i. i < n}\"}\n  is ugly to work with.\n  But now that we have @{const fold} things are easy:\n*}\n\ndefinition card :: \"'a set \\<Rightarrow> nat\" where\n  \"card = folding.F (\\<lambda>_. Suc) 0\"\n\ninterpretation card!: folding \"\\<lambda>_. Suc\" 0\nwhere\n  \"folding.F (\\<lambda>_. Suc) 0 = card\"\nproof -\n  show \"folding (\\<lambda>_. Suc)\" by default rule\n  then interpret card!: folding \"\\<lambda>_. Suc\" 0 .\n  from card_def show \"folding.F (\\<lambda>_. Suc) 0 = card\" by rule\nqed\n\nlemma card_infinite:\n  \"\\<not> finite A \\<Longrightarrow> card A = 0\"\n  by (fact card.infinite)\n\nlemma card_empty:\n  \"card {} = 0\"\n  by (fact card.empty)\n\nlemma card_insert_disjoint:\n  \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> card (insert x A) = Suc (card A)\"\n  by (fact card.insert)\n\nlemma card_insert_if:\n  \"finite A \\<Longrightarrow> card (insert x A) = (if x \\<in> A then card A else Suc (card A))\"\n  by auto (simp add: card.insert_remove card.remove)\n\nlemma card_ge_0_finite:\n  \"card A > 0 \\<Longrightarrow> finite A\"\n  by (rule ccontr) simp\n\nlemma card_0_eq [simp]:\n  \"finite A \\<Longrightarrow> card A = 0 \\<longleftrightarrow> A = {}\"\n  by (auto dest: mk_disjoint_insert)\n\nlemma finite_UNIV_card_ge_0:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> card (UNIV :: 'a set) > 0\"\n  by (rule ccontr) simp\n\nlemma card_eq_0_iff:\n  \"card A = 0 \\<longleftrightarrow> A = {} \\<or> \\<not> finite A\"\n  by auto\n\nlemma card_gt_0_iff:\n  \"0 < card A \\<longleftrightarrow> A \\<noteq> {} \\<and> finite A\"\n  by (simp add: neq0_conv [symmetric] card_eq_0_iff) \n\nlemma card_Suc_Diff1:\n  \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> Suc (card (A - {x})) = card A\"\napply(rule_tac t = A in insert_Diff [THEN subst], assumption)\napply(simp del:insert_Diff_single)\ndone\n\nlemma card_Diff_singleton:\n  \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> card (A - {x}) = card A - 1\"\n  by (simp add: card_Suc_Diff1 [symmetric])\n\nlemma card_Diff_singleton_if:\n  \"finite A \\<Longrightarrow> card (A - {x}) = (if x \\<in> A then card A - 1 else card A)\"\n  by (simp add: card_Diff_singleton)\n\nlemma card_Diff_insert[simp]:\n  assumes \"finite A\" and \"a \\<in> A\" and \"a \\<notin> B\"\n  shows \"card (A - insert a B) = card (A - B) - 1\"\nproof -\n  have \"A - insert a B = (A - B) - {a}\" using assms by blast\n  then show ?thesis using assms by(simp add: card_Diff_singleton)\nqed\n\nlemma card_insert: \"finite A ==> card (insert x A) = Suc (card (A - {x}))\"\n  by (fact card.insert_remove)\n\nlemma card_insert_le: \"finite A ==> card A <= card (insert x A)\"\nby (simp add: card_insert_if)\n\nlemma card_Collect_less_nat[simp]: \"card{i::nat. i < n} = n\"\nby (induct n) (simp_all add:less_Suc_eq Collect_disj_eq)\n\nlemma card_Collect_le_nat[simp]: \"card{i::nat. i <= n} = Suc n\"\nusing card_Collect_less_nat[of \"Suc n\"] by(simp add: less_Suc_eq_le)\n\nlemma card_mono:\n  assumes \"finite B\" and \"A \\<subseteq> B\"\n  shows \"card A \\<le> card B\"\nproof -\n  from assms have \"finite A\" by (auto intro: finite_subset)\n  then show ?thesis using assms proof (induct A arbitrary: B)\n    case empty then show ?case by simp\n  next\n    case (insert x A)\n    then have \"x \\<in> B\" by simp\n    from insert have \"A \\<subseteq> B - {x}\" and \"finite (B - {x})\" by auto\n    with insert.hyps have \"card A \\<le> card (B - {x})\" by auto\n    with `finite A` `x \\<notin> A` `finite B` `x \\<in> B` show ?case by simp (simp only: card.remove)\n  qed\nqed\n\nlemma card_seteq: \"finite B ==> (!!A. A <= B ==> card B <= card A ==> A = B)\"\napply (induct rule: finite_induct)\napply simp\napply clarify\napply (subgoal_tac \"finite A & A - {x} <= F\")\n prefer 2 apply (blast intro: finite_subset, atomize)\napply (drule_tac x = \"A - {x}\" in spec)\napply (simp add: card_Diff_singleton_if split add: split_if_asm)\napply (case_tac \"card A\", auto)\ndone\n\nlemma psubset_card_mono: \"finite B ==> A < B ==> card A < card B\"\napply (simp add: psubset_eq linorder_not_le [symmetric])\napply (blast dest: card_seteq)\ndone\n\nlemma card_Un_Int:\n  assumes \"finite A\" and \"finite B\"\n  shows \"card A + card B = card (A \\<union> B) + card (A \\<inter> B)\"\nusing assms proof (induct A)\n  case empty then show ?case by simp\nnext\n case (insert x A) then show ?case\n    by (auto simp add: insert_absorb Int_insert_left)\nqed\n\nlemma card_Un_disjoint:\n  assumes \"finite A\" and \"finite B\"\n  assumes \"A \\<inter> B = {}\"\n  shows \"card (A \\<union> B) = card A + card B\"\nusing assms card_Un_Int [of A B] by simp\n\nlemma card_Diff_subset:\n  assumes \"finite B\" and \"B \\<subseteq> A\"\n  shows \"card (A - B) = card A - card B\"\nproof (cases \"finite A\")\n  case False with assms show ?thesis by simp\nnext\n  case True with assms show ?thesis by (induct B arbitrary: A) simp_all\nqed\n\nlemma card_Diff_subset_Int:\n  assumes AB: \"finite (A \\<inter> B)\" shows \"card (A - B) = card A - card (A \\<inter> B)\"\nproof -\n  have \"A - B = A - A \\<inter> B\" by auto\n  thus ?thesis\n    by (simp add: card_Diff_subset AB) \nqed\n\nlemma diff_card_le_card_Diff:\nassumes \"finite B\" shows \"card A - card B \\<le> card(A - B)\"\nproof-\n  have \"card A - card B \\<le> card A - card (A \\<inter> B)\"\n    using card_mono[OF assms Int_lower2, of A] by arith\n  also have \"\\<dots> = card(A-B)\" using assms by(simp add: card_Diff_subset_Int)\n  finally show ?thesis .\nqed\n\nlemma card_Diff1_less: \"finite A ==> x: A ==> card (A - {x}) < card A\"\napply (rule Suc_less_SucD)\napply (simp add: card_Suc_Diff1 del:card_Diff_insert)\ndone\n\nlemma card_Diff2_less:\n  \"finite A ==> x: A ==> y: A ==> card (A - {x} - {y}) < card A\"\napply (case_tac \"x = y\")\n apply (simp add: card_Diff1_less del:card_Diff_insert)\napply (rule less_trans)\n prefer 2 apply (auto intro!: card_Diff1_less simp del:card_Diff_insert)\ndone\n\nlemma card_Diff1_le: \"finite A ==> card (A - {x}) <= card A\"\napply (case_tac \"x : A\")\n apply (simp_all add: card_Diff1_less less_imp_le)\ndone\n\nlemma card_psubset: \"finite B ==> A \\<subseteq> B ==> card A < card B ==> A < B\"\nby (erule psubsetI, blast)\n\nlemma card_le_inj:\n  assumes fA: \"finite A\"\n    and fB: \"finite B\"\n    and c: \"card A \\<le> card B\"\n  shows \"\\<exists>f. f ` A \\<subseteq> B \\<and> inj_on f A\"\n  using fA fB c\nproof (induct arbitrary: B rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x s t)\n  then show ?case\n  proof (induct rule: finite_induct[OF \"insert.prems\"(1)])\n    case 1\n    then show ?case by simp\n  next\n    case (2 y t)\n    from \"2.prems\"(1,2,5) \"2.hyps\"(1,2) have cst: \"card s \\<le> card t\"\n      by simp\n    from \"2.prems\"(3) [OF \"2.hyps\"(1) cst]\n    obtain f where \"f ` s \\<subseteq> t\" \"inj_on f s\"\n      by blast\n    with \"2.prems\"(2) \"2.hyps\"(2) show ?case\n      apply -\n      apply (rule exI[where x = \"\\<lambda>z. if z = x then y else f z\"])\n      apply (auto simp add: inj_on_def)\n      done\n  qed\nqed\n\nlemma card_subset_eq:\n  assumes fB: \"finite B\"\n    and AB: \"A \\<subseteq> B\"\n    and c: \"card A = card B\"\n  shows \"A = B\"\nproof -\n  from fB AB have fA: \"finite A\"\n    by (auto intro: finite_subset)\n  from fA fB have fBA: \"finite (B - A)\"\n    by auto\n  have e: \"A \\<inter> (B - A) = {}\"\n    by blast\n  have eq: \"A \\<union> (B - A) = B\"\n    using AB by blast\n  from card_Un_disjoint[OF fA fBA e, unfolded eq c] have \"card (B - A) = 0\"\n    by arith\n  then have \"B - A = {}\"\n    unfolding card_eq_0_iff using fA fB by simp\n  with AB show \"A = B\"\n    by blast\nqed\n\nlemma insert_partition:\n  \"\\<lbrakk> x \\<notin> F; \\<forall>c1 \\<in> insert x F. \\<forall>c2 \\<in> insert x F. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {} \\<rbrakk>\n  \\<Longrightarrow> x \\<inter> \\<Union> F = {}\"\nby auto\n\nlemma finite_psubset_induct[consumes 1, case_names psubset]:\n  assumes fin: \"finite A\" \n  and     major: \"\\<And>A. finite A \\<Longrightarrow> (\\<And>B. B \\<subset> A \\<Longrightarrow> P B) \\<Longrightarrow> P A\" \n  shows \"P A\"\nusing fin\nproof (induct A taking: card rule: measure_induct_rule)\n  case (less A)\n  have fin: \"finite A\" by fact\n  have ih: \"\\<And>B. \\<lbrakk>card B < card A; finite B\\<rbrakk> \\<Longrightarrow> P B\" by fact\n  { fix B \n    assume asm: \"B \\<subset> A\"\n    from asm have \"card B < card A\" using psubset_card_mono fin by blast\n    moreover\n    from asm have \"B \\<subseteq> A\" by auto\n    then have \"finite B\" using fin finite_subset by blast\n    ultimately \n    have \"P B\" using ih by simp\n  }\n  with fin show \"P A\" using major by blast\nqed\n\nlemma finite_induct_select[consumes 1, case_names empty select]:\n  assumes \"finite S\"\n  assumes \"P {}\"\n  assumes select: \"\\<And>T. T \\<subset> S \\<Longrightarrow> P T \\<Longrightarrow> \\<exists>s\\<in>S - T. P (insert s T)\"\n  shows \"P S\"\nproof -\n  have \"0 \\<le> card S\" by simp\n  then have \"\\<exists>T \\<subseteq> S. card T = card S \\<and> P T\"\n  proof (induct rule: dec_induct)\n    case base with `P {}` show ?case\n      by (intro exI[of _ \"{}\"]) auto\n  next\n    case (step n)\n    then obtain T where T: \"T \\<subseteq> S\" \"card T = n\" \"P T\"\n      by auto\n    with `n < card S` have \"T \\<subset> S\" \"P T\"\n      by auto\n    with select[of T] obtain s where \"s \\<in> S\" \"s \\<notin> T\" \"P (insert s T)\"\n      by auto\n    with step(2) T `finite S` show ?case\n      by (intro exI[of _ \"insert s T\"]) (auto dest: finite_subset)\n  qed\n  with `finite S` show \"P S\"\n    by (auto dest: card_subset_eq)\nqed\n\ntext{* main cardinality theorem *}\nlemma card_partition [rule_format]:\n  \"finite C ==>\n     finite (\\<Union> C) -->\n     (\\<forall>c\\<in>C. card c = k) -->\n     (\\<forall>c1 \\<in> C. \\<forall>c2 \\<in> C. c1 \\<noteq> c2 --> c1 \\<inter> c2 = {}) -->\n     k * card(C) = card (\\<Union> C)\"\napply (erule finite_induct, simp)\napply (simp add: card_Un_disjoint insert_partition \n       finite_subset [of _ \"\\<Union> (insert x F)\"])\ndone\n\nlemma card_eq_UNIV_imp_eq_UNIV:\n  assumes fin: \"finite (UNIV :: 'a set)\"\n  and card: \"card A = card (UNIV :: 'a set)\"\n  shows \"A = (UNIV :: 'a set)\"\nproof\n  show \"A \\<subseteq> UNIV\" by simp\n  show \"UNIV \\<subseteq> A\"\n  proof\n    fix x\n    show \"x \\<in> A\"\n    proof (rule ccontr)\n      assume \"x \\<notin> A\"\n      then have \"A \\<subset> UNIV\" by auto\n      with fin have \"card A < card (UNIV :: 'a set)\" by (fact psubset_card_mono)\n      with card show False by simp\n    qed\n  qed\nqed\n\ntext{*The form of a finite set of given cardinality*}\n\nlemma card_eq_SucD:\nassumes \"card A = Suc k\"\nshows \"\\<exists>b B. A = insert b B & b \\<notin> B & card B = k & (k=0 \\<longrightarrow> B={})\"\nproof -\n  have fin: \"finite A\" using assms by (auto intro: ccontr)\n  moreover have \"card A \\<noteq> 0\" using assms by auto\n  ultimately obtain b where b: \"b \\<in> A\" by auto\n  show ?thesis\n  proof (intro exI conjI)\n    show \"A = insert b (A-{b})\" using b by blast\n    show \"b \\<notin> A - {b}\" by blast\n    show \"card (A - {b}) = k\" and \"k = 0 \\<longrightarrow> A - {b} = {}\"\n      using assms b fin by(fastforce dest:mk_disjoint_insert)+\n  qed\nqed\n\nlemma card_Suc_eq:\n  \"(card A = Suc k) =\n   (\\<exists>b B. A = insert b B & b \\<notin> B & card B = k & (k=0 \\<longrightarrow> B={}))\"\n apply(auto elim!: card_eq_SucD)\n apply(subst card.insert)\n apply(auto simp add: intro:ccontr)\n done\n\nlemma card_le_Suc_iff: \"finite A \\<Longrightarrow>\n  Suc n \\<le> card A = (\\<exists>a B. A = insert a B \\<and> a \\<notin> B \\<and> n \\<le> card B \\<and> finite B)\"\nby (fastforce simp: card_Suc_eq less_eq_nat.simps(2) insert_eq_iff\n  dest: subset_singletonD split: nat.splits if_splits)\n\nlemma finite_fun_UNIVD2:\n  assumes fin: \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  shows \"finite (UNIV :: 'b set)\"\nproof -\n  from fin have \"\\<And>arbitrary. finite (range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary))\"\n    by (rule finite_imageI)\n  moreover have \"\\<And>arbitrary. UNIV = range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary)\"\n    by (rule UNIV_eq_I) auto\n  ultimately show \"finite (UNIV :: 'b set)\" by simp\nqed\n\nlemma card_UNIV_unit [simp]: \"card (UNIV :: unit set) = 1\"\n  unfolding UNIV_unit by simp\n\nlemma infinite_arbitrarily_large:\n  assumes \"\\<not> finite A\"\n  shows \"\\<exists>B. finite B \\<and> card B = n \\<and> B \\<subseteq> A\"\nproof (induction n)\n  case 0 show ?case by (intro exI[of _ \"{}\"]) auto\nnext \n  case (Suc n)\n  then guess B .. note B = this\n  with `\\<not> finite A` have \"A \\<noteq> B\" by auto\n  with B have \"B \\<subset> A\" by auto\n  hence \"\\<exists>x. x \\<in> A - B\" by (elim psubset_imp_ex_mem)\n  then guess x .. note x = this\n  with B have \"finite (insert x B) \\<and> card (insert x B) = Suc n \\<and> insert x B \\<subseteq> A\"\n    by auto\n  thus \"\\<exists>B. finite B \\<and> card B = Suc n \\<and> B \\<subseteq> A\" ..\nqed\n\nsubsubsection {* Cardinality of image *}\n\nlemma card_image_le: \"finite A ==> card (f ` A) \\<le> card A\"\n  by (induct rule: finite_induct) (simp_all add: le_SucI card_insert_if)\n\nlemma card_image:\n  assumes \"inj_on f A\"\n  shows \"card (f ` A) = card A\"\nproof (cases \"finite A\")\n  case True then show ?thesis using assms by (induct A) simp_all\nnext\n  case False then have \"\\<not> finite (f ` A)\" using assms by (auto dest: finite_imageD)\n  with False show ?thesis by simp\nqed\n\nlemma bij_betw_same_card: \"bij_betw f A B \\<Longrightarrow> card A = card B\"\nby(auto simp: card_image bij_betw_def)\n\nlemma endo_inj_surj: \"finite A ==> f ` A \\<subseteq> A ==> inj_on f A ==> f ` A = A\"\nby (simp add: card_seteq card_image)\n\nlemma eq_card_imp_inj_on:\n  assumes \"finite A\" \"card(f ` A) = card A\" shows \"inj_on f A\"\nusing assms\nproof (induct rule:finite_induct)\n  case empty show ?case by simp\nnext\n  case (insert x A)\n  then show ?case using card_image_le [of A f]\n    by (simp add: card_insert_if split: if_splits)\nqed\n\nlemma inj_on_iff_eq_card: \"finite A \\<Longrightarrow> inj_on f A \\<longleftrightarrow> card(f ` A) = card A\"\n  by (blast intro: card_image eq_card_imp_inj_on)\n\nlemma card_inj_on_le:\n  assumes \"inj_on f A\" \"f ` A \\<subseteq> B\" \"finite B\" shows \"card A \\<le> card B\"\nproof -\n  have \"finite A\" using assms\n    by (blast intro: finite_imageD dest: finite_subset)\n  then show ?thesis using assms \n   by (force intro: card_mono simp: card_image [symmetric])\nqed\n\nlemma card_bij_eq:\n  \"[|inj_on f A; f ` A \\<subseteq> B; inj_on g B; g ` B \\<subseteq> A;\n     finite A; finite B |] ==> card A = card B\"\nby (auto intro: le_antisym card_inj_on_le)\n\nlemma bij_betw_finite:\n  assumes \"bij_betw f A B\"\n  shows \"finite A \\<longleftrightarrow> finite B\"\nusing assms unfolding bij_betw_def\nusing finite_imageD[of f A] by auto\n\nlemma inj_on_finite:\nassumes \"inj_on f A\" \"f ` A \\<le> B\" \"finite B\"\nshows \"finite A\"\nusing assms finite_imageD finite_subset by blast\n\n\nsubsubsection {* Pigeonhole Principles *}\n\nlemma pigeonhole: \"card A > card(f ` A) \\<Longrightarrow> ~ inj_on f A \"\nby (auto dest: card_image less_irrefl_nat)\n\nlemma pigeonhole_infinite:\nassumes  \"~ finite A\" and \"finite(f`A)\"\nshows \"EX a0:A. ~finite{a:A. f a = f a0}\"\nproof -\n  have \"finite(f`A) \\<Longrightarrow> ~ finite A \\<Longrightarrow> EX a0:A. ~finite{a:A. f a = f a0}\"\n  proof(induct \"f`A\" arbitrary: A rule: finite_induct)\n    case empty thus ?case by simp\n  next\n    case (insert b F)\n    show ?case\n    proof cases\n      assume \"finite{a:A. f a = b}\"\n      hence \"~ finite(A - {a:A. f a = b})\" using `\\<not> finite A` by simp\n      also have \"A - {a:A. f a = b} = {a:A. f a \\<noteq> b}\" by blast\n      finally have \"~ finite({a:A. f a \\<noteq> b})\" .\n      from insert(3)[OF _ this]\n      show ?thesis using insert(2,4) by simp (blast intro: rev_finite_subset)\n    next\n      assume 1: \"~finite{a:A. f a = b}\"\n      hence \"{a \\<in> A. f a = b} \\<noteq> {}\" by force\n      thus ?thesis using 1 by blast\n    qed\n  qed\n  from this[OF assms(2,1)] show ?thesis .\nqed\n\nlemma pigeonhole_infinite_rel:\nassumes \"~finite A\" and \"finite B\" and \"ALL a:A. EX b:B. R a b\"\nshows \"EX b:B. ~finite{a:A. R a b}\"\nproof -\n   let ?F = \"%a. {b:B. R a b}\"\n   from finite_Pow_iff[THEN iffD2, OF `finite B`]\n   have \"finite(?F ` A)\" by(blast intro: rev_finite_subset)\n   from pigeonhole_infinite[where f = ?F, OF assms(1) this]\n   obtain a0 where \"a0\\<in>A\" and 1: \"\\<not> finite {a\\<in>A. ?F a = ?F a0}\" ..\n   obtain b0 where \"b0 : B\" and \"R a0 b0\" using `a0:A` assms(3) by blast\n   { assume \"finite{a:A. R a b0}\"\n     then have \"finite {a\\<in>A. ?F a = ?F a0}\"\n       using `b0 : B` `R a0 b0` by(blast intro: rev_finite_subset)\n   }\n   with 1 `b0 : B` show ?thesis by blast\nqed\n\n\nsubsubsection {* Cardinality of sums *}\n\nlemma card_Plus:\n  assumes \"finite A\" and \"finite B\"\n  shows \"card (A <+> B) = card A + card B\"\nproof -\n  have \"Inl`A \\<inter> Inr`B = {}\" by fast\n  with assms show ?thesis\n    unfolding Plus_def\n    by (simp add: card_Un_disjoint card_image)\nqed\n\nlemma card_Plus_conv_if:\n  \"card (A <+> B) = (if finite A \\<and> finite B then card A + card B else 0)\"\n  by (auto simp add: card_Plus)\n\ntext {* Relates to equivalence classes.  Based on a theorem of F. Kamm\\\"uller.  *}\n\nlemma dvd_partition:\n  assumes f: \"finite (\\<Union>C)\" and \"\\<forall>c\\<in>C. k dvd card c\" \"\\<forall>c1\\<in>C. \\<forall>c2\\<in>C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}\"\n    shows \"k dvd card (\\<Union>C)\"\nproof -\n  have \"finite C\" \n    by (rule finite_UnionD [OF f])\n  then show ?thesis using assms\n  proof (induct rule: finite_induct)\n    case empty show ?case by simp\n  next\n    case (insert c C)\n    then show ?case \n      apply simp\n      apply (subst card_Un_disjoint)\n      apply (auto simp add: disjoint_eq_subset_Compl)\n      done\n  qed\nqed\n\nsubsubsection {* Relating injectivity and surjectivity *}\n\nlemma finite_surj_inj: assumes \"finite A\" \"A \\<subseteq> f ` A\" shows \"inj_on f A\"\nproof -\n  have \"f ` A = A\" \n    by (rule card_seteq [THEN sym]) (auto simp add: assms card_image_le)\n  then show ?thesis using assms\n    by (simp add: eq_card_imp_inj_on)\nqed\n\nlemma finite_UNIV_surj_inj: fixes f :: \"'a \\<Rightarrow> 'a\"\nshows \"finite(UNIV:: 'a set) \\<Longrightarrow> surj f \\<Longrightarrow> inj f\"\nby (blast intro: finite_surj_inj subset_UNIV)\n\nlemma finite_UNIV_inj_surj: fixes f :: \"'a \\<Rightarrow> 'a\"\nshows \"finite(UNIV:: 'a set) \\<Longrightarrow> inj f \\<Longrightarrow> surj f\"\nby(fastforce simp:surj_def dest!: endo_inj_surj)\n\ncorollary infinite_UNIV_nat [iff]:\n  \"\\<not> finite (UNIV :: nat set)\"\nproof\n  assume \"finite (UNIV :: nat set)\"\n  with finite_UNIV_inj_surj [of Suc]\n  show False by simp (blast dest: Suc_neq_Zero surjD)\nqed\n\nlemma infinite_UNIV_char_0:\n  \"\\<not> finite (UNIV :: 'a::semiring_char_0 set)\"\nproof\n  assume \"finite (UNIV :: 'a set)\"\n  with subset_UNIV have \"finite (range of_nat :: 'a set)\"\n    by (rule finite_subset)\n  moreover have \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n    by (simp add: inj_on_def)\n  ultimately have \"finite (UNIV :: nat set)\"\n    by (rule finite_imageD)\n  then show False\n    by simp\nqed\n\nhide_const (open) Finite_Set.fold\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Finite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8887588023318196, "lm_q1q2_score": 0.7856976986894696}}
{"text": "(*  Title:      HOL/Number_Theory/Cong.thy\n    Authors:    Christophe Tabacznyj, Lawrence C. Paulson, Amine Chaieb,\n                Thomas M. Rasmussen, Jeremy Avigad\n\nDefines congruence (notation: [x = y] (mod z)) for natural numbers and\nintegers.\n\nThis file combines and revises a number of prior developments.\n\nThe original theories \"GCD\" and \"Primes\" were by Christophe Tabacznyj\nand Lawrence C. Paulson, based on @{cite davenport92}. They introduced\ngcd, lcm, and prime for the natural numbers.\n\nThe original theory \"IntPrimes\" was by Thomas M. Rasmussen, and\nextended gcd, lcm, primes to the integers. Amine Chaieb provided\nanother extension of the notions to the integers, and added a number\nof results to \"Primes\" and \"GCD\".\n\nThe original theory, \"IntPrimes\", by Thomas M. Rasmussen, defined and\ndeveloped the congruence relations on the integers. The notion was\nextended to the natural numbers by Chaieb. Jeremy Avigad combined\nthese, revised and tidied them, made the development uniform for the\nnatural numbers and the integers, and added a number of new theorems.\n*)\n\nsection \\<open>Congruence\\<close>\n\ntheory Cong\nimports Primes\nbegin\n\nsubsection \\<open>Turn off \\<open>One_nat_def\\<close>\\<close>\n\nlemma power_eq_one_eq_nat [simp]: \"((x::nat)^m = 1) = (m = 0 | x = 1)\"\n  by (induct m) auto\n\ndeclare mod_pos_pos_trivial [simp]\n\n\nsubsection \\<open>Main definitions\\<close>\n\nclass cong =\n  fixes cong :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(1[_ = _] '(()mod _'))\")\nbegin\n\nabbreviation notcong :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (\"(1[_ \\<noteq> _] '(()mod _'))\")\n  where \"notcong x y m \\<equiv> \\<not> cong x y m\"\n\nend\n\n(* definitions for the natural numbers *)\n\ninstantiation nat :: cong\nbegin\n\ndefinition cong_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"cong_nat x y m = ((x mod m) = (y mod m))\"\n\ninstance ..\n\nend\n\n\n(* definitions for the integers *)\n\ninstantiation int :: cong\nbegin\n\ndefinition cong_int :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> bool\"\n  where \"cong_int x y m = ((x mod m) = (y mod m))\"\n\ninstance ..\n\nend\n\n\nsubsection \\<open>Set up Transfer\\<close>\n\n\nlemma transfer_nat_int_cong:\n  \"(x::int) >= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> m >= 0 \\<Longrightarrow>\n    ([(nat x) = (nat y)] (mod (nat m))) = ([x = y] (mod m))\"\n  unfolding cong_int_def cong_nat_def\n  by (metis Divides.transfer_int_nat_functions(2) nat_0_le nat_mod_distrib)\n\n\ndeclare transfer_morphism_nat_int[transfer add return:\n    transfer_nat_int_cong]\n\nlemma transfer_int_nat_cong:\n  \"[(int x) = (int y)] (mod (int m)) = [x = y] (mod m)\"\n  apply (auto simp add: cong_int_def cong_nat_def)\n  apply (auto simp add: zmod_int [symmetric])\n  done\n\ndeclare transfer_morphism_int_nat[transfer add return:\n    transfer_int_nat_cong]\n\n\nsubsection \\<open>Congruence\\<close>\n\n(* was zcong_0, etc. *)\nlemma cong_0_nat [simp, presburger]: \"([(a::nat) = b] (mod 0)) = (a = b)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_0_int [simp, presburger]: \"([(a::int) = b] (mod 0)) = (a = b)\"\n  unfolding cong_int_def by auto\n\nlemma cong_1_nat [simp, presburger]: \"[(a::nat) = b] (mod 1)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_Suc_0_nat [simp, presburger]: \"[(a::nat) = b] (mod Suc 0)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_1_int [simp, presburger]: \"[(a::int) = b] (mod 1)\"\n  unfolding cong_int_def by auto\n\nlemma cong_refl_nat [simp]: \"[(k::nat) = k] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_refl_int [simp]: \"[(k::int) = k] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_sym_nat: \"[(a::nat) = b] (mod m) \\<Longrightarrow> [b = a] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_sym_int: \"[(a::int) = b] (mod m) \\<Longrightarrow> [b = a] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_sym_eq_nat: \"[(a::nat) = b] (mod m) = [b = a] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_sym_eq_int: \"[(a::int) = b] (mod m) = [b = a] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_trans_nat [trans]:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow> [b = c] (mod m) \\<Longrightarrow> [a = c] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_trans_int [trans]:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [b = c] (mod m) \\<Longrightarrow> [a = c] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_add_nat:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a + c = b + d] (mod m)\"\n  unfolding cong_nat_def  by (metis mod_add_cong)\n\nlemma cong_add_int:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a + c = b + d] (mod m)\"\n  unfolding cong_int_def  by (metis mod_add_cong)\n\nlemma cong_diff_int:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a - c = b - d] (mod m)\"\n  unfolding cong_int_def  by (metis mod_diff_cong) \n\nlemma cong_diff_aux_int:\n  \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow>\n   (a::int) >= c \\<Longrightarrow> b >= d \\<Longrightarrow> [tsub a c = tsub b d] (mod m)\"\n  by (metis cong_diff_int tsub_eq)\n\nlemma cong_diff_nat:\n  assumes\"[a = b] (mod m)\" \"[c = d] (mod m)\" \"(a::nat) >= c\" \"b >= d\" \n  shows \"[a - c = b - d] (mod m)\"\n  using assms by (rule cong_diff_aux_int [transferred])\n\nlemma cong_mult_nat:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a * c = b * d] (mod m)\"\n  unfolding cong_nat_def  by (metis mod_mult_cong) \n\nlemma cong_mult_int:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a * c = b * d] (mod m)\"\n  unfolding cong_int_def  by (metis mod_mult_cong) \n\nlemma cong_exp_nat: \"[(x::nat) = y] (mod n) \\<Longrightarrow> [x^k = y^k] (mod n)\"\n  by (induct k) (auto simp add: cong_mult_nat)\n\nlemma cong_exp_int: \"[(x::int) = y] (mod n) \\<Longrightarrow> [x^k = y^k] (mod n)\"\n  by (induct k) (auto simp add: cong_mult_int)\n\nlemma cong_sum_nat [rule_format]:\n    \"(\\<forall>x\\<in>A. [((f x)::nat) = g x] (mod m)) \\<longrightarrow>\n      [(\\<Sum>x\\<in>A. f x) = (\\<Sum>x\\<in>A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_add_nat)\n  done\n\nlemma cong_sum_int [rule_format]:\n    \"(\\<forall>x\\<in>A. [((f x)::int) = g x] (mod m)) \\<longrightarrow>\n      [(\\<Sum>x\\<in>A. f x) = (\\<Sum>x\\<in>A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_add_int)\n  done\n\nlemma cong_prod_nat [rule_format]:\n    \"(\\<forall>x\\<in>A. [((f x)::nat) = g x] (mod m)) \\<longrightarrow>\n      [(\\<Prod>x\\<in>A. f x) = (\\<Prod>x\\<in>A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_mult_nat)\n  done\n\nlemma cong_prod_int [rule_format]:\n    \"(\\<forall>x\\<in>A. [((f x)::int) = g x] (mod m)) \\<longrightarrow>\n      [(\\<Prod>x\\<in>A. f x) = (\\<Prod>x\\<in>A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_mult_int)\n  done\n\nlemma cong_scalar_nat: \"[(a::nat)= b] (mod m) \\<Longrightarrow> [a * k = b * k] (mod m)\"\n  by (rule cong_mult_nat) simp_all\n\nlemma cong_scalar_int: \"[(a::int)= b] (mod m) \\<Longrightarrow> [a * k = b * k] (mod m)\"\n  by (rule cong_mult_int) simp_all\n\nlemma cong_scalar2_nat: \"[(a::nat)= b] (mod m) \\<Longrightarrow> [k * a = k * b] (mod m)\"\n  by (rule cong_mult_nat) simp_all\n\nlemma cong_scalar2_int: \"[(a::int)= b] (mod m) \\<Longrightarrow> [k * a = k * b] (mod m)\"\n  by (rule cong_mult_int) simp_all\n\nlemma cong_mult_self_nat: \"[(a::nat) * m = 0] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_mult_self_int: \"[(a::int) * m = 0] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_eq_diff_cong_0_int: \"[(a::int) = b] (mod m) = [a - b = 0] (mod m)\"\n  by (metis cong_add_int cong_diff_int cong_refl_int diff_add_cancel diff_self)\n\nlemma cong_eq_diff_cong_0_aux_int: \"a >= b \\<Longrightarrow>\n    [(a::int) = b] (mod m) = [tsub a b = 0] (mod m)\"\n  by (subst tsub_eq, assumption, rule cong_eq_diff_cong_0_int)\n\nlemma cong_eq_diff_cong_0_nat:\n  assumes \"(a::nat) >= b\"\n  shows \"[a = b] (mod m) = [a - b = 0] (mod m)\"\n  using assms by (rule cong_eq_diff_cong_0_aux_int [transferred])\n\nlemma cong_diff_cong_0'_nat:\n  \"[(x::nat) = y] (mod n) \\<longleftrightarrow>\n    (if x <= y then [y - x = 0] (mod n) else [x - y = 0] (mod n))\"\n  by (metis cong_eq_diff_cong_0_nat cong_sym_nat nat_le_linear)\n\nlemma cong_altdef_nat: \"(a::nat) >= b \\<Longrightarrow> [a = b] (mod m) = (m dvd (a - b))\"\n  apply (subst cong_eq_diff_cong_0_nat, assumption)\n  apply (unfold cong_nat_def)\n  apply (simp add: dvd_eq_mod_eq_0 [symmetric])\n  done\n\nlemma cong_altdef_int: \"[(a::int) = b] (mod m) = (m dvd (a - b))\"\n  by (metis cong_int_def zmod_eq_dvd_iff)\n\nlemma cong_abs_int: \"[(x::int) = y] (mod abs m) = [x = y] (mod m)\"\n  by (simp add: cong_altdef_int)\n\nlemma cong_square_int:\n  fixes a::int\n  shows \"\\<lbrakk> prime p; 0 < a; [a * a = 1] (mod p) \\<rbrakk>\n    \\<Longrightarrow> [a = 1] (mod p) \\<or> [a = - 1] (mod p)\"\n  apply (simp only: cong_altdef_int)\n  apply (subst prime_dvd_mult_eq_int [symmetric], assumption)\n  apply (auto simp add: field_simps)\n  done\n\nlemma cong_mult_rcancel_int:\n    \"coprime k (m::int) \\<Longrightarrow> [a * k = b * k] (mod m) = [a = b] (mod m)\"\n  by (metis cong_altdef_int left_diff_distrib coprime_dvd_mult_iff gcd.commute)\n\nlemma cong_mult_rcancel_nat:\n    \"coprime k (m::nat) \\<Longrightarrow> [a * k = b * k] (mod m) = [a = b] (mod m)\"\n  by (metis cong_mult_rcancel_int [transferred])\n\nlemma cong_mult_lcancel_nat:\n    \"coprime k (m::nat) \\<Longrightarrow> [k * a = k * b ] (mod m) = [a = b] (mod m)\"\n  by (simp add: mult.commute cong_mult_rcancel_nat)\n\nlemma cong_mult_lcancel_int:\n    \"coprime k (m::int) \\<Longrightarrow> [k * a = k * b] (mod m) = [a = b] (mod m)\"\n  by (simp add: mult.commute cong_mult_rcancel_int)\n\n(* was zcong_zgcd_zmult_zmod *)\nlemma coprime_cong_mult_int:\n  \"[(a::int) = b] (mod m) \\<Longrightarrow> [a = b] (mod n) \\<Longrightarrow> coprime m n\n    \\<Longrightarrow> [a = b] (mod m * n)\"\nby (metis divides_mult cong_altdef_int)\n\nlemma coprime_cong_mult_nat:\n  assumes \"[(a::nat) = b] (mod m)\" and \"[a = b] (mod n)\" and \"coprime m n\"\n  shows \"[a = b] (mod m * n)\"\n  by (metis assms coprime_cong_mult_int [transferred])\n\nlemma cong_less_imp_eq_nat: \"0 \\<le> (a::nat) \\<Longrightarrow>\n    a < m \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> b < m \\<Longrightarrow> [a = b] (mod m) \\<Longrightarrow> a = b\"\n  by (auto simp add: cong_nat_def)\n\nlemma cong_less_imp_eq_int: \"0 \\<le> (a::int) \\<Longrightarrow>\n    a < m \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> b < m \\<Longrightarrow> [a = b] (mod m) \\<Longrightarrow> a = b\"\n  by (auto simp add: cong_int_def)\n\nlemma cong_less_unique_nat:\n    \"0 < (m::nat) \\<Longrightarrow> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  by (auto simp: cong_nat_def) (metis mod_less_divisor mod_mod_trivial)\n\nlemma cong_less_unique_int:\n    \"0 < (m::int) \\<Longrightarrow> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  by (auto simp: cong_int_def)  (metis mod_mod_trivial pos_mod_conj)\n\nlemma cong_iff_lin_int: \"([(a::int) = b] (mod m)) = (\\<exists>k. b = a + m * k)\"\n  apply (auto simp add: cong_altdef_int dvd_def)\n  apply (rule_tac [!] x = \"-k\" in exI, auto)\n  done\n\nlemma cong_iff_lin_nat: \n   \"([(a::nat) = b] (mod m)) \\<longleftrightarrow> (\\<exists>k1 k2. b + k1 * m = a + k2 * m)\" (is \"?lhs = ?rhs\")\nproof (rule iffI)\n  assume eqm: ?lhs\n  show ?rhs\n  proof (cases \"b \\<le> a\")\n    case True\n    then show ?rhs using eqm\n      by (metis cong_altdef_nat dvd_def le_add_diff_inverse add_0_right mult_0 mult.commute)\n  next\n    case False\n    then show ?rhs using eqm \n      apply (subst (asm) cong_sym_eq_nat)\n      apply (auto simp: cong_altdef_nat)\n      apply (metis add_0_right add_diff_inverse dvd_div_mult_self less_or_eq_imp_le mult_0)\n      done\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by (metis cong_nat_def mod_mult_self2 mult.commute)\nqed\n\nlemma cong_gcd_eq_int: \"[(a::int) = b] (mod m) \\<Longrightarrow> gcd a m = gcd b m\"\n  by (metis cong_int_def gcd_red_int)\n\nlemma cong_gcd_eq_nat:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow>gcd a m = gcd b m\"\n  by (metis cong_gcd_eq_int [transferred])\n\nlemma cong_imp_coprime_nat: \"[(a::nat) = b] (mod m) \\<Longrightarrow> coprime a m \\<Longrightarrow> coprime b m\"\n  by (auto simp add: cong_gcd_eq_nat)\n\nlemma cong_imp_coprime_int: \"[(a::int) = b] (mod m) \\<Longrightarrow> coprime a m \\<Longrightarrow> coprime b m\"\n  by (auto simp add: cong_gcd_eq_int)\n\nlemma cong_cong_mod_nat: \"[(a::nat) = b] (mod m) = [a mod m = b mod m] (mod m)\"\n  by (auto simp add: cong_nat_def)\n\nlemma cong_cong_mod_int: \"[(a::int) = b] (mod m) = [a mod m = b mod m] (mod m)\"\n  by (auto simp add: cong_int_def)\n\nlemma cong_minus_int [iff]: \"[(a::int) = b] (mod -m) = [a = b] (mod m)\"\n  by (metis cong_iff_lin_int minus_equation_iff mult_minus_left mult_minus_right)\n\n(*\nlemma mod_dvd_mod_int:\n    \"0 < (m::int) \\<Longrightarrow> m dvd b \\<Longrightarrow> (a mod b mod m) = (a mod m)\"\n  apply (unfold dvd_def, auto)\n  apply (rule mod_mod_cancel)\n  apply auto\n  done\n\nlemma mod_dvd_mod:\n  assumes \"0 < (m::nat)\" and \"m dvd b\"\n  shows \"(a mod b mod m) = (a mod m)\"\n\n  apply (rule mod_dvd_mod_int [transferred])\n  using assms apply auto\n  done\n*)\n\nlemma cong_add_lcancel_nat:\n    \"[(a::nat) + x = a + y] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_lcancel_int:\n    \"[(a::int) + x = a + y] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_add_rcancel_nat: \"[(x::nat) + a = y + a] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_rcancel_int: \"[(x::int) + a = y + a] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_add_lcancel_0_nat: \"[(a::nat) + x = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_lcancel_0_int: \"[(a::int) + x = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_add_rcancel_0_nat: \"[x + (a::nat) = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_rcancel_0_int: \"[x + (a::int) = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_dvd_modulus_nat: \"[(x::nat) = y] (mod m) \\<Longrightarrow> n dvd m \\<Longrightarrow>\n    [x = y] (mod n)\"\n  apply (auto simp add: cong_iff_lin_nat dvd_def)\n  apply (rule_tac x=\"k1 * k\" in exI)\n  apply (rule_tac x=\"k2 * k\" in exI)\n  apply (simp add: field_simps)\n  done\n\nlemma cong_dvd_modulus_int: \"[(x::int) = y] (mod m) \\<Longrightarrow> n dvd m \\<Longrightarrow> [x = y] (mod n)\"\n  by (auto simp add: cong_altdef_int dvd_def)\n\nlemma cong_dvd_eq_nat: \"[(x::nat) = y] (mod n) \\<Longrightarrow> n dvd x \\<longleftrightarrow> n dvd y\"\n  unfolding cong_nat_def by (auto simp add: dvd_eq_mod_eq_0)\n\nlemma cong_dvd_eq_int: \"[(x::int) = y] (mod n) \\<Longrightarrow> n dvd x \\<longleftrightarrow> n dvd y\"\n  unfolding cong_int_def by (auto simp add: dvd_eq_mod_eq_0)\n\nlemma cong_mod_nat: \"(n::nat) ~= 0 \\<Longrightarrow> [a mod n = a] (mod n)\"\n  by (simp add: cong_nat_def)\n\nlemma cong_mod_int: \"(n::int) ~= 0 \\<Longrightarrow> [a mod n = a] (mod n)\"\n  by (simp add: cong_int_def)\n\nlemma mod_mult_cong_nat: \"(a::nat) ~= 0 \\<Longrightarrow> b ~= 0\n    \\<Longrightarrow> [x mod (a * b) = y] (mod a) \\<longleftrightarrow> [x = y] (mod a)\"\n  by (simp add: cong_nat_def mod_mult2_eq  mod_add_left_eq)\n\nlemma neg_cong_int: \"([(a::int) = b] (mod m)) = ([-a = -b] (mod m))\"\n  by (metis cong_int_def minus_minus zminus_zmod)\n\nlemma cong_modulus_neg_int: \"([(a::int) = b] (mod m)) = ([a = b] (mod -m))\"\n  by (auto simp add: cong_altdef_int)\n\nlemma mod_mult_cong_int: \"(a::int) ~= 0 \\<Longrightarrow> b ~= 0\n    \\<Longrightarrow> [x mod (a * b) = y] (mod a) \\<longleftrightarrow> [x = y] (mod a)\"\n  apply (cases \"b > 0\", simp add: cong_int_def mod_mod_cancel mod_add_left_eq)\n  apply (subst (1 2) cong_modulus_neg_int)\n  apply (unfold cong_int_def)\n  apply (subgoal_tac \"a * b = (-a * -b)\")\n  apply (erule ssubst)\n  apply (subst zmod_zmult2_eq)\n  apply (auto simp add: mod_add_left_eq mod_minus_right div_minus_right)\n  apply (metis mod_diff_left_eq mod_diff_right_eq mod_mult_self1_is_0 diff_zero)+\n  done\n\nlemma cong_to_1_nat: \"([(a::nat) = 1] (mod n)) \\<Longrightarrow> (n dvd (a - 1))\"\n  apply (cases \"a = 0\", force)\n  by (metis cong_altdef_nat leI less_one)\n\nlemma cong_0_1_nat': \"[(0::nat) = Suc 0] (mod n) = (n = Suc 0)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_0_1_nat: \"[(0::nat) = 1] (mod n) = (n = 1)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_0_1_int: \"[(0::int) = 1] (mod n) = ((n = 1) | (n = -1))\"\n  unfolding cong_int_def by (auto simp add: zmult_eq_1_iff)\n\nlemma cong_to_1'_nat: \"[(a::nat) = 1] (mod n) \\<longleftrightarrow>\n    a = 0 \\<and> n = 1 \\<or> (\\<exists>m. a = 1 + m * n)\"\nby (metis add.right_neutral cong_0_1_nat cong_iff_lin_nat cong_to_1_nat dvd_div_mult_self leI le_add_diff_inverse less_one mult_eq_if)\n\nlemma cong_le_nat: \"(y::nat) <= x \\<Longrightarrow> [x = y] (mod n) \\<longleftrightarrow> (\\<exists>q. x = q * n + y)\"\n  by (metis cong_altdef_nat Nat.le_imp_diff_is_add dvd_def mult.commute)\n\nlemma cong_solve_nat: \"(a::nat) \\<noteq> 0 \\<Longrightarrow> EX x. [a * x = gcd a n] (mod n)\"\n  apply (cases \"n = 0\")\n  apply force\n  apply (frule bezout_nat [of a n], auto)\n  by (metis cong_add_rcancel_0_nat cong_mult_self_nat mult.commute)\n\nlemma cong_solve_int: \"(a::int) \\<noteq> 0 \\<Longrightarrow> EX x. [a * x = gcd a n] (mod n)\"\n  apply (cases \"n = 0\")\n  apply (cases \"a \\<ge> 0\")\n  apply auto\n  apply (rule_tac x = \"-1\" in exI)\n  apply auto\n  apply (insert bezout_int [of a n], auto)\n  by (metis cong_iff_lin_int mult.commute)\n\nlemma cong_solve_dvd_nat:\n  assumes a: \"(a::nat) \\<noteq> 0\" and b: \"gcd a n dvd d\"\n  shows \"EX x. [a * x = d] (mod n)\"\nproof -\n  from cong_solve_nat [OF a] obtain x where \"[a * x = gcd a n](mod n)\"\n    by auto\n  then have \"[(d div gcd a n) * (a * x) = (d div gcd a n) * gcd a n] (mod n)\"\n    by (elim cong_scalar2_nat)\n  also from b have \"(d div gcd a n) * gcd a n = d\"\n    by (rule dvd_div_mult_self)\n  also have \"(d div gcd a n) * (a * x) = a * (d div gcd a n * x)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma cong_solve_dvd_int:\n  assumes a: \"(a::int) \\<noteq> 0\" and b: \"gcd a n dvd d\"\n  shows \"EX x. [a * x = d] (mod n)\"\nproof -\n  from cong_solve_int [OF a] obtain x where \"[a * x = gcd a n](mod n)\"\n    by auto\n  then have \"[(d div gcd a n) * (a * x) = (d div gcd a n) * gcd a n] (mod n)\"\n    by (elim cong_scalar2_int)\n  also from b have \"(d div gcd a n) * gcd a n = d\"\n    by (rule dvd_div_mult_self)\n  also have \"(d div gcd a n) * (a * x) = a * (d div gcd a n * x)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma cong_solve_coprime_nat: \"coprime (a::nat) n \\<Longrightarrow> EX x. [a * x = 1] (mod n)\"\n  apply (cases \"a = 0\")\n  apply force\n  apply (metis cong_solve_nat)\n  done\n\nlemma cong_solve_coprime_int: \"coprime (a::int) n \\<Longrightarrow> EX x. [a * x = 1] (mod n)\"\n  apply (cases \"a = 0\")\n  apply auto\n  apply (cases \"n \\<ge> 0\")\n  apply auto\n  apply (metis cong_solve_int)\n  done\n\nlemma coprime_iff_invertible_nat:\n  \"m > 0 \\<Longrightarrow> coprime a m = (EX x. [a * x = Suc 0] (mod m))\"\n  by (metis One_nat_def cong_gcd_eq_nat cong_solve_coprime_nat coprime_lmult gcd.commute gcd_Suc_0)\n  \nlemma coprime_iff_invertible_int: \"m > (0::int) \\<Longrightarrow> coprime a m = (EX x. [a * x = 1] (mod m))\"\n  apply (auto intro: cong_solve_coprime_int)\n  apply (metis cong_int_def coprime_mul_eq gcd_1_int gcd.commute gcd_red_int)\n  done\n\nlemma coprime_iff_invertible'_nat: \"m > 0 \\<Longrightarrow> coprime a m =\n    (EX x. 0 \\<le> x & x < m & [a * x = Suc 0] (mod m))\"\n  apply (subst coprime_iff_invertible_nat)\n  apply auto\n  apply (auto simp add: cong_nat_def)\n  apply (metis mod_less_divisor mod_mult_right_eq)\n  done\n\nlemma coprime_iff_invertible'_int: \"m > (0::int) \\<Longrightarrow> coprime a m =\n    (EX x. 0 <= x & x < m & [a * x = 1] (mod m))\"\n  apply (subst coprime_iff_invertible_int)\n  apply (auto simp add: cong_int_def)\n  apply (metis mod_mult_right_eq pos_mod_conj)\n  done\n\nlemma cong_cong_lcm_nat: \"[(x::nat) = y] (mod a) \\<Longrightarrow>\n    [x = y] (mod b) \\<Longrightarrow> [x = y] (mod lcm a b)\"\n  apply (cases \"y \\<le> x\")\n  apply (metis cong_altdef_nat lcm_least)\n  apply (meson cong_altdef_nat cong_sym_nat lcm_least_iff nat_le_linear)\n  done\n\nlemma cong_cong_lcm_int: \"[(x::int) = y] (mod a) \\<Longrightarrow>\n    [x = y] (mod b) \\<Longrightarrow> [x = y] (mod lcm a b)\"\n  by (auto simp add: cong_altdef_int lcm_least) [1]\n\nlemma cong_cong_prod_coprime_nat [rule_format]: \"finite A \\<Longrightarrow>\n    (\\<forall>i\\<in>A. (\\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))) \\<longrightarrow>\n    (\\<forall>i\\<in>A. [(x::nat) = y] (mod m i)) \\<longrightarrow>\n      [x = y] (mod (\\<Prod>i\\<in>A. m i))\"\n  apply (induct set: finite)\n  apply auto\n  apply (metis One_nat_def coprime_cong_mult_nat gcd.commute prod_coprime)\n  done\n\nlemma cong_cong_prod_coprime_int [rule_format]: \"finite A \\<Longrightarrow>\n    (\\<forall>i\\<in>A. (\\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))) \\<longrightarrow>\n    (\\<forall>i\\<in>A. [(x::int) = y] (mod m i)) \\<longrightarrow>\n      [x = y] (mod (\\<Prod>i\\<in>A. m i))\"\n  apply (induct set: finite)\n  apply auto\n  apply (metis coprime_cong_mult_int gcd.commute prod_coprime)\n  done\n\nlemma binary_chinese_remainder_aux_nat:\n  assumes a: \"coprime (m1::nat) m2\"\n  shows \"EX b1 b2. [b1 = 1] (mod m1) \\<and> [b1 = 0] (mod m2) \\<and>\n    [b2 = 0] (mod m1) \\<and> [b2 = 1] (mod m2)\"\nproof -\n  from cong_solve_coprime_nat [OF a] obtain x1 where one: \"[m1 * x1 = 1] (mod m2)\"\n    by auto\n  from a have b: \"coprime m2 m1\"\n    by (subst gcd.commute)\n  from cong_solve_coprime_nat [OF b] obtain x2 where two: \"[m2 * x2 = 1] (mod m1)\"\n    by auto\n  have \"[m1 * x1 = 0] (mod m1)\"\n    by (subst mult.commute, rule cong_mult_self_nat)\n  moreover have \"[m2 * x2 = 0] (mod m2)\"\n    by (subst mult.commute, rule cong_mult_self_nat)\n  moreover note one two\n  ultimately show ?thesis by blast\nqed\n\nlemma binary_chinese_remainder_aux_int:\n  assumes a: \"coprime (m1::int) m2\"\n  shows \"EX b1 b2. [b1 = 1] (mod m1) \\<and> [b1 = 0] (mod m2) \\<and>\n    [b2 = 0] (mod m1) \\<and> [b2 = 1] (mod m2)\"\nproof -\n  from cong_solve_coprime_int [OF a] obtain x1 where one: \"[m1 * x1 = 1] (mod m2)\"\n    by auto\n  from a have b: \"coprime m2 m1\"\n    by (subst gcd.commute)\n  from cong_solve_coprime_int [OF b] obtain x2 where two: \"[m2 * x2 = 1] (mod m1)\"\n    by auto\n  have \"[m1 * x1 = 0] (mod m1)\"\n    by (subst mult.commute, rule cong_mult_self_int)\n  moreover have \"[m2 * x2 = 0] (mod m2)\"\n    by (subst mult.commute, rule cong_mult_self_int)\n  moreover note one two\n  ultimately show ?thesis by blast\nqed\n\nlemma binary_chinese_remainder_nat:\n  assumes a: \"coprime (m1::nat) m2\"\n  shows \"EX x. [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  from binary_chinese_remainder_aux_nat [OF a] obtain b1 b2\n      where \"[b1 = 1] (mod m1)\" and \"[b1 = 0] (mod m2)\" and\n            \"[b2 = 0] (mod m1)\" and \"[b2 = 1] (mod m2)\"\n    by blast\n  let ?x = \"u1 * b1 + u2 * b2\"\n  have \"[?x = u1 * 1 + u2 * 0] (mod m1)\"\n    apply (rule cong_add_nat)\n    apply (rule cong_scalar2_nat)\n    apply (rule \\<open>[b1 = 1] (mod m1)\\<close>)\n    apply (rule cong_scalar2_nat)\n    apply (rule \\<open>[b2 = 0] (mod m1)\\<close>)\n    done\n  then have \"[?x = u1] (mod m1)\" by simp\n  have \"[?x = u1 * 0 + u2 * 1] (mod m2)\"\n    apply (rule cong_add_nat)\n    apply (rule cong_scalar2_nat)\n    apply (rule \\<open>[b1 = 0] (mod m2)\\<close>)\n    apply (rule cong_scalar2_nat)\n    apply (rule \\<open>[b2 = 1] (mod m2)\\<close>)\n    done\n  then have \"[?x = u2] (mod m2)\" by simp\n  with \\<open>[?x = u1] (mod m1)\\<close> show ?thesis by blast\nqed\n\nlemma binary_chinese_remainder_int:\n  assumes a: \"coprime (m1::int) m2\"\n  shows \"EX x. [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  from binary_chinese_remainder_aux_int [OF a] obtain b1 b2\n    where \"[b1 = 1] (mod m1)\" and \"[b1 = 0] (mod m2)\" and\n          \"[b2 = 0] (mod m1)\" and \"[b2 = 1] (mod m2)\"\n    by blast\n  let ?x = \"u1 * b1 + u2 * b2\"\n  have \"[?x = u1 * 1 + u2 * 0] (mod m1)\"\n    apply (rule cong_add_int)\n    apply (rule cong_scalar2_int)\n    apply (rule \\<open>[b1 = 1] (mod m1)\\<close>)\n    apply (rule cong_scalar2_int)\n    apply (rule \\<open>[b2 = 0] (mod m1)\\<close>)\n    done\n  then have \"[?x = u1] (mod m1)\" by simp\n  have \"[?x = u1 * 0 + u2 * 1] (mod m2)\"\n    apply (rule cong_add_int)\n    apply (rule cong_scalar2_int)\n    apply (rule \\<open>[b1 = 0] (mod m2)\\<close>)\n    apply (rule cong_scalar2_int)\n    apply (rule \\<open>[b2 = 1] (mod m2)\\<close>)\n    done\n  then have \"[?x = u2] (mod m2)\" by simp\n  with \\<open>[?x = u1] (mod m1)\\<close> show ?thesis by blast\nqed\n\nlemma cong_modulus_mult_nat: \"[(x::nat) = y] (mod m * n) \\<Longrightarrow>\n    [x = y] (mod m)\"\n  apply (cases \"y \\<le> x\")\n  apply (simp add: cong_altdef_nat)\n  apply (erule dvd_mult_left)\n  apply (rule cong_sym_nat)\n  apply (subst (asm) cong_sym_eq_nat)\n  apply (simp add: cong_altdef_nat)\n  apply (erule dvd_mult_left)\n  done\n\nlemma cong_modulus_mult_int: \"[(x::int) = y] (mod m * n) \\<Longrightarrow>\n    [x = y] (mod m)\"\n  apply (simp add: cong_altdef_int)\n  apply (erule dvd_mult_left)\n  done\n\nlemma cong_less_modulus_unique_nat:\n    \"[(x::nat) = y] (mod m) \\<Longrightarrow> x < m \\<Longrightarrow> y < m \\<Longrightarrow> x = y\"\n  by (simp add: cong_nat_def)\n\nlemma binary_chinese_remainder_unique_nat:\n  assumes a: \"coprime (m1::nat) m2\"\n    and nz: \"m1 \\<noteq> 0\" \"m2 \\<noteq> 0\"\n  shows \"\\<exists>!x. x < m1 * m2 \\<and> [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  from binary_chinese_remainder_nat [OF a] obtain y where\n      \"[y = u1] (mod m1)\" and \"[y = u2] (mod m2)\"\n    by blast\n  let ?x = \"y mod (m1 * m2)\"\n  from nz have less: \"?x < m1 * m2\"\n    by auto\n  have one: \"[?x = u1] (mod m1)\"\n    apply (rule cong_trans_nat)\n    prefer 2\n    apply (rule \\<open>[y = u1] (mod m1)\\<close>)\n    apply (rule cong_modulus_mult_nat)\n    apply (rule cong_mod_nat)\n    using nz apply auto\n    done\n  have two: \"[?x = u2] (mod m2)\"\n    apply (rule cong_trans_nat)\n    prefer 2\n    apply (rule \\<open>[y = u2] (mod m2)\\<close>)\n    apply (subst mult.commute)\n    apply (rule cong_modulus_mult_nat)\n    apply (rule cong_mod_nat)\n    using nz apply auto\n    done\n  have \"ALL z. z < m1 * m2 \\<and> [z = u1] (mod m1) \\<and> [z = u2] (mod m2) \\<longrightarrow> z = ?x\"\n  proof clarify\n    fix z\n    assume \"z < m1 * m2\"\n    assume \"[z = u1] (mod m1)\" and  \"[z = u2] (mod m2)\"\n    have \"[?x = z] (mod m1)\"\n      apply (rule cong_trans_nat)\n      apply (rule \\<open>[?x = u1] (mod m1)\\<close>)\n      apply (rule cong_sym_nat)\n      apply (rule \\<open>[z = u1] (mod m1)\\<close>)\n      done\n    moreover have \"[?x = z] (mod m2)\"\n      apply (rule cong_trans_nat)\n      apply (rule \\<open>[?x = u2] (mod m2)\\<close>)\n      apply (rule cong_sym_nat)\n      apply (rule \\<open>[z = u2] (mod m2)\\<close>)\n      done\n    ultimately have \"[?x = z] (mod m1 * m2)\"\n      by (auto intro: coprime_cong_mult_nat a)\n    with \\<open>z < m1 * m2\\<close> \\<open>?x < m1 * m2\\<close> show \"z = ?x\"\n      apply (intro cong_less_modulus_unique_nat)\n      apply (auto, erule cong_sym_nat)\n      done\n  qed\n  with less one two show ?thesis by auto\n qed\n\nlemma chinese_remainder_aux_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and cop: \"ALL i : A. (ALL j : A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))\"\n  shows \"EX b. (ALL i : A. [b i = 1] (mod m i) \\<and> [b i = 0] (mod (\\<Prod>j \\<in> A - {i}. m j)))\"\nproof (rule finite_set_choice, rule fin, rule ballI)\n  fix i\n  assume \"i : A\"\n  with cop have \"coprime (\\<Prod>j \\<in> A - {i}. m j) (m i)\"\n    by (intro prod_coprime, auto)\n  then have \"EX x. [(\\<Prod>j \\<in> A - {i}. m j) * x = 1] (mod m i)\"\n    by (elim cong_solve_coprime_nat)\n  then obtain x where \"[(\\<Prod>j \\<in> A - {i}. m j) * x = 1] (mod m i)\"\n    by auto\n  moreover have \"[(\\<Prod>j \\<in> A - {i}. m j) * x = 0]\n    (mod (\\<Prod>j \\<in> A - {i}. m j))\"\n    by (subst mult.commute, rule cong_mult_self_nat)\n  ultimately show \"\\<exists>a. [a = 1] (mod m i) \\<and> [a = 0]\n      (mod prod m (A - {i}))\"\n    by blast\nqed\n\nlemma chinese_remainder_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n    and u :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and cop: \"ALL i:A. (ALL j : A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))\"\n  shows \"EX x. (ALL i:A. [x = u i] (mod m i))\"\nproof -\n  from chinese_remainder_aux_nat [OF fin cop] obtain b where\n    bprop: \"ALL i:A. [b i = 1] (mod m i) \\<and>\n      [b i = 0] (mod (\\<Prod>j \\<in> A - {i}. m j))\"\n    by blast\n  let ?x = \"\\<Sum>i\\<in>A. (u i) * (b i)\"\n  show \"?thesis\"\n  proof (rule exI, clarify)\n    fix i\n    assume a: \"i : A\"\n    show \"[?x = u i] (mod m i)\"\n    proof -\n      from fin a have \"?x = (\\<Sum>j \\<in> {i}. u j * b j) +\n          (\\<Sum>j \\<in> A - {i}. u j * b j)\"\n        by (subst sum.union_disjoint [symmetric], auto intro: sum.cong)\n      then have \"[?x = u i * b i + (\\<Sum>j \\<in> A - {i}. u j * b j)] (mod m i)\"\n        by auto\n      also have \"[u i * b i + (\\<Sum>j \\<in> A - {i}. u j * b j) =\n                  u i * 1 + (\\<Sum>j \\<in> A - {i}. u j * 0)] (mod m i)\"\n        apply (rule cong_add_nat)\n        apply (rule cong_scalar2_nat)\n        using bprop a apply blast\n        apply (rule cong_sum_nat)\n        apply (rule cong_scalar2_nat)\n        using bprop apply auto\n        apply (rule cong_dvd_modulus_nat)\n        apply (drule (1) bspec)\n        apply (erule conjE)\n        apply assumption\n        apply rule\n        using fin a apply auto\n        done\n      finally show ?thesis\n        by simp\n    qed\n  qed\nqed\n\nlemma coprime_cong_prod_nat [rule_format]: \"finite A \\<Longrightarrow>\n    (\\<forall>i\\<in>A. (\\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))) \\<longrightarrow>\n      (\\<forall>i\\<in>A. [(x::nat) = y] (mod m i)) \\<longrightarrow>\n         [x = y] (mod (\\<Prod>i\\<in>A. m i))\"\n  apply (induct set: finite)\n  apply auto\n  apply (metis One_nat_def coprime_cong_mult_nat gcd.commute prod_coprime)\n  done\n\nlemma chinese_remainder_unique_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n    and u :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and nz: \"\\<forall>i\\<in>A. m i \\<noteq> 0\"\n    and cop: \"\\<forall>i\\<in>A. (\\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))\"\n  shows \"\\<exists>!x. x < (\\<Prod>i\\<in>A. m i) \\<and> (\\<forall>i\\<in>A. [x = u i] (mod m i))\"\nproof -\n  from chinese_remainder_nat [OF fin cop]\n  obtain y where one: \"(ALL i:A. [y = u i] (mod m i))\"\n    by blast\n  let ?x = \"y mod (\\<Prod>i\\<in>A. m i)\"\n  from fin nz have prodnz: \"(\\<Prod>i\\<in>A. m i) \\<noteq> 0\"\n    by auto\n  then have less: \"?x < (\\<Prod>i\\<in>A. m i)\"\n    by auto\n  have cong: \"ALL i:A. [?x = u i] (mod m i)\"\n    apply auto\n    apply (rule cong_trans_nat)\n    prefer 2\n    using one apply auto\n    apply (rule cong_dvd_modulus_nat)\n    apply (rule cong_mod_nat)\n    using prodnz apply auto\n    apply rule\n    apply (rule fin)\n    apply assumption\n    done\n  have unique: \"ALL z. z < (\\<Prod>i\\<in>A. m i) \\<and>\n      (ALL i:A. [z = u i] (mod m i)) \\<longrightarrow> z = ?x\"\n  proof (clarify)\n    fix z\n    assume zless: \"z < (\\<Prod>i\\<in>A. m i)\"\n    assume zcong: \"(ALL i:A. [z = u i] (mod m i))\"\n    have \"ALL i:A. [?x = z] (mod m i)\"\n      apply clarify\n      apply (rule cong_trans_nat)\n      using cong apply (erule bspec)\n      apply (rule cong_sym_nat)\n      using zcong apply auto\n      done\n    with fin cop have \"[?x = z] (mod (\\<Prod>i\\<in>A. m i))\"\n      apply (intro coprime_cong_prod_nat)\n      apply auto\n      done\n    with zless less show \"z = ?x\"\n      apply (intro cong_less_modulus_unique_nat)\n      apply (auto, erule cong_sym_nat)\n      done\n  qed\n  from less cong unique show ?thesis by blast\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Number_Theory/Cong.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.7856976813163501}}
{"text": "theory \"merge-sort\"\n  imports Main \"HOL-Library.Multiset\"\nbegin\n\ndeclare[[names_short]]\n\ntext \\<open>tail recursive\\<close>\n\nfunction merge:: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where \n\"merge xs [] = xs\" |\n\"merge [] ys = ys\" |\n\"merge  (x#xs) (y#ys) = (if x \\<le> y then x#merge xs (y#ys) else y#merge (x#xs) ys)\"\nby pat_completeness auto\ntermination\nproof (relation \"measure (\\<lambda>(xs,ys). length xs + length ys)\")\n  show \"wf (measure (\\<lambda>(xs, ys). length xs + length ys))\" by simp\nnext\n  fix xs ys::\"nat list\"\n  fix x y :: nat\n  assume a1: \"x \\<le> y\"\n  show \"((xs, y#ys), x#xs, y#ys) \\<in> measure (\\<lambda>(xs, ys). length xs + length ys)\" \n  proof (simp only: in_measure)\n    show \"(case (xs, y#ys) of (xs, ys) \\<Rightarrow> length xs + length ys) < (case (x#xs, y#ys) of (xs, ys) \\<Rightarrow> length xs + length ys)\"\n    proof(simp only: prod.case)\n      show \"length xs + length (y#ys) < length (x#xs) + length (y#ys)\" by simp\n    qed\n  qed\nnext\n  fix xs ys::\"nat list\"\n  fix x y :: nat\n  assume a2: \"\\<not> x \\<le> y \"\n  show \"((x#xs, ys), x#xs, y#ys) \\<in> measure (\\<lambda>(xs, ys). length xs + length ys)\"\n  proof (simp only: in_measure)\n    show \"(case (x# xs, ys) of (xs, ys) \\<Rightarrow> length xs + length ys) < (case (x#xs, y#ys) of (xs, ys) \\<Rightarrow> length xs + length ys)\" \n    proof(simp only: prod.case)\n      show \"length (x#xs) + length ys < length (x#xs) + length (y#ys)\" by simp\n    qed\n  qed\nqed\n\nvalue \"merge ([1,2,3]) ([1,2,3,10])\"\n\nlemma sorted4 :\"\\<lbrakk>sorted (y#ys);sorted (x#xs);sorted (merge (xs) (y#ys)); x \\<le> y\\<rbrakk> \\<Longrightarrow> sorted(x#merge (xs) (y#ys))\"\nproof(induction xs rule: sorted.induct)\n  case 1\n  then show ?case by auto\nnext\n  case (2 x ys)\n  then show ?case by (metis merge.simps(3) sorted2)\nqed\n\nlemma sorted5 :\"\\<lbrakk>sorted (y#ys);sorted (x#xs);sorted (merge (x#xs) (ys)); y \\<le> x\\<rbrakk> \\<Longrightarrow> sorted (y#merge (x#xs) (ys))\"\nproof(induction ys  rule: sorted.induct)\n  case 1\n  then show ?case  by auto\nnext\n  case (2 x ys)\n  then show ?case by (metis merge.simps(3) sorted2)\nqed\n\nlemma merge_order: \"\\<lbrakk>sorted (xs);sorted(ys)\\<rbrakk> \\<Longrightarrow> sorted(merge xs ys)\"\nproof(induct xs ys rule: merge.induct)\n  case (1 xs)\n  then show \"sorted (merge xs [])\" by simp\nnext\n  case (2 ys)\n  then show \"sorted (merge [] ys)\" by simp\nnext\n  case (3 x xs y ys)\n  then show \"sorted (merge (x # xs) (y # ys))\"\n  proof(cases \"x \\<le> y\")\n    case True\n    then show \"sorted (merge (x # xs) (y # ys))\"  \n    proof (simp only: merge.simps True if_True)\n      have \"sorted (merge xs (y # ys))\" using \"3.hyps\"(1) \"3.prems\"(1) \"3.prems\"(2) True sorted.simps(2) by simp\n      then show \"sorted (x # merge xs (y # ys))\"  by (simp only: \"3.prems\"(1) \"3.prems\"(2) True sorted4)\n    qed\n  next\n    case False\n    then show \"sorted (merge (x # xs) (y # ys))\"\n    proof (simp only: merge.simps False if_False)\n      have \"sorted(merge (x # xs) ys)\" using \"3.hyps\"(2) \"3.prems\"(1) \"3.prems\"(2) False sorted.simps(2) by simp\n      moreover have \"y \\<le> x\" using False nat_le_linear by simp\n      ultimately show \"sorted (y # merge (x # xs) ys)\" by (simp only: \"3.prems\"(1) \"3.prems\"(2) False sorted5)\n    qed\n  qed\nqed\n\nlemma merge_permutation: \"mset (merge xs ys) = mset xs + mset ys\"\nproof(induct xs ys rule: merge.induct)\n  case (1 ys)\n  have \"mset (merge ys []) = mset (ys)\" by simp\n  also have \"... =  mset ys + mset []\" by simp\n  finally show \"mset (merge ys []) = mset ys + mset []\" by this\nnext\n  case (2 xs)  \n  have \"mset (merge [] xs) = mset (xs)\" by simp\n  also have \"... =  mset xs + mset []\" by simp\n  then show \"mset (merge [] xs) = mset [] + mset xs\" by simp\nnext\n  case (3 x xs y ys)\n  then show ?case\n  proof(cases \"x \\<le> y\")\n    case True\n    have \"mset (merge (x # xs) (y # ys)) = mset (x#merge xs (y # ys))\" using True by simp \n    also have \"... =  {#x#} +  mset (merge xs (y # ys))\" by simp\n    also have \"... =  {#x#} +  mset xs + mset (y # ys)\" using \"3.hyps\"(1) True  by (simp)\n    also have \"... =   mset (x # xs) + mset (y # ys)\" by (simp add: \"3.hyps\"(1) True)\n    finally show \"mset (merge (x # xs) (y # ys)) = mset (x # xs) + mset (y # ys)\" by this\n  next\n    case False\n    have \"mset (merge (x # xs) (y # ys)) = mset (y#merge (x#xs) ys)\" using False by simp \n    also have \"... =  {#y#} +  mset(merge (x#xs) ys)\" by simp\n    also have \"... =  {#y#} +  mset (x # xs) + mset ys\" by (simp add: \"3.hyps\"(2) False)\n    also have \"... =  mset (x # xs) + mset (y # ys)\" by simp\n    finally show \"mset (merge (x # xs) (y # ys)) = mset (x # xs) + mset (y # ys)\" by this\n  qed\nqed\n\nvalue \"merge [1,2,3] [1,4,5,6]\"\n\nfun merge_sort:: \"nat list \\<Rightarrow> nat list\" where\n\"merge_sort [] = []\" |\n\"merge_sort [x] = [x]\" |\n\"merge_sort (x#xs) = ( let  half = ((length (x#xs)) div 2); left = take half (x#xs); right = drop half (x#xs) in  merge (merge_sort (left)) (merge_sort (right)))\"\n\nvalue \"msort [9,8,7,6,5,4]\"\n\ntheorem merge_sort_order: \"sorted(merge_sort xs)\"\nproof(induct xs rule:merge_sort.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 x)\n  then show ?case by simp\nnext\n  case (3 v vb vc)\n  thm  \"3.hyps\"\n  let ?half = \"length (v # vb # vc) div 2\"\n  let ?left = \"take ?half (v # vb # vc)\"\n  let ?right = \"drop ?half (v # vb # vc)\"\n  show \"sorted (merge_sort (v # vb # vc))\" \n  proof (simp only: merge_sort.simps Let_def)\n    have \"sorted ((merge_sort (?left)))\" using \"3.hyps\"(1) by simp\n    moreover have \"sorted ((merge_sort (?right)))\" using \"3.hyps\"(2) by simp\n    ultimately show \"sorted (merge (merge_sort (?left)) (merge_sort (?right)))\" by (simp only:merge_order)\n  qed\nqed\n\ntheorem merge_sort_permutation: \"mset (merge_sort xs) = mset xs\"\nproof(induct xs rule:merge_sort.induct)\n  case 1\n  then show \"mset (merge_sort []) = mset []\" by simp\nnext\n  case (2 x)\n  then show \"mset (merge_sort [x]) = mset [x]\" by simp\nnext\n  case (3 v vb vc)\n  let ?half = \"length (v # vb # vc) div 2\"\n  let ?left = \"take ?half (v # vb # vc)\"\n  let ?right = \"drop ?half (v # vb # vc)\"\n  have \"mset (merge_sort (v # vb # vc)) = mset(merge (merge_sort ?left) (merge_sort ?right))\" by simp\n  also have \"... = mset(merge_sort ?left) + mset(merge_sort ?right)\" using merge_permutation by simp\n  also have \"... = mset(?left) + mset(?right)\"  by (simp add: \"3.hyps\"(1) \"3.hyps\"(2))\n  also have \"... = mset (v # vb # vc)\"  by (metis append_take_drop_id mset_append)\n  finally show \"mset (merge_sort (v # vb # vc)) = mset (v # vb # vc)\" by this\nqed\n", "meta": {"author": "marco10507", "repo": "formalization-of-sorting-algorithms", "sha": "de905424e53d55829d54c2cd3c8f5241ac5ca904", "save_path": "github-repos/isabelle/marco10507-formalization-of-sorting-algorithms", "path": "github-repos/isabelle/marco10507-formalization-of-sorting-algorithms/formalization-of-sorting-algorithms-de905424e53d55829d54c2cd3c8f5241ac5ca904/merge-sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.8887587831798666, "lm_q1q2_score": 0.7856976681819328}}
{"text": "theory Boolean_Expression_Example\n  imports Boolean_Expression_Checkers Boolean_Expression_Checkers_AList_Mapping\nbegin\n\nsection \\<open>Example\\<close>\n\ntext \\<open>Example usage of checkers. We have our own type of Boolean expressions with its own evaluation function:\\<close>\n\ndatatype 'a bexp =\n  Const bool |\n  Atom 'a |\n  Neg \"'a bexp\" |\n  And \"'a bexp\" \"'a bexp\"\n\nfun bval where\n\"bval (Const b) s = b\" |\n\"bval (Atom a) s = s a\" |\n\"bval (Neg b) s = (\\<not> bval b s)\" |\n\"bval (And b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\n\nsubsection \\<open>Indirect Translation using the Boolean Expression Interface\\<close> \n\ntext \\<open>Now we translate into @{datatype bool_expr} provided by the checkers interface and show that the \n  semantics remains the same:\\<close>\n\nfun bool_expr_of_bexp :: \"'a bexp \\<Rightarrow> 'a bool_expr\" \nwhere\n  \"bool_expr_of_bexp (Const b) = Const_bool_expr b\" \n| \"bool_expr_of_bexp (Atom a) = Atom_bool_expr a\" \n| \"bool_expr_of_bexp (Neg b) = Neg_bool_expr(bool_expr_of_bexp b)\" \n| \"bool_expr_of_bexp (And b1 b2) = And_bool_expr (bool_expr_of_bexp b1) (bool_expr_of_bexp b2)\"\n\nlemma val_preservation: \n  \"val_bool_expr (bool_expr_of_bexp b) s = bval b s\"\n  by (induction b) auto \n\ndefinition \"my_taut_test_bool = bool_taut_test o bool_expr_of_bexp\"\n\ncorollary my_taut_test: \n  \"my_taut_test_bool b = (\\<forall>s. bval b s)\"\n  by (simp add: my_taut_test_bool_def val_preservation bool_tests)\n\nsubsection \\<open>Direct Translation into Reduced Binary Decision Trees\\<close> \n\ntext \\<open>Now we translate into a reduced binary decision tree, show that the semantics remains the same and \n  the tree is reduced:\\<close>\n\nfun ifex_of :: \"'a bexp \\<Rightarrow> 'a ifex\" \nwhere\n  \"ifex_of (Const b) = (if b then Trueif else Falseif)\" \n| \"ifex_of (Atom a) = IF a Trueif Falseif\" \n| \"ifex_of (Neg b)   = normif Mapping.empty (ifex_of b) Falseif Trueif\" \n| \"ifex_of (And b1 b2) = normif Mapping.empty (ifex_of b1) (ifex_of b2) Falseif\"\n\nlemma val_ifex: \n  \"val_ifex (ifex_of b) s = bval b s\"\n  by (induction b) (simp_all add: agree_Nil val_normif)\n\ntheorem reduced_ifex: \n  \"reduced (ifex_of b) {}\"\n  by (induction b) (simp; metis keys_empty reduced_normif)+\n\ndefinition \"my_taut_test_ifex = taut_test ifex_of\"\n\ncorollary my_taut_test_ifex: \n  \"my_taut_test_ifex b = (\\<forall>s. bval b s)\"\nproof -\n  interpret reduced_bdt_checkers ifex_of bval\n    by (unfold_locales; insert val_ifex reduced_ifex; blast)\n  show ?thesis\n    by (simp add: my_taut_test_ifex_def taut_test)\nqed\n\nsubsection \\<open>Test: Pigeonhole Formulas\\<close>\n\ndefinition \"Or b1 b2 == Neg (And (Neg b1) (Neg b2))\"\ndefinition \"ors = foldl Or (Const False)\"\ndefinition \"ands = foldl And (Const True)\"\n\ndefinition \"pc n = ands[ors[Atom(i,j). j <- [1..<n+1]]. i <- [1..<n+2]]\"\ndefinition \"nc n = ands[Or (Neg(Atom(i,k))) (Neg(Atom(j,k))). k <- [1..<n+1], i <- [1..<n+1], j <- [i+1..<n+2]]\"\n\ndefinition \"php n = Neg(And (pc n) (nc n))\"\n\ntext \\<open>Takes about 5 secs each; with 7 instead of 6 it takes about 4 mins (2015).\\<close>\n\nlemma \"my_taut_test_bool (php 6)\"\n  by eval\n\nlemma \"my_taut_test_ifex (php 6)\"\n  by eval \n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Boolean_Expression_Checkers/Boolean_Expression_Example.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.785606072181355}}
{"text": "(*  Title:      HOL/Library/Lub_Glb.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge\n    Author:     Amine Chaieb, University of Cambridge *)\n\nsection {* Definitions of Least Upper Bounds and Greatest Lower Bounds *}\n\ntheory Lub_Glb\nimports Complex_Main\nbegin\n\ntext {* Thanks to suggestions by James Margetson *}\n\ndefinition setle :: \"'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"  (infixl \"*<=\" 70)\n  where \"S *<= x = (ALL y: S. y \\<le> x)\"\n\ndefinition setge :: \"'a::ord \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infixl \"<=*\" 70)\n  where \"x <=* S = (ALL y: S. x \\<le> y)\"\n\n\nsubsection {* Rules for the Relations @{text \"*<=\"} and @{text \"<=*\"} *}\n\nlemma setleI: \"ALL y: S. y \\<le> x \\<Longrightarrow> S *<= x\"\n  by (simp add: setle_def)\n\nlemma setleD: \"S *<= x \\<Longrightarrow> y: S \\<Longrightarrow> y \\<le> x\"\n  by (simp add: setle_def)\n\nlemma setgeI: \"ALL y: S. x \\<le> y \\<Longrightarrow> x <=* S\"\n  by (simp add: setge_def)\n\nlemma setgeD: \"x <=* S \\<Longrightarrow> y: S \\<Longrightarrow> x \\<le> y\"\n  by (simp add: setge_def)\n\n\ndefinition leastP :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"leastP P x = (P x \\<and> x <=* Collect P)\"\n\ndefinition isUb :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isUb R S x = (S *<= x \\<and> x: R)\"\n\ndefinition isLub :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isLub R S x = leastP (isUb R S) x\"\n\ndefinition ubs :: \"'a set \\<Rightarrow> 'a::ord set \\<Rightarrow> 'a set\"\n  where \"ubs R S = Collect (isUb R S)\"\n\n\nsubsection {* Rules about the Operators @{term leastP}, @{term ub} and @{term lub} *}\n\nlemma leastPD1: \"leastP P x \\<Longrightarrow> P x\"\n  by (simp add: leastP_def)\n\nlemma leastPD2: \"leastP P x \\<Longrightarrow> x <=* Collect P\"\n  by (simp add: leastP_def)\n\nlemma leastPD3: \"leastP P x \\<Longrightarrow> y: Collect P \\<Longrightarrow> x \\<le> y\"\n  by (blast dest!: leastPD2 setgeD)\n\nlemma isLubD1: \"isLub R S x \\<Longrightarrow> S *<= x\"\n  by (simp add: isLub_def isUb_def leastP_def)\n\nlemma isLubD1a: \"isLub R S x \\<Longrightarrow> x: R\"\n  by (simp add: isLub_def isUb_def leastP_def)\n\nlemma isLub_isUb: \"isLub R S x \\<Longrightarrow> isUb R S x\"\n  unfolding isUb_def by (blast dest: isLubD1 isLubD1a)\n\nlemma isLubD2: \"isLub R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<le> x\"\n  by (blast dest!: isLubD1 setleD)\n\nlemma isLubD3: \"isLub R S x \\<Longrightarrow> leastP (isUb R S) x\"\n  by (simp add: isLub_def)\n\nlemma isLubI1: \"leastP(isUb R S) x \\<Longrightarrow> isLub R S x\"\n  by (simp add: isLub_def)\n\nlemma isLubI2: \"isUb R S x \\<Longrightarrow> x <=* Collect (isUb R S) \\<Longrightarrow> isLub R S x\"\n  by (simp add: isLub_def leastP_def)\n\nlemma isUbD: \"isUb R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<le> x\"\n  by (simp add: isUb_def setle_def)\n\nlemma isUbD2: \"isUb R S x \\<Longrightarrow> S *<= x\"\n  by (simp add: isUb_def)\n\nlemma isUbD2a: \"isUb R S x \\<Longrightarrow> x: R\"\n  by (simp add: isUb_def)\n\nlemma isUbI: \"S *<= x \\<Longrightarrow> x: R \\<Longrightarrow> isUb R S x\"\n  by (simp add: isUb_def)\n\nlemma isLub_le_isUb: \"isLub R S x \\<Longrightarrow> isUb R S y \\<Longrightarrow> x \\<le> y\"\n  unfolding isLub_def by (blast intro!: leastPD3)\n\nlemma isLub_ubs: \"isLub R S x \\<Longrightarrow> x <=* ubs R S\"\n  unfolding ubs_def isLub_def by (rule leastPD2)\n\nlemma isLub_unique: \"[| isLub R S x; isLub R S y |] ==> x = (y::'a::linorder)\"\n  apply (frule isLub_isUb)\n  apply (frule_tac x = y in isLub_isUb)\n  apply (blast intro!: order_antisym dest!: isLub_le_isUb)\n  done\n\nlemma isUb_UNIV_I: \"(\\<And>y. y \\<in> S \\<Longrightarrow> y \\<le> u) \\<Longrightarrow> isUb UNIV S u\"\n  by (simp add: isUbI setleI)\n\n\ndefinition greatestP :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"greatestP P x = (P x \\<and> Collect P *<=  x)\"\n\ndefinition isLb :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isLb R S x = (x <=* S \\<and> x: R)\"\n\ndefinition isGlb :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isGlb R S x = greatestP (isLb R S) x\"\n\ndefinition lbs :: \"'a set \\<Rightarrow> 'a::ord set \\<Rightarrow> 'a set\"\n  where \"lbs R S = Collect (isLb R S)\"\n\n\nsubsection {* Rules about the Operators @{term greatestP}, @{term isLb} and @{term isGlb} *}\n\nlemma greatestPD1: \"greatestP P x \\<Longrightarrow> P x\"\n  by (simp add: greatestP_def)\n\nlemma greatestPD2: \"greatestP P x \\<Longrightarrow> Collect P *<= x\"\n  by (simp add: greatestP_def)\n\nlemma greatestPD3: \"greatestP P x \\<Longrightarrow> y: Collect P \\<Longrightarrow> x \\<ge> y\"\n  by (blast dest!: greatestPD2 setleD)\n\nlemma isGlbD1: \"isGlb R S x \\<Longrightarrow> x <=* S\"\n  by (simp add: isGlb_def isLb_def greatestP_def)\n\nlemma isGlbD1a: \"isGlb R S x \\<Longrightarrow> x: R\"\n  by (simp add: isGlb_def isLb_def greatestP_def)\n\nlemma isGlb_isLb: \"isGlb R S x \\<Longrightarrow> isLb R S x\"\n  unfolding isLb_def by (blast dest: isGlbD1 isGlbD1a)\n\nlemma isGlbD2: \"isGlb R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<ge> x\"\n  by (blast dest!: isGlbD1 setgeD)\n\nlemma isGlbD3: \"isGlb R S x \\<Longrightarrow> greatestP (isLb R S) x\"\n  by (simp add: isGlb_def)\n\nlemma isGlbI1: \"greatestP (isLb R S) x \\<Longrightarrow> isGlb R S x\"\n  by (simp add: isGlb_def)\n\nlemma isGlbI2: \"isLb R S x \\<Longrightarrow> Collect (isLb R S) *<= x \\<Longrightarrow> isGlb R S x\"\n  by (simp add: isGlb_def greatestP_def)\n\nlemma isLbD: \"isLb R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<ge> x\"\n  by (simp add: isLb_def setge_def)\n\nlemma isLbD2: \"isLb R S x \\<Longrightarrow> x <=* S \"\n  by (simp add: isLb_def)\n\nlemma isLbD2a: \"isLb R S x \\<Longrightarrow> x: R\"\n  by (simp add: isLb_def)\n\nlemma isLbI: \"x <=* S \\<Longrightarrow> x: R \\<Longrightarrow> isLb R S x\"\n  by (simp add: isLb_def)\n\nlemma isGlb_le_isLb: \"isGlb R S x \\<Longrightarrow> isLb R S y \\<Longrightarrow> x \\<ge> y\"\n  unfolding isGlb_def by (blast intro!: greatestPD3)\n\nlemma isGlb_ubs: \"isGlb R S x \\<Longrightarrow> lbs R S *<= x\"\n  unfolding lbs_def isGlb_def by (rule greatestPD2)\n\nlemma isGlb_unique: \"[| isGlb R S x; isGlb R S y |] ==> x = (y::'a::linorder)\"\n  apply (frule isGlb_isLb)\n  apply (frule_tac x = y in isGlb_isLb)\n  apply (blast intro!: order_antisym dest!: isGlb_le_isLb)\n  done\n\nlemma bdd_above_setle: \"bdd_above A \\<longleftrightarrow> (\\<exists>a. A *<= a)\"\n  by (auto simp: bdd_above_def setle_def)\n\nlemma bdd_below_setge: \"bdd_below A \\<longleftrightarrow> (\\<exists>a. a <=* A)\"\n  by (auto simp: bdd_below_def setge_def)\n\nlemma isLub_cSup: \n  \"(S::'a :: conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> (\\<exists>b. S *<= b) \\<Longrightarrow> isLub UNIV S (Sup S)\"\n  by  (auto simp add: isLub_def setle_def leastP_def isUb_def\n            intro!: setgeI cSup_upper cSup_least)\n\nlemma isGlb_cInf: \n  \"(S::'a :: conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> (\\<exists>b. b <=* S) \\<Longrightarrow> isGlb UNIV S (Inf S)\"\n  by  (auto simp add: isGlb_def setge_def greatestP_def isLb_def\n            intro!: setleI cInf_lower cInf_greatest)\n\nlemma cSup_le: \"(S::'a::conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> S *<= b \\<Longrightarrow> Sup S \\<le> b\"\n  by (metis cSup_least setle_def)\n\nlemma cInf_ge: \"(S::'a :: conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> b <=* S \\<Longrightarrow> Inf S \\<ge> b\"\n  by (metis cInf_greatest setge_def)\n\nlemma cSup_bounds:\n  fixes S :: \"'a :: conditionally_complete_lattice set\"\n  shows \"S \\<noteq> {} \\<Longrightarrow> a <=* S \\<Longrightarrow> S *<= b \\<Longrightarrow> a \\<le> Sup S \\<and> Sup S \\<le> b\"\n  using cSup_least[of S b] cSup_upper2[of _ S a]\n  by (auto simp: bdd_above_setle setge_def setle_def)\n\nlemma cSup_unique: \"(S::'a :: {conditionally_complete_linorder, no_bot} set) *<= b \\<Longrightarrow> (\\<forall>b'<b. \\<exists>x\\<in>S. b' < x) \\<Longrightarrow> Sup S = b\"\n  by (rule cSup_eq) (auto simp: not_le[symmetric] setle_def)\n\nlemma cInf_unique: \"b <=* (S::'a :: {conditionally_complete_linorder, no_top} set) \\<Longrightarrow> (\\<forall>b'>b. \\<exists>x\\<in>S. b' > x) \\<Longrightarrow> Inf S = b\"\n  by (rule cInf_eq) (auto simp: not_le[symmetric] setge_def)\n\ntext{* Use completeness of reals (supremum property) to show that any bounded sequence has a least upper bound*}\n\nlemma reals_complete: \"\\<exists>X. X \\<in> S \\<Longrightarrow> \\<exists>Y. isUb (UNIV::real set) S Y \\<Longrightarrow> \\<exists>t. isLub (UNIV :: real set) S t\"\n  by (intro exI[of _ \"Sup S\"] isLub_cSup) (auto simp: setle_def isUb_def intro!: cSup_upper)\n\nlemma Bseq_isUb: \"\\<And>X :: nat \\<Rightarrow> real. Bseq X \\<Longrightarrow> \\<exists>U. isUb (UNIV::real set) {x. \\<exists>n. X n = x} U\"\n  by (auto intro: isUbI setleI simp add: Bseq_def abs_le_iff)\n\nlemma Bseq_isLub: \"\\<And>X :: nat \\<Rightarrow> real. Bseq X \\<Longrightarrow> \\<exists>U. isLub (UNIV::real set) {x. \\<exists>n. X n = x} U\"\n  by (blast intro: reals_complete Bseq_isUb)\n\nlemma isLub_mono_imp_LIMSEQ:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes u: \"isLub UNIV {x. \\<exists>n. X n = x} u\" (* FIXME: use 'range X' *)\n  assumes X: \"\\<forall>m n. m \\<le> n \\<longrightarrow> X m \\<le> X n\"\n  shows \"X ----> u\"\nproof -\n  have \"X ----> (SUP i. X i)\"\n    using u[THEN isLubD1] X\n    by (intro LIMSEQ_incseq_SUP) (auto simp: incseq_def image_def eq_commute bdd_above_setle)\n  also have \"(SUP i. X i) = u\"\n    using isLub_cSup[of \"range X\"] u[THEN isLubD1]\n    by (intro isLub_unique[OF _ u]) (auto simp add: SUP_def image_def eq_commute)\n  finally show ?thesis .\nqed\n\nlemmas real_isGlb_unique = isGlb_unique[where 'a=real]\n\nlemma real_le_inf_subset: \"t \\<noteq> {} \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> \\<exists>b. b <=* s \\<Longrightarrow> Inf s \\<le> Inf (t::real set)\"\n  by (rule cInf_superset_mono) (auto simp: bdd_below_setge)\n\nlemma real_ge_sup_subset: \"t \\<noteq> {} \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> \\<exists>b. s *<= b \\<Longrightarrow> Sup s \\<ge> Sup (t::real set)\"\n  by (rule cSup_subset_mono) (auto simp: bdd_above_setle)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Lub_Glb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473779969194, "lm_q2_score": 0.900529778109184, "lm_q1q2_score": 0.7855747907416943}}
{"text": "\nsection \"Arithmetic and Boolean Expressions\"\n\nsubsection \"Arithmetic Expressions\"\n\ntheory ModifiedAexpForEx4\n  imports Main\nbegin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw\\<open>\\snip{AExpaexpdef}{2}{1}{%\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\ntext_raw\\<open>\\snip{AExpavaldef}{1}{2}{%\\<close>\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\" |\n\"aval (Times a1 a2) s = aval a1 s * aval a2 s\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>\\noindent\n  We can now write a series of updates to the function \\<open>\\<lambda>x. 0\\<close> compactly:\n\\<close>\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext\\<open>Note that this \\<open><\\<dots>>\\<close> syntax works for any function space\n\\<open>\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\\<close> where \\<open>\\<tau>\\<^sub>2\\<close> has a \\<open>0\\<close>.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Evaluate constant subsexpressions:\\<close>\n\ntext_raw\\<open>\\snip{AExpasimpconstdef}{0}{2}{%\\<close>\n(* fun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone *)\n\ntext\\<open>Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors:\\<close>\n\ntext_raw\\<open>\\snip{AExpplusdef}{0}{2}{%\\<close>\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\nfun times :: \"aexp => aexp => aexp\" where\n\"times (N i) (N j) = N (i * j)\" |\n\"times (N i) a = (if i=1 then a else Times (N i) a)\" |\n\"times a (N i) = (if i=1 then a else Times a (N i))\" |\n\"times a b = Times a b\"\n\nlemma aval_times[simp]:\n  \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw\\<open>\\snip{AExpasimpdef}{2}{0}{%\\<close>\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\" |\n\"asimp (Times a1 a2) = times (asimp a1) (asimp a2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\nend", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/ConcreteSemanticsChapter3/ex3_1/ModifiedAexpForEx4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8723473697001441, "lm_q1q2_score": 0.7855747879277852}}
{"text": "(*  Title:      HOL/Computational_Algebra/Fundamental_Theorem_Algebra.thy\n    Author:     Amine Chaieb, TU Muenchen\n*)\n\nsection \\<open>Fundamental Theorem of Algebra\\<close>\n\ntheory Fundamental_Theorem_Algebra\nimports Polynomial Complex_Main\nbegin\n\nsubsection \\<open>More lemmas about module of complex numbers\\<close>\n\ntext \\<open>The triangle inequality for cmod\\<close>\n\nlemma complex_mod_triangle_sub: \"cmod w \\<le> cmod (w + z) + norm z\"\n  by (metis add_diff_cancel norm_triangle_ineq4)\n\n\nsubsection \\<open>Basic lemmas about polynomials\\<close>\n\nlemma poly_bound_exists:\n  fixes p :: \"'a::{comm_semiring_0,real_normed_div_algebra} poly\"\n  shows \"\\<exists>m. m > 0 \\<and> (\\<forall>z. norm z \\<le> r \\<longrightarrow> norm (poly p z) \\<le> m)\"\nproof (induct p)\n  case 0\n  then show ?case by (rule exI[where x=1]) simp\nnext\n  case (pCons c cs)\n  from pCons.hyps obtain m where m: \"\\<forall>z. norm z \\<le> r \\<longrightarrow> norm (poly cs z) \\<le> m\"\n    by blast\n  let ?k = \" 1 + norm c + \\<bar>r * m\\<bar>\"\n  have kp: \"?k > 0\"\n    using abs_ge_zero[of \"r*m\"] norm_ge_zero[of c] by arith\n  have \"norm (poly (pCons c cs) z) \\<le> ?k\" if H: \"norm z \\<le> r\" for z\n  proof -\n    from m H have th: \"norm (poly cs z) \\<le> m\"\n      by blast\n    from H have rp: \"r \\<ge> 0\"\n      using norm_ge_zero[of z] by arith\n    have \"norm (poly (pCons c cs) z) \\<le> norm c + norm (z * poly cs z)\"\n      using norm_triangle_ineq[of c \"z* poly cs z\"] by simp\n    also have \"\\<dots> \\<le> ?k\"\n      using mult_mono[OF H th rp norm_ge_zero[of \"poly cs z\"]]\n      by (simp add: norm_mult)\n    finally show ?thesis .\n  qed\n  with kp show ?case by blast\nqed\n\n\ntext \\<open>Offsetting the variable in a polynomial gives another of same degree\\<close>\n\ndefinition offset_poly :: \"'a::comm_semiring_0 poly \\<Rightarrow> 'a \\<Rightarrow> 'a poly\"\n  where \"offset_poly p h = fold_coeffs (\\<lambda>a q. smult h q + pCons a q) p 0\"\n\nlemma offset_poly_0: \"offset_poly 0 h = 0\"\n  by (simp add: offset_poly_def)\n\nlemma offset_poly_pCons:\n  \"offset_poly (pCons a p) h =\n    smult h (offset_poly p h) + pCons a (offset_poly p h)\"\n  by (cases \"p = 0 \\<and> a = 0\") (auto simp add: offset_poly_def)\n\nlemma offset_poly_single [simp]: \"offset_poly [:a:] h = [:a:]\"\n  by (simp add: offset_poly_pCons offset_poly_0)\n\nlemma poly_offset_poly: \"poly (offset_poly p h) x = poly p (h + x)\"\n  by (induct p) (auto simp add: offset_poly_0 offset_poly_pCons algebra_simps)\n\nlemma offset_poly_eq_0_lemma: \"smult c p + pCons a p = 0 \\<Longrightarrow> p = 0\"\n  by (induct p arbitrary: a) (simp, force)\n\nlemma offset_poly_eq_0_iff [simp]: \"offset_poly p h = 0 \\<longleftrightarrow> p = 0\"\nproof\n  show \"offset_poly p h = 0 \\<Longrightarrow> p = 0\"\n  proof(induction p)\n    case 0\n    then show ?case by blast\n  next\n    case (pCons a p)\n    then show ?case   \n      by (metis offset_poly_eq_0_lemma offset_poly_pCons offset_poly_single)\n  qed\nqed (simp add: offset_poly_0)\n\nlemma degree_offset_poly [simp]: \"degree (offset_poly p h) = degree p\"\nproof(induction p)\n  case 0\n  then show ?case\n    by (simp add: offset_poly_0)\nnext\n  case (pCons a p)\n  have \"p \\<noteq> 0 \\<Longrightarrow> degree (offset_poly (pCons a p) h) = Suc (degree p)\"\n    by (metis degree_add_eq_right degree_pCons_eq degree_smult_le le_imp_less_Suc offset_poly_eq_0_iff offset_poly_pCons pCons.IH)\n  then show ?case\n    by simp\nqed\n\ndefinition \"psize p = (if p = 0 then 0 else Suc (degree p))\"\n\nlemma psize_eq_0_iff [simp]: \"psize p = 0 \\<longleftrightarrow> p = 0\"\n  unfolding psize_def by simp\n\nlemma poly_offset:\n  fixes p :: \"'a::comm_ring_1 poly\"\n  shows \"\\<exists>q. psize q = psize p \\<and> (\\<forall>x. poly q x = poly p (a + x))\"\n  by (metis degree_offset_poly offset_poly_eq_0_iff poly_offset_poly psize_def)\n\ntext \\<open>An alternative useful formulation of completeness of the reals\\<close>\nlemma real_sup_exists:\n  assumes ex: \"\\<exists>x. P x\"\n    and bz: \"\\<exists>z. \\<forall>x. P x \\<longrightarrow> x < z\"\n  shows \"\\<exists>s::real. \\<forall>y. (\\<exists>x. P x \\<and> y < x) \\<longleftrightarrow> y < s\"\nproof\n  from bz have \"bdd_above (Collect P)\"\n    by (force intro: less_imp_le)\n  then show \"\\<forall>y. (\\<exists>x. P x \\<and> y < x) \\<longleftrightarrow> y < Sup (Collect P)\"\n    using ex bz by (subst less_cSup_iff) auto\nqed\n\n\nsubsection \\<open>Fundamental theorem of algebra\\<close>\n\nlemma unimodular_reduce_norm:\n  assumes md: \"cmod z = 1\"\n  shows \"cmod (z + 1) < 1 \\<or> cmod (z - 1) < 1 \\<or> cmod (z + \\<i>) < 1 \\<or> cmod (z - \\<i>) < 1\"\nproof -\n  obtain x y where z: \"z = Complex x y \"\n    by (cases z) auto\n  from md z have xy: \"x\\<^sup>2 + y\\<^sup>2 = 1\"\n    by (simp add: cmod_def)\n  have False if \"cmod (z + 1) \\<ge> 1\" \"cmod (z - 1) \\<ge> 1\" \"cmod (z + \\<i>) \\<ge> 1\" \"cmod (z - \\<i>) \\<ge> 1\"\n  proof -\n    from that z xy have *: \"2 * x \\<le> 1\" \"2 * x \\<ge> -1\" \"2 * y \\<le> 1\" \"2 * y \\<ge> -1\"\n      by (simp_all add: cmod_def power2_eq_square algebra_simps)\n    then have \"\\<bar>2 * x\\<bar> \\<le> 1\" \"\\<bar>2 * y\\<bar> \\<le> 1\"\n      by simp_all\n    then have \"\\<bar>2 * x\\<bar>\\<^sup>2 \\<le> 1\\<^sup>2\" \"\\<bar>2 * y\\<bar>\\<^sup>2 \\<le> 1\\<^sup>2\"\n      by (metis abs_square_le_1 one_power2 power2_abs)+\n    with xy * show ?thesis\n      by (smt (verit, best) four_x_squared square_le_1)\n  qed\n  then show ?thesis\n    by force\nqed\n\ntext \\<open>Hence we can always reduce modulus of \\<open>1 + b z^n\\<close> if nonzero\\<close>\nlemma reduce_poly_simple:\n  assumes b: \"b \\<noteq> 0\"\n    and n: \"n \\<noteq> 0\"\n  shows \"\\<exists>z. cmod (1 + b * z^n) < 1\"\n  using n\nproof (induct n rule: nat_less_induct)\n  fix n\n  assume IH: \"\\<forall>m<n. m \\<noteq> 0 \\<longrightarrow> (\\<exists>z. cmod (1 + b * z ^ m) < 1)\"\n  assume n: \"n \\<noteq> 0\"\n  let ?P = \"\\<lambda>z n. cmod (1 + b * z ^ n) < 1\"\n  show \"\\<exists>z. ?P z n\"\n  proof cases\n    assume \"even n\" \n    then obtain m where m: \"n = 2 * m\" and \"m \\<noteq> 0\" \"m < n\"\n      using n by auto\n    with IH obtain z where z: \"?P z m\"\n      by blast\n    from z have \"?P (csqrt z) n\"\n      by (simp add: m power_mult)\n    then show ?thesis ..\n  next\n    assume \"odd n\"\n    then have \"\\<exists>m. n = Suc (2 * m)\"\n      by presburger+\n    then obtain m where m: \"n = Suc (2 * m)\"\n      by blast\n    have 0: \"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    have \"\\<exists>v. cmod (complex_of_real (cmod b) / b + v^n) < 1\"\n    proof (cases \"cmod (complex_of_real (cmod b) / b + 1) < 1\")\n      case True\n      then show ?thesis\n        by (metis power_one)\n    next\n      case F1: False\n      show ?thesis\n      proof (cases \"cmod (complex_of_real (cmod b) / b - 1) < 1\")\n        case True\n        with \\<open>odd n\\<close> show ?thesis\n          by (metis add_uminus_conv_diff neg_one_odd_power)\n      next\n        case F2: False\n        show ?thesis\n        proof (cases \"cmod (complex_of_real (cmod b) / b + \\<i>) < 1\")\n          case T1: True\n          show ?thesis\n          proof (cases \"even m\")\n            case True\n            with T1 show ?thesis\n              by (rule_tac x=\"\\<i>\" in exI) (simp add: m power_mult)\n          next\n            case False\n            with T1 show ?thesis \n              by (rule_tac x=\"- \\<i>\" in exI) (simp add: m power_mult)\n          qed\n        next\n          case False\n          then have lt1: \"cmod (of_real (cmod b) / b - \\<i>) < 1\"\n            using \"0\" F1 F2 unimodular_reduce_norm by blast\n          show ?thesis\n          proof (cases \"even m\")\n            case True\n            with m lt1 show ?thesis \n              by (rule_tac x=\"- \\<i>\" in exI) (simp add: power_mult)\n          next\n            case False\n            with m lt1 show ?thesis \n              by (rule_tac x=\"\\<i>\" in exI) (simp add: power_mult)\n          qed\n        qed\n      qed\n    qed\n    then obtain v where v: \"cmod (complex_of_real (cmod b) / b + v^n) < 1\"\n      by blast\n    let ?w = \"v / complex_of_real (root n (cmod b))\"\n    from odd_real_root_pow[OF \\<open>odd n\\<close>, of \"cmod b\"]\n    have 1: \"?w ^ n = v^n / complex_of_real (cmod b)\"\n      by (simp add: power_divide of_real_power[symmetric])\n    have 2:\"cmod (complex_of_real (cmod b) / b) = 1\"\n      using b by (simp add: norm_divide)\n    then have 3: \"cmod (complex_of_real (cmod b) / b) \\<ge> 0\"\n      by simp\n    have 4: \"cmod (complex_of_real (cmod b) / b) *\n        cmod (1 + b * (v ^ n / complex_of_real (cmod b))) <\n        cmod (complex_of_real (cmod b) / b) * 1\"\n      apply (simp only: norm_mult[symmetric] distrib_left)\n      using b v\n      apply (simp add: 2)\n      done\n    show ?thesis\n      by (metis 1 mult_left_less_imp_less[OF 4 3])\n  qed\nqed\n\ntext \\<open>Bolzano-Weierstrass type property for closed disc in complex plane.\\<close>\n\nlemma metric_bound_lemma: \"cmod (x - y) \\<le> \\<bar>Re x - Re y\\<bar> + \\<bar>Im x - Im y\\<bar>\"\n  using real_sqrt_sum_squares_triangle_ineq[of \"Re x - Re y\" 0 0 \"Im x - Im y\"]\n  unfolding cmod_def by simp\n\nlemma Bolzano_Weierstrass_complex_disc:\n  assumes r: \"\\<forall>n. cmod (s n) \\<le> r\"\n  shows \"\\<exists>f z. strict_mono (f :: nat \\<Rightarrow> nat) \\<and> (\\<forall>e >0. \\<exists>N. \\<forall>n \\<ge> N. cmod (s (f n) - z) < e)\"\nproof -\n  from seq_monosub[of \"Re \\<circ> s\"]\n  obtain f where f: \"strict_mono f\" \"monoseq (\\<lambda>n. Re (s (f n)))\"\n    unfolding o_def by blast\n  from seq_monosub[of \"Im \\<circ> s \\<circ> f\"]\n  obtain g where g: \"strict_mono g\" \"monoseq (\\<lambda>n. Im (s (f (g n))))\"\n    unfolding o_def by blast\n  let ?h = \"f \\<circ> g\"\n  have \"r \\<ge> 0\"\n    by (meson norm_ge_zero order_trans r)\n  have \"\\<forall>n. r + 1 \\<ge> \\<bar>Re (s n)\\<bar>\"\n    by (smt (verit, ccfv_threshold) abs_Re_le_cmod r)\n  then have conv1: \"convergent (\\<lambda>n. Re (s (f n)))\"\n    by (metis Bseq_monoseq_convergent f(2) BseqI' real_norm_def)\n  have \"\\<forall>n. r + 1 \\<ge> \\<bar>Im (s n)\\<bar>\"\n    by (smt (verit) abs_Im_le_cmod r)\n  then have conv2: \"convergent (\\<lambda>n. Im (s (f (g n))))\"\n    by (metis Bseq_monoseq_convergent g(2) BseqI' real_norm_def)\n\n  obtain x where  x: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Re (s (f n)) - x\\<bar> < r\"\n    using conv1[unfolded convergent_def] LIMSEQ_iff real_norm_def by metis \n  obtain y where  y: \"\\<forall>r>0. \\<exists>n0. \\<forall>n\\<ge>n0. \\<bar>Im (s (f (g n))) - y\\<bar> < r\"\n    using conv2[unfolded convergent_def] LIMSEQ_iff real_norm_def by metis\n  let ?w = \"Complex x y\"\n  from f(1) g(1) have hs: \"strict_mono ?h\"\n    unfolding strict_mono_def by auto\n  have \"\\<exists>N. \\<forall>n\\<ge>N. cmod (s (?h n) - ?w) < e\" if \"e > 0\" for e\n  proof -\n    from that have e2: \"e/2 > 0\"\n      by simp\n    from x y e2\n    obtain N1 N2 where N1: \"\\<forall>n\\<ge>N1. \\<bar>Re (s (f n)) - x\\<bar> < e / 2\"\n      and N2: \"\\<forall>n\\<ge>N2. \\<bar>Im (s (f (g n))) - y\\<bar> < e / 2\"\n      by blast\n    have \"cmod (s (?h n) - ?w) < e\" if \"n \\<ge> N1 + N2\" for n\n    proof -\n      from that have nN1: \"g n \\<ge> N1\" and nN2: \"n \\<ge> N2\"\n        using seq_suble[OF g(1), of n] by arith+\n      show ?thesis\n        using metric_bound_lemma[of \"s (f (g n))\" ?w] N1 N2 nN1 nN2 by fastforce\n    qed\n    then show ?thesis by blast\n  qed\n  with hs show ?thesis by blast\nqed\n\ntext \\<open>Polynomial is continuous.\\<close>\n\nlemma poly_cont:\n  fixes p :: \"'a::{comm_semiring_0,real_normed_div_algebra} poly\"\n  assumes ep: \"e > 0\"\n  shows \"\\<exists>d >0. \\<forall>w. 0 < norm (w - z) \\<and> norm (w - z) < d \\<longrightarrow> norm (poly p w - poly p z) < e\"\nproof -\n  obtain q where \"degree q = degree p\" and q: \"\\<And>w. poly p w = poly q (w - z)\"\n    by (metis add.commute degree_offset_poly diff_add_cancel poly_offset_poly)\n  show ?thesis unfolding q\n  proof (induct q)\n    case 0\n    then show ?case\n      using ep by auto\n  next\n    case (pCons c cs)\n    obtain m where m: \"m > 0\" \"norm z \\<le> 1 \\<Longrightarrow> norm (poly cs z) \\<le> m\" for z\n      using poly_bound_exists[of 1 \"cs\"] by blast\n    with ep have em0: \"e/m > 0\"\n      by (simp add: field_simps)\n    obtain d where d: \"d > 0\" \"d < 1\" \"d < e / m\"\n      by (meson em0 field_lbound_gt_zero zero_less_one)\n    then have \"\\<And>w. norm (w - z) < d \\<Longrightarrow> norm (w - z) * norm (poly cs (w - z)) < e\"\n      by (smt (verit, del_insts) m mult_left_mono norm_ge_zero pos_less_divide_eq)\n    with d show ?case\n      by (force simp add: norm_mult)\n  qed\nqed\n\ntext \\<open>Hence a polynomial attains minimum on a closed disc\n  in the complex plane.\\<close>\nlemma poly_minimum_modulus_disc: \"\\<exists>z. \\<forall>w. cmod w \\<le> r \\<longrightarrow> cmod (poly p z) \\<le> cmod (poly p w)\"\nproof -\n  show ?thesis\n  proof (cases \"r \\<ge> 0\")\n    case False\n    then show ?thesis\n      by (metis norm_ge_zero order.trans)\n  next\n    case True\n    then have mth1: \"\\<exists>x z. cmod z \\<le> r \\<and> cmod (poly p z) = - x\"\n      by (metis add.inverse_inverse norm_zero)\n    obtain s where s: \"\\<forall>y. (\\<exists>x. (\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) = - x) \\<and> y < x) \\<longleftrightarrow> y < s\"\n      by (smt (verit, del_insts) real_sup_exists[OF mth1] norm_zero zero_less_norm_iff)\n\n    let ?m = \"- s\"\n    have s1: \"(\\<exists>z. cmod z \\<le> r \\<and> - (- cmod (poly p z)) < y) \\<longleftrightarrow> ?m < y\" for y\n      by (metis add.inverse_inverse minus_less_iff s)\n    then have s1m: \"\\<And>z. cmod z \\<le> r \\<Longrightarrow> cmod (poly p z) \\<ge> ?m\"\n      by force\n    have \"\\<exists>z. cmod z \\<le> r \\<and> cmod (poly p z) < - s + 1 / real (Suc n)\" for n\n      using s1[of \"?m + 1/real (Suc n)\"] by simp\n    then obtain g where g: \"\\<forall>n. cmod (g n) \\<le> r\" \"\\<forall>n. cmod (poly p (g n)) <?m + 1 /real(Suc n)\"\n      by metis\n    from Bolzano_Weierstrass_complex_disc[OF g(1)]\n    obtain f::\"nat \\<Rightarrow> nat\" and z where fz: \"strict_mono f\" \"\\<forall>e>0. \\<exists>N. \\<forall>n\\<ge>N. cmod (g (f n) - z) < e\"\n      by blast\n    {\n      fix w\n      assume wr: \"cmod w \\<le> r\"\n      let ?e = \"\\<bar>cmod (poly p z) - ?m\\<bar>\"\n      {\n        assume e: \"?e > 0\"\n        then have e2: \"?e/2 > 0\"\n          by simp\n        with poly_cont obtain d \n          where \"d > 0\" and d: \"\\<And>w. 0<cmod (w - z)\\<and> cmod(w - z) < d \\<longrightarrow> cmod(poly p w - poly p z) < ?e/2\"\n          by blast\n        have 1: \"cmod(poly p w - poly p z) < ?e / 2\" if w: \"cmod (w - z) < d\" for w\n          using d[of w] w e by (cases \"w = z\") simp_all\n        from fz(2) \\<open>d > 0\\<close> obtain N1 where N1: \"\\<forall>n\\<ge>N1. cmod (g (f n) - z) < d\"\n          by blast\n        from reals_Archimedean2 obtain N2 :: nat where N2: \"2/?e < real N2\"\n          by blast\n        have 2: \"cmod (poly p (g (f (N1 + N2))) - poly p z) < ?e/2\"\n          using N1 1 by auto\n        have 0: \"a < e2 \\<Longrightarrow> \\<bar>b - m\\<bar> < e2 \\<Longrightarrow> 2 * e2 \\<le> \\<bar>b - m\\<bar> + a \\<Longrightarrow> False\"\n          for a b e2 m :: real\n          by arith\n        from seq_suble[OF fz(1), of \"N1 + N2\"]\n        have 00: \"?m + 1 / real (Suc (f (N1 + N2))) \\<le> ?m + 1 / real (Suc (N1 + N2))\"\n          by (simp add: frac_le)\n        from N2 e2 less_imp_inverse_less[of \"2/?e\" \"real (Suc (N1 + N2))\"]\n        have \"?e/2 > 1/ real (Suc (N1 + N2))\"\n          by (simp add: inverse_eq_divide)\n        with  order_less_le_trans[OF _ 00]\n        have 1: \"\\<bar>cmod (poly p (g (f (N1 + N2)))) - ?m\\<bar> < ?e/2\"\n          using g s1 by (smt (verit))\n        with 0[OF 2] have False\n          by (smt (verit) field_sum_of_halves norm_triangle_ineq3)\n      }\n      then have \"?e = 0\"\n        by auto\n      with s1m[OF wr] have \"cmod (poly p z) \\<le> cmod (poly p w)\"\n        by simp\n    }\n    then show ?thesis by blast\n  qed\nqed\n\ntext \\<open>Nonzero polynomial in z goes to infinity as z does.\\<close>\n\nlemma poly_infinity:\n  fixes p:: \"'a::{comm_semiring_0,real_normed_div_algebra} poly\"\n  assumes ex: \"p \\<noteq> 0\"\n  shows \"\\<exists>r. \\<forall>z. r \\<le> norm z \\<longrightarrow> d \\<le> norm (poly (pCons a p) z)\"\n  using ex\nproof (induct p arbitrary: a d)\n  case 0\n  then show ?case by simp\nnext\n  case (pCons c cs a d)\n  show ?case\n  proof (cases \"cs = 0\")\n    case False\n    with pCons.hyps obtain r where r: \"\\<forall>z. r \\<le> norm z \\<longrightarrow> d + norm a \\<le> norm (poly (pCons c cs) z)\"\n      by blast\n    let ?r = \"1 + \\<bar>r\\<bar>\"\n    have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\" if \"1 + \\<bar>r\\<bar> \\<le> norm z\" for z\n    proof -\n      have \"d \\<le> norm(z * poly (pCons c cs) z) - norm a\"\n        by (smt (verit, best) norm_ge_zero mult_less_cancel_right2 norm_mult r that)\n      with norm_diff_ineq add.commute\n      show ?thesis\n        by (metis order.trans poly_pCons)\n    qed\n    then show ?thesis by blast\n  next\n    case True\n    have \"d \\<le> norm (poly (pCons a (pCons c cs)) z)\"\n      if \"(\\<bar>d\\<bar> + norm a) / norm c \\<le> norm z\" for z :: 'a\n    proof -\n      have \"\\<bar>d\\<bar> + norm a \\<le> norm (z * c)\"\n        by (metis that True norm_mult pCons.hyps(1) pos_divide_le_eq zero_less_norm_iff)\n      also have \"\\<dots> \\<le> norm (a + z * c) + norm a\"\n        by (simp add: add.commute norm_add_leD)\n      finally show ?thesis\n        using True by auto\n    qed\n    then show ?thesis by blast\n  qed\nqed\n\ntext \\<open>Hence polynomial's modulus attains its minimum somewhere.\\<close>\nlemma poly_minimum_modulus: \"\\<exists>z.\\<forall>w. cmod (poly p z) \\<le> cmod (poly p w)\"\nproof (induct p)\n  case 0\n  then show ?case by simp\nnext\n  case (pCons c cs)\n  show ?case\n  proof (cases \"cs = 0\")\n    case False\n    from poly_infinity[OF False, of \"cmod (poly (pCons c cs) 0)\" c]\n    obtain r where r: \"cmod (poly (pCons c cs) 0) \\<le> cmod (poly (pCons c cs) z)\"\n      if \"r \\<le> cmod z\" for z\n      by blast\n    from poly_minimum_modulus_disc[of \"\\<bar>r\\<bar>\" \"pCons c cs\"] show ?thesis\n      by (smt (verit, del_insts) order.trans linorder_linear r)\n  qed (use pCons.hyps in auto)\nqed\n\ntext \\<open>Constant function (non-syntactic characterization).\\<close>\ndefinition \"constant f \\<longleftrightarrow> (\\<forall>x y. f x = f y)\"\n\nlemma nonconstant_length: \"\\<not> constant (poly p) \\<Longrightarrow> psize p \\<ge> 2\"\n  by (induct p) (auto simp: constant_def psize_def)\n\nlemma poly_replicate_append: \"poly (monom 1 n * p) (x::'a::comm_ring_1) = x^n * poly p x\"\n  by (simp add: poly_monom)\n\ntext \\<open>Decomposition of polynomial, skipping zero coefficients after the first.\\<close>\n\nlemma poly_decompose_lemma:\n  assumes nz: \"\\<not> (\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly p z = (0::'a::idom))\"\n  shows \"\\<exists>k a q. a \\<noteq> 0 \\<and> Suc (psize q + k) = psize p \\<and> (\\<forall>z. poly p z = z^k * poly (pCons a q) z)\"\n  unfolding psize_def\n  using nz\nproof (induct p)\n  case 0\n  then show ?case by simp\nnext\n  case (pCons c cs)\n  show ?case\n  proof (cases \"c = 0\")\n    case True\n    from pCons.hyps pCons.prems True show ?thesis\n      apply auto\n      apply (rule_tac x=\"k+1\" in exI)\n      apply (rule_tac x=\"a\" in exI)\n      apply clarsimp\n      apply (rule_tac x=\"q\" in exI)\n      apply auto\n      done\n  qed force\nqed\n\nlemma poly_decompose:\n  fixes p :: \"'a::idom poly\"\n  assumes nc: \"\\<not> constant (poly p)\"\n  shows \"\\<exists>k a q. a \\<noteq> 0 \\<and> k \\<noteq> 0 \\<and>\n               psize q + k + 1 = psize p \\<and>\n              (\\<forall>z. poly p z = poly p 0 + z^k * poly (pCons a q) z)\" \n  using nc\nproof (induct p)\n  case 0\n  then show ?case\n    by (simp add: constant_def)\nnext\n  case (pCons c cs)\n  have \"\\<not> (\\<forall>z. z \\<noteq> 0 \\<longrightarrow> poly cs z = 0)\"\n    by (smt (verit) constant_def mult_eq_0_iff pCons.prems poly_pCons)\n  from poly_decompose_lemma[OF this]\n  obtain k a q where *: \"a \\<noteq> 0 \\<and>\n     Suc (psize q + k) = psize cs \\<and> (\\<forall>z. poly cs z = z ^ k * poly (pCons a q) z)\"\n    by blast\n  then have \"psize q + k + 2 = psize (pCons c cs)\"\n    by (auto simp add: psize_def split: if_splits)\n  then show ?case\n    using \"*\" by force\nqed\n\ntext \\<open>Fundamental theorem of algebra\\<close>\n\nlemma fundamental_theorem_of_algebra:\n  assumes nc: \"\\<not> constant (poly p)\"\n  shows \"\\<exists>z::complex. poly p z = 0\"\n  using nc\nproof (induct \"psize p\" arbitrary: p rule: less_induct)\n  case less\n  let ?p = \"poly p\"\n  let ?ths = \"\\<exists>z. ?p z = 0\"\n\n  from nonconstant_length[OF less(2)] have n2: \"psize p \\<ge> 2\" .\n  from poly_minimum_modulus obtain c where c: \"\\<forall>w. cmod (?p c) \\<le> cmod (?p w)\"\n    by blast\n\n  show ?ths\n  proof (cases \"?p c = 0\")\n    case True\n    then show ?thesis by blast\n  next\n    case False\n    obtain q where q: \"psize q = psize p\" \"\\<forall>x. poly q x = ?p (c + x)\"\n      using poly_offset[of p c] by blast\n    then have qnc: \"\\<not> constant (poly q)\"\n      by (metis (no_types, opaque_lifting) add.commute constant_def diff_add_cancel less.prems)\n    from q(2) have pqc0: \"?p c = poly q 0\"\n      by simp\n    from c pqc0 have cq0: \"\\<forall>w. cmod (poly q 0) \\<le> cmod (?p w)\"\n      by simp\n    let ?a0 = \"poly q 0\"\n    from False pqc0 have a00: \"?a0 \\<noteq> 0\"\n      by simp\n    from a00 have qr: \"\\<forall>z. poly q z = poly (smult (inverse ?a0) q) z * ?a0\"\n      by simp\n    let ?r = \"smult (inverse ?a0) q\"\n    have lgqr: \"psize q = psize ?r\"\n      by (simp add: a00 psize_def)\n    have rnc: \"\\<not> constant (poly ?r)\"\n      using constant_def qnc qr by fastforce \n    have r01: \"poly ?r 0 = 1\"\n      by (simp add: a00)\n    have mrmq_eq: \"cmod (poly ?r w) < 1 \\<longleftrightarrow> cmod (poly q w) < cmod ?a0\" for w\n      by (smt (verit, del_insts) a00 mult_less_cancel_right2 norm_mult qr zero_less_norm_iff)\n    from poly_decompose[OF rnc] obtain k a s where\n      kas: \"a \\<noteq> 0\" \"k \\<noteq> 0\" \"psize s + k + 1 = psize ?r\"\n        \"\\<forall>z. poly ?r z = poly ?r 0 + z^k* poly (pCons a s) z\" by blast\n    have \"\\<exists>w. cmod (poly ?r w) < 1\"\n    proof (cases \"psize p = k + 1\")\n      case True \n      with kas q have s0: \"s = 0\"\n        by (simp add: lgqr)\n      with reduce_poly_simple kas show ?thesis\n        by (metis mult.commute mult.right_neutral poly_1 poly_smult r01 smult_one)\n    next\n      case False note kn = this\n      from kn kas(3) q(1) lgqr have k1n: \"k + 1 < psize p\"\n        by simp\n      have 01: \"\\<not> constant (poly (pCons 1 (monom a (k - 1))))\"\n        unfolding constant_def poly_pCons poly_monom\n        by (metis add_cancel_left_right kas(1) mult.commute mult_cancel_right2 power_one)\n      have 02: \"k + 1 = psize (pCons 1 (monom a (k - 1)))\"\n        using kas by (simp add: psize_def degree_monom_eq)\n      from less(1) [OF _ 01] k1n 02\n      obtain w where w: \"1 + w^k * a = 0\"\n        by (metis kas(2) mult.commute mult.left_commute poly_monom poly_pCons power_eq_if)\n      from poly_bound_exists[of \"cmod w\" s] obtain m where\n        m: \"m > 0\" \"\\<forall>z. cmod z \\<le> cmod w \\<longrightarrow> cmod (poly s z) \\<le> m\" by blast\n      have \"w \\<noteq> 0\"\n        using kas(2) w by (auto simp add: power_0_left)\n      from w have wm1: \"w^k * a = - 1\"\n        by (simp add: add_eq_0_iff)\n      have inv0: \"0 < inverse (cmod w ^ (k + 1) * m)\"\n        by (simp add: \\<open>w \\<noteq> 0\\<close> m(1))\n      with field_lbound_gt_zero[OF zero_less_one] obtain t where\n        t: \"t > 0\" \"t < 1\" \"t < inverse (cmod w ^ (k + 1) * m)\" by blast\n      let ?ct = \"complex_of_real t\"\n      let ?w = \"?ct * w\"\n      have \"1 + ?w^k * (a + ?w * poly s ?w) = 1 + ?ct^k * (w^k * a) + ?w^k * ?w * poly s ?w\"\n        using kas(1) by (simp add: algebra_simps power_mult_distrib)\n      also have \"\\<dots> = complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w\"\n        unfolding wm1 by simp\n      finally have \"cmod (1 + ?w^k * (a + ?w * poly s ?w)) =\n        cmod (complex_of_real (1 - t^k) + ?w^k * ?w * poly s ?w)\"\n        by metis\n      with norm_triangle_ineq[of \"complex_of_real (1 - t^k)\" \"?w^k * ?w * poly s ?w\"]\n      have 11: \"cmod (1 + ?w^k * (a + ?w * poly s ?w)) \\<le> \\<bar>1 - t^k\\<bar> + cmod (?w^k * ?w * poly s ?w)\"\n        unfolding norm_of_real by simp\n      have ath: \"\\<And>x t::real. 0 \\<le> x \\<Longrightarrow> x < t \\<Longrightarrow> t \\<le> 1 \\<Longrightarrow> \\<bar>1 - t\\<bar> + x < 1\"\n        by arith\n      have tw: \"cmod ?w \\<le> cmod w\"\n        by (smt (verit) mult_le_cancel_right2 norm_ge_zero norm_mult norm_of_real t)\n      have \"t * (cmod w ^ (k + 1) * m) < 1\"\n        by (smt (verit, best) inv0 inverse_positive_iff_positive left_inverse mult_strict_right_mono t(3))\n      with zero_less_power[OF t(1), of k] have 30: \"t^k * (t* (cmod w ^ (k + 1) * m)) < t^k\"\n        by simp\n      have \"cmod (?w^k * ?w * poly s ?w) = t^k * (t* (cmod w ^ (k + 1) * cmod (poly s ?w)))\"\n        using \\<open>w \\<noteq> 0\\<close> t(1) by (simp add: algebra_simps norm_power norm_mult)\n      with 30 have 120: \"cmod (?w^k * ?w * poly s ?w) < t^k\"\n        by (smt (verit, ccfv_SIG) m(2) mult_left_mono norm_ge_zero t(1) tw zero_le_power)\n      from power_strict_mono[OF t(2), of k] t(1) kas(2) have 121: \"t^k \\<le> 1\"\n        by auto\n      from ath[OF norm_ge_zero[of \"?w^k * ?w * poly s ?w\"] 120 121]\n      show ?thesis\n        by (smt (verit) \"11\" kas(4) poly_pCons r01)\n    qed\n    with cq0 q(2) show ?thesis\n      by (smt (verit) mrmq_eq)\n  qed\nqed\n\ntext \\<open>Alternative version with a syntactic notion of constant polynomial.\\<close>\n\nlemma fundamental_theorem_of_algebra_alt:\n  assumes nc: \"\\<not> (\\<exists>a l. a \\<noteq> 0 \\<and> l = 0 \\<and> p = pCons a l)\"\n  shows \"\\<exists>z. poly p z = (0::complex)\"\nproof (rule ccontr)\n  assume N: \"\\<nexists>z. poly p z = 0\"\n  then have \"\\<not> constant (poly p)\"\n    unfolding constant_def\n    by (metis (no_types, opaque_lifting) nc poly_pcompose pcompose_0' pcompose_const poly_0_coeff_0 \n        poly_all_0_iff_0 poly_diff right_minus_eq)\n  then show False\n    using N fundamental_theorem_of_algebra by blast\nqed\n\nsubsection \\<open>Nullstellensatz, degrees and divisibility of polynomials\\<close>\n\nlemma nullstellensatz_lemma:\n  fixes p :: \"complex poly\"\n  assumes \"\\<forall>x. poly p x = 0 \\<longrightarrow> poly q x = 0\"\n    and \"degree p = n\"\n    and \"n \\<noteq> 0\"\n  shows \"p dvd (q ^ n)\"\n  using assms\nproof (induct n arbitrary: p q rule: nat_less_induct)\n  fix n :: nat\n  fix p q :: \"complex poly\"\n  assume IH: \"\\<forall>m<n. \\<forall>p q.\n                 (\\<forall>x. poly p x = (0::complex) \\<longrightarrow> poly q x = 0) \\<longrightarrow>\n                 degree p = m \\<longrightarrow> m \\<noteq> 0 \\<longrightarrow> p dvd (q ^ m)\"\n    and pq0: \"\\<forall>x. poly p x = 0 \\<longrightarrow> poly q x = 0\"\n    and dpn: \"degree p = n\"\n    and n0: \"n \\<noteq> 0\"\n  from dpn n0 have pne: \"p \\<noteq> 0\" by auto\n  show \"p dvd (q ^ n)\"\n  proof (cases \"\\<exists>a. poly p a = 0\")\n    case True\n    then obtain a where a: \"poly p a = 0\" ..\n    have ?thesis if oa: \"order a p \\<noteq> 0\"\n    proof -\n      let ?op = \"order a p\"\n      from pne have ap: \"([:- a, 1:] ^ ?op) dvd p\" \"\\<not> [:- a, 1:] ^ (Suc ?op) dvd p\"\n        using order by blast+\n      note oop = order_degree[OF pne, unfolded dpn]\n      show ?thesis\n      proof (cases \"q = 0\")\n        case True\n        with n0 show ?thesis by (simp add: power_0_left)\n      next\n        case False\n        from pq0[rule_format, OF a, unfolded poly_eq_0_iff_dvd]\n        obtain r where r: \"q = [:- a, 1:] * r\" by (rule dvdE)\n        from ap(1) obtain s where s: \"p = [:- a, 1:] ^ ?op * s\"\n          by (rule dvdE)\n        have sne: \"s \\<noteq> 0\"\n          using s pne by auto\n        show ?thesis\n        proof (cases \"degree s = 0\")\n          case True\n          then obtain k where kpn: \"s = [:k:]\"\n            by (cases s) (auto split: if_splits)\n          from sne kpn have k: \"k \\<noteq> 0\" by simp\n          let ?w = \"([:1/k:] * ([:-a,1:] ^ (n - ?op))) * (r ^ n)\"\n          have \"q^n = [:- a, 1:] ^ n * r ^ n\"\n            using power_mult_distrib r by blast\n          also have \"... = [:- a, 1:] ^ order a p * [:k:] * ([:1 / k:] * [:- a, 1:] ^ (n - order a p) * r ^ n)\"\n            using k oop [of a] by (simp flip: power_add)\n          also have \"... = p * ?w\"\n            by (metis s kpn)\n          finally show ?thesis\n            unfolding dvd_def by blast\n        next\n          case False\n          with sne dpn s oa have dsn: \"degree s < n\"\n            by (metis add_diff_cancel_right' degree_0 degree_linear_power degree_mult_eq gr0I zero_less_diff)\n          have \"poly r x = 0\" if h: \"poly s x = 0\" for x\n          proof -\n            have \"x \\<noteq> a\"\n              by (metis ap(2) dvd_refl mult_dvd_mono poly_eq_0_iff_dvd power_Suc power_commutes s that)\n            moreover have \"poly p x = 0\"\n              by (metis (no_types) mult_eq_0_iff poly_mult s that)\n            ultimately show ?thesis\n              using pq0 r by auto\n          qed\n          with False IH dsn obtain u where u: \"r ^ (degree s) = s * u\"\n            by blast\n          then have u': \"\\<And>x. poly s x * poly u x = poly r x ^ degree s\"\n            by (simp only: poly_mult[symmetric] poly_power[symmetric])\n          have \"q^n = [:- a, 1:] ^ n * r ^ n\"\n            using power_mult_distrib r by blast\n          also have \"... = [:- a, 1:] ^ order a p * (s * u * ([:- a, 1:] ^ (n - order a p) * r ^ (n - degree s)))\"\n            by (smt (verit, del_insts) s u mult_ac power_add add_diff_cancel_right' degree_linear_power degree_mult_eq dpn mult_zero_left)\n          also have \"... = p * (u * ([:-a,1:] ^ (n - ?op))) * (r ^ (n - degree s))\"\n            using s by force\n          finally show ?thesis\n            unfolding dvd_def by auto\n        qed\n      qed\n    qed\n    then show ?thesis\n      using a order_root pne by blast\n  next\n    case False\n    then show ?thesis\n      using dpn n0 fundamental_theorem_of_algebra_alt[of p]\n      by fastforce\n  qed\nqed\n\nlemma nullstellensatz_univariate:\n  \"(\\<forall>x. poly p x = (0::complex) \\<longrightarrow> poly q x = 0) \\<longleftrightarrow>\n    p dvd (q ^ (degree p)) \\<or> (p = 0 \\<and> q = 0)\"\nproof -\n  consider \"p = 0\" | \"p \\<noteq> 0\" \"degree p = 0\" | n where \"p \\<noteq> 0\" \"degree p = Suc n\"\n    by (cases \"degree p\") auto\n  then show ?thesis\n  proof cases\n    case p: 1\n    then have \"(\\<forall>x. poly p x = (0::complex) \\<longrightarrow> poly q x = 0) \\<longleftrightarrow> q = 0\"\n      by (auto simp add: poly_all_0_iff_0)\n    with p show ?thesis\n      by force\n  next\n    case dp: 2\n    then show ?thesis\n      by (meson dvd_trans is_unit_iff_degree poly_eq_0_iff_dvd unit_imp_dvd)\n  next\n    case dp: 3\n    have False if \"p dvd (q ^ (Suc n))\" \"poly p x = 0\" \"poly q x \\<noteq> 0\" for x\n      by (metis dvd_trans poly_eq_0_iff_dvd poly_power power_eq_0_iff that)\n    with dp nullstellensatz_lemma[of p q \"degree p\"] show ?thesis\n      by auto\n  qed\nqed\n\ntext \\<open>Useful lemma\\<close>\nlemma constant_degree:\n  fixes p :: \"'a::{idom,ring_char_0} poly\"\n  shows \"constant (poly p) \\<longleftrightarrow> degree p = 0\" (is \"?lhs = ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    from that[unfolded constant_def, rule_format, of _ \"0\"]\n    have \"poly p = poly [:poly p 0:]\"\n      by auto\n    then show ?thesis\n      by (metis degree_pCons_0 poly_eq_poly_eq_iff)\n  qed\n  show ?lhs if ?rhs\n    unfolding constant_def\n    by (metis degree_eq_zeroE pcompose_const poly_0 poly_pcompose that)\nqed\n\ntext \\<open>Arithmetic operations on multivariate polynomials.\\<close>\n\nlemma mpoly_base_conv:\n  fixes x :: \"'a::comm_ring_1\"\n  shows \"0 = poly 0 x\" \"c = poly [:c:] x\" \"x = poly [:0,1:] x\"\n  by simp_all\n\nlemma mpoly_norm_conv:\n  fixes x :: \"'a::comm_ring_1\"\n  shows \"poly [:0:] x = poly 0 x\" \"poly [:poly 0 y:] x = poly 0 x\"\n  by simp_all\n\nlemma mpoly_sub_conv:\n  fixes x :: \"'a::comm_ring_1\"\n  shows \"poly p x - poly q x = poly p x + -1 * poly q x\"\n  by simp\n\nlemma poly_pad_rule: \"poly p x = 0 \\<Longrightarrow> poly (pCons 0 p) x = 0\"\n  by simp\n\nlemma poly_cancel_eq_conv:\n  fixes x :: \"'a::field\"\n  shows \"x = 0 \\<Longrightarrow> a \\<noteq> 0 \\<Longrightarrow> y = 0 \\<longleftrightarrow> a * y - b * x = 0\"\n  by auto\n\nlemma poly_divides_pad_rule:\n  fixes p:: \"('a::comm_ring_1) poly\"\n  assumes pq: \"p dvd q\"\n  shows \"p dvd (pCons 0 q)\"\n  by (metis add_0 dvd_def mult_pCons_right pq smult_0_left)\n\nlemma poly_divides_conv0:\n  fixes p:: \"'a::field poly\"\n  assumes lgpq: \"degree q < degree p\" and lq: \"p \\<noteq> 0\"\n  shows \"p dvd q \\<longleftrightarrow> q = 0\"\n  using lgpq mod_poly_less by fastforce\n\nlemma poly_divides_conv1:\n  fixes p :: \"'a::field poly\"\n  assumes a0: \"a \\<noteq> 0\"\n    and pp': \"p dvd p'\"\n    and qrp': \"smult a q - p' = r\"\n  shows \"p dvd q \\<longleftrightarrow> p dvd r\"\n  by (metis a0 diff_add_cancel dvd_add_left_iff dvd_smult_iff pp' qrp')\n\nlemma basic_cqe_conv1:\n  \"(\\<exists>x. poly p x = 0 \\<and> poly 0 x \\<noteq> 0) \\<longleftrightarrow> False\"\n  \"(\\<exists>x. poly 0 x \\<noteq> 0) \\<longleftrightarrow> False\"\n  \"(\\<exists>x. poly [:c:] x \\<noteq> 0) \\<longleftrightarrow> c \\<noteq> 0\"\n  \"(\\<exists>x. poly 0 x = 0) \\<longleftrightarrow> True\"\n  \"(\\<exists>x. poly [:c:] x = 0) \\<longleftrightarrow> c = 0\"\n  by simp_all\n\nlemma basic_cqe_conv2:\n  assumes l: \"p \\<noteq> 0\"\n  shows \"\\<exists>x. poly (pCons a (pCons b p)) x = (0::complex)\"\n  by (meson fundamental_theorem_of_algebra_alt l pCons_eq_0_iff pCons_eq_iff)\n\nlemma  basic_cqe_conv_2b: \"(\\<exists>x. poly p x \\<noteq> (0::complex)) \\<longleftrightarrow> p \\<noteq> 0\"\n  by (metis poly_all_0_iff_0)\n\nlemma basic_cqe_conv3:\n  fixes p q :: \"complex poly\"\n  assumes l: \"p \\<noteq> 0\"\n  shows \"(\\<exists>x. poly (pCons a p) x = 0 \\<and> poly q x \\<noteq> 0) \\<longleftrightarrow> \\<not> (pCons a p) dvd (q ^ psize p)\"\n  by (metis degree_pCons_eq_if l nullstellensatz_univariate pCons_eq_0_iff psize_def)\n\nlemma basic_cqe_conv4:\n  fixes p q :: \"complex poly\"\n  assumes h: \"\\<And>x. poly (q ^ n) x = poly r x\"\n  shows \"p dvd (q ^ n) \\<longleftrightarrow> p dvd r\"\n  by (metis (no_types) basic_cqe_conv_2b h poly_diff right_minus_eq)\n\nlemma poly_const_conv:\n  fixes x :: \"'a::comm_ring_1\"\n  shows \"poly [:c:] x = y \\<longleftrightarrow> c = y\"\n  by simp\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Computational_Algebra/Fundamental_Theorem_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.8723473713594992, "lm_q1q2_score": 0.7855747870932919}}
{"text": "theory P6 imports Main begin\n\nfun occurs :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"occurs x Nil = 0\" | \n\"occurs x (y # xs) = (if x=y then (Suc (occurs x xs)) else (occurs x xs))\"\n\n\n\ntheorem \"occurs a xs = occurs a (rev xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\ntheorem \"occurs a xs <= length xs\"\n  apply (induct xs)\n  apply auto\n  done\n\nlemma \"occurs a (map f xs) = occurs (f a) xs\"\n  nitpick\n  oops\n\ntheorem \"occurs a (filter P xs) = (occurs True (map (\\<lambda>x. (P x \\<and> (x=a))) xs))\"\n  apply (induct xs)\n   apply auto\n  done\n\nfun remDups :: \"'a list \\<Rightarrow> 'a list\" where\n\"remDups Nil = Nil\" | \n\"remDups (x # xs) = (if (occurs x xs > 0) then (remDups xs) else (x # (remDups xs)))\"\n\ntheorem [simp]: \"occurs x (remDups xs) = (if (occurs x xs > 0) then 1 else 0)\"\n  apply (induct xs)\n   apply auto\n  done\n\nfun unique :: \"'a list \\<Rightarrow> bool\" where\n\"unique Nil = True\" |\n\"unique (x # xs) = (if (occurs x xs > 0) then False else (unique xs))\"\n\ntheorem \"unique (remDups xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7854756872405279}}
{"text": "(*<*)theory Even imports Main begin\nML_file \\<open>../../antiquote_setup.ML\\<close> \n(*>*)\n\nsection\\<open>The Set of Even Numbers\\<close>\n\ntext \\<open>\n\\index{even numbers!defining inductively|(}%\nThe set of even numbers can be inductively defined as the least set\ncontaining 0 and closed under the operation $+2$.  Obviously,\n\\emph{even} can also be expressed using the divides relation (\\<open>dvd\\<close>). \nWe shall prove below that the two formulations coincide.  On the way we\nshall examine the primary means of reasoning about inductively defined\nsets: rule induction.\n\\<close>\n\nsubsection\\<open>Making an Inductive Definition\\<close>\n\ntext \\<open>\nUsing \\commdx{inductive\\protect\\_set}, we declare the constant \\<open>even\\<close> to be\na set of natural numbers with the desired properties.\n\\<close>\n\ninductive_set even :: \"nat set\" where\nzero[intro!]: \"0 \\<in> even\" |\nstep[intro!]: \"n \\<in> even \\<Longrightarrow> (Suc (Suc n)) \\<in> even\"\n\ntext \\<open>\nAn inductive definition consists of introduction rules.  The first one\nabove states that 0 is even; the second states that if $n$ is even, then so\nis~$n+2$.  Given this declaration, Isabelle generates a fixed point\ndefinition for \\<^term>\\<open>even\\<close> and proves theorems about it,\nthus following the definitional approach (see {\\S}\\ref{sec:definitional}).\nThese theorems\ninclude the introduction rules specified in the declaration, an elimination\nrule for case analysis and an induction rule.  We can refer to these\ntheorems by automatically-generated names.  Here are two examples:\n@{named_thms[display,indent=0] even.zero[no_vars] (even.zero) even.step[no_vars] (even.step)}\n\nThe introduction rules can be given attributes.  Here\nboth rules are specified as \\isa{intro!},%\n\\index{intro\"!@\\isa {intro\"!} (attribute)}\ndirecting the classical reasoner to \napply them aggressively. Obviously, regarding 0 as even is safe.  The\n\\<open>step\\<close> rule is also safe because $n+2$ is even if and only if $n$ is\neven.  We prove this equivalence later.\n\\<close>\n\nsubsection\\<open>Using Introduction Rules\\<close>\n\ntext \\<open>\nOur first lemma states that numbers of the form $2\\times k$ are even.\nIntroduction rules are used to show that specific values belong to the\ninductive set.  Such proofs typically involve \ninduction, perhaps over some other inductive set.\n\\<close>\n\nlemma two_times_even[intro!]: \"2*k \\<in> even\"\napply (induct_tac k)\n apply auto\ndone\n(*<*)\nlemma \"2*k \\<in> even\"\napply (induct_tac k)\n(*>*)\ntxt \\<open>\n\\noindent\nThe first step is induction on the natural number \\<open>k\\<close>, which leaves\ntwo subgoals:\n@{subgoals[display,indent=0,margin=65]}\nHere \\<open>auto\\<close> simplifies both subgoals so that they match the introduction\nrules, which are then applied automatically.\n\nOur ultimate goal is to prove the equivalence between the traditional\ndefinition of \\<open>even\\<close> (using the divides relation) and our inductive\ndefinition.  One direction of this equivalence is immediate by the lemma\njust proved, whose \\<open>intro!\\<close> attribute ensures it is applied automatically.\n\\<close>\n(*<*)oops(*>*)\nlemma dvd_imp_even: \"2 dvd n \\<Longrightarrow> n \\<in> even\"\nby (auto simp add: dvd_def)\n\nsubsection\\<open>Rule Induction \\label{sec:rule-induction}\\<close>\n\ntext \\<open>\n\\index{rule induction|(}%\nFrom the definition of the set\n\\<^term>\\<open>even\\<close>, Isabelle has\ngenerated an induction rule:\n@{named_thms [display,indent=0,margin=40] even.induct [no_vars] (even.induct)}\nA property \\<^term>\\<open>P\\<close> holds for every even number provided it\nholds for~\\<open>0\\<close> and is closed under the operation\n\\isa{Suc(Suc \\(\\cdot\\))}.  Then \\<^term>\\<open>P\\<close> is closed under the introduction\nrules for \\<^term>\\<open>even\\<close>, which is the least set closed under those rules. \nThis type of inductive argument is called \\textbf{rule induction}. \n\nApart from the double application of \\<^term>\\<open>Suc\\<close>, the induction rule above\nresembles the familiar mathematical induction, which indeed is an instance\nof rule induction; the natural numbers can be defined inductively to be\nthe least set containing \\<open>0\\<close> and closed under~\\<^term>\\<open>Suc\\<close>.\n\nInduction is the usual way of proving a property of the elements of an\ninductively defined set.  Let us prove that all members of the set\n\\<^term>\\<open>even\\<close> are multiples of two.\n\\<close>\n\nlemma even_imp_dvd: \"n \\<in> even \\<Longrightarrow> 2 dvd n\"\ntxt \\<open>\nWe begin by applying induction.  Note that \\<open>even.induct\\<close> has the form\nof an elimination rule, so we use the method \\<open>erule\\<close>.  We get two\nsubgoals:\n\\<close>\napply (erule even.induct)\ntxt \\<open>\n@{subgoals[display,indent=0]}\nWe unfold the definition of \\<open>dvd\\<close> in both subgoals, proving the first\none and simplifying the second:\n\\<close>\napply (simp_all add: dvd_def)\ntxt \\<open>\n@{subgoals[display,indent=0]}\nThe next command eliminates the existential quantifier from the assumption\nand replaces \\<open>n\\<close> by \\<open>2 * k\\<close>.\n\\<close>\napply clarify\ntxt \\<open>\n@{subgoals[display,indent=0]}\nTo conclude, we tell Isabelle that the desired value is\n\\<^term>\\<open>Suc k\\<close>.  With this hint, the subgoal falls to \\<open>simp\\<close>.\n\\<close>\napply (rule_tac x = \"Suc k\" in exI, simp)\n(*<*)done(*>*)\n\ntext \\<open>\nCombining the previous two results yields our objective, the\nequivalence relating \\<^term>\\<open>even\\<close> and \\<open>dvd\\<close>. \n%\n%we don't want [iff]: discuss?\n\\<close>\n\ntheorem even_iff_dvd: \"(n \\<in> even) = (2 dvd n)\"\nby (blast intro: dvd_imp_even even_imp_dvd)\n\n\nsubsection\\<open>Generalization and Rule Induction \\label{sec:gen-rule-induction}\\<close>\n\ntext \\<open>\n\\index{generalizing for induction}%\nBefore applying induction, we typically must generalize\nthe induction formula.  With rule induction, the required generalization\ncan be hard to find and sometimes requires a complete reformulation of the\nproblem.  In this  example, our first attempt uses the obvious statement of\nthe result.  It fails:\n\\<close>\n\nlemma \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\napply (erule even.induct)\noops\n(*<*)\nlemma \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\napply (erule even.induct)\n(*>*)\ntxt \\<open>\nRule induction finds no occurrences of \\<^term>\\<open>Suc(Suc n)\\<close> in the\nconclusion, which it therefore leaves unchanged.  (Look at\n\\<open>even.induct\\<close> to see why this happens.)  We have these subgoals:\n@{subgoals[display,indent=0]}\nThe first one is hopeless.  Rule induction on\na non-variable term discards information, and usually fails.\nHow to deal with such situations\nin general is described in {\\S}\\ref{sec:ind-var-in-prems} below.\nIn the current case the solution is easy because\nwe have the necessary inverse, subtraction:\n\\<close>\n(*<*)oops(*>*)\nlemma even_imp_even_minus_2: \"n \\<in> even \\<Longrightarrow> n - 2 \\<in> even\"\napply (erule even.induct)\n apply auto\ndone\n(*<*)\nlemma \"n \\<in>  even \\<Longrightarrow> n - 2 \\<in> even\"\napply (erule even.induct)\n(*>*)\ntxt \\<open>\nThis lemma is trivially inductive.  Here are the subgoals:\n@{subgoals[display,indent=0]}\nThe first is trivial because \\<open>0 - 2\\<close> simplifies to \\<open>0\\<close>, which is\neven.  The second is trivial too: \\<^term>\\<open>Suc (Suc n) - 2\\<close> simplifies to\n\\<^term>\\<open>n\\<close>, matching the assumption.%\n\\index{rule induction|)}  %the sequel isn't really about induction\n\n\\medskip\nUsing our lemma, we can easily prove the result we originally wanted:\n\\<close>\n(*<*)oops(*>*)\nlemma Suc_Suc_even_imp_even: \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\nby (drule even_imp_even_minus_2, simp)\n\ntext \\<open>\nWe have just proved the converse of the introduction rule \\<open>even.step\\<close>.\nThis suggests proving the following equivalence.  We give it the\n\\attrdx{iff} attribute because of its obvious value for simplification.\n\\<close>\n\n\n\n\nsubsection\\<open>Rule Inversion \\label{sec:rule-inversion}\\<close>\n\ntext \\<open>\n\\index{rule inversion|(}%\nCase analysis on an inductive definition is called \\textbf{rule\ninversion}.  It is frequently used in proofs about operational\nsemantics.  It can be highly effective when it is applied\nautomatically.  Let us look at how rule inversion is done in\nIsabelle/HOL\\@.\n\nRecall that \\<^term>\\<open>even\\<close> is the minimal set closed under these two rules:\n@{thm [display,indent=0] even.intros [no_vars]}\nMinimality means that \\<^term>\\<open>even\\<close> contains only the elements that these\nrules force it to contain.  If we are told that \\<^term>\\<open>a\\<close>\nbelongs to\n\\<^term>\\<open>even\\<close> then there are only two possibilities.  Either \\<^term>\\<open>a\\<close> is \\<open>0\\<close>\nor else \\<^term>\\<open>a\\<close> has the form \\<^term>\\<open>Suc(Suc n)\\<close>, for some suitable \\<^term>\\<open>n\\<close>\nthat belongs to\n\\<^term>\\<open>even\\<close>.  That is the gist of the \\<^term>\\<open>cases\\<close> rule, which Isabelle proves\nfor us when it accepts an inductive definition:\n@{named_thms [display,indent=0,margin=40] even.cases [no_vars] (even.cases)}\nThis general rule is less useful than instances of it for\nspecific patterns.  For example, if \\<^term>\\<open>a\\<close> has the form\n\\<^term>\\<open>Suc(Suc n)\\<close> then the first case becomes irrelevant, while the second\ncase tells us that \\<^term>\\<open>n\\<close> belongs to \\<^term>\\<open>even\\<close>.  Isabelle will generate\nthis instance for us:\n\\<close>\n\ninductive_cases Suc_Suc_cases [elim!]: \"Suc(Suc n) \\<in> even\"\n\ntext \\<open>\nThe \\commdx{inductive\\protect\\_cases} command generates an instance of\nthe \\<open>cases\\<close> rule for the supplied pattern and gives it the supplied name:\n@{named_thms [display,indent=0] Suc_Suc_cases [no_vars] (Suc_Suc_cases)}\nApplying this as an elimination rule yields one case where \\<open>even.cases\\<close>\nwould yield two.  Rule inversion works well when the conclusions of the\nintroduction rules involve datatype constructors like \\<^term>\\<open>Suc\\<close> and \\<open>#\\<close>\n(list ``cons''); freeness reasoning discards all but one or two cases.\n\nIn the \\isacommand{inductive\\_cases} command we supplied an\nattribute, \\<open>elim!\\<close>,\n\\index{elim\"!@\\isa {elim\"!} (attribute)}%\nindicating that this elimination rule can be\napplied aggressively.  The original\n\\<^term>\\<open>cases\\<close> rule would loop if used in that manner because the\npattern~\\<^term>\\<open>a\\<close> matches everything.\n\nThe rule \\<open>Suc_Suc_cases\\<close> is equivalent to the following implication:\n@{term [display,indent=0] \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"}\nJust above we devoted some effort to reaching precisely\nthis result.  Yet we could have obtained it by a one-line declaration,\ndispensing with the lemma \\<open>even_imp_even_minus_2\\<close>. \nThis example also justifies the terminology\n\\textbf{rule inversion}: the new rule inverts the introduction rule\n\\<open>even.step\\<close>.  In general, a rule can be inverted when the set of elements\nit introduces is disjoint from those of the other introduction rules.\n\nFor one-off applications of rule inversion, use the \\methdx{ind_cases} method. \nHere is an example:\n\\<close>\n\n(*<*)lemma \"Suc(Suc n) \\<in> even \\<Longrightarrow> P\"(*>*)\napply (ind_cases \"Suc(Suc n) \\<in> even\")\n(*<*)oops(*>*)\n\ntext \\<open>\nThe specified instance of the \\<open>cases\\<close> rule is generated, then applied\nas an elimination rule.\n\nTo summarize, every inductive definition produces a \\<open>cases\\<close> rule.  The\n\\commdx{inductive\\protect\\_cases} command stores an instance of the\n\\<open>cases\\<close> rule for a given pattern.  Within a proof, the\n\\<open>ind_cases\\<close> method applies an instance of the \\<open>cases\\<close>\nrule.\n\nThe even numbers example has shown how inductive definitions can be\nused.  Later examples will show that they are actually worth using.%\n\\index{rule inversion|)}%\n\\index{even numbers!defining inductively|)}\n\\<close>\n\n(*<*)end(*>*)\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/Doc/Tutorial/Inductive/Even.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7854545998810405}}
{"text": "theory Exercises2_06\n  imports Main\nbegin\n\n(*---------------- Exercise 2.6----------------*)\n(* tree datatype *)\ndatatype 'a tree = None | Node \"'a tree\" 'a \"'a tree\"\n\n(* collect function *)\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents None = []\" |\n\"contents (Node l a r) = (Cons a (contents l))@(contents r)\"\n\n(* function to sum tree *)\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree None = 0\" |\n\"sum_tree (Node l a r) = (sum_tree l) + a + (sum_tree r)\"\n\ntheorem sum : \"sum_tree t = sum_list (contents t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\nend\n\n", "meta": {"author": "rohitdureja", "repo": "isabelle-practice", "sha": "1cb45450b155d1516c0cf3ce6787452ae33712c1", "save_path": "github-repos/isabelle/rohitdureja-isabelle-practice", "path": "github-repos/isabelle/rohitdureja-isabelle-practice/isabelle-practice-1cb45450b155d1516c0cf3ce6787452ae33712c1/Exercises2_06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7853804035605498}}
{"text": "theory Chapter2\nimports Main\nbegin\n\ntext{*\n\\section*{Chapter 2}\n\n\\exercise\nUse the \\textbf{value} command to evaluate the following expressions:\n*}\n\n \"1 + (2::nat)\"\n \"1 + (2::int)\"\n \"1 - (2::nat)\"\n \"1 - (2::int)\"\n \"[a,b] @ [c,d]\"\n\ntext{*\n\\endexercise\n\n\n\\exercise\nRecall the definition of our own addition function on @{typ nat}:\n*}\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\ntext{*\nProve that @{const add} is associative and commutative.\nYou will need additional lemmas.\n*}\n\n\n\nlemma add_comm: \"add m n = add n m\"\n(* your definition/proof here *)\n\ntext{* Define a recursive function *}\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n(* your definition/proof here *)\n\ntext{* and prove that *}\n\nlemma double_add: \"double m = add m m\"\n(* your definition/proof here *)\ntext{*\n\\endexercise\n\n\n\\exercise\nDefine a function that counts the number of occurrences of\nan element in a list:\n*}\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n(* your definition/proof here *)\ntext {*\nTest your definition of @{term count} on some examples.\nProve the following inequality:\n*}\n\ntheorem \"count xs x \\<le> length xs\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\nDefine a function @{text snoc} that appends an element to the end of a list.\nDo not use the existing append operator @{text \"@\"} for lists.\n*}\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n(* your definition/proof here *)\n\ntext {*\nConvince yourself on some test cases that your definition\nof @{term snoc} behaves as expected.\nWith the help of @{text snoc} define a recursive function @{text reverse}\nthat reverses a list. Do not use the predefined function @{const rev}.\n*}\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n(* your definition/proof here *)\n\ntext {*\nProve the following theorem. You will need an additional lemma.\n*}\ntheorem \"reverse (reverse xs) = xs\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\nThe aim of this exercise is to prove the summation formula\n\\[ \\sum_{i=0}^{n}i = \\frac{n(n+1)}{2} \\]\nDefine a recursive function @{text \"sum_upto n = 0 + ... + n\"}:\n*}\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n(* your definition/proof here *)\n\ntext {*\nNow prove the summation formula by induction on @{text \"n\"}.\nFirst, write a clear but informal proof by hand following the examples\nin the main text. Then prove the same property in Isabelle:\n*}\n\nlemma \"sum_upto n = n * (n+1) div 2\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\nStarting from the type @{text \"'a tree\"} defined in the text, define\na function that collects all values in a tree in a list, in any order,\nwithout removing duplicates.\n*}\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n(* your definition/proof here *)\n\ntext{*\nThen define a function that sums up all values in a tree of natural numbers\n*}\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n(* your definition/proof here *)\n\ntext{* and prove *}\n\nlemma \"sum_tree t = sum_list(contents t)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a new type @{text \"'a tree2\"} of binary trees where values are also\nstored in the leaves of the tree.  Also reformulate the\n@{text mirror} function accordingly. Define two functions *}\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n(* your definition/proof here *)\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n(* your definition/proof here *)\n\ntext{*\nthat traverse a tree and collect all stored values in the respective order in\na list. Prove *}\n\nlemma \"pre_order (mirror t) = rev (post_order t)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a recursive function\n*}\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n(* your definition/proof here *)\n\ntext{*\nsuch that @{text \"intersperse a [x\\<^sub>1, ..., x\\<^sub>n] = [x\\<^sub>1, a, x\\<^sub>2, a, ..., a, x\\<^sub>n]\"}.\nProve\n*}\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\nWrite a tail-recursive variant of the @{text add} function on @{typ nat}:\n*}\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n(* your definition/proof here *)\n\ntext{*\nTail-recursive means that in the recursive case, @{const itadd} needs to call\nitself directly: \\mbox{@{term\"itadd (Suc m) n\"}} @{text\"= itadd \\<dots>\"}.\nProve\n*}\n\nlemma \"itadd m n = add m n\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:tree0}\nDefine a datatype @{text tree0} of binary tree skeletons which do not store\nany information, neither in the inner nodes nor in the leaves.\nDefine a function that counts the number of all nodes (inner nodes and leaves)\nin such a tree:\n*}\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n(* your definition/proof here *)\n\ntext {*\nConsider the following recursive function:\n*}\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\ntext {*\nExperiment how @{text explode} influences the size of a binary tree\nand find an equation expressing the size of a tree after exploding it\n(\\noquotes{@{term [source] \"nodes (explode n t)\"}}) as a function\nof @{term \"nodes t\"} and @{text n}. Prove your equation.\nYou may use the usual arithmetic operations including the exponentiation\noperator ``@{text\"^\"}''. For example, \\noquotes{@{prop [source] \"2 ^ 2 = 4\"}}.\n\nHint: simplifying with the list of theorems @{thm[source] algebra_simps}\ntakes care of common algebraic properties of the arithmetic operators.\n\\endexercise\n*}\n\ntext{*\n\n\\exercise\nDefine arithmetic expressions in one variable over integers (type @{typ int})\nas a data type:\n*}\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\ntext{*\nDefine a function @{text eval} that evaluates an expression at some value:\n*}\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n(* your definition/proof here *)\n\ntext{*\nFor example, @{prop\"eval (Add (Mult (Const 2) Var) (Const 3)) i = 2*i+3\"}.\n\nA polynomial can be represented as a list of coefficients, starting with\nthe constant. For example, @{term \"[4, 2, -1, 3::int]\"} represents the\npolynomial $4 + 2x - x^2 + 3x^3$.\nDefine a function @{text evalp} that evaluates a polynomial at a given value:\n*}\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n(* your definition/proof here *)\n\ntext{*\nDefine a function @{text coeffs} that transforms an expression into a polynomial.\nThis will require auxiliary functions.\n*}\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n(* your definition/proof here *)\n\ntext{*\nProve that @{text coeffs} preserves the value of the expression:\n*}\n\ntheorem evalp_coeffs: \"evalp (coeffs e) x = eval e x\"\n(* your definition/proof here *)\n\ntext{*\nHint: consider the hint in Exercise~\\ref{exe:tree0}.\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "brando90", "repo": "isabelle-gym", "sha": "f4d231cb9f625422e873aa2c9c2c6f22b7da4b27", "save_path": "github-repos/isabelle/brando90-isabelle-gym", "path": "github-repos/isabelle/brando90-isabelle-gym/isabelle-gym-f4d231cb9f625422e873aa2c9c2c6f22b7da4b27/isar_brandos_resources/templates/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.919642528975397, "lm_q2_score": 0.853912760387131, "lm_q1q2_score": 0.7852944904867833}}
{"text": "(*\n  File:     Fermat_Test.thy\n  Authors:  Daniel Stüwe, Manuel Eberl\n\n  The probabilistic prime test known as Fermat's test\n*)\nsection \\<open>Fermat's Test\\<close>\ntheory Fermat_Test\nimports \n  Fermat_Witness\n  Generalized_Primality_Test\nbegin\n\ndefinition \"fermat_test = primality_test (\\<lambda>n a. fermat_liar a n)\"\n\ntext \\<open>\n  The Fermat test is a good probabilistic primality test on non-Carmichael numbers.\n\\<close>\nlocale fermat_test_not_Carmichael_number =\n  fixes n :: nat\n  assumes not_Carmichael_number: \"\\<not>Carmichael_number n \\<or> n < 3\"\nbegin\n\nsublocale fermat_test: good_prob_primality_test \"\\<lambda>a n. fermat_liar n a\" n \"1 / 2\"\n  rewrites \"primality_test (\\<lambda> a n. fermat_liar n a) = fermat_test\"\nproof -\n  show \"good_prob_primality_test (\\<lambda>a n. fermat_liar n a) n (1 / 2)\"\n    using not_Carmichael_number not_Carmichael_number_imp_card_fermat_witness_bound(3)[of n]\n          prime_imp_fermat_liar[of n]\n    by unfold_locales auto\nqed (auto simp: fermat_test_def)\n\nend\n\nlemma not_coprime_imp_fermat_witness:\n  fixes n :: nat\n  assumes \"n > 1\" \"\\<not>coprime a n\"\n  shows   \"fermat_witness a n\"\n  using assms lucas_coprime_lemma[of \"n - 1\" a n]\n  by (auto simp: fermat_witness_def)\n\ntheorem fermat_test_prime:\n  assumes \"prime n\"\n  shows   \"fermat_test n = return_pmf True\"\nproof -\n  interpret fermat_test_not_Carmichael_number n\n    using assms Carmichael_number_not_prime by unfold_locales auto\n  from assms show ?thesis by (rule fermat_test.prime)\nqed\n\ntheorem fermat_test_composite:\n  assumes \"\\<not>prime n\" \"\\<not>Carmichael_number n \\<or> n < 3\"\n  shows   \"pmf (fermat_test n) True < 1 / 2\"\nproof -\n  interpret fermat_test_not_Carmichael_number n by unfold_locales fact+\n  from assms(1) show ?thesis by (rule fermat_test.composite)\nqed\n\ntext \\<open>\n  For a Carmichael number $n$, Fermat's test as defined above mistakenly returns `True'\n  with probability $(\\varphi(n)-1) / (n - 2)$. This probability is close to 1 if \\<open>n\\<close>\n  has few and big prime factors; it is not quite as bad if it has many and/or small factors,\n  but in that case, simple trial division can also detect compositeness.\n\n  Moreover, Fermat's test only succeeds for a Carmichael number if it happens to guess a\n  number that is not coprime to \\<open>n\\<close>. In that case, the fact that we have found\n  a number between 2 and \\<open>n\\<close> that is not coprime to \\<open>n\\<close> alone is \n  proof that \\<open>n\\<close> is composite, and indeed we can even find a non-trivial factor\n  by computing the GCD. This means that for Carmichael numbers, Fermat's test is essentially\n  no better than the very crude method of attempting to guess numbers coprime to \\<open>n\\<close>.\n\n  This means that, in general, Fermat's test is not very helpful for Carmichael numbers.\n\\<close>\ntheorem fermat_test_Carmichael_number:\n  assumes \"Carmichael_number n\"\n  shows   \"fermat_test n = bernoulli_pmf (real (totient n - 1) / real (n - 2))\"\nproof (rule eq_bernoulli_pmfI)\n  from assms have n: \"n > 3\" \"odd n\"\n    using Carmichael_number_odd Carmichael_number_gt_3 by auto\n  from n have \"fermat_test n = pmf_of_set {2..<n} \\<bind> (\\<lambda>a. return_pmf (fermat_liar a n))\"\n    by (simp add: fermat_test_def primality_test_def)\n  also have \"\\<dots> = pmf_of_set {2..<n} \\<bind> (\\<lambda>a. return_pmf (coprime a n))\"\n    using n assms lucas_coprime_lemma[of \"n - 1\" _ n]\n    by (intro bind_pmf_cong refl) (auto simp: Carmichael_number_def fermat_liar_def)\n  also have \"pmf \\<dots> True = (\\<Sum>a=2..<n. indicat_real {True} (coprime a n)) / real (n - 2)\"\n    using n by (auto simp: pmf_bind_pmf_of_set)\n  also have \"(\\<Sum>a=2..<n. indicat_real {True} (coprime a n)) =\n               (\\<Sum>a | a \\<in> {2..<n} \\<and> coprime a n. 1)\"\n    by (intro sum.mono_neutral_cong_right) auto\n  also have \"\\<dots> = card {a\\<in>{2..<n}. coprime a n}\"\n    by simp\n  also have \"{a\\<in>{2..<n}. coprime a n} = totatives n - {1}\"\n    using n by (auto simp: totatives_def order.strict_iff_order[of _ n])\n  also have \"card \\<dots> = totient n - 1\"\n    using n by (subst card_Diff_subset) (auto simp: totient_def)\n  finally show \"pmf (fermat_test n) True = real (totient n - 1) / real (n - 2)\"\n    using n by simp\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Probabilistic_Prime_Tests/Fermat_Test.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.7852096924965297}}
{"text": "theory \"EWD-pairings\"\n  imports Main HOL.Real HOL.NthRoot \"./TLA-Utils\" \"HOL-Analysis.Product_Vector\"\nbegin\n\ntype_synonym point = \"real \\<times> real\"\n\ndefinition lineseg :: \"point \\<Rightarrow> point \\<Rightarrow> real \\<Rightarrow> point\"\n  where \"lineseg p0 p1 l \\<equiv> (1-l) *\\<^sub>R p0 + l *\\<^sub>R p1\"\n\ndefinition closed_01 :: \"real set\"\n  where \"closed_01 \\<equiv> {x. 0 \\<le> x \\<and> x \\<le> 1}\"\n\ndefinition segment_between :: \"point \\<Rightarrow> point \\<Rightarrow> point set\"\n  where \"segment_between p0 p1 \\<equiv> lineseg p0 p1 ` closed_01\"\n\ndefinition segments_cross :: \"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> bool\"\n  where \"segments_cross r0 b0 r1 b1 \\<equiv> segment_between r0 b0 \\<inter> segment_between r1 b1 \\<noteq> {}\"\n\nlemma segment_between_subset: \"segment_between p1 p0 \\<subseteq> segment_between p0 p1\"\nproof (intro subsetI)\n  fix p assume \"p \\<in> segment_between p1 p0\"\n  then obtain lp where p: \"p = lineseg p1 p0 lp\" and lp: \"lp \\<in> closed_01\" unfolding segment_between_def by auto\n  show \"p \\<in> segment_between p0 p1\"\n    unfolding p segment_between_def using lp\n    by (intro image_eqI [where x = \"1 - lp\"], auto simp add: lineseg_def closed_01_def)\nqed\n\nlemma segment_between_swap[simp]: \"segment_between p1 p0 = segment_between p0 p1\"\n  by (intro equalityI segment_between_subset)\n\nlemma segments_cross_swaps[simp]:\n  \"segments_cross b0 r0 r1 b1 = segments_cross r0 b0 r1 b1\" \n  \"segments_cross r0 b0 b1 r1 = segments_cross r0 b0 r1 b1\" \n  \"segments_cross r1 b1 r0 b0 = segments_cross r0 b0 r1 b1\"\n  by (auto simp add: segments_cross_def)\n\ndefinition signedArea :: \"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> real\"\n  where \"signedArea p0 p1 p2 \\<equiv> case (p0, p1, p2) of\n    ((x0,y0), (x1,y1), (x2,y2)) \\<Rightarrow> ((x1-x0)*(y2-y0) - (x2-x0)*(y1-y0))\"\n\nlemma signedArea_left_example:  \"signedArea (0,0) (1,0) (1, 1) > 0\" by (simp add: signedArea_def)\nlemma signedArea_right_example: \"signedArea (0,0) (1,0) (1,-1) < 0\" by (simp add: signedArea_def)\n\ndatatype Turn = Left | Right | Collinear\n\ndefinition turn :: \"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> Turn\"\n  where \"turn p0 p1 p2 \\<equiv> if 0 < signedArea p0 p1 p2 then Left else if signedArea p0 p1 p2 < 0 then Right else Collinear\"\n\nlemma signedArea_swap: \"signedArea p0 p2 p1 = - signedArea p0 p1 p2\"\n  by (cases p0, cases p1, cases p2, simp add: signedArea_def)\n\nlemma signedArea_rotate1[simp]: \"signedArea p0 p1 p2 = signedArea p1 p2 p0\"\n  unfolding signedArea_def\n  by (cases p0, cases p1, cases p2, simp add: left_diff_distrib right_diff_distrib)\n\nlemma signedArea_rotate2[simp]: \"signedArea p0 p1 p2 = signedArea p2 p0 p1\" by simp\n\nlemma signedArea_trivial[simp]: \"signedArea p0 p0 p1 = 0\" \"signedArea p0 p1 p0 = 0\" \"signedArea p0 p1 p1 = 0\"\n  unfolding signedArea_def by (cases p0, cases p1, simp)+\n\nlemma turn_swap: \"turn p0 p2 p1 = (case turn p0 p1 p2 of Left \\<Rightarrow> Right | Right \\<Rightarrow> Left | Collinear \\<Rightarrow> Collinear)\"\n  using signedArea_swap [of p0 p1 p2] unfolding turn_def by simp\n\nlemma turn_Left:      \"(turn p0 p1 p2 = Left)      = (0 < signedArea p0 p1 p2)\"\n  and turn_Right:     \"(turn p0 p1 p2 = Right)     = (signedArea p0 p1 p2 < 0)\"\n  and turn_Collinear: \"(turn p0 p1 p2 = Collinear) = (signedArea p0 p1 p2 = 0)\"\n  by (auto simp add: turn_def linorder_less_linear [of \"signedArea p0 p1 p2\" 0])\n\nlemma turn_trivial[simp]: \"turn p0 p0 p1 = Collinear\" \"turn p0 p1 p0 = Collinear\" \"turn p0 p1 p1 = Collinear\"\n  unfolding turn_def by simp_all\n\ndefinition collinear :: \"point set \\<Rightarrow> bool\"\n  where \"collinear ps \\<equiv> \\<forall> p0 p1 p2. {p0, p1, p2} \\<subseteq> ps \\<longrightarrow> turn p0 p1 p2 = Collinear\"\n\nlemma collinear_singleton[simp]: \"collinear {p}\" by (simp add: collinear_def)\nlemma collinear_doubleton[simp]: \"collinear {p0,p1}\" by (auto simp add: collinear_def)\nlemma collinear_tripleton: \"collinear {p0,p1,p2} = (turn p0 p1 p2 = Collinear)\"\n  unfolding collinear_def\n  by (metis empty_iff insert_iff insert_subset order_refl signedArea_rotate2 turn_Collinear turn_swap turn_trivial(1))\n\nlemma collinearI[intro]:\n  assumes \"\\<And>p0 p1 p2. p0 \\<in> ps \\<Longrightarrow> p1 \\<in> ps \\<Longrightarrow> p2 \\<in> ps \\<Longrightarrow> turn p0 p1 p2 = Collinear\"\n  shows \"collinear ps\"\n  using assms unfolding collinear_def by auto\n\nlemma collinear_subset: \"ps \\<subseteq> qs \\<Longrightarrow> collinear qs \\<Longrightarrow> collinear ps\" unfolding collinear_def by fastforce\n\nlemma turn_rotate1[simp]: \"turn p0 p1 p2 = turn p1 p2 p0\" unfolding turn_def by simp\n\nlemma Collinear_lineseg:\n  assumes \"turn p0 p1 q = Collinear\"\n  assumes \"p0 \\<noteq> p1\"\n  shows \"q \\<in> range (lineseg p0 p1)\"\nproof -\n  obtain x0 y0 x1 y1 x y where p0: \"p0 = (x0,y0)\" and p1: \"p1 = (x1,y1)\" and q: \"q = (x,y)\" by fastforce\n\n  from assms have gradient_eq: \"(x1-x0)*(y-y0) = (x-x0)*(y1-y0)\" unfolding turn_Collinear signedArea_def by (auto simp add: p0 p1 q)\n\n  define l where \"l \\<equiv> if x1 = x0 then (y-y0) / (y1-y0) else (x-x0) / (x1-x0)\"\n\n  have xl: \"(x1-x0) * l = (x-x0)\" using assms gradient_eq by (auto simp add: l_def p0 p1)\n  have yl: \"(y1-y0) * l = (y-y0)\" using assms gradient_eq\n    apply (auto simp add: l_def p0 p1)\n    by (metis eq_iff_diff_eq_0 linordered_field_class.sign_simps(24) nonzero_mult_div_cancel_left)+\n\n  from xl yl have \"q - p0 = l *\\<^sub>R (p1 - p0)\" by (auto simp add: p0 p1 q mult.commute)\n  thus ?thesis\n    apply (intro image_eqI [where x = l], auto simp add: lineseg_def)\n    by (smt add.assoc add.commute diff_add_cancel real_vector.scale_right_diff_distrib scaleR_collapse)\nqed\n\nlemma lineseg_collinear:\n  assumes \"collinear ps\"\n  assumes \"p1 \\<in> ps\" \"p2 \\<in> ps\" \"p1 \\<noteq> p2\"\n  shows \"ps \\<subseteq> range (lineseg p1 p2)\"\nproof (intro subsetI)\n  fix p3 assume \"p3 \\<in> ps\"\n  with assms have \"turn p1 p2 p3 = Collinear\" unfolding collinear_def by blast\n  with assms show \"p3 \\<in> range (lineseg p1 p2)\" by (metis Collinear_lineseg)\nqed\n\nlemma collinear_lineseg: \"collinear (range (lineseg p0 p1))\"\nproof (intro collinearI, elim imageE, simp)\n  fix la lb lc\n  show \"turn (lineseg p0 p1 la) (lineseg p0 p1 lb) (lineseg p0 p1 lc) = Collinear\"\n    by (cases p0, cases p1, auto simp add: turn_Collinear lineseg_def signedArea_def left_diff_distrib right_diff_distrib distrib_left distrib_right)\nqed\n\nlemma collinear_insert:\n  assumes \"p \\<in> range (lineseg p0 p1)\"\n  assumes \"p0 \\<in> ps\" \"p1 \\<in> ps\"\n  assumes \"collinear ps\"\n  shows \"collinear (insert p ps)\"\nproof (cases \"p0 = p1\")\n  case True with assms show ?thesis by (auto simp add: lineseg_def insert_absorb)\nnext\n  case False\n  have \"ps \\<subseteq> range (lineseg p0 p1)\" by (intro lineseg_collinear assms False)\n  with assms have \"insert p ps \\<subseteq> range (lineseg p0 p1)\" by auto\n  from collinear_subset [OF this collinear_lineseg] show ?thesis by simp\nqed\n\nlemma range_lineseg_p0:\n  \"p0 \\<in> range (lineseg p0 p1)\" by (intro image_eqI [where x = 0], auto simp add: lineseg_def)\n\nlemma range_lineseg_p1:\n  \"p1 \\<in> range (lineseg p0 p1)\" by (intro image_eqI [where x = 1], auto simp add: lineseg_def)\n\nlemma lineseg_Collinear:\n  assumes \"q \\<in> range (lineseg p0 p1)\"\n  shows \"turn p0 p1 q = Collinear\"\n  using range_lineseg_p0 range_lineseg_p1 assms collinear_lineseg unfolding collinear_def by blast\n\nlemma Collinear_trans:\n  assumes pq: \"p \\<noteq> q\"\n  assumes pqr: \"turn p q r = Collinear\"\n  assumes pqs: \"turn p q s = Collinear\"\n  shows \"turn p r s = Collinear\"\nproof -\n  from Collinear_lineseg [OF pqr pq] obtain lr where lr: \"r = lineseg p q lr\" by auto\n  from Collinear_lineseg [OF pqs pq] obtain ls where ls: \"s = lineseg p q ls\" by auto\n\n  from lr show ?thesis\n  proof (cases \"lr = 0\")\n    case False\n    thus ?thesis\n      apply (intro lineseg_Collinear image_eqI [where x = \"ls/lr\"])\n      apply (auto simp add: lineseg_def lr ls)\n      by (smt add.assoc add_diff_cancel_left' add_diff_eq eq_vector_fraction_iff real_vector.scale_left_commute scaleR_add_right scaleR_collapse)\n  qed (simp add: lineseg_def)\nqed\n\nlemma collinear_union:\n  assumes \"collinear (ps \\<union> qs)\"\n  assumes \"collinear (ps \\<union> rs)\"\n  assumes \"p1 \\<in> ps\" \"p2 \\<in> ps\" \"p1 \\<noteq> p2\"\n  shows \"collinear (ps \\<union> qs \\<union> rs)\"\nproof -\n  from assms have 1: \"ps \\<union> qs \\<subseteq> range (lineseg p1 p2)\" by (intro lineseg_collinear, auto)\n  from assms have 2: \"ps \\<union> rs \\<subseteq> range (lineseg p1 p2)\" by (intro lineseg_collinear, auto)\n  from 1 2 have 3: \"ps \\<union> qs \\<union> rs \\<subseteq> range (lineseg p1 p2)\" by auto\n  show ?thesis by (intro collinear_subset [OF 3] collinear_lineseg)\nqed\n\nlemma signedArea_lineseg: \"signedArea r0 b0 (lineseg r1 b1 l) = (1-l) * signedArea r0 b0 r1 + l * signedArea r0 b0 b1\"\n  unfolding signedArea_def lineseg_def\n  by (cases r0, cases b0, cases r1, cases b1, simp add: left_diff_distrib right_diff_distrib distrib_left distrib_right)\n\nlemma collinear_lineseg_subset:\n  assumes \"r0 \\<noteq> b0\"\n  assumes \"collinear {r0, b0, r1, b1}\"\n  shows \"range (lineseg r1 b1) \\<subseteq> range (lineseg r0 b0)\"\nproof (intro subsetI)\n  fix q assume \"q \\<in> range (lineseg r1 b1)\"\n  then obtain lq where q: \"q = lineseg r1 b1 lq\" by auto\n\n  have \"{r0, b0, r1, b1} \\<subseteq> range (lineseg r0 b0)\" by (intro lineseg_collinear assms, auto)\n  then obtain lq0 lq1 where q0: \"r1 = lineseg r0 b0 lq0\" and q1: \"b1 = lineseg r0 b0 lq1\" by auto\n\n  show \"q \\<in> range (lineseg r0 b0)\"\n    by (intro image_eqI [where x = \"lq * lq1 + (1-lq) * lq0\"],\n        simp_all add: q q0 q1 lineseg_def scaleR_diff_left left_diff_distrib scaleR_add_right scaleR_diff_right scaleR_add_left)\nqed\n\nlemma turns_segments_cross:\n  assumes \"turn r0 b0 r1 \\<noteq> turn r0 b0 b1\"\n  assumes \"turn r1 b1 r0 \\<noteq> turn r1 b1 b0\"\n  shows \"segments_cross r0 b0 r1 b1\"\nproof -\n  define sr1 sb1 sr0 sb0 where s_defs:\n    \"sr1 \\<equiv> signedArea r0 b0 r1\"\n    \"sb1 \\<equiv> signedArea r0 b0 b1\"\n    \"sr0 \\<equiv> signedArea r1 b1 r0\"\n    \"sb0 \\<equiv> signedArea r1 b1 b0\"\n\n  from assms have s_ne: \"sr1 \\<noteq> sb1\" \"sr0 \\<noteq> sb0\" unfolding s_defs turn_def by smt+\n\n  define l1 where \"l1 \\<equiv> sr1 / (sr1 - sb1)\"\n\n  have \"signedArea r0 b0 (lineseg r1 b1 l1) = (1 - l1) * sr1 + l1 * sb1\" unfolding signedArea_lineseg by (simp add: s_defs)\n  also have \"\\<dots> = sr1 - l1 * (sr1 - sb1)\" by (simp add: left_diff_distrib right_diff_distrib)\n  also have \"\\<dots> = 0\" using s_ne by (auto simp add: l1_def)\n  finally have lq_range: \"lineseg r1 b1 l1 \\<in> range (lineseg r0 b0)\"\n    using assms by (intro Collinear_lineseg iffD2 [OF turn_Collinear] notI, simp_all)\n  then obtain l0 where l0: \"lineseg r1 b1 l1 = lineseg r0 b0 l0\" by auto\n\n  have \"0 = signedArea r1 b1 (lineseg r1 b1 l1)\" unfolding signedArea_lineseg by simp\n  also have \"\\<dots> = signedArea r1 b1 (lineseg r0 b0 l0)\" by (simp add: l0)\n  also have \"\\<dots> = (1 - l0) * sr0 + l0 * sb0\" unfolding signedArea_lineseg by (simp add: s_defs)\n  also have \"\\<dots> = sr0 - l0 * (sr0 - sb0)\" by (simp add: left_diff_distrib right_diff_distrib)\n  finally have l0_def: \"l0 = sr0 / (sr0 - sb0)\"\n    using s_ne nonzero_eq_divide_eq by smt\n\n  have nonemptyI: \"\\<And>a S. a \\<in> S \\<Longrightarrow> S \\<noteq> {}\" by auto\n\n  show ?thesis\n    unfolding segments_cross_def segment_between_def\n  proof (intro nonemptyI IntI image_eqI)\n    from l0 show \"lineseg r1 b1 l1 = lineseg r0 b0 l0\".\n\n    from assms have \"0 \\<le> l1 \\<and> l1 \\<le> 1 \\<and> 0 \\<le> l0 \\<and> l0 \\<le> 1\"\n      unfolding l0_def l1_def s_defs turn_def\n      by (smt divide_le_eq_1 divide_nonneg_nonneg divide_nonpos_nonpos)\n    thus \"l0 \\<in> closed_01\" \"l1 \\<in> closed_01\" unfolding closed_01_def by auto\n  qed simp\nqed\n\nlemma Left_Left_not_segments_cross:\n  assumes \"turn r0 b0 r1 = Left\"\n  assumes \"turn r0 b0 b1 = Left\"\n  shows \"\\<not> segments_cross r0 b0 r1 b1\"\nproof (intro notI)\n  assume \"segments_cross r0 b0 r1 b1\"\n  then obtain l0 l1 where l1: \"l1 \\<in> closed_01\" and l0_l1: \"lineseg r0 b0 l0 = lineseg r1 b1 l1\"\n    unfolding segments_cross_def segment_between_def by fastforce\n\n  have \"0 = signedArea r0 b0 (lineseg r0 b0 l0)\" unfolding signedArea_lineseg by simp\n  also have \"\\<dots> = signedArea r0 b0 (lineseg r1 b1 l1)\" by (simp add: l0_l1)\n  also have \"\\<dots> = (1-l1) * signedArea r0 b0 r1 + l1 * signedArea r0 b0 b1\" unfolding signedArea_lineseg by simp\n  also have \"\\<dots> > 0\" using assms l1 unfolding turn_Left closed_01_def by (auto, smt mult_nonneg_nonneg no_zero_divisors)\n  finally show False by simp\nqed\n\nlemma Right_Right_not_segments_cross:\n  assumes \"turn r0 b0 r1 = Right\"\n  assumes \"turn r0 b0 b1 = Right\"\n  shows \"\\<not> segments_cross r0 b0 r1 b1\"\nproof -\n  from assms have \"turn b0 r0 r1 = Left\" \"turn b0 r0 b1 = Left\"\n    using turn_swap by (metis Turn.simps(8) turn_rotate1)+\n  hence \"\\<not> segments_cross b0 r0 r1 b1\" by (intro Left_Left_not_segments_cross)\n  thus ?thesis by simp\nqed\n\nlemma card_4_or_not_distinct: \"card {a,b,c,d} = 4 \\<or> a = b \\<or> a = c \\<or> a = d \\<or> b = c \\<or> b = d \\<or> c = d\"\n  using n_not_Suc_n by fastforce\n\nlemma segments_cross_turns:\n  assumes \"segments_cross r0 b0 r1 b1\"\n  shows \"collinear {r0, b0, r1, b1} \\<or> (turn r0 b0 r1 \\<noteq> turn r0 b0 b1 \\<and> turn r1 b1 r0 \\<noteq> turn r1 b1 b0)\"\nproof (intro disjCI)\n  assume \"\\<not> (turn r0 b0 r1 \\<noteq> turn r0 b0 b1 \\<and> turn r1 b1 r0 \\<noteq> turn r1 b1 b0)\"\n  then consider\n    \"turn r0 b0 r1 = Left\"      \"turn r0 b0 b1 = Left\"\n    | (CC0) \"turn r0 b0 r1 = Collinear\" \"turn r0 b0 b1 = Collinear\"\n    |       \"turn r0 b0 r1 = Right\"     \"turn r0 b0 b1 = Right\"\n    |       \"turn r1 b1 r0 = Left\"      \"turn r1 b1 b0 = Left\"\n    | (CC1) \"turn r1 b1 r0 = Collinear\" \"turn r1 b1 b0 = Collinear\" \"turn r0 b0 r1 \\<noteq> turn r0 b0 b1\"\n    |       \"turn r1 b1 r0 = Right\"     \"turn r1 b1 b0 = Right\"\n    apply auto by (metis Turn.exhaust)+\n  from this assms Left_Left_not_segments_cross Right_Right_not_segments_cross segments_cross_swaps(3)\n  show \"collinear {r0, b0, r1, b1}\"\n  proof cases\n    case CC1 with assms have ne: \"r1 \\<noteq> b1\" by blast\n    from ne CC1 have \"turn r1 r0 b0 = Collinear\" by (metis Collinear_trans)\n    moreover from CC1 have \"turn b1 r1 r0 = Collinear\" \"turn b1 r1 b0 = Collinear\"\n      by (smt Collinear_trans turn_rotate1)+\n    with ne have \"turn b1 r0 b0 = Collinear\" by (metis Collinear_trans)\n    ultimately show ?thesis using CC1 by (metis turn_rotate1)\n  next\n    case CC0\n    hence p: \"collinear ({r0,b0} \\<union> {r1})\" \"collinear ({r0,b0} \\<union> {b1})\"\n       apply (simp_all add: collinear_tripleton) by (metis turn_rotate1)\n\n    from card_4_or_not_distinct [of r0 b0 r1 b1] p\n    have \"collinear ({r0,b0} \\<union> {r1} \\<union> {b1})\"\n    proof (elim disjE)\n      assume 4: \"card {r0, b0, r1, b1} = 4\"\n      have card_ne_4: \"\\<And>a b c. card {a,b,c} \\<noteq> 4\" by (simp add: card_insert_if)\n      show ?thesis using CC0 4 by (intro collinear_union [of _ _ _ r0 b0] p, auto simp add: card_ne_4)\n    next\n      assume eq: \"r0 = b0\"\n      hence segment_between_p1: \"segment_between r0 b0 = {b0}\" by (auto simp add: segment_between_def lineseg_def closed_01_def image_def)\n      with assms obtain l where l: \"b0 = lineseg r1 b1 l\"\n        by (smt disjoint_iff_not_equal image_iff segment_between_def segments_cross_def singletonD)\n      thus ?thesis\n        by (intro collinear_subset [OF _ collinear_lineseg], auto simp add: range_lineseg_p0 range_lineseg_p1 eq)\n    qed (simp_all add: insert_commute)\n    thus ?thesis by (simp add: insert_commute)\n  qed blast+\nqed\n\nlemma dist_lineseg: \"dist (lineseg p0 p1 la) (lineseg p0 p1 lb) = \\<bar>lb-la\\<bar> * dist p0 p1\"\nproof -\n  have [simp]: \"\\<bar>lb-la\\<bar> = \\<bar>la-lb\\<bar>\" by simp\n  have \"dist (lineseg p0 p1 la) (lineseg p0 p1 lb) = norm ((lb - la) *\\<^sub>R (p0 - p1))\"\n    unfolding dist_norm lineseg_def\n    by (intro cong [OF refl, where f = norm], simp add: scaleR_diff_left scaleR_diff_right)\n  also have \"\\<dots> = \\<bar>lb-la\\<bar> * dist p0 p1\" by (simp add: dist_norm)\n  finally show ?thesis .\nqed\n\nlemma dist_split:\n  assumes \"l \\<in> closed_01\"\n  shows \"dist p0 p1 = dist p0 (lineseg p0 p1 l) + dist (lineseg p0 p1 l) p1\"\nproof -\n  from assms have 1: \"\\<bar>l\\<bar> + \\<bar>1-l\\<bar> = 1\" unfolding closed_01_def by auto\n\n  have \"dist p0 (lineseg p0 p1 l) = dist (lineseg p0 p1 0) (lineseg p0 p1 l)\" by (simp add: lineseg_def)\n  also note dist_lineseg\n  finally have 2: \"dist p0 (lineseg p0 p1 l) = \\<bar>l\\<bar> * dist p0 p1\" by simp\n\n  have \"dist (lineseg p0 p1 l) p1 = dist (lineseg p0 p1 l) (lineseg p0 p1 1)\" by (simp add: lineseg_def)\n  also note dist_lineseg\n  finally have 3: \"dist (lineseg p0 p1 l) p1 = \\<bar>1-l\\<bar> * dist p0 p1\" by simp\n\n  have \"dist p0 (lineseg p0 p1 l) + dist (lineseg p0 p1 l) p1 = (\\<bar>l\\<bar> + \\<bar>1-l\\<bar>) * dist p0 p1\"\n    by (simp add: 2 3 distrib_right)\n  thus ?thesis by (simp add: 1)\nqed\n\nlemma Collinear_dist:\n  assumes \"dist p0 p1 = dist p0 p2 + dist p2 p1\"\n  shows \"collinear {p0, p1, p2}\"\nproof (cases \"p0 = p1\")\n  case True thus ?thesis by simp\nnext\n  case False\n\n  define par where \"par \\<equiv> p1 - p0\"\n  define perp where \"perp \\<equiv> (case par of (dx, dy) \\<Rightarrow> (dy, -dx))\"\n\n  from False have inner_par_par_positive: \"0 < inner par par\" unfolding par_def by auto\n\n  have  perp_is_perp1[simp]: \"inner perp par = 0\" by (cases par, simp add: perp_def)\n  hence perp_is_perp2[simp]: \"inner par perp = 0\" by (simp add: inner_commute)\n  have inner_perp_perp[simp]: \"inner perp perp = inner par par\" by (cases par, simp add: perp_def)\n\n  have dist_norm_par: \"dist p0 p1 = norm par\" unfolding par_def by (metis dist_commute dist_norm)\n\n  define p02 where \"p02 \\<equiv> p2 - p0\"\n\n  have inner_par_p02_commute[simp]: \"inner par p02 = inner p02 par\" by (simp add: inner_commute)\n\n  define lpar  where \"lpar  \\<equiv> inner p02 par  / inner par par\"\n  define lperp where \"lperp \\<equiv> inner p02 perp / inner par par\"\n\n  have \"inner par par *\\<^sub>R p02 = inner p02 par *\\<^sub>R par + inner p02 perp *\\<^sub>R perp\"\n    by (cases par, cases p02, simp add: perp_def distrib_left distrib_right left_diff_distrib)\n  hence p02_components: \"p02 = lpar *\\<^sub>R par + lperp *\\<^sub>R perp\"\n    unfolding lpar_def lperp_def\n    using inner_par_par_positive\n    by (smt divide_inverse_commute left_inverse real_vector.scale_scale scaleR_collapse scaleR_left_distrib scaleR_right.add)\n\n  show ?thesis\n  proof (cases \"lperp = 0\")\n    case True\n    hence \"p02 = lpar *\\<^sub>R par\" by (simp add: p02_components)\n    hence p2_eq: \"p2 = lineseg p0 p1 lpar\" apply (simp add: p02_def lineseg_def par_def)\n      by (smt ab_semigroup_add_class.add_ac(1) add.commute diff_add_cancel real_vector.scale_right_diff_distrib scaleR_collapse)\n\n    show ?thesis unfolding collinear_tripleton by (intro lineseg_Collinear, simp add: p2_eq)\n  next\n\n    case offline: False\n\n    have pythagoras0: \"inner p02 p02 = (lpar * lpar + lperp * lperp) * inner par par\"\n      unfolding p02_components by (simp add: inner_add_left inner_add_right distrib_right)\n\n    define p12 where \"p12 \\<equiv> p2 - p1\"\n    have p12_eq: \"p12 = p02 - par\" by (simp add: p02_def par_def p12_def)\n\n    have p12_components: \"p12 = (lpar - 1) *\\<^sub>R par + lperp *\\<^sub>R perp\" unfolding p12_eq p02_components by (simp add: scaleR_left.diff)\n\n    have pythagoras1: \"inner p12 p12 = ((lpar - 1) * (lpar - 1) + lperp * lperp) * inner par par\"\n      unfolding p12_components by (simp add: inner_add_left inner_add_right distrib_right)\n\n    have \"lpar * dist p1 p0 \\<le> sqrt ((lpar * dist p1 p0)\\<^sup>2)\" by simp\n    also have \"\\<dots> = sqrt (lpar * lpar * inner par par)\"\n      by (intro cong [OF refl, where f = sqrt], simp add: power2_eq_square par_def dist_norm dot_square_norm)\n    also have \"\\<dots> < sqrt (inner p02 p02)\"\n      apply (intro real_sqrt_less_mono, simp add: pythagoras0 distrib_right)\n      using inner_par_par_positive mult_pos_pos not_real_square_gt_zero offline by blast\n    also have \"\\<dots> = dist p2 p0\" by (simp add: p02_def dist_norm norm_eq_sqrt_inner)\n    finally have d02: \"lpar * dist p1 p0 < dist p0 p2\" by (simp add: dist_commute)\n\n    have p: \"(lpar-1) * (lpar-1) = (1-lpar) * (1-lpar)\" by (auto simp add: left_diff_distrib right_diff_distrib)\n\n    have \"(1-lpar) * dist p1 p0 \\<le> sqrt (((1-lpar) * dist p1 p0)\\<^sup>2)\" by simp\n    also have \"\\<dots> = sqrt ((1-lpar) * (1-lpar) * inner par par)\"\n      by (intro cong [OF refl, where f = sqrt], simp add: power2_eq_square par_def dist_norm dot_square_norm)\n    also have \"\\<dots> = sqrt ((lpar-1) * (lpar-1) * inner par par)\" by (simp add: p)\n    also have \"\\<dots> < sqrt (inner p12 p12)\"\n      apply (intro real_sqrt_less_mono, simp add: pythagoras1 distrib_right)\n      using inner_par_par_positive mult_pos_pos not_real_square_gt_zero offline by blast\n    also have \"\\<dots> = dist p2 p1\" by (simp add: p12_def dist_norm norm_eq_sqrt_inner)\n    finally have d12: \"(1 - lpar) * dist p1 p0 < dist p1 p2\" by (simp add: dist_commute)\n\n    have \"dist p1 p0 = lpar * dist p1 p0 + (1 - lpar) * dist p1 p0\" by (auto simp add: left_diff_distrib)\n    also from d02 d12 have \"\\<dots> < dist p0 p2 + dist p1 p2\" by auto\n    also from assms have \"\\<dots> = dist p1 p0\" by (simp add: dist_commute)\n    finally show ?thesis by simp\n  qed\nqed\n\nlemma non_collinear_swap_decreases_length:\n  assumes distinct:       \"r0 \\<noteq> r1\" \"b0 \\<noteq> b1\"\n  assumes distinct_turns: \"turn r0 b0 r1 \\<noteq> turn r0 b0 b1\"\n                          \"turn r1 b1 r0 \\<noteq> turn r1 b1 b0\"\n  shows \"dist r0 b1 + dist r1 b0 < dist r0 b0 + dist r1 b1\"\nproof -\n  have segments_cross: \"segments_cross r0 b0 r1 b1\" by (intro turns_segments_cross assms)\n  then obtain lp lq pq where pq_lp: \"pq = lineseg r0 b0 lp\" and pq_lq: \"pq = lineseg r1 b1 lq\"\n    and lp: \"lp \\<in> closed_01\" and lq: \"lq \\<in> closed_01\"\n    unfolding segments_cross_def segment_between_def by blast\n\n  have \"dist r0 pq + dist pq b1 + dist r1 pq + dist pq b0\n     = dist r0 (lineseg r0 b0 lp) + dist (lineseg r0 b0 lp) b0 + dist r1 (lineseg r1 b1 lq) + dist (lineseg r1 b1 lq) b1\" using pq_lp pq_lq by simp\n  also have \"\\<dots> = dist r0 b0 + dist r1 b1\" using dist_split [OF lp, of r0 b0] dist_split [OF lq, of r1 b1] by simp\n  finally have \"dist r0 pq + dist pq b1 + dist r1 pq + dist pq b0 = dist r0 b0 + dist r1 b1\" .\n\n  moreover have \"dist r0 b1 \\<le> dist r0 pq + dist pq b1\" using dist_triangle.\n  moreover have \"dist r1 b0 \\<le> dist r1 pq + dist pq b0\" using dist_triangle.\n\n  moreover have \"dist r0 b1 \\<noteq> dist r0 pq + dist pq b1 \\<or> dist r1 b0 \\<noteq> dist r1 pq + dist pq b0\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence p0q1: \"dist r0 b1 = dist r0 pq + dist pq b1\" and q0p1: \"dist r1 b0 = dist r1 pq + dist pq b0\" by simp_all\n\n    have p0_p1_pq: \"collinear {r0, b0, pq}\" unfolding collinear_tripleton using pq_lp by (intro lineseg_Collinear, simp)\n    have q0_q1_pq: \"collinear {r1, b1, pq}\" unfolding collinear_tripleton using pq_lq by (intro lineseg_Collinear, simp)\n\n    have p0_q1_pq: \"collinear {r0, b1, pq}\" using p0q1 by (intro Collinear_dist)\n    have q0_p1_pq: \"collinear {r1, b0, pq}\" using q0p1 by (intro Collinear_dist)\n\n    have p0_pq: \"r0 \\<noteq> pq\"\n    proof (intro notI)\n      assume eq: \"r0 = pq\"\n      from assms have \"collinear ({r0,r1} \\<union> {b1} \\<union> {b0})\"\n      proof (intro collinear_union [of _ _ _ r0 r1])\n        from eq have \"{r1, b1, pq} = {r0, r1} \\<union> {b1}\" \"{r1, b0, pq} = {r0, r1} \\<union> {b0}\" by auto\n        with q0_q1_pq q0_p1_pq show \"collinear ({r0, r1} \\<union> {b1})\" \"collinear  ({r0, r1} \\<union> {b0})\" by simp_all\n      qed simp_all\n      with assms show False unfolding collinear_def by auto\n    qed\n\n    have q0_pq: \"r1 \\<noteq> pq\"\n    proof (intro notI)\n      assume eq: \"r1 = pq\"\n      from assms have \"collinear ({r0,r1} \\<union> {b1} \\<union> {b0})\"\n      proof (intro collinear_union [of _ _ _ r0 r1])\n        from eq have \"{r0, b0, pq} = {r0, r1} \\<union> {b0}\" \"{r0, b1, pq} = {r0, r1} \\<union> {b1}\" by auto\n        with p0_p1_pq p0_q1_pq show \"collinear ({r0, r1} \\<union> {b0})\" \"collinear  ({r0, r1} \\<union> {b1})\" by simp_all\n      qed simp_all\n      with distinct_turns show False unfolding collinear_def by auto\n    qed\n\n    note lineseg_collinear collinear_lineseg_subset\n\n    have \"collinear ({r0, pq} \\<union> {b0} \\<union> {b1})\"\n      using p0_pq p0_p1_pq p0_q1_pq by (intro collinear_union [of _ _ _ r0 pq], auto simp add: insert_commute)\n    hence \"range (lineseg r0 pq) = range (lineseg b0 b1)\"\n      using assms p0_pq by (intro equalityI collinear_lineseg_subset, auto simp add: insert_commute)\n\n    moreover\n    have \"collinear ({r1, pq} \\<union> {b0} \\<union> {b1})\"\n      using q0_pq q0_q1_pq q0_p1_pq by (intro collinear_union [of _ _ _ r1 pq], auto simp add: insert_commute)\n    hence \"range (lineseg r1 pq) = range (lineseg b0 b1)\"\n      using assms q0_pq by (intro equalityI collinear_lineseg_subset, auto simp add: insert_commute)\n\n    ultimately\n    have \"collinear {r0,b0,r1,b1}\"\n      using range_lineseg_p0 range_lineseg_p1\n      apply (intro collinear_subset [of \"{r0, b0, r1, b1}\" \"range (lineseg b0 b1)\"] subsetI collinear_lineseg)\n      by (metis empty_iff insert_iff)\n\n    with distinct_turns show False unfolding collinear_def by auto\n  qed\n\n  ultimately show ?thesis by auto\nqed\n\ndefinition badly_collinear :: \"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> bool\"\n  where \"badly_collinear r0 b0 r1 b1 \\<equiv> ({b0,b1} \\<subseteq> lineseg r0 r1 ` { l. 1 < l } \\<or> {b0,b1} \\<subseteq> lineseg r1 r0 ` { l. 1 < l })\"\n\nlemma badly_collinear_intersects_prelim:\n  assumes bad: \"{b0, b1} \\<subseteq> lineseg r0 r1 ` {l. 1 < l}\"\n  shows \"segments_cross r0 b0 r1 b1\"\nproof -\n  from bad obtain lp1 lq1 where b0: \"b0 = lineseg r0 r1 lp1\" and b1: \"b1 = lineseg r0 r1 lq1\"\n    and lp1: \"1 < lp1\" and lq1: \"1 < lq1\" unfolding badly_collinear_def by auto\n\n  have \"r1 \\<in> segment_between r1 b1\" unfolding segment_between_def\n    by (intro image_eqI [where x=0], auto simp add: lineseg_def closed_01_def)\n\n  moreover from lp1 have \"r1 \\<in> segment_between r0 b0\" unfolding segment_between_def\n    by (intro image_eqI [where x=\"1/lp1\"], auto simp add: lineseg_def closed_01_def b0 scaleR_diff_left scaleR_diff_right scaleR_add_right)\n\n  ultimately show ?thesis unfolding segments_cross_def by auto\nqed\n\nlemma badly_collinear_intersects:\n  assumes \"badly_collinear r0 b0 r1 b1\"\n  shows \"segments_cross r0 b0 r1 b1\"\n  using badly_collinear_intersects_prelim assms\n  unfolding badly_collinear_def segments_cross_def\n  by (metis (full_types) Int_commute insert_commute)\n\nlemma badly_collinear_swap_still_badly_collinear:\n  assumes \"badly_collinear r0 b0 r1 b1\"\n  shows   \"badly_collinear r0 b1 r1 b0\"\n  using assms unfolding badly_collinear_def by auto\n\nlemma badly_collinear_swap_preserves_length_prelim:\n  assumes bad: \"{b0, b1} \\<subseteq> lineseg r0 r1 ` {l. 1 < l}\"\n  shows \"dist r0 b1 + dist r1 b0 = dist r0 b0 + dist r1 b1\"\nproof -\n  from bad obtain lp1 lq1 where b0: \"b0 = lineseg r0 r1 lp1\" and b1: \"b1 = lineseg r0 r1 lq1\"\n    and lp1: \"1 < lp1\" and lq1: \"1 < lq1\" by auto\n\n  have \"dist (lineseg r0 r1 0) (lineseg r0 r1 lq1) = \\<bar>lq1\\<bar> * dist r0 r1\" unfolding dist_lineseg by simp\n  hence dist_p0_q1: \"dist r0 b1 = lq1 * dist r0 r1\" using b1 lq1 by (simp add: lineseg_def)\n\n  have \"dist (lineseg r0 r1 1) (lineseg r0 r1 lp1) = (lp1-1) * dist r0 r1\" unfolding dist_lineseg using lp1 by simp\n  hence dist_q0_p1: \"dist r1 b0 = (lp1-1) * dist r0 r1\" by (simp add: b0 lineseg_def)\n\n  have \"dist (lineseg r0 r1 0) (lineseg r0 r1 lp1) = lp1 * dist r0 r1\" unfolding dist_lineseg using lp1 by simp\n  hence dist_p0_p1: \"dist r0 b0 = lp1 * dist r0 r1\" using lp1 b0 by (simp add: lineseg_def)\n\n  have \"dist (lineseg r0 r1 1) (lineseg r0 r1 lq1) = (lq1-1) * dist r0 r1\" unfolding dist_lineseg using lq1 by simp\n  hence dist_q0_q1: \"dist r1 b1 = (lq1-1) * dist r0 r1\" using lq1 b1 by (simp add: lineseg_def)\n\n  show ?thesis unfolding dist_p0_q1 dist_q0_p1 dist_p0_p1 dist_q0_q1 by (simp add: left_diff_distrib)\nqed\n\nlemma badly_collinear_swap_preserves_length:\n  assumes bad: \"badly_collinear r0 b0 r1 b1\"\n  shows \"dist r0 b1 + dist r1 b0 = dist r0 b0 + dist r1 b1\"\n  using bad\n  unfolding badly_collinear_def\nproof (elim disjE)\n  assume \"{b0, b1} \\<subseteq> lineseg r0 r1 ` {l. 1 < l}\"\n  thus ?thesis by (intro badly_collinear_swap_preserves_length_prelim)\nnext\n  assume \"{b0, b1} \\<subseteq> lineseg r1 r0 ` {l. 1 < l}\"\n  hence \"{b1, b0} \\<subseteq> lineseg r1 r0 ` {l. 1 < l}\" by simp\n  hence \"dist r1 b0 + dist r0 b1 = dist r1 b1 + dist r0 b0\"\n    by (intro badly_collinear_swap_preserves_length_prelim, auto)\n  thus ?thesis by simp\nqed\n\nlemma swap_decreases_length:\n  assumes distinct:       \"distinct [r0, b0, r1, b1]\"\n  assumes segments_cross: \"segments_cross r0 b0 r1 b1\"\n  assumes not_bad:        \"\\<not> badly_collinear r0 b0 r1 b1\"\n  shows \"dist r0 b1 + dist r1 b0 < dist r0 b0 + dist r1 b1\"\n  using segments_cross_turns [OF segments_cross]\nproof (elim conjE disjE)\n  assume distinct_turns: \"turn r0 b0 r1 \\<noteq> turn r0 b0 b1\" \"turn r1 b1 r0 \\<noteq> turn r1 b1 b0\"\n  with distinct show ?thesis\n    by (intro non_collinear_swap_decreases_length, auto)\nnext\n  assume collinear: \"collinear {r0, b0, r1, b1}\"\n  hence \"{r0,b0,r1,b1} \\<subseteq> range (lineseg r0 b0)\" using distinct by (intro lineseg_collinear, auto)\n  then obtain lq0 lq1 where r1: \"r1 = lineseg r0 b0 lq0\" and b1: \"b1 = lineseg r0 b0 lq1\" by auto\n\n  from segments_cross obtain lp lq\n    where lp_lq: \"lineseg r0 b0 lp = lineseg r1 b1 lq\"\n      and lp01: \"0 \\<le> lp\" \"lp \\<le> 1\" and lq01: \"0 \\<le> lq\" \"lq \\<le> 1\"\n    unfolding segments_cross_def segment_between_def closed_01_def r1 b1 apply auto by presburger\n\n  from lp_lq have \"lp *\\<^sub>R (b0 - r0) = (lq0 - (lq * lq0) + (lq * lq1)) *\\<^sub>R (b0 - r0)\"\n    by (simp add: r1 b1 lineseg_def scaleR_diff_left scaleR_diff_right scaleR_add_right left_diff_distrib scaleR_add_left)\n  hence \"(lp - lq0 + lq * lq0 - lq * lq1) *\\<^sub>R (b0 - r0) = 0\" by auto\n  with distinct have eq0: \"lp - lq0 + lq * lq0 - lq * lq1 = 0\" by auto\n\n  from distinct b1 have lq1_ne: \"lq1 \\<noteq> 0\" \"lq1 \\<noteq> 1\" by (auto simp add: lineseg_def)\n  then consider (lq1_lt_0) \"lq1 < 0\" | (lq1_01) \"0 < lq1\" \"lq1 < 1\" | (lq1_gt_1) \"1 < lq1\" by linarith\n  note lq1_cases = this\n\n  from distinct r1 have lq0_ne: \"lq0 \\<noteq> 0\" \"lq0 \\<noteq> 1\" by (auto simp add: lineseg_def)\n  then consider (lq0_lt_0) \"lq0 < 0\" | (lq0_01) \"0 < lq0\" \"lq0 < 1\" | (lq0_gt_1) \"1 < lq0\" by linarith\n  note lq0_cases = this\n\n  have lineseg_eq: \"\\<And>l. lineseg r0 r1 l = lineseg r0 b0 (l*lq0)\"\n    by (auto simp add: lineseg_def r1 scaleR_diff_left scaleR_diff_right scaleR_add_right)\n\n  have b0': \"b0 = lineseg r0 r1   (1/lq0)\" unfolding lineseg_eq    using lq0_ne by (simp add: lineseg_def)\n  have b1': \"b1 = lineseg r0 r1 (lq1/lq0)\" unfolding lineseg_eq b1 using lq0_ne by (simp add: lineseg_def)\n\n  show ?thesis\n  proof (cases \"lq1 < lq0\")\n    case True      \n\n    have \"dist r0 b1 = dist (lineseg r0 b0 0) (lineseg r0 b0 lq1)\" by (simp add: lineseg_def b1)\n    hence dist_p0_q1: \"dist r0 b1 = \\<bar>lq1\\<bar> * dist r0 b0\" unfolding dist_lineseg by simp\n\n    have \"dist r1 b0 = dist (lineseg r0 b0 lq0) (lineseg r0 b0 1)\" by (simp add: lineseg_def r1)\n    hence dist_q0_p1: \"dist r1 b0 = \\<bar>1-lq0\\<bar> * dist r0 b0\" unfolding dist_lineseg by simp\n\n    have dist_q0_q1: \"dist r1 b1 = \\<bar>lq1-lq0\\<bar> * dist r0 b0\" unfolding dist_lineseg r1 b1 by simp\n\n    from eq0 True lp01 lq01 lq0_ne have lq0_0: \"0 < lq0\" apply auto by (smt mult_left_mono)\n    from eq0 True lp01 lq01 lq1_ne have lq1_1: \"lq1 < 1\" apply auto by (smt mult_left_le_one_le right_diff_distrib')\n\n    from True have abs_lq1_lq0: \"\\<bar>lq1-lq0\\<bar> = lq0 - lq1\" by simp\n\n    have \"\\<bar>lq1\\<bar> + \\<bar>1-lq0\\<bar> < 1 + \\<bar>lq1-lq0\\<bar>\" unfolding abs_lq1_lq0 using lq0_0 lq1_1 True by auto\n    with distinct have \"(\\<bar>lq1\\<bar> + \\<bar>1-lq0\\<bar>) * dist r0 b0 < (1 + \\<bar>lq1-lq0\\<bar>) * dist r0 b0\" by auto\n    thus ?thesis unfolding dist_p0_q1 dist_q0_p1 dist_q0_q1 by (simp add: distrib_right)\n  next\n    case False\n    from distinct have \"lq0 \\<noteq> lq1\" unfolding r1 b1 by auto\n    with False have lq0_lt_lq1: \"lq0 < lq1\" unfolding r1 b1 by auto (* --- r1 --- b1 --- *)\n\n    from lq0_cases have False\n    proof cases\n      case lq0_lt_0\n      with lp01 lq01 eq0 have lq1_gt_0: \"0 < lq1\" by (smt lq1_cases mult_left_le_one_le mult_minus_right zero_less_mult_iff)\n          (* --- r1 --- r0 --- {b1, b0} --- is bad *)\n      with lq0_lt_0 have \"{b0,b1} \\<subseteq> lineseg r0 r1 ` { l. l < 0 }\"\n        unfolding b0' b1'\n        apply auto using divide_pos_neg by blast\n      also have \"... \\<subseteq> lineseg r1 r0 ` { l. 1 < l }\"\n      proof (intro subsetI)\n        fix p assume \"p \\<in> lineseg r0 r1 ` {l. l < 0}\" then obtain l where l: \"p = lineseg r0 r1 l\" \"l < 0\" by auto\n        thus \"p \\<in> lineseg r1 r0 ` {l. 1 < l}\" by (intro image_eqI [where x = \"1-l\"], auto simp add: lineseg_def)\n      qed\n      finally show ?thesis using not_bad unfolding badly_collinear_def by simp\n    next\n      case lq0_01\n        (* --- r0 --- r1 --- {b0,b1} --- is bad *)\n      with lq0_lt_lq1 have \"{b0,b1} \\<subseteq> lineseg r0 r1 ` {l. 1 < l}\" unfolding b0' b1' by auto\n      thus ?thesis using not_bad unfolding badly_collinear_def by simp\n    next\n      case lq0_gt_1\n      with lp01 lq01 eq0 have lq1_lt_1: \"lq1 < 1\"\n        by (smt lq1_cases mult_minus_left ordered_comm_semiring_class.comm_mult_left_mono semiring_normalization_rules(2))\n      with lq0_gt_1 lq0_lt_lq1 show ?thesis by simp\n    qed\n    thus ?thesis by simp\n  qed\nqed\n\nlocale UncrossingSetup =\n  fixes redPoints bluePoints :: \"point set\"\n  assumes finite_redPoints:  \"finite redPoints\"\n  assumes finite_bluePoints: \"finite bluePoints\"\n  assumes cards_eq:  \"card redPoints = card bluePoints\"\n  assumes red_blue_disjoint: \"redPoints \\<inter> bluePoints = {}\"\n  assumes not_badly_collinear:\n      \"\\<And>r1 r2. \\<lbrakk> r1 \\<in> redPoints; r2 \\<in> redPoints \\<rbrakk>\n          \\<Longrightarrow> card (bluePoints \\<inter> lineseg r1 r2 ` {l. 1 < l}) \\<le> 1\"\n\ncontext UncrossingSetup\nbegin\n\nlemma uncross_reduces_length:\n  fixes r1 r2 b1 b2\n  assumes colours: \"r1 \\<in> redPoints\" \"r2 \\<in> redPoints\" \"b1 \\<in> bluePoints\" \"b2 \\<in> bluePoints\"\n  assumes distinct: \"r1 \\<noteq> r2\" \"b1 \\<noteq> b2\"\n  assumes segments_cross: \"segments_cross r1 b1 r2 b2\"\n  shows \"dist r1 b2 + dist r2 b1 < dist r1 b1 + dist r2 b2\"\nproof (intro swap_decreases_length segments_cross)\n  show \"distinct [r1, b1, r2, b2]\" using distinct colours red_blue_disjoint by auto\n  show \" \\<not> badly_collinear r1 b1 r2 b2\"\n    unfolding badly_collinear_def\n  proof (intro notI, elim disjE)\n    assume \"{b1, b2} \\<subseteq> lineseg r1 r2 ` {l. 1 < l}\"\n    with colours have \"{b1, b2} \\<subseteq> bluePoints \\<inter> lineseg r1 r2 ` {l. 1 < l}\" by auto\n    hence \"card {b1, b2} \\<le> card (bluePoints \\<inter> lineseg r1 r2 ` {l. 1 < l})\"\n      using finite_bluePoints by (intro card_mono, auto)\n    also have \"\\<dots> \\<le> 1\" by (intro not_badly_collinear colours)\n    finally show False using distinct by simp\n  next\n    assume \"{b1, b2} \\<subseteq> lineseg r2 r1 ` {l. 1 < l}\"\n    with colours have \"{b1, b2} \\<subseteq> bluePoints \\<inter> lineseg r2 r1 ` {l. 1 < l}\" by auto\n    hence \"card {b1, b2} \\<le> card (bluePoints \\<inter> lineseg r2 r1 ` {l. 1 < l})\"\n      using finite_bluePoints by (intro card_mono, auto)\n    also have \"\\<dots> \\<le> 1\" by (intro not_badly_collinear colours)\n    finally show False using distinct by simp\n  qed\nqed\n\ndefinition valid_total_lengths :: \"real set\"\n  where \"valid_total_lengths \\<equiv> (\\<lambda>pairs. \\<Sum> pair \\<in> pairs. dist (fst pair) (snd pair)) ` Pow (redPoints \\<times> bluePoints)\"\n\nlemma finite_valid_total_lengths: \"finite valid_total_lengths\"\n  unfolding valid_total_lengths_def\n  by (intro finite_imageI iffD2 [OF finite_Pow_iff] finite_cartesian_product finite_redPoints finite_bluePoints)\n\ndefinition valid_length_transitions :: \"(real \\<times> real) set\"\n  where \"valid_length_transitions \\<equiv> Restr {(x,y). x < y} valid_total_lengths\"\n\nlemma wf_less_valid_total_length: \"wf valid_length_transitions\"\nproof (intro finite_acyclic_wf)\n  have \"valid_length_transitions \\<subseteq> valid_total_lengths \\<times> valid_total_lengths\" by (auto simp add: valid_length_transitions_def)\n  thus \"finite valid_length_transitions\" using finite_subset finite_valid_total_lengths by blast\n\n  have \"x < y\" if p: \"(x,y) \\<in> {(x, y). x < y}\\<^sup>+\" for x y :: real using p by (induct y rule: trancl_induct, simp_all)\n  hence \"acyclic {(x, y). x < (y::real)}\" by (intro acyclicI, auto)\n\n  moreover have \"valid_length_transitions \\<subseteq> {(x, y). x < y}\" by (auto simp add: valid_length_transitions_def)\n  ultimately show \"acyclic valid_length_transitions\" using acyclic_subset by blast\nqed\n\nend\n\ndefinition swapPoints :: \"point \\<Rightarrow> point \\<Rightarrow> point \\<Rightarrow> point\"\n  where \"swapPoints p0 p1 p \\<equiv> if p = p0 then p1 else if p = p1 then p0 else p\"\n\nlocale Uncrossing = UncrossingSetup +\n  fixes blueFromRed :: \"(point \\<Rightarrow> point) stfun\"\n  assumes bv: \"basevars blueFromRed\"\n  fixes blueFromRed_range :: stpred\n  defines \"blueFromRed_range \\<equiv> PRED ((`)<blueFromRed,#redPoints> = #bluePoints)\" \n  fixes step :: action\n  defines \"step \\<equiv> ACT (\\<exists> r0 r1 b0 b1. #r0 \\<in> #redPoints \\<and> #r1 \\<in> #redPoints \\<and> #r0 \\<noteq> #r1\n            \\<and> #b0 = id<$blueFromRed,#r0>\n            \\<and> #b1 = id<$blueFromRed,#r1>\n            \\<and> #(segments_cross r0 b0 r1 b1)\n            \\<and> blueFromRed$ = (\\<circ>)<$blueFromRed,#(swapPoints r0 r1)>)\"\n  fixes Spec :: temporal\n  defines \"Spec \\<equiv> TEMP (Init blueFromRed_range \\<and> \\<box>[step]_blueFromRed \\<and> WF(step)_blueFromRed)\"\n\ncontext Uncrossing\nbegin\n\nlemma blueFromRed_range_preserved: \"\\<turnstile> step \\<longrightarrow> $blueFromRed_range \\<longrightarrow> blueFromRed_range$\"\n  apply (intro actionI)\n  apply (auto simp add: blueFromRed_range_def square_def step_def swapPoints_def)\n  by (metis (no_types, hide_lams) imageI image_comp swapPoints_def)+\n\nlemma blueFromRed_range_Invariant: \"\\<turnstile> Spec \\<longrightarrow> \\<box>blueFromRed_range\"\nproof invariant\n  fix sigma\n  assume Spec: \"sigma \\<Turnstile> Spec\"\n  thus \"sigma \\<Turnstile> stable blueFromRed_range\"\n  proof (intro Stable)\n    show \"\\<turnstile> $blueFromRed_range \\<and> [step]_blueFromRed \\<longrightarrow> blueFromRed_range$\"\n      using blueFromRed_range_preserved [temp_use]\n      by (auto simp add: square_def, simp add: blueFromRed_range_def)\n  qed (simp add: Spec_def)\nqed (simp add: Spec_def)\n\ndefinition total_length :: \"real stfun\"\n  where \"total_length s \\<equiv> \\<Sum> r \\<in> redPoints. dist r (blueFromRed s r)\"\n\nlemma blueFromRed_range_valid_total_length: \"\\<turnstile> blueFromRed_range \\<longrightarrow> total_length \\<in> #valid_total_lengths\"\n  unfolding valid_total_lengths_def\nproof (clarsimp, intro image_eqI)\n  fix w\n  assume \"blueFromRed_range w\"\n  thus \"(\\<lambda>r. (r, blueFromRed w r)) ` redPoints \\<in> Pow (redPoints \\<times> bluePoints)\"\n    by (auto simp add: blueFromRed_range_def)\n\n  have \"sum (\\<lambda>pair. dist (fst pair) (snd pair)) ((\\<lambda>r. (r, blueFromRed w r)) ` redPoints)\n      = sum ((\\<lambda>pair. dist (fst pair) (snd pair)) o ((\\<lambda>r. (r, blueFromRed w r)))) redPoints\"\n    by (intro sum.reindex inj_onI, simp)\n  thus \"total_length w = (\\<Sum>pair\\<in>(\\<lambda>r. (r, blueFromRed w r)) ` redPoints. dist (fst pair) (snd pair))\"\n    by (simp add: total_length_def)\nqed\n\ndefinition all_uncrossed :: stpred\n  where \"all_uncrossed \\<equiv> PRED (\\<forall> r0 r1 b0 b1. #r0 \\<in> #redPoints \\<and> #r1 \\<in> #redPoints \\<and> #r0 \\<noteq> #r1\n            \\<and> #b0 = id<blueFromRed,#r0>\n            \\<and> #b1 = id<blueFromRed,#r1>\n            \\<longrightarrow> \\<not> #(segments_cross r0 b0 r1 b1))\"\n\nlemma stops_when_all_uncrossed: \"\\<turnstile> Spec \\<longrightarrow> \\<box>($all_uncrossed \\<longrightarrow> blueFromRed$ = $blueFromRed)\"\nproof -\n  have \"\\<turnstile> Spec \\<longrightarrow> \\<box>[step]_blueFromRed\" by (auto simp add: Spec_def)\n  also have \"\\<turnstile> \\<box>[step]_blueFromRed \\<longrightarrow> \\<box>($all_uncrossed \\<longrightarrow> blueFromRed$ = $blueFromRed)\"\n    by (intro STL4, auto simp add: square_def step_def all_uncrossed_def)\n  finally show ?thesis .\nqed\n\nlemma step_valid_length_transition:\n  assumes \"(s,t) \\<Turnstile> step\"\n  assumes \"s \\<Turnstile> blueFromRed_range\"\n  shows \"(total_length t, total_length s) \\<in> valid_length_transitions\"\n  unfolding valid_length_transitions_def\nproof (intro IntI)\n  from assms blueFromRed_range_preserved [temp_use] have \"blueFromRed_range t\" by simp\n  with assms blueFromRed_range_valid_total_length [temp_use]\n  show \"(total_length t, total_length s) \\<in> valid_total_lengths \\<times> valid_total_lengths\" by simp\n\n  from assms have blueFromRed_range: \"blueFromRed s ` redPoints = bluePoints\"\n    unfolding blueFromRed_range_def by auto\n\n  from assms obtain r0 r1\n    where r0: \"r0 \\<in> redPoints\" and r1: \"r1 \\<in> redPoints\" and r0_r1_ne: \"r0 \\<noteq> r1\"\n      and segments_cross: \"segments_cross r0 (blueFromRed s r0) r1 (blueFromRed s r1)\"\n      and blueFromRed: \"blueFromRed t = blueFromRed s \\<circ> swapPoints r0 r1\"\n    unfolding step_def by clarsimp\n\n  have total_length_eq: \"\\<And>u. total_length u = (\\<Sum>r\\<in>(redPoints - {r0,r1}). dist r (blueFromRed u r))\n            + dist r0 (blueFromRed u r0)\n            + dist r1 (blueFromRed u r1)\"\n  proof -\n    fix u\n    define g where \"g \\<equiv> \\<lambda>r. dist r (blueFromRed u r)\"\n\n    have 1: \"redPoints - {r0} - {r1} = redPoints - {r0, r1}\" by auto\n\n    from finite_redPoints r1 r0_r1_ne\n    have 2: \"sum g (redPoints - {r0}) = g r1 + sum g (redPoints - {r0} - {r1})\"\n      by (intro sum.remove, auto)\n\n    have \"total_length u = sum g redPoints\" by (simp add: total_length_def g_def)\n    also have \"\\<dots> = g r0 + sum g (redPoints - {r0})\" by (intro sum.remove finite_redPoints r0)\n    also have \"\\<dots> = g r0 + g r1 + sum g (redPoints - {r0, r1})\" unfolding 1 2 by simp\n    finally show \"?thesis u\" by (simp add: g_def)\n  qed\n\n  have reduced_part: \"dist r0 (blueFromRed t r0) + dist r1 (blueFromRed t r1)\n                    < dist r0 (blueFromRed s r0) + dist r1 (blueFromRed s r1)\"\n    unfolding blueFromRed using r0_r1_ne\n  proof (simp add: swapPoints_def, intro uncross_reduces_length r0 r1 r0_r1_ne segments_cross)\n    from blueFromRed_range r0 r1\n    show \"blueFromRed s r0 \\<in> bluePoints\" \"blueFromRed s r1 \\<in> bluePoints\" by auto\n\n    have \"inj_on (blueFromRed s) redPoints\"\n      by (intro eq_card_imp_inj_on finite_redPoints, simp add: blueFromRed_range cards_eq)\n    with r0 r1 r0_r1_ne show \"blueFromRed s r0 \\<noteq> blueFromRed s r1\" by (meson inj_on_eq_iff)\n  qed\n\n  have unchanged_part: \"(\\<Sum>r\\<in>redPoints - {r0, r1}. dist r (blueFromRed t r)) = (\\<Sum>r\\<in>redPoints - {r0, r1}. dist r (blueFromRed s r))\"\n    by (intro sum.cong refl, auto simp add: blueFromRed swapPoints_def)\n\n  show \"(total_length t, total_length s) \\<in> {(x, y). x < y}\"\n    apply simp\n    unfolding total_length_eq unchanged_part\n    using reduced_part by simp\nqed\n\nlemma \"\\<turnstile> Spec \\<longrightarrow> \\<diamond>\\<box>all_uncrossed\"\nproof -\n  have \"\\<turnstile> Spec \\<longrightarrow> stable all_uncrossed\"\n    by (intro tempI temp_impI Stable, auto simp add: Spec_def all_uncrossed_def square_def step_def)\n  moreover have \"\\<turnstile> Spec \\<longrightarrow> \\<diamond>all_uncrossed\"\n  proof -\n    have \"\\<turnstile> Spec \\<longrightarrow> \\<diamond>(\\<exists>tl. all_uncrossed \\<or> total_length = #tl)\" by (intro imp_eventually_init, auto simp add: Init_def)\n    also have \"\\<turnstile> Spec \\<longrightarrow> ((\\<exists>tl. all_uncrossed \\<or> total_length = #tl) \\<leadsto> all_uncrossed)\" \n    proof (intro wf_imp_ex_leadsto [OF wf_less_valid_total_length] imp_disj_excl_leadstoI [OF imp_imp_leadsto])\n      fix tl\n\n      from blueFromRed_range_Invariant\n      have \"\\<turnstile> Spec \\<longrightarrow> \\<box>([step]_blueFromRed \\<and> $blueFromRed_range) \\<and> WF(step)_blueFromRed\"\n        unfolding Spec_def apply auto using Init_stp_act_rev boxInit_act boxInit_stp by auto\n      also have \"\\<turnstile> \\<box>([step]_blueFromRed \\<and> $blueFromRed_range) \\<and> WF(step)_blueFromRed\n                  \\<longrightarrow> (\\<not> all_uncrossed \\<and> total_length = #tl\n                      \\<leadsto> all_uncrossed \\<or> (\\<exists>t'. #((t', tl) \\<in> valid_length_transitions) \\<and> (all_uncrossed \\<or> total_length = #t')))\"\n      proof (intro WF1 actionI temp_impI)\n        fix s t\n        assume \"(s, t) \\<Turnstile> $(\\<not> all_uncrossed \\<and> total_length = #tl) \\<and> [step]_blueFromRed \\<and> $blueFromRed_range\"\n        hence maybe_step: \"((s,t) \\<Turnstile> step) \\<or> blueFromRed t = blueFromRed s\"\n          and some_crossed: \"\\<not> all_uncrossed s\"\n          and tl: \"tl = total_length s\"\n          and blueFromRed_range: \"blueFromRed s ` redPoints = bluePoints\"\n          by (auto simp add: square_def blueFromRed_range_def)\n\n        from some_crossed maybe_step consider (unchanged) \"blueFromRed t = blueFromRed s\"\n          | (finish) \"all_uncrossed t\"\n          | (step) \"(s,t) \\<Turnstile> step\" \"\\<not> all_uncrossed t\" by auto\n        note cases = this\n\n        from maybe_step\n        show \"(s, t) \\<Turnstile> (\\<not> all_uncrossed \\<and> total_length = #tl)$\n                          \\<or> (all_uncrossed \\<or> (\\<exists>t'. #((t', tl) \\<in> valid_length_transitions)\n                                \\<and> (all_uncrossed \\<or> total_length = #t')))$\"\n        proof (elim disjE)\n          assume \"blueFromRed t = blueFromRed s\"\n          with some_crossed tl some_crossed tl show ?thesis by (auto simp add: all_uncrossed_def total_length_def)\n        next\n          assume \"(s,t) \\<Turnstile> step\"\n          with blueFromRed_range\n          have \"(total_length t, total_length s) \\<in> valid_length_transitions\"\n            by (intro step_valid_length_transition, auto simp add: blueFromRed_range_def)\n          with tl show ?thesis by auto\n        qed\n\n        show \"(s,t) \\<Turnstile> $Enabled (<step>_blueFromRed)\"\n          unfolding unl_before enabled_def\n        proof -\n          from some_crossed obtain r0 r1 where r0: \"r0 \\<in> redPoints\" and r1: \"r1 \\<in> redPoints\" and r0_r1_ne: \"r0 \\<noteq> r1\"\n            and crossed: \"segments_cross r0 (blueFromRed s r0) r1 (blueFromRed s r1)\"\n            unfolding all_uncrossed_def by auto\n\n          from basevars [OF bv] obtain u where u: \"blueFromRed u = blueFromRed s \\<circ> swapPoints r0 r1\" by auto\n\n          have blueFromRed_changed: \"blueFromRed u \\<noteq> blueFromRed s\"\n          proof (intro notI)\n            assume \"blueFromRed u = blueFromRed s\"\n            with u have \"blueFromRed s r0 = (blueFromRed s \\<circ> swapPoints r0 r1) r0\" by simp\n            hence \"blueFromRed s r0 = blueFromRed s r1\" by (simp add: swapPoints_def)\n            moreover from blueFromRed_range\n            have \"inj_on (blueFromRed s) redPoints\"\n              by (intro eq_card_imp_inj_on finite_redPoints, simp add: blueFromRed_range_def cards_eq)\n            with r0 r1 r0_r1_ne have \"blueFromRed s r0 \\<noteq> blueFromRed s r1\" by (meson inj_on_eq_iff)\n            ultimately show False by simp\n          qed\n\n          from r0 r1 r0_r1_ne crossed u\n          show \"\\<exists>u. (s, u) \\<Turnstile> <step>_blueFromRed\"\n            by (cases r0, cases r1, intro exI [where x = u], auto simp add: angle_def blueFromRed_changed step_def)\n        qed\n\n      next\n        fix s t\n        assume \"(s,t) \\<Turnstile> ($(\\<not> all_uncrossed \\<and> total_length = #tl) \\<and> [step]_blueFromRed \\<and> $blueFromRed_range) \\<and> <step>_blueFromRed\"\n        hence step: \"(s,t) \\<Turnstile> step\" and tl: \"tl = total_length s\" and blueFromRed_range: \"blueFromRed_range s\" by (auto simp add: angle_def)\n        hence \"(total_length t, total_length s) \\<in> valid_length_transitions\" by (intro step_valid_length_transition)\n        thus \"(s,t) \\<Turnstile> ((all_uncrossed \\<or> (\\<exists>t'. #((t', tl) \\<in> valid_length_transitions) \\<and> (all_uncrossed \\<or> total_length = #t')))$)\"\n          by (auto simp add: tl)\n      qed\n      finally show \"\\<turnstile> Spec \\<longrightarrow> (\\<not> all_uncrossed \\<and> total_length = #tl \\<leadsto> all_uncrossed \\<or> (\\<exists>t'. #((t', tl) \\<in> valid_length_transitions) \\<and> (all_uncrossed \\<or> total_length = #t')))\" .\n    qed auto\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis using DmdStable by fastforce\nqed\n\nend\n\nend\n", "meta": {"author": "DaveCTurner", "repo": "tla-examples", "sha": "fd566a8bd41fbb317d2f0f7aa58e3086f4aff46f", "save_path": "github-repos/isabelle/DaveCTurner-tla-examples", "path": "github-repos/isabelle/DaveCTurner-tla-examples/tla-examples-fd566a8bd41fbb317d2f0f7aa58e3086f4aff46f/EWD-pairings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582612793112, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7852091698250258}}
{"text": "(*  \n    Title:      System_Of_Equations.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Solving systems of equations using the Gauss Jordan algorithm\\<close>\n\ntheory System_Of_Equations\nimports\n Gauss_Jordan_PA\n Bases_Of_Fundamental_Subspaces\nbegin\n\nsubsection\\<open>Definitions\\<close>\n\ntext\\<open>Given a system of equations @{term \"A *v x = b\"}, the following function returns the pair @{term \"(P ** A,P *v b)\"}, where P is the matrix\n      which states @{term \"Gauss_Jordan A = P ** A\"}. That matrix is computed by means of @{term \"Gauss_Jordan_PA\"}.\\<close>\n\ndefinition solve_system :: \"('a::{field}^'cols::{mod_type}^'rows::{mod_type}) \\<Rightarrow> ('a^'rows::{mod_type}) \n  \\<Rightarrow> (('a^'cols::{mod_type}^'rows::{mod_type}) \\<times> ('a^'rows::{mod_type}))\"\n  where \"solve_system A b = (let A' = Gauss_Jordan_PA A in (snd A', (fst A') *v b))\"\n\ndefinition is_solution where \"is_solution x A b = (A *v x = b)\"\n\nsubsection\\<open>Relationship between @{term \"is_solution_def\"} and @{term \"solve_system_def\"}\\<close>\n\nlemma is_solution_imp_solve_system:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes xAb:\"is_solution x A b\"\n  shows \"is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\nproof -\n  have \"(fst (Gauss_Jordan_PA A)*v(A *v x) = fst (Gauss_Jordan_PA A) *v b)\"\n    using xAb unfolding is_solution_def by fast\n  hence \"(snd (Gauss_Jordan_PA A) *v x = fst (Gauss_Jordan_PA A) *v b)\"\n    unfolding matrix_vector_mul_assoc\n    unfolding fst_Gauss_Jordan_PA[of A] .\n  thus \"is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\n    unfolding is_solution_def solve_system_def Let_def by simp\nqed\n\n\nlemma solve_system_imp_is_solution:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes xAb: \"is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\n  shows \"is_solution x A b\" \nproof -\n  have \"fst (solve_system A b) *v x = snd (solve_system A b)\" \n    using xAb unfolding is_solution_def .\n  hence \"snd (Gauss_Jordan_PA A) *v x = fst (Gauss_Jordan_PA A) *v b\" \n    unfolding solve_system_def Let_def fst_conv snd_conv .\n  hence \"(fst (Gauss_Jordan_PA A) ** A) *v x = fst (Gauss_Jordan_PA A) *v b\" \n    unfolding fst_Gauss_Jordan_PA .\n  hence \"fst (Gauss_Jordan_PA A) *v (A *v x) = fst (Gauss_Jordan_PA A) *v b\" \n    unfolding matrix_vector_mul_assoc .\n  hence \"matrix_inv (fst (Gauss_Jordan_PA A)) *v (fst (Gauss_Jordan_PA A) *v (A *v x)) \n  = matrix_inv (fst (Gauss_Jordan_PA A)) *v (fst (Gauss_Jordan_PA A) *v b)\" by simp\n  hence \"(A *v x) = b\"\n    unfolding matrix_vector_mul_assoc[of \"matrix_inv (fst (Gauss_Jordan_PA A))\"]\n    unfolding matrix_inv_left[OF invertible_fst_Gauss_Jordan_PA]\n    unfolding matrix_vector_mul_lid .\n  thus ?thesis unfolding is_solution_def .\nqed\n\nlemma is_solution_solve_system:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"is_solution x A b = is_solution x (fst (solve_system A b)) (snd (solve_system A b))\"\n  using solve_system_imp_is_solution is_solution_imp_solve_system by blast\n\nsubsection\\<open>Consistent and inconsistent systems of equations\\<close>\n\ndefinition consistent :: \"'a::{field}^'cols::{mod_type}^'rows::{mod_type} \\<Rightarrow> 'a::{field}^'rows::{mod_type} \\<Rightarrow> bool\"\n  where \"consistent A b = (\\<exists>x. is_solution x A b)\"\n\ndefinition inconsistent where \"inconsistent A b =  (\\<not> (consistent A b))\"\n\nlemma inconsistent: \"inconsistent A b = (\\<not> (\\<exists>x. is_solution x A b))\"\n  unfolding inconsistent_def consistent_def by simp\n\ntext\\<open>The following function will be use to solve consistent systems which are already in the reduced row echelon form.\\<close>\n\ndefinition solve_consistent_rref :: \"'a::{field}^'cols::{mod_type}^'rows::{mod_type} \\<Rightarrow> 'a::{field}^'rows::{mod_type} \\<Rightarrow> 'a::{field}^'cols::{mod_type}\"\n  where \"solve_consistent_rref A b = (\\<chi> j. if (\\<exists>i. A $ i $ j = 1 \\<and> j=(LEAST n. A $ i $ n \\<noteq> 0)) then b $ (THE i. A $ i $ j = 1) else 0)\"\n\nlemma solve_consistent_rref_code[code abstract]:\n  shows \"vec_nth (solve_consistent_rref A b) = (% j. if (\\<exists>i. A $ i $ j = 1 \\<and> j=(LEAST n. A $ i $ n \\<noteq> 0)) then b $ (THE i. A $ i $ j = 1) else 0)\"\n  unfolding solve_consistent_rref_def by auto\n\n\nlemma rank_ge_imp_is_solution:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes con: \"rank A \\<ge> (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) \n                                            then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0)\"\n  shows \"is_solution (solve_consistent_rref (Gauss_Jordan A) (P_Gauss_Jordan A *v b)) A b\"\nproof -\n  have \"is_solution (solve_consistent_rref (Gauss_Jordan A) (P_Gauss_Jordan A *v b)) (Gauss_Jordan A) (P_Gauss_Jordan A *v b)\"\n  proof (unfold is_solution_def solve_consistent_rref_def, subst matrix_vector_mult_def, vector, auto)\n    fix a\n    let ?f=\"\\<lambda>j. Gauss_Jordan A $ a $ j *\n      (if \\<exists>i. Gauss_Jordan A $ i $ j = 1 \\<and> j = (LEAST n. Gauss_Jordan A $ i $ n \\<noteq> 0) \n        then (P_Gauss_Jordan A *v b) $ (THE i. Gauss_Jordan A $ i $ j = 1) else 0)\"\n    show \"sum ?f UNIV = (P_Gauss_Jordan A *v b) $ a\"\n    proof (cases \"A=0\")\n      case True\n      hence rank_A_eq_0:\"rank A = 0\" using rank_0 by simp\n      have \"(P_Gauss_Jordan A *v b) = 0\"\n      proof (rule ccontr)\n        assume not_zero: \"P_Gauss_Jordan A *v b \\<noteq> 0\"\n        hence ex_a: \"\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0\" by (metis vec_eq_iff zero_index)\n        show False using con unfolding if_P[OF ex_a] unfolding rank_A_eq_0 by auto\n      qed\n\n      thus ?thesis unfolding A_0_imp_Gauss_Jordan_0[OF True] by force\n    next\n      case False note A_not_zero=False\n      define not_zero_positions_row_a where \"not_zero_positions_row_a = {j. Gauss_Jordan A $ a $ j \\<noteq> 0}\"\n      define zero_positions_row_a where \"zero_positions_row_a = {j. Gauss_Jordan A $ a $ j = 0}\"\n      have UNIV_rw: \"UNIV = not_zero_positions_row_a \\<union> zero_positions_row_a\" \n        unfolding zero_positions_row_a_def not_zero_positions_row_a_def by auto\n      have disj: \"not_zero_positions_row_a \\<inter> zero_positions_row_a = {}\" \n        unfolding zero_positions_row_a_def not_zero_positions_row_a_def by fastforce\n      have sum_zero: \"(sum ?f zero_positions_row_a) = 0\" \n        by (unfold zero_positions_row_a_def, rule sum.neutral, fastforce)\n      have \"sum ?f (UNIV::'cols set)=sum ?f (not_zero_positions_row_a \\<union> zero_positions_row_a)\" \n        unfolding UNIV_rw ..\n      also have \"... = sum ?f (not_zero_positions_row_a) + (sum ?f zero_positions_row_a)\" \n        by (rule sum.union_disjoint[OF _ _ disj], simp+)\n      also have \"... = sum ?f (not_zero_positions_row_a)\" unfolding sum_zero by simp\n      also have \"... = (P_Gauss_Jordan A *v b) $ a\"\n      proof (cases \"not_zero_positions_row_a = {}\")\n        case True note zero_row_a=True    \n        show ?thesis \n        proof (cases \"\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0\")\n          case False hence \"(P_Gauss_Jordan A *v b) $ a = 0\" by simp\n          thus ?thesis unfolding True by auto\n        next\n          case True\n          have rank_not_0: \"rank A \\<noteq> 0\" by (metis A_not_zero less_not_refl3 rank_Gauss_Jordan rank_greater_zero)\n          have greatest_less_a: \"(GREATEST a. \\<not> is_zero_row a (Gauss_Jordan A)) < a\"\n          proof (unfold is_zero_row_def, rule greatest_less_zero_row)\n            show \" reduced_row_echelon_form_upt_k (Gauss_Jordan A) (ncols (Gauss_Jordan A))\"\n              using rref_Gauss_Jordan unfolding reduced_row_echelon_form_def .\n            show \"is_zero_row_upt_k a (ncols (Gauss_Jordan A)) (Gauss_Jordan A)\"\n              by (metis (mono_tags) Collect_empty_eq is_zero_row_upt_ncols not_zero_positions_row_a_def zero_row_a)\n            show \"\\<not> (\\<forall>a. is_zero_row_upt_k a (ncols (Gauss_Jordan A)) (Gauss_Jordan A))\"\n              by (metis False Gauss_Jordan_not_0 is_zero_row_upt_ncols vec_eq_iff zero_index)\n          qed\n          hence \"to_nat (GREATEST a. \\<not> is_zero_row a (Gauss_Jordan A)) < to_nat a\" using to_nat_mono by fast\n          hence rank_le_to_nat_a: \"rank A \\<le> to_nat a\" unfolding rank_eq_suc_to_nat_greatest[OF A_not_zero] by simp\n          have \"to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) < to_nat a\" \n            using con unfolding consistent_def unfolding if_P[OF True] using rank_le_to_nat_a by simp \n          hence \"(GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) < a\" by (metis not_le to_nat_mono')\n          hence \"(P_Gauss_Jordan A *v b) $ a = 0\" using not_greater_Greatest by blast\n          thus ?thesis unfolding zero_row_a by simp\n        qed    \n      next\n        case False note not_empty=False\n        have not_zero_positions_row_a_rw: \"not_zero_positions_row_a = {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0} \\<union> (not_zero_positions_row_a - {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0})\"\n          unfolding not_zero_positions_row_a_def\n          by (metis (mono_tags) Collect_cong False LeastI_ex bot_set_def empty_iff insert_Diff_single insert_absorb insert_is_Un mem_Collect_eq not_zero_positions_row_a_def)  \n        have sum_zero': \"sum ?f (not_zero_positions_row_a - {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0}) = 0\"\n          by (rule sum.neutral, auto, metis is_zero_row_def' rref_Gauss_Jordan rref_condition4_explicit zero_neq_one)    \n        have \"sum ?f (not_zero_positions_row_a) = sum ?f {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0} + sum ?f (not_zero_positions_row_a - {LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0})\"\n          by (subst not_zero_positions_row_a_rw, rule sum.union_disjoint[OF _ _ _], simp+)\n        also have \"... = ?f (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0)\" using sum_zero' by force\n        also have \"... = (P_Gauss_Jordan A *v b) $ a\"\n        proof (cases \"\\<exists>i. (Gauss_Jordan A) $ i $ (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0) = 1 \\<and> (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0) = (LEAST n. (Gauss_Jordan A) $ i $ n \\<noteq> 0)\")\n          case True\n          have A_least_eq_1: \"(Gauss_Jordan A) $ a $ (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0) = 1\"\n            by (metis (mono_tags) empty_Collect_eq is_zero_row_def' not_empty not_zero_positions_row_a_def rref_Gauss_Jordan rref_condition2_explicit)\n          moreover have \"(THE i. (Gauss_Jordan A) $ i $ (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0) = 1) = a\"\n          proof (rule the_equality)\n            show \"(Gauss_Jordan A) $ a $ (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0) = 1\" using A_least_eq_1 .\n            show \"\\<And>i. (Gauss_Jordan A) $ i $ (LEAST j. (Gauss_Jordan A) $ a $ j \\<noteq> 0) = 1 \\<Longrightarrow> i = a\"\n              by (metis calculation is_zero_row_def' rref_Gauss_Jordan rref_condition4_explicit zero_neq_one)\n          qed    \n          ultimately show ?thesis unfolding if_P[OF True] by simp\n        next\n          case False \n          have \"is_zero_row a (Gauss_Jordan A)\" using False rref_Gauss_Jordan rref_condition2 by blast\n          hence \"(P_Gauss_Jordan A *v b) $ a = 0\" \n            by (metis (mono_tags) IntI disj empty_iff insert_compr insert_is_Un is_zero_row_def' mem_Collect_eq not_zero_positions_row_a_rw zero_positions_row_a_def)\n          thus ?thesis unfolding if_not_P[OF False] by fastforce\n        qed\n        finally show ?thesis .\n      qed\n      finally show \"sum ?f UNIV = (P_Gauss_Jordan A *v b) $ a\" .\n    qed\n  qed\n  thus ?thesis apply (subst is_solution_solve_system)\n    unfolding solve_system_def Let_def snd_conv fst_conv unfolding Gauss_Jordan_PA_eq P_Gauss_Jordan_def .\nqed\n\ncorollary rank_ge_imp_consistent:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nassumes \"rank A \\<ge> (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0)\"\nshows \"consistent A b\"\nusing rank_ge_imp_is_solution assms unfolding consistent_def by auto\n\n\nlemma inconsistent_imp_rank_less:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes inc: \"inconsistent A b\"\n  shows \"rank A < (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0)\"\nproof (rule ccontr)\n  assume \"\\<not> rank A < (if \\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0 then to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1 else 0)\"\n  hence \"(if \\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0 then to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1 else 0) \\<le> rank A\" by simp\n  hence \"consistent A b\" using rank_ge_imp_consistent by auto\n  thus False using inc unfolding inconsistent_def by contradiction\nqed\n\n\nlemma rank_less_imp_inconsistent:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes inc: \"rank A < (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0)\"\n  shows \"inconsistent A b\"\nproof (rule ccontr)\n  define i where \"i = (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0)\"\n  define j where \"j = (GREATEST a. \\<not> is_zero_row a (Gauss_Jordan A))\"\n  assume \"\\<not> inconsistent A b\"\n  hence ex_solution: \"\\<exists>x. is_solution x A b\" unfolding inconsistent_def consistent_def by auto\n  from this obtain x where \"is_solution x A b\"  by auto\n  hence is_solution_solve: \"is_solution x (Gauss_Jordan A) (P_Gauss_Jordan A *v b)\"\n    using is_solution_solve_system\n    by (metis Gauss_Jordan_PA_eq P_Gauss_Jordan_def fst_conv snd_conv solve_system_def)\n  show False \n  proof (cases \"A=0\")\n    case True\n    hence rank_eq_0: \"rank A = 0\" using rank_0 by simp\n    hence exists_not_0:\"(\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0)\" \n      using inc unfolding inconsistent\n      using to_nat_plus_1_set[of \"(GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0)\"]\n      by presburger\n    show False\n      using True \\<open>is_solution x A b\\<close> exists_not_0 is_solution_def by force \n  next\n    case False\n    have j_less_i: \"j<i\"\n    proof -\n      have rank_less_greatest_i: \"rank A < to_nat i + 1\"\n        using inc unfolding i_def inconsistent by presburger\n      moreover have rank_eq_greatest_A: \"rank A = to_nat j + 1\" unfolding j_def by (rule rank_eq_suc_to_nat_greatest[OF False])\n      ultimately have \"to_nat j + 1 < to_nat i + 1\" by simp\n      hence \"to_nat j < to_nat i\" by auto\n      thus \"j<i\" by (metis (full_types) not_le to_nat_mono')\n    qed\n    have is_zero_i: \"is_zero_row i (Gauss_Jordan A)\" by (metis (full_types) j_def j_less_i not_greater_Greatest)\n    have \"(Gauss_Jordan A *v x) $ i = 0\" \n    proof (unfold matrix_vector_mult_def, auto, rule sum.neutral,clarify)\n      fix a::'cols\n      show \"Gauss_Jordan A $ i $ a * x $ a = 0\" using is_zero_i unfolding is_zero_row_def' by simp\n    qed\n    moreover have \"(Gauss_Jordan A *v x) $ i \\<noteq> 0\"\n    proof -\n      have \"Gauss_Jordan A *v x = P_Gauss_Jordan A *v b\" using is_solution_def is_solution_solve by blast\n      also have \"... $ i \\<noteq> 0\"\n        unfolding i_def\n      proof (rule GreatestI_ex)\n        show \"\\<exists>x. (P_Gauss_Jordan A *v b) $ x \\<noteq> 0\" using inc unfolding i_def inconsistent by presburger\n      qed\n      finally show ?thesis .\n    qed\n    ultimately show \"False\" by contradiction\n  qed\nqed\n\n\ncorollary consistent_imp_rank_ge:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes \"consistent A b\"\n  shows \"rank A \\<ge> (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0)\"\n  using rank_less_imp_inconsistent by (metis assms inconsistent_def not_less)\n\nlemma inconsistent_eq_rank_less:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"inconsistent A b = (rank A < (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) \n                                            then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0))\"\n  using inconsistent_imp_rank_less rank_less_imp_inconsistent by blast\n\nlemma consistent_eq_rank_ge:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"consistent A b = (rank A \\<ge> (if (\\<exists>a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) \n                                            then (to_nat (GREATEST a. (P_Gauss_Jordan A *v b) $ a \\<noteq> 0) + 1) else 0))\"\n  using consistent_imp_rank_ge rank_ge_imp_consistent by blast\n\ncorollary consistent_imp_is_solution:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes \"consistent A b\"\n  shows \"is_solution (solve_consistent_rref (Gauss_Jordan A) (P_Gauss_Jordan A *v b)) A b\"\n  by (rule rank_ge_imp_is_solution[OF assms[unfolded consistent_eq_rank_ge]])\n\n\ncorollary consistent_imp_is_solution':\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes \"consistent A b\"\n  shows \"is_solution (solve_consistent_rref (fst (solve_system A b)) (snd (solve_system A b))) A b\"\n  using consistent_imp_is_solution[OF assms] unfolding solve_system_def Let_def snd_conv fst_conv\n  unfolding Gauss_Jordan_PA_eq P_Gauss_Jordan_def .\n\n\ntext\\<open>Code equations optimized using Lets\\<close>\n\nlemma inconsistent_eq_rank_less_code[code]:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"inconsistent A b = (let GJ_P=Gauss_Jordan_PA A; \n                                P_mult_b = (fst(GJ_P) *v b);\n                                rank_A = (if A = 0 then 0 else to_nat (GREATEST a. row a (snd GJ_P) \\<noteq> 0) + 1)  in (rank_A < (if (\\<exists>a. P_mult_b $ a \\<noteq> 0) \n                                            then (to_nat (GREATEST a. P_mult_b $ a \\<noteq> 0) + 1) else 0)))\"\nunfolding inconsistent_eq_rank_less Let_def rank_Gauss_Jordan_code\nunfolding Gauss_Jordan_PA_eq P_Gauss_Jordan_def ..\n\n\nlemma consistent_eq_rank_ge_code[code]:\nfixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\nshows \"consistent A b = (let GJ_P=Gauss_Jordan_PA A; \n                              P_mult_b = (fst(GJ_P) *v b);\n                              rank_A = (if A = 0 then 0 else to_nat (GREATEST a. row a (snd GJ_P) \\<noteq> 0) + 1) in (rank_A \\<ge> (if (\\<exists>a. P_mult_b $ a \\<noteq> 0) \n                                            then (to_nat (GREATEST a. P_mult_b $ a \\<noteq> 0) + 1) else 0)))\"\nunfolding consistent_eq_rank_ge Let_def rank_Gauss_Jordan_code\nunfolding Gauss_Jordan_PA_eq P_Gauss_Jordan_def ..\n\n\nsubsection\\<open>Solution set of a system of equations. Dependent and independent systems.\\<close>\n\ndefinition solution_set where \"solution_set A b = {x. is_solution x A b}\"\n\nlemma null_space_eq_solution_set: \nshows \"null_space A = solution_set A 0\" unfolding null_space_def solution_set_def is_solution_def ..\n\ncorollary dim_solution_set_homogeneous_eq_dim_null_space[code_unfold]:\nshows \"vec.dim (solution_set A 0) = vec.dim (null_space A)\" using null_space_eq_solution_set[of A] by simp\n\nlemma zero_is_solution_homogeneous_system:\nshows \"0 \\<in> (solution_set A 0)\"\nunfolding solution_set_def is_solution_def\nusing matrix_vector_mult_0_right by fast\n\nlemma homogeneous_solution_set_subspace:\nfixes A::\"'a::{field}^'n^'rows\"\nshows \"vec.subspace (solution_set A 0)\"\nusing subspace_null_space[of A] unfolding null_space_eq_solution_set .\n\n\nlemma solution_set_rel:\nfixes A::\"'a::{field}^'n^'rows\"\nassumes p: \"is_solution p A b\"\nshows \"solution_set A b = {p} + (solution_set A 0)\" \nproof (unfold set_plus_def, auto)\nfix ba\nassume ba: \"ba \\<in> solution_set A 0\"\nhave \"A *v (p + ba) = (A *v p) + (A *v ba)\" unfolding matrix_vector_right_distrib ..\nalso have \"... = b\" using p ba unfolding solution_set_def is_solution_def by simp\nfinally show \"p + ba \\<in> solution_set A b\" unfolding solution_set_def is_solution_def by simp\nnext\nfix x\nassume x: \"x \\<in> solution_set A b\"\nshow \"\\<exists>b\\<in>solution_set A 0. x = p + b\"\nproof (rule bexI[of _ \"x-p\"], simp)\nhave \"A *v (x - p) = (A *v x) - (A *v p)\" by (metis (no_types) add_diff_cancel diff_add_cancel matrix_vector_right_distrib)\nalso have \"... = 0\" using x p unfolding solution_set_def is_solution_def by simp\nfinally show  \"x - p \\<in> solution_set A 0\"  unfolding solution_set_def is_solution_def by simp\nqed\nqed\n\n\nlemma independent_and_consistent_imp_uniqueness_solution:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nassumes dim_0: \"vec.dim (solution_set A 0) = 0\"\nand con: \"consistent A b\"\nshows \"\\<exists>!x. is_solution x A b\"\nproof -\nobtain p where p: \"is_solution p A b\" using con unfolding consistent_def by blast\nhave solution_set_0: \"solution_set A 0 = {0}\"\n  using vec.dim_zero_eq[OF dim_0] zero_is_solution_homogeneous_system by blast\nshow \"\\<exists>!x. is_solution x A b\"\n  proof (rule ex_ex1I)\n    show \"\\<exists>x. is_solution x A b\" using p by auto\n    fix x y assume x: \"is_solution x A b\" and y: \"is_solution y A b\"\n    have \"solution_set A b = {p} + (solution_set A 0)\" unfolding solution_set_rel[OF p] ..\n    also have \"... = {p}\" unfolding solution_set_0 set_plus_def by force\n    finally show \"x = y\" using x y unfolding solution_set_def by (metis (full_types) mem_Collect_eq singleton_iff)\nqed\nqed\n\n(*TODO: Maybe move. Until Isabelle2013-2 this lemma was part of the library.*)\nlemma card_1_exists: \"card s = 1 \\<longleftrightarrow> (\\<exists>!x. x \\<in> s)\"\n  unfolding One_nat_def\n  apply rule apply(drule card_eq_SucD) defer apply(erule ex1E) \nproof-\n fix x assume as:\"x \\<in> s\" \"\\<forall>y. y \\<in> s \\<longrightarrow> y = x\"\n have *:\"s = insert x {}\" apply - apply(rule,rule) unfolding singleton_iff     \n apply(rule as(2)[rule_format]) using as(1) by auto\n show \"card s = Suc 0\" unfolding * using card_insert by auto \nqed auto\n \n\ncorollary independent_and_consistent_imp_card_1:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nassumes dim_0: \"vec.dim (solution_set A 0) = 0\"\nand con: \"consistent A b\"\nshows \"card (solution_set A b) = 1\"\nusing independent_and_consistent_imp_uniqueness_solution[OF assms] unfolding solution_set_def \nusing card_1_exists by auto\n\nlemma uniqueness_solution_imp_independent:\nfixes A::\"'a::{field}^'n^'rows\"\nassumes ex1_sol: \"\\<exists>!x. is_solution x A b\"\nshows \"vec.dim (solution_set A 0) = 0\"\nproof -\nobtain x where x: \"is_solution x A b\" using ex1_sol by blast\nhave solution_set_homogeneous_zero: \"solution_set A 0 = {0}\"\n    proof (rule ccontr)\n    assume not_zero_set: \"solution_set A 0 \\<noteq> {0}\"\n    have homogeneous_not_empty: \"solution_set A 0 \\<noteq> {}\" by (metis empty_iff zero_is_solution_homogeneous_system)\n    obtain y where y: \"y \\<in> solution_set A 0\" and y_not_0: \"y \\<noteq> 0\" using not_zero_set homogeneous_not_empty by blast\n   have \"{x} = solution_set A b\" unfolding solution_set_def using x ex1_sol by blast      \n   also have \"... = {x} + solution_set A 0\" unfolding solution_set_rel[OF x] ..\n   finally show False \n    by (metis (hide_lams, mono_tags) add_left_cancel monoid_add_class.add.right_neutral empty_iff insert_iff set_plus_intro y y_not_0)\n   qed\nthus ?thesis using vec.dim_zero_eq' by blast\nqed\n\n\ncorollary uniqueness_solution_eq_independent_and_consistent:\nfixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\nshows \"(\\<exists>!x. is_solution x A b) = (consistent A b \\<and> vec.dim (solution_set A 0) = 0)\"\nusing independent_and_consistent_imp_uniqueness_solution uniqueness_solution_imp_independent consistent_def\nby metis\n\n\nlemma consistent_homogeneous: \nshows \"consistent A 0\" unfolding consistent_def is_solution_def using matrix_vector_mult_0_right by fast\n\nlemma dim_solution_set_0:\n  fixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\n  shows \"(vec.dim (solution_set A 0) = 0) = (solution_set A 0 = {0})\"\n  using homogeneous_solution_set_subspace vec.dim_zero_subspace_eq by auto\n\n\ntext\\<open>We have to impose the restriction \\<open>semiring_char_0\\<close> in the following lemma,\nbecause it may not hold over a general field (for instance, in Z2 there is a finite number of elements, so the solution\nset can't be infinite.\\<close>\n\nlemma dim_solution_set_not_zero_imp_infinite_solutions_homogeneous:\nfixes A::\"'a::{field, semiring_char_0}^'n::{mod_type}^'rows::{mod_type}\"\nassumes dim_not_zero: \"vec.dim (solution_set A 0) > 0\"\nshows \"infinite (solution_set A 0)\" \nproof -\nhave \"solution_set A 0 \\<noteq> {0}\" using vec.dim_zero_subspace_eq[of \"solution_set A 0\"] dim_not_zero\n  by (metis less_numeral_extra(3) vec.dim_zero_eq')\nfrom this obtain x where x: \"x \\<in> solution_set A 0\" and x_not_0: \"x \\<noteq> 0\" using vec.subspace_0[OF homogeneous_solution_set_subspace, of A] by auto\ndefine f where \"f = (\\<lambda>n::nat. (of_nat n) *s x)\"\nshow ?thesis\n  proof (unfold infinite_iff_countable_subset, rule exI[of _ f], rule conjI)\n    show \"inj f\" unfolding inj_on_def unfolding f_def using x_not_0\n      by (auto simp: vec_eq_iff)\n    show \"range f \\<subseteq> solution_set A 0\" using homogeneous_solution_set_subspace using x unfolding vec.subspace_def image_def f_def by fast\n  qed\nqed\n\nlemma infinite_solutions_homogeneous_imp_dim_solution_set_not_zero:\n  fixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\n  assumes i: \"infinite (solution_set A 0)\"\n  shows \"vec.dim (solution_set A 0) > 0\"\n  by (metis dim_solution_set_0 finite.simps gr0I i)\n\ncorollary infinite_solution_set_homogeneous_eq:\nfixes A::\"'a::{field,semiring_char_0}^'n::{mod_type}^'rows::{mod_type}\"\nshows \"infinite (solution_set A 0) = (vec.dim (solution_set A 0) > 0)\"\nusing infinite_solutions_homogeneous_imp_dim_solution_set_not_zero\nusing dim_solution_set_not_zero_imp_infinite_solutions_homogeneous by metis\n\n\ncorollary infinite_solution_set_homogeneous_eq':\nfixes A::\"'a::{field,semiring_char_0}^'n::{mod_type}^'rows::{mod_type}\"\nshows \"(\\<exists>\\<^sub>\\<infinity>x. is_solution x A 0) = (vec.dim (solution_set A 0) > 0)\"\nunfolding infinite_solution_set_homogeneous_eq[symmetric] INFM_iff_infinite unfolding solution_set_def ..\n\nlemma infinite_solution_set_imp_consistent:\n  \"infinite (solution_set A b) \\<Longrightarrow> consistent A b\"\n  by (auto dest!: infinite_imp_nonempty simp: solution_set_def consistent_def)\n\n\n\nlemma infinite_solutions_no_homogeneous_imp_dim_solution_set_not_zero_imp:\n  fixes A::\"'a::{field}^'n::{mod_type}^'rows::{mod_type}\"\n  assumes i: \"infinite (solution_set A b)\"\n  shows \"vec.dim (solution_set A 0) > 0\"\n  using i independent_and_consistent_imp_card_1 infinite_solution_set_imp_consistent by fastforce\n\ncorollary infinite_solution_set_no_homogeneous_eq:\nfixes A::\"'a::{field, semiring_char_0}^'n::{mod_type}^'rows::{mod_type}\"\nshows \"infinite (solution_set A b) = (consistent A b \\<and> vec.dim (solution_set A 0) > 0)\"\nusing dim_solution_set_not_zero_imp_infinite_solutions_no_homogeneous\nusing infinite_solutions_no_homogeneous_imp_dim_solution_set_not_zero_imp\nusing infinite_solution_set_imp_consistent by blast\n\ncorollary infinite_solution_set_no_homogeneous_eq':\nfixes A::\"'a::{field, semiring_char_0}^'n::{mod_type}^'rows::{mod_type}\"\nshows \"(\\<exists>\\<^sub>\\<infinity>x. is_solution x A b) = (consistent A b \\<and> vec.dim (solution_set A 0) > 0)\"\nunfolding infinite_solution_set_no_homogeneous_eq[symmetric] INFM_iff_infinite unfolding solution_set_def ..\n\ndefinition \"independent_and_consistent A b = (consistent A b \\<and> vec.dim (solution_set A 0) = 0)\"\ndefinition \"dependent_and_consistent A b = (consistent A b \\<and> vec.dim (solution_set A 0) > 0)\"\n\nsubsection\\<open>Solving systems of linear equations\\<close>\n\ntext\\<open>The following function will solve any system of linear equations. Given a matrix \\<open>A\\<close> and a vector \\<open>b\\<close>, \nFirstly it makes use of the funcion @{term \"solve_system\"} to transform the original matrix \\<open>A\\<close> and the vector \\<open>b\\<close> \ninto another ones in reduced row echelon form. Then, that system will have the same solution than the original one but it is easier to be solved.\nSo we make use of the function @{term \"solve_consistent_rref\"} to obtain one solution of the system.\n\nWe will prove that any solution of the system can be rewritten as a linear combination of elements of a basis of the null space plus a particular solution of the system.\nSo the function @{term \"solve\"} will return an option type, depending on the consistency of the system:\n\\begin{itemize}\n\\item If the system is consistent (so there exists at least one solution), the function will return the \\<open>Some\\<close> of a pair.\n      In the first component of that pair will be one solution of the system and the second one will be a basis of the null space of the matrix. Hence:\n    \\begin{enumerate}\n        \\item If the system is consistent and independent (so there exists one and only one solution), the pair will consist of the solution and the empty set (this empty set is \n              the basis of the null space).\n        \\item If the system is consistent and dependent (so there exists more than one solution, maybe an infinite number), \n              the pair will consist of one particular solution and a basis of the null space (which will not be the empty set).\n    \\end{enumerate}\n\\item If the system is inconsistent (so there exists no solution), the function will return \\<open>None\\<close>.\n\\end{itemize}\n\\<close>\n\ndefinition \"solve A b = (if consistent A b then \n    Some (solve_consistent_rref (fst (solve_system A b)) (snd (solve_system A b)), basis_null_space A) \n    else None)\"\n\nlemma solve_code[code]:\n  shows \"solve A b = (let GJ_P=Gauss_Jordan_PA A; \n                        P_times_b=fst(GJ_P) *v b;\n                        rank_A = (if A = 0 then 0 else to_nat (GREATEST a. row a (snd GJ_P) \\<noteq> 0) + 1);\n                        consistent_Ab = (rank_A \\<ge> (if (\\<exists>a. (P_times_b) $ a \\<noteq> 0) then (to_nat (GREATEST a. (P_times_b) $ a \\<noteq> 0) + 1) else 0));\n                        GJ_transpose = Gauss_Jordan_PA (transpose A); \n                        basis = {row i (fst GJ_transpose) | i. to_nat i \\<ge> rank_A}\n                        in (if consistent_Ab then Some (solve_consistent_rref (snd GJ_P) P_times_b,basis) else None))\"\n  unfolding Let_def solve_def\n  unfolding consistent_eq_rank_ge_code[unfolded Let_def,symmetric]\n  unfolding basis_null_space_def Let_def\n  unfolding P_Gauss_Jordan_def\n  unfolding rank_Gauss_Jordan_code Let_def Gauss_Jordan_PA_eq\n  unfolding solve_system_def Let_def fst_conv snd_conv\n  unfolding Gauss_Jordan_PA_eq ..\n\nlemma consistent_imp_is_solution_solve:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes con: \"consistent A b\"\n  shows \"is_solution (fst (the (solve A b))) A b\"\n  unfolding solve_def unfolding if_P[OF con] fst_conv using consistent_imp_is_solution'[OF con] \n  by simp\n\ncorollary consistent_eq_solution_solve:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"consistent A b = is_solution (fst (the (solve A b))) A b\"\n  by (metis consistent_def consistent_imp_is_solution_solve)\n\nlemma inconsistent_imp_solve_eq_none:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes con: \"inconsistent A b\"\n  shows \"solve A b = None\" unfolding solve_def unfolding if_not_P[OF con[unfolded inconsistent_def]] ..\n\ncorollary inconsistent_eq_solve_eq_none:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  shows \"inconsistent A b = (solve A b = None)\"\n  unfolding solve_def unfolding inconsistent_def by force\n\ntext\\<open>We demonstrate that all solutions of a system of linear equations can be expressed as a linear combination of the basis of the null space plus a particular solution\nobtained. The basis and the particular solution are obtained by means of the function @{term \"solve A b\"}\\<close>\n\nlemma solution_set_rel_solve:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes con: \"consistent A b\"\n  shows \"solution_set A b = {fst (the (solve A b))} + vec.span (snd (the (solve A b)))\"\nproof -\n  have s: \"is_solution (fst (the (solve A b))) A b\" using consistent_imp_is_solution_solve[OF con] by simp\n  have \"solution_set A b = {fst (the (solve A b))} + solution_set A 0\" using solution_set_rel[OF s] .\n  also have \"... = {fst (the (solve A b))} + vec.span (snd (the (solve A b)))\"\n    unfolding set_plus_def solve_def unfolding if_P[OF con] snd_conv fst_conv \n  proof (safe, simp_all)\n    fix b assume \"b \\<in> solution_set A 0\"\n    thus \"b \\<in> vec.span (basis_null_space A)\" unfolding null_space_eq_solution_set[symmetric] using basis_null_space[of A] by fast\n  next\n    fix b\n    assume b: \"b \\<in> vec.span (basis_null_space A)\"\n    thus \"b \\<in> solution_set A 0\" unfolding null_space_eq_solution_set[symmetric] using basis_null_space by blast\n  qed\n  finally show \"solution_set A b = {fst (the (solve A b))} + vec.span (snd (the (solve A b)))\" .\nqed\n\nlemma is_solution_eq_in_span_solve:\n  fixes A::\"'a::{field}^'cols::{mod_type}^'rows::{mod_type}\"\n  assumes con: \"consistent A b\"\n  shows \"(is_solution x A b) = (x \\<in> {fst (the (solve A b))} + vec.span (snd (the (solve A b))))\"\n  using solution_set_rel_solve[OF con] unfolding solution_set_def by auto\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gauss_Jordan/System_Of_Equations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.8774767890838837, "lm_q1q2_score": 0.7851569900836155}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection {* List Insertion and Deletion *}\n\ntheory List_Ins_Del\nimports Sorted_Less\nbegin\n\nsubsection \\<open>Elements in a list\\<close>\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (x#xs) = Set.insert x (elems xs)\"\n\nlemma elems_app: \"elems (xs @ ys) = (elems xs \\<union> elems ys)\"\nby (induction xs) auto\n\nlemma elems_eq_set: \"elems xs = set xs\"\nby (induction xs) auto\n\nlemma sorted_Cons_iff:\n  \"sorted(x # xs) = (sorted xs \\<and> (\\<forall>y \\<in> elems xs. x < y))\"\nby(simp add: elems_eq_set Sorted_Less.sorted_Cons_iff)\n\nlemma sorted_snoc_iff:\n  \"sorted(xs @ [x]) = (sorted xs \\<and> (\\<forall>y \\<in> elems xs. y < x))\"\nby(simp add: elems_eq_set Sorted_Less.sorted_snoc_iff)\n\ntext{* The above two rules introduce quantifiers. It turns out\nthat in practice this is not a problem because of the simplicity of\nthe \"isin\" functions that implement @{const elems}. Nevertheless\nit is possible to avoid the quantifiers with the help of some rewrite rules: *}\n\nlemma sorted_ConsD: \"sorted (y # xs) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> x \\<notin> elems xs\"\nby (auto simp: sorted_Cons_iff)\n\nlemma sorted_snocD: \"sorted (xs @ [y]) \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x \\<notin> elems xs\"\nby (auto simp: sorted_snoc_iff)\n\nlemmas elems_simps = sorted_lems elems_app\nlemmas elems_simps1 = elems_simps sorted_Cons_iff sorted_snoc_iff\nlemmas elems_simps2 = elems_simps sorted_ConsD sorted_snocD\n\n\nsubsection \\<open>Inserting into an ordered list without duplicates:\\<close>\n\nfun ins_list :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"ins_list x [] = [x]\" |\n\"ins_list x (a#xs) =\n  (if x < a then x#a#xs else if x=a then a#xs else a # ins_list x xs)\"\n\nlemma set_ins_list: \"elems (ins_list x xs) = insert x (elems xs)\"\nby(induction xs) auto\n\nlemma distinct_if_sorted: \"sorted xs \\<Longrightarrow> distinct xs\"\napply(induction xs rule: sorted.induct)\napply auto\nby (metis in_set_conv_decomp_first less_imp_not_less sorted_mid_iff2)\n\nlemma sorted_ins_list: \"sorted xs \\<Longrightarrow> sorted(ins_list x xs)\"\nby(induction xs rule: sorted.induct) auto\n\nlemma ins_list_sorted: \"sorted (xs @ [a]) \\<Longrightarrow>\n  ins_list x (xs @ a # ys) =\n  (if x < a then ins_list x xs @ (a#ys) else xs @ ins_list x (a#ys))\"\nby(induction xs) (auto simp: sorted_lems)\n\ntext\\<open>In principle, @{thm ins_list_sorted} suffices, but the following two\ncorollaries speed up proofs.\\<close>\n\ncorollary ins_list_sorted1: \"sorted (xs @ [a]) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  ins_list x (xs @ a # ys) = xs @ ins_list x (a#ys)\"\nby(auto simp add: ins_list_sorted)\n\ncorollary ins_list_sorted2: \"sorted (xs @ [a]) \\<Longrightarrow> x < a \\<Longrightarrow>\n  ins_list x (xs @ a # ys) = ins_list x xs @ (a#ys)\"\nby(auto simp: ins_list_sorted)\n\nlemmas ins_list_simps = sorted_lems ins_list_sorted1 ins_list_sorted2\n\ntext\\<open>Splay trees need two additional @{const ins_list} lemmas:\\<close>\n\nlemma ins_list_Cons: \"sorted (x # xs) \\<Longrightarrow> ins_list x xs = x # xs\"\nby (induction xs) auto\n\nlemma ins_list_snoc: \"sorted (xs @ [x]) \\<Longrightarrow> ins_list x xs = xs @ [x]\"\nby(induction xs) (auto simp add: sorted_mid_iff2)\n\n\nsubsection \\<open>Delete one occurrence of an element from a list:\\<close>\n\nfun del_list :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"del_list x [] = []\" |\n\"del_list x (a#xs) = (if x=a then xs else a # del_list x xs)\"\n\nlemma del_list_idem: \"x \\<notin> elems xs \\<Longrightarrow> del_list x xs = xs\"\nby (induct xs) simp_all\n\nlemma elems_del_list_eq:\n  \"distinct xs \\<Longrightarrow> elems (del_list x xs) = elems xs - {x}\"\napply(induct xs)\n apply simp\napply (simp add: elems_eq_set)\napply blast\ndone\n\nlemma sorted_del_list: \"sorted xs \\<Longrightarrow> sorted(del_list x xs)\"\napply(induction xs rule: sorted.induct)\napply auto\nby (meson order.strict_trans sorted_Cons_iff)\n\nlemma del_list_sorted: \"sorted (xs @ a # ys) \\<Longrightarrow>\n  del_list x (xs @ a # ys) = (if x < a then del_list x xs @ a # ys else xs @ del_list x (a # ys))\"\nby(induction xs)\n  (fastforce simp: sorted_lems sorted_Cons_iff elems_eq_set intro!: del_list_idem)+\n\ntext\\<open>In principle, @{thm del_list_sorted} suffices, but the following\ncorollaries speed up proofs.\\<close>\n\ncorollary del_list_sorted1: \"sorted (xs @ a # ys) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  del_list x (xs @ a # ys) = xs @ del_list x (a # ys)\"\nby (auto simp: del_list_sorted)\n\ncorollary del_list_sorted2: \"sorted (xs @ a # ys) \\<Longrightarrow> x < a \\<Longrightarrow>\n  del_list x (xs @ a # ys) = del_list x xs @ a # ys\"\nby (auto simp: del_list_sorted)\n\ncorollary del_list_sorted3:\n  \"sorted (xs @ a # ys @ b # zs) \\<Longrightarrow> x < b \\<Longrightarrow>\n  del_list x (xs @ a # ys @ b # zs) = del_list x (xs @ a # ys) @ b # zs\"\nby (auto simp: del_list_sorted sorted_lems)\n\ncorollary del_list_sorted4:\n  \"sorted (xs @ a # ys @ b # zs @ c # us) \\<Longrightarrow> x < c \\<Longrightarrow>\n  del_list x (xs @ a # ys @ b # zs @ c # us) = del_list x (xs @ a # ys @ b # zs) @ c # us\"\nby (auto simp: del_list_sorted sorted_lems)\n\ncorollary del_list_sorted5:\n  \"sorted (xs @ a # ys @ b # zs @ c # us @ d # vs) \\<Longrightarrow> x < d \\<Longrightarrow>\n   del_list x (xs @ a # ys @ b # zs @ c # us @ d # vs) =\n   del_list x (xs @ a # ys @ b # zs @ c # us) @ d # vs\" \nby (auto simp: del_list_sorted sorted_lems)\n\nlemmas del_list_simps = sorted_lems\n  del_list_sorted1\n  del_list_sorted2\n  del_list_sorted3\n  del_list_sorted4\n  del_list_sorted5\n\ntext\\<open>Splay trees need two additional @{const del_list} lemmas:\\<close>\n\nlemma del_list_notin_Cons: \"sorted (x # xs) \\<Longrightarrow> del_list x xs = xs\"\nby(induction xs)(auto simp: sorted_Cons_iff)\n\nlemma del_list_sorted_app:\n  \"sorted(xs @ [x]) \\<Longrightarrow> del_list x (xs @ ys) = xs @ del_list x ys\"\nby (induction xs) (auto simp: sorted_mid_iff2)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Data_Structures/List_Ins_Del.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7851569740970467}}
{"text": "section \\<open>Isabelle Formalization II\\<close>\n\ntheory Boo2 imports Main\nbegin \n\ntext \"Boolos's inference\" \n\nlocale boolax_2 = \n fixes F :: \" 'a \\<times> 'a \\<Rightarrow>  'a \" \n fixes s :: \" 'a \\<Rightarrow> 'a \"\n fixes D :: \" 'a \\<Rightarrow> bool \"\n fixes e ::  \" 'a \"\n assumes A1: \"F(x, e) = s(e)\"\n and A2:  \"F(e, s(y)) = s(s(F(e, y)))\"\n and A3: \"F(s(x), s(y)) = F(x, F(s(x), y))\"\n and A4:  \"D(e)\"\n and A5: \"D(x) \\<longrightarrow> D(s(x))\"\n\ncontext boolax_2\nbegin \n\ntext \"Definitions\" \n\ndefinition (in boolax_2) induct :: \"'a set \\<Rightarrow> bool\"\n where \"induct X \\<equiv> (e \\<in> X \\<and> (\\<forall>x. (x \\<in> X \\<longrightarrow> s(x) \\<in>  X)))\" \n\ndefinition (in boolax_2) N :: \"'a set\"\n where \"N = {x. (\\<forall>Y. (induct Y \\<longrightarrow> x \\<in> Y))}\" \n\ndefinition (in boolax_2) P1 :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \n  where \"P1 x y \\<equiv> F(x,y) \\<in> N\" \n\ndefinition (in boolax_2) P2 :: \"'a \\<Rightarrow> bool\"\n  where \"P2 x \\<equiv> N \\<subseteq> {y. P1 x y}\"\n\ntext \"Lemmas\" \ntext \"I. Basic Lemmas\" \n\nlemma Induction_wrt_N: \"induct X \\<longrightarrow> N \\<subseteq> X\" using N_def by auto \n\nlemma N_is_inductive: \"induct N\" by (simp add: N_def induct_def) \n\nlemma D_is_inductive: \"induct {x. D(x)}\" using A4 A5 induct_def by auto \n\nlemma Four_in_N: \"s(s(s(s(e)))) \\<in> N\" using induct_def N_is_inductive by auto \n\ntext \"II. Proof that ${x. P1 e x}$ is inductive\" \n\nlemma P1ex_basis: \"P1 e e\"  using A1 P1_def induct_def N_is_inductive by auto \n\nlemma P1ex_closed: \"P1 e x \\<longrightarrow> P1 e (s(x))\" using A2 P1_def induct_def N_is_inductive by auto \n\nlemma P1ex_inductive: \"induct {x. P1 e x}\" using induct_def P1ex_basis P1ex_closed by auto\n\ntext \"III. Proof that ${x. P2 x}$ is inductive\" \n\nlemma P1sx_basis: \"P1 (s(x)) e\" using A1 P1_def induct_def N_is_inductive by auto \n\nlemma P2_basis: \"P2 e\" by (simp add: P2_def Induction_wrt_N P1ex_inductive) \n\nlemma P2_closeda: \"P2 x \\<longrightarrow> (\\<forall>y. (P1 (s(x)) y \\<longrightarrow> P1 (s(x)) (s(y))))\"  using A3 P1_def P2_def by auto \n\nlemma P2_closedb: \"P2 x \\<longrightarrow> P2(s(x))\" using P2_def induct_def Induction_wrt_N P1sx_basis P2_closeda by auto \n\nlemma P2_inductive: \"induct {x. P2 x}\"  using induct_def P2_basis P2_closedb by auto\n\ntext \"IV. Proof that $N$ is closed under $F$\" \n\nlemma N_closed_F: \"x \\<in> N \\<and> y \\<in> N \\<longrightarrow> F(x,y) \\<in> N\"  using Induction_wrt_N P1_def P2_def P2_inductive by auto\n\ntext \"V. Conclusion\" \n\nlemma F_Four_in_D: \"D(F(s(s(s(s(e)))), s(s(s(s(e))))))\" using D_is_inductive Four_in_N N_closed_F Induction_wrt_N by auto \n\nend \nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Boolos_Curious_Inference/Boo2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107949104866, "lm_q2_score": 0.8376199592797929, "lm_q1q2_score": 0.7850264678695041}}
{"text": "(*\n  File: Partial_Equiv_Rel.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Partial equivalence relation\\<close>\n\ntheory Partial_Equiv_Rel\n  imports \"Auto2_HOL.Auto2_Main\"\nbegin\n  \ntext \\<open>\n  Partial equivalence relations, following theory\n  Lib/Partial\\_Equivalence\\_Relation in \\cite{Collections-AFP}.\n\\<close>\n\ndefinition part_equiv :: \"('a \\<times> 'a) set \\<Rightarrow> bool\" where [rewrite]:\n  \"part_equiv R \\<longleftrightarrow> sym R \\<and> trans R\"\n\nlemma part_equivI [forward]: \"sym R \\<Longrightarrow> trans R \\<Longrightarrow> part_equiv R\" by auto2\nlemma part_equivD1 [forward]: \"part_equiv R \\<Longrightarrow> sym R\" by auto2\nlemma part_equivD2 [forward]: \"part_equiv R \\<Longrightarrow> trans R\" by auto2\nsetup \\<open>del_prfstep_thm_eqforward @{thm part_equiv_def}\\<close>\n\nsubsection \\<open>Combining two elements in a partial equivalence relation\\<close>\n\ndefinition per_union :: \"('a \\<times> 'a) set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<times> 'a) set\" where [rewrite]:\n  \"per_union R a b = R \\<union> { (x,y). (x,a)\\<in>R \\<and> (b,y)\\<in>R } \\<union> { (x,y). (x,b)\\<in>R \\<and> (a,y)\\<in>R }\"\n\nlemma per_union_memI1 [backward]:\n  \"(x, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> per_union R a b\" by (simp add: per_union_def)\nsetup \\<open>add_forward_prfstep_cond @{thm per_union_memI1} [with_term \"per_union ?R ?a ?b\"]\\<close>\n\nlemma per_union_memI2 [backward]:\n  \"(x, a) \\<in> R \\<Longrightarrow> (b, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> per_union R a b\" by (simp add: per_union_def)\n\nlemma per_union_memI3 [backward]:\n  \"(x, b) \\<in> R \\<Longrightarrow> (a, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> per_union R a b\" by (simp add: per_union_def)\n\nlemma per_union_memD:\n  \"(x, y) \\<in> per_union R a b \\<Longrightarrow> (x, y) \\<in> R \\<or> ((x, a) \\<in> R \\<and> (b, y) \\<in> R) \\<or> ((x, b) \\<in> R \\<and> (a, y) \\<in> R)\"\n  by (simp add: per_union_def)\nsetup \\<open>add_forward_prfstep_cond @{thm per_union_memD} [with_cond \"?x \\<noteq> ?y\", with_filt (order_filter \"x\" \"y\")]\\<close>\nsetup \\<open>del_prfstep_thm @{thm per_union_def}\\<close>\n\nlemma per_union_is_trans [forward]:\n  \"trans R \\<Longrightarrow> trans (per_union R a b)\" by auto2\n\nlemma per_union_is_part_equiv [forward]:\n  \"part_equiv R \\<Longrightarrow> part_equiv (per_union R a b)\" by auto2\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Auto2_Imperative_HOL/Functional/Partial_Equiv_Rel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8757870046160257, "lm_q1q2_score": 0.784925307886643}}
{"text": "theory sample1\n  imports Main begin\n\n(*for chapter 2.2*)\n\nfun conj :: \"bool\\<Rightarrow>bool\\<Rightarrow>bool\" where\n  \"conj True True = True\" |\n  \"conj _ _ = False\"\n\nthm conj.induct\n\nfun add :: \"nat\\<Rightarrow>nat\\<Rightarrow>nat\" where\n  \"add 0 n = n\" |\n  \"add (Suc m) n = Suc(add m n)\"\n\nthm add.induct\n\nlemma add_02 [simp]: \"add m 0 = m\" (*reversed fist rule of add()*)\n  apply(induction m)\n  (* 1: base case\n     2: induction step\n  *)\n  apply(auto)\n  done\n\n(*inspect this lemma*)\nthm add_02\n\n(* datatype 'a list = Nil | Cons 'a \"'a list\" *)\n\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"app Nil ys = ys\" |\n  \"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nthm app.induct\nvalue \"[] = Nil\" (* True  *)\n\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n  \"rev Nil = Nil\" |\n  \"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\nthm rev.induct\n\nvalue \"rev(Cons True (Cons False Nil))\"\nvalue \"rev(Cons a(Cons b Nil))\"\n\n(*third lemma for rev_app's second subgoal*)\n(*[] = Nil*)\nlemma app_assoc [simp]: \n  \"app (app xs ys) zs = app xs (app ys zs)\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(*second lemma for rev_app*)\nlemma app_Nil2[simp]: \"app xs Nil = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(*first lemma for rev_rev*)\nlemma rev_app[simp]:\n  \"rev(app xs ys) = app (rev ys) (rev xs)\"\n  apply(induction xs)\n(*\n 1. sample1.rev (app [] ys) =\n    app (sample1.rev ys) (sample1.rev [])\n*)\n   apply(auto)\n  (*can't resolve subgoals*)\n  (*for 1: xs is Nil, deal with app_Nil2*)\n  (* 1. \\<And>a xs.\n       sample1.rev (app xs ys) =\n       app (sample1.rev ys) (sample1.rev xs) \\<Longrightarrow>\n       app (app (sample1.rev ys) (sample1.rev xs)) [a] =\n       app (sample1.rev ys) (app (sample1.rev xs) [a])\n  *)\n  (*for 2: take care of last two line, \n    deal with app_assoc*)\n  done\n\ntheorem rev_rev [simp]: \"rev(rev xs) = xs\"\n  apply(induction xs)\n  apply(auto) (*one subgoal remains*)\n  (*need to define some lemmas for next step*)\n  (*based on proof state below*)\n  done\n\n(*apply a function to all elements inside list*)\nfun map :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\" where\n  \"map f Nil = Nil\" |\n  \"map f (Cons x xs) = Cons (f x) (map f xs)\"\n\nthm map.induct\n\n(*head of list*)\nfun hd :: \"'a list\\<Rightarrow>'a\" where\n  \"hd (x # xs) = x\"\n\n(*rest part of list*)\nfun tl :: \"'a list \\<Rightarrow> 'a list\" where\n  \"tl Nil = Nil\" |\n  \"tl (x # xs) = xs\"\n\n(*need to finish: exercise 2.3*)\n\n\n\n\n\n  \n\n\n\n\n\n\n\n\n\n", "meta": {"author": "RinGotou", "repo": "Isabelle-Practice", "sha": "41fb1aff3b7a08e010055bd5c887480d09cbfa05", "save_path": "github-repos/isabelle/RinGotou-Isabelle-Practice", "path": "github-repos/isabelle/RinGotou-Isabelle-Practice/Isabelle-Practice-41fb1aff3b7a08e010055bd5c887480d09cbfa05/sample1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009642742805, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7847728613893772}}
{"text": "chapter \\<open>Homework 1\\<close>\ntheory Homework1sol\nimports Main\nbegin\n  \n  (*\n    This file is intended to be viewed within the Isabelle/jEdit IDE.\n    In a standard text-editor, it is pretty unreadable!\n  *)\n\n  (*\n    HOMEWORK #1\n\n    Sample solutions and comments\n\n  *)\n  \n\nsection \\<open>General Hints\\<close>  \n(*\n  The best way to work on this homework is to fill in the missing gaps in this file.\n\n  All solutions are a few lines only, and do, unless indicated, not require \n  to define any auxiliary functions. So if you end up with \n  lengthy and complicated function definitions, you are probably just \n  missing an easier solution.\n\n  Do not hesitate to show me your problems with your solutions, \n  eg, if Isabelle throws some cryptic error messages at you \n    that you cannot decipher ...\n\n\n*)  \n  \nsection \\<open>Odd Natural Numbers\\<close>  \n  (*\n    Write a function to return whether a given natural number is odd:\n  *)\n  \n  fun odd :: \"nat \\<Rightarrow> bool\" where\n    \"odd 0 \\<longleftrightarrow> False\"\n  | \"odd (Suc n) \\<longleftrightarrow> \\<not>odd n\"\n  \n  (*\n\n    I accepted every solution here that produced the right result,\n    a common one was\n      \"odd (Suc n) \\<longleftrightarrow> n mod 2 = 0\"\n\n    however, note, that you don't need pattern matching at all in this case, \n    and could, much simpler, write:\n  *)  \n    \n  fun odd' :: \"nat \\<Rightarrow> bool\" where \"odd' n \\<longleftrightarrow> n mod 2 = 1\"  \n    \n    \n    \n    \n  (* Test cases: *)  \n  value \"odd 45\"\n  value \"\\<not>odd 42\"\n  \nsection \\<open>Flattening of Nested Lists\\<close>    \n  (*  \n    Write a function to flatten a list of lists, i.e., \n    concatenate all lists in the given list:\n  *)  \n\n  fun flatten :: \"'a list list \\<Rightarrow> 'a list\" where\n    \"flatten [] = []\"\n  | \"flatten (l#ls) = l @ flatten ls\"  \n\n  (* \n    I ignored additions of superfluous stuff like \"[]@l@flatten ls\"\n  *)  \n    \n  (* Test cases *)  \n  value \"flatten [[1::int,2],[],[3,4],[],[5]] = [1,2,3,4,5]\"\n  value \"flatten [[],[],[],[1],[5]] = [1,5]\"\n    \n\nsection \\<open>Full Adder\\<close>    \n  (*\n    Recall that a full adder (Wikipedia has a nice entry on that) is a circuit that \n    takes three bits (two operands and a carry), and returns the \n    sum and the new carry.\n\n    We model this as two functions, one for the sum and one for the new carry.\n    Complete the function definitions!\n  *)\n\n  (* Returns the sum *)  \n  fun full_adder_s :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n    \"full_adder_s False False False = False\"\n  | \"full_adder_s False False True  = True\" \n  | \"full_adder_s False True  False = True\" \n  | \"full_adder_s False True  True  = False\" \n  | \"full_adder_s True  False False = True\" \n  | \"full_adder_s True  False True  = False\" \n  | \"full_adder_s True  True  False = False\" \n  | \"full_adder_s True  True  True  = True\" \n      \n\n  (* Returns the new carry *)  \n  fun full_adder_c :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n    \"full_adder_c False False False = False\"\n  | \"full_adder_c False False True  = False\" \n  | \"full_adder_c False True  False = False\" \n  | \"full_adder_c False True  True  = True\" \n  | \"full_adder_c True  False False = False\" \n  | \"full_adder_c True  False True  = True\" \n  | \"full_adder_c True  True  False = True\" \n  | \"full_adder_c True  True  True  = True\"\n\n    \n  (*  \n    Good demo that you can use pattern matching for encoding \n    truth-tables in a very readable way.\n  *)  \n    \nsection \\<open>Binary Numbers as Lists of Booleans\\<close>    \n  (*\n    We represent unsigned binary numbers as lists of Booleans.\n    As addition goes from least to most significant bit, and \n    lists are best processed from head to tail, the first element \n    of the list is the least significant bit.\n\n    For example:\n      [True,False,True,True] represents the number 0b1101 = 13\n      [False,False,True] represents 0b100 = 4\n\n  *)  \n\n  (* \n    Implement a function \n      to_nat :: bool list \\<Rightarrow> nat \n    that returns the value of an unsigned binary number!\n  *)  \n  fun to_nat :: \"bool list \\<Rightarrow> nat\" where\n    \"to_nat [] = 0\"\n  | \"to_nat (True#bs) = 1 + 2*to_nat bs\"  \n  | \"to_nat (False#bs) = 2*to_nat bs\"  \n    \n  (*\n    The trick was to see how one can use the recursive function call.\n    This turned out to be a bit more difficult.\n  *)  \n    \n    \n    \n  (* Test cases *)  \n  value \"to_nat [True,False,True,True] = 13\"    \n  value \"to_nat [False,False,True] = 4\"\n\nsection \\<open>Adding Binary Numbers\\<close>    \n  (* \n    Implement a function add that adds two binary numbers. \n    Hint: Start with a function addc that adds to binary numbers \n        and takes an additional carry flag.\n\n  *)  \n    \n  fun addc :: \"bool list \\<Rightarrow> bool list \\<Rightarrow> bool \\<Rightarrow> bool list\" where\n    (* Addition completed. In case of overflow, we just add another bit to our result *)\n    \"addc [] [] c = (if c then [True] else [])\"\n    (* Special cases if the numbers have different length *)\n  | \"addc (a#as) [] c = full_adder_s a False c # addc as [] (full_adder_c a False c)\"  \n  | \"addc [] (b#bs) c = full_adder_s False b c # addc [] bs (full_adder_c False b c)\"  \n    (* Standard case *)    \n  | \"addc (a#as) (b#bs) c = full_adder_s a b c # addc as bs (full_adder_c a b c)\"\n    \n\n  definition \"add as bs = addc as bs False\"  \n\n  (*\n    It was not too difficult to derive the last equation.\n  *)  \n    \n    \n  (* Test Cases *)  \n  value \"add [True,True,False] [True,True,False] = [False,True,True]\"\n  value \"add [True,False,True,False] [True,True,False,False] = [False, False, False, True]\"  \n  value \"add [True,False,True,True] [True,True,False,False] = [False, False, False, False, True]\"  \n  value \"addc [True,True,True] [True,False,True] True = [True, False, True, True]\"  \n    \n  (*\n    By the way, if you wonder whether there is something meaningful to prove:\n      You can show that your adder actually adds, wrt. your to_nat \n      interpretation. Unfortunately, the proof is a bit technical, \n      doing tons of case distinctions manually.\n  *)  \n    \n  lemma addc_correct: \n    \"to_nat (addc as bs c) = (to_nat as + to_nat bs + (if c then 1 else 0))\"\n    apply (induction as bs c rule: addc.induct)\n    apply (auto split: if_splits)  \n    apply (case_tac a; simp)  \n    apply (case_tac a; simp)  \n    apply (case_tac a; simp)  \n    apply (case_tac a; simp)  \n    apply (case_tac b; simp)  \n    apply (case_tac b; simp)  \n    apply (case_tac b; simp)  \n    apply (case_tac b; simp)  \n    apply (case_tac a; case_tac b; simp)  \n    apply (case_tac a; case_tac b; simp)  \n    apply (case_tac a; case_tac b; simp)  \n    apply (case_tac a; case_tac b; simp)  \n    done\n\n  lemma add_correct: \"to_nat (add as bs) = to_nat as + to_nat bs\"\n    using addc_correct[where c=False] unfolding add_def by auto\n      \n      \nsection \\<open>Bonus: Convert natural numbers to binary numbers\\<close>      \n      \n  fun to_bin :: \"nat \\<Rightarrow> bool list\" where\n    \"to_bin 0 = []\"\n  | \"to_bin n = (Parity.odd n # to_bin (n div 2))\"  \n\n  (*\n    Unfortunately, I saw only few correct solutions to this one ... \n    all these did it like in the above, using either the odd function \n    from the homework, or, as I did, the one from the HOL library. \n    I had to refer to it by its long name \"Parity.odd\" as the short name \"odd\" \n    is hidden by the definition of \"odd\" in this theory file.\n  *)\n    \n\n  (**\n    Again, you can prove something: converting to bin, and then to \n      nat again should be identity. Note: The other way only holds if \n      the binary number is normalized, i.e. has no zero at most significant \n      position. \n  *)  \n  lemma \"to_nat (to_bin n) = n\"\n    apply (induction n rule: to_bin.induct)\n    apply auto\n    by (metis (full_types) Suc_eq_plus1_left even_Suc even_Suc_div_two \n        even_two_times_div_two to_nat.simps(2) to_nat.simps(3))\n    \n  (* The last line of the proof was actually automatically found by some advanced \n    proof search tool of Isabelle, which I will introduce later in the lecture, after\n    the basics.\n  *)\n      \n      \n      \nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Homeworks/Homework1sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.9149009555730611, "lm_q1q2_score": 0.7847728489359577}}
{"text": "theory C2\nimports \"HOL-Algebra.Group\"\nbegin\n\nsection \\<open>The group C2\\<close>\n\ntext \\<open>\nThe two-element group is defined over the set of boolean values. This allows to \nuse the equality of boolean values as the group operation.\n\\<close>\n\ndefinition \"C2\"\n  where \"C2 = \\<lparr> carrier = UNIV, mult = (=), one = True \\<rparr>\"\n\n\n\nlemma [simp]: \"\\<one>\\<^bsub>C2\\<^esub> = True\"\n  unfolding C2_def by simp\n\nlemma [simp]: \"carrier C2 = UNIV\"\n  unfolding C2_def by simp\n\nlemma C2_is_group: \"group C2\"\n  unfolding C2_def\n  by (rule groupI, auto simp add:Units_def)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Free-Groups/C2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.8397339756938818, "lm_q1q2_score": 0.7846433693119753}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_HSortSorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Heap = Node \"Heap\" \"Nat\" \"Heap\" | Nil\n\nfun toHeap :: \"Nat list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun ordered :: \"Nat list => bool\" where\n  \"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if le x2 x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else\n      Node (hmerge (Node z x2 x3) x6) x5 x4)\"\n| \"hmerge (Node z x2 x3) (Nil) = Node z x2 x3\"\n| \"hmerge (Nil) y = y\"\n\nfun hpairwise :: \"Heap list => Heap list\" where\n  \"hpairwise (nil2) = nil2\"\n| \"hpairwise (cons2 q (nil2)) = cons2 q (nil2)\"\n| \"hpairwise (cons2 q (cons2 r qs)) =\n     cons2 (hmerge q r) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 q (nil2)) = q\"\n| \"hmerging (cons2 q (cons2 z x2)) =\n     hmerging (hpairwise (cons2 q (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"Nat list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => Nat list\" where\n  \"toList (Node q y r) = cons2 y (toList (hmerge q r))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"Nat list => Nat list\" where\n  \"hsort x = toList (toHeap2 x)\"\n\ntheorem property0 :\n  \"ordered (hsort xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_HSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7845651673671521}}
{"text": "\ntheory Lists1_6\nimports Main\nbegin\n\nprimrec sum :: \"nat list \\<Rightarrow> nat\"\nwhere\n  \"sum [] = 0\"\n| \"sum (x#xs) = x + (sum xs)\"\n\nvalue \"sum [1::nat,2]\"\n\nprimrec flatten :: \"'a list list \\<Rightarrow> 'a list\"\nwhere\n  \"flatten [] = []\"\n| \"flatten (x#xs) = x @ (flatten xs)\"\n\nvalue \"flatten []\"\nvalue \"flatten [[]]\"\nvalue \"flatten [[],[1,2],[1,3]]\"\n\nlemma \"sum [2::nat, 4, 8] = 14\"\n  by auto\n\nlemma \"flatten [[2::nat, 3], [4, 5], [7, 9]] = [2::nat,3,4,5,7,9]\"\n  by auto\n\nlemma \"length (flatten xs) = sum (map length xs)\"\n  apply (induct xs)\n  apply simp+\ndone\n\nlemma sum_append: \"sum (xs @ ys) = sum xs + sum ys\"\n  apply (induct xs)\n    apply simp\n  apply (induct ys)\n  apply simp+\ndone\n\nlemma flatten_append: \"flatten (xs @ ys) = flatten xs @ flatten ys\"\n  apply (induct xs)\n  apply (induct ys)\n  apply simp+\ndone\n\nlemma \"flatten (map rev (rev xs)) = rev (flatten xs)\"\n  apply (induct xs)\n  apply (simp add:flatten_append)+\ndone\n\nlemma \"flatten (rev (map rev xs)) = rev (flatten xs)\"\n  apply (induct xs)\n  apply (simp add:flatten_append)+\ndone\n\nlemma \"list_all (list_all P) xs = list_all P (flatten xs)\"\n  apply (induct xs)\n  apply simp+\ndone\n\nlemma \"flatten (rev xs) = flatten xs\"\n  quickcheck\noops\n\nlemma \"sum (rev xs) = sum xs\"\n  apply (induct xs)\n  apply (simp add:sum_append)+\ndone\n\nlemma \"list_all (\\<lambda>x. x\\<ge>1) xs \\<longrightarrow> length xs \\<le> sum xs\"\n  apply (induct xs)\n  apply auto\ndone\n\nprimrec list_exists:: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n  \"list_exists P [] = False\"\n| \"list_exists P (x#xs) = (P x \\<or> list_exists P xs)\"\n\nvalue \"list_exists (\\<lambda>x. x=3) []\"\nvalue \"list_exists (\\<lambda>x. x=3) [3]\"\nvalue \"list_exists (\\<lambda>x. x=3) [1::int,3]\"\n\nlemma \"list_exists (\\<lambda>n. n < 3) [4::nat, 3, 7] = False\"\n  by auto\n\nlemma \"list_exists (\\<lambda>n. n < 4) [4::nat, 3, 7] = True\"\n  by auto\n\nlemma list_exists_append: \"list_exists P (xs@ys) = (list_exists P xs \\<or> list_exists P ys)\"\n  apply (induct ys)\n    apply simp\n  apply (induct xs)\n  apply simp\n  apply auto\ndone\n\nlemma \"list_exists (list_exists P) xs = list_exists P (flatten xs)\"\n  apply (induct xs)\n  apply (simp add:list_exists_append)+\ndone\n\ndefinition list_exists2 :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n  \"list_exists2 P xs == \\<not> list_all (\\<lambda>x. \\<not> P x) xs\"\n\nlemma \"list_exists P xs = list_exists2 P xs\"\n  apply (induct xs)\n  apply (simp add:list_exists2_def)+\ndone\n\nend\n\n", "meta": {"author": "jineshkj", "repo": "cis700_assured_systems", "sha": "9fb270e519a3644f9713bee8cef082aefbc8228f", "save_path": "github-repos/isabelle/jineshkj-cis700_assured_systems", "path": "github-repos/isabelle/jineshkj-cis700_assured_systems/cis700_assured_systems-9fb270e519a3644f9713bee8cef082aefbc8228f/Isabelle_HOL_Exercies/Lists1_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.7844930838175059}}
{"text": "section \"Weights for Dijkstra's Algorithm\"\ntheory Weight\nimports Complex_Main\nbegin\n\ntext \\<open>\n  In this theory, we set up a type class for weights, and\n  a typeclass for weights with an infinity element. The latter\n  one is used internally in Dijkstra's algorithm.\n\n  Moreover, we provide a datatype that adds an infinity element to a given\n  base type.\n\\<close>\n\nsubsection \\<open>Type Classes Setup\\<close>\n\nclass weight = ordered_ab_semigroup_add + comm_monoid_add + linorder\nbegin\n\nlemma add_nonneg_nonneg [simp]:\n  assumes \"0 \\<le> a\" and \"0 \\<le> b\" shows \"0 \\<le> a + b\"\nproof -\n  have \"0 + 0 \\<le> a + b\" \n    using assms by (rule add_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_nonpos_nonpos[simp]:\n  assumes \"a \\<le> 0\" and \"b \\<le> 0\" shows \"a + b \\<le> 0\"\nproof -\n  have \"a + b \\<le> 0 + 0\"\n    using assms by (rule add_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_nonneg_eq_0_iff:\n  assumes x: \"0 \\<le> x\" and y: \"0 \\<le> y\"\n  shows \"x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (metis add.comm_neutral add.left_neutral add_left_mono antisym x y)\n\nlemma add_incr: \"0\\<le>b \\<Longrightarrow> a \\<le> a+b\"\n  by (metis add.comm_neutral add_left_mono)\n\nlemma add_incr_left[simp, intro!]: \"0\\<le>b \\<Longrightarrow> a \\<le> b + a\"\n  by (metis add_incr add.commute)\n\nlemma sum_not_less[simp, intro!]: \n  \"0\\<le>b \\<Longrightarrow> \\<not> (a+b < a)\"\n  \"0\\<le>a \\<Longrightarrow> \\<not> (a+b < b)\"\n  apply (metis add_incr less_le_not_le)\n  apply (metis add_incr_left less_le_not_le)\n  done\n\nend\n\ninstance nat :: weight ..\ninstance int :: weight ..\ninstance rat :: weight ..\ninstance real :: weight ..\n\nterm top\n\n\nclass top_weight = order_top + weight +\n  assumes inf_add_right[simp]: \"a + top = top\"\nbegin\n\nlemma inf_add_left[simp]: \"top + a = top\"\n  by (metis add.commute inf_add_right)\n\nlemmas [simp] = top_unique less_top[symmetric]\n  \nlemma not_less_inf[simp]:\n  \"\\<not> (a < top) \\<longleftrightarrow> a=top\"\n  by simp\n  \nend\n\nsubsection \\<open>Adding Infinity\\<close>\ntext \\<open>\n  We provide a standard way to add an infinity element to any type.\n\\<close>\n\ndatatype 'a infty = Infty | Num 'a\n\nprimrec val where \"val (Num d) = d\"\n\nlemma num_val_iff[simp]: \"e\\<noteq>Infty \\<Longrightarrow> Num (val e) = e\" by (cases e) auto\n\ntype_synonym NatB = \"nat infty\"\n\ninstantiation infty :: (weight) top_weight\nbegin\n  definition \"(0::'a infty) == Num 0\"\n  definition \"top \\<equiv> Infty\"\n\n  fun less_eq_infty where\n    \"less_eq Infty (Num _) \\<longleftrightarrow> False\" |\n    \"less_eq _ Infty \\<longleftrightarrow> True\" |\n    \"less_eq (Num a) (Num b) \\<longleftrightarrow> a\\<le>b\"\n\n  \n\n  fun less_infty where\n    \"less Infty _ \\<longleftrightarrow> False\" |\n    \"less (Num _) Infty \\<longleftrightarrow> True\" |\n    \"less (Num a) (Num b) \\<longleftrightarrow> a<b\"\n\n  lemma [simp]: \"less a Infty \\<longleftrightarrow> a \\<noteq> Infty\"\n    by (cases a) auto\n\n  fun plus_infty where \n    \"plus _ Infty = Infty\" |\n    \"plus Infty _ = Infty\" |\n    \"plus (Num a) (Num b) = Num (a+b)\"\n\n  lemma [simp]: \"plus Infty a = Infty\" by (cases a) simp_all\n\n\n  instance\n    apply (intro_classes)\n    apply (case_tac [!] x) [4]\n    apply simp_all\n    apply (case_tac [!] y) [3]\n    apply (simp_all add: less_le_not_le)\n    apply (case_tac z)\n    apply (simp_all add: top_infty_def zero_infty_def)\n    apply (case_tac [!] a) [4]\n    apply simp_all\n    apply (case_tac [!] b) [3]\n    apply (simp_all add: ac_simps)\n    apply (case_tac [!] c) [2]\n    apply (simp_all add: ac_simps add_right_mono)\n    apply (case_tac \"(x,y)\" rule: less_eq_infty.cases)\n    apply (simp_all add: linear)\n    done\nend\n\nsubsubsection \\<open>Unboxing\\<close>\n\ntext \\<open>Conversion between the constants defined by the\n  typeclass, and the concrete functions on the @{typ \"'a infty\"} type. \n\\<close>\nlemma infty_inf_unbox:\n  \"Num a \\<noteq> top\"\n  \"top \\<noteq> Num a\"\n  \"Infty = top\"\n  by (auto simp add: top_infty_def)\n\nlemma infty_ord_unbox:\n  \"Num a \\<le> Num b \\<longleftrightarrow> a \\<le> b\"\n  \"Num a < Num b \\<longleftrightarrow> a < b\"\n  by auto\n\nlemma infty_plus_unbox:\n  \"Num a + Num b = Num (a+b)\"\n  by (auto)\n\nlemma infty_zero_unbox:\n  \"Num a = 0 \\<longleftrightarrow> a = 0\"\n  \"Num 0 = 0\"\n  by (auto simp: zero_infty_def)\n\nlemmas infty_unbox = \n  infty_inf_unbox infty_zero_unbox infty_ord_unbox infty_plus_unbox\n\nlemma inf_not_zero[simp]:\n  \"top\\<noteq>(0::_ infty)\" \"(0::_ infty)\\<noteq>top\"\n  apply (unfold zero_infty_def top_infty_def)\n  apply auto\n  done\n\nlemma num_val_iff'[simp]: \"e\\<noteq>top \\<Longrightarrow> Num (val e) = e\" \n  by (cases e) (auto simp add: infty_unbox)\n\nlemma infty_neE: \n  \"\\<lbrakk>a\\<noteq>Infty; \\<And>d. a=Num d \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  \"\\<lbrakk>a\\<noteq>top; \\<And>d. a=Num d \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by (case_tac [!] a) (auto simp add: infty_unbox)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Dijkstra_Shortest_Path/Weight.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8633916205190225, "lm_q1q2_score": 0.7844930827383961}}
{"text": "(* author: wzh*)\n\ntheory Chapter2\n  imports Main\nbegin\n\n(* 'b option means None | Some 'b  *)\nfun lookup :: \"('a * 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup [] x = None\" |\n\"lookup ((a, b) # ps) x = (if a = x then Some b else (lookup ps x))\"\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0 = 0\"|\n\"div2 (Suc 0) = 0\" |\n\"div2 (Suc (Suc n)) = Suc (div2 n)\"\n\nlemma \"div2 n = n div 2\"\n  apply(induction n rule: div2.induct)\n   apply(auto)\n  done\n\nfun itrev :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"itrev [] ys = ys\" |\n\"itrev (x # xs) ys = itrev xs (x # ys)\"\n\nlemma \"itrev xs ys = (rev xs) @ ys\"\n  apply(induction xs arbitrary: ys)\n   apply(auto)\n  done\n\nend", "meta": {"author": "yogurt-shadow", "repo": "Isar_Exercise", "sha": "27658bff434e0845a23aeb310eeb971e4fc20b98", "save_path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise", "path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise/Isar_Exercise-27658bff434e0845a23aeb310eeb971e4fc20b98/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7844930747537333}}
{"text": "theory tape_nat_conversion\n  imports Main \"Turing\" \"../IMP-/Com\" \"../IMP-/Big_StepT\" \"../IMP-/Small_StepT\" \"../IMP-/Big_Step_Small_Step_Equivalence\"  \"../IMP-/Max_Constant\"\nbegin\n\ntext \"In this theory we prove the conversion between natural numbers and the tape as described in turing.thy . \nNote that this closely mirrors the conversion between a binary (in string format or similar) and natural numbers\"\ntype_synonym enc_tape = \"nat \\<times> nat \\<times> nat\"\nabbreviation LeftShift_nat:: \"nat \\<Rightarrow> nat\" where\n\" LeftShift_nat a \\<equiv> a + a\"\n\nsubsection \"Conversion from tape to natural\"\nfun tape_to_nat :: \"cell list \\<Rightarrow> nat\" where\n\"tape_to_nat [] = 0\" |                \n\"tape_to_nat (x#xs) = (if x = Bk then LeftShift_nat (tape_to_nat xs)\n                                   else LeftShift_nat (tape_to_nat xs) + 1)\"\n\nfun encode_tape :: \"config \\<Rightarrow> enc_tape\" where\n\"encode_tape (s,ls,rs) = (s, tape_to_nat ls, tape_to_nat rs)\"\n\nlemma t2n_0: \"(\\<forall>x\\<in> set xs. x = Bk) \\<longleftrightarrow>  tape_to_nat xs = 0 \"\n  apply(induct xs)\n   apply(auto)\n  done\n\nlemma tape_to_nat_even: \"even (tape_to_nat xs) \\<longleftrightarrow> hd xs = Bk \\<or> xs = []\"\n  apply (induct xs)\n   apply(auto)\n  done\n\nlemma tape_to_nat_odd: \" xs \\<noteq> [] \\<Longrightarrow> odd (tape_to_nat xs) \\<longleftrightarrow> hd xs = Oc\"\n  apply (induct xs)\n  using cell.exhaust by auto\n\nsubsection \"Conversion from natural to tape\"\nfun nat_to_tape :: \"nat \\<Rightarrow> cell list\" where\n\"nat_to_tape 0 = []\" |\n\"nat_to_tape n = (if (n mod 2) = 1 then Oc else Bk) # nat_to_tape (n div 2)\"\n\n\nfun decode_tape :: \"enc_tape \\<Rightarrow> config\" where\n\"decode_tape (z,n,m) = (z, nat_to_tape n, nat_to_tape m)\"\n\nlemma nat_to_tape_double[simp]: \"n > 0 \\<Longrightarrow> nat_to_tape (2 * n) = Bk # (nat_to_tape n)\"\n  apply(induct n)\n   apply(auto)\n  done\n\nlemma nat_to_tape_nth_bit: \"nat_to_tape (2^n) = replicate n Bk  @ [Oc]\"\n  apply(induct n)\n   apply(auto)\n  done\n\n\ntext \"This function is used to compare tapes with each other. Two tapes are considered equal, \nif they are the same ignoring any leading blank cells.\"\nfun is_cell_list_eq :: \"cell list \\<Rightarrow> cell list \\<Rightarrow> bool\" where \n\"is_cell_list_eq xs ys = (dropWhile (\\<lambda>x. x = Bk)(rev xs)  = dropWhile (\\<lambda>y. y = Bk) (rev ys))\"\n\n\nlemma tape_to_nat_app_bk[simp]: \"tape_to_nat (xs @ [Bk]) = tape_to_nat xs\"\n  apply(induct xs)\n   apply(auto)\n  done\n\nlemma is_cell_list_eq_same[simp]: \"is_cell_list_eq xs xs\"\n  apply(induct xs)\n   apply(auto)\n  done\n\nlemma is_cell_list_eq_com: \"is_cell_list_eq xs ys \\<Longrightarrow> is_cell_list_eq ys xs\"\n  apply(induct xs)\n   apply(auto)\n  done\n\nlemma is_cell_list_eq_cons:\n  assumes \"is_cell_list_eq xs ys\"\n  shows \"is_cell_list_eq (x#xs) (x#ys)\"\nusing assms proof -\n  have \"(dropWhile (\\<lambda>x. x = Bk)(rev xs) = dropWhile (\\<lambda>y. y = Bk) (rev ys))\" using assms by auto\n  then have \"(if (\\<forall>x\\<in>set xs.  x = Bk) then dropWhile(\\<lambda>x. x = Bk) [] else dropWhile (\\<lambda>x. x = Bk) (rev xs) @ []) = \n            (if (\\<forall>x\\<in>set ys.  x = Bk) then dropWhile(\\<lambda>x. x = Bk) [] else dropWhile (\\<lambda>x. x = Bk) (rev ys) @ [])\" \n    by (smt (verit, best) dropWhile_eq_Nil_conv set_rev)\n  then have \"(if (\\<forall>x\\<in>set xs.  x = Bk) then dropWhile(\\<lambda>x. x = Bk) [x] else dropWhile (\\<lambda>x. x = Bk) (rev xs) @ [x]) = \n            (if (\\<forall>x\\<in>set ys.  x = Bk) then dropWhile(\\<lambda>x. x = Bk) [x] else dropWhile (\\<lambda>x. x = Bk) (rev ys) @ [x])\"\n    by (smt (verit, best) \\<open>dropWhile (\\<lambda>x. x = Bk) (rev xs) = dropWhile (\\<lambda>y. y = Bk) (rev ys)\\<close> dropWhile_eq_Nil_conv set_rev)\n  then have \"(dropWhile (\\<lambda>x. x = Bk)((rev xs) @ [x]) = dropWhile (\\<lambda>y. y = Bk) ((rev ys) @ [x]))\" by (simp add: dropWhile_append)\n  then show ?thesis by simp\nqed\n\n\nlemma tape_to_nat_inverse: \"tape_to_nat(nat_to_tape n) = n\"\nproof(induct n rule: nat_to_tape.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 v)\n  then show ?case\n    proof (cases v rule: parity_cases)\n    case even\n    then have \"tape_to_nat (nat_to_tape (Suc v)) = tape_to_nat (Oc # nat_to_tape (Suc v div 2))\" by auto\n    also have \"... = 2 * tape_to_nat(nat_to_tape (Suc v div 2)) + 1\" by simp\n    also have \"... = 2 * (Suc v div 2) + 1\" using \"2\" by simp\n    then show ?thesis by (metis calculation even(1) even_Suc odd_two_times_div_two_succ)\n  next\n    case odd\n    then have \"tape_to_nat (nat_to_tape (Suc v)) = tape_to_nat (Bk # nat_to_tape (Suc v div 2))\" by simp\n    also have \"... = 2 * tape_to_nat (nat_to_tape (Suc v div 2))\" by simp\n    also have \"... = 2 * Suc v div 2\" by (metis \"2\" div_mult_swap even_Suc odd(1))\n    finally show ?thesis by auto\n        qed\nqed\n\nlemma nat_to_tape_inverse: \"is_cell_list_eq (nat_to_tape(tape_to_nat xs)) xs\"\nproof (induction xs rule: tape_to_nat.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 x xs)\n  then show ?case proof (cases x)\n    case Bk\n    then have \"is_cell_list_eq (nat_to_tape(tape_to_nat xs)) xs\" using 2 by simp\n    then have Bk_cons: \"is_cell_list_eq (Bk # nat_to_tape(tape_to_nat xs)) (Bk#xs)\" using is_cell_list_eq_cons by fast\n    consider \"(\\<forall>x\\<in>set xs. x = Bk)\" | \"Oc \\<in> set xs\" using cell.exhaust by auto\n    then have \"is_cell_list_eq (nat_to_tape(2 * tape_to_nat xs)) (Bk#xs)\" proof (cases)\n      case 1\n       then show ?thesis using t2n_0 Bk_cons by simp\n    next\n      case 2\n      then show ?thesis using Bk_cons using t2n_0 by fastforce\n    qed (* case distinction on xs all blank vs some Oc *)\n    then show ?thesis by (simp add: Bk mult_2)\n  next\n    case Oc\n    then have \"is_cell_list_eq (nat_to_tape(tape_to_nat xs)) xs\" using 2 by simp\n    then have \"is_cell_list_eq (Oc # nat_to_tape(tape_to_nat xs)) (Oc#xs)\" using is_cell_list_eq_cons by fast\n    then have \"is_cell_list_eq (nat_to_tape(2 * tape_to_nat xs + 1)) (Oc#xs)\" by simp\n    then show ?thesis by (simp add: Oc mult_2)\n  qed\nqed\n\n\nlemma encode_decode_inverse: \"(z,x,y) = encode_tape(decode_tape(z,x,y))\"\n  by (simp add: tape_to_nat_inverse)\nlemma decode_encode_inverse: \n  assumes encoded_decoded: \"(z1,x1,y1) = decode_tape(encode_tape(z,x,y))\"\n  shows \"z=z1 \\<and> is_cell_list_eq x x1 \\<and> is_cell_list_eq y y1\"\n  using encoded_decoded nat_to_tape_inverse by auto\n\n\n\n\nend", "meta": {"author": "Stixxl", "repo": "turing2while", "sha": "078b9a2970c1b376ae6e6efc8ffac134c12d5972", "save_path": "github-repos/isabelle/Stixxl-turing2while", "path": "github-repos/isabelle/Stixxl-turing2while/turing2while-078b9a2970c1b376ae6e6efc8ffac134c12d5972/turing_to_while/tape_nat_conversion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7844930592804974}}
{"text": "\ntheory Trees2_2\nimports Main\nbegin\n\n(* copied from question *)\nprimrec sum :: \"nat list \\<Rightarrow> nat\"\nwhere\n  \"sum [] = 0\"\n| \"sum (x # xs) = x + sum xs\"\n\ntheorem sum_foldr: \"sum xs = foldr (op +) xs 0\"\n  apply (induct xs)\n  apply simp\n  apply simp\ndone\n\ntheorem length_foldr: \"length xs = foldr (\\<lambda> x res. 1 + res) xs 0\"\n  apply (induct xs)\n  apply simp\n  apply simp\ndone\n\ntheorem \"sum (map (\\<lambda> x. x + 3) xs) = foldr (\\<lambda> x res. res + x + 3) xs 0\"\n  apply (induct xs)\n  apply simp\n  apply simp\ndone\n\ntheorem \"foldr g (map f xs) a = foldr (\\<lambda> x res. (g (f x) res)) xs a\"\n  apply (induct xs)\n  apply simp\n  apply simp\ndone\n\nprimrec rev_acc :: \"['a list, 'a list] \\<Rightarrow> 'a list\"\nwhere\n  \"rev_acc [] ys = ys\"\n| \"rev_acc (x#xs) ys = (rev_acc xs (x#ys))\"\n\nvalue \"rev_acc [] []\"\nvalue \"rev_acc [1,2] []\"\nvalue \"rev_acc [] [1,2]\"\nvalue \"rev_acc [1,2] [3,4]\"\n\ntheorem rev_acc_foldl: \"rev_acc xs a = foldl (\\<lambda> ys x. x # ys) a xs\"\n  apply (induct xs arbitrary:a)\n  apply simp\n  apply simp\ndone\n\ntheorem sum_append[simp]: \"sum (xs @ ys) = sum xs + sum ys\"\n  apply (induct xs)\n  apply simp\n  apply simp\ndone\n\n\n(* Unclear how the problem was solved in text *)\ntheorem foldr_append: \"foldr f (xs @ ys) a = f (foldr f xs a) (foldr f ys a)\"\n  quickcheck\noops\n\n(*\nprimrec prod :: \"nat list \\<Rightarrow> nat\"\nwhere\n  \"prod [] = 1\"\n| \"prod (x#xs) = x * prod xs\"\n*)\n\ndefinition prod: \"prod xs \\<equiv> foldr (op *) xs (1::nat)\"\n\nvalue \"prod []\"\nvalue \"prod [2]\"\nvalue \"prod [1,2,3]\"\n\n(* FIXME: unable to prove this lemma *)\ntheorem \"prod (xs @ ys) = prod xs * prod ys\"\noops\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nvalue \"Tip\"\nvalue \"Node Tip 2 Tip\"\n\nprimrec preorder :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"preorder Tip = []\"\n| \"preorder (Node l v r) = (v # preorder l) @ preorder r\"\n\nvalue \"preorder Tip\"\nvalue \"preorder (Node (Node Tip 3 Tip) 2 (Node Tip 4 Tip))\"\n\nprimrec postorder :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"postorder Tip = []\"\n| \"postorder (Node l v r) = (postorder l) @ (postorder r) @ [v]\"\n\nvalue \"postorder Tip\"\nvalue \"postorder (Node (Node Tip 3 Tip) 2 (Node Tip 4 Tip))\"\n\nfun postorder_acc:: \"['a tree, 'a list] \\<Rightarrow> 'a list\"\nwhere\n  \"postorder_acc Tip acc = acc\"\n| \"postorder_acc (Node l v r) acc = (postorder_acc l (postorder_acc r (v#acc)))\"\n\nvalue \"postorder_acc Tip []\"\nvalue \"postorder_acc (Node (Node Tip 3 Tip) 2 (Node Tip 4 Tip)) []\"\n\ntheorem \"postorder_acc t xs = (postorder t) @ xs\"\n  apply (induct t arbitrary:xs)\n  apply simp+\ndone\n\nfun foldl_tree :: \"('b => 'a => 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a tree \\<Rightarrow> 'b\"\nwhere\n  \"foldl_tree f acc Tip = acc\"\n| \"foldl_tree f acc (Node l v r) = foldl_tree f (foldl_tree f (f acc v) r) l\"\n\n\ntheorem \"\\<forall> a. postorder_acc t a = foldl_tree (\\<lambda> xs x. Cons x xs) a t\"\n  apply (induct t)\n  apply simp\n  apply simp\ndone\n\nprimrec tree_sum :: \"nat tree \\<Rightarrow> nat\"\nwhere\n  \"tree_sum Tip = 0\"\n| \"tree_sum (Node l v r) = v + (tree_sum l) + (tree_sum r)\"\n\ntheorem \"tree_sum t = sum (preorder t)\"\n  apply (induct t)\n  apply simp+\ndone\n\nend\n\n", "meta": {"author": "jineshkj", "repo": "cis700_assured_systems", "sha": "9fb270e519a3644f9713bee8cef082aefbc8228f", "save_path": "github-repos/isabelle/jineshkj-cis700_assured_systems", "path": "github-repos/isabelle/jineshkj-cis700_assured_systems/cis700_assured_systems-9fb270e519a3644f9713bee8cef082aefbc8228f/Isabelle_HOL_Exercies/Trees2_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7844693461294076}}
{"text": "(*<*)\ntheory ex09_2\nimports\n  \"~~/src/HOL/Data_Structures/Tree23_Set\"\nbegin\n(*>*)\n\ntext \\<open>\\Exercise{Joining 2-3-Trees}\n\n  Write a join function for 2-3-trees: The function shall take two\n  2-3-trees \\<open>l\\<close> and \\<open>r\\<close> and an element \\<open>x\\<close>, and return a new 2-3-tree with\n  the inorder-traversal \\<open>l x r\\<close> .\n\n  Write two functions, one for the height of \\<open>l\\<close> being greater, the\n  other for the height of \\<open>r\\<close> being greater.\n\\<close>\n\n\n\ntext \\<open>\\<open>height r\\<close> greater\\<close>\nfun joinL :: \"'a tree23 \\<Rightarrow> 'a \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a up\\<^sub>i\"\n(*<*)\nwhere\n\"joinL l x r =\n  (if height l = height r then Up\\<^sub>i l x r\n   else case r of\n     Node2 r1 a r2 \\<Rightarrow>\n       (case joinL l x r1 of\n         T\\<^sub>i t \\<Rightarrow> T\\<^sub>i (Node2 t a r2) |\n         Up\\<^sub>i t1 b t2 \\<Rightarrow> T\\<^sub>i (Node3 t1 b t2 a r2)) |\n     Node3 r1 a r2 b r3 \\<Rightarrow> (case joinL l x r1 of\n         T\\<^sub>i t \\<Rightarrow> T\\<^sub>i (Node3 t a r2 b r3) |\n         Up\\<^sub>i t1 y t2 \\<Rightarrow> Up\\<^sub>i (Node2 t1 y t2) a (Node2 r2 b r3)))\"\n(*>*)\n\nlemma bal_joinL: \"\\<lbrakk> bal l; bal r; height l \\<le> height r \\<rbrakk> \\<Longrightarrow>\n  bal (tree\\<^sub>i (joinL l x r)) \\<and> height(joinL l x r) = height r\"\n(*<*)\napply(induction r)\n  apply simp\n apply (fastforce simp: le_less split: up\\<^sub>i.split)\napply (fastforce simp: le_less split: up\\<^sub>i.split)\ndone\n(*>*)\n\nlemma inorder_joinL: \"\\<lbrakk> bal l; bal r; height l \\<le> height r \\<rbrakk> \\<Longrightarrow> inorder (tree\\<^sub>i (joinL l x r)) = inorder l @x # inorder r\"\n(*<*)\n  apply(induction r)\n  apply (auto split: up\\<^sub>i.splits)\n  done\n(*>*)\n\ntext \\<open>\\<open>height l\\<close> greater\\<close>\nfun joinR :: \"'a tree23 \\<Rightarrow> 'a \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a up\\<^sub>i\"\n(*<*)\nwhere\n\"joinR l x r =\n  (if height l = height r then Up\\<^sub>i l x r\n   else case l of\n     Node2 l1 a l2 \\<Rightarrow>\n       (case joinR l2 x r of\n         T\\<^sub>i t \\<Rightarrow> T\\<^sub>i (Node2 l1 a t) |\n         Up\\<^sub>i t1 b t2 \\<Rightarrow> T\\<^sub>i (Node3 l1 a t1 b t2)) |\n     Node3 l1 a l2 b l3 \\<Rightarrow> (case joinR l3 x r of\n         T\\<^sub>i t \\<Rightarrow> T\\<^sub>i (Node3 l1 a l2 b t) |\n         Up\\<^sub>i t1 y t2 \\<Rightarrow> Up\\<^sub>i (Node2 l1 a l2) b (Node2 t1 y t2)))\"\n(*>*)\n\nlemma bal_joinR: \"\\<lbrakk> bal l; bal r; height l \\<ge> height r \\<rbrakk> \\<Longrightarrow>\n  bal (tree\\<^sub>i (joinR l x r)) \\<and> height(joinR l x r) = height l\"\n  text \\<open>Note the generalization: We augmented the lemma with a statement about the height of the result.\\<close>\n(*<*)\napply(induction l)\n  apply simp\n apply (auto simp: le_less split!: up\\<^sub>i.splits tree23.split)[]\napply (fastforce simp: le_less split: up\\<^sub>i.split)\ndone\n(*>*)\n\nlemma inorder_joinR: \"\\<lbrakk> bal l; bal r; height l \\<ge> height r \\<rbrakk> \\<Longrightarrow> inorder (tree\\<^sub>i (joinR l x r)) = inorder l @x # inorder r\"\n(*<*)\n  apply(induction l)\n  apply simp\n  apply (auto split!: up\\<^sub>i.splits tree23.split)\n  done\n(*>*)\n\n\ntext \\<open>Combine both functions\\<close>\nfun join :: \"'a tree23 \\<Rightarrow> 'a \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a tree23\"\n(*<*)\nwhere\n\"join l x r =\n  (if height l > height r\n   then tree\\<^sub>i(joinR l x r)\n   else if height l < height r\n   then tree\\<^sub>i(joinL l x r)\n   else Node2 l x r)\"\n(*>*)\n\nlemma \"\\<lbrakk> bal l; bal r \\<rbrakk> \\<Longrightarrow> bal (join l x r)\"\n(*<*)\n  by(auto simp: bal_joinL bal_joinR simp del: joinL.simps joinR.simps)\n(*>*)\n\nlemma \"\\<lbrakk> bal l; bal r \\<rbrakk> \\<Longrightarrow> inorder (join l x r) = inorder l @x # inorder r\"\n(*<*)\n  by(auto simp: inorder_joinL inorder_joinR simp del: joinL.simps joinR.simps)\n(*>*)\n\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "amartyads", "repo": "functional-data-structures-HW", "sha": "df9edfd02bda931a0633f0e66bf8e32d7347902b", "save_path": "github-repos/isabelle/amartyads-functional-data-structures-HW", "path": "github-repos/isabelle/amartyads-functional-data-structures-HW/functional-data-structures-HW-df9edfd02bda931a0633f0e66bf8e32d7347902b/09/ex09_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9294404116305639, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7843502169648461}}
{"text": "chapter \\<open>Colored Tiles\\<close>\nsection \\<open>Challenge\\<close>\ntext_raw \\<open>{\\upshape\nThis problem is based on Project Euler problem \\#114.\n\nAlice and Bob are decorating their kitchen, and they want to add\na single row of fifty tiles on the edge of the kitchen counter.\nTiles can be either red or black, and for aesthetic reasons,\nAlice and Bob insist that red tiles come by blocks of\nat least three consecutive tiles.\nBefore starting, they wish to know how many ways\nthere are of doing this.\nThey come up with the following algorithm:\n\\begin{lstlisting}[language=C,morekeywords={procedure,function,end,to,in,var,then,not,mod}]\nvar count[51]   // count[i] is the number of valid rows of size i\ncount[0] := 1   // []\ncount[1] := 1   // [B] - cannot have a single red tile\ncount[2] := 1   // [BB] - cannot have one or two red tiles\ncount[3] := 2   // [BBB] or [RRR]\nfor n = 4 to 50 do\n    count[n] := count[n-1]  // either the row starts with a black tile\n    for k = 3 to n-1 do     // or it starts with a block of k red tiles\n        count[n] := count[n] + count[n-k-1]  // followed by a black one\n    end-for\n    count[n] := count[n]+1  // or the entire row is red\nend-for\n\\end{lstlisting}\n\n\\paragraph{Verification tasks.}\nYou should verify that at the end, \\texttt{count[50]} will contain the right number.\n\n\\bigskip\n\\noindent\\emph{Hint:}\nSince the algorithm works by enumerating the valid colorings, we expect you to give\na nice specification of a valid coloring and to prove the following properties:\n\\begin{enumerate}\n\\item Each coloring counted by the algorithm is valid.\n\\item No coloring is counted twice.\n\\item No valid coloring is missed.\n\\end{enumerate}\n}\n\\clearpage\n\\<close>\nsection \\<open>Solution\\<close>\ntheory Challenge2\nimports \"lib/VTcomp\"\nbegin\n\n  text \\<open>\n    The algorithm describes a dynamic programming scheme. \n    \n    Instead of proving the 3 properties stated in the challenge separately,\n    we approach the problem by\n    \n    \\<^enum> Giving a natural specification of a valid tiling as a grammar\n    \\<^enum> Deriving a recursion equation for the number of valid tilings\n    \\<^enum> Verifying that the program returns the correct number \n      (which obviously implies all three properties stated in the challenge)\n  \\<close>\n\n\n  subsection \\<open>Problem Specification\\<close>\n\n  subsubsection \\<open>Colors\\<close>\n\n  datatype color = R | B\n\n  subsubsection \\<open>Direct Natural Definition of a Valid Line\\<close>\n\n  inductive valid where\n    \"valid []\" |\n    \"valid xs \\<Longrightarrow> valid (B # xs)\" |\n    \"valid xs \\<Longrightarrow> n \\<ge> 3 \\<Longrightarrow> valid (replicate n R @ xs)\"\n\n  definition \"lcount n = card {l. length l=n \\<and> valid l}\"\n\n  subsection \\<open>Derivation of Recursion Equations\\<close>\n  \n  text \\<open>This alternative variant helps us to prove the split lemma below.\\<close>\n  inductive valid' where\n    \"valid' []\" |\n    \"n \\<ge> 3 \\<Longrightarrow> valid' (replicate n R)\" |\n    \"valid' xs \\<Longrightarrow> valid' (B # xs)\" |\n    \"valid' xs \\<Longrightarrow> n \\<ge> 3 \\<Longrightarrow> valid' (replicate n R @ B # xs)\"\n\n  lemma valid_valid':\n    \"valid l \\<Longrightarrow> valid' l\"\n    by (induction rule: valid.induct)\n       (auto 4 4 intro: valid'.intros elim: valid'.cases\n          simp: replicate_add[symmetric] append_assoc[symmetric]\n       )\n\n  lemmas valid_red = valid.intros(3)[OF valid.intros(1), simplified]\n\n  lemma valid'_valid:\n    \"valid' l \\<Longrightarrow> valid l\"\n    by (induction rule: valid'.induct) (auto intro: valid.intros valid_red)\n\n  lemma valid_eq_valid':\n    \"valid' l = valid l\"\n    using valid_valid' valid'_valid by metis\n\n\n  subsubsection \\<open>Additional Facts on Replicate\\<close>\n\n  lemma replicate_iff:\n    \"(\\<forall>i<length l. l ! i = R) \\<longleftrightarrow> (\\<exists> n. l = replicate n R)\"\n    by auto (metis (full_types) in_set_conv_nth replicate_eqI)\n\n  lemma replicate_iff2:\n    \"(\\<forall>i<n. l ! i = R) \\<longleftrightarrow> (\\<exists> l'. l = replicate n R @ l')\" if \"n < length l\"\n    using that by (auto simp: list_eq_iff_nth_eq nth_append intro: exI[where x = \"drop n l\"])\n\n  lemma replicate_Cons_eq:\n    \"replicate n x = y # ys \\<longleftrightarrow> (\\<exists> n'. n = Suc n' \\<and> x = y \\<and> replicate n' x = ys)\"\n    by (cases n) auto\n\n\n  subsubsection \\<open>Main Case Analysis on \\<open>@term valid\\<close>\\<close>\n\n  lemma valid_split:\n    \"valid l \\<longleftrightarrow>\n    l = [] \\<or>\n    (l!0 = B \\<and> valid (tl l)) \\<or>\n    length l \\<ge> 3 \\<and> (\\<forall> i < length l. l ! i = R) \\<or>\n    (\\<exists> j < length l. j \\<ge> 3 \\<and> (\\<forall> i < j. l ! i = R) \\<and> l ! j = B \\<and> valid (drop (j + 1) l))\"\n    unfolding valid_eq_valid'[symmetric]\n    apply standard\n    subgoal\n      by (erule valid'.cases) (auto simp: nth_append nth_Cons split: nat.splits)\n    subgoal\n      by (auto intro: valid'.intros simp: replicate_iff elim!: disjE1)\n         (fastforce intro: valid'.intros simp: neq_Nil_conv replicate_iff2 nth_append)+\n    done\n\n\n  subsubsection \\<open>Base cases\\<close>\n\n  lemma lc0_aux:\n    \"{l. l = [] \\<and> valid l} = {[]}\"\n    by (auto intro: valid.intros)\n\n  lemma lc0: \"lcount 0 = 1\"\n    by (auto simp: lc0_aux lcount_def)\n\n  lemma lc1aux: \"{l. length l=1 \\<and> valid l} = {[B]}\"  \n    by (auto intro: valid.intros elim: valid.cases simp: replicate_Cons_eq)\n\n  lemma lc2aux: \"{l. length l=2 \\<and> valid l} = {[B,B]}\"\n    by (auto 4 3 intro: valid.intros elim: valid.cases simp: replicate_Cons_eq)\n\n  lemma lc3_aux: \"{l. length l=3 \\<and> valid l} = {[B,B,B], [R,R,R]}\"\n    by (auto 4 4 intro: valid.intros valid_red[of 3, simplified] elim: valid.cases\n        simp: replicate_Cons_eq)\n\n  lemma lcounts_init: \"lcount 0 = 1\" \"lcount 1 = 1\" \"lcount 2 = 1\" \"lcount 3 = 2\"\n    using lc0 lc1aux lc2aux lc3_aux unfolding lcount_def by simp_all\n\n\n  subsubsection \\<open>The Recursion Case\\<close>\n\n  lemma finite_valid_length:\n    \"finite {l. length l = n \\<and> valid l}\" (is \"finite ?S\")\n  proof -\n    have \"?S \\<subseteq> lists {R, B} \\<inter> {l. length l = n}\"\n      by (auto intro: color.exhaust)\n    moreover have \"finite \\<dots>\"\n      by (auto intro: lists_of_len_fin1)\n    ultimately show ?thesis\n      by (rule finite_subset)\n  qed\n\n  lemma valid_line_just_B:\n    \"valid (replicate n B)\"\n    by (induction n) (auto intro: valid.intros)\n\n  lemma valid_line_aux:\n    \"{l. length l = n \\<and> valid l} \\<noteq> {}\" (is \"?S \\<noteq> {}\")\n    using valid_line_just_B[of n] by force\n\n  lemma replicate_unequal_aux:\n    \"replicate x R @ B # l \\<noteq> replicate y R @ B # l'\" (is \"?l \\<noteq> ?r\") if \\<open>x < y\\<close> for l l'\n  proof -\n    have \"?l ! x = B\" \"?r ! x = R\"\n      using that by (auto simp: nth_append)\n    then show ?thesis\n      by auto\n  qed\n\n  lemma valid_prepend_B_iff:\n    \"valid (B # xs) \\<longleftrightarrow> valid xs\"\n    by (auto intro: valid.intros elim: valid.cases simp: Cons_replicate_eq Cons_eq_append_conv)\n\n  lemma lcrec: \"lcount n = lcount (n-1) + 1 + (\\<Sum>i=3..<n. lcount (n-i-1))\" if \\<open>n>3\\<close>\n  proof -\n    have \"{l. length l = n \\<and> valid l}\n          = {l. length l = n \\<and> valid (tl l) \\<and> l!0=B}\n          \\<union> {l. length l = n \\<and>\n              (\\<exists> i. i < n \\<and> i \\<ge> 3 \\<and> (\\<forall> k < i. l!k = R) \\<and> l!i = B \\<and> valid (drop (i + 1) l))}\n          \\<union> {l. length l = n \\<and> (\\<forall>i<n. l!i=R)}\n          \" (is \"?A = ?B \\<union> ?D \\<union> ?C\")\n      using \\<open>n > 3\\<close> by (subst valid_split) auto\n  \n    let ?B1 = \"((#) B) ` {l. length l = n - Suc 0 \\<and> valid l}\"\n    from \\<open>n > 3\\<close> have \"?B = ?B1\"\n      apply safe\n      subgoal for l\n        by (cases l) (auto simp: valid_prepend_B_iff)\n      by auto\n    have 1: \"card ?B1 = lcount (n-1)\"\n      unfolding lcount_def by (auto intro: card_image)\n  \n    have \"?C = {replicate n R}\"\n      by (auto simp: nth_equalityI)\n    have 2: \"card {replicate n R} = 1\"\n      by auto\n  \n    let ?D1=\"(\\<Union> i \\<in> {3..<n}. (\\<lambda> l. replicate i R @ B # l)` {l. length l = n - i - 1 \\<and> valid l})\"\n    have \"?D =\n        (\\<Union>i \\<in> {3..<n}. {l. length l = n \\<and> (\\<forall> k < i. l!k = R) \\<and> l!i = B \\<and> valid (drop (i + 1) l)})\"\n      by auto\n    have \"{l. length l = n \\<and> (\\<forall> k < i. l!k = R) \\<and> l!i = B \\<and> valid (drop (i + 1) l)}\n              = (\\<lambda> l. replicate i R @ B # l)` {l. length l = n - i - 1 \\<and> valid l}\"\n      if \"i < n\" \"2 < i\" for i\n      apply safe\n      subgoal for l\n        apply (rule image_eqI[where x = \"drop (i + 1) l\"])\n         apply (rule nth_equalityI)\n        using that\n          apply (simp_all split: nat.split add: nth_Cons nth_append)\n        using add_diff_inverse_nat apply fastforce\n        done\n      using that by (simp add: nth_append; fail)+\n  \n    then have D_eq: \"?D = ?D1\"\n      unfolding \\<open>?D = _\\<close> by auto\n  \n    have inj: \"inj_on (\\<lambda>l. replicate x R @ B # l) {l. length l = n - Suc x \\<and> valid l}\" for x\n      unfolding inj_on_def by auto\n  \n    have *:\n      \"(\\<lambda>l. replicate x R @ B # l) ` {l. length l = n - Suc x \\<and> valid l} \\<inter>\n         (\\<lambda>l. replicate y R @ B # l) ` {l. length l = n - Suc y \\<and> valid l} = {}\"\n      if \"3 \\<le> x\" \"x < y\" \"y < n\" for x y\n      using that replicate_unequal_aux[OF \\<open>x < y\\<close>] by auto\n  \n    have 3: \"card ?D1 = (\\<Sum>i=3..<n. lcount (n-i-1))\"\n    proof (subst card_Union_disjoint, goal_cases)\n      case 1\n      show ?case\n        unfolding pairwise_def disjnt_def\n      proof (clarsimp, goal_cases)\n        case prems: (1 x y)\n        from prems show ?case\n          apply -\n          apply (rule linorder_cases[of x y])\n            apply (rule *; assumption)\n           apply (simp; fail)\n          apply (subst Int_commute; rule *; assumption)\n          done\n      qed\n    next\n      case 3\n      show ?case\n      proof (subst sum.reindex, unfold inj_on_def, clarsimp, goal_cases)\n        case prems: (1 x y)\n        with *[of y x] *[of x y] valid_line_aux[of \"n - Suc x\"] show ?case\n          by - (rule linorder_cases[of x y], auto)\n      next\n        case 2\n        then show ?case\n          by (simp add: lcount_def card_image[OF inj])\n      qed\n    qed (auto intro: finite_subset[OF _ finite_valid_length])\n  \n    show ?thesis\n      apply (subst lcount_def)\n      unfolding \\<open>?A = _\\<close> \\<open>?B = _\\<close> \\<open>?C = _\\<close> D_eq\n      apply (subst card_Un_disjoint)\n        (* Finiteness *)\n         apply (blast intro: finite_subset[OF _ finite_valid_length])+\n        (* Disjointness *)\n      subgoal\n        using Cons_replicate_eq[of B _ n R] replicate_unequal_aux by fastforce\n      apply (subst card_Un_disjoint)\n        (* Finiteness *)\n         apply (blast intro: finite_subset[OF _ finite_valid_length])+\n        (* Disjointness & final rewriting *)\n      unfolding 1 2 3\n      by (auto simp: Cons_replicate_eq Cons_eq_append_conv)\n  qed\n\nsubsection \\<open>Verification of Program\\<close>  \n  subsubsection \\<open>Inner Loop: Summation\\<close>\n  definition \"sum_prog \\<Phi> l u f \\<equiv> \n    nfoldli [l..<u] (\\<lambda>_. True) (\\<lambda>i s. doN {\n      ASSERT (\\<Phi> i); \n      RETURN (s+f i)\n    }) 0\"\n   \n  lemma sum_spec[THEN SPEC_trans, refine_vcg]: \n    assumes \"l\\<le>u\"\n    assumes \"\\<And>i. l\\<le>i \\<Longrightarrow> i<u \\<Longrightarrow> \\<Phi> i\" \n    shows \"sum_prog \\<Phi> l u f \\<le> SPEC (\\<lambda>r. r=(\\<Sum>i=l..<u. f i))\"\n    unfolding sum_prog_def\n    supply nfoldli_upt_rule[where I=\"\\<lambda>j s. s=(\\<Sum>i=l..<j. f i)\", refine_vcg]\n    apply refine_vcg\n    using assms\n    apply auto\n    done    \n\n  subsubsection \\<open>Main Program\\<close>    \n  definition \"icount M \\<equiv> doN {\n    ASSERT (M>2);\n    let c = op_array_replicate (M+1) 0;\n    let c = c[0:=1, 1:=1, 2:=1, 3:=2];\n    \n    ASSERT (\\<forall>i<4. c!i = lcount i);\n    \n    c\\<leftarrow>nfoldli [4..<M+1] (\\<lambda>_. True) (\\<lambda>n c. doN {\n      \\<^cancel>\\<open>\\<open>let sum =    (\\<Sum>i=3..<n. c!(n-i-1));\\<close>\\<close>\n      sum \\<leftarrow> sum_prog (\\<lambda>i. n-i-1 < length c) 3 n (\\<lambda>i. c!(n-i-1));\n      ASSERT (n-1<length c \\<and> n<length c);\n      RETURN (c[n := c!(n-1) + 1 + sum])\n    }) c;\n    \n    ASSERT (\\<forall>i\\<le>M. c!i = lcount i);\n    \n    ASSERT (M < length c);\n    RETURN (c!M)\n  }\"  \n  \n  subsubsection \\<open>Abstract Correctness Statement\\<close>    \n  theorem icount_correct: \"M>2 \\<Longrightarrow> icount M \\<le> SPEC (\\<lambda>r. r=lcount M)\"    \n    unfolding icount_def\n    thm nfoldli_upt_rule\n    supply nfoldli_upt_rule[where \n      I=\"\\<lambda>n c. length c = M+1 \\<and> ( \\<forall>i<n. c!i = lcount i)\", refine_vcg]\n    apply refine_vcg\n    apply (auto simp:)\n    subgoal for i\n      apply (subgoal_tac \"i\\<in>{0,1,2,3}\") using lcounts_init\n      by (auto)\n    \n    subgoal for i c j\n      apply (cases \"j<i\")\n      apply auto\n      apply (subgoal_tac \"i=j\")  \n      apply auto\n      apply (subst lcrec[where n=j])\n      apply auto\n      done\n    done            \n\n\n  subsection \\<open>Refinement to Imperative Code\\<close>  \n  sepref_definition icount_impl is \"icount\" :: \"nat_assn\\<^sup>k \\<rightarrow>\\<^sub>a nat_assn\"  \n    unfolding icount_def sum_prog_def\n    by sepref\n\n  subsubsection \\<open>Main Correctness Statement\\<close>\n  text \\<open>\n  As the main theorem, we prove the following Hoare triple, stating:\n  starting from the empty heap, our program will compute the correct result (@{term \"lcount M\"}).\n  \\<close>\n  theorem icount_impl_correct: \n    \"M>2 \\<Longrightarrow> <emp> icount_impl M <\\<lambda>r. \\<up>(r = lcount M)>\\<^sub>t\"\n  proof -\n    note A = icount_impl.refine[to_hnr, THEN hn_refineD]\n    note A = A[unfolded autoref_tag_defs]\n    note A = A[unfolded hn_ctxt_def pure_def, of M M, simplified]\n    note [sep_heap_rules] = A\n\n    assume \"M>2\"\n        \n    show ?thesis\n      using icount_correct[OF \\<open>M>2\\<close>]\n      by (sep_auto simp: refine_pw_simps pw_le_iff)    \n  qed  \n\n  subsubsection \\<open>Code Export\\<close>    \n  export_code icount_impl in SML_imp module_name Tiling    \n  export_code icount_impl in OCaml_imp module_name Tiling   \n  export_code icount_impl in Haskell module_name Tiling   \n  export_code icount_impl in Scala_imp module_name Tiling   \n\n\nsubsection \\<open>Alternative Problem Specification\\<close>  \n  text \\<open>Alternative definition of a valid line that we used in the competition\\<close>\n\ncontext fixes l :: \"color list\" begin\n\n  inductive valid_point where\n    \"\\<lbrakk>i+2<length l; l!i=R; l!(i+1) = R; l!(i+2) = R \\<rbrakk> \\<Longrightarrow> valid_point i\"\n  | \"\\<lbrakk>1\\<le>i;i+1<length l; l!(i-1)=R; l!(i) = R; l!(i+1) = R \\<rbrakk> \\<Longrightarrow> valid_point i\"\n  | \"\\<lbrakk>2\\<le>i; i<length l; l!(i-2)=R; l!(i-1) = R; l!(i) = R \\<rbrakk> \\<Longrightarrow> valid_point i\"\n  | \"\\<lbrakk> i<length l; l!i=B\\<rbrakk> \\<Longrightarrow> valid_point i\"\n\n\n  definition \"valid_line = (\\<forall>i<length l. valid_point i)\"\nend\n\nlemma valid_lineI:\n  assumes \"\\<And> i. i < length l \\<Longrightarrow> valid_point l i\"\n  shows \"valid_line l\"\n  using assms unfolding valid_line_def by auto\n\nlemma valid_B_first:\n  \"valid_point xs i \\<Longrightarrow> i < length xs \\<Longrightarrow> valid_point (B # xs) (i + 1)\"\n  by (auto intro: valid_point.intros simp: numeral_2_eq_2 elim!: valid_point.cases)\n\nlemma valid_line_prepend_B:\n  \"valid_line (B # xs)\" if \"valid_line xs\"\n  using that\n  apply -\n  apply (rule valid_lineI)\n  subgoal for i\n    by (cases i) (auto intro: valid_B_first[simplified] valid_point.intros simp: valid_line_def)\n  done\n\nlemma valid_drop_B:\n  \"valid_point xs (i - 1)\" if \"valid_point (B # xs) i\" \"i > 0\"\n  using that\n  apply cases\n     apply (fastforce intro: valid_point.intros)\n  subgoal\n    by (cases \"i = 1\") (auto intro: valid_point.intros(2))\n  subgoal\n    unfolding numeral_nat by (cases \"i = 2\") (auto intro: valid_point.intros(3))\n  apply (fastforce intro: valid_point.intros)\n  done\n\nlemma valid_line_drop_B:\n  \"valid_line xs\" if \"valid_line (B # xs)\"\n  using that unfolding valid_line_def\nproof (safe, goal_cases)\n  case (1 i)\n  with valid_drop_B[of xs \"i + 1\"] show ?case\n    by auto\nqed\n\nlemma valid_line_prepend_B_iff:\n  \"valid_line (B # xs) \\<longleftrightarrow> valid_line xs\"\n  using valid_line_prepend_B valid_line_drop_B by metis\n\nlemma cases_valid_line:\n  assumes\n    \"l = [] \\<or>\n    (l!0 = B \\<and> valid_line (tl l)) \\<or>\n    length l \\<ge> 3 \\<and> (\\<forall> i < length l. l ! i = R) \\<or>\n    (\\<exists> j < length l. j \\<ge> 3 \\<and> (\\<forall> i < j. l ! i = R) \\<and> l ! j = B \\<and> valid_line (drop (j + 1) l))\"\n    (is \"?a \\<or> ?b \\<or> ?c \\<or> ?d\")\n  shows \"valid_line l\"\nproof -\n  from assms consider (empty) ?a | (B) \"\\<not> ?a \\<and> ?b\" | (all_red) ?c | (R_B) ?d\n    by blast\n  then show ?thesis\n  proof cases\n    case empty\n    then show ?thesis\n      by (simp add: valid_line_def)\n  next\n    case B\n    then show ?thesis\n      by (cases l) (auto simp: valid_line_prepend_B_iff)\n  next\n    case prems: all_red\n    show ?thesis\n    proof (rule valid_lineI)\n      fix i assume \"i < length l\"\n      consider \"i = 0\" | \"i = 1\" | \"i > 1\"\n        by atomize_elim auto\n      then show \"valid_point l i\"\n        using \\<open>i < _\\<close> prems by cases (auto 4 4 intro: valid_point.intros)\n    qed\n  next\n    case R_B\n    then obtain j where j:\n      \"j<length l\" \"3 \\<le> j\" \"(\\<forall>i<j. l ! i = R)\" \"l ! j = B\" \"valid_line (drop (j + 1) l)\"\n      by blast\n    show ?thesis\n    proof (rule valid_lineI)\n      fix i assume \"i < length l\"\n      with \\<open>j \\<ge> 3\\<close> consider \"i \\<le> j - 3\" | \"i = j - 2\" | \"i = j - 1\" | \"i = j\" | \"i > j\"\n        by atomize_elim auto\n      then show \"valid_point l i\"\n      proof cases\n        case 5\n        with \\<open>valid_line _\\<close> \\<open>i < length l\\<close> have \"valid_point (drop (j + 1) l) (i - j - 1)\"\n          unfolding valid_line_def by auto\n        then show ?thesis\n          using \\<open>i > j\\<close> by cases (auto intro: valid_point.intros)\n      qed (use j in \\<open>auto intro: valid_point.intros\\<close>)\n    qed\n  qed\nqed\n\nlemma valid_line_cases:\n  \"l = [] \\<or>\n  (l!0 = B \\<and> valid_line (tl l)) \\<or>\n  length l \\<ge> 3 \\<and> (\\<forall> i < length l. l ! i = R) \\<or>\n  (\\<exists> j < length l. j \\<ge> 3 \\<and> (\\<forall> i < j. l ! i = R) \\<and> l ! j = B \\<and> valid_line (drop (j + 1) l))\"\n  if \"valid_line l\"\nproof (cases \"l = []\")\n  case True\n  then show ?thesis\n    by (simp add: valid_line_def)\nnext\n  case False\n  show ?thesis\n  proof (cases \"l!0 = B\")\n    case True\n    with \\<open>l \\<noteq> []\\<close> have \"l = B # tl l\"\n      by (cases l) auto\n    with \\<open>valid_line l\\<close> True show ?thesis\n      by (metis valid_line_prepend_B_iff)\n  next\n    case False\n    from \\<open>valid_line l\\<close> \\<open>l \\<noteq> []\\<close> have \"valid_point l 0\"\n      unfolding valid_line_def by auto\n    with False have red_start: \"length l \\<ge> 3\" \"l!0 = R\" \"l!1 = R\" \"l!2 = R\"\n      by (auto elim!: valid_point.cases simp: numeral_2_eq_2)\n    show ?thesis\n    proof (cases \"\\<forall>i < length l. l ! i = R\")\n      case True\n      with \\<open>length l \\<ge> 3\\<close> show ?thesis\n        by auto\n    next\n      case False\n      let ?S = \"{j. j < length l \\<and> j \\<ge> 3 \\<and> l ! j = B}\" let ?j = \"Min ?S\"\n      have B_ge_3: \"i \\<ge> 3\" if \"l ! i = B\" for i\n      proof -\n        consider \"i = 0\" | \"i = 1\" | \"i = 2\" | \"i \\<ge> 3\"\n          by atomize_elim auto\n        then show \"i \\<ge> 3\"\n          using red_start \\<open>l ! i = B\\<close> by cases auto\n      qed\n      from False obtain i where \"l ! i = B\" \"i < length l\" \"i \\<ge> 3\"\n        by (auto intro: B_ge_3 color.exhaust)\n      then have \"?j \\<in> ?S\"\n        by - (rule Min_in, auto)\n      have \"\\<forall>i < ?j. l ! i = R\"\n      proof -\n        {\n          fix i assume \"i < ?j\" \"l ! i = B\"\n          then have \"i \\<ge> 3\"\n            by (auto intro: B_ge_3)\n          with \\<open>i < ?j\\<close> \\<open>l ! i = B\\<close> red_start \\<open>?j \\<in> ?S\\<close> have \"i \\<in> ?S\"\n            by auto\n          then have \"?j \\<le> i\"\n            by (auto intro: Min_le)\n          with \\<open>i < ?j\\<close> have False\n            by simp\n        }\n        then show ?thesis\n          by (auto intro: color.exhaust)\n      qed\n      with \\<open>?j \\<in> ?S\\<close> obtain j where j: \"j < length l\" \"j \\<ge> 3\" \"\\<forall>i < j. l ! i = R\" \"l ! j = B\"\n        by blast\n      moreover have \"valid_line (drop (j + 1) l)\"\n      proof (rule valid_lineI)\n        fix i assume \"i < length (drop (j + 1) l)\"\n        with j \\<open>valid_line l\\<close> have \"valid_point l (j + i + 1)\"\n          unfolding valid_line_def by auto\n        then show \"valid_point (drop (j + 1) l) i\"\n        proof cases\n          case 2\n          then show ?thesis\n            using j by (cases i) (auto intro: valid_point.intros)\n        next\n          case prems: 3\n          consider \"i = 0\" | \"i = 1\" | \"i > 1\"\n            by atomize_elim auto\n          then show ?thesis\n            using j prems by cases (auto intro: valid_point.intros)\n        qed (auto intro: valid_point.intros)\n      qed\n      ultimately show ?thesis\n        by auto\n    qed\n  qed\nqed\n\nlemma valid_line_split:\n  \"valid_line l \\<longleftrightarrow>\n  l = [] \\<or>\n  (l!0 = B \\<and> valid_line (tl l)) \\<or>\n  length l \\<ge> 3 \\<and> (\\<forall> i < length l. l ! i = R) \\<or>\n  (\\<exists> j < length l. j \\<ge> 3 \\<and> (\\<forall> i < j. l ! i = R) \\<and> l ! j = B \\<and> valid_line (drop (j + 1) l))\"\n  using valid_line_cases cases_valid_line by blast\n\ntext \\<open>Connection to the easier definition given above\\<close>\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/VerifyThis2018/Challenge2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8991213711878917, "lm_q1q2_score": 0.7843461766245984}}
{"text": "(*  Title:      HOL/Library/Complemented_Lattices.thy\n    Authors:    Jose Manuel Rodriguez Caballero, Dominique Unruh\n*)\n\nsection \\<open>Complemented Lattices\\<close>\n\ntheory Complemented_Lattices\n  imports Main\nbegin\n\ntext \\<open>The following class \\<open>complemented_lattice\\<close> describes complemented lattices (with\n  \\<^const>\\<open>uminus\\<close> for the complement). The definition follows\n  \\<^url>\\<open>https://en.wikipedia.org/wiki/Complemented_lattice#Definition_and_basic_properties\\<close>.\n  Additionally, it adopts the convention from \\<^class>\\<open>boolean_algebra\\<close> of defining\n  \\<^const>\\<open>minus\\<close> in terms of the complement.\\<close>\n\nclass complemented_lattice = bounded_lattice + uminus + minus\n  opening lattice_syntax +\n  assumes inf_compl_bot [simp]: \\<open>x \\<sqinter> - x = \\<bottom>\\<close>\n    and sup_compl_top [simp]: \\<open>x \\<squnion> - x = \\<top>\\<close>\n    and diff_eq: \\<open>x - y = x \\<sqinter> - y\\<close>\nbegin\n\nlemma dual_complemented_lattice:\n  \"class.complemented_lattice (\\<lambda>x y. x \\<squnion> (- y)) uminus (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<lambda>x y. y < x) (\\<sqinter>) \\<top> \\<bottom>\"\nproof (rule class.complemented_lattice.intro)\n  show \"class.bounded_lattice (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<lambda>x y. y < x) (\\<sqinter>) \\<top> \\<bottom>\"\n    by (rule dual_bounded_lattice)\n  show \"class.complemented_lattice_axioms (\\<lambda>x y. x \\<squnion> - y) uminus (\\<squnion>) (\\<sqinter>) \\<top> \\<bottom>\"\n    by (unfold_locales, auto simp add: diff_eq)\nqed\n\nlemma compl_inf_bot [simp]: \\<open>- x \\<sqinter> x = \\<bottom>\\<close>\n  by (simp add: inf_commute)\n\nlemma compl_sup_top [simp]: \\<open>- x \\<squnion> x = \\<top>\\<close>\n  by (simp add: sup_commute)\n\nend\n\nclass complete_complemented_lattice = complemented_lattice + complete_lattice\n\ntext \\<open>The following class \\<open>complemented_lattice\\<close> describes orthocomplemented lattices,\n  following   \\<^url>\\<open>https://en.wikipedia.org/wiki/Complemented_lattice#Orthocomplementation\\<close>.\\<close>\nclass orthocomplemented_lattice = complemented_lattice\n  opening lattice_syntax +\n  assumes ortho_involution [simp]: \"- (- x) = x\"\n    and ortho_antimono: \"x \\<le> y \\<Longrightarrow> - x \\<ge> - y\" begin\n\nlemma dual_orthocomplemented_lattice:\n  \"class.orthocomplemented_lattice (\\<lambda>x y. x \\<squnion> - y) uminus (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<lambda>x y. y < x) (\\<sqinter>) \\<top> \\<bottom>\"\nproof (rule class.orthocomplemented_lattice.intro)\n  show \"class.complemented_lattice (\\<lambda>x y. x \\<squnion> - y) uminus (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<lambda>x y. y < x) (\\<sqinter>) \\<top> \\<bottom>\"\n    by (rule dual_complemented_lattice)\n  show \"class.orthocomplemented_lattice_axioms uminus (\\<lambda>x y. y \\<le> x)\"\n    by (unfold_locales, auto simp add: diff_eq intro: ortho_antimono)\nqed\n\nlemma compl_eq_compl_iff [simp]: \\<open>- x = - y \\<longleftrightarrow> x = y\\<close> (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\nproof\n  assume ?P\n  then have \\<open>- (- x) = - (- y)\\<close>\n    by simp\n  then show ?Q\n    by simp\nnext\n  assume ?Q\n  then show ?P\n    by simp\nqed\n\nlemma compl_bot_eq [simp]: \\<open>- \\<bottom> = \\<top>\\<close>\nproof -\n  have \\<open>- \\<bottom> = - (\\<top> \\<sqinter> - \\<top>)\\<close>\n    by simp\n  also have \\<open>\\<dots> = \\<top>\\<close>\n    by (simp only: inf_top_left) simp\n  finally show ?thesis .\nqed\n\nlemma compl_top_eq [simp]: \"- \\<top> = \\<bottom>\"\n  using compl_bot_eq ortho_involution by blast\n\ntext \\<open>De Morgan's law\\<close> \\<comment> \\<open>Proof from \\<^url>\\<open>https://planetmath.org/orthocomplementedlattice\\<close>\\<close>\nlemma compl_sup [simp]: \"- (x \\<squnion> y) = - x \\<sqinter> - y\"\nproof -\n  have \"- (x \\<squnion> y) \\<le> - x\"\n    by (simp add: ortho_antimono)\n  moreover have \"- (x \\<squnion> y) \\<le> - y\"\n    by (simp add: ortho_antimono)\n  ultimately have 1: \"- (x \\<squnion> y) \\<le> - x \\<sqinter> - y\"\n    by (simp add: sup.coboundedI1)\n  have \\<open>x \\<le> - (-x \\<sqinter> -y)\\<close>\n    by (metis inf.cobounded1 ortho_antimono ortho_involution)\n  moreover have \\<open>y \\<le> - (-x \\<sqinter> -y)\\<close>\n    by (metis inf.cobounded2 ortho_antimono ortho_involution)\n  ultimately have \\<open>x \\<squnion> y \\<le> - (-x \\<sqinter> -y)\\<close>\n    by auto\n  hence 2: \\<open>-x \\<sqinter> -y \\<le> - (x \\<squnion> y)\\<close>\n    using ortho_antimono by fastforce\n  from 1 2 show ?thesis\n    using dual_order.antisym by blast\nqed\n\ntext \\<open>De Morgan's law\\<close>\nlemma compl_inf [simp]: \"- (x \\<sqinter> y) = - x \\<squnion> - y\"\n  using compl_sup\n  by (metis ortho_involution)\n\nlemma compl_mono:\n  assumes \"x \\<le> y\"\n  shows \"- y \\<le> - x\"\n  by (simp add: assms local.ortho_antimono)\n\nlemma compl_le_compl_iff [simp]: \"- x \\<le> - y \\<longleftrightarrow> y \\<le> x\"\n  by (auto dest: compl_mono)\n\n\n\nlemma compl_le_swap2:\n  assumes \"- y \\<le> x\"\n  shows \"- x \\<le> y\"\n  using assms local.ortho_antimono by fastforce\n\nlemma compl_less_compl_iff[simp]: \"- x < - y \\<longleftrightarrow> y < x\"\n  by (auto simp add: less_le)\n\nlemma compl_less_swap1:\n  assumes \"y < - x\"\n  shows \"x < - y\"\n  using assms compl_less_compl_iff by fastforce\n\nlemma compl_less_swap2:\n  assumes \"- y < x\"\n  shows \"- x < y\"\n  using assms compl_le_swap1 compl_le_swap2 less_le_not_le by auto\n\nlemma sup_cancel_left1: \\<open>x \\<squnion> a \\<squnion> (- x \\<squnion> b) = \\<top>\\<close>\n  by (simp add: sup_commute sup_left_commute)\n\nlemma sup_cancel_left2: \\<open>- x \\<squnion> a \\<squnion> (x \\<squnion> b) = \\<top>\\<close>\n  by (simp add: sup.commute sup_left_commute)\n\nlemma inf_cancel_left1: \\<open>x \\<sqinter> a \\<sqinter> (- x \\<sqinter> b) = \\<bottom>\\<close>\n  by (simp add: inf.left_commute inf_commute)\n\nlemma inf_cancel_left2: \\<open>- x \\<sqinter> a \\<sqinter> (x \\<sqinter> b) = \\<bottom>\\<close>\n  using inf.left_commute inf_commute by auto\n\nlemma sup_compl_top_left1 [simp]: \\<open>- x \\<squnion> (x \\<squnion> y) = \\<top>\\<close>\n  by (simp add: sup_assoc[symmetric])\n\nlemma sup_compl_top_left2 [simp]: \\<open>x \\<squnion> (- x \\<squnion> y) = \\<top>\\<close>\n  using sup_compl_top_left1[of \"- x\" y] by simp\n\nlemma inf_compl_bot_left1 [simp]: \\<open>- x \\<sqinter> (x \\<sqinter> y) = \\<bottom>\\<close>\n  by (simp add: inf_assoc[symmetric])\n\nlemma inf_compl_bot_left2 [simp]: \\<open>x \\<sqinter> (- x \\<sqinter> y) = \\<bottom>\\<close>\n  using inf_compl_bot_left1[of \"- x\" y] by simp\n\nlemma inf_compl_bot_right [simp]: \\<open>x \\<sqinter> (y \\<sqinter> - x) = \\<bottom>\\<close>\n  by (subst inf_left_commute) simp\n\nend\n\nclass complete_orthocomplemented_lattice = orthocomplemented_lattice + complete_lattice\nbegin\n\nsubclass complete_complemented_lattice ..\n\nend\n\ntext \\<open>The following class \\<open>orthomodular_lattice\\<close> describes orthomodular lattices,\nfollowing   \\<^url>\\<open>https://en.wikipedia.org/wiki/Complemented_lattice#Orthomodular_lattices\\<close>.\\<close>\nclass orthomodular_lattice = orthocomplemented_lattice\n  opening lattice_syntax +\n  assumes orthomodular: \"x \\<le> y \\<Longrightarrow> x \\<squnion> (- x) \\<sqinter> y = y\" begin\n\nlemma dual_orthomodular_lattice:\n  \"class.orthomodular_lattice (\\<lambda>x y. x \\<squnion> - y) uminus (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<lambda>x y. y < x) (\\<sqinter>)  \\<top> \\<bottom>\"\nproof (rule class.orthomodular_lattice.intro)\n  show \"class.orthocomplemented_lattice (\\<lambda>x y. x \\<squnion> - y) uminus (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<lambda>x y. y < x) (\\<sqinter>) \\<top> \\<bottom>\"\n    by (rule dual_orthocomplemented_lattice)\n  show \"class.orthomodular_lattice_axioms uminus (\\<squnion>) (\\<lambda>x y. y \\<le> x) (\\<sqinter>)\"\n  proof (unfold_locales)\n    show \"(x::'a) \\<sqinter> (- x \\<squnion> y) = y\"\n      if \"(y::'a) \\<le> x\"\n      for x :: 'a\n        and y :: 'a\n      using that local.compl_eq_compl_iff local.ortho_antimono local.orthomodular by fastforce\n  qed\n\nqed\n\nend\n\nclass complete_orthomodular_lattice = orthomodular_lattice + complete_lattice\nbegin\n\nsubclass complete_orthocomplemented_lattice ..\n\nend\n\ncontext boolean_algebra\n  opening lattice_syntax\nbegin\n\nsubclass orthomodular_lattice\nproof\n  fix x y\n  show \\<open>x \\<squnion> - x \\<sqinter> y = y\\<close>\n    if \\<open>x \\<le> y\\<close>\n    using that\n    by (simp add: sup.absorb_iff2 sup_inf_distrib1)\n  show \\<open>x - y = x \\<sqinter> - y\\<close>\n    by (simp add: diff_eq)\nqed auto\n\nend\n\ncontext complete_boolean_algebra\nbegin\n\nsubclass complete_orthomodular_lattice ..\n\nend\n\nlemma image_of_maximum:\n  fixes f::\"'a::order \\<Rightarrow> 'b::conditionally_complete_lattice\"\n  assumes \"mono f\"\n    and \"\\<And>x. x:M \\<Longrightarrow> x\\<le>m\"\n    and \"m:M\"\n  shows \"(SUP x\\<in>M. f x) = f m\"\n  by (smt (verit, ccfv_threshold) assms(1) assms(2) assms(3) cSup_eq_maximum imageE imageI monoD)\n\nlemma cSup_eq_cSup:\n  fixes A B :: \\<open>'a::conditionally_complete_lattice set\\<close>\n  assumes bdd: \\<open>bdd_above A\\<close>\n  assumes B: \\<open>\\<And>a. a\\<in>A \\<Longrightarrow> \\<exists>b\\<in>B. b \\<ge> a\\<close>\n  assumes A: \\<open>\\<And>b. b\\<in>B \\<Longrightarrow> \\<exists>a\\<in>A. a \\<ge> b\\<close>\n  shows \\<open>Sup A = Sup B\\<close>\nproof (cases \\<open>B = {}\\<close>)\n  case True\n  with A B have \\<open>A = {}\\<close>\n    by auto\n  with True show ?thesis by simp\nnext\n  case False\n  have \\<open>bdd_above B\\<close>\n    by (meson A bdd bdd_above_def order_trans)\n  have \\<open>A \\<noteq> {}\\<close>\n    using A False by blast\n  moreover have \\<open>a \\<le> Sup B\\<close> if \\<open>a \\<in> A\\<close> for a\n  proof -\n    obtain b where \\<open>b \\<in> B\\<close> and \\<open>b \\<ge> a\\<close>\n      using B \\<open>a \\<in> A\\<close> by auto\n    then show ?thesis\n      apply (rule cSup_upper2)\n      using \\<open>bdd_above B\\<close> by simp\n  qed\n  moreover have \\<open>Sup B \\<le> c\\<close> if \\<open>\\<And>a. a \\<in> A \\<Longrightarrow> a \\<le> c\\<close> for c\n    using False apply (rule cSup_least)\n    using A that by fastforce\n  ultimately show ?thesis\n    by (rule cSup_eq_non_empty)\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Complemented_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473779969193, "lm_q2_score": 0.8991213725394588, "lm_q1q2_score": 0.7843461718357881}}
{"text": "(*<*)\ntheory Brent\nimports\n  Basis\nbegin\n(*>*)\nsection\\<open> Brent's algorithm \\label{sec:brent} \\<close>\n\ntext\\<open>\n\n@{cite \"Brent:1980\"} improved on the Tortoise and Hare algorithm and\nused it to factor large primes. In practice it makes significantly\nfewer calls to the function \\<open>f\\<close> before detecting a loop.\n\nWe begin by defining the base-2 logarithm.\n\n\\<close>\n\nfun lg :: \"nat \\<Rightarrow> nat\" where\n[simp del]: \"lg x = (if x \\<le> 1 then 0 else 1 + lg (x div 2))\"\n\nlemma lg_safe:\n  \"lg 0 = 0\"\n  \"lg (Suc 0) = 0\"\n  \"lg (Suc (Suc 0)) = 1\"\n  \"0 < x \\<Longrightarrow> lg (x + x) = 1 + lg x\"\nby (simp_all add: lg.simps)\n\nlemma lg_inv:\n  \"0 < x \\<Longrightarrow> lg (2 ^ x) = x\"\nproof(induct x)\n  case (Suc x) then show ?case\n    by (cases x, simp_all add: lg.simps Suc_lessI not_le)\nqed simp\n\nlemma lg_inv2:\n  \\<open>2 ^ lg x = x\\<close> if \\<open>2 ^ i = x\\<close> for x\nproof -\n  have \\<open>2 ^ lg (2 ^ i) = (2::nat) ^ i\\<close>\n    by (induction i) (simp_all add: lg_safe mult_2)\n  with that show ?thesis\n    by simp\nqed\n\nlemmas lg_simps = lg_safe lg_inv lg_inv2\n\nsubsection\\<open> Finding \\<open>lambda\\<close> \\<close>\n\ntext (in properties) \\<open>\n\nImagine now that the Tortoise carries an unbounded number of carrots,\nwhich he passes to the Hare when they meet, and the Hare has a\nteleporter. The Hare eats a carrot each time she waits for the\nfunction @{term \"f\"} to execute, and initially has just one. If she\nruns out of carrots before meeting the Tortoise again, she teleports\nhim to her position, and he gives her twice as many carrots as the\nlast time they met (tracked by the variable \\<open>carrots\\<close>). By\ncounting how many carrots she has eaten from when she last teleported\nthe Tortoise (recorded in \\<open>l\\<close>) until she finally has surplus\ncarrots when she meets him again, the Hare directly discovers @{term\n\"lambda\"}.\n\n\\<close>\n\nrecord 'a state =\n  m :: nat  \\<comment> \\<open>\\<open>\\<mu>\\<close>\\<close>\n  l :: nat  \\<comment> \\<open>\\<open>\\<lambda>\\<close>\\<close>\n  carrots :: nat\n  hare :: \"'a\"\n  tortoise :: \"'a\"\n\ncontext properties\nbegin\n\ndefinition (in fx0) find_lambda :: \"'a state \\<Rightarrow> 'a state\" where\n  \"find_lambda \\<equiv>\n    (\\<lambda>s. s\\<lparr> carrots := 1, l := 1, tortoise := x0, hare := f x0 \\<rparr>) ;;\n    while (hare \\<^bold>\\<noteq> tortoise)\n          ( ( \\<^bold>if carrots \\<^bold>= l \\<^bold>then (\\<lambda>s. s\\<lparr> tortoise := hare s, carrots := 2 * carrots s, l := 0 \\<rparr>)\n                             \\<^bold>else SKIP ) ;;\n            (\\<lambda>s. s\\<lparr> hare := f (hare s), l := l s + 1 \\<rparr>) )\"\n\ntext\\<open>\n\nThe termination argument goes intuitively as follows. The Hare eats as\nmany carrots as it takes to teleport the Tortoise into the\nloop. Afterwards she continues the teleportation dance until the\nTortoise has given her enough carrots to make it all the way around\nthe loop and back to him.\n\nWe can calculate the Tortoise's position as a function of \\<open>carrots\\<close>.\n\n\\<close>\n\ndefinition carrots_total :: \"nat \\<Rightarrow> nat\" where\n  \"carrots_total c \\<equiv> \\<Sum>i<lg c. 2 ^ i\"\n\nlemma carrots_total_simps:\n  \"carrots_total (Suc 0) = 0\"\n  \"carrots_total (Suc (Suc 0)) = 1\"\n  \"2 ^ i = c \\<Longrightarrow> carrots_total (c + c) = c + carrots_total c\"\nby (auto simp: carrots_total_def lg_simps)\n\ndefinition find_lambda_measures :: \"( (nat \\<times> nat) \\<times> (nat \\<times> nat) ) set\" where\n  \"find_lambda_measures \\<equiv>\n    measures [\\<lambda>(l, c). mu - carrots_total c,\n              \\<lambda>(l, c). LEAST i. lambda \\<le> c * 2^i,\n              \\<lambda>(l, c). c - l]\"\n\nlemma find_lambda_measures_wellfounded:\n  \"wf find_lambda_measures\"\nby (simp add: find_lambda_measures_def)\n\nlemma find_lambda_measures_decreases1:\n  assumes \"c = 2 ^ i\"\n  assumes \"mu \\<le> carrots_total c \\<longrightarrow> c \\<le> lambda\"\n  assumes \"seq (carrots_total c) \\<noteq> seq (carrots_total c + c)\"\n  shows \"( (c', 2 * c), (c, c) ) \\<in> find_lambda_measures\"\nproof(cases \"mu \\<le> carrots_total c\")\n  case False with assms show ?thesis\n    by (auto simp: find_lambda_measures_def carrots_total_simps mult_2 field_simps diff_less_mono2)\nnext\n  case True\n  { fix x assume x: \"(0::nat) < x\" have \"\\<exists>n. lambda \\<le> x * 2 ^ n\"\n    proof(induct lambda)\n      case (Suc i)\n      then obtain n where \"i \\<le> x * 2 ^ n\" by blast\n      with x show ?case\n        by (clarsimp intro!: exI[where x=\"Suc n\"] simp: field_simps mult_2)\n           (metis Nat.add_0_right Suc_leI linorder_neqE_nat mult_eq_0_iff add_left_cancel not_le numeral_2_eq_2 old.nat.distinct(2) power_not_zero trans_le_add2)\n    qed simp } note ex = this\n  have \"(LEAST j. lambda \\<le> 2 ^ (i + 1) * 2 ^ j) < (LEAST j. lambda \\<le> 2 ^ i * 2 ^ j)\"\n  proof(rule LeastI2_wellorder_ex[OF ex, rotated], rule LeastI2_wellorder_ex[OF ex, rotated])\n    fix x y\n    assume \"lambda \\<le> 2 ^ i * 2 ^ y\"\n           \"lambda \\<le> 2 ^ (i + 1) * 2 ^ x\"\n           \"\\<forall>z. lambda \\<le> 2 ^ (i + 1) * 2 ^ z \\<longrightarrow> x \\<le> z\"\n    with True assms properties_loop[where i=\"carrots_total c\" and j=1]\n    show \"x < y\" by (cases y, auto simp: less_Suc_eq_le)\n  qed simp_all\n  with True \\<open>c = 2 ^ i\\<close> show ?thesis\n    by (clarsimp simp: find_lambda_measures_def mult_2 carrots_total_simps field_simps power_add)\nqed\n\nlemma find_lambda_measures_decreases2:\n  assumes \"ls < c\"\n  shows \"( (Suc ls, c), (ls, c) ) \\<in> find_lambda_measures\"\nusing assms by (simp add: find_lambda_measures_def)\n\nlemma find_lambda:\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> find_lambda \\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle>\\<rbrace>\"\napply (simp add: find_lambda_def)\napply (rule hoare_pre)\napply (rule whileI[where I=\"\\<langle>0\\<rangle> \\<^bold>< l \\<^bold>\\<and> l \\<^bold>\\<le> carrots \\<^bold>\\<and> (\\<langle>mu\\<rangle> \\<^bold>\\<le> carrots_total \\<circ> carrots \\<^bold>\\<longrightarrow> l \\<^bold>\\<le> \\<langle>lambda\\<rangle>) \\<^bold>\\<and> (\\<^bold>\\<exists>i. carrots \\<^bold>= \\<langle>2^i\\<rangle>)\n                           \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> carrots_total \\<circ> carrots \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (l \\<^bold>+ (carrots_total \\<circ> carrots))\"\n                      and r=\"inv_image find_lambda_measures (l \\<^bold>\\<bowtie> carrots)\"]\n            wp_intro)+\n   using properties_lambda_gt_0\n   apply (clarsimp simp: field_simps mult_2_right carrots_total_simps)\n   apply (intro conjI impI)\n      apply (metis mult_2 power_Suc)\n     apply (case_tac \"mu \\<le> carrots_total (l s)\")\n      apply (cut_tac i=\"carrots_total (l s)\" and j=\"l s\" in properties_distinct_contrapos, simp_all add: field_simps)[1]\n     apply (cut_tac i=\"carrots_total (l s)\" and j=\"l s\" in properties_loops_ge_mu, simp_all add: field_simps)[1]\n    apply (cut_tac i=\"carrots_total (2 ^ x)\" and j=1 in properties_loop, simp)\n    apply (fastforce simp: le_eq_less_or_eq field_simps)\n   apply (cut_tac i=\"carrots_total (2 ^ x)\" and j=\"l s\" in properties_loops_ge_mu, simp_all add: field_simps)[1]\n   apply (cut_tac i=\"carrots_total (2 ^ x)\" and j=\"l s\" in properties_distinct_contrapos, simp_all add: field_simps)[1]\n  apply (simp add: find_lambda_measures_wellfounded)\n apply (clarsimp simp: add.commute find_lambda_measures_decreases1 find_lambda_measures_decreases2)\napply (rule wp_intro)\nusing properties_lambda_gt_0\napply (simp add: carrots_total_simps exI[where x=0])\ndone\n\nsubsection\\<open> Finding \\<open>mu\\<close> \\<close>\n\ntext\\<open>\n\nWith @{term \"lambda\"} in hand, we can find \\<open>mu\\<close> using the same\napproach as for the Tortoise and Hare (\\S\\ref{sec:th-finding-mu}),\nafter we first move the Hare to @{term \"lambda\"}.\n\n\\<close>\n\ndefinition (in fx0) find_mu :: \"'a state \\<Rightarrow> 'a state\" where\n  \"find_mu \\<equiv>\n    (\\<lambda>s. s\\<lparr> m := 0, tortoise := x0, hare := seq (l s) \\<rparr>) ;;\n    while (hare \\<^bold>\\<noteq> tortoise)\n          (\\<lambda>s. s\\<lparr> tortoise := f (tortoise s), hare := f (hare s), m := m s + 1 \\<rparr>)\"\n\nlemma find_mu:\n  \"\\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle>\\<rbrace> find_mu \\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\napply (simp add: find_mu_def)\napply (rule hoare_pre)\napply (rule whileI[where I=\"l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>\\<le> \\<langle>mu\\<rangle> \\<^bold>\\<and> tortoise \\<^bold>= seq \\<circ> m \\<^bold>\\<and> hare \\<^bold>= seq \\<circ> (m \\<^bold>+ l)\"\n                      and r=\"measure (\\<langle>mu\\<rangle> \\<^bold>- m)\"]\n            wp_intro)+\n   using properties_lambda_gt_0 properties_loop[where i=mu and j=1]\n   apply (fastforce simp: le_less dest: properties_loops_ge_mu)\n  apply simp\n using properties_loop[where i=mu and j=1, simplified]\n apply (fastforce simp: le_eq_less_or_eq)\napply (rule wp_intro)\napply simp\ndone\n\n\nsubsection\\<open> Top level \\<close>\n\ndefinition (in fx0) brent :: \"'a state \\<Rightarrow> 'a state\" where\n  \"brent \\<equiv> find_lambda ;; find_mu\"\n\ntheorem brent:\n  \"\\<lbrace>\\<langle>True\\<rangle>\\<rbrace> brent \\<lbrace>l \\<^bold>= \\<langle>lambda\\<rangle> \\<^bold>\\<and> m \\<^bold>= \\<langle>mu\\<rangle>\\<rbrace>\"\nunfolding brent_def\nby (rule find_lambda find_mu wp_intro)+\n\nend\n\ncorollary brent_correct:\n  assumes s': \"s' = fx0.brent f x arbitrary\"\n  shows \"fx0.properties f x (l s') (m s')\"\nusing assms properties.brent[where f=f and ?x0.0=x]\nby (fastforce intro: fx0.properties_existence[where f=f and ?x0.0=x]\n               simp:  Basis.properties_def valid_def)\n\nschematic_goal brent_code[code]:\n  \"fx0.brent f x = ?code\"\nunfolding fx0.brent_def fx0.find_lambda_def fx0.find_mu_def fcomp_assoc[symmetric] fcomp_comp\nby (rule refl)\n\nexport_code fx0.brent in SML\n(*<*)\n\nend\n(*>*)\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/TortoiseHare/Brent.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7843461712462704}}
{"text": "(*\nAuthor:  Akihisa Yamada (2018-2019)\nLicense: LGPL (see file COPYING.LESSER)\n*)\nsection \\<open>Binary Relations\\<close>\n\ntext \\<open>We start with basic properties of binary relations.\\<close>\n\ntheory Binary_Relations\nimports Main\n(* uses mainly concepts from the theories Complete_Partial_Order, Wellfounded, Partial_Function *)\nbegin\n\ntext \\<open>Below we introduce an Isabelle-notation for $\\{ \\ldots x\\ldots \\mid x \\in X \\}$.\\<close>\n\nsyntax\n  \"_range\" :: \"'a \\<Rightarrow> pttrn \\<Rightarrow> 'a set\" (\"(1{_ /|./ _})\")\n  \"_image\" :: \"'a \\<Rightarrow> pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (\"(1{_ /|./ (_/ \\<in> _)})\")\ntranslations\n  \"{e |. p}\" \\<rightleftharpoons> \"CONST range (\\<lambda>p. e)\"\n  \"{e |. p \\<in> A}\" \\<rightleftharpoons> \"CONST image (\\<lambda>p. e) A\"\n\nlemma image_constant:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> f i = y\"\n  shows \"f ` I = (if I = {} then {} else {y})\"\n  using assms by auto\n\n\nsubsection \\<open>Various Definitions\\<close>\n\ntext \\<open>Here we introduce various definitions for binary relations.\nThe first one is our abbreviation for the dual of a relation.\\<close>\n\nabbreviation(input) dual (\"(_\\<^sup>-)\" [1000] 1000) where \"r\\<^sup>- x y \\<equiv> r y x\"\n\nlemma conversep_as_dual[simp]: \"conversep r = r\\<^sup>-\" by auto\n\ntext \\<open>Monotonicity is already defined in the library.\\<close>\nlemma monotone_dual: \"monotone r s f \\<Longrightarrow> monotone r\\<^sup>- s\\<^sup>- f\"\n  by (auto simp: monotone_def)\n\nlemma monotone_id: \"monotone r r id\"\n  by (auto simp: monotone_def)\n\ntext \\<open>So is the chain, but it is somehow hidden. We reactivate it.\\<close>\nabbreviation \"chain \\<equiv> Complete_Partial_Order.chain\"\n\ncontext fixes r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) begin\n\ntext \\<open>Here we define the following notions in a standard manner:\n(upper) bounds of a set:\\<close>\ndefinition \"bound X b \\<equiv> \\<forall>x \\<in> X. x \\<sqsubseteq> b\"\n\nlemma boundI[intro!]: \"(\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> b) \\<Longrightarrow> bound X b\"\n  and boundE[elim]: \"bound X b \\<Longrightarrow> ((\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> b) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  by (auto simp: bound_def)\n\nlemma bound_empty: \"bound {} = (\\<lambda>x. True)\" by auto\nlemma bound_insert[simp]: \"bound (insert x X) b \\<longleftrightarrow> x \\<sqsubseteq> b \\<and> bound X b\" by auto\n\nlemma bound_cmono: assumes \"X \\<subseteq> Y\" shows \"bound Y x \\<Longrightarrow> bound X x\"\n  using assms by auto\n\ntext \\<open>Extreme (greatest) elements in a set:\\<close>\ndefinition \"extreme X e \\<equiv> e \\<in> X \\<and> (\\<forall>x \\<in> X. x \\<sqsubseteq> e)\"\n\nlemma extremeI[intro]: \"e \\<in> X \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> e) \\<Longrightarrow> extreme X e\"\n  and extremeD: \"extreme X e \\<Longrightarrow> e \\<in> X\" \"extreme X e \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> e)\"\n  and extremeE[elim]: \"extreme X e \\<Longrightarrow> (e \\<in> X \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> e) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  by (auto simp: extreme_def)\n\nlemma extreme_UNIV[simp]: \"extreme UNIV t \\<longleftrightarrow> (\\<forall>x. x \\<sqsubseteq> t)\" by auto\n\nlemma extremes_equiv: \"extreme X b \\<Longrightarrow> extreme X c \\<Longrightarrow> b \\<sqsubseteq> c \\<and> c \\<sqsubseteq> b\" by auto\n\ntext \\<open>Directed sets:\\<close>\ndefinition \"directed X \\<equiv> \\<forall>x \\<in> X. \\<forall> y \\<in> X. \\<exists>z \\<in> X. x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\"\n\nlemma directedE:\n  assumes \"directed X\" and \"x \\<in> X\" and \"y \\<in> X\"\n    and \"\\<And>z. z \\<in> X \\<Longrightarrow> x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> thesis\"\n  shows \"thesis\"\n  using assms by (auto simp: directed_def)\n\nlemma directedI[intro]:\n  assumes \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> \\<exists>z \\<in> X. x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z\"\n  shows \"directed X\" \n  using assms by (auto simp: directed_def)\n\nlemma chain_imp_directed: \"chain (\\<sqsubseteq>) X \\<Longrightarrow> directed X\"\n  by (intro directedI, auto elim: chainE)\n\ntext \\<open>And sets of elements which are self-related:\\<close>\ndefinition \"reflexive_on X \\<equiv> \\<forall>x \\<in> X. x \\<sqsubseteq> x\"\n\nlemma reflexive_onI[intro]:\n  assumes \"\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> x\" shows \"reflexive_on X\" using assms reflexive_on_def by auto\n\nlemma reflexive_onE[elim]:\n  assumes \"reflexive_on X\" and \"(\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> x) \\<Longrightarrow> thesis\" shows thesis\n  using assms reflexive_on_def by auto\n\nlemma chain_imp_reflexive: \"chain (\\<sqsubseteq>) X \\<Longrightarrow> reflexive_on X\" by (auto elim: chainE)\n\nend\n\ncontext fixes r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\ntext \\<open>Now suprema and infima are given uniformly as follows. \\<close>\nabbreviation \"extreme_bound X \\<equiv> extreme (\\<lambda>x y. y \\<sqsubseteq> x) {b. bound (\\<sqsubseteq>) X b}\"\n\nlemma extreme_boundI[intro]:\n  assumes \"\\<And>b. bound (\\<sqsubseteq>) X b \\<Longrightarrow> s \\<sqsubseteq> b\" and \"\\<And>x. x \\<in> X \\<Longrightarrow> x \\<sqsubseteq> s\"\n  shows \"extreme_bound X s\"\n  using assms by auto\n\nlemma extreme_bound_mono:\n  assumes XY: \"X \\<subseteq> Y\"\n    and bX: \"extreme_bound X bX\"\n    and bY: \"extreme_bound Y bY\"\n  shows \"bX \\<sqsubseteq> bY\"\nproof-\n  have \"bound (\\<sqsubseteq>) X bY\" using XY bY by force\n  with bX show ?thesis by auto\nqed\n\nlemma extreme_bound_iff:\n  shows \"extreme_bound X b \\<longleftrightarrow> (\\<forall>c. (\\<forall>x\\<in>X. x \\<sqsubseteq> c) \\<longrightarrow> b \\<sqsubseteq> c) \\<and> (\\<forall>x \\<in> X. x \\<sqsubseteq> b)\"\n  by (auto simp: extreme_def)\n\nlemma extreme_bound_singleton_refl[simp]:\n  \"extreme_bound {x} x \\<longleftrightarrow> x \\<sqsubseteq> x\" by auto\n\nlemma extreme_bound_equiv: \"extreme_bound X b \\<Longrightarrow> c \\<in> X \\<Longrightarrow> b \\<sqsubseteq> c \\<Longrightarrow> c \\<sqsubseteq> b\"\n  by auto\n\nlemma extreme_bound_image_const:\n  \"x \\<sqsubseteq> x \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> C \\<Longrightarrow> f i = x) \\<Longrightarrow> extreme_bound (f ` C) x\"\n  by (auto simp: image_constant)\n\nlemma extreme_bound_UN_const:\n  \"x \\<sqsubseteq> x \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> (\\<And>i y. i \\<in> C \\<Longrightarrow> P i y \\<longleftrightarrow> x = y) \\<Longrightarrow>\n  extreme_bound (\\<Union>i\\<in>C. {y. P i y}) x\"\n  by auto\n\nend\n\ncontext\n  fixes r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\nlemma fun_ordI: \"(\\<And>x. f x \\<sqsubseteq> g x) \\<Longrightarrow> fun_ord (\\<sqsubseteq>) f g\"\n  and fun_ordD: \"fun_ord (\\<sqsubseteq>) f g \\<Longrightarrow> f x \\<sqsubseteq> g x\"\n  by (auto simp: fun_ord_def)\n\nlemma dual_fun_ord: \"(fun_ord (\\<sqsubseteq>))\\<^sup>- = fun_ord (\\<sqsubseteq>)\\<^sup>-\" by (auto intro!:ext simp: fun_ord_def)\n\nlemma fun_extreme_bound_iff:\n  shows \"extreme_bound (fun_ord (\\<sqsubseteq>)) F e \\<longleftrightarrow> (\\<forall>x. extreme_bound (\\<sqsubseteq>) {f x |. f \\<in> F} (e x))\" (is \"?l \\<longleftrightarrow> ?r\")\nproof(intro iffI allI extreme_boundI fun_ordI)\n  fix f x\n  assume ?r\n  then have e: \"extreme_bound (\\<sqsubseteq>) {f x |. f \\<in> F} (e x)\" by auto\n  show \"f \\<in> F \\<Longrightarrow> f x \\<sqsubseteq> e x\" using extremeD(1)[OF e] by auto\n  assume \"bound (fun_ord (\\<sqsubseteq>)) F f\"\n  then have \"bound (\\<sqsubseteq>) {f x |. f \\<in> F} (f x)\" by (auto simp: fun_ord_def)\n  with e show \"e x \\<sqsubseteq> f x\" by auto\nnext\n  fix x y\n  assume l: ?l\n  from l have e: \"f \\<in> F \\<Longrightarrow> f x \\<sqsubseteq> e x\" for f by (auto dest!:extremeD simp: fun_ord_def)\n  then show \"y \\<in> {f x |. f \\<in> F} \\<Longrightarrow> y \\<sqsubseteq> e x\" by auto\n  assume \"bound (\\<sqsubseteq>) {f x |. f \\<in> F} y\"\n  with extremeD(1)[OF l] have \"bound (fun_ord (\\<sqsubseteq>)) F (e(x:=y))\" by (auto simp: fun_ord_def elim!:boundE)\n  with l have \"fun_ord (\\<sqsubseteq>) e (e(x:=y))\" by auto\n  from fun_ordD[OF this, of x]\n  show \"e x \\<sqsubseteq> y\" by auto\nqed\n\ncontext\n  fixes ir :: \"'i \\<Rightarrow> 'i \\<Rightarrow> bool\" (infix \"\\<preceq>\" 50)\n  fixes f\n  assumes mono: \"monotone (\\<preceq>) (\\<sqsubseteq>) f\"\nbegin\n\nlemma monotone_chain_image:\n  assumes chain: \"chain (\\<preceq>) C\" shows \"chain (\\<sqsubseteq>) (f ` C)\"\nproof (rule chainI)\n  fix x y\n  assume \"x \\<in> f ` C\" and \"y \\<in> f ` C\"\n  then obtain i j where ij: \"i \\<in> C\" \"j \\<in> C\" and [simp]: \"x = f i\" \"y = f j\" by auto\n  from chain ij have \"i \\<preceq> j \\<or> j \\<preceq> i\" by (auto elim: chainE)\n  with ij mono show \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\" by (elim disjE, auto dest: monotoneD) \nqed\n\nlemma monotone_directed_image:\n  assumes dir: \"directed (\\<preceq>) D\" shows \"directed (\\<sqsubseteq>) (f ` D)\"\nproof (rule directedI, safe)\n  fix x y assume \"x \\<in> D\" and \"y \\<in> D\"\n  with dir obtain z where z: \"z \\<in> D\" and \"x \\<preceq> z\" and \"y \\<preceq> z\" by (auto elim: directedE)\n  with mono have \"f x \\<sqsubseteq> f z\" and \"f y \\<sqsubseteq> f z\" by (auto dest: monotoneD)\n  with z show \"\\<exists>fz \\<in> f ` D. f x \\<sqsubseteq> fz \\<and> f y \\<sqsubseteq> fz\" by auto\nqed\n\ncontext\n  fixes e C\n  assumes e: \"extreme (\\<preceq>) C e\"\nbegin\n\nlemma monotone_extreme_imp_extreme_bound:\n  shows \"extreme_bound (\\<sqsubseteq>) (f ` C) (f e)\"\n  using monotoneD[OF mono] e\n  by (auto simp: image_def intro!:extreme_boundI elim!:extremeE boundE)\n\nlemma monotone_extreme_extreme_boundI:\n  \"x = f e \\<Longrightarrow> extreme_bound (\\<sqsubseteq>) (f ` C) x\"\n  using monotone_extreme_imp_extreme_bound by auto\n\nend\n\nend\n\nend\n\nsubsection \\<open>Locales for Binary Relations\\<close>\n\ntext \\<open>We now define basic properties of binary relations,\nin form of \\emph{locales}~\\cite{Kammuller00,locale}.\\<close>\n\nsubsubsection \\<open>Syntactic Locales\\<close>\n\ntext \\<open>The following locales do not assume anything, but provide infix notations for\nrelations. \\<close>\n\nlocale less_eq_syntax = fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\n\nlocale less_syntax = fixes less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 50)\n\nlocale equivalence_syntax = fixes equiv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sim>\" 50)\nbegin\n\nabbreviation equiv_class (\"[_]\\<^sub>\\<sim>\") where \"[x]\\<^sub>\\<sim> \\<equiv> { y. x \\<sim> y }\"\n\nend\n\ntext \\<open>Next ones introduce abbreviations for dual etc.\nTo avoid needless constants, one should be careful when declaring them as sublocales.\\<close>\n\nlocale less_eq_dualize = less_eq_syntax\nbegin\n\nabbreviation (input) greater_eq (infix \"\\<sqsupseteq>\" 50) where \"x \\<sqsupseteq> y \\<equiv> y \\<sqsubseteq> x\"\nabbreviation (input) equiv (infix \"\\<sim>\" 50) where \"x \\<sim> y \\<equiv> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\n\nlemma equiv_sym[sym]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\" by auto\n\nend\n\nlocale less_dualize = less_syntax\nbegin\n\nabbreviation (input) greater (infix \"\\<sqsupset>\" 50) where \"x \\<sqsupset> y \\<equiv> y \\<sqsubset> x\"\n\nend\n\nsubsubsection \\<open>Basic Properties of Relations\\<close>\n\ntext \\<open>In the following we define basic properties in form of locales.\\<close>\n\nlocale reflexive = less_eq_syntax + assumes refl[iff]: \"x \\<sqsubseteq> x\"\nbegin\n\nlemma eq_implies: \"x = y \\<Longrightarrow> x \\<sqsubseteq> y\" by auto\n\nlemma extreme_singleton[simp]: \"extreme (\\<sqsubseteq>) {x} y \\<longleftrightarrow> x = y\" by auto\n\nlemma extreme_bound_singleton[iff]: \"extreme_bound (\\<sqsubseteq>) {x} x\" by auto\n\nend\nlemmas reflexiveI[intro] = reflexive.intro\n\nlocale irreflexive = less_syntax + assumes irrefl[iff]: \"\\<not> x \\<sqsubset> x\"\nbegin\n\nlemma implies_not_eq: \"x \\<sqsubset> y \\<Longrightarrow> x \\<noteq> y\" by auto\n\nend\nlemmas irreflexiveI[intro] = irreflexive.intro\n\nlocale transitive = less_eq_syntax + assumes trans[trans]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\nlemmas [intro?] = transitive.intro\n\nlocale symmetric = equivalence_syntax + assumes sym[sym]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\"\nbegin\n\nlemma dual_sym: \"(\\<sim>)\\<^sup>- = (\\<sim>)\" using sym by auto\n\nend\nlemmas [intro] = symmetric.intro\n\nlocale antisymmetric = less_eq_syntax + assumes antisym[dest]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nbegin\n\ninterpretation less_eq_dualize. \n\nlemma equiv_iff_eq_refl: \"x \\<sim> y \\<longleftrightarrow> x = y \\<and> y \\<sqsubseteq> y\" by auto\n\nlemma extreme_unique: \"extreme (\\<sqsubseteq>) X x \\<Longrightarrow> extreme (\\<sqsubseteq>) X y \\<longleftrightarrow> x = y\"\n  by (auto elim!: extremeE)\n\nlemma ex_extreme_iff_ex1: \"Ex (extreme (\\<sqsubseteq>) X) \\<longleftrightarrow> Ex1 (extreme (\\<sqsubseteq>) X)\" by (auto simp: extreme_unique)\n\nlemma ex_extreme_iff_the:\n   \"Ex (extreme (\\<sqsubseteq>) X) \\<longleftrightarrow> extreme (\\<sqsubseteq>) X (The (extreme (\\<sqsubseteq>) X))\"\n  apply (rule iffI)\n  apply (rule  theI')\n  using extreme_unique by auto\n\nend\nlemmas antisymmetricI[intro] = antisymmetric.intro\n\ntext \\<open>The following notion is new, generalizing antisymmetry and transitivity.\\<close>\n\nlocale semiattractive = less_eq_syntax +\n  assumes attract: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z\"\nbegin\n\ninterpretation less_eq_dualize.\n\nlemma equiv_trans:\n  assumes xy: \"x \\<sim> y\" and yz: \"y \\<sim> z\" shows \"x \\<sim> z\"\n  using attract[of y x z] attract[of y z x] xy yz by auto\n\nlemma extreme_bound_quasi_const:\n  assumes C: \"C \\<noteq> {}\" and const: \"\\<forall>y \\<in> C. y \\<sim> x\" shows \"extreme_bound (\\<sqsubseteq>) C x\"\nproof (intro extreme_boundI)\n  from C obtain c where c: \"c \\<in> C\" by auto\n  with const have cx: \"c \\<sim> x\" by auto\n  fix b assume \"bound (\\<sqsubseteq>) C b\"\n  with c have cb: \"c \\<sqsubseteq> b\" by auto\n  from attract[of c x b] cb cx show \"x \\<sqsubseteq> b\" by auto\nnext\n  fix c assume \"c \\<in> C\"\n  with const show \"c \\<sqsubseteq> x\" by auto\nqed\n\nlemma extreme_bound_quasi_const_iff:\n  assumes C: \"C \\<noteq> {}\" and const: \"\\<forall>z \\<in> C. z \\<sim> x\"\n  shows \"extreme_bound (\\<sqsubseteq>) C y \\<longleftrightarrow> x \\<sim> y\"\nproof (intro iffI)\n  assume \"extreme_bound (\\<sqsubseteq>) C y\"\n  with const show \"x \\<sim> y\"\n    by (metis C extreme_bound_quasi_const extremes_equiv)\nnext\n  assume xy: \"x \\<sim> y\"\n  with const equiv_trans[of _ x y] have Cy: \"\\<forall>z \\<in> C. z \\<sim> y\" by auto\n  show \"extreme_bound (\\<sqsubseteq>) C y\"\n    using extreme_bound_quasi_const[OF C Cy].\nqed\n\nend\n\nlocale attractive = semiattractive + dual: semiattractive \"(\\<sqsubseteq>)\\<^sup>-\"\n\nsublocale transitive \\<subseteq> attractive by (unfold_locales, auto dest: trans)\n\nsublocale antisymmetric \\<subseteq> attractive by (unfold_locales, auto)\n\nlocale asymmetric = irreflexive + strict: antisymmetric \"(\\<sqsubset>)\"\nbegin\n\nlemma asym[trans]: \"x \\<sqsubset> y \\<Longrightarrow> y \\<sqsubset> x \\<Longrightarrow> thesis\" by auto\n\nend\n\ncontext\n  fixes less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubset>\" 50)\nbegin\n\nlemma asymmetricI[intro]:\n  assumes \"\\<And>x y. x \\<sqsubset> y \\<Longrightarrow> y \\<sqsubset> x \\<Longrightarrow> False\" \n  shows \"asymmetric (\\<sqsubset>)\"\n  apply unfold_locales using assms by auto\n\nlemma asymmetric_def': \"asymmetric (\\<sqsubset>) \\<equiv> \\<forall>x y. \\<not> (x \\<sqsubset> y \\<and> y \\<sqsubset> x)\"\n  by (auto simp: atomize_eq dest!: asymmetric.asym)\n\nend\n\nlocale well_founded = less_syntax +\n  assumes induct: \"\\<And>P a. (\\<And>x. (\\<And>y. y \\<sqsubset> x \\<Longrightarrow> P y) \\<Longrightarrow> P x) \\<Longrightarrow> P a\"\nbegin\n\nlemma wfP[intro!]: \"wfP (\\<sqsubset>)\" using induct wfPUNIVI by blast\n\nsublocale asymmetric\nproof (intro asymmetricI notI)\n  show \"x \\<sqsubset> y \\<Longrightarrow> y \\<sqsubset> x \\<Longrightarrow> False\" for x y by (induct x arbitrary: y rule: induct)\nqed\n\nend\n\nsubsubsection \\<open>Combined Properties\\<close>\n\ntext \\<open>Some combinations of the above basic properties are given names.\\<close>\n\nlocale quasi_order = reflexive + transitive\n\nlocale near_order = antisymmetric + transitive\n\nlocale pseudo_order = reflexive + antisymmetric\nbegin\n\nlemma equiv_eq[simp]: \"x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x \\<longleftrightarrow> x = y\" by auto\n\nlemma extreme_bound_singleton_eq[simp]: \"extreme_bound (\\<sqsubseteq>) {x} y \\<longleftrightarrow> x = y\" by auto\n\nlemma eq_iff: \"x = y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\" by auto\n\nlemma extreme_order_iff_eq[simp]: \"extreme (\\<sqsubseteq>) {x. x \\<sqsubseteq> e} s \\<longleftrightarrow> e = s\" by auto\n\nend\n\nlocale partial_order = quasi_order + antisymmetric\n\nsublocale partial_order \\<subseteq> pseudo_order + near_order ..\n\nlocale strict_order = irreflexive + transitive \"(\\<sqsubset>)\"\n\nsublocale strict_order \\<subseteq> asymmetric by (auto dest: trans)\nsublocale strict_order \\<subseteq> near_order \"(\\<sqsubset>)\" ..\n\nlocale well_founded_order = well_founded + transitive \"(\\<sqsubset>)\"\n\nsublocale well_founded_order \\<subseteq> strict_order ..\n\nlocale tolerance = equivalence_syntax + reflexive \"(\\<sim>)\" + symmetric \"(\\<sim>)\"\n\nlocale partial_equivalence = equivalence_syntax + symmetric \"(\\<sim>)\" + transitive \"(\\<sim>)\"\n\nlocale equivalence = equivalence_syntax + symmetric \"(\\<sim>)\" + quasi_order \"(\\<sim>)\"\n\nsublocale equivalence \\<subseteq> partial_equivalence ..\n\ntext \\<open>Some combinations lead to uninteresting relations.\\<close>\n\nproposition reflexive_irreflexive_is_empty:\n  assumes \"reflexive r\" and \"irreflexive r\"\n  shows \"r = (\\<lambda>x y. False)\"\nproof(intro ext iffI)\n  interpret irreflexive r + reflexive r using assms by auto\n  fix x y\n  assume \"r x y\"\n  with irrefl have \"x \\<noteq> y\" by auto\n  with refl show False by auto\nqed auto\n\nproposition symmetric_antisymmetric_imp_eq:\n  assumes \"symmetric r\" and \"antisymmetric r\"\n  shows \"r x y \\<Longrightarrow> x = y\"\nproof-\n  interpret symmetric r + antisymmetric r using assms by auto\n  fix x y\n  assume \"r x y\"\n  with sym[OF this] show \"x = y\" by auto\nqed\n\nproposition nontolerance:\n  fixes r (infix \"\\<bowtie>\" 50)\n  shows \"irreflexive (\\<bowtie>) \\<and> symmetric (\\<bowtie>) \\<longleftrightarrow> tolerance (\\<lambda>x y. \\<not> x \\<bowtie> y)\"\nproof safe\n  assume \"irreflexive (\\<bowtie>)\" and \"symmetric (\\<bowtie>)\"\n  then interpret irreflexive \"(\\<bowtie>)\" + symmetric \"(\\<bowtie>)\".\n  show \"tolerance (\\<lambda>x y. \\<not> x \\<bowtie> y)\" by (unfold_locales, auto dest: sym)\nnext\n  assume \"tolerance (\\<lambda>x y. \\<not> x \\<bowtie> y)\"\n  then interpret tolerance \"\\<lambda>x y. \\<not> x \\<bowtie> y\".\n  show \"irreflexive (\\<bowtie>)\" by auto\n  show \"symmetric (\\<bowtie>)\" using sym by auto\nqed\n\nproposition irreflexive_transitive_symmetric_is_empty:\n  assumes \"irreflexive r\" and \"transitive r\" and \"symmetric r\"\n  shows \"r = (\\<lambda>x y. False)\"\nproof(intro ext iffI)\n  interpret strict_order r using assms by (unfold strict_order_def, auto)\n  interpret symmetric r using assms by auto\n  fix x y\n  assume \"r x y\"\n  also note sym[OF this]\n  finally have \"r x x\".\n  then show False by auto\nqed auto\n\nsubsection \\<open>Totality\\<close>\n\nlocale total = less_syntax + assumes total: \"x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x\"\nbegin\n\nlemma cases[case_names less eq greater]:\n  assumes \"x \\<sqsubset> y \\<Longrightarrow> P\" and \"x = y \\<Longrightarrow> P\" and \"y \\<sqsubset> x \\<Longrightarrow> P\"\n  shows \"P\" using total assms by auto\n\nlemma neqE: \"x \\<noteq> y \\<Longrightarrow> (x \\<sqsubset> y \\<Longrightarrow> P) \\<Longrightarrow> (y \\<sqsubset> x \\<Longrightarrow> P) \\<Longrightarrow> P\" by (cases x y rule: cases, auto)\n\nend\nlemmas totalI[intro] = total.intro\n\ntext \\<open>Totality is negated antisymmetry \\cite[Proposition 2.2.4]{Schmidt1993}.\\<close>\nproposition total_iff_neg_antisymmetric:\n  fixes less (infix \"\\<sqsubset>\" 50)\n  shows \"total (\\<sqsubset>) \\<longleftrightarrow> antisymmetric (\\<lambda>x y. \\<not> x \\<sqsubset> y)\" (is \"?l \\<longleftrightarrow> ?r\")\nproof (intro iffI totalI antisymmetricI)\n  assume ?l\n  then interpret total.\n  fix x y\n  assume \"\\<not> x \\<sqsubset> y\" and \"\\<not> y \\<sqsubset> x\"\n  then show \"x = y\" by (cases x y rule: cases, auto)\nnext\n  assume ?r\n  then interpret neg: antisymmetric \"(\\<lambda>x y. \\<not> x \\<sqsubset> y)\".\n  fix x y\n  show \"x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x\" using neg.antisym by auto\nqed\n\nlocale total_irreflexive = total + irreflexive\nbegin\n\nlemma neq_iff: \"x \\<noteq> y \\<longleftrightarrow> x \\<sqsubset> y \\<or> y \\<sqsubset> x\" by (auto elim:neqE)\n\nend\n\nlocale total_reflexive = reflexive + weak: total \"(\\<sqsubseteq>)\"\nbegin\n\nlemma comparable: \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\" by (cases x y rule:weak.cases, auto)\n\nlemma comparable_cases[case_names le ge]:\n  assumes \"x \\<sqsubseteq> y \\<Longrightarrow> P\" and \"y \\<sqsubseteq> x \\<Longrightarrow> P\" shows \"P\" using assms comparable by auto\n\nlemma chain_UNIV: \"chain (\\<sqsubseteq>) UNIV\" by (intro chainI comparable)\n\nend\n\ncontext\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50)\nbegin\n\nlemma total_reflexiveI[intro]:\n  assumes \"\\<And>x y. x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\" shows \"total_reflexive (\\<sqsubseteq>)\"\n  using assms by (unfold_locales, auto)\n\nlemma total_reflexive_def': \"total_reflexive (\\<sqsubseteq>) \\<equiv> \\<forall>x y. x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n  by (unfold atomize_eq, auto dest: total_reflexive.comparable)\n\nend\n\nlocale total_pseudo_order = total_reflexive + antisymmetric\nbegin\n\nsublocale pseudo_order ..\n\nlemma not_weak_iff: \"\\<not> y \\<sqsubseteq> x \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> x \\<noteq> y\" by (cases x y rule:comparable_cases, auto)\n\nend\n\nlocale total_quasi_order = total_reflexive + transitive\nbegin\n\nsublocale quasi_order ..\n\nend\n\nlocale total_order = total_quasi_order + antisymmetric\nbegin\n\nsublocale partial_order + total_pseudo_order ..\n\nend\n\ntext \\<open>A strict total order defines a total weak order, so we will formalize\nit after giving locales for pair of weak and strict parts.\\<close>\n\nsubsection \\<open>Order Pairs\\<close>\n\nlocale compatible_ordering = less_eq_syntax + less_syntax + reflexive \"(\\<sqsubseteq>)\" + irreflexive \"(\\<sqsubset>)\" +\n  assumes weak_strict_trans[trans]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubset> z \\<Longrightarrow> x \\<sqsubset> z\"\n  assumes strict_weak_trans[trans]: \"x \\<sqsubset> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubset> z\"\n  assumes strict_implies_weak: \"x \\<sqsubset> y \\<Longrightarrow> x \\<sqsubseteq> y\"\nbegin\n\ntext \\<open>The strict part is necessarily transitive.\\<close>\n\nsublocale strict: transitive \"(\\<sqsubset>)\"\n  using weak_strict_trans[OF strict_implies_weak] by unfold_locales\n\ntext \\<open>The following sequence of declarations are in order to obtain fact names in a manner\nsimilar to the Isabelle/HOL facts of orders.\\<close>\n\ninterpretation strict_order \"(\\<sqsubset>)\" ..\n\nsublocale strict: near_order \"(\\<sqsubset>)\" by unfold_locales\n\nsublocale asymmetric \"(\\<sqsubset>)\" by unfold_locales\n\nsublocale strict_order \"(\\<sqsubset>)\" ..\n\nthm strict.antisym strict.trans asym irrefl\n\nlemma strict_implies_not_weak: \"x \\<sqsubset> y \\<Longrightarrow> \\<not> y \\<sqsubseteq> x\" by (auto dest: strict_weak_trans)\n\nend\n\nlocale attractive_ordering = compatible_ordering + attractive\n\nlocale pseudo_ordering = compatible_ordering + antisymmetric\nbegin\n\nsublocale pseudo_order + attractive_ordering ..\n\nend\n\nlocale quasi_ordering = compatible_ordering + transitive\nbegin\n\nsublocale quasi_order + attractive_ordering ..\n\nend\n\nlocale partial_ordering = compatible_ordering + near_order\nbegin\n\nsublocale partial_order + pseudo_ordering + quasi_ordering ..\n\nend\n\nlocale well_founded_ordering = quasi_ordering + well_founded\n\nlocale total_ordering = compatible_ordering + total_order\nbegin\n\nsublocale partial_ordering ..\n\nend\n\nlocale strict_total_ordering = partial_ordering + total \"(\\<sqsubset>)\"\nbegin\n\nsublocale total_irreflexive \"(\\<sqsubset>)\" ..\n\nsublocale total_reflexive \"(\\<sqsubseteq>)\"\nproof\n  fix x y show \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\" by (cases x y rule: cases, auto dest: strict_implies_weak)\nqed\n\nsublocale total_ordering ..\n\nsublocale old: ordering \"(\\<sqsubseteq>)\" \"(\\<sqsubset>)\"\nproof-\n  have \"a \\<sqsubseteq> b \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a \\<sqsubset> b\" for a b\n    by (cases a b rule: cases, auto dest: strict_implies_weak)\n  then show \"ordering (\\<sqsubseteq>) (\\<sqsubset>)\"\n    by (unfold_locales, auto dest:strict_implies_weak trans)\nqed\n\nlemma not_weak[simp]: \"\\<not> x \\<sqsubseteq> y \\<longleftrightarrow> y \\<sqsubset> x\" by (simp add: not_weak_iff old.strict_iff_order)\n\nlemma not_strict[simp]: \"\\<not> x \\<sqsubset> y \\<longleftrightarrow> y \\<sqsubseteq> x\" by (auto simp: old.strict_iff_order)\n\nend\n\n\ntext \\<open>A locale which defines an equivalence relation. Be careful when declaring simp rules etc.,\nas the equivalence will often be rewritten to equality.\\<close>\n\nlocale quasi_order_equivalence = quasi_order + equivalence_syntax +\n  assumes equiv_def: \"x \\<sim> y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\nbegin\n\nsublocale equiv: equivalence by (unfold_locales, auto simp: equiv_def dest: trans)\n\nlemma [trans]:\n  shows equiv_weak_trans: \"x \\<sim> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n    and weak_equiv_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  by (auto simp: equiv_def dest: trans)\n\nlemma extreme_order_iff_equiv[simp]: \"extreme (\\<sqsubseteq>) {x. x \\<sqsubseteq> e} y \\<longleftrightarrow> e \\<sim> y\"\n  by (auto simp: equiv_def intro!: extremeI dest: trans)\n\nlemma extreme_bound_iff_equiv:\n  assumes bX: \"extreme_bound (\\<sqsubseteq>) X b\" shows \"extreme_bound (\\<sqsubseteq>) X c \\<longleftrightarrow> b \\<sim> c\"\nproof(rule iffI)\n  from bX have bX: \"bound (\\<sqsubseteq>) X b\" and leastb: \"\\<And>x. bound (\\<sqsubseteq>) X x \\<Longrightarrow> b \\<sqsubseteq> x\" by auto\n  { fix c assume \"extreme_bound (\\<sqsubseteq>) X c\"\n    then have cbounds: \"bound (\\<sqsubseteq>) X c\" and leastc: \"\\<And>b. bound (\\<sqsubseteq>) X b \\<Longrightarrow> c \\<sqsubseteq> b\" by auto\n    from leastb[OF cbounds] leastc[OF bX] show \"b \\<sim> c\" by (auto simp: equiv_def)\n  }\n  { fix c assume bc: \"b \\<sim> c\"\n    show \"extreme_bound (\\<sqsubseteq>) X c\"\n    proof(intro extreme_boundI)\n      fix x assume \"x \\<in> X\"\n      with bX have \"x \\<sqsubseteq> b\" by auto\n      with bc show \"x \\<sqsubseteq> c\" by (auto dest: trans simp: equiv_def)\n    next\n      fix x assume \"bound (\\<sqsubseteq>) X x\"\n      from leastb[OF this] bc show \"c \\<sqsubseteq> x\" by (auto dest: trans simp: equiv_def)\n    qed\n  }\nqed\n\nlemma extremes_are_equiv: \"extreme (\\<sqsubseteq>) X x \\<Longrightarrow> extreme (\\<sqsubseteq>) X y \\<Longrightarrow> x \\<sim> y\"\n  by (auto simp: equiv_def)\n\nend\n\nlocale quasi_ordering_equivalence = compatible_ordering + quasi_order_equivalence\nbegin\n\nlemma [trans]:\n  shows equiv_strict_trans: \"x \\<sim> y \\<Longrightarrow> y \\<sqsubset> z \\<Longrightarrow> x \\<sqsubset> z\"\n    and strict_equiv_trans: \"x \\<sqsubset> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> x \\<sqsubset> z\"\n  by (auto simp: equiv_def dest: weak_strict_trans strict_weak_trans)\n\nend\n\nsubsection \\<open>Relating to Classes\\<close>\n\ntext \\<open>In Isabelle 2019 (and earlier), we should declare sublocales in class before declaring dual\nsublocales, since otherwise facts would be prefixed by ``dual.dual.''\\<close>\n\ncontext ord begin\n\nabbreviation upper_bound where \"upper_bound \\<equiv> bound (\\<le>)\"\n\nabbreviation least where \"least \\<equiv> extreme (\\<lambda>x y. y \\<le> x)\"\n\nabbreviation lower_bound where \"lower_bound \\<equiv> bound (\\<lambda>x y. y \\<le> x)\"\n\nabbreviation greatest where \"greatest \\<equiv> extreme (\\<le>)\"\n\nabbreviation supremum where \"supremum \\<equiv> extreme_bound (\\<le>)\"\n\nabbreviation infimum where \"infimum \\<equiv> extreme_bound (\\<lambda>x y. y \\<le> x)\"\n\nlemma Least_eq_The_least: \"Least P = The (least {x. P x})\"\n  by (auto simp: Least_def extreme_def[unfolded atomize_eq, THEN ext])\n\nlemma Greatest_eq_The_greatest: \"Greatest P = The (greatest {x. P x})\"\n  by (auto simp: Greatest_def extreme_def[unfolded atomize_eq, THEN ext])\n\nend\n\nlemma fun_ord_le: \"fun_ord (\\<le>) = (\\<le>)\" by (intro ext, simp add: fun_ord_def le_fun_def)\nlemma fun_ord_ge: \"fun_ord (\\<ge>) = (\\<ge>)\" by (intro ext, simp add: fun_ord_def le_fun_def)\n\nlemmas fun_supremum_iff = fun_extreme_bound_iff[of \"(\\<le>)\", unfolded fun_ord_le]\nlemmas fun_infimum_iff = fun_extreme_bound_iff[of \"(\\<ge>)\", unfolded fun_ord_ge]\n\nclass compat = ord + assumes \"compatible_ordering (\\<le>) (<)\"\nbegin\n\nsublocale order: compatible_ordering using compat_axioms unfolding class.compat_def.\n\nend\n\ntext \\<open>We should have imported locale-based facts in classes, e.g.:\\<close>\nthm order.trans order.strict.trans order.refl order.irrefl order.asym order.extreme_bound_singleton\n\nclass attractive_order = ord + assumes \"attractive_ordering (\\<le>) (<)\"\nbegin\n\ninterpretation order: attractive_ordering\n  using attractive_order_axioms unfolding class.attractive_order_def.\n\nsubclass compat ..\n\nsublocale order: attractive_ordering ..\n\nend\n\nthm order.extreme_bound_quasi_const\n\nclass psorder = ord + assumes \"pseudo_ordering (\\<le>) (<)\"\nbegin\n\ntext \\<open>We need to declare subclasses before sublocales in order to preserve facts for superclasses.\\<close>\n\ninterpretation order: pseudo_ordering using psorder_axioms unfolding class.psorder_def.\n\nsubclass attractive_order ..\n\nsublocale order: pseudo_ordering ..\n\nend\n\nclass qorder = ord + assumes \"quasi_ordering (\\<le>) (<)\"\nbegin\n\ninterpretation order: quasi_ordering using qorder_axioms unfolding class.qorder_def.\n\nsubclass attractive_order ..\n\nsublocale order: quasi_ordering ..\n\nend\n\nclass porder = ord + assumes \"partial_ordering (\\<le>) (<)\"\nbegin\n\ninterpretation order: partial_ordering using porder_axioms unfolding class.porder_def.\n\nsubclass psorder ..\nsubclass qorder ..\n\nsublocale order: partial_ordering ..\n\nend\n\nclass wf_qorder = ord + assumes \"well_founded_ordering (\\<le>) (<)\"\nbegin\n\ninterpretation order: well_founded_ordering using wf_qorder_axioms unfolding class.wf_qorder_def.\n\nsubclass qorder ..\n\nsublocale order: well_founded_ordering ..\n\nend\n\nclass totalorder = ord + assumes \"total_ordering (\\<le>) (<)\"\nbegin\n\ninterpretation order: total_ordering using totalorder_axioms unfolding class.totalorder_def.\n\nsubclass porder ..\n\nsublocale order: total_ordering ..\n\nend\n\ntext \\<open>Isabelle/HOL's @{class preorder} belongs to @{class qorder}, but not vice versa.\\<close>\n\nsubclass (in preorder) qorder\n  apply unfold_locales\n  apply (fact order_refl)\n  apply simp\n  apply (fact le_less_trans)\n  apply (fact less_le_trans)\n  apply (fact less_imp_le)\n  apply (fact order_trans)\n  done\n\nsubclass (in order) porder by (unfold_locales, auto)\n\nsubclass (in wellorder) wf_qorder by (unfold_locales, fact less_induct)\n\ntext \\<open>Isabelle/HOL's @{class linorder} is equivalent to our locale @{locale strict_total_ordering}.\\<close>\n\ncontext linorder begin\n\ninterpretation order: strict_total_ordering by (unfold_locales, auto)\n\nsubclass totalorder ..\n\nsublocale order: strict_total_ordering ..\n\nend\n\ntext \\<open>Tests: facts should be available in the most general classes.\\<close>\n\nthm order.strict.trans[where 'a=\"'a::compat\"]\nthm order.extreme_bound_quasi_const[where 'a=\"'a::attractive_order\"]\nthm order.extreme_bound_singleton_eq[where 'a=\"'a::psorder\"]\nthm order.trans[where 'a=\"'a::qorder\"]\nthm order.comparable_cases[where 'a=\"'a::totalorder\"]\nthm order.cases[where 'a=\"'a::linorder\"]\n\nsubsection \\<open>Declaring Duals\\<close>\n\ntext \\<open>At this point, we declare dual as sublocales.\\<close>\n\nsublocale less_eq_syntax \\<subseteq> dual: less_eq_syntax \"(\\<sqsubseteq>)\\<^sup>-\".\n\nsublocale reflexive \\<subseteq> dual: reflexive \"(\\<sqsubseteq>)\\<^sup>-\" by auto\n\nsublocale attractive \\<subseteq> dual: attractive \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\nsublocale irreflexive \\<subseteq> dual: irreflexive \"(\\<sqsubset>)\\<^sup>-\" by (unfold_locales, auto)\n\nsublocale transitive \\<subseteq> dual: transitive \"(\\<sqsubseteq>)\\<^sup>-\" by (unfold_locales, erule trans)\n\nsublocale antisymmetric \\<subseteq> dual: antisymmetric \"(\\<sqsubseteq>)\\<^sup>-\" by auto\n\nsublocale asymmetric \\<subseteq> dual: asymmetric \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\nsublocale total \\<subseteq> dual: total \"(\\<sqsubset>)\\<^sup>-\" using total by auto\n\nsublocale total_reflexive \\<subseteq> dual: total_reflexive \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\nsublocale total_irreflexive \\<subseteq> dual: total_irreflexive \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\nsublocale pseudo_order \\<subseteq> dual: pseudo_order \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\nsublocale quasi_order \\<subseteq> dual: quasi_order \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\nsublocale partial_order \\<subseteq> dual: partial_order \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\ntext \\<open>In the following dual sublocale declaration, ``rewrites'' eventually cleans up redundant\nfacts.\\<close>\n\nsublocale symmetric \\<subseteq> dual: symmetric \"(\\<sim>)\\<^sup>-\" rewrites \"(\\<sim>)\\<^sup>- = (\\<sim>)\"\n  using symmetric_axioms by (auto simp: dual_sym)\n\nsublocale equivalence \\<subseteq> dual: equivalence \"(\\<sim>)\\<^sup>-\" rewrites \"(\\<sim>)\\<^sup>- = (\\<sim>)\"\n  by (unfold_locales, auto simp: dual_sym sym)\n\nsublocale total_pseudo_order \\<subseteq> dual: total_pseudo_order \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\nsublocale total_quasi_order \\<subseteq> dual: total_quasi_order \"(\\<sqsubseteq>)\\<^sup>-\" by unfold_locales\n\nsublocale compatible_ordering \\<subseteq> dual: compatible_ordering \"(\\<sqsubseteq>)\\<^sup>-\" \"(\\<sqsubset>)\\<^sup>-\"\n  using weak_strict_trans strict_weak_trans strict_implies_weak by unfold_locales\n\nsublocale attractive_ordering \\<subseteq> dual: attractive_ordering \"(\\<sqsubseteq>)\\<^sup>-\" \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\nsublocale pseudo_ordering \\<subseteq> dual: pseudo_ordering \"(\\<sqsubseteq>)\\<^sup>-\" \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\nsublocale quasi_ordering \\<subseteq> dual: quasi_ordering \"(\\<sqsubseteq>)\\<^sup>-\" \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\nsublocale partial_ordering \\<subseteq> dual: partial_ordering \"(\\<sqsubseteq>)\\<^sup>-\" \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\nsublocale total_ordering \\<subseteq> dual: total_ordering \"(\\<sqsubseteq>)\\<^sup>-\" \"(\\<sqsubset>)\\<^sup>-\" by unfold_locales\n\n\nlemma(in antisymmetric) monotone_extreme_imp_extreme_bound_iff:\n  fixes ir (infix \"\\<preceq>\" 50)\n  assumes \"monotone (\\<preceq>) (\\<sqsubseteq>) f\" and i: \"extreme (\\<preceq>) C i\"\n  shows \"extreme_bound (\\<sqsubseteq>) (f ` C) x \\<longleftrightarrow> f i = x\"\n  using dual.extreme_unique monotone_extreme_extreme_boundI[OF assms] by auto\n\n\nsubsection \\<open>Instantiations\\<close>\n\ntext \\<open>Finally, we instantiate our classes for sanity check.\\<close>\n\ninstance nat :: linorder ..\n\ntext \\<open>Pointwise ordering of functions are compatible only if the weak part is transitive.\\<close>\n\ninstance \"fun\" :: (type,qorder) compat\nproof (intro_classes, unfold_locales)\n  note [simp] = le_fun_def less_fun_def\n  fix f g h :: \"'a \\<Rightarrow> 'b\"\n  { assume fg: \"f \\<le> g\" and gh: \"g < h\"\n    show \"f < h\"\n    proof (unfold less_fun_def, intro conjI le_funI notI)\n      from fg have \"f x \\<le> g x\" for x by auto\n      also from gh have \"g x \\<le> h x\" for x by auto\n      finally show \"f x \\<le> h x\" for x.\n      assume hf: \"h \\<le> f\"\n      then have \"h x \\<le> f x\" for x by auto\n      also from fg have \"f x \\<le> g x\" for x by auto\n      finally have \"h \\<le> g\" by auto\n      with gh show False by auto\n    qed\n  }\n  { assume fg: \"f < g\" and gh: \"g \\<le> h\"\n    show \"f < h\"\n    proof (unfold less_fun_def, intro conjI le_funI notI)\n      from fg have \"f x \\<le> g x\" for x by auto\n      also from gh have \"g x \\<le> h x\" for x by auto\n      finally show \"f x \\<le> h x\" for x.\n      assume hf: \"h \\<le> f\"\n      then have \"h x \\<le> f x\" for x by auto\n      also from gh have \"g x \\<le> h x\" for x by auto\n      finally have \"g \\<le> f\" by auto\n      with fg show False by auto\n    qed\n  }\n  show \"f < g \\<Longrightarrow> f \\<le> g\" by auto\n  show \"\\<not>f < f\" by auto\n  show \"f \\<le> f\" by auto\nqed\n\ninstance \"fun\" :: (type,qorder) qorder\n  by (intro_classes, unfold_locales, auto simp: le_fun_def dest: order.trans)\n\ninstance \"fun\" :: (type,porder) porder\n  by (intro_classes, unfold_locales, auto simp: less_fun_def le_fun_def)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complete_Non_Orders/Binary_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.8824278741843883, "lm_q1q2_score": 0.7842655224040964}}
{"text": "theory ex5_07 imports Main \"~~/src/HOL/IMP/Star\" begin\n\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\ns1: \"S []\"  |\ns2: \"S w \\<Longrightarrow> S (a # w @ [b])\" |\ns3: \"\\<lbrakk> S w1; S w2 \\<rbrakk> \\<Longrightarrow> S (w1 @ w2)\"\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n\"balanced 0 w = (S w)\" |\n\"balanced (Suc n) w = balanced n (a # w)\"\n\nlemma r: \"balanced n w \\<Longrightarrow> S (replicate n a @ w)\"\nproof(induction n arbitrary: w)\n  fix w\n  let \"?case\" = \"S (replicate 0 a @ w)\"\n  assume \"balanced 0 w\"\n  then show ?case by auto\nnext\n  fix n w\n  let \"?case\" = \"S (replicate (Suc n) a @ w)\"\n  assume\n    IH : \"\\<And>w. balanced n w \\<Longrightarrow> S (replicate n a @ w)\" and\n    prems : \"balanced (Suc n) w\"\n  thus ?case\n    by (metis append_Cons balanced.simps(2) replicate_Suc replicate_app_Cons_same)\nqed\n\nlemma l: \"S (replicate n a @ w) \\<Longrightarrow> balanced n w\"\nproof(induction n arbitrary: w)\n  case 0\n    fix w\n    assume prems : \"S (replicate 0 a @ w)\"\n    thus \"balanced 0 w\" by auto\nnext\n  case Suc\n    fix n w\n    from Suc.IH Suc.prems show ?case by (simp add: replicate_app_Cons_same)\nqed\n\ntheorem \"balanced n w \\<longleftrightarrow> S (replicate n a @ w)\"\nusing r l by auto\n\nend", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter5/ex5_07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9314625031628428, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7841290227674486}}
{"text": "(*  Title:      HOL/Cardinals/Ordinal_Arithmetic.thy\n    Author:     Dmitriy Traytel, TU Muenchen\n    Copyright   2014\n\nOrdinal arithmetic.\n*)\n\nsection \\<open>Ordinal Arithmetic\\<close>\n\ntheory Ordinal_Arithmetic\n  imports Wellorder_Constructions\nbegin\n\ndefinition osum :: \"'a rel \\<Rightarrow> 'b rel \\<Rightarrow> ('a + 'b) rel\"  (infixr \"+o\" 70)\n  where\n    \"r +o r' = map_prod Inl Inl ` r \\<union> map_prod Inr Inr ` r' \\<union>\n     {(Inl a, Inr a') | a a' . a \\<in> Field r \\<and> a' \\<in> Field r'}\"\n\nlemma Field_osum: \"Field(r +o r') = Inl ` Field r \\<union> Inr ` Field r'\"\n  unfolding osum_def Field_def by auto\n\nlemma osum_Refl:\"\\<lbrakk>Refl r; Refl r'\\<rbrakk> \\<Longrightarrow> Refl (r +o r')\"\n  (*Need first unfold Field_osum, only then osum_def*)\n  unfolding refl_on_def Field_osum unfolding osum_def by blast\n\nlemma osum_trans:\n  assumes TRANS: \"trans r\" and TRANS': \"trans r'\"\n  shows \"trans (r +o r')\"\n  unfolding trans_def\nproof(safe)\n  fix x y z assume *: \"(x, y) \\<in> r +o r'\" \"(y, z) \\<in> r +o r'\"\n  thus \"(x, z) \\<in> r +o r'\"\n  proof (cases x y z rule: sum.exhaust[case_product sum.exhaust sum.exhaust])\n    case (Inl_Inl_Inl a b c)\n    with * have \"(a,b) \\<in> r\" \"(b,c) \\<in> r\" unfolding osum_def by auto\n    with TRANS have \"(a,c) \\<in> r\" unfolding trans_def by blast\n    with Inl_Inl_Inl show ?thesis unfolding osum_def by auto\n  next\n    case (Inl_Inl_Inr a b c)\n    with * have \"a \\<in> Field r\" \"c \\<in> Field r'\" unfolding osum_def Field_def by auto\n    with Inl_Inl_Inr show ?thesis unfolding osum_def by auto\n  next\n    case (Inl_Inr_Inr a b c)\n    with * have \"a \\<in> Field r\" \"c \\<in> Field r'\" unfolding osum_def Field_def by auto\n    with Inl_Inr_Inr show ?thesis unfolding osum_def by auto\n  next\n    case (Inr_Inr_Inr a b c)\n    with * have \"(a,b) \\<in> r'\" \"(b,c) \\<in> r'\" unfolding osum_def by auto\n    with TRANS' have \"(a,c) \\<in> r'\" unfolding trans_def by blast\n    with Inr_Inr_Inr show ?thesis unfolding osum_def by auto\n  qed (auto simp: osum_def)\nqed\n\nlemma osum_Preorder: \"\\<lbrakk>Preorder r; Preorder r'\\<rbrakk> \\<Longrightarrow> Preorder (r +o r')\"\n  unfolding preorder_on_def using osum_Refl osum_trans by blast\n\nlemma osum_antisym: \"\\<lbrakk>antisym r; antisym r'\\<rbrakk> \\<Longrightarrow> antisym (r +o r')\"\n  unfolding antisym_def osum_def by auto\n\nlemma osum_Partial_order: \"\\<lbrakk>Partial_order r; Partial_order r'\\<rbrakk> \\<Longrightarrow> Partial_order (r +o r')\"\n  unfolding partial_order_on_def using osum_Preorder osum_antisym by blast\n\nlemma osum_Total: \"\\<lbrakk>Total r; Total r'\\<rbrakk> \\<Longrightarrow> Total (r +o r')\"\n  unfolding total_on_def Field_osum unfolding osum_def by blast\n\nlemma osum_Linear_order: \"\\<lbrakk>Linear_order r; Linear_order r'\\<rbrakk> \\<Longrightarrow> Linear_order (r +o r')\"\n  unfolding linear_order_on_def using osum_Partial_order osum_Total by blast\n\nlemma osum_wf:\n  assumes WF: \"wf r\" and WF': \"wf r'\"\n  shows \"wf (r +o r')\"\n  unfolding wf_eq_minimal2 unfolding Field_osum\nproof(intro allI impI, elim conjE)\n  fix A assume *: \"A \\<subseteq> Inl ` Field r \\<union> Inr ` Field r'\" and **: \"A \\<noteq> {}\"\n  obtain B where B_def: \"B = A Int Inl ` Field r\" by blast\n  show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a', a) \\<notin> r +o r'\"\n  proof(cases \"B = {}\")\n    case False\n    hence \"B \\<noteq> {}\" \"B \\<le> Inl ` Field r\" using B_def by auto\n    hence \"Inl -` B \\<noteq> {}\" \"Inl -` B \\<le> Field r\" unfolding vimage_def by auto\n    then obtain a where 1: \"a \\<in> Inl -` B\" and \"\\<forall>a1 \\<in> Inl -` B. (a1, a) \\<notin> r\"\n      using WF unfolding wf_eq_minimal2 by metis\n    hence \"\\<forall>a1 \\<in> A. (a1, Inl a) \\<notin> r +o r'\"\n      unfolding osum_def using B_def ** by (auto simp: vimage_def Field_def)\n    thus ?thesis using 1 unfolding B_def by auto\n  next\n    case True\n    hence 1: \"A \\<le> Inr ` Field r'\" using * B_def by auto\n    with ** have \"Inr -`A \\<noteq> {}\" \"Inr -` A \\<le> Field r'\" unfolding vimage_def by auto\n    with ** obtain a' where 2: \"a' \\<in> Inr -` A\" and \"\\<forall>a1' \\<in> Inr -` A. (a1',a') \\<notin> r'\"\n      using WF' unfolding wf_eq_minimal2 by metis\n    hence \"\\<forall>a1' \\<in> A. (a1', Inr a') \\<notin> r +o r'\"\n      unfolding osum_def using ** 1 by (auto simp: vimage_def Field_def)\n    thus ?thesis using 2 by blast\n  qed\nqed\n\nlemma osum_minus_Id:\n  assumes r: \"Total r\" \"\\<not> (r \\<le> Id)\" and r': \"Total r'\" \"\\<not> (r' \\<le> Id)\"\n  shows \"(r +o r') - Id \\<le> (r - Id) +o (r' - Id)\"\n  unfolding osum_def Total_Id_Field[OF r] Total_Id_Field[OF r'] by auto\n\nlemma osum_minus_Id1:\n  \"r \\<le> Id \\<Longrightarrow> (r +o r') - Id \\<le> (Inl ` Field r \\<times> Inr ` Field r') \\<union> (map_prod Inr Inr ` (r' - Id))\"\n  unfolding osum_def by auto\n\nlemma osum_minus_Id2:\n  \"r' \\<le> Id \\<Longrightarrow> (r +o r') - Id \\<le> (map_prod Inl Inl ` (r - Id)) \\<union> (Inl ` Field r \\<times> Inr ` Field r')\"\n  unfolding osum_def by auto\n\nlemma osum_wf_Id:\n  assumes TOT: \"Total r\" and TOT': \"Total r'\" and WF: \"wf(r - Id)\" and WF': \"wf(r' - Id)\"\n  shows \"wf ((r +o r') - Id)\"\nproof(cases \"r \\<le> Id \\<or> r' \\<le> Id\")\n  case False\n  thus ?thesis\n    using osum_minus_Id[of r r'] assms osum_wf[of \"r - Id\" \"r' - Id\"]\n      wf_subset[of \"(r - Id) +o (r' - Id)\" \"(r +o r') - Id\"] by auto\nnext\n  have 1: \"wf (Inl ` Field r \\<times> Inr ` Field r')\" by (rule wf_Int_Times) auto\n  case True\n  thus ?thesis\n  proof (elim disjE)\n    assume \"r \\<subseteq> Id\"\n    thus \"wf ((r +o r') - Id)\"\n      by (rule wf_subset[rotated, OF osum_minus_Id1 wf_Un[OF 1 wf_map_prod_image[OF WF']]]) auto\n  next\n    assume \"r' \\<subseteq> Id\"\n    thus \"wf ((r +o r') - Id)\"\n      by (rule wf_subset[rotated, OF osum_minus_Id2 wf_Un[OF wf_map_prod_image[OF WF] 1]]) auto\n  qed\nqed\n\nlemma osum_Well_order:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\n  shows \"Well_order (r +o r')\"\n  by (meson WELL WELL' osum_Linear_order osum_wf_Id well_order_on_def wo_rel.TOTAL wo_rel.intro)\n\nlemma osum_embedL:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\n  shows \"embed r (r +o r') Inl\"\nproof -\n  have 1: \"Well_order (r +o r')\" using assms by (auto simp add: osum_Well_order)\n  moreover\n  have \"compat r (r +o r') Inl\" unfolding compat_def osum_def by auto\n  moreover\n  have \"ofilter (r +o r') (Inl ` Field r)\"\n    unfolding wo_rel.ofilter_def[unfolded wo_rel_def, OF 1] Field_osum under_def\n    unfolding osum_def Field_def by auto\n  ultimately show ?thesis using assms by (auto simp add: embed_iff_compat_inj_on_ofilter)\nqed\n\ncorollary osum_ordLeqL:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\n  shows \"r \\<le>o r +o r'\"\n  using assms osum_embedL osum_Well_order unfolding ordLeq_def by blast\n\nlemma dir_image_alt: \"dir_image r f = map_prod f f ` r\"\n  unfolding dir_image_def map_prod_def by auto\n\nlemma map_prod_ordIso: \"\\<lbrakk>Well_order r; inj_on f (Field r)\\<rbrakk> \\<Longrightarrow> map_prod f f ` r =o r\"\n  by (metis dir_image_alt dir_image_ordIso ordIso_symmetric)\n\ndefinition oprod :: \"'a rel \\<Rightarrow> 'b rel \\<Rightarrow> ('a \\<times> 'b) rel\"  (infixr \"*o\" 80)\n  where \"r *o r' = {((x1, y1), (x2, y2)).\n  (((y1, y2) \\<in> r' - Id \\<and> x1 \\<in> Field r \\<and> x2 \\<in> Field r) \\<or>\n   ((y1, y2) \\<in> Restr Id (Field r') \\<and> (x1, x2) \\<in> r))}\"\n\nlemma Field_oprod: \"Field (r *o r') = Field r \\<times> Field r'\"\n  unfolding oprod_def Field_def by auto blast+\n\nlemma oprod_Refl:\"\\<lbrakk>Refl r; Refl r'\\<rbrakk> \\<Longrightarrow> Refl (r *o r')\"\n  unfolding refl_on_def Field_oprod unfolding oprod_def by auto\n\nlemma oprod_trans:\n  assumes \"trans r\" \"trans r'\" \"antisym r\" \"antisym r'\"\n  shows \"trans (r *o r')\"\n  using assms by (clarsimp simp: trans_def antisym_def oprod_def) (metis FieldI1 FieldI2)\n\nlemma oprod_Preorder: \"\\<lbrakk>Preorder r; Preorder r'; antisym r; antisym r'\\<rbrakk> \\<Longrightarrow> Preorder (r *o r')\"\n  unfolding preorder_on_def using oprod_Refl oprod_trans by blast\n\nlemma oprod_antisym: \"\\<lbrakk>antisym r; antisym r'\\<rbrakk> \\<Longrightarrow> antisym (r *o r')\"\n  unfolding antisym_def oprod_def by auto\n\nlemma oprod_Partial_order: \"\\<lbrakk>Partial_order r; Partial_order r'\\<rbrakk> \\<Longrightarrow> Partial_order (r *o r')\"\n  unfolding partial_order_on_def using oprod_Preorder oprod_antisym by blast\n\nlemma oprod_Total: \"\\<lbrakk>Total r; Total r'\\<rbrakk> \\<Longrightarrow> Total (r *o r')\"\n  unfolding total_on_def Field_oprod unfolding oprod_def by auto\n\nlemma oprod_Linear_order: \"\\<lbrakk>Linear_order r; Linear_order r'\\<rbrakk> \\<Longrightarrow> Linear_order (r *o r')\"\n  unfolding linear_order_on_def using oprod_Partial_order oprod_Total by blast\n\nlemma oprod_wf:\n  assumes WF: \"wf r\" and WF': \"wf r'\"\n  shows \"wf (r *o r')\"\n  unfolding wf_eq_minimal2 unfolding Field_oprod\nproof(intro allI impI, elim conjE)\n  fix A assume *: \"A \\<subseteq> Field r \\<times> Field r'\" and **: \"A \\<noteq> {}\"\n  then obtain y where y: \"y \\<in> snd ` A\" \"\\<forall>y'\\<in>snd ` A. (y', y) \\<notin> r'\"\n    using spec[OF WF'[unfolded wf_eq_minimal2], of \"snd ` A\"] by auto\n  let ?A = \"fst ` A \\<inter> {x. (x, y) \\<in> A}\"\n  from * y have \"?A \\<noteq> {}\" \"?A \\<subseteq> Field r\" by auto\n  then obtain x where x: \"x \\<in> ?A\" and \"\\<forall>x'\\<in> ?A. (x', x) \\<notin> r\"\n    using spec[OF WF[unfolded wf_eq_minimal2], of \"?A\"] by auto\n  with y have \"\\<forall>a'\\<in>A. (a', (x, y)) \\<notin> r *o r'\"\n    unfolding oprod_def mem_Collect_eq split_beta fst_conv snd_conv Id_def by auto\n  moreover from x have \"(x, y) \\<in> A\" by auto\n  ultimately show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a', a) \\<notin> r *o r'\" by blast\nqed\n\nlemma oprod_minus_Id:\n  assumes r: \"Total r\" \"\\<not> (r \\<le> Id)\" and r': \"Total r'\" \"\\<not> (r' \\<le> Id)\"\n  shows \"(r *o r') - Id \\<le> (r - Id) *o (r' - Id)\"\n  unfolding oprod_def Total_Id_Field[OF r] Total_Id_Field[OF r'] by auto\n\nlemma oprod_minus_Id1:\n  \"r \\<le> Id \\<Longrightarrow> r *o r' - Id \\<le> {((x,y1), (x,y2)). x \\<in> Field r \\<and> (y1, y2) \\<in> (r' - Id)}\"\n  unfolding oprod_def by auto\n\nlemma wf_extend_oprod1:\n  assumes \"wf r\"\n  shows \"wf {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\"\nproof (unfold wf_eq_minimal2, intro allI impI, elim conjE)\n  fix B\n  assume *: \"B \\<subseteq> Field {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\" and \"B \\<noteq> {}\"\n  from image_mono[OF *, of snd] have \"snd ` B \\<subseteq> Field r\" unfolding Field_def by force\n  with \\<open>B \\<noteq> {}\\<close> obtain x where x: \"x \\<in> snd ` B\" \"\\<forall>x'\\<in>snd ` B. (x', x) \\<notin> r\"\n    using spec[OF assms[unfolded wf_eq_minimal2], of \"snd ` B\"] by auto\n  then obtain a where \"(a, x) \\<in> B\" by auto\n  moreover\n  from * x have \"\\<forall>a'\\<in>B. (a', (a, x)) \\<notin> {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\" by auto\n  ultimately show \"\\<exists>ax\\<in>B. \\<forall>a'\\<in>B. (a', ax) \\<notin> {((x,y1), (x,y2)) . x \\<in> A \\<and> (y1, y2) \\<in> r}\" by blast\nqed\n\nlemma oprod_minus_Id2:\n  \"r' \\<le> Id \\<Longrightarrow> r *o r' - Id \\<le> {((x1,y), (x2,y)). (x1, x2) \\<in> (r - Id) \\<and> y \\<in> Field r'}\"\n  unfolding oprod_def by auto\n\nlemma wf_extend_oprod2:\n  assumes \"wf r\"\n  shows \"wf {((x1,y), (x2,y)) . (x1, x2) \\<in> r \\<and> y \\<in> A}\"\nproof (unfold wf_eq_minimal2, intro allI impI, elim conjE)\n  fix B\n  assume *: \"B \\<subseteq> Field {((x1, y), (x2, y)). (x1, x2) \\<in> r \\<and> y \\<in> A}\" and \"B \\<noteq> {}\"\n  from image_mono[OF *, of fst] have \"fst ` B \\<subseteq> Field r\" unfolding Field_def by force\n  with \\<open>B \\<noteq> {}\\<close> obtain x where x: \"x \\<in> fst ` B\" \"\\<forall>x'\\<in>fst ` B. (x', x) \\<notin> r\"\n    using spec[OF assms[unfolded wf_eq_minimal2], of \"fst ` B\"] by auto\n  then obtain a where \"(x, a) \\<in> B\" by auto\n  moreover\n  from * x have \"\\<forall>a'\\<in>B. (a', (x, a)) \\<notin> {((x1, y), x2, y). (x1, x2) \\<in> r \\<and> y \\<in> A}\" by auto\n  ultimately show \"\\<exists>xa\\<in>B. \\<forall>a'\\<in>B. (a', xa) \\<notin> {((x1, y), x2, y). (x1, x2) \\<in> r \\<and> y \\<in> A}\" by blast\nqed\n\nlemma oprod_wf_Id:\n  assumes TOT: \"Total r\" and TOT': \"Total r'\" and WF: \"wf(r - Id)\" and WF': \"wf(r' - Id)\"\n  shows \"wf ((r *o r') - Id)\"\nproof(cases \"r \\<le> Id \\<or> r' \\<le> Id\")\n  case False\n  thus ?thesis\n    by (meson TOT TOT' WF WF' oprod_minus_Id oprod_wf wf_subset)\nnext\n  case True\n  thus ?thesis using wf_subset[OF wf_extend_oprod1[OF WF'] oprod_minus_Id1]\n      wf_subset[OF wf_extend_oprod2[OF WF] oprod_minus_Id2] by auto\nqed\n\nlemma oprod_Well_order:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\"\n  shows \"Well_order (r *o r')\"\n  by (meson WELL WELL' linear_order_on_def oprod_Linear_order oprod_wf_Id well_order_on_def)\n\nlemma oprod_embed:\n  assumes WELL: \"Well_order r\" and WELL': \"Well_order r'\" and \"r' \\<noteq> {}\"\n  shows \"embed r (r *o r') (\\<lambda>x. (x, minim r' (Field r')))\" (is \"embed _ _ ?f\")\nproof -\n  from assms(3) have r': \"Field r' \\<noteq> {}\" unfolding Field_def by auto\n  have minim[simp]: \"minim r' (Field r') \\<in> Field r'\"\n    using wo_rel.minim_inField[unfolded wo_rel_def, OF WELL' _ r'] by auto\n  { fix b\n    assume b: \"(b, minim r' (Field r')) \\<in> r'\"\n    hence \"b \\<in> Field r'\" unfolding Field_def by auto\n    hence \"(minim r' (Field r'), b) \\<in> r'\"\n      using wo_rel.minim_least[unfolded wo_rel_def, OF WELL' subset_refl] r' by auto\n    with b have \"b = minim r' (Field r')\"\n      by (metis WELL' antisym_def linear_order_on_def partial_order_on_def well_order_on_def)\n  } note * = this\n  have 1: \"Well_order (r *o r')\" using assms by (auto simp add: oprod_Well_order)\n  moreover\n  from r' have \"compat r (r *o r') ?f\"  unfolding compat_def oprod_def by auto\n  moreover\n  from * have \"ofilter (r *o r') (?f ` Field r)\"\n    unfolding wo_rel.ofilter_def[unfolded wo_rel_def, OF 1] Field_oprod under_def\n    unfolding oprod_def by auto (auto simp: image_iff Field_def)\n  moreover have \"inj_on ?f (Field r)\" unfolding inj_on_def by auto\n  ultimately show ?thesis using assms by (auto simp add: embed_iff_compat_inj_on_ofilter)\nqed\n\ncorollary oprod_ordLeq: \"\\<lbrakk>Well_order r; Well_order r'; r' \\<noteq> {}\\<rbrakk> \\<Longrightarrow> r \\<le>o r *o r'\"\n  using oprod_embed oprod_Well_order unfolding ordLeq_def by blast\n\ndefinition \"support z A f = {x \\<in> A. f x \\<noteq> z}\"\n\nlemma support_Un[simp]: \"support z (A \\<union> B) f = support z A f \\<union> support z B f\"\n  unfolding support_def by auto\n\nlemma support_upd[simp]: \"support z A (f(x := z)) = support z A f - {x}\"\n  unfolding support_def by auto\n\nlemma support_upd_subset[simp]: \"support z A (f(x := y)) \\<subseteq> support z A f \\<union> {x}\"\n  unfolding support_def by auto\n\nlemma fun_unequal_in_support:\n  assumes \"f \\<noteq> g\" \"f \\<in> Func A B\" \"g \\<in> Func A C\"\n  shows \"(support z A f \\<union> support z A g) \\<inter> {a. f a \\<noteq> g a} \\<noteq> {}\" \n  using assms by (simp add: Func_def support_def disjoint_iff fun_eq_iff) metis\n\ndefinition fin_support where\n  \"fin_support z A = {f. finite (support z A f)}\"\n\nlemma finite_support: \"f \\<in> fin_support z A \\<Longrightarrow> finite (support z A f)\"\n  unfolding support_def fin_support_def by auto\n\nlemma fin_support_Field_osum:\n  \"f \\<in> fin_support z (Inl ` A \\<union> Inr ` B) \\<longleftrightarrow>\n  (f o Inl) \\<in> fin_support z A \\<and> (f o Inr) \\<in> fin_support z B\" (is \"?L \\<longleftrightarrow> ?R1 \\<and> ?R2\")\nproof safe\n  assume ?L\n  from \\<open>?L\\<close> show ?R1 unfolding fin_support_def support_def\n    by (fastforce simp: image_iff elim: finite_surj[of _ _ \"case_sum id undefined\"])\n  from \\<open>?L\\<close> show ?R2 unfolding fin_support_def support_def\n    by (fastforce simp: image_iff elim: finite_surj[of _ _ \"case_sum undefined id\"])\nnext\n  assume ?R1 ?R2\n  thus ?L unfolding fin_support_def support_Un\n    by (auto simp: support_def elim: finite_surj[of _ _ Inl] finite_surj[of _ _ Inr])\nqed\n\nlemma Func_upd: \"\\<lbrakk>f \\<in> Func A B; x \\<in> A; y \\<in> B\\<rbrakk> \\<Longrightarrow> f(x := y) \\<in> Func A B\"\n  unfolding Func_def by auto\n\ncontext wo_rel\nbegin\n\ndefinition isMaxim :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"isMaxim A b \\<equiv> b \\<in> A \\<and> (\\<forall>a \\<in> A. (a,b) \\<in> r)\"\n\ndefinition maxim :: \"'a set \\<Rightarrow> 'a\"\n  where \"maxim A \\<equiv> THE b. isMaxim A b\"\n\nlemma isMaxim_unique[intro]: \"\\<lbrakk>isMaxim A x; isMaxim A y\\<rbrakk> \\<Longrightarrow> x = y\"\n  unfolding isMaxim_def using antisymD[OF ANTISYM, of x y] by auto\n\nlemma maxim_isMaxim: \"\\<lbrakk>finite A; A \\<noteq> {}; A \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> isMaxim A (maxim A)\"\n  unfolding maxim_def\nproof (rule theI', rule ex_ex1I[OF _ isMaxim_unique, rotated], assumption+,\n    induct A rule: finite_induct)\n  case (insert x A)\n  thus ?case\n  proof (cases \"A = {}\")\n    case True\n    moreover have \"isMaxim {x} x\" unfolding isMaxim_def using refl_onD[OF REFL] insert(5) by auto\n    ultimately show ?thesis by blast\n  next\n    case False\n    with insert(3,5) obtain y where \"isMaxim A y\" by blast\n    with insert(2,5) have \"if (y, x) \\<in> r then isMaxim (insert x A) x else isMaxim (insert x A) y\"\n      unfolding isMaxim_def subset_eq by (metis insert_iff max2_def max2_equals1 max2_iff)\n    thus ?thesis by metis\n  qed\nqed simp\n\nlemma maxim_in: \"\\<lbrakk>finite A; A \\<noteq> {}; A \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> maxim A \\<in> A\"\n  using maxim_isMaxim unfolding isMaxim_def by auto\n\nlemma maxim_greatest: \"\\<lbrakk>finite A; x \\<in> A; A \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> (x, maxim A) \\<in> r\"\n  using maxim_isMaxim unfolding isMaxim_def by auto\n\nlemma isMaxim_zero: \"isMaxim A zero \\<Longrightarrow> A = {zero}\"\n  unfolding isMaxim_def by auto\n\nlemma maxim_insert:\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> Field r\" \"x \\<in> Field r\"\n  shows \"maxim (insert x A) = max2 x (maxim A)\"\nproof -\n  from assms have *: \"isMaxim (insert x A) (maxim (insert x A))\" \"isMaxim A (maxim A)\"\n    using maxim_isMaxim by auto\n  show ?thesis\n  proof (cases \"(x, maxim A) \\<in> r\")\n    case True\n    with *(2) have \"isMaxim (insert x A) (maxim A)\"\n      by (simp add: isMaxim_def)\n    with *(1) True show ?thesis \n      unfolding max2_def by (metis isMaxim_unique)\n  next\n    case False\n    hence \"(maxim A, x) \\<in> r\" by (metis *(2) assms(3,4) in_mono in_notinI isMaxim_def)\n    with *(2) assms(4) have \"isMaxim (insert x A) x\" unfolding isMaxim_def\n      using transD[OF TRANS, of _ \"maxim A\" x] refl_onD[OF REFL, of x] by blast\n    with *(1) False show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  qed\nqed\n\nlemma maxim_Un:\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> Field r\" \"finite B\" \"B \\<noteq> {}\" \"B \\<subseteq> Field r\"\n  shows   \"maxim (A \\<union> B) = max2 (maxim A) (maxim B)\"\nproof -\n  from assms have *: \"isMaxim (A \\<union> B) (maxim (A \\<union> B))\" \"isMaxim A (maxim A)\" \"isMaxim B (maxim B)\"\n    using maxim_isMaxim by auto\n  show ?thesis\n  proof (cases \"(maxim A, maxim B) \\<in> r\")\n    case True\n    with *(2,3) have \"isMaxim (A \\<union> B) (maxim B)\" unfolding isMaxim_def\n      using transD[OF TRANS, of _ \"maxim A\" \"maxim B\"] by blast\n    with *(1) True show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  next\n    case False\n    hence \"(maxim B, maxim A) \\<in> r\" by (metis *(2,3) assms(3,6) in_mono in_notinI isMaxim_def)\n    with *(2,3) have \"isMaxim (A \\<union> B) (maxim A)\"\n      by (metis \"*\"(1) False Un_iff isMaxim_def isMaxim_unique)\n    with *(1) False show ?thesis unfolding max2_def by (metis isMaxim_unique)\n  qed\nqed\n\nlemma maxim_insert_zero:\n  assumes \"finite A\" \"A \\<noteq> {}\" \"A \\<subseteq> Field r\"\n  shows \"maxim (insert zero A) = maxim A\"\n  using assms finite.cases in_mono max2_def maxim_in maxim_insert subset_empty zero_in_Field zero_smallest by fastforce\n\nlemma maxim_equality: \"isMaxim A x \\<Longrightarrow> maxim A = x\"\n  unfolding maxim_def by (rule the_equality) auto\n\nlemma maxim_singleton:\n  \"x \\<in> Field r \\<Longrightarrow> maxim {x} = x\"\n  using refl_onD[OF REFL] by (intro maxim_equality) (simp add: isMaxim_def)\n\nlemma maxim_Int: \"\\<lbrakk>finite A; A \\<noteq> {}; A \\<subseteq> Field r; maxim A \\<in> B\\<rbrakk> \\<Longrightarrow> maxim (A \\<inter> B) = maxim A\"\n  by (rule maxim_equality) (auto simp: isMaxim_def intro: maxim_in maxim_greatest)\n\nlemma maxim_mono: \"\\<lbrakk>X \\<subseteq> Y; finite Y; X \\<noteq> {}; Y \\<subseteq> Field r\\<rbrakk> \\<Longrightarrow> (maxim X, maxim Y) \\<in> r\"\n  using maxim_in[OF finite_subset, of X Y] by (auto intro: maxim_greatest)\n\ndefinition \"max_fun_diff f g \\<equiv> maxim ({a \\<in> Field r. f a \\<noteq> g a})\"\n\nlemma max_fun_diff_commute: \"max_fun_diff f g = max_fun_diff g f\"\n  unfolding max_fun_diff_def by metis\n\nlemma zero_under: \"x \\<in> Field r \\<Longrightarrow> zero \\<in> under x\"\n  unfolding under_def by (auto intro: zero_smallest)\n\nend\n\ndefinition \"FinFunc r s = Func (Field s) (Field r) \\<inter> fin_support (zero r) (Field s)\"\n\nlemma FinFuncD: \"\\<lbrakk>f \\<in> FinFunc r s; x \\<in> Field s\\<rbrakk> \\<Longrightarrow> f x \\<in> Field r\"\n  unfolding FinFunc_def Func_def by (fastforce split: option.splits)\n\nlocale wo_rel2 =\n  fixes r s\n  assumes rWELL: \"Well_order r\"\n    and     sWELL: \"Well_order s\"\nbegin\n\ninterpretation r: wo_rel r by unfold_locales (rule rWELL)\ninterpretation s: wo_rel s by unfold_locales (rule sWELL)\n\nabbreviation \"SUPP \\<equiv> support r.zero (Field s)\"\nabbreviation \"FINFUNC \\<equiv> FinFunc r s\"\nlemmas FINFUNCD = FinFuncD[of _ r s]\n\nlemma fun_diff_alt: \"{a \\<in> Field s. f a \\<noteq> g a} = (SUPP f \\<union> SUPP g) \\<inter> {a. f a \\<noteq> g a}\"\n  by (auto simp: support_def)\n\nlemma max_fun_diff_alt:\n  \"s.max_fun_diff f g = s.maxim ((SUPP f \\<union> SUPP g) \\<inter> {a. f a \\<noteq> g a})\"\n  unfolding s.max_fun_diff_def fun_diff_alt ..\n\nlemma isMaxim_max_fun_diff: \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC\\<rbrakk> \\<Longrightarrow>\n  s.isMaxim {a \\<in> Field s. f a \\<noteq> g a} (s.max_fun_diff f g)\"\n  using fun_unequal_in_support[of f g] unfolding max_fun_diff_alt fun_diff_alt fun_eq_iff\n  by (intro s.maxim_isMaxim) (auto simp: FinFunc_def fin_support_def support_def)\n\nlemma max_fun_diff_in: \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC\\<rbrakk> \\<Longrightarrow>\n  s.max_fun_diff f g \\<in> {a \\<in> Field s. f a \\<noteq> g a}\"\n  using isMaxim_max_fun_diff unfolding s.isMaxim_def by blast\n\nlemma max_fun_diff_max: \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC; x \\<in> {a \\<in> Field s. f a \\<noteq> g a}\\<rbrakk> \\<Longrightarrow>\n  (x, s.max_fun_diff f g) \\<in> s\"\n  using isMaxim_max_fun_diff unfolding s.isMaxim_def by blast\n\nlemma max_fun_diff:\n  \"\\<lbrakk>f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC\\<rbrakk> \\<Longrightarrow>\n  (\\<exists>a b. a \\<noteq> b \\<and> a \\<in> Field r \\<and> b \\<in> Field r \\<and>\n     f (s.max_fun_diff f g) = a \\<and> g (s.max_fun_diff f g) = b)\"\n  using isMaxim_max_fun_diff[of f g] unfolding s.isMaxim_def FinFunc_def Func_def by auto\n\nlemma max_fun_diff_le_eq:\n  \"\\<lbrakk>(s.max_fun_diff f g, x) \\<in> s; f \\<noteq> g; f \\<in> FINFUNC; g \\<in> FINFUNC; x \\<noteq> s.max_fun_diff f g\\<rbrakk> \\<Longrightarrow>\n  f x = g x\"\n  using max_fun_diff_max[of f g x] antisymD[OF s.ANTISYM, of \"s.max_fun_diff f g\" x]\n  by (auto simp: Field_def)\n\nlemma max_fun_diff_max2:\n  assumes ineq: \"s.max_fun_diff f g = s.max_fun_diff g h \\<longrightarrow>\n    f (s.max_fun_diff f g) \\<noteq> h (s.max_fun_diff g h)\" and\n    fg: \"f \\<noteq> g\" and gh: \"g \\<noteq> h\" and fh: \"f \\<noteq> h\" and\n    f: \"f \\<in> FINFUNC\" and g: \"g \\<in> FINFUNC\" and h: \"h \\<in> FINFUNC\"\n  shows \"s.max_fun_diff f h = s.max2 (s.max_fun_diff f g) (s.max_fun_diff g h)\"\n    (is \"?fh = s.max2 ?fg ?gh\")\nproof (cases \"?fg = ?gh\")\n  case True\n  with ineq have \"f ?fg \\<noteq> h ?fg\" by simp\n  moreover\n  { fix x assume x: \"x \\<in> {a \\<in> Field s. f a \\<noteq> h a}\"\n    hence \"(x, ?fg) \\<in> s\"\n    proof (cases \"x = ?fg\")\n      case False show ?thesis\n        by (metis (mono_tags, lifting) True assms(5-7) max_fun_diff_max mem_Collect_eq x)\n    qed (simp add: refl_onD[OF s.REFL])\n  }\n  ultimately have \"s.isMaxim {a \\<in> Field s. f a \\<noteq> h a} ?fg\"\n    unfolding s.isMaxim_def using max_fun_diff_in[OF fg f g] by simp\n  hence \"?fh = ?fg\" using isMaxim_max_fun_diff[OF fh f h] by blast\n  thus ?thesis unfolding True s.max2_def by simp\nnext\n  case False note * = this\n  show ?thesis\n  proof (cases \"(?fg, ?gh) \\<in> s\")\n    case True\n    hence *: \"f ?gh = g ?gh\" by (rule max_fun_diff_le_eq[OF _ fg f g *[symmetric]])\n    hence \"s.isMaxim {a \\<in> Field s. f a \\<noteq> h a} ?gh\" using isMaxim_max_fun_diff[OF gh g h]\n        isMaxim_max_fun_diff[OF fg f g] transD[OF s.TRANS _ True]\n      unfolding s.isMaxim_def by auto\n    hence \"?fh = ?gh\" using isMaxim_max_fun_diff[OF fh f h] by blast\n    thus ?thesis using True unfolding s.max2_def by simp\n  next\n    case False\n    with max_fun_diff_in[OF fg f g] max_fun_diff_in[OF gh g h] have True: \"(?gh, ?fg) \\<in> s\"\n      by (blast intro: s.in_notinI)\n    hence *: \"g ?fg = h ?fg\" by (rule max_fun_diff_le_eq[OF _ gh g h *])\n    hence \"s.isMaxim {a \\<in> Field s. f a \\<noteq> h a} ?fg\" using isMaxim_max_fun_diff[OF gh g h]\n        isMaxim_max_fun_diff[OF fg f g] True transD[OF s.TRANS, of _ _ ?fg]\n      unfolding s.isMaxim_def by auto\n    hence \"?fh = ?fg\" using isMaxim_max_fun_diff[OF fh f h] by blast\n    thus ?thesis using False unfolding s.max2_def by simp\n  qed\nqed\n\ndefinition oexp where\n  \"oexp = {(f, g) . f \\<in> FINFUNC \\<and> g \\<in> FINFUNC \\<and>\n    ((let m = s.max_fun_diff f g in (f m, g m) \\<in> r) \\<or> f = g)}\"\n\nlemma Field_oexp: \"Field oexp = FINFUNC\"\n  unfolding oexp_def FinFunc_def by (auto simp: Let_def Field_def)\n\nlemma oexp_Refl: \"Refl oexp\"\n  unfolding refl_on_def Field_oexp unfolding oexp_def by (auto simp: Let_def)\n\nlemma oexp_trans: \"trans oexp\"\nproof (unfold trans_def, safe)\n  fix f g h :: \"'b \\<Rightarrow> 'a\"\n  let ?fg = \"s.max_fun_diff f g\"\n    and ?gh = \"s.max_fun_diff g h\"\n    and ?fh = \"s.max_fun_diff f h\"\n  assume oexp: \"(f, g) \\<in> oexp\" \"(g, h) \\<in> oexp\"\n  thus \"(f, h) \\<in> oexp\"\n  proof (cases \"f = g \\<or> g = h\")\n    case False\n    with oexp have \"f \\<in> FINFUNC\" \"g \\<in> FINFUNC\" \"h \\<in> FINFUNC\"\n      \"(f ?fg, g ?fg) \\<in> r\" \"(g ?gh, h ?gh) \\<in> r\" unfolding oexp_def Let_def by auto\n    note * = this False\n    show ?thesis\n    proof (cases \"f \\<noteq> h\")\n      case True\n      show ?thesis\n      proof (cases \"?fg = ?gh \\<longrightarrow> f ?fg \\<noteq> h ?gh\")\n        case True\n        show ?thesis using max_fun_diff_max2[of f g h, OF True] * \\<open>f \\<noteq> h\\<close> max_fun_diff_in\n            r.max2_iff[OF FINFUNCD FINFUNCD] r.max2_equals1[OF FINFUNCD FINFUNCD] max_fun_diff_le_eq\n            s.in_notinI[OF disjI1] unfolding oexp_def Let_def s.max2_def mem_Collect_eq by safe metis\n      next\n        case False with * show ?thesis unfolding oexp_def Let_def\n          using antisymD[OF r.ANTISYM, of \"g ?gh\" \"h ?gh\"] max_fun_diff_in[of g h] by auto\n      qed\n    qed (auto simp: oexp_def *(3))\n  qed auto\nqed\n\nlemma oexp_Preorder: \"Preorder oexp\"\n  unfolding preorder_on_def using oexp_Refl oexp_trans by blast\n\nlemma oexp_antisym: \"antisym oexp\"\nproof (unfold antisym_def, safe, rule ccontr)\n  fix f g assume \"(f, g) \\<in> oexp\" \"(g, f) \\<in> oexp\" \"g \\<noteq> f\"\n  thus False using refl_onD[OF r.REFL FINFUNCD] max_fun_diff_in unfolding oexp_def Let_def\n    by (auto dest!: antisymD[OF r.ANTISYM] simp: s.max_fun_diff_commute)\nqed\n\nlemma oexp_Partial_order: \"Partial_order oexp\"\n  unfolding partial_order_on_def using oexp_Preorder oexp_antisym by blast\n\nlemma oexp_Total: \"Total oexp\"\n  unfolding total_on_def Field_oexp unfolding oexp_def using FINFUNCD max_fun_diff_in\n  by (auto simp: Let_def s.max_fun_diff_commute intro!: r.in_notinI)\n\nlemma oexp_Linear_order: \"Linear_order oexp\"\n  unfolding linear_order_on_def using oexp_Partial_order oexp_Total by blast\n\ndefinition \"const = (\\<lambda>x. if x \\<in> Field s then r.zero else undefined)\"\n\nlemma const_in[simp]: \"x \\<in> Field s \\<Longrightarrow> const x = r.zero\"\n  unfolding const_def by auto\n\nlemma const_notin[simp]: \"x \\<notin> Field s \\<Longrightarrow> const x = undefined\"\n  unfolding const_def by auto\n\nlemma const_Int_Field[simp]: \"Field s \\<inter> - {x. const x = r.zero} = {}\"\n  by auto\n\nlemma const_FINFUNC[simp]: \"Field r \\<noteq> {} \\<Longrightarrow> const \\<in> FINFUNC\"\n  unfolding FinFunc_def Func_def fin_support_def support_def const_def Int_iff mem_Collect_eq\n  using r.zero_in_Field by (metis (lifting) Collect_empty_eq finite.emptyI)\n\nlemma const_least:\n  assumes \"Field r \\<noteq> {}\" \"f \\<in> FINFUNC\"\n  shows \"(const, f) \\<in> oexp\"\n  using assms const_FINFUNC max_fun_diff max_fun_diff_in oexp_def by fastforce\n\nlemma support_not_const:\n  assumes \"F \\<subseteq> FINFUNC\" and \"const \\<notin> F\"\n  shows \"\\<forall>f \\<in> F. finite (SUPP f) \\<and> SUPP f \\<noteq> {} \\<and> SUPP f \\<subseteq> Field s\"\nproof (intro ballI conjI)\n  fix f assume \"f \\<in> F\"\n  thus \"finite (SUPP f)\" \"SUPP f \\<subseteq> Field s\"\n    using assms(1) unfolding FinFunc_def fin_support_def support_def by auto\n  show \"SUPP f \\<noteq> {}\"\n  proof (rule ccontr, unfold not_not)\n    assume \"SUPP f = {}\"\n    moreover from \\<open>f \\<in> F\\<close> assms(1) have \"f \\<in> FINFUNC\" by blast\n    ultimately have \"f = const\"\n      by (auto simp: fun_eq_iff support_def FinFunc_def Func_def const_def)\n    with assms(2) \\<open>f \\<in> F\\<close> show False by blast\n  qed\nqed\n\nlemma maxim_isMaxim_support:\n  assumes \"F \\<subseteq> FINFUNC\" and \"const \\<notin> F\"\n  shows \"\\<forall>f \\<in> F. s.isMaxim (SUPP f) (s.maxim (SUPP f))\"\n  using assms s.maxim_isMaxim support_not_const by force\n\nlemma oexp_empty2: \"Field s = {} \\<Longrightarrow> oexp = {(\\<lambda>x. undefined, \\<lambda>x. undefined)}\"\n  unfolding oexp_def FinFunc_def fin_support_def support_def by auto\n\nlemma oexp_empty: \"\\<lbrakk>Field r = {}; Field s \\<noteq> {}\\<rbrakk> \\<Longrightarrow> oexp = {}\"\n  using FINFUNCD oexp_def by auto\n\nlemma fun_upd_FINFUNC: \"\\<lbrakk>f \\<in> FINFUNC; x \\<in> Field s; y \\<in> Field r\\<rbrakk> \\<Longrightarrow> f(x := y) \\<in> FINFUNC\"\n  unfolding FinFunc_def Func_def fin_support_def\n  by (auto intro: finite_subset[OF support_upd_subset])\n\nlemma fun_upd_same_oexp:\n  assumes \"(f, g) \\<in> oexp\" \"f x = g x\" \"x \\<in> Field s\" \"y \\<in> Field r\"\n  shows   \"(f(x := y), g(x := y)) \\<in> oexp\"\nproof -\n  from assms(1) fun_upd_FINFUNC[OF _ assms(3,4)] have fg: \"f(x := y) \\<in> FINFUNC\" \"g(x := y) \\<in> FINFUNC\"\n    unfolding oexp_def by auto\n  moreover from assms(2) have \"s.max_fun_diff (f(x := y)) (g(x := y)) = s.max_fun_diff f g\"\n    unfolding s.max_fun_diff_def by auto metis\n  ultimately show ?thesis using assms refl_onD[OF r.REFL] unfolding oexp_def Let_def by auto\nqed\n\nlemma fun_upd_smaller_oexp:\n  assumes \"f \\<in> FINFUNC\" \"x \\<in> Field s\" \"y \\<in> Field r\"  \"(y, f x) \\<in> r\"\n  shows   \"(f(x := y), f) \\<in> oexp\"\n  using assms fun_upd_FINFUNC[OF assms(1-3)] s.maxim_singleton[of \"x\"]\n  unfolding oexp_def FinFunc_def Let_def fin_support_def s.max_fun_diff_def by (auto simp: fun_eq_iff)\n\nlemma oexp_wf_Id: \"wf (oexp - Id)\"\nproof (cases \"Field r = {} \\<or> Field s = {}\")\n  case True thus ?thesis using oexp_empty oexp_empty2 by fastforce\nnext\n  case False\n  hence Fields: \"Field s \\<noteq> {}\" \"Field r \\<noteq> {}\" by simp_all\n  hence [simp]: \"r.zero \\<in> Field r\" by (intro r.zero_in_Field)\n  have const[simp]: \"\\<And>F. \\<lbrakk>const \\<in> F; F \\<subseteq> FINFUNC\\<rbrakk> \\<Longrightarrow> \\<exists>f0\\<in>F. \\<forall>f\\<in>F. (f0, f) \\<in> oexp\"\n    using const_least[OF Fields(2)] by auto\n  show ?thesis\n    unfolding Linear_order_wf_diff_Id[OF oexp_Linear_order] Field_oexp\n  proof (intro allI impI)\n    fix A assume A: \"A \\<subseteq> FINFUNC\" \"A \\<noteq> {}\"\n    { fix y F\n      have \"F \\<subseteq> FINFUNC \\<and> (\\<exists>f \\<in> F. y = s.maxim (SUPP f)) \\<longrightarrow>\n        (\\<exists>f0 \\<in> F. \\<forall>f \\<in> F. (f0, f) \\<in> oexp)\" (is \"?P F y\")\n      proof (induct y arbitrary: F rule: s.well_order_induct)\n        case (1 y)\n        show ?case\n        proof (intro impI, elim conjE bexE)\n          fix f assume F: \"F \\<subseteq> FINFUNC\" \"f \\<in> F\" \"y = s.maxim (SUPP f)\"\n          thus \"\\<exists>f0\\<in>F. \\<forall>f\\<in>F. (f0, f) \\<in> oexp\"\n          proof (cases \"const \\<in> F\")\n            case False\n            with F have maxF: \"\\<forall>f \\<in> F. s.isMaxim (SUPP f) (s.maxim (SUPP f))\"\n              and SUPPF: \"\\<forall>f \\<in> F. finite (SUPP f) \\<and> SUPP f \\<noteq> {} \\<and> SUPP f \\<subseteq> Field s\"\n              using maxim_isMaxim_support support_not_const by auto\n            define z where \"z = s.minim {s.maxim (SUPP f) | f. f \\<in> F}\"\n            from F SUPPF maxF have zmin: \"s.isMinim {s.maxim (SUPP f) | f. f \\<in> F} z\"\n              unfolding z_def by (intro s.minim_isMinim) (auto simp: s.isMaxim_def)\n            with F have zy: \"(z, y) \\<in> s\" unfolding s.isMinim_def by auto\n            hence zField: \"z \\<in> Field s\" unfolding Field_def by auto\n            define x0 where \"x0 = r.minim {f z | f. f \\<in> F \\<and> z = s.maxim (SUPP f)}\"\n            from F(1,2) maxF(1) SUPPF zmin\n            have x0min: \"r.isMinim {f z | f. f \\<in> F \\<and> z = s.maxim (SUPP f)} x0\"\n              unfolding x0_def s.isMaxim_def s.isMinim_def\n              by (blast intro!: r.minim_isMinim FinFuncD[of _ r s])\n            with maxF(1) SUPPF F(1) have x0Field: \"x0 \\<in> Field r\"\n              unfolding r.isMinim_def s.isMaxim_def by (auto intro!: FINFUNCD)\n            from x0min maxF(1) SUPPF F(1) have x0notzero: \"x0 \\<noteq> r.zero\"\n              unfolding r.isMinim_def s.isMaxim_def FinFunc_def Func_def support_def\n              by fastforce\n            define G where \"G = {f(z := r.zero) | f. f \\<in> F \\<and> z = s.maxim (SUPP f) \\<and> f z = x0}\"\n            from zmin x0min have \"G \\<noteq> {}\" unfolding G_def z_def s.isMinim_def r.isMinim_def by blast\n            have GF: \"G \\<subseteq> (\\<lambda>f. f(z := r.zero)) ` F\" unfolding G_def by auto\n            have \"G \\<subseteq> fin_support r.zero (Field s)\"\n              unfolding FinFunc_def fin_support_def\n              using F(1) FinFunc_def G_def fin_support_def by fastforce\n            moreover from F GF zField have \"G \\<subseteq> Func (Field s) (Field r)\"\n              using Func_upd[of _ \"Field s\" \"Field r\" z r.zero] unfolding FinFunc_def by auto\n            ultimately have G: \"G \\<subseteq> FINFUNC\" unfolding FinFunc_def by blast\n            hence \"\\<exists>g0\\<in>G. \\<forall>g\\<in>G. (g0, g) \\<in> oexp\"\n            proof (cases \"const \\<in> G\")\n              case False\n              with G have maxG: \"\\<forall>g \\<in> G. s.isMaxim (SUPP g) (s.maxim (SUPP g))\"\n                and SUPPG: \"\\<forall>g \\<in> G. finite (SUPP g) \\<and> SUPP g \\<noteq> {} \\<and> SUPP g \\<subseteq> Field s\"\n                using maxim_isMaxim_support support_not_const by auto\n              define y' where \"y' = s.minim {s.maxim (SUPP f) | f. f \\<in> G}\"\n              from G SUPPG maxG \\<open>G \\<noteq> {}\\<close> have y'min: \"s.isMinim {s.maxim (SUPP f) | f. f \\<in> G} y'\"\n                unfolding y'_def by (intro s.minim_isMinim) (auto simp: s.isMaxim_def)\n              moreover\n              have \"\\<forall>g \\<in> G. z \\<notin> SUPP g\" unfolding support_def G_def by auto\n              moreover\n              { fix g assume g: \"g \\<in> G\"\n                then obtain f where \"f \\<in> F\" \"g = f(z := r.zero)\" and z: \"z = s.maxim (SUPP f)\"\n                  unfolding G_def by auto\n                with SUPPF bspec[OF SUPPG g] have \"(s.maxim (SUPP g), z) \\<in> s\"\n                  unfolding z by (intro s.maxim_mono) auto\n              }\n              moreover from y'min have \"\\<And>g. g \\<in> G \\<Longrightarrow> (y', s.maxim (SUPP g)) \\<in> s\"\n                unfolding s.isMinim_def by auto\n              ultimately have \"y' \\<noteq> z\" \"(y', z) \\<in> s\" using maxG\n                unfolding s.isMinim_def s.isMaxim_def by auto\n              with zy have \"y' \\<noteq> y\" \"(y', y) \\<in> s\" using antisymD[OF s.ANTISYM] transD[OF s.TRANS]\n                by blast+\n              moreover from \\<open>G \\<noteq> {}\\<close> have \"\\<exists>g \\<in> G. y' = wo_rel.maxim s (SUPP g)\" using y'min\n                by (auto simp: G_def s.isMinim_def)\n              ultimately show ?thesis using mp[OF spec[OF mp[OF spec[OF 1]]], of y' G] G by auto\n            qed simp\n            then obtain g0 where g0: \"g0 \\<in> G\" \"\\<forall>g \\<in> G. (g0, g) \\<in> oexp\" by blast\n            hence g0z: \"g0 z = r.zero\" unfolding G_def by auto\n            define f0 where \"f0 = g0(z := x0)\"\n            with x0notzero zField have SUPP: \"SUPP f0 = SUPP g0 \\<union> {z}\" unfolding support_def by auto\n            from g0z have f0z: \"f0(z := r.zero) = g0\" unfolding f0_def fun_upd_upd by auto\n            have f0: \"f0 \\<in> F\" using x0min g0(1)\n                Func_elim[OF subsetD[OF subset_trans[OF F(1)[unfolded FinFunc_def] Int_lower1]] zField]\n              unfolding f0_def r.isMinim_def G_def by (force simp: fun_upd_idem)\n            from g0(1) maxF(1) have maxf0: \"s.maxim (SUPP f0) = z\" unfolding SUPP G_def\n              by (intro s.maxim_equality) (auto simp: s.isMaxim_def)\n            show ?thesis\n            proof (intro bexI[OF _ f0] ballI)\n              fix f assume f: \"f \\<in> F\"\n              show \"(f0, f) \\<in> oexp\"\n              proof (cases \"f0 = f\")\n                case True thus ?thesis by (metis F(1) Field_oexp f0 in_mono oexp_Refl refl_onD)\n              next\n                case False\n                thus ?thesis\n                proof (cases \"s.maxim (SUPP f) = z \\<and> f z = x0\")\n                  case True\n                  with f have \"f(z := r.zero) \\<in> G\" unfolding G_def by blast\n                  with g0(2) f0z have \"(f0(z := r.zero), f(z := r.zero)) \\<in> oexp\" by auto\n                  hence oexp: \"(f0(z := r.zero, z := x0), f(z := r.zero, z := x0)) \\<in> oexp\"\n                    by (elim fun_upd_same_oexp[OF _ _ zField x0Field]) simp\n                  with f F(1) x0min True\n                  have \"(f(z := x0), f) \\<in> oexp\" unfolding G_def r.isMinim_def\n                    by (intro fun_upd_smaller_oexp[OF _ zField x0Field]) auto\n                  with oexp show ?thesis using transD[OF oexp_trans, of f0 \"f(z := x0)\" f]\n                    unfolding f0_def by auto\n                next\n                  case False note notG = this\n                  thus ?thesis\n                  proof (cases \"s.maxim (SUPP f) = z\")\n                    case True\n                    with notG have \"f0 z \\<noteq> f z\" unfolding f0_def by auto\n                    hence \"f0 z \\<noteq> f z\" by metis\n                    with True maxf0 f0 f SUPPF have \"s.max_fun_diff f0 f = z\"\n                      using s.maxim_Un[of \"SUPP f0\" \"SUPP f\", unfolded s.max2_def]\n                      unfolding max_fun_diff_alt by (intro trans[OF s.maxim_Int]) auto\n                    moreover\n                    from x0min True f have \"(x0, f z) \\<in> r\" unfolding r.isMinim_def by auto\n                    ultimately show ?thesis using f f0 F(1) unfolding oexp_def f0_def by auto\n                  next\n                    case False\n                    with notG have *: \"(z, s.maxim (SUPP f)) \\<in> s\" \"z \\<noteq> s.maxim (SUPP f)\"\n                      using zmin f unfolding s.isMinim_def G_def by auto\n                    have f0f: \"f0 (s.maxim (SUPP f)) = r.zero\"\n                    proof (rule ccontr)\n                      assume \"f0 (s.maxim (SUPP f)) \\<noteq> r.zero\"\n                      with f SUPPF maxF(1) have \"s.maxim (SUPP f) \\<in> SUPP f0\"\n                        unfolding support_def[of _ _ f0] s.isMaxim_def by auto\n                      with SUPPF f0 have \"(s.maxim (SUPP f), z) \\<in> s\" unfolding maxf0[symmetric]\n                        by (auto intro: s.maxim_greatest)\n                      with * antisymD[OF s.ANTISYM] show False by simp\n                    qed\n                    moreover\n                    have \"f (s.maxim (SUPP f)) \\<noteq> r.zero\"\n                      using bspec[OF maxF(1) f, unfolded s.isMaxim_def] by (auto simp: support_def)\n                    with f0f * f f0 maxf0 SUPPF\n                    have \"s.max_fun_diff f0 f = s.maxim (SUPP f0 \\<union> SUPP f)\"\n                      unfolding max_fun_diff_alt using s.maxim_Un[of \"SUPP f0\" \"SUPP f\"]\n                      by (intro s.maxim_Int) (auto simp: s.max2_def)\n                    moreover have \"s.maxim (SUPP f0 \\<union> SUPP f) = s.maxim (SUPP f)\"\n                      using s.maxim_Un[of \"SUPP f0\" \"SUPP f\"] * maxf0 SUPPF f0 f\n                      by (auto simp: s.max2_def)\n                    ultimately show ?thesis using f f0 F(1) maxF(1) SUPPF unfolding oexp_def Let_def\n                      by (fastforce simp: s.isMaxim_def intro!: r.zero_smallest FINFUNCD)\n                  qed\n                qed\n              qed\n            qed\n          qed simp\n        qed\n      qed\n    } \n    with A show \"\\<exists>a\\<in>A. \\<forall>a'\\<in>A. (a, a') \\<in> oexp\"\n      by blast\n  qed\nqed\n\nlemma oexp_Well_order: \"Well_order oexp\"\n  unfolding well_order_on_def using oexp_Linear_order oexp_wf_Id by blast\n\ninterpretation o: wo_rel oexp by unfold_locales (rule oexp_Well_order)\n\nlemma zero_oexp: \"Field r \\<noteq> {} \\<Longrightarrow> o.zero = const\"\n  by (metis Field_oexp const_FINFUNC const_least o.Field_ofilter o.equals_minim o.ofilter_def o.zero_def)\n\nend\n\nnotation wo_rel2.oexp (infixl \"^o\" 90)\nlemmas oexp_def = wo_rel2.oexp_def[unfolded wo_rel2_def, OF conjI]\nlemmas oexp_Well_order = wo_rel2.oexp_Well_order[unfolded wo_rel2_def, OF conjI]\nlemmas Field_oexp = wo_rel2.Field_oexp[unfolded wo_rel2_def, OF conjI]\n\ndefinition \"ozero = {}\"\n\nlemma ozero_Well_order[simp]: \"Well_order ozero\"\n  unfolding ozero_def by simp\n\nlemma ozero_ordIso[simp]: \"ozero =o ozero\"\n  unfolding ozero_def ordIso_def iso_def[abs_def] embed_def bij_betw_def by auto\n\nlemma Field_ozero[simp]: \"Field ozero = {}\"\n  unfolding ozero_def by simp\n\nlemma iso_ozero_empty[simp]: \"r =o ozero = (r = {})\"\n  unfolding ozero_def ordIso_def iso_def[abs_def] embed_def bij_betw_def\n  by (auto dest: well_order_on_domain)\n\nlemma ozero_ordLeq:\n  assumes \"Well_order r\"  shows \"ozero \\<le>o r\"\n  using assms unfolding ozero_def ordLeq_def embed_def[abs_def] under_def by auto\n\ndefinition \"oone = {((),())}\"\n\nlemma oone_Well_order[simp]: \"Well_order oone\"\n  unfolding oone_def unfolding well_order_on_def linear_order_on_def partial_order_on_def\n    preorder_on_def total_on_def refl_on_def trans_def antisym_def by auto\n\nlemma Field_oone[simp]: \"Field oone = {()}\"\n  unfolding oone_def by simp\n\nlemma oone_ordIso: \"oone =o {(x,x)}\"\n  unfolding ordIso_def oone_def well_order_on_def linear_order_on_def partial_order_on_def\n    preorder_on_def total_on_def refl_on_def trans_def antisym_def\n  by (auto simp: iso_def embed_def bij_betw_def under_def inj_on_def intro!: exI[of _ \"\\<lambda>_. x\"])\n\nlemma osum_ordLeqR: \"Well_order r \\<Longrightarrow> Well_order s \\<Longrightarrow> s \\<le>o r +o s\"\n  unfolding ordLeq_def2 underS_def\n  by (auto intro!: exI[of _ Inr] osum_Well_order) (auto simp add: osum_def Field_def)\n\nlemma osum_congL:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"r +o t =o s +o t\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_sum f id\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_osum iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_osum iso_def bij_betw_def image_image image_Un by auto\n  moreover from f have \"compat ?L ?R ?f\"\n    unfolding osum_def iso_iff3[OF r s] compat_def bij_betw_def\n    by (auto simp: map_prod_imageI)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: osum_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: osum_Well_order r s t)\nqed\n\nlemma osum_congR:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"t +o r =o t +o s\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_sum id f\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_osum iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_osum iso_def bij_betw_def image_image image_Un by auto\n  moreover from f have \"compat ?L ?R ?f\"\n    unfolding osum_def iso_iff3[OF r s] compat_def bij_betw_def\n    by (auto simp: map_prod_imageI)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: osum_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: osum_Well_order r s t)\nqed\n\nlemma osum_cong:\n  assumes \"t =o u\" and \"r =o s\"\n  shows \"t +o r =o u +o s\"\n  using ordIso_transitive[OF osum_congL[OF assms(1)] osum_congR[OF assms(2)]]\n    assms[unfolded ordIso_def] by auto\n\nlemma Well_order_empty[simp]: \"Well_order {}\"\n  unfolding Field_empty by (rule well_order_on_empty)\n\nlemma well_order_on_singleton[simp]: \"well_order_on {x} {(x, x)}\"\n  unfolding well_order_on_def linear_order_on_def partial_order_on_def preorder_on_def total_on_def\n    Field_def refl_on_def trans_def antisym_def by auto\n\nlemma oexp_empty[simp]:\n  assumes \"Well_order r\"\n  shows \"r ^o {} = {(\\<lambda>x. undefined, \\<lambda>x. undefined)}\"\n  unfolding oexp_def[OF assms Well_order_empty] FinFunc_def fin_support_def support_def by auto\n\nlemma oexp_empty2[simp]:\n  assumes \"Well_order r\" \"r \\<noteq> {}\"\n  shows \"{} ^o r = {}\"\nproof -\n  from assms(2) have \"Field r \\<noteq> {}\" unfolding Field_def by auto\n  thus ?thesis\n    by (simp add: assms(1) wo_rel2.intro wo_rel2.oexp_empty)\nqed\n\nlemma oprod_zero[simp]: \"{} *o r = {}\" \"r *o {} = {}\"\n  unfolding oprod_def by simp_all\n\nlemma oprod_congL:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"r *o t =o s *o t\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_prod f id\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_oprod iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_oprod iso_def bij_betw_def by (auto intro!: map_prod_surj_on)\n  moreover from f have \"compat ?L ?R ?f\"\n    unfolding iso_iff3[OF r s] compat_def oprod_def bij_betw_def\n    by (auto simp: map_prod_imageI)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: oprod_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_congR:\n  assumes \"r =o s\" and t: \"Well_order t\"\n  shows \"t *o r =o t *o s\" (is \"?L =o ?R\")\nproof -\n  from assms(1) obtain f where r: \"Well_order r\" and s: \"Well_order s\" and f: \"iso r s f\"\n    unfolding ordIso_def by blast\n  let ?f = \"map_prod id f\"\n  from f have \"inj_on ?f (Field ?L)\"\n    unfolding Field_oprod iso_def bij_betw_def inj_on_def by fastforce\n  with f have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_oprod iso_def bij_betw_def by (auto intro!: map_prod_surj_on)\n  moreover from f well_order_on_domain[OF r] have \"compat ?L ?R ?f\"\n    unfolding iso_iff3[OF r s] compat_def oprod_def bij_betw_def\n    by (auto simp: map_prod_imageI dest: inj_onD)\n  ultimately have \"iso ?L ?R ?f\" by (subst iso_iff3) (auto intro: oprod_Well_order r s t)\n  thus ?thesis unfolding ordIso_def by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_cong:\n  assumes \"t =o u\" and \"r =o s\"\n  shows \"t *o r =o u *o s\"\n  using ordIso_transitive[OF oprod_congL[OF assms(1)] oprod_congR[OF assms(2)]]\n    assms[unfolded ordIso_def] by auto\n\nlemma Field_singleton[simp]: \"Field {(z,z)} = {z}\"\n  by (metis well_order_on_Field well_order_on_singleton)\n\nlemma zero_singleton[simp]: \"zero {(z,z)} = z\"\n  using wo_rel.zero_in_Field[unfolded wo_rel_def, of \"{(z, z)}\"] well_order_on_singleton[of z]\n  by auto\n\nlemma FinFunc_singleton: \"FinFunc {(z,z)} s = {\\<lambda>x. if x \\<in> Field s then z else undefined}\"\n  unfolding FinFunc_def Func_def fin_support_def support_def\n  by (auto simp: fun_eq_iff split: if_split_asm intro!: finite_subset[of _ \"{}\"])\n\nlemma oone_ordIso_oexp:\n  assumes \"r =o oone\" and s: \"Well_order s\"\n  shows \"r ^o s =o oone\" (is \"?L =o ?R\")\nproof -\n  from \\<open>r =o oone\\<close> obtain f where *: \"\\<forall>x\\<in>Field r. \\<forall>y\\<in>Field r. x = y\" and \"f ` Field r = {()}\"\n    and r: \"Well_order r\"\n    unfolding ordIso_def oone_def by (auto simp add: iso_def [abs_def] bij_betw_def inj_on_def)\n  then obtain x where \"x \\<in> Field r\" by auto\n  with * have Fr: \"Field r = {x}\" by auto\n  interpret r: wo_rel r by unfold_locales (rule r)\n  from Fr well_order_on_domain[OF r] refl_onD[OF r.REFL, of x] have r_def: \"r = {(x, x)}\" by fast\n  interpret wo_rel2 r s by unfold_locales (rule r, rule s)\n  have \"bij_betw (\\<lambda>x. ()) (Field ?L) (Field ?R)\"\n    unfolding bij_betw_def Field_oexp by (auto simp: r_def FinFunc_singleton)\n  moreover have \"compat ?L ?R (\\<lambda>x. ())\" unfolding compat_def oone_def by auto\n  ultimately have \"iso ?L ?R (\\<lambda>x. ())\" using s oone_Well_order\n    by (subst iso_iff3) (auto intro: oexp_Well_order)\n  thus ?thesis using s oone_Well_order unfolding ordIso_def by (auto intro: oexp_Well_order)\nqed\n\n(*Lemma 1.4.3 from Holz et al.*)\ncontext\n  fixes r s t\n  assumes r: \"Well_order r\"\n  assumes s: \"Well_order s\"\n  assumes t: \"Well_order t\"\nbegin\n\nlemma osum_ozeroL: \"ozero +o r =o r\"\n  using r unfolding osum_def ozero_def by (auto intro: map_prod_ordIso)\n\nlemma osum_ozeroR: \"r +o ozero =o r\"\n  using r unfolding osum_def ozero_def by (auto intro: map_prod_ordIso)\n\nlemma osum_assoc: \"(r +o s) +o t =o r +o s +o t\" (is \"?L =o ?R\")\nproof -\n  let ?f =\n    \"\\<lambda>rst. case rst of Inl (Inl r) \\<Rightarrow> Inl r | Inl (Inr s) \\<Rightarrow> Inr (Inl s) | Inr t \\<Rightarrow> Inr (Inr t)\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_osum bij_betw_def inj_on_def by (auto simp: image_Un image_iff)\n  moreover\n  have \"compat ?L ?R ?f\"\n  proof (unfold compat_def, safe)\n    fix a b\n    assume \"(a, b) \\<in> ?L\"\n    thus \"(?f a, ?f b) \\<in> ?R\"\n      unfolding osum_def[of \"r +o s\" t] osum_def[of r \"s +o t\"] Field_osum\n      unfolding osum_def Field_osum image_iff image_Un map_prod_def\n      by fastforce\n  qed\n  ultimately have \"iso ?L ?R ?f\" using r s t by (subst iso_iff3) (auto intro: osum_Well_order)\n  thus ?thesis using r s t unfolding ordIso_def by (auto intro: osum_Well_order)\nqed\n\nlemma osum_monoR:\n  assumes \"s <o t\"\n  shows \"r +o s <o r +o t\" (is \"?L <o ?R\")\nproof -\n  from assms obtain f where s: \"Well_order s\" and t:\" Well_order t\" and \"embedS s t f\"\n    unfolding ordLess_def by blast\n  hence *: \"inj_on f (Field s)\" \"compat s t f\" \"ofilter t (f ` Field s)\" \"f ` Field s \\<subset> Field t\"\n    using embed_iff_compat_inj_on_ofilter[OF s t, of f] embedS_iff[OF s, of t f]\n    unfolding embedS_def by auto\n  let ?f = \"map_sum id f\"\n  from *(1) have \"inj_on ?f (Field ?L)\" unfolding Field_osum inj_on_def by fastforce\n  moreover\n  from *(2,4) have \"compat ?L ?R ?f\" unfolding compat_def osum_def map_prod_def by fastforce\n  moreover\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret rt: wo_rel ?R by unfold_locales (rule osum_Well_order[OF r t])\n  from *(3) have \"ofilter ?R (?f ` Field ?L)\"\n    unfolding t.ofilter_def rt.ofilter_def Field_osum image_Un image_image under_def\n    by (auto simp: osum_def intro!: imageI) (auto simp: Field_def)\n  ultimately have \"embed ?L ?R ?f\" using embed_iff_compat_inj_on_ofilter[of ?L ?R ?f]\n    by (auto intro: osum_Well_order r s t)\n  moreover\n  from *(4) have \"?f ` Field ?L \\<subset> Field ?R\" unfolding Field_osum image_Un image_image by auto\n  ultimately have \"embedS ?L ?R ?f\" using embedS_iff[OF osum_Well_order[OF r s], of ?R ?f] by auto\n  thus ?thesis unfolding ordLess_def by (auto intro: osum_Well_order r s t)\nqed\n\nlemma osum_monoL:\n  assumes \"r \\<le>o s\"\n  shows \"r +o t \\<le>o s +o t\"\nproof -\n  from assms obtain f where f: \"\\<forall>a\\<in>Field r. f a \\<in> Field s \\<and> f ` underS r a \\<subseteq> underS s (f a)\"\n    unfolding ordLeq_def2 by blast\n  let ?f = \"map_sum f id\"\n  from f have \"\\<forall>a\\<in>Field (r +o t).\n     ?f a \\<in> Field (s +o t) \\<and> ?f ` underS (r +o t) a \\<subseteq> underS (s +o t) (?f a)\"\n    unfolding Field_osum underS_def by (fastforce simp: osum_def)\n  thus ?thesis unfolding ordLeq_def2 by (auto intro: osum_Well_order r s t)\nqed\n\nlemma oprod_ozeroL: \"ozero *o r =o ozero\"\n  using ozero_ordIso unfolding ozero_def by simp\n\nlemma oprod_ozeroR: \"r *o ozero =o ozero\"\n  using ozero_ordIso unfolding ozero_def by simp\n\nlemma oprod_ooneR: \"r *o oone =o r\" (is \"?L =o ?R\")\nproof -\n  have \"bij_betw fst (Field ?L) (Field ?R)\" unfolding Field_oprod bij_betw_def inj_on_def by simp\n  moreover have \"compat ?L ?R fst\" unfolding compat_def oprod_def by auto\n  ultimately have \"iso ?L ?R fst\" using r oone_Well_order\n    by (subst iso_iff3) (auto intro: oprod_Well_order)\n  thus ?thesis using r oone_Well_order unfolding ordIso_def by (auto intro: oprod_Well_order)\nqed\n\nlemma oprod_ooneL: \"oone *o r =o r\" (is \"?L =o ?R\")\nproof -\n  have \"bij_betw snd (Field ?L) (Field ?R)\" unfolding Field_oprod bij_betw_def inj_on_def by simp\n  moreover have \"Refl r\" by (rule wo_rel.REFL[unfolded wo_rel_def, OF r])\n  hence \"compat ?L ?R snd\" unfolding compat_def oprod_def refl_on_def by auto\n  ultimately have \"iso ?L ?R snd\" using r oone_Well_order\n    by (subst iso_iff3) (auto intro: oprod_Well_order)\n  thus ?thesis using r oone_Well_order unfolding ordIso_def by (auto intro: oprod_Well_order)\nqed\n\nlemma oprod_monoR:\n  assumes \"ozero <o r\" \"s <o t\"\n  shows \"r *o s <o r *o t\" (is \"?L <o ?R\")\nproof -\n  from assms obtain f where s: \"Well_order s\" and t:\" Well_order t\" and \"embedS s t f\"\n    unfolding ordLess_def by blast\n  hence *: \"inj_on f (Field s)\" \"compat s t f\" \"ofilter t (f ` Field s)\" \"f ` Field s \\<subset> Field t\"\n    using embed_iff_compat_inj_on_ofilter[OF s t, of f] embedS_iff[OF s, of t f]\n    unfolding embedS_def by auto\n  let ?f = \"map_prod id f\"\n  from *(1) have \"inj_on ?f (Field ?L)\" unfolding Field_oprod inj_on_def by fastforce\n  moreover\n  from *(2,4) the_inv_into_f_f[OF *(1)] have \"compat ?L ?R ?f\" unfolding compat_def oprod_def\n    by auto (metis well_order_on_domain t, metis well_order_on_domain s)\n  moreover\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret rt: wo_rel ?R by unfold_locales (rule oprod_Well_order[OF r t])\n  from *(3) have \"ofilter ?R (?f ` Field ?L)\"\n    unfolding t.ofilter_def rt.ofilter_def Field_oprod under_def\n    by (auto simp: oprod_def image_iff) (fast | metis r well_order_on_domain)+\n  ultimately have \"embed ?L ?R ?f\" using embed_iff_compat_inj_on_ofilter[of ?L ?R ?f]\n    by (auto intro: oprod_Well_order r s t)\n  moreover\n  from not_ordLess_ordIso[OF assms(1)] have \"r \\<noteq> {}\" by (metis ozero_def ozero_ordIso)\n  hence \"Field r \\<noteq> {}\" unfolding Field_def by auto\n  with *(4) have \"?f ` Field ?L \\<subset> Field ?R\" unfolding Field_oprod\n    by auto (metis SigmaD2 SigmaI map_prod_surj_on)\n  ultimately have \"embedS ?L ?R ?f\" using embedS_iff[OF oprod_Well_order[OF r s], of ?R ?f] by auto\n  thus ?thesis unfolding ordLess_def by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_monoL:\n  assumes \"r \\<le>o s\"\n  shows \"r *o t \\<le>o s *o t\"\nproof -\n  from assms obtain f where f: \"\\<forall>a\\<in>Field r. f a \\<in> Field s \\<and> f ` underS r a \\<subseteq> underS s (f a)\"\n    unfolding ordLeq_def2 by blast\n  let ?f = \"map_prod f id\"\n  from f have \"\\<forall>a\\<in>Field (r *o t).\n     ?f a \\<in> Field (s *o t) \\<and> ?f ` underS (r *o t) a \\<subseteq> underS (s *o t) (?f a)\"\n    unfolding Field_oprod underS_def unfolding map_prod_def oprod_def by auto\n  thus ?thesis unfolding ordLeq_def2 by (auto intro: oprod_Well_order r s t)\nqed\n\nlemma oprod_assoc: \"(r *o s) *o t =o r *o s *o t\" (is \"?L =o ?R\")\nproof -\n  let ?f = \"\\<lambda>((a,b),c). (a,b,c)\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding Field_oprod bij_betw_def inj_on_def by (auto simp: image_Un image_iff)\n  moreover\n  have \"compat ?L ?R ?f\"\n  proof (unfold compat_def, safe)\n    fix a1 a2 a3 b1 b2 b3\n    assume \"(((a1, a2), a3), ((b1, b2), b3)) \\<in> ?L\"\n    thus \"((a1, a2, a3), (b1, b2, b3)) \\<in> ?R\"\n      unfolding oprod_def[of \"r *o s\" t] oprod_def[of r \"s *o t\"] Field_oprod\n      unfolding oprod_def Field_oprod image_iff image_Un by fast\n  qed\n  ultimately have \"iso ?L ?R ?f\" using r s t by (subst iso_iff3) (auto intro: oprod_Well_order)\n  thus ?thesis using r s t unfolding ordIso_def by (auto intro: oprod_Well_order)\nqed\n\nlemma oprod_osum: \"r *o (s +o t) =o r *o s +o r *o t\" (is \"?L =o ?R\")\nproof -\n  let ?f = \"\\<lambda>(a,bc). case bc of Inl b \\<Rightarrow> Inl (a, b) | Inr c \\<Rightarrow> Inr (a, c)\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\" unfolding Field_oprod Field_osum bij_betw_def inj_on_def\n    by (fastforce simp: image_Un image_iff split: sum.splits)\n  moreover\n  have \"compat ?L ?R ?f\"\n  proof (unfold compat_def, intro allI impI)\n    fix a b\n    assume \"(a, b) \\<in> ?L\"\n    thus \"(?f a, ?f b) \\<in> ?R\"\n      unfolding oprod_def[of r \"s +o t\"] osum_def[of \"r *o s\" \"r *o t\"] Field_oprod Field_osum\n      unfolding oprod_def osum_def Field_oprod Field_osum image_iff image_Un by auto\n  qed\n  ultimately have \"iso ?L ?R ?f\" using r s t\n    by (subst iso_iff3) (auto intro: oprod_Well_order osum_Well_order)\n  thus ?thesis using r s t unfolding ordIso_def by (auto intro: oprod_Well_order osum_Well_order)\nqed\n\nlemma ozero_oexp: \"\\<not> (s =o ozero) \\<Longrightarrow> ozero ^o s =o ozero\"\n  by (fastforce simp add: oexp_def[OF ozero_Well_order s] FinFunc_def Func_def intro: FieldI1)\n\nlemma oone_oexp: \"oone ^o s =o oone\" (is \"?L =o ?R\")\n  by (rule oone_ordIso_oexp[OF ordIso_reflexive[OF oone_Well_order] s])\n\nlemma oexp_monoR:\n  assumes \"oone <o r\" \"s <o t\"\n  shows   \"r ^o s <o r ^o t\" (is \"?L <o ?R\")\nproof -\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rt: wo_rel2 r t by unfold_locales (rule r, rule t)\n  interpret rexpt: wo_rel \"r ^o t\" by unfold_locales (rule rt.oexp_Well_order)\n  interpret r: wo_rel r by unfold_locales (rule r)\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret t: wo_rel t by unfold_locales (rule t)\n  have \"Field r \\<noteq> {}\" by (metis assms(1) internalize_ordLess not_psubset_empty)\n  moreover\n  { assume \"Field r = {r.zero}\"\n    hence \"r = {(r.zero, r.zero)}\" using refl_onD[OF r.REFL, of r.zero] unfolding Field_def by auto\n    hence \"r =o oone\" by (metis oone_ordIso ordIso_symmetric)\n    with not_ordLess_ordIso[OF assms(1)] have False by (metis ordIso_symmetric)\n  }\n  ultimately obtain x where x: \"x \\<in> Field r\" \"r.zero \\<in> Field r\" \"x \\<noteq> r.zero\"\n    by (metis insert_iff r.zero_in_Field subsetI subset_singletonD)\n  moreover from assms(2) obtain f where \"embedS s t f\" unfolding ordLess_def by blast\n  hence *: \"inj_on f (Field s)\" \"compat s t f\" \"ofilter t (f ` Field s)\" \"f ` Field s \\<subset> Field t\"\n    using embed_iff_compat_inj_on_ofilter[OF s t, of f] embedS_iff[OF s, of t f]\n    unfolding embedS_def by auto\n  note invff = the_inv_into_f_f[OF *(1)] and injfD = inj_onD[OF *(1)]\n  define F where [abs_def]: \"F g z =\n    (if z \\<in> f ` Field s then g (the_inv_into (Field s) f z)\n     else if z \\<in> Field t then r.zero else undefined)\" for g z\n  from *(4) x(2) the_inv_into_f_eq[OF *(1)] have FLR: \"F ` Field ?L \\<subseteq> Field ?R\"\n    unfolding rt.Field_oexp rs.Field_oexp FinFunc_def Func_def fin_support_def support_def F_def\n    by (fastforce split: option.splits if_split_asm elim!: finite_surj[of _ _ f])\n  have \"inj_on F (Field ?L)\" unfolding rs.Field_oexp inj_on_def fun_eq_iff\n  proof safe\n    fix g h x assume \"g \\<in> FinFunc r s\" \"h \\<in> FinFunc r s\" \"\\<forall>y. F g y = F h y\"\n    with invff show \"g x = h x\" unfolding F_def fun_eq_iff FinFunc_def Func_def\n      by auto (metis image_eqI)\n  qed\n  moreover\n  have \"compat ?L ?R F\" unfolding compat_def rs.oexp_def rt.oexp_def\n  proof (safe elim!: bspec[OF iffD1[OF image_subset_iff FLR[unfolded rs.Field_oexp rt.Field_oexp]]])\n    fix g h assume gh: \"g \\<in> FinFunc r s\" \"h \\<in> FinFunc r s\" \"F g \\<noteq> F h\"\n      \"let m = s.max_fun_diff g h in (g m, h m) \\<in> r\"\n    hence \"g \\<noteq> h\" by auto\n    note max_fun_diff_in = rs.max_fun_diff_in[OF \\<open>g \\<noteq> h\\<close> gh(1,2)]\n      and max_fun_diff_max = rs.max_fun_diff_max[OF \\<open>g \\<noteq> h\\<close> gh(1,2)]\n    with *(4) invff *(2) have \"t.max_fun_diff (F g) (F h) = f (s.max_fun_diff g h)\"\n      unfolding t.max_fun_diff_def compat_def\n      by (intro t.maxim_equality) (auto simp: t.isMaxim_def F_def dest: injfD)\n    with gh invff max_fun_diff_in\n    show \"let m = t.max_fun_diff (F g) (F h) in (F g m, F h m) \\<in> r\"\n      unfolding F_def Let_def by (auto simp: dest: injfD)\n  qed\n  moreover\n  from FLR have \"ofilter ?R (F ` Field ?L)\"\n    unfolding rexpt.ofilter_def under_def rs.Field_oexp rt.Field_oexp unfolding rt.oexp_def\n  proof (safe elim!: imageI)\n    fix g h assume gh: \"g \\<in> FinFunc r s\" \"h \\<in> FinFunc r t\" \"F g \\<in> FinFunc r t\"\n      \"let m = t.max_fun_diff h (F g) in (h m, F g m) \\<in> r\"\n    thus \"h \\<in> F ` FinFunc r s\"\n    proof (cases \"h = F g\")\n      case False\n      hence max_Field: \"t.max_fun_diff h (F g) \\<in> {a \\<in> Field t. h a \\<noteq> F g a}\"\n        by (rule rt.max_fun_diff_in[OF _ gh(2,3)])\n      { assume *: \"t.max_fun_diff h (F g) \\<notin> f ` Field s\"\n        with max_Field have **: \"F g (t.max_fun_diff h (F g)) = r.zero\" unfolding F_def by auto\n        with * gh(4) have \"h (t.max_fun_diff h (F g)) = r.zero\" unfolding Let_def by auto\n        with ** have False using max_Field gh(2,3) unfolding FinFunc_def Func_def by auto\n      }\n      hence max_f_Field: \"t.max_fun_diff h (F g) \\<in> f ` Field s\" by blast\n      { fix z assume z: \"z \\<in> Field t - f ` Field s\"\n        have \"(t.max_fun_diff h (F g), z) \\<in> t\"\n        proof (rule ccontr)\n          assume \"(t.max_fun_diff h (F g), z) \\<notin> t\"\n          hence \"(z, t.max_fun_diff h (F g)) \\<in> t\" using t.in_notinI[of \"t.max_fun_diff h (F g)\" z]\n              z max_Field by auto\n          hence \"z \\<in> f ` Field s\" using *(3) max_f_Field unfolding t.ofilter_def under_def\n            by fastforce\n          with z show False by blast\n        qed\n        hence \"h z = r.zero\" using rt.max_fun_diff_le_eq[OF _ False gh(2,3), of z]\n            z max_f_Field unfolding F_def by auto\n      } note ** = this\n      with *(3) gh(2) have \"h = F (\\<lambda>x. if x \\<in> Field s then h (f x) else undefined)\" using invff\n        unfolding F_def fun_eq_iff FinFunc_def Func_def Let_def t.ofilter_def under_def by auto\n      moreover from gh(2) *(1,3) have \"(\\<lambda>x. if x \\<in> Field s then h (f x) else undefined) \\<in> FinFunc r s\"\n        unfolding FinFunc_def Func_def fin_support_def support_def t.ofilter_def under_def\n        by (auto intro: subset_inj_on elim!: finite_imageD[OF finite_subset[rotated]])\n      ultimately show \"?thesis\" by (rule image_eqI)\n    qed simp\n  qed\n  ultimately have \"embed ?L ?R F\" using embed_iff_compat_inj_on_ofilter[of ?L ?R F]\n    by (auto intro: oexp_Well_order r s t)\n  moreover\n  from FLR have \"F ` Field ?L \\<subset> Field ?R\"\n  proof (intro psubsetI)\n    from *(4) obtain z where z: \"z \\<in> Field t\" \"z \\<notin> f ` Field s\" by auto\n    define h where [abs_def]: \"h z' =\n      (if z' \\<in> Field t then if z' = z then x else r.zero else undefined)\" for z'\n    from z x(3) have \"rt.SUPP h = {z}\" unfolding support_def h_def by simp\n    with x have \"h \\<in> Field ?R\" unfolding h_def rt.Field_oexp FinFunc_def Func_def fin_support_def\n      by auto\n    moreover\n    { fix g\n      from z have \"F g z = r.zero\" \"h z = x\" unfolding support_def h_def F_def by auto\n      with x(3) have \"F g \\<noteq> h\" unfolding fun_eq_iff by fastforce\n    }\n    hence \"h \\<notin> F ` Field ?L\" by blast\n    ultimately show \"F ` Field ?L \\<noteq> Field ?R\" by blast\n  qed\n  ultimately have \"embedS ?L ?R F\" using embedS_iff[OF rs.oexp_Well_order, of ?R F] by auto\n  thus ?thesis unfolding ordLess_def using r s t by (auto intro: oexp_Well_order)\nqed\n\nlemma oexp_monoL:\n  assumes \"r \\<le>o s\"\n  shows   \"r ^o t \\<le>o s ^o t\"\nproof -\n  interpret rt: wo_rel2 r t by unfold_locales (rule r, rule t)\n  interpret st: wo_rel2 s t by unfold_locales (rule s, rule t)\n  interpret r: wo_rel r by unfold_locales (rule r)\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret t: wo_rel t by unfold_locales (rule t)\n  show ?thesis\n  proof (cases \"t = {}\")\n    case True thus ?thesis using r s unfolding ordLeq_def2 underS_def by auto\n  next\n    case False thus ?thesis\n    proof (cases \"r = {}\")\n      case True thus ?thesis using t \\<open>t \\<noteq> {}\\<close> st.oexp_Well_order ozero_ordLeq[unfolded ozero_def]\n        by auto\n    next\n      case False\n      from assms obtain f where f: \"embed r s f\" unfolding ordLeq_def by blast\n      hence f_underS: \"\\<forall>a\\<in>Field r. f a \\<in> Field s \\<and> f ` underS r a \\<subseteq> underS s (f a)\"\n        using embed_in_Field embed_underS2 rt.rWELL by fastforce\n      from f \\<open>t \\<noteq> {}\\<close> False have *: \"Field r \\<noteq> {}\" \"Field s \\<noteq> {}\" \"Field t \\<noteq> {}\"\n        unfolding Field_def embed_def under_def bij_betw_def by auto\n      with f obtain x where \"s.zero = f x\" \"x \\<in> Field r\" unfolding embed_def bij_betw_def\n        using s.zero_under subsetD[OF under_Field[of r]]\n        by (metis (no_types, lifting) f_inv_into_f f_underS inv_into_into r.zero_in_Field)\n      with f have fz: \"f r.zero = s.zero\" and inj: \"inj_on f (Field r)\" and compat: \"compat r s f\"\n        unfolding embed_iff_compat_inj_on_ofilter[OF r s] compat_def\n        by (fastforce intro: s.leq_zero_imp)+\n      let ?f = \"\\<lambda>g x. if x \\<in> Field t then f (g x) else undefined\"\n      { fix g assume g: \"g \\<in> Field (r ^o t)\"\n        with fz f_underS have Field_fg: \"?f g \\<in> Field (s ^o t)\"\n          unfolding st.Field_oexp rt.Field_oexp FinFunc_def Func_def fin_support_def support_def\n          by (auto elim!: finite_subset[rotated])\n        moreover\n        have \"?f ` underS (r ^o t) g \\<subseteq> underS (s ^o t) (?f g)\"\n        proof safe\n          fix h\n          assume h_underS: \"h \\<in> underS (r ^o t) g\"\n          hence \"h \\<in> Field (r ^o t)\" unfolding underS_def Field_def by auto\n          with fz f_underS have Field_fh: \"?f h \\<in> Field (s ^o t)\"\n            unfolding st.Field_oexp rt.Field_oexp FinFunc_def Func_def fin_support_def support_def\n            by (auto elim!: finite_subset[rotated])\n          from h_underS have \"h \\<noteq> g\" and hg: \"(h, g) \\<in> rt.oexp\" unfolding underS_def by auto\n          with f inj have neq: \"?f h \\<noteq> ?f g\"\n            unfolding fun_eq_iff inj_on_def rt.oexp_def map_option_case FinFunc_def Func_def Let_def\n            by simp metis\n          with hg have \"t.max_fun_diff (?f h) (?f g) = t.max_fun_diff h g\" unfolding rt.oexp_def\n            using rt.max_fun_diff[OF \\<open>h \\<noteq> g\\<close>] rt.max_fun_diff_in[OF \\<open>h \\<noteq> g\\<close>]\n            by (subst t.max_fun_diff_def, intro t.maxim_equality)\n              (auto simp: t.isMaxim_def intro: inj_onD[OF inj] intro!: rt.max_fun_diff_max)\n          with Field_fg Field_fh hg fz f_underS compat neq have \"(?f h, ?f g) \\<in> st.oexp\"\n            using rt.max_fun_diff[OF \\<open>h \\<noteq> g\\<close>] rt.max_fun_diff_in[OF \\<open>h \\<noteq> g\\<close>] unfolding st.Field_oexp\n            unfolding rt.oexp_def st.oexp_def Let_def compat_def by auto\n          with neq show \"?f h \\<in> underS (s ^o t) (?f g)\" unfolding underS_def by auto\n        qed\n        ultimately have \"?f g \\<in> Field (s ^o t) \\<and> ?f ` underS (r ^o t) g \\<subseteq> underS (s ^o t) (?f g)\"\n          by blast\n      }\n      thus ?thesis unfolding ordLeq_def2 by (fastforce intro: oexp_Well_order r s t)\n    qed\n  qed\nqed\n\nlemma ordLeq_oexp2:\n  assumes \"oone <o r\"\n  shows   \"s \\<le>o r ^o s\"\nproof -\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret r: wo_rel r by unfold_locales (rule r)\n  interpret s: wo_rel s by unfold_locales (rule s)\n  from assms well_order_on_domain[OF r] obtain x where\n    x: \"x \\<in> Field r\" \"r.zero \\<in> Field r\" \"x \\<noteq> r.zero\"\n    unfolding ordLess_def oone_def embedS_def[abs_def] bij_betw_def embed_def under_def\n    by (auto simp: image_def)\n      (metis (lifting) equals0D mem_Collect_eq r.zero_in_Field singletonI)\n  let ?f = \"\\<lambda>a b. if b \\<in> Field s then if b = a then x else r.zero else undefined\"\n  from x(3) have SUPP: \"\\<And>y. y \\<in> Field s \\<Longrightarrow> rs.SUPP (?f y) = {y}\" unfolding support_def by auto\n  { fix y assume y: \"y \\<in> Field s\"\n    with x(1,2) SUPP have \"?f y \\<in> Field (r ^o s)\" unfolding rs.Field_oexp\n      by (auto simp: FinFunc_def Func_def fin_support_def)\n    moreover\n    have \"?f ` underS s y \\<subseteq> underS (r ^o s) (?f y)\"\n    proof safe\n      fix z\n      assume \"z \\<in> underS s y\"\n      hence z: \"z \\<noteq> y\" \"(z, y) \\<in> s\" \"z \\<in> Field s\" unfolding underS_def Field_def by auto\n      from x(3) y z(1,3) have \"?f z \\<noteq> ?f y\" unfolding fun_eq_iff by auto\n      moreover\n      { from x(1,2) have \"?f z \\<in> FinFunc r s\" \"?f y \\<in> FinFunc r s\"\n          unfolding FinFunc_def Func_def fin_support_def by (auto simp: SUPP[OF z(3)] SUPP[OF y])\n        moreover\n        from x(3) y z(1,2) refl_onD[OF s.REFL] have \"s.max_fun_diff (?f z) (?f y) = y\"\n          unfolding rs.max_fun_diff_alt SUPP[OF z(3)] SUPP[OF y]\n          by (intro s.maxim_equality) (auto simp: s.isMaxim_def)\n        ultimately have \"(?f z, ?f y) \\<in> rs.oexp\" using y x(1)\n          unfolding rs.oexp_def Let_def by auto\n      }\n      ultimately show \"?f z \\<in> underS (r ^o s) (?f y)\" unfolding underS_def by blast\n    qed\n    ultimately have \"?f y \\<in> Field (r ^o s) \\<and> ?f ` underS s y \\<subseteq> underS (r ^o s) (?f y)\" by blast\n  }\n  thus ?thesis unfolding ordLeq_def2 by (fast intro: oexp_Well_order r s)\nqed\n\nlemma FinFunc_osum:\n  \"fg \\<in> FinFunc r (s +o t) = (fg o Inl \\<in> FinFunc r s \\<and> fg o Inr \\<in> FinFunc r t)\"\n  (is \"?L = (?R1 \\<and> ?R2)\")\nproof safe\n  assume ?L\n  from \\<open>?L\\<close> show ?R1 unfolding FinFunc_def Field_osum Func_def Int_iff fin_support_Field_osum o_def\n    by (auto split: sum.splits)\n  from \\<open>?L\\<close> show ?R2 unfolding FinFunc_def Field_osum Func_def Int_iff fin_support_Field_osum o_def\n    by (auto split: sum.splits)\nnext\n  assume ?R1 ?R2\n  thus \"?L\" unfolding FinFunc_def Field_osum Func_def\n    by (auto simp: fin_support_Field_osum o_def image_iff split: sum.splits) (metis sumE)\nqed\n\nlemma max_fun_diff_eq_Inl:\n  assumes \"wo_rel.max_fun_diff (s +o t) (case_sum f1 g1) (case_sum f2 g2) = Inl x\"\n    \"case_sum f1 g1 \\<noteq> case_sum f2 g2\"\n    \"case_sum f1 g1 \\<in> FinFunc r (s +o t)\" \"case_sum f2 g2 \\<in> FinFunc r (s +o t)\"\n  shows \"wo_rel.max_fun_diff s f1 f2 = x\" (is ?P) \"g1 = g2\" (is ?Q)\nproof -\n  interpret st: wo_rel \"s +o t\" by unfold_locales (rule osum_Well_order[OF s t])\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret rst: wo_rel2 r \"s +o t\" by unfold_locales (rule r, rule osum_Well_order[OF s t])\n  from assms(1) have *: \"st.isMaxim {a \\<in> Field (s +o t). case_sum f1 g1 a \\<noteq> case_sum f2 g2 a} (Inl x)\"\n    using rst.isMaxim_max_fun_diff[OF assms(2-4)] by simp\n  hence \"s.isMaxim {a \\<in> Field s. f1 a \\<noteq> f2 a} x\"\n    unfolding st.isMaxim_def s.isMaxim_def Field_osum by (auto simp: osum_def)\n  thus ?P unfolding s.max_fun_diff_def by (rule s.maxim_equality)\n  from assms(3,4) have **: \"g1 \\<in> FinFunc r t\" \"g2 \\<in> FinFunc r t\" unfolding FinFunc_osum\n    by (auto simp: o_def)\n  show ?Q\n  proof\n    fix x\n    from * ** show \"g1 x = g2 x\" unfolding st.isMaxim_def Field_osum FinFunc_def Func_def fun_eq_iff\n      unfolding osum_def by (case_tac \"x \\<in> Field t\") auto\n  qed\nqed\n\nlemma max_fun_diff_eq_Inr:\n  assumes \"wo_rel.max_fun_diff (s +o t) (case_sum f1 g1) (case_sum f2 g2) = Inr x\"\n    \"case_sum f1 g1 \\<noteq> case_sum f2 g2\"\n    \"case_sum f1 g1 \\<in> FinFunc r (s +o t)\" \"case_sum f2 g2 \\<in> FinFunc r (s +o t)\"\n  shows \"wo_rel.max_fun_diff t g1 g2 = x\" (is ?P) \"g1 \\<noteq> g2\" (is ?Q)\nproof -\n  interpret st: wo_rel \"s +o t\" by unfold_locales (rule osum_Well_order[OF s t])\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret rst: wo_rel2 r \"s +o t\" by unfold_locales (rule r, rule osum_Well_order[OF s t])\n  from assms(1) have *: \"st.isMaxim {a \\<in> Field (s +o t). case_sum f1 g1 a \\<noteq> case_sum f2 g2 a} (Inr x)\"\n    using rst.isMaxim_max_fun_diff[OF assms(2-4)] by simp\n  hence \"t.isMaxim {a \\<in> Field t. g1 a \\<noteq> g2 a} x\"\n    unfolding st.isMaxim_def t.isMaxim_def Field_osum by (auto simp: osum_def)\n  thus ?P ?Q unfolding t.max_fun_diff_def fun_eq_iff\n    by (auto intro: t.maxim_equality simp: t.isMaxim_def)\nqed\n\nlemma oexp_osum: \"r ^o (s +o t) =o (r ^o s) *o (r ^o t)\" (is \"?R =o ?L\")\nproof (rule ordIso_symmetric)\n  interpret rst: wo_rel2 r \"s +o t\" by unfold_locales (rule r, rule osum_Well_order[OF s t])\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rt: wo_rel2 r t by unfold_locales (rule r, rule t)\n  let ?f = \"\\<lambda>(f, g). case_sum f g\"\n  have \"bij_betw ?f (Field ?L) (Field ?R)\"\n    unfolding bij_betw_def rst.Field_oexp rs.Field_oexp rt.Field_oexp Field_oprod proof (intro conjI)\n    show \"inj_on ?f (FinFunc r s \\<times> FinFunc r t)\" unfolding inj_on_def\n      by (auto simp: fun_eq_iff split: sum.splits)\n    show \"?f ` (FinFunc r s \\<times> FinFunc r t) = FinFunc r (s +o t)\"\n    proof safe\n      fix fg assume \"fg \\<in> FinFunc r (s +o t)\"\n      thus \"fg \\<in> ?f ` (FinFunc r s \\<times> FinFunc r t)\"\n        by (intro image_eqI[of _ _ \"(fg o Inl, fg o Inr)\"])\n          (auto simp: FinFunc_osum fun_eq_iff split: sum.splits)\n    qed (auto simp: FinFunc_osum o_def)\n  qed\n  moreover have \"compat ?L ?R ?f\"\n    unfolding compat_def rst.Field_oexp rs.Field_oexp rt.Field_oexp oprod_def\n    unfolding rst.oexp_def Let_def rs.oexp_def rt.oexp_def\n    by (fastforce simp: Field_osum FinFunc_osum o_def split: sum.splits\n        dest: max_fun_diff_eq_Inl max_fun_diff_eq_Inr)\n  ultimately have \"iso ?L ?R ?f\" using r s t\n    by (subst iso_iff3) (auto intro: oexp_Well_order oprod_Well_order osum_Well_order)\n  thus \"?L =o ?R\" using r s t unfolding ordIso_def\n    by (auto intro: oexp_Well_order oprod_Well_order osum_Well_order)\nqed\n\ndefinition \"rev_curr f b = (if b \\<in> Field t then \\<lambda>a. f (a, b) else undefined)\"\n\nlemma rev_curr_FinFunc:\n  assumes Field: \"Field r \\<noteq> {}\"\n  shows \"rev_curr ` (FinFunc r (s *o t)) = FinFunc (r ^o s) t\"\nproof safe\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  fix g assume g: \"g \\<in> FinFunc r (s *o t)\"\n  hence \"finite (rst.SUPP (rev_curr g))\" \"\\<forall>x \\<in> Field t. finite (rs.SUPP (rev_curr g x))\"\n    unfolding FinFunc_def Field_oprod rs.Field_oexp Func_def fin_support_def support_def\n      rs.zero_oexp[OF Field] rev_curr_def by (auto simp: fun_eq_iff rs.const_def elim!: finite_surj)\n  with g show \"rev_curr g \\<in> FinFunc (r ^o s) t\"\n    unfolding FinFunc_def Field_oprod rs.Field_oexp Func_def\n    by (auto simp: rev_curr_def fin_support_def)\nnext\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  fix fg assume *: \"fg \\<in> FinFunc (r ^o s) t\"\n  let ?g = \"\\<lambda>(a, b). if (a, b) \\<in> Field (s *o t) then fg b a else undefined\"\n  show \"fg \\<in> rev_curr ` FinFunc r (s *o t)\"\n  proof (rule image_eqI[of _ _ ?g])\n    show \"fg = rev_curr ?g\"\n    proof\n      fix x\n      from * show \"fg x = rev_curr ?g x\"\n        unfolding FinFunc_def rs.Field_oexp Func_def rev_curr_def Field_oprod by auto\n    qed\n  next\n    have **: \"(\\<Union>g \\<in> fg ` Field t. rs.SUPP g) =\n              (\\<Union>g \\<in> fg ` Field t - {rs.const}. rs.SUPP g)\"\n      unfolding support_def by auto\n    from * have ***: \"\\<forall>g \\<in> fg ` Field t. finite (rs.SUPP g)\" \"finite (rst.SUPP fg)\"\n      unfolding rs.Field_oexp FinFunc_def Func_def fin_support_def Option.these_def by force+\n    hence \"finite (fg ` Field t - {rs.const})\" using *\n      unfolding support_def rs.zero_oexp[OF Field] FinFunc_def Func_def\n      by (elim finite_surj[of _ _ fg]) (fastforce simp: image_iff Option.these_def)\n    with *** have \"finite ((\\<Union>g \\<in> fg ` Field t. rs.SUPP g) \\<times> rst.SUPP fg)\"\n      by (subst **) (auto intro!: finite_cartesian_product)\n    with * show \"?g \\<in> FinFunc r (s *o t)\"\n      unfolding Field_oprod rs.Field_oexp FinFunc_def Func_def fin_support_def Option.these_def\n        support_def rs.zero_oexp[OF Field] by (auto elim!: finite_subset[rotated])\n  qed\nqed\n\nlemma rev_curr_app_FinFunc[elim!]:\n  \"\\<lbrakk>f \\<in> FinFunc r (s *o t); z \\<in> Field t\\<rbrakk> \\<Longrightarrow> rev_curr f z \\<in> FinFunc r s\"\n  unfolding rev_curr_def FinFunc_def Func_def Field_oprod fin_support_def support_def\n  by (auto elim: finite_surj)\n\nlemma max_fun_diff_oprod:\n  assumes Field: \"Field r \\<noteq> {}\" and \"f \\<noteq> g\" \"f \\<in> FinFunc r (s *o t)\" \"g \\<in> FinFunc r (s *o t)\"\n  defines \"m \\<equiv> wo_rel.max_fun_diff t (rev_curr f) (rev_curr g)\"\n  shows \"wo_rel.max_fun_diff (s *o t) f g =\n    (wo_rel.max_fun_diff s (rev_curr f m) (rev_curr g m), m)\"\nproof -\n  interpret st: wo_rel \"s *o t\" by unfold_locales (rule oprod_Well_order[OF s t])\n  interpret s: wo_rel s by unfold_locales (rule s)\n  interpret t: wo_rel t by unfold_locales (rule t)\n  interpret r_st: wo_rel2 r \"s *o t\" by unfold_locales (rule r, rule oprod_Well_order[OF s t])\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  from fun_unequal_in_support[OF assms(2), of \"Field (s *o t)\" \"Field r\" \"Field r\"] assms(3,4)\n  have diff1: \"rev_curr f \\<noteq> rev_curr g\"\n    \"rev_curr f \\<in> FinFunc (r ^o s) t\" \"rev_curr g \\<in> FinFunc (r ^o s) t\" using rev_curr_FinFunc[OF Field]\n    unfolding fun_eq_iff rev_curr_def[abs_def] FinFunc_def support_def Field_oprod\n    by auto fast\n  hence diff2: \"rev_curr f m \\<noteq> rev_curr g m\" \"rev_curr f m \\<in> FinFunc r s\" \"rev_curr g m \\<in> FinFunc r s\"\n    using rst.max_fun_diff[OF diff1] assms(3,4) rst.max_fun_diff_in unfolding m_def by auto\n  show ?thesis unfolding st.max_fun_diff_def\n  proof (intro st.maxim_equality, unfold st.isMaxim_def Field_oprod, safe)\n    show \"s.max_fun_diff (rev_curr f m) (rev_curr g m) \\<in> Field s\"\n      using rs.max_fun_diff_in[OF diff2] by auto\n  next\n    show \"m \\<in> Field t\" using rst.max_fun_diff_in[OF diff1] unfolding m_def by auto\n  next\n    assume \"f (s.max_fun_diff (rev_curr f m) (rev_curr g m), m) =\n            g (s.max_fun_diff (rev_curr f m) (rev_curr g m), m)\"\n      (is \"f (?x, m) = g (?x, m)\")\n    hence \"rev_curr f m ?x = rev_curr g m ?x\" unfolding rev_curr_def by auto\n    with rs.max_fun_diff[OF diff2] show False by auto\n  next\n    fix x y assume \"f (x, y) \\<noteq> g (x, y)\" \"x \\<in> Field s\" \"y \\<in> Field t\"\n    thus \"((x, y), (s.max_fun_diff (rev_curr f m) (rev_curr g m), m)) \\<in> s *o t\"\n      using rst.max_fun_diff_in[OF diff1] rs.max_fun_diff_in[OF diff2] diff1 diff2\n        rst.max_fun_diff_max[OF diff1, of y] rs.max_fun_diff_le_eq[OF _ diff2, of x]\n      unfolding oprod_def m_def rev_curr_def fun_eq_iff by (auto intro: s.in_notinI)\n  qed\nqed\n\nlemma oexp_oexp: \"(r ^o s) ^o t =o r ^o (s *o t)\" (is \"?R =o ?L\")\nproof (cases \"r = {}\")\n  case True\n  interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n  interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n  show ?thesis\n  proof (cases \"s = {} \\<or> t = {}\")\n    case True with \\<open>r = {}\\<close> show ?thesis\n      by (auto simp: oexp_empty[OF oexp_Well_order[OF Well_order_empty s]]\n          intro!: ordIso_transitive[OF ordIso_symmetric[OF oone_ordIso] oone_ordIso]\n          ordIso_transitive[OF oone_ordIso_oexp[OF ordIso_symmetric[OF oone_ordIso] t] oone_ordIso])\n  next\n    case False\n    hence \"s *o t \\<noteq> {}\" unfolding oprod_def Field_def by fastforce\n    with False show ?thesis\n      using \\<open>r = {}\\<close> ozero_ordIso\n      by (auto simp add: s t oprod_Well_order ozero_def)\n  qed\nnext\n  case False\n  hence Field: \"Field r \\<noteq> {}\" by (metis Field_def Range_empty_iff Un_empty)\n  show ?thesis\n  proof (rule ordIso_symmetric)\n    interpret r_st: wo_rel2 r \"s *o t\" by unfold_locales (rule r, rule oprod_Well_order[OF s t])\n    interpret rs: wo_rel2 r s by unfold_locales (rule r, rule s)\n    interpret rst: wo_rel2 \"r ^o s\" t by unfold_locales (rule oexp_Well_order[OF r s], rule t)\n    have bij: \"bij_betw rev_curr (Field ?L) (Field ?R)\"\n      unfolding bij_betw_def r_st.Field_oexp rst.Field_oexp Field_oprod proof (intro conjI)\n      show \"inj_on rev_curr (FinFunc r (s *o t))\"\n        unfolding inj_on_def FinFunc_def Func_def Field_oprod rs.Field_oexp rev_curr_def[abs_def]\n        by (auto simp: fun_eq_iff) metis\n      show \"rev_curr ` (FinFunc r (s *o t)) = FinFunc (r ^o s) t\" by (rule rev_curr_FinFunc[OF Field])\n    qed\n    moreover\n    have \"compat ?L ?R rev_curr\"\n      unfolding compat_def proof safe\n      fix fg1 fg2 assume fg: \"(fg1, fg2) \\<in> r ^o (s *o t)\"\n      show \"(rev_curr fg1, rev_curr fg2) \\<in> r ^o s ^o t\"\n      proof (cases \"fg1 = fg2\")\n        assume \"fg1 \\<noteq> fg2\"\n        with fg show ?thesis\n          using rst.max_fun_diff_in[of \"rev_curr fg1\" \"rev_curr fg2\"]\n            max_fun_diff_oprod[OF Field, of fg1 fg2]  rev_curr_FinFunc[OF Field, symmetric]\n          unfolding r_st.Field_oexp rs.Field_oexp rst.Field_oexp unfolding r_st.oexp_def rst.oexp_def\n          by (auto simp: rs.oexp_def Let_def) (auto simp: rev_curr_def[abs_def])\n      next\n        assume \"fg1 = fg2\"\n        with fg bij show ?thesis unfolding r_st.Field_oexp rs.Field_oexp rst.Field_oexp bij_betw_def\n          by (auto simp: r_st.oexp_def rst.oexp_def)\n      qed\n    qed\n    ultimately have \"iso ?L ?R rev_curr\" using r s t\n      by (subst iso_iff3) (auto intro: oexp_Well_order oprod_Well_order)\n    thus \"?L =o ?R\" using r s t unfolding ordIso_def\n      by (auto intro: oexp_Well_order oprod_Well_order)\n  qed\nqed\n\nend (* context with 3 wellorders *)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Cardinals/Ordinal_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397307, "lm_q2_score": 0.8791467770088162, "lm_q1q2_score": 0.7840328164093902}}
{"text": "section \\<open>Peano's axioms for Natural Numbers\\<close>\n\ntheory Peano_Axioms\n  imports Main\nbegin\n\nlocale peano =  \\<comment> \\<open>or: \\<^theory_text>\\<open>class\\<close>\\<close>\n  fixes zero :: 'a\n  fixes succ :: \"'a \\<Rightarrow> 'a\"\n  assumes succ_neq_zero [simp]: \"succ m \\<noteq> zero\"\n  assumes succ_inject [simp]: \"succ m = succ n \\<longleftrightarrow> m = n\"\n  assumes induct [case_names zero succ, induct type: 'a]:\n    \"P zero \\<Longrightarrow> (\\<And>n. P n \\<Longrightarrow> P (succ n)) \\<Longrightarrow> P n\"\nbegin\n\nlemma zero_neq_succ [simp]: \"zero \\<noteq> succ m\"\n  by (rule succ_neq_zero [symmetric])\n\n\ntext \\<open>\\<^medskip> Primitive recursion as a (functional) relation -- polymorphic!\\<close>\n\ninductive Rec :: \"'b \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  for e :: 'b and r :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\nwhere\n  Rec_zero: \"Rec e r zero e\"\n| Rec_succ: \"Rec e r m n \\<Longrightarrow> Rec e r (succ m) (r m n)\"\n\nlemma Rec_functional: \"\\<exists>!y::'b. Rec e r x y\" for x :: 'a\nproof -\n  let ?R = \"Rec e r\"\n  show ?thesis\n  proof (induct x)\n    case zero\n    show \"\\<exists>!y. ?R zero y\"\n    proof\n      show \"?R zero e\" ..\n      show \"y = e\" if \"?R zero y\" for y\n        using that by cases simp_all\n    qed\n  next\n    case (succ m)\n    from \\<open>\\<exists>!y. ?R m y\\<close>\n    obtain y where y: \"?R m y\" and yy': \"\\<And>y'. ?R m y' \\<Longrightarrow> y = y'\"\n      by blast\n    show \"\\<exists>!z. ?R (succ m) z\"\n    proof\n      from y show \"?R (succ m) (r m y)\" ..\n    next\n      fix z\n      assume \"?R (succ m) z\"\n      then obtain u where \"z = r m u\" and \"?R m u\"\n        by cases simp_all\n      with yy' show \"z = r m y\"\n        by (simp only:)\n    qed\n  qed\nqed\n\n\ntext \\<open>\\<^medskip> The recursion operator -- polymorphic!\\<close>\n\ndefinition rec :: \"'b \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where \"rec e r x = (THE y. Rec e r x y)\"\n\nlemma rec_eval:\n  assumes Rec: \"Rec e r x y\"\n  shows \"rec e r x = y\"\n  unfolding rec_def\n  using Rec_functional and Rec by (rule the1_equality)\n\nlemma rec_zero [simp]: \"rec e r zero = e\"\nproof (rule rec_eval)\n  show \"Rec e r zero e\" ..\nqed\n\nlemma rec_succ [simp]: \"rec e r (succ m) = r m (rec e r m)\"\nproof (rule rec_eval)\n  let ?R = \"Rec e r\"\n  have \"?R m (rec e r m)\"\n    unfolding rec_def using Rec_functional by (rule theI')\n  then show \"?R (succ m) (r m (rec e r m))\" ..\nqed\n\n\ntext \\<open>\\<^medskip> Example: addition (monomorphic)\\<close>\n\ndefinition add :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"add m n = rec n (\\<lambda>_ k. succ k) m\"\n\nlemma add_zero [simp]: \"add zero n = n\"\n  and add_succ [simp]: \"add (succ m) n = succ (add m n)\"\n  unfolding add_def by simp_all\n\n\n\nlemma add_zero_right: \"add m zero = m\"\n  by (induct m) simp_all\n\nlemma add_succ_right: \"add m (succ n) = succ (add m n)\"\n  by (induct m) simp_all\n\nlemma \"add (succ (succ (succ zero))) (succ (succ zero)) =\n    succ (succ (succ (succ (succ zero))))\"\n  by simp\n\n\ntext \\<open>\\<^medskip> Example: replication (polymorphic)\\<close>\n\ndefinition repl :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b list\"\n  where \"repl n x = rec [] (\\<lambda>_ xs. x # xs) n\"\n\nlemma repl_zero [simp]: \"repl zero x = []\"\n  and repl_succ [simp]: \"repl (succ n) x = x # repl n x\"\n  unfolding repl_def by simp_all\n\nlemma \"repl (succ (succ (succ zero))) True = [True, True, True]\"\n  by simp\n\nend\n\n\ntext \\<open>\\<^medskip> Just see that our abstract specification makes sense \\dots\\<close>\n\ninterpretation peano 0 Suc\nproof\n  fix m n\n  show \"Suc m \\<noteq> 0\" by simp\n  show \"Suc m = Suc n \\<longleftrightarrow> m = n\" by simp\n  show \"P n\"\n    if zero: \"P 0\"\n    and succ: \"\\<And>n. P n \\<Longrightarrow> P (Suc n)\"\n    for P\n  proof (induct n)\n    case 0\n    show ?case by (rule zero)\n  next\n    case Suc\n    then show ?case by (rule succ)\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/Peano_Axioms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874624, "lm_q2_score": 0.870597273444551, "lm_q1q2_score": 0.7839987787739621}}
{"text": "theory Chapter4\n  imports Main\nbegin\n\n(* 4.1 Isar by Example *)\n\nlemma \"\\<not> surj (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"surj f\"\n  from 0 have 1: \"\\<forall>A. \\<exists>a. A = f a\" by(simp add: surj_def)\n  from 1 have 2: \"\\<exists>a. {x. x \\<notin> f x} = f a\" by blast\n  from 2 show \"False\" by blast\nqed\n\n(* 4.1.1 this, then, hence and thus *)\nlemma \"\\<not> surj (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  hence \"\\<forall>A. \\<exists>a. A = f a\" by(simp add: surj_def)\n  hence \"\\<exists>a. {x. x \\<notin> f x} = f a\" by blast\n  thus \"False\" by blast\nqed\n\n(* 4.1.2 Structured Lemma Statements: fixes, assumes, shows *)\nlemma\n  fixes f :: \" 'a \\<Rightarrow> 'a set\"\n  assumes s: \"surj f\"\n  shows \"False\"\nproof -\n  have \"\\<exists>a. {x. x \\<notin> f x} = f a\" using s by (auto simp:surj_def)\n  thus \"False\" by blast\nqed\n\n(* 4.2 Proof Patterns *)\nlemma \"\\<not> surj (f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  hence \"\\<exists>a. {x. x \\<notin> f x} = f a\" by (auto simp:surj_def)\n  then obtain a where \"{x. x \\<notin> f x} = f a\" by blast\n  hence \"a \\<notin> f a \\<longleftrightarrow> a \\<in> f a\" by blast\n  thus \"False\" by blast\nqed\n\n(* 4.3 Streamlining Proofs *)\n\nlemma\n  fixes a b :: int\n  assumes \"b dvd (a + b)\"\n  shows \"b dvd a\"\nproof -\n  have \"\\<exists>k'. a = b * k'\" if asm: \"a + b = b * k\" for k\n  proof\n    show \"a = b * (k - 1)\" using asm by (simp add:algebra_simps)\n  qed\n  then show ?thesis using assms by (auto simp add:dvd_def)\nqed\n\n(* Exercise 4.1 *)\nlemma\n  assumes T: \"\\<forall>x y. T x y \\<or> T y x\"\n      and A: \"\\<forall>x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n      and TA: \"\\<forall>x y. T x y \\<longrightarrow> A x y\"\n      and \"A x y\"\n    shows \"T x y\"\nproof -\n  have \"T x y \\<or> T y x\" by (simp add:T)\n  then show \"T x y\"\n  proof\n    assume asm: \"T x y\"\n    show ?thesis using asm by assumption\n  next\n    assume asm: \"T y x\"\n    have \"A y x\" using TA asm by auto\n    hence \"x = y\" using `A x y` A by auto\n    thus ?thesis using asm by auto\n  qed\nqed\n\n(* Exercise 4.2 *)\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume asm:\"even (length xs)\"\n  let ?ys = \"take ((length xs) div 2) xs\"\n  let ?zs = \"drop ((length xs) div 2) xs\"\n  show ?thesis\n  proof\n    show \"\\<exists>zs. xs = ?ys @ zs \\<and> (length ?ys = length zs \\<or> length ?ys = length zs + 1)\"\n    proof\n      have \"xs = ?ys @ ?zs\" using append_eq_append_conv by auto\n      have \"length ?ys = length ?zs\" using asm by (auto simp add:algebra_simps)\n      hence \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\" by auto\n      thus \"xs = ?ys @ ?zs \\<and> (length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1)\" by auto\n    qed\n  qed\nnext\n  assume asm:\"odd (length xs)\"\n  let ?ys = \"take (length xs div 2 + 1) xs\"\n  let ?zs = \"drop (length xs div 2 + 1) xs\"\n  show ?thesis\n  proof\n    show \"\\<exists>zs. xs = ?ys @ zs \\<and> (length ?ys = length zs \\<or> length ?ys = length zs + 1)\"\n    proof\n      have \"xs = ?ys @ ?zs\" using append_eq_append_conv by auto\n      have \"length ?ys = length ?zs + 1\"\n      proof -\n        have \"length xs = 2 * (length xs div 2) + 1\" using asm by fastforce\n        hence 0:\"length ?zs = length xs div 2\" by auto\n\n        have \"\\<forall>n :: nat. odd n \\<longrightarrow> n \\<ge> 1\" using Parity.odd_pos by fastforce\n        hence \"length xs \\<ge> 1\" using asm by auto\n        hence 1:\"length ?ys = length xs div 2 + 1\" by auto\n        thus ?thesis using 0 by auto\n      qed\n      hence \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" by auto\n      thus \"xs = ?ys @ ?zs \\<and> (length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1)\" by auto\n    qed\n  qed\nqed\n\n(* 4.4 Case Analysis and Induction *)\n(* 4.4.1 Datatype Case Analysis *)\n\nlemma \"length (tl xs) = length xs - 1\"\nproof (cases xs)\n  (* Note that by definition, \"tl [] = []\" *)\n  case Nil (* assume \"xs = []\" *)\n  thus ?thesis by simp\nnext\n  case (Cons y ys) (* fix y ys assume xs = y # ys *)\n  thus ?thesis by simp\nqed\n\n(* 4.4.2 Structural Induction *)\nlemma \"\\<Sum>{0..n::nat} = n * (n + 1) div 2\" (is \"?P n\")\nproof (induction n)\n  show \"?P 0\" by simp\nnext\n  fix n assume \"?P n\"\n  thus \"?P (Suc n)\" by simp\nqed\n\nlemma \"\\<Sum>{0..n::nat} = n * (n + 1) div 2\" (is \"?P n\")\nproof (induction n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n) (* sets induction hypothesis to 'this' *)\n  thus ?case by simp\nqed\n\n(* 4.4.3 Computation Induction *)\n(* In computation induction (with induction rule defined by 'fun'),\n   we can specify case names like 'case (i x y ...)' where 'i' is\n   an index starting from 1 and x, y, ... are bound variables *)\n\n(* 4.4.4 Rule Induction *)\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n  ev0 : \"ev 0\"\n| evSS : \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n  \"evn 0 = True\"\n| \"evn (Suc 0) = False\"\n| \"evn (Suc(Suc n)) = evn n\"\n\nlemma \"ev n \\<Longrightarrow> evn n\"\nproof (induction rule:ev.induct)\n  case ev0\n  show ?case by simp\nnext\n  case (evSS n)\n  have \"evn (Suc (Suc n)) = evn n\" by simp\n  thus ?case using `evn n` by blast\nqed\n\n(* 4.4.6 Rule Inversion *)\nlemma\n  assumes \"ev n\"\n  shows \"ev (n - 2)\"\n  using assms\nproof cases\n  case ev0\n  thus \"ev(n - 2)\" by (simp add: ev.ev0)\nnext\n  case evSS\n  thus \"ev (n - 2)\" by (simp add: ev.evSS)\nqed\n\nlemma \"\\<not> ev (Suc 0)\"\nproof\n  assume \"ev (Suc 0)\"\n  then show False by cases\nqed\n\n(* 4.4.7 Advanced Rule Induction *)\nlemma \"ev (Suc m) \\<Longrightarrow> \\<not> ev m\"\nproof (induction \"Suc m\" arbitrary:m rule:ev.induct)\n  fix n assume IH: \"\\<And> m. n = Suc m \\<Longrightarrow> \\<not> ev m\"\n  show \"\\<not> ev (Suc n)\"\n  proof\n    assume \"ev (Suc n)\"\n    thus False\n    proof cases\n      fix k assume \"n = Suc k\" \"ev k\"\n      thus False using IH by auto\n    qed\n  qed\nqed\n\n(* Exercise 4.3 *)\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\n  using a\nproof cases\n  case evSS\n  show \"ev n \\<Longrightarrow> ev n\" by (simp add: ev.ev0)\nqed\n\n(* Exercise 4.4 *)\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\"\n  then have \"ev (Suc 0)\" by cases\n  thus False by cases\nqed\n\n(* Exercise 4.5 *)\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  iter_zero: \"iter r 0 x x\"\n| iter_succ: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl: \"star r x x\"\n| step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule:iter.induct)\n  case iter_zero\n  thus ?case by (auto simp add:refl)\nnext\n  case iter_succ\n  thus ?case by (auto simp add:step)\nqed\n\n(* Exercise 4.6 *)\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n  elems_Nil:  \"elems [] = {}\"\n| elems_Cons: \"elems (x#xs) = insert x (elems xs)\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\" (is \"?P(x,xs) \\<Longrightarrow> ?Q(x,xs)\")\nproof (induction xs)\n  case Nil\n  hence False by auto\n  thus ?case by auto\nnext\n  case (Cons x' xs)\n  hence \"x = x' \\<or> (x \\<noteq> x' \\<and> x \\<in> elems xs)\" by auto\n  then show ?case\n  proof\n    assume H:\"x = x'\"\n    show ?case\n    proof\n      show \"\\<exists> zs. x' # xs = [] @ x # zs \\<and> x \\<notin> elems []\"\n      proof\n        show \"x' # xs = [] @ x # xs \\<and> x \\<notin> elems []\" using H by auto\n      qed\n    qed\n  next\n    assume H:\"(x \\<noteq> x' \\<and> x \\<in> elems xs)\"\n    from this obtain ys where \"\\<exists>zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\" using Cons.IH by auto\n    from this obtain zs where H1: \"xs = ys @ x # zs \\<and> x \\<notin> elems ys\" by auto\n    show ?case\n    proof\n      show \"\\<exists> zs. x' # xs = (x' # ys) @ x # zs \\<and> x \\<notin> elems (x' # ys)\"\n      proof\n        show \"x' # xs = (x' # ys) @ x # zs \\<and> x \\<notin> elems (x' # ys)\" using H H1 by auto\n      qed\n    qed\n  qed\nqed\n\n(* Exercise 4.7 *)\n\nend", "meta": {"author": "momohatt", "repo": "sandbox", "sha": "6be8d7facf9b4c36965fea71580e609550631722", "save_path": "github-repos/isabelle/momohatt-sandbox", "path": "github-repos/isabelle/momohatt-sandbox/sandbox-6be8d7facf9b4c36965fea71580e609550631722/isabelle-tutorial/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.9059898299021698, "lm_q1q2_score": 0.7838842131040821}}
{"text": "\n(*<*) theory ex2_2 imports Main begin (*>*)\n\nsubsubsection {* Some more list functions *}\n\ntext {* Recall the summation function *}\n\nprimrec sum :: \"nat list \\<Rightarrow> nat\" where\n  \"sum [] = 0\"\n| \"sum (x # xs) = x + sum xs\"\n\ntext {* In the Isabelle library, you will find (in the theory {\\tt List.thy})\nthe functions @{text foldr} and @{text foldl}, which allow you to define some\nlist functions, among them @{text sum} and @{text length}.  Show the following:\n*}\n\nlemma sum_foldr: \"sum xs = foldr (+) xs 0\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma length_foldr: \"length xs = foldr (\\<lambda> x res. 1 + res) xs 0\"\n  apply(induct xs)\n   apply auto\n  done\n\n\ntext {* Repeated application of @{text foldr} and @{text map} has the\ndisadvantage that a list is traversed several times.  A single traversal is\nsufficient, as illustrated by the following example: *}\n\nlemma \"sum (map (\\<lambda> x. x + 3) xs) = foldr (\\<lambda> x res. x+res+3) xs 0\"\n  apply(induct xs)\n   apply auto\ndone\n\ntext {* Find terms @{text h} and @{text b} which solve this equation. *}\n\n\ntext {* Generalize this result, i.e.\\ show for appropriate @{text h} and @{text\nb}: *}\n\nlemma \"foldr g (map f xs) a = foldr (\\<lambda> x res. g (f x) res) xs a\"\n  apply(induct xs)\n   apply auto\n  done\n\ntext {* Hint: Isabelle can help you find the solution if you use the equalities\narising during a proof attempt. *}\n\n\ntext {* The following function @{text rev_acc} reverses a list in linear time:\n*}\n\nprimrec rev_acc :: \"['a list, 'a list] \\<Rightarrow> 'a list\" where\n  \"rev_acc [] ys = ys\"\n| \"rev_acc (x#xs) ys = (rev_acc xs (x#ys))\"\n\ntext {* Show that @{text rev_acc} can be defined by means of @{text foldl}. *}\n\nlemma rev_acc_foldl: \"rev_acc xs a = foldl (\\<lambda> ys x. x # ys) a xs\"\n  apply(induct xs arbitrary:a)\n   apply auto\n  done\n\n\ntext {* Prove the following distributivity property for @{text sum}: *}\n\nlemma sum_append [simp]: \"sum (xs @ ys) = sum xs + sum ys\"\n  apply(induct xs arbitrary:ys)\n   apply auto\n  done\n\n\ntext {* Prove a similar property for @{text foldr}, i.e.\\ something like @{text\n\"foldr f (xs @ ys) a = f (foldr f xs a) (foldr f ys a)\"}.  However, you will\nhave to strengthen the premises by taking into account algebraic properties of\n@{text f} and @{text a}. *}\n\ndefinition\n  left_neutral :: \"['a \\<Rightarrow> 'b \\<Rightarrow> 'b, 'a] \\<Rightarrow> bool\" where\n  \"left_neutral f a == (\\<forall> x. (f a x = x))\"\n\ndefinition\n  assoc :: \"['a \\<Rightarrow> 'a \\<Rightarrow> 'a] \\<Rightarrow> bool\" where\n  \"assoc f == (\\<forall> x y z. f (f x y) z = f x (f y z))\" \nlemma foldr_append: \"\\<lbrakk>  left_neutral f a; assoc f \\<rbrakk> \\<Longrightarrow> foldr f (xs @ ys) a = f (foldr f xs a) (foldr f ys a)\"\n  apply(induct xs arbitrary:ys)\n    apply (simp add: left_neutral_def)\n  apply (simp add: assoc_def)\n  done\n\n\ntext {* Now, define the function @{text prod}, which computes the product of\nall list elements *}\n\ndefinition  prod :: \"nat list \\<Rightarrow> nat\" where\n\"prod xs == foldr (*) xs 1\"\n\n\ntext {* directly with the aid of a fold and prove the following: *}\n\nlemma \"prod (xs @ ys) = prod xs * prod ys\"\n apply (simp only: prod_def)\n  apply (rule foldr_append)\n   apply (simp add:left_neutral_def )\n  apply (simp add:assoc_def )\n  done\n\n\nsubsubsection {* Functions on Trees *}\n\ntext {* Consider the following type of binary trees: *}\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\ntext {* Define functions which convert a tree into a list by traversing it in\npre-, resp.\\ postorder: *}\n\n(*<*) consts (*>*)\nprimrec  preorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"preorder Tip = []\"\n|\"preorder (Node a b c) = b#(preorder a)@(preorder c)\"\n\nprimrec  postorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"postorder Tip = []\"\n|\"postorder (Node a b c) = (postorder a)@(postorder c)@[b]\"\n\n\n\ntext {* You have certainly realized that computation of postorder traversal can\nbe efficiently realized with an accumulator, in analogy to @{text rev_acc}: *}\n\nprimrec\n  postorder_acc :: \"['a tree, 'a list] \\<Rightarrow> 'a list\" where\n\"postorder_acc Tip x = x\"\n|\"postorder_acc (Node a b c) x = (postorder_acc a (postorder_acc c (b#x)))\"\n\n\n\ntext {* Define this function and show: *}\n\nlemma \"postorder_acc t xs = (postorder t) @ xs\"\n  apply(induct t arbitrary: xs)\n   apply auto\n  done\n\n\ntext {* @{text postorder_acc} is the instance of a function @{text foldl_tree},\nwhich is similar to @{text foldl}. *}\n\nprimrec  foldl_tree :: \"('b => 'a => 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a tree \\<Rightarrow> 'b\" where\n\"foldl_tree f a Tip =a\"\n|\"foldl_tree f acc (Node a b c) = foldl_tree f  (foldl_tree f (f acc b) c)   a\"\n\n\ntext {* Show the following: *}\n\nlemma \"\\<forall> a. postorder_acc t a = foldl_tree (\\<lambda> xs x. Cons x xs) a t\"\n  apply(induct t)\n   apply auto\n\n  done\n\n\ntext {* Define a function @{text tree_sum} that computes the sum of the\nelements of a tree of natural numbers: *}\n\nprimrec\n  tree_sum :: \"nat tree \\<Rightarrow> nat\" where\n\"tree_sum Tip = 0\"\n|\"tree_sum (Node a b c) = b +(tree_sum a) + (tree_sum c)\"  \n\n\ntext {* and show that this function satisfies *}\n\nlemma \"tree_sum t = sum (preorder t)\"\n  apply(induct t)\n   apply auto\n  done\n\n\n(*<*) end (*>*)", "meta": {"author": "hei411", "repo": "Isabelle", "sha": "9126e84b3e39af28336f25e3b7563a01f70625fa", "save_path": "github-repos/isabelle/hei411-Isabelle", "path": "github-repos/isabelle/hei411-Isabelle/Isabelle-9126e84b3e39af28336f25e3b7563a01f70625fa/Online_exercises/ex2_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8933094131553264, "lm_q1q2_score": 0.7838582683583444}}
{"text": "(*\n    $Id: sol.thy,v 1.3 2011/06/28 18:11:38 webertj Exp $\n*)\n\nheader {* Replace, Reverse and Delete *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext{*\nDefine a function @{term replace}, such that @{term\"replace x y zs\"}\nyields @{term zs} with every occurrence of @{term x} replaced by @{term y}.\n*}\n\nprimrec replace :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"replace x y []     = []\"\n| \"replace x y (z#zs) = (if z=x then y else z)#(replace x y zs)\"\n\ntext {*\nProve or disprove (by counterexample) the following theorems.\nYou may have to prove some lemmas first.\n*}\n\nlemma replace_append: \"replace x y (xs @ ys) = replace x y xs @ replace x y ys\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntheorem \"rev(replace x y zs) = replace x y (rev zs)\"\n  apply (induct \"zs\")\n  apply (auto simp add: replace_append)\ndone\n\ntheorem \"replace x y (replace u v zs) = replace u v (replace x y zs)\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample:\n  u=0, v=1, x=0, y=-1, zs=[0]\n*}\n\ntheorem \"replace y z (replace x y zs) = replace x z zs\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample:\n  x=1, y=0, z=1, zs=[0]\n*}\n\ntext{* Define two functions for removing elements from a list:\n@{term\"del1 x xs\"} deletes the first occurrence (from the left) of\n@{term x} in @{term xs}, @{term\"delall x xs\"} all of them. *}\n\nprimrec del1 :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"del1 x []     = []\"\n| \"del1 x (y#ys) = (if y=x then ys else y # del1 x ys)\"\n\nprimrec delall :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"delall x []     = []\"\n| \"delall x (y#ys) = (if y=x then delall x ys else y # delall x ys)\"\n\ntext {*\nProve or disprove (by counterexample) the following theorems.\n*}\n\ntheorem \"del1 x (delall x xs) = delall x xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntheorem \"delall x (delall x xs) = delall x xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntheorem delall_del1: \"delall x (del1 x xs) = delall x xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntheorem \"del1 x (del1 y zs) = del1 y (del1 x zs)\"\n  apply (induct \"zs\")\n  apply auto\ndone\n\ntheorem \"delall x (del1 y zs) = del1 y (delall x zs)\"\n  apply (induct \"zs\")\n  apply (auto simp add: delall_del1)\ndone\n\ntheorem \"delall x (delall y zs) = delall y (delall x zs)\"\n  apply (induct \"zs\")\n  apply auto\ndone\n\ntheorem \"del1 y (replace x y xs) = del1 x xs\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample:\n  x=1, xs=[0], y=0\n*}\n\ntheorem \"delall y (replace x y xs) = delall x xs\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample:\n  x=1, xs=[0], y=0\n*}\n\ntheorem \"replace x y (delall x zs) = delall x zs\"\n  apply (induct \"zs\")\n  apply auto\ndone\n\ntheorem \"replace x y (delall z zs) = delall z (replace x y zs)\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample:\n  x=1, y=0, z=0, zs=[1]\n*}\n\ntheorem \"rev(del1 x xs) = del1 x (rev xs)\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample:\n  x=1, xs=[1, 0, 1]\n*}\n\nlemma delall_append: \"delall x (xs @ ys) = delall x xs @ delall x ys\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntheorem \"rev(delall x xs) = delall x (rev xs)\"\n  apply (induct \"xs\")\n  apply (auto simp add: delall_append)\ndone\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/lists/replace/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.7838582542804068}}
{"text": "header \"Priority Queues Based on Braun Trees\"\n\ntheory Priority_Queue_Braun\nimports\n  \"~~/src/HOL/Library/Tree\"\n  \"~~/src/HOL/Library/Multiset\"\nbegin\n\n\nsubsection \"Introduction\"\n\ntext{* Braun, Rem and Hoogerwoord \\cite{BraunRem,Hoogerwoord} used\nspecific balanced binary trees, often called Braun trees (where in\neach node with subtrees $l$ and $r$, $size(r) \\le size(l) \\le\nsize(r)+1$), to implement flexible arrays. Paulson \\cite{Paulson}\n(based on code supplied by Okasaki)\nimplemented priority queues via Braun trees. This theory verifies\nPaulsons's implementation, including the logarithmic bounds.  *}\n\n(* FIXME mv to Tree *)\n\nlemma size_0_iff_Leaf[simp]: \"size t = 0 \\<longleftrightarrow> t = Leaf\"\nby(cases t) auto\n\nfun height :: \"'a tree \\<Rightarrow> nat\" where\n\"height Leaf = 0\" |\n\"height (Node l x r) = max (height l) (height r) + 1\"\n\nlemma size1_height: \"size t + 1 \\<le> 2 ^ height t\"\nproof(induction t)\n  case (Node l a r)\n  show ?case\n  proof (cases \"height l \\<le> height r\")\n    case True\n    have \"size(Node l a r) + 1 = (size l + 1) + (size r + 1)\" by simp\n    also have \"size l + 1 \\<le> 2 ^ height l\" by(rule Node.IH(1))\n    also have \"size r + 1 \\<le> 2 ^ height r\" by(rule Node.IH(2))\n    also have \"(2::nat) ^ height l \\<le> 2 ^ height r\" using True by simp\n    finally show ?thesis using True by (auto simp: max_def mult_2)\n  next\n    case False\n    have \"size(Node l a r) + 1 = (size l + 1) + (size r + 1)\" by simp\n    also have \"size l + 1 \\<le> 2 ^ height l\" by(rule Node.IH(1))\n    also have \"size r + 1 \\<le> 2 ^ height r\" by(rule Node.IH(2))\n    also have \"(2::nat) ^ height r \\<le> 2 ^ height l\" using False by simp\n    finally show ?thesis using False by (auto simp: max_def mult_2)\n  qed\nqed simp\n\nfun heap :: \"'a::linorder tree \\<Rightarrow> bool\" where\n\"heap Leaf = True\" |\n\"heap (Node l m r) =\n  (heap l \\<and> heap r \\<and> (\\<forall>x \\<in> set_tree l \\<union> set_tree r. m \\<le> x))\"\n\n(* eomv *)\n\n\nsubsection {* Multiset of tree *}\n\ndefinition mset_tree :: \"'a tree \\<Rightarrow> 'a multiset\" where\n\"mset_tree t = multiset_of (inorder t)\"\n\nlemma mset_Leaf[simp]: \"mset_tree Leaf = {#}\"\nby(simp add: mset_tree_def)\n\nlemma mset_Node[simp]:\n  \"mset_tree (Node l x r) = {#x#} + mset_tree l + mset_tree r\"\nby(simp add: mset_tree_def ac_simps)\n\nlemma set_mset_tree: \"set_of(mset_tree t) = set_tree t\"\nby (simp add: mset_tree_def)\n\nlemma mset_iff_set_tree: \"x \\<in># mset_tree t \\<longleftrightarrow> x \\<in> set_tree t\"\nby(induction t arbitrary: x) auto\n\n\nsubsection {* Braun predicate *}\n\nfun braun :: \"'a tree \\<Rightarrow> bool\" where\n\"braun Leaf = True\" |\n\"braun (Node l x r) = (size r \\<le> size l \\<and> size l \\<le> Suc(size r) \\<and> braun l \\<and> braun r)\"\n\nlemma height_size_braun: \"braun t \\<Longrightarrow> 2 ^ (height t) \\<le> 2 * size t + 1\"\nproof(induction t)\n  case (Node t1)\n  show ?case\n  proof (cases \"height t1\")\n    case 0 thus ?thesis using Node by simp\n  next\n    case (Suc n)\n    hence \"2 ^ n \\<le> size t1\" using Node by simp\n    thus ?thesis using Suc Node by(auto simp: max_def)\n  qed\nqed simp\n\n\nsubsection {* Insertion *}\n\nfun insert_pq :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"insert_pq a Leaf = Node Leaf a Leaf\" |\n\"insert_pq a (Node l x r) =\n (if a < x then Node (insert_pq x r) a l else Node (insert_pq a r) x l)\"\n\nvalue \"fold insert_pq [0::int,1,2,3,-55,-5] Leaf\"\n\nlemma size_insert_pq[simp]: \"size(insert_pq x t) = size t + 1\"\nby(induction t arbitrary: x) auto\n\nlemma mset_insert_pq[simp]: \"mset_tree(insert_pq x t) = {#x#} + mset_tree t\"\nby(induction t arbitrary: x) (auto simp: ac_simps)\n\nlemma set_insert_pq[simp]: \"set_tree(insert_pq x t) = insert x (set_tree t)\"\nby(induction t arbitrary: x) auto\n\nlemma braun_insert_pq: \"braun t \\<Longrightarrow> braun(insert_pq x t)\"\nby(induction t arbitrary: x) auto\n\nlemma heap_insert_pq: \"heap t \\<Longrightarrow> heap(insert_pq x t)\"\nby(induction t arbitrary: x) (auto  simp add: ball_Un)\n\n\nsubsection {* Deletion *}\n\nfun del_left :: \"'a tree \\<Rightarrow> 'a * 'a tree\" where\n\"del_left (Node Leaf x Leaf) = (x,Leaf)\" |\n\"del_left (Node l x r) = (let (y,l') = del_left l in (y,Node r x l'))\"\n\nlemma del_left_size:\n  \"del_left t = (x,t') \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> size t = size t' + 1\"\napply(induction t arbitrary: x t' rule: del_left.induct)\napply(auto split: prod.splits)\nby fastforce\n\nlemma del_left_braun:\n  \"del_left t = (x,t') \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> braun t'\"\napply(induction t arbitrary: x t' rule: del_left.induct)\napply(fastforce dest: del_left_size split: prod.splits)+\ndone\n\nlemma del_left_elem:\n  \"del_left t = (x,t') \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> x \\<in> set_tree t\"\napply(induction t arbitrary: x t' rule: del_left.induct)\napply(fastforce split: prod.splits)+\ndone\n\nlemma del_left_set:\n  \"del_left t = (x,t') \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf\n  \\<Longrightarrow> set_tree t = insert x (set_tree t')\"\napply(induction t arbitrary: x t' rule: del_left.induct)\napply(fastforce split: prod.splits)+\ndone\n\nlemma del_left_mset:\n  \"del_left t = (x,t') \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf\n  \\<Longrightarrow> mset_tree t' = mset_tree t - {#x#}\"\napply(induction t arbitrary: x t' rule: del_left.induct)\n   apply(auto simp: ac_simps mset_iff_set_tree[symmetric]\n     dest!: del_left_elem split: prod.splits)\n   apply(simp add: multiset_eq_iff)\n  apply(simp add: multiset_eq_iff)\n apply(simp add: multiset_eq_iff)\napply(fastforce simp: multiset_eq_iff)\ndone\n\nlemma del_left_heap:\n  \"del_left t = (x,t') \\<Longrightarrow> heap t \\<Longrightarrow> braun t \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> heap t'\"\nproof(induction t arbitrary: x t' rule: del_left.induct)\n  case (\"2_1\" ll a lr b r)\n  from \"2_1.prems\"(1) obtain l' where\n    \"del_left (Node ll a lr) = (x,l')\" and [simp]: \"t' = Node r b l'\"\n    by(auto split: prod.splits)\n  from del_left_set[OF this(1)] \"2_1.IH\"[OF this(1)] \"2_1.prems\"\n  show ?case by(auto)\nnext\n  case \"2_2\" thus ?case by(fastforce dest: del_left_set split: prod.splits)\nnext\nqed auto\n\n\nfunction (sequential) sift_down :: \"'a::linorder tree \\<Rightarrow> 'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"sift_down Leaf a Leaf = Node Leaf a Leaf\" |\n\"sift_down (Node Leaf x Leaf) a Leaf =\n  (if a \\<le> x then Node (Node Leaf x Leaf) a Leaf\n   else Node (Node Leaf a Leaf) x Leaf)\" |\n\"sift_down (Node l1 x1 r1) a (Node l2 x2 r2) =\n  (if a \\<le> x1 \\<and> a \\<le> x2\n   then Node (Node l1 x1 r1) a (Node l2 x2 r2)\n   else if x1 \\<le> x2 then Node (sift_down l1 a r1) x1 (Node l2 x2 r2)\n        else Node (Node l1 x1 r1) x2 (sift_down l2 a r2))\"\nby pat_completeness auto\ntermination\nby (relation \"measure (%(l,a,r). size l + size r)\") auto\n\nlemma size_sift_down:\n  \"braun(Node l a r) \\<Longrightarrow> size(sift_down l a r) = size l + size r + 1\"\nby(induction l a r rule: sift_down.induct) auto\n\nlemma braun_sift_down:\n  \"braun(Node l a r) \\<Longrightarrow> braun(sift_down l a r)\"\nby(induction l a r rule: sift_down.induct) (auto simp: size_sift_down)\n\nlemma mset_sift_down:\n  \"braun(Node l a r) \\<Longrightarrow> mset_tree(sift_down l a r) = {#a#} + (mset_tree l + mset_tree r)\"\nby(induction l a r rule: sift_down.induct) (auto simp: ac_simps)\n\nlemma set_sift_down: \"braun(Node l a r)\n  \\<Longrightarrow> set_tree(sift_down l a r) = insert a (set_tree l \\<union> set_tree r)\"\nby(drule arg_cong[where f=set_of, OF mset_sift_down]) (simp add:set_mset_tree)\n\nlemma heap_sift_down:\n  \"braun(Node l a r) \\<Longrightarrow> heap l \\<Longrightarrow> heap r \\<Longrightarrow> heap(sift_down l a r)\"\nby (induction l a r rule: sift_down.induct) (auto simp: set_sift_down ball_Un)\n\nfun del_min :: \"'a::linorder tree \\<Rightarrow> 'a tree\" where\n\"del_min Leaf = Leaf\" |\n\"del_min (Node Leaf x r) = Leaf\" |\n\"del_min (Node l x r) = (let (y,l') = del_left l in sift_down r y l')\"\n\nlemma braun_del_min: \"braun t \\<Longrightarrow> braun(del_min t)\"\napply(cases t rule: del_min.cases)\n  apply simp\n apply simp\napply (fastforce split: prod.split intro!: braun_sift_down\n  dest: del_left_size del_left_braun)\ndone\n\nlemma heap_del_min: \"heap t \\<Longrightarrow> braun t \\<Longrightarrow> heap(del_min t)\"\napply(cases t rule: del_min.cases)\n  apply simp\n apply simp\napply (fastforce split: prod.split intro!: heap_sift_down\n  dest: del_left_size del_left_braun del_left_heap)\ndone\n\n\n\nlemma mset_del_min: assumes \"braun t\" \"heap t\" \"t \\<noteq> Leaf\"\nshows \"mset_tree t = {#val t#} + mset_tree(del_min t)\"\nproof(cases t rule: del_min.cases)\n  case 1 with assms show ?thesis by simp\nnext\n  case 2 with assms show ?thesis by simp\nnext\n  case (3 ll b lr a r)[simp]\n  { fix y l' assume del: \"del_left (Node ll b lr) = (y,l')\"\n    have \"mset_tree t = {#a#} + mset_tree(sift_down r y l')\"\n      using assms del_left_mset[OF del] del_left_size[OF del]\n        del_left_braun[OF del]del_left_elem[OF del]\n      by(subst mset_sift_down)\n        (auto simp: ac_simps multiset_eq_iff mset_iff_set_tree[symmetric]) }\n  thus ?thesis by(auto split: prod.split)\nqed\n\nlemma set_del_min: \"\\<lbrakk> braun t; heap t; t \\<noteq> Leaf \\<rbrakk>\n  \\<Longrightarrow> set_tree t = insert (val t) (set_tree(del_min t))\"\nby(drule (2) arg_cong[where f=set_of, OF mset_del_min]) (simp add:set_mset_tree)\n\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Priority_Queue_Braun/Priority_Queue_Braun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7837225854008523}}
{"text": "theory Ex16 \nimports Main\nbegin \n\n\n(*Proof A \\<or> B \\<longleftrightarrow> B \\<or> A, commutativity of or*) \n\n\nlemma \"A \\<or> B \\<longleftrightarrow> B \\<or> A\"\nproof -\n{\n  assume \"A \\<or> B\"\n  moreover\n  { \n    assume A \n    hence \"B \\<or> A\" by (rule disjI2)\n  }\n  moreover\n  {\n    assume B\n    hence \"B \\<or> A\" by (rule disjI1)\n  }\n  ultimately have \"B \\<or> A\" by (rule disjE)\n}\nmoreover\n{\n  assume \"B \\<or> A\"\n  moreover\n  {\n    assume B\n    hence \"A \\<or> B\" by (rule disjI2)\n  }\n  moreover\n  { \n    assume A \n    hence \"A \\<or> B\" by (rule disjI1)\n  }\n  ultimately have \"A \\<or> B\" by (rule disjE)\n}\nultimately show ?thesis by (rule iffI)\nqed", "meta": {"author": "SvenWille", "repo": "LogicForwardProofs", "sha": "b03c110b073eb7c34a561fce94b860b14cde75f7", "save_path": "github-repos/isabelle/SvenWille-LogicForwardProofs", "path": "github-repos/isabelle/SvenWille-LogicForwardProofs/LogicForwardProofs-b03c110b073eb7c34a561fce94b860b14cde75f7/src/propLogic/Ex16.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357702, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7836424799229933}}
{"text": "theory NatDoubleInduction imports Main begin\n\nhide_const Suc\ndatatype nat = Zero | Suc nat\n\n\nsection \"How to define custom induction rules\"\nsubsection \"Example for cutom induction rules\"\nlemma nat_induct: \"\\<lbrakk> P Zero; \\<And>n. P n \\<Longrightarrow> P (Suc n) \\<rbrakk> \\<Longrightarrow> P n\"\n  apply(rule nat.induct)\n  apply(assumption)\n  apply(assumption)\n  done\n\n\nfun nat_eq :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  nat_eq_ZeroZero: \"nat_eq Zero Zero = True\" |\n  nat_eq_SucZero:  \"nat_eq (Suc n) Zero = False\" |\n  nat_eq_ZeroSuc:  \"nat_eq Zero (Suc m) = False\" |\n  nat_eq_SucSuc:   \"nat_eq (Suc n) (Suc m) = nat_eq n m\"\n\n\ntext \"Single-induction example using the custom induction rule\"\nlemma nat_eq_refl: \"nat_eq n n\"\n  apply(rule nat_induct)\n  apply(subst nat_eq_ZeroZero)\n  apply(rule TrueI)\n  apply(subst nat_eq_SucSuc)\n  apply(assumption)\n  done\n\n\nlemma nat_eq_sym[rule_format]: \"\\<forall>n. nat_eq m n \\<longleftrightarrow> nat_eq n m\"\n  apply(rule nat_induct)\n  apply(rule allI)\n  apply(rule_tac y=n in nat.exhaust)\n  apply(erule ssubst)\n  apply(subst (1 2) nat_eq_ZeroZero)\n  apply(rule refl)\n  apply(erule ssubst)\n  apply(subst nat_eq_SucZero)\n  apply(subst nat_eq_ZeroSuc)\n  apply(rule refl)\n  apply(rule allI)\n  apply(rule_tac y=na in nat.exhaust)\n  apply(erule ssubst)\n  apply(subst nat_eq_SucZero)\n  apply(subst nat_eq_ZeroSuc)\n  apply(rule refl)\n  apply(erule ssubst)\n  apply(subst (1 2) nat_eq_SucSuc)\n  apply(drule_tac x=x2 in spec)\n  apply(assumption)\n  done\n\n\nfun nat_plus :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  nat_plus_ZeroFree: \"nat_plus Zero n = n\" |\n  nat_plus_SucFree:  \"nat_plus (Suc m) n = nat_plus m (Suc n)\"\n\n\nlemma nat_plus_FreeSuc[rule_format]: \"\\<forall>n. nat_plus m (Suc n) = Suc (nat_plus m n)\"\n  apply(rule_tac n=m in nat_induct)\n  apply(subst (1 2) nat_plus_ZeroFree)\n  apply(rule allI)\n  apply(rule refl)\n\n  apply(simp only: nat_plus_SucFree)\n  apply(rule allI)\n  apply(subst nat.simps(1))\n  apply(subst nat.simps(1))\n  apply(rule refl)\n  done\n\n\nsubsection \"Double-induction example using the custom induction rule\"\nlemma \"nat_eq (nat_plus m n) (nat_plus n m)\"\n  apply(rule_tac n=m in nat_induct)\n  apply(rule_tac n=n in nat_induct)\n  apply(unfold nat_plus_ZeroFree nat_eq_ZeroZero)\n  apply(rule TrueI)\n\n  apply(rule_tac y=n in nat.exhaust)\n  apply(clarify)\n  apply(unfold nat_plus_SucFree nat_plus_ZeroFree nat_eq_SucSuc nat_eq_ZeroZero)\n  apply(rule TrueI)\n\n  apply(clarify)\n  apply(unfold nat_plus_SucFree nat_plus_ZeroFree nat_plus_FreeSuc nat_eq_SucSuc)\n  apply(assumption)\n  apply(assumption)\n  done\n\n\nsection \"How to define double-induction rules\"\nsubsection \"Lemmas to proof the double induction rule\"\nlemma nat_induct_N_M: \"\\<lbrakk> P Zero Zero; \\<And>m n. P m n \\<Longrightarrow> P (Suc m) n; \\<And>m n. P m n \\<Longrightarrow> P m (Suc n) \\<rbrakk> \\<Longrightarrow> P m n\"\n  apply(rule_tac n=m in nat_induct)\n  apply(rule_tac n=n in nat_induct)\n  apply(assumption)\n\n  apply(drule_tac P=\"\\<lambda>m. (\\<And>n. P m n \\<Longrightarrow> P m (Suc n))\"  and x=\"Zero\" in meta_spec)\n  apply(drule_tac P=\"\\<lambda>n. (P Zero n \\<Longrightarrow> P Zero (Suc n))\"  and x=\"n\" in meta_spec)\n  apply(drule meta_mp)\n  apply(assumption)\n  apply(assumption)\n\n  apply(drule_tac P=\"\\<lambda>m. (\\<And>n. P m n \\<Longrightarrow> P (Suc m) n)\" and x=\"na\" in meta_spec)\n  apply(drule_tac P=\"\\<lambda>n. (P na n \\<Longrightarrow> P (Suc na) n)\" and x=\"n\" in meta_spec)\n  apply(drule meta_mp)\n  apply(assumption)\n  apply(assumption)\n  done\n\n\nsubsection \"Proof using the custom double-induction rule\"\nlemma \"nat_eq (nat_plus m n) (nat_plus n m)\"\n  apply(rule_tac n=n and m=m in nat_induct_N_M)\n  apply(unfold nat_plus_ZeroFree)\n  apply(subst nat_eq_ZeroZero)\n  apply(rule TrueI)\n  apply(unfold nat_plus_SucFree nat_plus_FreeSuc nat_eq_SucSuc)\n  apply(assumption)\n  apply(assumption)\n  done\nend", "meta": {"author": "Kuniwak", "repo": "DoubleInductionExample", "sha": "e2bea70734121655b2447ab6cda4947507c7c7de", "save_path": "github-repos/isabelle/Kuniwak-DoubleInductionExample", "path": "github-repos/isabelle/Kuniwak-DoubleInductionExample/DoubleInductionExample-e2bea70734121655b2447ab6cda4947507c7c7de/NatDoubleInduction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.783642472836515}}
{"text": "(* Title: Block_Designs.thy\n   Author: Chelsea Edmonds\n*)\n\nsection \\<open> Block and Balanced Designs \\<close>\ntext \\<open> We define a selection of the many different types of block and balanced designs, building up \nto properties required for defining a BIBD, in addition to several base generalisations \\<close> \n\ntheory Block_Designs imports Design_Operations\nbegin\n\nsubsection \\<open>Block Designs\\<close>\ntext \\<open>A block design is a design where all blocks have the same size.\\<close>\n\nsubsubsection \\<open>K Block Designs \\<close> \ntext \\<open>An important generalisation of a typical block design is the $\\mathcal{K}$ block design, \nwhere all blocks must have a size $x$ where $x \\in \\mathcal{K}$\\<close>\nlocale K_block_design = proper_design +\n  fixes sizes :: \"nat set\" (\"\\<K>\")\n  assumes block_sizes: \"bl \\<in># \\<B> \\<Longrightarrow> (card bl) \\<in> \\<K>\"\n  assumes positive_ints: \"x \\<in> \\<K> \\<Longrightarrow> x > 0\"\nbegin\n\nlemma sys_block_size_subset: \"sys_block_sizes \\<subseteq> \\<K>\"\n  using block_sizes sys_block_sizes_obtain_bl by blast\n\nend\n\nsubsubsection\\<open>Uniform Block Design\\<close>\ntext \\<open>The typical uniform block design is defined below \\<close>\nlocale block_design = proper_design + \n  fixes u_block_size :: nat (\"\\<k>\")\n  assumes uniform [simp]: \"bl \\<in># \\<B> \\<Longrightarrow> card bl = \\<k>\"\nbegin\n\nlemma k_non_zero: \"\\<k> \\<ge> 1\"\nproof -\n  obtain bl where bl_in: \"bl \\<in># \\<B>\"\n    using design_blocks_nempty by auto \n  then have \"card bl \\<ge> 1\" using block_size_gt_0\n    by (metis less_not_refl less_one not_le_imp_less) \n  thus ?thesis by (simp add: bl_in)\nqed\n\nlemma uniform_alt_def_all: \"\\<forall> bl \\<in># \\<B> .card bl = \\<k>\"\n  using uniform by auto \n\nlemma uniform_unfold_point_set: \"bl \\<in># \\<B> \\<Longrightarrow> card {p \\<in> \\<V>. p \\<in> bl} = \\<k>\"\n  using uniform wellformed by (simp add: Collect_conj_eq inf.absorb_iff2) \n\nlemma uniform_unfold_point_set_mset: \"bl \\<in># \\<B> \\<Longrightarrow> size {#p \\<in># mset_set \\<V>. p \\<in> bl #} = \\<k>\"\n  using uniform_unfold_point_set by (simp add: finite_sets) \n\nlemma sys_block_sizes_uniform [simp]:  \"sys_block_sizes  = {\\<k>}\"\nproof -\n  have \"sys_block_sizes = {bs . \\<exists> bl . bs = card bl \\<and> bl\\<in># \\<B>}\" by (simp add: sys_block_sizes_def)\n  then have \"sys_block_sizes  = {bs . bs = \\<k>}\" using uniform uniform_unfold_point_set \n      b_positive block_set_nempty_imp_block_ex\n    by (smt (verit, best) Collect_cong design_blocks_nempty)\n  thus ?thesis by auto\nqed\n\nlemma sys_block_sizes_uniform_single: \"is_singleton (sys_block_sizes)\"\n  by simp\n\nlemma uniform_size_incomp: \"\\<k> \\<le> \\<v> - 1 \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  using uniform k_non_zero\n  by (metis block_size_lt_v diff_diff_cancel diff_is_0_eq' less_numeral_extra(1) nat_less_le)\n\nlemma uniform_complement_block_size:\n  assumes \"bl \\<in># \\<B>\\<^sup>C\"\n  shows \"card bl = \\<v> - \\<k>\"\nproof -\n  obtain bl' where bl_assm: \"bl = bl'\\<^sup>c \\<and> bl' \\<in># \\<B>\" \n    using wellformed assms by (auto simp add: complement_blocks_def)\n  then have \"int (card bl') = \\<k>\" by simp\n  thus ?thesis using bl_assm block_complement_size wellformed\n    by (simp add: block_size_lt_order of_nat_diff) \nqed\n\nlemma uniform_complement[intro]: \n  assumes \"\\<k> \\<le> \\<v> - 1\"\n  shows \"block_design \\<V> \\<B>\\<^sup>C (\\<v> - \\<k>)\"\nproof - \n  interpret des: proper_design \\<V> \"\\<B>\\<^sup>C\" \n    using  uniform_size_incomp assms complement_proper_design by auto \n  show ?thesis using assms uniform_complement_block_size by (unfold_locales) (simp)\nqed\n\nlemma block_size_lt_v: \"\\<k> \\<le> \\<v>\"\n  using v_non_zero block_size_lt_v design_blocks_nempty uniform by auto \n\nend\n\nlemma (in proper_design) block_designI[intro]: \"(\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> card bl = k) \n  \\<Longrightarrow> block_design \\<V> \\<B> k\"\n  by (unfold_locales) (auto)\n\ncontext block_design \nbegin\n\nlemma block_design_multiple: \"n > 0 \\<Longrightarrow> block_design \\<V> (multiple_blocks n) \\<k>\"\n  using elem_in_repeat_in_original multiple_proper_design proper_design.block_designI \n  by (metis uniform_alt_def_all) \n\nend\ntext \\<open>A uniform block design is clearly a type of $K$\\_block\\_design with a singleton $K$ set \\<close>\nsublocale block_design \\<subseteq> K_block_design \\<V> \\<B> \"{\\<k>}\"\n  using k_non_zero uniform by unfold_locales simp_all\n\nsubsubsection \\<open>Incomplete Designs \\<close>\ntext \\<open> An incomplete design is a design where $k < v$, i.e. no block is equal to the point set \\<close>\nlocale incomplete_design = block_design + \n  assumes incomplete: \"\\<k> < \\<v>\"\n\nbegin\n\nlemma incomplete_imp_incomp_block: \"bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  using incomplete uniform uniform_size_incomp by fastforce  \n\nlemma incomplete_imp_proper_subset: \"bl \\<in># \\<B> \\<Longrightarrow> bl \\<subset> \\<V>\"\n  using incomplete_block_proper_subset incomplete_imp_incomp_block by auto\n\nend\n\nlemma (in block_design) incomplete_designI[intro]: \"\\<k> < \\<v> \\<Longrightarrow> incomplete_design \\<V> \\<B> \\<k>\"\n  by unfold_locales auto\n\ncontext incomplete_design\nbegin\n\nlemma multiple_incomplete: \"n > 0 \\<Longrightarrow> incomplete_design \\<V> (multiple_blocks n) \\<k>\"\n  using block_design_multiple incomplete by (simp add: block_design.incomplete_designI) \n\nlemma complement_incomplete: \"incomplete_design \\<V> (\\<B>\\<^sup>C) (\\<v> - \\<k>)\"\nproof -\n  have \"\\<v> - \\<k> < \\<v>\" using v_non_zero k_non_zero by linarith\n  thus ?thesis using uniform_complement incomplete incomplete_designI\n    by (simp add: block_design.incomplete_designI) \nqed\n\nend\n\nsubsection \\<open>Balanced Designs \\<close>\ntext \\<open> t-wise balance is a design with the property that all point subsets of size $t$ occur in \n$\\lambda_t$ blocks \\<close>\n\nlocale t_wise_balance = proper_design + \n  fixes grouping :: nat (\"\\<t>\") and index :: nat (\"\\<Lambda>\\<^sub>t\")\n  assumes t_non_zero: \"\\<t> \\<ge> 1\"\n  assumes t_lt_order: \"\\<t> \\<le> \\<v>\"\n  assumes balanced [simp]: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps = \\<Lambda>\\<^sub>t\"\nbegin\n\nlemma t_non_zero_suc: \"\\<t> \\<ge> Suc 0\"\n  using t_non_zero by auto\n\nlemma balanced_alt_def_all: \"\\<forall> ps \\<subseteq> \\<V> . card ps = \\<t> \\<longrightarrow> \\<B> index ps = \\<Lambda>\\<^sub>t\"\n  using balanced by auto\n\nend\n\nlemma (in proper_design) t_wise_balanceI[intro]: \"\\<t> \\<le> \\<v> \\<Longrightarrow> \\<t> \\<ge> 1 \\<Longrightarrow> \n  (\\<And> ps . ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t>  \\<Longrightarrow> \\<B> index ps = \\<Lambda>\\<^sub>t) \\<Longrightarrow> t_wise_balance \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t\"\n  by (unfold_locales) auto\n\ncontext t_wise_balance\nbegin\n\nlemma obtain_t_subset_points:\n  obtains T where \"T \\<subseteq> \\<V>\" \"card T = \\<t>\" \"finite T\"\n  using obtain_subset_with_card_n design_points_nempty t_lt_order t_non_zero finite_sets by auto\n\nlemma multiple_t_wise_balance_index [simp]:\n  assumes \"ps \\<subseteq> \\<V>\"\n  assumes \"card ps = \\<t>\"\n  shows \"(multiple_blocks n) index ps = \\<Lambda>\\<^sub>t * n\"\n  using multiple_point_index balanced assms by fastforce \n\nlemma multiple_t_wise_balance: \n  assumes \"n > 0\" \n  shows \"t_wise_balance \\<V> (multiple_blocks n) \\<t> (\\<Lambda>\\<^sub>t * n)\"\nproof - \n  interpret des: proper_design \\<V> \"(multiple_blocks n)\" by (simp add: assms multiple_proper_design)  \n  show ?thesis using t_non_zero t_lt_order multiple_t_wise_balance_index \n    by (unfold_locales) (simp_all)\nqed\n\nlemma twise_set_pair_index: \"ps \\<subseteq> \\<V> \\<Longrightarrow> ps2 \\<subseteq> \\<V> \\<Longrightarrow> ps \\<noteq> ps2 \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> card ps2 = \\<t> \n  \\<Longrightarrow> \\<B> index ps = \\<B> index ps2\"\n  using balanced by simp\n\nlemma t_wise_balance_alt: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps = l2 \n  \\<Longrightarrow> (\\<And> ps . ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps = l2)\"\n  using twise_set_pair_index by blast\n\nlemma index_1_imp_mult_1 [simp]: \n  assumes \"\\<Lambda>\\<^sub>t = 1\"\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"card bl \\<ge> \\<t>\"\n  shows \"multiplicity bl = 1\"\nproof (rule ccontr)\n  assume \"\\<not> (multiplicity bl = 1)\"\n  then have not: \"multiplicity bl \\<noteq> 1\" by simp\n  have \"multiplicity bl \\<noteq> 0\" using assms by simp \n  then have m: \"multiplicity bl \\<ge> 2\" using not by linarith\n  obtain ps where ps: \"ps \\<subseteq> bl \\<and> card ps = \\<t>\"\n    using assms obtain_t_subset_points\n    by (metis obtain_subset_with_card_n) \n  then have \"\\<B> index ps \\<ge> 2\"\n    using m points_index_count_min ps by blast\n  then show False using balanced ps antisym_conv2 not_numeral_less_zero numeral_le_one_iff \n      points_index_ps_nin semiring_norm(69) zero_neq_numeral assms(1) \n    by (metis assms(1)) \nqed\n\nend\n\nsubsubsection \\<open>Sub-types of t-wise balance\\<close>\n\ntext \\<open>Pairwise balance is when $t = 2$. These are commonly of interest \\<close>\nlocale pairwise_balance = t_wise_balance \\<V> \\<B> 2 \\<Lambda> \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and index (\"\\<Lambda>\")\n\ntext \\<open>We can combine the balance properties with $K$\\_block design to define tBD's \n(t-wise balanced designs), and PBD's (pairwise balanced designs) \\<close>\n\nlocale tBD = t_wise_balance + K_block_design +\n  assumes block_size_gt_t: \"k \\<in> \\<K> \\<Longrightarrow> k \\<ge> \\<t>\"\n\nlocale \\<Lambda>_PBD = pairwise_balance + K_block_design + \n  assumes block_size_gt_t: \"k \\<in> \\<K> \\<Longrightarrow> k \\<ge> 2\"\n\nsublocale \\<Lambda>_PBD \\<subseteq> tBD \\<V> \\<B> 2 \\<Lambda> \\<K>\n  using t_lt_order block_size_gt_t by (unfold_locales) (simp_all)\n\nlocale PBD = \\<Lambda>_PBD \\<V> \\<B> 1 \\<K> for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and sizes (\"\\<K>\")\nbegin\nlemma multiplicity_is_1:\n  assumes \"bl \\<in># \\<B>\"\n  shows \"multiplicity bl = 1\"\n  using block_size_gt_t index_1_imp_mult_1 by (simp add: assms block_sizes) \n\nend\n\nsublocale PBD \\<subseteq> simple_design\n  using multiplicity_is_1 by (unfold_locales)\n\ntext \\<open>PBD's are often only used in the case where $k$ is uniform, defined here. \\<close>\nlocale k_\\<Lambda>_PBD = pairwise_balance + block_design + \n  assumes block_size_t: \"2 \\<le> \\<k>\"\n\nsublocale k_\\<Lambda>_PBD \\<subseteq> \\<Lambda>_PBD \\<V> \\<B> \\<Lambda> \"{\\<k>}\"\n  using k_non_zero uniform block_size_t by(unfold_locales) (simp_all)\n\nlocale k_PBD = k_\\<Lambda>_PBD \\<V> \\<B> 1 \\<k> for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and u_block_size (\"\\<k>\")\n\nsublocale k_PBD \\<subseteq> PBD \\<V> \\<B> \"{\\<k>}\"\n  using  block_size_t by (unfold_locales, simp_all)\n\nsubsubsection \\<open>Covering and Packing Designs \\<close>\ntext \\<open> Covering and packing designs involve a looser balance restriction. Upper/lower bounds\nare placed on the points index, instead of a strict equality \\<close>\n\ntext \\<open> A t-covering design is a relaxed version of a tBD, where, for all point subsets of size t, \na lower bound is put on the points index \\<close>\nlocale t_covering_design = block_design +\n  fixes grouping :: nat (\"\\<t>\")\n  fixes min_index :: nat (\"\\<Lambda>\\<^sub>t\")\n  assumes covering: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps \\<ge> \\<Lambda>\\<^sub>t\" \n  assumes block_size_t: \"\\<t> \\<le> \\<k>\"\n  assumes t_non_zero: \"\\<t> \\<ge> 1\"\nbegin\n\nlemma covering_alt_def_all: \"\\<forall> ps \\<subseteq> \\<V> . card ps = \\<t> \\<longrightarrow> \\<B> index ps \\<ge> \\<Lambda>\\<^sub>t\"\n  using covering by auto\n\nend\n\nlemma (in block_design) t_covering_designI [intro]: \"t \\<le> \\<k> \\<Longrightarrow> t \\<ge> 1 \\<Longrightarrow> \n  (\\<And> ps. ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = t \\<Longrightarrow> \\<B> index ps \\<ge> \\<Lambda>\\<^sub>t) \\<Longrightarrow> t_covering_design \\<V> \\<B> \\<k> t \\<Lambda>\\<^sub>t\"\n  by (unfold_locales) simp_all\n\ntext \\<open> A t-packing design is a relaxed version of a tBD, where, for all point subsets of size t, \nan upper bound is put on the points index \\<close>\nlocale t_packing_design = block_design + \n  fixes grouping :: nat (\"\\<t>\")\n  fixes min_index :: nat (\"\\<Lambda>\\<^sub>t\")\n  assumes packing: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps \\<le> \\<Lambda>\\<^sub>t\"\n  assumes block_size_t: \"\\<t> \\<le> \\<k>\"\n  assumes t_non_zero: \"\\<t> \\<ge> 1\"\nbegin\n\nlemma packing_alt_def_all: \"\\<forall> ps \\<subseteq> \\<V> . card ps = \\<t> \\<longrightarrow> \\<B> index ps \\<le> \\<Lambda>\\<^sub>t\"\n  using packing by auto\n\nend\n\nlemma (in block_design) t_packing_designI [intro]: \"t \\<le> \\<k> \\<Longrightarrow> t \\<ge> 1 \\<Longrightarrow> \n  (\\<And> ps . ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = t \\<Longrightarrow> \\<B> index ps \\<le> \\<Lambda>\\<^sub>t) \\<Longrightarrow> t_packing_design \\<V> \\<B> \\<k> t \\<Lambda>\\<^sub>t\"\n  by (unfold_locales) simp_all\n\nlemma packing_covering_imp_balance: \n  assumes \"t_packing_design V B k t \\<Lambda>\\<^sub>t\" \n  assumes \"t_covering_design V B k t \\<Lambda>\\<^sub>t\" \n  shows \"t_wise_balance V B t \\<Lambda>\\<^sub>t\"\nproof -\n  from assms interpret des: proper_design V B \n    using block_design.axioms(1) t_covering_design.axioms(1) by blast\n  show ?thesis \n  proof (unfold_locales)\n    show \"1 \\<le> t\" using assms t_packing_design.t_non_zero by auto\n    show \"t \\<le> des.\\<v>\" using block_design.block_size_lt_v t_packing_design.axioms(1) \n      by (metis assms(1) dual_order.trans t_packing_design.block_size_t)\n    show \"\\<And>ps. ps \\<subseteq> V \\<Longrightarrow> card ps = t \\<Longrightarrow> B index ps = \\<Lambda>\\<^sub>t\" \n      using t_packing_design.packing t_covering_design.covering by (metis assms dual_order.antisym) \n  qed\nqed\n\nsubsection \\<open>Constant Replication Design \\<close>\ntext \\<open> When the replication number for all points in a design is constant, it is the \ndesign replication number.\\<close>\nlocale constant_rep_design = proper_design +\n  fixes design_rep_number :: nat (\"\\<r>\")\n  assumes rep_number [simp]: \"x \\<in> \\<V> \\<Longrightarrow>  \\<B> rep x = \\<r>\" \n\nbegin\n\nlemma rep_number_alt_def_all: \"\\<forall> x \\<in> \\<V>. \\<B> rep x = \\<r>\"\n  by (simp)\n\nlemma rep_number_unfold_set: \"x \\<in> \\<V> \\<Longrightarrow> size {#bl \\<in># \\<B> . x \\<in> bl#} = \\<r>\"\n  using rep_number by (simp add: point_replication_number_def)\n\nlemma rep_numbers_constant [simp]: \"replication_numbers  = {\\<r>}\"\n  unfolding replication_numbers_def using rep_number design_points_nempty Collect_cong finite.cases \n    finite_sets insertCI singleton_conv fst_conv snd_conv\n  by (smt (z3)) \n\nlemma replication_number_single: \"is_singleton (replication_numbers)\"\n  using is_singleton_the_elem by simp\n\nlemma constant_rep_point_pair: \"x1 \\<in> \\<V> \\<Longrightarrow> x2 \\<in> \\<V> \\<Longrightarrow> x1 \\<noteq> x2 \\<Longrightarrow> \\<B> rep x1 = \\<B> rep x2\"\n  using rep_number by auto\n\nlemma constant_rep_alt: \"x1 \\<in> \\<V> \\<Longrightarrow> \\<B> rep x1 = r2 \\<Longrightarrow> (\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x = r2)\"\n  by (simp)\n\nlemma constant_rep_point_not_0:\n  assumes \"x \\<in> \\<V>\" \n  shows \"\\<B> rep x \\<noteq> 0\"\nproof (rule ccontr)\n  assume \"\\<not> \\<B> rep x \\<noteq> 0\"\n  then have \"\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x = 0\" using rep_number assms by auto\n  then have \"\\<And> x . x \\<in> \\<V> \\<Longrightarrow>  size {#bl \\<in># \\<B> . x \\<in> bl#} = 0\" \n    by (simp add: point_replication_number_def)\n  then show False using design_blocks_nempty wf_design wf_design_iff wf_invalid_point\n    by (metis ex_in_conv filter_mset_empty_conv multiset_nonemptyE size_eq_0_iff_empty)\nqed\n\nlemma rep_not_zero: \"\\<r> \\<noteq> 0\"\n  using rep_number constant_rep_point_not_0 design_points_nempty by auto \n\nlemma r_gzero: \"\\<r> > 0\"\n  using point_replication_number_def rep_number constant_rep_design.rep_not_zero\n  using rep_not_zero by auto\n\nlemma r_lt_eq_b: \"\\<r> \\<le> \\<b>\"\n  using rep_number max_point_rep \n  by (metis all_not_in_conv design_points_nempty) \n\nlemma complement_rep_number: \n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  shows \"constant_rep_design \\<V> \\<B>\\<^sup>C (\\<b> - \\<r>)\"\nproof - \n  interpret d: proper_design \\<V> \"(\\<B>\\<^sup>C)\" using complement_proper_design\n    by (simp add: assms) \n  show ?thesis using complement_rep_number rep_number by (unfold_locales) simp\nqed\n\nlemma multiple_rep_number: \n  assumes \"n > 0\"\n  shows \"constant_rep_design \\<V> (multiple_blocks n) (\\<r> * n)\"\nproof - \n  interpret d: proper_design \\<V> \"(multiple_blocks n)\" using multiple_proper_design\n    by (simp add: assms) \n  show ?thesis using multiple_point_rep_num by (unfold_locales) (simp_all)\nqed\nend\n\nlemma (in proper_design) constant_rep_designI [intro]: \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x = \\<r>) \n    \\<Longrightarrow> constant_rep_design \\<V> \\<B> \\<r>\"\n  by unfold_locales auto\n\nsubsection \\<open> T-designs \\<close>\ntext \\<open>All the before mentioned designs build up to the concept of a t-design, which has uniform \nblock size and is t-wise balanced. We limit $t$ to be less than $k$, so the balance condition has \nrelevance \\<close>\nlocale t_design = incomplete_design + t_wise_balance + \n  assumes block_size_t: \"\\<t> \\<le> \\<k>\"\nbegin\n\nlemma point_indices_balanced: \"point_indices \\<t> = {\\<Lambda>\\<^sub>t}\" \nproof -\n  have \"point_indices \\<t> = {i . \\<exists> ps . i = \\<B> index ps \\<and> card ps = \\<t> \\<and> ps \\<subseteq> \\<V>}\"\n    by (simp add: point_indices_def) \n  then have \"point_indices  \\<t> = {i . i = \\<Lambda>\\<^sub>t}\" using balanced Collect_cong obtain_t_subset_points\n    by (smt (verit, best)) \n  thus ?thesis by auto\nqed\n\nlemma point_indices_singleton: \"is_singleton (point_indices \\<t>)\"\n  using point_indices_balanced is_singleton_the_elem by simp\n\nend\n\nlemma t_designI [intro]: \n  assumes \"incomplete_design V B k\"\n  assumes \"t_wise_balance V B t \\<Lambda>\\<^sub>t\"\n  assumes \"t \\<le> k\"\n  shows \"t_design V B k t \\<Lambda>\\<^sub>t\"\n  by (simp add: assms(1) assms(2) assms(3) t_design.intro t_design_axioms.intro)\n\nsublocale t_design \\<subseteq> t_covering_design \\<V> \\<B> \\<k> \\<t> \\<Lambda>\\<^sub>t\n  using t_non_zero by (unfold_locales) (auto simp add: block_size_t)\n\nsublocale t_design \\<subseteq> t_packing_design \\<V> \\<B> \\<k> \\<t> \\<Lambda>\\<^sub>t\n  using t_non_zero by (unfold_locales) (auto simp add: block_size_t)\n\nlemma t_design_pack_cov [intro]: \n  assumes \"k < card V\"\n  assumes \"t_covering_design V B k t \\<Lambda>\\<^sub>t\"\n  assumes \"t_packing_design V B k t \\<Lambda>\\<^sub>t\"\n  shows \"t_design V B k t \\<Lambda>\\<^sub>t\"\nproof -\n  from assms interpret id: incomplete_design V B k\n    using block_design.incomplete_designI t_packing_design.axioms(1)\n    by blast\n  from assms interpret balance: t_wise_balance V B t \\<Lambda>\\<^sub>t \n    using packing_covering_imp_balance by blast \n  show ?thesis using assms(3) \n    by (unfold_locales) (simp_all add: t_packing_design.block_size_t)\nqed\n\nsublocale t_design \\<subseteq> tBD \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t \"{\\<k>}\"\n  using uniform k_non_zero block_size_t by (unfold_locales) simp_all\n\ncontext t_design \nbegin\n\nlemma multiple_t_design: \"n > 0 \\<Longrightarrow> t_design \\<V> (multiple_blocks n) \\<k> \\<t> (\\<Lambda>\\<^sub>t * n)\"\n  using multiple_t_wise_balance multiple_incomplete block_size_t by (simp add: t_designI)\n\nlemma t_design_min_v: \"\\<v> > 1\"\n  using k_non_zero incomplete by simp\n\nend\n\nsubsection \\<open>Steiner Systems \\<close>\n\ntext \\<open>Steiner systems are a special type of t-design where $\\Lambda_t = 1$ \\<close>\nlocale steiner_system = t_design \\<V> \\<B> \\<k> \\<t> 1 \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and u_block_size (\"\\<k>\") and grouping (\"\\<t>\")\n\nbegin\n\nlemma block_multiplicity [simp]: \n  assumes \"bl \\<in># \\<B>\"\n  shows \"multiplicity bl = 1\"\n  by (simp add: assms block_size_t)\n\nend\n\nsublocale steiner_system \\<subseteq> simple_design\n  by unfold_locales (simp)\n\nlemma (in t_design) steiner_systemI[intro]: \"\\<Lambda>\\<^sub>t = 1 \\<Longrightarrow> steiner_system \\<V> \\<B> \\<k> \\<t>\"\n  using t_non_zero t_lt_order block_size_t\n  by unfold_locales auto\n\nsubsection \\<open>Combining block designs \\<close>\ntext \\<open>We define some closure properties for various block designs under the combine operator.\nThis is done using locales to reason on multiple instances of the same type of design, building \non what was presented in the design operations theory\\<close>\n\nlocale two_t_wise_eq_points = two_designs_proper \\<V> \\<B> \\<V> \\<B>' + des1: t_wise_balance \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t + \n  des2: t_wise_balance \\<V> \\<B>' \\<t> \\<Lambda>\\<^sub>t' for \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t \\<B>' \\<Lambda>\\<^sub>t'\nbegin\n\nlemma combine_t_wise_balance_index: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B>\\<^sup>+ index ps = (\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using des1.balanced des2.balanced by (simp add: combine_points_index)\n\nlemma combine_t_wise_balance: \"t_wise_balance \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<t> (\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\nproof (unfold_locales, simp add: des1.t_non_zero_suc)\n  have \"card \\<V>\\<^sup>+  \\<ge> card \\<V>\" by simp \n  then show \"\\<t> \\<le> card (\\<V>\\<^sup>+)\" using des1.t_lt_order by linarith \n  show \"\\<And>ps. ps \\<subseteq> \\<V>\\<^sup>+ \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> (\\<B>\\<^sup>+ index ps) = \\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t'\" \n    using combine_t_wise_balance_index by blast \nqed\n\nsublocale combine_t_wise_des: t_wise_balance \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<t>\" \"(\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using combine_t_wise_balance by auto\n\nend\n\nlocale two_k_block_designs = two_designs_proper \\<V> \\<B> \\<V>' \\<B>' + des1: block_design \\<V> \\<B> \\<k> + \n  des2: block_design \\<V>' \\<B>' \\<k> for \\<V> \\<B> \\<k> \\<V>' \\<B>'\nbegin\n\nlemma block_design_combine: \"block_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<k>\"\n  using des1.uniform des2.uniform by (unfold_locales) (auto)\n\nsublocale combine_block_des: block_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<k>\"\n  using block_design_combine by simp\n\nend\n\nlocale two_rep_designs_eq_points = two_designs_proper \\<V> \\<B> \\<V> \\<B>' + des1: constant_rep_design \\<V> \\<B> \\<r> + \n  des2: constant_rep_design \\<V> \\<B>' \\<r>' for \\<V> \\<B> \\<r> \\<B>' \\<r>' \nbegin\n\nlemma combine_rep_number: \"constant_rep_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ (\\<r> + \\<r>')\"\n  using combine_rep_number des1.rep_number des2.rep_number by (unfold_locales) (simp)\n\nsublocale combine_const_rep: constant_rep_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"(\\<r> + \\<r>')\"\n  using combine_rep_number by simp\n\nend\n\nlocale two_incomplete_designs = two_k_block_designs \\<V> \\<B> \\<k> \\<V>' \\<B>' + des1: incomplete_design \\<V> \\<B> \\<k> + \n  des2: incomplete_design \\<V>' \\<B>' \\<k> for \\<V> \\<B> \\<k> \\<V>' \\<B>'\nbegin\n\nlemma combine_is_incomplete: \"incomplete_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<k>\"\n  using combine_order des1.incomplete des2.incomplete by (unfold_locales) (simp)\n\nsublocale combine_incomplete: incomplete_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<k>\"\n  using combine_is_incomplete by simp\nend\n\nlocale two_t_designs_eq_points = two_incomplete_designs \\<V> \\<B> \\<k> \\<V> \\<B>' \n  + two_t_wise_eq_points \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t \\<B>' \\<Lambda>\\<^sub>t' + des1: t_design \\<V> \\<B> \\<k> \\<t> \\<Lambda>\\<^sub>t + \n  des2: t_design \\<V> \\<B>' \\<k> \\<t> \\<Lambda>\\<^sub>t' for \\<V> \\<B> \\<k> \\<B>' \\<t> \\<Lambda>\\<^sub>t \\<Lambda>\\<^sub>t'\nbegin\n\nlemma combine_is_t_des: \"t_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<k> \\<t> (\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using des1.block_size_t des2.block_size_t by (unfold_locales)\n\nsublocale combine_t_des: t_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<k>\" \"\\<t>\" \"(\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using combine_is_t_des by blast\n\nend\nend", "meta": {"author": "cledmonds", "repo": "design-theory", "sha": "399b979e974b4a894d2c8803f6761836dffbec7a", "save_path": "github-repos/isabelle/cledmonds-design-theory", "path": "github-repos/isabelle/cledmonds-design-theory/design-theory-399b979e974b4a894d2c8803f6761836dffbec7a/src/Block_Designs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425245706048, "lm_q2_score": 0.8519527944504227, "lm_q1q2_score": 0.7834920187033683}}
{"text": "theory condes_dilemmas imports Main begin \n\ntext {*\n  Proving the constructive and destructive dilemmas in propositional calculus\n*}\n\nlemma \"(P\\<longrightarrow>Q) \\<Longrightarrow>(R\\<longrightarrow>S) \\<Longrightarrow>(P\\<or>R) \\<Longrightarrow>(Q\\<or>S)\"\n  apply(erule disjE)\n   apply(erule impE)\n    apply assumption\n   apply(rule disjI1)\n   apply assumption\n  apply(rule disjI2)\n  apply (erule mp)\n  apply assumption\n  done\n\nlemma \"(P\\<longrightarrow>Q) \\<Longrightarrow>(R\\<longrightarrow>S) \\<Longrightarrow>(\\<not>Q\\<or>\\<not>S)\\<Longrightarrow>(\\<not>P\\<or>\\<not>R) \"\n  apply(erule disjE)\n   apply(rule disjI1)\n   apply(rule notI)\n   apply(erule notE)\n   apply (erule mp)\n   apply assumption\n  apply(rule disjI2)\n  apply(rule notI)\n  apply(erule notE)\n  apply(erule mp)\n  apply assumption\n  done\n", "meta": {"author": "hei411", "repo": "Isabelle", "sha": "9126e84b3e39af28336f25e3b7563a01f70625fa", "save_path": "github-repos/isabelle/hei411-Isabelle", "path": "github-repos/isabelle/hei411-Isabelle/Isabelle-9126e84b3e39af28336f25e3b7563a01f70625fa/Fun_attempts/condes_dilemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7834649138061777}}
{"text": "(*  Title:      HOL/Orderings.thy\n    Author:     Tobias Nipkow, Markus Wenzel, and Larry Paulson\n*)\n\nsection \\<open>Abstract orderings\\<close>\n\ntheory Orderings\nimports HOL\nkeywords \"print_orders\" :: diag\nbegin\n\nML_file \\<open>~~/src/Provers/order_procedure.ML\\<close>\nML_file \\<open>~~/src/Provers/order_tac.ML\\<close>\n\nsubsection \\<open>Abstract ordering\\<close>\n\nlocale partial_preordering =\n  fixes less_eq :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> (infix \\<open>\\<^bold>\\<le>\\<close> 50)\n  assumes refl: \\<open>a \\<^bold>\\<le> a\\<close> \\<comment> \\<open>not \\<open>iff\\<close>: makes problems due to multiple (dual) interpretations\\<close>\n    and trans: \\<open>a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>\\<le> c \\<Longrightarrow> a \\<^bold>\\<le> c\\<close>\n\nlocale preordering = partial_preordering +\n  fixes less :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> (infix \\<open>\\<^bold><\\<close> 50)\n  assumes strict_iff_not: \\<open>a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> \\<not> b \\<^bold>\\<le> a\\<close>\nbegin\n\nlemma strict_implies_order:\n  \\<open>a \\<^bold>< b \\<Longrightarrow> a \\<^bold>\\<le> b\\<close>\n  by (simp add: strict_iff_not)\n\nlemma irrefl: \\<comment> \\<open>not \\<open>iff\\<close>: makes problems due to multiple (dual) interpretations\\<close>\n  \\<open>\\<not> a \\<^bold>< a\\<close>\n  by (simp add: strict_iff_not)\n\nlemma asym:\n  \\<open>a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< a \\<Longrightarrow> False\\<close>\n  by (auto simp add: strict_iff_not)\n\nlemma strict_trans1:\n  \\<open>a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\\<close>\n  by (auto simp add: strict_iff_not intro: trans)\n\nlemma strict_trans2:\n  \\<open>a \\<^bold>< b \\<Longrightarrow> b \\<^bold>\\<le> c \\<Longrightarrow> a \\<^bold>< c\\<close>\n  by (auto simp add: strict_iff_not intro: trans)\n\nlemma strict_trans:\n  \\<open>a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\\<close>\n  by (auto intro: strict_trans1 strict_implies_order)\n\nend\n\nlemma preordering_strictI: \\<comment> \\<open>Alternative introduction rule with bias towards strict order\\<close>\n  fixes less_eq (infix \\<open>\\<^bold>\\<le>\\<close> 50)\n    and less (infix \\<open>\\<^bold><\\<close> 50)\n  assumes less_eq_less: \\<open>\\<And>a b. a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\\<close>\n    assumes asym: \\<open>\\<And>a b. a \\<^bold>< b \\<Longrightarrow> \\<not> b \\<^bold>< a\\<close>\n  assumes irrefl: \\<open>\\<And>a. \\<not> a \\<^bold>< a\\<close>\n  assumes trans: \\<open>\\<And>a b c. a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\\<close>\n  shows \\<open>preordering (\\<^bold>\\<le>) (\\<^bold><)\\<close>\nproof\n  fix a b\n  show \\<open>a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> \\<not> b \\<^bold>\\<le> a\\<close>\n    by (auto simp add: less_eq_less asym irrefl)\nnext\n  fix a\n  show \\<open>a \\<^bold>\\<le> a\\<close>\n    by (auto simp add: less_eq_less)\nnext\n  fix a b c\n  assume \\<open>a \\<^bold>\\<le> b\\<close> and \\<open>b \\<^bold>\\<le> c\\<close> then show \\<open>a \\<^bold>\\<le> c\\<close>\n    by (auto simp add: less_eq_less intro: trans)\nqed\n\nlemma preordering_dualI:\n  fixes less_eq (infix \\<open>\\<^bold>\\<le>\\<close> 50)\n    and less (infix \\<open>\\<^bold><\\<close> 50)\n  assumes \\<open>preordering (\\<lambda>a b. b \\<^bold>\\<le> a) (\\<lambda>a b. b \\<^bold>< a)\\<close>\n  shows \\<open>preordering (\\<^bold>\\<le>) (\\<^bold><)\\<close>\nproof -\n  from assms interpret preordering \\<open>\\<lambda>a b. b \\<^bold>\\<le> a\\<close> \\<open>\\<lambda>a b. b \\<^bold>< a\\<close> .\n  show ?thesis\n    by standard (auto simp: strict_iff_not refl intro: trans)\nqed\n\nlocale ordering = partial_preordering +\n  fixes less :: \\<open>'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> (infix \\<open>\\<^bold><\\<close> 50)\n  assumes strict_iff_order: \\<open>a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> a \\<noteq> b\\<close>\n  assumes antisym: \\<open>a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>\\<le> a \\<Longrightarrow> a = b\\<close>\nbegin\n\nsublocale preordering \\<open>(\\<^bold>\\<le>)\\<close> \\<open>(\\<^bold><)\\<close>\nproof\n  show \\<open>a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> \\<not> b \\<^bold>\\<le> a\\<close> for a b\n    by (auto simp add: strict_iff_order intro: antisym)\nqed\n\nlemma strict_implies_not_eq:\n  \\<open>a \\<^bold>< b \\<Longrightarrow> a \\<noteq> b\\<close>\n  by (simp add: strict_iff_order)\n\nlemma not_eq_order_implies_strict:\n  \\<open>a \\<noteq> b \\<Longrightarrow> a \\<^bold>\\<le> b \\<Longrightarrow> a \\<^bold>< b\\<close>\n  by (simp add: strict_iff_order)\n\nlemma order_iff_strict:\n  \\<open>a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\\<close>\n  by (auto simp add: strict_iff_order refl)\n\nlemma eq_iff: \\<open>a = b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> b \\<^bold>\\<le> a\\<close>\n  by (auto simp add: refl intro: antisym)\n\nend\n\nlemma ordering_strictI: \\<comment> \\<open>Alternative introduction rule with bias towards strict order\\<close>\n  fixes less_eq (infix \\<open>\\<^bold>\\<le>\\<close> 50)\n    and less (infix \\<open>\\<^bold><\\<close> 50)\n  assumes less_eq_less: \\<open>\\<And>a b. a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\\<close>\n    assumes asym: \\<open>\\<And>a b. a \\<^bold>< b \\<Longrightarrow> \\<not> b \\<^bold>< a\\<close>\n  assumes irrefl: \\<open>\\<And>a. \\<not> a \\<^bold>< a\\<close>\n  assumes trans: \\<open>\\<And>a b c. a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\\<close>\n  shows \\<open>ordering (\\<^bold>\\<le>) (\\<^bold><)\\<close>\nproof\n  fix a b\n  show \\<open>a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> a \\<noteq> b\\<close>\n    by (auto simp add: less_eq_less asym irrefl)\nnext\n  fix a\n  show \\<open>a \\<^bold>\\<le> a\\<close>\n    by (auto simp add: less_eq_less)\nnext\n  fix a b c\n  assume \\<open>a \\<^bold>\\<le> b\\<close> and \\<open>b \\<^bold>\\<le> c\\<close> then show \\<open>a \\<^bold>\\<le> c\\<close>\n    by (auto simp add: less_eq_less intro: trans)\nnext\n  fix a b\n  assume \\<open>a \\<^bold>\\<le> b\\<close> and \\<open>b \\<^bold>\\<le> a\\<close> then show \\<open>a = b\\<close>\n    by (auto simp add: less_eq_less asym)\nqed\n\nlemma ordering_dualI:\n  fixes less_eq (infix \\<open>\\<^bold>\\<le>\\<close> 50)\n    and less (infix \\<open>\\<^bold><\\<close> 50)\n  assumes \\<open>ordering (\\<lambda>a b. b \\<^bold>\\<le> a) (\\<lambda>a b. b \\<^bold>< a)\\<close>\n  shows \\<open>ordering (\\<^bold>\\<le>) (\\<^bold><)\\<close>\nproof -\n  from assms interpret ordering \\<open>\\<lambda>a b. b \\<^bold>\\<le> a\\<close> \\<open>\\<lambda>a b. b \\<^bold>< a\\<close> .\n  show ?thesis\n    by standard (auto simp: strict_iff_order refl intro: antisym trans)\nqed\n\nlocale ordering_top = ordering +\n  fixes top :: \\<open>'a\\<close>  (\\<open>\\<^bold>\\<top>\\<close>)\n  assumes extremum [simp]: \\<open>a \\<^bold>\\<le> \\<^bold>\\<top>\\<close>\nbegin\n\nlemma extremum_uniqueI:\n  \\<open>\\<^bold>\\<top> \\<^bold>\\<le> a \\<Longrightarrow> a = \\<^bold>\\<top>\\<close>\n  by (rule antisym) auto\n\nlemma extremum_unique:\n  \\<open>\\<^bold>\\<top> \\<^bold>\\<le> a \\<longleftrightarrow> a = \\<^bold>\\<top>\\<close>\n  by (auto intro: antisym)\n\nlemma extremum_strict [simp]:\n  \\<open>\\<not> (\\<^bold>\\<top> \\<^bold>< a)\\<close>\n  using extremum [of a] by (auto simp add: order_iff_strict intro: asym irrefl)\n\nlemma not_eq_extremum:\n  \\<open>a \\<noteq> \\<^bold>\\<top> \\<longleftrightarrow> a \\<^bold>< \\<^bold>\\<top>\\<close>\n  by (auto simp add: order_iff_strict intro: not_eq_order_implies_strict extremum)\n\nend\n\n\nsubsection \\<open>Syntactic orders\\<close>\n\nclass ord =\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    and less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation\n  less_eq  (\"'(\\<le>')\") and\n  less_eq  (\"(_/ \\<le> _)\"  [51, 51] 50) and\n  less  (\"'(<')\") and\n  less  (\"(_/ < _)\"  [51, 51] 50)\n\nabbreviation (input)\n  greater_eq  (infix \"\\<ge>\" 50)\n  where \"x \\<ge> y \\<equiv> y \\<le> x\"\n\nabbreviation (input)\n  greater  (infix \">\" 50)\n  where \"x > y \\<equiv> y < x\"\n\nnotation (ASCII)\n  less_eq  (\"'(<=')\") and\n  less_eq  (\"(_/ <= _)\" [51, 51] 50)\n\nnotation (input)\n  greater_eq  (infix \">=\" 50)\n\nend\n\n\nsubsection \\<open>Quasi orders\\<close>\n\nclass preorder = ord +\n  assumes less_le_not_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> (y \\<le> x)\"\n  and order_refl [iff]: \"x \\<le> x\"\n  and order_trans: \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\nbegin\n\nsublocale order: preordering less_eq less + dual_order: preordering greater_eq greater\nproof -\n  interpret preordering less_eq less\n    by standard (auto intro: order_trans simp add: less_le_not_le)\n  show \\<open>preordering less_eq less\\<close>\n    by (fact preordering_axioms)\n  then show \\<open>preordering greater_eq greater\\<close>\n    by (rule preordering_dualI)\nqed\n\ntext \\<open>Reflexivity.\\<close>\n\nlemma eq_refl: \"x = y \\<Longrightarrow> x \\<le> y\"\n    \\<comment> \\<open>This form is useful with the classical reasoner.\\<close>\nby (erule ssubst) (rule order_refl)\n\nlemma less_irrefl [iff]: \"\\<not> x < x\"\nby (simp add: less_le_not_le)\n\nlemma less_imp_le: \"x < y \\<Longrightarrow> x \\<le> y\"\nby (simp add: less_le_not_le)\n\n\ntext \\<open>Asymmetry.\\<close>\n\nlemma less_not_sym: \"x < y \\<Longrightarrow> \\<not> (y < x)\"\nby (simp add: less_le_not_le)\n\nlemma less_asym: \"x < y \\<Longrightarrow> (\\<not> P \\<Longrightarrow> y < x) \\<Longrightarrow> P\"\nby (drule less_not_sym, erule contrapos_np) simp\n\n\ntext \\<open>Transitivity.\\<close>\n\nlemma less_trans: \"x < y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\nlemma le_less_trans: \"x \\<le> y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\nlemma less_le_trans: \"x < y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\n\ntext \\<open>Useful for simplification, but too risky to include by default.\\<close>\n\nlemma less_imp_not_less: \"x < y \\<Longrightarrow> (\\<not> y < x) \\<longleftrightarrow> True\"\nby (blast elim: less_asym)\n\nlemma less_imp_triv: \"x < y \\<Longrightarrow> (y < x \\<longrightarrow> P) \\<longleftrightarrow> True\"\nby (blast elim: less_asym)\n\n\ntext \\<open>Transitivity rules for calculational reasoning\\<close>\n\nlemma less_asym': \"a < b \\<Longrightarrow> b < a \\<Longrightarrow> P\"\nby (rule less_asym)\n\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_preorder:\n  \\<open>class.preorder (\\<ge>) (>)\\<close>\n  by standard (auto simp add: less_le_not_le intro: order_trans)\n\nend\n\nlemma preordering_preorderI:\n  \\<open>class.preorder (\\<^bold>\\<le>) (\\<^bold><)\\<close> if \\<open>preordering (\\<^bold>\\<le>) (\\<^bold><)\\<close>\n    for less_eq (infix \\<open>\\<^bold>\\<le>\\<close> 50) and less (infix \\<open>\\<^bold><\\<close> 50)\nproof -\n  from that interpret preordering \\<open>(\\<^bold>\\<le>)\\<close> \\<open>(\\<^bold><)\\<close> .\n  show ?thesis\n    by standard (auto simp add: strict_iff_not refl intro: trans)\nqed\n\n\n\nsubsection \\<open>Partial orders\\<close>\n\nclass order = preorder +\n  assumes order_antisym: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma less_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> x \\<noteq> y\"\n  by (auto simp add: less_le_not_le intro: order_antisym)\n\nsublocale order: ordering less_eq less + dual_order: ordering greater_eq greater\nproof -\n  interpret ordering less_eq less\n    by standard (auto intro: order_antisym order_trans simp add: less_le)\n  show \"ordering less_eq less\"\n    by (fact ordering_axioms)\n  then show \"ordering greater_eq greater\"\n    by (rule ordering_dualI)\nqed\n\nprint_theorems\n\ntext \\<open>Reflexivity.\\<close>\n\nlemma le_less: \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x = y\"\n    \\<comment> \\<open>NOT suitable for iff, since it can cause PROOF FAILED.\\<close>\nby (fact order.order_iff_strict)\n\nlemma le_imp_less_or_eq: \"x \\<le> y \\<Longrightarrow> x < y \\<or> x = y\"\nby (simp add: less_le)\n\n\ntext \\<open>Useful for simplification, but too risky to include by default.\\<close>\n\nlemma less_imp_not_eq: \"x < y \\<Longrightarrow> (x = y) \\<longleftrightarrow> False\"\nby auto\n\nlemma less_imp_not_eq2: \"x < y \\<Longrightarrow> (y = x) \\<longleftrightarrow> False\"\nby auto\n\n\ntext \\<open>Transitivity rules for calculational reasoning\\<close>\n\nlemma neq_le_trans: \"a \\<noteq> b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a < b\"\nby (fact order.not_eq_order_implies_strict)\n\nlemma le_neq_trans: \"a \\<le> b \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a < b\"\nby (rule order.not_eq_order_implies_strict)\n\n\ntext \\<open>Asymmetry.\\<close>\n\nlemma order_eq_iff: \"x = y \\<longleftrightarrow> x \\<le> y \\<and> y \\<le> x\"\n  by (fact order.eq_iff)\n\nlemma antisym_conv: \"y \\<le> x \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x = y\"\n  by (simp add: order.eq_iff)\n\nlemma less_imp_neq: \"x < y \\<Longrightarrow> x \\<noteq> y\"\n  by (fact order.strict_implies_not_eq)\n\nlemma antisym_conv1: \"\\<not> x < y \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x = y\"\n  by (simp add: local.le_less)\n\nlemma antisym_conv2: \"x \\<le> y \\<Longrightarrow> \\<not> x < y \\<longleftrightarrow> x = y\"\n  by (simp add: local.less_le)\n\nlemma leD: \"y \\<le> x \\<Longrightarrow> \\<not> x < y\"\n  by (auto simp: less_le order.antisym)\n\ntext \\<open>Least value operator\\<close>\n\ndefinition (in ord)\n  Least :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \"LEAST \" 10) where\n  \"Least P = (THE x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<le> y))\"\n\nlemma Least_equality:\n  assumes \"P x\"\n    and \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n  shows \"Least P = x\"\nunfolding Least_def by (rule the_equality)\n  (blast intro: assms order.antisym)+\n\nlemma LeastI2_order:\n  assumes \"P x\"\n    and \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n    and \"\\<And>x. P x \\<Longrightarrow> \\<forall>y. P y \\<longrightarrow> x \\<le> y \\<Longrightarrow> Q x\"\n  shows \"Q (Least P)\"\nunfolding Least_def by (rule theI2)\n  (blast intro: assms order.antisym)+\n\nlemma Least_ex1:\n  assumes   \"\\<exists>!x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<le> y)\"\n  shows     Least1I: \"P (Least P)\" and Least1_le: \"P z \\<Longrightarrow> Least P \\<le> z\"\n  using     theI'[OF assms]\n  unfolding Least_def\n  by        auto\n\ntext \\<open>Greatest value operator\\<close>\n\ndefinition Greatest :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \"GREATEST \" 10) where\n\"Greatest P = (THE x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<ge> y))\"\n\nlemma GreatestI2_order:\n  \"\\<lbrakk> P x;\n    \\<And>y. P y \\<Longrightarrow> x \\<ge> y;\n    \\<And>x. \\<lbrakk> P x; \\<forall>y. P y \\<longrightarrow> x \\<ge> y \\<rbrakk> \\<Longrightarrow> Q x \\<rbrakk>\n  \\<Longrightarrow> Q (Greatest P)\"\nunfolding Greatest_def\nby (rule theI2) (blast intro: order.antisym)+\n\nlemma Greatest_equality:\n  \"\\<lbrakk> P x;  \\<And>y. P y \\<Longrightarrow> x \\<ge> y \\<rbrakk> \\<Longrightarrow> Greatest P = x\"\nunfolding Greatest_def\nby (rule the_equality) (blast intro: order.antisym)+\n\nend\n\nlemma ordering_orderI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"ordering less_eq less\"\n  shows \"class.order less_eq less\"\nproof -\n  from assms interpret ordering less_eq less .\n  show ?thesis\n    by standard (auto intro: antisym trans simp add: refl strict_iff_order)\nqed\n\nlemma order_strictI:\n  fixes less (infix \"\\<^bold><\" 50)\n    and less_eq (infix \"\\<^bold>\\<le>\" 50)\n  assumes \"\\<And>a b. a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\"\n    assumes \"\\<And>a b. a \\<^bold>< b \\<Longrightarrow> \\<not> b \\<^bold>< a\"\n  assumes \"\\<And>a. \\<not> a \\<^bold>< a\"\n  assumes \"\\<And>a b c. a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  shows \"class.order less_eq less\"\n  by (rule ordering_orderI) (rule ordering_strictI, (fact assms)+)\n\ncontext order\nbegin\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_order:\n  \"class.order (\\<ge>) (>)\"\n  using dual_order.ordering_axioms by (rule ordering_orderI)\n\nend\n\n\nsubsection \\<open>Linear (total) orders\\<close>\n\nclass linorder = order +\n  assumes linear: \"x \\<le> y \\<or> y \\<le> x\"\nbegin\n\nlemma less_linear: \"x < y \\<or> x = y \\<or> y < x\"\nunfolding less_le using less_le linear by blast\n\nlemma le_less_linear: \"x \\<le> y \\<or> y < x\"\nby (simp add: le_less less_linear)\n\nlemma le_cases [case_names le ge]:\n  \"(x \\<le> y \\<Longrightarrow> P) \\<Longrightarrow> (y \\<le> x \\<Longrightarrow> P) \\<Longrightarrow> P\"\nusing linear by blast\n\nlemma (in linorder) le_cases3:\n  \"\\<lbrakk>\\<lbrakk>x \\<le> y; y \\<le> z\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>y \\<le> x; x \\<le> z\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>x \\<le> z; z \\<le> y\\<rbrakk> \\<Longrightarrow> P;\n    \\<lbrakk>z \\<le> y; y \\<le> x\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>y \\<le> z; z \\<le> x\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>z \\<le> x; x \\<le> y\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (blast intro: le_cases)\n\nlemma linorder_cases [case_names less equal greater]:\n  \"(x < y \\<Longrightarrow> P) \\<Longrightarrow> (x = y \\<Longrightarrow> P) \\<Longrightarrow> (y < x \\<Longrightarrow> P) \\<Longrightarrow> P\"\nusing less_linear by blast\n\nlemma linorder_wlog[case_names le sym]:\n  \"(\\<And>a b. a \\<le> b \\<Longrightarrow> P a b) \\<Longrightarrow> (\\<And>a b. P b a \\<Longrightarrow> P a b) \\<Longrightarrow> P a b\"\n  by (cases rule: le_cases[of a b]) blast+\n\nlemma not_less: \"\\<not> x < y \\<longleftrightarrow> y \\<le> x\"\n  unfolding less_le\n  using linear by (blast intro: order.antisym)\n\nlemma not_less_iff_gr_or_eq: \"\\<not>(x < y) \\<longleftrightarrow> (x > y \\<or> x = y)\"\n  by (auto simp add:not_less le_less)\n\nlemma not_le: \"\\<not> x \\<le> y \\<longleftrightarrow> y < x\"\n  unfolding less_le\n  using linear by (blast intro: order.antisym)\n\nlemma neq_iff: \"x \\<noteq> y \\<longleftrightarrow> x < y \\<or> y < x\"\nby (cut_tac x = x and y = y in less_linear, auto)\n\nlemma neqE: \"x \\<noteq> y \\<Longrightarrow> (x < y \\<Longrightarrow> R) \\<Longrightarrow> (y < x \\<Longrightarrow> R) \\<Longrightarrow> R\"\nby (simp add: neq_iff) blast\n\nlemma antisym_conv3: \"\\<not> y < x \\<Longrightarrow> \\<not> x < y \\<longleftrightarrow> x = y\"\nby (blast intro: order.antisym dest: not_less [THEN iffD1])\n\nlemma leI: \"\\<not> x < y \\<Longrightarrow> y \\<le> x\"\nunfolding not_less .\n\nlemma not_le_imp_less: \"\\<not> y \\<le> x \\<Longrightarrow> x < y\"\nunfolding not_le .\n\nlemma linorder_less_wlog[case_names less refl sym]:\n     \"\\<lbrakk>\\<And>a b. a < b \\<Longrightarrow> P a b;  \\<And>a. P a a;  \\<And>a b. P b a \\<Longrightarrow> P a b\\<rbrakk> \\<Longrightarrow> P a b\"\n  using antisym_conv3 by blast\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_linorder:\n  \"class.linorder (\\<ge>) (>)\"\nby (rule class.linorder.intro, rule dual_order) (unfold_locales, rule linear)\n\nend\n\n\ntext \\<open>Alternative introduction rule with bias towards strict order\\<close>\n\nlemma linorder_strictI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"class.order less_eq less\"\n  assumes trichotomy: \"\\<And>a b. a \\<^bold>< b \\<or> a = b \\<or> b \\<^bold>< a\"\n  shows \"class.linorder less_eq less\"\nproof -\n  interpret order less_eq less\n    by (fact \\<open>class.order less_eq less\\<close>)\n  show ?thesis\n  proof\n    fix a b\n    show \"a \\<^bold>\\<le> b \\<or> b \\<^bold>\\<le> a\"\n      using trichotomy by (auto simp add: le_less)\n  qed\nqed\n\n\nsubsection \\<open>Reasoning tools setup\\<close>\n\nML \\<open>\nstructure Logic_Signature : LOGIC_SIGNATURE = struct\n  val mk_Trueprop = HOLogic.mk_Trueprop\n  val dest_Trueprop = HOLogic.dest_Trueprop\n  val Trueprop_conv = HOLogic.Trueprop_conv\n  val Not = HOLogic.Not\n  val conj = HOLogic.conj\n  val disj = HOLogic.disj\n  \n  val notI = @{thm notI}\n  val ccontr = @{thm ccontr}\n  val conjI = @{thm conjI}  \n  val conjE = @{thm conjE}\n  val disjE = @{thm disjE}\n\n  val not_not_conv = Conv.rewr_conv @{thm eq_reflection[OF not_not]}\n  val de_Morgan_conj_conv = Conv.rewr_conv @{thm eq_reflection[OF de_Morgan_conj]}\n  val de_Morgan_disj_conv = Conv.rewr_conv @{thm eq_reflection[OF de_Morgan_disj]}\n  val conj_disj_distribL_conv = Conv.rewr_conv @{thm eq_reflection[OF conj_disj_distribL]}\n  val conj_disj_distribR_conv = Conv.rewr_conv @{thm eq_reflection[OF conj_disj_distribR]}\nend\n\nstructure HOL_Base_Order_Tac = Base_Order_Tac(\n  structure Logic_Sig = Logic_Signature;\n  (* Exclude types with specialised solvers. *)\n  val excluded_types = [HOLogic.natT, HOLogic.intT, HOLogic.realT]\n)\n\nstructure HOL_Order_Tac = Order_Tac(structure Base_Tac = HOL_Base_Order_Tac)\n\nfun print_orders ctxt0 =\n  let\n    val ctxt = Config.put show_sorts true ctxt0\n    val orders = HOL_Order_Tac.Data.get (Context.Proof ctxt)\n    fun pretty_term t = Pretty.block\n      [Pretty.quote (Syntax.pretty_term ctxt t), Pretty.brk 1,\n        Pretty.str \"::\", Pretty.brk 1,\n        Pretty.quote (Syntax.pretty_typ ctxt (type_of t)), Pretty.brk 1]\n    fun pretty_order ({kind = kind, ops = ops, ...}, _) =\n      Pretty.block ([Pretty.str (@{make_string} kind), Pretty.str \":\", Pretty.brk 1]\n                    @ map pretty_term ops)\n  in\n    Pretty.writeln (Pretty.big_list \"order structures:\" (map pretty_order orders))\n  end\n\nval _ =\n  Outer_Syntax.command \\<^command_keyword>\\<open>print_orders\\<close>\n    \"print order structures available to transitivity reasoner\"\n    (Scan.succeed (Toplevel.keep (print_orders o Toplevel.context_of)))\n\n\\<close>\n\nmethod_setup order = \\<open>\n  Scan.succeed (fn ctxt => SIMPLE_METHOD' (HOL_Order_Tac.tac [] ctxt))\n\\<close> \"transitivity reasoner\"\n\n\ntext \\<open>Declarations to set up transitivity reasoner of partial and linear orders.\\<close>\n\ncontext order\nbegin\n\nlemma nless_le: \"(\\<not> a < b) \\<longleftrightarrow> (\\<not> a \\<le> b) \\<or> a = b\"\n  using local.dual_order.order_iff_strict by blast\n\nlocal_setup \\<open>\n  HOL_Order_Tac.declare_order {\n    ops = {eq = @{term \\<open>(=) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>}, le = @{term \\<open>(\\<le>)\\<close>}, lt = @{term \\<open>(<)\\<close>}},\n    thms = {trans = @{thm order_trans}, refl = @{thm order_refl}, eqD1 = @{thm eq_refl},\n            eqD2 = @{thm eq_refl[OF sym]}, antisym = @{thm order_antisym}, contr = @{thm notE}},\n    conv_thms = {less_le = @{thm eq_reflection[OF less_le]},\n                 nless_le = @{thm eq_reflection[OF nless_le]}}\n  }\n\\<close>\n\nend\n\ncontext linorder\nbegin\n\nlemma nle_le: \"(\\<not> a \\<le> b) \\<longleftrightarrow> b \\<le> a \\<and> b \\<noteq> a\"\n  using not_le less_le by simp\n\nlocal_setup \\<open>\n  HOL_Order_Tac.declare_linorder {\n    ops = {eq = @{term \\<open>(=) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>}, le = @{term \\<open>(\\<le>)\\<close>}, lt = @{term \\<open>(<)\\<close>}},\n    thms = {trans = @{thm order_trans}, refl = @{thm order_refl}, eqD1 = @{thm eq_refl},\n            eqD2 = @{thm eq_refl[OF sym]}, antisym = @{thm order_antisym}, contr = @{thm notE}},\n    conv_thms = {less_le = @{thm eq_reflection[OF less_le]},\n                 nless_le = @{thm eq_reflection[OF not_less]},\n                 nle_le = @{thm eq_reflection[OF nle_le]}}\n  }\n\\<close>\n\nend\n\nsetup \\<open>\n  map_theory_simpset (fn ctxt0 => ctxt0 addSolver\n    mk_solver \"Transitivity\" (fn ctxt => HOL_Order_Tac.tac (Simplifier.prems_of ctxt) ctxt))\n\\<close>\n\nML \\<open>\nlocal\n  fun prp t thm = Thm.prop_of thm = t;  (* FIXME proper aconv!? *)\nin\n\nfun antisym_le_simproc ctxt ct =\n  (case Thm.term_of ct of\n    (le as Const (_, T)) $ r $ s =>\n     (let\n        val prems = Simplifier.prems_of ctxt;\n        val less = Const (\\<^const_name>\\<open>less\\<close>, T);\n        val t = HOLogic.mk_Trueprop(le $ s $ r);\n      in\n        (case find_first (prp t) prems of\n          NONE =>\n            let val t = HOLogic.mk_Trueprop(HOLogic.Not $ (less $ r $ s)) in\n              (case find_first (prp t) prems of\n                NONE => NONE\n              | SOME thm => SOME(mk_meta_eq(thm RS @{thm antisym_conv1})))\n             end\n         | SOME thm => SOME (mk_meta_eq (thm RS @{thm order_class.antisym_conv})))\n      end handle THM _ => NONE)\n  | _ => NONE);\n\nfun antisym_less_simproc ctxt ct =\n  (case Thm.term_of ct of\n    NotC $ ((less as Const(_,T)) $ r $ s) =>\n     (let\n       val prems = Simplifier.prems_of ctxt;\n       val le = Const (\\<^const_name>\\<open>less_eq\\<close>, T);\n       val t = HOLogic.mk_Trueprop(le $ r $ s);\n      in\n        (case find_first (prp t) prems of\n          NONE =>\n            let val t = HOLogic.mk_Trueprop (NotC $ (less $ s $ r)) in\n              (case find_first (prp t) prems of\n                NONE => NONE\n              | SOME thm => SOME (mk_meta_eq(thm RS @{thm linorder_class.antisym_conv3})))\n            end\n        | SOME thm => SOME (mk_meta_eq (thm RS @{thm antisym_conv2})))\n      end handle THM _ => NONE)                           \n  | _ => NONE);\n\nend;\n\\<close>\n\nsimproc_setup antisym_le (\"(x::'a::order) \\<le> y\") = \"K antisym_le_simproc\"\nsimproc_setup antisym_less (\"\\<not> (x::'a::linorder) < y\") = \"K antisym_less_simproc\"\n\n\nsubsection \\<open>Bounded quantifiers\\<close>\n\nsyntax (ASCII)\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _<=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _<=_./ _)\" [0, 0, 10] 10)\n\n  \"_All_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _>_./ _)\"  [0, 0, 10] 10)\n  \"_All_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _>=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _>=_./ _)\" [0, 0, 10] 10)\n\n  \"_All_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _~=_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _~=_./ _)\"  [0, 0, 10] 10)\n\nsyntax\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<le>_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<le>_./ _)\" [0, 0, 10] 10)\n\n  \"_All_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_>_./ _)\"  [0, 0, 10] 10)\n  \"_All_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<ge>_./ _)\" [0, 0, 10] 10)\n  \"_Ex_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<ge>_./ _)\" [0, 0, 10] 10)\n\n  \"_All_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<noteq>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<noteq>_./ _)\"  [0, 0, 10] 10)\n\nsyntax (input)\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _<=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _<=_./ _)\" [0, 0, 10] 10)\n  \"_All_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _~=_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _~=_./ _)\"  [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall>x<y. P\" \\<rightharpoonup> \"\\<forall>x. x < y \\<longrightarrow> P\"\n  \"\\<exists>x<y. P\" \\<rightharpoonup> \"\\<exists>x. x < y \\<and> P\"\n  \"\\<forall>x\\<le>y. P\" \\<rightharpoonup> \"\\<forall>x. x \\<le> y \\<longrightarrow> P\"\n  \"\\<exists>x\\<le>y. P\" \\<rightharpoonup> \"\\<exists>x. x \\<le> y \\<and> P\"\n  \"\\<forall>x>y. P\" \\<rightharpoonup> \"\\<forall>x. x > y \\<longrightarrow> P\"\n  \"\\<exists>x>y. P\" \\<rightharpoonup> \"\\<exists>x. x > y \\<and> P\"\n  \"\\<forall>x\\<ge>y. P\" \\<rightharpoonup> \"\\<forall>x. x \\<ge> y \\<longrightarrow> P\"\n  \"\\<exists>x\\<ge>y. P\" \\<rightharpoonup> \"\\<exists>x. x \\<ge> y \\<and> P\"\n  \"\\<forall>x\\<noteq>y. P\" \\<rightharpoonup> \"\\<forall>x. x \\<noteq> y \\<longrightarrow> P\"\n  \"\\<exists>x\\<noteq>y. P\" \\<rightharpoonup> \"\\<exists>x. x \\<noteq> y \\<and> P\"\n\nprint_translation \\<open>\nlet\n  val All_binder = Mixfix.binder_name \\<^const_syntax>\\<open>All\\<close>;\n  val Ex_binder = Mixfix.binder_name \\<^const_syntax>\\<open>Ex\\<close>;\n  val impl = \\<^const_syntax>\\<open>HOL.implies\\<close>;\n  val conj = \\<^const_syntax>\\<open>HOL.conj\\<close>;\n  val less = \\<^const_syntax>\\<open>less\\<close>;\n  val less_eq = \\<^const_syntax>\\<open>less_eq\\<close>;\n\n  val trans =\n   [((All_binder, impl, less),\n    (\\<^syntax_const>\\<open>_All_less\\<close>, \\<^syntax_const>\\<open>_All_greater\\<close>)),\n    ((All_binder, impl, less_eq),\n    (\\<^syntax_const>\\<open>_All_less_eq\\<close>, \\<^syntax_const>\\<open>_All_greater_eq\\<close>)),\n    ((Ex_binder, conj, less),\n    (\\<^syntax_const>\\<open>_Ex_less\\<close>, \\<^syntax_const>\\<open>_Ex_greater\\<close>)),\n    ((Ex_binder, conj, less_eq),\n    (\\<^syntax_const>\\<open>_Ex_less_eq\\<close>, \\<^syntax_const>\\<open>_Ex_greater_eq\\<close>))];\n\n  fun matches_bound v t =\n    (case t of\n      Const (\\<^syntax_const>\\<open>_bound\\<close>, _) $ Free (v', _) => v = v'\n    | _ => false);\n  fun contains_var v = Term.exists_subterm (fn Free (x, _) => x = v | _ => false);\n  fun mk x c n P = Syntax.const c $ Syntax_Trans.mark_bound_body x $ n $ P;\n\n  fun tr' q = (q, fn _ =>\n    (fn [Const (\\<^syntax_const>\\<open>_bound\\<close>, _) $ Free (v, T),\n        Const (c, _) $ (Const (d, _) $ t $ u) $ P] =>\n        (case AList.lookup (=) trans (q, c, d) of\n          NONE => raise Match\n        | SOME (l, g) =>\n            if matches_bound v t andalso not (contains_var v u) then mk (v, T) l u P\n            else if matches_bound v u andalso not (contains_var v t) then mk (v, T) g t P\n            else raise Match)\n      | _ => raise Match));\nin [tr' All_binder, tr' Ex_binder] end\n\\<close>\n\n\nsubsection \\<open>Transitivity reasoning\\<close>\n\ncontext ord\nbegin\n\nlemma ord_le_eq_trans: \"a \\<le> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<le> c\"\n  by (rule subst)\n\nlemma ord_eq_le_trans: \"a = b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n  by (rule ssubst)\n\nlemma ord_less_eq_trans: \"a < b \\<Longrightarrow> b = c \\<Longrightarrow> a < c\"\n  by (rule subst)\n\nlemma ord_eq_less_trans: \"a = b \\<Longrightarrow> b < c \\<Longrightarrow> a < c\"\n  by (rule ssubst)\n\nend\n\nlemma order_less_subst2: \"(a::'a::order) < b ==> f b < (c::'c::order) ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b < c\"\n  finally (less_trans) show ?thesis .\nqed\n\nlemma order_less_subst1: \"(a::'a::order) < f b ==> (b::'b::order) < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (less_trans) show ?thesis .\nqed\n\nlemma order_le_less_subst2: \"(a::'a::order) <= b ==> f b < (c::'c::order) ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b < c\"\n  finally (le_less_trans) show ?thesis .\nqed\n\nlemma order_le_less_subst1: \"(a::'a::order) <= f b ==> (b::'b::order) < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a <= f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (le_less_trans) show ?thesis .\nqed\n\nlemma order_less_le_subst2: \"(a::'a::order) < b ==> f b <= (c::'c::order) ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b <= c\"\n  finally (less_le_trans) show ?thesis .\nqed\n\nlemma order_less_le_subst1: \"(a::'a::order) < f b ==> (b::'b::order) <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a < f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (less_le_trans) show ?thesis .\nqed\n\nlemma order_subst1: \"(a::'a::order) <= f b ==> (b::'b::order) <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a <= f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (order_trans) show ?thesis .\nqed\n\nlemma order_subst2: \"(a::'a::order) <= b ==> f b <= (c::'c::order) ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a <= c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b <= c\"\n  finally (order_trans) show ?thesis .\nqed\n\nlemma ord_le_eq_subst: \"a <= b ==> f b = c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a <= c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b = c\"\n  finally (ord_le_eq_trans) show ?thesis .\nqed\n\nlemma ord_eq_le_subst: \"a = f b ==> b <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a <= f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a = f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (ord_eq_le_trans) show ?thesis .\nqed\n\nlemma ord_less_eq_subst: \"a < b ==> f b = c ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b = c\"\n  finally (ord_less_eq_trans) show ?thesis .\nqed\n\nlemma ord_eq_less_subst: \"a = f b ==> b < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a = f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (ord_eq_less_trans) show ?thesis .\nqed\n\ntext \\<open>\n  Note that this list of rules is in reverse order of priorities.\n\\<close>\n\nlemmas [trans] =\n  order_less_subst2\n  order_less_subst1\n  order_le_less_subst2\n  order_le_less_subst1\n  order_less_le_subst2\n  order_less_le_subst1\n  order_subst2\n  order_subst1\n  ord_le_eq_subst\n  ord_eq_le_subst\n  ord_less_eq_subst\n  ord_eq_less_subst\n  forw_subst\n  back_subst\n  rev_mp\n  mp\n\nlemmas (in order) [trans] =\n  neq_le_trans\n  le_neq_trans\n\nlemmas (in preorder) [trans] =\n  less_trans\n  less_asym'\n  le_less_trans\n  less_le_trans\n  order_trans\n\nlemmas (in order) [trans] =\n  order.antisym\n\nlemmas (in ord) [trans] =\n  ord_le_eq_trans\n  ord_eq_le_trans\n  ord_less_eq_trans\n  ord_eq_less_trans\n\nlemmas [trans] =\n  trans\n\nlemmas order_trans_rules =\n  order_less_subst2\n  order_less_subst1\n  order_le_less_subst2\n  order_le_less_subst1\n  order_less_le_subst2\n  order_less_le_subst1\n  order_subst2\n  order_subst1\n  ord_le_eq_subst\n  ord_eq_le_subst\n  ord_less_eq_subst\n  ord_eq_less_subst\n  forw_subst\n  back_subst\n  rev_mp\n  mp\n  neq_le_trans\n  le_neq_trans\n  less_trans\n  less_asym'\n  le_less_trans\n  less_le_trans\n  order_trans\n  order.antisym\n  ord_le_eq_trans\n  ord_eq_le_trans\n  ord_less_eq_trans\n  ord_eq_less_trans\n  trans\n\ntext \\<open>These support proving chains of decreasing inequalities\n    a >= b >= c ... in Isar proofs.\\<close>\n\nlemma xt1 [no_atp]:\n  \"a = b \\<Longrightarrow> b > c \\<Longrightarrow> a > c\"\n  \"a > b \\<Longrightarrow> b = c \\<Longrightarrow> a > c\"\n  \"a = b \\<Longrightarrow> b \\<ge> c \\<Longrightarrow> a \\<ge> c\"\n  \"a \\<ge> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<ge> c\"\n  \"(x::'a::order) \\<ge> y \\<Longrightarrow> y \\<ge> x \\<Longrightarrow> x = y\"\n  \"(x::'a::order) \\<ge> y \\<Longrightarrow> y \\<ge> z \\<Longrightarrow> x \\<ge> z\"\n  \"(x::'a::order) > y \\<Longrightarrow> y \\<ge> z \\<Longrightarrow> x > z\"\n  \"(x::'a::order) \\<ge> y \\<Longrightarrow> y > z \\<Longrightarrow> x > z\"\n  \"(a::'a::order) > b \\<Longrightarrow> b > a \\<Longrightarrow> P\"\n  \"(x::'a::order) > y \\<Longrightarrow> y > z \\<Longrightarrow> x > z\"\n  \"(a::'a::order) \\<ge> b \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a > b\"\n  \"(a::'a::order) \\<noteq> b \\<Longrightarrow> a \\<ge> b \\<Longrightarrow> a > b\"\n  \"a = f b \\<Longrightarrow> b > c \\<Longrightarrow> (\\<And>x y. x > y \\<Longrightarrow> f x > f y) \\<Longrightarrow> a > f c\"\n  \"a > b \\<Longrightarrow> f b = c \\<Longrightarrow> (\\<And>x y. x > y \\<Longrightarrow> f x > f y) \\<Longrightarrow> f a > c\"\n  \"a = f b \\<Longrightarrow> b \\<ge> c \\<Longrightarrow> (\\<And>x y. x \\<ge> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> a \\<ge> f c\"\n  \"a \\<ge> b \\<Longrightarrow> f b = c \\<Longrightarrow> (\\<And>x y. x \\<ge> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> f a \\<ge> c\"\n  by auto\n\nlemma xt2 [no_atp]:\n  \"(a::'a::order) >= f b ==> b >= c ==> (!!x y. x >= y ==> f x >= f y) ==> a >= f c\"\nby (subgoal_tac \"f b >= f c\", force, force)\n\nlemma xt3 [no_atp]: \"(a::'a::order) >= b ==> (f b::'b::order) >= c ==>\n    (!!x y. x >= y ==> f x >= f y) ==> f a >= c\"\nby (subgoal_tac \"f a >= f b\", force, force)\n\nlemma xt4 [no_atp]: \"(a::'a::order) > f b ==> (b::'b::order) >= c ==>\n  (!!x y. x >= y ==> f x >= f y) ==> a > f c\"\nby (subgoal_tac \"f b >= f c\", force, force)\n\nlemma xt5 [no_atp]: \"(a::'a::order) > b ==> (f b::'b::order) >= c==>\n    (!!x y. x > y ==> f x > f y) ==> f a > c\"\nby (subgoal_tac \"f a > f b\", force, force)\n\nlemma xt6 [no_atp]: \"(a::'a::order) >= f b ==> b > c ==>\n    (!!x y. x > y ==> f x > f y) ==> a > f c\"\nby (subgoal_tac \"f b > f c\", force, force)\n\nlemma xt7 [no_atp]: \"(a::'a::order) >= b ==> (f b::'b::order) > c ==>\n    (!!x y. x >= y ==> f x >= f y) ==> f a > c\"\nby (subgoal_tac \"f a >= f b\", force, force)\n\nlemma xt8 [no_atp]: \"(a::'a::order) > f b ==> (b::'b::order) > c ==>\n    (!!x y. x > y ==> f x > f y) ==> a > f c\"\nby (subgoal_tac \"f b > f c\", force, force)\n\nlemma xt9 [no_atp]: \"(a::'a::order) > b ==> (f b::'b::order) > c ==>\n    (!!x y. x > y ==> f x > f y) ==> f a > c\"\nby (subgoal_tac \"f a > f b\", force, force)\n\nlemmas xtrans = xt1 xt2 xt3 xt4 xt5 xt6 xt7 xt8 xt9\n\n(*\n  Since \"a >= b\" abbreviates \"b <= a\", the abbreviation \"...\" stands\n  for the wrong thing in an Isar proof.\n\n  The extra transitivity rules can be used as follows:\n\nlemma \"(a::'a::order) > z\"\nproof -\n  have \"a >= b\" (is \"_ >= ?rhs\")\n    sorry\n  also have \"?rhs >= c\" (is \"_ >= ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs = d\" (is \"_ = ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs >= e\" (is \"_ >= ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs > f\" (is \"_ > ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs > z\"\n    sorry\n  finally (xtrans) show ?thesis .\nqed\n\n  Alternatively, one can use \"declare xtrans [trans]\" and then\n  leave out the \"(xtrans)\" above.\n*)\n\n\nsubsection \\<open>Monotonicity\\<close>\n\ncontext order\nbegin\n\ndefinition mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"mono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nlemma monoI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> mono f\"\n  unfolding mono_def by iprover\n\nlemma monoD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"mono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  unfolding mono_def by iprover\n\nlemma monoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<le> f y\"\nproof\n  from assms show \"f x \\<le> f y\" by (simp add: mono_def)\nqed\n\ndefinition antimono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"antimono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<ge> f y)\"\n\nlemma antimonoI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> antimono f\"\n  unfolding antimono_def by iprover\n\nlemma antimonoD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"antimono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  unfolding antimono_def by iprover\n\nlemma antimonoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"antimono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<ge> f y\"\nproof\n  from assms show \"f x \\<ge> f y\" by (simp add: antimono_def)\nqed\n\ndefinition strict_mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"strict_mono f \\<longleftrightarrow> (\\<forall>x y. x < y \\<longrightarrow> f x < f y)\"\n\nlemma strict_monoI [intro?]:\n  assumes \"\\<And>x y. x < y \\<Longrightarrow> f x < f y\"\n  shows \"strict_mono f\"\n  using assms unfolding strict_mono_def by auto\n\nlemma strict_monoD [dest?]:\n  \"strict_mono f \\<Longrightarrow> x < y \\<Longrightarrow> f x < f y\"\n  unfolding strict_mono_def by auto\n\nlemma strict_mono_mono [dest?]:\n  assumes \"strict_mono f\"\n  shows \"mono f\"\nproof (rule monoI)\n  fix x y\n  assume \"x \\<le> y\"\n  show \"f x \\<le> f y\"\n  proof (cases \"x = y\")\n    case True then show ?thesis by simp\n  next\n    case False with \\<open>x \\<le> y\\<close> have \"x < y\" by simp\n    with assms strict_monoD have \"f x < f y\" by auto\n    then show ?thesis by simp\n\n  qed\nqed\n\nend\n\ncontext linorder\nbegin\n\nlemma mono_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x \\<le> y\"\nproof\n  show \"x \\<le> y\"\n  proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma mono_strict_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x < y\"\nproof\n  show \"x < y\"\n  proof (rule ccontr)\n    assume \"\\<not> x < y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_eq:\n  assumes \"strict_mono f\"\n  shows \"f x = f y \\<longleftrightarrow> x = y\"\nproof\n  assume \"f x = f y\"\n  show \"x = y\" proof (cases x y rule: linorder_cases)\n    case less with assms strict_monoD have \"f x < f y\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  next\n    case equal then show ?thesis .\n  next\n    case greater with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  qed\nqed simp\n\nlemma strict_mono_less_eq:\n  assumes \"strict_mono f\"\n  shows \"f x \\<le> f y \\<longleftrightarrow> x \\<le> y\"\nproof\n  assume \"x \\<le> y\"\n  with assms strict_mono_mono monoD show \"f x \\<le> f y\" by auto\nnext\n  assume \"f x \\<le> f y\"\n  show \"x \\<le> y\" proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\" then have \"y < x\" by simp\n    with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x \\<le> f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_less:\n  assumes \"strict_mono f\"\n  shows \"f x < f y \\<longleftrightarrow> x < y\"\n  using assms\n    by (auto simp add: less_le Orderings.less_le strict_mono_eq strict_mono_less_eq)\n\nend\n\n\nsubsection \\<open>min and max -- fundamental\\<close>\n\ndefinition (in ord) min :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"min a b = (if a \\<le> b then a else b)\"\n\ndefinition (in ord) max :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"max a b = (if a \\<le> b then b else a)\"\n\nlemma min_absorb1: \"x \\<le> y \\<Longrightarrow> min x y = x\"\n  by (simp add: min_def)\n\nlemma max_absorb2: \"x \\<le> y \\<Longrightarrow> max x y = y\"\n  by (simp add: max_def)\n\nlemma min_absorb2: \"(y::'a::order) \\<le> x \\<Longrightarrow> min x y = y\"\n  by (simp add:min_def)\n\nlemma max_absorb1: \"(y::'a::order) \\<le> x \\<Longrightarrow> max x y = x\"\n  by (simp add: max_def)\n\nlemma max_min_same [simp]:\n  fixes x y :: \"'a :: linorder\"\n  shows \"max x (min x y) = x\" \"max (min x y) x = x\" \"max (min x y) y = y\" \"max y (min x y) = y\"\nby(auto simp add: max_def min_def)\n\n\nsubsection \\<open>(Unique) top and bottom elements\\<close>\n\nclass bot =\n  fixes bot :: 'a (\"\\<bottom>\")\n\nclass order_bot = order + bot +\n  assumes bot_least: \"\\<bottom> \\<le> a\"\nbegin\n\nsublocale bot: ordering_top greater_eq greater bot\n  by standard (fact bot_least)\n\nlemma le_bot:\n  \"a \\<le> \\<bottom> \\<Longrightarrow> a = \\<bottom>\"\n  by (fact bot.extremum_uniqueI)\n\nlemma bot_unique:\n  \"a \\<le> \\<bottom> \\<longleftrightarrow> a = \\<bottom>\"\n  by (fact bot.extremum_unique)\n\nlemma not_less_bot:\n  \"\\<not> a < \\<bottom>\"\n  by (fact bot.extremum_strict)\n\nlemma bot_less:\n  \"a \\<noteq> \\<bottom> \\<longleftrightarrow> \\<bottom> < a\"\n  by (fact bot.not_eq_extremum)\n\nlemma max_bot[simp]: \"max bot x = x\"\nby(simp add: max_def bot_unique)\n\nlemma max_bot2[simp]: \"max x bot = x\"\nby(simp add: max_def bot_unique)\n\nlemma min_bot[simp]: \"min bot x = bot\"\nby(simp add: min_def bot_unique)\n\nlemma min_bot2[simp]: \"min x bot = bot\"\nby(simp add: min_def bot_unique)\n\nend\n\nclass top =\n  fixes top :: 'a (\"\\<top>\")\n\nclass order_top = order + top +\n  assumes top_greatest: \"a \\<le> \\<top>\"\nbegin\n\nsublocale top: ordering_top less_eq less top\n  by standard (fact top_greatest)\n\nlemma top_le:\n  \"\\<top> \\<le> a \\<Longrightarrow> a = \\<top>\"\n  by (fact top.extremum_uniqueI)\n\nlemma top_unique:\n  \"\\<top> \\<le> a \\<longleftrightarrow> a = \\<top>\"\n  by (fact top.extremum_unique)\n\nlemma not_top_less:\n  \"\\<not> \\<top> < a\"\n  by (fact top.extremum_strict)\n\nlemma less_top:\n  \"a \\<noteq> \\<top> \\<longleftrightarrow> a < \\<top>\"\n  by (fact top.not_eq_extremum)\n\nlemma max_top[simp]: \"max top x = top\"\nby(simp add: max_def top_unique)\n\nlemma max_top2[simp]: \"max x top = top\"\nby(simp add: max_def top_unique)\n\nlemma min_top[simp]: \"min top x = x\"\nby(simp add: min_def top_unique)\n\nlemma min_top2[simp]: \"min x top = x\"\nby(simp add: min_def top_unique)\n\nend\n\n\nsubsection \\<open>Dense orders\\<close>\n\nclass dense_order = order +\n  assumes dense: \"x < y \\<Longrightarrow> (\\<exists>z. x < z \\<and> z < y)\"\n\nclass dense_linorder = linorder + dense_order\nbegin\n\nlemma dense_le:\n  fixes y z :: 'a\n  assumes \"\\<And>x. x < y \\<Longrightarrow> x \\<le> z\"\n  shows \"y \\<le> z\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"z < y\" by simp\n  from dense[OF this]\n  obtain x where \"x < y\" and \"z < x\" by safe\n  moreover have \"x \\<le> z\" using assms[OF \\<open>x < y\\<close>] .\n  ultimately show False by auto\nqed\n\nlemma dense_le_bounded:\n  fixes x y z :: 'a\n  assumes \"x < y\"\n  assumes *: \"\\<And>w. \\<lbrakk> x < w ; w < y \\<rbrakk> \\<Longrightarrow> w \\<le> z\"\n  shows \"y \\<le> z\"\nproof (rule dense_le)\n  fix w assume \"w < y\"\n  from dense[OF \\<open>x < y\\<close>] obtain u where \"x < u\" \"u < y\" by safe\n  from linear[of u w]\n  show \"w \\<le> z\"\n  proof (rule disjE)\n    assume \"u \\<le> w\"\n    from less_le_trans[OF \\<open>x < u\\<close> \\<open>u \\<le> w\\<close>] \\<open>w < y\\<close>\n    show \"w \\<le> z\" by (rule *)\n  next\n    assume \"w \\<le> u\"\n    from \\<open>w \\<le> u\\<close> *[OF \\<open>x < u\\<close> \\<open>u < y\\<close>]\n    show \"w \\<le> z\" by (rule order_trans)\n  qed\nqed\n\nlemma dense_ge:\n  fixes y z :: 'a\n  assumes \"\\<And>x. z < x \\<Longrightarrow> y \\<le> x\"\n  shows \"y \\<le> z\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"z < y\" by simp\n  from dense[OF this]\n  obtain x where \"x < y\" and \"z < x\" by safe\n  moreover have \"y \\<le> x\" using assms[OF \\<open>z < x\\<close>] .\n  ultimately show False by auto\nqed\n\nlemma dense_ge_bounded:\n  fixes x y z :: 'a\n  assumes \"z < x\"\n  assumes *: \"\\<And>w. \\<lbrakk> z < w ; w < x \\<rbrakk> \\<Longrightarrow> y \\<le> w\"\n  shows \"y \\<le> z\"\nproof (rule dense_ge)\n  fix w assume \"z < w\"\n  from dense[OF \\<open>z < x\\<close>] obtain u where \"z < u\" \"u < x\" by safe\n  from linear[of u w]\n  show \"y \\<le> w\"\n  proof (rule disjE)\n    assume \"w \\<le> u\"\n    from \\<open>z < w\\<close> le_less_trans[OF \\<open>w \\<le> u\\<close> \\<open>u < x\\<close>]\n    show \"y \\<le> w\" by (rule *)\n  next\n    assume \"u \\<le> w\"\n    from *[OF \\<open>z < u\\<close> \\<open>u < x\\<close>] \\<open>u \\<le> w\\<close>\n    show \"y \\<le> w\" by (rule order_trans)\n  qed\nqed\n\nend\n\nclass no_top = order +\n  assumes gt_ex: \"\\<exists>y. x < y\"\n\nclass no_bot = order +\n  assumes lt_ex: \"\\<exists>y. y < x\"\n\nclass unbounded_dense_linorder = dense_linorder + no_top + no_bot\n\n\nsubsection \\<open>Wellorders\\<close>\n\nclass wellorder = linorder +\n  assumes less_induct [case_names less]: \"(\\<And>x. (\\<And>y. y < x \\<Longrightarrow> P y) \\<Longrightarrow> P x) \\<Longrightarrow> P a\"\nbegin\n\nlemma wellorder_Least_lemma:\n  fixes k :: 'a\n  assumes \"P k\"\n  shows LeastI: \"P (LEAST x. P x)\" and Least_le: \"(LEAST x. P x) \\<le> k\"\nproof -\n  have \"P (LEAST x. P x) \\<and> (LEAST x. P x) \\<le> k\"\n  using assms proof (induct k rule: less_induct)\n    case (less x) then have \"P x\" by simp\n    show ?case proof (rule classical)\n      assume assm: \"\\<not> (P (LEAST a. P a) \\<and> (LEAST a. P a) \\<le> x)\"\n      have \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n      proof (rule classical)\n        fix y\n        assume \"P y\" and \"\\<not> x \\<le> y\"\n        with less have \"P (LEAST a. P a)\" and \"(LEAST a. P a) \\<le> y\"\n          by (auto simp add: not_le)\n        with assm have \"x < (LEAST a. P a)\" and \"(LEAST a. P a) \\<le> y\"\n          by auto\n        then show \"x \\<le> y\" by auto\n      qed\n      with \\<open>P x\\<close> have Least: \"(LEAST a. P a) = x\"\n        by (rule Least_equality)\n      with \\<open>P x\\<close> show ?thesis by simp\n    qed\n  qed\n  then show \"P (LEAST x. P x)\" and \"(LEAST x. P x) \\<le> k\" by auto\nqed\n\n\\<comment> \\<open>The following 3 lemmas are due to Brian Huffman\\<close>\nlemma LeastI_ex: \"\\<exists>x. P x \\<Longrightarrow> P (Least P)\"\n  by (erule exE) (erule LeastI)\n\nlemma LeastI2:\n  \"P a \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> Q (Least P)\"\n  by (blast intro: LeastI)\n\nlemma LeastI2_ex:\n  \"\\<exists>a. P a \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> Q (Least P)\"\n  by (blast intro: LeastI_ex)\n\nlemma LeastI2_wellorder:\n  assumes \"P a\"\n  and \"\\<And>a. \\<lbrakk> P a; \\<forall>b. P b \\<longrightarrow> a \\<le> b \\<rbrakk> \\<Longrightarrow> Q a\"\n  shows \"Q (Least P)\"\nproof (rule LeastI2_order)\n  show \"P (Least P)\" using \\<open>P a\\<close> by (rule LeastI)\nnext\n  fix y assume \"P y\" thus \"Least P \\<le> y\" by (rule Least_le)\nnext\n  fix x assume \"P x\" \"\\<forall>y. P y \\<longrightarrow> x \\<le> y\" thus \"Q x\" by (rule assms(2))\nqed\n\nlemma LeastI2_wellorder_ex:\n  assumes \"\\<exists>x. P x\"\n  and \"\\<And>a. \\<lbrakk> P a; \\<forall>b. P b \\<longrightarrow> a \\<le> b \\<rbrakk> \\<Longrightarrow> Q a\"\n  shows \"Q (Least P)\"\nusing assms by clarify (blast intro!: LeastI2_wellorder)\n\nlemma not_less_Least: \"k < (LEAST x. P x) \\<Longrightarrow> \\<not> P k\"\napply (simp add: not_le [symmetric])\napply (erule contrapos_nn)\napply (erule Least_le)\ndone\n\nlemma exists_least_iff: \"(\\<exists>n. P n) \\<longleftrightarrow> (\\<exists>n. P n \\<and> (\\<forall>m < n. \\<not> P m))\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs thus ?lhs by blast\nnext\n  assume H: ?lhs then obtain n where n: \"P n\" by blast\n  let ?x = \"Least P\"\n  { fix m assume m: \"m < ?x\"\n    from not_less_Least[OF m] have \"\\<not> P m\" . }\n  with LeastI_ex[OF H] show ?rhs by blast\nqed\n\nend\n\n\nsubsection \\<open>Order on \\<^typ>\\<open>bool\\<close>\\<close>\n\ninstantiation bool :: \"{order_bot, order_top, linorder}\"\nbegin\n\ndefinition\n  le_bool_def [simp]: \"P \\<le> Q \\<longleftrightarrow> P \\<longrightarrow> Q\"\n\ndefinition\n  [simp]: \"(P::bool) < Q \\<longleftrightarrow> \\<not> P \\<and> Q\"\n\ndefinition\n  [simp]: \"\\<bottom> \\<longleftrightarrow> False\"\n\ndefinition\n  [simp]: \"\\<top> \\<longleftrightarrow> True\"\n\ninstance proof\nqed auto\n\nend\n\nlemma le_boolI: \"(P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<le> Q\"\n  by simp\n\nlemma le_boolI': \"P \\<longrightarrow> Q \\<Longrightarrow> P \\<le> Q\"\n  by simp\n\nlemma le_boolE: \"P \\<le> Q \\<Longrightarrow> P \\<Longrightarrow> (Q \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by simp\n\nlemma le_boolD: \"P \\<le> Q \\<Longrightarrow> P \\<longrightarrow> Q\"\n  by simp\n\nlemma bot_boolE: \"\\<bottom> \\<Longrightarrow> P\"\n  by simp\n\nlemma top_boolI: \\<top>\n  by simp\n\n\n\n\nsubsection \\<open>Order on \\<^typ>\\<open>_ \\<Rightarrow> _\\<close>\\<close>\n\ninstantiation \"fun\" :: (type, ord) ord\nbegin\n\ndefinition\n  le_fun_def: \"f \\<le> g \\<longleftrightarrow> (\\<forall>x. f x \\<le> g x)\"\n\ndefinition\n  \"(f::'a \\<Rightarrow> 'b) < g \\<longleftrightarrow> f \\<le> g \\<and> \\<not> (g \\<le> f)\"\n\ninstance ..\n\nend\n\ninstance \"fun\" :: (type, preorder) preorder proof\nqed (auto simp add: le_fun_def less_fun_def\n  intro: order_trans order.antisym)\n\ninstance \"fun\" :: (type, order) order proof\nqed (auto simp add: le_fun_def intro: order.antisym)\n\ninstantiation \"fun\" :: (type, bot) bot\nbegin\n\ndefinition\n  \"\\<bottom> = (\\<lambda>x. \\<bottom>)\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, order_bot) order_bot\nbegin\n\nlemma bot_apply [simp, code]:\n  \"\\<bottom> x = \\<bottom>\"\n  by (simp add: bot_fun_def)\n\ninstance proof\nqed (simp add: le_fun_def)\n\nend\n\ninstantiation \"fun\" :: (type, top) top\nbegin\n\ndefinition\n  [no_atp]: \"\\<top> = (\\<lambda>x. \\<top>)\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, order_top) order_top\nbegin\n\nlemma top_apply [simp, code]:\n  \"\\<top> x = \\<top>\"\n  by (simp add: top_fun_def)\n\ninstance proof\nqed (simp add: le_fun_def)\n\nend\n\nlemma le_funI: \"(\\<And>x. f x \\<le> g x) \\<Longrightarrow> f \\<le> g\"\n  unfolding le_fun_def by simp\n\nlemma le_funE: \"f \\<le> g \\<Longrightarrow> (f x \\<le> g x \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding le_fun_def by simp\n\nlemma le_funD: \"f \\<le> g \\<Longrightarrow> f x \\<le> g x\"\n  by (rule le_funE)\n\nlemma mono_compose: \"mono Q \\<Longrightarrow> mono (\\<lambda>i x. Q i (f x))\"\n  unfolding mono_def le_fun_def by auto\n\n\nsubsection \\<open>Order on unary and binary predicates\\<close>\n\nlemma predicate1I:\n  assumes PQ: \"\\<And>x. P x \\<Longrightarrow> Q x\"\n  shows \"P \\<le> Q\"\n  apply (rule le_funI)\n  apply (rule le_boolI)\n  apply (rule PQ)\n  apply assumption\n  done\n\nlemma predicate1D:\n  \"P \\<le> Q \\<Longrightarrow> P x \\<Longrightarrow> Q x\"\n  apply (erule le_funE)\n  apply (erule le_boolE)\n  apply assumption+\n  done\n\nlemma rev_predicate1D:\n  \"P x \\<Longrightarrow> P \\<le> Q \\<Longrightarrow> Q x\"\n  by (rule predicate1D)\n\nlemma predicate2I:\n  assumes PQ: \"\\<And>x y. P x y \\<Longrightarrow> Q x y\"\n  shows \"P \\<le> Q\"\n  apply (rule le_funI)+\n  apply (rule le_boolI)\n  apply (rule PQ)\n  apply assumption\n  done\n\nlemma predicate2D:\n  \"P \\<le> Q \\<Longrightarrow> P x y \\<Longrightarrow> Q x y\"\n  apply (erule le_funE)+\n  apply (erule le_boolE)\n  apply assumption+\n  done\n\nlemma rev_predicate2D:\n  \"P x y \\<Longrightarrow> P \\<le> Q \\<Longrightarrow> Q x y\"\n  by (rule predicate2D)\n\nlemma bot1E [no_atp]: \"\\<bottom> x \\<Longrightarrow> P\"\n  by (simp add: bot_fun_def)\n\nlemma bot2E: \"\\<bottom> x y \\<Longrightarrow> P\"\n  by (simp add: bot_fun_def)\n\nlemma top1I: \"\\<top> x\"\n  by (simp add: top_fun_def)\n\nlemma top2I: \"\\<top> x y\"\n  by (simp add: top_fun_def)\n\n\nsubsection \\<open>Name duplicates\\<close>\n\nlemmas antisym = order.antisym\nlemmas eq_iff = order.eq_iff\n\nlemmas order_eq_refl = preorder_class.eq_refl\nlemmas order_less_irrefl = preorder_class.less_irrefl\nlemmas order_less_imp_le = preorder_class.less_imp_le\nlemmas order_less_not_sym = preorder_class.less_not_sym\nlemmas order_less_asym = preorder_class.less_asym\nlemmas order_less_trans = preorder_class.less_trans\nlemmas order_le_less_trans = preorder_class.le_less_trans\nlemmas order_less_le_trans = preorder_class.less_le_trans\nlemmas order_less_imp_not_less = preorder_class.less_imp_not_less\nlemmas order_less_imp_triv = preorder_class.less_imp_triv\nlemmas order_less_asym' = preorder_class.less_asym'\n\nlemmas order_less_le = order_class.less_le\nlemmas order_le_less = order_class.le_less\nlemmas order_le_imp_less_or_eq = order_class.le_imp_less_or_eq\nlemmas order_less_imp_not_eq = order_class.less_imp_not_eq\nlemmas order_less_imp_not_eq2 = order_class.less_imp_not_eq2\nlemmas order_neq_le_trans = order_class.neq_le_trans\nlemmas order_le_neq_trans = order_class.le_neq_trans\nlemmas order_eq_iff = order_class.order.eq_iff\nlemmas order_antisym_conv = order_class.antisym_conv\n\nlemmas linorder_linear = linorder_class.linear\nlemmas linorder_less_linear = linorder_class.less_linear\nlemmas linorder_le_less_linear = linorder_class.le_less_linear\nlemmas linorder_le_cases = linorder_class.le_cases\nlemmas linorder_not_less = linorder_class.not_less\nlemmas linorder_not_le = linorder_class.not_le\nlemmas linorder_neq_iff = linorder_class.neq_iff\nlemmas linorder_neqE = linorder_class.neqE\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Orderings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8962513828326955, "lm_q1q2_score": 0.7833929336590015}}
{"text": "theory border_algebra\n  imports operators_basic\nbegin\nnitpick_params[assms=true, user_axioms=true, show_all, expect=genuine, format=3] (*default Nitpick settings*)\n\nsection \\<open>Border algebra\\<close>\n(**We define a border algebra in an analogous fashion to the well-known closure/interior algebras.\nWe also verify a few interesting properties.*)\n\n(**Declares a primitive (unconstrained) border operation and defines others from it.*)\nconsts \\<B>::\"\\<sigma>\\<Rightarrow>\\<sigma>\"\nabbreviation \"\\<I> \\<equiv> \\<I>\\<^sub>B \\<B>\" (**interior*)\nabbreviation \"\\<C> \\<equiv> \\<C>\\<^sub>B \\<B>\" (**closure*)\nabbreviation \"\\<F> \\<equiv> \\<F>\\<^sub>B \\<B>\" (**frontier*)\n\n\nsubsection \\<open>Basic properties\\<close>\n\n(**Verifies minimal conditions under which operators resulting from conversion functions coincide.*)\nlemma ICdual:  \"\\<I> \\<^bold>\\<equiv> \\<C>\\<^sup>d\" by (simp add: Cl_br_def Int_br_def dual_def equal_op_def conn)\nlemma ICdual': \"\\<C> \\<^bold>\\<equiv> \\<I>\\<^sup>d\"  by (simp add: Cl_br_def Int_br_def dual_def equal_op_def conn)\nlemma FI_rel: \"Br_1 \\<B> \\<Longrightarrow> \\<F> \\<^bold>\\<equiv> \\<F>\\<^sub>I \\<I>\" using Fr_br_def Fr_int_def Int_br_def equal_op_def by (smt Br_5b_def PB5b dual_def conn)\nlemma IF_rel: \"Br_1 \\<B> \\<Longrightarrow> \\<I> \\<^bold>\\<equiv> \\<I>\\<^sub>F \\<F>\" using Br_5b_def Fr_br_def Int_br_def Int_fr_def PB5b unfolding equal_op_def conn by fastforce\nlemma FC_rel: \"Br_1 \\<B> \\<Longrightarrow> \\<F> \\<^bold>\\<equiv> \\<F>\\<^sub>C \\<C>\" using Br_5b_def Cl_br_def Fr_br_def Fr_cl_def PB5b unfolding equal_op_def conn by fastforce\nlemma CF_rel: \"Br_1 \\<B> \\<Longrightarrow> \\<C> \\<^bold>\\<equiv> \\<C>\\<^sub>F \\<F>\" using Br_5b_def Cl_br_def Cl_fr_def Fr_br_def PB5b unfolding equal_op_def conn by fastforce\n\n\n(**Fixed-point and other operators are interestingly related.*)\nlemma fp1: \"Br_1 \\<B> \\<Longrightarrow> \\<I>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<B>\\<^sup>c\" using Br_5b_def Int_br_def PB5b unfolding equal_op_def conn by fastforce\nlemma fp2: \"Br_1 \\<B> \\<Longrightarrow> \\<B>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<I>\\<^sup>c\" using Br_5b_def Int_br_def PB5b conn equal_op_def by fastforce \nlemma fp3: \"Br_1 \\<B> \\<Longrightarrow> \\<C>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<B>\\<^sup>d\" using Br_5c_def Cl_br_def PB5c dual_def unfolding equal_op_def conn by fastforce\nlemma fp4: \"Br_1 \\<B> \\<Longrightarrow> (\\<B>\\<^sup>d)\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<C>\" by (smt dimp_def equal_op_def fp3)\nlemma fp5: \"Br_1 \\<B> \\<Longrightarrow> \\<F>\\<^sup>f\\<^sup>p \\<^bold>\\<equiv> \\<B> \\<^bold>\\<squnion> (\\<C>\\<^sup>c)\" by (smt Br_5b_def Cl_br_def Fr_br_def PB5b equal_op_def conn)\n\n(**Define some fixed-point predicates and prove some properties.*)\nabbreviation openset (\"Op\") where \"Op A \\<equiv> fp \\<I> A\"\nabbreviation closedset (\"Cl\") where \"Cl A \\<equiv> fp \\<C> A\"\nabbreviation borderset (\"Br\") where \"Br A \\<equiv> fp \\<B> A\"\nabbreviation frontierset (\"Fr\") where \"Fr A \\<equiv> fp \\<F> A\"\n\nlemma Int_Open: \"Br_1 \\<B> \\<Longrightarrow> Br_3 \\<B> \\<Longrightarrow> \\<forall>A. Op(\\<I> A)\" using IB4 IDEM_def by blast\nlemma Cl_Closed: \"Br_1 \\<B> \\<Longrightarrow> Br_3 \\<B> \\<Longrightarrow> \\<forall>A. Cl(\\<C> A)\" using CB4 IDEM_def by blast\nlemma Br_Border: \"Br_1 \\<B> \\<Longrightarrow> \\<forall>A. Br(\\<B> A)\" using IDEM_def PB6 by blast\n(**In contrast, there is no analogous fixed-point result for frontier:*)\nlemma \"\\<BB> \\<B> \\<Longrightarrow> \\<forall>A. Fr(\\<F> A)\" nitpick oops (*counterexample even if assuming all border conditions*)\n\nlemma OpCldual: \"\\<forall>A. Cl A \\<longleftrightarrow> Op(\\<^bold>\\<midarrow>A)\" using Cl_br_def Int_br_def conn by auto \nlemma ClOpdual: \"\\<forall>A. Op A \\<longleftrightarrow> Cl(\\<^bold>\\<midarrow>A)\" using Cl_br_def Int_br_def conn by auto\nlemma Fr_ClBr: \"Br_1 \\<B> \\<Longrightarrow> \\<forall>A. Fr(A) = (Cl(A) \\<and> Br(A))\" by (metis BF_rel Br_fr_def CF_rel Cl_fr_def eq_ext' join_def meet_def)\nlemma Cl_F: \"Br_1 \\<B> \\<Longrightarrow> Br_3 \\<B> \\<Longrightarrow> \\<forall>A. Cl(\\<F> A)\" by (metis CF_rel Cl_fr_def FB4 Fr_4_def eq_ext' join_def)\n\nend", "meta": {"author": "davfuenmayor", "repo": "topological-semantics", "sha": "770a84ffa2cf8498bd5f60853d11be4d77fc8cd3", "save_path": "github-repos/isabelle/davfuenmayor-topological-semantics", "path": "github-repos/isabelle/davfuenmayor-topological-semantics/topological-semantics-770a84ffa2cf8498bd5f60853d11be4d77fc8cd3/old-stuff (to migrate from old version)/TBA/border_algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8740772368049822, "lm_q1q2_score": 0.7833929237113059}}
{"text": "theory Fixpoint\n  imports Main\nbegin\n\ncontext order\nbegin\n\ndefinition endo_galois_connection :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_galois_connection f g \\<equiv> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n\ndefinition endo_lower_adjoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_lower_adjoint f \\<equiv> \\<exists>g. endo_galois_connection f g\"\n\ndefinition endo_upper_adjoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_upper_adjoint g \\<equiv> \\<exists>f. endo_galois_connection f g\"\n\nlemma endo_deflation: \"endo_galois_connection f g \\<Longrightarrow> f (g y) \\<le> y\"\n  by (metis endo_galois_connection_def le_less)\n\nlemma endo_inflation: \"endo_galois_connection f g \\<Longrightarrow> x \\<le> g (f x)\"\n  by (metis endo_galois_connection_def le_less)\n\n(* Sledgehammer can't seem to use mono due to it's sort constraints *)\ndefinition isotone :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"isotone f \\<equiv> \\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y\"\n\nlemma isotone_is_mono: \"isotone f \\<Longrightarrow> mono f\"\n  by (metis (hide_lams, mono_tags) order_class.isotone_def order_class.mono_def)\n\nlemma isotoneD: \"\\<lbrakk>isotone f; x \\<le> y\\<rbrakk> \\<Longrightarrow> f x \\<le> f y\"\n  by (metis isotone_def)\n\ndefinition idempotent :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"idempotent f \\<equiv> f \\<circ> f = f\"\n\nlemma endo_lower_iso: \"endo_galois_connection f g \\<Longrightarrow> isotone f\"\n  by (metis endo_galois_connection_def endo_inflation isotone_def order_trans)\n\nlemma endo_upper_iso: \"endo_galois_connection f g \\<Longrightarrow> isotone g\"\n  by (metis (lifting) endo_deflation endo_galois_connection_def isotone_def order_trans)\n\nlemma endo_lower_comp: \"endo_galois_connection f g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\nproof\n  fix x\n  assume \"endo_galois_connection f g\"\n  thus \"(f \\<circ> g \\<circ> f) x = f x\"\n    by (metis comp_apply endo_deflation endo_galois_connection_def endo_inflation isotoneD less_le less_le_not_le endo_lower_iso endo_upper_adjoint_def)\nqed\n\nlemma endo_upper_comp: \"endo_galois_connection f g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\nproof\n  fix x\n  assume \"endo_galois_connection f g\"\n  thus \"(g \\<circ> f \\<circ> g) x = g x\"\n    by (metis (full_types) antisym endo_deflation endo_inflation isotone_def o_apply endo_upper_iso)\nqed\n\nlemma endo_upper_idempotency1: \"endo_galois_connection f g \\<Longrightarrow> idempotent (f \\<circ> g)\"\n  by (metis idempotent_def o_assoc endo_upper_comp)\n\nlemma endo_upper_idempotency2: \"endo_galois_connection f g \\<Longrightarrow> idempotent (g \\<circ> f)\"\n  by (metis idempotent_def o_assoc endo_lower_comp)\n\nlemma endo_galois_comp: assumes g1: \"endo_galois_connection F G\" and g2 :\"endo_galois_connection H K\"\n  shows \"endo_galois_connection (F \\<circ> H) (K \\<circ> G)\"\n  by (smt g1 g2 endo_galois_connection_def o_apply)\n\nlemma endo_galois_id: \"endo_galois_connection id id\" by (metis endo_galois_connection_def id_def)\n\nlemma endo_galois_isotone1: \"endo_galois_connection f g \\<Longrightarrow> isotone (g \\<circ> f)\"\n  by (smt endo_galois_connection_def endo_inflation isotoneD isotone_def o_apply order_trans endo_upper_iso)\n\nlemma endo_galois_isotone2: \"endo_galois_connection f g \\<Longrightarrow> isotone (f \\<circ> g)\"\n  by (metis isotone_def endo_lower_iso o_apply endo_upper_iso)\n\nlemma endo_cancel: assumes g: \"endo_galois_connection f g\" shows \"f (g x) \\<le> g (f x)\"\n  by (metis assms endo_deflation endo_inflation order_trans)\n\nlemma endo_cancel_cor1: assumes g: \"endo_galois_connection f g\"\n  shows \"(g x = g y) \\<longleftrightarrow> (f (g x) = f (g y))\"\n  by (metis assms endo_upper_comp o_apply)\n\nlemma endo_cancel_cor2: assumes g: \"endo_galois_connection f g\"\n  shows \"(f x = f y) \\<longleftrightarrow> (g (f x) = g (f y))\"\n  by (metis assms endo_lower_comp o_apply)\n\nlemma endo_semi_inverse1: \"endo_galois_connection f g \\<Longrightarrow> f x = f (g (f x))\"\n  by (metis o_def endo_lower_comp)\n\nlemma endo_semi_inverse2: \"endo_galois_connection f g \\<Longrightarrow> g x = g (f (g x))\"\n  by (metis o_def endo_upper_comp)\n\nlemma endo_universal_mapping_property1:\n  assumes a: \"isotone g\" and b: \"\\<forall>x. x \\<le> g (f x)\"\n  and c: \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n  shows \"endo_galois_connection f g\"\n  by (metis a b c endo_galois_connection_def isotoneD order_trans)\n\nlemma endo_universal_mapping_property2:\n  assumes a: \"isotone f\" and b: \"\\<forall>x. f (g x) \\<le> x\"\n  and c: \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n  shows \"endo_galois_connection f g\"\n  by (metis a b c endo_galois_connection_def isotoneD order_trans)\n\nlemma endo_galois_ump2: \"endo_galois_connection f g = (isotone f \\<and> (\\<forall>y. f (g y) \\<le> y) \\<and> (\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y))\"\n  by (metis endo_deflation endo_galois_connection_def endo_lower_iso endo_universal_mapping_property2)\n\nlemma endo_galois_ump1: \"endo_galois_connection f g = (isotone g \\<and> (\\<forall>x. x \\<le> g (f x)) \\<and> (\\<forall>x y. x \\<le> g y \\<longrightarrow> f x \\<le> y))\"\n  by (metis endo_galois_connection_def endo_inflation endo_universal_mapping_property1 endo_upper_iso)\n\n(* +------------------------------------------------------------------------+\n   | Theorem 4.10(a)                                                        |\n   +------------------------------------------------------------------------+ *)\n\nlemma endo_ore_galois:\n  assumes\"\\<forall>x. x \\<le> g (f x)\" and \"\\<forall>x. f (g x) \\<le> x\"\n  and \"isotone f\" and  \"isotone g\"\n  shows \"endo_galois_connection f g\"\n  by (metis assms isotoneD order_trans endo_universal_mapping_property1)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.32(a) and 4.32(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma endo_perfect1: \"endo_galois_connection f g \\<Longrightarrow> g (f x) = x \\<longleftrightarrow> x \\<in> range g\"\n  by (metis (full_types) image_iff range_eqI endo_semi_inverse2)\n\nlemma endo_perfect2: \"endo_galois_connection f g \\<Longrightarrow> f (g x) = x \\<longleftrightarrow> x \\<in> range f\"\n  by (metis (full_types) image_iff range_eqI endo_semi_inverse1)\n\nend\n\ndefinition pleq :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"pleq f g \\<equiv> \\<forall>x. f x \\<le> g x\"\n\ndefinition galois_connection :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"galois_connection f g \\<equiv> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n\nlemma galoisD: \"galois_connection f g \\<Longrightarrow> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n  by (simp add: galois_connection_def)\n\nlemma rev_galoisD: \"galois_connection f g \\<Longrightarrow> \\<forall>x y.  (x \\<le> g y) \\<longleftrightarrow> (f x \\<le> y)\"\n  by (simp add: galois_connection_def)\n\ndefinition lower_adjoint :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"lower_adjoint f \\<equiv> \\<exists>g. galois_connection f g\"\n\ndefinition upper_adjoint :: \"('b::order \\<Rightarrow> 'a::order) \\<Rightarrow> bool\" where\n  \"upper_adjoint g \\<equiv> \\<exists>f. galois_connection f g\"\n\nlemma deflation: \"galois_connection f g \\<Longrightarrow> f (g y) \\<le> y\"\n  by (metis galois_connection_def le_less)\n\nlemma deflationD: \"galois_connection f g \\<Longrightarrow> \\<forall>y. f (g y) \\<le> y\"\n  by (metis galois_connection_def le_less)\n\nlemma inflation: \"galois_connection f g \\<Longrightarrow> x \\<le> g (f x)\"\n  by (metis galois_connection_def le_less)\n\nlemma inflationD: \"galois_connection f g \\<Longrightarrow> \\<forall>x. x \\<le> g (f x)\"\n  by (metis galois_connection_def le_less)\n\ndefinition idempotent :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"idempotent f \\<equiv> f \\<circ> f = f\"\n\nlemma lower_iso: \"galois_connection f g \\<Longrightarrow> mono f\"\n  apply (frule galoisD)\n  apply (auto simp add: mono_def)\n  apply (drule inflationD)\n  apply (erule_tac x = y in allE) back\n  by (metis order_trans)\n\nlemma upper_iso: \"galois_connection f g \\<Longrightarrow> mono g\"\n  apply (frule rev_galoisD)\n  apply (auto simp add: mono_def)\n  apply (drule deflationD)\n  apply (erule_tac x = x in allE)\n  by (metis order_trans)\n\nlemma lower_comp: \"galois_connection f g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\nproof\n  fix x\n  assume \"galois_connection f g\"\n  thus \"(f \\<circ> g \\<circ> f) x = f x\"\n    apply (simp add: galois_connection_def)\n    by (metis `galois_connection f g` lower_iso monoE order_class.order.antisym order_refl)\nqed\n\nlemma upper_comp: \"galois_connection f g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\nproof\n  fix x\n  assume \"galois_connection f g\"\n  thus \"(g \\<circ> f \\<circ> g) x = g x\"\n    apply (simp add: galois_connection_def)\n    by (metis `galois_connection f g` monoE order_class.order.antisym order_refl upper_iso)\nqed\n\nlemma upper_idempotency1: \"galois_connection f g \\<Longrightarrow> idempotent (f \\<circ> g)\"\n  by (metis idempotent_def o_assoc upper_comp)\n\nlemma upper_idempotency2: \"galois_connection f g \\<Longrightarrow> idempotent (g \\<circ> f)\"\n  by (metis idempotent_def o_assoc lower_comp)\n\nlemma galois_comp: assumes g1: \"galois_connection F G\" and g2 :\"galois_connection H K\"\n  shows \"galois_connection (F \\<circ> H) (K \\<circ> G)\"\n  by (smt g1 g2 galois_connection_def o_apply)\n\nlemma galois_id: \"galois_connection id id\"\n  by (simp add: galois_connection_def)\n\nlemma galois_isotone1: \"galois_connection f g \\<Longrightarrow> mono (g \\<circ> f)\"\n  by (smt galois_connection_def inflation monoD mono_def o_apply order_trans upper_iso)\n\nlemma galois_isotone2: \"galois_connection f g \\<Longrightarrow> mono (f \\<circ> g)\"\n  by (metis mono_def lower_iso o_apply upper_iso)\n\nlemma point_id1: \"galois_connection f g \\<Longrightarrow> id \\<sqsubseteq> g \\<circ> f\"\n  by (metis inflation id_apply o_apply pleq_def)\n\nlemma point_id2: \"galois_connection f g \\<Longrightarrow> f \\<circ> g \\<sqsubseteq> id\"\n  by (metis deflation id_apply o_apply pleq_def)\n\nlemma point_cancel: assumes g: \"galois_connection f g\" shows \"f \\<circ> g \\<sqsubseteq> g \\<circ> f\" using g\n  by (simp add: galois_connection_def o_def pleq_def) (metis g monoE order_refl upper_iso)\n\nlemma cancel: assumes g: \"galois_connection f g\" shows \"f (g x) \\<le> g (f x)\"\n  by (metis assms deflation inflation order_trans)\n\nlemma cancel_cor1: assumes g: \"galois_connection f g\"\n  shows \"(g x = g y) \\<longleftrightarrow> (f (g x) = f (g y))\"\n  by (metis assms upper_comp o_apply)\n\nlemma cancel_cor2: assumes g: \"galois_connection f g\"\n  shows \"(f x = f y) \\<longleftrightarrow> (g (f x) = g (f y))\"\n  by (metis assms lower_comp o_apply)\n\nlemma semi_inverse1: \"galois_connection f g \\<Longrightarrow> f x = f (g (f x))\"\n  by (metis o_def lower_comp)\n\nlemma semi_inverse2: \"galois_connection f g \\<Longrightarrow> g x = g (f (g x))\"\n  by (metis o_def upper_comp)\n\nlemma universal_mapping_property1:\n  assumes a: \"mono g\" and b: \"\\<forall>x. x \\<le> g (f x)\"\n  and c: \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n  shows \"galois_connection f g\"\n  by (metis (full_types) a b c galois_connection_def monoD order_trans)\n\nlemma universal_mapping_property2:\n  assumes a: \"mono f\" and b: \"\\<forall>x. f (g x) \\<le> x\"\n  and c: \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n  shows \"galois_connection f g\"\n  by (metis (full_types) a b c galois_connection_def monoD order_trans)\n\nlemma galois_ump2: \"galois_connection f g = (mono f \\<and> (\\<forall>y. f (g y) \\<le> y) \\<and> (\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y))\"\n  by (metis deflation galois_connection_def lower_iso universal_mapping_property2)\n\nlemma galois_ump1: \"galois_connection f g = (mono g \\<and> (\\<forall>x. x \\<le> g (f x)) \\<and> (\\<forall>x y. x \\<le> g y \\<longrightarrow> f x \\<le> y))\"\n  by (metis galois_connection_def inflation universal_mapping_property1 upper_iso)\n\n(* +------------------------------------------------------------------------+\n   | Theorem 4.10(a)                                                        |\n   +------------------------------------------------------------------------+ *)\n\nlemma ore_galois:\n  assumes\"\\<forall>x. x \\<le> g (f x)\" and \"\\<forall>x. f (g x) \\<le> x\"\n  and \"mono f\" and  \"mono g\"\n  shows \"galois_connection f g\"\n  by (metis assms monoD order_trans universal_mapping_property1)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.32(a) and 4.32(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma perfect1: \"galois_connection f g \\<Longrightarrow> g (f x) = x \\<longleftrightarrow> x \\<in> range g\"\n  by (metis (full_types) image_iff range_eqI semi_inverse2)\n\nlemma perfect2: \"galois_connection f g \\<Longrightarrow> f (g x) = x \\<longleftrightarrow> x \\<in> range f\"\n  by (metis (full_types) image_iff range_eqI semi_inverse1)\n\n(* Fixpoints *)\n\ncontext order\nbegin\n\ndefinition is_lpp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lpp x f \\<equiv> f x \\<le> x \\<and> (\\<forall>y. f y \\<le> y \\<longrightarrow> x \\<le> y)\"\n\ndefinition is_gpp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gpp x f \\<equiv> x \\<le> f x \\<and> (\\<forall>y. y \\<le> f y \\<longrightarrow> y \\<le> x)\"\n\nlemma lpp_unique: \"\\<lbrakk>is_lpp x f; is_lpp y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (auto intro: antisym simp only: is_lpp_def)\n\nlemma gpp_unique: \"\\<lbrakk>is_gpp x f; is_gpp y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (auto intro: antisym simp only: is_gpp_def)\n\ndefinition is_lfp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lfp x f \\<equiv> f x = x \\<and> (\\<forall>y. f y = y \\<longrightarrow> x \\<le> y)\"\n\ndefinition is_gfp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gfp x f \\<equiv> x = f x \\<and> (\\<forall>y. f y = y \\<longrightarrow> y \\<le> x)\"\n\ndefinition least_fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<mu>\") where\n  \"\\<mu> f \\<equiv> THE x. is_lfp x f\"\n\nnotation least_fixpoint (binder \"\\<mu>\" 10)\n\nlemma lfp_eta: \"(\\<mu> x. f x) = \\<mu> f\" by simp\n\nlemma lfp_equality: \"is_lfp x f \\<Longrightarrow> \\<mu> f = x\"\n  by (metis (lifting) eq_iff is_lfp_def least_fixpoint_def the_equality)\n\nlemma lpp_is_lfp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_lpp x f \\<Longrightarrow> is_lfp x f\"\n  by (auto intro: antisym simp add: is_lfp_def is_lpp_def)\n\ndefinition greatest_fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<nu>\") where\n  \"\\<nu> f \\<equiv> THE x. is_gfp x f\"\n\nnotation greatest_fixpoint (binder \"\\<nu>\" 10)\n\nlemma gfp_eta: \"(\\<nu> x. f x) = \\<nu> f\" by simp\n\nlemma gfp_equality: \"is_gfp x f \\<Longrightarrow> \\<nu> f = x\"\n  by (metis (lifting) eq_iff greatest_fixpoint_def is_gfp_def the_equality)\n\nlemma gpp_is_gfp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_gpp x f \\<Longrightarrow> is_gfp x f\"\n  by (auto intro: antisym simp add: is_gfp_def is_gpp_def)\n\nend\n\nlemma continuity_mono:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"(\\<And>X. Sup (f ` X) = f (Sup X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis Sup_le_iff antisym atMost_iff imageI order_refl)\n\nlemma Inf_continuity_mono:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"(\\<And>X. Inf (f ` X) = f (Inf X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis antisym atLeast_iff image_eqI le_Inf_iff order_refl)\n\ndefinition (in order) directed :: \"'a set \\<Rightarrow> bool\" where\n  \"directed X \\<equiv> X \\<noteq> {} \\<and> (\\<forall>x y. x \\<in> X \\<and> y \\<in> X \\<longrightarrow> (\\<exists>z. x \\<le> z \\<and> y \\<le> z))\"\n\ncontext complete_lattice\nbegin\n\nlemma continuity_mono1: \"(\\<And>X. Sup (f ` X) = f (Sup X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis Sup_le_iff antisym atMost_iff imageI order_refl)\n\nlemma continuity_mono2: \"(\\<And>X. Inf (f ` X) = f (Inf X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis (full_types) Inf_atLeastAtMost Inf_superset_mono atLeastatMost_subset_iff eq_refl image_mono)\n\nlemma scott_continuity_mono: \"(\\<And>X. directed X \\<Longrightarrow> Sup (f ` X) = f (Sup X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\nproof -\n  assume scott_continuity: \"\\<And>X. directed X \\<Longrightarrow> Sup (f ` X) = f (Sup X)\"\n \n  {\n    fix x y\n    have \"directed {x, y}\"\n    by (auto intro: exI[of _ \"sup x y\"] simp add: directed_def)\n    hence \"Sup (f ` {x, y}) = f (Sup {x, y})\"\n      by (metis scott_continuity)\n    hence \"sup (f x) (f y) = f (sup x y)\"\n      by auto\n  }\n  moreover assume \"x \\<le> y\"\n  ultimately show ?thesis\n    by (metis le_iff_sup)\nqed \n\nlemma Inf_continuity_mono1: \"(\\<And>X. Inf (f ` X) = f (Inf X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis antisym atLeast_iff image_eqI le_Inf_iff order_refl)\n\ntheorem knaster_tarski_lpp:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" shows \"\\<exists>!x. is_lpp x f\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"Inf ?H\"\n\n  have \"f ?a \\<le> ?a\"\n  proof -\n    have \"\\<forall>x\\<in>?H. ?a \\<le> x\"\n      by (auto intro: Inf_lower)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<le> f x\"\n      by (metis assms)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<le> x\"\n      by (metis (lifting) mem_Collect_eq order_trans)\n    thus \"f ?a \\<le> ?a\"\n      by (metis Inf_greatest lfp_def)\n  qed\n  moreover show \"\\<And>x. is_lpp x f \\<Longrightarrow> x = ?a\"\n    by (metis eq_iff is_lpp_def lfp_def lfp_greatest lfp_lowerbound)\n  ultimately show \"is_lpp ?a f\"\n    by (metis is_lpp_def lfp_def lfp_lowerbound)\nqed\n\ntheorem knaster_tarski: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> \\<exists>!x. is_lfp x f\"\n  by (metis knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\ncorollary is_lfp_lfp [intro?]:\n  \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_lfp (\\<mu> f) f\"\n  by (metis knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\ntheorem knaster_tarski_gpp:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" shows \"\\<exists>!x. is_gpp x f\"\nproof\n  let ?H = \"{u. u \\<le> f u}\"\n  let ?a = \"Sup ?H\"\n\n  have \"?a \\<le> f ?a\"\n  proof -\n    have \"\\<forall>x\\<in>?H. x \\<le> ?a\"\n      by (metis Sup_upper)\n    hence \"\\<forall>x\\<in>?H. f x \\<le> f ?a\"\n      by (metis assms)\n    hence \"\\<forall>x\\<in>?H. x \\<le> f ?a\"\n      by (metis (lifting) mem_Collect_eq order_trans)\n    thus \"?a \\<le> f ?a\"\n      by (metis Sup_least gfp_def)\n  qed\n  moreover show \"\\<And>x. is_gpp x f \\<Longrightarrow> x = ?a\"\n    by (metis (lifting, full_types) Sup_upper calculation eq_iff is_gpp_def mem_Collect_eq)\n  ultimately show \"is_gpp ?a f\"\n    by (simp add: is_gpp_def) (metis (full_types) Sup_upper mem_Collect_eq)\nqed\n\ntheorem knaster_tarski_gfp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> \\<exists>!x. is_gfp x f\"\n  by (metis gfp_equality gpp_is_gfp knaster_tarski_gpp)\n\ncorollary is_gfp_gfp [intro?]:\n  \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_gfp (\\<nu> f) f\"\n  by (metis gfp_equality knaster_tarski_gfp)\n\nlemma fp_compute [simp]: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> f (\\<mu> f) = \\<mu> f\"\n  by (metis is_lfp_def is_lfp_lfp)\n\nlemma gfp_compute [simp]: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> f (\\<nu> f) = \\<nu> f\"\n  by (metis is_gfp_def is_gfp_gfp)\n\nlemma fp_induct [intro?]:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" and \"f x \\<le> x\" shows \"\\<mu> f \\<le> x\"\n  by (metis (full_types) assms is_lpp_def knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\nlemma gfp_induct [intro?]:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" and \"x \\<le> f x\" shows \"x \\<le> \\<nu> f\"\n  by (metis assms gpp_is_gfp is_gfp_gfp is_gpp_def knaster_tarski_gfp knaster_tarski_gpp)\n\nprimrec iter :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"iter f 0 x = x\"\n| \"iter f (Suc n) x = f (iter f n x)\"\n\nlemma iter_mono: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> iter f n x \\<le> iter f n y\"\n  by (induct n) simp_all\n\nlemma iter_pp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> f y \\<le> y \\<Longrightarrow> iter f n y \\<le> y\"\n  apply (induct n)\n  apply simp\n  by (metis (full_types) iter.simps(2) order_trans)\n\nlemma iter_plus: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> iter f n bot \\<le> iter f (n + m) bot\"\nproof (induct n)\n  case 0 thus ?case\n    by auto\nnext\n  case (Suc n)\n  thus ?case\n    by auto\nqed\n\ntheorem kleene_lfp:\n  assumes scott_continuity: \"(\\<And>X. directed X \\<Longrightarrow> Sup (f ` X) = f (Sup X))\"\n  shows \"\\<mu> f = Sup {iter f n bot|n. True}\"\nproof -\n  let ?C = \"{iter f n bot|n. True}\"\n  let ?c = \"Sup {iter f n bot|n. True}\"\n\n  have directed_C: \"directed ?C\"\n    apply (auto simp add: directed_def)\n    apply (rename_tac n m)\n    apply (rule_tac x = \"iter f (n + m) bot\" in exI)\n    apply auto\n    apply (metis iter_plus scott_continuity scott_continuity_mono)\n    by (metis (full_types) iter_plus nat_add_commute scott_continuity scott_continuity_mono)\n\n  have \"f ?c \\<le> ?c\"\n  proof -\n    have \"f ?c = Sup (f ` ?C)\"\n      by (metis scott_continuity[OF directed_C])\n    also have \"... \\<le> ?c\"\n      apply (rule Sup_mono)\n      apply (auto simp add: image_def)\n      apply (rule_tac x = \"iter f (Suc n) bot\" in exI)\n      apply auto\n      by (metis iter.simps(2))\n    finally show ?thesis .\n  qed\n\n  moreover have \"(\\<forall>y. f y \\<le> y \\<longrightarrow> ?c \\<le> y)\"\n  proof clarify\n    fix y assume y_fp: \"f y \\<le> y\"\n    have \"bot \\<le> y\"\n      by (metis bot_least)\n    hence \"\\<forall>n. iter f n bot \\<le> iter f n y\"\n      by (metis scott_continuity scott_continuity_mono iter_mono)\n     hence \"\\<forall>n. iter f n bot \\<le> y\"\n      by (metis scott_continuity scott_continuity_mono iter_pp order_trans y_fp)\n    thus \"?c \\<le> y\"\n      by (auto intro!: Sup_least)\n  qed\n\n  ultimately have \"is_lpp ?c f\"\n    by (auto simp add: is_lpp_def)\n  hence \"is_lfp ?c f\"\n    by (metis (full_types) scott_continuity scott_continuity_mono lpp_is_lfp)\n  thus \"\\<mu> f = ?c\"\n    by (metis lfp_equality)\nqed\n\nlemma kleene_gfp:\n  assumes continuity: \"(\\<And>X. Inf (f ` X) = f (Inf X))\"\n  shows \"\\<nu> f = Inf {iter f n top|n. True}\"\nproof -\n  let ?C = \"{iter f n top|n. True}\"\n  let ?c = \"Inf {iter f n top|n. True}\"\n\n  have \"?c \\<le> f ?c\"\n  proof -\n    have \"?c \\<le> Inf (f ` ?C)\"\n      apply (rule Inf_mono)\n      apply (auto simp add: image_def)\n      apply (rule_tac x = \"iter f (Suc n) top\" in exI)\n      apply auto\n      by (metis iter.simps(2))\n    also have \"... \\<le> f ?c\"\n      by (metis continuity eq_refl)\n    finally show ?thesis .\n  qed\n\n  moreover have \"(\\<forall>y. y \\<le> f y \\<longrightarrow> y \\<le> ?c)\"\n  proof clarify\n    fix y assume y_fp: \"y \\<le> f y\"\n    have \"y \\<le> top\"\n     by (metis top_greatest)\n    hence \"\\<forall>n. iter f n y \\<le> iter f n top\"\n      by (metis continuity Inf_continuity_mono1 iter_mono)\n    moreover have \"\\<forall>n. y \\<le> iter f n y\"\n    proof clarify\n      fix n show \"y \\<le> iter f n y\" apply (induct n) apply simp_all\n        apply (rule order_trans[of _ \"f y\"])\n        apply (metis y_fp)\n        apply (rule Inf_continuity_mono1[OF continuity])\n        by auto\n    qed\n    ultimately have \"\\<forall>n. y \\<le> iter f n top\"\n      by (metis order_trans)\n    thus \"y \\<le> ?c\"\n      by (auto intro!: Inf_greatest)\n  qed\n\n  ultimately have \"is_gpp ?c f\"\n    by (auto simp add: is_gpp_def)\n  hence \"is_gfp ?c f\"\n    by (metis (full_types) Inf_continuity_mono1 continuity gpp_is_gfp)\n  thus \"\\<nu> f = ?c\"\n    by (metis gfp_equality)\nqed\n\nlemma gfp_equality_var [intro?]: \"\\<lbrakk>f x = x; \\<And>y. f y = y \\<Longrightarrow> y \\<le> x\\<rbrakk> \\<Longrightarrow> x = \\<nu> f\"\n  by (metis gfp_equality is_gfp_def)\n\nlemma lfp_equality_var [intro?]: \"\\<lbrakk>f x = x; \\<And>y. f y = y \\<Longrightarrow> x \\<le> y\\<rbrakk> \\<Longrightarrow> x = \\<mu> f\"\n  by (metis is_lfp_def lfp_equality)\n\ntheorem endo_fixpoint_fusion [simp]:\n  assumes upper_ex: \"endo_lower_adjoint f\"\n  and hiso: \"isotone h\" and kiso: \"isotone k\"\n  and comm: \"f\\<circ>h = k\\<circ>f\"\n  shows \"f (\\<mu> h) = \\<mu> k\"\nproof\n  show \"k (f (\\<mu> h)) = f (\\<mu> h)\"\n    by (metis comm fp_compute hiso isotone_def o_eq_dest_lhs)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain g where conn: \"endo_galois_connection f g\" by (metis endo_lower_adjoint_def upper_ex)\n  have \"\\<mu> h \\<le> g y\" using isotoneD[OF hiso]\n  proof (rule fp_induct)\n    have \"f (g y) \\<le> y\" by (metis conn endo_deflation)\n    hence \"f (h (g y)) \\<le> y\" by (metis comm kiso ky isotoneD o_def)\n    thus \"h (g y) \\<le> g y\" by (metis conn endo_galois_connection_def)\n  qed\n  thus \"f (\\<mu> h) \\<le> y\" by (metis conn endo_galois_connection_def)\nqed\n\ntheorem endo_greatest_fixpoint_fusion [simp]:\n  assumes lower_ex: \"endo_upper_adjoint g\"\n  and hiso: \"isotone h\" and kiso: \"isotone k\"\n  and comm: \"g\\<circ>h = k\\<circ>g\"\n  shows \"g (\\<nu> h) = \\<nu> k\"\nproof\n  show \"k (g (\\<nu> h)) = g (\\<nu> h)\"\n    by (metis comm gfp_compute hiso isotone_def o_eq_dest_lhs)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain f where conn: \"endo_galois_connection f g\" by (metis lower_ex endo_upper_adjoint_def)\n  have \"f y \\<le> \\<nu> h\" using isotoneD[OF hiso]\n  proof (rule gfp_induct)\n    have \"y \\<le> g (f y)\" by (metis conn endo_inflation)\n    hence \"y \\<le> g (h (f y))\" by (metis (full_types) comm comp_apply isotoneD kiso ky)\n    thus \"f y \\<le> h (f y)\" by (metis conn endo_galois_connection_def)\n  qed\n  thus \"y \\<le> g (\\<nu> h)\" by (metis conn endo_galois_connection_def)\nqed\n\nend\n\ntheorem fixpoint_fusion [simp]:\n  fixes k :: \"'b::complete_lattice \\<Rightarrow> 'b\"\n  and h :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  and f :: \"'a \\<Rightarrow> 'b\"\n  assumes upper_ex: \"lower_adjoint f\"\n  and hiso: \"mono h\" and kiso: \"mono k\"\n  and comm: \"f\\<circ>h = k\\<circ>f\"\n  shows \"f (\\<mu> h) = \\<mu> k\"\nproof\n  show \"k (f (\\<mu> h)) = f (\\<mu> h)\" using monoD[OF hiso]\n    by (metis comm fp_compute o_eq_dest_lhs)\nnext\n  fix y :: \"'b\" assume ky: \"k y = y\"\n  obtain g where conn: \"galois_connection f g\" by (metis lower_adjoint_def upper_ex)\n  have \"\\<mu> h \\<le> g y\"\n  proof (rule fp_induct)\n    fix x y :: 'a assume \"x \\<le> y\" thus \"h x \\<le> h y\"\n      by (rule monoD[OF hiso])\n  next\n    have \"f (g y) \\<le> y\" by (metis conn deflation)\n    hence \"f (h (g y)) \\<le> y\" by (metis comm kiso ky monoD o_def)\n    thus \"h (g y) \\<le> g y\" by (metis conn galois_connection_def)\n  qed\n  thus \"f (\\<mu> h) \\<le> y\" by (metis conn galois_connection_def)\nqed\n\ntheorem greatest_fixpoint_fusion [simp]:\n  fixes k :: \"'b::complete_lattice \\<Rightarrow> 'b\"\n  and h :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  and f :: \"'a \\<Rightarrow> 'b\"\n  assumes lower_ex: \"upper_adjoint g\"\n  and hiso: \"mono h\" and kiso: \"mono k\"\n  and comm: \"g\\<circ>h = k\\<circ>g\"\n  shows \"g (\\<nu> h) = \\<nu> k\"\nproof\n  show \"k (g (\\<nu> h)) = g (\\<nu> h)\" using monoD[OF hiso]\n    by (metis (full_types) comm comp_apply gfp_compute)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain f where conn: \"galois_connection f g\" by (metis lower_ex upper_adjoint_def)\n  have \"f y \\<le> \\<nu> h\"\n  proof (rule gfp_induct)\n    fix x y :: 'a assume \"x \\<le> y\" thus \"h x \\<le> h y\"\n      by (rule monoD[OF hiso])\n  next\n    have \"y \\<le> g (f y)\" by (metis conn inflation)\n    hence \"y \\<le> g (h (f y))\" by (metis (full_types) comm comp_apply monoD kiso ky)\n    thus \"f y \\<le> h (f y)\" by (metis conn galois_connection_def)\n  qed\n  thus \"y \\<le> g (\\<nu> h)\" by (metis conn galois_connection_def)\nqed\n\ndefinition join_preserving :: \"('a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<Rightarrow> bool\" where\n  \"join_preserving f \\<equiv> \\<forall>X. Sup (f ` X) = f (Sup X)\"\n\ndefinition meet_preserving :: \"('a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<Rightarrow> bool\" where\n  \"meet_preserving g \\<equiv> \\<forall>X. Inf (g ` X) = g (Inf X)\"\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.25(a) and 4.25(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma (in complete_lattice) Sup_eq_equiv: \"Sup A = x \\<longleftrightarrow> (\\<forall>z. (x \\<le> z \\<longleftrightarrow> (\\<forall>y\\<in>A. y \\<le> z)))\"\n  apply default\n  apply (metis Sup_le_iff)\n  by (metis (full_types) Sup_le_iff Sup_upper le_iff_inf less_infI2 less_le order_refl)\n\nlemma (in complete_lattice) Inf_eq_equiv: \"Inf A = x \\<longleftrightarrow> (\\<forall>z. (z \\<le> x \\<longleftrightarrow> (\\<forall>y\\<in>A. z \\<le> y)))\"\n  apply default\n  apply (metis Inf_greatest Inf_lower order_trans)\n  by (metis Inf_atLeast Inf_lower Inf_superset_mono atLeast_def mem_Collect_eq order.antisym subsetI)\n\nlemma lower_adjoint_Sup:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  assumes \"Sup X = x\" and \"lower_adjoint f\" shows \"Sup (f ` X) = f x\" using assms\n  apply (simp add: Sup_eq_equiv lower_adjoint_def)\n  apply (erule exE)\n  apply (simp add: galois_ump2 mono_def)\n  apply (erule conjE)+\n  by (metis order_trans)\n\nlemma lower_preserves_join: \"lower_adjoint f \\<Longrightarrow> join_preserving f\"\n  by (metis join_preserving_def lower_adjoint_Sup)\n\ntheorem suprema_galois: \"galois_connection f g = (join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y))\"\nproof (intro iffI conjI)\n  assume \"galois_connection f g\"\n  hence \"lower_adjoint f\"\n    by (metis lower_adjoint_def)\n  thus \"join_preserving f\"\n    by (rule lower_preserves_join)\n  from `galois_connection f g`\n  show \"\\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by (simp add: Sup_eq_equiv galois_ump2 mono_def) (metis (full_types) order_trans)\nnext\n  assume \"join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)\"\n  hence f_jp: \"join_preserving f\" and a2: \"\\<And>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  have f_iso: \"mono f\"\n    apply (rule monoI)\n    apply (rule continuity_mono) back\n    apply (metis f_jp join_preserving_def)\n    by simp\n  show \"galois_connection f g\"\n  proof (simp add: galois_connection_def)\n    have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n      using a2 by (auto simp only: Sup_eq_equiv)\n    moreover have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n    proof (intro impI allI)\n      fix x y\n      assume gr: \"x \\<le> g y\"\n      show \"f x \\<le> y\"\n      proof -\n        have lem: \"Sup (f ` {x. f x \\<le> y}) \\<le> y\"\n          by (rule Sup_least) auto\n\n        have \"f x \\<le> y \\<Longrightarrow> x \\<le> Sup {z. f z \\<le> y}\"\n          by (metis `join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n        moreover have \"x \\<le> Sup {z. f z \\<le> y} \\<Longrightarrow> f x \\<le> f (Sup {z. f z \\<le> y})\"\n          by (metis f_iso monoD)\n        moreover have \"(f x \\<le> f (Sup {z. f z \\<le> y})) = (f x \\<le> Sup (f ` {z. f z \\<le> y}))\"\n          by (metis (full_types) `join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` join_preserving_def)\n        moreover have \"... \\<Longrightarrow> f x \\<le> y\" using lem\n          by (metis order_trans)\n        ultimately show ?thesis\n          by (metis `join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\"\n      by auto\n  qed\nqed\n\nlemma lower_is_jp: \"lower_adjoint f \\<longleftrightarrow> join_preserving f\"\nproof\n  assume \"lower_adjoint f\" thus \"join_preserving f\"\n    by (metis lower_preserves_join)\nnext\n  assume \"join_preserving f\"\n  moreover hence \"\\<exists>g. \\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  ultimately show \"lower_adjoint f\"\n    by (metis (full_types) lower_adjoint_def suprema_galois)\nqed\n\ncontext complete_lattice begin\n\ndefinition endo_join_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_join_preserving f \\<equiv> \\<forall>X. Sup (f ` X) = f (Sup X)\"\n\ndefinition endo_meet_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_meet_preserving g \\<equiv> \\<forall>X. Inf (g ` X) = g (Inf X)\"\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.25(a) and 4.25(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma endo_lower_adjoint_Sup: \"Sup X = x \\<Longrightarrow> endo_lower_adjoint f \\<Longrightarrow> Sup (f ` X) = f x\"\n  apply (simp add: Sup_eq_equiv endo_lower_adjoint_def)\n  apply (erule exE)\n  apply (simp add: endo_galois_ump2 isotone_def)\n  apply (erule conjE)+\n  by (metis order_trans)\n\nlemma endo_lower_preserves_join: \"endo_lower_adjoint f \\<Longrightarrow> endo_join_preserving f\"\n  by (metis endo_join_preserving_def endo_lower_adjoint_Sup)\n\ntheorem endo_suprema_galois: \"endo_galois_connection f g = (endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y))\"\nproof (intro iffI conjI)\n  assume \"endo_galois_connection f g\"\n  hence \"endo_lower_adjoint f\"\n    by (metis endo_lower_adjoint_def)\n  thus \"endo_join_preserving f\"\n    by (rule endo_lower_preserves_join)\n  from `endo_galois_connection f g`\n  show \"\\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by (simp add: Sup_eq_equiv endo_galois_ump2 isotone_def) (metis (full_types) order_trans)\nnext\n  assume \"endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)\"\n  hence f_jp: \"endo_join_preserving f\" and a2: \"\\<And>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  hence f_iso: \"isotone f\"\n    by (metis (mono_tags) continuity_mono1 endo_join_preserving_def isotone_def)\n  show \"endo_galois_connection f g\"\n  proof (simp add: endo_galois_connection_def)\n    have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n      using a2 by (auto simp only: Sup_eq_equiv)\n    moreover have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n    proof (intro impI allI)\n      fix x y\n      assume gr: \"x \\<le> g y\"\n      show \"f x \\<le> y\"\n      proof -\n        have lem: \"Sup (f ` {x. f x \\<le> y}) \\<le> y\"\n          by (metis (full_types) SUP_def SUP_le_iff mem_Collect_eq)\n\n        have \"f x \\<le> y \\<Longrightarrow> x \\<le> Sup {z. f z \\<le> y}\"\n          by (metis `endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n        moreover have \"x \\<le> Sup {z. f z \\<le> y} \\<Longrightarrow> f x \\<le> f (Sup {z. f z \\<le> y})\"\n          by (metis f_iso isotoneD)\n        moreover have \"(f x \\<le> f (Sup {z. f z \\<le> y})) = (f x \\<le> Sup (f ` {z. f z \\<le> y}))\"\n          by (metis (full_types) `endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` endo_join_preserving_def)\n        moreover have \"... \\<Longrightarrow> f x \\<le> y\" using lem\n          by (metis order_trans)\n        ultimately show ?thesis\n          by (metis `endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\"\n      by auto\n  qed\nqed\n\nlemma endo_lower_is_jp: \"endo_lower_adjoint f \\<longleftrightarrow> endo_join_preserving f\"\nproof\n  assume \"endo_lower_adjoint f\" thus \"endo_join_preserving f\"\n    by (metis endo_lower_preserves_join)\nnext\n  assume \"endo_join_preserving f\"\n  moreover hence \"\\<exists>g. \\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  ultimately show \"endo_lower_adjoint f\"\n    by (metis (full_types) endo_lower_adjoint_def endo_suprema_galois)\nqed\n\nlemma endo_upper_adjoint_Inf: \"Inf X = x \\<Longrightarrow> endo_upper_adjoint f \\<Longrightarrow> Inf (f ` X) = f x\"\n  apply (simp add: Inf_eq_equiv endo_upper_adjoint_def)\n  apply (erule exE)\n  apply (simp add: endo_galois_ump2 isotone_def)\n  apply (erule conjE)+\n  by (metis order_trans)\n\nlemma endo_upper_preserves_meet: \"endo_upper_adjoint f \\<Longrightarrow> endo_meet_preserving f\"\n  by (metis endo_meet_preserving_def endo_upper_adjoint_Inf)\n\ntheorem endo_infima_galois: \"endo_galois_connection f g = (endo_meet_preserving g \\<and> (\\<forall>y. Inf {x. y \\<le> g x} = f y))\"\nproof (intro iffI conjI)\n  assume \"endo_galois_connection f g\"\n  hence \"endo_upper_adjoint g\"\n    by (metis endo_upper_adjoint_def)\n  thus \"endo_meet_preserving g\"\n    by (rule endo_upper_preserves_meet)\n  from `endo_galois_connection f g`\n  show \"\\<forall>y. Inf {x. y \\<le> g x} = f y\"\n    by (simp add: Inf_eq_equiv endo_galois_ump1 isotone_def) (metis (full_types) order_trans)\nnext\n  assume \"endo_meet_preserving g \\<and> (\\<forall>y. Inf {x. y \\<le> g x} = f y)\"\n  hence f_jp: \"endo_meet_preserving g\" and a2: \"\\<And>y. Inf {x. y \\<le> g x} = f y\"\n    by auto\n  hence f_iso: \"isotone g\"\n    by (metis (mono_tags) continuity_mono2 endo_meet_preserving_def isotone_def)\n  show \"endo_galois_connection f g\"\n  proof (simp add: endo_galois_connection_def)\n    have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n      using a2 by (metis Inf_lower mem_Collect_eq)\n    moreover have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n    proof (intro impI allI)\n      fix x y\n      assume gr: \"f x \\<le> y\"\n      thus \"x \\<le> g y\"\n      proof -\n        have lem: \"x \\<le> Inf (g ` {y. x \\<le> g y})\"\n          by (metis (full_types) INF_def INF_greatest mem_Collect_eq)\n\n        also have \"... \\<le> g y\"\n          by (metis (mono_tags) `endo_meet_preserving g \\<and> (\\<forall>y. Inf {x. y \\<le> g x} = f y)` endo_meet_preserving_def f_iso gr isotoneD)\n\n        finally show ?thesis .\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\"\n      by auto\n  qed\nqed\n\n(* Dual theorem *)\nlemma endo_upper_is_mp: \"endo_upper_adjoint g \\<longleftrightarrow> endo_meet_preserving g\"\nproof\n  assume \"endo_upper_adjoint g\" thus \"endo_meet_preserving g\"\n    by (metis endo_upper_preserves_meet)\nnext\n  assume \"endo_meet_preserving g\"\n  moreover hence \"\\<exists>f. \\<forall>x. Inf {y. x \\<le> g y} = f x\"\n    by auto\n  ultimately show \"endo_upper_adjoint g\"\n    by (metis endo_infima_galois endo_upper_adjoint_def)\nqed\n\nend\n\nend\n", "meta": {"author": "Alasdair", "repo": "FM2014", "sha": "967b9a0d1903d90fffba49524cd217dcef8797c5", "save_path": "github-repos/isabelle/Alasdair-FM2014", "path": "github-repos/isabelle/Alasdair-FM2014/FM2014-967b9a0d1903d90fffba49524cd217dcef8797c5/Models/Fixpoint.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7831883734737065}}
{"text": "(*  \n    Title:      Projections.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Projections\\<close>\n\ntheory Projections\nimports \n  Miscellaneous_QR\nbegin\n\nsubsection\\<open>Definitions of vector projection and projection of a vector onto a set.\\<close>\n\ndefinition \"proj v u = (v \\<bullet> u / (u \\<bullet> u)) *\\<^sub>R u\"\n\ndefinition \"proj_onto a S = (sum (\\<lambda>x. proj a x) S)\"\n\nsubsection\\<open>Properties\\<close>\n\nlemma proj_onto_sum_rw: \n  \"sum (\\<lambda>x. (x \\<bullet> v / (x \\<bullet> x)) *\\<^sub>R x) A = sum (\\<lambda>x. (v \\<bullet> x / (x \\<bullet> x)) *\\<^sub>R x) A\"\n  by (rule sum.cong, auto simp add: inner_commute)\n\nlemma vector_sub_project_orthogonal_proj:\n  fixes b x :: \"'a::euclidean_space\"\n  shows \"inner b (x - proj x b) = 0\"\n  using vector_sub_project_orthogonal\n  unfolding proj_def inner_commute[of x b]\n  by auto\n\nlemma orthogonal_proj_set:\n  assumes yC: \"y\\<in>C\" and C: \"finite C\" and p: \"pairwise orthogonal C\"\n  shows \"orthogonal (a - proj_onto a C) y\"\nproof -\n  have Cy: \"C = insert y (C - {y})\" using yC\n    by blast\n  have fth: \"finite (C - {y})\"\n    using C by simp\n  show \"orthogonal (a - proj_onto a C) y\"\n    unfolding orthogonal_def unfolding proj_onto_def unfolding proj_def[abs_def]\n    unfolding inner_diff\n    unfolding inner_sum_left \n    unfolding right_minus_eq\n    unfolding sum.remove[OF C yC]\n    apply (clarsimp simp add: inner_commute[of y a])\n    apply (rule sum.neutral)\n    apply clarsimp\n    apply (rule p[unfolded pairwise_def orthogonal_def, rule_format])\n    using yC by auto\nqed\n\n\nlemma pairwise_orthogonal_proj_set:\n  assumes C: \"finite C\" and p: \"pairwise orthogonal C\"\n  shows \"pairwise orthogonal (insert (a - proj_onto a C) C)\"\n  by (rule pairwise_orthogonal_insert[OF p], auto simp add: orthogonal_proj_set C p)\n\nsubsection\\<open>Orthogonal Complement\\<close>\n\ndefinition \"orthogonal_complement W = {x. \\<forall>y \\<in> W. orthogonal x y}\"\n\nlemma in_orthogonal_complement_imp_orthogonal:\n  assumes x: \"y \\<in> S\"\n  and \"x \\<in> orthogonal_complement S\"\n  shows \"orthogonal x y\" \n  using assms orthogonal_commute \n  unfolding orthogonal_complement_def \n  by blast\n\nlemma subspace_orthogonal_complement: \"subspace (orthogonal_complement W)\"\n  unfolding subspace_def orthogonal_complement_def\n  by (simp add: orthogonal_def inner_left_distrib)\n\nlemma orthogonal_complement_mono:\n  assumes A_in_B: \"A \\<subseteq> B\"\n  shows \"orthogonal_complement B \\<subseteq> orthogonal_complement A\"\nproof\n  fix x assume x: \"x \\<in> orthogonal_complement B\"\n  show \"x \\<in> orthogonal_complement A\" using x unfolding orthogonal_complement_def\n    by (simp add: orthogonal_def, metis A_in_B in_mono)\nqed\n\nlemma B_in_orthogonal_complement_of_orthogonal_complement:\n  shows \"B \\<subseteq> orthogonal_complement (orthogonal_complement B)\"\n  by (auto simp add: orthogonal_complement_def orthogonal_def inner_commute)\n\n\nlemma phytagorean_theorem_norm:\n  assumes o: \"orthogonal x y\"\n  shows \"norm (x+y)^2=norm x^2 + norm y^2\"\nproof -\n  have \"norm (x+y)^2 = (x+y) \\<bullet> (x+y)\" unfolding power2_norm_eq_inner ..\n  also have \"... = ((x+y) \\<bullet> x) + ((x+y) \\<bullet> y)\" unfolding inner_right_distrib ..\n  also have \"... = (x \\<bullet> x) + (x \\<bullet> y) + (y \\<bullet> x) + (y \\<bullet> y) \"\n    unfolding real_inner_class.inner_add_left by simp\n  also have \"... = (x \\<bullet> x) + (y \\<bullet> y)\" using o unfolding orthogonal_def \n    by (metis monoid_add_class.add.right_neutral inner_commute)\n  also have \"... = norm x^2 + norm y^2\" unfolding power2_norm_eq_inner ..\n  finally show ?thesis .\nqed\n\nlemma in_orthogonal_complement_basis:\n  fixes B::\"'a::{euclidean_space} set\"\n  assumes S: \"subspace S\"\n  and ind_B: \"independent B\"\n  and B: \"B \\<subseteq> S\"\n  and span_B: \"S \\<subseteq> span B\"\n  shows \"(v \\<in> orthogonal_complement S) = (\\<forall>a\\<in>B. orthogonal a v)\" \nproof (unfold orthogonal_complement_def, auto)\n  fix a assume \"\\<forall>x\\<in>S. orthogonal v x\" and \"a \\<in> B\"  \n  thus \"orthogonal a v\" \n    by (metis B orthogonal_commute rev_subsetD)\nnext\n  fix x assume o: \"\\<forall>a\\<in>B. orthogonal a v\" and x: \"x \\<in> S\"\n  have finite_B: \"finite B\" using independent_bound_general[OF ind_B] ..\n  have span_B_eq: \"S = span B\" using B S span_B span_subspace by blast\n  obtain f where f: \"(\\<Sum>a\\<in>B. f a *\\<^sub>R a) = x\" using span_finite[OF finite_B]\n    using x unfolding span_B_eq by force\n  have \"v \\<bullet> x = v \\<bullet> (\\<Sum>a\\<in>B. f a *\\<^sub>R a)\" unfolding f ..\n  also have \"... = (\\<Sum>a\\<in>B. v \\<bullet> (f a *\\<^sub>R a))\" unfolding inner_sum_right ..\n  also have \"... = (\\<Sum>a\\<in>B. f a * (v \\<bullet> a))\" unfolding inner_scaleR_right ..\n  also have \"... = 0\" using sum.neutral o by (simp add: orthogonal_def inner_commute)\n  finally show \"orthogonal v x\" unfolding orthogonal_def .\nqed\n\n\ntext\\<open>See @{url \"https://people.math.osu.edu/husen.1/teaching/571/least_squares.pdf\"}\\<close>\n\ntext\\<open>Part 1 of the Theorem 1.7 in the previous website, but the proof has been carried out\n  in other way.\\<close>\n\nlemma v_minus_p_orthogonal_complement:\n  fixes X::\"'a::{euclidean_space} set\"\n  assumes subspace_S: \"subspace S\"\n  and ind_X: \"independent X\"\n  and X: \"X \\<subseteq> S\"\n  and span_X: \"S \\<subseteq> span X\"\n  and o: \"pairwise orthogonal X\"\n  shows \"(v - proj_onto v X) \\<in> orthogonal_complement S\"\n  unfolding in_orthogonal_complement_basis[OF subspace_S ind_X X span_X]\nproof \n  fix a assume a: \"a \\<in> X\"\n  let ?p=\"proj_onto v X\"\n  show \"orthogonal a (v - ?p)\"\n    unfolding orthogonal_commute[of a \"v-?p\"]\n    by (rule orthogonal_proj_set[OF a _ o])\n       (simp add: independent_bound_general[OF ind_X])\nqed\n\ntext\\<open>Part 2 of the Theorem 1.7 in the previous website.\\<close>\n\nlemma UNIV_orthogonal_complement_decomposition:\n  fixes S::\"'a::{euclidean_space} set\"\n  assumes s: \"subspace S\"\n  shows \"UNIV = S + (orthogonal_complement S)\"\nproof (unfold set_plus_def, auto)\n  fix v\n  obtain X where ind_X: \"independent X\"\n    and X: \"X \\<subseteq> S\"\n    and span_X: \"S \\<subseteq> span X\"\n    and o: \"pairwise orthogonal X\"\n    by (metis order_refl orthonormal_basis_subspace s)\n  have finite_X: \"finite X\" by (metis independent_bound_general ind_X)\n  let ?p=\"proj_onto v X\"\n  have \"v=?p +(v-?p)\" by simp\n  moreover have \"?p \\<in> S\" unfolding proj_onto_def proj_def[abs_def]\n    by (rule subspace_sum[OF s])\n      (simp add: X s rev_subsetD subspace_mul)\n  moreover have \"(v-?p) \\<in> orthogonal_complement S\"\n    by (rule v_minus_p_orthogonal_complement[OF s ind_X X span_X o])\n  ultimately show \"\\<exists>a\\<in>S. \\<exists>b\\<in>orthogonal_complement S. v = a + b\" by force\nqed\n\nsubsection\\<open>Normalization of vectors\\<close>\n\ndefinition normalize\n  where \"normalize x  = ((1/norm x) *\\<^sub>R x)\"\ndefinition normalize_set_of_vec\n  where \"normalize_set_of_vec X  = normalize` X\"\n\n\n\nlemma normalize_0: \"(normalize x = 0) = (x = 0)\"\n  unfolding normalize_def by auto\n\nlemma norm_normalize_set_of_vec:\n  assumes \"x \\<noteq> 0\"\n  and \"x \\<in> normalize_set_of_vec X\"\n  shows \"norm x = 1\" \n  using assms norm_normalize normalize_0 unfolding normalize_set_of_vec_def  by blast\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/QR_Decomposition/Projections.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7831883665612683}}
{"text": "(*\n    File:      Liouville_Lambda.thy\n    Author:    Manuel Eberl, TU München\n*)\nsection \\<open>The Liouville $\\lambda$ function\\<close>\ntheory Liouville_Lambda\n  imports \n    \"HOL-Computational_Algebra.Computational_Algebra\"\n    \"HOL-Number_Theory.Number_Theory\"\n    Dirichlet_Series\n    Multiplicative_Function \n    Moebius_Mu\nbegin\n\ndefinition liouville_lambda :: \"nat \\<Rightarrow> 'a :: comm_ring_1\" where\n  \"liouville_lambda n = (if n = 0 then 0 else (-1) ^ size (prime_factorization n))\"\n\ninterpretation liouville_lambda: completely_multiplicative_function' liouville_lambda \"\\<lambda>_. -1\"\nproof\n  fix a b :: nat assume \"a > 1\" \"b > 1\"\n  thus \"liouville_lambda (a * b) = liouville_lambda a * liouville_lambda b\"\n    by (simp add: liouville_lambda_def prime_factorization_mult power_add)\nqed (simp_all add: liouville_lambda_def prime_factorization_prime One_nat_def [symmetric] \n              del: One_nat_def)\n\nlemma liouville_lambda_prime [simp]: \"prime p \\<Longrightarrow> liouville_lambda p = -1\"\n  by (simp add: liouville_lambda_def prime_factorization_prime)\n\nlemma liouville_lambda_prime_power [simp]: \"prime p \\<Longrightarrow> liouville_lambda (p ^ k) = (-1) ^ k\"\n  by (simp add: liouville_lambda_def prime_factorization_prime_power)\n\nlemma liouville_lambda_squarefree: \"squarefree n \\<Longrightarrow> liouville_lambda n = moebius_mu n\"\n  by (auto simp: liouville_lambda_def moebius_mu_squarefree_eq' intro!: Nat.gr0I)\n\nlemma power_neg_one_If: \"(-1) ^ n = (if even n then 1 else -1 :: 'a :: ring_1)\"\n  by (induction n) (simp_all split: if_splits)\n\nlemma liouville_lambda_power_even: \n  \"n > 0 \\<Longrightarrow> even m \\<Longrightarrow> liouville_lambda (n ^ m) = 1\"\n  by (subst liouville_lambda.power) (auto elim!: evenE simp: liouville_lambda_def power_neg_one_If)\n\nlemma liouville_lambda_power_odd: \n  \"odd m \\<Longrightarrow> liouville_lambda (n ^ m) = liouville_lambda n\"\n  by (subst liouville_lambda.power) (auto elim!: oddE simp: liouville_lambda_def power_neg_one_If)\n    \nlemma liouville_lambda_power:\n  \"liouville_lambda (n ^ m) = \n     (if n = 0 \\<and> m > 0 then 0 else if even m then 1 else liouville_lambda n)\"\n  by (auto simp: liouville_lambda_power_even liouville_lambda_power_odd power_0_left)\n                                      \ninterpretation squarefree: multiplicative_function' \n  \"ind squarefree\" \"\\<lambda>p k. if k > 1 then 0 else 1\" \"\\<lambda>_. 1\"\nproof\n  fix p k :: nat assume \"prime p\" \"k > 0\"\n  thus \"ind squarefree (p ^ k) = (if 1 < k then 0 else 1 :: 'a)\"\n    by (cases \"k = 1\") (auto simp: squarefree_power_iff squarefree_prime ind_def)\nqed (auto simp: squarefree_mult_coprime squarefree_power_iff ind_def dest: squarefree_multD \n          simp del: One_nat_def)\n        \n\ninterpretation is_nth_power: multiplicative_function \"ind (is_nth_power n)\"\n  by standard (auto simp: is_nth_power_mult_coprime_nat_iff)\n\ninterpretation is_nth_power: multiplicative_function' \n  \"ind (is_nth_power n)\" \"\\<lambda>p k. if n dvd k then 1 else 0\" \"\\<lambda>_. if n = 1 then 1 else 0\"\n  by standard (simp_all add: is_nth_power_prime_power_nat_iff ind_def)\n\ninterpretation is_square: multiplicative_function \"ind is_square\"\n  by standard (auto simp: is_nth_power_mult_coprime_nat_iff)\n\ninterpretation is_square: multiplicative_function' \n  \"ind is_square\" \"\\<lambda>p k. if even k then 1 else 0\" \"\\<lambda>_. 0\"\n  by standard (simp_all add: is_nth_power_prime_power_nat_iff ind_def)\n\n\nlemma liouville_lambda_divisors_sum:\n  \"(\\<Sum>d | d dvd n. liouville_lambda d) = ind is_square n\"\nproof (rule multiplicative_function_eqI)\n  show \"multiplicative_function (\\<lambda>n. (\\<Sum>d | d dvd n. liouville_lambda d))\"\n    by (rule liouville_lambda.multiplicative_sum_divisors)\n  show \"multiplicative_function (ind is_square)\"\n    by (rule is_nth_power.multiplicative_function_axioms)\nnext\n  fix p k :: nat assume pk: \"prime p\" \"k > 0\"\n  hence p_gt_1: \"p > 1\" by (simp add: prime_gt_Suc_0_nat)\n  have \"(\\<Sum>d | d dvd p ^ k. liouville_lambda d) = (\\<Sum>d\\<in>(\\<lambda>i. p ^ i) ` {..k}. liouville_lambda d)\"\n    using pk by (intro sum.cong refl) (auto intro: le_imp_power_dvd simp: divides_primepow_nat)\n  also from pk and p_gt_1 have \"\\<dots> = (\\<Sum>i\\<le>k. liouville_lambda (p ^ i))\"\n    by (subst sum.reindex) (auto simp: inj_on_def prime_gt_1_nat)\n  also from pk have \"\\<dots> = (\\<Sum>i\\<le>k. (-1) ^ i)\" by (intro sum.cong refl) simp\n  also have \"\\<dots> = (if even k then 1 else 0)\" by (induction k) auto\n  also from pk have \"\\<dots> = ind is_square (p ^ k)\" by (simp add: is_square.prime_power)\n  finally show \"(\\<Sum>d | d dvd p ^ k. liouville_lambda d) = ind is_square (p ^ k)\" .\nqed\n\nlemma fds_liouville_lambda_times_zeta: \"fds liouville_lambda * fds_zeta = fds_ind is_square\"\n  by (rule fds_eqI) (simp add: liouville_lambda_divisors_sum fds_nth_mult dirichlet_prod_def)\n\nlemma fds_liouville_lambda: \"fds liouville_lambda = fds_ind is_square * fds moebius_mu\"\nproof -\n  have \"fds liouville_lambda * fds_zeta * fds moebius_mu = fds_ind is_square * fds moebius_mu\"\n    by (simp add: fds_liouville_lambda_times_zeta)\n  also have \"fds liouville_lambda * fds_zeta * fds moebius_mu = fds liouville_lambda\"\n    by (simp only: mult.assoc fds_zeta_times_moebius_mu mult_1_right)\n  finally show ?thesis .\nqed\n\nlemma liouville_lambda_altdef:\n  \"liouville_lambda n = (\\<Sum>d | d ^ 2 dvd n. moebius_mu (n div d ^ 2))\"\nproof (cases \"n = 0\")\n  case False\n  have \"liouville_lambda n = fds_nth (fds liouville_lambda) n\" by (simp add: fds_nth_fds)\n  also have \"fds liouville_lambda = fds_ind is_square * (fds moebius_mu :: 'a fds)\" \n    by (rule fds_liouville_lambda)\n  also have \"fds_nth \\<dots> n = (\\<Sum>d | d dvd n. ind is_square d * moebius_mu (n div d))\"\n    by (simp add: fds_nth_mult dirichlet_prod_def)\n  also have \"\\<dots> = (\\<Sum>d \\<in> (\\<lambda>d. d^2) ` {d. d ^ 2 dvd n}. moebius_mu (n div d))\" using False\n    by (intro sum.mono_neutral_cong_right) (auto simp: ind_def is_nth_power_def)\n  also have \"\\<dots> = (\\<Sum>d | d ^ 2 dvd n. moebius_mu (n div d ^ 2))\"\n    by (subst sum.reindex) (auto simp: inj_on_def dest: power2_eq_imp_eq)\n  finally show ?thesis .\nqed auto\n\nlemma abs_moebius_mu: \"abs (moebius_mu n :: 'a :: linordered_idom) = ind squarefree n\"\n  by (auto simp: ind_def moebius_mu_def)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Dirichlet_Series/Liouville_Lambda.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.7831021289432183}}
{"text": "section \\<open>Ranks, $k$ smallest element and elements\\<close>\n\ntheory K_Smallest\n  imports \n    Frequency_Moments_Preliminary_Results\n    Interpolation_Polynomials_HOL_Algebra.Interpolation_Polynomial_Cardinalities\nbegin\n\ntext \\<open>This section contains definitions and results for the selection of the $k$ smallest elements, the $k$-th smallest element, rank of an element in an ordered set.\\<close>\n\ndefinition rank_of :: \"'a :: linorder \\<Rightarrow> 'a set \\<Rightarrow> nat\" where \"rank_of x S = card {y \\<in> S. y < x}\"  \ntext \\<open>The function @{term \"rank_of\"} returns the rank of an element within a set.\\<close>\n\nlemma rank_mono:\n  assumes \"finite S\"\n  shows \"x \\<le> y \\<Longrightarrow> rank_of x S \\<le> rank_of y S\"\n  unfolding rank_of_def using assms by (intro card_mono, auto)\n\nlemma rank_mono_2:\n  assumes \"finite S\"\n  shows \"S' \\<subseteq> S \\<Longrightarrow> rank_of x S' \\<le> rank_of x S\"\n  unfolding rank_of_def using assms by (intro card_mono, auto)\n\nlemma rank_mono_commute:\n  assumes \"finite S\"\n  assumes \"S \\<subseteq> T\"\n  assumes \"strict_mono_on T f\"\n  assumes \"x \\<in> T\"\n  shows \"rank_of x S = rank_of (f x) (f ` S)\"\nproof -\n  have a: \"inj_on f T\"\n    by (metis assms(3) strict_mono_on_imp_inj_on)\n\n  have \"rank_of (f x) (f ` S) = card (f ` {y \\<in> S. f y < f x})\"\n    unfolding rank_of_def by (intro arg_cong[where f=\"card\"], auto)\n  also have \"... = card (f ` {y \\<in> S. y < x})\"\n    using assms by (intro arg_cong[where f=\"card\"] arg_cong[where f=\"(`) f\"])\n     (meson in_mono linorder_not_le strict_mono_onD strict_mono_on_leD set_eq_iff)\n  also have \"... = card {y \\<in> S. y < x}\"\n    using assms by (intro card_image  inj_on_subset[OF a], blast)\n  also have \"... = rank_of x S\"\n    by (simp add:rank_of_def)\n  finally show ?thesis\n    by simp\nqed\n\ndefinition least where \"least k S = {y \\<in> S. rank_of y S < k}\"\ntext \\<open>The function @{term \"least\"} returns the k smallest elements of a finite set.\\<close>\n\nlemma rank_strict_mono: \n  assumes \"finite S\"\n  shows \"strict_mono_on S (\\<lambda>x. rank_of x S)\"\nproof -\n  have \"\\<And>x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> x < y \\<Longrightarrow> rank_of x S < rank_of y S\"\n    unfolding rank_of_def using assms \n    by (intro psubset_card_mono, auto)\n\n  thus ?thesis\n    by (simp add:rank_of_def strict_mono_on_def)\nqed\n\nlemma rank_of_image:\n  assumes \"finite S\"\n  shows \"(\\<lambda>x. rank_of x S) ` S = {0..<card S}\"\nproof (rule card_seteq)\n  show \"finite {0..<card S}\" by simp\n\n  have \"\\<And>x. x \\<in> S \\<Longrightarrow> card {y \\<in> S. y < x} < card S\"\n    by (rule psubset_card_mono, metis assms, blast)\n  thus \"(\\<lambda>x. rank_of x S) ` S \\<subseteq> {0..<card S}\"\n    by (intro image_subsetI, simp add:rank_of_def)\n\n  have \"inj_on (\\<lambda>x. rank_of x S) S\"\n    by (metis strict_mono_on_imp_inj_on rank_strict_mono assms) \n  thus \"card {0..<card S} \\<le> card ((\\<lambda>x. rank_of x S) ` S)\"\n    by (simp add:card_image)\nqed\n\nlemma card_least:\n  assumes \"finite S\"\n  shows \"card (least k S) = min k (card S)\"\nproof (cases \"card S < k\")\n  case True\n  have \"\\<And>t. rank_of t S \\<le> card S\" \n    unfolding rank_of_def using assms \n    by (intro card_mono, auto)\n  hence \"\\<And>t. rank_of t S < k\" \n    by (metis True not_less_iff_gr_or_eq order_less_le_trans)\n  hence \"least k S = S\"\n    by (simp add:least_def)\n  then show ?thesis using True by simp\nnext\n  case False\n  hence a:\"card S \\<ge> k\" using leI by blast\n  hence \"card ((\\<lambda>x. rank_of x S) -` {0..<k} \\<inter> S) = card {0..<k}\"\n    using assms\n    by (intro card_vimage_inj_on strict_mono_on_imp_inj_on rank_strict_mono)\n     (simp_all add: rank_of_image)\n  hence \"card (least k S) = k\"\n    by (simp add: Collect_conj_eq Int_commute least_def vimage_def)\n  then show ?thesis using a by linarith\nqed\n\nlemma least_subset: \"least k S \\<subseteq> S\"\n  by (simp add:least_def)\n\nlemma least_mono_commute:\n  assumes \"finite S\"\n  assumes \"strict_mono_on S f\"\n  shows \"f ` least k S = least k (f ` S)\"\nproof -\n  have a:\"inj_on f S\" \n    using strict_mono_on_imp_inj_on[OF assms(2)] by simp\n\n  have \"card (least k (f ` S)) = min k (card (f ` S))\"\n    by (subst card_least, auto simp add:assms)\n  also have \"... = min k (card S)\"\n    by (subst card_image, metis a, auto)\n  also have \"... = card (least k S)\"\n    by (subst card_least, auto simp add:assms)\n  also have \"... = card (f ` least k S)\"\n    by (subst card_image[OF inj_on_subset[OF a]], simp_all add:least_def)\n  finally have b: \"card (least k (f ` S)) \\<le> card (f ` least k S)\" by simp\n\n  have c: \"f ` least k S \\<subseteq>least k (f ` S)\"\n    using assms by (intro image_subsetI) \n      (simp add:least_def rank_mono_commute[symmetric, where T=\"S\"])\n\n  show ?thesis\n    using b c assms by (intro card_seteq, simp_all add:least_def)\nqed\n\nlemma least_eq_iff:\n  assumes \"finite B\"\n  assumes \"A \\<subseteq> B\"\n  assumes \"\\<And>x. x \\<in> B \\<Longrightarrow> rank_of x B < k \\<Longrightarrow> x \\<in> A\"\n  shows \"least k A = least k B\"\nproof -\n  have \"least k B \\<subseteq> least k A\"\n    using assms rank_mono_2[OF assms(1,2)] order_le_less_trans\n    by (simp add:least_def, blast) \n  moreover have \"card (least k B) \\<ge> card (least k A)\"\n    using assms finite_subset[OF assms(2,1)] card_mono[OF assms(1,2)]\n    by (simp add: card_least min_le_iff_disj)\n  moreover have \"finite (least k A)\" \n    using finite_subset least_subset assms(1,2) by metis\n  ultimately show ?thesis\n    by (intro card_seteq[symmetric], simp_all)\nqed\n\nlemma least_insert: \n  assumes \"finite S\"\n  shows \"least k (insert x (least k S)) = least k (insert x S)\" (is \"?lhs = ?rhs\")\nproof (rule least_eq_iff)\n  show \"finite (insert x S)\"\n    using assms(1) by simp\n  show \"insert x (least k S) \\<subseteq> insert x S\"\n    using least_subset by blast\n  show \"y \\<in> insert x (least k S)\" if a: \"y \\<in> insert x S\" and b: \"rank_of y (insert x S) < k\" for y\n  proof -\n    have \"rank_of y S \\<le> rank_of y (insert x S)\"\n      using assms by (intro rank_mono_2, auto)\n    also have \"... < k\" using b by simp\n    finally have \"rank_of y S < k\" by simp\n    hence \"y = x \\<or> (y \\<in> S \\<and> rank_of y S < k)\" \n      using a by simp\n    thus ?thesis by (simp add:least_def)\n  qed\nqed\n\n\ndefinition count_le where \"count_le x M = size {#y \\<in># M. y \\<le> x#}\"\ndefinition count_less where \"count_less x M = size {#y \\<in># M. y < x#}\"\n\ndefinition nth_mset :: \"nat \\<Rightarrow> ('a :: linorder) multiset \\<Rightarrow> 'a\" where\n  \"nth_mset k M = sorted_list_of_multiset M ! k\"\n\nlemma nth_mset_bound_left:\n  assumes \"k < size M\"\n  assumes \"count_less x M \\<le> k\"\n  shows \"x \\<le> nth_mset k M\"\nproof (rule ccontr)\n  define xs where \"xs = sorted_list_of_multiset M\"\n  have s_xs: \"sorted xs\" by (simp add:xs_def sorted_sorted_list_of_multiset)\n  have l_xs: \"k < length xs\"\n    using  assms(1) by (simp add:xs_def size_mset[symmetric]) \n  have M_xs: \"M = mset xs\" by (simp add:xs_def)\n  hence a:\"\\<And>i. i \\<le> k \\<Longrightarrow> xs ! i \\<le> xs ! k\"\n    using s_xs l_xs sorted_iff_nth_mono by blast\n\n  assume \"\\<not>(x \\<le> nth_mset k M)\"\n  hence \"x > nth_mset k M\" by simp\n  hence b:\"x > xs ! k\" by (simp add:nth_mset_def xs_def[symmetric])\n\n  have \"k < card {0..k}\" by simp\n  also have \"... \\<le> card {i. i < length xs \\<and> xs ! i < x}\"\n    using a b l_xs order_le_less_trans \n    by (intro card_mono subsetI) auto\n  also have \"... = length (filter (\\<lambda>y. y < x) xs)\"\n    by (subst length_filter_conv_card, simp)\n  also have \"... = size (mset (filter (\\<lambda>y. y < x) xs))\"\n    by (subst size_mset, simp)\n  also have \"... = count_less x M\"\n    by (simp add:count_less_def M_xs)\n  also have \"... \\<le> k\"\n    using assms by simp\n  finally show \"False\" by simp\nqed\n\nlemma nth_mset_bound_left_excl:\n  assumes \"k < size M\"\n  assumes \"count_le x M \\<le> k\"\n  shows \"x < nth_mset k M\"\nproof (rule ccontr)\n  define xs where \"xs = sorted_list_of_multiset M\"\n  have s_xs: \"sorted xs\" by (simp add:xs_def sorted_sorted_list_of_multiset)\n  have l_xs: \"k < length xs\" \n    using  assms(1) by (simp add:xs_def size_mset[symmetric]) \n  have M_xs: \"M = mset xs\" by (simp add:xs_def)\n  hence a:\"\\<And>i. i \\<le> k \\<Longrightarrow> xs ! i \\<le> xs ! k\"\n    using s_xs l_xs sorted_iff_nth_mono by blast\n\n  assume \"\\<not>(x < nth_mset k M)\"\n  hence \"x \\<ge> nth_mset k M\" by simp\n  hence b:\"x \\<ge> xs ! k\" by (simp add:nth_mset_def xs_def[symmetric])\n\n  have \"k+1 \\<le> card {0..k}\" by simp\n  also have \"... \\<le> card {i. i < length xs \\<and> xs ! i \\<le> xs ! k}\"\n    using a b l_xs order_le_less_trans\n    by (intro card_mono subsetI, auto)\n  also have \"... \\<le> card {i. i < length xs \\<and> xs ! i \\<le> x}\"\n    using b by (intro card_mono subsetI, auto)\n  also have \"... = length (filter (\\<lambda>y. y \\<le> x) xs)\"\n    by (subst length_filter_conv_card, simp)\n  also have \"... = size (mset (filter (\\<lambda>y. y \\<le> x) xs))\"\n    by (subst size_mset, simp)\n  also have \"... = count_le x M\"\n    by (simp add:count_le_def M_xs)\n  also have \"... \\<le> k\"\n    using assms by simp\n  finally show \"False\" by simp\nqed\n\nlemma nth_mset_bound_right:\n  assumes \"k < size M\"\n  assumes \"count_le x M > k\"\n  shows \"nth_mset k M \\<le> x\"\nproof (rule ccontr)\n  define xs where \"xs = sorted_list_of_multiset M\"\n  have s_xs: \"sorted xs\" by (simp add:xs_def sorted_sorted_list_of_multiset)\n  have l_xs: \"k < length xs\" \n    using  assms(1) by (simp add:xs_def size_mset[symmetric]) \n  have M_xs: \"M = mset xs\" by (simp add:xs_def)\n\n  assume \"\\<not>(nth_mset k M \\<le> x)\"\n  hence \"x < nth_mset k M\" by simp\n  hence \"x < xs ! k\" \n    by (simp add:nth_mset_def xs_def[symmetric])\n  hence a:\"\\<And>i. i < length xs \\<and> xs ! i \\<le> x \\<Longrightarrow> i < k\"\n    using s_xs l_xs sorted_iff_nth_mono leI by fastforce\n  have \"count_le x M = size (mset (filter (\\<lambda>y. y \\<le> x) xs))\"\n    by (simp add:count_le_def M_xs)\n  also have \"... = length (filter (\\<lambda>y. y \\<le> x) xs)\"\n    by (subst size_mset, simp)\n  also have \"... = card {i. i < length xs \\<and> xs ! i \\<le> x}\"\n    by (subst length_filter_conv_card, simp)\n  also have \"... \\<le> card {i. i < k}\"\n    using a by (intro card_mono subsetI, auto)\n  also have \"... = k\" by simp\n  finally have \"count_le x M \\<le> k\" by simp\n  thus \"False\" using assms by simp\nqed\n\nlemma nth_mset_commute_mono:\n  assumes \"mono f\"\n  assumes \"k < size M\"\n  shows \"f (nth_mset k M) = nth_mset k (image_mset f M)\"\nproof -\n  have a:\"k < length (sorted_list_of_multiset M)\"\n    by (metis assms(2) mset_sorted_list_of_multiset size_mset)\n  show ?thesis\n    using a by (simp add:nth_mset_def sorted_list_of_multiset_image_commute[OF assms(1)])\nqed \n\nlemma nth_mset_max: \n  assumes \"size A > k\"\n  assumes \"\\<And>x. x \\<le> nth_mset k A \\<Longrightarrow> count A x \\<le> 1\"\n  shows \"nth_mset k A = Max (least (k+1) (set_mset A))\" and \"card (least (k+1) (set_mset A)) = k+1\"\nproof -\n  define xs where \"xs = sorted_list_of_multiset A\"\n  have k_bound: \"k < length xs\" unfolding xs_def\n    by (metis size_mset mset_sorted_list_of_multiset assms(1))  \n\n  have A_def: \"A = mset xs\" by (simp add:xs_def)\n  have s_xs: \"sorted xs\" by (simp add:xs_def sorted_sorted_list_of_multiset)\n  have \"\\<And>x. x \\<le> xs ! k \\<Longrightarrow> count A x \\<le> Suc 0\"\n    using assms(2) by (simp add:xs_def[symmetric] nth_mset_def)\n  hence no_col: \"\\<And>x. x \\<le> xs ! k \\<Longrightarrow> count_list xs x \\<le> 1\" \n    by (simp add:A_def count_mset) \n\n  have inj_xs: \"inj_on (\\<lambda>k. xs ! k) {0..k}\"\n    by (rule inj_onI, simp) (metis (full_types) count_list_ge_2_iff k_bound no_col\n        le_neq_implies_less linorder_not_le order_le_less_trans s_xs sorted_iff_nth_mono)\n\n  have \"\\<And>y. y < length xs \\<Longrightarrow> rank_of (xs ! y) (set xs) < k+1 \\<Longrightarrow> y < k+1\"\n  proof (rule ccontr)\n    fix y\n    assume b:\"y < length xs\"\n    assume \"\\<not>y < k +1\"\n    hence a:\"k + 1 \\<le> y\" by simp\n\n    have d:\"Suc k < length xs\" using a b by simp\n\n    have \"k+1 = card ((!) xs ` {0..k})\" \n      by (subst card_image[OF inj_xs], simp)\n    also have \"... \\<le> rank_of (xs ! (k+1)) (set xs)\"\n      unfolding rank_of_def using k_bound\n      by (intro card_mono image_subsetI conjI, simp_all) (metis count_list_ge_2_iff no_col not_le le_imp_less_Suc s_xs \n          sorted_iff_nth_mono d order_less_le)\n    also have \"... \\<le> rank_of (xs ! y) (set xs)\"\n      unfolding rank_of_def\n      by (intro card_mono subsetI, simp_all)\n       (metis Suc_eq_plus1 a b s_xs order_less_le_trans sorted_iff_nth_mono)\n    also assume \"... < k+1\"\n    finally show \"False\" by force\n  qed\n\n  moreover have \"rank_of (xs ! y) (set xs) < k+1\" if a:\"y < k + 1\" for y\n  proof -\n    have \"rank_of (xs ! y) (set xs) \\<le> card ((\\<lambda>k. xs ! k) ` {k. k < length xs \\<and> xs ! k < xs ! y})\"\n      unfolding rank_of_def\n      by (intro card_mono subsetI, simp)\n       (metis (no_types, lifting) imageI in_set_conv_nth mem_Collect_eq)\n    also have \"... \\<le> card {k. k < length xs \\<and> xs ! k < xs ! y}\"\n      by (rule card_image_le, simp)\n    also have \"... \\<le> card {k. k < y}\"\n      by (intro card_mono subsetI, simp_all add:not_less)\n       (metis sorted_iff_nth_mono s_xs linorder_not_less)\n    also have \"... = y\" by simp\n    also have \"... < k + 1\" using a by simp\n    finally show \"rank_of (xs ! y) (set xs) < k+1\" by simp\n  qed\n\n  ultimately have rank_conv: \"\\<And>y. y < length xs \\<Longrightarrow> rank_of (xs ! y) (set xs) < k+1 \\<longleftrightarrow> y < k+1\"\n    by blast\n\n  have \"y \\<le> xs ! k\"  if a:\"y \\<in> least (k+1) (set xs)\"  for y\n  proof -\n    have \"y \\<in> set xs\" using a least_subset by blast\n    then obtain i where i_bound: \"i < length xs\" and y_def: \"y = xs ! i\" using in_set_conv_nth by metis\n    hence \"rank_of (xs ! i) (set xs) < k+1\"\n      using a y_def i_bound by (simp add: least_def)\n    hence \"i < k+1\"\n      using rank_conv i_bound by blast\n    hence \"i \\<le> k\" by linarith\n    hence \"xs ! i \\<le> xs ! k\"\n      using s_xs i_bound k_bound sorted_nth_mono by blast\n    thus \"y \\<le> xs ! k\" using y_def by simp\n  qed\n\n  moreover have \"xs ! k \\<in> least (k+1) (set xs)\"\n    using k_bound rank_conv by (simp add:least_def)\n\n  ultimately have \"Max (least (k+1) (set xs)) = xs ! k\"\n    by (intro Max_eqI finite_subset[OF least_subset], auto)\n\n  hence \"nth_mset k A = Max (K_Smallest.least (Suc k) (set xs))\" \n    by (simp add:nth_mset_def xs_def[symmetric])\n  also have \"... = Max (least (k+1) (set_mset A))\"\n    by (simp add:A_def)\n  finally show \"nth_mset k A = Max (least (k+1) (set_mset A))\"  by simp\n\n  have \"k + 1 = card ((\\<lambda>i. xs ! i) ` {0..k})\" \n    by (subst card_image[OF inj_xs], simp) \n  also have \"... \\<le> card (least (k+1) (set xs))\"\n    using rank_conv k_bound\n    by (intro card_mono image_subsetI finite_subset[OF least_subset], simp_all add:least_def)\n  finally have \"card (least (k+1) (set xs)) \\<ge> k+1\" by simp\n  moreover have \"card (least (k+1) (set xs)) \\<le> k+1\"\n    by (subst card_least, simp, simp)\n  ultimately have \"card (least (k+1) (set xs)) = k+1\" by simp\n  thus \"card (least (k+1) (set_mset A)) = k+1\"  by (simp add:A_def)\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Frequency_Moments/K_Smallest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8723473630627235, "lm_q1q2_score": 0.7831021256788935}}
{"text": "(*  Title:      HOL/Int.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Author:     Tobias Nipkow, Florian Haftmann, TU Muenchen\n*)\n\nsection {* The Integers as Equivalence Classes over Pairs of Natural Numbers *} \n\ntheory Int\nimports Equiv_Relations Power Quotient Fun_Def\nbegin\n\nsubsection {* Definition of integers as a quotient type *}\n\ndefinition intrel :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> bool\" where\n  \"intrel = (\\<lambda>(x, y) (u, v). x + v = u + y)\"\n\nlemma intrel_iff [simp]: \"intrel (x, y) (u, v) \\<longleftrightarrow> x + v = u + y\"\n  by (simp add: intrel_def)\n\nquotient_type int = \"nat \\<times> nat\" / \"intrel\"\n  morphisms Rep_Integ Abs_Integ\nproof (rule equivpI)\n  show \"reflp intrel\"\n    unfolding reflp_def by auto\n  show \"symp intrel\"\n    unfolding symp_def by auto\n  show \"transp intrel\"\n    unfolding transp_def by auto\nqed\n\nlemma eq_Abs_Integ [case_names Abs_Integ, cases type: int]:\n     \"(!!x y. z = Abs_Integ (x, y) ==> P) ==> P\"\nby (induct z) auto\n\nsubsection {* Integers form a commutative ring *}\n\ninstantiation int :: comm_ring_1\nbegin\n\nlift_definition zero_int :: \"int\" is \"(0, 0)\" .\n\nlift_definition one_int :: \"int\" is \"(1, 0)\" .\n\nlift_definition plus_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y) (u, v). (x + u, y + v)\"\n  by clarsimp\n\nlift_definition uminus_int :: \"int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y). (y, x)\"\n  by clarsimp\n\nlift_definition minus_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y) (u, v). (x + v, y + u)\"\n  by clarsimp\n\nlift_definition times_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  is \"\\<lambda>(x, y) (u, v). (x*u + y*v, x*v + y*u)\"\nproof (clarsimp)\n  fix s t u v w x y z :: nat\n  assume \"s + v = u + t\" and \"w + z = y + x\"\n  hence \"(s + v) * w + (u + t) * x + u * (w + z) + v * (y + x)\n       = (u + t) * w + (s + v) * x + u * (y + x) + v * (w + z)\"\n    by simp\n  thus \"(s * w + t * x) + (u * z + v * y) = (u * y + v * z) + (s * x + t * w)\"\n    by (simp add: algebra_simps)\nqed\n\ninstance\n  by default (transfer, clarsimp simp: algebra_simps)+\n\nend\n\nabbreviation int :: \"nat \\<Rightarrow> int\" where\n  \"int \\<equiv> of_nat\"\n\nlemma int_def: \"int n = Abs_Integ (n, 0)\"\n  by (induct n, simp add: zero_int.abs_eq,\n    simp add: one_int.abs_eq plus_int.abs_eq)\n\nlemma int_transfer [transfer_rule]:\n  \"(rel_fun (op =) pcr_int) (\\<lambda>n. (n, 0)) int\"\n  unfolding rel_fun_def int.pcr_cr_eq cr_int_def int_def by simp\n\nlemma int_diff_cases:\n  obtains (diff) m n where \"z = int m - int n\"\n  by transfer clarsimp\n\nsubsection {* Integers are totally ordered *}\n\ninstantiation int :: linorder\nbegin\n\nlift_definition less_eq_int :: \"int \\<Rightarrow> int \\<Rightarrow> bool\"\n  is \"\\<lambda>(x, y) (u, v). x + v \\<le> u + y\"\n  by auto\n\nlift_definition less_int :: \"int \\<Rightarrow> int \\<Rightarrow> bool\"\n  is \"\\<lambda>(x, y) (u, v). x + v < u + y\"\n  by auto\n\ninstance\n  by default (transfer, force)+\n\nend\n\ninstantiation int :: distrib_lattice\nbegin\n\ndefinition\n  \"(inf \\<Colon> int \\<Rightarrow> int \\<Rightarrow> int) = min\"\n\ndefinition\n  \"(sup \\<Colon> int \\<Rightarrow> int \\<Rightarrow> int) = max\"\n\ninstance\n  by intro_classes\n    (auto simp add: inf_int_def sup_int_def max_min_distrib2)\n\nend\n\nsubsection {* Ordering properties of arithmetic operations *}\n\ninstance int :: ordered_cancel_ab_semigroup_add\nproof\n  fix i j k :: int\n  show \"i \\<le> j \\<Longrightarrow> k + i \\<le> k + j\"\n    by transfer clarsimp\nqed\n\ntext{*Strict Monotonicity of Multiplication*}\n\ntext{*strict, in 1st argument; proof is by induction on k>0*}\nlemma zmult_zless_mono2_lemma:\n     \"(i::int)<j ==> 0<k ==> int k * i < int k * j\"\napply (induct k)\napply simp\napply (simp add: distrib_right)\napply (case_tac \"k=0\")\napply (simp_all add: add_strict_mono)\ndone\n\nlemma zero_le_imp_eq_int: \"(0::int) \\<le> k ==> \\<exists>n. k = int n\"\napply transfer\napply clarsimp\napply (rule_tac x=\"a - b\" in exI, simp)\ndone\n\nlemma zero_less_imp_eq_int: \"(0::int) < k ==> \\<exists>n>0. k = int n\"\napply transfer\napply clarsimp\napply (rule_tac x=\"a - b\" in exI, simp)\ndone\n\nlemma zmult_zless_mono2: \"[| i<j;  (0::int) < k |] ==> k*i < k*j\"\napply (drule zero_less_imp_eq_int)\napply (auto simp add: zmult_zless_mono2_lemma)\ndone\n\ntext{*The integers form an ordered integral domain*}\ninstantiation int :: linordered_idom\nbegin\n\ndefinition\n  zabs_def: \"\\<bar>i\\<Colon>int\\<bar> = (if i < 0 then - i else i)\"\n\ndefinition\n  zsgn_def: \"sgn (i\\<Colon>int) = (if i=0 then 0 else if 0<i then 1 else - 1)\"\n\ninstance proof\n  fix i j k :: int\n  show \"i < j \\<Longrightarrow> 0 < k \\<Longrightarrow> k * i < k * j\"\n    by (rule zmult_zless_mono2)\n  show \"\\<bar>i\\<bar> = (if i < 0 then -i else i)\"\n    by (simp only: zabs_def)\n  show \"sgn (i\\<Colon>int) = (if i=0 then 0 else if 0<i then 1 else - 1)\"\n    by (simp only: zsgn_def)\nqed\n\nend\n\nlemma zless_imp_add1_zle: \"w < z \\<Longrightarrow> w + (1\\<Colon>int) \\<le> z\"\n  by transfer clarsimp\n\nlemma zless_iff_Suc_zadd:\n  \"(w \\<Colon> int) < z \\<longleftrightarrow> (\\<exists>n. z = w + int (Suc n))\"\napply transfer\napply auto\napply (rename_tac a b c d)\napply (rule_tac x=\"c+b - Suc(a+d)\" in exI)\napply arith\ndone\n\nlemmas int_distrib =\n  distrib_right [of z1 z2 w]\n  distrib_left [of w z1 z2]\n  left_diff_distrib [of z1 z2 w]\n  right_diff_distrib [of w z1 z2]\n  for z1 z2 w :: int\n\n\nsubsection {* Embedding of the Integers into any @{text ring_1}: @{text of_int}*}\n\ncontext ring_1\nbegin\n\nlift_definition of_int :: \"int \\<Rightarrow> 'a\" is \"\\<lambda>(i, j). of_nat i - of_nat j\"\n  by (clarsimp simp add: diff_eq_eq eq_diff_eq diff_add_eq\n    of_nat_add [symmetric] simp del: of_nat_add)\n\nlemma of_int_0 [simp]: \"of_int 0 = 0\"\n  by transfer simp\n\nlemma of_int_1 [simp]: \"of_int 1 = 1\"\n  by transfer simp\n\nlemma of_int_add [simp]: \"of_int (w+z) = of_int w + of_int z\"\n  by transfer (clarsimp simp add: algebra_simps)\n\nlemma of_int_minus [simp]: \"of_int (-z) = - (of_int z)\"\n  by (transfer fixing: uminus) clarsimp\n\nlemma of_int_diff [simp]: \"of_int (w - z) = of_int w - of_int z\"\n  using of_int_add [of w \"- z\"] by simp\n\nlemma of_int_mult [simp]: \"of_int (w*z) = of_int w * of_int z\"\n  by (transfer fixing: times) (clarsimp simp add: algebra_simps of_nat_mult)\n\ntext{*Collapse nested embeddings*}\nlemma of_int_of_nat_eq [simp]: \"of_int (int n) = of_nat n\"\nby (induct n) auto\n\nlemma of_int_numeral [simp, code_post]: \"of_int (numeral k) = numeral k\"\n  by (simp add: of_nat_numeral [symmetric] of_int_of_nat_eq [symmetric])\n\nlemma of_int_neg_numeral [code_post]: \"of_int (- numeral k) = - numeral k\"\n  by simp\n\nlemma of_int_power:\n  \"of_int (z ^ n) = of_int z ^ n\"\n  by (induct n) simp_all\n\nend\n\ncontext ring_char_0\nbegin\n\nlemma of_int_eq_iff [simp]:\n   \"of_int w = of_int z \\<longleftrightarrow> w = z\"\n  by transfer (clarsimp simp add: algebra_simps\n    of_nat_add [symmetric] simp del: of_nat_add)\n\ntext{*Special cases where either operand is zero*}\nlemma of_int_eq_0_iff [simp]:\n  \"of_int z = 0 \\<longleftrightarrow> z = 0\"\n  using of_int_eq_iff [of z 0] by simp\n\nlemma of_int_0_eq_iff [simp]:\n  \"0 = of_int z \\<longleftrightarrow> z = 0\"\n  using of_int_eq_iff [of 0 z] by simp\n\nend\n\ncontext linordered_idom\nbegin\n\ntext{*Every @{text linordered_idom} has characteristic zero.*}\nsubclass ring_char_0 ..\n\nlemma of_int_le_iff [simp]:\n  \"of_int w \\<le> of_int z \\<longleftrightarrow> w \\<le> z\"\n  by (transfer fixing: less_eq) (clarsimp simp add: algebra_simps\n    of_nat_add [symmetric] simp del: of_nat_add)\n\nlemma of_int_less_iff [simp]:\n  \"of_int w < of_int z \\<longleftrightarrow> w < z\"\n  by (simp add: less_le order_less_le)\n\nlemma of_int_0_le_iff [simp]:\n  \"0 \\<le> of_int z \\<longleftrightarrow> 0 \\<le> z\"\n  using of_int_le_iff [of 0 z] by simp\n\nlemma of_int_le_0_iff [simp]:\n  \"of_int z \\<le> 0 \\<longleftrightarrow> z \\<le> 0\"\n  using of_int_le_iff [of z 0] by simp\n\nlemma of_int_0_less_iff [simp]:\n  \"0 < of_int z \\<longleftrightarrow> 0 < z\"\n  using of_int_less_iff [of 0 z] by simp\n\nlemma of_int_less_0_iff [simp]:\n  \"of_int z < 0 \\<longleftrightarrow> z < 0\"\n  using of_int_less_iff [of z 0] by simp\n\nend\n\nlemma of_nat_less_of_int_iff:\n  \"(of_nat n::'a::linordered_idom) < of_int x \\<longleftrightarrow> int n < x\"\n  by (metis of_int_of_nat_eq of_int_less_iff)\n\nlemma of_int_eq_id [simp]: \"of_int = id\"\nproof\n  fix z show \"of_int z = id z\"\n    by (cases z rule: int_diff_cases, simp)\nqed\n\n\ninstance int :: no_top\n  apply default\n  apply (rule_tac x=\"x + 1\" in exI)\n  apply simp\n  done\n\ninstance int :: no_bot\n  apply default\n  apply (rule_tac x=\"x - 1\" in exI)\n  apply simp\n  done\n\nsubsection {* Magnitude of an Integer, as a Natural Number: @{text nat} *}\n\nlift_definition nat :: \"int \\<Rightarrow> nat\" is \"\\<lambda>(x, y). x - y\"\n  by auto\n\nlemma nat_int [simp]: \"nat (int n) = n\"\n  by transfer simp\n\nlemma int_nat_eq [simp]: \"int (nat z) = (if 0 \\<le> z then z else 0)\"\n  by transfer clarsimp\n\ncorollary nat_0_le: \"0 \\<le> z ==> int (nat z) = z\"\nby simp\n\nlemma nat_le_0 [simp]: \"z \\<le> 0 ==> nat z = 0\"\n  by transfer clarsimp\n\nlemma nat_le_eq_zle: \"0 < w | 0 \\<le> z ==> (nat w \\<le> nat z) = (w\\<le>z)\"\n  by transfer (clarsimp, arith)\n\ntext{*An alternative condition is @{term \"0 \\<le> w\"} *}\ncorollary nat_mono_iff: \"0 < z ==> (nat w < nat z) = (w < z)\"\nby (simp add: nat_le_eq_zle linorder_not_le [symmetric]) \n\ncorollary nat_less_eq_zless: \"0 \\<le> w ==> (nat w < nat z) = (w<z)\"\nby (simp add: nat_le_eq_zle linorder_not_le [symmetric]) \n\nlemma zless_nat_conj [simp]: \"(nat w < nat z) = (0 < z & w < z)\"\n  by transfer (clarsimp, arith)\n\nlemma nonneg_eq_int:\n  fixes z :: int\n  assumes \"0 \\<le> z\" and \"\\<And>m. z = int m \\<Longrightarrow> P\"\n  shows P\n  using assms by (blast dest: nat_0_le sym)\n\nlemma nat_eq_iff:\n  \"nat w = m \\<longleftrightarrow> (if 0 \\<le> w then w = int m else m = 0)\"\n  by transfer (clarsimp simp add: le_imp_diff_is_add)\n \ncorollary nat_eq_iff2:\n  \"m = nat w \\<longleftrightarrow> (if 0 \\<le> w then w = int m else m = 0)\"\n  using nat_eq_iff [of w m] by auto\n\nlemma nat_0 [simp]:\n  \"nat 0 = 0\"\n  by (simp add: nat_eq_iff)\n\nlemma nat_1 [simp]:\n  \"nat 1 = Suc 0\"\n  by (simp add: nat_eq_iff)\n\nlemma nat_numeral [simp]:\n  \"nat (numeral k) = numeral k\"\n  by (simp add: nat_eq_iff)\n\nlemma nat_neg_numeral [simp]:\n  \"nat (- numeral k) = 0\"\n  by simp\n\nlemma nat_2: \"nat 2 = Suc (Suc 0)\"\n  by simp\n \nlemma nat_less_iff: \"0 \\<le> w ==> (nat w < m) = (w < of_nat m)\"\n  by transfer (clarsimp, arith)\n\nlemma nat_le_iff: \"nat x \\<le> n \\<longleftrightarrow> x \\<le> int n\"\n  by transfer (clarsimp simp add: le_diff_conv)\n\nlemma nat_mono: \"x \\<le> y \\<Longrightarrow> nat x \\<le> nat y\"\n  by transfer auto\n\nlemma nat_0_iff[simp]: \"nat(i::int) = 0 \\<longleftrightarrow> i\\<le>0\"\n  by transfer clarsimp\n\nlemma int_eq_iff: \"(of_nat m = z) = (m = nat z & 0 \\<le> z)\"\nby (auto simp add: nat_eq_iff2)\n\nlemma zero_less_nat_eq [simp]: \"(0 < nat z) = (0 < z)\"\nby (insert zless_nat_conj [of 0], auto)\n\nlemma nat_add_distrib:\n  \"0 \\<le> z \\<Longrightarrow> 0 \\<le> z' \\<Longrightarrow> nat (z + z') = nat z + nat z'\"\n  by transfer clarsimp\n\nlemma nat_diff_distrib':\n  \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> nat (x - y) = nat x - nat y\"\n  by transfer clarsimp\n \nlemma nat_diff_distrib:\n  \"0 \\<le> z' \\<Longrightarrow> z' \\<le> z \\<Longrightarrow> nat (z - z') = nat z - nat z'\"\n  by (rule nat_diff_distrib') auto\n\nlemma nat_zminus_int [simp]: \"nat (- int n) = 0\"\n  by transfer simp\n\nlemma le_nat_iff:\n  \"k \\<ge> 0 \\<Longrightarrow> n \\<le> nat k \\<longleftrightarrow> int n \\<le> k\"\n  by transfer auto\n  \nlemma zless_nat_eq_int_zless: \"(m < nat z) = (int m < z)\"\n  by transfer (clarsimp simp add: less_diff_conv)\n\ncontext ring_1\nbegin\n\nlemma of_nat_nat: \"0 \\<le> z \\<Longrightarrow> of_nat (nat z) = of_int z\"\n  by transfer (clarsimp simp add: of_nat_diff)\n\nend\n\nlemma diff_nat_numeral [simp]: \n  \"(numeral v :: nat) - numeral v' = nat (numeral v - numeral v')\"\n  by (simp only: nat_diff_distrib' zero_le_numeral nat_numeral)\n\n\ntext {* For termination proofs: *}\nlemma measure_function_int[measure_function]: \"is_measure (nat o abs)\" ..\n\n\nsubsection{*Lemmas about the Function @{term of_nat} and Orderings*}\n\nlemma negative_zless_0: \"- (int (Suc n)) < (0 \\<Colon> int)\"\nby (simp add: order_less_le del: of_nat_Suc)\n\nlemma negative_zless [iff]: \"- (int (Suc n)) < int m\"\nby (rule negative_zless_0 [THEN order_less_le_trans], simp)\n\nlemma negative_zle_0: \"- int n \\<le> 0\"\nby (simp add: minus_le_iff)\n\nlemma negative_zle [iff]: \"- int n \\<le> int m\"\nby (rule order_trans [OF negative_zle_0 of_nat_0_le_iff])\n\nlemma not_zle_0_negative [simp]: \"~ (0 \\<le> - (int (Suc n)))\"\nby (subst le_minus_iff, simp del: of_nat_Suc)\n\nlemma int_zle_neg: \"(int n \\<le> - int m) = (n = 0 & m = 0)\"\n  by transfer simp\n\nlemma not_int_zless_negative [simp]: \"~ (int n < - int m)\"\nby (simp add: linorder_not_less)\n\nlemma negative_eq_positive [simp]: \"(- int n = of_nat m) = (n = 0 & m = 0)\"\nby (force simp add: order_eq_iff [of \"- of_nat n\"] int_zle_neg)\n\nlemma zle_iff_zadd: \"w \\<le> z \\<longleftrightarrow> (\\<exists>n. z = w + int n)\"\nproof -\n  have \"(w \\<le> z) = (0 \\<le> z - w)\"\n    by (simp only: le_diff_eq add_0_left)\n  also have \"\\<dots> = (\\<exists>n. z - w = of_nat n)\"\n    by (auto elim: zero_le_imp_eq_int)\n  also have \"\\<dots> = (\\<exists>n. z = w + of_nat n)\"\n    by (simp only: algebra_simps)\n  finally show ?thesis .\nqed\n\nlemma zadd_int_left: \"int m + (int n + z) = int (m + n) + z\"\nby simp\n\nlemma int_Suc0_eq_1: \"int (Suc 0) = 1\"\nby simp\n\ntext{*This version is proved for all ordered rings, not just integers!\n      It is proved here because attribute @{text arith_split} is not available\n      in theory @{text Rings}.\n      But is it really better than just rewriting with @{text abs_if}?*}\nlemma abs_split [arith_split, no_atp]:\n     \"P(abs(a::'a::linordered_idom)) = ((0 \\<le> a --> P a) & (a < 0 --> P(-a)))\"\nby (force dest: order_less_le_trans simp add: abs_if linorder_not_less)\n\nlemma negD: \"x < 0 \\<Longrightarrow> \\<exists>n. x = - (int (Suc n))\"\napply transfer\napply clarsimp\napply (rule_tac x=\"b - Suc a\" in exI, arith)\ndone\n\nsubsection {* Cases and induction *}\n\ntext{*Now we replace the case analysis rule by a more conventional one:\nwhether an integer is negative or not.*}\n\ntheorem int_cases [case_names nonneg neg, cases type: int]:\n  \"[|!! n. z = int n ==> P;  !! n. z =  - (int (Suc n)) ==> P |] ==> P\"\napply (cases \"z < 0\")\napply (blast dest!: negD)\napply (simp add: linorder_not_less del: of_nat_Suc)\napply auto\napply (blast dest: nat_0_le [THEN sym])\ndone\n\ntheorem int_of_nat_induct [case_names nonneg neg, induct type: int]:\n     \"[|!! n. P (int n);  !!n. P (- (int (Suc n))) |] ==> P z\"\n  by (cases z) auto\n\nlemma nonneg_int_cases:\n  assumes \"0 \\<le> k\" obtains n where \"k = int n\"\n  using assms by (rule nonneg_eq_int)\n\nlemma Let_numeral [simp]: \"Let (numeral v) f = f (numeral v)\"\n  -- {* Unfold all @{text let}s involving constants *}\n  by (fact Let_numeral) -- {* FIXME drop *}\n\nlemma Let_neg_numeral [simp]: \"Let (- numeral v) f = f (- numeral v)\"\n  -- {* Unfold all @{text let}s involving constants *}\n  by (fact Let_neg_numeral) -- {* FIXME drop *}\n\ntext {* Unfold @{text min} and @{text max} on numerals. *}\n\nlemmas max_number_of [simp] =\n  max_def [of \"numeral u\" \"numeral v\"]\n  max_def [of \"numeral u\" \"- numeral v\"]\n  max_def [of \"- numeral u\" \"numeral v\"]\n  max_def [of \"- numeral u\" \"- numeral v\"] for u v\n\nlemmas min_number_of [simp] =\n  min_def [of \"numeral u\" \"numeral v\"]\n  min_def [of \"numeral u\" \"- numeral v\"]\n  min_def [of \"- numeral u\" \"numeral v\"]\n  min_def [of \"- numeral u\" \"- numeral v\"] for u v\n\n\nsubsubsection {* Binary comparisons *}\n\ntext {* Preliminaries *}\n\nlemma even_less_0_iff:\n  \"a + a < 0 \\<longleftrightarrow> a < (0::'a::linordered_idom)\"\nproof -\n  have \"a + a < 0 \\<longleftrightarrow> (1+1)*a < 0\" by (simp add: distrib_right del: one_add_one)\n  also have \"(1+1)*a < 0 \\<longleftrightarrow> a < 0\"\n    by (simp add: mult_less_0_iff zero_less_two \n                  order_less_not_sym [OF zero_less_two])\n  finally show ?thesis .\nqed\n\nlemma le_imp_0_less: \n  assumes le: \"0 \\<le> z\"\n  shows \"(0::int) < 1 + z\"\nproof -\n  have \"0 \\<le> z\" by fact\n  also have \"... < z + 1\" by (rule less_add_one)\n  also have \"... = 1 + z\" by (simp add: ac_simps)\n  finally show \"0 < 1 + z\" .\nqed\n\nlemma odd_less_0_iff:\n  \"(1 + z + z < 0) = (z < (0::int))\"\nproof (cases z)\n  case (nonneg n)\n  thus ?thesis by (simp add: linorder_not_less add.assoc add_increasing\n                             le_imp_0_less [THEN order_less_imp_le])  \nnext\n  case (neg n)\n  thus ?thesis by (simp del: of_nat_Suc of_nat_add of_nat_1\n    add: algebra_simps of_nat_1 [where 'a=int, symmetric] of_nat_add [symmetric])\nqed\n\nsubsubsection {* Comparisons, for Ordered Rings *}\n\nlemmas double_eq_0_iff = double_zero\n\nlemma odd_nonzero:\n  \"1 + z + z \\<noteq> (0::int)\"\nproof (cases z)\n  case (nonneg n)\n  have le: \"0 \\<le> z+z\" by (simp add: nonneg add_increasing) \n  thus ?thesis using  le_imp_0_less [OF le]\n    by (auto simp add: add.assoc) \nnext\n  case (neg n)\n  show ?thesis\n  proof\n    assume eq: \"1 + z + z = 0\"\n    have \"(0::int) < 1 + (int n + int n)\"\n      by (simp add: le_imp_0_less add_increasing) \n    also have \"... = - (1 + z + z)\" \n      by (simp add: neg add.assoc [symmetric]) \n    also have \"... = 0\" by (simp add: eq) \n    finally have \"0<0\" ..\n    thus False by blast\n  qed\nqed\n\n\nsubsection {* The Set of Integers *}\n\ncontext ring_1\nbegin\n\ndefinition Ints  :: \"'a set\" where\n  \"Ints = range of_int\"\n\nnotation (xsymbols)\n  Ints  (\"\\<int>\")\n\nlemma Ints_of_int [simp]: \"of_int z \\<in> \\<int>\"\n  by (simp add: Ints_def)\n\nlemma Ints_of_nat [simp]: \"of_nat n \\<in> \\<int>\"\n  using Ints_of_int [of \"of_nat n\"] by simp\n\nlemma Ints_0 [simp]: \"0 \\<in> \\<int>\"\n  using Ints_of_int [of \"0\"] by simp\n\nlemma Ints_1 [simp]: \"1 \\<in> \\<int>\"\n  using Ints_of_int [of \"1\"] by simp\n\nlemma Ints_add [simp]: \"a \\<in> \\<int> \\<Longrightarrow> b \\<in> \\<int> \\<Longrightarrow> a + b \\<in> \\<int>\"\napply (auto simp add: Ints_def)\napply (rule range_eqI)\napply (rule of_int_add [symmetric])\ndone\n\nlemma Ints_minus [simp]: \"a \\<in> \\<int> \\<Longrightarrow> -a \\<in> \\<int>\"\napply (auto simp add: Ints_def)\napply (rule range_eqI)\napply (rule of_int_minus [symmetric])\ndone\n\nlemma Ints_diff [simp]: \"a \\<in> \\<int> \\<Longrightarrow> b \\<in> \\<int> \\<Longrightarrow> a - b \\<in> \\<int>\"\napply (auto simp add: Ints_def)\napply (rule range_eqI)\napply (rule of_int_diff [symmetric])\ndone\n\nlemma Ints_mult [simp]: \"a \\<in> \\<int> \\<Longrightarrow> b \\<in> \\<int> \\<Longrightarrow> a * b \\<in> \\<int>\"\napply (auto simp add: Ints_def)\napply (rule range_eqI)\napply (rule of_int_mult [symmetric])\ndone\n\nlemma Ints_power [simp]: \"a \\<in> \\<int> \\<Longrightarrow> a ^ n \\<in> \\<int>\"\nby (induct n) simp_all\n\nlemma Ints_cases [cases set: Ints]:\n  assumes \"q \\<in> \\<int>\"\n  obtains (of_int) z where \"q = of_int z\"\n  unfolding Ints_def\nproof -\n  from `q \\<in> \\<int>` have \"q \\<in> range of_int\" unfolding Ints_def .\n  then obtain z where \"q = of_int z\" ..\n  then show thesis ..\nqed\n\nlemma Ints_induct [case_names of_int, induct set: Ints]:\n  \"q \\<in> \\<int> \\<Longrightarrow> (\\<And>z. P (of_int z)) \\<Longrightarrow> P q\"\n  by (rule Ints_cases) auto\n\nend\n\ntext {* The premise involving @{term Ints} prevents @{term \"a = 1/2\"}. *}\n\nlemma Ints_double_eq_0_iff:\n  assumes in_Ints: \"a \\<in> Ints\"\n  shows \"(a + a = 0) = (a = (0::'a::ring_char_0))\"\nproof -\n  from in_Ints have \"a \\<in> range of_int\" unfolding Ints_def [symmetric] .\n  then obtain z where a: \"a = of_int z\" ..\n  show ?thesis\n  proof\n    assume \"a = 0\"\n    thus \"a + a = 0\" by simp\n  next\n    assume eq: \"a + a = 0\"\n    hence \"of_int (z + z) = (of_int 0 :: 'a)\" by (simp add: a)\n    hence \"z + z = 0\" by (simp only: of_int_eq_iff)\n    hence \"z = 0\" by (simp only: double_eq_0_iff)\n    thus \"a = 0\" by (simp add: a)\n  qed\nqed\n\nlemma Ints_odd_nonzero:\n  assumes in_Ints: \"a \\<in> Ints\"\n  shows \"1 + a + a \\<noteq> (0::'a::ring_char_0)\"\nproof -\n  from in_Ints have \"a \\<in> range of_int\" unfolding Ints_def [symmetric] .\n  then obtain z where a: \"a = of_int z\" ..\n  show ?thesis\n  proof\n    assume eq: \"1 + a + a = 0\"\n    hence \"of_int (1 + z + z) = (of_int 0 :: 'a)\" by (simp add: a)\n    hence \"1 + z + z = 0\" by (simp only: of_int_eq_iff)\n    with odd_nonzero show False by blast\n  qed\nqed \n\nlemma Nats_numeral [simp]: \"numeral w \\<in> Nats\"\n  using of_nat_in_Nats [of \"numeral w\"] by simp\n\nlemma Ints_odd_less_0: \n  assumes in_Ints: \"a \\<in> Ints\"\n  shows \"(1 + a + a < 0) = (a < (0::'a::linordered_idom))\"\nproof -\n  from in_Ints have \"a \\<in> range of_int\" unfolding Ints_def [symmetric] .\n  then obtain z where a: \"a = of_int z\" ..\n  hence \"((1::'a) + a + a < 0) = (of_int (1 + z + z) < (of_int 0 :: 'a))\"\n    by (simp add: a)\n  also have \"... = (z < 0)\" by (simp only: of_int_less_iff odd_less_0_iff)\n  also have \"... = (a < 0)\" by (simp add: a)\n  finally show ?thesis .\nqed\n\n\nsubsection {* @{term setsum} and @{term setprod} *}\n\nlemma of_nat_setsum: \"of_nat (setsum f A) = (\\<Sum>x\\<in>A. of_nat(f x))\"\n  apply (cases \"finite A\")\n  apply (erule finite_induct, auto)\n  done\n\nlemma of_int_setsum: \"of_int (setsum f A) = (\\<Sum>x\\<in>A. of_int(f x))\"\n  apply (cases \"finite A\")\n  apply (erule finite_induct, auto)\n  done\n\nlemma of_nat_setprod: \"of_nat (setprod f A) = (\\<Prod>x\\<in>A. of_nat(f x))\"\n  apply (cases \"finite A\")\n  apply (erule finite_induct, auto simp add: of_nat_mult)\n  done\n\nlemma of_int_setprod: \"of_int (setprod f A) = (\\<Prod>x\\<in>A. of_int(f x))\"\n  apply (cases \"finite A\")\n  apply (erule finite_induct, auto)\n  done\n\nlemmas int_setsum = of_nat_setsum [where 'a=int]\nlemmas int_setprod = of_nat_setprod [where 'a=int]\n\n\ntext {* Legacy theorems *}\n\nlemmas zle_int = of_nat_le_iff [where 'a=int]\nlemmas int_int_eq = of_nat_eq_iff [where 'a=int]\nlemmas numeral_1_eq_1 = numeral_One\n\nsubsection {* Setting up simplification procedures *}\n\nlemmas of_int_simps =\n  of_int_0 of_int_1 of_int_add of_int_mult\n\nlemmas int_arith_rules =\n  numeral_One more_arith_simps of_nat_simps of_int_simps\n\nML_file \"Tools/int_arith.ML\"\ndeclaration {* K Int_Arith.setup *}\n\nsimproc_setup fast_arith (\"(m::'a::linordered_idom) < n\" |\n  \"(m::'a::linordered_idom) <= n\" |\n  \"(m::'a::linordered_idom) = n\") =\n  {* fn _ => fn ss => fn ct => Lin_Arith.simproc ss (term_of ct) *}\n\n\nsubsection{*More Inequality Reasoning*}\n\nlemma zless_add1_eq: \"(w < z + (1::int)) = (w<z | w=z)\"\nby arith\n\nlemma add1_zle_eq: \"(w + (1::int) \\<le> z) = (w<z)\"\nby arith\n\nlemma zle_diff1_eq [simp]: \"(w \\<le> z - (1::int)) = (w<z)\"\nby arith\n\nlemma zle_add1_eq_le [simp]: \"(w < z + (1::int)) = (w\\<le>z)\"\nby arith\n\nlemma int_one_le_iff_zero_less: \"((1::int) \\<le> z) = (0 < z)\"\nby arith\n\n\nsubsection{*The functions @{term nat} and @{term int}*}\n\ntext{*Simplify the term @{term \"w + - z\"}*}\n\nlemma one_less_nat_eq [simp]: \"(Suc 0 < nat z) = (1 < z)\"\napply (insert zless_nat_conj [of 1 z])\napply auto\ndone\n\ntext{*This simplifies expressions of the form @{term \"int n = z\"} where\n      z is an integer literal.*}\nlemmas int_eq_iff_numeral [simp] = int_eq_iff [of _ \"numeral v\"] for v\n\nlemma split_nat [arith_split]:\n  \"P(nat(i::int)) = ((\\<forall>n. i = int n \\<longrightarrow> P n) & (i < 0 \\<longrightarrow> P 0))\"\n  (is \"?P = (?L & ?R)\")\nproof (cases \"i < 0\")\n  case True thus ?thesis by auto\nnext\n  case False\n  have \"?P = ?L\"\n  proof\n    assume ?P thus ?L using False by clarsimp\n  next\n    assume ?L thus ?P using False by simp\n  qed\n  with False show ?thesis by simp\nqed\n\nlemma nat_abs_int_diff: \"nat \\<bar>int a - int b\\<bar> = (if a \\<le> b then b - a else a - b)\"\n  by auto\n\nlemma nat_int_add: \"nat (int a + int b) = a + b\"\n  by auto\n\ncontext ring_1\nbegin\n\nlemma of_int_of_nat [nitpick_simp]:\n  \"of_int k = (if k < 0 then - of_nat (nat (- k)) else of_nat (nat k))\"\nproof (cases \"k < 0\")\n  case True then have \"0 \\<le> - k\" by simp\n  then have \"of_nat (nat (- k)) = of_int (- k)\" by (rule of_nat_nat)\n  with True show ?thesis by simp\nnext\n  case False then show ?thesis by (simp add: not_less of_nat_nat)\nqed\n\nend\n\nlemma nat_mult_distrib:\n  fixes z z' :: int\n  assumes \"0 \\<le> z\"\n  shows \"nat (z * z') = nat z * nat z'\"\nproof (cases \"0 \\<le> z'\")\n  case False with assms have \"z * z' \\<le> 0\"\n    by (simp add: not_le mult_le_0_iff)\n  then have \"nat (z * z') = 0\" by simp\n  moreover from False have \"nat z' = 0\" by simp\n  ultimately show ?thesis by simp\nnext\n  case True with assms have ge_0: \"z * z' \\<ge> 0\" by (simp add: zero_le_mult_iff)\n  show ?thesis\n    by (rule injD [of \"of_nat :: nat \\<Rightarrow> int\", OF inj_of_nat])\n      (simp only: of_nat_mult of_nat_nat [OF True]\n         of_nat_nat [OF assms] of_nat_nat [OF ge_0], simp)\nqed\n\nlemma nat_mult_distrib_neg: \"z \\<le> (0::int) ==> nat(z*z') = nat(-z) * nat(-z')\"\napply (rule trans)\napply (rule_tac [2] nat_mult_distrib, auto)\ndone\n\nlemma nat_abs_mult_distrib: \"nat (abs (w * z)) = nat (abs w) * nat (abs z)\"\napply (cases \"z=0 | w=0\")\napply (auto simp add: abs_if nat_mult_distrib [symmetric] \n                      nat_mult_distrib_neg [symmetric] mult_less_0_iff)\ndone\n\nlemma Suc_nat_eq_nat_zadd1: \"(0::int) <= z ==> Suc (nat z) = nat (1 + z)\"\napply (rule sym)\napply (simp add: nat_eq_iff)\ndone\n\nlemma diff_nat_eq_if:\n     \"nat z - nat z' =  \n        (if z' < 0 then nat z   \n         else let d = z-z' in     \n              if d < 0 then 0 else nat d)\"\nby (simp add: Let_def nat_diff_distrib [symmetric])\n\nlemma nat_numeral_diff_1 [simp]:\n  \"numeral v - (1::nat) = nat (numeral v - 1)\"\n  using diff_nat_numeral [of v Num.One] by simp\n\n\nsubsection \"Induction principles for int\"\n\ntext{*Well-founded segments of the integers*}\n\ndefinition\n  int_ge_less_than  ::  \"int => (int * int) set\"\nwhere\n  \"int_ge_less_than d = {(z',z). d \\<le> z' & z' < z}\"\n\ntheorem wf_int_ge_less_than: \"wf (int_ge_less_than d)\"\nproof -\n  have \"int_ge_less_than d \\<subseteq> measure (%z. nat (z-d))\"\n    by (auto simp add: int_ge_less_than_def)\n  thus ?thesis \n    by (rule wf_subset [OF wf_measure]) \nqed\n\ntext{*This variant looks odd, but is typical of the relations suggested\nby RankFinder.*}\n\ndefinition\n  int_ge_less_than2 ::  \"int => (int * int) set\"\nwhere\n  \"int_ge_less_than2 d = {(z',z). d \\<le> z & z' < z}\"\n\ntheorem wf_int_ge_less_than2: \"wf (int_ge_less_than2 d)\"\nproof -\n  have \"int_ge_less_than2 d \\<subseteq> measure (%z. nat (1+z-d))\" \n    by (auto simp add: int_ge_less_than2_def)\n  thus ?thesis \n    by (rule wf_subset [OF wf_measure]) \nqed\n\n(* `set:int': dummy construction *)\ntheorem int_ge_induct [case_names base step, induct set: int]:\n  fixes i :: int\n  assumes ge: \"k \\<le> i\" and\n    base: \"P k\" and\n    step: \"\\<And>i. k \\<le> i \\<Longrightarrow> P i \\<Longrightarrow> P (i + 1)\"\n  shows \"P i\"\nproof -\n  { fix n\n    have \"\\<And>i::int. n = nat (i - k) \\<Longrightarrow> k \\<le> i \\<Longrightarrow> P i\"\n    proof (induct n)\n      case 0\n      hence \"i = k\" by arith\n      thus \"P i\" using base by simp\n    next\n      case (Suc n)\n      then have \"n = nat((i - 1) - k)\" by arith\n      moreover\n      have ki1: \"k \\<le> i - 1\" using Suc.prems by arith\n      ultimately\n      have \"P (i - 1)\" by (rule Suc.hyps)\n      from step [OF ki1 this] show ?case by simp\n    qed\n  }\n  with ge show ?thesis by fast\nqed\n\n(* `set:int': dummy construction *)\ntheorem int_gr_induct [case_names base step, induct set: int]:\n  assumes gr: \"k < (i::int)\" and\n        base: \"P(k+1)\" and\n        step: \"\\<And>i. \\<lbrakk>k < i; P i\\<rbrakk> \\<Longrightarrow> P(i+1)\"\n  shows \"P i\"\napply(rule int_ge_induct[of \"k + 1\"])\n  using gr apply arith\n apply(rule base)\napply (rule step, simp+)\ndone\n\ntheorem int_le_induct [consumes 1, case_names base step]:\n  assumes le: \"i \\<le> (k::int)\" and\n        base: \"P(k)\" and\n        step: \"\\<And>i. \\<lbrakk>i \\<le> k; P i\\<rbrakk> \\<Longrightarrow> P(i - 1)\"\n  shows \"P i\"\nproof -\n  { fix n\n    have \"\\<And>i::int. n = nat(k-i) \\<Longrightarrow> i \\<le> k \\<Longrightarrow> P i\"\n    proof (induct n)\n      case 0\n      hence \"i = k\" by arith\n      thus \"P i\" using base by simp\n    next\n      case (Suc n)\n      hence \"n = nat (k - (i + 1))\" by arith\n      moreover\n      have ki1: \"i + 1 \\<le> k\" using Suc.prems by arith\n      ultimately\n      have \"P (i + 1)\" by(rule Suc.hyps)\n      from step[OF ki1 this] show ?case by simp\n    qed\n  }\n  with le show ?thesis by fast\nqed\n\ntheorem int_less_induct [consumes 1, case_names base step]:\n  assumes less: \"(i::int) < k\" and\n        base: \"P(k - 1)\" and\n        step: \"\\<And>i. \\<lbrakk>i < k; P i\\<rbrakk> \\<Longrightarrow> P(i - 1)\"\n  shows \"P i\"\napply(rule int_le_induct[of _ \"k - 1\"])\n  using less apply arith\n apply(rule base)\napply (rule step, simp+)\ndone\n\ntheorem int_induct [case_names base step1 step2]:\n  fixes k :: int\n  assumes base: \"P k\"\n    and step1: \"\\<And>i. k \\<le> i \\<Longrightarrow> P i \\<Longrightarrow> P (i + 1)\"\n    and step2: \"\\<And>i. k \\<ge> i \\<Longrightarrow> P i \\<Longrightarrow> P (i - 1)\"\n  shows \"P i\"\nproof -\n  have \"i \\<le> k \\<or> i \\<ge> k\" by arith\n  then show ?thesis\n  proof\n    assume \"i \\<ge> k\"\n    then show ?thesis using base\n      by (rule int_ge_induct) (fact step1)\n  next\n    assume \"i \\<le> k\"\n    then show ?thesis using base\n      by (rule int_le_induct) (fact step2)\n  qed\nqed\n\nsubsection{*Intermediate value theorems*}\n\nlemma int_val_lemma:\n     \"(\\<forall>i<n::nat. abs(f(i+1) - f i) \\<le> 1) -->  \n      f 0 \\<le> k --> k \\<le> f n --> (\\<exists>i \\<le> n. f i = (k::int))\"\nunfolding One_nat_def\napply (induct n)\napply simp\napply (intro strip)\napply (erule impE, simp)\napply (erule_tac x = n in allE, simp)\napply (case_tac \"k = f (Suc n)\")\napply force\napply (erule impE)\n apply (simp add: abs_if split add: split_if_asm)\napply (blast intro: le_SucI)\ndone\n\nlemmas nat0_intermed_int_val = int_val_lemma [rule_format (no_asm)]\n\nlemma nat_intermed_int_val:\n     \"[| \\<forall>i. m \\<le> i & i < n --> abs(f(i + 1::nat) - f i) \\<le> 1; m < n;  \n         f m \\<le> k; k \\<le> f n |] ==> ? i. m \\<le> i & i \\<le> n & f i = (k::int)\"\napply (cut_tac n = \"n-m\" and f = \"%i. f (i+m) \" and k = k \n       in int_val_lemma)\nunfolding One_nat_def\napply simp\napply (erule exE)\napply (rule_tac x = \"i+m\" in exI, arith)\ndone\n\n\nsubsection{*Products and 1, by T. M. Rasmussen*}\n\nlemma zabs_less_one_iff [simp]: \"(\\<bar>z\\<bar> < 1) = (z = (0::int))\"\nby arith\n\nlemma abs_zmult_eq_1:\n  assumes mn: \"\\<bar>m * n\\<bar> = 1\"\n  shows \"\\<bar>m\\<bar> = (1::int)\"\nproof -\n  have 0: \"m \\<noteq> 0 & n \\<noteq> 0\" using mn\n    by auto\n  have \"~ (2 \\<le> \\<bar>m\\<bar>)\"\n  proof\n    assume \"2 \\<le> \\<bar>m\\<bar>\"\n    hence \"2*\\<bar>n\\<bar> \\<le> \\<bar>m\\<bar>*\\<bar>n\\<bar>\"\n      by (simp add: mult_mono 0) \n    also have \"... = \\<bar>m*n\\<bar>\" \n      by (simp add: abs_mult)\n    also have \"... = 1\"\n      by (simp add: mn)\n    finally have \"2*\\<bar>n\\<bar> \\<le> 1\" .\n    thus \"False\" using 0\n      by arith\n  qed\n  thus ?thesis using 0\n    by auto\nqed\n\nlemma pos_zmult_eq_1_iff_lemma: \"(m * n = 1) ==> m = (1::int) | m = -1\"\nby (insert abs_zmult_eq_1 [of m n], arith)\n\nlemma pos_zmult_eq_1_iff:\n  assumes \"0 < (m::int)\" shows \"(m * n = 1) = (m = 1 & n = 1)\"\nproof -\n  from assms have \"m * n = 1 ==> m = 1\" by (auto dest: pos_zmult_eq_1_iff_lemma)\n  thus ?thesis by (auto dest: pos_zmult_eq_1_iff_lemma)\nqed\n\nlemma zmult_eq_1_iff: \"(m*n = (1::int)) = ((m = 1 & n = 1) | (m = -1 & n = -1))\"\napply (rule iffI) \n apply (frule pos_zmult_eq_1_iff_lemma)\n apply (simp add: mult.commute [of m]) \n apply (frule pos_zmult_eq_1_iff_lemma, auto) \ndone\n\nlemma infinite_UNIV_int: \"\\<not> finite (UNIV::int set)\"\nproof\n  assume \"finite (UNIV::int set)\"\n  moreover have \"inj (\\<lambda>i\\<Colon>int. 2 * i)\"\n    by (rule injI) simp\n  ultimately have \"surj (\\<lambda>i\\<Colon>int. 2 * i)\"\n    by (rule finite_UNIV_inj_surj)\n  then obtain i :: int where \"1 = 2 * i\" by (rule surjE)\n  then show False by (simp add: pos_zmult_eq_1_iff)\nqed\n\n\nsubsection {* Further theorems on numerals *}\n\nsubsubsection{*Special Simplification for Constants*}\n\ntext{*These distributive laws move literals inside sums and differences.*}\n\nlemmas distrib_right_numeral [simp] = distrib_right [of _ _ \"numeral v\"] for v\nlemmas distrib_left_numeral [simp] = distrib_left [of \"numeral v\"] for v\nlemmas left_diff_distrib_numeral [simp] = left_diff_distrib [of _ _ \"numeral v\"] for v\nlemmas right_diff_distrib_numeral [simp] = right_diff_distrib [of \"numeral v\"] for v\n\ntext{*These are actually for fields, like real: but where else to put them?*}\n\nlemmas zero_less_divide_iff_numeral [simp, no_atp] = zero_less_divide_iff [of \"numeral w\"] for w\nlemmas divide_less_0_iff_numeral [simp, no_atp] = divide_less_0_iff [of \"numeral w\"] for w\nlemmas zero_le_divide_iff_numeral [simp, no_atp] = zero_le_divide_iff [of \"numeral w\"] for w\nlemmas divide_le_0_iff_numeral [simp, no_atp] = divide_le_0_iff [of \"numeral w\"] for w\n\n\ntext {*Replaces @{text \"inverse #nn\"} by @{text \"1/#nn\"}.  It looks\n  strange, but then other simprocs simplify the quotient.*}\n\nlemmas inverse_eq_divide_numeral [simp] =\n  inverse_eq_divide [of \"numeral w\"] for w\n\nlemmas inverse_eq_divide_neg_numeral [simp] =\n  inverse_eq_divide [of \"- numeral w\"] for w\n\ntext {*These laws simplify inequalities, moving unary minus from a term\ninto the literal.*}\n\nlemmas equation_minus_iff_numeral [no_atp] =\n  equation_minus_iff [of \"numeral v\"] for v\n\nlemmas minus_equation_iff_numeral [no_atp] =\n  minus_equation_iff [of _ \"numeral v\"] for v\n\nlemmas le_minus_iff_numeral [no_atp] =\n  le_minus_iff [of \"numeral v\"] for v\n\nlemmas minus_le_iff_numeral [no_atp] =\n  minus_le_iff [of _ \"numeral v\"] for v\n\nlemmas less_minus_iff_numeral [no_atp] =\n  less_minus_iff [of \"numeral v\"] for v\n\nlemmas minus_less_iff_numeral [no_atp] =\n  minus_less_iff [of _ \"numeral v\"] for v\n\n-- {* FIXME maybe simproc *}\n\n\ntext {*Cancellation of constant factors in comparisons (@{text \"<\"} and @{text \"\\<le>\"}) *}\n\nlemmas mult_less_cancel_left_numeral [simp, no_atp] = mult_less_cancel_left [of \"numeral v\"] for v\nlemmas mult_less_cancel_right_numeral [simp, no_atp] = mult_less_cancel_right [of _ \"numeral v\"] for v\nlemmas mult_le_cancel_left_numeral [simp, no_atp] = mult_le_cancel_left [of \"numeral v\"] for v\nlemmas mult_le_cancel_right_numeral [simp, no_atp] = mult_le_cancel_right [of _ \"numeral v\"] for v\n\n\ntext {*Multiplying out constant divisors in comparisons (@{text \"<\"}, @{text \"\\<le>\"} and @{text \"=\"}) *}\n\nlemmas le_divide_eq_numeral1 [simp] =\n  pos_le_divide_eq [of \"numeral w\", OF zero_less_numeral]\n  neg_le_divide_eq [of \"- numeral w\", OF neg_numeral_less_zero] for w\n\nlemmas divide_le_eq_numeral1 [simp] =\n  pos_divide_le_eq [of \"numeral w\", OF zero_less_numeral]\n  neg_divide_le_eq [of \"- numeral w\", OF neg_numeral_less_zero] for w\n\nlemmas less_divide_eq_numeral1 [simp] =\n  pos_less_divide_eq [of \"numeral w\", OF zero_less_numeral]\n  neg_less_divide_eq [of \"- numeral w\", OF neg_numeral_less_zero] for w\n\nlemmas divide_less_eq_numeral1 [simp] =\n  pos_divide_less_eq [of \"numeral w\", OF zero_less_numeral]\n  neg_divide_less_eq [of \"- numeral w\", OF neg_numeral_less_zero] for w\n\nlemmas eq_divide_eq_numeral1 [simp] =\n  eq_divide_eq [of _ _ \"numeral w\"]\n  eq_divide_eq [of _ _ \"- numeral w\"] for w\n\nlemmas divide_eq_eq_numeral1 [simp] =\n  divide_eq_eq [of _ \"numeral w\"]\n  divide_eq_eq [of _ \"- numeral w\"] for w\n\n\nsubsubsection{*Optional Simplification Rules Involving Constants*}\n\ntext{*Simplify quotients that are compared with a literal constant.*}\n\nlemmas le_divide_eq_numeral =\n  le_divide_eq [of \"numeral w\"]\n  le_divide_eq [of \"- numeral w\"] for w\n\nlemmas divide_le_eq_numeral =\n  divide_le_eq [of _ _ \"numeral w\"]\n  divide_le_eq [of _ _ \"- numeral w\"] for w\n\nlemmas less_divide_eq_numeral =\n  less_divide_eq [of \"numeral w\"]\n  less_divide_eq [of \"- numeral w\"] for w\n\nlemmas divide_less_eq_numeral =\n  divide_less_eq [of _ _ \"numeral w\"]\n  divide_less_eq [of _ _ \"- numeral w\"] for w\n\nlemmas eq_divide_eq_numeral =\n  eq_divide_eq [of \"numeral w\"]\n  eq_divide_eq [of \"- numeral w\"] for w\n\nlemmas divide_eq_eq_numeral =\n  divide_eq_eq [of _ _ \"numeral w\"]\n  divide_eq_eq [of _ _ \"- numeral w\"] for w\n\n\ntext{*Not good as automatic simprules because they cause case splits.*}\nlemmas divide_const_simps =\n  le_divide_eq_numeral divide_le_eq_numeral less_divide_eq_numeral\n  divide_less_eq_numeral eq_divide_eq_numeral divide_eq_eq_numeral\n  le_divide_eq_1 divide_le_eq_1 less_divide_eq_1 divide_less_eq_1\n\n\nsubsection {* The divides relation *}\n\nlemma zdvd_antisym_nonneg:\n    \"0 <= m ==> 0 <= n ==> m dvd n ==> n dvd m ==> m = (n::int)\"\n  apply (simp add: dvd_def, auto)\n  apply (auto simp add: mult.assoc zero_le_mult_iff zmult_eq_1_iff)\n  done\n\nlemma zdvd_antisym_abs: assumes \"(a::int) dvd b\" and \"b dvd a\" \n  shows \"\\<bar>a\\<bar> = \\<bar>b\\<bar>\"\nproof cases\n  assume \"a = 0\" with assms show ?thesis by simp\nnext\n  assume \"a \\<noteq> 0\"\n  from `a dvd b` obtain k where k:\"b = a*k\" unfolding dvd_def by blast \n  from `b dvd a` obtain k' where k':\"a = b*k'\" unfolding dvd_def by blast \n  from k k' have \"a = a*k*k'\" by simp\n  with mult_cancel_left1[where c=\"a\" and b=\"k*k'\"]\n  have kk':\"k*k' = 1\" using `a\\<noteq>0` by (simp add: mult.assoc)\n  hence \"k = 1 \\<and> k' = 1 \\<or> k = -1 \\<and> k' = -1\" by (simp add: zmult_eq_1_iff)\n  thus ?thesis using k k' by auto\nqed\n\nlemma zdvd_zdiffD: \"k dvd m - n ==> k dvd n ==> k dvd (m::int)\"\n  using dvd_add_right_iff [of k \"- n\" m] by simp \n\nlemma zdvd_reduce: \"(k dvd n + k * m) = (k dvd (n::int))\"\n  using dvd_add_times_triv_right_iff [of k n m] by (simp add: ac_simps)\n\nlemma dvd_imp_le_int:\n  fixes d i :: int\n  assumes \"i \\<noteq> 0\" and \"d dvd i\"\n  shows \"\\<bar>d\\<bar> \\<le> \\<bar>i\\<bar>\"\nproof -\n  from `d dvd i` obtain k where \"i = d * k\" ..\n  with `i \\<noteq> 0` have \"k \\<noteq> 0\" by auto\n  then have \"1 \\<le> \\<bar>k\\<bar>\" and \"0 \\<le> \\<bar>d\\<bar>\" by auto\n  then have \"\\<bar>d\\<bar> * 1 \\<le> \\<bar>d\\<bar> * \\<bar>k\\<bar>\" by (rule mult_left_mono)\n  with `i = d * k` show ?thesis by (simp add: abs_mult)\nqed\n\nlemma zdvd_not_zless:\n  fixes m n :: int\n  assumes \"0 < m\" and \"m < n\"\n  shows \"\\<not> n dvd m\"\nproof\n  from assms have \"0 < n\" by auto\n  assume \"n dvd m\" then obtain k where k: \"m = n * k\" ..\n  with `0 < m` have \"0 < n * k\" by auto\n  with `0 < n` have \"0 < k\" by (simp add: zero_less_mult_iff)\n  with k `0 < n` `m < n` have \"n * k < n * 1\" by simp\n  with `0 < n` `0 < k` show False unfolding mult_less_cancel_left by auto\nqed\n\nlemma zdvd_mult_cancel: assumes d:\"k * m dvd k * n\" and kz:\"k \\<noteq> (0::int)\"\n  shows \"m dvd n\"\nproof-\n  from d obtain h where h: \"k*n = k*m * h\" unfolding dvd_def by blast\n  {assume \"n \\<noteq> m*h\" hence \"k* n \\<noteq> k* (m*h)\" using kz by simp\n    with h have False by (simp add: mult.assoc)}\n  hence \"n = m * h\" by blast\n  thus ?thesis by simp\nqed\n\ntheorem zdvd_int: \"(x dvd y) = (int x dvd int y)\"\nproof -\n  have \"\\<And>k. int y = int x * k \\<Longrightarrow> x dvd y\"\n  proof -\n    fix k\n    assume A: \"int y = int x * k\"\n    then show \"x dvd y\"\n    proof (cases k)\n      case (nonneg n)\n      with A have \"y = x * n\" by (simp add: of_nat_mult [symmetric])\n      then show ?thesis ..\n    next\n      case (neg n)\n      with A have \"int y = int x * (- int (Suc n))\" by simp\n      also have \"\\<dots> = - (int x * int (Suc n))\" by (simp only: mult_minus_right)\n      also have \"\\<dots> = - int (x * Suc n)\" by (simp only: of_nat_mult [symmetric])\n      finally have \"- int (x * Suc n) = int y\" ..\n      then show ?thesis by (simp only: negative_eq_positive) auto\n    qed\n  qed\n  then show ?thesis by (auto elim!: dvdE simp only: dvd_triv_left of_nat_mult)\nqed\n\nlemma zdvd1_eq[simp]: \"(x::int) dvd 1 = (\\<bar>x\\<bar> = 1)\"\nproof\n  assume d: \"x dvd 1\" hence \"int (nat \\<bar>x\\<bar>) dvd int (nat 1)\" by simp\n  hence \"nat \\<bar>x\\<bar> dvd 1\" by (simp add: zdvd_int)\n  hence \"nat \\<bar>x\\<bar> = 1\"  by simp\n  thus \"\\<bar>x\\<bar> = 1\" by (cases \"x < 0\") auto\nnext\n  assume \"\\<bar>x\\<bar>=1\"\n  then have \"x = 1 \\<or> x = -1\" by auto\n  then show \"x dvd 1\" by (auto intro: dvdI)\nqed\n\nlemma zdvd_mult_cancel1: \n  assumes mp:\"m \\<noteq>(0::int)\" shows \"(m * n dvd m) = (\\<bar>n\\<bar> = 1)\"\nproof\n  assume n1: \"\\<bar>n\\<bar> = 1\" thus \"m * n dvd m\" \n    by (cases \"n >0\") (auto simp add: minus_equation_iff)\nnext\n  assume H: \"m * n dvd m\" hence H2: \"m * n dvd m * 1\" by simp\n  from zdvd_mult_cancel[OF H2 mp] show \"\\<bar>n\\<bar> = 1\" by (simp only: zdvd1_eq)\nqed\n\nlemma int_dvd_iff: \"(int m dvd z) = (m dvd nat (abs z))\"\n  unfolding zdvd_int by (cases \"z \\<ge> 0\") simp_all\n\nlemma dvd_int_iff: \"(z dvd int m) = (nat (abs z) dvd m)\"\n  unfolding zdvd_int by (cases \"z \\<ge> 0\") simp_all\n\nlemma dvd_int_unfold_dvd_nat:\n  \"k dvd l \\<longleftrightarrow> nat \\<bar>k\\<bar> dvd nat \\<bar>l\\<bar>\"\n  unfolding dvd_int_iff [symmetric] by simp\n\nlemma nat_dvd_iff: \"(nat z dvd m) = (if 0 \\<le> z then (z dvd int m) else m = 0)\"\n  by (auto simp add: dvd_int_iff)\n\nlemma eq_nat_nat_iff:\n  \"0 \\<le> z \\<Longrightarrow> 0 \\<le> z' \\<Longrightarrow> nat z = nat z' \\<longleftrightarrow> z = z'\"\n  by (auto elim!: nonneg_eq_int)\n\nlemma nat_power_eq:\n  \"0 \\<le> z \\<Longrightarrow> nat (z ^ n) = nat z ^ n\"\n  by (induct n) (simp_all add: nat_mult_distrib)\n\nlemma zdvd_imp_le: \"[| z dvd n; 0 < n |] ==> z \\<le> (n::int)\"\n  apply (cases n)\n  apply (auto simp add: dvd_int_iff)\n  apply (cases z)\n  apply (auto simp add: dvd_imp_le)\n  done\n\nlemma zdvd_period:\n  fixes a d :: int\n  assumes \"a dvd d\"\n  shows \"a dvd (x + t) \\<longleftrightarrow> a dvd ((x + c * d) + t)\"\nproof -\n  from assms obtain k where \"d = a * k\" by (rule dvdE)\n  show ?thesis\n  proof\n    assume \"a dvd (x + t)\"\n    then obtain l where \"x + t = a * l\" by (rule dvdE)\n    then have \"x = a * l - t\" by simp\n    with `d = a * k` show \"a dvd x + c * d + t\" by simp\n  next\n    assume \"a dvd x + c * d + t\"\n    then obtain l where \"x + c * d + t = a * l\" by (rule dvdE)\n    then have \"x = a * l - c * d - t\" by simp\n    with `d = a * k` show \"a dvd (x + t)\" by simp\n  qed\nqed\n\n\nsubsection {* Finiteness of intervals *}\n\nlemma finite_interval_int1 [iff]: \"finite {i :: int. a <= i & i <= b}\"\nproof (cases \"a <= b\")\n  case True\n  from this show ?thesis\n  proof (induct b rule: int_ge_induct)\n    case base\n    have \"{i. a <= i & i <= a} = {a}\" by auto\n    from this show ?case by simp\n  next\n    case (step b)\n    from this have \"{i. a <= i & i <= b + 1} = {i. a <= i & i <= b} \\<union> {b + 1}\" by auto\n    from this step show ?case by simp\n  qed\nnext\n  case False from this show ?thesis\n    by (metis (lifting, no_types) Collect_empty_eq finite.emptyI order_trans)\nqed\n\nlemma finite_interval_int2 [iff]: \"finite {i :: int. a <= i & i < b}\"\nby (rule rev_finite_subset[OF finite_interval_int1[of \"a\" \"b\"]]) auto\n\nlemma finite_interval_int3 [iff]: \"finite {i :: int. a < i & i <= b}\"\nby (rule rev_finite_subset[OF finite_interval_int1[of \"a\" \"b\"]]) auto\n\nlemma finite_interval_int4 [iff]: \"finite {i :: int. a < i & i < b}\"\nby (rule rev_finite_subset[OF finite_interval_int1[of \"a\" \"b\"]]) auto\n\n\nsubsection {* Configuration of the code generator *}\n\ntext {* Constructors *}\n\ndefinition Pos :: \"num \\<Rightarrow> int\" where\n  [simp, code_abbrev]: \"Pos = numeral\"\n\ndefinition Neg :: \"num \\<Rightarrow> int\" where\n  [simp, code_abbrev]: \"Neg n = - (Pos n)\"\n\ncode_datatype \"0::int\" Pos Neg\n\n\ntext {* Auxiliary operations *}\n\ndefinition dup :: \"int \\<Rightarrow> int\" where\n  [simp]: \"dup k = k + k\"\n\nlemma dup_code [code]:\n  \"dup 0 = 0\"\n  \"dup (Pos n) = Pos (Num.Bit0 n)\"\n  \"dup (Neg n) = Neg (Num.Bit0 n)\"\n  unfolding Pos_def Neg_def\n  by (simp_all add: numeral_Bit0)\n\ndefinition sub :: \"num \\<Rightarrow> num \\<Rightarrow> int\" where\n  [simp]: \"sub m n = numeral m - numeral n\"\n\nlemma sub_code [code]:\n  \"sub Num.One Num.One = 0\"\n  \"sub (Num.Bit0 m) Num.One = Pos (Num.BitM m)\"\n  \"sub (Num.Bit1 m) Num.One = Pos (Num.Bit0 m)\"\n  \"sub Num.One (Num.Bit0 n) = Neg (Num.BitM n)\"\n  \"sub Num.One (Num.Bit1 n) = Neg (Num.Bit0 n)\"\n  \"sub (Num.Bit0 m) (Num.Bit0 n) = dup (sub m n)\"\n  \"sub (Num.Bit1 m) (Num.Bit1 n) = dup (sub m n)\"\n  \"sub (Num.Bit1 m) (Num.Bit0 n) = dup (sub m n) + 1\"\n  \"sub (Num.Bit0 m) (Num.Bit1 n) = dup (sub m n) - 1\"\n  apply (simp_all only: sub_def dup_def numeral.simps Pos_def Neg_def numeral_BitM)\n  apply (simp_all only: algebra_simps minus_diff_eq)\n  apply (simp_all only: add.commute [of _ \"- (numeral n + numeral n)\"])\n  apply (simp_all only: minus_add add.assoc left_minus)\n  done\n\ntext {* Implementations *}\n\nlemma one_int_code [code, code_unfold]:\n  \"1 = Pos Num.One\"\n  by simp\n\nlemma plus_int_code [code]:\n  \"k + 0 = (k::int)\"\n  \"0 + l = (l::int)\"\n  \"Pos m + Pos n = Pos (m + n)\"\n  \"Pos m + Neg n = sub m n\"\n  \"Neg m + Pos n = sub n m\"\n  \"Neg m + Neg n = Neg (m + n)\"\n  by simp_all\n\nlemma uminus_int_code [code]:\n  \"uminus 0 = (0::int)\"\n  \"uminus (Pos m) = Neg m\"\n  \"uminus (Neg m) = Pos m\"\n  by simp_all\n\nlemma minus_int_code [code]:\n  \"k - 0 = (k::int)\"\n  \"0 - l = uminus (l::int)\"\n  \"Pos m - Pos n = sub m n\"\n  \"Pos m - Neg n = Pos (m + n)\"\n  \"Neg m - Pos n = Neg (m + n)\"\n  \"Neg m - Neg n = sub n m\"\n  by simp_all\n\nlemma times_int_code [code]:\n  \"k * 0 = (0::int)\"\n  \"0 * l = (0::int)\"\n  \"Pos m * Pos n = Pos (m * n)\"\n  \"Pos m * Neg n = Neg (m * n)\"\n  \"Neg m * Pos n = Neg (m * n)\"\n  \"Neg m * Neg n = Pos (m * n)\"\n  by simp_all\n\ninstantiation int :: equal\nbegin\n\ndefinition\n  \"HOL.equal k l \\<longleftrightarrow> k = (l::int)\"\n\ninstance by default (rule equal_int_def)\n\nend\n\nlemma equal_int_code [code]:\n  \"HOL.equal 0 (0::int) \\<longleftrightarrow> True\"\n  \"HOL.equal 0 (Pos l) \\<longleftrightarrow> False\"\n  \"HOL.equal 0 (Neg l) \\<longleftrightarrow> False\"\n  \"HOL.equal (Pos k) 0 \\<longleftrightarrow> False\"\n  \"HOL.equal (Pos k) (Pos l) \\<longleftrightarrow> HOL.equal k l\"\n  \"HOL.equal (Pos k) (Neg l) \\<longleftrightarrow> False\"\n  \"HOL.equal (Neg k) 0 \\<longleftrightarrow> False\"\n  \"HOL.equal (Neg k) (Pos l) \\<longleftrightarrow> False\"\n  \"HOL.equal (Neg k) (Neg l) \\<longleftrightarrow> HOL.equal k l\"\n  by (auto simp add: equal)\n\nlemma equal_int_refl [code nbe]:\n  \"HOL.equal (k::int) k \\<longleftrightarrow> True\"\n  by (fact equal_refl)\n\nlemma less_eq_int_code [code]:\n  \"0 \\<le> (0::int) \\<longleftrightarrow> True\"\n  \"0 \\<le> Pos l \\<longleftrightarrow> True\"\n  \"0 \\<le> Neg l \\<longleftrightarrow> False\"\n  \"Pos k \\<le> 0 \\<longleftrightarrow> False\"\n  \"Pos k \\<le> Pos l \\<longleftrightarrow> k \\<le> l\"\n  \"Pos k \\<le> Neg l \\<longleftrightarrow> False\"\n  \"Neg k \\<le> 0 \\<longleftrightarrow> True\"\n  \"Neg k \\<le> Pos l \\<longleftrightarrow> True\"\n  \"Neg k \\<le> Neg l \\<longleftrightarrow> l \\<le> k\"\n  by simp_all\n\nlemma less_int_code [code]:\n  \"0 < (0::int) \\<longleftrightarrow> False\"\n  \"0 < Pos l \\<longleftrightarrow> True\"\n  \"0 < Neg l \\<longleftrightarrow> False\"\n  \"Pos k < 0 \\<longleftrightarrow> False\"\n  \"Pos k < Pos l \\<longleftrightarrow> k < l\"\n  \"Pos k < Neg l \\<longleftrightarrow> False\"\n  \"Neg k < 0 \\<longleftrightarrow> True\"\n  \"Neg k < Pos l \\<longleftrightarrow> True\"\n  \"Neg k < Neg l \\<longleftrightarrow> l < k\"\n  by simp_all\n\nlemma nat_code [code]:\n  \"nat (Int.Neg k) = 0\"\n  \"nat 0 = 0\"\n  \"nat (Int.Pos k) = nat_of_num k\"\n  by (simp_all add: nat_of_num_numeral)\n\nlemma (in ring_1) of_int_code [code]:\n  \"of_int (Int.Neg k) = - numeral k\"\n  \"of_int 0 = 0\"\n  \"of_int (Int.Pos k) = numeral k\"\n  by simp_all\n\n\ntext {* Serializer setup *}\n\ncode_identifier\n  code_module Int \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nquickcheck_params [default_type = int]\n\nhide_const (open) Pos Neg sub dup\n\n\nsubsection {* Legacy theorems *}\n\nlemmas inj_int = inj_of_nat [where 'a=int]\nlemmas zadd_int = of_nat_add [where 'a=int, symmetric]\nlemmas int_mult = of_nat_mult [where 'a=int]\nlemmas zmult_int = of_nat_mult [where 'a=int, symmetric]\nlemmas int_eq_0_conv = of_nat_eq_0_iff [where 'a=int and m=\"n\"] for n\nlemmas zless_int = of_nat_less_iff [where 'a=int]\nlemmas int_less_0_conv = of_nat_less_0_iff [where 'a=int and m=\"k\"] for k\nlemmas zero_less_int_conv = of_nat_0_less_iff [where 'a=int]\nlemmas zero_zle_int = of_nat_0_le_iff [where 'a=int]\nlemmas int_le_0_conv = of_nat_le_0_iff [where 'a=int and m=\"n\"] for n\nlemmas int_0 = of_nat_0 [where 'a=int]\nlemmas int_1 = of_nat_1 [where 'a=int]\nlemmas int_Suc = of_nat_Suc [where 'a=int]\nlemmas int_numeral = of_nat_numeral [where 'a=int]\nlemmas abs_int_eq = abs_of_nat [where 'a=int and n=\"m\"] for m\nlemmas of_int_int_eq = of_int_of_nat_eq [where 'a=int]\nlemmas zdiff_int = of_nat_diff [where 'a=int, symmetric]\nlemmas zpower_numeral_even = power_numeral_even [where 'a=int]\nlemmas zpower_numeral_odd = power_numeral_odd [where 'a=int]\n\nlemma zpower_zpower:\n  \"(x ^ y) ^ z = (x ^ (y * z)::int)\"\n  by (rule power_mult [symmetric])\n\nlemma int_power:\n  \"int (m ^ n) = int m ^ n\"\n  by (fact of_nat_power)\n\nlemmas zpower_int = int_power [symmetric]\n\ntext {* De-register @{text \"int\"} as a quotient type: *}\n\nlifting_update int.lifting\nlifting_forget int.lifting\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8723473647220787, "lm_q1q2_score": 0.7831021176180326}}
{"text": "theory Bin_Search\nimports \"../sepref/IICF/IICF\" \"List-Index.List_Index\"\nbegin\n\n  subsection \\<open>Binary Search\\<close>\n    \n  subsubsection \\<open>Abstract Algorithm\\<close>\n  \n  abbreviation \"bin_search_invar xs x \\<equiv> (\\<lambda>(l,h). \n        0\\<le>l \\<and> l\\<le>h \\<and> h\\<le>length xs \n      \\<and> (\\<forall>i<l. xs!i<x) \\<and> (\\<forall>i\\<in>{h..<length xs}. x \\<le> xs!i))\"\n  \n  definition \"bin_search xs x \\<equiv> do {\n    (l,h) \\<leftarrow> WHILEIT (bin_search_invar xs x)\n      (\\<lambda>(l,h). l<h) \n      (\\<lambda>(l,h). do {\n        ASSERT (l<length xs \\<and> h\\<le>length xs \\<and> l\\<le>h);\n        let m = l + (h-l) div 2;\n        if xs!m < x then RETURN (m+1,h) else RETURN (l,m)\n      }) \n      (0,length xs);\n    RETURN l\n  }\"\n\n  \n  definition \"fi_spec xs x = SPEC (\\<lambda>i. i=find_index (\\<lambda>y. x\\<le>y) xs)\"\n  \n  lemma bin_search_correct:\n    assumes \"sorted xs\"\n    shows \"bin_search xs x \\<le> SPEC (\\<lambda>i. i=find_index (\\<lambda>y. x\\<le>y) xs)\"\n    unfolding bin_search_def\n    apply (refine_vcg WHILEIT_rule[where R=\"measure (\\<lambda>(l,h). h-l)\"])\n    apply (all \\<open>(auto;fail)?\\<close>)\n\n    apply (clarsimp simp: less_Suc_eq_le)\n    subgoal for l h i \n      apply (frule sorted_nth_mono[OF assms, of i \"l + (h-l) div 2\"])\n      by auto\n    subgoal\n      by clarsimp (meson assms leI le_less_trans sorted_iff_nth_mono)\n    \n    apply clarsimp\n    subgoal for i\n      by (simp add: find_index_eqI less_le_not_le)\n      \n    done\n\n  lemma bin_search_correct': \"(uncurry bin_search,uncurry fi_spec)\n    \\<in>[\\<lambda>(xs,_). sorted xs]\\<^sub>f Id \\<times>\\<^sub>r Id \\<rightarrow> \\<langle>nat_rel\\<rangle>nres_rel\"  \n    using bin_search_correct unfolding fi_spec_def\n    by (fastforce intro!: frefI nres_relI)\n    \n    \n  subsubsection \\<open>Implementation\\<close>\n    \n  type_synonym size_t = 64\n  type_synonym elem_t = 64\n\n  sepref_def bin_search_impl is \"uncurry bin_search\"  \n    :: \"(larray_assn' TYPE(size_t) (sint_assn' TYPE(elem_t)))\\<^sup>k \n        *\\<^sub>a (sint_assn' TYPE(elem_t))\\<^sup>k \n       \\<rightarrow>\\<^sub>a snat_assn' TYPE(size_t)\"\n    unfolding bin_search_def\n    apply (rule hfref_with_rdomI)\n    apply (annot_snat_const \"TYPE(size_t)\")\n    apply sepref    \n    done\n\n  definition [llvm_code, llvm_inline]: \"bin_search_impl' a x \\<equiv> doM {\n    a \\<leftarrow> ll_load a;\n    bin_search_impl a x\n  }\"  \n    \n    \n  export_llvm bin_search_impl' is \\<open>int64_t bin_search(larray_t*, elem_t)\\<close> \n  defines \\<open>\n    typedef uint64_t elem_t;\n    typedef struct {\n      int64_t len;\n      elem_t *data;\n    } larray_t;\n  \\<close>\n  file \"../../regression/gencode/bin_search.ll\"\n    \n  export_llvm bin_search_impl' is \\<open>int64_t bin_search(larray_t*, elem_t)\\<close> \n  defines \\<open>\n    typedef uint64_t elem_t;\n    typedef struct {\n      int64_t len;\n      elem_t *data;\n    } larray_t;\n  \\<close>\n  file \"code/bin_search.ll\"\n  \n  \n  lemmas bs_impl_correct = bin_search_impl.refine[FCOMP bin_search_correct']\n  \n  subsubsection \\<open>Combined Correctness Theorem\\<close>\n  \n  theorem bin_search_impl_correct:\n    \"llvm_htriple \n      (larray_assn sint_assn xs xsi ** sint_assn x xi ** \\<up>(sorted xs)) \n      (bin_search_impl xsi xi)\n      (\\<lambda>ii. EXS i. larray_assn sint_assn xs xsi ** sint_assn x xi ** snat_assn i ii \n                  ** \\<up>(i=find_index (\\<lambda>y. x\\<le>y) xs))\"\n  proof -\n  \n    from bin_search_correct have R: \n        \"(uncurry bin_search, uncurry (\\<lambda>xs x. SPEC (\\<lambda>i. i = find_index ((\\<le>) x) xs))) \n      \\<in> [\\<lambda>(xs,x). sorted xs]\\<^sub>f Id \\<rightarrow> \\<langle>Id\\<rangle>nres_rel\"\n      apply (intro frefI nres_relI)\n      apply fastforce \n      done\n  \n    note bin_search_impl.refine  \n    note R = bin_search_impl.refine[FCOMP R]\n    note R = R[THEN hfrefD, THEN hn_refineD, of \"(xs,x)\" \"(xsi,xi)\", simplified]\n    note [vcg_rules] = R\n    \n    show ?thesis by vcg'\n  qed\n\n  theorem bin_search_impl'_correct:\n    \"llvm_htriple \n      (\\<upharpoonleft>ll_pto xsi xsip ** larray_assn sint_assn xs xsi ** sint_assn x xi ** \\<up>(sorted xs)) \n      (bin_search_impl' xsip xi)\n      (\\<lambda>ii. EXS i. \\<upharpoonleft>ll_pto xsi xsip ** larray_assn sint_assn xs xsi ** sint_assn x xi ** snat_assn i ii \n                  ** \\<up>(i=find_index (\\<lambda>y. x\\<le>y) xs))\"\n  proof -\n    interpret llvm_prim_setup .\n    show ?thesis\n      unfolding bin_search_impl'_def\n      supply [vcg_rules] = bin_search_impl_correct\n      by vcg\n  qed\n  \nend\n", "meta": {"author": "lammich", "repo": "isabelle_llvm", "sha": "6be37a9c3cae74a1134dbef2979e312abb5f7f42", "save_path": "github-repos/isabelle/lammich-isabelle_llvm", "path": "github-repos/isabelle/lammich-isabelle_llvm/isabelle_llvm-6be37a9c3cae74a1134dbef2979e312abb5f7f42/thys/examples/Bin_Search.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.8723473630627234, "lm_q1q2_score": 0.783102116128437}}
{"text": "theory Submission\n  imports Defs\nbegin\n\ntype_synonym vname = string\n\n(* Arithmetic expressions *)\n\ndatatype aexp = N nat | V vname | Plus aexp aexp \n\nfun subterms :: \"aexp ⇒ aexp set\" where\n  \"subterms (N n) = {N n}\" |\n  \"subterms (V v) = {V v}\" |\n  \"subterms (Plus e⇩1 e⇩2) = {Plus e⇩1 e⇩2} ∪ subterms e⇩1 ∪ subterms e⇩2\"\n\nlemma e_is_subterm_e: \"e ∈ subterms e\" \n  apply(induction e)\n  apply(auto)\n  done\n\ndefinition \"strict_subterms e = subterms e - {e}\"\n\nlemma strict_subt_le_subt: \"strict_subterms e ⊂ subterms e\"\n  using e_is_subterm_e order_less_le strict_subterms_def by auto \n\nlemma e_does_not_contain_e: \"e ∉ strict_subterms e\"\n  by (simp add: strict_subterms_def)\n\nlemma subt_trans: \"f ∈ subterms e ⟹ g ∈ subterms f ⟹ g ∈ subterms e\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma subt_not_parent: \"e ≠ f ⟹ f ∈ subterms e ⟹ e ∉ subterms f\"\nproof(induction e arbitrary: f)\n  case (Plus e1 e2)\n  have \"f ∈ subterms e1 ∨ f ∈ subterms e2\" using Plus.prems(1) Plus.prems(2) by auto \n  then show ?case\n  proof(cases \"f ∈ subterms e1\")\n    case True\n    then show ?thesis\n    proof(cases \"f = e1\")\n      case True\n      then show ?thesis using Plus.IH(1) Plus.prems(2) by force \n    next\n      case False\n      have \"e1 ∉ subterms f\" using False Plus.IH(1) True by presburger\n      moreover\n      have \"e1 ∈ subterms (Plus e1 e2)\" using e_is_subterm_e by auto\n      moreover\n      have \"(Plus e1 e2) ∉ subterms f\" using calculation(1) calculation(2) subt_trans by blast \n      ultimately\n      show ?thesis by blast \n    qed\n  next\n    case False\n    have \"f ∈ subterms e2\" using False ‹f ∈ subterms e1 ∨ f ∈ subterms e2› by auto \n    then show ?thesis\n    proof(cases \"f = e2\")\n      case True\n      then show ?thesis using Plus.IH(2) Plus.prems(2) by force \n    next\n      case False\n      have \"e2 ∉ subterms f\" using False Plus.IH(2) ‹f ∈ subterms e2› by presburger \n      moreover\n      have \"e2 ∈ subterms (Plus e1 e2)\" using e_is_subterm_e by fastforce \n      moreover\n      have \"(Plus e1 e2) ∉ subterms f\" using calculation(1) calculation(2) subt_trans by blast \n      ultimately\n      show ?thesis by blast \n    qed\n  qed\nqed simp_all\n\nfun strict_subterms' :: \"aexp ⇒ aexp set\" where\n  \"strict_subterms' (N _) = {}\" |\n  \"strict_subterms' (V _) = {}\" |\n  \"strict_subterms' (Plus e⇩1 e⇩2) = subterms e⇩1 ∪ subterms e⇩2\"\n\nlemma strict_subt_eq_strict_subt': \"strict_subterms e = strict_subterms' e\"\nproof(cases e)\n  case (Plus e⇩1 e⇩2)\n  have \"strict_subterms e = subterms e - {e}\" using strict_subterms_def by force \n  also have \"… = ({Plus e⇩1 e⇩2} ∪ subterms e⇩1 ∪ subterms e⇩2) - {Plus e⇩1 e⇩2}\"\n    using Plus subterms.simps(3) by presburger \n  then show ?thesis\n    using Plus Un_insert_left subt_not_parent calculation e_is_subterm_e by fastforce \nqed(simp_all add:strict_subterms_def)\n\ncorollary strict_subt_of_plus: \"strict_subterms (Plus e⇩1 e⇩2) = subterms e⇩1 ∪ subterms e⇩2\"\n  by (simp add: strict_subt_eq_strict_subt')\n\nfun vars :: \"aexp ⇒ vname set\" where\n  \"vars (N n) = {}\" |\n  \"vars (V v) = {v}\" |\n  \"vars (Plus e⇩1 e⇩2) = vars e⇩1 ∪ vars e⇩2\"\n\nlemma finite_vars: \"finite (vars e)\"\n  apply(induction e)\n  apply(auto)\n  done\n\n(* Substitution *)\n\nfun substitute :: \"vname ⇒ aexp ⇒ aexp ⇒ aexp\" where\n  \"substitute v (N n) _  = (N n)\" |\n  \"substitute v (V v') e = (if v = v' then e else (V v'))\" |\n  \"substitute v (Plus e⇩1 e⇩2) e = Plus (substitute v e⇩1 e) (substitute v e⇩2 e)\"\n\nlemma substitute_eq: \"substitute v e (V v) = e\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma substitute_var_not_int_exp: \"v ∉ vars e ⟹ substitute v e x = e\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma substitute_intermediate_var: \n  \"y ∉ vars e ⟹ substitute y (substitute x e (V y)) e' = substitute x e e'\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma substitute_change_order: \"x ≠ y ⟹ x ∉ vars u ⟹ \n    substitute y (substitute x e t) u = substitute x (substitute y e u) (substitute y t u)\"\n  apply(induction e)\n  apply(auto simp add:substitute_var_not_int_exp)\n  done\n\nlemma substitute_flip: \"x ≠ y ⟹ y ∉ vars t ⟹ x ∉ vars u ⟹\n  substitute y (substitute x e t) u = substitute x (substitute y e u) t\"\n  apply(induction e)\n  apply(auto simp add:substitute_var_not_int_exp)\n  done\n\nlemma substitution_no_new_vars: \"vars (substitute v e t) ⊆ vars e ∪ vars t\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma substitution_removes_var: \"v ∉ vars t ⟹ v ∉ vars (substitute v e t)\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma no_vars_e_eq_sub_e: \"vars e = {} ⟹ substitute v e a = e\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma subst_adds_subt: \"v ∈ vars e ⟹ t ∈ subterms (substitute v e t)\"\n  apply(induction e)\n  apply(auto simp add:e_is_subterm_e)\n  done\n\nlemma subst_is_strict_subt: \"e ≠ V v ⟹ v ∈ vars e ⟹ t ∈ strict_subterms (substitute v e t)\"\nproof-\n  assume \"e ≠ V v\" \"v ∈ vars e\"\n  then show ?thesis\n  proof(cases e)\n    case (N x1)\n    then show ?thesis using ‹v ∈ vars e› by auto \n  next\n    case (V x2)\n    then show ?thesis using ‹e ≠ V v› ‹v ∈ vars e› by force \n  next\n    case (Plus e1 e2)\n    have \"v ∈ vars e1 ∨ v ∈ vars e2\" using Plus ‹v ∈ vars e› by auto\n    have \"∃f1 f2. substitute v e t = Plus f1 f2\" using Plus by force \n    from this obtain f1 f2 where 0: \"substitute v e t = Plus f1 f2\" by blast\n    then show ?thesis\n    proof(cases \"v ∈ vars e1\")\n      case True\n      have \"t ∈ subterms f1\" using 0 Plus True subst_adds_subt by auto \n      then show ?thesis by (simp add: 0 strict_subt_of_plus) \n    next\n      case False\n      have \"v ∈ vars e2\" using False ‹v ∈ vars e1 ∨ v ∈ vars e2› by force \n      hence \"t ∈ subterms f2\" using 0 Plus ‹v ∈ vars e2› subst_adds_subt by auto \n      then show ?thesis by (simp add: 0 strict_subt_of_plus) \n    qed\n  qed\nqed\n\nlemma e_not_eq_subst: \"e ≠ V v ⟹ v ∈ vars e ⟹ substitute v e t ≠ t\"\nproof(induction e)\n  case (Plus e1 e2)\n  have 0: \"v ∈ vars e1 ∨ v ∈ vars e2\" using Plus.prems(2) by auto \n  then show ?case \n  proof(cases \"v ∈ vars e1\")\n    case True\n    then show ?thesis\n    proof(cases \"e1 = V v\")\n      case False\n      then show ?thesis\n        by (metis Plus.prems(1) Plus.prems(2) e_does_not_contain_e subst_is_strict_subt) \n    qed simp\n  next\n    case False\n    have \"v ∈ vars e2\" using 0 False by simp\n    then show ?thesis\n    proof(cases \"e2 = V v\")\n      case False\n      then show ?thesis\n        by (metis Plus.prems(1) Plus.prems(2) e_does_not_contain_e subst_is_strict_subt) \n    qed simp\n  qed\nqed simp_all\n\nlemma subst_pres_subt: \"f ∈ subterms e ⟹ substitute v f t ∈ subterms (substitute v e t)\"\n  apply(induction e)\n  apply(auto simp add:e_is_subterm_e)\n  done\n\nlemma subst_other_vars_in_e: \"x ≠ v ⟹ x ∈ vars e ⟹ x ∈ vars (substitute v e t)\"\n  apply(induction e)\n  apply(auto)\n  done\n\nlemma vars_subst_e_sub_vars_e: \"vars t ⊆ vars e ⟹ vars (substitute v e t) ⊆ vars e\"\n  using substitution_no_new_vars by blast\n\nlemma vars_subst_e_strict_sub_vars_e: \n  \"vars t ⊆ vars e ⟹ v ∈ vars e ⟹ v ∉ vars t ⟹ vars (substitute v e t) ⊂ vars e\"\n  by (metis vars_subst_e_sub_vars_e psubsetI substitution_removes_var)\n\n(* Simultaneous Substitutions *)\n\ntype_synonym substitutions = \"(vname * aexp) list\"\n\nfun substitute' :: \"substitutions ⇒ aexp ⇒ aexp\" where\n  \"substitute' [] e = e\" |\n  \"substitute' ((v, e')#st) e = substitute' st (substitute v e e')\"\n\nlemma no_vars_e_eq_sub'_e: \"vars e = {} ⟹ substitute' s e = e\"\n  apply(induction s)\n  apply(auto simp add:no_vars_e_eq_sub_e)\n  done\n\nlemma not_eq_impl_subst_not_eq:\n  \"f ∈ subterms e ⟹ e ≠ f ⟹ substitute v e t ≠ substitute v f t\"\nproof(induction e)\n  case (Plus e1 e2)\n  have 0:\"f ∈ subterms e1 ∨ f ∈ subterms e2\" using Plus.prems(1) Plus.prems(2) by auto\n  then show ?case\n  proof(cases \"f ∈ subterms e1\")\n    case True\n    then show ?thesis\n    proof(cases \"e1 = f\")\n      case False\n      have \"substitute v e1 t ≠ substitute v f t\"\n        using False Plus.IH(1) True by linarith\n      then show ?thesis\n        by (metis True Un_iff e_does_not_contain_e strict_subt_of_plus subst_pres_subt substitute.simps(3)) \n    qed simp\n  next\n    case False\n    have \"f ∈ subterms e2\" using False 0 by force \n    then show ?thesis\n    proof(cases \"e2 = f\")\n      case False\n      have \"substitute v e2 t ≠ substitute v f t\"\n        using False Plus.IH(2) ‹f ∈ subterms e2› by fastforce \n      then show ?thesis\n        by (metis UnI2 ‹f ∈ subterms e2› e_is_subterm_e subst_pres_subt subt_not_parent subterms.simps(3)) \n    qed simp\n  qed\nqed simp_all\n\nlemma not_eq_impl_subst'_not_eq: \n  \"f ∈ subterms e ⟹ e ≠ f ⟹ substitute' s e ≠ substitute' s f\"\nproof(induction s arbitrary: e f)\n  case (Cons sh st)\n  have \"∃a e'. sh = (a, e')\" by simp \n  from this obtain a e' where \"sh = (a, e')\" by blast\n  have \"substitute' (sh#st) e = substitute' st (substitute a e e')\" using ‹sh = (a, e')› by auto \n  moreover\n  have \"substitute' (sh#st) f = substitute' st (substitute a f e')\" using ‹sh = (a, e')› by auto \n  ultimately\n  have \"substitute a f e' ≠ substitute a e e'\" \n    by (metis Cons.prems(1) Cons.prems(2) not_eq_impl_subst_not_eq)\n  moreover\n  have \"substitute a f e' ∈ subterms (substitute a e e')\"\n    using Cons.prems(1) subst_pres_subt by presburger \n  ultimately\n  show ?case using Cons.IH ‹sh = (a, e')› substitute'.simps(2) by presburger \nqed simp\n\nlemma plus_subst_to_plus: \"∃f⇩1 f⇩2. substitute' s (Plus e⇩1 e⇩2) = Plus f⇩1 f⇩2\"\nproof(induction s arbitrary: e⇩1 e⇩2)\n  case Nil\n  then show ?case by simp \nnext\n  case (Cons sh st)\n  have \"∃a e'. sh = (a, e')\" by simp \n  from this obtain a e' where \"sh = (a, e')\" by blast\n  hence \"substitute' (Cons sh st) (Plus e⇩1 e⇩2) = \n    substitute' st (Plus (substitute a e⇩1 e') (substitute a e⇩2 e'))\" by simp\n  moreover\n  have \"∃f⇩1 f⇩2. substitute' st (Plus (substitute a e⇩1 e') (substitute a e⇩2 e')) =\n    Plus f⇩1 f⇩2\" using local.Cons by force \n  ultimately \n  show ?case by presburger \nqed\n\n(* Unifier *)\n\ndefinition \"unifiable e⇩1 e⇩2 ⟷  (∃s. substitute' s e⇩1 = substitute' s e⇩2)\"\ndefinition \"unifier s e⇩1 e⇩2 ⟷ (substitute' s e⇩1 = substitute' s e⇩2)\"\n\nlemma unifier_eq_unifiable: \"unifiable e⇩1 e⇩2 ⟷ (∃s. unifier s e⇩1 e⇩2)\"\nproof\n  assume \"unifiable e⇩1 e⇩2\"\n  then show \"∃s. unifier s e⇩1 e⇩2\" \n    using unifiable_def unifier_def by auto \nnext\n  assume \"∃s. unifier s e⇩1 e⇩2\"\n  then show \"unifiable e⇩1 e⇩2\"\n    using unifiable_def unifier_def by auto \nqed\n\nlemma unifier_com: \"unifier s e⇩1 e⇩2 ⟷ unifier s e⇩2 e⇩1\"\n  using unifier_def by fastforce \n\nlemma v_in_e_not_unif: \"v ∈ vars e ⟹ V v ≠ e ⟹ ¬unifiable (V v) e\" \nproof\n  assume assm0: \"v ∈ vars e\" \n  assume assm1: \"V v ≠ e\"\n  assume assm2: \"unifiable (V v) e\"\n  hence \"∃s. unifier s (V v) e\" using unifier_eq_unifiable by auto \n  from this obtain s where s_unif: \"unifier s (V v) e\" by blast\n  have \"v ∈ vars e ⟹ V v ≠ e ⟹ unifier s (V v) e ⟹ False\"\n  proof(induction s arbitrary: e)\n    case Nil\n    then show ?case by (simp add: unifier_def) \n  next\n    case (Cons sh st)\n    have \"∃a e'. sh = (a, e')\" by simp\n    from this obtain a e' where \" sh = (a, e')\" by blast\n    have \"(substitute' (Cons sh st) e = substitute' (Cons sh st) (V v))\"\n      using Cons.prems(3) unifier_def by fastforce \n    hence 0: \"substitute' st (substitute a e e') = substitute' st (substitute a (V v) e')\"\n      by (simp add: ‹sh = (a, e')›)\n    then show ?case\n    proof(cases \"a = v\")\n      case True\n      have \"substitute a (V v) e' = e'\" by (simp add: True)\n      moreover\n      have \"e' ∈ subterms (substitute a e e')\" using assm0\n        using Cons.prems(1) True subst_adds_subt by presburger\n      moreover\n      have \"substitute a e e' ≠ e'\"\n        using Cons.prems(1) Cons.prems(2) True e_not_eq_subst by auto \n      ultimately\n      show ?thesis using 0 not_eq_impl_subst'_not_eq by auto \n    next\n      case False\n      have 1:\"substitute a (V v) e' = (V v)\" by (simp add: False)\n      hence \"substitute' st (substitute a e e') = substitute' st (V v)\" using 0 by presburger \n      moreover \n      have \"(V v) ∈ subterms (substitute a e e')\"\n        by (metis Cons.prems(1) 1 subst_adds_subt subst_pres_subt substitute_eq)\n      moreover\n      have \"substitute' st (substitute a e e') ≠ substitute' st (V v)\"\n        by (metis \"1\" Cons.prems(1) Cons.prems(2) calculation(2) not_eq_impl_subst'_not_eq not_eq_impl_subst_not_eq psubsetD strict_subt_le_subt subst_is_strict_subt substitute_eq) \n      ultimately\n      have \"False\" by blast \n      then show ?thesis.\n    qed\n  qed\n  thus False using assm0 assm1 s_unif by fastforce \nqed\n\nfun have_common_root :: \"aexp ⇒ aexp ⇒ bool\" where\n  \"have_common_root (N _) (N _) = True\" |\n  \"have_common_root (V _) (V _) = True\" |\n  \"have_common_root (Plus _ _) (Plus _ _) = True\" |\n  \"have_common_root _ _ = False\"\n\nfun is_var :: \"aexp ⇒ bool\" where\n  \"is_var (V _) = True\" |\n  \"is_var _ = False\"\n\nlemma no_common_root_no_var_impl_non_unif:\n  \"¬have_common_root e⇩1 e⇩2 ⟹ ¬is_var e⇩1 ⟹ ¬is_var e⇩2 ⟹ ¬unifiable e⇩1 e⇩2\"\nproof(induction e⇩1 e⇩2 rule:have_common_root.induct)\n  case (\"4_3\" f⇩1 f⇩2 n)\n  have \"¬unifiable (Plus f⇩1 f⇩2) (N n)\"\n  proof(rule ccontr)\n    assume \"¬¬unifiable (Plus f⇩1 f⇩2) (N n)\"\n    hence \"unifiable (Plus f⇩1 f⇩2) (N n)\" by blast\n    hence \"∃s. unifier s (Plus f⇩1 f⇩2) (N n)\" using unifier_eq_unifiable by auto \n    from this obtain s where \"unifier s (Plus f⇩1 f⇩2) (N n)\" by blast\n    hence 0: \"substitute' s (Plus f⇩1 f⇩2) = substitute' s (N n)\" using unifier_def by blast \n    hence \"∃f⇩1' f⇩2'. substitute' s (Plus f⇩1 f⇩2) = Plus f⇩1' f⇩2'\" using plus_subst_to_plus by blast\n    from this obtain f⇩1' f⇩2' where \"substitute' s (Plus f⇩1 f⇩2) = Plus f⇩1' f⇩2'\" by blast\n    moreover\n    have \"substitute' s (N n) = N n\" by (simp add: no_vars_e_eq_sub'_e) \n    moreover\n    have \"substitute' s (Plus f⇩1 f⇩2) ≠ substitute' s (N n)\"\n      by (simp add: calculation(1) calculation(2)) \n    then show False using 0 by blast\n  qed\n  then show ?case by simp \nnext\n  case (\"4_7\" n e⇩1 e⇩2)\n  have \"unifiable (N n) (Plus e⇩1 e⇩2) = unifiable (Plus e⇩1 e⇩2) (N n)\"\n    by (simp add: unifier_com unifier_eq_unifiable)\n  moreover\n  have \"¬unifiable (Plus e⇩1 e⇩2) (N n)\" \n    by (metis aexp.distinct(3) no_vars_e_eq_sub'_e plus_subst_to_plus unifiable_def vars.simps(1)) \n  then show ?case by (simp add: calculation) \nqed simp_all\n\nlemma subst_plus_subst_child:\n  \"substitute' s (Plus e⇩1 e⇩2) = Plus (substitute' s e⇩1) (substitute' s e⇩2)\"\n  apply(induction s arbitrary: e⇩1 e⇩2)\n  apply(auto)\n  done\n\nlemma subst_subst': \"substitute' (s@[(a, e')]) e = substitute a (substitute' s e) e'\"\n  apply(induction s e rule: substitute'.induct)\n  apply(auto)\n  done\n\n(* Finding a neccessary improvement for the substitution *)\n\ndatatype substitution = None | NonSubst | Subst vname aexp\n\nfun find_substitution :: \"aexp ⇒ aexp ⇒ substitution\" where\n  \"find_substitution (N n⇩1) (N n⇩2) = (if n⇩1 = n⇩2 then None else NonSubst)\" |\n  \"find_substitution (N n) (V v) = Subst v (N n)\" |\n  \"find_substitution (N _) (Plus _ _) = NonSubst\" |\n  \"find_substitution (V v) (N n) = Subst v (N n)\" |\n  \"find_substitution (V v⇩1) (V v⇩2) = (if v⇩1 = v⇩2 then None else Subst v⇩1 (V v⇩2))\" |\n  \"find_substitution (V v) (Plus e⇩1 e⇩2) = (if v ∈ vars (Plus e⇩1 e⇩2) then NonSubst else Subst v (Plus e⇩1 e⇩2))\" |\n  \"find_substitution (Plus _ _) (N _) = NonSubst\" |\n  \"find_substitution (Plus e⇩1 e⇩2) (V v) = (if v ∈ vars (Plus e⇩1 e⇩2) then NonSubst else Subst v (Plus e⇩1 e⇩2))\" |\n  \"find_substitution (Plus e⇩1 e⇩2) (Plus f⇩1 f⇩2) = (case find_substitution e⇩1 f⇩1 of\n      None ⇒ find_substitution e⇩2 f⇩2 |\n      NonSubst ⇒ NonSubst |\n      Subst v e ⇒ Subst v e\n  )\"\n\nlemma find_subst_plus_in_child: \n  \"find_substitution (Plus e⇩1 e⇩2) (Plus f⇩1 f⇩2) = Subst v e ⟹ \n  find_substitution e⇩1 f⇩1 = Subst v e ∨ find_substitution e⇩2 f⇩2 = Subst v e\"\n  by (metis find_substitution.simps(9) substitution.exhaust substitution.simps(10) substitution.simps(8) substitution.simps(9))\n\nlemma no_subst_es_eq:\"find_substitution e⇩1 e⇩2 = None ⟷ e⇩1 = e⇩2\" \n  apply(induction e⇩1 e⇩2 rule:find_substitution.induct)\n  apply(auto split:substitution.splits)\n  done\n\nlemma subst_found_es_eq: \"find_substitution e⇩1 e⇩2 = Subst v e' ⟹ e⇩1 ≠ e⇩2\"\n  apply(induction e⇩1 e⇩2 rule:find_substitution.induct)\n  apply(auto split:substitution.splits)\n  done\n\nlemma non_subst_es_not_eq: \"find_substitution e⇩1 e⇩2 = NonSubst ⟹ e⇩1 ≠ e⇩2\"\n  apply(induction e⇩1 e⇩2 rule:find_substitution.induct)\n  apply(auto split:substitution.splits)\n  done\n\nlemma find_subst_e_in_es: \"find_substitution e⇩1 e⇩2 = Subst v e ⟹ vars e ⊆ vars e⇩1 ∪ vars e⇩2\"\n  apply(induction e⇩1 e⇩2 rule:find_substitution.induct)\n  apply(auto split:if_splits substitution.splits)\n  done\n\nlemma find_subst_var_in_es: \"find_substitution e⇩1 e⇩2 = Subst v e ⟹ v ∈ vars e⇩1 ∪ vars e⇩2\"\n  apply(induction e⇩1 e⇩2 rule:find_substitution.induct)\n  apply(auto split:if_splits substitution.splits)\n  done\n\nlemma find_subst_v_not_in_e: \"find_substitution e⇩1 e⇩2 = Subst v e ⟹ v ∉ vars e\"\n  apply(induction e⇩1 e⇩2 rule:find_substitution.induct)\n  apply(auto split:if_splits substitution.splits)\n  done\n\nlemma find_subst_none_impl_unif:\n  \"find_substitution e⇩1 e⇩2 = None ⟹ unifiable e⇩1 e⇩2\"\n  by (simp add: no_subst_es_eq unifiable_def)\n\nlemma find_subst_non_subst_impl_not_unif:\n  \"find_substitution e⇩1 e⇩2 = NonSubst ⟹ ¬unifiable e⇩1 e⇩2\"\nproof(rule ccontr)\n  assume assm0: \"find_substitution e⇩1 e⇩2 = NonSubst\"\n  assume assm1: \"¬ ¬unifiable e⇩1 e⇩2\"\n  hence \"unifiable e⇩1 e⇩2\" by blast\n  hence \"∃s. unifier s e⇩1 e⇩2\" using unifier_eq_unifiable by blast \n  from this obtain s where \"unifier s e⇩1 e⇩2\" by blast\n  have \"find_substitution e⇩1 e⇩2 = NonSubst ⟹ unifier s e⇩1 e⇩2 ⟹ False\"\n  proof(induction e⇩1 e⇩2 rule: find_substitution.induct)\n    case (1 n⇩1 n⇩2)\n    then show ?case by (simp add: no_vars_e_eq_sub'_e unifier_def) \n  next\n    case (3 uu uv uw)\n    then show ?case using no_common_root_no_var_impl_non_unif unifier_eq_unifiable by auto \n  next\n    case (5 v⇩1 v⇩2)\n    then show ?case by (metis find_substitution.simps(5) substitution.distinct(1) substitution.distinct(5)) \n  next\n    case (6 v e⇩1 e⇩2)\n    then show ?case\n      by (metis aexp.simps(9) find_substitution.simps(6) substitution.distinct(6) unifier_eq_unifiable v_in_e_not_unif) \n  next\n    case (7 ux uy uz)\n    then show ?case\n      using no_common_root_no_var_impl_non_unif unifier_eq_unifiable by auto \n  next\n    case (8 e⇩1 e⇩2 v)\n    then show ?case\n      by (metis aexp.distinct(5) find_substitution.simps(8) substitution.distinct(5) unifiable_def unifier_def v_in_e_not_unif) \n  next\n    case (9 e⇩1 e⇩2 f⇩1 f⇩2)\n    then show ?case\n    proof(induction \"find_substitution e⇩1 f⇩1\" rule:substitution.induct)\n      case None\n      then show ?case using None.hyps None.prems(2) None.prems(4) subst_plus_subst_child unifier_def by auto \n    next\n      case NonSubst\n      then show ?case by (simp add: subst_plus_subst_child unifier_def) \n    next\n      case (Subst x1 x2)\n      then show ?case by (metis find_substitution.simps(9) substitution.distinct(5) substitution.simps(10)) \n    qed\n  qed simp_all\n  then show False using ‹unifier s e⇩1 e⇩2› assm0 by blast \nqed\n\nlemma find_subst_impl_unif_impl_unif_e: \n  \"find_substitution e⇩1 e⇩2 = Subst v t ⟹ unifiable (substitute v e⇩1 e) (substitute v e⇩2 e) ⟹ unifiable e⇩1 e⇩2\"\n  by (metis substitute'.simps(2) unifiable_def)\n\ncorollary find_subst_not_unif_impl_subst_not_unif:\n  \"find_substitution e⇩1 e⇩2 = Subst v e ⟹ ¬unifiable e⇩1 e⇩2 ⟹ ¬unifiable (substitute v e⇩1 e) (substitute v e⇩2 e)\"\n  using find_subst_impl_unif_impl_unif_e by blast\n\nlemma find_subst_le_vars: \"find_substitution e⇩1 e⇩2 = Subst v t ⟹ \n  vars (substitute v e⇩1 t) ∪ vars (substitute v e⇩2 t) ⊂ vars e⇩1 ∪ vars e⇩2\"\n  by (metis find_subst_e_in_es find_subst_v_not_in_e find_subst_var_in_es substitute.simps(3) vars.simps(3) vars_subst_e_strict_sub_vars_e)\n\nlemma card_vars_union_decr:\n  \"find_substitution e⇩1 e⇩2 = Subst v t ⟹ \n  card (vars (substitute v e⇩1 t) ∪ vars (substitute v e⇩2 t)) < card (vars e⇩1 ∪ vars e⇩2)\"\nproof-\n  assume assm:\"find_substitution e⇩1 e⇩2 = Subst v t\"\n  let ?s⇩1 = \"vars (substitute v e⇩1 t) ∪ vars (substitute v e⇩2 t)\"\n  let ?s⇩2 = \"vars e⇩1 ∪ vars e⇩2\"\n  have \"finite ?s⇩2\" by (simp add: finite_vars)\n  moreover\n  have \"?s⇩1 ⊂ ?s⇩2\" using assm find_subst_le_vars by presburger \n  ultimately \n  show ?thesis using psubset_card_mono[of ?s⇩2 ?s⇩1] by blast \nqed\n\n(* Unification of arithmetic expressions  *)\n\ndatatype aexpUnif = NonUnif | Unif substitutions\n\nfunction unify' :: \"substitutions ⇒ aexp ⇒ aexp ⇒ aexpUnif\" where\n  \"unify' s e⇩1 e⇩2 = (case (substitute' s e⇩1, substitute' s e⇩2) of\n    (s⇩1, s⇩2) ⇒ (if s⇩1 = s⇩2 then Unif s else \n      (case find_substitution s⇩1 s⇩2 of\n        None ⇒ NonUnif |\n        NonSubst ⇒ NonUnif |\n        Subst v e ⇒ unify' (s@[(v, e)]) e⇩1 e⇩2\n      )\n    )\n  )\"\nby pat_completeness auto\ntermination \n  apply(relation \"measure (λ(s, e⇩1, e⇩2). card (vars (substitute' s e⇩1) ∪ vars (substitute' s e⇩2)))\")\n  by(auto simp add:card_vars_union_decr subst_subst')\n\ndefinition \"unify e⇩1 e⇩2 = unify' [] e⇩1 e⇩2\"\n\nvalue \"unify (V x) (N 3)\"\nvalue \"unify (Plus (V x) (N 3)) (Plus (N 3) (N 3))\"\nvalue \"unify (Plus (N 4) (N 3)) (Plus (N 3) (N 3))\"\nvalue \"unify (Plus (V ''x'') (N 3)) (Plus (V ''y'') (N 3))\"\nvalue \"unify (Plus (N 3) (N 3)) (Plus (V x) (N 3))\"\nvalue \"unify' [(''x'', N 3)] (N 3) (N 5)\"\nvalue \"unify (Plus (N 3) (N 4)) (Plus (V ''x'') (N 4))\"\nvalue \"unify (Plus (Plus (V ''y'') (N 3)) (N 4)) (Plus (V ''x'') (N 4))\"\n\nlemma unify'_es_eq: \n  \"unify' s e⇩1 e⇩2 = Unif s' ⟹ (substitute' s' e⇩1) = (substitute' s' e⇩2)\" \nproof(induction s e⇩1 e⇩2 arbitrary: s' rule:unify'.induct)\n  case (1 s e⇩1 e⇩2)\n  let ?s⇩1 = \"substitute' s e⇩1\"\n  let ?s⇩2 = \"substitute' s e⇩2\"\n  from 1 show ?case \n  proof(cases \"?s⇩1 = ?s⇩2\")\n    case True\n    then show ?thesis using \"1.prems\" by fastforce \n  next\n    case False\n    have \"∃v e. find_substitution ?s⇩1 ?s⇩2 = Subst v e\"\n      by (smt (verit) \"1.prems\" False aexpUnif.distinct(1) no_subst_es_eq old.prod.case substitution.exhaust substitution.simps(9) unify'.simps)\n    from this obtain v e where 0:\"find_substitution ?s⇩1 ?s⇩2 = Subst v e\" by blast\n    hence \"unify' s e⇩1 e⇩2 = unify' (s@[(v, e)]) e⇩1 e⇩2\" using False by auto \n    moreover\n    have \"unify' (s@[(v, e)]) e⇩1 e⇩2 = Unif s'\"\n      using \"1.prems\" calculation by presburger \n    ultimately\n    show ?thesis using \"1.IH\" False 0 by blast \n  qed\nqed\n\ncorollary unifiy'_unifies: \"unify' s e⇩1 e⇩2 = Unif s' ⟹ unifier s' e⇩1 e⇩2\"\n  using unifier_def unify'_es_eq by blast\n\ntheorem unify_correct: \"unify e⇩1 e⇩2 = Unif s ⟹ unifier s e⇩1 e⇩2\"\n  by (metis unifiy'_unifies unify_def) \n\n(* TODO *)\nlemma unify'_non_unif_invar_under_subst: \n  \"unify' [] e⇩1 e⇩2 = NonUnif ⟹ unify' [] (substitute v e⇩1 e) (substitute v e⇩2 e) = NonUnif\" \n  nitpick sorry\n\nlemma unify'_non_unif_no_unifier:\n  \"unify' [] e⇩1 e⇩2 = NonUnif ⟹ ∄s. unifier s e⇩1 e⇩2\" \nproof(rule ccontr)\n  assume \"unify' [] e⇩1 e⇩2 = NonUnif\"\n  assume \"¬(∄s. unifier s e⇩1 e⇩2)\"\n  hence \"∃s. unifier s e⇩1 e⇩2\" by simp\n  from this obtain s where \"unifier s e⇩1 e⇩2\" by blast\n  have \"unify' [] e⇩1 e⇩2 = NonUnif ⟹ unifier s e⇩1 e⇩2 ⟹ False\"\n  proof(induction s arbitrary: e⇩1 e⇩2)\n    case Nil\n    then show ?case\n      by (simp add: unifier_def) \n  next\n    case (Cons a s)\n    then show ?case\n      by (metis prod.exhaust_sel substitute'.simps(2) unifier_def unify'_non_unif_invar_under_subst) \n  qed\n  then show False using ‹unifier s e⇩1 e⇩2› ‹unify' [] e⇩1 e⇩2 = NonUnif› by fastforce \nqed\n\ncorollary unify'_correct': \"unify' [] e⇩1 e⇩2 = NonUnif ⟹ ¬unifiable e⇩1 e⇩2\"\n  using unify'_non_unif_no_unifier unifier_eq_unifiable by presburger\n\ncorollary unify_correct': \"unify e⇩1 e⇩2 = NonUnif ⟹ ¬unifiable e⇩1 e⇩2\"\n  by (simp add: unify'_correct' unify_def) \n\nlemma unify_complete: \"unifiable e⇩1 e⇩2 ⟹ (∃s. unify' [] e⇩1 e⇩2 = Unif s)\"\n  by (meson aexpUnif.exhaust unify'_correct') \n\ntheorem unify_complete_correct: \"unifiable e⇩1 e⇩2 ⟷ (∃s. unify e⇩1 e⇩2 = Unif s ∧ unifier s e⇩1 e⇩2)\"\n  by (metis unifier_eq_unifiable unifiy'_unifies unify_complete unify_def)\n\ncorollary unify_complete_correct': \"¬unifiable e⇩1 e⇩2 ⟷ unify e⇩1 e⇩2 = NonUnif\"\n  by (metis aexpUnif.exhaust aexpUnif.simps(3) unify_complete_correct unifiy'_unifies unify_def) \n\nend\n", "meta": {"author": "nicolaifrech", "repo": "musical-computing-machine", "sha": "ce75b522503e330ec0808e37ffd2e8e86c28feed", "save_path": "github-repos/isabelle/nicolaifrech-musical-computing-machine", "path": "github-repos/isabelle/nicolaifrech-musical-computing-machine/musical-computing-machine-ce75b522503e330ec0808e37ffd2e8e86c28feed/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7830190297063295}}
{"text": "(*Author: Giuliano Losa *)\n\nheader {* Definition and properties of the longest common postfix of a set of lists *}\n\ntheory LCP\nimports Main \"~~/src/HOL/Library/Sublist\"\nbegin\n\ndefinition common_postfix_p :: \"('a list) set => 'a list => bool\" \n  -- {*Predicate that recognizes the common postfix of a set of lists*}\n  -- {*The common postfix of the empty set is the empty list*}\n  where\n  \"common_postfix_p \\<equiv> \\<lambda> xss xs . if xss = {} then xs = [] else ALL xs' . xs' \\<in> xss \\<longrightarrow> suffixeq xs xs'\"\n\ndefinition l_c_p_pred :: \"'a list set \\<Rightarrow> 'a list => bool\"\n  -- {*Predicate that recognizes the longest common postfix of a set of lists*}\n  where\n  \"l_c_p_pred \\<equiv> \\<lambda> xss xs . common_postfix_p xss xs \\<and> (ALL xs' . common_postfix_p xss xs' \\<longrightarrow> suffixeq xs' xs)\"\n\ndefinition l_c_p:: \"'a list set \\<Rightarrow> 'a list\"\n  -- {* The longest common postfix of a set of lists *}\n  where\n  \"l_c_p \\<equiv> \\<lambda> xss . THE xs . l_c_p_pred xss xs\"\n\nlemma l_c_p_ok: \"l_c_p_pred xss (l_c_p xss)\"\n  -- {*Proof that the definition of the longest common postfix of a set of lists is consistent*}\nproof %invisible -\n  have \"\\<exists>! x . l_c_p_pred xss x\"\n  proof (cases)\n    assume \"xss = {}\"\n    thus ?thesis by (auto simp add: l_c_p_pred_def common_postfix_p_def)\n  next\n    assume \"xss \\<noteq> {}\"\n    have \"\\<exists> x . l_c_p_pred xss x\"\n    proof -\n        -- {*By contradiction*}\n      { assume \"\\<forall> x . \\<not> l_c_p_pred xss x\"\n        from `xss \\<noteq> {}` obtain xs where \"xs \\<in> xss\" by auto\n        { fix n\n          have \"\\<exists> xs . common_postfix_p xss xs \\<and> length xs \\<ge> n\"\n          proof (induct n)\n            show \"\\<exists>xs . common_postfix_p xss xs \\<and> 0 \\<le> length xs\" by (auto simp add:common_postfix_p_def)\n          next\n            fix m\n            assume \"\\<exists> xs . common_postfix_p xss xs \\<and> length xs \\<ge> m\"\n            from this obtain xs where \"common_postfix_p xss xs\" and \"length xs \\<ge> m\" by auto\n            from `common_postfix_p xss xs` and  `\\<forall> x . \\<not> l_c_p_pred xss x` obtain xs' where \"common_postfix_p xss xs'\" and 1:\"\\<not> suffixeq xs' xs\" by (auto simp add: l_c_p_pred_def)\n            from `common_postfix_p xss xs` and `common_postfix_p xss xs'` have 2:\"suffixeq xs' xs \\<or> suffixeq xs xs'\" apply (auto simp add:common_postfix_p_def suffixeq_def split: split_if_asm) by (metis append_eq_append_conv2)\n            from 1 and 2 have \"suffixeq xs xs'\" and \"xs \\<noteq> xs'\" by auto\n            hence \"length xs' > length xs\" by (auto simp add:suffixeq_def)\n            with `common_postfix_p xss xs'` and `length xs \\<ge> m` show \"\\<exists> xs . common_postfix_p xss xs \\<and> length xs \\<ge> Suc m\" by auto\n          qed\n        }\n        from this[of \"Suc (length xs)\"] obtain xs' where \"common_postfix_p xss xs'\" and \"length xs' > length xs\" by auto\n        with `xs \\<in> xss` have False by (auto simp add:common_postfix_p_def suffixeq_def split:split_if_asm)\n      }\n      thus ?thesis by auto\n    qed\n    moreover have \"\\<forall> x y . l_c_p_pred xss x \\<and> l_c_p_pred xss y \\<longrightarrow> x = y\" by (force simp add:l_c_p_pred_def suffixeq_def)\n    ultimately show ?thesis by auto\n  qed\n  thus ?thesis by (auto simp add:l_c_p_def intro: theI'[of \"l_c_p_pred xss\"])\nqed\n\nlemma l_c_p_lemma: \n  -- {*A useful lemma*}\n  \"(ls \\<noteq> {} \\<and> (\\<forall> l \\<in> ls . (\\<exists> l' . l = l' @ xs))) \\<longrightarrow> suffixeq xs (l_c_p ls)\"\nproof %invisible -\n  { assume \"ls \\<noteq> {}\" and \"\\<forall> l \\<in> ls . (\\<exists> l' . l = l' @ xs)\"\n    hence \"common_postfix_p ls xs\" by (auto simp add:common_postfix_p_def suffixeq_def)\n    with l_c_p_ok have \"suffixeq xs (l_c_p ls)\" by (auto simp add: l_c_p_pred_def)\n  }\n  thus ?thesis by auto\nqed\n\nlemma l_c_p_common_postfix: \"common_postfix_p xss (l_c_p xss)\" \n  using l_c_p_ok[of xss] by (auto simp add:l_c_p_pred_def)\n\nlemma l_c_p_longest: \"common_postfix_p xss xs \\<longrightarrow> suffixeq xs (l_c_p xss)\"\n  using l_c_p_ok[of xss] by (auto simp add:l_c_p_pred_def)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Abortable_Linearizable_Modules/LCP.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8872046011730965, "lm_q1q2_score": 0.7828940715513837}}
{"text": "(*  Title:      HOL/Library/Indicator_Function.thy\n    Author:     Johannes Hoelzl (TU Muenchen)\n*)\n\nsection \\<open>Indicator Function\\<close>\n\ntheory Indicator_Function\nimports Complex_MainRLT Disjoint_Sets\nbegin\n\ndefinition \"indicator S x = of_bool (x \\<in> S)\"\n\ntext\\<open>Type constrained version\\<close>\nabbreviation indicat_real :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> real\" where \"indicat_real S \\<equiv> indicator S\"\n\nlemma indicator_simps[simp]:\n  \"x \\<in> S \\<Longrightarrow> indicator S x = 1\"\n  \"x \\<notin> S \\<Longrightarrow> indicator S x = 0\"\n  unfolding indicator_def by auto\n\nlemma indicator_pos_le[intro, simp]: \"(0::'a::linordered_semidom) \\<le> indicator S x\"\n  and indicator_le_1[intro, simp]: \"indicator S x \\<le> (1::'a::linordered_semidom)\"\n  unfolding indicator_def by auto\n\nlemma indicator_abs_le_1: \"\\<bar>indicator S x\\<bar> \\<le> (1::'a::linordered_idom)\"\n  unfolding indicator_def by auto\n\nlemma indicator_eq_0_iff: \"indicator A x = (0::'a::zero_neq_one) \\<longleftrightarrow> x \\<notin> A\"\n  by (auto simp: indicator_def)\n\nlemma indicator_eq_1_iff: \"indicator A x = (1::'a::zero_neq_one) \\<longleftrightarrow> x \\<in> A\"\n  by (auto simp: indicator_def)\n\nlemma indicator_UNIV [simp]: \"indicator UNIV = (\\<lambda>x. 1)\"\n  by auto\n\nlemma indicator_leI:\n  \"(x \\<in> A \\<Longrightarrow> y \\<in> B) \\<Longrightarrow> (indicator A x :: 'a::linordered_nonzero_semiring) \\<le> indicator B y\"\n  by (auto simp: indicator_def)\n\nlemma split_indicator: \"P (indicator S x) \\<longleftrightarrow> ((x \\<in> S \\<longrightarrow> P 1) \\<and> (x \\<notin> S \\<longrightarrow> P 0))\"\n  unfolding indicator_def by auto\n\nlemma split_indicator_asm: \"P (indicator S x) \\<longleftrightarrow> (\\<not> (x \\<in> S \\<and> \\<not> P 1 \\<or> x \\<notin> S \\<and> \\<not> P 0))\"\n  unfolding indicator_def by auto\n\nlemma indicator_inter_arith: \"indicator (A \\<inter> B) x = indicator A x * (indicator B x::'a::semiring_1)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_union_arith:\n  \"indicator (A \\<union> B) x = indicator A x + indicator B x - indicator A x * (indicator B x :: 'a::ring_1)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_inter_min: \"indicator (A \\<inter> B) x = min (indicator A x) (indicator B x::'a::linordered_semidom)\"\n  and indicator_union_max: \"indicator (A \\<union> B) x = max (indicator A x) (indicator B x::'a::linordered_semidom)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_disj_union:\n  \"A \\<inter> B = {} \\<Longrightarrow> indicator (A \\<union> B) x = (indicator A x + indicator B x :: 'a::linordered_semidom)\"\n  by (auto split: split_indicator)\n\nlemma indicator_compl: \"indicator (- A) x = 1 - (indicator A x :: 'a::ring_1)\"\n  and indicator_diff: \"indicator (A - B) x = indicator A x * (1 - indicator B x ::'a::ring_1)\"\n  unfolding indicator_def by (auto simp: min_def max_def)\n\nlemma indicator_times:\n  \"indicator (A \\<times> B) x = indicator A (fst x) * (indicator B (snd x) :: 'a::semiring_1)\"\n  unfolding indicator_def by (cases x) auto\n\nlemma indicator_sum:\n  \"indicator (A <+> B) x = (case x of Inl x \\<Rightarrow> indicator A x | Inr x \\<Rightarrow> indicator B x)\"\n  unfolding indicator_def by (cases x) auto\n\nlemma indicator_image: \"inj f \\<Longrightarrow> indicator (f ` X) (f x) = (indicator X x::_::zero_neq_one)\"\n  by (auto simp: indicator_def inj_def)\n\nlemma indicator_vimage: \"indicator (f -` A) x = indicator A (f x)\"\n  by (auto split: split_indicator)\n\nlemma mult_indicator_cong:\n  fixes f g :: \"_ \\<Rightarrow> 'a :: semiring_1\"\n  shows \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x) \\<Longrightarrow> indicator A x * f x = indicator A x * g x\"\n  by (auto simp: indicator_def)\n  \nlemma  \n  fixes f :: \"'a \\<Rightarrow> 'b::semiring_1\"\n  assumes \"finite A\"\n  shows sum_mult_indicator[simp]: \"(\\<Sum>x \\<in> A. f x * indicator B x) = (\\<Sum>x \\<in> A \\<inter> B. f x)\"\n    and sum_indicator_mult[simp]: \"(\\<Sum>x \\<in> A. indicator B x * f x) = (\\<Sum>x \\<in> A \\<inter> B. f x)\"\n  unfolding indicator_def\n  using assms by (auto intro!: sum.mono_neutral_cong_right split: if_split_asm)\n\nlemma sum_indicator_eq_card:\n  assumes \"finite A\"\n  shows \"(\\<Sum>x \\<in> A. indicator B x) = card (A Int B)\"\n  using sum_mult_indicator [OF assms, of \"\\<lambda>x. 1::nat\"]\n  unfolding card_eq_sum by simp\n\nlemma sum_indicator_scaleR[simp]:\n  \"finite A \\<Longrightarrow>\n    (\\<Sum>x \\<in> A. indicator (B x) (g x) *\\<^sub>R f x) = (\\<Sum>x \\<in> {x\\<in>A. g x \\<in> B x}. f x :: 'a::real_vector)\"\n  by (auto intro!: sum.mono_neutral_cong_right split: if_split_asm simp: indicator_def)\n\nlemma LIMSEQ_indicator_incseq:\n  assumes \"incseq A\"\n  shows \"(\\<lambda>i. indicator (A i) x :: 'a::{topological_space,zero_neq_one}) \\<longlonglongrightarrow> indicator (\\<Union>i. A i) x\"\nproof (cases \"\\<exists>i. x \\<in> A i\")\n  case True\n  then obtain i where \"x \\<in> A i\"\n    by auto\n  then have *:\n    \"\\<And>n. (indicator (A (n + i)) x :: 'a) = 1\"\n    \"(indicator (\\<Union>i. A i) x :: 'a) = 1\"\n    using incseqD[OF \\<open>incseq A\\<close>, of i \"n + i\" for n] \\<open>x \\<in> A i\\<close> by (auto simp: indicator_def)\n  show ?thesis\n    by (rule LIMSEQ_offset[of _ i]) (use * in simp)\nnext\n  case False\n  then show ?thesis by (simp add: indicator_def)\nqed\n\nlemma LIMSEQ_indicator_UN:\n  \"(\\<lambda>k. indicator (\\<Union>i<k. A i) x :: 'a::{topological_space,zero_neq_one}) \\<longlonglongrightarrow> indicator (\\<Union>i. A i) x\"\nproof -\n  have \"(\\<lambda>k. indicator (\\<Union>i<k. A i) x::'a) \\<longlonglongrightarrow> indicator (\\<Union>k. \\<Union>i<k. A i) x\"\n    by (intro LIMSEQ_indicator_incseq) (auto simp: incseq_def intro: less_le_trans)\n  also have \"(\\<Union>k. \\<Union>i<k. A i) = (\\<Union>i. A i)\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma LIMSEQ_indicator_decseq:\n  assumes \"decseq A\"\n  shows \"(\\<lambda>i. indicator (A i) x :: 'a::{topological_space,zero_neq_one}) \\<longlonglongrightarrow> indicator (\\<Inter>i. A i) x\"\nproof (cases \"\\<exists>i. x \\<notin> A i\")\n  case True\n  then obtain i where \"x \\<notin> A i\"\n    by auto\n  then have *:\n    \"\\<And>n. (indicator (A (n + i)) x :: 'a) = 0\"\n    \"(indicator (\\<Inter>i. A i) x :: 'a) = 0\"\n    using decseqD[OF \\<open>decseq A\\<close>, of i \"n + i\" for n] \\<open>x \\<notin> A i\\<close> by (auto simp: indicator_def)\n  show ?thesis\n    by (rule LIMSEQ_offset[of _ i]) (use * in simp)\nnext\n  case False\n  then show ?thesis by (simp add: indicator_def)\nqed\n\nlemma LIMSEQ_indicator_INT:\n  \"(\\<lambda>k. indicator (\\<Inter>i<k. A i) x :: 'a::{topological_space,zero_neq_one}) \\<longlonglongrightarrow> indicator (\\<Inter>i. A i) x\"\nproof -\n  have \"(\\<lambda>k. indicator (\\<Inter>i<k. A i) x::'a) \\<longlonglongrightarrow> indicator (\\<Inter>k. \\<Inter>i<k. A i) x\"\n    by (intro LIMSEQ_indicator_decseq) (auto simp: decseq_def intro: less_le_trans)\n  also have \"(\\<Inter>k. \\<Inter>i<k. A i) = (\\<Inter>i. A i)\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma indicator_add:\n  \"A \\<inter> B = {} \\<Longrightarrow> (indicator A x::_::monoid_add) + indicator B x = indicator (A \\<union> B) x\"\n  unfolding indicator_def by auto\n\nlemma of_real_indicator: \"of_real (indicator A x) = indicator A x\"\n  by (simp split: split_indicator)\n\nlemma real_of_nat_indicator: \"real (indicator A x :: nat) = indicator A x\"\n  by (simp split: split_indicator)\n\nlemma abs_indicator: \"\\<bar>indicator A x :: 'a::linordered_idom\\<bar> = indicator A x\"\n  by (simp split: split_indicator)\n\nlemma mult_indicator_subset:\n  \"A \\<subseteq> B \\<Longrightarrow> indicator A x * indicator B x = (indicator A x :: 'a::comm_semiring_1)\"\n  by (auto split: split_indicator simp: fun_eq_iff)\n\nlemma indicator_times_eq_if:\n  fixes f :: \"'a \\<Rightarrow> 'b::comm_ring_1\"\n  shows \"indicator S x * f x = (if x \\<in> S then f x else 0)\" \"f x * indicator S x = (if x \\<in> S then f x else 0)\"\n  by auto\n\nlemma indicator_scaleR_eq_if:\n  fixes f :: \"'a \\<Rightarrow> 'b::real_vector\"\n  shows \"indicator S x *\\<^sub>R f x = (if x \\<in> S then f x else 0)\"\n  by simp\n\nlemma indicator_sums:\n  assumes \"\\<And>i j. i \\<noteq> j \\<Longrightarrow> A i \\<inter> A j = {}\"\n  shows \"(\\<lambda>i. indicator (A i) x::real) sums indicator (\\<Union>i. A i) x\"\nproof (cases \"\\<exists>i. x \\<in> A i\")\n  case True\n  then obtain i where i: \"x \\<in> A i\" ..\n  with assms have \"(\\<lambda>i. indicator (A i) x::real) sums (\\<Sum>i\\<in>{i}. indicator (A i) x)\"\n    by (intro sums_finite) (auto split: split_indicator)\n  also have \"(\\<Sum>i\\<in>{i}. indicator (A i) x) = indicator (\\<Union>i. A i) x\"\n    using i by (auto split: split_indicator)\n  finally show ?thesis .\nnext\n  case False\n  then show ?thesis by simp\nqed\n\ntext \\<open>\n  The indicator function of the union of a disjoint family of sets is the\n  sum over all the individual indicators.\n\\<close>\n\nlemma indicator_UN_disjoint:\n  \"finite A \\<Longrightarrow> disjoint_family_on f A \\<Longrightarrow> indicator (\\<Union>(f ` A)) x = (\\<Sum>y\\<in>A. indicator (f y) x)\"\n  by (induct A rule: finite_induct)\n    (auto simp: disjoint_family_on_def indicator_def split: if_splits)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Indicator_Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.880797071719777, "lm_q1q2_score": 0.7828161479638146}}
{"text": "(*  Title:       Instances of Schneider's generalized protocol of clock synchronization\n    Author:      Damián Barsotti <damian at hal.famaf.unc.edu.ar>, 2006\n    Maintainer:  Damián Barsotti <damian at hal.famaf.unc.edu.ar>\n*)\n\nheader {* Fault-tolerant Midpoint algorithm *}\n\ntheory LynchInstance imports Complex_Main begin\n\ntext {* This algorithm is presented in \\cite{lynch_cs}. *}\n\nsubsection {* Model of the system *}\n\ntext {* The main ideas for the formalization of the system were\nobtained from \\cite{shankar92mechanical}.  *}\n\nsubsubsection {* Types in the formalization *}\n\ntext {* The election of the basics types was based on\n\\cite{shankar92mechanical}. There, the process are natural numbers and\nthe real time and the clock readings are reals. *}\n\ntype_synonym process = nat  \ntype_synonym time = real      -- \"real time\"\ntype_synonym Clocktime = real -- \"time of the clock readings (clock time)\"\n\nsubsubsection {* Some constants *}\n\ntext{* Here we define some parameters of the algorithm that we use:\nthe number of process and the number of lowest and highest readed\nvalues that the algorithm discards. The defined constants must satisfy\nthis axiom. If not, the algorithm cannot obtain the maximum and\nminimum value, because it will have discarded all the values. *}\n\naxiomatization\n  np  :: nat  -- \"Number of processes\" and\n  khl :: nat  -- \"Number of lowest and highest values\" where\n  constants_ax: \"2 * khl < np\"\n\ntext {* We define also the set of process that the algorithm\nmanage. This definition exist only for readability matters. *}\n\ndefinition\nPR :: \"process set\" where\n[simp]: \"PR = {..<np}\"\n\n\nsubsubsection {* Convergence function *}\n\ntext {* This functions is called ``Fault-tolerant Midpoint''\n(\\cite{schneider87understanding})*}\n\ntext {* In this algorithm each process has an array where it store the\nclocks readings from the others processes (including itself). We\nformalise that as a function from processes to clock time as\n\\cite{shankar92mechanical}. *}\n\ntext {* First we define two functions. They take a function of clock\nreadings and a set of processes and they return a set of @{term khl}\nprocesses which has the greater (smaller) clock readings. They were\ndefined with the Hilbert's $\\varepsilon$-operator (the indefinite\ndescription operator @{text SOME} in Isabelle) because in this way the\nformalization is not fixed to a particular eleccion of the processes's\nreadings to discards and then the modelization is more general. *}\n\ndefinition\nkmax :: \"(process \\<Rightarrow> Clocktime) \\<Rightarrow> process set \\<Rightarrow> process set\" where\n\"kmax f P = (SOME S. S \\<subseteq> P \\<and> card S = khl \\<and> \n                (\\<forall> i\\<in>S. \\<forall> j\\<in>(P-S). f j <= f i))\"\n\ndefinition\nkmin :: \"(process \\<Rightarrow> Clocktime) \\<Rightarrow> process set \\<Rightarrow> process set\" where\n\"kmin f P = (SOME S. S \\<subseteq> P \\<and> card S = khl \\<and> \n                (\\<forall> i\\<in>S. \\<forall> j\\<in>(P-S). f i <= f j))\"\n\ntext {* With the previus functions we define a new one @{term\nreduce}\\footnote{The name of this function was taken from\n\\cite{lynch_cs}.}. This take a function of clock readings and a set of\nprocesses and return de set of readings of the not dicarded\nprocesses. In order to define this function we use the image operator\n(@{term \"op `\"}) of Isabelle.*}\n\ndefinition\nreduce :: \"(process \\<Rightarrow> Clocktime) \\<Rightarrow> process set \\<Rightarrow> Clocktime set\" where\n\"reduce f P = f ` (P - (kmax f P \\<union> kmin f P))\"\n\ntext {* And finally the convergence function. This is defined with the\nbuiltin @{term Max} and @{term Min} functions of Isabelle.\n*}\n\ndefinition\ncfnl :: \"process  \\<Rightarrow> (process \\<Rightarrow> Clocktime) \\<Rightarrow> Clocktime\" where\n\"cfnl p f = (Max (reduce f PR) + Min (reduce f PR)) / 2\"\n\n\nsubsection {* Translation Invariance property.*}\n\nsubsubsection {* Auxiliary lemmas *}\n\ntext {* These lemmas proves the existence of the maximum and minimum\nof the image of a set, if the set is finite and not empty. *}\n\n(* The proofs are almost the same one that those of the lemmas @{thm *)\n(* [source] ex_Max} and @{thm [source] ex_Min} in the Isabelle's standard *)\n(* theories. *)\n\nlemma ex_Maxf:\nfixes S and f :: \"'a \\<Rightarrow> ('b::linorder)\"\n  assumes fin: \"finite S\" \n  shows \"S \\<noteq> {} ==> \\<exists>m\\<in>S. \\<forall>s \\<in> S. f s \\<le> f m\"\nusing fin\nproof (induct)\n  case empty thus ?case by simp\nnext\n  case (insert x S)\n  show ?case\n  proof (cases)\n    assume \"S = {}\" thus ?thesis by simp\n  next\n    assume nonempty: \"S \\<noteq> {}\"\n    then obtain m where m: \"m\\<in>S\" \"\\<forall>s\\<in>S. f s \\<le> f m\" \n      using insert by blast\n    show ?thesis\n    proof (cases)\n      assume \"f x \\<le> f m\" thus ?thesis using m by blast\n    next\n      assume \"~ f x \\<le> f m\" thus ?thesis using m\n        by(simp add:linorder_not_le order_less_le)\n          (blast intro: order_trans)\n    qed\n  qed\nqed\n\nlemma ex_Minf:\nfixes S and f :: \"'a \\<Rightarrow> ('b::linorder)\"\n  assumes fin: \"finite S\" \n  shows \"S \\<noteq> {} ==> \\<exists>m\\<in>S. \\<forall>s \\<in> S. f m \\<le> f s\"\nusing fin\nproof (induct)\n  case empty thus ?case by simp\nnext\n  case (insert x S)\n  show ?case\n  proof (cases)\n    assume \"S = {}\" thus ?thesis by simp\n  next\n    assume nonempty: \"S \\<noteq> {}\"\n    then obtain m where m: \"m\\<in>S\" \"\\<forall>s\\<in>S. f m \\<le> f s\" \n      using insert by blast\n    show ?thesis\n    proof (cases)\n      assume \"f m \\<le> f x\" thus ?thesis using m by blast\n    next\n      assume \"~ f m \\<le> f x\" thus ?thesis using m\n        by(simp add:linorder_not_le order_less_le)\n          (blast intro: order_trans)\n    qed\n  qed\nqed\n\ntext {* This trivial lemma is needed by the next two. *}\n\nlemma khl_bound: \"khl < np\"\n  using constants_ax by arith\n\ntext {* The next two lemmas prove that de functions kmin and kmax\nreturn some values that satisfy their definition. This is not trivial\nbecause we need to prove the existence of these values, according to\nthe rule of the Hilbert's operator. We will need this lemma many\ntimes because is the only thing that we know about these functions. *}\n\nlemma kmax_prop:\nfixes f :: \"nat \\<Rightarrow> Clocktime\"\n  shows\n\"(kmax f PR) \\<subseteq> PR \\<and> card (kmax f PR) = khl \\<and> \n                (\\<forall>i\\<in>(kmax f PR). \\<forall>j\\<in>PR - (kmax f PR). f j \\<le> f i)\"\nproof-\n  have \"khl <= np \\<longrightarrow> \n    (\\<exists> S. S \\<subseteq> PR \\<and> card S = khl \\<and> (\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f j \\<le> f i))\"\n    ( is \"khl <= np \\<longrightarrow> ?P khl\" )\n  proof(induct (khl))\n    have \"?P 0\" by force\n    thus \"0 <= np \\<longrightarrow> ?P 0\" ..\n  next\n    fix n \n    assume asm: \"n <= np \\<longrightarrow> ?P n\" \n    show \"Suc n <= np \\<longrightarrow> ?P (Suc n)\"\n    proof\n      assume asm2: \"Suc n <= np\"\n      with asm have \"?P n\" by simp\n      then obtain S where\n        SinPR : \"S\\<subseteq>PR\" and \n        cardS: \"card S = n\" and \n        HI: \"(\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f j \\<le> f i)\" \n        by blast\n      let ?e = \"SOME i. i\\<in>PR-S \\<and> \n        (\\<forall>j\\<in>PR-S. f j \\<le> f i)\"\n      let ?S = \"insert  ?e S\"\n      have \"\\<exists>i. i\\<in>PR-S \\<and> (\\<forall>j\\<in>PR-S. f j \\<le> f i)\"\n      proof-\n        from SinPR and finite_subset \n        have \"finite (PR-S)\" \n          by auto\n        moreover\n        from cardS and asm2 SinPR\n        have \"S\\<subset>PR\" by auto\n        hence \"PR-S \\<noteq> {}\" by auto\n        ultimately\n        show ?thesis using ex_Maxf by blast\n      qed\n      hence \n        ePRS: \"?e \\<in> PR-S\" and maxH: \"(\\<forall>j \\<in> PR-S. f j \\<le> f ?e)\"\n        by (auto dest!: someI_ex)\n      from maxH and HI\n      have \"(\\<forall>i\\<in>?S. \\<forall>j\\<in>PR - ?S. f j \\<le> f i)\"\n        by blast\n      moreover\n      from SinPR and finite_subset \n      cardS and ePRS \n      have \"card ?S = Suc n\"  \n        by (auto dest: card_insert_disjoint)\n      moreover\n      have \"?S \\<subseteq> PR\" using SinPR and ePRS by auto\n      ultimately\n      show \"?P (Suc n)\" by blast\n    qed\n  qed\n  hence \"?P khl\" using khl_bound by auto\n  then obtain S where \n    \"S\\<le>PR \\<and> card S = khl \\<and> (\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f j \\<le> f i)\" ..\n    thus ?thesis by (unfold kmax_def)\n      (rule someI [where P=\"\\<lambda>S. S \\<subseteq> PR \\<and> card S = khl \\<and> (\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f j \\<le> f i)\"])\nqed\n\nlemma kmin_prop:\nfixes f :: \"nat \\<Rightarrow> Clocktime\"\n  shows\n\"(kmin f PR) \\<subseteq> PR \\<and> card (kmin f PR) = khl \\<and> \n                (\\<forall>i\\<in>(kmin f PR). \\<forall>j\\<in>PR - (kmin f PR). f i \\<le> f j)\"\nproof-\n  have \"khl <= np \\<longrightarrow> \n    (\\<exists> S. S \\<subseteq> PR \\<and> card S = khl \\<and> (\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f i \\<le> f j))\"\n    ( is \"khl <= np \\<longrightarrow> ?P khl\" )\n  proof(induct (khl))\n    have \"?P 0\" by force\n    thus \"0 <= np \\<longrightarrow> ?P 0\" ..\n  next\n    fix n \n    assume asm: \"n <= np \\<longrightarrow> ?P n\" \n    show \"Suc n <= np \\<longrightarrow> ?P (Suc n)\"\n    proof\n      assume asm2: \"Suc n <= np\"\n      with asm have \"?P n\" by simp\n      then obtain S where\n        SinPR : \"S\\<subseteq>PR\" and \n        cardS: \"card S = n\" and \n        HI: \"(\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f i \\<le> f j)\" \n        by blast\n      let ?e = \"SOME i. i\\<in>PR-S \\<and> \n        (\\<forall>j\\<in>PR-S. f i \\<le> f j)\"\n      let ?S = \"insert  ?e S\"\n      have \"\\<exists>i. i\\<in>PR-S \\<and> (\\<forall>j\\<in>PR-S. f i \\<le> f j)\"\n      proof-\n        from SinPR and finite_subset \n        have \"finite (PR-S)\" \n          by auto\n        moreover\n        from cardS and asm2 SinPR\n        have \"S\\<subset>PR\" by auto\n        hence \"PR-S \\<noteq> {}\" by auto\n        ultimately\n        show ?thesis using ex_Minf by blast\n      qed\n      hence \n        ePRS: \"?e \\<in> PR-S\" and minH: \"(\\<forall>j \\<in> PR-S. f ?e \\<le> f j)\"\n        by (auto dest!: someI_ex)\n      from minH and  HI \n      have \"(\\<forall>i\\<in>?S. \\<forall>j\\<in>PR - ?S. f i \\<le> f j)\"\n        by blast\n      moreover\n      from SinPR and finite_subset and\n        cardS and ePRS\n      have \"card ?S = Suc n\" \n        by (auto dest: card_insert_disjoint)\n      moreover\n      have \"?S \\<subseteq> PR\" using SinPR and ePRS by auto\n      ultimately\n      show \"?P (Suc n)\" by blast\n    qed\n  qed\n  hence \"?P khl\" using khl_bound by auto\n  then obtain S where \n    \"S\\<le>PR \\<and> card S = khl \\<and> (\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f i \\<le> f j)\" ..\n    thus ?thesis by (unfold kmin_def)\n      (rule someI [where P=\"\\<lambda>S. S \\<subseteq> PR \\<and> card S = khl \\<and> (\\<forall>i\\<in>S. \\<forall>j\\<in>PR - S. f i \\<le> f j)\"])\nqed\n\ntext {* The next two lemmas are trivial from the previous ones *}\n\nlemma finite_kmax:\n\"finite (kmax f PR)\"\nproof-\n  have \"finite PR\" by auto\n  with  kmax_prop and finite_subset show ?thesis\n    by blast\nqed\n\nlemma finite_kmin:\n\"finite (kmin f PR)\"\nproof-\n  have \"finite PR\" by auto\n  with  kmin_prop and finite_subset show ?thesis\n    by blast\nqed\n\ntext {* This lemma is necesary because the definition of the\nconvergence function use the builtin Max and Min. *}\n\nlemma reduce_not_empty:\n\"reduce f PR \\<noteq> {}\"\nproof-\n  from constants_ax have \n    \"0 < (np - 2 * khl)\" by arith\n  also\n  {\n    from kmax_prop kmin_prop \n    have \"card (kmax f PR) = khl \\<and> card (kmin f PR) = khl\" \n      by blast\n    moreover\n    from finite_kmax and finite_kmin card_Un_Int[THEN sym]\n    have \"card (kmax f PR \\<union> kmin f PR) + \n      card (kmax f PR \\<inter> kmin f PR) = \n      card (kmax f PR) +  card (kmin f PR)\"\n      by auto\n    ultimately\n    have \"card (kmax f PR \\<union> kmin f PR) <= 2 * khl\"\n      by auto\n  }\n  hence \n    \"... <= card PR - card (kmax f PR \\<union> kmin f PR)\"\n    by simp\n  also\n  {\n    from kmax_prop and kmin_prop have\n    \"(kmax f PR \\<union> kmin f PR) \\<subseteq> PR\" by blast\n  }\n  hence\n    \"... = card (PR-(kmax f PR \\<union> kmin f PR))\"\n    apply (intro card_Diff_subset[THEN sym])\n    apply (rule finite_subset)\n    by auto\n    (* by (intro card_Diff_subset,auto) *)\n  finally\n  have \"0 < card (PR-(kmax f PR \\<union> kmin f PR))\" .\n  hence \"(PR-(kmax f PR \\<union> kmin f PR)) \\<noteq> {}\"\n    by (intro notI, simp only: card_0_eq, simp)\n  thus ?thesis\n    by (auto simp add: reduce_def)\nqed\n\ntext {* The next three are the main lemmas necessary for prove the\nTranslation Invariance property.*}\n\nlemma reduce_shift:\nfixes f :: \"nat \\<Rightarrow> Clocktime\"\n  shows\n  \"f ` (PR - (kmax f PR \\<union> kmin f PR)) = \n            f ` (PR - (kmax (\\<lambda> p. f p + c) PR \\<union> kmin (\\<lambda> p. f p + c) PR))\"\napply (unfold kmin_def kmax_def)\nby simp\n\nlemma max_shift:\nfixes f :: \"nat \\<Rightarrow> Clocktime\" and S\nassumes notEmpFin: \"S \\<noteq> {}\" \"finite S\"\nshows\n\"Max (f`S) + x = Max ( (\\<lambda> p. f p + x) ` S) \"\nproof-  \n  from notEmpFin have \"f`S \\<noteq> {}\" and \"(\\<lambda> p. f p + x) ` S \\<noteq> {}\"\n    by auto\n  with notEmpFin have\n    \"Max (f`S) \\<in> f ` S \" \"Max ((\\<lambda> p. f p + x)`S) \\<in> (\\<lambda> p. f p + x) ` S \"\n    \"(\\<forall>fs \\<in> (f`S). fs \\<le> Max (f`S))\" \n    \"(\\<forall>fs \\<in> ((\\<lambda> p. f p + x)`S). fs \\<le> Max ((\\<lambda> p. f p + x)`S))\"\n    by auto\n  thus ?thesis by force\nqed\n  \nlemma min_shift:\nfixes f :: \"nat \\<Rightarrow> Clocktime\" and S\nassumes notEmpFin: \"S \\<noteq> {}\" \"finite S\"\nshows\n\"Min (f`S) + x = Min ( (\\<lambda> p. f p + x) ` S) \"\nproof-\n  from notEmpFin have \"f`S \\<noteq> {}\" and \"(\\<lambda> p. f p + x) ` S \\<noteq> {}\"\n    by auto\n  with notEmpFin have\n    \"Min (f`S) \\<in> f ` S \" \"Min ((\\<lambda> p. f p + x)`S) \\<in> (\\<lambda> p. f p + x) ` S \"\n    \"(\\<forall>fs \\<in> (f`S). Min (f`S) <= fs)\" \n    \"(\\<forall>fs \\<in> ((\\<lambda> p. f p + x)`S). Min ((\\<lambda> p. f p + x)`S) <= fs)\"\n    by auto\n  thus ?thesis by force\nqed\n\nsubsubsection {* Main theorem *}\n  \ntheorem trans_inv: \nfixes f :: \"nat \\<Rightarrow> Clocktime\"\n  shows\n\"cfnl p f + x = cfnl p (\\<lambda> p. f p + x)\"\nproof-\n  have \"cfnl p (\\<lambda> p. f p + x) = \n      (Max (reduce (\\<lambda> p. f p + x) PR) + Min (reduce (\\<lambda> p. f p + x) PR)) / 2\" \n    by (unfold cfnl_def, simp)\n  also\n  have \"... = \n    (Max ((\\<lambda> p. f p + x) ` \n             (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR))) + \n     Min ((\\<lambda> p. f p + x) ` \n             (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR)))) / 2\"\n    by (unfold reduce_def, simp)\n  also\n  have\n    \"... = \n    (Max (f ` \n             (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR))) + x + \n     Min (f ` \n             (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR))) + x ) / 2\"\n  proof-\n    have \"finite (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR))\"\n      by auto\n    moreover\n    from reduce_not_empty have \n      \"PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR) \\<noteq> {}\"\n      by (auto simp add: reduce_def)\n    ultimately\n    have \n      \"Max ((\\<lambda> p. f p + x) ` \n       (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR)))\n      = \n       Max (f ` \n             (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR))) + x\"\n       and \n      \"Min ((\\<lambda> p. f p + x) ` \n       (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR)))\n      = \n       Min (f ` \n             (PR - (kmax (\\<lambda> p. f p + x) PR \\<union> kmin (\\<lambda> p. f p + x) PR))) + x\"\n      using max_shift and min_shift\n      by auto\n    thus ?thesis by auto\n  qed\n  also\n  from reduce_shift\n  have\n    \"... = \n    (Max (f ` \n             (PR - (kmax f  PR \\<union> kmin f PR))) + x + \n     Min (f ` \n             (PR - (kmax f PR \\<union> kmin f PR))) + x ) / 2\"\n    by auto\n  also\n  have \"... = ((Max (reduce f PR)+ x) + (Min (reduce f PR) + x)) / 2\"\n    by (auto simp add: reduce_def)\n  also\n  have \"... = (Max (reduce f PR) + Min (reduce f PR)) / 2 + x\" \n    by auto\n  finally\n  show ?thesis by (auto simp add: cfnl_def) \nqed\n\n\nsubsection {* Precision Enhancement property *}\n\ntext {* An informal proof of this theorem can be found in \\cite{miner93} *}\n\nsubsubsection {* Auxiliary lemmas *}\n\ntext {* This first lemma is most important for prove the\nproperty. This is a consecuence of the @{thm [source] card_Un_Int}\nlemma *}\n\nlemma pigeonhole:\nassumes\n  finitA: \"finite A\" and \n  Bss: \"B \\<subseteq> A\" and Css: \"C \\<subseteq> A\" and \n  cardH: \"card A + k <= card B + card C\"\nshows \"k <= card (B \\<inter> C)\"\nproof-\n  from Bss Css have \"B \\<union> C \\<subseteq> A\" by blast\n  with finitA have \"card (B \\<union> C) <= card A\"\n    by (simp add: card_mono)\n  with cardH have\n      h: \"k <= card B + card C - card (B \\<union> C)\" \n    by arith\n  from finitA Bss Css and finite_subset \n  have \"finite B \\<and> finite C\" by auto\n  thus ?thesis\n    using card_Un_Int and h by force\nqed\n\ntext {*This lemma is a trivial consecuence of the previous one. With\nonly this lemma we can prove the Precision Enhancement property with\nthe bound $\\pi(x,y) = x + y$. But this bound not satisfy the property\n\\[ \\pi(2\\Lambda + 2 \\beta\\rho, \\delta_S + 2\\rho(r_{max}+\\beta) +\n2\\Lambda) \\leq \\delta_S \n\\] that is used in \\cite{shankar92mechanical} for prove the\nSchneider's schema. *}\n\nlemma subsets_int:\nassumes\n  finitA: \"finite A\" and \n  Bss: \"B \\<subseteq> A\" and Css: \"C \\<subseteq> A\" and \n  cardH: \"card A < card B + card C\"\nshows\n  \"B \\<inter> C \\<noteq> {}\"\nproof-\n  from finitA Bss Css cardH\n  have \"1 <= card (B \\<inter> C)\"\n    by (auto intro!:  pigeonhole)\n  thus ?thesis by auto\nqed\n\ntext {* This lemma is true because @{term \"reduce f PR\"} is the image\nof @{term \"PR-(kmax f PR \\<union> kmin f PR)\"} by the function @{term f}. *}\n\nlemma exist_reduce:\n\"\\<forall> c \\<in> reduce f PR. \\<exists> i\\<in> PR-(kmax f PR \\<union> kmin f PR). f i = c\"\nproof\nfix c assume asm: \"c \\<in> reduce f PR\"\nthus \"\\<exists> i\\<in> PR-(kmax f PR \\<union> kmin f PR). f i = c\"\n  by (auto simp add: reduce_def kmax_def kmin_def)\nqed\n\ntext {* The next three lemmas are consequence of the definition of\n@{term reduce}, @{term kmax} and @{term kmin} *}\n \nlemma finite_reduce:\n\"finite (reduce f PR)\"\nproof(unfold reduce_def)\n  show \"finite (f ` (PR - (kmax f PR \\<union> kmin f PR)))\"\n    by auto\nqed\n\nlemma kmax_ge:\n  \"\\<forall> i\\<in> (kmax f PR). \\<forall> r \\<in> (reduce f PR). r <= f i \"\nproof\n  fix i assume asm: \"i \\<in> kmax f PR\"\n  show \"\\<forall>r\\<in>reduce f PR. r \\<le> f i\"\n  proof\n    fix r assume asm2: \"r \\<in> reduce f PR\"\n    show \"r \\<le> f i\"\n    proof-\n      from asm2 and exist_reduce have\n        \"\\<exists> j \\<in> PR-(kmax f PR \\<union> kmin f PR). f j = r\" by blast\n      then obtain j \n      where fjr:\"j \\<in> PR-(kmax f PR \\<union> kmin f PR) \\<and> f j = r\" \n        by blast\n      hence \"j \\<in> (PR - kmax f PR)\"\n        by blast\n      from this fjr asm  \n      show ?thesis using kmax_prop\n        by auto\n    qed\n  qed\nqed\n\nlemma kmin_le:\n  \"\\<forall> i\\<in> (kmin f PR). \\<forall> r \\<in> (reduce f PR). f i <= r \"\nproof\n  fix i assume asm: \"i \\<in> kmin f PR\"\n  show \"\\<forall>r\\<in>reduce f PR. f i \\<le> r\"\n  proof\n    fix r assume asm2: \"r \\<in> reduce f PR\"\n    show \"f i <= r\"\n    proof-\n      from asm2 and exist_reduce have\n        \"\\<exists> j\\<in> PR-(kmax f PR \\<union> kmin f PR). f j = r\" by blast\n      then obtain j \n      where fjr:\"j \\<in> PR-(kmax f PR \\<union> kmin f PR) \\<and> f j = r\" \n        by blast\n      hence \"j \\<in> (PR - kmin f PR)\"\n        by blast\n      from this fjr asm  \n      show ?thesis using kmin_prop\n        by auto\n    qed\n  qed\nqed\n\ntext {* The next lemma is used for prove the Precision Enhancement\nproperty. This has been proved in ICS. The proof is in the appendix\n\\ref{sec:abs_distrib_mult}.  This cannot be prove by a simple @{text\narith} or @{text auto} tactic. *}\n\ntext{* This lemma is true also with @{text \"0 <= c\"} !! *}\n\n\nlemma abs_distrib_div:\n  \"0 < (c::real)  \\<Longrightarrow> \\<bar>a / c - b / c\\<bar> = \\<bar>a - b\\<bar> / c\"\nproof-\n  assume ch: \"0<c\"\n  {\n    fix d :: real\n    assume dh: \"0<=d\"\n    have \"a * d - b * d = (a - b) * d \"\n      by (simp add: algebra_simps)\n    hence \"\\<bar>a * d - b * d\\<bar> = \\<bar>(a - b) * d\\<bar>\"\n      by simp\n    also with dh have\n      \"... = \\<bar>a - b\\<bar> * d\"\n      by (simp add: abs_mult)\n    finally\n      have \"\\<bar>a * d - b * d\\<bar> = \\<bar>a - b\\<bar> * d\"\n        .\n    (* This sublemma is solved by ICS, file: abs_distrib_mult.ics *)\n    (* It is not solved nor \n       by (auto simp add: distrib_right diff_minus)(arith) \n        in Isabelle  *)\n  }\n  with ch and divide_inverse show ?thesis\n    by (auto simp add: divide_inverse)\nqed\n\ntext {* The next three lemmas are about the existence of bounds of the\nvalues @{term \"Max (reduce f PR)\"} and @{term \"Min (reduce f PR)\"}. These\nare used in the proof of the main property. *}\n\nlemma uboundmax:\nassumes \n  hC: \"C \\<subseteq> PR\" and\n  hCk: \"np <= card C + khl\"\nshows\n  \"\\<exists> i\\<in>C. Max (reduce f PR) <= f i\"\nproof-\n  from reduce_not_empty and finite_reduce \n  have maxrinr: \"Max (reduce f PR) \\<in> reduce f PR\" \n    by simp\n  with exist_reduce\n  have \"\\<exists> i\\<in> PR-(kmax f PR \\<union> kmin f PR). f i = Max (reduce f PR)\"\n    by simp\n  then obtain pmax where \n    pmax_in_reduc: \"pmax \\<in> PR-(kmax f PR \\<union> kmin f PR)\" and \n    fpmax_ismax: \"f pmax = Max (reduce f PR)\" ..\n  hence \"C \\<inter> insert pmax (kmax f PR)  \\<noteq> {}\"\n  proof-\n    from kmax_prop and pmax_in_reduc \n      and finite_kmax and hCk  have \n      \"card PR < card C + card (insert pmax (kmax f PR))\"\n      by simp\n    moreover\n    from pmax_in_reduc and kmax_prop\n    have \"insert pmax (kmax f PR) \\<subseteq> PR\" by blast\n    moreover\n    note hC\n    ultimately\n    show ?thesis \n      using subsets_int[of PR C \"insert pmax (kmax f PR)\"]\n      by simp\n  qed\n  hence res: \"\\<exists> i\\<in>C. i=pmax \\<or> i \\<in> kmax f PR\" by blast\n  then obtain i where\n    iinC: \"i\\<in>C\" and altern: \"i=pmax \\<or> i \\<in> kmax f PR\" ..\n  thus ?thesis\n  proof(cases \"i=pmax\")\n    case True\n    with iinC fpmax_ismax show ?thesis by force\n  next\n    case False\n    with altern maxrinr fpmax_ismax kmax_ge\n    have \"f pmax <= f i\" by simp\n    with iinC fpmax_ismax show ?thesis by auto \n  qed\nqed\n  \nlemma lboundmin:\nassumes \n  hC: \"C \\<subseteq> PR\" and\n  hCk: \"np <= card C + khl\"\nshows\n  \"\\<exists> i\\<in>C. f i <= Min (reduce f PR)\"\nproof-\n  from reduce_not_empty and finite_reduce \n  have minrinr: \"Min (reduce f PR) \\<in> reduce f PR\" \n    by simp\n  with exist_reduce\n  have \"\\<exists> i\\<in> PR-(kmax f PR \\<union> kmin f PR). f i = Min (reduce f PR)\"\n    by simp\n  then obtain pmin where \n    pmin_in_reduc: \"pmin \\<in> PR-(kmax f PR \\<union> kmin f PR)\" and \n    fpmin_ismin: \"f pmin = Min (reduce f PR)\" ..\n  hence \"C \\<inter> insert pmin (kmin f PR)  \\<noteq> {}\"\n  proof-\n    from kmin_prop and pmin_in_reduc \n      and finite_kmin and hCk  have \n      \"card PR < card C + card (insert pmin (kmin f PR))\"\n      by simp\n    moreover\n    from pmin_in_reduc and kmin_prop\n    have \"insert pmin (kmin f PR) \\<subseteq> PR\" by blast\n    moreover\n    note hC\n    ultimately\n    show ?thesis \n      using subsets_int[of PR C \"insert pmin (kmin f PR)\"]\n      by simp\n  qed\n  hence res: \"\\<exists> i\\<in>C. i=pmin \\<or> i \\<in> kmin f PR\" by blast\n  then obtain i where\n    iinC: \"i\\<in>C\" and altern: \"i=pmin \\<or> i \\<in> kmin f PR\" ..\n  thus ?thesis\n  proof(cases \"i=pmin\")\n    case True\n    with iinC fpmin_ismin show ?thesis by force\n  next\n    case False\n    with altern minrinr fpmin_ismin kmin_le\n    have \"f i <= f pmin\" by simp\n    with iinC fpmin_ismin show ?thesis by auto \n  qed\nqed\n  \nlemma same_bound:\nassumes \n  hC: \"C \\<subseteq> PR\" and\n  hCk: \"np <= card C + khl\" and\n  hnk: \"3 * khl < np\" \nshows\n  \"\\<exists> i\\<in>C. Min (reduce f PR) <= f i \\<and> g i <= Max (reduce g PR) \"\nproof-\n  have b1: \"khl + 1 <= card (C \\<inter> (PR - kmin f PR))\"\n  proof(rule pigeonhole)\n    show \"finite PR\" by simp\n  next\n    show \"C \\<subseteq> PR\" by fact\n  next\n    show \"PR - kmin f PR \\<subseteq> PR\" by blast\n  next\n    show \"card PR + (khl + 1) \\<le> card C + card (PR - kmin f PR)\" \n    proof-\n      from hnk and hCk have \n        \"np + khl < np + card C - khl\" by arith \n      also\n      from kmin_prop\n      have \"... = np + card C - card (kmin f PR)\"\n        by auto\n      also\n      have \"... = card C + (card PR - card (kmin f PR))\"\n      proof-\n        from kmin_prop have\n          \"card (kmin f PR) <= card PR\"\n          by (intro card_mono, auto)\n        thus ?thesis by (simp)\n      qed\n      also\n      from kmin_prop \n      have \"... = card C +  card (PR - kmin f PR)\" \n      proof-\n        from kmin_prop and finite_kmin have \n          \"card PR - card (kmin f PR) =  card (PR - kmin f PR)\"\n          by (intro card_Diff_subset[THEN sym])(auto)\n        thus ?thesis by auto\n      qed\n      finally\n      show ?thesis \n        by (simp)\n    qed\n  qed\n        \n  have \"C \\<inter> (PR - kmin f PR) \\<inter> (PR - kmax g PR) \\<noteq> {}\"\n  proof(intro subsets_int)\n    show \"finite PR\" by simp\n  next\n    show \"C \\<inter> (PR - kmin f PR) \\<subseteq> PR\"\n      by blast\n  next\n    show \"PR - kmax g PR \\<subseteq> PR\" \n      by blast\n  next\n    show \"card PR < \n      card (C \\<inter> (PR - kmin f PR)) + card (PR - kmax g PR)\"\n    proof-\n      from kmax_prop and finite_kmax\n      have \"card (PR - kmax g PR)= card PR - card (kmax g PR) \" \n        by  (intro card_Diff_subset, auto)\n      with kmax_prop have \n        \"card (PR - kmax g PR) = card PR - khl\" by simp\n      with b1\n      show ?thesis by arith\n    qed\n  qed\n\n  hence \n    \"\\<exists> i. i \\<in> C \\<and> i \\<in> (PR - kmin f PR) \\<and> i \\<in> (PR - kmax g PR)\"\n    by blast\n  then obtain i where \n    in_C: \"i \\<in> C\" and \n    not_in_kmin: \"i \\<in> (PR - kmin f PR)\" and \n    not_in_kmax: \"i \\<in> (PR - kmax g PR)\" by blast\n  have \"Min (reduce f PR) <= f i\" \n  proof(cases \"i \\<in> kmax f PR\")\n    case True\n    from reduce_not_empty and finite_reduce have\n      \" Min (reduce f PR) \\<in> reduce f PR\" by auto\n    with True show ?thesis\n      using kmax_ge by blast\n  next\n    case False\n    with not_in_kmin  \n    have \"i \\<in> PR - (kmax f PR \\<union> kmin f PR)\" \n      by blast\n    with reduce_def have \"f i \\<in> reduce f PR\"\n      by auto\n    with reduce_not_empty and finite_reduce\n    show ?thesis by auto\n  qed\n  moreover\n  have \"g i <= Max (reduce g PR)\" \n  proof(cases \"i \\<in> kmin g PR\")\n    case True\n    from reduce_not_empty and finite_reduce have\n      \" Max (reduce g PR) \\<in> reduce g PR\" by auto\n    with True show ?thesis\n      using kmin_le by blast\n  next\n    case False\n    with not_in_kmax  \n    have \"i \\<in> PR - (kmax g PR \\<union> kmin g PR)\" \n      by blast\n    with reduce_def have \"g i \\<in> reduce g PR\"\n      by auto\n    with reduce_not_empty and finite_reduce\n    show ?thesis by auto\n  qed\n  moreover\n  note in_C\n  ultimately\n  show ?thesis by blast\nqed\n\n\nsubsubsection {* Main theorem *}\n\ntext {* The most part of this theorem can be proved with CVC-lite\nusing the three previous lemmas (appendix \\ref{sec:bound_prec_enh}).*}\n\ntheorem prec_enh:\nassumes \n  hC: \"C \\<subseteq> PR\" and\n  hCF: \"np - nF <= card C\" and\n  hFn: \"3 * nF < np\" and\n  hFk: \"nF = khl\" and\n  hbx: \"\\<forall> l\\<in>C. \\<bar>f l - g l\\<bar> <= x\" and\n  hby1: \"\\<forall> l\\<in>C. \\<forall> m\\<in>C. \\<bar>f l - f m\\<bar> <= y\" and\n  hby2: \"\\<forall> l\\<in>C. \\<forall> m\\<in>C. \\<bar>g l - g m\\<bar> <= y\" and\n  hpC: \"p\\<in>C\" and\n  hqC: \"q\\<in>C\" \nshows \"\\<bar> cfnl p f - cfnl q g \\<bar> <= y / 2 + x\"\nproof-\n  from hCF and hFk \n  have hCk: \"np <= card C + khl\" by arith\n  from hFn and hFk \n  have hnk: \"3 * khl < np\"  by arith\n  let    ?maxf = \"Max (reduce f PR)\" \n    and  ?minf = \"Min (reduce f PR)\"\n    and  ?maxg = \"Max (reduce g PR)\" \n    and  ?ming = \"Min (reduce g PR)\"\n  from abs_distrib_div\n  have \"\\<bar>cfnl p f - cfnl q g\\<bar> = \n    \\<bar>?maxf + ?minf  +  - ?maxg + - ?ming\\<bar> / 2\"\n    by (unfold cfnl_def) simp\n  moreover\n  have \"\\<bar>?maxf + ?minf  +  - ?maxg + - ?ming\\<bar> <= y + 2 * x\"\n    -- {* The rest of the property can be proved by CVC-lite\n           (see appendix \\ref{sec:bound_prec_enh}) *}\n  proof ( cases \"0 <= ?maxf + ?minf  +  - ?maxg + - ?ming\")\n    case True\n    hence\n    \"\\<bar>?maxf + ?minf  +  - ?maxg + - ?ming\\<bar> = \n      ?maxf + ?minf  +  - ?maxg + - ?ming\" by arith\n    moreover\n    from uboundmax hC hCk \n    obtain mxf\n      where mxfinC: \"mxf\\<in>C\" and \n            maxf: \"?maxf <= f mxf\" by blast\n    moreover\n    from lboundmin hC hCk \n    obtain mng \n      where mnginC: \"mng\\<in>C\" and \n            ming: \"g mng <= ?ming\" by blast    \n    moreover\n    from same_bound hC hCk hnk  \n    obtain mxn \n      where mxninC: \"mxn\\<in>C\" and \n            mxnf: \"?minf  \\<le> f mxn\" and\n            mxng: \"g mxn \\<le> ?maxg\" by blast\n    ultimately\n    have \n      \"\\<bar> ?maxf + ?minf  +  - ?maxg + - ?ming\\<bar> <= \n      (f mxf + - g mng) + (f mxn  +  - g mxn)\" by arith\n    also \n    from  mxninC hbx abs_le_D1\n    have\n      \"... <= (f mxf + - g mng) + x\"\n      by auto\n    also\n    have \n      \"... = (f mxf + - f mng ) + ( f mng + - g mng) + x\"\n      by arith\n    also\n    have \"... <= y + ( f mng + - g mng) + x\"\n    proof-\n      from  mxfinC mnginC hby1 abs_le_D1\n      have \"f mxf + - f mng <= y\" \n        by auto\n      thus ?thesis\n        by auto\n    qed\n    also\n    from  mnginC hbx abs_le_D1\n    have \"... <= y + 2 * x\"\n      by auto\n    finally \n    show ?thesis .\n  next\n    case False\n    hence\n    \"\\<bar>?maxf + ?minf  +  - ?maxg + - ?ming\\<bar> = \n      ?maxg + ?ming  +  - ?maxf + - ?minf\" by arith\n    moreover\n    from uboundmax hC hCk \n    obtain mxg \n      where mxginC: \"mxg\\<in>C\" and \n            maxg: \"?maxg <= g mxg\" by blast\n    moreover\n    from lboundmin hC hCk \n    obtain mnf \n      where mnfinC: \"mnf\\<in>C\" and \n            minf: \"f mnf <= ?minf\" by blast    \n    moreover\n    from same_bound hC hCk hnk  \n    obtain mxn \n      where mxninC: \"mxn\\<in>C\" and \n            mxnf: \"?ming  \\<le> g mxn\" and\n            mxng: \"f mxn \\<le> ?maxf\" by blast\n    ultimately\n    have \n      \"\\<bar> ?maxf + ?minf  +  - ?maxg + - ?ming\\<bar> <= \n      (g mxg + - f mnf) + (g mxn  +  - f mxn)\" by arith\n    also\n    from  mxninC hbx \n    have \"... <= (g mxg + - f mnf) + x\"\n        by (auto dest!: abs_le_D2)\n    also\n    have \n      \"... = (g mxg + - g mnf ) + ( g mnf + - f mnf) + x\"\n      by arith\n    also\n    have \"... <= y + ( g mnf + - f mnf) + x\"\n    proof-\n      from  mxginC mnfinC hby2 abs_le_D1\n      have \"g mxg + - g mnf <= y\" \n        by auto\n      thus ?thesis\n        by auto\n    qed\n    also\n    from  mnfinC hbx\n    have \"... <= y + 2 * x\"\n      by (auto dest!: abs_le_D2)\n    finally \n    show ?thesis .\n  qed\n  ultimately\n  show ?thesis\n    by simp\nqed\n\nsubsection {* Accuracy Preservation property *}\n\ntext {* No new lemmas are needed for prove this property. The bound\nhas been found using the lemmas @{thm [source] uboundmax} and @{thm\n[source] lboundmin} *}\n\ntext {* This theorem can be proved with ICS and CVC-lite assuming\nthose lemmas (see appendix \\ref{sec:accur_pres}).  *}\n\ntheorem accur_pres:\nassumes\n  hC: \"C \\<subseteq> PR\" and\n  hCF: \"np - nF <= card C\" and\n  hFk: \"nF = khl\" and\n  hby: \"\\<forall> l\\<in>C. \\<forall> m\\<in>C. \\<bar>f l - f m\\<bar> <= y\" and\n  hqC: \"q\\<in>C\" \nshows \"\\<bar> cfnl p f - f q \\<bar> <= y\"\nproof-\n  from hCF and hFk \n  have npleCk: \"np <= card C + khl\" by arith\n  show ?thesis\n  proof(cases \"f q <= cfnl p f\")\n    case True\n    from npleCk hC and  uboundmax \n    have \"\\<exists> i\\<in>C. Max (reduce f PR) <= f i\"\n      by auto\n    then obtain pi where \n      hpiC: \"pi \\<in> C\" and \n      fpiGeMax: \"Max (reduce f PR) <= f pi\" by blast\n    from reduce_not_empty \n    have \"Min (reduce f PR) <= Max (reduce f PR)\"\n      by (auto simp add: reduce_def)\n    with fpiGeMax have\n      cfnlLefpi: \"cfnl p f <= f pi\"\n      by (auto simp add: cfnl_def)\n    with True have \n      \"\\<bar> cfnl p f - f q \\<bar> <= \\<bar> f pi - f q \\<bar>\"\n      by arith\n    with hpiC and hqC and hby show ?thesis \n      by force\n  next\n    case False\n    from npleCk hC and lboundmin \n    have \"\\<exists> i\\<in>C. f i <= Min (reduce f PR)\"\n      by auto\n    then obtain qi where \n      hqiC: \"qi \\<in> C\" and \n      fqiLeMax: \"f qi <= Min (reduce f PR)\" by blast\n    from reduce_not_empty \n    have \"Min (reduce f PR) <= Max (reduce f PR)\"\n      by (auto simp add: reduce_def)\n    with fqiLeMax \n    have \"f qi <= cfnl p f\"\n      by (auto simp add: cfnl_def)\n    with False have \n      \"\\<bar> cfnl p f - f q \\<bar> <= \\<bar> f qi - f q \\<bar>\"\n      by arith\n    with hqiC and hqC and hby show ?thesis \n      by force\n  qed\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/ClockSynchInst/LynchInstance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8887587831798666, "lm_q1q2_score": 0.7828161448139508}}
{"text": "(*  Author:     Manuel Eberl (TU München)\n\nDefines the set of permutations of a given multiset (or set), i.e. the set of all lists whose \nentries correspond to the multiset (resp. set).\n*)\n\nsection \\<open>Permutations of a Multiset\\<close>\n\ntheory Multiset_Permutations\nimports\n  Complex_Main\n  Permutations\nbegin\n\n(* TODO Move *)\nlemma mset_tl: \"xs \\<noteq> [] \\<Longrightarrow> mset (tl xs) = mset xs - {#hd xs#}\"\n  by (cases xs) simp_all\n\nlemma mset_set_image_inj:\n  assumes \"inj_on f A\"\n  shows   \"mset_set (f ` A) = image_mset f (mset_set A)\"\nproof (cases \"finite A\")\n  case True\n  from this and assms show ?thesis by (induction A) auto\nqed (insert assms, simp add: finite_image_iff)\n\nlemma multiset_remove_induct [case_names empty remove]:\n  assumes \"P {#}\" \"\\<And>A. A \\<noteq> {#} \\<Longrightarrow> (\\<And>x. x \\<in># A \\<Longrightarrow> P (A - {#x#})) \\<Longrightarrow> P A\"\n  shows   \"P A\"\nproof (induction A rule: full_multiset_induct)\n  case (less A)\n  hence IH: \"P B\" if \"B \\<subset># A\" for B using that by blast\n  show ?case\n  proof (cases \"A = {#}\")\n    case True\n    thus ?thesis by (simp add: assms)\n  next\n    case False\n    hence \"P (A - {#x#})\" if \"x \\<in># A\" for x\n      using that by (intro IH) (simp add: mset_subset_diff_self)\n    from False and this show \"P A\" by (rule assms)\n  qed\nqed\n\nlemma map_list_bind: \"map g (List.bind xs f) = List.bind xs (map g \\<circ> f)\"\n  by (simp add: List.bind_def map_concat)\n\nlemma mset_eq_mset_set_imp_distinct:\n  \"finite A \\<Longrightarrow> mset_set A = mset xs \\<Longrightarrow> distinct xs\"\nproof (induction xs arbitrary: A)\n  case (Cons x xs A)\n  from Cons.prems(2) have \"x \\<in># mset_set A\" by simp\n  with Cons.prems(1) have [simp]: \"x \\<in> A\" by simp\n  from Cons.prems have \"x \\<notin># mset_set (A - {x})\" by simp\n  also from Cons.prems have \"mset_set (A - {x}) = mset_set A - {#x#}\"\n    by (subst mset_set_Diff) simp_all\n  also have \"mset_set A = mset (x#xs)\" by (simp add: Cons.prems)\n  also have \"\\<dots> - {#x#} = mset xs\" by simp\n  finally have [simp]: \"x \\<notin> set xs\" by (simp add: in_multiset_in_set)\n  from Cons.prems show ?case by (auto intro!: Cons.IH[of \"A - {x}\"] simp: mset_set_Diff)\nqed simp_all\n(* END TODO *)\n\n\nsubsection \\<open>Permutations of a multiset\\<close>\n\ndefinition permutations_of_multiset :: \"'a multiset \\<Rightarrow> 'a list set\" where\n  \"permutations_of_multiset A = {xs. mset xs = A}\"\n\nlemma permutations_of_multisetI: \"mset xs = A \\<Longrightarrow> xs \\<in> permutations_of_multiset A\"\n  by (simp add: permutations_of_multiset_def)\n\nlemma permutations_of_multisetD: \"xs \\<in> permutations_of_multiset A \\<Longrightarrow> mset xs = A\"\n  by (simp add: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_Cons_iff:\n  \"x # xs \\<in> permutations_of_multiset A \\<longleftrightarrow> x \\<in># A \\<and> xs \\<in> permutations_of_multiset (A - {#x#})\"\n  by (auto simp: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_empty [simp]: \"permutations_of_multiset {#} = {[]}\"\n  unfolding permutations_of_multiset_def by simp\n\nlemma permutations_of_multiset_nonempty: \n  assumes nonempty: \"A \\<noteq> {#}\"\n  shows   \"permutations_of_multiset A = \n             (\\<Union>x\\<in>set_mset A. ((#) x) ` permutations_of_multiset (A - {#x#}))\" (is \"_ = ?rhs\")\nproof safe\n  fix xs assume \"xs \\<in> permutations_of_multiset A\"\n  hence mset_xs: \"mset xs = A\" by (simp add: permutations_of_multiset_def)\n  hence \"xs \\<noteq> []\" by (auto simp: nonempty)\n  then obtain x xs' where xs: \"xs = x # xs'\" by (cases xs) simp_all\n  with mset_xs have \"x \\<in> set_mset A\" \"xs' \\<in> permutations_of_multiset (A - {#x#})\"\n    by (auto simp: permutations_of_multiset_def)\n  with xs show \"xs \\<in> ?rhs\" by auto\nqed (auto simp: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_singleton [simp]: \"permutations_of_multiset {#x#} = {[x]}\"\n  by (simp add: permutations_of_multiset_nonempty)\n\nlemma permutations_of_multiset_doubleton: \n  \"permutations_of_multiset {#x,y#} = {[x,y], [y,x]}\"\n  by (simp add: permutations_of_multiset_nonempty insert_commute)\n\nlemma rev_permutations_of_multiset [simp]:\n  \"rev ` permutations_of_multiset A = permutations_of_multiset A\"\nproof\n  have \"rev ` rev ` permutations_of_multiset A \\<subseteq> rev ` permutations_of_multiset A\"\n    unfolding permutations_of_multiset_def by auto\n  also have \"rev ` rev ` permutations_of_multiset A = permutations_of_multiset A\"\n    by (simp add: image_image)\n  finally show \"permutations_of_multiset A \\<subseteq> rev ` permutations_of_multiset A\" .\nnext\n  show \"rev ` permutations_of_multiset A \\<subseteq> permutations_of_multiset A\"\n    unfolding permutations_of_multiset_def by auto\nqed\n\nlemma length_finite_permutations_of_multiset:\n  \"xs \\<in> permutations_of_multiset A \\<Longrightarrow> length xs = size A\"\n  by (auto simp: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_lists: \"permutations_of_multiset A \\<subseteq> lists (set_mset A)\"\n  by (auto simp: permutations_of_multiset_def)\n\nlemma finite_permutations_of_multiset [simp]: \"finite (permutations_of_multiset A)\"\nproof (rule finite_subset)\n  show \"permutations_of_multiset A \\<subseteq> {xs. set xs \\<subseteq> set_mset A \\<and> length xs = size A}\" \n    by (auto simp: permutations_of_multiset_def)\n  show \"finite {xs. set xs \\<subseteq> set_mset A \\<and> length xs = size A}\" \n    by (rule finite_lists_length_eq) simp_all\nqed\n\nlemma permutations_of_multiset_not_empty [simp]: \"permutations_of_multiset A \\<noteq> {}\"\nproof -\n  from ex_mset[of A] obtain xs where \"mset xs = A\" ..\n  thus ?thesis by (auto simp: permutations_of_multiset_def)\nqed\n\nlemma permutations_of_multiset_image:\n  \"permutations_of_multiset (image_mset f A) = map f ` permutations_of_multiset A\"\nproof safe\n  fix xs assume A: \"xs \\<in> permutations_of_multiset (image_mset f A)\"\n  from ex_mset[of A] obtain ys where ys: \"mset ys = A\" ..\n  with A have \"mset xs = mset (map f ys)\" \n    by (simp add: permutations_of_multiset_def)\n  then obtain \\<sigma> where \\<sigma>: \"\\<sigma> permutes {..<length (map f ys)}\" \"permute_list \\<sigma> (map f ys) = xs\"\n    by (rule mset_eq_permutation)\n  with ys have \"xs = map f (permute_list \\<sigma> ys)\"\n    by (simp add: permute_list_map)\n  moreover from \\<sigma> ys have \"permute_list \\<sigma> ys \\<in> permutations_of_multiset A\"\n    by (simp add: permutations_of_multiset_def)\n  ultimately show \"xs \\<in> map f ` permutations_of_multiset A\" by blast\nqed (auto simp: permutations_of_multiset_def)\n\n\nsubsection \\<open>Cardinality of permutations\\<close>\n\ntext \\<open>\n  In this section, we prove some basic facts about the number of permutations of a multiset.\n\\<close>\n\ncontext\nbegin\n\nprivate lemma multiset_prod_fact_insert:\n  \"(\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count (A+{#x#}) y)) =\n     (count A x + 1) * (\\<Prod>y\\<in>set_mset A. fact (count A y))\"\nproof -\n  have \"(\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count (A+{#x#}) y)) =\n          (\\<Prod>y\\<in>set_mset (A+{#x#}). (if y = x then count A x + 1 else 1) * fact (count A y))\"\n    by (intro prod.cong) simp_all\n  also have \"\\<dots> = (count A x + 1) * (\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count A y))\"\n    by (simp add: prod.distrib)\n  also have \"(\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count A y)) = (\\<Prod>y\\<in>set_mset A. fact (count A y))\"\n    by (intro prod.mono_neutral_right) (auto simp: not_in_iff)\n  finally show ?thesis .\nqed\n\nprivate lemma multiset_prod_fact_remove:\n  \"x \\<in># A \\<Longrightarrow> (\\<Prod>y\\<in>set_mset A. fact (count A y)) =\n                   count A x * (\\<Prod>y\\<in>set_mset (A-{#x#}). fact (count (A-{#x#}) y))\"\n  using multiset_prod_fact_insert[of \"A - {#x#}\" x] by simp\n\nlemma card_permutations_of_multiset_aux:\n  \"card (permutations_of_multiset A) * (\\<Prod>x\\<in>set_mset A. fact (count A x)) = fact (size A)\"\nproof (induction A rule: multiset_remove_induct)\n  case (remove A)\n  have \"card (permutations_of_multiset A) = \n          card (\\<Union>x\\<in>set_mset A. (#) x ` permutations_of_multiset (A - {#x#}))\"\n    by (simp add: permutations_of_multiset_nonempty remove.hyps)\n  also have \"\\<dots> = (\\<Sum>x\\<in>set_mset A. card (permutations_of_multiset (A - {#x#})))\"\n    by (subst card_UN_disjoint) (auto simp: card_image)\n  also have \"\\<dots> * (\\<Prod>x\\<in>set_mset A. fact (count A x)) = \n               (\\<Sum>x\\<in>set_mset A. card (permutations_of_multiset (A - {#x#})) * \n                 (\\<Prod>y\\<in>set_mset A. fact (count A y)))\"\n    by (subst sum_distrib_right) simp_all\n  also have \"\\<dots> = (\\<Sum>x\\<in>set_mset A. count A x * fact (size A - 1))\"\n  proof (intro sum.cong refl)\n    fix x assume x: \"x \\<in># A\"\n    have \"card (permutations_of_multiset (A - {#x#})) * (\\<Prod>y\\<in>set_mset A. fact (count A y)) = \n            count A x * (card (permutations_of_multiset (A - {#x#})) * \n              (\\<Prod>y\\<in>set_mset (A - {#x#}). fact (count (A - {#x#}) y)))\" (is \"?lhs = _\")\n      by (subst multiset_prod_fact_remove[OF x]) simp_all\n    also note remove.IH[OF x]\n    also from x have \"size (A - {#x#}) = size A - 1\" by (simp add: size_Diff_submset)\n    finally show \"?lhs = count A x * fact (size A - 1)\" .\n  qed\n  also have \"(\\<Sum>x\\<in>set_mset A. count A x * fact (size A - 1)) =\n                size A * fact (size A - 1)\"\n    by (simp add: sum_distrib_right size_multiset_overloaded_eq)\n  also from remove.hyps have \"\\<dots> = fact (size A)\"\n    by (cases \"size A\") auto\n  finally show ?case .\nqed simp_all\n\ntheorem card_permutations_of_multiset:\n  \"card (permutations_of_multiset A) = fact (size A) div (\\<Prod>x\\<in>set_mset A. fact (count A x))\"\n  \"(\\<Prod>x\\<in>set_mset A. fact (count A x) :: nat) dvd fact (size A)\"\n  by (simp_all flip: card_permutations_of_multiset_aux[of A])\n\nlemma card_permutations_of_multiset_insert_aux:\n  \"card (permutations_of_multiset (A + {#x#})) * (count A x + 1) = \n      (size A + 1) * card (permutations_of_multiset A)\"\nproof -\n  note card_permutations_of_multiset_aux[of \"A + {#x#}\"]\n  also have \"fact (size (A + {#x#})) = (size A + 1) * fact (size A)\" by simp\n  also note multiset_prod_fact_insert[of A x]\n  also note card_permutations_of_multiset_aux[of A, symmetric]\n  finally have \"card (permutations_of_multiset (A + {#x#})) * (count A x + 1) *\n                    (\\<Prod>y\\<in>set_mset A. fact (count A y)) =\n                (size A + 1) * card (permutations_of_multiset A) *\n                    (\\<Prod>x\\<in>set_mset A. fact (count A x))\" by (simp only: mult_ac)\n  thus ?thesis by (subst (asm) mult_right_cancel) simp_all\nqed\n\nlemma card_permutations_of_multiset_remove_aux:\n  assumes \"x \\<in># A\"\n  shows   \"card (permutations_of_multiset A) * count A x = \n             size A * card (permutations_of_multiset (A - {#x#}))\"\nproof -\n  from assms have A: \"A - {#x#} + {#x#} = A\" by simp\n  from assms have B: \"size A = size (A - {#x#}) + 1\" \n    by (subst A [symmetric], subst size_union) simp\n  show ?thesis\n    using card_permutations_of_multiset_insert_aux[of \"A - {#x#}\" x, unfolded A] assms\n    by (simp add: B)\nqed\n\nlemma real_card_permutations_of_multiset_remove:\n  assumes \"x \\<in># A\"\n  shows   \"real (card (permutations_of_multiset (A - {#x#}))) = \n             real (card (permutations_of_multiset A) * count A x) / real (size A)\"\n  using assms by (subst card_permutations_of_multiset_remove_aux[OF assms]) auto\n\nlemma real_card_permutations_of_multiset_remove':\n  assumes \"x \\<in># A\"\n  shows   \"real (card (permutations_of_multiset A)) = \n             real (size A * card (permutations_of_multiset (A - {#x#}))) / real (count A x)\"\n  using assms by (subst card_permutations_of_multiset_remove_aux[OF assms, symmetric]) simp\n\nend\n\n\n\nsubsection \\<open>Permutations of a set\\<close>\n\ndefinition permutations_of_set :: \"'a set \\<Rightarrow> 'a list set\" where\n  \"permutations_of_set A = {xs. set xs = A \\<and> distinct xs}\"\n\nlemma permutations_of_set_altdef:\n  \"finite A \\<Longrightarrow> permutations_of_set A = permutations_of_multiset (mset_set A)\"\n  by (auto simp add: permutations_of_set_def permutations_of_multiset_def mset_set_set \n        in_multiset_in_set [symmetric] mset_eq_mset_set_imp_distinct)\n\nlemma permutations_of_setI [intro]:\n  assumes \"set xs = A\" \"distinct xs\"\n  shows   \"xs \\<in> permutations_of_set A\"\n  using assms unfolding permutations_of_set_def by simp\n  \nlemma permutations_of_setD:\n  assumes \"xs \\<in> permutations_of_set A\"\n  shows   \"set xs = A\" \"distinct xs\"\n  using assms unfolding permutations_of_set_def by simp_all\n  \nlemma permutations_of_set_lists: \"permutations_of_set A \\<subseteq> lists A\"\n  unfolding permutations_of_set_def by auto\n\nlemma permutations_of_set_empty [simp]: \"permutations_of_set {} = {[]}\"\n  by (auto simp: permutations_of_set_def)\n  \nlemma UN_set_permutations_of_set [simp]:\n  \"finite A \\<Longrightarrow> (\\<Union>xs\\<in>permutations_of_set A. set xs) = A\"\n  using finite_distinct_list by (auto simp: permutations_of_set_def)\n\nlemma permutations_of_set_infinite:\n  \"\\<not>finite A \\<Longrightarrow> permutations_of_set A = {}\"\n  by (auto simp: permutations_of_set_def)\n\nlemma permutations_of_set_nonempty:\n  \"A \\<noteq> {} \\<Longrightarrow> permutations_of_set A = \n                  (\\<Union>x\\<in>A. (\\<lambda>xs. x # xs) ` permutations_of_set (A - {x}))\"\n  by (cases \"finite A\")\n     (simp_all add: permutations_of_multiset_nonempty mset_set_empty_iff mset_set_Diff \n                    permutations_of_set_altdef permutations_of_set_infinite)\n    \nlemma permutations_of_set_singleton [simp]: \"permutations_of_set {x} = {[x]}\"\n  by (subst permutations_of_set_nonempty) auto\n\nlemma permutations_of_set_doubleton: \n  \"x \\<noteq> y \\<Longrightarrow> permutations_of_set {x,y} = {[x,y], [y,x]}\"\n  by (subst permutations_of_set_nonempty) \n     (simp_all add: insert_Diff_if insert_commute)\n\nlemma rev_permutations_of_set [simp]:\n  \"rev ` permutations_of_set A = permutations_of_set A\"\n  by (cases \"finite A\") (simp_all add: permutations_of_set_altdef permutations_of_set_infinite)\n\nlemma length_finite_permutations_of_set:\n  \"xs \\<in> permutations_of_set A \\<Longrightarrow> length xs = card A\"\n  by (auto simp: permutations_of_set_def distinct_card)\n\nlemma finite_permutations_of_set [simp]: \"finite (permutations_of_set A)\"\n  by (cases \"finite A\") (simp_all add: permutations_of_set_infinite permutations_of_set_altdef)\n\nlemma permutations_of_set_empty_iff [simp]:\n  \"permutations_of_set A = {} \\<longleftrightarrow> \\<not>finite A\"\n  unfolding permutations_of_set_def using finite_distinct_list[of A] by auto\n\nlemma card_permutations_of_set [simp]:\n  \"finite A \\<Longrightarrow> card (permutations_of_set A) = fact (card A)\"\n  by (simp add: permutations_of_set_altdef card_permutations_of_multiset del: One_nat_def)\n\nlemma permutations_of_set_image_inj:\n  assumes inj: \"inj_on f A\"\n  shows   \"permutations_of_set (f ` A) = map f ` permutations_of_set A\"\n  by (cases \"finite A\")\n     (simp_all add: permutations_of_set_infinite permutations_of_set_altdef\n                    permutations_of_multiset_image mset_set_image_inj inj finite_image_iff)\n\nlemma permutations_of_set_image_permutes:\n  \"\\<sigma> permutes A \\<Longrightarrow> map \\<sigma> ` permutations_of_set A = permutations_of_set A\"\n  by (subst permutations_of_set_image_inj [symmetric])\n     (simp_all add: permutes_inj_on permutes_image)\n\n\nsubsection \\<open>Code generation\\<close>\n\ntext \\<open>\n  First, we give code an implementation for permutations of lists.\n\\<close>\n\ndeclare length_remove1 [termination_simp] \n\nfun permutations_of_list_impl where\n  \"permutations_of_list_impl xs = (if xs = [] then [[]] else\n     List.bind (remdups xs) (\\<lambda>x. map ((#) x) (permutations_of_list_impl (remove1 x xs))))\"\n\nfun permutations_of_list_impl_aux where\n  \"permutations_of_list_impl_aux acc xs = (if xs = [] then [acc] else\n     List.bind (remdups xs) (\\<lambda>x. permutations_of_list_impl_aux (x#acc) (remove1 x xs)))\"\n\ndeclare permutations_of_list_impl_aux.simps [simp del]    \ndeclare permutations_of_list_impl.simps [simp del]\n    \nlemma permutations_of_list_impl_Nil [simp]:\n  \"permutations_of_list_impl [] = [[]]\"\n  by (simp add: permutations_of_list_impl.simps)\n\nlemma permutations_of_list_impl_nonempty:\n  \"xs \\<noteq> [] \\<Longrightarrow> permutations_of_list_impl xs = \n     List.bind (remdups xs) (\\<lambda>x. map ((#) x) (permutations_of_list_impl (remove1 x xs)))\"\n  by (subst permutations_of_list_impl.simps) simp_all\n\nlemma set_permutations_of_list_impl:\n  \"set (permutations_of_list_impl xs) = permutations_of_multiset (mset xs)\"\n  by (induction xs rule: permutations_of_list_impl.induct)\n     (subst permutations_of_list_impl.simps, \n      simp_all add: permutations_of_multiset_nonempty set_list_bind)\n\nlemma distinct_permutations_of_list_impl:\n  \"distinct (permutations_of_list_impl xs)\"\n  by (induction xs rule: permutations_of_list_impl.induct, \n      subst permutations_of_list_impl.simps)\n     (auto intro!: distinct_list_bind simp: distinct_map o_def disjoint_family_on_def)\n\nlemma permutations_of_list_impl_aux_correct':\n  \"permutations_of_list_impl_aux acc xs = \n     map (\\<lambda>xs. rev xs @ acc) (permutations_of_list_impl xs)\"\n  by (induction acc xs rule: permutations_of_list_impl_aux.induct,\n      subst permutations_of_list_impl_aux.simps, subst permutations_of_list_impl.simps)\n     (auto simp: map_list_bind intro!: list_bind_cong)\n    \nlemma permutations_of_list_impl_aux_correct:\n  \"permutations_of_list_impl_aux [] xs = map rev (permutations_of_list_impl xs)\"\n  by (simp add: permutations_of_list_impl_aux_correct')\n\nlemma distinct_permutations_of_list_impl_aux:\n  \"distinct (permutations_of_list_impl_aux acc xs)\"\n  by (simp add: permutations_of_list_impl_aux_correct' distinct_map \n        distinct_permutations_of_list_impl inj_on_def)\n\nlemma set_permutations_of_list_impl_aux:\n  \"set (permutations_of_list_impl_aux [] xs) = permutations_of_multiset (mset xs)\"\n  by (simp add: permutations_of_list_impl_aux_correct set_permutations_of_list_impl)\n  \ndeclare set_permutations_of_list_impl_aux [symmetric, code]\n\nvalue [code] \"permutations_of_multiset {#1,2,3,4::int#}\"\n\n\n\ntext \\<open>\n  Now we turn to permutations of sets. We define an auxiliary version with an \n  accumulator to avoid having to map over the results.\n\\<close>\nfunction permutations_of_set_aux where\n  \"permutations_of_set_aux acc A = \n     (if \\<not>finite A then {} else if A = {} then {acc} else \n        (\\<Union>x\\<in>A. permutations_of_set_aux (x#acc) (A - {x})))\"\nby auto\ntermination by (relation \"Wellfounded.measure (card \\<circ> snd)\") (simp_all add: card_gt_0_iff)\n\nlemma permutations_of_set_aux_altdef:\n  \"permutations_of_set_aux acc A = (\\<lambda>xs. rev xs @ acc) ` permutations_of_set A\"\nproof (cases \"finite A\")\n  assume \"finite A\"\n  thus ?thesis\n  proof (induction A arbitrary: acc rule: finite_psubset_induct)\n    case (psubset A acc)\n    show ?case\n    proof (cases \"A = {}\")\n      case False\n      note [simp del] = permutations_of_set_aux.simps\n      from psubset.hyps False \n        have \"permutations_of_set_aux acc A = \n                (\\<Union>y\\<in>A. permutations_of_set_aux (y#acc) (A - {y}))\"\n        by (subst permutations_of_set_aux.simps) simp_all\n      also have \"\\<dots> = (\\<Union>y\\<in>A. (\\<lambda>xs. rev xs @ acc) ` (\\<lambda>xs. y # xs) ` permutations_of_set (A - {y}))\"\n        apply (rule arg_cong [of _ _ Union], rule image_cong)\n         apply (simp_all add: image_image)\n        apply (subst psubset)\n         apply auto\n        done\n      also from False have \"\\<dots> = (\\<lambda>xs. rev xs @ acc) ` permutations_of_set A\"\n        by (subst (2) permutations_of_set_nonempty) (simp_all add: image_UN)\n      finally show ?thesis .\n    qed simp_all\n  qed\nqed (simp_all add: permutations_of_set_infinite)\n\ndeclare permutations_of_set_aux.simps [simp del]\n\nlemma permutations_of_set_aux_correct:\n  \"permutations_of_set_aux [] A = permutations_of_set A\"\n  by (simp add: permutations_of_set_aux_altdef)\n\n\ntext \\<open>\n  In another refinement step, we define a version on lists.\n\\<close>\ndeclare length_remove1 [termination_simp]\n\nfun permutations_of_set_aux_list where\n  \"permutations_of_set_aux_list acc xs = \n     (if xs = [] then [acc] else \n        List.bind xs (\\<lambda>x. permutations_of_set_aux_list (x#acc) (List.remove1 x xs)))\"\n\ndefinition permutations_of_set_list where\n  \"permutations_of_set_list xs = permutations_of_set_aux_list [] xs\"\n\ndeclare permutations_of_set_aux_list.simps [simp del]\n\nlemma permutations_of_set_aux_list_refine:\n  assumes \"distinct xs\"\n  shows   \"set (permutations_of_set_aux_list acc xs) = permutations_of_set_aux acc (set xs)\"\n  using assms\n  by (induction acc xs rule: permutations_of_set_aux_list.induct)\n     (subst permutations_of_set_aux_list.simps,\n      subst permutations_of_set_aux.simps,\n      simp_all add: set_list_bind)\n\n\ntext \\<open>\n  The permutation lists contain no duplicates if the inputs contain no duplicates.\n  Therefore, these functions can easily be used when working with a representation of\n  sets by distinct lists.\n  The same approach should generalise to any kind of set implementation that supports\n  a monadic bind operation, and since the results are disjoint, merging should be cheap.\n\\<close>\nlemma distinct_permutations_of_set_aux_list:\n  \"distinct xs \\<Longrightarrow> distinct (permutations_of_set_aux_list acc xs)\"\n  by (induction acc xs rule: permutations_of_set_aux_list.induct)\n     (subst permutations_of_set_aux_list.simps,\n      auto intro!: distinct_list_bind simp: disjoint_family_on_def \n         permutations_of_set_aux_list_refine permutations_of_set_aux_altdef)\n\nlemma distinct_permutations_of_set_list:\n    \"distinct xs \\<Longrightarrow> distinct (permutations_of_set_list xs)\"\n  by (simp add: permutations_of_set_list_def distinct_permutations_of_set_aux_list)\n\nlemma permutations_of_list:\n    \"permutations_of_set (set xs) = set (permutations_of_set_list (remdups xs))\"\n  by (simp add: permutations_of_set_aux_correct [symmetric] \n        permutations_of_set_aux_list_refine permutations_of_set_list_def)\n\nlemma permutations_of_list_code [code]:\n  \"permutations_of_set (set xs) = set (permutations_of_set_list (remdups xs))\"\n  \"permutations_of_set (List.coset xs) = \n     Code.abort (STR ''Permutation of set complement not supported'') \n       (\\<lambda>_. permutations_of_set (List.coset xs))\"\n  by (simp_all add: permutations_of_list)\n\nvalue [code] \"permutations_of_set (set ''abcd'')\"\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Combinatorics/Multiset_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616712, "lm_q2_score": 0.8887587846530938, "lm_q1q2_score": 0.7828161294257264}}
{"text": "(**\n  * Author: Alasdair Armstrong\n**)\n\ntheory Fixpoint\n  imports Main\nbegin\n\ncontext order\nbegin\n\ndefinition endo_galois_connection :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_galois_connection f g \\<equiv> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n\ndefinition endo_lower_adjoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_lower_adjoint f \\<equiv> \\<exists>g. endo_galois_connection f g\"\n\ndefinition endo_upper_adjoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_upper_adjoint g \\<equiv> \\<exists>f. endo_galois_connection f g\"\n\nlemma endo_deflation: \"endo_galois_connection f g \\<Longrightarrow> f (g y) \\<le> y\"\n  by (metis endo_galois_connection_def le_less)\n\nlemma endo_inflation: \"endo_galois_connection f g \\<Longrightarrow> x \\<le> g (f x)\"\n  by (metis endo_galois_connection_def le_less)\n\n(* Sledgehammer can't seem to use mono due to it's sort constraints *)\ndefinition isotone :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"isotone f \\<equiv> \\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y\"\n\nlemma isotone_is_mono: \"isotone f \\<Longrightarrow> mono f\"\n  by (metis (hide_lams, mono_tags) order_class.isotone_def order_class.mono_def)\n\nlemma isotoneD: \"\\<lbrakk>isotone f; x \\<le> y\\<rbrakk> \\<Longrightarrow> f x \\<le> f y\"\n  by (metis isotone_def)\n\ndefinition idempotent :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"idempotent f \\<equiv> f \\<circ> f = f\"\n\nlemma endo_lower_iso: \"endo_galois_connection f g \\<Longrightarrow> isotone f\"\n  by (metis endo_galois_connection_def endo_inflation isotone_def order_trans)\n\nlemma endo_upper_iso: \"endo_galois_connection f g \\<Longrightarrow> isotone g\"\n  by (metis (lifting) endo_deflation endo_galois_connection_def isotone_def order_trans)\n\nlemma endo_lower_comp: \"endo_galois_connection f g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\nproof\n  fix x\n  assume \"endo_galois_connection f g\"\n  thus \"(f \\<circ> g \\<circ> f) x = f x\"\n    by (metis comp_apply endo_deflation endo_galois_connection_def endo_inflation isotoneD less_le less_le_not_le endo_lower_iso endo_upper_adjoint_def)\nqed\n\nlemma endo_upper_comp: \"endo_galois_connection f g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\nproof\n  fix x\n  assume \"endo_galois_connection f g\"\n  thus \"(g \\<circ> f \\<circ> g) x = g x\"\n    by (metis (full_types) antisym endo_deflation endo_inflation isotone_def o_apply endo_upper_iso)\nqed\n\nlemma endo_upper_idempotency1: \"endo_galois_connection f g \\<Longrightarrow> idempotent (f \\<circ> g)\"\n  by (metis idempotent_def o_assoc endo_upper_comp)\n\nlemma endo_upper_idempotency2: \"endo_galois_connection f g \\<Longrightarrow> idempotent (g \\<circ> f)\"\n  by (metis idempotent_def o_assoc endo_lower_comp)\n\nlemma endo_galois_comp: assumes g1: \"endo_galois_connection F G\" and g2 :\"endo_galois_connection H K\"\n  shows \"endo_galois_connection (F \\<circ> H) (K \\<circ> G)\"\n  by (smt g1 g2 endo_galois_connection_def o_apply)\n\nlemma endo_galois_id: \"endo_galois_connection id id\" by (metis endo_galois_connection_def id_def)\n\nlemma endo_galois_isotone1: \"endo_galois_connection f g \\<Longrightarrow> isotone (g \\<circ> f)\"\n  by (smt endo_galois_connection_def endo_inflation isotoneD isotone_def o_apply order_trans endo_upper_iso)\n\nlemma endo_galois_isotone2: \"endo_galois_connection f g \\<Longrightarrow> isotone (f \\<circ> g)\"\n  by (metis isotone_def endo_lower_iso o_apply endo_upper_iso)\n\nlemma endo_cancel: assumes g: \"endo_galois_connection f g\" shows \"f (g x) \\<le> g (f x)\"\n  by (metis assms endo_deflation endo_inflation order_trans)\n\nlemma endo_cancel_cor1: assumes g: \"endo_galois_connection f g\"\n  shows \"(g x = g y) \\<longleftrightarrow> (f (g x) = f (g y))\"\n  by (metis assms endo_upper_comp o_apply)\n\nlemma endo_cancel_cor2: assumes g: \"endo_galois_connection f g\"\n  shows \"(f x = f y) \\<longleftrightarrow> (g (f x) = g (f y))\"\n  by (metis assms endo_lower_comp o_apply)\n\nlemma endo_semi_inverse1: \"endo_galois_connection f g \\<Longrightarrow> f x = f (g (f x))\"\n  by (metis o_def endo_lower_comp)\n\nlemma endo_semi_inverse2: \"endo_galois_connection f g \\<Longrightarrow> g x = g (f (g x))\"\n  by (metis o_def endo_upper_comp)\n\nlemma endo_universal_mapping_property1:\n  assumes a: \"isotone g\" and b: \"\\<forall>x. x \\<le> g (f x)\"\n  and c: \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n  shows \"endo_galois_connection f g\"\n  by (metis a b c endo_galois_connection_def isotoneD order_trans)\n\nlemma endo_universal_mapping_property2:\n  assumes a: \"isotone f\" and b: \"\\<forall>x. f (g x) \\<le> x\"\n  and c: \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n  shows \"endo_galois_connection f g\"\n  by (metis a b c endo_galois_connection_def isotoneD order_trans)\n\nlemma endo_galois_ump2: \"endo_galois_connection f g = (isotone f \\<and> (\\<forall>y. f (g y) \\<le> y) \\<and> (\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y))\"\n  by (metis endo_deflation endo_galois_connection_def endo_lower_iso endo_universal_mapping_property2)\n\nlemma endo_galois_ump1: \"endo_galois_connection f g = (isotone g \\<and> (\\<forall>x. x \\<le> g (f x)) \\<and> (\\<forall>x y. x \\<le> g y \\<longrightarrow> f x \\<le> y))\"\n  by (metis endo_galois_connection_def endo_inflation endo_universal_mapping_property1 endo_upper_iso)\n\n(* +------------------------------------------------------------------------+\n   | Theorem 4.10(a)                                                        |\n   +------------------------------------------------------------------------+ *)\n\nlemma endo_ore_galois:\n  assumes\"\\<forall>x. x \\<le> g (f x)\" and \"\\<forall>x. f (g x) \\<le> x\"\n  and \"isotone f\" and  \"isotone g\"\n  shows \"endo_galois_connection f g\"\n  by (metis assms isotoneD order_trans endo_universal_mapping_property1)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.32(a) and 4.32(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma endo_perfect1: \"endo_galois_connection f g \\<Longrightarrow> g (f x) = x \\<longleftrightarrow> x \\<in> range g\"\n  by (metis (full_types) image_iff range_eqI endo_semi_inverse2)\n\nlemma endo_perfect2: \"endo_galois_connection f g \\<Longrightarrow> f (g x) = x \\<longleftrightarrow> x \\<in> range f\"\n  by (metis (full_types) image_iff range_eqI endo_semi_inverse1)\n\nend\n\ndefinition pleq :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"pleq f g \\<equiv> \\<forall>x. f x \\<le> g x\"\n\ndefinition galois_connection :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"galois_connection f g \\<equiv> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n\nlemma galoisD: \"galois_connection f g \\<Longrightarrow> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n  by (simp add: galois_connection_def)\n\nlemma rev_galoisD: \"galois_connection f g \\<Longrightarrow> \\<forall>x y.  (x \\<le> g y) \\<longleftrightarrow> (f x \\<le> y)\"\n  by (simp add: galois_connection_def)\n\ndefinition lower_adjoint :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"lower_adjoint f \\<equiv> \\<exists>g. galois_connection f g\"\n\ndefinition upper_adjoint :: \"('b::order \\<Rightarrow> 'a::order) \\<Rightarrow> bool\" where\n  \"upper_adjoint g \\<equiv> \\<exists>f. galois_connection f g\"\n\nlemma deflation: \"galois_connection f g \\<Longrightarrow> f (g y) \\<le> y\"\n  by (metis galois_connection_def le_less)\n\nlemma deflationD: \"galois_connection f g \\<Longrightarrow> \\<forall>y. f (g y) \\<le> y\"\n  by (metis galois_connection_def le_less)\n\nlemma inflation: \"galois_connection f g \\<Longrightarrow> x \\<le> g (f x)\"\n  by (metis galois_connection_def le_less)\n\nlemma inflationD: \"galois_connection f g \\<Longrightarrow> \\<forall>x. x \\<le> g (f x)\"\n  by (metis galois_connection_def le_less)\n\ndefinition idempotent :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"idempotent f \\<equiv> f \\<circ> f = f\"\n\nlemma lower_iso: \"galois_connection f g \\<Longrightarrow> mono f\"\n  apply (frule galoisD)\n  apply (auto simp add: mono_def)\n  apply (drule inflationD)\n  apply (erule_tac x = y in allE) back\n  by (metis order_trans)\n\nlemma upper_iso: \"galois_connection f g \\<Longrightarrow> mono g\"\n  apply (frule rev_galoisD)\n  apply (auto simp add: mono_def)\n  apply (drule deflationD)\n  apply (erule_tac x = x in allE)\n  by (metis order_trans)\n\nlemma lower_comp: \"galois_connection f g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\nproof\n  fix x\n  assume \"galois_connection f g\"\n  thus \"(f \\<circ> g \\<circ> f) x = f x\"\n    apply (simp add: galois_connection_def)\n    by (metis `galois_connection f g` lower_iso monoE order_class.order.antisym order_refl)\nqed\n\nlemma upper_comp: \"galois_connection f g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\nproof\n  fix x\n  assume \"galois_connection f g\"\n  thus \"(g \\<circ> f \\<circ> g) x = g x\"\n    apply (simp add: galois_connection_def)\n    by (metis `galois_connection f g` monoE order_class.order.antisym order_refl upper_iso)\nqed\n\nlemma upper_idempotency1: \"galois_connection f g \\<Longrightarrow> idempotent (f \\<circ> g)\"\n  by (metis idempotent_def o_assoc upper_comp)\n\nlemma upper_idempotency2: \"galois_connection f g \\<Longrightarrow> idempotent (g \\<circ> f)\"\n  by (metis idempotent_def o_assoc lower_comp)\n\nlemma galois_comp: assumes g1: \"galois_connection F G\" and g2 :\"galois_connection H K\"\n  shows \"galois_connection (F \\<circ> H) (K \\<circ> G)\"\n  by (smt g1 g2 galois_connection_def o_apply)\n\nlemma galois_id: \"galois_connection id id\"\n  by (simp add: galois_connection_def)\n\nlemma galois_isotone1: \"galois_connection f g \\<Longrightarrow> mono (g \\<circ> f)\"\n  by (smt galois_connection_def inflation monoD mono_def o_apply order_trans upper_iso)\n\nlemma galois_isotone2: \"galois_connection f g \\<Longrightarrow> mono (f \\<circ> g)\"\n  by (metis mono_def lower_iso o_apply upper_iso)\n\nlemma point_id1: \"galois_connection f g \\<Longrightarrow> id \\<sqsubseteq> g \\<circ> f\"\n  by (metis inflation id_apply o_apply pleq_def)\n\nlemma point_id2: \"galois_connection f g \\<Longrightarrow> f \\<circ> g \\<sqsubseteq> id\"\n  by (metis deflation id_apply o_apply pleq_def)\n\nlemma point_cancel: assumes g: \"galois_connection f g\" shows \"f \\<circ> g \\<sqsubseteq> g \\<circ> f\" using g\n  by (simp add: galois_connection_def o_def pleq_def) (metis g monoE order_refl upper_iso)\n\nlemma cancel: assumes g: \"galois_connection f g\" shows \"f (g x) \\<le> g (f x)\"\n  by (metis assms deflation inflation order_trans)\n\nlemma cancel_cor1: assumes g: \"galois_connection f g\"\n  shows \"(g x = g y) \\<longleftrightarrow> (f (g x) = f (g y))\"\n  by (metis assms upper_comp o_apply)\n\nlemma cancel_cor2: assumes g: \"galois_connection f g\"\n  shows \"(f x = f y) \\<longleftrightarrow> (g (f x) = g (f y))\"\n  by (metis assms lower_comp o_apply)\n\nlemma semi_inverse1: \"galois_connection f g \\<Longrightarrow> f x = f (g (f x))\"\n  by (metis o_def lower_comp)\n\nlemma semi_inverse2: \"galois_connection f g \\<Longrightarrow> g x = g (f (g x))\"\n  by (metis o_def upper_comp)\n\nlemma universal_mapping_property1:\n  assumes a: \"mono g\" and b: \"\\<forall>x. x \\<le> g (f x)\"\n  and c: \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n  shows \"galois_connection f g\"\n  by (metis (full_types) a b c galois_connection_def monoD order_trans)\n\nlemma universal_mapping_property2:\n  assumes a: \"mono f\" and b: \"\\<forall>x. f (g x) \\<le> x\"\n  and c: \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n  shows \"galois_connection f g\"\n  by (metis (full_types) a b c galois_connection_def monoD order_trans)\n\nlemma galois_ump2: \"galois_connection f g = (mono f \\<and> (\\<forall>y. f (g y) \\<le> y) \\<and> (\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y))\"\n  by (metis deflation galois_connection_def lower_iso universal_mapping_property2)\n\nlemma galois_ump1: \"galois_connection f g = (mono g \\<and> (\\<forall>x. x \\<le> g (f x)) \\<and> (\\<forall>x y. x \\<le> g y \\<longrightarrow> f x \\<le> y))\"\n  by (metis galois_connection_def inflation universal_mapping_property1 upper_iso)\n\n(* +------------------------------------------------------------------------+\n   | Theorem 4.10(a)                                                        |\n   +------------------------------------------------------------------------+ *)\n\nlemma ore_galois:\n  assumes\"\\<forall>x. x \\<le> g (f x)\" and \"\\<forall>x. f (g x) \\<le> x\"\n  and \"mono f\" and  \"mono g\"\n  shows \"galois_connection f g\"\n  by (metis assms monoD order_trans universal_mapping_property1)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.32(a) and 4.32(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma perfect1: \"galois_connection f g \\<Longrightarrow> g (f x) = x \\<longleftrightarrow> x \\<in> range g\"\n  by (metis (full_types) image_iff range_eqI semi_inverse2)\n\nlemma perfect2: \"galois_connection f g \\<Longrightarrow> f (g x) = x \\<longleftrightarrow> x \\<in> range f\"\n  by (metis (full_types) image_iff range_eqI semi_inverse1)\n\n(* Fixpoints *)\n\ncontext order\nbegin      \n\ndefinition is_lpp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lpp x f \\<equiv> f x \\<le> x \\<and> (\\<forall>y. f y \\<le> y \\<longrightarrow> x \\<le> y)\"\n\ndefinition is_gpp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gpp x f \\<equiv> x \\<le> f x \\<and> (\\<forall>y. y \\<le> f y \\<longrightarrow> y \\<le> x)\"\n\nlemma lpp_unique: \"\\<lbrakk>is_lpp x f; is_lpp y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (auto intro: antisym simp only: is_lpp_def)\n\nlemma gpp_unique: \"\\<lbrakk>is_gpp x f; is_gpp y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (auto intro: antisym simp only: is_gpp_def)\n\ndefinition is_lfp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lfp x f \\<equiv> f x = x \\<and> (\\<forall>y. f y = y \\<longrightarrow> x \\<le> y)\"\n\ndefinition is_gfp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gfp x f \\<equiv> x = f x \\<and> (\\<forall>y. f y = y \\<longrightarrow> y \\<le> x)\"\n\ndefinition least_fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<mu>\") where\n  \"\\<mu> f \\<equiv> THE x. is_lfp x f\"\n\nnotation least_fixpoint (binder \"\\<mu>\" 10)\n\nlemma lfp_eta: \"(\\<mu> x. f x) = \\<mu> f\" by simp\n\nlemma lfp_equality: \"is_lfp x f \\<Longrightarrow> \\<mu> f = x\"\n  by (metis (lifting) eq_iff is_lfp_def least_fixpoint_def the_equality)\n\nlemma lpp_is_lfp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_lpp x f \\<Longrightarrow> is_lfp x f\"\n  by (auto intro: antisym simp add: is_lfp_def is_lpp_def)\n\ndefinition greatest_fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<nu>\") where\n  \"\\<nu> f \\<equiv> THE x. is_gfp x f\"\n\nnotation greatest_fixpoint (binder \"\\<nu>\" 10)\n\nlemma gfp_eta: \"(\\<nu> x. f x) = \\<nu> f\" by simp\n\nlemma gfp_equality: \"is_gfp x f \\<Longrightarrow> \\<nu> f = x\"\n  by (metis (lifting) eq_iff greatest_fixpoint_def is_gfp_def the_equality)\n\nlemma gpp_is_gfp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_gpp x f \\<Longrightarrow> is_gfp x f\"\n  by (auto intro: antisym simp add: is_gfp_def is_gpp_def)\n\nend\n\nlemma continuity_mono:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"(\\<And>X. Sup (f ` X) = f (Sup X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis Sup_le_iff antisym atMost_iff imageI order_refl)\n\nlemma Inf_continuity_mono:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"(\\<And>X. Inf (f ` X) = f (Inf X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis antisym atLeast_iff image_eqI le_Inf_iff order_refl)\n\ndefinition (in order) directed :: \"'a set \\<Rightarrow> bool\" where\n  \"directed X \\<equiv> X \\<noteq> {} \\<and> (\\<forall>x y. x \\<in> X \\<and> y \\<in> X \\<longrightarrow> (\\<exists>z. x \\<le> z \\<and> y \\<le> z))\"\n\ncontext complete_lattice\nbegin\n\nlemma continuity_mono1: \"(\\<And>X. Sup (f ` X) = f (Sup X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis Sup_le_iff antisym atMost_iff imageI order_refl)\n\nlemma continuity_mono2: \"(\\<And>X. Inf (f ` X) = f (Inf X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis (full_types) Inf_atLeastAtMost Inf_superset_mono atLeastatMost_subset_iff eq_refl image_mono)\n\nlemma scott_continuity_mono: \"(\\<And>X. directed X \\<Longrightarrow> Sup (f ` X) = f (Sup X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\nproof -\n  assume scott_continuity: \"\\<And>X. directed X \\<Longrightarrow> Sup (f ` X) = f (Sup X)\"\n \n  {\n    fix x y\n    have \"directed {x, y}\"\n    by (auto intro: exI[of _ \"sup x y\"] simp add: directed_def)\n    hence \"Sup (f ` {x, y}) = f (Sup {x, y})\"\n      by (metis scott_continuity)\n    hence \"sup (f x) (f y) = f (sup x y)\"\n      by auto\n  }\n  moreover assume \"x \\<le> y\"\n  ultimately show ?thesis\n    by (metis le_iff_sup)\nqed \n\nlemma Inf_continuity_mono1: \"(\\<And>X. Inf (f ` X) = f (Inf X)) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (metis antisym atLeast_iff image_eqI le_Inf_iff order_refl)\n\ntheorem knaster_tarski_lpp:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" shows \"\\<exists>!x. is_lpp x f\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"Inf ?H\"\n\n  have \"f ?a \\<le> ?a\"\n  proof -\n    have \"\\<forall>x\\<in>?H. ?a \\<le> x\"\n      by (auto intro: Inf_lower)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<le> f x\"\n      by (metis assms)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<le> x\"\n      by (metis (lifting) mem_Collect_eq order_trans)\n    thus \"f ?a \\<le> ?a\"\n      by (metis Inf_greatest lfp_def)\n  qed\n  moreover show \"\\<And>x. is_lpp x f \\<Longrightarrow> x = ?a\"\n    by (metis eq_iff is_lpp_def lfp_def lfp_greatest lfp_lowerbound)\n  ultimately show \"is_lpp ?a f\"\n    by (metis is_lpp_def lfp_def lfp_lowerbound)\nqed\n\ntheorem knaster_tarski: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> \\<exists>!x. is_lfp x f\"\n  by (metis knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\ncorollary is_lfp_lfp [intro?]:\n  \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_lfp (\\<mu> f) f\"\n  by (metis knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\ntheorem knaster_tarski_gpp:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" shows \"\\<exists>!x. is_gpp x f\"\nproof\n  let ?H = \"{u. u \\<le> f u}\"\n  let ?a = \"Sup ?H\"\n\n  have \"?a \\<le> f ?a\"\n  proof -\n    have \"\\<forall>x\\<in>?H. x \\<le> ?a\"\n      by (metis Sup_upper)\n    hence \"\\<forall>x\\<in>?H. f x \\<le> f ?a\"\n      by (metis assms)\n    hence \"\\<forall>x\\<in>?H. x \\<le> f ?a\"\n      by (metis (lifting) mem_Collect_eq order_trans)\n    thus \"?a \\<le> f ?a\"\n      by (metis Sup_least gfp_def)\n  qed\n  moreover show \"\\<And>x. is_gpp x f \\<Longrightarrow> x = ?a\"\n    by (metis (lifting, full_types) Sup_upper calculation eq_iff is_gpp_def mem_Collect_eq)\n  ultimately show \"is_gpp ?a f\"\n    by (simp add: is_gpp_def) (metis (full_types) Sup_upper mem_Collect_eq)\nqed\n\ntheorem knaster_tarski_gfp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> \\<exists>!x. is_gfp x f\"\n  by (metis gfp_equality gpp_is_gfp knaster_tarski_gpp)\n\ncorollary is_gfp_gfp [intro?]:\n  \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> is_gfp (\\<nu> f) f\"\n  by (metis gfp_equality knaster_tarski_gfp)\n\nlemma fp_compute [simp]: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> f (\\<mu> f) = \\<mu> f\"\n  by (metis is_lfp_def is_lfp_lfp)\n\nlemma gfp_compute [simp]: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> f (\\<nu> f) = \\<nu> f\"\n  by (metis is_gfp_def is_gfp_gfp)\n\nlemma fp_induct [intro?]:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" and \"f x \\<le> x\" shows \"\\<mu> f \\<le> x\"\n  by (metis (full_types) assms is_lpp_def knaster_tarski_lpp lfp_equality lpp_is_lfp)\n\nlemma gfp_induct [intro?]:\n  assumes \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y)\" and \"x \\<le> f x\" shows \"x \\<le> \\<nu> f\"\n  by (metis assms gpp_is_gfp is_gfp_gfp is_gpp_def knaster_tarski_gfp knaster_tarski_gpp)\n\nprimrec iter :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"iter f 0 x = x\"\n| \"iter f (Suc n) x = f (iter f n x)\"\n\nlemma iter_mono: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> iter f n x \\<le> iter f n y\"\n  by (induct n) simp_all\n\nlemma iter_pp: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> f y \\<le> y \\<Longrightarrow> iter f n y \\<le> y\"\n  apply (induct n)\n  apply simp\n  by (metis (full_types) iter.simps(2) order_trans)\n\nlemma iter_plus: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> iter f n bot \\<le> iter f (n + m) bot\"\nproof (induct n)\n  case 0 thus ?case\n    by auto\nnext\n  case (Suc n)\n  thus ?case\n    by auto\nqed\n\ntheorem kleene_lfp:\n  assumes scott_continuity: \"(\\<And>X. directed X \\<Longrightarrow> Sup (f ` X) = f (Sup X))\"\n  shows \"\\<mu> f = Sup {iter f n bot|n. True}\"\nproof -\n  let ?C = \"{iter f n bot|n. True}\"\n  let ?c = \"Sup {iter f n bot|n. True}\"\n\n  have directed_C: \"directed ?C\"\n    apply (auto simp add: directed_def)\n    apply (rename_tac n m)\n    apply (rule_tac x = \"iter f (n + m) bot\" in exI)\n    apply auto\n    apply (metis iter_plus scott_continuity scott_continuity_mono)\n    by (metis add.commute iter_plus scott_continuity scott_continuity_mono)\n\n  have \"f ?c \\<le> ?c\"\n  proof -\n    have \"f ?c = Sup (f ` ?C)\"\n      by (metis scott_continuity[OF directed_C])\n    also have \"... \\<le> ?c\"\n      apply (rule Sup_mono)\n      apply (auto simp add: image_def)\n      apply (rule_tac x = \"iter f (Suc n) bot\" in exI)\n      apply auto\n      by (metis iter.simps(2))\n    finally show ?thesis .\n  qed\n\n  moreover have \"(\\<forall>y. f y \\<le> y \\<longrightarrow> ?c \\<le> y)\"\n  proof clarify\n    fix y assume y_fp: \"f y \\<le> y\"\n    have \"bot \\<le> y\"\n      by (metis bot_least)\n    hence \"\\<forall>n. iter f n bot \\<le> iter f n y\"\n      by (metis scott_continuity scott_continuity_mono iter_mono)\n     hence \"\\<forall>n. iter f n bot \\<le> y\"\n      by (metis scott_continuity scott_continuity_mono iter_pp order_trans y_fp)\n    thus \"?c \\<le> y\"\n      by (auto intro!: Sup_least)\n  qed\n\n  ultimately have \"is_lpp ?c f\"\n    by (auto simp add: is_lpp_def)\n  hence \"is_lfp ?c f\"\n    by (metis (full_types) scott_continuity scott_continuity_mono lpp_is_lfp)\n  thus \"\\<mu> f = ?c\"\n    by (metis lfp_equality)\nqed\n\nlemma kleene_gfp:\n  assumes continuity: \"(\\<And>X. Inf (f ` X) = f (Inf X))\"\n  shows \"\\<nu> f = Inf {iter f n top|n. True}\"\nproof -\n  let ?C = \"{iter f n top|n. True}\"\n  let ?c = \"Inf {iter f n top|n. True}\"\n\n  have \"?c \\<le> f ?c\"\n  proof -\n    have \"?c \\<le> Inf (f ` ?C)\"\n      apply (rule Inf_mono)\n      apply (auto simp add: image_def)\n      apply (rule_tac x = \"iter f (Suc n) top\" in exI)\n      apply auto\n      by (metis iter.simps(2))\n    also have \"... \\<le> f ?c\"\n      by (metis continuity eq_refl)\n    finally show ?thesis .\n  qed\n\n  moreover have \"(\\<forall>y. y \\<le> f y \\<longrightarrow> y \\<le> ?c)\"\n  proof clarify\n    fix y assume y_fp: \"y \\<le> f y\"\n    have \"y \\<le> top\"\n     by (metis top_greatest)\n    hence \"\\<forall>n. iter f n y \\<le> iter f n top\"\n      by (metis continuity Inf_continuity_mono1 iter_mono)\n    moreover have \"\\<forall>n. y \\<le> iter f n y\"\n    proof clarify\n      fix n show \"y \\<le> iter f n y\" apply (induct n) apply simp_all\n        apply (rule order_trans[of _ \"f y\"])\n        apply (metis y_fp)\n        apply (rule Inf_continuity_mono1[OF continuity])\n        by auto\n    qed\n    ultimately have \"\\<forall>n. y \\<le> iter f n top\"\n      by (metis order_trans)\n    thus \"y \\<le> ?c\"\n      by (auto intro!: Inf_greatest)\n  qed\n\n  ultimately have \"is_gpp ?c f\"\n    by (auto simp add: is_gpp_def)\n  hence \"is_gfp ?c f\"\n    by (metis (full_types) Inf_continuity_mono1 continuity gpp_is_gfp)\n  thus \"\\<nu> f = ?c\"\n    by (metis gfp_equality)\nqed\n\nlemma gfp_equality_var [intro?]: \"\\<lbrakk>f x = x; \\<And>y. f y = y \\<Longrightarrow> y \\<le> x\\<rbrakk> \\<Longrightarrow> x = \\<nu> f\"\n  by (metis gfp_equality is_gfp_def)\n\nlemma lfp_equality_var [intro?]: \"\\<lbrakk>f x = x; \\<And>y. f y = y \\<Longrightarrow> x \\<le> y\\<rbrakk> \\<Longrightarrow> x = \\<mu> f\"\n  by (metis is_lfp_def lfp_equality)\n\ntheorem endo_fixpoint_fusion [simp]:\n  assumes upper_ex: \"endo_lower_adjoint f\"\n  and hiso: \"isotone h\" and kiso: \"isotone k\"\n  and comm: \"f\\<circ>h = k\\<circ>f\"\n  shows \"f (\\<mu> h) = \\<mu> k\"\nproof\n  show \"k (f (\\<mu> h)) = f (\\<mu> h)\"\n    by (metis comm fp_compute hiso isotone_def o_eq_dest_lhs)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain g where conn: \"endo_galois_connection f g\" by (metis endo_lower_adjoint_def upper_ex)\n  have \"\\<mu> h \\<le> g y\" using isotoneD[OF hiso]\n  proof (rule fp_induct)\n    have \"f (g y) \\<le> y\" by (metis conn endo_deflation)\n    hence \"f (h (g y)) \\<le> y\" by (metis comm kiso ky isotoneD o_def)\n    thus \"h (g y) \\<le> g y\" by (metis conn endo_galois_connection_def)\n  qed\n  thus \"f (\\<mu> h) \\<le> y\" by (metis conn endo_galois_connection_def)\nqed\n\ntheorem endo_greatest_fixpoint_fusion [simp]:\n  assumes lower_ex: \"endo_upper_adjoint g\"\n  and hiso: \"isotone h\" and kiso: \"isotone k\"\n  and comm: \"g\\<circ>h = k\\<circ>g\"\n  shows \"g (\\<nu> h) = \\<nu> k\"\nproof\n  show \"k (g (\\<nu> h)) = g (\\<nu> h)\"\n    by (metis comm gfp_compute hiso isotone_def o_eq_dest_lhs)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain f where conn: \"endo_galois_connection f g\" by (metis lower_ex endo_upper_adjoint_def)\n  have \"f y \\<le> \\<nu> h\" using isotoneD[OF hiso]\n  proof (rule gfp_induct)\n    have \"y \\<le> g (f y)\" by (metis conn endo_inflation)\n    hence \"y \\<le> g (h (f y))\" by (metis (full_types) comm comp_apply isotoneD kiso ky)\n    thus \"f y \\<le> h (f y)\" by (metis conn endo_galois_connection_def)\n  qed\n  thus \"y \\<le> g (\\<nu> h)\" by (metis conn endo_galois_connection_def)\nqed\n\nend\n\ntheorem fixpoint_fusion [simp]:\n  fixes k :: \"'b::complete_lattice \\<Rightarrow> 'b\"\n  and h :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  and f :: \"'a \\<Rightarrow> 'b\"\n  assumes upper_ex: \"lower_adjoint f\"\n  and hiso: \"mono h\" and kiso: \"mono k\"\n  and comm: \"f\\<circ>h = k\\<circ>f\"\n  shows \"f (\\<mu> h) = \\<mu> k\"\nproof\n  show \"k (f (\\<mu> h)) = f (\\<mu> h)\" using monoD[OF hiso]\n    by (metis comm fp_compute o_eq_dest_lhs)\nnext\n  fix y :: \"'b\" assume ky: \"k y = y\"\n  obtain g where conn: \"galois_connection f g\" by (metis lower_adjoint_def upper_ex)\n  have \"\\<mu> h \\<le> g y\"\n  proof (rule fp_induct)\n    fix x y :: 'a assume \"x \\<le> y\" thus \"h x \\<le> h y\"\n      by (rule monoD[OF hiso])\n  next\n    have \"f (g y) \\<le> y\" by (metis conn deflation)\n    hence \"f (h (g y)) \\<le> y\" by (metis comm kiso ky monoD o_def)\n    thus \"h (g y) \\<le> g y\" by (metis conn galois_connection_def)\n  qed\n  thus \"f (\\<mu> h) \\<le> y\" by (metis conn galois_connection_def)\nqed\n\ntheorem greatest_fixpoint_fusion [simp]:\n  fixes k :: \"'b::complete_lattice \\<Rightarrow> 'b\"\n  and h :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  and f :: \"'a \\<Rightarrow> 'b\"\n  assumes lower_ex: \"upper_adjoint g\"\n  and hiso: \"mono h\" and kiso: \"mono k\"\n  and comm: \"g\\<circ>h = k\\<circ>g\"\n  shows \"g (\\<nu> h) = \\<nu> k\"\nproof\n  show \"k (g (\\<nu> h)) = g (\\<nu> h)\" using monoD[OF hiso]\n    by (metis (full_types) comm comp_apply gfp_compute)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain f where conn: \"galois_connection f g\" by (metis lower_ex upper_adjoint_def)\n  have \"f y \\<le> \\<nu> h\"\n  proof (rule gfp_induct)\n    fix x y :: 'a assume \"x \\<le> y\" thus \"h x \\<le> h y\"\n      by (rule monoD[OF hiso])\n  next\n    have \"y \\<le> g (f y)\" by (metis conn inflation)\n    hence \"y \\<le> g (h (f y))\" by (metis (full_types) comm comp_apply monoD kiso ky)\n    thus \"f y \\<le> h (f y)\" by (metis conn galois_connection_def)\n  qed\n  thus \"y \\<le> g (\\<nu> h)\" by (metis conn galois_connection_def)\nqed\n\ndefinition join_preserving :: \"('a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<Rightarrow> bool\" where\n  \"join_preserving f \\<equiv> \\<forall>X. Sup (f ` X) = f (Sup X)\"\n\ndefinition meet_preserving :: \"('a::complete_lattice \\<Rightarrow> 'b::complete_lattice) \\<Rightarrow> bool\" where\n  \"meet_preserving g \\<equiv> \\<forall>X. Inf (g ` X) = g (Inf X)\"\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.25(a) and 4.25(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma (in complete_lattice) Sup_eq_equiv: \"Sup A = x \\<longleftrightarrow> (\\<forall>z. (x \\<le> z \\<longleftrightarrow> (\\<forall>y\\<in>A. y \\<le> z)))\"\n  apply default\n  apply (metis Sup_le_iff)\n  by (metis (full_types) Sup_le_iff Sup_upper le_iff_inf less_infI2 less_le order_refl)\n\nlemma (in complete_lattice) Inf_eq_equiv: \"Inf A = x \\<longleftrightarrow> (\\<forall>z. (z \\<le> x \\<longleftrightarrow> (\\<forall>y\\<in>A. z \\<le> y)))\"\n  apply default\n  apply (metis Inf_greatest Inf_lower order_trans)\n  by (metis Inf_atLeast Inf_lower Inf_superset_mono atLeast_def mem_Collect_eq order.antisym subsetI)\n\nlemma lower_adjoint_Sup:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  assumes \"Sup X = x\" and \"lower_adjoint f\" shows \"Sup (f ` X) = f x\" using assms\n  apply (simp add: Sup_eq_equiv lower_adjoint_def)\n  apply (erule exE)\n  apply (simp add: galois_ump2 mono_def)\n  apply (erule conjE)+\n  by (metis (mono_tags, hide_lams) SUP_le_iff SUP_upper eq_iff order.trans order_refl)\n\nlemma lower_preserves_join: \"lower_adjoint f \\<Longrightarrow> join_preserving f\"\n  by (metis join_preserving_def lower_adjoint_Sup)\n\ntheorem suprema_galois: \"galois_connection f g = (join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y))\"\nproof (intro iffI conjI)\n  assume \"galois_connection f g\"\n  hence \"lower_adjoint f\"\n    by (metis lower_adjoint_def)\n  thus \"join_preserving f\"\n    by (rule lower_preserves_join)\n  from `galois_connection f g`\n  show \"\\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by (simp add: Sup_eq_equiv galois_ump2 mono_def) (metis (full_types) order_trans)\nnext\n  assume \"join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)\"\n  hence f_jp: \"join_preserving f\" and a2: \"\\<And>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  have f_iso: \"mono f\"\n    apply (rule monoI)\n    apply (rule continuity_mono) back\n    apply (metis f_jp join_preserving_def)\n    by simp\n  show \"galois_connection f g\"\n  proof (simp add: galois_connection_def)\n    have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n      using a2 by (auto simp only: Sup_eq_equiv)\n    moreover have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n    proof (intro impI allI)\n      fix x y\n      assume gr: \"x \\<le> g y\"\n      show \"f x \\<le> y\"\n      proof -\n        have lem: \"Sup (f ` {x. f x \\<le> y}) \\<le> y\"\n          by (rule Sup_least) auto\n\n        have \"f x \\<le> y \\<Longrightarrow> x \\<le> Sup {z. f z \\<le> y}\"\n          by (metis `join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n        moreover have \"x \\<le> Sup {z. f z \\<le> y} \\<Longrightarrow> f x \\<le> f (Sup {z. f z \\<le> y})\"\n          by (metis f_iso monoD)\n        moreover have \"(f x \\<le> f (Sup {z. f z \\<le> y})) = (f x \\<le> Sup (f ` {z. f z \\<le> y}))\"\n          by (metis (full_types) `join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` join_preserving_def)\n        moreover have \"... \\<Longrightarrow> f x \\<le> y\" using lem\n          by (metis order_trans)\n        ultimately show ?thesis\n          by (metis `join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\"\n      by auto\n  qed\nqed\n\nlemma lower_is_jp: \"lower_adjoint f \\<longleftrightarrow> join_preserving f\"\nproof\n  assume \"lower_adjoint f\" thus \"join_preserving f\"\n    by (metis lower_preserves_join)\nnext\n  assume \"join_preserving f\"\n  moreover hence \"\\<exists>g. \\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  ultimately show \"lower_adjoint f\"\n    by (metis (full_types) lower_adjoint_def suprema_galois)\nqed\n\ncontext complete_lattice begin\n\ndefinition endo_join_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_join_preserving f \\<equiv> \\<forall>X. Sup (f ` X) = f (Sup X)\"\n\ndefinition endo_meet_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"endo_meet_preserving g \\<equiv> \\<forall>X. Inf (g ` X) = g (Inf X)\"\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.25(a) and 4.25(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma endo_lower_adjoint_Sup: \"Sup X = x \\<Longrightarrow> endo_lower_adjoint f \\<Longrightarrow> Sup (f ` X) = f x\"\n  apply (simp add: Sup_eq_equiv endo_lower_adjoint_def)\n  apply (erule exE)\n  apply (simp add: endo_galois_ump2 isotone_def)\n  apply (erule conjE)+\nproof -\n  fix g :: \"'a \\<Rightarrow> 'a\"\n  assume a1: \"\\<forall>z. (x \\<le> z) = (\\<forall>y\\<in>X. y \\<le> z)\"\n  assume a2: \"\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y\"\n  assume a3: \"\\<forall>y. f (g y) \\<le> y\"\n  assume a4: \"\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y\"\n  have f5: \"\\<forall>x\\<^sub>0 x\\<^sub>1 x. (\\<not> SUPREMUM x\\<^sub>0 x\\<^sub>1 \\<le> (x\\<Colon>'a) \\<or> (\\<forall>b_x. (b_x\\<Colon>'a) \\<notin> x\\<^sub>0 \\<or> x\\<^sub>1 b_x \\<le> x)) \\<and> ((\\<exists>e_x. e_x \\<in> x\\<^sub>0 \\<and> \\<not> x\\<^sub>1 e_x \\<le> x) \\<or> SUPREMUM x\\<^sub>0 x\\<^sub>1 \\<le> x)\" by (metis (no_types) local.SUP_le_iff)\n  obtain sk\\<^sub>0 :: \"'a \\<Rightarrow> 'a\" where \"x \\<le> g (SUPREMUM X f)\" using a1 a4 by (simp add: local.SUP_upper)\n  hence \"f x \\<le> SUPREMUM X f\" using a2 a3 local.order_trans by blast\n  thus \"(SUP x:X. f x) = f x\" using a1 a2 f5 by (metis (no_types) local.eq_iff)\nqed\n\nlemma endo_lower_preserves_join: \"endo_lower_adjoint f \\<Longrightarrow> endo_join_preserving f\"\n  by (metis endo_join_preserving_def endo_lower_adjoint_Sup)\n\ntheorem endo_suprema_galois: \"endo_galois_connection f g = (endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y))\"\nproof (intro iffI conjI)\n  assume \"endo_galois_connection f g\"\n  hence \"endo_lower_adjoint f\"\n    by (metis endo_lower_adjoint_def)\n  thus \"endo_join_preserving f\"\n    by (rule endo_lower_preserves_join)\n  from `endo_galois_connection f g`\n  show \"\\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by (simp add: Sup_eq_equiv endo_galois_ump2 isotone_def) (metis (full_types) order_trans)\nnext\n  assume \"endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)\"\n  hence f_jp: \"endo_join_preserving f\" and a2: \"\\<And>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  hence f_iso: \"isotone f\"\n    by (metis (mono_tags) continuity_mono1 endo_join_preserving_def isotone_def)\n  show \"endo_galois_connection f g\"\n  proof (simp add: endo_galois_connection_def)\n    have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n      using a2 by (auto simp only: Sup_eq_equiv)\n    moreover have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n    proof (intro impI allI)\n      fix x y\n      assume gr: \"x \\<le> g y\"\n      show \"f x \\<le> y\"\n      proof -\n        have lem: \"Sup (f ` {x. f x \\<le> y}) \\<le> y\"\n          by (metis (full_types) SUP_def SUP_le_iff mem_Collect_eq)\n\n        have \"f x \\<le> y \\<Longrightarrow> x \\<le> Sup {z. f z \\<le> y}\"\n          by (metis `endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n        moreover have \"x \\<le> Sup {z. f z \\<le> y} \\<Longrightarrow> f x \\<le> f (Sup {z. f z \\<le> y})\"\n          by (metis f_iso isotoneD)\n        moreover have \"(f x \\<le> f (Sup {z. f z \\<le> y})) = (f x \\<le> Sup (f ` {z. f z \\<le> y}))\"\n          by (metis (full_types) `endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` endo_join_preserving_def)\n        moreover have \"... \\<Longrightarrow> f x \\<le> y\" using lem\n          by (metis order_trans)\n        ultimately show ?thesis\n          by (metis `endo_join_preserving f \\<and> (\\<forall>y. Sup {x. f x \\<le> y} = g y)` gr)\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\"\n      by auto\n  qed\nqed\n\nlemma endo_lower_is_jp: \"endo_lower_adjoint f \\<longleftrightarrow> endo_join_preserving f\"\nproof\n  assume \"endo_lower_adjoint f\" thus \"endo_join_preserving f\"\n    by (metis endo_lower_preserves_join)\nnext\n  assume \"endo_join_preserving f\"\n  moreover hence \"\\<exists>g. \\<forall>y. Sup {x. f x \\<le> y} = g y\"\n    by auto\n  ultimately show \"endo_lower_adjoint f\"\n    by (metis (full_types) endo_lower_adjoint_def endo_suprema_galois)\nqed\n\nlemma endo_upper_adjoint_Inf: \"Inf X = x \\<Longrightarrow> endo_upper_adjoint f \\<Longrightarrow> Inf (f ` X) = f x\"\n  apply (simp add: Inf_eq_equiv endo_upper_adjoint_def)\n  apply (erule exE)\n  apply (simp add: endo_galois_ump2 isotone_def)\n  apply (erule conjE)+\nproof -\n  fix fa :: \"'a \\<Rightarrow> 'a\"\n  assume a1: \"\\<forall>z. (z \\<le> x) = (\\<forall>y\\<in>X. z \\<le> y)\"\n  assume a2: \"\\<forall>x y. x \\<le> y \\<longrightarrow> fa x \\<le> fa y\"\n  assume a3: \"\\<forall>y. fa (f y) \\<le> y\"\n  assume a4: \"\\<forall>x y. fa x \\<le> y \\<longrightarrow> x \\<le> f y\"\n  have f5: \"\\<forall>x\\<^sub>0 x\\<^sub>1 x. (\\<not> (x\\<^sub>0\\<Colon>'a) \\<le> INFIMUM x\\<^sub>1 x \\<or> (\\<forall>b_x. (b_x\\<Colon>'a) \\<notin> x\\<^sub>1 \\<or> x\\<^sub>0 \\<le> x b_x)) \\<and> ((\\<exists>e_x. e_x \\<in> x\\<^sub>1 \\<and> \\<not> x\\<^sub>0 \\<le> x e_x) \\<or> x\\<^sub>0 \\<le> INFIMUM x\\<^sub>1 x)\" by (metis (no_types) local.le_INF_iff)\n  have \"\\<forall>x\\<^sub>2\\<^sub>6 x\\<^sub>2\\<^sub>7. \\<not> x\\<^sub>2\\<^sub>6 \\<le> fa (f x\\<^sub>2\\<^sub>7) \\<or> x\\<^sub>2\\<^sub>6 \\<le> x\\<^sub>2\\<^sub>7\" using a3 local.order_trans by blast\n  then obtain sk\\<^sub>0 :: \"'a \\<Rightarrow> 'a\" where \"fa (INFIMUM X f) \\<le> x\" using a1 a2 by (metis local.INF_lower)\n  thus \"(INF x:X. f x) = f x\" using a1 a3 a4 f5 by (metis local.eq_iff)\nqed\n\nlemma endo_upper_preserves_meet: \"endo_upper_adjoint f \\<Longrightarrow> endo_meet_preserving f\"\n  by (metis endo_meet_preserving_def endo_upper_adjoint_Inf)\n\ntheorem endo_infima_galois: \"endo_galois_connection f g = (endo_meet_preserving g \\<and> (\\<forall>y. Inf {x. y \\<le> g x} = f y))\"\nproof (intro iffI conjI)\n  assume \"endo_galois_connection f g\"\n  hence \"endo_upper_adjoint g\"\n    by (metis endo_upper_adjoint_def)\n  thus \"endo_meet_preserving g\"\n    by (rule endo_upper_preserves_meet)\n  from `endo_galois_connection f g`\n  show \"\\<forall>y. Inf {x. y \\<le> g x} = f y\"\n    by (simp add: Inf_eq_equiv endo_galois_ump1 isotone_def) (metis (full_types) order_trans)\nnext\n  assume \"endo_meet_preserving g \\<and> (\\<forall>y. Inf {x. y \\<le> g x} = f y)\"\n  hence f_jp: \"endo_meet_preserving g\" and a2: \"\\<And>y. Inf {x. y \\<le> g x} = f y\"\n    by auto\n  hence f_iso: \"isotone g\"\n    by (metis (mono_tags) continuity_mono2 endo_meet_preserving_def isotone_def)\n  show \"endo_galois_connection f g\"\n  proof (simp add: endo_galois_connection_def)\n    have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n      using a2 by (metis Inf_lower mem_Collect_eq)\n    moreover have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n    proof (intro impI allI)\n      fix x y\n      assume gr: \"f x \\<le> y\"\n      thus \"x \\<le> g y\"\n      proof -\n        have lem: \"x \\<le> Inf (g ` {y. x \\<le> g y})\"\n          by (metis (full_types) INF_def INF_greatest mem_Collect_eq)\n\n        also have \"... \\<le> g y\"\n          by (metis (mono_tags) `endo_meet_preserving g \\<and> (\\<forall>y. Inf {x. y \\<le> g x} = f y)` endo_meet_preserving_def f_iso gr isotoneD)\n\n        finally show ?thesis .\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\"\n      by auto\n  qed\nqed\n\n(* Dual theorem *)\nlemma endo_upper_is_mp: \"endo_upper_adjoint g \\<longleftrightarrow> endo_meet_preserving g\"\nproof\n  assume \"endo_upper_adjoint g\" thus \"endo_meet_preserving g\"\n    by (metis endo_upper_preserves_meet)\nnext\n  assume \"endo_meet_preserving g\"\n  moreover hence \"\\<exists>f. \\<forall>x. Inf {y. x \\<le> g y} = f x\"\n    by auto\n  ultimately show \"endo_upper_adjoint g\"\n    by (metis endo_infima_galois endo_upper_adjoint_def)\nqed\n\nend\n\nend\n", "meta": {"author": "victorgomes", "repo": "veritas", "sha": "d0b50770f9146f18713a690b87dc8fafa6a87580", "save_path": "github-repos/isabelle/victorgomes-veritas", "path": "github-repos/isabelle/victorgomes-veritas/veritas-d0b50770f9146f18713a690b87dc8fafa6a87580/Algebra/Fixpoint.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7827726257629862}}
{"text": "section \\<open>Proof of Sturm's Theorem\\<close>\n(* Author: Manuel Eberl <eberlm@in.tum.de> *)\ntheory Sturm_Theorem\n  imports \"HOL-Computational_Algebra.Polynomial\"\n    \"Lib/Sturm_Library\" \"HOL-Computational_Algebra.Field_as_Ring\"\nbegin\n\nsubsection \\<open>Sign changes of polynomial sequences\\<close>\n\ntext \\<open>\n  For a given sequence of polynomials, this function computes the number of sign changes\n  of the sequence of polynomials evaluated at a given position $x$. A sign change is a\n  change from a negative value to a positive one or vice versa; zeros in the sequence are\n  ignored.\n\\<close>\n\ndefinition sign_changes where\n\"sign_changes ps (x::real) =\n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map (\\<lambda>p. sgn (poly p x)) ps))) - 1\"\n\ntext \\<open>\n  The number of sign changes of a sequence distributes over a list in the sense that\n  the number of sign changes of a sequence $p_1, \\ldots, p_i, \\ldots, p_n$ at $x$ is the same\n  as the sum of the sign changes of the sequence $p_1, \\ldots, p_i$ and $p_i, \\ldots, p_n$\n  as long as $p_i(x)\\neq 0$.\n\\<close>\n\nlemma sign_changes_distrib:\n  \"poly p x \\<noteq> 0 \\<Longrightarrow>\n      sign_changes (ps\\<^sub>1 @ [p] @ ps\\<^sub>2) x =\n      sign_changes (ps\\<^sub>1 @ [p]) x + sign_changes ([p] @ ps\\<^sub>2) x\"\n  by (simp add: sign_changes_def sgn_zero_iff, subst remdups_adj_append, simp)\n\ntext \\<open>\n  The following two congruences state that the number of sign changes is the same\n  if all the involved signs are the same.\n\\<close>\n\nlemma sign_changes_cong:\n  assumes \"length ps = length ps'\"\n  assumes \"\\<forall>i < length ps. sgn (poly (ps!i) x) = sgn (poly (ps'!i) y)\"\n  shows \"sign_changes ps x = sign_changes ps' y\"\nproof-\n from assms(2) have A: \"map (\\<lambda>p. sgn (poly p x)) ps = map (\\<lambda>p. sgn (poly p y)) ps'\"\n  proof (induction rule: list_induct2[OF assms(1)])\n    case 1\n      then show ?case by simp\n  next\n    case (2 p ps p' ps')\n      from 2(3)\n      have \"\\<forall>i<length ps. sgn (poly (ps ! i) x) =\n                         sgn (poly (ps' ! i) y)\" by auto\n      from 2(2)[OF this] 2(3) show ?case by auto\n  qed\n  show ?thesis unfolding sign_changes_def by (simp add: A)\nqed\n\nlemma sign_changes_cong':\n  assumes \"\\<forall>p \\<in> set ps. sgn (poly p x) = sgn (poly p y)\"\n  shows \"sign_changes ps x = sign_changes ps y\"\nusing assms by (intro sign_changes_cong, simp_all)\n\ntext \\<open>\n  For a sequence of polynomials of length 3, if the first and the third\n  polynomial have opposite and nonzero sign at some $x$, the number of\n  sign changes is always 1, irrespective of the sign of the second\n  polynomial.\n\\<close>\n\nlemma sign_changes_sturm_triple:\n  assumes \"poly p x \\<noteq> 0\" and \"sgn (poly r x) = - sgn (poly p x)\"\n  shows \"sign_changes [p,q,r] x = 1\"\nunfolding sign_changes_def by (insert assms, auto simp: sgn_real_def)\n\ntext \\<open>\n  Finally, we define two additional functions that count the sign changes ``at infinity''.\n\\<close>\n\ndefinition sign_changes_inf where\n\"sign_changes_inf ps =\n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map poly_inf ps))) - 1\"\n\ndefinition sign_changes_neg_inf where\n\"sign_changes_neg_inf ps =\n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map poly_neg_inf ps))) - 1\"\n\n\n\nsubsection \\<open>Definition of Sturm sequences locale\\<close>\n\ntext \\<open>\n  We first define the notion of a ``Quasi-Sturm sequence'', which is a weakening of\n  a Sturm sequence that captures the properties that are fulfilled by a nonempty\n  suffix of a Sturm sequence:\n  \\begin{itemize}\n    \\item The sequence is nonempty.\n    \\item The last polynomial does not change its sign.\n    \\item If the middle one of three adjacent polynomials has a root at $x$, the other\n          two have opposite and nonzero signs at $x$.\n  \\end{itemize}\n\\<close>\n\nlocale quasi_sturm_seq =\n  fixes ps :: \"(real poly) list\"\n  assumes last_ps_sgn_const[simp]:\n      \"\\<And>x y. sgn (poly (last ps) x) = sgn (poly (last ps) y)\"\n  assumes ps_not_Nil[simp]: \"ps \\<noteq> []\"\n  assumes signs: \"\\<And>i x. \\<lbrakk>i < length ps - 2; poly (ps ! (i+1)) x = 0\\<rbrakk>\n                     \\<Longrightarrow> (poly (ps ! (i+2)) x) * (poly (ps ! i) x) < 0\"\n\n\ntext \\<open>\n  Now we define a Sturm sequence $p_1,\\ldots,p_n$ of a polynomial $p$ in the following way:\n  \\begin{itemize}\n    \\item The sequence contains at least two elements.\n    \\item $p$ is the first polynomial, i.\\,e. $p_1 = p$.\n    \\item At any root $x$ of $p$, $p_2$ and $p$ have opposite sign left of $x$ and\n          the same sign right of $x$ in some neighbourhood around $x$.\n    \\item The first two polynomials in the sequence have no common roots.\n    \\item If the middle one of three adjacent polynomials has a root at $x$, the other\n          two have opposite and nonzero signs at $x$.\n  \\end{itemize}\n\\<close>\n\nlocale sturm_seq = quasi_sturm_seq +\n  fixes p :: \"real poly\"\n  assumes hd_ps_p[simp]: \"hd ps = p\"\n  assumes length_ps_ge_2[simp]: \"length ps \\<ge> 2\"\n  assumes deriv: \"\\<And>x\\<^sub>0. poly p x\\<^sub>0 = 0 \\<Longrightarrow>\n      eventually (\\<lambda>x. sgn (poly (p * ps!1) x) =\n                      (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\n  assumes p_squarefree: \"\\<And>x. \\<not>(poly p x = 0 \\<and> poly (ps!1) x = 0)\"\nbegin\n\n  text \\<open>\n    Any Sturm sequence is obviously a Quasi-Sturm sequence.\n\\<close>\n  lemma quasi_sturm_seq: \"quasi_sturm_seq ps\" ..\n\n(*<*)\n  lemma ps_first_two:\n    obtains q ps' where \"ps = p # q # ps'\"\n    using hd_ps_p length_ps_ge_2\n      by (cases ps, simp, clarsimp, rename_tac ps', case_tac ps', auto)\n\n  lemma ps_first: \"ps ! 0 = p\" by (rule ps_first_two, simp)\n\n  \n\n(*<*)\nlemma [simp]: \"\\<not>quasi_sturm_seq []\" by (simp add: quasi_sturm_seq_def)\n(*>*)\n\ntext \\<open>\n  Any suffix of a Quasi-Sturm sequence is again a Quasi-Sturm sequence.\n\\<close>\n\nlemma quasi_sturm_seq_Cons:\n  assumes \"quasi_sturm_seq (p#ps)\" and \"ps \\<noteq> []\"\n  shows \"quasi_sturm_seq ps\"\nproof (unfold_locales)\n  show \"ps \\<noteq> []\" by fact\nnext\n  from assms(1) interpret quasi_sturm_seq \"p#ps\" .\n  fix x y\n  from last_ps_sgn_const and \\<open>ps \\<noteq> []\\<close>\n      show \"sgn (poly (last ps) x) = sgn (poly (last ps) y)\" by simp_all\nnext\n  from assms(1) interpret quasi_sturm_seq \"p#ps\" .\n  fix i x\n  assume \"i < length ps - 2\" and \"poly (ps ! (i+1)) x = 0\"\n  with signs[of \"i+1\"]\n      show \"poly (ps ! (i+2)) x * poly (ps ! i) x < 0\" by simp\nqed\n\n\n\nsubsection \\<open>Auxiliary lemmas about roots and sign changes\\<close>\n\nlemma sturm_adjacent_root_aux:\n  assumes \"i < length (ps :: real poly list) - 1\"\n  assumes \"poly (ps ! i) x = 0\" and \"poly (ps ! (i + 1)) x = 0\"\n  assumes \"\\<And>i x. \\<lbrakk>i < length ps - 2; poly (ps ! (i+1)) x = 0\\<rbrakk>\n                   \\<Longrightarrow> sgn (poly (ps ! (i+2)) x) = - sgn (poly (ps ! i) x)\"\n  shows \"\\<forall>j\\<le>i+1. poly (ps ! j) x = 0\"\nusing assms\nproof (induction i)\n  case 0 thus ?case by (clarsimp, rename_tac j, case_tac j, simp_all)\nnext\n  case (Suc i)\n    from Suc.prems(1,2)\n        have \"sgn (poly (ps ! (i + 2)) x) = - sgn (poly (ps ! i) x)\"\n        by (intro assms(4)) simp_all\n    with Suc.prems(3) have \"poly (ps ! i) x = 0\" by (simp add: sgn_zero_iff)\n    with Suc.prems have \"\\<forall>j\\<le>i+1. poly (ps ! j) x = 0\"\n        by (intro Suc.IH, simp_all)\n    with Suc.prems(3) show ?case\n      by (clarsimp, rename_tac j, case_tac \"j = Suc (Suc i)\", simp_all)\nqed\n\n\ntext \\<open>\n  This function splits the sign list of a Sturm sequence at a\n  position @{term x} that is not a root of @{term p} into a\n  list of sublists such that the number of sign changes within\n  every sublist is constant in the neighbourhood of @{term x},\n  thus proving that the total number is also constant.\n\\<close>\nfun split_sign_changes where\n\"split_sign_changes [p] (x :: real) = [[p]]\" |\n\"split_sign_changes [p,q] x = [[p,q]]\" |\n\"split_sign_changes (p#q#r#ps) x =\n    (if poly p x \\<noteq> 0 \\<and> poly q x = 0 then\n       [p,q,r] # split_sign_changes (r#ps) x\n     else\n       [p,q] # split_sign_changes (q#r#ps) x)\"\n\nlemma (in quasi_sturm_seq) split_sign_changes_subset[dest]:\n  \"ps' \\<in> set (split_sign_changes ps x) \\<Longrightarrow> set ps' \\<subseteq> set ps\"\napply (insert ps_not_Nil)\napply (induction ps x rule: split_sign_changes.induct)\napply (simp, simp, rename_tac p q r ps x,\n       case_tac \"poly p x \\<noteq> 0 \\<and> poly q x = 0\", auto)\ndone\n\ntext \\<open>\n  A custom induction rule for @{term split_sign_changes} that\n  uses the fact that all the intermediate parameters in calls\n  of @{term split_sign_changes} are quasi-Sturm sequences.\n\\<close>\nlemma (in quasi_sturm_seq) split_sign_changes_induct:\n  \"\\<lbrakk>\\<And>p x. P [p] x; \\<And>p q x. quasi_sturm_seq [p,q] \\<Longrightarrow> P [p,q] x;\n    \\<And>p q r ps x. quasi_sturm_seq (p#q#r#ps) \\<Longrightarrow>\n       \\<lbrakk>poly p x \\<noteq> 0 \\<Longrightarrow> poly q x = 0 \\<Longrightarrow> P (r#ps) x;\n        poly q x \\<noteq> 0 \\<Longrightarrow> P (q#r#ps) x;\n        poly p x = 0 \\<Longrightarrow> P (q#r#ps) x\\<rbrakk>\n           \\<Longrightarrow> P (p#q#r#ps) x\\<rbrakk> \\<Longrightarrow> P ps x\"\nproof goal_cases\n  case prems: 1\n  have \"quasi_sturm_seq ps\" ..\n  with prems show ?thesis\n  proof (induction ps x rule: split_sign_changes.induct)\n    case (3 p q r ps x)\n      show ?case\n      proof (rule 3(5)[OF 3(6)])\n        assume A: \"poly p x \\<noteq> 0\" \"poly q x = 0\"\n        from 3(6) have \"quasi_sturm_seq (r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with 3 A show \"P (r # ps) x\" by blast\n      next\n        assume A: \"poly q x \\<noteq> 0\"\n        from 3(6) have \"quasi_sturm_seq (q#r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with 3 A show \"P (q # r # ps) x\" by blast\n      next\n        assume A: \"poly p x = 0\"\n        from 3(6) have \"quasi_sturm_seq (q#r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with 3 A show \"P (q # r # ps) x\" by blast\n      qed\n  qed simp_all\nqed\n\ntext \\<open>\n  The total number of sign changes in the split list is the same\n  as the number of sign changes in the original list.\n\\<close>\nlemma (in quasi_sturm_seq) split_sign_changes_correct:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  defines \"sign_changes' \\<equiv> \\<lambda>ps x.\n               \\<Sum>ps'\\<leftarrow>split_sign_changes ps x. sign_changes ps' x\"\n  shows \"sign_changes' ps x\\<^sub>0 = sign_changes ps x\\<^sub>0\"\nusing assms(1)\nproof (induction x\\<^sub>0 rule: split_sign_changes_induct)\ncase (3 p q r ps x\\<^sub>0)\n  hence \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n  note IH = 3(2,3,4)\n  show ?case\n  proof (cases \"poly q x\\<^sub>0 = 0\")\n    case True\n      from 3 interpret quasi_sturm_seq \"p#q#r#ps\" by simp\n      from signs[of 0] and True have\n           sgn_r_x0: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n      with 3 have \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n      from sign_changes_distrib[OF this, of \"[p,q]\" ps]\n        have \"sign_changes (p#q#r#ps) x\\<^sub>0 =\n                  sign_changes ([p, q, r]) x\\<^sub>0 + sign_changes (r # ps) x\\<^sub>0\" by simp\n      also have \"sign_changes (r#ps) x\\<^sub>0 = sign_changes' (r#ps) x\\<^sub>0\"\n          using \\<open>poly q x\\<^sub>0 = 0\\<close> \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\\<open>poly r x\\<^sub>0 \\<noteq> 0\\<close>\n          by (intro IH(1)[symmetric], simp_all)\n      finally show ?thesis unfolding sign_changes'_def\n          using True \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> by simp\n  next\n    case False\n      from sign_changes_distrib[OF this, of \"[p]\" \"r#ps\"]\n          have \"sign_changes (p#q#r#ps) x\\<^sub>0 =\n                  sign_changes ([p,q]) x\\<^sub>0 + sign_changes (q#r#ps) x\\<^sub>0\" by simp\n      also have \"sign_changes (q#r#ps) x\\<^sub>0 = sign_changes' (q#r#ps) x\\<^sub>0\"\n          using \\<open>poly q x\\<^sub>0 \\<noteq> 0\\<close> \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\n          by (intro IH(2)[symmetric], simp_all)\n      finally show ?thesis unfolding sign_changes'_def\n          using False by simp\n    qed\nqed (simp_all add: sign_changes_def sign_changes'_def)\n\n\ntext \\<open>\n  We now prove that if $p(x)\\neq 0$, the number of sign changes of a Sturm sequence of $p$\n  at $x$ is constant in a neighbourhood of $x$.\n\\<close>\n\nlemma (in quasi_sturm_seq) split_sign_changes_correct_nbh:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  defines \"sign_changes' \\<equiv> \\<lambda>x\\<^sub>0 ps x.\n               \\<Sum>ps'\\<leftarrow>split_sign_changes ps x\\<^sub>0. sign_changes ps' x\"\n  shows \"eventually (\\<lambda>x. sign_changes' x\\<^sub>0 ps x = sign_changes ps x) (at x\\<^sub>0)\"\nproof (rule eventually_mono)\n  show \"eventually (\\<lambda>x. \\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\"\n      by (rule eventually_ball_finite, auto intro: poly_neighbourhood_same_sign)\nnext\n  fix x\n  show \"(\\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)) \\<Longrightarrow>\n        sign_changes' x\\<^sub>0 ps x = sign_changes ps x\"\n  proof -\n    fix x assume nbh: \"\\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n    thus \"sign_changes' x\\<^sub>0 ps x = sign_changes ps x\" using assms(1)\n    proof (induction x\\<^sub>0 rule: split_sign_changes_induct)\n    case (3 p q r ps x\\<^sub>0)\n      hence \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n      note IH = 3(2,3,4)\n      show ?case\n      proof (cases \"poly q x\\<^sub>0 = 0\")\n        case True\n          from 3 interpret quasi_sturm_seq \"p#q#r#ps\" by simp\n          from signs[of 0] and True have\n               sgn_r_x0: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n          with 3 have \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n          with nbh 3(5) have \"poly r x \\<noteq> 0\" by (auto simp: sgn_zero_iff)\n          from sign_changes_distrib[OF this, of \"[p,q]\" ps]\n            have \"sign_changes (p#q#r#ps) x =\n                      sign_changes ([p, q, r]) x + sign_changes (r # ps) x\" by simp\n          also have \"sign_changes (r#ps) x = sign_changes' x\\<^sub>0 (r#ps) x\"\n              using \\<open>poly q x\\<^sub>0 = 0\\<close> nbh \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\\<open>poly r x\\<^sub>0 \\<noteq> 0\\<close>\n              by (intro IH(1)[symmetric], simp_all)\n          finally show ?thesis unfolding sign_changes'_def\n              using True \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close>by simp\n      next\n        case False\n          with nbh 3(5) have \"poly q x \\<noteq> 0\" by (auto simp: sgn_zero_iff)\n          from sign_changes_distrib[OF this, of \"[p]\" \"r#ps\"]\n              have \"sign_changes (p#q#r#ps) x =\n                      sign_changes ([p,q]) x + sign_changes (q#r#ps) x\" by simp\n          also have \"sign_changes (q#r#ps) x = sign_changes' x\\<^sub>0 (q#r#ps) x\"\n              using \\<open>poly q x\\<^sub>0 \\<noteq> 0\\<close> nbh \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\n              by (intro IH(2)[symmetric], simp_all)\n          finally show ?thesis unfolding sign_changes'_def\n              using False by simp\n        qed\n    qed (simp_all add: sign_changes_def sign_changes'_def)\n  qed\nqed\n\n\n\nlemma (in quasi_sturm_seq) hd_nonzero_imp_sign_changes_const_aux:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\" and \"ps' \\<in> set (split_sign_changes ps x\\<^sub>0)\"\n  shows \"eventually (\\<lambda>x. sign_changes ps' x = sign_changes ps' x\\<^sub>0) (at x\\<^sub>0)\"\nusing assms\nproof (induction x\\<^sub>0 rule: split_sign_changes_induct)\n  case (1 p x)\n    thus ?case by (simp add: sign_changes_def)\nnext\n  case (2 p q x\\<^sub>0)\n    hence [simp]: \"ps' = [p,q]\" by simp\n    from 2 have \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n    from 2(1) interpret quasi_sturm_seq \"[p,q]\" .\n    from poly_neighbourhood_same_sign[OF \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close>]\n        have \"eventually (\\<lambda>x. sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\" .\n    moreover from last_ps_sgn_const\n        have sgn_q: \"\\<And>x. sgn (poly q x) = sgn (poly q x\\<^sub>0)\" by simp\n    ultimately have A:  \"eventually (\\<lambda>x. \\<forall>p\\<in>set[p,q]. sgn (poly p x) =\n                           sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\" by simp\n    thus ?case by (force intro: eventually_mono[OF A]\n                                sign_changes_cong')\nnext\n  case (3 p q r ps'' x\\<^sub>0)\n    hence p_not_0: \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n    note sturm = 3(1)\n    note IH = 3(2,3)\n    note ps''_props = 3(6)\n    show ?case\n    proof (cases \"poly q x\\<^sub>0 = 0\")\n      case True\n        note q_0 = this\n        from sturm interpret quasi_sturm_seq \"p#q#r#ps''\" .\n        from signs[of 0] and q_0\n            have signs': \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n        with p_not_0 have r_not_0: \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n        show ?thesis\n        proof (cases \"ps' \\<in> set (split_sign_changes (r # ps'') x\\<^sub>0)\")\n          case True\n            show ?thesis by (rule IH(1), fact, fact, simp add: r_not_0, fact)\n        next\n          case False\n            with ps''_props p_not_0 q_0 have ps'_props: \"ps' = [p,q,r]\" by simp\n            from signs[of 0] and q_0\n                have sgn_r: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n            from p_not_0 sgn_r\n              have A: \"eventually (\\<lambda>x. sgn (poly p x) = sgn (poly p x\\<^sub>0) \\<and>\n                                     sgn (poly r x) = sgn (poly r x\\<^sub>0)) (at x\\<^sub>0)\"\n                  by (intro eventually_conj poly_neighbourhood_same_sign,\n                      simp_all add: r_not_0)\n            show ?thesis\n            proof (rule eventually_mono[OF A], clarify,\n                   subst ps'_props, subst sign_changes_sturm_triple)\n              fix x assume A: \"sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n                       and B: \"sgn (poly r x) = sgn (poly r x\\<^sub>0)\"\n              have prod_neg: \"\\<And>a (b::real). \\<lbrakk>a>0; b>0; a*b<0\\<rbrakk> \\<Longrightarrow> False\"\n                             \"\\<And>a (b::real). \\<lbrakk>a<0; b<0; a*b<0\\<rbrakk> \\<Longrightarrow> False\"\n                  by (drule mult_pos_pos, simp, simp,\n                      drule mult_neg_neg, simp, simp)\n              from A and \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> show \"poly p x \\<noteq> 0\"\n                  by (force simp: sgn_zero_iff)\n\n              with sgn_r p_not_0 r_not_0 A B\n                  have \"poly r x * poly p x < 0\" \"poly r x \\<noteq> 0\"\n                  by (metis sgn_less sgn_mult, metis sgn_0_0)\n              with sgn_r show sgn_r': \"sgn (poly r x) = - sgn (poly p x)\"\n                  apply (simp add: sgn_real_def not_le not_less\n                             split: if_split_asm, intro conjI impI)\n                  using prod_neg[of \"poly r x\" \"poly p x\"] apply force+\n                  done\n\n              show \"1 = sign_changes ps' x\\<^sub>0\"\n                  by (subst ps'_props, subst sign_changes_sturm_triple,\n                      fact, metis A B sgn_r', simp)\n            qed\n        qed\n    next\n      case False\n        note q_not_0 = this\n        show ?thesis\n        proof (cases \"ps' \\<in> set (split_sign_changes (q # r # ps'') x\\<^sub>0)\")\n          case True\n            show ?thesis by (rule IH(2), fact, simp add: q_not_0, fact)\n        next\n          case False\n            with ps''_props and q_not_0 have \"ps' = [p, q]\" by simp\n            hence [simp]: \"\\<forall>p\\<in>set ps'. poly p x\\<^sub>0 \\<noteq> 0\"\n                using q_not_0 p_not_0 by simp\n            show ?thesis\n            proof (rule eventually_mono)\n              fix x assume \"\\<forall>p\\<in>set ps'. sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n              thus \"sign_changes ps' x = sign_changes ps' x\\<^sub>0\"\n                  by (rule sign_changes_cong')\n            next\n              show \"eventually (\\<lambda>x. \\<forall>p\\<in>set ps'.\n                        sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\"\n                  by (force intro: eventually_ball_finite\n                                   poly_neighbourhood_same_sign)\n            qed\n    qed\n  qed\nqed\n\n\nlemma (in quasi_sturm_seq) hd_nonzero_imp_sign_changes_const:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  shows \"eventually (\\<lambda>x. sign_changes ps x = sign_changes ps x\\<^sub>0) (at x\\<^sub>0)\"\nproof-\n  let ?pss = \"split_sign_changes ps x\\<^sub>0\"\n  let ?f = \"\\<lambda>pss x. \\<Sum>ps'\\<leftarrow>pss. sign_changes ps' x\"\n  {\n    fix pss assume \"\\<And>ps'. ps'\\<in>set pss \\<Longrightarrow>\n        eventually (\\<lambda>x. sign_changes ps' x = sign_changes ps' x\\<^sub>0) (at x\\<^sub>0)\"\n    hence \"eventually (\\<lambda>x. ?f pss x = ?f pss x\\<^sub>0) (at x\\<^sub>0)\"\n    proof (induction pss)\n      case (Cons ps' pss)\n      then show ?case\n        apply (rule eventually_mono[OF eventually_conj])\n        apply (auto simp add: Cons.prems)\n        done\n    qed simp\n  }\n  note A = this[of ?pss]\n  have B: \"eventually (\\<lambda>x. ?f ?pss x = ?f ?pss x\\<^sub>0) (at x\\<^sub>0)\"\n      by (rule A, rule hd_nonzero_imp_sign_changes_const_aux[OF assms], simp)\n  note C = split_sign_changes_correct_nbh[OF assms]\n  note D = split_sign_changes_correct[OF assms]\n  note E = eventually_conj[OF B C]\n  show ?thesis by (rule eventually_mono[OF E], auto simp: D)\nqed\n\n(*<*)\nhide_fact quasi_sturm_seq.split_sign_changes_correct_nbh\nhide_fact quasi_sturm_seq.hd_nonzero_imp_sign_changes_const_aux\n(*>*)\n\nlemma (in sturm_seq) p_nonzero_imp_sign_changes_const:\n  \"poly p x\\<^sub>0 \\<noteq> 0 \\<Longrightarrow>\n       eventually (\\<lambda>x. sign_changes ps x = sign_changes ps x\\<^sub>0) (at x\\<^sub>0)\"\n  using hd_nonzero_imp_sign_changes_const by simp\n\n\ntext \\<open>\n  If $x$ is a root of $p$ and $p$ is not the zero polynomial, the\n  number of sign changes of a Sturm chain of $p$ decreases by 1 at $x$.\n\\<close>\nlemma (in sturm_seq) p_zero:\n  assumes \"poly p x\\<^sub>0 = 0\" \"p \\<noteq> 0\"\n  shows \"eventually (\\<lambda>x. sign_changes ps x =\n      sign_changes ps x\\<^sub>0 + (if x<x\\<^sub>0 then 1 else 0)) (at x\\<^sub>0)\"\nproof-\n  from ps_first_two obtain q ps' where [simp]: \"ps = p#q#ps'\" .\n  hence \"ps!1 = q\" by simp\n  have \"eventually (\\<lambda>x. x \\<noteq> x\\<^sub>0) (at x\\<^sub>0)\"\n      by (simp add: eventually_at, rule exI[of _ 1], simp)\n  moreover from p_squarefree and assms(1) have \"poly q x\\<^sub>0 \\<noteq> 0\" by simp\n  {\n      have A: \"quasi_sturm_seq ps\" ..\n      with quasi_sturm_seq_Cons[of p \"q#ps'\"]\n          interpret quasi_sturm_seq \"q#ps'\" by simp\n      from \\<open>poly q x\\<^sub>0 \\<noteq> 0\\<close> have \"eventually (\\<lambda>x. sign_changes (q#ps') x =\n                                     sign_changes (q#ps') x\\<^sub>0) (at x\\<^sub>0)\"\n      using hd_nonzero_imp_sign_changes_const[where x\\<^sub>0=x\\<^sub>0] by simp\n  }\n  moreover note poly_neighbourhood_without_roots[OF assms(2)] deriv[OF assms(1)]\n  ultimately\n      have A: \"eventually (\\<lambda>x. x \\<noteq> x\\<^sub>0 \\<and> poly p x \\<noteq> 0 \\<and>\n                   sgn (poly (p*ps!1) x) = (if x > x\\<^sub>0 then 1 else -1) \\<and>\n                   sign_changes (q#ps') x = sign_changes (q#ps') x\\<^sub>0) (at x\\<^sub>0)\"\n           by (simp only: \\<open>ps!1 = q\\<close>, intro eventually_conj)\n  show ?thesis\n  proof (rule eventually_mono[OF A], clarify, goal_cases)\n    case prems: (1 x)\n    from zero_less_mult_pos have zero_less_mult_pos':\n        \"\\<And>a b. \\<lbrakk>(0::real) < a*b; 0 < b\\<rbrakk> \\<Longrightarrow> 0 < a\"\n        by (subgoal_tac \"a*b = b*a\", auto)\n    from prems have \"poly q x \\<noteq> 0\" and q_sgn: \"sgn (poly q x) =\n              (if x < x\\<^sub>0 then -sgn (poly p x) else sgn (poly p x))\"\n        by (auto simp add: sgn_real_def elim: linorder_neqE_linordered_idom\n                 dest: mult_neg_neg zero_less_mult_pos\n                 zero_less_mult_pos' split: if_split_asm)\n     from sign_changes_distrib[OF \\<open>poly q x \\<noteq> 0\\<close>, of \"[p]\" ps']\n        have \"sign_changes ps x = sign_changes [p,q] x + sign_changes (q#ps') x\"\n            by simp\n    also from q_sgn and \\<open>poly p x \\<noteq> 0\\<close>\n        have \"sign_changes [p,q] x = (if x<x\\<^sub>0 then 1 else 0)\"\n        by (simp add: sign_changes_def sgn_zero_iff split: if_split_asm)\n    also note prems(4)\n    also from assms(1) have \"sign_changes (q#ps') x\\<^sub>0 = sign_changes ps x\\<^sub>0\"\n        by (simp add: sign_changes_def)\n    finally show ?case by simp\n  qed\nqed\n\ntext \\<open>\n  With these two results, we can now show that if $p$ is nonzero, the number\n  of roots in an interval of the form $(a;b]$ is the difference of the sign changes\n  of a Sturm sequence of $p$ at $a$ and $b$.\\\\\n  First, however, we prove the following auxiliary lemma that shows that\n  if a function $f: \\RR\\to\\NN$ is locally constant at any $x\\in(a;b]$, it is constant\n  across the entire interval $(a;b]$:\n\\<close>\n\nlemma count_roots_between_aux:\n  assumes \"a \\<le> b\"\n  assumes \"\\<forall>x::real. a < x \\<and> x \\<le> b \\<longrightarrow> eventually (\\<lambda>\\<xi>. f \\<xi> = (f x::nat)) (at x)\"\n  shows \"\\<forall>x. a < x \\<and> x \\<le> b \\<longrightarrow> f x = f b\"\nproof (clarify)\n  fix x assume \"x > a\" \"x \\<le> b\"\n  with assms have \"\\<forall>x'. x \\<le> x' \\<and> x' \\<le> b \\<longrightarrow>\n                       eventually (\\<lambda>\\<xi>. f \\<xi> = f x') (at x')\" by auto\n  from fun_eq_in_ivl[OF \\<open>x \\<le> b\\<close> this] show \"f x = f b\" .\nqed\n\ntext \\<open>\n  Now we can prove the actual root-counting theorem:\n\\<close>\n\n\n              show \"sign_changes ps a = sign_changes ps b\"\n              proof (cases \"a = b\")\n                case False\n                  define x where \"x = min (a+\\<delta>/2) b\"\n                  with False have \"a < x\" \"x < a+\\<delta>\" \"x \\<le> b\"\n                     using \\<open>\\<delta> > 0\\<close> \\<open>a \\<le> b\\<close> by simp_all\n                  from \\<delta>_props \\<open>a < x\\<close> \\<open>x < a+\\<delta>\\<close>\n                      have \"sign_changes ps a = sign_changes ps x\" by simp\n                  also from A \\<open>a < x\\<close> \\<open>x \\<le> b\\<close> have \"... = sign_changes ps b\"\n                      by blast\n                  finally show ?thesis .\n              qed simp\n          qed\n\n      next\n        case True\n          from poly_roots_finite[OF assms(1)]\n            have fin: \"finite {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0}\"\n            by (force intro: finite_subset)\n          from True have \"{x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} \\<noteq> {}\" by blast\n          with fin have card_greater_0:\n              \"card {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} > 0\" by fastforce\n\n          define x\\<^sub>2 where \"x\\<^sub>2 = Min {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0}\"\n          from Min_in[OF fin] and True\n              have x\\<^sub>2_props: \"x\\<^sub>2 > a\" \"x\\<^sub>2 \\<le> b\" \"poly p x\\<^sub>2 = 0\"\n              unfolding x\\<^sub>2_def by blast+\n          from Min_le[OF fin] x\\<^sub>2_props\n              have x\\<^sub>2_le: \"\\<And>x'. \\<lbrakk>x' > a; x' \\<le> b; poly p x' = 0\\<rbrakk> \\<Longrightarrow> x\\<^sub>2 \\<le> x'\"\n              unfolding x\\<^sub>2_def by simp\n\n          have left: \"{x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} = {x\\<^sub>2}\"\n              using x\\<^sub>2_props x\\<^sub>2_le by force\n          hence [simp]: \"card {x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} = 1\" by simp\n\n          from p_zero[OF \\<open>poly p x\\<^sub>2 = 0\\<close> \\<open>p \\<noteq> 0\\<close>,\n              unfolded eventually_at dist_real_def] guess \\<epsilon> ..\n          hence \\<epsilon>_props: \"\\<epsilon> > 0\"\n              \"\\<forall>x. x \\<noteq> x\\<^sub>2 \\<and> \\<bar>x - x\\<^sub>2\\<bar> < \\<epsilon> \\<longrightarrow>\n                   sign_changes ps x = sign_changes ps x\\<^sub>2 +\n                       (if x < x\\<^sub>2 then 1 else 0)\" by auto\n          define x\\<^sub>1 where \"x\\<^sub>1 = max (x\\<^sub>2 - \\<epsilon> / 2) a\"\n          have \"\\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar> < \\<epsilon>\" using \\<open>\\<epsilon> > 0\\<close> x\\<^sub>2_props by (simp add: x\\<^sub>1_def)\n          hence \"sign_changes ps x\\<^sub>1 =\n              (if x\\<^sub>1 < x\\<^sub>2 then sign_changes ps x\\<^sub>2 + 1 else sign_changes ps x\\<^sub>2)\"\n              using \\<epsilon>_props(2) by (cases \"x\\<^sub>1 = x\\<^sub>2\", auto)\n          hence \"sign_changes ps x\\<^sub>1 - sign_changes ps x\\<^sub>2 = 1\"\n              unfolding x\\<^sub>1_def using x\\<^sub>2_props \\<open>\\<epsilon> > 0\\<close> by simp\n\n          also have \"x\\<^sub>2 \\<notin> {x. a < x \\<and> x \\<le> x\\<^sub>1 \\<and> poly p x = 0}\"\n              unfolding x\\<^sub>1_def using \\<open>\\<epsilon> > 0\\<close> by force\n          with left have \"{x. a < x \\<and> x \\<le> x\\<^sub>1 \\<and> poly p x = 0} = {}\" by force\n          with less(1)[of a x\\<^sub>1] have \"sign_changes ps x\\<^sub>1 = sign_changes ps a\"\n              unfolding x\\<^sub>1_def \\<open>\\<epsilon> > 0\\<close> by (force simp: card_greater_0)\n\n          finally have signs_left:\n              \"sign_changes ps a - int (sign_changes ps x\\<^sub>2) = 1\" by simp\n\n          have \"{x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} =\n                {x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} \\<union>\n                {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0}\" using x\\<^sub>2_props by auto\n          also note left\n          finally have A: \"card {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0} + 1 =\n              card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" using fin by simp\n          hence \"card {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0} <\n                 card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by simp\n          from less(1)[OF this x\\<^sub>2_props(2)] and A\n              have signs_right: \"sign_changes ps x\\<^sub>2 - int (sign_changes ps b) + 1 =\n                  card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by simp\n\n          from signs_left and signs_right show ?thesis by simp\n        qed\n  qed\n  thus ?thesis by simp\nqed\n\ntext \\<open>\n  By applying this result to a sufficiently large upper bound, we can effectively count\n  the number of roots ``between $a$ and infinity'', i.\\,e. the roots greater than $a$:\n\\<close>\nlemma (in sturm_seq) count_roots_above:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes ps a - sign_changes_inf ps =\n             card {x. x > a \\<and> poly p x = 0}\"\nproof-\n  have \"p \\<in> set ps\" using hd_in_set[OF ps_not_Nil] by simp\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n  let ?u = \"max a u\"\n  {fix x assume \"poly p x = 0\" hence \"x \\<le> ?u\"\n   using lu_props(3)[OF \\<open>p \\<in> set ps\\<close>, of x] \\<open>p \\<noteq> 0\\<close>\n       by (cases \"u \\<le> x\", auto simp: sgn_zero_iff)\n  } note [simp] = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p ?u)) ps = map poly_inf ps\" by simp\n  hence \"sign_changes ps a - sign_changes_inf ps =\n             sign_changes ps a - sign_changes ps ?u\"\n      by (simp_all only: sign_changes_def sign_changes_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. a < x \\<and> x \\<le> ?u \\<and> poly p x = 0}\" by simp\n  also have \"{x. a < x \\<and> x \\<le> ?u \\<and> poly p x = 0} = {x. a < x \\<and> poly p x = 0}\"\n      using lu_props by auto\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The same works analogously for the number of roots below $a$ and the\n  total number of roots.\n\\<close>\n\nlemma (in sturm_seq) count_roots_below:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes_neg_inf ps - sign_changes ps a =\n             card {x. x \\<le> a \\<and> poly p x = 0}\"\nproof-\n  have \"p \\<in> set ps\" using hd_in_set[OF ps_not_Nil] by simp\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n  let ?l = \"min a l\"\n  {fix x assume \"poly p x = 0\" hence \"x > ?l\"\n   using lu_props(4)[OF \\<open>p \\<in> set ps\\<close>, of x] \\<open>p \\<noteq> 0\\<close>\n       by (cases \"l < x\", auto simp: sgn_zero_iff)\n  } note [simp] = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p ?l)) ps = map poly_neg_inf ps\" by simp\n  hence \"sign_changes_neg_inf ps - sign_changes ps a =\n             sign_changes ps ?l - sign_changes ps a\"\n      by (simp_all only: sign_changes_def sign_changes_neg_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. ?l < x \\<and> x \\<le> a \\<and> poly p x = 0}\" by simp\n  also have \"{x. ?l < x \\<and> x \\<le> a \\<and> poly p x = 0} = {x. a \\<ge> x \\<and> poly p x = 0}\"\n      using lu_props by auto\n  finally show ?thesis .\nqed\n\nlemma (in sturm_seq) count_roots:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes_neg_inf ps - sign_changes_inf ps =\n             card {x. poly p x = 0}\"\nproof-\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p l)) ps = map poly_neg_inf ps\"\n         \"map (\\<lambda>p. sgn (poly p u)) ps = map poly_inf ps\" by simp_all\n  hence \"sign_changes_neg_inf ps - sign_changes_inf ps =\n             sign_changes ps l - sign_changes ps u\"\n      by (simp_all only: sign_changes_def sign_changes_inf_def\n                         sign_changes_neg_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. l < x \\<and> x \\<le> u \\<and> poly p x = 0}\" by simp\n  also have \"{x. l < x \\<and> x \\<le> u \\<and> poly p x = 0} = {x. poly p x = 0}\"\n      using lu_props assms by simp\n  finally show ?thesis .\nqed\n\n\n\nsubsection \\<open>Constructing Sturm sequences\\<close>\n\nsubsection \\<open>The canonical Sturm sequence\\<close>\n\ntext \\<open>\n  In this subsection, we will present the canonical Sturm sequence construction for\n  a polynomial $p$ without multiple roots that is very similar to the Euclidean\n  algorithm:\n  $$p_i = \\begin{cases}\n    p & \\text{for}\\ i = 1\\\\\n    p' & \\text{for}\\ i = 2\\\\\n    -p_{i-2}\\ \\text{mod}\\ p_{i-1} & \\text{otherwise}\n  \\end{cases}$$\n  We break off the sequence at the first constant polynomial.\n\\<close>\n\n(*<*)\nlemma degree_mod_less': \"degree q \\<noteq> 0 \\<Longrightarrow> degree (p mod q) < degree q\"\n  by (metis degree_0 degree_mod_less not_gr0)\n(*>*)\n\nfunction sturm_aux where\n\"sturm_aux (p :: real poly) q =\n    (if degree q = 0 then [p,q] else p # sturm_aux q (-(p mod q)))\"\n  by (pat_completeness, simp_all)\ntermination by (relation \"measure (degree \\<circ> snd)\",\n                simp_all add: o_def degree_mod_less')\n\n(*<*)\ndeclare sturm_aux.simps[simp del]\n(*>*)\n\ndefinition sturm where \"sturm p = sturm_aux p (pderiv p)\"\n\ntext \\<open>Next, we show some simple facts about this construction:\\<close>\n\nlemma sturm_0[simp]: \"sturm 0 = [0,0]\"\n    by (unfold sturm_def, subst sturm_aux.simps, simp)\n\nlemma [simp]: \"sturm_aux p q = [] \\<longleftrightarrow> False\"\n    by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, auto)\n\nlemma sturm_neq_Nil[simp]: \"sturm p \\<noteq> []\" unfolding sturm_def by simp\n\nlemma [simp]: \"hd (sturm p) = p\"\n  unfolding sturm_def by (subst sturm_aux.simps, simp)\n\nlemma [simp]: \"p \\<in> set (sturm p)\"\n  using hd_in_set[OF sturm_neq_Nil] by simp\n\nlemma [simp]: \"length (sturm p) \\<ge> 2\"\nproof-\n  {fix q have \"length (sturm_aux p q) \\<ge> 2\"\n           by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, auto)\n  }\n  thus ?thesis unfolding sturm_def .\nqed\n\nlemma [simp]: \"degree (last (sturm p)) = 0\"\nproof-\n  {fix q have \"degree (last (sturm_aux p q)) = 0\"\n           by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, simp)\n  }\n  thus ?thesis unfolding sturm_def .\nqed\n\nlemma [simp]: \"sturm_aux p q ! 0 = p\"\n    by (subst sturm_aux.simps, simp)\nlemma [simp]: \"sturm_aux p q ! Suc 0 = q\"\n    by (subst sturm_aux.simps, simp)\n\nlemma [simp]: \"sturm p ! 0 = p\"\n    unfolding sturm_def by simp\nlemma [simp]: \"sturm p ! Suc 0 = pderiv p\"\n    unfolding sturm_def by simp\n\n\nlemma sturm_indices:\n  assumes \"i < length (sturm p) - 2\"\n  shows \"sturm p!(i+2) = -(sturm p!i mod sturm p!(i+1))\"\nproof-\n {fix ps q\n  have \"\\<lbrakk>ps = sturm_aux p q; i < length ps - 2\\<rbrakk>\n            \\<Longrightarrow> ps!(i+2) = -(ps!i mod ps!(i+1))\"\n  proof (induction p q arbitrary: ps i rule: sturm_aux.induct)\n    case (1 p q)\n      show ?case\n      proof (cases \"i = 0\")\n        case False\n          then obtain i' where [simp]: \"i = Suc i'\" by (cases i, simp_all)\n          hence \"length ps \\<ge> 4\" using 1 by simp\n          with 1(2) have deg: \"degree q \\<noteq> 0\"\n              by (subst (asm) sturm_aux.simps, simp split: if_split_asm)\n          with 1(2) obtain ps' where [simp]: \"ps = p # ps'\"\n              by (subst (asm) sturm_aux.simps, simp)\n          with 1(2) deg have ps': \"ps' = sturm_aux q (-(p mod q))\"\n              by (subst (asm) sturm_aux.simps, simp)\n          from \\<open>length ps \\<ge> 4\\<close> and \\<open>ps = p # ps'\\<close> 1(3) False\n              have \"i - 1 < length ps' - 2\" by simp\n          from 1(1)[OF deg ps' this]\n              show ?thesis by simp\n      next\n        case True\n          with 1(3) have \"length ps \\<ge> 3\" by simp\n          with 1(2) have \"degree q \\<noteq> 0\"\n              by (subst (asm) sturm_aux.simps, simp split: if_split_asm)\n          with 1(2) have [simp]: \"sturm_aux p q ! Suc (Suc 0) = -(p mod q)\"\n              by (subst sturm_aux.simps, simp)\n          from True have \"ps!i = p\" \"ps!(i+1) = q\" \"ps!(i+2) = -(p mod q)\"\n              by (simp_all add: 1(2))\n          thus ?thesis by simp\n      qed\n    qed}\n  from this[OF sturm_def assms] show ?thesis .\nqed\n\ntext \\<open>\n  If the Sturm sequence construction is applied to polynomials $p$ and $q$,\n  the greatest common divisor of $p$ and $q$ a divisor of every element in the\n  sequence. This is obvious from the similarity to Euclid's algorithm for\n  computing the GCD.\n\\<close>\n\nlemma sturm_aux_gcd: \"r \\<in> set (sturm_aux p q) \\<Longrightarrow> gcd p q dvd r\"\nproof (induction p q rule: sturm_aux.induct)\n  case (1 p q)\n    show ?case\n    proof (cases \"r = p\")\n      case False\n        with 1(2) have r: \"r \\<in> set (sturm_aux q (-(p mod q)))\"\n          by (subst (asm) sturm_aux.simps, simp split: if_split_asm,\n              subst sturm_aux.simps, simp)\n        show ?thesis\n        proof (cases \"degree q = 0\")\n          case False\n            hence \"q \\<noteq> 0\" by force\n            with 1(1) [OF False r] show ?thesis\n              by (simp add: gcd_mod_right ac_simps)\n        next\n          case True\n            with 1(2) and \\<open>r \\<noteq> p\\<close> have \"r = q\"\n                by (subst (asm) sturm_aux.simps, simp)\n            thus ?thesis by simp\n        qed\n    qed simp\nqed\n\nlemma sturm_gcd: \"r \\<in> set (sturm p) \\<Longrightarrow> gcd p (pderiv p) dvd r\"\n    unfolding sturm_def by (rule sturm_aux_gcd)\n\ntext \\<open>\n  If two adjacent polynomials in the result of the canonical Sturm chain construction\n  both have a root at some $x$, this $x$ is a root of all polynomials in the sequence.\n\\<close>\n\nlemma sturm_adjacent_root_propagate_left:\n  assumes \"i < length (sturm (p :: real poly)) - 1\"\n  assumes \"poly (sturm p ! i) x = 0\"\n      and \"poly (sturm p ! (i + 1)) x = 0\"\n  shows \"\\<forall>j\\<le>i+1. poly (sturm p ! j) x = 0\"\nusing assms(2)\nproof (intro sturm_adjacent_root_aux[OF assms(1,2,3)], goal_cases)\n  case prems: (1 i x)\n    let ?p = \"sturm p ! i\"\n    let ?q = \"sturm p ! (i + 1)\"\n    let ?r = \"sturm p ! (i + 2)\"\n    from sturm_indices[OF prems(2)] have \"?p = ?p div ?q * ?q - ?r\"\n        by (simp add: div_mult_mod_eq)\n    hence \"poly ?p x = poly (?p div ?q * ?q - ?r) x\" by simp\n    hence \"poly ?p x = -poly ?r x\" using prems(3) by simp\n    thus ?case by (simp add: sgn_minus)\nqed\n\ntext \\<open>\n  Consequently, if this is the case in the canonical Sturm chain of $p$,\n  $p$ must have multiple roots.\n\\<close>\nlemma sturm_adjacent_root_not_squarefree:\n  assumes \"i < length (sturm (p :: real poly)) - 1\"\n          \"poly (sturm p ! i) x = 0\" \"poly (sturm p ! (i + 1)) x = 0\"\n  shows \"\\<not>rsquarefree p\"\nproof-\n  from sturm_adjacent_root_propagate_left[OF assms]\n      have \"poly p x = 0\" \"poly (pderiv p) x = 0\" by auto\n  thus ?thesis by (auto simp: rsquarefree_roots)\nqed\n\n\ntext \\<open>\n  Since the second element of the sequence is chosen to be the derivative of $p$,\n  $p_1$ and $p_2$ fulfil the property demanded by the definition of a Sturm sequence\n  that they locally have opposite sign left of a root $x$ of $p$ and the same sign\n  to the right of $x$.\n\\<close>\n\nlemma sturm_firsttwo_signs_aux:\n  assumes \"(p :: real poly) \\<noteq> 0\" \"q \\<noteq> 0\"\n  assumes q_pderiv:\n      \"eventually (\\<lambda>x. sgn (poly q x) = sgn (poly (pderiv p) x)) (at x\\<^sub>0)\"\n  assumes p_0: \"poly p (x\\<^sub>0::real) = 0\"\n  shows \"eventually (\\<lambda>x. sgn (poly (p*q) x) = (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\nproof-\n  have A: \"eventually (\\<lambda>x. poly p x \\<noteq> 0 \\<and> poly q x \\<noteq> 0 \\<and>\n               sgn (poly q x) = sgn (poly (pderiv p) x)) (at x\\<^sub>0)\"\n      using \\<open>p \\<noteq> 0\\<close>  \\<open>q \\<noteq> 0\\<close>\n      by (intro poly_neighbourhood_same_sign q_pderiv\n                poly_neighbourhood_without_roots eventually_conj)\n  then obtain \\<epsilon> where \\<epsilon>_props: \"\\<epsilon> > 0\" \"\\<forall>x. x \\<noteq> x\\<^sub>0 \\<and> \\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon> \\<longrightarrow>\n      poly p x \\<noteq> 0 \\<and> poly q x \\<noteq> 0 \\<and> sgn (poly (pderiv p) x) = sgn (poly q x)\"\n      by (auto simp: eventually_at dist_real_def)\n  have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> sgn x * sgn x = 1\"\n      by (auto simp: sgn_real_def)\n\n  show ?thesis\n  proof (simp only: eventually_at dist_real_def, rule exI[of _ \\<epsilon>],\n         intro conjI, fact \\<open>\\<epsilon> > 0\\<close>, clarify)\n    fix x assume \"x \\<noteq> x\\<^sub>0\" \"\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\"\n    with \\<epsilon>_props have [simp]: \"poly p x \\<noteq> 0\" \"poly q x \\<noteq> 0\"\n        \"sgn (poly (pderiv p) x) = sgn (poly q x)\" by auto\n    show \"sgn (poly (p*q) x) = (if x > x\\<^sub>0 then 1 else -1)\"\n    proof (cases \"x \\<ge> x\\<^sub>0\")\n      case True\n        with \\<open>x \\<noteq> x\\<^sub>0\\<close> have \"x > x\\<^sub>0\" by simp\n        from poly_MVT[OF this, of p] guess \\<xi> ..\n        note \\<xi>_props = this\n        with \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close> \\<open>poly p x\\<^sub>0 = 0\\<close> \\<open>x > x\\<^sub>0\\<close> \\<epsilon>_props\n            have \"\\<bar>\\<xi> - x\\<^sub>0\\<bar> < \\<epsilon>\" \"sgn (poly p x) = sgn (x - x\\<^sub>0) * sgn (poly q \\<xi>)\"\n            by (auto simp add: q_pderiv sgn_mult)\n        moreover from \\<xi>_props \\<epsilon>_props \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close>\n            have \"\\<forall>t. \\<xi> \\<le> t \\<and> t \\<le> x \\<longrightarrow> poly q t \\<noteq> 0\" by auto\n        hence \"sgn (poly q \\<xi>) = sgn (poly q x)\" using \\<xi>_props \\<epsilon>_props\n            by (intro no_roots_inbetween_imp_same_sign, simp_all)\n        ultimately show ?thesis using True \\<open>x \\<noteq> x\\<^sub>0\\<close> \\<epsilon>_props \\<xi>_props\n            by (auto simp: sgn_mult sqr_pos)\n    next\n      case False\n        hence \"x < x\\<^sub>0\" by simp\n        hence sgn: \"sgn (x - x\\<^sub>0) = -1\" by simp\n        from poly_MVT[OF \\<open>x < x\\<^sub>0\\<close>, of p] guess \\<xi> ..\n        note \\<xi>_props = this\n        with \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close> \\<open>poly p x\\<^sub>0 = 0\\<close> \\<open>x < x\\<^sub>0\\<close> \\<epsilon>_props\n            have \"\\<bar>\\<xi> - x\\<^sub>0\\<bar> < \\<epsilon>\" \"poly p x = (x - x\\<^sub>0) * poly (pderiv p) \\<xi>\"\n                 \"poly p \\<xi> \\<noteq> 0\" by (auto simp: field_simps)\n        hence \"sgn (poly p x) = sgn (x - x\\<^sub>0) * sgn (poly q \\<xi>)\"\n            using \\<epsilon>_props \\<xi>_props by (auto simp: q_pderiv sgn_mult)\n        moreover from \\<xi>_props \\<epsilon>_props \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close>\n            have \"\\<forall>t. x \\<le> t \\<and> t \\<le> \\<xi> \\<longrightarrow> poly q t \\<noteq> 0\" by auto\n        hence \"sgn (poly q \\<xi>) = sgn (poly q x)\" using \\<xi>_props \\<epsilon>_props\n            by (rule_tac sym, intro no_roots_inbetween_imp_same_sign, simp_all)\n        ultimately show ?thesis using False \\<open>x \\<noteq> x\\<^sub>0\\<close>\n            by (auto simp: sgn_mult sqr_pos)\n    qed\n  qed\nqed\n\nlemma sturm_firsttwo_signs:\n  fixes ps :: \"real poly list\"\n  assumes squarefree: \"rsquarefree p\"\n  assumes p_0: \"poly p (x\\<^sub>0::real) = 0\"\n  shows \"eventually (\\<lambda>x. sgn (poly (p * sturm p ! 1) x) =\n             (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\nproof-\n  from assms have [simp]: \"p \\<noteq> 0\" by (auto simp add: rsquarefree_roots)\n  with squarefree p_0 have [simp]: \"pderiv p \\<noteq> 0\"\n      by (auto simp  add:rsquarefree_roots)\n  from assms show ?thesis\n      by (intro sturm_firsttwo_signs_aux,\n          simp_all add: rsquarefree_roots)\nqed\n\n\ntext \\<open>\n  The construction also obviously fulfils the property about three\n  adjacent polynomials in the sequence.\n\\<close>\n\nlemma sturm_signs:\n  assumes squarefree: \"rsquarefree p\"\n  assumes i_in_range: \"i < length (sturm (p :: real poly)) - 2\"\n  assumes q_0: \"poly (sturm p ! (i+1)) x = 0\" (is \"poly ?q x = 0\")\n  shows \"poly (sturm p ! (i+2)) x * poly (sturm p ! i) x < 0\"\n            (is \"poly ?p x * poly ?r x < 0\")\nproof-\n  from sturm_indices[OF i_in_range]\n      have \"sturm p ! (i+2) = - (sturm p ! i mod sturm p ! (i+1))\"\n           (is \"?r = - (?p mod ?q)\") .\n  hence \"-?r = ?p mod ?q\" by simp\n  with div_mult_mod_eq[of ?p ?q] have \"?p div ?q * ?q - ?r = ?p\" by simp\n  hence \"poly (?p div ?q) x * poly ?q x - poly ?r x = poly ?p x\"\n      by (metis poly_diff poly_mult)\n  with q_0 have r_x: \"poly ?r x = -poly ?p x\" by simp\n  moreover have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> x * x > 0\" apply (case_tac \"x \\<ge> 0\")\n      by (simp_all add: mult_neg_neg)\n  from sturm_adjacent_root_not_squarefree[of i p] assms r_x\n      have \"poly ?p x * poly ?p x > 0\" by (force intro: sqr_pos)\n  ultimately show \"poly ?r x * poly ?p x < 0\" by simp\nqed\n\n\ntext \\<open>\n  Finally, if $p$ contains no multiple roots, @{term \"sturm p\"}, i.e.\n  the canonical Sturm sequence for $p$, is a Sturm sequence\n  and can be used to determine the number of roots of $p$.\n\\<close>\nlemma sturm_seq_sturm[simp]:\n   assumes \"rsquarefree p\"\n   shows \"sturm_seq (sturm p) p\"\nproof\n  show \"sturm p \\<noteq> []\" by simp\n  show \"hd (sturm p) = p\" by simp\n  show \"length (sturm p) \\<ge> 2\" by simp\n  from assms show \"\\<And>x. \\<not>(poly p x = 0 \\<and> poly (sturm p ! 1) x = 0)\"\n      by (simp add: rsquarefree_roots)\nnext\n  fix x :: real and y :: real\n  have \"degree (last (sturm p)) = 0\" by simp\n  then obtain c where \"last (sturm p) = [:c:]\"\n      by (cases \"last (sturm p)\", simp split: if_split_asm)\n  thus \"\\<And>x y. sgn (poly (last (sturm p)) x) =\n            sgn (poly (last (sturm p)) y)\" by simp\nnext\n  from sturm_firsttwo_signs[OF assms]\n    show \"\\<And>x\\<^sub>0. poly p x\\<^sub>0 = 0 \\<Longrightarrow>\n         eventually (\\<lambda>x. sgn (poly (p*sturm p ! 1) x) =\n                         (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\" by simp\nnext\n  from sturm_signs[OF assms]\n    show \"\\<And>i x. \\<lbrakk>i < length (sturm p) - 2; poly (sturm p ! (i + 1)) x = 0\\<rbrakk>\n          \\<Longrightarrow> poly (sturm p ! (i + 2)) x * poly (sturm p ! i) x < 0\" by simp\nqed\n\n\nsubsubsection \\<open>Canonical squarefree Sturm sequence\\<close>\n\ntext \\<open>\n  The previous construction does not work for polynomials with multiple roots,\n  but we can simply ``divide away'' multiple roots by dividing $p$ by the\n  GCD of $p$ and $p'$. The resulting polynomial has the same roots as $p$,\n  but with multiplicity 1, allowing us to again use the canonical construction.\n\\<close>\ndefinition sturm_squarefree where\n  \"sturm_squarefree p = sturm (p div (gcd p (pderiv p)))\"\n\nlemma sturm_squarefree_not_Nil[simp]: \"sturm_squarefree p \\<noteq> []\"\n  by (simp add: sturm_squarefree_def)\n\n\nlemma sturm_seq_sturm_squarefree:\n  assumes [simp]: \"p \\<noteq> 0\"\n  defines [simp]: \"p' \\<equiv> p div gcd p (pderiv p)\"\n  shows \"sturm_seq (sturm_squarefree p) p'\"\nproof\n  have \"rsquarefree p'\"\n  proof (subst rsquarefree_roots, clarify)\n    fix x assume \"poly p' x = 0\" \"poly (pderiv p') x = 0\"\n    hence \"[:-x,1:] dvd gcd p' (pderiv p')\" by (simp add: poly_eq_0_iff_dvd)\n    also from poly_div_gcd_squarefree(1)[OF assms(1)]\n        have \"gcd p' (pderiv p') = 1\" by simp\n    finally show False by (simp add: poly_eq_0_iff_dvd[symmetric])\n  qed\n\n  from sturm_seq_sturm[OF \\<open>rsquarefree p'\\<close>]\n      interpret sturm_seq: sturm_seq \"sturm_squarefree p\" p'\n      by (simp add: sturm_squarefree_def)\n\n  show \"\\<And>x y. sgn (poly (last (sturm_squarefree p)) x) =\n      sgn (poly (last (sturm_squarefree p)) y)\" by simp\n  show \"sturm_squarefree p \\<noteq> []\" by simp\n  show \"hd (sturm_squarefree p) = p'\" by (simp add: sturm_squarefree_def)\n  show \"length (sturm_squarefree p) \\<ge> 2\" by simp\n\n  have [simp]: \"sturm_squarefree p ! 0 = p'\"\n               \"sturm_squarefree p ! Suc 0 = pderiv p'\"\n      by (simp_all add: sturm_squarefree_def)\n\n  from \\<open>rsquarefree p'\\<close>\n      show \"\\<And>x. \\<not> (poly p' x = 0 \\<and> poly (sturm_squarefree p ! 1) x = 0)\"\n      by (simp add: rsquarefree_roots)\n\n  from sturm_seq.signs show \"\\<And>i x. \\<lbrakk>i < length (sturm_squarefree p) - 2;\n                                 poly (sturm_squarefree p ! (i + 1)) x = 0\\<rbrakk>\n                                 \\<Longrightarrow> poly (sturm_squarefree p ! (i + 2)) x *\n                                         poly (sturm_squarefree p ! i) x < 0\" .\n\n  from sturm_seq.deriv show \"\\<And>x\\<^sub>0. poly p' x\\<^sub>0 = 0 \\<Longrightarrow>\n         eventually (\\<lambda>x. sgn (poly (p' * sturm_squarefree p ! 1) x) =\n                         (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\" .\nqed\n\n\nsubsubsection \\<open>Optimisation for multiple roots\\<close>\n\ntext \\<open>\n  We can also define the following non-canonical Sturm sequence that\n  is obtained by taking the canonical Sturm sequence of $p$\n  (possibly with multiple roots) and then dividing the entire\n  sequence by the GCD of $p$ and its derivative.\n\\<close>\ndefinition sturm_squarefree' where\n\"sturm_squarefree' p = (let d = gcd p (pderiv p)\n                         in map (\\<lambda>p'. p' div d) (sturm p))\"\n\ntext \\<open>\n  This construction also has all the desired properties:\n\\<close>\n\nlemma sturm_squarefree'_adjacent_root_propagate_left:\n  assumes \"p \\<noteq> 0\"\n  assumes \"i < length (sturm_squarefree' (p :: real poly)) - 1\"\n  assumes \"poly (sturm_squarefree' p ! i) x = 0\"\n      and \"poly (sturm_squarefree' p ! (i + 1)) x = 0\"\n  shows \"\\<forall>j\\<le>i+1. poly (sturm_squarefree' p ! j) x = 0\"\nproof (intro sturm_adjacent_root_aux[OF assms(2,3,4)], goal_cases)\n  case prems: (1 i x)\n    define q where \"q = sturm p ! i\"\n    define r where \"r = sturm p ! (Suc i)\"\n    define s where \"s = sturm p ! (Suc (Suc i))\"\n    define d where \"d = gcd p (pderiv p)\"\n    define q' r' s' where \"q' = q div d\" and \"r' = r div d\" and \"s' = s div d\"\n    from \\<open>p \\<noteq> 0\\<close> have \"d \\<noteq> 0\" unfolding d_def by simp\n    from prems(1) have i_in_range: \"i < length (sturm p) - 2\"\n        unfolding sturm_squarefree'_def Let_def by simp\n    have [simp]: \"d dvd q\" \"d dvd r\" \"d dvd s\" unfolding q_def r_def s_def d_def\n        using i_in_range by (auto intro: sturm_gcd)\n    hence qrs_simps: \"q = q' * d\" \"r = r' * d\" \"s = s' * d\"\n        unfolding q'_def r'_def s'_def by (simp_all)\n    with prems(2) i_in_range have r'_0: \"poly r' x = 0\"\n        unfolding r'_def r_def d_def sturm_squarefree'_def Let_def by simp\n    hence r_0: \"poly r x = 0\" by (simp add: \\<open>r = r' * d\\<close>)\n    from sturm_indices[OF i_in_range] have \"q = q div r * r - s\"\n        unfolding q_def r_def s_def by (simp add: div_mult_mod_eq)\n    hence \"q' = (q div r * r - s) div d\" by (simp add: q'_def)\n    also have \"... = (q div r * r) div d - s'\"\n      by (simp add: s'_def poly_div_diff_left)\n    also have \"... = q div r * r' - s'\"\n        using dvd_div_mult[OF \\<open>d dvd r\\<close>, of \"q div r\"]\n        by (simp add: algebra_simps r'_def)\n    also have \"q div r = q' div r'\" by (simp add: qrs_simps \\<open>d \\<noteq> 0\\<close>)\n    finally have \"poly q' x = poly (q' div r' * r' - s') x\" by simp\n    also from r'_0 have \"... = -poly s' x\" by simp\n    finally have \"poly s' x = -poly q' x\" by simp\n    thus ?case using i_in_range\n        unfolding q'_def s'_def q_def s_def sturm_squarefree'_def Let_def\n        by (simp add: d_def sgn_minus)\nqed\n\nlemma sturm_squarefree'_adjacent_roots:\n  assumes \"p \\<noteq> 0\"\n           \"i < length (sturm_squarefree' (p :: real poly)) - 1\"\n          \"poly (sturm_squarefree' p ! i) x = 0\"\n          \"poly (sturm_squarefree' p ! (i + 1)) x = 0\"\n  shows False\nproof-\n  define d where \"d = gcd p (pderiv p)\"\n  from sturm_squarefree'_adjacent_root_propagate_left[OF assms]\n      have \"poly (sturm_squarefree' p ! 0) x = 0\"\n           \"poly (sturm_squarefree' p ! 1) x = 0\" by auto\n  hence \"poly (p div d) x = 0\" \"poly (pderiv p div d) x = 0\"\n      using assms(2)\n      unfolding sturm_squarefree'_def Let_def d_def by auto\n  moreover from div_gcd_coprime assms(1)\n      have \"coprime (p div d) (pderiv p div d)\" unfolding d_def by auto\n  ultimately show False using coprime_imp_no_common_roots by auto\nqed\n\nlemma sturm_squarefree'_signs:\n  assumes \"p \\<noteq> 0\"\n  assumes i_in_range: \"i < length (sturm_squarefree' (p :: real poly)) - 2\"\n  assumes q_0: \"poly (sturm_squarefree' p ! (i+1)) x = 0\" (is \"poly ?q x = 0\")\n  shows \"poly (sturm_squarefree' p ! (i+2)) x *\n         poly (sturm_squarefree' p ! i) x < 0\"\n            (is \"poly ?r x * poly ?p x < 0\")\nproof-\n  define d where \"d = gcd p (pderiv p)\"\n  with \\<open>p \\<noteq> 0\\<close> have [simp]: \"d \\<noteq> 0\" by simp\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>]\n       coprime_imp_no_common_roots\n      have rsquarefree: \"rsquarefree (p div d)\"\n      by (auto simp: rsquarefree_roots d_def)\n\n  from i_in_range have i_in_range': \"i < length (sturm p) - 2\"\n      unfolding sturm_squarefree'_def by simp\n  hence \"d dvd (sturm p ! i)\" (is \"d dvd ?p'\")\n        \"d dvd (sturm p ! (Suc i))\" (is \"d dvd ?q'\")\n        \"d dvd (sturm p ! (Suc (Suc i)))\" (is \"d dvd ?r'\")\n      unfolding d_def by (auto intro: sturm_gcd)\n  hence pqr_simps: \"?p' = ?p * d\" \"?q' = ?q * d\" \"?r' = ?r * d\"\n    unfolding sturm_squarefree'_def Let_def d_def using i_in_range'\n    by (auto simp: dvd_div_mult_self)\n  with q_0 have q'_0: \"poly ?q' x = 0\" by simp\n  from sturm_indices[OF i_in_range']\n      have \"sturm p ! (i+2) = - (sturm p ! i mod sturm p ! (i+1))\" .\n  hence \"-?r' = ?p' mod ?q'\" by simp\n  with div_mult_mod_eq[of ?p' ?q'] have \"?p' div ?q' * ?q' - ?r' = ?p'\" by simp\n  hence \"d*(?p div ?q * ?q - ?r) = d* ?p\" by (simp add: pqr_simps algebra_simps)\n  hence \"?p div ?q * ?q - ?r = ?p\" by simp\n  hence \"poly (?p div ?q) x * poly ?q x - poly ?r x = poly ?p x\"\n      by (metis poly_diff poly_mult)\n  with q_0 have r_x: \"poly ?r x = -poly ?p x\" by simp\n\n  from sturm_squarefree'_adjacent_roots[OF \\<open>p \\<noteq> 0\\<close>] i_in_range q_0\n      have \"poly ?p x \\<noteq> 0\" by force\n  moreover have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> x * x > 0\" apply (case_tac \"x \\<ge> 0\")\n      by (simp_all add: mult_neg_neg)\n  ultimately show ?thesis using r_x by simp\nqed\n\n\ntext \\<open>\n  This approach indeed also yields a valid squarefree Sturm sequence\n  for the polynomial $p/\\text{gcd}(p,p')$.\n\\<close>\nlemma sturm_seq_sturm_squarefree':\n  assumes \"(p :: real poly) \\<noteq> 0\"\n  defines \"d \\<equiv> gcd p (pderiv p)\"\n  shows \"sturm_seq (sturm_squarefree' p) (p div d)\"\n      (is \"sturm_seq ?ps' ?p'\")\nproof\n  show \"?ps' \\<noteq> []\" \"hd ?ps' = ?p'\" \"2 \\<le> length ?ps'\"\n      by (simp_all add: sturm_squarefree'_def d_def hd_map)\n\n  from assms have \"d \\<noteq> 0\" by simp\n  {\n    have \"d dvd last (sturm p)\" unfolding d_def\n        by (rule sturm_gcd, simp)\n    hence *: \"last (sturm p) = last ?ps' * d\"\n        by (simp add: sturm_squarefree'_def last_map d_def dvd_div_mult_self)\n    then have \"last ?ps' dvd last (sturm p)\" by simp\n    with * dvd_imp_degree_le[OF this] have \"degree (last ?ps') \\<le> degree (last (sturm p))\"\n        using \\<open>d \\<noteq> 0\\<close> by (cases \"last ?ps' = 0\") auto\n    hence \"degree (last ?ps') = 0\" by simp\n    then obtain c where \"last ?ps' = [:c:]\"\n        by (cases \"last ?ps'\", simp split: if_split_asm)\n    thus \"\\<And>x y. sgn (poly (last ?ps') x) = sgn (poly (last ?ps') y)\" by simp\n  }\n\n  have squarefree: \"rsquarefree ?p'\" using \\<open>p \\<noteq> 0\\<close>\n    by (subst rsquarefree_roots, unfold d_def,\n        intro allI coprime_imp_no_common_roots poly_div_gcd_squarefree)\n  have [simp]: \"sturm_squarefree' p ! Suc 0 = pderiv p div d\"\n      unfolding sturm_squarefree'_def Let_def sturm_def d_def\n          by (subst sturm_aux.simps, simp)\n  have coprime: \"coprime ?p' (pderiv p div d)\"\n      unfolding d_def using div_gcd_coprime \\<open>p \\<noteq> 0\\<close> by blast\n  thus squarefree':\n      \"\\<And>x. \\<not> (poly (p div d) x = 0 \\<and> poly (sturm_squarefree' p ! 1) x = 0)\"\n      using coprime_imp_no_common_roots by simp\n\n  from sturm_squarefree'_signs[OF \\<open>p \\<noteq> 0\\<close>]\n      show \"\\<And>i x. \\<lbrakk>i < length ?ps' - 2; poly (?ps' ! (i + 1)) x = 0\\<rbrakk>\n                \\<Longrightarrow> poly (?ps' ! (i + 2)) x * poly (?ps' ! i) x < 0\" .\n\n  have [simp]: \"?p' \\<noteq> 0\" using squarefree by (simp add: rsquarefree_def)\n  have A: \"?p' = ?ps' ! 0\" \"pderiv p div d = ?ps' ! 1\"\n      by (simp_all add: sturm_squarefree'_def Let_def d_def sturm_def,\n          subst sturm_aux.simps, simp)\n  have [simp]: \"?ps' ! 0 \\<noteq> 0\" using squarefree\n      by (auto simp: A rsquarefree_def)\n\n  fix x\\<^sub>0 :: real\n  assume \"poly ?p' x\\<^sub>0 = 0\"\n  hence \"poly p x\\<^sub>0 = 0\" using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      unfolding d_def by simp\n  hence \"pderiv p \\<noteq> 0\" using \\<open>p \\<noteq> 0\\<close> by (auto dest: pderiv_iszero)\n  with \\<open>p \\<noteq> 0\\<close> \\<open>poly p x\\<^sub>0 = 0\\<close>\n      have A: \"eventually (\\<lambda>x. sgn (poly (p * pderiv p) x) =\n                              (if x\\<^sub>0 < x then 1 else -1)) (at x\\<^sub>0)\"\n      by (intro sturm_firsttwo_signs_aux, simp_all)\n  note ev = eventually_conj[OF A poly_neighbourhood_without_roots[OF \\<open>d \\<noteq> 0\\<close>]]\n\n  show \"eventually (\\<lambda>x. sgn (poly (p div d * sturm_squarefree' p ! 1) x) =\n                        (if x\\<^sub>0 < x then 1 else -1)) (at x\\<^sub>0)\"\n  proof (rule eventually_mono[OF ev], goal_cases)\n      have [intro]:\n          \"\\<And>a (b::real). b \\<noteq> 0 \\<Longrightarrow> a < 0 \\<Longrightarrow> a / (b * b) < 0\"\n          \"\\<And>a (b::real). b \\<noteq> 0 \\<Longrightarrow> a > 0 \\<Longrightarrow> a / (b * b) > 0\"\n          by ((case_tac \"b > 0\",\n              auto simp: mult_neg_neg field_simps) [])+\n    case prems: (1 x)\n      hence  [simp]: \"poly d x * poly d x > 0\"\n           by (cases \"poly d x > 0\", auto simp: mult_neg_neg)\n      from poly_div_gcd_squarefree_aux(2)[OF \\<open>pderiv p \\<noteq> 0\\<close>]\n          have \"poly (p div d) x = 0 \\<longleftrightarrow> poly p x = 0\" by (simp add: d_def)\n      moreover have \"d dvd p\" \"d dvd pderiv p\" unfolding d_def by simp_all\n      ultimately show ?case using prems\n          by (auto simp: sgn_real_def poly_div not_less[symmetric]\n                         zero_less_divide_iff split: if_split_asm)\n  qed\nqed\n\n\ntext \\<open>\n  This construction is obviously more expensive to compute than the one that \\emph{first}\n  divides $p$ by $\\text{gcd}(p,p')$ and \\emph{then} applies the canonical construction.\n  In this construction, we \\emph{first} compute the canonical Sturm sequence of $p$ as if\n  it had no multiple roots and \\emph{then} divide by the GCD.\n  However, it can be seen quite easily that unless $x$ is a multiple root of $p$,\n  i.\\,e. as long as $\\text{gcd}(P,P')\\neq 0$, the number of sign changes in a sequence of\n  polynomials does not actually change when we divide the polynomials by $\\text{gcd}(p,p')$.\\\\\n  There\\-fore we can use the ca\\-no\\-ni\\-cal Sturm se\\-quence even in the non-square\\-free\n  case as long as the borders of the interval we are interested in are not multiple roots\n  of the polynomial.\n\\<close>\n\nlemma sign_changes_mult_aux:\n  assumes \"d \\<noteq> (0::real)\"\n  shows \"length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map ((*) d \\<circ> f) xs))) =\n         length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map f xs)))\"\nproof-\n  from assms have inj: \"inj ((*) d)\" by (auto intro: injI)\n  from assms have [simp]: \"filter (\\<lambda>x. ((*) d \\<circ> f) x \\<noteq> 0) = filter (\\<lambda>x. f x \\<noteq> 0)\"\n                          \"filter ((\\<lambda>x. x \\<noteq> 0) \\<circ> f) = filter (\\<lambda>x. f x \\<noteq> 0)\"\n      by (simp_all add: o_def)\n  have \"filter (\\<lambda>x. x \\<noteq> 0) (map ((*) d \\<circ> f) xs) =\n        map ((*) d \\<circ> f) (filter (\\<lambda>x. ((*) d \\<circ> f) x \\<noteq> 0) xs)\"\n      by (simp add: filter_map o_def)\n  thus ?thesis using remdups_adj_map_injective[OF inj] assms\n      by (simp add: filter_map map_map[symmetric] del: map_map)\nqed\n\nlemma sturm_sturm_squarefree'_same_sign_changes:\n  fixes p :: \"real poly\"\n  defines \"ps \\<equiv> sturm p\" and \"ps' \\<equiv> sturm_squarefree' p\"\n  shows \"poly p x \\<noteq> 0 \\<or> poly (pderiv p) x \\<noteq> 0 \\<Longrightarrow>\n             sign_changes ps' x = sign_changes ps x\"\n        \"p \\<noteq> 0 \\<Longrightarrow> sign_changes_inf ps' = sign_changes_inf ps\"\n        \"p \\<noteq> 0 \\<Longrightarrow> sign_changes_neg_inf ps' = sign_changes_neg_inf ps\"\nproof-\n  define d where \"d = gcd p (pderiv p)\"\n  define p' where \"p' = p div d\"\n  define s' where \"s' = poly_inf d\"\n  define s'' where \"s'' = poly_neg_inf d\"\n\n  {\n    fix x :: real and q :: \"real poly\"\n    assume \"q \\<in> set ps\"\n    hence \"d dvd q\" unfolding d_def ps_def using sturm_gcd by simp\n    hence q_prod: \"q = (q div d) * d\" unfolding p'_def d_def\n        by (simp add: algebra_simps dvd_mult_div_cancel)\n\n    have \"poly q x = poly d x * poly (q div d) x\"  by (subst q_prod, simp)\n    hence s1: \"sgn (poly q x) = sgn (poly d x) * sgn (poly (q div d) x)\"\n        by (subst q_prod, simp add: sgn_mult)\n    from poly_inf_mult have s2: \"poly_inf q = s' * poly_inf (q div d)\"\n        unfolding s'_def by (subst q_prod, simp)\n    from poly_inf_mult have s3: \"poly_neg_inf q = s'' * poly_neg_inf (q div d)\"\n        unfolding s''_def by (subst q_prod, simp)\n    note s1 s2 s3\n  }\n  note signs = this\n\n  {\n    fix f :: \"real poly \\<Rightarrow> real\" and s :: real\n    assume f: \"\\<And>q. q \\<in> set ps \\<Longrightarrow> f q = s * f (q div d)\" and s: \"s \\<noteq> 0\"\n    hence \"inverse s \\<noteq> 0\" by simp\n    {fix q assume \"q \\<in> set ps\"\n     hence \"f (q div d) = inverse s * f q\"\n         by (subst f[of q], simp_all add: s)\n    } note f' = this\n    have \"length (remdups_adj [x\\<leftarrow>map f (map (\\<lambda>q. q div d) ps). x \\<noteq> 0]) - 1 =\n           length (remdups_adj [x\\<leftarrow>map (\\<lambda>q. f (q div d)) ps . x \\<noteq> 0]) - 1\"\n        by (simp only: sign_changes_def o_def map_map)\n    also have \"map (\\<lambda>q. q div d) ps = ps'\"\n        by (simp add: ps_def ps'_def sturm_squarefree'_def Let_def d_def)\n    also from f' have \"map (\\<lambda>q. f (q div d)) ps =\n                      map (\\<lambda>x. ((*)(inverse s) \\<circ> f) x) ps\" by (simp add: o_def)\n    also note sign_changes_mult_aux[OF \\<open>inverse s \\<noteq> 0\\<close>, of f ps]\n    finally have\n        \"length (remdups_adj [x\\<leftarrow>map f ps' . x \\<noteq> 0]) - 1 =\n         length (remdups_adj [x\\<leftarrow>map f ps . x \\<noteq> 0]) - 1\" by simp\n  }\n  note length_remdups_adj = this\n\n  {\n    fix x assume A: \"poly p x \\<noteq> 0 \\<or> poly (pderiv p) x \\<noteq> 0\"\n    have \"d dvd p\" \"d dvd pderiv p\" unfolding d_def by simp_all\n    with A have \"sgn (poly d x) \\<noteq> 0\"\n        by (auto simp add: sgn_zero_iff elim: dvdE)\n    thus \"sign_changes ps' x = sign_changes ps x\" using signs(1)\n        unfolding sign_changes_def\n        by (intro length_remdups_adj[of \"\\<lambda>q. sgn (poly q x)\"], simp_all)\n  }\n\n  assume \"p \\<noteq> 0\"\n  hence \"d \\<noteq> 0\" unfolding d_def by simp\n  hence \"s' \\<noteq> 0\" \"s'' \\<noteq> 0\" unfolding s'_def s''_def by simp_all\n  from length_remdups_adj[of poly_inf s', OF signs(2) \\<open>s' \\<noteq> 0\\<close>]\n      show \"sign_changes_inf ps' = sign_changes_inf ps\"\n      unfolding sign_changes_inf_def .\n  from length_remdups_adj[of poly_neg_inf s'', OF signs(3) \\<open>s'' \\<noteq> 0\\<close>]\n      show \"sign_changes_neg_inf ps' = sign_changes_neg_inf ps\"\n      unfolding sign_changes_neg_inf_def .\nqed\n\n\n\nsubsection \\<open>Root-counting functions\\<close>\n\ntext \\<open>\n  With all these results, we can now define functions that count roots\n  in bounded and unbounded intervals:\n\\<close>\n\ndefinition count_roots_between where\n\"count_roots_between p a b = (if a \\<le> b \\<and> p \\<noteq> 0 then\n  (let ps = sturm_squarefree p\n    in sign_changes ps a - sign_changes ps b) else 0)\"\n\ndefinition count_roots where\n\"count_roots p = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes_neg_inf ps - sign_changes_inf ps))\"\n\ndefinition count_roots_above where\n\"count_roots_above p a = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes ps a - sign_changes_inf ps))\"\n\ndefinition count_roots_below where\n\"count_roots_below p a = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes_neg_inf ps - sign_changes ps a))\"\n\n\nlemma count_roots_between_correct:\n  \"count_roots_between p a b = card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\"\nproof (cases \"p \\<noteq> 0 \\<and> a \\<le> b\")\n  case False\n    note False' = this\n    hence \"card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0} = 0\"\n    proof (cases \"a < b\")\n      case True\n        with False have [simp]: \"p = 0\" by simp\n        have subset: \"{a<..<b} \\<subseteq> {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by auto\n        from infinite_Ioo[OF True] have \"\\<not>finite {a<..<b}\" .\n        hence \"\\<not>finite {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\"\n            using finite_subset[OF subset] by blast\n        thus ?thesis by simp\n    next\n      case False\n        with False' show ?thesis by (auto simp: not_less card_eq_0_iff)\n    qed\n    thus ?thesis unfolding count_roots_between_def Let_def using False by auto\nnext\n  case True\n  hence \"p \\<noteq> 0\" \"a \\<le> b\" by simp_all\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from poly_roots_finite[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"finite {x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0}\" by fast\n  have \"count_roots_between p a b = card {x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0}\"\n      unfolding count_roots_between_def Let_def\n      using True count_roots_between[OF \\<open>p' \\<noteq> 0\\<close> \\<open>a \\<le> b\\<close>] by simp\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0} =\n            {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots p = card {x. poly p x = 0}\" (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with finite_subset[of \"{0<..<1}\" ?S]\n    have \"\\<not>finite {x. poly p x = 0}\" by (auto simp: infinite_Ioo)\n    thus ?thesis by (simp add: count_roots_def True)\nnext\n  case False\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"count_roots p = card {x. poly p' x = 0}\"\n      unfolding count_roots_def Let_def by (simp add: \\<open>p \\<noteq> 0\\<close>)\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. poly p' x = 0} = {x. poly p x = 0}\" unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_above_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots_above p a = card {x. x > a \\<and> poly p x = 0}\"\n         (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n  with finite_subset[of \"{a<..<a+1}\" ?S]\n    have \"\\<not>finite {x. x > a \\<and> poly p x = 0}\" by (auto simp: infinite_Ioo subset_eq)\n  thus ?thesis by (simp add: count_roots_above_def True)\nnext\n  case False\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots_above[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"count_roots_above p a = card {x. x > a \\<and> poly p' x = 0}\"\n      unfolding count_roots_above_def Let_def by (simp add: \\<open>p \\<noteq> 0\\<close>)\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. x > a \\<and> poly p' x = 0} = {x. x > a \\<and> poly p x = 0}\"\n      unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_below_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots_below p a = card {x. x \\<le> a \\<and> poly p x = 0}\"\n         (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with finite_subset[of \"{a - 1<..<a}\" ?S]\n        have \"\\<not>finite {x. x \\<le> a \\<and> poly p x = 0}\" by (auto simp: infinite_Ioo subset_eq)\n    thus ?thesis by (simp add: count_roots_below_def True)\nnext\n  case False\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots_below[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"count_roots_below p a = card {x. x \\<le> a \\<and> poly p' x = 0}\"\n      unfolding count_roots_below_def Let_def by (simp add: \\<open>p \\<noteq> 0\\<close>)\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. x \\<le> a \\<and> poly p' x = 0} = {x. x \\<le> a \\<and> poly p x = 0}\"\n      unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The optimisation explained above can be used to prove more efficient code equations that\n  use the more efficient construction in the case that the interval borders are not\n  multiple roots:\n\\<close>\n\nlemma count_roots_between[code]:\n  \"count_roots_between p a b =\n     (let q = pderiv p\n       in if a > b \\<or> p = 0 then 0\n       else if (poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0) \\<and> (poly p b \\<noteq> 0 \\<or> poly q b \\<noteq> 0)\n            then (let ps = sturm p\n                   in sign_changes ps a - sign_changes ps b)\n            else (let ps = sturm_squarefree p\n                   in sign_changes ps a - sign_changes ps b))\"\nproof (cases \"a > b \\<or> p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_between_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"a \\<le> b\" \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0) \\<and>\n                  (poly p b \\<noteq> 0 \\<or> poly (pderiv p) b \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1\n          by (auto simp add: Let_def count_roots_between_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" and\n            B: \"poly p b \\<noteq> 0 \\<or> poly (pderiv p) b \\<noteq> 0\" by auto\n      define d where \"d = gcd p (pderiv p)\"\n      from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n          using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_between_correct\n      also have \"{x. a < x \\<and> x \\<le> b \\<and> poly p x = 0} =\n                 {x. a < x \\<and> x \\<le> b \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n      also note count_roots_between[OF \\<open>p div d \\<noteq> 0\\<close> \\<open>a \\<le> b\\<close>, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF B]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\n\nlemma count_roots_code[code]:\n  \"count_roots (p::real poly) =\n    (if p = 0 then 0\n     else let ps = sturm p\n           in sign_changes_neg_inf ps - sign_changes_inf ps)\"\nproof (cases \"p = 0\", simp add: count_roots_def)\n  case False\n    define d where \"d = gcd p (pderiv p)\"\n    from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n        using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n    from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n        interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n        unfolding sturm_squarefree'_def Let_def d_def .\n\n    note count_roots_correct\n    also have \"{x. poly p x = 0} = {x. poly (p div d) x = 0}\"\n        unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n    also note count_roots[OF \\<open>p div d \\<noteq> 0\\<close>, symmetric]\n    also note sturm_sturm_squarefree'_same_sign_changes(2)[OF \\<open>p \\<noteq> 0\\<close>]\n    also note sturm_sturm_squarefree'_same_sign_changes(3)[OF \\<open>p \\<noteq> 0\\<close>]\n    finally show ?thesis using False unfolding Let_def by simp\nqed\n\n\nlemma count_roots_above_code[code]:\n  \"count_roots_above p a =\n     (let q = pderiv p\n       in if p = 0 then 0\n       else if poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0\n            then (let ps = sturm p\n                   in sign_changes ps a - sign_changes_inf ps)\n            else (let ps = sturm_squarefree p\n                   in sign_changes ps a - sign_changes_inf ps))\"\nproof (cases \"p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_above_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1\n          by (auto simp add: Let_def count_roots_above_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" by simp\n      define d where \"d = gcd p (pderiv p)\"\n      from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n          using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_above_correct\n      also have \"{x. a < x \\<and> poly p x = 0} =\n                 {x. a < x \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n      also note count_roots_above[OF \\<open>p div d \\<noteq> 0\\<close>, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\nlemma count_roots_below_code[code]:\n  \"count_roots_below p a =\n     (let q = pderiv p\n       in if p = 0 then 0\n       else if poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0\n            then (let ps = sturm p\n                   in sign_changes_neg_inf ps - sign_changes ps a)\n            else (let ps = sturm_squarefree p\n                   in sign_changes_neg_inf ps - sign_changes ps a))\"\nproof (cases \"p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_below_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1\n          by (auto simp add: Let_def count_roots_below_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" by simp\n      define d where \"d = gcd p (pderiv p)\"\n      from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n          using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_below_correct\n      also have \"{x. x \\<le> a \\<and> poly p x = 0} =\n                 {x. x \\<le> a \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n      also note count_roots_below[OF \\<open>p div d \\<noteq> 0\\<close>, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(3)[OF \\<open>p \\<noteq> 0\\<close>]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Sturm_Sequences/Sturm_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.782725435840787}}
{"text": "section \\<open>Challenge 1.A\\<close>\ntheory Challenge1A\nimports Main\nbegin\n\ntext \\<open>Problem definition:\n\\<^url>\\<open>https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Verify%20This/Challenges%202019/ghc_sort.pdf\\<close>\\<close>\n\n  subsection \\<open>Implementation\\<close>\n  text \\<open>We phrase the algorithm as a functional program. \n    Instead of a list of indexes for segment boundaries,\n    we return a list of lists, containing the segments.\\<close>\n\n  text \\<open>We start with auxiliary functions to take the longest\n    increasing/decreasing sequence from the start of the list\n  \\<close>  \n  fun take_incr :: \"int list \\<Rightarrow> _\" where\n    \"take_incr [] = []\"\n  | \"take_incr [x] = [x]\"\n  | \"take_incr (x#y#xs) = (if x<y then x#take_incr (y#xs) else [x])\"  \n\n  fun take_decr :: \"int list \\<Rightarrow> _\" where\n    \"take_decr [] = []\"\n  | \"take_decr [x] = [x]\"\n  | \"take_decr (x#y#xs) = (if x\\<ge>y then x#take_decr (y#xs) else [x])\"  \n  \n  fun take where\n    \"take [] = []\"\n  | \"take [x] = [x]\"\n  | \"take (x#y#xs) = (if x<y then take_incr (x#y#xs) else take_decr (x#y#xs))\"  \n\n  \n  definition \"take2 xs \\<equiv> let l=take xs in (l,drop (length l) xs)\"\n    \\<comment> \\<open>Splits of a longest increasing/decreasing sequence from the list\\<close>\n\n  \n  text \\<open>The main algorithm then iterates until the whole input list is split\\<close>\n  function cuts where\n    \"cuts xs = (if xs=[] then [] else let (c,xs) = take2 xs in c#cuts xs)\"    \n    by pat_completeness auto\n\n  subsection \\<open>Termination\\<close>  \n  text \\<open>First, we show termination. This will give us induction and proper unfolding lemmas.\\<close>\n\n  lemma take_non_empty:\n    \"take xs \\<noteq> []\" if \"xs \\<noteq> []\"\n    using that\n    apply (cases xs)\n     apply clarsimp\n    subgoal for x ys\n      apply (cases ys)\n       apply auto\n      done\n    done\n\n  termination\n    apply (relation \"measure length\")\n     apply (auto simp: take2_def Let_def)\n    using take_non_empty\n    apply auto\n    done\n    \n  declare cuts.simps[simp del]  \n    \n  subsection \\<open>Correctness\\<close>\n  \n\n  subsubsection \\<open>Property 1: The Exact Sequence is Covered\\<close>\n  lemma tdconc: \"\\<exists>ys. xs = take_decr xs @ ys\"\n    apply (induction xs rule: take_decr.induct)\n    apply auto\n    done\n\n  lemma ticonc: \"\\<exists>ys. xs = take_incr xs @ ys\"\n    apply (induction xs rule: take_incr.induct)\n    apply auto\n    done\n\n  lemma take_conc: \"\\<exists>ys. xs = take xs@ys\"  \n    using tdconc ticonc \n    apply (cases xs rule: take.cases)\n    by auto \n  \n  theorem concat_cuts: \"concat (cuts xs) = xs\"\n    apply (induction xs rule: cuts.induct)\n    apply (subst cuts.simps)\n    apply (auto simp: take2_def Let_def)\n    by (metis append_eq_conv_conj take_conc)  \n  \n        \n        \n  subsubsection \\<open>Property 2: Monotonicity\\<close>\n  text \\<open>We define constants to specify increasing/decreasing sequences.\\<close>\n  fun incr where\n    \"incr [] \\<longleftrightarrow> True\"\n  | \"incr [_] \\<longleftrightarrow> True\"\n  | \"incr (x#y#xs) \\<longleftrightarrow> x<y \\<and> incr (y#xs)\"  \n  \n  fun decr where\n    \"decr [] \\<longleftrightarrow> True\"\n  | \"decr [_] \\<longleftrightarrow> True\"\n  | \"decr (x#y#xs) \\<longleftrightarrow> x\\<ge>y \\<and> decr (y#xs)\"  \n  \n  lemma tki: \"incr (take_incr xs)\"\n    apply (induction xs rule: take_incr.induct)\n    apply auto\n    apply (case_tac xs)\n    apply auto\n    done\n    \n  lemma tkd: \"decr (take_decr xs)\"\n    apply (induction xs rule: take_decr.induct)\n    apply auto\n    apply (case_tac xs)\n    apply auto\n    done\n  \n  lemma icod: \"incr (take xs) \\<or> decr (take xs)\"\n    apply (cases xs rule: take.cases) \n    apply (auto simp: tki tkd simp del: take_incr.simps take_decr.simps)\n    done   \n        \n  theorem cuts_incr_decr: \"\\<forall>c\\<in>set (cuts xs). incr c \\<or> decr c\"  \n    apply (induction xs rule: cuts.induct)\n    apply (subst cuts.simps)\n    apply (auto simp: take2_def Let_def)\n    using icod by blast\n    \n      \n  subsubsection \\<open>Property 3: Maximality\\<close>      \n  text \\<open>Specification of a cut that consists of maximal segments:\n    The segements are non-empty, and for every two neighbouring segments,\n    the first value of the last segment cannot be used to continue the first segment:\n  \\<close>\n  fun maxi where\n     \"maxi [] \\<longleftrightarrow> True\"\n   | \"maxi [c] \\<longleftrightarrow> c\\<noteq>[]\"\n   | \"maxi (c1#c2#cs) \\<longleftrightarrow> (c1\\<noteq>[] \\<and> c2\\<noteq>[] \\<and> maxi (c2#cs) \\<and> ( \n        incr c1 \\<and> \\<not>(last c1 < hd c2) \n      \\<or> decr c1 \\<and> \\<not>(last c1 \\<ge> hd c2)        \n        ))\"  \n\n  text \\<open>Obviously, our specification implies that there are no \n    empty segments\\<close>    \n  lemma maxi_imp_non_empty: \"maxi xs \\<Longrightarrow> []\\<notin>set xs\"  \n    by (induction xs rule: maxi.induct) auto\n        \n          \n  lemma tdconc': \"xs\\<noteq>[] \\<Longrightarrow> \n    \\<exists>ys. xs = take_decr xs @ ys \\<and> (ys\\<noteq>[] \n      \\<longrightarrow> \\<not>(last (take_decr xs) \\<ge> hd ys))\"\n    apply (induction xs rule: take_decr.induct)\n    apply auto\n    apply (case_tac xs) apply (auto split: if_splits)\n    done\n    \n  lemma ticonc': \"xs\\<noteq>[] \\<Longrightarrow> \\<exists>ys. xs = take_incr xs @ ys \\<and> (ys\\<noteq>[] \\<longrightarrow> \\<not>(last (take_incr xs) < hd ys))\"\n    apply (induction xs rule: take_incr.induct)\n    apply auto\n    apply (case_tac xs) apply (auto split: if_splits)\n    done\n\n  lemma take_conc': \"xs\\<noteq>[] \\<Longrightarrow> \\<exists>ys. xs = take xs@ys \\<and> (ys\\<noteq>[] \\<longrightarrow> (\n    take xs=take_incr xs \\<and> \\<not>(last (take_incr xs) < hd ys)\n  \\<or> take xs=take_decr xs \\<and> \\<not>(last (take_decr xs) \\<ge> hd ys)  \n  ))\"  \n    using tdconc' ticonc' \n    apply (cases xs rule: take.cases)\n    by auto \n    \n    \n  lemma take_decr_non_empty:\n    \"take_decr xs \\<noteq> []\" if \"xs \\<noteq> []\"\n    using that\n    apply (cases xs)\n     apply auto\n    subgoal for x ys\n      apply (cases ys)\n       apply (auto split: if_split_asm)\n      done\n    done\n  \n  lemma take_incr_non_empty:\n    \"take_incr xs \\<noteq> []\" if \"xs \\<noteq> []\"\n    using that\n    apply (cases xs)\n     apply auto\n    subgoal for x ys\n      apply (cases ys)\n       apply (auto split: if_split_asm)\n      done\n    done\n    \n  lemma take_conc'': \"xs\\<noteq>[] \\<Longrightarrow> \\<exists>ys. xs = take xs@ys \\<and> (ys\\<noteq>[] \\<longrightarrow> (\n    incr (take xs) \\<and> \\<not>(last (take xs) < hd ys)\n  \\<or> decr (take xs) \\<and> \\<not>(last (take xs) \\<ge> hd ys)  \n  ))\"  \n    using tdconc' ticonc' tki tkd \n    apply (cases xs rule: take.cases)\n    apply auto\n    apply (auto simp add: take_incr_non_empty) \n    apply (simp add: take_decr_non_empty)\n    apply (metis list.distinct(1) take_incr.simps(3))\n    by (smt list.simps(3) take_decr.simps(3))\n    \n    \n  \n  \n\n  lemma inv_cuts: \"cuts xs = c#cs \\<Longrightarrow> \\<exists>ys. c=take xs \\<and> xs=c@ys \\<and> cs = cuts ys\"\n    apply (subst (asm) cuts.simps)\n    apply (cases xs rule: cuts.cases)\n    apply (auto split: if_splits simp: take2_def Let_def)\n    by (metis append_eq_conv_conj take_conc)\n    \n  theorem maximal_cuts: \"maxi (cuts xs)\" \n    apply (induction \"cuts xs\" arbitrary: xs rule: maxi.induct)\n    subgoal by auto\n    subgoal for c xs\n      apply (drule sym; simp)\n      apply (subst (asm) cuts.simps)\n      apply (auto split: if_splits prod.splits simp: take2_def Let_def take_non_empty)\n      done\n    subgoal for c1 c2 cs xs\n      apply (drule sym)\n      apply simp\n      apply (drule inv_cuts; clarsimp)\n      apply auto\n      subgoal by (metis cuts.simps list.distinct(1) take_non_empty) \n      subgoal by (metis append.left_neutral inv_cuts not_Cons_self) \n      subgoal using icod by blast \n      subgoal by (metis\n            Nil_is_append_conv cuts.simps hd_append2 inv_cuts list.distinct(1)\n            same_append_eq take_conc'' take_non_empty) \n      subgoal by (metis\n            append_is_Nil_conv cuts.simps hd_append2 inv_cuts list.distinct(1)\n            same_append_eq take_conc'' take_non_empty) \n      done\n    done\n\n  subsubsection \\<open>Equivalent Formulation Over Indexes\\<close>\n  text \\<open>After the competition, we got the comment that a specification of \n    monotonic sequences via indexes might be more readable.\n  \n    We show that our functional specification is equivalent to a \n    specification over indexes.\\<close>\n    \n  fun ii_induction where\n    \"ii_induction [] = ()\"\n  | \"ii_induction [_] = ()\"\n  | \"ii_induction (_#y#xs) = ii_induction (y#xs)\"      \n\n  locale cnvSpec =\n    fixes fP P\n    assumes [simp]: \"fP [] \\<longleftrightarrow> True\"\n    assumes [simp]: \"fP [x] \\<longleftrightarrow> True\"\n    assumes [simp]: \"fP (a#b#xs) \\<longleftrightarrow> P a b \\<and> fP (b#xs)\"\n  begin\n\n    lemma idx_spec: \"fP xs \\<longleftrightarrow> (\\<forall>i<length xs - 1. P (xs!i) (xs!Suc i))\"\n      apply (induction xs rule: ii_induction.induct)\n      using less_Suc_eq_0_disj\n      by auto\n  \n  end\n\n  locale cnvSpec' =\n    fixes fP P P'\n    assumes [simp]: \"fP [] \\<longleftrightarrow> True\"\n    assumes [simp]: \"fP [x] \\<longleftrightarrow> P' x\"\n    assumes [simp]: \"fP (a#b#xs) \\<longleftrightarrow> P' a \\<and> P' b \\<and> P a b \\<and> fP (b#xs)\"\n  begin\n\n    lemma idx_spec: \"fP xs \\<longleftrightarrow> (\\<forall>i<length xs. P' (xs!i)) \\<and> (\\<forall>i<length xs - 1. P (xs!i) (xs!Suc i))\"\n      apply (induction xs rule: ii_induction.induct)\n      apply auto []\n      apply auto []\n      apply clarsimp\n      by (smt less_Suc_eq_0_disj nth_Cons_0 nth_Cons_Suc)\n  \n  end\n    \n  interpretation INCR: cnvSpec incr \"(<)\"\n    apply unfold_locales by auto\n  \n  interpretation DECR: cnvSpec decr \"(\\<ge>)\"\n    apply unfold_locales by auto\n  \n  interpretation MAXI: cnvSpec' maxi \"\\<lambda>c1 c2. ( ( \n        incr c1 \\<and> \\<not>(last c1 < hd c2) \n      \\<or> decr c1 \\<and> \\<not>(last c1 \\<ge> hd c2)        \n        ))\"\n      \"\\<lambda>x. x \\<noteq> []\"  \n    apply unfold_locales by auto\n  \n  lemma incr_by_idx: \"incr xs = (\\<forall>i<length xs - 1. xs ! i < xs ! Suc i)\" \n    by (rule INCR.idx_spec)\n    \n  lemma decr_by_idx: \"decr xs = (\\<forall>i<length xs - 1. xs ! i \\<ge> xs ! Suc i)\" \n    by (rule DECR.idx_spec)\n    \n  lemma maxi_by_idx: \"maxi xs \\<longleftrightarrow>\n    (\\<forall>i<length xs. xs ! i \\<noteq> []) \\<and>\n    (\\<forall>i<length xs - 1. \n         incr (xs ! i) \\<and> \\<not> last (xs ! i) < hd (xs ! Suc i) \n       \\<or> decr (xs ! i) \\<and> \\<not> hd (xs ! Suc i) \\<le> last (xs ! i)\n    )\"\n    by (rule MAXI.idx_spec)\n\n  theorem all_correct:  \n    \"concat (cuts xs) = xs\"\n    \"\\<forall>c\\<in>set (cuts xs). incr c \\<or> decr c\"\n    \"maxi (cuts xs)\"\n    \"[] \\<notin> set (cuts xs)\"\n    using cuts_incr_decr concat_cuts maximal_cuts \n          maxi_imp_non_empty[OF maximal_cuts]\n    by auto\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/VerifyThis2019/Challenge1A.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.9046505376715775, "lm_q1q2_score": 0.7827254346536422}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Sorting\"\n\ntheory Sorting\nimports\n  Complex_Main\n  \"HOL-Library.Multiset\"\nbegin\n\nhide_const List.insort\n\ndeclare Let_def [simp]\n\n\nsubsection \"Insertion Sort\"\n\nfun insort1 :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"insort1 x [] = [x]\" |\n\"insort1 x (y#ys) =\n  (if x \\<le> y then x#y#ys else y#(insort1 x ys))\"\n\nfun insort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"insort [] = []\" |\n\"insort (x#xs) = insort1 x (insort xs)\"\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_insort1: \"mset (insort1 x xs) = {#x#} + mset xs\"\napply(induction xs)\napply auto\ndone\n\nlemma mset_insort: \"mset (insort xs) = mset xs\"\napply(induction xs)\napply simp\napply (simp add: mset_insort1)\ndone\n\nlemma set_insort1: \"set (insort1 x xs) = {x} \\<union> set xs\"\nby(simp add: mset_insort1 flip: set_mset_mset)\n\nlemma sorted_insort1: \"sorted (insort1 a xs) = sorted xs\"\napply(induction xs)\napply(auto simp add: set_insort1)\ndone\n\nlemma sorted_insort: \"sorted (insort xs)\"\napply(induction xs)\napply(auto simp: sorted_insort1)\ndone\n\n\nsubsubsection \"Time Complexity\"\n\ntext \\<open>We count the number of function calls.\\<close>\n\ntext\\<open>\n\\<open>insort1 x [] = [x]\\<close>\n\\<open>insort1 x (y#ys) =\n  (if x \\<le> y then x#y#ys else y#(insort1 x ys))\\<close>\n\\<close>\nfun T_insort1 :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"T_insort1 x [] = 1\" |\n\"T_insort1 x (y#ys) =\n  (if x \\<le> y then 0 else T_insort1 x ys) + 1\"\n\ntext\\<open>\n\\<open>insort [] = []\\<close>\n\\<open>insort (x#xs) = insort1 x (insort xs)\\<close>\n\\<close>\nfun T_insort :: \"'a::linorder list \\<Rightarrow> nat\" where\n\"T_insort [] = 1\" |\n\"T_insort (x#xs) = T_insort xs + T_insort1 x (insort xs) + 1\"\n\n\nlemma T_insort1_length: \"T_insort1 x xs \\<le> length xs + 1\"\napply(induction xs)\napply auto\ndone\n\nlemma length_insort1: \"length (insort1 x xs) = length xs + 1\"\napply(induction xs)\napply auto\ndone\n\nlemma length_insort: \"length (insort xs) = length xs\"\napply(induction xs)\napply (auto simp: length_insort1)\ndone\n\nlemma T_insort_length: \"T_insort xs \\<le> (length xs + 1) ^ 2\"\nproof(induction xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  have \"T_insort (x#xs) = T_insort xs + T_insort1 x (insort xs) + 1\" by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + T_insort1 x (insort xs) + 1\"\n    using Cons.IH by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + length xs + 1 + 1\"\n    using T_insort1_length[of x \"insort xs\"] by (simp add: length_insort)\n  also have \"\\<dots> \\<le> (length(x#xs) + 1) ^ 2\"\n    by (simp add: power2_eq_square)\n  finally show ?case .\nqed\n\n\nsubsection \"Merge Sort\"\n\nfun merge :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"merge [] ys = ys\" |\n\"merge xs [] = xs\" |\n\"merge (x#xs) (y#ys) = (if x \\<le> y then x # merge xs (y#ys) else y # merge (x#xs) ys)\"\n\nfun msort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"msort xs = (let n = length xs in\n  if n \\<le> 1 then xs\n  else merge (msort (take (n div 2) xs)) (msort (drop (n div 2) xs)))\"\n\ndeclare msort.simps [simp del]\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_merge: \"mset(merge xs ys) = mset xs + mset ys\"\nby(induction xs ys rule: merge.induct) auto\n\nlemma mset_msort: \"mset (msort xs) = mset xs\"\nproof(induction xs rule: msort.induct)\n  case (1 xs)\n  let ?n = \"length xs\"\n  let ?ys = \"take (?n div 2) xs\"\n  let ?zs = \"drop (?n div 2) xs\"\n  show ?case\n  proof cases\n    assume \"?n \\<le> 1\"\n    thus ?thesis by(simp add: msort.simps[of xs])\n  next\n    assume \"\\<not> ?n \\<le> 1\"\n    hence \"mset (msort xs) = mset (msort ?ys) + mset (msort ?zs)\"\n      by(simp add: msort.simps[of xs] mset_merge)\n    also have \"\\<dots> = mset ?ys + mset ?zs\"\n      using \\<open>\\<not> ?n \\<le> 1\\<close> by(simp add: \"1.IH\")\n    also have \"\\<dots> = mset (?ys @ ?zs)\" by (simp del: append_take_drop_id)\n    also have \"\\<dots> = mset xs\" by simp\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>Via the previous lemma or directly:\\<close>\n\nlemma set_merge: \"set(merge xs ys) = set xs \\<union> set ys\"\nby (metis mset_merge set_mset_mset set_mset_union)\n\nlemma \"set(merge xs ys) = set xs \\<union> set ys\"\nby(induction xs ys rule: merge.induct) (auto)\n\nlemma sorted_merge: \"sorted (merge xs ys) \\<longleftrightarrow> (sorted xs \\<and> sorted ys)\"\nby(induction xs ys rule: merge.induct) (auto simp: set_merge)\n\nlemma sorted_msort: \"sorted (msort xs)\"\nproof(induction xs rule: msort.induct)\n  case (1 xs)\n  let ?n = \"length xs\"\n  show ?case\n  proof cases\n    assume \"?n \\<le> 1\"\n    thus ?thesis by(simp add: msort.simps[of xs] sorted01)\n  next\n    assume \"\\<not> ?n \\<le> 1\"\n    thus ?thesis using \"1.IH\"\n      by(simp add: sorted_merge msort.simps[of xs])\n  qed\nqed\n\n\nsubsubsection \"Time Complexity\"\n\ntext \\<open>We only count the number of comparisons between list elements.\\<close>\n\nfun C_merge :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"C_merge [] ys = 0\" |\n\"C_merge xs [] = 0\" |\n\"C_merge (x#xs) (y#ys) = 1 + (if x \\<le> y then C_merge xs (y#ys) else C_merge (x#xs) ys)\"\n\nlemma C_merge_ub: \"C_merge xs ys \\<le> length xs + length ys\"\nby (induction xs ys rule: C_merge.induct) auto\n\nfun C_msort :: \"'a::linorder list \\<Rightarrow> nat\" where\n\"C_msort xs =\n  (let n = length xs;\n       ys = take (n div 2) xs;\n       zs = drop (n div 2) xs\n   in if n \\<le> 1 then 0\n      else C_msort ys + C_msort zs + C_merge (msort ys) (msort zs))\"\n\ndeclare C_msort.simps [simp del]\n\nlemma length_merge: \"length(merge xs ys) = length xs + length ys\"\napply (induction xs ys rule: merge.induct)\napply auto\ndone\n\nlemma length_msort: \"length(msort xs) = length xs\"\nproof (induction xs rule: msort.induct)\n  case (1 xs)\n  show ?case\n    by (auto simp: msort.simps [of xs] 1 length_merge)\nqed\ntext \\<open>Why structured proof?\n   To have the name \"xs\" to specialize msort.simps with xs\n   to ensure that msort.simps cannot be used recursively.\nAlso works without this precaution, but that is just luck.\\<close>\n\nlemma C_msort_le: \"length xs = 2^k \\<Longrightarrow> C_msort xs \\<le> k * 2^k\"\nproof(induction k arbitrary: xs)\n  case 0 thus ?case by (simp add: C_msort.simps)\nnext\n  case (Suc k)\n  let ?n = \"length xs\"\n  let ?ys = \"take (?n div 2) xs\"\n  let ?zs = \"drop (?n div 2) xs\"\n  show ?case\n  proof (cases \"?n \\<le> 1\")\n    case True\n    thus ?thesis by(simp add: C_msort.simps)\n  next\n    case False\n    have \"C_msort(xs) =\n      C_msort ?ys + C_msort ?zs + C_merge (msort ?ys) (msort ?zs)\"\n      by (simp add: C_msort.simps msort.simps)\n    also have \"\\<dots> \\<le> C_msort ?ys + C_msort ?zs + length ?ys + length ?zs\"\n      using C_merge_ub[of \"msort ?ys\" \"msort ?zs\"] length_msort[of ?ys] length_msort[of ?zs]\n      by arith\n    also have \"\\<dots> \\<le> k * 2^k + C_msort ?zs + length ?ys + length ?zs\"\n      using Suc.IH[of ?ys] Suc.prems by simp\n    also have \"\\<dots> \\<le> k * 2^k + k * 2^k + length ?ys + length ?zs\"\n      using Suc.IH[of ?zs] Suc.prems by simp\n    also have \"\\<dots> = 2 * k * 2^k + 2 * 2 ^ k\"\n      using Suc.prems by simp\n    finally show ?thesis by simp\n  qed\nqed\n\n(* Beware of implicit conversions: *)\nlemma C_msort_log: \"length xs = 2^k \\<Longrightarrow> C_msort xs \\<le> length xs * log 2 (length xs)\"\nusing C_msort_le[of xs k] apply (simp add: log_nat_power algebra_simps)\nby (metis (mono_tags) numeral_power_eq_of_nat_cancel_iff of_nat_le_iff of_nat_mult)\n\n\nsubsection \"Bottom-Up Merge Sort\"\n\nfun merge_adj :: \"('a::linorder) list list \\<Rightarrow> 'a list list\" where\n\"merge_adj [] = []\" |\n\"merge_adj [xs] = [xs]\" |\n\"merge_adj (xs # ys # zss) = merge xs ys # merge_adj zss\"\n\ntext \\<open>For the termination proof of \\<open>merge_all\\<close> below.\\<close>\nlemma length_merge_adjacent[simp]: \"length (merge_adj xs) = (length xs + 1) div 2\"\nby (induction xs rule: merge_adj.induct) auto\n\nfun merge_all :: \"('a::linorder) list list \\<Rightarrow> 'a list\" where\n\"merge_all [] = []\" |\n\"merge_all [xs] = xs\" |\n\"merge_all xss = merge_all (merge_adj xss)\"\n\ndefinition msort_bu :: \"('a::linorder) list \\<Rightarrow> 'a list\" where\n\"msort_bu xs = merge_all (map (\\<lambda>x. [x]) xs)\"\n\n\nsubsubsection \"Functional Correctness\"\n\nabbreviation mset_mset :: \"'a list list \\<Rightarrow> 'a multiset\" where\n\"mset_mset xss \\<equiv> \\<Sum>\\<^sub># (image_mset mset (mset xss))\"\n\nlemma mset_merge_adj:\n  \"mset_mset (merge_adj xss) = mset_mset xss\"\nby(induction xss rule: merge_adj.induct) (auto simp: mset_merge)\n\nlemma mset_merge_all:\n  \"mset (merge_all xss) = mset_mset xss\"\nby(induction xss rule: merge_all.induct) (auto simp: mset_merge mset_merge_adj)\n\nlemma mset_msort_bu: \"mset (msort_bu xs) = mset xs\"\nby(simp add: msort_bu_def mset_merge_all multiset.map_comp comp_def)\n\nlemma sorted_merge_adj:\n  \"\\<forall>xs \\<in> set xss. sorted xs \\<Longrightarrow> \\<forall>xs \\<in> set (merge_adj xss). sorted xs\"\nby(induction xss rule: merge_adj.induct) (auto simp: sorted_merge)\n\nlemma sorted_merge_all:\n  \"\\<forall>xs \\<in> set xss. sorted xs \\<Longrightarrow> sorted (merge_all xss)\"\napply(induction xss rule: merge_all.induct)\nusing [[simp_depth_limit=3]] by (auto simp add: sorted_merge_adj)\n\nlemma sorted_msort_bu: \"sorted (msort_bu xs)\"\nby(simp add: msort_bu_def sorted_merge_all)\n\n\nsubsubsection \"Time Complexity\"\n\nfun C_merge_adj :: \"('a::linorder) list list \\<Rightarrow> nat\" where\n\"C_merge_adj [] = 0\" |\n\"C_merge_adj [xs] = 0\" |\n\"C_merge_adj (xs # ys # zss) = C_merge xs ys + C_merge_adj zss\"\n\nfun C_merge_all :: \"('a::linorder) list list \\<Rightarrow> nat\" where\n\"C_merge_all [] = 0\" |\n\"C_merge_all [xs] = 0\" |\n\"C_merge_all xss = C_merge_adj xss + C_merge_all (merge_adj xss)\"\n\ndefinition C_msort_bu :: \"('a::linorder) list \\<Rightarrow> nat\" where\n\"C_msort_bu xs = C_merge_all (map (\\<lambda>x. [x]) xs)\"\n\nlemma length_merge_adj:\n  \"\\<lbrakk> even(length xss); \\<forall>xs \\<in> set xss. length xs = m \\<rbrakk>\n  \\<Longrightarrow> \\<forall>xs \\<in> set (merge_adj xss). length xs = 2*m\"\nby(induction xss rule: merge_adj.induct) (auto simp: length_merge)\n\nlemma C_merge_adj: \"\\<forall>xs \\<in> set xss. length xs = m \\<Longrightarrow> C_merge_adj xss \\<le> m * length xss\"\nproof(induction xss rule: C_merge_adj.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 x y) thus ?case using C_merge_ub[of x y] by (simp add: algebra_simps)\nqed\n\nlemma C_merge_all: \"\\<lbrakk> \\<forall>xs \\<in> set xss. length xs = m; length xss = 2^k \\<rbrakk>\n  \\<Longrightarrow> C_merge_all xss \\<le> m * k * 2^k\"\nproof (induction xss arbitrary: k m rule: C_merge_all.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 xs ys xss)\n  let ?xss = \"xs # ys # xss\"\n  let ?xss2 = \"merge_adj ?xss\"\n  obtain k' where k': \"k = Suc k'\" using \"3.prems\"(2)\n    by (metis length_Cons nat.inject nat_power_eq_Suc_0_iff nat.exhaust)\n  have \"even (length ?xss)\" using \"3.prems\"(2) k' by auto\n  from length_merge_adj[OF this \"3.prems\"(1)]\n  have *: \"\\<forall>x \\<in> set(merge_adj ?xss). length x = 2*m\" .\n  have **: \"length ?xss2 = 2 ^ k'\" using \"3.prems\"(2) k' by auto\n  have \"C_merge_all ?xss = C_merge_adj ?xss + C_merge_all ?xss2\" by simp\n  also have \"\\<dots> \\<le> m * 2^k + C_merge_all ?xss2\"\n    using \"3.prems\"(2) C_merge_adj[OF \"3.prems\"(1)] by (auto simp: algebra_simps)\n  also have \"\\<dots> \\<le> m * 2^k + (2*m) * k' * 2^k'\"\n    using \"3.IH\"[OF * **] by simp\n  also have \"\\<dots> = m * k * 2^k\"\n    using k' by (simp add: algebra_simps)\n  finally show ?case .\nqed\n\ncorollary C_msort_bu: \"length xs = 2 ^ k \\<Longrightarrow> C_msort_bu xs \\<le> k * 2 ^ k\"\nusing C_merge_all[of \"map (\\<lambda>x. [x]) xs\" 1] by (simp add: C_msort_bu_def)\n\n\nsubsection \"Quicksort\"\n\nfun quicksort :: \"('a::linorder) list \\<Rightarrow> 'a list\" where\n\"quicksort []     = []\" |\n\"quicksort (x#xs) = quicksort (filter (\\<lambda>y. y < x) xs) @ [x] @ quicksort (filter (\\<lambda>y. x \\<le> y) xs)\"\n\nlemma mset_quicksort: \"mset (quicksort xs) = mset xs\"\napply (induction xs rule: quicksort.induct)\napply (auto simp: not_le)\ndone\n\nlemma set_quicksort: \"set (quicksort xs) = set xs\"\nby(rule mset_eq_setD[OF mset_quicksort])\n\nlemma sorted_quicksort: \"sorted (quicksort xs)\"\napply (induction xs rule: quicksort.induct)\napply (auto simp add: sorted_append set_quicksort)\ndone\n\n\nsubsection \"Insertion Sort w.r.t. Keys and Stability\"\n\nhide_const List.insort_key\n\nfun insort1_key :: \"('a \\<Rightarrow> 'k::linorder) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"insort1_key f x [] = [x]\" |\n\"insort1_key f x (y # ys) = (if f x \\<le> f y then x # y # ys else y # insort1_key f x ys)\"\n\nfun insort_key :: \"('a \\<Rightarrow> 'k::linorder) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"insort_key f [] = []\" |\n\"insort_key f (x # xs) = insort1_key f x (insort_key f xs)\"\n\n\nsubsubsection \"Standard functional correctness\"\n\nlemma mset_insort1_key: \"mset (insort1_key f x xs) = {#x#} + mset xs\"\nby(induction xs) simp_all\n\nlemma mset_insort_key: \"mset (insort_key f xs) = mset xs\"\nby(induction xs) (simp_all add: mset_insort1_key)\n\n(* Inductive proof simpler than derivation from mset lemma: *)\nlemma set_insort1_key: \"set (insort1_key f x xs) = {x} \\<union> set xs\"\nby (induction xs) auto\n\nlemma sorted_insort1_key: \"sorted (map f (insort1_key f a xs)) = sorted (map f xs)\"\nby(induction xs)(auto simp: set_insort1_key)\n\nlemma sorted_insort_key: \"sorted (map f (insort_key f xs))\"\nby(induction xs)(simp_all add: sorted_insort1_key)\n\n\nsubsubsection \"Stability\"\n\nlemma insort1_is_Cons: \"\\<forall>x\\<in>set xs. f a \\<le> f x \\<Longrightarrow> insort1_key f a xs = a # xs\"\nby (cases xs) auto\n\nlemma filter_insort1_key_neg:\n  \"\\<not> P x \\<Longrightarrow> filter P (insort1_key f x xs) = filter P xs\"\nby (induction xs) simp_all\n\nlemma filter_insort1_key_pos:\n  \"sorted (map f xs) \\<Longrightarrow> P x \\<Longrightarrow> filter P (insort1_key f x xs) = insort1_key f x (filter P xs)\"\nby (induction xs) (auto, subst insort1_is_Cons, auto)\n\nlemma sort_key_stable: \"filter (\\<lambda>y. f y = k) (insort_key f xs) = filter (\\<lambda>y. f y = k) xs\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\n  thus ?case\n  proof (cases \"f a = k\")\n    case False thus ?thesis  by (simp add: Cons.IH filter_insort1_key_neg)\n  next\n    case True\n    have \"filter (\\<lambda>y. f y = k) (insort_key f (a # xs))\n      = filter (\\<lambda>y. f y = k) (insort1_key f a (insort_key f xs))\"  by simp\n    also have \"\\<dots> = insort1_key f a (filter (\\<lambda>y. f y = k) (insort_key f xs))\"\n      by (simp add: True filter_insort1_key_pos sorted_insort_key)\n    also have \"\\<dots> = insort1_key f a (filter (\\<lambda>y. f y = k) xs)\"  by (simp add: Cons.IH)\n    also have \"\\<dots> = a # (filter (\\<lambda>y. f y = k) xs)\"  by(simp add: True insort1_is_Cons)\n    also have \"\\<dots> = filter (\\<lambda>y. f y = k) (a # xs)\" by (simp add: True)\n    finally show ?thesis .\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/Sorting.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.9046505261034854, "lm_q1q2_score": 0.7827254152128824}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_TSortSorts\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Tree = TNode \"Tree\" \"Nat\" \"Tree\" | TNil\n\nfun le :: \"Nat => Nat => bool\" where\n\"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun ordered :: \"Nat list => bool\" where\n\"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun flatten :: \"Tree => Nat list => Nat list\" where\n\"flatten (TNode q z r) y = flatten q (cons2 z (flatten r y))\"\n| \"flatten (TNil) y = y\"\n\nfun add :: \"Nat => Tree => Tree\" where\n\"add x (TNode q z r) =\n   (if le x z then TNode (add x q) z r else TNode q z (add x r))\"\n| \"add x (TNil) = TNode TNil x TNil\"\n\nfun toTree :: \"Nat list => Tree\" where\n\"toTree (nil2) = TNil\"\n| \"toTree (cons2 y xs) = add y (toTree xs)\"\n\nfun tsort :: \"Nat list => Nat list\" where\n\"tsort x = flatten (toTree x) (nil2)\"\n\ntheorem property0 :\n  \"ordered (tsort xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_TSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299570920387, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7826912795829672}}
{"text": "(*  Title:      HOL/Isar_Examples/Mutilated_Checkerboard.thy\n    Author:     Markus Wenzel, TU Muenchen (Isar document)\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory (original scripts)\n*)\n\nsection \\<open>The Mutilated Checker Board Problem\\<close>\n\ntheory Mutilated_Checkerboard\n  imports Main\nbegin\n\ntext \\<open>\n  The Mutilated Checker Board Problem, formalized inductively. See \\<^cite>\\<open>\"paulson-mutilated-board\"\\<close> for the original tactic script version.\n\\<close>\n\nsubsection \\<open>Tilings\\<close>\n\ninductive_set tiling :: \"'a set set \\<Rightarrow> 'a set set\" for A :: \"'a set set\"\n  where\n    empty: \"{} \\<in> tiling A\"\n  | Un: \"a \\<union> t \\<in> tiling A\" if \"a \\<in> A\" and \"t \\<in> tiling A\" and \"a \\<subseteq> - t\"\n\n\ntext \\<open>The union of two disjoint tilings is a tiling.\\<close>\n\nlemma tiling_Un:\n  assumes \"t \\<in> tiling A\"\n    and \"u \\<in> tiling A\"\n    and \"t \\<inter> u = {}\"\n  shows \"t \\<union> u \\<in> tiling A\"\nproof -\n  let ?T = \"tiling A\"\n  from \\<open>t \\<in> ?T\\<close> and \\<open>t \\<inter> u = {}\\<close>\n  show \"t \\<union> u \\<in> ?T\"\n  proof (induct t)\n    case empty\n    with \\<open>u \\<in> ?T\\<close> show \"{} \\<union> u \\<in> ?T\" by simp\n  next\n    case (Un a t)\n    show \"(a \\<union> t) \\<union> u \\<in> ?T\"\n    proof -\n      have \"a \\<union> (t \\<union> u) \\<in> ?T\"\n        using \\<open>a \\<in> A\\<close>\n      proof (rule tiling.Un)\n        from \\<open>(a \\<union> t) \\<inter> u = {}\\<close> have \"t \\<inter> u = {}\" by blast\n        then show \"t \\<union> u \\<in> ?T\" by (rule Un)\n        from \\<open>a \\<subseteq> - t\\<close> and \\<open>(a \\<union> t) \\<inter> u = {}\\<close>\n        show \"a \\<subseteq> - (t \\<union> u)\" by blast\n      qed\n      also have \"a \\<union> (t \\<union> u) = (a \\<union> t) \\<union> u\"\n        by (simp only: Un_assoc)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Basic properties of ``below''\\<close>\n\ndefinition below :: \"nat \\<Rightarrow> nat set\"\n  where \"below n = {i. i < n}\"\n\nlemma below_less_iff [iff]: \"i \\<in> below k \\<longleftrightarrow> i < k\"\n  by (simp add: below_def)\n\nlemma below_0: \"below 0 = {}\"\n  by (simp add: below_def)\n\nlemma Sigma_Suc1: \"m = n + 1 \\<Longrightarrow> below m \\<times> B = ({n} \\<times> B) \\<union> (below n \\<times> B)\"\n  by (simp add: below_def less_Suc_eq) blast\n\nlemma Sigma_Suc2:\n  \"m = n + 2 \\<Longrightarrow>\n    A \\<times> below m = (A \\<times> {n}) \\<union> (A \\<times> {n + 1}) \\<union> (A \\<times> below n)\"\n  by (auto simp add: below_def)\n\nlemmas Sigma_Suc = Sigma_Suc1 Sigma_Suc2\n\n\nsubsection \\<open>Basic properties of ``evnodd''\\<close>\n\ndefinition evnodd :: \"(nat \\<times> nat) set \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"evnodd A b = A \\<inter> {(i, j). (i + j) mod 2 = b}\"\n\nlemma evnodd_iff: \"(i, j) \\<in> evnodd A b \\<longleftrightarrow> (i, j) \\<in> A  \\<and> (i + j) mod 2 = b\"\n  by (simp add: evnodd_def)\n\nlemma evnodd_subset: \"evnodd A b \\<subseteq> A\"\n  unfolding evnodd_def by (rule Int_lower1)\n\nlemma evnoddD: \"x \\<in> evnodd A b \\<Longrightarrow> x \\<in> A\"\n  by (rule subsetD) (rule evnodd_subset)\n\nlemma evnodd_finite: \"finite A \\<Longrightarrow> finite (evnodd A b)\"\n  by (rule finite_subset) (rule evnodd_subset)\n\nlemma evnodd_Un: \"evnodd (A \\<union> B) b = evnodd A b \\<union> evnodd B b\"\n  unfolding evnodd_def by blast\n\nlemma evnodd_Diff: \"evnodd (A - B) b = evnodd A b - evnodd B b\"\n  unfolding evnodd_def by blast\n\nlemma evnodd_empty: \"evnodd {} b = {}\"\n  by (simp add: evnodd_def)\n\nlemma evnodd_insert: \"evnodd (insert (i, j) C) b =\n    (if (i + j) mod 2 = b\n      then insert (i, j) (evnodd C b) else evnodd C b)\"\n  by (simp add: evnodd_def)\n\n\nsubsection \\<open>Dominoes\\<close>\n\ninductive_set domino :: \"(nat \\<times> nat) set set\"\n  where\n    horiz: \"{(i, j), (i, j + 1)} \\<in> domino\"\n  | vertl: \"{(i, j), (i + 1, j)} \\<in> domino\"\n\nlemma dominoes_tile_row:\n  \"{i} \\<times> below (2 * n) \\<in> tiling domino\"\n  (is \"?B n \\<in> ?T\")\nproof (induct n)\n  case 0\n  show ?case by (simp add: below_0 tiling.empty)\nnext\n  case (Suc n)\n  let ?a = \"{i} \\<times> {2 * n + 1} \\<union> {i} \\<times> {2 * n}\"\n  have \"?B (Suc n) = ?a \\<union> ?B n\"\n    by (auto simp add: Sigma_Suc Un_assoc)\n  also have \"\\<dots> \\<in> ?T\"\n  proof (rule tiling.Un)\n    have \"{(i, 2 * n), (i, 2 * n + 1)} \\<in> domino\"\n      by (rule domino.horiz)\n    also have \"{(i, 2 * n), (i, 2 * n + 1)} = ?a\" by blast\n    finally show \"\\<dots> \\<in> domino\" .\n    show \"?B n \\<in> ?T\" by (rule Suc)\n    show \"?a \\<subseteq> - ?B n\" by blast\n  qed\n  finally show ?case .\nqed\n\nlemma dominoes_tile_matrix:\n  \"below m \\<times> below (2 * n) \\<in> tiling domino\"\n  (is \"?B m \\<in> ?T\")\nproof (induct m)\n  case 0\n  show ?case by (simp add: below_0 tiling.empty)\nnext\n  case (Suc m)\n  let ?t = \"{m} \\<times> below (2 * n)\"\n  have \"?B (Suc m) = ?t \\<union> ?B m\" by (simp add: Sigma_Suc)\n  also have \"\\<dots> \\<in> ?T\"\n  proof (rule tiling_Un)\n    show \"?t \\<in> ?T\" by (rule dominoes_tile_row)\n    show \"?B m \\<in> ?T\" by (rule Suc)\n    show \"?t \\<inter> ?B m = {}\" by blast\n  qed\n  finally show ?case .\nqed\n\nlemma domino_singleton:\n  assumes \"d \\<in> domino\"\n    and \"b < 2\"\n  shows \"\\<exists>i j. evnodd d b = {(i, j)}\"  (is \"?P d\")\n  using assms\nproof induct\n  from \\<open>b < 2\\<close> have b_cases: \"b = 0 \\<or> b = 1\" by arith\n  fix i j\n  note [simp] = evnodd_empty evnodd_insert mod_Suc\n  from b_cases show \"?P {(i, j), (i, j + 1)}\" by rule auto\n  from b_cases show \"?P {(i, j), (i + 1, j)}\" by rule auto\nqed\n\nlemma domino_finite:\n  assumes \"d \\<in> domino\"\n  shows \"finite d\"\n  using assms\nproof induct\n  fix i j :: nat\n  show \"finite {(i, j), (i, j + 1)}\" by (intro finite.intros)\n  show \"finite {(i, j), (i + 1, j)}\" by (intro finite.intros)\nqed\n\n\nsubsection \\<open>Tilings of dominoes\\<close>\n\nlemma tiling_domino_finite:\n  assumes t: \"t \\<in> tiling domino\"  (is \"t \\<in> ?T\")\n  shows \"finite t\"  (is \"?F t\")\n  using t\nproof induct\n  show \"?F {}\" by (rule finite.emptyI)\n  fix a t assume \"?F t\"\n  assume \"a \\<in> domino\"\n  then have \"?F a\" by (rule domino_finite)\n  from this and \\<open>?F t\\<close> show \"?F (a \\<union> t)\" by (rule finite_UnI)\nqed\n\nlemma tiling_domino_01:\n  assumes t: \"t \\<in> tiling domino\"  (is \"t \\<in> ?T\")\n  shows \"card (evnodd t 0) = card (evnodd t 1)\"\n  using t\nproof induct\n  case empty\n  show ?case by (simp add: evnodd_def)\nnext\n  case (Un a t)\n  let ?e = evnodd\n  note hyp = \\<open>card (?e t 0) = card (?e t 1)\\<close>\n    and at = \\<open>a \\<subseteq> - t\\<close>\n  have card_suc: \"card (?e (a \\<union> t) b) = Suc (card (?e t b))\" if \"b < 2\" for b :: nat\n  proof -\n    have \"?e (a \\<union> t) b = ?e a b \\<union> ?e t b\" by (rule evnodd_Un)\n    also obtain i j where e: \"?e a b = {(i, j)}\"\n    proof -\n      from \\<open>a \\<in> domino\\<close> and \\<open>b < 2\\<close>\n      have \"\\<exists>i j. ?e a b = {(i, j)}\" by (rule domino_singleton)\n      then show ?thesis by (blast intro: that)\n    qed\n    also have \"\\<dots> \\<union> ?e t b = insert (i, j) (?e t b)\" by simp\n    also have \"card \\<dots> = Suc (card (?e t b))\"\n    proof (rule card_insert_disjoint)\n      from \\<open>t \\<in> tiling domino\\<close> have \"finite t\"\n        by (rule tiling_domino_finite)\n      then show \"finite (?e t b)\"\n        by (rule evnodd_finite)\n      from e have \"(i, j) \\<in> ?e a b\" by simp\n      with at show \"(i, j) \\<notin> ?e t b\" by (blast dest: evnoddD)\n    qed\n    finally show ?thesis .\n  qed\n  then have \"card (?e (a \\<union> t) 0) = Suc (card (?e t 0))\" by simp\n  also from hyp have \"card (?e t 0) = card (?e t 1)\" .\n  also from card_suc have \"Suc \\<dots> = card (?e (a \\<union> t) 1)\"\n    by simp\n  finally show ?case .\nqed\n\n\nsubsection \\<open>Main theorem\\<close>\n\ndefinition mutilated_board :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"mutilated_board m n =\n    below (2 * (m + 1)) \\<times> below (2 * (n + 1)) - {(0, 0)} - {(2 * m + 1, 2 * n + 1)}\"\n\ntheorem mutil_not_tiling: \"mutilated_board m n \\<notin> tiling domino\"\nproof (unfold mutilated_board_def)\n  let ?T = \"tiling domino\"\n  let ?t = \"below (2 * (m + 1)) \\<times> below (2 * (n + 1))\"\n  let ?t' = \"?t - {(0, 0)}\"\n  let ?t'' = \"?t' - {(2 * m + 1, 2 * n + 1)}\"\n\n  show \"?t'' \\<notin> ?T\"\n  proof\n    have t: \"?t \\<in> ?T\" by (rule dominoes_tile_matrix)\n    assume t'': \"?t'' \\<in> ?T\"\n\n    let ?e = evnodd\n    have fin: \"finite (?e ?t 0)\"\n      by (rule evnodd_finite, rule tiling_domino_finite, rule t)\n\n    note [simp] = evnodd_iff evnodd_empty evnodd_insert evnodd_Diff\n    have \"card (?e ?t'' 0) < card (?e ?t' 0)\"\n    proof -\n      have \"card (?e ?t' 0 - {(2 * m + 1, 2 * n + 1)})\n        < card (?e ?t' 0)\"\n      proof (rule card_Diff1_less)\n        from _ fin show \"finite (?e ?t' 0)\"\n          by (rule finite_subset) auto\n        show \"(2 * m + 1, 2 * n + 1) \\<in> ?e ?t' 0\" by simp\n      qed\n      then show ?thesis by simp\n    qed\n    also have \"\\<dots> < card (?e ?t 0)\"\n    proof -\n      have \"(0, 0) \\<in> ?e ?t 0\" by simp\n      with fin have \"card (?e ?t 0 - {(0, 0)}) < card (?e ?t 0)\"\n        by (rule card_Diff1_less)\n      then show ?thesis by simp\n    qed\n    also from t have \"\\<dots> = card (?e ?t 1)\"\n      by (rule tiling_domino_01)\n    also have \"?e ?t 1 = ?e ?t'' 1\" by simp\n    also from t'' have \"card \\<dots> = card (?e ?t'' 0)\"\n      by (rule tiling_domino_01 [symmetric])\n    finally have \"\\<dots> < \\<dots>\" . then show False ..\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Isar_Examples/Mutilated_Checkerboard.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013356, "lm_q2_score": 0.8577681031721325, "lm_q1q2_score": 0.782658642807691}}
{"text": "theory YT_tut_1 imports Main begin\n\nvalue \"2 + (2 :: nat)\"\nvalue \"(2 :: nat) * (5+3)\"\n\nlemma \"(x :: nat) + y = y + x\" by auto\n\nlemma \"(x :: nat) + (y + z) = (x + y) + z\" by auto\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count [] _ = 0\"\n| \"count (x#xs) x' = (if x = x' then Suc (count xs x') else count xs x')\"\n\nvalue \"count [1,2,3,0,0] (0::nat)\"\n\ntheorem \"count xs x \\<le> length xs\"\napply (induction xs) apply auto done\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc [] x     = [x]\"\n| \"snoc (x#xs) x' = x # (snoc xs x')\"\n\nvalue \"snoc [86, 1] (42::nat)\"\nlemma \"snoc [86, 1] (42::nat) = [86, 1, 42]\" by auto\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse []     = []\"\n| \"reverse (x#xs) = snoc (reverse xs) x\"\n\nvalue \"reverse [1::nat,2,3,4]\"\n\nlemma reverse_snoc: \"reverse (snoc ys a) = a # (reverse ys)\" apply (induction ys) by auto\n\ntheorem \"reverse (reverse xs) = xs\" apply (induction xs) by (auto simp: reverse_snoc)\n\nend\n", "meta": {"author": "brunoflores", "repo": "concrete-semantics-book", "sha": "bb45ae1ded27aa1ca2fb25e49013815293c51f80", "save_path": "github-repos/isabelle/brunoflores-concrete-semantics-book", "path": "github-repos/isabelle/brunoflores-concrete-semantics-book/concrete-semantics-book-bb45ae1ded27aa1ca2fb25e49013815293c51f80/YT_tut_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91243616285804, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7826586333628345}}
{"text": "theory TeslDenotationalTickNum\n\nimports \"../TeslDenotationalOperators\"\n\nbegin\n\ntext {*\n  Number of ticks of clock c in a window [s, s+w]\n*}\ndefinition tick_num\nwhere\n  \"tick_num c h s w \\<equiv> card {i. s \\<le> i \\<and> i \\<le> s+w \\<and> ticks c (h i)}\"\n\nfun tick_num_fun :: \"('a, 'b)\\<H> \\<Rightarrow> hamlet \\<Rightarrow> instant \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"tick_num_fun c h s 0 = (if ticks c (h s) then 1 else 0)\"\n| \"tick_num_fun c h s (Suc w) = (if ticks c (h (s + (Suc w)))\n                                 then Suc (tick_num_fun c h s w)\n                                 else tick_num_fun c h s w)\"\n\ntext {*\n  Some lemmas about cardinals\n*}\nlemma card_sing:\"card {i. i = k \\<and> P i} = (if P k then 1 else 0)\"\nproof (cases \"P k\")\n  case True\n    hence \"{i. i = k \\<and> P i} = {k}\" by auto\n    hence \"card {i. i = k \\<and> P i} = 1\" by simp\n    thus ?thesis using True by simp\nnext\n  case False\n    hence \"{i. i = k \\<and> P i} = {}\" by auto\n    hence \"card {i. i = k \\<and> P i} = 0\" by simp\n    thus ?thesis using False by simp\nqed\n\nlemma card_suc:\"card {i. l \\<le> i \\<and> i \\<le> l + (Suc h) \\<and> P i} =\n                  (if P (l + Suc h) then Suc (card {i. l \\<le> i \\<and> i \\<le> l + h \\<and> P i})\n                                else card {i. l \\<le> i \\<and> i \\<le> l + h \\<and> P i})\"\nproof (cases \"P (l + Suc h)\")\n  case True\n    hence \"{i. l \\<le> i \\<and> i \\<le> l + (Suc h) \\<and> P i} = {i. l \\<le> i \\<and> i \\<le> l + h \\<and> P i} \\<union> {l + Suc h}\" by auto\n    hence \"card {i. l \\<le> i \\<and> i \\<le> l + (Suc h) \\<and> P i} = Suc (card {i. l \\<le> i \\<and> i \\<le> l + h \\<and> P i})\" by simp\n    thus ?thesis using True by simp\nnext\n  case False\n    hence \"{i. l \\<le> i \\<and> i \\<le> l + (Suc h) \\<and> P i} = {i. l \\<le> i \\<and> i \\<le> l + h \\<and> P i}\" using le_Suc_eq by auto\n    hence \"card {i. l \\<le> i \\<and> i \\<le> l + (Suc h) \\<and> P i} = card {i. l \\<le> i \\<and> i \\<le> l + h \\<and> P i}\" by simp\n    thus ?thesis using False by simp\nqed\n\ntext {*\n  Equivalence of the denotational and the function definitions of tick_num.\n*}\nlemma tick_num_is_fun:\"tick_num c h s w = tick_num_fun c h s w\"\nproof (induction w)\n  case 0\n    have \"tick_num c h s 0 = card {i. s \\<le> i \\<and> i \\<le> s+0 \\<and> ticks c (h i)}\" using tick_num_def by blast\n    also have \"... = card {i. s = i \\<and> ticks c (h i)}\" by (simp add: eq_iff)\n    also have \"... = card {i. i = s \\<and> ticks c (h i)}\" using eq_sym_conv[of _ \"s\"] by simp \n    also have \"... = (if ticks c (h s) then 1 else 0)\" using card_sing[of \"s\" \"\\<lambda>i. ticks c (h i)\"] .\n    finally show ?case by simp\nnext\n  case (Suc v)\n    have \"tick_num c h s (Suc v) = card {i. s \\<le> i \\<and> i \\<le> s + (Suc v) \\<and> ticks c (h i)}\" using tick_num_def by blast\n    also have \"... = (if ticks c (h (s + Suc v))\n                      then Suc (card {i. s \\<le> i \\<and> i \\<le> s + v \\<and> ticks c (h i)})\n                      else card {i. s \\<le> i \\<and> i \\<le> s + v \\<and> ticks c (h i)})\"  using card_suc by simp\n    also have \"... = (if ticks c (h (s + Suc v))\n                      then Suc (tick_num c h s v)\n                      else tick_num c h s v)\" using tick_num_def[of \"c\" \"h\" \"s\" \"v\",symmetric] by simp\n    finally show ?case using Suc.IH by simp\nqed\n\ntext {*\n  hasticked clk hmt from width n = clock clk, in a system with hamlet hmt, has ticked n times\n                               in the interval [from, from+width]\n*}\ninductive hasticked :: \"('a, 'b)\\<H> \\<Rightarrow> hamlet \\<Rightarrow> instant \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  (* Base case for a singleton interval *)\n  \"\\<not> ticks clk (hmt from) \\<Longrightarrow> hasticked clk hmt from 0 0\"\n| \"  ticks clk (hmt from) \\<Longrightarrow> hasticked clk hmt from 0 1\"\n  (* Induction for larger intervals *)\n| \"hasticked clk hmt from w d \\<and> \\<not> ticks clk (hmt (from + (Suc w))) \\<Longrightarrow> hasticked clk hmt from (Suc w) d\"\n| \"hasticked clk hmt from w d \\<and> ticks clk (hmt (from + (Suc w))) \\<Longrightarrow> hasticked clk hmt from (Suc w) (Suc d)\"\n\ninductive_cases Ticked00[elim!]: \"hasticked clk hmt from 0 0\"\nthm Ticked00\ninductive_cases Ticked01[elim!]: \"hasticked clk hmt from 0 1\"\nthm Ticked01\ninductive_cases Tickedw0[elim!]: \"hasticked clk hmt from (Suc w) d\"\ninductive_cases Tickedwd[elim!]: \"hasticked clk hmt from (Suc w) (Suc d)\"\ninductive_cases Ticked0d[elim!]:\"hasticked clk hmt from 0 d\"\nthm Ticked0d\ninductive_cases Ticked0sd[elim!]:\"hasticked clk hmt from 0 (Suc d)\"\nthm Ticked0sd\n\nlemmas hasticked.intros[intro]\n\ntext {*\n  Functional version of the inductive predicate\n*}\nfun hasticked_fun :: \"('a, 'b)\\<H> \\<Rightarrow> hamlet \\<Rightarrow> instant \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"hasticked_fun clk hmt from 0 0 = (\\<not>ticks clk (hmt from))\"\n| \"hasticked_fun clk hmt from 0 (Suc 0) = ticks clk (hmt from)\"\n| \"hasticked_fun clk hmt from (Suc w) 0 =\n    (hasticked_fun clk hmt from w 0 \\<and> \\<not>ticks clk (hmt (from + (Suc w))))\"\n| \"hasticked_fun clk hmt from (Suc w) (Suc d) = (\n    (hasticked_fun clk hmt from w (Suc d) \\<and> \\<not>ticks clk (hmt (from + (Suc w))))\n  \\<or> (hasticked_fun clk hmt from w d \\<and> ticks clk (hmt (from + (Suc w))))\n   )\"\n| \"hasticked_fun clk hmt from _ _ = False\"\n\ntext {*\n  Proof of equivalence of the two definitions.\n*}\nlemma hasticked_is_fun[code]: \"hasticked clk hmt from w d = hasticked_fun clk hmt from w d\"\nproof (induction d arbitrary: w)\n  case 0 thus ?case by (induction w, auto)\nnext\n  case (Suc d') thus ?case\n    proof (induction w)\n      case 0 thus ?case\n        proof (cases \"d' = 0\")\n          case True thus ?thesis by (metis One_nat_def Ticked01 hasticked_fun.simps(2) hasticked.intros(2))\n        next\n          case False\n            hence \"\\<not>hasticked clk hmt from 0 (Suc d')\" using Ticked0sd by blast\n            moreover have \"\\<not>hasticked_fun clk hmt from 0 (Suc d')\" by (metis False hasticked_fun.simps(5) lessI less_Suc_eq_0_disj) \n            ultimately show ?thesis by simp\n        qed\n    next\n      case (Suc w') thus ?case by auto\n    qed\nqed\n\ntext {*\n  hasjustticked clk hmt from width n = clock c, in a system with hamlet h, has ticked for the nth time\n                                       at the end of the interval [from, from+width]\n*}\ninductive hasjustticked :: \"('a, 'b)\\<H> \\<Rightarrow> hamlet \\<Rightarrow> instant \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"ticks clk (hmt from) \\<Longrightarrow> hasjustticked clk hmt from 0 1\"\n| \"hasticked clk hmt from w d \\<and> ticks clk (hmt (from + (Suc w)))\n    \\<Longrightarrow> hasjustticked clk hmt from (Suc w) (Suc d)\"\n\nfun hasjustticked_fun :: \"('a, 'b)\\<H> \\<Rightarrow> hamlet \\<Rightarrow> instant \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"hasjustticked_fun clk hmt from 0 (Suc 0) = ticks clk (hmt from)\"\n| \"hasjustticked_fun clk hmt from (Suc w) (Suc d)\n    = (hasticked_fun clk hmt from w d \\<and> ticks clk (hmt (from + (Suc w))))\"\n| \"hasjustticked_fun clk hmt from w 0 = False\"\n| \"hasjustticked_fun clk hmt from 0 (Suc (Suc d)) = False\"\n\n\nend\n", "meta": {"author": "Frederic-Boulanger-UPS", "repo": "TESL_Denotational5", "sha": "050f44752b5354c4ec0e946df7bde910174be80c", "save_path": "github-repos/isabelle/Frederic-Boulanger-UPS-TESL_Denotational5", "path": "github-repos/isabelle/Frederic-Boulanger-UPS-TESL_Denotational5/TESL_Denotational5-050f44752b5354c4ec0e946df7bde910174be80c/src/extra/TeslDenotationalTickNum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632976542185, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7825973451792255}}
{"text": "(*  Title:       Partitions \n    Authors:     Thomas Tuerk <tuerk@in.tum.de>\n*)\n\nsection \\<open> Partition \\<close>\n\ntheory Partition\nimports Main \nbegin\n\ndefinition is_partition :: \"'a set \\<Rightarrow> ('a set) set \\<Rightarrow> bool\" where\n  \"is_partition Q P \\<longleftrightarrow>\n   (\\<Union>P = Q) \\<and> ({} \\<notin> P) \\<and> (\\<forall>p1 p2. p1 \\<in> P \\<and> p2 \\<in> P \\<and> p1 \\<noteq> p2 \\<longrightarrow> p1 \\<inter> p2 = {})\"\n\nlemma is_partitionI [intro!]:\n  \"\\<lbrakk>\\<And>q. q \\<in> Q \\<Longrightarrow> q \\<in> \\<Union>P;\n    \\<And>p. p \\<in> P \\<Longrightarrow> p \\<subseteq> Q;\n    \\<And>p. p \\<in> P \\<Longrightarrow> p \\<noteq> {};\n    \\<And>q p1 p2. \\<lbrakk>p1 \\<in> P; p2 \\<in> P; q \\<in> p1; q \\<in> p2\\<rbrakk> \\<Longrightarrow> p1 = p2\n   \\<rbrakk> \\<Longrightarrow> is_partition Q P\"\nunfolding is_partition_def\nby auto metis+\n\nlemma is_partition_Nil_Q :\n  \"is_partition {} P \\<longleftrightarrow> P = {}\"\nunfolding is_partition_def\nby auto\n\nlemma is_partition_Nil [simp] :\n  \"is_partition Q {} \\<longleftrightarrow> Q = {}\"\nunfolding is_partition_def\nby auto\n\nlemma is_partition_Insert :\nassumes p_nin: \"p \\<notin> P\"\nshows \"is_partition Q (insert p P) \\<longleftrightarrow> \n       (p \\<noteq> {}) \\<and> (p \\<subseteq> Q) \\<and> is_partition (Q - p) P\"\nproof (cases \"p \\<noteq> {} \\<and> ({} \\<notin> P) \\<and> p \\<subseteq> Q\")\n  case False thus ?thesis\n    unfolding is_partition_def\n    by (rule_tac iffI, auto)\nnext\n  case True \n  note p_not_Emp = conjunct1 [OF True]\n  note P_not_Emp = conjunct1 [OF conjunct2 [OF True]]\n  note p_subset = conjunct2 [OF conjunct2 [OF True]]\n\n  have \"(p \\<union> \\<Union>P = Q \\<and>\n        (\\<forall>p1 p2. (p1 = p \\<or> p1 \\<in> P) \\<and> (p2 = p \\<or> p2 \\<in> P) \\<and> p1 \\<noteq> p2 \\<longrightarrow> p1 \\<inter> p2 = {})) =\n        (\\<Union>P = Q - p \\<and> (\\<forall>p1 p2. p1 \\<in> P \\<and> p2 \\<in> P \\<and> p1 \\<noteq> p2 \\<longrightarrow> p1 \\<inter> p2 = {}))\"\n     (is \"?l1 \\<and> ?l2 \\<longleftrightarrow> ?r1 \\<and> ?r2\")\n  proof (intro iffI conjI)\n    assume r12: \"?r1 \\<and> ?r2\"\n    note r1 = conjunct1 [OF r12]\n    note r2 = conjunct2 [OF r12]\n\n    from r1 show \"?l1\" using p_subset by auto\n\n    have p_disjoint : \"\\<And>p'. p' \\<in> P \\<Longrightarrow> p \\<inter> p' = {}\"\n    proof -\n      fix p'\n      assume \"p' \\<in> P\" \n      with r1 have \"p' \\<subseteq> Q - p\"\n        by auto\n      thus \"p \\<inter> p' = {}\" by auto\n    qed\n\n    with r2 show ?l2 by blast\n  next\n    assume l12: \"?l1 \\<and> ?l2\"\n    note l1 = conjunct1 [OF l12]\n    note l2 = conjunct2 [OF l12]\n\n    from l2 show ?r2 by blast\n\n    from l2 p_nin \n    have p_disjoint : \"\\<And>p'. p' \\<in> P \\<Longrightarrow> p \\<inter> p' = {}\" by blast\n    with l1 show ?r1 by auto\n  qed\n  with p_not_Emp P_not_Emp p_subset show ?thesis  \n    unfolding is_partition_def\n    by simp\nqed\n\nlemma is_partition_in_subset :\nassumes is_part: \"is_partition Q P\"\n    and p_in: \"p \\<in> P\"\nshows \"p \\<subseteq> Q\"\nusing assms \nunfolding is_partition_def\nby auto\n\nlemma is_partition_memb_finite :\nassumes fin_Q: \"finite Q\"\n    and is_part: \"is_partition Q P\"\n    and p_in: \"p \\<in> P\"\nshows \"finite p\"\nby (metis finite_subset[OF _ fin_Q] is_partition_in_subset[OF is_part p_in])\n\nlemma is_partition_distinct_subset :\nassumes is_part: \"is_partition Q P\"\n    and p_in: \"p \\<in> P\"\n    and p'_sub: \"p' \\<subseteq> p\"\nshows \"p' \\<notin> P - {p}\"\nproof (rule notI)\n  assume p'_in: \"p' \\<in> P - {p}\"\n  \n  with is_part have \"p' \\<noteq> {}\"\n    unfolding is_partition_def by auto\n  hence \"p' \\<inter> p \\<noteq> {}\" using p'_sub by auto\n\n  with is_part show False\n    using p'_in p_in\n    unfolding is_partition_def\n    by blast\nqed\n\nlemma is_partition_finite :\nassumes fin_Q: \"finite Q\"\n    and is_part: \"is_partition Q P\"\nshows \"finite P\"\nproof -\n  from is_part have \"P \\<subseteq> Pow Q\"\n    unfolding is_partition_def by auto\n  moreover\n  from fin_Q have \"finite (Pow Q)\" by blast\n  ultimately show \"finite P\"\n    by (metis finite_subset)\nqed\n\nlemma is_partition_card :\nassumes fin_Q: \"finite Q\"\n    and is_part: \"is_partition Q P\"\nshows \"card Q = sum card P\"\nproof -\n  have fin_P: \"finite P\"\n    using is_partition_finite [OF fin_Q is_part] \n    .\n\n  have \"finite P \\<Longrightarrow> finite Q \\<Longrightarrow> is_partition Q P \\<Longrightarrow> card Q = sum card P\"\n  proof (induct arbitrary: Q rule: finite_induct)\n    case empty thus ?case by simp\n  next\n    case (insert p P Q)\n    note fin_P = insert(1)\n    note p_nin_P = insert(2)\n    note ind_hyp = insert(3)\n    note fin_Q = insert(4)\n    note is_part_pP = insert(5)\n\n    from is_part_pP p_nin_P have is_part_P: \"is_partition (Q - p) P\"\n      and p_neq_Nil: \"p \\<noteq> {}\" and p_subset: \"p \\<subseteq> Q\"  \n      by (simp_all add: is_partition_Insert)\n\n    from p_subset fin_Q have fin_p: \"finite p\" by (metis finite_subset)\n    from fin_Q have fin_Q_p: \"finite (Q - p)\" by simp\n    from p_subset have card_p: \"card p \\<le> card Q\"\n      using card_mono [OF fin_Q] by simp\n\n    show ?case\n      using sum.insert [OF fin_P p_nin_P, of card]\n            card_Diff_subset [OF fin_p p_subset]\n            ind_hyp[OF fin_Q_p is_part_P, symmetric]\n            card_p\n      by simp\n  qed\n  with fin_Q fin_P is_part\n  show ?thesis by simp\nqed\n\nlemma is_partition_card_P :\nassumes fin_Q: \"finite Q\"\n    and is_part: \"is_partition Q P\"\nshows \"card P \\<le> card Q\"\nproof -\n  from is_partition_card [OF fin_Q is_part]\n  have \"card Q = sum card P\" .\n  moreover  \n  have \"sum (\\<lambda>p. 1) P \\<le> sum card P\"\n  proof (rule sum_mono)\n    fix p\n    assume \"p \\<in> P\"\n    with is_part have p_neq_Nil: \"p \\<noteq> {}\" and p_sub: \"p \\<subseteq> Q\"\n      unfolding is_partition_def\n      by auto\n    from p_sub fin_Q have \"finite p\" by (metis finite_subset)\n    with p_neq_Nil have \"card p \\<noteq> 0\"\n      by (simp add: card_eq_0_iff)\n    thus \"1 \\<le> card p\" by auto\n  qed\n  moreover \n  have \"sum (\\<lambda>p. 1) P = card P\"\n    by (metis card_eq_sum)  \n  ultimately show ?thesis by simp\nqed\n\n\nlemma is_partition_find :\nassumes is_part: \"is_partition Q P\"\n    and q_in_Q: \"q \\<in> Q\"\nshows \"\\<exists>!p. p \\<in> P \\<and> q \\<in> p\"\nusing assms\nunfolding is_partition_def\nby auto\n\nlemma is_partition_refine :\nassumes fin_Q:         \"finite Q\"\n    and p_nin:         \"p \\<notin> P\"\n    and is_part:       \"is_partition Q (insert p P)\"\n    and p1_p2_neq_emp: \"p1 \\<noteq> {}\" \"p2 \\<noteq> {}\"\n    and p1_p2_disj: \"p1 \\<inter> p2 = {}\"\n    and p1_p2_union: \"p = p1 \\<union> p2\"\nshows \"is_partition Q (insert p1 (insert p2 P)) \\<and>\n       card (insert p1 (insert p2 P)) = Suc (card (insert p P))\"\nproof \n  from p1_p2_neq_emp p1_p2_disj \n  have p1_neq_p2: \"p1 \\<noteq> p2\" by auto\n\n  have q_disj: \"\\<And>p'. p' \\<subseteq> p \\<Longrightarrow> p' \\<notin> P\"\n  proof (rule notI)\n    fix p'\n    assume p'_sub: \"p' \\<subseteq> p\"\n    assume p'_in: \"p' \\<in> P\"\n\n    from is_part p'_in p_nin have \"p' \\<inter> p = {} \\<and> p' \\<noteq> {}\"\n      unfolding is_partition_def by blast\n    with p'_sub show \"False\" by auto\n  qed\n  hence p1_nin: \"p1 \\<notin> insert p2 P\" and\n        p2_nin: \"p2 \\<notin> P\"  \n    unfolding p1_p2_union using p1_neq_p2 by auto\n\n  have \"Q - p = Q - p1 - p2\"\n    unfolding p1_p2_union by auto\n  with is_part p1_p2_disj\n  show \"is_partition Q (insert p1 (insert p2 P))\"\n    using p_nin p1_nin p2_nin\n    apply (simp add: is_partition_Insert p1_p2_neq_emp)\n    apply (simp add: p1_p2_union)\n    apply auto\n  done\n\n  have \"finite P\" using is_partition_finite[OF fin_Q is_part] by simp\n  thus \"card (insert p1 (insert p2 P)) = Suc (card (insert p P))\"\n    using p_nin p2_nin p1_nin\n    by (simp add: card_insert_if)\nqed\n\n\nsubsection \\<open> Partitions and Equivalence Relations \\<close>\n\nlemma quotient_of_equiv_relation_is_partition :\nassumes eq_r: \"equiv Q r\"\nshows \"is_partition Q (Q//r)\"\nproof -\n  note Q_eq = Union_quotient[OF eq_r]\n  note quot_disj = quotient_disj [OF eq_r]\n\n  from eq_r have \"\\<And>q. q \\<in> Q \\<Longrightarrow> (q, q) \\<in> r\"\n    unfolding equiv_def refl_on_def by simp\n  hence emp_nin: \"{} \\<notin> Q // r\"\n    by (simp add: quotient_def Image_def) blast\n\n  from Q_eq quot_disj emp_nin\n  show ?thesis by blast\nqed\n\ndefinition relation_of_partition where\n  \"relation_of_partition P = {(q1, q2). \\<exists>Q \\<in> P. q1 \\<in> Q \\<and> q2 \\<in> Q}\"\n\nlemma relation_of_partition_is_equiv :\nassumes part_P: \"is_partition Q P\"\nshows \"equiv Q (relation_of_partition P)\"\nusing is_partition_in_subset[OF part_P] is_partition_find[OF part_P]\nunfolding equiv_def relation_of_partition_def refl_on_def sym_def trans_def\nby (auto simp add: subset_iff Ball_def Bex_def) metis+\n\ndefinition partition_less_eq where \n\"partition_less_eq P1 P2 \\<longleftrightarrow> relation_of_partition P1 \\<subseteq> relation_of_partition P2\"\n\nlemma relation_of_partition_inverse :\nassumes part_P: \"is_partition Q P\"\nshows \"Q // (relation_of_partition P) = P\"\n  (is \"?ls = ?rs\")\nproof \n  {\n    fix q\n    assume q_in: \"q \\<in> Q\" \n    from is_partition_find[OF part_P q_in]\n    obtain p where p_props: \"p \\<in> P\" \"q \\<in> p\" \"\\<And>p'. \\<lbrakk>p' \\<in> P; q \\<in> p'\\<rbrakk> \\<Longrightarrow> p' = p\" by auto\n\n    have \"{q2. \\<exists>Q\\<in>P. q \\<in> Q \\<and> q2 \\<in> Q} = p\" \n      apply (intro set_eqI)\n      apply (simp add: Bex_def)\n      apply (metis p_props)\n    done\n    with p_props(1)\n    have \"{q2. \\<exists>Q\\<in>P. q \\<in> Q \\<and> q2 \\<in> Q} \\<in> P\" by simp \n  }\n  thus \"?ls \\<subseteq> ?rs\"\n    unfolding relation_of_partition_def quotient_def\n    by auto\nnext\n  {\n    fix p\n    assume p_in: \"p \\<in> P\" \n    from p_in part_P have \"p \\<noteq> {}\" unfolding is_partition_def by blast\n    then obtain q where q_in_p: \"q \\<in> p\" by auto \n\n    with is_partition_in_subset[OF part_P p_in] have q_in_Q: \"q \\<in> Q\" by blast\n\n    from is_partition_find[OF part_P q_in_Q] p_in q_in_p\n    have p_dist: \"\\<And>p'. \\<lbrakk>p' \\<in> P; q \\<in> p'\\<rbrakk> \\<Longrightarrow> p' = p\" by auto\n\n    have \"{q2. \\<exists>Q\\<in>P. q \\<in> Q \\<and> q2 \\<in> Q} = p\" \n      apply (intro set_eqI)\n      apply (simp add: Bex_def)\n      apply (metis p_dist p_in q_in_p)\n    done\n    hence \"\\<exists>q\\<in>Q. p = {q2. \\<exists>Q\\<in>P. q \\<in> Q \\<and> q2 \\<in> Q}\" \n      unfolding Bex_def\n      apply (rule_tac exI [where x = q])\n      apply (simp add: q_in_Q)\n    done\n  }\n  thus \"?rs \\<subseteq> ?ls\"\n    unfolding relation_of_partition_def quotient_def\n    by auto\nqed\n\nlemma quotient_inverse :\nassumes eq_r: \"equiv Q r\"\nshows \"(relation_of_partition (Q // r)) = r\"\n  (is \"?ls = ?rs\")\nusing eq_r\nunfolding relation_of_partition_def quotient_def \napply (rule_tac set_eqI)\napply auto\napply (metis equiv_def sym_def trans_def)\napply (simp add: equiv_def refl_on_def subset_iff sym_def)\napply metis\ndone\n\nend", "meta": {"author": "VTrelat", "repo": "Hopcroft_verif", "sha": "ede77c3a2105fd6722cf96896a297db294edf269", "save_path": "github-repos/isabelle/VTrelat-Hopcroft_verif", "path": "github-repos/isabelle/VTrelat-Hopcroft_verif/Hopcroft_verif-ede77c3a2105fd6722cf96896a297db294edf269/Isabelle/Partition.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8757869835428966, "lm_q1q2_score": 0.7823487600491446}}
{"text": "theory Padic_Construction\nimports \"HOL-Number_Theory.Residues\" \"HOL-Algebra.RingHom\" \"HOL-Algebra.IntRing\"\nbegin\n\ntype_synonym padic_int = \"nat \\<Rightarrow> int\"\n\nsection  \\<open>Inverse Limit Construction of the $p$-adic Integers\\<close>\n\ntext\\<open>\n  This section formalizes the standard construction of the $p$-adic integers as the inverse\n  limit of the finite rings $\\mathbb{Z} / p^n \\mathbb{Z}$ along the residue maps\n  $\\mathbb{Z} / p^n \\mathbb{Z} \\mapsto \\mathbb{Z} / p^n \\mathbb{Z} $ defined by\n  $x \\mapsto x \\mod p^m$ when $n \\geq m$. This is exposited, for example, in section 7.6 of \n  \\<^cite>\\<open>\"dummit2004abstract\"\\<close>. The other main route for formalization is to first define the\n  $p$-adic absolute value $|\\cdot|_p$ on the rational numbers, and then define the field\n  $\\mathbb{Q}_p$ of $p$-adic numbers as the completion of the rationals under this absolute\n  value. One can then define the ring of $p$-adic integers $\\mathbb{Z}_p$ as the unit ball in \n  $\\mathbb{Q}_p$ using the unique extension of $|\\cdot|_p$. There exist advantages and \n  disadvantages to both approaches. The primary advantage to the absolute value approach is \n  that the construction can be done generically using existing libraries for completions of \n  normed fields. There are difficulties associated with performing such a construction in \n  Isabelle using existing HOL formalizations. The chief issue is that the tools in HOL-Analysis \n  require that a metric space be a type. If one then wanted to construct the fields \n  $\\mathbb{Q}_p$ as metric spaces, one would have to circumvent the apparent dependence on \n  the parameter $p$, as Isabelle does not support dependent types. A workaround to this proposed \n  by José Manuel Rodríguez Caballero on the Isabelle mailing list is to define a typeclass for \n  fields $\\mathbb{Q}_p$ as the completions of the rational numbers with a non-Archimedean absolute \n  value. By Ostrowski's Theorem, any such absolute value must be a $p$-adic absolute value. We can \n  recover the parameter $p$ from a completion under one of these absolute values as the cardinality \n  of the residue field.\n\n  Our approach uses HOL-Algebra, where algebraic structures are constructed as records which carry \n  the data of the underlying carrier set plus other algebraic operations, and assumptions about \n  these structures can be organized into locales. This approach is practical for abstract \n  algebraic reasoning where definitions of structures which are dependent on object-level \n  parameters are ubiquitous. Using this approach, we define $\\mathbb{Z}_p$ directly as an \n  inverse limit of rings, from which $\\mathbb{Q}_p$ can later be defined as the field of fractions.\n\\<close>\n\nsubsection\\<open>Canonical Projection Maps Between Residue Rings\\<close>\n\ndefinition residue :: \"int \\<Rightarrow> int \\<Rightarrow> int\" where \n\"residue n m = m mod n\"\n\nlemma residue_is_hom_0:\n  assumes \"n > 1\"\n  shows \"residue n \\<in> ring_hom \\<Z> (residue_ring n)\" \nproof(rule ring_hom_memI)\n  have R: \"residues n\" \n    by (simp add: assms residues_def) \n  show \"\\<And>x. x \\<in> carrier \\<Z> \\<Longrightarrow> residue n x \\<in> carrier (residue_ring n)\"\n    using assms residue_def residues.mod_in_carrier residues_def by auto \n  show \" \\<And>x y. x \\<in> carrier \\<Z> \\<Longrightarrow> y \\<in> carrier \\<Z> \\<Longrightarrow>\n   residue n (x \\<otimes>\\<^bsub>\\<Z>\\<^esub> y) = residue n x \\<otimes>\\<^bsub>residue_ring n\\<^esub> residue n y\"\n    by (simp add: R residue_def residues.mult_cong) \n  show \"\\<And>x y. x \\<in> carrier \\<Z> \\<Longrightarrow>\n               y \\<in> carrier \\<Z> \\<Longrightarrow>\n         residue n (x \\<oplus>\\<^bsub>\\<Z>\\<^esub> y) = residue n x \\<oplus>\\<^bsub>residue_ring n\\<^esub> residue n y\"\n    by (simp add: R residue_def residues.res_to_cong_simps(1)) \n  show \"residue n \\<one>\\<^bsub>\\<Z>\\<^esub> = \\<one>\\<^bsub>residue_ring n\\<^esub>\" \n    by (simp add: R residue_def residues.res_to_cong_simps(4)) \nqed\n\ntext\\<open>The residue map is a ring homomorphism from $\\mathbb{Z}/m\\mathbb{Z} \\to \\mathbb{Z}/n\\mathbb{Z}$ when n divides m\\<close>\n\nlemma residue_is_hom_1:\n  assumes \"n > 1\"\n  assumes \"m > 1\"\n  assumes \"n dvd m\"\n  shows \"residue n \\<in> ring_hom (residue_ring m) (residue_ring n)\"\nproof(rule ring_hom_memI)\n  have 0: \"residues n\" \n    by (simp add: assms(1) residues_def) \n  have 1: \"residues m\" \n    by (simp add: assms(2) residues_def) \n  show \"\\<And>x. x \\<in> carrier (residue_ring m) \\<Longrightarrow> residue n x \\<in> carrier (residue_ring n)\" \n    using assms(1) residue_def residue_ring_def by auto \n  show \"\\<And>x y. x \\<in> carrier (residue_ring m) \\<Longrightarrow>\n               y \\<in> carrier (residue_ring m) \\<Longrightarrow> \n          residue n (x \\<otimes>\\<^bsub>residue_ring m\\<^esub> y) = residue n x \\<otimes>\\<^bsub>residue_ring n\\<^esub> residue n y\"\n    using 0 1 assms by (metis mod_mod_cancel residue_def residues.mult_cong residues.res_mult_eq) \n  show \"\\<And>x y. x \\<in> carrier (residue_ring m) \n        \\<Longrightarrow> y \\<in> carrier (residue_ring m) \n        \\<Longrightarrow> residue n (x \\<oplus>\\<^bsub>residue_ring m\\<^esub> y) = residue n x \\<oplus>\\<^bsub>residue_ring n\\<^esub> residue n y\"\n    using 0 1 assms by (metis mod_mod_cancel residue_def residues.add_cong residues.res_add_eq) \n  show \"residue n \\<one>\\<^bsub>residue_ring m\\<^esub> = \\<one>\\<^bsub>residue_ring n\\<^esub>\" \n    by (simp add: assms(1) residue_def residue_ring_def) \nqed\n\nlemma residue_id:\n  assumes \"x \\<in> carrier (residue_ring n)\"\n  assumes \"n \\<ge>0\"\n  shows \"residue n x = x\"\nproof(cases \"n=0\")\n  case True\n  then show ?thesis \n    by (simp add: residue_def) \nnext\n  case False \n  have 0: \"x \\<ge>0\"  \n    using assms(1)  by (simp add: residue_ring_def)\n  have 1: \"x < n\" \n    using assms(1) residue_ring_def by auto \n  have \"x mod n = x\" \n    using 0 1 by simp \n  then show ?thesis \n    using residue_def by auto\nqed\n\ntext\\<open>\n  The residue map is a ring homomorphism from\n  $\\mathbb{Z}/p^n\\mathbb{Z} \\to \\mathbb{Z}/p^m\\mathbb{Z}$ when $n \\geq m$:\n\\<close>\n\nlemma residue_hom_p:\n  assumes \"(n::nat) \\<ge> m\"\n  assumes \"m >0\"\n  assumes \"prime (p::int)\"\n  shows \"residue (p^m) \\<in> ring_hom (residue_ring (p^n)) (residue_ring (p^m))\"\nproof(rule residue_is_hom_1)\n  show \" 1 < p^n\" using assms  \n    using prime_gt_1_int by auto\n  show \"1 < p^m\" \n    by (simp add: assms(2) assms(3) prime_gt_1_int)\n  show \"p ^ m dvd p ^ n\" using assms(1) \n    by (simp add: dvd_power_le) \nqed\n\nsubsection\\<open>Defining the Set of $p$-adic Integers\\<close>\n\ntext\\<open>\n  The set of $p$-adic integers is the set of all maps $f: \\mathbb{N} \\to \\mathbb{Z}$ which maps\n  $n \\to \\{0,...,p^n -1\\}$ such that $f m \\mod p^{n} = f n$ when $m \\geq n$. A p-adic integer $x$\n  consists of the data of a residue map $x \\mapsto x\\mod p^n$ which commutes with further reduction\n  $\\mod p^m$. This formalization is specialized to just the $p$-adics, but this definition would\n  work essentially as-is for any family of rings and residue maps indexed by a partially\n  ordered type.\n\\<close>\n\ndefinition padic_set :: \"int \\<Rightarrow> padic_int set\" where\n\"padic_set p = {f::nat \\<Rightarrow> int .(\\<forall> m::nat. (f m) \\<in> carrier (residue_ring (p^m)))\n                  \n                   \\<and>(\\<forall>(n::nat) (m::nat). n > m \\<longrightarrow> residue (p^m) (f n) = (f m)) }\"\n\n\nlemma padic_set_res_closed:\n  assumes \"f \\<in> padic_set p\"\n  shows \"(f m) \\<in> (carrier (residue_ring (p^m)))\" \n  using assms padic_set_def by auto  \n\nlemma padic_set_res_coherent:\n  assumes \"f \\<in> padic_set p\"\n  assumes \"n \\<ge> m\"\n  assumes \"prime p\"\n  shows \"residue (p^m) (f n) = (f m)\"\nproof(cases \"n=m\")\n  case True\n  have \"(f m) \\<in> carrier (residue_ring (p^m))\" \n    using assms padic_set_res_closed by blast \n  then have \"residue (p^m) (f m) = (f m)\" \n    by (simp add: residue_def residue_ring_def) \n  then show ?thesis \n    using True by blast \nnext\n  case False\n  then show ?thesis\n    using assms(1) assms(2) padic_set_def by auto \nqed\n\ntext\\<open>\n  A consequence of this formalization is that each $p$-adic number is trivially\n  defined to take a value of $0$ at $0$:\n\\<close>\n\nlemma padic_set_zero_res:\n  assumes \"prime p\"\n  assumes \"f \\<in> (padic_set p)\"\n  shows \"f 0 = 0\"\nproof-\n  have \"f 0 \\<in> carrier (residue_ring 1)\" \n    using assms(1) padic_set_res_closed \n    by (metis assms(2)  power_0) \n  then show ?thesis \n    using residue_ring_def  by simp \nqed\n\nlemma padic_set_memI:\n  fixes f :: \"padic_int\"\n  assumes \"\\<And>m. (f m) \\<in> (carrier (residue_ring (p^m)))\"\n  assumes \"(\\<And>(m::nat) n. (n > m \\<Longrightarrow> (residue (p^m) (f n) = (f m))))\"\n  shows \"f \\<in> padic_set (p::int)\"\n  by (simp add: assms(1) assms(2) padic_set_def) \n\nlemma padic_set_memI':\n  fixes f :: \"padic_int\"\n  assumes \"\\<And>m. (f m) \\<in> {0..<p^m}\"\n  assumes \"\\<And>(m::nat) n. n > m \\<Longrightarrow> (f n) mod p^m = (f m)\"\n  shows \"f \\<in> padic_set (p::int)\"\n  apply(rule padic_set_memI)\n  using assms(1) residue_ring_def apply auto[1]\n  by (simp add: assms(2) residue_def)\n\n\nsection\\<open>The standard operations on the $p$-adic integers\\<close>\n\n    (**********************************************************************************************)\n    subsection\\<open>Addition\\<close>\n    (**********************************************************************************************)\n\ntext\\<open>Addition and multiplication are defined componentwise on residue rings:\\<close>\n\ndefinition padic_add :: \"int \\<Rightarrow> padic_int \\<Rightarrow> padic_int \\<Rightarrow> padic_int \" \n  where \"padic_add p f g \\<equiv> (\\<lambda> n. (f n) \\<oplus>\\<^bsub>(residue_ring (p^n))\\<^esub> (g n))\"\n\nlemma padic_add_res:\n\"(padic_add p f g) n = (f n) \\<oplus>\\<^bsub>(residue_ring (p^n))\\<^esub> (g n)\"\n  by (simp add: padic_add_def) \n\ntext\\<open>Definition of the $p$-adic additive unit:\\<close>\n\ndefinition padic_zero :: \"int \\<Rightarrow> padic_int\" where\n\"padic_zero p \\<equiv> (\\<lambda>n. 0)\"\n\nlemma padic_zero_simp:\n\"padic_zero p n = \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n\"padic_zero p n = 0\"\n  apply (simp add: padic_zero_def residue_ring_def) \n  using  padic_zero_def by auto\n\nlemma padic_zero_in_padic_set:\n  assumes \"p > 0\"\n  shows \"padic_zero p \\<in> padic_set p\" \n  apply(rule padic_set_memI)\n  by(auto simp: assms padic_zero_def residue_def residue_ring_def)\n\ntext\\<open>$p$-adic additive inverses:\\<close>\n\ndefinition padic_a_inv :: \"int \\<Rightarrow>  padic_int \\<Rightarrow>  padic_int\" where\n\"padic_a_inv p f \\<equiv> \\<lambda> n. \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\"\n\nlemma padic_a_inv_simp:\n\"padic_a_inv p f n\\<equiv> \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\"\n   by (simp add: padic_a_inv_def) \n\nlemma padic_a_inv_simp':\n  assumes \"prime p\"\n  assumes \"f \\<in> padic_set p\"\n  assumes \"n >0\"\n  shows \"padic_a_inv p f n = (if n=0 then 0 else (- (f n)) mod (p^n))\"\nproof-\n  have \"residues (p^n)\"\n  by (simp add: assms(1) assms(3) prime_gt_1_int residues.intro)  \n  then show ?thesis \n    using residue_ring_def padic_a_inv_def residues.res_neg_eq\n    by auto \nqed\n\ntext\\<open>\n  We show that \\<^const>\\<open>padic_set\\<close> is closed under additive inverses. Note that we have to treat the\n  case of residues at $0$ separately.\n\\<close>\n\nlemma residue_1_prop:\n\"\\<ominus>\\<^bsub>residue_ring 1\\<^esub> \\<zero>\\<^bsub>residue_ring 1\\<^esub> =  \\<zero>\\<^bsub>residue_ring 1\\<^esub>\"\nproof-\n  let ?x = \"\\<zero>\\<^bsub>residue_ring 1\\<^esub>\"\n  let ?y = \"\\<ominus>\\<^bsub>residue_ring 1\\<^esub> \\<zero>\\<^bsub>residue_ring 1\\<^esub>\"\n  let ?G = \"add_monoid (residue_ring 1)\"\n  have P0:\" ?x \\<oplus>\\<^bsub>residue_ring 1\\<^esub> ?x =  ?x\" \n    by (simp add: residue_ring_def) \n  have P1: \"?x \\<in> carrier (residue_ring 1)\" \n    by (simp add: residue_ring_def) \n  have \"?x \\<in> carrier ?G \\<and> ?x \\<otimes>\\<^bsub>?G\\<^esub> ?x = \\<one>\\<^bsub>?G\\<^esub> \\<and> ?x \\<otimes>\\<^bsub>?G\\<^esub> ?x = \\<one>\\<^bsub>?G\\<^esub>\"\n    using P0 P1  by auto \n  then show ?thesis \n    by (simp add: m_inv_def a_inv_def residue_ring_def) \nqed\n\nlemma residue_1_zero:\n  \"residue 1 n = 0\" \n  by (simp add: residue_def) \n\nlemma padic_a_inv_in_padic_set:\n  assumes \"f \\<in> padic_set p\"\n  assumes \"prime (p::int)\"\n  shows \"(padic_a_inv p f) \\<in> padic_set p\"\nproof(rule padic_set_memI)\n  show \"\\<And>m. padic_a_inv p f m \\<in> carrier (residue_ring (p ^ m))\"\n  proof-\n    fix m\n    show \"padic_a_inv p f m \\<in> carrier (residue_ring (p ^ m))\"\n    proof-\n      have P0: \"padic_a_inv p f m = \\<ominus>\\<^bsub>residue_ring (p^m)\\<^esub> (f m)\" \n        using padic_a_inv_def by simp \n      then show ?thesis \n        by (metis (no_types, lifting) assms(1) assms(2) cring.cring_simprules(3) neq0_conv \n            one_less_power padic_set_res_closed padic_set_zero_res power_0 prime_gt_1_int residue_1_prop\n            residue_ring_def residues.cring residues.intro ring.simps(1))\n    qed\n  qed\n  show \"\\<And>m n. m < n \\<Longrightarrow> residue (p ^ m) (padic_a_inv p f n) = padic_a_inv p f m\" \n  proof-\n    fix m n::nat\n    assume \"m < n\"\n    show \"residue (p ^ m) (padic_a_inv p f n) = padic_a_inv p f m\" \n    proof(cases \"m=0\")\n      case True\n      then have 0: \"residue (p ^ m) (padic_a_inv p f n) = 0\" using residue_1_zero \n        by simp\n      have \"f m = 0\" \n        using assms True padic_set_def residue_ring_def padic_set_zero_res \n        by auto       \n      then have 1: \"padic_a_inv p f m = 0\" using residue_1_prop assms\n        by (simp add: True padic_a_inv_def residue_ring_def) \n      then show ?thesis using 0 1\n        by simp \n      next\n        case False\n        have 0: \"f n \\<in> carrier (residue_ring (p^n)) \"\n          using assms(1) padic_set_res_closed by auto\n        have 1: \"padic_a_inv p f n = \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\" using padic_a_inv_def\n          by simp \n        have 2: \"padic_a_inv p f m = \\<ominus>\\<^bsub>residue_ring (p^m)\\<^esub> (f m)\" using  False padic_a_inv_def\n          by simp \n        have 3: \"residue (p ^ m) \\<in> ring_hom (residue_ring (p ^ n)) (residue_ring (p ^ m))\" \n          using residue_hom_p False \\<open>m < n\\<close> assms(2) by auto \n        have 4: \" cring (residue_ring (p ^ n))\" \n          using \\<open>m < n\\<close> assms(2) prime_gt_1_int residues.cring residues.intro by auto \n        have 5: \" cring (residue_ring (p ^ m))\" \n          using False assms(2) prime_gt_1_int residues.cring residues.intro by auto\n        have  \"ring_hom_cring (residue_ring (p ^ n))  (residue_ring (p ^ m)) (residue (p ^ m))\"\n          using 3 4 5 UnivPoly.ring_hom_cringI by blast  \n        then show ?thesis using 0  1 2 ring_hom_cring.hom_a_inv \n          by (metis \\<open>m < n\\<close> assms(1) assms(2) less_imp_le_nat padic_set_res_coherent)          \n      qed\n    qed\n  qed\n\n    (**********************************************************************************************)\n    subsection\\<open>Multiplication\\<close>\n    (**********************************************************************************************)\n\ndefinition padic_mult :: \"int \\<Rightarrow> padic_int \\<Rightarrow> padic_int \\<Rightarrow> padic_int\" \n  where \"padic_mult p f g \\<equiv> (\\<lambda> n. (f n) \\<otimes>\\<^bsub>(residue_ring (p^n))\\<^esub> (g n))\"\n\nlemma padic_mult_res: \n\"(padic_mult p f g) n = (f n) \\<otimes>\\<^bsub>(residue_ring (p^n))\\<^esub> (g n)\"\n  by (simp add: padic_mult_def) \n\ntext\\<open>Definition of the $p$-adic multiplicative unit:\\<close>\n\ndefinition padic_one :: \"int \\<Rightarrow> padic_int\" where\n\"padic_one p \\<equiv> (\\<lambda>n.(if n=0 then 0 else 1))\"\n\nlemma padic_one_simp:\n  assumes \"n >0\"\n  shows \"padic_one p n =  \\<one>\\<^bsub>residue_ring (p^n)\\<^esub>\" \n        \"padic_one p n = 1\"\n  apply (simp add: assms padic_one_def residue_ring_def) \n  using assms padic_one_def by auto\n\nlemma padic_one_in_padic_set:\n  assumes \"prime p\"\n  shows \"padic_one p \\<in> padic_set p\"\n  apply(rule padic_set_memI)\n  by(auto simp : assms padic_one_def prime_gt_1_int residue_def residue_ring_def)\n\nlemma padic_simps:\n\"padic_zero p n = \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\" \n\"padic_a_inv p f n \\<equiv> \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (f n)\"\n\"(padic_mult p f g) n = (f n) \\<otimes>\\<^bsub>(residue_ring (p^n))\\<^esub> (g n)\"\n\"(padic_add p f g) n = (f n) \\<oplus>\\<^bsub>(residue_ring (p^n))\\<^esub> (g n)\"\n\"n>0 \\<Longrightarrow>padic_one p n =  \\<one>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n  apply (simp add: padic_zero_simp) \n  apply (simp add: padic_a_inv_simp)\n  apply (simp add: padic_mult_def)\n  apply (simp add: padic_add_res)  \n  using padic_one_simp by auto\n\nlemma residue_1_mult:\n  assumes \"x \\<in> carrier (residue_ring 1)\"\n  assumes \"y \\<in> carrier (residue_ring 1)\"\n  shows \"x \\<otimes>\\<^bsub>residue_ring 1\\<^esub> y = 0\"\n  by (simp add: residue_ring_def)\n\nlemma padic_mult_in_padic_set:\n  assumes \"f \\<in> (padic_set p)\"\n  assumes \"g \\<in> (padic_set p)\"\n  assumes \"prime p\"\n  shows \"(padic_mult p f g)\\<in> (padic_set p)\"\nproof(rule padic_set_memI')\n  show \"\\<And>m. padic_mult p f g m \\<in> {0..<p ^ m}\"\n    unfolding padic_mult_def \n    using assms residue_ring_def  \n    by (simp add: prime_gt_0_int)\n  show \"\\<And>m n. m < n \\<Longrightarrow> padic_mult p f g n mod p ^ m = padic_mult p f g m\"\n  proof-\n      fix m n::nat\n      assume A: \"m < n\"\n      then show \"padic_mult p f g n mod p ^ m = padic_mult p f g m\"\n      proof(cases \"m=0\")\n        case True\n        then show ?thesis \n          by (metis assms(1) assms(2) mod_by_1 padic_mult_def padic_set_res_closed power_0 residue_1_mult)\n      next\n        case False       \n        have 0:\"residue (p ^ m)  \\<in> ring_hom (residue_ring (p^n)) (residue_ring (p^m))\"\n          using A residue_hom_p assms  False by auto  \n        have 1:\"f n \\<in> carrier (residue_ring (p^n))\" \n          using assms(1) padic_set_res_closed by auto \n        have 2:\"g n \\<in> carrier (residue_ring (p^n))\" \n          using assms(2) padic_set_res_closed by auto \n        have 3: \"residue (p^m) (f n \\<otimes>\\<^bsub>residue_ring (p^n)\\<^esub> g n) \n                    = f m \\<otimes>\\<^bsub>residue_ring (p^m)\\<^esub> g m\" \n          using  \"0\" \"1\" \"2\" A assms(1) assms(2) assms(3) less_imp_le of_nat_power padic_set_res_coherent \n            by (simp add: assms(2) ring_hom_mult)\n        then show ?thesis\n          using ring_hom_mult padic_simps[simp] residue_def\n          by auto          \n        qed\n  qed\nqed\n\nsection\\<open>The $p$-adic Valuation\\<close>\n\ntext\\<open>This section defines the integer-valued $p$-adic valuation. Maps $0$ to $-1$ for now, otherwise is correct. We want the valuation to be integer-valued, but in practice we know it will always be positive. When we extend the valuation from the $p$-adic integers to the $p$-adic field we will have elements of negative valuation. \\<close>\n\ndefinition padic_val :: \"int \\<Rightarrow>  padic_int \\<Rightarrow> int\"  where\n\"padic_val p f \\<equiv> if (f = padic_zero p) then -1 else int (LEAST k::nat. (f (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\"\n\ntext\\<open>Characterization of $padic\\_val$ on nonzero elements\\<close>\n\nlemma val_of_nonzero:\n  assumes \"f \\<in> padic_set p\"\n  assumes \"f \\<noteq> padic_zero p\"\n  assumes \"prime p\"\n  shows \"f (nat (padic_val p f) + 1) \\<noteq>  \\<zero>\\<^bsub>residue_ring (p^((nat (padic_val p f) + 1)))\\<^esub>\"\n        \"f (nat (padic_val p f)) =  \\<zero>\\<^bsub>residue_ring (p^((nat (padic_val p f))))\\<^esub>\"\n        \"f (nat (padic_val p f) + 1) \\<noteq> 0\"\n        \"f (nat (padic_val p f)) =  0\"\nproof-\n  let ?vf = \"padic_val p f\"\n  have 0: \"?vf =int (LEAST k::nat. (f (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\"\n    using assms(2) padic_val_def by auto    \n  have 1: \"(\\<exists> k::nat. (f (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\"\n    proof-\n      obtain k where 1: \"(f k) \\<noteq> (padic_zero p k)\"\n        using assms(2) by (meson ext) \n      have 2: \"k \\<noteq> 0\" \n      proof\n        assume \"k=0\"\n        then have \"f k = 0\"\n          using assms padic_set_zero_res by blast \n        then show False \n          using padic_zero_def 1 by simp \n      qed\n        then obtain m where \"k = Suc m\"\n      by (meson lessI less_Suc_eq_0_disj)\n    then have \"(f (Suc m)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc m))\\<^esub>\" \n      using \"1\" padic_zero_simp by simp    \n    then show ?thesis \n      by auto\n  qed\n  then have \"(f (Suc (nat ?vf))) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc (nat ?vf)))\\<^esub>\" \n    using 0 by (metis (mono_tags, lifting) LeastI_ex nat_int) \n  then show C0: \"f (nat (padic_val p f) + 1) \\<noteq>  \\<zero>\\<^bsub>residue_ring (p^((nat (padic_val p f) + 1)))\\<^esub>\" \n    using 0 1 by simp\n  show C1: \"f (nat (padic_val p f)) =  \\<zero>\\<^bsub>residue_ring (p^((nat (padic_val p f))))\\<^esub>\"\n  proof(cases \"(padic_val p f) = 0\")\n    case True\n    then show ?thesis \n      using assms(1) assms(3) padic_set_zero_res residue_ring_def by auto \n  next\n    case False \n    have \"\\<not> f (nat (padic_val p f)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p ^ nat (padic_val p f))\\<^esub>\"\n    proof\n      assume \"f (nat (padic_val p f)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p ^ nat (padic_val p f))\\<^esub>\"\n      obtain k where \" (Suc k) = (nat (padic_val p f))\" using False \n        using \"0\" gr0_conv_Suc by auto\n      then have \"?vf  \\<noteq> int (LEAST k::nat. (f (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\"\n        using False by (metis (mono_tags, lifting) Least_le \n          \\<open>f (nat (padic_val p f)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p ^ nat (padic_val p f))\\<^esub>\\<close>\n            add_le_same_cancel2 nat_int not_one_le_zero plus_1_eq_Suc)\n      then show False  using \"0\" by blast\n    qed    \n    then show \"f (nat (padic_val p f)) = \\<zero>\\<^bsub>residue_ring (p ^ nat (padic_val p f))\\<^esub>\" by auto\n  qed\n  show  \"f (nat (padic_val p f) + 1) \\<noteq> 0\"\n    using C0  residue_ring_def \n    by auto \n  show  \"f (nat (padic_val p f)) =  0\"\n    by (simp add: C1 residue_ring_def) \nqed\n\ntext\\<open>If $x \\mod p^{n+1} \\neq 0$, then $n \\geq val x$.\\<close>\n\nlemma below_val_zero:\n  assumes \"prime p\"\n  assumes \"x \\<in> (padic_set p)\"\n  assumes \"x (Suc n) \\<noteq>  \\<zero>\\<^bsub>residue_ring (p^(Suc n))\\<^esub>\"\n  shows  \"int n \\<ge> (padic_val p x )\"\nproof(cases \"x = padic_zero p\")\n  case True\n  then show  ?thesis  \n    using assms(3) padic_zero_simp by blast \nnext\n  case False\n  then have \"padic_val p x = int (LEAST k::nat. x (Suc k) \\<noteq> \\<zero>\\<^bsub>residue_ring (p ^ Suc k)\\<^esub>)\"\n    using padic_val_def by auto  \n  then show \"of_nat n \\<ge> (padic_val p x )\"\n    by (metis (mono_tags, lifting) Least_le assms(3) nat_int nat_le_iff)\nqed\n\ntext\\<open>If $n < val x$ then $x \\mod p^n = 0$:\\<close>\n\nlemma  zero_below_val:\n  assumes \"prime p\"\n  assumes \"x \\<in> padic_set p\"\n  assumes \"n \\<le> padic_val p x\"\n  shows  \"x n =  \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n         \"x n = 0\"\nproof-\n show \"x n = \\<zero>\\<^bsub>residue_ring (p ^ n)\\<^esub>\"\n proof(cases \"n=0\")\n  case True\n  then have  \"x 0 \\<in>carrier (residue_ring (p^0))\" \n    using assms(2) padic_set_res_closed  by blast\n  then show ?thesis \n    by (simp add: True residue_ring_def) \n  next\n    case False \n    show ?thesis \n    proof(cases \"x = padic_zero p\")\n      case True \n      then show ?thesis \n        by (simp add: padic_zero_simp)\n    next\n      case F: False\n      then have A: \"padic_val p x = int (LEAST k::nat. (x (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\" \n        using padic_val_def by auto\n      have \"\\<not> (x n) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n      proof\n        assume \"(x n) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n        obtain k where \"n = Suc k\" \n          using False old.nat.exhaust by auto\n        then have \"k \\<ge> padic_val p x\" using A \n          using \\<open>x n \\<noteq> \\<zero>\\<^bsub>residue_ring (p ^ n)\\<^esub>\\<close> assms(1) assms(2) below_val_zero by blast          \n        then have \"n > padic_val p x\" \n          using \\<open>n = Suc k\\<close> by linarith\n        then show False using assms(3) \n          by linarith\n      qed\n      then show ?thesis \n        by simp\n    qed\n  qed\n  show \"x n = 0\"\n    by (simp add: \\<open>x n = \\<zero>\\<^bsub>residue_ring (p ^ n)\\<^esub>\\<close> residue_ring_def) \nqed\n\ntext\\<open>Zero is the only element with valuation equal to $-1$:\\<close>\n\nlemma val_zero:\n assumes P: \"f \\<in> (padic_set p)\"   \n shows \"padic_val p f = -1 \\<longleftrightarrow>  (f = (padic_zero p))\"\nproof\n  show \"padic_val p f = -1 \\<Longrightarrow>  (f = (padic_zero p))\"\n  proof\n    assume A:\"padic_val p f = -1\" \n    fix k\n    show \"f k = padic_zero p k\" \n    proof-\n      have  \"f k \\<noteq> padic_zero p k \\<Longrightarrow> False\"\n      proof-\n        assume A0: \" f k \\<noteq> padic_zero p k\"\n        have False\n        proof-\n          have \"f 0 \\<in> carrier (residue_ring 1)\" using P padic_set_def \n            by (metis (no_types, lifting) mem_Collect_eq power_0) \n          then have \"f 0 = \\<zero>\\<^bsub>residue_ring (p^0)\\<^esub>\"  \n            by (simp add: residue_ring_def) \n          then have \"k>0\" \n            using A0 gr0I padic_zero_def \n            by (metis padic_zero_simp)    \n          then have \"(LEAST k. 0 < k \\<and> f (Suc k) \\<noteq> padic_zero p (Suc k)) \\<ge>0 \" \n            by simp\n          then have \"padic_val p f \\<ge>0\" \n            using A0 padic_val_def by auto \n          then show ?thesis  using A0 by (simp add: A)  \n        qed\n        then show ?thesis by blast\n      qed\n      then show ?thesis \n        by blast\n    qed\n  qed\n  assume B: \"f = padic_zero p\"\n  then show \"padic_val p f = -1\" \n  using padic_val_def by simp \nqed\n\ntext\\<open>\n  The valuation turns multiplication into integer addition on nonzero elements. Note that this i\n  the first instance where we need to explicity use the fact that $p$ is a prime.\n\\<close>\n\nlemma val_prod:\n  assumes \"prime p\"\n  assumes \"f \\<in> (padic_set p)\" \n  assumes \"g \\<in> (padic_set p)\"\n  assumes \"f \\<noteq> padic_zero p\"\n  assumes \"g \\<noteq> padic_zero p\"\n  shows \"padic_val p (padic_mult p f g) = padic_val p f + padic_val p g\"\nproof-\n  let ?vp = \"padic_val p (padic_mult p f g)\"\n  let ?vf = \"padic_val p f\"\n  let ?vg = \"padic_val p g\"\n  have 0: \"f (nat ?vf + 1) \\<noteq>  \\<zero>\\<^bsub>residue_ring (p^(nat ?vf + 1))\\<^esub>\" \n    using assms(2) assms(4) val_of_nonzero  assms(1) by blast \n  have 1: \"g (nat ?vg + 1) \\<noteq>  \\<zero>\\<^bsub>residue_ring (p^(nat ?vg + 1))\\<^esub>\" \n    using assms(3) assms(5) val_of_nonzero assms(1) by blast \n  have 2: \"f (nat ?vf) =  \\<zero>\\<^bsub>residue_ring (p^(nat ?vf))\\<^esub>\" \n    using assms(1) assms(2) assms(4) val_of_nonzero(2) by blast \n  have 3: \"g (nat ?vg) =  \\<zero>\\<^bsub>residue_ring (p^(nat ?vg))\\<^esub>\" \n    using assms(1) assms(3) assms(5) val_of_nonzero(2) by blast\n  let ?nm = \"((padic_mult p f g) (Suc (nat (?vf + ?vg))))\"    \n  let ?n = \"(f (Suc (nat (?vf + ?vg))))\"    \n  let ?m = \"(g (Suc (nat (?vf + ?vg))))\"  \n  have A: \"?nm = ?n \\<otimes>\\<^bsub>residue_ring (p^((Suc (nat (?vf + ?vg))))) \\<^esub> ?m\" \n    using padic_mult_def  by simp \n  have 5: \"f (nat ?vf + 1) = residue (p^(nat ?vf + 1)) ?n\" \n  proof-\n    have \"(Suc (nat (?vf + ?vg))) \\<ge> (nat ?vf + 1)\" \n      by (simp add: assms(5) padic_val_def)\n    then have \"f (nat ?vf + 1) =  residue (p^(nat ?vf + 1)) (f (Suc (nat (?vf + ?vg))))\" \n      using assms(1) assms(2) padic_set_res_coherent by presburger\n    then show ?thesis by auto \n  qed\n  have 6: \"f (nat ?vf) = residue (p^(nat ?vf)) ?n\" \n   using add.commute assms(1) assms(2) assms(5) int_nat_eq nat_int \n        nat_le_iff not_less_eq_eq padic_set_res_coherent padic_val_def plus_1_eq_Suc  by auto \n  have 7: \"g (nat ?vg + 1) = residue (p^(nat ?vg + 1)) ?m\"  \n  proof-\n    have \"(Suc (nat (?vf + ?vg))) \\<ge> (nat ?vg + 1)\" \n      by (simp add: assms(4) padic_val_def)\n    then have \"g (nat ?vg + 1) =  residue (p^(nat ?vg + 1)) (g (Suc (nat (?vf + ?vg))))\" \n      using assms(1) assms(3) padic_set_res_coherent by presburger\n    then show ?thesis by auto \n  qed\n  have 8: \"g (nat ?vg) = residue (p^(nat ?vg)) ?m\"\n  proof-\n    have \"(Suc (nat (?vf + ?vg))) \\<ge> (nat ?vg)\" \n      by (simp add: assms(4) padic_val_def)\n    then have \"g (nat ?vg) =  residue (p^(nat ?vg)) (g (Suc (nat (?vf + ?vg))))\" \n      using assms(1) assms(3) padic_set_res_coherent by presburger\n    then show ?thesis by auto \n  qed \n  have 9: \"f (nat ?vf) = 0\" \n    by (simp add: \"2\" residue_ring_def) \n  have 10: \"g (nat ?vg) = 0\" \n    by (simp add: \"3\" residue_ring_def) \n  have 11: \"f (nat ?vf + 1) \\<noteq> 0\" \n    using \"0\" residue_ring_def by auto \n  have 12: \"g (nat ?vg + 1) \\<noteq>0\" \n    using \"1\" residue_ring_def by auto \n  have 13:\"\\<exists>i. ?n = i*p^(nat ?vf) \\<and> \\<not> p dvd (nat i)\" \n  proof-\n    have  \"residue (p^(nat ?vf)) (?n) = f (nat ?vf)\" \n      by (simp add: \"6\") \n    then have P0: \"residue (p^(nat ?vf)) (?n) = 0\" \n      using \"9\" by linarith \n    have \"residue (p^(nat ?vf + 1)) (?n) = f (nat ?vf + 1)\" \n      using \"5\" by linarith \n    then have P1: \"residue (p^(nat ?vf + 1)) (?n) \\<noteq> 0\"\n      using \"11\" by linarith \n    have P2: \"?n mod (p^(nat ?vf)) = 0\" \n      using P0 residue_def by auto \n    have P3: \"?n mod (p^(nat ?vf + 1)) \\<noteq>  0\" \n      using P1 residue_def by auto \n    have \"p^(nat ?vf) dvd ?n\" \n      using P2 by auto \n    then obtain i where A0:\"?n = i*(p^(nat ?vf))\" \n      by fastforce \n    have \"?n \\<in> carrier (residue_ring (p^(Suc (nat (?vf + ?vg)))))\" \n      using assms(2) padic_set_res_closed by blast \n    then have \"?n \\<ge>0\" \n      by (simp add: residue_ring_def) \n    then have NN:\"i \\<ge> 0\" \n    proof-\n      have S0:\"?n \\<ge>0\" \n        using \\<open>0 \\<le> f (Suc (nat (padic_val p f + padic_val p g)))\\<close> by blast\n      have S1:\"(p^(nat ?vf)) > 0\" \n        using assms(1) prime_gt_0_int zero_less_power by blast        \n      have \"\\<not> i<0\"\n      proof\n        assume \"i < 0\"\n        then have \"?n < 0\" \n          using S1 A0 by (metis mult.commute times_int_code(1) zmult_zless_mono2)\n        then show False \n          using S0  by linarith\n      qed\n      then show ?thesis by auto \n    qed\n    have A1: \"\\<not> p dvd (nat i)\"\n    proof\n      assume \"p dvd nat i\"\n      then obtain j where \"nat i = j*p\" \n        by fastforce \n      then have \"?n = j*p*(p^(nat ?vf))\" using A0 NN \n        by simp        \n      then show False \n        using P3 by auto \n    qed\n    then show ?thesis \n      using A0 by blast      \n  qed\n  have 14:\"\\<exists> i. ?m = i*p^(nat ?vg) \\<and> \\<not> p dvd (nat i)\"\n  proof-\n    have  \"residue (p^(nat ?vg)) (?m) = g (nat ?vg)\" \n      by (simp add: \"8\") \n    then have P0: \"residue (p^(nat ?vg)) (?m) = 0\" \n      using \"10\" by linarith \n    have \"residue (p^(nat ?vg + 1)) (?m) = g (nat ?vg + 1)\" \n      using \"7\" by auto \n    then have P1: \"residue (p^(nat ?vg + 1)) (?m) \\<noteq> 0\"\n      using \"12\" by linarith \n    have P2: \"?m mod (p^(nat ?vg)) = 0\"\n      using P0 residue_def by auto \n    have P3: \"?m mod (p^(nat ?vg + 1)) \\<noteq>  0\" \n      using P1 residue_def by auto \n    have \"p^(nat ?vg) dvd ?m\" \n      using P2 by auto \n    then obtain i where A0:\"?m = i*(p^(nat ?vg))\" \n      by fastforce \n    have \"?m \\<in> carrier (residue_ring (p^(Suc (nat (?vf + ?vg)))))\" \n      using assms(3) padic_set_res_closed by blast \n    then have S0: \"?m \\<ge>0\" \n      by (simp add: residue_ring_def) \n    then have NN:\"i \\<ge> 0\" \n      using 0 assms(1) prime_gt_0_int[of p] zero_le_mult_iff zero_less_power[of p]\n      by (metis A0 linorder_not_less) \n    have A1: \"\\<not> p dvd (nat i)\"\n    proof\n      assume \"p dvd nat i\"\n      then obtain j where \"nat i = j*p\" \n        by fastforce \n      then have \"?m = j*p*(p^(nat ?vg))\" using A0 NN \n        by (metis int_nat_eq ) \n      then show False \n        using P3 by auto \n    qed\n    then show ?thesis \n      by (metis (no_types, lifting) A0) \n  qed\n  obtain i where I:\"?n = i*p^(nat ?vf) \\<and> \\<not> p dvd (nat i)\" \n    using \"13\" by blast \n  obtain j where J:\"?m = j*p^(nat ?vg) \\<and> \\<not> p dvd (nat j)\"\n    using \"14\" by blast \n  let ?i = \"(p^(Suc (nat (?vf + ?vg))))\"\n  have P:\"?nm mod ?i = ?n*?m mod ?i\"\n  proof-\n    have P1:\"?nm = (?n \\<otimes>\\<^bsub>residue_ring ?i \\<^esub> ?m)\"\n      using A by simp\n    have P2:\"(?n \\<otimes>\\<^bsub>residue_ring ?i \\<^esub> ?m) = (residue ?i (?n)) \\<otimes>\\<^bsub>residue_ring ?i\\<^esub>   (residue ?i (?m))\" \n      using assms(1) assms(2) assms(3) padic_set_res_closed prime_ge_0_int residue_id by presburger      \n    then have P3:\"(?n \\<otimes>\\<^bsub>residue_ring ?i \\<^esub> ?m) = (residue ?i (?n*?m))\" \n      by (metis monoid.simps(1) residue_def residue_ring_def) \n    then show ?thesis \n      by (simp add: P1 residue_def) \n  qed\n  then have 15: \"?nm mod ?i =  i*j*p^((nat ?vf) +(nat ?vg)) mod ?i\"\n    by (simp add: I J mult.assoc mult.left_commute power_add)   \n  have 16: \"\\<not> p dvd (i*j)\" using 13 14\n    using I J assms(1) prime_dvd_mult_iff \n    by (metis dvd_0_right int_nat_eq)     \n  have 17: \"((nat ?vf) +(nat ?vg)) < (Suc (nat (?vf + ?vg)))\" \n    by (simp add: assms(4) assms(5) nat_add_distrib padic_val_def) \n  have 18:\"?nm mod ?i \\<noteq>0\"\n  proof-\n    have A0:\"\\<not>  p^((Suc (nat (?vf + ?vg)))) dvd p^((nat ?vf) +(nat ?vg)) \" \n      using 17 \n      by (metis \"16\" assms(1) dvd_power_iff dvd_trans less_int_code(1) linorder_not_less one_dvd prime_gt_0_int)\n    then have A1: \"p^((nat ?vf) +(nat ?vg)) mod ?i \\<noteq> 0\" \n      using dvd_eq_mod_eq_0 \n      by auto      \n    have \"\\<not>  p^((Suc (nat (?vf + ?vg)))) dvd i*j*p^((nat ?vf) +(nat ?vg)) \"\n      using 16 A0 assms(1) assms(4) assms(5) nat_int_add padic_val_def by auto      \n    then show ?thesis \n      using \"15\" by force\n  qed\n  have 19: \"(?nm mod ?i ) mod (p^(nat ?vf + nat ?vg)) = i*j*p^((nat ?vf) +(nat ?vg)) mod (p^(nat ?vf + nat ?vg))\"\n    using 15 by (simp add: assms(4) assms(5) nat_add_distrib padic_val_def)  \n  have 20: \"?nm mod (p^(nat ?vf + nat ?vg)) = 0\"\n  proof-\n    have \"(?nm mod ?i ) mod (p^(nat ?vf + nat ?vg)) = 0\"\n      using 19 \n      by simp\n    then show ?thesis \n      using \"17\" assms(1) int_nat_eq mod_mod_cancel[of \"p^(nat ?vf + nat ?vg)\" ?i] \n           mod_pos_pos_trivial\n      by (metis le_imp_power_dvd less_imp_le_nat)\n  qed\n  have 21: \"(padic_mult p f g) \\<noteq> padic_zero p\"\n  proof\n    assume \"(padic_mult p f g) =  padic_zero p\"\n    then have \"(padic_mult p f g) (Suc (nat (padic_val p f + padic_val p g))) =  padic_zero p (Suc (nat (padic_val p f + padic_val p g)))\"\n      by simp\n    then have \"?nm  = (padic_zero p (Suc (nat (padic_val p f + padic_val p g))))\"\n      by blast \n    then have \"?nm = 0\"  \n      by (simp add: padic_zero_def)  \n    then show False\n      using \"18\" by auto\n  qed\n  have 22: \"(padic_mult p f g)\\<in> (padic_set p)\" \n    using assms(1) assms(2) assms(3) padic_mult_in_padic_set by blast \n  have 23: \"\\<And> j. j < Suc (nat (padic_val p f + padic_val p g)) \\<Longrightarrow> (padic_mult p f g) j = \\<zero>\\<^bsub>residue_ring (p^j)\\<^esub>\"\n  proof-\n    fix k\n    let ?j = \"Suc (nat (padic_val p f + padic_val p g))\"\n    assume P: \"k < ?j\"\n    show \"(padic_mult p f g) k = \\<zero>\\<^bsub>residue_ring (p^k)\\<^esub>\" \n      proof-\n      have P0: \"(padic_mult p f g) (nat ?vf + nat ?vg) = \\<zero>\\<^bsub>residue_ring (p^(nat ?vf + nat ?vg))\\<^esub>\"\n        proof-\n          let ?k = \"(nat ?vf + nat ?vg)\"\n          have \"((padic_mult p f g) ?k) = residue (p^?k) ((padic_mult p f g) ?k) \" \n            using P 22 padic_set_res_coherent by (simp add: assms(1) prime_gt_0_nat)\n          then have \"((padic_mult p f g) ?k) = residue (p^?k) ?nm\" \n            using \"17\" \"22\" assms(1) padic_set_res_coherent by fastforce \n          then have \"((padic_mult p f g) ?k) = residue (p^?k) ?nm\" \n            by (simp add: residue_def)\n          then have \"((padic_mult p f g) ?k) = residue (p^?k) 0\"  \n            using \"20\" residue_def by auto \n          then show ?thesis \n            by (simp add: residue_def residue_ring_def) \n        qed\n      then show ?thesis \n      proof(cases \"k = (nat ?vf + nat ?vg)\")\n      case True then show ?thesis  \n        using P0 by blast\n    next\n      case B: False\n      then show ?thesis \n      proof(cases \"k=0\")\n        case True\n        then show ?thesis \n          using \"22\" assms(1) padic_set_zero_res residue_ring_def by auto \n      next\n        case C: False \n        then have \"((padic_mult p f g) k) = residue (p^k) ((padic_mult p f g) (nat ?vf + nat ?vg)) \" \n          using B P 22 padic_set_res_coherent by (simp add: assms(1) assms(4) assms(5) padic_val_def prime_gt_0_nat) \n        then have S: \"((padic_mult p f g) k) = residue (p^k) \\<zero>\\<^bsub>residue_ring (p^((nat ?vf + nat ?vg)))\\<^esub>\" \n          by (simp add: P0)\n        have \"residue (p^k) \\<in> ring_hom (residue_ring (p^((nat ?vf + nat ?vg)))) (residue_ring (p^k))\"\n          using B P C residue_hom_p \n          using assms(1) assms(4) assms(5) less_Suc0 nat_int not_less_eq of_nat_power padic_val_def prime_nat_int_transfer by auto \n        then show ?thesis using S \n          using P0 padic_zero_def padic_zero_simp residue_def by auto \n      qed\n    qed\n  qed\nqed\n  have 24: \"(padic_mult p f g) (Suc (nat ?vf + nat ?vg)) \\<noteq> \\<zero>\\<^bsub>residue_ring ((p ^ Suc (nat (padic_val p f + padic_val p g))))\\<^esub>\" \n    by (metis (no_types, lifting) \"18\" A P assms(4) assms(5) monoid.simps(1) nat_int nat_int_add padic_val_def residue_ring_def ring.simps(1)) \n  have 25: \"padic_val p (padic_mult p f g) = int (LEAST k::nat. ((padic_mult p f g) (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\"\n    using padic_val_def 21 by auto \n  have 26:\"(nat (padic_val p f + padic_val p g)) \\<in> {k::nat. ((padic_mult p f g) (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>}\" using 24 \n    using \"18\" assms(1) prime_gt_0_nat \n    by (metis (mono_tags, lifting) mem_Collect_eq mod_0 residue_ring_def ring.simps(1))\n  have 27: \"\\<And> j. j < (nat (padic_val p f + padic_val p g)) \\<Longrightarrow>\n     j \\<notin> {k::nat. ((padic_mult p f g) (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>}\" \n    by (simp add: \"23\") \n  have \"(nat (padic_val p f + padic_val p g)) = (LEAST k::nat. ((padic_mult p f g) (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>) \"\n  proof-\n    obtain P where C0: \"P= (\\<lambda> k. ((padic_mult p f g) (Suc k)) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc k))\\<^esub>)\" \n      by simp\n    obtain x where C1: \"x = (nat (padic_val p f + padic_val p g))\" \n      by blast\n    have C2: \"P x\" \n      using \"26\" C0 C1  by blast\n    have C3:\"\\<And> j. j< x \\<Longrightarrow> \\<not> P j\" \n      using C0 C1 by (simp add: \"23\")\n    have C4: \"\\<And> j. P j \\<Longrightarrow> x \\<le>j\" \n      using C3 le_less_linear by blast\n    have \"x = (LEAST k. P k)\" \n      using C2 C4 Least_equality by auto \n    then show ?thesis using C0 C1 by auto\n  qed\n  then have \"padic_val p (padic_mult p f g) = (nat (padic_val p f + padic_val p g))\" \n    using \"25\" by linarith\n  then show ?thesis \n    by (simp add: assms(4) assms(5) padic_val_def)\n\nqed\n\nsection\\<open>Defining the Ring of $p$-adic Integers:\\<close>\n\ndefinition padic_int :: \"int \\<Rightarrow> padic_int ring\"\n  where \"padic_int p \\<equiv> \\<lparr>carrier = (padic_set p),\n         Group.monoid.mult = (padic_mult p), one = (padic_one p), \n          zero = (padic_zero p), add = (padic_add p)\\<rparr>\"\n\nlemma padic_int_simps:\n \"\\<one>\\<^bsub>padic_int p\\<^esub> = padic_one p\"\n \"\\<zero>\\<^bsub>padic_int p\\<^esub> = padic_zero p\"\n \"(\\<oplus>\\<^bsub>padic_int p\\<^esub>) = padic_add p\"\n \"(\\<otimes>\\<^bsub>padic_int p\\<^esub>) = padic_mult p\"\n \"carrier (padic_int p) = padic_set p\"\n  unfolding padic_int_def by auto \n\nlemma residues_n:\n  assumes \"n \\<noteq> 0\"\n  assumes \"prime p\"\n  shows \"residues (p^n)\" \nproof\n  have \"p > 1\" using assms(2) \n    using prime_gt_1_int by auto\n  then show \" 1 < p ^ n \"  \n    using assms(1) by auto\nqed\n\ntext\\<open>$p$-adic multiplication is associative\\<close>\n\nlemma padic_mult_assoc:\nassumes \"prime p\"\nshows  \"\\<And>x y z.\n       x \\<in> carrier (padic_int p) \\<Longrightarrow>\n       y \\<in> carrier (padic_int p) \\<Longrightarrow> \n       z \\<in> carrier (padic_int p) \\<Longrightarrow>\n       x \\<otimes>\\<^bsub>padic_int p\\<^esub> y \\<otimes>\\<^bsub>padic_int p\\<^esub> z = x \\<otimes>\\<^bsub>padic_int p\\<^esub> (y \\<otimes>\\<^bsub>padic_int p\\<^esub> z)\"\nproof-\n  fix x y z\n  assume Ax: \" x \\<in> carrier (padic_int p)\"\n  assume Ay: \" y \\<in> carrier (padic_int p)\"\n  assume Az: \" z \\<in> carrier (padic_int p)\"\n  show \"x \\<otimes>\\<^bsub>padic_int p\\<^esub> y \\<otimes>\\<^bsub>padic_int p\\<^esub> z = x \\<otimes>\\<^bsub>padic_int p\\<^esub> (y \\<otimes>\\<^bsub>padic_int p\\<^esub> z)\"\n  proof\n    fix n\n    show \"((x \\<otimes>\\<^bsub>padic_int p\\<^esub> y) \\<otimes>\\<^bsub>padic_int p\\<^esub> z) n = (x \\<otimes>\\<^bsub>padic_int p\\<^esub> (y \\<otimes>\\<^bsub>padic_int p\\<^esub> z)) n\"\n    proof(cases \"n=0\") \n      case True\n      then show ?thesis using padic_int_simps\n        by (metis Ax Ay Az assms padic_mult_in_padic_set padic_set_zero_res)        \n    next\n      case False\n      then have \"residues (p^n)\" \n        by (simp add: assms residues_n)\n      then show ?thesis \n        using residues.cring padic_set_res_closed padic_mult_in_padic_set Ax Ay Az padic_mult_res\n        by (simp add: cring.cring_simprules(11) padic_int_def)        \n    qed\n  qed\nqed\n\ntext\\<open>The $p$-adic integers are closed under addition:\\<close>\n\nlemma padic_add_closed:\n  assumes \"prime p\"\n  shows  \"\\<And>x y.\n         x \\<in> carrier (padic_int p) \\<Longrightarrow>\n         y \\<in> carrier (padic_int p) \\<Longrightarrow>\n         x \\<oplus>\\<^bsub>(padic_int p)\\<^esub> y \\<in> carrier (padic_int p)\"\nproof\n  fix x::\"padic_int\"\n  fix y::\"padic_int\"\n  assume Px: \"x \\<in>carrier (padic_int p) \"\n  assume Py: \"y \\<in>carrier (padic_int p)\"\n  show \"x \\<oplus>\\<^bsub>(padic_int p)\\<^esub> y \\<in> carrier (padic_int p)\"\n  proof-\n    let ?f = \"x \\<oplus>\\<^bsub>(padic_int p)\\<^esub> y\"       \n    have 0: \"(\\<forall>(m::nat). (?f m) \\<in> (carrier (residue_ring (p^m))))\"\n    proof fix m\n      have A1 : \"?f m = (x m) \\<oplus>\\<^bsub>(residue_ring (p^m))\\<^esub> (y m)\"\n        by (simp add: padic_int_def padic_add_def)  \n      have A2: \"(x m) \\<in>(carrier (residue_ring (p^m)))\" \n        using Px by (simp add: padic_int_def padic_set_def) \n      have A3: \"(y m) \\<in>(carrier (residue_ring (p^m)))\" \n        using Py by (simp add: padic_int_def padic_set_def) \n      then show \"(?f m) \\<in> (carrier (residue_ring (p^m)))\" \n        using A1 assms of_nat_0_less_iff prime_gt_0_nat residue_ring_def by force  \n    qed\n    have 1: \"(\\<forall>(n::nat) (m::nat). (n > m \\<longrightarrow> (residue (p^m) (?f n) = (?f m))))\" \n    proof \n      fix n::nat\n      show \"(\\<forall>(m::nat). (n > m \\<longrightarrow> (residue (p^m) (?f n) = (?f m))))\" \n      proof\n        fix m::nat\n        show \"(n > m \\<longrightarrow> (residue (p^m) (?f n) = (?f m)))\"\n        proof\n          assume A: \"m < n\"\n          show \"(residue (p^m) (?f n) = (?f m))\"\n          proof(cases \"m = 0\")\n            case True \n            then have A0: \"(residue (p^m) (?f n)) = 0\" \n              by (simp add: residue_1_zero) \n            have A1: \"?f m = 0\" using True \n              by (simp add: padic_add_res padic_int_simps(3) residue_ring_def)              \n            then show ?thesis \n              using A0 by linarith \n          next\n            case False\n            then have  \"m \\<noteq>0\" using A by linarith\n            have D: \"p^n mod p^m = 0\" using A \n              by (simp add: le_imp_power_dvd)\n            let ?LHS = \"residue (p ^ m) ((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) n)\"\n            have A0: \"?LHS = residue (p ^ m) ((x n)\\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub>( y n))\" \n              by (simp add: padic_int_def padic_add_def)  \n            have \"residue (p^m) \\<in> ring_hom (residue_ring ((p^n))) (residue_ring ((p^m)))\"\n              using A False assms residue_hom_p by auto \n            then have \"residue (p ^ m) ((x n)\\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub>( y n)) = (residue (p ^ m) (x n))\\<oplus>\\<^bsub>residue_ring (p^m)\\<^esub>((residue (p ^ m) (y n)))\"  \n              by (metis (no_types, lifting) padic_int_simps(5) Px Py mem_Collect_eq padic_set_def ring_hom_add) \n            then have \"?LHS =(residue (p ^ m) (x n))\\<oplus>\\<^bsub>residue_ring (p^m)\\<^esub>((residue (p ^ m) (y n)))\" \n              using A0 by force \n            then show ?thesis\n              using A Px Py padic_set_def by (simp add: padic_int_def padic_add_def) \n          qed\n        qed\n      qed\n    qed\n    then show ?thesis\n      using \"0\" padic_set_memI padic_int_simps by auto \n  qed\n  then have \"  x \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<in> (padic_set p)\" \n    by(simp add:  padic_int_def)\n  then show \"carrier (padic_int p) \\<subseteq> carrier (padic_int p)\" \n    by blast  \nqed\n\ntext\\<open>$p$-adic addition is associative:\\<close>\n\nlemma padic_add_assoc:\nassumes \"prime p\"\nshows  \" \\<And>x y z.\n       x \\<in> carrier (padic_int p) \\<Longrightarrow>\n       y \\<in> carrier (padic_int p) \\<Longrightarrow> z \\<in> carrier (padic_int p)\n       \\<Longrightarrow> x \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<oplus>\\<^bsub>padic_int p\\<^esub> z = x \\<oplus>\\<^bsub>padic_int p\\<^esub> (y \\<oplus>\\<^bsub>padic_int p\\<^esub> z)\"\nproof-\n  fix x y z\n  assume Ax: \"x \\<in> carrier (padic_int p)\"\n  assume Ay: \"y \\<in> carrier (padic_int p)\"\n  assume Az: \"z \\<in> carrier (padic_int p)\"\n  show \" (x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<oplus>\\<^bsub>padic_int p\\<^esub> z = x \\<oplus>\\<^bsub>padic_int p\\<^esub> (y \\<oplus>\\<^bsub>padic_int p\\<^esub> z)\"\n  proof\n    fix n\n    show \"((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n = (x \\<oplus>\\<^bsub>padic_int p\\<^esub> (y \\<oplus>\\<^bsub>padic_int p\\<^esub> z)) n \"\n    proof-\n      have Ex: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n        using Ax padic_set_def padic_int_simps by auto \n      have Ey: \"(y n) \\<in> carrier (residue_ring (p^n))\" \n        using Ay padic_set_def padic_int_simps by auto \n      have Ez: \"(z n) \\<in> carrier (residue_ring (p^n))\" \n        using Az padic_set_def  padic_int_simps by auto \n      let ?x = \"(x n)\"\n      let ?y = \"(y n)\"\n      let ?z = \"(z n)\"\n      have P1: \"(?x \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ?y) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ?z = (x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ((y \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n)\"\n      proof(cases \"n = 0\")\n        case True\n        then show ?thesis \n          by (simp add: residue_ring_def)\n      next\n        case False\n        then have \"residues (p^n)\" \n          by (simp add: assms residues_n)\n        then show ?thesis \n          using Ex Ey Ez cring.cring_simprules(7) padic_add_res residues.cring  padic_int_simps \n          by fastforce\n      qed\n      have \" ((y n)) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> z n =((y \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n)\"\n        using padic_add_def padic_int_simps by simp \n      then have P0: \"(x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ((y \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n) = ((x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ((y n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> z n))\"\n        using padic_add_def  padic_int_simps by simp \n      have \"((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n = ((x  \\<oplus>\\<^bsub>padic_int p\\<^esub> y) n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> z n\"\n        using padic_add_def padic_int_simps by simp\n      then have  \"((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n =((x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> (y n)) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> z n\"\n        using padic_add_def padic_int_simps by simp \n      then have  \"((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n =((x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ((y n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> z n))\"\n        using Ex Ey Ez P1 P0  by linarith \n      then have  \"((x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n = (x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> ((y \\<oplus>\\<^bsub>padic_int p\\<^esub> z) n)\"\n        using P0 by linarith \n      then show ?thesis by (simp add:  padic_int_def padic_add_def) \n    qed\n  qed\nqed\n\ntext\\<open>$p$-adic addition is commutative:\\<close>\n\nlemma padic_add_comm:\n  assumes \"prime p\"\n  shows \" \\<And>x y. \n          x \\<in> carrier (padic_int p) \\<Longrightarrow> \n          y \\<in> carrier (padic_int p) \\<Longrightarrow> \n          x \\<oplus>\\<^bsub>padic_int p\\<^esub> y = y \\<oplus>\\<^bsub>padic_int p\\<^esub> x\"\nproof-\n  fix x y\n  assume Ax: \"x \\<in> carrier (padic_int p)\" assume Ay:\"y \\<in> carrier (padic_int p)\"\n  show \"x \\<oplus>\\<^bsub>padic_int p\\<^esub> y = y \\<oplus>\\<^bsub>padic_int p\\<^esub> x\"\n  proof fix n\n    show \"(x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) n = (y \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n \" \n    proof(cases \"n=0\")\n      case True\n      then show ?thesis \n        by (metis Ax Ay assms padic_add_def padic_set_zero_res padic_int_simps(3,5)) \n    next\n      case False\n      have LHS0: \"(x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) n = (x n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> (y n)\" \n        by (simp add:  padic_int_simps padic_add_res) \n      have RHS0: \"(y \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = (y n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> (x n)\" \n        by (simp add:  padic_int_simps padic_add_res) \n      have Ex: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n        using Ax padic_set_res_closed  padic_int_simps by auto \n      have Ey: \"(y n) \\<in> carrier (residue_ring (p^n))\" \n        using Ay padic_set_res_closed  padic_int_simps by auto \n      have LHS1: \"(x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) n = ((x n) +(y n)) mod (p^n)\"\n        using LHS0 residue_ring_def by simp\n      have RHS1: \"(y \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = ((y n) +(x n)) mod (p^n)\"\n        using RHS0 residue_ring_def by simp\n      then show ?thesis using LHS1 RHS1 by presburger \n    qed\n  qed\nqed\n\ntext\\<open>$padic\\_zero$ is an additive identity:\\<close>\n\nlemma padic_add_zero:\nassumes \"prime p\"\nshows \"\\<And>x. x \\<in> carrier (padic_int p) \\<Longrightarrow> \\<zero>\\<^bsub>padic_int p\\<^esub> \\<oplus>\\<^bsub>padic_int p\\<^esub> x = x\"\nproof-\n  fix x\n  assume Ax: \"x \\<in> carrier (padic_int p)\"\n  show \" \\<zero>\\<^bsub>padic_int p\\<^esub> \\<oplus>\\<^bsub>padic_int p\\<^esub> x = x \" \n  proof fix n\n    have A: \"(padic_zero p) n = 0\" \n      by (simp add: padic_zero_def) \n    have \"((padic_zero p) \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = x n\" \n      using Ax padic_int_simps(5) padic_set_res_closed residue_ring_def \n      by(auto simp add: padic_zero_def padic_int_simps padic_add_res residue_ring_def)\n    then show \"(\\<zero>\\<^bsub>padic_int p\\<^esub> \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = x n\" \n      by (simp add: padic_int_def)      \n  qed\nqed\n\ntext\\<open>Closure under additive inverses:\\<close>\n\nlemma padic_add_inv:\nassumes \"prime p\"\nshows \"\\<And>x. x \\<in> carrier (padic_int p) \\<Longrightarrow>\n           \\<exists>y\\<in>carrier (padic_int p). y \\<oplus>\\<^bsub>padic_int p\\<^esub> x = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\nproof-\n  fix x\n  assume Ax: \" x \\<in> carrier (padic_int p)\"\n  show \"\\<exists>y\\<in>carrier (padic_int p). y \\<oplus>\\<^bsub>padic_int p\\<^esub> x = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n    proof\n      let ?y = \"(padic_a_inv p) x\"\n      show \"?y \\<oplus>\\<^bsub>padic_int p\\<^esub> x = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n      proof \n        fix n\n        show  \"(?y \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = \\<zero>\\<^bsub>padic_int p\\<^esub> n\" \n        proof(cases \"n=0\")\n          case True\n          then show ?thesis \n            using Ax assms padic_add_closed padic_set_zero_res \n              padic_a_inv_in_padic_set padic_zero_def padic_int_simps by auto \n        next\n          case False \n          have C: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n            using Ax padic_set_res_closed padic_int_simps by auto\n          have R: \"residues (p^n)\" \n            using False  by (simp add: assms residues_n)\n          have \"(?y \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = (?y n) \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> x n\" \n            by (simp add: padic_int_def padic_add_res)\n          then have \"(?y \\<oplus>\\<^bsub>padic_int p\\<^esub> x) n = 0\"\n            using C R residue_ring_def[simp] residues.cring \n            by (metis (no_types, lifting) cring.cring_simprules(9) padic_a_inv_def residues.zero_cong)            \n          then show ?thesis \n            by (simp add: padic_int_def padic_zero_def)\n        qed\n      qed\n    then show \"padic_a_inv p x \\<in> carrier (padic_int p)\" \n      using padic_a_inv_in_padic_set padic_int_simps\n            Ax assms prime_gt_0_nat by auto \n  qed\nqed\n\ntext\\<open>The ring of padic integers forms an abelian group under addition:\\<close>\n\nlemma padic_is_abelian_group:\nassumes \"prime p\"\nshows \"abelian_group (padic_int p)\"\n  proof (rule abelian_groupI)\n    show 0: \"\\<And>x y. x \\<in> carrier (padic_int p) \\<Longrightarrow>\n                y \\<in> carrier (padic_int p) \\<Longrightarrow> \n                x \\<oplus>\\<^bsub>(padic_int p)\\<^esub> y \\<in> carrier (padic_int p)\"\n      using padic_add_closed  by (simp add: assms)\n    show zero: \"\\<zero>\\<^bsub>padic_int p\\<^esub> \\<in> carrier (padic_int p)\" \n      by (metis \"0\" assms padic_add_inv padic_int_simps(5) padic_one_in_padic_set)      \n    show add_assoc: \" \\<And>x y z.\n                      x \\<in> carrier (padic_int p) \\<Longrightarrow>\n                      y \\<in> carrier (padic_int p) \\<Longrightarrow> \n                      z \\<in> carrier (padic_int p) \\<Longrightarrow> \n                             x \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<oplus>\\<^bsub>padic_int p\\<^esub> z \n                           = x \\<oplus>\\<^bsub>padic_int p\\<^esub> (y \\<oplus>\\<^bsub>padic_int p\\<^esub> z)\"\n      using assms padic_add_assoc by auto\n    show comm: \" \\<And>x y. \n                      x \\<in> carrier (padic_int p) \\<Longrightarrow>\n                      y \\<in> carrier (padic_int p) \\<Longrightarrow> \n                      x \\<oplus>\\<^bsub>padic_int p\\<^esub> y = y \\<oplus>\\<^bsub>padic_int p\\<^esub> x\"\n      using assms padic_add_comm by blast\n    show \"\\<And>x. x \\<in> carrier (padic_int p) \\<Longrightarrow> \\<zero>\\<^bsub>padic_int p\\<^esub> \\<oplus>\\<^bsub>padic_int p\\<^esub> x = x\"\n      using assms padic_add_zero by blast\n    show \"\\<And>x. x \\<in> carrier (padic_int p) \\<Longrightarrow> \n          \\<exists>y\\<in>carrier (padic_int p). y \\<oplus>\\<^bsub>padic_int p\\<^esub> x = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n      using assms padic_add_inv by blast\n  qed\n\ntext\\<open>One is a multiplicative identity:\\<close>\n\nlemma padic_one_id:\nassumes \"prime p\"\nassumes \"x \\<in> carrier (padic_int p)\"\nshows  \"\\<one>\\<^bsub>padic_int p\\<^esub> \\<otimes>\\<^bsub>padic_int p\\<^esub> x = x\"\nproof\n  fix n\n  show \"(\\<one>\\<^bsub>padic_int p\\<^esub> \\<otimes>\\<^bsub>padic_int p\\<^esub> x) n = x n \"\n  proof(cases \"n=0\")\n    case True\n    then show ?thesis \n      by (metis padic_int_simps(1,4,5) assms(1) assms(2) padic_mult_in_padic_set padic_one_in_padic_set padic_set_zero_res) \n  next\n    case False\n    then have \"residues (p^n)\" \n      by (simp add: assms(1) residues_n)\n    then show ?thesis \n      using False assms(2) cring.cring_simprules(12) padic_int_simps\n        padic_mult_res padic_one_simp padic_set_res_closed residues.cring by fastforce\n  qed\nqed\n\ntext\\<open>$p$-adic multiplication is commutative:\\<close>\n\nlemma padic_mult_comm:\nassumes \"prime p\"\nassumes \"x \\<in> carrier (padic_int p)\"\nassumes \"y \\<in> carrier (padic_int p)\"\nshows \"x \\<otimes>\\<^bsub>padic_int p\\<^esub> y = y \\<otimes>\\<^bsub>padic_int p\\<^esub> x\"\nproof\n  fix n\n  have Ax: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n    using padic_set_def assms(2) padic_int_simps by auto\n  have Ay: \"(y n) \\<in>carrier (residue_ring (p^n))\"\n    using padic_set_def assms(3) padic_set_res_closed padic_int_simps \n    by blast    \n  show \"(x \\<otimes>\\<^bsub>padic_int p\\<^esub> y) n = (y \\<otimes>\\<^bsub>padic_int p\\<^esub> x) n\"\n  proof(cases \"n=0\")\n    case True\n    then show ?thesis \n      by (metis padic_int_simps(4,5) assms(1) assms(2) assms(3) padic_set_zero_res padic_simps(3)) \n  next\n    case False\n    have LHS0: \"(x \\<otimes>\\<^bsub>padic_int p\\<^esub> y) n = (x n) \\<otimes>\\<^bsub>residue_ring (p^n)\\<^esub> (y n)\" \n      by (simp add: padic_int_def padic_mult_res)       \n    have RHS0: \"(y \\<otimes>\\<^bsub>padic_int p\\<^esub> x) n = (y n) \\<otimes>\\<^bsub>residue_ring (p^n)\\<^esub> (x n)\" \n      by (simp add: padic_int_def padic_mult_res) \n    have Ex: \"(x n) \\<in> carrier (residue_ring (p^n))\" \n      using Ax padic_set_res_closed by auto \n    have Ey: \"(y n) \\<in> carrier (residue_ring (p^n))\" \n      using Ay padic_set_res_closed by auto \n    have LHS1: \"(x \\<otimes>\\<^bsub>padic_int p\\<^esub> y) n = ((x n) *(y n)) mod (p^n)\"\n      using LHS0 \n      by (simp add: residue_ring_def) \n    have RHS1: \"(y \\<otimes>\\<^bsub>padic_int p\\<^esub> x) n = ((y n) *(x n)) mod (p^n)\"\n      using RHS0 \n      by (simp add: residue_ring_def) \n    then show ?thesis using LHS1 RHS1 \n      by (simp add: mult.commute) \n  qed\nqed\n\nlemma padic_is_comm_monoid:\nassumes \"prime p\"\nshows \"Group.comm_monoid (padic_int p)\"\nproof(rule comm_monoidI)\n  show  \"\\<And>x y. \n            x \\<in> carrier (padic_int p) \\<Longrightarrow> \n            y \\<in> carrier (padic_int p) \\<Longrightarrow> \n            x \\<otimes>\\<^bsub>padic_int p\\<^esub> y \\<in> carrier (padic_int p)\"\n    by (simp add: padic_int_def assms padic_mult_in_padic_set) \n  show \"\\<one>\\<^bsub>padic_int p\\<^esub> \\<in> carrier (padic_int p)\" \n    by (metis padic_int_simps(1,5) assms  padic_one_in_padic_set)\n  show \"\\<And>x y z. \n            x \\<in> carrier (padic_int p) \\<Longrightarrow>\n            y \\<in> carrier (padic_int p) \\<Longrightarrow> \n            z \\<in> carrier (padic_int p) \\<Longrightarrow>\n            x \\<otimes>\\<^bsub>padic_int p\\<^esub> y \\<otimes>\\<^bsub>padic_int p\\<^esub> z = x \\<otimes>\\<^bsub>padic_int p\\<^esub> (y \\<otimes>\\<^bsub>padic_int p\\<^esub> z)\"\n    using assms padic_mult_assoc by auto\n  show \"\\<And>x. x \\<in> carrier (padic_int p) \\<Longrightarrow> \\<one>\\<^bsub>padic_int p\\<^esub> \\<otimes>\\<^bsub>padic_int p\\<^esub> x = x\"\n    using assms  padic_one_id by blast \n  show \"\\<And>x y. \n          x \\<in> carrier (padic_int p) \\<Longrightarrow>\n          y \\<in> carrier (padic_int p) \\<Longrightarrow>\n          x \\<otimes>\\<^bsub>padic_int p\\<^esub> y = y \\<otimes>\\<^bsub>padic_int p\\<^esub> x\"\n    using padic_mult_comm  by (simp add: assms)\nqed\n\nlemma padic_int_is_cring:\n  assumes \"prime p\"\n  shows \"cring (padic_int p)\"\nproof (rule cringI)\n  show \"abelian_group (padic_int p)\"\n    by (simp add: assms padic_is_abelian_group)\n  show \"Group.comm_monoid (padic_int p)\"\n    by (simp add: assms padic_is_comm_monoid)\n  show \"\\<And>x y z.\n       x \\<in> carrier (padic_int p) \\<Longrightarrow>\n       y \\<in> carrier (padic_int p) \\<Longrightarrow>\n       z \\<in> carrier (padic_int p) \\<Longrightarrow>\n       (x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<otimes>\\<^bsub>padic_int p\\<^esub> z =\n         x \\<otimes>\\<^bsub>padic_int p\\<^esub> z \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<otimes>\\<^bsub>padic_int p\\<^esub> z \"\n  proof-\n    fix x y z\n    assume Ax: \" x \\<in> carrier (padic_int p)\"\n    assume Ay: \" y \\<in> carrier (padic_int p)\"\n    assume Az: \" z \\<in> carrier (padic_int p)\"\n    show \"(x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<otimes>\\<^bsub>padic_int p\\<^esub> z \n          = x \\<otimes>\\<^bsub>padic_int p\\<^esub> z \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<otimes>\\<^bsub>padic_int p\\<^esub> z\"\n    proof\n      fix n\n      have Ex: \" (x n) \\<in> carrier (residue_ring (p^n))\" \n        using Ax padic_set_def padic_int_simps by auto\n      have Ey: \" (y n) \\<in> carrier (residue_ring (p^n))\" \n        using Ay padic_set_def padic_int_simps by auto\n      have Ez: \" (z n) \\<in> carrier (residue_ring (p^n))\" \n        using Az padic_set_def padic_int_simps by auto\n      show \"( (x \\<oplus>\\<^bsub>padic_int p\\<^esub> y) \\<otimes>\\<^bsub>padic_int p\\<^esub> z) n \n            = (x \\<otimes>\\<^bsub>padic_int p\\<^esub> z \\<oplus>\\<^bsub>padic_int p\\<^esub> y \\<otimes>\\<^bsub>padic_int p\\<^esub> z) n \"\n      proof(cases \"n=0\")\n        case True\n        then show ?thesis \n          by (metis Ax Ay Az assms padic_add_closed padic_int_simps(4) padic_int_simps(5) padic_mult_in_padic_set padic_set_zero_res)                            \n      next\n        case False \n        then have \"residues (p^n)\" \n          by (simp add: assms residues_n)\n        then show ?thesis \n          using Ex Ey Ez cring.cring_simprules(13) padic_add_res padic_int_simps\n            padic_mult_res residues.cring by fastforce \n      qed\n    qed\n  qed\nqed\n\ntext\\<open>The $p$-adic ring has no nontrivial zero divisors. Note that this argument is short because we have proved that the valuation is multiplicative on nonzero elements, which is where the primality assumption is used.\\<close>\n\nlemma padic_no_zero_divisors:\nassumes \"prime p\"\nassumes \"a \\<in> carrier (padic_int p)\"\nassumes \"b \\<in>carrier (padic_int p)\"\nassumes \"a \\<noteq>\\<zero>\\<^bsub>padic_int p\\<^esub> \"\nassumes \"b \\<noteq>\\<zero>\\<^bsub>padic_int p\\<^esub> \"\nshows \"a \\<otimes>\\<^bsub>padic_int p\\<^esub> b \\<noteq> \\<zero>\\<^bsub>padic_int p\\<^esub> \"\nproof\n  assume C: \"a \\<otimes>\\<^bsub>padic_int p\\<^esub> b = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n  show False\n  proof-\n    have 0: \"a = \\<zero>\\<^bsub>padic_int p\\<^esub> \\<or> b = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n    proof(cases \"a = \\<zero>\\<^bsub>padic_int p\\<^esub>\")\n      case True\n      then show ?thesis by auto\n    next\n      case False\n      have \"\\<not> b  \\<noteq>\\<zero>\\<^bsub>padic_int p\\<^esub>\"\n      proof\n        assume \"b \\<noteq> \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n        have \"padic_val p (a \\<otimes>\\<^bsub>padic_int p\\<^esub> b) = (padic_val p a) + (padic_val p b)\" \n          using False assms(1) assms(2) assms(3) assms(5) val_prod padic_int_simps by auto\n          then have \"padic_val p (a \\<otimes>\\<^bsub>padic_int p\\<^esub> b) \\<noteq> -1\" \n          using False \\<open>b \\<noteq> \\<zero>\\<^bsub>padic_int p\\<^esub>\\<close> padic_val_def padic_int_simps by auto\n        then show False \n          using C padic_val_def padic_int_simps by auto      \n        qed\n      then show ?thesis \n        by blast\n    qed\n    show ?thesis \n      using \"0\" assms(4) assms(5) by blast\n  qed\nqed\n\nlemma padic_int_is_domain:\n  assumes \"prime p\"\n  shows \"domain (padic_int p)\"\nproof(rule domainI)\n  show \"cring (padic_int p)\" \n    using padic_int_is_cring assms(1) by auto\n  show \"\\<one>\\<^bsub>padic_int p\\<^esub> \\<noteq> \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n  proof\n    assume \"\\<one>\\<^bsub>padic_int p\\<^esub> = \\<zero>\\<^bsub>padic_int p\\<^esub> \"\n    then have \"(\\<one>\\<^bsub>padic_int p\\<^esub>) 1 = \\<zero>\\<^bsub>padic_int p\\<^esub> 1\" by auto\n    then show False \n      using padic_int_simps(1,2) \n      unfolding padic_one_def padic_zero_def by auto  \n  qed\n  show \"\\<And>a b. a \\<otimes>\\<^bsub>padic_int p\\<^esub> b = \\<zero>\\<^bsub>padic_int p\\<^esub>   \\<Longrightarrow>\n              a \\<in> carrier (padic_int p) \\<Longrightarrow> \n              b \\<in> carrier (padic_int p) \\<Longrightarrow> \n              a = \\<zero>\\<^bsub>padic_int p\\<^esub> \\<or> b = \\<zero>\\<^bsub>padic_int p\\<^esub>\"\n    using assms padic_no_zero_divisors \n    by (meson prime_nat_int_transfer)    \nqed     \n\nsection\\<open>The Ultrametric Inequality:\\<close>\n\nlemma padic_val_ultrametric:\n  assumes \"prime p\"\n  assumes \"a \\<in> carrier (padic_int p) \"\n  assumes \"b \\<in> carrier (padic_int p) \"\n  assumes \"a \\<noteq> \\<zero>\\<^bsub>(padic_int p)\\<^esub>\"\n  assumes \"b \\<noteq> \\<zero>\\<^bsub>(padic_int p)\\<^esub>\"\n  assumes  \"a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b \\<noteq> \\<zero>\\<^bsub>(padic_int p)\\<^esub>\"\n  shows \"padic_val p (a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b) \\<ge> min (padic_val p a) (padic_val p b)\"\nproof-\n  let ?va = \" nat (padic_val p a)\"\n  let ?vb = \"nat (padic_val p b)\"\n  let ?vab = \"nat (padic_val p (a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b))\"\n  have P:\" \\<not> ?vab < min ?va ?vb\"\n  proof\n    assume P0: \"?vab < min ?va ?vb\"\n    then have \"Suc ?vab \\<le> min ?va ?vb\"\n      using Suc_leI by blast\n    have \"(a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b) \\<in> carrier (padic_int p) \" \n      using assms(1) assms(2) assms(3)  padic_add_closed by simp\n    then have C: \"(a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b) (?vab + 1) \\<noteq>  \\<zero>\\<^bsub>residue_ring (p^(?vab + 1))\\<^esub>\" \n      using val_of_nonzero(1) assms(6)\n      by (simp add: padic_int_def val_of_nonzero(1) assms(1)) \n    have S: \"(a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b) (?vab + 1) = (a (?vab + 1)) \\<oplus>\\<^bsub>residue_ring (p^((?vab + 1)))\\<^esub> (b ((?vab + 1)))\"  \n      by (simp add: padic_int_def padic_add_def)\n    have \"int (?vab + 1) \\<le> padic_val p a\" \n      using P0  using Suc_le_eq by auto\n    then have A: \"(a (?vab + 1)) = \\<zero>\\<^bsub>residue_ring (p^((?vab + 1)))\\<^esub> \" \n      using assms(1) assms(2) zero_below_val padic_int_simps residue_ring_def \n      by auto     \n    have \"int (?vab + 1) \\<le> padic_val p b\" \n      using P0  using Suc_le_eq by auto\n    then have B: \"(b (?vab + 1)) = \\<zero>\\<^bsub>residue_ring (p^((?vab + 1)))\\<^esub> \" \n      using assms(1) assms(3) zero_below_val \n      by (metis A \\<open>int (nat (padic_val p (a \\<oplus>\\<^bsub>padic_int p\\<^esub> b)) + 1) \\<le> padic_val p a\\<close> \n          assms(2) padic_int_simps(3,5))      \n    have \"p^(?vab + 1) > 1\" \n      using assms(1) by (metis add.commute plus_1_eq_Suc power_gt1 prime_gt_1_int)\n    then have \"residues (p^(?vab + 1))\" \n      using less_imp_of_nat_less residues.intro by fastforce \n    then have \"(a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b) (?vab + 1) = \\<zero>\\<^bsub>residue_ring (p^((?vab + 1)))\\<^esub> \"\n      using A B by (metis (no_types, lifting) S cring.cring_simprules(2)\n          cring.cring_simprules(8) residues.cring) \n    then show False using C by auto\n  qed\n  have A0: \"(padic_val p a) \\<ge> 0\" \n    using assms(4) padic_val_def by(auto simp: padic_int_def) \n  have A1: \"(padic_val p b) \\<ge> 0\" \n    using assms(5) padic_val_def by(auto simp: padic_int_def) \n  have A2: \"padic_val p (a \\<oplus>\\<^bsub>(padic_int p)\\<^esub> b) \\<ge> 0\" \n    using assms(6) padic_val_def by(auto simp: padic_int_def) \n  show ?thesis using P A0 A1 A2 \n    by linarith \nqed\n\nlemma padic_a_inv:\n  assumes \"prime p\"\n  assumes \"a \\<in> carrier (padic_int p)\"\n  shows \"\\<ominus>\\<^bsub>padic_int p\\<^esub> a = (\\<lambda> n. \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> (a n))\"\nproof\n  fix n\n  show \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a) n = \\<ominus>\\<^bsub>residue_ring (p^n)\\<^esub> a n\" \n  proof(cases \"n=0\")\n    case True\n    then show ?thesis \n      by (metis (no_types, lifting) abelian_group.a_inv_closed assms(1) assms(2) padic_int_simps(5) \n          padic_is_abelian_group padic_set_zero_res power_0 residue_1_prop residue_ring_def ring.simps(1))             \n  next\n    case False\n    then have R: \"residues (p^n)\" \n      by (simp add: assms(1) residues_n)\n    have \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a) \\<oplus>\\<^bsub>padic_int p\\<^esub> a = \\<zero>\\<^bsub>padic_int p\\<^esub>\" \n      by (simp add: abelian_group.l_neg assms(1) assms(2) padic_is_abelian_group)      \n    then have P: \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a) n \\<oplus>\\<^bsub>residue_ring (p^n)\\<^esub> a n = 0\"\n      by (metis padic_add_res padic_int_simps(2) padic_int_simps(3) padic_zero_def)      \n    have Q: \"(a n) \\<in> carrier (residue_ring (p^n))\" \n      using assms(2) padic_set_res_closed by(auto simp: padic_int_def)\n    show ?thesis using R Q residues.cring  \n      by (metis P abelian_group.a_inv_closed abelian_group.minus_equality assms(1) assms(2) \n          padic_int_simps(5) padic_is_abelian_group padic_set_res_closed residues.abelian_group\n          residues.res_zero_eq)                \n  qed\nqed\n\nlemma padic_val_a_inv:\n  assumes \"prime p\"\n  assumes \"a \\<in> carrier (padic_int p)\"\n  shows \"padic_val p a = padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a)\"\nproof(cases \"a = \\<zero>\\<^bsub>padic_int p\\<^esub>\")\n  case True\n  then show ?thesis \n    by (metis abelian_group.a_inv_closed abelian_group.r_neg abelian_groupE(5) assms(1) assms(2) padic_is_abelian_group)    \nnext\n  case False\n  have 0: \"\\<And> n. (a n) = \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub> \\<Longrightarrow> (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) n = \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n    using padic_a_inv \n    by (metis (no_types, lifting) assms(1) assms(2) cring.cring_simprules(22) power_0 residue_1_prop residues.cring residues_n)    \n  have 1: \"\\<And> n. (a n) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub> \\<Longrightarrow> (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) n \\<noteq> \\<zero>\\<^bsub>residue_ring (p^n)\\<^esub>\"\n    using padic_a_inv \n    by (metis (no_types, lifting) abelian_group.a_inv_closed abelian_group.minus_minus assms(1)\n        assms(2) cring.cring_simprules(22) padic_int_simps(5) padic_is_abelian_group padic_set_zero_res\n        residues.cring residues_n)        \n  have A:\"padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) \\<ge> (padic_val p a)\" \n  proof-\n    have \"\\<not> padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) < (padic_val p a)\" \n    proof \n      assume \"padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) < padic_val p a\"\n      let ?n = \"padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a)\"\n      let ?m = \" padic_val p a\"\n      have \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a)  \\<noteq> (padic_zero p)\" \n        by (metis False abelian_group.l_neg assms(1) assms(2) padic_add_zero padic_int_simps(2) padic_is_abelian_group)                      \n      then have P0: \"?n \\<ge>0\" \n        by (simp add: padic_val_def)\n      have P1: \"?m \\<ge>0\" using False \n        using \\<open>0 \\<le> padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a)\\<close> \n          \\<open>padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) < padic_val p a\\<close> by linarith\n      have \"(Suc (nat ?n)) < Suc (nat (padic_val p a))\"\n        using P0 P1  \\<open>padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) < padic_val p a\\<close> by linarith\n      then have \"int (Suc (nat ?n)) \\<le> (padic_val p a)\" \n        using of_nat_less_iff by linarith\n      then have \"a (Suc (nat ?n)) =  \\<zero>\\<^bsub>residue_ring (p ^ ((Suc (nat ?n))))\\<^esub>\" \n        using assms(1) assms(2) zero_below_val residue_ring_def by(auto simp: padic_int_def)\n      then have \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a) (Suc (nat ?n)) =  \\<zero>\\<^bsub>residue_ring (p ^ ((Suc (nat ?n))))\\<^esub>\" \n        using 0 by simp\n      then show False using below_val_zero assms \n        by (metis Suc_eq_plus1 \\<open>\\<ominus>\\<^bsub>padic_int p\\<^esub> a \\<noteq> padic_zero p\\<close> abelian_group.a_inv_closed \n            padic_int_simps(5) padic_is_abelian_group val_of_nonzero(1))                    \n    qed\n    then show ?thesis \n      by linarith\n  qed\n  have B: \"padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) \\<le> (padic_val p a)\" \n  proof-\n   let ?n = \"nat (padic_val p a)\"\n    have \"a (Suc ?n) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc ?n))\\<^esub> \" \n      using False assms(2) val_of_nonzero(1) \n      by (metis padic_int_simps(2,5) Suc_eq_plus1 assms(1)) \n    then have \"(\\<ominus>\\<^bsub>padic_int p\\<^esub> a) (Suc ?n) \\<noteq> \\<zero>\\<^bsub>residue_ring (p^(Suc ?n))\\<^esub> \"\n      using 1  by blast \n    then have  \"padic_val p (\\<ominus>\\<^bsub>padic_int p\\<^esub> a) \\<le> int ?n\"  using assms(1) assms(2) below_val_zero  \n      by (metis padic_int_simps(5) abelian_group.a_inv_closed padic_is_abelian_group) \n    then show ?thesis \n      using False padic_val_def padic_int_simps by auto \n  qed\n  then show ?thesis using A B by auto\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Padic_Ints/Padic_Construction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.8539127548105611, "lm_q1q2_score": 0.7822776858043748}}
{"text": "theory P7 imports Main begin\n\nfun sum :: \"nat list \\<Rightarrow> nat\" where\n\"sum Nil = 0\" |\n\"sum (x # xs) = (x + (sum xs))\"\n\nfun flatten :: \"'a list list \\<Rightarrow> 'a list\" where\n\"flatten Nil = Nil\" |\n\"flatten (xs # xss) = xs @ (flatten xss)\"\n\nlemma \"sum [2::nat, 4, 8] = 14\"\n  by simp\n\nlemma \"flatten [[2::nat, 3], [4, 5], [7, 9]] = [2::nat, 3, 4, 5, 7, 9]\"\n  by simp\n\nlemma \"length (flatten xs) = sum (map length xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma sum_append: \"sum (xs @ ys) = sum xs + sum ys\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma flatten_append[simp]: \"flatten (xs @ ys) = flatten xs @ flatten ys\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"flatten (map rev (rev xs)) = rev (flatten xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"flatten (rev (map rev xs)) = rev (flatten xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"list_all (list_all P) xs = list_all P (flatten xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"flatten (rev xs) = flatten xs\"\n  nitpick\n  oops\n\n\n\nlemma \"sum (rev xs) = sum xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"list_all (\\<lambda>x. x\\<ge>1) xs \\<longrightarrow> length xs \\<le> sum xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nfun list_exists:: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a list) \\<Rightarrow> bool\" where\n\"list_exists P Nil = False\" |\n\"list_exists P (x # xs) = (if (P x) then True else (list_exists P xs))\"\n\nlemma \"list_exists (\\<lambda> n. n < 3) [4::nat, 3, 7] = False\"\n  by simp\n\nlemma \"list_exists (\\<lambda> n. n < 4) [4::nat, 3, 7] = True\"\n  by simp\n\nlemma list_exists_append[simp]: \"list_exists P (xs @ ys) = (list_exists P xs \\<or> list_exists P ys)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"list_exists (list_exists P) xs = list_exists P (flatten xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nfun list_exists2:: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a list) \\<Rightarrow> bool\" where\n\"list_exists2 P xs = (\\<not> list_all (\\<lambda>x. (\\<not> P x)) xs)\"\n\nlemma list_exists_equ: \"list_exists2 P xs = list_exists P xs\"\n  apply (induct xs)\n   apply auto\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7822140740908611}}
{"text": "(*  Title:      HOL/Isar_Examples/Mutilated_Checkerboard.thy\n    Author:     Markus Wenzel, TU Muenchen (Isar document)\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory (original scripts)\n*)\n\nsection \\<open>The Mutilated Checker Board Problem\\<close>\n\ntheory Mutilated_Checkerboard\n  imports MainRLT\nbegin\n\ntext \\<open>\n  The Mutilated Checker Board Problem, formalized inductively. See @{cite\n  \"paulson-mutilated-board\"} for the original tactic script version.\n\\<close>\n\nsubsection \\<open>Tilings\\<close>\n\ninductive_set tiling :: \"'a set set \\<Rightarrow> 'a set set\" for A :: \"'a set set\"\n  where\n    empty: \"{} \\<in> tiling A\"\n  | Un: \"a \\<union> t \\<in> tiling A\" if \"a \\<in> A\" and \"t \\<in> tiling A\" and \"a \\<subseteq> - t\"\n\n\ntext \\<open>The union of two disjoint tilings is a tiling.\\<close>\n\nlemma tiling_Un:\n  assumes \"t \\<in> tiling A\"\n    and \"u \\<in> tiling A\"\n    and \"t \\<inter> u = {}\"\n  shows \"t \\<union> u \\<in> tiling A\"\nproof -\n  let ?T = \"tiling A\"\n  from \\<open>t \\<in> ?T\\<close> and \\<open>t \\<inter> u = {}\\<close>\n  show \"t \\<union> u \\<in> ?T\"\n  proof (induct t)\n    case empty\n    with \\<open>u \\<in> ?T\\<close> show \"{} \\<union> u \\<in> ?T\" by simp\n  next\n    case (Un a t)\n    show \"(a \\<union> t) \\<union> u \\<in> ?T\"\n    proof -\n      have \"a \\<union> (t \\<union> u) \\<in> ?T\"\n        using \\<open>a \\<in> A\\<close>\n      proof (rule tiling.Un)\n        from \\<open>(a \\<union> t) \\<inter> u = {}\\<close> have \"t \\<inter> u = {}\" by blast\n        then show \"t \\<union> u \\<in> ?T\" by (rule Un)\n        from \\<open>a \\<subseteq> - t\\<close> and \\<open>(a \\<union> t) \\<inter> u = {}\\<close>\n        show \"a \\<subseteq> - (t \\<union> u)\" by blast\n      qed\n      also have \"a \\<union> (t \\<union> u) = (a \\<union> t) \\<union> u\"\n        by (simp only: Un_assoc)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Basic properties of ``below''\\<close>\n\ndefinition below :: \"nat \\<Rightarrow> nat set\"\n  where \"below n = {i. i < n}\"\n\nlemma below_less_iff [iff]: \"i \\<in> below k \\<longleftrightarrow> i < k\"\n  by (simp add: below_def)\n\nlemma below_0: \"below 0 = {}\"\n  by (simp add: below_def)\n\nlemma Sigma_Suc1: \"m = n + 1 \\<Longrightarrow> below m \\<times> B = ({n} \\<times> B) \\<union> (below n \\<times> B)\"\n  by (simp add: below_def less_Suc_eq) blast\n\nlemma Sigma_Suc2:\n  \"m = n + 2 \\<Longrightarrow>\n    A \\<times> below m = (A \\<times> {n}) \\<union> (A \\<times> {n + 1}) \\<union> (A \\<times> below n)\"\n  by (auto simp add: below_def)\n\nlemmas Sigma_Suc = Sigma_Suc1 Sigma_Suc2\n\n\nsubsection \\<open>Basic properties of ``evnodd''\\<close>\n\ndefinition evnodd :: \"(nat \\<times> nat) set \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"evnodd A b = A \\<inter> {(i, j). (i + j) mod 2 = b}\"\n\nlemma evnodd_iff: \"(i, j) \\<in> evnodd A b \\<longleftrightarrow> (i, j) \\<in> A  \\<and> (i + j) mod 2 = b\"\n  by (simp add: evnodd_def)\n\nlemma evnodd_subset: \"evnodd A b \\<subseteq> A\"\n  unfolding evnodd_def by (rule Int_lower1)\n\nlemma evnoddD: \"x \\<in> evnodd A b \\<Longrightarrow> x \\<in> A\"\n  by (rule subsetD) (rule evnodd_subset)\n\nlemma evnodd_finite: \"finite A \\<Longrightarrow> finite (evnodd A b)\"\n  by (rule finite_subset) (rule evnodd_subset)\n\nlemma evnodd_Un: \"evnodd (A \\<union> B) b = evnodd A b \\<union> evnodd B b\"\n  unfolding evnodd_def by blast\n\nlemma evnodd_Diff: \"evnodd (A - B) b = evnodd A b - evnodd B b\"\n  unfolding evnodd_def by blast\n\nlemma evnodd_empty: \"evnodd {} b = {}\"\n  by (simp add: evnodd_def)\n\nlemma evnodd_insert: \"evnodd (insert (i, j) C) b =\n    (if (i + j) mod 2 = b\n      then insert (i, j) (evnodd C b) else evnodd C b)\"\n  by (simp add: evnodd_def)\n\n\nsubsection \\<open>Dominoes\\<close>\n\ninductive_set domino :: \"(nat \\<times> nat) set set\"\n  where\n    horiz: \"{(i, j), (i, j + 1)} \\<in> domino\"\n  | vertl: \"{(i, j), (i + 1, j)} \\<in> domino\"\n\nlemma dominoes_tile_row:\n  \"{i} \\<times> below (2 * n) \\<in> tiling domino\"\n  (is \"?B n \\<in> ?T\")\nproof (induct n)\n  case 0\n  show ?case by (simp add: below_0 tiling.empty)\nnext\n  case (Suc n)\n  let ?a = \"{i} \\<times> {2 * n + 1} \\<union> {i} \\<times> {2 * n}\"\n  have \"?B (Suc n) = ?a \\<union> ?B n\"\n    by (auto simp add: Sigma_Suc Un_assoc)\n  also have \"\\<dots> \\<in> ?T\"\n  proof (rule tiling.Un)\n    have \"{(i, 2 * n), (i, 2 * n + 1)} \\<in> domino\"\n      by (rule domino.horiz)\n    also have \"{(i, 2 * n), (i, 2 * n + 1)} = ?a\" by blast\n    finally show \"\\<dots> \\<in> domino\" .\n    show \"?B n \\<in> ?T\" by (rule Suc)\n    show \"?a \\<subseteq> - ?B n\" by blast\n  qed\n  finally show ?case .\nqed\n\nlemma dominoes_tile_matrix:\n  \"below m \\<times> below (2 * n) \\<in> tiling domino\"\n  (is \"?B m \\<in> ?T\")\nproof (induct m)\n  case 0\n  show ?case by (simp add: below_0 tiling.empty)\nnext\n  case (Suc m)\n  let ?t = \"{m} \\<times> below (2 * n)\"\n  have \"?B (Suc m) = ?t \\<union> ?B m\" by (simp add: Sigma_Suc)\n  also have \"\\<dots> \\<in> ?T\"\n  proof (rule tiling_Un)\n    show \"?t \\<in> ?T\" by (rule dominoes_tile_row)\n    show \"?B m \\<in> ?T\" by (rule Suc)\n    show \"?t \\<inter> ?B m = {}\" by blast\n  qed\n  finally show ?case .\nqed\n\nlemma domino_singleton:\n  assumes \"d \\<in> domino\"\n    and \"b < 2\"\n  shows \"\\<exists>i j. evnodd d b = {(i, j)}\"  (is \"?P d\")\n  using assms\nproof induct\n  from \\<open>b < 2\\<close> have b_cases: \"b = 0 \\<or> b = 1\" by arith\n  fix i j\n  note [simp] = evnodd_empty evnodd_insert mod_Suc\n  from b_cases show \"?P {(i, j), (i, j + 1)}\" by rule auto\n  from b_cases show \"?P {(i, j), (i + 1, j)}\" by rule auto\nqed\n\nlemma domino_finite:\n  assumes \"d \\<in> domino\"\n  shows \"finite d\"\n  using assms\nproof induct\n  fix i j :: nat\n  show \"finite {(i, j), (i, j + 1)}\" by (intro finite.intros)\n  show \"finite {(i, j), (i + 1, j)}\" by (intro finite.intros)\nqed\n\n\nsubsection \\<open>Tilings of dominoes\\<close>\n\nlemma tiling_domino_finite:\n  assumes t: \"t \\<in> tiling domino\"  (is \"t \\<in> ?T\")\n  shows \"finite t\"  (is \"?F t\")\n  using t\nproof induct\n  show \"?F {}\" by (rule finite.emptyI)\n  fix a t assume \"?F t\"\n  assume \"a \\<in> domino\"\n  then have \"?F a\" by (rule domino_finite)\n  from this and \\<open>?F t\\<close> show \"?F (a \\<union> t)\" by (rule finite_UnI)\nqed\n\nlemma tiling_domino_01:\n  assumes t: \"t \\<in> tiling domino\"  (is \"t \\<in> ?T\")\n  shows \"card (evnodd t 0) = card (evnodd t 1)\"\n  using t\nproof induct\n  case empty\n  show ?case by (simp add: evnodd_def)\nnext\n  case (Un a t)\n  let ?e = evnodd\n  note hyp = \\<open>card (?e t 0) = card (?e t 1)\\<close>\n    and at = \\<open>a \\<subseteq> - t\\<close>\n  have card_suc: \"card (?e (a \\<union> t) b) = Suc (card (?e t b))\" if \"b < 2\" for b :: nat\n  proof -\n    have \"?e (a \\<union> t) b = ?e a b \\<union> ?e t b\" by (rule evnodd_Un)\n    also obtain i j where e: \"?e a b = {(i, j)}\"\n    proof -\n      from \\<open>a \\<in> domino\\<close> and \\<open>b < 2\\<close>\n      have \"\\<exists>i j. ?e a b = {(i, j)}\" by (rule domino_singleton)\n      then show ?thesis by (blast intro: that)\n    qed\n    also have \"\\<dots> \\<union> ?e t b = insert (i, j) (?e t b)\" by simp\n    also have \"card \\<dots> = Suc (card (?e t b))\"\n    proof (rule card_insert_disjoint)\n      from \\<open>t \\<in> tiling domino\\<close> have \"finite t\"\n        by (rule tiling_domino_finite)\n      then show \"finite (?e t b)\"\n        by (rule evnodd_finite)\n      from e have \"(i, j) \\<in> ?e a b\" by simp\n      with at show \"(i, j) \\<notin> ?e t b\" by (blast dest: evnoddD)\n    qed\n    finally show ?thesis .\n  qed\n  then have \"card (?e (a \\<union> t) 0) = Suc (card (?e t 0))\" by simp\n  also from hyp have \"card (?e t 0) = card (?e t 1)\" .\n  also from card_suc have \"Suc \\<dots> = card (?e (a \\<union> t) 1)\"\n    by simp\n  finally show ?case .\nqed\n\n\nsubsection \\<open>Main theorem\\<close>\n\ndefinition mutilated_board :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"mutilated_board m n =\n    below (2 * (m + 1)) \\<times> below (2 * (n + 1)) - {(0, 0)} - {(2 * m + 1, 2 * n + 1)}\"\n\ntheorem mutil_not_tiling: \"mutilated_board m n \\<notin> tiling domino\"\nproof (unfold mutilated_board_def)\n  let ?T = \"tiling domino\"\n  let ?t = \"below (2 * (m + 1)) \\<times> below (2 * (n + 1))\"\n  let ?t' = \"?t - {(0, 0)}\"\n  let ?t'' = \"?t' - {(2 * m + 1, 2 * n + 1)}\"\n\n  show \"?t'' \\<notin> ?T\"\n  proof\n    have t: \"?t \\<in> ?T\" by (rule dominoes_tile_matrix)\n    assume t'': \"?t'' \\<in> ?T\"\n\n    let ?e = evnodd\n    have fin: \"finite (?e ?t 0)\"\n      by (rule evnodd_finite, rule tiling_domino_finite, rule t)\n\n    note [simp] = evnodd_iff evnodd_empty evnodd_insert evnodd_Diff\n    have \"card (?e ?t'' 0) < card (?e ?t' 0)\"\n    proof -\n      have \"card (?e ?t' 0 - {(2 * m + 1, 2 * n + 1)})\n        < card (?e ?t' 0)\"\n      proof (rule card_Diff1_less)\n        from _ fin show \"finite (?e ?t' 0)\"\n          by (rule finite_subset) auto\n        show \"(2 * m + 1, 2 * n + 1) \\<in> ?e ?t' 0\" by simp\n      qed\n      then show ?thesis by simp\n    qed\n    also have \"\\<dots> < card (?e ?t 0)\"\n    proof -\n      have \"(0, 0) \\<in> ?e ?t 0\" by simp\n      with fin have \"card (?e ?t 0 - {(0, 0)}) < card (?e ?t 0)\"\n        by (rule card_Diff1_less)\n      then show ?thesis by simp\n    qed\n    also from t have \"\\<dots> = card (?e ?t 1)\"\n      by (rule tiling_domino_01)\n    also have \"?e ?t 1 = ?e ?t'' 1\" by simp\n    also from t'' have \"card \\<dots> = card (?e ?t'' 0)\"\n      by (rule tiling_domino_01 [symmetric])\n    finally have \"\\<dots> < \\<dots>\" . then show False ..\n  qed\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Isar_Examples/Mutilated_Checkerboard.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.781842542258268}}
{"text": "(*  Title:      HOL/Metis_Examples/Binary_Tree.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring binary trees.\n*)\n\nsection \\<open>Metis Example Featuring Binary Trees\\<close>\n\ntheory Binary_Tree\nimports Main\nbegin\n\ndeclare [[metis_new_skolem]]\n\ndatatype 'a bt =\n    Lf\n  | Br 'a  \"'a bt\"  \"'a bt\"\n\nprimrec n_nodes :: \"'a bt => nat\" where\n  \"n_nodes Lf = 0\"\n| \"n_nodes (Br a t1 t2) = Suc (n_nodes t1 + n_nodes t2)\"\n\nprimrec n_leaves :: \"'a bt => nat\" where\n  \"n_leaves Lf = Suc 0\"\n| \"n_leaves (Br a t1 t2) = n_leaves t1 + n_leaves t2\"\n\nprimrec depth :: \"'a bt => nat\" where\n  \"depth Lf = 0\"\n| \"depth (Br a t1 t2) = Suc (max (depth t1) (depth t2))\"\n\nprimrec reflect :: \"'a bt => 'a bt\" where\n  \"reflect Lf = Lf\"\n| \"reflect (Br a t1 t2) = Br a (reflect t2) (reflect t1)\"\n\nprimrec bt_map :: \"('a => 'b) => ('a bt => 'b bt)\" where\n  \"bt_map f Lf = Lf\"\n| \"bt_map f (Br a t1 t2) = Br (f a) (bt_map f t1) (bt_map f t2)\"\n\nprimrec preorder :: \"'a bt => 'a list\" where\n  \"preorder Lf = []\"\n| \"preorder (Br a t1 t2) = [a] @ (preorder t1) @ (preorder t2)\"\n\nprimrec inorder :: \"'a bt => 'a list\" where\n  \"inorder Lf = []\"\n| \"inorder (Br a t1 t2) = (inorder t1) @ [a] @ (inorder t2)\"\n\nprimrec postorder :: \"'a bt => 'a list\" where\n  \"postorder Lf = []\"\n| \"postorder (Br a t1 t2) = (postorder t1) @ (postorder t2) @ [a]\"\n\nprimrec append :: \"'a bt => 'a bt => 'a bt\" where\n  \"append Lf t = t\"\n| \"append (Br a t1 t2) t = Br a (append t1 t) (append t2 t)\"\n\ntext \\<open>\\medskip BT simplification\\<close>\n\nlemma n_leaves_reflect: \"n_leaves (reflect t) = n_leaves t\"\nproof (induct t)\n  case Lf thus ?case\n  proof -\n    let \"?p\\<^sub>1 x\\<^sub>1\" = \"x\\<^sub>1 \\<noteq> n_leaves (reflect (Lf::'a bt))\"\n    have \"\\<not> ?p\\<^sub>1 (Suc 0)\" by (metis reflect.simps(1) n_leaves.simps(1))\n    hence \"\\<not> ?p\\<^sub>1 (n_leaves (Lf::'a bt))\" by (metis n_leaves.simps(1))\n    thus \"n_leaves (reflect (Lf::'a bt)) = n_leaves (Lf::'a bt)\" by metis\n  qed\nnext\n  case (Br a t1 t2) thus ?case\n    by (metis n_leaves.simps(2) add.commute reflect.simps(2))\nqed\n\nlemma n_nodes_reflect: \"n_nodes (reflect t) = n_nodes t\"\nproof (induct t)\n  case Lf thus ?case by (metis reflect.simps(1))\nnext\n  case (Br a t1 t2) thus ?case\n    by (metis add.commute n_nodes.simps(2) reflect.simps(2))\nqed\n\nlemma depth_reflect: \"depth (reflect t) = depth t\"\napply (induct t)\n apply (metis depth.simps(1) reflect.simps(1))\nby (metis depth.simps(2) max.commute reflect.simps(2))\n\ntext \\<open>\nThe famous relationship between the numbers of leaves and nodes.\n\\<close>\n\nlemma n_leaves_nodes: \"n_leaves t = Suc (n_nodes t)\"\napply (induct t)\n apply (metis n_leaves.simps(1) n_nodes.simps(1))\nby auto\n\nlemma reflect_reflect_ident: \"reflect (reflect t) = t\"\napply (induct t)\n apply (metis reflect.simps(1))\nproof -\n  fix a :: 'a and t1 :: \"'a bt\" and t2 :: \"'a bt\"\n  assume A1: \"reflect (reflect t1) = t1\"\n  assume A2: \"reflect (reflect t2) = t2\"\n  have \"\\<And>V U. reflect (Br U V (reflect t1)) = Br U t1 (reflect V)\"\n    using A1 by (metis reflect.simps(2))\n  hence \"\\<And>V U. Br U t1 (reflect (reflect V)) = reflect (reflect (Br U t1 V))\"\n    by (metis reflect.simps(2))\n  hence \"\\<And>U. reflect (reflect (Br U t1 t2)) = Br U t1 t2\"\n    using A2 by metis\n  thus \"reflect (reflect (Br a t1 t2)) = Br a t1 t2\" by blast\nqed\n\nlemma bt_map_ident: \"bt_map (%x. x) = (%y. y)\"\napply (rule ext)\napply (induct_tac y)\n apply (metis bt_map.simps(1))\nby (metis bt_map.simps(2))\n\nlemma bt_map_append: \"bt_map f (append t u) = append (bt_map f t) (bt_map f u)\"\napply (induct t)\n apply (metis append.simps(1) bt_map.simps(1))\nby (metis append.simps(2) bt_map.simps(2))\n\nlemma bt_map_compose: \"bt_map (f o g) t = bt_map f (bt_map g t)\"\napply (induct t)\n apply (metis bt_map.simps(1))\nby (metis bt_map.simps(2) o_eq_dest_lhs)\n\nlemma bt_map_reflect: \"bt_map f (reflect t) = reflect (bt_map f t)\"\napply (induct t)\n apply (metis bt_map.simps(1) reflect.simps(1))\nby (metis bt_map.simps(2) reflect.simps(2))\n\nlemma preorder_bt_map: \"preorder (bt_map f t) = map f (preorder t)\"\napply (induct t)\n apply (metis bt_map.simps(1) list.map(1) preorder.simps(1))\nby simp\n\nlemma inorder_bt_map: \"inorder (bt_map f t) = map f (inorder t)\"\nproof (induct t)\n  case Lf thus ?case\n  proof -\n    have \"map f [] = []\" by (metis list.map(1))\n    hence \"map f [] = inorder Lf\" by (metis inorder.simps(1))\n    hence \"inorder (bt_map f Lf) = map f []\" by (metis bt_map.simps(1))\n    thus \"inorder (bt_map f Lf) = map f (inorder Lf)\" by (metis inorder.simps(1))\n  qed\nnext\n  case (Br a t1 t2) thus ?case by simp\nqed\n\nlemma postorder_bt_map: \"postorder (bt_map f t) = map f (postorder t)\"\napply (induct t)\n apply (metis Nil_is_map_conv bt_map.simps(1) postorder.simps(1))\nby simp\n\nlemma depth_bt_map [simp]: \"depth (bt_map f t) = depth t\"\napply (induct t)\n apply (metis bt_map.simps(1) depth.simps(1))\nby simp\n\nlemma n_leaves_bt_map [simp]: \"n_leaves (bt_map f t) = n_leaves t\"\napply (induct t)\n apply (metis bt_map.simps(1) n_leaves.simps(1))\nproof -\n  fix a :: 'b and t1 :: \"'b bt\" and t2 :: \"'b bt\"\n  assume A1: \"n_leaves (bt_map f t1) = n_leaves t1\"\n  assume A2: \"n_leaves (bt_map f t2) = n_leaves t2\"\n  have \"\\<And>V U. n_leaves (Br U (bt_map f t1) V) = n_leaves t1 + n_leaves V\"\n    using A1 by (metis n_leaves.simps(2))\n  hence \"\\<And>V U. n_leaves (bt_map f (Br U t1 V)) = n_leaves t1 + n_leaves (bt_map f V)\"\n    by (metis bt_map.simps(2))\n  hence F1: \"\\<And>U. n_leaves (bt_map f (Br U t1 t2)) = n_leaves t1 + n_leaves t2\"\n    using A2 by metis\n  have \"n_leaves t1 + n_leaves t2 = n_leaves (Br a t1 t2)\"\n    by (metis n_leaves.simps(2))\n  thus \"n_leaves (bt_map f (Br a t1 t2)) = n_leaves (Br a t1 t2)\"\n    using F1 by metis\nqed\n\nlemma preorder_reflect: \"preorder (reflect t) = rev (postorder t)\"\napply (induct t)\n apply (metis Nil_is_rev_conv postorder.simps(1) preorder.simps(1)\n              reflect.simps(1))\napply simp\ndone\n\nlemma inorder_reflect: \"inorder (reflect t) = rev (inorder t)\"\napply (induct t)\n apply (metis Nil_is_rev_conv inorder.simps(1) reflect.simps(1))\nby simp\n(* Slow:\nby (metis append.simps(1) append_eq_append_conv2 inorder.simps(2)\n          reflect.simps(2) rev.simps(2) rev_append)\n*)\n\nlemma postorder_reflect: \"postorder (reflect t) = rev (preorder t)\"\napply (induct t)\n apply (metis Nil_is_rev_conv postorder.simps(1) preorder.simps(1)\n              reflect.simps(1))\nby (metis preorder_reflect reflect_reflect_ident rev_swap)\n\ntext \\<open>\nAnalogues of the standard properties of the append function for lists.\n\\<close>\n\nlemma append_assoc [simp]: \"append (append t1 t2) t3 = append t1 (append t2 t3)\"\napply (induct t1)\n apply (metis append.simps(1))\nby (metis append.simps(2))\n\nlemma append_Lf2 [simp]: \"append t Lf = t\"\napply (induct t)\n apply (metis append.simps(1))\nby (metis append.simps(2))\n\ndeclare max_add_distrib_left [simp]\n\nlemma depth_append [simp]: \"depth (append t1 t2) = depth t1 + depth t2\"\napply (induct t1)\n apply (metis append.simps(1) depth.simps(1) plus_nat.simps(1))\nby simp\n\nlemma n_leaves_append [simp]:\n     \"n_leaves (append t1 t2) = n_leaves t1 * n_leaves t2\"\napply (induct t1)\n apply (metis append.simps(1) n_leaves.simps(1) nat_mult_1 plus_nat.simps(1)\n              Suc_eq_plus1)\nby (simp add: distrib_right)\n\nlemma (*bt_map_append:*)\n     \"bt_map f (append t1 t2) = append (bt_map f t1) (bt_map f t2)\"\napply (induct t1)\n apply (metis append.simps(1) bt_map.simps(1))\nby (metis bt_map_append)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Metis_Examples/Binary_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343393, "lm_q2_score": 0.8962513620489619, "lm_q1q2_score": 0.7818425316583762}}
{"text": "theory Chapter4\nimports \"HOL-IMP.ASM\"\nbegin\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  for r where\nrefl:  \"star r x x\" |\nstep:  \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ntext \\<open>\n\\section*{Chapter 4}\n\n\\exercise\nStart from the data type of binary trees defined earlier:\n\\<close>\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\ntext \\<open>\nAn @{typ \"int tree\"} is ordered if for every @{term \"Node l i r\"} in the tree,\n@{text l} and @{text r} are ordered\nand all values in @{text l} are @{text \"< i\"}\nand all values in @{text r} are @{text \"> i\"}.\nDefine a function that returns the elements in a tree and one\nthe tests if a tree is ordered:\n\\<close>\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\"  where\n\"set Tip = {}\" |\n\"set (Node l v r) = {v}\\<union>(set l)\\<union>(set r)\"\n(* your definition/proof here *)\n\nfun ord :: \"int tree \\<Rightarrow> bool\"  where\n\"ord Tip = True\" |\n\"ord (Node l v r) = ((\\<forall>x\\<in>(set l). x < v) \\<and> (\\<forall>x\\<in>(set r). v < x) \\<and> (ord l) \\<and> (ord r))\"\n\n(* your definition/proof here *)\n\ntext\\<open>\n Hint: use quantifiers.\n\nDefine a function @{text ins} that inserts an element into an ordered @{typ \"int tree\"}\nwhile maintaining the order of the tree. If the element is already in the tree, the\nsame tree should be returned.\n\\<close>\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\"  where\n\"ins i Tip = Node Tip i Tip \" |\n\"ins i (Node l v r) = (if i = v then Node l v r else if i < v then Node (ins i l) v r else Node l v (ins i r))\"\n(* your definition/proof here *)\n\ntext\\<open> Prove correctness of @{const ins}: \\<close>\n\nlemma set_ins: \"set(ins x t) = {x} \\<union> set t\"\n  by(induction x t rule: ins.induct, auto)\n(* your definition/proof here *)\n\ntheorem ord_ins: \"ord t \\<Longrightarrow> ord(ins i t)\"\n  using set_ins by(induction t rule: ins.induct, auto)\n(* your definition/proof here *)\n\n  text\\<open>\n\\endexercise\n\n\\exercise\nFormalize the following definition of palindromes\n\\begin{itemize}\n\\item The empty list and a singleton list are palindromes.\n\\item If @{text xs} is a palindrome, so is @{term \"a # xs @ [a]\"}.\n\\end{itemize}\nas an inductive predicate\n\\<close>\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n  empty: \"palindrome []\" |\n  singleton: \"palindrome [x]\" |\n  cont: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n  \n\n(* your definition/proof here *)\n\ntext \\<open> and prove \\<close>\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  by(induction xs rule: palindrome.induct, auto)\n(* your definition/proof here *)\n\ntext \\<open>\n\\endexercise\n\n\\exercise\nWe could also have defined @{const star} as follows:\n\\<close>\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\ntext \\<open>\nThe single @{text r} step is performer after rather than before the @{text star'}\nsteps. Prove\n\\<close>\n\nlemma star_suc: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  by(induction rule: star.induct, auto simp: star.refl star.step)\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\n  by(induction rule: star'.induct, auto simp: star.refl star_suc)\n(* your definition/proof here *)\n\nlemma star_suc': \"r x y \\<Longrightarrow> star' r y z \\<Longrightarrow> star' r x z\"\n  sorry\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n  by(induction rule:star.induct, auto simp: star'.refl' star_suc')\n(* your definition/proof here *)\n\ntext \\<open>\nYou may need lemmas. Note that rule induction fails\nif the assumption about the inductive predicate\nis not the first assumption.\n\\endexercise\n\n\\exercise\\label{exe:iter}\nAnalogous to @{const star}, give an inductive definition of the @{text n}-fold iteration\nof a relation @{text r}: @{term \"iter r n x y\"} should hold if there are @{text x\\<^sub>0}, \\dots, @{text x\\<^sub>n}\nsuch that @{prop\"x = x\\<^sub>0\"}, @{prop\"x\\<^sub>n = y\"} and @{text\"r x\\<^bsub>i\\<^esub> x\\<^bsub>i+1\\<^esub>\"} for\nall @{prop\"i < n\"}:\n\\<close>\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"iter r _ x x\" |\nstep: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z \"\n(* your definition/proof here *)\n\ntext\\<open>\nCorrect and prove the following claim:\n\\<close>\n\nlemma \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\n  apply(induction rule: star.induct)\n  apply (auto simp: iter.refl iter.step)\n  by (meson iter.step)\n(* your definition/proof here *)\n\ntext \\<open>\n\\endexercise\n\n\\exercise\\label{exe:cfg}\nA context-free grammar can be seen as an inductive definition where each\nnonterminal $A$ is an inductively defined predicate on lists of terminal\nsymbols: $A(w)$ mans that $w$ is in the language generated by $A$.\nFor example, the production $S \\to aSb$ can be viewed as the implication\n@{prop\"S w \\<Longrightarrow> S (a # w @ [b])\"} where @{text a} and @{text b} are terminal symbols,\ni.e., elements of some alphabet. The alphabet can be defined as a datatype:\n\\<close>\n\ndatatype alpha = a | b\n\ntext \\<open>\nIf you think of @{const a} and @{const b} as ``@{text \"(\"}'' and  ``@{text \")\"}'',\nthe following two grammars both generate strings of balanced parentheses\n(where $\\varepsilon$ is the empty word):\n\\[\n\\begin{array}{r@ {\\quad}c@ {\\quad}l}\nS &\\to& \\varepsilon \\quad\\mid\\quad aSb \\quad\\mid\\quad SS \\\\\nT &\\to& \\varepsilon \\quad\\mid\\quad TaTb\n\\end{array}\n\\]\nDefine them as inductive predicates and prove their equivalence:\n\\<close>\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nempty: \"S []\" |\nprod: \"S w \\<Longrightarrow> S (a#w@[b])\" |\nconcat: \"S w \\<Longrightarrow> S v \\<Longrightarrow> S (w@v)\"\n(* your definition/proof here *)\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nempty: \"T []\" |\nprod: \"T w \\<Longrightarrow> T v \\<Longrightarrow> T (w@[a]@v@[b])\"\n(* your definition/proof here *)\n\nlemma TS: \"T w \\<Longrightarrow> S w\"\n  by(induction rule: T.induct, auto simp: S.empty S.prod S.concat)\n(* your definition/proof here *)\n\n\n\nlemma ST: \"S w \\<Longrightarrow> T w\"\n  apply(induction rule: S.induct, simp add: T.empty)\n  using T.empty T.prod apply force\n  sorry\n(* your definition/proof here *)\n\ncorollary SeqT: \"S w \\<longleftrightarrow> T w\"\n  using TS ST by blast\n(* your definition/proof here *)\n\ntext \\<open>\n\\endexercise\n\\<close>\n(* your definition/proof here *)\ntext \\<open>\n\\exercise\nIn Chapter 3 we defined a recursive evaluation function\n@{text \"aval ::\"} @{typ \"aexp \\<Rightarrow> state \\<Rightarrow> val\"}.\nDefine an inductive evaluation predicate and prove that it agrees with\nthe recursive function:\n\\<close>\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nnum: \"aval_rel (N n) s n\" |\nvar: \"s n = v \\<Longrightarrow> aval_rel (V n) s v\" |\nplus: \"v1 + v2 = v \\<Longrightarrow> aval_rel e1 s v1 \\<Longrightarrow> aval_rel e2 s v2 \\<Longrightarrow> aval_rel (Plus e1 e2) s v\"\n(* your definition/proof here *)\n\nlemma aval_rel_aval: \"aval_rel a s v \\<Longrightarrow> aval a s = v\"\n(* your definition/proof here *)\n\nlemma aval_aval_rel: \"aval a s = v \\<Longrightarrow> aval_rel a s v\"\n(* your definition/proof here *)\n\ncorollary \"aval_rel a s v \\<longleftrightarrow> aval a s = v\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider the stack machine from Chapter~3\nand recall the concept of \\concept{stack underflow}\nfrom Exercise~\\ref{exe:stack-underflow}.\nDefine an inductive predicate\n*}\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{*\nsuch that @{text \"ok n is n'\"} means that with any initial stack of length\n@{text n} the instructions @{text \"is\"} can be executed\nwithout stack underflow and that the final stack has length @{text n'}.\n\nUsing the introduction rules for @{const ok},\nprove the following special cases: *}\n\nlemma \"ok 0 [LOAD x] (Suc 0)\"\n(* your definition/proof here *)\n\nlemma \"ok 0 [LOAD x, LOADI v, ADD] (Suc 0)\"\n(* your definition/proof here *)\n\nlemma \"ok (Suc (Suc 0)) [LOAD x, ADD, ADD, LOAD y] (Suc (Suc 0))\"\n(* your definition/proof here *)\n\ntext {* Prove that @{text ok} correctly computes the final stack size: *}\n\nlemma \"\\<lbrakk>ok n is n'; length stk = n\\<rbrakk> \\<Longrightarrow> length (exec is s stk) = n'\"\n(* your definition/proof here *)\n\ntext {*\nLemma @{thm [source] length_Suc_conv} may come in handy.\n\nProve that instruction sequences generated by @{text comp}\ncannot cause stack underflow: \\ @{text \"ok n (comp a) ?\"} \\ for\nsome suitable value of @{text \"?\"}.\n\\endexercise\n*}\n\n\nend\n\n", "meta": {"author": "MaximilianAnzinger", "repo": "semantics2223-exercises", "sha": "938719cbbe0aaf89e133cd7d47e52da6adca8fec", "save_path": "github-repos/isabelle/MaximilianAnzinger-semantics2223-exercises", "path": "github-repos/isabelle/MaximilianAnzinger-semantics2223-exercises/semantics2223-exercises-938719cbbe0aaf89e133cd7d47e52da6adca8fec/general/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.872347368040789, "lm_q2_score": 0.8962513765975758, "lm_q1q2_score": 0.7818425294778293}}
{"text": "(*by Ammer*)\ntheory VEBT_MinMax imports VEBT_Member\nbegin\n\nsection \\<open>The Minimum and Maximum Operation\\<close>\n\nfun vebt_mint :: \"VEBT \\<Rightarrow> nat option\" where\n  \"vebt_mint (Leaf a b) = (if a then Some 0 else if b then Some 1 else None)\"|\n  \"vebt_mint (Node None _ _ _) = None\"|\n  \"vebt_mint (Node (Some (mi,ma)) _ _ _ ) = Some mi\"\n\n\nfun vebt_maxt :: \"VEBT \\<Rightarrow> nat option\" where\n  \"vebt_maxt (Leaf a b) = (if b then Some 1 else if a then Some 0 else None)\"|\n  \"vebt_maxt (Node None _ _ _) = None\"|\n  \"vebt_maxt (Node (Some (mi,ma)) _ _ _ ) = Some ma\"\n\n\ncontext VEBT_internal begin  \n  \nfun option_shift::\"('a\\<Rightarrow>'a\\<Rightarrow>'a) \\<Rightarrow>'a option \\<Rightarrow>'a option\\<Rightarrow> 'a option\" where\n\"option_shift _ None _ = None\"|\n\"option_shift _ _ None = None\"|\n\"option_shift f (Some a) (Some b) = Some (f a b)\"\n\ndefinition power::\"nat option \\<Rightarrow> nat option \\<Rightarrow> nat option\" (infixl\"^\\<^sub>o\" 81) where\n\"power= option_shift (^)\"\n\ndefinition add::\"nat option \\<Rightarrow> nat option \\<Rightarrow> nat option\" (infixl\"+\\<^sub>o\" 79) where\n\"add= option_shift (+)\"\n\ndefinition mul::\"nat option \\<Rightarrow> nat option \\<Rightarrow> nat option\" (infixl\"*\\<^sub>o\" 80) where\n\"mul = option_shift (*)\"\n\nfun option_comp_shift::\"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a option \\<Rightarrow> 'a option \\<Rightarrow> bool\" where\n\"option_comp_shift _ None _ = False\"|\n\"option_comp_shift _ _ None = False\"|\n\"option_comp_shift f (Some x) (Some y) =  f x y\"\n\nfun less::\"nat option \\<Rightarrow> nat option \\<Rightarrow> bool\" (infixl\"<\\<^sub>o\" 80) where\n\"less x y= option_comp_shift (<) x y\"\n\nfun lesseq::\"nat option \\<Rightarrow> nat option \\<Rightarrow> bool\" (infixl\"\\<le>\\<^sub>o\" 80) where\n\"lesseq x y = option_comp_shift (\\<le>) x y\"\n\nfun greater::\"nat option \\<Rightarrow> nat option \\<Rightarrow> bool\" (infixl\">\\<^sub>o\" 80) where\n\"greater x y = option_comp_shift (>) x y\"\n\nlemma add_shift:\"x+y = z \\<longleftrightarrow> Some x +\\<^sub>o Some y = Some z\" \n  by (simp add: add_def)\n\nlemma mul_shift:\"x*y = z \\<longleftrightarrow> Some x *\\<^sub>o Some y = Some z\" by (simp add: mul_def)\n\nlemma power_shift:\"x^y = z \\<longleftrightarrow> Some x ^\\<^sub>o Some y = Some z\" by (simp add: power_def)\n\nlemma less_shift: \"x < y \\<longleftrightarrow> Some x <\\<^sub>o Some y\" by simp\n\nlemma lesseq_shift: \"x \\<le> y \\<longleftrightarrow> Some x \\<le>\\<^sub>o Some y\" by simp\n\nlemma greater_shift: \"x > y \\<longleftrightarrow> Some x >\\<^sub>o Some y\" by simp\n\ndefinition max_in_set :: \"nat set \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"max_in_set xs x \\<longleftrightarrow> (x \\<in> xs \\<and> (\\<forall> y \\<in> xs. y \\<le> x))\"\n\nlemma maxt_member: \"invar_vebt t n \\<Longrightarrow> vebt_maxt t = Some maxi \\<Longrightarrow> vebt_member t maxi\"\nproof(induction t n  arbitrary: maxi rule: invar_vebt.induct)\ncase (1 a b)\n  then show ?case\n    by (metis VEBT_Member.vebt_member.simps(1) vebt_maxt.simps(1) option.distinct(1) option.inject zero_neq_one)\nnext\ncase (2 treeList n summary m deg)\n  then show ?case\n    by simp\nnext\ncase (3 treeList n summary m deg)\n  then show ?case\n    by simp\nnext\n  case (4 treeList n summary m deg mi ma)\n  hence \"deg \\<ge> 2\" \n    by (metis One_nat_def Suc_le_eq add_mono deg_not_0 numeral_2_eq_2 plus_1_eq_Suc)\n  then show ?case\n    by (metis \"4.prems\" VEBT_Member.vebt_member.simps(5) Suc_diff_Suc Suc_pred lessI less_le_trans vebt_maxt.simps(3) numeral_2_eq_2 option.inject zero_less_Suc)\nnext\n  case (5 treeList n summary m deg mi ma)\n  hence \"deg \\<ge> 2\"\n    by (metis Suc_leI le_add2 less_add_same_cancel2 less_le_trans not_less_iff_gr_or_eq not_one_le_zero numeral_2_eq_2 plus_1_eq_Suc set_n_deg_not_0)\n  then show ?case\n    by (metis \"5.prems\" VEBT_Member.vebt_member.simps(5) add_2_eq_Suc le_add_diff_inverse vebt_maxt.simps(3) option.inject)\nqed\n\n\nlemma maxt_corr_help: \"invar_vebt t n \\<Longrightarrow> vebt_maxt t = Some maxi \\<Longrightarrow> vebt_member t x \\<Longrightarrow> maxi \\<ge> x \" \n  by (smt VEBT_Member.vebt_member.simps(1) le_less vebt_maxt.elims member_inv mi_ma_2_deg option.simps(1) option.simps(3) zero_le_one)\n\nlemma maxt_corr_help_empty: \"invar_vebt t n \\<Longrightarrow> vebt_maxt t = None \\<Longrightarrow> set_vebt' t = {}\" \n  by (metis (full_types) VEBT_Member.vebt_member.simps(1) empty_Collect_eq vebt_maxt.elims minNull.simps(4) min_Null_member option.distinct(1) set_vebt'_def)\n\n\ntheorem maxt_corr:assumes \"invar_vebt t n\" and \"vebt_maxt t = Some x\" shows \"max_in_set (set_vebt' t) x\" \n  unfolding set_vebt'_def Max_def max_in_set_def\n  using assms(1) assms(2) maxt_corr_help maxt_member by blast\n\ntheorem maxt_sound:assumes \"invar_vebt t n\" and  \"max_in_set (set_vebt' t) x\" shows \"vebt_maxt t = Some x\"\n  by (metis (no_types, opaque_lifting) assms(1) assms(2) empty_Collect_eq le_less max_in_set_def\n maxt_corr_help maxt_corr_help_empty maxt_member mem_Collect_eq not_le option.exhaust set_vebt'_def)\n\n\ndefinition min_in_set :: \"nat set \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"min_in_set xs x \\<longleftrightarrow> (x \\<in> xs \\<and> (\\<forall> y \\<in> xs. y \\<ge> x))\"\n\nlemma mint_member: \"invar_vebt t n \\<Longrightarrow> vebt_mint t = Some maxi \\<Longrightarrow> vebt_member t maxi\"\nproof(induction t n  arbitrary: maxi rule: invar_vebt.induct)\ncase (1 a b)\n  then show ?case\n    by (metis VEBT_Member.vebt_member.simps(1) vebt_mint.simps(1) option.distinct(1) option.inject zero_neq_one)\nnext\ncase (2 treeList n summary m deg)\n  then show ?case\n    by simp\nnext\ncase (3 treeList n summary m deg)\n  then show ?case\n    by simp\nnext\n  case (4 treeList n summary m deg mi ma)\n  hence \"deg \\<ge> 2\" \n    by (metis One_nat_def Suc_le_eq add_mono deg_not_0 numeral_2_eq_2 plus_1_eq_Suc)\n  then show ?case\n    by (metis \"4.prems\" VEBT_Member.vebt_member.simps(5) One_nat_def Suc_diff_Suc Suc_pred dual_order.strict_trans1 le_imp_less_Suc le_numeral_extra(4) vebt_mint.simps(3) numeral_2_eq_2 option.inject zero_le_one)\nnext\n  case (5 treeList n summary m deg mi ma)\n  hence \"deg \\<ge> 2\"\n    by (metis Suc_leI le_add2 less_add_same_cancel2 less_le_trans not_less_iff_gr_or_eq not_one_le_zero numeral_2_eq_2 plus_1_eq_Suc set_n_deg_not_0)\n  then show ?case using  \"5.prems\" VEBT_Member.vebt_member.simps(5) add_2_eq_Suc  le_add_diff_inverse vebt_mint.simps(3)\n    by (metis option.inject)\nqed\n\n\nlemma mint_corr_help: \"invar_vebt t n \\<Longrightarrow> vebt_mint t = Some mini \\<Longrightarrow> vebt_member t x \\<Longrightarrow> mini \\<le> x \" \n  by (smt VEBT_Member.vebt_member.simps(1) eq_iff option.inject less_imp_le_nat member_inv mi_ma_2_deg vebt_mint.elims of_nat_0 of_nat_0_le_iff of_nat_le_iff option.simps(3))\n\nlemma mint_corr_help_empty: \"invar_vebt t n \\<Longrightarrow> vebt_mint t = None \\<Longrightarrow> set_vebt' t = {}\"\n  by (metis VEBT_internal.maxt_corr_help_empty option.distinct(1) vebt_maxt.simps(1) vebt_maxt.simps(2) vebt_mint.elims)\n\ntheorem mint_corr:assumes \"invar_vebt t n\" and \"vebt_mint t = Some x\" shows \"min_in_set (set_vebt' t) x\"\n  using assms(1) assms(2) min_in_set_def mint_corr_help mint_member set_vebt'_def by auto\n\ntheorem mint_sound:assumes \"invar_vebt t n\" and  \"min_in_set (set_vebt' t) x\" shows \"vebt_mint t = Some x\"\n  by (metis assms(1) assms(2) empty_Collect_eq eq_iff mem_Collect_eq min_in_set_def\n mint_corr_help mint_corr_help_empty mint_member option.exhaust set_vebt'_def)\n\nlemma summaxma:assumes \"invar_vebt (Node (Some (mi, ma)) deg treeList summary) deg\" and \"mi \\<noteq> ma\"\n  shows \"the (vebt_maxt summary) = high ma (deg div 2)\"\nproof-\n  from assms(1) show ?thesis \n  proof(cases)\n    case (4 n m)\n    have \"both_member_options summary (high ma n)\" \n      using \"4\"(10) \"4\"(2) \"4\"(4) \"4\"(5) \"4\"(6) \"4\"(9) assms(2) deg_not_0 exp_split_high_low(1) by blast\n    have \"high ma n \\<le> the (vebt_maxt summary)\" using  \"4\"(2) \\<open>both_member_options summary \n          (high ma n)\\<close> empty_Collect_eq option.inject maxt_corr_help maxt_corr_help_empty \n          not_None_eq set_vebt'_def valid_member_both_member_options\n      by (metis option.exhaust_sel)\n    have \"high ma n < the (vebt_maxt summary) \\<Longrightarrow> False\"\n    proof-\n      assume \"high ma n < the (vebt_maxt summary)\"\n      obtain maxs where \"Some maxs = vebt_maxt summary\" \n        by (metis \"4\"(2) \\<open>both_member_options summary (high ma n)\\<close> empty_Collect_eq maxt_corr_help_empty\n            not_None_eq set_vebt'_def valid_member_both_member_options) \n      hence \"\\<exists> x. both_member_options (treeList ! maxs) x\" \n        by (metis \"4\"(2) \"4\"(6) both_member_options_equiv_member maxt_member member_bound)\n      then obtain x where \"both_member_options (treeList ! maxs) x\"\n        by auto\n      hence \"vebt_member (treeList ! maxs) x\"\n        by (metis \"4\"(1) \"4\"(2) \"4\"(3) \\<open>Some maxs = vebt_maxt summary\\<close> maxt_member member_bound nth_mem valid_member_both_member_options)\n      have \"maxs < 2^m\" \n        by (metis \"4\"(2) \\<open>Some maxs = vebt_maxt summary\\<close> maxt_member member_bound)\n      have \"invar_vebt (treeList ! maxs) n\"\n        by (metis \"4\"(1) \"4\"(3) \\<open>maxs < 2 ^ m\\<close> inthall member_def)\n      hence \"x < 2^n\"\n        using \\<open>vebt_member (treeList ! maxs) x\\<close> member_bound by auto\n      let ?X =  \"2^n*maxs + x\"\n      have \"high ?X n = maxs\" \n        by (simp add: \\<open>x < 2 ^ n\\<close> high_inv mult.commute)\n      hence \"both_member_options (Node (Some (mi, ma)) deg treeList summary) (2^n*maxs + x)\" \n        by (metis \"4\"(3) \"4\"(4) \"4\"(5) One_nat_def Suc_leI \\<open>both_member_options (treeList ! maxs) x\\<close> \\<open>maxs < 2 ^ m\\<close> \\<open>x < 2 ^ n\\<close> add_self_div_2 assms(1) both_member_options_from_chilf_to_complete_tree deg_not_0 low_inv mult.commute)\n      hence \"vebt_member (Node (Some (mi, ma)) deg treeList summary) ?X\"\n        using assms(1) both_member_options_equiv_member by auto\n      have \"high ?X n> high ma n\"\n        by (metis \\<open>Some maxs = vebt_maxt summary\\<close> \\<open>high (2 ^ n * maxs + x) n = maxs\\<close> \\<open>high ma n < the (vebt_maxt summary)\\<close> option.exhaust_sel option.inject option.simps(3))\n     hence \"?X > ma\"  \n        by (metis div_le_mono high_def not_le)\n      then show ?thesis \n        by (metis \"4\"(8) \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) (2 ^ n * maxs + x)\\<close> leD member_inv not_less_iff_gr_or_eq)\n    qed\n    then show ?thesis\n      using \"4\"(4) \"4\"(5) \\<open>high ma n \\<le> the (vebt_maxt summary)\\<close> by fastforce\nnext\n  case (5 n m)\n   have \"both_member_options summary (high ma n)\" \n     by (metis \"5\"(10) \"5\"(5) \"5\"(6) \"5\"(9) div_eq_0_iff assms(2) div_exp_eq high_def nat.simps(3) numerals(2) power_not_zero)\n      have \"high ma n \\<le> the (vebt_maxt summary)\" \n        by (metis \"5\"(2) VEBT_Member.vebt_member.simps(2) \\<open>both_member_options summary (high ma n)\\<close> vebt_maxt.elims maxt_corr_help minNull.simps(1) min_Null_member option.exhaust_sel option.simps(3) valid_member_both_member_options)\n   have \"high ma n < the (vebt_maxt summary) \\<Longrightarrow> False\"\n    proof-\n      assume \"high ma n < the (vebt_maxt summary)\"\n      obtain maxs where \"Some maxs = vebt_maxt summary\" \n        by (metis \"5\"(2) \\<open>both_member_options summary (high ma n)\\<close> empty_Collect_eq maxt_corr_help_empty\n         not_None_eq set_vebt'_def valid_member_both_member_options) \n      hence \"\\<exists> x. both_member_options (treeList ! maxs) x\" \n        by (metis \"5\"(2) \"5\"(6) both_member_options_equiv_member maxt_member member_bound)\n      then obtain x where \"both_member_options (treeList ! maxs) x\"\n        by auto\n      hence \"vebt_member (treeList ! maxs) x\" \n        by (metis \"5\"(1) \"5\"(2) \"5\"(3) \\<open>Some maxs = vebt_maxt summary\\<close> both_member_options_equiv_member maxt_member member_bound nth_mem)\n      have \"maxs < 2^m\" \n        by (metis \"5\"(2) \\<open>Some maxs = vebt_maxt summary\\<close> maxt_member member_bound)\n      have \"invar_vebt (treeList ! maxs) n\"\n        by (metis \"5\"(1) \"5\"(3) \\<open>maxs < 2 ^ m\\<close> inthall member_def)\n      hence \"x < 2^n\"\n        using \\<open>vebt_member (treeList ! maxs) x\\<close> member_bound by auto\n      let ?X =  \"2^n*maxs + x\"\n      have \"high ?X n = maxs\" \n        by (simp add: \\<open>x < 2 ^ n\\<close> high_inv mult.commute)\n      hence \"both_member_options (Node (Some (mi, ma)) deg treeList summary) (2^n*maxs + x)\" \n        by (smt (z3) \"5\"(3) \"5\"(4) \"5\"(5) \\<open>both_member_options (treeList ! maxs) x\\<close> \\<open>maxs < 2 ^ m\\<close> \\<open>x < 2 ^ n\\<close> add_Suc_right add_self_div_2 both_member_options_from_chilf_to_complete_tree even_Suc_div_two le_add1 low_inv mult.commute odd_add plus_1_eq_Suc)\n    hence \"vebt_member (Node (Some (mi, ma)) deg treeList summary) ?X\"\n        using assms(1) both_member_options_equiv_member by auto\n      have \"high ?X n> high ma n\"\n        by (metis \\<open>Some maxs = vebt_maxt summary\\<close> \\<open>high (2 ^ n * maxs + x) n = maxs\\<close> \\<open>high ma n < the (vebt_maxt summary)\\<close> option.sel)\n     hence \"?X > ma\" \n        by (metis div_le_mono high_def not_le)\n      then show ?thesis \n        by (metis \"5\"(8) \\<open>vebt_member (Node (Some (mi, ma)) deg treeList summary) (2 ^ n * maxs + x)\\<close> leD member_inv not_less_iff_gr_or_eq)\n    qed\n    then show ?thesis\n      using \"5\"(4) \"5\"(5) \\<open>high ma n \\<le> the(vebt_maxt summary)\\<close> by fastforce\n  qed\nqed\n\nlemma maxbmo: \"vebt_maxt t = Some x \\<Longrightarrow> both_member_options t x\"\n  apply(induction t rule: vebt_maxt.induct)\n    apply auto\n  apply (metis both_member_options_def naive_member.simps(1) option.distinct(1) option.sel zero_neq_one)\n  by (metis One_nat_def Suc_le_D both_member_options_def div_by_1 div_greater_zero_iff membermima.simps(3) membermima.simps(4) not_gr0)\n\nlemma misiz:\"invar_vebt t n \\<Longrightarrow> Some m = vebt_mint t \\<Longrightarrow> m < 2^n\" \n  by (metis member_bound mint_member)  \n\nlemma mintlistlength: assumes \"invar_vebt (Node (Some (mi, ma)) deg treeList summary) n \" \" \n    mi \\<noteq> ma \" shows \" ma > mi \\<and> (\\<exists> m. Some m = vebt_mint summary \\<and> m < 2^(n - n div 2))\"\n  using assms(1) \nproof cases\n  case (4 n m)\n  hence \"both_member_options (treeList ! high ma n) (low ma n)\" \n    by (metis assms(2) high_bound_aux)\n  moreover  hence \"both_member_options summary (high ma n)\" \n    using \"4\"(10) \"4\"(6) \"4\"(7) high_bound_aux by blast\n  moreover  then obtain mini where \"Some mini = vebt_mint summary\" \n    by (metis \"4\"(3) empty_Collect_eq mint_corr_help_empty option.exhaust_sel set_vebt'_def valid_member_both_member_options)\n  moreover hence \"mini < 2^m\" \n    by (metis \"4\"(3)  mint_member member_bound)\n  moreover have \"m = (deg - deg div 2)\" using 4(6) 4(5) \n    by auto\n  ultimately show ?thesis using 4(1) assms 4(9) by auto\nnext\n  case (5 n m)\n  hence \"both_member_options (treeList ! high ma n) (low ma n)\" \n    by (metis assms(2) high_bound_aux)\n  moreover  hence \"both_member_options summary (high ma n)\" \n    using \"5\"(10) \"5\"(6) \"5\"(7) high_bound_aux by blast\n  moreover  then obtain mini where \"Some mini = vebt_mint summary\" \n    by (metis \"5\"(3) empty_Collect_eq mint_corr_help_empty option.exhaust_sel set_vebt'_def valid_member_both_member_options)\n  moreover hence \"mini < 2^m\" \n    by (metis \"5\"(3)  mint_member member_bound)\n  moreover have \"m = (deg - deg div 2)\" using 5(6) 5(5) \n    by auto\n  ultimately show ?thesis using 5(1) assms 5(9) by auto\nqed\n\nlemma power_minus_is_div:\n  \"b \\<le> a \\<Longrightarrow> (2 :: nat) ^ (a - b) = 2 ^ a div 2 ^ b\"\n  apply (induct a arbitrary: b)\n   apply simp\n  apply (erule le_SucE)\n   apply (clarsimp simp:Suc_diff_le le_iff_add power_add)\n  apply simp\n  done\n\nlemma nested_mint:assumes \"invar_vebt (Node (Some (mi, ma)) deg treeList summary) n \" \"n = Suc (Suc va) \"\"\n    \\<not> ma < mi \"\" ma \\<noteq> mi \" shows \"\n    high (the (vebt_mint summary) * (2 * 2 ^ (va div 2)) + the (vebt_mint (treeList ! the (vebt_mint summary)))) (Suc (va div 2))\n    < length treeList\"\nproof-\n  have setprop: \"t \\<in> set treeList \\<Longrightarrow> invar_vebt t (n div 2 )\" for t using assms(1)\n    by (cases) simp+\n  have listlength: \"length treeList = 2^(n - n div 2)\" using assms(1)\n    by (cases) simp+\n  have sumprop: \"invar_vebt summary (n - n div 2)\" using assms(1)\n    by (cases) simp+\n  have mimaxprop: \"mi \\<le> ma \\<and> ma \\<le> 2^n\" using assms(1)\n    by cases  simp+\n  hence xbound: \"mi \\<le> x \\<Longrightarrow> x \\<le> ma \\<Longrightarrow> high x (n div 2) \\<le> length treeList \" for x \n    using div_le_dividend div_le_mono high_def listlength power_minus_is_div by auto\n  have contcong:\"i < length treeList \\<Longrightarrow> \\<exists> x. both_member_options (treeList ! i) x \\<longleftrightarrow> both_member_options summary i \" for i\n    using assms(1)by cases  auto+\n  obtain m where \" Some m = vebt_mint summary \\<and> m < 2^(n - n div 2)\"\n    using assms(1) assms(4) mintlistlength by blast\n  then obtain miny where \"(vebt_mint (treeList ! the (vebt_mint summary))) =Some miny\" \n    by (metis both_member_options_equiv_member contcong empty_Collect_eq listlength mint_corr_help_empty mint_member nth_mem option.exhaust_sel option.sel setprop sumprop set_vebt'_def)\n  hence \"miny < 2^(n div 2)\" \n    by (metis \\<open>\\<And>thesis. (\\<And>m. Some m = vebt_mint summary \\<and> m < 2 ^ (n - n div 2) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> listlength misiz nth_mem option.sel setprop)\n  then show ?thesis \n    by (metis \\<open>\\<And>thesis. (\\<And>m. Some m = vebt_mint summary \\<and> m < 2 ^ (n - n div 2) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> \\<open>vebt_mint (treeList ! the (vebt_mint summary)) = Some miny\\<close> assms(2) div2_Suc_Suc high_inv listlength option.sel power_Suc)\nqed\n\nlemma minminNull: \"vebt_mint t = None \\<Longrightarrow> minNull t\" \n  by (metis minNull.simps(1) minNull.simps(4) vebt_mint.elims option.distinct(1))\n\nlemma minNullmin: \"minNull t \\<Longrightarrow> vebt_mint t = None\" \n  by (metis minNull.elims(2) vebt_mint.simps(1) vebt_mint.simps(2))\n\n  \nend  \nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Van_Emde_Boas_Trees/VEBT_MinMax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7817031886450029}}
{"text": "theory Concrete_Semantics_2_2_ex6\nimports Main\nbegin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree => 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l a r) = (contents r) @ (a # (contents l))\"\n\nfun sum_tree :: \"nat tree => nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l a r) = (sum_tree l) + a + (sum_tree r)\"\n\nlemma \"sum_tree t = sum_list (contents t)\"\napply(induction t)\napply(auto)\ndone\n\nend", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/ConcreteSemanticsChapter2/ex2_3/Concrete_Semantics_2_2_ex6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7816696523963533}}
{"text": "(* Property from Case-Analysis for Rippling and Inductive Proof, \n   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. \n   This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n   Some proofs were added by Yutaka Nagashima.*)\ntheory TIP_prop_23\n  imports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\nfun max :: \"Nat => Nat => Nat\" where\n  \"max (Z) y = y\"\n| \"max (S z) (Z) = S z\"\n| \"max (S z) (S x2) = S (max z x2)\"\n\ntheorem property0 :\n  \"((max a b) = (max b a))\"\n  (*why \"induct a arbitrary: b\" rather than \"induct b arbitrary: a\"?\n    \\<rightarrow> both work well.*)\n  apply(induct a arbitrary: b)\n   apply(induct_tac b)(*\"case_tac\" works well. See below.*)\n    apply fastforce+\n  apply(induct_tac b)(*\"case_tac\" works well. See below.*)\n   apply fastforce+\n  done\n\ntheorem property0' :\n  \"((max a b) = (max b a))\"\n  apply(induct a arbitrary: b)\n   apply (case_tac b)\n    apply fastforce+\n  apply (case_tac b)\n   apply fastforce+\n  done\n\ntheorem property0'' :\n  \"((max a b) = (max b a))\"\n  apply(induct b arbitrary: a)\n   apply (induct_tac a)\n    apply fastforce+\n  apply (induct_tac a)\n   apply fastforce+\n  done\n\ntheorem property0''' :\n  \"((max a b) = (max b a))\"\n  apply(induct b arbitrary: a)\n   apply (case_tac a)\n    apply fastforce+\n  apply (case_tac a)\n   apply fastforce+\n  done\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/Isaplanner/Isaplanner/TIP_prop_23.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8652240738888188, "lm_q1q2_score": 0.7815519024544072}}
{"text": "(*  Title:      ZF/Ordinal.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection\\<open>Transitive Sets and Ordinals\\<close>\n\ntheory Ordinal imports WF Bool equalities begin\n\ndefinition\n  Memrel        :: \"i\\<Rightarrow>i\"  where\n    \"Memrel(A)   \\<equiv> {z\\<in>A*A . \\<exists>x y. z=\\<langle>x,y\\<rangle> \\<and> x\\<in>y }\"\n\ndefinition\n  Transset  :: \"i\\<Rightarrow>o\"  where\n    \"Transset(i) \\<equiv> \\<forall>x\\<in>i. x<=i\"\n\ndefinition\n  Ord  :: \"i\\<Rightarrow>o\"  where\n    \"Ord(i)      \\<equiv> Transset(i) \\<and> (\\<forall>x\\<in>i. Transset(x))\"\n\ndefinition\n  lt        :: \"[i,i] \\<Rightarrow> o\"  (infixl \\<open><\\<close> 50)   (*less-than on ordinals*)  where\n    \"i<j         \\<equiv> i\\<in>j \\<and> Ord(j)\"\n\ndefinition\n  Limit         :: \"i\\<Rightarrow>o\"  where\n    \"Limit(i)    \\<equiv> Ord(i) \\<and> 0<i \\<and> (\\<forall>y. y<i \\<longrightarrow> succ(y)<i)\"\n\nabbreviation\n  le  (infixl \\<open>\\<le>\\<close> 50) where\n  \"x \\<le> y \\<equiv> x < succ(y)\"\n\n\nsubsection\\<open>Rules for Transset\\<close>\n\nsubsubsection\\<open>Three Neat Characterisations of Transset\\<close>\n\nlemma Transset_iff_Pow: \"Transset(A) <-> A<=Pow(A)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_iff_Union_succ: \"Transset(A) <-> \\<Union>(succ(A)) = A\"\n  unfolding Transset_def\napply (blast elim!: equalityE)\ndone\n\nlemma Transset_iff_Union_subset: \"Transset(A) <-> \\<Union>(A) \\<subseteq> A\"\nby (unfold Transset_def, blast)\n\nsubsubsection\\<open>Consequences of Downwards Closure\\<close>\n\nlemma Transset_doubleton_D:\n    \"\\<lbrakk>Transset(C); {a,b}: C\\<rbrakk> \\<Longrightarrow> a\\<in>C \\<and> b\\<in>C\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Pair_D:\n    \"\\<lbrakk>Transset(C); \\<langle>a,b\\<rangle>\\<in>C\\<rbrakk> \\<Longrightarrow> a\\<in>C \\<and> b\\<in>C\"\napply (simp add: Pair_def)\napply (blast dest: Transset_doubleton_D)\ndone\n\nlemma Transset_includes_domain:\n    \"\\<lbrakk>Transset(C); A*B \\<subseteq> C; b \\<in> B\\<rbrakk> \\<Longrightarrow> A \\<subseteq> C\"\nby (blast dest: Transset_Pair_D)\n\nlemma Transset_includes_range:\n    \"\\<lbrakk>Transset(C); A*B \\<subseteq> C; a \\<in> A\\<rbrakk> \\<Longrightarrow> B \\<subseteq> C\"\nby (blast dest: Transset_Pair_D)\n\nsubsubsection\\<open>Closure Properties\\<close>\n\nlemma Transset_0: \"Transset(0)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Un:\n    \"\\<lbrakk>Transset(i);  Transset(j)\\<rbrakk> \\<Longrightarrow> Transset(i \\<union> j)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Int:\n    \"\\<lbrakk>Transset(i);  Transset(j)\\<rbrakk> \\<Longrightarrow> Transset(i \\<inter> j)\"\nby (unfold Transset_def, blast)\n\nlemma Transset_succ: \"Transset(i) \\<Longrightarrow> Transset(succ(i))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Pow: \"Transset(i) \\<Longrightarrow> Transset(Pow(i))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Union: \"Transset(A) \\<Longrightarrow> Transset(\\<Union>(A))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Union_family:\n    \"\\<lbrakk>\\<And>i. i\\<in>A \\<Longrightarrow> Transset(i)\\<rbrakk> \\<Longrightarrow> Transset(\\<Union>(A))\"\nby (unfold Transset_def, blast)\n\nlemma Transset_Inter_family:\n    \"\\<lbrakk>\\<And>i. i\\<in>A \\<Longrightarrow> Transset(i)\\<rbrakk> \\<Longrightarrow> Transset(\\<Inter>(A))\"\nby (unfold Inter_def Transset_def, blast)\n\nlemma Transset_UN:\n     \"(\\<And>x. x \\<in> A \\<Longrightarrow> Transset(B(x))) \\<Longrightarrow> Transset (\\<Union>x\\<in>A. B(x))\"\nby (rule Transset_Union_family, auto)\n\nlemma Transset_INT:\n     \"(\\<And>x. x \\<in> A \\<Longrightarrow> Transset(B(x))) \\<Longrightarrow> Transset (\\<Inter>x\\<in>A. B(x))\"\nby (rule Transset_Inter_family, auto)\n\n\nsubsection\\<open>Lemmas for Ordinals\\<close>\n\nlemma OrdI:\n    \"\\<lbrakk>Transset(i);  \\<And>x. x\\<in>i \\<Longrightarrow> Transset(x)\\<rbrakk>  \\<Longrightarrow>  Ord(i)\"\nby (simp add: Ord_def)\n\nlemma Ord_is_Transset: \"Ord(i) \\<Longrightarrow> Transset(i)\"\nby (simp add: Ord_def)\n\nlemma Ord_contains_Transset:\n    \"\\<lbrakk>Ord(i);  j\\<in>i\\<rbrakk> \\<Longrightarrow> Transset(j) \"\nby (unfold Ord_def, blast)\n\n\nlemma Ord_in_Ord: \"\\<lbrakk>Ord(i);  j\\<in>i\\<rbrakk> \\<Longrightarrow> Ord(j)\"\nby (unfold Ord_def Transset_def, blast)\n\n(*suitable for rewriting PROVIDED i has been fixed*)\nlemma Ord_in_Ord': \"\\<lbrakk>j\\<in>i; Ord(i)\\<rbrakk> \\<Longrightarrow> Ord(j)\"\nby (blast intro: Ord_in_Ord)\n\n(* Ord(succ(j)) \\<Longrightarrow> Ord(j) *)\nlemmas Ord_succD = Ord_in_Ord [OF _ succI1]\n\nlemma Ord_subset_Ord: \"\\<lbrakk>Ord(i);  Transset(j);  j<=i\\<rbrakk> \\<Longrightarrow> Ord(j)\"\nby (simp add: Ord_def Transset_def, blast)\n\nlemma OrdmemD: \"\\<lbrakk>j\\<in>i;  Ord(i)\\<rbrakk> \\<Longrightarrow> j<=i\"\nby (unfold Ord_def Transset_def, blast)\n\nlemma Ord_trans: \"\\<lbrakk>i\\<in>j;  j\\<in>k;  Ord(k)\\<rbrakk> \\<Longrightarrow> i\\<in>k\"\nby (blast dest: OrdmemD)\n\nlemma Ord_succ_subsetI: \"\\<lbrakk>i\\<in>j;  Ord(j)\\<rbrakk> \\<Longrightarrow> succ(i) \\<subseteq> j\"\nby (blast dest: OrdmemD)\n\n\nsubsection\\<open>The Construction of Ordinals: 0, succ, Union\\<close>\n\nlemma Ord_0 [iff,TC]: \"Ord(0)\"\nby (blast intro: OrdI Transset_0)\n\nlemma Ord_succ [TC]: \"Ord(i) \\<Longrightarrow> Ord(succ(i))\"\nby (blast intro: OrdI Transset_succ Ord_is_Transset Ord_contains_Transset)\n\nlemmas Ord_1 = Ord_0 [THEN Ord_succ]\n\nlemma Ord_succ_iff [iff]: \"Ord(succ(i)) <-> Ord(i)\"\nby (blast intro: Ord_succ dest!: Ord_succD)\n\nlemma Ord_Un [intro,simp,TC]: \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> Ord(i \\<union> j)\"\n  unfolding Ord_def\napply (blast intro!: Transset_Un)\ndone\n\nlemma Ord_Int [TC]: \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> Ord(i \\<inter> j)\"\n  unfolding Ord_def\napply (blast intro!: Transset_Int)\ndone\n\ntext\\<open>There is no set of all ordinals, for then it would contain itself\\<close>\nlemma ON_class: \"\\<not> (\\<forall>i. i\\<in>X <-> Ord(i))\"\nproof (rule notI)\n  assume X: \"\\<forall>i. i \\<in> X \\<longleftrightarrow> Ord(i)\"\n  have \"\\<forall>x y. x\\<in>X \\<longrightarrow> y\\<in>x \\<longrightarrow> y\\<in>X\"\n    by (simp add: X, blast intro: Ord_in_Ord)\n  hence \"Transset(X)\"\n     by (auto simp add: Transset_def)\n  moreover have \"\\<And>x. x \\<in> X \\<Longrightarrow> Transset(x)\"\n     by (simp add: X Ord_def)\n  ultimately have \"Ord(X)\" by (rule OrdI)\n  hence \"X \\<in> X\" by (simp add: X)\n  thus \"False\" by (rule mem_irrefl)\nqed\n\nsubsection\\<open>< is 'less Than' for Ordinals\\<close>\n\nlemma ltI: \"\\<lbrakk>i\\<in>j;  Ord(j)\\<rbrakk> \\<Longrightarrow> i<j\"\nby (unfold lt_def, blast)\n\nlemma ltE:\n    \"\\<lbrakk>i<j;  \\<lbrakk>i\\<in>j;  Ord(i);  Ord(j)\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  unfolding lt_def\napply (blast intro: Ord_in_Ord)\ndone\n\nlemma ltD: \"i<j \\<Longrightarrow> i\\<in>j\"\nby (erule ltE, assumption)\n\nlemma not_lt0 [simp]: \"\\<not> i<0\"\nby (unfold lt_def, blast)\n\nlemma lt_Ord: \"j<i \\<Longrightarrow> Ord(j)\"\nby (erule ltE, assumption)\n\nlemma lt_Ord2: \"j<i \\<Longrightarrow> Ord(i)\"\nby (erule ltE, assumption)\n\n(* @{term\"ja \\<le> j \\<Longrightarrow> Ord(j)\"} *)\nlemmas le_Ord2 = lt_Ord2 [THEN Ord_succD]\n\n(* i<0 \\<Longrightarrow> R *)\nlemmas lt0E = not_lt0 [THEN notE, elim!]\n\nlemma lt_trans [trans]: \"\\<lbrakk>i<j;  j<k\\<rbrakk> \\<Longrightarrow> i<k\"\nby (blast intro!: ltI elim!: ltE intro: Ord_trans)\n\nlemma lt_not_sym: \"i<j \\<Longrightarrow> \\<not> (j<i)\"\n  unfolding lt_def\napply (blast elim: mem_asym)\ndone\n\n(* \\<lbrakk>i<j;  \\<not>P \\<Longrightarrow> j<i\\<rbrakk> \\<Longrightarrow> P *)\nlemmas lt_asym = lt_not_sym [THEN swap]\n\nlemma lt_irrefl [elim!]: \"i<i \\<Longrightarrow> P\"\nby (blast intro: lt_asym)\n\nlemma lt_not_refl: \"\\<not> i<i\"\napply (rule notI)\napply (erule lt_irrefl)\ndone\n\n\ntext\\<open>Recall that  \\<^term>\\<open>i \\<le> j\\<close>  abbreviates  \\<^term>\\<open>i<succ(j)\\<close>!\\<close>\n\nlemma le_iff: \"i \\<le> j <-> i<j | (i=j \\<and> Ord(j))\"\nby (unfold lt_def, blast)\n\n(*Equivalently, i<j \\<Longrightarrow> i < succ(j)*)\nlemma leI: \"i<j \\<Longrightarrow> i \\<le> j\"\nby (simp add: le_iff)\n\nlemma le_eqI: \"\\<lbrakk>i=j;  Ord(j)\\<rbrakk> \\<Longrightarrow> i \\<le> j\"\nby (simp add: le_iff)\n\nlemmas le_refl = refl [THEN le_eqI]\n\nlemma le_refl_iff [iff]: \"i \\<le> i <-> Ord(i)\"\nby (simp (no_asm_simp) add: lt_not_refl le_iff)\n\nlemma leCI: \"(\\<not> (i=j \\<and> Ord(j)) \\<Longrightarrow> i<j) \\<Longrightarrow> i \\<le> j\"\nby (simp add: le_iff, blast)\n\nlemma leE:\n    \"\\<lbrakk>i \\<le> j;  i<j \\<Longrightarrow> P;  \\<lbrakk>i=j;  Ord(j)\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (simp add: le_iff, blast)\n\nlemma le_anti_sym: \"\\<lbrakk>i \\<le> j;  j \\<le> i\\<rbrakk> \\<Longrightarrow> i=j\"\napply (simp add: le_iff)\napply (blast elim: lt_asym)\ndone\n\nlemma le0_iff [simp]: \"i \\<le> 0 <-> i=0\"\nby (blast elim!: leE)\n\nlemmas le0D = le0_iff [THEN iffD1, dest!]\n\nsubsection\\<open>Natural Deduction Rules for Memrel\\<close>\n\n(*The lemmas MemrelI/E give better speed than [iff] here*)\nlemma Memrel_iff [simp]: \"\\<langle>a,b\\<rangle> \\<in> Memrel(A) <-> a\\<in>b \\<and> a\\<in>A \\<and> b\\<in>A\"\nby (unfold Memrel_def, blast)\n\nlemma MemrelI [intro!]: \"\\<lbrakk>a \\<in> b;  a \\<in> A;  b \\<in> A\\<rbrakk> \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<in> Memrel(A)\"\nby auto\n\nlemma MemrelE [elim!]:\n    \"\\<lbrakk>\\<langle>a,b\\<rangle> \\<in> Memrel(A);\n        \\<lbrakk>a \\<in> A;  b \\<in> A;  a\\<in>b\\<rbrakk>  \\<Longrightarrow> P\\<rbrakk>\n     \\<Longrightarrow> P\"\nby auto\n\nlemma Memrel_type: \"Memrel(A) \\<subseteq> A*A\"\nby (unfold Memrel_def, blast)\n\nlemma Memrel_mono: \"A<=B \\<Longrightarrow> Memrel(A) \\<subseteq> Memrel(B)\"\nby (unfold Memrel_def, blast)\n\nlemma Memrel_0 [simp]: \"Memrel(0) = 0\"\nby (unfold Memrel_def, blast)\n\nlemma Memrel_1 [simp]: \"Memrel(1) = 0\"\nby (unfold Memrel_def, blast)\n\nlemma relation_Memrel: \"relation(Memrel(A))\"\nby (simp add: relation_def Memrel_def)\n\n(*The membership relation (as a set) is well-founded.\n  Proof idea: show A<=B by applying the foundation axiom to A-B *)\nlemma wf_Memrel: \"wf(Memrel(A))\"\n  unfolding wf_def\napply (rule foundation [THEN disjE, THEN allI], erule disjI1, blast)\ndone\n\ntext\\<open>The premise \\<^term>\\<open>Ord(i)\\<close> does not suffice.\\<close>\nlemma trans_Memrel:\n    \"Ord(i) \\<Longrightarrow> trans(Memrel(i))\"\nby (unfold Ord_def Transset_def trans_def, blast)\n\ntext\\<open>However, the following premise is strong enough.\\<close>\nlemma Transset_trans_Memrel:\n    \"\\<forall>j\\<in>i. Transset(j) \\<Longrightarrow> trans(Memrel(i))\"\nby (unfold Transset_def trans_def, blast)\n\n(*If Transset(A) then Memrel(A) internalizes the membership relation below A*)\nlemma Transset_Memrel_iff:\n    \"Transset(A) \\<Longrightarrow> \\<langle>a,b\\<rangle> \\<in> Memrel(A) <-> a\\<in>b \\<and> b\\<in>A\"\nby (unfold Transset_def, blast)\n\n\nsubsection\\<open>Transfinite Induction\\<close>\n\n(*Epsilon induction over a transitive set*)\nlemma Transset_induct:\n    \"\\<lbrakk>i \\<in> k;  Transset(k);\n        \\<And>x.\\<lbrakk>x \\<in> k;  \\<forall>y\\<in>x. P(y)\\<rbrakk> \\<Longrightarrow> P(x)\\<rbrakk>\n     \\<Longrightarrow>  P(i)\"\napply (simp add: Transset_def)\napply (erule wf_Memrel [THEN wf_induct2], blast+)\ndone\n\n(*Induction over an ordinal*)\nlemma Ord_induct [consumes 2]:\n  \"i \\<in> k \\<Longrightarrow> Ord(k) \\<Longrightarrow> (\\<And>x. x \\<in> k \\<Longrightarrow> (\\<And>y. y \\<in> x \\<Longrightarrow> P(y)) \\<Longrightarrow> P(x)) \\<Longrightarrow> P(i)\"\n  using Transset_induct [OF _ Ord_is_Transset, of i k P] by simp\n\n(*Induction over the class of ordinals -- a useful corollary of Ord_induct*)\nlemma trans_induct [consumes 1, case_names step]:\n  \"Ord(i) \\<Longrightarrow> (\\<And>x. Ord(x) \\<Longrightarrow> (\\<And>y. y \\<in> x \\<Longrightarrow> P(y)) \\<Longrightarrow> P(x)) \\<Longrightarrow> P(i)\"\n  apply (rule Ord_succ [THEN succI1 [THEN Ord_induct]], assumption)\n  apply (blast intro: Ord_succ [THEN Ord_in_Ord])\n  done\n\n\nsection\\<open>Fundamental properties of the epsilon ordering (< on ordinals)\\<close>\n\n\nsubsubsection\\<open>Proving That < is a Linear Ordering on the Ordinals\\<close>\n\nlemma Ord_linear:\n     \"Ord(i) \\<Longrightarrow> Ord(j) \\<Longrightarrow> i\\<in>j | i=j | j\\<in>i\"\nproof (induct i arbitrary: j rule: trans_induct)\n  case (step i)\n  note step_i = step\n  show ?case using \\<open>Ord(j)\\<close>\n    proof (induct j rule: trans_induct)\n      case (step j)\n      thus ?case using step_i\n        by (blast dest: Ord_trans)\n    qed\nqed\n\ntext\\<open>The trichotomy law for ordinals\\<close>\nlemma Ord_linear_lt:\n assumes o: \"Ord(i)\" \"Ord(j)\"\n obtains (lt) \"i<j\" | (eq) \"i=j\" | (gt) \"j<i\"\napply (simp add: lt_def)\napply (rule_tac i1=i and j1=j in Ord_linear [THEN disjE])\napply (blast intro: o)+\ndone\n\nlemma Ord_linear2:\n assumes o: \"Ord(i)\" \"Ord(j)\"\n obtains (lt) \"i<j\" | (ge) \"j \\<le> i\"\napply (rule_tac i = i and j = j in Ord_linear_lt)\napply (blast intro: leI le_eqI sym o) +\ndone\n\nlemma Ord_linear_le:\n assumes o: \"Ord(i)\" \"Ord(j)\"\n obtains (le) \"i \\<le> j\" | (ge) \"j \\<le> i\"\napply (rule_tac i = i and j = j in Ord_linear_lt)\napply (blast intro: leI le_eqI o) +\ndone\n\nlemma le_imp_not_lt: \"j \\<le> i \\<Longrightarrow> \\<not> i<j\"\nby (blast elim!: leE elim: lt_asym)\n\nlemma not_lt_imp_le: \"\\<lbrakk>\\<not> i<j;  Ord(i);  Ord(j)\\<rbrakk> \\<Longrightarrow> j \\<le> i\"\nby (rule_tac i = i and j = j in Ord_linear2, auto)\n\n\nsubsubsection \\<open>Some Rewrite Rules for \\<open><\\<close>, \\<open>\\<le>\\<close>\\<close>\n\nlemma Ord_mem_iff_lt: \"Ord(j) \\<Longrightarrow> i\\<in>j <-> i<j\"\nby (unfold lt_def, blast)\n\nlemma not_lt_iff_le: \"\\<lbrakk>Ord(i);  Ord(j)\\<rbrakk> \\<Longrightarrow> \\<not> i<j <-> j \\<le> i\"\nby (blast dest: le_imp_not_lt not_lt_imp_le)\n\nlemma not_le_iff_lt: \"\\<lbrakk>Ord(i);  Ord(j)\\<rbrakk> \\<Longrightarrow> \\<not> i \\<le> j <-> j<i\"\nby (simp (no_asm_simp) add: not_lt_iff_le [THEN iff_sym])\n\n(*This is identical to 0<succ(i) *)\nlemma Ord_0_le: \"Ord(i) \\<Longrightarrow> 0 \\<le> i\"\nby (erule not_lt_iff_le [THEN iffD1], auto)\n\nlemma Ord_0_lt: \"\\<lbrakk>Ord(i);  i\\<noteq>0\\<rbrakk> \\<Longrightarrow> 0<i\"\napply (erule not_le_iff_lt [THEN iffD1])\napply (rule Ord_0, blast)\ndone\n\nlemma Ord_0_lt_iff: \"Ord(i) \\<Longrightarrow> i\\<noteq>0 <-> 0<i\"\nby (blast intro: Ord_0_lt)\n\n\nsubsection\\<open>Results about Less-Than or Equals\\<close>\n\n(** For ordinals, @{term\"j\\<subseteq>i\"} implies @{term\"j \\<le> i\"} (less-than or equals) **)\n\nlemma zero_le_succ_iff [iff]: \"0 \\<le> succ(x) <-> Ord(x)\"\nby (blast intro: Ord_0_le elim: ltE)\n\nlemma subset_imp_le: \"\\<lbrakk>j<=i;  Ord(i);  Ord(j)\\<rbrakk> \\<Longrightarrow> j \\<le> i\"\napply (rule not_lt_iff_le [THEN iffD1], assumption+)\napply (blast elim: ltE mem_irrefl)\ndone\n\nlemma le_imp_subset: \"i \\<le> j \\<Longrightarrow> i<=j\"\nby (blast dest: OrdmemD elim: ltE leE)\n\nlemma le_subset_iff: \"j \\<le> i <-> j<=i \\<and> Ord(i) \\<and> Ord(j)\"\nby (blast dest: subset_imp_le le_imp_subset elim: ltE)\n\nlemma le_succ_iff: \"i \\<le> succ(j) <-> i \\<le> j | i=succ(j) \\<and> Ord(i)\"\napply (simp (no_asm) add: le_iff)\napply blast\ndone\n\n(*Just a variant of subset_imp_le*)\nlemma all_lt_imp_le: \"\\<lbrakk>Ord(i);  Ord(j);  \\<And>x. x<j \\<Longrightarrow> x<i\\<rbrakk> \\<Longrightarrow> j \\<le> i\"\nby (blast intro: not_lt_imp_le dest: lt_irrefl)\n\nsubsubsection\\<open>Transitivity Laws\\<close>\n\nlemma lt_trans1: \"\\<lbrakk>i \\<le> j;  j<k\\<rbrakk> \\<Longrightarrow> i<k\"\nby (blast elim!: leE intro: lt_trans)\n\nlemma lt_trans2: \"\\<lbrakk>i<j;  j \\<le> k\\<rbrakk> \\<Longrightarrow> i<k\"\nby (blast elim!: leE intro: lt_trans)\n\nlemma le_trans: \"\\<lbrakk>i \\<le> j;  j \\<le> k\\<rbrakk> \\<Longrightarrow> i \\<le> k\"\nby (blast intro: lt_trans1)\n\nlemma succ_leI: \"i<j \\<Longrightarrow> succ(i) \\<le> j\"\napply (rule not_lt_iff_le [THEN iffD1])\napply (blast elim: ltE leE lt_asym)+\ndone\n\n(*Identical to  succ(i) < succ(j) \\<Longrightarrow> i<j  *)\nlemma succ_leE: \"succ(i) \\<le> j \\<Longrightarrow> i<j\"\napply (rule not_le_iff_lt [THEN iffD1])\napply (blast elim: ltE leE lt_asym)+\ndone\n\nlemma succ_le_iff [iff]: \"succ(i) \\<le> j <-> i<j\"\nby (blast intro: succ_leI succ_leE)\n\nlemma succ_le_imp_le: \"succ(i) \\<le> succ(j) \\<Longrightarrow> i \\<le> j\"\nby (blast dest!: succ_leE)\n\nlemma lt_subset_trans: \"\\<lbrakk>i \\<subseteq> j;  j<k;  Ord(i)\\<rbrakk> \\<Longrightarrow> i<k\"\napply (rule subset_imp_le [THEN lt_trans1])\napply (blast intro: elim: ltE) +\ndone\n\nlemma lt_imp_0_lt: \"j<i \\<Longrightarrow> 0<i\"\nby (blast intro: lt_trans1 Ord_0_le [OF lt_Ord])\n\nlemma succ_lt_iff: \"succ(i) < j <-> i<j \\<and> succ(i) \\<noteq> j\"\napply auto\napply (blast intro: lt_trans le_refl dest: lt_Ord)\napply (frule lt_Ord)\napply (rule not_le_iff_lt [THEN iffD1])\n  apply (blast intro: lt_Ord2)\n apply blast\napply (simp add: lt_Ord lt_Ord2 le_iff)\napply (blast dest: lt_asym)\ndone\n\nlemma Ord_succ_mem_iff: \"Ord(j) \\<Longrightarrow> succ(i) \\<in> succ(j) <-> i\\<in>j\"\napply (insert succ_le_iff [of i j])\napply (simp add: lt_def)\ndone\n\nsubsubsection\\<open>Union and Intersection\\<close>\n\nlemma Un_upper1_le: \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> i \\<le> i \\<union> j\"\nby (rule Un_upper1 [THEN subset_imp_le], auto)\n\nlemma Un_upper2_le: \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> j \\<le> i \\<union> j\"\nby (rule Un_upper2 [THEN subset_imp_le], auto)\n\n(*Replacing k by succ(k') yields the similar rule for le!*)\nlemma Un_least_lt: \"\\<lbrakk>i<k;  j<k\\<rbrakk> \\<Longrightarrow> i \\<union> j < k\"\napply (rule_tac i = i and j = j in Ord_linear_le)\napply (auto simp add: Un_commute le_subset_iff subset_Un_iff lt_Ord)\ndone\n\nlemma Un_least_lt_iff: \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> i \\<union> j < k  <->  i<k \\<and> j<k\"\napply (safe intro!: Un_least_lt)\napply (rule_tac [2] Un_upper2_le [THEN lt_trans1])\napply (rule Un_upper1_le [THEN lt_trans1], auto)\ndone\n\nlemma Un_least_mem_iff:\n    \"\\<lbrakk>Ord(i); Ord(j); Ord(k)\\<rbrakk> \\<Longrightarrow> i \\<union> j \\<in> k  <->  i\\<in>k \\<and> j\\<in>k\"\napply (insert Un_least_lt_iff [of i j k])\napply (simp add: lt_def)\ndone\n\n(*Replacing k by succ(k') yields the similar rule for le!*)\nlemma Int_greatest_lt: \"\\<lbrakk>i<k;  j<k\\<rbrakk> \\<Longrightarrow> i \\<inter> j < k\"\napply (rule_tac i = i and j = j in Ord_linear_le)\napply (auto simp add: Int_commute le_subset_iff subset_Int_iff lt_Ord)\ndone\n\nlemma Ord_Un_if:\n     \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> i \\<union> j = (if j<i then i else j)\"\nby (simp add: not_lt_iff_le le_imp_subset leI\n              subset_Un_iff [symmetric]  subset_Un_iff2 [symmetric])\n\nlemma succ_Un_distrib:\n     \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> succ(i \\<union> j) = succ(i) \\<union> succ(j)\"\nby (simp add: Ord_Un_if lt_Ord le_Ord2)\n\nlemma lt_Un_iff:\n     \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> k < i \\<union> j <-> k < i | k < j\"\napply (simp add: Ord_Un_if not_lt_iff_le)\napply (blast intro: leI lt_trans2)+\ndone\n\nlemma le_Un_iff:\n     \"\\<lbrakk>Ord(i); Ord(j)\\<rbrakk> \\<Longrightarrow> k \\<le> i \\<union> j <-> k \\<le> i | k \\<le> j\"\nby (simp add: succ_Un_distrib lt_Un_iff [symmetric])\n\nlemma Un_upper1_lt: \"\\<lbrakk>k < i; Ord(j)\\<rbrakk> \\<Longrightarrow> k < i \\<union> j\"\nby (simp add: lt_Un_iff lt_Ord2)\n\nlemma Un_upper2_lt: \"\\<lbrakk>k < j; Ord(i)\\<rbrakk> \\<Longrightarrow> k < i \\<union> j\"\nby (simp add: lt_Un_iff lt_Ord2)\n\n(*See also Transset_iff_Union_succ*)\nlemma Ord_Union_succ_eq: \"Ord(i) \\<Longrightarrow> \\<Union>(succ(i)) = i\"\nby (blast intro: Ord_trans)\n\n\nsubsection\\<open>Results about Limits\\<close>\n\nlemma Ord_Union [intro,simp,TC]: \"\\<lbrakk>\\<And>i. i\\<in>A \\<Longrightarrow> Ord(i)\\<rbrakk> \\<Longrightarrow> Ord(\\<Union>(A))\"\napply (rule Ord_is_Transset [THEN Transset_Union_family, THEN OrdI])\napply (blast intro: Ord_contains_Transset)+\ndone\n\nlemma Ord_UN [intro,simp,TC]:\n     \"\\<lbrakk>\\<And>x. x\\<in>A \\<Longrightarrow> Ord(B(x))\\<rbrakk> \\<Longrightarrow> Ord(\\<Union>x\\<in>A. B(x))\"\nby (rule Ord_Union, blast)\n\nlemma Ord_Inter [intro,simp,TC]:\n    \"\\<lbrakk>\\<And>i. i\\<in>A \\<Longrightarrow> Ord(i)\\<rbrakk> \\<Longrightarrow> Ord(\\<Inter>(A))\"\napply (rule Transset_Inter_family [THEN OrdI])\napply (blast intro: Ord_is_Transset)\napply (simp add: Inter_def)\napply (blast intro: Ord_contains_Transset)\ndone\n\nlemma Ord_INT [intro,simp,TC]:\n    \"\\<lbrakk>\\<And>x. x\\<in>A \\<Longrightarrow> Ord(B(x))\\<rbrakk> \\<Longrightarrow> Ord(\\<Inter>x\\<in>A. B(x))\"\nby (rule Ord_Inter, blast)\n\n\n(* No < version of this theorem: consider that @{term\"(\\<Union>i\\<in>nat.i)=nat\"}! *)\nlemma UN_least_le:\n    \"\\<lbrakk>Ord(i);  \\<And>x. x\\<in>A \\<Longrightarrow> b(x) \\<le> i\\<rbrakk> \\<Longrightarrow> (\\<Union>x\\<in>A. b(x)) \\<le> i\"\napply (rule le_imp_subset [THEN UN_least, THEN subset_imp_le])\napply (blast intro: Ord_UN elim: ltE)+\ndone\n\nlemma UN_succ_least_lt:\n    \"\\<lbrakk>j<i;  \\<And>x. x\\<in>A \\<Longrightarrow> b(x)<j\\<rbrakk> \\<Longrightarrow> (\\<Union>x\\<in>A. succ(b(x))) < i\"\napply (rule ltE, assumption)\napply (rule UN_least_le [THEN lt_trans2])\napply (blast intro: succ_leI)+\ndone\n\nlemma UN_upper_lt:\n     \"\\<lbrakk>a\\<in>A;  i < b(a);  Ord(\\<Union>x\\<in>A. b(x))\\<rbrakk> \\<Longrightarrow> i < (\\<Union>x\\<in>A. b(x))\"\nby (unfold lt_def, blast)\n\nlemma UN_upper_le:\n     \"\\<lbrakk>a \\<in> A;  i \\<le> b(a);  Ord(\\<Union>x\\<in>A. b(x))\\<rbrakk> \\<Longrightarrow> i \\<le> (\\<Union>x\\<in>A. b(x))\"\napply (frule ltD)\napply (rule le_imp_subset [THEN subset_trans, THEN subset_imp_le])\napply (blast intro: lt_Ord UN_upper)+\ndone\n\nlemma lt_Union_iff: \"\\<forall>i\\<in>A. Ord(i) \\<Longrightarrow> (j < \\<Union>(A)) <-> (\\<exists>i\\<in>A. j<i)\"\nby (auto simp: lt_def Ord_Union)\n\nlemma Union_upper_le:\n     \"\\<lbrakk>j \\<in> J;  i\\<le>j;  Ord(\\<Union>(J))\\<rbrakk> \\<Longrightarrow> i \\<le> \\<Union>J\"\napply (subst Union_eq_UN)\napply (rule UN_upper_le, auto)\ndone\n\nlemma le_implies_UN_le_UN:\n    \"\\<lbrakk>\\<And>x. x\\<in>A \\<Longrightarrow> c(x) \\<le> d(x)\\<rbrakk> \\<Longrightarrow> (\\<Union>x\\<in>A. c(x)) \\<le> (\\<Union>x\\<in>A. d(x))\"\napply (rule UN_least_le)\napply (rule_tac [2] UN_upper_le)\napply (blast intro: Ord_UN le_Ord2)+\ndone\n\nlemma Ord_equality: \"Ord(i) \\<Longrightarrow> (\\<Union>y\\<in>i. succ(y)) = i\"\nby (blast intro: Ord_trans)\n\n(*Holds for all transitive sets, not just ordinals*)\nlemma Ord_Union_subset: \"Ord(i) \\<Longrightarrow> \\<Union>(i) \\<subseteq> i\"\nby (blast intro: Ord_trans)\n\n\nsubsection\\<open>Limit Ordinals -- General Properties\\<close>\n\nlemma Limit_Union_eq: \"Limit(i) \\<Longrightarrow> \\<Union>(i) = i\"\n  unfolding Limit_def\napply (fast intro!: ltI elim!: ltE elim: Ord_trans)\ndone\n\nlemma Limit_is_Ord: \"Limit(i) \\<Longrightarrow> Ord(i)\"\n  unfolding Limit_def\napply (erule conjunct1)\ndone\n\nlemma Limit_has_0: \"Limit(i) \\<Longrightarrow> 0 < i\"\n  unfolding Limit_def\napply (erule conjunct2 [THEN conjunct1])\ndone\n\nlemma Limit_nonzero: \"Limit(i) \\<Longrightarrow> i \\<noteq> 0\"\nby (drule Limit_has_0, blast)\n\nlemma Limit_has_succ: \"\\<lbrakk>Limit(i);  j<i\\<rbrakk> \\<Longrightarrow> succ(j) < i\"\nby (unfold Limit_def, blast)\n\nlemma Limit_succ_lt_iff [simp]: \"Limit(i) \\<Longrightarrow> succ(j) < i <-> (j<i)\"\napply (safe intro!: Limit_has_succ)\napply (frule lt_Ord)\napply (blast intro: lt_trans)\ndone\n\nlemma zero_not_Limit [iff]: \"\\<not> Limit(0)\"\nby (simp add: Limit_def)\n\nlemma Limit_has_1: \"Limit(i) \\<Longrightarrow> 1 < i\"\nby (blast intro: Limit_has_0 Limit_has_succ)\n\nlemma increasing_LimitI: \"\\<lbrakk>0<l; \\<forall>x\\<in>l. \\<exists>y\\<in>l. x<y\\<rbrakk> \\<Longrightarrow> Limit(l)\"\napply (unfold Limit_def, simp add: lt_Ord2, clarify)\napply (drule_tac i=y in ltD)\napply (blast intro: lt_trans1 [OF _ ltI] lt_Ord2)\ndone\n\nlemma non_succ_LimitI:\n  assumes i: \"0<i\" and nsucc: \"\\<And>y. succ(y) \\<noteq> i\"\n  shows \"Limit(i)\"\nproof -\n  have Oi: \"Ord(i)\" using i by (simp add: lt_def)\n  { fix y\n    assume yi: \"y<i\"\n    hence Osy: \"Ord(succ(y))\" by (simp add: lt_Ord Ord_succ)\n    have \"\\<not> i \\<le> y\" using yi by (blast dest: le_imp_not_lt)\n    hence \"succ(y) < i\" using nsucc [of y]\n      by (blast intro: Ord_linear_lt [OF Osy Oi]) }\n  thus ?thesis using i Oi by (auto simp add: Limit_def)\nqed\n\nlemma succ_LimitE [elim!]: \"Limit(succ(i)) \\<Longrightarrow> P\"\napply (rule lt_irrefl)\napply (rule Limit_has_succ, assumption)\napply (erule Limit_is_Ord [THEN Ord_succD, THEN le_refl])\ndone\n\nlemma not_succ_Limit [simp]: \"\\<not> Limit(succ(i))\"\nby blast\n\nlemma Limit_le_succD: \"\\<lbrakk>Limit(i);  i \\<le> succ(j)\\<rbrakk> \\<Longrightarrow> i \\<le> j\"\nby (blast elim!: leE)\n\n\nsubsubsection\\<open>Traditional 3-Way Case Analysis on Ordinals\\<close>\n\nlemma Ord_cases_disj: \"Ord(i) \\<Longrightarrow> i=0 | (\\<exists>j. Ord(j) \\<and> i=succ(j)) | Limit(i)\"\nby (blast intro!: non_succ_LimitI Ord_0_lt)\n\nlemma Ord_cases:\n assumes i: \"Ord(i)\"\n obtains (\"0\") \"i=0\" | (succ) j where \"Ord(j)\" \"i=succ(j)\" | (limit) \"Limit(i)\"\nby (insert Ord_cases_disj [OF i], auto)\n\nlemma trans_induct3_raw:\n     \"\\<lbrakk>Ord(i);\n         P(0);\n         \\<And>x. \\<lbrakk>Ord(x);  P(x)\\<rbrakk> \\<Longrightarrow> P(succ(x));\n         \\<And>x. \\<lbrakk>Limit(x);  \\<forall>y\\<in>x. P(y)\\<rbrakk> \\<Longrightarrow> P(x)\n\\<rbrakk> \\<Longrightarrow> P(i)\"\napply (erule trans_induct)\napply (erule Ord_cases, blast+)\ndone\n\nlemma trans_induct3 [case_names 0 succ limit, consumes 1]:\n  \"Ord(i) \\<Longrightarrow> P(0) \\<Longrightarrow> (\\<And>x. Ord(x) \\<Longrightarrow> P(x) \\<Longrightarrow> P(succ(x))) \\<Longrightarrow> (\\<And>x. Limit(x) \\<Longrightarrow> (\\<And>y. y \\<in> x \\<Longrightarrow> P(y)) \\<Longrightarrow> P(x)) \\<Longrightarrow> P(i)\"\n  using trans_induct3_raw [of i P] by simp\n\ntext\\<open>A set of ordinals is either empty, contains its own union, or its\nunion is a limit ordinal.\\<close>\n\nlemma Union_le: \"\\<lbrakk>\\<And>x. x\\<in>I \\<Longrightarrow> x\\<le>j; Ord(j)\\<rbrakk> \\<Longrightarrow> \\<Union>(I) \\<le> j\"\n  by (auto simp add: le_subset_iff Union_least)\n\nlemma Ord_set_cases:\n  assumes I: \"\\<forall>i\\<in>I. Ord(i)\"\n  shows \"I=0 \\<or> \\<Union>(I) \\<in> I \\<or> (\\<Union>(I) \\<notin> I \\<and> Limit(\\<Union>(I)))\"\nproof (cases \"\\<Union>(I)\" rule: Ord_cases)\n  show \"Ord(\\<Union>I)\" using I by (blast intro: Ord_Union)\nnext\n  assume \"\\<Union>I = 0\" thus ?thesis by (simp, blast intro: subst_elem)\nnext\n  fix j\n  assume j: \"Ord(j)\" and UIj:\"\\<Union>(I) = succ(j)\"\n  { assume \"\\<forall>i\\<in>I. i\\<le>j\"\n    hence \"\\<Union>(I) \\<le> j\"\n      by (simp add: Union_le j)\n    hence False\n      by (simp add: UIj lt_not_refl) }\n  then obtain i where i: \"i \\<in> I\" \"succ(j) \\<le> i\" using I j\n    by (atomize, auto simp add: not_le_iff_lt)\n  have \"\\<Union>(I) \\<le> succ(j)\" using UIj j by auto\n  hence \"i \\<le> succ(j)\" using i\n    by (simp add: le_subset_iff Union_subset_iff)\n  hence \"succ(j) = i\" using i\n    by (blast intro: le_anti_sym)\n  hence \"succ(j) \\<in> I\" by (simp add: i)\n  thus ?thesis by (simp add: UIj)\nnext\n  assume \"Limit(\\<Union>I)\" thus ?thesis by auto\nqed\n\ntext\\<open>If the union of a set of ordinals is a successor, then it is an element of that set.\\<close>\nlemma Ord_Union_eq_succD: \"\\<lbrakk>\\<forall>x\\<in>X. Ord(x);  \\<Union>X = succ(j)\\<rbrakk> \\<Longrightarrow> succ(j) \\<in> X\"\n  by (drule Ord_set_cases, auto)\n\nlemma Limit_Union [rule_format]: \"\\<lbrakk>I \\<noteq> 0;  (\\<And>i. i\\<in>I \\<Longrightarrow> Limit(i))\\<rbrakk> \\<Longrightarrow> Limit(\\<Union>I)\"\napply (simp add: Limit_def lt_def)\napply (blast intro!: equalityI)\ndone\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/ZF/Ordinal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.7815310763201738}}
{"text": "(*\n  Boolean Expression Checkers Based on Binary Decision Trees\n  Author: Tobias Nipkow\n*)\n\ntheory Boolean_Expression_Checkers\n  imports Main \"HOL-Library.Mapping\"\nbegin\n\nsection \\<open>Tautology (etc) Checking via Binary Decision Trees\\<close>\n\nsubsection \\<open>Binary Decision Trees\\<close>\n\ndatatype 'a ifex = Trueif | Falseif | IF 'a \"'a ifex\" \"'a ifex\"\n\nfun val_ifex :: \"'a ifex \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" \nwhere\n  \"val_ifex Trueif s = True\"\n| \"val_ifex Falseif s = False\"\n| \"val_ifex (IF n t1 t2) s = (if s n then val_ifex t1 s else val_ifex t2 s)\"\n\nsubsubsection \\<open>Environment\\<close>\n\ntext \\<open>Environments are substitutions of values for variables:\\<close>\n\ntype_synonym 'a env_bool = \"('a, bool) mapping\"\n\ndefinition agree :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a env_bool \\<Rightarrow> bool\"\nwhere\n  \"agree s env = (\\<forall>x b. Mapping.lookup env x = Some b \\<longrightarrow> s x = b)\"\n\nlemma agree_Nil: \n  \"agree s Mapping.empty\"\n  by (simp add: agree_def lookup_empty)\n\nlemma lookup_update_unfold: \n  \"Mapping.lookup (Mapping.update k v m) k' = (if k = k' then Some v else Mapping.lookup m k')\"\n  using lookup_update lookup_update_neq by metis\n\nlemma agree_Cons: \n  \"x \\<notin> Mapping.keys env \\<Longrightarrow> agree s (Mapping.update x b env) = ((if b then s x else \\<not> s x) \\<and> agree s env)\"\n  by (simp add: agree_def lookup_update_unfold; unfold keys_is_none_rep lookup_update_unfold Option.is_none_def; blast)\n\nlemma agreeDT:\n  \"agree s env \\<Longrightarrow> Mapping.lookup env x = Some True \\<Longrightarrow> s x\"\n  by (simp add: agree_def)\n\nlemma agreeDF:\n  \"agree s env \\<Longrightarrow> Mapping.lookup env x = Some False \\<Longrightarrow> \\<not>s x\"\n  by (auto simp add: agree_def)\n\nsubsection \\<open>Recursive Tautology Checker\\<close>\n\ntext \\<open>Provided for completeness. However, it is recommend to use the checkers based on reduced trees.\\<close>\n\nfun taut_test_rec :: \"'a ifex \\<Rightarrow> 'a env_bool \\<Rightarrow> bool\" \nwhere\n  \"taut_test_rec Trueif env = True\" \n| \"taut_test_rec Falseif env = False\" \n| \"taut_test_rec (IF x t1 t2) env = (case Mapping.lookup env x of\n  Some b \\<Rightarrow> taut_test_rec (if b then t1 else t2) env |\n  None \\<Rightarrow> taut_test_rec t1 (Mapping.update x True env) \\<and> taut_test_rec t2 (Mapping.update x False env))\"\n\nlemma taut_test_rec: \n  \"taut_test_rec t env = (\\<forall>s. agree s env \\<longrightarrow> val_ifex t s)\"\nproof (induction t arbitrary: env)\n  case Falseif\n    have \"agree (\\<lambda>x. the (Mapping.lookup env x)) env\" \n      by (auto simp: agree_def)\n    thus ?case \n      by auto\nnext\n  case (IF x t1 t2) \n    thus ?case\n    proof (cases \"Mapping.lookup env x\")\n      case None \n        with IF show ?thesis \n          by simp (metis is_none_simps(1) agree_Cons keys_is_none_rep)\n    qed (simp add: agree_def)\nqed simp\n\ndefinition taut_test_ifex :: \"'a ifex \\<Rightarrow> bool\" \nwhere\n  \"taut_test_ifex t = taut_test_rec t Mapping.empty\"\n\ncorollary taut_test_ifex: \n  \"taut_test_ifex t = (\\<forall>s. val_ifex t s)\"\n  by (auto simp: taut_test_ifex_def taut_test_rec agree_Nil)\n\nsubsection \\<open>Reduced Binary Decision Trees\\<close>\n\nsubsubsection \\<open>Normalisation\\<close>\n\ntext \\<open>A normalisation avoiding duplicate variables and collapsing @{term \"If x t t\"} to \\<open>t\\<close>.\\<close>\n\ndefinition mkIF :: \"'a \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\" \nwhere\n  \"mkIF x t1 t2 = (if t1=t2 then t1 else IF x t1 t2)\"\n\nfun reduce :: \"'a env_bool \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\"\nwhere\n  \"reduce env (IF x t1 t2) = (case Mapping.lookup env x of\n     None \\<Rightarrow> mkIF x (reduce (Mapping.update x True env) t1) (reduce (Mapping.update x False env) t2) |\n     Some b \\<Rightarrow> reduce env (if b then t1 else t2))\" \n| \"reduce _ t = t\"\n\nprimrec normif :: \"'a env_bool \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\" \nwhere\n  \"normif env Trueif t1 t2 = reduce env t1\" \n| \"normif env Falseif t1 t2 = reduce env t2\" \n| \"normif env (IF x t1 t2) t3 t4 =\n    (case Mapping.lookup env x of\n       None \\<Rightarrow> mkIF x (normif (Mapping.update x True env) t1 t3 t4) (normif (Mapping.update x False env) t2 t3 t4) |\n       Some b \\<Rightarrow> if b then normif env t1 t3 t4 else normif env t2 t3 t4)\"\n\nsubsubsection \\<open>Functional Correctness Proof\\<close>\n\nlemma val_mkIF: \n  \"val_ifex (mkIF x t1 t2) s = val_ifex (IF x t1 t2) s\"\n  by (auto simp: mkIF_def Let_def)\n\ntheorem val_reduce: \n  \"agree s env \\<Longrightarrow> val_ifex (reduce env t) s = val_ifex t s\"\n  by (induction t arbitrary: s env)\n     (auto simp: map_of_eq_None_iff val_mkIF agree_Cons Let_def keys_is_none_rep\n           dest: agreeDT agreeDF split: option.splits) \n\nlemma val_normif: \n  \"agree s env \\<Longrightarrow> val_ifex (normif env t t1 t2) s = val_ifex (if val_ifex t s then t1 else t2) s\"\n  by (induct t arbitrary: t1 t2 s env)\n     (auto simp: val_reduce val_mkIF agree_Cons map_of_eq_None_iff keys_is_none_rep\n           dest: agreeDT agreeDF split: option.splits)   \n\nsubsubsection \\<open>Reduced If-Expressions\\<close>\n\ntext \\<open>An expression reduced iff no variable appears twice on any branch and there is no subexpression @{term \"IF x t t\"}.\\<close>\n\nfun reduced :: \"'a ifex \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"reduced (IF x t1 t2) X =\n  (x \\<notin> X \\<and> t1 \\<noteq> t2 \\<and> reduced t1 (insert x X) \\<and> reduced t2 (insert x X))\" |\n\"reduced _ _ = True\"\n\nlemma reduced_antimono: \n  \"X \\<subseteq> Y \\<Longrightarrow> reduced t Y \\<Longrightarrow> reduced t X\"\n  by (induction t arbitrary: X Y)\n     (auto, (metis insert_mono)+)\n\nlemma reduced_mkIF: \n  \"x \\<notin> X \\<Longrightarrow> reduced t1 (insert x X) \\<Longrightarrow> reduced t2 (insert x X) \\<Longrightarrow> reduced (mkIF x t1 t2) X\"\n  by (auto simp: mkIF_def intro:reduced_antimono)\n\nlemma reduced_reduce:\n  \"reduced (reduce env t) (Mapping.keys env)\"\nproof(induction t arbitrary: env)\n  case (IF x t1 t2)\n    thus ?case \n      using IF.IH(1) IF.IH(2)\n      apply (auto simp: map_of_eq_None_iff image_iff reduced_mkIF split: option.split) \n      by (metis is_none_code(1) keys_is_none_rep keys_update reduced_mkIF)\nqed auto\n\nlemma reduced_normif:\n  \"reduced (normif env t t1 t2) (Mapping.keys env)\"\nproof(induction t arbitrary: t1 t2 env)\n  case (IF x s1 s2)\n  thus ?case using IF.IH\n    apply (auto simp: reduced_mkIF map_of_eq_None_iff split: option.split) \n    by (metis is_none_code(1) keys_is_none_rep keys_update reduced_mkIF)\nqed (auto simp: reduced_reduce)\n\nsubsubsection \\<open>Checkers Based on Reduced Binary Decision Trees\\<close>\n\ntext \\<open>The checkers are parameterized over the translation function to binary decision trees. \n  They rely on the fact that @{term ifex_of} produces reduced trees\\<close>\n\ndefinition taut_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"taut_test ifex_of b = (ifex_of b = Trueif)\"\n\ndefinition sat_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"sat_test ifex_of b = (ifex_of b \\<noteq> Falseif)\"\n\ndefinition impl_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"impl_test ifex_of b1 b2 = (normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif = Trueif)\"\n\ndefinition equiv_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"equiv_test ifex_of b1 b2 = (let t1 = ifex_of b1; t2 = ifex_of b2 \n    in Trueif = normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif))\"\n\nlocale reduced_bdt_checkers = \n  fixes\n    ifex_of :: \"'b \\<Rightarrow> 'a ifex\"\n  fixes\n    val :: \"'b \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  assumes\n    val_ifex: \"val_ifex (ifex_of b) s = val b s\"\n  assumes \n    reduced_ifex: \"reduced (ifex_of b) {}\"\nbegin\n\ntext \\<open>Proof that reduced if-expressions are @{const Trueif}, @{const Falseif}\nor can evaluate to both @{const True} and @{const False}.\\<close>\n\nlemma same_val_if_reduced:\n  \"reduced t X \\<Longrightarrow> \\<forall>x. x \\<notin> X \\<longrightarrow> s1 x = s2 x \\<Longrightarrow> val_ifex t s1 = val_ifex t s2\"\n  by (induction t arbitrary: X) auto\n\nlemma reduced_IF_depends: \n  \"\\<lbrakk> reduced t X; t \\<noteq> Trueif; t \\<noteq> Falseif \\<rbrakk> \\<Longrightarrow> \\<exists>s1 s2. val_ifex t s1 \\<noteq> val_ifex t s2\"\nproof(induction t arbitrary: X)\n  case (IF x t1 t2)\n  let ?t = \"IF x t1 t2\"\n  have 1: \"reduced t1 (insert x X)\" using IF.prems(1) by simp\n  have 2: \"reduced t2 (insert x X)\" using IF.prems(1) by simp\n  show ?case\n  proof(cases t1)\n    case [simp]: Trueif\n    show ?thesis\n    proof (cases t2)\n      case Trueif thus ?thesis using IF.prems(1) by simp\n    next\n      case Falseif\n      hence \"val_ifex ?t (\\<lambda>_. True) \\<noteq> val_ifex ?t (\\<lambda>_. False)\" by simp\n      thus ?thesis by blast\n    next\n      case IF\n      then obtain s1 s2 where \"val_ifex t2 s1 \\<noteq> val_ifex t2 s2\"\n        using IF.IH(2)[OF 2] IF.prems(1) by auto\n      hence \"val_ifex ?t (s1(x:=False)) \\<noteq> val_ifex ?t (s2(x:=False))\"\n        using same_val_if_reduced[OF 2, of \"s1(x:=False)\" s1]\n          same_val_if_reduced[OF 2, of \"s2(x:=False)\" s2] by simp\n      thus ?thesis by blast\n    qed\n  next\n    case [simp]: Falseif\n    show ?thesis\n    proof (cases t2)\n      case Falseif thus ?thesis using IF.prems(1) by simp\n    next\n      case Trueif\n      hence \"val_ifex ?t (\\<lambda>_. True) \\<noteq> val_ifex ?t (\\<lambda>_. False)\" by simp\n      thus ?thesis by blast\n    next\n      case IF\n      then obtain s1 s2 where \"val_ifex t2 s1 \\<noteq> val_ifex t2 s2\"\n        using IF.IH(2)[OF 2] IF.prems(1) by auto\n      hence \"val_ifex ?t (s1(x:=False)) \\<noteq> val_ifex ?t (s2(x:=False))\"\n        using same_val_if_reduced[OF 2, of \"s1(x:=False)\" s1]\n          same_val_if_reduced[OF 2, of \"s2(x:=False)\" s2] by simp\n      thus ?thesis by blast\n    qed\n  next\n    case IF\n    then obtain s1 s2 where \"val_ifex t1 s1 \\<noteq> val_ifex t1 s2\"\n      using IF.IH(1)[OF 1] IF.prems(1) by auto\n    hence \"val_ifex ?t (s1(x:=True)) \\<noteq> val_ifex ?t (s2(x:=True))\"\n      using same_val_if_reduced[OF 1, of \"s1(x:=True)\" s1]\n          same_val_if_reduced[OF 1, of \"s2(x:=True)\" s2] by simp\n    thus ?thesis by blast\n  qed\nqed auto\n\ncorollary taut_test: \n  \"taut_test ifex_of b = (\\<forall>s. val b s)\"    \n  by (metis taut_test_def reduced_IF_depends[OF reduced_ifex] val_ifex val_ifex.simps(1,2))\n\ncorollary sat_test: \n  \"sat_test ifex_of b = (\\<exists>s. val b s)\"\n  by (metis sat_test_def reduced_IF_depends[OF reduced_ifex] val_ifex val_ifex.simps(1,2))\n\ncorollary impl_test: \n  \"impl_test ifex_of b1 b2 = (\\<forall>s. val b1 s \\<longrightarrow> val b2 s)\"\nproof -\n  have \"impl_test ifex_of b1 b2 = (\\<forall>s. val_ifex (normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif) s)\"\n    using reduced_IF_depends[OF reduced_normif] by (fastforce  simp: impl_test_def)\n  also\n  have \"(\\<forall>s. val_ifex (normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif) s) \\<longleftrightarrow> (\\<forall>s. val b1 s \\<longrightarrow> val b2 s)\"\n    using reduced_IF_depends[OF reduced_ifex] val_ifex unfolding val_normif[OF agree_Nil] by simp\n  finally\n  show ?thesis .\nqed\n\ncorollary equiv_test: \n  \"equiv_test ifex_of b1 b2 = (\\<forall>s. val b1 s = val b2 s)\"\nproof -\n  have \"equiv_test ifex_of b1 b2 = (\\<forall>s. val_ifex (let t1 = ifex_of b1; t2 = ifex_of b2 in normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif)) s)\"\n    by (simp add: equiv_test_def Let_def; insert reduced_IF_depends[OF reduced_normif]; force)\n  moreover\n  {\n    fix s\n    have \"val_ifex (let t1 = ifex_of b1; t2 = ifex_of b2 in normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif)) s\n      = (val b1 s = val b2 s)\"\n      using val_ifex by (simp add: Let_def val_normif[OF agree_Nil]) \n  }\n  ultimately\n  show ?thesis \n    by blast\nqed\n\nend\n\nsubsection \\<open>Boolean Expressions\\<close>\n\ntext \\<open>This is the simplified interface to the tautology checker. If you have your own type of Boolean \nexpressions you can either define your own translation to reduced binary decision trees or you can just \ntranslate into this type.\\<close>\n\ndatatype 'a bool_expr =\n  Const_bool_expr bool |\n  Atom_bool_expr 'a |\n  Neg_bool_expr \"'a bool_expr\" |\n  And_bool_expr \"'a bool_expr\" \"'a bool_expr\" |\n  Or_bool_expr \"'a bool_expr\" \"'a bool_expr\" |\n  Imp_bool_expr \"'a bool_expr\" \"'a bool_expr\" |\n  Iff_bool_expr \"'a bool_expr\" \"'a bool_expr\"\n\nprimrec val_bool_expr :: \"'a bool_expr \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"val_bool_expr (Const_bool_expr b) s = b\" |\n\"val_bool_expr (Atom_bool_expr x) s = s x\" |\n\"val_bool_expr (Neg_bool_expr b) s = (\\<not> val_bool_expr b s)\" |\n\"val_bool_expr (And_bool_expr b1 b2) s = (val_bool_expr b1 s \\<and> val_bool_expr b2 s)\" |\n\"val_bool_expr (Or_bool_expr b1 b2) s = (val_bool_expr b1 s \\<or> val_bool_expr b2 s)\" |\n\"val_bool_expr (Imp_bool_expr b1 b2) s = (val_bool_expr b1 s \\<longrightarrow> val_bool_expr b2 s)\" |\n\"val_bool_expr (Iff_bool_expr b1 b2) s = (val_bool_expr b1 s = val_bool_expr b2 s)\"\n\nfun ifex_of :: \"'a bool_expr \\<Rightarrow> 'a ifex\" where\n\"ifex_of (Const_bool_expr b) = (if b then Trueif else Falseif)\" |\n\"ifex_of (Atom_bool_expr x)   = IF x Trueif Falseif\" |\n\"ifex_of (Neg_bool_expr b)   = normif Mapping.empty (ifex_of b) Falseif Trueif\" |\n\"ifex_of (And_bool_expr b1 b2) = normif Mapping.empty (ifex_of b1) (ifex_of b2) Falseif\" |\n\"ifex_of (Or_bool_expr b1 b2) = normif Mapping.empty (ifex_of b1) Trueif (ifex_of b2)\" |\n\"ifex_of (Imp_bool_expr b1 b2) = normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif\" |\n\"ifex_of (Iff_bool_expr b1 b2) = (let t1 = ifex_of b1; t2 = ifex_of b2 in\n   normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif))\"\n\ntheorem val_ifex:\n  \"val_ifex (ifex_of b) s = val_bool_expr b s\"\n  by (induct_tac b) (auto simp: val_normif agree_Nil Let_def)\n\ntheorem reduced_ifex: \n  \"reduced (ifex_of b) {}\"\n  by (induction b) (simp add: Let_def; metis keys_empty reduced_normif)+\n\ndefinition \"bool_taut_test \\<equiv> taut_test ifex_of\"\ndefinition \"bool_sat_test \\<equiv> sat_test ifex_of\"\ndefinition \"bool_impl_test \\<equiv> impl_test ifex_of\"\ndefinition \"bool_equiv_test \\<equiv> equiv_test ifex_of\"\n\nlemma bool_tests:\n  \"bool_taut_test b = (\\<forall>s. val_bool_expr b s)\" (is ?t1)\n  \"bool_sat_test b = (\\<exists>s. val_bool_expr b s)\" (is ?t2)\n  \"bool_impl_test b1 b2 = (\\<forall>s. val_bool_expr b1 s \\<longrightarrow> val_bool_expr b2 s)\" (is ?t3)\n  \"bool_equiv_test b1 b2 = (\\<forall>s. val_bool_expr b1 s \\<longleftrightarrow> val_bool_expr b2 s)\" (is ?t4)\nproof -\n  interpret reduced_bdt_checkers ifex_of val_bool_expr\n    by (unfold_locales; insert val_ifex reduced_ifex; blast)\n  show ?t1 ?t2 ?t3 ?t4\n    by (simp_all add: bool_taut_test_def bool_sat_test_def bool_impl_test_def bool_equiv_test_def taut_test sat_test impl_test equiv_test) \nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Boolean_Expression_Checkers/Boolean_Expression_Checkers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.8705972684083609, "lm_q1q2_score": 0.781531071554526}}
{"text": "section \\<open>Augmenting Flows\\<close>\ntheory Augmenting_Flow\nimports Residual_Graph\nbegin\n\ntext \\<open>\n  In this theory, we define the concept of an augmenting flow,\n  augmentation with a flow, and show that augmentation of a flow \n  with an augmenting flow yields a valid flow again.\n  \\<close>\n\ntext \\<open>We assume that there is a network with a flow @{term f} on it\\<close>\ncontext NFlow\nbegin\n\nsubsection \\<open>Augmentation of a Flow\\<close>\ntext \\<open>The flow can be augmented by another flow, by adding the flows \n  of edges parallel to edges in the network, and subtracting the edges \n  reverse to edges in the network.\\<close>\n(* TODO: Define in network locale, with \\<up> syntax. *)\ndefinition augment :: \"'capacity flow \\<Rightarrow> 'capacity flow\"\nwhere \"augment f' \\<equiv> \\<lambda>(u, v).\n  if (u, v) \\<in> E then\n    f (u, v) + f' (u, v) - f' (v, u)\n  else\n    0\"\n\ntext \\<open>We define a syntax similar to Cormen et el.:\\<close>    \nabbreviation (input) augment_syntax (infix \"\\<up>\" 55) \n  where \"\\<And>f f'. f\\<up>f' \\<equiv> NFlow.augment c f f'\"\ntext \\<open>such that we can write @{term [source] \"f\\<up>f'\"} for the flow @{term f} \n  augmented by @{term f'}.\\<close>\n\n\nsubsection \\<open>Augmentation yields Valid Flow\\<close>\ntext \\<open>We show that, if we augment the flow with a valid flow of\n  the residual graph, the augmented flow is a valid flow again, i.e. \n  it satisfies the capacity and conservation constraints:\\<close>\ncontext \n  \\<comment> \\<open>Let the \\emph{residual flow} @{term f'} be a flow in the residual graph\\<close>\n  fixes f' :: \"'capacity flow\"\n  assumes f'_flow: \"Flow cf s t f'\"\nbegin  \n\ninterpretation f': Flow cf s t f' by (rule f'_flow)\n\nsubsubsection \\<open>Capacity Constraint\\<close>\ntext \\<open>First, we have to show that the new flow satisfies the capacity constraint:\\<close>\n(* FIXME: Indentation unfortunate, but required to extract snippet for latex presentation *)    \ntext_raw \\<open>\\DefineSnippet{augment_flow_presv_cap}{\\<close>  \nlemma augment_flow_presv_cap: \n  shows \"0 \\<le> (f\\<up>f')(u,v) \\<and> (f\\<up>f')(u,v) \\<le> c(u,v)\"\nproof (cases \"(u,v)\\<in>E\"; rule conjI) \n  assume [simp]: \"(u,v)\\<in>E\"\n  hence \"f(u,v) = cf(v,u)\" \n    using no_parallel_edge by (auto simp: residualGraph_def)\n  also have \"cf(v,u) \\<ge> f'(v,u)\" using f'.capacity_const by auto\n  finally(*<*)(xtrans)(*>*) have \"f'(v,u) \\<le> f(u,v)\" .\n\n(*<*){\n    note [trans] = xtrans\n  (*>*)text_raw \\<open>\\isanewline\\<close>\n\n  text_raw \\<open>\\ \\ \\<close>have \"(f\\<up>f')(u,v) = f(u,v) + f'(u,v) - f'(v,u)\"\n    by (auto simp: augment_def)\n  also have \"\\<dots> \\<ge> f(u,v) + f'(u,v) - f(u,v)\"\n  (*<*)(is \"_ \\<ge> \\<dots>\")(*>*)  using \\<open>f'(v,u) \\<le> f(u,v)\\<close> by auto\n  also have \"\\<dots> = f'(u,v)\" by auto\n  also have \"\\<dots> \\<ge> 0\" using f'.capacity_const by auto\n  finally show \"(f\\<up>f')(u,v) \\<ge> 0\" .\n  (*<*)}(*>*)\n    \n  have \"(f\\<up>f')(u,v) = f(u,v) + f'(u,v) - f'(v,u)\" \n    by (auto simp: augment_def)\n  also have \"\\<dots> \\<le> f(u,v) + f'(u,v)\" using f'.capacity_const by auto\n  also have \"\\<dots> \\<le> f(u,v) + cf(u,v)\" using f'.capacity_const by auto\n  also have \"\\<dots> = f(u,v) + c(u,v) - f(u,v)\" \n    by (auto simp: residualGraph_def)\n  also have \"\\<dots> = c(u,v)\" by auto\n  finally show \"(f\\<up>f')(u, v) \\<le> c(u, v)\" .\nqed (auto simp: augment_def cap_positive)\ntext_raw \\<open>}%EndSnippet\\<close>\n\n  \nsubsubsection \\<open>Conservation Constraint\\<close>\ntext \\<open>In order to show the conservation constraint, we need some \n  auxiliary lemmas first.\\<close>\n\ntext \\<open>As there are no parallel edges in the network, and all edges \n  in the residual graph are either parallel or reverse to a network edge,\n  we can split summations of the residual flow over outgoing/incoming edges in the \n  residual graph to summations over outgoing/incoming edges in the network.\n\n  Note that the term @{term \\<open>E``{u}\\<close>} characterizes the successor nodes of @{term \\<open>u\\<close>},\n  and @{term \\<open>E\\<inverse>``{u}\\<close>} characterizes the predecessor nodes of @{term \\<open>u\\<close>}.\n\\<close>\n(* TODO: Introduce pred/succ functions on Graph *)\nprivate lemma split_rflow_outgoing: \n  \"(\\<Sum>v\\<in>cf.E``{u}. f' (u,v)) = (\\<Sum>v\\<in>E``{u}. f'(u,v)) + (\\<Sum>v\\<in>E\\<inverse>``{u}. f'(u,v))\"\n  (is \"?LHS = ?RHS\")\nproof -\n  from no_parallel_edge have DJ: \"E``{u} \\<inter> E\\<inverse>``{u} = {}\" by auto\n\n  have \"?LHS = (\\<Sum>v\\<in>E``{u} \\<union> E\\<inverse>``{u}. f' (u,v))\"\n    apply (rule sum.mono_neutral_left)\n    using cfE_ss_invE\n    by (auto intro: finite_Image)\n  also have \"\\<dots> = ?RHS\"\n    apply (subst sum.union_disjoint[OF _ _ DJ])\n    by (auto intro: finite_Image)\n  finally show \"?LHS = ?RHS\" .\nqed  \n\nprivate lemma split_rflow_incoming: \n  \"(\\<Sum>v\\<in>cf.E\\<inverse>``{u}. f' (v,u)) = (\\<Sum>v\\<in>E``{u}. f'(v,u)) + (\\<Sum>v\\<in>E\\<inverse>``{u}. f'(v,u))\"\n  (is \"?LHS = ?RHS\")\nproof -\n  from no_parallel_edge have DJ: \"E``{u} \\<inter> E\\<inverse>``{u} = {}\" by auto\n\n  have \"?LHS = (\\<Sum>v\\<in>E``{u} \\<union> E\\<inverse>``{u}. f' (v,u))\"\n    apply (rule sum.mono_neutral_left)\n    using cfE_ss_invE\n    by (auto intro: finite_Image)\n  also have \"\\<dots> = ?RHS\"\n    apply (subst sum.union_disjoint[OF _ _ DJ])\n    by (auto intro: finite_Image)\n  finally show \"?LHS = ?RHS\" .\nqed  \n\ntext \\<open>For proving the conservation constraint, let's fix a node @{term u}, which\n  is neither the source nor the sink: \\<close>\ncontext \n  fixes u :: node\n  assumes U_ASM: \"u\\<in>V - {s,t}\"\nbegin  \n\ntext \\<open>We first show an auxiliary lemma to compare the \n  effective residual flow on incoming network edges to\n  the effective residual flow on outgoing network edges.\n  \n  Intuitively, this lemma shows that the effective residual flow added to the \n  network edges satisfies the conservation constraint.\n\\<close>\nprivate lemma flow_summation_aux:\n  shows \"(\\<Sum>v\\<in>E``{u}. f' (u,v))  - (\\<Sum>v\\<in>E``{u}. f' (v,u))\n       = (\\<Sum>v\\<in>E\\<inverse>``{u}. f' (v,u)) - (\\<Sum>v\\<in>E\\<inverse>``{u}. f' (u,v))\"\n   (is \"?LHS = ?RHS\" is \"?A - ?B = ?RHS\")\nproof -\n  text \\<open>The proof is by splitting the flows, and careful \n    cancellation of the summands.\\<close>\n  have \"?A = (\\<Sum>v\\<in>cf.E``{u}. f' (u, v)) - (\\<Sum>v\\<in>E\\<inverse>``{u}. f' (u, v))\"\n    by (simp add: split_rflow_outgoing)\n  also have \"(\\<Sum>v\\<in>cf.E``{u}. f' (u, v)) = (\\<Sum>v\\<in>cf.E\\<inverse>``{u}. f' (v, u))\"  \n    using U_ASM\n    by (simp add: f'.conservation_const_pointwise)\n  finally have \"?A = (\\<Sum>v\\<in>cf.E\\<inverse>``{u}. f' (v, u)) - (\\<Sum>v\\<in>E\\<inverse>``{u}. f' (u, v))\" \n    by simp\n  moreover\n  have \"?B = (\\<Sum>v\\<in>cf.E\\<inverse>``{u}. f' (v, u)) - (\\<Sum>v\\<in>E\\<inverse>``{u}. f' (v, u))\"\n    by (simp add: split_rflow_incoming)\n  ultimately show \"?A - ?B = ?RHS\" by simp\nqed    \n\ntext \\<open>Finally, we are ready to prove that the augmented flow satisfies the \n  conservation constraint:\\<close>\nlemma augment_flow_presv_con: \n  shows \"(\\<Sum>e \\<in> outgoing u. augment f' e) = (\\<Sum>e \\<in> incoming u. augment f' e)\"\n    (is \"?LHS = ?RHS\")\nproof -\n  text \\<open>We define shortcuts for the successor and predecessor nodes of @{term u} \n    in the network:\\<close>\n  let ?Vo = \"E``{u}\" let ?Vi = \"E\\<inverse>``{u}\"\n\n  text \\<open>Using the auxiliary lemma for the effective residual flow,\n    the proof is straightforward:\\<close>\n  have \"?LHS = (\\<Sum>v\\<in>?Vo. augment f' (u,v))\"\n    by (auto simp: sum_outgoing_pointwise)\n  also have \"\\<dots> \n    = (\\<Sum>v\\<in>?Vo. f (u,v) + f'(u,v) - f'(v,u))\"  \n    by (auto simp: augment_def)\n  also have \"\\<dots> \n    = (\\<Sum>v\\<in>?Vo. f (u,v)) + (\\<Sum>v\\<in>?Vo. f' (u,v)) - (\\<Sum>v\\<in>?Vo. f' (v,u))\"\n    by (auto simp: sum_subtractf sum.distrib)\n  also have \"\\<dots> \n    = (\\<Sum>v\\<in>?Vi. f (v,u)) + (\\<Sum>v\\<in>?Vi. f' (v,u)) - (\\<Sum>v\\<in>?Vi. f' (u,v))\" \n    by (auto simp: conservation_const_pointwise[OF U_ASM] flow_summation_aux)\n  also have \"\\<dots> \n    = (\\<Sum>v\\<in>?Vi. f (v,u) + f' (v,u) - f' (u,v))\" \n    by (auto simp: sum_subtractf sum.distrib)\n  also have \"\\<dots> \n    = (\\<Sum>v\\<in>?Vi. augment f' (v,u))\"  \n    by (auto simp: augment_def)\n  also have \"\\<dots> \n    = ?RHS\"\n    by (auto simp: sum_incoming_pointwise)\n  finally show \"?LHS = ?RHS\" .\nqed  \ntext \\<open>Note that we tried to follow the proof presented by Cormen et al.~\\cite{CLRS09} \n  as closely as possible. Unfortunately, this proof generalizes the summation to all \n  nodes immediately, rendering the first equation invalid.\n  Trying to fix this error, we encountered that the step that uses the conservation \n  constraints on the augmenting flow is more subtle as indicated in the original proof.\n  Thus, we moved this argument to an auxiliary lemma. \\<close>\n\n\nend \\<comment> \\<open>@{term u} is node\\<close>\n\ntext \\<open>As main result, we get that the augmented flow is again a valid flow.\\<close>\ncorollary augment_flow_presv: \"Flow c s t (f\\<up>f')\"\n  using augment_flow_presv_cap augment_flow_presv_con \n  by (rule_tac intro_Flow) auto\n\nsubsection \\<open>Value of the Augmented Flow\\<close>\ntext \\<open>Next, we show that the value of the augmented flow is the sum of the values\n  of the original flow and the augmenting flow.\\<close>\n  \nlemma augment_flow_value: \"Flow.val c s (f\\<up>f') = val + Flow.val cf s f'\"\nproof -\n  interpret f'': Flow c s t \"f\\<up>f'\" using augment_flow_presv . \n\n  txt \\<open>For this proof, we set up Isabelle's rewriting engine for rewriting of sums.\n    In particular, we add lemmas to convert sums over incoming or outgoing \n    edges to sums over all vertices. This allows us to write the summations\n    from Cormen et al.~a bit more concise, leaving some of the tedious \n    calculation work to the computer.\\<close>\n  note sum_simp_setup[simp] = \n    sum_outgoing_alt[OF capacity_const] s_node\n    sum_incoming_alt[OF capacity_const]\n    cf.sum_outgoing_alt[OF f'.capacity_const]\n    cf.sum_incoming_alt[OF f'.capacity_const]\n    sum_outgoing_alt[OF f''.capacity_const]\n    sum_incoming_alt[OF f''.capacity_const]\n    sum_subtractf sum.distrib\n  \n  txt \\<open>Note that, if neither an edge nor its reverse is in the graph,\n    there is also no edge in the residual graph, and thus the flow value\n    is zero.\\<close>  \n  have aux1: \"f'(u,v) = 0\" if \"(u,v)\\<notin>E\" \"(v,u)\\<notin>E\" for u v\n  proof -\n    from that cfE_ss_invE have \"(u,v)\\<notin>cf.E\" by auto\n    thus \"f'(u,v) = 0\" by auto\n  qed  \n\n  txt \\<open>Now, the proposition follows by straightforward rewriting of \n    the summations:\\<close>\n  have \"f''.val = (\\<Sum>u\\<in>V. augment f' (s, u) - augment f' (u, s))\" \n    unfolding f''.val_def by simp\n  also have \"\\<dots> = (\\<Sum>u\\<in>V. f (s, u) - f (u, s) + (f' (s, u) - f' (u, s)))\"\n    \\<comment> \\<open>Note that this is the crucial step of the proof, which Cormen et al. leave as an exercise.\\<close>\n    by (rule sum.cong) (auto simp: augment_def no_parallel_edge aux1)\n  also have \"\\<dots> = val + Flow.val cf s f'\"  \n    unfolding val_def f'.val_def by simp\n  finally show \"f''.val = val + f'.val\" .  \nqed    \n\ntxt \\<open>Note, there is also an automatic proof. When creating the above \n    explicit proof, this automatic one has been used to extract meaningful\n    subgoals, abusing Isabelle as a term rewriter.\\<close>\nlemma \"Flow.val c s (f\\<up>f') = val + Flow.val cf s f'\"\nproof -\n  interpret f'': Flow c s t \"f\\<up>f'\" using augment_flow_presv . \n\n  have aux1: \"f'(u,v) = 0\" if A: \"(u,v)\\<notin>E\" \"(v,u)\\<notin>E\" for u v\n  proof -\n    from A cfE_ss_invE have \"(u,v)\\<notin>cf.E\" by auto\n    thus \"f'(u,v) = 0\" by auto\n  qed  \n\n  show ?thesis\n    unfolding val_def f'.val_def f''.val_def\n    apply (simp del:\n      add: \n      sum_outgoing_alt[OF capacity_const] s_node\n      sum_incoming_alt[OF capacity_const]\n      sum_outgoing_alt[OF f''.capacity_const]\n      sum_incoming_alt[OF f''.capacity_const]\n      cf.sum_outgoing_alt[OF f'.capacity_const]\n      cf.sum_incoming_alt[OF f'.capacity_const]\n      sum_subtractf[symmetric] sum.distrib[symmetric]\n      )\n    apply (rule sum.cong)\n    apply (auto simp: augment_def no_parallel_edge aux1)\n    done\nqed\n\n\nend \\<comment> \\<open>Augmenting flow\\<close>\nend \\<comment> \\<open>Network flow\\<close>\n\nend \\<comment> \\<open>Theory\\<close>\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Flow_Networks/Augmenting_Flow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278540866547, "lm_q2_score": 0.885631470799559, "lm_q1q2_score": 0.7815058782892625}}
{"text": "theory Ch5\nimports Main \"~~/src/Doc/Prog_Prove/Logic\"\nbegin\n\n(* 5.1 *)\nlemma\n  assumes T: \"\\<forall> x y. T x y \\<or> T y x\"\n  and A: \"\\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n  and TA: \"\\<forall> x y. T x y \\<longrightarrow> A x y\"\n  and \"A x y\"\n  shows \"T x y\"\nproof -\n  have \"T x y \\<or> T y x\" using T by simp\n  thus \"?thesis\"\n  proof\n    assume \"T x y\"\n    thus \"?thesis\" by assumption\n  next\n    assume \"T y x\"\n    hence \"A y x\" using TA by simp\n    hence \"A x y \\<and> A y x\" using \\<open>A x y\\<close> by simp\n    hence \"x = y\" using A by simp\n    thus \"T x y\" using \\<open>T y x\\<close> by simp\n  qed\nqed\n\n(* 5.2 *)\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof -\n  let ?n = \"(length xs + 1) div 2\"\n  let ?ys = \"take ?n xs\"\n  let ?zs = \"drop ?n xs\"\n  have \"xs = ?ys @ ?zs \\<and> (length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1)\" by auto\n  thus \"?thesis\" by blast\nqed\n\n(* 5.3 *)\nlemma assumes a: \"ev (Suc(Suc n))\" shows \"ev n\"\nproof -\n  show \"?thesis\" using a by cases\nqed\n\n(* 5.4 *)\nlemma \"\\<not>ev (Suc (Suc (Suc 0)))\" (is \"\\<not>?P\")\nproof\n  assume \"?P\"\n  hence \"ev (Suc 0)\" by cases\n  thus \"False\" by cases\nqed\n\n(* 5.5 *)\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  iter0: \"iter r 0 x x\" |\n  iterS: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (S n) x z\"\n\nlemma \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\nproof (induction rule: star.induct)\n  case (refl x)\n  hence \"iter r 0 x x\" by (simp add: iter0)\n  thus ?case by auto\nnext\n  case (step x y z)\n  then obtain n where \"iter r n y z\" by auto\n  hence \"iter r (Suc n) x z\" using \"step.hyps\"(1) by (simp add: iterS)\n  thus ?case by auto\nqed\n\n(* 5.6 *)\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n  \"elems [] = {}\" |\n  \"elems (x # xs) = {x} \\<union> elems xs\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  then show ?case\n  proof (cases \"a = x\")\n    case True\n    let ?ys = \"[]\"\n    let ?zs = \"xs\"\n    have \"a # xs = ?ys @ x # ?zs \\<and> x \\<notin> elems ?ys\" using True by auto\n    thus ?thesis using True by blast\n  next\n    case False\n    hence \"x \\<in> elems xs\" using Cons.prems by auto\n    then obtain ys zs where \"xs = ys @ x # zs \\<and> x \\<notin> elems ys\" using Cons.IH by auto\n    hence \"a # xs = (a # ys) @ x # zs \\<and> x \\<notin> elems (a # ys)\" using False by auto\n    thus ?thesis by blast\n  qed\nqed\n\n(* 5.7 *)\ndatatype alpha = A | B\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\n  S_empty: \"S []\" |\n  S_surround: \"S w \\<Longrightarrow> S (A # w @ [B])\" |\n  S_double: \"S w1 \\<Longrightarrow> S w2 \\<Longrightarrow> S (w1 @ w2)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\n  T_empty: \"T []\" |\n  T_step: \"T w1 \\<Longrightarrow> T w2 \\<Longrightarrow> T (w1 @ [A] @ w2 @ [B])\"\n\ndeclare S.intros[simp,intro]\n\ndeclare T.intros[simp,intro]\n\ntheorem T_S: \"T w \\<Longrightarrow> S w\"\n  by (simp add: T.inducts)\n\nlemma T_app: \"\\<lbrakk> T w2 ; T w1 \\<rbrakk> \\<Longrightarrow> T (w1 @ w2)\"\n  apply(induction rule: T.induct)\n  apply(simp)\n  apply(metis T_step append_assoc)\ndone\n\ntheorem S_T: \"S w \\<Longrightarrow> T w\"\n  by(metis S.induct T.simps T_app append_Cons append_Nil)\n\ntheorem S_T_equiv: \"S w = T w\"\n  by(metis T_S S_T)\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n  \"balanced 0 [] = True\" |\n  \"balanced n (A # w) = balanced (Suc n) w\" |\n  \"balanced (Suc n) (B # w) = balanced n w\" |\n  \"balanced _ _ = False\"\n\nlemma balanced_nil: \"balanced n [] \\<Longrightarrow> n = 0\"\n  by (induction n, auto)\n\nlemma balanced_cons: \"balanced n (a # w) \\<Longrightarrow>\n    a = A \\<and> balanced (Suc n) w \\<or>\n    a = B \\<and> (\\<exists> m. n = Suc m \\<and> balanced m w)\"\n  using balanced.elims(2) by auto\n\nlemma balanced_snoc: \"balanced n w \\<Longrightarrow> balanced (Suc n) (w @ [B])\"\n  by (induction n w rule: balanced.induct, auto)\n\nlemma balanced_app: \"balanced m v \\<Longrightarrow> balanced n w \\<Longrightarrow> balanced (m + n) (v @ w)\"\n  using balanced_cons by (induction v arbitrary: m, subst balanced_nil, auto, fastforce)\n\nlemma replicate_cons_snoc: \"replicate n a = a # as \\<Longrightarrow> a # as = as @ [a]\"\nproof (induction as)\n  case Nil\n  then show ?case by (simp add: Cons_replicate_eq)\nnext\n  case (Cons a as)\n  then show ?case by (metis Cons_replicate_eq replicate_append_same)\nqed\n\nlemma T_replicate_Nil: \"T (replicate n A) \\<Longrightarrow> n = 0\"\nproof (induction \"replicate n A\" rule: T.induct)\n  case T_empty\n  then show ?case by auto\nnext\n  case (T_step w1 w2)\n  then show ?case\n  proof (cases \"replicate n A\")\n    case Nil\n    then show ?thesis by auto\n  next\n    case (Cons a as)\n    hence \"a = A\" by (metis Cons_replicate_eq)\n    hence \"replicate n A = as @ [A]\" using Cons replicate_cons_snoc by fastforce\n    hence \"B = A\" using T_step.hyps(5) by fastforce\n    then show ?thesis by simp\n  qed\nqed\n\nlemma S_replicate_Nil: \"S (replicate n A) \\<Longrightarrow> n = 0\"\n  using S_T_equiv T_replicate_Nil by blast\n\nlemma S_balanced: \"S (replicate n A @ w) \\<Longrightarrow> balanced n w\"\nproof (induction \"replicate n A @ w\" arbitrary: n w rule: S.induct)\n  case S_empty\n  then show ?case by simp\nnext\n  case (S_surround v)\n  then show ?case\n  proof (cases w)\n    case Nil\n    then show ?thesis\n      using S.S_surround S_replicate_Nil S_surround.hyps(1) S_surround.hyps(3) by fastforce\n  next\n    let ?xs = \"butlast w\"\n    let ?x = \"last w\"\n    case (Cons a w')\n    hence 0: \"w = ?xs @ [?x]\" by simp\n    hence 1: \"(A # v) @ [B] = (replicate n A @ ?xs) @ [?x]\" using S_surround by simp\n    hence 2: \"B = ?x \\<and> A # v = replicate n A @ ?xs\" by simp\n    then show ?thesis\n    proof (cases n)\n      case 0\n      then show ?thesis\n      proof (cases ?xs)\n        case Nil\n        then show ?thesis using 0 2 by simp\n      next\n        case (Cons x xs)\n        hence 3: \"A = x \\<and> v = replicate 0 A @ xs\" using 0 2 by simp\n        hence 4: \"balanced 0 xs\" using S_surround by simp\n        hence \"w = A # xs @ [B]\" using S_surround 0 3 by auto\n        then show ?thesis using 0 4 balanced_snoc by force\n      qed\n    next\n      case (Suc n')\n      hence \"v = replicate n' A @ ?xs\" using 2 by simp\n      hence \"balanced n' ?xs\" using S_surround by simp\n      then show ?thesis using 0 balanced_snoc using 2 Suc by fastforce\n    qed\n  qed\nnext\n  case (S_double w1 w2)\n  hence \"(\\<exists>v. w1 = replicate n A @ v \\<and> v @ w2 = w \\<or> w1 @ v = replicate n A \\<and> w2 = v @ w)\"\n    (is \"\\<exists>v. ?P v\") by (simp add: append_eq_append_conv2)\n  then obtain v where p: \"?P v\" by auto\n  then show ?case\n  proof\n    assume 0: \"w1 = replicate n A @ v \\<and> v @ w2 = w\"\n    hence \"balanced n v\" using S_double by simp\n    then show ?thesis\n      by (metis S_double.hyps(4) 0 add.right_neutral append_Nil balanced_app replicate_0)\n  next\n    assume 1: \"w1 @ v = replicate n A \\<and> w2 = v @ w\"\n    then show ?thesis\n    proof (cases n)\n      case 0\n      then show ?thesis using 1 S_double by simp\n    next\n      case (Suc n')\n      hence \"w1 @ v = replicate n' A @ [A]\" using 1 by (simp add: replicate_append_same)\n      then show ?thesis\n        by (smt (verit, ccfv_threshold) 1 S_double.hyps S_replicate_Nil append_eq_append_conv\n                length_0_conv length_append length_replicate replicate_add self_append_conv2)\n    qed\n  qed\nqed\n\nlemma S_app_in: \"S (u @ w) \\<Longrightarrow> S v \\<Longrightarrow> S (u @ v @ w)\"\nproof (induction \"u @ w\" arbitrary: u w rule: S.induct)\n  case S_empty\n  then show ?case by simp\nnext\n  case (S_surround v')\n  then show ?case\n  proof (cases w)\n    case Nil\n    hence \"S u\" using S.S_surround S_surround by auto\n    then show ?thesis by (simp add: S_surround Nil)\n  next\n    case (Cons a w')\n    let ?xs = \"butlast w\"\n    let ?x = \"last w\"\n    have 0: \"w = ?xs @ [?x]\" using Cons by simp\n    hence 1: \"(A # v') @ [B] = (u @ ?xs) @ [?x]\" using S_surround by simp\n    hence 2: \"B = ?x \\<and> A # v' = u @ ?xs\" by simp\n    then show ?thesis\n    proof (cases u)\n      case Nil\n      hence 3: \"A # v' = ?xs\" using 2 by simp\n      then show ?thesis\n      proof (cases ?xs)\n        case Nil\n        then show ?thesis using \\<open>A # v' = ?xs\\<close> by simp\n      next\n        case (Cons x xs)\n        hence 4: \"A = x \\<and> v' = xs\" using 3 by simp\n        hence \"S (v @ xs)\" using S_double S_surround by simp\n        moreover have \"v @ (x # xs) @ [?x] = v @ w\" using 0 Nil S_surround Cons by simp\n        hence \"S w\" using 2 4 S.S_surround S_surround by auto\n        then show ?thesis using S_double S_surround Nil by simp\n      qed\n    next\n      case (Cons b u')\n      hence \"A # v' = b # (u' @ ?xs)\" using 2 by simp\n      hence \"A = b \\<and> v' = u' @ ?xs\" using 2 by simp\n      hence \"S (u' @ v @ ?xs)\" using S_double S_surround by simp\n      hence \"S (A # (u' @ v @ ?xs) @ [B])\" using S.S_surround by fastforce\n      then show ?thesis using 0 2 Cons by auto\n    qed\n  qed\nnext\n  case (S_double u' w')\n  hence \"\\<exists>uw. u' = u @ uw \\<and> uw @ w' = w \\<or>\n              u' @ uw = u \\<and> w' = uw @ w\" (is \"\\<exists>uw. ?P uw\") by (simp add: append_eq_append_conv2)\n  then obtain uw where p: \"?P uw\" by fastforce\n  thus ?case\n  proof\n    assume \"u' = u @ uw \\<and> uw @ w' = w\"\n    hence \"S (u @ v @ uw)\" and \"w = uw @ w'\" using S_double.prems(1) S_double.hyps(2) by auto\n    hence \"S ((u @ v @ uw) @ w')\" using S_double.hyps(3) S.S_double by blast\n    thus ?thesis using \\<open>w = uw @ w'\\<close> by auto\n  next\n    assume \"u' @ uw = u \\<and> w' = uw @ w\"\n    hence \"S (uw @ v @ w)\" and \"u = u' @ uw\" using S_double.prems(1) S_double.hyps(4) by auto\n    hence \"S (u' @ uw @ v @ w)\" using S_double.hyps(1) S.S_double by blast\n    thus ?thesis using \\<open>u = u' @ uw\\<close> by auto\n  qed\nqed\n\nlemma balanced_S: \"balanced n w \\<Longrightarrow> S (replicate n A @ w)\"\nproof (induction w arbitrary: n)\n  case Nil\n  hence \"n = 0\" by (cases n, auto)\n  thus ?case by auto\nnext\n  case (Cons a w)\n  thus ?case\n  proof (induction a arbitrary: n w)\n    case A\n    hence \"balanced (Suc n) w\" by simp\n    hence \"S (replicate (Suc n) A @ w)\" using A.prems(1) by fastforce\n    thus ?case using A by (simp add: replicate_app_Cons_same)\n  next\n    have \"S [A, B]\" using S.simps by blast\n    case B\n    hence \"\\<exists> m. n = Suc m \\<and> balanced m w\" using balanced_cons by fastforce\n    then obtain m where p: \"n = Suc m \\<and> balanced m w\" by fastforce\n    hence \"S (replicate m A @ w)\" using B.prems(1) by simp\n    hence \"S (replicate m A @ [A, B] @ w)\" using S_app_in \\<open>S [A, B]\\<close> by fastforce\n    thus ?case by (simp add: p replicate_app_Cons_same)\n  qed\nqed\n\ntheorem balanced_S_equiv: \"balanced n w = S (replicate n A @ w)\" using S_balanced balanced_S by auto\n\nend\n", "meta": {"author": "lemmarathon", "repo": "isabelle-exercises", "sha": "6a4a5c030b23a0152c1245424d25232958d9c2f8", "save_path": "github-repos/isabelle/lemmarathon-isabelle-exercises", "path": "github-repos/isabelle/lemmarathon-isabelle-exercises/isabelle-exercises-6a4a5c030b23a0152c1245424d25232958d9c2f8/concrete-semantics/Ch5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8872045937171068, "lm_q1q2_score": 0.7814472109384721}}
{"text": "(*\n    $Id: ex.thy,v 1.2 2004/11/23 15:14:34 webertj Exp $\n    Author: Martin Strecker\n*)\n\nheader {* Searching in Lists *}\n\n(*<*) theory ex imports Main begin (*>*)\n\ntext {* Define a function @{text first_pos} that computes the index\nof the first element in a list that satisfies a given predicate: *}\n\n(*<*) consts (*>*)\n  first_pos :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n\ntext {* The smallest index is @{text 0}.  If no element in the\nlist satisfies the predicate, the behaviour of @{text first_pos} should\nbe as described below. *}\n\n\ntext {* Verify your definition by computing\n\\begin{itemize}\n\\item the index of the first number equal to @{text 3} in the list\n  @{text \"[1::nat, 3, 5, 3, 1]\"},\n\\item the index of the first number greater than @{text 4} in the list\n  @{text \"[1::nat, 3, 5, 7]\"},\n\\item the index of  the first list with more than one element in the list\n  @{text \"[[], [1, 2], [3]]\"}.\n\\end{itemize}\n\n\\emph{Note:} Isabelle does not know the operators @{text \">\"} and @{text\n\"\\<ge>\"}.  Use @{text \"<\"} and @{text \"\\<le>\"} instead. *}\n\n\ntext {* Prove that @{text first_pos} returns the length of the list if\nand only if no element in the list satisfies the given predicate. *}\n\n\ntext {* Now prove: *}\n\nlemma \"list_all (\\<lambda> x. \\<not> P x) (take (first_pos P xs) xs)\"\n(*<*) oops (*>*)\n\n\ntext {* How can @{text \"first_pos (\\<lambda> x. P x \\<or> Q x) xs\"} be computed from\n@{text \"first_pos P xs\"} and @{text \"first_pos Q xs\"}?  Can something\nsimilar be said for the conjunction of @{text P} and @{text Q}?  Prove\nyour statement(s). *}\n\n\ntext {* Suppose @{text P} implies @{text Q}. What can be said about the\nrelation between @{text \"first_pos P xs\"} and @{text \"first_pos Q xs\"}?\nProve your statement. *}\n\n\ntext {* Define a function @{text count} that counts the number of\nelements in a list that satisfy a given predicate. *}\n\n(*<*) consts (*>*)\n  count :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat\"\n\n\ntext {* Show: The number of elements with a given property stays the\nsame when one reverses a list with @{text rev}.  The proof will require\na lemma. *}\n\n\ntext {* Find and prove a connection between the two functions @{text filter}\nand @{text count}. *}\n\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/isabelle.in.tum.de/exercises/lists/position/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.7813494206183886}}
{"text": "theory ExF009\n  imports Main \nbegin \n  \n\nlemma \"(\\<exists>x. P x) =  (\\<not>(\\<forall>x. \\<not>P x))\" \nproof -\n  {\n    assume a:\"\\<exists>x. P x\"\n    {\n      assume b:\"\\<forall>x. \\<not>P x\"\n      {\n        fix aa\n        assume c:\"P aa\"\n        from b have \"\\<not>P aa\" by (rule allE)\n        with c have False by contradiction\n      }\n      with a have False by (rule exE)\n    }\n    hence \"\\<not>(\\<forall>x. \\<not>P x)\" by (rule notI)\n  }\n  moreover\n  {\n    assume d:\"\\<not>(\\<forall>x. \\<not>P x)\"\n    {\n      assume e:\"\\<not>(\\<exists>x. P x)\"\n      {\n        fix aa\n        {\n          assume \"P aa\"\n          hence \"\\<exists>x. P x\" by (rule exI)\n          with e have False by contradiction\n        }   \n        hence \"\\<not>P aa\" by (rule notI)\n      }\n      hence \"\\<forall>x. \\<not>P x\" by (rule allI)\n      with d have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<exists>x. P x)\" by (rule notI)\n    hence \"(\\<exists>x. P x)\" by (rule notnotD)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed", "meta": {"author": "SvenWille", "repo": "LogicForwardProofs", "sha": "b03c110b073eb7c34a561fce94b860b14cde75f7", "save_path": "github-repos/isabelle/SvenWille-LogicForwardProofs", "path": "github-repos/isabelle/SvenWille-LogicForwardProofs/LogicForwardProofs-b03c110b073eb7c34a561fce94b860b14cde75f7/src/FOL/ExF009.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582554941719, "lm_q2_score": 0.8397339676722393, "lm_q1q2_score": 0.7813374026395111}}
{"text": "(*<*)\ntheory Szpilrajn \n  imports Main\nbegin\n  (*>*)\n\ntext \\<open>\n  We formalize a more general version of Szpilrajn's extension theorem~@{cite \"Szpilrajn:1930\"},\n  employing the terminology of Bossert and Suzumura~@{cite \"Bossert:2010\"}. We also formalize \n  Theorem 2.7 of their book. Our extension theorem states that any preorder can be extended to a\n  total preorder while maintaining its structure. The proof of the extension theorem follows the\n  proof presented in the Wikipedia article~@{cite Wiki}.\n\\<close>\n\nsection \\<open>Definitions\\<close>\n\nsubsection \\<open>Symmetric and asymmetric factor of a relation\\<close>\n\ntext \\<open>\n  According to Bossert and Suzumura, every relation can be partitioned into its symmetric\n  and asymmetric factor. The symmetric factor of a relation \\<^term>\\<open>r\\<close> contains all pairs\n  \\<^term>\\<open>(x, y) \\<in> r\\<close> where \\<^term>\\<open>(y, x) \\<in> r\\<close>. Conversely, the asymmetric factor contains all pairs\n   where this is not the case. In terms of an order \\<^term>\\<open>(\\<le>)\\<close>, the asymmetric factor contains all\n  \\<^term>\\<open>(x, y) \\<in> {(x, y) |x y. x \\<le> y}\\<close> where \\<^term>\\<open>x < y\\<close>.\n\\<close>\ndefinition sym_factor :: \"'a rel \\<Rightarrow> 'a rel\"\n  where \"sym_factor r \\<equiv> {(x, y) \\<in> r. (y, x) \\<in> r}\"\n\nlemma sym_factor_def': \"sym_factor r = r \\<inter> r\\<inverse>\"\n  unfolding sym_factor_def by fast\n\ndefinition asym_factor :: \"'a rel \\<Rightarrow> 'a rel\"\n  where \"asym_factor r = {(x, y) \\<in> r. (y, x) \\<notin> r}\"\n\n\nsubsubsection \\<open>Properties of the symmetric factor\\<close>\n\nlemma sym_factorI[intro]: \"(x, y) \\<in> r \\<Longrightarrow> (y, x) \\<in> r \\<Longrightarrow> (x, y) \\<in> sym_factor r\"\n  unfolding sym_factor_def by blast\n\nlemma sym_factorE[elim?]:\n  assumes \"(x, y) \\<in> sym_factor r\" obtains \"(x, y) \\<in> r\" \"(y, x) \\<in> r\"\n  using assms[unfolded sym_factor_def] by blast\n\nlemma sym_sym_factor[simp]: \"sym (sym_factor r)\"\n  unfolding sym_factor_def\n  by (auto intro!: symI) \n\nlemma trans_sym_factor[simp]: \"trans r \\<Longrightarrow> trans (sym_factor r)\"\n  unfolding sym_factor_def' using trans_Int by force\n\nlemma refl_on_sym_factor[simp]: \"refl_on A r \\<Longrightarrow> refl_on A (sym_factor r)\"\n  unfolding sym_factor_def\n  by (auto intro!: refl_onI dest: refl_onD refl_onD1)\n\nlemma sym_factor_absorb_if_sym[simp]: \"sym r \\<Longrightarrow> sym_factor r = r\"\n  unfolding sym_factor_def'\n  by (simp add: sym_conv_converse_eq)\n\nlemma sym_factor_idem[simp]: \"sym_factor (sym_factor r) = sym_factor r\"\n  using sym_factor_absorb_if_sym[OF sym_sym_factor] .\n\nlemma sym_factor_reflc[simp]: \"sym_factor (r\\<^sup>=) = (sym_factor r)\\<^sup>=\"\n  unfolding sym_factor_def by auto\n\nlemma sym_factor_Restr[simp]: \"sym_factor (Restr r A) = Restr (sym_factor r) A\"\n  unfolding sym_factor_def by blast\n\ntext \\<open>\n  In contrast to \\<^term>\\<open>asym_factor\\<close>, the \\<^term>\\<open>sym_factor\\<close> is monotone.\n\\<close>\nlemma sym_factor_mono: \"r \\<subseteq> s \\<Longrightarrow> sym_factor r \\<subseteq> sym_factor s\"\n  unfolding sym_factor_def by auto\n\n\nsubsubsection \\<open>Properties of the asymmetric factor\\<close>\n\nlemma asym_factorI[intro]: \"(x, y) \\<in> r \\<Longrightarrow> (y, x) \\<notin> r \\<Longrightarrow> (x, y) \\<in> asym_factor r\"\n  unfolding asym_factor_def by blast\n\nlemma asym_factorE[elim?]:\n  assumes \"(x, y) \\<in> asym_factor r\" obtains \"(x, y) \\<in> r\"\n  using assms unfolding asym_factor_def by blast\n\nlemma refl_not_in_asym_factor[simp]: \"(x, x) \\<notin> asym_factor r\"\n  unfolding asym_factor_def by blast\n\nlemma irrefl_asym_factor[simp]: \"irrefl (asym_factor r)\"\n  unfolding asym_factor_def irrefl_def by fast\n\nlemma asym_asym_factor[simp]: \"asym (asym_factor r)\"\n  using irrefl_asym_factor\n  by (auto intro!: asymI simp: asym_factor_def)\n\nlemma trans_asym_factor[simp]: \"trans r \\<Longrightarrow> trans (asym_factor r)\"\n  unfolding asym_factor_def trans_def by fast\n\nlemma asym_if_irrefl_trans: \"irrefl r \\<Longrightarrow> trans r \\<Longrightarrow> asym r\"\n  by (intro asymI) (auto simp: irrefl_def trans_def)\n\nlemma antisym_if_irrefl_trans: \"irrefl r \\<Longrightarrow> trans r \\<Longrightarrow> antisym r\"\n  using antisym_def asym.cases asym_if_irrefl_trans by auto\n    \nlemma asym_factor_asym_rel[simp]: \"asym r \\<Longrightarrow> asym_factor r = r\"\n  unfolding asym_factor_def\n  by (cases r rule: asym.cases) auto\n\nlemma irrefl_trans_asym_factor_id[simp]: \"irrefl r \\<Longrightarrow> trans r \\<Longrightarrow> asym_factor r = r\"\n  using asym_factor_asym_rel[OF asym_if_irrefl_trans] .\n\nlemma asym_factor_id[simp]: \"asym_factor (asym_factor r) = asym_factor r\"\n  using asym_factor_asym_rel[OF asym_asym_factor] .\n\nlemma asym_factor_rtrancl: \"asym_factor (r\\<^sup>*) = asym_factor (r\\<^sup>+)\"\n  unfolding asym_factor_def\n  by (auto simp add: rtrancl_eq_or_trancl)\n\nlemma asym_factor_Restr[simp]: \"asym_factor (Restr r A) = Restr (asym_factor r) A\"\n  unfolding asym_factor_def by blast\n\nlemma acyclic_asym_factor[simp]: \"acyclic r \\<Longrightarrow> acyclic (asym_factor r)\"\n  unfolding asym_factor_def by (auto intro: acyclic_subset)\n\n\nsubsubsection \\<open>Relations between symmetric and asymmetric factor\\<close>\n\ntext \\<open>\n  We prove that \\<^term>\\<open>sym_factor\\<close> and \\<^term>\\<open>asym_factor\\<close> partition the input relation.\n\\<close>\nlemma sym_asym_factor_Un: \"sym_factor r \\<union> asym_factor r = r\"\n  unfolding sym_factor_def asym_factor_def by blast\n\nlemma disjnt_sym_asym_factor[simp]: \"disjnt (sym_factor r) (asym_factor r)\"\n  unfolding disjnt_def\n  unfolding sym_factor_def asym_factor_def by blast\n\nlemma Field_sym_asym_factor_Un:\n  \"Field (sym_factor r) \\<union> Field (asym_factor r) = Field r\"\n  using sym_asym_factor_Un Field_Un by metis\n\nlemma asym_factor_tranclE:\n  assumes \"(a, b) \\<in> (asym_factor r)\\<^sup>+\" shows \"(a, b) \\<in> r\\<^sup>+\"\n  using assms sym_asym_factor_Un\n  by (metis UnCI subsetI trancl_mono)\n\n\nsubsection \\<open>Extension of Orders\\<close>\n\ntext \\<open>\n  We use the definition of Bossert and Suzumura for \\<open>extends\\<close>. The requirement \\<^term>\\<open>r \\<subseteq> R\\<close> is\n  obvious. The second requirement \\<^term>\\<open>asym_factor r \\<subseteq> asym_factor R\\<close> enforces that the \n  extension \\<^term>\\<open>R\\<close> maintains all strict preferences of \\<^term>\\<open>r\\<close> (viewing \\<^term>\\<open>r\\<close> as a \n  preference relation).\n\\<close>\n                    \ndefinition extends :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"extends R r \\<equiv> r \\<subseteq> R \\<and> asym_factor r \\<subseteq> asym_factor R\"\n\ntext \\<open>\n  We define a stronger notion of \\<^term>\\<open>extends\\<close> where we also demand that\n  \\<^term>\\<open>sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\\<close>. This enforces that the extension does not introduce\n  preference cycles between previously unrelated pairs \\<^term>\\<open>(x, y) \\<in> R - r\\<close>.\n\\<close>\n\ndefinition strict_extends :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"strict_extends R r \\<equiv> extends R r \\<and> sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\"\n\nlemma extendsI[intro]: \"r \\<subseteq> R \\<Longrightarrow> asym_factor r \\<subseteq> asym_factor R \\<Longrightarrow> extends R r\"\n  unfolding extends_def by (intro conjI)\n\nlemma extendsE:\n  assumes \"extends R r\"\n  obtains \"r \\<subseteq> R\" \"asym_factor r \\<subseteq> asym_factor R\"\n  using assms unfolding extends_def by blast\n\nlemma trancl_subs_extends_if_trans: \"extends r_ext r \\<Longrightarrow> trans r_ext \\<Longrightarrow> r\\<^sup>+ \\<subseteq> r_ext\"\n  unfolding extends_def asym_factor_def\n  by (metis subrelI trancl_id trancl_mono)\n\nlemma extends_if_strict_extends: \"strict_extends r_ext ext \\<Longrightarrow> extends r_ext ext\"\n  unfolding strict_extends_def by blast\n\nlemma strict_extendsI[intro]:\n  assumes \"r \\<subseteq> R\" \"asym_factor r \\<subseteq> asym_factor R\" \"sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\"\n  shows \"strict_extends R r\"\n  unfolding strict_extends_def using assms by (intro conjI extendsI)\n\nlemma strict_extendsE:\n  assumes \"strict_extends R r\"\n  obtains \"r \\<subseteq> R\" \"asym_factor r \\<subseteq> asym_factor R\" \"sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\"\n  using assms extendsE unfolding strict_extends_def by blast\n\nlemma strict_extends_antisym_Restr:\n  assumes \"strict_extends R r\"\n  assumes \"antisym (Restr r A)\"\n  shows \"antisym ((R - r) \\<union> Restr r A)\"\nproof(rule antisymI, rule ccontr)\n  fix x y assume \"(x, y) \\<in> (R - r) \\<union> Restr r A\" \"(y, x) \\<in> (R - r) \\<union> Restr r A\" \"x \\<noteq> y\"\n  with \\<open>strict_extends R r\\<close> have \"(x, y) \\<in> sym_factor R\"\n    unfolding sym_factor_def by (auto elim!: strict_extendsE)\n  with assms \\<open>x \\<noteq> y\\<close> have \"(x, y) \\<in> sym_factor r\"\n    by (auto elim!: strict_extendsE)\n  then have \"(x, y) \\<in> r\" \"(y, x) \\<in> r\"\n    unfolding sym_factor_def by simp_all\n  with \\<open>antisym (Restr r A)\\<close> \\<open>x \\<noteq> y\\<close> \\<open>(y, x) \\<in> R - r \\<union> Restr r A\\<close> show False\n    using antisymD by fastforce\nqed\n\ntext \\<open>Here we prove that we have no preference cycles between previously unrelated pairs.\\<close>\nlemma antisym_Diff_if_strict_extends:\n  assumes \"strict_extends R r\"\n  shows \"antisym (R - r)\"\n  using strict_extends_antisym_Restr[OF assms, where ?A=\"{}\"] by simp\n\nlemma strict_extends_antisym:\n  assumes \"strict_extends R r\"\n  assumes \"antisym r\"\n  shows \"antisym R\"\n  using assms strict_extends_antisym_Restr[OF assms(1), where ?A=UNIV]\n  by (auto elim!: strict_extendsE simp: antisym_def) \n\nlemma strict_extends_if_strict_extends_reflc:\n  assumes \"strict_extends r_ext (r\\<^sup>=)\"\n  shows \"strict_extends r_ext r\"\nproof(intro strict_extendsI)\n  from assms show \"r \\<subseteq> r_ext\"\n    by (auto elim: strict_extendsE)\n\n  from assms \\<open>r \\<subseteq> r_ext\\<close> show \"asym_factor r \\<subseteq> asym_factor r_ext\"\n    unfolding strict_extends_def\n    by (auto simp: asym_factor_def sym_factor_def)\n\n  from assms show \"sym_factor r_ext \\<subseteq> (sym_factor r)\\<^sup>=\"\n    by (auto simp: sym_factor_def strict_extends_def)\nqed\n\nlemma strict_extends_diff_Id:\n  assumes \"irrefl r\" \"trans r\"\n  assumes \"strict_extends r_ext (r\\<^sup>=)\"\n  shows \"strict_extends (r_ext - Id) r\"\nproof(intro strict_extendsI)\n  from assms show \"r \\<subseteq> r_ext - Id\"\n    by (auto elim: strict_extendsE simp: irrefl_def)\n\n  note antisym_r = antisym_if_irrefl_trans[OF assms(1,2)]\n  with assms strict_extends_if_strict_extends_reflc show \"asym_factor r \\<subseteq> asym_factor (r_ext - Id)\"\n    unfolding asym_factor_def\n    by (auto intro: strict_extends_antisym[THEN antisymD] elim: strict_extendsE transE)\n\n  from assms antisym_r show \"sym_factor (r_ext - Id) \\<subseteq> (sym_factor r)\\<^sup>=\"\n    unfolding sym_factor_def\n    by (auto intro: strict_extends_antisym[THEN antisymD])\nqed\n\ntext \\<open>\n  Both \\<^term>\\<open>extends\\<close> and \\<^term>\\<open>strict_extends\\<close> form a partial order since they\n  are reflexive, transitive, and antisymmetric.\n\\<close>\nlemma shows\n    reflp_extends: \"reflp extends\" and\n    transp_extends: \"transp extends\" and\n    antisymp_extends: \"antisymp extends\"\n  unfolding extends_def reflp_def transp_def antisymp_def\n  by auto\n\nlemma shows\n    reflp_strict_extends: \"reflp strict_extends\" and\n    transp_strict_extends: \"transp strict_extends\" and\n    antisymp_strict_extends: \"antisymp strict_extends\"\n  using reflp_extends transp_extends antisymp_extends\n  unfolding strict_extends_def reflp_def transp_def antisymp_def\n  by auto\n\nsubsection \\<open>Missing order definitions\\<close>\n\nlemma preorder_onD[dest?]:\n  assumes \"preorder_on A r\"\n  shows \"refl_on A r\" \"trans r\"\n  using assms unfolding preorder_on_def by blast+\n\nlemma preorder_onI[intro]: \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> preorder_on A r\"\n  unfolding preorder_on_def by (intro conjI)\n\nabbreviation \"preorder \\<equiv> preorder_on UNIV\"\n\nlemma preorder_rtrancl: \"preorder (r\\<^sup>*)\"\n  by (intro preorder_onI refl_rtrancl trans_rtrancl)\n\ndefinition \"total_preorder_on A r \\<equiv> preorder_on A r \\<and> total_on A r\"\n\nabbreviation \"total_preorder r \\<equiv> total_preorder_on UNIV r\"\n\nlemma total_preorder_onI[intro]:\n  \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> total_on A r \\<Longrightarrow> total_preorder_on A r\"\n  unfolding total_preorder_on_def by (intro conjI preorder_onI)\n\nlemma total_preorder_onD[dest?]:\n  assumes \"total_preorder_on A r\"\n  shows \"refl_on A r\" \"trans r\" \"total_on A r\"\n  using assms unfolding total_preorder_on_def preorder_on_def by blast+\n\ndefinition \"strict_partial_order r \\<equiv> trans r \\<and> irrefl r\"\n\nlemma strict_partial_orderI[intro]:\n  \"trans r \\<Longrightarrow> irrefl r \\<Longrightarrow> strict_partial_order r\"\n  unfolding strict_partial_order_def by blast\n\nlemma strict_partial_orderD[dest?]:\n  assumes \"strict_partial_order r\"\n  shows \"trans r\" \"irrefl r\"\n  using assms unfolding strict_partial_order_def by blast+\n\nlemma strict_partial_order_acyclic:\n  assumes \"strict_partial_order r\"\n  shows \"acyclic r\"\n  by (metis acyclic_irrefl assms strict_partial_order_def trancl_id)\n\n\nabbreviation \"partial_order \\<equiv> partial_order_on UNIV\"\n\nlemma partial_order_onI[intro]:\n  \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> antisym r \\<Longrightarrow> partial_order_on A r\"\n  using partial_order_on_def by blast\n\nlemma linear_order_onI[intro]:\n  \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> antisym r \\<Longrightarrow> total_on A r \\<Longrightarrow> linear_order_on A r\"\n  using linear_order_on_def by blast\n\nlemma linear_order_onD[dest?]:\n  assumes \"linear_order_on A r\"\n  shows \"refl_on A r\" \"trans r\" \"antisym r\" \"total_on A r\"\n  using assms[unfolded linear_order_on_def] partial_order_onD by blast+\n\ntext \\<open>A typical example is \\<^term>\\<open>(\\<subset>)\\<close> on sets:\\<close>\n\nlemma strict_partial_order_subset:\n  \"strict_partial_order {(x,y). x \\<subset> y}\"\nproof\n  show \"trans {(x,y). x \\<subset> y}\"\n    by (auto simp add: trans_def)\n  show \"irrefl {(x, y). x \\<subset> y}\"\n    by (simp add: irrefl_def)\nqed\n\ntext \\<open>We already have a definition of a strict linear order in \\<^term>\\<open>strict_linear_order\\<close>.\\<close>\n\nsection \\<open>Extending preorders to total preorders\\<close>\n\ntext \\<open>\n  We start by proving that a preorder with two incomparable elements \\<^term>\\<open>x\\<close> and \\<^term>\\<open>y\\<close> can be\n  strictly extended to a preorder where \\<^term>\\<open>x < y\\<close>.\n\\<close>\n\nlemma can_extend_preorder: \n  assumes \"preorder_on A r\"\n    and \"y \\<in> A\" \"x \\<in> A\" \"(y, x) \\<notin> r\"\n  shows\n    \"preorder_on A ((insert (x, y) r)\\<^sup>+)\" \"strict_extends ((insert (x, y) r)\\<^sup>+) r\"\nproof -\n  note preorder_onD[OF \\<open>preorder_on A r\\<close>]\n  then have \"insert (x, y) r \\<subseteq> A \\<times> A\"\n    using \\<open>y \\<in> A\\<close> \\<open>x \\<in> A\\<close> refl_on_domain by fast\n  with \\<open>refl_on A r\\<close> show \"preorder_on A ((insert (x, y) r)\\<^sup>+)\"\n    by (intro preorder_onI refl_onI trans_trancl)\n       (auto simp: trancl_subset_Sigma intro!: r_into_trancl' dest: refl_onD)\n\n  show \"strict_extends ((insert (x, y) r)\\<^sup>+) r\"\n  proof(intro strict_extendsI)\n    from preorder_onD(2)[OF \\<open>preorder_on A r\\<close>] \\<open>(y, x) \\<notin> r\\<close>\n    show \"asym_factor r \\<subseteq> asym_factor ((insert (x, y) r)\\<^sup>+)\"\n       unfolding asym_factor_def trancl_insert\n       using rtranclD rtrancl_into_trancl1 r_r_into_trancl\n       by fastforce\n\n     from assms have \"(y, x) \\<notin> (insert (x, y) r)\\<^sup>+\"\n       unfolding preorder_on_def trancl_insert\n       using refl_onD rtranclD by fastforce\n     with \\<open>trans r\\<close> show \"sym_factor ((insert (x, y) r)\\<^sup>+) \\<subseteq> (sym_factor r)\\<^sup>=\"\n       unfolding trancl_insert sym_factor_def by (fastforce intro: rtrancl_trans)\n  qed auto\nqed\n\n\ntext \\<open>\n  With this, we can start the proof of our main extension theorem.\n  For this we will use a variant of Zorns Lemma, which only considers nonempty chains:\n\\<close>\nlemma Zorns_po_lemma_nonempty:\n  assumes po: \"Partial_order r\"\n    and u: \"\\<And>C. \\<lbrakk>C \\<in> Chains r; C\\<noteq>{}\\<rbrakk> \\<Longrightarrow> \\<exists>u\\<in>Field r. \\<forall>a\\<in>C. (a, u) \\<in> r\"\n    and \"r \\<noteq> {}\"\n  shows \"\\<exists>m\\<in>Field r. \\<forall>a\\<in>Field r. (m, a) \\<in> r \\<longrightarrow> a = m\"\nproof -\n  from \\<open>r \\<noteq> {}\\<close> obtain x where \"x \\<in> Field r\"\n    using FieldI2 by fastforce\n  with assms show ?thesis\n    using Zorns_po_lemma by (metis empty_iff)  \nqed\n\n\ntheorem strict_extends_preorder_on:\n  assumes \"preorder_on A base_r\"\n  shows \"\\<exists>r. total_preorder_on A r \\<and> strict_extends r base_r\" \nproof -\n\n  text \\<open>\n    We define an order on the set of strict extensions of the base relation \\<^term>\\<open>base_r\\<close>, \n    where \\<^term>\\<open>r \\<le> s\\<close> iff \\<^term>\\<open>strict_extends r base_r\\<close> and \\<^term>\\<open>strict_extends s r\\<close>:\n  \\<close>\n\n  define order_of_orders :: \"('a rel) rel\" where \"order_of_orders =\n    Restr {(r, s). strict_extends r base_r \\<and> strict_extends s r} {r. preorder_on A r}\"\n\n  text \\<open>\n    We show that this order consists of those relations that are preorders and that strictly extend\n    the base relation \\<^term>\\<open>base_r\\<close>\n  \\<close>\n\n  have Field_order_of_orders: \"Field order_of_orders =\n    {r. preorder_on A r \\<and> strict_extends r base_r}\"\n    using transp_strict_extends\n  proof(safe)\n    fix r assume \"preorder_on A r\" \"strict_extends r base_r\"\n    with reflp_strict_extends have\n      \"(r, r) \\<in> {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      by (auto elim!: reflpE)\n    with \\<open>preorder_on A r\\<close> show \"r \\<in> Field order_of_orders\"\n      unfolding order_of_orders_def by (auto simp: Field_def)\n  qed (auto simp: order_of_orders_def Field_def elim: transpE)\n\n  text \\<open>\n    We now show that this set has a maximum and that any maximum of this set is a total preorder\n    and as thus is one of the extensions we are looking for.\n    We begin by showing the existence of a maximal element using Zorn's lemma.\n  \\<close>\n\n  have \"\\<exists>m \\<in> Field order_of_orders.\n      \\<forall>a \\<in> Field order_of_orders. (m, a) \\<in> order_of_orders \\<longrightarrow> a = m\"\n  proof (rule Zorns_po_lemma_nonempty)\n\n    text \\<open>\n      Zorn's Lemma requires us to prove that our \\<^term>\\<open>order_of_orders\\<close> is a nonempty partial order\n      and that every nonempty chain has an upper bound. \n      The partial order property is trivial, since we used \\<^term>\\<open>strict_extends\\<close> for the relation, \n      which is a partial order as shown above.\n    \\<close>\n\n    from reflp_strict_extends transp_strict_extends\n    have \"Refl {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      unfolding refl_on_def Field_def by (auto elim: transpE reflpE)\n    moreover have \"trans {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      using transp_strict_extends  by (auto elim: transpE intro: transI)\n    moreover have \"antisym {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      using antisymp_strict_extends by (fastforce dest: antisympD intro: antisymI)\n\n    ultimately show \"Partial_order order_of_orders\"\n      unfolding order_of_orders_def order_on_defs\n      using Field_order_of_orders Refl_Restr trans_Restr antisym_Restr\n      by blast\n\n    text \\<open>Also, our order is obviously not empty since it contains \\<^term>\\<open>(base_r, base_r)\\<close>:\\<close>\n\n    have \"(base_r, base_r) \\<in> order_of_orders\"\n      unfolding order_of_orders_def\n      using assms reflp_strict_extends by (auto dest: reflpD)\n    thus \"order_of_orders \\<noteq> {}\" by force\n\n\n    text \\<open>\n      Next we show that each chain has an upper bound.\n      For the upper bound we take the union of all relations in the chain.\n    \\<close>\n\n    show \"\\<exists>u \\<in> Field order_of_orders. \\<forall>a \\<in> C. (a, u) \\<in> order_of_orders\" \n      if C_def: \"C \\<in> Chains order_of_orders\" and C_nonempty: \"C \\<noteq> {}\"\n      for C\n    proof (rule bexI[where x=\"\\<Union>C\"])\n\n      text \\<open>\n        Obviously each element in the chain is a strict extension of \\<^term>\\<open>base_r\\<close> by definition\n        and as such it is also a preorder.\n      \\<close>\n\n      have preorder_r: \"preorder_on A r\" and extends_r: \"strict_extends r base_r\" if \"r \\<in> C\" for r\n        using that C_def[unfolded order_of_orders_def Chains_def] by blast+\n\n      text \\<open>\n        Because a chain is partially ordered, the union of the chain is reflexive and transitive.\n      \\<close>\n\n      have total_subs_C: \"r \\<subseteq> s \\<or> s \\<subseteq> r\" if \"r \\<in> C\" and \"s \\<in> C\" for r s\n        using C_def that\n        unfolding Chains_def order_of_orders_def strict_extends_def extends_def\n        by blast\n\n      have preorder_UnC: \"preorder_on A (\\<Union>C)\"\n      proof(intro preorder_onI)\n        show \"refl_on A (\\<Union>C)\"\n          using preorder_onD(1)[OF preorder_r] C_nonempty\n          unfolding refl_on_def by auto\n\n        from total_subs_C show \"trans (\\<Union>C)\"\n          using chain_subset_trans_Union[unfolded chain_subset_def]\n          by (metis preorder_onD(2)[OF preorder_r])\n      qed\n\n      text \\<open>We show that \\<^term>\\<open>\\<Union>C\\<close> strictly extends the base relation.\\<close>\n    \n      have strict_extends_UnC: \"strict_extends (\\<Union>C) base_r\"\n      proof(intro strict_extendsI)\n        note extends_r_unfolded = extends_r[unfolded extends_def strict_extends_def]\n\n        show \"base_r \\<subseteq> (\\<Union>C)\"\n          using C_nonempty extends_r_unfolded\n          by blast\n\n        then show \"asym_factor base_r \\<subseteq> asym_factor (\\<Union>C)\"\n          using extends_r_unfolded\n          unfolding asym_factor_def by auto\n\n        show \"sym_factor (\\<Union>C) \\<subseteq> (sym_factor base_r)\\<^sup>=\"\n        proof(safe)\n          fix x y assume \"(x, y) \\<in> sym_factor (\\<Union>C)\" \"(x, y) \\<notin> sym_factor base_r\"\n          then have \"(x, y) \\<in> \\<Union>C\" \"(y, x) \\<in> \\<Union>C\"\n            unfolding sym_factor_def by blast+\n\n          with extends_r obtain c where \"c \\<in> C\" \"(x, y) \\<in> c\" \"(y, x) \\<in> c\"\n            \"strict_extends c base_r\"\n            using total_subs_C by blast\n          then have \"(x, y) \\<in> sym_factor c\"\n            unfolding sym_factor_def by blast\n          with \\<open>strict_extends c base_r\\<close> \\<open>(x, y) \\<notin> sym_factor base_r\\<close>\n          show \"x = y\"\n            unfolding strict_extends_def by blast\n        qed\n      qed\n\n      from preorder_UnC strict_extends_UnC show \"(\\<Union>C) \\<in> Field order_of_orders\"\n        unfolding Field_order_of_orders by simp\n\n      text \\<open>\n        Lastly, we prove by contradiction that \\<^term>\\<open>\\<Union>C\\<close> is an upper bound for the chain.\n      \\<close>\n\n      show \"\\<forall>a \\<in> C. (a, \\<Union>C) \\<in> order_of_orders\"\n      proof(rule ccontr)\n        presume \"\\<exists>a \\<in> C. (a, \\<Union>C) \\<notin> order_of_orders\"\n        then obtain m where m: \"m \\<in> C\" \"(m, \\<Union>C) \\<notin> order_of_orders\"\n          by blast\n\n        hence strict_extends_m: \"strict_extends m base_r\" \"preorder_on A m\"\n          using extends_r preorder_r by blast+\n        with m have \"\\<not> strict_extends (\\<Union>C) m\"\n          using preorder_UnC unfolding order_of_orders_def by blast\n\n        from m have \"m \\<subseteq> \\<Union>C\"\n          by blast\n        moreover\n        have \"sym_factor (\\<Union>C) \\<subseteq> (sym_factor m)\\<^sup>=\"\n        proof(safe)\n          fix a b\n          assume \"(a, b) \\<in> sym_factor (\\<Union> C)\" \"(a, b) \\<notin> sym_factor m\"\n          then have \"(a, b) \\<in> sym_factor base_r \\<or> (a, b) \\<in> Id\"\n            using strict_extends_UnC[unfolded strict_extends_def] by blast\n          with \\<open>(a, b) \\<notin> sym_factor m\\<close> strict_extends_m(1) show \"a = b\"\n            by (auto elim: strict_extendsE simp: sym_factor_mono[THEN in_mono])\n        qed\n        ultimately\n        have \"\\<not> asym_factor m \\<subseteq> asym_factor (\\<Union>C)\"\n          using \\<open>\\<not> strict_extends (\\<Union>C) m\\<close> unfolding strict_extends_def extends_def by blast\n\n        then obtain x y where\n          \"(x, y) \\<in> m\" \"(y, x) \\<notin> m\" \"(x, y) \\<in> asym_factor m\" \"(x, y) \\<notin> asym_factor (\\<Union>C)\"\n          unfolding asym_factor_def by blast\n    \n        then obtain w where \"w \\<in> C\" \"(y, x) \\<in> w\"\n          unfolding asym_factor_def using \\<open>m \\<in> C\\<close> by auto\n\n        with \\<open>(y, x) \\<notin> m\\<close> have \"\\<not> extends m w\"\n          unfolding extends_def by auto\n        moreover\n        from \\<open>(x, y) \\<in> m\\<close> have \"\\<not> extends w m\"\n        proof(cases \"(x, y) \\<in> w\")\n          case True\n          with \\<open>(y, x) \\<in> w\\<close> have \"(x, y) \\<notin> asym_factor w\"\n            unfolding asym_factor_def by simp\n          with \\<open>(x, y) \\<in> asym_factor m\\<close> show \"\\<not> extends w m\"\n            unfolding extends_def by auto\n        qed (auto simp: extends_def)\n\n        ultimately show False\n          using \\<open>m \\<in> C\\<close> \\<open>w \\<in> C\\<close>\n          using C_def[unfolded Chains_def order_of_orders_def strict_extends_def]\n          by auto\n      qed blast\n    qed\n  qed\n\n  text \\<open>Let our maximal element be named \\<^term>\\<open>max\\<close>:\\<close>\n\n  from this obtain max \n    where max_field: \"max \\<in> Field order_of_orders\"\n      and is_max: \n        \"\\<forall>a\\<in>Field order_of_orders. (max, a) \\<in> order_of_orders \\<longrightarrow> a = max\"\n    by auto\n\n  from max_field have max_extends_base: \"preorder_on A max\" \"strict_extends max base_r\"\n    using Field_order_of_orders by blast+\n\n  text \\<open>\n    We still have to show, that \\<^term>\\<open>max\\<close> is a strict linear order,\n    meaning that it is also a total order:\n  \\<close>\n\n  have \"total_on A max\"\n  proof\n    fix x y :: 'a\n    assume \"x \\<noteq> y\" \"x \\<in> A\" \"y \\<in> A\"\n\n    show \"(x, y) \\<in> max \\<or> (y, x) \\<in> max\"\n    proof (rule ccontr)\n\n      text \\<open>\n        Assume that \\<^term>\\<open>max\\<close> is not total, and \\<^term>\\<open>x\\<close> and \\<^term>\\<open>y\\<close> are incomparable.\n        Then we can extend \\<^term>\\<open>max\\<close> by setting $x < y$:\n      \\<close>\n\n      presume \"(x, y) \\<notin> max\" and \"(y, x) \\<notin> max\"\n      let ?max' = \"(insert (x, y) max)\\<^sup>+\"\n\n      note max'_extends_max = can_extend_preorder[OF\n          \\<open>preorder_on A max\\<close> \\<open>y \\<in> A\\<close> \\<open>x \\<in> A\\<close> \\<open>(y, x) \\<notin> max\\<close>]\n\n      hence max'_extends_base: \"strict_extends ?max' base_r\"\n        using \\<open>strict_extends max base_r\\<close> transp_strict_extends by (auto elim: transpE)\n\n\n      text \\<open>The extended relation is greater than \\<^term>\\<open>max\\<close>, which is a contradiction.\\<close>\n\n      have \"(max, ?max') \\<in> order_of_orders\"\n        using max'_extends_base max'_extends_max max_extends_base\n        unfolding order_of_orders_def by simp\n      thus False\n        using FieldI2 \\<open>(x, y) \\<notin> max\\<close> is_max by fastforce\n    qed simp_all\n  qed\n\n  with \\<open>preorder_on A max\\<close> have \"total_preorder_on A max\"\n    unfolding total_preorder_on_def by simp\n\n  with \\<open>strict_extends max base_r\\<close> show \"?thesis\" by blast\nqed\n\ntext \\<open>\n  With this extension theorem, we can easily prove Szpilrajn's theorem and its equivalent for\n  partial orders.\n\\<close>\n\ncorollary partial_order_extension:\n  assumes \"partial_order_on A r\"\n  shows \"\\<exists>r_ext. linear_order_on A r_ext \\<and> r \\<subseteq> r_ext\"\nproof -\n  from assms strict_extends_preorder_on obtain r_ext where r_ext:\n    \"total_preorder_on A r_ext\" \"strict_extends r_ext r\"\n    unfolding partial_order_on_def by blast\n\n  with assms have \"antisym r_ext\"\n    unfolding partial_order_on_def using strict_extends_antisym by blast\n\n  with assms r_ext have \"linear_order_on A r_ext \\<and> r \\<subseteq> r_ext\"\n    unfolding total_preorder_on_def order_on_defs strict_extends_def extends_def\n    by blast\n  then show ?thesis ..\nqed\n\ncorollary Szpilrajn:\n  assumes \"strict_partial_order r\"\n  shows \"\\<exists>r_ext. strict_linear_order r_ext \\<and> r \\<subseteq> r_ext\"\nproof -\n  from assms have \"partial_order (r\\<^sup>=)\"\n    by (auto simp: antisym_if_irrefl_trans strict_partial_order_def)\n  from partial_order_extension[OF this] obtain r_ext where \"linear_order r_ext\" \"(r\\<^sup>=) \\<subseteq> r_ext\"\n    by blast\n  with assms have \"r \\<subseteq> r_ext - Id\" \"strict_linear_order (r_ext - Id)\"\n    by (auto simp: irrefl_def strict_linear_order_on_diff_Id dest: strict_partial_orderD(2))\n  then show ?thesis by blast\nqed\n\ncorollary acyclic_order_extension:\n  assumes \"acyclic r\"\n  shows \"\\<exists>r_ext. strict_linear_order r_ext \\<and> r \\<subseteq> r_ext\"\nproof -\n  from assms have \"strict_partial_order (r\\<^sup>+)\"\n    unfolding strict_partial_order_def using acyclic_irrefl trans_trancl by blast\n  thus ?thesis\n    by (meson Szpilrajn r_into_trancl' subset_iff)\nqed\n\nsection \\<open>Consistency\\<close>\n\ntext \\<open>\n  As a weakening of transitivity, Suzumura introduces the notion of consistency which rules out\n  all preference cycles that contain at least one strict preference.\n  Consistency characterises those order relations which can be extended (in terms of \\<^term>\\<open>extends\\<close>)\n  to a total order relation. \n\\<close>\n\ndefinition consistent :: \"'a rel \\<Rightarrow> bool\"\n  where \"consistent r = (\\<forall>(x, y) \\<in> r\\<^sup>+. (y, x) \\<notin> asym_factor r)\"\n\nlemma consistentI: \"(\\<And>x y. (x, y) \\<in> r\\<^sup>+ \\<Longrightarrow> (y, x) \\<notin> asym_factor r) \\<Longrightarrow> consistent r\"\n  unfolding consistent_def by blast\n\nlemma consistent_if_preorder_on[simp]:\n  \"preorder_on A r \\<Longrightarrow> consistent r\"\n  unfolding preorder_on_def consistent_def asym_factor_def by auto\n\nlemma consistent_asym_factor[simp]: \"consistent r \\<Longrightarrow> consistent (asym_factor r)\"\n  unfolding consistent_def\n  using asym_factor_tranclE by fastforce\n\nlemma acyclic_asym_factor_if_consistent[simp]: \"consistent r \\<Longrightarrow> acyclic (asym_factor r)\"\n  unfolding consistent_def acyclic_def\n  using asym_factor_tranclE by (metis case_prodD trancl.simps)\n\nlemma consistent_Restr[simp]: \"consistent r \\<Longrightarrow> consistent (Restr r A)\"\n  unfolding consistent_def asym_factor_def\n  using trancl_mono by fastforce\n\ntext \\<open>\n  This corresponds to Theorem 2.2~@{cite \"Bossert:2010\"}.\n\\<close>\ntheorem trans_if_refl_total_consistent:\n  assumes \"refl r\" \"total r\" and \"consistent r\"\n  shows \"trans r\"\nproof\n  fix x y z assume \"(x, y) \\<in> r\" \"(y, z) \\<in> r\"\n  \n  from \\<open>(x, y) \\<in> r\\<close> \\<open>(y, z) \\<in> r\\<close> have \"(x, z) \\<in> r\\<^sup>+\"\n    by simp\n  hence \"(z, x) \\<notin> asym_factor r\"\n    using \\<open>consistent r\\<close> unfolding consistent_def by blast\n  hence \"x \\<noteq> z \\<Longrightarrow> (x, z) \\<in> r\"\n    unfolding asym_factor_def using \\<open>total r\\<close>\n    by (auto simp: total_on_def)\n  then show \"(x, z) \\<in> r\"\n    apply(cases \"x = z\")\n    using refl_onD[OF \\<open>refl r\\<close>] by blast+ \nqed\n\n\nlemma order_extension_if_consistent:\n  assumes \"consistent r\"\n  obtains r_ext where \"extends r_ext r\" \"total_preorder r_ext\"  \nproof -\n  from assms have extends: \"extends (r\\<^sup>*) r\"\n    unfolding extends_def consistent_def asym_factor_def\n    using rtranclD by (fastforce simp: Field_def)\n  have preorder: \"preorder (r\\<^sup>*)\"\n    unfolding preorder_on_def using refl_on_def trans_def by fastforce\n\n  from strict_extends_preorder_on[OF preorder] extends obtain r_ext where\n    \"total_preorder r_ext\" \"extends r_ext r\"\n    using transpE[OF transp_extends] unfolding strict_extends_def by blast\n  then show thesis using that by blast\nqed\n\nlemma consistent_if_extends_trans:\n  assumes \"extends r_ext r\" \"trans r_ext\"\n  shows \"consistent r\"\nproof(rule consistentI, standard)\n  fix x y assume *: \"(x, y) \\<in> r\\<^sup>+\" \"(y, x) \\<in> asym_factor r\"\n  with assms have \"(x, y) \\<in> r_ext\"\n    using trancl_subs_extends_if_trans[OF assms] by blast\n  moreover from * assms have \"(x, y) \\<notin> r_ext\"\n    unfolding extends_def asym_factor_def by auto\n  ultimately show False by blast\nqed\n\ntext \\<open>\n  With Theorem 2.6~@{cite \"Bossert:2010\"}, we show that \\<^term>\\<open>consistent\\<close> characterises the existence\n  of order extensions.\n\\<close>\ncorollary order_extension_iff_consistent:\n  \"(\\<exists>r_ext. extends r_ext r \\<and> total_preorder r_ext) \\<longleftrightarrow> consistent r\"\n  using order_extension_if_consistent consistent_if_extends_trans\n  by (metis total_preorder_onD(2))\n\n\ntext \\<open>\n  The following theorem corresponds to Theorem 2.7~@{cite \"Bossert:2010\"}.\n  Bossert and Suzumura claim that this theorem generalises Szpilrajn's theorem; however, we cannot\n  use the theorem to strictly extend a given order \\<^term>\\<open>Q\\<close>. Therefore, it is not strong enough to\n  extend a strict partial order to a strict linear order. It works for total preorders (called \n  orderings by Bossert and Suzumura). Unfortunately, we were not able to generalise the theorem\n  to allow for strict extensions.\n\\<close>\n\ntheorem general_order_extension_iff_consistent:\n  assumes \"\\<And>x y. \\<lbrakk> x \\<in> S; y \\<in> S; x \\<noteq> y \\<rbrakk> \\<Longrightarrow> (x, y) \\<notin> Q\\<^sup>+\"\n  assumes \"total_preorder_on S Ord\"\n  shows \"(\\<exists>Ext. extends Ext Q \\<and> total_preorder Ext \\<and> Restr Ext S = Ord)\n     \\<longleftrightarrow> consistent Q\" (is \"?ExExt \\<longleftrightarrow> _\")\nproof\n  assume \"?ExExt\"\n  then obtain Ext where\n    \"extends Ext Q\"\n    \"refl Ext\" \"trans Ext\" \"total Ext\"\n    \"Restr Ext S = Restr Ord S\"\n    using total_preorder_onD by fast\n  show \"consistent Q\"\n  proof(rule consistentI)\n    fix x y assume \"(x, y) \\<in> Q\\<^sup>+\"\n    with \\<open>extends Ext Q\\<close> \\<open>trans Ext\\<close> have \"(x, y) \\<in> Ext\"\n      unfolding extends_def by (metis trancl_id trancl_mono)\n    then have \"(y, x) \\<notin> asym_factor Ext\"\n      unfolding asym_factor_def by blast\n    with \\<open>extends Ext Q\\<close> show \"(y, x) \\<notin> asym_factor Q\"\n      unfolding extends_def asym_factor_def by blast\n  qed\nnext\n  assume \"consistent Q\"\n\n  define Q' where \"Q' \\<equiv> Q\\<^sup>* \\<union> Ord \\<union> Ord O Q\\<^sup>* \\<union> Q\\<^sup>* O Ord \\<union> (Q\\<^sup>* O Ord) O Q\\<^sup>*\"\n\n  have \"refl (Q\\<^sup>*)\" \"trans (Q\\<^sup>*)\" \"refl_on S Ord\" \"trans Ord\" \"total_on S Ord\"\n    using refl_rtrancl trans_rtrancl total_preorder_onD[OF \\<open>total_preorder_on S Ord\\<close>]\n    by - assumption\n\n  have preorder_Q': \"preorder Q'\"\n  proof\n    show \"refl Q'\"\n      unfolding Q'_def refl_on_def by auto\n\n    from \\<open>trans (Q\\<^sup>*)\\<close> \\<open>refl_on S Ord\\<close> \\<open>trans Ord\\<close> show \"trans Q'\"\n      unfolding Q'_def[simplified]\n      apply(safe intro!: transI)\n      unfolding relcomp.simps\n      by (metis assms(1) refl_on_domain rtranclD transD)+\n  qed\n\n  have \"consistent Q'\"\n    using consistent_if_preorder_on preorder_Q' by blast\n\n  have \"extends Q' Q\"\n  proof(rule extendsI)\n    have \"Q \\<subseteq> Restr (Q\\<^sup>*) (Field Q)\"\n      by (auto intro: FieldI1 FieldI2)\n    then show \"Q \\<subseteq> Q'\"\n      unfolding Q'_def by blast\n\n    from \\<open>consistent Q\\<close> have consistentD: \"(x, y) \\<in> Q\\<^sup>+ \\<Longrightarrow> (y, x) \\<in> Q \\<Longrightarrow> (x, y) \\<in> Q\" for x y\n      unfolding consistent_def asym_factor_def using rtranclD by fastforce\n    have refl_on_domainE: \"\\<lbrakk> (x, y) \\<in> Ord; x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\" for x y P\n      using refl_on_domain[OF \\<open>refl_on S Ord\\<close>] by blast\n\n    show \"asym_factor Q \\<subseteq> asym_factor Q'\"\n      unfolding Q'_def asym_factor_def Field_def\n      apply(safe)\n      using assms(1) consistentD refl_on_domainE\n      by (metis r_into_rtrancl rtranclD rtrancl_trancl_trancl)+\n  qed\n\n  with strict_extends_preorder_on[OF \\<open>preorder Q'\\<close>]\n  obtain Ext where Ext: \"extends Ext Q'\" \"extends Ext Q\" \"total_preorder Ext\"\n    unfolding strict_extends_def\n    by (metis transpE transp_extends)\n\n  have not_in_Q': \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> (x, y) \\<notin> Ord \\<Longrightarrow> (x, y) \\<notin> Q'\" for x y\n    using assms(1) unfolding Q'_def\n    apply(safe)\n    by (metis \\<open>refl_on S Ord\\<close> refl_on_def refl_on_domain rtranclD)+\n\n  have \"Restr Ext S = Ord\"\n  proof\n    from \\<open>extends Ext Q'\\<close> have \"Ord \\<subseteq> Ext\"\n      unfolding Q'_def extends_def by auto\n    with \\<open>refl_on S Ord\\<close> show \"Ord \\<subseteq> Restr Ext S\"\n      using refl_on_domain by fast\n  next\n    have \"(x, y) \\<in> Ord\" if \"x \\<in> S\" and \"y \\<in> S\" and \"(x, y) \\<in> Ext\" for x y\n    proof(rule ccontr)\n      assume \"(x, y) \\<notin> Ord\"\n      with that not_in_Q' have \"(x, y) \\<notin> Q'\"\n        by blast\n      with \\<open>refl_on S Ord\\<close> \\<open>total_on S Ord\\<close> \\<open>x \\<in> S\\<close> \\<open>y \\<in> S\\<close> \\<open>(x, y) \\<notin> Ord\\<close>\n      have \"(y, x) \\<in> Ord\"\n        unfolding refl_on_def total_on_def by fast\n      hence \"(y, x) \\<in> Q'\"\n        unfolding Q'_def by blast\n      with \\<open>(x, y) \\<notin> Q'\\<close> \\<open>(y, x) \\<in> Q'\\<close> \\<open>extends Ext Q'\\<close>\n      have \"(x, y) \\<notin> Ext\"\n        unfolding extends_def asym_factor_def by auto\n      with \\<open>(x, y) \\<in> Ext\\<close> show False by blast\n    qed\n    then show \"Restr Ext S \\<subseteq> Ord\"\n      by blast\n  qed\n\n  with Ext show \"?ExExt\" by blast\nqed\n\nsection \\<open>Strong consistency\\<close>\n\ntext \\<open>\n  We define a stronger version of \\<^term>\\<open>consistent\\<close> which requires that the relation does not\n  contain hidden preference cycles, i.e. if there is a preference cycle then all the elements\n  in the cycle should already be related (in both directions).\n  In contrast to consistency which characterises relations that can be extended, strong consistency\n  characterises relations that can be extended strictly (cf. \\<^term>\\<open>strict_extends\\<close>).\n\\<close>\n\ndefinition \"strongly_consistent r \\<equiv> sym_factor (r\\<^sup>+) \\<subseteq> sym_factor (r\\<^sup>=)\"\n\nlemma consistent_if_strongly_consistent: \"strongly_consistent r \\<Longrightarrow> consistent r\"\n  unfolding strongly_consistent_def consistent_def\n  by (auto simp: sym_factor_def asym_factor_def) \n\nlemma strongly_consistentI: \"sym_factor (r\\<^sup>+) \\<subseteq> sym_factor (r\\<^sup>=) \\<Longrightarrow> strongly_consistent r\"\n  unfolding strongly_consistent_def by blast\n\nlemma strongly_consistent_if_trans_strict_extension:\n  assumes \"strict_extends r_ext r\"\n  assumes \"trans r_ext\"\n  shows   \"strongly_consistent r\"\nproof(unfold strongly_consistent_def, standard)\n  fix x assume \"x \\<in> sym_factor (r\\<^sup>+)\"\n  then show \"x \\<in> sym_factor (r\\<^sup>=)\"\n    using assms trancl_subs_extends_if_trans[OF extends_if_strict_extends]\n    by (metis sym_factor_mono strict_extendsE subsetD sym_factor_reflc)\nqed\n\nlemma strict_order_extension_if_consistent:\n  assumes \"strongly_consistent r\"\n  obtains r_ext where \"strict_extends r_ext r\" \"total_preorder r_ext\" \nproof -\n  from assms have \"strict_extends (r\\<^sup>+) r\"\n    unfolding strongly_consistent_def strict_extends_def extends_def asym_factor_def sym_factor_def\n    by (auto simp: Field_def dest: tranclD)\n  moreover have \"strict_extends (r\\<^sup>*) (r\\<^sup>+)\"\n    unfolding strict_extends_def extends_def\n    by (auto simp: asym_factor_rtrancl sym_factor_def dest: rtranclD)\n  ultimately have extends: \"strict_extends (r\\<^sup>*) r\"\n    using transpE[OF transp_strict_extends] by blast\n\n  have \"preorder (r\\<^sup>*)\"\n    unfolding preorder_on_def using refl_on_def trans_def by fastforce\n  from strict_extends_preorder_on[OF this] extends obtain r_ext where\n    \"total_preorder r_ext\" \"strict_extends r_ext r\"\n    using transpE[OF transp_strict_extends] by blast\n  then show thesis using that by blast\nqed\n\n\nexperiment begin\n\ntext \\<open>We can instantiate the above theorem to get Szpilrajn's theorem.\\<close>\nlemma\n  assumes \"strict_partial_order r\"\n  shows \"\\<exists>r_ext. strict_linear_order r_ext \\<and> r \\<subseteq> r_ext\"\nproof -                  \n  from assms[unfolded strict_partial_order_def] have \"strongly_consistent r\" \"antisym r\"\n    unfolding strongly_consistent_def by (simp_all add: antisym_if_irrefl_trans)\n  from strict_order_extension_if_consistent[OF this(1)] obtain r_ext\n    where \"strict_extends r_ext r\" \"total_preorder r_ext\" \n    by blast\n  with assms[unfolded strict_partial_order_def] \n  have \"trans (r_ext - Id)\" \"irrefl (r_ext - Id)\" \"total (r_ext - Id)\" \"r \\<subseteq> (r_ext - Id)\"\n    using strict_extends_antisym[OF _ \\<open>antisym r\\<close>]\n    by (auto simp: irrefl_def elim: strict_extendsE intro: trans_diff_Id dest: total_preorder_onD)\n  then show ?thesis\n    unfolding strict_linear_order_on_def by blast\nqed\n\nend\n\n \n(*<*)\nend\n(*>*)\n\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Szpilrajn/Szpilrajn.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8774767970940975, "lm_q1q2_score": 0.7812125260089264}}
{"text": "(*\n  File: FundamentalGroup.thy\n  Author: Bohua Zhan\n\n  Construction of the fundamental group.\n*)\n\ntheory FundamentalGroup\n  imports PathHomotopy\nbegin\n\nsection \\<open>Definition of fundamental group\\<close>\n\ndefinition is_loop :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_loop(f) \\<longleftrightarrow> (is_path(f) \\<and> f`(0\\<^sub>\\<real>) = f`(1\\<^sub>\\<real>))\"\n  \nlemma is_loopI [forward,backward]: \"is_path(f) \\<Longrightarrow> f`(0\\<^sub>\\<real>) = f`(1\\<^sub>\\<real>) \\<Longrightarrow> is_loop(f)\" by auto2\nlemma is_loopD [forward]:\n  \"is_loop(f) \\<Longrightarrow> is_path(f)\"\n  \"is_loop(f) \\<Longrightarrow> f`(0\\<^sub>\\<real>) = f`(1\\<^sub>\\<real>)\" by auto2+\nsetup {* del_prfstep_thm @{thm is_loop_def} *}\n  \nlemma const_is_loop:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> is_loop(const_mor(I,X,x))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm const_is_loop} [with_term \"const_mor(?I,?X,?x)\"] *}\n\nlemma product_is_loop:\n  \"is_loop(f) \\<Longrightarrow> is_loop(g) \\<Longrightarrow> target_str(f) = target_str(g) \\<Longrightarrow> f`(1\\<^sub>\\<real>) = g`(0\\<^sub>\\<real>) \\<Longrightarrow> is_loop(f \\<star> g)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm product_is_loop} [with_term \"?f \\<star> ?g\"] *}\n  \nlemma inv_path_is_loop [forward]:\n  \"is_loop(f) \\<Longrightarrow> is_loop(inv_path(f))\" by auto2\n\ndefinition loop_space :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"loop_space(X,x) = {f \\<in> I \\<rightharpoonup>\\<^sub>T X. f`(0\\<^sub>\\<real>) = x \\<and> f`(1\\<^sub>\\<real>) = x}\"\nsetup {* register_wellform_data (\"loop_space(X,x)\", [\"x \\<in>. X\"]) *}\n\ndefinition loop_space_rel :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"loop_space_rel(X,x) = Equiv(loop_space(X,x), \\<lambda>f g. path_homotopic(f,g))\"\nsetup {* register_wellform_data (\"loop_space_rel(X,x)\", [\"x \\<in>. X\"]) *}\n\nlemma loop_spaceI [typing]:\n  \"is_loop(f) \\<Longrightarrow> f \\<in> loop_space(target_str(f),f`(0\\<^sub>\\<real>))\" by auto2\n\nlemma loop_spaceD [forward]:\n  \"f \\<in> loop_space(X,x) \\<Longrightarrow> is_loop(f) \\<and> target_str(f) = X \\<and> f`(0\\<^sub>\\<real>) = x\" by auto2\nsetup {* del_prfstep_thm @{thm loop_space_def} *}\n    \nlemma loop_space_rel_is_rel [typing]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> loop_space_rel(X,x) \\<in> equiv_space(loop_space(X,x))\" by auto2\n\nlemma loop_space_rel_eval:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. \\<R> \\<Longrightarrow> g \\<in>. \\<R> \\<Longrightarrow> f \\<sim>\\<^sub>\\<R> g \\<longleftrightarrow> path_homotopic(f,g)\" by auto2\nsetup {* add_rewrite_rule_cond @{thm loop_space_rel_eval} [with_cond \"?f \\<noteq> ?g\"] *}\nsetup {* del_prfstep_thm @{thm loop_space_rel_def} *}\n  \nlemma const_mor_in_rel [typing]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow> const_mor(I,X,x) \\<in>. \\<R>\" by auto2\n\ndefinition loop_classes :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where loop_classes [rewrite_bidir]:\n  \"loop_classes(X,x) = loop_space(X,x) // loop_space_rel(X,x)\"\nsetup {* register_wellform_data (\"loop_classes(X,x)\", [\"x \\<in>. X\"]) *}\n\ndefinition fundamental_group :: \"i \\<Rightarrow> i \\<Rightarrow> i\" (\"\\<pi>\\<^sub>1\") where [rewrite]:\n  \"\\<pi>\\<^sub>1(X,x) = (let \\<R> = loop_space_rel(X,x) in\n    Group(loop_classes(X,x), equiv_class(\\<R>,const_mor(I,X,x)), \\<lambda>f g. equiv_class(\\<R>,rep(\\<R>,f) \\<star> rep(\\<R>,g))))\"\nsetup {* register_wellform_data (\"\\<pi>\\<^sub>1(X,x)\", [\"x \\<in>. X\"]) *}\n\nlemma fundamental_group_group_form:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> group_form(\\<pi>\\<^sub>1(X,x))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm fundamental_group_group_form} [with_term \"\\<pi>\\<^sub>1(?X,?x)\"] *}\n\nlemma fundamental_group_carrier [rewrite_bidir]:\n  \"carrier(\\<pi>\\<^sub>1(X,x)) = loop_classes(X,x)\" by auto2\n    \nlemma fundamental_group_evals [rewrite]:\n  \"G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<one>\\<^sub>G = equiv_class(loop_space_rel(X,x),const_mor(I,X,x))\"\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow> f \\<in>. G \\<Longrightarrow> g \\<in>. G \\<Longrightarrow>\n   f *\\<^sub>G g = equiv_class(\\<R>,rep(\\<R>,f) \\<star> rep(\\<R>,g))\" by auto2+\nsetup {* del_prfstep_thm @{thm fundamental_group_def} *}\n\nsection \\<open>Multiplication on the fundamental group\\<close>\n  \nlemma fundamental_group_mult_compat [resolve]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> compat_meta_bin(loop_space_rel(X,x), \\<lambda>f g. f \\<star> g)\" by auto2\n\nlemma fundamental_group_mult_eval [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. \\<R> \\<Longrightarrow> g \\<in>. \\<R> \\<Longrightarrow> equiv_class(\\<R>,f) *\\<^sub>G equiv_class(\\<R>,g) = equiv_class(\\<R>,f \\<star> g)\"\n@proof @have \"compat_meta_bin(loop_space_rel(X,x), \\<lambda>f g. f \\<star> g)\" @qed\nsetup {* del_prfstep_thm @{thm fundamental_group_mult_compat} *}\nsetup {* del_prfstep_thm @{thm fundamental_group_evals(2)} *}\n\nlemma fundamental_group_mult_assoc [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. G \\<Longrightarrow> g \\<in>. G \\<Longrightarrow> h \\<in>. G \\<Longrightarrow> f *\\<^sub>G g *\\<^sub>G h = f *\\<^sub>G (g *\\<^sub>G h)\"\n@proof @let \"f' = rep(\\<R>,f)\" \"g' = rep(\\<R>,g)\" \"h' = rep(\\<R>,h)\" @qed\n\nlemma fundamental_group_mult_id [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. G \\<Longrightarrow> f *\\<^sub>G \\<one>\\<^sub>G = f\"\n@proof @let \"f' = rep(\\<R>,f)\" @qed\n\nlemma fundamental_group_mult_id2 [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. G \\<Longrightarrow> \\<one>\\<^sub>G *\\<^sub>G f = f\"\n@proof @let \"f' = rep(\\<R>,f)\" @qed\n  \ndefinition fundamental_group_inv :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"fundamental_group_inv(\\<R>,f) = equiv_class(\\<R>,inv_path(rep(\\<R>,f)))\"\n\nlemma fundamental_group_inv_typing [typing]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. G \\<Longrightarrow> fundamental_group_inv(\\<R>,f) \\<in>. G\" by auto2\n\nlemma fundamental_group_inv2 [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   f \\<in>. G \\<Longrightarrow> fundamental_group_inv(\\<R>,f) *\\<^sub>G f = \\<one>\\<^sub>G\" by auto2\n\nlemma fundamental_group_is_group:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> is_group(\\<pi>\\<^sub>1(X,x))\"\n@proof\n  @let \"G = \\<pi>\\<^sub>1(X,x)\" \"\\<R> = loop_space_rel(X,x)\"\n  @have \"is_monoid(G)\"\n  @have \"\\<forall>f\\<in>.G. fundamental_group_inv(\\<R>,f) *\\<^sub>G f = \\<one>\\<^sub>G\"\n@qed\nsetup {* add_forward_prfstep_cond @{thm fundamental_group_is_group} [with_term \"\\<pi>\\<^sub>1(?X,?x)\"] *}\n\nsetup {* fold del_prfstep_thm [@{thm fundamental_group_mult_assoc},\n  @{thm fundamental_group_mult_id}, @{thm fundamental_group_mult_id2},\n  @{thm fundamental_group_inv2}] *}\n\nsection \\<open>Morphisms on fundamental groups\\<close>\n\ndefinition induced_mor :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"induced_mor(k,x) =\n    (let X = source_str(k) in let Y = target_str(k) in\n     let \\<R> = loop_space_rel(X,x) in let \\<S> = loop_space_rel(Y,k`x) in\n      Mor(\\<pi>\\<^sub>1(X,x), \\<pi>\\<^sub>1(Y,k`x), \\<lambda>f. equiv_class(\\<S>, k \\<circ>\\<^sub>m rep(\\<R>,f))))\"\nsetup {* register_wellform_data (\"induced_mor(k,x)\", [\"x \\<in> source(k)\"]) *}\n\nlemma induced_mor_is_morphism [typing]:\n  \"continuous(k) \\<Longrightarrow> X = source_str(k) \\<Longrightarrow> Y = target_str(k) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   induced_mor(k,x) \\<in> \\<pi>\\<^sub>1(X,x) \\<rightharpoonup> \\<pi>\\<^sub>1(Y,k`x)\" by auto2\n\nlemma induced_mor_eval [rewrite]:\n  \"continuous(k) \\<Longrightarrow> X = source_str(k) \\<Longrightarrow> Y = target_str(k) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   \\<R> = loop_space_rel(X,x) \\<Longrightarrow> \\<S> = loop_space_rel(Y,k`x) \\<Longrightarrow> f \\<in>. \\<R> \\<Longrightarrow>\n   induced_mor(k,x)`equiv_class(\\<R>,f) = equiv_class(\\<S>, k \\<circ>\\<^sub>m f)\" by auto2\nsetup {* del_prfstep_thm @{thm induced_mor_def} *}\n\nsetup {* add_rewrite_rule_back @{thm path_product_comp} *}\nlemma induced_mor_product [rewrite]:\n  \"continuous(k) \\<Longrightarrow> X = source_str(k) \\<Longrightarrow> Y = target_str(k) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> H = \\<pi>\\<^sub>1(Y,k`x) \\<Longrightarrow> f \\<in>. G \\<Longrightarrow> g \\<in>. G \\<Longrightarrow>\n   induced_mor(k,x)`(f *\\<^sub>G g) = induced_mor(k,x)`f *\\<^sub>H induced_mor(k,x)`g\"\n@proof\n  @let \"\\<R> = loop_space_rel(X,x)\"\n  @let \"f' = rep(\\<R>,f)\" \"g' = rep(\\<R>,g)\"\n@qed\nsetup {* del_prfstep_thm_str \"@sym\" @{thm path_product_comp} *}\n\nlemma induced_mor_on_id [rewrite]:\n  \"continuous(k) \\<Longrightarrow> X = source_str(k) \\<Longrightarrow> Y = target_str(k) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> H = \\<pi>\\<^sub>1(Y,k`x) \\<Longrightarrow> induced_mor(k,x)`(\\<one>\\<^sub>G) = \\<one>\\<^sub>H\"\n@proof\n  @let \"\\<R> = loop_space_rel(X,x)\"\n  @have \"path_homotopic(k \\<circ>\\<^sub>m rep(\\<R>,\\<one>\\<^sub>G), k \\<circ>\\<^sub>m const_mor(I,X,x))\"\n@qed\n\nlemma induced_mor_is_homomorphism [typing]:\n  \"continuous(k) \\<Longrightarrow> X = source_str(k) \\<Longrightarrow> Y = target_str(k) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   induced_mor(k,x) \\<in> \\<pi>\\<^sub>1(X,x) \\<rightharpoonup>\\<^sub>G \\<pi>\\<^sub>1(Y,k`x)\" by auto2\n\nlemma induced_mor_id [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> induced_mor(id_mor(X),x) = id_mor(\\<pi>\\<^sub>1(X,x))\"\n@proof\n  @let \"G = \\<pi>\\<^sub>1(X,x)\" \"\\<R> = loop_space_rel(X,x)\"\n  @have (@rule) \"\\<forall>f\\<in>.G. induced_mor(id_mor(X),x)`f = f\" @with\n    @let \"f' = rep(\\<R>,f)\" @end\n@qed\n\nlemma induced_mor_comp' [rewrite]:\n  \"continuous(k) \\<Longrightarrow> continuous(h) \\<Longrightarrow> target_str(k) = source_str(h) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   X = source_str(k) \\<Longrightarrow> G = \\<pi>\\<^sub>1(X,x) \\<Longrightarrow> f \\<in>. G \\<Longrightarrow> \\<R> = loop_space_rel(X,x) \\<Longrightarrow>\n   induced_mor(h \\<circ>\\<^sub>m k, x) ` f = induced_mor(h,k`x) ` (induced_mor(k,x) ` f)\"\n@proof\n  @have \"f = equiv_class(\\<R>,rep(\\<R>,f))\"\n  @have \"(h \\<circ>\\<^sub>m k) \\<circ>\\<^sub>m rep(\\<R>,f) = h \\<circ>\\<^sub>m (k \\<circ>\\<^sub>m rep(\\<R>,f))\"\n@qed\n\nlemma induced_mor_comp [rewrite]:\n  \"continuous(k) \\<Longrightarrow> continuous(h) \\<Longrightarrow> target_str(k) = source_str(h) \\<Longrightarrow> x \\<in> source(k) \\<Longrightarrow>\n   induced_mor(h \\<circ>\\<^sub>m k, x) = induced_mor(h,k`x) \\<circ>\\<^sub>m induced_mor(k,x)\" by auto2\nsetup {* del_prfstep_thm @{thm induced_mor_comp'} *}\n\nend\n", "meta": {"author": "bzhan", "repo": "auto2", "sha": "2e83c30b095f2ed9fa5257f79570eb354ed6e6a7", "save_path": "github-repos/isabelle/bzhan-auto2", "path": "github-repos/isabelle/bzhan-auto2/auto2-2e83c30b095f2ed9fa5257f79570eb354ed6e6a7/FOL/Homotopy/FundamentalGroup.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213745668094, "lm_q2_score": 0.8688267796346598, "lm_q1q2_score": 0.7811807283655697}}
{"text": "(* \n    Title:      Miscellaneous.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Miscellaneous*}\n\ntheory Miscellaneous\nimports \n  Generalizations\n  \"$ISABELLE_HOME/src/HOL/Library/Bit\"\n  Mod_Type\nbegin\n\ntext{*In this file, we present some basic definitions and lemmas about linear algebra and matrices.*}\n\nsubsection{*Definitions of number of rows and columns of a matrix*}\n\ndefinition nrows :: \"'a^'columns^'rows => nat\"\n  where \"nrows A = CARD('rows)\"\n\ndefinition ncols :: \"'a^'columns^'rows => nat\"\n  where \"ncols A = CARD('columns)\"\n  \ndefinition matrix_scalar_mult :: \"'a => ('a::semiring_1) ^'n^'m => ('a::semiring_1) ^'n^'m\"\n    (infixl \"*k\" 70)\n  where \"k *k A \\<equiv> (\\<chi> i j. k * A $ i $ j)\"\n\nsubsection{*Basic properties about matrices*}\n\nlemma nrows_not_0[simp]:\n  shows \"0 \\<noteq> nrows A\" unfolding nrows_def by simp\n\nlemma ncols_not_0[simp]:\n  shows \"0 \\<noteq> ncols A\" unfolding ncols_def by simp\n\nlemma nrows_transpose: \"nrows (transpose A) = ncols A\"\n  unfolding nrows_def ncols_def ..\n\nlemma ncols_transpose: \"ncols (transpose A) = nrows A\"\n  unfolding nrows_def ncols_def ..\n\nlemma finite_rows: \"finite (rows A)\"\n  using finite_Atleast_Atmost_nat[of \"\\<lambda>i. row i A\"] unfolding rows_def .\n\nlemma finite_columns: \"finite (columns A)\"\n  using finite_Atleast_Atmost_nat[of \"\\<lambda>i. column i A\"] unfolding columns_def .\n\nlemma matrix_vector_zero: \"A *v 0 = 0\"\n  unfolding matrix_vector_mult_def by (simp add: zero_vec_def)\n\nlemma vector_matrix_zero: \"0 v* A = 0\"\n  unfolding vector_matrix_mult_def by (simp add: zero_vec_def)\n\nlemma vector_matrix_zero': \"x v* 0 = 0\"\n  unfolding vector_matrix_mult_def by (simp add: zero_vec_def)\n\nlemma transpose_vector: \"x v* A = transpose A *v x\"\n  by (unfold matrix_vector_mult_def vector_matrix_mult_def transpose_def, auto)\n\n\nlemma transpose_zero[simp]: \"(transpose A = 0) = (A = 0)\"\n  unfolding transpose_def zero_vec_def vec_eq_iff by auto\n\n\nsubsection{*Theorems obtained from the AFP*}\n\ntext{*The following theorems and definitions have been obtained from the AFP \n\\url{http://afp.sourceforge.net/browser_info/current/HOL/Tarskis_Geometry/Linear_Algebra2.html}.\nI have removed some restrictions over the type classes.*}\n\nlemma vector_matrix_left_distrib:\n  (*fixes x y :: \"real^('n::finite)\" and A :: \"real^('m::finite)^'n\"*)\n  shows \"(x + y) v* A = x v* A + y v* A\"\n  unfolding vector_matrix_mult_def\n  by (simp add: algebra_simps setsum.distrib vec_eq_iff)\n\nlemma matrix_vector_right_distrib:\n  (*fixes v w :: \"real^('n::finite)\" and M :: \"real^'n^('m::finite)\"*)\n  shows \"M *v (v + w) = M *v v + M *v w\"\nproof -\n  have \"M *v (v + w) = (v + w) v* transpose M\" by (metis transpose_transpose transpose_vector)\n  also have \"\\<dots> = v v* transpose M + w v* transpose M\"\n    by (rule vector_matrix_left_distrib [of v w \"transpose M\"])\n  finally show \"M *v (v + w) = M *v v + M *v w\" by (metis transpose_transpose transpose_vector)\nqed\n\n\nlemma scalar_vector_matrix_assoc:\n  fixes k :: \"'a::{field}\" and x :: \"'a::{field}^'n\" and A :: \"'a^'m^'n\"\n  shows \"(k *s x) v* A = k *s (x v* A)\"\n  unfolding vector_matrix_mult_def unfolding vec_eq_iff \n  by (auto simp add: setsum_right_distrib, rule setsum.cong, simp_all) \n \n\nlemma vector_scalar_matrix_ac:\n  fixes k :: \"'a::{field}\" and x :: \"'a::{field}^'n\" and A :: \"'a^'m^'n\"\n  shows \"x v* (k *k A) = k *s (x v* A)\"\n  using scalar_vector_matrix_assoc \n  unfolding vector_matrix_mult_def matrix_scalar_mult_def vec_eq_iff \n  by (auto simp add: setsum_right_distrib)\n\nlemma transpose_scalar: \"transpose (k *k A) = k *k transpose A\"\n  unfolding transpose_def \n  by (vector, simp add: matrix_scalar_mult_def)\n\nlemma scalar_matrix_vector_assoc:\n  fixes A :: \"'a::{field}^'m^'n\"\n  shows \"k *s (A *v v) = k *k A *v v\"\nproof -\n  have \"k *s (A *v v) = k *s (v v* transpose A)\" by (metis transpose_transpose transpose_vector)\n  also have \"\\<dots> = v v* (k *k transpose A)\"\n    by (rule vector_scalar_matrix_ac [symmetric])\n  also have \"\\<dots> = v v* transpose (k *k A)\" unfolding transpose_scalar ..\n  finally show \"k *s (A *v v) = k *k A *v v\" by (metis transpose_transpose transpose_vector)\nqed\n\nlemma matrix_scalar_vector_ac:\n  fixes A :: \"'a::{field}^'m^'n\"\n  shows \"A *v (k *s v) = k *k A *v v\"\nproof -\n  have \"A *v (k *s v) = k *s (v v* transpose A)\" \n    by (metis transpose_transpose scalar_vector_matrix_assoc transpose_vector)\n  also have \"\\<dots> = v v* (k *k transpose A)\"\n    by (subst vector_scalar_matrix_ac) simp\n  also have \"\\<dots> = v v* transpose (k *k A)\" by (subst transpose_scalar) simp\n  also have \"\\<dots> = k *k A *v v\" by (metis transpose_transpose transpose_vector)\n  finally show \"A *v (k *s v) = k *k A *v v\" .\nqed\n\n\ndefinition\n  is_basis :: \"('a::{field}^'n) set => bool\" where\n  \"is_basis S \\<equiv> vec.independent S \\<and> vec.span S = UNIV\"\n\nlemma card_finite:\n  assumes \"card S = CARD('n::finite)\"\n  shows \"finite S\"\nproof -\n  from `card S = CARD('n)` have \"card S \\<noteq> 0\" by simp\n  with card_eq_0_iff [of S] show \"finite S\" by simp\nqed\n\nlemma independent_is_basis:\n  fixes B :: \"('a::{field}^'n) set\"\n  shows \"vec.independent B \\<and> card B = CARD('n) \\<longleftrightarrow> is_basis B\"\nproof\n  assume \"vec.independent B \\<and> card B = CARD('n)\"\n  hence \"vec.independent B\" and \"card B = CARD('n)\" by simp+\n  from card_finite [of B, where 'n = 'n] and `card B = CARD('n)`\n  have \"finite B\" by simp\n  from `card B = CARD('n)`\n  have \"card B = vec.dim (UNIV :: (('a^'n) set))\" unfolding vec_dim_card .\n  with vec.card_eq_dim [of B UNIV] and `finite B` and `vec.independent B`\n  have \"vec.span B = UNIV\" by auto\n  with `vec.independent B` show \"is_basis B\" unfolding is_basis_def ..\nnext\n  assume \"is_basis B\"\n  hence \"vec.independent B\" unfolding is_basis_def ..\n  moreover have \"card B = CARD('n)\"\n  proof -\n    have \"B \\<subseteq> UNIV\" by simp\n    moreover\n    { from `is_basis B` have \"UNIV \\<subseteq> vec.span B\" and \"vec.independent B\"\n        unfolding is_basis_def\n        by simp+ }\n    ultimately have \"card B = vec.dim (UNIV::((real^'n) set))\"\n      using vec.basis_card_eq_dim [of B UNIV]\n      unfolding vec_dim_card\n      by simp\n    then show \"card B = CARD('n)\"\n      by (metis vec_dim_card)\n  qed\n  ultimately show \"vec.independent B \\<and> card B = CARD('n)\" ..\nqed\n\n\n\ntext{*Here ends the statements obtained from AFP: \n  \\url{http://afp.sourceforge.net/browser_info/current/HOL/Tarskis_Geometry/Linear_Algebra2.html} \n  which have been generalized.*}\n\nsubsection{*Basic properties involving span, linearity and dimensions*}\n\ncontext finite_dimensional_vector_space\nbegin\n\ntext{*This theorem is the reciprocal theorem of @{thm \"indep_card_eq_dim_span\"}*}\n\nlemma card_eq_dim_span_indep:\n(*fixes A :: \"('n::euclidean_space) set\"*)\nassumes \"dim (span A) = card A\" and \"finite A\"\nshows \"independent A\" \nby (metis assms card_le_dim_spanning dim_subset equalityE span_inc)\n\nlemma dim_zero_eq:\n(*fixes A::\"'a::euclidean_space set\"*)\nassumes dim_A: \"dim A = 0\"\nshows \"A = {} \\<or> A = {0}\"\nproof -\nobtain B where ind_B: \"independent B\" and A_in_span_B: \"A \\<subseteq> span B\" \n  and card_B: \"card B = 0\" using basis_exists[of A] unfolding dim_A by blast\nhave finite_B: \"finite B\" using indep_card_eq_dim_span[OF ind_B] by simp\nhence B_eq_empty: \"B={}\" using card_B unfolding card_eq_0_iff by simp\nhave \"A \\<subseteq> {0}\" using A_in_span_B unfolding B_eq_empty span_empty .\nthus ?thesis by blast\nqed\n\nlemma dim_zero_eq': \n  (*fixes A::\"'a::euclidean_space set\"*)\n  assumes A: \"A = {} \\<or> A = {0}\"\n  shows \"dim A = 0\"\nproof -\nhave \"card ({}::'b set) = dim A\"\n  proof (rule basis_card_eq_dim[THEN conjunct2, of \"{}::'b set\" A])\n     show \"{} \\<subseteq> A\" by simp\n     show \"A \\<subseteq> span {}\" using A by fastforce\n     show \"independent {}\" by (rule independent_empty)\n  qed\nthus ?thesis by simp\nqed\n\n\nlemma dim_zero_subspace_eq:\n(*  fixes A::\"'a::euclidean_space set\"*)\nassumes subs_A: \"subspace A\"\nshows \"(dim A = 0) = (A = {0})\" using dim_zero_eq dim_zero_eq' subspace_0[OF subs_A] by auto\n\n\n\ncontext linear\nbegin\n\nlemma linear_injective_ker_0:\nshows \"inj f = ({x. f x = 0} = {0})\"\nunfolding linear_injective_0\nusing linear_0 by blast\n\nend\n\nlemma snd_if_conv:\nshows \"snd (if P then (A,B) else (C,D))=(if P then B else D)\" by simp\n\nsubsection{*Basic properties about matrix multiplication*}\n\nlemma row_matrix_matrix_mult:\nfixes A::\"'a::{comm_ring_1}^'n^'m\"\nshows \"(P $ i) v* A = (P ** A) $ i\"\nunfolding vec_eq_iff\nunfolding vector_matrix_mult_def unfolding matrix_matrix_mult_def\nby (auto intro!: setsum.cong)\n\ncorollary row_matrix_matrix_mult':\nfixes A::\"'a::{comm_ring_1}^'n^'m\"\nshows \"(row i P) v* A = row i (P ** A)\"\nusing row_matrix_matrix_mult unfolding row_def vec_nth_inverse .\n\nlemma column_matrix_matrix_mult:\nshows \"column i (P**A) = P *v (column i A)\"\nunfolding column_def matrix_vector_mult_def matrix_matrix_mult_def by fastforce\n\nlemma matrix_matrix_mult_inner_mult:\nshows \"(A ** B) $ i $ j = row i A \\<bullet> column j B\"\nunfolding inner_vec_def matrix_matrix_mult_def row_def column_def by auto\n\n\nlemma matrix_vmult_column_sum:\n  fixes A::\"'a::{field}^'n^'m\"\n  shows \"\\<exists>f. A *v x = setsum (\\<lambda>y. f y *s y) (columns A)\"\nproof (rule exI[of _ \"\\<lambda>y. setsum (\\<lambda>i. x $ i) {i. y = column i A}\"])\n  let ?f=\"\\<lambda>y. setsum (\\<lambda>i. x $ i) {i. y = column i A}\"  \n  let ?g=\"(\\<lambda>y. {i. y=column i (A)})\"\n  have inj: \"inj_on ?g (columns (A))\" unfolding inj_on_def unfolding columns_def by auto\n  have union_univ: \"\\<Union> (?g`(columns (A))) = UNIV\" unfolding columns_def by auto\n  have \"A *v x = (\\<Sum>i\\<in>UNIV. x $ i *s column i A)\" unfolding matrix_mult_vsum ..\n  also have \"... = setsum (\\<lambda>i.  x $ i *s column i A) (\\<Union>(?g`(columns A)))\" unfolding union_univ ..\n  also have \"... = setsum (setsum ((\\<lambda>i.  x $ i *s column i A)))  (?g`(columns A))\"\n    by (rule setsum.Union_disjoint[unfolded o_def], auto) \n  also have \"... = setsum ((setsum ((\\<lambda>i.  x $ i *s column i A))) \\<circ> ?g)  (columns A)\" \n    by (rule setsum.reindex, simp add: inj)\n  also have \"... =  setsum (\\<lambda>y. ?f y *s y) (columns A)\"\n  proof (rule setsum.cong, unfold o_def)\n    fix xa\n    have \"setsum (\\<lambda>i. x $ i *s column i A) {i. xa = column i A} \n      = setsum (\\<lambda>i. x $ i *s xa) {i. xa = column i A}\" by simp\n    also have \"... = setsum (\\<lambda>i. x $ i) {i. xa = column i A} *s xa\" \n      using vec.scale_setsum_left[of \"(\\<lambda>i. x $ i)\" \"{i. xa = column i A}\" xa] ..\n    finally show \"(\\<Sum>i | xa = column i A. x $ i *s column i A) = (\\<Sum>i | xa = column i A. x $ i) *s xa\" . \n  qed rule\n  finally show \"A *v x = (\\<Sum>y\\<in>columns A. (\\<Sum>i | y = column i A. x $ i) *s y)\" .\nqed\n\n\nsubsection{*Properties about invertibility*}\n\nlemma matrix_inv:\n  assumes \"invertible M\"\n  shows matrix_inv_left: \"matrix_inv M ** M = mat 1\"\n  and matrix_inv_right: \"M ** matrix_inv M = mat 1\"\n  using `invertible M` and someI_ex [of \"\\<lambda> N. M ** N = mat 1 \\<and> N ** M = mat 1\"]\n  unfolding invertible_def and matrix_inv_def\n  by simp_all\n\nlemma invertible_mult:\n  assumes inv_A: \"invertible A\"\n  and inv_B: \"invertible B\"\n  shows \"invertible (A**B)\"\nproof -\n  obtain A' where AA': \"A ** A' = mat 1\" and A'A: \"A' ** A = mat 1\" \n    using inv_A unfolding invertible_def by blast\n  obtain B' where BB': \"B ** B' = mat 1\" and B'B: \"B' ** B = mat 1\" \n    using inv_B unfolding invertible_def by blast\n  show ?thesis\n  proof (unfold invertible_def, rule exI[of _ \"B'**A'\"], rule conjI)\n    have \"A ** B ** (B' ** A') = A ** (B ** (B' ** A'))\" \n      using matrix_mul_assoc[of A B \"(B' ** A')\", symmetric] .\n    also have \"... = A ** (B ** B' ** A')\" unfolding matrix_mul_assoc[of B \"B'\" \"A'\"] ..\n    also have \"... = A ** (mat 1 ** A')\" unfolding BB' ..\n    also have \"... = A ** A'\" unfolding matrix_mul_lid ..\n    also have \"... = mat 1\" unfolding AA' ..\n    finally show \"A ** B ** (B' ** A') = mat (1\\<Colon>'a)\" .    \n    have \"B' ** A' ** (A ** B) = B' ** (A' ** (A ** B))\" using matrix_mul_assoc[of B' A' \"(A ** B)\", symmetric] .\n    also have \"... =  B' ** (A' ** A ** B)\" unfolding matrix_mul_assoc[of A' A B] ..\n    also have \"... =  B' ** (mat 1 ** B)\" unfolding A'A ..\n    also have \"... = B' ** B\"  unfolding matrix_mul_lid ..\n    also have \"... = mat 1\" unfolding B'B ..\n    finally show \"B' ** A' ** (A ** B) = mat 1\" .\n  qed\nqed\n\n\ntext{*In the library, @{thm \"matrix_inv_def\"} allows the use of non squary matrices.\n  The following lemma can be also proved fixing @{term \"A::'a::{semiring_1}^'n^'m\"}*}\n\nlemma matrix_inv_unique:\n  fixes A::\"'a::{semiring_1}^'n^'n\"\n  assumes AB: \"A ** B = mat 1\" and BA: \"B ** A = mat 1\"\n  shows \"matrix_inv A = B\" \nproof (unfold matrix_inv_def, rule some_equality)\n  show \"A ** B = mat (1\\<Colon>'a) \\<and> B ** A = mat (1\\<Colon>'a)\" using AB BA by simp\n  fix C assume \"A ** C = mat (1\\<Colon>'a) \\<and> C ** A = mat (1\\<Colon>'a)\"\n  hence AC: \"A ** C = mat (1\\<Colon>'a)\" and CA: \"C ** A = mat (1\\<Colon>'a)\" by auto  \n  have \"B = B ** (mat 1)\" unfolding matrix_mul_rid ..\n  also have \"... = B ** (A**C)\" unfolding AC ..\n  also have \"... = B ** A ** C\" unfolding matrix_mul_assoc ..\n  also have \"... = C\" unfolding BA matrix_mul_lid ..\n  finally show \"C = B\" ..\nqed\n\n\nlemma matrix_vector_mult_zero_eq:\nassumes P: \"invertible P\"\nshows \"((P**A)*v x = 0) = (A *v x = 0)\"\nproof (rule iffI)\nassume \"P ** A *v x = 0\" \nhence \"matrix_inv P *v (P ** A *v x) = matrix_inv P *v 0\" by simp\nhence \"matrix_inv P *v (P ** A *v x) =  0\" by (metis matrix_vector_zero)\nhence \"(matrix_inv P ** P ** A) *v x =  0\" by (metis matrix_vector_mul_assoc)\nthus \"A *v x =  0\" by (metis assms matrix_inv_left matrix_mul_lid)\nnext\nassume \"A *v x = 0\" \nthus \"P ** A *v x = 0\" by (metis matrix_vector_mul_assoc matrix_vector_zero)\nqed\n\nlemma inj_matrix_vector_mult:\nfixes P::\"'a::{field}^'n^'m\"\nassumes P: \"invertible P\"\nshows \"inj (op *v P)\"\nunfolding vec.linear_injective_0\nusing matrix_left_invertible_ker[of P] P unfolding invertible_def by blast\n\nlemma independent_image_matrix_vector_mult:\nfixes P::\"'a::{field}^'n^'m\"\nassumes ind_B: \"vec.independent B\" and inv_P: \"invertible P\"\nshows \"vec.independent ((op *v P)` B)\"\nproof (rule vec.independent_injective_on_span_image)\n  show \"vec.independent B\" using ind_B .\n  show \"inj_on (op *v P) (vec.span B)\" \n    using inj_matrix_vector_mult[OF inv_P] unfolding inj_on_def by simp\nqed\n\nlemma independent_preimage_matrix_vector_mult:\nfixes P::\"'a::{field}^'n^'n\"\nassumes ind_B: \"vec.independent ((op *v P)` B)\" and inv_P: \"invertible P\"\nshows \"vec.independent B\"\nproof -\nhave \"vec.independent ((op *v (matrix_inv P))` ((op *v P)` B))\"\n  proof (rule independent_image_matrix_vector_mult)\n    show \"vec.independent (op *v P ` B)\" using ind_B .\n    show \"invertible (matrix_inv P)\"\n      by (metis matrix_inv_left matrix_inv_right inv_P invertible_def)\n    qed\nmoreover have \"(op *v (matrix_inv P))` ((op *v P)` B) = B\"\n    proof (auto)\n      fix x assume x: \"x \\<in> B\" show \"matrix_inv P *v (P *v x) \\<in> B\" \n      by (metis (full_types) x inv_P matrix_inv_left matrix_vector_mul_assoc matrix_vector_mul_lid)\n      thus \"x \\<in> op *v (matrix_inv P) ` op *v P ` B\" \n      unfolding image_def \n      by (auto, metis  inv_P matrix_inv_left matrix_vector_mul_assoc matrix_vector_mul_lid)\n     qed\nultimately show ?thesis by simp\nqed\n\nsubsection{*Properties about the dimension of vectors*}\n\nlemma dimension_vector[code_unfold]: \"vec.dimension TYPE('a::{field}) TYPE('rows::{mod_type})=CARD('rows)\"\nproof -\nlet ?f=\"\\<lambda>x. axis (from_nat x) 1::'a^'rows::{mod_type}\"\nhave \"vec.dimension TYPE('a::{field}) TYPE('rows::{mod_type}) = card (cart_basis::('a^'rows::{mod_type}) set)\"\n  unfolding vec.dimension_def ..\nalso have \"... = card{..<CARD('rows)}\" unfolding cart_basis_def \n  proof (rule bij_betw_same_card[symmetric, of ?f], unfold bij_betw_def, unfold inj_on_def axis_eq_axis, auto)\n     fix x y assume x: \"x < CARD('rows)\" and y: \"y < CARD('rows)\" and eq: \"from_nat x = (from_nat y::'rows)\"\n     show \"x = y\" using from_nat_eq_imp_eq[OF eq x y] .\n     next\n     fix i show \"axis i 1 \\<in> (\\<lambda>x. axis (from_nat x::'rows) 1) ` {..<CARD('rows)}\" unfolding image_def\n     by (auto, metis lessThan_iff to_nat_from_nat to_nat_less_card)\n  qed\nalso have \"... = CARD('rows)\" by (metis card_lessThan)\nfinally show ?thesis .\nqed\n\nsubsection{*Instantiations and interpretations*}\n\ntext{*Functions between two real vector spaces form a real vector*}\ninstantiation \"fun\" :: (real_vector, real_vector) real_vector\nbegin\n\ndefinition \"plus_fun f g = (\\<lambda>i. f i + g i)\"\ndefinition \"zero_fun = (\\<lambda>i. 0)\"\ndefinition \"scaleR_fun a f = (\\<lambda>i. a *\\<^sub>R f i )\"\n\ninstance proof\n  fix a::\"'a \\<Rightarrow> 'b\" and b::\"'a \\<Rightarrow> 'b\" and c::\"'a \\<Rightarrow> 'b\"\n  show \"a + b + c = a + (b + c)\" unfolding fun_eq_iff unfolding plus_fun_def by auto\n  show \"a + b = b + a\" unfolding fun_eq_iff unfolding plus_fun_def by auto\n  show \" (0\\<Colon>'a \\<Rightarrow> 'b) + a = a\"  unfolding fun_eq_iff unfolding plus_fun_def zero_fun_def by auto\n  show \"- a + a = (0\\<Colon>'a \\<Rightarrow> 'b)\" unfolding fun_eq_iff unfolding plus_fun_def zero_fun_def by auto\n  show \"a - b = a + - b\" unfolding fun_eq_iff unfolding plus_fun_def zero_fun_def by auto\nnext\n  fix a::real and x::\"('a \\<Rightarrow> 'b)\" and y::\"'a \\<Rightarrow> 'b\"\n  show \"a *\\<^sub>R (x + y) = a *\\<^sub>R x + a *\\<^sub>R y\" \n  unfolding fun_eq_iff plus_fun_def scaleR_fun_def scaleR_right.add by auto\nnext\n  fix a::real and b::real and x::\"'a \\<Rightarrow> 'b\" \n  show \"(a + b) *\\<^sub>R x = a *\\<^sub>R x + b *\\<^sub>R x\" \n    unfolding fun_eq_iff unfolding plus_fun_def scaleR_fun_def unfolding  scaleR_left.add by auto\n  show \" a *\\<^sub>R b *\\<^sub>R x = (a * b) *\\<^sub>R x\" unfolding fun_eq_iff unfolding scaleR_fun_def by auto\n  show \"(1\\<Colon>real) *\\<^sub>R x = x\" unfolding fun_eq_iff unfolding scaleR_fun_def by auto\nqed\nend\n\n\ninstantiation vec :: (type, finite) equal\nbegin\ndefinition equal_vec :: \"('a, 'b::finite) vec => ('a, 'b::finite) vec => bool\" \n  where \"equal_vec x y = (\\<forall>i. x$i = y$i)\"\ninstance \nproof (intro_classes)\n  fix x y::\"('a, 'b::finite) vec\"\n  show \"equal_class.equal x y = (x = y)\" unfolding equal_vec_def using vec_eq_iff by auto\nqed\nend\n\ninstantiation bit :: linorder\nbegin\n\ndefinition less_eq_bit :: \"bit \\<Rightarrow> bit \\<Rightarrow> bool\"\nwhere \"less_eq_bit x y = (y=1 \\<or> x=0)\"\n\ndefinition less_bit :: \"bit \\<Rightarrow> bit \\<Rightarrow> bool\"\nwhere \"less_bit x y = (y=1 \\<and> x=0)\"\n\ninstance\nproof (intro_classes, auto simp add: less_eq_bit_def less_bit_def)\nqed\nend\n\ninterpretation matrix: vector_space \"(op *k)::'a::{field}=>'a^'cols^'rows=>'a^'cols^'rows\"\nproof (unfold_locales)\nfix a::'a and x y::\"'a^'cols^'rows\"\nshow \"a *k (x + y) = a *k x + a *k y\"\n  unfolding matrix_scalar_mult_def vec_eq_iff\n  by (simp add: vector_space_over_itself.scale_right_distrib)\nnext\nfix a b::'a and x::\"'a^'cols^'rows\"\nshow \"(a + b) *k x = a *k x + b *k x\"\nunfolding matrix_scalar_mult_def vec_eq_iff\n  by (simp add: comm_semiring_class.distrib)\nshow \"a *k (b *k x) = a * b *k x\"\n  unfolding matrix_scalar_mult_def vec_eq_iff by auto\nshow\"1 *k x = x\" unfolding matrix_scalar_mult_def vec_eq_iff by auto\nqed\n\nsubsection{*Properties about lists*}\n\ntext{*The following definitions and theorems are developed in order to compute setprods. \n  More theorems and properties can be demonstrated in a similar way to the ones\n  about @{term \"listsum\"}.*}\n\ndefinition (in monoid_mult) listprod :: \"'a list => 'a\" where\n  \"listprod xs = foldr times xs 1\"\n\nlemma (in monoid_mult) listprod_simps [simp]:\n  \"listprod [] = 1\"\n  \"listprod (x # xs) = x * listprod xs\"\n  by (simp_all add: listprod_def)\n\nlemma (in monoid_mult) listprod_append [simp]:\n  \"listprod (xs @ ys) = listprod xs * listprod ys\"\n  by (induct xs) (simp_all add: mult.assoc)\n\nlemma (in comm_monoid_mult) listprod_rev [simp]:\n  \"listprod (rev xs) = listprod xs\"\n  by (simp add: listprod_def foldr_fold fold_rev fun_eq_iff ac_simps)\n\nlemma (in monoid_mult) listprod_distinct_conv_setprod_set:\n  \"distinct xs ==> listprod (map f xs) = setprod f (set xs)\"\n  by (induct xs) simp_all\n\nlemma setprod_code [code]:\n  \"setprod f (set xs) = listprod (map f (remdups xs))\"\n  by (simp add: listprod_distinct_conv_setprod_set)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Rank_Nullity_Theorem/Miscellaneous.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7811058675762023}}
{"text": "(*  Title:      HOL/Algebra/Generated_Groups.thy\n    Author:     Paulo Emílio de Vilhena\n*)\n\ntheory Generated_Groups\n  imports Group Coset\n  \nbegin\n\nsection \\<open>Generated Groups\\<close>\n\ninductive_set generate :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  for G and H where\n    one:  \"\\<one>\\<^bsub>G\\<^esub> \\<in> generate G H\"\n  | incl: \"h \\<in> H \\<Longrightarrow> h \\<in> generate G H\"\n  | inv:  \"h \\<in> H \\<Longrightarrow> inv\\<^bsub>G\\<^esub> h \\<in> generate G H\"\n  | eng:  \"h1 \\<in> generate G H \\<Longrightarrow> h2 \\<in> generate G H \\<Longrightarrow> h1 \\<otimes>\\<^bsub>G\\<^esub> h2 \\<in> generate G H\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma (in group) generate_consistent:\n  assumes \"K \\<subseteq> H\" \"subgroup H G\" shows \"generate (G \\<lparr> carrier := H \\<rparr>) K = generate G K\"\nproof\n  show \"generate (G \\<lparr> carrier := H \\<rparr>) K \\<subseteq> generate G K\"\n  proof\n    fix h assume \"h \\<in> generate (G \\<lparr> carrier := H \\<rparr>) K\" thus \"h \\<in> generate G K\"\n    proof (induction, simp add: one, simp_all add: incl[of _ K G] eng)\n      case inv thus ?case\n        using m_inv_consistent assms generate.inv[of _ K G] by auto\n    qed\n  qed\nnext\n  show \"generate G K \\<subseteq> generate (G \\<lparr> carrier := H \\<rparr>) K\"\n  proof\n    note gen_simps = one incl eng\n    fix h assume \"h \\<in> generate G K\" thus \"h \\<in> generate (G \\<lparr> carrier := H \\<rparr>) K\"\n      using gen_simps[where ?G = \"G \\<lparr> carrier := H \\<rparr>\"]\n    proof (induction, auto)\n      fix h assume \"h \\<in> K\" thus \"inv h \\<in> generate (G \\<lparr> carrier := H \\<rparr>) K\"\n        using m_inv_consistent assms generate.inv[of h K \"G \\<lparr> carrier := H \\<rparr>\"] by auto\n    qed\n  qed\nqed\n\nlemma (in group) generate_in_carrier:\n  assumes \"H \\<subseteq> carrier G\" and \"h \\<in> generate G H\" shows \"h \\<in> carrier G\"\n  using assms(2,1) by (induct h rule: generate.induct) (auto)\n\nlemma (in group) generate_incl:\n  assumes \"H \\<subseteq> carrier G\" shows \"generate G H \\<subseteq> carrier G\"\n  using generate_in_carrier[OF assms(1)] by auto\n\nlemma (in group) generate_m_inv_closed:\n  assumes \"H \\<subseteq> carrier G\" and \"h \\<in> generate G H\" shows \"(inv h) \\<in> generate G H\"\n  using assms(2,1)\nproof (induction rule: generate.induct, auto simp add: one inv incl)\n  fix h1 h2\n  assume h1: \"h1 \\<in> generate G H\" \"inv h1 \\<in> generate G H\"\n     and h2: \"h2 \\<in> generate G H\" \"inv h2 \\<in> generate G H\"\n  hence \"inv (h1 \\<otimes> h2) = (inv h2) \\<otimes> (inv h1)\"\n    by (meson assms generate_in_carrier group.inv_mult_group is_group)\n  thus \"inv (h1 \\<otimes> h2) \\<in> generate G H\"\n    using generate.eng[OF h2(2) h1(2)] by simp\nqed\n\nlemma (in group) generate_is_subgroup:\n  assumes \"H \\<subseteq> carrier G\" shows \"subgroup (generate G H) G\"\n  using subgroup.intro[OF generate_incl eng one generate_m_inv_closed] assms by auto\n\nlemma (in group) mono_generate:\n  assumes \"K \\<subseteq> H\" shows \"generate G K \\<subseteq> generate G H\"\nproof\n  fix h assume \"h \\<in> generate G K\" thus \"h \\<in> generate G H\"\n    using assms by (induction) (auto simp add: one incl inv eng)\nqed\n\nlemma (in group) generate_subgroup_incl:\n  assumes \"K \\<subseteq> H\" \"subgroup H G\" shows \"generate G K \\<subseteq> H\"\n  using group.generate_incl[OF subgroup_imp_group[OF assms(2)], of K] assms(1)\n  by (simp add: generate_consistent[OF assms])\n\nlemma (in group) generate_minimal:\n  assumes \"H \\<subseteq> carrier G\" shows \"generate G H = \\<Inter> { H'. subgroup H' G \\<and> H \\<subseteq> H' }\"\n  using generate_subgroup_incl generate_is_subgroup[OF assms] incl[of _ H] by blast\n\nlemma (in group) generateI:\n  assumes \"subgroup E G\" \"H \\<subseteq> E\" and \"\\<And>K. \\<lbrakk> subgroup K G; H \\<subseteq> K \\<rbrakk> \\<Longrightarrow> E \\<subseteq> K\"\n  shows \"E = generate G H\"\nproof -\n  have subset: \"H \\<subseteq> carrier G\"\n    using subgroup.subset assms by auto\n  show ?thesis\n    using assms unfolding generate_minimal[OF subset] by blast\nqed\n\nlemma (in group) normal_generateI:\n  assumes \"H \\<subseteq> carrier G\" and \"\\<And>h g. \\<lbrakk> h \\<in> H; g \\<in> carrier G \\<rbrakk> \\<Longrightarrow> g \\<otimes> h \\<otimes> (inv g) \\<in> H\"\n  shows \"generate G H \\<lhd> G\"\nproof (rule normal_invI[OF generate_is_subgroup[OF assms(1)]])\n  fix g h assume g: \"g \\<in> carrier G\" show \"h \\<in> generate G H \\<Longrightarrow> g \\<otimes> h \\<otimes> (inv g) \\<in> generate G H\"\n  proof (induct h rule: generate.induct)\n    case one thus ?case\n      using g generate.one by auto\n  next\n    case incl show ?case\n      using generate.incl[OF assms(2)[OF incl g]] .\n  next\n    case (inv h)\n    hence h: \"h \\<in> carrier G\"\n      using assms(1) by auto\n    hence \"inv (g \\<otimes> h \\<otimes> (inv g)) = g \\<otimes> (inv h) \\<otimes> (inv g)\"\n      using g by (simp add: inv_mult_group m_assoc)\n    thus ?case\n      using generate_m_inv_closed[OF assms(1) generate.incl[OF assms(2)[OF inv g]]] by simp\n  next\n    case (eng h1 h2)\n    note in_carrier = eng(1,3)[THEN generate_in_carrier[OF assms(1)]]\n    have \"g \\<otimes> (h1 \\<otimes> h2) \\<otimes> inv g = (g \\<otimes> h1 \\<otimes> inv g) \\<otimes> (g \\<otimes> h2 \\<otimes> inv g)\"\n      using in_carrier g by (simp add: inv_solve_left m_assoc)\n    thus ?case\n      using generate.eng[OF eng(2,4)] by simp\n  qed\nqed\n\nlemma (in group) subgroup_int_pow_closed:\n  assumes \"subgroup H G\" \"h \\<in> H\" shows \"h [^] (k :: int) \\<in> H\"\n  using group.int_pow_closed[OF subgroup_imp_group[OF assms(1)]] assms(2)\n  unfolding int_pow_consistent[OF assms] by simp\n\nlemma (in group) generate_pow:\n  assumes \"a \\<in> carrier G\" shows \"generate G { a } = { a [^] (k :: int) | k. k \\<in> UNIV }\"\nproof\n  show \"{ a [^] (k :: int) | k. k \\<in> UNIV } \\<subseteq> generate G { a }\"\n    using subgroup_int_pow_closed[OF generate_is_subgroup[of \"{ a }\"] incl[of a]] assms by auto\nnext\n  show \"generate G { a } \\<subseteq> { a [^] (k :: int) | k. k \\<in> UNIV }\"\n  proof\n    fix h assume \"h \\<in> generate G { a }\" hence \"\\<exists>k :: int. h = a [^] k\"\n    proof (induction, metis int_pow_0[of a], metis singletonD int_pow_1[OF assms])\n      case (inv h)\n      hence \"inv h = a [^] ((- 1) :: int)\"\n        using assms unfolding int_pow_def2 by simp\n      thus ?case\n        by blast \n    next\n      case eng thus ?case\n        using assms by (metis int_pow_mult)\n    qed\n    thus \"h \\<in> { a [^] (k :: int) | k. k \\<in> UNIV }\"\n      by blast\n  qed\nqed\n\ncorollary (in group) generate_one: \"generate G { \\<one> } = { \\<one> }\"\n  using generate_pow[of \"\\<one>\", OF one_closed] by simp\n\ncorollary (in group) generate_empty: \"generate G {} = { \\<one> }\"\n  using mono_generate[of \"{}\" \"{ \\<one> }\"] generate.one unfolding generate_one by auto\n\nlemma (in group_hom)\n  \"subgroup K G \\<Longrightarrow> subgroup (h ` K) H\"\n  using subgroup_img_is_subgroup by auto\n\nlemma (in group_hom) generate_img:\n  assumes \"K \\<subseteq> carrier G\" shows \"generate H (h ` K) = h ` (generate G K)\"\nproof\n  have \"h ` K \\<subseteq> h ` (generate G K)\"\n    using incl[of _ K G] by auto\n  thus \"generate H (h ` K) \\<subseteq> h ` (generate G K)\"\n    using generate_subgroup_incl subgroup_img_is_subgroup[OF G.generate_is_subgroup[OF assms]] by auto\nnext\n  show \"h ` (generate G K) \\<subseteq> generate H (h ` K)\"\n  proof\n    fix a assume \"a \\<in> h ` (generate G K)\"\n    then obtain k where \"k \\<in> generate G K\" \"a = h k\"\n      by blast\n    show \"a \\<in> generate H (h ` K)\"\n      using \\<open>k \\<in> generate G K\\<close> unfolding \\<open>a = h k\\<close>\n    proof (induct k, auto simp add: generate.one[of H] generate.incl[of _ \"h ` K\" H])\n      case (inv k) show ?case\n        using assms generate.inv[of \"h k\" \"h ` K\" H] inv by auto  \n    next\n      case eng show ?case\n        using generate.eng[OF eng(2,4)] eng(1,3)[THEN G.generate_in_carrier[OF assms]] by auto\n    qed\n  qed\nqed\n\n\nsection \\<open>Derived Subgroup\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\nabbreviation derived_set :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"derived_set G H \\<equiv>\n           \\<Union>h1 \\<in> H. (\\<Union>h2 \\<in> H. { h1 \\<otimes>\\<^bsub>G\\<^esub> h2 \\<otimes>\\<^bsub>G\\<^esub> (inv\\<^bsub>G\\<^esub> h1) \\<otimes>\\<^bsub>G\\<^esub> (inv\\<^bsub>G\\<^esub> h2) })\"\n\ndefinition derived :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n  \"derived G H = generate G (derived_set G H)\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma (in group) derived_set_incl:\n  assumes \"K \\<subseteq> H\" \"subgroup H G\" shows \"derived_set G K \\<subseteq> H\"\n  using assms(1) subgroupE(3-4)[OF assms(2)] by (auto simp add: subset_iff)\n\nlemma (in group) derived_incl:\n  assumes \"K \\<subseteq> H\" \"subgroup H G\" shows \"derived G K \\<subseteq> H\"\n  using generate_subgroup_incl[OF derived_set_incl] assms unfolding derived_def by auto\n\nlemma (in group) derived_set_in_carrier:\n  assumes \"H \\<subseteq> carrier G\" shows \"derived_set G H \\<subseteq> carrier G\"\n  using derived_set_incl[OF assms subgroup_self] .\n\nlemma (in group) derived_in_carrier:\n  assumes \"H \\<subseteq> carrier G\" shows \"derived G H \\<subseteq> carrier G\"\n  using derived_incl[OF assms subgroup_self] .\n\nlemma (in group) exp_of_derived_in_carrier:\n  assumes \"H \\<subseteq> carrier G\" shows \"(derived G ^^ n) H \\<subseteq> carrier G\"\n  using assms derived_in_carrier by (induct n) (auto)\n\nlemma (in group) derived_is_subgroup:\n  assumes \"H \\<subseteq> carrier G\" shows \"subgroup (derived G H) G\"\n  unfolding derived_def using generate_is_subgroup[OF derived_set_in_carrier[OF assms]] .\n\nlemma (in group) exp_of_derived_is_subgroup:\n  assumes \"subgroup H G\" shows \"subgroup ((derived G ^^ n) H) G\"\n  using assms derived_is_subgroup subgroup.subset by (induct n) (auto)\n\nlemma (in group) exp_of_derived_is_subgroup':\n  assumes \"H \\<subseteq> carrier G\" shows \"subgroup ((derived G ^^ (Suc n)) H) G\"\n  using assms derived_is_subgroup[OF subgroup.subset] derived_is_subgroup by (induct n) (auto)\n\nlemma (in group) mono_derived_set:\n  assumes \"K \\<subseteq> H\" shows \"derived_set G K \\<subseteq> derived_set G H\"\n  using assms by auto\n\nlemma (in group) mono_derived:\n  assumes \"K \\<subseteq> H\" shows \"derived G K \\<subseteq> derived G H\"\n  unfolding derived_def using mono_generate[OF mono_derived_set[OF assms]] .\n\nlemma (in group) mono_exp_of_derived:\n  assumes \"K \\<subseteq> H\" shows \"(derived G ^^ n) K \\<subseteq> (derived G ^^ n) H\"\n  using assms mono_derived by (induct n) (auto)\n\nlemma (in group) derived_set_consistent:\n  assumes \"K \\<subseteq> H\" \"subgroup H G\" shows \"derived_set (G \\<lparr> carrier := H \\<rparr>) K = derived_set G K\"\n  using m_inv_consistent[OF assms(2)] assms(1) by (auto simp add: subset_iff)\n\nlemma (in group) derived_consistent:\n  assumes \"K \\<subseteq> H\" \"subgroup H G\" shows \"derived (G \\<lparr> carrier := H \\<rparr>) K = derived G K\"\n  using generate_consistent[OF derived_set_incl] derived_set_consistent assms by (simp add: derived_def)\n\nlemma (in comm_group) derived_eq_singleton:\n  assumes \"H \\<subseteq> carrier G\" shows \"derived G H = { \\<one> }\"\nproof (cases \"derived_set G H = {}\")\n  case True show ?thesis\n    using generate_empty unfolding derived_def True by simp\nnext\n  case False\n  have aux_lemma: \"h \\<in> derived_set G H \\<Longrightarrow> h = \\<one>\" for h\n    using assms by (auto simp add: subset_iff)\n       (metis (no_types, lifting) m_comm m_closed inv_closed inv_solve_right l_inv l_inv_ex)\n  have \"derived_set G H = { \\<one> }\"\n  proof\n    show \"derived_set G H \\<subseteq> { \\<one> }\"\n      using aux_lemma by auto\n  next\n    obtain h where h: \"h \\<in> derived_set G H\"\n      using False by blast\n    thus \"{ \\<one> } \\<subseteq> derived_set G H\"\n      using aux_lemma[OF h] by auto\n  qed\n  thus ?thesis\n    using generate_one unfolding derived_def by auto\nqed\n\nlemma (in group) derived_is_normal:\n  assumes \"H \\<lhd> G\" shows \"derived G H \\<lhd> G\"\nproof -\n  interpret H: normal H G\n    using assms .\n\n  show ?thesis\n    unfolding derived_def\n  proof (rule normal_generateI[OF derived_set_in_carrier[OF H.subset]])\n    fix h g assume \"h \\<in> derived_set G H\" and g: \"g \\<in> carrier G\"\n    then obtain h1 h2 where h: \"h1 \\<in> H\" \"h2 \\<in> H\" \"h = h1 \\<otimes> h2 \\<otimes> inv h1 \\<otimes> inv h2\"\n      by auto\n    hence in_carrier: \"h1 \\<in> carrier G\" \"h2 \\<in> carrier G\" \"g \\<in> carrier G\"\n      using H.subset g by auto\n    have \"g \\<otimes> h \\<otimes> inv g =\n           g \\<otimes> h1 \\<otimes> (inv g \\<otimes> g) \\<otimes> h2 \\<otimes> (inv g \\<otimes> g) \\<otimes> inv h1 \\<otimes> (inv g \\<otimes> g) \\<otimes> inv h2 \\<otimes> inv g\"\n      unfolding h(3) by (simp add: in_carrier m_assoc)\n    also have \" ... =\n          (g \\<otimes> h1 \\<otimes> inv g) \\<otimes> (g \\<otimes> h2 \\<otimes> inv g) \\<otimes> (g \\<otimes> inv h1 \\<otimes> inv g) \\<otimes> (g \\<otimes> inv h2 \\<otimes> inv g)\"\n      using in_carrier m_assoc inv_closed m_closed by presburger\n    finally have \"g \\<otimes> h \\<otimes> inv g =\n          (g \\<otimes> h1 \\<otimes> inv g) \\<otimes> (g \\<otimes> h2 \\<otimes> inv g) \\<otimes> inv (g \\<otimes> h1 \\<otimes> inv g) \\<otimes> inv (g \\<otimes> h2 \\<otimes> inv g)\"\n      by (simp add: in_carrier inv_mult_group m_assoc)\n    thus \"g \\<otimes> h \\<otimes> inv g \\<in> derived_set G H\"\n      using h(1-2)[THEN H.inv_op_closed2[OF g]] by auto\n  qed\nqed\n\nlemma (in group) normal_self: \"carrier G \\<lhd> G\"\n  by (rule normal_invI[OF subgroup_self], simp)\n\ncorollary (in group) derived_self_is_normal: \"derived G (carrier G) \\<lhd> G\"\n  using derived_is_normal[OF normal_self] .\n\ncorollary (in group) derived_subgroup_is_normal:\n  assumes \"subgroup H G\" shows \"derived G H \\<lhd> G \\<lparr> carrier := H \\<rparr>\"\n  using group.derived_self_is_normal[OF subgroup_imp_group[OF assms]]\n        derived_consistent[OF _ assms]\n  by simp\n\ncorollary (in group) derived_quot_is_group: \"group (G Mod (derived G (carrier G)))\"\n  using normal.factorgroup_is_group[OF derived_self_is_normal] by auto\n\nlemma (in group) derived_quot_is_comm_group: \"comm_group (G Mod (derived G (carrier G)))\"\nproof (rule group.group_comm_groupI[OF derived_quot_is_group], simp add: FactGroup_def)\n  interpret DG: normal \"derived G (carrier G)\" G\n    using derived_self_is_normal .\n\n  fix H K assume \"H \\<in> rcosets derived G (carrier G)\" and \"K \\<in> rcosets derived G (carrier G)\"\n  then obtain g1 g2\n    where g1: \"g1 \\<in> carrier G\" \"H = derived G (carrier G) #> g1\"\n      and g2: \"g2 \\<in> carrier G\" \"K = derived G (carrier G) #> g2\"\n    unfolding RCOSETS_def by auto\n  hence \"H <#> K = derived G (carrier G) #> (g1 \\<otimes> g2)\"\n    by (simp add: DG.rcos_sum)\n  also have \" ... = derived G (carrier G) #> (g2 \\<otimes> g1)\"\n  proof -\n    { fix g1 g2 assume g1: \"g1 \\<in> carrier G\" and g2: \"g2 \\<in> carrier G\"\n      have \"derived G (carrier G) #> (g1 \\<otimes> g2) \\<subseteq> derived G (carrier G) #> (g2 \\<otimes> g1)\"\n      proof\n        fix h assume \"h \\<in> derived G (carrier G) #> (g1 \\<otimes> g2)\"\n        then obtain g' where h: \"g' \\<in> carrier G\" \"g' \\<in> derived G (carrier G)\" \"h = g' \\<otimes> (g1 \\<otimes> g2)\"\n          using DG.subset unfolding r_coset_def by auto\n        hence \"h = g' \\<otimes> (g1 \\<otimes> g2) \\<otimes> (inv g1 \\<otimes> inv g2 \\<otimes> g2 \\<otimes> g1)\"\n          using g1 g2 by (simp add: m_assoc)\n        hence \"h = (g' \\<otimes> (g1 \\<otimes> g2 \\<otimes> inv g1 \\<otimes> inv g2)) \\<otimes> (g2 \\<otimes> g1)\"\n          using h(1) g1 g2 inv_closed m_assoc m_closed by presburger\n        moreover have \"g1 \\<otimes> g2 \\<otimes> inv g1 \\<otimes> inv g2 \\<in> derived G (carrier G)\"\n          using incl[of _ \"derived_set G (carrier G)\"] g1 g2 unfolding derived_def by blast\n        hence \"g' \\<otimes> (g1 \\<otimes> g2 \\<otimes> inv g1 \\<otimes> inv g2) \\<in> derived G (carrier G)\"\n          using DG.m_closed[OF h(2)] by simp\n        ultimately show \"h \\<in> derived G (carrier G) #> (g2 \\<otimes> g1)\"\n          unfolding r_coset_def by blast\n      qed }\n    thus ?thesis\n      using g1(1) g2(1) by auto\n  qed\n  also have \" ... = K <#> H\"\n    by (simp add: g1 g2 DG.rcos_sum)\n  finally show \"H <#> K = K <#> H\" .\nqed\n\ncorollary (in group) derived_quot_of_subgroup_is_comm_group:\n  assumes \"subgroup H G\" shows \"comm_group ((G \\<lparr> carrier := H \\<rparr>) Mod (derived G H))\"\n  using group.derived_quot_is_comm_group[OF subgroup_imp_group[OF assms]]\n        derived_consistent[OF _ assms]\n  by simp\n\nproposition (in group) derived_minimal:\n  assumes \"H \\<lhd> G\" and \"comm_group (G Mod H)\" shows \"derived G (carrier G) \\<subseteq> H\"\nproof -\n  interpret H: normal H G\n    using assms(1) .\n\n  show ?thesis\n    unfolding derived_def\n  proof (rule generate_subgroup_incl[OF _ H.subgroup_axioms])\n    show \"derived_set G (carrier G) \\<subseteq> H\"\n    proof\n      fix h assume \"h \\<in> derived_set G (carrier G)\"\n      then obtain g1 g2 where h: \"g1 \\<in> carrier G\" \"g2 \\<in> carrier G\" \"h = g1 \\<otimes> g2 \\<otimes> inv g1 \\<otimes> inv g2\"\n        by auto\n      have \"H #> (g1 \\<otimes> g2) = (H #> g1) <#> (H #> g2)\"\n        by (simp add: h(1-2) H.rcos_sum)\n      also have \" ... = (H #> g2) <#> (H #> g1)\"\n        using comm_groupE(4)[OF assms(2)] h(1-2) unfolding FactGroup_def RCOSETS_def by auto\n      also have \" ... = H #> (g2 \\<otimes> g1)\"\n        by (simp add: h(1-2) H.rcos_sum)\n      finally have \"H #> (g1 \\<otimes> g2) = H #> (g2 \\<otimes> g1)\" .\n      then obtain h' where \"h' \\<in> H\" \"\\<one> \\<otimes> (g1 \\<otimes> g2) = h' \\<otimes> (g2 \\<otimes> g1)\"\n        using H.one_closed unfolding r_coset_def by blast\n      thus \"h \\<in> H\"\n        using h m_assoc by auto\n    qed\n  qed\nqed\n\nproposition (in group) derived_of_subgroup_minimal:\n  assumes \"K \\<lhd> G \\<lparr> carrier := H \\<rparr>\" \"subgroup H G\" and \"comm_group ((G \\<lparr> carrier := H \\<rparr>) Mod K)\"\n  shows \"derived G H \\<subseteq> K\"\n  using group.derived_minimal[OF subgroup_imp_group[OF assms(2)] assms(1,3)]\n        derived_consistent[OF _ assms(2)]\n  by simp\n\nlemma (in group_hom) derived_img:\n  assumes \"K \\<subseteq> carrier G\" shows \"derived H (h ` K) = h ` (derived G K)\"\nproof -\n  have \"derived_set H (h ` K) = h ` (derived_set G K)\"\n  proof\n    show \"derived_set H (h ` K) \\<subseteq> h ` derived_set G K\"\n    proof\n      fix a assume \"a \\<in> derived_set H (h ` K)\"\n      then obtain k1 k2\n        where \"k1 \\<in> K\" \"k2 \\<in> K\" \"a = (h k1) \\<otimes>\\<^bsub>H\\<^esub> (h k2) \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> (h k1) \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> (h k2)\"\n        by auto\n      hence \"a = h (k1 \\<otimes> k2 \\<otimes> inv k1 \\<otimes> inv k2)\"\n        using assms by (simp add: subset_iff)\n      from this \\<open>k1 \\<in> K\\<close> and \\<open>k2 \\<in> K\\<close> show \"a \\<in> h ` derived_set G K\" by auto\n    qed\n  next\n    show \"h ` (derived_set G K) \\<subseteq> derived_set H (h ` K)\"\n    proof\n      fix a assume \"a \\<in> h ` (derived_set G K)\"\n      then obtain k1 k2 where \"k1 \\<in> K\" \"k2 \\<in> K\" \"a = h (k1 \\<otimes> k2 \\<otimes> inv k1 \\<otimes> inv k2)\"\n        by auto\n      hence \"a = (h k1) \\<otimes>\\<^bsub>H\\<^esub> (h k2) \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> (h k1) \\<otimes>\\<^bsub>H\\<^esub> inv\\<^bsub>H\\<^esub> (h k2)\"\n        using assms by (simp add: subset_iff)\n      from this \\<open>k1 \\<in> K\\<close> and \\<open>k2 \\<in> K\\<close> show \"a \\<in> derived_set H (h ` K)\" by auto\n    qed\n  qed\n  thus ?thesis\n    unfolding derived_def using generate_img[OF G.derived_set_in_carrier[OF assms]] by simp\nqed\n\nlemma (in group_hom) exp_of_derived_img:\n  assumes \"K \\<subseteq> carrier G\" shows \"(derived H ^^ n) (h ` K) = h ` ((derived G ^^ n) K)\"\n  using derived_img[OF G.exp_of_derived_in_carrier[OF assms]] by (induct n) (auto)\n\nend", "meta": {"author": "DeVilhena-Paulo", "repo": "GaloisCVC4", "sha": "7d7e0ea67f44a3655ad145650c4fd24b3c159fa8", "save_path": "github-repos/isabelle/DeVilhena-Paulo-GaloisCVC4", "path": "github-repos/isabelle/DeVilhena-Paulo-GaloisCVC4/GaloisCVC4-7d7e0ea67f44a3655ad145650c4fd24b3c159fa8/Generated_Groups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.891811041124754, "lm_q1q2_score": 0.7810365203901476}}
{"text": "theory P26 imports Main begin\n\nfun le :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"le n Nil = True\" |\n\"le n (x # xs) = (n\\<le>x \\<and> (le n xs))\"\n\nfun sorted :: \"nat list \\<Rightarrow> bool\" where\n\"sorted Nil = True\" |\n\"sorted (x # xs) = (le x xs \\<and> (sorted xs))\"\n\nfun count :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"count Nil x = 0\" |\n\"count (y # ys) x = (count ys x + (if x=y then 1 else 0))\"\n\nfun merge :: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n\"merge xs Nil = xs\" |\n\"merge Nil ys = ys\" |\n\"merge (x # xs) (y # ys) = \n  (if x \\<le> y then (x # (merge xs (y # ys))) \n  else (y # (merge (x # xs) ys)))\"\n\nfun msort :: \"nat list \\<Rightarrow> nat list\" where\n\"msort Nil = Nil\" |\n\"msort (x # Nil) = (x # Nil)\" |\n\"msort xs = (merge (msort (take ((length xs) div 2) xs))\n                   (msort (drop ((length xs) div 2) xs)))\"\n\n\n\nlemma [simp]: \"le x (merge xs ys) = (le x xs \\<and> le x ys)\"\n  apply (induct xs ys rule: merge.induct)\n  apply auto\ndone\n\nlemma [simp]: \"sorted (merge xs ys) = (sorted xs \\<and> sorted ys)\"\n  apply (induct xs ys rule: merge.induct)\n    apply (auto simp add: linorder_not_le order_less_le)\n  done\n\ntheorem \"sorted (msort xs)\"\n  apply (induct xs rule: msort.induct)\n    apply auto\n  done\n\nlemma [simp]: \"count (merge xs ys) a = (count xs a) + (count ys a)\"\n  apply (induct xs ys rule: merge.induct)\n    apply auto\n  done\n\nlemma [simp]: \"count xs a + count ys a = (count (xs @ ys) a)\"\n  apply (induct xs)\n   apply auto\n  done\n\ntheorem \"count (msort xs) x = count xs x\"\n  apply (induct xs rule: msort.induct)\n    apply auto\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P26.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.8558511506439707, "lm_q1q2_score": 0.7809095357954908}}
{"text": "(*  Title:      HOL/ex/Primrec.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n*)\n\nsection \\<open>Ackermann's Function and the Primitive Recursive Functions\\<close>\n\ntheory Primrec imports MainRLT begin\n\ntext \\<open>\n  Proof adopted from\n\n  Nora Szasz, A Machine Checked Proof that Ackermann's Function is not\n  Primitive Recursive, In: Huet \\& Plotkin, eds., Logical Environments\n  (CUP, 1993), 317-338.\n\n  See also E. Mendelson, Introduction to Mathematical Logic.  (Van\n  Nostrand, 1964), page 250, exercise 11.\n  \\medskip\n\\<close>\n\n\nsubsection\\<open>Ackermann's Function\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n =  Suc n\"\n| \"ack (Suc m) 0 = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\n\ntext \\<open>PROPERTY A 4\\<close>\n\nlemma less_ack2 [iff]: \"j < ack i j\"\n  by (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc2 [iff]: \"ack i j < ack i (Suc j)\"\n  by (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5, monotonicity for \\<open><\\<close>\\<close>\n\nlemma ack_less_mono2: \"j < k \\<Longrightarrow> ack i j < ack i k\"\n  by (simp add: lift_Suc_mono_less)\n\n\ntext \\<open>PROPERTY A 5', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono2: \"j \\<le> k \\<Longrightarrow> ack i j \\<le> ack i k\"\n  by (simp add: ack_less_mono2 less_mono_imp_le_mono)\n\n\ntext \\<open>PROPERTY A 6\\<close>\n\nlemma ack2_le_ack1 [iff]: \"ack i (Suc j) \\<le> ack (Suc i) j\"\nproof (induct j)\n  case 0 show ?case by simp\nnext\n  case (Suc j) show ?case\n    by (metis Suc ack.simps(3) ack_le_mono2 le_trans less_ack2 less_eq_Suc_le) \nqed\n\n\ntext \\<open>PROPERTY A 7-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc1 [iff]: \"ack i j < ack (Suc i) j\"\n  by (blast intro: ack_less_mono2 less_le_trans)\n\n\ntext \\<open>PROPERTY A 4'? Extra lemma needed for \\<^term>\\<open>CONSTANT\\<close> case, constant functions\\<close>\n\nlemma less_ack1 [iff]: \"i < ack i j\"\nproof (induct i)\n  case 0\n  then show ?case \n    by simp\nnext\n  case (Suc i)\n  then show ?case\n    using less_trans_Suc by blast\nqed\n\n\ntext \\<open>PROPERTY A 8\\<close>\n\nlemma ack_1 [simp]: \"ack (Suc 0) j = j + 2\"\n  by (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 9.  The unary \\<open>1\\<close> and \\<open>2\\<close> in \\<^term>\\<open>ack\\<close> is essential for the rewriting.\\<close>\n\nlemma ack_2 [simp]: \"ack (Suc (Suc 0)) j = 2 * j + 3\"\n  by (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 7, monotonicity for \\<open><\\<close> [not clear why\n  @{thm [source] ack_1} is now needed first!]\\<close>\n\nlemma ack_less_mono1_aux: \"ack i k < ack (Suc (i +i')) k\"\nproof (induct i k rule: ack.induct)\n  case (1 n) show ?case\n    using less_le_trans by auto\nnext\n  case (2 m) thus ?case by simp\nnext\n  case (3 m n) thus ?case\n    using ack_less_mono2 less_trans by fastforce\nqed\n\nlemma ack_less_mono1: \"i < j \\<Longrightarrow> ack i k < ack j k\"\n  using ack_less_mono1_aux less_iff_Suc_add by auto\n\n\ntext \\<open>PROPERTY A 7', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono1: \"i \\<le> j \\<Longrightarrow> ack i k \\<le> ack j k\"\n  using ack_less_mono1 le_eq_less_or_eq by auto\n\n\ntext \\<open>PROPERTY A 10\\<close>\n\nlemma ack_nest_bound: \"ack i1 (ack i2 j) < ack (2 + (i1 + i2)) j\"\nproof -\n  have \"ack i1 (ack i2 j) < ack (i1 + i2) (ack (Suc (i1 + i2)) j)\"\n    by (meson ack_le_mono1 ack_less_mono1 ack_less_mono2 le_add1 le_trans less_add_Suc2 not_less)\n  also have \"... = ack (Suc (i1 + i2)) (Suc j)\"\n    by simp\n  also have \"... \\<le> ack (2 + (i1 + i2)) j\"\n    using ack2_le_ack1 add_2_eq_Suc by presburger\n  finally show ?thesis .\nqed\n\n\n\ntext \\<open>PROPERTY A 11\\<close>\n\nlemma ack_add_bound: \"ack i1 j + ack i2 j < ack (4 + (i1 + i2)) j\"\nproof -\n  have \"ack i1 j \\<le> ack (i1 + i2) j\" \"ack i2 j \\<le> ack (i1 + i2) j\"\n    by (simp_all add: ack_le_mono1)\n  then have \"ack i1 j + ack i2 j < ack (Suc (Suc 0)) (ack (i1 + i2) j)\"\n    by simp\n  also have \"... < ack (4 + (i1 + i2)) j\"\n    by (metis ack_nest_bound add.assoc numeral_2_eq_2 numeral_Bit0)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>PROPERTY A 12.  Article uses existential quantifier but the ALF proof\n  used \\<open>k + 4\\<close>.  Quantified version must be nested \\<open>\\<exists>k'. \\<forall>i j. ...\\<close>\\<close>\n\nlemma ack_add_bound2: \n  assumes \"i < ack k j\" shows \"i + j < ack (4 + k) j\"\nproof -\n  have \"i + j < ack k j + ack 0 j\"\n    using assms by auto\n  also have \"... < ack (4 + k) j\"\n    by (metis ack_add_bound add.right_neutral)\n  finally show ?thesis .\nqed\n\n\nsubsection\\<open>Primitive Recursive Functions\\<close>\n\nprimrec hd0 :: \"nat list \\<Rightarrow> nat\" where\n  \"hd0 [] = 0\" \n| \"hd0 (m # ms) = m\"\n\n\ntext \\<open>Inductive definition of the set of primitive recursive functions of type \\<^typ>\\<open>nat list \\<Rightarrow> nat\\<close>.\\<close>\n\ndefinition SC :: \"nat list \\<Rightarrow> nat\" \n  where \"SC l = Suc (hd0 l)\"\n\ndefinition CONSTANT :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\" \n  where \"CONSTANT k l = k\"\n\ndefinition PROJ :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\" \n  where \"PROJ i l = hd0 (drop i l)\"\n\ndefinition COMP :: \"[nat list \\<Rightarrow> nat, (nat list \\<Rightarrow> nat) list, nat list] \\<Rightarrow> nat\"\n  where \"COMP g fs l = g (map (\\<lambda>f. f l) fs)\"\n\nfun PREC :: \"[nat list \\<Rightarrow> nat, nat list \\<Rightarrow> nat, nat list] \\<Rightarrow> nat\"\n  where\n    \"PREC f g [] = 0\"\n  | \"PREC f g (x # l) = rec_nat (f l) (\\<lambda>y r. g (r # y # l)) x\"\n    \\<comment> \\<open>Note that \\<^term>\\<open>g\\<close> is applied first to \\<^term>\\<open>PREC f g y\\<close> and then to \\<^term>\\<open>y\\<close>!\\<close>\n\ninductive PRIMREC :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n  SC: \"PRIMREC SC\"\n| CONSTANT: \"PRIMREC (CONSTANT k)\"\n| PROJ: \"PRIMREC (PROJ i)\"\n| COMP: \"PRIMREC g \\<Longrightarrow> \\<forall>f \\<in> set fs. PRIMREC f \\<Longrightarrow> PRIMREC (COMP g fs)\"\n| PREC: \"PRIMREC f \\<Longrightarrow> PRIMREC g \\<Longrightarrow> PRIMREC (PREC f g)\"\n\n\ntext \\<open>Useful special cases of evaluation\\<close>\n\nlemma SC [simp]: \"SC (x # l) = Suc x\"\n  by (simp add: SC_def)\n\nlemma PROJ_0 [simp]: \"PROJ 0 (x # l) = x\"\n  by (simp add: PROJ_def)\n\nlemma COMP_1 [simp]: \"COMP g [f] l = g [f l]\"\n  by (simp add: COMP_def)\n\nlemma PREC_0: \"PREC f g (0 # l) = f l\"\n  by simp\n\nlemma PREC_Suc [simp]: \"PREC f g (Suc x # l) = g (PREC f g (x # l) # x # l)\"\n  by auto\n\n\nsubsection \\<open>MAIN RESULT\\<close>\n\nlemma SC_case: \"SC l < ack 1 (sum_list l)\"\n  unfolding SC_def\n  by (induct l) (simp_all add: le_add1 le_imp_less_Suc)\n\nlemma CONSTANT_case: \"CONSTANT k l < ack k (sum_list l)\"\n  by (simp add: CONSTANT_def)\n\nlemma PROJ_case: \"PROJ i l < ack 0 (sum_list l)\"\n  unfolding PROJ_def\nproof (induct l arbitrary: i)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons a l)\n  then show ?case\n    by (metis ack.simps(1) add.commute drop_Cons' hd0.simps(2) leD leI lessI not_less_eq sum_list.Cons trans_le_add2)\nqed\n\n\ntext \\<open>\\<^term>\\<open>COMP\\<close> case\\<close>\n\nlemma COMP_map_aux: \"\\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (sum_list l))\n  \\<Longrightarrow> \\<exists>k. \\<forall>l. sum_list (map (\\<lambda>f. f l) fs) < ack k (sum_list l)\"\nproof (induct fs)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons a fs)\n  then show ?case\n    by simp (blast intro: add_less_mono ack_add_bound less_trans)\nqed\n\nlemma COMP_case:\n  assumes 1: \"\\<forall>l. g l < ack kg (sum_list l)\" \n      and 2: \"\\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (sum_list l))\"\n  shows \"\\<exists>k. \\<forall>l. COMP g fs  l < ack k (sum_list l)\"\n  unfolding COMP_def\n  using 1 COMP_map_aux [OF 2] by (meson ack_less_mono2 ack_nest_bound less_trans)\n\ntext \\<open>\\<^term>\\<open>PREC\\<close> case\\<close>\n\nlemma PREC_case_aux:\n  assumes f: \"\\<And>l. f l + sum_list l < ack kf (sum_list l)\"\n      and g: \"\\<And>l. g l + sum_list l < ack kg (sum_list l)\"\n  shows \"PREC f g l + sum_list l < ack (Suc (kf + kg)) (sum_list l)\"\nproof (cases l)\n  case Nil\n  then show ?thesis\n    by (simp add: Suc_lessD)\nnext\n  case (Cons m l)\n  have \"rec_nat (f l) (\\<lambda>y r. g (r # y # l)) m + (m + sum_list l) < ack (Suc (kf + kg)) (m + sum_list l)\"\n  proof (induct m)\n    case 0\n    then show ?case\n      using ack_less_mono1_aux f less_trans by fastforce\n  next\n    case (Suc m)\n    let ?r = \"rec_nat (f l) (\\<lambda>y r. g (r # y # l)) m\"\n    have \"\\<not> g (?r # m # l) + sum_list (?r # m # l) < g (?r # m # l) + (m + sum_list l)\"\n      by force\n    then have \"g (?r # m # l) + (m + sum_list l) < ack kg (sum_list (?r # m # l))\"\n      by (meson assms(2) leI less_le_trans)\n    moreover \n    have \"... < ack (kf + kg) (ack (Suc (kf + kg)) (m + sum_list l))\"\n      using Suc.hyps by simp (meson ack_le_mono1 ack_less_mono2 le_add2 le_less_trans)\n    ultimately show ?case\n      by auto\n  qed\n  then show ?thesis\n    by (simp add: local.Cons)\nqed\n\nproposition PREC_case:\n  \"\\<lbrakk>\\<And>l. f l < ack kf (sum_list l); \\<And>l. g l < ack kg (sum_list l)\\<rbrakk> \n  \\<Longrightarrow> \\<exists>k. \\<forall>l. PREC f g l < ack k (sum_list l)\"\n  by (metis le_less_trans [OF le_add1 PREC_case_aux] ack_add_bound2)\n\nlemma ack_bounds_PRIMREC: \"PRIMREC f \\<Longrightarrow> \\<exists>k. \\<forall>l. f l < ack k (sum_list l)\"\n  by (erule PRIMREC.induct) (blast intro: SC_case CONSTANT_case PROJ_case COMP_case PREC_case)+\n\ntheorem ack_not_PRIMREC:\n  \"\\<not> PRIMREC (\\<lambda>l. case l of [] \\<Rightarrow> 0 | x # l' \\<Rightarrow> ack x x)\"\nproof\n  assume *: \"PRIMREC (\\<lambda>l. case l of [] \\<Rightarrow> 0 | x # l' \\<Rightarrow> ack x x)\"\n  then obtain m where m: \"\\<And>l. (case l of [] \\<Rightarrow> 0 | x # l' \\<Rightarrow> ack x x) < ack m (sum_list l)\"\n    using ack_bounds_PRIMREC by metis\n  show False\n    using m [of \"[m]\"] by simp\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/ex/Primrec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8740772286044095, "lm_q1q2_score": 0.7808214099302363}}
{"text": "(* License: LGPL *)\n(*\nAuthor: Julian Parsert <julian.parsert@gmail.com>\nAuthor: Cezary Kaliszyk\n*)\n\n\ntheory Common\n  imports\n    \"../Preferences\"\n    \"../Utility_Functions\"\n    \"../Argmax\"\nbegin\n\n\nsection \\<open> Pareto Ordering \\<close>\n\ntext \\<open> Allows us to define a Pareto Ordering. \\<close>\n\nlocale pareto_ordering =\n  fixes agents :: \"'i set\"\n  fixes U :: \"'i \\<Rightarrow> 'a \\<Rightarrow> real\"\nbegin\nnotation U (\"U[_]\")\n\ndefinition pareto_dominating (infix \"\\<succ>Pareto\"  60)\n  where\n    \"X \\<succ>Pareto Y \\<longleftrightarrow>\n      (\\<forall>i \\<in> agents. U[i] (X i) \\<ge> U[i] (Y i)) \\<and>\n      (\\<exists>i \\<in> agents. U[i] (X i) > U[i] (Y i))\"\n\nlemma trans_strict_pareto: \"X \\<succ>Pareto Y \\<Longrightarrow> Y \\<succ>Pareto Z \\<Longrightarrow> X \\<succ>Pareto Z\"\nproof -\n  assume a1: \"X \\<succ>Pareto Y\"\n  assume \"Y \\<succ>Pareto Z\"\n  then have f3: \"\\<forall>i \\<in> agents. U[i] (Z i) \\<le> U[i] (X i)\"\n    by (meson a1 order_trans pareto_dominating_def)\n  moreover have \"\\<exists>i \\<in> agents. \\<not> U[i] (X i) \\<le> U[i] (Y i)\"\n    using a1 pareto_dominating_def by fastforce\n  ultimately show ?thesis\n    by (metis \\<open>Y \\<succ>Pareto Z\\<close> less_eq_real_def pareto_dominating_def)\nqed\n\nlemma anti_sym_strict_pareto: \"X \\<succ>Pareto Y \\<Longrightarrow> \\<not>Y \\<succ>Pareto X\"\n  using pareto_dominating_def by auto\n\nend\n\nsubsection \\<open> Budget constraint\\<close>\n\ntext \\<open> Definition returns all afforedable bundles given wealth W \\<close>\ntext \\<open> f is a function that computes the value given a bundle\\<close>\ndefinition budget_constraint\n  where\n    \"budget_constraint f S W = {x \\<in> S. f x \\<le> W}\"\n\n\nsubsection \\<open> Feasiblity \\<close>\n\ndefinition feasible_private_ownership\n  where\n    \"feasible_private_ownership A F \\<E> Cs Ps X Y \\<longleftrightarrow>\n      (\\<Sum>i\\<in>A. X i) \\<le> (\\<Sum>i\\<in>A. \\<E> i) + (\\<Sum>j\\<in>F. Y j) \\<and>\n      (\\<forall>i\\<in>A. X i \\<in> Cs) \\<and> (\\<forall>j\\<in>F. Y j \\<in> Ps j)\"\n\nlemma feasible_private_ownershipD:\n  assumes \"feasible_private_ownership A F \\<E> Cs Ps X Y\"\n  shows \"(\\<Sum>i\\<in>A. X i) \\<le> (\\<Sum>i\\<in>A. \\<E> i) + (\\<Sum>j\\<in>F. Y j)\"\n    and \"(\\<forall>i\\<in>A. X i \\<in> Cs)\" and \"(\\<forall>j\\<in>F. Y j \\<in> Ps j)\"\n  using assms feasible_private_ownership_def apply blast\n  by (meson assms feasible_private_ownership_def)\n    (meson assms feasible_private_ownership_def)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/First_Welfare_Theorem/Microeconomics/Common.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7807999682389111}}
{"text": "(*  Title:      HOL/Isar_Examples/Group.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Basic group theory\\<close>\n\ntheory Group\nimports Main\nbegin\n\nsubsection \\<open>Groups and calculational reasoning\\<close> \n\ntext \\<open>Groups over signature $({\\times} :: \\alpha \\To \\alpha \\To\n  \\alpha, \\idt{one} :: \\alpha, \\idt{inverse} :: \\alpha \\To \\alpha)$\n  are defined as an axiomatic type class as follows.  Note that the\n  parent class $\\idt{times}$ is provided by the basic HOL theory.\\<close>\n\nclass group = times + one + inverse +\n  assumes group_assoc: \"(x * y) * z = x * (y * z)\"\n    and group_left_one: \"1 * x = x\"\n    and group_left_inverse: \"inverse x * x = 1\"\n\ntext \\<open>The group axioms only state the properties of left one and\n  inverse, the right versions may be derived as follows.\\<close>\n\ntheorem (in group) group_right_inverse: \"x * inverse x = 1\"\nproof -\n  have \"x * inverse x = 1 * (x * inverse x)\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1 * x * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x * x * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (inverse x * x) * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * 1 * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (1 * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1\"\n    by (simp only: group_left_inverse)\n  finally show ?thesis .\nqed\n\ntext \\<open>With \\name{group-right-inverse} already available,\n  \\name{group-right-one}\\label{thm:group-right-one} is now established\n  much easier.\\<close>\n\ntheorem (in group) group_right_one: \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\\medskip The calculational proof style above follows typical\n  presentations given in any introductory course on algebra.  The\n  basic technique is to form a transitive chain of equations, which in\n  turn are established by simplifying with appropriate rules.  The\n  low-level logical details of equational reasoning are left implicit.\n\n  Note that ``$\\dots$'' is just a special term variable that is bound\n  automatically to the argument\\footnote{The argument of a curried\n  infix expression happens to be its right-hand side.} of the last\n  fact achieved by any local assumption or proven statement.  In\n  contrast to $\\var{thesis}$, the ``$\\dots$'' variable is bound\n  \\emph{after} the proof is finished, though.\n\n  There are only two separate Isar language elements for calculational\n  proofs: ``\\isakeyword{also}'' for initial or intermediate\n  calculational steps, and ``\\isakeyword{finally}'' for exhibiting the\n  result of a calculation.  These constructs are not hardwired into\n  Isabelle/Isar, but defined on top of the basic Isar/VM interpreter.\n  Expanding the \\isakeyword{also} and \\isakeyword{finally} derived\n  language elements, calculations may be simulated by hand as\n  demonstrated below.\\<close>\n\ntheorem (in group) \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n\n  note calculation = this\n    -- \\<open>first calculational step: init calculation register\\<close>\n\n  have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n\n  note calculation = trans [OF calculation this]\n    -- \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n\n  note calculation = trans [OF calculation this]\n    -- \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n\n  note calculation = trans [OF calculation this]\n    -- \\<open>final calculational step: compose with transitivity rule \\dots\\<close>\n  from calculation\n    -- \\<open>\\dots\\ and pick up the final result\\<close>\n\n  show ?thesis .\nqed\n\ntext \\<open>Note that this scheme of calculations is not restricted to\n  plain transitivity.  Rules like anti-symmetry, or even forward and\n  backward substitution work as well.  For the actual implementation\n  of \\isacommand{also} and \\isacommand{finally}, Isabelle/Isar\n  maintains separate context information of ``transitivity'' rules.\n  Rule selection takes place automatically by higher-order\n  unification.\\<close>\n\n\nsubsection \\<open>Groups as monoids\\<close>\n\ntext \\<open>Monoids over signature $({\\times} :: \\alpha \\To \\alpha \\To\n  \\alpha, \\idt{one} :: \\alpha)$ are defined like this.\\<close>\n\nclass monoid = times + one +\n  assumes monoid_assoc: \"(x * y) * z = x * (y * z)\"\n    and monoid_left_one: \"1 * x = x\"\n    and monoid_right_one: \"x * 1 = x\"\n\ntext \\<open>Groups are \\emph{not} yet monoids directly from the\n  definition.  For monoids, \\name{right-one} had to be included as an\n  axiom, but for groups both \\name{right-one} and \\name{right-inverse}\n  are derivable from the other axioms.  With \\name{group-right-one}\n  derived as a theorem of group theory (see\n  page~\\pageref{thm:group-right-one}), we may still instantiate\n  $\\idt{group} \\subseteq \\idt{monoid}$ properly as follows.\\<close>\n\ninstance group < monoid\n  by intro_classes\n    (rule group_assoc,\n      rule group_left_one,\n      rule group_right_one)\n\ntext \\<open>The \\isacommand{instance} command actually is a version of\n  \\isacommand{theorem}, setting up a goal that reflects the intended\n  class relation (or type constructor arity).  Thus any Isar proof\n  language element may be involved to establish this statement.  When\n  concluding the proof, the result is transformed into the intended\n  type signature extension behind the scenes.\\<close>\n\n\nsubsection \\<open>More theorems of group theory\\<close>\n\ntext \\<open>The one element is already uniquely determined by preserving\n  an \\emph{arbitrary} group element.\\<close>\n\ntheorem (in group) group_one_equality:\n  assumes eq: \"e * x = x\"\n  shows \"1 = e\"\nproof -\n  have \"1 = x * inverse x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = (e * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = e * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = e * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>Likewise, the inverse is already determined by the cancel property.\\<close>\n\ntheorem (in group) group_inverse_equality:\n  assumes eq: \"x' * x = 1\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = 1 * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = (x' * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = x' * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = x' * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>The inverse operation has some further characteristic properties.\\<close>\n\ntheorem (in group) group_inverse_times: \"inverse (x * y) = inverse y * inverse x\"\nproof (rule group_inverse_equality)\n  show \"(inverse y * inverse x) * (x * y) = 1\"\n  proof -\n    have \"(inverse y * inverse x) * (x * y) =\n        (inverse y * (inverse x * x)) * y\"\n      by (simp only: group_assoc)\n    also have \"\\<dots> = (inverse y * 1) * y\"\n      by (simp only: group_left_inverse)\n    also have \"\\<dots> = inverse y * y\"\n      by (simp only: group_right_one)\n    also have \"\\<dots> = 1\"\n      by (simp only: group_left_inverse)\n    finally show ?thesis .\n  qed\nqed\n\ntheorem (in group) inverse_inverse: \"inverse (inverse x) = x\"\nproof (rule group_inverse_equality)\n  show \"x * inverse x = one\"\n    by (simp only: group_right_inverse)\nqed\n\ntheorem (in group) inverse_inject:\n  assumes eq: \"inverse x = inverse y\"\n  shows \"x = y\"\nproof -\n  have \"x = x * 1\"\n    by (simp only: group_right_one)\n  also have \"\\<dots> = x * (inverse y * y)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * (inverse x * y)\"\n    by (simp only: eq)\n  also have \"\\<dots> = (x * inverse x) * y\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * y\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = y\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\nend", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Isar_Examples/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7807915435570445}}
{"text": "header {* Solutions to Chapter 3 of \"Concrete Semantics\" *}\n\ntheory Chap_three imports Main begin\n\ndeclare [[names_short]]\n\n(* 3.1 *)\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N a) s = a\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a b) s = aval a s + aval b s\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N a) = N a\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus p q) = \n (case (asimp_const p, asimp_const q) of \n  (N a, N b) \\<Rightarrow> N (a+b) |\n  (x, y) \\<Rightarrow> Plus x y)\"\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N a) (N b) = N (a+b)\" |\n\"plus p (N i) = (if i = 0 then p else Plus p (N i))\" |\n\"plus (N i) p = (if i = 0 then p else Plus (N i) p)\" |\n\"plus p q = (Plus p q)\"\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N a) = N a\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus p q) = plus (asimp p) (asimp q)\"\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N a) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus (N a) (N b)) = False\" | \n\"optimal (Plus x y) = ((optimal x) \\<and> (optimal y))\"\n\ntheorem asimp_const_optimal: \"optimal (asimp_const a)\"\napply (induction a)\napply (auto split: aexp.split)\ndone\n\n(* 3.2 *)\n\nfun plus_ex :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus_ex (N a) (N b) = N (a+b)\" |\n\"plus_ex (Plus p (N a)) (N b) = Plus p (N (a+b))\" |\n\"plus_ex (N b) (Plus p (N a)) = Plus p (N (a+b))\" |\n\"plus_ex (Plus p (N a)) q = Plus (Plus p q) (N a)\" |\n\"plus_ex q (Plus p (N a)) = Plus (Plus p q) (N a)\" |\n\"plus_ex p (N i) = (if i = 0 then p else Plus p (N i))\" |\n\"plus_ex (N i) p = (if i = 0 then p else Plus p (N i))\" |\n\"plus_ex p q = (Plus p q)\"\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp (N a) = N a\" |\n\"full_asimp (V x) = V x\" |\n\"full_asimp (Plus p q) = plus_ex (full_asimp p) (full_asimp q)\"\n\nvalue \"full_asimp (Plus (Plus ((Plus (V ''x'') (N 7))) (V ''x'')) (N 5))\" \n\nlemma aval_plus_ex: \"aval (plus_ex p q) s = aval p s + aval q s\"\napply (induction rule:plus_ex.induct)\napply (auto)\ndone\n\ntheorem \"aval (full_asimp p) s = aval p s\"\napply (induction p)\napply (auto simp add:aval_plus_ex)\ndone\n\n(* 3.3 *)\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst x a (N k) = (N k)\" |\n\"subst x a (V y) = (if x = y then a else (V y))\" |\n\"subst x a (Plus p q) = Plus (subst x a p) (subst x a q)\"\n\ntheorem aval_subst[simp]:  \"aval (subst x a e) s = aval e (s(x:=aval a s))\"\napply (induction e)\napply (auto)\ndone \n\ntheorem \"aval a s = aval b s \\<Longrightarrow> aval (subst x a e) s = aval (subst x b e) s\"\napply (auto)\ndone\n\n(* 3.4 *)\n\ndatatype aexpm = Nm int | Vm vname | Plusm aexpm aexpm | Timesm aexpm aexpm\n\nfun avalm :: \"aexpm \\<Rightarrow> state \\<Rightarrow> val\" where\n\"avalm (Nm a) s = a\" |\n\"avalm (Vm x) s = s x\" |\n\"avalm (Plusm a b) s = avalm a s + avalm b s\" |\n\"avalm (Timesm a b) s = avalm a s * avalm b s\"\n\nfun plusm :: \"aexpm \\<Rightarrow> aexpm \\<Rightarrow> aexpm\" where\n\"plusm (Nm a) (Nm b) = Nm (a+b)\" |\n\"plusm p (Nm i) = (if i = 0 then p else Plusm p (Nm i))\" |\n\"plusm (Nm i) p = (if i = 0 then p else Plusm (Nm i) p)\" |\n\"plusm p q = (Plusm p q)\"\n\nfun timesm :: \"aexpm \\<Rightarrow> aexpm \\<Rightarrow> aexpm\" where\n\"timesm (Nm a) (Nm b) = Nm (a*b)\" |\n\"timesm p (Nm i) = (if i = 0 then (Nm 0) else if i = 1 then p else Timesm p (Nm i))\" |\n\"timesm (Nm i) p = (if i = 0 then (Nm 0) else if i = 1 then p else Timesm p (Nm i))\" |\n\"timesm p q = (Timesm p q)\"\n\nfun asimpm :: \"aexpm \\<Rightarrow> aexpm\" where\n\"asimpm (Nm a) = Nm a\" |\n\"asimpm (Vm x) = Vm x\" |\n\"asimpm (Plusm p q) = plusm (asimpm p) (asimpm q)\" |\n\"asimpm (Timesm p q) = timesm (asimpm p) (asimpm q)\"\n\nlemma avalm_plus[simp]: \"avalm (plusm p q) s = avalm p s + avalm q s\"\napply (induction rule:plusm.induct)\napply (auto)\ndone\n\nlemma avalm_times[simp]: \"avalm (timesm p q) s = avalm p s * avalm q s\"\napply (induction rule:timesm.induct)\napply (auto)\ndone\n\ntheorem \"avalm (asimpm p) s = avalm p s\"\napply (induction p)\napply (auto)\ndone \n\n(*  3.5 *)\n\ndatatype aexp2 = N2 int | V2 vname | PlusPlus2 vname | Plus2 aexp2 aexp2 | \n Times2 aexp2 aexp2 | Div2 aexp2 aexp2 \n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"aval2 (N2 a) s = Some (a, s)\" |\n\"aval2 (V2 x) s = Some (s x, s)\" |\n\"aval2 (PlusPlus2 x) s = Some (s x, s(x:= 1 + (s x)))\" |\n\"aval2 (Plus2 a b) s = \n (case (aval2 a s, aval2 b s) of \n  (None, Some q) \\<Rightarrow> None |\n  (Some p, None) \\<Rightarrow> None |\n  (Some p, Some q) \\<Rightarrow> Some ((fst p + fst q), (\\<lambda>x.((snd p) x) + ((snd q) x) - (s x))))\" |\n\"aval2 (Times2 a b) s = \n (case (aval2 a s, aval2 b s) of \n  (None, Some q) \\<Rightarrow> None |\n  (Some p, None) \\<Rightarrow> None |\n  (Some p, Some q) \\<Rightarrow> Some ((fst p * fst q), (\\<lambda>x.((snd p) x) + ((snd q) x) - (s x))))\" |\n\"aval2 (Div2 a b) s =\n (case (aval2 a s, aval2 b s) of \n  (None, Some q) \\<Rightarrow> None |\n  (Some p, None) \\<Rightarrow> None |\n  (Some p, Some q) \\<Rightarrow> \n   (if fst q = 0 then \n    None \n   else Some ((fst p div fst q), (\\<lambda>x.((snd p) x) + ((snd q) x) - (s x)))))\"\n\n(* 3.6 *)\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n\"lval (Nl a) s = a\" |\n\"lval (Vl x) s = s x\" |\n\"lval (Plusl p q) s = lval p s + lval q s\" |\n\"lval (LET x a e) s = lval e (s(x:=lval a s))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl a) = (N a)\" |\n\"inline (Vl x) = (V x)\" |\n\"inline (Plusl p q) = Plus (inline p) (inline q)\" |\n\"inline (LET x a e) = subst x (inline a) (inline e)\"  \n\ntheorem \"aval (inline e) s = lval e s\"\napply (induction e arbitrary:s)\napply (auto)\ndone\n\n(* 3.7 *)\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And a b) s = (bval a s \\<and> bval b s)\" |\n\"bval (Less a b) s = (aval a s < aval b s)\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n) (N m) = Bc(n < m)\" |\n\"less a b = Less a b\"\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and a b = And a b\"\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And a b) = and (bsimp a) (bsimp b)\" |\n\"bsimp (Less a b) = less (asimp a) (asimp b)\"\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq p q = And (Not (Less p q)) (Not (Less q p))\"\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le p q = Not (Less q p)\"\n\ntheorem \"bval (Eq p q) s = (aval p s = aval q s)\"\napply (auto simp add:Eq_def)\ndone\n\ntheorem \"bval (Le p q) s = (aval p s \\<le> aval q s)\"\napply (auto simp add:Le_def)\ndone\n\n(* 3.8 *)\n\ndefinition or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"or p q = Not (And (Not p) (Not q))\"\n\ndefinition implies :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"implies p q = or (Not p) q\"\n\ndefinition bIf :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"bIf a b c = And (implies a b) (implies (Not a) c)\"\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n \nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 b) s = b\" |\n\"ifval (If a b c) s = (if (ifval a s) then (ifval b s) else (ifval c s))\" |\n\"ifval (Less2 x y) s = (aval x s < aval y s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc b) = Bc2 b\" |\n\"b2ifexp (Not b) = (If (b2ifexp b) (Bc2 False) (Bc2 True))\" |\n\"b2ifexp (And a b) = (If (b2ifexp a) (b2ifexp b) (Bc2 False))\" |\n\"b2ifexp (Less x y) = (Less2 x y)\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b) = Bc b\" |\n\"if2bexp (If a b c) = bIf (if2bexp a) (if2bexp b) (if2bexp c)\" |\n\"if2bexp (Less2 x y) = (Less x y)\"\n\ntheorem \"bval (if2bexp p) s = ifval p s\"\napply (induction p)\napply (auto simp add:bIf_def implies_def or_def)\ndone\n\ntheorem \"ifval (b2ifexp p) s = bval p s\"\napply (induction p)\napply (auto)\ndone\n\n(* 3.9 *)\n\ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\" |\n\"pbval (NOT a) s = (\\<not>pbval a s)\" |\n\"pbval (AND a b) s = (pbval a s \\<and> pbval b s)\" |\n\"pbval (OR a b) s = (pbval a s \\<or> pbval b s)\"\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (NOT (VAR x)) = True\" |\n\"is_nnf (NOT p) = False\" |\n\"is_nnf (AND p q) = (is_nnf p \\<and> is_nnf q)\" |\n\"is_nnf (OR p q) = (is_nnf p \\<and> is_nnf q)\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = (VAR x)\" |\n\"nnf (NOT (VAR p)) = (NOT (VAR p))\" |\n\"nnf (NOT (NOT p)) = nnf p\" |\n\"nnf (NOT (AND p q)) = OR (nnf (NOT p)) (nnf (NOT q))\" |\n\"nnf (NOT (OR p q)) = AND (nnf (NOT p)) (nnf (NOT q))\" |\n\"nnf (AND p q) = AND (nnf p) (nnf q)\" |\n\"nnf (OR p q) = OR (nnf p) (nnf q)\"\n\nlemma not_nnf[simp]: \"pbval (nnf (NOT p)) s = (\\<not> (pbval (nnf p) s))\"\napply (induction p)\napply (auto)\ndone\n\ntheorem \"pbval (nnf p) s = pbval p s\"\napply (induction p)\napply (auto)\ndone\n\nlemma nnf_n: \"is_nnf (nnf p)\"\napply (induction p rule:nnf.induct)\napply (auto)\ndone\n\nfun andb :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"andb p (OR h t) = OR (andb p h) (andb p t)\" |\n\"andb (OR h t) p = OR (andb h p) (andb t p)\" |\n\"andb p q = AND p q\"\n\nlemma pbval_andb: \"pbval (andb a b) s = pbval (AND a b) s\"\napply (induction a b rule:andb.induct)\napply (auto)\ndone\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR x) = VAR x\" |\n\"dnf_of_nnf (NOT p) = NOT p\" |\n\"dnf_of_nnf (OR p q) = OR (dnf_of_nnf p) (dnf_of_nnf q)\" |\n\"dnf_of_nnf (AND p q) = andb (dnf_of_nnf p) (dnf_of_nnf q)\"\n\ntheorem \"pbval (dnf_of_nnf p) s = pbval p s\"\napply (induction p)\napply (auto simp add: pbval_andb)\ndone\n\nfun is_no_or :: \"pbexp \\<Rightarrow> bool\" where\n\"is_no_or (VAR x) = True\" |\n\"is_no_or (NOT p) = True\" |\n\"is_no_or (AND p q) = ((is_no_or p) \\<and> (is_no_or q))\" |\n\"is_no_or (OR p q) = False\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf (VAR x) = True\" |\n\"is_dnf (NOT p) = True\" |\n\"is_dnf (AND p q) = ((is_no_or p) \\<and> (is_no_or q))\" |\n\"is_dnf (OR p q) = ((is_dnf p) \\<and> (is_dnf q))\"\n\nlemma isdnf_andb: \"is_dnf p \\<Longrightarrow> is_dnf q \\<Longrightarrow> is_dnf (andb p q)\"\napply (induction p q rule:andb.induct)\napply (auto)\ndone \n\ntheorem \"is_nnf p \\<Longrightarrow> is_dnf (dnf_of_nnf p)\"\napply (induction p)\napply (auto simp add: isdnf_andb)\ndone\n\n(* 3.10 *)\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nabbreviation hd2 where \n\"hd2 xs \\<equiv> hd (tl xs)\"\n\nabbreviation tl2 where \n\"tl2 xs \\<equiv> tl (tl xs)\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec1 (LOADI n) _ stk = Some (n # stk)\" |\n\"exec1 (LOAD x) s stk = Some (s(x) # stk)\" |\n\"exec1 ADD _ stk = \n (case stk of \n  (x # y # xs) \\<Rightarrow> Some ((hd2 stk + hd stk) # tl2 stk) |\n  (xs) \\<Rightarrow> None)\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec [] _ stk = Some stk\" |\n\"exec (i#is) s stk = \n (case (exec1 i s stk) of \n  Some res \\<Rightarrow> exec is s res |\n  None \\<Rightarrow> None)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\nlemma exec_append: \"exec is1 s stk = Some new_stk \\<Longrightarrow> exec (is1 @ is2) s stk = exec is2 s new_stk\"\napply (induction is1 arbitrary:stk)\napply (auto split:option.split)\ndone\n\nlemma \"exec (comp a) s stk = Some (aval a s # stk)\"\napply (induction a arbitrary:stk)\napply (auto simp add: exec_append)\ndone\n\n(* 3.11 *)\n\ntype_synonym reg = nat \n\ndatatype rinstr = LDI val reg | LD vname reg | ADD reg reg\n\nfun rexec1 :: \"rinstr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"rexec1 (LDI n r) s rs = rs(r:=n)\" |\n\"rexec1 (LD v r) s rs = rs(r:=(s v))\" |\n\"rexec1 (ADD r q) s rs = rs(r:=(rs r)+(rs q))\"\n\nfun rexec :: \"rinstr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"rexec [] s rs = rs\" |\n\"rexec (x # xs) s rs = rexec xs s (rexec1 x s rs)\"\n\nfun rcomp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> rinstr list\" where\n\"rcomp (N n) r = [LDI n r]\" |\n\"rcomp (V x) r = [LD x r]\" |\n\"rcomp (Plus p q) r = (rcomp p r) @ (rcomp q (r+1)) @ ([ADD r (r+1)])\"\n\nlemma rexec_app[simp]: \"rexec (xs @ ys) s rs = rexec ys s (rexec xs s rs)\"\napply (induction xs arbitrary: rs)\napply (auto)\ndone\n\nlemma rcomp_respects: \"r < q \\<Longrightarrow> rexec (rcomp a q) s rs r = rs r\"\napply (induction a arbitrary: rs r q)\napply (auto)\ndone\n\ntheorem \"rexec (rcomp a r) s rs r = aval a s\"\napply (induction a arbitrary:rs r)\napply (auto simp add: rcomp_respects)\ndone\n\n(* 3.12 *)\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg \n\nfun exec10 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec10 (LDI0 n) s rs = rs(0:=n)\" |\n\"exec10 (LD0 v) s rs = rs(0:=(s v))\" |\n\"exec10 (MV0 r) s rs = rs(r:=(rs 0))\" |\n\"exec10 (ADD0 r) s rs = rs(0:=(rs 0)+(rs r))\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec0 [] s rs = rs\" |\n\"exec0 (x # xs) s rs = exec0 xs s (exec10 x s rs)\"\n\nfun comp0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0 (N n) r = [LDI0 n]\" |\n\"comp0 (V x) r = [LD0 x]\" |\n\"comp0 (Plus p q) r = (comp0 p (r+1)) @ [MV0 (r+1)] @ (comp0 q (r+2)) @ [ADD0 (r+1)]\"\n\nlemma exec0_app[simp]: \"exec0 (xs @ ys) s rs = exec0 ys s (exec0 xs s rs)\"\napply (induction xs arbitrary: rs)\napply (auto)\ndone\n\nlemma comp0_respects: \"(0 < r) \\<and> (r \\<le> q) \\<Longrightarrow> exec0 (comp0 a q) s rs r = rs r\"\napply (induction a arbitrary: rs r q)\napply (auto)\ndone\n\ntheorem \"exec0 (comp0 a r) s rs 0 = aval a s\"\napply (induction a arbitrary:rs r)\napply (auto simp add:comp0_respects)\ndone\n\nend\n", "meta": {"author": "kolya-vasiliev", "repo": "concrete-semantics", "sha": "ae2a4b32ec63766e6a11e043d85d082c70eeaebc", "save_path": "github-repos/isabelle/kolya-vasiliev-concrete-semantics", "path": "github-repos/isabelle/kolya-vasiliev-concrete-semantics/concrete-semantics-ae2a4b32ec63766e6a11e043d85d082c70eeaebc/Chap_three.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7805448404788583}}
{"text": "theory exercises_3 \n  imports Main \"../My_IMP/Exp\"\nbegin\ntext \\<open>Exercise 3.1\\<close>\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N n) = True\" |\n\"optimal (V v) = True\" |\n\"optimal (Plus (N n1) (N n2)) = False\" |\n\"optimal (Plus e1 e2) = ((optimal e1) \\<and> (optimal e2))\"\n\nlemma \"optimal (asimp_const e)\"\n  apply(induct e)\n  by(auto split: aexp.split)\n\ntext \\<open>Exercise 3.2\\<close>\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp (N n) = (N n)\" |\n\"full_asimp (V v) = (V v)\" |\n\"full_asimp (Plus e1 e2) = \n  (case (full_asimp e1, full_asimp e2) of\n    (N n1, N n2) \\<Rightarrow> (N (n1 + n2)) |\n    (N n1, (Plus e1' (N n2))) \\<Rightarrow> (Plus e1' (N (n1 + n2))) |\n    (N n1, (Plus (N n2) e2')) \\<Rightarrow> (Plus (N (n1 + n2)) e2') |\n    ((Plus e1' (N n1)), N n2) \\<Rightarrow> (Plus e1' (N (n1 + n2))) |\n    ((Plus (N n1) e2'), N n2) \\<Rightarrow> (Plus (N (n1 + n2)) e2') |\n    (a, b) \\<Rightarrow> (Plus a b))\"\n\nlemma \"aval (full_asimp a) s = aval a s\"\n  apply (induct a)\n  by(auto split: aexp.split)\n\ntext \\<open>Exercise 3.3\\<close>\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst x a (N n) = (N n)\" |\n\"subst x a (V v) = (if v=x then a else (V v))\" |\n\"subst x a (Plus e1 e2) = (Plus (subst x a e1) (subst x a e2))\"\n\nvalue \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\"\n\nlemma \"aval (subst x a e) s = aval e (s (x := aval a s))\"\n  apply(induct e)\n  by simp_all\n\ntext \\<open>Exercise 3.4\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V v) s = s v\" |\n\"aval (Plus e1 e2) s = aval e1 s + aval e2 s\" |\n\"aval (Times e1 e2) s = aval e1 s * aval e2 s\"\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N n1) (N n2) = N (n1 + n2)\" |\n\"plus (N n1) e = (if n1=0 then e else Plus (N n1) e)\" |\n\"plus e (N n2) = (if n2=0 then e else Plus e (N n2))\" |\n\"plus e1 e2 = Plus e1 e2\"\n\nlemma aval_plus[simp]: \n  \"aval (plus e1 e2) s = aval e1 s + aval e2 s\"\n  apply (induction e1 e2 rule: plus.induct)\n  by simp_all\n\nfun times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"times (N n1) (N n2) = N (n1 * n2)\" |\n\"times (N n1) e = (if n1=0 \n                   then (N 0) \n                   else if n1=1\n                        then e \n                        else (Times (N n1) e))\" |\n\"times e (N n2) = (if n2=0 \n                   then (N 0) \n                   else if n2=1\n                        then e\n                        else (Times e (N n2)))\" |\n\"times e1 e2 = (Times e1 e2)\"\n\nvalue \"times (plus (N 0) (N 0)) (V ''x'')\"\n\nlemma aval_times[simp]:\n  \"aval (times e1 e2) s = aval e1 s * aval e2 s\"\n  apply (induction e1 e2 rule: times.induct)\n  by simp_all\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V v) = V v\" |\n\"asimp (Plus e1 e2) = plus (asimp e1) (asimp e2)\" |\n\"asimp (Times e1 e2) = times (asimp e1) (asimp e2)\"\n\nvalue \"asimp (Plus (N 1) (Times (Plus (N 0) (V ''y'')) (V ''x'')))\"\n\nlemma \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n  by simp_all\n\ntext \\<open>Exercise 3.5\\<close>\ndatatype aexp2 = N int \n  | V vname \n  | Plus aexp2 aexp2 \n  | Times aexp2 aexp2 \n  | Div aexp2 aexp2\n  | Self_inc vname\n\n(*\ndefinition get_val :: \"(val \\<times> state) option \\<Rightarrow> val option\" where\n\"get_val x = (if Option.is_none x then None else Some (fst (the x)))\"\n(* How to prove the correctness of  get_val?*)\n*)\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> (val \\<times> state) option\" where\n\"aval2 (N n) s = Some (n, s)\" |\n\"aval2 (V v) s = Some (s v, s)\" |\n\"aval2 (Self_inc v) s = Some (s v, (s (v := (s v + 1))))\" |\n\"aval2 (Plus e1 e2) s = (case (aval2 e1 s, aval2 e2 s) of\n                          (None, None) \\<Rightarrow> None|\n                          (None, e2') \\<Rightarrow> None |\n                          (e1', None) \\<Rightarrow> None |\n                          (e1', e2') \\<Rightarrow> Some ((fst (the e1')) + (fst (the e2')), s))\" |\n\"aval2 (Times e1 e2) s = (case (aval2 e1 s, aval2 e2 s) of\n                          (None, None) \\<Rightarrow> None|\n                          (None, e2') \\<Rightarrow> None |\n                          (e1', None) \\<Rightarrow> None |\n                          (e1', e2') \\<Rightarrow> Some (fst (the e1') * fst (the e2'), s))\" |\n\"aval2 (Div e1 e2) s = (case (aval2 e1 s, aval2 e2 s) of\n                          (None, None) \\<Rightarrow> None|                          \n                          (None, e2') \\<Rightarrow> None |\n                          (e1', None) \\<Rightarrow> None |\n                          (e1', e2') \\<Rightarrow> (if fst (the e2') = 0 then None else Some (fst (the e1') div fst (the e2'), s)))\"\n\n\nvalue \"fst (the (Some (1::int, 2::int)))\"\nvalue \"((4::int) div 2)\"\n\nvalue \"aval2 (N 1) (\\<lambda>x. 0)\"\nvalue \"aval2 (V ''x'') (\\<lambda>x. 0)\"\nvalue \"aval2 (V ''x'') (snd (the (aval2 (Self_inc ''x'') (\\<lambda>x. 1))))\"\nvalue \"aval2 (Plus (N 1) (N 2)) (\\<lambda>x. 0)\"\nvalue \"aval2 (Plus (V ''x'') (N 1)) (\\<lambda>x. 0)\"\ndefinition \"now_x_state = snd (the (aval2 (Plus (Self_inc ''x'') (Plus (Self_inc ''x'') (N 0))) (\\<lambda>x. 0)))\"\n\ntext \\<open>There is a problem: how maintain the state after self_inc\\<close>\nvalue \"aval2 (Plus (Self_inc ''x'') (N 0)) (\\<lambda>x. 0)\"\n\ntext \\<open>Exercise 3.6\\<close>\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | Let vname lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"lval (Nl n) s = n\" |\n\"lval (Vl v) s = (s v)\" |\n\"lval (Plusl e1 e2) s = (lval e1 s) + (lval e2 s)\" |\n\"lval (Let v e1 e2) s = (lval e2 (s (v := lval e1 s)))\"\n\nvalue \"lval (Let ''x'' (Plusl (Nl 1) (Nl 2)) (Plusl (Vl ''x'') (Vl ''x''))) (\\<lambda>x. 0)\"\n\nfun inline :: \"lexp \\<Rightarrow> Exp.aexp\" where \n\"inline (Nl n) = (Exp.aexp.N n)\" |\n\"inline (Vl v) = (Exp.aexp.V v)\" |\n\"inline (Plusl e1 e2) = (Exp.aexp.Plus (inline e1) (inline e2))\" |\n\"inline (Let v e1 e2) = (subst v (inline e1) (inline e2))\"\n\nlemma \"Exp.aval (inline e) s = lval e s\"\napply(induction e arbitrary: s)\n     apply(auto split: lexp.split)\n  sorry\n\ntext \\<open>Exercise 3.7\\<close>\nfun eq :: \"Exp.aexp \\<Rightarrow> Exp.aexp \\<Rightarrow> bexp\" where\n\"eq a1 a2 = and (not (less a1 a2)) (not (less a2 a1))\"\n\nlemma correctness_eq[simp]:\n  \"bval (eq a1 a2) s = ((Exp.aval a1 s) = (Exp.aval a2 s))\"\n  by auto\n\nfun le :: \"Exp.aexp \\<Rightarrow> Exp.aexp \\<Rightarrow> bexp\" where\n\"le a1 a2 = not (less a2 a1)\"\n\nlemma correctness_le[simp]:\n  \"bval (le a1 a2) s = ((Exp.aval a1 s) \\<le> (Exp.aval a2 s))\"\n  by auto\n \ntext \\<open>Exercise 3.8\\<close>\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 Exp.aexp Exp.aexp\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 c) s = c\" |\n\"ifval (If i1 i2 i3) s = (if (ifval i1 s) then (ifval i2 s) else (ifval i3 s))\" |\n\"ifval (Less2 a1 a2) s = ((Exp.aval a1 s) < (Exp.aval a2 s))\"\n\nvalue \"ifval (Bc2 True) (\\<lambda>x. 0)\"\nvalue \"ifval (If (Bc2 True) (Bc2 False) (Bc2 True)) (\\<lambda>x. 0)\"\nvalue \"ifval (If (Bc2 False) (Bc2 False) (Bc2 True)) (\\<lambda>x. 0)\"\nvalue \"ifval (Less2 (Exp.N 1) (Exp.N 0)) (\\<lambda>x. 0)\"\nvalue \"Bc2 True = Bc2 False\"\n\nfun b_ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b_ifexp (Bc c) = Bc2 c\" |\n\"b_ifexp (Not b) = (If (b_ifexp b) (Bc2 False) (Bc2 True))\" |\n\"b_ifexp (And b1 b2) = (If (b_ifexp b1) (b_ifexp b2) (Bc2 False))\" |\n\"b_ifexp (Less a1 a2) = (Less2 a1 a2)\"\n\nlemma corectness_b_ifexp[simp]:\n  \"ifval (b_ifexp b) s = bval b s\"\n  apply (induct b)\n  by auto\n\nfun ifexp_bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"ifexp_bexp (Bc2 c) = (Bc c)\" |\n\"ifexp_bexp (If i1 i2 i3) = (or (And (ifexp_bexp i1) (ifexp_bexp i2)) (And (Not (ifexp_bexp i1)) (ifexp_bexp i3)))\" |\n\"ifexp_bexp (Less2 a1 a2) = (Less a1 a2)\"\n\nlemma correctness_ifexp_bexp[simp]:\n  \"bval (ifexp_bexp ie) s = ifval ie s\"\n  apply (induct ie)\n  by auto\n\n\ntext \\<open>Exercise 3.9\\<close>\ntype_synonym bval = bool\ndatatype pbexp = Pvar vname | Pnot pbexp | Pand pbexp pbexp | Por pbexp pbexp\ntype_synonym bstate = \"vname \\<Rightarrow> bval\"\n\nfun pbval :: \"pbexp \\<Rightarrow> bstate \\<Rightarrow> bval\" where\n\"pbval (Pvar v) s = s v\" |\n\"pbval (Pnot b) s = (\\<not> (pbval b s))\" |\n\"pbval (Pand b1 b2) s = ((pbval b1 s) \\<and> (pbval b2 s))\" |\n\"pbval (Por b1 b2) s = ((pbval b1 s) \\<or> (pbval b2 s))\"\n\nlemma \"pbval (Pnot (Pand b1 b2)) s = pbval (Por (Pnot b1) (Pnot b2)) s\"\n  by auto\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (Pvar v) = True\" |\n(*\n\"is_nnf (Pnot b) = (case b of \n                      Pvar _ \\<Rightarrow> True | \n                      _ \\<Rightarrow> False)\" |\n*)\n\"is_nnf (Pnot (Pvar _)) = True\" |\n\"is_nnf (Pnot _) = False\" |\n\"is_nnf (Pand b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" |\n\"is_nnf (Por b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\"\n\nvalue \"is_nnf (Pvar ''x'')\"\nvalue \"is_nnf (Pnot (Pvar ''x''))\"\nvalue \"is_nnf (Pnot (Pnot (Pvar ''x'')))\"\nvalue \"is_nnf (Pand (Pnot (Pvar ''x'')) (Pnot (Pvar ''y'')))\"\nvalue \"is_nnf (Pnot (Pand (Pnot (Pvar ''x'')) (Pnot (Pvar ''y''))))\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (Pvar v) = (Pvar v)\" |\n(* What's wrong?\n\"nnf (Pnot b) = (case b of\n                  Pvar v \\<Rightarrow> (Pnot (Pvar v)) |\n                  Pnot b' \\<Rightarrow> (nnf b') |\n                  Pand b1 b2 \\<Rightarrow> (Por (nnf (Pnot b1)) (nnf (Pnot b2))) |\n                  Por b1 b2 \\<Rightarrow> (Pand (nnf (Pnot b1)) (nnf (Pnot b2))))\" |\n*)\n\"nnf (Pnot (Pvar v)) = (Pnot (Pvar v))\" |\n\"nnf (Pnot (Pnot b)) = nnf b\" |\n\"nnf (Pnot (Pand b1 b2)) = (Por (nnf (Pnot b1)) (nnf (Pnot b2)))\" |\n\"nnf (Pnot (Por b1 b2)) = (Pand (nnf (Pnot b1)) (nnf (Pnot b2)))\" |\n\"nnf (Pand b1 b2) = (Pand (nnf b1) (nnf b2))\" |\n\"nnf (Por b1 b2) = (Por (nnf b1) (nnf b2))\"\n\nvalue \"nnf (Pvar ''x'')\"\nvalue \"nnf (Pnot (Pnot (Pnot (Pvar ''x''))))\"\nvalue \"nnf (Pnot (Pand (Pnot (Pnot (Pvar ''x''))) (Pnot (Pvar ''y''))))\"\nvalue \"is_nnf (nnf (Pvar ''x''))\"\nvalue \"is_nnf(nnf (Pnot (Pand (Pnot (Pvar ''x'')) (Pnot (Pvar ''y'')))))\"\nvalue \"is_nnf(nnf (Pand (Pnot (Pnot (Pvar ''x''))) (Pvar ''y'')))\"\n\nlemma pbval_nnf[simp]:\n  \"pbval (nnf b) s = pbval b s\"\n  apply(induction b rule: nnf.induct)\n  by auto\n \nlemma correctness_nnf[simp]:\n  \"is_nnf (nnf pb)\"\n  apply (induction pb rule: nnf.induct)\n  by auto\n\nfun is_dnf_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf_nnf (Pvar v) = True\" |\n\"is_dnf_nnf (Pnot b) = True\" |\n\"is_dnf_nnf (Por b1 b2) = True\" |\n\"is_dnf_nnf (Pand (Por b11 b12) b2) = False\" |\n\"is_dnf_nnf (Pand b1 (Por b21 b22)) = False\" |\n\"is_dnf_nnf (Pand b1 b2) = True\"\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf b =  (if is_nnf b \n              then is_dnf_nnf (nnf b) \n              else False)\"\n\ntext \\<open>assume it is a nnf\\<close>\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (Pvar v) = (Pvar v)\" |\n\"dnf_of_nnf (Pnot b) = (Pnot b)\" |\n\"dnf_of_nnf (Por b1 b2) = (Por (dnf_of_nnf b1) (dnf_of_nnf b2))\" |\n(*\n\"dnf_of_nnf (Pand b1 b2) = (case (dnf_of_nnf b1, dnf_of_nnf b2) of\n                            ((Por b11 b12), b2') \\<Rightarrow> (Por (Pand b11 b2) (Pand b12 b2)) |\n                            (b1', (Por b21 b22)) \\<Rightarrow> (Por (Pand b1' b21) (Pand b1' b22)))\"\n*)\n\"dnf_of_nnf (Pand (Por b11 b12) b2) = (Por (Pand (dnf_of_nnf b11) (dnf_of_nnf b2)) \n                                          (Pand (dnf_of_nnf b12) (dnf_of_nnf b2)))\" |\n\"dnf_of_nnf (Pand b1 (Por b21 b22)) = (Por (Pand (dnf_of_nnf b1) (dnf_of_nnf b21))\n                                          (Pand (dnf_of_nnf b1) (dnf_of_nnf b22)))\" |\n\"dnf_of_nnf (Pand b1 b2) = (Pand b1 b2)\"\n\n\nlemma pbval_dnf_of_nnf[simp]:\n  \"pbval (dnf_of_nnf b) s = pbval b s\"\n  apply (induction b rule: dnf_of_nnf.induct)\n  by auto\n\nlemma correctness_convert[simp]:\n  \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n  apply (induction b rule: dnf_of_nnf.induct)\n  apply (simp_all)\n  using is_nnf.elims(2) apply fastforce\n           apply meson\n  apply metis\n  apply presburger\n        apply metis\n  apply meson\n  using is_nnf.elims(2) apply fastforce\n  using is_nnf.elims(2) apply fastforce\n  apply (metis is_dnf_nnf.simps(12) is_nnf.elims(2) nnf.simps(2) pbexp.distinct(1) pbexp.distinct(7) pbexp.distinct(9))\n  using is_nnf.elims(2) apply fastforce\n  using is_nnf.elims(2) by force\n\n\n\ntext \\<open>Exercise 3.10\\<close>\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec1 (LOADI n) _ stk = (Some (n # stk))\" |\n\"exec1 (LOAD x) s stk = (Some (s(x) # stk))\" |\n\"exec1 ADD _ (j # i # stk) = (Some ((i + j) # stk))\" |\n\"exec1 ADD _ _ = None \"\n(*\n\"exec1 ADD _ stk = (if length stk < 2 then None else (case stk of (j # i # xs) \\<Rightarrow> (Some ((i+j) # xs))))\"\n*)\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec [] _ stk = Some stk\" |\n\"exec (i # is) s stk = (case (exec1 i s stk) of\n                          None \\<Rightarrow> None |\n                          Some stk' \\<Rightarrow> exec is s stk')\"\n\nfun comp :: \"Exp.aexp \\<Rightarrow> instr list\" where\n\"comp (Exp.N n) = [LOADI n]\" |\n\"comp (Exp.V x) = [LOAD x]\" |\n\"comp (Exp.Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\nlemma exec_append[simp]:\n  \"(exec is1 s stk = Some stk1) \\<Longrightarrow> (exec (is1 @ is2) s stk) = (exec is2 s stk1)\"\n  apply(induction is1 arbitrary: stk)\n   apply(simp_all)\n  by (metis option.case_eq_if option.simps(3))\n\nlemma correctness_asm[simp]:\n  \"exec (comp a) s stk = Some ((Exp.aval a s) # stk)\"\n  apply(induction a arbitrary: stk)\n  by auto\n  \ntext \\<open>Exercise 3.11\\<close>\ntype_synonym reg = nat\ndatatype instr_reg = LDI int reg | LD vname reg | ADD reg reg\ntype_synonym reg_state = \"reg \\<Rightarrow> int\"\n\nfun exec_reg1 :: \"instr_reg \\<Rightarrow> state \\<Rightarrow> reg_state \\<Rightarrow> reg_state\" where\n\"exec_reg1 (LDI n r) _ reg_s = reg_s (r := n)\" |\n\"exec_reg1 (LD x r) s reg_s = reg_s (r := (s x))\" |\n\"exec_reg1 (ADD r1 r2) _ reg_s = reg_s (r1 := (reg_s r1 + reg_s r2))\"\n\nfun exec_reg :: \"instr_reg list \\<Rightarrow> state \\<Rightarrow> reg_state \\<Rightarrow> reg_state\" where\n\"exec_reg [] _ reg_s = reg_s\" |\n\"exec_reg (i # is) s reg_s = exec_reg is s (exec_reg1 i s reg_s)\"\n\nvalue \"(exec_reg [(LDI 1 1), (LDI 2 2), (LDI 3 3), (ADD 2 3), (ADD 1 2)] (\\<lambda>x. 0) (\\<lambda>r. 0)) 1\"\n\nfun comp_reg :: \"Exp.aexp \\<Rightarrow> reg \\<Rightarrow> instr_reg list\" where\n\"comp_reg (Exp.N n) r = [LDI n r]\" |\n\"comp_reg (Exp.V v) r = [LD v r]\" |\n\"comp_reg (Exp.Plus e1 e2) r = (comp_reg e1 r) @ (comp_reg e2 (Suc r)) @ [ADD r (Suc r)]\"\n\nlemma l0[simp]:\n  \"exec_reg (i1 @ i2) s rs = exec_reg i2 s (exec_reg i1 s rs)\"\n  apply (induction i1 arbitrary: s rs)\n  by simp_all\n\nlemma left_alone[simp]:\n  \"r1 < r2 \\<Longrightarrow> (exec_reg (comp_reg a r2) s rs) r1 = rs r1 \"\n  apply (induction a arbitrary: rs r2)\n  by simp_all\n\nlemma correctness_comp[simp]:\n  \"exec_reg (comp_reg a r) s rs r = Exp.aval a s\"\n  apply (induction a arbitrary: r rs)\n  by simp_all  \n\n\ntext \\<open>Exercise 3.12\\<close>\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> reg_state \\<Rightarrow> reg_state\" where\n\"exec01 (LDI0 n) s rs = rs (0 := n)\" |\n\"exec01 (LD0 v) s rs = rs (0 := (s v))\" |\n\"exec01 (MV0 r) s rs = rs (r := (rs 0))\" |\n\"exec01 (ADD0 r) s rs = rs (0 := (rs r + rs 0))\"\n\nvalue \"(exec01 (ADD0 1) <> <0 := 3, 1 := 2>) 0\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> reg_state \\<Rightarrow> reg_state\" where\n\"exec0 [] _ rs = rs\" |\n\"exec0 (i # is) s rs = exec0 is s (exec01 i s rs)\"\n\nlemma exec0_append[simp]:\n  \"exec0 (i1 @ i2) s rs = exec0 i2 s (exec0 i1 s rs)\"\n  apply (induction i1 arbitrary: s rs)\n  by auto\n\nfun comp0 :: \"Exp.aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0 (Exp.N n) _ = [LDI0 n]\" |\n\"comp0 (Exp.V v) _ = [LD0 v]\" |\n\"comp0 (Exp.Plus a1 a2) r = (comp0 a2 (Suc r)) @ [MV0 (Suc r)] @ (comp0 a1 (Suc (Suc r))) @ [ADD0 (Suc r)]\"\n \nlemma left_alone2[simp]:\n  \"0 < r1 \\<Longrightarrow> r1 < r2 \\<Longrightarrow> exec0 (comp0 a r2) s rs r1 = rs r1\"\n  apply (induct a arbitrary: rs r2)\n  by simp_all\n\nlemma correctness_comp0[simp]:\n  \"exec0 (comp0 a r) s rs 0 = Exp.aval a s\"\n  apply (induction a arbitrary: r s rs)\n  by simp_all\n\nvalue \"if (1::int)=2 then (3::int) else 4\"\nvalue \"let x=1::int in (x + 1)\"\ndatatype N = One | Suc N\nfun case_test :: \"N \\<Rightarrow> bool\" where\n\"case_test t = (case t of \n                  One \\<Rightarrow> True | \n                  _ \\<Rightarrow> False)\"\nvalue \"case_test One\"\nvalue \"case_test (Suc One)\"\nvalue \"[(1::int)..6]\"\n\nend", "meta": {"author": "3-F", "repo": "concrete-semanitcs", "sha": "0a35764f047d93b3069342ddea34a17dd0cbe414", "save_path": "github-repos/isabelle/3-F-concrete-semanitcs", "path": "github-repos/isabelle/3-F-concrete-semanitcs/concrete-semanitcs-0a35764f047d93b3069342ddea34a17dd0cbe414/Exercises/exercises_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.780489204866636}}
{"text": "theory ex2_10 imports Main begin\n\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 1\" |\n\"nodes (Node l r) = 1 + nodes l + nodes r\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\ntheorem \"nodes (explode n t) = 2^n-1 + 2^n * nodes t\"\napply(induction n arbitrary: t)\napply(auto simp add: algebra_simps)\ndone\n\nend", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter2/ex2_10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9390248157222396, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7804639512815281}}
{"text": "section \\<open>Parity of a list permutation\\<close>\n\ntheory Parity_Swap\nimports \"../lib/Lib\"\nbegin\n\ntext \\<open>Define the parity of a list @{term xs} as the evenness of the number of inversions.\n      Count an inversion for every pair of indices @{term i} and @{term j}, such that\n      @{text \"i < j\"}, but @{text \"xs!i > xs!j\"}.\\<close>\n\nprimrec\n  parity :: \"nat list \\<Rightarrow> bool\"\nwhere\n  \"parity [] = True\"\n| \"parity (x # ys) = (parity ys = even (length [y \\<leftarrow> ys. x > y]))\"\n\ntext \\<open>In a list that is sufficiently distinct, swapping any two elements inverts\n      the @{term parity}.\\<close>\n\nlemma parity_swap_adj:\n  \"b \\<noteq> c \\<Longrightarrow> parity (as @ b # c # ds) \\<longleftrightarrow> \\<not> parity (as @ c # b # ds)\"\n  by (induct as) auto\n\nlemma parity_swap:\n  assumes \"b \\<noteq> d \\<and> b \\<notin> set cs \\<and> d \\<notin> set cs\"\n  shows \"parity (as @ b # cs @ d # es) \\<longleftrightarrow> \\<not> parity (as @ d # cs @ b # es)\"\n  using assms\n  proof (induct cs arbitrary: as)\n    case Nil thus ?case using parity_swap_adj[of b d as es] by simp\n  next\n    case (Cons c cs) show ?case\n      using parity_swap_adj[of b c as \"cs @ d # es\"]\n            parity_swap_adj[of d c as \"cs @ b # es\"]\n            Cons(1)[where as=\"as @ [c]\"] Cons(2)\n      by simp\n  qed\n\nend\n", "meta": {"author": "mbrcknl", "repo": "puzzle-parity-permutations", "sha": "366632499cdbcac8fe3f014c122e2ceb7ae74b5e", "save_path": "github-repos/isabelle/mbrcknl-puzzle-parity-permutations", "path": "github-repos/isabelle/mbrcknl-puzzle-parity-permutations/puzzle-parity-permutations-366632499cdbcac8fe3f014c122e2ceb7ae74b5e/extras/Parity_Swap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7803634927626493}}
{"text": "theory Height\n  imports \"../Nominal\"\nbegin\n\ntext {*  \n  A small problem suggested by D. Wang. It shows how\n  the height of a lambda-terms behaves under substitution.\n*}\n\natom_decl name\n\nnominal_datatype lam = \n    Var \"name\"\n  | App \"lam\" \"lam\"\n  | Lam \"\\<guillemotleft>name\\<guillemotright>lam\" (\"Lam [_]._\" [100,100] 100)\n\ntext {* Definition of the height-function on lambda-terms. *} \n\nnominal_primrec\n  height :: \"lam \\<Rightarrow> int\"\nwhere\n  \"height (Var x) = 1\"\n| \"height (App t1 t2) = (max (height t1) (height t2)) + 1\"\n| \"height (Lam [a].t) = (height t) + 1\"\n  apply(finite_guess add: perm_int_def)+\n  apply(rule TrueI)+\n  apply(simp add: fresh_int)\n  apply(fresh_guess add: perm_int_def)+\n  done\n\ntext {* Definition of capture-avoiding substitution. *}\n\nnominal_primrec\n  subst :: \"lam \\<Rightarrow> name \\<Rightarrow> lam \\<Rightarrow> lam\"  (\"_[_::=_]\" [100,100,100] 100)\nwhere\n  \"(Var x)[y::=t'] = (if x=y then t' else (Var x))\"\n| \"(App t1 t2)[y::=t'] = App (t1[y::=t']) (t2[y::=t'])\"\n| \"\\<lbrakk>x\\<sharp>y; x\\<sharp>t'\\<rbrakk> \\<Longrightarrow> (Lam [x].t)[y::=t'] = Lam [x].(t[y::=t'])\"\napply(finite_guess)+\napply(rule TrueI)+\napply(simp add: abs_fresh)\napply(fresh_guess)+\ndone\n\ntext{* The next lemma is needed in the Var-case of the theorem below. *}\n\nlemma height_ge_one: \n  shows \"1 \\<le> (height e)\"\nby (nominal_induct e rule: lam.strong_induct) (simp_all)\n\ntext {* \n  Unlike the proplem suggested by Wang, however, the \n  theorem is here formulated entirely by using functions. \n*}\n\ntheorem height_subst:\n  shows \"height (e[x::=e']) \\<le> ((height e) - 1) + (height e')\"\nproof (nominal_induct e avoiding: x e' rule: lam.strong_induct)\n  case (Var y)\n  have \"1 \\<le> height e'\" by (rule height_ge_one)\n  then show \"height (Var y[x::=e']) \\<le> height (Var y) - 1 + height e'\" by simp\nnext\n  case (Lam y e1)\n  hence ih: \"height (e1[x::=e']) \\<le> ((height e1) - 1) + (height e')\" by simp\n  moreover\n  have vc: \"y\\<sharp>x\" \"y\\<sharp>e'\" by fact+ (* usual variable convention *)\n  ultimately show \"height ((Lam [y].e1)[x::=e']) \\<le> height (Lam [y].e1) - 1 + height e'\" by simp\nnext    \n  case (App e1 e2)\n  hence ih1: \"height (e1[x::=e']) \\<le> ((height e1) - 1) + (height e')\" \n    and ih2: \"height (e2[x::=e']) \\<le> ((height e2) - 1) + (height e')\" by simp_all\n  then show \"height ((App e1 e2)[x::=e']) \\<le> height (App e1 e2) - 1 + height e'\"  by simp \nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Nominal/Examples/Height.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7803634814973315}}
{"text": "chapter {* R5: Eliminación de duplicados *}\n\ntheory R5_Eliminacion_de_duplicados\nimports Main \nbegin\n        \ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 1. Definir la funcion primitiva recursiva \n     estaEn :: 'a \\<Rightarrow> 'a list \\<Rightarrow> bool\n  tal que (estaEn x xs) se verifica si el elemento x está en la lista\n  xs. Por ejemplo, \n     estaEn (2::nat) [3,2,4] = True\n     estaEn (1::nat) [3,2,4] = False\n  --------------------------------------------------------------------- \n*}\n\nfun estaEn :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"estaEn _ [] = False\"\n| \"estaEn x (y#xs) = ((x = y) \\<or> (estaEn x xs))\"\n\nvalue \"estaEn (2::nat) [3,2,4] = True\"\nvalue \"estaEn (1::nat) [3,2,4] = False\"\n\ntext {* \n  --------------------------------------------------------------------- \n  Ejercicio 2. Definir la función primitiva recursiva \n     sinDuplicados :: 'a list \\<Rightarrow> bool\n  tal que (sinDuplicados xs) se verifica si la lista xs no contiene\n  duplicados. Por ejemplo,  \n     sinDuplicados [1::nat,4,2]   = True\n     sinDuplicados [1::nat,4,2,4] = False\n  --------------------------------------------------------------------- \n*}\n\nfun sinDuplicados :: \"'a list \\<Rightarrow> bool\" where\n  \"sinDuplicados [] = True\"\n| \"sinDuplicados (x#xs) = (\\<not>estaEn x xs \\<and> sinDuplicados xs)\"\n\nvalue \"sinDuplicados [1::nat,4,2]   = True\"\nvalue \"sinDuplicados [1::nat,4,2,4] = False\"\n\ntext {* \n  --------------------------------------------------------------------- \n  Ejercicio 3. Definir la función primitiva recursiva \n     borraDuplicados :: 'a list \\<Rightarrow> bool\n  tal que (borraDuplicados xs) es la lista obtenida eliminando los\n  elementos duplicados de la lista xs. Por ejemplo, \n     borraDuplicados [1::nat,2,4,2,3] = [1,4,2,3]\n\n  Nota: La función borraDuplicados es equivalente a la predefinida\n  remdups.  \n  --------------------------------------------------------------------- \n*}\n\nfun borraDuplicados :: \"'a list \\<Rightarrow> 'a list\" where\n  \"borraDuplicados[] = []\"\n| \"borraDuplicados (x#xs) = (if estaEn x xs then borraDuplicados xs  else x # borraDuplicados xs)\"\n\nvalue \"borraDuplicados [1::nat,2,4,2,3] = [1,4,2,3]\"\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 4.1. Demostrar o refutar automáticamente\n     length (borraDuplicados xs) \\<le> length xs\n  --------------------------------------------------------------------- \n*}\n\n-- \"La demostración automática es\"\nlemma length_borraDuplicados:\n  \"length (borraDuplicados xs) \\<le> length xs\"\nby (induct xs) auto\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 4.2. Demostrar o refutar detalladamente\n     length (borraDuplicados xs) \\<le> length xs\n  --------------------------------------------------------------------- \n*}\n\n-- \"La demostración estructurada es\"\n\nlemma length_borraDuplicados_2: \"length (borraDuplicados xs) \\<le> length xs\" (is \"?P xs\")\nproof (induct xs)\n  show \"?P []\" by simp\nnext \n  fix a xs\n  assume HI: \"?P xs\"\n  have \"length (borraDuplicados (a # xs)) \\<le> 1+length (borraDuplicados xs)\" by simp\n  also have \"... \\<le> 1+length xs\" using HI by simp\n  finally show \"?P (a # xs)\" by simp\nqed\n\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 5.1. Demostrar o refutar automáticamente\n     estaEn a (borraDuplicados xs) = estaEn a xs\n  --------------------------------------------------------------------- \n*}\n\n-- \"La demostración automática es\"\nlemma estaEn_borraDuplicados: \n  \"estaEn a (borraDuplicados xs) = estaEn a xs\"\nby (induct xs) auto\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 5.2. Demostrar o refutar detalladamente\n     estaEn a (borraDuplicados xs) = estaEn a xs\n  Nota: Para la demostración de la equivalencia se puede usar\n     proof (rule iffI)\n  La regla iffI es\n     \\<lbrakk>P \\<Longrightarrow> Q ; Q \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P = Q\n  --------------------------------------------------------------------- \n*}\n\n-- \"La demostración estructurada es\"\nlemma estaEn_borraDuplicados_2: \"estaEn a (borraDuplicados xs) = estaEn a xs\" (is \"?P a xs\")\nproof (induct xs)\n  show \"?P a []\" by simp\nnext \n  fix b xs\n  assume HI: \"?P a xs\"\n  show \"?P a (b#xs)\"\n  proof (rule iffI)\n    assume HII: \"?P a (b#xs)\"\noops\n    \n    \n  \n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 6.1. Demostrar o refutar automáticamente\n     sinDuplicados (borraDuplicados xs)\n  --------------------------------------------------------------------- \n*}\n\n-- \"La demostración automática\"\nlemma sinDuplicados_borraDuplicados:\n  \"sinDuplicados (borraDuplicados xs)\"\nby (induct xs) (auto simp add: estaEn_borraDuplicados)\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 6.2. Demostrar o refutar detalladamente\n     sinDuplicados (borraDuplicados xs)\n  --------------------------------------------------------------------- \n*}\n\n-- \"La demostración estructurada es\"\nlemma sinDuplicados_borraDuplicados_2:\n  \"sinDuplicados (borraDuplicados xs)\"\nproof (induct xs)\n  show \"sinDuplicados (borraDuplicados [])\" by simp\nnext\n  fix x xs\n  assume HI: \"sinDuplicados (borraDuplicados xs)\"\n  show \"sinDuplicados (borraDuplicados (x # xs))\" \n  proof (cases)\n    assume \"estaEn x xs\" \n    then show \"sinDuplicados (borraDuplicados (x # xs))\" using HI by simp\n  next\n    assume \"\\<not>(estaEn x xs)\"\n    then show \"sinDuplicados (borraDuplicados (x # xs))\" using HI by (simp add: estaEn_borraDuplicados)\n  qed\nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 7. Demostrar o refutar:\n    borraDuplicados (rev xs) = rev (borraDuplicados xs)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"borraDuplicados (rev xs) = rev (borraDuplicados xs)\"\nquickcheck\noops\n\nend", "meta": {"author": "serrodcal-MULCIA", "repo": "RAIsabelleHOL", "sha": "2f551971b248b3dac6009d09b74f5b3e16e0d12f", "save_path": "github-repos/isabelle/serrodcal-MULCIA-RAIsabelleHOL", "path": "github-repos/isabelle/serrodcal-MULCIA-RAIsabelleHOL/RAIsabelleHOL-2f551971b248b3dac6009d09b74f5b3e16e0d12f/R5_Eliminacion_de_duplicados.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.9136765251766503, "lm_q1q2_score": 0.7802000505080902}}
{"text": "(*  \n  Title:    Random_Dictatorship.thy\n  Author:   Manuel Eberl, TU München\n\n  Definition and basic properties of Random Dictatorship\n  (on weak preferences)\n*)\n\nsection \\<open>Random Dictatorship\\<close>\n\ntheory Random_Dictatorship\nimports\n  Complex_Main\n  Social_Decision_Schemes\nbegin\n\ntext \\<open>\n  We define Random Dictatorship as a social decision scheme on total preorders \n  (i.e. agents are allowed to have ties in their rankings) by first selecting an agent\n  uniformly at random and then selecting one of that agents' most preferred alternatives\n  uniformly at random. Note that this definition also works for weak preferences.\n\\<close>\ndefinition random_dictatorship :: \"'agent set \\<Rightarrow> ('agent, 'alt) pref_profile \\<Rightarrow> 'alt lottery\" where\n  \"random_dictatorship agents R =\n      do {\n        i \\<leftarrow> pmf_of_set agents; \n        pmf_of_set (favorites R i)\n      }\"\n\ncontext election\nbegin\n\nabbreviation RD :: \"('agent, 'alt) pref_profile \\<Rightarrow> 'alt lottery\" where\n  \"RD \\<equiv> random_dictatorship agents\"\n\nlemma random_dictatorship_unique_favorites:\n  assumes \"is_pref_profile R\" \"has_unique_favorites R\"\n  shows   \"RD R = map_pmf (favorite R) (pmf_of_set agents)\"\nproof -\n  from assms(1) interpret pref_profile_wf agents alts R .\n  from assms(2) interpret pref_profile_unique_favorites agents alts R by unfold_locales\n  show ?thesis unfolding random_dictatorship_def map_pmf_def \n    by (intro bind_pmf_cong) (auto simp: unique_favorites pmf_of_set_singleton)\nqed\n\nlemma random_dictatorship_unique_favorites':\n  assumes \"is_pref_profile R\" \"has_unique_favorites R\"\n  shows   \"RD R = pmf_of_multiset (image_mset (favorite R) (mset_set agents))\"\n  using assms by (simp add: random_dictatorship_unique_favorites map_pmf_of_set)\n\nlemma pmf_random_dictatorship:\n  assumes \"is_pref_profile R\"\n  shows \"pmf (RD R) x =\n           (\\<Sum>i\\<in>agents. indicator (favorites R i) x /\n              real (card (favorites R i))) / real (card agents)\"\nproof -\n  from assms(1) interpret pref_profile_wf agents alts R .\n  have \"ereal (pmf (RD R) x) = \n          ereal ((\\<Sum>i\\<in>agents. pmf (pmf_of_set (favorites R i)) x) / real (card agents))\"\n    (is \"_ = ereal (?p / _)\") unfolding random_dictatorship_def\n    by (simp_all add: ereal_pmf_bind nn_integral_pmf_of_set max_def pmf_nonneg)\n  also have \"?p = (\\<Sum>i\\<in>agents. indicator (favorites R i) x / real (card (favorites R i)))\"\n    by (intro setsum.cong) (simp_all add: favorites_nonempty)\n  finally show ?thesis by simp\nqed\n\n\nsublocale RD: social_decision_scheme agents alts RD\nproof\n  fix R assume R_wf: \"is_pref_profile R\"\n  then interpret pref_profile_wf agents alts R .\n  from R_wf show \"RD R \\<in> lotteries\"\n    using favorites_subset_alts favorites_nonempty\n    by (auto simp: lotteries_on_def random_dictatorship_def)\nqed\n\ntext \\<open>\n  We now show that Random Dictatorship fulfils anonymity, neutrality, \n  and strong strategyproofness.\n  At the very least, this shows that the definitions of these notions are \n  consistent.\n\\<close>\n\nsubsection \\<open>Anonymity\\<close>\n\ntext \\<open>\n  The following proof is essentially the following:\n  In Random Dictatorship, permuting the agents in the preference profile is the same\n  as applying the permutation to the agent that was picked uniformly at random in the \n  first step. However, uniform distributions are invariant under permutation, therefore\n  the outcome is totally unchanged.\n\\<close>\n\nsublocale RD: anonymous_sds agents alts RD\nproof\n  fix R \\<pi> assume wf: \"is_pref_profile R\" and perm: \"\\<pi> permutes agents\"\n  have \"RD (R \\<circ> \\<pi>) = map_pmf \\<pi> (pmf_of_set agents) \\<bind> (\\<lambda>i. pmf_of_set (favorites R i))\"\n    by (simp add: bind_map_pmf random_dictatorship_def o_def favorites_def)\n  also from perm have \"\\<dots> = RD R\"\n    by (simp add: map_pmf_of_set_inj permutes_inj_on permutes_image random_dictatorship_def)\n  finally show \"RD (R \\<circ> \\<pi>) = RD R\" .\nqed\n\n\nsubsection \\<open>Neutrality\\<close>\n\ntext \\<open>\n  The proof of neutrality is similar to that of anonymity. We have proven elsewhere\n  that the most preferred alternatives of an agent in a profile with permuted alternatives\n  are simply the image of the originally preferred alternatives.\n  Since we pick one alternative from the most preferred alternatives of the selected agent\n  uniformly at random, this means that we effectively pick an agent, then pick on of her \n  most preferred alternatives, and then apply the permutation to that alternative, \n  which is simply Random Dictatorship transformed with the permutation.\n\\<close>\n\nsublocale RD: neutral_sds agents alts RD\nproof\n  fix \\<sigma> R\n  assume perm: \"\\<sigma> permutes alts\" and R_wf: \"is_pref_profile R\"\n  from R_wf interpret pref_profile_wf agents alts R .\n  from perm show \"RD (permute_profile \\<sigma> R) = map_pmf \\<sigma> (RD R)\"\n    by (auto intro!: bind_pmf_cong simp: random_dictatorship_def map_bind_pmf \n          favorites_permute map_pmf_of_set_inj permutes_inj_on favorites_nonempty)\nqed\n\n\nsubsection \\<open>Strong strategyproofness\\<close>\n\ntext \\<open>\n  The argument for strategyproofness is quite simple:\n  Since the preferences submitted by an agent @{term i} only influence \n  the outcome when that agent is picked in the first process, it suffices \n  to focus on this case.\n  When the agent @{term i} submits her true preferences, the probability of \n  obtaining a result at least as good as @{term x} (for any alternative @{term x})\n  is 1, since the outcome will always be one of her most-preferred alternatives.\n  Obviously, the probability of obtaining such a result cannot exceed 1 no matter\n  what preferences she submits instead, and thus, RD is strategyproof.\n\\<close>\n\nsublocale RD: strongly_strategyproof_sds agents alts RD\nproof (unfold_locales, unfold RD.strongly_strategyproof_profile_def)\n  fix R i Ri' assume R_wf: \"is_pref_profile R\" and i: \"i \\<in> agents\"\n                 and Ri'_wf: \"total_preorder_on alts Ri'\"\n  interpret R: pref_profile_wf agents alts R by fact\n  from R_wf Ri'_wf i have R'_wf: \"is_pref_profile (R(i := Ri'))\"\n    by (simp add: R.wf_update)\n  interpret R': pref_profile_wf agents alts \"R(i := Ri')\" by fact\n\n  show \"SD (R i) (RD (R(i := Ri'))) (RD R)\"\n  proof (rule R.SD_pref_profileI)\n    fix x assume \"x \\<in> alts\"\n    hence \"emeasure (measure_pmf (RD (R(i := Ri')))) (preferred_alts (R i) x)\n             \\<le> emeasure (measure_pmf (RD R)) (preferred_alts (R i) x)\"\n      using Ri'_wf maximal_imp_preferred[of \"R i\" x]\n      by (auto intro!: card_mono nn_integral_mono_AE \n               simp: random_dictatorship_def AE_measure_pmf_iff Max_wrt_prefs_finite\n                     emeasure_pmf_of_set favorites_def Int_absorb2\n                     Max_wrt_prefs_nonempty card_gt_0_iff)\n    thus \"lottery_prob (RD (R(i := Ri'))) (preferred_alts (R i) x)\n            \\<le> lottery_prob (RD R) (preferred_alts (R i) x)\"\n      by (simp add: measure_pmf.emeasure_eq_measure) \n  qed (insert R_wf R'_wf, simp_all add: RD.sds_wf i)\nqed\n\nend\n\nend", "meta": {"author": "pruvisto", "repo": "SDS", "sha": "e0b280bff615c917314285b374d77416c51ed39c", "save_path": "github-repos/isabelle/pruvisto-SDS", "path": "github-repos/isabelle/pruvisto-SDS/SDS-e0b280bff615c917314285b374d77416c51ed39c/thys/Randomised_Social_Choice/Random_Dictatorship.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7802000485394366}}
{"text": "(* Header of theory always looks like this: *)\ntheory FunProg_Demo (* Theory name, must coincide with filename *)\nimports Main \"~~/src/HOL/Library/Multiset\" (* List of imported theories. Typically only Main. *)\nbegin\n\n  section \\<open>Datatype Examples\\<close> (* Section commands have no semantic meaning, only for source structuring. *)\n    (* Hint: Use sidekick-panel! *)\n    \n  (* First Example: Nat  *)\n  (* Data represented as algebraic datatypes: *)\n  datatype my_nat = Z | S my_nat \n  (* Intuitive reading: A natural number is either *Z*ero, or the *S*uccessor of a natural number *)\n    \n  (* Note: Unary representation. \n    Not efficient for computation. But very efficient for proving!\n  *)\n\n  (* Use the term command to display a term and its type in the Output panel *)\n  term \"Z\" (* In theory text, terms and types always enclosed in \"quotes\". *)\n  term \"''This is a string''\" (* Do not confuse with strings *)\n  term \"CHR ''a''\" (* Syntax for single character *) \n    \n  term \"S Z\" (* Function application is written: f x\\<^sub>1 ... x\\<^sub>n *)\n  term \"S (S (S Z))\" (* Note the parentheses! *)\n\n  term \"Z\"  \n    \n  term \\<open>S (S Z)\\<close> (* You may also use cartouches \\<open>...\\<close>  instead of quotes. \n      Type backtick ` and wait for completion menu. \n      Hint: Set Plugins>Plugin Options>Isabelle>General>Completion Delay to 0 for smoother typing.\n    *)\n  (* Hint: Use the Symbols-panel to explore available \n    symbols, and methods how to enter them! *)\n    \n  datatype 'a my_list = NIL | CONS 'a \"'a my_list\"\n  (* \\<open>\\<open>'a\\<close> is type parameter. May be filled with any type, e.g.: *)\n  typ \"my_nat my_list\" typ \"bool my_list\"\n    \n  datatype bintree = Leaf | Node bintree bintree\n    \n  datatype 'a bt = Leaf' | Node' 'a \"'a bt\" \"'a bt\" \n    \n  section \\<open>Functions\\<close>\n    \n  (* Functions: Recursive functions. For example: *)\n  fun add where\n    \"add Z m = m\"\n  | \"add (S n) m = S (add n m)\"\n\n  (* Note: This definition is much simpler than it would be for binary numbers! *)\n  (* Also simpler than what you would write in C++ or Java! *)\n    \n  value \"add (S Z) (S (S Z))\" (* Evaluate a term *)\n  value \"add (S n) (S (S (Z)))\" (* Partial evaluation also possible! *)\n  \n  fun appnd  \n    where  \n    \"appnd NIL l = l\"\n  | \"appnd (CONS x l) ll = CONS x (appnd l ll)\"  \n\n    \n  value \"appnd (CONS a (CONS b NIL)) (CONS c (CONS d NIL))\"  \n    \n  (*\n      appnd (CONS a (CONS b NIL)) (CONS c (CONS d NIL)) \n    = CONS a (appnd (CONS b NIL) (CONS c (CONS d NIL)))\n    = CONS a (CONS b (appnd NIL (CONS c (CONS d NIL))))\n    = CONS a (CONS b (CONS c (CONS d NIL)))\n\n\n\n\n    More examples how evaluation works: [DO ON DOC-CAM IF POSSIBLE]\n\n      add (S (S Z)) (S Z)    -- Match with equation add (S n) m = S (add n m)\n    = S (add (S Z) (S Z))    -- Match with equation add (S n) m = S (add n m)\n    = S (S (add Z (S Z)))    -- Match with equation add Z m = m\n    = S (S (S Z))            -- No more equations to match with\n\n\n  *)  \n    \n    \n    \n    \n  section \\<open>Types\\<close>\n  (* Every term in Isabelle must be typeable, e.g., it has a type. *)\n  term \"Z\" \n  term \"S Z\"  \n    \n    \n  term \"S\" (* Function type indicated by \\<Rightarrow>  *)\n  term \"add\" (* Function with many arguments. Note: \\<Rightarrow> is right associative, i.e. \"a\\<Rightarrow>b\\<Rightarrow>c\" is same as \"a\\<Rightarrow>(b\\<Rightarrow>c)\" *)\n  term \"add (S Z) (S Z)\"\n  term \"add (S Z)\" (* Partial application *)\n    \n  (*\n    Hint: press Ctrl (Mac: Cmd) and move the mouse over (almost) any item in the editor window.\n      A tooltip will show further information. Left-click will move to the definition of the item.\n  *)  \n    \n    \n  (* We may specify type with function definition. If no type specified,\n    Isabelle infers most generic one (type inference). *)\n  fun numnodes :: \"bintree \\<Rightarrow> my_nat\" where\n    \"numnodes Leaf = Z\"\n  | \"numnodes (Node t1 t2) = S (add (numnodes t1) (numnodes t2))\"  \n    \n  value \"numnodes (Node (Node Leaf Leaf) (Node Leaf (Node Leaf Leaf)))\"\n    \n    \n  (* Type annotations may be added everywhere in term. \n    To influence (restrict) inferred type *)\n  term \"CONS x xs\"\n  term \"(CONS :: my_nat \\<Rightarrow> my_nat my_list \\<Rightarrow> my_nat my_list) (x::my_nat) xs\"\n  term \"(CONS x xs)::my_nat my_list\"  \n    \n    \n  (* Note: Variables and constants are displayed in different color! Useful to find typos! *)  \n    \n  term \"CONS x xs\"  \n  term \"C0NS x xs\"\n    \n  (* Also, bound variables get different color. Bound variable: \n    Occurs in pattern on left hand side of function equation\n  *)  \n  fun double :: \"my_nat \\<Rightarrow> my_nat\" where\n    \"double Z = Z\"\n  | \"double (S n) = S (S (double n))\"\n    \n  (* Don't get confused: The function that is actually being defined is rendered\n    as a free variable!\n  *)  \n  term double  (* It only becomes a constant after definition *)\n    \n  section \\<open>Standard Library\\<close>  \n\n  (* Of course, Isabelle has data types for natural numbers and lists in\n        its standard library. Included by default! With many functions! *)\n    \n  typ nat\n  term \"42::nat\"  \n  term \"0::nat\" \n  term Suc \n\n  typ \"int\"\n  term \"42::int\"\n  term \"-42::int\"\n    \n  term Suc  \n  (* Note: For numerals, you always have to specify the type *)  \n  term \"Suc 41\" (* Unless clear from type inference! *)\n  term \"(10::int) - 7\"  \n    \n  term \"2+3\"  \n    \n  typ bool  \n  term True term False\n\n  typ \"'a\\<times>'b\"  \n  term \"(True, False)\"  \n  term \"(10::nat, True, 5::int, 6::int)\"  \n  term \"(10::nat, (True, (5::int, 6::int)))\"  \n    \n  term fst term snd \n  value \"fst (snd (10::nat, True, 5::int, 6::int))\"    \n      \n    \n  typ \"'a list\"  \n  term Nil term Cons  \n  term \"[]\" (* Nil *)\n  term \"x#l\" (* Cons *)\n  term \"[a,b,c]\" (* Syntax sugar for a#b#c#Nil *)\n  term \"l1@l2\" (* append *)\n    \n  term \"l1@l2#x1#x2@l3\"  \n    \n  (* Arithmetic operations overloaded for int and nat *)\n  value \"(3::int) + 7\"  \n  value \"(3::nat) + 7\"  \n    \n  value \"(1::int)*3 - 4*5 + 2*6^2\" (* Priority and associativity of standard operators is as expected *)\n\n  lemma \"x\\<ge>y \\<Longrightarrow> (x::nat) - y + y = x\"  oops\n    \n  (* BEWARE: Subtraction on nat saturates at 0 *)\n  value \"(5::nat) - 10\"  \n\n  (* BEWARE: Division on int rounds down. In many PLs (such as C), it rounds towards zero! *)\n  value \"(-3::int) div 2\"  \n    \n  (* Numbers in Isabelle are arbitrary precision! *)\n  term \"3871637126732613123526352635726456213527813658125817512332323232323::nat\"  \n  (* Warning: Computing with this may be really slow! \n    But Isabelle's main purpose is proving, not computing. *)\n    \n  value \"(100::nat) + 1\" (* A standard machine should take a few seconds for numbers around 1000..2000 here! *)   \n\n  lemma \"(3871637126732613123526352635726456213527813658125817512332323232323::nat) > 0\" by simp\n    (* However, Isabelle proves this (obvious) lemma within a few milliseconds! \n      Note: Proving lemmas will be introduced later!\n    *)  \n\n  value \"\n       (77777777777777777777777777777777777777777777777777777::int) \n      + 22222222222222222222222222222222222222222222222222222\"    \n    (* It's much better for integers (they use binary representation internally), but still not super-fast! *)\n    \n  subsection \\<open>Boolean Connectives\\<close>  \n    \n  term \"a\\<and>b \\<or> c\\<and>\\<not>d    \\<longrightarrow>    e\"  (* Priority is as expected. Use symbols panel to find out how to type these symbols! *)\n\n  (* Don't use *)  \n  term \"a & b | c & ~d\"  \n    \n  (*\n    Priority, from highest to lowest\n      \\<not>             not\n      \\<and>             and\n      \\<or>             or\n      \\<longrightarrow>, \\<longleftrightarrow>      implies, equal\n  *)  \n\n  (* Beware of using = for Booleans. It binds stronger than \\<and>.  *)  \n  value \\<open> let A=True; B=False in (A = B)  =  A\\<and>B \\<or> \\<not>A\\<and>\\<not>B \\<close>\n    (* This should output True, shouldn't it? *)\n    \n    (* Actually, it means: *)\n    declare [[show_brackets]]\n    term \"(A = B)  =  A\\<and>B \\<or> \\<not>A\\<and>\\<not>B\"\n    declare [[show_brackets = false]] (* To not see all these brackets in the following *)\n    \n    (* However, we meant *)  \n    term \"A = B \\<longleftrightarrow> A\\<and>B \\<or> \\<not>A\\<and>\\<not>B\"\n      \n  (* Usually, this is encountered on function definitions: *)\n  fun is_a_bit_smaller :: \"int \\<Rightarrow> int \\<Rightarrow> bool\" where \n    \"is_a_bit_smaller a b \\<longleftrightarrow> a < b \\<and> b-a < 10\"\n    \n      \n  subsection \\<open>Some Simple Examples\\<close>  \n  fun nth_odd :: \"nat \\<Rightarrow> nat\" where\n    \"nth_odd 0 = 1\"\n  | \"nth_odd (Suc n) = nth_odd n + 2\"\n\n  value \"int (nth_odd 2)\"  \n\n  (* YOU! Define nth_even! *)  \n  fun nth_even :: \"nat \\<Rightarrow> nat\" where\n    \"nth_even 0 = 0\"\n  | \"nth_even (Suc n) = nth_even n + 2\"\n    \n  value \"int (nth_even 4)\"  \n    \n    \n  (* n\\<^sup>2 can be computed as the sum of the first n odd numbers! *)  \n  fun square :: \"nat \\<Rightarrow> nat\" where\n    \"square 0 = 0\"\n  | \"square (Suc n) = nth_odd n + square n\"  \n\n  value \"square 2\"\n  value \"int (square 5)\" (* Using conversion to int for more readable output *)\n    \n  (* YOU: Define function sum :: nat list \\<Rightarrow> nat that sums up the elements of a list.\n    E.g. sum [3,4,5] = 12 *)\n    \n  fun sum :: \"nat list \\<Rightarrow> nat\" where\n    \"sum [] = 0\"\n  | \"sum (x#xs) = x + sum xs\"  \n    \n  value \"int (sum [3,4,5])\"  \n\n  (* YOU: Define Fibonacchi sequence: fib :: \"nat \\<Rightarrow> nat\" where\n    fib 0 = 0, fib 1 = 1, fib n = fib (n-2) + fib (n-1)\n  *)  \n\n  (* YOU: Define function rep_list :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n    such that \"rep_list n l = l @ \\<dots> @ l  (n times)\"\n  *)  \n    \n  fun rep_list :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n    \"rep_list 0 l = []\"\n  | \"rep_list (Suc n) l = l @ rep_list n l\"  \n    \n  value \"rep_list 5 ''Hello World!''\" (* Note: Strings are just lists of characters! *) \n  typ string\n  \n    \n    \n    \n  subsection \\<open>Some list functions\\<close>\n  \n  subsubsection \\<open>Map\\<close>  \n    \n  term map  \n  value \"map (\\<lambda>x. x+1) [-1,-2,3,4,5::int]\"\n  (* Apply function to each element in list *)\n  (* \\<open>\\<lambda>\\<close> used to create ''anonymous'' function. *)\n  term \"\\<lambda>x y z. Suc (x+y+z)\" -- \\<open>Multiple arguments\\<close>  \n\n  (* In Isabelle/HOL, there are no side effects! A term's value will never \n    change as the result of evaluating a term!\n  *)\n  value \"let l=[1,2,3::int] in map (\\<lambda>x. x+1) l @ map (\\<lambda>x. x+1) l\"\n\n    \n  subsubsection \\<open>Filter\\<close>  \n  \n  definition \"f x = (x>0)\"  \n  value \"filter f [-3,-6,3,4,-5,9::int]\"\n    \n  value \"filter (\\<lambda>x. x>0) [-3,-6,3,4,-5,9::int]\"\n  (* Filter out elements that do not satisfy condition *)\n\n  section \\<open>Quicksort\\<close>  \n    \n  (* We select the first element as pivot.\n    Note: Simpler than imperative in-situ implementation, as\n      no swapping of array elements is required.\n      However: Also less efficient :( But same worst and average case complexity!\n  *)\n    \n  fun qsort :: \"int list \\<Rightarrow> int list\" where\n    \"qsort [] = []\"\n  | \"qsort (p#xs) = qsort (filter (\\<lambda>x. x\\<le>p) xs) @ p # qsort (filter (\\<lambda>x. x>p) xs)\"  \n    \n  value \"qsort [3,4,1,7,8,4]\"    \n\n  subsection \\<open>Outlook: Correctness proof\\<close>  \n    \n  (* Let's prove that quicksort actually sorts the list.\n    We have to show:\n      \\<^enum> The elements and the number of each element is not altered by sorting\n      \\<^enum> The resulting list is sorted\n  *)\n\n  (* We show that the multiset of the result list is the same \n    as the multiset of the original list.\n\n    Multiset (sometimes called bag): Elements with counts, but no order.\n  *)\n  lemma qsort_pres_mset: \"mset (qsort xs) = mset xs\"\n    apply (induction xs rule: qsort.induct) \n    using mset_compl_union[where P=\"\\<lambda>x::int. x\\<le>p\" for p, unfolded not_le]\n    by auto\n\n  (* We use the predicate sorted from the standard library \n    to express sortedness of a list:\n  *)\n  lemma qsort_sorted: \"sorted (qsort xs)\"\n    by (induction xs rule: qsort.induct)\n       (auto simp: sorted_append sorted_Cons mset_eq_setD[OF qsort_pres_mset])\n       \n  (*For now, just ignore the proofs. After the Isabelle introduction, you'll \n    be able to conduct similar proofs easily!*)\n\n    \nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Demos/FunProg_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.7800616146414694}}
{"text": "(*  Title:      HOL/Number_Theory/Residues.thy\n    Author:     Jeremy Avigad\n\nAn algebraic treatment of residue rings, and resulting proofs of\nEuler's theorem and Wilson's theorem.\n*)\n\nsection {* Residue rings *}\n\ntheory Residues\nimports\n  UniqueFactorization\n  Binomial\n  MiscAlgebra\nbegin\n\n(*\n\n  A locale for residue rings\n\n*)\n\ndefinition residue_ring :: \"int => int ring\" where\n  \"residue_ring m == (|\n    carrier =       {0..m - 1},\n    mult =          (%x y. (x * y) mod m),\n    one =           1,\n    zero =          0,\n    add =           (%x y. (x + y) mod m) |)\"\n\nlocale residues =\n  fixes m :: int and R (structure)\n  assumes m_gt_one: \"m > 1\"\n  defines \"R == residue_ring m\"\n\ncontext residues\nbegin\n\nlemma abelian_group: \"abelian_group R\"\n  apply (insert m_gt_one)\n  apply (rule abelian_groupI)\n  apply (unfold R_def residue_ring_def)\n  apply (auto simp add: mod_add_right_eq [symmetric] ac_simps)\n  apply (case_tac \"x = 0\")\n  apply force\n  apply (subgoal_tac \"(x + (m - x)) mod m = 0\")\n  apply (erule bexI)\n  apply auto\n  done\n\nlemma comm_monoid: \"comm_monoid R\"\n  apply (insert m_gt_one)\n  apply (unfold R_def residue_ring_def)\n  apply (rule comm_monoidI)\n  apply auto\n  apply (subgoal_tac \"x * y mod m * z mod m = z * (x * y mod m) mod m\")\n  apply (erule ssubst)\n  apply (subst mod_mult_right_eq [symmetric])+\n  apply (simp_all only: ac_simps)\n  done\n\nlemma cring: \"cring R\"\n  apply (rule cringI)\n  apply (rule abelian_group)\n  apply (rule comm_monoid)\n  apply (unfold R_def residue_ring_def, auto)\n  apply (subst mod_add_eq [symmetric])\n  apply (subst mult.commute)\n  apply (subst mod_mult_right_eq [symmetric])\n  apply (simp add: field_simps)\n  done\n\nend\n\nsublocale residues < cring\n  by (rule cring)\n\n\ncontext residues\nbegin\n\n(* These lemmas translate back and forth between internal and\n   external concepts *)\n\nlemma res_carrier_eq: \"carrier R = {0..m - 1}\"\n  unfolding R_def residue_ring_def by auto\n\nlemma res_add_eq: \"x \\<oplus> y = (x + y) mod m\"\n  unfolding R_def residue_ring_def by auto\n\nlemma res_mult_eq: \"x \\<otimes> y = (x * y) mod m\"\n  unfolding R_def residue_ring_def by auto\n\nlemma res_zero_eq: \"\\<zero> = 0\"\n  unfolding R_def residue_ring_def by auto\n\nlemma res_one_eq: \"\\<one> = 1\"\n  unfolding R_def residue_ring_def units_of_def by auto\n\nlemma res_units_eq: \"Units R = { x. 0 < x & x < m & coprime x m}\"\n  apply (insert m_gt_one)\n  apply (unfold Units_def R_def residue_ring_def)\n  apply auto\n  apply (subgoal_tac \"x ~= 0\")\n  apply auto\n  apply (metis invertible_coprime_int)\n  apply (subst (asm) coprime_iff_invertible'_int)\n  apply (auto simp add: cong_int_def mult.commute)\n  done\n\nlemma res_neg_eq: \"\\<ominus> x = (- x) mod m\"\n  apply (insert m_gt_one)\n  apply (unfold R_def a_inv_def m_inv_def residue_ring_def)\n  apply auto\n  apply (rule the_equality)\n  apply auto\n  apply (subst mod_add_right_eq [symmetric])\n  apply auto\n  apply (subst mod_add_left_eq [symmetric])\n  apply auto\n  apply (subgoal_tac \"y mod m = - x mod m\")\n  apply simp\n  apply (metis minus_add_cancel mod_mult_self1 mult.commute)\n  done\n\nlemma finite [iff]: \"finite (carrier R)\"\n  by (subst res_carrier_eq, auto)\n\nlemma finite_Units [iff]: \"finite (Units R)\"\n  by (subst res_units_eq) auto\n\n(* The function a -> a mod m maps the integers to the\n   residue classes. The following lemmas show that this mapping\n   respects addition and multiplication on the integers. *)\n\nlemma mod_in_carrier [iff]: \"a mod m : carrier R\"\n  apply (unfold res_carrier_eq)\n  apply (insert m_gt_one, auto)\n  done\n\nlemma add_cong: \"(x mod m) \\<oplus> (y mod m) = (x + y) mod m\"\n  unfolding R_def residue_ring_def\n  apply auto\n  apply presburger\n  done\n\nlemma mult_cong: \"(x mod m) \\<otimes> (y mod m) = (x * y) mod m\"\n  unfolding R_def residue_ring_def\n  by auto (metis mod_mult_eq)\n\nlemma zero_cong: \"\\<zero> = 0\"\n  unfolding R_def residue_ring_def by auto\n\nlemma one_cong: \"\\<one> = 1 mod m\"\n  using m_gt_one unfolding R_def residue_ring_def by auto\n\n(* revise algebra library to use 1? *)\nlemma pow_cong: \"(x mod m) (^) n = x^n mod m\"\n  apply (insert m_gt_one)\n  apply (induct n)\n  apply (auto simp add: nat_pow_def one_cong)\n  apply (metis mult.commute mult_cong)\n  done\n\nlemma neg_cong: \"\\<ominus> (x mod m) = (- x) mod m\"\n  by (metis mod_minus_eq res_neg_eq)\n\nlemma (in residues) prod_cong:\n    \"finite A \\<Longrightarrow> (\\<Otimes> i:A. (f i) mod m) = (PROD i:A. f i) mod m\"\n  by (induct set: finite) (auto simp: one_cong mult_cong)\n\nlemma (in residues) sum_cong:\n    \"finite A \\<Longrightarrow> (\\<Oplus> i:A. (f i) mod m) = (SUM i: A. f i) mod m\"\n  by (induct set: finite) (auto simp: zero_cong add_cong)\n\nlemma mod_in_res_units [simp]: \"1 < m \\<Longrightarrow> coprime a m \\<Longrightarrow>\n    a mod m : Units R\"\n  apply (subst res_units_eq, auto)\n  apply (insert pos_mod_sign [of m a])\n  apply (subgoal_tac \"a mod m ~= 0\")\n  apply arith\n  apply auto\n  apply (metis gcd_int.commute gcd_red_int)\n  done\n\nlemma res_eq_to_cong: \"((a mod m) = (b mod m)) = [a = b] (mod (m::int))\"\n  unfolding cong_int_def by auto\n\n(* Simplifying with these will translate a ring equation in R to a\n   congruence. *)\n\nlemmas res_to_cong_simps = add_cong mult_cong pow_cong one_cong\n    prod_cong sum_cong neg_cong res_eq_to_cong\n\n(* Other useful facts about the residue ring *)\n\nlemma one_eq_neg_one: \"\\<one> = \\<ominus> \\<one> \\<Longrightarrow> m = 2\"\n  apply (simp add: res_one_eq res_neg_eq)\n  apply (metis add.commute add_diff_cancel mod_mod_trivial one_add_one uminus_add_conv_diff\n            zero_neq_one zmod_zminus1_eq_if)\n  done\n\nend\n\n\n(* prime residues *)\n\nlocale residues_prime =\n  fixes p and R (structure)\n  assumes p_prime [intro]: \"prime p\"\n  defines \"R == residue_ring p\"\n\nsublocale residues_prime < residues p\n  apply (unfold R_def residues_def)\n  using p_prime apply auto\n  apply (metis (full_types) int_1 of_nat_less_iff prime_gt_1_nat)\n  done\n\ncontext residues_prime\nbegin\n\nlemma is_field: \"field R\"\n  apply (rule cring.field_intro2)\n  apply (rule cring)\n  apply (auto simp add: res_carrier_eq res_one_eq res_zero_eq res_units_eq)\n  apply (rule classical)\n  apply (erule notE)\n  apply (subst gcd_commute_int)\n  apply (rule prime_imp_coprime_int)\n  apply (rule p_prime)\n  apply (rule notI)\n  apply (frule zdvd_imp_le)\n  apply auto\n  done\n\nlemma res_prime_units_eq: \"Units R = {1..p - 1}\"\n  apply (subst res_units_eq)\n  apply auto\n  apply (subst gcd_commute_int)\n  apply (auto simp add: p_prime prime_imp_coprime_int zdvd_not_zless)\n  done\n\nend\n\nsublocale residues_prime < field\n  by (rule is_field)\n\n\n(*\n  Test cases: Euler's theorem and Wilson's theorem.\n*)\n\n\nsubsection{* Euler's theorem *}\n\n(* the definition of the phi function *)\n\ndefinition phi :: \"int => nat\"\n  where \"phi m = card({ x. 0 < x & x < m & gcd x m = 1})\"\n\nlemma phi_def_nat: \"phi m = card({ x. 0 < x & x < nat m & gcd x (nat m) = 1})\"\n  apply (simp add: phi_def)\n  apply (rule bij_betw_same_card [of nat])\n  apply (auto simp add: inj_on_def bij_betw_def image_def)\n  apply (metis dual_order.irrefl dual_order.strict_trans leI nat_1 transfer_nat_int_gcd(1))\n  apply (metis One_nat_def int_0 int_1 int_less_0_conv int_nat_eq nat_int transfer_int_nat_gcd(1) zless_int)\n  done\n\nlemma prime_phi:\n  assumes  \"2 \\<le> p\" \"phi p = p - 1\" shows \"prime p\"\nproof -\n  have \"{x. 0 < x \\<and> x < p \\<and> coprime x p} = {1..p - 1}\"\n    using assms unfolding phi_def_nat\n    by (intro card_seteq) fastforce+\n  then have cop: \"\\<And>x. x \\<in> {1::nat..p - 1} \\<Longrightarrow> coprime x p\"\n    by blast\n  { fix x::nat assume *: \"1 < x\" \"x < p\" and \"x dvd p\"\n    have \"coprime x p\" \n      apply (rule cop)\n      using * apply auto\n      done\n    with `x dvd p` `1 < x` have \"False\" by auto }\n  then show ?thesis \n    using `2 \\<le> p` \n    by (simp add: prime_def)\n       (metis One_nat_def dvd_pos_nat nat_dvd_not_less nat_neq_iff not_gr0 \n              not_numeral_le_zero one_dvd)\nqed\n\nlemma phi_zero [simp]: \"phi 0 = 0\"\n  apply (subst phi_def)\n(* Auto hangs here. Once again, where is the simplification rule\n   1 == Suc 0 coming from? *)\n  apply (auto simp add: card_eq_0_iff)\n(* Add card_eq_0_iff as a simp rule? delete card_empty_imp? *)\n  done\n\nlemma phi_one [simp]: \"phi 1 = 0\"\n  by (auto simp add: phi_def card_eq_0_iff)\n\nlemma (in residues) phi_eq: \"phi m = card(Units R)\"\n  by (simp add: phi_def res_units_eq)\n\nlemma (in residues) euler_theorem1:\n  assumes a: \"gcd a m = 1\"\n  shows \"[a^phi m = 1] (mod m)\"\nproof -\n  from a m_gt_one have [simp]: \"a mod m : Units R\"\n    by (intro mod_in_res_units)\n  from phi_eq have \"(a mod m) (^) (phi m) = (a mod m) (^) (card (Units R))\"\n    by simp\n  also have \"\\<dots> = \\<one>\"\n    by (intro units_power_order_eq_one, auto)\n  finally show ?thesis\n    by (simp add: res_to_cong_simps)\nqed\n\n(* In fact, there is a two line proof!\n\nlemma (in residues) euler_theorem1:\n  assumes a: \"gcd a m = 1\"\n  shows \"[a^phi m = 1] (mod m)\"\nproof -\n  have \"(a mod m) (^) (phi m) = \\<one>\"\n    by (simp add: phi_eq units_power_order_eq_one a m_gt_one)\n  then show ?thesis\n    by (simp add: res_to_cong_simps)\nqed\n\n*)\n\n(* outside the locale, we can relax the restriction m > 1 *)\n\nlemma euler_theorem:\n  assumes \"m >= 0\" and \"gcd a m = 1\"\n  shows \"[a^phi m = 1] (mod m)\"\nproof (cases)\n  assume \"m = 0 | m = 1\"\n  then show ?thesis by auto\nnext\n  assume \"~(m = 0 | m = 1)\"\n  with assms show ?thesis\n    by (intro residues.euler_theorem1, unfold residues_def, auto)\nqed\n\nlemma (in residues_prime) phi_prime: \"phi p = (nat p - 1)\"\n  apply (subst phi_eq)\n  apply (subst res_prime_units_eq)\n  apply auto\n  done\n\nlemma phi_prime: \"prime p \\<Longrightarrow> phi p = (nat p - 1)\"\n  apply (rule residues_prime.phi_prime)\n  apply (erule residues_prime.intro)\n  done\n\nlemma fermat_theorem:\n  fixes a::int\n  assumes \"prime p\" and \"~ (p dvd a)\"\n  shows \"[a^(p - 1) = 1] (mod p)\"\nproof -\n  from assms have \"[a^phi p = 1] (mod p)\"\n    apply (intro euler_theorem)\n    apply (metis of_nat_0_le_iff)\n    apply (metis gcd_int.commute prime_imp_coprime_int)\n    done\n  also have \"phi p = nat p - 1\"\n    by (rule phi_prime, rule assms)\n  finally show ?thesis\n    by (metis nat_int) \nqed\n\nlemma fermat_theorem_nat:\n  assumes \"prime p\" and \"~ (p dvd a)\"\n  shows \"[a^(p - 1) = 1] (mod p)\"\nusing fermat_theorem [of p a] assms\nby (metis int_1 of_nat_power transfer_int_nat_cong zdvd_int)\n\n\nsubsection {* Wilson's theorem *}\n\nlemma (in field) inv_pair_lemma: \"x : Units R \\<Longrightarrow> y : Units R \\<Longrightarrow>\n    {x, inv x} ~= {y, inv y} \\<Longrightarrow> {x, inv x} Int {y, inv y} = {}\"\n  apply auto\n  apply (metis Units_inv_inv)+\n  done\n\nlemma (in residues_prime) wilson_theorem1:\n  assumes a: \"p > 2\"\n  shows \"[fact (p - 1) = - 1] (mod p)\"\nproof -\n  let ?InversePairs = \"{ {x, inv x} | x. x : Units R - {\\<one>, \\<ominus> \\<one>}}\"\n  have UR: \"Units R = {\\<one>, \\<ominus> \\<one>} Un (Union ?InversePairs)\"\n    by auto\n  have \"(\\<Otimes>i: Units R. i) =\n    (\\<Otimes>i: {\\<one>, \\<ominus> \\<one>}. i) \\<otimes> (\\<Otimes>i: Union ?InversePairs. i)\"\n    apply (subst UR)\n    apply (subst finprod_Un_disjoint)\n    apply (auto intro: funcsetI)\n    apply (metis Units_inv_inv inv_one inv_neg_one)+\n    done\n  also have \"(\\<Otimes>i: {\\<one>, \\<ominus> \\<one>}. i) = \\<ominus> \\<one>\"\n    apply (subst finprod_insert)\n    apply auto\n    apply (frule one_eq_neg_one)\n    apply (insert a, force)\n    done\n  also have \"(\\<Otimes>i:(Union ?InversePairs). i) =\n      (\\<Otimes>A: ?InversePairs. (\\<Otimes>y:A. y))\"\n    apply (subst finprod_Union_disjoint, auto)\n    apply (metis Units_inv_inv)+\n    done\n  also have \"\\<dots> = \\<one>\"\n    apply (rule finprod_one, auto)\n    apply (subst finprod_insert, auto)\n    apply (metis inv_eq_self)\n    done\n  finally have \"(\\<Otimes>i: Units R. i) = \\<ominus> \\<one>\"\n    by simp\n  also have \"(\\<Otimes>i: Units R. i) = (\\<Otimes>i: Units R. i mod p)\"\n    apply (rule finprod_cong')\n    apply (auto)\n    apply (subst (asm) res_prime_units_eq)\n    apply auto\n    done\n  also have \"\\<dots> = (PROD i: Units R. i) mod p\"\n    apply (rule prod_cong)\n    apply auto\n    done\n  also have \"\\<dots> = fact (p - 1) mod p\"\n    apply (subst fact_altdef_nat)\n    apply (insert assms)\n    apply (subst res_prime_units_eq)\n    apply (simp add: int_setprod zmod_int setprod_int_eq)\n    done\n  finally have \"fact (p - 1) mod p = \\<ominus> \\<one>\".\n  then show ?thesis\n    by (metis Divides.transfer_int_nat_functions(2) cong_int_def res_neg_eq res_one_eq)\nqed\n\nlemma wilson_theorem:\n  assumes \"prime p\" shows \"[fact (p - 1) = - 1] (mod p)\"\nproof (cases \"p = 2\")\n  case True \n  then show ?thesis\n    by (simp add: cong_int_def fact_altdef_nat)\nnext\n  case False\n  then show ?thesis\n    using assms prime_ge_2_nat\n    by (metis residues_prime.wilson_theorem1 residues_prime.intro le_eq_less_or_eq)\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Number_Theory/Residues.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7799834389787454}}
{"text": "theory ex3_04 imports Main begin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\" |\n\"aval (Times a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s * aval a\\<^sub>2 s\"\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\nfun times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"times (N n) (N m) = N (n*m)\" |\n\"times (N n) a = (if n = 0 then N 0 else if n = 1 then a else Times (N n) a)\" |\n\"times a (N n) = (if n = 0 then N 0 else if n = 1 then a else Times a (N n))\" |\n\"times a b = Times a b\"\n\nlemma aval_times[simp]:\n  \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all\ndone\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\" |\n\"asimp (Times a\\<^sub>1 a\\<^sub>2) = times (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend\n", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter3/ex3_04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7799834325150754}}
{"text": "(*  Title:      Schutz_Spacetime/TernaryOrdering.thy\n    Authors:    Richard Schmoetten, Jake Palmer and Jacques D. Fleuriot\n                University of Edinburgh, 2021          \n*)\ntheory TernaryOrdering\nimports Util\n\nbegin\n\ntext \\<open>\n  Definition of chains using an ordering on sets of events\n  based on natural numbers, plus some proofs.\n\\<close>\n\nsection \\<open>Totally ordered chains\\<close>\n\ntext \\<open>\n  Based on page 110 of Phil Scott's thesis and the following HOL Light definition:\n  \\begin{verbatim}\n  let ORDERING = new_definition\n    `ORDERING f X <=> (!n. (FINITE X ==> n < CARD X) ==> f n IN X)\n                    /\\ (!x. x IN X ==> ?n. (FINITE X ==> n < CARD X)\n                        /\\ f n = x)                   \n                    /\\ !n n' n''. (FINITE X ==> n'' < CARD X)\n                          /\\ n < n' /\\ n' < n'' \n                          ==> between (f n) (f n') (f n'')`;;\n  \\end{verbatim}\n  I've made it strict for simplicity, and because that's how Schutz's ordering is. It could be\n  made more generic by taking in the function corresponding to $<$ as a paramater.\n  Main difference to Schutz: he has local order, not total (cf Theorem 2 and \\<open>local_ordering\\<close>).\n\\<close>\n\ndefinition ordering :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"ordering f ord X \\<equiv> (\\<forall>n. (finite X \\<longrightarrow> n < card X) \\<longrightarrow> f n \\<in> X)\n                     \\<and> (\\<forall>x\\<in>X. (\\<exists>n. (finite X \\<longrightarrow> n < card X) \\<and> f n = x))\n                     \\<and> (\\<forall>n n' n''. (finite X \\<longrightarrow> n'' < card X) \\<and> n < n' \\<and> n' < n''\n                                   \\<longrightarrow> ord (f n) (f n') (f n''))\"\n\nlemma finite_ordering_intro:\n  assumes \"finite X\"\n    and \"\\<forall>n < card X. f n \\<in> X\"\n    and \"\\<forall>x \\<in> X. \\<exists>n < card X. f n = x\"\n    and \"\\<forall>n n' n''. n < n' \\<and> n' < n'' \\<and> n'' < card X \\<longrightarrow> ord (f n) (f n') (f n'')\"\n  shows \"ordering f ord X\"\n  unfolding ordering_def by (simp add: assms)\n\nlemma infinite_ordering_intro:\n  assumes \"infinite X\"\n    and \"\\<forall>n::nat. f n \\<in> X\"\n    and \"\\<forall>x \\<in> X. \\<exists>n::nat. f n = x\"\n    and \"\\<forall>n n' n''. n < n' \\<and> n' < n'' \\<longrightarrow> ord (f n) (f n') (f n'')\"\n  shows \"ordering f ord X\"\n  unfolding ordering_def by (simp add: assms)\n\nlemma ordering_ord_ijk:\n  assumes \"ordering f ord X\"\n      and \"i < j \\<and> j < k \\<and> (finite X \\<longrightarrow> k < card X)\"\n  shows \"ord (f i) (f j) (f k)\"\n  by (metis ordering_def assms)\n\nlemma empty_ordering [simp]: \"\\<exists>f. ordering f ord {}\"\n  by (simp add: ordering_def)\n\nlemma singleton_ordering [simp]: \"\\<exists>f. ordering f ord {a}\"\n  apply (rule_tac x = \"\\<lambda>n. a\" in exI)\n  by (simp add: ordering_def)\n\nlemma two_ordering [simp]: \"\\<exists>f. ordering f ord {a, b}\"\nproof cases\n  assume \"a = b\"\n  thus ?thesis using singleton_ordering by simp\nnext\n  assume a_neq_b: \"a \\<noteq> b\"\n  let ?f = \"\\<lambda>n. if n = 0 then a else b\"\n  have ordering1: \"(\\<forall>n. (finite {a,b} \\<longrightarrow> n < card {a,b}) \\<longrightarrow> ?f n \\<in> {a,b})\" by simp\n  have local_ordering: \"(\\<forall>x\\<in>{a,b}. \\<exists>n. (finite {a,b} \\<longrightarrow> n < card {a,b}) \\<and> ?f n = x)\"\n    using a_neq_b all_not_in_conv card_Suc_eq card_0_eq card_gt_0_iff insert_iff lessI by auto\n  have ordering3: \"(\\<forall>n n' n''. (finite {a,b} \\<longrightarrow> n'' < card {a,b}) \\<and> n < n' \\<and> n' < n''\n                                \\<longrightarrow> ord (?f n) (?f n') (?f n''))\" using a_neq_b by auto\n  have \"ordering ?f ord {a, b}\" using ordering_def ordering1 local_ordering ordering3 by blast\n  thus ?thesis by auto\nqed\n\nlemma card_le2_ordering:\n  assumes finiteX: \"finite X\"\n      and card_le2: \"card X \\<le> 2\"\n  shows \"\\<exists>f. ordering f ord X\"\nproof -\n  have card012: \"card X = 0 \\<or> card X = 1 \\<or> card X = 2\" using card_le2 by auto\n  have card0: \"card X = 0 \\<longrightarrow> ?thesis\" using finiteX by simp\n  have card1: \"card X = 1 \\<longrightarrow> ?thesis\" using card_eq_SucD by fastforce\n  have card2: \"card X = 2 \\<longrightarrow> ?thesis\" by (metis two_ordering card_eq_SucD numeral_2_eq_2)\n  thus ?thesis using card012 card0 card1 card2 by auto\nqed\n\nlemma ord_ordered:\n  assumes abc: \"ord a b c\"\n      and abc_neq: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c\"\n  shows \"\\<exists>f. ordering f ord {a,b,c}\"\n  apply (rule_tac x = \"\\<lambda>n. if n = 0 then a else if n = 1 then b else c\" in exI)\n  apply (unfold ordering_def)\n  using abc abc_neq by auto\n\nlemma overlap_ordering:\n  assumes abc: \"ord a b c\"\n      and bcd: \"ord b c d\"\n      and abd: \"ord a b d\"\n      and acd: \"ord a c d\"\n      and abc_neq: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> a \\<noteq> d \\<and> b \\<noteq> c \\<and> b \\<noteq> d \\<and> c \\<noteq> d\"\n  shows \"\\<exists>f. ordering f ord {a,b,c,d}\"\nproof -\n  let ?X = \"{a,b,c,d}\"\n  let ?f = \"\\<lambda>n. if n = 0 then a else if n = 1 then b else if n = 2 then c else d\"\n  have card4: \"card ?X = 4\" using abc bcd abd abc_neq by simp\n  have ordering1: \"\\<forall>n. (finite ?X \\<longrightarrow> n < card ?X) \\<longrightarrow> ?f n \\<in> ?X\" by simp\n  have local_ordering: \"\\<forall>x\\<in>?X. \\<exists>n. (finite ?X \\<longrightarrow> n < card ?X) \\<and> ?f n = x\"\n    by (metis card4 One_nat_def Suc_1 Suc_lessI empty_iff insertE numeral_3_eq_3 numeral_eq_iff\n              numeral_eq_one_iff rel_simps(51) semiring_norm(85) semiring_norm(86) semiring_norm(87)\n              semiring_norm(89) zero_neq_numeral)\n  have ordering3: \"(\\<forall>n n' n''. (finite ?X \\<longrightarrow> n'' < card ?X) \\<and> n < n' \\<and> n' < n''\n                                 \\<longrightarrow> ord (?f n) (?f n') (?f n''))\"\n    using card4 abc bcd abd acd card_0_eq card_insert_if finite.emptyI finite_insert less_antisym\n          less_one less_trans_Suc not_less_eq not_one_less_zero numeral_2_eq_2 by auto\n  have \"ordering ?f ord ?X\" using ordering1 local_ordering ordering3 ordering_def by blast\n  thus ?thesis by auto\nqed\n\nlemma overlap_ordering_alt1:\n  assumes abc: \"ord a b c\"\n      and bcd: \"ord b c d\"\n      and abc_bcd_abd: \"\\<forall> a b c d. ord a b c \\<and> ord b c d \\<longrightarrow> ord a b d\"\n      and abc_bcd_acd: \"\\<forall> a b c d. ord a b c \\<and> ord b c d \\<longrightarrow> ord a c d\"\n      and ord_distinct: \"\\<forall>a b c. (ord a b c \\<longrightarrow> a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c)\"\n  shows \"\\<exists>f. ordering f ord {a,b,c,d}\"\n  by (metis (full_types) assms overlap_ordering)\n\nlemma overlap_ordering_alt2:\n  assumes abc: \"ord a b c\"\n      and bcd: \"ord b c d\"\n      and abd: \"ord a b d\"\n      and acd: \"ord a c d\"\n      and ord_distinct: \"\\<forall>a b c. (ord a b c \\<longrightarrow> a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c)\"\n  shows \"\\<exists>f. ordering f ord {a,b,c,d}\"\n  by (metis assms overlap_ordering)\n\nlemma overlap_ordering_alt:\n  assumes abc: \"ord a b c\"\n      and bcd: \"ord b c d\"\n      and abc_bcd_abd: \"\\<forall> a b c d. ord a b c \\<and> ord b c d \\<longrightarrow> ord a b d\"\n      and abc_bcd_acd: \"\\<forall> a b c d. ord a b c \\<and> ord b c d \\<longrightarrow> ord a c d\"\n      and abc_neq: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> a \\<noteq> d \\<and> b \\<noteq> c \\<and> b \\<noteq> d \\<and> c \\<noteq> d\"\n  shows \"\\<exists>f. ordering f ord {a,b,c,d}\"\n  by (meson assms overlap_ordering)\n\ntext \\<open>\n  The lemmas below are easy to prove for \\<open>X = {}\\<close>, and if I included that case then I would have\n  to write a conditional definition in place of \\<open>{0..|X| - 1}\\<close>.\n\\<close>\n\nlemma finite_ordering_img: \"\\<lbrakk>X \\<noteq> {}; finite X; ordering f ord X\\<rbrakk> \\<Longrightarrow> f ` {0..card X - 1} = X\"\n  by (force simp add: ordering_def image_def)\n\nlemma inf_ordering_img: \"\\<lbrakk>infinite X; ordering f ord X\\<rbrakk> \\<Longrightarrow> f ` {0..} = X\"\n  by (auto simp add: ordering_def image_def)\n\nlemma inf_ordering_inv_img: \"\\<lbrakk>infinite X; ordering f ord X\\<rbrakk> \\<Longrightarrow> f -` X = {0..}\"\n  by (auto simp add: ordering_def image_def)\n\nlemma inf_ordering_img_inv_img: \"\\<lbrakk>infinite X; ordering f ord X\\<rbrakk> \\<Longrightarrow> f ` f -` X = X\"\n  using inf_ordering_img by auto\n\nlemma finite_ordering_inj_on: \"\\<lbrakk>finite X; ordering f ord X\\<rbrakk> \\<Longrightarrow> inj_on f {0..card X - 1}\"\n  by (metis finite_ordering_img Suc_diff_1 atLeastAtMost_iff card_atLeastAtMost card_eq_0_iff\n        diff_0_eq_0 diff_zero eq_card_imp_inj_on gr0I inj_onI le_0_eq)\n\nlemma finite_ordering_bij:\n  assumes orderingX: \"ordering f ord X\"\n      and finiteX: \"finite X\"\n      and non_empty: \"X \\<noteq> {}\"\n  shows \"bij_betw f {0..card X - 1} X\"\nproof -\n  have f_image: \"f ` {0..card X - 1} = X\" by (metis orderingX finiteX finite_ordering_img non_empty)\n  thus ?thesis by (metis inj_on_imp_bij_betw orderingX finiteX finite_ordering_inj_on)  \nqed\n\nlemma inf_ordering_inj':\n  assumes infX: \"infinite X\"\n      and f_ord: \"ordering f ord X\"\n      and ord_distinct: \"\\<forall>a b c. (ord a b c \\<longrightarrow> a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c)\"\n      and f_eq: \"f m = f n\"\n  shows \"m = n\"\nproof (rule ccontr)\n  assume m_not_n: \"m \\<noteq> n\"\n  have betw_3n: \"\\<forall>n n' n''. n < n' \\<and> n' < n'' \\<longrightarrow> ord (f n) (f n') (f n'')\"\n       using f_ord by (simp add: ordering_def infX)\n  thus False\n  proof cases\n    assume m_less_n: \"m < n\"\n    then obtain k where \"n < k\" by auto\n    then have \"ord (f m) (f n) (f k)\" using m_less_n betw_3n by simp\n    then have \"f m \\<noteq> f n\" using ord_distinct by simp\n    thus ?thesis using f_eq by simp\n  next\n    assume \"\\<not> m < n\"\n    then have n_less_m: \"n < m\" using m_not_n by simp\n    then obtain k where \"m < k\" by auto\n    then have \"ord (f n) (f m) (f k)\" using n_less_m betw_3n by simp\n    then have \"f n \\<noteq> f m\" using ord_distinct by simp\n    thus ?thesis using f_eq by simp\n  qed\nqed\n\nlemma inf_ordering_inj:\n  assumes \"infinite X\"\n      and \"ordering f ord X\"\n      and \"\\<forall>a b c. (ord a b c \\<longrightarrow> a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c)\"\n  shows \"inj f\"\n  using inf_ordering_inj' assms by (metis injI) \n\ntext \\<open>\n  The finite case is a little more difficult as I can't just choose some other natural number\n  to form the third part of the betweenness relation and the initial simplification isn't as nice.\n  Note that I cannot prove \\<open>inj f\\<close> (over the whole type that \\<open>f\\<close> is defined on, i.e. natural numbers),\n  because I need to capture the \\<open>m\\<close> and \\<open>n\\<close> that obey specific requirements for the finite case.\n  In order to prove \\<open>inj f\\<close>, I would have to extend the definition for ordering to include \\<open>m\\<close> and \\<open>n\\<close>\n  beyond \\<open>card X\\<close>, such that it is still injective. That would probably not be very useful.\n\\<close>\n\nlemma finite_ordering_inj:\n  assumes finiteX: \"finite X\"\n      and f_ord: \"ordering f ord X\"\n      and ord_distinct: \"\\<forall>a b c. (ord a b c \\<longrightarrow> a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c)\"\n      and m_less_card: \"m < card X\"\n      and n_less_card: \"n < card X\"\n      and f_eq: \"f m = f n\"\n  shows \"m = n\"\nproof (rule ccontr)\n  assume m_not_n: \"m \\<noteq> n\"\n  have surj_f: \"\\<forall>x\\<in>X. \\<exists>n<card X. f n = x\"\n               using f_ord by (simp add: ordering_def finiteX)\n  have betw_3n: \"\\<forall>n n' n''. n'' < card X \\<and> n < n' \\<and> n' < n'' \\<longrightarrow> ord (f n) (f n') (f n'')\"\n                using f_ord by (simp add: ordering_def)\n  show False\n  proof cases\n    assume card_le2: \"card X \\<le> 2\"\n    have card0: \"card X = 0 \\<longrightarrow> False\" using m_less_card by simp\n    have card1: \"card X = 1 \\<longrightarrow> False\" using m_less_card n_less_card m_not_n by simp\n    have card2: \"card X = 2 \\<longrightarrow> False\"\n    proof (rule impI)\n      assume card_is_2: \"card X = 2\"\n      then have mn01: \"m = 0 \\<and> n = 1 \\<or> n = 0 \\<and> m = 1\" using m_less_card n_less_card m_not_n by auto\n      then have \"f m \\<noteq> f n\" using card_is_2 surj_f One_nat_def card_eq_SucD insertCI\n                                  less_2_cases numeral_2_eq_2 by (metis (no_types, lifting))\n      thus False using f_eq by simp\n    qed\n    show False using card0 card1 card2 card_le2 by simp\n  next\n    assume \"\\<not> card X \\<le> 2\"\n    then have card_ge3: \"card X \\<ge> 3\" by simp\n    thus False\n    proof cases\n      assume m_less_n: \"m < n\"\n      then obtain k where k_pos: \"k < m \\<or> (m < k \\<and> k < n) \\<or> (n < k \\<and> k < card X)\"\n          using is_free_nat m_less_n n_less_card card_ge3 by blast\n      have k1: \"k < m \\<longrightarrow>ord (f k) (f m) (f n)\" using m_less_n n_less_card betw_3n by simp\n      have k2: \"m < k \\<and> k < n \\<longrightarrow> ord (f m) (f k) (f n)\" using m_less_n n_less_card betw_3n by simp\n      have k3: \"n < k \\<and> k < card X \\<longrightarrow> ord (f m) (f n) (f k)\" using m_less_n betw_3n by simp\n      have \"f m \\<noteq> f n\" using k1 k2 k3 k_pos ord_distinct by auto\n      thus False using f_eq by simp\n    next\n      assume \"\\<not> m < n\"\n      then have n_less_m: \"n < m\" using m_not_n by simp\n      then obtain k where k_pos: \"k < n \\<or> (n < k \\<and> k < m) \\<or> (m < k \\<and> k < card X)\"\n          using is_free_nat n_less_m m_less_card card_ge3 by blast\n      have k1: \"k < n \\<longrightarrow>ord (f k) (f n) (f m)\" using n_less_m m_less_card betw_3n by simp\n      have k2: \"n < k \\<and> k < m \\<longrightarrow> ord (f n) (f k) (f m)\" using n_less_m m_less_card betw_3n by simp\n      have k3: \"m < k \\<and> k < card X \\<longrightarrow> ord (f n) (f m) (f k)\" using n_less_m betw_3n by simp\n      have \"f n \\<noteq> f m\" using k1 k2 k3 k_pos ord_distinct by auto\n      thus False using f_eq by simp\n    qed\n  qed\nqed\n\nlemma ordering_inj:\n  assumes \"ordering f ord X\"\n      and \"\\<forall>a b c. (ord a b c \\<longrightarrow> a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c)\"\n      and \"finite X \\<longrightarrow> m < card X\"\n      and \"finite X \\<longrightarrow> n < card X\"\n      and \"f m = f n\"\n  shows \"m = n\"\n  using inf_ordering_inj' finite_ordering_inj assms by blast\n\nlemma ordering_sym:\n  assumes ord_sym: \"\\<And>a b c. ord a b c \\<Longrightarrow> ord c b a\"\n      and \"finite X\"\n      and \"ordering f ord X\"\n  shows \"ordering (\\<lambda>n. f (card X - 1 - n)) ord X\"\nunfolding ordering_def using assms(2)\n  apply auto\n  apply (metis ordering_def assms(3) card_0_eq card_gt_0_iff diff_Suc_less gr_implies_not0)\nproof -\n  fix x\n  assume \"finite X\"\n  assume \"x \\<in> X\"\n  obtain n where \"finite X \\<longrightarrow> n < card X\" and \"f n = x\"\n    by (metis ordering_def \\<open>x \\<in> X\\<close> assms(3))\n  have \"f (card X - ((card X - 1 - n) + 1)) = x\"\n    by (simp add: Suc_leI \\<open>f n = x\\<close> \\<open>finite X \\<longrightarrow> n < card X\\<close> assms(2))\n  thus \"\\<exists>n<card X. f (card X - Suc n) = x\"\n    by (metis \\<open>x \\<in> X\\<close> add.commute assms(2) card_Diff_singleton card_Suc_Diff1 diff_less_Suc plus_1_eq_Suc)\nnext\n  fix n n' n''\n  assume \"finite X\"\n  assume \"n'' < card X\" \"n < n'\" \"n' < n''\"\n  have \"ord (f (card X - Suc n'')) (f (card X - Suc n')) (f (card X - Suc n))\"\n    using assms(3) unfolding ordering_def\n    using \\<open>n < n'\\<close> \\<open>n' < n''\\<close> \\<open>n'' < card X\\<close> diff_less_mono2 by auto \n  thus \" ord (f (card X - Suc n)) (f (card X - Suc n')) (f (card X - Suc n''))\"\n    using ord_sym by blast\nqed\n\nlemma  zero_into_ordering:\n  assumes \"ordering f betw X\"\n  and \"X \\<noteq> {}\"\n  shows \"(f 0) \\<in> X\"\n  using ordering_def\n  by (metis assms card_eq_0_iff gr_implies_not0 linorder_neqE_nat)\n\n\nsection \"Locally ordered chains\"\ntext \\<open>Definitions for Schutz-like chains, with local order only.\\<close>\n\ndefinition local_ordering :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"local_ordering f ord X\n    \\<equiv> (\\<forall>n. (finite X \\<longrightarrow> n < card X) \\<longrightarrow> f n \\<in> X) \\<and>\n      (\\<forall>x\\<in>X. \\<exists>n. (finite X \\<longrightarrow> n < card X) \\<and> f n = x) \\<and>\n      (\\<forall>n. (finite X \\<longrightarrow> Suc (Suc n) < card X) \\<longrightarrow> ord (f n) (f (Suc n)) (f (Suc (Suc n))))\"\n\nlemma finite_local_ordering_intro:\n  assumes \"finite X\"\n    and \"\\<forall>n < card X. f n \\<in> X\"\n    and \"\\<forall>x \\<in> X. \\<exists>n < card X. f n = x\"\n    and \"\\<forall>n n' n''. Suc n = n' \\<and> Suc n' = n'' \\<and> n'' < card X \\<longrightarrow> ord (f n) (f n') (f n'')\"\n  shows \"local_ordering f ord X\"\n  unfolding local_ordering_def by (simp add: assms)\n\nlemma infinite_local_ordering_intro:\n  assumes \"infinite X\"\n    and \"\\<forall>n::nat. f n \\<in> X\"\n    and \"\\<forall>x \\<in> X. \\<exists>n::nat. f n = x\"\n    and \"\\<forall>n n' n''. Suc n = n' \\<and> Suc n' = n'' \\<longrightarrow> ord (f n) (f n') (f n'')\"\n  shows \"local_ordering f ord X\"\n  using assms unfolding local_ordering_def by metis\n\nlemma total_implies_local:\n  \"ordering f ord X \\<Longrightarrow> local_ordering f ord X\"\n  unfolding ordering_def local_ordering_def\n  using lessI by presburger\n\nlemma ordering_ord_ijk_loc:\n  assumes \"local_ordering f ord X\"\n      and \"finite X \\<longrightarrow> Suc (Suc i) < card X\"\n  shows \"ord (f i) (f (Suc i)) (f (Suc (Suc i)))\"\n  by (metis local_ordering_def assms)\n\nlemma empty_ordering_loc [simp]: \n  \"\\<exists>f. local_ordering f ord {}\"\n  by (simp add: local_ordering_def)\n\nlemma singleton_ordered_loc [simp]:\n  \"local_ordering f ord {f 0}\"\n  unfolding local_ordering_def by simp\n\nlemma singleton_ordering_loc [simp]: \n  \"\\<exists>f. local_ordering f ord {a}\"\n  using singleton_ordered_loc by fast\n\nlemma two_ordered_loc:\n  assumes \"a = f 0\" and \"b = f 1\"\n  shows \"local_ordering f ord {a, b}\"\nproof cases\n  assume \"a = b\"\n  thus ?thesis using assms singleton_ordered_loc by (metis insert_absorb2)\nnext\n  assume a_neq_b: \"a \\<noteq> b\"\n  hence \"(\\<forall>n. (finite {a,b} \\<longrightarrow> n < card {a,b}) \\<longrightarrow> f n \\<in> {a,b})\"\n    using assms by (metis One_nat_def card.infinite card_2_iff fact_0 fact_2 insert_iff less_2_cases_iff)\n  moreover have \"(\\<forall>x\\<in>{a,b}. \\<exists>n. (finite {a,b} \\<longrightarrow> n < card {a,b}) \\<and> f n = x)\"\n    using assms a_neq_b all_not_in_conv card_Suc_eq card_0_eq card_gt_0_iff insert_iff lessI by auto\n  moreover have \"(\\<forall>n. (finite {a,b} \\<longrightarrow> Suc (Suc n) < card {a,b}) \n                      \\<longrightarrow> ord (f n) (f (Suc n)) (f (Suc (Suc n))))\" \n    using a_neq_b by auto\n  ultimately have \"local_ordering f ord {a, b}\" \n     using local_ordering_def by blast\n  thus ?thesis by auto\nqed\n\nlemma two_ordering_loc [simp]: \n  \"\\<exists>f. local_ordering f ord {a, b}\"\n  using total_implies_local two_ordering by fastforce\n\nlemma card_le2_ordering_loc:\n  assumes finiteX: \"finite X\"\n      and card_le2: \"card X \\<le> 2\"\n  shows \"\\<exists>f. local_ordering f ord X\"\n  using assms total_implies_local card_le2_ordering by metis\n\nlemma ord_ordered_loc:\n  assumes abc: \"ord a b c\"\n      and abc_neq: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c\"\n  shows \"\\<exists>f. local_ordering f ord {a,b,c}\"\n  using assms total_implies_local ord_ordered by metis\n\nlemma overlap_ordering_loc:\n  assumes abc: \"ord a b c\"\n      and bcd: \"ord b c d\"\n      and abd: \"ord a b d\"\n      and acd: \"ord a c d\"\n      and abc_neq: \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> a \\<noteq> d \\<and> b \\<noteq> c \\<and> b \\<noteq> d \\<and> c \\<noteq> d\"\n  shows \"\\<exists>f. local_ordering f ord {a,b,c,d}\"\n  using overlap_ordering[OF assms] total_implies_local by blast\n\nlemma ordering_sym_loc:\n  assumes ord_sym: \"\\<And>a b c. ord a b c \\<Longrightarrow> ord c b a\"\n      and \"finite X\"\n      and \"local_ordering f ord X\"\n  shows \"local_ordering (\\<lambda>n. f (card X - 1 - n)) ord X\"\n  unfolding local_ordering_def using assms(2) apply auto\n  apply (metis local_ordering_def assms(3) card_0_eq card_gt_0_iff diff_Suc_less gr_implies_not0)\nproof -\n  fix x\n  assume \"finite X\"\n  assume \"x \\<in> X\"\n  obtain n where \"finite X \\<longrightarrow> n < card X\" and \"f n = x\"\n    by (metis local_ordering_def \\<open>x \\<in> X\\<close> assms(3))\n  have \"f (card X - ((card X - 1 - n) + 1)) = x\"\n    by (simp add: Suc_leI \\<open>f n = x\\<close> \\<open>finite X \\<longrightarrow> n < card X\\<close> assms(2))\n  thus \"\\<exists>n<card X. f (card X - Suc n) = x\"\n    by (metis \\<open>x \\<in> X\\<close> add.commute assms(2) card_Diff_singleton card_Suc_Diff1 diff_less_Suc plus_1_eq_Suc)\nnext\n  fix n\n  let ?n1 = \"Suc n\"\n  let ?n2 = \"Suc ?n1\"\n  assume \"finite X\"\n  assume \"Suc (Suc n) < card X\"\n  have \"ord (f (card X - Suc ?n2)) (f (card X - Suc ?n1)) (f (card X - Suc n))\"\n    using assms(3) unfolding local_ordering_def\n    using \\<open>Suc (Suc n) < card X\\<close> by (metis\n      Suc_diff_Suc Suc_lessD card_eq_0_iff card_gt_0_iff diff_less gr_implies_not0 zero_less_Suc)\n  thus \" ord (f (card X - Suc n)) (f (card X - Suc ?n1)) (f (card X - Suc ?n2))\"\n    using ord_sym by blast\nqed\n\nlemma  zero_into_ordering_loc:\n  assumes \"local_ordering f betw X\"\n  and \"X \\<noteq> {}\"\n  shows \"(f 0) \\<in> X\"\n    using local_ordering_def by (metis assms card_eq_0_iff gr_implies_not0 linorder_neqE_nat)\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Schutz_Spacetime/TernaryOrdering.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.7799830683843368}}
{"text": "(*  Title:      HOL/Isar_Examples/Group.thy\n    Author:     Makarius\n*)\n\nsection \\<open>Basic group theory\\<close>\n\ntheory Group\n  imports MainRLT\nbegin\n\nsubsection \\<open>Groups and calculational reasoning\\<close> \n\ntext \\<open>\n  Groups over signature \\<open>(* :: \\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> \\<alpha>, 1 :: \\<alpha>, inverse :: \\<alpha> \\<Rightarrow> \\<alpha>)\\<close> are\n  defined as an axiomatic type class as follows. Note that the parent classes\n  \\<^class>\\<open>times\\<close>, \\<^class>\\<open>one\\<close>, \\<^class>\\<open>inverse\\<close> is provided by the basic HOL theory.\n\\<close>\n\nclass group = times + one + inverse +\n  assumes group_assoc: \"(x * y) * z = x * (y * z)\"\n    and group_left_one: \"1 * x = x\"\n    and group_left_inverse: \"inverse x * x = 1\"\n\ntext \\<open>\n  The group axioms only state the properties of left one and inverse, the\n  right versions may be derived as follows.\n\\<close>\n\ntheorem (in group) group_right_inverse: \"x * inverse x = 1\"\nproof -\n  have \"x * inverse x = 1 * (x * inverse x)\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1 * x * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x * x * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (inverse x * x) * inverse x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * 1 * inverse x\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = inverse (inverse x) * (1 * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = inverse (inverse x) * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = 1\"\n    by (simp only: group_left_inverse)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  With \\<open>group_right_inverse\\<close> already available, \\<open>group_right_one\\<close>\n  is now established much easier.\n\\<close>\n\ntheorem (in group) group_right_one: \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  \\<^medskip>\n  The calculational proof style above follows typical presentations given in\n  any introductory course on algebra. The basic technique is to form a\n  transitive chain of equations, which in turn are established by simplifying\n  with appropriate rules. The low-level logical details of equational\n  reasoning are left implicit.\n\n  Note that ``\\<open>\\<dots>\\<close>'' is just a special term variable that is bound\n  automatically to the argument\\<^footnote>\\<open>The argument of a curried infix expression\n  happens to be its right-hand side.\\<close> of the last fact achieved by any local\n  assumption or proven statement. In contrast to \\<open>?thesis\\<close>, the ``\\<open>\\<dots>\\<close>''\n  variable is bound \\<^emph>\\<open>after\\<close> the proof is finished.\n\n  There are only two separate Isar language elements for calculational proofs:\n  ``\\<^theory_text>\\<open>also\\<close>'' for initial or intermediate calculational steps, and\n  ``\\<^theory_text>\\<open>finally\\<close>'' for exhibiting the result of a calculation. These constructs\n  are not hardwired into Isabelle/Isar, but defined on top of the basic\n  Isar/VM interpreter. Expanding the \\<^theory_text>\\<open>also\\<close> and \\<^theory_text>\\<open>finally\\<close> derived language\n  elements, calculations may be simulated by hand as demonstrated below.\n\\<close>\n\ntheorem (in group) \"x * 1 = x\"\nproof -\n  have \"x * 1 = x * (inverse x * x)\"\n    by (simp only: group_left_inverse)\n\n  note calculation = this\n    \\<comment> \\<open>first calculational step: init calculation register\\<close>\n\n  have \"\\<dots> = x * inverse x * x\"\n    by (simp only: group_assoc)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = 1 * x\"\n    by (simp only: group_right_inverse)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>general calculational step: compose with transitivity rule\\<close>\n\n  have \"\\<dots> = x\"\n    by (simp only: group_left_one)\n\n  note calculation = trans [OF calculation this]\n    \\<comment> \\<open>final calculational step: compose with transitivity rule \\dots\\<close>\n  from calculation\n    \\<comment> \\<open>\\dots\\ and pick up the final result\\<close>\n\n  show ?thesis .\nqed\n\ntext \\<open>\n  Note that this scheme of calculations is not restricted to plain\n  transitivity. Rules like anti-symmetry, or even forward and backward\n  substitution work as well. For the actual implementation of \\<^theory_text>\\<open>also\\<close> and\n  \\<^theory_text>\\<open>finally\\<close>, Isabelle/Isar maintains separate context information of\n  ``transitivity'' rules. Rule selection takes place automatically by\n  higher-order unification.\n\\<close>\n\n\nsubsection \\<open>Groups as monoids\\<close>\n\ntext \\<open>\n  Monoids over signature \\<open>(* :: \\<alpha> \\<Rightarrow> \\<alpha> \\<Rightarrow> \\<alpha>, 1 :: \\<alpha>)\\<close> are defined like this.\n\\<close>\n\nclass monoid = times + one +\n  assumes monoid_assoc: \"(x * y) * z = x * (y * z)\"\n    and monoid_left_one: \"1 * x = x\"\n    and monoid_right_one: \"x * 1 = x\"\n\ntext \\<open>\n  Groups are \\<^emph>\\<open>not\\<close> yet monoids directly from the definition. For monoids,\n  \\<open>right_one\\<close> had to be included as an axiom, but for groups both \\<open>right_one\\<close>\n  and \\<open>right_inverse\\<close> are derivable from the other axioms. With\n  \\<open>group_right_one\\<close> derived as a theorem of group theory (see @{thm\n  group_right_one}), we may still instantiate \\<open>group \\<subseteq> monoid\\<close> properly as\n  follows.\n\\<close>\n\ninstance group \\<subseteq> monoid\n  by intro_classes\n    (rule group_assoc,\n      rule group_left_one,\n      rule group_right_one)\n\ntext \\<open>\n  The \\<^theory_text>\\<open>instance\\<close> command actually is a version of \\<^theory_text>\\<open>theorem\\<close>, setting up a\n  goal that reflects the intended class relation (or type constructor arity).\n  Thus any Isar proof language element may be involved to establish this\n  statement. When concluding the proof, the result is transformed into the\n  intended type signature extension behind the scenes.\n\\<close>\n\n\nsubsection \\<open>More theorems of group theory\\<close>\n\ntext \\<open>\n  The one element is already uniquely determined by preserving an \\<^emph>\\<open>arbitrary\\<close>\n  group element.\n\\<close>\n\ntheorem (in group) group_one_equality:\n  assumes eq: \"e * x = x\"\n  shows \"1 = e\"\nproof -\n  have \"1 = x * inverse x\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = (e * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = e * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = e * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = e\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Likewise, the inverse is already determined by the cancel property.\n\\<close>\n\ntheorem (in group) group_inverse_equality:\n  assumes eq: \"x' * x = 1\"\n  shows \"inverse x = x'\"\nproof -\n  have \"inverse x = 1 * inverse x\"\n    by (simp only: group_left_one)\n  also have \"\\<dots> = (x' * x) * inverse x\"\n    by (simp only: eq)\n  also have \"\\<dots> = x' * (x * inverse x)\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = x' * 1\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = x'\"\n    by (simp only: group_right_one)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The inverse operation has some further characteristic properties.\n\\<close>\n\ntheorem (in group) group_inverse_times: \"inverse (x * y) = inverse y * inverse x\"\nproof (rule group_inverse_equality)\n  show \"(inverse y * inverse x) * (x * y) = 1\"\n  proof -\n    have \"(inverse y * inverse x) * (x * y) =\n        (inverse y * (inverse x * x)) * y\"\n      by (simp only: group_assoc)\n    also have \"\\<dots> = (inverse y * 1) * y\"\n      by (simp only: group_left_inverse)\n    also have \"\\<dots> = inverse y * y\"\n      by (simp only: group_right_one)\n    also have \"\\<dots> = 1\"\n      by (simp only: group_left_inverse)\n    finally show ?thesis .\n  qed\nqed\n\ntheorem (in group) inverse_inverse: \"inverse (inverse x) = x\"\nproof (rule group_inverse_equality)\n  show \"x * inverse x = one\"\n    by (simp only: group_right_inverse)\nqed\n\ntheorem (in group) inverse_inject:\n  assumes eq: \"inverse x = inverse y\"\n  shows \"x = y\"\nproof -\n  have \"x = x * 1\"\n    by (simp only: group_right_one)\n  also have \"\\<dots> = x * (inverse y * y)\"\n    by (simp only: group_left_inverse)\n  also have \"\\<dots> = x * (inverse x * y)\"\n    by (simp only: eq)\n  also have \"\\<dots> = (x * inverse x) * y\"\n    by (simp only: group_assoc)\n  also have \"\\<dots> = 1 * y\"\n    by (simp only: group_right_inverse)\n  also have \"\\<dots> = y\"\n    by (simp only: group_left_one)\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Isar_Examples/Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8791467785920306, "lm_q1q2_score": 0.7799830500305901}}
{"text": "(*  Title:      HOL/Library/ContNonDenum.thy\n    Author:     Benjamin Porter, Monash University, NICTA, 2005\n    Author:     Johannes Hölzl, TU München\n*)\n\nsection {* Non-denumerability of the Continuum. *}\n\ntheory ContNotDenum\nimports Complex_Main Countable_Set\nbegin\n\nsubsection {* Abstract *}\n\ntext {* The following document presents a proof that the Continuum is\nuncountable. It is formalised in the Isabelle/Isar theorem proving\nsystem.\n\n{\\em Theorem:} The Continuum @{text \"\\<real>\"} is not denumerable. In other\nwords, there does not exist a function @{text \"f: \\<nat> \\<Rightarrow> \\<real>\"} such that f is\nsurjective.\n\n{\\em Outline:} An elegant informal proof of this result uses Cantor's\nDiagonalisation argument. The proof presented here is not this\none. First we formalise some properties of closed intervals, then we\nprove the Nested Interval Property. This property relies on the\ncompleteness of the Real numbers and is the foundation for our\nargument. Informally it states that an intersection of countable\nclosed intervals (where each successive interval is a subset of the\nlast) is non-empty. We then assume a surjective function @{text\n\"f: \\<nat> \\<Rightarrow> \\<real>\"} exists and find a real x such that x is not in the range of f\nby generating a sequence of closed intervals then using the NIP. *}\n\ntheorem real_non_denum: \"\\<not> (\\<exists>f :: nat \\<Rightarrow> real. surj f)\"\nproof\n  assume \"\\<exists>f::nat \\<Rightarrow> real. surj f\"\n  then obtain f :: \"nat \\<Rightarrow> real\" where \"surj f\" ..\n\n  txt {* First we construct a sequence of nested intervals, ignoring @{term \"range f\"}. *}\n\n  have \"\\<forall>a b c::real. a < b \\<longrightarrow> (\\<exists>ka kb. ka < kb \\<and> {ka..kb} \\<subseteq> {a..b} \\<and> c \\<notin> {ka..kb})\"\n    using assms\n    by (auto simp add: not_le cong: conj_cong)\n       (metis dense le_less_linear less_linear less_trans order_refl)\n  then obtain i j where ij:\n    \"\\<And>a b c::real. a < b \\<Longrightarrow> i a b c < j a b c\"\n    \"\\<And>a b c. a < b \\<Longrightarrow> {i a b c .. j a b c} \\<subseteq> {a .. b}\"\n    \"\\<And>a b c. a < b \\<Longrightarrow> c \\<notin> {i a b c .. j a b c}\"\n    by metis\n\n  def ivl \\<equiv> \"rec_nat (f 0 + 1, f 0 + 2) (\\<lambda>n x. (i (fst x) (snd x) (f n), j (fst x) (snd x) (f n)))\"\n  def I \\<equiv> \"\\<lambda>n. {fst (ivl n) .. snd (ivl n)}\"\n\n  have ivl[simp]:\n    \"ivl 0 = (f 0 + 1, f 0 + 2)\"\n    \"\\<And>n. ivl (Suc n) = (i (fst (ivl n)) (snd (ivl n)) (f n), j (fst (ivl n)) (snd (ivl n)) (f n))\"\n    unfolding ivl_def by simp_all\n\n  txt {* This is a decreasing sequence of non-empty intervals. *}\n\n  { fix n have \"fst (ivl n) < snd (ivl n)\"\n      by (induct n) (auto intro!: ij) }\n  note less = this\n\n  have \"decseq I\"\n    unfolding I_def decseq_Suc_iff ivl fst_conv snd_conv by (intro ij allI less)\n\n  txt {* Now we apply the finite intersection property of compact sets. *}\n\n  have \"I 0 \\<inter> (\\<Inter>i. I i) \\<noteq> {}\"\n  proof (rule compact_imp_fip_image)\n    fix S :: \"nat set\" assume fin: \"finite S\"\n    have \"{} \\<subset> I (Max (insert 0 S))\"\n      unfolding I_def using less[of \"Max (insert 0 S)\"] by auto\n    also have \"I (Max (insert 0 S)) \\<subseteq> (\\<Inter>i\\<in>insert 0 S. I i)\"\n      using fin decseqD[OF `decseq I`, of _ \"Max (insert 0 S)\"] by (auto simp: Max_ge_iff)\n    also have \"(\\<Inter>i\\<in>insert 0 S. I i) = I 0 \\<inter> (\\<Inter>i\\<in>S. I i)\"\n      by auto\n    finally show \"I 0 \\<inter> (\\<Inter>i\\<in>S. I i) \\<noteq> {}\"\n      by auto\n  qed (auto simp: I_def)\n  then obtain x where \"\\<And>n. x \\<in> I n\"\n    by blast\n  moreover from `surj f` obtain j where \"x = f j\"\n    by blast\n  ultimately have \"f j \\<in> I (Suc j)\"\n    by blast\n  with ij(3)[OF less] show False\n    unfolding I_def ivl fst_conv snd_conv by auto\nqed\n\nlemma uncountable_UNIV_real: \"uncountable (UNIV::real set)\"\n  using real_non_denum unfolding uncountable_def by auto\n\nlemma bij_betw_open_intervals:\n  fixes a b c d :: real\n  assumes \"a < b\" \"c < d\"\n  shows \"\\<exists>f. bij_betw f {a<..<b} {c<..<d}\"\nproof -\n  def f \\<equiv> \"\\<lambda>a b c d x::real. (d - c)/(b - a) * (x - a) + c\"\n  { fix a b c d x :: real assume *: \"a < b\" \"c < d\" \"a < x\" \"x < b\"\n    moreover from * have \"(d - c) * (x - a) < (d - c) * (b - a)\"\n      by (intro mult_strict_left_mono) simp_all\n    moreover from * have \"0 < (d - c) * (x - a) / (b - a)\"\n      by simp\n    ultimately have \"f a b c d x < d\" \"c < f a b c d x\"\n      by (simp_all add: f_def field_simps) }\n  with assms have \"bij_betw (f a b c d) {a<..<b} {c<..<d}\"\n    by (intro bij_betw_byWitness[where f'=\"f c d a b\"]) (auto simp: f_def)\n  thus ?thesis by auto\nqed\n\nlemma bij_betw_tan: \"bij_betw tan {-pi/2<..<pi/2} UNIV\"\n  using arctan_ubound by (intro bij_betw_byWitness[where f'=arctan]) (auto simp: arctan_tan)\n\nlemma uncountable_open_interval:\n  fixes a b :: real assumes ab: \"a < b\"\n  shows \"uncountable {a<..<b}\"\nproof -\n  obtain f where \"bij_betw f {a <..< b} {-pi/2<..<pi/2}\"\n    using bij_betw_open_intervals[OF `a < b`, of \"-pi/2\" \"pi/2\"] by auto\n  then show ?thesis\n    by (metis bij_betw_tan uncountable_bij_betw uncountable_UNIV_real)\nqed\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/ContNotDenum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8633916222765627, "lm_q1q2_score": 0.7798966460236687}}
{"text": "theory Samplers\n  imports Main \"HOL-Library.Omega_Words_Fun\"\nbegin\n\nsection \\<open>Utility Lemmas\\<close>\n\ntext \\<open>\n  The following lemmas about strictly monotonic functions could go\n  to the standard library of Isabelle/HOL.\n\\<close>\n\ntext \\<open>\n  Strongly monotonic functions over the integers grow without bound.\n\\<close>\nlemma strict_mono_exceeds:\n  assumes f: \"strict_mono (f::nat \\<Rightarrow> nat)\"\n  shows \"\\<exists>k. n < f k\"\nproof (induct n)\n  from f have \"f 0 < f 1\" by (rule strict_monoD) simp\n  hence \"0 < f 1\" by simp\n  thus \"\\<exists>k. 0 < f k\" ..\nnext\n  fix n\n  assume \"\\<exists>k. n < f k\"\n  then obtain k where \"n < f k\" ..\n  hence \"Suc n \\<le> f k\" by simp\n  also from f have \"f k < f (Suc k)\" by (rule strict_monoD) simp\n  finally show \"\\<exists>k. Suc n < f k\" ..\nqed\n\ntext \\<open>\n  More precisely, any natural number \\<open>n \\<ge> f 0\\<close> lies in the interval\n  between \\<open>f k\\<close> and \\<open>f (Suc k)\\<close>, for some \\<open>k\\<close>.\n\\<close>\nlemma strict_mono_interval:\n  assumes f: \"strict_mono (f::nat \\<Rightarrow> nat)\" and n: \"f 0 \\<le> n\"\n  obtains k where \"f k \\<le> n\" and \"n < f (Suc k)\"\nproof -\n  from f[THEN strict_mono_exceeds] obtain m where m: \"n < f m\" ..\n  have \"m \\<noteq> 0\"\n  proof\n    assume \"m = 0\"\n    with m n show \"False\" by simp\n  qed\n  with m obtain m' where m': \"n < f (Suc m')\" by (auto simp: gr0_conv_Suc)\n  let ?k = \"LEAST k. n < f (Suc k)\"\n  from m' have 1: \"n < f (Suc ?k)\" by (rule LeastI)\n  have \"f ?k \\<le> n\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    hence k: \"n < f ?k\" by simp\n    show \"False\"\n    proof (cases \"?k\")\n      case 0 with k n show \"False\" by simp\n    next\n      case Suc with k show \"False\" by (auto dest: Least_le)\n    qed\n  qed\n  with 1 that show ?thesis by simp\nqed\n\nlemma strict_mono_comp:\n  assumes g: \"strict_mono (g::'a::order \\<Rightarrow> 'b::order)\"\n      and f: \"strict_mono (f::'b::order \\<Rightarrow> 'c::order)\"\n  shows \"strict_mono (f \\<circ> g)\"\n  using assms by (auto simp: strict_mono_def)\n\nsection \\<open>Stuttering Sampling Functions\\<close>\n\ntext \\<open>\n  Given an \\<open>\\<omega>\\<close>-sequence \\<open>\\<sigma>\\<close>, a stuttering sampling function \n  is a strictly monotonic function \\<open>f::nat \\<Rightarrow> nat\\<close> such that\n  \\<open>f 0 = 0\\<close> and for all \\<open>i\\<close> and all \\<open>f i \\<le> k < f (i+1)\\<close>,\n  the elements \\<open>\\<sigma> k\\<close> are the same. In other words, \\<open>f\\<close> skips some\n  (but not necessarily all) stuttering steps, but never skips a non-stuttering step.\n  Given such \\<open>\\<sigma>\\<close> and \\<open>f\\<close>, the (stuttering-)sampled\n  reduction of \\<open>\\<sigma>\\<close> is the sequence of elements of \\<open>\\<sigma>\\<close> at the\n  indices \\<open>f i\\<close>, which can simply be written as \\<open>\\<sigma> \\<circ> f\\<close>.\n\\<close>\n\n\nsubsection \\<open>Definition and elementary properties\\<close>\n\ndefinition stutter_sampler where\n  \\<comment> \\<open>f is a stuttering sampling function for @{text \"\\<sigma>\"}\\<close>\n  \"stutter_sampler (f::nat \\<Rightarrow> nat) \\<sigma> \\<equiv>\n     f 0 = 0\n   \\<and> strict_mono f\n   \\<and> (\\<forall>k n. f k < n \\<and> n < f (Suc k) \\<longrightarrow> \\<sigma> n = \\<sigma> (f k))\"\n\nlemma stutter_sampler_0: \"stutter_sampler f \\<sigma> \\<Longrightarrow> f 0 = 0\"\n  by (simp add: stutter_sampler_def)\n\nlemma stutter_sampler_mono: \"stutter_sampler f \\<sigma> \\<Longrightarrow> strict_mono f\"\n  by (simp add: stutter_sampler_def)\n\nlemma stutter_sampler_between:\n  assumes f: \"stutter_sampler f \\<sigma>\"\n      and lo: \"f k \\<le> n\" and hi: \"n < f (Suc k)\"\n    shows \"\\<sigma> n = \\<sigma> (f k)\"\n  using assms by (auto simp: stutter_sampler_def less_le)\n\nlemma stutter_sampler_interval:\n  assumes f: \"stutter_sampler f \\<sigma>\"\n  obtains k where \"f k \\<le> n\" and \"n < f (Suc k)\"\nusing f[THEN stutter_sampler_mono] proof (rule strict_mono_interval)\n  from f show \"f 0 \\<le> n\" by (simp add: stutter_sampler_0)\nqed\n\ntext \\<open>\n  The identity function is a stuttering sampling function for any \\<open>\\<sigma>\\<close>.\n\\<close>\nlemma id_stutter_sampler [iff]: \"stutter_sampler id \\<sigma>\"\n  by (auto simp: stutter_sampler_def strict_mono_def)\n\ntext \\<open>\n  Stuttering sampling functions compose, sort of.\n\\<close>\nlemma stutter_sampler_comp:\n  assumes f: \"stutter_sampler f \\<sigma>\"\n      and g: \"stutter_sampler g (\\<sigma> \\<circ> f)\"\n  shows \"stutter_sampler (f \\<circ> g) \\<sigma>\"\nproof (auto simp: stutter_sampler_def)\n  from f g show \"f (g 0) = 0\" by (simp add: stutter_sampler_0)\nnext\n  from g[THEN stutter_sampler_mono] f[THEN stutter_sampler_mono]\n  show \"strict_mono (f \\<circ> g)\" by (rule strict_mono_comp)\nnext\n  fix i k\n  assume lo: \"f (g i) < k\" and hi: \"k < f (g (Suc i))\"\n  from f obtain m where 1: \"f m \\<le> k\" and 2: \"k < f (Suc m)\"\n    by (rule stutter_sampler_interval)\n  with f have 3: \"\\<sigma> k = \\<sigma> (f m)\" by (rule stutter_sampler_between)\n  from lo 2 have \"f (g i) < f (Suc m)\" by simp\n  with f[THEN stutter_sampler_mono] have 4: \"g i \\<le> m\" by (simp add: strict_mono_less)\n  from 1 hi have \"f m < f (g (Suc i))\" by simp\n  with f[THEN stutter_sampler_mono] have 5: \"m < g (Suc i)\"by (simp add: strict_mono_less)\n  from g 4 5 have \"(\\<sigma> \\<circ> f) m = (\\<sigma> \\<circ> f) (g i)\" by (rule stutter_sampler_between)\n  with 3 show \"\\<sigma> k = \\<sigma> (f (g i))\" by simp\nqed\n\ntext \\<open>\n  Stuttering sampling functions can be extended to suffixes.\n\\<close>\nlemma stutter_sampler_suffix:\n  assumes f: \"stutter_sampler f \\<sigma>\"\n  shows \"stutter_sampler (\\<lambda>k. f (n+k) - f n) (suffix (f n) \\<sigma>)\"\nproof (auto simp: stutter_sampler_def strict_mono_def)\n  fix i j\n  assume ij: \"(i::nat) < j\"\n  from f have mono: \"strict_mono f\" by (rule stutter_sampler_mono)\n\n  from mono[THEN strict_mono_mono] have \"f n \\<le> f (n+i)\"\n    by (rule monoD) simp\n  moreover\n  from mono[THEN strict_mono_mono] have \"f n \\<le> f (n+j)\"\n    by (rule monoD) simp\n  moreover\n  from mono ij have \"f (n+i) < f (n+j)\" by (auto intro: strict_monoD)\n  ultimately\n  show \"f (n+i) - f n < f (n+j) - f n\" by simp\nnext\n  fix i k\n  assume lo: \"f (n+i) - f n < k\" and hi: \"k < f (Suc (n+i)) - f n\"\n  from lo have \"f (n+i) \\<le> f n + k\" by simp\n  moreover\n  from hi have \"f n + k < f (Suc (n + i))\" by simp\n  moreover\n  from f[THEN stutter_sampler_mono, THEN strict_mono_mono]\n  have \"f n \\<le> f (n+i)\" by (rule monoD) simp\n  ultimately show \"\\<sigma> (f n + k) = \\<sigma> (f n + (f (n+i) - f n))\" \n    by (auto dest: stutter_sampler_between[OF f])\nqed\n\n\nsubsection \\<open>Preservation of properties through stuttering sampling\\<close>\n\ntext \\<open>\n  Stuttering sampling preserves the initial element of the sequence, as well as\n  the presence and relative ordering of different elements.\n\\<close>\n\nlemma stutter_sampled_0:\n  assumes \"stutter_sampler f \\<sigma>\"\n  shows \"\\<sigma> (f 0) = \\<sigma> 0\"\n  using assms[THEN stutter_sampler_0] by simp\n\nlemma stutter_sampled_in_range:\n  assumes f: \"stutter_sampler f \\<sigma>\" and s: \"s \\<in> range \\<sigma>\"\n  shows \"s \\<in> range (\\<sigma> \\<circ> f)\"\nproof -\n  from s obtain n where n: \"\\<sigma> n = s\" by auto\n  from f obtain k where \"f k \\<le> n\" \"n < f (Suc k)\" by (rule stutter_sampler_interval)\n  with f have \"\\<sigma> n = \\<sigma> (f k)\" by (rule stutter_sampler_between)\n  with n show ?thesis by auto\nqed\n\nlemma stutter_sampled_range:\n  \"range (\\<sigma> \\<circ> f) = range \\<sigma>\" if \"stutter_sampler f \\<sigma>\"\n  using that stutter_sampled_in_range [of f \\<sigma>] by auto\n\nlemma stutter_sampled_precedence:\n  assumes f: \"stutter_sampler f \\<sigma>\" and ij: \"i \\<le> j\"\n  obtains k l where \"k \\<le> l\" \"\\<sigma> (f k) = \\<sigma> i\" \"\\<sigma> (f l) = \\<sigma> j\"\nproof -\n  from f obtain k where k: \"f k \\<le> i\" \"i < f (Suc k)\" by (rule stutter_sampler_interval)\n  with f have 1: \"\\<sigma> i = \\<sigma> (f k)\" by (rule stutter_sampler_between)\n  from f obtain l where l: \"f l \\<le> j\" \"j < f (Suc l)\" by (rule stutter_sampler_interval)\n  with f have 2: \"\\<sigma> j = \\<sigma> (f l)\" by (rule stutter_sampler_between)\n  from k l ij have \"f k < f (Suc l)\" by simp\n  with f[THEN stutter_sampler_mono] have \"k \\<le> l\" by (simp add: strict_mono_less)\n  with 1 2 that show ?thesis by simp\nqed\n\n\nsubsection \\<open>Maximal stuttering sampling\\<close>\n\ntext \\<open>\n  We define a particular sampling function that is maximal in the sense that it\n  eliminates all finite stuttering. If a sequence ends with infinite stuttering\n  then it behaves as the identity over the (maximal such) suffix.\n\\<close>\n\nfun max_stutter_sampler where\n  \"max_stutter_sampler \\<sigma> 0 = 0\"\n| \"max_stutter_sampler \\<sigma> (Suc n) =\n    (let prev = max_stutter_sampler \\<sigma> n\n     in  if (\\<forall>k > prev. \\<sigma> k = \\<sigma> prev)\n         then Suc prev\n         else (LEAST k. prev < k \\<and> \\<sigma> k \\<noteq> \\<sigma> prev))\"\n\ntext \\<open>\n  \\<open>max_stutter_sampler\\<close> is indeed a stuttering sampling function.\n\\<close>\nlemma max_stutter_sampler: \n  \"stutter_sampler (max_stutter_sampler \\<sigma>) \\<sigma>\" (is \"stutter_sampler ?ms _\")\nproof -\n  have \"?ms 0 = 0\" by simp\n  moreover\n  have \"\\<forall>n. ?ms n < ?ms (Suc n)\"\n  proof\n    fix n\n    show \"?ms n < ?ms (Suc n)\" (is \"?prev < ?next\")\n    proof (cases \"\\<forall>k > ?prev. \\<sigma> k = \\<sigma> ?prev\")\n      case True thus ?thesis by (simp add: Let_def)\n    next\n      case False\n      hence \"\\<exists>k. ?prev < k \\<and> \\<sigma> k \\<noteq> \\<sigma> ?prev\" by simp\n      from this[THEN LeastI_ex] \n      have \"?prev < (LEAST k. ?prev < k \\<and> \\<sigma> k \\<noteq> \\<sigma> ?prev)\" ..\n      with False show ?thesis by (simp add: Let_def)\n    qed\n  qed\n  hence \"strict_mono ?ms\"\n    unfolding strict_mono_def by (blast intro: lift_Suc_mono_less)\n  moreover\n  have \"\\<forall>n k. ?ms n < k \\<and> k < ?ms (Suc n) \\<longrightarrow> \\<sigma> k = \\<sigma> (?ms n)\"\n  proof (clarify)\n    fix n k\n    assume lo: \"?ms n < k\" (is \"?prev < k\")\n       and hi: \"k < ?ms (Suc n)\" (is \"k < ?next\")\n    show \"\\<sigma> k = \\<sigma> ?prev\"\n    proof (cases \"\\<forall>k > ?prev. \\<sigma> k = \\<sigma> ?prev\")\n      case True\n      hence \"?next = Suc ?prev\" by (simp add: Let_def)\n      with lo hi show ?thesis by simp  \\<comment> \\<open>no room for intermediate index\\<close>\n    next\n      case False\n      hence \"?next = (LEAST k. ?prev < k \\<and> \\<sigma> k \\<noteq> \\<sigma> ?prev)\"\n        by (auto simp add: Let_def)\n      with lo hi show ?thesis by (auto dest: not_less_Least)\n    qed\n  qed\n  ultimately show ?thesis unfolding stutter_sampler_def by blast\nqed\n\ntext \\<open>\n  We write \\<open>\\<natural>\\<sigma>\\<close> for the sequence \\<open>\\<sigma>\\<close> sampled by the\n  maximal stuttering sampler. Also, a sequence is \\emph{stutter free}\n  if it contains no finite stuttering: whenever two subsequent\n  elements are equal then all subsequent elements are the same.\n\\<close>\ndefinition stutter_reduced (\"\\<natural>_\" [100] 100) where\n  \"\\<natural>\\<sigma> = \\<sigma> \\<circ> (max_stutter_sampler \\<sigma>)\"\n\ndefinition stutter_free where\n  \"stutter_free \\<sigma> \\<equiv> \\<forall>k. \\<sigma> (Suc k) = \\<sigma> k \\<longrightarrow> (\\<forall>n>k. \\<sigma> n = \\<sigma> k)\"\n\nlemma stutter_freeI:\n  assumes \"\\<And>k n. \\<lbrakk>\\<sigma> (Suc k) = \\<sigma> k; n>k\\<rbrakk> \\<Longrightarrow> \\<sigma> n = \\<sigma> k\"\n  shows \"stutter_free \\<sigma>\"\n  using assms unfolding stutter_free_def by blast\n\nlemma stutter_freeD:\n  assumes \"stutter_free \\<sigma>\" and \"\\<sigma> (Suc k) = \\<sigma> k\" and \"n>k\"\n  shows \"\\<sigma> n = \\<sigma> k\"\n  using assms unfolding stutter_free_def by blast\n\ntext \\<open>\n  Any suffix of a stutter free sequence is itself stutter free.\n\\<close>\nlemma stutter_free_suffix: \n  assumes sigma: \"stutter_free \\<sigma>\"\n  shows \"stutter_free (suffix k \\<sigma>)\"\nproof (rule stutter_freeI)\n  fix j n\n  assume j: \"(suffix k \\<sigma>) (Suc j) = (suffix k \\<sigma>) j\" and n: \"j < n\"\n  from j have \"\\<sigma> (Suc (k+j)) = \\<sigma> (k+j)\" by simp\n  moreover from n have \"k+n > k+j\" by simp\n  ultimately have \"\\<sigma> (k+n) = \\<sigma> (k+j)\" by (rule stutter_freeD[OF sigma])\n  thus \"(suffix k \\<sigma>) n = (suffix k \\<sigma>) j\" by simp\nqed\n\nlemma stutter_reduced_0: \"(\\<natural>\\<sigma>) 0 = \\<sigma> 0\"\n  by (simp add: stutter_reduced_def stutter_sampled_0 max_stutter_sampler)\n\nlemma stutter_free_reduced:\n  assumes sigma: \"stutter_free \\<sigma>\"\n  shows \"\\<natural>\\<sigma> = \\<sigma>\"\nproof -\n  {\n    fix n\n    have \"max_stutter_sampler \\<sigma> n = n\" (is \"?ms n = n\")\n    proof (induct n)\n      show \"?ms 0 = 0\" by simp\n    next\n      fix n\n      assume ih: \"?ms n = n\"\n      show \"?ms (Suc n) = Suc n\"\n      proof (cases \"\\<sigma> (Suc n) = \\<sigma> (?ms n)\")\n        case True\n        with ih have \"\\<sigma> (Suc n) = \\<sigma> n\" by simp\n        with sigma have \"\\<forall>k > n. \\<sigma> k = \\<sigma> n\"\n          unfolding stutter_free_def by blast\n        with ih show ?thesis by (simp add: Let_def)\n      next\n        case False\n        with ih have \"(LEAST k. k>n \\<and> \\<sigma> k \\<noteq> \\<sigma> (?ms n)) = Suc n\"\n          by (auto intro: Least_equality)\n        with ih False show ?thesis by (simp add: Let_def)\n      qed\n    qed\n  }\n  thus ?thesis by (auto simp: stutter_reduced_def)\nqed\n\ntext \\<open>\n  Whenever two sequence elements at two consecutive sampling points of the \n  maximal stuttering sampler are equal then the sequence stutters infinitely \n  from the first sampling point onwards. In particular, \\<open>\\<natural>\\<sigma>\\<close> is\n  stutter free.\n\\<close>\nlemma max_stutter_sampler_nostuttering:\n  assumes stut: \"\\<sigma> (max_stutter_sampler \\<sigma> (Suc k)) = \\<sigma> (max_stutter_sampler \\<sigma> k)\"\n      and n: \"n > max_stutter_sampler \\<sigma> k\" (is \"_ > ?ms k\")\n  shows \"\\<sigma> n = \\<sigma> (?ms k)\"\nproof (rule ccontr)\n  assume contr: \"\\<not> ?thesis\"\n  with n have \"?ms k < n \\<and> \\<sigma> n \\<noteq> \\<sigma> (?ms k)\" (is \"?diff n\") ..\n  hence \"?diff (LEAST n. ?diff n)\" by (rule LeastI)\n  with contr have \"\\<sigma> (?ms (Suc k)) \\<noteq> \\<sigma> (?ms k)\" by (auto simp add: Let_def)\n  from this stut show \"False\" ..\nqed\n\nlemma stutter_reduced_stutter_free: \"stutter_free (\\<natural>\\<sigma>)\"\nproof (rule stutter_freeI)\n  fix k n\n  assume k: \"(\\<natural>\\<sigma>) (Suc k) = (\\<natural>\\<sigma>) k\" and n: \"k < n\"\n  from n have \"max_stutter_sampler \\<sigma> k < max_stutter_sampler \\<sigma> n\"\n    using max_stutter_sampler[THEN stutter_sampler_mono, THEN strict_monoD]\n    by blast\n  with k show \"(\\<natural>\\<sigma>) n = (\\<natural>\\<sigma>) k\"\n    unfolding stutter_reduced_def \n    by (auto elim: max_stutter_sampler_nostuttering \n             simp del: max_stutter_sampler.simps)\nqed\n\nlemma stutter_reduced_suffix: \"\\<natural> (suffix k (\\<natural>\\<sigma>)) = suffix k (\\<natural>\\<sigma>)\"\nproof (rule stutter_free_reduced)\n  have \"stutter_free (\\<natural>\\<sigma>)\" by (rule stutter_reduced_stutter_free)\n  thus \"stutter_free (suffix k (\\<natural>\\<sigma>))\" by (rule stutter_free_suffix)\nqed\n\nlemma stutter_reduced_reduced: \"\\<natural>\\<natural>\\<sigma> = \\<natural>\\<sigma>\"\n  by (insert stutter_reduced_suffix[of 0 \"\\<sigma>\", simplified])\n  \ntext \\<open>\n  One can define a partial order on sampling functions for a given sequence\n  \\<open>\\<sigma>\\<close> by saying that function \\<open>g\\<close> is better than function \\<open>f\\<close>\n  if the reduced sequence induced by \\<open>f\\<close> can be further reduced to obtain\n  the reduced sequence corresponding to \\<open>g\\<close>, i.e. if there exists a\n  stuttering sampling function \\<open>h\\<close> for the reduced sequence \\<open>\\<sigma> \\<circ> f\\<close>\n  such that \\<open>\\<sigma> \\<circ> f \\<circ> h = \\<sigma> \\<circ> g\\<close>. (Note that \\<open>f \\<circ> h\\<close> is indeed a stuttering\n  sampling function for \\<open>\\<sigma>\\<close>, by theorem \\<open>stutter_sampler_comp\\<close>.)\n\n  We do not formalize this notion but prove that \\<open>max_stutter_sampler \\<sigma>\\<close>\n  is the best sampling function according to this order.\n\\<close>\n\ntheorem sample_max_sample:\n  assumes f: \"stutter_sampler f \\<sigma>\"\n  shows \"\\<natural>(\\<sigma> \\<circ> f) = \\<natural>\\<sigma>\"\nproof -\n  let ?mss = \"max_stutter_sampler \\<sigma>\"\n  let ?mssf = \"max_stutter_sampler (\\<sigma> \\<circ> f)\"\n  from f have mssf: \"stutter_sampler (f \\<circ> ?mssf) \\<sigma>\"\n    by (blast intro: stutter_sampler_comp max_stutter_sampler)\n  txt \\<open>\n    The following is the core invariant of the proof: the sampling functions\n    \\<open>max_stutter_sampler \\<sigma>\\<close> and \\<open>f \\<circ> (max_stutter_sampler (\\<sigma> \\<circ> f))\\<close>\n    work in lock-step (i.e., sample the same points), except if \\<open>\\<sigma>\\<close> ends\n    in infinite stuttering, at which point function \\<open>f\\<close> may make larger\n    steps than the maximal sampling functions.\n\\<close>\n  {\n    fix k\n    have \"  ?mss k = f (?mssf k)\n          \\<or> ?mss k \\<le> f (?mssf k) \\<and> (\\<forall>n \\<ge> ?mss k. \\<sigma> (?mss k) = \\<sigma> n)\"\n          (is \"?P k\" is \"?A k \\<or> ?B k\")\n    proof (induct k)\n      from f mssf have \"?mss 0 = f (?mssf 0)\"\n        by (simp add: max_stutter_sampler stutter_sampler_0)\n      thus \"?P 0\" ..\n    next\n      fix k\n      assume ih: \"?P k\"\n      have b: \"?B k \\<longrightarrow> ?B (Suc k)\"\n      proof\n        assume 0: \"?B k\" hence 1: \"?mss k \\<le> f (?mssf k)\" ..\n        (* NB: For some reason \"... hence 1: ... and 2: ...\" cannot be proved *)\n        from 0 have 2: \"\\<forall>n \\<ge> ?mss k. \\<sigma> (?mss k) = \\<sigma> n\" ..\n        hence \"\\<forall>n > ?mss k. \\<sigma> (?mss k) = \\<sigma> n\" by auto\n        hence \"\\<forall>n > ?mss k. \\<sigma> n = \\<sigma> (?mss k)\" by auto\n        hence 3: \"?mss (Suc k) = Suc (?mss k)\" by (simp add: Let_def)\n        with 2 have \"\\<sigma> (?mss k) = \\<sigma> (?mss (Suc k))\"\n          by (auto simp del: max_stutter_sampler.simps)\n        from sym[OF this] 2 3 have \"\\<forall>n \\<ge> ?mss (Suc k). \\<sigma> (?mss (Suc k)) = \\<sigma> n\"\n          by (auto simp del: max_stutter_sampler.simps)\n        moreover\n        from mssf[THEN stutter_sampler_mono, THEN strict_monoD] \n        have \"f (?mssf k) < f (?mssf (Suc k))\"\n          by (simp del: max_stutter_sampler.simps)\n        with 1 3 have \"?mss (Suc k) \\<le> f (?mssf (Suc k))\"\n          by (simp del: max_stutter_sampler.simps)\n        ultimately show \"?B (Suc k)\" by blast\n      qed\n      from ih show \"?P (Suc k)\"\n      proof\n        assume a: \"?A k\"\n        show ?thesis\n        proof (cases \"\\<forall>n > ?mss k. \\<sigma> n = \\<sigma> (?mss k)\")\n          case True\n          hence \"\\<forall>n \\<ge> ?mss k. \\<sigma> (?mss k) = \\<sigma> n\" by (auto simp: le_less)\n          with a have \"?B k\" by simp\n          with b show ?thesis by (simp del: max_stutter_sampler.simps)\n        next\n          case False\n          hence diff: \"\\<sigma> (?mss (Suc k)) \\<noteq> \\<sigma> (?mss k)\"\n            by (blast dest: max_stutter_sampler_nostuttering)\n          have \"?A (Suc k)\"\n          proof (rule antisym)\n            show \"f (?mssf (Suc k)) \\<le> ?mss (Suc k)\"\n            proof (rule ccontr)\n              assume \"\\<not> ?thesis\"\n              hence contr: \"?mss (Suc k) < f (?mssf (Suc k))\" by simp\n              from mssf have \"\\<sigma> (?mss (Suc k)) = \\<sigma> ((f \\<circ> ?mssf) k)\"\n              proof (rule stutter_sampler_between)\n                from max_stutter_sampler[of \"\\<sigma>\", THEN stutter_sampler_mono]\n                have \"?mss k < ?mss (Suc k)\" by (rule strict_monoD) simp\n                with a show \"(f \\<circ> ?mssf) k \\<le> ?mss (Suc k)\"\n                  by (simp add: o_def del: max_stutter_sampler.simps)\n              next\n                from contr show \"?mss (Suc k) < (f \\<circ> ?mssf) (Suc k)\" by simp\n              qed\n              with a have \"\\<sigma> (?mss (Suc k)) = \\<sigma> (?mss k)\"\n                by (simp add: o_def del: max_stutter_sampler.simps)\n              with diff show \"False\" ..\n            qed\n          next\n            have \"\\<exists>m > ?mssf k. f m = ?mss (Suc k)\"\n            proof (rule ccontr)\n              assume \"\\<not> ?thesis\"\n              hence contr: \"\\<forall>i. f ((?mssf k) + Suc i) \\<noteq> ?mss (Suc k)\" by simp\n              {\n                fix i\n                have \"f (?mssf k + i) < ?mss (Suc k)\" (is \"?F i\")\n                proof (induct i)\n                  from a have \"f (?mssf k + 0) = ?mss k\" by (simp add: o_def)\n                  also from max_stutter_sampler[of \"\\<sigma>\", THEN stutter_sampler_mono] \n                       have \"... < ?mss (Suc k)\"\n                         by (rule strict_monoD) simp\n                  finally show \"?F 0\" .\n                next\n                  fix i\n                  assume ih: \"?F i\"\n                  show \"?F (Suc i)\"\n                  proof (rule ccontr)\n                    assume \"\\<not> ?thesis\"\n                    then have \"?mss (Suc k) \\<le> f (?mssf k + Suc i)\" \n                      by (simp add: o_def)\n                    moreover from contr have \"f (?mssf k + Suc i) \\<noteq> ?mss (Suc k)\"\n                      by blast\n                    ultimately have i: \"?mss (Suc k) < f (?mssf k + Suc i)\"\n                      by (simp add: less_le)\n                    from f have \"\\<sigma> (?mss (Suc k)) = \\<sigma> (f (?mssf k + i))\"\n                    proof (rule stutter_sampler_between)\n                      from ih show \"f (?mssf k + i) \\<le> ?mss (Suc k)\" \n                        by (simp add: o_def)\n                    next\n                      from i show \"?mss (Suc k) < f (Suc (?mssf k + i))\" \n                        by simp\n                    qed\n                    also from max_stutter_sampler have \"... = \\<sigma> (?mss k)\"\n                    proof (rule stutter_sampler_between)\n                      from f[THEN stutter_sampler_mono, THEN strict_mono_mono]\n                      have \"f (?mssf k) \\<le> f (?mssf k + i)\" by (rule monoD) simp\n                      with a show \"?mss k \\<le> f (?mssf k + i)\" by (simp add: o_def)\n                    qed (rule ih)\n                    also note diff\n                    finally show \"False\" by simp\n                  qed\n                qed\n              } note bounded = this\n              from f[THEN stutter_sampler_mono] \n              have \"strict_mono (\\<lambda>i. f (?mssf k + i))\" \n                by (auto simp: strict_mono_def)\n              then obtain i where i: \"?mss (Suc k) < f (?mssf k + i)\"\n                by (blast dest: strict_mono_exceeds)\n              from bounded have \"f (?mssf k + i) < ?mss (Suc k)\" .\n              with i show \"False\" by (simp del: max_stutter_sampler.simps)\n            qed\n            then obtain m where m: \"m > ?mssf k\" and m': \"f m = ?mss (Suc k)\"\n              by blast\n            show \"?mss (Suc k) \\<le> f (?mssf (Suc k))\"\n            proof (rule ccontr)\n              assume \"\\<not> ?thesis\"\n              hence contr: \"f (?mssf (Suc k)) < ?mss (Suc k)\" by simp\n              from mssf[THEN stutter_sampler_mono]\n              have \"(f \\<circ> ?mssf) k < (f \\<circ> ?mssf) (Suc k)\" \n                by (rule strict_monoD) simp\n              with a have \"?mss k \\<le> f (?mssf (Suc k))\"\n                by (simp add: o_def)\n              from this contr have \"\\<sigma> (f (?mssf (Suc k))) = \\<sigma> (?mss k)\"\n                by (rule stutter_sampler_between[OF max_stutter_sampler])\n              with a have stut: \"(\\<sigma> \\<circ> f) (?mssf (Suc k)) = (\\<sigma> \\<circ> f) (?mssf k)\"\n                by (simp add: o_def)\n              from this m have \"(\\<sigma> \\<circ> f) m = (\\<sigma> \\<circ> f) (?mssf k)\"\n                by (blast intro: max_stutter_sampler_nostuttering)\n              with diff m' a show \"False\"\n                by (simp add: o_def)\n            qed\n          qed\n          thus ?thesis ..\n        qed\n      next\n        assume \"?B k\" with b show ?thesis by (simp del: max_stutter_sampler.simps)\n      qed\n    qed\n  }\n  hence \"\\<natural>\\<sigma> = \\<natural>(\\<sigma> \\<circ> f)\" unfolding stutter_reduced_def by force\n  thus ?thesis by (rule sym)\nqed\n\n\nend  (* theory Samplers *)\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Stuttering_Equivalence/Samplers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8633915976709976, "lm_q1q2_score": 0.7798966237976044}}
{"text": "theory Induccion\nimports Main\nbegin\n\n(* HINT FOR ONLINE DEMO\n   Start your first proof attempt with\n   inversaIaux xs [] = rev xs\n   then generalize by introducing ys, and finally quantify over ys.\n   Each generalization should be motivated by the previous failed\n   proof attempt.\n*)\n\nsection {* Definiciones de la función inversa *}\n\ntext {* (inversa xs) es la inversa de xs. Por ejemplo,\n     inversa [a,b,c] = [c,b,a]\n*}\nfun inversa :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  \"inversa []     = []\"\n| \"inversa (x#xs) = inversa xs @ [x]\"\n\nvalue \"inversa [a,b,c]\"\nlemma \"inversa [a,b,c] = [c,b,a]\" by simp\n\ntext {* (inversaIaux xs) es la inversa de xs calculada de manera\n  iterativa. Por ejemplo, \n     inversaIaux [a,b,c] = [c,b,a]\n*}\nfun inversaIaux :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"inversaIaux [] ys     = ys\" \n| \"inversaIaux (x#xs) ys = inversaIaux xs (x#ys)\"\n\ndefinition inversaI :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  \"inversaI xs = inversaIaux xs []\"\n\nvalue \"inversaI [a,b,c]\"\nlemma \"inversaI [a,b,c] = [c,b,a]\" by (simp add: inversaI_def)\n\nsection {* Equivalencia de las definiciones de inversa *}\n\ntext {* El objetivo de esta sección es demostrar la equivalencia de las\n  dos definiciones; es decir,\n     equiv_inversa: \"inversaI xs = inversa xs\"\n  \n  A la vista de la definición de inversaI, se observa que la propiedad\n  anterior es un corolario de \n     equiv_inversa_aux: \"inversaIaux xs [] = inversa xs\"\n\n  Vamos a demostrar equiv_inversa_aux usando heurísticas de inducción.  \n*}  \n\ntext {* 1\\<ordmasculine> intento de prueba de equiv_inversa_aux *}\nlemma equiv_inversa_aux_1:\n  \"inversaIaux xs [] = inversa xs\"\napply (induction xs)  \napply auto\noops\n\ntext {* Se observa que se queda sin demostrar el objetivo \n     inversaIaux xs [] = inversa xs \\<Longrightarrow> \n     inversaIaux xs [a] = inversa xs @ [a]\n  \n  La causa es que el enunciado era demasiado específico al tener como\n  segundo argumento la lista vacía. Lo generalizamos a\n     equiv_inversa_aux_2: inversaIaux xs ys = inversa xs @ ys\n*}\n\ntext {* 2\\<ordmasculine> intento de prueba de equiv_inversa_aux *}\nlemma equiv_inversa_aux_2:\n  \"inversaIaux xs ys = inversa xs @ ys\"\napply (induction xs)  \napply auto\noops\n\ntext {* Se observa que se queda sin demostrar el objetivo \n     inversaIaux xs ys = inversa xs @ ys \\<Longrightarrow> \n     inversaIaux xs (a # ys) = inversa xs @ a # ys\n  \n  La causa es que aunque el segundo argumento es la variable ys, no se\n  ha tenido en cuenta que su valor varía. Por tanto, hay que declararla\n  como arbitraria.\n*}\n\ntext {* Prueba de equiv_inversa_aux *}\nlemma equiv_inversa_aux:\n  \"inversaIaux xs ys = inversa xs @ ys\"\napply (induction xs arbitrary: ys)  \napply auto\ndone\n\ntext {* Prueba de equiv_inversa *}\ncorollary equiv_inversa: \n  \"inversaI xs = inversa xs\"\napply (simp add: inversaI_def equiv_inversa_aux)\ndone\n\nend\n", "meta": {"author": "jaalonso", "repo": "AFV", "sha": "4605a58a1ad82f2255ac8bbe8d931942fd3d095c", "save_path": "github-repos/isabelle/jaalonso-AFV", "path": "github-repos/isabelle/jaalonso-AFV/AFV-4605a58a1ad82f2255ac8bbe8d931942fd3d095c/Temas/Ejemplos/Induccion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782737, "lm_q2_score": 0.8774767810736692, "lm_q1q2_score": 0.7798652156064596}}
{"text": "section \"N-Subsets\"\n\ntheory n_Subsets\n  imports\n    Common_Lemmas\n    \"HOL-Combinatorics.Multiset_Permutations\"\n    Filter_Bool_List\nbegin\n\nsubsection\"Definition\"\n\ndefinition n_subsets :: \"'a set \\<Rightarrow> nat \\<Rightarrow> 'a set set\" where\n  \"n_subsets A n = {B. B \\<subseteq> A \\<and> card B = n}\"\n\ntext \"Cardinality: \\<open>binomial (card A) n\\<close>\"\ntext \"Example: \\<open>n_subsets {0,1,2} 2 = {{0,1}, {0,2}, {1,2}}\\<close>\"\n\nsubsection\"Algorithm\"\n\nfun n_bool_lists :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool list list\" where\n  \"n_bool_lists n 0 = (if n > 0 then [] else [[]])\"\n| \"n_bool_lists n (Suc x) = (if n = 0 then [replicate (Suc x) False]\n    else if n = Suc x then [replicate (Suc x) True]\n    else if n > x then []\n    else [False#xs . xs \\<leftarrow> n_bool_lists n x] @ [True#xs . xs \\<leftarrow> n_bool_lists (n-1) x])\"\n\nfun n_subset_enum :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list list\" where\n  \"n_subset_enum xs n = [(filter_bool_list bs xs) . bs \\<leftarrow> (n_bool_lists n (length xs))]\"\n\nsubsection\"Verification\"\n                        \nsubsubsection\"n-bool-lists\"\n\nlemma n_bool_lists_True_count: \"xs \\<in> set (n_bool_lists n x) \\<Longrightarrow> count_list xs True = n\"\n by (induct x arbitrary: xs n) (auto split: if_splits simp: count_list_replicate)\n\nlemma n_bool_lists_length: \"xs \\<in> set (n_bool_lists n x) \\<Longrightarrow> length xs = x\"\n  by (induct x arbitrary: xs n) (auto split: if_splits)\n\nlemma n_bool_lists_distinct: \"distinct (n_bool_lists n x)\"\nproof(induct x arbitrary: n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc x)\n  then show ?case\n    using distinct_map by fastforce\nqed\n\nlemma replicate_True_not_False: \"count_list ys True = 0 \\<longleftrightarrow> ys = replicate (length ys) False\"\n  using count_list_zero_not_elem count_list_full_elem count_list_length_replicate by fastforce\n\nlemma n_bool_lists_correct_aux:\n  \"length xs = x \\<Longrightarrow> count_list xs True = n \\<Longrightarrow> xs \\<in> set (n_bool_lists n x)\"\nproof(induct x arbitrary: n xs)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc x)\n   show ?case proof(cases \"n = 0\")\n    case True\n    then show ?thesis\n      using Suc True replicate_True_not_False by auto\n  next\n    case c1: False\n    then show ?thesis proof(cases \"n = Suc x\")\n      case True\n      then have \"xs = True # replicate x True \"\n        using Suc.prems count_list_length_replicate replicate_Suc by metis\n      then show ?thesis\n        using True by simp\n    next\n      case c2: False\n      then show ?thesis proof(cases \"n > x\")\n        case True\n        then have \"xs = []\"\n          using Suc.prems c2 count_le_length by (metis Suc_lessI linorder_not_less)\n        then show ?thesis\n          using Suc by auto\n      next\n        case c3: False\n        then show ?thesis proof (cases xs)\n          case Nil\n          then show ?thesis\n            using Suc.prems(1) by auto \n        next\n          case (Cons y ys)\n          then show ?thesis proof (cases y)\n            case True\n            then show ?thesis using Suc c1 c2 c3 Cons\n              by simp \n          next\n            case False \n            then show ?thesis using Suc c1 c2 c3 Cons\n              by simp\n          qed \n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma n_bool_lists_correct: \"set (n_bool_lists n x) = {xs. length xs = x \\<and> count_list xs True = n}\"\nproof(standard)\n  show \"set (n_bool_lists n x) \\<subseteq> {xs. length xs = x \\<and> count_list xs True = n}\"\n  proof(cases x)\n    case 0\n    then show ?thesis by simp\n  next\n    case (Suc x)\n    then show ?thesis using n_bool_lists_True_count n_bool_lists_length\n      by blast\n  qed\nnext\n  show \"{xs. length xs = x \\<and> count_list xs True = n} \\<subseteq> set (n_bool_lists n x)\"\n    using n_bool_lists_correct_aux by auto\nqed\n\n\nsubsubsection\"Correctness\"\n\nlemma n_subset_enum_correct_aux1:\n  \"\\<lbrakk>distinct xs; length ys = length xs\\<rbrakk>\n    \\<Longrightarrow> set (filter_bool_list ys xs) \\<in> n_subsets (set xs) (count_list ys True)\"\n  unfolding n_subsets_def\n  by (auto simp: filter_bool_list_card filter_bool_list_elem)\n\nlemma n_subset_enum_correct_aux2:\n  \"distinct xs \\<Longrightarrow> n_subsets (set xs) n \\<subseteq> set (map set (n_subset_enum xs n))\"\n  unfolding n_subsets_def\n  by (auto simp: n_bool_lists_correct image_def filter_bool_list_exist_length_card_True)\n\ntheorem n_subset_enum_correct:\n  \"distinct xs \\<Longrightarrow> set (map set (n_subset_enum xs n)) = n_subsets (set xs) n\"\nproof(standard)\n  show \"distinct xs \\<Longrightarrow> set (map set (n_subset_enum xs n)) \\<subseteq> n_subsets (set xs) n\"\n    using n_subset_enum_correct_aux1 n_bool_lists_correct by auto\nnext\n  show \"distinct xs \\<Longrightarrow> n_subsets (set xs) n \\<subseteq> set (map set (n_subset_enum xs n))\"\n    using n_subset_enum_correct_aux2 by auto\nqed\n\nsubsubsection\"Distinctness\"\n\ntheorem n_subset_enum_distinct_elem:\n  \"distinct xs \\<Longrightarrow> ys \\<in> set (n_subset_enum xs n) \\<Longrightarrow> distinct ys\"\n  by(cases \"length xs < n\") (auto simp: filter_bool_list_distinct)\n\ntheorem n_subset_enum_distinct: \"distinct xs \\<Longrightarrow> distinct (n_subset_enum xs n)\"\n  by(auto simp: distinct_map n_bool_lists_distinct inj_on_def filter_bool_list_inj_aux n_bool_lists_length)\n\nsubsubsection\"Cardinality\"\n\ntext \\<open>Cardinality of @{term \"n_subsets\"} is already shown in @{thm [source] \"Binomial.n_subsets\"}.\\<close>\n\nsubsection \"Alternative using Multiset permutations\"\n\ntext \"It would be possible to define \\<open>n_bool_lists\\<close> using \\<open>permutations_of_multiset\\<close> with the\nfollowing definition:\"\n\nfun n_bool_lists2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool list set\" where\n  \"n_bool_lists2 n x = (if n > x then {}\n    else permutations_of_multiset (mset (replicate n True @ replicate (x-n) False)))\"\n\nsubsection\"\\<open>mset_count\\<close>\"\n\ntext\"Correspondence between \\<open>count_list\\<close> and \\<open>count (mset xs)\\<close> and transfer of a few results\nfor multisets to lists.\"\n\nlemma count_list_count_mset: \"count_list ys T = n \\<Longrightarrow> count (mset ys) T = n\"\n  by(induct ys arbitrary: n) auto\n\nlemma count_mset_count_list: \"count (mset ys) T = n \\<Longrightarrow> count_list ys T = n\"\n  by(induct ys arbitrary: n) auto\n\nlemma count_mset_replicate_aux1:\n  \"\\<lbrakk>\\<not> x < n; mset ys = mset (replicate n True) + mset (replicate (x - n) False)\\<rbrakk>\n    \\<Longrightarrow> count (mset ys) True = n\"\n  by (auto simp: count_list_count_mset count_mset)\n\nlemma  count_mset_replicate_aux2: \n  assumes \"\\<not> length xs < count_list xs True\"\n  shows \"mset xs = mset (replicate (count_list xs True) True) + mset (replicate (length xs - count_list xs True) False)\"\nproof -\n  have \"count_list xs B =\n         count_list (replicate (count_list xs True) True) B + count_list (replicate (length xs - count_list xs True) False) B\"\n    for B\n  proof(cases B)\n    case True\n    then show ?thesis\n      by (simp add: count_list_replicate)\n  next\n    case False\n\n    have \"count_list xs False = count_list (replicate (length xs - count_list xs True) False) False\"\n      by (metis count_list_True_False count_list_replicate diff_add_inverse)\n      \n    from this False show ?thesis\n      using assms by auto \n  qed\n\n  then have \"count (mset xs) B =\n         count (mset (replicate (count_list xs True) True) + mset (replicate (length xs - count_list xs True) False)) B\"\n    for B\n    by (metis count_mset_count_list count_union)\n  \n  then show \"mset xs = mset (replicate (count_list xs True) True) + mset (replicate (length xs - count_list xs True) False)\"\n    using multiset_eqI by blast\nqed\n\nlemma n_bool_lists2_correct: \"set (n_bool_lists n x) = n_bool_lists2 n x\"\nproof(standard)\n  have \"\\<lbrakk>\\<not> length ys < count_list ys True; x = length ys; n = count_list ys True\\<rbrakk>\n          \\<Longrightarrow> ys \\<in> permutations_of_multiset\n                     (mset (replicate (count_list ys True) True) + mset (replicate (length ys - count_list ys True) False))\"\n          for ys\n    using count_mset_replicate_aux2 permutations_of_multisetI by blast\n  \n  then show \"set (n_bool_lists n x) \\<subseteq> n_bool_lists2 n x\"\n    unfolding n_bool_lists_correct\n    by (auto simp: count_le_length leD)\nnext\n  have \"\\<lbrakk>\\<not> x < n; ys \\<in> permutations_of_multiset (mset (replicate n True) + mset (replicate (x - n) False))\\<rbrakk>\n          \\<Longrightarrow> count (mset ys) True = n \" for ys\n    using count_mset_replicate_aux1 permutations_of_multisetD by blast\n  then have \"\\<lbrakk>\\<not> x < n; ys \\<in> permutations_of_multiset (mset (replicate n True) + mset (replicate (x - n) False))\\<rbrakk>\n          \\<Longrightarrow>  count_list ys True = n \" for ys\n    by (simp add: count_list_count_mset) \n  then show \"n_bool_lists2 n x \\<subseteq> set (n_bool_lists n x)\" unfolding n_bool_lists_correct \n    by (auto simp: length_finite_permutations_of_multiset)\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Combinatorial_Enumeration_Algorithms/n_Subsets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7798652090117397}}
{"text": "(*<*)\ntheory IHOML_Examples\nimports IHOML\nbegin\nnitpick_params[user_axioms=true, show_all, expect=genuine, format = 3, atoms e = a b c d]\nsledgehammer_params[verbose=true]\n(*>*)\n\nsection \\<open>Textbook Examples\\<close>\n  \ntext\\<open>  In this section we provide further evidence that our embedded logic works as intended by proving the examples discussed in the book.\n In many cases, we consider further theorems which we derived from the original ones. We were able to confirm that all results\n (proofs or counterexamples) agree with Fitting's claims. \\<close>\n  \nsubsection \\<open>Modal Logic - Syntax and Semantics (Chapter 7)\\<close>\n\ntext\\<open> Reminder: We call a term \\emph{relativized} if it is of the form \\<open>\\<down>\\<alpha>\\<close>\n(i.e. an intensional term preceded by the \\emph{extension-of} operator), otherwise it is \\emph{non-relativized}.\nRelativized terms are non-rigid and non-relativized terms are rigid. \\<close>\n  \nsubsubsection \\<open>Considerations Regarding \\<open>\\<beta>\\<eta>\\<close>-redex  (p. 94)\\<close>\n\ntext\\<open>  \\<open>\\<beta>\\<eta>\\<close>-redex is valid for non-relativized (intensional or extensional) terms:  \\<close>\nlemma \"\\<lfloor>((\\<lambda>\\<alpha>. \\<phi> \\<alpha>)  (\\<tau>::\\<up>\\<zero>)) \\<^bold>\\<leftrightarrow> (\\<phi>  \\<tau>)\\<rfloor>\" by simp\nlemma \"\\<lfloor>((\\<lambda>\\<alpha>. \\<phi> \\<alpha>)  (\\<tau>::\\<zero>)) \\<^bold>\\<leftrightarrow> (\\<phi>  \\<tau>)\\<rfloor>\" by simp\nlemma \"\\<lfloor>((\\<lambda>\\<alpha>. \\<^bold>\\<box>\\<phi> \\<alpha>) (\\<tau>::\\<up>\\<zero>)) \\<^bold>\\<leftrightarrow> (\\<^bold>\\<box>\\<phi> \\<tau>)\\<rfloor>\" by simp\nlemma \"\\<lfloor>((\\<lambda>\\<alpha>. \\<^bold>\\<box>\\<phi> \\<alpha>) (\\<tau>::\\<zero>)) \\<^bold>\\<leftrightarrow> (\\<^bold>\\<box>\\<phi> \\<tau>)\\<rfloor>\" by simp    \ntext\\<open>  \\<open>\\<beta>\\<eta>\\<close>-redex is valid for relativized terms as long as no modal operators occur inside the predicate abstract:  \\<close>\nlemma \"\\<lfloor>((\\<lambda>\\<alpha>. \\<phi> \\<alpha>) \\<downharpoonleft>(\\<tau>::\\<up>\\<zero>)) \\<^bold>\\<leftrightarrow> (\\<phi> \\<downharpoonleft>\\<tau>)\\<rfloor>\" by simp\ntext\\<open>  \\<open>\\<beta>\\<eta>\\<close>-redex is non-valid for relativized terms when modal operators are present:  \\<close>\nlemma \"\\<lfloor>((\\<lambda>\\<alpha>. \\<^bold>\\<box>\\<phi> \\<alpha>) \\<downharpoonleft>(\\<tau>::\\<up>\\<zero>)) \\<^bold>\\<leftrightarrow> (\\<^bold>\\<box>\\<phi> \\<downharpoonleft>\\<tau>)\\<rfloor>\" nitpick oops   \\<comment> \\<open>countersatisfiable\\<close>\n\n\nsubsubsection \\<open>Equality Axioms (Subsection 1.1)\\<close>\n    \ntext\\<open>  Example 9.1:  \\<close>\nlemma \"\\<lfloor>((\\<lambda>X. \\<^bold>\\<box>(X \\<downharpoonleft>(p::\\<up>\\<zero>))) \\<^bold>\\<down>(\\<lambda>x. \\<^bold>\\<diamond>(\\<lambda>z. z \\<^bold>\\<approx> x) \\<downharpoonleft>p))\\<rfloor>\" \n  by auto \\<comment> \\<open>using normal equality\\<close>\nlemma \"\\<lfloor>((\\<lambda>X. \\<^bold>\\<box>(X \\<downharpoonleft>(p::\\<up>\\<zero>))) \\<^bold>\\<down>(\\<lambda>x. \\<^bold>\\<diamond>(\\<lambda>z. z \\<^bold>\\<approx>\\<^sup>L x) \\<downharpoonleft>p))\\<rfloor>\" \n  by auto \\<comment> \\<open>using Leibniz equality\\<close>\nlemma \"\\<lfloor>((\\<lambda>X. \\<^bold>\\<box>(X  (p::\\<up>\\<zero>))) \\<^bold>\\<down>(\\<lambda>x. \\<^bold>\\<diamond>(\\<lambda>z. z \\<^bold>\\<approx>\\<^sup>C x) p))\\<rfloor>\" \n  by simp  \\<comment> \\<open>using equality as defined for individual concepts\\<close>\n\n    \nsubsubsection \\<open>Extensionality (Subsection 1.2)\\<close>\n  \ntext\\<open>  In Fitting's book (p. 118), extensionality is assumed (globally) for extensional terms. While Fitting introduces \nthe following extensionality principles as axioms, they are already implicitly valid in Isabelle/HOL:  \\<close>    \n\n\ntext\\<open>  \\emph{De re} is equivalent to \\emph{de dicto} for non-relativized (extensional or intensional) terms:  \\<close>\nlemma \"\\<lfloor>\\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) (\\<tau>::\\<zero>))   \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<tau>)\\<rfloor>\" by simp\nlemma \"\\<lfloor>\\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) (\\<tau>::\\<up>\\<zero>))  \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<tau>)\\<rfloor>\" by simp\nlemma \"\\<lfloor>\\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) (\\<tau>::\\<langle>\\<zero>\\<rangle>))  \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<tau>)\\<rfloor>\" by simp\nlemma \"\\<lfloor>\\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>)) \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<tau>)\\<rfloor>\" by simp\n\ntext\\<open>  \\emph{De re} is not equivalent to \\emph{de dicto} for relativized terms:  \\<close>    \nlemma \"\\<lfloor>\\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<downharpoonleft>(\\<tau>::\\<up>\\<zero>)) \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>( (\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>)\\<rfloor>\" \n  nitpick[card 't=2, card i=2] oops \\<comment> \\<open>countersatisfiable\\<close>\nlemma \"\\<lfloor>\\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<^bold>\\<down>(\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>)) \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>( (\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>)\\<rfloor>\" \n  nitpick[card 't=1, card i=2] oops \\<comment> \\<open>countersatisfiable\\<close>\n  \ntext\\<open>  Proposition 9.6 - If we can prove one side of the equivalence, then we can prove the other (p. 120):  \\<close>\nabbreviation deDictoImplDeRe::\"\\<up>\\<zero>\\<Rightarrow>io\" \n  where \"deDictoImplDeRe \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>) \\<^bold>\\<rightarrow> ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>)\"\nabbreviation deReImplDeDicto::\"\\<up>\\<zero>\\<Rightarrow>io\" \n  where \"deReImplDeDicto \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>) \\<^bold>\\<rightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>)\"\nabbreviation deReEquDeDicto::\"\\<up>\\<zero>\\<Rightarrow>io\" \n  where \"deReEquDeDicto \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>) \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<downharpoonleft>\\<tau>)\"\ntext\\<open> \\bigbreak \\<close>\nabbreviation deDictoImplDeRe_pred::\"('t\\<Rightarrow>io)\\<Rightarrow>io\" \n  where \"deDictoImplDeRe_pred \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>) \\<^bold>\\<rightarrow> ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>)\"\nabbreviation deReImplDeDicto_pred::\"('t\\<Rightarrow>io)\\<Rightarrow>io\" \n  where \"deReImplDeDicto_pred \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>) \\<^bold>\\<rightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>)\"\nabbreviation deReEquDeDicto_pred::\"('t\\<Rightarrow>io)\\<Rightarrow>io\" \n  where \"deReEquDeDicto_pred \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. ((\\<lambda>\\<beta>. \\<^bold>\\<box>(\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>) \\<^bold>\\<leftrightarrow> \\<^bold>\\<box>((\\<lambda>\\<beta>. (\\<alpha> \\<beta>)) \\<^bold>\\<down>\\<tau>)\"\n\ntext\\<open>  We can prove local consequence: \\<close>\nlemma AimpB: \"\\<lfloor>deReImplDeDicto (\\<tau>::\\<up>\\<zero>) \\<^bold>\\<rightarrow> deDictoImplDeRe \\<tau>\\<rfloor>\"\n  by force \\<comment> \\<open>for individuals\\<close>\nlemma AimpB_p: \"\\<lfloor>deReImplDeDicto_pred (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>) \\<^bold>\\<rightarrow> deDictoImplDeRe_pred \\<tau>\\<rfloor>\"\n  by force \\<comment> \\<open>for predicates\\<close>\n\ntext\\<open>  And global consequence follows directly (since local consequence implies global consequence, as shown before): \\<close>\nlemma \"\\<lfloor>deReImplDeDicto (\\<tau>::\\<up>\\<zero>)\\<rfloor> \\<longrightarrow> \\<lfloor>deDictoImplDeRe \\<tau>\\<rfloor>\"\n  using AimpB by (rule localImpGlobalCons) \\<comment> \\<open>for individuals\\<close>\nlemma \"\\<lfloor>deReImplDeDicto_pred (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>)\\<rfloor> \\<longrightarrow> \\<lfloor>deDictoImplDeRe_pred \\<tau>\\<rfloor>\"\n  using AimpB_p by (rule localImpGlobalCons) \\<comment> \\<open>for predicates\\<close>\n       \n    \nsubsubsection \\<open>Rigidity (Subsection 3)\\<close>\n    \ntext\\<open>  (Local) rigidity for intensional individuals:  \\<close>    \nabbreviation rigidIndiv::\"\\<up>\\<langle>\\<up>\\<zero>\\<rangle>\" where\n  \"rigidIndiv \\<tau> \\<equiv> (\\<lambda>\\<beta>. \\<^bold>\\<box>((\\<lambda>z. \\<beta> \\<^bold>\\<approx> z) \\<downharpoonleft>\\<tau>)) \\<downharpoonleft>\\<tau>\"\ntext\\<open>  (Local) rigidity for intensional predicates:  \\<close>    \nabbreviation rigidPred::\"('t\\<Rightarrow>io)\\<Rightarrow>io\" where\n  \"rigidPred \\<tau> \\<equiv> (\\<lambda>\\<beta>. \\<^bold>\\<box>((\\<lambda>z. \\<beta> \\<^bold>\\<approx> z) \\<^bold>\\<down>\\<tau>)) \\<^bold>\\<down>\\<tau>\"\n  \ntext\\<open>  Proposition 9.8 - An intensional term is rigid if and only if the \\emph{de re/de dicto} distinction vanishes.\nNote that we can prove this theorem for local consequence (global consequence follows directly).  \\<close>  \nlemma \"\\<lfloor>rigidIndiv (\\<tau>::\\<up>\\<zero>) \\<^bold>\\<rightarrow> deReEquDeDicto \\<tau>\\<rfloor>\" by simp\nlemma \"\\<lfloor>deReImplDeDicto (\\<tau>::\\<up>\\<zero>) \\<^bold>\\<rightarrow> rigidIndiv \\<tau>\\<rfloor>\" by auto\nlemma \"\\<lfloor>rigidPred (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>) \\<^bold>\\<rightarrow> deReEquDeDicto_pred \\<tau>\\<rfloor>\" by simp\nlemma \"\\<lfloor>deReImplDeDicto_pred (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>) \\<^bold>\\<rightarrow> rigidPred \\<tau>\\<rfloor>\" by auto\n   \nsubsubsection \\<open>Stability Conditions (Subsection 4)\\<close>\n    \naxiomatization where\n S5: \"equivalence aRel\" \\<comment> \\<open>using Sahlqvist correspondence for improved performance\\<close>\n    \ntext\\<open>  Definition 9.10 - Stability conditions come in pairs:  \\<close>\nabbreviation stabilityA::\"('t\\<Rightarrow>io)\\<Rightarrow>io\" where \"stabilityA \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. (\\<tau> \\<alpha>) \\<^bold>\\<rightarrow> \\<^bold>\\<box>(\\<tau> \\<alpha>)\"\nabbreviation stabilityB::\"('t\\<Rightarrow>io)\\<Rightarrow>io\" where \"stabilityB \\<tau> \\<equiv> \\<^bold>\\<forall>\\<alpha>. \\<^bold>\\<diamond>(\\<tau> \\<alpha>) \\<^bold>\\<rightarrow> (\\<tau> \\<alpha>)\"\n\ntext\\<open>  Proposition 9.10 - In an \\emph{S5} modal logic both stability conditions are equivalent. \\<close>\ntext\\<open>  The last proposition holds for global consequence: \\<close>  \nlemma \"\\<lfloor>stabilityA (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>)\\<rfloor> \\<longrightarrow> \\<lfloor>stabilityB \\<tau>\\<rfloor>\" using S5 by blast    \nlemma \"\\<lfloor>stabilityB (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>)\\<rfloor> \\<longrightarrow> \\<lfloor>stabilityA \\<tau>\\<rfloor>\" using S5 by blast    \ntext\\<open>  But it does not hold for local consequence: \\<close>      \nlemma \"\\<lfloor>stabilityA (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>) \\<^bold>\\<rightarrow> stabilityB \\<tau>\\<rfloor>\" \n  nitpick[card 't=1, card i=2] oops \\<comment> \\<open>countersatisfiable\\<close>\nlemma \"\\<lfloor>stabilityB (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>) \\<^bold>\\<rightarrow> stabilityA \\<tau>\\<rfloor>\" \n  nitpick[card 't=1, card i=2] oops \\<comment> \\<open>countersatisfiable\\<close>\n    \ntext\\<open>  Theorem 9.11 - A term is rigid if and only if it satisfies the stability conditions. Note that\n we can prove this theorem for local consequence (global consequence follows directly).  \\<close>\ntheorem \"\\<lfloor>rigidPred (\\<tau>::\\<up>\\<langle>\\<zero>\\<rangle>) \\<^bold>\\<leftrightarrow> (stabilityA \\<tau> \\<^bold>\\<and> stabilityB \\<tau>)\\<rfloor>\" by meson   \ntheorem \"\\<lfloor>rigidPred (\\<tau>::\\<up>\\<langle>\\<up>\\<zero>\\<rangle>) \\<^bold>\\<leftrightarrow> (stabilityA \\<tau> \\<^bold>\\<and> stabilityB \\<tau>)\\<rfloor>\" by meson   \ntheorem \"\\<lfloor>rigidPred (\\<tau>::\\<up>\\<langle>\\<up>\\<langle>\\<zero>\\<rangle>\\<rangle>) \\<^bold>\\<leftrightarrow> (stabilityA \\<tau> \\<^bold>\\<and> stabilityB \\<tau>)\\<rfloor>\" by meson   \ntext\\<open>  \\pagebreak \\<close>\n(*<*)\nend\n(*>*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Types_Tableaus_and_Goedels_God/IHOML_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.7798652047402505}}
{"text": "theory Height\n  imports \"../Nominal\"\nbegin\n\ntext \\<open>\n  A small problem suggested by D. Wang. It shows how\n  the height of a lambda-terms behaves under substitution.\n\\<close>\n\natom_decl name\n\nnominal_datatype lam = \n    Var \"name\"\n  | App \"lam\" \"lam\"\n  | Lam \"\\<guillemotleft>name\\<guillemotright>lam\" (\"Lam [_]._\" [100,100] 100)\n\ntext \\<open>Definition of the height-function on lambda-terms.\\<close> \n\nnominal_primrec\n  height :: \"lam \\<Rightarrow> int\"\nwhere\n  \"height (Var x) = 1\"\n| \"height (App t1 t2) = (max (height t1) (height t2)) + 1\"\n| \"height (Lam [a].t) = (height t) + 1\"\n  apply(finite_guess add: perm_int_def)+\n  apply(rule TrueI)+\n  apply(simp add: fresh_int)\n  apply(fresh_guess add: perm_int_def)+\n  done\n\ntext \\<open>Definition of capture-avoiding substitution.\\<close>\n\nnominal_primrec\n  subst :: \"lam \\<Rightarrow> name \\<Rightarrow> lam \\<Rightarrow> lam\"  (\"_[_::=_]\" [100,100,100] 100)\nwhere\n  \"(Var x)[y::=t'] = (if x=y then t' else (Var x))\"\n| \"(App t1 t2)[y::=t'] = App (t1[y::=t']) (t2[y::=t'])\"\n| \"\\<lbrakk>x\\<sharp>y; x\\<sharp>t'\\<rbrakk> \\<Longrightarrow> (Lam [x].t)[y::=t'] = Lam [x].(t[y::=t'])\"\napply(finite_guess)+\napply(rule TrueI)+\napply(simp add: abs_fresh)\napply(fresh_guess)+\ndone\n\ntext\\<open>The next lemma is needed in the Var-case of the theorem below.\\<close>\n\nlemma height_ge_one: \n  shows \"1 \\<le> (height e)\"\nby (nominal_induct e rule: lam.strong_induct) (simp_all)\n\ntext \\<open>\n  Unlike the proplem suggested by Wang, however, the \n  theorem is here formulated entirely by using functions. \n\\<close>\n\ntheorem height_subst:\n  shows \"height (e[x::=e']) \\<le> ((height e) - 1) + (height e')\"\nproof (nominal_induct e avoiding: x e' rule: lam.strong_induct)\n  case (Var y)\n  have \"1 \\<le> height e'\" by (rule height_ge_one)\n  then show \"height (Var y[x::=e']) \\<le> height (Var y) - 1 + height e'\" by simp\nnext\n  case (Lam y e1)\n  hence ih: \"height (e1[x::=e']) \\<le> ((height e1) - 1) + (height e')\" by simp\n  moreover\n  have vc: \"y\\<sharp>x\" \"y\\<sharp>e'\" by fact+ (* usual variable convention *)\n  ultimately show \"height ((Lam [y].e1)[x::=e']) \\<le> height (Lam [y].e1) - 1 + height e'\" by simp\nnext    \n  case (App e1 e2)\n  hence ih1: \"height (e1[x::=e']) \\<le> ((height e1) - 1) + (height e')\" \n    and ih2: \"height (e2[x::=e']) \\<le> ((height e2) - 1) + (height e')\" by simp_all\n  then show \"height ((App e1 e2)[x::=e']) \\<le> height (App e1 e2) - 1 + height e'\"  by simp \nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Nominal/Examples/Height.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7798272118357251}}
{"text": "section \\<open>Graphs\\<close>\ntheory Graph\nimports Main\nbegin\ntext \\<open>\n  This theory defines a notion of graphs. A graph is a record that\n  contains a set of nodes \\<open>V\\<close> and a set of labeled edges \n  \\<open>E \\<subseteq> V\\<times>W\\<times>V\\<close>, where \\<open>W\\<close> are the edge labels.\n\\<close>\n\nsubsection \\<open>Definitions\\<close>\n  text \\<open>A graph is represented by a record.\\<close>\n  record ('v,'w) graph =\n    nodes :: \"'v set\"\n    edges :: \"('v \\<times> 'w \\<times> 'v) set\"\n\n  text \\<open>In a valid graph, edges only go from nodes to nodes.\\<close>\n  locale valid_graph = \n    fixes G :: \"('v,'w) graph\"\n    assumes E_valid: \"fst`edges G \\<subseteq> nodes G\"\n                     \"snd`snd`edges G \\<subseteq> nodes G\"\n  begin\n    abbreviation \"V \\<equiv> nodes G\"\n    abbreviation \"E \\<equiv> edges G\"\n\n    lemma E_validD: assumes \"(v,e,v')\\<in>E\"\n      shows \"v\\<in>V\" \"v'\\<in>V\"\n      apply -\n      apply (rule subsetD[OF E_valid(1)])\n      using assms apply force\n      apply (rule subsetD[OF E_valid(2)])\n      using assms apply force\n      done\n\n  end\n\n  subsection \\<open>Basic operations on Graphs\\<close>\n\n  text \\<open>The empty graph.\\<close>\n  definition empty where \n    \"empty \\<equiv> \\<lparr> nodes = {}, edges = {} \\<rparr>\"\n  text \\<open>Adds a node to a graph.\\<close>\n  definition add_node where \n    \"add_node v g \\<equiv> \\<lparr> nodes = insert v (nodes g), edges=edges g\\<rparr>\"\n  text \\<open>Deletes a node from a graph. Also deletes all adjacent edges.\\<close>\n  definition delete_node where \"delete_node v g \\<equiv> \\<lparr> \n    nodes = nodes g - {v},   \n    edges = edges g \\<inter> (-{v})\\<times>UNIV\\<times>(-{v})\n    \\<rparr>\"\n  text \\<open>Adds an edge to a graph.\\<close>\n  definition add_edge where \"add_edge v e v' g \\<equiv> \\<lparr>\n    nodes = {v,v'} \\<union> nodes g,\n    edges = insert (v,e,v') (edges g)\n    \\<rparr>\"\n  text \\<open>Deletes an edge from a graph.\\<close>\n  definition delete_edge where \"delete_edge v e v' g \\<equiv> \\<lparr>\n    nodes = nodes g, edges = edges g - {(v,e,v')} \\<rparr>\"\n  text \\<open>Successors of a node.\\<close>\n  definition succ :: \"('v,'w) graph \\<Rightarrow> 'v \\<Rightarrow> ('w\\<times>'v) set\"\n    where \"succ G v \\<equiv> {(w,v'). (v,w,v')\\<in>edges G}\"\n\n  text \\<open>Now follow some simplification lemmas.\\<close>\n  lemma empty_valid[simp]: \"valid_graph empty\"\n    unfolding empty_def by unfold_locales auto\n  lemma add_node_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (add_node v g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding add_node_def \n      by unfold_locales (auto dest: E_validD)\n  qed\n  lemma delete_node_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (delete_node v g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding delete_node_def \n      by unfold_locales (auto dest: E_validD)\n  qed\n  lemma add_edge_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (add_edge v e v' g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding add_edge_def\n      by unfold_locales (auto dest: E_validD)\n  qed\n  lemma delete_edge_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (delete_edge v e v' g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding delete_edge_def\n      by unfold_locales (auto dest: E_validD)\n  qed\n\n  lemma succ_finite[simp, intro]: \"finite (edges G) \\<Longrightarrow> finite (succ G v)\"\n    unfolding succ_def\n    by (rule finite_subset[where B=\"snd`edges G\"]) force+\n\n  lemma nodes_empty[simp]: \"nodes empty = {}\" unfolding empty_def by simp\n  lemma edges_empty[simp]: \"edges empty = {}\" unfolding empty_def by simp\n  lemma succ_empty[simp]: \"succ empty v = {}\" unfolding empty_def succ_def by auto\n\n  lemma nodes_add_node[simp]: \"nodes (add_node v g) = insert v (nodes g)\"\n    by (simp add: add_node_def)\n  lemma nodes_add_edge[simp]: \n    \"nodes (add_edge v e v' g) = insert v (insert v' (nodes g))\"\n    by (simp add: add_edge_def)\n  \n\n  lemma (in valid_graph) succ_subset: \"succ G v \\<subseteq> UNIV\\<times>V\"\n    unfolding succ_def using E_valid\n    by (force)\n\nsubsection \\<open>Paths\\<close>\n  text \\<open>A path is represented by a list of adjacent edges.\\<close>\n  type_synonym ('v,'w) path = \"('v\\<times>'w\\<times>'v) list\"\n\n  context valid_graph\n  begin\n    text \\<open>The following predicate describes a valid path:\\<close>\n    fun is_path :: \"'v \\<Rightarrow> ('v,'w) path \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n      \"is_path v [] v' \\<longleftrightarrow> v=v' \\<and> v'\\<in>V\" |\n      \"is_path v ((v1,w,v2)#p) v' \\<longleftrightarrow> v=v1 \\<and> (v1,w,v2)\\<in>E \\<and> is_path v2 p v'\"\n  \n    lemma is_path_simps[simp, intro!]:\n      \"is_path v [] v \\<longleftrightarrow> v\\<in>V\"\n      \"is_path v [(v,w,v')] v' \\<longleftrightarrow> (v,w,v')\\<in>E\"\n      by (auto dest: E_validD)\n    \n    lemma is_path_memb[simp]:\n      \"is_path v p v' \\<Longrightarrow> v\\<in>V \\<and> v'\\<in>V\"\n      apply (induct p arbitrary: v) \n      apply (auto dest: E_validD)\n      done\n\n    lemma is_path_split:\n      \"is_path v (p1@p2) v' \\<longleftrightarrow> (\\<exists>u. is_path v p1 u \\<and> is_path u p2 v')\"\n      by (induct p1 arbitrary: v) auto\n\n    lemma is_path_split'[simp]: \n      \"is_path v (p1@(u,w,u')#p2) v' \n        \\<longleftrightarrow> is_path v p1 u \\<and> (u,w,u')\\<in>E \\<and> is_path u' p2 v'\"\n      by (auto simp add: is_path_split)\n  end\n\n  text \\<open>Set of intermediate vertices of a path. These are all vertices but\n    the last one. Note that, if the last vertex also occurs earlier on the path,\n    it is contained in \\<open>int_vertices\\<close>.\\<close>\n  definition int_vertices :: \"('v,'w) path \\<Rightarrow> 'v set\" where\n    \"int_vertices p \\<equiv> set (map fst p)\"\n\n  lemma int_vertices_simps[simp]:\n    \"int_vertices [] = {}\"\n    \"int_vertices (vv#p) = insert (fst vv) (int_vertices p)\"\n    \"int_vertices (p1@p2) = int_vertices p1 \\<union> int_vertices p2\"\n    by (auto simp add: int_vertices_def)\n  \n  lemma (in valid_graph) int_vertices_subset: \n    \"is_path v p v' \\<Longrightarrow> int_vertices p \\<subseteq> V\"\n    apply (induct p arbitrary: v)\n    apply (simp) \n    apply (force dest: E_validD)\n    done\n\n  lemma int_vertices_empty[simp]: \"int_vertices p = {} \\<longleftrightarrow> p=[]\"\n    by (cases p) auto\n\nsubsubsection \\<open>Splitting Paths\\<close>\n  text \\<open>Split a path at the point where it first leaves the set \\<open>W\\<close>:\\<close>\n  lemma (in valid_graph) path_split_set:\n    assumes \"is_path v p v'\" and \"v\\<in>W\" and \"v'\\<notin>W\"\n    obtains p1 p2 u w u' where\n    \"p=p1@(u,w,u')#p2\" and\n    \"int_vertices p1 \\<subseteq> W\" and \"u\\<in>W\" and \"u'\\<notin>W\"\n    using assms\n  proof (induct p arbitrary: v thesis)\n    case Nil thus ?case by auto\n  next\n    case (Cons vv p)\n    note [simp, intro!] = \\<open>v\\<in>W\\<close> \\<open>v'\\<notin>W\\<close>\n    from Cons.prems obtain w u' where \n      [simp]: \"vv=(v,w,u')\" and\n        REST: \"is_path u' p v'\"\n      by (cases vv) auto\n    \n    txt \\<open>Distinguish wether the second node \\<open>u'\\<close> of the path is \n      in \\<open>W\\<close>. If yes, the proposition follows by the \n      induction hypothesis, otherwise it is straightforward, as\n      the split takes place at the first edge of the path.\\<close>\n    {\n      assume A [simp, intro!]: \"u'\\<in>W\"\n      from Cons.hyps[OF _ REST] obtain p1 uu ww uu' p2 where\n        \"p=p1@(uu,ww,uu')#p2\" \"int_vertices p1 \\<subseteq> W\" \"uu \\<in> W\" \"uu' \\<notin> W\"\n        by blast\n      with Cons.prems(1)[of \"vv#p1\" uu ww uu' p2] have thesis by auto\n    } moreover {\n      assume \"u'\\<notin>W\"\n      with Cons.prems(1)[of \"[]\" v w u' p] have thesis by auto\n    } ultimately show thesis by blast\n  qed\n  \n  text \\<open>Split a path at the point where it first enters the set \\<open>W\\<close>:\\<close>\n  lemma (in valid_graph) path_split_set':\n    assumes \"is_path v p v'\" and \"v'\\<in>W\"\n    obtains p1 p2 u where\n    \"p=p1@p2\" and\n    \"is_path v p1 u\" and\n    \"is_path u p2 v'\" and\n    \"int_vertices p1 \\<subseteq> -W\" and \"u\\<in>W\"\n    using assms\n  proof (cases \"v\\<in>W\")\n    case True with that[of \"[]\" p] assms show ?thesis\n      by auto\n  next\n    case False with assms that show ?thesis\n    proof (induct p arbitrary: v thesis)\n      case Nil thus ?case by auto\n    next\n      case (Cons vv p)\n      note [simp, intro!] = \\<open>v'\\<in>W\\<close> \\<open>v\\<notin>W\\<close>\n      from Cons.prems obtain w u' where \n        [simp]: \"vv=(v,w,u')\" and [simp]: \"(v,w,u')\\<in>E\" and\n          REST: \"is_path u' p v'\"\n        by (cases vv) auto\n    \n      txt \\<open>Distinguish wether the second node \\<open>u'\\<close> of the path is \n        in \\<open>W\\<close>. If yes, the proposition is straightforward, otherwise,\n        it follows by the induction hypothesis.\n\\<close>\n      {\n        assume A [simp, intro!]: \"u'\\<in>W\"\n        from Cons.prems(3)[of \"[vv]\" p u'] REST have ?case by auto\n      } moreover {\n        assume [simp, intro!]: \"u'\\<notin>W\"\n        from Cons.hyps[OF REST] obtain p1 p2 u'' where\n          [simp]: \"p=p1@p2\" and \n            \"is_path u' p1 u''\" and \n            \"is_path u'' p2 v'\" and\n            \"int_vertices p1 \\<subseteq> -W\" and\n            \"u''\\<in>W\" by blast\n        with Cons.prems(3)[of \"vv#p1\"] have ?case by auto\n      } ultimately show ?case by blast\n    qed\n  qed\n\n  text \\<open>Split a path at the point where a given vertex is first visited:\\<close>\n  lemma (in valid_graph) path_split_vertex:\n    assumes \"is_path v p v'\" and \"u\\<in>int_vertices p\"\n    obtains p1 p2 where\n    \"p=p1@p2\" and\n    \"is_path v p1 u\" and\n    \"u \\<notin> int_vertices p1\"\n    using assms\n  proof (induct p arbitrary: v thesis)\n    case Nil thus ?case by auto\n  next\n    case (Cons vv p)\n    from Cons.prems obtain w u' where \n      [simp]: \"vv=(v,w,u')\" \"v\\<in>V\" \"(v,w,u')\\<in>E\" and\n        REST: \"is_path u' p v'\"\n      by (cases vv) auto\n    \n    {\n      assume \"u=v\"\n      with Cons.prems(1)[of \"[]\" \"vv#p\"] have thesis by auto\n    } moreover {\n      assume [simp]: \"u\\<noteq>v\"\n      with Cons.hyps(1)[OF _ REST] Cons.prems(3) obtain p1 p2 where\n        \"p=p1@p2\" \"is_path u' p1 u\" \"u\\<notin>int_vertices p1\"\n        by auto\n      with Cons.prems(1)[of \"vv#p1\" p2] have thesis\n        by auto\n    } ultimately show ?case by blast\n  qed\n\nsubsection \\<open>Weighted Graphs\\<close>\n  locale valid_mgraph = valid_graph G for G::\"('v,'w::monoid_add) graph\"\n\n  definition path_weight :: \"('v,'w::monoid_add) path \\<Rightarrow> 'w\"\n    where \"path_weight p \\<equiv> sum_list (map (fst \\<circ> snd) p)\"\n\n  (* \n    lemma path_weight_alt: \"path_weight p \\<equiv> sum_list (map (fst \\<circ> snd) p)\"\n    unfolding path_weight_def foldl_conv_fold\n    by (simp add: sum_list_foldl)\n  *)\n\n  lemma path_weight_split[simp]:\n    \"(path_weight (p1@p2)::'w::monoid_add) = path_weight p1 + path_weight p2\"\n    unfolding path_weight_def\n    by (auto)\n\n  lemma path_weight_empty[simp]: \"path_weight [] = 0\"\n    unfolding path_weight_def\n    by auto\n\n  lemma path_weight_cons[simp]:\n    \"(path_weight (e#p)::'w::monoid_add) = fst (snd e) + path_weight p\"\n    unfolding path_weight_def\n    by (auto)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Dijkstra_Shortest_Path/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642806, "lm_q2_score": 0.8740772482857833, "lm_q1q2_score": 0.7795117521273502}}
{"text": "(*  Author:     Amine Chaieb\n    Author:     Florian Haftmann\n    Author:     Lukas Bulwahn\n    Author:     Manuel Eberl\n*)\n\nsection \\<open>Stirling numbers of first and second kind\\<close>\n\ntheory Stirling\nimports Main\nbegin\n\nsubsection \\<open>Stirling numbers of the second kind\\<close>\n\nfun Stirling :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Stirling 0 0 = 1\"\n  | \"Stirling 0 (Suc k) = 0\"\n  | \"Stirling (Suc n) 0 = 0\"\n  | \"Stirling (Suc n) (Suc k) = Suc k * Stirling n (Suc k) + Stirling n k\"\n\nlemma Stirling_1 [simp]: \"Stirling (Suc n) (Suc 0) = 1\"\n  by (induct n) simp_all\n\nlemma Stirling_less [simp]: \"n < k \\<Longrightarrow> Stirling n k = 0\"\n  by (induct n k rule: Stirling.induct) simp_all\n\nlemma Stirling_same [simp]: \"Stirling n n = 1\"\n  by (induct n) simp_all\n\nlemma Stirling_2_2: \"Stirling (Suc (Suc n)) (Suc (Suc 0)) = 2 ^ Suc n - 1\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"Stirling (Suc (Suc (Suc n))) (Suc (Suc 0)) =\n      2 * Stirling (Suc (Suc n)) (Suc (Suc 0)) + Stirling (Suc (Suc n)) (Suc 0)\"\n    by simp\n  also have \"\\<dots> = 2 * (2 ^ Suc n - 1) + 1\"\n    by (simp only: Suc Stirling_1)\n  also have \"\\<dots> = 2 ^ Suc (Suc n) - 1\"\n  proof -\n    have \"(2::nat) ^ Suc n - 1 > 0\"\n      by (induct n) simp_all\n    then have \"2 * ((2::nat) ^ Suc n - 1) > 0\"\n      by simp\n    then have \"2 \\<le> 2 * ((2::nat) ^ Suc n)\"\n      by simp\n    with add_diff_assoc2 [of 2 \"2 * 2 ^ Suc n\" 1]\n    have \"2 * 2 ^ Suc n - 2 + (1::nat) = 2 * 2 ^ Suc n + 1 - 2\" .\n    then show ?thesis\n      by (simp add: nat_distrib)\n  qed\n  finally show ?case by simp\nqed\n\nlemma Stirling_2: \"Stirling (Suc n) (Suc (Suc 0)) = 2 ^ n - 1\"\n  using Stirling_2_2 by (cases n) simp_all\n\n\nsubsection \\<open>Stirling numbers of the first kind\\<close>\n\nfun stirling :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"stirling 0 0 = 1\"\n  | \"stirling 0 (Suc k) = 0\"\n  | \"stirling (Suc n) 0 = 0\"\n  | \"stirling (Suc n) (Suc k) = n * stirling n (Suc k) + stirling n k\"\n\nlemma stirling_0 [simp]: \"n > 0 \\<Longrightarrow> stirling n 0 = 0\"\n  by (cases n) simp_all\n\nlemma stirling_less [simp]: \"n < k \\<Longrightarrow> stirling n k = 0\"\n  by (induct n k rule: stirling.induct) simp_all\n\nlemma stirling_same [simp]: \"stirling n n = 1\"\n  by (induct n) simp_all\n\nlemma stirling_Suc_n_1: \"stirling (Suc n) (Suc 0) = fact n\"\n  by (induct n) auto\n\nlemma stirling_Suc_n_n: \"stirling (Suc n) n = Suc n choose 2\"\n  by (induct n) (auto simp add: numerals(2))\n\nlemma stirling_Suc_n_2:\n  assumes \"n \\<ge> Suc 0\"\n  shows \"stirling (Suc n) 2 = (\\<Sum>k=1..n. fact n div k)\"\n  using assms\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by (simp add: numerals(2))\n  next\n    case Suc\n    then have geq1: \"Suc 0 \\<le> n\"\n      by simp\n    have \"stirling (Suc (Suc n)) 2 = Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0)\"\n      by (simp only: stirling.simps(4)[of \"Suc n\"] numerals(2))\n    also have \"\\<dots> = Suc n * (\\<Sum>k=1..n. fact n div k) + fact n\"\n      using Suc.hyps[OF geq1]\n      by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)\n    also have \"\\<dots> = Suc n * (\\<Sum>k=1..n. fact n div k) + Suc n * fact n div Suc n\"\n      by (metis nat.distinct(1) nonzero_mult_div_cancel_left)\n    also have \"\\<dots> = (\\<Sum>k=1..n. fact (Suc n) div k) + fact (Suc n) div Suc n\"\n      by (simp add: sum_distrib_left div_mult_swap dvd_fact)\n    also have \"\\<dots> = (\\<Sum>k=1..Suc n. fact (Suc n) div k)\"\n      by simp\n    finally show ?thesis .\n  qed\nqed\n\nlemma of_nat_stirling_Suc_n_2:\n  assumes \"n \\<ge> Suc 0\"\n  shows \"(of_nat (stirling (Suc n) 2)::'a::field_char_0) = fact n * (\\<Sum>k=1..n. (1 / of_nat k))\"\n  using assms\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by (auto simp add: numerals(2))\n  next\n    case Suc\n    then have geq1: \"Suc 0 \\<le> n\"\n      by simp\n    have \"(of_nat (stirling (Suc (Suc n)) 2)::'a) =\n        of_nat (Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0))\"\n      by (simp only: stirling.simps(4)[of \"Suc n\"] numerals(2))\n    also have \"\\<dots> = of_nat (Suc n) * (fact n * (\\<Sum>k = 1..n. 1 / of_nat k)) + fact n\"\n      using Suc.hyps[OF geq1]\n      by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)\n    also have \"\\<dots> = fact (Suc n) * (\\<Sum>k = 1..n. 1 / of_nat k) + fact (Suc n) * (1 / of_nat (Suc n))\"\n      using of_nat_neq_0 by auto\n    also have \"\\<dots> = fact (Suc n) * (\\<Sum>k = 1..Suc n. 1 / of_nat k)\"\n      by (simp add: distrib_left)\n    finally show ?thesis .\n  qed\nqed\n\nlemma sum_stirling: \"(\\<Sum>k\\<le>n. stirling n k) = fact n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>k\\<le>Suc n. stirling (Suc n) k) = stirling (Suc n) 0 + (\\<Sum>k\\<le>n. stirling (Suc n) (Suc k))\"\n    by (simp only: sum.atMost_Suc_shift)\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. stirling (Suc n) (Suc k))\"\n    by simp\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. n * stirling n (Suc k) + stirling n k)\"\n    by simp\n  also have \"\\<dots> = n * (\\<Sum>k\\<le>n. stirling n (Suc k)) + (\\<Sum>k\\<le>n. stirling n k)\"\n    by (simp add: sum.distrib sum_distrib_left)\n  also have \"\\<dots> = n * fact n + fact n\"\n  proof -\n    have \"n * (\\<Sum>k\\<le>n. stirling n (Suc k)) = n * ((\\<Sum>k\\<le>Suc n. stirling n k) - stirling n 0)\"\n      by (metis add_diff_cancel_left' sum.atMost_Suc_shift)\n    also have \"\\<dots> = n * (\\<Sum>k\\<le>n. stirling n k)\"\n      by (cases n) simp_all\n    also have \"\\<dots> = n * fact n\"\n      using Suc.hyps by simp\n    finally have \"n * (\\<Sum>k\\<le>n. stirling n (Suc k)) = n * fact n\" .\n    moreover have \"(\\<Sum>k\\<le>n. stirling n k) = fact n\"\n      using Suc.hyps .\n    ultimately show ?thesis by simp\n  qed\n  also have \"\\<dots> = fact (Suc n)\" by simp\n  finally show ?case .\nqed\n\nlemma stirling_pochhammer:\n  \"(\\<Sum>k\\<le>n. of_nat (stirling n k) * x ^ k) = (pochhammer x n :: 'a::comm_semiring_1)\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"of_nat (n * stirling n 0) = (0 :: 'a)\" by (cases n) simp_all\n  then have \"(\\<Sum>k\\<le>Suc n. of_nat (stirling (Suc n) k) * x ^ k) =\n      (of_nat (n * stirling n 0) * x ^ 0 +\n      (\\<Sum>i\\<le>n. of_nat (n * stirling n (Suc i)) * (x ^ Suc i))) +\n      (\\<Sum>i\\<le>n. of_nat (stirling n i) * (x ^ Suc i))\"\n    by (subst sum.atMost_Suc_shift) (simp add: sum.distrib ring_distribs)\n  also have \"\\<dots> = pochhammer x (Suc n)\"\n    by (subst sum.atMost_Suc_shift [symmetric])\n      (simp add: algebra_simps sum.distrib sum_distrib_left pochhammer_Suc flip: Suc)\n  finally show ?case .\nqed\n\n\ntext \\<open>A row of the Stirling number triangle\\<close>\n\ndefinition stirling_row :: \"nat \\<Rightarrow> nat list\"\n  where \"stirling_row n = [stirling n k. k \\<leftarrow> [0..<Suc n]]\"\n\nlemma nth_stirling_row: \"k \\<le> n \\<Longrightarrow> stirling_row n ! k = stirling n k\"\n  by (simp add: stirling_row_def del: upt_Suc)\n\nlemma length_stirling_row [simp]: \"length (stirling_row n) = Suc n\"\n  by (simp add: stirling_row_def)\n\nlemma stirling_row_nonempty [simp]: \"stirling_row n \\<noteq> []\"\n  using length_stirling_row[of n] by (auto simp del: length_stirling_row)\n\n\nsubsubsection \\<open>Efficient code\\<close>\n\ntext \\<open>\n  Naively using the defining equations of the Stirling numbers of the first\n  kind to compute them leads to exponential run time due to repeated\n  computations. We can use memoisation to compute them row by row without\n  repeating computations, at the cost of computing a few unneeded values.\n\n  As a bonus, this is very efficient for applications where an entire row of\n  Stirling numbers is needed.\n\\<close>\n\ndefinition zip_with_prev :: \"('a \\<Rightarrow> 'a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'b list\"\n  where \"zip_with_prev f x xs = map2 f (x # xs) xs\"\n\nlemma zip_with_prev_altdef:\n  \"zip_with_prev f x xs =\n    (if xs = [] then [] else f x (hd xs) # [f (xs!i) (xs!(i+1)). i \\<leftarrow> [0..<length xs - 1]])\"\nproof (cases xs)\n  case Nil\n  then show ?thesis\n    by (simp add: zip_with_prev_def)\nnext\n  case (Cons y ys)\n  then have \"zip_with_prev f x xs = f x (hd xs) # zip_with_prev f y ys\"\n    by (simp add: zip_with_prev_def)\n  also have \"zip_with_prev f y ys = map (\\<lambda>i. f (xs ! i) (xs ! (i + 1))) [0..<length xs - 1]\"\n    unfolding Cons\n    by (induct ys arbitrary: y)\n      (simp_all add: zip_with_prev_def upt_conv_Cons flip: map_Suc_upt del: upt_Suc)\n  finally show ?thesis\n    using Cons by simp\nqed\n\n\nprimrec stirling_row_aux\n  where\n    \"stirling_row_aux n y [] = [1]\"\n  | \"stirling_row_aux n y (x#xs) = (y + n * x) # stirling_row_aux n x xs\"\n\nlemma stirling_row_aux_correct:\n  \"stirling_row_aux n y xs = zip_with_prev (\\<lambda>a b. a + n * b) y xs @ [1]\"\n  by (induct xs arbitrary: y) (simp_all add: zip_with_prev_def)\n\nlemma stirling_row_code [code]:\n  \"stirling_row 0 = [1]\"\n  \"stirling_row (Suc n) = stirling_row_aux n 0 (stirling_row n)\"\nproof goal_cases\n  case 1\n  show ?case by (simp add: stirling_row_def)\nnext\n  case 2\n  have \"stirling_row (Suc n) =\n    0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \\<leftarrow> [0..<n]] @ [1]\"\n  proof (rule nth_equalityI, goal_cases length nth)\n    case (nth i)\n    from nth have \"i \\<le> Suc n\"\n      by simp\n    then consider \"i = 0 \\<or> i = Suc n\" | \"i > 0\" \"i \\<le> n\"\n      by linarith\n    then show ?case\n    proof cases\n      case 1\n      then show ?thesis\n        by (auto simp: nth_stirling_row nth_append)\n    next\n      case 2\n      then show ?thesis\n        by (cases i) (simp_all add: nth_append nth_stirling_row)\n    qed\n  next\n    case length\n    then show ?case by simp\n  qed\n  also have \"0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \\<leftarrow> [0..<n]] @ [1] =\n      zip_with_prev (\\<lambda>a b. a + n * b) 0 (stirling_row n) @ [1]\"\n    by (cases n) (auto simp add: zip_with_prev_altdef stirling_row_def hd_map simp del: upt_Suc)\n  also have \"\\<dots> = stirling_row_aux n 0 (stirling_row n)\"\n    by (simp add: stirling_row_aux_correct)\n  finally show ?case .\nqed\n\nlemma stirling_code [code]:\n  \"stirling n k =\n    (if k = 0 then (if n = 0 then 1 else 0)\n     else if k > n then 0\n     else if k = n then 1\n     else stirling_row n ! k)\"\n  by (simp add: nth_stirling_row)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Combinatorics/Stirling.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8740772253241802, "lm_q1q2_score": 0.7795117291365732}}
{"text": "section \\<open>Contour integration\\<close>\ntheory Contour_Integration\n  imports \"HOL-Analysis.Analysis\"\nbegin\n\nlemma lhopital_complex_simple:\n  assumes \"(f has_field_derivative f') (at z)\"\n  assumes \"(g has_field_derivative g') (at z)\"\n  assumes \"f z = 0\" \"g z = 0\" \"g' \\<noteq> 0\" \"f' / g' = c\"\n  shows   \"((\\<lambda>w. f w / g w) \\<longlongrightarrow> c) (at z)\"\nproof -\n  have \"eventually (\\<lambda>w. w \\<noteq> z) (at z)\"\n    by (auto simp: eventually_at_filter)\n  hence \"eventually (\\<lambda>w. ((f w - f z) / (w - z)) / ((g w - g z) / (w - z)) = f w / g w) (at z)\"\n    by eventually_elim (simp add: assms field_split_simps)\n  moreover have \"((\\<lambda>w. ((f w - f z) / (w - z)) / ((g w - g z) / (w - z))) \\<longlongrightarrow> f' / g') (at z)\"\n    by (intro tendsto_divide has_field_derivativeD assms)\n  ultimately have \"((\\<lambda>w. f w / g w) \\<longlongrightarrow> f' / g') (at z)\"\n    by (blast intro: Lim_transform_eventually)\n  with assms show ?thesis by simp\nqed\n\nsubsection\\<open>Definition\\<close>\n\ntext\\<open>\n  This definition is for complex numbers only, and does not generalise to\n  line integrals in a vector field\n\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> has_contour_integral :: \"(complex \\<Rightarrow> complex) \\<Rightarrow> complex \\<Rightarrow> (real \\<Rightarrow> complex) \\<Rightarrow> bool\"\n           (infixr \"has'_contour'_integral\" 50)\n  where \"(f has_contour_integral i) g \\<equiv>\n           ((\\<lambda>x. f(g x) * vector_derivative g (at x within {0..1}))\n            has_integral i) {0..1}\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> contour_integrable_on\n           (infixr \"contour'_integrable'_on\" 50)\n  where \"f contour_integrable_on g \\<equiv> \\<exists>i. (f has_contour_integral i) g\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> contour_integral\n  where \"contour_integral g f \\<equiv> SOME i. (f has_contour_integral i) g \\<or> \\<not> f contour_integrable_on g \\<and> i=0\"\n\nlemma not_integrable_contour_integral: \"\\<not> f contour_integrable_on g \\<Longrightarrow> contour_integral g f = 0\"\n  unfolding contour_integrable_on_def contour_integral_def by blast\n\nlemma contour_integral_unique: \"(f has_contour_integral i) g \\<Longrightarrow> contour_integral g f = i\"\n  apply (simp add: contour_integral_def has_contour_integral_def contour_integrable_on_def)\n  using has_integral_unique by blast\n\nlemma has_contour_integral_eqpath:\n     \"\\<lbrakk>(f has_contour_integral y) p; f contour_integrable_on \\<gamma>;\n       contour_integral p f = contour_integral \\<gamma> f\\<rbrakk>\n      \\<Longrightarrow> (f has_contour_integral y) \\<gamma>\"\nusing contour_integrable_on_def contour_integral_unique by auto\n\nlemma has_contour_integral_integral:\n    \"f contour_integrable_on i \\<Longrightarrow> (f has_contour_integral (contour_integral i f)) i\"\n  by (metis contour_integral_unique contour_integrable_on_def)\n\nlemma has_contour_integral_unique:\n    \"(f has_contour_integral i) g \\<Longrightarrow> (f has_contour_integral j) g \\<Longrightarrow> i = j\"\n  using has_integral_unique\n  by (auto simp: has_contour_integral_def)\n\nlemma has_contour_integral_integrable: \"(f has_contour_integral i) g \\<Longrightarrow> f contour_integrable_on g\"\n  using contour_integrable_on_def by blast\n\ntext\\<open>Show that we can forget about the localized derivative.\\<close>\n\nlemma has_integral_localized_vector_derivative:\n    \"((\\<lambda>x. f (g x) * vector_derivative p (at x within {a..b})) has_integral i) {a..b} \\<longleftrightarrow>\n     ((\\<lambda>x. f (g x) * vector_derivative p (at x)) has_integral i) {a..b}\"\nproof -\n  have *: \"{a..b} - {a,b} = interior {a..b}\"\n    by (simp add: atLeastAtMost_diff_ends)\n  show ?thesis\n    by (rule has_integral_spike_eq [of \"{a,b}\"]) (auto simp: at_within_interior [of _ \"{a..b}\"])\nqed\n\nlemma integrable_on_localized_vector_derivative:\n    \"(\\<lambda>x. f (g x) * vector_derivative p (at x within {a..b})) integrable_on {a..b} \\<longleftrightarrow>\n     (\\<lambda>x. f (g x) * vector_derivative p (at x)) integrable_on {a..b}\"\n  by (simp add: integrable_on_def has_integral_localized_vector_derivative)\n\nlemma has_contour_integral:\n     \"(f has_contour_integral i) g \\<longleftrightarrow>\n      ((\\<lambda>x. f (g x) * vector_derivative g (at x)) has_integral i) {0..1}\"\n  by (simp add: has_integral_localized_vector_derivative has_contour_integral_def)\n\nlemma contour_integrable_on:\n     \"f contour_integrable_on g \\<longleftrightarrow>\n      (\\<lambda>t. f(g t) * vector_derivative g (at t)) integrable_on {0..1}\"\n  by (simp add: has_contour_integral integrable_on_def contour_integrable_on_def)\n\nlemma has_contour_integral_mirror_iff:\n  assumes \"valid_path g\"\n  shows   \"(f has_contour_integral I) (-g) \\<longleftrightarrow> ((\\<lambda>x. -f (- x)) has_contour_integral I) g\"\nproof -\n  from assms have \"g piecewise_differentiable_on {0..1}\"\n    by (auto simp: valid_path_def piecewise_C1_imp_differentiable)\n  then obtain S where \"finite S\" and S: \"\\<And>x. x \\<in> {0..1} - S \\<Longrightarrow> g differentiable at x within {0..1}\"\n     unfolding piecewise_differentiable_on_def by blast\n  have S': \"g differentiable at x\" if \"x \\<in> {0..1} - ({0, 1} \\<union> S)\" for x\n  proof -\n    from that have \"x \\<in> interior {0..1}\" by auto\n    with S[of x] that show ?thesis by (auto simp: at_within_interior[of _ \"{0..1}\"])\n  qed\n\n  have \"(f has_contour_integral I) (-g) \\<longleftrightarrow>\n          ((\\<lambda>x. f (- g x) * vector_derivative (-g) (at x)) has_integral I) {0..1}\"\n    by (simp add: has_contour_integral)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. -f (- g x) * vector_derivative g (at x)) has_integral I) {0..1}\"\n    by (intro has_integral_spike_finite_eq[of \"S \\<union> {0, 1}\"])\n       (insert \\<open>finite S\\<close> S', auto simp: o_def fun_Compl_def)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. -f (-x)) has_contour_integral I) g\"\n    by (simp add: has_contour_integral)\n  finally show ?thesis .\nqed\n\nlemma contour_integral_on_mirror_iff:\n  assumes \"valid_path g\"\n  shows   \"f contour_integrable_on (-g) \\<longleftrightarrow> (\\<lambda>x. -f (- x)) contour_integrable_on g\"\n  by (auto simp: contour_integrable_on_def has_contour_integral_mirror_iff assms)\n\nlemma contour_integral_mirror:\n  assumes \"valid_path g\"\n  shows   \"contour_integral (-g) f = contour_integral g (\\<lambda>x. -f (- x))\"\nproof (cases \"f contour_integrable_on (-g)\")\n  case True with contour_integral_unique assms show ?thesis \n    by (auto simp: contour_integrable_on_def has_contour_integral_mirror_iff)\nnext\n  case False then show ?thesis\n    by (simp add: assms contour_integral_on_mirror_iff not_integrable_contour_integral)\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Reversing a path\\<close>\n\nlemma has_contour_integral_reversepath:\n  assumes \"valid_path g\" and f: \"(f has_contour_integral i) g\"\n    shows \"(f has_contour_integral (-i)) (reversepath g)\"\nproof -\n  { fix S x\n    assume xs: \"g C1_differentiable_on ({0..1} - S)\" \"x \\<notin> (-) 1 ` S\" \"0 \\<le> x\" \"x \\<le> 1\"\n    have \"vector_derivative (\\<lambda>x. g (1 - x)) (at x within {0..1}) =\n            - vector_derivative g (at (1 - x) within {0..1})\"\n    proof -\n      obtain f' where f': \"(g has_vector_derivative f') (at (1 - x))\"\n        using xs\n        by (force simp: has_vector_derivative_def C1_differentiable_on_def)\n      have \"(g \\<circ> (\\<lambda>x. 1 - x) has_vector_derivative -1 *\\<^sub>R f') (at x)\"\n        by (intro vector_diff_chain_within has_vector_derivative_at_within [OF f'] derivative_eq_intros | simp)+\n      then have mf': \"((\\<lambda>x. g (1 - x)) has_vector_derivative -f') (at x)\"\n        by (simp add: o_def)\n      show ?thesis\n        using xs\n        by (auto simp: vector_derivative_at_within_ivl [OF mf'] vector_derivative_at_within_ivl [OF f'])\n    qed\n  } note * = this\n  obtain S where S: \"continuous_on {0..1} g\" \"finite S\" \"g C1_differentiable_on {0..1} - S\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def)\n  have \"((\\<lambda>x. - (f (g (1 - x)) * vector_derivative g (at (1 - x) within {0..1}))) has_integral -i)\n       {0..1}\"\n    using has_integral_affinity01 [where m= \"-1\" and c=1, OF f [unfolded has_contour_integral_def]]\n    by (simp add: has_integral_neg)\n  then show ?thesis\n    using S\n    unfolding reversepath_def has_contour_integral_def\n    by (rule_tac S = \"(\\<lambda>x. 1 - x) ` S\" in has_integral_spike_finite) (auto simp: *)\nqed\n\nlemma contour_integrable_reversepath:\n    \"valid_path g \\<Longrightarrow> f contour_integrable_on g \\<Longrightarrow> f contour_integrable_on (reversepath g)\"\n  using has_contour_integral_reversepath contour_integrable_on_def by blast\n\nlemma contour_integrable_reversepath_eq:\n    \"valid_path g \\<Longrightarrow> (f contour_integrable_on (reversepath g) \\<longleftrightarrow> f contour_integrable_on g)\"\n  using contour_integrable_reversepath valid_path_reversepath by fastforce\n\nlemma contour_integral_reversepath:\n  assumes \"valid_path g\"\n    shows \"contour_integral (reversepath g) f = - (contour_integral g f)\"\nproof (cases \"f contour_integrable_on g\")\n  case True then show ?thesis\n    by (simp add: assms contour_integral_unique has_contour_integral_integral has_contour_integral_reversepath)\nnext\n  case False then have \"\\<not> f contour_integrable_on (reversepath g)\"\n    by (simp add: assms contour_integrable_reversepath_eq)\n  with False show ?thesis by (simp add: not_integrable_contour_integral)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Joining two paths together\\<close>\n\nlemma has_contour_integral_join:\n  assumes \"(f has_contour_integral i1) g1\" \"(f has_contour_integral i2) g2\"\n          \"valid_path g1\" \"valid_path g2\"\n    shows \"(f has_contour_integral (i1 + i2)) (g1 +++ g2)\"\nproof -\n  obtain s1 s2\n    where s1: \"finite s1\" \"\\<forall>x\\<in>{0..1} - s1. g1 differentiable at x\"\n      and s2: \"finite s2\" \"\\<forall>x\\<in>{0..1} - s2. g2 differentiable at x\"\n    using assms\n    by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have 1: \"((\\<lambda>x. f (g1 x) * vector_derivative g1 (at x)) has_integral i1) {0..1}\"\n   and 2: \"((\\<lambda>x. f (g2 x) * vector_derivative g2 (at x)) has_integral i2) {0..1}\"\n    using assms\n    by (auto simp: has_contour_integral)\n  have i1: \"((\\<lambda>x. (2*f (g1 (2*x))) * vector_derivative g1 (at (2*x))) has_integral i1) {0..1/2}\"\n   and i2: \"((\\<lambda>x. (2*f (g2 (2*x - 1))) * vector_derivative g2 (at (2*x - 1))) has_integral i2) {1/2..1}\"\n    using has_integral_affinity01 [OF 1, where m= 2 and c=0, THEN has_integral_cmul [where c=2]]\n          has_integral_affinity01 [OF 2, where m= 2 and c=\"-1\", THEN has_integral_cmul [where c=2]]\n    by (simp_all only: image_affinity_atLeastAtMost_div_diff, simp_all add: scaleR_conv_of_real mult_ac)\n  have g1: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at z) =\n            2 *\\<^sub>R vector_derivative g1 (at (z*2))\"\n      if \"0 \\<le> z\" \"z*2 < 1\" \"z*2 \\<notin> s1\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>z - 1/2\\<bar>\"\n      using that by auto\n    have \"((*) 2 has_vector_derivative 2) (at z)\"\n      by (simp add: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    moreover have \"(g1 has_vector_derivative vector_derivative g1 (at (z * 2))) (at (2 * z))\"\n      using s1 that by (auto simp: algebra_simps vector_derivative_works)\n    ultimately\n    show \"((\\<lambda>x. g1 (2 * x)) has_vector_derivative 2 *\\<^sub>R vector_derivative g1 (at (z * 2))) (at z)\"\n      by (intro vector_diff_chain_at [simplified o_def])\n  qed (use that in \\<open>simp_all add: dist_real_def abs_if split: if_split_asm\\<close>)\n\n  have g2: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at z) =\n            2 *\\<^sub>R vector_derivative g2 (at (z*2 - 1))\"\n           if \"1 < z*2\" \"z \\<le> 1\" \"z*2 - 1 \\<notin> s2\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>z - 1/2\\<bar>\"\n      using that by auto\n    have \"((\\<lambda>x. 2 * x - 1) has_vector_derivative 2) (at z)\"\n      by (simp add: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    moreover have \"(g2 has_vector_derivative vector_derivative g2 (at (z * 2 - 1))) (at (2 * z - 1))\"\n      using s2 that by (auto simp: algebra_simps vector_derivative_works)\n    ultimately\n    show \"((\\<lambda>x. g2 (2 * x - 1)) has_vector_derivative 2 *\\<^sub>R vector_derivative g2 (at (z * 2 - 1))) (at z)\"\n      by (intro vector_diff_chain_at [simplified o_def])\n  qed (use that in \\<open>simp_all add: dist_real_def abs_if split: if_split_asm\\<close>)\n\n  have \"((\\<lambda>x. f ((g1 +++ g2) x) * vector_derivative (g1 +++ g2) (at x)) has_integral i1) {0..1/2}\"\n  proof (rule has_integral_spike_finite [OF _ _ i1])\n    show \"finite (insert (1/2) ((*) 2 -` s1))\"\n      using s1 by (force intro: finite_vimageI [where h = \"(*)2\"] inj_onI)\n  qed (auto simp add: joinpaths_def scaleR_conv_of_real mult_ac g1)\n  moreover have \"((\\<lambda>x. f ((g1 +++ g2) x) * vector_derivative (g1 +++ g2) (at x)) has_integral i2) {1/2..1}\"\n  proof (rule has_integral_spike_finite [OF _ _ i2])\n    show \"finite (insert (1/2) ((\\<lambda>x. 2 * x - 1) -` s2))\"\n      using s2 by (force intro: finite_vimageI [where h = \"\\<lambda>x. 2*x-1\"] inj_onI)\n  qed (auto simp add: joinpaths_def scaleR_conv_of_real mult_ac g2)\n  ultimately\n  show ?thesis\n    by (simp add: has_contour_integral has_integral_combine [where c = \"1/2\"])\nqed\n\nlemma contour_integrable_joinI:\n  assumes \"f contour_integrable_on g1\" \"f contour_integrable_on g2\"\n          \"valid_path g1\" \"valid_path g2\"\n    shows \"f contour_integrable_on (g1 +++ g2)\"\n  using assms\n  by (meson has_contour_integral_join contour_integrable_on_def)\n\nlemma contour_integrable_joinD1:\n  assumes \"f contour_integrable_on (g1 +++ g2)\" \"valid_path g1\"\n    shows \"f contour_integrable_on g1\"\nproof -\n  obtain s1\n    where s1: \"finite s1\" \"\\<forall>x\\<in>{0..1} - s1. g1 differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have \"(\\<lambda>x. f ((g1 +++ g2) (x/2)) * vector_derivative (g1 +++ g2) (at (x/2))) integrable_on {0..1}\"\n    using assms integrable_affinity [of _ 0 \"1/2\" \"1/2\" 0] integrable_on_subcbox [where a=0 and b=\"1/2\"]\n    by (fastforce simp: contour_integrable_on)\n  then have *: \"(\\<lambda>x. (f ((g1 +++ g2) (x/2))/2) * vector_derivative (g1 +++ g2) (at (x/2))) integrable_on {0..1}\"\n    by (auto dest: integrable_cmul [where c=\"1/2\"] simp: scaleR_conv_of_real)\n  have g1: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at (z/2)) =\n            2 *\\<^sub>R vector_derivative g1 (at z)\"\n    if \"0 < z\" \"z < 1\" \"z \\<notin> s1\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>(z - 1)/2\\<bar>\"\n      using that by auto\n    have \\<section>: \"((\\<lambda>x. x * 2) has_vector_derivative 2) (at (z/2))\"\n      using s1 by (auto simp: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    have \"(g1 has_vector_derivative vector_derivative g1 (at z)) (at z)\"\n      using s1 that by (auto simp: vector_derivative_works)\n    then show \"((\\<lambda>x. g1 (2 * x)) has_vector_derivative 2 *\\<^sub>R vector_derivative g1 (at z)) (at (z/2))\"\n      using vector_diff_chain_at [OF \\<section>] by (auto simp: field_simps o_def)\n  qed (use that in \\<open>simp_all add: field_simps dist_real_def abs_if split: if_split_asm\\<close>)\n  have fin01: \"finite ({0, 1} \\<union> s1)\"\n    by (simp add: s1)\n  show ?thesis\n    unfolding contour_integrable_on\n    by (intro integrable_spike_finite [OF fin01 _ *]) (auto simp: joinpaths_def scaleR_conv_of_real g1)\nqed\n\nlemma contour_integrable_joinD2:\n  assumes \"f contour_integrable_on (g1 +++ g2)\" \"valid_path g2\"\n    shows \"f contour_integrable_on g2\"\nproof -\n  obtain s2\n    where s2: \"finite s2\" \"\\<forall>x\\<in>{0..1} - s2. g2 differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have \"(\\<lambda>x. f ((g1 +++ g2) (x/2 + 1/2)) * vector_derivative (g1 +++ g2) (at (x/2 + 1/2))) integrable_on {0..1}\"\n    using assms integrable_affinity [of _ \"1/2::real\" 1 \"1/2\" \"1/2\"]\n                integrable_on_subcbox [where a=\"1/2\" and b=1]\n    by (fastforce simp: contour_integrable_on image_affinity_atLeastAtMost_diff)\n  then have *: \"(\\<lambda>x. (f ((g1 +++ g2) (x/2 + 1/2))/2) * vector_derivative (g1 +++ g2) (at (x/2 + 1/2)))\n                integrable_on {0..1}\"\n    by (auto dest: integrable_cmul [where c=\"1/2\"] simp: scaleR_conv_of_real)\n  have g2: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at (z/2+1/2)) =\n            2 *\\<^sub>R vector_derivative g2 (at z)\"\n        if \"0 < z\" \"z < 1\" \"z \\<notin> s2\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>z/2\\<bar>\"\n      using that by auto\n    have \\<section>: \"((\\<lambda>x. x * 2 - 1) has_vector_derivative 2) (at ((1 + z)/2))\"\n      using s2 by (auto simp: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    have \"(g2 has_vector_derivative vector_derivative g2 (at z)) (at z)\"\n      using s2 that by (auto simp: vector_derivative_works)\n    then show \"((\\<lambda>x. g2 (2*x - 1)) has_vector_derivative 2 *\\<^sub>R vector_derivative g2 (at z)) (at (z/2 + 1/2))\"\n      using vector_diff_chain_at [OF \\<section>] by (auto simp: field_simps o_def)\n  qed (use that in \\<open>simp_all add: field_simps dist_real_def abs_if split: if_split_asm\\<close>)\n  have fin01: \"finite ({0, 1} \\<union> s2)\"\n    by (simp add: s2)\n  show ?thesis\n    unfolding contour_integrable_on\n    by (intro integrable_spike_finite [OF fin01 _ *]) (auto simp: joinpaths_def scaleR_conv_of_real g2)\nqed\n\nlemma contour_integrable_join [simp]:\n    \"\\<lbrakk>valid_path g1; valid_path g2\\<rbrakk>\n     \\<Longrightarrow> f contour_integrable_on (g1 +++ g2) \\<longleftrightarrow> f contour_integrable_on g1 \\<and> f contour_integrable_on g2\"\nusing contour_integrable_joinD1 contour_integrable_joinD2 contour_integrable_joinI by blast\n\nlemma contour_integral_join [simp]:\n    \"\\<lbrakk>f contour_integrable_on g1; f contour_integrable_on g2; valid_path g1; valid_path g2\\<rbrakk>\n        \\<Longrightarrow> contour_integral (g1 +++ g2) f = contour_integral g1 f + contour_integral g2 f\"\n  by (simp add: has_contour_integral_integral has_contour_integral_join contour_integral_unique)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Shifting the starting point of a (closed) path\\<close>\n\nlemma has_contour_integral_shiftpath:\n  assumes f: \"(f has_contour_integral i) g\" \"valid_path g\"\n      and a: \"a \\<in> {0..1}\"\n    shows \"(f has_contour_integral i) (shiftpath a g)\"\nproof -\n  obtain S\n    where S: \"finite S\" and g: \"\\<forall>x\\<in>{0..1} - S. g differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have *: \"((\\<lambda>x. f (g x) * vector_derivative g (at x)) has_integral i) {0..1}\"\n    using assms by (auto simp: has_contour_integral)\n  then have i: \"i = integral {a..1} (\\<lambda>x. f (g x) * vector_derivative g (at x)) +\n                    integral {0..a} (\\<lambda>x. f (g x) * vector_derivative g (at x))\"\n    apply (rule has_integral_unique)\n    apply (subst add.commute)\n    apply (subst Henstock_Kurzweil_Integration.integral_combine)\n    using assms * integral_unique by auto\n\n  have vd1: \"vector_derivative (shiftpath a g) (at x) = vector_derivative g (at (x + a))\"\n    if \"0 \\<le> x\" \"x + a < 1\" \"x \\<notin> (\\<lambda>x. x - a) ` S\" for x\n    unfolding shiftpath_def\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    have \"((\\<lambda>x. g (x + a)) has_vector_derivative vector_derivative g (at (a + x))) (at x)\"\n    proof (rule vector_diff_chain_at [of _ 1, simplified o_def scaleR_one])\n      show \"((\\<lambda>x. x + a) has_vector_derivative 1) (at x)\"\n        by (rule derivative_eq_intros | simp)+\n      have \"g differentiable at (x + a)\"\n        using g a that by force\n      then show \"(g has_vector_derivative vector_derivative g (at (a + x))) (at (x + a))\"\n        by (metis add.commute vector_derivative_works)\n    qed\n    then\n    show \"((\\<lambda>x. g (a + x)) has_vector_derivative vector_derivative g (at (x + a))) (at x)\"\n      by (auto simp: field_simps)\n    show \"0 < dist (1 - a) x\"\n      using that by auto\n  qed (use that in \\<open>auto simp: dist_real_def\\<close>)\n\n  have vd2: \"vector_derivative (shiftpath a g) (at x) = vector_derivative g (at (x + a - 1))\"\n    if \"x \\<le> 1\" \"1 < x + a\" \"x \\<notin> (\\<lambda>x. x - a + 1) ` S\" for x\n    unfolding shiftpath_def\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    have \"((\\<lambda>x. g (x + a - 1)) has_vector_derivative vector_derivative g (at (a+x-1))) (at x)\"\n    proof (rule vector_diff_chain_at [of _ 1, simplified o_def scaleR_one])\n      show \"((\\<lambda>x. x + a - 1) has_vector_derivative 1) (at x)\"\n        by (rule derivative_eq_intros | simp)+\n      have \"g differentiable at (x+a-1)\"\n        using g a that by force\n      then show \"(g has_vector_derivative vector_derivative g (at (a+x-1))) (at (x + a - 1))\"\n        by (metis add.commute vector_derivative_works)\n    qed\n    then show \"((\\<lambda>x. g (a + x - 1)) has_vector_derivative vector_derivative g (at (x + a - 1))) (at x)\"\n      by (auto simp: field_simps)\n    show \"0 < dist (1 - a) x\"\n      using that by auto\n  qed (use that in \\<open>auto simp: dist_real_def\\<close>)\n\n  have va1: \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on ({a..1})\"\n    using * a   by (fastforce intro: integrable_subinterval_real)\n  have v0a: \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on ({0..a})\"\n    using * a by (force intro: integrable_subinterval_real)\n  have \"finite ({1 - a} \\<union> (\\<lambda>x. x - a) ` S)\"\n    using S by blast\n  then have \"((\\<lambda>x. f (shiftpath a g x) * vector_derivative (shiftpath a g) (at x))\n        has_integral integral {a..1} (\\<lambda>x. f (g x) * vector_derivative g (at x)))  {0..1 - a}\"\n    apply (rule has_integral_spike_finite\n        [where f = \"\\<lambda>x. f(g(a+x)) * vector_derivative g (at(a+x))\"])\n    subgoal\n      using a by (simp add: vd1) (force simp: shiftpath_def add.commute)\n    subgoal\n      using has_integral_affinity [where m=1 and c=a] integrable_integral [OF va1]\n      by (force simp add: add.commute)\n    done\n  moreover\n  have \"finite ({1 - a} \\<union> (\\<lambda>x. x - a + 1) ` S)\"\n    using S by blast\n  then have \"((\\<lambda>x. f (shiftpath a g x) * vector_derivative (shiftpath a g) (at x))\n             has_integral  integral {0..a} (\\<lambda>x. f (g x) * vector_derivative g (at x)))  {1 - a..1}\"\n    apply (rule has_integral_spike_finite\n        [where f = \"\\<lambda>x. f(g(a+x-1)) * vector_derivative g (at(a+x-1))\"])\n    subgoal\n      using a by (simp add: vd2) (force simp: shiftpath_def add.commute)\n    subgoal\n      using has_integral_affinity [where m=1 and c=\"a-1\", simplified, OF integrable_integral [OF v0a]]\n      by (force simp add: algebra_simps)\n    done\n  ultimately show ?thesis\n    using a\n    by (auto simp: i has_contour_integral intro: has_integral_combine [where c = \"1-a\"])\nqed\n\nlemma has_contour_integral_shiftpath_D:\n  assumes \"(f has_contour_integral i) (shiftpath a g)\"\n          \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"(f has_contour_integral i) g\"\nproof -\n  obtain S\n    where S: \"finite S\" and g: \"\\<forall>x\\<in>{0..1} - S. g differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  { fix x\n    assume x: \"0 < x\" \"x < 1\" \"x \\<notin> S\"\n    then have gx: \"g differentiable at x\"\n      using g by auto\n    have \\<section>: \"shiftpath (1 - a) (shiftpath a g) differentiable at x\"\n      using assms x\n      by (intro differentiable_transform_within [OF gx, of \"min x (1-x)\"])\n         (auto simp: dist_real_def shiftpath_shiftpath abs_if split: if_split_asm)\n    have \"vector_derivative g (at x within {0..1}) =\n          vector_derivative (shiftpath (1 - a) (shiftpath a g)) (at x within {0..1})\"\n      apply (rule vector_derivative_at_within_ivl\n                  [OF has_vector_derivative_transform_within_open\n                      [where f = \"(shiftpath (1 - a) (shiftpath a g))\" and S = \"{0<..<1}-S\"]])\n      using S assms x \\<section>\n      apply (auto simp: finite_imp_closed open_Diff shiftpath_shiftpath\n                        at_within_interior [of _ \"{0..1}\"] vector_derivative_works [symmetric])\n      done\n  } note vd = this\n  have fi: \"(f has_contour_integral i) (shiftpath (1 - a) (shiftpath a g))\"\n    using assms  by (auto intro!: has_contour_integral_shiftpath)\n  show ?thesis\n    unfolding has_contour_integral_def\n  proof (rule has_integral_spike_finite [of \"{0,1} \\<union> S\", OF _ _  fi [unfolded has_contour_integral_def]])\n    show \"finite ({0, 1} \\<union> S)\"\n      by (simp add: S)\n  qed (use S assms vd in \\<open>auto simp: shiftpath_shiftpath\\<close>)\nqed\n\nlemma has_contour_integral_shiftpath_eq:\n  assumes \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"(f has_contour_integral i) (shiftpath a g) \\<longleftrightarrow> (f has_contour_integral i) g\"\n  using assms has_contour_integral_shiftpath has_contour_integral_shiftpath_D by blast\n\nlemma contour_integrable_on_shiftpath_eq:\n  assumes \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"f contour_integrable_on (shiftpath a g) \\<longleftrightarrow> f contour_integrable_on g\"\nusing assms contour_integrable_on_def has_contour_integral_shiftpath_eq by auto\n\nlemma contour_integral_shiftpath:\n  assumes \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"contour_integral (shiftpath a g) f = contour_integral g f\"\n   using assms\n   by (simp add: contour_integral_def contour_integrable_on_def has_contour_integral_shiftpath_eq)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>More about straight-line paths\\<close>\n\nlemma has_contour_integral_linepath:\n  shows \"(f has_contour_integral i) (linepath a b) \\<longleftrightarrow>\n         ((\\<lambda>x. f(linepath a b x) * (b - a)) has_integral i) {0..1}\"\n  by (simp add: has_contour_integral)\n\nlemma has_contour_integral_trivial [iff]: \"(f has_contour_integral 0) (linepath a a)\"\n  by (simp add: has_contour_integral_linepath)\n\nlemma has_contour_integral_trivial_iff [simp]: \"(f has_contour_integral i) (linepath a a) \\<longleftrightarrow> i=0\"\n  using has_contour_integral_unique by blast\n\nlemma contour_integral_trivial [simp]: \"contour_integral (linepath a a) f = 0\"\n  using has_contour_integral_trivial contour_integral_unique by blast\n\n\nsubsection\\<open>Relation to subpath construction\\<close>\n\nlemma has_contour_integral_subpath_refl [iff]: \"(f has_contour_integral 0) (subpath u u g)\"\n  by (simp add: has_contour_integral subpath_def)\n\nlemma contour_integrable_subpath_refl [iff]: \"f contour_integrable_on (subpath u u g)\"\n  using has_contour_integral_subpath_refl contour_integrable_on_def by blast\n\nlemma contour_integral_subpath_refl [simp]: \"contour_integral (subpath u u g) f = 0\"\n  by (simp add: contour_integral_unique)\n\nlemma has_contour_integral_subpath:\n  assumes f: \"f contour_integrable_on g\" and g: \"valid_path g\"\n      and uv: \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<le> v\"\n    shows \"(f has_contour_integral  integral {u..v} (\\<lambda>x. f(g x) * vector_derivative g (at x)))\n           (subpath u v g)\"\nproof (cases \"v=u\")\n  case True\n  then show ?thesis\n    using f   by (simp add: contour_integrable_on_def subpath_def has_contour_integral)\nnext\n  case False\n  obtain S where S: \"\\<And>x. x \\<in> {0..1} - S \\<Longrightarrow> g differentiable at x\" and fs: \"finite S\"\n    using g unfolding piecewise_C1_differentiable_on_def C1_differentiable_on_eq valid_path_def by blast\n  have \\<section>: \"(\\<lambda>t. f (g t) * vector_derivative g (at t)) integrable_on {u..v}\"\n    using contour_integrable_on f integrable_on_subinterval uv by fastforce\n  then have *: \"((\\<lambda>x. f (g ((v - u) * x + u)) * vector_derivative g (at ((v - u) * x + u)))\n            has_integral (1 / (v - u)) * integral {u..v} (\\<lambda>t. f (g t) * vector_derivative g (at t)))\n           {0..1}\"\n    using uv False unfolding has_integral_integral\n    apply simp\n    apply (drule has_integral_affinity [where m=\"v-u\" and c=u, simplified])\n    apply (simp_all add: image_affinity_atLeastAtMost_div_diff scaleR_conv_of_real)\n    apply (simp add: divide_simps)\n    done\n\n  have vd: \"vector_derivative (\\<lambda>x. g ((v-u) * x + u)) (at x) = (v-u) *\\<^sub>R vector_derivative g (at ((v-u) * x + u))\"\n    if \"x \\<in> {0..1}\"  \"x \\<notin> (\\<lambda>t. (v-u) *\\<^sub>R t + u) -` S\" for x\n  proof (rule vector_derivative_at [OF vector_diff_chain_at [simplified o_def]])\n    show \"((\\<lambda>x. (v - u) * x + u) has_vector_derivative v - u) (at x)\"\n      by (intro derivative_eq_intros | simp)+\n  qed (use S uv mult_left_le [of x \"v-u\"] that in \\<open>auto simp: vector_derivative_works\\<close>)\n\n  have fin: \"finite ((\\<lambda>t. (v - u) *\\<^sub>R t + u) -` S)\"\n    using fs by (auto simp: inj_on_def False finite_vimageI)\n  show ?thesis\n    unfolding subpath_def has_contour_integral\n    apply (rule has_integral_spike_finite [OF fin])\n    using has_integral_cmul [OF *, where c = \"v-u\"] fs assms\n    by (auto simp: False vd scaleR_conv_of_real)\nqed\n\nlemma contour_integrable_subpath:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\"\n    shows \"f contour_integrable_on (subpath u v g)\"\nproof (cases u v rule: linorder_class.le_cases)\n  case le\n  then show ?thesis\n    by (metis contour_integrable_on_def has_contour_integral_subpath [OF assms])\nnext\n  case ge\n  with assms show ?thesis\n    by (metis (no_types, lifting) contour_integrable_on_def contour_integrable_reversepath_eq has_contour_integral_subpath reversepath_subpath valid_path_subpath)\nqed\n\nlemma has_integral_contour_integral_subpath:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<le> v\"\n    shows \"(((\\<lambda>x. f(g x) * vector_derivative g (at x)))\n            has_integral  contour_integral (subpath u v g) f) {u..v}\"\n  using assms\nproof -\n  have \"(\\<lambda>r. f (g r) * vector_derivative g (at r)) integrable_on {u..v}\"\n    by (metis (full_types) assms(1) assms(3) assms(4) atLeastAtMost_iff atLeastatMost_subset_iff contour_integrable_on integrable_on_subinterval)\n  then have \"((\\<lambda>r. f (g r) * vector_derivative g (at r)) has_integral integral {u..v} (\\<lambda>r. f (g r) * vector_derivative g (at r))) {u..v}\"\n    by blast\n  then show ?thesis\n    by (metis (full_types) assms contour_integral_unique has_contour_integral_subpath)\nqed\n\nlemma contour_integral_subcontour_integral:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<le> v\"\n    shows \"contour_integral (subpath u v g) f =\n           integral {u..v} (\\<lambda>x. f(g x) * vector_derivative g (at x))\"\n  using assms has_contour_integral_subpath contour_integral_unique by blast\n\nlemma contour_integral_subpath_combine_less:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"w \\<in> {0..1}\"\n          \"u<v\" \"v<w\"\n    shows \"contour_integral (subpath u v g) f + contour_integral (subpath v w g) f =\n           contour_integral (subpath u w g) f\"\nproof -\n  have \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on {u..w}\"\n    using integrable_on_subcbox [where a=u and b=w and S = \"{0..1}\"] assms\n    by (auto simp: contour_integrable_on)\n  with assms show ?thesis\n    by (auto simp: contour_integral_subcontour_integral Henstock_Kurzweil_Integration.integral_combine)\nqed\n\nlemma contour_integral_subpath_combine:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"w \\<in> {0..1}\"\n    shows \"contour_integral (subpath u v g) f + contour_integral (subpath v w g) f =\n           contour_integral (subpath u w g) f\"\nproof (cases \"u\\<noteq>v \\<and> v\\<noteq>w \\<and> u\\<noteq>w\")\n  case True\n    have *: \"subpath v u g = reversepath(subpath u v g) \\<and>\n             subpath w u g = reversepath(subpath u w g) \\<and>\n             subpath w v g = reversepath(subpath v w g)\"\n      by (auto simp: reversepath_subpath)\n    have \"u < v \\<and> v < w \\<or>\n          u < w \\<and> w < v \\<or>\n          v < u \\<and> u < w \\<or>\n          v < w \\<and> w < u \\<or>\n          w < u \\<and> u < v \\<or>\n          w < v \\<and> v < u\"\n      using True assms by linarith\n    with assms show ?thesis\n      using contour_integral_subpath_combine_less [of f g u v w]\n            contour_integral_subpath_combine_less [of f g u w v]\n            contour_integral_subpath_combine_less [of f g v u w]\n            contour_integral_subpath_combine_less [of f g v w u]\n            contour_integral_subpath_combine_less [of f g w u v]\n            contour_integral_subpath_combine_less [of f g w v u]\n      by (elim disjE) (auto simp: * contour_integral_reversepath contour_integrable_subpath\n                                    valid_path_subpath algebra_simps)\nnext\n  case False\n  with assms show ?thesis\n    by (metis add.right_neutral contour_integral_reversepath contour_integral_subpath_refl diff_0 eq_diff_eq add_0 reversepath_subpath valid_path_subpath)\nqed\n\nlemma contour_integral_integral:\n     \"contour_integral g f = integral {0..1} (\\<lambda>x. f (g x) * vector_derivative g (at x))\"\n  by (simp add: contour_integral_def integral_def has_contour_integral contour_integrable_on)\n\nlemma contour_integral_cong:\n  assumes \"g = g'\" \"\\<And>x. x \\<in> path_image g \\<Longrightarrow> f x = f' x\"\n  shows   \"contour_integral g f = contour_integral g' f'\"\n  unfolding contour_integral_integral using assms\n  by (intro integral_cong) (auto simp: path_image_def)\n\nlemma contour_integral_spike_finite_simple_path:\n  assumes \"finite A\" \"simple_path g\" \"g = g'\" \"\\<And>x. x \\<in> path_image g - A \\<Longrightarrow> f x = f' x\"\n  shows   \"contour_integral g f = contour_integral g' f'\"\n  unfolding contour_integral_integral\nproof (rule integral_spike)\n  have \"finite (g -` A \\<inter> {0<..<1})\" using \\<open>simple_path g\\<close> \\<open>finite A\\<close>\n    by (intro finite_vimage_IntI simple_path_inj_on) auto\n  hence \"finite ({0, 1} \\<union> g -` A \\<inter> {0<..<1})\" by auto\n  thus \"negligible ({0, 1} \\<union> g -` A \\<inter> {0<..<1})\" by (rule negligible_finite)\nnext\n  fix x assume \"x \\<in> {0..1} - ({0, 1} \\<union> g -` A \\<inter> {0<..<1})\"\n  hence \"g x \\<in> path_image g - A\" by (auto simp: path_image_def)\n  from assms(4)[OF this] and assms(3)\n    show \"f' (g' x) * vector_derivative g' (at x) = f (g x) * vector_derivative g (at x)\" by simp\n  qed\n\n\ntext \\<open>Contour integral along a segment on the real axis\\<close>\n\nlemma has_contour_integral_linepath_Reals_iff:\n  fixes a b :: complex and f :: \"complex \\<Rightarrow> complex\"\n  assumes \"a \\<in> Reals\" \"b \\<in> Reals\" \"Re a < Re b\"\n  shows   \"(f has_contour_integral I) (linepath a b) \\<longleftrightarrow>\n             ((\\<lambda>x. f (of_real x)) has_integral I) {Re a..Re b}\"\nproof -\n  from assms have [simp]: \"of_real (Re a) = a\" \"of_real (Re b) = b\"\n    by (simp_all add: complex_eq_iff)\n  from assms have \"a \\<noteq> b\" by auto\n  have \"((\\<lambda>x. f (of_real x)) has_integral I) (cbox (Re a) (Re b)) \\<longleftrightarrow>\n          ((\\<lambda>x. f (a + b * of_real x - a * of_real x)) has_integral I /\\<^sub>R (Re b - Re a)) {0..1}\"\n    by (subst has_integral_affinity_iff [of \"Re b - Re a\" _ \"Re a\", symmetric])\n       (insert assms, simp_all add: field_simps scaleR_conv_of_real)\n  also have \"(\\<lambda>x. f (a + b * of_real x - a * of_real x)) =\n               (\\<lambda>x. (f (a + b * of_real x - a * of_real x) * (b - a)) /\\<^sub>R (Re b - Re a))\"\n    using \\<open>a \\<noteq> b\\<close> by (auto simp: field_simps fun_eq_iff scaleR_conv_of_real)\n  also have \"(\\<dots> has_integral I /\\<^sub>R (Re b - Re a)) {0..1} \\<longleftrightarrow>\n               ((\\<lambda>x. f (linepath a b x) * (b - a)) has_integral I) {0..1}\" using assms\n    by (subst has_integral_cmul_iff) (auto simp: linepath_def scaleR_conv_of_real algebra_simps)\n  also have \"\\<dots> \\<longleftrightarrow> (f has_contour_integral I) (linepath a b)\" unfolding has_contour_integral_def\n    by (intro has_integral_cong) (simp add: vector_derivative_linepath_within)\n  finally show ?thesis by simp\nqed\n\n\n\nlemma contour_integral_linepath_Reals_eq:\n  fixes a b :: complex and f :: \"complex \\<Rightarrow> complex\"\n  assumes \"a \\<in> Reals\" \"b \\<in> Reals\" \"Re a < Re b\"\n  shows   \"contour_integral (linepath a b) f = integral {Re a..Re b} (\\<lambda>x. f (of_real x))\"\nproof (cases \"f contour_integrable_on linepath a b\")\n  case True\n  thus ?thesis using has_contour_integral_linepath_Reals_iff[OF assms, of f]\n    using has_contour_integral_integral has_contour_integral_unique by blast\nnext\n  case False\n  thus ?thesis using contour_integrable_linepath_Reals_iff[OF assms, of f]\n    by (simp add: not_integrable_contour_integral not_integrable_integral)\nqed\n\nsubsection \\<open>Cauchy's theorem where there's a primitive\\<close>\n\nlemma contour_integral_primitive_lemma:\n  fixes f :: \"complex \\<Rightarrow> complex\" and g :: \"real \\<Rightarrow> complex\"\n  assumes \"a \\<le> b\"\n      and \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and \"g piecewise_differentiable_on {a..b}\"  \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> g x \\<in> S\"\n    shows \"((\\<lambda>x. f'(g x) * vector_derivative g (at x within {a..b}))\n             has_integral (f(g b) - f(g a))) {a..b}\"\nproof -\n  obtain K where \"finite K\" and K: \"\\<forall>x\\<in>{a..b} - K. g differentiable (at x within {a..b})\" and cg: \"continuous_on {a..b} g\"\n    using assms by (auto simp: piecewise_differentiable_on_def)\n  have \"continuous_on (g ` {a..b}) f\"\n    using assms\n    by (metis field_differentiable_def field_differentiable_imp_continuous_at continuous_on_eq_continuous_within continuous_on_subset image_subset_iff)\n  then have cfg: \"continuous_on {a..b} (\\<lambda>x. f (g x))\"\n    by (rule continuous_on_compose [OF cg, unfolded o_def])\n  { fix x::real\n    assume a: \"a < x\" and b: \"x < b\" and xk: \"x \\<notin> K\"\n    then have \"g differentiable at x within {a..b}\"\n      using K by (simp add: differentiable_at_withinI)\n    then have \"(g has_vector_derivative vector_derivative g (at x within {a..b})) (at x within {a..b})\"\n      by (simp add: vector_derivative_works has_field_derivative_def scaleR_conv_of_real)\n    then have gdiff: \"(g has_derivative (\\<lambda>u. u * vector_derivative g (at x within {a..b}))) (at x within {a..b})\"\n      by (simp add: has_vector_derivative_def scaleR_conv_of_real)\n    have \"(f has_field_derivative (f' (g x))) (at (g x) within g ` {a..b})\"\n      using assms by (metis a atLeastAtMost_iff b DERIV_subset image_subset_iff less_eq_real_def)\n    then have fdiff: \"(f has_derivative (*) (f' (g x))) (at (g x) within g ` {a..b})\"\n      by (simp add: has_field_derivative_def)\n    have \"((\\<lambda>x. f (g x)) has_vector_derivative f' (g x) * vector_derivative g (at x within {a..b})) (at x within {a..b})\"\n      using diff_chain_within [OF gdiff fdiff]\n      by (simp add: has_vector_derivative_def scaleR_conv_of_real o_def mult_ac)\n  } note * = this\n  show ?thesis\n    using assms cfg *\n    by (force simp: at_within_Icc_at intro: fundamental_theorem_of_calculus_interior_strong [OF \\<open>finite K\\<close>])\nqed\n\nlemma contour_integral_primitive:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and \"valid_path g\" \"path_image g \\<subseteq> S\"\n    shows \"(f' has_contour_integral (f(pathfinish g) - f(pathstart g))) g\"\n  using assms\n  apply (simp add: valid_path_def path_image_def pathfinish_def pathstart_def has_contour_integral_def)\n  apply (auto intro!: piecewise_C1_imp_differentiable contour_integral_primitive_lemma [of 0 1 S])\n  done\n\ncorollary Cauchy_theorem_primitive:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and \"valid_path g\"  \"path_image g \\<subseteq> S\" \"pathfinish g = pathstart g\"\n    shows \"(f' has_contour_integral 0) g\"\n  using assms by (metis diff_self contour_integral_primitive)\n\ntext\\<open>Existence of path integral for continuous function\\<close>\nlemma contour_integrable_continuous_linepath:\n  assumes \"continuous_on (closed_segment a b) f\"\n  shows \"f contour_integrable_on (linepath a b)\"\nproof -\n  have \"continuous_on (closed_segment a b) (\\<lambda>x. f x * (b - a))\"\n    by (rule continuous_intros | simp add: assms)+\n  then have \"continuous_on {0..1} (\\<lambda>x. f (linepath a b x) * (b - a))\"\n    by (metis (no_types, lifting) continuous_on_compose continuous_on_cong continuous_on_linepath linepath_image_01 o_apply)\n  then have \"(\\<lambda>x. f (linepath a b x) *\n         vector_derivative (linepath a b)\n          (at x within {0..1})) integrable_on\n    {0..1}\"\n    by (metis (no_types, lifting) continuous_on_cong integrable_continuous_real vector_derivative_linepath_within)\n  then show ?thesis\n    by (simp add: contour_integrable_on_def has_contour_integral_def integrable_on_def [symmetric])\nqed\n\nlemma has_field_der_id: \"((\\<lambda>x. x\\<^sup>2/2) has_field_derivative x) (at x)\"\n  by (rule has_derivative_imp_has_field_derivative)\n     (rule derivative_intros | simp)+\n\nlemma contour_integral_id [simp]: \"contour_integral (linepath a b) (\\<lambda>y. y) = (b^2 - a^2)/2\"\n  using contour_integral_primitive [of UNIV \"\\<lambda>x. x^2/2\" \"\\<lambda>x. x\" \"linepath a b\"] contour_integral_unique\n  by (simp add: has_field_der_id)\n\nlemma contour_integrable_on_const [iff]: \"(\\<lambda>x. c) contour_integrable_on (linepath a b)\"\n  by (simp add: contour_integrable_continuous_linepath)\n\nlemma contour_integrable_on_id [iff]: \"(\\<lambda>x. x) contour_integrable_on (linepath a b)\"\n  by (simp add: contour_integrable_continuous_linepath)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Arithmetical combining theorems\\<close>\n\nlemma has_contour_integral_neg:\n    \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. -(f x)) has_contour_integral (-i)) g\"\n  by (simp add: has_integral_neg has_contour_integral_def)\n\nlemma has_contour_integral_add:\n    \"\\<lbrakk>(f1 has_contour_integral i1) g; (f2 has_contour_integral i2) g\\<rbrakk>\n     \\<Longrightarrow> ((\\<lambda>x. f1 x + f2 x) has_contour_integral (i1 + i2)) g\"\n  by (simp add: has_integral_add has_contour_integral_def algebra_simps)\n\nlemma has_contour_integral_diff:\n  \"\\<lbrakk>(f1 has_contour_integral i1) g; (f2 has_contour_integral i2) g\\<rbrakk>\n         \\<Longrightarrow> ((\\<lambda>x. f1 x - f2 x) has_contour_integral (i1 - i2)) g\"\n  by (simp add: has_integral_diff has_contour_integral_def algebra_simps)\n\nlemma has_contour_integral_lmul:\n  \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. c * (f x)) has_contour_integral (c*i)) g\"\n  by (simp add: has_contour_integral_def algebra_simps has_integral_mult_right)\n\nlemma has_contour_integral_rmul:\n  \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. (f x) * c) has_contour_integral (i*c)) g\"\n  by (simp add: mult.commute has_contour_integral_lmul)\n\nlemma has_contour_integral_div:\n  \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. f x/c) has_contour_integral (i/c)) g\"\n  by (simp add: field_class.field_divide_inverse) (metis has_contour_integral_rmul)\n\nlemma has_contour_integral_eq:\n    \"\\<lbrakk>(f has_contour_integral y) p; \\<And>x. x \\<in> path_image p \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> (g has_contour_integral y) p\"\n  by (metis (mono_tags, lifting) has_contour_integral_def has_integral_eq image_eqI path_image_def)\n\nlemma has_contour_integral_bound_linepath:\n  assumes \"(f has_contour_integral i) (linepath a b)\"\n          \"0 \\<le> B\" and B: \"\\<And>x. x \\<in> closed_segment a b \\<Longrightarrow> norm(f x) \\<le> B\"\n    shows \"norm i \\<le> B * norm(b - a)\"\nproof -\n  have \"norm i \\<le> (B * norm (b - a)) * content (cbox 0 (1::real))\"\n  proof (rule has_integral_bound\n       [of _ \"\\<lambda>x. f (linepath a b x) * vector_derivative (linepath a b) (at x within {0..1})\"])\n    show  \"cmod (f (linepath a b x) * vector_derivative (linepath a b) (at x within {0..1}))\n         \\<le> B * cmod (b - a)\"\n      if \"x \\<in> cbox 0 1\" for x::real\n      using that box_real(2) norm_mult\n      by (metis B linepath_in_path mult_right_mono norm_ge_zero vector_derivative_linepath_within)\n  qed (use assms has_contour_integral_def in auto)\n  then show ?thesis\n    by (auto simp: content_real)\nqed\n\nlemma has_contour_integral_const_linepath: \"((\\<lambda>x. c) has_contour_integral c*(b - a))(linepath a b)\"\n  unfolding has_contour_integral_linepath\n  by (metis content_real diff_0_right has_integral_const_real lambda_one of_real_1 scaleR_conv_of_real zero_le_one)\n\nlemma has_contour_integral_0: \"((\\<lambda>x. 0) has_contour_integral 0) g\"\n  by (simp add: has_contour_integral_def)\n\nlemma has_contour_integral_is_0:\n    \"(\\<And>z. z \\<in> path_image g \\<Longrightarrow> f z = 0) \\<Longrightarrow> (f has_contour_integral 0) g\"\n  by (rule has_contour_integral_eq [OF has_contour_integral_0]) auto\n\nlemma has_contour_integral_sum:\n    \"\\<lbrakk>finite s; \\<And>a. a \\<in> s \\<Longrightarrow> (f a has_contour_integral i a) p\\<rbrakk>\n     \\<Longrightarrow> ((\\<lambda>x. sum (\\<lambda>a. f a x) s) has_contour_integral sum i s) p\"\n  by (induction s rule: finite_induct) (auto simp: has_contour_integral_0 has_contour_integral_add)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Operations on path integrals\\<close>\n\nlemma contour_integral_const_linepath [simp]: \"contour_integral (linepath a b) (\\<lambda>x. c) = c*(b - a)\"\n  by (rule contour_integral_unique [OF has_contour_integral_const_linepath])\n\nlemma contour_integral_neg: \"contour_integral g (\\<lambda>z. -f z) = -contour_integral g f\"\n  by (simp add: contour_integral_integral)\n\nlemma contour_integral_add:\n    \"f1 contour_integrable_on g \\<Longrightarrow> f2 contour_integrable_on g \\<Longrightarrow> contour_integral g (\\<lambda>x. f1 x + f2 x) =\n                contour_integral g f1 + contour_integral g f2\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_add)\n\nlemma contour_integral_diff:\n    \"f1 contour_integrable_on g \\<Longrightarrow> f2 contour_integrable_on g \\<Longrightarrow> contour_integral g (\\<lambda>x. f1 x - f2 x) =\n                contour_integral g f1 - contour_integral g f2\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_diff)\n\nlemma contour_integral_lmul:\n  shows \"f contour_integrable_on g\n           \\<Longrightarrow> contour_integral g (\\<lambda>x. c * f x) = c*contour_integral g f\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_lmul)\n\nlemma contour_integral_rmul:\n  shows \"f contour_integrable_on g\n        \\<Longrightarrow> contour_integral g (\\<lambda>x. f x * c) = contour_integral g f * c\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_rmul)\n\nlemma contour_integral_div:\n  shows \"f contour_integrable_on g\n        \\<Longrightarrow> contour_integral g (\\<lambda>x. f x / c) = contour_integral g f / c\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_div)\n\nlemma contour_integral_eq:\n    \"(\\<And>x. x \\<in> path_image p \\<Longrightarrow> f x = g x) \\<Longrightarrow> contour_integral p f = contour_integral p g\"\n  using contour_integral_cong contour_integral_def by fastforce\n\nlemma contour_integral_eq_0:\n    \"(\\<And>z. z \\<in> path_image g \\<Longrightarrow> f z = 0) \\<Longrightarrow> contour_integral g f = 0\"\n  by (simp add: has_contour_integral_is_0 contour_integral_unique)\n\nlemma contour_integral_bound_linepath:\n  shows\n    \"\\<lbrakk>f contour_integrable_on (linepath a b);\n      0 \\<le> B; \\<And>x. x \\<in> closed_segment a b \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n     \\<Longrightarrow> norm(contour_integral (linepath a b) f) \\<le> B*norm(b - a)\"\n  by (meson has_contour_integral_bound_linepath has_contour_integral_integral)\n\nlemma contour_integral_0 [simp]: \"contour_integral g (\\<lambda>x. 0) = 0\"\n  by (simp add: contour_integral_unique has_contour_integral_0)\n\nlemma contour_integral_sum:\n    \"\\<lbrakk>finite s; \\<And>a. a \\<in> s \\<Longrightarrow> (f a) contour_integrable_on p\\<rbrakk>\n     \\<Longrightarrow> contour_integral p (\\<lambda>x. sum (\\<lambda>a. f a x) s) = sum (\\<lambda>a. contour_integral p (f a)) s\"\n  by (auto simp: contour_integral_unique has_contour_integral_sum has_contour_integral_integral)\n\nlemma contour_integrable_eq:\n    \"\\<lbrakk>f contour_integrable_on p; \\<And>x. x \\<in> path_image p \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> g contour_integrable_on p\"\n  unfolding contour_integrable_on_def\n  by (metis has_contour_integral_eq)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Arithmetic theorems for path integrability\\<close>\n\nlemma contour_integrable_neg:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. -(f x)) contour_integrable_on g\"\n  using has_contour_integral_neg contour_integrable_on_def by blast\n\nlemma contour_integrable_add:\n    \"\\<lbrakk>f1 contour_integrable_on g; f2 contour_integrable_on g\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f1 x + f2 x) contour_integrable_on g\"\n  using has_contour_integral_add contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_diff:\n    \"\\<lbrakk>f1 contour_integrable_on g; f2 contour_integrable_on g\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f1 x - f2 x) contour_integrable_on g\"\n  using has_contour_integral_diff contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_lmul:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. c * f x) contour_integrable_on g\"\n  using has_contour_integral_lmul contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_rmul:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. f x * c) contour_integrable_on g\"\n  using has_contour_integral_rmul contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_div:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. f x / c) contour_integrable_on g\"\n  using has_contour_integral_div contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_sum:\n    \"\\<lbrakk>finite s; \\<And>a. a \\<in> s \\<Longrightarrow> (f a) contour_integrable_on p\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. sum (\\<lambda>a. f a x) s) contour_integrable_on p\"\n   unfolding contour_integrable_on_def\n   by (metis has_contour_integral_sum)\n\nlemma contour_integrable_neg_iff:\n  \"(\\<lambda>x. -f x) contour_integrable_on g \\<longleftrightarrow> f contour_integrable_on g\"\n  using contour_integrable_neg[of f g] contour_integrable_neg[of \"\\<lambda>x. -f x\" g] by auto\n\nlemma contour_integrable_lmul_iff:\n    \"c \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. c * f x) contour_integrable_on g \\<longleftrightarrow> f contour_integrable_on g\"\n  using contour_integrable_lmul[of f g c] contour_integrable_lmul[of \"\\<lambda>x. c * f x\" g \"inverse c\"]\n  by (auto simp: field_simps)\n\nlemma contour_integrable_rmul_iff:\n    \"c \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. f x * c) contour_integrable_on g \\<longleftrightarrow> f contour_integrable_on g\"\n  using contour_integrable_rmul[of f g c] contour_integrable_rmul[of \"\\<lambda>x. c * f x\" g \"inverse c\"]\n  by (auto simp: field_simps)\n\nlemma contour_integrable_div_iff:\n    \"c \\<noteq> 0 \\<Longrightarrow> (\\<lambda>x. f x / c) contour_integrable_on g \\<longleftrightarrow> f contour_integrable_on g\"\n  using contour_integrable_rmul_iff[of \"inverse c\"] by (simp add: field_simps)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Reversing a path integral\\<close>\n\nlemma has_contour_integral_reverse_linepath:\n    \"(f has_contour_integral i) (linepath a b)\n     \\<Longrightarrow> (f has_contour_integral (-i)) (linepath b a)\"\n  using has_contour_integral_reversepath valid_path_linepath by fastforce\n\nlemma contour_integral_reverse_linepath:\n    \"continuous_on (closed_segment a b) f \\<Longrightarrow> contour_integral (linepath a b) f = - (contour_integral(linepath b a) f)\"\n  using contour_integral_reversepath by fastforce\n\n\n\ntext \\<open>Splitting a path integral in a flat way.*)\\<close>\n\nlemma has_contour_integral_split:\n  assumes f: \"(f has_contour_integral i) (linepath a c)\" \"(f has_contour_integral j) (linepath c b)\"\n      and k: \"0 \\<le> k\" \"k \\<le> 1\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"(f has_contour_integral (i + j)) (linepath a b)\"\nproof (cases \"k = 0 \\<or> k = 1\")\n  case True\n  then show ?thesis\n    using assms by auto\nnext\n  case False\n  then have k: \"0 < k\" \"k < 1\" \"complex_of_real k \\<noteq> 1\"\n    using assms by auto\n  have c': \"c = k *\\<^sub>R (b - a) + a\"\n    by (metis diff_add_cancel c)\n  have bc: \"(b - c) = (1 - k) *\\<^sub>R (b - a)\"\n    by (simp add: algebra_simps c')\n  { assume *: \"((\\<lambda>x. f ((1 - x) *\\<^sub>R a + x *\\<^sub>R c) * (c - a)) has_integral i) {0..1}\"\n    have \"\\<And>x. (x / k) *\\<^sub>R a + ((k - x) / k) *\\<^sub>R a = a\"\n      using False by (simp add: field_split_simps flip: real_vector.scale_left_distrib)\n    then have \"\\<And>x. ((k - x) / k) *\\<^sub>R a + (x / k) *\\<^sub>R c = (1 - x) *\\<^sub>R a + x *\\<^sub>R b\"\n      using False by (simp add: c' algebra_simps)\n    then have \"((\\<lambda>x. f ((1 - x) *\\<^sub>R a + x *\\<^sub>R b) * (b - a)) has_integral i) {0..k}\"\n      using k has_integral_affinity01 [OF *, of \"inverse k\" \"0\"]\n      by (force dest: has_integral_cmul [where c = \"inverse k\"]\n              simp add: divide_simps mult.commute [of _ \"k\"] image_affinity_atLeastAtMost c)\n  } note fi = this\n  { assume *: \"((\\<lambda>x. f ((1 - x) *\\<^sub>R c + x *\\<^sub>R b) * (b - c)) has_integral j) {0..1}\"\n    have **: \"\\<And>x. (((1 - x) / (1 - k)) *\\<^sub>R c + ((x - k) / (1 - k)) *\\<^sub>R b) = ((1 - x) *\\<^sub>R a + x *\\<^sub>R b)\"\n      using k unfolding c' scaleR_conv_of_real\n      apply (simp add: divide_simps)\n      apply (simp add: distrib_right distrib_left right_diff_distrib left_diff_distrib)\n      done\n    have \"((\\<lambda>x. f ((1 - x) *\\<^sub>R a + x *\\<^sub>R b) * (b - a)) has_integral j) {k..1}\"\n      using k has_integral_affinity01 [OF *, of \"inverse(1 - k)\" \"-(k/(1 - k))\"]\n      apply (simp add: divide_simps mult.commute [of _ \"1-k\"] image_affinity_atLeastAtMost ** bc)\n      apply (auto dest: has_integral_cmul [where k = \"(1 - k) *\\<^sub>R j\" and c = \"inverse (1 - k)\"])\n      done\n  } note fj = this\n  show ?thesis\n    using f k unfolding has_contour_integral_linepath\n    by (simp add: linepath_def has_integral_combine [OF _ _ fi fj])\nqed\n\nlemma continuous_on_closed_segment_transform:\n  assumes f: \"continuous_on (closed_segment a b) f\"\n      and k: \"0 \\<le> k\" \"k \\<le> 1\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"continuous_on (closed_segment a c) f\"\nproof -\n  have c': \"c = (1 - k) *\\<^sub>R a + k *\\<^sub>R b\"\n    using c by (simp add: algebra_simps)\n  have \"closed_segment a c \\<subseteq> closed_segment a b\"\n    by (metis c' ends_in_segment(1) in_segment(1) k subset_closed_segment)\n  then show \"continuous_on (closed_segment a c) f\"\n    by (rule continuous_on_subset [OF f])\nqed\n\nlemma contour_integral_split:\n  assumes f: \"continuous_on (closed_segment a b) f\"\n      and k: \"0 \\<le> k\" \"k \\<le> 1\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"contour_integral(linepath a b) f = contour_integral(linepath a c) f + contour_integral(linepath c b) f\"\nproof -\n  have c': \"c = (1 - k) *\\<^sub>R a + k *\\<^sub>R b\"\n    using c by (simp add: algebra_simps)\n  have \"closed_segment a c \\<subseteq> closed_segment a b\"\n    by (metis c' ends_in_segment(1) in_segment(1) k subset_closed_segment)\n  moreover have \"closed_segment c b \\<subseteq> closed_segment a b\"\n    by (metis c' ends_in_segment(2) in_segment(1) k subset_closed_segment)\n  ultimately\n  have *: \"continuous_on (closed_segment a c) f\" \"continuous_on (closed_segment c b) f\"\n    by (auto intro: continuous_on_subset [OF f])\n  show ?thesis\n    by (rule contour_integral_unique) (meson \"*\" c contour_integrable_continuous_linepath has_contour_integral_integral has_contour_integral_split k)\nqed\n\nlemma contour_integral_split_linepath:\n  assumes f: \"continuous_on (closed_segment a b) f\"\n      and c: \"c \\<in> closed_segment a b\"\n    shows \"contour_integral(linepath a b) f = contour_integral(linepath a c) f + contour_integral(linepath c b) f\"\n  using c by (auto simp: closed_segment_def algebra_simps intro!: contour_integral_split [OF f])\n\n\nsubsection\\<open>Reversing the order in a double path integral\\<close>\n\ntext\\<open>The condition is stronger than needed but it's often true in typical situations\\<close>\n\nlemma fst_im_cbox [simp]: \"cbox c d \\<noteq> {} \\<Longrightarrow> (fst ` cbox (a,c) (b,d)) = cbox a b\"\n  by (auto simp: cbox_Pair_eq)\n\nlemma snd_im_cbox [simp]: \"cbox a b \\<noteq> {} \\<Longrightarrow> (snd ` cbox (a,c) (b,d)) = cbox c d\"\n  by (auto simp: cbox_Pair_eq)\n\nproposition contour_integral_swap:\n  assumes fcon:  \"continuous_on (path_image g \\<times> path_image h) (\\<lambda>(y1,y2). f y1 y2)\"\n      and vp:    \"valid_path g\" \"valid_path h\"\n      and gvcon: \"continuous_on {0..1} (\\<lambda>t. vector_derivative g (at t))\"\n      and hvcon: \"continuous_on {0..1} (\\<lambda>t. vector_derivative h (at t))\"\n  shows \"contour_integral g (\\<lambda>w. contour_integral h (f w)) =\n         contour_integral h (\\<lambda>z. contour_integral g (\\<lambda>w. f w z))\"\nproof -\n  have gcon: \"continuous_on {0..1} g\" and hcon: \"continuous_on {0..1} h\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def)\n  have fgh1: \"\\<And>x. (\\<lambda>t. f (g x) (h t)) = (\\<lambda>(y1,y2). f y1 y2) \\<circ> (\\<lambda>t. (g x, h t))\"\n    by (rule ext) simp\n  have fgh2: \"\\<And>x. (\\<lambda>t. f (g t) (h x)) = (\\<lambda>(y1,y2). f y1 y2) \\<circ> (\\<lambda>t. (g t, h x))\"\n    by (rule ext) simp\n  have fcon_im1: \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> continuous_on ((\\<lambda>t. (g x, h t)) ` {0..1}) (\\<lambda>(x, y). f x y)\"\n    by (rule continuous_on_subset [OF fcon]) (auto simp: path_image_def)\n  have fcon_im2: \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> continuous_on ((\\<lambda>t. (g t, h x)) ` {0..1}) (\\<lambda>(x, y). f x y)\"\n    by (rule continuous_on_subset [OF fcon]) (auto simp: path_image_def)\n  have \"continuous_on (cbox (0, 0) (1, 1::real)) ((\\<lambda>x. vector_derivative g (at x)) \\<circ> fst)\"\n       \"continuous_on (cbox (0, 0) (1::real, 1)) ((\\<lambda>x. vector_derivative h (at x)) \\<circ> snd)\"\n    by (rule continuous_intros | simp add: gvcon hvcon)+\n  then have gvcon': \"continuous_on (cbox (0, 0) (1, 1::real)) (\\<lambda>z. vector_derivative g (at (fst z)))\"\n       and  hvcon': \"continuous_on (cbox (0, 0) (1::real, 1)) (\\<lambda>x. vector_derivative h (at (snd x)))\"\n    by auto\n  have \"continuous_on (cbox (0, 0) (1, 1)) ((\\<lambda>(y1, y2). f y1 y2) \\<circ> (\\<lambda>w. ((g \\<circ> fst) w, (h \\<circ> snd) w)))\"\n    apply (intro gcon hcon continuous_intros | simp)+\n    apply (auto simp: path_image_def intro: continuous_on_subset [OF fcon])\n    done\n  then have fgh: \"continuous_on (cbox (0, 0) (1, 1)) (\\<lambda>x. f (g (fst x)) (h (snd x)))\"\n    by auto\n  have \"integral {0..1} (\\<lambda>x. contour_integral h (f (g x)) * vector_derivative g (at x)) =\n        integral {0..1} (\\<lambda>x. contour_integral h (\\<lambda>y. f (g x) y * vector_derivative g (at x)))\"\n  proof (rule integral_cong [OF contour_integral_rmul [symmetric]])\n    have \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow>\n         continuous_on {0..1} (\\<lambda>xa. f (g x) (h xa))\"\n    by (subst fgh1) (rule fcon_im1 hcon continuous_intros | simp)+\n    then show \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> f (g x) contour_integrable_on h\"\n      unfolding contour_integrable_on\n      using continuous_on_mult hvcon integrable_continuous_real by blast\n  qed\n  also have \"\\<dots> = integral {0..1}\n                     (\\<lambda>y. contour_integral g (\\<lambda>x. f x (h y) * vector_derivative h (at y)))\"\n    unfolding contour_integral_integral\n    apply (subst integral_swap_continuous [where 'a = real and 'b = real, of 0 0 1 1, simplified])\n    subgoal\n      by (rule fgh gvcon' hvcon' continuous_intros | simp add: split_def)+\n    subgoal\n      unfolding integral_mult_left [symmetric]\n      by (simp only: mult_ac)\n    done\n  also have \"\\<dots> = contour_integral h (\\<lambda>z. contour_integral g (\\<lambda>w. f w z))\"\n    unfolding contour_integral_integral integral_mult_left [symmetric]\n    by (simp add: algebra_simps)\n  finally show ?thesis\n    by (simp add: contour_integral_integral)\nqed\n\nlemma valid_path_negatepath: \"valid_path \\<gamma> \\<Longrightarrow> valid_path (uminus \\<circ> \\<gamma>)\"\n   unfolding o_def using piecewise_C1_differentiable_neg valid_path_def by blast\n\nlemma has_contour_integral_negatepath:\n  assumes \\<gamma>: \"valid_path \\<gamma>\" and cint: \"((\\<lambda>z. f (- z)) has_contour_integral - i) \\<gamma>\"\n  shows \"(f has_contour_integral i) (uminus \\<circ> \\<gamma>)\"\nproof -\n  obtain S where cont: \"continuous_on {0..1} \\<gamma>\" and \"finite S\" and diff: \"\\<gamma> C1_differentiable_on {0..1} - S\"\n    using \\<gamma> by (auto simp: valid_path_def piecewise_C1_differentiable_on_def)\n  have \"((\\<lambda>x. - (f (- \\<gamma> x) * vector_derivative \\<gamma> (at x within {0..1}))) has_integral i) {0..1}\"\n    using cint by (auto simp: has_contour_integral_def dest: has_integral_neg)\n  then\n  have \"((\\<lambda>x. f (- \\<gamma> x) * vector_derivative (uminus \\<circ> \\<gamma>) (at x within {0..1})) has_integral i) {0..1}\"\n  proof (rule rev_iffD1 [OF _ has_integral_spike_eq])\n    show \"negligible S\"\n      by (simp add: \\<open>finite S\\<close> negligible_finite)\n    show \"f (- \\<gamma> x) * vector_derivative (uminus \\<circ> \\<gamma>) (at x within {0..1}) =\n         - (f (- \\<gamma> x) * vector_derivative \\<gamma> (at x within {0..1}))\"\n      if \"x \\<in> {0..1} - S\" for x\n    proof -\n      have \"vector_derivative (uminus \\<circ> \\<gamma>) (at x within cbox 0 1) = - vector_derivative \\<gamma> (at x within cbox 0 1)\"\n      proof (rule vector_derivative_within_cbox)\n        show \"(uminus \\<circ> \\<gamma> has_vector_derivative - vector_derivative \\<gamma> (at x within cbox 0 1)) (at x within cbox 0 1)\"\n          using that unfolding o_def\n          by (metis C1_differentiable_on_eq UNIV_I diff differentiable_subset has_vector_derivative_minus subsetI that vector_derivative_works)\n      qed (use that in auto)\n      then show ?thesis\n        by simp\n    qed\n  qed\n  then show ?thesis by (simp add: has_contour_integral_def)\nqed\n\nlemma contour_integrable_negatepath:\n  assumes \\<gamma>: \"valid_path \\<gamma>\" and pi: \"(\\<lambda>z. f (- z)) contour_integrable_on \\<gamma>\"\n  shows \"f contour_integrable_on (uminus \\<circ> \\<gamma>)\"\n  by (metis \\<gamma> add.inverse_inverse contour_integrable_on_def has_contour_integral_negatepath pi)\n\nlemma C1_differentiable_polynomial_function:\n  fixes p :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"polynomial_function p \\<Longrightarrow> p C1_differentiable_on S\"\n  by (metis continuous_on_polymonial_function C1_differentiable_on_def  has_vector_derivative_polynomial_function)\n\nlemma valid_path_polynomial_function:\n  fixes p :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"polynomial_function p \\<Longrightarrow> valid_path p\"\nby (force simp: valid_path_def piecewise_C1_differentiable_on_def continuous_on_polymonial_function C1_differentiable_polynomial_function)\n\nlemma valid_path_subpath_trivial [simp]:\n    fixes g :: \"real \\<Rightarrow> 'a::euclidean_space\"\n    shows \"z \\<noteq> g x \\<Longrightarrow> valid_path (subpath x x g)\"\n  by (simp add: subpath_def valid_path_polynomial_function)\n\nsubsection\\<open>Partial circle path\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> part_circlepath :: \"[complex, real, real, real, real] \\<Rightarrow> complex\"\n  where \"part_circlepath z r s t \\<equiv> \\<lambda>x. z + of_real r * exp (\\<i> * of_real (linepath s t x))\"\n\nlemma pathstart_part_circlepath [simp]:\n     \"pathstart(part_circlepath z r s t) = z + r*exp(\\<i> * s)\"\nby (metis part_circlepath_def pathstart_def pathstart_linepath)\n\nlemma pathfinish_part_circlepath [simp]:\n     \"pathfinish(part_circlepath z r s t) = z + r*exp(\\<i>*t)\"\nby (metis part_circlepath_def pathfinish_def pathfinish_linepath)\n\nlemma reversepath_part_circlepath[simp]:\n    \"reversepath (part_circlepath z r s t) = part_circlepath z r t s\"\n  unfolding part_circlepath_def reversepath_def linepath_def\n  by (auto simp:algebra_simps)\n\nlemma has_vector_derivative_part_circlepath [derivative_intros]:\n    \"((part_circlepath z r s t) has_vector_derivative\n      (\\<i> * r * (of_real t - of_real s) * exp(\\<i> * linepath s t x)))\n     (at x within X)\"\n  unfolding part_circlepath_def linepath_def scaleR_conv_of_real\n  by (rule has_vector_derivative_real_field derivative_eq_intros | simp)+\n\nlemma differentiable_part_circlepath:\n  \"part_circlepath c r a b differentiable at x within A\"\n  using has_vector_derivative_part_circlepath[of c r a b x A] differentiableI_vector by blast\n\nlemma vector_derivative_part_circlepath:\n    \"vector_derivative (part_circlepath z r s t) (at x) =\n       \\<i> * r * (of_real t - of_real s) * exp(\\<i> * linepath s t x)\"\n  using has_vector_derivative_part_circlepath vector_derivative_at by blast\n\nlemma vector_derivative_part_circlepath01:\n    \"\\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk>\n     \\<Longrightarrow> vector_derivative (part_circlepath z r s t) (at x within {0..1}) =\n          \\<i> * r * (of_real t - of_real s) * exp(\\<i> * linepath s t x)\"\n  using has_vector_derivative_part_circlepath\n  by (auto simp: vector_derivative_at_within_ivl)\n\nlemma valid_path_part_circlepath [simp]: \"valid_path (part_circlepath z r s t)\"\n  unfolding valid_path_def\n  by (auto simp: C1_differentiable_on_eq vector_derivative_works vector_derivative_part_circlepath has_vector_derivative_part_circlepath\n              intro!: C1_differentiable_imp_piecewise continuous_intros)\n\nlemma path_part_circlepath [simp]: \"path (part_circlepath z r s t)\"\n  by (simp add: valid_path_imp_path)\n\nproposition path_image_part_circlepath:\n  assumes \"s \\<le> t\"\n    shows \"path_image (part_circlepath z r s t) = {z + r * exp(\\<i> * of_real x) | x. s \\<le> x \\<and> x \\<le> t}\"\nproof -\n  { fix z::real\n    assume \"0 \\<le> z\" \"z \\<le> 1\"\n    with \\<open>s \\<le> t\\<close> have \"\\<exists>x. (exp (\\<i> * linepath s t z) = exp (\\<i> * of_real x)) \\<and> s \\<le> x \\<and> x \\<le> t\"\n      apply (rule_tac x=\"(1 - z) * s + z * t\" in exI)\n      apply (simp add: linepath_def scaleR_conv_of_real algebra_simps)\n      by (metis (no_types) affine_ineq mult.commute mult_left_mono)\n  }\n  moreover\n  { fix z\n    assume \"s \\<le> z\" \"z \\<le> t\"\n    then have \"z + of_real r * exp (\\<i> * of_real z) \\<in> (\\<lambda>x. z + of_real r * exp (\\<i> * linepath s t x)) ` {0..1}\"\n      apply (rule_tac x=\"(z - s)/(t - s)\" in image_eqI)\n      apply (simp add: linepath_def scaleR_conv_of_real divide_simps exp_eq)\n      apply (auto simp: field_split_simps)\n      done\n  }\n  ultimately show ?thesis\n    by (fastforce simp add: path_image_def part_circlepath_def)\nqed\n\nlemma path_image_part_circlepath':\n  \"path_image (part_circlepath z r s t) = (\\<lambda>x. z + r * cis x) ` closed_segment s t\"\nproof -\n  have \"path_image (part_circlepath z r s t) =\n          (\\<lambda>x. z + r * exp(\\<i> * of_real x)) ` linepath s t ` {0..1}\"\n    by (simp add: image_image path_image_def part_circlepath_def)\n  also have \"linepath s t ` {0..1} = closed_segment s t\"\n    by (rule linepath_image_01)\n  finally show ?thesis by (simp add: cis_conv_exp)\nqed\n\nlemma path_image_part_circlepath_subset:\n    \"\\<lbrakk>s \\<le> t; 0 \\<le> r\\<rbrakk> \\<Longrightarrow> path_image(part_circlepath z r s t) \\<subseteq> sphere z r\"\nby (auto simp: path_image_part_circlepath sphere_def dist_norm algebra_simps norm_mult)\n\nlemma in_path_image_part_circlepath:\n  assumes \"w \\<in> path_image(part_circlepath z r s t)\" \"s \\<le> t\" \"0 \\<le> r\"\n    shows \"norm(w - z) = r\"\nproof -\n  have \"w \\<in> {c. dist z c = r}\"\n    by (metis (no_types) path_image_part_circlepath_subset sphere_def subset_eq assms)\n  thus ?thesis\n    by (simp add: dist_norm norm_minus_commute)\nqed\n\nlemma path_image_part_circlepath_subset':\n  assumes \"r \\<ge> 0\"\n  shows   \"path_image (part_circlepath z r s t) \\<subseteq> sphere z r\"\nproof (cases \"s \\<le> t\")\n  case True\n  thus ?thesis using path_image_part_circlepath_subset[of s t r z] assms by simp\nnext\n  case False\n  thus ?thesis using path_image_part_circlepath_subset[of t s r z] assms\n    by (subst reversepath_part_circlepath [symmetric], subst path_image_reversepath) simp_all\nqed\n\nlemma part_circlepath_cnj: \"cnj (part_circlepath c r a b x) = part_circlepath (cnj c) r (-a) (-b) x\"\n  by (simp add: part_circlepath_def exp_cnj linepath_def algebra_simps)\n\nlemma contour_integral_bound_part_circlepath:\n  assumes \"f contour_integrable_on part_circlepath c r a b\"\n  assumes \"B \\<ge> 0\" \"r \\<ge> 0\" \"\\<And>x. x \\<in> path_image (part_circlepath c r a b) \\<Longrightarrow> norm (f x) \\<le> B\"\n  shows   \"norm (contour_integral (part_circlepath c r a b) f) \\<le> B * r * \\<bar>b - a\\<bar>\"\nproof -\n  let ?I = \"integral {0..1} (\\<lambda>x. f (part_circlepath c r a b x) * \\<i> * of_real (r * (b - a)) *\n              exp (\\<i> * linepath a b x))\"\n  have \"norm ?I \\<le> integral {0..1} (\\<lambda>x::real. B * 1 * (r * \\<bar>b - a\\<bar>) * 1)\"\n  proof (rule integral_norm_bound_integral, goal_cases)\n    case 1\n    with assms(1) show ?case\n      by (simp add: contour_integrable_on vector_derivative_part_circlepath mult_ac)\n  next\n    case (3 x)\n    with assms(2-) show ?case unfolding norm_mult norm_of_real abs_mult\n      by (intro mult_mono) (auto simp: path_image_def)\n  qed auto\n  also have \"?I = contour_integral (part_circlepath c r a b) f\"\n    by (simp add: contour_integral_integral vector_derivative_part_circlepath mult_ac)\n  finally show ?thesis by simp\nqed\n\nlemma has_contour_integral_part_circlepath_iff:\n  assumes \"a < b\"\n  shows \"(f has_contour_integral I) (part_circlepath c r a b) \\<longleftrightarrow>\n           ((\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) has_integral I) {a..b}\"\nproof -\n  have \"(f has_contour_integral I) (part_circlepath c r a b) \\<longleftrightarrow>\n          ((\\<lambda>x. f (part_circlepath c r a b x) * vector_derivative (part_circlepath c r a b)\n           (at x within {0..1})) has_integral I) {0..1}\"\n    unfolding has_contour_integral_def ..\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. f (part_circlepath c r a b x) * r * (b - a) * \\<i> *\n                            cis (linepath a b x)) has_integral I) {0..1}\"\n    by (intro has_integral_cong, subst vector_derivative_part_circlepath01)\n       (simp_all add: cis_conv_exp)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. f (c + r * exp (\\<i> * linepath (of_real a) (of_real b) x)) *\n                       r * \\<i> * exp (\\<i> * linepath (of_real a) (of_real b) x) *\n                       vector_derivative (linepath (of_real a) (of_real b))\n                         (at x within {0..1})) has_integral I) {0..1}\"\n    by (intro has_integral_cong, subst vector_derivative_linepath_within)\n       (auto simp: part_circlepath_def cis_conv_exp of_real_linepath [symmetric])\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>z. f (c + r * exp (\\<i> * z)) * r * \\<i> * exp (\\<i> * z)) has_contour_integral I)\n                      (linepath (of_real a) (of_real b))\"\n    by (simp add: has_contour_integral_def)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) has_integral I) {a..b}\" using assms\n    by (subst has_contour_integral_linepath_Reals_iff) (simp_all add: cis_conv_exp)\n  finally show ?thesis .\nqed\n\nlemma contour_integrable_part_circlepath_iff:\n  assumes \"a < b\"\n  shows \"f contour_integrable_on (part_circlepath c r a b) \\<longleftrightarrow>\n           (\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) integrable_on {a..b}\"\n  using assms by (auto simp: contour_integrable_on_def integrable_on_def\n                             has_contour_integral_part_circlepath_iff)\n\nlemma contour_integral_part_circlepath_eq:\n  assumes \"a < b\"\n  shows \"contour_integral (part_circlepath c r a b) f =\n           integral {a..b} (\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t)\"\nproof (cases \"f contour_integrable_on part_circlepath c r a b\")\n  case True\n  hence \"(\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) integrable_on {a..b}\"\n    using assms by (simp add: contour_integrable_part_circlepath_iff)\n  with True show ?thesis\n    using has_contour_integral_part_circlepath_iff[OF assms]\n          contour_integral_unique has_integral_integrable_integral by blast\nnext\n  case False\n  hence \"\\<not>(\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) integrable_on {a..b}\"\n    using assms by (simp add: contour_integrable_part_circlepath_iff)\n  with False show ?thesis\n    by (simp add: not_integrable_contour_integral not_integrable_integral)\nqed\n\nlemma contour_integral_part_circlepath_reverse:\n  \"contour_integral (part_circlepath c r a b) f = -contour_integral (part_circlepath c r b a) f\"\n  by (metis contour_integral_reversepath reversepath_part_circlepath valid_path_part_circlepath)\n\nlemma contour_integral_part_circlepath_reverse':\n  \"b < a \\<Longrightarrow> contour_integral (part_circlepath c r a b) f =\n               -contour_integral (part_circlepath c r b a) f\"\n  by (rule contour_integral_part_circlepath_reverse)\n\nlemma finite_bounded_log: \"finite {z::complex. norm z \\<le> b \\<and> exp z = w}\"\nproof (cases \"w = 0\")\n  case True then show ?thesis by auto\nnext\n  case False\n  have *: \"finite {x. cmod ((2 * real_of_int x * pi) * \\<i>) \\<le> b + cmod (Ln w)}\"\n  proof (simp add: norm_mult finite_int_iff_bounded_le)\n    show \"\\<exists>k. abs ` {x. 2 * \\<bar>of_int x\\<bar> * pi \\<le> b + cmod (Ln w)} \\<subseteq> {..k}\"\n    apply (rule_tac x=\"\\<lfloor>(b + cmod (Ln w)) / (2*pi)\\<rfloor>\" in exI)\n    apply (auto simp: field_split_simps le_floor_iff)\n      done\n  qed\n  have [simp]: \"\\<And>P f. {z. P z \\<and> (\\<exists>n. z = f n)} = f ` {n. P (f n)}\"\n    by blast\n  have \"finite {z. cmod z \\<le> b \\<and> exp z = exp (Ln w)}\"\n    using norm_add_leD by (fastforce intro: finite_subset [OF _ *] simp: exp_eq)\n  then show ?thesis\n    using False by auto\nqed\n\nlemma finite_bounded_log2:\n  fixes a::complex\n    assumes \"a \\<noteq> 0\"\n    shows \"finite {z. norm z \\<le> b \\<and> exp(a*z) = w}\"\nproof -\n  have *: \"finite ((\\<lambda>z. z / a) ` {z. cmod z \\<le> b * cmod a \\<and> exp z = w})\"\n    by (rule finite_imageI [OF finite_bounded_log])\n  show ?thesis\n    by (rule finite_subset [OF _ *]) (force simp: assms norm_mult)\nqed\n\nlemma has_contour_integral_bound_part_circlepath_strong:\n  assumes fi: \"(f has_contour_integral i) (part_circlepath z r s t)\"\n      and \"finite k\" and le: \"0 \\<le> B\" \"0 < r\" \"s \\<le> t\"\n      and B: \"\\<And>x. x \\<in> path_image(part_circlepath z r s t) - k \\<Longrightarrow> norm(f x) \\<le> B\"\n    shows \"cmod i \\<le> B * r * (t - s)\"\nproof -\n  consider \"s = t\" | \"s < t\" using \\<open>s \\<le> t\\<close> by linarith\n  then show ?thesis\n  proof cases\n    case 1 with fi [unfolded has_contour_integral]\n    have \"i = 0\"  by (simp add: vector_derivative_part_circlepath)\n    with assms show ?thesis by simp\n  next\n    case 2\n    have [simp]: \"\\<bar>r\\<bar> = r\" using \\<open>r > 0\\<close> by linarith\n    have [simp]: \"cmod (complex_of_real t - complex_of_real s) = t-s\"\n      by (metis \"2\" abs_of_pos diff_gt_0_iff_gt norm_of_real of_real_diff)\n    have \"finite (part_circlepath z r s t -` {y} \\<inter> {0..1})\" if \"y \\<in> k\" for y\n    proof -\n      let ?w = \"(y - z)/of_real r / exp(\\<i> * of_real s)\"\n      have fin: \"finite (of_real -` {z. cmod z \\<le> 1 \\<and> exp (\\<i> * complex_of_real (t - s) * z) = ?w})\"\n        using \\<open>s < t\\<close>\n        by (intro finite_vimageI [OF finite_bounded_log2]) (auto simp: inj_of_real)\n      show ?thesis\n        unfolding part_circlepath_def linepath_def vimage_def\n        using le\n        by (intro finite_subset [OF _ fin]) (auto simp: algebra_simps scaleR_conv_of_real exp_add exp_diff)\n    qed\n    then have fin01: \"finite ((part_circlepath z r s t) -` k \\<inter> {0..1})\"\n      by (rule finite_finite_vimage_IntI [OF \\<open>finite k\\<close>])\n    have **: \"((\\<lambda>x. if (part_circlepath z r s t x) \\<in> k then 0\n                    else f(part_circlepath z r s t x) *\n                       vector_derivative (part_circlepath z r s t) (at x)) has_integral i)  {0..1}\"\n      by (rule has_integral_spike [OF negligible_finite [OF fin01]])  (use fi has_contour_integral in auto)\n    have *: \"\\<And>x. \\<lbrakk>0 \\<le> x; x \\<le> 1; part_circlepath z r s t x \\<notin> k\\<rbrakk> \\<Longrightarrow> cmod (f (part_circlepath z r s t x)) \\<le> B\"\n      by (auto intro!: B [unfolded path_image_def image_def])\n    show ?thesis\n      apply (rule has_integral_bound [where 'a=real, simplified, OF _ **, simplified])\n      using assms le * \"2\" \\<open>r > 0\\<close> by (auto simp add: norm_mult vector_derivative_part_circlepath)\n  qed\nqed\n\ncorollary contour_integral_bound_part_circlepath_strong:\n  assumes \"f contour_integrable_on part_circlepath z r s t\"\n      and \"finite k\" and \"0 \\<le> B\" \"0 < r\" \"s \\<le> t\"\n      and \"\\<And>x. x \\<in> path_image(part_circlepath z r s t) - k \\<Longrightarrow> norm(f x) \\<le> B\"\n    shows \"cmod (contour_integral (part_circlepath z r s t) f) \\<le> B * r * (t - s)\"\n  using assms has_contour_integral_bound_part_circlepath_strong has_contour_integral_integral by blast\n\nlemma has_contour_integral_bound_part_circlepath:\n      \"\\<lbrakk>(f has_contour_integral i) (part_circlepath z r s t);\n        0 \\<le> B; 0 < r; s \\<le> t;\n        \\<And>x. x \\<in> path_image(part_circlepath z r s t) \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n       \\<Longrightarrow> norm i \\<le> B*r*(t - s)\"\n  by (auto intro: has_contour_integral_bound_part_circlepath_strong)\n\nlemma contour_integrable_continuous_part_circlepath:\n     \"continuous_on (path_image (part_circlepath z r s t)) f\n      \\<Longrightarrow> f contour_integrable_on (part_circlepath z r s t)\"\n  unfolding contour_integrable_on has_contour_integral_def vector_derivative_part_circlepath path_image_def\n  by (best intro: integrable_continuous_real path_part_circlepath [unfolded path_def] continuous_intros \n      continuous_on_compose2 [where g=f, OF _ _ order_refl])\n\nlemma simple_path_part_circlepath:\n    \"simple_path(part_circlepath z r s t) \\<longleftrightarrow> (r \\<noteq> 0 \\<and> s \\<noteq> t \\<and> \\<bar>s - t\\<bar> \\<le> 2*pi)\"\nproof (cases \"r = 0 \\<or> s = t\")\n  case True\n  then show ?thesis\n    unfolding part_circlepath_def simple_path_def loop_free_def\n    by (rule disjE) (force intro: bexI [where x = \"1/4\"] bexI [where x = \"1/3\"])+\nnext\n  case False then have \"r \\<noteq> 0\" \"s \\<noteq> t\" by auto\n  have *: \"\\<And>x y z s t. \\<i>*((1 - x) * s + x * t) = \\<i>*(((1 - y) * s + y * t)) + z  \\<longleftrightarrow> \\<i>*(x - y) * (t - s) = z\"\n    by (simp add: algebra_simps)\n  have abs01: \"\\<And>x y::real. 0 \\<le> x \\<and> x \\<le> 1 \\<and> 0 \\<le> y \\<and> y \\<le> 1\n                      \\<Longrightarrow> (x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0 \\<longleftrightarrow> \\<bar>x - y\\<bar> \\<in> {0,1})\"\n    by auto\n  have **: \"\\<And>x y. (\\<exists>n. (complex_of_real x - of_real y) * (of_real t - of_real s) = 2 * (of_int n * of_real pi)) \\<longleftrightarrow>\n                  (\\<exists>n. \\<bar>x - y\\<bar> * (t - s) = 2 * (of_int n * pi))\"\n    by (force simp: algebra_simps abs_if dest: arg_cong [where f=Re] arg_cong [where f=complex_of_real]\n                    intro: exI [where x = \"-n\" for n])\n  have 1: \"\\<bar>s - t\\<bar> \\<le> 2 * pi\"\n    if \"\\<And>x. 0 \\<le> x \\<and> x \\<le> 1 \\<Longrightarrow> (\\<exists>n. x * (t - s) = 2 * (real_of_int n * pi)) \\<longrightarrow> x = 0 \\<or> x = 1\"\n  proof (rule ccontr)\n    assume \"\\<not> \\<bar>s - t\\<bar> \\<le> 2 * pi\"\n    then have *: \"\\<And>n. t - s \\<noteq> of_int n * \\<bar>s - t\\<bar>\"\n      using False that [of \"2*pi / \\<bar>t - s\\<bar>\"]\n      by (simp add: abs_minus_commute divide_simps)\n    show False\n      using * [of 1] * [of \"-1\"] by auto\n  qed\n  have 2: \"\\<bar>s - t\\<bar> = \\<bar>2 * (real_of_int n * pi) / x\\<bar>\" if \"x \\<noteq> 0\" \"x * (t - s) = 2 * (real_of_int n * pi)\" for x n\n  proof -\n    have \"t-s = 2 * (real_of_int n * pi)/x\"\n      using that by (simp add: field_simps)\n    then show ?thesis by (metis abs_minus_commute)\n  qed\n  have abs_away: \"\\<And>P. (\\<forall>x\\<in>{0..1}. \\<forall>y\\<in>{0..1}. P \\<bar>x - y\\<bar>) \\<longleftrightarrow> (\\<forall>x::real. 0 \\<le> x \\<and> x \\<le> 1 \\<longrightarrow> P x)\"\n    by force\n  show ?thesis using False\n    apply (simp add: simple_path_def loop_free_def)\n    apply (simp add: part_circlepath_def linepath_def exp_eq  * ** abs01 del: Set.insert_iff)\n    apply (subst abs_away)\n    apply (auto simp: 1)\n    apply (rule ccontr)\n    apply (auto simp: 2 field_split_simps abs_mult dest: of_int_leD)\n    done\nqed\n\nlemma arc_part_circlepath:\n  assumes \"r \\<noteq> 0\" \"s \\<noteq> t\" \"\\<bar>s - t\\<bar> < 2*pi\"\n    shows \"arc (part_circlepath z r s t)\"\nproof -\n  have *: \"x = y\" if eq: \"\\<i> * (linepath s t x) = \\<i> * (linepath s t y) + 2 * of_int n * complex_of_real pi * \\<i>\"\n    and x: \"x \\<in> {0..1}\" and y: \"y \\<in> {0..1}\" for x y n\n  proof (rule ccontr)\n    assume \"x \\<noteq> y\"\n    have \"(linepath s t x) = (linepath s t y) + 2 * of_int n * complex_of_real pi\"\n      by (metis add_divide_eq_iff complex_i_not_zero mult.commute nonzero_mult_div_cancel_left eq)\n    then have \"s*y + t*x = s*x + (t*y + of_int n * (pi * 2))\"\n      by (force simp: algebra_simps linepath_def dest: arg_cong [where f=Re])\n    with \\<open>x \\<noteq> y\\<close> have st: \"s-t = (of_int n * (pi * 2) / (y-x))\"\n      by (force simp: field_simps)\n    have \"\\<bar>real_of_int n\\<bar> < \\<bar>y - x\\<bar>\"\n      using assms \\<open>x \\<noteq> y\\<close> by (simp add: st abs_mult field_simps)\n    then show False\n      using assms x y st by (auto dest: of_int_lessD)\n  qed\n  then have \"inj_on (part_circlepath z r s t) {0..1}\"\n    using assms by (force simp add: part_circlepath_def inj_on_def exp_eq)\n  then show ?thesis\n    by (simp add: arc_def)\nqed\n\nsubsection\\<open>Special case of one complete circle\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> circlepath :: \"[complex, real, real] \\<Rightarrow> complex\"\n  where \"circlepath z r \\<equiv> part_circlepath z r 0 (2*pi)\"\n\nlemma circlepath: \"circlepath z r = (\\<lambda>x. z + r * exp(2 * of_real pi * \\<i> * of_real x))\"\n  by (simp add: circlepath_def part_circlepath_def linepath_def algebra_simps)\n\nlemma pathstart_circlepath [simp]: \"pathstart (circlepath z r) = z + r\"\n  by (simp add: circlepath_def)\n\nlemma pathfinish_circlepath [simp]: \"pathfinish (circlepath z r) = z + r\"\n  by (simp add: circlepath_def) (metis exp_two_pi_i mult.commute)\n\nlemma circlepath_minus: \"circlepath z (-r) x = circlepath z r (x + 1/2)\"\nproof -\n  have \"z + of_real r * exp (2 * pi * \\<i> * (x + 1/2)) =\n        z + of_real r * exp (2 * pi * \\<i> * x + pi * \\<i>)\"\n    by (simp add: divide_simps) (simp add: algebra_simps)\n  also have \"\\<dots> = z - r * exp (2 * pi * \\<i> * x)\"\n    by (simp add: exp_add)\n  finally show ?thesis\n    by (simp add: circlepath path_image_def sphere_def dist_norm)\nqed\n\nlemma circlepath_add1: \"circlepath z r (x+1) = circlepath z r x\"\n  using circlepath_minus [of z r \"x+1/2\"] circlepath_minus [of z \"-r\" x]\n  by (simp add: add.commute)\n\nlemma circlepath_add_half: \"circlepath z r (x + 1/2) = circlepath z r (x - 1/2)\"\n  using circlepath_add1 [of z r \"x-1/2\"]\n  by (simp add: add.commute)\n\nlemma path_image_circlepath_minus_subset:\n     \"path_image (circlepath z (-r)) \\<subseteq> path_image (circlepath z r)\"\nproof -\n  have \"\\<exists>x\\<in>{0..1}. circlepath z r (y + 1/2) = circlepath z r x\"\n    if \"0 \\<le> y\" \"y \\<le> 1\" for y\n  proof (cases \"y \\<le> 1/2\")\n    case False\n    with that show ?thesis\n      by (force simp: circlepath_add_half)\n  qed (use that in force)\n  then show ?thesis\n    by (auto simp add: path_image_def image_def circlepath_minus)\nqed\n\nlemma path_image_circlepath_minus: \"path_image (circlepath z (-r)) = path_image (circlepath z r)\"\n  using path_image_circlepath_minus_subset by fastforce\n\nlemma has_vector_derivative_circlepath [derivative_intros]:\n \"((circlepath z r) has_vector_derivative (2 * pi * \\<i> * r * exp (2 * of_real pi * \\<i> * x)))\n   (at x within X)\"\n  unfolding circlepath_def scaleR_conv_of_real\n  by (rule derivative_eq_intros) (simp add: algebra_simps)\n\nlemma vector_derivative_circlepath:\n  \"vector_derivative (circlepath z r) (at x) =\n    2 * pi * \\<i> * r * exp(2 * of_real pi * \\<i> * x)\"\n  using has_vector_derivative_circlepath vector_derivative_at by blast\n\nlemma vector_derivative_circlepath01:\n    \"\\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk>\n     \\<Longrightarrow> vector_derivative (circlepath z r) (at x within {0..1}) =\n          2 * pi * \\<i> * r * exp(2 * of_real pi * \\<i> * x)\"\n  using has_vector_derivative_circlepath\n  by (auto simp: vector_derivative_at_within_ivl)\n\nlemma valid_path_circlepath [simp]: \"valid_path (circlepath z r)\"\n  by (simp add: circlepath_def)\n\nlemma path_circlepath [simp]: \"path (circlepath z r)\"\n  by (simp add: valid_path_imp_path)\n\nlemma path_image_circlepath_nonneg:\n  assumes \"0 \\<le> r\" shows \"path_image (circlepath z r) = sphere z r\"\nproof -\n  have *: \"x \\<in> (\\<lambda>u. z + (cmod (x - z)) * exp (\\<i> * (of_real u * (of_real pi * 2)))) ` {0..1}\" for x\n  proof (cases \"x = z\")\n    case True then show ?thesis by force\n  next\n    case False\n    define w where \"w = x - z\"\n    then have \"w \\<noteq> 0\" by (simp add: False)\n    have **: \"\\<And>t. \\<lbrakk>Re w = cos t * cmod w; Im w = sin t * cmod w\\<rbrakk> \\<Longrightarrow> w = of_real (cmod w) * exp (\\<i> * t)\"\n      using cis_conv_exp complex_eq_iff by auto\n    obtain t where \"0 \\<le> t\" \"t < 2*pi\" \"Re(w/norm w) = cos t\" \"Im(w/norm w) = sin t\"\n      apply (rule sincos_total_2pi [of \"Re(w/(norm w))\" \"Im(w/(norm w))\"])\n      by (auto simp add: divide_simps \\<open>w \\<noteq> 0\\<close> cmod_power2 [symmetric])\n    then\n    show ?thesis\n      using False ** w_def \\<open>w \\<noteq> 0\\<close>\n      by (rule_tac x=\"t / (2*pi)\" in image_eqI) (auto simp add: field_simps)\n  qed\n  show ?thesis\n    unfolding circlepath path_image_def sphere_def dist_norm\n    by (force simp: assms algebra_simps norm_mult norm_minus_commute intro: *)\nqed\n\nlemma path_image_circlepath [simp]:\n    \"path_image (circlepath z r) = sphere z \\<bar>r\\<bar>\"\n  using path_image_circlepath_minus\n  by (force simp: path_image_circlepath_nonneg abs_if)\n\nlemma has_contour_integral_bound_circlepath_strong:\n      \"\\<lbrakk>(f has_contour_integral i) (circlepath z r);\n        finite k; 0 \\<le> B; 0 < r;\n        \\<And>x. \\<lbrakk>norm(x - z) = r; x \\<notin> k\\<rbrakk> \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n        \\<Longrightarrow> norm i \\<le> B*(2*pi*r)\"\n  unfolding circlepath_def\n  by (auto simp: algebra_simps in_path_image_part_circlepath dest!: has_contour_integral_bound_part_circlepath_strong)\n\nlemma has_contour_integral_bound_circlepath:\n      \"\\<lbrakk>(f has_contour_integral i) (circlepath z r);\n        0 \\<le> B; 0 < r; \\<And>x. norm(x - z) = r \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n        \\<Longrightarrow> norm i \\<le> B*(2*pi*r)\"\n  by (auto intro: has_contour_integral_bound_circlepath_strong)\n\nlemma contour_integrable_continuous_circlepath:\n    \"continuous_on (path_image (circlepath z r)) f\n     \\<Longrightarrow> f contour_integrable_on (circlepath z r)\"\n  by (simp add: circlepath_def contour_integrable_continuous_part_circlepath)\n\nlemma simple_path_circlepath: \"simple_path(circlepath z r) \\<longleftrightarrow> (r \\<noteq> 0)\"\n  by (simp add: circlepath_def simple_path_part_circlepath)\n\nlemma notin_path_image_circlepath [simp]: \"cmod (w - z) < r \\<Longrightarrow> w \\<notin> path_image (circlepath z r)\"\n  by (simp add: sphere_def dist_norm norm_minus_commute)\n\nlemma contour_integral_circlepath:\n  assumes \"r > 0\"\n  shows \"contour_integral (circlepath z r) (\\<lambda>w. 1 / (w - z)) = 2 * complex_of_real pi * \\<i>\"\nproof (rule contour_integral_unique)\n  show \"((\\<lambda>w. 1 / (w - z)) has_contour_integral 2 * complex_of_real pi * \\<i>) (circlepath z r)\"\n    unfolding has_contour_integral_def using assms has_integral_const_real [of _ 0 1]\n    apply (subst has_integral_cong)\n     apply (simp add: vector_derivative_circlepath01)\n    apply (force simp: circlepath)\n    done\nqed\n\nsubsection\\<open> Uniform convergence of path integral\\<close>\n\ntext\\<open>Uniform convergence when the derivative of the path is bounded, and in particular for the special case of a circle.\\<close>\n\nproposition contour_integral_uniform_limit:\n  assumes ev_fint: \"eventually (\\<lambda>n::'a. (f n) contour_integrable_on \\<gamma>) F\"\n      and ul_f: \"uniform_limit (path_image \\<gamma>) f l F\"\n      and noleB: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> norm (vector_derivative \\<gamma> (at t)) \\<le> B\"\n      and \\<gamma>: \"valid_path \\<gamma>\"\n      and [simp]: \"\\<not> trivial_limit F\"\n  shows \"l contour_integrable_on \\<gamma>\" \"((\\<lambda>n. contour_integral \\<gamma> (f n)) \\<longlongrightarrow> contour_integral \\<gamma> l) F\"\nproof -\n  have \"0 \\<le> B\" by (meson noleB [of 0] atLeastAtMost_iff norm_ge_zero order_refl order_trans zero_le_one)\n  { fix e::real\n    assume \"0 < e\"\n    then have \"0 < e / (\\<bar>B\\<bar> + 1)\" by simp\n    then have \"\\<forall>\\<^sub>F n in F. \\<forall>x\\<in>path_image \\<gamma>. cmod (f n x - l x) < e / (\\<bar>B\\<bar> + 1)\"\n      using ul_f [unfolded uniform_limit_iff dist_norm] by auto\n    with ev_fint\n    obtain a where fga: \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> cmod (f a (\\<gamma> x) - l (\\<gamma> x)) < e / (\\<bar>B\\<bar> + 1)\"\n               and inta: \"(\\<lambda>t. f a (\\<gamma> t) * vector_derivative \\<gamma> (at t)) integrable_on {0..1}\"\n      using eventually_happens [OF eventually_conj]\n      by (fastforce simp: contour_integrable_on path_image_def)\n    have Ble: \"B * e / (\\<bar>B\\<bar> + 1) \\<le> e\"\n      using \\<open>0 \\<le> B\\<close>  \\<open>0 < e\\<close> by (simp add: field_split_simps)\n    have \"\\<exists>h. (\\<forall>x\\<in>{0..1}. cmod (l (\\<gamma> x) * vector_derivative \\<gamma> (at x) - h x) \\<le> e) \\<and> h integrable_on {0..1}\"\n    proof (intro exI conjI ballI)\n      show \"cmod (l (\\<gamma> x) * vector_derivative \\<gamma> (at x) - f a (\\<gamma> x) * vector_derivative \\<gamma> (at x)) \\<le> e\"\n        if \"x \\<in> {0..1}\" for x\n        apply (rule order_trans [OF _ Ble])\n        using noleB [OF that] fga [OF that] \\<open>0 \\<le> B\\<close> \\<open>0 < e\\<close>\n        apply (fastforce simp: mult_ac dest: mult_mono [OF less_imp_le] simp add: norm_mult left_diff_distrib [symmetric] norm_minus_commute divide_simps)\n        done\n    qed (rule inta)\n  }\n  then show lintg: \"l contour_integrable_on \\<gamma>\"\n    unfolding contour_integrable_on by (metis (mono_tags, lifting)integrable_uniform_limit_real)\n  { fix e::real\n    define B' where \"B' = B + 1\"\n    have B': \"B' > 0\" \"B' > B\" using  \\<open>0 \\<le> B\\<close> by (auto simp: B'_def)\n    assume \"0 < e\"\n    then have ev_no': \"\\<forall>\\<^sub>F n in F. \\<forall>x\\<in>path_image \\<gamma>. 2 * cmod (f n x - l x) < e / B'\"\n      using ul_f [unfolded uniform_limit_iff dist_norm, rule_format, of \"e / B'/2\"] B'\n        by (simp add: field_simps)\n    have ie: \"integral {0..1::real} (\\<lambda>x. e/2) < e\" using \\<open>0 < e\\<close> by simp\n    have *: \"cmod (f x (\\<gamma> t) * vector_derivative \\<gamma> (at t) - l (\\<gamma> t) * vector_derivative \\<gamma> (at t)) \\<le> e/2\"\n             if t: \"t\\<in>{0..1}\" and leB': \"2 * cmod (f x (\\<gamma> t) - l (\\<gamma> t)) < e / B'\" for x t\n    proof -\n      have \"2 * cmod (f x (\\<gamma> t) - l (\\<gamma> t)) * cmod (vector_derivative \\<gamma> (at t)) \\<le> e * (B/ B')\"\n        using mult_mono [OF less_imp_le [OF leB'] noleB] B' \\<open>0 < e\\<close> t by auto\n      also have \"\\<dots> < e\"\n        by (simp add: B' \\<open>0 < e\\<close> mult_imp_div_pos_less)\n      finally have \"2 * cmod (f x (\\<gamma> t) - l (\\<gamma> t)) * cmod (vector_derivative \\<gamma> (at t)) < e\" .\n      then show ?thesis\n        by (simp add: left_diff_distrib [symmetric] norm_mult)\n    qed\n    have le_e: \"\\<And>x. \\<lbrakk>\\<forall>u\\<in>{0..1}. 2 * cmod (f x (\\<gamma> u) - l (\\<gamma> u)) < e / B'; f x contour_integrable_on \\<gamma>\\<rbrakk>\n         \\<Longrightarrow> cmod (integral {0..1}\n                    (\\<lambda>u. f x (\\<gamma> u) * vector_derivative \\<gamma> (at u) - l (\\<gamma> u) * vector_derivative \\<gamma> (at u))) < e\"\n      apply (rule le_less_trans [OF integral_norm_bound_integral ie])\n        apply (simp add: lintg integrable_diff contour_integrable_on [symmetric])\n       apply (blast intro: *)+\n      done\n    have \"\\<forall>\\<^sub>F x in F. dist (contour_integral \\<gamma> (f x)) (contour_integral \\<gamma> l) < e\"\n      apply (rule eventually_mono [OF eventually_conj [OF ev_no' ev_fint]])\n      apply (simp add: dist_norm contour_integrable_on path_image_def contour_integral_integral)\n      apply (simp add: lintg integral_diff [symmetric] contour_integrable_on [symmetric] le_e)\n      done\n  }\n  then show \"((\\<lambda>n. contour_integral \\<gamma> (f n)) \\<longlongrightarrow> contour_integral \\<gamma> l) F\"\n    by (rule tendstoI)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> contour_integral_uniform_limit_circlepath:\n  assumes \"\\<forall>\\<^sub>F n::'a in F. (f n) contour_integrable_on (circlepath z r)\"\n      and \"uniform_limit (sphere z r) f l F\"\n      and \"\\<not> trivial_limit F\" \"0 < r\"\n    shows \"l contour_integrable_on (circlepath z r)\"\n          \"((\\<lambda>n. contour_integral (circlepath z r) (f n)) \\<longlongrightarrow> contour_integral (circlepath z r) l) F\"\n  using assms by (auto simp: vector_derivative_circlepath norm_mult intro!: contour_integral_uniform_limit)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Complex_Analysis/Contour_Integration.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7793910015649761}}
{"text": "(*  Title:      AVL Trees\n    Author:     Tobias Nipkow and Cornelia Pusch,\n                converted to Isar by Gerwin Klein\n                contributions by Achim Brucker, Burkhart Wolff and Jan Smaus\n                delete formalization and a transformation to Isar by Ondrej Kuncar\n    Maintainer: Gerwin Klein <gerwin.klein at nicta.com.au>\n\n    see the file Changelog for a list of changes\n*)\n\nsection \"AVL Trees\"\n\ntheory AVL\nimports Main\nbegin\n\ntext \\<open>\n  This is a monolithic formalization of AVL trees.\n\\<close>\n\nsubsection \\<open>AVL tree type definition\\<close>\n\ndatatype (set_of: 'a) tree = ET |  MKT 'a \"'a tree\" \"'a tree\" nat\n\nsubsection \\<open>Invariants and auxiliary functions\\<close>\n\nprimrec height :: \"'a tree \\<Rightarrow> nat\" where\n\"height ET = 0\" |\n\"height (MKT x l r h) = max (height l) (height r) + 1\"\n\nprimrec avl :: \"'a tree \\<Rightarrow> bool\" where\n\"avl ET = True\" |\n\"avl (MKT x l r h) =\n ((height l = height r \\<or> height l = height r + 1 \\<or> height r = height l + 1) \\<and> \n  h = max (height l) (height r) + 1 \\<and> avl l \\<and> avl r)\"\n\nprimrec is_ord :: \"('a::order) tree \\<Rightarrow> bool\" where\n\"is_ord ET = True\" |\n\"is_ord (MKT n l r h) =\n ((\\<forall>n' \\<in> set_of l. n' < n) \\<and> (\\<forall>n' \\<in> set_of r. n < n') \\<and> is_ord l \\<and> is_ord r)\"\n\n\nsubsection \\<open>AVL interface and implementation\\<close>\n\nprimrec is_in :: \"('a::order) \\<Rightarrow> 'a tree \\<Rightarrow> bool\" where\n \"is_in k ET = False\" |\n \"is_in k (MKT n l r h) = (if k = n then True else\n                           if k < n then (is_in k l)\n                           else (is_in k r))\"\n\nprimrec ht :: \"'a tree \\<Rightarrow> nat\" where\n\"ht ET = 0\" |\n\"ht (MKT x l r h) = h\"\n\ndefinition\n mkt :: \"'a \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"mkt x l r = MKT x l r (max (ht l) (ht r) + 1)\"\n\nfun mkt_bal_l where\n\"mkt_bal_l n l r = (\n  if ht l = ht r + 2 then (case l of \n    MKT ln ll lr _ \\<Rightarrow> (if ht ll < ht lr\n    then case lr of\n      MKT lrn lrl lrr _ \\<Rightarrow> mkt lrn (mkt ln ll lrl) (mkt n lrr r)\n    else mkt ln ll (mkt n lr r)))\n  else mkt n l r\n)\"\n\nfun mkt_bal_r where\n\"mkt_bal_r n l r = (\n  if ht r = ht l + 2 then (case r of\n    MKT rn rl rr _ \\<Rightarrow> (if ht rl > ht rr\n    then case rl of\n      MKT rln rll rlr _ \\<Rightarrow> mkt rln (mkt n l rll) (mkt rn rlr rr)\n    else mkt rn (mkt n l rl) rr))\n  else mkt n l r\n)\"\n\nprimrec insert :: \"'a::order \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"insert x ET = MKT x ET ET 1\" |\n\"insert x (MKT n l r h) = \n   (if x=n\n    then MKT n l r h\n    else if x<n\n      then mkt_bal_l n (insert x l) r\n      else mkt_bal_r n l (insert x r))\"\n\nfun delete_max where\n\"delete_max (MKT n l ET h) = (n,l)\" |\n\"delete_max (MKT n l r h) = (\n  let (n',r') = delete_max r in\n  (n',mkt_bal_l n l r'))\"\n\nlemmas delete_max_induct = delete_max.induct[case_names ET MKT]\n\nfun delete_root where\n\"delete_root (MKT n ET r h) = r\" |\n\"delete_root (MKT n l ET h) = l\" |\n\"delete_root (MKT n l r h) =  \n  (let (new_n, l') = delete_max l in\n      mkt_bal_r new_n l' r\n  )\"\n\nlemmas delete_root_cases = delete_root.cases[case_names ET_t MKT_ET MKT_MKT]\n\nprimrec delete :: \"'a::order \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"delete _ ET = ET\" |\n\"delete x (MKT n l r h) = (\n   if x = n then delete_root (MKT n l r h)\n   else if x < n then \n        let l' = delete x l in\n        mkt_bal_r n l' r\n   else \n        let r' = delete x r in\n        mkt_bal_l n l r'\n   )\"\n\nsubsection \\<open>Correctness proof\\<close>\n\nsubsubsection \\<open>Insertion maintains AVL balance\\<close>\n\ndeclare Let_def [simp]\n\n\n\nlemma height_mkt_bal_l:\n  \"\\<lbrakk> height l = height r + 2; avl l; avl r \\<rbrakk> \\<Longrightarrow>\n   height (mkt_bal_l n l r) = height r + 2 \\<or>\n   height (mkt_bal_l n l r) = height r + 3\"\nby (cases l) (auto simp:mkt_def split:tree.split)\n       \nlemma height_mkt_bal_r:\n  \"\\<lbrakk> height r = height l + 2; avl l; avl r \\<rbrakk> \\<Longrightarrow>\n   height (mkt_bal_r n l r) = height l + 2 \\<or>\n   height (mkt_bal_r n l r) = height l + 3\"\nby (cases r) (auto simp add:mkt_def split:tree.split)\n\nlemma [simp]: \"height(mkt x l r) = max (height l) (height r) + 1\"\nby (simp add: mkt_def)\n\nlemma avl_mkt:\n  \"\\<lbrakk> avl l; avl r;\n     height l = height r \\<or> height l = height r + 1 \\<or> height r = height l + 1\n   \\<rbrakk> \\<Longrightarrow> avl(mkt x l r)\"\nby (auto simp add:max_def mkt_def)\n\nlemma height_mkt_bal_l2:\n  \"\\<lbrakk> avl l; avl r; height l \\<noteq> height r + 2 \\<rbrakk> \\<Longrightarrow>\n   height (mkt_bal_l n l r) = (1 + max (height l) (height r))\"\nby (cases l, cases r) simp_all\n\nlemma height_mkt_bal_r2:\n  \"\\<lbrakk> avl l;  avl r;  height r \\<noteq> height l + 2 \\<rbrakk> \\<Longrightarrow>\n   height (mkt_bal_r n l r) = (1 + max (height l) (height r))\"\nby (cases l, cases r) simp_all\n\nlemma avl_mkt_bal_l: \n  assumes \"avl l\" \"avl r\" and \"height l = height r \\<or> height l = height r + 1\n    \\<or> height r = height l + 1 \\<or> height l = height r + 2\" \n  shows \"avl(mkt_bal_l n l r)\"\nproof(cases l)\n  case ET\n  with assms show ?thesis by (simp add: mkt_def)\nnext\n  case (MKT ln ll lr lh)\n  with assms show ?thesis\n  proof(cases \"height l = height r + 2\")\n    case True\n      from True MKT assms show ?thesis by (auto intro!: avl_mkt split: tree.split) arith+\n  next\n    case False\n      with assms show ?thesis by (simp add: avl_mkt)\n  qed\nqed\n\nlemma avl_mkt_bal_r: \n  assumes \"avl l\" and \"avl r\" and \"height l = height r \\<or> height l = height r + 1\n    \\<or> height r = height l + 1 \\<or> height r = height l + 2\" \n  shows \"avl(mkt_bal_r n l r)\"\nproof(cases r)\n  case ET\n  with assms show ?thesis by (simp add: mkt_def)\nnext\n  case (MKT rn rl rr rh)\n  with assms show ?thesis\n  proof(cases \"height r = height l + 2\")\n    case True\n      from True MKT assms show ?thesis by (auto intro!: avl_mkt split: tree.split) arith+\n  next\n    case False\n      with assms show ?thesis by (simp add: avl_mkt)\n  qed\nqed\n\n(* It apppears that these two properties need to be proved simultaneously: *)\n\ntext\\<open>Insertion maintains the AVL property:\\<close>\n\ntheorem avl_insert_aux:\n  assumes \"avl t\"\n  shows \"avl(insert x t)\"\n        \"(height (insert x t) = height t \\<or> height (insert x t) = height t + 1)\"\nusing assms\nproof (induction t)\n  case (MKT n l r h)\n  case 1\n  with MKT show ?case\n  proof(cases \"x = n\")\n    case True\n    with MKT 1 show ?thesis by simp\n  next\n    case False\n    with MKT 1 show ?thesis \n    proof(cases \"x<n\")\n      case True\n      with MKT 1 show ?thesis by (auto simp add:avl_mkt_bal_l simp del:mkt_bal_l.simps)\n    next\n      case False\n      with MKT 1 \\<open>x\\<noteq>n\\<close> show ?thesis by (auto simp add:avl_mkt_bal_r simp del:mkt_bal_r.simps)\n    qed\n  qed\n  case 2\n  from 2 MKT show ?case\n  proof(cases \"x = n\")\n    case True\n    with MKT 1 show ?thesis by simp\n  next\n    case False\n    with MKT 1 show ?thesis \n     proof(cases \"x<n\")\n      case True\n      with MKT 2 show ?thesis\n      proof(cases \"height (AVL.insert x l) = height r + 2\")\n        case False with MKT 2 \\<open>x < n\\<close> show ?thesis by (auto simp del: mkt_bal_l.simps simp: height_mkt_bal_l2)\n      next\n        case True \n        then consider (a) \"height (mkt_bal_l n (AVL.insert x l) r) = height r + 2\"\n          | (b) \"height (mkt_bal_l n (AVL.insert x l) r) = height r + 3\" \n          using MKT 2 by (atomize_elim, intro height_mkt_bal_l) simp_all\n        then show ?thesis\n        proof cases\n          case a\n          with 2 \\<open>x < n\\<close> show ?thesis by (auto simp del: mkt_bal_l.simps)\n        next\n          case b\n          with True 1 MKT(2) \\<open>x < n\\<close> show ?thesis by (simp del: mkt_bal_l.simps) arith\n        qed\n      qed\n    next\n      case False\n      with MKT 2 show ?thesis \n      proof(cases \"height (AVL.insert x r) = height l + 2\")\n        case False with MKT 2 \\<open>\\<not>x < n\\<close> show ?thesis by (auto simp del: mkt_bal_r.simps simp: height_mkt_bal_r2)\n      next\n        case True \n        then consider (a) \"height (mkt_bal_r n l (AVL.insert x r)) = height l + 2\"\n          | (b) \"height (mkt_bal_r n l (AVL.insert x r)) = height l + 3\" \n          using MKT 2 by (atomize_elim, intro height_mkt_bal_r) simp_all\n        then show ?thesis \n        proof cases\n          case a\n          with 2 \\<open>\\<not>x < n\\<close> show ?thesis by (auto simp del: mkt_bal_r.simps)\n        next\n          case b\n          with True 1 MKT(4) \\<open>\\<not>x < n\\<close> show ?thesis by (simp del: mkt_bal_r.simps) arith\n        qed\n      qed\n    qed\n  qed\nqed simp_all\n\nlemmas avl_insert = avl_insert_aux(1)\n\nsubsubsection \\<open>Deletion maintains AVL balance\\<close>\n\nlemma avl_delete_max:\n  assumes \"avl x\" and \"x \\<noteq> ET\"\n  shows \"avl (snd (delete_max x))\" \"height x = height(snd (delete_max x)) \\<or>\n         height x = height(snd (delete_max x)) + 1\"\nusing assms\nproof (induct x rule: delete_max_induct)\n  case (MKT n l rn rl rr rh h)\n  case 1\n  with MKT have \"avl l\" \"avl (snd (delete_max (MKT rn rl rr rh)))\" by auto\n  with 1 MKT have \"avl (mkt_bal_l n l (snd (delete_max (MKT rn rl rr rh))))\"\n    by (intro avl_mkt_bal_l) fastforce+\n  then show ?case \n    by (auto simp: height_mkt_bal_l height_mkt_bal_l2\n      linorder_class.max.absorb1 linorder_class.max.absorb2\n      split:prod.split simp del:mkt_bal_l.simps)\nnext\n  case (MKT n l rn rl rr rh h)\n  case 2\n  let ?r = \"MKT rn rl rr rh\"\n  let ?r' = \"snd (delete_max ?r)\"\n  from \\<open>avl x\\<close> MKT 2 have \"avl l\" and \"avl ?r\" by simp_all\n  then show ?case using MKT 2 height_mkt_bal_l[of l ?r' n] height_mkt_bal_l2[of l ?r' n]\n    apply (auto split:prod.splits simp del:avl.simps mkt_bal_l.simps) by arith+\nqed auto\n\nlemma avl_delete_root:\n  assumes \"avl t\" and \"t \\<noteq> ET\"\n  shows \"avl(delete_root t)\" \nusing assms\nproof (cases t rule:delete_root_cases)\n  case (MKT_MKT n ln ll lr lh rn rl rr rh h) \n  let ?l = \"MKT ln ll lr lh\"\n  let ?r = \"MKT rn rl rr rh\"\n  let ?l' = \"snd (delete_max ?l)\"\n  from \\<open>avl t\\<close> and MKT_MKT have \"avl ?r\" by simp\n  from \\<open>avl t\\<close> and MKT_MKT have \"avl ?l\" by simp\n  then have \"avl(?l')\" \"height ?l = height(?l') \\<or>\n         height ?l = height(?l') + 1\" by (rule avl_delete_max,simp)+\n  with \\<open>avl t\\<close> MKT_MKT have \"height ?l' = height ?r \\<or> height ?l' = height ?r + 1\n            \\<or> height ?r = height ?l' + 1 \\<or> height ?r = height ?l' + 2\" by fastforce\n  with \\<open>avl ?l'\\<close> \\<open>avl ?r\\<close> have \"avl(mkt_bal_r (fst(delete_max ?l)) ?l' ?r)\"\n    by (rule avl_mkt_bal_r)\n  with MKT_MKT show ?thesis by (auto split:prod.splits simp del:mkt_bal_r.simps)\nqed simp_all\n\nlemma height_delete_root:\n  assumes \"avl t\" and \"t \\<noteq> ET\" \n  shows \"height t = height(delete_root t) \\<or> height t = height(delete_root t) + 1\"\nusing assms\nproof (cases t rule: delete_root_cases)\n  case (MKT_MKT n ln ll lr lh rn rl rr rh h) \n  let ?l = \"MKT ln ll lr lh\"\n  let ?r = \"MKT rn rl rr rh\"\n  let ?l' = \"snd (delete_max ?l)\"\n  let ?t' = \"mkt_bal_r (fst(delete_max ?l)) ?l' ?r\"\n  from \\<open>avl t\\<close> and MKT_MKT have \"avl ?r\" by simp\n  from \\<open>avl t\\<close> and MKT_MKT have \"avl ?l\" by simp\n  then have \"avl(?l')\"  by (rule avl_delete_max,simp)\n  have l'_height: \"height ?l = height ?l' \\<or> height ?l = height ?l' + 1\" using \\<open>avl ?l\\<close> by (intro avl_delete_max) auto\n  have t_height: \"height t = 1 + max (height ?l) (height ?r)\" using \\<open>avl t\\<close> MKT_MKT by simp\n  have \"height t = height ?t' \\<or> height t = height ?t' + 1\" using  \\<open>avl t\\<close> MKT_MKT\n  proof(cases \"height ?r = height ?l' + 2\")\n    case False\n    show ?thesis using l'_height t_height False by (subst  height_mkt_bal_r2[OF \\<open>avl ?l'\\<close> \\<open>avl ?r\\<close> False])+ arith\n  next\n    case True\n    show ?thesis\n    proof(cases rule: disjE[OF height_mkt_bal_r[OF True \\<open>avl ?l'\\<close> \\<open>avl ?r\\<close>, of \"fst (delete_max ?l)\"]])\n      case 1\n      then show ?thesis using l'_height t_height True by arith\n    next\n      case 2\n      then show ?thesis using l'_height t_height True by arith\n    qed\n  qed\n  thus ?thesis using MKT_MKT by (auto split:prod.splits simp del:mkt_bal_r.simps)\nqed simp_all\n\ntext\\<open>Deletion maintains the AVL property:\\<close>\n\ntheorem avl_delete_aux:\n  assumes \"avl t\" \n  shows \"avl(delete x t)\" and \"height t = (height (delete x t)) \\<or> height t = height (delete x t) + 1\"\nusing assms\nproof (induct t)\n  case (MKT n l r h)\n  case 1\n  with MKT show ?case\n  proof(cases \"x = n\")\n    case True\n    with MKT 1 show ?thesis by (auto simp:avl_delete_root)\n  next\n    case False\n    with MKT 1 show ?thesis \n    proof(cases \"x<n\")\n      case True\n      with MKT 1 show ?thesis by (auto simp add:avl_mkt_bal_r simp del:mkt_bal_r.simps)\n    next\n      case False\n      with MKT 1 \\<open>x\\<noteq>n\\<close> show ?thesis by (auto simp add:avl_mkt_bal_l simp del:mkt_bal_l.simps)\n    qed\n  qed\n  case 2\n  with MKT show ?case\n  proof(cases \"x = n\")\n    case True\n    with 1 have \"height (MKT n l r h) = height(delete_root (MKT n l r h))\n      \\<or> height (MKT n l r h) = height(delete_root (MKT n l r h)) + 1\"\n      by (subst height_delete_root,simp_all)\n    with True show ?thesis by simp\n  next\n    case False\n    with MKT 1 show ?thesis \n     proof(cases \"x<n\")\n      case True\n      show ?thesis\n      proof(cases \"height r = height (delete x l) + 2\")\n        case False with MKT 1 \\<open>x < n\\<close> show ?thesis by auto\n      next\n        case True \n        then consider (a) \"height (mkt_bal_r n (delete x l) r) = height (delete x l) + 2\"\n          | (b) \"height (mkt_bal_r n (delete x l) r) = height (delete x l) + 3\"\n          using MKT 2 by (atomize_elim, intro height_mkt_bal_r) auto\n        then show ?thesis \n        proof cases\n          case a\n          with \\<open>x < n\\<close> MKT 2 show ?thesis by auto\n        next\n          case b\n          with \\<open>x < n\\<close> MKT 2 show ?thesis by auto\n        qed\n      qed\n    next\n      case False\n      show ?thesis\n      proof(cases \"height l = height (delete x r) + 2\")\n        case False with MKT 1 \\<open>\\<not>x < n\\<close> \\<open>x \\<noteq> n\\<close> show ?thesis by auto\n      next\n        case True \n        then consider (a) \"height (mkt_bal_l n l (delete x r)) = height (delete x r) + 2\"\n          | (b) \"height (mkt_bal_l n l (delete x r)) = height (delete x r) + 3\" \n          using MKT 2 by (atomize_elim, intro height_mkt_bal_l) auto\n        then show ?thesis \n        proof cases\n          case a\n          with \\<open>\\<not>x < n\\<close> \\<open>x \\<noteq> n\\<close> MKT 2 show ?thesis by auto\n        next\n          case b\n          with \\<open>\\<not>x < n\\<close> \\<open>x \\<noteq> n\\<close> MKT 2 show ?thesis by auto\n        qed\n      qed\n    qed\n  qed\nqed simp_all\n\nlemmas avl_delete = avl_delete_aux(1)\n\n\nsubsubsection \\<open>Correctness of insertion\\<close>\n\nlemma set_of_mkt_bal_l:\n  \"\\<lbrakk> avl l; avl r \\<rbrakk> \\<Longrightarrow>\n  set_of (mkt_bal_l n l r) = Set.insert n (set_of l \\<union> set_of r)\"\nby (auto simp: mkt_def split:tree.splits)\n\nlemma set_of_mkt_bal_r:\n  \"\\<lbrakk> avl l; avl r \\<rbrakk> \\<Longrightarrow>\n  set_of (mkt_bal_r n l r) = Set.insert n (set_of l \\<union> set_of r)\"\nby (auto simp: mkt_def split:tree.splits)\n\ntext\\<open>Correctness of @{const insert}:\\<close>\n\ntheorem set_of_insert:\n  \"avl t \\<Longrightarrow> set_of(insert x t) = Set.insert x (set_of t)\"\nby (induct t) \n   (auto simp: avl_insert set_of_mkt_bal_l set_of_mkt_bal_r simp del:mkt_bal_l.simps mkt_bal_r.simps)\n\nsubsubsection \\<open>Correctness of deletion\\<close>\n\nfun rightmost_item :: \"'a tree \\<Rightarrow> 'a\" where\n\"rightmost_item (MKT n l ET h) = n\" |\n\"rightmost_item (MKT n l r h) = rightmost_item r\"\n\nlemma avl_dist:\n  \"\\<lbrakk> avl(MKT n l r h); is_ord(MKT n l r h); x \\<in> set_of l \\<rbrakk> \\<Longrightarrow>\n  x \\<notin> set_of r\"\nby fastforce\n\nlemma avl_dist2:\n  \"\\<lbrakk> avl(MKT n l r h); is_ord(MKT n l r h); x \\<in> set_of l \\<or> x \\<in> set_of r \\<rbrakk> \\<Longrightarrow>\n  x \\<noteq> n\"\nby auto\n\nlemma ritem_in_rset: \"r \\<noteq> ET \\<Longrightarrow> rightmost_item r \\<in> set_of r\"\nby(induct r rule:rightmost_item.induct) auto\n\nlemma ritem_greatest_in_rset:\n  \"\\<lbrakk> r \\<noteq> ET; is_ord r \\<rbrakk> \\<Longrightarrow>\n  \\<forall>x.  x \\<in> set_of r \\<longrightarrow> x \\<noteq> rightmost_item r \\<longrightarrow> x < rightmost_item r\" \nproof(induct r rule:rightmost_item.induct)\n  case (2 n l rn rl rr rh h)\n  show ?case (is \"\\<forall>x. ?P x\") \n  proof\n    fix x\n    from 2 have \"is_ord (MKT rn rl rr rh)\" by auto\n    moreover from 2 have \"n < rightmost_item (MKT rn rl rr rh)\" \n      by (metis is_ord.simps(2) ritem_in_rset tree.simps(2))\n    moreover from 2 have \"x \\<in> set_of l \\<longrightarrow> x < rightmost_item (MKT rn rl rr rh)\"\n      by (metis calculation(2) is_ord.simps(2) xt1(10))\n    ultimately show \"?P x\" using 2 by simp\n  qed\nqed auto\n\nlemma ritem_not_in_ltree:\n  \"\\<lbrakk> avl(MKT n l r h); is_ord(MKT n l r h); r \\<noteq> ET \\<rbrakk> \\<Longrightarrow>\n  rightmost_item r \\<notin> set_of l\"\nby (metis avl_dist ritem_in_rset)\n\nlemma set_of_delete_max:\n  \"\\<lbrakk> avl t; is_ord t; t\\<noteq>ET \\<rbrakk> \\<Longrightarrow>\n   set_of (snd(delete_max t)) = (set_of t) - {rightmost_item t}\"\nproof (induct t rule: delete_max_induct)\n  case (MKT n l rn rl rr rh h)\n  let ?r = \"MKT rn rl rr rh\"\n  from MKT have \"avl l\" and \"avl ?r\" by simp_all\n  let ?t' = \"mkt_bal_l n l (snd (delete_max ?r))\"\n  from MKT have \"avl (snd(delete_max ?r))\" by (auto simp add: avl_delete_max)\n  with MKT ritem_not_in_ltree[of n l ?r h]\n  have \"set_of ?t' = (set_of l) \\<union> (set_of ?r) - {rightmost_item ?r} \\<union> {n}\" \n    by (auto simp add:set_of_mkt_bal_l simp del: mkt_bal_l.simps)\n  moreover have \"n \\<notin> {rightmost_item ?r}\" \n    by (metis MKT(2) MKT(3) avl_dist2 ritem_in_rset singletonE tree.simps(3))\n  ultimately show ?case\n    by (auto simp add:insert_Diff_if split:prod.splits simp del: mkt_bal_l.simps) \nqed auto\n\nlemma fst_delete_max_eq_ritem:\n  \"t\\<noteq>ET \\<Longrightarrow> fst(delete_max t) = rightmost_item t\"\nby (induct t rule:rightmost_item.induct) (auto split:prod.splits)\n\nlemma set_of_delete_root:\n  assumes \"t = MKT n l r h\" and \"avl t\" and \"is_ord t\"\n  shows \"set_of (delete_root t) = (set_of t) - {n}\"\nusing assms\nproof(cases t rule:delete_root_cases)\n  case(MKT_MKT n ln ll lr lh rn rl rr rh h)\n  let ?t' = \"mkt_bal_r (fst (delete_max l)) (snd (delete_max l)) r\"\n  from assms MKT_MKT have \"avl l\" and \"avl r\" and \"is_ord l\" and \"l\\<noteq>ET\" by auto\n  moreover from MKT_MKT assms have \"avl (snd(delete_max l))\" \n    by (auto simp add: avl_delete_max)\n  ultimately have \"set_of ?t' = (set_of l) \\<union> (set_of r)\"\n    by (fastforce simp add: Set.insert_Diff ritem_in_rset fst_delete_max_eq_ritem  \n       set_of_delete_max set_of_mkt_bal_r  simp del: mkt_bal_r.simps)\n  moreover from MKT_MKT assms(1) have \"set_of (delete_root t) = set_of ?t'\" \n    by (simp split:prod.split del:mkt_bal_r.simps)\n  moreover from MKT_MKT assms have \"(set_of t) - {n} = set_of l \\<union> set_of r\" \n    by (metis Diff_insert_absorb UnE avl_dist2 tree.set(2) tree.inject)\n  ultimately show ?thesis using MKT_MKT assms(1)\n    by (simp del: delete_root.simps)\nqed auto\n\ntext\\<open>Correctness of @{const delete}:\\<close>\n\n\n\nsubsubsection \\<open>Correctness of lookup\\<close>\n\ntheorem is_in_correct: \"is_ord t \\<Longrightarrow> is_in k t = (k : set_of t)\"\nby (induct t) auto\n\nsubsubsection \\<open>Insertion maintains order\\<close>\n\nlemma is_ord_mkt_bal_l:\n  \"is_ord(MKT n l r h) \\<Longrightarrow> is_ord (mkt_bal_l n l r)\"\nby (cases l) (auto simp: mkt_def split:tree.splits intro: order_less_trans)\n\nlemma is_ord_mkt_bal_r: \"is_ord(MKT n l r h) \\<Longrightarrow> is_ord (mkt_bal_r n l r)\"\nby (cases r) (auto simp: mkt_def split:tree.splits intro: order_less_trans)\n\ntext\\<open>If the order is linear, @{const insert} maintains the order:\\<close>\n\ntheorem is_ord_insert:\n  \"\\<lbrakk> avl t; is_ord t \\<rbrakk> \\<Longrightarrow> is_ord(insert (x::'a::linorder) t)\"\nby (induct t) (simp_all add:is_ord_mkt_bal_l is_ord_mkt_bal_r avl_insert set_of_insert\n                linorder_not_less order_neq_le_trans del:mkt_bal_l.simps mkt_bal_r.simps)\n\nsubsubsection \\<open>Deletion maintains order\\<close>\n\nlemma is_ord_delete_max:\n  \"\\<lbrakk> avl t; is_ord t; t\\<noteq>ET \\<rbrakk> \\<Longrightarrow> is_ord(snd(delete_max t))\"\nproof(induct t rule:delete_max_induct)\n  case(MKT n l rn rl rr rh h)\n  let ?r = \"MKT rn rl rr rh\"\n  let ?r' = \"snd(delete_max ?r)\"\n  from MKT have \"\\<forall>h. is_ord(MKT n l ?r' h)\" by (auto simp: set_of_delete_max)\n  moreover from MKT have \"avl(?r')\" by (auto simp: avl_delete_max)\n  moreover note MKT is_ord_mkt_bal_l[of n l ?r']\n  ultimately show ?case by (auto split:prod.splits simp del:is_ord.simps mkt_bal_l.simps)\nqed auto\n\nlemma is_ord_delete_root:\n  assumes \"avl t\" and \"is_ord t\" and \"t \\<noteq> ET\"\n  shows \"is_ord (delete_root t)\"\nusing assms\nproof(cases t rule:delete_root_cases)\n  case(MKT_MKT n ln ll lr lh rn rl rr rh h)\n  let ?l = \"MKT ln ll lr lh\"\n  let ?r = \"MKT rn rl rr rh\"\n  let ?l' = \"snd (delete_max ?l)\"\n  let ?n' = \"fst (delete_max ?l)\"\n  from assms MKT_MKT have \"\\<forall>h. is_ord(MKT ?n' ?l' ?r h)\" \n  proof -\n    from assms MKT_MKT have \"is_ord ?l'\" by (auto simp add: is_ord_delete_max)\n    moreover from assms MKT_MKT have \"is_ord ?r\" by auto\n    moreover from assms MKT_MKT have \"\\<forall>x. x \\<in> set_of ?r \\<longrightarrow> ?n' < x\" \n      by (metis fst_delete_max_eq_ritem is_ord.simps(2) order_less_trans ritem_in_rset \n          tree.simps(3))\n    moreover from assms MKT_MKT ritem_greatest_in_rset have \"\\<forall>x. x \\<in> set_of ?l' \\<longrightarrow> x < ?n'\" \n      by (metis Diff_iff avl.simps(2) fst_delete_max_eq_ritem is_ord.simps(2) \n          set_of_delete_max singleton_iff tree.simps(3))\n    ultimately show ?thesis by auto\n  qed\n  moreover from assms MKT_MKT have \"avl ?r\" by simp\n  moreover from assms MKT_MKT have \"avl ?l'\"  by (simp add: avl_delete_max)\n  moreover note MKT_MKT is_ord_mkt_bal_r[of  ?n' ?l' ?r]\n  ultimately show ?thesis by (auto simp del:mkt_bal_r.simps is_ord.simps split:prod.splits)\nqed simp_all\n\ntext\\<open>If the order is linear, @{const delete} maintains the order:\\<close>\n\ntheorem is_ord_delete:\n  \"\\<lbrakk> avl t; is_ord t \\<rbrakk> \\<Longrightarrow> is_ord (delete x t)\"\nproof (induct t)\n  case (MKT n l r h)\n  then show ?case\n  proof(cases \"x = n\")\n    case True\n    with MKT is_ord_delete_root[of \"MKT n l r h\"] show ?thesis by simp\n  next\n    case False\n    with MKT show ?thesis \n    proof(cases \"x<n\")\n      case True\n      with True MKT have \"\\<forall>h. is_ord (MKT n (delete x l) r h)\" by (auto simp:set_of_delete)\n      with True MKT is_ord_mkt_bal_r[of n \"(delete x l)\" r]  show ?thesis \n        by (auto simp add: avl_delete)\n    next\n      case False\n      with False MKT have \"\\<forall>h. is_ord (MKT n l (delete x r) h)\" by (auto simp:set_of_delete)\n      with False MKT is_ord_mkt_bal_l[of n l \"(delete x r)\"] \\<open>x\\<noteq>n\\<close> show ?thesis by (simp add: avl_delete)\n    qed\n  qed\nqed simp\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/AVL-Trees/AVL.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7793909993502308}}
{"text": "theory Graph_Theory_Batteries\n  imports \"Graph_Theory.Graph_Theory\"\nbegin\n\ntext \\<open>This theory collects some useful lemmas which extend the graph library.\\<close>\n\nlemma (in wf_digraph) sp_non_neg_if_w_non_neg:\n  assumes w_non_neg: \"\\<forall>e \\<in> arcs G. w e \\<ge> 0\"\n  shows \"\\<mu> w u v \\<ge> 0\"\nproof(cases \"u \\<rightarrow>\\<^sup>*\\<^bsub>G\\<^esub> v\")\n  case True\n  have *: \"awalk u p v \\<Longrightarrow> awalk_cost w p \\<ge> 0\" for p\n    by (simp add: pos_cost_pos_awalk_cost w_non_neg)\n  then show ?thesis unfolding \\<mu>_def\n    by (metis (mono_tags, lifting) INF_less_iff ereal_less_eq(5) mem_Collect_eq not_less)\nnext\n  case False\n  then show ?thesis by (simp add: shortest_path_inf)\nqed\n\n\nlemma (in wf_digraph) sp_to_self_if_w_non_neg:\n  assumes w_non_neg: \"\\<forall>e \\<in> arcs G. w e \\<ge> 0\" and \"u \\<in> verts G\"\n  shows \"\\<mu> w u u = 0\"\nproof -\n  have \"awalk u [] u\" and \"awalk_cost w [] = 0\"\n    by (auto simp: assms(2) awalk_Nil_iff)\n  moreover\n  have \"\\<mu> w u u \\<ge> 0\" by (simp add: sp_non_neg_if_w_non_neg w_non_neg)\n  ultimately show \"\\<mu> w u u = 0\"\n    by (metis antisym ereal_eq_0(2) min_cost_le_walk_cost)\nqed\n\nlemma (in fin_digraph) reachable_verts_finite: \"finite {x. u \\<rightarrow>\\<^sup>* x}\"\n  using finite_verts\n  by (metis finite_subset mem_Collect_eq reachable_in_vertsE subsetI)\n\nlemma (in wf_digraph) awalk_not_distinct:\n  assumes \"finite (verts G)\" and \"awalk u p v\" and \"length p \\<ge> card (verts G)\"\n  shows \"\\<not> distinct (awalk_verts u p)\"\nproof -\n  have *: \"length (awalk_verts u p) > length p\"\n    by (induction p arbitrary: u) auto\n\n  show ?thesis\n  proof(cases \"length p = 0\")\n    case True\n    with assms show ?thesis unfolding awalk_def by simp\n  next\n    case False\n    with assms * have \"length (awalk_verts u p) > card (verts G)\"\n      by auto\n    moreover\n    have \"set (awalk_verts u p) \\<subseteq> verts G\" using assms(2) by blast\n    ultimately show ?thesis using assms(1)\n      by (induction p arbitrary: u)\n         (auto, metis card_subset_eq distinct_card less_antisym)\n  qed\nqed\n\nlemma (in wf_digraph) awalk_del_vert:\n  \"\\<lbrakk> awalk u p v; x \\<notin> set (awalk_verts u p) \\<rbrakk> \\<Longrightarrow> pre_digraph.awalk (del_vert x) u p v\"\nproof(induction p arbitrary: u)\n  case Nil\n  then have \"set (awalk_verts u []) = {u}\" by auto\n  with Nil have \"x \\<noteq> u\" by simp\n  moreover\n  from Nil have \"u = v\" unfolding awalk_def by auto\n  ultimately show ?case using Nil\n    by (simp add: awalk_hd_in_verts pre_digraph.verts_del_vert\n        wf_digraph.awalk_Nil_iff wf_digraph_del_vert)\nnext\n  case (Cons a p)\n  then obtain u' where u': \"pre_digraph.awalk (del_vert x) u' p v\"\n    using awalk_Cons_iff by auto\n  moreover\n  from Cons.prems have \"head G a \\<noteq> x\"\n    using hd_in_awalk_verts(1) awalk_Cons_iff by auto\n  ultimately show ?case using Cons\n    by (auto simp: awalk_Cons_iff head_del_vert pre_digraph.del_vert_simps(2)\n        tail_del_vert wf_digraph.awalk_Cons_iff wf_digraph_del_vert)\nqed\n\ntext \\<open>This is an alternative formulation of @{thm pre_digraph.arcs_del_vert}.\\<close>\nlemma (in pre_digraph) arcs_del_vert2:\n  \"arcs (del_vert v) = arcs G - in_arcs G v - out_arcs G v\"\n  using arcs_del_vert by force\n\nlemma (in wf_digraph) strongly_con_imp_reachable_eq_verts:\n  \"\\<lbrakk> r \\<in> verts G; strongly_connected G \\<rbrakk> \\<Longrightarrow> {x. r \\<rightarrow>\\<^sup>* x} = verts G\"\n  unfolding strongly_connected_def using reachable_in_verts(2) by blast\n\nlemma (in wf_digraph) strongly_con_imp_sp_finite:\n  \"\\<lbrakk> u \\<in> verts G; v \\<in> verts G; strongly_connected G \\<rbrakk> \\<Longrightarrow> \\<mu> w u v < \\<infinity>\"\n  unfolding strongly_connected_def using \\<mu>_reach_conv by auto\n\ntext \\<open>This is an alternative formulation of @{thm fin_digraph.min_cost_awalk} with different\n  assumptions.\\<close>\nlemma (in fin_digraph) min_cost_awalk2:\n  assumes \"\\<mu> w a b \\<noteq> \\<infinity>\" \"\\<mu> w a b \\<noteq> -\\<infinity>\"\n  shows \"\\<exists>p. apath a p b \\<and> \\<mu> w a b = awalk_cost w p\"\nproof -\n  from assms have \"a \\<rightarrow>\\<^sup>* b\" using \\<mu>_reach_conv by auto\n  then show ?thesis using no_neg_cyc_reach_imp_path\n    using assms(2) neg_cycle_imp_inf_\\<mu> by blast\nqed\n\nlemma (in fin_digraph) sp_triangle:\n  assumes \"a \\<in> verts G\" \"b \\<in> verts G\" \"c \\<in> verts G\"\n      and w_non_neg: \"\\<forall>e \\<in> arcs G. w e \\<ge> 0\"\n    shows \"\\<mu> w a c \\<le> \\<mu> w a b + \\<mu> w b c\"\nproof(rule ccontr)\n  assume \"\\<not> \\<mu> w a c \\<le> \\<mu> w a b + \\<mu> w b c\"\n  then have *: \"\\<mu> w a c > \\<mu> w a b + \\<mu> w b c\"\n    using not_less by blast\n  consider (minf) \"\\<mu> w a c = -\\<infinity>\" | (pinf) \"\\<mu> w a c = \\<infinity>\"\n    | (fin) \"\\<mu> w a c \\<noteq> -\\<infinity> \\<and> \\<mu> w a c \\<noteq> \\<infinity>\" by auto\n  then show \"False\"\n  proof(cases)\n    case minf\n    with * show ?thesis by auto\n  next\n    case pinf\n    with * have \"\\<mu> w a b < \\<infinity>\" \"\\<mu> w b c < \\<infinity>\"\n      by auto\n    then have \"a \\<rightarrow>\\<^sup>* b\" \"b \\<rightarrow>\\<^sup>* c\" using \\<mu>_reach_conv by auto\n    then have \"a \\<rightarrow>\\<^sup>* c\" using reachable_trans by blast\n    then have \"\\<mu> w a c \\<noteq> \\<infinity>\" using \\<mu>_reach_conv by auto\n    with pinf show ?thesis by simp\n  next\n    case fin\n    with * have \"\\<mu> w a b \\<noteq> \\<infinity>\" \"\\<mu> w b c \\<noteq> \\<infinity>\" by auto\n    moreover\n    from fin * have \"\\<mu> w a b \\<noteq> -\\<infinity>\" \"\\<mu> w b c \\<noteq> -\\<infinity>\"\n      using w_non_neg sp_non_neg_if_w_non_neg by auto\n    ultimately have\n      \"\\<exists>p. awalk a p b \\<and> awalk_cost w p = \\<mu> w a b\"\n      \"\\<exists>p. awalk b p c \\<and> awalk_cost w p = \\<mu> w b c\"\n      using min_cost_awalk2 by (fastforce intro: awalkI_apath)+\n    then obtain p1 p2 where\n        \"awalk a p1 b\" \"awalk_cost w p1 = \\<mu> w a b\" and\n        \"awalk b p2 c\" \"awalk_cost w p2 = \\<mu> w b c\" by blast\n    then have \"awalk a (p1@p2) c \\<and> awalk_cost w (p1@p2) = \\<mu> w a b + \\<mu> w b c\"\n      by (auto intro: awalk_appendI) (metis plus_ereal.simps(1))\n    then show ?thesis using min_cost_le_walk_cost\n      by (metis \\<open>\\<not> \\<mu> w a c \\<le> \\<mu> w a b + \\<mu> w b c\\<close>)\n  qed\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Query_Optimization/Graph_Theory_Batteries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8615382129861583, "lm_q1q2_score": 0.7793909987435574}}
{"text": "theory BST_Demo\nimports \"HOL-Library.Tree\"\nbegin\n\n(* useful most of the time: *)\ndeclare Let_def [simp]\n\nsection \"Basic BST Functions\"\n\nfun isin :: \"('a::linorder) tree \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"isin Leaf x = False\" |\n\"isin (Node l a r) x =\n  (if x < a then isin l x else\n   if x > a then isin r x\n   else True)\"\n\nfun ins :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"ins x Leaf = Node Leaf x Leaf\" |\n\"ins x (Node l a r) =\n  (if x < a then Node (ins x l) a r else\n   if x > a then Node l a (ins x r)\n   else Node l a r)\"\n\nsubsection \"Functional Correctness\"\n\nlemma \"bst t \\<Longrightarrow> isin t x = (x \\<in> set_tree t)\"\napply(induction t)\napply auto\ndone\n\nlemma set_tree_ins: \"set_tree (ins x t) = {x} \\<union> set_tree t\"\napply(induction t)\napply auto\ndone\n\nsubsection \"Preservation of Invariant\"\n\nlemma bst_ins: \"bst t \\<Longrightarrow> bst (ins x t)\"\napply(induction t)\napply (auto simp: set_tree_ins)\ndone\n\n\nsection \"Reducing the Number of Comparisons\"\n\ntext \\<open>Idea: never test for \\<open>=\\<close> but remember the last value where you\nshould have tested for \\<open>=\\<close> but did not. Compare with that value when\nyou reach a leaf.\\<close>\n\nfun isin2 :: \"('a::linorder) tree \\<Rightarrow> 'a option \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"isin2 Leaf z x = (case z of None \\<Rightarrow> False | Some y \\<Rightarrow> x = y) \" |\n\"isin2 (Node l a r) z x =\n  (if x < a then isin2 l z x else isin2 r (Some a) x)\"\n\nlemma isin2_Some:\n  \"\\<lbrakk> bst t;  \\<forall>x \\<in> set_tree t. y < x \\<rbrakk>\n  \\<Longrightarrow> isin2 t (Some y) x = (isin t x \\<or> x=y)\"\napply(induction t arbitrary: y)\napply auto\ndone\n\nlemma isin2_None:\n  \"bst t \\<Longrightarrow> isin2 t None x = isin t x\"\napply(induction t)\napply (auto simp: isin2_Some)\ndone\n\n\nsection \"Trees with Size Info\"\n\ntype_synonym 'a tree_sz = \"('a * nat) tree\"\n\nfun inv_sz :: \"('a::linorder) tree_sz \\<Rightarrow> bool\" where\n\"inv_sz \\<langle>\\<rangle> = True\" |\n\"inv_sz \\<langle>l, (a,s), r\\<rangle> = (inv_sz l \\<and> inv_sz r \\<and> s = size l + size r + 1)\"\n\nfun sz :: \"'a tree_sz \\<Rightarrow> nat\" where\n\"sz Leaf = 0\" |\n\"sz (Node _ (_,s) _) = s\"\n\nabbreviation un_sz :: \"'a tree_sz \\<Rightarrow> 'a tree\" where\n\"un_sz t == map_tree fst t\"\n\nfun ins_sz :: \"'a::linorder \\<Rightarrow> 'a tree_sz \\<Rightarrow> 'a tree_sz\" where\n\"ins_sz x Leaf = Node Leaf (x,1) Leaf\" |\n\"ins_sz x (Node l (a,s) r) =\n  (if x < a then let l' = ins_sz x l in Node l' (a, sz l' + sz r + 1) r else\n   if x > a then let r' = ins_sz x r in Node l (a, sz l + sz r' + 1) r'\n   else Node l (a,s) r)\"\n\nsubsection \"Functional Correctness\"\n\nlemma un_sz_ins_sz: \"un_sz (ins_sz x t) = ins x (un_sz t)\"\napply(induction t)\napply auto\ndone\n\nsubsection \"Preservation of Invariants\"\n\nlemma \"bst(un_sz t) \\<Longrightarrow> bst(un_sz (ins_sz x t))\"\nby(simp add: un_sz_ins_sz bst_ins)\n\nlemma sz_size[simp]: \"inv_sz t \\<Longrightarrow> sz t = size t\"\napply(induction t)\napply auto\ndone\n\nlemma \"inv_sz t \\<Longrightarrow> inv_sz (ins_sz x t)\"\napply(induction t)\napply (auto)\ndone\n\n(* nth smallest element: *)\nfun nth_min :: \"('a::linorder) tree_sz \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n\"nth_min \\<langle>l, (a,s), r\\<rangle> n =\n   (let sl = sz l in\n    if n = sl then a else\n    if n < sl then nth_min l n else nth_min r (n-sl-1))\"\n\nlemma \"\\<lbrakk> bst(un_sz t);  inv_sz t;  n < size t \\<rbrakk>\n \\<Longrightarrow> nth_min t n = nth (inorder(un_sz t)) n\"\napply(induction t arbitrary: n)\napply (auto simp: nth_append)\ndone\n\n\nsection \"Compressing the Height of BSTs\"\n\nfun compress :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"compress (Node Leaf a t) =\n  (case compress t of\n     Node Leaf b u \\<Rightarrow> Node (Node Leaf a Leaf) b u |\n     u \\<Rightarrow> Node Leaf a u)\" |\n\"compress (Node l a r) = Node (compress l) a (compress r)\" |\n\"compress Leaf = Leaf\"\n\n(* Another way of saying that \\<open>bst\\<close> and \\<open>set_tree\\<close> are preserved: *)\nlemma \"inorder(compress t) = inorder t\"\napply(induction t rule: compress.induct)\napply (auto split: tree.split)\ndone\n\nlemma \"height (compress t) \\<le> height t\"\napply(induction t rule: compress.induct)\napply (auto split: tree.split)\ndone\n\n(* What is the correct relationship? *)\nlemma \"height t \\<le> height (compress t)\"\noops\n\n\nsection \"BST Implementation of Maps\"\n\nfun lookup :: \"('a::linorder * 'b) tree \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup Leaf x = None\" |\n\"lookup (Node l (a,b) r) x =\n  (if x < a then lookup l x else\n   if x > a then lookup r x\n   else Some b)\"\n\nfun update :: \"'a \\<Rightarrow> 'b \\<Rightarrow> ('a::linorder * 'b) tree \\<Rightarrow> ('a * 'b) tree\" where\n\"update x y Leaf = Node Leaf (x,y) Leaf\" |\n\"update x y (Node l (a,b) r) =\n  (if x < a then Node (update x y l) (a,b) r else\n   if x > a then Node l (a,b) (update x y r)\n   else Node l (x,y) r)\"\n\nsubsection \"Functional Correctness\"\n\nlemma \"lookup (update x y t) a = (if x=a then Some y else lookup t a)\"\napply(induction t)\napply auto\ndone\n\nsubsection \"Preservation of Invariant\"\n\ndefinition \"bst1 t = bst (map_tree fst t)\"\n\nlemma map_tree_update: \"map_tree fst (update x y t) = ins x (map_tree fst t)\"\napply(induction t)\napply auto\ndone\n\nlemma \"bst1 t \\<Longrightarrow> bst1(update x y t)\"\napply(induction t)\napply (auto simp: bst1_def map_tree_update set_tree_ins)\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Complete/BST_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.7793909917045967}}
{"text": "section \\<open>Prefixes\\<close>\n\ntheory prefix\n  imports Main\nbegin\n\n\ntext \\<open>This Function describes that a list is a prefix of another list.\\<close>\n\ndefinition\n  \"isPrefix xs ys \\<equiv> xs = take (length xs) ys\"\n\nlemma isPrefix_append:\n  \"isPrefix xs ys \\<Longrightarrow> isPrefix xs (ys@zs)\"\n  using take_all by (fastforce simp add: isPrefix_def)\n\nlemma isPrefix_refl: \"isPrefix xs xs\"\n  by (simp add: isPrefix_def)\n\nlemma isPrefix_empty: \"isPrefix xs [] \\<longleftrightarrow> xs = []\"\n  by (simp add: isPrefix_def)\n\nlemma isPrefix_empty_first: \"isPrefix [] xs\"\n  by (simp add: isPrefix_def)\n\nlemma isPrefix_appendI:\n  \"isPrefix xs (xs@ys)\"\n  by (simp add: isPrefix_def)\n\nlemma isPrefix_len:\n  \"isPrefix tr tr' \\<Longrightarrow> length tr \\<le> length tr'\"\n  by (metis isPrefix_def nat_le_linear take_all)\n\nlemma isPrefix_trans:\n  \"isPrefix xs ys \\<Longrightarrow> isPrefix ys zs \\<Longrightarrow> isPrefix xs zs\"\n  by (auto simp add: isPrefix_def, metis length_take take_take)\n\n\nlemma isPrefix_appendPrefix:\n  \"isPrefix (xs@ys) zs \\<Longrightarrow> isPrefix xs zs\"\n  using isPrefix_appendI isPrefix_trans by blast\n\nlemma isPrefix_subset:\n  \"isPrefix xs ys \\<Longrightarrow> set xs \\<subseteq> set ys\"\n  by (metis isPrefix_def set_take_subset)\n\nlemma isPrefix_subset2:\n  \"isPrefix xs ys \\<Longrightarrow> x\\<in>set xs \\<Longrightarrow> x\\<in> set ys\"\n  using isPrefix_subset by auto\n\n\n\n\nlemma isPrefix_same: \n  assumes \"isPrefix tr tr'\"\n    and \"i<length tr\"\n  shows \"tr!i = tr'!i\"\n  using assms by (auto simp add: isPrefix_def, metis nth_take)\n\n\nend", "meta": {"author": "peterzeller", "repo": "repliss-isabelle", "sha": "f43744678cc9c5a4684e8bd0e9c83510bae1d9a4", "save_path": "github-repos/isabelle/peterzeller-repliss-isabelle", "path": "github-repos/isabelle/peterzeller-repliss-isabelle/repliss-isabelle-f43744678cc9c5a4684e8bd0e9c83510bae1d9a4/prefix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837705, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7793834473670216}}
{"text": "theory ch12\nimports Main\nbegin\n\ntext {*\n Note: to avoid name clashes with the existing type of lists we build\n on top of Datatype rather than Main. This is an exception!\n*}\n\ndatatype 'a list = Nil | Cons 'a \"'a list\"\n\nprimrec app :: \"'a list => 'a list => 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nprimrec rev :: \"'a list => 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\nvalue \"rev(Cons a (Cons b Nil))\"\n\n\ntext {*\n  Simple proofs:\n\n  Command 'lemma' / 'theorem': state a proposition\n  Attribute 'simp': use this theorem as a simplification rule in future proofs\n  Method 'induct': structural induction\n  Method 'auto':  automatic proof (mostly by simplification)\n  Command 'done':  end of proof\n*}\n\nlemma app_Nil2[simp]: \"app xs Nil = xs\"\napply (induct xs)\napply auto\ndone\n\nlemma app_assoc[simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply (induct xs)\napply auto\ndone\n\nlemma rev_app[simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"\napply (induct xs)\napply auto\ndone\n\ntheorem rev_rev[simp]: \"rev (rev xs) = xs\"\napply (induct xs)\napply auto\ndone\n\n(* Hint for demo:\n   do the proof top down, discovering the lemmas one by one,\n   as described in LNCS2283.\n*)\n\nend\n", "meta": {"author": "tecty", "repo": "COMP4161", "sha": "95aa77d289c14cb85477c7f91467f81cd66fcd62", "save_path": "github-repos/isabelle/tecty-COMP4161", "path": "github-repos/isabelle/tecty-COMP4161/COMP4161-95aa77d289c14cb85477c7f91467f81cd66fcd62/hol-tut/demo/ch12.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094032139576, "lm_q2_score": 0.8723473746782093, "lm_q1q2_score": 0.7792761126690538}}
{"text": "theory group_class\nimports Main\nbegin\n\nclass semigroup =\n  fixes mult :: \"'a \\<Rightarrow> 'a  \\<Rightarrow> 'a\" (infixl \"\\<otimes>\" 70)\n  assumes assoc: \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\n\nclass monoidl = semigroup +\n  fixes neutral :: 'a (\"e\")\n  assumes neutl: \"e \\<otimes> x = x\"\n\nclass monoid = monoidl +\n  assumes neutr: \"x \\<otimes> e = x\"\n\nclass group = monoidl +\nfixes inverse ::\"'a \\<Rightarrow> 'a\" (\"inv\")\nassumes invl: \"(inv x) \\<otimes> x = e\"\n\nlemma (in group) left_cancel: \"x \\<otimes> y = x \\<otimes> z \\<Longrightarrow> y = z\"\nproof-\nassume \"x \\<otimes> y = x \\<otimes> z\"\nthen have \"(inv x) \\<otimes> (x \\<otimes> y) = (inv x) \\<otimes> (x \\<otimes> z)\" by simp\nthen have \"((inv x) \\<otimes> x) \\<otimes> y = ((inv x) \\<otimes> x) \\<otimes> z\" using assoc by simp\nthen show \"y = z\" using neutl and invl by simp\nqed\n\n(*\nsubclass (in group) monoid\nproof-\nfix x\nfrom invl have \"(inv x) \\<otimes> x = e\" by simp\nthen have \"(inv x) \\<otimes> (x \\<otimes> e) = (inv x) \\<otimes> x\" using assoc [symmetric] and neutl and invl by simp\nthen have \"x \\<otimes> e = x\" using left_cancel by simp\n*)", "meta": {"author": "prathamesht-cs", "repo": "Groupabelle", "sha": "3b8369e3016b8e380eccd9c0033c60aa4a9755cf", "save_path": "github-repos/isabelle/prathamesht-cs-Groupabelle", "path": "github-repos/isabelle/prathamesht-cs-Groupabelle/Groupabelle-3b8369e3016b8e380eccd9c0033c60aa4a9755cf/group_class.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9399133481428691, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7791306586789901}}
{"text": "theory power \n  imports Main \nbegin\n\n  (*\n    We define the property of power x^n. We will recursively go through till n is equal to 0.\n  *)\n  primrec pow :: \"nat => nat => nat\"\n    where\n      \"pow x 0       = Suc 0\"\n    | \"pow x (Suc n) = x * pow x n\"\n  \n  \n  \n  (*\n    We will prove that when we multiply the powers,\n    its the same as doing the power twice first with m then with n.\n  *)\n  \n  (*\n    First we will prove the base case, which is multiplying the\n    results of two powered numbers is the same as adding the powers before hand.\n    We use induction tactic on the power and apply auto.\n  *)\n  lemma pow_add: \"pow x (m + n) = pow x m * pow x n\"\n    apply (induct n)\n    apply auto\n  done\n  \n  (*\n    This uses the base case that we proved above using the lemma.\n    We use induction tactic on the power and apply auto.\n  *)\n  theorem pow_mult: \"pow x (m * n) = pow (pow x m) n\"\n    apply (induct n)\n    apply (auto simp add: pow_add)\n  done\n\nend", "meta": {"author": "SNavleen", "repo": "Isabelle-Examples", "sha": "bd7cc76f8503952af85e6dbdc0edd9b2bbb8a457", "save_path": "github-repos/isabelle/SNavleen-Isabelle-Examples", "path": "github-repos/isabelle/SNavleen-Isabelle-Examples/Isabelle-Examples-bd7cc76f8503952af85e6dbdc0edd9b2bbb8a457/power.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133565584851, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7791306497669237}}
{"text": "(*  Title:      HOL/Complete_Partial_Order.thy\n    Author:     Brian Huffman, Portland State University\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection \\<open>Chain-complete partial orders and their fixpoints\\<close>\n\ntheory Complete_Partial_Order\n  imports Product_Type\nbegin\n\nsubsection \\<open>Monotone functions\\<close>\n\ntext \\<open>Dictionary-passing version of @{const Orderings.mono}.\\<close>\n\ndefinition monotone :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"monotone orda ordb f \\<longleftrightarrow> (\\<forall>x y. orda x y \\<longrightarrow> ordb (f x) (f y))\"\n\nlemma monotoneI[intro?]: \"(\\<And>x y. orda x y \\<Longrightarrow> ordb (f x) (f y)) \\<Longrightarrow> monotone orda ordb f\"\n  unfolding monotone_def by iprover\n\nlemma monotoneD[dest?]: \"monotone orda ordb f \\<Longrightarrow> orda x y \\<Longrightarrow> ordb (f x) (f y)\"\n  unfolding monotone_def by iprover\n\n\nsubsection \\<open>Chains\\<close>\n\ntext \\<open>\n  A chain is a totally-ordered set. Chains are parameterized over\n  the order for maximal flexibility, since type classes are not enough.\n\\<close>\n\ndefinition chain :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"chain ord S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<forall>y\\<in>S. ord x y \\<or> ord y x)\"\n\nlemma chainI:\n  assumes \"\\<And>x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> ord x y \\<or> ord y x\"\n  shows \"chain ord S\"\n  using assms unfolding chain_def by fast\n\nlemma chainD:\n  assumes \"chain ord S\" and \"x \\<in> S\" and \"y \\<in> S\"\n  shows \"ord x y \\<or> ord y x\"\n  using assms unfolding chain_def by fast\n\nlemma chainE:\n  assumes \"chain ord S\" and \"x \\<in> S\" and \"y \\<in> S\"\n  obtains \"ord x y\" | \"ord y x\"\n  using assms unfolding chain_def by fast\n\nlemma chain_empty: \"chain ord {}\"\n  by (simp add: chain_def)\n\nlemma chain_equality: \"chain op = A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x = y)\"\n  by (auto simp add: chain_def)\n\nlemma chain_subset: \"chain ord A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> chain ord B\"\n  by (rule chainI) (blast dest: chainD)\n\nlemma chain_imageI:\n  assumes chain: \"chain le_a Y\"\n    and mono: \"\\<And>x y. x \\<in> Y \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> le_a x y \\<Longrightarrow> le_b (f x) (f y)\"\n  shows \"chain le_b (f ` Y)\"\n  by (blast intro: chainI dest: chainD[OF chain] mono)\n\n\nsubsection \\<open>Chain-complete partial orders\\<close>\n\ntext \\<open>\n  A \\<open>ccpo\\<close> has a least upper bound for any chain.  In particular, the\n  empty set is a chain, so every \\<open>ccpo\\<close> must have a bottom element.\n\\<close>\n\nclass ccpo = order + Sup +\n  assumes ccpo_Sup_upper: \"chain (op \\<le>) A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<le> Sup A\"\n  assumes ccpo_Sup_least: \"chain (op \\<le>) A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> Sup A \\<le> z\"\nbegin\n\nlemma chain_singleton: \"Complete_Partial_Order.chain op \\<le> {x}\"\n  by (rule chainI) simp\n\nlemma ccpo_Sup_singleton [simp]: \"\\<Squnion>{x} = x\"\n  by (rule antisym) (auto intro: ccpo_Sup_least ccpo_Sup_upper simp add: chain_singleton)\n\n\nsubsection \\<open>Transfinite iteration of a function\\<close>\n\ncontext notes [[inductive_internals]]\nbegin\n\ninductive_set iterates :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a set\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  where\n    step: \"x \\<in> iterates f \\<Longrightarrow> f x \\<in> iterates f\"\n  | Sup: \"chain (op \\<le>) M \\<Longrightarrow> \\<forall>x\\<in>M. x \\<in> iterates f \\<Longrightarrow> Sup M \\<in> iterates f\"\n\nend\n\nlemma iterates_le_f: \"x \\<in> iterates f \\<Longrightarrow> monotone (op \\<le>) (op \\<le>) f \\<Longrightarrow> x \\<le> f x\"\n  by (induct x rule: iterates.induct)\n    (force dest: monotoneD intro!: ccpo_Sup_upper ccpo_Sup_least)+\n\nlemma chain_iterates:\n  assumes f: \"monotone (op \\<le>) (op \\<le>) f\"\n  shows \"chain (op \\<le>) (iterates f)\" (is \"chain _ ?C\")\nproof (rule chainI)\n  fix x y\n  assume \"x \\<in> ?C\" \"y \\<in> ?C\"\n  then show \"x \\<le> y \\<or> y \\<le> x\"\n  proof (induct x arbitrary: y rule: iterates.induct)\n    fix x y\n    assume y: \"y \\<in> ?C\"\n      and IH: \"\\<And>z. z \\<in> ?C \\<Longrightarrow> x \\<le> z \\<or> z \\<le> x\"\n    from y show \"f x \\<le> y \\<or> y \\<le> f x\"\n    proof (induct y rule: iterates.induct)\n      case (step y)\n      with IH f show ?case by (auto dest: monotoneD)\n    next\n      case (Sup M)\n      then have chM: \"chain (op \\<le>) M\"\n        and IH': \"\\<And>z. z \\<in> M \\<Longrightarrow> f x \\<le> z \\<or> z \\<le> f x\" by auto\n      show \"f x \\<le> Sup M \\<or> Sup M \\<le> f x\"\n      proof (cases \"\\<exists>z\\<in>M. f x \\<le> z\")\n        case True\n        then have \"f x \\<le> Sup M\"\n          apply rule\n          apply (erule order_trans)\n          apply (rule ccpo_Sup_upper[OF chM])\n          apply assumption\n          done\n        then show ?thesis ..\n      next\n        case False\n        with IH' show ?thesis\n          by (auto intro: ccpo_Sup_least[OF chM])\n      qed\n    qed\n  next\n    case (Sup M y)\n    show ?case\n    proof (cases \"\\<exists>x\\<in>M. y \\<le> x\")\n      case True\n      then have \"y \\<le> Sup M\"\n        apply rule\n        apply (erule order_trans)\n        apply (rule ccpo_Sup_upper[OF Sup(1)])\n        apply assumption\n        done\n      then show ?thesis ..\n    next\n      case False with Sup\n      show ?thesis by (auto intro: ccpo_Sup_least)\n    qed\n  qed\nqed\n\nlemma bot_in_iterates: \"Sup {} \\<in> iterates f\"\n  by (auto intro: iterates.Sup simp add: chain_empty)\n\n\nsubsection \\<open>Fixpoint combinator\\<close>\n\ndefinition fixp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"fixp f = Sup (iterates f)\"\n\nlemma iterates_fixp:\n  assumes f: \"monotone (op \\<le>) (op \\<le>) f\"\n  shows \"fixp f \\<in> iterates f\"\n  unfolding fixp_def\n  by (simp add: iterates.Sup chain_iterates f)\n\nlemma fixp_unfold:\n  assumes f: \"monotone (op \\<le>) (op \\<le>) f\"\n  shows \"fixp f = f (fixp f)\"\nproof (rule antisym)\n  show \"fixp f \\<le> f (fixp f)\"\n    by (intro iterates_le_f iterates_fixp f)\n  have \"f (fixp f) \\<le> Sup (iterates f)\"\n    by (intro ccpo_Sup_upper chain_iterates f iterates.step iterates_fixp)\n  then show \"f (fixp f) \\<le> fixp f\"\n    by (simp only: fixp_def)\nqed\n\nlemma fixp_lowerbound:\n  assumes f: \"monotone (op \\<le>) (op \\<le>) f\"\n    and z: \"f z \\<le> z\"\n  shows \"fixp f \\<le> z\"\n  unfolding fixp_def\nproof (rule ccpo_Sup_least[OF chain_iterates[OF f]])\n  fix x\n  assume \"x \\<in> iterates f\"\n  then show \"x \\<le> z\"\n  proof (induct x rule: iterates.induct)\n    case (step x)\n    from f \\<open>x \\<le> z\\<close> have \"f x \\<le> f z\" by (rule monotoneD)\n    also note z\n    finally show \"f x \\<le> z\" .\n  next\n    case (Sup M)\n    then show ?case\n      by (auto intro: ccpo_Sup_least)\n  qed\nqed\n\nend\n\n\nsubsection \\<open>Fixpoint induction\\<close>\n\nsetup \\<open>Sign.map_naming (Name_Space.mandatory_path \"ccpo\")\\<close>\n\ndefinition admissible :: \"('a set \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where \"admissible lub ord P \\<longleftrightarrow> (\\<forall>A. chain ord A \\<longrightarrow> A \\<noteq> {} \\<longrightarrow> (\\<forall>x\\<in>A. P x) \\<longrightarrow> P (lub A))\"\n\nlemma admissibleI:\n  assumes \"\\<And>A. chain ord A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \\<forall>x\\<in>A. P x \\<Longrightarrow> P (lub A)\"\n  shows \"ccpo.admissible lub ord P\"\n  using assms unfolding ccpo.admissible_def by fast\n\nlemma admissibleD:\n  assumes \"ccpo.admissible lub ord P\"\n  assumes \"chain ord A\"\n  assumes \"A \\<noteq> {}\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> P x\"\n  shows \"P (lub A)\"\n  using assms by (auto simp: ccpo.admissible_def)\n\nsetup \\<open>Sign.map_naming Name_Space.parent_path\\<close>\n\nlemma (in ccpo) fixp_induct:\n  assumes adm: \"ccpo.admissible Sup (op \\<le>) P\"\n  assumes mono: \"monotone (op \\<le>) (op \\<le>) f\"\n  assumes bot: \"P (Sup {})\"\n  assumes step: \"\\<And>x. P x \\<Longrightarrow> P (f x)\"\n  shows \"P (fixp f)\"\n  unfolding fixp_def\n  using adm chain_iterates[OF mono]\nproof (rule ccpo.admissibleD)\n  show \"iterates f \\<noteq> {}\"\n    using bot_in_iterates by auto\nnext\n  fix x\n  assume \"x \\<in> iterates f\"\n  then show \"P x\"\n  proof (induct rule: iterates.induct)\n    case prems: (step x)\n    from this(2) show ?case by (rule step)\n  next\n    case (Sup M)\n    then show ?case by (cases \"M = {}\") (auto intro: step bot ccpo.admissibleD adm)\n  qed\nqed\n\nlemma admissible_True: \"ccpo.admissible lub ord (\\<lambda>x. True)\"\n  unfolding ccpo.admissible_def by simp\n\n(*lemma admissible_False: \"\\<not> ccpo.admissible lub ord (\\<lambda>x. False)\"\nunfolding ccpo.admissible_def chain_def by simp\n*)\nlemma admissible_const: \"ccpo.admissible lub ord (\\<lambda>x. t)\"\n  by (auto intro: ccpo.admissibleI)\n\nlemma admissible_conj:\n  assumes \"ccpo.admissible lub ord (\\<lambda>x. P x)\"\n  assumes \"ccpo.admissible lub ord (\\<lambda>x. Q x)\"\n  shows \"ccpo.admissible lub ord (\\<lambda>x. P x \\<and> Q x)\"\n  using assms unfolding ccpo.admissible_def by simp\n\nlemma admissible_all:\n  assumes \"\\<And>y. ccpo.admissible lub ord (\\<lambda>x. P x y)\"\n  shows \"ccpo.admissible lub ord (\\<lambda>x. \\<forall>y. P x y)\"\n  using assms unfolding ccpo.admissible_def by fast\n\nlemma admissible_ball:\n  assumes \"\\<And>y. y \\<in> A \\<Longrightarrow> ccpo.admissible lub ord (\\<lambda>x. P x y)\"\n  shows \"ccpo.admissible lub ord (\\<lambda>x. \\<forall>y\\<in>A. P x y)\"\n  using assms unfolding ccpo.admissible_def by fast\n\nlemma chain_compr: \"chain ord A \\<Longrightarrow> chain ord {x \\<in> A. P x}\"\n  unfolding chain_def by fast\n\ncontext ccpo\nbegin\n\nlemma admissible_disj:\n  fixes P Q :: \"'a \\<Rightarrow> bool\"\n  assumes P: \"ccpo.admissible Sup (op \\<le>) (\\<lambda>x. P x)\"\n  assumes Q: \"ccpo.admissible Sup (op \\<le>) (\\<lambda>x. Q x)\"\n  shows \"ccpo.admissible Sup (op \\<le>) (\\<lambda>x. P x \\<or> Q x)\"\nproof (rule ccpo.admissibleI)\n  fix A :: \"'a set\"\n  assume chain: \"chain (op \\<le>) A\"\n  assume A: \"A \\<noteq> {}\" and P_Q: \"\\<forall>x\\<in>A. P x \\<or> Q x\"\n  have \"(\\<exists>x\\<in>A. P x) \\<and> (\\<forall>x\\<in>A. \\<exists>y\\<in>A. x \\<le> y \\<and> P y) \\<or> (\\<exists>x\\<in>A. Q x) \\<and> (\\<forall>x\\<in>A. \\<exists>y\\<in>A. x \\<le> y \\<and> Q y)\"\n    (is \"?P \\<or> ?Q\" is \"?P1 \\<and> ?P2 \\<or> _\")\n  proof (rule disjCI)\n    assume \"\\<not> ?Q\"\n    then consider \"\\<forall>x\\<in>A. \\<not> Q x\" | a where \"a \\<in> A\" \"\\<forall>y\\<in>A. a \\<le> y \\<longrightarrow> \\<not> Q y\"\n      by blast\n    then show ?P\n    proof cases\n      case 1\n      with P_Q have \"\\<forall>x\\<in>A. P x\" by blast\n      with A show ?P by blast\n    next\n      case 2\n      note a = \\<open>a \\<in> A\\<close>\n      show ?P\n      proof\n        from P_Q 2 have *: \"\\<forall>y\\<in>A. a \\<le> y \\<longrightarrow> P y\" by blast\n        with a have \"P a\" by blast\n        with a show ?P1 by blast\n        show ?P2\n        proof\n          fix x\n          assume x: \"x \\<in> A\"\n          with chain a show \"\\<exists>y\\<in>A. x \\<le> y \\<and> P y\"\n          proof (rule chainE)\n            assume le: \"a \\<le> x\"\n            with * a x have \"P x\" by blast\n            with x le show ?thesis by blast\n          next\n            assume \"a \\<ge> x\"\n            with a \\<open>P a\\<close> show ?thesis by blast\n          qed\n        qed\n      qed\n    qed\n  qed\n  moreover\n  have \"Sup A = Sup {x \\<in> A. P x}\" if \"\\<forall>x\\<in>A. \\<exists>y\\<in>A. x \\<le> y \\<and> P y\" for P\n  proof (rule antisym)\n    have chain_P: \"chain (op \\<le>) {x \\<in> A. P x}\"\n      by (rule chain_compr [OF chain])\n    show \"Sup A \\<le> Sup {x \\<in> A. P x}\"\n      apply (rule ccpo_Sup_least [OF chain])\n      apply (drule that [rule_format])\n      apply clarify\n      apply (erule order_trans)\n      apply (simp add: ccpo_Sup_upper [OF chain_P])\n      done\n    show \"Sup {x \\<in> A. P x} \\<le> Sup A\"\n      apply (rule ccpo_Sup_least [OF chain_P])\n      apply clarify\n      apply (simp add: ccpo_Sup_upper [OF chain])\n      done\n  qed\n  ultimately\n  consider \"\\<exists>x. x \\<in> A \\<and> P x\" \"Sup A = Sup {x \\<in> A. P x}\"\n    | \"\\<exists>x. x \\<in> A \\<and> Q x\" \"Sup A = Sup {x \\<in> A. Q x}\"\n    by blast\n  then show \"P (Sup A) \\<or> Q (Sup A)\"\n    apply cases\n     apply simp_all\n     apply (rule disjI1)\n     apply (rule ccpo.admissibleD [OF P chain_compr [OF chain]]; simp)\n    apply (rule disjI2)\n    apply (rule ccpo.admissibleD [OF Q chain_compr [OF chain]]; simp)\n    done\nqed\n\nend\n\ninstance complete_lattice \\<subseteq> ccpo\n  by standard (fast intro: Sup_upper Sup_least)+\n\nlemma lfp_eq_fixp:\n  assumes mono: \"mono f\"\n  shows \"lfp f = fixp f\"\nproof (rule antisym)\n  from mono have f': \"monotone (op \\<le>) (op \\<le>) f\"\n    unfolding mono_def monotone_def .\n  show \"lfp f \\<le> fixp f\"\n    by (rule lfp_lowerbound, subst fixp_unfold [OF f'], rule order_refl)\n  show \"fixp f \\<le> lfp f\"\n    by (rule fixp_lowerbound [OF f']) (simp add: lfp_fixpoint [OF mono])\nqed\n\nhide_const (open) iterates fixp\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Complete_Partial_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.8705972633721708, "lm_q1q2_score": 0.7790012604831191}}
{"text": "section \\<open>Challenge 1.A\\<close>\ntheory Challenge1A\n  imports Main\n  \"../../../../SeLFiE\"\nbegin\n\ntext \\<open>Problem definition:\n\\<^url>\\<open>https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Verify%20This/Challenges%202019/ghc_sort.pdf\\<close>\\<close>\n\n  subsection \\<open>Implementation\\<close>\n  text \\<open>We phrase the algorithm as a functional program. \n    Instead of a list of indexes for segment boundaries,\n    we return a list of lists, containing the segments.\\<close>\n\n  text \\<open>We start with auxiliary functions to take the longest\n    increasing/decreasing sequence from the start of the list\n  \\<close>  \n  fun take_incr :: \"int list \\<Rightarrow> _\" where\n    \"take_incr [] = []\"\n  | \"take_incr [x] = [x]\"\n  | \"take_incr (x#y#xs) = (if x<y then x#take_incr (y#xs) else [x])\"  \n\n  fun take_decr :: \"int list \\<Rightarrow> _\" where\n    \"take_decr [] = []\"\n  | \"take_decr [x] = [x]\"\n  | \"take_decr (x#y#xs) = (if x\\<ge>y then x#take_decr (y#xs) else [x])\"  \n  \n  fun take where\n    \"take [] = []\"\n  | \"take [x] = [x]\"\n  | \"take (x#y#xs) = (if x<y then take_incr (x#y#xs) else take_decr (x#y#xs))\"  \n\n  \n  definition \"take2 xs \\<equiv> let l=take xs in (l,drop (length l) xs)\"\n    \\<comment> \\<open>Splits of a longest increasing/decreasing sequence from the list\\<close>\n\n  \n  text \\<open>The main algorithm then iterates until the whole input list is split\\<close>\n  function cuts where\n    \"cuts xs = (if xs=[] then [] else let (c,xs) = take2 xs in c#cuts xs)\"    \n    by pat_completeness auto\n\n  subsection \\<open>Termination\\<close>  \n  text \\<open>First, we show termination. This will give us induction and proper unfolding lemmas.\\<close>\n\n  lemma take_non_empty:\n    \"take xs \\<noteq> []\" if \"xs \\<noteq> []\"\n    using that\n    apply (cases xs)\n     apply clarsimp\n    subgoal for x ys\n      apply (cases ys)\n       apply auto\n      done\n    done\n\n  termination\n    apply (relation \"measure length\")\n     apply (auto simp: take2_def Let_def)\n    using take_non_empty\n    apply auto\n    done\n    \n  declare cuts.simps[simp del]  \n    \n  subsection \\<open>Correctness\\<close>\n  \n\n  subsubsection \\<open>Property 1: The Exact Sequence is Covered\\<close>\n  lemma tdconc: \"\\<exists>ys. xs = take_decr xs @ ys\"semantic_induct\n    apply (induction xs rule: take_decr.induct)\n    apply auto\n    done\n\n  lemma ticonc: \"\\<exists>ys. xs = take_incr xs @ ys\"semantic_induct\n    apply (induction xs rule: take_incr.induct)\n    apply auto\n    done\n\n  lemma take_conc: \"\\<exists>ys. xs = take xs@ys\"  \n    using tdconc ticonc \n    apply (cases xs rule: take.cases)\n    by auto \n  \n  theorem concat_cuts: \"concat (cuts xs) = xs\"semantic_induct\n    apply (induction xs rule: cuts.induct)\n    apply (subst cuts.simps)\n    apply (auto simp: take2_def Let_def)\n    by (metis append_eq_conv_conj take_conc)  \n  \n        \n        \n  subsubsection \\<open>Property 2: Monotonicity\\<close>\n  text \\<open>We define constants to specify increasing/decreasing sequences.\\<close>\n  fun incr where\n    \"incr [] \\<longleftrightarrow> True\"\n  | \"incr [_] \\<longleftrightarrow> True\"\n  | \"incr (x#y#xs) \\<longleftrightarrow> x<y \\<and> incr (y#xs)\"  \n  \n  fun decr where\n    \"decr [] \\<longleftrightarrow> True\"\n  | \"decr [_] \\<longleftrightarrow> True\"\n  | \"decr (x#y#xs) \\<longleftrightarrow> x\\<ge>y \\<and> decr (y#xs)\"  \n  \n  lemma tki: \"incr (take_incr xs)\"semantic_induct\n    apply (induction xs rule: take_incr.induct)\n    apply auto\n    apply (case_tac xs)\n    apply auto\n    done\n    \n  lemma tkd: \"decr (take_decr xs)\"semantic_induct\n    apply (induction xs rule: take_decr.induct)\n    apply auto\n    apply (case_tac xs)\n    apply auto\n    done\n  \n  lemma icod: \"incr (take xs) \\<or> decr (take xs)\"\n    apply (cases xs rule: take.cases) \n    apply (auto simp: tki tkd simp del: take_incr.simps take_decr.simps)\n    done   \n        \ntheorem cuts_incr_decr: \"\\<forall>c\\<in>set (cuts xs). incr c \\<or> decr c\"  semantic_induct\n  all_induction_heuristic [on[\"xs\"], arb[],rule[\"cuts.induct\"]]\n    apply (induction xs rule: cuts.induct)\n    apply (subst cuts.simps)\n    apply (auto simp: take2_def Let_def)\n    using icod by blast\n    \n      \n  subsubsection \\<open>Property 3: Maximality\\<close>      \n  text \\<open>Specification of a cut that consists of maximal segments:\n    The segements are non-empty, and for every two neighbouring segments,\n    the first value of the last segment cannot be used to continue the first segment:\n  \\<close>\n  fun maxi where\n     \"maxi [] \\<longleftrightarrow> True\"\n   | \"maxi [c] \\<longleftrightarrow> c\\<noteq>[]\"\n   | \"maxi (c1#c2#cs) \\<longleftrightarrow> (c1\\<noteq>[] \\<and> c2\\<noteq>[] \\<and> maxi (c2#cs) \\<and> ( \n        incr c1 \\<and> \\<not>(last c1 < hd c2) \n      \\<or> decr c1 \\<and> \\<not>(last c1 \\<ge> hd c2)        \n        ))\"  \n\n  text \\<open>Obviously, our specification implies that there are no \n    empty segments\\<close>    \n  lemma maxi_imp_non_empty: \"maxi xs \\<Longrightarrow> []\\<notin>set xs\"  \n    by (induction xs rule: maxi.induct) auto\n        \n          \n  lemma tdconc': \"xs\\<noteq>[] \\<Longrightarrow>\n    \\<exists>ys. xs = take_decr xs @ ys \\<and> (ys\\<noteq>[] \n      \\<longrightarrow> \\<not>(last (take_decr xs) \\<ge> hd ys))\"semantic_induct\n    apply (induction xs rule: take_decr.induct)\n    apply auto\n    apply (case_tac xs) apply (auto split: if_splits)\n    done\n    \n  lemma ticonc': \"xs\\<noteq>[] \\<Longrightarrow> \\<exists>ys. xs = take_incr xs @ ys \\<and> (ys\\<noteq>[] \\<longrightarrow> \\<not>(last (take_incr xs) < hd ys))\"semantic_induct\n    apply (induction xs rule: take_incr.induct)\n    apply auto\n    apply (case_tac xs) apply (auto split: if_splits)\n    done\n\n  lemma take_conc': \"xs\\<noteq>[] \\<Longrightarrow> \\<exists>ys. xs = take xs@ys \\<and> (ys\\<noteq>[] \\<longrightarrow> (\n    take xs=take_incr xs \\<and> \\<not>(last (take_incr xs) < hd ys)\n  \\<or> take xs=take_decr xs \\<and> \\<not>(last (take_decr xs) \\<ge> hd ys)  \n  ))\"  \n    using tdconc' ticonc' \n    apply (cases xs rule: take.cases)\n    by auto \n    \n    \n  lemma take_decr_non_empty:\n    \"take_decr xs \\<noteq> []\" if \"xs \\<noteq> []\"\n    using that\n    apply (cases xs)\n     apply auto\n    subgoal for x ys\n      apply (cases ys)\n       apply (auto split: if_split_asm)\n      done\n    done\n  \n  lemma take_incr_non_empty:\n    \"take_incr xs \\<noteq> []\" if \"xs \\<noteq> []\"\n    using that\n    apply (cases xs)\n     apply auto\n    subgoal for x ys\n      apply (cases ys)\n       apply (auto split: if_split_asm)\n      done\n    done\n    \n  lemma take_conc'': \"xs\\<noteq>[] \\<Longrightarrow> \\<exists>ys. xs = take xs@ys \\<and> (ys\\<noteq>[] \\<longrightarrow> (\n    incr (take xs) \\<and> \\<not>(last (take xs) < hd ys)\n  \\<or> decr (take xs) \\<and> \\<not>(last (take xs) \\<ge> hd ys)  \n  ))\"  \n    using tdconc' ticonc' tki tkd \n    apply (cases xs rule: take.cases)\n    apply auto\n    apply (auto simp add: take_incr_non_empty) \n    apply (simp add: take_decr_non_empty)\n    apply (metis list.distinct(1) take_incr.simps(3))\n    by (smt list.simps(3) take_decr.simps(3))\n    \n    \n  \n  \n\n  lemma inv_cuts: \"cuts xs = c#cs \\<Longrightarrow> \\<exists>ys. c=take xs \\<and> xs=c@ys \\<and> cs = cuts ys\"\n    apply (subst (asm) cuts.simps)\n    apply (cases xs rule: cuts.cases)\n    apply (auto split: if_splits simp: take2_def Let_def)\n    by (metis append_eq_conv_conj take_conc)\n    \ntheorem maximal_cuts: \"maxi (cuts xs)\" semantic_induct\n  all_induction_heuristic [on[\"cuts xs\"], arb[],rule[\"maxi.induct\"]]\n    apply (induction \"cuts xs\" arbitrary: xs rule: maxi.induct)\n    subgoal by auto\n    subgoal for c xs\n      apply (drule sym; simp)\n      apply (subst (asm) cuts.simps)\n      apply (auto split: if_splits prod.splits simp: take2_def Let_def take_non_empty)\n      done\n    subgoal for c1 c2 cs xs\n      apply (drule sym)\n      apply simp\n      apply (drule inv_cuts; clarsimp)\n      apply auto\n      subgoal by (metis cuts.simps list.distinct(1) take_non_empty) \n      subgoal by (metis append.left_neutral inv_cuts not_Cons_self) \n      subgoal using icod by blast \n      subgoal by (metis\n            Nil_is_append_conv cuts.simps hd_append2 inv_cuts list.distinct(1)\n            same_append_eq take_conc'' take_non_empty) \n      subgoal by (metis\n            append_is_Nil_conv cuts.simps hd_append2 inv_cuts list.distinct(1)\n            same_append_eq take_conc'' take_non_empty) \n      done\n    done\n\n  subsubsection \\<open>Equivalent Formulation Over Indexes\\<close>\n  text \\<open>After the competition, we got the comment that a specification of \n    monotonic sequences via indexes might be more readable.\n  \n    We show that our functional specification is equivalent to a \n    specification over indexes.\\<close>\n    \n  fun ii_induction where\n    \"ii_induction [] = ()\"\n  | \"ii_induction [_] = ()\"\n  | \"ii_induction (_#y#xs) = ii_induction (y#xs)\"      \n\n  locale cnvSpec =\n    fixes fP P\n    assumes [simp]: \"fP [] \\<longleftrightarrow> True\"\n    assumes [simp]: \"fP [x] \\<longleftrightarrow> True\"\n    assumes [simp]: \"fP (a#b#xs) \\<longleftrightarrow> P a b \\<and> fP (b#xs)\"\n  begin\n\n    lemma idx_spec: \"fP xs \\<longleftrightarrow> (\\<forall>i<length xs - 1. P (xs!i) (xs!Suc i))\"semantic_induct\n      apply (induction xs rule: ii_induction.induct)\n      using less_Suc_eq_0_disj\n      by auto\n  \n  end\n\n  locale cnvSpec' =\n    fixes fP P P'\n    assumes [simp]: \"fP [] \\<longleftrightarrow> True\"\n    assumes [simp]: \"fP [x] \\<longleftrightarrow> P' x\"\n    assumes [simp]: \"fP (a#b#xs) \\<longleftrightarrow> P' a \\<and> P' b \\<and> P a b \\<and> fP (b#xs)\"\n  begin\n\n    lemma idx_spec: \"fP xs \\<longleftrightarrow> (\\<forall>i<length xs. P' (xs!i)) \\<and> (\\<forall>i<length xs - 1. P (xs!i) (xs!Suc i))\"semantic_induct\n      apply (induction xs rule: ii_induction.induct)\n      apply auto []\n      apply auto []\n      apply clarsimp\n      by (smt less_Suc_eq_0_disj nth_Cons_0 nth_Cons_Suc)\n  \n  end\n    \n  interpretation INCR: cnvSpec incr \"(<)\"\n    apply unfold_locales by auto\n  \n  interpretation DECR: cnvSpec decr \"(\\<ge>)\"\n    apply unfold_locales by auto\n  \n  interpretation MAXI: cnvSpec' maxi \"\\<lambda>c1 c2. ( ( \n        incr c1 \\<and> \\<not>(last c1 < hd c2) \n      \\<or> decr c1 \\<and> \\<not>(last c1 \\<ge> hd c2)        \n        ))\"\n      \"\\<lambda>x. x \\<noteq> []\"  \n    apply unfold_locales by auto\n  \n  lemma incr_by_idx: \"incr xs = (\\<forall>i<length xs - 1. xs ! i < xs ! Suc i)\" \n    by (rule INCR.idx_spec)\n    \n  lemma decr_by_idx: \"decr xs = (\\<forall>i<length xs - 1. xs ! i \\<ge> xs ! Suc i)\" \n    by (rule DECR.idx_spec)\n    \n  lemma maxi_by_idx: \"maxi xs \\<longleftrightarrow>\n    (\\<forall>i<length xs. xs ! i \\<noteq> []) \\<and>\n    (\\<forall>i<length xs - 1. \n         incr (xs ! i) \\<and> \\<not> last (xs ! i) < hd (xs ! Suc i) \n       \\<or> decr (xs ! i) \\<and> \\<not> hd (xs ! Suc i) \\<le> last (xs ! i)\n    )\"\n    by (rule MAXI.idx_spec)\n\n  theorem all_correct:  \n    \"concat (cuts xs) = xs\"\n    \"\\<forall>c\\<in>set (cuts xs). incr c \\<or> decr c\"\n    \"maxi (cuts xs)\"\n    \"[] \\<notin> set (cuts xs)\"\n    using cuts_incr_decr concat_cuts maximal_cuts \n          maxi_imp_non_empty[OF maximal_cuts]\n    by auto\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/VerifyThis2019/Challenge1A.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.870597265050901, "lm_q2_score": 0.8947894604912848, "lm_q1q2_score": 0.7790012571000837}}
{"text": "(*\n  File: Partial_Equiv_Rel.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Partial equivalence relation\\<close>\n\ntheory Partial_Equiv_Rel\n  imports \"Auto2_HOL.Auto2_Main\"\nbegin\n  \ntext \\<open>\n  Partial equivalence relations, following theory\n  Lib/Partial\\_Equivalence\\_Relation in \\<^cite>\\<open>\"Collections-AFP\"\\<close>.\n\\<close>\n\ndefinition part_equiv :: \"('a \\<times> 'a) set \\<Rightarrow> bool\" where [rewrite]:\n  \"part_equiv R \\<longleftrightarrow> sym R \\<and> trans R\"\n\nlemma part_equivI [forward]: \"sym R \\<Longrightarrow> trans R \\<Longrightarrow> part_equiv R\" by auto2\nlemma part_equivD1 [forward]: \"part_equiv R \\<Longrightarrow> sym R\" by auto2\nlemma part_equivD2 [forward]: \"part_equiv R \\<Longrightarrow> trans R\" by auto2\nsetup \\<open>del_prfstep_thm_eqforward @{thm part_equiv_def}\\<close>\n\nsubsection \\<open>Combining two elements in a partial equivalence relation\\<close>\n\ndefinition per_union :: \"('a \\<times> 'a) set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<times> 'a) set\" where [rewrite]:\n  \"per_union R a b = R \\<union> { (x,y). (x,a)\\<in>R \\<and> (b,y)\\<in>R } \\<union> { (x,y). (x,b)\\<in>R \\<and> (a,y)\\<in>R }\"\n\nlemma per_union_memI1 [backward]:\n  \"(x, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> per_union R a b\" by (simp add: per_union_def)\nsetup \\<open>add_forward_prfstep_cond @{thm per_union_memI1} [with_term \"per_union ?R ?a ?b\"]\\<close>\n\nlemma per_union_memI2 [backward]:\n  \"(x, a) \\<in> R \\<Longrightarrow> (b, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> per_union R a b\" by (simp add: per_union_def)\n\nlemma per_union_memI3 [backward]:\n  \"(x, b) \\<in> R \\<Longrightarrow> (a, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> per_union R a b\" by (simp add: per_union_def)\n\nlemma per_union_memD:\n  \"(x, y) \\<in> per_union R a b \\<Longrightarrow> (x, y) \\<in> R \\<or> ((x, a) \\<in> R \\<and> (b, y) \\<in> R) \\<or> ((x, b) \\<in> R \\<and> (a, y) \\<in> R)\"\n  by (simp add: per_union_def)\nsetup \\<open>add_forward_prfstep_cond @{thm per_union_memD} [with_cond \"?x \\<noteq> ?y\", with_filt (order_filter \"x\" \"y\")]\\<close>\nsetup \\<open>del_prfstep_thm @{thm per_union_def}\\<close>\n\nlemma per_union_is_trans [forward]:\n  \"trans R \\<Longrightarrow> trans (per_union R a b)\" by auto2\n\nlemma per_union_is_part_equiv [forward]:\n  \"part_equiv R \\<Longrightarrow> part_equiv (per_union R a b)\" by auto2\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Auto2_Imperative_HOL/Functional/Partial_Equiv_Rel.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.870597265050901, "lm_q1q2_score": 0.7790012522149381}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Extended Regular Expressions\"\n\ntheory Regular_Exp2\nimports Regular_Set\nbegin\n\ndatatype (atoms: 'a) rexp =\n  is_Zero: Zero |\n  is_One: One |\n  Atom 'a |\n  Plus \"('a rexp)\" \"('a rexp)\" |\n  Times \"('a rexp)\" \"('a rexp)\" |\n  Star \"('a rexp)\" |\n  Not \"('a rexp)\" |\n  Inter \"('a rexp)\" \"('a rexp)\"\n\ncontext\nfixes S :: \"'a set\"\nbegin\n\nprimrec lang :: \"'a rexp => 'a lang\" where\n\"lang Zero = {}\" |\n\"lang One = {[]}\" |\n\"lang (Atom a) = {[a]}\" |\n\"lang (Plus r s) = (lang r) Un (lang s)\" |\n\"lang (Times r s) = conc (lang r) (lang s)\" |\n\"lang (Star r) = star(lang r)\" |\n\"lang (Not r) = lists S - lang r\" |\n\"lang (Inter r s) = (lang r Int lang s)\"\n\nend\n\nlemma lang_subset_lists: \"atoms r \\<subseteq> S \\<Longrightarrow> lang S r \\<subseteq> lists S\"\nby(induction r)(auto simp: conc_subset_lists star_subset_lists)\n\nprimrec nullable :: \"'a rexp \\<Rightarrow> bool\" where\n\"nullable Zero = False\" |\n\"nullable One = True\" |\n\"nullable (Atom c) = False\" |\n\"nullable (Plus r1 r2) = (nullable r1 \\<or> nullable r2)\" |\n\"nullable (Times r1 r2) = (nullable r1 \\<and> nullable r2)\" |\n\"nullable (Star r) = True\" |\n\"nullable (Not r) = (\\<not> (nullable r))\" |\n\"nullable (Inter r s) = (nullable r \\<and> nullable s)\"\n\nlemma nullable_iff: \"nullable r \\<longleftrightarrow> [] \\<in> lang S r\"\nby (induct r) (auto simp add: conc_def split: if_splits)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Regular-Sets/Regular_Exp2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391727723469, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7789482391805258}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_MSortBU2IsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(Nat list) list => (Nat list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(Nat list) list => Nat list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun risers :: \"Nat list => (Nat list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if le y y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun msortbu2 :: \"Nat list => Nat list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\nfun insert :: \"Nat => Nat list => Nat list\" where\n  \"insert x (nil2) = cons2 x (nil2)\"\n| \"insert x (cons2 z xs) =\n     (if le x z then cons2 x (cons2 z xs) else cons2 z (insert x xs))\"\n\nfun isort :: \"Nat list => Nat list\" where\n  \"isort (nil2) = nil2\"\n| \"isort (cons2 y xs) = insert y (isort xs)\"\n\ntheorem property0 :\n  \"((msortbu2 xs) = (isort xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_MSortBU2IsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7788416357881073}}
{"text": "theory Predic_Logic\n  imports Main\nbegin\n\nlemma \"(\\<exists>x. \\<forall>y. P(x,y)) \\<longrightarrow> (\\<forall> y. \\<exists>x. P(x,y))\"\n  apply (rule impI)\n  apply (erule exE)\n  apply (rule allI)\n  apply (erule allE)\n  apply (rule exI)\n  apply assumption\n  done\n\nlemma \"(\\<forall>x. P(x) \\<longrightarrow> Q) = ((\\<exists>x. P(x)) \\<longrightarrow> Q)\"\n  apply (rule iffI)\n   apply (rule impI)\n   apply (erule exE)\n   apply (erule allE)\n   apply (erule impE)\n    apply assumption+\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule impE)\n   apply (rule exI)\n   apply assumption+\n  done\n\nlemma \"(\\<not> (\\<forall>x. P x)) = (\\<exists>x. \\<not> P x)\"\nproof (rule iffI)\n  assume \"\\<not> (\\<forall>x. P x)\"\n  show \"\\<exists>x. \\<not> P x\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<exists>x. \\<not> P x)\"\n    then have \"\\<forall>x. P x\" by simp \n    with \\<open>\\<not> (\\<forall>x. P x)\\<close> show False by contradiction\n  qed\nnext\n  assume \"\\<exists>x. \\<not> P x\"\n  then obtain c where \"\\<not> P c\" by (rule exE)\n  show \"\\<not> (\\<forall>x. P x)\"\n  proof (rule notI)\n    assume \"\\<forall>x. P x\"\n    then have \"P c\" by (rule allE)\n    with \\<open>\\<not> P c\\<close> show False by contradiction\n  qed\nqed\n\nend", "meta": {"author": "waynee95", "repo": "isabelle-hol-playground", "sha": "6ed735e98e99b475088e59932d0bae43dbd314d8", "save_path": "github-repos/isabelle/waynee95-isabelle-hol-playground", "path": "github-repos/isabelle/waynee95-isabelle-hol-playground/isabelle-hol-playground-6ed735e98e99b475088e59932d0bae43dbd314d8/Predic_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632956467157, "lm_q2_score": 0.8397339736884711, "lm_q1q2_score": 0.778738465306253}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nheader {* Ordinal Arithmetic *}\n\ntheory OrdinalArith\nimports OrdinalRec\nbegin\n\nsubsection {* Addition *}\n\ninstantiation ordinal :: plus\nbegin\n\ndefinition\n  \"op + = (\\<lambda>x. ordinal_rec x (\\<lambda>p. oSuc))\"\n\ninstance ..\n\nend\n\n\n\nlemma ordinal_plus_0 [simp]: \"x + 0 = (x::ordinal)\"\nby (simp add: plus_ordinal_def)\n\nlemma ordinal_plus_oSuc [simp]: \"x + oSuc y = oSuc (x + y)\"\nby (simp add: plus_ordinal_def)\n\nlemma ordinal_plus_oLimit [simp]: \"x + oLimit f = oLimit (\\<lambda>n. x + f n)\"\nby (simp add: normal.oLimit normal_plus)\n\nlemma ordinal_0_plus [simp]: \"0 + x = (x::ordinal)\"\nby (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_plus_assoc:\n\"(x + y) + z = x + (y + z::ordinal)\"\nby (rule_tac a=z in oLimit_induct, simp_all)\n\nlemma ordinal_plus_monoL [rule_format]:\n\"\\<forall>x x'. x \\<le> x' \\<longrightarrow> x + y \\<le> x' + (y::ordinal)\"\n apply (rule_tac a=y in oLimit_induct, simp_all)\n apply clarify\n apply (rule oLimit_leI, clarify)\n apply (rule_tac n=n in le_oLimitI)\n apply simp\ndone\n\nlemma ordinal_plus_monoR: \"y \\<le> y' \\<Longrightarrow> x + y \\<le> x + (y'::ordinal)\"\nby (rule normal.monoD[OF normal_plus])\n\nlemma ordinal_plus_mono:\n\"\\<lbrakk>x \\<le> x'; y \\<le> y'\\<rbrakk> \\<Longrightarrow> x + y \\<le> x' + (y'::ordinal)\"\nby (rule order_trans[OF ordinal_plus_monoL ordinal_plus_monoR])\n\nlemma ordinal_plus_strict_monoR: \"y < y' \\<Longrightarrow> x + y < x + (y'::ordinal)\"\nby (rule normal.strict_monoD[OF normal_plus])\n\nlemma ordinal_le_plusL [simp]: \"y \\<le> x + (y::ordinal)\"\nby (cut_tac ordinal_plus_monoL[OF ordinal_0_le], simp)\n\nlemma ordinal_le_plusR [simp]: \"x \\<le> x + (y::ordinal)\"\nby (cut_tac ordinal_plus_monoR[OF ordinal_0_le], simp)\n\nlemma ordinal_less_plusR: \"0 < y \\<Longrightarrow> x < x + (y::ordinal)\"\nby (drule_tac ordinal_plus_strict_monoR, simp)\n\nlemma ordinal_plus_left_cancel [simp]:\n\"(w + x = w + y) = (x = (y::ordinal))\"\nby (rule normal.cancel_eq[OF normal_plus])\n\nlemma ordinal_plus_left_cancel_le [simp]:\n\"(w + x \\<le> w + y) = (x \\<le> (y::ordinal))\"\nby (rule normal.cancel_le[OF normal_plus])\n\nlemma ordinal_plus_left_cancel_less [simp]:\n\"(w + x < w + y) = (x < (y::ordinal))\"\nby (rule normal.cancel_less[OF normal_plus])\n\nlemma ordinal_plus_not_0: \"(0 < x + y) = (0 < x \\<or> 0 < (y::ordinal))\"\n apply safe\n   apply simp\n  apply (erule order_less_le_trans, rule ordinal_le_plusR)\n apply (erule order_less_le_trans, rule ordinal_le_plusL)\ndone\n\nlemma not_inject: \"(\\<not> P) = (\\<not> Q) \\<Longrightarrow> P = Q\"\nby auto\n\nlemma ordinal_plus_eq_0:\n\"((x::ordinal) + y = 0) = (x = 0 \\<and> y = 0)\"\nby (rule not_inject, simp add: ordinal_plus_not_0)\n\n\nsubsection {* Subtraction *}\n\ninstantiation ordinal :: minus\nbegin\n\ndefinition\n  minus_ordinal_def:\n    \"x - y = ordinal_rec 0 (\\<lambda>p w. if y \\<le> p then oSuc w else w) x\"\n\ninstance ..\n\nend\n\nlemma continuous_minus: \"continuous (\\<lambda>x. x - y)\"\n apply (unfold minus_ordinal_def)\n apply (rule continuous_ordinal_rec)\n apply (simp add: order_less_imp_le)\ndone\n\nlemma ordinal_0_minus [simp]: \"0 - x = (0::ordinal)\"\nby (simp add: minus_ordinal_def)\n\nlemma ordinal_oSuc_minus [simp]: \"y \\<le> x \\<Longrightarrow> oSuc x - y = oSuc (x - y)\"\nby (simp add: minus_ordinal_def)\n\nlemma ordinal_oLimit_minus [simp]: \"oLimit f - y = oLimit (\\<lambda>n. f n - y)\"\nby (rule continuousD[OF continuous_minus])\n\nlemma ordinal_minus_0 [simp]: \"x - 0 = (x::ordinal)\"\nby (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_oSuc_minus2: \"x < y \\<Longrightarrow> oSuc x - y = x - y\"\nby (simp add: minus_ordinal_def linorder_not_le[symmetric])\n\nlemma ordinal_minus_eq_0 [rule_format, simp]:\n\"x \\<le> y \\<longrightarrow> x - y = (0::ordinal)\"\n apply (rule_tac a=x in oLimit_induct)\n   apply simp\n  apply (simp add: ordinal_oSuc_minus2 order_less_imp_le oSuc_le_eq_less)\n apply (simp add: order_trans[OF le_oLimit])\ndone\n\nlemma ordinal_plus_minus1 [simp]: \"(x + y) - x = (y::ordinal)\"\nby (rule_tac a=y in oLimit_induct, simp_all)\n\nlemma ordinal_plus_minus2 [simp]: \"x \\<le> y \\<Longrightarrow> x + (y - x) = (y::ordinal)\"\n apply (subgoal_tac \"\\<forall>z. y < x + z \\<longrightarrow> x + (y - x) = y\")\n  apply (drule_tac x=\"oSuc y\" in spec, erule mp)\n  apply (rule order_less_le_trans[OF less_oSuc], simp)\n apply (rule allI, rule_tac a=z in oLimit_induct)\n   apply (simp add: linorder_not_less[symmetric])\n  apply (clarsimp simp add: less_oSuc_eq_le)\n apply (clarsimp, drule less_oLimitD, clarsimp)\ndone\n\nlemma ordinal_minusI: \"x = y + z \\<Longrightarrow> x - y = (z::ordinal)\"\nby simp\n\nlemma ordinal_minus_less_eq [simp]:\n\"(y::ordinal) \\<le> x \\<Longrightarrow> (x - y < z) = (x < y + z)\"\n apply (subgoal_tac \"(x - y < z) = (y + (x - y) < y + z)\", simp)\n apply (simp only: ordinal_plus_left_cancel_less)\ndone\n\nlemma ordinal_minus_le_eq [simp]:\n\"(x - y \\<le> z) = (x \\<le> y + (z::ordinal))\"\n apply (rule_tac x=x and y=y in linorder_le_cases)\n  apply (simp, erule order_trans, simp)\n apply (subgoal_tac \"(x - y \\<le> z) = (y + (x - y) \\<le> y + z)\", simp)\n apply (simp only: ordinal_plus_left_cancel_le)\ndone\n\nlemma ordinal_minus_monoL: \"x \\<le> y \\<Longrightarrow> x - z \\<le> y - (z::ordinal)\"\nby (erule continuous.monoD[OF continuous_minus])\n\nlemma ordinal_minus_monoR: \"x \\<le> y \\<Longrightarrow> z - y \\<le> z - (x::ordinal)\"\n apply (rule_tac x=y and y=z in linorder_le_cases)\n  apply (subst ordinal_minus_le_eq)\n  apply (subgoal_tac \"x + (z - x) \\<le> y + (z - x)\")\n   apply (drule order_trans, assumption, simp)\n  apply (erule ordinal_plus_monoL)\n apply simp\ndone\n\n\nsubsection {* Multiplication *}\n\ninstantiation ordinal :: times\nbegin\n\ndefinition\n  times_ordinal_def: \"op * = (\\<lambda>x. ordinal_rec 0 (\\<lambda>p w. w + x))\"\n\ninstance ..\n\nend\n\nlemma continuous_times: \"continuous (op * x)\"\nby (simp add: times_ordinal_def continuous_ordinal_rec)\n\nlemma normal_times: \"0 < x \\<Longrightarrow> normal (op * x)\"\n apply (unfold times_ordinal_def)\n apply (rule normal_ordinal_rec[rule_format], rename_tac y)\n apply (subgoal_tac \"y + 0 < y + x\", simp)\n apply (simp only: ordinal_plus_left_cancel_less)\ndone\n\nlemma ordinal_times_0 [simp]: \"x * 0 = (0::ordinal)\"\nby (simp add: times_ordinal_def)\n\nlemma ordinal_times_oSuc [simp]: \"x * oSuc y = (x * y) + x\"\nby (simp add: times_ordinal_def)\n\nlemma ordinal_times_oLimit [simp]: \"x * oLimit f = oLimit (\\<lambda>n. x * f n)\"\nby (simp add: times_ordinal_def ordinal_rec_oLimit)\n\nlemma ordinal_0_times [simp]: \"0 * x = (0::ordinal)\"\nby (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_1_times [simp]: \"oSuc 0 * x = (x::ordinal)\"\nby (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_times_1 [simp]: \"x * oSuc 0 = (x::ordinal)\"\nby simp\n\nlemma ordinal_times_distrib:\n\"x * (y + z) = (x * y) + (x * z::ordinal)\"\nby (rule_tac a=z in oLimit_induct, simp_all add: ordinal_plus_assoc)\n\nlemma ordinal_times_assoc:\n\"(x * y::ordinal) * z = x * (y * z)\"\nby (rule_tac a=z in oLimit_induct, simp_all add: ordinal_times_distrib)\n\nlemma ordinal_times_monoL [rule_format]:\n\"\\<forall>x x'. x \\<le> x' \\<longrightarrow> x * y \\<le> x' * (y::ordinal)\"\n apply (rule_tac a=y in oLimit_induct)\n   apply simp\n  apply clarify\n  apply (simp add: ordinal_plus_mono)\n apply clarsimp\n apply (rule oLimit_leI, clarify)\n apply (rule_tac n=n in le_oLimitI)\n apply simp\ndone\n\nlemma ordinal_times_monoR: \"y \\<le> y' \\<Longrightarrow> x * y \\<le> x * (y'::ordinal)\"\nby (rule continuous.monoD[OF continuous_times])\n\nlemma ordinal_times_mono:\n\"\\<lbrakk>x \\<le> x'; y \\<le> y'\\<rbrakk> \\<Longrightarrow> x * y \\<le> x' * (y'::ordinal)\"\nby (rule order_trans[OF ordinal_times_monoL ordinal_times_monoR])\n\nlemma ordinal_times_strict_monoR:\n\"\\<lbrakk>y < y'; 0 < x\\<rbrakk> \\<Longrightarrow> x * y < x * (y'::ordinal)\"\nby (rule normal.strict_monoD[OF normal_times])\n\nlemma ordinal_le_timesL [simp]: \"0 < x \\<Longrightarrow> y \\<le> x * (y::ordinal)\"\nby (drule ordinal_times_monoL[OF oSuc_leI], simp)\n\nlemma ordinal_le_timesR [simp]: \"0 < y \\<Longrightarrow> x \\<le> x * (y::ordinal)\"\nby (drule ordinal_times_monoR[OF oSuc_leI], simp)\n\nlemma ordinal_less_timesR: \"\\<lbrakk>0 < x; oSuc 0 < y\\<rbrakk> \\<Longrightarrow> x < x * (y::ordinal)\"\nby (drule ordinal_times_strict_monoR, assumption, simp)\n\nlemma ordinal_times_left_cancel [simp]:\n\"0 < w \\<Longrightarrow> (w * x = w * y) = (x = (y::ordinal))\"\nby (rule normal.cancel_eq[OF normal_times])\n\nlemma ordinal_times_left_cancel_le [simp]:\n\"0 < w \\<Longrightarrow> (w * x \\<le> w * y) = (x \\<le> (y::ordinal))\"\nby (rule normal.cancel_le[OF normal_times])\n\nlemma ordinal_times_left_cancel_less [simp]:\n\"0 < w \\<Longrightarrow> (w * x < w * y) = (x < (y::ordinal))\"\nby (rule normal.cancel_less[OF normal_times])\n\nlemma ordinal_times_eq_0:\n\"((x::ordinal) * y = 0) = (x = 0 \\<or> y = 0)\"\n apply (rule iffI)\n  apply (erule contrapos_pp, clarsimp)\n  apply (drule oSuc_leI)\n  apply (erule order_less_le_trans)\n  apply (drule ordinal_times_monoL, simp)\n apply auto\ndone\n\nlemma ordinal_times_not_0 [simp]:\n\"((0::ordinal) < x * y) = (0 < x \\<and> 0 < y)\"\nby (rule not_inject, simp add: ordinal_times_eq_0)\n\n\nsubsection {* Exponentiation *}\n\ndefinition\n  exp_ordinal :: \"[ordinal, ordinal] \\<Rightarrow> ordinal\" (infixr \"**\" 75) where\n  \"op ** = (\\<lambda>x. if 0 < x then ordinal_rec 1 (\\<lambda>p w. w * x)\n                         else (\\<lambda>y. if y = 0 then 1 else 0))\"\n\nlemma continuous_exp: \"0 < x \\<Longrightarrow> continuous (op ** x)\"\nby (simp add: exp_ordinal_def continuous_ordinal_rec)\n\nlemma ordinal_exp_0 [simp]: \"x ** 0 = (1::ordinal)\"\nby (simp add: exp_ordinal_def)\n\nlemma ordinal_exp_oSuc [simp]: \"x ** oSuc y = (x ** y) * x\"\nby (simp add: exp_ordinal_def)\n\nlemma ordinal_exp_oLimit [simp]:\n\"0 < x \\<Longrightarrow> x ** oLimit f = oLimit (\\<lambda>n. x ** f n)\"\nby (rule continuousD[OF continuous_exp])\n\nlemma ordinal_0_exp [simp]: \"0 ** x = (if x = 0 then 1 else 0)\"\nby (simp add: exp_ordinal_def)\n\nlemma ordinal_1_exp [simp]: \"oSuc 0 ** x = oSuc 0\"\nby (rule_tac a=x in oLimit_induct, simp_all)\n\nlemma ordinal_exp_1 [simp]: \"x ** oSuc 0 = x\"\nby simp\n\nlemma ordinal_exp_distrib:\n\"x ** (y + z) = (x ** y) * (x ** (z::ordinal))\"\n apply (case_tac \"x = 0\", simp_all add: ordinal_plus_not_0)\n apply (rule_tac a=z in oLimit_induct, simp_all add: ordinal_times_assoc)\ndone\n\nlemma ordinal_exp_not_0 [simp]: \"(0 < x ** y) = (0 < x \\<or> y = 0)\"\n apply auto\n  apply (erule contrapos_pp, simp)\n apply (rule_tac a=y in oLimit_induct, simp_all)\n apply (rule less_oLimitI, erule spec)\ndone\n\nlemma ordinal_exp_eq_0 [simp]: \"(x ** y = 0) = (x = 0 \\<and> 0 < y)\"\nby (rule not_inject, simp)\n\nlemma ordinal_exp_assoc:\n\"(x ** y) ** z = x ** (y * z)\"\n apply (case_tac \"x = 0\", simp_all)\n apply (rule_tac a=z in oLimit_induct, simp_all add: ordinal_exp_distrib)\ndone\n\nlemma ordinal_exp_monoL [rule_format]:\n\"\\<forall>x x'. x \\<le> x' \\<longrightarrow> x ** y \\<le> x' ** (y::ordinal)\"\n apply (rule_tac a=y in oLimit_induct)\n   apply simp\n  apply (simp add: ordinal_times_mono)\n apply clarsimp\n apply (case_tac \"x = 0\", simp)\n apply (case_tac \"x' = 0\", simp_all)\n apply (rule oLimit_leI, clarify)\n apply (rule_tac n=n in le_oLimitI)\n apply simp\ndone\n\nlemma normal_exp: \"oSuc 0 < x \\<Longrightarrow> normal (op ** x)\"\n apply (frule_tac order_less_trans[OF less_oSuc])\n apply (rule normalI, simp, rename_tac y)\n apply (subgoal_tac \"x ** y * 1 < x ** y * x\", simp)\n apply (subst ordinal_times_left_cancel_less)\n  apply simp\n apply simp\ndone\n\nlemma ordinal_exp_monoR:\n\"\\<lbrakk>0 < x; y \\<le> y'\\<rbrakk> \\<Longrightarrow> x ** y \\<le> x ** (y'::ordinal)\"\nby (rule continuous.monoD[OF continuous_exp])\n\nlemma ordinal_exp_mono:\n\"\\<lbrakk>0 < x'; x \\<le> x'; y \\<le> y'\\<rbrakk> \\<Longrightarrow> x ** y \\<le> x' ** (y'::ordinal)\"\nby (rule order_trans[OF ordinal_exp_monoL ordinal_exp_monoR])\n\nlemma ordinal_exp_strict_monoR:\n\"\\<lbrakk>oSuc 0 < x; y < y'\\<rbrakk> \\<Longrightarrow> x ** y < x ** (y'::ordinal)\"\nby (rule normal.strict_monoD[OF normal_exp])\n\nlemma ordinal_le_expR [simp]: \"0 < y \\<Longrightarrow> x \\<le> x ** (y::ordinal)\"\n apply (subgoal_tac \"x ** oSuc 0 \\<le> x ** y\")\n  apply (simp del: ordinal_exp_oSuc)\n apply (case_tac \"x = 0\", simp)\n apply (rule ordinal_exp_monoR, simp_all add: oSuc_leI)\ndone\n\nlemma ordinal_exp_left_cancel [simp]:\n\"oSuc 0 < w \\<Longrightarrow> (w ** x = w ** y) = (x = y)\"\nby (rule normal.cancel_eq[OF normal_exp])\n\nlemma ordinal_exp_left_cancel_le [simp]:\n\"oSuc 0 < w \\<Longrightarrow> (w ** x \\<le> w ** y) = (x \\<le> y)\"\nby (rule normal.cancel_le[OF normal_exp])\n\nlemma ordinal_exp_left_cancel_less [simp]:\n\"oSuc 0 < w \\<Longrightarrow> (w ** x < w ** y) = (x < y)\"\nby (rule normal.cancel_less[OF normal_exp])\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Ordinal/OrdinalArith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.863391624034103, "lm_q1q2_score": 0.7787107485541159}}
{"text": "(*\n  File:     Power_By_Squaring.thy\n  Author:   Manuel Eberl, TU München\n  \n  Fast computing of funpow (applying some functon n times) for weakly associative binary\n  functions using exponentiation by squaring. Yields efficient exponentiation algorithms on\n  monoid_mult and for modular exponentiation \"b ^ e mod m\" (and thus also for \"cong\")\n*)\nsection \\<open>Exponentiation by Squaring\\<close>\ntheory Power_By_Squaring\n  imports Main\nbegin\n\ncontext\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nbegin\n\nfunction efficient_funpow :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n  \"efficient_funpow y x 0 = y\"\n| \"efficient_funpow y x (Suc 0) = f x y\"\n| \"n \\<noteq> 0 \\<Longrightarrow> even n \\<Longrightarrow> efficient_funpow y x n = efficient_funpow y (f x x) (n div 2)\"\n| \"n \\<noteq> 1 \\<Longrightarrow> odd n \\<Longrightarrow> efficient_funpow y x n = efficient_funpow (f x y) (f x x) (n div 2)\"\n  by force+\ntermination by (relation \"measure (snd \\<circ> snd)\") (auto elim: oddE)\n\nlemma efficient_funpow_code [code]:\n  \"efficient_funpow y x n =\n     (if n = 0 then y\n      else if n = 1 then f x y\n      else if even n then efficient_funpow y (f x x) (n div 2)\n      else efficient_funpow (f x y) (f x x) (n div 2))\"\n  by (induction y x n rule: efficient_funpow.induct) auto\n\nend\n\nlemma efficient_funpow_correct:\n  assumes f_assoc: \"\\<And>x z. f x (f x z) = f (f x x) z\"\n  shows \"efficient_funpow f y x n = (f x ^^ n) y\"\nproof -\n  have [simp]: \"f ^^ 2 = (\\<lambda>x. f (f x))\" for f :: \"'a \\<Rightarrow> 'a\"\n    by (simp add: eval_nat_numeral o_def)\n  show ?thesis\n    by (induction y x n rule: efficient_funpow.induct[of _ f])\n       (auto elim!: evenE oddE simp: funpow_mult [symmetric] funpow_Suc_right f_assoc\n             simp del: funpow.simps(2))\nqed\n\n(*\n  TODO: This could be used as a code_unfold rule or something like that but the\n  implications are not quite clear. Would this be a good default implementation\n  for powers?\n*)\ncontext monoid_mult\nbegin\n\nlemma power_by_squaring: \"efficient_funpow (*) (1 :: 'a) = (^)\"\nproof (intro ext)\n  fix x :: 'a and n\n  have \"efficient_funpow (*) 1 x n = ((*) x ^^ n) 1\"\n    by (subst efficient_funpow_correct) (simp_all add: mult.assoc)\n  also have \"\\<dots> = x ^ n\"\n    by (induction n) simp_all\n  finally show \"efficient_funpow (*) 1 x n = x ^ n\" .\nqed\n\nend\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Power_By_Squaring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7786871970577407}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\ntheory AExp imports Main begin\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext {* The same state more concisely: *}\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext {* A little syntax magic to write larger states compactly: *}\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\n*}\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\nvalue \"<>\"  \n\n\ntext {* In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n*}\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext{* Note that this @{text\"<\\<dots>>\"} syntax works for any function space\n@{text\"\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\"} where @{text \"\\<tau>\\<^sub>2\"} has a @{text 0}. *}\n\n\nlemma null_state_app[simp]: \"<> x = 0\" by (auto simp: null_state_def)\n\nsubsection \"Constant Folding\"\n\ntext{* Evaluate constant subsexpressions: *}\n\ntext_raw{*\\snip{AExpasimpconstdef}{0}{2}{% *}\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\n  apply(induction a)\n  apply (auto split: aexp.split)\n  done\n  \ntext{* Now we also eliminate all occurrences of 0 in additions. The standard\nmethod: optimized versions of the constructors: *}\n\ntext_raw{*\\snip{AExpplusdef}{0}{2}{% *}\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw{*\\snip{AExpasimpdef}{2}{0}{% *}\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntext{* Note that in @{const asimp_const} the optimized constructor was\ninlined. Making it a separate function @{const plus} improves modularity of\nthe code and the proofs. *}\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/IMP/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7786871836084894}}
{"text": "theory Graph\n  imports Main\nbegin\n\nsection \\<open>Graphs\\<close>\n\nrecord 'a graph =\n  vertices :: \"'a set\"\n  edges :: \"'a set set\"\n\nlocale graph =\n  fixes G :: \"'a graph\"\n  assumes graph: \"\\<forall>e\\<in>edges G. \\<exists>u v. u \\<in> vertices G \\<and> v \\<in> vertices G \\<and> u \\<noteq> v \\<and> e = {u, v}\"\n\nlemma (in graph) Union_edges_subset_vertices:\n  shows \"\\<Union> (edges G) \\<subseteq> vertices G\"\n  using graph\n  by fastforce\n\nlemma (in graph) edge_subset_vertices:\n  assumes \"e \\<in> edges G\"\n  shows \"e \\<subseteq> vertices G\"\n  using assms Union_edges_subset_vertices\n  by blast\n  \nlocale finite_graph = graph G for G +\n  assumes vertices_finite: \"finite (vertices G)\"\n\nlemma (in finite_graph) edges_finite:\n  shows \"finite (edges G)\"\nproof -\n  have \"\\<Union> (edges G) \\<subseteq> vertices G\"\n    using Union_edges_subset_vertices\n    by simp\n  moreover have \"finite ...\"\n    using vertices_finite\n    by simp\n  ultimately have \"finite (\\<Union> (edges G))\"\n    by (rule finite_subset)\n  thus ?thesis\n    by (rule finite_UnionD)\nqed\n\nsection \\<open>Subgraphs\\<close>\n\nlocale subgraph = supergraph: graph G + subgraph: graph H for G H +\n  assumes vertices_subset: \"vertices H \\<subseteq> vertices G\"\n  assumes edges_subset: \"edges H \\<subseteq> edges G\"\n\nlocale induced_subgraph = graph G for G +\n  fixes H :: \"'a graph\"\n  fixes V :: \"'a set\"\n  assumes induced: \"H = \\<lparr>vertices = vertices G \\<inter> V, edges = {e \\<in> edges G. e \\<subseteq> V}\\<rparr>\"\n\nsublocale induced_subgraph \\<subseteq> subgraph\nproof (rule subgraph.intro)\n  show \"graph G\"\n    using graph_axioms\n    .\nnext\n  { fix e\n    assume \"e \\<in> edges H\"\n    hence\n      \"e \\<in> edges G\"\n      \"e \\<subseteq> V\"\n      by (simp add: induced)+\n    then obtain u v where\n      \"u \\<noteq> v\" and\n      \"e = {u, v}\" and\n      \"u \\<in> vertices H\"\n      \"v \\<in> vertices H\"\n      using graph\n      by (auto simp add: induced)\n    hence \"\\<exists>u v. u \\<in> vertices H \\<and> v \\<in> vertices H \\<and> u \\<noteq> v \\<and> e = {u, v}\"\n      by blast }\n  thus \"graph H\"\n    by (simp add: graph_def)\nnext\n  have \"vertices H \\<subseteq> vertices G\"\n    by (simp add: induced)\n  moreover have \"edges H \\<subseteq> edges G\"\n    by (simp add: induced)\n  ultimately show \"subgraph_axioms G H\"\n    by (rule subgraph_axioms.intro)\nqed\n\nlemmas (in induced_subgraph) vertices_subset = vertices_subset\nlemmas (in induced_subgraph) edges_subset = edges_subset\nlemmas (in induced_subgraph) subgraph_graph_axioms = subgraph.graph_axioms\n\nlemma (in induced_subgraph) vertices_subgraph_subset:\n  shows \"vertices H \\<subseteq> V\"\n  by (simp add: induced)\n\nlemma (in induced_subgraph) vertices_subgraph_eq:\n  assumes \"V \\<subseteq> vertices G\"\n  shows \"vertices H = V\"\n  using assms\n  by (auto simp add: induced)\n\nlemma induced_subgraph_trans:\n  assumes G_induced_subgraph: \"induced_subgraph F G V\"\n  assumes H_induced_subgraph: \"induced_subgraph G H W\"\n  shows \"induced_subgraph F H (V \\<inter> W)\"\nproof (rule induced_subgraph.intro)\n  show \"graph F\"\n    using G_induced_subgraph\n    by (rule induced_subgraph.axioms(1))\nnext\n  have\n    \"vertices H = vertices G \\<inter> W\"\n    \"edges H = {e \\<in> edges G. e \\<subseteq> W}\"\n    by (simp add: induced_subgraph.induced[OF H_induced_subgraph])+\n  hence\n    \"vertices H = vertices F \\<inter> V \\<inter> W\"\n    \"edges H = {e \\<in> {e \\<in> edges F. e \\<subseteq> V}. e \\<subseteq> W}\"\n    by (simp add: induced_subgraph.induced[OF G_induced_subgraph])+\n  hence\n    \"vertices H = vertices F \\<inter> (V \\<inter> W)\"\n    \"edges H = {e \\<in> edges F. e \\<subseteq> (V \\<inter> W)}\"\n    by blast+\n  thus \"induced_subgraph_axioms F H (V \\<inter> W)\"\n    by (intro induced_subgraph_axioms.intro) simp\nqed\n\nsection \\<open>Neighborhood\\<close>\n\ndefinition neighborhood :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a set\" where\n  \"neighborhood G v \\<equiv> {u \\<in> vertices G. {v, u} \\<in> edges G}\"\n\nlemma (in graph) in_neighborhood_iff:\n  shows \"u \\<in> neighborhood G v \\<longleftrightarrow> {v, u} \\<in> edges G\"\n  using edge_subset_vertices\n  by (auto simp add: neighborhood_def)\n\nlemma (in graph) neighborhood_symmetric:\n  shows \"u \\<in> neighborhood G v \\<longleftrightarrow> v \\<in> neighborhood G u\"\n  by (simp add: in_neighborhood_iff insert_commute)\n\nlemma neighborhood_subset_vertices:\n  shows \"neighborhood G v \\<subseteq> vertices G\"\n  by (simp add: neighborhood_def)\n\nlemma in_neighborhood_implies_in_vertices:\n  assumes \"u \\<in> neighborhood G v\"\n  shows \"u \\<in> vertices G\"\n  using assms neighborhood_subset_vertices\n  by fastforce\n\nlemma (in finite_graph) neighborhood_finite:\n  shows \"finite (neighborhood G v)\"\n  using neighborhood_subset_vertices vertices_finite\n  by (rule finite_subset)\n\nsection \\<open>Degree\\<close>\n\nabbreviation degree :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"degree G v \\<equiv> card (neighborhood G v)\"\n\nlemma (in finite_graph) degree_0_conv:\n  shows \"degree G v = 0 \\<longleftrightarrow> (\\<nexists>e. e \\<in> edges G \\<and> v \\<in> e)\"\nproof -\n  have \"finite (neighborhood G v)\"\n    using neighborhood_finite\n    .\n  hence \"card (neighborhood G v) = 0 \\<longleftrightarrow> neighborhood G v = {}\"\n    by (rule card_0_eq)\n  also have \"... \\<longleftrightarrow> (\\<nexists>u. {v, u} \\<in> edges G)\"\n    by (auto simp add: in_neighborhood_iff)\n  finally show ?thesis\n    using graph\n    by (auto simp add: insert_commute)\nqed\n\nend", "meta": {"author": "wimmers", "repo": "archive-of-graph-formalizations", "sha": "cf49dd3379174cca7f3f1de16214e1c66238841e", "save_path": "github-repos/isabelle/wimmers-archive-of-graph-formalizations", "path": "github-repos/isabelle/wimmers-archive-of-graph-formalizations/archive-of-graph-formalizations-cf49dd3379174cca7f3f1de16214e1c66238841e/Undirected_Graphs/Mitja/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7786667648818528}}
{"text": "theory YT_tut_2 imports Main begin\n\nthm fold.simps\n\nfun list_sum :: \"nat list \\<Rightarrow> nat\" where\n  \"list_sum [] = 0\"\n| \"list_sum (x#xs) = x + list_sum xs\"\n\nvalue \"list_sum [1,2,3]\"\n\ndefinition list_sum' :: \"nat list \\<Rightarrow> nat\" where\n  \"list_sum' xs = fold (+) xs 0\"\n\nvalue \"list_sum' [1,2,3]\"\n\nthm list_sum'_def\n\nlemma lemma_aux:  \"\\<forall>a. fold (+) xs a = list_sum xs + a\" apply (induction xs) by auto\nlemma \"list_sum xs = list_sum' xs\" apply (induction xs) by (auto simp: list_sum'_def lemma_aux)\n\ndatatype 'a ltree = Leaf 'a | Node \"'a ltree\" \"'a ltree\"\n\nfun inorder :: \"'a ltree \\<Rightarrow> 'a list\" where\n  \"inorder (Leaf x) = [x]\"\n| \"inorder (Node l r) = inorder l @ inorder r\"\n\nvalue \"inorder (Node (Node (Leaf (1::nat)) (Leaf 2)) (Leaf 3))\"\n\nfun fold_ltree :: \"('a \\<Rightarrow> 's \\<Rightarrow> 's) \\<Rightarrow> 'a ltree \\<Rightarrow> 's \\<Rightarrow> 's\" where\n  \"fold_ltree f (Leaf x) a = f x a\"\n| \"fold_ltree f (Node l r) a = fold_ltree f r (fold_ltree f l a)\"\n\nvalue \"fold_ltree (+) (Node (Node (Leaf (1::nat)) (Leaf 2)) (Leaf 3)) 0\"\n\nlemma \"\\<forall> a. fold f (inorder t) a = fold_ltree f t a\" apply (induction t) by auto\n\nfun mirror :: \"'a ltree \\<Rightarrow> 'a ltree\" where\n  \"mirror (Leaf x) = Leaf x\"\n| \"mirror (Node l r) = (Node (mirror r) (mirror l))\"\n\n\nlemma \"inorder (mirror t) = rev (inorder t)\" apply (induction t) by auto\n\nfun shuffles :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" where\n  \"shuffles xs [] = [xs]\"\n| \"shuffles [] ys = [ys]\"\n| \"shuffles (x#xs) (y#ys) = map (\\<lambda>xs. x#xs) (shuffles xs (y#ys)) @\n                            map (\\<lambda>ys. y#ys) (shuffles (x#xs) ys)\"\n\nthm shuffles.induct\n\nlemma \"zs \\<in> set (shuffles xs ys) \\<Longrightarrow> length zs = length xs + length ys\"\n  apply (induction xs ys arbitrary: zs rule: shuffles.induct) by auto\n\nend\n", "meta": {"author": "brunoflores", "repo": "concrete-semantics-book", "sha": "bb45ae1ded27aa1ca2fb25e49013815293c51f80", "save_path": "github-repos/isabelle/brunoflores-concrete-semantics-book", "path": "github-repos/isabelle/brunoflores-concrete-semantics-book/concrete-semantics-book-bb45ae1ded27aa1ca2fb25e49013815293c51f80/YT_tut_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8840392817460333, "lm_q1q2_score": 0.7786592272443935}}
{"text": "(*  \n    Author:      René Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Rational Factorization\\<close>\n\ntext \\<open>We combine the rational root test, the\n  formulas for explicit roots, and the Kronecker's factorization algorithm to provide a\n  basic factorization algorithm for polynomial over rational numbers. Moreover, also the roots\n  of a rational polynomial can be determined.\\<close>\n  \ntheory Rational_Factorization\nimports\n  Explicit_Roots\n  Kronecker_Factorization\n  Square_Free_Factorization\n  Rational_Root_Test\n  Gcd_Rat_Poly\n  Show.Show_Poly\nbegin\n\nfunction roots_of_rat_poly_main :: \"rat poly \\<Rightarrow> rat list\" where \n  \"roots_of_rat_poly_main p = (let n = degree p in if n = 0 then [] else if n = 1 then [roots1 p]\n  else if n = 2 then rat_roots2 p else \n  case rational_root_test p of None \\<Rightarrow> [] | Some x \\<Rightarrow> x # roots_of_rat_poly_main (p div [:-x,1:]))\"\n  by pat_completeness auto\n\ntermination by (relation \"measure degree\", \n  auto dest: rational_root_test(1) intro!: degree_div_less simp: poly_eq_0_iff_dvd)\n\nlemma roots_of_rat_poly_main_code[code]: \"roots_of_rat_poly_main p = (let n = degree p in if n = 0 then [] else if n = 1 then [roots1 p]\n  else if n = 2 then rat_roots2 p else \n  case rational_root_test p of None \\<Rightarrow> [] | Some x \\<Rightarrow> x # roots_of_rat_poly_main (p div [:-x,1:]))\"\nproof -\n  note d = roots_of_rat_poly_main.simps[of p] Let_def\n  show ?thesis\n  proof (cases \"rational_root_test p\")\n    case (Some x)\n    let ?x = \"[:-x,1:]\"\n    from rational_root_test(1)[OF Some] have  \"?x dvd p\" \n      by (simp add: poly_eq_0_iff_dvd)\n    from dvd_mult_div_cancel[OF this]\n    have pp: \"p div ?x = ?x * (p div ?x) div ?x\" by simp\n    then show ?thesis unfolding d Some by auto\n  qed (simp add: d)\nqed\n\nlemma roots_of_rat_poly_main: \"p \\<noteq> 0 \\<Longrightarrow> set (roots_of_rat_poly_main p) = {x. poly p x = 0}\"\nproof (induct p rule: roots_of_rat_poly_main.induct)\n  case (1 p)\n  note IH = 1(1)\n  note p = 1(2)\n  let ?n = \"degree p\"\n  let ?rr = \"roots_of_rat_poly_main\"\n  show ?case\n  proof (cases \"?n = 0\")\n    case True\n    from roots0[OF p True] True show ?thesis by simp\n  next\n    case False note 0 = this\n    show ?thesis\n    proof (cases \"?n = 1\")\n      case True\n      from roots1[OF True] True show ?thesis by simp\n    next\n      case False note 1 = this\n      show ?thesis\n      proof (cases \"?n = 2\")\n        case True\n        from rat_roots2[OF True] True show ?thesis by simp\n      next\n        case False note 2 = this\n        from 0 1 2 have id: \"?rr p = (case rational_root_test p of None \\<Rightarrow> [] | Some x \\<Rightarrow> \n          x # ?rr (p div [: -x, 1 :]))\" by simp\n        show ?thesis\n        proof (cases \"rational_root_test p\")\n          case None\n          from rational_root_test(2)[OF None] None id show ?thesis by simp\n        next\n          case (Some x)\n          from rational_root_test(1)[OF Some] have \"[: -x, 1:] dvd p\"         \n            by (simp add: poly_eq_0_iff_dvd)\n          from dvd_mult_div_cancel[OF this]\n          have pp: \"p = [: -x, 1:] * (p div [: -x, 1:])\" by simp\n          with p have p: \"p div [:- x, 1:] \\<noteq> 0\" by auto\n          from arg_cong[OF pp, of \"\\<lambda> p. {x. poly p x = 0}\"]\n             rational_root_test(1)[OF Some] IH[OF refl 0 1 2 Some p]  show ?thesis\n            unfolding id Some by auto\n        qed\n      qed\n    qed\n  qed\nqed\n\ndeclare roots_of_rat_poly_main.simps[simp del]\n\ndefinition roots_of_rat_poly :: \"rat poly \\<Rightarrow> rat list\" where\n  \"roots_of_rat_poly p \\<equiv> let (c,pis) = yun_factorization gcd_rat_poly p in\n    concat (map (roots_of_rat_poly_main o fst) pis)\"\n\nlemma roots_of_rat_poly: assumes p: \"p \\<noteq> 0\"\n  shows \"set (roots_of_rat_poly p) = {x. poly p x = 0}\"\nproof -\n  obtain c pis where yun: \"yun_factorization gcd p = (c,pis)\" by force\n  from yun\n  have res: \"roots_of_rat_poly p = concat (map (roots_of_rat_poly_main \\<circ> fst) pis)\"\n    by (auto simp: roots_of_rat_poly_def split: if_splits)\n  note yun = square_free_factorizationD(1,2,4)[OF yun_factorization(1)[OF yun]]\n  from yun(1) p have c: \"c \\<noteq> 0\" by auto\n  from yun(1) have p: \"p = smult c (\\<Prod>(a, i)\\<in>set pis. a ^ Suc i)\" .\n  have \"{x. poly p x = 0} = {x. poly (\\<Prod>(a, i)\\<in>set pis. a ^ Suc i) x = 0}\"\n    unfolding p using c by auto\n  also have \"\\<dots> = \\<Union> ((\\<lambda> p. {x. poly p x = 0}) ` fst ` set pis)\" (is \"_ = ?r\")\n    by (subst poly_prod_0, force+)\n  finally have r: \"{x. poly p x = 0} = ?r\" .\n  {\n    fix p i\n    assume p: \"(p,i) \\<in> set pis\"\n    have \"set (roots_of_rat_poly_main p) = {x. poly p x = 0}\"\n      by (rule roots_of_rat_poly_main, insert yun(2) p, force)\n  } note main = this\n  have \"set (roots_of_rat_poly p) = \\<Union> ((\\<lambda> (p, i). set (roots_of_rat_poly_main p)) ` set pis)\" \n    unfolding res o_def by auto\n  also have \"\\<dots> = ?r\" using main by auto\n  finally show ?thesis unfolding r by simp\nqed\n\ndefinition root_free :: \"'a :: comm_semiring_0 poly \\<Rightarrow> bool\" where\n  \"root_free p = (degree p = 1 \\<or> (\\<forall> x. poly p x \\<noteq> 0))\"\n\nlemma irreducible_root_free:\n  fixes p :: \"'a :: idom poly\"\n  assumes \"irreducible p\" shows \"root_free p\"\nproof-\n  from assms have p0: \"p \\<noteq> 0\" by auto\n  {\n    fix x\n    assume \"poly p x = 0\" and degp: \"degree p \\<noteq> 1\"\n    hence \"[:-x,1:] dvd p\" using poly_eq_0_iff_dvd by blast\n    then obtain q where p: \"p = [:-x,1:] * q\" by (elim dvdE)\n    with p0 have q0: \"q \\<noteq> 0\" by auto\n    from irreducibleD[OF assms p]\n    have \"q dvd 1\" by (metis one_neq_zero poly_1 poly_eq_0_iff_dvd)\n    then have \"degree q = 0\" by (simp add: poly_dvd_1)\n    with degree_mult_eq[of \"[:-x,1:]\" q, folded p] q0 degp\n    have False by auto\n  }\n  thus ?thesis unfolding root_free_def by auto\nqed\n\npartial_function (tailrec) factorize_root_free_main :: \"rat poly \\<Rightarrow> rat list \\<Rightarrow> rat poly list \\<Rightarrow> rat \\<times> rat poly list\" where\n  [code]: \"factorize_root_free_main p xs fs = (case xs of Nil \\<Rightarrow> \n     let l = coeff p (degree p); q = smult (inverse l) p in (l, (if q = 1 then fs else q # fs) )\n  | x # xs \\<Rightarrow> \n    if poly p x = 0 then factorize_root_free_main (p div [:-x,1:]) (x # xs) ([:-x,1:] # fs)\n    else factorize_root_free_main p xs fs)\"\n\ndefinition factorize_root_free :: \"rat poly \\<Rightarrow> rat \\<times> rat poly list\" where\n  \"factorize_root_free p = (if degree p = 0 then (coeff p 0,[]) else\n     factorize_root_free_main p (roots_of_rat_poly p) [])\"\n\nlemma factorize_root_free_0[simp]: \"factorize_root_free 0 = (0,[])\" \n  unfolding factorize_root_free_def by simp\n\nlemma factorize_root_free: assumes res: \"factorize_root_free p = (c,qs)\" \n  shows \"p = smult c (prod_list qs)\" \n  \"\\<And> q. q \\<in> set qs \\<Longrightarrow> root_free q \\<and> monic q \\<and> degree q \\<noteq> 0\"\nproof -\n  have \"p = smult c (prod_list qs) \\<and> (\\<forall> q \\<in> set qs. root_free q \\<and> monic q \\<and> degree q \\<noteq> 0)\"\n  proof (cases \"degree p = 0\")\n    case True\n    thus ?thesis using res unfolding factorize_root_free_def by (auto dest: degree0_coeffs) \n  next\n    case False\n    hence p0: \"p \\<noteq> 0\" by auto\n    define fs where \"fs = ([] :: rat poly list)\" \n    define xs where \"xs = roots_of_rat_poly p\"\n    define q where \"q = p\"\n    obtain n  where n: \"n = degree q + length xs\" by auto \n    have prod: \"p = q * prod_list fs\" unfolding q_def fs_def by auto\n    have sub: \"{x. poly q x = 0} \\<subseteq> set xs\" using roots_of_rat_poly[OF p0] unfolding q_def xs_def by auto\n    have fs: \"\\<And> q. q \\<in> set fs \\<Longrightarrow> root_free q \\<and> monic q \\<and> degree q \\<noteq> 0\" unfolding fs_def by auto\n    have res: \"factorize_root_free_main q xs fs = (c,qs)\" using res False \n      unfolding xs_def fs_def q_def factorize_root_free_def by auto\n    from False have \"q \\<noteq> 0\" unfolding q_def by auto\n    from prod sub fs res n this show ?thesis\n    proof (induct n arbitrary: q fs xs rule: wf_induct[OF wf_less])\n      case (1 n q fs xs)\n      note simp = factorize_root_free_main.simps[of q xs fs]\n      note IH = 1(1)[rule_format]\n      note 0 = 1(2-)[unfolded simp]\n      show ?case\n      proof (cases xs)\n        case Nil\n        note 0 = 0[unfolded Nil Let_def]\n        hence no_rt: \"\\<And> x. poly q x \\<noteq> 0\" by auto\n        hence q: \"q \\<noteq> 0\" by auto\n        let ?r = \"smult (inverse c) q\"\n        define r where \"r = ?r\"\n        from 0(4-5) have c: \"c = coeff q (degree q)\" and qs: \"qs = (if r = 1 then fs else r # fs)\" by (auto simp: r_def)\n        from q c qs 0(1) have c0: \"c \\<noteq> 0\" and p: \"p = smult c (prod_list (r # fs))\" by (auto simp: r_def)\n        from p have p: \"p = smult c (prod_list qs)\" unfolding qs by auto \n        from 0(2,5) c0 c have \"root_free ?r\" \"monic ?r\" \n          unfolding root_free_def by auto\n        with 0(3) have \"\\<And> q. q \\<in> set qs \\<Longrightarrow> root_free q \\<and> monic q \\<and> degree q \\<noteq> 0\" unfolding qs \n          by (cases \"degree q = 0\", insert degree0_coeffs[of q], auto split: if_splits simp: r_def)\n        with p show ?thesis by auto\n      next\n        case (Cons x xs)\n        note 0 = 0[unfolded Cons]\n        show ?thesis\n        proof (cases \"poly q x = 0\")\n          case True\n          let ?q = \"q div [:-x,1:]\"\n          let ?x = \"[:-x,1:]\" \n          let ?fs = \"?x # fs\"\n          let ?xs = \"x # xs\"\n          from True have q: \"q = ?q * ?x\"\n            by (metis dvd_mult_div_cancel mult.commute poly_eq_0_iff_dvd)\n          with 0(6) have q': \"?q \\<noteq> 0\" by auto\n          have deg: \"degree q = Suc (degree ?q)\" unfolding arg_cong[OF q, of degree] \n            by (subst degree_mult_eq[OF q'], auto)\n          hence n: \"degree ?q + length ?xs < n\" unfolding 0(5) by auto\n          from arg_cong[OF q, of poly] 0(2) have rt: \"{x. poly ?q x = 0} \\<subseteq> set ?xs\" by auto\n          have p: \"p = ?q * prod_list ?fs\" unfolding prod_list.Cons 0(1) mult.assoc[symmetric] q[symmetric] ..\n          have \"root_free ?x\" unfolding root_free_def by auto\n          with 0(3) have rf: \"\\<And> f. f \\<in> set ?fs \\<Longrightarrow> root_free f \\<and> monic f \\<and> degree f \\<noteq> 0\" by auto\n          from True 0(4) have res: \"factorize_root_free_main ?q ?xs ?fs = (c,qs)\" by simp\n          show ?thesis\n            by (rule IH[OF _ p rt rf res refl q'], insert n, auto)\n        next\n          case False\n          with 0(4) have res: \"factorize_root_free_main q xs fs = (c,qs)\" by simp\n          from 0(5) obtain m where m: \"m = degree q + length xs\" and n: \"n = Suc m\" by auto\n          from False 0(2) have rt: \"{x. poly q x = 0} \\<subseteq> set xs\" by auto\n          show ?thesis by (rule IH[OF _ 0(1) rt 0(3) res m 0(6)], unfold n, auto)\n        qed\n      qed\n    qed\n  qed\n  thus \"p = smult c (prod_list qs)\" \n    \"\\<And> q. q \\<in> set qs \\<Longrightarrow> root_free q \\<and> monic q \\<and> degree q \\<noteq> 0\" by auto\nqed\n\n\ndefinition rational_proper_factor :: \"rat poly \\<Rightarrow> rat poly option\" where\n  \"rational_proper_factor p = (if degree p \\<le> 1 then None\n    else if degree p = 2 then (case rat_roots2 p of Nil \\<Rightarrow> None | Cons x xs \\<Rightarrow> Some [:-x,1 :])\n    else if degree p = 3 then (case rational_root_test p of None \\<Rightarrow> None | Some x \\<Rightarrow> Some [:-x,1:])\n    else kronecker_factorization_rat p)\"\n\nlemma degree_1_dvd_root: assumes q: \"degree (q :: 'a :: field poly) = 1\"\n  and rt: \"\\<And> x. poly p x \\<noteq> 0\"\n  shows \"\\<not> q dvd p\"\nproof -\n  from degree1_coeffs[OF q] obtain a b where q: \"q = [: b, a :]\" and a: \"a \\<noteq> 0\" by auto\n  have q: \"q = smult a [: - (- b / a), 1 :]\" unfolding q \n    by (rule poly_eqI, unfold coeff_smult, insert a, auto simp: field_simps coeff_pCons\n      split: nat.splits)\n  show ?thesis unfolding q smult_dvd_iff poly_eq_0_iff_dvd[symmetric, of _ p] using a rt by auto\nqed\n\n\n\n\nlemma rational_proper_factor: \n  \"degree p > 0 \\<Longrightarrow> rational_proper_factor p = None \\<Longrightarrow> irreducible\\<^sub>d p\" \n  \"rational_proper_factor p = Some q \\<Longrightarrow> q dvd p \\<and> degree q \\<ge> 1 \\<and> degree q < degree p\"\nproof -\n  let ?rp = \"rational_proper_factor p\"\n  let ?rr = \"rational_root_test\"\n  note d = rational_proper_factor_def[of p]\n  have \"(degree p > 0 \\<longrightarrow> ?rp = None \\<longrightarrow> irreducible\\<^sub>d p) \\<and> \n        (?rp = Some q \\<longrightarrow> q dvd p \\<and> degree q \\<ge> 1 \\<and> degree q < degree p)\"\n  proof (cases \"degree p = 0\")\n    case True\n    thus ?thesis unfolding d by auto\n  next\n    case False note 0 = this\n    show ?thesis\n    proof (cases \"degree p = 1\")\n      case True\n      hence \"?rp = None\" unfolding d by auto\n      with linear_irreducible\\<^sub>d[OF True] show ?thesis by auto\n    next\n      case False note 1 = this\n      show ?thesis\n      proof (cases \"degree p = 2\")\n        case True\n        hence rp: \"?rp = (case rat_roots2 p of Nil \\<Rightarrow> None | Cons x xs \\<Rightarrow> Some [:-x,1 :])\" unfolding d by auto\n        show ?thesis\n        proof (cases \"rat_roots2 p\")\n          case Nil\n          with rp have rp: \"?rp = None\" by auto\n          from Nil rat_roots2[OF True] have nex: \"\\<not> (\\<exists> x. poly p x = 0)\" by auto\n          have \"irreducible\\<^sub>d p\"\n          proof (rule irreducible\\<^sub>dI)\n            fix q r :: \"rat poly\"\n            assume \"degree q > 0\" \"degree q < degree p\" and p: \"p = q * r\"\n            with True have dq: \"degree q = 1\" by auto\n            have \"\\<not> q dvd p\" by (rule degree_1_dvd_root[OF dq], insert nex, auto)\n            with p show False by auto\n          qed (insert True, auto)\n          with rp show ?thesis by auto\n        next\n          case (Cons x xs)\n          from Cons rat_roots2[OF True] have \"poly p x = 0\" by auto\n          from this[unfolded poly_eq_0_iff_dvd] have x: \"[: -x , 1 :] dvd p\" by auto\n          from Cons rp have rp: \"?rp = Some ([: - x, 1 :])\" by auto\n          show ?thesis using True x unfolding rp by auto\n        qed\n      next\n        case False note 2 = this\n        show ?thesis\n        proof (cases \"degree p = 3\")\n          case True\n          hence rp: \"?rp = (case ?rr p of None \\<Rightarrow> None | Some x \\<Rightarrow> Some [:- x, 1:])\" unfolding d by auto\n          show ?thesis\n          proof (cases \"?rr p\")\n            case None\n            from rational_root_test(2)[OF None] have nex: \"\\<not> (\\<exists> x. poly p x = 0)\" by auto\n            from rp[unfolded None] have rp: \"?rp = None\" by auto\n            have \"irreducible\\<^sub>d p\"\n            proof (rule irreducible\\<^sub>dI2)\n              fix q :: \"rat poly\"\n              assume \"degree q > 0\" \"degree q \\<le> degree p div 2\"\n              with True have dq: \"degree q = 1\" by auto\n              show \"\\<not> q dvd p\" \n                by (rule degree_1_dvd_root[OF dq], insert nex, auto)\n            qed (insert True, auto)\n            with rp show ?thesis by auto\n          next\n            case (Some x)\n            from rational_root_test(1)[OF Some] have \"poly p x = 0\" .\n            from this[unfolded poly_eq_0_iff_dvd] have x: \"[: -x , 1 :] dvd p\" by auto\n            from Some rp have rp: \"?rp = Some ([: - x, 1 :])\" by auto\n            show ?thesis using True x unfolding rp by auto\n          qed\n        next\n          case False note 3 = this\n          let ?kp = \"kronecker_factorization_rat p\"\n          from 0 1 2 3 have d4: \"degree p \\<ge> 4\" and d1: \"degree p \\<ge> 1\" by auto\n          hence rp: \"?rp = ?kp\" using d4 d by auto\n          show ?thesis\n          proof (cases ?kp)\n            case None\n            with rp kronecker_factorization_rat(2)[OF None d1] show ?thesis by auto\n          next\n            case (Some q)\n            with rp kronecker_factorization_rat(1)[OF Some] show ?thesis by auto\n          qed\n        qed\n      qed\n    qed\n  qed\n  thus \"degree p > 0 \\<Longrightarrow> rational_proper_factor p = None \\<Longrightarrow> irreducible\\<^sub>d p\" \n    \"rational_proper_factor p = Some q \\<Longrightarrow> q dvd p \\<and> degree q \\<ge> 1 \\<and> degree q < degree p\" by auto\nqed\n\nfunction factorize_rat_poly_main :: \"rat \\<Rightarrow> rat poly list \\<Rightarrow> rat poly list \\<Rightarrow> rat \\<times> rat poly list\" where\n  \"factorize_rat_poly_main c irr [] = (c,irr)\"\n| \"factorize_rat_poly_main c irr (p # ps) = (if degree p = 0 \n    then factorize_rat_poly_main (c * coeff p 0) irr ps \n    else (case rational_proper_factor p of \n      None \\<Rightarrow> factorize_rat_poly_main c (p # irr) ps\n    | Some q \\<Rightarrow> factorize_rat_poly_main c irr (q # p div q # ps)))\"\n  by pat_completeness auto\n\ndefinition \"factorize_rat_poly_main_wf_rel = inv_image (mult1 {(x, y). x < y}) (\\<lambda>(c, irr, ps). mset (map degree ps))\"\n\nlemma wf_factorize_rat_poly_main_wf_rel: \"wf factorize_rat_poly_main_wf_rel\"\n  unfolding factorize_rat_poly_main_wf_rel_def using wf_mult1[OF wf_less] by auto\n\nlemma factorize_rat_poly_main_wf_rel_sub:\n  \"((a, b, ps), (c, d, p # ps)) \\<in> factorize_rat_poly_main_wf_rel\"\n  unfolding factorize_rat_poly_main_wf_rel_def\n  by (auto intro: mult1I [of _ _ _ _ \"{#}\"])\n\nlemma factorize_rat_poly_main_wf_rel_two: assumes \"degree q < degree p\" \"degree r < degree p\"\n  shows \"((a,b,q # r # ps), (c,d,p # ps)) \\<in> factorize_rat_poly_main_wf_rel\"\n  unfolding factorize_rat_poly_main_wf_rel_def mult1_def\n  using add_eq_conv_ex assms ab_semigroup_add_class.add_ac\n    by fastforce\n\ntermination \nproof (relation factorize_rat_poly_main_wf_rel,\n  rule wf_factorize_rat_poly_main_wf_rel, rule factorize_rat_poly_main_wf_rel_sub, \n  rule factorize_rat_poly_main_wf_rel_sub, rule factorize_rat_poly_main_wf_rel_two)\n  fix p q\n  assume rf: \"rational_proper_factor p = Some q\" and dp: \"degree p \\<noteq> 0\"\n  from rational_proper_factor(2)[OF rf] \n  have dvd: \"q dvd p\" and deg: \"1 \\<le> degree q\" \"degree q < degree p\" by auto\n  show \"degree q < degree p\" by fact\n  from dvd have \"p = q * (p div q)\" by auto\n  from arg_cong[OF this, of degree]\n  have \"degree p = degree q + degree (p div q)\"\n    by (subst degree_mult_eq[symmetric], insert dp, auto)\n  with deg\n  show \"degree (p div q) < degree p\" by simp\nqed  \n\ndeclare factorize_rat_poly_main.simps[simp del]\n\nlemma factorize_rat_poly_main:\n  assumes \"factorize_rat_poly_main c irr ps = (d,qs)\"\n    and \"Ball (set irr) irreducible\\<^sub>d\"\n  shows \"Ball (set qs) irreducible\\<^sub>d\" (is ?g1)\n    and \"smult c (prod_list (irr @ ps)) = smult d (prod_list qs)\" (is ?g2)\nproof (atomize(full), insert assms, induct c irr ps rule: factorize_rat_poly_main.induct)\n  case (1 c irr)\n  thus ?case by (auto simp: factorize_rat_poly_main.simps)\nnext\n  case (2 c irr p ps)\n  note IH = 2(1-3)\n  note res = 2(4)[unfolded factorize_rat_poly_main.simps(2)[of c irr p ps]]\n  note irr = 2(5)\n  let ?f = factorize_rat_poly_main\n  show ?case\n  proof (cases \"degree p = 0\")\n    case True\n    with res have res: \"?f (c * coeff p 0) irr ps = (d,qs)\" by simp\n    from degree0_coeffs[OF True] obtain a where p: \"p = [: a :]\" by auto\n    from IH(1)[OF True res irr]\n    show ?thesis using p by simp\n  next\n    case False\n    note IH = IH(2-)[OF False]\n    from False have \"(degree p = 0) = False\" by auto\n    note res = res[unfolded this if_False]\n    let ?rf = \"rational_proper_factor p\"\n    show ?thesis\n    proof (cases ?rf)\n      case None\n      with res have res: \"?f c (p # irr) ps = (d,qs)\" by auto\n      from rational_proper_factor(1)[OF _ None] False\n      have irp: \"irreducible\\<^sub>d p\" by auto\n      note IH(1)[OF None res, unfolded atomize_imp imp_conjR, simplified]\n      note 1 = conjunct1[OF this, rule_format] conjunct2[OF this, rule_format]\n      from irr irp show ?thesis by (auto intro:1 simp: ac_simps)\n    next\n      case (Some q)\n      define pq where \"pq = p div q\" \n      from Some res have res: \"?f c irr (q # pq # ps) = (d,qs)\" unfolding pq_def by auto\n      from rational_proper_factor(2)[OF Some] have \"q dvd p\" by auto\n      hence p: \"p = q * pq\" unfolding pq_def by auto\n      from IH(2)[OF Some, folded pq_def, OF res irr] show ?thesis unfolding p \n        by (auto simp: ac_simps)\n    qed\n  qed\nqed\n\ndefinition \"factorize_rat_poly_basic p = factorize_rat_poly_main 1 [] [p]\" \n\nlemma factorize_rat_poly_basic: assumes res: \"factorize_rat_poly_basic p = (c,qs)\" \n  shows \"p = smult c (prod_list qs)\" \n  \"\\<And> q. q \\<in> set qs \\<Longrightarrow> irreducible\\<^sub>d q\"\n  using factorize_rat_poly_main[OF res[unfolded factorize_rat_poly_basic_def]] by auto\n\ntext \\<open>We removed the factorize-rat-poly function from this theory, since the one in \n  Berlekamp-Zassenhaus is easier to use and implements a more efficient algorithm.\\<close>\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Polynomial_Factorization/Rational_Factorization.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8791467754256017, "lm_q1q2_score": 0.7786000650379524}}
{"text": "(*<*)\ntheory Szpilrajn \n  imports Main\nbegin\n  (*>*)\n\ntext \\<open>\n  We formalize a more general version of Szpilrajn's extension theorem~\\<^cite>\\<open>\"Szpilrajn:1930\"\\<close>,\n  employing the terminology of Bossert and Suzumura~\\<^cite>\\<open>\"Bossert:2010\"\\<close>. We also formalize \n  Theorem 2.7 of their book. Our extension theorem states that any preorder can be extended to a\n  total preorder while maintaining its structure. The proof of the extension theorem follows the\n  proof presented in the Wikipedia article~\\<^cite>\\<open>Wiki\\<close>.\n\\<close>\n\nsection \\<open>Definitions\\<close>\n\nsubsection \\<open>Symmetric and asymmetric factor of a relation\\<close>\n\ntext \\<open>\n  According to Bossert and Suzumura, every relation can be partitioned into its symmetric\n  and asymmetric factor. The symmetric factor of a relation \\<^term>\\<open>r\\<close> contains all pairs\n  \\<^term>\\<open>(x, y) \\<in> r\\<close> where \\<^term>\\<open>(y, x) \\<in> r\\<close>. Conversely, the asymmetric factor contains all pairs\n   where this is not the case. In terms of an order \\<^term>\\<open>(\\<le>)\\<close>, the asymmetric factor contains all\n  \\<^term>\\<open>(x, y) \\<in> {(x, y) |x y. x \\<le> y}\\<close> where \\<^term>\\<open>x < y\\<close>.\n\\<close>\ndefinition sym_factor :: \"'a rel \\<Rightarrow> 'a rel\"\n  where \"sym_factor r \\<equiv> {(x, y) \\<in> r. (y, x) \\<in> r}\"\n\nlemma sym_factor_def': \"sym_factor r = r \\<inter> r\\<inverse>\"\n  unfolding sym_factor_def by fast\n\ndefinition asym_factor :: \"'a rel \\<Rightarrow> 'a rel\"\n  where \"asym_factor r = {(x, y) \\<in> r. (y, x) \\<notin> r}\"\n\n\nsubsubsection \\<open>Properties of the symmetric factor\\<close>\n\nlemma sym_factorI[intro]: \"(x, y) \\<in> r \\<Longrightarrow> (y, x) \\<in> r \\<Longrightarrow> (x, y) \\<in> sym_factor r\"\n  unfolding sym_factor_def by blast\n\nlemma sym_factorE[elim?]:\n  assumes \"(x, y) \\<in> sym_factor r\" obtains \"(x, y) \\<in> r\" \"(y, x) \\<in> r\"\n  using assms[unfolded sym_factor_def] by blast\n\nlemma sym_sym_factor[simp]: \"sym (sym_factor r)\"\n  unfolding sym_factor_def\n  by (auto intro!: symI) \n\nlemma trans_sym_factor[simp]: \"trans r \\<Longrightarrow> trans (sym_factor r)\"\n  unfolding sym_factor_def' using trans_Int by force\n\nlemma refl_on_sym_factor[simp]: \"refl_on A r \\<Longrightarrow> refl_on A (sym_factor r)\"\n  unfolding sym_factor_def\n  by (auto intro!: refl_onI dest: refl_onD refl_onD1)\n\nlemma sym_factor_absorb_if_sym[simp]: \"sym r \\<Longrightarrow> sym_factor r = r\"\n  unfolding sym_factor_def'\n  by (simp add: sym_conv_converse_eq)\n\nlemma sym_factor_idem[simp]: \"sym_factor (sym_factor r) = sym_factor r\"\n  using sym_factor_absorb_if_sym[OF sym_sym_factor] .\n\nlemma sym_factor_reflc[simp]: \"sym_factor (r\\<^sup>=) = (sym_factor r)\\<^sup>=\"\n  unfolding sym_factor_def by auto\n\nlemma sym_factor_Restr[simp]: \"sym_factor (Restr r A) = Restr (sym_factor r) A\"\n  unfolding sym_factor_def by blast\n\ntext \\<open>\n  In contrast to \\<^term>\\<open>asym_factor\\<close>, the \\<^term>\\<open>sym_factor\\<close> is monotone.\n\\<close>\nlemma sym_factor_mono: \"r \\<subseteq> s \\<Longrightarrow> sym_factor r \\<subseteq> sym_factor s\"\n  unfolding sym_factor_def by auto\n\n\nsubsubsection \\<open>Properties of the asymmetric factor\\<close>\n\nlemma asym_factorI[intro]: \"(x, y) \\<in> r \\<Longrightarrow> (y, x) \\<notin> r \\<Longrightarrow> (x, y) \\<in> asym_factor r\"\n  unfolding asym_factor_def by blast\n\nlemma asym_factorE[elim?]:\n  assumes \"(x, y) \\<in> asym_factor r\" obtains \"(x, y) \\<in> r\"\n  using assms unfolding asym_factor_def by blast\n\nlemma refl_not_in_asym_factor[simp]: \"(x, x) \\<notin> asym_factor r\"\n  unfolding asym_factor_def by blast\n\nlemma irrefl_asym_factor[simp]: \"irrefl (asym_factor r)\"\n  unfolding asym_factor_def irrefl_def by fast\n\nlemma asym_asym_factor[simp]: \"asym (asym_factor r)\"\n  using irrefl_asym_factor\n  by (auto intro!: asymI simp: asym_factor_def)\n\nlemma trans_asym_factor[simp]: \"trans r \\<Longrightarrow> trans (asym_factor r)\"\n  unfolding asym_factor_def trans_def by fast\n\nlemma asym_if_irrefl_trans: \"irrefl r \\<Longrightarrow> trans r \\<Longrightarrow> asym r\"\n  by (intro asymI) (auto simp: irrefl_def trans_def)\n\nlemma antisym_if_irrefl_trans: \"irrefl r \\<Longrightarrow> trans r \\<Longrightarrow> antisym r\"\n  using antisym_def asym_if_irrefl_trans by (auto dest: asymD)\n    \nlemma asym_factor_asym_rel[simp]: \"asym r \\<Longrightarrow> asym_factor r = r\"\n  unfolding asym_factor_def\n  by (auto dest: asymD)\n\nlemma irrefl_trans_asym_factor_id[simp]: \"irrefl r \\<Longrightarrow> trans r \\<Longrightarrow> asym_factor r = r\"\n  using asym_factor_asym_rel[OF asym_if_irrefl_trans] .\n\nlemma asym_factor_id[simp]: \"asym_factor (asym_factor r) = asym_factor r\"\n  using asym_factor_asym_rel[OF asym_asym_factor] .\n\nlemma asym_factor_rtrancl: \"asym_factor (r\\<^sup>*) = asym_factor (r\\<^sup>+)\"\n  unfolding asym_factor_def\n  by (auto simp add: rtrancl_eq_or_trancl)\n\nlemma asym_factor_Restr[simp]: \"asym_factor (Restr r A) = Restr (asym_factor r) A\"\n  unfolding asym_factor_def by blast\n\nlemma acyclic_asym_factor[simp]: \"acyclic r \\<Longrightarrow> acyclic (asym_factor r)\"\n  unfolding asym_factor_def by (auto intro: acyclic_subset)\n\n\nsubsubsection \\<open>Relations between symmetric and asymmetric factor\\<close>\n\ntext \\<open>\n  We prove that \\<^term>\\<open>sym_factor\\<close> and \\<^term>\\<open>asym_factor\\<close> partition the input relation.\n\\<close>\nlemma sym_asym_factor_Un: \"sym_factor r \\<union> asym_factor r = r\"\n  unfolding sym_factor_def asym_factor_def by blast\n\nlemma disjnt_sym_asym_factor[simp]: \"disjnt (sym_factor r) (asym_factor r)\"\n  unfolding disjnt_def\n  unfolding sym_factor_def asym_factor_def by blast\n\nlemma Field_sym_asym_factor_Un:\n  \"Field (sym_factor r) \\<union> Field (asym_factor r) = Field r\"\n  using sym_asym_factor_Un Field_Un by metis\n\nlemma asym_factor_tranclE:\n  assumes \"(a, b) \\<in> (asym_factor r)\\<^sup>+\" shows \"(a, b) \\<in> r\\<^sup>+\"\n  using assms sym_asym_factor_Un\n  by (metis UnCI subsetI trancl_mono)\n\n\nsubsection \\<open>Extension of Orders\\<close>\n\ntext \\<open>\n  We use the definition of Bossert and Suzumura for \\<open>extends\\<close>. The requirement \\<^term>\\<open>r \\<subseteq> R\\<close> is\n  obvious. The second requirement \\<^term>\\<open>asym_factor r \\<subseteq> asym_factor R\\<close> enforces that the \n  extension \\<^term>\\<open>R\\<close> maintains all strict preferences of \\<^term>\\<open>r\\<close> (viewing \\<^term>\\<open>r\\<close> as a \n  preference relation).\n\\<close>\n                    \ndefinition extends :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"extends R r \\<equiv> r \\<subseteq> R \\<and> asym_factor r \\<subseteq> asym_factor R\"\n\ntext \\<open>\n  We define a stronger notion of \\<^term>\\<open>extends\\<close> where we also demand that\n  \\<^term>\\<open>sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\\<close>. This enforces that the extension does not introduce\n  preference cycles between previously unrelated pairs \\<^term>\\<open>(x, y) \\<in> R - r\\<close>.\n\\<close>\n\ndefinition strict_extends :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> bool\"\n  where \"strict_extends R r \\<equiv> extends R r \\<and> sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\"\n\nlemma extendsI[intro]: \"r \\<subseteq> R \\<Longrightarrow> asym_factor r \\<subseteq> asym_factor R \\<Longrightarrow> extends R r\"\n  unfolding extends_def by (intro conjI)\n\nlemma extendsE:\n  assumes \"extends R r\"\n  obtains \"r \\<subseteq> R\" \"asym_factor r \\<subseteq> asym_factor R\"\n  using assms unfolding extends_def by blast\n\nlemma trancl_subs_extends_if_trans: \"extends r_ext r \\<Longrightarrow> trans r_ext \\<Longrightarrow> r\\<^sup>+ \\<subseteq> r_ext\"\n  unfolding extends_def asym_factor_def\n  by (metis subrelI trancl_id trancl_mono)\n\nlemma extends_if_strict_extends: \"strict_extends r_ext ext \\<Longrightarrow> extends r_ext ext\"\n  unfolding strict_extends_def by blast\n\nlemma strict_extendsI[intro]:\n  assumes \"r \\<subseteq> R\" \"asym_factor r \\<subseteq> asym_factor R\" \"sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\"\n  shows \"strict_extends R r\"\n  unfolding strict_extends_def using assms by (intro conjI extendsI)\n\nlemma strict_extendsE:\n  assumes \"strict_extends R r\"\n  obtains \"r \\<subseteq> R\" \"asym_factor r \\<subseteq> asym_factor R\" \"sym_factor R \\<subseteq> (sym_factor r)\\<^sup>=\"\n  using assms extendsE unfolding strict_extends_def by blast\n\nlemma strict_extends_antisym_Restr:\n  assumes \"strict_extends R r\"\n  assumes \"antisym (Restr r A)\"\n  shows \"antisym ((R - r) \\<union> Restr r A)\"\nproof(rule antisymI, rule ccontr)\n  fix x y assume \"(x, y) \\<in> (R - r) \\<union> Restr r A\" \"(y, x) \\<in> (R - r) \\<union> Restr r A\" \"x \\<noteq> y\"\n  with \\<open>strict_extends R r\\<close> have \"(x, y) \\<in> sym_factor R\"\n    unfolding sym_factor_def by (auto elim!: strict_extendsE)\n  with assms \\<open>x \\<noteq> y\\<close> have \"(x, y) \\<in> sym_factor r\"\n    by (auto elim!: strict_extendsE)\n  then have \"(x, y) \\<in> r\" \"(y, x) \\<in> r\"\n    unfolding sym_factor_def by simp_all\n  with \\<open>antisym (Restr r A)\\<close> \\<open>x \\<noteq> y\\<close> \\<open>(y, x) \\<in> R - r \\<union> Restr r A\\<close> show False\n    using antisymD by fastforce\nqed\n\ntext \\<open>Here we prove that we have no preference cycles between previously unrelated pairs.\\<close>\nlemma antisym_Diff_if_strict_extends:\n  assumes \"strict_extends R r\"\n  shows \"antisym (R - r)\"\n  using strict_extends_antisym_Restr[OF assms, where ?A=\"{}\"] by simp\n\nlemma strict_extends_antisym:\n  assumes \"strict_extends R r\"\n  assumes \"antisym r\"\n  shows \"antisym R\"\n  using assms strict_extends_antisym_Restr[OF assms(1), where ?A=UNIV]\n  by (auto elim!: strict_extendsE simp: antisym_def) \n\nlemma strict_extends_if_strict_extends_reflc:\n  assumes \"strict_extends r_ext (r\\<^sup>=)\"\n  shows \"strict_extends r_ext r\"\nproof(intro strict_extendsI)\n  from assms show \"r \\<subseteq> r_ext\"\n    by (auto elim: strict_extendsE)\n\n  from assms \\<open>r \\<subseteq> r_ext\\<close> show \"asym_factor r \\<subseteq> asym_factor r_ext\"\n    unfolding strict_extends_def\n    by (auto simp: asym_factor_def sym_factor_def)\n\n  from assms show \"sym_factor r_ext \\<subseteq> (sym_factor r)\\<^sup>=\"\n    by (auto simp: sym_factor_def strict_extends_def)\nqed\n\nlemma strict_extends_diff_Id:\n  assumes \"irrefl r\" \"trans r\"\n  assumes \"strict_extends r_ext (r\\<^sup>=)\"\n  shows \"strict_extends (r_ext - Id) r\"\nproof(intro strict_extendsI)\n  from assms show \"r \\<subseteq> r_ext - Id\"\n    by (auto elim: strict_extendsE simp: irrefl_def)\n\n  note antisym_r = antisym_if_irrefl_trans[OF assms(1,2)]\n  with assms strict_extends_if_strict_extends_reflc show \"asym_factor r \\<subseteq> asym_factor (r_ext - Id)\"\n    unfolding asym_factor_def\n    by (auto intro: strict_extends_antisym[THEN antisymD] elim: strict_extendsE transE)\n\n  from assms antisym_r show \"sym_factor (r_ext - Id) \\<subseteq> (sym_factor r)\\<^sup>=\"\n    unfolding sym_factor_def\n    by (auto intro: strict_extends_antisym[THEN antisymD])\nqed\n\ntext \\<open>\n  Both \\<^term>\\<open>extends\\<close> and \\<^term>\\<open>strict_extends\\<close> form a partial order since they\n  are reflexive, transitive, and antisymmetric.\n\\<close>\nlemma shows\n    reflp_extends: \"reflp extends\" and\n    transp_extends: \"transp extends\" and\n    antisymp_extends: \"antisymp extends\"\n  unfolding extends_def reflp_def transp_def antisymp_def\n  by auto\n\nlemma shows\n    reflp_strict_extends: \"reflp strict_extends\" and\n    transp_strict_extends: \"transp strict_extends\" and\n    antisymp_strict_extends: \"antisymp strict_extends\"\n  using reflp_extends transp_extends antisymp_extends\n  unfolding strict_extends_def reflp_def transp_def antisymp_def\n  by auto\n\nsubsection \\<open>Missing order definitions\\<close>\n\nlemma preorder_onD[dest?]:\n  assumes \"preorder_on A r\"\n  shows \"refl_on A r\" \"trans r\"\n  using assms unfolding preorder_on_def by blast+\n\nlemma preorder_onI[intro]: \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> preorder_on A r\"\n  unfolding preorder_on_def by (intro conjI)\n\nabbreviation \"preorder \\<equiv> preorder_on UNIV\"\n\nlemma preorder_rtrancl: \"preorder (r\\<^sup>*)\"\n  by (intro preorder_onI refl_rtrancl trans_rtrancl)\n\ndefinition \"total_preorder_on A r \\<equiv> preorder_on A r \\<and> total_on A r\"\n\nabbreviation \"total_preorder r \\<equiv> total_preorder_on UNIV r\"\n\nlemma total_preorder_onI[intro]:\n  \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> total_on A r \\<Longrightarrow> total_preorder_on A r\"\n  unfolding total_preorder_on_def by (intro conjI preorder_onI)\n\nlemma total_preorder_onD[dest?]:\n  assumes \"total_preorder_on A r\"\n  shows \"refl_on A r\" \"trans r\" \"total_on A r\"\n  using assms unfolding total_preorder_on_def preorder_on_def by blast+\n\ndefinition \"strict_partial_order r \\<equiv> trans r \\<and> irrefl r\"\n\nlemma strict_partial_orderI[intro]:\n  \"trans r \\<Longrightarrow> irrefl r \\<Longrightarrow> strict_partial_order r\"\n  unfolding strict_partial_order_def by blast\n\nlemma strict_partial_orderD[dest?]:\n  assumes \"strict_partial_order r\"\n  shows \"trans r\" \"irrefl r\"\n  using assms unfolding strict_partial_order_def by blast+\n\nlemma strict_partial_order_acyclic:\n  assumes \"strict_partial_order r\"\n  shows \"acyclic r\"\n  by (metis acyclic_irrefl assms strict_partial_order_def trancl_id)\n\n\nabbreviation \"partial_order \\<equiv> partial_order_on UNIV\"\n\nlemma partial_order_onI[intro]:\n  \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> antisym r \\<Longrightarrow> partial_order_on A r\"\n  using partial_order_on_def by blast\n\nlemma linear_order_onI[intro]:\n  \"refl_on A r \\<Longrightarrow> trans r \\<Longrightarrow> antisym r \\<Longrightarrow> total_on A r \\<Longrightarrow> linear_order_on A r\"\n  using linear_order_on_def by blast\n\nlemma linear_order_onD[dest?]:\n  assumes \"linear_order_on A r\"\n  shows \"refl_on A r\" \"trans r\" \"antisym r\" \"total_on A r\"\n  using assms[unfolded linear_order_on_def] partial_order_onD by blast+\n\ntext \\<open>A typical example is \\<^term>\\<open>(\\<subset>)\\<close> on sets:\\<close>\n\nlemma strict_partial_order_subset:\n  \"strict_partial_order {(x,y). x \\<subset> y}\"\nproof\n  show \"trans {(x,y). x \\<subset> y}\"\n    by (auto simp add: trans_def)\n  show \"irrefl {(x, y). x \\<subset> y}\"\n    by (simp add: irrefl_def)\nqed\n\ntext \\<open>We already have a definition of a strict linear order in \\<^term>\\<open>strict_linear_order\\<close>.\\<close>\n\nsection \\<open>Extending preorders to total preorders\\<close>\n\ntext \\<open>\n  We start by proving that a preorder with two incomparable elements \\<^term>\\<open>x\\<close> and \\<^term>\\<open>y\\<close> can be\n  strictly extended to a preorder where \\<^term>\\<open>x < y\\<close>.\n\\<close>\n\nlemma can_extend_preorder: \n  assumes \"preorder_on A r\"\n    and \"y \\<in> A\" \"x \\<in> A\" \"(y, x) \\<notin> r\"\n  shows\n    \"preorder_on A ((insert (x, y) r)\\<^sup>+)\" \"strict_extends ((insert (x, y) r)\\<^sup>+) r\"\nproof -\n  note preorder_onD[OF \\<open>preorder_on A r\\<close>]\n  then have \"insert (x, y) r \\<subseteq> A \\<times> A\"\n    using \\<open>y \\<in> A\\<close> \\<open>x \\<in> A\\<close> refl_on_domain by fast\n  with \\<open>refl_on A r\\<close> show \"preorder_on A ((insert (x, y) r)\\<^sup>+)\"\n    by (intro preorder_onI refl_onI trans_trancl)\n       (auto simp: trancl_subset_Sigma intro!: r_into_trancl' dest: refl_onD)\n\n  show \"strict_extends ((insert (x, y) r)\\<^sup>+) r\"\n  proof(intro strict_extendsI)\n    from preorder_onD(2)[OF \\<open>preorder_on A r\\<close>] \\<open>(y, x) \\<notin> r\\<close>\n    show \"asym_factor r \\<subseteq> asym_factor ((insert (x, y) r)\\<^sup>+)\"\n       unfolding asym_factor_def trancl_insert\n       using rtranclD rtrancl_into_trancl1 r_r_into_trancl\n       by fastforce\n\n     from assms have \"(y, x) \\<notin> (insert (x, y) r)\\<^sup>+\"\n       unfolding preorder_on_def trancl_insert\n       using refl_onD rtranclD by fastforce\n     with \\<open>trans r\\<close> show \"sym_factor ((insert (x, y) r)\\<^sup>+) \\<subseteq> (sym_factor r)\\<^sup>=\"\n       unfolding trancl_insert sym_factor_def by (fastforce intro: rtrancl_trans)\n  qed auto\nqed\n\n\ntext \\<open>\n  With this, we can start the proof of our main extension theorem.\n  For this we will use a variant of Zorns Lemma, which only considers nonempty chains:\n\\<close>\nlemma Zorns_po_lemma_nonempty:\n  assumes po: \"Partial_order r\"\n    and u: \"\\<And>C. \\<lbrakk>C \\<in> Chains r; C\\<noteq>{}\\<rbrakk> \\<Longrightarrow> \\<exists>u\\<in>Field r. \\<forall>a\\<in>C. (a, u) \\<in> r\"\n    and \"r \\<noteq> {}\"\n  shows \"\\<exists>m\\<in>Field r. \\<forall>a\\<in>Field r. (m, a) \\<in> r \\<longrightarrow> a = m\"\nproof -\n  from \\<open>r \\<noteq> {}\\<close> obtain x where \"x \\<in> Field r\"\n    using FieldI2 by fastforce\n  with assms show ?thesis\n    using Zorns_po_lemma by (metis empty_iff)  \nqed\n\n\ntheorem strict_extends_preorder_on:\n  assumes \"preorder_on A base_r\"\n  shows \"\\<exists>r. total_preorder_on A r \\<and> strict_extends r base_r\" \nproof -\n\n  text \\<open>\n    We define an order on the set of strict extensions of the base relation \\<^term>\\<open>base_r\\<close>, \n    where \\<^term>\\<open>r \\<le> s\\<close> iff \\<^term>\\<open>strict_extends r base_r\\<close> and \\<^term>\\<open>strict_extends s r\\<close>:\n  \\<close>\n\n  define order_of_orders :: \"('a rel) rel\" where \"order_of_orders =\n    Restr {(r, s). strict_extends r base_r \\<and> strict_extends s r} {r. preorder_on A r}\"\n\n  text \\<open>\n    We show that this order consists of those relations that are preorders and that strictly extend\n    the base relation \\<^term>\\<open>base_r\\<close>\n  \\<close>\n\n  have Field_order_of_orders: \"Field order_of_orders =\n    {r. preorder_on A r \\<and> strict_extends r base_r}\"\n    using transp_strict_extends\n  proof(safe)\n    fix r assume \"preorder_on A r\" \"strict_extends r base_r\"\n    with reflp_strict_extends have\n      \"(r, r) \\<in> {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      by (auto elim!: reflpE)\n    with \\<open>preorder_on A r\\<close> show \"r \\<in> Field order_of_orders\"\n      unfolding order_of_orders_def by (auto simp: Field_def)\n  qed (auto simp: order_of_orders_def Field_def elim: transpE)\n\n  text \\<open>\n    We now show that this set has a maximum and that any maximum of this set is a total preorder\n    and as thus is one of the extensions we are looking for.\n    We begin by showing the existence of a maximal element using Zorn's lemma.\n  \\<close>\n\n  have \"\\<exists>m \\<in> Field order_of_orders.\n      \\<forall>a \\<in> Field order_of_orders. (m, a) \\<in> order_of_orders \\<longrightarrow> a = m\"\n  proof (rule Zorns_po_lemma_nonempty)\n\n    text \\<open>\n      Zorn's Lemma requires us to prove that our \\<^term>\\<open>order_of_orders\\<close> is a nonempty partial order\n      and that every nonempty chain has an upper bound. \n      The partial order property is trivial, since we used \\<^term>\\<open>strict_extends\\<close> for the relation, \n      which is a partial order as shown above.\n    \\<close>\n\n    from reflp_strict_extends transp_strict_extends\n    have \"Refl {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      unfolding refl_on_def Field_def by (auto elim: transpE reflpE)\n    moreover have \"trans {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      using transp_strict_extends  by (auto elim: transpE intro: transI)\n    moreover have \"antisym {(r, s). strict_extends r base_r \\<and> strict_extends s r}\"\n      using antisymp_strict_extends by (fastforce dest: antisympD intro: antisymI)\n\n    ultimately show \"Partial_order order_of_orders\"\n      unfolding order_of_orders_def order_on_defs\n      using Field_order_of_orders Refl_Restr trans_Restr antisym_Restr\n      by blast\n\n    text \\<open>Also, our order is obviously not empty since it contains \\<^term>\\<open>(base_r, base_r)\\<close>:\\<close>\n\n    have \"(base_r, base_r) \\<in> order_of_orders\"\n      unfolding order_of_orders_def\n      using assms reflp_strict_extends by (auto dest: reflpD)\n    thus \"order_of_orders \\<noteq> {}\" by force\n\n\n    text \\<open>\n      Next we show that each chain has an upper bound.\n      For the upper bound we take the union of all relations in the chain.\n    \\<close>\n\n    show \"\\<exists>u \\<in> Field order_of_orders. \\<forall>a \\<in> C. (a, u) \\<in> order_of_orders\" \n      if C_def: \"C \\<in> Chains order_of_orders\" and C_nonempty: \"C \\<noteq> {}\"\n      for C\n    proof (rule bexI[where x=\"\\<Union>C\"])\n\n      text \\<open>\n        Obviously each element in the chain is a strict extension of \\<^term>\\<open>base_r\\<close> by definition\n        and as such it is also a preorder.\n      \\<close>\n\n      have preorder_r: \"preorder_on A r\" and extends_r: \"strict_extends r base_r\" if \"r \\<in> C\" for r\n        using that C_def[unfolded order_of_orders_def Chains_def] by blast+\n\n      text \\<open>\n        Because a chain is partially ordered, the union of the chain is reflexive and transitive.\n      \\<close>\n\n      have total_subs_C: \"r \\<subseteq> s \\<or> s \\<subseteq> r\" if \"r \\<in> C\" and \"s \\<in> C\" for r s\n        using C_def that\n        unfolding Chains_def order_of_orders_def strict_extends_def extends_def\n        by blast\n\n      have preorder_UnC: \"preorder_on A (\\<Union>C)\"\n      proof(intro preorder_onI)\n        show \"refl_on A (\\<Union>C)\"\n          using preorder_onD(1)[OF preorder_r] C_nonempty\n          unfolding refl_on_def by auto\n\n        from total_subs_C show \"trans (\\<Union>C)\"\n          using chain_subset_trans_Union[unfolded chain_subset_def]\n          by (metis preorder_onD(2)[OF preorder_r])\n      qed\n\n      text \\<open>We show that \\<^term>\\<open>\\<Union>C\\<close> strictly extends the base relation.\\<close>\n    \n      have strict_extends_UnC: \"strict_extends (\\<Union>C) base_r\"\n      proof(intro strict_extendsI)\n        note extends_r_unfolded = extends_r[unfolded extends_def strict_extends_def]\n\n        show \"base_r \\<subseteq> (\\<Union>C)\"\n          using C_nonempty extends_r_unfolded\n          by blast\n\n        then show \"asym_factor base_r \\<subseteq> asym_factor (\\<Union>C)\"\n          using extends_r_unfolded\n          unfolding asym_factor_def by auto\n\n        show \"sym_factor (\\<Union>C) \\<subseteq> (sym_factor base_r)\\<^sup>=\"\n        proof(safe)\n          fix x y assume \"(x, y) \\<in> sym_factor (\\<Union>C)\" \"(x, y) \\<notin> sym_factor base_r\"\n          then have \"(x, y) \\<in> \\<Union>C\" \"(y, x) \\<in> \\<Union>C\"\n            unfolding sym_factor_def by blast+\n\n          with extends_r obtain c where \"c \\<in> C\" \"(x, y) \\<in> c\" \"(y, x) \\<in> c\"\n            \"strict_extends c base_r\"\n            using total_subs_C by blast\n          then have \"(x, y) \\<in> sym_factor c\"\n            unfolding sym_factor_def by blast\n          with \\<open>strict_extends c base_r\\<close> \\<open>(x, y) \\<notin> sym_factor base_r\\<close>\n          show \"x = y\"\n            unfolding strict_extends_def by blast\n        qed\n      qed\n\n      from preorder_UnC strict_extends_UnC show \"(\\<Union>C) \\<in> Field order_of_orders\"\n        unfolding Field_order_of_orders by simp\n\n      text \\<open>\n        Lastly, we prove by contradiction that \\<^term>\\<open>\\<Union>C\\<close> is an upper bound for the chain.\n      \\<close>\n\n      show \"\\<forall>a \\<in> C. (a, \\<Union>C) \\<in> order_of_orders\"\n      proof(rule ccontr)\n        presume \"\\<exists>a \\<in> C. (a, \\<Union>C) \\<notin> order_of_orders\"\n        then obtain m where m: \"m \\<in> C\" \"(m, \\<Union>C) \\<notin> order_of_orders\"\n          by blast\n\n        hence strict_extends_m: \"strict_extends m base_r\" \"preorder_on A m\"\n          using extends_r preorder_r by blast+\n        with m have \"\\<not> strict_extends (\\<Union>C) m\"\n          using preorder_UnC unfolding order_of_orders_def by blast\n\n        from m have \"m \\<subseteq> \\<Union>C\"\n          by blast\n        moreover\n        have \"sym_factor (\\<Union>C) \\<subseteq> (sym_factor m)\\<^sup>=\"\n        proof(safe)\n          fix a b\n          assume \"(a, b) \\<in> sym_factor (\\<Union> C)\" \"(a, b) \\<notin> sym_factor m\"\n          then have \"(a, b) \\<in> sym_factor base_r \\<or> (a, b) \\<in> Id\"\n            using strict_extends_UnC[unfolded strict_extends_def] by blast\n          with \\<open>(a, b) \\<notin> sym_factor m\\<close> strict_extends_m(1) show \"a = b\"\n            by (auto elim: strict_extendsE simp: sym_factor_mono[THEN in_mono])\n        qed\n        ultimately\n        have \"\\<not> asym_factor m \\<subseteq> asym_factor (\\<Union>C)\"\n          using \\<open>\\<not> strict_extends (\\<Union>C) m\\<close> unfolding strict_extends_def extends_def by blast\n\n        then obtain x y where\n          \"(x, y) \\<in> m\" \"(y, x) \\<notin> m\" \"(x, y) \\<in> asym_factor m\" \"(x, y) \\<notin> asym_factor (\\<Union>C)\"\n          unfolding asym_factor_def by blast\n    \n        then obtain w where \"w \\<in> C\" \"(y, x) \\<in> w\"\n          unfolding asym_factor_def using \\<open>m \\<in> C\\<close> by auto\n\n        with \\<open>(y, x) \\<notin> m\\<close> have \"\\<not> extends m w\"\n          unfolding extends_def by auto\n        moreover\n        from \\<open>(x, y) \\<in> m\\<close> have \"\\<not> extends w m\"\n        proof(cases \"(x, y) \\<in> w\")\n          case True\n          with \\<open>(y, x) \\<in> w\\<close> have \"(x, y) \\<notin> asym_factor w\"\n            unfolding asym_factor_def by simp\n          with \\<open>(x, y) \\<in> asym_factor m\\<close> show \"\\<not> extends w m\"\n            unfolding extends_def by auto\n        qed (auto simp: extends_def)\n\n        ultimately show False\n          using \\<open>m \\<in> C\\<close> \\<open>w \\<in> C\\<close>\n          using C_def[unfolded Chains_def order_of_orders_def strict_extends_def]\n          by auto\n      qed blast\n    qed\n  qed\n\n  text \\<open>Let our maximal element be named \\<^term>\\<open>max\\<close>:\\<close>\n\n  from this obtain max \n    where max_field: \"max \\<in> Field order_of_orders\"\n      and is_max: \n        \"\\<forall>a\\<in>Field order_of_orders. (max, a) \\<in> order_of_orders \\<longrightarrow> a = max\"\n    by auto\n\n  from max_field have max_extends_base: \"preorder_on A max\" \"strict_extends max base_r\"\n    using Field_order_of_orders by blast+\n\n  text \\<open>\n    We still have to show, that \\<^term>\\<open>max\\<close> is a strict linear order,\n    meaning that it is also a total order:\n  \\<close>\n\n  have \"total_on A max\"\n  proof\n    fix x y :: 'a\n    assume \"x \\<noteq> y\" \"x \\<in> A\" \"y \\<in> A\"\n\n    show \"(x, y) \\<in> max \\<or> (y, x) \\<in> max\"\n    proof (rule ccontr)\n\n      text \\<open>\n        Assume that \\<^term>\\<open>max\\<close> is not total, and \\<^term>\\<open>x\\<close> and \\<^term>\\<open>y\\<close> are incomparable.\n        Then we can extend \\<^term>\\<open>max\\<close> by setting $x < y$:\n      \\<close>\n\n      presume \"(x, y) \\<notin> max\" and \"(y, x) \\<notin> max\"\n      let ?max' = \"(insert (x, y) max)\\<^sup>+\"\n\n      note max'_extends_max = can_extend_preorder[OF\n          \\<open>preorder_on A max\\<close> \\<open>y \\<in> A\\<close> \\<open>x \\<in> A\\<close> \\<open>(y, x) \\<notin> max\\<close>]\n\n      hence max'_extends_base: \"strict_extends ?max' base_r\"\n        using \\<open>strict_extends max base_r\\<close> transp_strict_extends by (auto elim: transpE)\n\n\n      text \\<open>The extended relation is greater than \\<^term>\\<open>max\\<close>, which is a contradiction.\\<close>\n\n      have \"(max, ?max') \\<in> order_of_orders\"\n        using max'_extends_base max'_extends_max max_extends_base\n        unfolding order_of_orders_def by simp\n      thus False\n        using FieldI2 \\<open>(x, y) \\<notin> max\\<close> is_max by fastforce\n    qed simp_all\n  qed\n\n  with \\<open>preorder_on A max\\<close> have \"total_preorder_on A max\"\n    unfolding total_preorder_on_def by simp\n\n  with \\<open>strict_extends max base_r\\<close> show \"?thesis\" by blast\nqed\n\ntext \\<open>\n  With this extension theorem, we can easily prove Szpilrajn's theorem and its equivalent for\n  partial orders.\n\\<close>\n\ncorollary partial_order_extension:\n  assumes \"partial_order_on A r\"\n  shows \"\\<exists>r_ext. linear_order_on A r_ext \\<and> r \\<subseteq> r_ext\"\nproof -\n  from assms strict_extends_preorder_on obtain r_ext where r_ext:\n    \"total_preorder_on A r_ext\" \"strict_extends r_ext r\"\n    unfolding partial_order_on_def by blast\n\n  with assms have \"antisym r_ext\"\n    unfolding partial_order_on_def using strict_extends_antisym by blast\n\n  with assms r_ext have \"linear_order_on A r_ext \\<and> r \\<subseteq> r_ext\"\n    unfolding total_preorder_on_def order_on_defs strict_extends_def extends_def\n    by blast\n  then show ?thesis ..\nqed\n\ncorollary Szpilrajn:\n  assumes \"strict_partial_order r\"\n  shows \"\\<exists>r_ext. strict_linear_order r_ext \\<and> r \\<subseteq> r_ext\"\nproof -\n  from assms have \"partial_order (r\\<^sup>=)\"\n    by (auto simp: antisym_if_irrefl_trans strict_partial_order_def)\n  from partial_order_extension[OF this] obtain r_ext where \"linear_order r_ext\" \"(r\\<^sup>=) \\<subseteq> r_ext\"\n    by blast\n  with assms have \"r \\<subseteq> r_ext - Id\" \"strict_linear_order (r_ext - Id)\"\n    by (auto simp: irrefl_def strict_linear_order_on_diff_Id dest: strict_partial_orderD(2))\n  then show ?thesis by blast\nqed\n\ncorollary acyclic_order_extension:\n  assumes \"acyclic r\"\n  shows \"\\<exists>r_ext. strict_linear_order r_ext \\<and> r \\<subseteq> r_ext\"\nproof -\n  from assms have \"strict_partial_order (r\\<^sup>+)\"\n    unfolding strict_partial_order_def using acyclic_irrefl trans_trancl by blast\n  thus ?thesis\n    by (meson Szpilrajn r_into_trancl' subset_iff)\nqed\n\nsection \\<open>Consistency\\<close>\n\ntext \\<open>\n  As a weakening of transitivity, Suzumura introduces the notion of consistency which rules out\n  all preference cycles that contain at least one strict preference.\n  Consistency characterises those order relations which can be extended (in terms of \\<^term>\\<open>extends\\<close>)\n  to a total order relation. \n\\<close>\n\ndefinition consistent :: \"'a rel \\<Rightarrow> bool\"\n  where \"consistent r = (\\<forall>(x, y) \\<in> r\\<^sup>+. (y, x) \\<notin> asym_factor r)\"\n\nlemma consistentI: \"(\\<And>x y. (x, y) \\<in> r\\<^sup>+ \\<Longrightarrow> (y, x) \\<notin> asym_factor r) \\<Longrightarrow> consistent r\"\n  unfolding consistent_def by blast\n\nlemma consistent_if_preorder_on[simp]:\n  \"preorder_on A r \\<Longrightarrow> consistent r\"\n  unfolding preorder_on_def consistent_def asym_factor_def by auto\n\nlemma consistent_asym_factor[simp]: \"consistent r \\<Longrightarrow> consistent (asym_factor r)\"\n  unfolding consistent_def\n  using asym_factor_tranclE by fastforce\n\nlemma acyclic_asym_factor_if_consistent[simp]: \"consistent r \\<Longrightarrow> acyclic (asym_factor r)\"\n  unfolding consistent_def acyclic_def\n  using asym_factor_tranclE by (metis case_prodD trancl.simps)\n\nlemma consistent_Restr[simp]: \"consistent r \\<Longrightarrow> consistent (Restr r A)\"\n  unfolding consistent_def asym_factor_def\n  using trancl_mono by fastforce\n\ntext \\<open>\n  This corresponds to Theorem 2.2~\\<^cite>\\<open>\"Bossert:2010\"\\<close>.\n\\<close>\ntheorem trans_if_refl_total_consistent:\n  assumes \"refl r\" \"total r\" and \"consistent r\"\n  shows \"trans r\"\nproof\n  fix x y z assume \"(x, y) \\<in> r\" \"(y, z) \\<in> r\"\n  \n  from \\<open>(x, y) \\<in> r\\<close> \\<open>(y, z) \\<in> r\\<close> have \"(x, z) \\<in> r\\<^sup>+\"\n    by simp\n  hence \"(z, x) \\<notin> asym_factor r\"\n    using \\<open>consistent r\\<close> unfolding consistent_def by blast\n  hence \"x \\<noteq> z \\<Longrightarrow> (x, z) \\<in> r\"\n    unfolding asym_factor_def using \\<open>total r\\<close>\n    by (auto simp: total_on_def)\n  then show \"(x, z) \\<in> r\"\n    apply(cases \"x = z\")\n    using refl_onD[OF \\<open>refl r\\<close>] by blast+ \nqed\n\n\nlemma order_extension_if_consistent:\n  assumes \"consistent r\"\n  obtains r_ext where \"extends r_ext r\" \"total_preorder r_ext\"  \nproof -\n  from assms have extends: \"extends (r\\<^sup>*) r\"\n    unfolding extends_def consistent_def asym_factor_def\n    using rtranclD by (fastforce simp: Field_def)\n  have preorder: \"preorder (r\\<^sup>*)\"\n    unfolding preorder_on_def using refl_on_def trans_def by fastforce\n\n  from strict_extends_preorder_on[OF preorder] extends obtain r_ext where\n    \"total_preorder r_ext\" \"extends r_ext r\"\n    using transpE[OF transp_extends] unfolding strict_extends_def by blast\n  then show thesis using that by blast\nqed\n\nlemma consistent_if_extends_trans:\n  assumes \"extends r_ext r\" \"trans r_ext\"\n  shows \"consistent r\"\nproof(rule consistentI, standard)\n  fix x y assume *: \"(x, y) \\<in> r\\<^sup>+\" \"(y, x) \\<in> asym_factor r\"\n  with assms have \"(x, y) \\<in> r_ext\"\n    using trancl_subs_extends_if_trans[OF assms] by blast\n  moreover from * assms have \"(x, y) \\<notin> r_ext\"\n    unfolding extends_def asym_factor_def by auto\n  ultimately show False by blast\nqed\n\ntext \\<open>\n  With Theorem 2.6~\\<^cite>\\<open>\"Bossert:2010\"\\<close>, we show that \\<^term>\\<open>consistent\\<close> characterises the existence\n  of order extensions.\n\\<close>\ncorollary order_extension_iff_consistent:\n  \"(\\<exists>r_ext. extends r_ext r \\<and> total_preorder r_ext) \\<longleftrightarrow> consistent r\"\n  using order_extension_if_consistent consistent_if_extends_trans\n  by (metis total_preorder_onD(2))\n\n\ntext \\<open>\n  The following theorem corresponds to Theorem 2.7~\\<^cite>\\<open>\"Bossert:2010\"\\<close>.\n  Bossert and Suzumura claim that this theorem generalises Szpilrajn's theorem; however, we cannot\n  use the theorem to strictly extend a given order \\<^term>\\<open>Q\\<close>. Therefore, it is not strong enough to\n  extend a strict partial order to a strict linear order. It works for total preorders (called \n  orderings by Bossert and Suzumura). Unfortunately, we were not able to generalise the theorem\n  to allow for strict extensions.\n\\<close>\n\ntheorem general_order_extension_iff_consistent:\n  assumes \"\\<And>x y. \\<lbrakk> x \\<in> S; y \\<in> S; x \\<noteq> y \\<rbrakk> \\<Longrightarrow> (x, y) \\<notin> Q\\<^sup>+\"\n  assumes \"total_preorder_on S Ord\"\n  shows \"(\\<exists>Ext. extends Ext Q \\<and> total_preorder Ext \\<and> Restr Ext S = Ord)\n     \\<longleftrightarrow> consistent Q\" (is \"?ExExt \\<longleftrightarrow> _\")\nproof\n  assume \"?ExExt\"\n  then obtain Ext where\n    \"extends Ext Q\"\n    \"refl Ext\" \"trans Ext\" \"total Ext\"\n    \"Restr Ext S = Restr Ord S\"\n    using total_preorder_onD by fast\n  show \"consistent Q\"\n  proof(rule consistentI)\n    fix x y assume \"(x, y) \\<in> Q\\<^sup>+\"\n    with \\<open>extends Ext Q\\<close> \\<open>trans Ext\\<close> have \"(x, y) \\<in> Ext\"\n      unfolding extends_def by (metis trancl_id trancl_mono)\n    then have \"(y, x) \\<notin> asym_factor Ext\"\n      unfolding asym_factor_def by blast\n    with \\<open>extends Ext Q\\<close> show \"(y, x) \\<notin> asym_factor Q\"\n      unfolding extends_def asym_factor_def by blast\n  qed\nnext\n  assume \"consistent Q\"\n\n  define Q' where \"Q' \\<equiv> Q\\<^sup>* \\<union> Ord \\<union> Ord O Q\\<^sup>* \\<union> Q\\<^sup>* O Ord \\<union> (Q\\<^sup>* O Ord) O Q\\<^sup>*\"\n\n  have \"refl (Q\\<^sup>*)\" \"trans (Q\\<^sup>*)\" \"refl_on S Ord\" \"trans Ord\" \"total_on S Ord\"\n    using refl_rtrancl trans_rtrancl total_preorder_onD[OF \\<open>total_preorder_on S Ord\\<close>]\n    by - assumption\n\n  have preorder_Q': \"preorder Q'\"\n  proof\n    show \"refl Q'\"\n      unfolding Q'_def refl_on_def by auto\n\n    from \\<open>trans (Q\\<^sup>*)\\<close> \\<open>refl_on S Ord\\<close> \\<open>trans Ord\\<close> show \"trans Q'\"\n      unfolding Q'_def[simplified]\n      apply(safe intro!: transI)\n      unfolding relcomp.simps\n      by (metis assms(1) refl_on_domain rtranclD transD)+\n  qed\n\n  have \"consistent Q'\"\n    using consistent_if_preorder_on preorder_Q' by blast\n\n  have \"extends Q' Q\"\n  proof(rule extendsI)\n    have \"Q \\<subseteq> Restr (Q\\<^sup>*) (Field Q)\"\n      by (auto intro: FieldI1 FieldI2)\n    then show \"Q \\<subseteq> Q'\"\n      unfolding Q'_def by blast\n\n    from \\<open>consistent Q\\<close> have consistentD: \"(x, y) \\<in> Q\\<^sup>+ \\<Longrightarrow> (y, x) \\<in> Q \\<Longrightarrow> (x, y) \\<in> Q\" for x y\n      unfolding consistent_def asym_factor_def using rtranclD by fastforce\n    have refl_on_domainE: \"\\<lbrakk> (x, y) \\<in> Ord; x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\" for x y P\n      using refl_on_domain[OF \\<open>refl_on S Ord\\<close>] by blast\n\n    show \"asym_factor Q \\<subseteq> asym_factor Q'\"\n      unfolding Q'_def asym_factor_def Field_def\n      apply(safe)\n      using assms(1) consistentD refl_on_domainE\n      by (metis r_into_rtrancl rtranclD rtrancl_trancl_trancl)+\n  qed\n\n  with strict_extends_preorder_on[OF \\<open>preorder Q'\\<close>]\n  obtain Ext where Ext: \"extends Ext Q'\" \"extends Ext Q\" \"total_preorder Ext\"\n    unfolding strict_extends_def\n    by (metis transpE transp_extends)\n\n  have not_in_Q': \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> (x, y) \\<notin> Ord \\<Longrightarrow> (x, y) \\<notin> Q'\" for x y\n    using assms(1) unfolding Q'_def\n    apply(safe)\n    by (metis \\<open>refl_on S Ord\\<close> refl_on_def refl_on_domain rtranclD)+\n\n  have \"Restr Ext S = Ord\"\n  proof\n    from \\<open>extends Ext Q'\\<close> have \"Ord \\<subseteq> Ext\"\n      unfolding Q'_def extends_def by auto\n    with \\<open>refl_on S Ord\\<close> show \"Ord \\<subseteq> Restr Ext S\"\n      using refl_on_domain by fast\n  next\n    have \"(x, y) \\<in> Ord\" if \"x \\<in> S\" and \"y \\<in> S\" and \"(x, y) \\<in> Ext\" for x y\n    proof(rule ccontr)\n      assume \"(x, y) \\<notin> Ord\"\n      with that not_in_Q' have \"(x, y) \\<notin> Q'\"\n        by blast\n      with \\<open>refl_on S Ord\\<close> \\<open>total_on S Ord\\<close> \\<open>x \\<in> S\\<close> \\<open>y \\<in> S\\<close> \\<open>(x, y) \\<notin> Ord\\<close>\n      have \"(y, x) \\<in> Ord\"\n        unfolding refl_on_def total_on_def by fast\n      hence \"(y, x) \\<in> Q'\"\n        unfolding Q'_def by blast\n      with \\<open>(x, y) \\<notin> Q'\\<close> \\<open>(y, x) \\<in> Q'\\<close> \\<open>extends Ext Q'\\<close>\n      have \"(x, y) \\<notin> Ext\"\n        unfolding extends_def asym_factor_def by auto\n      with \\<open>(x, y) \\<in> Ext\\<close> show False by blast\n    qed\n    then show \"Restr Ext S \\<subseteq> Ord\"\n      by blast\n  qed\n\n  with Ext show \"?ExExt\" by blast\nqed\n\nsection \\<open>Strong consistency\\<close>\n\ntext \\<open>\n  We define a stronger version of \\<^term>\\<open>consistent\\<close> which requires that the relation does not\n  contain hidden preference cycles, i.e. if there is a preference cycle then all the elements\n  in the cycle should already be related (in both directions).\n  In contrast to consistency which characterises relations that can be extended, strong consistency\n  characterises relations that can be extended strictly (cf. \\<^term>\\<open>strict_extends\\<close>).\n\\<close>\n\ndefinition \"strongly_consistent r \\<equiv> sym_factor (r\\<^sup>+) \\<subseteq> sym_factor (r\\<^sup>=)\"\n\nlemma consistent_if_strongly_consistent: \"strongly_consistent r \\<Longrightarrow> consistent r\"\n  unfolding strongly_consistent_def consistent_def\n  by (auto simp: sym_factor_def asym_factor_def) \n\nlemma strongly_consistentI: \"sym_factor (r\\<^sup>+) \\<subseteq> sym_factor (r\\<^sup>=) \\<Longrightarrow> strongly_consistent r\"\n  unfolding strongly_consistent_def by blast\n\nlemma strongly_consistent_if_trans_strict_extension:\n  assumes \"strict_extends r_ext r\"\n  assumes \"trans r_ext\"\n  shows   \"strongly_consistent r\"\nproof(unfold strongly_consistent_def, standard)\n  fix x assume \"x \\<in> sym_factor (r\\<^sup>+)\"\n  then show \"x \\<in> sym_factor (r\\<^sup>=)\"\n    using assms trancl_subs_extends_if_trans[OF extends_if_strict_extends]\n    by (metis sym_factor_mono strict_extendsE subsetD sym_factor_reflc)\nqed\n\nlemma strict_order_extension_if_consistent:\n  assumes \"strongly_consistent r\"\n  obtains r_ext where \"strict_extends r_ext r\" \"total_preorder r_ext\" \nproof -\n  from assms have \"strict_extends (r\\<^sup>+) r\"\n    unfolding strongly_consistent_def strict_extends_def extends_def asym_factor_def sym_factor_def\n    by (auto simp: Field_def dest: tranclD)\n  moreover have \"strict_extends (r\\<^sup>*) (r\\<^sup>+)\"\n    unfolding strict_extends_def extends_def\n    by (auto simp: asym_factor_rtrancl sym_factor_def dest: rtranclD)\n  ultimately have extends: \"strict_extends (r\\<^sup>*) r\"\n    using transpE[OF transp_strict_extends] by blast\n\n  have \"preorder (r\\<^sup>*)\"\n    unfolding preorder_on_def using refl_on_def trans_def by fastforce\n  from strict_extends_preorder_on[OF this] extends obtain r_ext where\n    \"total_preorder r_ext\" \"strict_extends r_ext r\"\n    using transpE[OF transp_strict_extends] by blast\n  then show thesis using that by blast\nqed\n\n\nexperiment begin\n\ntext \\<open>We can instantiate the above theorem to get Szpilrajn's theorem.\\<close>\nlemma\n  assumes \"strict_partial_order r\"\n  shows \"\\<exists>r_ext. strict_linear_order r_ext \\<and> r \\<subseteq> r_ext\"\nproof -                  \n  from assms[unfolded strict_partial_order_def] have \"strongly_consistent r\" \"antisym r\"\n    unfolding strongly_consistent_def by (simp_all add: antisym_if_irrefl_trans)\n  from strict_order_extension_if_consistent[OF this(1)] obtain r_ext\n    where \"strict_extends r_ext r\" \"total_preorder r_ext\" \n    by blast\n  with assms[unfolded strict_partial_order_def] \n  have \"trans (r_ext - Id)\" \"irrefl (r_ext - Id)\" \"total (r_ext - Id)\" \"r \\<subseteq> (r_ext - Id)\"\n    using strict_extends_antisym[OF _ \\<open>antisym r\\<close>]\n    by (auto simp: irrefl_def elim: strict_extendsE intro: trans_diff_Id dest: total_preorder_onD)\n  then show ?thesis\n    unfolding strict_linear_order_on_def by blast\nqed\n\nend\n\n \n(*<*)\nend\n(*>*)\n\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Szpilrajn/Szpilrajn.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642945, "lm_q2_score": 0.8774767842777551, "lm_q1q2_score": 0.7785014417422885}}
{"text": "header {* Graphs *}\ntheory Graph\nimports Main\nbegin\ntext {*\n  This theory defines a notion of graphs. A graph is a record that\n  contains a set of nodes @{text \"V\"} and a set of labeled edges \n  @{text \"E \\<subseteq> V\\<times>W\\<times>V\"}, where @{text \"W\"} are the edge labels.\n*}\n\nsubsection {* Definitions *}\n  text {* A graph is represented by a record. *}\n  record ('v,'w) graph =\n    nodes :: \"'v set\"\n    edges :: \"('v \\<times> 'w \\<times> 'v) set\"\n\n  text {* In a valid graph, edges only go from nodes to nodes. *}\n  locale valid_graph = \n    fixes G :: \"('v,'w) graph\"\n    assumes E_valid: \"fst`edges G \\<subseteq> nodes G\"\n                     \"snd`snd`edges G \\<subseteq> nodes G\"\n  begin\n    abbreviation \"V \\<equiv> nodes G\"\n    abbreviation \"E \\<equiv> edges G\"\n\n    lemma E_validD: assumes \"(v,e,v')\\<in>E\"\n      shows \"v\\<in>V\" \"v'\\<in>V\"\n      apply -\n      apply (rule set_mp[OF E_valid(1)])\n      using assms apply force\n      apply (rule set_mp[OF E_valid(2)])\n      using assms apply force\n      done\n\n  end\n\n  subsection {* Basic operations on Graphs *}\n\n  text {* The empty graph. *}\n  definition empty where \n    \"empty \\<equiv> \\<lparr> nodes = {}, edges = {} \\<rparr>\"\n  text {* Adds a node to a graph. *}\n  definition add_node where \n    \"add_node v g \\<equiv> \\<lparr> nodes = insert v (nodes g), edges=edges g\\<rparr>\"\n  text {* Deletes a node from a graph. Also deletes all adjacent edges. *}\n  definition delete_node where \"delete_node v g \\<equiv> \\<lparr> \n    nodes = nodes g - {v},   \n    edges = edges g \\<inter> (-{v})\\<times>UNIV\\<times>(-{v})\n    \\<rparr>\"\n  text {* Adds an edge to a graph. *}\n  definition add_edge where \"add_edge v e v' g \\<equiv> \\<lparr>\n    nodes = {v,v'} \\<union> nodes g,\n    edges = insert (v,e,v') (edges g)\n    \\<rparr>\"\n  text {* Deletes an edge from a graph. *}\n  definition delete_edge where \"delete_edge v e v' g \\<equiv> \\<lparr>\n    nodes = nodes g, edges = edges g - {(v,e,v')} \\<rparr>\"\n  text {* Successors of a node. *}\n  definition succ :: \"('v,'w) graph \\<Rightarrow> 'v \\<Rightarrow> ('w\\<times>'v) set\"\n    where \"succ G v \\<equiv> {(w,v'). (v,w,v')\\<in>edges G}\"\n\n  text {* Now follow some simplification lemmas. *}\n  lemma empty_valid[simp]: \"valid_graph empty\"\n    unfolding empty_def by unfold_locales auto\n  lemma add_node_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (add_node v g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding add_node_def \n      by unfold_locales (auto dest: E_validD)\n  qed\n  lemma delete_node_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (delete_node v g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding delete_node_def \n      by unfold_locales (auto dest: E_validD)\n  qed\n  lemma add_edge_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (add_edge v e v' g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding add_edge_def\n      by unfold_locales (auto dest: E_validD)\n  qed\n  lemma delete_edge_valid[simp]: assumes \"valid_graph g\" \n    shows \"valid_graph (delete_edge v e v' g)\"\n  proof -\n    interpret valid_graph g by fact\n    show ?thesis\n      unfolding delete_edge_def\n      by unfold_locales (auto dest: E_validD)\n  qed\n\n  lemma succ_finite[simp, intro]: \"finite (edges G) \\<Longrightarrow> finite (succ G v)\"\n    unfolding succ_def\n    by (rule finite_subset[where B=\"snd`edges G\"]) force+\n\n  lemma nodes_empty[simp]: \"nodes empty = {}\" unfolding empty_def by simp\n  lemma edges_empty[simp]: \"edges empty = {}\" unfolding empty_def by simp\n  lemma succ_empty[simp]: \"succ empty v = {}\" unfolding empty_def succ_def by auto\n\n  lemma nodes_add_node[simp]: \"nodes (add_node v g) = insert v (nodes g)\"\n    by (simp add: add_node_def)\n  lemma nodes_add_edge[simp]: \n    \"nodes (add_edge v e v' g) = insert v (insert v' (nodes g))\"\n    by (simp add: add_edge_def)\n  \n\n  lemma (in valid_graph) succ_subset: \"succ G v \\<subseteq> UNIV\\<times>V\"\n    unfolding succ_def using E_valid\n    by (force)\n\nsubsection {* Paths *}\n  text {* A path is represented by a list of adjacent edges. *}\n  type_synonym ('v,'w) path = \"('v\\<times>'w\\<times>'v) list\"\n\n  context valid_graph\n  begin\n    text {* The following predicate describes a valid path: *}\n    fun is_path :: \"'v \\<Rightarrow> ('v,'w) path \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n      \"is_path v [] v' \\<longleftrightarrow> v=v' \\<and> v'\\<in>V\" |\n      \"is_path v ((v1,w,v2)#p) v' \\<longleftrightarrow> v=v1 \\<and> (v1,w,v2)\\<in>E \\<and> is_path v2 p v'\"\n  \n    lemma is_path_simps[simp, intro!]:\n      \"is_path v [] v \\<longleftrightarrow> v\\<in>V\"\n      \"is_path v [(v,w,v')] v' \\<longleftrightarrow> (v,w,v')\\<in>E\"\n      by (auto dest: E_validD)\n    \n    lemma is_path_memb[simp]:\n      \"is_path v p v' \\<Longrightarrow> v\\<in>V \\<and> v'\\<in>V\"\n      apply (induct p arbitrary: v) \n      apply (auto dest: E_validD)\n      done\n\n    lemma is_path_split:\n      \"is_path v (p1@p2) v' \\<longleftrightarrow> (\\<exists>u. is_path v p1 u \\<and> is_path u p2 v')\"\n      by (induct p1 arbitrary: v) auto\n\n    lemma is_path_split'[simp]: \n      \"is_path v (p1@(u,w,u')#p2) v' \n        \\<longleftrightarrow> is_path v p1 u \\<and> (u,w,u')\\<in>E \\<and> is_path u' p2 v'\"\n      by (auto simp add: is_path_split)\n  end\n\n  text {* Set of intermediate vertices of a path. These are all vertices but\n    the last one. Note that, if the last vertex also occurs earlier on the path,\n    it is contained in @{text \"int_vertices\"}. *}\n  definition int_vertices :: \"('v,'w) path \\<Rightarrow> 'v set\" where\n    \"int_vertices p \\<equiv> set (map fst p)\"\n\n  lemma int_vertices_simps[simp]:\n    \"int_vertices [] = {}\"\n    \"int_vertices (vv#p) = insert (fst vv) (int_vertices p)\"\n    \"int_vertices (p1@p2) = int_vertices p1 \\<union> int_vertices p2\"\n    by (auto simp add: int_vertices_def)\n  \n  lemma (in valid_graph) int_vertices_subset: \n    \"is_path v p v' \\<Longrightarrow> int_vertices p \\<subseteq> V\"\n    apply (induct p arbitrary: v)\n    apply (simp) \n    apply (force dest: E_validD)\n    done\n\n  lemma int_vertices_empty[simp]: \"int_vertices p = {} \\<longleftrightarrow> p=[]\"\n    by (cases p) auto\n\nsubsubsection {* Splitting Paths *}\n  text {*Split a path at the point where it first leaves the set @{text W}: *}\n  lemma (in valid_graph) path_split_set:\n    assumes \"is_path v p v'\" and \"v\\<in>W\" and \"v'\\<notin>W\"\n    obtains p1 p2 u w u' where\n    \"p=p1@(u,w,u')#p2\" and\n    \"int_vertices p1 \\<subseteq> W\" and \"u\\<in>W\" and \"u'\\<notin>W\"\n    using assms\n  proof (induct p arbitrary: v thesis)\n    case Nil thus ?case by auto\n  next\n    case (Cons vv p)\n    note [simp, intro!] = `v\\<in>W` `v'\\<notin>W`\n    from Cons.prems obtain w u' where \n      [simp]: \"vv=(v,w,u')\" and\n        REST: \"is_path u' p v'\"\n      by (cases vv) auto\n    \n    txt {* Distinguish wether the second node @{text u'} of the path is \n      in @{text W}. If yes, the proposition follows by the \n      induction hypothesis, otherwise it is straightforward, as\n      the split takes place at the first edge of the path. *}\n    {\n      assume A [simp, intro!]: \"u'\\<in>W\"\n      from Cons.hyps[OF _ REST] obtain p1 uu ww uu' p2 where\n        \"p=p1@(uu,ww,uu')#p2\" \"int_vertices p1 \\<subseteq> W\" \"uu \\<in> W\" \"uu' \\<notin> W\"\n        by blast\n      with Cons.prems(1)[of \"vv#p1\" uu ww uu' p2] have thesis by auto\n    } moreover {\n      assume \"u'\\<notin>W\"\n      with Cons.prems(1)[of \"[]\" v w u' p] have thesis by auto\n    } ultimately show thesis by blast\n  qed\n  \n  text {*Split a path at the point where it first enters the set @{text W}:*}\n  lemma (in valid_graph) path_split_set':\n    assumes \"is_path v p v'\" and \"v'\\<in>W\"\n    obtains p1 p2 u where\n    \"p=p1@p2\" and\n    \"is_path v p1 u\" and\n    \"is_path u p2 v'\" and\n    \"int_vertices p1 \\<subseteq> -W\" and \"u\\<in>W\"\n    using assms\n  proof (cases \"v\\<in>W\")\n    case True with that[of \"[]\" p] assms show ?thesis\n      by auto\n  next\n    case False with assms that show ?thesis\n    proof (induct p arbitrary: v thesis)\n      case Nil thus ?case by auto\n    next\n      case (Cons vv p)\n      note [simp, intro!] = `v'\\<in>W` `v\\<notin>W`\n      from Cons.prems obtain w u' where \n        [simp]: \"vv=(v,w,u')\" and [simp]: \"(v,w,u')\\<in>E\" and\n          REST: \"is_path u' p v'\"\n        by (cases vv) auto\n    \n      txt {* Distinguish wether the second node @{text u'} of the path is \n        in @{text W}. If yes, the proposition is straightforward, otherwise,\n        it follows by the induction hypothesis.\n        *}\n      {\n        assume A [simp, intro!]: \"u'\\<in>W\"\n        from Cons.prems(3)[of \"[vv]\" p u'] REST have ?case by auto\n      } moreover {\n        assume [simp, intro!]: \"u'\\<notin>W\"\n        from Cons.hyps[OF REST] obtain p1 p2 u'' where\n          [simp]: \"p=p1@p2\" and \n            \"is_path u' p1 u''\" and \n            \"is_path u'' p2 v'\" and\n            \"int_vertices p1 \\<subseteq> -W\" and\n            \"u''\\<in>W\" by blast\n        with Cons.prems(3)[of \"vv#p1\"] have ?case by auto\n      } ultimately show ?case by blast\n    qed\n  qed\n\n  text {* Split a path at the point where a given vertex is first visited: *}\n  lemma (in valid_graph) path_split_vertex:\n    assumes \"is_path v p v'\" and \"u\\<in>int_vertices p\"\n    obtains p1 p2 where\n    \"p=p1@p2\" and\n    \"is_path v p1 u\" and\n    \"u \\<notin> int_vertices p1\"\n    using assms\n  proof (induct p arbitrary: v thesis)\n    case Nil thus ?case by auto\n  next\n    case (Cons vv p)\n    from Cons.prems obtain w u' where \n      [simp]: \"vv=(v,w,u')\" \"v\\<in>V\" \"(v,w,u')\\<in>E\" and\n        REST: \"is_path u' p v'\"\n      by (cases vv) auto\n    \n    {\n      assume \"u=v\"\n      with Cons.prems(1)[of \"[]\" \"vv#p\"] have thesis by auto\n    } moreover {\n      assume [simp]: \"u\\<noteq>v\"\n      with Cons.hyps(1)[OF _ REST] Cons.prems(3) obtain p1 p2 where\n        \"p=p1@p2\" \"is_path u' p1 u\" \"u\\<notin>int_vertices p1\"\n        by auto\n      with Cons.prems(1)[of \"vv#p1\" p2] have thesis\n        by auto\n    } ultimately show ?case by blast\n  qed\n\nsubsection {* Weighted Graphs *}\n  locale valid_mgraph = valid_graph G for G::\"('v,'w::monoid_add) graph\"\n\n  definition path_weight :: \"('v,'w::monoid_add) path \\<Rightarrow> 'w\"\n    where \"path_weight p \\<equiv> listsum (map (fst \\<circ> snd) p)\"\n\n  (* \n    lemma path_weight_alt: \"path_weight p \\<equiv> listsum (map (fst \\<circ> snd) p)\"\n    unfolding path_weight_def foldl_conv_fold\n    by (simp add: listsum_foldl)\n  *)\n\n  lemma path_weight_split[simp]:\n    \"(path_weight (p1@p2)::'w::monoid_add) = path_weight p1 + path_weight p2\"\n    unfolding path_weight_def\n    by (auto)\n\n  lemma path_weight_empty[simp]: \"path_weight [] = 0\"\n    unfolding path_weight_def\n    by auto\n\n  lemma path_weight_cons[simp]:\n    \"(path_weight (e#p)::'w::monoid_add) = fst (snd e) + path_weight p\"\n    unfolding path_weight_def\n    by (auto)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Dijkstra_Shortest_Path/Graph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.7785014253633}}
{"text": "(*  Title:      HOL/Algebra/Bij.thy\n    Author:     Florian Kammueller, with new proofs by L C Paulson\n*)\n\ntheory Bij\nimports Group\nbegin\n\nsection \\<open>Bijections of a Set, Permutation and Automorphism Groups\\<close>\n\ndefinition\n  Bij :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n    \\<comment> \\<open>Only extensional functions, since otherwise we get too many.\\<close>\n   where \"Bij S = extensional S \\<inter> {f. bij_betw f S S}\"\n\ndefinition\n  BijGroup :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"BijGroup S =\n    \\<lparr>carrier = Bij S,\n     mult = \\<lambda>g \\<in> Bij S. \\<lambda>f \\<in> Bij S. compose S g f,\n     one = \\<lambda>x \\<in> S. x\\<rparr>\"\n\n\ndeclare Id_compose [simp] compose_Id [simp]\n\nlemma Bij_imp_extensional: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> extensional S\"\n  by (simp add: Bij_def)\n\nlemma Bij_imp_funcset: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> S \\<rightarrow> S\"\n  by (auto simp add: Bij_def bij_betw_imp_funcset)\n\n\nsubsection \\<open>Bijections Form a Group\\<close>\n\nlemma restrict_inv_into_Bij: \"f \\<in> Bij S \\<Longrightarrow> (\\<lambda>x \\<in> S. (inv_into S f) x) \\<in> Bij S\"\n  by (simp add: Bij_def bij_betw_inv_into)\n\nlemma id_Bij: \"(\\<lambda>x\\<in>S. x) \\<in> Bij S \"\n  by (auto simp add: Bij_def bij_betw_def inj_on_def)\n\nlemma compose_Bij: \"\\<lbrakk>x \\<in> Bij S; y \\<in> Bij S\\<rbrakk> \\<Longrightarrow> compose S x y \\<in> Bij S\"\n  by (auto simp add: Bij_def bij_betw_compose) \n\nlemma Bij_compose_restrict_eq:\n     \"f \\<in> Bij S \\<Longrightarrow> compose S (restrict (inv_into S f) S) f = (\\<lambda>x\\<in>S. x)\"\n  by (simp add: Bij_def compose_inv_into_id)\n\ntheorem group_BijGroup: \"group (BijGroup S)\"\n  apply (simp add: BijGroup_def)\n  apply (rule groupI)\n      apply (auto simp: compose_Bij id_Bij Bij_imp_funcset Bij_imp_extensional compose_assoc [symmetric])\n  apply (blast intro: Bij_compose_restrict_eq restrict_inv_into_Bij)\n  done\n\n\nsubsection\\<open>Automorphisms Form a Group\\<close>\n\nlemma Bij_inv_into_mem: \"\\<lbrakk> f \\<in> Bij S;  x \\<in> S\\<rbrakk> \\<Longrightarrow> inv_into S f x \\<in> S\"\nby (simp add: Bij_def bij_betw_def inv_into_into)\n\nlemma Bij_inv_into_lemma:\n  assumes eq: \"\\<And>x y. \\<lbrakk>x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> h(g x y) = g (h x) (h y)\"\n      and hg: \"h \\<in> Bij S\" \"g \\<in> S \\<rightarrow> S \\<rightarrow> S\" and \"x \\<in> S\" \"y \\<in> S\"\n  shows \"inv_into S h (g x y) = g (inv_into S h x) (inv_into S h y)\"\nproof -\n  have \"h ` S = S\"\n    by (metis (no_types) Bij_def Int_iff assms(2) bij_betw_def mem_Collect_eq)\n  with \\<open>x \\<in> S\\<close> \\<open>y \\<in> S\\<close> have \"\\<exists>x'\\<in>S. \\<exists>y'\\<in>S. x = h x' \\<and> y = h y'\"\n    by auto\n  then show ?thesis\n    using assms\n    by (auto simp add: Bij_def bij_betw_def eq [symmetric] inv_f_f funcset_mem [THEN funcset_mem])\nqed\n\n\ndefinition\n  auto :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n  where \"auto G = hom G G \\<inter> Bij (carrier G)\"\n\ndefinition\n  AutoGroup :: \"('a, 'c) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"AutoGroup G = BijGroup (carrier G) \\<lparr>carrier := auto G\\<rparr>\"\n\nlemma (in group) id_in_auto: \"(\\<lambda>x \\<in> carrier G. x) \\<in> auto G\"\n  by (simp add: auto_def hom_def restrictI group.axioms id_Bij)\n\nlemma (in group) mult_funcset: \"mult G \\<in> carrier G \\<rightarrow> carrier G \\<rightarrow> carrier G\"\n  by (simp add:  Pi_I group.axioms)\n\nlemma (in group) restrict_inv_into_hom:\n      \"\\<lbrakk>h \\<in> hom G G; h \\<in> Bij (carrier G)\\<rbrakk>\n       \\<Longrightarrow> restrict (inv_into (carrier G) h) (carrier G) \\<in> hom G G\"\n  by (simp add: hom_def Bij_inv_into_mem restrictI mult_funcset\n                group.axioms Bij_inv_into_lemma)\n\nlemma inv_BijGroup:\n     \"f \\<in> Bij S \\<Longrightarrow> m_inv (BijGroup S) f = (\\<lambda>x \\<in> S. (inv_into S f) x)\"\napply (rule group.inv_equality [OF group_BijGroup])\napply (simp_all add:BijGroup_def restrict_inv_into_Bij Bij_compose_restrict_eq)\ndone\n\nlemma (in group) subgroup_auto:\n      \"subgroup (auto G) (BijGroup (carrier G))\"\nproof (rule subgroup.intro)\n  show \"auto G \\<subseteq> carrier (BijGroup (carrier G))\"\n    by (force simp add: auto_def BijGroup_def)\nnext\n  fix x y\n  assume \"x \\<in> auto G\" \"y \\<in> auto G\" \n  thus \"x \\<otimes>\\<^bsub>BijGroup (carrier G)\\<^esub> y \\<in> auto G\"\n    by (force simp add: BijGroup_def is_group auto_def Bij_imp_funcset \n                        group.hom_compose compose_Bij)\nnext\n  show \"\\<one>\\<^bsub>BijGroup (carrier G)\\<^esub> \\<in> auto G\" by (simp add:  BijGroup_def id_in_auto)\nnext\n  fix x \n  assume \"x \\<in> auto G\" \n  thus \"inv\\<^bsub>BijGroup (carrier G)\\<^esub> x \\<in> auto G\"\n    by (simp del: restrict_apply\n        add: inv_BijGroup auto_def restrict_inv_into_Bij restrict_inv_into_hom)\nqed\n\ntheorem (in group) AutoGroup: \"group (AutoGroup G)\"\nby (simp add: AutoGroup_def subgroup.subgroup_is_group subgroup_auto \n              group_BijGroup)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Algebra/Bij.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7784092682072907}}
{"text": "section\\<open>Sum of divisors function\\<close>\n\ntheory Sigma\nimports PerfectBasics \"HOL-Library.Infinite_Set\"\nbegin\n\ndefinition divisors :: \"nat => nat set\" where\n    \"divisors (m::nat) == {n . n dvd m}\"\n\ndefinition sigma :: \"nat => nat\" where\n    \"sigma m == \\<Sum> n | n dvd m . n\"\n\nlemma sigma_divisors: \"sigma(n) = \\<Sum> (divisors(n))\"\nby (auto simp: sigma_def divisors_def)\n\nlemma divisors_eq_dvd[iff]: \"(a:divisors(n)) = (a dvd n)\"\nby(simp add: divisors_def)\n\nlemma mult_divisors: \"(a::nat)*b=c==>a: divisors c\"\nby (unfold divisors_def dvd_def,blast)\nlemma mult_divisors2: \"(a::nat)*b=c==>b: divisors c\"\nby (unfold divisors_def dvd_def,auto)\n\nlemma divisorsfinite[simp]:\n   assumes \"n>0\"\n   shows \"finite (divisors n)\"\nproof -\n  from assms have  \"divisors n = {m . m dvd n & m <= n}\"\n    by (auto simp only:divisors_def dvd_imp_le)\n  hence \"divisors n <= {m . m<=n}\" by auto\n  thus \"finite (divisors n)\"\n    by (metis finite_Collect_le_nat finite_subset) \nqed\n\nlemma divs_of_zero_UNIV[simp]: \"divisors(0) = UNIV\"\nby(auto simp add: divisors_def)\n\nlemma sigma0[simp]: \"sigma(0) = 0\"\nby (simp add: sigma_def)\nlemma sigma1[simp]: \"sigma(1) = 1\"\nby (simp add: sigma_def)\n\nlemma prime_divisors: \"prime (p::nat) \\<longleftrightarrow> divisors p = {1,p} & p>1\"\n  by (auto simp add: divisors_def prime_nat_iff)\n\nlemma prime_imp_sigma: \"prime (p::nat) ==> sigma(p) = p+1\"\nproof -\n  assume \"prime (p::nat)\"\n  hence \"p>1 \\<and> divisors(p) = {1,p}\" by (simp add: prime_divisors)\n  hence \"p>1 \\<and> sigma(p) = \\<Sum> {1,p}\" by (auto simp only: sigma_divisors divisors_def)\n  thus \"sigma(p) = p+1\" by simp\nqed\n\nlemma sigma_third_divisor:\n  assumes  \"1 < a\" \"a < n\" \"a : divisors n\"\n  shows \"1+a+n <= sigma(n)\"\nproof -\n  from assms have \"finite {1,a,n} & finite (divisors n) & {1,a,n} <= divisors n\" by auto\n  hence \"\\<Sum> {1,a,n} <= \\<Sum> (divisors n)\" by (simp only: sum_mono2)\n  hence \"\\<Sum> {1,a,n} <= sigma n\" by (simp add: sigma_divisors)\n  with assms show \"?thesis\" by auto\nqed\n\nlemma sigma_imp_divisors: \"sigma(n)=n+1 ==> n>1 & divisors n = {n,1}\"\nproof\n  assume ass:\"sigma(n)=n+1\"\n  hence \"n\\<noteq>0 & n\\<noteq>1\"\n    by (metis Suc_eq_plus1 n_not_Suc_n sigma0 sigma1)\n  thus conc1: \"n>1\" by simp\n\n  show \"divisors n = {n,1}\" (*TODO: use sigma_third_divisor *)\n  proof (rule ccontr)\n    assume \"divisors n \\<noteq> {n,1}\"\n    with conc1 have \"divisors n \\<noteq> {n,1} & 1<n\" by auto\n    moreover\n    from ass conc1 have \"1 : divisors(n) & n : divisors n & ~0 : divisors n\"\n      by (simp add: dvd_def divisors_def)\n    ultimately\n    have  \"(\\<exists>a. a\\<noteq>n & a\\<noteq>1 & 1<n & a : divisors n) & 0 ~: divisors n\" by auto\n    hence \"(\\<exists>a. a\\<noteq>n & a\\<noteq>1 & 1<n & a\\<noteq>0 & a : divisors n)\" by metis\n    hence \"\\<exists>a . a\\<noteq>n & a\\<noteq>1 & 1\\<noteq>n & a\\<noteq>0 & finite {1,a,n} & finite (divisors n) & {1,a,n} <= divisors n\" by auto\n    hence \"\\<exists>a. a\\<noteq>n & a\\<noteq>1 & 1\\<noteq>n & a\\<noteq>0 & \\<Sum> {1,a,n} <= sigma n\"\n      by (metis sum_mono2_nat sigma_divisors)\n    hence \"\\<exists>a. a\\<noteq>0 & (1+a+n) <= sigma n\" by auto\n    hence \"1+n<sigma n\" by auto (*TODO: this step can be deleted, should i?*)\n    with ass show \"False\" by auto\n  qed\nqed\n\n\nlemma sigma_imp_prime: \"sigma(n)=n+1 ==> prime n\"\nproof -\n  assume ass: \"sigma(n)=n+1\"\n  hence \"n>1 & divisors(n)={1,n}\" by (metis insert_commute sigma_imp_divisors)\n  thus \"prime n\" by (simp add: prime_divisors)\nqed\n\nlemma pr_pow_div_eq_sm_pr_pow: \n  fixes p::nat\n  assumes prime: \"prime p\"\n  shows \"{d . d dvd p^n} = {p^f| f . f<=n}\"\nproof\n  show \"{p^f | f . f<=n} <= { d .  d dvd p^n}\"\n  proof\n    fix x\n    assume \"x: {p ^ f | f . f <= n}\"\n    hence \"\\<exists>i . x = p^i & i<= n\"   by auto\n    with prime have  \"x dvd p^n\"\n      by (metis le_imp_power_dvd) \n    thus \"x : { d . d dvd p^n}\" by auto\n  qed\n  next\n  show \"{d. d dvd p ^ n} <= {p ^ f | f . f <= n}\"\n  proof\n    fix x\n    assume \"x : {d . d dvd p^n}\"\n    hence \"x dvd p^n\" by auto\n    with prime obtain \"i\" where  \"i <= n & x = p^i\" using prime_dvd_power_nat_iff prime_dvd_power_nat\n      by (auto simp only: divides_primepow_nat)\n    hence \"x = p^i & i <=n\" by auto\n    thus \"x : { p^f | f . f<=n }\" by auto\n  qed\nqed\n\nlemma rewrite_sum_of_powers:\nassumes p: \"(p::nat)>1\"\nshows \"(\\<Sum> {p^m | m . m<=(n::nat)}) = (\\<Sum> i = 0 .. n . p^i)\" (is \"?l = ?r\")\nproof -\n  have \"?l = sum (%x. x) {((^) p) m |m . m<= n}\" by auto\n  also have \"... = sum (%x. x) (((^) p)`{m . m<= n})\"\n    by (simp add: setcompr_eq_image)\n  moreover with p have \"inj_on ((^) p) {m . m<=n}\"\n    by (simp add: inj_on_def)\n  ultimately have \"?l = sum ((^) p) {m . m<=n}\"\n    by (simp add: sum.reindex)\n  moreover have \"{m::nat . m<=n} = {0..n}\" by auto\n  ultimately show \"?l = (\\<Sum> i = 0 .. n . p^i)\" by auto\nqed\n\ntheorem sigma_primepower:\n  \"prime p ==> (p - 1)*sigma(p^(e::nat)) = (p^(e+1) - 1)\"\nproof -\n  assume \"prime p\"\n  hence \"sigma(p^(e::nat)) = (\\<Sum>i=0 .. e . p^i)\"\n    by (simp add: pr_pow_div_eq_sm_pr_pow sigma_def rewrite_sum_of_powers prime_nat_iff)\n  thus \"(p - 1)*sigma(p^e)=p^(e+1) - 1\" by (simp only: simplify_sum_of_powers)\nqed\n\nlemma sigma_prime_power_two: \"sigma(2^(n::nat)) = 2^(n+1) - 1\"\nproof -\n  have \"(2 - 1)*sigma(2^(n::nat))=2^(n+1) - 1\"\n    by (auto simp only: sigma_primepower two_is_prime_nat)\n  thus ?thesis by simp\nqed\n\n\n\ndeclare [[simproc add: finite_Collect]]\n\nlemma rewrite_for_sigma_semimultiplicative:\nfixes p::nat\nassumes \"prime p\"\nshows \"{p^f*b |f b. f<=n & b dvd m} = {a*b |a b. a dvd (p^n) & b dvd m}\"\nproof\n  show \"{p^f * b |f b. f <= n & b dvd m} <= {a*b |a b. a dvd p ^ n & b dvd m}\"\n  proof\n    fix x\n    assume \"x : {p ^ f * b | f b. f <= n & b dvd m}\"\n    then obtain b f where \"x = p^f*b & f <= n & b dvd m\" by auto\n    with \\<open>prime p\\<close> show \"x : {a * b |a b. a dvd p ^ n & b dvd m}\"\n      by (auto simp add: divides_primepow_nat)\n  qed\nnext\n  show \"{a*b |a b. a dvd p ^ n & b dvd m} <= {p^f * b |f b. f <= n & b dvd m}\"\n    using \\<open>prime p\\<close> by auto (metis assms divides_primepow_nat)\nqed\n\n\nlemma div_decomp_comp:\n  fixes a::nat\n  shows \"coprime m n \\<Longrightarrow> a dvd m*n \\<longleftrightarrow> (\\<exists>b c. a = b * c & b dvd m & c dvd n)\"\nby (auto simp only: division_decomp mult_dvd_mono)\n\ntheorem sigma_semimultiplicative:\n  assumes p: \"prime p\" and cop: \"coprime p m\"\n  shows \"sigma (p^n) * sigma m = sigma (p^n * m)\" (is \"?l = ?r\")\nproof -\n  from cop have cop2: \"coprime (p^n) m\"\n    by simp\n  have \"?l = (\\<Sum> {a . a dvd p^n})*(\\<Sum> {b . b dvd m})\" by (simp add: sigma_def)\n  also from p have \"... = (\\<Sum> {p^f| f . f<=n})*(\\<Sum> {b . b dvd m})\"\n    by (simp add: pr_pow_div_eq_sm_pr_pow)\n  also from cop  have \"... = (\\<Sum> {p^f*b| f b . f<=n & b dvd m})\"\n    by (auto simp add: prodsums_eq_sumprods prime_nat_iff)\n  also have \"... = (\\<Sum> {a*b| a b . a dvd (p^n) & b dvd m})\"\n    by (simp add: p rewrite_for_sigma_semimultiplicative)\n  finally have \"?l = \\<Sum>{c. c dvd (p^n*m)}\" by (subst div_decomp_comp[OF cop2])\n  thus \"?l = sigma (p^n*m)\" by (auto simp add: sigma_def)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Perfect-Number-Thm/Sigma.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8519527963298946, "lm_q1q2_score": 0.7784092650581697}}
{"text": "header {* \\isaheader{Operations on sorted Lists} *}\ntheory Sorted_List_Operations\nimports Main \"../../Automatic_Refinement/Lib/Misc\"\nbegin \n\nfun inter_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"inter_sorted [] l2 = []\"\n | \"inter_sorted l1 [] = []\"\n | \"inter_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then (inter_sorted l1 (x2 # l2)) else \n     (if (x1 = x2) then x1 # (inter_sorted l1 l2) else inter_sorted (x1 # l1) l2))\"\n\nlemma inter_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"distinct (inter_sorted l1 l2) \\<and> sorted (inter_sorted l1 l2) \\<and> \n       set (inter_sorted l1 l2) = set l1 \\<inter> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply (auto simp add: sorted_Cons Ball_def)\n        apply (metis linorder_not_le)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis by (simp add: x1_eq_x2 sorted_Cons Ball_def)\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n        show ?thesis \n          apply (auto simp add: x2_less_x1 sorted_Cons Ball_def)\n          apply (metis linorder_not_le x2_less_x1)\n        done\n      qed\n    qed\n  qed\nqed\n\nfun diff_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"diff_sorted [] l2 = []\"\n | \"diff_sorted l1 [] = l1\"\n | \"diff_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then x1 # (diff_sorted l1 (x2 # l2)) else \n     (if (x1 = x2) then (diff_sorted l1 l2) else diff_sorted (x1 # l1) l2))\"\n\nlemma diff_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"distinct (diff_sorted l1 l2) \\<and> sorted (diff_sorted l1 l2) \\<and> \n       set (diff_sorted l1 l2) = set l1 - set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply simp\n        apply (simp add: sorted_Cons Ball_def set_eq_iff)\n        apply (metis linorder_not_le order_less_imp_not_eq2)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis by (simp add: x1_eq_x2 sorted_Cons Ball_def)\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from x2_less_x1 x1_le have x2_nin_l1: \"x2 \\<notin> set l1\"\n           by (metis linorder_not_less)\n\n        from ind_hyp_l2 x1_le x2_nin_l1\n        show ?thesis \n          apply (simp add: x2_less_x1 x1_neq_x2 x2_le_x1 x1_nin_l1 sorted_Cons Ball_def set_eq_iff)\n          apply (metis x1_neq_x2)\n        done\n      qed\n    qed\n  qed\nqed\n\nfun subset_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n   \"subset_sorted [] l2 = True\"\n | \"subset_sorted (x1 # l1) [] = False\"\n | \"subset_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then False else \n     (if (x1 = x2) then (subset_sorted l1 l2) else subset_sorted (x1 # l1) l2))\"\n\nlemma subset_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"subset_sorted l1 l2 \\<longleftrightarrow> set l1 \\<subseteq> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply (auto simp add: sorted_Cons Ball_def)\n        apply (metis linorder_not_le)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis \n          apply (simp add: subset_iff x1_eq_x2 sorted_Cons Ball_def)\n          apply metis\n        done\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n        show ?thesis \n          apply (simp add: subset_iff x2_less_x1 sorted_Cons Ball_def)\n          apply (metis linorder_not_le x2_less_x1)\n        done\n      qed\n    qed\n  qed\nqed\n\nlemma set_eq_sorted_correct :\n  assumes l1_OK: \"distinct l1 \\<and> sorted l1\"\n  assumes l2_OK: \"distinct l2 \\<and> sorted l2\"\n  shows \"l1 = l2 \\<longleftrightarrow> set l1 = set l2\"\n  using assms\nproof -\n  have l12_eq: \"l1 = l2 \\<longleftrightarrow> subset_sorted l1 l2 \\<and> subset_sorted l2 l1\"\n  proof (induct l1 arbitrary: l2)\n    case Nil thus ?case by (cases l2) auto\n  next\n    case (Cons x1 l1')\n    note ind_hyp = Cons(1)\n\n    show ?case\n    proof (cases l2)\n      case Nil thus ?thesis by simp\n    next\n      case (Cons x2 l2')\n      thus ?thesis by (simp add: ind_hyp)\n    qed\n  qed\n  also have \"\\<dots> \\<longleftrightarrow> ((set l1 \\<subseteq> set l2) \\<and> (set l2 \\<subseteq> set l1))\"\n    using subset_sorted_correct[OF l1_OK l2_OK] subset_sorted_correct[OF l2_OK l1_OK]\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> set l1 = set l2\" by auto\n  finally show ?thesis .\nqed\n\nfun memb_sorted where\n   \"memb_sorted [] x = False\"\n | \"memb_sorted (y # xs) x =\n    (if (y < x) then memb_sorted xs x else (x = y))\"\n\nlemma memb_sorted_correct :\n  \"sorted xs \\<Longrightarrow> memb_sorted xs x \\<longleftrightarrow> x \\<in> set xs\"\nby (induct xs) (auto simp add: sorted_Cons Ball_def)\n\n\nfun insertion_sort where\n   \"insertion_sort x [] = [x]\"\n | \"insertion_sort x (y # xs) =\n    (if (y < x) then y # insertion_sort x xs else \n     (if (x = y) then y # xs else x # y # xs))\"\n\nlemma insertion_sort_correct :\n  \"sorted xs \\<Longrightarrow> distinct xs \\<Longrightarrow>\n   distinct (insertion_sort x xs) \\<and> \n   sorted (insertion_sort x xs) \\<and>\n   set (insertion_sort x xs) = set (x # xs)\"\nby (induct xs) (auto simp add: sorted_Cons Ball_def)\n\nfun delete_sorted where\n   \"delete_sorted x [] = []\"\n | \"delete_sorted x (y # xs) =\n    (if (y < x) then y # delete_sorted x xs else \n     (if (x = y) then xs else y # xs))\"\n\nlemma delete_sorted_correct :\n  \"sorted xs \\<Longrightarrow> distinct xs \\<Longrightarrow>\n   distinct (delete_sorted x xs) \\<and> \n   sorted (delete_sorted x xs) \\<and>\n   set (delete_sorted x xs) = set xs - {x}\"\napply (induct xs) \napply simp\napply (simp add: sorted_Cons Ball_def set_eq_iff)\napply (metis order_less_le)\ndone\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Collections/Lib/Sorted_List_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8887587920192298, "lm_q1q2_score": 0.7783633945259316}}
{"text": "theory Probability_Theory \n  imports \"HOL-Analysis.Sigma_Algebra\" \"HOL-Analysis.Infinite_Sum\" \"HOL-Library.Liminf_Limsup\"\nbegin\n\nchapter \"Basics from Measure Theory\"\n\nsection \"Auxiliary lemmas\"\n\n(* Every non-empty set of natural numbers has a least element. *)\nlemma min_nat_elem: \n  assumes non_empty: \"\\<exists>n::nat. n \\<in> S\" \n  shows \"\\<exists>n. n \\<in> S \\<and> (\\<forall>m\\<in>S. m \\<ge> n)\" \nproof -\n  obtain P where P_fun: \"P = (\\<lambda>n. n \\<in> S)\"\n    by simp\n  have \"(\\<exists>n. P n) = (\\<exists>n. P n \\<and> (\\<forall>m<n. \\<not> P m))\"\n    using exists_least_iff by auto\n  thus ?thesis using P_fun non_empty\n    using leI by auto\nqed \n\n(* If the intersection of the family of sets fulfilling a property fulfils that property, it is the\n   smallest set that does so. *)\nlemma inter_is_Least_if_P:\n  assumes P_inter: \"P (\\<Inter>S\\<in>{S. P S}. S)\"\n  shows \"(\\<Inter>S\\<in>{S. P S}. S) = Least P\"\nproof -  \n  let ?U = \"(\\<Inter>S\\<in>{S. P S}. S)\"\n  have \"\\<forall>S. P S \\<longrightarrow> ?U \\<subseteq> S\"\n    by auto \n  moreover have \"P ?U\"\n    using P_inter by auto\n  ultimately show ?thesis\n    unfolding Least_def by (simp add: subset_antisym the_equality)\nqed\n\n(* The preimage of a set under a given mapping. *)\ndefinition preimage :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'b set \\<Rightarrow> 'a set\"\n  where \"preimage f T = {s. \\<exists>t\\<in>T. f s = t}\"\n\nlemma preimage_union: \n  shows \"preimage f (\\<Union>M) = (\\<Union>S\\<in>M. preimage f S)\"\nproof (rule ; rule) \n  fix x \n  assume \"x \\<in> preimage f (\\<Union>M)\"\n  hence \"x \\<in> {s. \\<exists>t\\<in>(\\<Union>M). f s = t}\"\n    using preimage_def by metis \n  thus \"x \\<in> (\\<Union>S\\<in>M. preimage f S)\"\n    by (simp add: preimage_def)\nnext\n  fix x \n  assume \"x \\<in> (\\<Union>S\\<in>M. preimage f S)\"\n  thus \"x \\<in> preimage f (\\<Union>M)\"\n    by (simp add: preimage_def)\nqed \n\nlemma preimage_set_diff: \n  shows \"preimage f (R-S) = (preimage f R) - (preimage f S)\"\nproof (rule ; rule)\n  fix x \n  assume \"x \\<in> preimage f (R - S)\"\n  hence \"x \\<in> {s. \\<exists>t\\<in>(R-S). f s = t}\"\n    using preimage_def by metis \n  thus \"x \\<in> preimage f R - preimage f S\"\n    by (simp add: preimage_def)\nnext \n  fix x\n  assume \"x \\<in> preimage f R - preimage f S\"\n  thus \"x \\<in> preimage f (R - S)\"\n    by (simp add: preimage_def) \nqed \n\n(* This is shown with inj_on f A as assumption but the provers don't find that. *)\nlemma inj_infinite_image:\n  assumes inj: \"inj f\"\n      and inf: \"infinite A\"\n    shows \"infinite (f ` A)\"\n  by (meson finite_imageD inf inj inj_def inj_onI)\n\nlemma even_inf: \n  shows \"infinite ((\\<lambda>n::nat. 2 * n) ` UNIV)\"\n    by (simp add: range_inj_infinite injI)\n\nlemma odd_inf: \n  shows \"infinite ((\\<lambda>n::nat. 2 * n + 1) ` UNIV)\"\n  by (simp add: range_inj_infinite injI)\n\nlemma nat_remainder: \n  fixes x m :: nat\n  assumes m_pos: \"m > 0\"\n      and x_pos: \"x > 0\"\n  shows \"\\<exists>k r :: nat. x = k * m + r \\<and> r < m\"  \nproof (induction x)\n  case 0\n  then show ?case\n    using m_pos by auto \nnext\n  case (Suc x)\n  then obtain k r :: nat where ind_hyp: \"x = k * m + r \\<and> r < m\"\n    by auto\n  then consider (l) \"r + 1 < m\" | (eq) \"r + 1 = m\"\n    by linarith\n  then show ?case \n  proof cases\n    case l\n    then show ?thesis\n      by (metis Suc_eq_plus1 add_Suc_right ind_hyp) \n  next\n    case eq\n    then show ?thesis\n      by (metis Suc_eq_plus1 add_0 add_diff_cancel_right' diff_cancel2 ind_hyp \n          linordered_semidom_class.add_diff_inverse m_pos mult_0 mult_Suc) \n  qed \nqed\n\nlemma even_odd_UNIV: \n  shows \"(UNIV :: nat set) = ((\\<lambda>n::nat. 2 * n) ` UNIV) \\<union> ((\\<lambda>n::nat. 2 * n + 1) ` UNIV)\"\nproof -\n  let ?E = \"(\\<lambda>n::nat. 2 * n) ` UNIV\"\n  let ?O = \"(\\<lambda>n::nat. 2 * n + 1) ` UNIV\"\n  have \"\\<forall>x. x \\<in> ?E \\<or> x \\<in> ?O\"\n  proof \n    fix x :: nat\n    consider (0) \"x = 0\" | (p) \"x > 0\"\n      by auto\n    thus \"x \\<in> ?E \\<or> x \\<in> ?O\"\n    proof cases\n      case 0\n      then show ?thesis\n        by simp \n    next\n      case p\n      hence \"\\<exists>k r. x = k * 2 + r \\<and> r < 2\"\n        by (simp add: nat_remainder)\n      hence \"\\<exists>k r :: nat. x = k * 2 \\<or> x = k * 2 + 1\"\n        by (metis div_mult_self1 div_mult_self_is_m mod2_gr_0 mod_less neq0_conv plus_nat.add_0)\n      thus ?thesis by auto \n    qed\n  qed \n  thus ?thesis\n    by blast \nqed\n  \nlemma even_odd_disjoint: \n  shows \"(\\<lambda>n::nat. 2 * n) ` UNIV \\<inter> (\\<lambda>n::nat. 2 * n + 1) ` UNIV = {}\"\nproof (rule ; rule)\n  let ?E = \"(\\<lambda>n::nat. 2 * n) ` UNIV\"\n  let ?O = \"(\\<lambda>n::nat. 2 * n + 1) ` UNIV\"\n  fix x :: nat\n  assume \"x \\<in> ?E \\<inter> ?O\"\n  then obtain n m :: nat where \"x = 2 * n\" and \"x = 2 * m + 1\"\n    by blast \n  thus \"x \\<in> {}\"\n    by (metis Suc_eq_plus1 double_not_eq_Suc_double) \nqed\n  \n\nsection \"Sets\"\n\nsubsection \"Set operations\"\n\nsubsubsection \"Elementary operations\"\n\ntext \"Just as real (or complex) numbers can be added or multiplied, there exist operations on sets.\"\n\ntext \"Union:\"\ncorollary \"A \\<union> B = {x. x \\<in> A \\<or> x \\<in> B}\" \n  using Un_def by auto\n\ntext \"Intersection:\"\ncorollary \"A \\<inter> B = {x. x \\<in> A \\<and> x \\<in> B}\" \n  using Int_def by auto \n\ntext \"Complement:\"\ncorollary \"-A = {x. x \\<notin> A}\" \n  using Compl_eq by auto \n\ntext \"Difference:\"\ncorollary \"A - B = A \\<inter> (-B)\" \n  using Diff_eq by auto \n\ntext \"Symmetric difference:\"\ndefinition symm_diff :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where \"symm_diff A B = (A - B) \\<union> (B - A)\"\n\nnotation symm_diff (infix \"\\<Delta>\" 50)\n\nlemma symm_diff_xor: \"A \\<Delta> B = {x. (x\\<in>A \\<or> x\\<in>B) \\<and> \\<not>(x\\<in>A \\<and> x\\<in>B)}\"\n    by (simp add: Un_def symm_diff_def ; auto)\n\ntext \"We also use standard notation for unions and intersections of finitely / countably many sets.\"\n\ncorollary \n  fixes A :: \"nat \\<Rightarrow> 'a set\"\n  shows \"(\\<Union>i\\<in>{0..n}. A i) = {x. \\<exists>i\\<in>{0..n}. x \\<in> A i}\" \n  using UNION_eq by auto\n\ncorollary \n  fixes A :: \"nat \\<Rightarrow> 'a set\"\n  shows \"(\\<Inter>i. A i) = {x. \\<forall>i\\<in>{0..}. x \\<in> A i}\" \n  by blast \n\n\nsubsubsection \"Additional terminology\"\n\ntext \"Some additional terminology:\"\n\ntext \"The empty set:\"\ncorollary \"\\<not>(\\<exists>x. x \\<in> {})\"\n  by simp\n\ntext \"Subsets:\"\ncorollary \"A \\<subseteq> B \\<longleftrightarrow> (\\<forall>x. x \\<in> A \\<longrightarrow> x \\<in> B)\"\n  by (simp add: subset_iff)\n\ntext \"Disjoint:\"\ncorollary \"A \\<inter> B = {} \\<longleftrightarrow> \\<not>(\\<exists>x. x \\<in> A \\<and> x \\<in> B)\"\n  by (simp add: disjoint_iff) \n\ntext \"Power set:\"\ncorollary \"Pow \\<Omega> = {A. A \\<subseteq> \\<Omega>}\"\n  by (simp add: Pow_def)\n\ntext \"{A n, n \\<ge> 0} is non-decreasing:\"\ndefinition non_decreasing :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\n  where \"non_decreasing A \\<equiv> \\<forall>n. A n \\<subseteq> A (n + 1)\"\n\n(* In a non-decreasing set sequence, any set is a subset of all the ones that follow. *)\nlemma non_decreasing_multistep: \n  assumes non_dec: \"non_decreasing A\"\n      and leq: \"n \\<le> m\"\n    shows \"A n \\<subseteq> A m\"\nproof - \n  have \"\\<forall>n y. y \\<in> A n \\<longrightarrow> y \\<in> A (Suc n)\"\n    using non_dec non_decreasing_def Suc_eq_plus1 subset_iff by metis\n  hence \"\\<forall>n. \\<forall>d\\<ge>0. (A n \\<subseteq> A (n+d))\" \n      using add.commute le_add2 lift_Suc_mono_le subset_iff by metis\n  thus \"A n \\<subseteq> A m\"\n    by (metis bot_nat_0.extremum le_iff_add leq)\nqed \n\n(* Hence, once an element arises within a sequence, it will stay there for all of eternity. *)\nlemma non_decreasing_stay_in: \n  assumes non_dec: \"non_decreasing A\"\n      and base: \"x \\<in> A n\"\n    shows \"\\<forall>m\\<ge>n. x \\<in> A m\"\n  using base non_dec non_decreasing_multistep by auto\n\nlemma non_dec_to_disj: \n  assumes non_dec: \"non_decreasing A\"\n  shows \"disjoint_family (\\<lambda>n. if n = 0 then A 0 else A n - A (n - 1))\"\n  unfolding disjoint_family_on_def \nproof (rule ; rule ; rule) \n  let ?B = \"(\\<lambda>n. if n = 0 then A 0 else A n - A (n-1))\"\n  fix m n :: nat \n  assume \"m \\<noteq> n\" \n  then consider (M) \"m > n\" | (N) \"n > m\"\n    using nat_neq_iff by blast\n  thus \"?B m \\<inter> ?B n = {}\"\n  proof cases\n    case M\n    hence \"\\<forall>x\\<in>?B m. \\<forall>k<m. x \\<notin> A k\"\n      using non_dec non_decreasing_stay_in by fastforce\n    hence \"\\<forall>x\\<in>?B m. \\<forall>k<m. x \\<notin> ?B k\"\n      using Diff_iff by metis \n    then show ?thesis\n      using M by blast\n   next\n     case N\n     hence \"\\<forall>x\\<in>?B n. \\<forall>k<n. x \\<notin> A k\"\n       using non_dec non_decreasing_stay_in by fastforce \n     hence \"\\<forall>x\\<in>?B n. \\<forall>k<n. x \\<notin> ?B k\"\n       by (metis Diff_iff)\n     then show ?thesis\n       using N by blast\n  qed \nqed\n\nlemma non_dec_N_is_fu: \n  assumes non_dec: \"non_decreasing A\"\n  shows \"(\\<Union>n\\<in>{..N}. A n) = A N\"\nproof (rule ; rule)\n  fix x \n  assume \"x \\<in> \\<Union> (A ` {..N})\"\n  thus \"x \\<in> A N\"\n    by (metis UN_iff atMost_iff non_dec non_decreasing_stay_in)\nnext \n  fix x \n  assume \"x \\<in> A N\" \n  thus \"x \\<in> \\<Union> (A ` {..N})\"\n    by auto \nqed\n\nlemma non_dec_is_disj_fu: \n  assumes non_dec: \"non_decreasing A\"\n  shows \"\\<forall>N. A N = (\\<Union>n\\<in>{..N}. (\\<lambda>n. if n = 0 then A 0 else A n - A (n - 1)) n)\"\nproof - \n  let ?B = \"(\\<lambda>n. if n = 0 then A 0 else A n - A (n - 1))\"\n  have \"\\<forall>N. (\\<Union>n\\<in>{..N}. A n) \\<subseteq> (\\<Union>n\\<in>{..N}. ?B n)\"\n  proof (rule ; rule) \n    fix N x \n    obtain P where P_fun: \"P = (\\<lambda>n. n \\<in> {..N} \\<and> x \\<in> A n)\"\n      by auto \n\n    assume \"x \\<in> \\<Union> (A ` {..N})\"\n    hence \"\\<exists>n. P n\"\n      using P_fun by auto \n    hence \"\\<exists>n. P n \\<and> (\\<forall>m<n. \\<not> P m)\"\n      using exists_least_iff by auto \n    then obtain n where n_choice: \"n \\<in> {..N} \\<and> x \\<in> A n \\<and> (\\<forall>m\\<in>{..N}. m < n \\<longrightarrow> x \\<notin> A m)\"\n      using P_fun by auto \n\n    consider (0) \"n = 0\" | (Suc) \"n = Suc (n - 1)\"\n      by linarith \n    hence \"x \\<in> A n \\<and> (n = 0 \\<or> x \\<notin> A (n - 1))\"\n    proof cases\n      case 0\n      then show ?thesis\n        using n_choice by auto \n    next\n      case Suc\n      then show ?thesis\n        using n_choice by auto \n    qed\n\n    hence \"x \\<in> ?B n\"\n      by auto\n    thus \"x \\<in> \\<Union> (?B ` {..N})\"\n      using n_choice by blast \n  qed \n  \n  hence \"\\<forall>N. \\<Union> (A ` {..N}) = (\\<Union>n\\<le>N. if n = 0 then A 0 else A n - A (n - 1))\"\n    by auto \n  thus ?thesis \n    using non_dec non_dec_N_is_fu by metis \nqed\n\nlemma non_dec_to_disj_same_cu: \n  assumes non_dec: \"non_decreasing A\"\n  shows \"(\\<Union>n. A n) = (\\<Union>n. (\\<lambda>n. if n = 0 then A 0 else A n - A (n - 1)) n)\"\nproof - \n  let ?B = \"(\\<lambda>n. if n = 0 then A 0 else A n - A (n - 1))\"\n  have \"\\<Union> (range A) \\<subseteq> (\\<Union>n. ?B n)\"\n  proof \n    fix x \n    assume \"x \\<in> \\<Union> (range A)\"\n    hence \"\\<exists>n. n \\<in> {n'. x \\<in> A n'}\"\n      by simp \n    then obtain n where \"n \\<in> {n'. x \\<in> A n'} \\<and> (\\<forall>m\\<in>{n'. x \\<in> A n'}. n \\<le> m)\"\n      using min_nat_elem by meson\n    hence \"x \\<in> ?B n\"\n      by fastforce \n    thus \"x \\<in> (\\<Union>i::nat. ?B i)\"\n      by fast \n  qed\n  thus ?thesis by auto \nqed\n\ntext \"{A n, n \\<ge> 0} is non-increasing:\"\ndefinition non_increasing :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\"\n  where \"non_increasing A \\<equiv> \\<forall>n. A (n + 1) \\<subseteq> A n\"\n\n(* In a non-decreasing set sequence, any set is a subset of all the ones that precede it. *)\nlemma non_increasing_multistep: \n  assumes non_inc: \"non_increasing A\"\n      and leq: \"n \\<le> m\"\n    shows \"A m \\<subseteq> A n\"\nproof - \n  have \"\\<forall>n y. y \\<in> A (Suc n) \\<longrightarrow> y \\<in> A n\"\n    using non_inc non_increasing_def Suc_eq_plus1 subset_iff by metis\n  hence \"\\<forall>n. \\<forall>d\\<ge>0. (A (n+d) \\<subseteq> A n)\" \n      using add.commute le_add2 subset_iff lift_Suc_antimono_le by metis \n  thus \"A m \\<subseteq> A n\"\n    by (metis bot_nat_0.extremum le_iff_add leq)\nqed \n\n(* Hence, once an element is absent from a set in the sequence, it will stay absent forever. *)\nlemma non_increasing_stay_out: \n  assumes non_inc: \"non_increasing A\"\n      and base: \"x \\<notin> A n\"\n    shows \"\\<forall>m\\<ge>n. x \\<notin> A m\"\n  using base non_inc non_increasing_multistep by auto\n\nlemma non_inc_to_disj: \n  assumes non_inc: \"non_increasing A\"\n  shows \"disjoint_family (\\<lambda>n. A n - A (n + 1))\"\n  unfolding disjoint_family_on_def \nproof (rule ; rule ; rule) \n  let ?B = \"(\\<lambda>n. A n - A (n + 1))\"\n  fix m n :: nat \n  assume \"m \\<noteq> n\" \n  then consider (N) \"m < n\" | (M) \"n < m\"\n    using nat_neq_iff by blast\n  thus \"?B m \\<inter> ?B n = {}\"\n  proof cases\n    case N\n    hence \"\\<forall>x\\<in>?B m. \\<forall>k>m. x \\<notin> A k\"\n      using non_inc non_increasing_stay_out by fastforce\n    hence \"\\<forall>x\\<in>?B m. \\<forall>k>m. x \\<notin> ?B k\"\n      using Diff_iff by metis \n    then show ?thesis\n      using N by auto \n   next\n     case M\n     hence \"\\<forall>x\\<in>?B n. \\<forall>k>n. x \\<notin> A k\"\n       using non_inc non_increasing_stay_out by fastforce \n     hence \"\\<forall>x\\<in>?B n. \\<forall>k>n. x \\<notin> ?B k\"\n       by (metis Diff_iff)\n     then show ?thesis\n       using M by blast\n  qed \nqed\n\nlemma nd_complement_ni: \n  assumes nd: \"non_decreasing A\"\n  shows \"non_increasing (\\<lambda>n. \\<Omega> - A n)\"\n  using nd unfolding non_decreasing_def non_increasing_def by blast \n\nlemma ni_complement_nd: \n  assumes ni: \"non_increasing A\"\n  shows \"non_decreasing (\\<lambda>n. \\<Omega> - A n)\"\n  using ni unfolding non_decreasing_def non_increasing_def by blast \n\ntext \"The de Morgan formulas are as follows:\n\n(i)  The elements that don't belong to any set in a family are exactly the ones that belong to every \n     complement of sets in the family.\n\n(ii) The elements that don't belong to all sets in a family are exactly the ones that appear in some \n     complement of a set in the family.\"\ncorollary \"-(\\<Union>k\\<in>I. A k) = (\\<Inter>k\\<in>I. -(A k))\" by simp\n\ncorollary \"-(\\<Inter>k\\<in>I. A k) = (\\<Union>k\\<in>I. -(A k))\" by simp\n\n\n\nsubsection \"Limits of Sets\"\n\ntext \"It is also possible to define limits of sets. However not every sequence of sets has a limit.\"\n\n(* Any sensible notion of a limit should at least include these elements... *)\nlemma liminf_set:\n  fixes A :: \"nat \\<Rightarrow> ('a set)\"\n  shows \"liminf A = (\\<Union>n. (\\<Inter>m\\<in>{n..}. A m))\"\n    by (simp add: liminf_SUP_INF) \n\n(* ... as they eventually occur at every single index of the sequence. *)\nlemma liminf_greater_n: \"(x \\<in> liminf A) = (\\<exists>n.\\<forall>m\\<ge>n. x \\<in> A m)\"\n  by (simp add: liminf_set atLeast_def) \n\n(* Any sensible notion of a limit should at most include these elements... *)\nlemma limsup_set:\n  fixes A :: \"nat \\<Rightarrow> ('a set)\"\n  shows \"limsup A = (\\<Inter> n. \\<Union>m\\<in>{n..}. A m)\"\n    by (simp add: limsup_INF_SUP) \n\n(* ... as all others eventually stop appearing forever. *)\nlemma limsup_greater_n: \"(x \\<notin> limsup A) = (\\<exists>n.\\<forall>m\\<ge>n. x \\<notin> A m)\"\n  by (simp add: limsup_set atLeast_def) \n\n(* It's reassuring that the two requirements above never lead to a contradiction. *)\nlemma liminf_subseq_limsup: \"liminf A \\<subseteq> limsup A\"\nproof \n  fix x \n  assume \"x \\<in> liminf A\"\n  hence \"\\<exists>n.\\<forall>m\\<ge>n. x \\<in> A m\"\n    by (simp add: liminf_greater_n)\n  hence \"\\<forall>n.\\<exists>m\\<ge>n. x \\<in> A m\"\n    by (metis nat_le_linear)\n  thus \"x \\<in> limsup A\"\n    by (metis limsup_greater_n)\nqed \n\n(* We thus get a handy condition for checking whether liminf and limsup are the same. *)\nlemma liminf_limsup_eq_cond: \n  shows \"(liminf A = limsup A) \\<longleftrightarrow> (limsup A \\<subseteq> liminf A)\"\n  by (simp add: liminf_subseq_limsup set_eq_subset)\n\ntext \"We say that a sequence of sets has a limit if the two above notions agree.\"\ndefinition set_limit :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> 'a set\"\n  where \"set_limit A = (THE S. S = liminf A \\<and> S = limsup A)\"\n\n(* If the limit exists, it's of course equal to liminf... *)\nlemma set_limit_eq_liminf: \n  assumes limsup_subseq_liminf: \"limsup A \\<subseteq> liminf A\" \n  shows \"set_limit A = liminf A\"\nproof - \n  have \"limsup A = liminf A\"\n    using liminf_limsup_eq_cond limsup_subseq_liminf by fast\n  thus ?thesis \n    by (simp add: set_limit_def) \nqed\n\n(* ... and to limsup. *)\nlemma set_limit_eq_limsup: \n  assumes limsup_subseq_liminf: \"limsup A \\<subseteq> liminf A\" \n  shows \"set_limit A = limsup A\"\n  by (simp add: liminf_limsup_eq_cond limsup_subseq_liminf set_limit_eq_liminf)\n\ntext \"One instance when a limit exists is when the sequence of sets is monotone.\"\n\n(* For a non-decreasing sequence of sets, any element that doesn't disappear forever will start\n   appearing forever. These are precisely all elements that appear in the sequence at any point. \n\n   The limit is thus defined.*)\nproposition non_decreasing_set_limit: \n  assumes non_decreasing: \"non_decreasing A\"\n  shows \"set_limit A = \\<Union>(range A)\" \nproof - \n  have \"limsup A = \\<Union>(range A)\" \n  proof \n    show \"limsup A \\<subseteq> \\<Union>(range A)\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\"\n      hence \"(\\<exists>m. m \\<ge> 1 \\<and> x \\<in> A m)\"\n        using limsup_greater_n by fast\n      thus \"x \\<in> \\<Union>(range A)\"\n        by auto \n    qed\n  next \n    show \"\\<Union>(range A) \\<subseteq> limsup A\"\n    proof \n      fix x \n      assume \"x \\<in> \\<Union>(range A)\" \n      then obtain n where \"x \\<in> A n\" \n        by auto \n      hence \"\\<forall>m\\<ge>n. x \\<in> A m\"\n        by (meson non_decreasing non_decreasing_stay_in)\n      thus \"x \\<in> limsup A\"\n        by (meson limsup_greater_n nat_le_linear) \n    qed\n  qed\n\n  moreover have \"limsup A = liminf A\" \n  proof - \n    have \"limsup A \\<subseteq> liminf A\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\"\n      hence \"\\<forall>n.\\<exists>m\\<ge>n. x \\<in> A m\"\n        by (metis limsup_greater_n)\n      hence \"\\<exists>n.\\<forall>m\\<ge>n. x \\<in> A m\"\n        by (meson non_decreasing non_decreasing_stay_in)\n      thus \"x \\<in> liminf A\"\n        by (simp add: liminf_greater_n)\n    qed\n    thus ?thesis\n      using liminf_limsup_eq_cond by fast \n  qed\n\n  ultimately show ?thesis\n    by (simp add: set_limit_eq_limsup) \nqed\n\n(* For a non-increasing sequence of sets, any element that doesn't appear at every single index\n   will eventually disappear forever.\n\n   The limit is thus defined.*)\nproposition non_increasing_set_limit: \n  assumes non_increasing: \"non_increasing A\"\n  shows \"set_limit A = \\<Inter>(range A)\" \nproof - \n  have \"limsup A = \\<Inter>(range A)\" \n  proof \n    show \"limsup A \\<subseteq> \\<Inter>(range A)\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\"\n      hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m\"\n        by (meson limsup_greater_n)\n      hence \"\\<forall>m. x \\<in> A m\"\n        using non_increasing non_increasing_stay_out by metis \n      thus \"x \\<in> \\<Inter>(range A)\"\n        by simp \n    qed\n  next \n    show \"\\<Inter>(range A) \\<subseteq> limsup A\"\n    proof \n      fix x \n      assume \"x \\<in> \\<Inter>(range A)\" \n      hence \"\\<forall>m. x \\<in> A m\"\n        by simp \n      thus \"x \\<in> limsup A\"\n        by (meson limsup_greater_n nat_le_linear) \n    qed\n  qed\n\n  moreover have \"limsup A = liminf A\" \n  proof - \n    have \"limsup A \\<subseteq> liminf A\"\n    proof \n      fix x \n      assume \"x \\<in> limsup A\"\n      hence \"\\<forall>n. \\<exists>m. m \\<ge> n \\<and> x \\<in> A m\"\n        by (meson limsup_greater_n)\n      hence \"\\<exists>n. \\<forall>k\\<ge>n. x \\<in> A k\"\n        by (meson non_increasing non_increasing_stay_out)\n      thus \"x \\<in> liminf A\"\n        by (simp add: liminf_greater_n) \n    qed\n    thus ?thesis\n      using liminf_limsup_eq_cond by fast  \n  qed \n\n  ultimately show ?thesis\n    by (simp add: set_limit_eq_limsup) \nqed\n\nlemma nd_c_ni_set_limit: \n  assumes non_dec: \"non_decreasing A\"\n    shows \"set_limit (\\<lambda>n. \\<Omega> - A n) = \\<Omega> - set_limit A\"\nproof - \n  let ?B = \"(\\<lambda>n. \\<Omega> - A n)\"\n  have non_inc: \"non_increasing ?B\"\n    by (simp add: nd_complement_ni non_dec)\n\n  have \"set_limit A = \\<Union> (range A)\"\n    using non_dec non_decreasing_set_limit by auto\n  moreover have \"set_limit ?B = \\<Inter> (range ?B)\"\n    using non_inc non_increasing_set_limit by auto\n  hence \"set_limit ?B = \\<Omega> - \\<Union> (range A)\"\n    by simp \n  ultimately show ?thesis\n    by auto \nqed\n\nlemma ni_c_nd_set_limit: \n  assumes non_inc: \"non_increasing A\"\n  shows \"set_limit (\\<lambda>n. \\<Omega> - A n) = \\<Omega> - set_limit A\"\nproof - \n  let ?B = \"(\\<lambda>n. \\<Omega> - A n)\"\n  have non_dec: \"non_decreasing ?B\"\n    by (simp add: ni_complement_nd non_inc)\n\n  have \"set_limit A = \\<Inter> (range A)\"\n    using non_inc non_increasing_set_limit by auto\n  moreover have \"set_limit ?B = \\<Union> (range ?B)\"\n    using non_dec non_decreasing_set_limit by auto  \n  hence \"set_limit ?B = \\<Omega> - \\<Inter> (range A)\"\n    by simp \n  ultimately show ?thesis\n    by blast\nqed\n\n\nsection \"Collections of Sets\"\n\nsubsection \"Rules for Collections of Sets\"\n\ntext \"Set collections are commonly selected according to whether they are stable under certain \noperations.  \nA collection of sets may, for instance, be stable under \n(i) The complement.\n(ii) Finite unions.\n(iii) Finite intersections.\n\nNote: (i), (ii) and (i), (iii) are equivalent, due to deMorgan's formulas.\n\nNote: We defined (ii) and (iii) with just a normal binary union / intersection. That's enough, it\n      follows for all finite families by induction.\n\n(iv) Set differences with respect to ones subset, provided that it's also in the collection \n\nNote: If the subsets we want to be able to remove weren't required to be in the collection, this\n      condition would just mean 'stable under taking subsets'. \n\n(v) Countable unions.\n(vi) Countable union of a family of sets as long as it is disjoint. \n\nNote: This does not hold for finite, disjoint unions unless {} is in the set. Only then is it possible\n      to represent any finite disjoint union as a countable disjoint union, where all but the first\n      finitely many entries of the sequence that yields the union can be {}. \n\n(vii) Countable intersections.\n\nNote: Yes, (i), (v) and (i), (vii) are also equivalent by deMorgan.\n\nNote: If a set is stable under countable un./in., it is of course so under finite ones as well.\n\n(viii) The (countable) union (limit!) of non-decreasing sequences of sets.\n(ix) The (countable) intersection (limit!) of non-increasing sequences of sets. \n\"\n\nsubsubsection \"Complements, finite unions and intersections\"\n\ndefinition complement_stable :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\"\n  where \"complement_stable \\<Omega> M = ((M \\<noteq> {}) \\<and> (\\<forall>S\\<in>M. \\<Omega> - S \\<in> M))\"\n\ndefinition finite_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"finite_union_stable M = ((M \\<noteq> {}) \\<and> (\\<forall>S\\<in>M.\\<forall>T\\<in>M. S \\<union> T \\<in> M))\"\n\nlemma fu_stable_finite: \n  assumes fu_stable: \"finite_union_stable M\"\n      and family_in: \"\\<forall>i\\<in>I. A i \\<in> M\"\n      and finite: \"finite I\"\n      and non_empty: \"I \\<noteq> {}\"\n    shows \"(\\<Union>i\\<in>I. A i) \\<in> M\"\n  using finite non_empty family_in fu_stable\nproof (induction I rule: finite_induct)\n  case empty\n  then show ?case\n    by auto \nnext\n  case (insert x F)\n  show ?case \n  proof (cases \"F = {}\")\n    case True\n    hence \"\\<Union> (A ` insert x F) = A x\"\n      by simp\n    then show \"\\<Union> (A ` insert x F) \\<in> M\"\n      by (simp add: insert.prems(2)) \n  next\n    case False\n    hence \"(\\<Union>i\\<in>F. A i) \\<in> M\"\n      by (simp add: fu_stable insert.IH insert.prems(2)) \n    moreover have \"A x \\<in> M\"\n      by (simp add: insert.prems(2))\n    moreover have \"\\<Union> (A ` insert x F) = (\\<Union>i\\<in>F. A i) \\<union> (A x)\"\n      by auto \n    ultimately show \"\\<Union> (A ` insert x F) \\<in> M\"\n      by (metis finite_union_stable_def fu_stable) \n  qed\nqed \n    \n\ndefinition finite_inter_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"finite_inter_stable M = ((M \\<noteq> {}) \\<and> (\\<forall>S\\<in>M.\\<forall>T\\<in>M. S \\<inter> T \\<in> M))\"\n\nlemma fi_stable_finite: \n  assumes fi_stable: \"finite_inter_stable M\"\n      and family_in: \"\\<forall>i\\<in>I. A i \\<in> M\"\n      and finite: \"finite I\"\n      and non_empty: \"I \\<noteq> {}\"\n    shows \"(\\<Inter>i\\<in>I. A i) \\<in> M\"\n  using finite non_empty family_in fi_stable\nproof (induction I rule: finite_induct)\n  case empty\n  then show ?case\n    by auto \nnext\n  case (insert x F)\n  show ?case \n  proof (cases \"F = {}\")\n    case True\n    hence \"\\<Inter> (A ` insert x F) = A x\"\n      by simp\n    then show \"\\<Inter> (A ` insert x F) \\<in> M\"\n      by (simp add: insert.prems(2)) \n  next\n    case False\n    hence \"(\\<Inter>i\\<in>F. A i) \\<in> M\"\n      by (simp add: fi_stable insert.IH insert.prems(2)) \n    moreover have \"A x \\<in> M\"\n      by (simp add: insert.prems(2))\n    moreover have \"\\<Inter> (A ` insert x F) = (\\<Inter>i\\<in>F. A i) \\<inter> (A x)\"\n      by auto \n    ultimately show \"\\<Inter> (A ` insert x F) \\<in> M\"\n      by (metis finite_inter_stable_def fi_stable) \n  qed\nqed \n\nlemma c_fu_imp_fi_stable: \n  assumes c_stable: \"complement_stable \\<Omega> M\"\n      and fu_stable: \"finite_union_stable M\" \n      and subseq: \"\\<forall>S\\<in>M. S \\<subseteq> \\<Omega>\"\n    shows \"finite_inter_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using c_stable complement_stable_def by auto \n\n  moreover have \"\\<forall>S\\<in>M.\\<forall>T\\<in>M. S \\<inter> T \\<in> M\" \n  proof \n    fix S\n    assume S_in: \"S\\<in>M\"\n    show \"\\<forall>T\\<in>M. S \\<inter> T \\<in> M\"\n    proof \n      fix T\n      assume \"T\\<in>M\"\n      hence \"\\<Omega>-T \\<in> M\"\n        using c_stable complement_stable_def by fast\n      moreover have \"\\<Omega>-S \\<in> M\"\n        using S_in c_stable complement_stable_def by fast\n      ultimately have \"(\\<Omega>-S) \\<union> (\\<Omega>-T) \\<in> M\"\n        using fu_stable finite_union_stable_def by fast \n      hence \"\\<Omega> - (S \\<inter> T) \\<in> M\"\n        by (simp add: Diff_Int)\n      hence \"\\<Omega> - (\\<Omega> - (S \\<inter> T)) \\<in> M\"\n        using c_stable complement_stable_def by fast\n      moreover have \"\\<Omega> - (\\<Omega> - (S \\<inter> T)) = S \\<inter> T\"\n        using S_in subseq by auto \n      ultimately show \"S \\<inter> T \\<in> M\" \n        by simp \n    qed\n  qed \n    \n  ultimately show ?thesis \n    by (simp add: finite_inter_stable_def) \nqed \n\nlemma c_fi_imp_fu_stable: \n  assumes c_stable: \"complement_stable \\<Omega> M\"\n      and fi_stable: \"finite_inter_stable M\" \n      and subseq: \"\\<forall>S\\<in>M. S \\<subseteq> \\<Omega>\"\n    shows \"finite_union_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using c_stable complement_stable_def by auto \n\n  moreover have \"\\<forall>S\\<in>M.\\<forall>T\\<in>M. S \\<union> T \\<in> M\" \n  proof \n    fix S\n    assume S_in: \"S\\<in>M\"\n    show \"\\<forall>T\\<in>M. S \\<union> T \\<in> M\"\n    proof \n      fix T\n      assume T_in: \"T\\<in>M\"\n      hence \"\\<Omega>-T \\<in> M\"\n        using c_stable complement_stable_def by fast\n      moreover have \"\\<Omega>-S \\<in> M\"\n        using S_in c_stable complement_stable_def by fast\n      ultimately have \"(\\<Omega>-S) \\<inter> (\\<Omega>-T) \\<in> M\"\n        using fi_stable finite_inter_stable_def by fast \n      hence \"\\<Omega> - (S \\<union> T) \\<in> M\"\n        by (simp add: Diff_Un)\n      hence \"\\<Omega> - (\\<Omega> - (S \\<union> T)) \\<in> M\"\n        using c_stable complement_stable_def by fast\n      moreover have \"\\<Omega> - (\\<Omega> - (S \\<union> T)) = S \\<union> T\"\n        using S_in T_in subseq by auto \n      ultimately show \"S \\<union> T \\<in> M\" \n        by simp \n    qed\n  qed \n    \n  ultimately show ?thesis \n    by (simp add: finite_union_stable_def) \nqed\n\nsubsubsection \"Set Difference\"\n\ndefinition set_diff_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"set_diff_stable M = ((M \\<noteq> {}) \\<and> (\\<forall>S\\<in>M.\\<forall>T\\<in>M. (T \\<subseteq> S) \\<longrightarrow> (S - T \\<in> M)))\"\n\nlemma sd_omega_imp_c_stable: \n  assumes sd_stable: \"set_diff_stable M\"\n      and omega: \"\\<Omega> \\<in> M\"\n      and M_pow: \"M \\<subseteq> Pow \\<Omega>\"\n    shows \"complement_stable \\<Omega> M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using omega by auto\n  moreover have \"\\<forall>S\\<in>M. \\<Omega> - S \\<in> M\"\n    by (meson M_pow PowD in_mono omega sd_stable set_diff_stable_def)\n  ultimately show ?thesis\n    by (simp add: complement_stable_def) \nqed\n\nlemma c_fu_omega_imp_sd_stable:\n  assumes c_stable: \"complement_stable \\<Omega> M\" \n      and fu_stable: \"finite_union_stable M\"\n      and omega: \"\\<Omega> \\<in> M\"\n      and M_pow: \"M \\<subseteq> Pow \\<Omega>\"\n    shows \"set_diff_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using omega by auto\n  moreover have \"\\<forall>S\\<in>M. \\<forall>T\\<in>M. T \\<subseteq> S \\<longrightarrow> S - T \\<in> M\"\n  proof (rule ; rule ; rule) \n    fix S T :: \"'a set\"\n    assume T_M: \"T \\<in> M\" and S_M: \"S \\<in> M\" and T_S: \"T \\<subseteq> S\"\n    hence \"S - T = \\<Omega> - ((\\<Omega> - S) \\<union> T)\"\n      using M_pow by auto\n    moreover have \"\\<Omega> - S \\<in> M\"\n      using S_M c_stable complement_stable_def by blast\n    hence \"(\\<Omega> - S) \\<union> T \\<in> M\"\n      using T_M fu_stable unfolding finite_union_stable_def by simp \n    ultimately show \"S - T \\<in> M\"  \n      using c_stable M_pow unfolding complement_stable_def by simp \n  qed \n  ultimately show ?thesis \n    unfolding set_diff_stable_def by auto \nqed\n  \n\nsubsubsection \"Countable unions and intersections\"\n\ndefinition countable_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"countable_union_stable M = ((M \\<noteq> {}) \\<and> (\\<forall>A. (range A \\<subseteq> M) \\<longrightarrow> ((\\<Union>i::nat. A i) \\<in> M)))\"\n\nlemma cu_imp_fu_stable: \n  assumes cu_stable: \"countable_union_stable M\"\n  shows \"finite_union_stable M\"\nproof - \n  have \"M \\<noteq> {}\" \n    using cu_stable countable_union_stable_def by auto \n\n  moreover have \"\\<forall>S\\<in>M.\\<forall>T\\<in>M. S \\<union> T \\<in> M\" \n  proof \n    fix S\n    assume S_in: \"S \\<in> M\"\n    show \"\\<forall>T\\<in>M. S \\<union> T \\<in> M\"\n    proof \n      fix T\n      let ?A = \"(\\<lambda>n. if n = (1::nat) then S else T)\"\n      let ?U = \"(\\<Union>i. ?A i)\"\n      assume \"T \\<in> M\"\n      hence \"range ?A \\<subseteq> M\"\n        using S_in by auto \n      hence \"?U \\<in> M\"\n        using cu_stable countable_union_stable_def by metis\n      moreover have \"?U = S \\<union> T\" \n      proof \n        show \"?U \\<subseteq> S \\<union> T\"\n          by simp\n      next \n        show \"S \\<union> T \\<subseteq> ?U\" \n        proof \n          fix x \n          assume \"x \\<in> S \\<union> T\"\n          then consider (S) \"x \\<in> S\" | (T) \"x \\<in> T\"\n            by fast \n          thus \"x \\<in> ?U\"  \n          proof cases\n            case S\n            hence \"x \\<in> ?A 1\"\n              by simp\n            thus ?thesis \n              by fast \n          next\n            case T\n            hence \"x \\<in> ?A 0\"\n              by simp\n            thus ?thesis \n              by fast \n          qed \n        qed\n      qed\n      ultimately show \"S \\<union> T \\<in> M\" \n        by simp \n    qed\n  qed\n\n  ultimately show ?thesis \n    using finite_union_stable_def by auto \nqed\n\ndefinition countable_inter_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"countable_inter_stable M = ((M \\<noteq> {}) \\<and> (\\<forall>A. (range A \\<subseteq> M) \\<longrightarrow> ((\\<Inter>i::nat. A i) \\<in> M)))\"\n\nlemma ci_imp_fi_stable: \n  assumes ci_stable: \"countable_inter_stable M\"\n  shows \"finite_inter_stable M\"\nproof - \n  have \"M \\<noteq> {}\" \n    using ci_stable countable_inter_stable_def by auto \n\n  moreover have \"\\<forall>S\\<in>M.\\<forall>T\\<in>M. S \\<inter> T \\<in> M\" \n  proof \n    fix S\n    assume S_in: \"S \\<in> M\"\n    show \"\\<forall>T\\<in>M. S \\<inter> T \\<in> M\"\n    proof \n      fix T\n      let ?A = \"(\\<lambda>n. if n = (1::nat) then S else T)\"\n      let ?U = \"(\\<Inter>i. ?A i)\"\n      assume \"T \\<in> M\"\n      hence \"range ?A \\<subseteq> M\"\n        using S_in by auto \n      hence \"?U \\<in> M\"\n        using ci_stable countable_inter_stable_def by metis\n      moreover have \"?U = S \\<inter> T\" \n      proof \n        show \"?U \\<subseteq> S \\<inter> T\"\n        proof \n          fix x \n          assume x_in: \"x \\<in> ?U\"\n          hence \"\\<forall>i. x \\<in> ?A i\"\n            by fast \n          moreover have \"?A 0 = T \\<and> ?A 1 = S\"\n            by auto \n          ultimately show \"x \\<in> S \\<inter> T\" \n            by fast \n        qed\n      next \n        show \"S \\<inter> T \\<subseteq> ?U\"\n          by auto \n      qed\n      ultimately show \"S \\<inter> T \\<in> M\" \n        by simp \n    qed\n  qed\n\n  ultimately show ?thesis \n    using finite_inter_stable_def by auto \nqed\n\nlemma c_cu_imp_ci_stable: \n  assumes c_stable: \"complement_stable \\<Omega> M\"\n      and cu_stable: \"countable_union_stable M\" \n      and subseq: \"\\<forall>S\\<in>M. S \\<subseteq> \\<Omega>\"\n    shows \"countable_inter_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using c_stable complement_stable_def by auto \n\n  moreover have \"\\<forall>A. (range A \\<subseteq> M) \\<longrightarrow> ((\\<Inter>i::nat. A i) \\<in> M)\" \n  proof (rule allI; rule impI)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume seq_in: \"range A \\<subseteq> M\"\n    hence \"range (\\<lambda>n. \\<Omega> - A n) \\<subseteq> M\"\n      using c_stable complement_stable_def by auto\n    hence \"(\\<Union>i::nat. \\<Omega> - A i) \\<in> M\"\n      using countable_union_stable_def cu_stable by metis\n    hence \"\\<Omega> - (\\<Union>i::nat. \\<Omega> - A i) \\<in> M\" \n      using c_stable complement_stable_def by auto\n\n    moreover have \"\\<forall>i. A i \\<subseteq> \\<Omega>\"\n      using seq_in subseq by auto \n    hence \"\\<Omega> - (\\<Union>i. \\<Omega> - A i) = (\\<Inter>i. A i)\" \n      by blast \n\n    ultimately show \"(\\<Inter>i::nat. A i) \\<in> M\"\n      by simp \n  qed \n    \n  ultimately show ?thesis\n    by (simp add: countable_inter_stable_def) \nqed \n\nlemma c_ci_imp_cu_stable: \n  assumes c_stable: \"complement_stable \\<Omega> M\"\n      and ci_stable: \"countable_inter_stable M\" \n      and subseq: \"\\<forall>S\\<in>M. S \\<subseteq> \\<Omega>\"\n    shows \"countable_union_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using c_stable complement_stable_def by auto \n\n  moreover have \"\\<forall>A. (range A \\<subseteq> M) \\<longrightarrow> ((\\<Union>i::nat. A i) \\<in> M)\" \n  proof (rule allI; rule impI)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume seq_in: \"range A \\<subseteq> M\"\n    hence \"range (\\<lambda>n. \\<Omega> - A n) \\<subseteq> M\"\n      using c_stable complement_stable_def by auto\n    hence \"(\\<Inter>i::nat. \\<Omega> - A i) \\<in> M\"\n      using countable_inter_stable_def ci_stable by metis\n    hence \"\\<Omega> - (\\<Inter>i::nat. \\<Omega> - A i) \\<in> M\" \n      using c_stable complement_stable_def by auto\n\n    moreover have \"\\<forall>i. A i \\<subseteq> \\<Omega>\"\n      using seq_in subseq by auto \n    hence \"\\<Omega> - (\\<Inter>i. \\<Omega> - A i) = (\\<Union>i. A i)\" \n      by blast \n\n    ultimately show \"(\\<Union>i::nat. A i) \\<in> M\"\n      by simp \n  qed \n    \n  ultimately show ?thesis\n    by (simp add: countable_union_stable_def) \nqed \n\nsubsubsection \"Disjoint unions\"\n\ndefinition disj_countable_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"disj_countable_union_stable M = \n        ((M \\<noteq> {}) \\<and> (\\<forall>A. (range A \\<subseteq> M \\<and> disjoint_family A) \\<longrightarrow> ((\\<Union>i::nat. A i) \\<in> M)))\"\n\n\ndefinition disj_finite_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"disj_finite_union_stable M = ((M \\<noteq> {}) \\<and> (\\<forall>S\\<in>M. \\<forall>T\\<in>M. (S \\<inter> T = {}) \\<longrightarrow> (S \\<union> T \\<in> M)))\"\n\n(* TODO - Could show by induction that this suffices for unions of disjoint families of size n *)\n  \nlemma dcu_imp_dfu_stable:\n  assumes dcu_stable: \"disj_countable_union_stable M\"\n      and empty_in: \"{} \\<in> M\"\n  shows \"disj_finite_union_stable M\"\nproof -\n  have \"M \\<noteq> {}\" \n    using dcu_stable unfolding disj_countable_union_stable_def by fast \n\n  moreover have \"\\<forall>S\\<in>M. \\<forall>T\\<in>M. (S \\<inter> T = {}) \\<longrightarrow> (S \\<union> T \\<in> M)\" \n  proof \n    fix S\n    assume S_in: \"S \\<in> M\"\n    show \"\\<forall>T\\<in>M. (S \\<inter> T = {}) \\<longrightarrow> (S \\<union> T \\<in> M)\"\n    proof \n      fix T\n      assume T_in: \"T \\<in> M\"\n      show \"(S \\<inter> T = {}) \\<longrightarrow> (S \\<union> T \\<in> M)\"\n      proof \n        assume disj: \"S \\<inter> T = {}\"\n\n        let ?A = \"(\\<lambda>n. if n = (0::nat) then S else if n = (1::nat) then T else {})\"\n        let ?U = \"\\<Union>(range ?A)\"\n      \n        have \"range ?A \\<subseteq> M\"\n          using S_in T_in empty_in by auto \n        moreover have \"disjoint_family ?A\"\n          by (simp add: Int_commute disj disjoint_family_on_def) \n        ultimately have\"?U \\<in> M\"\n          using dcu_stable disj unfolding disj_countable_union_stable_def by blast  \n        moreover have \"?U = S \\<union> T\" \n        proof \n          show \"?U \\<subseteq> S \\<union> T\"\n            by simp\n        next \n          show \"S \\<union> T \\<subseteq> ?U\" \n          proof \n            fix x \n            assume \"x \\<in> S \\<union> T\"\n            then consider (S) \"x \\<in> S\" | (T) \"x \\<in> T\"\n              by fast \n            thus \"x \\<in> ?U\"  \n            proof cases\n              case S\n              hence \"x \\<in> ?A 0\"\n                by simp\n              thus ?thesis \n                by fast \n            next\n              case T\n                hence \"x \\<in> ?A 1\"\n                  by simp\n                thus ?thesis \n                  by fast \n            qed \n          qed\n        qed\n\n        ultimately show \"S \\<union> T \\<in> M\"\n          by fastforce \n      qed\n    qed\n  qed\n  ultimately show ?thesis\n    by (simp add: disj_finite_union_stable_def)\nqed\n\n\n\nlemma dcu_c_empty_imp_sd_stable: \n  assumes dcu_stable: \"disj_countable_union_stable M\"\n      and c_stable: \"complement_stable \\<Omega> M\"\n      and empty_in: \"{} \\<in> M\"\n      and M_pow: \"M \\<subseteq> Pow \\<Omega>\"\n    shows \"set_diff_stable M\"\nproof -  \n  have dfu_stable: \"disj_finite_union_stable M\"\n    by (simp add: dcu_imp_dfu_stable assms)\n\n  have \"M \\<noteq> {}\" \n    using c_stable complement_stable_def by auto \n  moreover have \" \\<forall>S\\<in>M.\\<forall>T\\<in>M. (T \\<subseteq> S) \\<longrightarrow> (S - T \\<in> M)\" \n  proof \n    fix S\n    assume S_in: \"S \\<in> M\"\n    show \"\\<forall>T\\<in>M. T \\<subseteq> S \\<longrightarrow> S - T \\<in> M\"\n    proof\n      fix T\n      assume T_in_collection: \"T \\<in> M\"\n      show \"T \\<subseteq> S \\<longrightarrow> S - T \\<in> M\"\n      proof \n        assume T_in_set: \"T \\<subseteq> S\"\n        have \"\\<Omega> - S \\<in> M\"\n          using c_stable unfolding complement_stable_def using S_in by auto\n        moreover have \"T \\<inter> (\\<Omega> - S) = {}\"\n          using T_in_set by auto\n        ultimately have \"T \\<union> (\\<Omega> - S) \\<in> M\"  \n          using dfu_stable unfolding disj_finite_union_stable_def using S_in T_in_collection by simp\n        hence \"\\<Omega> - (T \\<union> (\\<Omega> - S)) \\<in> M\"\n          using c_stable complement_stable_def by blast\n        moreover have \"\\<Omega> - (T \\<union> (\\<Omega> - S)) = S - T\"\n          using Diff_Diff_Int M_pow S_in by auto \n        ultimately show \"S - T \\<in> M\"\n          by simp \n      qed\n    qed\n  qed\n  ultimately show ?thesis\n    by (simp add: set_diff_stable_def)\nqed\n\nsubsubsection \"Monotonic sequences\"\n\ndefinition non_decreasing_union_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"non_decreasing_union_stable M = \n        ((M \\<noteq> {}) \\<and> (\\<forall>A. (range A \\<subseteq> M \\<and> non_decreasing A) \\<longrightarrow> ((\\<Union>i::nat. A i) \\<in> M)))\"\n\nlemma cu_imp_ndu_stable:\n  assumes cu_stable: \"countable_union_stable M\"\n  shows \"non_decreasing_union_stable M\"\n  using cu_stable unfolding countable_union_stable_def non_decreasing_union_stable_def by simp\n\nlemma sd_omega_imp_ndu_stable: \n  assumes sd_stable: \"set_diff_stable M\"\n      and ndu_stable: \"non_decreasing_union_stable M\"\n      and omega: \"\\<Omega> \\<in> M\"\n      and M_pow: \"M \\<subseteq> Pow \\<Omega>\" \n    shows \"disj_countable_union_stable M\" \nproof - \n  have \"M \\<noteq> {}\"\n    using omega by auto  \n\n  moreover have \"\\<forall>A. (range A \\<subseteq> M \\<and> disjoint_family A \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M)\"\n  proof (rule ; rule)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume A_disj_in_M: \"range A \\<subseteq> M \\<and> disjoint_family A\"\n    let ?B = \"(\\<lambda>n. (\\<Union>i\\<in>{i::nat. i \\<le> n}. A i))\"\n    have \"non_decreasing ?B\" \n      unfolding non_decreasing_def by (simp add: UN_subset_iff UN_upper) \n      \n    moreover have \"\\<forall>n. ?B n \\<in> M\" \n    proof \n      fix n \n      show \"?B n \\<in> M\" \n        using A_disj_in_M\n      proof (induction n)\n        case 0\n        thus \"\\<Union> (A ` {i::nat. i \\<le> 0}) \\<in> M\"\n          using A_disj_in_M by auto \n      next\n        case (Suc n)\n        have \"{i::nat. i \\<le> (Suc n)} = insert (Suc n) {i::nat. i \\<le> n}\" \n          unfolding insert_def by auto \n        hence \"?B (Suc n) = A (Suc n) \\<union> ?B n\"\n          by simp\n        moreover have \"A (Suc n) \\<subseteq> \\<Omega>\"\n          using A_disj_in_M M_pow by blast\n        moreover have B_in_Omega: \"?B n \\<subseteq> \\<Omega>\"\n          using M_pow Suc.IH Suc.prems by blast\n        ultimately have \"?B (Suc n) = \\<Omega> - ((\\<Omega> - A (Suc n)) - ?B n)\"\n          by blast \n      \n        moreover have \"(\\<Omega> - A (Suc n)) \\<in> M\"\n          by (meson A_disj_in_M M_pow complement_stable_def omega range_subsetD sd_stable \n             sd_omega_imp_c_stable)\n        moreover have \"?B n \\<subseteq> (\\<Omega> - A (Suc n))\" \n        proof \n          fix x\n          assume x_in_B: \"x \\<in> ?B n\"\n          hence x_in_smaller_A: \"\\<exists>m<(Suc n). x \\<in> A m\"\n            using neq0_conv by fastforce \n          hence \"x \\<in> \\<Omega>\"\n            using B_in_Omega x_in_B by blast\n          moreover have \"x \\<notin> A (Suc n)\"\n            using x_in_smaller_A A_disj_in_M unfolding disjoint_family_on_def\n            by (metis UNIV_I disjoint_iff less_SucI not_less_eq)\n          ultimately show \"x \\<in> (\\<Omega> - A (Suc n))\"\n            by simp \n        qed\n        moreover have \"((\\<Omega> - A (Suc n)) - ?B n) \\<in> M\"\n          using calculation sd_stable Suc.IH Suc.prems unfolding set_diff_stable_def by blast \n        ultimately show \"\\<Union> (A ` {i. i \\<le> Suc n}) \\<in> M\"\n          using omega sd_stable unfolding set_diff_stable_def by auto \n      qed\n    qed  \n    hence \"range ?B \\<subseteq> M\" \n      by auto \n\n    ultimately have \"\\<Union> (range ?B) \\<in> M\"\n      using ndu_stable unfolding non_decreasing_union_stable_def by blast \n\n    moreover have \"\\<Union> (range ?B) = \\<Union> (range A)\"\n      by fastforce \n\n    ultimately show \"(\\<Union>i::nat. A i) \\<in> M\"\n      by auto \n  qed \n  ultimately show ?thesis \n    using disj_countable_union_stable_def by metis \nqed\n\nlemma ndu_fu_imp_cu_stable:\n  assumes ndu_stable: \"non_decreasing_union_stable M\"\n      and fu_stable: \"finite_union_stable M\"\n    shows \"countable_union_stable M\"\nproof - \n  have M_non_empty: \"M \\<noteq> {}\"\n    using fu_stable unfolding finite_union_stable_def by auto \n\n  moreover have \"\\<forall>A::(nat \\<Rightarrow> 'a set). range A \\<subseteq> M \\<longrightarrow> \\<Union> (range A) \\<in> M\"\n  proof (rule ; rule)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    let ?B = \"(\\<lambda>n. (\\<Union>i\\<in>{0..n}. A i))\"\n    have \"non_decreasing ?B\" \n      unfolding non_decreasing_def by (simp add: UN_subset_iff UN_upper)\n    moreover assume A_within_M: \"range A \\<subseteq> M\"\n    have \"\\<forall>n::nat. ?B n \\<in> M\" \n    proof (rule)\n      fix n\n      show \"?B n \\<in> M\"\n      proof (induction n)\n        case 0\n        have \"\\<Union> (A ` {0..0}) = A 0\"\n          by auto \n        then show \"\\<Union> (A ` {0..0}) \\<in> M\"\n          using A_within_M by auto\n      next\n        case (Suc n)\n   \n        have \"\\<Union> (A ` {0..Suc n}) = \\<Union> (A ` {0..n}) \\<union> A (Suc n)\" \n        proof (rule ; rule)\n          fix x \n          assume \"x \\<in> \\<Union> (A ` {0..Suc n})\"\n          hence \"\\<exists>m\\<in>{0..Suc n}. x \\<in> A m\"\n            by blast\n          hence \"(\\<exists>m\\<in>{0..n}. x \\<in> A m) \\<or> x \\<in> A (Suc n)\"\n            by (metis atLeastAtMost_iff le_SucE) \n          thus \"x \\<in> \\<Union> (A ` {0..n}) \\<union> A (Suc n)\"\n            by blast\n        next \n          fix x \n          assume \"x \\<in> \\<Union> (A ` {0..n}) \\<union> A (Suc n)\"\n          hence \"(\\<exists>m\\<in>{0..n}. x \\<in> A m) \\<or> x \\<in> A (Suc n)\"\n            by blast\n          thus \"x \\<in> \\<Union> (A ` {0..Suc n})\"\n            by auto\n        qed\n\n        moreover have \"\\<Union> (A ` {0..n}) \\<in> M\"\n          using Suc by auto\n        moreover have \"A (Suc n) \\<in> M\"\n          using A_within_M by auto    \n        ultimately show \"\\<Union> (A ` {0..Suc n}) \\<in> M\"  \n          using fu_stable unfolding finite_union_stable_def by auto  \n      qed\n    qed \n    hence \"range ?B \\<subseteq> M\" \n      by blast \n   \n    ultimately have \"\\<Union> (range ?B) \\<in> M\"\n      using M_non_empty ndu_stable unfolding non_decreasing_union_stable_def by auto \n    moreover have \"\\<Union> (range ?B) = \\<Union> (range A)\" \n      by fastforce \n    ultimately show \"\\<Union> (range A) \\<in> M\" \n      by auto \n  qed\n\n  ultimately show ?thesis\n    unfolding countable_union_stable_def by auto\nqed\n\nlemma dcu_c_empty_imp_ndu_stable: \n  assumes dcu_stable: \"disj_countable_union_stable M\"\n      and c_stable: \"complement_stable \\<Omega> M\"\n      and empty_in: \"{} \\<in> M\"\n      and M_pow: \"M \\<subseteq> Pow \\<Omega>\"\n    shows \"non_decreasing_union_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using empty_in by auto \n\n  moreover have \"\\<forall>A. (range A \\<subseteq> M \\<and> non_decreasing A) \\<longrightarrow> ((\\<Union>i::nat. A i) \\<in> M)\" \n  proof (rule allI; rule impI)\n    fix A :: \"nat \\<Rightarrow> 'a set\" \n    assume A_is_nondecreasing_within_M: \"range A \\<subseteq> M \\<and> non_decreasing A\"\n    let ?B = \"(\\<lambda>n. if n = 0 then A 0 else A n - A (n-1))\"\n\n    have \"disjoint_family ?B\"\n      by (simp add: A_is_nondecreasing_within_M non_dec_to_disj)\n       \n    moreover have sd_stable: \"set_diff_stable M\"\n      using assms dcu_c_empty_imp_sd_stable by auto\n    hence \"\\<forall>n. ?B n \\<in> M\" \n    proof - \n      have \"\\<forall>n. ?B n = A 0 \\<or> ?B n = A n - A (n-1)\"\n        by simp\n      moreover have \"\\<forall>n. A n \\<in> M\"\n        using A_is_nondecreasing_within_M by blast\n      ultimately show \"\\<forall>n. ?B n \\<in> M\"\n        using sd_stable unfolding set_diff_stable_def\n        by (simp add: A_is_nondecreasing_within_M non_decreasing_multistep) \n    qed\n    hence \"range ?B \\<subseteq> M\"\n      by blast\n        \n    ultimately have \"((\\<Union>i::nat. ?B i) \\<in> M)\"\n      using dcu_stable unfolding disj_countable_union_stable_def by blast\n\n    moreover have \"\\<Union> (range A) = (\\<Union>i. ?B i)\"\n      by (simp add: A_is_nondecreasing_within_M non_dec_to_disj_same_cu)\n\n    ultimately show \"((\\<Union>i. A i) \\<in> M)\"\n      by simp \n  qed \n\n  ultimately show ?thesis\n    by (simp add: non_decreasing_union_stable_def)\nqed\n\n\ndefinition non_increasing_inter_stable :: \"'a set set \\<Rightarrow> bool\"\n  where \"non_increasing_inter_stable M = \n        ((M \\<noteq> {}) \\<and> (\\<forall>A. (range A \\<subseteq> M \\<and> non_increasing A) \\<longrightarrow> ((\\<Inter>i::nat. A i) \\<in> M)))\"\n\nlemma ci_imp_nii_stable: \n  assumes ci_stable: \"countable_inter_stable M\"\n  shows \"non_increasing_inter_stable M\"\n  using ci_stable unfolding countable_inter_stable_def non_increasing_inter_stable_def by simp \n\nlemma ndu_c_imp_nii_stable: \n  assumes ndu_stable: \"non_decreasing_union_stable M\"\n      and c_stable: \"complement_stable \\<Omega> M\"\n      and M_pow: \"M \\<subseteq> Pow \\<Omega>\"\n    shows \"non_increasing_inter_stable M\"\nproof - \n  have \"M \\<noteq> {}\"\n    using c_stable complement_stable_def by auto\n\n  moreover have \"\\<forall>A. range A \\<subseteq> M \\<and> non_increasing A \\<longrightarrow> \\<Inter> (range A) \\<in> M\"\n  proof (rule; rule)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    let ?B = \"(\\<lambda>n. \\<Omega> - A n)\"\n    assume A_non_inc_within_M: \"range A \\<subseteq> M \\<and> non_increasing A\"\n\n    hence \"non_decreasing ?B\" \n      unfolding non_increasing_def non_decreasing_def by auto \n    moreover have \"range ?B \\<subseteq> M\"\n      using A_non_inc_within_M c_stable complement_stable_def by blast  \n    ultimately have \"\\<Union> (range ?B) \\<in> M\" \n      using ndu_stable unfolding non_decreasing_union_stable_def by blast \n    hence \"\\<Omega> - \\<Union> (range ?B) \\<in> M\" \n      using c_stable unfolding complement_stable_def by auto \n\n    moreover have \"\\<Inter> (range A) = \\<Omega> - \\<Union> (range ?B)\" \n    proof (rule ; rule)\n      fix x\n      assume \"x \\<in> \\<Inter> (range A)\"\n      hence x_in_all: \"\\<forall>n. x \\<in> A n\"\n        by blast \n      moreover have \"\\<forall>n. A n \\<in> M\"\n        by (simp add: A_non_inc_within_M range_subsetD) \n      ultimately have \"x \\<in> \\<Omega>\" \n        using M_pow by auto \n         \n      moreover have \"x \\<notin> (\\<Union>n. \\<Omega> - A n)\"\n        by (simp add: x_in_all) \n\n      ultimately show \"x \\<in> \\<Omega> - (\\<Union>n. \\<Omega> - A n)\" \n        by auto \n    next \n      fix x\n      assume \"x \\<in> \\<Omega> - (\\<Union>n. \\<Omega> - A n)\" \n      thus \"x \\<in> \\<Inter> (range A)\"\n        by simp  \n    qed \n\n    ultimately show \"\\<Inter> (range A) \\<in> M\"\n      by presburger \n  qed\n\n  ultimately show ?thesis \n    unfolding non_increasing_inter_stable_def by auto \nqed\n\n\nsubsection \"Algebras and Systems\"\n\nsubsubsection \"Exemplary Set Collections\"\n\ntext \"For now, these are just some famous types of set collections that people choose when they want\nto prove something and need a convenient set to do it. We'll soon see what they're useful for.\n\nThe following proofs will be pretty easy. The heavy lifting was done in the previous subsection.\"\n\nlemma algebra_omega_c_fu_stable: \n  shows \"algebra \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M)\"\nproof \n  assume alg: \"algebra \\<Omega> M\"\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> {} \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\"\n    using algebra_iff_Un complement_stable_def finite_union_stable_def by fastforce\n  moreover have \"\\<Omega> \\<in> M\"\n    by (simp add: alg algebra.top) \n  ultimately show \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\" \n    by simp \nnext \n  assume \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\"\n  moreover have \"{} \\<in> M\"\n    using calculation complement_stable_def Diff_cancel by metis \n  ultimately show \"algebra \\<Omega> M\" \n    by (simp add: algebra_iff_Un complement_stable_def finite_union_stable_def) \nqed \n\nlemma algebra_omega_c_fi_stable: \n  shows \"algebra \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_inter_stable M)\"\nproof \n  assume \"algebra \\<Omega> M\"\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\"\n    by (simp add: algebra_omega_c_fu_stable)\n  thus \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_inter_stable M\"\n    by (meson Pow_iff c_fu_imp_fi_stable subset_iff)\nnext \n  assume \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_inter_stable M\"\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\"\n    by (meson PowD c_fi_imp_fu_stable subset_eq)\n  thus \"algebra \\<Omega> M\"\n    by (simp add: algebra_omega_c_fu_stable)\nqed \n\nlemma sigma_algebra_omega_c_cu_stable: \n  shows \"sigma_algebra \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_union_stable M)\"\nproof -\n  have \"sigma_algebra \\<Omega> M = (algebra \\<Omega> M \\<and> (\\<forall>A. range A \\<subseteq> M \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M))\"\n    using sigma_algebra_iff by simp \n  hence \"sigma_algebra \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\n        \\<and> (\\<forall>A. range A \\<subseteq> M \\<longrightarrow> (\\<Union>i::nat. A i) \\<in> M))\"\n    by (simp add: algebra_omega_c_fu_stable)\n  thus ?thesis\n    by (metis countable_union_stable_def empty_iff cu_imp_fu_stable)\nqed\n\nlemma sigma_algebra_omega_c_ci_stable: \n  shows \"sigma_algebra \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_inter_stable M)\"\nproof \n  assume \"sigma_algebra \\<Omega> M\"\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_union_stable M\"\n    by (simp add: sigma_algebra_omega_c_cu_stable)\n  thus \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_inter_stable M\"\n    by (meson Pow_iff c_cu_imp_ci_stable subset_iff)\nnext \n  assume \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_inter_stable M\"\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_union_stable M\"\n    by (meson PowD c_ci_imp_cu_stable subset_eq)\n  thus \"sigma_algebra \\<Omega> M\"\n    by (simp add: sigma_algebra_omega_c_cu_stable)\nqed\n\nlemma sigma_sd_stable: \n  assumes sa: \"sigma_algebra \\<Omega> M\"\n  shows \"set_diff_stable M\"\n  by (meson c_fu_omega_imp_sd_stable cu_imp_fu_stable sa sigma_algebra_omega_c_cu_stable)\n\nlemma empty_in_sigma: \n  assumes sa: \"sigma_algebra \\<Omega> M\"\n  shows \"{} \\<in> M\"\nproof - \n  have \"\\<Omega> - \\<Omega> \\<in> M\"\n    using sigma_algebra_omega_c_ci_stable sa unfolding complement_stable_def by blast \n  thus ?thesis \n    by auto \nqed \n\nlocale monotone_class = subset_class + \n  assumes ndu_stable: \"non_decreasing_union_stable M\"\n      and ncdi_stable: \"non_increasing_inter_stable M\"\n\nlemma monotone_classI:\n  assumes \"M \\<subseteq> Pow \\<Omega>\"\n      and \"non_decreasing_union_stable M\"\n      and \"non_increasing_inter_stable M\"\n    shows \"monotone_class \\<Omega> M\"\n  by (simp add: assms monotone_class_axioms.intro monotone_class_def subset_class.intro)\n\nlemma monotone_class_trivial:\n  shows \"monotone_class A (Pow A)\"\n  by (meson cu_imp_ndu_stable monotone_classI ndu_c_imp_nii_stable sigma_algebra_Pow \n      sigma_algebra_omega_c_cu_stable)\n\nlocale pi_system = subset_class + \n  assumes fi_stable: \"finite_inter_stable M\"\n\nlemma pi_systemI:\n  assumes \"M \\<subseteq> Pow \\<Omega>\"\n      and \"finite_inter_stable M\"\n    shows \"pi_system \\<Omega> M\"\n  by (simp add: assms pi_system.intro pi_system_axioms.intro subset_class.intro)\n\nlemma Dynkin_omega_c_disju_stable:\n  shows \"Dynkin_system \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> disj_countable_union_stable M)\"\nproof - \n  have \"Dynkin_system \\<Omega> M = (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> (\\<forall>A. A \\<in> M \\<longrightarrow> \\<Omega> - A \\<in> M) \\<and> \n       (\\<forall>A::nat \\<Rightarrow> 'a set. disjoint_family A \\<longrightarrow> range A \\<subseteq> M \\<longrightarrow> \\<Union> (range A) \\<in> M))\"\n    unfolding Dynkin_system_def Dynkin_system_axioms_def subset_class_def by fast \n  thus ?thesis \n    using complement_stable_def disj_countable_union_stable_def empty_iff by metis\nqed\n\ntext \"We show an equivalent definition of a Dynkin system.\"\nlemma Dynkin_omega_diff_ndu_stable:\n  shows \"Dynkin_system \\<Omega> M = \n         (M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> set_diff_stable M \\<and> non_decreasing_union_stable M)\"\nproof\n  assume dynk: \"Dynkin_system \\<Omega> M\"\n  hence \"{} \\<in> M\"\n    by (simp add: Dynkin_system.empty)\n  thus \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> set_diff_stable M \\<and> non_decreasing_union_stable M\"\n    by (metis Dynkin_omega_c_disju_stable dcu_c_empty_imp_ndu_stable dcu_c_empty_imp_sd_stable dynk)\nnext\n  assume \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> set_diff_stable M \\<and> non_decreasing_union_stable M\"\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> disj_countable_union_stable M\"\n    using sd_omega_imp_c_stable sd_omega_imp_ndu_stable by auto\n  thus \"Dynkin_system \\<Omega> M\"\n    using Dynkin_omega_c_disju_stable by auto \nqed \n\nsubsubsection \"Relations between Set Collections\"\n\ntheorem algebra_is_pi:\n  assumes a: \"algebra \\<Omega> M\"\n  shows \"pi_system \\<Omega> M\"\nproof - \n  have \"subset_class \\<Omega> M\"\n    by (meson algebra_omega_c_fi_stable a subset_class.intro)\n  moreover have \"finite_inter_stable M\"\n    using algebra_omega_c_fi_stable a by blast  \n  ultimately show ?thesis\n    by (simp add: pi_system.intro pi_system_axioms.intro) \nqed\n\ntheorem sigma_is_algebra: \n  assumes sa: \"sigma_algebra \\<Omega> M\"\n  shows \"algebra \\<Omega> M\"\nproof - \n  have \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_union_stable M\"\n    by (meson sa sigma_algebra_omega_c_cu_stable)\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> finite_union_stable M\"\n    by (simp add: cu_imp_fu_stable)\n  thus ?thesis\n    by (simp add: algebra_omega_c_fu_stable) \nqed\n\ntheorem sigma_is_mono: \n  assumes sa: \"sigma_algebra \\<Omega> M\"\n  shows \"monotone_class \\<Omega> M\"\nproof - \n  have sa_properties: \"M \\<subseteq> Pow \\<Omega> \\<and> complement_stable \\<Omega> M \\<and> countable_union_stable M\"\n    using sa sigma_algebra_omega_c_cu_stable by auto\n\n  hence \"M \\<subseteq> Pow \\<Omega>\"\n    by simp\n  moreover have \"non_decreasing_union_stable M\"\n    by (simp add: cu_imp_ndu_stable sa_properties)\n  moreover have \"non_increasing_inter_stable M\"\n    using sa_properties calculation ndu_c_imp_nii_stable by auto\n\n  ultimately show ?thesis\n    unfolding monotone_class_def monotone_class_axioms_def subset_class_def by auto \nqed\n\ntheorem algebra_is_sigma_iff_mono: \n  assumes a: \"algebra \\<Omega> M\"\n  shows \"sigma_algebra \\<Omega> M = monotone_class \\<Omega> M\"\nproof \n  assume \"sigma_algebra \\<Omega> M\"\n  thus \"monotone_class \\<Omega> M\"\n    by (simp add: sigma_is_mono) \nnext\n  assume \"monotone_class \\<Omega> M\"\n  hence \"{} \\<in> M \\<and> finite_union_stable M \\<and> non_decreasing_union_stable M\"\n    by (metis algebra_iff_Int algebra_omega_c_fu_stable a monotone_class.ndu_stable)\n  hence \"countable_union_stable M\"\n    by (simp add: ndu_fu_imp_cu_stable)  \n  thus \"sigma_algebra \\<Omega> M\"\n    by (meson algebra_omega_c_fi_stable a sigma_algebra_omega_c_cu_stable) \nqed\n\ntheorem sigma_is_Dynkin:\n  assumes sa: \"sigma_algebra \\<Omega> M\"\n  shows \"Dynkin_system \\<Omega> M\"\nproof - \n\n  have \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M\"\n    by (metis sa sigma_algebra_omega_c_cu_stable)\n\n  moreover have \"finite_union_stable M\"\n    using cu_imp_fu_stable sa sigma_algebra_omega_c_cu_stable by auto\n\n  moreover have \"complement_stable \\<Omega> M\"\n    using sa sigma_algebra_omega_c_cu_stable by auto  \n  hence \"set_diff_stable M\"\n    using c_fu_omega_imp_sd_stable calculation\n    by auto \n\n  ultimately show ?thesis\n    by (simp add: sa sigma_algebra_imp_Dynkin_system)\nqed \n\ntheorem Dynkin_is_sigma_iff_pi: \n  assumes dynk: \"Dynkin_system \\<Omega> M\"\n  shows \"sigma_algebra \\<Omega> M = pi_system \\<Omega> M\"\nproof \n  assume \"sigma_algebra \\<Omega> M\"\n  thus \"pi_system \\<Omega> M\"\n    by (simp add: algebra_is_pi sigma_is_algebra)\nnext \n  assume \"pi_system \\<Omega> M\"\n  hence \"finite_inter_stable M \\<and> complement_stable \\<Omega> M \\<and> (\\<forall>S\\<in>M. S \\<subseteq> \\<Omega>) \\<and> non_decreasing_union_stable M\"\n    using dynk Dynkin_omega_diff_ndu_stable Dynkin_omega_c_disju_stable \n    unfolding pi_system_def pi_system_axioms_def by blast \n  hence \"finite_union_stable M \\<and> non_decreasing_union_stable M\"\n    using c_fi_imp_fu_stable by auto \n  hence \"countable_union_stable M\"\n    by (simp add: ndu_fu_imp_cu_stable) \n\n  moreover have \"M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M\"\n    by (metis Dynkin_omega_c_disju_stable dynk)\n \n  ultimately show \"sigma_algebra \\<Omega> M\"\n    using sigma_algebra_omega_c_cu_stable by auto\nqed\n\ntheorem Dynkin_is_mono:\n  assumes dynk: \"Dynkin_system \\<Omega> M\"\n  shows \"monotone_class \\<Omega> M\"\nproof - \n  have \"M \\<subseteq> Pow \\<Omega> \\<and> complement_stable \\<Omega> M \\<and> non_decreasing_union_stable M\"\n    by (meson Dynkin_omega_c_disju_stable Dynkin_omega_diff_ndu_stable dynk)\n  hence \"M \\<subseteq> Pow \\<Omega> \\<and> non_decreasing_union_stable M \\<and> non_increasing_inter_stable M\"\n    using ndu_c_imp_nii_stable by auto\n  thus ?thesis\n    by (simp add: monotone_class.intro monotone_class_axioms.intro subset_class.intro) \nqed\n\ntheorem sigma_Pow_is_sigma:\n  assumes sa: \"sigma_algebra \\<Omega> M\"\n      and subseq: \"S \\<in> M\"\n    shows \"sigma_algebra S (Pow S)\"\nproof - \n  have \"complement_stable S (Pow S)\" \n    unfolding complement_stable_def by (simp add: Pow_not_empty complement_stable_def)\n  moreover have \"countable_union_stable (Pow S)\" \n    unfolding countable_union_stable_def by blast \n  ultimately show ?thesis\n    by (simp add: sigma_algebra_omega_c_cu_stable) \nqed \n\ntheorem sigma_inter_is_sigma:\n  assumes sas: \"\\<forall>M\\<in>X. sigma_algebra \\<Omega> M\"\n      and non_empty: \"X \\<noteq> {}\"\n    shows \"sigma_algebra \\<Omega> (\\<Inter>M\\<in>X. M)\"\nproof - \n  let ?I = \"(\\<Inter>M\\<in>X. M)\"\n\n  have sa_properties: \"\\<forall>M\\<in>X. M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> complement_stable \\<Omega> M \\<and> countable_union_stable M\"\n    by (meson sas sigma_algebra_omega_c_cu_stable)\n\n  have \"?I \\<subseteq> Pow \\<Omega>\" \n  proof \n    fix x\n    assume \"x \\<in> ?I\"\n    then obtain M where \"M \\<in> X \\<and> x \\<in> M\" \n      using non_empty by auto \n    thus \"x \\<in> Pow \\<Omega>\"\n      using sa_properties by auto \n  qed \n\n  moreover have \"\\<Omega> \\<in> ?I\"  \n    using sa_properties by simp \n \n  moreover have \"complement_stable \\<Omega> ?I\" \n    using sa_properties unfolding complement_stable_def by blast\n\n  moreover have \"countable_union_stable ?I\" \n    unfolding countable_union_stable_def \n  proof \n    show \"?I \\<noteq> {}\"\n      using calculation(2) by auto\n  next \n    show \"\\<forall>A :: (nat \\<Rightarrow> 'a set). range A \\<subseteq> ?I \\<longrightarrow> \\<Union> (range A) \\<in> ?I\"\n      using sa_properties unfolding countable_union_stable_def\n      by (simp add: le_Inf_iff) \n  qed\n\n  ultimately show ?thesis\n    by (simp add: sigma_algebra_omega_c_cu_stable)\nqed\n\nlemma Dynkin_inter_is_Dynkin:\n  assumes dynks: \"\\<forall>M\\<in>X. Dynkin_system \\<Omega> M\"\n      and non_empty: \"X \\<noteq> {}\"\n    shows \"Dynkin_system \\<Omega> (\\<Inter>M\\<in>X. M)\"\nproof - \n  let ?I = \"(\\<Inter>M\\<in>X. M)\"\n\n  have dy_properties: \"\\<forall>M\\<in>X. M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> M \\<and> set_diff_stable M \\<and> non_decreasing_union_stable M\"\n    by (metis Dynkin_omega_diff_ndu_stable dynks)\n\n  have \"?I \\<subseteq> Pow \\<Omega>\" \n  proof \n    fix x\n    assume \"x \\<in> ?I\"\n    then obtain M where \"M \\<in> X \\<and> x \\<in> M\" \n      using non_empty by auto \n    thus \"x \\<in> Pow \\<Omega>\"\n      using dy_properties by auto \n  qed \n\n  moreover have \"\\<Omega> \\<in> ?I\"  \n    using dy_properties by simp \n \n  moreover have \"set_diff_stable ?I\" \n    using dy_properties unfolding set_diff_stable_def by auto \n\n  moreover have \"non_decreasing_union_stable ?I\" \n    unfolding non_decreasing_union_stable_def \n  proof \n    show \"?I \\<noteq> {}\"\n      using calculation(2) by auto\n  next \n    show \"\\<forall>A. range A \\<subseteq> ?I \\<and> non_decreasing A \\<longrightarrow> \\<Union> (range A) \\<in> ?I\"\n      using dy_properties unfolding non_decreasing_union_stable_def\n      by (simp add: le_Inf_iff) \n  qed\n\n  ultimately show ?thesis\n    by (simp add: Dynkin_omega_diff_ndu_stable)\nqed\n\ntheorem sigma_ndu_is_algebra:\n  assumes sas: \"\\<forall>n::nat. sigma_algebra \\<Omega> (X n)\"\n      and non_dec: \"non_decreasing X\"\n    shows \"algebra \\<Omega> (\\<Union>(range X))\"\nproof -\n  have a_properties: \"\\<forall>n. X n \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> X n \\<and> complement_stable \\<Omega> (X n) \\<and> countable_union_stable (X n)\"\n    by (meson sas sigma_algebra_omega_c_cu_stable)\n\n  hence \"(\\<Union>(range X)) \\<subseteq> Pow \\<Omega>\" \n    by fast \n\n  moreover have \"\\<Omega> \\<in> (\\<Union>(range X))\"\n    using a_properties by auto \n\n  moreover have \"complement_stable \\<Omega> (\\<Union>(range X))\"\n    using a_properties unfolding complement_stable_def by blast \n\n  moreover have \"finite_union_stable (\\<Union>(range X))\"\n    unfolding finite_union_stable_def \n  proof \n    show \"\\<Union> (range X) \\<noteq> {}\"\n      using calculation(2) by auto\n  next \n    have fu_stable: \"\\<forall>n. finite_union_stable (X n)\"\n      by (simp add: a_properties cu_imp_fu_stable)\n    show \"\\<forall>S\\<in>\\<Union> (range X). \\<forall>T\\<in>\\<Union> (range X). S \\<union> T \\<in> \\<Union> (range X)\"\n    proof (rule ; rule)\n      fix S T\n      assume \"S \\<in> \\<Union> (range X)\" and \"T \\<in> \\<Union> (range X)\"\n      then obtain n m where S_n: \"S \\<in> X n\" and T_m: \"T \\<in> X m\"\n        by blast\n      thus \"S \\<union> T \\<in> \\<Union> (range X)\"\n      proof (cases \"m \\<ge> n\")\n        case True\n        hence \"S \\<in> X m\"\n          by (meson S_n non_dec non_decreasing_stay_in)\n        thus \"S \\<union> T \\<in> \\<Union> (range X)\"\n          using fu_stable T_m unfolding finite_union_stable_def by auto \n      next\n        case False\n        hence \"T \\<in> X n\"\n          by (meson T_m nle_le non_dec non_decreasing_stay_in)  \n        thus \"S \\<union> T \\<in> \\<Union> (range X)\"\n          using fu_stable S_n unfolding finite_union_stable_def by auto \n      qed \n    qed\n  qed\n\n  ultimately show ?thesis\n    by (simp add: algebra_omega_c_fu_stable) \nqed\n\ntext \"If M is a \\<sigma>-algebra, and R \\<subseteq> \\<Omega>, then 'R \\<inter> M' = {R \\<inter> S : S \\<in> M} is a \\<sigma>-algebra on R.\"\n\ntheorem sigma_inter_coll_is_sigma:\n  assumes sa: \"sigma_algebra \\<Omega> M\"\n      and subseq: \"R \\<subseteq> \\<Omega>\"\n    shows \"sigma_algebra R {C. \\<exists>A \\<in> M. C = R \\<inter> A}\"\nproof - \n  let ?N = \"{C. \\<exists>S \\<in> M. C = R \\<inter> S}\"\n  have \"?N \\<subseteq> Pow R\"\n    by auto \n\n  moreover have \"\\<Omega> \\<in> M\"\n    using sigma_algebra_omega_c_ci_stable sa by auto \n  hence \"R \\<in> ?N\"\n    using subseq by auto \n\n  moreover have \"\\<forall>S\\<in>?N. R - S \\<in> ?N\" \n  proof \n    fix S\n    assume \"S \\<in> ?N\"\n    then obtain T where T_choice: \"T \\<in> M \\<and> S = R \\<inter> T\"\n      by blast\n    hence \"R - S = R \\<inter> (\\<Omega> - T)\"\n      using subseq by fast \n    moreover have \"\\<Omega> - T \\<in> M\"\n      using sigma_algebra_omega_c_ci_stable T_choice sa unfolding complement_stable_def by fast \n    ultimately show \"R - S \\<in> ?N\" \n      by auto \n  qed\n  hence \"complement_stable R ?N\" \n    using calculation(2) unfolding complement_stable_def by auto \n\n  moreover have \"\\<forall>A :: (nat \\<Rightarrow> 'a set). range A \\<subseteq> ?N \\<longrightarrow> \\<Union> (range A) \\<in> ?N\"\n  proof (rule ; rule)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume \"range A \\<subseteq> ?N\"\n    hence \"\\<forall>n. \\<exists>S \\<in> M. A n = R \\<inter> S\"\n      by auto \n    then obtain B where B_choice: \"\\<forall>n. ((A n = R \\<inter> B n) \\<and> (B n \\<in> M))\"\n      by metis \n\n    hence \"\\<Union>(range A) = R \\<inter> \\<Union>(range B)\" \n      by blast \n\n    moreover have \"range B \\<subseteq> M\"\n      using B_choice by auto \n    hence \"\\<Union>(range B) \\<in> M\" \n      using sa sigma_algebra_omega_c_cu_stable unfolding countable_union_stable_def by blast \n\n    ultimately show \"\\<Union> (range A) \\<in> ?N\"\n      by auto  \n  qed \n  hence \"countable_union_stable ?N\" \n    using calculation(2) unfolding countable_union_stable_def by auto\n\n  ultimately show \"sigma_algebra R ?N\"\n    by (simp add: sigma_algebra_omega_c_cu_stable)\nqed\n\ntext \"If \\<Omega> and \\<Omega>' are sets, M' a \\<sigma>-algebra on \\<Omega>' and T: \\<Omega> \\<rightarrow> \\<Omega>' a mapping, then the collection of \npreimages of sets in M' is a \\<sigma>-algebra on \\<Omega>.\"\n\ntheorem preimage_sigma_on_domain: \n  fixes f :: \"'a \\<Rightarrow> 'b\"\n  assumes sa: \"sigma_algebra \\<Omega>' M'\"\n    shows \"sigma_algebra (preimage f \\<Omega>') {R. \\<exists>S'\\<in>M'. R = preimage f S'}\"\nproof - \n  let ?N = \"{R. \\<exists>S'\\<in>M'. R = preimage f S'}\"\n  let ?\\<Omega> = \"preimage f \\<Omega>'\"\n\n  have \"?N \\<subseteq> Pow ?\\<Omega>\" \n  proof \n    fix S\n    assume \"S \\<in> ?N\"\n    hence \"\\<exists>S'\\<in>M'. S = preimage f S'\"\n      by simp\n    then obtain S' where \"S = preimage f S'\" and \"S' \\<subseteq> \\<Omega>'\"\n      using sa sigma_algebra_omega_c_cu_stable PowD subsetD by metis \n    thus \"S \\<in> Pow ?\\<Omega>\"\n      unfolding preimage_def by auto \n  qed \n\n  moreover have \"?\\<Omega> \\<in> ?N\"\n    using sa sigma_algebra_omega_c_cu_stable by auto\n\n  moreover have \"(\\<forall>S\\<in>?N. ?\\<Omega> - S \\<in> ?N)\"\n  proof \n    fix S\n    assume \"S \\<in> ?N\"\n    then obtain S' where S'_M': \"S' \\<in> M'\" and \"S = preimage f S'\"\n      by blast\n    hence \"?\\<Omega> - S = (preimage f \\<Omega>') - (preimage f S')\"\n      by simp\n    hence \"?\\<Omega> - S = preimage f (\\<Omega>' - S')\"\n      by (simp add: preimage_set_diff)  \n    moreover have \"(\\<Omega>' - S') \\<in> M'\" \n      using sigma_algebra_omega_c_ci_stable sa S'_M' unfolding complement_stable_def by blast\n    ultimately show \"?\\<Omega> - S \\<in> ?N \"\n      by auto\n  qed \n  hence \"complement_stable ?\\<Omega> ?N\"\n    unfolding complement_stable_def using calculation(2) by blast \n\n  moreover have \"\\<forall>A :: nat \\<Rightarrow> 'a set. range A \\<subseteq> ?N \\<longrightarrow> \\<Union> (range A) \\<in> ?N\"\n  proof (rule ; rule)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume \"range A \\<subseteq> ?N\" \n    hence \"\\<forall>n. \\<exists>S'\\<in>M'. A n = preimage f S'\" \n      by auto \n    then obtain B where B_choice: \"\\<forall>n. B n \\<in> M' \\<and> A n = preimage f (B n)\"\n      by metis \n    hence \"\\<Union>(range A) = (\\<Union>S\\<in>(range B). preimage f S)\" \n      by simp  \n    hence \"\\<Union>(range A) = preimage f (\\<Union>(range B))\"\n      using preimage_union by metis \n    moreover have \"range B \\<subseteq> M'\"\n      by (simp add: B_choice image_subsetI)\n    hence \"(\\<Union>(range B)) \\<in> M'\"\n      using sa sigma_algebra_omega_c_cu_stable B_choice unfolding countable_union_stable_def by auto  \n    ultimately show  \"\\<Union> (range A) \\<in> ?N\"\n      by blast\n  qed \n  hence \"countable_union_stable ?N\"\n    unfolding countable_union_stable_def using calculation(2) by blast \n\n  ultimately show \"sigma_algebra ?\\<Omega> ?N\"\n    by (simp add: sigma_algebra_omega_c_cu_stable)\nqed \n\ntext \"For the infinite set \\<Omega>, M consists of all S \\<subseteq> \\<Omega>, such that either S or -S is finite, then \nM is an algebra...\"\n\nlemma finite_cofinite_algebra:\n  assumes infinite_ground: \"infinite \\<Omega>\"\n  shows \"algebra \\<Omega> {S. S \\<subseteq> \\<Omega> \\<and> (finite S \\<or> finite (\\<Omega>-S))}\"\nproof - \n  let ?M = \"{S. S \\<subseteq> \\<Omega> \\<and> (finite S \\<or> finite (\\<Omega>-S))}\"\n  \n  have \"?M \\<subseteq> Pow \\<Omega> \\<and> \\<Omega> \\<in> ?M\"\n    by auto  \n\n  moreover have \"(\\<forall>S\\<in>?M. \\<Omega> - S \\<in> ?M)\"  \n  proof \n    fix S \n    assume S_in_M: \"S \\<in> ?M\"\n    thus \"\\<Omega> - S \\<in> ?M\"\n    proof (cases \"finite S\")\n      case True\n      hence \"finite (\\<Omega>-(\\<Omega>-S))\"\n        by (simp add: Diff_Diff_Int)\n      then show ?thesis\n        by simp \n    next\n      case False\n      then show ?thesis\n        using S_in_M by auto\n    qed\n  qed\n  hence \"complement_stable \\<Omega> ?M\" \n    unfolding complement_stable_def by blast  \n  \n  moreover have \"(\\<forall>S\\<in>?M. \\<forall>T\\<in>?M. S \\<inter> T \\<in> ?M)\" \n  proof (rule ; rule)\n    fix S T assume S_in_M: \"S \\<in> ?M\" and T_in_M: \"T \\<in> ?M\"\n    then consider (F) \"finite S \\<or> finite T\"  | (II) \"infinite S \\<and> infinite T\"\n      by auto\n    thus \"S \\<inter> T \\<in> ?M\"\n    proof cases\n      case F\n      then show ?thesis\n        using S_in_M by blast \n    next\n      case II\n      consider (fin_int) \"finite (S \\<inter> T)\" | (inf_int) \"infinite (S \\<inter> T)\"\n        by fast \n      then show ?thesis \n      proof cases\n        case fin_int\n        then show ?thesis\n          using S_in_M by auto \n      next\n        case inf_int\n        moreover have \"finite (\\<Omega> - S)\"\n          using II S_in_M by auto\n        moreover have \"finite (\\<Omega> - T)\"\n          using II T_in_M by auto\n        moreover have \"\\<Omega> - (S \\<inter> T) = (\\<Omega> - S) \\<union> (\\<Omega> - T)\"\n          by auto \n        ultimately show ?thesis\n          using S_in_M by auto \n      qed \n    qed \n  qed \n  hence \"finite_inter_stable ?M\"\n    unfolding finite_inter_stable_def by blast \n\n  ultimately show \"algebra \\<Omega> ?M\"\n    by (simp add: algebra_omega_c_fi_stable) \nqed\n\ntext \"...but not a \\<sigma>-algebra.\"\n\nlemma finite_cofinite_no_sigma:\n  assumes infinite_ground: \"infinite \\<Omega>\"\n  shows \"\\<not>sigma_algebra \\<Omega> {S. S \\<subseteq> \\<Omega> \\<and> (finite S \\<or> finite (\\<Omega>-S))}\"\nproof - \n  let ?M = \"{S. S \\<subseteq> \\<Omega> \\<and> (finite S \\<or> finite (\\<Omega>-S))}\"\n\n  have \"\\<exists>A :: (nat \\<Rightarrow> 'a set). range A \\<subseteq> ?M \\<and> \\<Union> (range A) \\<notin> ?M\"\n  proof (cases \"countable \\<Omega>\")\n    case True\n    then obtain f :: \"nat \\<Rightarrow> 'a\" where f_sur: \"range f = \\<Omega>\" and f_inj: \"inj f\"\n      by (metis countable_as_injective_image infinite_ground)\n    let ?E = \"(\\<lambda>n::nat. 2 * n) ` UNIV\"\n    let ?O = \"(\\<lambda>n::nat. 2 * n + 1) ` UNIV\"\n    let ?A = \"(\\<lambda>n. if n\\<in>?E then {f n} else {})\"\n\n    have \"\\<Union> (range ?A) = image f ?E\"\n      by auto\n\n    moreover have \"infinite (image f ?E)\"\n      using f_inj inj_infinite_image even_inf by blast\n\n    moreover have \"?O = UNIV - ?E\"\n      by (metis even_odd_disjoint even_odd_UNIV Diff_cancel \n          Diff_triv Int_Un_eq(2) Int_commute Un_Diff)\n    hence \"(\\<Omega> - image f ?E) = image f ?O\"\n      by (metis Compl_eq_Diff_UNIV f_inj image_set_diff f_sur)\n    hence \"infinite (\\<Omega> - image f ?E)\"  \n      using f_inj inj_infinite_image odd_inf by auto \n\n    ultimately have \"\\<Union> (range ?A) \\<notin> ?M\"\n      by auto \n\n    moreover have \"\\<forall>n. finite (?A n) \\<and> (?A n) \\<subseteq> \\<Omega>\"\n      using f_sur by auto\n    hence \"range ?A \\<subseteq> ?M\"\n      by blast \n\n    ultimately show ?thesis\n      by blast   \n  next\n    case False\n    obtain f :: \"nat \\<Rightarrow> 'a\" where f_range: \"range f \\<subseteq> \\<Omega>\" and f_inj: \"inj f\"\n      using infinite_countable_subset infinite_ground by blast\n    let ?A = \"(\\<lambda>n. {f n})\"\n\n    have \"\\<Union> (range ?A) = image f UNIV\"\n      by auto \n    moreover have \"infinite (image f UNIV)\" \n      using f_inj finite_imageD by auto \n    moreover have \"uncountable \\<Omega>\"\n      using False by auto \n    hence \"infinite (\\<Omega> - image f UNIV)\"\n      by (simp add: uncountable_infinite uncountable_minus_countable)   \n    ultimately have \"range ?A \\<subseteq> ?M \\<and> \\<Union> (range ?A) \\<notin> ?M\" \n      using f_range by auto \n    thus ?thesis \n      by meson  \n    qed\n    hence \"\\<not>(countable_union_stable ?M)\" \n      using countable_union_stable_def by (metis (no_types)) \n\n  thus \"\\<not>sigma_algebra \\<Omega> ?M\" \n    using sigma_algebra_omega_c_cu_stable by auto \nqed\n\nsection \"Generators\"\n\nsubsection \"Least Set Collections\"\n\nsubsubsection \"Least Sigma Algebras\"\n\n(* 'sigma_sets \\<Omega> M' describes the smallest sigma algebra containing all sets in M.\n   The LEAST operator guarantees uniqueness. *)\nlemma sigma_sets_Least: \n  assumes M_Pow: \"M \\<subseteq> Pow \\<Omega>\"\n  shows \"sigma_sets \\<Omega> M = (LEAST N. M \\<subseteq> N \\<and> sigma_algebra \\<Omega> N)\"\nproof - \n  have \"{N. M \\<subseteq> N \\<and> sigma_algebra \\<Omega> N} \\<noteq> {}\"\n    using sigma_algebra_Pow M_Pow by auto \n  hence \"sigma_algebra \\<Omega> (\\<Inter>N\\<in>{N. M \\<subseteq> N \\<and> sigma_algebra \\<Omega> N}. N)\"\n    by (metis (mono_tags, lifting) mem_Collect_eq sigma_inter_is_sigma)\n  hence \"(LEAST N. M \\<subseteq> N \\<and> sigma_algebra \\<Omega> N) = (\\<Inter>N\\<in>{N. M \\<subseteq> N \\<and> sigma_algebra \\<Omega> N}. N)\"\n    using inter_is_Least_if_P\n    by (metis (mono_tags, lifting) Inf_greatest image_ident mem_Collect_eq) \n  thus ?thesis \n    using sigma_sets_least_sigma_algebra M_Pow image_ident by metis \nqed\n\ncorollary\n  assumes M_Pow: \"M \\<subseteq> Pow \\<Omega>\"\n  shows \"sigma_algebra \\<Omega> (sigma_sets \\<Omega> M)\"\n  by (simp add: assms sigma_algebra_sigma_sets)\n\ndefinition generates_sigma_algebra :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\"\n  where \"generates_sigma_algebra N \\<Omega> M = (M = sigma_sets \\<Omega> N)\"\n\nsubsubsection \"Least Dynkin systems\"\n\nlemma Dynkin_Least:\n  assumes M_Pow: \"M \\<subseteq> Pow \\<Omega>\"\n  shows \"Dynkin \\<Omega> M = (LEAST N. M \\<subseteq> N \\<and> Dynkin_system \\<Omega> N)\"\nproof - \n  have \"{N. M \\<subseteq> N \\<and> Dynkin_system \\<Omega> N} \\<noteq> {}\"\n    using Dynkin_system_trivial M_Pow by auto\n  hence \"Dynkin_system \\<Omega> (\\<Inter>N\\<in>{N. M \\<subseteq> N \\<and> Dynkin_system \\<Omega> N}. N)\"\n    by (metis (mono_tags, lifting) Dynkin_inter_is_Dynkin mem_Collect_eq)\n  hence \"(LEAST N. M \\<subseteq> N \\<and> Dynkin_system \\<Omega> N) = (\\<Inter>N\\<in>{N. M \\<subseteq> N \\<and> Dynkin_system \\<Omega> N}. N)\"\n    using inter_is_Least_if_P\n    by (metis (mono_tags, lifting) INT_greatest mem_Collect_eq)\n  thus ?thesis\n    by (metis (mono_tags, lifting) Collect_cong Dynkin_def image_ident) \nqed\n\ncorollary\n  assumes M_Pow: \"M \\<subseteq> Pow \\<Omega>\"\n  shows \"Dynkin_system \\<Omega> (Dynkin \\<Omega> M)\"\n  by (simp add: Dynkin_system_Dynkin assms)\n\ndefinition generates_dynkin_system :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\"\n  where \"generates_dynkin_system N \\<Omega> M = (M = Dynkin \\<Omega> N)\"\n\nsubsubsection \"Least Monotone classes\"\n\ndefinition Mono :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> 'a set set\" where\n  \"Mono \\<Omega> M =  (\\<Inter>{N. monotone_class \\<Omega> N \\<and> M \\<subseteq> N})\"\n\nlemma monotone_class_Mono:\n  assumes M_Pow: \"M \\<subseteq> Pow (\\<Omega>)\"\n      and non_empty: \"M \\<noteq> {}\"\n  shows \"monotone_class \\<Omega> (Mono \\<Omega> M)\"\nproof (rule monotone_classI)\n  show \"Mono \\<Omega> M \\<subseteq> Pow \\<Omega>\"\n  proof \n    fix x \n    assume \"x \\<in> Mono \\<Omega> M\"\n    then obtain N where \"monotone_class \\<Omega> N \\<and> x \\<in> N\"\n      by (metis (no_types, lifting) Inter_iff Mono_def M_Pow mem_Collect_eq monotone_class_trivial)\n    thus \"x \\<in> Pow \\<Omega>\"\n      by (meson PowI monotone_class_def subset_class.sets_into_space)  \n  qed \nnext\n  have \"\\<forall>A. range A \\<subseteq> Mono \\<Omega> M \\<and> non_decreasing A \\<longrightarrow> \\<Union> (range A) \\<in> Mono \\<Omega> M\"\n  proof (rule ; rule ; erule conjE)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume A_range: \"range A \\<subseteq> Mono \\<Omega> M\" and A_nd: \"non_decreasing A\"\n    thus \"\\<Union> (range A) \\<in> Mono \\<Omega> M\" \n      unfolding Mono_def monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n      by blast \n  qed \n  thus \"non_decreasing_union_stable (Mono \\<Omega> M)\"\n    unfolding non_decreasing_union_stable_def Mono_def \n    using monotone_class_trivial M_Pow non_empty by blast \nnext\n  have \"\\<forall>A. range A \\<subseteq> Mono \\<Omega> M \\<and> non_increasing A \\<longrightarrow> \\<Inter> (range A) \\<in> Mono \\<Omega> M\"\n  proof (rule ; rule ; erule conjE)\n    fix A :: \"nat \\<Rightarrow> 'a set\"\n    assume A_range: \"range A \\<subseteq> Mono \\<Omega> M\" and A_ni: \"non_increasing A\"\n    thus \"\\<Inter> (range A) \\<in> Mono \\<Omega> M\"\n      unfolding Mono_def monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n      by blast \n  qed \n  thus \"non_increasing_inter_stable (Mono \\<Omega> M)\"\n    unfolding non_increasing_inter_stable_def Mono_def \n    using monotone_class_trivial M_Pow non_empty by blast \nqed\n\nlemma Mono_Least:\n  assumes M_Pow: \"M \\<subseteq> Pow \\<Omega>\"\n      and non_empty: \"M \\<noteq> {}\"\n  shows \"Mono \\<Omega> M = (LEAST N. M \\<subseteq> N \\<and> monotone_class \\<Omega> N)\"\nproof - \n  have \"monotone_class \\<Omega> (\\<Inter> {N. monotone_class \\<Omega> N \\<and> M \\<subseteq> N})\"\n    using assms monotone_class_Mono unfolding Mono_def by blast \n  hence \"(LEAST N. M \\<subseteq> N \\<and> monotone_class \\<Omega> N) = (\\<Inter>N\\<in>{N. M \\<subseteq> N \\<and> monotone_class \\<Omega> N}. N)\"\n    using inter_is_Least_if_P\n    by (smt (verit) image_ident le_Inf_iff mem_Collect_eq set_eq_subset)\n  thus ?thesis\n    by (metis (mono_tags, lifting) Collect_cong Mono_def image_ident)\nqed\n\ndefinition generates_monotone_class :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\"\n  where \"generates_monotone_class N \\<Omega> M = (M = Mono \\<Omega> N)\"\n\nsubsection \"Relations between least collections\"\n\ntext \"If M = A, a single set, then \\<sigma>{M} = \\<sigma>{A} = {{}, A, \\<Omega>-A, \\<Omega>}.\"\ncorollary\n  assumes subseq: \"A \\<subseteq> \\<Omega>\"\n  shows \"sigma_sets \\<Omega> {A} = {{}, A, \\<Omega>-A, \\<Omega>}\"\n  by (simp add: sigma_sets_singleton subseq)\n\ntext \"If M is a \\<sigma>-algebra, then \\<sigma>{M} = M\"\ncorollary \n  assumes \"sigma_algebra \\<Omega> M\"\n  shows \"sigma_sets \\<Omega> M = M\"\n  by (simp add: assms sigma_algebra.sigma_sets_eq)\n\ntext \"Let M be an algebra. Then \\<MM>(M) = \\<sigma>(M).\"\ntheorem monotone_class_theorem:\n  assumes alg: \"algebra \\<Omega> M\"\n  shows \"Mono \\<Omega> M = sigma_sets \\<Omega> M\"\nproof \n  text \"Since every \\<sigma>-algebra is a monotone class and \\<MM>(M) is the minimal monotone class containing\n        M, we know from the outset that \\<MM>(M) \\<subseteq> \\<sigma>(M).\"\n  have \"sigma_algebra \\<Omega> (sigma_sets \\<Omega> M)\"\n    by (metis algebra_iff_Un assms sigma_algebra_sigma_sets)\n  hence \"monotone_class \\<Omega> (sigma_sets \\<Omega> M)\"\n    by (simp add: sigma_is_mono)\n  moreover have \"M \\<subseteq> (sigma_sets \\<Omega> M)\"\n    by (simp add: sigma_sets_superset_generator)\n  moreover have M_non_empty_subseq: \"M \\<noteq> {} \\<and> M \\<subseteq> Pow \\<Omega>\"\n    using algebra.top alg algebra_iff_Int empty_iff by metis \n  hence Mono_least: \"Mono \\<Omega> M = (LEAST N. M \\<subseteq> N \\<and> monotone_class \\<Omega> N)\"\n    using Mono_Least by auto\n  ultimately show \"Mono \\<Omega> M \\<subseteq> sigma_sets \\<Omega> M\"\n    by (metis (mono_tags, lifting) Inter_lower Mono_def mem_Collect_eq) \nnext \n  have \"M \\<noteq> {} \\<and> M \\<subseteq> Pow \\<Omega>\"\n    using algebra.top alg algebra_iff_Int empty_iff by metis \n  hence mono_mono: \"monotone_class \\<Omega> (Mono \\<Omega> M)\"\n    by (simp add: monotone_class_Mono)\n  text \"To prove the opposite inclusion we must, due to the minimality of \\<sigma>{M}, prove that \\<MM>{M}\n        is a \\<sigma>-algebra, for which it is sufficient to prove that \\<MM>{M} is an algebra.\"\n  moreover have \"algebra \\<Omega> (Mono \\<Omega> M)\" \n  proof -\n    have mono_Pow: \"(Mono \\<Omega> M) \\<subseteq> Pow \\<Omega>\"\n      using mono_mono monotone_class_def subset_class_def by blast\n    moreover have M_subseq: \"M \\<subseteq> (Mono \\<Omega> M)\"\n      unfolding Mono_def by auto \n\n    (* \\<MM>(M) is complement-stable. *)\n    moreover have \"\\<forall>S\\<in>Mono \\<Omega> M. \\<forall>T\\<in>Mono \\<Omega> M. \\<Omega> - S \\<in> Mono \\<Omega> M \\<and> S \\<union> T \\<in> Mono \\<Omega> M\" \n    proof -\n      let ?\\<xi> = \"{S\\<in>Mono \\<Omega> M. \\<forall>T\\<in>M. S \\<union> T \\<in> Mono \\<Omega> M}\"\n      let ?\\<xi>' = \"{S\\<in>Mono \\<Omega> M. \\<Omega> - S \\<in> Mono \\<Omega> M}\"\n      let ?\\<xi>'' = \"{S\\<in>Mono \\<Omega> M. \\<forall>T\\<in>Mono \\<Omega> M. S \\<union> T \\<in> Mono \\<Omega> M}\"\n        \n      have \"Mono \\<Omega> M = ?\\<xi>''\"\n      proof -\n        have \"{} \\<in> ?\\<xi>''\"\n          using M_subseq algebra_iff_Un assms by auto\n        hence ne_xi'': \"?\\<xi>'' \\<noteq> {}\"\n          by blast\n        hence ne_xi: \"?\\<xi> \\<noteq> {}\"\n          using M_subseq by blast \n\n        have \"Mono \\<Omega> M = ?\\<xi>\"\n        proof \n          text \"We first note that \\<xi> is a monotone class via the identities \n                (\\<Inter>n. A n) \\<union> S = (\\<Inter>n. A n \\<union> S) and (\\<Union>n. A n) \\<union> S = (\\<Union>n. A n \\<union> S).\"\n          have \"monotone_class \\<Omega> ?\\<xi>\"\n            unfolding monotone_class_def monotone_class_axioms_def subset_class_def \n          proof (rule ; rule)\n            fix x\n            assume \"x \\<in> ?\\<xi>\"\n            thus \"x \\<in> Pow \\<Omega>\"\n              using mono_Pow by auto\n          next \n            have \"\\<forall>A. range A \\<subseteq> ?\\<xi> \\<and> non_decreasing A \\<longrightarrow> \\<Union> (range A) \\<in> ?\\<xi>\"\n            proof (rule ; rule ; erule conjE)\n              fix A :: \"nat \\<Rightarrow> 'a set\"\n              assume A_rng: \"range A \\<subseteq> ?\\<xi>\" and A_nd: \"non_decreasing A\"\n              hence \"range A \\<subseteq> Mono \\<Omega> M \\<and> non_decreasing A\"\n                by auto\n              hence \"\\<Union> (range A) \\<in> Mono \\<Omega> M\" \n                using mono_mono \n                unfolding monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n                by auto \n              moreover have \"\\<forall>T\\<in>M. \\<Union> (range A) \\<union> T \\<in> Mono \\<Omega> M\"  \n              proof \n                fix T\n                let ?B = \"(\\<lambda>n. A n \\<union> T)\"\n                assume \"T \\<in> M\"\n                hence \"\\<forall>n. ?B n \\<in> Mono \\<Omega> M\"\n                  using A_rng by auto\n                moreover have \"non_decreasing ?B\"\n                  using A_nd unfolding non_decreasing_def by blast\n                ultimately have \"\\<Union> (range ?B) \\<in> Mono \\<Omega> M\" \n                  using mono_mono \n                  unfolding monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n                  by auto \n                thus \"\\<Union> (range A) \\<union> T \\<in> Mono \\<Omega> M\" \n                  by auto \n              qed\n               \n              ultimately show \"\\<Union> (range A) \\<in> ?\\<xi>\"\n                by auto  \n            qed\n            thus \"non_decreasing_union_stable ?\\<xi>\"\n              using ne_xi unfolding non_decreasing_union_stable_def by auto  \n          next \n            have \"\\<forall>A. range A \\<subseteq> ?\\<xi> \\<and> non_increasing A \\<longrightarrow> \\<Inter> (range A) \\<in> ?\\<xi>\"\n            proof (rule ; rule ; erule conjE)\n              fix A :: \"nat \\<Rightarrow> 'a set\"\n              assume A_rng: \"range A \\<subseteq> ?\\<xi>\" and A_ni: \"non_increasing A\"\n              hence \"range A \\<subseteq> Mono \\<Omega> M \\<and> non_increasing A\"\n                by auto\n              hence \"\\<Inter> (range A) \\<in> Mono \\<Omega> M\" \n                using mono_mono \n                unfolding monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n                by auto \n              moreover have \"\\<forall>T\\<in>M. \\<Inter> (range A) \\<union> T \\<in> Mono \\<Omega> M\"  \n              proof \n                fix T\n                let ?B = \"(\\<lambda>n. A n \\<union> T)\"\n                assume \"T \\<in> M\"\n                hence \"\\<forall>n. ?B n \\<in> Mono \\<Omega> M\"\n                  using A_rng by blast \n                moreover have \"non_increasing ?B\"\n                  using A_ni unfolding non_increasing_def by blast\n                ultimately have \"\\<Inter> (range ?B) \\<in> Mono \\<Omega> M\" \n                  using mono_mono \n                  unfolding monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n                  by auto \n                thus \"\\<Inter> (range A) \\<union> T \\<in> Mono \\<Omega> M\" \n                  by auto \n              qed\n               \n              ultimately show \"\\<Inter> (range A) \\<in> ?\\<xi>\"\n                by auto  \n            qed\n            thus \"non_increasing_inter_stable ?\\<xi>\"\n              using ne_xi unfolding non_increasing_inter_stable_def by auto \n          qed \n          moreover have \"M \\<subseteq> ?\\<xi>\"\n            by (smt (verit) Ball_Collect M_subseq algebra_iff_Un assms subset_iff)  \n          text \"\\<MM>(M) \\<subseteq> \\<xi>, in view of minimality of \\<MM>(M).\"\n          ultimately show \"Mono \\<Omega> M \\<subseteq> ?\\<xi>\"\n            unfolding Mono_def by blast \n        next \n          text \"\\<xi> \\<subseteq> \\<MM>(M), by construction.\"\n          show \"?\\<xi> \\<subseteq> Mono \\<Omega> M\" \n            by auto  \n        qed\n        hence \"\\<forall>S\\<in>Mono \\<Omega> M. \\<forall>T\\<in>M. S \\<union> T \\<in> Mono \\<Omega> M\"\n          by blast\n        hence \"\\<forall>T\\<in>M. \\<forall>S\\<in>Mono \\<Omega> M. T \\<union> S \\<in> Mono \\<Omega> M\"\n          by (metis sup_commute)\n        hence \"M \\<subseteq> ?\\<xi>''\"\n          using M_subseq by blast \n\n        text \"\\<xi>'' is a monotone class due to the same identities as \\<xi>.\"\n        moreover have \"monotone_class \\<Omega> ?\\<xi>''\" \n        unfolding monotone_class_def monotone_class_axioms_def subset_class_def \n          proof (rule ; rule)\n            fix x\n            assume \"x \\<in> ?\\<xi>''\"\n            thus \"x \\<in> Pow \\<Omega>\"\n              using mono_Pow by auto\n          next \n            have \"\\<forall>A. range A \\<subseteq> ?\\<xi>'' \\<and> non_decreasing A \\<longrightarrow> \\<Union> (range A) \\<in> ?\\<xi>''\"\n            proof (rule ; rule ; erule conjE)\n              fix A :: \"nat \\<Rightarrow> 'a set\"\n              assume A_rng: \"range A \\<subseteq> ?\\<xi>''\" and A_nd: \"non_decreasing A\"\n              hence \"range A \\<subseteq> Mono \\<Omega> M \\<and> non_decreasing A\"\n                by auto\n              hence \"\\<Union> (range A) \\<in> Mono \\<Omega> M\" \n                using mono_mono \n                unfolding monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n                by auto \n              moreover have \"\\<forall>T\\<in>Mono \\<Omega> M. \\<Union> (range A) \\<union> T \\<in> Mono \\<Omega> M\"  \n              proof \n                fix T\n                let ?B = \"(\\<lambda>n. A n \\<union> T)\"\n                assume \"T \\<in> Mono \\<Omega> M\"\n                hence \"\\<forall>n. ?B n \\<in> Mono \\<Omega> M\"\n                  using A_rng by auto\n                moreover have \"non_decreasing ?B\"\n                  using A_nd unfolding non_decreasing_def by blast\n                ultimately have \"\\<Union> (range ?B) \\<in> Mono \\<Omega> M\" \n                  using mono_mono \n                  unfolding monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n                  by auto \n                thus \"\\<Union> (range A) \\<union> T \\<in> Mono \\<Omega> M\" \n                  by auto \n              qed\n               \n              ultimately show \"\\<Union> (range A) \\<in> ?\\<xi>''\"\n                by auto  \n            qed\n            thus \"non_decreasing_union_stable ?\\<xi>''\"\n              using ne_xi'' unfolding non_decreasing_union_stable_def by auto \n          next \n            have \"\\<forall>A. range A \\<subseteq> ?\\<xi>'' \\<and> non_increasing A \\<longrightarrow> \\<Inter> (range A) \\<in> ?\\<xi>''\"\n            proof (rule ; rule ; erule conjE)\n              fix A :: \"nat \\<Rightarrow> 'a set\"\n              assume A_rng: \"range A \\<subseteq> ?\\<xi>''\" and A_ni: \"non_increasing A\"\n              hence \"range A \\<subseteq> Mono \\<Omega> M \\<and> non_increasing A\"\n                by auto\n              hence \"\\<Inter> (range A) \\<in> Mono \\<Omega> M\" \n                using mono_mono \n                unfolding monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n                by auto \n              moreover have \"\\<forall>T\\<in>Mono \\<Omega> M. \\<Inter> (range A) \\<union> T \\<in> Mono \\<Omega> M\"  \n              proof \n                fix T\n                let ?B = \"(\\<lambda>n. A n \\<union> T)\"\n                assume \"T \\<in> Mono \\<Omega> M\"\n                hence \"\\<forall>n. ?B n \\<in> Mono \\<Omega> M\"\n                  using A_rng by blast \n                moreover have \"non_increasing ?B\"\n                  using A_ni unfolding non_increasing_def by blast\n                ultimately have \"\\<Inter> (range ?B) \\<in> Mono \\<Omega> M\" \n                  using mono_mono \n                  unfolding monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n                  by auto \n                thus \"\\<Inter> (range A) \\<union> T \\<in> Mono \\<Omega> M\" \n                  by auto \n              qed\n              ultimately show \"\\<Inter> (range A) \\<in> ?\\<xi>''\"\n                by simp\n            qed\n            thus \"non_increasing_inter_stable ?\\<xi>''\"\n              using ne_xi'' unfolding non_increasing_inter_stable_def by auto \n          qed\n\n        (* \\<MM>(M) is finite-union-stable. *)\n        ultimately show \"Mono \\<Omega> M = ?\\<xi>''\" \n          using Mono_def by blast \n      qed \n\n      moreover have \"Mono \\<Omega> M = ?\\<xi>'\"\n      proof \n        have \"?\\<xi>' \\<subseteq> Pow \\<Omega>\"\n          using mono_Pow by auto  \n        moreover have \"\\<forall>A. range A \\<subseteq> ?\\<xi>' \\<and> non_decreasing A \\<longrightarrow> \\<Union> (range A) \\<in> ?\\<xi>'\"\n        proof (rule ; rule ; erule conjE)\n          fix A :: \"nat \\<Rightarrow> 'a set\"\n          assume A_rng: \"range A \\<subseteq> ?\\<xi>'\" and A_nd: \"non_decreasing A\"\n          hence \"range A \\<subseteq> Mono \\<Omega> M \\<and> non_decreasing A\"\n            by auto\n          hence \"\\<Union> (range A) \\<in> Mono \\<Omega> M\" \n            using mono_mono \n            unfolding monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n             by simp \n          moreover have \"\\<Omega> - \\<Union> (range A) \\<in> Mono \\<Omega> M\" \n          proof - \n            let ?B = \"(\\<lambda>n. \\<Omega> - A n)\"\n            have \"range ?B \\<subseteq> Mono \\<Omega> M\"\n              using A_rng by blast\n            moreover have \"non_increasing ?B\"\n              by (simp add: A_nd nd_complement_ni) \n            moreover have \"\\<Omega> - \\<Union> (range A) = \\<Inter> (range ?B)\" \n              by simp \n            ultimately show ?thesis\n              using mono_mono \n              unfolding monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n              by metis \n          qed\n          ultimately show \"\\<Union> (range A) \\<in> ?\\<xi>'\"\n            by simp \n        qed \n        moreover have \"\\<forall>A. range A \\<subseteq> ?\\<xi>' \\<and> non_increasing A \\<longrightarrow> \\<Inter> (range A) \\<in> ?\\<xi>'\"\n        proof (rule ; rule ; erule conjE)\n          fix A :: \"nat \\<Rightarrow> 'a set\"\n          assume A_rng: \"range A \\<subseteq> ?\\<xi>'\" and A_ni: \"non_increasing A\"\n          hence \"range A \\<subseteq> Mono \\<Omega> M \\<and> non_increasing A\"\n            by auto\n          hence \"\\<Inter> (range A) \\<in> Mono \\<Omega> M\" \n            using mono_mono \n            unfolding monotone_class_def monotone_class_axioms_def non_increasing_inter_stable_def\n             by simp \n          moreover have \"\\<Omega> - \\<Inter> (range A) \\<in> Mono \\<Omega> M\" \n          proof - \n            let ?B = \"(\\<lambda>n. \\<Omega> - A n)\"\n            have \"range ?B \\<subseteq> Mono \\<Omega> M\"\n              using A_rng by blast\n            moreover have \"non_decreasing ?B\"\n              by (simp add: A_ni ni_complement_nd) \n            moreover have \"\\<Omega> - \\<Inter> (range A) = \\<Union> (range ?B)\" \n              by simp \n            ultimately show ?thesis\n              using mono_mono \n              unfolding monotone_class_def monotone_class_axioms_def non_decreasing_union_stable_def\n              by metis \n          qed\n          ultimately show \"\\<Inter> (range A) \\<in> ?\\<xi>'\"\n            by simp \n        qed\n        moreover have \"?\\<xi>' \\<noteq> {}\"\n          using M_subseq algebra.compl_sets algebra.top assms by blast\n        ultimately have \"monotone_class \\<Omega> ?\\<xi>'\"\n          using monotone_classI non_decreasing_union_stable_def non_increasing_inter_stable_def\n          by (metis (no_types, lifting)) \n        moreover have \"M \\<subseteq> ?\\<xi>'\"\n          using M_subseq algebra.compl_sets assms by auto \n        ultimately show \"Mono \\<Omega> M \\<subseteq> ?\\<xi>'\" \n          unfolding Mono_def by blast \n      next  \n        show \"?\\<xi>' \\<subseteq> Mono \\<Omega> M\" by auto \n      qed \n\n      ultimately show ?thesis\n        by blast  \n    qed\n\n    ultimately show ?thesis\n      using complement_stable_def finite_union_stable_def unfolding algebra_omega_c_fu_stable\n      using algebra_omega_c_fu_stable assms by fastforce \n  qed\n\n  ultimately have \"sigma_algebra \\<Omega> (Mono \\<Omega> M)\"\n    by (simp add: algebra_is_sigma_iff_mono)\n\n  moreover have \"sigma_sets \\<Omega> M = (LEAST N. M \\<subseteq> N \\<and> sigma_algebra \\<Omega> N)\" \n    using sigma_sets_Least alg algebra_omega_c_fu_stable by metis\n\n  ultimately show \"sigma_sets \\<Omega> M \\<subseteq> Mono \\<Omega> M\"\n    by (metis (no_types, lifting) Inter_greatest Mono_def mem_Collect_eq sigma_algebra.sigma_sets_subset)  \nqed\n\ntext \"By suppressing the minimality of the monotone class, the following corollary emerges.\"\n\nlemma sigma_of_algebra_in_mono:\n  assumes alg: \"algebra \\<Omega> M\"\n      and mono: \"monotone_class \\<Omega> N\"\n      and subseq: \"M \\<subseteq> N\"\n    shows \"sigma_sets \\<Omega> M \\<subseteq> N\"\nproof - \n  have \"Mono \\<Omega> M \\<subseteq> N\"\n    using mono subseq unfolding Mono_def by auto \n  thus ?thesis\n    using alg monotone_class_theorem by auto \nqed\n\ntext \"A related theorem, 'Dynkin's pi-lambda theorem', concerns the equality between the Dynkin\n      system and the \\<sigma>-algebra generated by the same \\<pi>-system.\"\n\ntheorem dynkin_pi_lambda:\n  assumes pi: \"pi_system \\<Omega> M\"\n  shows \"Dynkin \\<Omega> M = sigma_sets \\<Omega> M\"\nproof \n  text \"\\<D>(M) \\<subseteq> \\<sigma>(M), since every \\<sigma>-algebra is a Dynkin system.\"\n  have \"M \\<subseteq> Pow \\<Omega>\"\n    using pi pi_system_def subset_class.space_closed by blast\n  hence \"sigma_algebra \\<Omega> (sigma_sets \\<Omega> M)\"\n    using sigma_algebra_sigma_sets by auto\n  hence \"Dynkin_system \\<Omega> (sigma_sets \\<Omega> M)\"\n    by (simp add: sigma_algebra_imp_Dynkin_system)\n  thus \"Dynkin \\<Omega> M \\<subseteq> sigma_sets \\<Omega> M\"\n    unfolding Dynkin_def by blast \nnext \n  text \"For the converse, we must show that \\<D>(M) is a \\<pi>-system.\"\n  have \"pi_system \\<Omega> (Dynkin \\<Omega> M)\"\n  proof - \n    text \"In order to achieve this, let \\<D> T = {S\\<subseteq>\\<Omega> : S \\<inter> T \\<in> Dynkin \\<Omega> M} and show that this is a \n          Dynkin system.\"\n    have Dynkin_dynk: \"Dynkin_system \\<Omega> (Dynkin \\<Omega> M)\"\n      by (meson Dynkin_system_Dynkin pi pi_system.axioms(1) subset_class_def)\n    hence Dynkin_Pow: \"(Dynkin \\<Omega> M) \\<subseteq> Pow \\<Omega>\" \n      using Dynkin_omega_c_disju_stable by auto \n\n    let ?\\<D> = \"(\\<lambda>T. {S. S \\<subseteq> \\<Omega> \\<and> S \\<inter> T \\<in> Dynkin \\<Omega> M})\"\n    have \\<D>_Dynkin: \"\\<forall>T\\<in>Dynkin \\<Omega> M. Dynkin_system \\<Omega> (?\\<D> T)\"\n    proof \n      text \"Let T \\<in> \\<D>(M).\"\n      fix T\n      assume T_in_dynk: \"T \\<in> Dynkin \\<Omega> M\"\n      text \"Since \\<Omega> \\<inter> T = T, it follows that \\<Omega> \\<in> \\<D> T.\"\n      moreover have inter_is_T: \"\\<Omega> \\<inter> T = T\"\n        using calculation Dynkin_Pow by auto\n      ultimately have \"\\<Omega> \\<in> ?\\<D> T\"\n        by auto  \n\n      text \"If S \\<in> \\<D> T, then (\\<Omega> - S) \\<inter> T = (\\<Omega> \\<inter> T) - (S \\<inter> T).\"\n      moreover have \"complement_stable \\<Omega> (?\\<D> T)\"\n        unfolding complement_stable_def \n      proof (rule ; rule) \n        show \"?\\<D> T = {} \\<Longrightarrow> False\"\n          using calculation by auto\n      next \n        fix S\n        assume \"S \\<in> ?\\<D> T\"\n        hence \"T - (S \\<inter> T) \\<in> Dynkin \\<Omega> M\"\n          using Dynkin_system.diff T_in_dynk Dynkin_dynk by auto \n        hence \"(\\<Omega> \\<inter> T) - (S \\<inter> T) \\<in> Dynkin \\<Omega> M\"\n          using inter_is_T by auto\n        moreover have \"(\\<Omega> - S) \\<inter> T = (\\<Omega> \\<inter> T) - (S \\<inter> T)\"\n          by auto \n        ultimately show \"\\<Omega> - S \\<in> ?\\<D> T\" \n          by auto \n      qed\n\n      text \"If {B n, n \\<ge> 1} are disjoint sets in \\<D> T, then (\\<Inter>n. B n) \\<inter> T = (\\<Inter>n. B n \\<inter> T).\"\n      moreover have \"disj_countable_union_stable (?\\<D> T)\" \n        unfolding disj_countable_union_stable_def\n      proof (rule ; rule) \n        show \"(?\\<D> T) = {} \\<Longrightarrow> False\"\n          using calculation(1) by auto\n      next \n        fix A :: \"nat \\<Rightarrow> 'a set\"\n        show \"range A \\<subseteq> ?\\<D> T \\<and> disjoint_family A \\<longrightarrow> \\<Union> (range A) \\<in> ?\\<D> T\"\n        proof (rule ; rule ; erule conjE)\n          assume A_rng: \"range A \\<subseteq> ?\\<D> T\" and A_disj: \"disjoint_family A\"\n          hence \"\\<Union> (range A) \\<subseteq> \\<Omega>\" \n            by auto \n          moreover have \"\\<Union> (range A) \\<inter> T \\<in> Dynkin \\<Omega> M\"\n          proof - \n            let ?B = \"(\\<lambda>n. A n \\<inter> T)\"\n            have \"range ?B \\<subseteq> Dynkin \\<Omega> M\"\n              using A_rng by blast \n            moreover have \"disjoint_family ?B\"\n              using A_disj unfolding disjoint_family_on_def by auto \n            moreover have \"disj_countable_union_stable (Dynkin \\<Omega> M)\"\n              using Dynkin_dynk Dynkin_omega_c_disju_stable by auto\n            ultimately have \"\\<Union> (range ?B) \\<in> Dynkin \\<Omega> M\"\n              unfolding disj_countable_union_stable_def by blast \n            moreover have \"\\<Union> (range A) \\<inter> T = \\<Union> (range ?B)\" \n              by auto \n            ultimately show \"\\<Union> (range A) \\<inter> T \\<in> Dynkin \\<Omega> M\"\n              by presburger \n          qed\n          ultimately show \"\\<Union> (range A) \\<subseteq> \\<Omega> \\<and> \\<Union> (range A) \\<inter> T \\<in> Dynkin \\<Omega> M\"\n            by auto\n        qed\n      qed\n\n      ultimately show \"Dynkin_system \\<Omega> (?\\<D> T)\"\n        using Dynkin_omega_c_disju_stable by blast \n    qed\n    text \"Since, by definition, M \\<subseteq> \\<D> S for every S \\<in> M, it follows that Dynkin \\<Omega> M \\<subseteq> \\<D> S \\<forall>S\\<in>M.\"\n    (* Because D_S is a Dynkin system containing all of M and Dynkin \\<Omega> M is the smallest such coll. *)\n    moreover have M_in_\\<D>: \"\\<forall>S\\<in>M. M \\<subseteq> ?\\<D> S\"\n      using pi pi_system.axioms(1) subset_class.sets_into_space \n      using pi_system.fi_stable unfolding finite_inter_stable_def by fast \n    ultimately have \"\\<forall>S\\<in>M. Dynkin \\<Omega> M \\<subseteq> ?\\<D> S\"\n      by (simp add: Dynkin_Basic Dynkin_system.Dynkin_subset)\n\n    text \"For T\\<in>\\<D>(M), we now have T\\<inter>S \\<in> \\<D>(M) \\<forall>S\\<in>M, which implies that M \\<subseteq> \\<D> T and, hence, that\n          \\<D>(M) \\<subseteq> \\<D>(T) \\<forall>T\\<in>\\<D>(M).\"\n    hence \"\\<forall>T\\<in>Dynkin \\<Omega> M. \\<forall>S\\<in>M. T \\<inter> S \\<in> Dynkin \\<Omega> M\"\n      by auto\n    hence \"\\<forall>T\\<in>Dynkin \\<Omega> M. M \\<subseteq> ?\\<D> T\"\n      by (smt (verit, best) M_in_\\<D> inf_commute mem_Collect_eq subset_iff)\n    hence \"\\<forall>T\\<in>Dynkin \\<Omega> M. Dynkin \\<Omega> M \\<subseteq> ?\\<D> T\"\n      by (simp add: Dynkin_system.Dynkin_subset \\<D>_Dynkin)\n    hence \"\\<forall>T\\<in>Dynkin \\<Omega> M. \\<forall>T'\\<in>Dynkin \\<Omega> M. T \\<inter> T' \\<in> Dynkin \\<Omega> M\"\n      by blast\n    moreover have \"Dynkin \\<Omega> M \\<noteq> {}\"\n      using M_in_\\<D> finite_inter_stable_def pi pi_system.fi_stable by fastforce\n    ultimately have \"finite_inter_stable (Dynkin \\<Omega> M)\"\n      unfolding finite_inter_stable_def by auto \n    thus \"pi_system \\<Omega> (Dynkin \\<Omega> M)\"\n      by (simp add: pi_systemI Dynkin_Pow) \n  qed\n  moreover have \"Dynkin_system \\<Omega> (Dynkin \\<Omega> M)\"\n    by (meson Dynkin_system_Dynkin pi pi_system_def subset_class_def)\n  ultimately have \"sigma_algebra \\<Omega> (Dynkin \\<Omega> M)\"\n    by (simp add: Dynkin_is_sigma_iff_pi)\n  moreover have \"M \\<subseteq> Dynkin \\<Omega> M\"\n    by (simp add: Dynkin_Basic subsetI)\n  ultimately show \"sigma_sets \\<Omega> M \\<subseteq> Dynkin \\<Omega> M\"\n    by (simp add: sigma_algebra.sigma_sets_subset) \nqed\n\ncorollary mono_dynk_sigma_of_sigma: \n  assumes \"sigma_algebra \\<Omega> M\"\n  shows \"Mono \\<Omega> M = M \\<and> Dynkin \\<Omega> M = M \\<and> sigma_sets \\<Omega> M = M\"\nproof - \n  have \"Mono \\<Omega> M = M\"\n    by (simp add: monotone_class_theorem assms sigma_algebra.sigma_sets_eq sigma_is_algebra) \n  moreover have \"Dynkin \\<Omega> M = M\"\n    by (simp add: Dynkin_system.Dynkin_idem assms sigma_algebra_imp_Dynkin_system) \n  moreover have \"sigma_sets \\<Omega> M = M\"\n    by (simp add: assms sigma_algebra.sigma_sets_eq)\n  ultimately show ?thesis\n    by simp \nqed\n\nsection \"Two Metatheorems\"\n\ntheorem check_alg_in_mono_for_sigma:\n  assumes mono: \"monotone_class \\<Omega> M\"\n      and P_on_M: \"\\<forall>S\\<in>M. P S\"\n      and alg: \"algebra \\<Omega> N\"\n      and subseq: \"N \\<subseteq> M\"\n    shows \"\\<forall>S\\<in>sigma_sets \\<Omega> N. P S\"\nproof - \n  have \"sigma_sets \\<Omega> N \\<subseteq> M\"\n    using alg mono sigma_of_algebra_in_mono subseq by blast\n  thus ?thesis\n    using P_on_M by fast \nqed\n\ntheorem check_pi_in_dynk_for_sigma: \n  assumes dynk: \"Dynkin_system \\<Omega> M\"\n      and P_on_M: \"\\<forall>S\\<in>M. P S\"\n      and pi: \"pi_system \\<Omega> N\"\n      and subseq: \"N \\<subseteq> M\"\n    shows \"\\<forall>S\\<in>sigma_sets \\<Omega> N. P S\"\nproof - \n  have \"sigma_sets \\<Omega> N = Dynkin \\<Omega> N\"\n    using dynkin_pi_lambda pi by auto\n  hence \"sigma_sets \\<Omega> N \\<subseteq> M\"\n    by (simp add: Dynkin_system.Dynkin_subset dynk subseq)\n  thus ?thesis \n    using P_on_M by fast \nqed \n\nchapter \"The Probability Space\"\n\nlocale probability_space = \n    fixes \\<Omega> :: \"'a set\"\n      and \\<F> :: \"'a set set\"\n      and P :: \"'a set \\<Rightarrow> real\"\n  assumes \\<F>_Pow: \"\\<F> \\<subseteq> Pow \\<Omega>\"\n      and sigma: \"sigma_algebra \\<Omega> \\<F>\"\n      and non_neg_prob: \"\\<forall>A\\<in>\\<F>. P A \\<ge> 0\"\n      and sample_space_prob_1: \"P \\<Omega> = 1\"\n      and countable_additivity: \"disjoint_family (A :: nat \\<Rightarrow> 'a set) \\<and> range A \\<subseteq> \\<F> \\<longrightarrow> \n                                 P (\\<Union>(range A)) = infsum (\\<lambda>n. P (A n)) UNIV\"\nbegin\n\nsection \"Moving towards an intuitive notion of probability\"\n\nsubsection \"Measurable Sets\"\n\ndefinition measurable :: \"'a set \\<Rightarrow> bool\"\n  where \"measurable S = (S \\<in> \\<F>)\"\n\nlemma measurable_c: \n  assumes meas: \"measurable S\"\n  shows \"measurable (\\<Omega> - S)\"\n  using sigma meas measurable_def complement_stable_def sigma_algebra_omega_c_cu_stable by metis \n\nlemma measurable_empty: \n  shows \"measurable {}\"\n  using empty_in_sigma measurable_def sigma by auto\n\nlemma measurable_omega: \n  shows \"measurable \\<Omega>\"\n  using measurable_c measurable_empty by fastforce\n\nlemma countable_additivity_meas:\n  assumes disj: \"disjoint_family (A :: nat \\<Rightarrow> 'a set)\"\n      and meas: \"\\<forall>n. measurable (A n)\"\n    shows \"P (\\<Union>(range A)) = infsum (\\<lambda>n. P (A n)) (UNIV :: nat set)\"\n  using assms countable_additivity measurable_def by fast\n\nlemma measurable_fu: \n  assumes meas_A: \"measurable A\"\n      and meas_B: \"measurable B\"\n    shows \"measurable (A \\<union> B)\"\n  using sigma assms measurable_def \n        sigma_algebra_omega_c_cu_stable cu_imp_fu_stable finite_union_stable_def by metis \n\nlemma measurable_fu_ind: \n  assumes meas: \"\\<forall>S\\<in>M. measurable S\"\n      and fin: \"finite M\"\n    shows \"measurable (\\<Union>S\\<in>M. S)\"\n  using sigma assms sigma_algebra_omega_c_cu_stable cu_imp_fu_stable fu_stable_finite Union_empty \n        empty_in_sigma image_ident measurable_def by metis \n\nlemma measurable_cu:\n  assumes meas: \"\\<forall>n::nat. measurable (A n)\"\n  shows \"measurable (\\<Union>(range A))\"\nproof - \n  have \"range A \\<subseteq> \\<F>\"\n    by (meson image_subset_iff measurable_def meas)  \n  moreover have \"countable_union_stable \\<F>\"\n    using sigma sigma_algebra_omega_c_cu_stable by auto\n  ultimately have \"(\\<Union>(range A)) \\<in> \\<F>\"\n    unfolding countable_union_stable_def by auto \n  thus ?thesis \n    by (simp add: measurable_def) \nqed\n\nlemma measurable_union:\n  fixes I :: \"nat set\"\n  assumes meas: \"\\<forall>n\\<in>I. measurable (A n)\"\n  shows \"measurable (\\<Union>n\\<in>I. A n)\"\nproof - \n  let ?A' = \"(\\<lambda>n. if n\\<notin>I then {} else A n)\"\n  let ?U' = \"(\\<Union>(range ?A'))\"\n\n  have \"\\<forall>n. measurable (?A' n)\"\n  proof \n    fix n \n    consider (I) \"n\\<in>I\" | (no_I) \"n\\<notin>I\"\n      by auto\n    thus \"measurable (?A' n)\"\n    proof cases\n      case I\n      then show ?thesis\n        by (simp add: meas) \n    next\n      case no_I\n      then show ?thesis\n        by (simp add: measurable_empty) \n    qed \n  qed\n\n  hence \"measurable ?U'\"\n    using measurable_cu by presburger \n\n  moreover have \"?U' = (\\<Union>n\\<in>I. A n)\" \n    by simp \n\n  ultimately show ?thesis \n    by simp   \nqed\n\n\nlemma measurable_fi: \n  assumes meas_A: \"measurable A\"\n      and meas_B: \"measurable B\"\n    shows \"measurable (A \\<inter> B)\"\n  using sigma assms measurable_def \n        sigma_algebra_omega_c_ci_stable ci_imp_fi_stable finite_inter_stable_def by metis \n\nlemma measurable_fi_ind: \n  assumes meas: \"\\<forall>S\\<in>M. measurable S\"\n      and fin: \"finite M\"\n      and non_empty: \"M \\<noteq> {}\"\n    shows \"measurable (\\<Inter>S\\<in>M. S)\"\n  using sigma assms sigma_algebra_omega_c_ci_stable ci_imp_fi_stable fi_stable_finite measurable_def\n    by metis \n\nlemma measurable_ci:\n  assumes meas: \"\\<forall>n::nat. measurable (A n)\"\n    shows \"measurable (\\<Inter>(range A))\"\nproof - \n  have \"range A \\<subseteq> \\<F>\"\n    by (meson image_subset_iff measurable_def meas)  \n  moreover have \"countable_inter_stable \\<F>\"\n    using sigma sigma_algebra_omega_c_ci_stable by auto\n  ultimately have \"(\\<Inter>(range A)) \\<in> \\<F>\"\n    unfolding countable_inter_stable_def by auto \n  thus ?thesis \n    by (simp add: measurable_def) \nqed \n\nlemma measurable_inter:\n  fixes I :: \"nat set\"\n  assumes meas: \"\\<forall>n\\<in>I. measurable (A n)\"\n      and non_empty: \"I \\<noteq> {}\"\n  shows \"measurable (\\<Inter>n\\<in>I. A n)\"\nproof - \n  let ?A' = \"(\\<lambda>n. if n\\<notin>I then \\<Omega> else A n)\"\n  let ?I' = \"(\\<Inter>(range ?A'))\"\n\n  have \"\\<forall>n. measurable (?A' n)\"\n  proof \n    fix n \n    consider (I) \"n\\<in>I\" | (no_I) \"n\\<notin>I\"\n      by auto\n    thus \"measurable (?A' n)\"\n    proof cases\n      case I\n      then show ?thesis\n        by (simp add: meas) \n    next\n      case no_I\n      then show ?thesis\n        by (simp add: measurable_omega) \n    qed \n  qed\n\n  hence \"measurable ?I'\"\n    using measurable_ci by presburger\n\n  moreover have \"?I' = (\\<Inter>n\\<in>I. A n)\"\n  proof (rule ; rule) \n    show \"\\<And>x. x \\<in> (\\<Inter>n. if n \\<notin> I then \\<Omega> else A n) \\<Longrightarrow> x \\<in> \\<Inter> (A ` I)\"\n      by simp \n  next \n    fix x\n    assume x_in_sub_I: \"x \\<in> (\\<Inter>n\\<in>I. A n)\"\n    have \"\\<forall>n. x \\<in> ?A' n\"\n    proof \n      fix n \n      consider (I) \"n\\<in>I\" | (no_I) \"n\\<notin>I\"\n        by auto\n      thus \"x \\<in> ?A' n\"\n      proof cases\n        case I\n        then show ?thesis \n          using x_in_sub_I by auto \n      next\n        case no_I\n        moreover have \"x \\<in> \\<Omega>\" \n          using x_in_sub_I non_empty \\<F>_Pow measurable_def meas by fastforce \n        ultimately show ?thesis \n          by auto \n      qed \n    qed\n    thus \"x \\<in> ?I'\"\n      by fastforce \n  qed \n\n  ultimately show ?thesis \n    by simp   \nqed\n\nlemma measurable_sd: \n  assumes meas_S: \"measurable S\"\n      and meas_T: \"measurable T\"\n    shows \"measurable (S - T)\"\n  unfolding measurable_def \nproof - \n  have \"(S \\<inter> T) \\<in> \\<F>\"\n    using meas_S meas_T measurable_fi measurable_def by auto \n  hence \"S - (S \\<inter> T) \\<in> \\<F>\"\n    using meas_S sigma sigma_sd_stable unfolding set_diff_stable_def measurable_def by blast \n  thus \"S - T \\<in> \\<F>\"\n    by (metis Diff_Int_distrib Int_Diff Int_absorb) \nqed\n\nsubsection \"Probabilities of sets and their combinations\"\n\ntext \"Departing from the axioms (only!) one can now derive various relations between probabilities\nof unions, subsets, complements and so on. Following is a list of some of them.\"\n\nlemma P_empty:\n  shows \"P {} = 0\" \nproof - \n  let ?A = \"(\\<lambda>n::nat. if n = 0 then \\<Omega> else {})\"\n  let ?P = \"(\\<lambda>n. P (?A n))\"\n  let ?S = \"(UNIV - {0}) :: nat set\"\n\n  have \"\\<forall>n. (n \\<in> (UNIV - {0})) \\<longrightarrow> (?P n = 0)\"\n  proof (rule ; rule) \n    fix n\n\n    have \"disjoint_family ?A\"\n      unfolding disjoint_family_on_def by auto \n    moreover have \"\\<forall>n. measurable (?A n)\"\n      using measurable_c measurable_empty by fastforce\n    ultimately have \"P (\\<Union>(range ?A)) = infsum ?P UNIV\"\n      using countable_additivity_meas by presburger \n    hence UNIV_sum_1: \"infsum ?P UNIV = 1\"\n      using sample_space_prob_1 by auto \n    hence \"infsum ?P (UNIV - {0}) + infsum ?P {0} = 1\"\n      using infsum_Diff infsum_not_exists subset_UNIV summable_on_subset_banach by smt \n    hence non_0_sum_0: \"infsum ?P (UNIV - {0}) = 0\"\n      by (simp add: sample_space_prob_1) \n\n    moreover assume \"n \\<in> ?S\"\n\n    moreover have \"?P summable_on UNIV\"\n      using infsum_not_exists UNIV_sum_1 by fastforce \n    hence \"has_sum ?P ?S 0\"\n      using non_0_sum_0 Diff_subset has_sum_infsum summable_on_subset_banach by metis \n    moreover have \"(\\<And>x. x \\<in> ?S \\<Longrightarrow> 0 \\<le> ?P x)\"\n      using empty_in_sigma non_neg_prob sigma by auto\n    ultimately show \"?P n = 0\"\n      using nonneg_has_sum_le_0D by smt \n  qed \n  \n  thus ?thesis\n    by auto\nqed\n\nlemma binary_additivity:\n  assumes disj: \"A \\<inter> B = {}\"\n      and meas_A: \"measurable A\"\n      and meas_B: \"measurable B\"\n    shows \"P (A \\<union> B) = P A + P B\"\nproof - \n  let ?A = \"(\\<lambda>n::nat. if n = 0 then A else if n = 1 then B else {})\"\n  let ?P = \"(\\<lambda>n. P (?A n))\"\n  have \"disjoint_family ?A\"\n    using disj unfolding disjoint_family_on_def by auto \n  moreover have \"\\<forall>n. measurable (?A n)\"\n    using disj meas_A meas_B measurable_fi by fastforce \n  ultimately have \"P (\\<Union>(range ?A)) = infsum ?P UNIV\"\n    using countable_additivity_meas by presburger \n  moreover have \"\\<Union>(range ?A) = A \\<union> B\" \n    by auto \n  ultimately have \"P (A \\<union> B) = infsum ?P UNIV\"\n    by auto  \n  moreover have \"\\<forall>n\\<in>(UNIV - {0, 1}). ?P n = 0\" \n    using P_empty by simp\n  hence \"infsum ?P UNIV = infsum ?P {0, 1}\"\n    using Diff_UNIV empty_iff infsum_cong_neutral by (metis (no_types, lifting)) \n  ultimately show ?thesis \n    by auto \nqed\n\nlemma finite_additivity:\n  assumes disj: \"disjoint_family_on A S\"\n      and meas_As: \"\\<forall>n\\<in>S. measurable (A n)\"\n      and fin: \"finite S\"\n    shows \"P (\\<Union>n\\<in>S. A n) = sum P (A ` S)\" \n  using fin meas_As disj \nproof (induction S rule: finite_induct)\n  case empty\n  hence \"P (\\<Union> (A ` {})) = sum P {}\"\n    by (simp add: P_empty)\n  thus ?case\n    by auto \nnext\n  case (insert x F) \n  have \"P (\\<Union> (A ` insert x F)) = P ((\\<Union> (A ` F)) \\<union> A x)\"\n    by (simp add: Un_commute)\n  moreover have \"finite {T. \\<exists>n\\<in>F. T = A n} \\<and> (\\<forall>n\\<in>F. measurable (A n))\"\n    by (simp add: insert.hyps(1) insert.prems(1)) \n  hence \"measurable (\\<Union>S\\<in>{T. \\<exists>n\\<in>F. T = A n}. S)\"\n    by (smt (verit, best) measurable_fu_ind mem_Collect_eq)\n  hence \"measurable (\\<Union> (A ` F))\"\n    by (smt (verit) Collect_cong UNION_eq mem_Collect_eq) \n  moreover have \"measurable (A x)\"\n    by (simp add: insert.prems(1)) \n  moreover have \"(\\<Union> (A ` F)) \\<inter> (A x) = {}\" \n    using insert.prems(2) insert.hyps(2) unfolding disjoint_family_on_def by fastforce \n  ultimately have \"P (\\<Union> (A ` insert x F)) = P (\\<Union> (A ` F)) + P (A x)\"\n    using binary_additivity by fastforce\n  moreover have meas_F: \"\\<forall>n\\<in>F. measurable (A n)\"\n    by (simp add: insert.prems(1))  \n  moreover have disj_F: \"disjoint_family_on A F\"\n    by (metis disjoint_family_on_insert insert.hyps(2) insert.prems(2))  \n  ultimately have \"P (\\<Union> (A ` insert x F)) = sum P (A ` F) + P (A x)\"\n    using insert.IH by auto \n  thus ?case\n    by (smt meas_F disj_F finite_imageI image_insert insert.IH insert.hyps(1) insert_absorb \n                    sum.insert)  \nqed\n\nlemma finite_additivity':\n  assumes disj: \"disjoint_family_on A S\"\n      and meas_As: \"\\<forall>n\\<in>S. measurable (A n)\"\n      and fin: \"finite S\"\n    shows \"P (\\<Union>n\\<in>S. A n) = sum (\\<lambda>n. P (A n)) S\" \nproof - \n  have \"P (\\<Union>n\\<in>S. A n) = sum P (A ` S)\"\n    by (simp add: disj fin finite_additivity meas_As)\n  moreover have \"sum (P \\<circ> A) S = sum P (A ` S)\" \n    using disj unfolding disjoint_family_on_def\n    by (metis P_empty fin inf.idem sum.reindex_nontrivial) \n  ultimately show ?thesis \n    by simp \nqed\n\nlemma P_set_diff: \n  assumes meas_S: \"measurable S\"\n      and meas_T: \"measurable T\"\n    shows \"P (S - T) = P S - P (S \\<inter> T)\"\nproof - \n  have \"measurable (S \\<inter> T)\"\n    by (simp add: meas_S meas_T measurable_fi)\n  moreover have \"measurable (S - T)\"\n    by (simp add: meas_S meas_T measurable_sd)\n  ultimately have \"P (S - T) + P (S \\<inter> T) = P S\"\n    by (metis Int_Diff_disjoint Int_Diff_Un add.commute binary_additivity)\n  thus ?thesis\n    by simp \nqed\n\nlemma P_subset_diff: \n  assumes meas_S: \"measurable S\"\n      and meas_T: \"measurable T\"\n      and subseq: \"T \\<subseteq> S\"\n    shows \"P (S - T) = P S - P T\"\n  by (metis inf.absorb_iff2 meas_S meas_T P_set_diff subseq)\n\nlemma P_complement: \n  assumes meas: \"measurable S\"\n  shows \"P (\\<Omega> - S) = 1 - P S\"\nproof - \n  have \"measurable \\<Omega>\"\n    by (simp add: measurable_omega)\n  moreover have \"S \\<subseteq> \\<Omega>\"\n    using \\<F>_Pow measurable_def meas by auto\n  ultimately show ?thesis\n    by (simp add: meas P_subset_diff sample_space_prob_1)\nqed\n\nlemma binary_incl_excl: \n  assumes meas_A: \"measurable A\"\n      and meas_B: \"measurable B\"\n    shows \"P (A \\<union> B) = P A + P B - P (A \\<inter> B)\"\nproof - \n  have \"measurable (B - A)\"\n    by (simp add: meas_A meas_B measurable_sd) \n  hence \"P (A \\<union> B) = P A + P (B - A)\"\n    using assms binary_additivity Diff_disjoint Un_Diff_cancel by metis \n  moreover have \"P (B - A) = P B - P (A \\<inter> B)\"\n    by (simp add: Int_commute meas_A meas_B P_set_diff)\n  ultimately show ?thesis \n    by simp \nqed\n\nlemma binary_subadditivty:\n  assumes meas_A: \"measurable A\"\n      and meas_B: \"measurable B\"\n  shows \"P (A \\<union> B) \\<le> P A + P B\"\n  using binary_incl_excl measurable_def meas_A meas_B measurable_fi non_neg_prob by auto  \n\n(* TODO: Finite, countable subadditivity*)\n\nlemma P_subseq: \n  assumes meas_S: \"measurable S\"\n      and meas_T: \"measurable T\"\n      and subseq: \"S \\<subseteq> T\"\n    shows \"P S \\<le> P T\"\nproof - \n  have meas_sd: \"measurable (T - S)\"\n    by (simp add: meas_S meas_T measurable_sd)\n  hence \"P S + P (T - S) = P T\"\n    by (simp add: assms P_subset_diff)\n  thus ?thesis \n    using meas_sd measurable_def non_neg_prob by auto \nqed \n\nlemma P_cu_cci_1: \n  assumes meas_As: \"\\<forall>n::nat. measurable (A n)\"\n  shows \"P (\\<Union>n. A n) + P (\\<Inter>n. \\<Omega> - A n) = 1\"\nproof - \n  have \"measurable (\\<Union>n. A n)\"\n    by (simp add: meas_As measurable_cu)\n  moreover have \"\\<forall>n. measurable (\\<Omega> - A n)\"\n    by (simp add: meas_As measurable_c)\n  hence \"measurable (\\<Inter>n. \\<Omega> - A n)\"\n    by (meson measurable_ci)\n  moreover have \"(\\<Inter>n. \\<Omega> - A n) = \\<Omega> - (\\<Union>n. A n)\"\n    by auto\n  ultimately show ?thesis\n    by (simp add: P_complement)\nqed\n\nsection \"Limits and Completeness\"\n\nlemma partial_sum_LIM_infsum: \n  fixes Q :: \"nat \\<Rightarrow> real\"\n  assumes smmble: \"Q summable_on UNIV\"\n  shows \"(\\<lambda>N. sum Q {..N}) \\<longlonglongrightarrow> infsum Q UNIV\"\nproof - \n  have \"(sum Q \\<longlongrightarrow> infsum Q UNIV) (finite_subsets_at_top UNIV)\"\n    using infsum_tendsto smmble by blast\n  hence  \"((\\<lambda>N. sum Q {..N}) \\<longlongrightarrow> infsum Q UNIV) at_top\"\n    using filterlim_atMost_at_top filterlim_compose by blast\n  thus ?thesis\n    by simp\nqed\n\ntheorem non_dec_prob_limit: \n  fixes A :: \"nat \\<Rightarrow> 'a set\"\n  assumes meas_As: \"\\<forall>n. measurable (A n)\"\n      and non_dec: \"non_decreasing A\"\n    shows \"(\\<lambda>n. P (A n)) \\<longlonglongrightarrow> P (set_limit A)\"\nproof -\n  let ?B = \"(\\<lambda>n. if n = 0 then A 0 else A n - A (n - 1))\"\n\n  have meas_B: \"\\<forall>n. measurable (?B n)\"\n      by (simp add: meas_As measurable_sd) \n  have disj_B: \"disjoint_family ?B\"\n    by (simp add: non_dec non_dec_to_disj)\n\n  have \"\\<forall>N. A N = \\<Union> (?B ` {..N})\"\n    using non_dec non_dec_is_disj_fu by auto \n  hence \"\\<forall>N. P (A N) = P (\\<Union> (?B ` {..N}))\"\n    by metis\n  moreover have \"\\<forall>N. P (\\<Union> (?B ` {..N})) = sum (\\<lambda>n. P (?B n)) {..N}\"\n  proof \n    fix N\n    have \"disjoint_family_on ?B {..N}\"  \n      using disj_B unfolding disjoint_family_on_def by blast \n    thus \"P (\\<Union> (?B ` {..N})) = sum (\\<lambda>n. P (?B n)) {..N}\" \n      using finite_additivity' meas_B by blast  \n  qed \n  ultimately have \"\\<forall>N. P (A N) = sum (\\<lambda>n. P (?B n)) {..N}\"  \n    by auto \n\n  moreover consider (null) \"\\<forall>n. P (?B n) = 0\" | (non_null) \"\\<exists>n. P (?B n) \\<noteq> 0\"\n    by auto \n  hence \"(\\<lambda>n. P (?B n)) summable_on UNIV\" \n  proof cases\n    case null\n    then show ?thesis by simp \n  next\n    case non_null\n    then obtain N where \"P (?B N) \\<noteq> 0\"\n      by auto \n    moreover have \"measurable (?B N)\"\n      using meas_B by auto \n    ultimately have \"P (?B N) > 0\"\n      using measurable_def non_neg_prob by auto \n    moreover have \"measurable (\\<Union> (range ?B))\"\n      using meas_B measurable_cu by presburger\n    moreover have \"?B N \\<subseteq> (\\<Union> (range ?B))\"\n      by blast \n    ultimately have \"P (\\<Union> (range ?B)) > 0\"\n      using P_subseq meas_B by (smt (verit)) \n    hence \"infsum (\\<lambda>n. P (?B n)) UNIV > 0\"\n      using countable_additivity_meas meas_B disj_B by fastforce \n    then show ?thesis\n      using infsum_not_exists by fastforce \n  qed \n  hence \"((\\<lambda>N. sum (\\<lambda>n. P (?B n)) {..N}) \\<longlongrightarrow> infsum (\\<lambda>n. P (?B n)) UNIV) at_top\"\n    using partial_sum_LIM_infsum by auto\n\n  ultimately have \"(\\<lambda>N. P (A N)) \\<longlonglongrightarrow> (\\<Sum>\\<^sub>\\<infinity>n. P (?B n))\" \n    by simp \n  moreover have \"P (\\<Union> (range ?B)) = (\\<Sum>\\<^sub>\\<infinity>n. P (?B n))\"\n    using countable_additivity_meas meas_B disj_B by blast \n  moreover have \"(\\<Union> (range ?B)) = (\\<Union> (range A))\"\n    by (simp add: non_dec non_dec_to_disj_same_cu)\n  ultimately have \"(\\<lambda>N. P (A N)) \\<longlonglongrightarrow> P (\\<Union> (range A))\"\n    by simp  \n\n  thus ?thesis \n    using non_dec non_decreasing_set_limit by fastforce \nqed\n\n\ntheorem non_inc_prob_limit: \n  fixes A :: \"nat \\<Rightarrow> 'a set\"\n  assumes meas_As: \"\\<forall>n. measurable (A n)\"\n      and non_inc: \"non_increasing A\"\n    shows \"(\\<lambda>n. P (A n)) \\<longlonglongrightarrow> P (set_limit A)\"\nproof -\n  let ?B = \"(\\<lambda>n. \\<Omega> - A n)\"\n\n  have non_dec: \"non_decreasing ?B\"\n    by (simp add: ni_complement_nd non_inc)\n  hence \"(\\<lambda>n. P (?B n)) \\<longlonglongrightarrow> P (set_limit ?B)\"\n    using meas_As measurable_c non_dec_prob_limit by auto\n\n  moreover have \"\\<forall>n. P (?B n) = 1 - P (A n)\"\n    by (simp add: P_complement meas_As)\n\n  moreover have \"P (set_limit ?B) = P (\\<Omega> - set_limit A)\"\n    by (simp add: ni_c_nd_set_limit non_inc)\n  hence \"P (set_limit ?B) = 1 - P (set_limit A)\"\n    by (simp add: meas_As measurable_ci non_inc non_increasing_set_limit P_complement)\n\n  ultimately have \"(\\<lambda>n. 1 - P (A n)) \\<longlonglongrightarrow> 1 - P (set_limit A)\"\n    by simp   \n  moreover have \"\\<forall>x y :: real. dist (1 - x) (1 - y) = dist x y\"\n    using dist_real_def by auto\n  ultimately show ?thesis \n    by (simp add: tendsto_iff dist_real_def) \nqed\n\ntheorem P_liminf_le: \n  fixes A :: \"nat \\<Rightarrow> 'a set\"\n  assumes meas_As: \"\\<forall>n. measurable (A n)\"\n  shows \"P (liminf A) \\<le> liminf (\\<lambda>n. P (A n))\"\nproof - \n  let ?I = \"(\\<lambda>n. \\<Inter>m\\<in>{n..}. A m)\"\n\n  have nd_I: \"non_decreasing ?I\"\n    unfolding non_decreasing_def by (simp add: Inter_anti_mono image_mono)\n  moreover have meas_Is: \"\\<forall>n. measurable (?I n)\"\n    by (simp add: meas_As measurable_inter) \n  ultimately have \"(\\<lambda>n. P (?I n)) \\<longlonglongrightarrow> P (set_limit ?I)\"\n    by (simp add: non_dec_prob_limit) \n  hence \"P (set_limit ?I) \\<le> liminf (\\<lambda>n. P (?I n))\" sorry   \n\n  moreover have \"\\<forall>n. ?I n \\<subseteq> A n\"\n    by (simp add: INT_lower)\n  hence \"\\<forall>n. P (?I n) \\<le> P (A n)\"\n    using P_subseq meas_As meas_Is by auto\n  hence \"liminf (\\<lambda>n. P (?I n)) \\<le> liminf (\\<lambda>n. P (A n))\" sorry \n\n  ultimately have \"P (set_limit ?I) \\<le> liminf (\\<lambda>n. P (A n))\" \n    by simp \n\n  moreover have \"liminf ?I = liminf A\" \n    unfolding liminf_set by auto \n\n  moreover have \"set_limit ?I = \\<Union>(range ?I)\" \n    using nd_I non_decreasing_set_limit by auto \n  \n  ultimately show ?thesis\n    by (simp add: liminf_set) \nqed\n\nend\n\nend", "meta": {"author": "larswe", "repo": "probability-theory", "sha": "764ba6f319eb9225fae8b66704104b245d8dd2b3", "save_path": "github-repos/isabelle/larswe-probability-theory", "path": "github-repos/isabelle/larswe-probability-theory/probability-theory-764ba6f319eb9225fae8b66704104b245d8dd2b3/Probability_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8976952989498449, "lm_q1q2_score": 0.7783339255958156}}
{"text": "theory NQueens_CSP\nimports Main CSP\nbegin\n\n(* The general problem *)\n\ndefinition board0 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"board0 n b = (n\\<ge>0 \\<and> b \\<subseteq> {1..n}\\<times>{1..n} \\<and> (int (card b) = n))\"\n\ndefinition safe0 :: \"int \\<Rightarrow> int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"safe0 p q b = (\\<forall>i. i\\<noteq>0 \\<longrightarrow> (p+i,q)\\<notin>b \\<and> (p,q+i)\\<notin>b \\<and> (p+i,q+i)\\<notin>b \\<and> (p+i,q-i)\\<notin>b)\"\n\ndefinition nqueens0 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"nqueens0 n b = (board0 n b \\<and> (\\<forall>p q. (p,q)\\<in>b \\<longrightarrow> safe0 p q b))\"\n\n(* The problem with all queens preassigned to different columns, *)\n(* that is, no queen can vertically attack another. *)\n(* This makes b an array! *)\n\ndefinition board1 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"board1 n b = (n\\<ge>0 \\<and> array n n b)\"\n\ndefinition safe1 :: \"int \\<Rightarrow> int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"safe1 p q b = (\\<forall>i. i\\<noteq>0 \\<longrightarrow> (p+i,q)\\<notin>b \\<and> (p+i,q+i)\\<notin>b \\<and> (p+i,q-i)\\<notin>b)\"\n\ndefinition nqueens1 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"nqueens1 n b = (board1 n b \\<and> (\\<forall>p q. (p,q)\\<in>b \\<longrightarrow> safe1 p q b))\"\n\nlemma from0to1: \"nqueens1 n b \\<Longrightarrow> nqueens0 n b\" \napply (simp add: nqueens1_def nqueens0_def safe1_def safe0_def board1_def board0_def)\nby (smt Domain.intros Range.RangeI array_def arraycard mem_Sigma_iff subrelI subsetCE)\n\n(* The safety constraints split. *)\n(* Constraint a: No queen can horizontally attack another. *)\n(* Constraint 2: No queen can diagonally attack another. *)\n\ndefinition board2 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"board2 n b = board1 n b\"\n\ndefinition safe2a :: \"int rel \\<Rightarrow> bool\" where\n  \"safe2a b = allDifferent b\"\n\ndefinition safe2b :: \"int rel \\<Rightarrow> bool\" where\n  \"safe2b b = (\\<forall>p q r s. (p,q)\\<in>b \\<and> (r,s)\\<in>b \\<and> p\\<noteq>r \\<longrightarrow> abs (p-r) \\<noteq> abs (q-s))\"\n\ndefinition safe2b_impl :: \"int rel \\<Rightarrow> bool\" where\n  \"safe2b_impl b = (\\<forall>p r. p\\<in>Domain b \\<and> r\\<in>Domain b \\<and> p\\<noteq>r \\<longrightarrow> abs (p-r) \\<noteq> abs ((valof b p)-(valof b r)))\"\n\nlemma safe2bimpl: \"array n n b \\<Longrightarrow> (safe2b b \\<longleftrightarrow> safe2b_impl b)\"\napply (simp add: safe2b_def safe2b_impl_def)\nby (metis Domain.DomainI valofarr valofarrev)\n\ndefinition nqueens2 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"nqueens2 n b = (board2 n b \\<and> safe2a b \\<and> safe2b b)\"\n\nlemma nqueens2_impl: \"nqueens2 n b \\<longleftrightarrow> (board2 n b \\<and> safe2a b \\<and> safe2b_impl b)\"\nusing board1_def board2_def nqueens2_def safe2bimpl by blast\n\nlemma safe1dcmp: \"\\<lbrakk>\\<forall>p q. (p, q) \\<in> b \\<longrightarrow> (\\<forall>i. i\\<noteq>0 \\<longrightarrow> (p+i,q)\\<notin>b); \\<forall>p q. (p, q) \\<in> b \\<longrightarrow> (\\<forall>i. i\\<noteq>0 \\<longrightarrow> (p+i,q+i)\\<notin>b); \\<forall>p q. (p, q) \\<in> b \\<longrightarrow> (\\<forall>i. i\\<noteq>0 \\<longrightarrow> (p+i,q-i)\\<notin>b)\\<rbrakk> \\<Longrightarrow> (\\<forall>p q. (p, q) \\<in> b \\<longrightarrow> safe1 p q b)\"\nby (simp add: safe1_def)\n\nlemma from1to2: \"nqueens2 n b \\<longrightarrow> nqueens1 n b\"\nproof (simp add: nqueens2_def nqueens1_def board2_def, standard)\n  {\n  fix p q\n  assume b1: \"board1 n b\"\n     and s1: \"safe2a b\"\n     and s2: \"safe2b b\"\n     and b2: \"(p, q) \\<in> b\"\n  hence \"\\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> q \\<noteq> s\" \n  by (simp add: safe2a_def allDifferent_def)\n  hence s3: \"\\<forall>i. i \\<noteq> 0 \\<longrightarrow> (p + i, q) \\<notin> b\" using b2 by force\n  have s4: \"\\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> \\<bar>p - r\\<bar> \\<noteq> \\<bar>q - s\\<bar>\" \n  using s2 safe2b_def by blast\n  hence \"\\<forall>i. i \\<noteq> 0 \\<longrightarrow> (p + i, q) \\<notin> b \\<and> (p + i, q + i) \\<notin> b \\<and> (p + i, q - i) \\<notin> b\" \n  using s3 using b2 by fastforce\n  hence \"safe1 p q b\" by (simp add: safe1_def)\n  }\n  thus \"board1 n b \\<and> safe2a b \\<and> safe2b b \\<Longrightarrow> \\<forall>p q. (p, q) \\<in> b \\<longrightarrow> safe1 p q b\" by blast\nqed\n\ndefinition board3 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"board3 n b = board2 n b\"\n\ndefinition safe3a :: \"int rel \\<Rightarrow> bool\" where\n  \"safe3a b = safe2a b\"\n\ndefinition safe3b :: \"int rel \\<Rightarrow> bool\" where\n  \"safe3b b = (\\<forall>p q r s. (p,q)\\<in>b \\<and> (r,s)\\<in>b \\<and> p\\<noteq>r \\<longrightarrow> q+p\\<noteq>s+r)\"\n\nlemma safead3b: \"safe3b b \\<longleftrightarrow> allDifferent {(x,y). \\<exists>z. (x,z)\\<in>b \\<and> y=z+x}\"\nproof (simp add: safe3b_def allDifferent_def array_def, standard)\nshow \"\\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> q + p \\<noteq> s + r \\<Longrightarrow>\n    \\<forall>x y p q. (\\<exists>z. (x, z) \\<in> b \\<and> p = z + x) \\<and> (\\<exists>z. (y, z) \\<in> b \\<and> q = z + y) \\<and> x \\<noteq> y \\<longrightarrow> p \\<noteq> q\"\nby smt\nnext\n  {\n  fix p q r s\n  assume h2: \"\\<forall>x y p q. (\\<exists>z. (x, z) \\<in> b \\<and> p = x + z) \\<and> (\\<exists>z. (y, z) \\<in> b \\<and> q = y + z) \\<and> x \\<noteq> y \\<longrightarrow> p \\<noteq> q\"\n     and h3: \"(p, q) \\<in> b\"\n     and h4: \"(r, s) \\<in> b\"\n     and h5: \"p \\<noteq> r\"\n  hence \"\\<forall>p0 q0. (\\<exists>z. (p, z) \\<in> b \\<and> p0 = p + z) \\<and> (\\<exists>z. (r, z) \\<in> b \\<and> q0 = r + z) \\<and> p \\<noteq> r \\<longrightarrow> p0 \\<noteq> q0\" by blast\n  hence \"\\<forall>p0 q0. ((p, q) \\<in> b \\<and> p0 = p + q) \\<and> ((r, s) \\<in> b \\<and> q0 = r + s) \\<and> p \\<noteq> r \\<longrightarrow> p0 \\<noteq> q0\" by blast\n  hence \"(p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> p+q \\<noteq> r+s\" by blast\n  hence \"p + q \\<noteq> r + s\" using h3 h4 h5 by blast\n  }\n  thus \"\\<forall>x y p q. (\\<exists>z. (x, z) \\<in> b \\<and> p = z + x) \\<and> (\\<exists>z. (y, z) \\<in> b \\<and> q = z + y) \\<and> x \\<noteq> y \\<longrightarrow> p \\<noteq> q \\<Longrightarrow>\n    \\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> q + p \\<noteq> s + r\" by blast\nqed\n\ndefinition safe3c :: \"int rel \\<Rightarrow> bool\" where\n  \"safe3c b = (\\<forall>p q r s. (p,q)\\<in>b \\<and> (r,s)\\<in>b \\<and> p\\<noteq>r \\<longrightarrow> q-p\\<noteq>s-r)\"\n\nlemma safead3c: \"safe3c b \\<longleftrightarrow> allDifferent {(x,y). \\<exists>z. (x,z)\\<in>b \\<and> y=z-x}\"\nproof (simp add: safe3c_def allDifferent_def array_def, standard)\nshow \"\\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> q - p \\<noteq> s - r \\<Longrightarrow>\n    \\<forall>x y p q. (\\<exists>z. (x, z) \\<in> b \\<and> p = z - x) \\<and> (\\<exists>z. (y, z) \\<in> b \\<and> q = z - y) \\<and> x \\<noteq> y \\<longrightarrow> p \\<noteq> q\"\nby smt\nnext\n  {\n  fix p q r s\n  assume h2: \"\\<forall>x y p q. (\\<exists>z. (x, z) \\<in> b \\<and> p = z - x) \\<and> (\\<exists>z. (y, z) \\<in> b \\<and> q = z - y) \\<and> x \\<noteq> y \\<longrightarrow> p \\<noteq> q\"\n     and h3: \"(p, q) \\<in> b\"\n     and h4: \"(r, s) \\<in> b\"\n     and h5: \"p \\<noteq> r\"\n  hence \"\\<forall>p0 q0. (\\<exists>z. (p, z) \\<in> b \\<and> p0 = z - p) \\<and> (\\<exists>z. (r, z) \\<in> b \\<and> q0 = z - r) \\<and> p \\<noteq> r \\<longrightarrow> p0 \\<noteq> q0\" by blast\n  hence \"\\<forall>p0 q0. ((p, q) \\<in> b \\<and> p0 = q - p) \\<and> ((r, s) \\<in> b \\<and> q0 = s - r) \\<and> p \\<noteq> r \\<longrightarrow> p0 \\<noteq> q0\" by blast\n  hence \"(p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> q-p \\<noteq> s-r\" by blast\n  hence \"q-p \\<noteq> s-r\" using h3 h4 h5 by blast\n  }\n  thus \"\\<forall>x y p q. (\\<exists>z. (x, z) \\<in> b \\<and> p = z - x) \\<and> (\\<exists>z. (y, z) \\<in> b \\<and> q = z - y) \\<and> x \\<noteq> y \\<longrightarrow> p \\<noteq> q \\<Longrightarrow>\n    \\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> q - p \\<noteq> s - r\" by blast\nqed\n\n\ndefinition nqueens3 :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"nqueens3 n b = (board3 n b \\<and> safe3a b \\<and> safe3b b \\<and> safe3c b)\"\n\nlemma from2to3: \"nqueens3 n b \\<longrightarrow> nqueens2 n b\"\nproof (simp add: nqueens3_def nqueens2_def board3_def safe3a_def, standard)\n  {\n  assume b1:\"board2 n b\"\n     and s1: \"safe2a b\"\n     and s2: \"safe3b b\"\n     and s3: \"safe3c b\"\n     hence \"\\<forall>p q r s. (p, q) \\<in> b \\<and> (r, s) \\<in> b \\<and> p \\<noteq> r \\<longrightarrow> \\<bar>p - r\\<bar> \\<noteq> \\<bar>q - s\\<bar>\" by (smt s3 safe3b_def safe3c_def)\n     hence \"safe2b b\" by (simp add: safe2b_def)\n  }\n  thus \"board2 n b \\<and> safe2a b \\<and> safe3b b \\<and> safe3c b \\<Longrightarrow> safe2b b\" by blast\nqed\n\ndefinition nqueens3i :: \"int \\<Rightarrow> int rel \\<Rightarrow> bool\" where\n  \"nqueens3i n b = (n\\<ge>0 \\<and> array n n b \\<and> \n                    allDifferent b \\<and> \n                    allDifferent {(x,y). \\<exists>z. (x,z)\\<in>b \\<and> y=z+x} \\<and> \n                    allDifferent {(x,y). \\<exists>z. (x,z)\\<in>b \\<and> y=z-x})\"\n\nlemma impl3: \"nqueens3i n b \\<longleftrightarrow> nqueens3 n b\"\nby (simp add: nqueens3_def board3_def board2_def board1_def safe3a_def safe2a_def safead3b safead3c nqueens3i_def)\n\nlemma arrplus: \"array n n b \\<Longrightarrow> {(x, y). \\<exists>z. (x, z) \\<in> b \\<and> y = z + x} = {(x, y). x\\<in>Domain b \\<and> y = valof b x + x}\"\nusing valofarr valofarrev Collect_cong Domain.DomainI Pair_inject case_prodE case_prodI2 by blast\n\nlemma arrminus: \"array n n b \\<Longrightarrow> {(x, y). \\<exists>z. (x, z) \\<in> b \\<and> y = z - x} = {(x, y). x\\<in>Domain b \\<and> y = valof b x - x}\"\nusing valofarr valofarrev Collect_cong Domain.DomainI Pair_inject case_prodE case_prodI2 by blast\n\nlemma implNotation: \"nqueens3i n b \\<longleftrightarrow> (n\\<ge>0 \\<and> array n n b \\<and> \n                    allDifferent b \\<and> \n                    allDifferent {(x,y). x\\<in>Domain b \\<and> y=(valof b x)+x} \\<and> \n                    allDifferent {(x,y). x\\<in>Domain b \\<and> y=(valof b x)-x})\"\napply (simp_all add: nqueens3i_def arrplus arrminus)\napply (auto)\nby (simp_all add: nqueens3i_def arrplus arrminus)\n", "meta": {"author": "miranha", "repo": "SpecCP", "sha": "a41f5135b382e7c77e5c8293b2af0a5d3bfb3a6c", "save_path": "github-repos/isabelle/miranha-SpecCP", "path": "github-repos/isabelle/miranha-SpecCP/SpecCP-a41f5135b382e7c77e5c8293b2af0a5d3bfb3a6c/Nqueens/Isabelle/NQueens_CSP.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952838963489, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.778333920254545}}
{"text": "(*\n  File:     Power_By_Squaring.thy\n  Author:   Manuel Eberl, TU München\n  \n  Fast computing of funpow (applying some functon n times) for weakly associative binary\n  functions using exponentiation by squaring. Yields efficient exponentiation algorithms on\n  monoid_mult and for modular exponentiation \"b ^ e mod m\" (and thus also for \"cong\")\n*)\nsection \\<open>Exponentiation by Squaring\\<close>\ntheory Power_By_Squaring\n  imports MainRLT\nbegin\n\ncontext\n  fixes f :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nbegin\n\nfunction efficient_funpow :: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n  \"efficient_funpow y x 0 = y\"\n| \"efficient_funpow y x (Suc 0) = f x y\"\n| \"n \\<noteq> 0 \\<Longrightarrow> even n \\<Longrightarrow> efficient_funpow y x n = efficient_funpow y (f x x) (n div 2)\"\n| \"n \\<noteq> 1 \\<Longrightarrow> odd n \\<Longrightarrow> efficient_funpow y x n = efficient_funpow (f x y) (f x x) (n div 2)\"\n  by force+\ntermination by (relation \"measure (snd \\<circ> snd)\") (auto elim: oddE)\n\nlemma efficient_funpow_code [code]:\n  \"efficient_funpow y x n =\n     (if n = 0 then y\n      else if n = 1 then f x y\n      else if even n then efficient_funpow y (f x x) (n div 2)\n      else efficient_funpow (f x y) (f x x) (n div 2))\"\n  by (induction y x n rule: efficient_funpow.induct) auto\n\nend\n\nlemma efficient_funpow_correct:\n  assumes f_assoc: \"\\<And>x z. f x (f x z) = f (f x x) z\"\n  shows \"efficient_funpow f y x n = (f x ^^ n) y\"\nproof -\n  have [simp]: \"f ^^ 2 = (\\<lambda>x. f (f x))\" for f :: \"'a \\<Rightarrow> 'a\"\n    by (simp add: eval_nat_numeral o_def)\n  show ?thesis\n    by (induction y x n rule: efficient_funpow.induct[of _ f])\n       (auto elim!: evenE oddE simp: funpow_mult [symmetric] funpow_Suc_right f_assoc\n             simp del: funpow.simps(2))\nqed\n\n(*\n  TODO: This could be used as a code_unfold rule or something like that but the\n  implications are not quite clear. Would this be a good default implementation\n  for powers?\n*)\ncontext monoid_mult\nbegin\n\nlemma power_by_squaring: \"efficient_funpow (*) (1 :: 'a) = (^)\"\nproof (intro ext)\n  fix x :: 'a and n\n  have \"efficient_funpow (*) 1 x n = ((*) x ^^ n) 1\"\n    by (subst efficient_funpow_correct) (simp_all add: mult.assoc)\n  also have \"\\<dots> = x ^ n\"\n    by (induction n) simp_all\n  finally show \"efficient_funpow (*) 1 x n = x ^ n\" .\nqed\n\nend\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Power_By_Squaring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7783339095793999}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n  \ntheory AExp imports Main begin\n  \nsubsection \"Arithmetic Expressions\"\n  \ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname ⇒ val\"\n  \ntext_raw{*\\snip{AExpaexpdef}{2}{1}{% *}\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw{*}%endsnip*}\n  \ntext_raw{*\\snip{AExpavaldef}{1}{2}{% *}\nfun aval :: \"aexp ⇒ state ⇒ val\" where\n  \"aval (N n) s = n\" |\n  \"aval (V x) s = s x\" |\n  \"aval (Plus a⇩1 a⇩2) s = aval a⇩1 s + aval a⇩2 s\"\ntext_raw{*}%endsnip*}\n  \n  \nvalue \"aval (Plus (V ''x'') (N 5)) (λx. if x = ''x'' then 7 else 0)\"\n  \ntext {* The same state more concisely: *}\nvalue \"aval (Plus (V ''x'') (N 5)) ((λx. 0) (''x'':= 7))\"\n  \ntext {* A little syntax magic to write larger states compactly: *}\n  \ndefinition null_state (\"<>\") where\n  \"null_state ≡ λx. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n  \ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"λx. 0\"} compactly:\n*}\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n    \nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n  \n  \ntext {* In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n*}\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n  \ntext{* Note that this @{text\"<…>\"} syntax works for any function space\n@{text\"τ⇩1 ⇒ τ⇩2\"} where @{text \"τ⇩2\"} has a @{text 0}. *}\n  \n  \nsubsection \"Constant Folding\"\n  \ntext{* Evaluate constant subsexpressions: *}\n  \ntext_raw{*\\snip{AExpasimpconstdef}{0}{2}{% *}\nfun asimp_const :: \"aexp ⇒ aexp\" where\n  \"asimp_const (N n) = N n\" |\n  \"asimp_const (V x) = V x\" |\n  \"asimp_const (Plus a⇩1 a⇩2) =\n  (case (asimp_const a⇩1, asimp_const a⇩2) of\n    (N n⇩1, N n⇩2) ⇒ N(n⇩1+n⇩2) |\n    (b⇩1,b⇩2) ⇒ Plus b⇩1 b⇩2)\"\ntext_raw{*}%endsnip*}\n  \ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\n  apply(induction a)\n    apply (auto split: aexp.split)\n  done\n    \ntext{* Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors: *}\n  \ntext_raw{*\\snip{AExpplusdef}{0}{2}{% *}\nfun plus :: \"aexp ⇒ aexp ⇒ aexp\" where\n  \"plus (N i⇩1) (N i⇩2) = N(i⇩1+i⇩2)\" |\n  \"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n  \"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n  \"plus a⇩1 a⇩2 = Plus a⇩1 a⇩2\"\ntext_raw{*}%endsnip*}\n  \nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  (* apply(induction a1 a2 rule: plus.induct) Original. The 'a1 a2' is extraneous. *)\n  apply(induction rule: plus.induct)\n    (* apply(induction a1) apply(induction a2)  Does not work*)\n              apply simp_all (* just for a change from auto *)\n  done\n    \ntext_raw{*\\snip{AExpasimpdef}{2}{0}{% *}\nfun asimp :: \"aexp ⇒ aexp\" where\n  \"asimp (N n) = N n\" |\n  \"asimp (V x) = V x\" |\n  \"asimp (Plus a⇩1 a⇩2) = plus (asimp a⇩1) (asimp a⇩2)\"\ntext_raw{*}%endsnip*}\n  \ntext{* Note that in @{const asimp_const} the optimized constructor was\ninlined. Making it a separate function @{const plus} improves modularity of\nthe code and the proofs. *}\n  \nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n  \ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n  apply simp_all\n  done\n    \n    (* exercise 3.1 *)\n \nfun is_N :: \"aexp ⇒ bool\" where\n  \"is_N (N _) = True\"|\n  \"is_N _ = False\"\n  \n  (* check that expression does not contain any unoptimized sub-expressions, \n      i.e. Plus (N i) (N j) *)\nfun optimal :: \"aexp ⇒ bool\" where\n  (* TODO why won't this, the ∧ function, work? *)\n  (* \"optimal (Plus e1 e2) = (is_N e1) ∧ (is_N e2)\" | *)\n  (* definition conj :: \"[bool, bool] ⇒ bool\"  (infixr \"∧\" 35) *)\n  \"optimal (Plus e1 e2) = Not(conj (is_N e1) (is_N e2))\" |\n  \"optimal _ = True\"\n  \ntheorem asimp_const_is_optimal:\n  \"optimal (asimp_const e)\"  \n  apply(induction e)\n    apply(auto)\n  apply(simp split:aexp.split)\n  done   \n    \n    (* Sum all N's found in expression. Change all values of (N x) to (N 0) in expression.\nAssume that asimp will be run later to cleanup expressions like (Plus (N 0) (V v))\nBecause the only operator is '+' , we can blindly sum all N's.\nhelper for full_asimp *)\nfun sum_Ns :: \"aexp ⇒ int ⇒ (aexp × int)\" where\n  \"sum_Ns (N n) s = (Plus (N 0) (N 0), s+n)\"|\n  \"sum_Ns (V v) s = (V v, s)\"|\n  \"sum_Ns (Plus e⇩1 e⇩2) s = \n    (let (re⇩1, s⇩1) = sum_Ns e⇩1 0;\n         (re⇩2, s⇩2) = sum_Ns e⇩2 0\n      in (Plus re⇩1 re⇩2, s⇩1 + s⇩2))\"\n \n(* When all variables are 0, aval = sum_Ns *)\nlemma aval_sum_Ns:\"aval e <> = snd (sum_Ns e 0)\"\n  apply(induction e)\n    apply(auto)\n   apply (simp add: null_state_def)\n  by (simp add: case_prod_beta)\n \n(* constant folding for aexp where we sum up all constants, even if they are not next to\neach other. For example, Plus (N 1) (Plus (V x ) (N 2)) becomes Plus (V x ) (N 3). *)\nfun full_asimp :: \"aexp ⇒ aexp\" where\n   \"full_asimp e⇩1 = (\n      let (e⇩2, s) = sum_Ns e⇩1 0;\n           e⇩3 = Plus (N s) e⇩2\n      in  asimp e⇩3)\"\n   \nvalue \"full_asimp (Plus (N 1) (Plus (V x ) (N 2)))\"\n  \ntheorem aval_full_asimp[simp]:\n  \"aval (full_asimp e) s = aval e s\"\n  apply(induction e)\n    apply(auto)\n  by (simp add: case_prod_beta)\n    (* by (simp add: case_prod_unfold) *)\n    \n(* Define a substitution function \nsubst :: vname ⇒ aexp ⇒ aexp ⇒ aexp \nsuch that \nsubst x a e \nis the result of replacing every\noccurrence of variable x by a in e *)\nfun subst :: \"vname ⇒ aexp ⇒ aexp ⇒ aexp\" where\n  \"subst matchMe replaceWith (V vname) = \n      (if matchMe = vname\n      then replaceWith\n      else V vname)\"|\n  \"subst matchMe replaceWith (N n) = N n\"|\n  \"subst matchMe replaceWith (Plus e⇩1 e⇩2) = \n      Plus (subst matchMe replaceWith e⇩1) (subst matchMe replaceWith e⇩2)\"\n  \nvalue \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\"\n \n(*   Prove the so-called substitution lemma that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\naval (subst x a e) s = aval e (s(x := aval a s)). As a consequence prove\naval a1 s = aval a2 s =⇒ aval (subst x a1 e) s = aval (subst x a2 e) s. *)\nlemma substitution:\"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply(induction e) \n  by auto\n    \ntheorem foo:\n  \"aval a⇩1 s = aval a⇩2 s \n  ⟹ aval (subst x a⇩1 e) s = aval (subst x a⇩2 e) s\"\n  apply(induction e)\n  by auto\n    \nend\n  \n \n \n", "meta": {"author": "gittywithexcitement", "repo": "isabelle", "sha": "42c53b2797e1b14c741c316f2585449b818a8f07", "save_path": "github-repos/isabelle/gittywithexcitement-isabelle", "path": "github-repos/isabelle/gittywithexcitement-isabelle/isabelle-42c53b2797e1b14c741c316f2585449b818a8f07/Chapter 3/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7782634961486836}}
{"text": "theory R02Sol\n\nimports Complex_Main\nbegin\n\ntext {* Relación 2 *}\n\ntext {* \n  ----------------------------------------------------------------------\n  Ejercicio 1.1. [Plegados sobre árboles]\n  \n  Definir el tipo de dato arbolH para representar los árboles binarios\n  que sólo tienen valores en las hojas. Por ejemplo, el árbol\n       ·\n      / \\\n     3   ·\n        / \\\n       5   7\n  se representa por\n     Nodo (Hoja 3) (Nodo (Hoja 5) (Hoja 7))\n  ------------------------------------------------------------------- *}\n\ndatatype 'a arbolH = \n  Hoja 'a \n| Nodo \"'a arbolH\" \"'a arbolH\"\n\nabbreviation ejArbolH1 :: \"int arbolH\" \nwhere\n  \"ejArbolH1 \\<equiv> Nodo (Hoja (3::int)) (Nodo (Hoja 5) (Hoja 7))\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 1.2. Definir la función\n     infijo :: \"'a arbolH \\<Rightarrow> 'a list\" \n  tal que (infijo x) es el recorrido infijo del árbol hoja x. Por\n  ejemplo,\n     infijo ejArbolH1 = [3,5,7]\n  ------------------------------------------------------------------- *}\n\nfun infijo :: \"'a arbolH \\<Rightarrow> 'a list\" \nwhere\n  \"infijo (Hoja x)   = [x]\"\n| \"infijo (Nodo i d) = infijo i @ infijo d\"  \n\nvalue \"infijo ejArbolH1\"\nlemma \"infijo ejArbolH1 = [3,5,7]\" by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 1.3. Consultar la definición de la función fold de plegado\n  de listas.\n  ------------------------------------------------------------------- *}\n\n-- \"Una forma de consultarlo es\"  \nthm fold.simps  \n\ntext {*\n  El resultado es   \n     fold ?f []         = id\n     fold ?f (?x # ?xs) = fold ?f ?xs \\<circ> ?f ?x\n  *}\n\n-- \"Otra forma de consultarlo es\"  \nthm fold_simps\n\ntext {*\n  El resultado es\n     fold ?f [] ?s         = ?s\n     fold ?f (?x # ?xs) ?s = fold ?f ?xs (?f ?x ?s)\n  *}\n\n-- \"Se puede comprobar la definición\"  \nlemma \n  \"fold f [] s     = s\"\n  \"fold f (x#xs) s = fold f xs (f x s)\" \nby simp_all\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 1.4. Definir la función\n     fold_arbolH :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'a arbolH \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  tal que (fold_arbolH f x y) es plegado del árbol hoja x con la\n  operación f y el valor inicial x. Por ejemplo,\n     fold_arbolH op+ ejArbolH1 0 = 15\n     fold_arbolH op* ejArbolH1 1 = 105\n  ------------------------------------------------------------------- *}\n  \nfun fold_arbolH :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'a arbolH \\<Rightarrow> 'b \\<Rightarrow> 'b\" \nwhere\n  \"fold_arbolH f (Hoja x) y   = f x y\"\n| \"fold_arbolH f (Nodo i d) y = fold_arbolH f d (fold_arbolH f i y)\"\n\nvalue \"fold_arbolH op+ ejArbolH1 0\"\nlemma \"fold_arbolH op+ ejArbolH1 0 = 15\" by simp\nvalue \"fold_arbolH op* ejArbolH1 1\"\nlemma \"fold_arbolH op* ejArbolH1 1 = 105\" by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 1.5. Demostrar que\n     fold_arbolH f x y = fold f (infijo x) y\n  ------------------------------------------------------------------- *}\n\nlemma \"fold_arbolH f x y = fold f (infijo x) y\"  \nby (induction x arbitrary: y) auto\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 1.6. Definir la función\n     espejo :: \"'a arbolH \\<Rightarrow> 'a arbolH\"\n  tal que (espejo x) es la imagen especular del árbol x. Por ejemplo,\n     espejo ejArbolH1 = Nodo (Nodo (Hoja 7) (Hoja 5)) (Hoja 3)\n  ------------------------------------------------------------------- *}\n\nfun espejo :: \"'a arbolH \\<Rightarrow> 'a arbolH\" \nwhere\n  \"espejo (Hoja x)   = Hoja x\"  \n| \"espejo (Nodo i d) = Nodo (espejo d) (espejo i)\"\n\nvalue \"espejo ejArbolH1\"\nlemma \"espejo ejArbolH1 = Nodo (Nodo (Hoja 7) (Hoja 5)) (Hoja 3)\" \n  by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 1.7. Demostrar que\n     infijo (espejo t) = rev (infijo t)\n  ------------------------------------------------------------------- *}\n    \nlemma \"infijo (espejo t) = rev (infijo t)\"  \nby (induction t) auto\n    \ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.1. [Alineamientos de lista]\n  Un alineamiento de dos lista xs e ys es una lista cuyos elementos son\n  los de xs e ys consevando su orden original. Por ejemplo, un\n  alineamiento de [a,b] y [c,d,e] es [a,c,d,b,e] y otro es [c,a,d,e,b].\n  \n  Definir la función\n     alineamientos :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\" \n  tal que (alineamientos xs ys) es la lista de los alineamientos de xs e\n  ys. Por ejemplo, \n     alineamientos [a,b] [c,d,e] \n     = [[a,b,c,d,e],[a,c,b,d,e],[a,c,d,b,e],[a,c,d,e,b],[c,a,b,d,e],\n        [c,a,d,b,e],[c,a,d,e,b],[c,d,a,b,e],[c,d,a,e,b],[c,d,e,a,b]]\n  ------------------------------------------------------------------- *}\n\nfun alineamientos :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list list\"  \nwhere\n  \"alineamientos xs []         = [xs]\"\n| \"alineamientos [] ys         = [ys]\"  \n| \"alineamientos (x#xs) (y#ys) = \n    map (op # x) (alineamientos xs (y#ys)) @ \n    map (op # y) (alineamientos (x#xs) ys)\"  \n   \nvalue \"alineamientos [a,b] [c,d,e]\"\nlemma \"alineamientos [a,b] [c,d,e] =\n       [[a,b,c,d,e],[a,c,b,d,e],[a,c,d,b,e],[a,c,d,e,b],[c,a,b,d,e],\n        [c,a,d,b,e],[c,a,d,e,b],[c,d,a,b,e],[c,d,a,e,b],[c,d,e,a,b]]\"\n  by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 2.2. Demostrar que la longitud de cualquier alineamiento de\n  las listas xs e ys es la suma de las longitudes de los alineamientos\n  de xs e ys.\n  ------------------------------------------------------------------- *}\n\nlemma \"zs \\<in> set (alineamientos xs ys) \\<Longrightarrow> \n       length zs = length xs + length ys\"\napply (induction xs ys arbitrary: zs rule: alineamientos.induct)\napply auto  \ndone  \n\ntext {* Nota. La función set convierte una lista en el conjunto de sus\n  elementos. Por ejemplo, el resultado de\n     value \"set [a,b,c]\"\n  es   \n     \"{a, b, c}\"\n      :: \"'a set\"\n  *}\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 3.1. [Plegado de listas]\n  \n  Definir, por recursión, la función\n     suma1 :: \"int list \\<Rightarrow> int\" \n  tal que (suma1 xs) es la suma de los elementos de la lista xs. Por\n  ejemplo, \n     suma1 [3,1,4] = 8\n  ------------------------------------------------------------------- *}\n  \nfun suma1 :: \"int list \\<Rightarrow> int\" \nwhere\n  \"suma1 []     = 0\"\n| \"suma1 (x#xs) = x + suma1 xs\"  \n\nvalue \"suma1 [3,1,4]\"\nlemma \"suma1 [3,1,4] = 8\" by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 3.2. Definir, por plegado, la función\n     suma2 :: \"int list \\<Rightarrow> int\" \n  tal que (suma2 xs) es la suma de los elementos de la lista xs. Por\n  ejemplo, \n     suma2 [3,1,4] = 8\n  ------------------------------------------------------------------- *}\n  \ndefinition suma2 :: \"int list \\<Rightarrow> int\" \nwhere \n  \"suma2 xs \\<equiv> fold op+ xs 0\"\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 3.3. Demostrar que las funciones suma1 y suma2 son\n  equivalentes.\n  ------------------------------------------------------------------- *}\n\nlemma aux: \"fold op+ xs a = suma1 xs + a\"  \nby (induction xs arbitrary: a) auto\n  \nlemma \"suma1 xs = suma2 xs\"\nby (simp add: aux suma2_def)\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 4.1. [Lista con elementos distintos]\n  \n  Definir, por recursión, la función\n     pertenece :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" \n  tal que (pertenece x ys) se verifica si x es un elemento de ys. Por\n  ejemplo, \n     pertenece 2 [7,2,5] = True\n     pertenece 4 [7,2,5] = False\n  ------------------------------------------------------------------- *}\n\nfun pertenece :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" \nwhere\n  \"pertenece x []     = False\"\n| \"pertenece x (y#ys) = (x = y \\<or> pertenece x ys)\"\n\nvalue \"pertenece 4 [7,2,(5::nat)]\"\nlemma \"pertenece 4 [7,2,(5::nat)] = False\" by simp\nvalue \"pertenece 2 [7,2,(5::nat)]\"\nlemma \"pertenece 2 [7,2,(5::nat)] = True\" by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 4.2. Definir la función\n     distintos :: \"'a list \\<Rightarrow> bool\n  tal que (distintos xs) se verifica si la lista xs no tiene elementos\n  repetidos. Por ejemplo, \n     distintos [7,2,5] = True\n     distintos [7,2,7] = False\n  ------------------------------------------------------------------- *}\n\nfun distintos :: \"'a list \\<Rightarrow> bool\" \nwhere\n  \"distintos []     = True\"\n| \"distintos (x#xs) = (\\<not>(pertenece x xs) \\<and> distintos xs)\"\n\nvalue \"distintos [7,2,(5::nat)]\"\nlemma \"distintos [7,2,(5::nat)] = True\" by simp\nvalue \"distintos [7,2,(7::nat)]\"\nlemma \"distintos [7,2,(7::nat)] = False\" by simp\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 4.3. Demostrar que la inversa de una lista no tiene\n  repeticiones si, y sólo si, la lista original no tiene repeticiones. \n  ------------------------------------------------------------------- *}\n\nlemma pertenece_conc:\n  \"pertenece x (ys @ zs) = (pertenece x ys \\<or> pertenece x zs)\"\nby (induction ys) simp_all\n\nlemma pertenece_rev:\n  \"pertenece x (rev ys) = pertenece x ys\"\nby (induction ys) (auto simp add: pertenece_conc)\n\nlemma distintos_conc:\n  \"distintos (xs @ [y]) = ( \\<not>(pertenece y xs) \\<and> distintos xs)\"\nby (induction xs) (auto simp add: pertenece_conc)  \n\nlemma \"distintos (rev xs) = distintos xs\"\nby (induction xs) (auto simp add: distintos_conc pertenece_rev)\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 5.1. [Plegados de listas por la derecha y por la izquierda]\n  \n  Consultar las definidiciones de fold y foldr\n  ------------------------------------------------------------------- *}\n\nthm fold.simps\nthm foldr.simps\n\ntext {*\n  El resultado es\n    fold ?f []         = id\n    fold ?f (?x # ?xs) = fold ?f ?xs \\<circ> ?f ?x\n    \n    foldr ?f []         = id\n    foldr ?f (?x # ?xs) = ?f ?x \\<circ> foldr ?f ?xs\n*}\n\nlemma \"fold  f [a,b,c] d = f c (f b (f a d))\" by simp\nlemma \"foldr f [a,b,c] d = f a (f b (f c d))\" by simp\n\nlemma \"foldr (op-) [1,2,3::int] 7 = (1 - (2 - (3 - 7)))\" by auto\nlemma \"fold  (op-) [1,2,3::int] 7 = 3 - (2 - (1 - 7)) \" by auto\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 5.2. Definir, usando fold, la función\n     longitud1 :: \"'a list \\<Rightarrow> nat\" \n  tal que (longitud1 xs) es la longitud de la lista xs. Por ejemplo,\n     longitud1 [a,b,c] = 3\n  ------------------------------------------------------------------- *}\n\ndefinition longitud1 :: \"'a list \\<Rightarrow> nat\" \nwhere\n  \"longitud1 xs = fold (\\<lambda>x. Suc) xs 0\"\n\nvalue \"longitud1 [a,b,c]\"  \nlemma \"longitud1 [a,b,c] = 3\" by (simp add: longitud1_def)  \n  \ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 5.3. Definir, usando fold, la función\n     longitud2 :: \"'a list \\<Rightarrow> nat\" \n  tal que (longitud2 xs) es la longitud de la lista xs. Por ejemplo,\n     longitud2 [a,b,c] = 3\n  ------------------------------------------------------------------- *}\n\ndefinition longitud2 :: \"'a list \\<Rightarrow> nat\" \nwhere\n  \"longitud2 xs = foldr (\\<lambda>x. Suc) xs 0\"\n  \nvalue \"longitud2 [a,b,c]\"  \nlemma \"longitud2 [a,b,c] = 3\" by (simp add: longitud2_def)  \n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 5.4. Demostrar que las funciones longitud1 y length son\n  equivalentes.\n  ------------------------------------------------------------------- *}\n\nlemma aux_fold:\n  \"fold (\\<lambda>x. Suc) xs y  = y + length xs\"\nby (induction xs arbitrary: y) auto\n\nlemma \"longitud1 xs = length xs\"\nby (simp add: longitud1_def aux_fold)\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 5.5. Demostrar que las funciones longitud2 y length son\n  equivalentes.\n  ------------------------------------------------------------------- *}\n\nlemma aux_foldr:\n  \"foldr (\\<lambda>x. Suc) xs y  = y + length xs\"\nby (induction xs arbitrary: y) auto\n\nlemma \"longitud2 xs = length xs\"\nby (simp add: longitud2_def aux_foldr)\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 6.1. [Cortes de listas]\n  \n  Dada una lista xs, el corte de xs de longitud menor o igual que m con\n  inicio en i es la lista formada por el elemento de xs en la posición i\n  y en las m-1 siguientes posiciones (si existen dichos elementos). \n  \n  Definir la función\n     corte :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\"\n  tal que (corte xs i m) es el corte de xs de longitud menor o igual que\n  m que empieza en la posición i. Por ejemplo, \n     \"corte [0,1,2,3,4,5,6] 2 3 = [2,3,4] \n     \"corte [0,1,2,3,4,5,6] 2 9 = [2,3,4,5,6] \n     \"corte [0,1,2,3,4,5,6] 9 9 = []\n  ------------------------------------------------------------------- *}\n\ndefinition corte :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\"\nwhere\n  \"corte xs i m = take m (drop i xs)\"\n\ndeclare corte_def [simp]\n  \nlemma \"corte [0,1,2,3,4,5,6 ::int] 2 3 = [2,3,4]\" by simp\nlemma \"corte [0,1,2,3,4,5,6 ::int] 2 9 = [2,3,4,5,6]\" by simp \nlemma \"corte [0,1,2,3,4,5,6 ::int] 9 9 = []\" by simp\n  \ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 6.2. Demostrar que la concatenación de dos cortes adyacentes\n  se puede expresar como un único corte.\n  ------------------------------------------------------------------- *}\n\nlemma \"corte xs i m1 @ corte xs (i + m1) m2 = corte xs i (m1 + m2)\"\nby (induction xs) (auto simp add: take_add add.commute)\n\ntext {*\n  Los lemas utilizados son\n  + take_add:    take (i + j) xs = take i xs @ take j (drop i xs)\n  + add.commute: a + b = b + a\n*}\n\ntext {*\n  ----------------------------------------------------------------------\n  Ejercicio 6.3. Demostrar que los cortes en listas de elementos no\n  repetidos no tienen elementos repetidos.\n  ------------------------------------------------------------------- *}\n\nlemma pertenece_take:\n  \"pertenece a (take n xs) \\<Longrightarrow> pertenece a xs\"\nby (metis append_take_drop_id pertenece_conc)\n \nlemma distintos_take:\n  \"distintos xs \\<Longrightarrow> distintos (take n xs)\"\napply (induction xs arbitrary: n)\napply simp\napply (case_tac n)\n  apply (auto simp add: pertenece_take)\ndone\n\nlemma pertenece_drop:\n  \"pertenece a (drop n xs) \\<Longrightarrow> pertenece a xs\"\nby (metis append_take_drop_id pertenece_conc)\n\nlemma distintos_drop:\n  \"distintos xs \\<Longrightarrow> distintos (drop n xs)\"\napply (induction xs arbitrary: n)\napply simp\napply (case_tac n)\n  apply (auto simp add: pertenece_drop)\ndone\n  \nlemma \"distintos xs \\<Longrightarrow> distintos (corte xs i m)\"\nby (induct xs) (auto simp add: distintos_take distintos_drop)\n\nend\n\n", "meta": {"author": "jaalonso", "repo": "AFV", "sha": "4605a58a1ad82f2255ac8bbe8d931942fd3d095c", "save_path": "github-repos/isabelle/jaalonso-AFV", "path": "github-repos/isabelle/jaalonso-AFV/AFV-4605a58a1ad82f2255ac8bbe8d931942fd3d095c/Ejercicios/R02Sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.9073122213606241, "lm_q1q2_score": 0.7782634913487338}}
{"text": "(*\n    Author:     Wenda Li <wl302@cam.ac.uk / liwenda1990@hotmail.com>\n*)\n\nsection \\<open>Some useful lemmas in topology\\<close>\n\ntheory Missing_Topology imports \"HOL-Analysis.Multivariate_Analysis\"\nbegin\n\nsubsection \\<open>Misc\\<close>    \n \nlemma open_times_image:\n  fixes S::\"'a::real_normed_field set\"\n  assumes \"open S\" \"c\\<noteq>0\"\n  shows \"open (((*) c) ` S)\" \nproof -\n  let ?f = \"\\<lambda>x. x/c\" and ?g=\"((*) c)\"\n  have \"continuous_on UNIV ?f\" using \\<open>c\\<noteq>0\\<close> by (auto intro:continuous_intros)\n  then have \"open (?f -` S)\" using \\<open>open S\\<close> by (auto elim:open_vimage)\n  moreover have \"?g ` S = ?f -` S\" using \\<open>c\\<noteq>0\\<close>\n    using image_iff by fastforce\n  ultimately show ?thesis by auto\nqed   \n \nlemma image_linear_greaterThan:\n  fixes x::\"'a::linordered_field\"\n  assumes \"c\\<noteq>0\"\n  shows \"((\\<lambda>x. c*x+b) ` {x<..}) = (if c>0 then {c*x+b <..} else {..< c*x+b})\"\nusing \\<open>c\\<noteq>0\\<close>\n  apply (auto simp add:image_iff field_simps)    \n  subgoal for y by (rule bexI[where x=\"(y-b)/c\"],auto simp add:field_simps)\n  subgoal for y by (rule bexI[where x=\"(y-b)/c\"],auto simp add:field_simps)\ndone\n\nlemma image_linear_lessThan:\n  fixes x::\"'a::linordered_field\"\n  assumes \"c\\<noteq>0\"\n  shows \"((\\<lambda>x. c*x+b) ` {..<x}) = (if c>0 then {..<c*x+b} else {c*x+b<..})\"\nusing \\<open>c\\<noteq>0\\<close>\n  apply (auto simp add:image_iff field_simps)    \n  subgoal for y by (rule bexI[where x=\"(y-b)/c\"],auto simp add:field_simps)\n  subgoal for y by (rule bexI[where x=\"(y-b)/c\"],auto simp add:field_simps)\ndone    \n \nlemma continuous_on_neq_split:\n  fixes f :: \"'a::linear_continuum_topology \\<Rightarrow> 'b::linorder_topology\"\n  assumes \"\\<forall>x\\<in>s. f x\\<noteq>y\" \"continuous_on s f\" \"connected s\"\n  shows \"(\\<forall>x\\<in>s. f x>y) \\<or> (\\<forall>x\\<in>s. f x<y)\"\n  by (smt (verit) assms connectedD_interval connected_continuous_image imageE image_eqI leI) \n\nlemma\n  fixes f::\"'a::linorder_topology \\<Rightarrow> 'b::topological_space\"\n  assumes \"continuous_on {a..b} f\" \"a<b\"\n  shows continuous_on_at_left:\"continuous (at_left b) f\" \n    and continuous_on_at_right:\"continuous (at_right a) f\"\n  using assms continuous_on_Icc_at_leftD continuous_within apply blast\n  using assms continuous_on_Icc_at_rightD continuous_within by blast\n \nsubsection \\<open>More about @{term eventually}\\<close>    \n    \nlemma eventually_comp_filtermap:\n    \"eventually (P o f) F \\<longleftrightarrow> eventually P (filtermap f F)\"\n  unfolding comp_def using eventually_filtermap by auto\n \nlemma eventually_at_infinityI:\n  fixes P::\"'a::real_normed_vector \\<Rightarrow> bool\"\n  assumes \"\\<And>x. c \\<le> norm x \\<Longrightarrow> P x\"\n  shows \"eventually P at_infinity\"  \nunfolding eventually_at_infinity using assms by auto\n   \nlemma eventually_at_bot_linorderI:\n  fixes c::\"'a::linorder\"\n  assumes \"\\<And>x. x \\<le> c \\<Longrightarrow> P x\"\n  shows \"eventually P at_bot\"\n  using assms by (auto simp: eventually_at_bot_linorder)     \n\nsubsection \\<open>More about @{term filtermap}\\<close> \n\nlemma filtermap_linear_at_within:\n  assumes \"bij f\" and cont: \"isCont f a\" and open_map: \"\\<And>S. open S \\<Longrightarrow> open (f`S)\"\n  shows \"filtermap f (at a within S) = at (f a) within f`S\"\n  unfolding filter_eq_iff\nproof safe\n  fix P\n  assume \"eventually P (filtermap f (at a within S))\"\n  then obtain T where \"open T\" \"a \\<in> T\" and impP:\"\\<forall>x\\<in>T. x\\<noteq>a \\<longrightarrow> x\\<in>S\\<longrightarrow> P (f x)\"\n    by (auto simp: eventually_filtermap eventually_at_topological)\n  then show \"eventually P (at (f a) within f ` S)\"\n    unfolding eventually_at_topological\n    apply (intro exI[of _ \"f`T\"])\n    using \\<open>bij f\\<close> open_map by (metis bij_pointE imageE imageI)  \nnext\n  fix P\n  assume \"eventually P (at (f a) within f ` S)\"\n  then obtain T1 where \"open T1\" \"f a \\<in> T1\" and impP:\"\\<forall>x\\<in>T1. x\\<noteq>f a \\<longrightarrow> x\\<in>f`S\\<longrightarrow> P (x)\"\n    unfolding eventually_at_topological by auto\n  then obtain T2 where \"open T2\" \"a \\<in> T2\" \"(\\<forall>x'\\<in>T2. f x' \\<in> T1)\" \n    using cont[unfolded continuous_at_open,rule_format,of T1] by blast \n  then have \"\\<forall>x\\<in>T2. x\\<noteq>a \\<longrightarrow> x\\<in>S\\<longrightarrow> P (f x)\"\n    using impP by (metis assms(1) bij_pointE imageI)\n  then show \"eventually P (filtermap f (at a within S))\" \n    unfolding eventually_filtermap eventually_at_topological \n    apply (intro exI[of _ T2])\n    using \\<open>open T2\\<close> \\<open>a \\<in> T2\\<close> by auto\nqed\n  \nlemma filtermap_at_bot_linear_eq:\n  fixes c::\"'a::linordered_field\"\n  assumes \"c\\<noteq>0\"\n  shows \"filtermap (\\<lambda>x. x * c + b) at_bot = (if c>0 then at_bot else at_top)\"\nproof (cases \"c>0\")\n  case True\n  then have \"filtermap (\\<lambda>x. x * c + b) at_bot = at_bot\" \n    apply (intro filtermap_fun_inverse[of \"\\<lambda>x. (x-b) / c\"])\n    subgoal unfolding eventually_at_bot_linorder filterlim_at_bot\n      by (auto simp add: field_simps)\n    subgoal unfolding eventually_at_bot_linorder filterlim_at_bot\n      by (metis mult.commute real_affinity_le)\n    by auto\n  then show ?thesis using \\<open>c>0\\<close> by auto\nnext\n  case False\n  then have \"c<0\" using \\<open>c\\<noteq>0\\<close> by auto\n  then have \"filtermap (\\<lambda>x. x * c + b) at_bot = at_top\"\n    apply (intro filtermap_fun_inverse[of \"\\<lambda>x. (x-b) / c\"])\n    subgoal unfolding eventually_at_top_linorder filterlim_at_bot\n      by (meson le_diff_eq neg_divide_le_eq)\n    subgoal unfolding eventually_at_bot_linorder filterlim_at_top\n      using \\<open>c < 0\\<close> by (meson False diff_le_eq le_divide_eq)\n    by auto\n  then show ?thesis using \\<open>c<0\\<close> by auto\nqed  \n  \nlemma filtermap_linear_at_left:\n  fixes c::\"'a::{linordered_field,linorder_topology,real_normed_field}\"\n  assumes \"c\\<noteq>0\"\n  shows \"filtermap (\\<lambda>x. c*x+b) (at_left x) = (if c>0 then at_left (c*x+b) else at_right (c*x+b))\"\nproof -\n  let ?f = \"\\<lambda>x. c*x+b\"\n  have \"filtermap (\\<lambda>x. c*x+b) (at_left x) = (at (?f x) within ?f ` {..<x})\"\n  proof (subst filtermap_linear_at_within)\n    show \"bij ?f\" using \\<open>c\\<noteq>0\\<close> \n      by (auto intro!: o_bij[of \"\\<lambda>x. (x-b)/c\"])\n    show \"isCont ?f x\" by auto\n    show \"\\<And>S. open S \\<Longrightarrow> open (?f ` S)\" \n      using open_times_image[OF _ \\<open>c\\<noteq>0\\<close>,THEN open_translation,of _ b]  \n      by (simp add:image_image add.commute)\n    show \"at (?f x) within ?f ` {..<x} = at (?f x) within ?f ` {..<x}\" by simp\n  qed\n  moreover have \"?f ` {..<x} =  {..<?f x}\" when \"c>0\" \n    using image_linear_lessThan[OF \\<open>c\\<noteq>0\\<close>,of b x] that by auto\n  moreover have \"?f ` {..<x} =  {?f x<..}\" when \"\\<not> c>0\" \n    using image_linear_lessThan[OF \\<open>c\\<noteq>0\\<close>,of b x] that by auto\n  ultimately show ?thesis by auto\nqed\n    \nlemma filtermap_linear_at_right:\n  fixes c::\"'a::{linordered_field,linorder_topology,real_normed_field}\"\n  assumes \"c\\<noteq>0\"\n  shows \"filtermap (\\<lambda>x. c*x+b) (at_right x) = (if c>0 then at_right (c*x+b) else at_left (c*x+b))\" \nproof -\n  let ?f = \"\\<lambda>x. c*x+b\"\n  have \"filtermap ?f (at_right x) = (at (?f x) within ?f ` {x<..})\"\n  proof (subst filtermap_linear_at_within)\n    show \"bij ?f\" using \\<open>c\\<noteq>0\\<close> \n      by (auto intro!: o_bij[of \"\\<lambda>x. (x-b)/c\"])\n    show \"isCont ?f x\" by auto\n    show \"\\<And>S. open S \\<Longrightarrow> open (?f ` S)\" \n      using open_times_image[OF _ \\<open>c\\<noteq>0\\<close>,THEN open_translation,of _ b]  \n      by (simp add:image_image add.commute)\n    show \"at (?f x) within ?f ` {x<..} = at (?f x) within ?f ` {x<..}\" by simp\n  qed\n  moreover have \"?f ` {x<..} =  {?f x<..}\" when \"c>0\" \n    using image_linear_greaterThan[OF \\<open>c\\<noteq>0\\<close>,of b x] that by auto\n  moreover have \"?f ` {x<..} =  {..<?f x}\" when \"\\<not> c>0\" \n    using image_linear_greaterThan[OF \\<open>c\\<noteq>0\\<close>,of b x] that by auto\n  ultimately show ?thesis by auto\nqed\n \nlemma filtermap_at_top_linear_eq:\n  fixes c::\"'a::linordered_field\"\n  assumes \"c\\<noteq>0\"\n  shows \"filtermap (\\<lambda>x. x * c + b) at_top = (if c>0 then at_top else at_bot)\"\nproof (cases \"c>0\")\n  case True\n  then have \"filtermap (\\<lambda>x. x * c + b) at_top = at_top\" \n    apply (intro filtermap_fun_inverse[of \"\\<lambda>x. (x-b) / c\"])\n    subgoal unfolding eventually_at_top_linorder filterlim_at_top \n      by (meson le_diff_eq pos_le_divide_eq)\n    subgoal unfolding eventually_at_top_linorder filterlim_at_top\n      apply auto\n      by (metis mult.commute real_le_affinity) \n    by auto\n  then show ?thesis using \\<open>c>0\\<close> by auto\nnext\n  case False\n  then have \"c<0\" using \\<open>c\\<noteq>0\\<close> by auto\n  then have \"filtermap (\\<lambda>x. x * c + b) at_top = at_bot\"\n    apply (intro filtermap_fun_inverse[of \"\\<lambda>x. (x-b) / c\"])\n    subgoal unfolding eventually_at_bot_linorder filterlim_at_top\n      by (auto simp add: field_simps)\n    subgoal unfolding eventually_at_top_linorder filterlim_at_bot\n      by (meson le_diff_eq neg_divide_le_eq)\n    by auto\n  then show ?thesis using \\<open>c<0\\<close> by auto\nqed\n\nsubsection \\<open>More about @{term filterlim}\\<close>\n  \nlemma filterlim_at_top_linear_iff:\n  fixes f::\"'a::linordered_field \\<Rightarrow> 'b\"\n  assumes \"c\\<noteq>0\"\n  shows \"(LIM x at_top. f (x * c + b) :> F2) \\<longleftrightarrow> (if c>0 then (LIM x at_top. f x :> F2) \n            else (LIM x at_bot. f x :> F2))\"\n  unfolding filterlim_def\n  apply (subst filtermap_filtermap[of f \"\\<lambda>x. x * c + b\",symmetric])\n  using assms by (auto simp add:filtermap_at_top_linear_eq)\n    \nlemma filterlim_at_bot_linear_iff:\n  fixes f::\"'a::linordered_field \\<Rightarrow> 'b\"\n  assumes \"c\\<noteq>0\"\n  shows \"(LIM x at_bot. f (x * c + b) :> F2) \\<longleftrightarrow> (if c>0 then (LIM x at_bot. f x :> F2) \n            else (LIM x at_top. f x :> F2)) \"\n  unfolding filterlim_def \n  apply (subst filtermap_filtermap[of f \"\\<lambda>x. x * c + b\",symmetric])\n  using assms by (auto simp add:filtermap_at_bot_linear_eq)      \n  \n  \nlemma filterlim_tendsto_add_at_top_iff:\n  assumes f: \"(f \\<longlongrightarrow> c) F\"\n  shows \"(LIM x F. (f x + g x :: real) :> at_top) \\<longleftrightarrow> (LIM x F. g x :> at_top)\"\nproof     \n  assume \"LIM x F. f x + g x :> at_top\" \n  moreover have \"((\\<lambda>x. - f x) \\<longlongrightarrow> - c) F\"\n    using f by (intro tendsto_intros,simp)\n  ultimately show \"filterlim g at_top F\" using filterlim_tendsto_add_at_top \n    by fastforce\nqed (auto simp add:filterlim_tendsto_add_at_top[OF f])    \n    \n  \nlemma filterlim_tendsto_add_at_bot_iff:\n  fixes c::real\n  assumes f: \"(f \\<longlongrightarrow> c) F\"\n  shows \"(LIM x F. f x + g x :> at_bot) \\<longleftrightarrow> (LIM x F. g x :> at_bot)\" \nproof -\n  have \"(LIM x F. f x + g x :> at_bot) \n        \\<longleftrightarrow>  (LIM x F. - f x + (- g x)  :> at_top)\"\n    apply (subst filterlim_uminus_at_top)\n    by (rule filterlim_cong,auto)\n  also have \"... = (LIM x F. - g x  :> at_top)\"\n    apply (subst filterlim_tendsto_add_at_top_iff[of _ \"-c\"])\n    by (auto intro:tendsto_intros simp add:f)\n  also have \"... = (LIM x F. g x  :> at_bot)\"\n    apply (subst filterlim_uminus_at_top)\n    by (rule filterlim_cong,auto)\n  finally show ?thesis .\nqed\n  \nlemma tendsto_inverse_0_at_infinity: \n    \"LIM x F. f x :> at_infinity \\<Longrightarrow> ((\\<lambda>x. inverse (f x) :: real) \\<longlongrightarrow> 0) F\"\n  by (metis filterlim_at filterlim_inverse_at_iff)\n\n(*\nlemma filterlim_at_top_tendsto[elim]:\n  fixes f::\"'a \\<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}\" and F::\"'a filter\"\n  assumes top:\"filterlim f at_top F\" and tendsto: \"(f \\<longlongrightarrow> c) F\" \n          and \"F\\<noteq>bot\"\n  shows False\nproof -\n  obtain cc where \"cc>c\" using gt_ex by blast\n  have \"\\<forall>\\<^sub>F x in F. cc < f x\" \n    using top unfolding filterlim_at_top_dense by auto\n  moreover have \"\\<forall>\\<^sub>F x in F. f x < cc\" \n    using tendsto order_tendstoD(2)[OF _ \\<open>cc>c\\<close>] by auto\n  ultimately have \"\\<forall>\\<^sub>F x in F. cc < f x \\<and> f x < cc\" \n    using eventually_conj by auto\n  then have \"\\<forall>\\<^sub>F x in F. False\" by (auto elim:eventually_mono)\n  then show False using \\<open>F\\<noteq>bot\\<close> by auto\nqed\n\nlemma filterlim_at_bot_tendsto[elim]:\n  fixes f::\"'a \\<Rightarrow> 'b::{unbounded_dense_linorder,order_topology}\" and F::\"'a filter\"\n  assumes top:\"filterlim f at_bot F\" and tendsto: \"(f \\<longlongrightarrow> c) F\" \n          and \"F\\<noteq>bot\"\n  shows False\nproof -\n  obtain cc where \"cc<c\" using lt_ex by blast\n  have \"\\<forall>\\<^sub>F x in F. cc > f x\" \n    using top unfolding filterlim_at_bot_dense by auto\n  moreover have \"\\<forall>\\<^sub>F x in F. f x > cc\" \n    using tendsto order_tendstoD(1)[OF _ \\<open>cc<c\\<close>] by auto\n  ultimately have \"\\<forall>\\<^sub>F x in F. cc < f x \\<and> f x < cc\" \n    using eventually_conj by auto\n  then have \"\\<forall>\\<^sub>F x in F. False\" by (auto elim:eventually_mono)\n  then show False using \\<open>F\\<noteq>bot\\<close> by auto\nqed\n*)\n  \nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Winding_Number_Eval/Missing_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7782224679788837}}
{"text": "(*  Author:     Steven Obua, TU Muenchen *)\n\nsection \\<open>Various algebraic structures combined with a lattice\\<close>\n\ntheory Lattice_Algebras\n  imports Complex_Main\nbegin\n\nclass semilattice_inf_ab_group_add = ordered_ab_group_add + semilattice_inf\nbegin\n\nlemma add_inf_distrib_left: \"a + inf b c = inf (a + b) (a + c)\"\n  apply (rule order.antisym)\n   apply (simp_all add: le_infI)\n  apply (rule add_le_imp_le_left [of \"uminus a\"])\n  apply (simp only: add.assoc [symmetric], simp add: diff_le_eq add.commute)\n  done\n\nlemma add_inf_distrib_right: \"inf a b + c = inf (a + c) (b + c)\"\nproof -\n  have \"c + inf a b = inf (c + a) (c + b)\"\n    by (simp add: add_inf_distrib_left)\n  then show ?thesis\n    by (simp add: add.commute)\nqed\n\nend\n\nclass semilattice_sup_ab_group_add = ordered_ab_group_add + semilattice_sup\nbegin\n\nlemma add_sup_distrib_left: \"a + sup b c = sup (a + b) (a + c)\"\n  apply (rule order.antisym)\n   apply (rule add_le_imp_le_left [of \"uminus a\"])\n   apply (simp only: add.assoc [symmetric], simp)\n   apply (simp add: le_diff_eq add.commute)\n  apply (rule le_supI)\n   apply (rule add_le_imp_le_left [of \"a\"], simp only: add.assoc[symmetric], simp)+\n  done\n\nlemma add_sup_distrib_right: \"sup a b + c = sup (a + c) (b + c)\"\nproof -\n  have \"c + sup a b = sup (c+a) (c+b)\"\n    by (simp add: add_sup_distrib_left)\n  then show ?thesis\n    by (simp add: add.commute)\nqed\n\nend\n\nclass lattice_ab_group_add = ordered_ab_group_add + lattice\nbegin\n\nsubclass semilattice_inf_ab_group_add ..\nsubclass semilattice_sup_ab_group_add ..\n\nlemmas add_sup_inf_distribs =\n  add_inf_distrib_right add_inf_distrib_left add_sup_distrib_right add_sup_distrib_left\n\nlemma inf_eq_neg_sup: \"inf a b = - sup (- a) (- b)\"\nproof (rule inf_unique)\n  fix a b c :: 'a\n  show \"- sup (- a) (- b) \\<le> a\"\n    by (rule add_le_imp_le_right [of _ \"sup (uminus a) (uminus b)\"])\n      (simp, simp add: add_sup_distrib_left)\n  show \"- sup (-a) (-b) \\<le> b\"\n    by (rule add_le_imp_le_right [of _ \"sup (uminus a) (uminus b)\"])\n      (simp, simp add: add_sup_distrib_left)\n  assume \"a \\<le> b\" \"a \\<le> c\"\n  then show \"a \\<le> - sup (-b) (-c)\"\n    by (subst neg_le_iff_le [symmetric]) (simp add: le_supI)\nqed\n\nlemma sup_eq_neg_inf: \"sup a b = - inf (- a) (- b)\"\nproof (rule sup_unique)\n  fix a b c :: 'a\n  show \"a \\<le> - inf (- a) (- b)\"\n    by (rule add_le_imp_le_right [of _ \"inf (uminus a) (uminus b)\"])\n      (simp, simp add: add_inf_distrib_left)\n  show \"b \\<le> - inf (- a) (- b)\"\n    by (rule add_le_imp_le_right [of _ \"inf (uminus a) (uminus b)\"])\n      (simp, simp add: add_inf_distrib_left)\n  show \"- inf (- a) (- b) \\<le> c\" if \"a \\<le> c\" \"b \\<le> c\"\n    using that by (subst neg_le_iff_le [symmetric]) (simp add: le_infI)\nqed\n\nlemma neg_inf_eq_sup: \"- inf a b = sup (- a) (- b)\"\n  by (simp add: inf_eq_neg_sup)\n\nlemma diff_inf_eq_sup: \"a - inf b c = a + sup (- b) (- c)\"\n  using neg_inf_eq_sup [of b c, symmetric] by simp\n\nlemma neg_sup_eq_inf: \"- sup a b = inf (- a) (- b)\"\n  by (simp add: sup_eq_neg_inf)\n\nlemma diff_sup_eq_inf: \"a - sup b c = a + inf (- b) (- c)\"\n  using neg_sup_eq_inf [of b c, symmetric] by simp\n\nlemma add_eq_inf_sup: \"a + b = sup a b + inf a b\"\nproof -\n  have \"0 = - inf 0 (a - b) + inf (a - b) 0\"\n    by (simp add: inf_commute)\n  then have \"0 = sup 0 (b - a) + inf (a - b) 0\"\n    by (simp add: inf_eq_neg_sup)\n  then have \"0 = (- a + sup a b) + (inf a b + (- b))\"\n    by (simp only: add_sup_distrib_left add_inf_distrib_right) simp\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\n\nsubsection \\<open>Positive Part, Negative Part, Absolute Value\\<close>\n\ndefinition nprt :: \"'a \\<Rightarrow> 'a\"\n  where \"nprt x = inf x 0\"\n\ndefinition pprt :: \"'a \\<Rightarrow> 'a\"\n  where \"pprt x = sup x 0\"\n\nlemma pprt_neg: \"pprt (- x) = - nprt x\"\nproof -\n  have \"sup (- x) 0 = sup (- x) (- 0)\"\n    by (simp only: minus_zero)\n  also have \"\\<dots> = - inf x 0\"\n    by (simp only: neg_inf_eq_sup)\n  finally have \"sup (- x) 0 = - inf x 0\" .\n  then show ?thesis\n    by (simp only: pprt_def nprt_def)\nqed\n\nlemma nprt_neg: \"nprt (- x) = - pprt x\"\nproof -\n  from pprt_neg have \"pprt (- (- x)) = - nprt (- x)\" .\n  then have \"pprt x = - nprt (- x)\" by simp\n  then show ?thesis by simp\nqed\n\nlemma prts: \"a = pprt a + nprt a\"\n  by (simp add: pprt_def nprt_def flip: add_eq_inf_sup)\n\nlemma zero_le_pprt[simp]: \"0 \\<le> pprt a\"\n  by (simp add: pprt_def)\n\nlemma nprt_le_zero[simp]: \"nprt a \\<le> 0\"\n  by (simp add: nprt_def)\n\nlemma le_eq_neg: \"a \\<le> - b \\<longleftrightarrow> a + b \\<le> 0\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n    by (rule add_le_imp_le_right[of _ \"uminus b\" _]) (simp add: add.assoc \\<open>?lhs\\<close>)\nnext\n  assume ?rhs\n  show ?lhs\n    by (rule add_le_imp_le_right[of _ \"b\" _]) (simp add: \\<open>?rhs\\<close>)\nqed\n\nlemma pprt_0[simp]: \"pprt 0 = 0\" by (simp add: pprt_def)\nlemma nprt_0[simp]: \"nprt 0 = 0\" by (simp add: nprt_def)\n\nlemma pprt_eq_id [simp, no_atp]: \"0 \\<le> x \\<Longrightarrow> pprt x = x\"\n  by (simp add: pprt_def sup_absorb1)\n\nlemma nprt_eq_id [simp, no_atp]: \"x \\<le> 0 \\<Longrightarrow> nprt x = x\"\n  by (simp add: nprt_def inf_absorb1)\n\nlemma pprt_eq_0 [simp, no_atp]: \"x \\<le> 0 \\<Longrightarrow> pprt x = 0\"\n  by (simp add: pprt_def sup_absorb2)\n\nlemma nprt_eq_0 [simp, no_atp]: \"0 \\<le> x \\<Longrightarrow> nprt x = 0\"\n  by (simp add: nprt_def inf_absorb2)\n\nlemma sup_0_imp_0:\n  assumes \"sup a (- a) = 0\"\n  shows \"a = 0\"\nproof -\n  have pos: \"0 \\<le> a\" if \"sup a (- a) = 0\" for a :: 'a\n  proof -\n    from that have \"sup a (- a) + a = a\"\n      by simp\n    then have \"sup (a + a) 0 = a\"\n      by (simp add: add_sup_distrib_right)\n    then have \"sup (a + a) 0 \\<le> a\"\n      by simp\n    then show ?thesis\n      by (blast intro: order_trans inf_sup_ord)\n  qed\n  from assms have **: \"sup (-a) (-(-a)) = 0\"\n    by (simp add: sup_commute)\n  from pos[OF assms] pos[OF **] show \"a = 0\"\n    by simp\nqed\n\nlemma inf_0_imp_0: \"inf a (- a) = 0 \\<Longrightarrow> a = 0\"\n  apply (simp add: inf_eq_neg_sup)\n  apply (simp add: sup_commute)\n  apply (erule sup_0_imp_0)\n  done\n\nlemma inf_0_eq_0 [simp, no_atp]: \"inf a (- a) = 0 \\<longleftrightarrow> a = 0\"\n  apply (rule iffI)\n   apply (erule inf_0_imp_0)\n  apply simp\n  done\n\nlemma sup_0_eq_0 [simp, no_atp]: \"sup a (- a) = 0 \\<longleftrightarrow> a = 0\"\n  apply (rule iffI)\n   apply (erule sup_0_imp_0)\n  apply simp\n  done\n\nlemma zero_le_double_add_iff_zero_le_single_add [simp]: \"0 \\<le> a + a \\<longleftrightarrow> 0 \\<le> a\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    from that have a: \"inf (a + a) 0 = 0\"\n      by (simp add: inf_commute inf_absorb1)\n    have \"inf a 0 + inf a 0 = inf (inf (a + a) 0) a\"  (is \"?l = _\")\n      by (simp add: add_sup_inf_distribs inf_aci)\n    then have \"?l = 0 + inf a 0\"\n      by (simp add: a, simp add: inf_commute)\n    then have \"inf a 0 = 0\"\n      by (simp only: add_right_cancel)\n    then show ?thesis\n      unfolding le_iff_inf by (simp add: inf_commute)\n  qed\n  show ?lhs if ?rhs\n    by (simp add: add_mono[OF that that, simplified])\nqed\n\nlemma double_zero [simp]: \"a + a = 0 \\<longleftrightarrow> a = 0\"\n  using add_nonneg_eq_0_iff order.eq_iff by auto\n\nlemma zero_less_double_add_iff_zero_less_single_add [simp]: \"0 < a + a \\<longleftrightarrow> 0 < a\"\n  by (meson le_less_trans less_add_same_cancel2 less_le_not_le\n      zero_le_double_add_iff_zero_le_single_add)\n\nlemma double_add_le_zero_iff_single_add_le_zero [simp]: \"a + a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\nproof -\n  have \"a + a \\<le> 0 \\<longleftrightarrow> 0 \\<le> - (a + a)\"\n    by (subst le_minus_iff) simp\n  moreover have \"\\<dots> \\<longleftrightarrow> a \\<le> 0\"\n    by (simp only: minus_add_distrib zero_le_double_add_iff_zero_le_single_add) simp\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma double_add_less_zero_iff_single_less_zero [simp]: \"a + a < 0 \\<longleftrightarrow> a < 0\"\nproof -\n  have \"a + a < 0 \\<longleftrightarrow> 0 < - (a + a)\"\n    by (subst less_minus_iff) simp\n  moreover have \"\\<dots> \\<longleftrightarrow> a < 0\"\n    by (simp only: minus_add_distrib zero_less_double_add_iff_zero_less_single_add) simp\n  ultimately show ?thesis\n    by blast\nqed\n\ndeclare neg_inf_eq_sup [simp]\n  and neg_sup_eq_inf [simp]\n  and diff_inf_eq_sup [simp]\n  and diff_sup_eq_inf [simp]\n\nlemma le_minus_self_iff: \"a \\<le> - a \\<longleftrightarrow> a \\<le> 0\"\nproof -\n  from add_le_cancel_left [of \"uminus a\" \"plus a a\" zero]\n  have \"a \\<le> - a \\<longleftrightarrow> a + a \\<le> 0\"\n    by (simp flip: add.assoc)\n  then show ?thesis\n    by simp\nqed\n\nlemma minus_le_self_iff: \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a\"\nproof -\n  have \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a + a\"\n    using add_le_cancel_left [of \"uminus a\" zero \"plus a a\"]\n    by (simp flip: add.assoc)\n  then show ?thesis\n    by simp\nqed\n\nlemma zero_le_iff_zero_nprt: \"0 \\<le> a \\<longleftrightarrow> nprt a = 0\"\n  unfolding le_iff_inf by (simp add: nprt_def inf_commute)\n\nlemma le_zero_iff_zero_pprt: \"a \\<le> 0 \\<longleftrightarrow> pprt a = 0\"\n  unfolding le_iff_sup by (simp add: pprt_def sup_commute)\n\nlemma le_zero_iff_pprt_id: \"0 \\<le> a \\<longleftrightarrow> pprt a = a\"\n  unfolding le_iff_sup by (simp add: pprt_def sup_commute)\n\nlemma zero_le_iff_nprt_id: \"a \\<le> 0 \\<longleftrightarrow> nprt a = a\"\n  unfolding le_iff_inf by (simp add: nprt_def inf_commute)\n\nlemma pprt_mono [simp, no_atp]: \"a \\<le> b \\<Longrightarrow> pprt a \\<le> pprt b\"\n  unfolding le_iff_sup by (simp add: pprt_def sup_aci sup_assoc [symmetric, of a])\n\nlemma nprt_mono [simp, no_atp]: \"a \\<le> b \\<Longrightarrow> nprt a \\<le> nprt b\"\n  unfolding le_iff_inf by (simp add: nprt_def inf_aci inf_assoc [symmetric, of a])\n\nend\n\nlemmas add_sup_inf_distribs =\n  add_inf_distrib_right add_inf_distrib_left add_sup_distrib_right add_sup_distrib_left\n\n\nclass lattice_ab_group_add_abs = lattice_ab_group_add + abs +\n  assumes abs_lattice: \"\\<bar>a\\<bar> = sup a (- a)\"\nbegin\n\nlemma abs_prts: \"\\<bar>a\\<bar> = pprt a - nprt a\"\nproof -\n  have \"0 \\<le> \\<bar>a\\<bar>\"\n  proof -\n    have a: \"a \\<le> \\<bar>a\\<bar>\" and b: \"- a \\<le> \\<bar>a\\<bar>\"\n      by (auto simp add: abs_lattice)\n    show ?thesis\n      by (rule add_mono [OF a b, simplified])\n  qed\n  then have \"0 \\<le> sup a (- a)\"\n    unfolding abs_lattice .\n  then have \"sup (sup a (- a)) 0 = sup a (- a)\"\n    by (rule sup_absorb1)\n  then show ?thesis\n    by (simp add: add_sup_inf_distribs ac_simps pprt_def nprt_def abs_lattice)\nqed\n\nsubclass ordered_ab_group_add_abs\nproof\n  have abs_ge_zero [simp]: \"0 \\<le> \\<bar>a\\<bar>\" for a\n  proof -\n    have a: \"a \\<le> \\<bar>a\\<bar>\" and b: \"- a \\<le> \\<bar>a\\<bar>\"\n      by (auto simp add: abs_lattice)\n    show \"0 \\<le> \\<bar>a\\<bar>\"\n      by (rule add_mono [OF a b, simplified])\n  qed\n  have abs_leI: \"a \\<le> b \\<Longrightarrow> - a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\" for a b\n    by (simp add: abs_lattice le_supI)\n  fix a b\n  show \"0 \\<le> \\<bar>a\\<bar>\"\n    by simp\n  show \"a \\<le> \\<bar>a\\<bar>\"\n    by (auto simp add: abs_lattice)\n  show \"\\<bar>-a\\<bar> = \\<bar>a\\<bar>\"\n    by (simp add: abs_lattice sup_commute)\n  show \"- a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\" if \"a \\<le> b\"\n    using that by (rule abs_leI)\n  show \"\\<bar>a + b\\<bar> \\<le> \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\n  proof -\n    have g: \"\\<bar>a\\<bar> + \\<bar>b\\<bar> = sup (a + b) (sup (- a - b) (sup (- a + b) (a + (- b))))\"\n      (is \"_ = sup ?m ?n\")\n      by (simp add: abs_lattice add_sup_inf_distribs ac_simps)\n    have a: \"a + b \\<le> sup ?m ?n\"\n      by simp\n    have b: \"- a - b \\<le> ?n\"\n      by simp\n    have c: \"?n \\<le> sup ?m ?n\"\n      by simp\n    from b c have d: \"- a - b \\<le> sup ?m ?n\"\n      by (rule order_trans)\n    have e: \"- a - b = - (a + b)\"\n      by simp\n    from a d e have \"\\<bar>a + b\\<bar> \\<le> sup ?m ?n\"\n      apply -\n      apply (drule abs_leI)\n       apply (simp_all only: algebra_simps minus_add)\n      apply (metis add_uminus_conv_diff d sup_commute uminus_add_conv_diff)\n      done\n    with g[symmetric] show ?thesis by simp\n  qed\nqed\n\nend\n\nlemma sup_eq_if:\n  fixes a :: \"'a::{lattice_ab_group_add,linorder}\"\n  shows \"sup a (- a) = (if a < 0 then - a else a)\"\n  using add_le_cancel_right [of a a \"- a\", symmetric, simplified]\n    and add_le_cancel_right [of \"-a\" a a, symmetric, simplified]\n  by (auto simp: sup_max max.absorb1 max.absorb2)\n\nlemma abs_if_lattice:\n  fixes a :: \"'a::{lattice_ab_group_add_abs,linorder}\"\n  shows \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\"\n  by auto\n\nlemma estimate_by_abs:\n  fixes a b c :: \"'a::lattice_ab_group_add_abs\"\n  assumes \"a + b \\<le> c\"\n  shows \"a \\<le> c + \\<bar>b\\<bar>\"\nproof -\n  from assms have \"a \\<le> c + (- b)\"\n    by (simp add: algebra_simps)\n  have \"- b \\<le> \\<bar>b\\<bar>\"\n    by (rule abs_ge_minus_self)\n  then have \"c + (- b) \\<le> c + \\<bar>b\\<bar>\"\n    by (rule add_left_mono)\n  with \\<open>a \\<le> c + (- b)\\<close> show ?thesis\n    by (rule order_trans)\nqed\n\nclass lattice_ring = ordered_ring + lattice_ab_group_add_abs\nbegin\n\nsubclass semilattice_inf_ab_group_add ..\nsubclass semilattice_sup_ab_group_add ..\n\nend\n\nlemma abs_le_mult:\n  fixes a b :: \"'a::lattice_ring\"\n  shows \"\\<bar>a * b\\<bar> \\<le> \\<bar>a\\<bar> * \\<bar>b\\<bar>\"\nproof -\n  let ?x = \"pprt a * pprt b - pprt a * nprt b - nprt a * pprt b + nprt a * nprt b\"\n  let ?y = \"pprt a * pprt b + pprt a * nprt b + nprt a * pprt b + nprt a * nprt b\"\n  have a: \"\\<bar>a\\<bar> * \\<bar>b\\<bar> = ?x\"\n    by (simp only: abs_prts[of a] abs_prts[of b] algebra_simps)\n  have bh: \"u = a \\<Longrightarrow> v = b \\<Longrightarrow>\n            u * v = pprt a * pprt b + pprt a * nprt b +\n                    nprt a * pprt b + nprt a * nprt b\" for u v :: 'a\n    apply (subst prts[of u], subst prts[of v])\n    apply (simp add: algebra_simps)\n    done\n  note b = this[OF refl[of a] refl[of b]]\n  have xy: \"- ?x \\<le> ?y\"\n    apply simp\n    apply (metis (full_types) add_increasing add_uminus_conv_diff\n      lattice_ab_group_add_class.minus_le_self_iff minus_add_distrib mult_nonneg_nonneg\n      mult_nonpos_nonpos nprt_le_zero zero_le_pprt)\n    done\n  have yx: \"?y \\<le> ?x\"\n    apply simp\n    apply (metis (full_types) add_nonpos_nonpos add_uminus_conv_diff\n      lattice_ab_group_add_class.le_minus_self_iff minus_add_distrib mult_nonneg_nonpos\n      mult_nonpos_nonneg nprt_le_zero zero_le_pprt)\n    done\n  have i1: \"a * b \\<le> \\<bar>a\\<bar> * \\<bar>b\\<bar>\"\n    by (simp only: a b yx)\n  have i2: \"- (\\<bar>a\\<bar> * \\<bar>b\\<bar>) \\<le> a * b\"\n    by (simp only: a b xy)\n  show ?thesis\n    apply (rule abs_leI)\n    apply (simp add: i1)\n    apply (simp add: i2[simplified minus_le_iff])\n    done\nqed\n\ninstance lattice_ring \\<subseteq> ordered_ring_abs\nproof\n  fix a b :: \"'a::lattice_ring\"\n  assume a: \"(0 \\<le> a \\<or> a \\<le> 0) \\<and> (0 \\<le> b \\<or> b \\<le> 0)\"\n  show \"\\<bar>a * b\\<bar> = \\<bar>a\\<bar> * \\<bar>b\\<bar>\"\n  proof -\n    have s: \"(0 \\<le> a * b) \\<or> (a * b \\<le> 0)\"\n      apply auto\n      apply (rule_tac split_mult_pos_le)\n      apply (rule_tac contrapos_np[of \"a * b \\<le> 0\"])\n      apply simp\n      apply (rule_tac split_mult_neg_le)\n      using a\n      apply blast\n      done\n    have mulprts: \"a * b = (pprt a + nprt a) * (pprt b + nprt b)\"\n      by (simp flip: prts)\n    show ?thesis\n    proof (cases \"0 \\<le> a * b\")\n      case True\n      then show ?thesis\n        apply (simp_all add: mulprts abs_prts)\n        using a\n        apply (auto simp add:\n          algebra_simps\n          iffD1[OF zero_le_iff_zero_nprt] iffD1[OF le_zero_iff_zero_pprt]\n          iffD1[OF le_zero_iff_pprt_id] iffD1[OF zero_le_iff_nprt_id])\n        apply(drule (1) mult_nonneg_nonpos[of a b], simp)\n        apply(drule (1) mult_nonneg_nonpos2[of b a], simp)\n        done\n    next\n      case False\n      with s have \"a * b \\<le> 0\"\n        by simp\n      then show ?thesis\n        apply (simp_all add: mulprts abs_prts)\n        apply (insert a)\n        apply (auto simp add: algebra_simps)\n        apply(drule (1) mult_nonneg_nonneg[of a b],simp)\n        apply(drule (1) mult_nonpos_nonpos[of a b],simp)\n        done\n    qed\n  qed\nqed\n\nlemma mult_le_prts:\n  fixes a b :: \"'a::lattice_ring\"\n  assumes \"a1 \\<le> a\"\n    and \"a \\<le> a2\"\n    and \"b1 \\<le> b\"\n    and \"b \\<le> b2\"\n  shows \"a * b \\<le>\n    pprt a2 * pprt b2 + pprt a1 * nprt b2 + nprt a2 * pprt b1 + nprt a1 * nprt b1\"\nproof -\n  have \"a * b = (pprt a + nprt a) * (pprt b + nprt b)\"\n    by (subst prts[symmetric])+ simp\n  then have \"a * b = pprt a * pprt b + pprt a * nprt b + nprt a * pprt b + nprt a * nprt b\"\n    by (simp add: algebra_simps)\n  moreover have \"pprt a * pprt b \\<le> pprt a2 * pprt b2\"\n    by (simp_all add: assms mult_mono)\n  moreover have \"pprt a * nprt b \\<le> pprt a1 * nprt b2\"\n  proof -\n    have \"pprt a * nprt b \\<le> pprt a * nprt b2\"\n      by (simp add: mult_left_mono assms)\n    moreover have \"pprt a * nprt b2 \\<le> pprt a1 * nprt b2\"\n      by (simp add: mult_right_mono_neg assms)\n    ultimately show ?thesis\n      by simp\n  qed\n  moreover have \"nprt a * pprt b \\<le> nprt a2 * pprt b1\"\n  proof -\n    have \"nprt a * pprt b \\<le> nprt a2 * pprt b\"\n      by (simp add: mult_right_mono assms)\n    moreover have \"nprt a2 * pprt b \\<le> nprt a2 * pprt b1\"\n      by (simp add: mult_left_mono_neg assms)\n    ultimately show ?thesis\n      by simp\n  qed\n  moreover have \"nprt a * nprt b \\<le> nprt a1 * nprt b1\"\n  proof -\n    have \"nprt a * nprt b \\<le> nprt a * nprt b1\"\n      by (simp add: mult_left_mono_neg assms)\n    moreover have \"nprt a * nprt b1 \\<le> nprt a1 * nprt b1\"\n      by (simp add: mult_right_mono_neg assms)\n    ultimately show ?thesis\n      by simp\n  qed\n  ultimately show ?thesis\n    by - (rule add_mono | simp)+\nqed\n\nlemma mult_ge_prts:\n  fixes a b :: \"'a::lattice_ring\"\n  assumes \"a1 \\<le> a\"\n    and \"a \\<le> a2\"\n    and \"b1 \\<le> b\"\n    and \"b \\<le> b2\"\n  shows \"a * b \\<ge>\n    nprt a1 * pprt b2 + nprt a2 * nprt b2 + pprt a1 * pprt b1 + pprt a2 * nprt b1\"\nproof -\n  from assms have a1: \"- a2 \\<le> -a\"\n    by auto\n  from assms have a2: \"- a \\<le> -a1\"\n    by auto\n  from mult_le_prts[of \"- a2\" \"- a\" \"- a1\" \"b1\" b \"b2\",\n    OF a1 a2 assms(3) assms(4), simplified nprt_neg pprt_neg]\n  have le: \"- (a * b) \\<le>\n    - nprt a1 * pprt b2 + - nprt a2 * nprt b2 +\n    - pprt a1 * pprt b1 + - pprt a2 * nprt b1\"\n    by simp\n  then have \"- (- nprt a1 * pprt b2 + - nprt a2 * nprt b2 +\n      - pprt a1 * pprt b1 + - pprt a2 * nprt b1) \\<le> a * b\"\n    by (simp only: minus_le_iff)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\ninstance int :: lattice_ring\nproof\n  show \"\\<bar>k\\<bar> = sup k (- k)\" for k :: int\n    by (auto simp add: sup_int_def)\nqed\n\ninstance real :: lattice_ring\nproof\n  show \"\\<bar>a\\<bar> = sup a (- a)\" for a :: real\n    by (auto simp add: sup_real_def)\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Lattice_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8740772335247531, "lm_q1q2_score": 0.7781859167360728}}
{"text": "theory Walk\n  imports\n    Graph\n    \"Misc\"\nbegin\n\nsection \\<open>Walks\\<close>\n\ntext \\<open>\nA walk is an alternating sequence v_0, e_1, v_2, ..., e_k, v_k of vertices v_i and edges e_i\nsuch that the endpoints of e_i are v_{i-1} and v_i for every i = 1, ..., k.\nWe represent a walk by the sequence of its vertices.\n\\<close>\n\ntype_synonym 'a walk = \"'a list\"\n\n(* Adapted from the formalization of undirected graphs by Mohammad Abdulaziz. *)\ninductive consistent_seq where\n  consistent_seq_Nil: \"consistent_seq G []\" |\n  consistent_seq_Cons: \"v \\<in> vertices G \\<Longrightarrow> consistent_seq G [v]\" |\n  consistent_seq_Cons_Cons: \"\\<lbrakk> {v, v'} \\<in> edges G; consistent_seq G (v' # vs) \\<rbrakk> \\<Longrightarrow>\n    consistent_seq G (v # v' # vs)\"\n\ndeclare consistent_seq_Nil [simp]\ninductive_simps consistent_seq_Cons [simp]: \"consistent_seq G [v]\"\ninductive_simps consistent_seq_Cons_Cons [simp]: \"consistent_seq G (v # v' # vs)\"\n\ndefinition walk :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"walk G u p v \\<equiv> p \\<noteq> [] \\<and> u = hd p \\<and> v = last p \\<and> consistent_seq G p\"\n\ntext \\<open>A walk is closed if its endpoints are the same.\\<close>\n\nabbreviation closed_walk :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<Rightarrow> bool\" where\n  \"closed_walk G v c \\<equiv> walk G v c v \\<and> Suc 0 < length c\"\n\n(* Adapted from the formalization of undirected graphs by Mohammad Abdulaziz. *)\nfun walk_edges :: \"'a walk \\<Rightarrow> 'a set list\" where\n  \"walk_edges [] = []\" |\n  \"walk_edges [v] = []\" |\n  \"walk_edges (v # v' # vs) = {v, v'} # (walk_edges (v' # vs))\"\n\nlemmas walk_induct = walk_edges.induct\n\ntext \\<open>The length of a walk is the number of its edges.\\<close>\n\nabbreviation walk_length :: \"'a walk \\<Rightarrow> nat\" where\n  \"walk_length p \\<equiv> length (walk_edges p)\"\n\nsubsection \\<open>Basic Lemmas\\<close>\n\nlemma Cons_Cons_walk_iff:\n  shows \"walk G u (v # v' # vs) w \\<longleftrightarrow> u = v \\<and> {v, v'} \\<in> edges G \\<and> walk G v' (v' # vs) w\"\n  by (auto simp add: walk_def)\n\nlemma singleton_is_walk:\n  assumes \"v \\<in> vertices G\"\n  shows \"walk G v [v] v\"\n  using assms\n  by (simp add: walk_def)\n\nlemma (in graph) edge_is_walk:\n  assumes \"{u, v} \\<in> edges G\"\n  shows \"walk G u [u, v] v\"\nproof -\n  have \"{u, v} \\<subseteq> vertices G\"\n    using assms\n    by (rule edge_subset_vertices)\n  hence \"v \\<in> vertices G\"\n    by simp\n  hence \"walk G v [v] v\"\n    by (simp add: walk_def)\n  thus ?thesis\n    using assms\n    by (simp add: Cons_Cons_walk_iff)\nqed\n\nlemma (in graph) edge_iff_walk:\n  shows \"{u, v} \\<in> edges G = walk G u [u, v] v\"\nproof\n  assume \"{u, v} \\<in> edges G\"\n  thus \"walk G u [u, v] v\"\n    by (rule edge_is_walk)\nnext\n  assume \"walk G u [u, v] v\"\n  thus \"{u, v} \\<in> edges G\"\n    by (simp add: Cons_Cons_walk_iff)\nqed\n\nlemma walk_length:\n  assumes \"p \\<noteq> []\"\n  shows \"length p = Suc (walk_length p)\"\n  using assms\n  by (induction p rule: walk_induct) simp+\n\n(**)\nsubsection \\<open>\\<close>\n\nlemma (in graph) walk_in_vertices:\n  assumes \"walk G u p v\"\n  assumes \"w \\<in> set p\"\n  shows \"w \\<in> vertices G\"\n  using assms\nproof (induction p arbitrary: u rule: walk_induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 _)\n  thus ?case\n    by (simp add: walk_def)\nnext\n  case (3 _ _ _)\n  thus ?case\n    using Union_edges_subset_vertices\n    by (auto simp add: walk_def)\nqed\n\nlemma (in graph) walk_hd_in_vertices:\n  assumes \"walk G u p v\"\n  shows \"u \\<in> vertices G\"\n  using assms\n  by (intro walk_in_vertices) (simp add: walk_def)+\n\nlemma (in graph) walk_last_in_vertices:\n  assumes \"walk G u p v\"\n  shows \"v \\<in> vertices G\"\n  using assms\n  by (intro walk_in_vertices) (simp add: walk_def)+\n\nlemma walk_hd_neq_last_implies_edges_non_empty:\n  assumes \"walk G u p v\"\n  assumes \"u \\<noteq> v\"\n  shows \"edges G \\<noteq> {}\"\n  using assms\n  by (induction p rule: walk_induct) (auto simp add: walk_def)\n\nlemma walk_edges_in_edges:\n  assumes \"walk G u p w\"\n  shows \"set (walk_edges p) \\<subseteq> edges G\"\n  using assms\nproof (induction p arbitrary: u rule: walk_induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 _)\n  thus ?case\n    by simp\nnext\n  case (3 v v' vs)\n  have \"walk G v' (v' # vs) w\"\n    using \"3.prems\"\n    by (simp add: Cons_Cons_walk_iff)\n  hence \"set (walk_edges (v' # vs)) \\<subseteq> edges G\"\n    by (rule \"3.IH\")\n  moreover have \"{v, v'} \\<in> edges G\"\n    using \"3.prems\"\n    by (simp add: Cons_Cons_walk_iff)\n  ultimately show ?case\n    by simp\nqed\n\nsubsection \\<open>Prefixes/suffixes of walks\\<close>\n\nlemma (in graph) walk_prefix_is_walk:\n  assumes \"p \\<noteq> []\"\n  assumes \"walk G u (p @ q) w\"\n  shows \"walk G u p (last p)\"\n  using assms\nproof (induction p arbitrary: u rule: walk_induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 _)\n  thus ?case\n    by (auto simp add: walk_def intro: walk_in_vertices)\nnext\n  case (3 _ _ _)\n  thus ?case\n    by (simp add: walk_def)\nqed\n\nlemma tl_consistent_seq:\n  assumes \"consistent_seq G p\"\n  shows \"consistent_seq G (tl p)\"\n  using assms\n  by (induction p rule: walk_induct) simp+\n\nlemma suffix_consistent_seq:\n  assumes \"consistent_seq G (p @ q)\"\n  shows \"consistent_seq G q\"\n  using assms\nproof (induction p rule: walk_induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 v)\n  hence \"consistent_seq G (v # q)\"\n    by simp\n  hence \"consistent_seq G (tl (v # q))\"\n    by (rule tl_consistent_seq)\n  thus ?case\n    by simp\nnext\n  case (3 _ _ _)\n  thus ?case\n    by simp\nqed\n\nlemma (in graph) walk_suffix_is_walk:\n  assumes \"q \\<noteq> []\"\n  assumes \"walk G u (p @ q) w\"\n  shows \"walk G (hd q) q w\"\n  using assms\nproof (induction q arbitrary: u rule: walk_induct)\n  case 1\n  thus ?case\n    by simp\nnext\n  case (2 v)\n  have \"v \\<in> vertices G\"\n    using \"2.prems\"(2)\n    by (rule walk_in_vertices) simp\n  thus ?case\n    using \"2.prems\"(2)\n    by (simp add: walk_def)\nnext\n  case (3 v v' vs)\n  have \"consistent_seq G (p @ v # v' # vs)\"\n    using \"3.prems\"(2)\n    by (simp add: walk_def)\n  hence \"consistent_seq G (v # v' # vs)\"\n    by (rule suffix_consistent_seq)\n  thus ?case\n    using \"3.prems\"(2)\n    by (simp add: walk_def)\nqed\n\nsubsection \\<open>Appending walks\\<close>\n\nlemma append_consistent_seq:\n  assumes \"consistent_seq G p\"\n  assumes q_consistent_seq: \"consistent_seq G q\"\n  assumes \"{last p, hd q} \\<in> edges G\"\n  shows \"consistent_seq G (p @ q)\"\n  using assms(1, 3)\nproof (induction p rule: walk_induct)\ncase 1\n  show ?case\n    using q_consistent_seq\n    by simp\nnext\n  case (2 _)\n  show ?case\n  proof (cases q)\n    case Nil\n    thus ?thesis\n      using \"2.prems\"(1)\n      by simp\n  next\n    case (Cons _ _)\n    thus ?thesis\n      using \"2.prems\"(2) q_consistent_seq\n      by simp\n  qed\nnext\n  case (3 _ _ _)\n  thus ?case\n    by simp\nqed\n\nlemma append_consistent_seq_2:\n  assumes p_consistent_seq: \"consistent_seq G p\"\n  assumes q_consistent_seq: \"consistent_seq G q\"\n  assumes \"last p = hd q\"\n  shows \"consistent_seq G (p @ tl q)\"\nproof (cases \"tl q\")\n  case Nil\n  thus ?thesis\n    using p_consistent_seq\n    by simp\nnext\n  case (Cons _ _)\n  hence \"q \\<noteq> []\"\n    by auto\n  hence \"q = hd q # tl q\"\n    by (rule hd_Cons_tl[symmetric])\n  hence \"consistent_seq G (hd q # tl q)\"\n    using q_consistent_seq\n    by simp\n  hence \"{hd q, hd (tl q)} \\<in> edges G\"\n    using q_consistent_seq\n    by (simp add: Cons)\n  thus ?thesis\n    using assms\n    by (intro tl_consistent_seq append_consistent_seq) simp+\nqed\n\nlemma walk_append_is_walk:\n  notes walk_def [simp]\n  assumes p_walk: \"walk G u p v\"\n  assumes q_walk: \"walk G v q w\"\n  shows \"walk G u (p @ tl q) w\"\nproof -\n  have \"q = v # tl q\"\n    using q_walk\n    by simp\n  hence \"w = last (p @ tl q)\"\n    using assms\n    by (cases \"tl q\") simp+\n  moreover have \"consistent_seq G (p @ tl q)\"\n    using assms\n    by (intro append_consistent_seq_2) simp+\n  ultimately show ?thesis\n    using p_walk\n    by simp\nqed\n\nlemma walk_append_append_is_walk:\n  assumes p_walk: \"walk G u p v\"\n  assumes q_walk: \"walk G v q w\"\n  assumes r_walk: \"walk G w r x\"\n  shows \"walk G u (p @ tl q @ tl r) x\"\nproof -\n  have \"walk G u (p @ tl q) w\"\n    using p_walk q_walk\n    by (rule walk_append_is_walk)\n  from walk_append_is_walk[OF this r_walk]\n  show ?thesis\n    by simp\nqed\n\nlemma walk_edges_append:\n  assumes \"p \\<noteq> []\"\n  shows \"walk_edges (p @ q) = walk_edges p @ walk_edges ([last p] @ q)\"\n  using assms\n  by (induction p rule: walk_induct) simp+\n\nlemma walk_edges_append_2:\n  assumes \"q \\<noteq> []\"\n  shows \"walk_edges (p @ q) = walk_edges (p @ [hd q]) @ walk_edges q\"\n  using assms walk_edges_append[of \"p @ [hd q]\" \"tl q\"]\n  by simp\n\nsubsection \\<open>Reversing walks\\<close>\n\nlemma (in graph) rev_consistent_seq:\n  assumes \"consistent_seq G p\"\n  shows \"consistent_seq G (rev p)\"\n  using assms\nproof (induction p rule: walk_induct)\ncase 1\n  thus ?case\n    by simp\nnext\n  case (2 _)\n  thus ?case\n    by simp\nnext\n  case (3 v v' vs)\n  have \"consistent_seq G (rev (v' # vs))\"\n    using \"3.prems\"\n    by (intro \"3.IH\") simp\n  moreover have \"consistent_seq G [v]\"\n    using \"3.prems\" Union_edges_subset_vertices\n    by auto\n  moreover have \"{last (rev (v' # vs)), hd [v]} \\<in> edges G\"\n    using \"3.prems\"\n    by (simp add: insert_commute)\n  ultimately have \"consistent_seq G (rev (v' # vs) @ [v])\"\n    by (rule append_consistent_seq)\n  thus ?case\n    by simp\nqed\n\nlemma (in graph) walk_rev_is_walk:\n  notes walk_def [simp]\n  assumes \"walk G u p v\"\n  shows \"walk G v (rev p) u\"\nproof -\n  have \"(rev p) \\<noteq> []\"\n    using assms\n    by simp\n  moreover have \"v = hd (rev p)\"\n    using assms\n    by (auto intro: hd_rev[symmetric])\n  moreover have \"u = last (rev p)\"\n    using assms\n    by (auto intro: last_rev[symmetric])\n  moreover have \"consistent_seq G (rev p)\"\n    using assms\n    by (intro rev_consistent_seq) simp\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma (in graph) walk_rev:\n  shows \"walk G v (rev p) u = walk G u p v\"\nproof\n  assume \"walk G v (rev p) u\"\n  from walk_rev_is_walk[OF this]\n  show \"walk G u p v\"\n    by simp\nnext\n  assume \"walk G u p v\"\n  from walk_rev_is_walk[OF this]\n  show \"walk G v (rev p) u\"\n    by simp\nqed\n\nlemma walk_edges_rev:\n  shows \"rev (walk_edges p) = walk_edges (rev p)\"\nproof (induction p rule: walk_induct)\ncase 1\n  thus ?case\n    by simp\nnext\n  case (2 _)\n  thus ?case\n    by simp\nnext\n  case (3 v v' vs)\n  have \"rev (walk_edges (v # v' # vs)) = rev ({v, v'} # walk_edges (v' # vs))\"\n    by simp\n  also have \"... = rev (walk_edges (v' # vs)) @ [{v, v'}]\"\n    by simp\n  also have \"... = walk_edges (rev (v' # vs)) @ [{v, v'}]\"\n    by (simp add: \"3.IH\")\n  also have \"... = walk_edges (rev (v' # vs)) @ walk_edges ([last (rev (v' # vs))] @ [v])\"\n    by (simp add: insert_commute)\n  also have \"... = walk_edges (rev (v' # vs) @ [v])\"\n    by (intro walk_edges_append[symmetric]) simp\n  finally show ?case\n    by simp\nqed\n\nsubsection \\<open>Decomposing walks\\<close>\n\nsubsubsection \\<open>Splitting a walk at a vertex\\<close>\n\nfun is_walk_vertex_decomp :: \"'a graph \\<Rightarrow> 'a walk \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<times> 'a walk \\<Rightarrow> bool\" where\n  \"is_walk_vertex_decomp G p v (q, r) \\<longleftrightarrow> p = q @ tl r \\<and> (\\<exists>u w. walk G u q v \\<and> walk G v r w)\"\n\ndefinition walk_vertex_decomp :: \"'a graph \\<Rightarrow> 'a walk \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<times> 'a walk\" where\n  \"walk_vertex_decomp G p v \\<equiv> SOME qr. is_walk_vertex_decomp G p v qr\"\n\nlemma (in graph) walk_vertex_decompE:\n  assumes p_walk: \"walk G u p v\"\n  assumes p_decomp: \"p = xs @ y # ys\"\n  obtains q r where\n    \"p = q @ tl r\"\n    \"q = xs @ [y]\"\n    \"r = y # ys\"\n    \"walk G u q y\"\n    \"walk G y r v\"\nproof\n  define q r where\n    \"q = xs @ [y]\" and\n    \"r = y # ys\"\n  thus\n    \"p = q @ tl r\"\n    \"q = xs @ [y]\"\n    \"r = y # ys\"\n    by (simp add: p_decomp)+\n  thus \"walk G u q y\"\n    using p_walk walk_prefix_is_walk[where ?p = q]\n    by simp\n  show \"walk G y r v\"\n    using p_walk walk_suffix_is_walk[where ?q = r]\n    by (simp add: p_decomp r_def)\nqed\n\nlemma (in graph) walk_vertex_decomp_is_walk_vertex_decomp:\n  assumes p_walk: \"walk G u p w\"\n  assumes v_in_p: \"v \\<in> set p\"\n  shows \"is_walk_vertex_decomp G p v (walk_vertex_decomp G p v)\"\nproof -\n  obtain xs ys where\n    \"p = xs @ v # ys\"\n    using v_in_p\n    by (auto simp add: in_set_conv_decomp)\n  with p_walk\n  obtain q r where\n    \"p = q @ tl r\"\n    \"walk G u q v\"\n    \"walk G v r w\"\n    by (blast elim: walk_vertex_decompE)\n  hence \"is_walk_vertex_decomp G p v (q, r)\"\n    using p_walk\n    by (simp add: walk_def)\n  hence \"\\<exists>qr. is_walk_vertex_decomp G p v qr\"\n    by blast\n  thus ?thesis\n    unfolding walk_vertex_decomp_def\n    ..\nqed\n\nlemma (in graph) walk_vertex_decompE_2:\n  assumes p_walk: \"walk G u p w\"\n  assumes v_in_p: \"v \\<in> set p\"\n  assumes qr_def: \"walk_vertex_decomp G p v = (q, r)\"\n  obtains\n    \"p = q @ tl r\"\n    \"walk G u q v\"\n    \"walk G v r w\"\nproof\n  have \"is_walk_vertex_decomp G p v (q, r)\"\n    unfolding qr_def[symmetric]\n    using p_walk v_in_p\n    by (rule walk_vertex_decomp_is_walk_vertex_decomp)\n  then obtain u' w' where\n    p_decomp: \"p = q @ tl r\" and\n    q_walk: \"walk G u' q v\" and\n    r_walk: \"walk G v r w'\"\n    by auto\n  hence \"walk G u' p w'\"\n    by (blast intro: walk_append_is_walk)\n  hence\n    \"u' = u\"\n    \"w' = w\"\n    using p_walk\n    by (simp add: walk_def)+\n  thus\n    \"p = q @ tl r\"\n    \"walk G u q v\"\n    \"walk G v r w\"\n    using p_decomp q_walk r_walk\n    by simp+\nqed\n\n(**)\nsubsubsection \\<open>\\<close>\n\n(* This subsubsection is largely based on the formalization of directed graphs (Graph_Theory). *)\n\nfun is_walk_closed_walk_decomp :: \"'a graph \\<Rightarrow> 'a walk \\<Rightarrow> 'a walk \\<times> 'a walk \\<times> 'a walk \\<Rightarrow> bool\" where\n  \"is_walk_closed_walk_decomp G p (q, r, s) \\<longleftrightarrow>\n    p = q @ tl r @ tl s \\<and>\n    (\\<exists>u v w. walk G u q v \\<and> closed_walk G v r \\<and> walk G v s w) \\<and>\n    distinct q\"\n\ndefinition walk_closed_walk_decomp :: \"'a graph \\<Rightarrow> 'a walk \\<Rightarrow> 'a walk \\<times> 'a walk \\<times> 'a walk\" where\n  \"walk_closed_walk_decomp G p \\<equiv> SOME qrs. is_walk_closed_walk_decomp G p qrs\"\n\nlemma (in graph) walk_closed_walk_decompE:\n  assumes p_walk: \"walk G u p v\"\n  assumes p_decomp: \"p = xs @ y # ys @ y # zs\"\n  obtains q r s where\n    \"p = q @ tl r @ tl s\"\n    \"q = xs @ [y]\"\n    \"r = y # ys @ [y]\"\n    \"s = y # zs\"\n    \"walk G u q y\"\n    \"walk G y r y\"\n    \"walk G y s v\"\nproof -\n  have \"p = (xs @ y # ys) @ y # zs\"\n    using p_decomp\n    by simp\n  with p_walk\n  obtain qr s where\n    \"p = qr @ tl s\"\n    \"qr = xs @ y # ys @ [y]\"\n    \"s = y # zs\"\n    \"walk G u qr y\"\n    \"walk G y s v\"\n    by (rule walk_vertex_decompE) simp\n  moreover from this(4, 2)\n  obtain q r where\n    \"qr = q @ tl r\"\n    \"q = xs @ [y]\"\n    \"r = y # ys @ [y]\"\n    \"walk G u q y\"\n    \"walk G y r y\"\n    by (erule walk_vertex_decompE)\n  ultimately show ?thesis\n    by (auto intro!: that)\nqed\n\nlemma (in graph) walk_closed_walk_decomp_is_walk_closed_walk_decomp:\n  assumes p_walk: \"walk G u p v\"\n  assumes p_not_distinct: \"\\<not> distinct p\"\n  shows \"is_walk_closed_walk_decomp G p (walk_closed_walk_decomp G p)\"\nproof -\n  obtain xs y ys zs where\n    \"p = xs @ y # ys @ y # zs\" and\n    xs_distinct: \"distinct xs\" and\n    y_not_in_xs: \"y \\<notin> set xs\"\n    using p_not_distinct not_distinct_decomp\n    by blast\n  from p_walk this(1)\n  obtain q r s where\n    \"p = q @ tl r @ tl s\"\n    \"q = xs @ [y]\"\n    \"r = y # ys @ [y]\"\n    \"s = y # zs\"\n    \"walk G u q y\"\n    \"walk G y r y\"\n    \"walk G y s v\"\n    by (erule walk_closed_walk_decompE)\n  moreover hence\n    \"distinct q\"\n    \"Suc 0 < length r\"\n    using xs_distinct y_not_in_xs\n    by simp+\n  ultimately have\n    \"\\<exists>q r s.\n      p = q @ tl r @ tl s \\<and>\n      (\\<exists>u v w. walk G u q v \\<and> closed_walk G v r \\<and> walk G v s w) \\<and>\n      distinct q\"\n    by blast\n  hence \"\\<exists>qrs. is_walk_closed_walk_decomp G p qrs\"\n    by simp\n  thus ?thesis\n    unfolding walk_closed_walk_decomp_def\n    ..\nqed\n\nlemma (in graph) walk_closed_walk_decompE_2:\n  assumes p_walk: \"walk G u p v\"\n  assumes p_not_distinct: \"\\<not> distinct p\"\n  assumes qrs_def: \"walk_closed_walk_decomp G p = (q, r, s)\"\n  obtains\n    \"p = q @ tl r @ tl s\"\n    \"\\<exists>w. walk G u q w \\<and> closed_walk G w r \\<and> walk G w s v\"\n    \"distinct q\"\nproof -\n  have \"is_walk_closed_walk_decomp G p (q, r, s)\"\n    unfolding qrs_def[symmetric]\n    using p_walk p_not_distinct\n    by (rule walk_closed_walk_decomp_is_walk_closed_walk_decomp)\n  then obtain u' w' v' where\n    p_decomp: \"p = q @ tl r @ tl s\" and\n    q_distinct: \"distinct q\" and\n    walks: \"walk G u' q w'\"\n    \"closed_walk G w' r\"\n    \"walk G w' s v'\"\n    by auto\n  hence \"walk G u' p v'\"\n    by (auto simp add: p_decomp intro: walk_append_append_is_walk)\n  hence \"u' = u\" \"v' = v\"\n    using p_walk\n    by (simp add: walk_def)+\n  hence \"\\<exists>w. walk G u q w \\<and> closed_walk G w r \\<and> walk G w s v\"\n    using walks\n    by blast\n  with p_decomp\n  show ?thesis\n    using q_distinct\n    by (rule that)\nqed\n\nsubsection \\<open>Walks in subgraphs/supergraphs\\<close>\n\nlemma (in subgraph) consistent_seq_in_subgraph_implies_consistent_seq_in_supergraph:\n  assumes \"consistent_seq H p\"\n  shows \"consistent_seq G p\"\n  using assms vertices_subset edges_subset\n  by (induction p rule: walk_induct) auto\n\nlemma (in subgraph) walk_subgraph_is_walk_supergraph:\n  assumes \"walk H u p v\"\n  shows \"walk G u p v\"\n  using assms\n  by (auto simp add: walk_def intro: consistent_seq_in_subgraph_implies_consistent_seq_in_supergraph)\n\nlemma (in induced_subgraph) walk_supergraph_is_walk_subgraph:\n  assumes \"walk G u p w\"\n  assumes \"set p \\<subseteq> V\"\n  shows \"walk H u p w\"\n  using assms\n  by (induction p arbitrary: u rule: walk_induct) (auto simp add: walk_def induced)\n  \nsection \\<open>Trails\\<close>\n\ntext \\<open>A trail is a walk in which all edges are distinct.\\<close>\n\ndefinition trail :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"trail G u p v \\<equiv> walk G u p v \\<and> distinct (walk_edges p)\"\n\ntext \\<open>A trail is closed if its endpoints are the same.\\<close>\n\nabbreviation closed_trail :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<Rightarrow> bool\" where\n  \"closed_trail G v c \\<equiv> trail G v c v \\<and> Suc 0 < length c\"\n\nsubsection \\<open>Basic Lemmas\\<close>\n\nlemma closed_trail_implies_Cons:\n  assumes \"closed_trail G v c\"\n  shows \"c = v # tl c\"\n  using assms\n  by (simp add: trail_def walk_def)\n\nlemma closed_trail_implies_tl_non_empty:\n  assumes \"closed_trail G v c\"\n  shows \"tl c \\<noteq> []\"\n  using assms\n  by (simp add: tl_non_empty_conv)\n\n(**)\nsubsection \\<open>\\<close>\n\nlemma (in graph) trail_in_vertices:\n  assumes \"trail G u p v\"\n  assumes \"w \\<in> set p\"\n  shows \"w \\<in> vertices G\"\n  using assms\n  by (auto simp add: trail_def intro: walk_in_vertices)\n\nlemma (in graph) trail_hd_in_vertices:\n  assumes \"trail G u p v\"\n  shows \"u \\<in> vertices G\"\n  using assms\n  by (auto simp add: trail_def intro: walk_hd_in_vertices)\n\nlemma (in graph) trail_last_in_vertices:\n  assumes \"trail G u p v\"\n  shows \"v \\<in> vertices G\"\n  using assms\n  by (auto simp add: trail_def intro: walk_last_in_vertices)\n\nlemma (in graph) closed_trail_tl_hd_in_vertices:\n  assumes \"closed_trail G v c\"\n  shows \"hd (tl c) \\<in> vertices G\"\nproof -\n  have \"hd (tl c) \\<in> set (tl c)\"\n    using assms\n    by (intro closed_trail_implies_tl_non_empty hd_in_set)\n  hence \"hd (tl c) \\<in> set c\"\n    by (auto intro: closed_trail_implies_tl_non_empty list.set_sel(2))\n  with assms\n  show ?thesis\n    by (blast intro: trail_in_vertices)\nqed\n\nsubsection \\<open>Prefixes/suffixes of trails\\<close>\n\nlemma (in graph) trail_prefix_is_trail:\n  notes trail_def [simp]\n  assumes p_non_empty: \"p \\<noteq> []\"\n  assumes p_append_q_trail: \"trail G u (p @ q) v\"\n  shows \"trail G u p (last p)\"\nproof -\n  have \"walk G u p (last p)\"\n    using assms\n    by (auto intro: walk_prefix_is_walk)\n  moreover have \"distinct (walk_edges p)\"\n    using p_append_q_trail p_non_empty\n    by (simp add: walk_edges_append)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma (in graph) trail_suffix_is_trail:\n  notes trail_def [simp]\n  assumes q_non_empty: \"q \\<noteq> []\"\n  assumes p_append_q_trail: \"trail G u (p @ q) v\"\n  shows \"trail G (hd q) q v\"\nproof -\n  have \"walk G (hd q) q v\"\n    using assms\n    by (auto intro: walk_suffix_is_walk)\n  moreover have \"distinct (walk_edges q)\"\n    using p_append_q_trail\n    by (simp add: walk_edges_append_2[OF q_non_empty])\n  ultimately show ?thesis\n    by simp\nqed\n\nsubsection \\<open>Reversing trails\\<close>\n\nlemma (in graph) trail_rev_is_trail:\n  assumes \"trail G u p v\"\n  shows \"trail G v (rev p) u\"\nproof -\n  have \"walk_edges (rev p) = rev (walk_edges p)\"\n    using walk_edges_rev[symmetric]\n    .\n  moreover have \"distinct ...\"\n    using assms\n    by (simp add: trail_def)\n  ultimately have \"distinct (walk_edges (rev p))\"\n    by simp\n  moreover have \"walk G v (rev p) u\"\n    using assms\n    by (intro walk_rev_is_walk) (simp add: trail_def)\n  ultimately show ?thesis\n    by (simp add: trail_def)\nqed\n\nlemma (in graph) closed_trail_rev_is_closed_trail:\n  assumes \"closed_trail G v c\"\n  shows \"closed_trail G v (rev c)\"\nproof -\n  have \"trail G v (rev c) v\"\n    using assms\n    by (intro trail_rev_is_trail) simp\n  moreover have \"Suc 0 < length (rev c)\"\n    using assms\n    by simp\n  ultimately show ?thesis\n    by simp\nqed\n\nsubsection \\<open>Convenience Lemmas\\<close>\n\nlemma (in graph) closed_trail_hd_tl_hd_is_trail:\n  assumes \"closed_trail G v c\"\n  shows \"trail G v [v, hd (tl c)] (hd (tl c))\"\nproof -\n  have \"c = [v, hd (tl c)] @ tl (tl c)\"\n    using assms closed_trail_implies_tl_non_empty\n    by (fastforce simp add: closed_trail_implies_Cons)\n  hence \"trail G v ([v, hd (tl c)] @ tl (tl c)) v\"\n    using assms\n    by simp\n  from trail_prefix_is_trail[OF _ this]\n  show ?thesis\n    by simp\nqed\n\nlemma (in graph) closed_trail_tl_rev_is_trail:\n  assumes \"closed_trail G v c\"\n  shows \"trail G v (rev (tl c)) (hd (tl c))\"\nproof -\n  have \"c = [v] @ tl c\"\n    using assms\n    by (auto simp add: closed_trail_implies_Cons)\n  hence \"trail G v ([v] @ tl c) v\"\n    using assms\n    by simp\n  hence \"trail G (hd (tl c)) (tl c) v\"\n    using assms\n    by (intro closed_trail_implies_tl_non_empty trail_suffix_is_trail)\n  thus ?thesis\n    by (rule trail_rev_is_trail)\nqed\n\nlemma (in graph) closed_trail_hd_tl_hd_neq_tl_rev:\n  assumes \"closed_trail G v c\"\n  shows \"[v, hd (tl c)] \\<noteq> rev (tl c)\"\nproof (rule ccontr)\n  define u where\n    \"u = hd (tl c)\"\n  assume \"\\<not> [v, u] \\<noteq> rev (tl c)\"\n  hence \"rev [u, v] = rev (tl c)\"\n    by simp\n  hence \"[u, v] = tl c\"\n    by blast\n  hence \"c = [v, u, v]\"\n    using assms\n    by (auto simp add: closed_trail_implies_Cons)\n  hence \"\\<not> distinct (walk_edges c)\"\n    by auto\n  hence \"\\<not> trail G v c v\"\n    by (simp add: trail_def)\n  thus \"False\"\n    using assms\n    by simp\nqed\n\nsection \\<open>Paths\\<close>\n\n(* This section is largely based on the formalization of directed graphs (Graph_Theory). *)\n\ntext \\<open>A path is a walk in which all vertices are distinct.\\<close>\n\ndefinition path :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a walk \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"path G u p v \\<equiv> walk G u p v \\<and> distinct p\"\n\n(**)\nsubsection \\<open>\\<close>\n\nlemma (in finite_graph) path_length_le_card_vertices:\n  assumes \"path G u p v\"\n  shows \"length p \\<le> card (vertices G)\"\nproof -\n  have \"length p = card (set p)\"\n    using assms\n    by (intro distinct_card[symmetric]) (simp add: path_def)\n  also have \"... \\<le> card (vertices G)\"\n    using vertices_finite assms\n    by (auto simp add: path_def intro: walk_in_vertices card_mono)\n  finally show ?thesis\n    .\nqed\n\nlemma (in finite_graph) path_triples_finite:\n  shows \"finite {(u, p, v). path G u p v}\"\nproof (rule finite_subset)\n  have \"\\<And>u p v. walk G u p v \\<Longrightarrow> distinct p \\<Longrightarrow> length p \\<le> card (vertices G)\"\n    by (intro path_length_le_card_vertices) (simp add: path_def)\n  thus\n    \"{(u, p, v). path G u p v} \\<subseteq>\n      vertices G \\<times> {p. set p \\<subseteq> vertices G \\<and> length p \\<le> card (vertices G)} \\<times> vertices G\"\n    by (auto simp add: path_def intro: walk_hd_in_vertices walk_in_vertices walk_last_in_vertices)\n  show \"finite ...\"\n    using vertices_finite\n    by (intro finite_lists_length_le finite_cartesian_product)\nqed\n\nlemma (in finite_graph) paths_finite:\n  shows \"finite {p. path G u p v}\"\nproof -\n  have \"{p. path G u p v} \\<subseteq> (fst \\<circ> snd) ` {(u, p, v). path G u p v}\"\n    by (auto simp add: image_def)\n  with path_triples_finite\n  show ?thesis\n    by (rule finite_surj)\nqed\n\nsubsection \\<open>Transforming walks into paths\\<close>\n\nfunction (in graph) walk_to_path :: \"'a walk \\<Rightarrow> 'a walk\" where\n  \"walk_to_path p =\n    (if (\\<exists>u v. walk G u p v) \\<and> \\<not> distinct p\n     then let (q, r, s) = walk_closed_walk_decomp G p in walk_to_path (q @ tl s)\n     else p)\"\n  by auto\n\ntermination (in graph) walk_to_path\nproof (relation \"measure length\")\n  fix p qrs rs q r s\n  assume\n    p_not_path: \"(\\<exists>u v. walk G u p v) \\<and> \\<not> distinct p\" and\n    assms: \"qrs = walk_closed_walk_decomp G p\"\n    \"(q, rs) = qrs\"\n    \"(r, s) = rs\"\n  then obtain u v where\n    p_walk: \"walk G u p v\"\n    by blast\n  hence \"(q, r, s) = walk_closed_walk_decomp G p\"\n    using assms\n    by simp\n  then obtain\n    \"p = q @ tl r @ tl s\"\n    \"Suc 0 < length r\"\n    using p_walk p_not_path\n    by (elim walk_closed_walk_decompE_2) auto\n  thus \"(q @ tl s, p) \\<in> measure length\"\n    by auto\nqed simp\n\nlemma (in graph) walk_to_path_induct [consumes 1, case_names path decomp]:\n  assumes \"walk G u p v\"\n  assumes distinct: \"\\<And>p. \\<lbrakk> walk G u p v; distinct p \\<rbrakk> \\<Longrightarrow> P p\"\n  assumes\n    decomp: \"\\<And>p q r s. \\<lbrakk> walk G u p v; \\<not> distinct p;\n      walk_closed_walk_decomp G p = (q, r, s); P (q @ tl s) \\<rbrakk> \\<Longrightarrow> P p\"\n  shows \"P p\"\n  using assms(1)\nproof (induct \"length p\" arbitrary: p rule: less_induct)\n  case less\n  show ?case\n  proof (cases \"distinct p\")\n    case True\n    with less.prems\n    show ?thesis\n      by (rule distinct)\n  next\n    case False\n    obtain q r s where\n      qrs_def: \"walk_closed_walk_decomp G p = (q, r, s)\"\n      by (cases \"walk_closed_walk_decomp G p\")\n    with less.prems False\n    obtain\n      \"p = q @ tl r @ tl s\"\n      \"\\<exists>w. walk G u q w \\<and> closed_walk G w r \\<and> walk G w s v\"\n      by (elim walk_closed_walk_decompE_2)\n    hence\n      \"length (q @ tl s) < length p\"\n      \"walk G u (q @ tl s) v\"\n      by (auto simp add: tl_non_empty_conv intro: walk_append_is_walk)\n    hence \"P (q @ tl s)\"\n      by (rule less.hyps)\n    with less.prems False qrs_def\n    show ?thesis\n      by (rule decomp)\n  qed\nqed\n\nlemma (in graph) walk_to_path_is_path:\n  assumes \"walk G u p v\"\n  shows \"path G u (walk_to_path p) v\"\n  using assms\n  by (induction rule: walk_to_path_induct) (auto simp add: path_def)\n\nsection \\<open>Reachability\\<close>\n\ndefinition reachable :: \"'a graph \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"reachable G u v \\<equiv> \\<exists>p. walk G u p v\"\n\ndefinition connected :: \"'a graph \\<Rightarrow> bool\" where\n  \"connected G \\<equiv> \\<forall>u\\<in>vertices G. \\<forall>v\\<in>vertices G. reachable G u v\"\n\nlemma reachable_trans:\n  assumes \"reachable G u v\"\n  assumes \"reachable G v w\"\n  shows \"reachable G u w\"\nproof -\n  obtain p q where\n    \"walk G u p v\"\n    \"walk G v q w\"\n    using assms\n    by (auto simp add: reachable_def)\n  hence \"walk G u (p @ (tl q)) w\"\n    by (rule walk_append_is_walk)\n  thus ?thesis\n    by (auto simp add: reachable_def)\nqed\n\nlemma (in graph) reachable_symmetric:\n  assumes \"reachable G u v\"\n  shows \"reachable G v u\"\nproof -\n  obtain p where\n    \"walk G u p v\"\n    using assms\n    by (auto simp add: reachable_def)\n  hence \"walk G v (rev p) u\"\n    by (rule walk_rev_is_walk)\n  thus ?thesis\n    by (auto simp add: reachable_def)\nqed\n\nlemma (in graph) not_reachable_if_not_in_vertices:\n  assumes \"u \\<notin> vertices G \\<or> v \\<notin> vertices G\"\n  shows \"\\<not> reachable G u v\"\nproof (rule ccontr)\n  assume \"\\<not> \\<not> reachable G u v\"\n  then obtain p where\n    \"walk G u p v\"\n    by (auto simp add: reachable_def)\n  hence\n    \"u \\<in> vertices G\"\n    \"v \\<in> vertices G\"\n    by (auto intro: walk_hd_in_vertices walk_last_in_vertices)\n  thus \"False\"\n    using assms\n    by simp\nqed\n\nlemma (in subgraph) not_reachable_in_subgraph_if_not_reachable_in_supergraph:\n  assumes \"\\<not> reachable G u v\"\n  shows \"\\<not> reachable H u v\"\n  using assms\n  by (auto simp add: reachable_def intro: walk_subgraph_is_walk_supergraph)\n\nlemmas (in induced_subgraph) not_reachable_in_subgraph_if_not_reachable_in_supergraph =\n  not_reachable_in_subgraph_if_not_reachable_in_supergraph\n\nend", "meta": {"author": "wimmers", "repo": "archive-of-graph-formalizations", "sha": "cf49dd3379174cca7f3f1de16214e1c66238841e", "save_path": "github-repos/isabelle/wimmers-archive-of-graph-formalizations", "path": "github-repos/isabelle/wimmers-archive-of-graph-formalizations/archive-of-graph-formalizations-cf49dd3379174cca7f3f1de16214e1c66238841e/Undirected_Graphs/Mitja/Walk.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.7779690265791794}}
{"text": "(*\nTitle:  Allen's qualitative temporal calculus\nAuthor:  Fadoua Ghourabi (fadouaghourabi@gmail.com)\nAffiliation: Ochanomizu University, Japan\n*)\n\ntheory xor_cal\n\nimports\n\n  Main\n\nbegin\ndefinition xor::\"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixl \"\\<oplus>\" 60)\nwhere \"xor A B \\<equiv> (A \\<and> \\<not>B) \\<or> (\\<not>A \\<and> B)\"\n\ndeclare xor_def [simp]\n\ninterpretation bool:semigroup \"(\\<oplus>) \"\nproof\n{ fix a b c show \"a \\<oplus> b \\<oplus> c = a \\<oplus> (b \\<oplus> c)\" by auto}\nqed\n\nlemma xor_distr_L [simp]:\"A \\<oplus> (B \\<oplus> C) = (A\\<and>\\<not>B\\<and>\\<not>C)\\<or>(A\\<and>B\\<and>C)\\<or>(\\<not>A\\<and>B\\<and>\\<not>C)\\<or>(\\<not>A\\<and>\\<not>B\\<and>C)\"\nby auto\n\nlemma xor_distr_R [simp]:\"(A \\<oplus> B) \\<oplus> C = A \\<oplus> (B \\<oplus> C)\"\nby auto\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Allen_Calculus/xor_cal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7779662946995247}}
{"text": "theory Chapter7\nimports \"~~/src/HOL/IMP/Small_Step\"\nbegin\n\ntext{*\n\\section*{Chapter 7}\n\n\\exercise\nDefine a function that computes the set of variables that are assigned to\nin a command:\n*}\n\nfun assigned :: \"com \\<Rightarrow> vname set\" where\n\"assigned SKIP = {}\" |\n\"assigned (a ::= e) = {a}\" |\n\"assigned (a;; b) = assigned a \\<union> assigned b\" |\n\"assigned (IF a THEN b ELSE c) = assigned b \\<union> assigned c\" |\n\"assigned (WHILE a DO b) = assigned b\"\n\ntext{*\nProve that if some variable is not assigned to in a command,\nthen that variable is never modified by the command:\n*}\n\nlemma \"\\<lbrakk> (c, s) \\<Rightarrow> t; x \\<notin> assigned c \\<rbrakk> \\<Longrightarrow> s x = t x\"\nby (induction rule: big_step_induct) auto\n\ntext {*\n\\endexercise\n\n\\exercise\nDefine a recursive function that determines if a command behaves like @{const SKIP}\nand prove its correctness:\n*}\n\nfun skip :: \"com \\<Rightarrow> bool\" where\n\"skip SKIP = True\" |\n\"skip (a ::= e) = False\" |\n\"skip (a;; b) = (skip a \\<and> skip b)\" |\n\"skip (IF a THEN b ELSE c) = (skip b \\<and> skip c)\" |\n(* I initially had skip (WHILE a DO b) = skip b, however consider the case where b = SKIP and\n   a = Bc True. We would need to show that, \\<forall>s t. (SKIP, s) \\<Rightarrow> t \\<longrightarrow> (WHILE a DO b, s) \\<Rightarrow> t,\n   however this is not the case since there exists no t that that command reduces to (as it doesn't\n   terminate. Since the exercise wants the type signature to be com \\<Rightarrow> bool, and I don't feel like\n   handling only statically-false cases, I just define it to be false. *)\n\"skip (WHILE a DO b) = False\"\n\nlemma \"skip c \\<Longrightarrow> c \\<sim> SKIP\"\nproof (induction c)\n  case SKIP thus ?case by simp (* trivial *)\nnext \n  case Assign thus ?case by simp (* contradiction *)\nnext \n  case (Seq a b)\n  hence \"a \\<sim> SKIP\" and \"b \\<sim> SKIP\" by auto\n  moreover hence \"(a;; b) \\<sim> (SKIP;; SKIP)\" by blast\n  moreover hence \"(SKIP;; SKIP) \\<sim> SKIP\" by auto\n  ultimately show ?case by auto\nnext \n  case (If a b c)\n  hence \"b \\<sim> SKIP \\<and> c \\<sim> SKIP\" by auto\n  thus ?case by blast\nnext\n  case While thus ?case by auto (* contradiction *)\nqed\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a recursive function\n*}\n\nfun deskip :: \"com \\<Rightarrow> com\" where\n\"deskip SKIP = SKIP\" |\n\"deskip (a ::= b) = a ::= b\" |\n\"deskip (a;; b) = (if deskip a = SKIP then deskip b else (if deskip b = SKIP then deskip a else deskip a;; deskip b))\" |\n\"deskip (IF a THEN b ELSE c) = IF a THEN deskip b ELSE deskip c\" |\n\"deskip (WHILE a DO b) = WHILE a DO deskip b\"\n\ntext{*\nthat eliminates as many @{const SKIP}s as possible from a command. For example:\n@{prop[display]\"deskip (SKIP;; WHILE b DO (x::=a;; SKIP)) = WHILE b DO x::=a\"}\nProve its correctness by induction on @{text c}: *}\n\nlemma \"deskip c \\<sim> c\"\nproof (induction c)\n  case SKIP show ?case by simp\nnext\n  case Assign show ?case by simp\nnext\n  case (Seq a b)\n  hence \"a;; b \\<sim> deskip a;; deskip b\" by auto\n  moreover have \"deskip (a;; b) \\<sim> deskip a;; deskip b\" by auto\n  ultimately show ?case by auto\nnext\n  case If thus ?case by auto\nnext\n  case While\n  thus ?case by (simp add: sim_while_cong)\nqed\n\ntext{*\nRemember lemma @{thm[source]sim_while_cong} for the @{text WHILE} case.\n\\endexercise\n\n\\exercise\nA small-step semantics for the evaluation of arithmetic expressions\ncan be defined like this:\n*}\n\ninductive astep :: \"aexp \\<times> state \\<Rightarrow> aexp \\<Rightarrow> bool\" (infix \"\\<leadsto>\" 50) where\n\"(V x, s) \\<leadsto> N (s x)\" |\n\"(Plus (N i) (N j), s) \\<leadsto> N (i + j)\" |\n\"(a, s) \\<leadsto> a' \\<Longrightarrow> (Plus a b, s) \\<leadsto> Plus a' b\" |\n\"(b, s) \\<leadsto> b' \\<Longrightarrow> (Plus (N i) b, s) \\<leadsto> Plus (N i) b'\"\n\n(* your definition/proof here *)\n\ntext{*\nComplete the definition with two rules for @{const Plus}\nthat model a left-to-right evaluation strategy:\nreduce the first argument with @{text\"\\<leadsto>\"} if possible,\nreduce the second argument with @{text\"\\<leadsto>\"} if the first argument is a number.\nProve that each @{text\"\\<leadsto>\"} step preserves the value of the expression:\n*}\n\nlemma \"(a, s) \\<leadsto> a' \\<Longrightarrow> aval a s = aval a' s\"\nproof (induction rule: astep.induct [split_format (complete)])\n\nfix x s\nshow \"aval (V x) s = aval (N (s x)) s\" by auto\n\nfix i j s\nshow \"aval (Plus (N i) (N j)) s = aval (N (i + j)) s\" by auto\n\nfix a s a' b\nassume 0: \"aval a s = aval a' s\"\nfrom 0 show \"aval (Plus a b) s = aval (Plus a' b) s\" by auto\n\nfix b s b' i\nassume 0: \"aval b s = aval b' s\"\nfrom 0 show \"aval (Plus (N i) b) s = aval (Plus (N i) b') s\" by auto\n\nqed\n\n(* ok, I lied, I love case. some of those hairier proofs would have been pretty impossible to\n   read without it. writing out certain steps explicitly can make the structure of the proof\n   clear while still leaving the meat to the automation. *)\n\ntext{*\nDo not use the \\isacom{case} idiom but write down explicitly what you assume\nand show in each case: \\isacom{fix} \\dots \\isacom{assume} \\dots \\isacom{show} \\dots.\n\\endexercise\n\n\\exercise\nProve or disprove (by giving a counterexample):\n*}\n\nlemma \"IF And b\\<^sub>1 b\\<^sub>2 THEN c\\<^sub>1 ELSE c\\<^sub>2 \\<sim>\n          IF b\\<^sub>1 THEN IF b\\<^sub>2 THEN c\\<^sub>1 ELSE c\\<^sub>2 ELSE c\\<^sub>2\" (is \"?Small \\<sim> ?Big\")\nproof -\n  \n  {fix s t\n  have lower: \"bval (And b\\<^sub>1 b\\<^sub>2) s = (if bval b\\<^sub>1 s then bval b\\<^sub>2 s else False)\" by auto\n  {\n    assume ltr: \"(?Small, s) \\<Rightarrow> t\" (is \"?P\")\n    {\n      assume b1: \"bval b\\<^sub>1 s\"\n      assume b2: \"bval b\\<^sub>2 s\"\n      from b1 b2 ltr have fst: \"(c\\<^sub>1, s) \\<Rightarrow> t\" by auto\n    }\n    note fst = this\n\n    {\n      assume b1: \"bval b\\<^sub>1 s\"\n      assume b3: \"\\<not>bval b\\<^sub>2 s\"\n      from b1 b3 ltr have snd: \"(c\\<^sub>2, s) \\<Rightarrow> t\" by auto\n    }\n    note snd = this\n\n    {\n      assume b4: \"\\<not>bval b\\<^sub>1 s\"\n      from b4 ltr have thd: \"(c\\<^sub>2, s) \\<Rightarrow> t\" by auto\n    }\n    note thd = this\n    \n    from fst snd thd lower have \"(?Big, s) \\<Rightarrow> t\" by auto\n  }\n  note ltr = this\n  \n  {\n  assume rtl: \"(?Big, s) \\<Rightarrow> t\" (is \"?P\")\n    \n    {\n      assume b1: \"bval b\\<^sub>1 s\"\n      assume b2: \"bval b\\<^sub>2 s\"\n      from b1 b2 rtl have fst: \"(c\\<^sub>1, s) \\<Rightarrow> t\" by auto\n    }\n    note fst = this\n    \n    {\n      assume b1: \"bval b\\<^sub>1 s\"\n      assume b3: \"\\<not>bval b\\<^sub>2 s\"\n      from b1 b3 rtl have snd: \"(c\\<^sub>2, s) \\<Rightarrow> t\" by auto\n    }\n    note snd = this\n    \n    {\n      assume b4: \"\\<not>bval b\\<^sub>1 s\"\n      from b4 rtl have thd: \"(c\\<^sub>2, s) \\<Rightarrow> t\" by auto\n    }\n    note thd = this\n  \n    from fst snd thd lower have \"(?Big, s) \\<Rightarrow> t\" by auto\n  }\n  note rtl = this\n  \n  from ltr rtl have \"(?Small, s) \\<Rightarrow> t = (?Big, s) \\<Rightarrow> t\" by auto\n  }\n  from this show ?thesis by auto\nqed\n\n(* ... Wow that is ugly. I'm not sure how to improve it, though. I tried using \"moreover have\"\n  unsuccessfully. A next/case shorthand for this sort of thing would be nice. I think part of the\n  problem is that it's phrased in terms of = of booleans, which here I decompose into \n  P \\<longrightarrow> Q \\<and> Q \\<longrightarrow> P \\<Longrightarrow> P = Q (some of that reasoning is hidden behind auto). Alas,\n  sledgehammer finds a metis proof quite quickly. I was hoping writing out the structured proof\n  would provide some deeper insight into Isar, but I ended up using really low-level things. *)\n\n(* note: needed to explicitly add quantifiers, since the free variables didn't seem to want to\n   unify with the concrete counterexample *)\nlemma \"\\<not> (\\<forall>b\\<^sub>1 b\\<^sub>2 c. WHILE And b\\<^sub>1 b\\<^sub>2 DO c \\<sim> WHILE b\\<^sub>1 DO WHILE b\\<^sub>2 DO c)\" (is \"\\<not> ?P\")\nproof\n  assume are_sim: ?P\n  (* concrete counterexample: the first program terminates while the second does not. \n     if we assume the second *does* terminate because the first does, we can show by rule\n     induction that this is a contradiction (no rule can derive that (second, s) \\<Rightarrow> t) *)\n  have conc: \"WHILE And (Bc True) (Bc False) DO SKIP \\<sim> WHILE (Bc True) DO WHILE (Bc False) DO SKIP\"\n    using are_sim by simp\n  have is_skip: \"(WHILE And (Bc True) (Bc False) DO SKIP, s) \\<Rightarrow> s\" by auto\n  hence \"(WHILE (Bc True) DO WHILE (Bc False) DO SKIP, s) \\<Rightarrow> s\" using conc by simp\n  thus False \n  by (induction \"(WHILE (Bc True) DO WHILE (Bc False) DO SKIP)\" s s rule: big_step_induct, simp)\nqed\n\ndefinition Or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Or b\\<^sub>1 b\\<^sub>2 = Not (And (Not b\\<^sub>1) (Not b\\<^sub>2))\"\n\n\nlemma\nwhile_terminates_then_cond_false:\nassumes a: \"(WHILE b DO c, s) \\<Rightarrow> t\" (is \"(?C, s) \\<Rightarrow> t\")\nshows \"\\<not> bval b t\"\nproof -\n  (* it seems using \"assumes\" statements instead of explicit P \\<Longrightarrow> Q makes you need to\n     name it explicitly if you want to use it. It doesn't become a \"this\" at the start of the proof\n  *)\n  from a show ?thesis by (induction ?C s t rule: big_step_induct, auto)\nqed\n\nlemma \"WHILE Or b\\<^sub>1 b\\<^sub>2 DO c \\<sim>\n          WHILE Or b\\<^sub>1 b\\<^sub>2 DO c;; WHILE b\\<^sub>1 DO c\" (is \"?P \\<sim> ?P;; ?Q\")\nproof -\n  have ltr: \"\\<forall>s t. (?P, s) \\<Rightarrow> t \\<longrightarrow> (?P;; ?Q, s) \\<Rightarrow> t\"\n  proof -\n      {fix s t\n      assume terminates: \"(?P, s) \\<Rightarrow> t\"\n      hence \"\\<not> bval (Or b\\<^sub>1 b\\<^sub>2) t\" using while_terminates_then_cond_false by auto\n      hence \"(?Q, t) \\<Rightarrow> t\" by (auto simp add: Or_def)\n      from this have \"(?P;; ?Q, s) \\<Rightarrow> t\" using terminates by auto\n      } thus ?thesis by auto\n  qed\n\n  have rtl: \"\\<forall>s t. (?P;; ?Q, s) \\<Rightarrow> t \\<longrightarrow> (?P, s) \\<Rightarrow> t\"\n  proof -\n    {fix s t\n    assume terminates: \"(?P;; ?Q, s) \\<Rightarrow> t\"\n    then obtain t1 where seq1: \"(?P, s) \\<Rightarrow> t1\" and seq2: \"(?Q, t1) \\<Rightarrow> t\" by auto\n    hence \"\\<not> bval (Or b\\<^sub>1 b\\<^sub>2) t1\" using while_terminates_then_cond_false terminates by auto\n    hence nb1: \"\\<not> bval b\\<^sub>1 t1\" by (auto simp add: Or_def)\n    hence \"t1 = t\" using seq2 by auto\n    hence \"(?P, s) \\<Rightarrow> t\" using terminates seq1 seq2 nb1 by auto\n    } thus ?thesis by auto\n  qed\n\n  show ?thesis using ltr rtl by blast\nqed\n  \ntext{*\n\\endexercise\n\n\\exercise\nDefine a new loop construct @{text \"DO c WHILE b\"} (where @{text c} is\nexecuted once before @{text b} is tested) in terms of the\nexisting constructs in @{typ com}:\n*}\n\ndefinition Do :: \"com \\<Rightarrow> bexp \\<Rightarrow> com\" (\"DO _ WHILE _\"  [0, 61] 61) where\n\"DO c WHILE b = c ;; WHILE b DO c\" \n\ntext{*\nDefine a translation on commands that replaces all @{term \"WHILE b DO c\"}\nby suitable commands that use @{term \"DO c WHILE b\"} instead:\n*}\n\nfun dewhile :: \"com \\<Rightarrow> com\" where\n\"dewhile SKIP = SKIP\" |\n\"dewhile (a ::= b) = a ::= b\" |\n\"dewhile (a;; b) = dewhile a;; dewhile b\" |\n\"dewhile (IF a THEN b ELSE c) = IF a THEN dewhile b ELSE dewhile c\" |\n\"dewhile (WHILE a DO b) = IF Not a THEN SKIP ELSE (DO dewhile b WHILE a)\"\n\ntext{* Prove that your translation preserves the semantics: *}\n\nlemma \"dewhile c \\<sim> c\"\nproof (induction c)\n  case SKIP thus ?case by simp\n  next case Assign thus ?case by simp\n  next case Seq thus ?case by auto\n  next case If thus ?case by auto\n  next\n    case (While b c)\n    hence \"WHILE b DO c \\<sim> WHILE b DO dewhile c\" using sim_while_cong by simp\n    thus ?case using Do_def while_unfold by auto\nqed\n\ntext{*\n\\endexercise\n\n\\exercise\nLet @{text \"C :: nat \\<Rightarrow> com\"} be an infinite sequence of commands and\n@{text \"S :: nat \\<Rightarrow> state\"} an infinite sequence of states such that\n@{prop\"C(0::nat) = c;;d\"} and \\mbox{@{prop\"\\<forall>n. (C n, S n) \\<rightarrow> (C(Suc n), S(Suc n))\"}}.\nThen either all @{text\"C n\"} are of the form \\mbox{@{term\"c\\<^sub>n;;d\"}}\nand it is always @{text c\\<^sub>n} that is reduced or @{text c\\<^sub>n} eventually becomes @{const SKIP}.\nProve\n*}\n\n\nlemma assumes \"C 0 = c;;d\" and \"\\<forall>n. (C n, S n) \\<rightarrow> (C(Suc n), S(Suc n))\"\nshows \"(\\<forall>n. \\<exists>c\\<^sub>1 c\\<^sub>2. C n = c\\<^sub>1;;d \\<and> C(Suc n) = c\\<^sub>2;;d \\<and> (c\\<^sub>1, S n) \\<rightarrow> (c\\<^sub>2, S(Suc n)))\n     \\<or> (\\<exists>k. C k = SKIP;;d)\" (is \"(\\<forall>i. ?P i) \\<or> ?Q\")\nproof cases\n  assume ?Q\n  thus ?thesis by simp\nnext\n  assume not: \"\\<not>?Q\"\n  {fix i\n  have \"\\<exists>c1 c2. C i = c1;; d \\<and> C (Suc i) = c2;; d \\<and> (c1, S i) \\<rightarrow> (c2, S (Suc i))\"\n  proof (induction i)\n    case 0\n    have \"C 1 \\<noteq> SKIP;; d\" using not by simp\n    thus ?case using assms by (metis Small_Step.SeqE not prod.sel(1) prod.sel(2))\n  next\n    case (Suc n)\n    (* Relatively straightforward - use the induction hypothesis to chain forward another step\n       from original c1 and c2, show that this c3 has the necessary properties. Since c2 \\<rightarrow> SKIP\n       is not possible, there will always be something in front of the ;; that prevents the ;; from\n       reducing away. *)\n    then obtain c1 c2 where \"C n = c1;; d \\<and> C (Suc n) = c2;; d \\<and> (c1, S n) \\<rightarrow> (c2, S (Suc n))\" by auto\n    moreover have \"C (Suc (Suc n)) \\<noteq> SKIP;; d\" using not by simp\n    moreover obtain c3 where \"C (Suc (Suc n)) = c3;; d\" using not calculation by (metis Pair_inject Small_Step.SeqE assms(2))\n    moreover have \"(C (Suc n), S (Suc n)) \\<rightarrow> (C (Suc (Suc n)), S (Suc (Suc n)))\" using assms by auto\n    moreover have \"C (Suc n) = c2;; d \\<and> C (Suc (Suc n)) = c3 ;; d \\<and> (c2, S (Suc n)) \\<rightarrow> (c3, S (Suc (Suc n)))\" using calculation not by auto\n    ultimately show ?case using not by auto\n  qed\n  }\n  thus ?thesis by auto\nqed\n    \n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\\bigskip\n\nFor the following exercises copy theories\n@{theory Com}, @{theory Big_Step} and @{theory Small_Step}\nand modify them as required. Those parts of the theories\nthat do not contribute to the results required in the exercise can be discarded.\nIf there are multiple proofs of the same result, you may update any one of them.\n\n\\begin{exercise}\\label{exe:IMP:REPEAT}\nExtend IMP with a @{text \"REPEAT c UNTIL b\"} command by adding the constructor\n\\begin{alltt}\n  Repeat com bexp   (\"(REPEAT _/ UNTIL _)\"  [0, 61] 61)\n\\end{alltt}\nto datatype @{typ com}.\nAdjust the definitions of big-step and small-step semantics,\nthe proof that the big-step semantics is deterministic and\nthe equivalence proof between the two semantics.\n\\end{exercise}\n\n\\begin{exercise}\\label{exe:IMP:OR}\nExtend IMP with a new command @{text \"c\\<^sub>1 OR c\\<^sub>2\"} that is a\nnondeterministic choice: it may execute either @{text\n\"c\\<^sub>1\"} or @{text \"c\\<^sub>2\"}. Add the constructor\n\\begin{alltt}\n  Or com com   (\"_ OR/ _\" [60, 61] 60)\n\\end{alltt}\nto datatype @{typ com}. Adjust the definitions of big-step\nand small-step semantics, prove @{text\"(c\\<^sub>1 OR c\\<^sub>2) \\<sim> (c\\<^sub>2 OR c\\<^sub>1)\"}\nand update the equivalence proof between the two semantics.\n\\end{exercise}\n\n\\begin{exercise}\nExtend IMP with exceptions. Add two constructors @{text THROW} and\n@{text \"TRY c\\<^sub>1 CATCH c\\<^sub>2\"} to datatype @{typ com}:\n\\begin{alltt}\n  THROW  |  Try com com   (\"(TRY _/ CATCH _)\"  [0, 61] 61)\n\\end{alltt}\nCommand @{text THROW} throws an exception. The only command that can\ncatch an execption is @{text \"TRY c\\<^sub>1 CATCH c\\<^sub>2\"}: if an execption\nis thrown by @{text c\\<^sub>1}, execution continues with @{text c\\<^sub>2},\notherwise @{text c\\<^sub>2} is ignored.\nAdjust the definitions of big-step and small-step semantics as follows.\n\nThe big-step semantics is now of type @{typ \"com \\<times> state \\<Rightarrow> com \\<times> state\"}.\nIn a big step @{text \"(c,s) \\<Rightarrow> (x,t)\"}, @{text x} can only be @{term SKIP}\n(signalling normal termination) or @{text THROW} (signalling that an exception\nwas thrown but not caught).\n\nThe small-step semantics is of the same type as before. There are two final\nconfigurations now, @{term \"(SKIP, t)\"} and @{term \"(THROW, t)\"}.\nExceptions propagate upwards until an enclosing handler is found.\nThat is, until a configuration @{text \"(TRY THROW CATCH c, s)\"}\nis reached and @{text THROW} can be caught.\n\nAdjust the equivalence proof between the two semantics such that you obtain\n@{text \"cs \\<Rightarrow> (SKIP,t)  \\<longleftrightarrow>  cs \\<rightarrow>* (SKIP,t)\"}\nand @{text \"cs \\<Rightarrow> (THROW,t)  \\<longleftrightarrow>  cs \\<rightarrow>* (THROW,t)\"}.\nAlso revise the proof of\n\\noquotes{@{prop [source] \"(\\<exists>cs'. cs \\<Rightarrow> cs')  \\<longleftrightarrow>  (\\<exists>cs'. cs \\<rightarrow>* cs' \\<and> final cs')\"}}.\n\\end{exercise}\n*}\n\nend\n\n", "meta": {"author": "emberian", "repo": "ConcreteSemantics", "sha": "99843c9250212f926829e70affde8f8cacaf57f9", "save_path": "github-repos/isabelle/emberian-ConcreteSemantics", "path": "github-repos/isabelle/emberian-ConcreteSemantics/ConcreteSemantics-99843c9250212f926829e70affde8f8cacaf57f9/Chapter7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8418256551882382, "lm_q2_score": 0.924141813188682, "lm_q1q2_score": 0.7779662873744086}}
{"text": "theory ConcreteSemantics11_Denotational\n  imports Main \"~~/src/HOL/IMP/Big_Step\"\nbegin \n\nsection \"Denotational Semantics of Commands\"\n\ntype_synonym com_den = \"(state \\<times> state) set\"\n\ndefinition W :: \"(state \\<Rightarrow> bool) \\<Rightarrow> com_den \\<Rightarrow> (com_den \\<Rightarrow> com_den)\" where\n\"W db dc = (\\<lambda>dw. {(s,t). if db s then (s, t) \\<in> dc O dw else s = t})\"\n\nfun D :: \"com \\<Rightarrow> com_den\" where\n\"D SKIP   = Id\" |\n\"D (x ::= a) = {(s,t). t = s(x := aval a s)}\" |\n\"D (c1;;c2)  = D(c1) O D(c2)\" |\n\"D (IF b THEN c1 ELSE c2)\n = {(s,t). if bval b s then (s,t) \\<in> D c1 else (s,t) \\<in> D c2}\" |\n\"D (WHILE b DO c) = lfp (W (bval b) (D c))\"\n\nlemma W_mono: \"mono (W b r)\"\n  apply(unfold mono_def W_def)\n  apply(auto)\n  done\n\nlemma D_While_If:\n  \"D(WHILE b DO c) = D(IF b THEN c;;WHILE b DO c ELSE SKIP)\"\nproof -\n  let ?w = \"WHILE b DO c\"\n  let ?f = \"W (bval b) (D c)\"\n  have \"D ?w = lfp ?f\" \n    by simp\n  also have \"... = ?f (lfp ?f)\" \n    by (simp add: W_mono def_lfp_unfold)\n(*  also have \"... = ?f (D ?w)\" \n    by simp*)\n  also have \"... = D(IF b THEN c;;WHILE b DO c ELSE SKIP)\" \n    using W_def by auto\n  then show ?thesis \n    using calculation by auto\n    (*using \\<open>lfp (W (bval b) (D c)) = W (bval b) (D c) (lfp (W (bval b) (D c)))\\<close> by auto*)\nqed\n\ntext\\<open>Equivalence of denotational and big-step semantics:\\<close>\n\n(*Lemma 11.4.*)\nlemma D_if_big_step:  \"(c,s) \\<Rightarrow> t \\<Longrightarrow> (s,t) \\<in> D(c)\"\nproof(induction rule: big_step_induct)\ncase (Skip s)\n  then show ?case \n    by simp\nnext\n  case (Assign x a s)\n  then show ?case \n    by auto\nnext\n  case (Seq c\\<^sub>1 s\\<^sub>1 s\\<^sub>2 c\\<^sub>2 s\\<^sub>3)\n  then show ?case \n    by auto\nnext\n  case (IfTrue b s c\\<^sub>1 t c\\<^sub>2)\n  then show ?case \n    by simp\nnext\n  case (IfFalse b s c\\<^sub>2 t c\\<^sub>1)\n  then show ?case \n    by simp\nnext\n  case (WhileFalse b s c)\n  then show ?case \n    using D_While_If by auto\nnext\n  case (WhileTrue b s\\<^sub>1 c s\\<^sub>2 s\\<^sub>3)\n  then show ?case \n  proof -\n    have \"(s\\<^sub>1, s\\<^sub>3) \\<in> D (c;; WHILE b DO c)\"\n      using D.simps(3) WhileTrue.IH(1) WhileTrue.IH(2) by blast\n    then show ?thesis\n      using D_While_If WhileTrue.hyps(1) by force\n  qed\nqed\n\nabbreviation Big_step :: \"com \\<Rightarrow> com_den\" where\n\"Big_step c \\<equiv> {(s,t). (c,s) \\<Rightarrow> t}\"\n\n(*Lemma 11.5.*)\nlemma Big_step_if_D:  \"(s,t) \\<in> D(c) \\<Longrightarrow> (s,t) \\<in> Big_step c\"\nproof(induction c arbitrary: s t)\ncase SKIP\n  then show ?case \n    by auto\nnext\n  case (Assign x1 x2)\n  then show ?case by fastforce\nnext\n  case (Seq c1 c2)\n  then show ?case by fastforce\nnext\n  case (If x1 c1 c2)\n  then show ?case by (auto split: if_splits)\nnext\n  case (While b c)\n  let ?B = \"Big_step (WHILE b DO c)\"\n  let ?f = \"W (bval b) (D c)\"\n  have \"?f ?B \\<subseteq> ?B\" using While.IH by (auto simp: W_def)\n  then show ?case \n    using D.simps(5) While.prems lfp_lowerbound by blast\nqed\n\n(*Theorem 11.6 (Equivalence of denotational and big-step semantics).*)\ntheorem denotational_is_big_step: \"(s, t) \\<in> D c = (c, s) \\<Rightarrow> t\"\n  using Big_step_if_D D_if_big_step by blast\n\n(*Corollary 11.7.*)\ncorollary equiv_c_iff_equal_D: \"(c1 \\<sim> c2) \\<longleftrightarrow> D c1 = D c2\"\n  apply(simp add: denotational_is_big_step[symmetric])\n  apply(simp add: set_eq_iff)\n  done\n\nsubsection \"Continuity\"\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\" where\n\"chain S = (\\<forall>i. S i \\<subseteq> S(Suc i))\"\n\n(*Lemma 11.10.*)\nlemma chain_total: \"chain S \\<Longrightarrow> S i \\<le> S j \\<or> S j \\<le> S i\"\n  by (meson ConcreteSemantics11_Denotational.chain_def le_cases lift_Suc_mono_le)\n\ndefinition cont:: \"('a set \\<Rightarrow> 'b set) \\<Rightarrow> bool\" where\n\"cont f = (\\<forall> S. chain S \\<longrightarrow> f (\\<Union> n. S n) = (\\<Union> n. f (S n)))\"\n\n(*Lemma 11.11.*)\nlemma mono_if_cont: fixes f :: \"'a set \\<Rightarrow> 'b set\"\n  assumes \"cont f\" shows \"mono f\"\nproof\n  fix a b :: \"'a set\" assume \"a \\<subseteq> b\"\n  let ?S = \"\\<lambda>i::nat. if i = 0 then a else b\"\n  have \"chain ?S\" using \\<open>a \\<subseteq> b\\<close> \n    by (simp add: ConcreteSemantics11_Denotational.chain_def)\n  then have \"f (\\<Union>n. ?S n) = (\\<Union>n. f(?S n))\" \n    by (metis assms cont_def)\n  moreover have \"(\\<Union>n. ?S n) = b\" using \\<open>a \\<subseteq> b\\<close> by auto\n  moreover have \"(\\<Union>n. f(?S n)) = f a \\<union> f b\" by (auto split: if_splits)\n  ultimately show \"f a \\<subseteq> f b\" \n    by (simp add: subset_Un_eq)\nqed\n\nlemma chain_iterates: fixes f :: \"'a set \\<Rightarrow> 'a set\"\n  assumes \"mono f\" shows \"chain(\\<lambda>n. (f^^n) {})\"\nproof-\n  have \"(f ^^ n ) {} \\<subseteq> (f ^^ (Suc n)) {} \" for n \n    using assms funpow_decreasing le_SucI by blast\n  thus ?thesis \n    by (simp add: ConcreteSemantics11_Denotational.chain_def)\nqed\n\n(*Theorem 11.12 (Kleene fixpoint theorem).*)\ntheorem lfp_if_cont:\n  assumes \"cont f\" shows \"lfp f = (UN n. (f^^n) {})\" (is \"_ = ?U\")\nproof\n(* \n 1. lfp f \\<subseteq> (\\<Union>n. (f ^^ n) {})\n 2. (\\<Union>n. (f ^^ n) {}) \\<subseteq> lfp f\n*)\n  have \"mono f\" \n    by (simp add: assms mono_if_cont)\n  then have mono: \"(f ^^ n) {} \\<subseteq> (f ^^ Suc n) {}\" for n \n    using funpow_decreasing order.strict_implies_order by blast\n  show \"lfp f \\<subseteq> ?U\" \n  proof (rule lfp_lowerbound)\n    have \"f ?U = (\\<Union>n. (f ^^ (Suc n)) {})\" \n      using chain_iterates[OF mono_if_cont[OF assms]] assms\n      by(simp add: cont_def)\n    also have \"\\<dots> = (f ^^ 0) {} \\<union> (\\<Union>n. (f ^^ (Suc n)) {})\" \n      by simp\n    also have \"\\<dots> = ?U\" using mono by auto (metis funpow_simps_right(2) funpow_swap1 o_apply)\n    finally show \"f ?U \\<subseteq> ?U\" \n      by simp\n  qed\nnext\n  have \"(f^^n){} \\<subseteq> p\" if \"f p \\<subseteq> p\" for n p\n(*  have \"(f ^^ n) {} \\<subseteq> lfp f\" for n *)\n(*    using Kleene_iter_lpfp assms lfp_unfold mono_if_cont by blast*)\n(*Q: is it good to use Kleene_iter_lpfp ? \\<rightarrow> Not good.*)\n  proof (induction n)\n    case 0\n    then show ?case \n      by simp\n  next\n    case (Suc n)\n    from monoD[OF mono_if_cont[OF assms] Suc] \\<open>f p \\<subseteq> p\\<close>\n    show ?case \n      by auto\n(*    using Kleene_iter_lpfp assms mono_if_cont that by blast*)\n(*    by (meson Kleene_iter_lpfp assms lfp_greatest mono_if_cont)*)\nqed\n  then show \"?U \\<subseteq> lfp f\"  by(auto simp: lfp_def)\n(*    by (simp add: UN_least \\<open>\\<And>n. (f ^^ n) {} \\<subseteq> lfp f\\<close>)*)\nqed\n\n(*Lemma 11.13.*)\nlemma cont_W: \"cont(W b r)\"\n  apply(simp add: cont_def)\n  apply(simp add: W_def)\n  apply(auto)\n  done\n\nsubsection\\<open>The denotational semantics is deterministic\\<close>\n\nlemma single_valued_UN_chain:\n  assumes \"chain S\" \"(\\<And>n. single_valued (S n))\"\n  shows \"single_valued(UN n. S n)\"\nproof(auto simp: single_valued_def)\n(*  \\<And>x y xa z xb. (x, y) \\<in> S xa \\<Longrightarrow> (x, z) \\<in> S xb \\<Longrightarrow> y = z *)\n  fix m n x y z  assume \"(x, y) \\<in> S m \" \"(x, z) \\<in> S n\"\n  show \"y = z\" \n    by (meson \\<open>(x, y) \\<in> S m\\<close> \\<open>(x, z) \\<in> S n\\<close> assms(1) assms(2) chain_total single_valuedD subsetD)\n(*    by (meson \\<open>(x, y) \\<in> S m\\<close> \\<open>(x, z) \\<in> S n\\<close> assms(1) assms(2) chain_total single_valued_def subset_iff)*)\n(* There also exists an proof using `chain_total`*)\nqed\n\n(*Lemma 11.15.*)\nlemma single_valued_lfp: fixes f :: \"com_den \\<Rightarrow> com_den\"\nassumes \"cont f\" \"\\<And>r. single_valued r \\<Longrightarrow> single_valued (f r)\"\nshows \"single_valued(lfp f)\"\n  unfolding lfp_if_cont[OF assms(1)]\nproof(rule single_valued_UN_chain)\n  from chain_iterates[OF mono_if_cont]\n  show \"chain (\\<lambda>n. (f ^^ n) {})\" \n    by (simp add: \\<open>\\<And>f. cont f \\<Longrightarrow> chain (\\<lambda>n. (f ^^ n) {})\\<close> assms(1))\nnext\n  fix n show \" single_valued ((f ^^ n) {})\" \n  proof(induction n)\n    case 0\n    then show ?case \n      by simp\n  next\n    case (Suc n)\n    then show ?case by (auto simp: assms(2) )\n  qed\nqed\n(*\n 1. \\<forall>x y. (\\<exists>xa. (x, y) \\<in> (f ^^ xa) {}) \\<longrightarrow> (\\<forall>z. (\\<exists>xa. (x, z) \\<in> (f ^^ xa) {}) \\<longrightarrow> y = z)\n*)\n  (*\napply(simp add: single_valued_def)\napply(simp add: lfp_def)\n  sledgehammer*)\n\n(*Lemma 11.16.*)\nlemma single_valued_D: \"single_valued (D c)\"\nproof(induction c)\n  case SKIP\n  then show ?case \n    by simp\nnext\n  case (Assign x1 x2)\n  then show ?case by (auto simp: single_valued_def)\nnext\n  case (Seq c1 c2)\n  then show ?case \n    by (simp add: single_valued_relcomp)\nnext\n  case (If x1 c1 c2)\n  then show ?case by (auto simp: single_valued_def)\nnext\n  case (While x1 c)\n(*\\<And>x1 c. single_valued (D c) \\<Longrightarrow> single_valued (D (WHILE x1 DO c))*)\n  let ?f = \"W (bval x1) (D c)\"\n  have \"single_valued (lfp ?f)\"\n  proof (rule single_valued_lfp[OF cont_W])\n(*\n 1. cont (W (bval x1) (D c))\n 2. \\<And>r. single_valued r \\<Longrightarrow> single_valued (W (bval x1) (D c) r)\n*)\n    fix r show \"single_valued r \\<Longrightarrow> single_valued (W (bval x1) (D c) r)\" using While.IH \n       by(force simp: single_valued_def W_def)\n  qed\n  then show ?case \n    by simp\n(*    by (meson big_step_determ denotational_is_big_step single_valuedI)*)\nqed\n\n\nend", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/ConcreteSemanticsChapter11/ConcreteSemantics11_Denotational.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8652240704135291, "lm_q1q2_score": 0.7779414578373188}}
{"text": "(* Title:      (More) Relation Algebra\n   Author:     Walter Guttmann, Peter Hoefner\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n               Peter Hoefner <peter at hoefner-online.de>\n*)\n\nsection \\<open>(More) Relation Algebra\\<close>\n\ntext \\<open>\nThis theory presents fundamental properties of relation algebras, which are not present in the AFP entry on relation algebras but could be integrated there \\cite{ArmstrongFosterStruthWeber2014}.\nMany theorems concern vectors and points.\n\\<close>\n\ntheory More_Relation_Algebra\n\nimports Relation_Algebra.Relation_Algebra_RTC Relation_Algebra.Relation_Algebra_Functions\n\nbegin\n\nno_notation\n  trancl (\"(_\\<^sup>+)\" [1000] 999)\n\ncontext relation_algebra\nbegin\n\nnotation\n  converse (\"(_\\<^sup>T)\" [102] 101)\n\nabbreviation bijective\n  where \"bijective x \\<equiv> is_inj x \\<and> is_sur x\"\n\nabbreviation reflexive\n  where \"reflexive R \\<equiv> 1' \\<le> R\"\n\nabbreviation symmetric\n  where \"symmetric R \\<equiv> R = R\\<^sup>T\"\n\nabbreviation transitive\n  where \"transitive R \\<equiv> R;R \\<le> R\"\n\ntext \\<open>General theorems\\<close>\n\nlemma x_leq_triple_x:\n  \"x \\<le> x;x\\<^sup>T;x\"\nproof -\n  have \"x = x;1' \\<cdot> 1\"\n    by simp\n  also have \"... \\<le> (x \\<cdot> 1;1'\\<^sup>T);(1' \\<cdot> x\\<^sup>T;1)\"\n    by (rule dedekind)\n  also have \"... = x;(x\\<^sup>T;1 \\<cdot> 1')\"\n    by (simp add: inf.commute)\n  also have \"... \\<le> x;(x\\<^sup>T \\<cdot> 1';1\\<^sup>T);(1 \\<cdot> (x\\<^sup>T)\\<^sup>T;1')\"\n    by (metis comp_assoc dedekind mult_isol)\n  also have \"... \\<le> x;x\\<^sup>T;x\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma inj_triple:\n  assumes \"is_inj x\"\n    shows \"x = x;x\\<^sup>T;x\"\nby (metis assms order.eq_iff inf_absorb2 is_inj_def mult_1_left mult_subdistr x_leq_triple_x)\n\nlemma p_fun_triple:\n  assumes \"is_p_fun x\"\n    shows \"x = x;x\\<^sup>T;x\"\nby (metis assms comp_assoc order.eq_iff is_p_fun_def mult_isol mult_oner x_leq_triple_x)\n\nlemma loop_backward_forward:\n  \"x\\<^sup>T \\<le> -(1') + x\"\nby (metis conv_e conv_times inf.cobounded2 test_dom test_domain test_eq_conv galois_2 inf.commute\n           sup.commute)\n\nlemma inj_sur_semi_swap:\n  assumes \"is_sur z\"\n      and \"is_inj x\"\n    shows \"z \\<le> y;x \\<Longrightarrow> x \\<le> y\\<^sup>T;z\"\nproof -\n  assume \"z \\<le> y;x\"\n  hence \"z;x\\<^sup>T \\<le> y;(x;x\\<^sup>T)\"\n    by (metis mult_isor mult_assoc)\n  hence \"z;x\\<^sup>T \\<le> y\"\n    using \\<open>is_inj x\\<close> unfolding is_inj_def\n    by (metis mult_isol order.trans mult_1_right)\n  hence \"(z\\<^sup>T;z);x\\<^sup>T \\<le> z\\<^sup>T;y\"\n    by (metis mult_isol mult_assoc)\n  hence \"x\\<^sup>T \\<le> z\\<^sup>T;y\"\n    using \\<open>is_sur z\\<close> unfolding is_sur_def\n    by (metis mult_isor order.trans mult_1_left)\n  thus ?thesis\n    using conv_iso by fastforce\nqed\n\nlemma inj_sur_semi_swap_short:\n  assumes \"is_sur z\"\n      and \"is_inj x\"\n    shows \"z \\<le> y\\<^sup>T;x \\<Longrightarrow> x \\<le> y;z\"\nproof -\n  assume as: \"z \\<le> y\\<^sup>T;x\"\n  hence \"z;x\\<^sup>T \\<le> y\\<^sup>T\"\n    using \\<open>z \\<le> y\\<^sup>T;x\\<close> \\<open>is_inj x\\<close> unfolding is_inj_def\n    by (metis assms(2) conv_invol inf.orderI inf_absorb1 inj_p_fun ss_422iii)\n  hence \"x\\<^sup>T \\<le> z\\<^sup>T;y\\<^sup>T\"\n    using \\<open>is_sur z\\<close> unfolding is_sur_def\n    by (metis as assms inj_sur_semi_swap conv_contrav conv_invol conv_iso)\n  thus \"x \\<le> y;z\"\n    using conv_iso by fastforce\nqed\n\nlemma bij_swap:\n  assumes \"bijective z\"\n      and \"bijective x\"\n    shows \"z \\<le> y\\<^sup>T;x \\<longleftrightarrow> x \\<le> y;z\"\nby (metis assms inj_sur_semi_swap conv_invol)\n\ntext \\<open>The following result is \\cite[Proposition 4.2.2(iv)]{SchmidtStroehlein1993}.\\<close>\n\n\n\ntext \\<open>The following results are variants of \\cite[Proposition 4.2.3]{SchmidtStroehlein1993}.\\<close>\n\nlemma ss423conv:\n  assumes \"bijective x\"\n    shows \"x ; y \\<le> z \\<longleftrightarrow> y \\<le> x\\<^sup>T ; z\"\nby (metis assms conv_contrav conv_iso inj_p_fun is_map_def ss423 sur_total)\n\nlemma ss423bij:\n  assumes \"bijective x\"\n    shows \"y ; x\\<^sup>T \\<le> z \\<longleftrightarrow> y \\<le> z ; x\"\nby (simp add: assms is_map_def p_fun_inj ss423 total_sur)\n\nlemma inj_distr:\n  assumes \"is_inj z\"\n    shows \"(x\\<cdot>y);z = (x;z)\\<cdot>(y;z)\"\napply (rule order.antisym)\n using mult_subdistr_var apply blast\nusing assms conv_iso inj_p_fun p_fun_distl by fastforce\n\nlemma test_converse:\n  \"x \\<cdot> 1' = x\\<^sup>T \\<cdot> 1'\"\nby (metis conv_e conv_times inf_le2 is_test_def test_eq_conv)\n\nlemma injective_down_closed:\n  assumes \"is_inj x\"\n      and \"y \\<le> x\"\n    shows \"is_inj y\"\nby (meson assms conv_iso dual_order.trans is_inj_def mult_isol_var)\n\nlemma injective_sup:\n  assumes \"is_inj t\"\n      and \"e;t\\<^sup>T \\<le> 1'\"\n      and \"is_inj e\"\n    shows \"is_inj (t + e)\"\nproof -\n  have 1: \"t;e\\<^sup>T \\<le> 1'\"\n    using assms(2) conv_contrav conv_e conv_invol conv_iso by fastforce\n  have \"(t + e);(t + e)\\<^sup>T = t;t\\<^sup>T + t;e\\<^sup>T + e;t\\<^sup>T + e;e\\<^sup>T\"\n    by (metis conv_add distrib_left distrib_right' sup_assoc)\n  also have \"... \\<le> 1'\"\n    using 1 assms by (simp add: is_inj_def le_supI)\n  finally show ?thesis\n    unfolding is_inj_def .\nqed\n\ntext \\<open>Some (more) results about vectors\\<close>\n\nlemma vector_meet_comp:\n  assumes \"is_vector v\"\n      and \"is_vector w\"\n    shows \"v;w\\<^sup>T = v\\<cdot>w\\<^sup>T\"\nby (metis assms conv_contrav conv_one inf_top_right is_vector_def vector_1)\n\nlemma vector_meet_comp':\n  assumes \"is_vector v\"\n    shows \"v;v\\<^sup>T = v\\<cdot>v\\<^sup>T\"\nusing assms vector_meet_comp by blast\n\nlemma vector_meet_comp_x:\n  \"x;1;x\\<^sup>T = x;1\\<cdot>1;x\\<^sup>T\"\nby (metis comp_assoc inf_top.right_neutral is_vector_def one_idem_mult vector_1)\n\nlemma vector_meet_comp_x':\n  \"x;1;x = x;1\\<cdot>1;x\"\nby (metis inf_commute inf_top.right_neutral ra_1)\n\nlemma vector_prop1:\n  assumes \"is_vector v\"\n    shows \"-v\\<^sup>T;v = 0\"\nby (metis assms compl_inf_bot inf_top.right_neutral one_compl one_idem_mult vector_2)\n\ntext \\<open>The following results and a number of others in this theory are from \\cite{Guttmann2017a}.\\<close>\n\nlemma ee:\n  assumes \"is_vector v\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n    shows \"e;e = 0\"\nproof -\n  have \"e;v \\<le> 0\"\n    by (metis assms annir mult_isor vector_prop1 comp_assoc)\n  thus ?thesis\n    by (metis assms(2) annil order.antisym bot_least comp_assoc mult_isol)\nqed\n\nlemma et:\n  assumes \"is_vector v\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n      and \"t \\<le> v;v\\<^sup>T\"\n    shows \"e;t = 0\"\n      and \"e;t\\<^sup>T = 0\"\nproof -\n  have \"e;t \\<le> v;-v\\<^sup>T;v;v\\<^sup>T\"\n    by (metis assms(2-3) mult_isol_var comp_assoc)\n  thus \"e;t = 0\"\n    by (simp add: assms(1) comp_assoc le_bot vector_prop1)\nnext\n  have \"t\\<^sup>T \\<le> v;v\\<^sup>T\"\n    using assms(3) conv_iso by fastforce\n  hence \"e;t\\<^sup>T \\<le> v;-v\\<^sup>T;v;v\\<^sup>T\"\n    by (metis assms(2) mult_isol_var comp_assoc)\n  thus \"e;t\\<^sup>T = 0\"\n    by (simp add: assms(1) comp_assoc le_bot vector_prop1)\nqed\n\ntext \\<open>Some (more) results about points\\<close>\n\ndefinition point\n  where \"point x \\<equiv> is_vector x \\<and> bijective x\"\n\nlemma point_swap:\n  assumes \"point p\"\n      and \"point q\"\n    shows \"p \\<le> x;q \\<longleftrightarrow> q \\<le> x\\<^sup>T;p\"\nby (metis assms conv_invol inj_sur_semi_swap point_def)\n\ntext \\<open>Some (more) results about singletons\\<close>\n\nabbreviation singleton\n  where \"singleton x \\<equiv> bijective (x;1) \\<and> bijective (x\\<^sup>T;1)\"\n\nlemma singleton_injective:\n  assumes \"singleton x\"\n    shows \"is_inj x\"\nusing assms injective_down_closed maddux_20 by blast\n\nlemma injective_inv:\n  assumes \"is_vector v\"\n      and \"singleton e\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n      and \"t \\<le> v;v\\<^sup>T\"\n      and \"is_inj t\"\n    shows \"is_inj (t + e)\"\nby (metis assms singleton_injective injective_sup bot_least et(2))\n\nlemma singleton_is_point:\n  assumes \"singleton p\"\n    shows \"point (p;1)\"\nby (simp add: assms comp_assoc is_vector_def point_def)\n\nlemma singleton_transp:\n  assumes \"singleton p\"\n    shows \"singleton (p\\<^sup>T)\"\nby (simp add: assms)\n\nlemma point_to_singleton:\n  assumes \"singleton p\"\n    shows \"singleton (1'\\<cdot>p;p\\<^sup>T)\"\nusing assms dom_def_aux_var dom_one is_vector_def point_def by fastforce\n\nlemma singleton_singletonT:\n  assumes \"singleton p\"\n    shows \"p;p\\<^sup>T \\<le> 1'\"\nusing assms singleton_injective is_inj_def by blast\n\ntext \\<open>Minimality\\<close>\n\nabbreviation minimum\n  where \"minimum x v \\<equiv> v \\<cdot> -(x\\<^sup>T;v)\"\n\ntext \\<open>Regressively finite\\<close>\n\nabbreviation regressively_finite\n  where \"regressively_finite x \\<equiv> \\<forall>v . is_vector v \\<and> v \\<le> x\\<^sup>T;v \\<longrightarrow> v = 0\"\n\nlemma regressively_finite_minimum:\n  \"regressively_finite R \\<Longrightarrow> is_vector v \\<Longrightarrow> v \\<noteq> 0 \\<Longrightarrow> minimum R v \\<noteq> 0\"\nusing galois_aux2 by blast\n\nlemma regressively_finite_irreflexive:\n  assumes \"regressively_finite x\"\n    shows \"x \\<le> -1'\"\nproof -\n  have 1: \"is_vector ((x\\<^sup>T \\<cdot> 1');1)\"\n    by (simp add: is_vector_def mult_assoc)\n  have \"(x\\<^sup>T \\<cdot> 1');1 = (x\\<^sup>T \\<cdot> 1');(x\\<^sup>T \\<cdot> 1');1\"\n    by (simp add: is_test_def test_comp_eq_mult)\n  with 1 have \"(x\\<^sup>T \\<cdot> 1');1 = 0\"\n    by (metis assms comp_assoc mult_subdistr)\n  thus ?thesis\n    by (metis conv_e conv_invol conv_times conv_zero galois_aux ss_p18)\nqed\n\nend (* relation_algebra *)\n\nsubsection \\<open>Relation algebras satisfying the Tarski rule\\<close>\n\nclass relation_algebra_tarski = relation_algebra +\n  assumes tarski: \"x \\<noteq> 0 \\<longleftrightarrow> 1;x;1 = 1\"\nbegin\n\ntext \\<open>Some (more) results about points\\<close>\n\nlemma point_equations:\n  assumes \"is_point p\"\n  shows \"p;1=p\"\n    and \"1;p=1\"\n    and \"p\\<^sup>T;1=1\"\n    and \"1;p\\<^sup>T=p\\<^sup>T\"\n   apply (metis assms is_point_def is_vector_def)\n  using assms is_point_def is_vector_def tarski vector_comp apply fastforce\n apply (metis assms conv_contrav conv_one conv_zero is_point_def is_vector_def tarski)\nby (metis assms conv_contrav conv_one is_point_def is_vector_def)\n\ntext \\<open>The following result is \\cite[Proposition 2.4.5(i)]{SchmidtStroehlein1993}.\\<close>\n\nlemma point_singleton:\n  assumes \"is_point p\"\n      and \"is_vector v\"\n      and \"v \\<noteq> 0\"\n      and \"v \\<le> p\"\n    shows \"v = p\"\nproof -\n  have \"1;v = 1\"\n    using assms(2,3) comp_assoc is_vector_def tarski by fastforce\n  hence \"p = 1;v \\<cdot> p\"\n    by simp\n  also have \"... \\<le> (1 \\<cdot> p;v\\<^sup>T);(v \\<cdot> 1\\<^sup>T;p)\"\n    using dedekind by blast\n  also have \"... \\<le> p;v\\<^sup>T;v\"\n    by (simp add: mult_subdistl)\n  also have \"... \\<le> p;p\\<^sup>T;v\"\n    using assms(4) conv_iso mult_double_iso by blast\n  also have \"... \\<le> v\"\n    by (metis assms(1) is_inj_def is_point_def mult_isor mult_onel)\n  finally show ?thesis\n    using assms(4) by simp\nqed\n\nlemma point_not_equal_aux:\n  assumes \"is_point p\"\n      and \"is_point q\"\n    shows \"p\\<noteq>q \\<longleftrightarrow> p \\<cdot> -q \\<noteq> 0\"\nproof\n  show \"p \\<noteq> q \\<Longrightarrow> p \\<cdot> - q \\<noteq> 0\"\n  proof (rule contrapos_nn)\n    assume \"p \\<cdot> -q = 0\"\n    thus \"p = q\"\n     using assms galois_aux2 is_point_def point_singleton by fastforce\n  qed\nnext\n  show \"p \\<cdot> - q \\<noteq> 0 \\<Longrightarrow> p \\<noteq> q\"\n    using inf_compl_bot by blast\nqed\n\ntext \\<open>The following result is part of \\cite[Proposition 2.4.5(ii)]{SchmidtStroehlein1993}.\\<close>\n\nlemma point_not_equal:\n  assumes \"is_point p\"\n      and \"is_point q\"\n    shows \"p\\<noteq>q \\<longleftrightarrow> p\\<le>-q\"\n      and \"p\\<le>-q \\<longleftrightarrow> p;q\\<^sup>T \\<le> -1'\"\n      and \"p;q\\<^sup>T \\<le> -1' \\<longleftrightarrow> p\\<^sup>T;q \\<le> 0\"\nproof -\n  have \"p \\<noteq> q \\<Longrightarrow> p \\<le> - q\"\n    by (metis assms point_not_equal_aux is_point_def vector_compl vector_mult point_singleton\n              inf.orderI inf.cobounded1)\n  thus \"p\\<noteq>q \\<longleftrightarrow> p\\<le>-q\"\n    by (metis assms(1) galois_aux inf.orderE is_point_def order.refl)\nnext\n  show \"(p \\<le> - q) = (p ; q\\<^sup>T \\<le> - 1')\"\n    by (simp add: conv_galois_2)\nnext\n  show \"(p ; q\\<^sup>T \\<le> - 1') = (p\\<^sup>T ; q \\<le> 0)\"\n    by (metis assms(2) compl_bot_eq conv_galois_2 galois_aux maddux_141 mult_1_right\n              point_equations(4))\nqed\n\nlemma point_is_point:\n  \"point x \\<longleftrightarrow> is_point x\"\napply (rule iffI)\n apply (simp add: is_point_def point_def surj_one tarski)\nusing is_point_def is_vector_def mult_assoc point_def sur_def_var1 tarski by fastforce\n\nlemma point_in_vector_or_complement:\n  assumes \"point p\"\n      and \"is_vector v\"\n    shows \"p \\<le> v \\<or> p \\<le> -v\"\nproof (cases \"p \\<le> -v\")\n  assume \"p \\<le> -v\"\n  thus ?thesis\n    by simp\nnext\n  assume \"\\<not>(p \\<le> -v)\"\n  hence \"p\\<cdot>v \\<noteq> 0\"\n    by (simp add: galois_aux)\n  hence \"1;(p\\<cdot>v) = 1\"\n    using assms comp_assoc is_vector_def point_def tarski vector_mult by fastforce\n  hence \"p \\<le> p;(p\\<cdot>v)\\<^sup>T;(p\\<cdot>v)\"\n    by (metis inf_top.left_neutral modular_2_var)\n  also have \"... \\<le> p;p\\<^sup>T;v\"\n    by (simp add: mult_isol_var)\n  also have \"... \\<le> v\"\n    using assms(1) comp_assoc point_def ss423conv by fastforce\n  finally show ?thesis ..\nqed\n\nlemma point_in_vector_or_complement_iff:\n  assumes \"point p\"\n      and \"is_vector v\"\n    shows \"p \\<le> v \\<longleftrightarrow> \\<not>(p \\<le> -v)\"\nby (metis assms annir compl_top_eq galois_aux inf.orderE one_compl point_def ss423conv tarski\n          top_greatest point_in_vector_or_complement)\n\nlemma different_points_consequences:\n  assumes \"point p\"\n      and \"point q\"\n      and \"p\\<noteq>q\"\n    shows \"p\\<^sup>T;-q=1\"\n      and \"-q\\<^sup>T;p=1\"\n      and \"-(p\\<^sup>T;-q)=0\"\n      and \"-(-q\\<^sup>T;p)=0\"\nproof -\n  have \"p \\<le> -q\"\n    by (metis assms compl_le_swap1 inf.absorb1 inf.absorb2 point_def point_in_vector_or_complement)\n  thus 1: \"p\\<^sup>T;-q=1\"\n    using assms(1) by (metis is_vector_def point_def ss423conv top_le)\n  thus 2: \"-q\\<^sup>T;p=1\"\n    using conv_compl conv_one by force\n  from 1 show \"-(p\\<^sup>T;-q)=0\"\n    by simp\n  from 2 show \"-(-q\\<^sup>T;p)=0\"\n    by simp\nqed\n\ntext \\<open>Some (more) results about singletons\\<close>\n\nlemma singleton_pq:\n  assumes \"point p\"\n      and \"point q\"\n    shows \"singleton (p;q\\<^sup>T)\"\nusing assms comp_assoc point_def point_equations(1,3) point_is_point by fastforce\n\nlemma singleton_equal_aux:\n  assumes \"singleton p\"\n      and \"singleton q\"\n      and \"q\\<le>p\"\n    shows \"p \\<le> q;1\"\nproof -\n  have pLp: \"p;1;p\\<^sup>T \\<le>1'\"\n    by (simp add: assms(1) maddux_21 ss423conv)\n\n  have \"p = 1;(q\\<^sup>T;q;1) \\<cdot> p\"\n    using tarski\n    by (metis assms(2) annir singleton_injective inf.commute inf_top.right_neutral inj_triple\n              mult_assoc surj_one)\n  also have \"... \\<le> (1 \\<cdot> p;(q\\<^sup>T;q;1)\\<^sup>T);(q\\<^sup>T;q;1 \\<cdot> 1;p)\"\n    using dedekind by (metis conv_one)\n  also have \"... \\<le> p;1;q\\<^sup>T;q;q\\<^sup>T;q;1\"\n    by (simp add: comp_assoc mult_isol)\n  also have \"... \\<le> p;1;p\\<^sup>T;q;q\\<^sup>T;q;1\"\n    using assms(3) by (metis comp_assoc conv_iso mult_double_iso)\n  also have \"... \\<le> 1';q;q\\<^sup>T;q;1\"\n    using pLp using mult_isor by blast\n  also have \"... \\<le> q;1\"\n    using assms(2) singleton_singletonT by (simp add: comp_assoc mult_isol)\n  finally show ?thesis .\nqed\n\nlemma singleton_equal:\n assumes \"singleton p\"\n     and \"singleton q\"\n     and \"q\\<le>p\"\n   shows \"q=p\"\nproof -\n  have p1: \"p \\<le> q;1\"\n    using assms by (rule singleton_equal_aux)\n  have \"p\\<^sup>T \\<le> q\\<^sup>T;1\"\n    using assms singleton_equal_aux singleton_transp conv_iso by fastforce\n  hence p2: \"p \\<le> 1;q\"\n    using conv_iso by force\n\n  have \"p \\<le> q;1 \\<cdot> 1;q\"\n    using p1 p2 inf.boundedI by blast\n  also have \"... \\<le> (q \\<cdot> 1;q;1);(1 \\<cdot> q\\<^sup>T;1;q)\"\n    using dedekind by (metis comp_assoc conv_one)\n  also have \"... \\<le> q;q\\<^sup>T;1;q\"\n    by (simp add: mult_isor comp_assoc)\n  also have \"... \\<le> q;1'\"\n    by (metis assms(2) conv_contrav conv_invol conv_one is_inj_def mult_assoc mult_isol\n              one_idem_mult)\n  also have \"... \\<le> q\"\n    by simp\n  finally have \"p \\<le> q\" .\n  thus \"q=p\"\n  using assms(3) by simp\nqed\n\nlemma singleton_nonsplit:\n  assumes \"singleton p\"\n      and \"x\\<le>p\"\n    shows \"x=0 \\<or> x=p\"\nproof (cases \"x=0\")\n  assume \"x=0\"\n  thus ?thesis ..\nnext\n  assume 1: \"x\\<noteq>0\"\n  have \"singleton x\"\n  proof (safe)\n    show \"is_inj (x;1)\"\n      using assms injective_down_closed mult_isor by blast\n    show \"is_inj (x\\<^sup>T;1)\"\n      using assms conv_iso injective_down_closed mult_isol_var by blast\n    show \"is_sur (x;1)\"\n      using 1 comp_assoc sur_def_var1 tarski by fastforce\n    thus \"is_sur (x\\<^sup>T;1)\"\n      by (metis conv_contrav conv_one mult.semigroup_axioms sur_def_var1 semigroup.assoc)\n  qed\n  thus ?thesis\n    using assms singleton_equal by blast\nqed\n\nlemma singleton_nonzero:\n  assumes \"singleton p\"\n    shows \"p\\<noteq>0\"\nproof\n  assume \"p = 0\"\n  hence \"point 0\"\n    using assms singleton_is_point by fastforce\n  thus False\n    by (simp add: is_point_def point_is_point)\nqed\n\nlemma singleton_sum:\n  assumes \"singleton p\"\n    shows \"p \\<le> x+y \\<longleftrightarrow> (p\\<le>x \\<or> p\\<le>y)\"\nproof\n  show \"p \\<le> x + y \\<Longrightarrow> p \\<le> x \\<or> p \\<le> y\"\n  proof -\n    assume as: \"p \\<le> x + y\"\n    show \"p \\<le> x \\<or> p \\<le> y\"\n    proof (cases \"p\\<le>x\")\n      assume \"p\\<le>x\"\n      thus ?thesis ..\n    next\n      assume a:\"\\<not>(p\\<le>x)\"\n      hence \"p\\<cdot>x \\<noteq> p\"\n        using a inf.orderI by fastforce\n      hence \"p \\<le> -x\"\n        using assms singleton_nonsplit galois_aux inf_le1 by blast\n      hence \"p\\<le>y\"\n        using as by (metis galois_1 inf.orderE)\n      thus ?thesis\n        by simp\n    qed\n  qed\nnext\n  show \"p \\<le> x \\<or> p \\<le> y \\<Longrightarrow> p \\<le> x + y\"\n    using sup.coboundedI1 sup.coboundedI2 by blast\nqed\n\nlemma singleton_iff:\n \"singleton x \\<longleftrightarrow> x \\<noteq> 0 \\<and> x\\<^sup>T;1;x + x;1;x\\<^sup>T \\<le> 1'\"\nby (smt comp_assoc conv_contrav conv_invol conv_one is_inj_def le_sup_iff one_idem_mult\n        sur_def_var1 tarski)\n\nlemma singleton_not_atom_in_relation_algebra_tarski:\n assumes \"p\\<noteq>0\"\n     and \"\\<forall>x . x\\<le>p \\<longrightarrow> x=0 \\<or> x=p\"\n   shows \"singleton p\"\nnitpick [expect=genuine] oops\n\nend (* relation_algebra_tarski *)\n\nsubsection \\<open>Relation algebras satisfying the point axiom\\<close>\n\nclass relation_algebra_point = relation_algebra +\n  assumes point_axiom: \"x \\<noteq> 0 \\<longrightarrow> (\\<exists>y z . point y \\<and> point z \\<and> y;z\\<^sup>T \\<le> x)\"\nbegin\n\ntext \\<open>Some (more) results about points\\<close>\n\nlemma point_exists:\n  \"\\<exists>x . point x\"\nby (metis (full_types) order.eq_iff is_inj_def is_sur_def is_vector_def point_axiom point_def)\n\nlemma point_below_vector:\n  assumes \"is_vector v\"\n      and \"v \\<noteq> 0\"\n    shows \"\\<exists>x . point x \\<and> x \\<le> v\"\nproof -\n  from assms(2) obtain y and z where 1: \"point y \\<and> point z \\<and> y;z\\<^sup>T \\<le> v\"\n    using point_axiom by blast\n  have \"z\\<^sup>T;1 = (1;z)\\<^sup>T\"\n    using conv_contrav conv_one by simp\n  hence \"y;(1;z)\\<^sup>T \\<le> v\"\n    using 1 by (metis assms(1) comp_assoc is_vector_def mult_isor)\n  thus ?thesis\n    using 1 by (metis conv_one is_vector_def point_def sur_def_var1)\nqed\n\nend (* relation_algebra_point *)\n\nclass relation_algebra_tarski_point = relation_algebra_tarski + relation_algebra_point\nbegin\n\nlemma atom_is_singleton:\n  assumes \"p\\<noteq>0\"\n      and \"\\<forall>x . x\\<le>p \\<longrightarrow> x=0 \\<or> x=p\"\n    shows \"singleton p\"\nby (metis assms singleton_nonzero singleton_pq point_axiom)\n\nlemma singleton_iff_atom:\n  \"singleton p \\<longleftrightarrow> p\\<noteq>0 \\<and> (\\<forall>x . x\\<le>p \\<longrightarrow> x=0 \\<or> x=p)\"\nusing singleton_nonsplit singleton_nonzero atom_is_singleton by blast\n\nlemma maddux_tarski:\n  assumes \"x\\<noteq>0\"\n  shows \"\\<exists>y . y\\<noteq>0 \\<and> y\\<le>x \\<and> is_p_fun y\"\nproof -\n  obtain p q where 1: \"point p \\<and> point q \\<and> p;q\\<^sup>T \\<le> x\"\n    using assms point_axiom by blast\n  hence 2: \"p;q\\<^sup>T\\<noteq>0\"\n    by (simp add: singleton_nonzero singleton_pq)\n  have \"is_p_fun (p;q\\<^sup>T)\"\n    using 1 by (meson singleton_singletonT singleton_pq singleton_transp is_inj_def p_fun_inj)\n  thus ?thesis\n    using 1 2 by force\nqed\n\ntext \\<open>Intermediate Point Theorem \\cite[Proposition 2.4.8]{SchmidtStroehlein1993}\\<close>\n\nlemma intermediate_point_theorem:\n  assumes \"point p\"\n      and \"point r\"\n    shows \"p \\<le> x;y;r \\<longleftrightarrow> (\\<exists>q . point q \\<and> p \\<le> x;q \\<and> q \\<le> y;r)\"\nproof\n  assume 1: \"p \\<le> x;y;r\"\n  let ?v = \"x\\<^sup>T;p \\<cdot> y;r\"\n  have 2: \"is_vector ?v\"\n    using assms comp_assoc is_vector_def point_def vector_mult by fastforce\n  have \"?v \\<noteq> 0\"\n    using 1 by (metis assms(1) inf.absorb2 is_point_def maddux_141 point_is_point mult.assoc)\n  hence \"\\<exists>q . point q \\<and> q \\<le> ?v\"\n    using 2 point_below_vector by blast\n  thus \"\\<exists>q . point q \\<and> p \\<le> x;q \\<and> q \\<le> y;r\"\n    using assms(1) point_swap by auto\nnext\n  assume \"\\<exists>q . point q \\<and> p \\<le> x;q \\<and> q \\<le> y;r\"\n  thus \"p \\<le> x;y;r\"\n    using comp_assoc mult_isol order_trans by fastforce\nqed\n\nend (* relation_algebra_tarski_point *)\n\n(*\nThe following shows that rtc can be defined with only 2 axioms.\nThis should eventually go into AFP/Relation_Algebra_RTC.relation_algebra_rtc.\nThere the class definition should be replaced with:\n\nclass relation_algebra_rtc = relation_algebra + star_op +\n  assumes rtc_unfoldl: \"1' + x ; x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n      and rtc_inductl: \"z + x ; y \\<le> y \\<longrightarrow> x\\<^sup>\\<star> ; z \\<le> y\"\n\nand the following lemmas:\n*)\n\ncontext relation_algebra\nbegin\n\nlemma unfoldl_inductl_implies_unfoldr:\n  assumes \"\\<And>x. 1' + x;(rtc x) \\<le> rtc x\"\n      and \"\\<And>x y z. x+y;z \\<le> z \\<Longrightarrow> rtc(y);x \\<le> z\"\n    shows \"1' + rtc(x);x \\<le> rtc x\"\nby (metis assms le_sup_iff mult_oner order.trans subdistl_eq sup_absorb2 sup_ge1)\n\nlemma star_transpose_swap:\n  assumes \"\\<And>x. 1' + x;(rtc x) \\<le> rtc x\"\n      and \"\\<And>x y z. x+y;z \\<le> z \\<Longrightarrow> rtc(y);x \\<le> z\"\n    shows \"rtc(x\\<^sup>T) = (rtc x)\\<^sup>T\"\napply(simp only: order.eq_iff; rule conjI)\n  apply (metis assms conv_add conv_contrav conv_e conv_iso mult_1_right\n             unfoldl_inductl_implies_unfoldr )\nby (metis assms conv_add conv_contrav conv_e conv_invol conv_iso mult_1_right\n          unfoldl_inductl_implies_unfoldr)\n\nlemma unfoldl_inductl_implies_inductr:\n  assumes \"\\<And>x. 1' + x;(rtc x) \\<le> rtc x\"\n      and \"\\<And>x y z. x+y;z \\<le> z \\<Longrightarrow> rtc(y);x \\<le> z\"\n    shows \"x+z;y \\<le> z \\<Longrightarrow> x;rtc(y) \\<le> z\"\nby (metis assms conv_add conv_contrav conv_iso star_transpose_swap)\n\nend (* relation_algebra *)\n\ncontext relation_algebra_rtc\nbegin\n\nabbreviation tc (\"(_\\<^sup>+)\" [101] 100) where \"tc x \\<equiv> x;x\\<^sup>\\<star>\"\n\nabbreviation is_acyclic\n  where \"is_acyclic x \\<equiv> x\\<^sup>+ \\<le> -1'\"\n\ntext \\<open>General theorems\\<close>\n\nlemma star_denest_10:\n  assumes \"x;y=0\"\n    shows \"(x+y)\\<^sup>\\<star> = y;y\\<^sup>\\<star>;x\\<^sup>\\<star>+x\\<^sup>\\<star>\"\nusing assms bubble_sort sup.commute by auto\n\n\n\ntext \\<open>The following two lemmas are from \\cite{Guttmann2018b}.\\<close>\n\nlemma cancel_separate:\n  assumes \"x ; y \\<le> 1'\"\n  shows \"x\\<^sup>\\<star> ; y\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> + y\\<^sup>\\<star>\"\nproof -\n  have \"x ; y\\<^sup>\\<star> = x + x ; y ; y\\<^sup>\\<star>\"\n    by (metis comp_assoc conway.dagger_unfoldl_distr distrib_left mult_oner)\n  also have \"... \\<le> x + y\\<^sup>\\<star>\"\n    by (metis assms join_isol star_invol star_plus_one star_subdist_var_2 sup.absorb2 sup.assoc)\n  also have \"... \\<le> x\\<^sup>\\<star> + y\\<^sup>\\<star>\"\n    using join_iso by fastforce\n  finally have \"x ; (x\\<^sup>\\<star> + y\\<^sup>\\<star>) \\<le> x\\<^sup>\\<star> + y\\<^sup>\\<star>\"\n    by (simp add: distrib_left le_supI1)\n  thus ?thesis\n    by (simp add: rtc_inductl)\nqed\n\nlemma cancel_separate_inj_converse:\n  assumes \"is_inj x\"\n    shows \"x\\<^sup>\\<star> ; x\\<^sup>T\\<^sup>\\<star> = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\n apply (rule order.antisym)\n  using assms cancel_separate is_inj_def apply blast\nby (metis conway.dagger_unfoldl_distr le_supI mult_1_right mult_isol sup.cobounded1)\n\nlemma cancel_separate_p_fun_converse:\n  assumes \"is_p_fun x\"\n    shows \"x\\<^sup>T\\<^sup>\\<star> ; x\\<^sup>\\<star> = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nusing sup_commute assms cancel_separate_inj_converse p_fun_inj by fastforce\n\nlemma cancel_separate_converse_idempotent:\n  assumes \"is_inj x\"\n      and \"is_p_fun x\"\n    shows \"(x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>);(x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>) = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nby (metis assms cancel_separate cancel_separate_p_fun_converse church_rosser_equiv is_inj_def\n          star_denest_var_6)\n\nlemma triple_star:\n  assumes \"is_inj x\"\n      and \"is_p_fun x\"\n    shows \"x\\<^sup>\\<star>;x\\<^sup>T\\<^sup>\\<star>;x\\<^sup>\\<star> = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nby (simp add: assms cancel_separate_inj_converse cancel_separate_p_fun_converse)\n\nlemma inj_xxts:\n  assumes \"is_inj x\"\n    shows \"x;x\\<^sup>T\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nby (metis assms cancel_separate_inj_converse distrib_right less_eq_def star_ext)\n\nlemma plus_top:\n  \"x\\<^sup>+;1 = x;1\"\nby (metis comp_assoc conway.dagger_unfoldr_distr sup_top_left)\n\nlemma top_plus:\n  \"1;x\\<^sup>+ = 1;x\"\nby (metis comp_assoc conway.dagger_unfoldr_distr star_denest_var_2 star_ext star_slide_var\n           sup_top_left top_unique)\n\nlemma plus_conv:\n  \"(x\\<^sup>+)\\<^sup>T = x\\<^sup>T\\<^sup>+\"\nby (simp add: star_conv star_slide_var)\n\nlemma inj_implies_step_forwards_backwards:\n  assumes \"is_inj x\"\n    shows \"x\\<^sup>\\<star>;(x\\<^sup>+\\<cdot>1');1 \\<le> x\\<^sup>T;1\"\nproof -\n  have \"(x\\<^sup>+\\<cdot>1');1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);(x\\<cdot>(x\\<^sup>\\<star>)\\<^sup>T);1\"\n    by (metis conv_contrav conv_e dedekind mult_1_right mult_isor star_slide_var)\n  also have \"... \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\"\n    by (simp add: comp_assoc mult_isol)\n  finally have 1: \"(x\\<^sup>+\\<cdot>1');1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\" .\n\n  have \"x;(x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1 \\<le> (x\\<^sup>+\\<cdot>x;x\\<^sup>T);1\"\n    by (metis inf_idem meet_interchange mult_isor)\n  also have \"... \\<le> (x\\<^sup>+\\<cdot>1');1\"\n    using assms is_inj_def meet_isor mult_isor by fastforce\n  finally have \"x;(x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\"\n    using 1 by fastforce\n  hence \"x\\<^sup>\\<star>;(x\\<^sup>+\\<cdot>1');1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\"\n    using 1 by (simp add: comp_assoc rtc_inductl)\n  thus \"x\\<^sup>\\<star>;(x\\<^sup>+\\<cdot>1');1 \\<le> x\\<^sup>T;1\"\n    using inf.cobounded2 mult_isor order_trans by blast\nqed\n\ntext \\<open>Acyclic relations\\<close>\n\ntext \\<open>The following result is from \\cite{Guttmann2017c}.\\<close>\n\nlemma acyclic_inv:\n  assumes \"is_acyclic t\"\n      and \"is_vector v\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n      and \"t \\<le> v;v\\<^sup>T\"\n    shows \"is_acyclic (t + e)\"\nproof -\n  have \"t\\<^sup>+;e \\<le> t\\<^sup>+;v;-v\\<^sup>T\"\n    by (simp add: assms(3) mult_assoc mult_isol)\n  also have \"... \\<le> v;v\\<^sup>T;t\\<^sup>\\<star>;v;-v\\<^sup>T\"\n    by (simp add: assms(4) mult_isor)\n  also have \"... \\<le> v;-v\\<^sup>T\"\n    by (metis assms(2) mult_double_iso top_greatest is_vector_def mult_assoc)\n  also have \"... \\<le> -1'\"\n    by (simp add: conv_galois_1)\n  finally have 1: \"t\\<^sup>+;e \\<le> -1'\" .\n  have \"e \\<le> v;-v\\<^sup>T\"\n    using assms(3) by simp\n  also have \"... \\<le> -1'\"\n    by (simp add: conv_galois_1)\n  finally have 2: \"t\\<^sup>+;e + e \\<le> -1'\"\n    using 1 by simp\n  have 3: \"e;t\\<^sup>\\<star> = e\"\n    by (metis assms(2-4) et(1) independence2)\n  have 4: \"e\\<^sup>\\<star> = 1' + e\"\n    using assms(2-3) ee boffa_var bot_least by blast\n  have \"(t + e)\\<^sup>+ = (t + e);t\\<^sup>\\<star>;(e;t\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: comp_assoc)\n  also have \"... = (t + e);t\\<^sup>\\<star>;(1' + e)\"\n    using 3 4 by simp\n  also have \"... = t\\<^sup>+;(1' + e) + e;t\\<^sup>\\<star>;(1' + e)\"\n    by simp\n  also have \"... = t\\<^sup>+;(1' + e) + e;(1' + e)\"\n    using 3 by simp\n  also have \"... = t\\<^sup>+;(1' + e) + e\"\n    using 4 assms(2-3) ee independence2 by fastforce\n  also have \"... = t\\<^sup>+ + t\\<^sup>+;e + e\"\n    by (simp add: distrib_left)\n  also have \"... \\<le> -1'\"\n    using assms(1) 2 by simp\n  finally show ?thesis .\nqed\n\nlemma acyclic_single_step:\n  assumes \"is_acyclic x\"\n    shows \"x \\<le> -1'\"\nby (metis assms dual_order.trans mult_isol mult_oner star_ref)\n\nlemma acyclic_reachable_points:\n  assumes \"is_point p\"\n      and \"is_point q\"\n      and \"p \\<le> x;q\"\n      and \"is_acyclic x\"\n    shows \"p\\<noteq>q\"\nproof\n  assume \"p=q\"\n  hence \"p \\<le> x;q \\<cdot> q\"\n    by (simp add: assms(3) order.eq_iff inf.absorb2)\n  also have \"... = (x \\<cdot> 1');q\"\n    using assms(2) inj_distr is_point_def by simp\n  also have \"... \\<le> (-1' \\<cdot> 1');q\"\n    using acyclic_single_step assms(4) by (metis abel_semigroup.commute inf.abel_semigroup_axioms\n          meet_isor mult_isor)\n also have \"... = 0\"\n  by simp\n finally have \"p \\<le> 0\" .\n thus False\n  using assms(1) bot_unique is_point_def by blast\nqed\n\nlemma acyclic_trans:\n assumes \"is_acyclic x\"\n   shows \"x \\<le> -(x\\<^sup>T\\<^sup>+)\"\nproof -\n have \"\\<exists>c\\<ge>x. c \\<le> - (x\\<^sup>+)\\<^sup>T\"\n  by (metis assms compl_mono conv_galois_2 conv_iso double_compl mult_onel star_1l)\n thus ?thesis\n  by (metis dual_order.trans plus_conv)\nqed\n\nlemma acyclic_trans':\n assumes \"is_acyclic x\"\n   shows \"x\\<^sup>\\<star> \\<le> -(x\\<^sup>T\\<^sup>+)\"\nproof -\n have \"x\\<^sup>\\<star> \\<le> - (- (- (x\\<^sup>T ; - (- 1'))) ; (x\\<^sup>\\<star>)\\<^sup>T)\"\n  by (metis assms conv_galois_1 conv_galois_2 order_trans star_trans)\n then show ?thesis\n  by (simp add: star_conv)\nqed\n\ntext \\<open>Regressively finite\\<close>\n\nlemma regressively_finite_acyclic:\n  assumes \"regressively_finite x\"\n    shows \"is_acyclic x\"\nproof -\n  have 1: \"is_vector ((x\\<^sup>+ \\<cdot> 1');1)\"\n    by (simp add: is_vector_def mult_assoc)\n  have \"(x\\<^sup>+ \\<cdot> 1');1 = (x\\<^sup>T\\<^sup>+ \\<cdot> 1');1\"\n    by (metis plus_conv test_converse)\n  also have \"... \\<le> x\\<^sup>T;(1';x\\<^sup>T\\<^sup>\\<star> \\<cdot> x);1\"\n    by (metis conv_invol modular_1_var mult_isor mult_oner mult_onel)\n  also have \"... \\<le> x\\<^sup>T;(1' \\<cdot> x\\<^sup>+);x\\<^sup>T\\<^sup>\\<star>;1\"\n    by (metis comp_assoc conv_invol modular_2_var mult_isol mult_isor star_conv)\n  also have \"... = x\\<^sup>T;(x\\<^sup>+ \\<cdot> 1');1\"\n    by (metis comp_assoc conway.dagger_unfoldr_distr inf.commute sup.cobounded1 top_le)\n  finally have \"(x\\<^sup>+ \\<cdot> 1');1 = 0\"\n    using 1 assms by (simp add: comp_assoc)\n  thus ?thesis\n    by (simp add: galois_aux ss_p18)\nqed\n\nnotation power (infixr \"\\<up>\" 80)\n\nlemma power_suc_below_plus:\n  \"x \\<up> Suc n \\<le> x\\<^sup>+\"\n  apply (induct n)\n using mult_isol star_ref apply fastforce\nby (simp add: mult_isol_var order_trans)\n\nend (* relation_algebra_rtc *)\n\nclass relation_algebra_rtc_tarski = relation_algebra_rtc + relation_algebra_tarski\nbegin\n\nlemma point_loop_not_acyclic:\n  assumes \"is_point p\"\n      and \"p \\<le> x \\<up> Suc n ; p\"\n    shows \"\\<not> is_acyclic x\"\nproof -\n  have \"p \\<le> x\\<^sup>+ ; p\"\n    by (meson assms dual_order.trans point_def point_is_point ss423bij power_suc_below_plus)\n  hence \"p ; p\\<^sup>T \\<le> x\\<^sup>+\"\n    using assms(1) point_def point_is_point ss423bij by blast\n  thus ?thesis\n    using assms(1) order.trans point_not_equal(1) point_not_equal(2) by blast\nqed\n\nend\n\nclass relation_algebra_rtc_point = relation_algebra_rtc + relation_algebra_point\n\nclass relation_algebra_rtc_tarski_point = relation_algebra_rtc_tarski + relation_algebra_rtc_point +\n                                          relation_algebra_tarski_point\n\ntext \\<open>\nFinite graphs: the axiom says the algebra has finitely many elements.\nThis means the relations have a finite base set.\n\\<close>\n\nclass relation_algebra_rtc_tarski_point_finite = relation_algebra_rtc_tarski_point + finite\nbegin\n\ntext \\<open>For a finite acyclic relation, the powers eventually vanish.\\<close>\n\nlemma acyclic_power_vanishes:\n  assumes \"is_acyclic x\"\n    shows \"\\<exists>n . x \\<up> Suc n = 0\"\nproof -\n  let ?n = \"card { p . is_point p }\"\n  let ?p = \"x \\<up> ?n\"\n  have \"?p = 0\"\n  proof (rule ccontr)\n    assume \"?p \\<noteq> 0\"\n    from this obtain p q where 1: \"point p \\<and> point q \\<and> p;q\\<^sup>T \\<le> ?p\"\n      using point_axiom by blast\n    hence 2: \"p \\<le> ?p;q\"\n      using point_def ss423bij by blast\n    have \"\\<forall>n\\<le>?n . (\\<exists>f. \\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x\\<up>(?n-i) ; f i \\<and> f i \\<le> x\\<up>(i-j) ; f j))\"\n    proof\n      fix n\n      show \"n\\<le>?n \\<longrightarrow> (\\<exists>f. \\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x\\<up>(?n-i) ; f i \\<and> f i \\<le> x\\<up>(i-j) ; f j))\"\n      proof (induct n)\n        case 0\n        thus ?case\n          using 1 2 point_is_point by fastforce\n      next\n        case (Suc n)\n        fix n\n        assume 3: \"n\\<le>?n \\<longrightarrow> (\\<exists>f . \\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j))\"\n        show \"Suc n\\<le>?n \\<longrightarrow> (\\<exists>f . \\<forall>i\\<le>Suc n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j))\"\n        proof\n          assume 4: \"Suc n\\<le>?n\"\n          from this obtain f where 5: \"\\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j)\"\n            using 3 by auto\n          have \"p \\<le> x \\<up> (?n-n) ; f n\"\n            using 5 by blast\n          also have \"... = x \\<up> (?n-n-one_class.one) ; x ; f n\"\n            using 4 by (metis (no_types) Suc_diff_le diff_Suc_1 diff_Suc_Suc power_Suc2)\n          finally obtain r where 6: \"point r \\<and> p \\<le> x \\<up> (?n-Suc n) ; r \\<and> r \\<le> x ; f n\"\n            using 1 5 intermediate_point_theorem point_is_point by fastforce\n          let ?g = \"\\<lambda>m . if m = Suc n then r else f m\"\n          have \"\\<forall>i\\<le>Suc n . is_point (?g i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; ?g i \\<and> ?g i \\<le> x \\<up> (i-j) ; ?g j)\"\n          proof\n            fix i\n            show \"i\\<le>Suc n \\<longrightarrow> is_point (?g i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; ?g i \\<and> ?g i \\<le> x \\<up> (i-j) ; ?g j)\"\n            proof (cases \"i\\<le>n\")\n              case True\n              thus ?thesis\n                using 5 by simp\n            next\n              case False\n              have \"is_point (?g (Suc n)) \\<and> (\\<forall>j\\<le>Suc n . p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j)\"\n              proof\n                show \"is_point (?g (Suc n))\"\n                  using 6 point_is_point by fastforce\n              next\n                show \"\\<forall>j\\<le>Suc n . p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                proof\n                  fix j\n                  show \"j\\<le>Suc n \\<longrightarrow> p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                  proof\n                    assume 7: \"j\\<le>Suc n\"\n                    show \"p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                    proof\n                      show \"p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n)\"\n                        using 6 by simp\n                    next\n                      show \"?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                      proof (cases \"j = Suc n\")\n                        case True\n                        thus ?thesis\n                          by simp\n                      next\n                        case False\n                        hence \"f n \\<le> x \\<up> (n-j) ; f j\"\n                          using 5 7 by fastforce\n                        hence \"x ; f n \\<le> x \\<up> (Suc n-j) ; f j\"\n                          using 7 False Suc_diff_le comp_assoc mult_isol by fastforce\n                        thus ?thesis\n                          using 6 False by fastforce\n                      qed\n                    qed\n                  qed\n                qed\n              qed\n              thus ?thesis\n                by (simp add: False le_Suc_eq)\n            qed\n          qed\n          thus \"\\<exists>f . \\<forall>i\\<le>Suc n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j)\"\n            by auto\n        qed\n      qed\n    qed\n    from this obtain f where 8: \"\\<forall>i\\<le>?n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j)\"\n      by fastforce\n    let ?A = \"{ k . k\\<le>?n }\"\n    have \"f ` ?A \\<subseteq> { p . is_point p }\"\n      using 8 by blast\n    hence \"card (f ` ?A) \\<le> ?n\"\n      by (simp add: card_mono)\n    hence \"\\<not> inj_on f ?A\"\n      by (simp add: pigeonhole)\n    from this obtain i j where 9: \"i \\<le> ?n \\<and> j \\<le> ?n \\<and> i \\<noteq> j \\<and> f i = f j\"\n      by (metis (no_types, lifting) inj_on_def mem_Collect_eq)\n    show False\n      apply (cases \"i < j\")\n     using 8 9 apply (metis Suc_diff_le Suc_leI assms diff_Suc_Suc order_less_imp_le\n                            point_loop_not_acyclic)\n    using 8 9 by (metis assms neqE point_loop_not_acyclic Suc_diff_le Suc_leI assms diff_Suc_Suc\n                        order_less_imp_le)\n    qed\n    thus ?thesis\n      by (metis annir power.simps(2))\nqed\n\ntext \\<open>Hence finite acyclic relations are regressively finite.\\<close>\n\nlemma acyclic_regressively_finite:\n  assumes \"is_acyclic x\"\n    shows \"regressively_finite x\"\nproof\n  have \"is_acyclic (x\\<^sup>T)\"\n    using assms acyclic_trans' compl_le_swap1 order_trans star_ref by blast\n  from this obtain n where 1: \"x\\<^sup>T \\<up> Suc n = 0\"\n    using acyclic_power_vanishes by fastforce\n  fix v\n  show \"is_vector v \\<and> v \\<le> x\\<^sup>T;v \\<longrightarrow> v = 0\"\n  proof\n    assume 2: \"is_vector v \\<and> v \\<le> x\\<^sup>T;v\"\n    have \"v \\<le> x\\<^sup>T \\<up> Suc n ; v\"\n    proof (induct n)\n      case 0\n      thus ?case\n        using 2 by simp\n    next\n      case (Suc n)\n      hence \"x\\<^sup>T ; v \\<le> x\\<^sup>T \\<up> Suc (Suc n) ; v\"\n        by (simp add: comp_assoc mult_isol)\n      thus ?case\n        using 2 dual_order.trans by blast\n    qed\n    thus \"v = 0\"\n      using 1 by (simp add: le_bot)\n  qed\n qed\n\nlemma acyclic_is_regressively_finite:\n  \"is_acyclic x \\<longleftrightarrow> regressively_finite x\"\nusing acyclic_regressively_finite regressively_finite_acyclic by blast\n\nend (* end relation_algebra_rtc_tarski_point_finite *)\n\nend\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Relational_Paths/More_Relation_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7778508474459098}}
{"text": "theory Part_1 imports Main\n\nbegin\n\n(* 5.1 *)\n\nlemma assumes T: \"\\<forall>x y. T x y \\<or> T y x\"\n  and A: \"\\<forall>x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n  and TA: \"\\<forall>x y. T x y \\<longrightarrow> A x y\" and \"A x y\"\n  shows \"T x y\"\nproof (rule ccontr)\n  assume \"\\<not> T x y\"\n  from this and T have \"T y x\" by blast\n  from this and TA have \"A y x\" by blast\n  from this and `A x y` and A have \"x = y\" by blast\n  from this and `\\<not> T x y` and `T y x` show \"False\" by blast\nqed\n\n(* 5.2 *)\n\nlemma \"(\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs)\n  \\<or> (\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs + 1)\"\nproof cases\n  assume \"even (length xs)\"\n  then obtain k where ks:\"(length xs) = 2*k\" by blast\n  obtain ys where 1:\"ys = take k xs\" by auto\n  obtain zs where 2:\"zs = drop k xs\" by auto\n  then have \"xs = ys @ zs\" by (simp add: \\<open>ys = take k xs\\<close>)\n  moreover have \"length ys = length zs\" using 1 and 2 and ks by simp\n  ultimately show ?thesis by blast\nnext\n  assume \"odd (length xs)\"\n  then obtain k where ks:\"length xs = 2*k + 1\" using oddE by blast\n  obtain ys where 1:\"ys = take (Suc k) xs\" by auto\n  obtain zs where 2:\"zs = drop (Suc k) xs\" by auto\n  then have \"xs = ys @ zs\" using 1 and 2 by simp\n  moreover have \"length ys = length zs + 1\" by (simp add: \"1\" \"2\" ks)\n  ultimately show ?thesis by blast\nqed\n\nend", "meta": {"author": "joshua-morris", "repo": "concrete-semantics", "sha": "a6621e2d7b55b7a6965ed17a21befc93cd9dd298", "save_path": "github-repos/isabelle/joshua-morris-concrete-semantics", "path": "github-repos/isabelle/joshua-morris-concrete-semantics/concrete-semantics-a6621e2d7b55b7a6965ed17a21befc93cd9dd298/chapter-5/Part_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7778430763237002}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Braun Trees\\<close>\n\ntheory Braun_Tree\nimports \"HOL-Library.Tree_Real\"\nbegin\n\ntext \\<open>Braun Trees were studied by Braun and Rem~\\<^cite>\\<open>\"BraunRem\"\\<close>\nand later Hoogerwoord~\\<^cite>\\<open>\"Hoogerwoord\"\\<close>.\\<close>\n\nfun braun :: \"'a tree \\<Rightarrow> bool\" where\n\"braun Leaf = True\" |\n\"braun (Node l x r) = ((size l = size r \\<or> size l = size r + 1) \\<and> braun l \\<and> braun r)\"\n\nlemma braun_Node':\n  \"braun (Node l x r) = (size r \\<le> size l \\<and> size l \\<le> size r + 1 \\<and> braun l \\<and> braun r)\"\nby auto\n\ntext \\<open>The shape of a Braun-tree is uniquely determined by its size:\\<close>\n\nlemma braun_unique: \"\\<lbrakk> braun (t1::unit tree); braun t2; size t1 = size t2 \\<rbrakk> \\<Longrightarrow> t1 = t2\"\nproof (induction t1 arbitrary: t2)\n  case Leaf thus ?case by simp\nnext\n  case (Node l1 _ r1)\n  from Node.prems(3) have \"t2 \\<noteq> Leaf\" by auto\n  then obtain l2 x2 r2 where [simp]: \"t2 = Node l2 x2 r2\" by (meson neq_Leaf_iff)\n  with Node.prems have \"size l1 = size l2 \\<and> size r1 = size r2\" by auto\n  thus ?case using Node.prems(1,2) Node.IH by auto\nqed\n\ntext \\<open>Braun trees are almost complete:\\<close>\n\nlemma acomplete_if_braun: \"braun t \\<Longrightarrow> acomplete t\"\nproof(induction t)\n  case Leaf show ?case by (simp add: acomplete_def)\nnext\n  case (Node l x r) thus ?case using acomplete_Node_if_wbal2 by force\nqed\n\nsubsection \\<open>Numbering Nodes\\<close>\n\ntext \\<open>We show that a tree is a Braun tree iff a parity-based\nnumbering (\\<open>braun_indices\\<close>) of nodes yields an interval of numbers.\\<close>\n\nfun braun_indices :: \"'a tree \\<Rightarrow> nat set\" where\n\"braun_indices Leaf = {}\" |\n\"braun_indices (Node l _ r) = {1} \\<union> (*) 2 ` braun_indices l \\<union> Suc ` (*) 2 ` braun_indices r\"\n\nlemma braun_indices1: \"0 \\<notin> braun_indices t\"\nby (induction t) auto\n\nlemma finite_braun_indices: \"finite(braun_indices t)\"\nby (induction t) auto\n\ntext \"One direction:\"\n\nlemma braun_indices_if_braun: \"braun t \\<Longrightarrow> braun_indices t = {1..size t}\"\nproof(induction t)\n  case Leaf thus ?case by simp\nnext\n  have *: \"(*) 2 ` {a..b} \\<union> Suc ` (*) 2 ` {a..b} = {2*a..2*b+1}\" (is \"?l = ?r\") for a b\n  proof\n    show \"?l \\<subseteq> ?r\" by auto\n  next\n    have \"\\<exists>x2\\<in>{a..b}. x \\<in> {Suc (2*x2), 2*x2}\" if *: \"x \\<in> {2*a .. 2*b+1}\" for x\n    proof -\n      have \"x div 2 \\<in> {a..b}\" using * by auto\n      moreover have \"x \\<in> {2 * (x div 2), Suc(2 * (x div 2))}\" by auto\n      ultimately show ?thesis by blast\n    qed\n    thus \"?r \\<subseteq> ?l\" by fastforce\n  qed\n  case (Node l x r)\n  hence \"size l = size r \\<or> size l = size r + 1\" (is \"?A \\<or> ?B\") by auto\n  thus ?case\n  proof\n    assume ?A\n    with Node show ?thesis by (auto simp: *)\n  next\n    assume ?B\n    with Node show ?thesis by (auto simp: * atLeastAtMostSuc_conv)\n  qed\nqed\n\ntext \"The other direction is more complicated. The following proof is due to Thomas Sewell.\"\n\nlemma disj_evens_odds: \"(*) 2 ` A \\<inter> Suc ` (*) 2 ` B = {}\"\nusing double_not_eq_Suc_double by auto\n\nlemma card_braun_indices: \"card (braun_indices t) = size t\"\nproof (induction t)\n  case Leaf thus ?case by simp\nnext\n  case Node\n  thus ?case\n    by(auto simp: UNION_singleton_eq_range finite_braun_indices card_Un_disjoint\n                  card_insert_if disj_evens_odds card_image inj_on_def braun_indices1)\nqed\n\nlemma braun_indices_intvl_base_1:\n  assumes bi: \"braun_indices t = {m..n}\"\n  shows \"{m..n} = {1..size t}\"\nproof (cases \"t = Leaf\")\n  case True then show ?thesis using bi by simp\nnext\n  case False\n  note eqs = eqset_imp_iff[OF bi]\n  from eqs[of 0] have 0: \"0 < m\"\n    by (simp add: braun_indices1)\n  from eqs[of 1] have 1: \"m \\<le> 1\"\n    by (cases t; simp add: False)\n  from 0 1 have eq1: \"m = 1\" by simp\n  from card_braun_indices[of t] show ?thesis\n    by (simp add: bi eq1)\nqed\n\nlemma even_of_intvl_intvl:\n  fixes S :: \"nat set\"\n  assumes \"S = {m..n} \\<inter> {i. even i}\"\n  shows \"\\<exists>m' n'. S = (\\<lambda>i. i * 2) ` {m'..n'}\"\n  apply (rule exI[where x=\"Suc m div 2\"], rule exI[where x=\"n div 2\"])\n  apply (fastforce simp add: assms mult.commute)\n  done\n\nlemma odd_of_intvl_intvl:\n  fixes S :: \"nat set\"\n  assumes \"S = {m..n} \\<inter> {i. odd i}\"\n  shows \"\\<exists>m' n'. S = Suc ` (\\<lambda>i. i * 2) ` {m'..n'}\"\nproof -\n  have step1: \"\\<exists>m'. S = Suc ` ({m'..n - 1} \\<inter> {i. even i})\"\n    apply (rule_tac x=\"if n = 0 then 1 else m - 1\" in exI)\n    apply (auto simp: assms image_def elim!: oddE)\n    done\n  thus ?thesis\n    by (metis even_of_intvl_intvl)\nqed\n\nlemma image_int_eq_image:\n  \"(\\<forall>i \\<in> S. f i \\<in> T) \\<Longrightarrow> (f ` S) \\<inter> T = f ` S\"\n  \"(\\<forall>i \\<in> S. f i \\<notin> T) \\<Longrightarrow> (f ` S) \\<inter> T = {}\"\n  by auto\n\nlemma braun_indices1_le:\n  \"i \\<in> braun_indices t \\<Longrightarrow> Suc 0 \\<le> i\"\n  using braun_indices1 not_less_eq_eq by blast\n\nlemma braun_if_braun_indices: \"braun_indices t = {1..size t} \\<Longrightarrow> braun t\"\nproof(induction t)\ncase Leaf\n  then show ?case by simp\nnext\n  case (Node l x r)\n  obtain t where t: \"t = Node l x r\" by simp\n  from Node.prems have eq: \"{2 .. size t} = (\\<lambda>i. i * 2) ` braun_indices l \\<union> Suc ` (\\<lambda>i. i * 2) ` braun_indices r\"\n    (is \"?R = ?S \\<union> ?T\")\n    apply clarsimp\n    apply (drule_tac f=\"\\<lambda>S. S \\<inter> {2..}\" in arg_cong)\n    apply (simp add: t mult.commute Int_Un_distrib2 image_int_eq_image braun_indices1_le)\n    done\n  then have ST: \"?S = ?R \\<inter> {i. even i}\" \"?T = ?R \\<inter> {i. odd i}\"\n    by (simp_all add: Int_Un_distrib2 image_int_eq_image)\n  from ST have l: \"braun_indices l = {1 .. size l}\"\n    by (fastforce dest: braun_indices_intvl_base_1 dest!: even_of_intvl_intvl\n                  simp: mult.commute inj_image_eq_iff[OF inj_onI])\n  from ST have r: \"braun_indices r = {1 .. size r}\"\n    by (fastforce dest: braun_indices_intvl_base_1 dest!: odd_of_intvl_intvl\n                  simp: mult.commute inj_image_eq_iff[OF inj_onI])\n  note STa = ST[THEN eqset_imp_iff, THEN iffD2]\n  note STb = STa[of \"size t\"] STa[of \"size t - 1\"]\n  then have sizes: \"size l = size r \\<or> size l = size r + 1\"\n    apply (clarsimp simp: t l r inj_image_mem_iff[OF inj_onI])\n    apply (cases \"even (size l)\"; cases \"even (size r)\"; clarsimp elim!: oddE; fastforce)\n    done\n  from l r sizes show ?case\n    by (clarsimp simp: Node.IH)\nqed\n\nlemma braun_iff_braun_indices: \"braun t \\<longleftrightarrow> braun_indices t = {1..size t}\"\nusing braun_if_braun_indices braun_indices_if_braun by blast\n\n(* An older less appealing proof:\nlemma Suc0_notin_double: \"Suc 0 \\<notin> ( * ) 2 ` A\"\nby(auto)\n\nlemma zero_in_double_iff: \"(0::nat) \\<in> ( * ) 2 ` A \\<longleftrightarrow> 0 \\<in> A\"\nby(auto)\n\nlemma Suc_in_Suc_image_iff: \"Suc n \\<in> Suc ` A \\<longleftrightarrow> n \\<in> A\"\nby(auto)\n\nlemmas nat_in_image = Suc0_notin_double zero_in_double_iff Suc_in_Suc_image_iff\n\nlemma disj_union_eq_iff:\n  \"\\<lbrakk> L1 \\<inter> R2 = {}; L2 \\<inter> R1 = {} \\<rbrakk> \\<Longrightarrow> L1 \\<union> R1 = L2 \\<union> R2 \\<longleftrightarrow> L1 = L2 \\<and> R1 = R2\"\nby blast\n\nlemma inj_braun_indices: \"braun_indices t1 = braun_indices t2 \\<Longrightarrow> t1 = (t2::unit tree)\"\nproof(induction t1 arbitrary: t2)\n  case Leaf thus ?case using braun_indices.elims by blast\nnext\n  case (Node l1 x1 r1)\n  have \"t2 \\<noteq> Leaf\"\n  proof\n    assume \"t2 = Leaf\"\n    with Node.prems show False by simp\n  qed\n  thus ?case using Node\n    by (auto simp: neq_Leaf_iff insert_ident nat_in_image braun_indices1\n                  disj_union_eq_iff disj_evens_odds inj_image_eq_iff inj_def)\nqed\n\ntext \\<open>How many even/odd natural numbers are there between m and n?\\<close>\n\nlemma card_Icc_even_nat:\n  \"card {i \\<in> {m..n::nat}. even i} = (n+1-m + (m+1) mod 2) div 2\" (is \"?l m n = ?r m n\")\nproof(induction \"n+1 - m\" arbitrary: n m)\n   case 0 thus ?case by simp\nnext\n  case Suc\n  have \"m \\<le> n\" using Suc(2) by arith\n  hence \"{m..n} = insert m {m+1..n}\" by auto\n  hence \"?l m n = card {i \\<in> insert m {m+1..n}. even i}\" by simp\n  also have \"\\<dots> = ?r m n\" (is \"?l = ?r\")\n  proof (cases)\n    assume \"even m\"\n    hence \"{i \\<in> insert m {m+1..n}. even i} = insert m {i \\<in> {m+1..n}. even i}\" by auto\n    hence \"?l = card {i \\<in> {m+1..n}. even i} + 1\" by simp\n    also have \"\\<dots> = (n-m + (m+2) mod 2) div 2 + 1\" using Suc(1)[of n \"m+1\"] Suc(2) by simp\n    also have \"\\<dots> = ?r\" using \\<open>even m\\<close> \\<open>m \\<le> n\\<close> by auto\n    finally show ?thesis .\n  next\n    assume \"odd m\"\n    hence \"{i \\<in> insert m {m+1..n}. even i} = {i \\<in> {m+1..n}. even i}\" by auto\n    hence \"?l = card ...\" by simp\n    also have \"\\<dots> = (n-m + (m+2) mod 2) div 2\" using Suc(1)[of n \"m+1\"] Suc(2) by simp\n    also have \"\\<dots> = ?r\" using \\<open>odd m\\<close> \\<open>m \\<le> n\\<close> even_iff_mod_2_eq_zero[of m] by simp\n    finally show ?thesis .\n  qed\n  finally show ?case .\nqed\n\nlemma card_Icc_odd_nat: \"card {i \\<in> {m..n::nat}. odd i} = (n+1-m + m mod 2) div 2\"\nproof -\n  let ?A = \"{i \\<in> {m..n}. odd i}\"\n  let ?B = \"{i \\<in> {m+1..n+1}. even i}\"\n  have \"card ?A = card (Suc ` ?A)\" by (simp add: card_image)\n  also have \"Suc ` ?A = ?B\" using Suc_le_D by(force simp: image_iff)\n  also have \"card ?B = (n+1-m + (m) mod 2) div 2\"\n    using card_Icc_even_nat[of \"m+1\" \"n+1\"] by simp\n  finally show ?thesis .\nqed\n\nlemma compact_Icc_even: assumes \"A = {i \\<in> {m..n}. even i}\"\nshows \"A = (\\<lambda>j. 2*(j-1) + m + m mod 2) ` {1..card A}\" (is \"_ = ?A\")\nproof\n  let ?a = \"(n+1-m + (m+1) mod 2) div 2\"\n  have \"\\<exists>j \\<in> {1..?a}. i = 2*(j-1) + m + m mod 2\" if *: \"i \\<in> {m..n}\" \"even i\" for i\n  proof -\n    let ?j = \"(i - (m + m mod 2)) div 2 + 1\"\n    have \"?j \\<in> {1..?a} \\<and> i = 2*(?j-1) + m + m mod 2\" using * by(auto simp: mod2_eq_if) presburger+\n    thus ?thesis by blast\n  qed\n  thus \"A \\<subseteq> ?A\" using assms\n    by(auto simp: image_iff card_Icc_even_nat simp del: atLeastAtMost_iff)\nnext\n  let ?a = \"(n+1-m + (m+1) mod 2) div 2\"\n  have 1: \"2 * (j - 1) + m + m mod 2 \\<in> {m..n}\" if *: \"j \\<in> {1..?a}\" for j\n    using * by(auto simp: mod2_eq_if)\n  have 2: \"even (2 * (j - 1) + m + m mod 2)\" for j by presburger\n  show \"?A \\<subseteq> A\"\n    apply(simp add: assms card_Icc_even_nat del: atLeastAtMost_iff One_nat_def)\n    using 1 2 by blast\nqed\n\nlemma compact_Icc_odd:\n  assumes \"B = {i \\<in> {m..n}. odd i}\" shows \"B = (\\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..card B}\"\nproof -\n  define A :: \" nat set\" where \"A = Suc ` B\"\n  have \"A = {i \\<in> {m+1..n+1}. even i}\"\n    using Suc_le_D by(force simp add: A_def assms image_iff)\n  from compact_Icc_even[OF this]\n  have \"A = Suc ` (\\<lambda>i. 2 * (i - 1) + m + (m + 1) mod 2) ` {1..card A}\"\n    by (simp add: image_comp o_def)\n  hence B: \"B = (\\<lambda>i. 2 * (i - 1) + m + (m + 1) mod 2) ` {1..card A}\"\n    using A_def by (simp add: inj_image_eq_iff)\n  have \"card A = card B\" by (metis A_def bij_betw_Suc bij_betw_same_card) \n  with B show ?thesis by simp\nqed\n\nlemma even_odd_decomp: assumes \"\\<forall>x \\<in> A. even x\" \"\\<forall>x \\<in> B. odd x\"  \"A \\<union> B = {m..n}\"\nshows \"(let a = card A; b = card B in\n   a + b = n+1-m \\<and>\n   A = (\\<lambda>i. 2*(i-1) + m + m mod 2) ` {1..a} \\<and>\n   B = (\\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..b} \\<and>\n   (a = b \\<or> a = b+1 \\<and> even m \\<or> a+1 = b \\<and> odd m))\"\nproof -\n  let ?a = \"card A\" let ?b = \"card B\"\n  have \"finite A \\<and> finite B\"\n    by (metis \\<open>A \\<union> B = {m..n}\\<close> finite_Un finite_atLeastAtMost)\n  hence ab: \"?a + ?b = Suc n - m\"\n    by (metis Int_emptyI assms card_Un_disjoint card_atLeastAtMost)\n  have A: \"A = {i \\<in> {m..n}. even i}\" using assms by auto\n  hence A': \"A = (\\<lambda>i. 2*(i-1) + m + m mod 2) ` {1..?a}\" by(rule compact_Icc_even)\n  have B: \"B = {i \\<in> {m..n}. odd i}\" using assms by auto\n  hence B': \"B = (\\<lambda>i. 2*(i-1) + m + (m+1) mod 2) ` {1..?b}\" by(rule compact_Icc_odd)\n  have \"?a = ?b \\<or> ?a = ?b+1 \\<and> even m \\<or> ?a+1 = ?b \\<and> odd m\"\n    apply(simp add: Let_def mod2_eq_if\n      card_Icc_even_nat[of m n, simplified A[symmetric]]\n      card_Icc_odd_nat[of m n, simplified B[symmetric]] split!: if_splits)\n    by linarith\n  with ab A' B' show ?thesis by simp\nqed\n\nlemma braun_if_braun_indices: \"braun_indices t = {1..size t} \\<Longrightarrow> braun t\"\nproof(induction t)\ncase Leaf\n  then show ?case by simp\nnext\n  case (Node t1 x2 t2)\n  have 1: \"i > 0 \\<Longrightarrow> Suc(Suc(2 * (i - Suc 0))) = 2*i\" for i::nat by(simp add: algebra_simps)\n  have 2: \"i > 0 \\<Longrightarrow> 2 * (i - Suc 0) + 3 = 2*i + 1\" for i::nat by(simp add: algebra_simps)\n  have 3: \"( * ) 2 ` braun_indices t1 \\<union> Suc ` ( * ) 2 ` braun_indices t2 =\n     {2..size t1 + size t2 + 1}\" using Node.prems\n    by (simp add: insert_ident Icc_eq_insert_lb_nat nat_in_image braun_indices1)\n  thus ?case using Node.IH even_odd_decomp[OF _ _ 3]\n    by(simp add: card_image inj_on_def card_braun_indices Let_def 1 2 inj_image_eq_iff image_comp\n           cong: image_cong_simp)\nqed\n*)\n\nend", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/Braun_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8933093954028816, "lm_q1q2_score": 0.7777127224805237}}
{"text": "theory Exe2p11\n  imports Main\nbegin\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var i = i\" |\n\"eval (Const i) _ = i\" |\n\"eval (Add e1 e2) i = (eval e1 i) + (eval e2 i)\" |\n\"eval (Mult e1 e2) i = (eval e1 i) * (eval e2 i)\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] x = 0\" |\n\"evalp (h#t) x = h + (evalp t x) * x\"\n\nfun trimp :: \"int list \\<Rightarrow> int list\" where\n\"trimp [] = []\" |\n\"trimp (h#t) = (if h = 0\n                then (if length (trimp t) = 0\n                      then []\n                      else (h#trimp t))\n                else (h#trimp t))\" \n\nfun addp :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"addp [] xs = xs\" |\n\"addp xs [] = xs\" |\n\"addp (h1#t1) (h2#t2) = (h1 + h2) # (addp t1 t2)\"\n\nfun multp :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"multp [] _ = []\" |\n\"multp (h#t) l = addp (map (op * h) l) (0 # multp t l)\" \n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0,1]\" |\n\"coeffs (Const z) = [z]\" |\n\"coeffs (Add e1 e2) = addp (coeffs e1) (coeffs e2)\" |\n\"coeffs (Mult e1 e2) = multp (coeffs e1) (coeffs e2)\"\n\n\n\nlemma [simp]: \"evalp (addp l1 l2) x = evalp l1 x + evalp l2 x\"\n  apply(induction l1 rule: addp.induct)\n    apply(auto simp add: algebra_simps)\n  done\n\nlemma [simp]: \"evalp (multp l []) x = 0\"\n  apply(induction l)\n   apply(auto)\n  done\n\nlemma [simp]: \"evalp (multp l (h # t)) x = h * evalp l x + x * (evalp (multp l t) x)\"\n  apply(induction l)\n   apply(auto simp add: algebra_simps)\n  done\n\nlemma [simp]: \"evalp (multp l1 l2) x = evalp l1 x * evalp l2 x\"\n  apply(induction l1 rule: multp.induct)\n   apply(auto simp add: algebra_simps)\n  done\n\nlemma \"evalp (coeffs e) x = eval e x\"\n  apply(induction e arbitrary: x)\n   apply(auto simp add: algebra_simps)\n  done\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/prog-prove/Exe2p11.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7776473990356957}}
{"text": "chapter \\<open>Examples for IMP with Arrays\\<close>\ntheory IMPAHP_Examples\nimports IMPArrayHoareTotal\nbegin\n  \nsection \\<open>Program Verification\\<close>\n\ncontext Imp_Array_Examples begin\n\nsubsection \\<open>Common Loop Patterns\\<close>\n\nsubsubsection \\<open>Approximate from Below\\<close>\ntext \\<open>Used to invert a monotonic function. \n  We count up, until we overshoot the desired result, \n  then we subtract one. \n\\<close>  \n\nabbreviation \"sqrt_prog \\<equiv> \n  CLR r;; \n  r ::= N 1;;\n  WHILE ($r * $r <= $n) DO (\n    r ::= Plus ($r) (N 1)\n  );;\n  r ::= Minus ($r) (N 1)\n  \"\n\ntext \\<open>The invariant states that the \\<open>r-1\\<close> is not too big.\n  When the loop terminates, \\<open>r-1\\<close> is not too big, but \\<open>r\\<close> is already too big,\n  so \\<open>r-1\\<close> is the desired value (rounding down).\n\\<close>\ndefinition Isqrt :: \"int \\<Rightarrow> int \\<Rightarrow> bool\" \n  where \"Isqrt n\\<^sub>0 r \\<equiv> 0\\<le>r \\<and> (r-1)\\<^sup>2 \\<le> n\\<^sub>0\"  \n  \ntext \\<open>Note: Be careful to not accidentally define the invariant \n  over some generic type \\<open>'a\\<close>! \\<close>  \n  \nlemma Isqrt_aux:\n  \"0 \\<le> n\\<^sub>0 \\<Longrightarrow> Isqrt n\\<^sub>0 1\"\n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; r * r \\<le> n\\<^sub>0; Isqrt n\\<^sub>0 r\\<rbrakk> \\<Longrightarrow> Isqrt n\\<^sub>0 (r + 1)\"\n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; \\<not> r * r \\<le> n\\<^sub>0; Isqrt n\\<^sub>0 r\\<rbrakk> \\<Longrightarrow> (r - 1)\\<^sup>2 \\<le> n\\<^sub>0 \\<and> n\\<^sub>0 < r\\<^sup>2\"\n  \"Isqrt n\\<^sub>0 r \\<Longrightarrow> r * r \\<le> n\\<^sub>0 \\<Longrightarrow> r\\<le>n\\<^sub>0\"\n  apply (auto simp: Isqrt_def power2_eq_square algebra_simps)\n  by (smt combine_common_factor mult_right_mono semiring_normalization_rules(3))\n  \nfind_theorems \"(_(_:=_)) _\"\n\nlemma \"0\\<le>n\\<^sub>0 \\<Longrightarrow>                    \n  \\<Turnstile>\\<^sub>t {vars n in n=n\\<^sub>0}           \n      sqrt_prog \n    {vars r n in n=n\\<^sub>0 \\<and> r\\<^sup>2 \\<le> n\\<^sub>0 \\<and> n\\<^sub>0 < (r+1)\\<^sup>2}\"\n  apply (rewrite annot_tinvar[where \n    R=\"measure (\\<lambda>s. nat (s ''n'' 0 + 1 - s ''r'' 0))\" and\n    I=\"vars r n in n=n\\<^sub>0 \\<and> Isqrt n\\<^sub>0 r\n    \"]) \n  supply Isqrt_aux [simp]\n  apply vcg\n  done  \n\nsubsubsection \\<open>Count up\\<close>\n\ntext \\<open>Count up to the desired value, and iteratively compute a function on the way\\<close>\nabbreviation \"exp_prog \\<equiv> \n  CLR c;; CLR r;;  \n  c ::= N 0;;\n  r ::= N 1;;\n  WHILE $c < $n DO (\n    r ::= $r * $b;;\n    c ::= $c + (N 1)\n  )\"\n\ntext \\<open>The invariant states that we have computed the function for value \\<open>c\\<close>:\\<close>  \n  \nabbreviation \"Iexp n\\<^sub>0 b\\<^sub>0 r c \\<equiv> 0\\<le>c \\<and> c\\<le>n\\<^sub>0 \\<and> r = b\\<^sub>0 ^ nat c\"\n  \nlemma \"0\\<le>n\\<^sub>0 \\<Longrightarrow>                                \n  \\<Turnstile>\\<^sub>t {vars n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0}  \n       exp_prog \n     {vars r n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0 \\<and> r = b\\<^sub>0 ^ nat n\\<^sub>0}\"\n  apply (rewrite annot_tinvar[where \n    R=\"measure (\\<lambda>s. nat (s ''n'' 0 - s ''c'' 0))\" and \n    I=\"vars r c n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0 \\<and> Iexp n\\<^sub>0 b\\<^sub>0 r c\"])\n  supply nat_add_distrib[simp]\n  apply vcg\n  done\n\n  \nsubsubsection \\<open>Count down\\<close>  \n  \ntext \\<open>Essentially the same as count up, but we use the input variable as counter\\<close>\n\nabbreviation \"exp_prog' \\<equiv> \n  CLR r;;  (* Aux variables are cleared before use. *)\n  r ::= N 1;;\n  WHILE N 0 < $n DO (\n    r ::= $r * $b;;\n    n ::= $n - N 1\n  )\"\n\ntext \\<open>The invariant is the same as for count-up. \n  Only that we have to compute the actual number \n  of loop iterations by \\<open>n\\<^sub>0 - n\\<close>\n\\<close>  \ndefinition exp_invar' :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> bool\"\n  where \"exp_invar' n\\<^sub>0 b\\<^sub>0 n r \\<equiv> (\n      let c=n\\<^sub>0-n in\n        0\\<le>c \\<and> c\\<le>n\\<^sub>0 \\<and> r = b\\<^sub>0 ^ nat c\n    )\"\n\ntext \\<open>If the invariants become more complex or hard to prove automatically,\n  it can be advantageous to define the (logical part of) the invariant as\n  a predicate, and prove the required VCs as separate lemmas.\n\\<close>  \n    \n\n\nlemma \"0\\<le>n\\<^sub>0 \\<Longrightarrow> \n  \\<Turnstile>\\<^sub>t {vars n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0} \n       exp_prog' \n    {vars r b in b=b\\<^sub>0 \\<and> r = (b\\<^sub>0 ^ nat n\\<^sub>0)}\"\nproof -\n  note [simp] = aux1 aux2 aux3\n  assume \"0\\<le>n\\<^sub>0\"\n  then show ?thesis\n    apply (rewrite annot_tinvar[where \n      I=\"vars r n b in b=b\\<^sub>0 \\<and> exp_invar' n\\<^sub>0 b\\<^sub>0 n r\" and\n      R=\"measure (\\<lambda>s. nat (s ''n'' 0))\"\n      ])\n    by vcg \nqed    \n\n\n\n\nabbreviation \"sqr_prog \\<equiv> \n  CLR a;; CLR b;; \n  b ::= \\<acute>1;;\n  a ::= \\<acute>0;;\n  WHILE (\\<acute>0 < $n) DO (\n    a ::= $a + $b;;\n    b ::= $b + \\<acute>2;;\n    n ::= $n - \\<acute>1\n  )\"\n\nlemma \"n\\<^sub>0\\<ge>0 \\<Longrightarrow> \\<Turnstile>\\<^sub>t {vars n in n=n\\<^sub>0} sqr_prog {vars a in a=n\\<^sub>0\\<^sup>2}\"\n  apply (rewrite annot_tinvar[where R=\"measure (\\<lambda>s. nat (s ''n'' 0))\" \n        and I=\"vars a b n in 0\\<le>n \\<and> n\\<le>n\\<^sub>0 \\<and> (let i=n\\<^sub>0-n in b=2*i+1 \\<and> a=i\\<^sup>2)\"])\n  apply vcg_all\n  apply (auto simp: power2_eq_square algebra_simps)\n  done\n\n\nabbreviation \"sqr_prog' \\<equiv> \n  CLR a;; CLR b;; CLR c;;\n  b ::= \\<acute>1;;\n  a ::= \\<acute>0;;\n  c ::= \\<acute>0;;\n  WHILE ($c < $n) DO (\n    a ::= $a + $b;;\n    b ::= $b + \\<acute>2;;\n    c ::= $c + \\<acute>1\n  )\"\n\nlemma \"n\\<^sub>0\\<ge>0 \\<Longrightarrow> \\<Turnstile>\\<^sub>t {vars n in n=n\\<^sub>0} sqr_prog' {vars n a in n=n\\<^sub>0 \\<and> a=n\\<^sub>0\\<^sup>2}\"\n  apply (rewrite annot_tinvar[where R=\"measure (\\<lambda>s. nat (s ''n'' 0 - s ''c'' 0))\" \n        and I=\"vars a b c n in n=n\\<^sub>0 \\<and> a=c\\<^sup>2 \\<and> b = 2*c+1 \\<and> c\\<le>n\\<^sub>0\"])\n  apply vcg_all\n  apply (auto simp: power2_eq_square algebra_simps)\n  done\n\n\n  \nend\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/IMP/IMPAHP_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.9005297894548548, "lm_q1q2_score": 0.7775098710776466}}
{"text": "theory P20 imports Main begin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nprimrec preorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"preorder Tip = Nil\" |\n\"preorder (Node l x r) = x # (preorder l) @ (preorder r)\"\n\nprimrec postorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"postorder Tip = Nil\" |\n\"postorder (Node l x r) = (postorder l) @ (postorder r) @ [x]\"\n\nprimrec postorder_acc :: \"'a tree \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"postorder_acc Tip xs = xs\" |\n\"postorder_acc (Node l x r) xs = postorder_acc l (postorder_acc r (x # xs))\"\n\nlemma \"postorder_acc t xs = (postorder t) @ xs\"\n  apply (induct t arbitrary: xs)\n   apply auto\n  done\n\nprimrec foldl_tree :: \"('b => 'a => 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a tree \\<Rightarrow> 'b\" where\n\"foldl_tree f b Tip = b\" |\n\"foldl_tree f b (Node l x r) = foldl_tree f (foldl_tree f (f b x) r) l\"\n\nlemma \"\\<forall> a. postorder_acc t a = foldl_tree (\\<lambda> xs x. x # xs) a t\"\n  apply (induct t)\n   apply auto\n  done\n\nprimrec tree_sum :: \"nat tree \\<Rightarrow> nat\" where\n\"tree_sum Tip = 0\" |\n\"tree_sum (Node l x r) = x + (tree_sum l) + (tree_sum r)\"\n\nprimrec list_sum :: \"nat list \\<Rightarrow> nat\" where\n\"list_sum Nil = 0\" |\n\"list_sum (x # xs) = x + list_sum xs\"\n\nlemma partition_sum: \"list_sum (xs @ ys) = list_sum xs + list_sum ys\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"tree_sum t = list_sum (preorder t)\"\n  apply (induct t)\n   apply (auto simp add: partition_sum)\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P20.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8633916152464016, "lm_q1q2_score": 0.7775098666138242}}
{"text": "(*  Authors:    Christophe Tabacznyj, Lawrence C. Paulson, Amine Chaieb,\n                Thomas M. Rasmussen, Jeremy Avigad, Tobias Nipkow\n\n\nThis file deals with the functions gcd and lcm.  Definitions and\nlemmas are proved uniformly for the natural numbers and integers.\n\nThis file combines and revises a number of prior developments.\n\nThe original theories \"GCD\" and \"Primes\" were by Christophe Tabacznyj\nand Lawrence C. Paulson, based on @{cite davenport92}. They introduced\ngcd, lcm, and prime for the natural numbers.\n\nThe original theory \"IntPrimes\" was by Thomas M. Rasmussen, and\nextended gcd, lcm, primes to the integers. Amine Chaieb provided\nanother extension of the notions to the integers, and added a number\nof results to \"Primes\" and \"GCD\". IntPrimes also defined and developed\nthe congruence relations on the integers. The notion was extended to\nthe natural numbers by Chaieb.\n\nJeremy Avigad combined all of these, made everything uniform for the\nnatural numbers and the integers, and added a number of new theorems.\n\nTobias Nipkow cleaned up a lot.\n*)\n\n\nsection {* Greatest common divisor and least common multiple *}\n\ntheory GCD\nimports Fact\nbegin\n\ndeclare One_nat_def [simp del]\n\nsubsection {* GCD and LCM definitions *}\n\nclass gcd = zero + one + dvd +\n  fixes gcd :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n    and lcm :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nbegin\n\nabbreviation\n  coprime :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  \"coprime x y == (gcd x y = 1)\"\n\nend\n\nclass semiring_gcd = comm_semiring_1 + gcd +\n  assumes gcd_dvd1 [iff]: \"gcd a b dvd a\"\n\t\tand gcd_dvd2 [iff]: \"gcd a b dvd b\"\n\t\tand gcd_greatest: \"c dvd a \\<Longrightarrow> c dvd b \\<Longrightarrow> c dvd gcd a b\" \n\nclass ring_gcd = comm_ring_1 + semiring_gcd\n\ninstantiation nat :: gcd\nbegin\n\nfun\n  gcd_nat  :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd_nat x y =\n   (if y = 0 then x else gcd y (x mod y))\"\n\ndefinition\n  lcm_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"lcm_nat x y = x * y div (gcd x y)\"\n\ninstance proof qed\n\nend\n\ninstantiation int :: gcd\nbegin\n\ndefinition\n  gcd_int  :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\nwhere\n  \"gcd_int x y = int (gcd (nat (abs x)) (nat (abs y)))\"\n\ndefinition\n  lcm_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\nwhere\n  \"lcm_int x y = int (lcm (nat (abs x)) (nat (abs y)))\"\n\ninstance proof qed\n\nend\n\n\nsubsection {* Transfer setup *}\n\nlemma transfer_nat_int_gcd:\n  \"(x::int) >= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> gcd (nat x) (nat y) = nat (gcd x y)\"\n  \"(x::int) >= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> lcm (nat x) (nat y) = nat (lcm x y)\"\n  unfolding gcd_int_def lcm_int_def\n  by auto\n\nlemma transfer_nat_int_gcd_closures:\n  \"x >= (0::int) \\<Longrightarrow> y >= 0 \\<Longrightarrow> gcd x y >= 0\"\n  \"x >= (0::int) \\<Longrightarrow> y >= 0 \\<Longrightarrow> lcm x y >= 0\"\n  by (auto simp add: gcd_int_def lcm_int_def)\n\ndeclare transfer_morphism_nat_int[transfer add return:\n    transfer_nat_int_gcd transfer_nat_int_gcd_closures]\n\nlemma transfer_int_nat_gcd:\n  \"gcd (int x) (int y) = int (gcd x y)\"\n  \"lcm (int x) (int y) = int (lcm x y)\"\n  by (unfold gcd_int_def lcm_int_def, auto)\n\nlemma transfer_int_nat_gcd_closures:\n  \"is_nat x \\<Longrightarrow> is_nat y \\<Longrightarrow> gcd x y >= 0\"\n  \"is_nat x \\<Longrightarrow> is_nat y \\<Longrightarrow> lcm x y >= 0\"\n  by (auto simp add: gcd_int_def lcm_int_def)\n\ndeclare transfer_morphism_int_nat[transfer add return:\n    transfer_int_nat_gcd transfer_int_nat_gcd_closures]\n\n\nsubsection {* GCD properties *}\n\n(* was gcd_induct *)\nlemma gcd_nat_induct:\n  fixes m n :: nat\n  assumes \"\\<And>m. P m 0\"\n    and \"\\<And>m n. 0 < n \\<Longrightarrow> P n (m mod n) \\<Longrightarrow> P m n\"\n  shows \"P m n\"\n  apply (rule gcd_nat.induct)\n  apply (case_tac \"y = 0\")\n  using assms apply simp_all\ndone\n\n(* specific to int *)\n\nlemma gcd_neg1_int [simp]: \"gcd (-x::int) y = gcd x y\"\n  by (simp add: gcd_int_def)\n\nlemma gcd_neg2_int [simp]: \"gcd (x::int) (-y) = gcd x y\"\n  by (simp add: gcd_int_def)\n\nlemma gcd_neg_numeral_1_int [simp]:\n  \"gcd (- numeral n :: int) x = gcd (numeral n) x\"\n  by (fact gcd_neg1_int)\n\nlemma gcd_neg_numeral_2_int [simp]:\n  \"gcd x (- numeral n :: int) = gcd x (numeral n)\"\n  by (fact gcd_neg2_int)\n\nlemma abs_gcd_int[simp]: \"abs(gcd (x::int) y) = gcd x y\"\nby(simp add: gcd_int_def)\n\nlemma gcd_abs_int: \"gcd (x::int) y = gcd (abs x) (abs y)\"\nby (simp add: gcd_int_def)\n\nlemma gcd_abs1_int[simp]: \"gcd (abs x) (y::int) = gcd x y\"\nby (metis abs_idempotent gcd_abs_int)\n\nlemma gcd_abs2_int[simp]: \"gcd x (abs y::int) = gcd x y\"\nby (metis abs_idempotent gcd_abs_int)\n\nlemma gcd_cases_int:\n  fixes x :: int and y\n  assumes \"x >= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> P (gcd x y)\"\n      and \"x >= 0 \\<Longrightarrow> y <= 0 \\<Longrightarrow> P (gcd x (-y))\"\n      and \"x <= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> P (gcd (-x) y)\"\n      and \"x <= 0 \\<Longrightarrow> y <= 0 \\<Longrightarrow> P (gcd (-x) (-y))\"\n  shows \"P (gcd x y)\"\nby (insert assms, auto, arith)\n\nlemma gcd_ge_0_int [simp]: \"gcd (x::int) y >= 0\"\n  by (simp add: gcd_int_def)\n\nlemma lcm_neg1_int: \"lcm (-x::int) y = lcm x y\"\n  by (simp add: lcm_int_def)\n\nlemma lcm_neg2_int: \"lcm (x::int) (-y) = lcm x y\"\n  by (simp add: lcm_int_def)\n\nlemma lcm_abs_int: \"lcm (x::int) y = lcm (abs x) (abs y)\"\n  by (simp add: lcm_int_def)\n\nlemma abs_lcm_int [simp]: \"abs (lcm i j::int) = lcm i j\"\nby(simp add:lcm_int_def)\n\nlemma lcm_abs1_int[simp]: \"lcm (abs x) (y::int) = lcm x y\"\nby (metis abs_idempotent lcm_int_def)\n\nlemma lcm_abs2_int[simp]: \"lcm x (abs y::int) = lcm x y\"\nby (metis abs_idempotent lcm_int_def)\n\nlemma lcm_cases_int:\n  fixes x :: int and y\n  assumes \"x >= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> P (lcm x y)\"\n      and \"x >= 0 \\<Longrightarrow> y <= 0 \\<Longrightarrow> P (lcm x (-y))\"\n      and \"x <= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> P (lcm (-x) y)\"\n      and \"x <= 0 \\<Longrightarrow> y <= 0 \\<Longrightarrow> P (lcm (-x) (-y))\"\n  shows \"P (lcm x y)\"\n  using assms by (auto simp add: lcm_neg1_int lcm_neg2_int) arith\n\nlemma lcm_ge_0_int [simp]: \"lcm (x::int) y >= 0\"\n  by (simp add: lcm_int_def)\n\n(* was gcd_0, etc. *)\nlemma gcd_0_nat: \"gcd (x::nat) 0 = x\"\n  by simp\n\n(* was igcd_0, etc. *)\nlemma gcd_0_int [simp]: \"gcd (x::int) 0 = abs x\"\n  by (unfold gcd_int_def, auto)\n\nlemma gcd_0_left_nat: \"gcd 0 (x::nat) = x\"\n  by simp\n\nlemma gcd_0_left_int [simp]: \"gcd 0 (x::int) = abs x\"\n  by (unfold gcd_int_def, auto)\n\nlemma gcd_red_nat: \"gcd (x::nat) y = gcd y (x mod y)\"\n  by (case_tac \"y = 0\", auto)\n\n(* weaker, but useful for the simplifier *)\n\nlemma gcd_non_0_nat: \"y ~= (0::nat) \\<Longrightarrow> gcd (x::nat) y = gcd y (x mod y)\"\n  by simp\n\nlemma gcd_1_nat [simp]: \"gcd (m::nat) 1 = 1\"\n  by simp\n\nlemma gcd_Suc_0 [simp]: \"gcd (m::nat) (Suc 0) = Suc 0\"\n  by (simp add: One_nat_def)\n\nlemma gcd_1_int [simp]: \"gcd (m::int) 1 = 1\"\n  by (simp add: gcd_int_def)\n\nlemma gcd_idem_nat: \"gcd (x::nat) x = x\"\nby simp\n\nlemma gcd_idem_int: \"gcd (x::int) x = abs x\"\nby (auto simp add: gcd_int_def)\n\ndeclare gcd_nat.simps [simp del]\n\ntext {*\n  \\medskip @{term \"gcd m n\"} divides @{text m} and @{text n}.  The\n  conjunctions don't seem provable separately.\n*}\n\ninstance nat :: semiring_gcd\nproof\n  fix m n :: nat\n  show \"gcd m n dvd m\" and \"gcd m n dvd n\"\n  proof (induct m n rule: gcd_nat_induct)\n    fix m n :: nat\n    assume \"gcd n (m mod n) dvd m mod n\" and \"gcd n (m mod n) dvd n\"\n    then have \"gcd n (m mod n) dvd m\"\n      by (rule dvd_mod_imp_dvd)\n    moreover assume \"0 < n\"\n    ultimately show \"gcd m n dvd m\"\n      by (simp add: gcd_non_0_nat)\n  qed (simp_all add: gcd_0_nat gcd_non_0_nat)\nnext\n  fix m n k :: nat\n  assume \"k dvd m\" and \"k dvd n\"\n  then show \"k dvd gcd m n\"\n    by (induct m n rule: gcd_nat_induct) (simp_all add: gcd_non_0_nat dvd_mod gcd_0_nat)\nqed\n  \ninstance int :: ring_gcd\n  by intro_classes (simp_all add: dvd_int_unfold_dvd_nat gcd_int_def gcd_greatest)\n  \nlemma dvd_gcd_D1_nat: \"k dvd gcd m n \\<Longrightarrow> (k::nat) dvd m\"\n  by (metis gcd_dvd1 dvd_trans)\n\nlemma dvd_gcd_D2_nat: \"k dvd gcd m n \\<Longrightarrow> (k::nat) dvd n\"\n  by (metis gcd_dvd2 dvd_trans)\n\nlemma dvd_gcd_D1_int: \"i dvd gcd m n \\<Longrightarrow> (i::int) dvd m\"\n  by (metis gcd_dvd1 dvd_trans)\n\nlemma dvd_gcd_D2_int: \"i dvd gcd m n \\<Longrightarrow> (i::int) dvd n\"\n  by (metis gcd_dvd2 dvd_trans)\n\nlemma gcd_le1_nat [simp]: \"a \\<noteq> 0 \\<Longrightarrow> gcd (a::nat) b \\<le> a\"\n  by (rule dvd_imp_le, auto)\n\nlemma gcd_le2_nat [simp]: \"b \\<noteq> 0 \\<Longrightarrow> gcd (a::nat) b \\<le> b\"\n  by (rule dvd_imp_le, auto)\n\nlemma gcd_le1_int [simp]: \"a > 0 \\<Longrightarrow> gcd (a::int) b \\<le> a\"\n  by (rule zdvd_imp_le, auto)\n\nlemma gcd_le2_int [simp]: \"b > 0 \\<Longrightarrow> gcd (a::int) b \\<le> b\"\n  by (rule zdvd_imp_le, auto)\n\nlemma gcd_greatest_iff_nat [iff]: \"(k dvd gcd (m::nat) n) =\n    (k dvd m & k dvd n)\"\n  by (blast intro!: gcd_greatest intro: dvd_trans)\n\nlemma gcd_greatest_iff_int: \"((k::int) dvd gcd m n) = (k dvd m & k dvd n)\"\n  by (blast intro!: gcd_greatest intro: dvd_trans)\n\nlemma gcd_zero_nat [simp]: \"(gcd (m::nat) n = 0) = (m = 0 & n = 0)\"\n  by (simp only: dvd_0_left_iff [symmetric] gcd_greatest_iff_nat)\n\nlemma gcd_zero_int [simp]: \"(gcd (m::int) n = 0) = (m = 0 & n = 0)\"\n  by (auto simp add: gcd_int_def)\n\nlemma gcd_pos_nat [simp]: \"(gcd (m::nat) n > 0) = (m ~= 0 | n ~= 0)\"\n  by (insert gcd_zero_nat [of m n], arith)\n\nlemma gcd_pos_int [simp]: \"(gcd (m::int) n > 0) = (m ~= 0 | n ~= 0)\"\n  by (insert gcd_zero_int [of m n], insert gcd_ge_0_int [of m n], arith)\n\nlemma gcd_unique_nat: \"(d::nat) dvd a \\<and> d dvd b \\<and>\n    (\\<forall>e. e dvd a \\<and> e dvd b \\<longrightarrow> e dvd d) \\<longleftrightarrow> d = gcd a b\"\n  apply auto\n  apply (rule dvd_antisym)\n  apply (erule (1) gcd_greatest)\n  apply auto\ndone\n\nlemma gcd_unique_int: \"d >= 0 & (d::int) dvd a \\<and> d dvd b \\<and>\n    (\\<forall>e. e dvd a \\<and> e dvd b \\<longrightarrow> e dvd d) \\<longleftrightarrow> d = gcd a b\"\napply (case_tac \"d = 0\")\n apply simp\napply (rule iffI)\n apply (rule zdvd_antisym_nonneg)\n apply (auto intro: gcd_greatest)\ndone\n\ninterpretation gcd_nat: abel_semigroup \"gcd :: nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  + gcd_nat: semilattice_neutr_order \"gcd :: nat \\<Rightarrow> nat \\<Rightarrow> nat\" 0 \"op dvd\" \"(\\<lambda>m n. m dvd n \\<and> \\<not> n dvd m)\"\napply default\napply (auto intro: dvd_antisym dvd_trans)[4]\napply (metis dvd.dual_order.refl gcd_unique_nat)\napply (auto intro: dvdI elim: dvdE)\ndone\n\ninterpretation gcd_int: abel_semigroup \"gcd :: int \\<Rightarrow> int \\<Rightarrow> int\"\nproof\nqed (simp_all add: gcd_int_def gcd_nat.assoc gcd_nat.commute gcd_nat.left_commute)\n\nlemmas gcd_assoc_nat = gcd_nat.assoc\nlemmas gcd_commute_nat = gcd_nat.commute\nlemmas gcd_left_commute_nat = gcd_nat.left_commute\nlemmas gcd_assoc_int = gcd_int.assoc\nlemmas gcd_commute_int = gcd_int.commute\nlemmas gcd_left_commute_int = gcd_int.left_commute\n\nlemmas gcd_ac_nat = gcd_assoc_nat gcd_commute_nat gcd_left_commute_nat\n\nlemmas gcd_ac_int = gcd_assoc_int gcd_commute_int gcd_left_commute_int\n\nlemma gcd_proj1_if_dvd_nat [simp]: \"(x::nat) dvd y \\<Longrightarrow> gcd x y = x\"\n  by (fact gcd_nat.absorb1)\n\nlemma gcd_proj2_if_dvd_nat [simp]: \"(y::nat) dvd x \\<Longrightarrow> gcd x y = y\"\n  by (fact gcd_nat.absorb2)\n\nlemma gcd_proj1_if_dvd_int [simp]: \"x dvd y \\<Longrightarrow> gcd (x::int) y = abs x\"\n  by (metis abs_dvd_iff gcd_0_left_int gcd_abs_int gcd_unique_int)\n\nlemma gcd_proj2_if_dvd_int [simp]: \"y dvd x \\<Longrightarrow> gcd (x::int) y = abs y\"\n  by (metis gcd_proj1_if_dvd_int gcd_commute_int)\n\ntext {*\n  \\medskip Multiplication laws\n*}\n\nlemma gcd_mult_distrib_nat: \"(k::nat) * gcd m n = gcd (k * m) (k * n)\"\n    -- {* @{cite \\<open>page 27\\<close> davenport92} *}\n  apply (induct m n rule: gcd_nat_induct)\n  apply simp\n  apply (case_tac \"k = 0\")\n  apply (simp_all add: gcd_non_0_nat)\ndone\n\nlemma gcd_mult_distrib_int: \"abs (k::int) * gcd m n = gcd (k * m) (k * n)\"\n  apply (subst (1 2) gcd_abs_int)\n  apply (subst (1 2) abs_mult)\n  apply (rule gcd_mult_distrib_nat [transferred])\n  apply auto\ndone\n\nlemma coprime_dvd_mult_nat: \"coprime (k::nat) n \\<Longrightarrow> k dvd m * n \\<Longrightarrow> k dvd m\"\n  apply (insert gcd_mult_distrib_nat [of m k n])\n  apply simp\n  apply (erule_tac t = m in ssubst)\n  apply simp\n  done\n\nlemma coprime_dvd_mult_int:\n  \"coprime (k::int) n \\<Longrightarrow> k dvd m * n \\<Longrightarrow> k dvd m\"\napply (subst abs_dvd_iff [symmetric])\napply (subst dvd_abs_iff [symmetric])\napply (subst (asm) gcd_abs_int)\napply (rule coprime_dvd_mult_nat [transferred])\n    prefer 4 apply assumption\n   apply auto\napply (subst abs_mult [symmetric], auto)\ndone\n\nlemma coprime_dvd_mult_iff_nat: \"coprime (k::nat) n \\<Longrightarrow>\n    (k dvd m * n) = (k dvd m)\"\n  by (auto intro: coprime_dvd_mult_nat)\n\nlemma coprime_dvd_mult_iff_int: \"coprime (k::int) n \\<Longrightarrow>\n    (k dvd m * n) = (k dvd m)\"\n  by (auto intro: coprime_dvd_mult_int)\n\nlemma gcd_mult_cancel_nat: \"coprime k n \\<Longrightarrow> gcd ((k::nat) * m) n = gcd m n\"\n  apply (rule dvd_antisym)\n  apply (rule gcd_greatest)\n  apply (rule_tac n = k in coprime_dvd_mult_nat)\n  apply (simp add: gcd_assoc_nat)\n  apply (simp add: gcd_commute_nat)\n  apply (simp_all add: mult.commute)\ndone\n\nlemma gcd_mult_cancel_int:\n  \"coprime (k::int) n \\<Longrightarrow> gcd (k * m) n = gcd m n\"\napply (subst (1 2) gcd_abs_int)\napply (subst abs_mult)\napply (rule gcd_mult_cancel_nat [transferred], auto)\ndone\n\nlemma coprime_crossproduct_nat:\n  fixes a b c d :: nat\n  assumes \"coprime a d\" and \"coprime b c\"\n  shows \"a * c = b * d \\<longleftrightarrow> a = b \\<and> c = d\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs then show ?lhs by simp\nnext\n  assume ?lhs\n  from `?lhs` have \"a dvd b * d\" by (auto intro: dvdI dest: sym)\n  with `coprime a d` have \"a dvd b\" by (simp add: coprime_dvd_mult_iff_nat)\n  from `?lhs` have \"b dvd a * c\" by (auto intro: dvdI dest: sym)\n  with `coprime b c` have \"b dvd a\" by (simp add: coprime_dvd_mult_iff_nat)\n  from `?lhs` have \"c dvd d * b\" by (auto intro: dvdI dest: sym simp add: mult.commute)\n  with `coprime b c` have \"c dvd d\" by (simp add: coprime_dvd_mult_iff_nat gcd_commute_nat)\n  from `?lhs` have \"d dvd c * a\" by (auto intro: dvdI dest: sym simp add: mult.commute)\n  with `coprime a d` have \"d dvd c\" by (simp add: coprime_dvd_mult_iff_nat gcd_commute_nat)\n  from `a dvd b` `b dvd a` have \"a = b\" by (rule Nat.dvd.antisym)\n  moreover from `c dvd d` `d dvd c` have \"c = d\" by (rule Nat.dvd.antisym)\n  ultimately show ?rhs ..\nqed\n\nlemma coprime_crossproduct_int:\n  fixes a b c d :: int\n  assumes \"coprime a d\" and \"coprime b c\"\n  shows \"\\<bar>a\\<bar> * \\<bar>c\\<bar> = \\<bar>b\\<bar> * \\<bar>d\\<bar> \\<longleftrightarrow> \\<bar>a\\<bar> = \\<bar>b\\<bar> \\<and> \\<bar>c\\<bar> = \\<bar>d\\<bar>\"\n  using assms by (intro coprime_crossproduct_nat [transferred]) auto\n\ntext {* \\medskip Addition laws *}\n\nlemma gcd_add1_nat [simp]: \"gcd ((m::nat) + n) n = gcd m n\"\n  apply (case_tac \"n = 0\")\n  apply (simp_all add: gcd_non_0_nat)\ndone\n\nlemma gcd_add2_nat [simp]: \"gcd (m::nat) (m + n) = gcd m n\"\n  apply (subst (1 2) gcd_commute_nat)\n  apply (subst add.commute)\n  apply simp\ndone\n\n(* to do: add the other variations? *)\n\nlemma gcd_diff1_nat: \"(m::nat) >= n \\<Longrightarrow> gcd (m - n) n = gcd m n\"\n  by (subst gcd_add1_nat [symmetric], auto)\n\nlemma gcd_diff2_nat: \"(n::nat) >= m \\<Longrightarrow> gcd (n - m) n = gcd m n\"\n  apply (subst gcd_commute_nat)\n  apply (subst gcd_diff1_nat [symmetric])\n  apply auto\n  apply (subst gcd_commute_nat)\n  apply (subst gcd_diff1_nat)\n  apply assumption\n  apply (rule gcd_commute_nat)\ndone\n\nlemma gcd_non_0_int: \"(y::int) > 0 \\<Longrightarrow> gcd x y = gcd y (x mod y)\"\n  apply (frule_tac b = y and a = x in pos_mod_sign)\n  apply (simp del: pos_mod_sign add: gcd_int_def abs_if nat_mod_distrib)\n  apply (auto simp add: gcd_non_0_nat nat_mod_distrib [symmetric]\n    zmod_zminus1_eq_if)\n  apply (frule_tac a = x in pos_mod_bound)\n  apply (subst (1 2) gcd_commute_nat)\n  apply (simp del: pos_mod_bound add: nat_diff_distrib gcd_diff2_nat\n    nat_le_eq_zle)\ndone\n\nlemma gcd_red_int: \"gcd (x::int) y = gcd y (x mod y)\"\n  apply (case_tac \"y = 0\")\n  apply force\n  apply (case_tac \"y > 0\")\n  apply (subst gcd_non_0_int, auto)\n  apply (insert gcd_non_0_int [of \"-y\" \"-x\"])\n  apply auto\ndone\n\nlemma gcd_add1_int [simp]: \"gcd ((m::int) + n) n = gcd m n\"\nby (metis gcd_red_int mod_add_self1 add.commute)\n\nlemma gcd_add2_int [simp]: \"gcd m ((m::int) + n) = gcd m n\"\nby (metis gcd_add1_int gcd_commute_int add.commute)\n\nlemma gcd_add_mult_nat: \"gcd (m::nat) (k * m + n) = gcd m n\"\nby (metis mod_mult_self3 gcd_commute_nat gcd_red_nat)\n\nlemma gcd_add_mult_int: \"gcd (m::int) (k * m + n) = gcd m n\"\nby (metis gcd_commute_int gcd_red_int mod_mult_self1 add.commute)\n\n\n(* to do: differences, and all variations of addition rules\n    as simplification rules for nat and int *)\n\n(* FIXME remove iff *)\nlemma gcd_dvd_prod_nat [iff]: \"gcd (m::nat) n dvd k * n\"\n  using mult_dvd_mono [of 1] by auto\n\n(* to do: add the three variations of these, and for ints? *)\n\nlemma finite_divisors_nat[simp]:\n  assumes \"(m::nat) ~= 0\" shows \"finite{d. d dvd m}\"\nproof-\n  have \"finite{d. d <= m}\" by(blast intro: bounded_nat_set_is_finite)\n  from finite_subset[OF _ this] show ?thesis using assms\n    by(bestsimp intro!:dvd_imp_le)\nqed\n\nlemma finite_divisors_int[simp]:\n  assumes \"(i::int) ~= 0\" shows \"finite{d. d dvd i}\"\nproof-\n  have \"{d. abs d <= abs i} = {- abs i .. abs i}\" by(auto simp:abs_if)\n  hence \"finite{d. abs d <= abs i}\" by simp\n  from finite_subset[OF _ this] show ?thesis using assms\n    by(bestsimp intro!:dvd_imp_le_int)\nqed\n\nlemma Max_divisors_self_nat[simp]: \"n\\<noteq>0 \\<Longrightarrow> Max{d::nat. d dvd n} = n\"\napply(rule antisym)\n apply (fastforce intro: Max_le_iff[THEN iffD2] simp: dvd_imp_le)\napply simp\ndone\n\nlemma Max_divisors_self_int[simp]: \"n\\<noteq>0 \\<Longrightarrow> Max{d::int. d dvd n} = abs n\"\napply(rule antisym)\n apply(rule Max_le_iff [THEN iffD2])\n  apply (auto intro: abs_le_D1 dvd_imp_le_int)\ndone\n\nlemma gcd_is_Max_divisors_nat:\n  \"m ~= 0 \\<Longrightarrow> n ~= 0 \\<Longrightarrow> gcd (m::nat) n = (Max {d. d dvd m & d dvd n})\"\napply(rule Max_eqI[THEN sym])\n  apply (metis finite_Collect_conjI finite_divisors_nat)\n apply simp\n apply(metis Suc_diff_1 Suc_neq_Zero dvd_imp_le gcd_greatest_iff_nat gcd_pos_nat)\napply simp\ndone\n\nlemma gcd_is_Max_divisors_int:\n  \"m ~= 0 ==> n ~= 0 ==> gcd (m::int) n = (Max {d. d dvd m & d dvd n})\"\napply(rule Max_eqI[THEN sym])\n  apply (metis finite_Collect_conjI finite_divisors_int)\n apply simp\n apply (metis gcd_greatest_iff_int gcd_pos_int zdvd_imp_le)\napply simp\ndone\n\nlemma gcd_code_int [code]:\n  \"gcd k l = \\<bar>if l = (0::int) then k else gcd l (\\<bar>k\\<bar> mod \\<bar>l\\<bar>)\\<bar>\"\n  by (simp add: gcd_int_def nat_mod_distrib gcd_non_0_nat)\n\n\nsubsection {* Coprimality *}\n\nlemma div_gcd_coprime_nat:\n  assumes nz: \"(a::nat) \\<noteq> 0 \\<or> b \\<noteq> 0\"\n  shows \"coprime (a div gcd a b) (b div gcd a b)\"\nproof -\n  let ?g = \"gcd a b\"\n  let ?a' = \"a div ?g\"\n  let ?b' = \"b div ?g\"\n  let ?g' = \"gcd ?a' ?b'\"\n  have dvdg: \"?g dvd a\" \"?g dvd b\" by simp_all\n  have dvdg': \"?g' dvd ?a'\" \"?g' dvd ?b'\" by simp_all\n  from dvdg dvdg' obtain ka kb ka' kb' where\n      kab: \"a = ?g * ka\" \"b = ?g * kb\" \"?a' = ?g' * ka'\" \"?b' = ?g' * kb'\"\n    unfolding dvd_def by blast\n  from this [symmetric] have \"?g * ?a' = (?g * ?g') * ka'\" \"?g * ?b' = (?g * ?g') * kb'\"\n    by (simp_all add: mult.assoc mult.left_commute [of \"gcd a b\"])\n  then have dvdgg':\"?g * ?g' dvd a\" \"?g* ?g' dvd b\"\n    by (auto simp add: dvd_mult_div_cancel [OF dvdg(1)]\n      dvd_mult_div_cancel [OF dvdg(2)] dvd_def)\n  have \"?g \\<noteq> 0\" using nz by simp\n  then have gp: \"?g > 0\" by arith\n  from gcd_greatest [OF dvdgg'] have \"?g * ?g' dvd ?g\" .\n  with dvd_mult_cancel1 [OF gp] show \"?g' = 1\" by simp\nqed\n\nlemma div_gcd_coprime_int:\n  assumes nz: \"(a::int) \\<noteq> 0 \\<or> b \\<noteq> 0\"\n  shows \"coprime (a div gcd a b) (b div gcd a b)\"\napply (subst (1 2 3) gcd_abs_int)\napply (subst (1 2) abs_div)\n  apply simp\n apply simp\napply(subst (1 2) abs_gcd_int)\napply (rule div_gcd_coprime_nat [transferred])\nusing nz apply (auto simp add: gcd_abs_int [symmetric])\ndone\n\nlemma coprime_nat: \"coprime (a::nat) b \\<longleftrightarrow> (\\<forall>d. d dvd a \\<and> d dvd b \\<longleftrightarrow> d = 1)\"\n  using gcd_unique_nat[of 1 a b, simplified] by auto\n\nlemma coprime_Suc_0_nat:\n    \"coprime (a::nat) b \\<longleftrightarrow> (\\<forall>d. d dvd a \\<and> d dvd b \\<longleftrightarrow> d = Suc 0)\"\n  using coprime_nat by (simp add: One_nat_def)\n\nlemma coprime_int: \"coprime (a::int) b \\<longleftrightarrow>\n    (\\<forall>d. d >= 0 \\<and> d dvd a \\<and> d dvd b \\<longleftrightarrow> d = 1)\"\n  using gcd_unique_int [of 1 a b]\n  apply clarsimp\n  apply (erule subst)\n  apply (rule iffI)\n  apply force\n  apply (drule_tac x = \"abs ?e\" in exI)\n  apply (case_tac \"(?e::int) >= 0\")\n  apply force\n  apply force\ndone\n\nlemma gcd_coprime_nat:\n  assumes z: \"gcd (a::nat) b \\<noteq> 0\" and a: \"a = a' * gcd a b\" and\n    b: \"b = b' * gcd a b\"\n  shows    \"coprime a' b'\"\n\n  apply (subgoal_tac \"a' = a div gcd a b\")\n  apply (erule ssubst)\n  apply (subgoal_tac \"b' = b div gcd a b\")\n  apply (erule ssubst)\n  apply (rule div_gcd_coprime_nat)\n  using z apply force\n  apply (subst (1) b)\n  using z apply force\n  apply (subst (1) a)\n  using z apply force\n  done\n\nlemma gcd_coprime_int:\n  assumes z: \"gcd (a::int) b \\<noteq> 0\" and a: \"a = a' * gcd a b\" and\n    b: \"b = b' * gcd a b\"\n  shows    \"coprime a' b'\"\n\n  apply (subgoal_tac \"a' = a div gcd a b\")\n  apply (erule ssubst)\n  apply (subgoal_tac \"b' = b div gcd a b\")\n  apply (erule ssubst)\n  apply (rule div_gcd_coprime_int)\n  using z apply force\n  apply (subst (1) b)\n  using z apply force\n  apply (subst (1) a)\n  using z apply force\n  done\n\nlemma coprime_mult_nat: assumes da: \"coprime (d::nat) a\" and db: \"coprime d b\"\n    shows \"coprime d (a * b)\"\n  apply (subst gcd_commute_nat)\n  using da apply (subst gcd_mult_cancel_nat)\n  apply (subst gcd_commute_nat, assumption)\n  apply (subst gcd_commute_nat, rule db)\ndone\n\nlemma coprime_mult_int: assumes da: \"coprime (d::int) a\" and db: \"coprime d b\"\n    shows \"coprime d (a * b)\"\n  apply (subst gcd_commute_int)\n  using da apply (subst gcd_mult_cancel_int)\n  apply (subst gcd_commute_int, assumption)\n  apply (subst gcd_commute_int, rule db)\ndone\n\nlemma coprime_lmult_nat:\n  assumes dab: \"coprime (d::nat) (a * b)\" shows \"coprime d a\"\nproof -\n  have \"gcd d a dvd gcd d (a * b)\"\n    by (rule gcd_greatest, auto)\n  with dab show ?thesis\n    by auto\nqed\n\nlemma coprime_lmult_int:\n  assumes \"coprime (d::int) (a * b)\" shows \"coprime d a\"\nproof -\n  have \"gcd d a dvd gcd d (a * b)\"\n    by (rule gcd_greatest, auto)\n  with assms show ?thesis\n    by auto\nqed\n\nlemma coprime_rmult_nat:\n  assumes \"coprime (d::nat) (a * b)\" shows \"coprime d b\"\nproof -\n  have \"gcd d b dvd gcd d (a * b)\"\n    by (rule gcd_greatest, auto intro: dvd_mult)\n  with assms show ?thesis\n    by auto\nqed\n\nlemma coprime_rmult_int:\n  assumes dab: \"coprime (d::int) (a * b)\" shows \"coprime d b\"\nproof -\n  have \"gcd d b dvd gcd d (a * b)\"\n    by (rule gcd_greatest, auto intro: dvd_mult)\n  with dab show ?thesis\n    by auto\nqed\n\nlemma coprime_mul_eq_nat: \"coprime (d::nat) (a * b) \\<longleftrightarrow>\n    coprime d a \\<and>  coprime d b\"\n  using coprime_rmult_nat[of d a b] coprime_lmult_nat[of d a b]\n    coprime_mult_nat[of d a b]\n  by blast\n\nlemma coprime_mul_eq_int: \"coprime (d::int) (a * b) \\<longleftrightarrow>\n    coprime d a \\<and>  coprime d b\"\n  using coprime_rmult_int[of d a b] coprime_lmult_int[of d a b]\n    coprime_mult_int[of d a b]\n  by blast\n\nlemma coprime_power_int:\n  assumes \"0 < n\" shows \"coprime (a :: int) (b ^ n) \\<longleftrightarrow> coprime a b\"\n  using assms\nproof (induct n)\n  case (Suc n) then show ?case\n    by (cases n) (simp_all add: coprime_mul_eq_int)\nqed simp\n\nlemma gcd_coprime_exists_nat:\n    assumes nz: \"gcd (a::nat) b \\<noteq> 0\"\n    shows \"\\<exists>a' b'. a = a' * gcd a b \\<and> b = b' * gcd a b \\<and> coprime a' b'\"\n  apply (rule_tac x = \"a div gcd a b\" in exI)\n  apply (rule_tac x = \"b div gcd a b\" in exI)\n  using nz apply (auto simp add: div_gcd_coprime_nat dvd_div_mult)\ndone\n\nlemma gcd_coprime_exists_int:\n    assumes nz: \"gcd (a::int) b \\<noteq> 0\"\n    shows \"\\<exists>a' b'. a = a' * gcd a b \\<and> b = b' * gcd a b \\<and> coprime a' b'\"\n  apply (rule_tac x = \"a div gcd a b\" in exI)\n  apply (rule_tac x = \"b div gcd a b\" in exI)\n  using nz apply (auto simp add: div_gcd_coprime_int)\ndone\n\nlemma coprime_exp_nat: \"coprime (d::nat) a \\<Longrightarrow> coprime d (a^n)\"\n  by (induct n, simp_all add: coprime_mult_nat)\n\nlemma coprime_exp_int: \"coprime (d::int) a \\<Longrightarrow> coprime d (a^n)\"\n  by (induct n, simp_all add: coprime_mult_int)\n\nlemma coprime_exp2_nat [intro]: \"coprime (a::nat) b \\<Longrightarrow> coprime (a^n) (b^m)\"\n  apply (rule coprime_exp_nat)\n  apply (subst gcd_commute_nat)\n  apply (rule coprime_exp_nat)\n  apply (subst gcd_commute_nat, assumption)\ndone\n\nlemma coprime_exp2_int [intro]: \"coprime (a::int) b \\<Longrightarrow> coprime (a^n) (b^m)\"\n  apply (rule coprime_exp_int)\n  apply (subst gcd_commute_int)\n  apply (rule coprime_exp_int)\n  apply (subst gcd_commute_int, assumption)\ndone\n\nlemma gcd_exp_nat: \"gcd ((a::nat)^n) (b^n) = (gcd a b)^n\"\nproof (cases)\n  assume \"a = 0 & b = 0\"\n  thus ?thesis by simp\n  next assume \"~(a = 0 & b = 0)\"\n  hence \"coprime ((a div gcd a b)^n) ((b div gcd a b)^n)\"\n    by (auto simp:div_gcd_coprime_nat)\n  hence \"gcd ((a div gcd a b)^n * (gcd a b)^n)\n      ((b div gcd a b)^n * (gcd a b)^n) = (gcd a b)^n\"\n    apply (subst (1 2) mult.commute)\n    apply (subst gcd_mult_distrib_nat [symmetric])\n    apply simp\n    done\n  also have \"(a div gcd a b)^n * (gcd a b)^n = a^n\"\n    apply (subst div_power)\n    apply auto\n    apply (rule dvd_div_mult_self)\n    apply (rule dvd_power_same)\n    apply auto\n    done\n  also have \"(b div gcd a b)^n * (gcd a b)^n = b^n\"\n    apply (subst div_power)\n    apply auto\n    apply (rule dvd_div_mult_self)\n    apply (rule dvd_power_same)\n    apply auto\n    done\n  finally show ?thesis .\nqed\n\nlemma gcd_exp_int: \"gcd ((a::int)^n) (b^n) = (gcd a b)^n\"\n  apply (subst (1 2) gcd_abs_int)\n  apply (subst (1 2) power_abs)\n  apply (rule gcd_exp_nat [where n = n, transferred])\n  apply auto\ndone\n\nlemma division_decomp_nat: assumes dc: \"(a::nat) dvd b * c\"\n  shows \"\\<exists>b' c'. a = b' * c' \\<and> b' dvd b \\<and> c' dvd c\"\nproof-\n  let ?g = \"gcd a b\"\n  {assume \"?g = 0\" with dc have ?thesis by auto}\n  moreover\n  {assume z: \"?g \\<noteq> 0\"\n    from gcd_coprime_exists_nat[OF z]\n    obtain a' b' where ab': \"a = a' * ?g\" \"b = b' * ?g\" \"coprime a' b'\"\n      by blast\n    have thb: \"?g dvd b\" by auto\n    from ab'(1) have \"a' dvd a\"  unfolding dvd_def by blast\n    with dc have th0: \"a' dvd b*c\" using dvd_trans[of a' a \"b*c\"] by simp\n    from dc ab'(1,2) have \"a'*?g dvd (b'*?g) *c\" by auto\n    hence \"?g*a' dvd ?g * (b' * c)\" by (simp add: mult.assoc)\n    with z have th_1: \"a' dvd b' * c\" by auto\n    from coprime_dvd_mult_nat[OF ab'(3)] th_1\n    have thc: \"a' dvd c\" by (subst (asm) mult.commute, blast)\n    from ab' have \"a = ?g*a'\" by algebra\n    with thb thc have ?thesis by blast }\n  ultimately show ?thesis by blast\nqed\n\nlemma division_decomp_int: assumes dc: \"(a::int) dvd b * c\"\n  shows \"\\<exists>b' c'. a = b' * c' \\<and> b' dvd b \\<and> c' dvd c\"\nproof-\n  let ?g = \"gcd a b\"\n  {assume \"?g = 0\" with dc have ?thesis by auto}\n  moreover\n  {assume z: \"?g \\<noteq> 0\"\n    from gcd_coprime_exists_int[OF z]\n    obtain a' b' where ab': \"a = a' * ?g\" \"b = b' * ?g\" \"coprime a' b'\"\n      by blast\n    have thb: \"?g dvd b\" by auto\n    from ab'(1) have \"a' dvd a\"  unfolding dvd_def by blast\n    with dc have th0: \"a' dvd b*c\"\n      using dvd_trans[of a' a \"b*c\"] by simp\n    from dc ab'(1,2) have \"a'*?g dvd (b'*?g) *c\" by auto\n    hence \"?g*a' dvd ?g * (b' * c)\" by (simp add: mult.assoc)\n    with z have th_1: \"a' dvd b' * c\" by auto\n    from coprime_dvd_mult_int[OF ab'(3)] th_1\n    have thc: \"a' dvd c\" by (subst (asm) mult.commute, blast)\n    from ab' have \"a = ?g*a'\" by algebra\n    with thb thc have ?thesis by blast }\n  ultimately show ?thesis by blast\nqed\n\nlemma pow_divides_pow_nat:\n  assumes ab: \"(a::nat) ^ n dvd b ^n\" and n:\"n \\<noteq> 0\"\n  shows \"a dvd b\"\nproof-\n  let ?g = \"gcd a b\"\n  from n obtain m where m: \"n = Suc m\" by (cases n, simp_all)\n  {assume \"?g = 0\" with ab n have ?thesis by auto }\n  moreover\n  {assume z: \"?g \\<noteq> 0\"\n    hence zn: \"?g ^ n \\<noteq> 0\" using n by simp\n    from gcd_coprime_exists_nat[OF z]\n    obtain a' b' where ab': \"a = a' * ?g\" \"b = b' * ?g\" \"coprime a' b'\"\n      by blast\n    from ab have \"(a' * ?g) ^ n dvd (b' * ?g)^n\"\n      by (simp add: ab'(1,2)[symmetric])\n    hence \"?g^n*a'^n dvd ?g^n *b'^n\"\n      by (simp only: power_mult_distrib mult.commute)\n    then have th0: \"a'^n dvd b'^n\"\n      using zn by auto\n    have \"a' dvd a'^n\" by (simp add: m)\n    with th0 have \"a' dvd b'^n\" using dvd_trans[of a' \"a'^n\" \"b'^n\"] by simp\n    hence th1: \"a' dvd b'^m * b'\" by (simp add: m mult.commute)\n    from coprime_dvd_mult_nat[OF coprime_exp_nat [OF ab'(3), of m]] th1\n    have \"a' dvd b'\" by (subst (asm) mult.commute, blast)\n    hence \"a'*?g dvd b'*?g\" by simp\n    with ab'(1,2)  have ?thesis by simp }\n  ultimately show ?thesis by blast\nqed\n\nlemma pow_divides_pow_int:\n  assumes ab: \"(a::int) ^ n dvd b ^n\" and n:\"n \\<noteq> 0\"\n  shows \"a dvd b\"\nproof-\n  let ?g = \"gcd a b\"\n  from n obtain m where m: \"n = Suc m\" by (cases n, simp_all)\n  {assume \"?g = 0\" with ab n have ?thesis by auto }\n  moreover\n  {assume z: \"?g \\<noteq> 0\"\n    hence zn: \"?g ^ n \\<noteq> 0\" using n by simp\n    from gcd_coprime_exists_int[OF z]\n    obtain a' b' where ab': \"a = a' * ?g\" \"b = b' * ?g\" \"coprime a' b'\"\n      by blast\n    from ab have \"(a' * ?g) ^ n dvd (b' * ?g)^n\"\n      by (simp add: ab'(1,2)[symmetric])\n    hence \"?g^n*a'^n dvd ?g^n *b'^n\"\n      by (simp only: power_mult_distrib mult.commute)\n    with zn z n have th0:\"a'^n dvd b'^n\" by auto\n    have \"a' dvd a'^n\" by (simp add: m)\n    with th0 have \"a' dvd b'^n\"\n      using dvd_trans[of a' \"a'^n\" \"b'^n\"] by simp\n    hence th1: \"a' dvd b'^m * b'\" by (simp add: m mult.commute)\n    from coprime_dvd_mult_int[OF coprime_exp_int [OF ab'(3), of m]] th1\n    have \"a' dvd b'\" by (subst (asm) mult.commute, blast)\n    hence \"a'*?g dvd b'*?g\" by simp\n    with ab'(1,2)  have ?thesis by simp }\n  ultimately show ?thesis by blast\nqed\n\nlemma pow_divides_eq_nat [simp]: \"n ~= 0 \\<Longrightarrow> ((a::nat)^n dvd b^n) = (a dvd b)\"\n  by (auto intro: pow_divides_pow_nat dvd_power_same)\n\nlemma pow_divides_eq_int [simp]: \"n ~= 0 \\<Longrightarrow> ((a::int)^n dvd b^n) = (a dvd b)\"\n  by (auto intro: pow_divides_pow_int dvd_power_same)\n\nlemma divides_mult_nat:\n  assumes mr: \"(m::nat) dvd r\" and nr: \"n dvd r\" and mn:\"coprime m n\"\n  shows \"m * n dvd r\"\nproof-\n  from mr nr obtain m' n' where m': \"r = m*m'\" and n': \"r = n*n'\"\n    unfolding dvd_def by blast\n  from mr n' have \"m dvd n'*n\" by (simp add: mult.commute)\n  hence \"m dvd n'\" using coprime_dvd_mult_iff_nat[OF mn] by simp\n  then obtain k where k: \"n' = m*k\" unfolding dvd_def by blast\n  from n' k show ?thesis unfolding dvd_def by auto\nqed\n\nlemma divides_mult_int:\n  assumes mr: \"(m::int) dvd r\" and nr: \"n dvd r\" and mn:\"coprime m n\"\n  shows \"m * n dvd r\"\nproof-\n  from mr nr obtain m' n' where m': \"r = m*m'\" and n': \"r = n*n'\"\n    unfolding dvd_def by blast\n  from mr n' have \"m dvd n'*n\" by (simp add: mult.commute)\n  hence \"m dvd n'\" using coprime_dvd_mult_iff_int[OF mn] by simp\n  then obtain k where k: \"n' = m*k\" unfolding dvd_def by blast\n  from n' k show ?thesis unfolding dvd_def by auto\nqed\n\nlemma coprime_plus_one_nat [simp]: \"coprime ((n::nat) + 1) n\"\n  apply (subgoal_tac \"gcd (n + 1) n dvd (n + 1 - n)\")\n  apply force\n  apply (rule dvd_diff_nat)\n  apply auto\ndone\n\nlemma coprime_Suc_nat [simp]: \"coprime (Suc n) n\"\n  using coprime_plus_one_nat by (simp add: One_nat_def)\n\nlemma coprime_plus_one_int [simp]: \"coprime ((n::int) + 1) n\"\n  apply (subgoal_tac \"gcd (n + 1) n dvd (n + 1 - n)\")\n  apply force\n  apply (rule dvd_diff)\n  apply auto\ndone\n\nlemma coprime_minus_one_nat: \"(n::nat) \\<noteq> 0 \\<Longrightarrow> coprime (n - 1) n\"\n  using coprime_plus_one_nat [of \"n - 1\"]\n    gcd_commute_nat [of \"n - 1\" n] by auto\n\nlemma coprime_minus_one_int: \"coprime ((n::int) - 1) n\"\n  using coprime_plus_one_int [of \"n - 1\"]\n    gcd_commute_int [of \"n - 1\" n] by auto\n\nlemma setprod_coprime_nat [rule_format]:\n    \"(ALL i: A. coprime (f i) (x::nat)) --> coprime (PROD i:A. f i) x\"\n  apply (case_tac \"finite A\")\n  apply (induct set: finite)\n  apply (auto simp add: gcd_mult_cancel_nat)\ndone\n\nlemma setprod_coprime_int [rule_format]:\n    \"(ALL i: A. coprime (f i) (x::int)) --> coprime (PROD i:A. f i) x\"\n  apply (case_tac \"finite A\")\n  apply (induct set: finite)\n  apply (auto simp add: gcd_mult_cancel_int)\ndone\n\nlemma coprime_common_divisor_nat: \"coprime (a::nat) b \\<Longrightarrow> x dvd a \\<Longrightarrow>\n    x dvd b \\<Longrightarrow> x = 1\"\n  apply (subgoal_tac \"x dvd gcd a b\")\n  apply simp\n  apply (erule (1) gcd_greatest)\ndone\n\nlemma coprime_common_divisor_int: \"coprime (a::int) b \\<Longrightarrow> x dvd a \\<Longrightarrow>\n    x dvd b \\<Longrightarrow> abs x = 1\"\n  apply (subgoal_tac \"x dvd gcd a b\")\n  apply simp\n  apply (erule (1) gcd_greatest)\ndone\n\nlemma coprime_divisors_nat: \"(d::int) dvd a \\<Longrightarrow> e dvd b \\<Longrightarrow> coprime a b \\<Longrightarrow>\n    coprime d e\"\n  apply (auto simp add: dvd_def)\n  apply (frule coprime_lmult_int)\n  apply (subst gcd_commute_int)\n  apply (subst (asm) (2) gcd_commute_int)\n  apply (erule coprime_lmult_int)\ndone\n\nlemma invertible_coprime_nat: \"(x::nat) * y mod m = 1 \\<Longrightarrow> coprime x m\"\napply (metis coprime_lmult_nat gcd_1_nat gcd_commute_nat gcd_red_nat)\ndone\n\nlemma invertible_coprime_int: \"(x::int) * y mod m = 1 \\<Longrightarrow> coprime x m\"\napply (metis coprime_lmult_int gcd_1_int gcd_commute_int gcd_red_int)\ndone\n\n\nsubsection {* Bezout's theorem *}\n\n(* Function bezw returns a pair of witnesses to Bezout's theorem --\n   see the theorems that follow the definition. *)\nfun\n  bezw  :: \"nat \\<Rightarrow> nat \\<Rightarrow> int * int\"\nwhere\n  \"bezw x y =\n  (if y = 0 then (1, 0) else\n      (snd (bezw y (x mod y)),\n       fst (bezw y (x mod y)) - snd (bezw y (x mod y)) * int(x div y)))\"\n\nlemma bezw_0 [simp]: \"bezw x 0 = (1, 0)\" by simp\n\nlemma bezw_non_0: \"y > 0 \\<Longrightarrow> bezw x y = (snd (bezw y (x mod y)),\n       fst (bezw y (x mod y)) - snd (bezw y (x mod y)) * int(x div y))\"\n  by simp\n\ndeclare bezw.simps [simp del]\n\nlemma bezw_aux [rule_format]:\n    \"fst (bezw x y) * int x + snd (bezw x y) * int y = int (gcd x y)\"\nproof (induct x y rule: gcd_nat_induct)\n  fix m :: nat\n  show \"fst (bezw m 0) * int m + snd (bezw m 0) * int 0 = int (gcd m 0)\"\n    by auto\n  next fix m :: nat and n\n    assume ngt0: \"n > 0\" and\n      ih: \"fst (bezw n (m mod n)) * int n +\n        snd (bezw n (m mod n)) * int (m mod n) =\n        int (gcd n (m mod n))\"\n    thus \"fst (bezw m n) * int m + snd (bezw m n) * int n = int (gcd m n)\"\n      apply (simp add: bezw_non_0 gcd_non_0_nat)\n      apply (erule subst)\n      apply (simp add: field_simps)\n      apply (subst mod_div_equality [of m n, symmetric])\n      (* applying simp here undoes the last substitution!\n         what is procedure cancel_div_mod? *)\n      apply (simp only: NO_MATCH_def field_simps of_nat_add of_nat_mult)\n      done\nqed\n\nlemma bezout_int:\n  fixes x y\n  shows \"EX u v. u * (x::int) + v * y = gcd x y\"\nproof -\n  have bezout_aux: \"!!x y. x \\<ge> (0::int) \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow>\n      EX u v. u * x + v * y = gcd x y\"\n    apply (rule_tac x = \"fst (bezw (nat x) (nat y))\" in exI)\n    apply (rule_tac x = \"snd (bezw (nat x) (nat y))\" in exI)\n    apply (unfold gcd_int_def)\n    apply simp\n    apply (subst bezw_aux [symmetric])\n    apply auto\n    done\n  have \"(x \\<ge> 0 \\<and> y \\<ge> 0) | (x \\<ge> 0 \\<and> y \\<le> 0) | (x \\<le> 0 \\<and> y \\<ge> 0) |\n      (x \\<le> 0 \\<and> y \\<le> 0)\"\n    by auto\n  moreover have \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> ?thesis\"\n    by (erule (1) bezout_aux)\n  moreover have \"x >= 0 \\<Longrightarrow> y <= 0 \\<Longrightarrow> ?thesis\"\n    apply (insert bezout_aux [of x \"-y\"])\n    apply auto\n    apply (rule_tac x = u in exI)\n    apply (rule_tac x = \"-v\" in exI)\n    apply (subst gcd_neg2_int [symmetric])\n    apply auto\n    done\n  moreover have \"x <= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> ?thesis\"\n    apply (insert bezout_aux [of \"-x\" y])\n    apply auto\n    apply (rule_tac x = \"-u\" in exI)\n    apply (rule_tac x = v in exI)\n    apply (subst gcd_neg1_int [symmetric])\n    apply auto\n    done\n  moreover have \"x <= 0 \\<Longrightarrow> y <= 0 \\<Longrightarrow> ?thesis\"\n    apply (insert bezout_aux [of \"-x\" \"-y\"])\n    apply auto\n    apply (rule_tac x = \"-u\" in exI)\n    apply (rule_tac x = \"-v\" in exI)\n    apply (subst gcd_neg1_int [symmetric])\n    apply (subst gcd_neg2_int [symmetric])\n    apply auto\n    done\n  ultimately show ?thesis by blast\nqed\n\ntext {* versions of Bezout for nat, by Amine Chaieb *}\n\nlemma ind_euclid:\n  assumes c: \" \\<forall>a b. P (a::nat) b \\<longleftrightarrow> P b a\" and z: \"\\<forall>a. P a 0\"\n  and add: \"\\<forall>a b. P a b \\<longrightarrow> P a (a + b)\"\n  shows \"P a b\"\nproof(induct \"a + b\" arbitrary: a b rule: less_induct)\n  case less\n  have \"a = b \\<or> a < b \\<or> b < a\" by arith\n  moreover {assume eq: \"a= b\"\n    from add[rule_format, OF z[rule_format, of a]] have \"P a b\" using eq\n    by simp}\n  moreover\n  {assume lt: \"a < b\"\n    hence \"a + b - a < a + b \\<or> a = 0\" by arith\n    moreover\n    {assume \"a =0\" with z c have \"P a b\" by blast }\n    moreover\n    {assume \"a + b - a < a + b\"\n      also have th0: \"a + b - a = a + (b - a)\" using lt by arith\n      finally have \"a + (b - a) < a + b\" .\n      then have \"P a (a + (b - a))\" by (rule add[rule_format, OF less])\n      then have \"P a b\" by (simp add: th0[symmetric])}\n    ultimately have \"P a b\" by blast}\n  moreover\n  {assume lt: \"a > b\"\n    hence \"b + a - b < a + b \\<or> b = 0\" by arith\n    moreover\n    {assume \"b =0\" with z c have \"P a b\" by blast }\n    moreover\n    {assume \"b + a - b < a + b\"\n      also have th0: \"b + a - b = b + (a - b)\" using lt by arith\n      finally have \"b + (a - b) < a + b\" .\n      then have \"P b (b + (a - b))\" by (rule add[rule_format, OF less])\n      then have \"P b a\" by (simp add: th0[symmetric])\n      hence \"P a b\" using c by blast }\n    ultimately have \"P a b\" by blast}\nultimately  show \"P a b\" by blast\nqed\n\nlemma bezout_lemma_nat:\n  assumes ex: \"\\<exists>(d::nat) x y. d dvd a \\<and> d dvd b \\<and>\n    (a * x = b * y + d \\<or> b * x = a * y + d)\"\n  shows \"\\<exists>d x y. d dvd a \\<and> d dvd a + b \\<and>\n    (a * x = (a + b) * y + d \\<or> (a + b) * x = a * y + d)\"\n  using ex\n  apply clarsimp\n  apply (rule_tac x=\"d\" in exI, simp)\n  apply (case_tac \"a * x = b * y + d\" , simp_all)\n  apply (rule_tac x=\"x + y\" in exI)\n  apply (rule_tac x=\"y\" in exI)\n  apply algebra\n  apply (rule_tac x=\"x\" in exI)\n  apply (rule_tac x=\"x + y\" in exI)\n  apply algebra\ndone\n\nlemma bezout_add_nat: \"\\<exists>(d::nat) x y. d dvd a \\<and> d dvd b \\<and>\n    (a * x = b * y + d \\<or> b * x = a * y + d)\"\n  apply(induct a b rule: ind_euclid)\n  apply blast\n  apply clarify\n  apply (rule_tac x=\"a\" in exI, simp)\n  apply clarsimp\n  apply (rule_tac x=\"d\" in exI)\n  apply (case_tac \"a * x = b * y + d\", simp_all)\n  apply (rule_tac x=\"x+y\" in exI)\n  apply (rule_tac x=\"y\" in exI)\n  apply algebra\n  apply (rule_tac x=\"x\" in exI)\n  apply (rule_tac x=\"x+y\" in exI)\n  apply algebra\ndone\n\nlemma bezout1_nat: \"\\<exists>(d::nat) x y. d dvd a \\<and> d dvd b \\<and>\n    (a * x - b * y = d \\<or> b * x - a * y = d)\"\n  using bezout_add_nat[of a b]\n  apply clarsimp\n  apply (rule_tac x=\"d\" in exI, simp)\n  apply (rule_tac x=\"x\" in exI)\n  apply (rule_tac x=\"y\" in exI)\n  apply auto\ndone\n\nlemma bezout_add_strong_nat: assumes nz: \"a \\<noteq> (0::nat)\"\n  shows \"\\<exists>d x y. d dvd a \\<and> d dvd b \\<and> a * x = b * y + d\"\nproof-\n from nz have ap: \"a > 0\" by simp\n from bezout_add_nat[of a b]\n have \"(\\<exists>d x y. d dvd a \\<and> d dvd b \\<and> a * x = b * y + d) \\<or>\n   (\\<exists>d x y. d dvd a \\<and> d dvd b \\<and> b * x = a * y + d)\" by blast\n moreover\n    {fix d x y assume H: \"d dvd a\" \"d dvd b\" \"a * x = b * y + d\"\n     from H have ?thesis by blast }\n moreover\n {fix d x y assume H: \"d dvd a\" \"d dvd b\" \"b * x = a * y + d\"\n   {assume b0: \"b = 0\" with H  have ?thesis by simp}\n   moreover\n   {assume b: \"b \\<noteq> 0\" hence bp: \"b > 0\" by simp\n     from b dvd_imp_le [OF H(2)] have \"d < b \\<or> d = b\"\n       by auto\n     moreover\n     {assume db: \"d=b\"\n       with nz H have ?thesis apply simp\n         apply (rule exI[where x = b], simp)\n         apply (rule exI[where x = b])\n        by (rule exI[where x = \"a - 1\"], simp add: diff_mult_distrib2)}\n    moreover\n    {assume db: \"d < b\"\n        {assume \"x=0\" hence ?thesis using nz H by simp }\n        moreover\n        {assume x0: \"x \\<noteq> 0\" hence xp: \"x > 0\" by simp\n          from db have \"d \\<le> b - 1\" by simp\n          hence \"d*b \\<le> b*(b - 1)\" by simp\n          with xp mult_mono[of \"1\" \"x\" \"d*b\" \"b*(b - 1)\"]\n          have dble: \"d*b \\<le> x*b*(b - 1)\" using bp by simp\n          from H (3) have \"d + (b - 1) * (b*x) = d + (b - 1) * (a*y + d)\"\n            by simp\n          hence \"d + (b - 1) * a * y + (b - 1) * d = d + (b - 1) * b * x\"\n            by (simp only: mult.assoc distrib_left)\n          hence \"a * ((b - 1) * y) + d * (b - 1 + 1) = d + x*b*(b - 1)\"\n            by algebra\n          hence \"a * ((b - 1) * y) = d + x*b*(b - 1) - d*b\" using bp by simp\n          hence \"a * ((b - 1) * y) = d + (x*b*(b - 1) - d*b)\"\n            by (simp only: diff_add_assoc[OF dble, of d, symmetric])\n          hence \"a * ((b - 1) * y) = b*(x*(b - 1) - d) + d\"\n            by (simp only: diff_mult_distrib2 ac_simps)\n          hence ?thesis using H(1,2)\n            apply -\n            apply (rule exI[where x=d], simp)\n            apply (rule exI[where x=\"(b - 1) * y\"])\n            by (rule exI[where x=\"x*(b - 1) - d\"], simp)}\n        ultimately have ?thesis by blast}\n    ultimately have ?thesis by blast}\n  ultimately have ?thesis by blast}\n ultimately show ?thesis by blast\nqed\n\nlemma bezout_nat: assumes a: \"(a::nat) \\<noteq> 0\"\n  shows \"\\<exists>x y. a * x = b * y + gcd a b\"\nproof-\n  let ?g = \"gcd a b\"\n  from bezout_add_strong_nat[OF a, of b]\n  obtain d x y where d: \"d dvd a\" \"d dvd b\" \"a * x = b * y + d\" by blast\n  from d(1,2) have \"d dvd ?g\" by simp\n  then obtain k where k: \"?g = d*k\" unfolding dvd_def by blast\n  from d(3) have \"a * x * k = (b * y + d) *k \" by auto\n  hence \"a * (x * k) = b * (y*k) + ?g\" by (algebra add: k)\n  thus ?thesis by blast\nqed\n\n\nsubsection {* LCM properties *}\n\nlemma lcm_altdef_int [code]: \"lcm (a::int) b = (abs a) * (abs b) div gcd a b\"\n  by (simp add: lcm_int_def lcm_nat_def zdiv_int\n    of_nat_mult gcd_int_def)\n\nlemma prod_gcd_lcm_nat: \"(m::nat) * n = gcd m n * lcm m n\"\n  unfolding lcm_nat_def\n  by (simp add: dvd_mult_div_cancel [OF gcd_dvd_prod_nat])\n\nlemma prod_gcd_lcm_int: \"abs(m::int) * abs n = gcd m n * lcm m n\"\n  unfolding lcm_int_def gcd_int_def\n  apply (subst int_mult [symmetric])\n  apply (subst prod_gcd_lcm_nat [symmetric])\n  apply (subst nat_abs_mult_distrib [symmetric])\n  apply (simp, simp add: abs_mult)\ndone\n\nlemma lcm_0_nat [simp]: \"lcm (m::nat) 0 = 0\"\n  unfolding lcm_nat_def by simp\n\nlemma lcm_0_int [simp]: \"lcm (m::int) 0 = 0\"\n  unfolding lcm_int_def by simp\n\nlemma lcm_0_left_nat [simp]: \"lcm (0::nat) n = 0\"\n  unfolding lcm_nat_def by simp\n\nlemma lcm_0_left_int [simp]: \"lcm (0::int) n = 0\"\n  unfolding lcm_int_def by simp\n\nlemma lcm_pos_nat:\n  \"(m::nat) > 0 \\<Longrightarrow> n>0 \\<Longrightarrow> lcm m n > 0\"\nby (metis gr0I mult_is_0 prod_gcd_lcm_nat)\n\nlemma lcm_pos_int:\n  \"(m::int) ~= 0 \\<Longrightarrow> n ~= 0 \\<Longrightarrow> lcm m n > 0\"\n  apply (subst lcm_abs_int)\n  apply (rule lcm_pos_nat [transferred])\n  apply auto\ndone\n\nlemma dvd_pos_nat:\n  fixes n m :: nat\n  assumes \"n > 0\" and \"m dvd n\"\n  shows \"m > 0\"\nusing assms by (cases m) auto\n\nlemma lcm_least_nat:\n  assumes \"(m::nat) dvd k\" and \"n dvd k\"\n  shows \"lcm m n dvd k\"\nproof (cases k)\n  case 0 then show ?thesis by auto\nnext\n  case (Suc _) then have pos_k: \"k > 0\" by auto\n  from assms dvd_pos_nat [OF this] have pos_mn: \"m > 0\" \"n > 0\" by auto\n  with gcd_zero_nat [of m n] have pos_gcd: \"gcd m n > 0\" by simp\n  from assms obtain p where k_m: \"k = m * p\" using dvd_def by blast\n  from assms obtain q where k_n: \"k = n * q\" using dvd_def by blast\n  from pos_k k_m have pos_p: \"p > 0\" by auto\n  from pos_k k_n have pos_q: \"q > 0\" by auto\n  have \"k * k * gcd q p = k * gcd (k * q) (k * p)\"\n    by (simp add: ac_simps gcd_mult_distrib_nat)\n  also have \"\\<dots> = k * gcd (m * p * q) (n * q * p)\"\n    by (simp add: k_m [symmetric] k_n [symmetric])\n  also have \"\\<dots> = k * p * q * gcd m n\"\n    by (simp add: ac_simps gcd_mult_distrib_nat)\n  finally have \"(m * p) * (n * q) * gcd q p = k * p * q * gcd m n\"\n    by (simp only: k_m [symmetric] k_n [symmetric])\n  then have \"p * q * m * n * gcd q p = p * q * k * gcd m n\"\n    by (simp add: ac_simps)\n  with pos_p pos_q have \"m * n * gcd q p = k * gcd m n\"\n    by simp\n  with prod_gcd_lcm_nat [of m n]\n  have \"lcm m n * gcd q p * gcd m n = k * gcd m n\"\n    by (simp add: ac_simps)\n  with pos_gcd have \"lcm m n * gcd q p = k\" by auto\n  then show ?thesis using dvd_def by auto\nqed\n\nlemma lcm_least_int:\n  \"(m::int) dvd k \\<Longrightarrow> n dvd k \\<Longrightarrow> lcm m n dvd k\"\napply (subst lcm_abs_int)\napply (rule dvd_trans)\napply (rule lcm_least_nat [transferred, of _ \"abs k\" _])\napply auto\ndone\n\nlemma lcm_dvd1_nat: \"(m::nat) dvd lcm m n\"\nproof (cases m)\n  case 0 then show ?thesis by simp\nnext\n  case (Suc _)\n  then have mpos: \"m > 0\" by simp\n  show ?thesis\n  proof (cases n)\n    case 0 then show ?thesis by simp\n  next\n    case (Suc _)\n    then have npos: \"n > 0\" by simp\n    have \"gcd m n dvd n\" by simp\n    then obtain k where \"n = gcd m n * k\" using dvd_def by auto\n    then have \"m * n div gcd m n = m * (gcd m n * k) div gcd m n\"\n      by (simp add: ac_simps)\n    also have \"\\<dots> = m * k\" using mpos npos gcd_zero_nat by simp\n    finally show ?thesis by (simp add: lcm_nat_def)\n  qed\nqed\n\nlemma lcm_dvd1_int: \"(m::int) dvd lcm m n\"\n  apply (subst lcm_abs_int)\n  apply (rule dvd_trans)\n  prefer 2\n  apply (rule lcm_dvd1_nat [transferred])\n  apply auto\ndone\n\nlemma lcm_dvd2_nat: \"(n::nat) dvd lcm m n\"\n  using lcm_dvd1_nat [of n m] by (simp only: lcm_nat_def mult.commute gcd_nat.commute)\n\nlemma lcm_dvd2_int: \"(n::int) dvd lcm m n\"\n  using lcm_dvd1_int [of n m] by (simp only: lcm_int_def lcm_nat_def mult.commute gcd_nat.commute)\n\nlemma dvd_lcm_I1_nat[simp]: \"(k::nat) dvd m \\<Longrightarrow> k dvd lcm m n\"\nby(metis lcm_dvd1_nat dvd_trans)\n\nlemma dvd_lcm_I2_nat[simp]: \"(k::nat) dvd n \\<Longrightarrow> k dvd lcm m n\"\nby(metis lcm_dvd2_nat dvd_trans)\n\nlemma dvd_lcm_I1_int[simp]: \"(i::int) dvd m \\<Longrightarrow> i dvd lcm m n\"\nby(metis lcm_dvd1_int dvd_trans)\n\nlemma dvd_lcm_I2_int[simp]: \"(i::int) dvd n \\<Longrightarrow> i dvd lcm m n\"\nby(metis lcm_dvd2_int dvd_trans)\n\nlemma lcm_unique_nat: \"(a::nat) dvd d \\<and> b dvd d \\<and>\n    (\\<forall>e. a dvd e \\<and> b dvd e \\<longrightarrow> d dvd e) \\<longleftrightarrow> d = lcm a b\"\n  by (auto intro: dvd_antisym lcm_least_nat lcm_dvd1_nat lcm_dvd2_nat)\n\nlemma lcm_unique_int: \"d >= 0 \\<and> (a::int) dvd d \\<and> b dvd d \\<and>\n    (\\<forall>e. a dvd e \\<and> b dvd e \\<longrightarrow> d dvd e) \\<longleftrightarrow> d = lcm a b\"\n  by (auto intro: dvd_antisym [transferred] lcm_least_int)\n\ninterpretation lcm_nat: abel_semigroup \"lcm :: nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  + lcm_nat: semilattice_neutr \"lcm :: nat \\<Rightarrow> nat \\<Rightarrow> nat\" 1\nproof\n  fix n m p :: nat\n  show \"lcm (lcm n m) p = lcm n (lcm m p)\"\n    by (rule lcm_unique_nat [THEN iffD1]) (metis dvd.order_trans lcm_unique_nat)\n  show \"lcm m n = lcm n m\"\n    by (simp add: lcm_nat_def gcd_commute_nat field_simps)\n  show \"lcm m m = m\"\n    by (metis dvd.order_refl lcm_unique_nat)\n  show \"lcm m 1 = m\"\n    by (metis dvd.dual_order.refl lcm_unique_nat one_dvd)\nqed\n\ninterpretation lcm_int: abel_semigroup \"lcm :: int \\<Rightarrow> int \\<Rightarrow> int\"\nproof\n  fix n m p :: int\n  show \"lcm (lcm n m) p = lcm n (lcm m p)\"\n    by (rule lcm_unique_int [THEN iffD1]) (metis dvd_trans lcm_unique_int)\n  show \"lcm m n = lcm n m\"\n    by (simp add: lcm_int_def lcm_nat.commute)\nqed\n\nlemmas lcm_assoc_nat = lcm_nat.assoc\nlemmas lcm_commute_nat = lcm_nat.commute\nlemmas lcm_left_commute_nat = lcm_nat.left_commute\nlemmas lcm_assoc_int = lcm_int.assoc\nlemmas lcm_commute_int = lcm_int.commute\nlemmas lcm_left_commute_int = lcm_int.left_commute\n\nlemmas lcm_ac_nat = lcm_assoc_nat lcm_commute_nat lcm_left_commute_nat\nlemmas lcm_ac_int = lcm_assoc_int lcm_commute_int lcm_left_commute_int\n\nlemma lcm_proj2_if_dvd_nat [simp]: \"(x::nat) dvd y \\<Longrightarrow> lcm x y = y\"\n  apply (rule sym)\n  apply (subst lcm_unique_nat [symmetric])\n  apply auto\ndone\n\nlemma lcm_proj2_if_dvd_int [simp]: \"(x::int) dvd y \\<Longrightarrow> lcm x y = abs y\"\n  apply (rule sym)\n  apply (subst lcm_unique_int [symmetric])\n  apply auto\ndone\n\nlemma lcm_proj1_if_dvd_nat [simp]: \"(x::nat) dvd y \\<Longrightarrow> lcm y x = y\"\nby (subst lcm_commute_nat, erule lcm_proj2_if_dvd_nat)\n\nlemma lcm_proj1_if_dvd_int [simp]: \"(x::int) dvd y \\<Longrightarrow> lcm y x = abs y\"\nby (subst lcm_commute_int, erule lcm_proj2_if_dvd_int)\n\nlemma lcm_proj1_iff_nat[simp]: \"lcm m n = (m::nat) \\<longleftrightarrow> n dvd m\"\nby (metis lcm_proj1_if_dvd_nat lcm_unique_nat)\n\nlemma lcm_proj2_iff_nat[simp]: \"lcm m n = (n::nat) \\<longleftrightarrow> m dvd n\"\nby (metis lcm_proj2_if_dvd_nat lcm_unique_nat)\n\nlemma lcm_proj1_iff_int[simp]: \"lcm m n = abs(m::int) \\<longleftrightarrow> n dvd m\"\nby (metis dvd_abs_iff lcm_proj1_if_dvd_int lcm_unique_int)\n\nlemma lcm_proj2_iff_int[simp]: \"lcm m n = abs(n::int) \\<longleftrightarrow> m dvd n\"\nby (metis dvd_abs_iff lcm_proj2_if_dvd_int lcm_unique_int)\n\nlemma comp_fun_idem_gcd_nat: \"comp_fun_idem (gcd :: nat\\<Rightarrow>nat\\<Rightarrow>nat)\"\nproof qed (auto simp add: gcd_ac_nat)\n\nlemma comp_fun_idem_gcd_int: \"comp_fun_idem (gcd :: int\\<Rightarrow>int\\<Rightarrow>int)\"\nproof qed (auto simp add: gcd_ac_int)\n\nlemma comp_fun_idem_lcm_nat: \"comp_fun_idem (lcm :: nat\\<Rightarrow>nat\\<Rightarrow>nat)\"\nproof qed (auto simp add: lcm_ac_nat)\n\nlemma comp_fun_idem_lcm_int: \"comp_fun_idem (lcm :: int\\<Rightarrow>int\\<Rightarrow>int)\"\nproof qed (auto simp add: lcm_ac_int)\n\n\n(* FIXME introduce selimattice_bot/top and derive the following lemmas in there: *)\n\nlemma lcm_0_iff_nat[simp]: \"lcm (m::nat) n = 0 \\<longleftrightarrow> m=0 \\<or> n=0\"\nby (metis lcm_0_left_nat lcm_0_nat mult_is_0 prod_gcd_lcm_nat)\n\nlemma lcm_0_iff_int[simp]: \"lcm (m::int) n = 0 \\<longleftrightarrow> m=0 \\<or> n=0\"\nby (metis lcm_0_int lcm_0_left_int lcm_pos_int less_le)\n\nlemma lcm_1_iff_nat[simp]: \"lcm (m::nat) n = 1 \\<longleftrightarrow> m=1 \\<and> n=1\"\nby (metis gcd_1_nat lcm_unique_nat nat_mult_1 prod_gcd_lcm_nat)\n\nlemma lcm_1_iff_int[simp]: \"lcm (m::int) n = 1 \\<longleftrightarrow> (m=1 \\<or> m = -1) \\<and> (n=1 \\<or> n = -1)\"\nby (auto simp add: abs_mult_self trans [OF lcm_unique_int eq_commute, symmetric] zmult_eq_1_iff)\n\n\nsubsection {* The complete divisibility lattice *}\n\ninterpretation gcd_semilattice_nat: semilattice_inf gcd \"op dvd\" \"(%m n::nat. m dvd n & ~ n dvd m)\"\nproof\n  case goal3 thus ?case by(metis gcd_unique_nat)\nqed auto\n\ninterpretation lcm_semilattice_nat: semilattice_sup lcm \"op dvd\" \"(%m n::nat. m dvd n & ~ n dvd m)\"\nproof\n  case goal3 thus ?case by(metis lcm_unique_nat)\nqed auto\n\ninterpretation gcd_lcm_lattice_nat: lattice gcd \"op dvd\" \"(%m n::nat. m dvd n & ~ n dvd m)\" lcm ..\n\ntext{* Lifting gcd and lcm to sets (Gcd/Lcm).\nGcd is defined via Lcm to facilitate the proof that we have a complete lattice.\n*}\n\nclass Gcd = gcd +\n  fixes Gcd :: \"'a set \\<Rightarrow> 'a\"\n  fixes Lcm :: \"'a set \\<Rightarrow> 'a\"\n\ninstantiation nat :: Gcd\nbegin\n\ndefinition\n  \"Lcm (M::nat set) = (if finite M then semilattice_neutr_set.F lcm 1 M else 0)\"\n\ninterpretation semilattice_neutr_set lcm \"1::nat\" ..\n\nlemma Lcm_nat_infinite:\n  \"\\<not> finite M \\<Longrightarrow> Lcm M = (0::nat)\"\n  by (simp add: Lcm_nat_def)\n\nlemma Lcm_nat_empty:\n  \"Lcm {} = (1::nat)\"\n  by (simp add: Lcm_nat_def)\n\nlemma Lcm_nat_insert:\n  \"Lcm (insert n M) = lcm (n::nat) (Lcm M)\"\n  by (cases \"finite M\") (simp_all add: Lcm_nat_def Lcm_nat_infinite)\n\ndefinition\n  \"Gcd (M::nat set) = Lcm {d. \\<forall>m\\<in>M. d dvd m}\"\n\ninstance ..\n\nend\n\nlemma dvd_Lcm_nat [simp]:\n  fixes M :: \"nat set\"\n  assumes \"m \\<in> M\"\n  shows \"m dvd Lcm M\"\nproof (cases \"finite M\")\n  case False then show ?thesis by (simp add: Lcm_nat_infinite)\nnext\n  case True then show ?thesis using assms by (induct M) (auto simp add: Lcm_nat_insert)\nqed\n\nlemma Lcm_dvd_nat [simp]:\n  fixes M :: \"nat set\"\n  assumes \"\\<forall>m\\<in>M. m dvd n\"\n  shows \"Lcm M dvd n\"\nproof (cases \"n = 0\")\n  assume \"n \\<noteq> 0\"\n  hence \"finite {d. d dvd n}\" by (rule finite_divisors_nat)\n  moreover have \"M \\<subseteq> {d. d dvd n}\" using assms by fast\n  ultimately have \"finite M\" by (rule rev_finite_subset)\n  then show ?thesis using assms by (induct M) (simp_all add: Lcm_nat_empty Lcm_nat_insert)\nqed simp\n\ninterpretation gcd_lcm_complete_lattice_nat:\n  complete_lattice Gcd Lcm gcd Rings.dvd \"\\<lambda>m n. m dvd n \\<and> \\<not> n dvd m\" lcm 1 \"0::nat\"\nwhere\n  \"Inf.INFIMUM Gcd A f = Gcd (f ` A :: nat set)\"\n  and \"Sup.SUPREMUM Lcm A f = Lcm (f ` A)\"\nproof -\n  show \"class.complete_lattice Gcd Lcm gcd Rings.dvd (\\<lambda>m n. m dvd n \\<and> \\<not> n dvd m) lcm 1 (0::nat)\"\n  proof\n    case goal1 thus ?case by (simp add: Gcd_nat_def)\n  next\n    case goal2 thus ?case by (simp add: Gcd_nat_def)\n  next\n    case goal5 show ?case by (simp add: Gcd_nat_def Lcm_nat_infinite)\n  next\n    case goal6 show ?case by (simp add: Lcm_nat_empty)\n  next\n    case goal3 thus ?case by simp\n  next\n    case goal4 thus ?case by simp\n  qed\n  then interpret gcd_lcm_complete_lattice_nat:\n    complete_lattice Gcd Lcm gcd Rings.dvd \"\\<lambda>m n. m dvd n \\<and> \\<not> n dvd m\" lcm 1 \"0::nat\" .\n  from gcd_lcm_complete_lattice_nat.INF_def show \"Inf.INFIMUM Gcd A f = Gcd (f ` A)\" .\n  from gcd_lcm_complete_lattice_nat.SUP_def show \"Sup.SUPREMUM Lcm A f = Lcm (f ` A)\" .\nqed\n\ndeclare gcd_lcm_complete_lattice_nat.Inf_image_eq [simp del]\ndeclare gcd_lcm_complete_lattice_nat.Sup_image_eq [simp del]\n\nlemma Lcm_empty_nat: \"Lcm {} = (1::nat)\"\n  by (fact Lcm_nat_empty)\n\nlemma Gcd_empty_nat: \"Gcd {} = (0::nat)\"\n  by (fact gcd_lcm_complete_lattice_nat.Inf_empty) (* already simp *)\n\nlemma Lcm_insert_nat [simp]:\n  shows \"Lcm (insert (n::nat) N) = lcm n (Lcm N)\"\n  by (fact gcd_lcm_complete_lattice_nat.Sup_insert)\n\nlemma Gcd_insert_nat [simp]:\n  shows \"Gcd (insert (n::nat) N) = gcd n (Gcd N)\"\n  by (fact gcd_lcm_complete_lattice_nat.Inf_insert)\n\nlemma Lcm0_iff[simp]: \"finite (M::nat set) \\<Longrightarrow> M \\<noteq> {} \\<Longrightarrow> Lcm M = 0 \\<longleftrightarrow> 0 : M\"\nby(induct rule:finite_ne_induct) auto\n\nlemma Lcm_eq_0[simp]: \"finite (M::nat set) \\<Longrightarrow> 0 : M \\<Longrightarrow> Lcm M = 0\"\nby (metis Lcm0_iff empty_iff)\n\nlemma Gcd_dvd_nat [simp]:\n  fixes M :: \"nat set\"\n  assumes \"m \\<in> M\" shows \"Gcd M dvd m\"\n  using assms by (fact gcd_lcm_complete_lattice_nat.Inf_lower)\n\nlemma dvd_Gcd_nat[simp]:\n  fixes M :: \"nat set\"\n  assumes \"\\<forall>m\\<in>M. n dvd m\" shows \"n dvd Gcd M\"\n  using assms by (simp only: gcd_lcm_complete_lattice_nat.Inf_greatest)\n\ntext{* Alternative characterizations of Gcd: *}\n\nlemma Gcd_eq_Max: \"finite(M::nat set) \\<Longrightarrow> M \\<noteq> {} \\<Longrightarrow> 0 \\<notin> M \\<Longrightarrow> Gcd M = Max(\\<Inter>m\\<in>M. {d. d dvd m})\"\napply(rule antisym)\n apply(rule Max_ge)\n  apply (metis all_not_in_conv finite_divisors_nat finite_INT)\n apply simp\napply (rule Max_le_iff[THEN iffD2])\n  apply (metis all_not_in_conv finite_divisors_nat finite_INT)\n apply fastforce\napply clarsimp\napply (metis Gcd_dvd_nat Max_in dvd_0_left dvd_Gcd_nat dvd_imp_le linorder_antisym_conv3 not_less0)\ndone\n\nlemma Gcd_remove0_nat: \"finite M \\<Longrightarrow> Gcd M = Gcd (M - {0::nat})\"\napply(induct pred:finite)\n apply simp\napply(case_tac \"x=0\")\n apply simp\napply(subgoal_tac \"insert x F - {0} = insert x (F - {0})\")\n apply simp\napply blast\ndone\n\nlemma Lcm_in_lcm_closed_set_nat:\n  \"finite M \\<Longrightarrow> M \\<noteq> {} \\<Longrightarrow> ALL m n :: nat. m:M \\<longrightarrow> n:M \\<longrightarrow> lcm m n : M \\<Longrightarrow> Lcm M : M\"\napply(induct rule:finite_linorder_min_induct)\n apply simp\napply simp\napply(subgoal_tac \"ALL m n :: nat. m:A \\<longrightarrow> n:A \\<longrightarrow> lcm m n : A\")\n apply simp\n apply(case_tac \"A={}\")\n  apply simp\n apply simp\napply (metis lcm_pos_nat lcm_unique_nat linorder_neq_iff nat_dvd_not_less not_less0)\ndone\n\nlemma Lcm_eq_Max_nat:\n  \"finite M \\<Longrightarrow> M \\<noteq> {} \\<Longrightarrow> 0 \\<notin> M \\<Longrightarrow> ALL m n :: nat. m:M \\<longrightarrow> n:M \\<longrightarrow> lcm m n : M \\<Longrightarrow> Lcm M = Max M\"\napply(rule antisym)\n apply(rule Max_ge, assumption)\n apply(erule (2) Lcm_in_lcm_closed_set_nat)\napply clarsimp\napply (metis Lcm0_iff dvd_Lcm_nat dvd_imp_le neq0_conv)\ndone\n\nlemma Lcm_set_nat [code, code_unfold]:\n  \"Lcm (set ns) = fold lcm ns (1::nat)\"\n  by (fact gcd_lcm_complete_lattice_nat.Sup_set_fold)\n\nlemma Gcd_set_nat [code, code_unfold]:\n  \"Gcd (set ns) = fold gcd ns (0::nat)\"\n  by (fact gcd_lcm_complete_lattice_nat.Inf_set_fold)\n\nlemma mult_inj_if_coprime_nat:\n  \"inj_on f A \\<Longrightarrow> inj_on g B \\<Longrightarrow> ALL a:A. ALL b:B. coprime (f a) (g b)\n   \\<Longrightarrow> inj_on (%(a,b). f a * g b::nat) (A \\<times> B)\"\napply(auto simp add:inj_on_def)\napply (metis coprime_dvd_mult_iff_nat dvd.neq_le_trans dvd_triv_left)\napply (metis gcd_semilattice_nat.inf_commute coprime_dvd_mult_iff_nat\n             dvd.neq_le_trans dvd_triv_right mult.commute)\ndone\n\ntext{* Nitpick: *}\n\nlemma gcd_eq_nitpick_gcd [nitpick_unfold]: \"gcd x y = Nitpick.nat_gcd x y\"\nby (induct x y rule: nat_gcd.induct)\n   (simp add: gcd_nat.simps Nitpick.nat_gcd.simps)\n\nlemma lcm_eq_nitpick_lcm [nitpick_unfold]: \"lcm x y = Nitpick.nat_lcm x y\"\nby (simp only: lcm_nat_def Nitpick.nat_lcm_def gcd_eq_nitpick_gcd)\n\n\nsubsubsection {* Setwise gcd and lcm for integers *}\n\ninstantiation int :: Gcd\nbegin\n\ndefinition\n  \"Lcm M = int (Lcm (nat ` abs ` M))\"\n\ndefinition\n  \"Gcd M = int (Gcd (nat ` abs ` M))\"\n\ninstance ..\nend\n\nlemma Lcm_empty_int [simp]: \"Lcm {} = (1::int)\"\n  by (simp add: Lcm_int_def)\n\nlemma Gcd_empty_int [simp]: \"Gcd {} = (0::int)\"\n  by (simp add: Gcd_int_def)\n\nlemma Lcm_insert_int [simp]:\n  shows \"Lcm (insert (n::int) N) = lcm n (Lcm N)\"\n  by (simp add: Lcm_int_def lcm_int_def)\n\nlemma Gcd_insert_int [simp]:\n  shows \"Gcd (insert (n::int) N) = gcd n (Gcd N)\"\n  by (simp add: Gcd_int_def gcd_int_def)\n\nlemma dvd_int_iff: \"x dvd y \\<longleftrightarrow> nat (abs x) dvd nat (abs y)\"\n  by (simp add: zdvd_int)\n\nlemma dvd_Lcm_int [simp]:\n  fixes M :: \"int set\" assumes \"m \\<in> M\" shows \"m dvd Lcm M\"\n  using assms by (simp add: Lcm_int_def dvd_int_iff)\n\nlemma Lcm_dvd_int [simp]:\n  fixes M :: \"int set\"\n  assumes \"\\<forall>m\\<in>M. m dvd n\" shows \"Lcm M dvd n\"\n  using assms by (simp add: Lcm_int_def dvd_int_iff)\n\nlemma Gcd_dvd_int [simp]:\n  fixes M :: \"int set\"\n  assumes \"m \\<in> M\" shows \"Gcd M dvd m\"\n  using assms by (simp add: Gcd_int_def dvd_int_iff)\n\nlemma dvd_Gcd_int[simp]:\n  fixes M :: \"int set\"\n  assumes \"\\<forall>m\\<in>M. n dvd m\" shows \"n dvd Gcd M\"\n  using assms by (simp add: Gcd_int_def dvd_int_iff)\n\nlemma Lcm_set_int [code, code_unfold]:\n  \"Lcm (set xs) = fold lcm xs (1::int)\"\n  by (induct xs rule: rev_induct) (simp_all add: lcm_commute_int)\n\nlemma Gcd_set_int [code, code_unfold]:\n  \"Gcd (set xs) = fold gcd xs (0::int)\"\n  by (induct xs rule: rev_induct) (simp_all add: gcd_commute_int)\n\n\ntext \\<open>Fact aliasses\\<close>\n  \nlemmas gcd_dvd1_nat = gcd_dvd1 [where ?'a = nat] \n  and gcd_dvd2_nat = gcd_dvd2 [where ?'a = nat]\n  and gcd_greatest_nat = gcd_greatest [where ?'a = nat]\n\nlemmas gcd_dvd1_int = gcd_dvd1 [where ?'a = int] \n  and gcd_dvd2_int = gcd_dvd2 [where ?'a = int]\n  and gcd_greatest_int = gcd_greatest [where ?'a = int]\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/GCD.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7775098463152658}}
{"text": "(*\n    $Id: sol.thy,v 1.3 2011/06/28 18:11:38 webertj Exp $\n    Author: Martin Strecker\n*)\n\nheader {* Summation, Flattening *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext{* Define a function @{text sum}, which computes the sum of\nelements of a list of natural numbers. *}\n\nprimrec sum :: \"nat list \\<Rightarrow> nat\" where\n  \"sum []     = 0\"\n| \"sum (x#xs) = x + sum xs\"\n\n\ntext{* Then, define a function @{text flatten} which flattens a list\nof lists by appending the member lists. *}\n\nprimrec flatten :: \"'a list list \\<Rightarrow> 'a list\" where\n  \"flatten []       = []\"\n| \"flatten (xs#xss) = xs @ flatten xss\"\n\n\ntext{* Test your functions by applying them to the following example lists: *}\n\nlemma \"sum [2::nat, 4, 8] = x\"\n  apply simp  -- {* x = 14 *}\noops\n\nlemma \"flatten [[2::nat, 3], [4, 5], [7, 9]] = x\"\n  apply simp  -- {* x = [2, 3, 4, 5, 7, 9] *}\noops\n\n\ntext{* Prove the following statements, or give a counterexample: *}\n\nlemma \"length (flatten xs) = sum (map length xs)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma sum_append: \"sum (xs @ ys) = sum xs + sum ys\"\n  apply (induct \"ys\")\n    apply simp\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma flatten_append: \"flatten (xs @ ys) = flatten xs @ flatten ys\"\n  apply (induct \"ys\")\n    apply simp\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma \"flatten (map rev (rev xs)) = rev (flatten xs)\"\n  apply (induct \"xs\")\n  apply (auto simp add: flatten_append)\ndone\n\nlemma \"flatten (rev (map rev xs)) = rev (flatten xs)\"\n  apply (induct \"xs\")\n  apply (auto simp add: flatten_append)\ndone\n\nlemma \"list_all (list_all P) xs = list_all P (flatten xs)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma \"flatten (rev xs) = flatten xs\"\n  quickcheck\noops\n\ntext{*\n  A possible counterexample is:\n  xs = [[0], [1]]\n*}\n\nlemma \"sum (rev xs) = sum xs\"\n  apply (induct \"xs\")\n  apply (auto simp add: sum_append)\ndone\n\n\ntext{* Find a (non-trivial) predicate @{text P} which satisfies *}\n\nlemma \"list_all P xs \\<longrightarrow> length xs \\<le> sum xs\"\n(*<*) oops (*>*)\n\nlemma \"list_all (\\<lambda>x. 1 \\<le> x) xs \\<longrightarrow> length xs \\<le> sum xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\n\ntext{* Define, by means of primitive recursion, a function @{text\nlist_exists} which checks whether an element satisfying a given property\nis contained in the list: *}\n\nprimrec list_exists :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a list \\<Rightarrow> bool)\" where\n  \"list_exists P []     = False\"\n| \"list_exists P (x#xs) = (P x \\<or> list_exists P xs)\"\n\n\ntext{* Test your function on the following examples: *}\n\nlemma \"list_exists (\\<lambda> n. n < 3) [4::nat, 3, 7] = b\"\n  apply simp  -- {* b is false *}\noops\n\nlemma \"list_exists (\\<lambda> n. n < 4) [4::nat, 3, 7] = b\"\n  apply simp  -- {* b is true *}\noops\n\n\ntext{* Prove the following statements: *}\n\nlemma list_exists_append: \n  \"list_exists P (xs @ ys) = (list_exists P xs \\<or> list_exists P ys)\"\n  apply (induct \"ys\")\n    apply simp\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma \"list_exists (list_exists P) xs = list_exists P (flatten xs)\"\n  apply (induct \"xs\")\n  apply (auto simp add: list_exists_append)\ndone\n\n\ntext{* You could have defined @{text list_exists} only with the aid of\n@{text list_all}.  Do this now, i.e. define a function @{text\nlist_exists2} and show that it is equivalent to @{text list_exists}. *}\n\ndefinition list_exists2 :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a list \\<Rightarrow> bool)\" where\n  \"list_exists2 P xs == \\<not> list_all (\\<lambda>x. \\<not> P x) xs\"\n\nlemma \"list_exists2 P xs = list_exists P xs\"\n  apply (induct \"xs\")\n  apply (auto simp add: list_exists2_def)\ndone\n\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/lists/sum/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8688267813328977, "lm_q1q2_score": 0.7774170518044539}}
{"text": "section\\<open>Lemmas about undirected graphs\\<close>\n\ntheory Ugraph_Lemmas\nimports\n  Prob_Lemmas\n  Girth_Chromatic.Girth_Chromatic\nbegin\n\ntext\\<open>The complete graph is a graph where all possible edges are present. It is wellformed by\ndefinition.\\<close>\n\ndefinition complete :: \"nat set \\<Rightarrow> ugraph\" where\n\"complete V = (V, all_edges V)\"\n\nlemma complete_wellformed: \"uwellformed (complete V)\"\nunfolding complete_def uwellformed_def all_edges_def\nby simp\n\ntext\\<open>If the set of vertices is finite, the set of edges in the complete graph is finite.\\<close>\n\nlemma all_edges_finite: \"finite V \\<Longrightarrow> finite (all_edges V)\"\nunfolding all_edges_def\nby simp\n\ncorollary complete_finite_edges: \"finite V \\<Longrightarrow> finite (uedges (complete V))\"\nunfolding complete_def using all_edges_finite\nby simp\n\ntext\\<open>The sets of possible edges of disjoint sets of vertices are disjoint.\\<close>\n\nlemma all_edges_disjoint: \"S \\<inter> T = {} \\<Longrightarrow> all_edges S \\<inter> all_edges T = {}\"\nunfolding all_edges_def\nby force\n\ntext\\<open>A graph is called `finite' if its set of edges and its set of vertices are finite.\\<close>\n\ndefinition \"finite_graph G \\<equiv> finite (uverts G) \\<and> finite (uedges G)\"\n\ntext\\<open>The complete graph is finite.\\<close>\n\ncorollary complete_finite: \"finite V \\<Longrightarrow> finite_graph (complete V)\"\nusing complete_finite_edges unfolding finite_graph_def complete_def\nby simp\n\ntext\\<open>A graph is called `nonempty' if it contains at least one vertex and at least one edge.\\<close>\n\ndefinition \"nonempty_graph G \\<equiv> uverts G \\<noteq> {} \\<and> uedges G \\<noteq> {}\"\n\ntext\\<open>A random graph is both wellformed and finite.\\<close>\n\nlemma (in edge_space) wellformed_and_finite:\n  assumes \"E \\<in> Pow S_edges\"\n  shows \"finite_graph (edge_ugraph E)\" \"uwellformed (edge_ugraph E)\"\nunfolding finite_graph_def\nproof\n  show \"finite (uverts (edge_ugraph E))\"\n    unfolding edge_ugraph_def S_verts_def by simp\nnext\n  show \"finite (uedges (edge_ugraph E))\"\n    using assms unfolding edge_ugraph_def S_edges_def by (auto intro: all_edges_finite)\nnext\n  show \"uwellformed (edge_ugraph E)\"\n    using complete_wellformed unfolding edge_ugraph_def S_edges_def complete_def uwellformed_def by force\nqed\n\ntext\\<open>The probability for a random graph to have $e$ edges is $p ^ e$.\\<close>\n\nlemma (in edge_space) cylinder_empty_prob:\n  \"A \\<subseteq> S_edges \\<Longrightarrow> prob (cylinder S_edges A {}) = p ^ (card A)\"\nusing cylinder_prob by auto\n\nsubsection\\<open>Subgraphs\\<close>\n\ndefinition subgraph :: \"ugraph \\<Rightarrow> ugraph \\<Rightarrow> bool\" where\n\"subgraph G' G \\<equiv> uverts G' \\<subseteq> uverts G \\<and> uedges G' \\<subseteq> uedges G\"\n\nlemma subgraph_refl: \"subgraph G G\"\nunfolding subgraph_def\nby simp\n\nlemma subgraph_trans: \"subgraph G'' G' \\<Longrightarrow> subgraph G' G \\<Longrightarrow> subgraph G'' G\"\nunfolding subgraph_def\nby auto\n\nlemma subgraph_antisym: \"subgraph G G' \\<Longrightarrow> subgraph G' G \\<Longrightarrow> G = G'\"\nunfolding subgraph_def\nby (auto simp add: Product_Type.prod_eqI)\n\nlemma subgraph_complete:\n  assumes \"uwellformed G\"\n  shows \"subgraph G (complete (uverts G))\"\nproof -\n  {\n    fix e\n    assume \"e \\<in> uedges G\"\n    with assms have \"card e = 2\" and u: \"\\<And>u. u \\<in> e \\<Longrightarrow> u \\<in> uverts G\"\n      unfolding uwellformed_def by auto\n    moreover then obtain u v where \"e = {u, v}\" \"u \\<noteq> v\"\n      by (metis card_2_elements)\n    ultimately have \"e = mk_uedge (u, v)\" \"u \\<in> uverts G\" \"v \\<in> uverts G\"\n      by auto\n    hence \"e \\<in> all_edges (uverts G)\"\n      unfolding all_edges_def using \\<open>u \\<noteq> v\\<close> by fastforce\n  }\n  thus ?thesis\n    unfolding complete_def subgraph_def by auto\nqed\n\ncorollary wellformed_all_edges: \"uwellformed G \\<Longrightarrow> uedges G \\<subseteq> all_edges (uverts G)\"\nusing subgraph_complete subgraph_def complete_def by simp\n\nlemma subgraph_finite: \"\\<lbrakk> finite_graph G; subgraph G' G \\<rbrakk> \\<Longrightarrow> finite_graph G'\"\nunfolding finite_graph_def subgraph_def\nby (metis rev_finite_subset)\n\ncorollary wellformed_finite:\n  assumes \"finite (uverts G)\" and \"uwellformed G\"\n  shows \"finite_graph G\"\nproof (rule subgraph_finite[where G = \"complete (uverts G)\"])\n  show \"subgraph G (complete (uverts G))\"\n    using assms by (simp add: subgraph_complete)\nnext\n  have \"finite (uedges (complete (uverts G)))\"\n    using complete_finite_edges[OF assms(1)] .\n  thus \"finite_graph (complete (uverts G))\"\n    unfolding finite_graph_def complete_def using assms(1) by auto\nqed\n\ndefinition subgraphs :: \"ugraph \\<Rightarrow> ugraph set\" where\n\"subgraphs G = {G'. subgraph G' G}\"\n\ndefinition nonempty_subgraphs :: \"ugraph \\<Rightarrow> ugraph set\" where\n\"nonempty_subgraphs G = {G'. uwellformed G' \\<and> subgraph G' G \\<and> nonempty_graph G'}\"\n\nlemma subgraphs_finite:\n  assumes \"finite_graph G\"\n  shows \"finite (subgraphs G)\"\nproof -\n  have \"subgraphs G = {(V', E'). V' \\<subseteq> uverts G \\<and> E' \\<subseteq> uedges G}\"\n    unfolding subgraphs_def subgraph_def by force\n  moreover have \"finite (uverts G)\" \"finite (uedges G)\"\n    using assms unfolding finite_graph_def by auto\n  ultimately show ?thesis\n    by simp\nqed\n\ncorollary nonempty_subgraphs_finite: \"finite_graph G \\<Longrightarrow> finite (nonempty_subgraphs G)\"\nusing subgraphs_finite\nunfolding nonempty_subgraphs_def subgraphs_def\nby auto\n\nsubsection\\<open>Induced subgraphs\\<close>\n\ndefinition induced_subgraph :: \"uvert set \\<Rightarrow> ugraph \\<Rightarrow> ugraph\" where\n\"induced_subgraph V G = (V, uedges G \\<inter> all_edges V)\"\n\nlemma induced_is_subgraph:\n  \"V \\<subseteq> uverts G \\<Longrightarrow> subgraph (induced_subgraph V G) G\"\n  \"V \\<subseteq> uverts G \\<Longrightarrow> subgraph (induced_subgraph V G) (complete V)\"\nunfolding subgraph_def induced_subgraph_def complete_def\nby simp+\n\nlemma induced_wellformed: \"uwellformed G \\<Longrightarrow> V \\<subseteq> uverts G \\<Longrightarrow> uwellformed (induced_subgraph V G)\"\nunfolding uwellformed_def induced_subgraph_def all_edges_def\nby force\n\nlemma subgraph_union_induced:\n  assumes \"uverts H\\<^sub>1 \\<subseteq> S\" and \"uverts H\\<^sub>2 \\<subseteq> T\"\n  assumes \"uwellformed H\\<^sub>1\" and \"uwellformed H\\<^sub>2\"\n  shows \"subgraph H\\<^sub>1 (induced_subgraph S G) \\<and> subgraph H\\<^sub>2 (induced_subgraph T G) \\<longleftrightarrow>\n         subgraph (uverts H\\<^sub>1 \\<union> uverts H\\<^sub>2, uedges H\\<^sub>1 \\<union> uedges H\\<^sub>2) (induced_subgraph (S \\<union> T) G)\"\nunfolding induced_subgraph_def subgraph_def\napply auto\nusing all_edges_mono apply blast\nusing all_edges_mono apply blast\nusing assms(1,2) wellformed_all_edges[OF assms(3)] wellformed_all_edges[OF assms(4)] all_edges_mono[OF assms(1)] all_edges_mono[OF assms(2)]\napply auto\ndone\n\nlemma (in edge_space) induced_subgraph_prob:\n  assumes \"uverts H \\<subseteq> V\" and \"uwellformed H\" and \"V \\<subseteq> S_verts\"\n  shows \"prob {es \\<in> space P. subgraph H (induced_subgraph V (edge_ugraph es))} = p ^ card (uedges H)\" (is \"prob ?A = _\")\nproof -\n  have \"prob ?A = prob (cylinder S_edges (uedges H) {})\"\n    unfolding cylinder_def space_eq subgraph_def induced_subgraph_def edge_ugraph_def S_edges_def\n    by (rule arg_cong[OF Collect_cong]) (metis (no_types) assms(1,2) Pow_iff all_edges_mono fst_conv inf_absorb1 inf_bot_left le_inf_iff snd_conv wellformed_all_edges)\n  also have \"\\<dots> = p ^ card (uedges H)\"\n    proof (rule cylinder_empty_prob)\n      have \"uedges H \\<subseteq> all_edges (uverts H)\"\n        by (rule wellformed_all_edges[OF assms(2)])\n      also have \"all_edges (uverts H) \\<subseteq> all_edges S_verts\"\n        using assms by (auto simp: all_edges_mono[OF subset_trans])\n      finally show \"uedges H \\<subseteq> S_edges\"\n        unfolding S_edges_def .\n    qed\n  finally show ?thesis\n    .\nqed\n\nsubsection\\<open>Graph isomorphism\\<close>\n\ntext\\<open>We define graph isomorphism slightly different than in the literature. The usual definition\nis that two graphs are isomorphic iff there exists a bijection between the vertex sets which\npreserves the adjacency. However, this complicates many proofs.\n\nInstead, we define the intuitive mapping operation on graphs. An isomorphism between two graphs\narises if there is a suitable mapping function from the first to the second graph. Later, we show\nthat this operation can be inverted.\\<close>\n\nfun map_ugraph :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> ugraph \\<Rightarrow> ugraph\" where\n\"map_ugraph f (V, E) = (f ` V, (\\<lambda>e. f ` e) ` E)\"\n\ndefinition isomorphism :: \"ugraph \\<Rightarrow> ugraph \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n\"isomorphism G\\<^sub>1 G\\<^sub>2 f \\<equiv> bij_betw f (uverts G\\<^sub>1) (uverts G\\<^sub>2) \\<and> G\\<^sub>2 = map_ugraph f G\\<^sub>1\"\n\nabbreviation isomorphic :: \"ugraph \\<Rightarrow> ugraph \\<Rightarrow> bool\" (\"_ \\<simeq> _\") where\n\"G\\<^sub>1 \\<simeq> G\\<^sub>2 \\<equiv> uwellformed G\\<^sub>1 \\<and> uwellformed G\\<^sub>2 \\<and> (\\<exists>f. isomorphism G\\<^sub>1 G\\<^sub>2 f)\"\n\nlemma map_ugraph_id: \"map_ugraph id = id\"\nunfolding fun_eq_iff\nby simp\n\nlemma map_ugraph_trans: \"map_ugraph (g \\<circ> f) = (map_ugraph g) \\<circ> (map_ugraph f)\"\n  by (simp add: fun_eq_iff image_image)\n\nlemma map_ugraph_wellformed:\n  assumes \"uwellformed G\" and \"inj_on f (uverts G)\"\n  shows \"uwellformed (map_ugraph f G)\"\nunfolding uwellformed_def\nproof safe\n  fix e'\n  assume \"e' \\<in> uedges (map_ugraph f G)\"\n  hence \"e' \\<in> (\\<lambda>e. f ` e) ` (uedges G)\"\n    by (metis map_ugraph.simps snd_conv surjective_pairing)\n  then obtain e where e: \"e' = f ` e\" \"e \\<in> uedges G\"\n    by blast\n  hence \"card e = 2\" \"e \\<subseteq> uverts G\"\n    using assms(1) unfolding uwellformed_def by blast+\n  thus \"card e' = 2\"\n    using e(1) by (simp add: card_inj_subs[OF assms(2)])\n\n  fix u'\n  assume \"u' \\<in> e'\"\n  hence \"u' \\<in> f ` e\"\n    using e by force\n  then obtain u where u: \"u' = f u\" \"u \\<in> e\"\n    by blast\n  hence \"u \\<in> uverts G\"\n    using assms(1) e(2) unfolding uwellformed_def by blast\n  hence \"u' \\<in> f ` uverts G\"\n    using u(1) by simp\n  thus \"u' \\<in> uverts (map_ugraph f G)\"\n    by (metis map_ugraph.simps fst_conv surjective_pairing)\nqed\n\nlemma map_ugraph_finite: \"finite_graph G \\<Longrightarrow> finite_graph (map_ugraph f G)\"\nunfolding finite_graph_def\nby (metis finite_imageI fst_conv map_ugraph.simps snd_conv surjective_pairing)\n\nlemma map_ugraph_preserves_sub:\n  assumes \"subgraph G\\<^sub>1 G\\<^sub>2\"\n  shows \"subgraph (map_ugraph f G\\<^sub>1) (map_ugraph f G\\<^sub>2)\"\nproof -\n  have \"f ` uverts G\\<^sub>1 \\<subseteq> f ` uverts G\\<^sub>2\" \"(\\<lambda>e. f ` e) ` uedges G\\<^sub>1 \\<subseteq> (\\<lambda>e. f ` e) ` uedges G\\<^sub>2\"\n    using assms(1) unfolding subgraph_def by auto\n  thus ?thesis\n    unfolding subgraph_def by (metis map_ugraph.simps fst_conv snd_conv surjective_pairing)\nqed\n\nlemma isomorphic_refl: \"uwellformed G \\<Longrightarrow> G \\<simeq> G\"\nunfolding isomorphism_def\nby (metis bij_betw_id id_def map_ugraph_id)\n\nlemma isomorphic_trans:\n  assumes \"G\\<^sub>1 \\<simeq> G\\<^sub>2\" and \"G\\<^sub>2 \\<simeq> G\\<^sub>3\"\n  shows \"G\\<^sub>1 \\<simeq> G\\<^sub>3\"\nproof -\n  from assms obtain f\\<^sub>1 f\\<^sub>2 where\n    bij: \"bij_betw f\\<^sub>1 (uverts G\\<^sub>1) (uverts G\\<^sub>2)\" \"bij_betw f\\<^sub>2 (uverts G\\<^sub>2) (uverts G\\<^sub>3)\" and\n    map: \"G\\<^sub>2 = map_ugraph f\\<^sub>1 G\\<^sub>1\" \"G\\<^sub>3 = map_ugraph f\\<^sub>2 G\\<^sub>2\"\n    unfolding isomorphism_def by blast\n\n  let ?f = \"f\\<^sub>2 \\<circ> f\\<^sub>1\"\n  have \"bij_betw ?f (uverts G\\<^sub>1) (uverts G\\<^sub>3)\"\n    using bij by (simp add: bij_betw_comp_iff)\n  moreover have \"G\\<^sub>3 = map_ugraph ?f G\\<^sub>1\"\n    using map by (simp add: map_ugraph_trans)\n  moreover have \"uwellformed G\\<^sub>1\" \"uwellformed G\\<^sub>3\"\n    using assms unfolding isomorphism_def by simp+\n  ultimately show \"G\\<^sub>1 \\<simeq> G\\<^sub>3\"\n    unfolding isomorphism_def by blast\nqed\n\nlemma isomorphic_sym:\n  assumes \"G\\<^sub>1 \\<simeq> G\\<^sub>2\"\n  shows \"G\\<^sub>2 \\<simeq> G\\<^sub>1\"\nproof safe\n  from assms obtain f where \"isomorphism G\\<^sub>1 G\\<^sub>2 f\"\n    by blast\n  hence bij: \"bij_betw f (uverts G\\<^sub>1) (uverts G\\<^sub>2)\" and map: \"G\\<^sub>2 = map_ugraph f G\\<^sub>1\"\n    unfolding isomorphism_def by auto\n\n  let ?f' = \"inv_into (uverts G\\<^sub>1) f\"\n  have bij': \"bij_betw ?f' (uverts G\\<^sub>2) (uverts G\\<^sub>1)\"\n    by (rule bij_betw_inv_into) fact\n  moreover have \"uverts G\\<^sub>1 = ?f' ` uverts G\\<^sub>2\"\n    using bij' unfolding bij_betw_def by force\n  moreover have \"uedges G\\<^sub>1 = (\\<lambda>e. ?f' ` e) ` uedges G\\<^sub>2\"\n    proof -\n      have \"uedges G\\<^sub>1 = id ` uedges G\\<^sub>1\"\n        by simp\n      also have \"\\<dots> = (\\<lambda>e. ?f' ` (f ` e)) ` uedges G\\<^sub>1\"\n        proof (rule image_cong)\n          fix a\n          assume \"a \\<in> uedges G\\<^sub>1\"\n          hence \"a \\<subseteq> uverts G\\<^sub>1\"\n            using assms unfolding isomorphism_def uwellformed_def by blast\n          thus \"id a = inv_into (uverts G\\<^sub>1) f ` f ` a\"\n            by (metis (full_types) id_def bij bij_betw_imp_inj_on inv_into_image_cancel)\n        qed simp\n      also have \"\\<dots> = (\\<lambda>e. ?f' ` e) ` ((\\<lambda>e. f ` e) ` uedges G\\<^sub>1)\"\n        by (rule image_image[symmetric])\n      also have \"\\<dots> = (\\<lambda>e. ?f' ` e) ` uedges G\\<^sub>2\"\n        using bij map by (metis map_ugraph.simps prod.collapse snd_eqD)\n      finally show ?thesis\n        .\n    qed\n  ultimately have \"isomorphism G\\<^sub>2 G\\<^sub>1 ?f'\"\n    unfolding isomorphism_def by (metis map_ugraph.simps split_pairs)\n  thus \"\\<exists>f. isomorphism G\\<^sub>2 G\\<^sub>1 f\"\n    by blast\nqed (auto simp: assms)\n\nlemma isomorphic_cards:\n  assumes \"G\\<^sub>1 \\<simeq> G\\<^sub>2\"\n  shows\n    \"card (uverts G\\<^sub>1) = card (uverts G\\<^sub>2)\" (is \"?V\")\n    \"card (uedges G\\<^sub>1) = card (uedges G\\<^sub>2)\" (is \"?E\")\nproof -\n  from assms obtain f where\n    bij: \"bij_betw f (uverts G\\<^sub>1) (uverts G\\<^sub>2)\" and\n    map: \"G\\<^sub>2 = map_ugraph f G\\<^sub>1\"\n    unfolding isomorphism_def by blast\n  from assms have wellformed: \"uwellformed G\\<^sub>1\" \"uwellformed G\\<^sub>2\"\n    by simp+\n\n  show ?V\n    by (rule bij_betw_same_card[OF bij])\n\n  let ?g = \"\\<lambda>e. f ` e\"\n  have \"bij_betw ?g (Pow (uverts G\\<^sub>1)) (Pow (uverts G\\<^sub>2))\"\n    by (rule bij_lift[OF bij])\n  moreover have \"uedges G\\<^sub>1 \\<subseteq> Pow (uverts G\\<^sub>1)\"\n    using wellformed(1) unfolding uwellformed_def by blast\n  ultimately have \"card (?g ` uedges G\\<^sub>1) = card (uedges G\\<^sub>1)\"\n    unfolding bij_betw_def by (metis card_inj_subs)\n  thus ?E\n    by (metis map map_ugraph.simps snd_conv surjective_pairing)\nqed\n\nsubsection\\<open>Isomorphic subgraphs\\<close>\n\ntext\\<open>The somewhat sloppy term `isomorphic subgraph' denotes a subgraph which is isomorphic to a\nfixed other graph. For example, saying that a graph contains a triangle usually means that it\ncontains \\emph{any} triangle, not the specific triangle with the nodes $1$, $2$ and $3$. Hence, such\na graph would have a triangle as an isomorphic subgraph.\\<close>\n\ndefinition subgraph_isomorphic :: \"ugraph \\<Rightarrow> ugraph \\<Rightarrow> bool\" (\"_ \\<sqsubseteq> _\") where\n\"G' \\<sqsubseteq> G \\<equiv> uwellformed G \\<and> (\\<exists>G''. G' \\<simeq> G'' \\<and> subgraph G'' G)\"\n\nlemma subgraph_is_subgraph_isomorphic: \"\\<lbrakk> uwellformed G'; uwellformed G; subgraph G' G \\<rbrakk> \\<Longrightarrow> G' \\<sqsubseteq> G\"\nunfolding subgraph_isomorphic_def\nby (metis isomorphic_refl)\n\nlemma isomorphic_is_subgraph_isomorphic: \"G\\<^sub>1 \\<simeq> G\\<^sub>2 \\<Longrightarrow> G\\<^sub>1 \\<sqsubseteq> G\\<^sub>2\"\nunfolding subgraph_isomorphic_def\nby (metis subgraph_refl)\n\nlemma subgraph_isomorphic_refl: \"uwellformed G \\<Longrightarrow> G \\<sqsubseteq> G\"\nunfolding subgraph_isomorphic_def\nby (metis isomorphic_refl subgraph_refl)\n\nlemma subgraph_isomorphic_pre_iso_closed:\n  assumes \"G\\<^sub>1 \\<simeq> G\\<^sub>2\" and \"G\\<^sub>2 \\<sqsubseteq> G\\<^sub>3\"\n  shows \"G\\<^sub>1 \\<sqsubseteq> G\\<^sub>3\"\nunfolding subgraph_isomorphic_def\nproof\n  show \"uwellformed G\\<^sub>3\"\n    using assms unfolding subgraph_isomorphic_def by blast\nnext\n  from assms(2) obtain G\\<^sub>2' where \"G\\<^sub>2 \\<simeq> G\\<^sub>2'\" \"subgraph G\\<^sub>2' G\\<^sub>3\"\n    unfolding subgraph_isomorphic_def by blast\n  moreover with assms(1) have \"G\\<^sub>1 \\<simeq> G\\<^sub>2'\"\n    by (metis isomorphic_trans)\n  ultimately show \"\\<exists>G''. G\\<^sub>1 \\<simeq> G'' \\<and> subgraph G'' G\\<^sub>3\"\n    by blast\nqed\n\nlemma subgraph_isomorphic_pre_subgraph_closed:\n  assumes \"uwellformed G\\<^sub>1\" and \"subgraph G\\<^sub>1 G\\<^sub>2\" and \"G\\<^sub>2 \\<sqsubseteq> G\\<^sub>3\"\n  shows \"G\\<^sub>1 \\<sqsubseteq> G\\<^sub>3\"\nunfolding subgraph_isomorphic_def\nproof\n  show \"uwellformed G\\<^sub>3\"\n    using assms unfolding subgraph_isomorphic_def by blast\nnext\n  from assms(3) obtain G\\<^sub>2' where \"G\\<^sub>2 \\<simeq> G\\<^sub>2'\" \"subgraph G\\<^sub>2' G\\<^sub>3\"\n    unfolding subgraph_isomorphic_def by blast\n  then obtain f where bij: \"bij_betw f (uverts G\\<^sub>2) (uverts G\\<^sub>2')\" \"G\\<^sub>2' = map_ugraph f G\\<^sub>2\"\n    unfolding isomorphism_def by blast\n  let ?G\\<^sub>1' = \"map_ugraph f G\\<^sub>1\"\n\n  have \"bij_betw f (uverts G\\<^sub>1) (f ` uverts G\\<^sub>1)\"\n    using bij(1) assms(2) unfolding subgraph_def by (auto intro: bij_betw_subset)\n  moreover hence \"uwellformed ?G\\<^sub>1'\"\n    using map_ugraph_wellformed[OF assms(1)] unfolding bij_betw_def ..\n  ultimately have \"G\\<^sub>1 \\<simeq> ?G\\<^sub>1'\"\n    using assms(1) unfolding isomorphism_def by (metis map_ugraph.simps fst_conv surjective_pairing)\n  moreover have \"subgraph ?G\\<^sub>1' G\\<^sub>3\" (* Yes, I will TOTALLY understand that step tomorrow. *)\n    using subgraph_trans[OF map_ugraph_preserves_sub[OF assms(2)]] bij(2) \\<open>subgraph G\\<^sub>2' G\\<^sub>3\\<close> by simp\n  ultimately show \"\\<exists>G''. G\\<^sub>1 \\<simeq> G'' \\<and> subgraph G'' G\\<^sub>3\"\n    by blast\nqed\n\nlemmas subgraph_isomorphic_pre_closed = subgraph_isomorphic_pre_subgraph_closed subgraph_isomorphic_pre_iso_closed\n\n\n\n\n\nlemmas subgraph_isomorphic_post_closed = subgraph_isomorphic_post_iso_closed\n\nlemmas subgraph_isomorphic_closed = subgraph_isomorphic_pre_closed subgraph_isomorphic_post_closed\n\nsubsection\\<open>Density\\<close>\n\ntext\\<open>The density of a graph is the quotient of the number of edges and the number of vertices of\na graph.\\<close>\n\ndefinition density :: \"ugraph \\<Rightarrow> real\" where\n\"density G = card (uedges G) / card (uverts G)\"\n\ntext\\<open>The maximum density of a graph is the density of its densest nonempty subgraph.\\<close>\n\ndefinition max_density :: \"ugraph \\<Rightarrow> real\" where\n\"max_density G = Lattices_Big.Max (density ` nonempty_subgraphs G)\"\n\ntext\\<open>We prove some obvious results about the maximum density, such as that there is a subgraph\nwhich has the maximum density and that the (maximum) density is preserved by isomorphisms. The\nproofs are a bit complicated by the fact that most facts about @{term Lattices_Big.Max} require\nnon-emptiness of the target set, but we need that anyway to get a value out of it.\\<close>\n\n\n\nlemma max_density_is_max:\n  assumes \"finite_graph G\" and \"finite_graph G'\" and \"nonempty_graph G'\" and \"uwellformed G'\" and \"subgraph G' G\"\n  shows \"density G' \\<le> max_density G\"\nunfolding max_density_def\nproof (rule Max_ge)\n  show \"finite (density ` nonempty_subgraphs G)\"\n    using assms(1) by (simp add: nonempty_subgraphs_finite)\nnext\n  show \"density G' \\<in> density ` nonempty_subgraphs G\"\n    unfolding nonempty_subgraphs_def using assms by blast\nqed\n\nlemma max_density_gr_zero:\n  assumes \"finite_graph G\" and \"nonempty_graph G\" and \"uwellformed G\"\n  shows \"0 < max_density G\"\nproof -\n  have \"0 < card (uverts G)\" \"0 < card (uedges G)\"\n    using assms unfolding finite_graph_def nonempty_graph_def by auto\n  hence \"0 < density G\"\n    unfolding density_def by simp\n  also have \"density G \\<le> max_density G\"\n    using assms by (simp add: max_density_is_max subgraph_refl)\n  finally show ?thesis\n    .\nqed\n\nlemma isomorphic_density:\n  assumes \"G\\<^sub>1 \\<simeq> G\\<^sub>2\"\n  shows \"density G\\<^sub>1 = density G\\<^sub>2\"\nunfolding density_def\nusing isomorphic_cards[OF assms]\nby simp\n\nlemma isomorphic_max_density:\n  assumes \"G\\<^sub>1 \\<simeq> G\\<^sub>2\" and \"nonempty_graph G\\<^sub>1\" and \"nonempty_graph G\\<^sub>2\" and \"finite_graph G\\<^sub>1\" and \"finite_graph G\\<^sub>2\"\n  shows \"max_density G\\<^sub>1 = max_density G\\<^sub>2\"\nproof -\n  \\<comment> \\<open>The proof strategy is not completely straightforward. We first show that if two graphs are\n       isomorphic, the maximum density of one graph is less or equal than the maximum density of\n       the other graph. The reason is that this proof is quite long and the desired result directly\n       follows from the symmetry of the isomorphism relation.\\footnote{Some famous mathematician\n       once said that if you prove that $a \\le b$ and $b \\le a$, you know \\emph{that} these\n       numbers are equal, but not \\emph{why}. Since many proofs in this work are mostly opaque to\n       me, I can live with that.}\\<close>\n  {\n    fix A B\n    assume A: \"nonempty_graph A\" \"finite_graph A\"\n    assume iso: \"A \\<simeq> B\"\n\n    then obtain f where f: \"B = map_ugraph f A\" \"bij_betw f (uverts A) (uverts B)\"\n      unfolding isomorphism_def by blast\n    have wellformed: \"uwellformed A\"\n      using iso unfolding isomorphism_def by simp\n    \\<comment> \\<open>We observe that the set of densities of the subgraphs does not change if we map the\n         subgraphs first.\\<close>\n    have \"density ` nonempty_subgraphs A = density ` (map_ugraph f ` nonempty_subgraphs A)\"\n      proof (rule image_comp_cong)\n        fix G\n        assume \"G \\<in> nonempty_subgraphs A\"\n        hence \"uverts G \\<subseteq> uverts A\" \"uwellformed G\"\n          unfolding nonempty_subgraphs_def subgraph_def by simp+\n        hence \"inj_on f (uverts G)\"\n          using f(2) unfolding bij_betw_def by (metis subset_inj_on)\n        hence \"G \\<simeq> map_ugraph f G\"\n          unfolding isomorphism_def bij_betw_def\n          by (metis map_ugraph.simps fst_conv surjective_pairing map_ugraph_wellformed \\<open>uwellformed G\\<close>)\n        thus \"density G = density (map_ugraph f G)\"\n          by (fact isomorphic_density)\n      qed\n    \\<comment> \\<open>Additionally, we show that the operations @{term nonempty_subgraphs} and @{term map_ugraph}\n         can be swapped without changing the densities. This is an obvious result, because\n         @{term map_ugraph} does not change the structure of a graph. Still, the proof is a bit\n         hairy, which is why we only show inclusion in one direction and use symmetry of isomorphism\n         later.\\<close>\n    also have \"\\<dots> \\<subseteq> density ` nonempty_subgraphs (map_ugraph f A)\"\n      proof (rule image_mono, rule subsetI)\n        fix G''\n        assume \"G'' \\<in> map_ugraph f ` nonempty_subgraphs A\"\n        then obtain G' where G_subst: \"G'' = map_ugraph f G'\" \"G' \\<in> nonempty_subgraphs A\"\n          by blast\n        hence G': \"subgraph G' A\" \"nonempty_graph G'\" \"uwellformed G'\"\n          unfolding nonempty_subgraphs_def by auto\n        hence \"inj_on f (uverts G')\"\n          using f unfolding bij_betw_def subgraph_def by (metis subset_inj_on)\n        hence \"uwellformed G''\"\n          using map_ugraph_wellformed G' G_subst by simp\n        moreover have \"nonempty_graph G''\"\n          using G' G_subst unfolding nonempty_graph_def by (metis map_ugraph.simps fst_conv snd_conv surjective_pairing empty_is_image)\n        moreover have \"subgraph G'' (map_ugraph f A)\"\n          using map_ugraph_preserves_sub G' G_subst by simp\n        ultimately show \"G'' \\<in> nonempty_subgraphs (map_ugraph f A)\"\n          unfolding nonempty_subgraphs_def by simp\n      qed\n    finally have \"density ` nonempty_subgraphs A \\<subseteq> density ` nonempty_subgraphs (map_ugraph f A)\"\n      .\n    hence \"max_density A \\<le> max_density (map_ugraph f A)\"\n      unfolding max_density_def\n      proof (rule Max_mono)\n        have \"A \\<in> nonempty_subgraphs A\"\n          using A iso unfolding nonempty_subgraphs_def by (simp add: subgraph_refl)\n        thus \"density ` nonempty_subgraphs A \\<noteq> {}\"\n          by blast\n      next\n        have \"finite (nonempty_subgraphs (map_ugraph f A))\"\n          by (rule nonempty_subgraphs_finite[OF map_ugraph_finite[OF A(2)]])\n        thus \"finite (density ` nonempty_subgraphs (map_ugraph f A))\"\n          by blast\n      qed\n    hence \"max_density A \\<le> max_density B\"\n      by (subst f)\n  }\n  note le = this\n\n  show ?thesis\n    using le[OF assms(2) assms(4) assms(1)] le[OF assms(3) assms(5) isomorphic_sym[OF assms(1)]]\n    by (fact antisym)\nqed\n\nsubsection\\<open>Fixed selectors\\<close>\n\ntext\\<open>\\label{sec:selector}\nIn the proof of the main theorem in the lecture notes, the concept of a ``fixed copy'' of a graph is\nfundamental.\n\nLet $H$ be a fixed graph. A `fixed selector' is basically a function mapping a set with the same\nsize as the vertex set of $H$ to a new graph which is isomorphic to $H$ and its vertex set is the\nsame as the input set.\\footnote{We call such a selector \\emph{fixed} because its result is\ndeterministic.}\\<close>\n\ndefinition \"is_fixed_selector H f = (\\<forall>V. finite V \\<and> card (uverts H) = card V \\<longrightarrow> H \\<simeq> f V \\<and> uverts (f V) = V)\"\n\ntext\\<open>Obviously, there may be many possible fixed selectors for a given graph. First, we show\nthat there is always at least one. This is sufficient, because we can always obtain that one and\nuse its properties without knowing exactly which one we chose.\\<close>\n\nlemma ex_fixed_selector:\n  assumes \"uwellformed H\" and \"finite_graph H\"\n  obtains f where \"is_fixed_selector H f\"\nproof\n  \\<comment> \\<open>I guess this is the only place in the whole work where we make use of a nifty little HOL\n       feature called \\emph{SOME}, which is basically Hilbert's choice operator. The reason is that\n       any bijection between the the vertex set of @{term H} and the input set gives rise to a\n       fixed selector function. In the lecture notes, a specific bijection was defined, but this\n       is shorter and more elegant.\\<close>\n  let ?bij = \"\\<lambda>V. SOME g. bij_betw g (uverts H) V\"\n  let ?f = \"\\<lambda>V. map_ugraph (?bij V) H\"\n  {\n    fix V :: \"uvert set\"\n    assume \"finite V\" \"card (uverts H) = card V\"\n    moreover have \"finite (uverts H)\"\n      using assms unfolding finite_graph_def by simp\n    ultimately have \"bij_betw (?bij V) (uverts H) V\"\n      by (metis finite_same_card_bij someI_ex)\n    moreover hence *: \"uverts (?f V) = V \\<and> uwellformed (?f V)\"\n      using map_ugraph_wellformed[OF assms(1)]\n      by (metis bij_betw_def map_ugraph.simps fst_conv surjective_pairing)\n    ultimately have **: \"H \\<simeq> ?f V\"\n      unfolding isomorphism_def using assms(1) by auto\n    note * **\n  }\n  thus \"is_fixed_selector H ?f\"\n    unfolding is_fixed_selector_def by blast\nqed\n\nlemma fixed_selector_induced_subgraph:\n  assumes \"is_fixed_selector H f\" and \"card (uverts H) = card V\" and \"finite V\"\n  assumes sub: \"subgraph (f V) (induced_subgraph V G)\" and V: \"V \\<subseteq> uverts G\" and G: \"uwellformed G\"\n  shows \"H \\<sqsubseteq> G\"\nproof -\n  have post: \"H \\<simeq> f V\" \"uverts (f V) = V\"\n    using assms unfolding is_fixed_selector_def by auto\n\n  have \"H \\<sqsubseteq> f V\"\n    by (rule isomorphic_is_subgraph_isomorphic)\n       (simp add: post)\n  also have \"f V \\<sqsubseteq> induced_subgraph V G\"\n    by (rule subgraph_is_subgraph_isomorphic)\n       (auto simp: induced_wellformed[OF G V] post sub)\n  also have \"\\<dots> \\<sqsubseteq> G\"\n    by (rule subgraph_is_subgraph_isomorphic[OF induced_wellformed])\n       (auto simp: G V induced_is_subgraph(1)[OF V])\n  finally show \"H \\<sqsubseteq> G\"\n    .\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Random_Graph_Subgraph_Threshold/Ugraph_Lemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8688267813328976, "lm_q1q2_score": 0.7774170420540318}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_bin_nat_plus\nimports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Bin = One | ZeroAnd \"Bin\" | OneAnd \"Bin\"\n\nfun s :: \"Bin => Bin\" where\n\"s (One) = ZeroAnd One\"\n| \"s (ZeroAnd xs) = OneAnd xs\"\n| \"s (OneAnd ys) = ZeroAnd (s ys)\"\n\nfun plus2 :: \"Bin => Bin => Bin\" where\n\"plus2 (One) y = s y\"\n| \"plus2 (ZeroAnd z) (One) = s (ZeroAnd z)\"\n| \"plus2 (ZeroAnd z) (ZeroAnd ys) = ZeroAnd (plus2 z ys)\"\n| \"plus2 (ZeroAnd z) (OneAnd xs) = OneAnd (plus2 z xs)\"\n| \"plus2 (OneAnd x2) (One) = s (OneAnd x2)\"\n| \"plus2 (OneAnd x2) (ZeroAnd zs) = OneAnd (plus2 x2 zs)\"\n| \"plus2 (OneAnd x2) (OneAnd ys2) = ZeroAnd (s (plus2 x2 ys2))\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun toNat :: \"Bin => Nat\" where\n\"toNat (One) = S Z\"\n| \"toNat (ZeroAnd xs) = plus (toNat xs) (toNat xs)\"\n| \"toNat (OneAnd ys) = plus (plus (S Z) (toNat ys)) (toNat ys)\"\n\ntheorem property0 :\n  \"((toNat (plus2 x y)) = (plus (toNat x) (toNat y)))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_bin_nat_plus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7773825589661395}}
{"text": "(*  Title:      CCL/Gfp.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection \\<open>Greatest fixed points\\<close>\n\ntheory Gfp\nimports Lfp\nbegin\n\ndefinition\n  gfp :: \"['a set\\<Rightarrow>'a set] \\<Rightarrow> 'a set\" where \\<comment> \\<open>greatest fixed point\\<close>\n  \"gfp(f) == Union({u. u <= f(u)})\"\n\n(* gfp(f) is the least upper bound of {u. u <= f(u)} *)\n\nlemma gfp_upperbound: \"A <= f(A) \\<Longrightarrow> A <= gfp(f)\"\n  unfolding gfp_def by blast\n\nlemma gfp_least: \"(\\<And>u. u <= f(u) \\<Longrightarrow> u <= A) \\<Longrightarrow> gfp(f) <= A\"\n  unfolding gfp_def by blast\n\nlemma gfp_lemma2: \"mono(f) \\<Longrightarrow> gfp(f) <= f(gfp(f))\"\n  by (rule gfp_least, rule subset_trans, assumption, erule monoD,\n    rule gfp_upperbound, assumption)\n\nlemma gfp_lemma3: \"mono(f) \\<Longrightarrow> f(gfp(f)) <= gfp(f)\"\n  by (rule gfp_upperbound, frule monoD, rule gfp_lemma2, assumption+)\n\nlemma gfp_Tarski: \"mono(f) \\<Longrightarrow> gfp(f) = f(gfp(f))\"\n  by (rule equalityI gfp_lemma2 gfp_lemma3 | assumption)+\n\n\n(*** Coinduction rules for greatest fixed points ***)\n\n(*weak version*)\nlemma coinduct: \"\\<lbrakk>a: A;  A <= f(A)\\<rbrakk> \\<Longrightarrow> a : gfp(f)\"\n  by (blast dest: gfp_upperbound)\n\nlemma coinduct2_lemma: \"\\<lbrakk>A <= f(A) Un gfp(f); mono(f)\\<rbrakk> \\<Longrightarrow> A Un gfp(f) <= f(A Un gfp(f))\"\n  apply (rule subset_trans)\n   prefer 2\n   apply (erule mono_Un)\n  apply (rule subst, erule gfp_Tarski)\n  apply (erule Un_least)\n  apply (rule Un_upper2)\n  done\n\n(*strong version, thanks to Martin Coen*)\nlemma coinduct2: \"\\<lbrakk>a: A; A <= f(A) Un gfp(f); mono(f)\\<rbrakk> \\<Longrightarrow> a : gfp(f)\"\n  apply (rule coinduct)\n   prefer 2\n   apply (erule coinduct2_lemma, assumption)\n  apply blast\n  done\n\n(***  Even Stronger version of coinduct  [by Martin Coen]\n         - instead of the condition  A <= f(A)\n                           consider  A <= (f(A) Un f(f(A)) ...) Un gfp(A) ***)\n\nlemma coinduct3_mono_lemma: \"mono(f) \\<Longrightarrow> mono(\\<lambda>x. f(x) Un A Un B)\"\n  by (rule monoI) (blast dest: monoD)\n\nlemma coinduct3_lemma:\n  assumes prem: \"A <= f(lfp(\\<lambda>x. f(x) Un A Un gfp(f)))\"\n    and mono: \"mono(f)\"\n  shows \"lfp(\\<lambda>x. f(x) Un A Un gfp(f)) <= f(lfp(\\<lambda>x. f(x) Un A Un gfp(f)))\"\n  apply (rule subset_trans)\n   apply (rule mono [THEN coinduct3_mono_lemma, THEN lfp_lemma3])\n  apply (rule Un_least [THEN Un_least])\n    apply (rule subset_refl)\n   apply (rule prem)\n  apply (rule mono [THEN gfp_Tarski, THEN equalityD1, THEN subset_trans])\n  apply (rule mono [THEN monoD])\n  apply (subst mono [THEN coinduct3_mono_lemma, THEN lfp_Tarski])\n  apply (rule Un_upper2)\n  done\n\nlemma coinduct3:\n  assumes 1: \"a:A\"\n    and 2: \"A <= f(lfp(\\<lambda>x. f(x) Un A Un gfp(f)))\"\n    and 3: \"mono(f)\"\n  shows \"a : gfp(f)\"\n  apply (rule coinduct)\n   prefer 2\n   apply (rule coinduct3_lemma [OF 2 3])\n  apply (subst lfp_Tarski [OF coinduct3_mono_lemma, OF 3])\n  using 1 apply blast\n  done\n\n\nsubsection \\<open>Definition forms of \\<open>gfp_Tarski\\<close>, to control unfolding\\<close>\n\nlemma def_gfp_Tarski: \"\\<lbrakk>h == gfp(f); mono(f)\\<rbrakk> \\<Longrightarrow> h = f(h)\"\n  apply unfold\n  apply (erule gfp_Tarski)\n  done\n\nlemma def_coinduct: \"\\<lbrakk>h == gfp(f); a:A; A <= f(A)\\<rbrakk> \\<Longrightarrow> a: h\"\n  apply unfold\n  apply (erule coinduct)\n  apply assumption\n  done\n\nlemma def_coinduct2: \"\\<lbrakk>h == gfp(f); a:A; A <= f(A) Un h; mono(f)\\<rbrakk> \\<Longrightarrow> a: h\"\n  apply unfold\n  apply (erule coinduct2)\n   apply assumption\n  apply assumption\n  done\n\nlemma def_coinduct3: \"\\<lbrakk>h == gfp(f); a:A; A <= f(lfp(\\<lambda>x. f(x) Un A Un h)); mono(f)\\<rbrakk> \\<Longrightarrow> a: h\"\n  apply unfold\n  apply (erule coinduct3)\n   apply assumption\n  apply assumption\n  done\n\n(*Monotonicity of gfp!*)\nlemma gfp_mono: \"\\<lbrakk>mono(f); \\<And>Z. f(Z) <= g(Z)\\<rbrakk> \\<Longrightarrow> gfp(f) <= gfp(g)\"\n  apply (rule gfp_upperbound)\n  apply (rule subset_trans)\n   apply (rule gfp_lemma2)\n   apply assumption\n  apply (erule meta_spec)\n  done\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/CCL/Gfp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7773525458778064}}
{"text": "section \\<open> Function.thy \\<close>\n\ntheory Function\n  imports Main\nbegin\n\n(* Types *)\n\nrecord ('x, 'y) Function =\n  cod :: \"'y set\"\n  func :: \"('x \\<times> 'y) set\"\n\ndefinition dom :: \"('x, 'y) Function \\<Rightarrow> 'x set\" where\n \"dom f \\<equiv> {x. \\<exists>y. (x, y) \\<in> func f}\"\n\ndefinition valid_map :: \"('x, 'y) Function \\<Rightarrow> bool\" where\n\"valid_map f \\<equiv>\n  let\n      welldefined = \\<forall>x y. (x, y) \\<in> func f \\<longrightarrow> y \\<in> cod f;\n      deterministic = \\<forall>x y y'. (x, y) \\<in> func f \\<and> (x, y') \\<in> func f \\<longrightarrow> y = y';\n      total = (\\<forall>x. x \\<in> dom f \\<longrightarrow> (\\<exists>y. (x, y) \\<in> func f))\n\n  in welldefined \\<and> deterministic \\<and> total\"\n\n(* Validity *)\n\nlemma dom : \"(x, y) \\<in> func f \\<Longrightarrow> x \\<in> dom f\" \n  unfolding dom_def\n  by blast\n\nlemma valid_map_welldefined : \"valid_map f \\<Longrightarrow> (x, y) \\<in> func f \\<Longrightarrow> y \\<in> cod f\"\n  by (simp add: valid_map_def) \n\nlemma valid_map_deterministic : \"valid_map f \\<Longrightarrow> (x, y) \\<in> func f \\<Longrightarrow> (x, y') \\<in> func f \\<Longrightarrow> y = y'\"\n  by (simp add: valid_map_def) \n\nlemma valid_map_total : \"valid_map f \\<Longrightarrow> x \\<in> dom f \\<Longrightarrow> \\<exists>y. (x, y) \\<in> func f\"\n  by (simp add: valid_map_def) \n\nlemma valid_mapI [intro] : \"((\\<And>x y. (x, y) \\<in> func f \\<Longrightarrow>  x \\<in> dom f \\<and> y \\<in> cod f) \\<Longrightarrow>\n                   (\\<And>x y y'. (x, y) \\<in> func f \\<Longrightarrow> (x, y') \\<in> func f \\<Longrightarrow> y = y') \\<Longrightarrow>\n                   (\\<And>x. x \\<in> dom f \\<Longrightarrow> (\\<exists>y. (x, y) \\<in> func f))\n                   \\<Longrightarrow> valid_map f) \"\n  by (metis valid_map_def)\n\nlemma valid_map_eqI: \"cod f = cod g \\<Longrightarrow> dom f = dom g \\<Longrightarrow> func f = func g \\<Longrightarrow> (f :: ('x, 'y) Function) = g\"\n  by simp\n\n(* Function application *)\n\ndefinition \"Function_app_undefined_arg_not_in_domain _ \\<equiv> undefined\"\n\ndefinition app :: \"('x, 'y) Function \\<Rightarrow> 'x \\<Rightarrow> 'y\" (infixr \"\\<cdot>\" 998) where\n\"app f x \\<equiv> \n   if x \\<in> dom f\n   then  (THE y. (x, y) \\<in> func f)\n  else Function_app_undefined_arg_not_in_domain x\" \n\nlemma fun_app : \"valid_map f \\<Longrightarrow> x \\<in> dom f \\<Longrightarrow> (x, f \\<cdot> x) \\<in> func f\"\n  by (metis (no_types, lifting) app_def theI' valid_map_def)  \n\nlemma fun_app2 : \"valid_map f \\<Longrightarrow> x \\<in> dom f \\<Longrightarrow> f \\<cdot> x  \\<in> cod f\"\n  by (meson fun_app valid_map_welldefined)\n\nlemma fun_app3 [simp] : \"x \\<in> dom f \\<Longrightarrow> f \\<cdot> x = (THE y. (x, y) \\<in> func f) \"\n  by (simp add: app_def)\n\nlemma fun_ext_raw : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom f = dom g \\<Longrightarrow> cod f = cod g \\<Longrightarrow> (\\<And>x. x \\<in> dom f \\<Longrightarrow> f \\<cdot> x = g \\<cdot> x) \\<Longrightarrow> func f = func g\"\n  by (metis dom fun_app pred_equals_eq2 valid_map_deterministic)\n\nlemma fun_ext : \"valid_map f \\<Longrightarrow> valid_map g \\<Longrightarrow> dom f = dom g \\<Longrightarrow> cod f = cod g \\<Longrightarrow> (\\<And>x. x \\<in> dom f \\<Longrightarrow> f \\<cdot> x = g \\<cdot> x) \\<Longrightarrow> f = g\"\n  by (metis (full_types) equality fun_ext_raw old.unit.exhaust)\n\nlemma fun_app_iff : \"valid_map f \\<Longrightarrow> (x, y) \\<in> func f \\<Longrightarrow> (f \\<cdot> x) = y\"\n  by (meson valid_map_deterministic fun_app dom) \n\n(* Composition of functions *)\n\ndefinition \"Function_compose_undefined_incomposable _ _ \\<equiv> undefined\"\n\ndefinition compose :: \"('y, 'z) Function \\<Rightarrow> ('x, 'y) Function \\<Rightarrow> ('x, 'z) Function\"  (infixl \"\\<bullet>\" 55) \n  where\n  \"compose g f \\<equiv>\n    if dom g = cod f\n    then \\<lparr> cod = cod g, func = relcomp (func f) (func g) \\<rparr>\n    else Function_compose_undefined_incomposable g f\"\n\nlemma compose_welldefined_cod : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (x, y) \\<in> func (g \\<bullet> f) \\<Longrightarrow> y \\<in> cod g\"\n  by (metis compose_def relcompEpair select_convs(2) valid_map_def)\n\nlemma compose_welldefined_dom : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (x, y) \\<in> func (g \\<bullet> f) \\<Longrightarrow> x \\<in> dom f\"\n  by (metis compose_def dom relcomp.cases select_convs(2))\n\nlemma compose_welldefined : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (x, y) \\<in> func (g \\<bullet> f) \\<Longrightarrow> x \\<in> dom f \\<and> y \\<in> cod g\"\n  by (simp add: compose_welldefined_cod compose_welldefined_dom)\n\nlemma compose_deterministic : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (x, y) \\<in> func (g \\<bullet> f) \\<Longrightarrow> (x, y') \\<in> func (g \\<bullet> f) \\<Longrightarrow> y = y'\"\n  by (smt (verit, ccfv_threshold) compose_def valid_map_deterministic relcomp.simps select_convs(2))\n\nlemma compose_total : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> x \\<in> dom f \\<Longrightarrow> \\<exists>y. (x, y) \\<in> func (g \\<bullet> f)\"\n  by (metis (no_types, opaque_lifting) compose_def relcomp.simps select_convs(2) valid_map_total valid_map_welldefined)\n\nlemma compose_valid : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> valid_map (g \\<bullet> f)\"\n  by (smt (verit) CollectD Function.dom_def compose_def compose_deterministic compose_welldefined_cod select_convs(1) valid_map_def)\n\nlemma cod_compose [simp] : \"dom g = cod f \\<Longrightarrow> cod (g \\<bullet> f) = cod g\"\n  by (simp add: compose_def)\n\nlemma dom_compose [simp] : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> dom (g \\<bullet> f) = dom f\"\n  by (smt (verit) Collect_cong Function.dom_def compose_total compose_welldefined_dom mem_Collect_eq)\n  \nlemma compose_assoc : \"valid_map h \\<Longrightarrow> valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> dom h = cod g \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (h \\<bullet> g) \\<bullet> f = h \\<bullet> (g \\<bullet> f)\"\n  by (smt (verit, ccfv_SIG) O_assoc cod_compose cod_compose compose_def compose_def compose_def compose_def dom_compose select_convs(2) select_convs(2))\n\nlemma compose_app [simp] : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> (x, y) \\<in> func f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (y, z) \\<in> func g \n \\<Longrightarrow> (g \\<bullet> f) \\<cdot> x = z\"\n  unfolding valid_map_def compose_def dom_def app_def\n  apply (simp add: Let_def)\n  apply clarsimp\n  apply safe\n  apply (smt (verit) relcomp.simps the_equality)\n  by (meson relcomp.relcompI)\n\nlemma compose_app_assoc : \"valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> x \\<in> dom f \\<Longrightarrow> dom g = cod f \\<Longrightarrow> (g \\<bullet> f) \\<cdot> x = g \\<cdot> (f \\<cdot> x)\"\n  by (metis compose_app fun_app fun_app2)\n\n(* Properties *)\n\nabbreviation is_surjective :: \"('x, 'y) Function \\<Rightarrow> bool\" where\n\"is_surjective f \\<equiv> \\<forall> y . y \\<in> cod f \\<longrightarrow> (\\<exists> x . x \\<in> dom f \\<and> f \\<cdot> x = y)\"\n\nabbreviation is_injective :: \"('x, 'y) Function \\<Rightarrow> bool\" where\n\"is_injective f \\<equiv> \\<forall>x x' . x \\<in> dom f \\<longrightarrow> x' \\<in> dom f \\<longrightarrow> f \\<cdot> x = f \\<cdot> x' \\<longrightarrow> x = x'\"\n\nabbreviation is_bijective :: \"('x, 'y) Function \\<Rightarrow> bool\" where\n\"is_bijective f \\<equiv> is_surjective f \\<and> is_injective f\"\n\nlemma surjection_is_right_cancellative : \"valid_map h \\<Longrightarrow> valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> is_surjective f \\<Longrightarrow> cod f = dom g \\<Longrightarrow> cod f = dom h\n \\<Longrightarrow> g \\<bullet> f = h \\<bullet> f \\<Longrightarrow> g = h\"\n  by (metis cod_compose compose_app_assoc fun_ext) \n\nlemma injection_is_left_cancellative : \"valid_map h \\<Longrightarrow> valid_map g \\<Longrightarrow> valid_map f \\<Longrightarrow> is_injective f \\<Longrightarrow> cod g = dom f \\<Longrightarrow> cod h = dom f \n \\<Longrightarrow> f \\<bullet> g = f \\<bullet> h \\<Longrightarrow> g = h\"\n  by (metis compose_app_assoc dom_compose fun_app2 fun_ext) \n\n(* Identity functions *)\n\ndefinition ident :: \"'x set \\<Rightarrow> ('x, 'x) Function\" where\n\"ident X \\<equiv>  \\<lparr> cod = X, func = Id_on X \\<rparr>\"\n\nlemma ident_valid : \"valid_map (ident X)\"\n  by (simp add: Function.dom_def Id_on_iff ident_def valid_map_def) \n\nlemma ident_dom [simp] : \"dom (ident X) = X\" \n  by (simp add: Id_on_iff dom_def ident_def)\n\nlemma ident_cod [simp] : \"cod (ident X) = X\"\n  by (simp add: ident_def)\n\nlemma ident_app [simp] : \"x \\<in> X \\<Longrightarrow> ident X \\<cdot> x = x\"\n  by (metis Id_onI fun_app_iff ident_def ident_valid select_convs(2)) \n\nlemma compose_ident_left [simp] : \"valid_map f \\<Longrightarrow> ident (cod f) \\<bullet> f = f\"\n  by (smt (verit) cod_compose compose_app_assoc compose_valid dom_compose fun_app2 fun_ext ident_app ident_cod ident_dom ident_valid)\n\nlemma compose_ident_right [simp] : \"valid_map f \\<Longrightarrow> f \\<bullet> ident (dom f) = f\"\n  by (smt (verit, best) cod_compose compose_app_assoc compose_def compose_ident_left compose_valid dom_compose ext_inject fun_ext ident_app ident_def ident_dom ident_valid) \n\n(* Constant functions *)\n\ndefinition \"Function_const_undefined_arg_not_in_codomain _ \\<equiv> undefined\"\n\ndefinition const :: \"'x set \\<Rightarrow>  'y set  \\<Rightarrow> 'y \\<Rightarrow>  ('x, 'y) Function\" where\n\"const X Y y \\<equiv> \n  if y \\<in> Y\n  then \\<lparr> cod = Y, func = { (x, y) | x. x \\<in> X }\\<rparr>\n  else Function_const_undefined_arg_not_in_codomain y\" \n\nlemma const_dom [simp] : \"y \\<in> Y \\<Longrightarrow> dom (const X Y y) = X\"  \n  by (simp add: const_def dom_def)\n\nlemma const_cod [simp] : \"y \\<in> Y \\<Longrightarrow> cod (const X Y y) = Y\"\n  by (simp add: const_def)\n\nlemma const_app [simp] : \"x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> (const X Y y) \\<cdot> x = y\"\n  by (smt (verit) Pair_inject const_cod const_def const_dom fun_app mem_Collect_eq select_convs(2) valid_mapI)\n\nlemma const_valid : \"x \\<in> X \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> valid_map (const X Y y)\"\n  unfolding valid_map_def const_def\n  apply clarsimp\n  by (simp add: Function.dom_def)\n\nlemma const_func : \"y \\<in> Y \\<Longrightarrow> func (const X Y y) = {(x, y) | x . x \\<in> X }\"\n  by (simp add: const_def)\n\nend\n", "meta": {"author": "nasosev", "repo": "cva", "sha": "master", "save_path": "github-repos/isabelle/nasosev-cva", "path": "github-repos/isabelle/nasosev-cva/cva-main/Function.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.77735254244801}}
{"text": "theory Int_Pair_State_Fib\nimports \n  Main\n  \"~~/src/HOL/Library/State_Monad\"\n\nbegin\ntype_synonym 'a pair = \"'a \\<times> 'a\"\n\ndefinition return:: \"'a \\<Rightarrow> ('b, 'a) state\" where \"return = State_Monad.return\"\ndefinition get:: \"('a pair, 'a pair) state\" where \"get = State (\\<lambda>x. (x,x))\"\ndefinition put:: \"'a pair \\<Rightarrow> ('a pair, unit) state\" where \"put x = State (\\<lambda>_. ((),x))\"\ndefinition get_fst:: \"('a pair, 'a) state\" where \"get_fst = do { x \\<leftarrow> get; return (fst x) }\" \ndefinition get_snd:: \"('a pair, 'a) state\" where \"get_snd = do { x \\<leftarrow> get; return (snd x) }\" \ndefinition set_fst:: \"'a pair \\<Rightarrow> 'a \\<Rightarrow> 'a pair\" where \"set_fst v x = (x, snd v)\"\ndefinition set_snd:: \"'a pair \\<Rightarrow> 'a \\<Rightarrow> 'a pair\" where \"set_snd v x = (fst v, x)\"\ndefinition put_fst:: \"'a \\<Rightarrow> ('a pair, unit) state\" where \"put_fst x = do { v \\<leftarrow> get; put (set_fst v x) }\"\ndefinition put_snd:: \"'a \\<Rightarrow> ('a pair, unit) state\" where \"put_snd x = do { v \\<leftarrow> get; put (set_snd v x) }\"\ndefinition skip:: \"('a pair, unit) state\" where \"skip = State (\\<lambda>x. ((),x))\"\n\n(*\ndefinition return:: \"nat \\<Rightarrow> ('b, nat) state\" where \"return = State_Monad.return\"\ndefinition get:: \"(nat pair, nat pair) state\" where \"get = State (\\<lambda>x. (x,x))\"\ndefinition put:: \"nat pair \\<Rightarrow> (nat pair, unit) state\" where \"put x = State (\\<lambda>_. ((),x))\"\ndefinition get_fst:: \"(nat pair, nat) state\" where \"get_fst = do { x \\<leftarrow> get; return (fst x) }\"\ndefinition get_snd:: \"(nat pair, nat) state\" where \"get_snd = do { x \\<leftarrow> get; return (snd x) }\"\ndefinition set_fst:: \"nat pair \\<Rightarrow> nat \\<Rightarrow> nat pair\" where \"set_fst v x = (x, snd v)\"\ndefinition set_snd:: \"nat pair \\<Rightarrow> nat \\<Rightarrow> nat pair\" where \"set_snd v x = (fst v, x)\"\ndefinition put_fst:: \"nat \\<Rightarrow> (nat pair, unit) state\" where \"put_fst x = do { v \\<leftarrow> get; put (set_fst v x) }\"\ndefinition put_snd:: \"nat \\<Rightarrow> (nat pair, unit) state\" where \"put_snd x = do { v \\<leftarrow> get; put (set_snd v x) }\"\ndefinition skip:: \"(nat pair, unit) state\" where \"skip = State (\\<lambda>x. ((),x))\"\n*)\n\nfun fibacc :: \"nat \\<Rightarrow> nat => nat \\<Rightarrow> nat\" where\nfa1: \"fibacc 0 a b = a\"| \nfa2: \"fibacc (Suc 0) a b = b\"|\nfa3: \"fibacc (Suc (Suc n)) a b = fibacc (Suc n) b (a+b)\"\n\ndefinition fib_wrap:: \"nat \\<Rightarrow> nat\" where\n\"fib_wrap n = fibacc n 0 1\"\n\nfun fib :: \"nat => nat\" where\n  \"fib 0 = 0\"\n| \"fib (Suc 0) = 1\"\n| \"fib (Suc (Suc x)) = fib x + fib (Suc x)\"\n\ntext\\<open>Experiment with finding a pattern to extract in the proof\\<close>\nvalue \\<open>fibacc 2 (fib 7) (fib 8)\\<close>\nvalue \\<open>fibacc 8 (fib 1) (fib 2)\\<close>\nvalue \\<open>fibacc 6 (fib 1) (fib 2)\\<close>\nvalue \\<open>fib 5 + fibacc (Suc 5) 0 1 = fib 7\\<close>\nvalue \\<open>fibacc (Suc 5) 0 (fibacc 5 0 1) = fibacc (Suc( Suc 5)) 0 1\\<close>\nvalue \\<open>fibacc (Suc 5) 0 1 =  fibacc (Suc (Suc 5)) 0 1 - fibacc 5 0 1\\<close>\nvalue \\<open>fibacc 5 0 (fibacc 5 0 1)\\<close>\nvalue \\<open>fibacc 5 (fib 1) (fib 2)\\<close>\nvalue\\<open>fib 7\\<close>\n\nlemma fib_aux: \"fibacc n b (a + b) = fibacc (Suc n) a b\"\n  apply(induction n)\n   apply(simp_all)\n  done\n\nlemma fib_aux1: \"fibacc (Suc (Suc n)) a b = fibacc n a b + fibacc (Suc n) a b\"\n  apply(induct n arbitrary: a b)\n  apply(simp_all)\n  apply(simp only: fib_aux)\n  done\n\nlemma fib_main1: \"fib n = fibacc n 0 1\"\n  apply(induction n rule: fib.induct)\n    apply(simp)\n    apply(simp)\n    apply (simp only: fib_aux1)\n  by (simp)\n\nlemma fibwrap_main: \"fib_wrap n = fibacc n 0 1\"\n  apply(induction n rule: nat.induct)\n   apply(simp_all add: fib_wrap_def)\n  done\n\nlemma fib_main: \"fib_wrap n = fib n\"\n  apply(induction n rule: fib.induct)\n   apply(simp_all add: fib_main1 fibwrap_main)\n  done\n\ntext\\<open>The fibonacci function does always return the result at the fst value of the pair. The initial state passed in should be (0,1)\\<close>\nfun monfib:: \"nat \\<Rightarrow> (nat pair, unit) state\" where\n  \"monfib 0 = skip\" |\n  \"monfib (Suc 0) = do {b \\<leftarrow> get_snd; put_fst b}\" |\n  \"monfib (Suc (Suc n)) = do { a \\<leftarrow> get_fst; b \\<leftarrow> get_snd; put (b,(a + b)); monfib (Suc n)}\"\n\ntext\\<open>Stefan do you - know why I can't run any of these examples?\\<close>\nvalue \\<open>fst(snd(run_state (monfib 5) (fst((0,1), ()))))\\<close>\nvalue \\<open>fst(snd(run_state (monfib 5) (0,1)))\\<close>\n\nvalue \"fst(snd (run_state (monfib 6) x))\"\n\nlemma monfib_aux: \"fst(snd (run_state (monfib n) (b, (a + b)))) = fst(snd (run_state (monfib (Suc n)) (a, b)))\"\n  apply(induction n rule: nat.induct)\n   apply(simp_all add: skip_def snd_def fst_def get_fst_def get_snd_def put_def put_fst_def get_def return_def set_fst_def)\n  done\n\nvalue \"fst(snd (run_state (monfib (Suc (Suc 4))) x)) \n        = fst(snd (run_state (monfib 4) x)) + fst(snd (run_state (monfib (Suc 4)) x))\"\n\nlemma monfib_aux1: \"fst(snd (run_state (monfib (Suc (Suc n))) x)) \n      = fst(snd (run_state (monfib n) x)) + fst(snd (run_state (monfib (Suc n)) x))\"\n  apply (induction n arbitrary: x rule: nat.induct)\n   apply (simp_all add: skip_def get_snd_def return_def snd_def get_def put_fst_def set_fst_def put_def get_fst_def fst_def)\n  by (simp add: case_prod_beta' monfib_aux)\n\nlemma fib_mon_basic: \"fst(snd(run_state (monfib n) (a,b))) = fibacc n a b\"\n  apply (induction n arbitrary: a b)\n  apply(simp_all add: skip_def snd_def fst_def get_fst_def get_snd_def put_def put_fst_def)\n  by (metis case_prod_beta' fib_aux monfib_aux)\n\nlemma fib_m_main: \"fst(snd(run_state (monfib n) (0,1))) = fib n\"\n  apply (induction n rule:fib.induct)\n  apply(simp_all add: skip_def snd_def fst_def get_fst_def get_snd_def put_def put_fst_def get_def return_def set_fst_def)\n  by (metis One_nat_def add.commute case_prod_beta' monfib_aux monfib_aux1 plus_1_eq_Suc)\n\nlemma fib_basic_aux: \"fst(snd(run_state (monfib n) (0,1))) = fibacc n 0 1\"\napply (induction n)\napply(simp_all add: skip_def snd_def fst_def)\n  by (metis One_nat_def case_prod_beta' fib_m_main fib_main1)\n\nend", "meta": {"author": "SimplisticCode", "repo": "Tarjan-Isabelle", "sha": "ecd72ef5fc352075e6037965cc30844b7db4bacc", "save_path": "github-repos/isabelle/SimplisticCode-Tarjan-Isabelle", "path": "github-repos/isabelle/SimplisticCode-Tarjan-Isabelle/Tarjan-Isabelle-ecd72ef5fc352075e6037965cc30844b7db4bacc/Monad_Play Around/Fibonacci/Int_Pair_State_Fib.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7772002752722025}}
{"text": "(* Title:      Pseudocomplemented Algebras\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Pseudocomplemented Algebras\\<close>\n\ntext \\<open>\nThis theory expands lattices with a pseudocomplement operation.\nIn particular, we consider the following algebraic structures:\n\\begin{itemize}\n\\item pseudocomplemented lattices (p-algebras)\n\\item pseudocomplemented distributive lattices (distributive p-algebras)\n\\item Stone algebras\n\\item Heyting semilattices\n\\item Heyting lattices\n\\item Heyting algebras\n\\item Heyting-Stone algebras\n\\item Brouwer algebras\n\\item Boolean algebras\n\\end{itemize}\nMost of these structures and many results in this theory are discussed in \\cite{BalbesDwinger1974,Birkhoff1967,Blyth2005,Curry1977,Graetzer1971,Maddux1996}.\n\\<close>\n\ntheory P_Algebras\n\nimports Lattice_Basics\n\nbegin\n\nsubsection \\<open>P-Algebras\\<close>\n\ntext \\<open>\nIn this section we add a pseudocomplement operation to lattices and to distributive lattices.\n\\<close>\n\nsubsubsection \\<open>Pseudocomplemented Lattices\\<close>\n\ntext \\<open>\nThe pseudocomplement of an element \\<open>y\\<close> is the greatest element whose meet with \\<open>y\\<close> is the least element of the lattice.\n\\<close>\n\nclass p_algebra = bounded_lattice + uminus +\n  assumes pseudo_complement: \"x \\<sqinter> y = bot \\<longleftrightarrow> x \\<le> -y\"\nbegin\n\nsubclass sup_inf_top_bot_uminus_ord .\n\ntext \\<open>\nRegular elements and dense elements are frequently used in pseudocomplemented algebras.\n\\<close>\n\nabbreviation \"regular x \\<equiv> x = --x\"\nabbreviation \"dense x \\<equiv> -x = bot\"\nabbreviation \"complemented x \\<equiv> \\<exists>y . x \\<sqinter> y = bot \\<and> x \\<squnion> y = top\"\nabbreviation \"in_p_image x \\<equiv> \\<exists>y . x = -y\"\nabbreviation \"selection s x \\<equiv> s = --s \\<sqinter> x\"\n\nabbreviation \"dense_elements \\<equiv> { x . dense x }\"\nabbreviation \"regular_elements \\<equiv> { x . in_p_image x }\"\n\nlemma p_bot [simp]:\n  \"-bot = top\"\n  using inf_top.left_neutral pseudo_complement top_unique by blast\n\nlemma p_top [simp]:\n  \"-top = bot\"\n  by (metis eq_refl inf_top.comm_neutral pseudo_complement)\n\ntext \\<open>\nThe pseudocomplement satisfies the following half of the requirements of a complement.\n\\<close>\n\nlemma inf_p [simp]:\n  \"x \\<sqinter> -x = bot\"\n  using inf.commute pseudo_complement by fastforce\n\nlemma p_inf [simp]:\n  \"-x \\<sqinter> x = bot\"\n  by (simp add: inf_commute)\n\nlemma pp_inf_p:\n  \"--x \\<sqinter> -x = bot\"\n  by simp\n\ntext \\<open>\nThe double complement is a closure operation.\n\\<close>\n\nlemma pp_increasing:\n  \"x \\<le> --x\"\n  using inf_p pseudo_complement by blast\n\nlemma ppp [simp]:\n  \"---x = -x\"\n  by (metis antisym inf.commute order_trans pseudo_complement pp_increasing)\n\nlemma pp_idempotent:\n  \"----x = --x\"\n  by simp\n\nlemma regular_in_p_image_iff:\n  \"regular x \\<longleftrightarrow> in_p_image x\"\n  by auto\n\nlemma pseudo_complement_pp:\n  \"x \\<sqinter> y = bot \\<longleftrightarrow> --x \\<le> -y\"\n  by (metis inf_commute pseudo_complement ppp)\n\nlemma p_antitone:\n  \"x \\<le> y \\<Longrightarrow> -y \\<le> -x\"\n  by (metis inf_commute order_trans pseudo_complement pp_increasing)\n\nlemma p_antitone_sup:\n  \"-(x \\<squnion> y) \\<le> -x\"\n  by (simp add: p_antitone)\n\nlemma p_antitone_inf:\n  \"-x \\<le> -(x \\<sqinter> y)\"\n  by (simp add: p_antitone)\n\nlemma p_antitone_iff:\n  \"x \\<le> -y \\<longleftrightarrow> y \\<le> -x\"\n  using order_lesseq_imp p_antitone pp_increasing by blast\n\nlemma pp_isotone:\n  \"x \\<le> y \\<Longrightarrow> --x \\<le> --y\"\n  by (simp add: p_antitone)\n\nlemma pp_isotone_sup:\n  \"--x \\<le> --(x \\<squnion> y)\"\n  by (simp add: p_antitone)\n\nlemma pp_isotone_inf:\n  \"--(x \\<sqinter> y) \\<le> --x\"\n  by (simp add: p_antitone)\n\ntext \\<open>\nOne of De Morgan's laws holds in pseudocomplemented lattices.\n\\<close>\n\nlemma p_dist_sup [simp]:\n  \"-(x \\<squnion> y) = -x \\<sqinter> -y\"\n  apply (rule antisym)\n  apply (simp add: p_antitone)\n  using inf_le1 inf_le2 le_sup_iff p_antitone_iff by blast\n\nlemma p_supdist_inf:\n  \"-x \\<squnion> -y \\<le> -(x \\<sqinter> y)\"\n  by (simp add: p_antitone)\n\nlemma pp_dist_pp_sup [simp]:\n  \"--(--x \\<squnion> --y) = --(x \\<squnion> y)\"\n  by simp\n\nlemma p_sup_p [simp]:\n  \"-(x \\<squnion> -x) = bot\"\n  by simp\n\nlemma pp_sup_p [simp]:\n  \"--(x \\<squnion> -x) = top\"\n  by simp\n\nlemma dense_pp:\n  \"dense x \\<longleftrightarrow> --x = top\"\n  by (metis p_bot p_top ppp)\n\nlemma dense_sup_p:\n  \"dense (x \\<squnion> -x)\"\n  by simp\n\nlemma regular_char:\n  \"regular x \\<longleftrightarrow> (\\<exists>y . x = -y)\"\n  by auto\n\nlemma pp_inf_bot_iff:\n  \"x \\<sqinter> y = bot \\<longleftrightarrow> --x \\<sqinter> y = bot\"\n  by (simp add: pseudo_complement_pp)\n\ntext \\<open>\nWeak forms of the shunting property hold.\nMost require a pseudocomplemented element on the right-hand side.\n\\<close>\n\nlemma p_shunting_swap:\n  \"x \\<sqinter> y \\<le> -z \\<longleftrightarrow> x \\<sqinter> z \\<le> -y\"\n  by (metis inf_assoc inf_commute pseudo_complement)\n\nlemma pp_inf_below_iff:\n  \"x \\<sqinter> y \\<le> -z \\<longleftrightarrow> --x \\<sqinter> y \\<le> -z\"\n  by (simp add: inf_commute p_shunting_swap)\n\nlemma p_inf_pp [simp]:\n  \"-(x \\<sqinter> --y) = -(x \\<sqinter> y)\"\n  apply (rule antisym)\n  apply (simp add: inf.coboundedI2 p_antitone pp_increasing)\n  using inf_commute p_antitone_iff pp_inf_below_iff by auto\n\nlemma p_inf_pp_pp [simp]:\n  \"-(--x \\<sqinter> --y) = -(x \\<sqinter> y)\"\n  by (simp add: inf_commute)\n\nlemma regular_closed_inf:\n  \"regular x \\<Longrightarrow> regular y \\<Longrightarrow> regular (x \\<sqinter> y)\"\n  by (metis p_dist_sup ppp)\n\nlemma regular_closed_p:\n  \"regular (-x)\"\n  by simp\n\nlemma regular_closed_pp:\n  \"regular (--x)\"\n  by simp\n\nlemma regular_closed_bot:\n  \"regular bot\"\n  by simp\n\nlemma regular_closed_top:\n  \"regular top\"\n  by simp\n\nlemma pp_dist_inf [simp]:\n  \"--(x \\<sqinter> y) = --x \\<sqinter> --y\"\n  by (metis p_dist_sup p_inf_pp_pp ppp)\n\nlemma inf_import_p [simp]:\n  \"x \\<sqinter> -(x \\<sqinter> y) = x \\<sqinter> -y\"\n  apply (rule antisym)\n  using p_shunting_swap apply fastforce\n  using inf.sup_right_isotone p_antitone by auto\n\ntext \\<open>\nPseudocomplements are unique.\n\\<close>\n\nlemma p_unique:\n  \"(\\<forall>x . x \\<sqinter> y = bot \\<longleftrightarrow> x \\<le> z) \\<Longrightarrow> z = -y\"\n  using inf.eq_iff pseudo_complement by auto\n\nlemma maddux_3_5:\n  \"x \\<squnion> x = x \\<squnion> -(y \\<squnion> -y)\"\n  by simp\n\nlemma shunting_1_pp:\n  \"x \\<le> --y \\<longleftrightarrow> x \\<sqinter> -y = bot\"\n  by (simp add: pseudo_complement)\n\nlemma pp_pp_inf_bot_iff:\n  \"x \\<sqinter> y = bot \\<longleftrightarrow> --x \\<sqinter> --y = bot\"\n  by (simp add: pseudo_complement_pp)\n\nlemma inf_pp_semi_commute:\n  \"x \\<sqinter> --y \\<le> --(x \\<sqinter> y)\"\n  using inf.eq_refl p_antitone_iff p_inf_pp by presburger\n\nlemma inf_pp_commute:\n  \"--(--x \\<sqinter> y) = --x \\<sqinter> --y\"\n  by simp\n\nlemma sup_pp_semi_commute:\n  \"x \\<squnion> --y \\<le> --(x \\<squnion> y)\"\n  by (simp add: p_antitone_iff)\n\nlemma regular_sup:\n  \"regular z \\<Longrightarrow> (x \\<le> z \\<and> y \\<le> z \\<longleftrightarrow> --(x \\<squnion> y) \\<le> z)\"\n  apply (rule iffI)\n  apply (metis le_supI pp_isotone)\n  using dual_order.trans sup_ge2 pp_increasing pp_isotone_sup by blast\n\nlemma dense_closed_inf:\n  \"dense x \\<Longrightarrow> dense y \\<Longrightarrow> dense (x \\<sqinter> y)\"\n  by (simp add: dense_pp)\n\nlemma dense_closed_sup:\n  \"dense x \\<Longrightarrow> dense y \\<Longrightarrow> dense (x \\<squnion> y)\"\n  by simp\n\nlemma dense_closed_pp:\n  \"dense x \\<Longrightarrow> dense (--x)\"\n  by simp\n\n\n\nlemma dense_up_closed:\n  \"dense x \\<Longrightarrow> x \\<le> y \\<Longrightarrow> dense y\"\n  using dense_pp top_le pp_isotone by auto\n\nlemma regular_dense_top:\n  \"regular x \\<Longrightarrow> dense x \\<Longrightarrow> x = top\"\n  using p_bot by blast\n\nlemma selection_char:\n  \"selection s x \\<longleftrightarrow> (\\<exists>y . s = -y \\<sqinter> x)\"\n  by (metis inf_import_p inf_commute regular_closed_p)\n\nlemma selection_closed_inf:\n  \"selection s x \\<Longrightarrow> selection t x \\<Longrightarrow> selection (s \\<sqinter> t) x\"\n  by (metis inf_assoc inf_commute inf_idem pp_dist_inf)\n\nlemma selection_closed_pp:\n  \"regular x \\<Longrightarrow> selection s x \\<Longrightarrow> selection (--s) x\"\n  by (metis pp_dist_inf)\n\nlemma selection_closed_bot:\n  \"selection bot x\"\n  by simp\n\nlemma selection_closed_id:\n  \"selection x x\"\n  using inf.le_iff_sup pp_increasing by auto\n\ntext \\<open>\nConjugates are usually studied for Boolean algebras, however, some of their properties generalise to pseudocomplemented algebras.\n\\<close>\n\nlemma conjugate_unique_p:\n  assumes \"conjugate f g\"\n      and \"conjugate f h\"\n    shows \"uminus \\<circ> g = uminus \\<circ> h\"\nproof -\n  have \"\\<forall>x y . x \\<sqinter> g y = bot \\<longleftrightarrow> x \\<sqinter> h y = bot\"\n    using assms conjugate_def inf.commute by simp\n  hence \"\\<forall>x y . x \\<le> -(g y) \\<longleftrightarrow> x \\<le> -(h y)\"\n    using inf.commute pseudo_complement by simp\n  hence \"\\<forall>y . -(g y) = -(h y)\"\n    using eq_iff by blast\n  thus ?thesis\n    by auto\nqed\n\nlemma conjugate_symmetric:\n  \"conjugate f g \\<Longrightarrow> conjugate g f\"\n  by (simp add: conjugate_def inf_commute)\n\nlemma additive_isotone:\n  \"additive f \\<Longrightarrow> isotone f\"\n  by (metis additive_def isotone_def le_iff_sup)\n\nlemma dual_additive_antitone:\n  assumes \"dual_additive f\"\n    shows \"isotone (uminus \\<circ> f)\"\nproof -\n  have \"\\<forall>x y . f (x \\<squnion> y) \\<le> f x\"\n    using assms dual_additive_def by simp\n  hence \"\\<forall>x y . x \\<le> y \\<longrightarrow> f y \\<le> f x\"\n    by (metis sup_absorb2)\n  hence \"\\<forall>x y . x \\<le> y \\<longrightarrow> -(f x) \\<le> -(f y)\"\n    by (simp add: p_antitone)\n  thus ?thesis\n    by (simp add: isotone_def)\nqed\n\nlemma conjugate_dual_additive:\n  assumes \"conjugate f g\"\n    shows \"dual_additive (uminus \\<circ> f)\"\nproof -\n  have 1: \"\\<forall>x y z . -z \\<le> -(f (x \\<squnion> y)) \\<longleftrightarrow> -z \\<le> -(f x) \\<and> -z \\<le> -(f y)\"\n  proof (intro allI)\n    fix x y z\n    have \"(-z \\<le> -(f (x \\<squnion> y))) = (f (x \\<squnion> y) \\<sqinter> -z = bot)\"\n      by (simp add: p_antitone_iff pseudo_complement)\n    also have \"... = ((x \\<squnion> y) \\<sqinter> g(-z) = bot)\"\n      using assms conjugate_def by auto\n    also have \"... = (x \\<squnion> y \\<le> -(g(-z)))\"\n      by (simp add: pseudo_complement)\n    also have \"... = (x \\<le> -(g(-z)) \\<and> y \\<le> -(g(-z)))\"\n      by (simp add: le_sup_iff)\n    also have \"... = (x \\<sqinter> g(-z) = bot \\<and> y \\<sqinter> g(-z) = bot)\"\n      by (simp add: pseudo_complement)\n    also have \"... = (f x \\<sqinter> -z = bot \\<and> f y \\<sqinter> -z = bot)\"\n      using assms conjugate_def by auto\n    also have \"... = (-z \\<le> -(f x) \\<and> -z \\<le> -(f y))\"\n      by (simp add: p_antitone_iff pseudo_complement)\n    finally show \"-z \\<le> -(f (x \\<squnion> y)) \\<longleftrightarrow> -z \\<le> -(f x) \\<and> -z \\<le> -(f y)\"\n      by simp\n  qed\n  have \"\\<forall>x y . -(f (x \\<squnion> y)) = -(f x) \\<sqinter> -(f y)\"\n  proof (intro allI)\n    fix x y\n    have \"-(f x) \\<sqinter> -(f y) = --(-(f x) \\<sqinter> -(f y))\"\n      by simp\n    hence \"-(f x) \\<sqinter> -(f y) \\<le> -(f (x \\<squnion> y))\"\n      using 1 by (metis inf_le1 inf_le2)\n    thus \"-(f (x \\<squnion> y)) = -(f x) \\<sqinter> -(f y)\"\n      using 1 antisym by fastforce\n  qed\n  thus ?thesis\n    using dual_additive_def by simp\nqed\n\nlemma conjugate_isotone_pp:\n  \"conjugate f g \\<Longrightarrow> isotone (uminus \\<circ> uminus \\<circ> f)\"\n  by (simp add: comp_assoc conjugate_dual_additive dual_additive_antitone)\n\nlemma conjugate_char_1_pp:\n  \"conjugate f g \\<longleftrightarrow> (\\<forall>x y . f(x \\<sqinter> -(g y)) \\<le> --f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> --g y \\<sqinter> -x)\"\nproof\n  assume 1: \"conjugate f g\"\n  show \"\\<forall>x y . f(x \\<sqinter> -(g y)) \\<le> --f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> --g y \\<sqinter> -x\"\n  proof (intro allI)\n    fix x y\n    have 2: \"f(x \\<sqinter> -(g y)) \\<le> -y\"\n      using 1 by (simp add: conjugate_def pseudo_complement)\n    have \"f(x \\<sqinter> -(g y)) \\<le> --f(x \\<sqinter> -(g y))\"\n      by (simp add: pp_increasing)\n    also have \"... \\<le> --f x\"\n      using 1 conjugate_isotone_pp isotone_def by simp\n    finally have 3: \"f(x \\<sqinter> -(g y)) \\<le> --f x \\<sqinter> -y\"\n      using 2 by simp\n    have 4: \"isotone (uminus \\<circ> uminus \\<circ> g)\"\n      using 1 conjugate_isotone_pp conjugate_symmetric by auto\n    have 5: \"g(y \\<sqinter> -(f x)) \\<le> -x\"\n      using 1 by (metis conjugate_def inf.cobounded2 inf_commute pseudo_complement)\n    have \"g(y \\<sqinter> -(f x)) \\<le> --g(y \\<sqinter> -(f x))\"\n      by (simp add: pp_increasing)\n    also have \"... \\<le> --g y\"\n      using 4 isotone_def by auto\n    finally have \"g(y \\<sqinter> -(f x)) \\<le> --g y \\<sqinter> -x\"\n      using 5 by simp\n    thus \"f(x \\<sqinter> -(g y)) \\<le> --f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> --g y \\<sqinter> -x\"\n      using 3 by simp\n  qed\nnext\n  assume 6: \"\\<forall>x y . f(x \\<sqinter> -(g y)) \\<le> --f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> --g y \\<sqinter> -x\"\n  hence 7: \"\\<forall>x y . f x \\<sqinter> y = bot \\<longrightarrow> x \\<sqinter> g y = bot\"\n    by (metis inf.le_iff_sup inf.le_sup_iff inf_commute pseudo_complement)\n  have \"\\<forall>x y . x \\<sqinter> g y = bot \\<longrightarrow> f x \\<sqinter> y = bot\"\n    using 6 by (metis inf.le_iff_sup inf.le_sup_iff inf_commute pseudo_complement)\n  thus \"conjugate f g\"\n    using 7 conjugate_def by auto\nqed\n\nlemma conjugate_char_1_isotone:\n  \"conjugate f g \\<Longrightarrow> isotone f \\<Longrightarrow> isotone g \\<Longrightarrow> f(x \\<sqinter> -(g y)) \\<le> f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> g y \\<sqinter> -x\"\n  by (simp add: conjugate_char_1_pp ord.isotone_def)\n\nlemma dense_lattice_char_1:\n  \"(\\<forall>x y . x \\<sqinter> y = bot \\<longrightarrow> x = bot \\<or> y = bot) \\<longleftrightarrow> (\\<forall>x . x \\<noteq> bot \\<longrightarrow> dense x)\"\n  by (metis inf_top.left_neutral p_bot p_inf pp_inf_bot_iff)\n\nlemma dense_lattice_char_2:\n  \"(\\<forall>x y . x \\<sqinter> y = bot \\<longrightarrow> x = bot \\<or> y = bot) \\<longleftrightarrow> (\\<forall>x . regular x \\<longrightarrow> x = bot \\<or> x = top)\"\n  by (metis dense_lattice_char_1 inf_top.left_neutral p_inf regular_closed_p regular_closed_top)\n\nlemma restrict_below_Rep_eq:\n  \"x \\<sqinter> --y \\<le> z \\<Longrightarrow> x \\<sqinter> y = x \\<sqinter> z \\<sqinter> y\"\n  by (metis inf.absorb2 inf.commute inf.left_commute pp_increasing)\n\n(*\nlemma p_inf_sup_below: \"-x \\<sqinter> (x \\<squnion> y) \\<le> y\" nitpick [expect=genuine] oops\nlemma complement_p: \"x \\<sqinter> y = bot \\<and> x \\<squnion> y = top \\<longrightarrow> -x = y\" nitpick [expect=genuine] oops\nlemma complemented_regular: \"complemented x \\<longrightarrow> regular x\" nitpick [expect=genuine] oops\n*)\n\nend\n\ntext \\<open>\nThe following class gives equational axioms for the pseudocomplement operation.\n\\<close>\n\nclass p_algebra_eq = bounded_lattice + uminus +\n  assumes p_bot_eq: \"-bot = top\"\n      and p_top_eq: \"-top = bot\"\n      and inf_import_p_eq: \"x \\<sqinter> -(x \\<sqinter> y) = x \\<sqinter> -y\"\nbegin\n\nlemma inf_p_eq:\n  \"x \\<sqinter> -x = bot\"\n  by (metis inf_bot_right inf_import_p_eq inf_top_right p_top_eq)\n\nsubclass p_algebra\n  apply unfold_locales\n  apply (rule iffI)\n  apply (metis inf.orderI inf_import_p_eq inf_top.right_neutral p_bot_eq)\n  by (metis (full_types) inf.left_commute inf.orderE inf_bot_right inf_commute inf_p_eq)\n\nend\n\nsubsubsection \\<open>Pseudocomplemented Distributive Lattices\\<close>\n\ntext \\<open>\nWe obtain further properties if we assume that the lattice operations are distributive.\n\\<close>\n\nclass pd_algebra = p_algebra + bounded_distrib_lattice\nbegin\n\nlemma p_inf_sup_below:\n  \"-x \\<sqinter> (x \\<squnion> y) \\<le> y\"\n  by (simp add: inf_sup_distrib1)\n\nlemma pp_inf_sup_p [simp]:\n  \"--x \\<sqinter> (x \\<squnion> -x) = x\"\n  using inf.absorb2 inf_sup_distrib1 pp_increasing by auto\n\nlemma complement_p:\n  \"x \\<sqinter> y = bot \\<Longrightarrow> x \\<squnion> y = top \\<Longrightarrow> -x = y\"\n  by (metis pseudo_complement inf.commute inf_top.left_neutral sup.absorb_iff1 sup.commute sup_bot.right_neutral sup_inf_distrib2 p_inf)\n\nlemma complemented_regular:\n  \"complemented x \\<Longrightarrow> regular x\"\n  using complement_p inf.commute sup.commute by fastforce\n\nlemma regular_inf_dense:\n  \"\\<exists>y z . regular y \\<and> dense z \\<and> x = y \\<sqinter> z\"\n  by (metis pp_inf_sup_p dense_sup_p ppp)\n\nlemma maddux_3_12 [simp]:\n  \"(x \\<squnion> -y) \\<sqinter> (x \\<squnion> y) = x\"\n  by (metis p_inf sup_bot_right sup_inf_distrib1)\n\nlemma maddux_3_13 [simp]:\n  \"(x \\<squnion> y) \\<sqinter> -x = y \\<sqinter> -x\"\n  by (simp add: inf_sup_distrib2)\n\nlemma maddux_3_20:\n  \"((v \\<sqinter> w) \\<squnion> (-v \\<sqinter> x)) \\<sqinter> -((v \\<sqinter> y) \\<squnion> (-v \\<sqinter> z)) = (v \\<sqinter> w \\<sqinter> -y) \\<squnion> (-v \\<sqinter> x \\<sqinter> -z)\"\nproof -\n  have \"v \\<sqinter> w \\<sqinter> -(v \\<sqinter> y) \\<sqinter> -(-v \\<sqinter> z) = v \\<sqinter> w \\<sqinter> -(v \\<sqinter> y)\"\n    by (meson inf.cobounded1 inf_absorb1 le_infI1 p_antitone_iff)\n  also have \"... = v \\<sqinter> w \\<sqinter> -y\"\n    using inf.sup_relative_same_increasing inf_import_p inf_le1 by blast\n  finally have 1: \"v \\<sqinter> w \\<sqinter> -(v \\<sqinter> y) \\<sqinter> -(-v \\<sqinter> z) = v \\<sqinter> w \\<sqinter> -y\"\n    .\n  have \"-v \\<sqinter> x \\<sqinter> -(v \\<sqinter> y) \\<sqinter> -(-v \\<sqinter> z) = -v \\<sqinter> x \\<sqinter> -(-v \\<sqinter> z)\"\n    by (simp add: inf.absorb1 le_infI1 p_antitone_inf)\n  also have \"... = -v \\<sqinter> x \\<sqinter> -z\"\n    by (simp add: inf.assoc inf_left_commute)\n  finally have 2: \"-v \\<sqinter> x \\<sqinter> -(v \\<sqinter> y) \\<sqinter> -(-v \\<sqinter> z) = -v \\<sqinter> x \\<sqinter> -z\"\n    .\n  have \"((v \\<sqinter> w) \\<squnion> (-v \\<sqinter> x)) \\<sqinter> -((v \\<sqinter> y) \\<squnion> (-v \\<sqinter> z)) = (v \\<sqinter> w \\<sqinter> -(v \\<sqinter> y) \\<sqinter> -(-v \\<sqinter> z)) \\<squnion> (-v \\<sqinter> x \\<sqinter> -(v \\<sqinter> y) \\<sqinter> -(-v \\<sqinter> z))\"\n    by (simp add: inf_assoc inf_sup_distrib2)\n  also have \"... = (v \\<sqinter> w \\<sqinter> -y) \\<squnion> (-v \\<sqinter> x \\<sqinter> -z)\"\n    using 1 2 by simp\n  finally show ?thesis\n    .\nqed\n\nlemma order_char_1:\n  \"x \\<le> y \\<longleftrightarrow> x \\<le> y \\<squnion> -x\"\n  by (metis inf.sup_left_isotone inf_sup_absorb le_supI1 maddux_3_12 sup_commute)\n\nlemma order_char_2:\n  \"x \\<le> y \\<longleftrightarrow> x \\<squnion> -x \\<le> y \\<squnion> -x\"\n  using order_char_1 by auto\n\n(*\nlemma pp_dist_sup [simp]: \"--(x \\<squnion> y) = --x \\<squnion> --y\" nitpick [expect=genuine] oops\nlemma regular_closed_sup: \"regular x \\<and> regular y \\<longrightarrow> regular (x \\<squnion> y)\" nitpick [expect=genuine] oops\nlemma regular_complemented_iff: \"regular x \\<longleftrightarrow> complemented x\" nitpick [expect=genuine] oops\nlemma selection_closed_sup: \"selection s x \\<and> selection t x \\<longrightarrow> selection (s \\<squnion> t) x\" nitpick [expect=genuine] oops\nlemma stone [simp]: \"-x \\<squnion> --x = top\" nitpick [expect=genuine] oops\n*)\n\nend\n\nsubsection \\<open>Stone Algebras\\<close>\n\ntext \\<open>\nA Stone algebra is a distributive lattice with a pseudocomplement that satisfies the following equation.\nWe thus obtain the other half of the requirements of a complement at least for the regular elements.\n\\<close>\n\nclass stone_algebra = pd_algebra +\n  assumes stone [simp]: \"-x \\<squnion> --x = top\"\nbegin\n\ntext \\<open>\nAs a consequence, we obtain both De Morgan's laws for all elements.\n\\<close>\n\nlemma p_dist_inf [simp]:\n  \"-(x \\<sqinter> y) = -x \\<squnion> -y\"\nproof (rule p_unique[THEN sym], rule allI, rule iffI)\n  fix w\n  assume \"w \\<sqinter> (x \\<sqinter> y) = bot\"\n  hence \"w \\<sqinter> --x \\<sqinter> y = bot\"\n    using inf_commute inf_left_commute pseudo_complement by auto\n  hence 1: \"w \\<sqinter> --x \\<le> -y\"\n    by (simp add: pseudo_complement)\n  have \"w = (w \\<sqinter> -x) \\<squnion> (w \\<sqinter> --x)\"\n    using distrib_imp2 sup_inf_distrib1 by auto\n  thus \"w \\<le> -x \\<squnion> -y\"\n    using 1 by (metis inf_le2 sup.mono)\nnext\n  fix w\n  assume \"w \\<le> -x \\<squnion> -y\"\n  thus \"w \\<sqinter> (x \\<sqinter> y) = bot\"\n    using order_trans p_supdist_inf pseudo_complement by blast\nqed\n\nlemma pp_dist_sup [simp]:\n  \"--(x \\<squnion> y) = --x \\<squnion> --y\"\n  by simp\n\nlemma regular_closed_sup:\n  \"regular x \\<Longrightarrow> regular y \\<Longrightarrow> regular (x \\<squnion> y)\"\n  by simp\n\ntext \\<open>\nThe regular elements are precisely the ones having a complement.\n\\<close>\n\nlemma regular_complemented_iff:\n  \"regular x \\<longleftrightarrow> complemented x\"\n  by (metis inf_p stone complemented_regular)\n\nlemma selection_closed_sup:\n  \"selection s x \\<Longrightarrow> selection t x \\<Longrightarrow> selection (s \\<squnion> t) x\"\n  by (simp add: inf_sup_distrib2)\n\nlemma huntington_3_pp [simp]:\n  \"-(-x \\<squnion> -y) \\<squnion> -(-x \\<squnion> y) = --x\"\n  by (metis p_dist_inf p_inf sup.commute sup_bot_left sup_inf_distrib1)\n\nlemma maddux_3_3 [simp]:\n  \"-(x \\<squnion> y) \\<squnion> -(x \\<squnion> -y) = -x\"\n  by (simp add: sup_commute sup_inf_distrib1)\n\nlemma maddux_3_11_pp:\n  \"(x \\<sqinter> -y) \\<squnion> (x \\<sqinter> --y) = x\"\n  by (metis inf_sup_distrib1 inf_top_right stone)\n\nlemma maddux_3_19_pp:\n  \"(-x \\<sqinter> y) \\<squnion> (--x \\<sqinter> z) = (--x \\<squnion> y) \\<sqinter> (-x \\<squnion> z)\"\nproof -\n  have \"(--x \\<squnion> y) \\<sqinter> (-x \\<squnion> z) = (--x \\<sqinter> z) \\<squnion> (y \\<sqinter> -x) \\<squnion> (y \\<sqinter> z)\"\n    by (simp add: inf.commute inf_sup_distrib1 sup.assoc)\n  also have \"... = (--x \\<sqinter> z) \\<squnion> (y \\<sqinter> -x) \\<squnion> (y \\<sqinter> z \\<sqinter> (-x \\<squnion> --x))\"\n    by simp\n  also have \"... = (--x \\<sqinter> z) \\<squnion> ((y \\<sqinter> -x) \\<squnion> (y \\<sqinter> -x \\<sqinter> z)) \\<squnion> (y \\<sqinter> z \\<sqinter> --x)\"\n    using inf_sup_distrib1 sup_assoc inf_commute inf_assoc by presburger\n  also have \"... = (--x \\<sqinter> z) \\<squnion> (y \\<sqinter> -x) \\<squnion> (y \\<sqinter> z \\<sqinter> --x)\"\n    by simp\n  also have \"... = ((--x \\<sqinter> z) \\<squnion> (--x \\<sqinter> z \\<sqinter> y)) \\<squnion> (y \\<sqinter> -x)\"\n    by (simp add: inf_assoc inf_commute sup.left_commute sup_commute)\n  also have \"... = (--x \\<sqinter> z) \\<squnion> (y \\<sqinter> -x)\"\n    by simp\n  finally show ?thesis\n    by (simp add: inf_commute sup_commute)\nqed\n\nlemma compl_inter_eq_pp:\n  \"--x \\<sqinter> y = --x \\<sqinter> z \\<Longrightarrow> -x \\<sqinter> y = -x \\<sqinter> z \\<Longrightarrow> y = z\"\n  by (metis inf_commute inf_p inf_sup_distrib1 inf_top.right_neutral p_bot p_dist_inf)\n\nlemma maddux_3_21_pp [simp]:\n  \"--x \\<squnion> (-x \\<sqinter> y) = --x \\<squnion> y\"\n  by (simp add: sup.commute sup_inf_distrib1)\n\nlemma shunting_2_pp:\n  \"x \\<le> --y \\<longleftrightarrow> -x \\<squnion> --y = top\"\n  by (metis inf_top_left p_bot p_dist_inf pseudo_complement)\n\nlemma shunting_p:\n  \"x \\<sqinter> y \\<le> -z \\<longleftrightarrow> x \\<le> -z \\<squnion> -y\"\n  by (metis inf.assoc p_dist_inf p_shunting_swap pseudo_complement)\n\ntext \\<open>\nThe following weak shunting property is interesting as it does not require the element \\<open>z\\<close> on the right-hand side to be regular.\n\\<close>\n\nlemma shunting_var_p:\n  \"x \\<sqinter> -y \\<le> z \\<longleftrightarrow> x \\<le> z \\<squnion> --y\"\nproof\n  assume \"x \\<sqinter> -y \\<le> z\"\n  hence \"z \\<squnion> --y = --y \\<squnion> (z \\<squnion> x \\<sqinter> -y)\"\n    by (simp add: sup.absorb1 sup.commute)\n  thus \"x \\<le> z \\<squnion> --y\"\n    by (metis inf_commute maddux_3_21_pp sup.commute sup.left_commute sup_left_divisibility)\nnext\n  assume \"x \\<le> z \\<squnion> --y\"\n  thus \"x \\<sqinter> -y \\<le> z\"\n    by (metis inf.mono maddux_3_12 sup_ge2)\nqed\n\n(* Whether conjugate_char_2_pp can be proved in pd_algebra or in p_algebra is unknown. *)\nlemma conjugate_char_2_pp:\n  \"conjugate f g \\<longleftrightarrow> f bot = bot \\<and> g bot = bot \\<and> (\\<forall>x y . f x \\<sqinter> y \\<le> --(f(x \\<sqinter> --(g y))) \\<and> g y \\<sqinter> x \\<le> --(g(y \\<sqinter> --(f x))))\"\nproof\n  assume 1: \"conjugate f g\"\n  hence 2: \"dual_additive (uminus \\<circ> g)\"\n    using conjugate_symmetric conjugate_dual_additive by auto\n  show \"f bot = bot \\<and> g bot = bot \\<and> (\\<forall>x y . f x \\<sqinter> y \\<le> --(f(x \\<sqinter> --(g y))) \\<and> g y \\<sqinter> x \\<le> --(g(y \\<sqinter> --(f x))))\"\n  proof (intro conjI)\n    show \"f bot = bot\"\n      using 1 by (metis conjugate_def inf_idem inf_bot_left)\n  next\n    show \"g bot = bot\"\n      using 1 by (metis conjugate_def inf_idem inf_bot_right)\n  next\n    show \"\\<forall>x y . f x \\<sqinter> y \\<le> --(f(x \\<sqinter> --(g y))) \\<and> g y \\<sqinter> x \\<le> --(g(y \\<sqinter> --(f x)))\"\n    proof (intro allI)\n      fix x y\n      have 3: \"y \\<le> -(f(x \\<sqinter> -(g y)))\"\n        using 1 by (simp add: conjugate_def pseudo_complement inf_commute)\n      have 4: \"x \\<le> -(g(y \\<sqinter> -(f x)))\"\n        using 1 conjugate_def inf.commute pseudo_complement by fastforce\n      have \"y \\<sqinter> -(f(x \\<sqinter> --(g y))) = y \\<sqinter> -(f(x \\<sqinter> -(g y))) \\<sqinter> -(f(x \\<sqinter> --(g y)))\"\n        using 3 by (simp add: inf.le_iff_sup inf_commute)\n      also have \"... = y \\<sqinter> -(f((x \\<sqinter> -(g y)) \\<squnion> (x \\<sqinter> --(g y))))\"\n        using 1 conjugate_dual_additive dual_additive_def inf_assoc by auto\n      also have \"... = y \\<sqinter> -(f x)\"\n        by (simp add: maddux_3_11_pp)\n      also have \"... \\<le> -(f x)\"\n        by simp\n      finally have 5: \"f x \\<sqinter> y \\<le> --(f(x \\<sqinter> --(g y)))\"\n        by (simp add: inf_commute p_shunting_swap)\n      have \"x \\<sqinter> -(g(y \\<sqinter> --(f x))) = x \\<sqinter> -(g(y \\<sqinter> -(f x))) \\<sqinter> -(g(y \\<sqinter> --(f x)))\"\n        using 4 by (simp add: inf.le_iff_sup inf_commute)\n      also have \"... = x \\<sqinter> -(g((y \\<sqinter> -(f x)) \\<squnion> (y \\<sqinter> --(f x))))\"\n        using 2 by (simp add: dual_additive_def inf_assoc)\n      also have \"... = x \\<sqinter> -(g y)\"\n        by (simp add: maddux_3_11_pp)\n      also have \"... \\<le> -(g y)\"\n        by simp\n      finally have \"g y \\<sqinter> x \\<le> --(g(y \\<sqinter> --(f x)))\"\n        by (simp add: inf_commute p_shunting_swap)\n      thus \"f x \\<sqinter> y \\<le> --(f(x \\<sqinter> --(g y))) \\<and> g y \\<sqinter> x \\<le> --(g(y \\<sqinter> --(f x)))\"\n        using 5 by simp\n    qed\n  qed\nnext\n  assume \"f bot = bot \\<and> g bot = bot \\<and> (\\<forall>x y . f x \\<sqinter> y \\<le> --(f(x \\<sqinter> --(g y))) \\<and> g y \\<sqinter> x \\<le> --(g(y \\<sqinter> --(f x))))\"\n  thus \"conjugate f g\"\n    by (unfold conjugate_def, metis inf_commute le_bot pp_inf_bot_iff regular_closed_bot)\nqed\n\nlemma conjugate_char_2_pp_additive:\n  assumes \"conjugate f g\"\n      and \"additive f\"\n      and \"additive g\"\n    shows \"f x \\<sqinter> y \\<le> f(x \\<sqinter> --(g y)) \\<and> g y \\<sqinter> x \\<le> g(y \\<sqinter> --(f x))\"\nproof -\n  have \"f x \\<sqinter> y = f ((x \\<sqinter> --g y) \\<squnion> (x \\<sqinter> -g y)) \\<sqinter> y\"\n    by (simp add: sup.commute sup_inf_distrib1)\n  also have \"... = (f (x \\<sqinter> --g y) \\<sqinter> y) \\<squnion> (f (x \\<sqinter> -g y) \\<sqinter> y)\"\n    using assms(2) additive_def inf_sup_distrib2 by auto\n  also have \"... = f (x \\<sqinter> --g y) \\<sqinter> y\"\n    by (metis assms(1) conjugate_def inf_le2 pseudo_complement sup_bot.right_neutral)\n  finally have 2: \"f x \\<sqinter> y \\<le> f (x \\<sqinter> --g y)\"\n    by simp\n  have \"g y \\<sqinter> x = g ((y \\<sqinter> --f x) \\<squnion> (y \\<sqinter> -f x)) \\<sqinter> x\"\n    by (simp add: sup.commute sup_inf_distrib1)\n  also have \"... = (g (y \\<sqinter> --f x) \\<sqinter> x) \\<squnion> (g (y \\<sqinter> -f x) \\<sqinter> x)\"\n    using assms(3) additive_def inf_sup_distrib2 by auto\n  also have \"... = g (y \\<sqinter> --f x) \\<sqinter> x\"\n    by (metis assms(1) conjugate_def inf.cobounded2 pseudo_complement sup_bot.right_neutral inf_commute)\n  finally have \"g y \\<sqinter> x \\<le> g (y \\<sqinter> --f x)\"\n    by simp\n  thus ?thesis\n    using 2 by simp\nqed\n\n(*\nlemma compl_le_swap2_iff: \"-x \\<le> y \\<longleftrightarrow> -y \\<le> x\" nitpick [expect=genuine] oops\nlemma huntington_3: \"x = -(-x \\<squnion> -y) \\<squnion> -(-x \\<squnion> y)\" nitpick [expect=genuine] oops\nlemma maddux_3_1: \"x \\<squnion> -x = y \\<squnion> -y\" nitpick [expect=genuine] oops\nlemma maddux_3_4: \"x \\<squnion> (y \\<squnion> -y) = z \\<squnion> -z\" nitpick [expect=genuine] oops\nlemma maddux_3_11: \"x = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> -y)\" nitpick [expect=genuine] oops\nlemma maddux_3_19: \"(-x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (-x \\<squnion> z)\" nitpick [expect=genuine] oops\nlemma compl_inter_eq: \"x \\<sqinter> y = x \\<sqinter> z \\<and> -x \\<sqinter> y = -x \\<sqinter> z \\<longrightarrow> y = z\" nitpick [expect=genuine] oops\nlemma maddux_3_21: \"x \\<squnion> y = x \\<squnion> (-x \\<sqinter> y)\" nitpick [expect=genuine] oops\nlemma shunting_1: \"x \\<le> y \\<longleftrightarrow> x \\<sqinter> -y = bot\" nitpick [expect=genuine] oops\nlemma shunting_2: \"x \\<le> y \\<longleftrightarrow> -x \\<squnion> y = top\" nitpick [expect=genuine] oops\nlemma conjugate_unique: \"conjugate f g \\<and> conjugate f h \\<longrightarrow> g = h\" nitpick [expect=genuine] oops\nlemma conjugate_isotone_pp: \"conjugate f g \\<longrightarrow> isotone f\" nitpick [expect=genuine] oops\nlemma conjugate_char_1: \"conjugate f g \\<longleftrightarrow> (\\<forall>x y . f(x \\<sqinter> -(g y)) \\<le> f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> g y \\<sqinter> -x)\" nitpick [expect=genuine] oops\nlemma conjugate_char_2: \"conjugate f g \\<longleftrightarrow> f bot = bot \\<and> g bot = bot \\<and> (\\<forall>x y . f x \\<sqinter> y \\<le> f(x \\<sqinter> g y) \\<and> g y \\<sqinter> x \\<le> g(y \\<sqinter> f x))\" nitpick [expect=genuine] oops\nlemma shunting: \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> x \\<le> z \\<squnion> -y\" nitpick [expect=genuine] oops\nlemma shunting_var: \"x \\<sqinter> -y \\<le> z \\<longleftrightarrow> x \\<le> z \\<squnion> y\" nitpick [expect=genuine] oops\nlemma sup_compl_top: \"x \\<squnion> -x = top\" nitpick [expect=genuine] oops\nlemma selection_closed_p: \"selection s x \\<longrightarrow> selection (-s) x\" nitpick [expect=genuine] oops\nlemma selection_closed_pp: \"selection s x \\<longrightarrow> selection (--s) x\" nitpick [expect=genuine] oops\n*)\n\nend\n\nabbreviation stone_algebra_isomorphism :: \"('a::stone_algebra \\<Rightarrow> 'b::stone_algebra) \\<Rightarrow> bool\"\n  where \"stone_algebra_isomorphism f \\<equiv> sup_inf_top_bot_uminus_isomorphism f\"\n\ntext \\<open>\nEvery bounded linear order can be expanded to a Stone algebra.\nThe pseudocomplement takes \\<open>bot\\<close> to the \\<open>top\\<close> and every other element to \\<open>bot\\<close>.\n\\<close>\n\nclass linorder_stone_algebra_expansion = linorder_lattice_expansion + uminus +\n  assumes uminus_def [simp]: \"-x = (if x = bot then top else bot)\"\nbegin\n\nsubclass stone_algebra\n  apply unfold_locales\n  using bot_unique min_def top_le by auto\n\ntext \\<open>\nThe regular elements are the least and greatest elements.\nAll elements except the least element are dense.\n\\<close>\n\nlemma regular_bot_top:\n  \"regular x \\<longleftrightarrow> x = bot \\<or> x = top\"\n  by simp\n\nlemma not_bot_dense:\n  \"x \\<noteq> bot \\<Longrightarrow> --x = top\"\n  by simp\n\nend\n\nsubsection \\<open>Heyting Algebras\\<close>\n\ntext \\<open>\nIn this section we add a relative pseudocomplement operation to semilattices and to lattices.\n\\<close>\n\nsubsubsection \\<open>Heyting Semilattices\\<close>\n\ntext \\<open>\nThe pseudocomplement of an element \\<open>y\\<close> relative to an element \\<open>z\\<close> is the least element whose meet with \\<open>y\\<close> is below \\<open>z\\<close>.\nThis can be stated as a Galois connection.\nSpecialising \\<open>z = bot\\<close> gives (non-relative) pseudocomplements.\nMany properties can already be shown if the underlying structure is just a semilattice.\n\\<close>\n\nclass implies =\n  fixes implies :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<leadsto>\" 65)\n\nclass heyting_semilattice = semilattice_inf + implies +\n  assumes implies_galois: \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> x \\<le> y \\<leadsto> z\"\nbegin\n\nlemma implies_below_eq [simp]:\n  \"y \\<sqinter> (x \\<leadsto> y) = y\"\n  using implies_galois inf.absorb_iff1 inf.cobounded1 by blast\n\nlemma implies_increasing:\n  \"x \\<le> y \\<leadsto> x\"\n  by (simp add: inf.orderI)\n\nlemma implies_galois_swap:\n  \"x \\<le> y \\<leadsto> z \\<longleftrightarrow> y \\<le> x \\<leadsto> z\"\n  by (metis implies_galois inf_commute)\n\nlemma implies_galois_var:\n  \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> y \\<le> x \\<leadsto> z\"\n  by (simp add: implies_galois_swap implies_galois)\n\nlemma implies_galois_increasing:\n  \"x \\<le> y \\<leadsto> (x \\<sqinter> y)\"\n  using implies_galois by blast\n\nlemma implies_galois_decreasing:\n  \"(y \\<leadsto> x) \\<sqinter> y \\<le> x\"\n  using implies_galois by blast\n\nlemma implies_mp_below:\n  \"x \\<sqinter> (x \\<leadsto> y) \\<le> y\"\n  using implies_galois_decreasing inf_commute by auto\n\nlemma implies_isotone:\n  \"x \\<le> y \\<Longrightarrow> z \\<leadsto> x \\<le> z \\<leadsto> y\"\n  using implies_galois order_trans by blast\n\nlemma implies_antitone:\n  \"x \\<le> y \\<Longrightarrow> y \\<leadsto> z \\<le> x \\<leadsto> z\"\n  by (meson implies_galois_swap order_lesseq_imp)\n\nlemma implies_isotone_inf:\n  \"x \\<leadsto> (y \\<sqinter> z) \\<le> x \\<leadsto> y\"\n  by (simp add: implies_isotone)\n\nlemma implies_antitone_inf:\n  \"x \\<leadsto> z \\<le> (x \\<sqinter> y) \\<leadsto> z\"\n  by (simp add: implies_antitone)\n\nlemma implies_curry:\n  \"x \\<leadsto> (y \\<leadsto> z) = (x \\<sqinter> y) \\<leadsto> z\"\n  by (metis implies_galois_decreasing implies_galois inf_assoc antisym)\n\nlemma implies_curry_flip:\n  \"x \\<leadsto> (y \\<leadsto> z) = y \\<leadsto> (x \\<leadsto> z)\"\n  by (simp add: implies_curry inf_commute)\n\nlemma triple_implies [simp]:\n  \"((x \\<leadsto> y) \\<leadsto> y) \\<leadsto> y = x \\<leadsto> y\"\n  using implies_antitone implies_galois_swap eq_iff by auto\n\nlemma implies_mp_eq [simp]:\n  \"x \\<sqinter> (x \\<leadsto> y) = x \\<sqinter> y\"\n  by (metis implies_below_eq implies_mp_below inf_left_commute inf.absorb2)\n\nlemma implies_dist_implies:\n  \"x \\<leadsto> (y \\<leadsto> z) \\<le> (x \\<leadsto> y) \\<leadsto> (x \\<leadsto> z)\"\n  using implies_curry implies_curry_flip by auto\n\nlemma implies_import_inf [simp]:\n  \"x \\<sqinter> ((x \\<sqinter> y) \\<leadsto> (x \\<leadsto> z)) = x \\<sqinter> (y \\<leadsto> z)\"\n  by (metis implies_curry implies_mp_eq inf_commute)\n\nlemma implies_dist_inf:\n  \"x \\<leadsto> (y \\<sqinter> z) = (x \\<leadsto> y) \\<sqinter> (x \\<leadsto> z)\"\nproof -\n  have \"(x \\<leadsto> y) \\<sqinter> (x \\<leadsto> z) \\<sqinter> x \\<le> y \\<sqinter> z\"\n    by (simp add: implies_galois)\n  hence \"(x \\<leadsto> y) \\<sqinter> (x \\<leadsto> z) \\<le> x \\<leadsto> (y \\<sqinter> z)\"\n    using implies_galois by blast\n  thus ?thesis\n    by (simp add: implies_isotone eq_iff)\nqed\n\nlemma implies_itself_top:\n  \"y \\<le> x \\<leadsto> x\"\n  by (simp add: implies_galois_swap implies_increasing)\n\nlemma inf_implies_top:\n  \"z \\<le> (x \\<sqinter> y) \\<leadsto> x\"\n  using implies_galois_var le_infI1 by blast\n\nlemma inf_inf_implies [simp]:\n  \"z \\<sqinter> ((x \\<sqinter> y) \\<leadsto> x) = z\"\n  by (simp add: inf_implies_top inf_absorb1)\n\nlemma le_implies_top:\n  \"x \\<le> y \\<Longrightarrow> z \\<le> x \\<leadsto> y\"\n  using implies_antitone implies_itself_top order.trans by blast\n\nlemma le_iff_le_implies:\n  \"x \\<le> y \\<longleftrightarrow> x \\<le> x \\<leadsto> y\"\n  using implies_galois inf_idem by force\n\nlemma implies_inf_isotone:\n  \"x \\<leadsto> y \\<le> (x \\<sqinter> z) \\<leadsto> (y \\<sqinter> z)\"\n  by (metis implies_curry implies_galois_increasing implies_isotone)\n\nlemma implies_transitive:\n  \"(x \\<leadsto> y) \\<sqinter> (y \\<leadsto> z) \\<le> x \\<leadsto> z\"\n  using implies_dist_implies implies_galois_var implies_increasing order_lesseq_imp by blast\n\nlemma implies_inf_absorb [simp]:\n  \"x \\<leadsto> (x \\<sqinter> y) = x \\<leadsto> y\"\n  using implies_dist_inf implies_itself_top inf.absorb_iff2 by auto\n\nlemma implies_implies_absorb [simp]:\n  \"x \\<leadsto> (x \\<leadsto> y) = x \\<leadsto> y\"\n  by (simp add: implies_curry)\n\nlemma implies_inf_identity:\n  \"(x \\<leadsto> y) \\<sqinter> y = y\"\n  by (simp add: inf_commute)\n\nlemma implies_itself_same:\n  \"x \\<leadsto> x = y \\<leadsto> y\"\n  by (simp add: le_implies_top eq_iff)\n\nend\n\ntext \\<open>\nThe following class gives equational axioms for the relative pseudocomplement operation (inequalities can be written as equations).\n\\<close>\n\nclass heyting_semilattice_eq = semilattice_inf + implies +\n  assumes implies_mp_below: \"x \\<sqinter> (x \\<leadsto> y) \\<le> y\"\n      and implies_galois_increasing: \"x \\<le> y \\<leadsto> (x \\<sqinter> y)\"\n      and implies_isotone_inf: \"x \\<leadsto> (y \\<sqinter> z) \\<le> x \\<leadsto> y\"\nbegin\n\nsubclass heyting_semilattice\n  apply unfold_locales\n  apply (rule iffI)\n  apply (metis implies_galois_increasing implies_isotone_inf inf.absorb2 order_lesseq_imp)\n  by (metis implies_mp_below inf_commute order_trans inf_mono order_refl)\n\nend\n\ntext \\<open>\nThe following class allows us to explicitly give the pseudocomplement of an element relative to itself.\n\\<close>\n\nclass bounded_heyting_semilattice = bounded_semilattice_inf_top + heyting_semilattice\nbegin\n\nlemma implies_itself [simp]:\n  \"x \\<leadsto> x = top\"\n  using implies_galois inf_le2 top_le by blast\n\nlemma implies_order:\n  \"x \\<le> y \\<longleftrightarrow> x \\<leadsto> y = top\"\n  by (metis implies_galois inf_top.left_neutral top_unique)\n\nlemma inf_implies [simp]:\n  \"(x \\<sqinter> y) \\<leadsto> x = top\"\n  using implies_order inf_le1 by blast\n\nlemma top_implies [simp]:\n  \"top \\<leadsto> x = x\"\n  by (metis implies_mp_eq inf_top.left_neutral)\n\nend\n\nsubsubsection \\<open>Heyting Lattices\\<close>\n\ntext \\<open>\nWe obtain further properties if the underlying structure is a lattice.\nIn particular, the lattice operations are automatically distributive in this case.\n\\<close>\n\nclass heyting_lattice = lattice + heyting_semilattice\nbegin\n\nlemma sup_distrib_inf_le:\n  \"(x \\<squnion> y) \\<sqinter> (x \\<squnion> z) \\<le> x \\<squnion> (y \\<sqinter> z)\"\nproof -\n  have \"x \\<squnion> z \\<le> y \\<leadsto> (x \\<squnion> (y \\<sqinter> z))\"\n    using implies_galois_var implies_increasing sup.bounded_iff sup.cobounded2 by blast\n  hence \"x \\<squnion> y \\<le> (x \\<squnion> z) \\<leadsto> (x \\<squnion> (y \\<sqinter> z))\"\n    using implies_galois_swap implies_increasing le_sup_iff by blast\n  thus ?thesis\n    by (simp add: implies_galois)\nqed\n\nsubclass distrib_lattice\n  apply unfold_locales\n  using distrib_sup_le eq_iff sup_distrib_inf_le by auto\n\nlemma implies_isotone_sup:\n  \"x \\<leadsto> y \\<le> x \\<leadsto> (y \\<squnion> z)\"\n  by (simp add: implies_isotone)\n\nlemma implies_antitone_sup:\n  \"(x \\<squnion> y) \\<leadsto> z \\<le> x \\<leadsto> z\"\n  by (simp add: implies_antitone)\n\nlemma implies_sup:\n  \"x \\<leadsto> z \\<le> (y \\<leadsto> z) \\<leadsto> ((x \\<squnion> y) \\<leadsto> z)\"\nproof -\n  have \"(x \\<leadsto> z) \\<sqinter> (y \\<leadsto> z) \\<sqinter> y \\<le> z\"\n    by (simp add: implies_galois)\n  hence \"(x \\<leadsto> z) \\<sqinter> (y \\<leadsto> z) \\<sqinter> (x \\<squnion> y) \\<le> z\"\n    using implies_galois_swap implies_galois_var by fastforce\n  thus ?thesis\n    by (simp add: implies_galois)\nqed\n\nlemma implies_dist_sup:\n  \"(x \\<squnion> y) \\<leadsto> z = (x \\<leadsto> z) \\<sqinter> (y \\<leadsto> z)\"\n  apply (rule antisym)\n  apply (simp add: implies_antitone)\n  by (simp add: implies_sup implies_galois)\n\nlemma implies_antitone_isotone:\n  \"(x \\<squnion> y) \\<leadsto> (x \\<sqinter> y) \\<le> x \\<leadsto> y\"\n  by (simp add: implies_antitone_sup implies_dist_inf le_infI2)\n\nlemma implies_antisymmetry:\n  \"(x \\<leadsto> y) \\<sqinter> (y \\<leadsto> x) = (x \\<squnion> y) \\<leadsto> (x \\<sqinter> y)\"\n  by (metis implies_dist_sup implies_inf_absorb inf.commute)\n\nlemma sup_inf_implies [simp]:\n  \"(x \\<squnion> y) \\<sqinter> (x \\<leadsto> y) = y\"\n  by (simp add: inf_sup_distrib2 sup.absorb2)\n\nlemma implies_subdist_sup:\n  \"(x \\<leadsto> y) \\<squnion> (x \\<leadsto> z) \\<le> x \\<leadsto> (y \\<squnion> z)\"\n  by (simp add: implies_isotone)\n\nlemma implies_subdist_inf:\n  \"(x \\<leadsto> z) \\<squnion> (y \\<leadsto> z) \\<le> (x \\<sqinter> y) \\<leadsto> z\"\n  by (simp add: implies_antitone)\n\nlemma implies_sup_absorb:\n  \"(x \\<leadsto> y) \\<squnion> z \\<le> (x \\<squnion> z) \\<leadsto> (y \\<squnion> z)\"\n  by (metis implies_dist_sup implies_isotone_sup implies_increasing inf_inf_implies le_sup_iff sup_inf_implies)\n\nlemma sup_below_implies_implies:\n  \"x \\<squnion> y \\<le> (x \\<leadsto> y) \\<leadsto> y\"\n  by (simp add: implies_dist_sup implies_galois_swap implies_increasing)\n\nend\n\nclass bounded_heyting_lattice = bounded_lattice + heyting_lattice\nbegin\n\nsubclass bounded_heyting_semilattice ..\n\nlemma implies_bot [simp]:\n  \"bot \\<leadsto> x = top\"\n  using implies_galois top_unique by fastforce\n\nend\n\nsubsubsection \\<open>Heyting Algebras\\<close>\n\ntext \\<open>\nThe pseudocomplement operation can be defined in Heyting algebras, but it is typically not part of their signature.\nWe add the definition as an axiom so that we can use the class hierarchy, for example, to inherit results from the class \\<open>pd_algebra\\<close>.\n\\<close>\n\nclass heyting_algebra = bounded_heyting_lattice + uminus +\n  assumes uminus_eq: \"-x = x \\<leadsto> bot\"\nbegin\n\nsubclass pd_algebra\n  apply unfold_locales\n  using bot_unique implies_galois uminus_eq by auto\n\nlemma boolean_implies_below:\n  \"-x \\<squnion> y \\<le> x \\<leadsto> y\"\n  by (simp add: implies_increasing implies_isotone uminus_eq)\n\nlemma negation_implies:\n  \"-(x \\<leadsto> y) = --x \\<sqinter> -y\"\nproof (rule antisym)\n  show \"-(x \\<leadsto> y) \\<le> --x \\<sqinter> -y\"\n    using boolean_implies_below p_antitone by auto\nnext\n  have \"x \\<sqinter> -y \\<sqinter> (x \\<leadsto> y) = bot\"\n    by (metis implies_mp_eq inf_p inf_bot_left inf_commute inf_left_commute)\n  hence \"--x \\<sqinter> -y \\<sqinter> (x \\<leadsto> y) = bot\"\n    using pp_inf_bot_iff inf_assoc by auto\n  thus \"--x \\<sqinter> -y \\<le> -(x \\<leadsto> y)\"\n    by (simp add: pseudo_complement)\nqed\n\nlemma double_negation_dist_implies:\n  \"--(x \\<leadsto> y) = --x \\<leadsto> --y\"\n  apply (rule antisym)\n  apply (metis pp_inf_below_iff implies_galois_decreasing implies_galois negation_implies ppp)\n  by (simp add: p_antitone_iff negation_implies)\n\n(*\nlemma stone: \"-x \\<squnion> --x = top\" nitpick [expect=genuine] oops\n*)\n\nend\n\ntext \\<open>\nThe following class gives equational axioms for Heyting algebras.\n\\<close>\n\nclass heyting_algebra_eq = bounded_lattice + implies + uminus +\n  assumes implies_mp_eq: \"x \\<sqinter> (x \\<leadsto> y) = x \\<sqinter> y\"\n      and implies_import_inf: \"x \\<sqinter> ((x \\<sqinter> y) \\<leadsto> (x \\<leadsto> z)) = x \\<sqinter> (y \\<leadsto> z)\"\n      and inf_inf_implies: \"z \\<sqinter> ((x \\<sqinter> y) \\<leadsto> x) = z\"\n      and uminus_eq_eq: \"-x = x \\<leadsto> bot\"\nbegin\n\nsubclass heyting_algebra\n  apply unfold_locales\n  apply (rule iffI)\n  apply (metis implies_import_inf inf.sup_left_divisibility inf_inf_implies le_iff_inf)\n  apply (metis implies_mp_eq inf.commute inf.le_sup_iff inf.sup_right_isotone)\n  by (simp add: uminus_eq_eq)\n\nend\n\ntext \\<open>\nA relative pseudocomplement is not enough to obtain the Stone equation, so we add it in the following class.\n\\<close>\n\nclass heyting_stone_algebra = heyting_algebra +\n  assumes heyting_stone: \"-x \\<squnion> --x = top\"\nbegin\n\nsubclass stone_algebra\n  by unfold_locales (simp add: heyting_stone)\n\n(*\nlemma pre_linear: \"(x \\<leadsto> y) \\<squnion> (y \\<leadsto> x) = top\" nitpick [expect=genuine] oops\n*)\n\nend\n\nsubsubsection \\<open>Brouwer Algebras\\<close>\n\ntext \\<open>\nBrouwer algebras are dual to Heyting algebras.\nThe dual pseudocomplement of an element \\<open>y\\<close> relative to an element \\<open>x\\<close> is the least element whose join with \\<open>y\\<close> is above \\<open>x\\<close>.\nWe can now use the binary operation provided by Boolean algebras in Isabelle/HOL because it is compatible with dual relative pseudocomplements (not relative pseudocomplements).\n\\<close>\n\nclass brouwer_algebra = bounded_lattice + minus + uminus +\n  assumes minus_galois: \"x \\<le> y \\<squnion> z \\<longleftrightarrow> x - y \\<le> z\"\n      and uminus_eq_minus: \"-x = top - x\"\nbegin\n\nsublocale brouwer: heyting_algebra where inf = sup and less_eq = greater_eq and less = greater and sup = inf and bot = top and top = bot and implies = \"\\<lambda>x y . y - x\"\n  apply unfold_locales\n  apply simp\n  apply simp\n  apply simp\n  apply simp\n  apply (metis minus_galois sup_commute)\n  by (simp add: uminus_eq_minus)\n\nlemma curry_minus:\n  \"x - (y \\<squnion> z) = (x - y) - z\"\n  by (simp add: brouwer.implies_curry sup_commute)\n\nlemma minus_subdist_sup:\n  \"(x - z) \\<squnion> (y - z) \\<le> (x \\<squnion> y) - z\"\n  by (simp add: brouwer.implies_dist_inf)\n\nlemma inf_sup_minus:\n  \"(x \\<sqinter> y) \\<squnion> (x - y) = x\"\n  by (simp add: inf.absorb1 brouwer.inf_sup_distrib2)\n\nend\n\nsubsection \\<open>Boolean Algebras\\<close>\n\ntext \\<open>\nThis section integrates Boolean algebras in the above hierarchy.\nIn particular, we strengthen several results shown above.\n\\<close>\n\ncontext boolean_algebra\nbegin\n\ntext \\<open>\nEvery Boolean algebra is a Stone algebra, a Heyting algebra and a Brouwer algebra.\n\\<close>\n\nsubclass stone_algebra\n  apply unfold_locales\n  apply (rule iffI)\n  apply (metis compl_sup_top inf.orderI inf_bot_right inf_sup_distrib1 inf_top_right sup_inf_absorb)\n  using inf.commute inf.sup_right_divisibility apply fastforce\n  by simp\n\nsublocale heyting: heyting_algebra where implies = \"\\<lambda>x y . -x \\<squnion> y\"\n  apply unfold_locales\n  apply (rule iffI)\n  using shunting_var_p sup_commute apply fastforce\n  using shunting_var_p sup_commute apply force\n  by simp\n\nsubclass brouwer_algebra\n  apply unfold_locales\n  apply (simp add: diff_eq shunting_var_p sup.commute)\n  by (simp add: diff_eq)\n\nlemma huntington_3 [simp]:\n  \"-(-x \\<squnion> -y) \\<squnion> -(-x \\<squnion> y) = x\"\n  using huntington_3_pp by auto\n\nlemma maddux_3_1:\n  \"x \\<squnion> -x = y \\<squnion> -y\"\n  by simp\n\nlemma maddux_3_4:\n  \"x \\<squnion> (y \\<squnion> -y) = z \\<squnion> -z\"\n  by simp\n\nlemma maddux_3_11 [simp]:\n  \"(x \\<sqinter> y) \\<squnion> (x \\<sqinter> -y) = x\"\n  using brouwer.maddux_3_12 sup.commute by auto\n\nlemma maddux_3_19:\n  \"(-x \\<sqinter> y) \\<squnion> (x \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (-x \\<squnion> z)\"\n  using maddux_3_19_pp by auto\n\nlemma compl_inter_eq:\n  \"x \\<sqinter> y = x \\<sqinter> z \\<Longrightarrow> -x \\<sqinter> y = -x \\<sqinter> z \\<Longrightarrow> y = z\"\n  by (metis inf_commute maddux_3_11)\n\nlemma maddux_3_21 [simp]:\n  \"x \\<squnion> (-x \\<sqinter> y) = x \\<squnion> y\"\n  by (simp add: sup_inf_distrib1)\n\nlemma shunting_1:\n  \"x \\<le> y \\<longleftrightarrow> x \\<sqinter> -y = bot\"\n  by (simp add: pseudo_complement)\n\nlemma uminus_involutive:\n  \"uminus \\<circ> uminus = id\"\n  by auto\n\nlemma uminus_injective:\n  \"uminus \\<circ> f = uminus \\<circ> g \\<Longrightarrow> f = g\"\n  by (metis comp_assoc id_o minus_comp_minus)\n\nlemma conjugate_unique:\n  \"conjugate f g \\<Longrightarrow> conjugate f h \\<Longrightarrow> g = h\"\n  using conjugate_unique_p uminus_injective by blast\n\nlemma dual_additive_additive:\n  \"dual_additive (uminus \\<circ> f) \\<Longrightarrow> additive f\"\n  by (metis additive_def compl_eq_compl_iff dual_additive_def p_dist_sup o_def)\n\nlemma conjugate_additive:\n  \"conjugate f g \\<Longrightarrow> additive f\"\n  by (simp add: conjugate_dual_additive dual_additive_additive)\n\nlemma conjugate_isotone:\n  \"conjugate f g \\<Longrightarrow> isotone f\"\n  by (simp add: conjugate_additive additive_isotone)\n\nlemma conjugate_char_1:\n  \"conjugate f g \\<longleftrightarrow> (\\<forall>x y . f(x \\<sqinter> -(g y)) \\<le> f x \\<sqinter> -y \\<and> g(y \\<sqinter> -(f x)) \\<le> g y \\<sqinter> -x)\"\n  by (simp add: conjugate_char_1_pp)\n\nlemma conjugate_char_2:\n  \"conjugate f g \\<longleftrightarrow> f bot = bot \\<and> g bot = bot \\<and> (\\<forall>x y . f x \\<sqinter> y \\<le> f(x \\<sqinter> g y) \\<and> g y \\<sqinter> x \\<le> g(y \\<sqinter> f x))\"\n  by (simp add: conjugate_char_2_pp)\n\nlemma shunting:\n  \"x \\<sqinter> y \\<le> z \\<longleftrightarrow> x \\<le> z \\<squnion> -y\"\n  by (simp add: heyting.implies_galois sup.commute)\n\nlemma shunting_var:\n  \"x \\<sqinter> -y \\<le> z \\<longleftrightarrow> x \\<le> z \\<squnion> y\"\n  by (simp add: shunting)\n\nend\n\nclass non_trivial_stone_algebra = non_trivial_bounded_order + stone_algebra\n\nclass non_trivial_boolean_algebra = non_trivial_stone_algebra + boolean_algebra\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Stone_Algebras/P_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8774767906859264, "lm_q1q2_score": 0.7771210739715357}}
{"text": "(*  Author: Lukas Bulwahn <lukas.bulwahn-at-gmail.com> *)\n\nsection \\<open>Cardinality of Multisets\\<close>\n\ntheory Card_Multisets\nimports\n  \"HOL-Library.Multiset\"\nbegin\n\nsubsection \\<open>Additions to Multiset Theory\\<close>\n\nlemma mset_set_set_mset_subseteq:\n  \"mset_set (set_mset M) \\<subseteq># M\"\nproof (induct M)\n  case empty\n  show ?case by simp\nnext\n  case (add x M)\n  from this show ?case\n  proof (cases \"x \\<in># M\")\n    assume \"x \\<in># M\"\n    from this have \"mset_set (set_mset (M + {#x#})) = mset_set (set_mset M)\"\n      by (simp add: insert_absorb)\n    from this add.hyps show ?thesis\n      using subset_mset.trans by fastforce\n  next\n    assume \"\\<not> x \\<in># M\"\n    from this add.hyps have \"{#x#} + mset_set (set_mset M) \\<subseteq># M + {#x#}\"\n      by (simp add: insert_subset_eq_iff)\n    from this \\<open>\\<not> x \\<in># M\\<close> show ?thesis by simp\n  qed\nqed\n\nlemma size_mset_set_eq_card:\n  assumes \"finite A\"\n  shows \"size (mset_set A) = card A\"\nusing assms by (induct A) auto\n\nlemma card_set_mset_leq:\n  \"card (set_mset M) \\<le> size M\"\nby (induct M) (auto simp add: card_insert_le_m1)\n\nsubsection \\<open>Lemma to Enumerate Sets of Multisets\\<close>\n\nlemma set_of_multisets_eq:\n  assumes \"x \\<notin> A\"\n  shows \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k} =\n    {M. set_mset M \\<subseteq> A \\<and> size M = Suc k} \\<union>\n    (\\<lambda>M. M + {#x#}) ` {M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\"\nproof -\n  from \\<open>x \\<notin> A\\<close> have \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k} =\n    {M. set_mset M \\<subseteq> A \\<and> size M = Suc k} \\<union>\n    {M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k \\<and> x \\<in># M}\"\n    by auto\n  moreover have \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k \\<and> x \\<in># M} =\n    (\\<lambda>M. M + {#x#}) ` {M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\" (is \"?S = ?T\")\n  proof\n    show \"?S \\<subseteq> ?T\"\n    proof\n      fix M\n      assume \"M \\<in> ?S\"\n      from this have \"M = M - {#x#} + {#x#}\" by auto\n      moreover have \"M - {#x#} \\<in> {M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\"\n      proof -\n        have \"set_mset (M - {#x#} + {#x#}) \\<subseteq> insert x A\"\n          using \\<open>M \\<in> ?S\\<close> by force\n        moreover have \"size (M - {#x#} + {#x#}) = Suc k \\<and> x \\<in># M - {#x#} + {#x#}\"\n          using \\<open>M \\<in> ?S\\<close> by force\n        ultimately show ?thesis by force\n      qed\n      ultimately show \"M \\<in> ?T\" by auto\n    qed\n  next\n    show \"?T \\<subseteq> ?S\" by force\n  qed\n  ultimately show ?thesis by auto\nqed\n\nsubsection \\<open>Derivation of Suitable Induction Rule\\<close>\n\ncontext\nbegin\n\nprivate inductive R :: \"'a set \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere\n  \"finite A \\<Longrightarrow> R A 0\"\n| \"R {} k\"\n| \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> R A (Suc k) \\<Longrightarrow> R (insert x A) k \\<Longrightarrow> R (insert x A) (Suc k)\"\n\nprivate lemma R_eq_finite:\n  \"R A k \\<longleftrightarrow> finite A\"\nproof\n  assume \"R A k\"\n  from this show \"finite A\" by cases auto\nnext\n  assume \"finite A\"\n  from this show \"R A k\"\n  proof (induct A)\n    case empty\n    from this show ?case by (rule R.intros(2))\n  next\n    case insert\n    from this show ?case\n    proof (induct k)\n      case 0\n      from this show ?case\n        by (intro R.intros(1) finite.insertI)\n    next\n      case Suc\n      from this show ?case\n        by (metis R.simps Zero_neq_Suc diff_Suc_1)\n    qed\n  qed\nqed\n\nlemma finite_set_and_nat_induct[consumes 1, case_names zero empty step]:\n  assumes \"finite A\"\n  assumes \"\\<And>A. finite A \\<Longrightarrow> P A 0\"\n  assumes \"\\<And>k. P {} k\"\n  assumes \"\\<And>A k x. finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> P A (Suc k) \\<Longrightarrow> P (insert x A) k \\<Longrightarrow> P (insert x A) (Suc k)\"\n  shows \"P A k\"\nproof -\n  from \\<open>finite A\\<close> have \"R A k\" by (subst R_eq_finite)\n  from this assms(2-4) show ?thesis by (induct A k) auto\nqed\n\nend\n\nsubsection \\<open>Finiteness of Sets of Multisets\\<close>\n\nlemma finite_multisets:\n  assumes \"finite A\"\n  shows \"finite {M. set_mset M \\<subseteq> A \\<and> size M = k}\"\nusing assms\nproof (induct A k rule: finite_set_and_nat_induct)\n  case zero\n  from this show ?case by auto\nnext\n  case empty\n  from this show ?case by auto\nnext\n  case (step A k x)\n  from this show ?case\n    using set_of_multisets_eq[OF \\<open>x \\<notin> A\\<close>] by simp\nqed\n\nsubsection \\<open>Cardinality of Multisets\\<close>\n\nlemma card_multisets:\n  assumes \"finite A\"\n  shows \"card {M. set_mset M \\<subseteq> A \\<and> size M = k} = (card A + k - 1) choose k\"\nusing assms\nproof (induct A k rule: finite_set_and_nat_induct)\n  case (zero A)\n  assume \"finite (A :: 'a set)\"\n  have \"{M. set_mset M \\<subseteq> A \\<and> size M = 0} = {{#}}\" by auto\n  from this show \"card {M. set_mset M \\<subseteq> A \\<and> size M = 0} = card A + 0 - 1 choose 0\"\n    by simp\nnext\n  case (empty k)\n  show \"card {M. set_mset M \\<subseteq> {} \\<and> size M = k} = card {} + k - 1 choose k\"\n    by (cases k) (auto simp add: binomial_eq_0)\nnext\n  case (step A k x)\n  let ?S\\<^sub>1 = \"{M. set_mset M \\<subseteq> A \\<and> size M = Suc k}\"\n  and ?S\\<^sub>2 = \"{M. set_mset M \\<subseteq> insert x A \\<and> size M = k}\"\n  assume hyps1: \"card ?S\\<^sub>1 = card A + Suc k - 1 choose Suc k\"\n  assume hyps2: \"card ?S\\<^sub>2 = card (insert x A) + k - 1 choose k\"\n  have finite_sets: \"finite ?S\\<^sub>1\" \"finite ((\\<lambda>M. M + {#x#}) ` ?S\\<^sub>2)\"\n    using \\<open>finite A\\<close> by (auto simp add: finite_multisets)\n  have inj: \"inj_on (\\<lambda>M. M + {#x#}) ?S\\<^sub>2\" by (rule inj_onI) auto\n  have \"card {M. set_mset M \\<subseteq> insert x A \\<and> size M = Suc k} =\n    card (?S\\<^sub>1 \\<union> (\\<lambda>M. M + {#x#}) ` ?S\\<^sub>2)\"\n    using set_of_multisets_eq \\<open>x \\<notin> A\\<close> by fastforce\n  also have \"\\<dots> = card ?S\\<^sub>1 + card ((\\<lambda>M. M + {#x#}) ` ?S\\<^sub>2)\"\n    using finite_sets \\<open>x \\<notin> A\\<close> by (subst card_Un_disjoint) auto\n  also have \"\\<dots> = card ?S\\<^sub>1 + card ?S\\<^sub>2\"\n    using inj by (auto intro: card_image)\n  also have \"\\<dots> = card A + Suc k - 1 choose Suc k + (card (insert x A) + k - 1 choose k)\"\n    using hyps1 hyps2 by simp\n  also have \"\\<dots> = card (insert x A) + Suc k - 1 choose Suc k\"\n    using \\<open>x \\<notin> A\\<close> \\<open>finite A\\<close> by simp\n  finally show ?case .\nqed\n\nlemma card_too_small_multisets_covering_set:\n  assumes \"finite A\"\n  assumes \"k < card A\"\n  shows \"card {M. set_mset M = A \\<and> size M = k} = 0\"\nproof -\n  from \\<open>k < card A\\<close> have eq: \"{M. set_mset M = A \\<and> size M = k} = {}\"\n    using card_set_mset_leq Collect_empty_eq leD by auto\n  from this show ?thesis by (metis card.empty)\nqed\n\nlemma card_multisets_covering_set:\n  assumes \"finite A\"\n  assumes \"card A \\<le> k\"\n  shows \"card {M. set_mset M = A \\<and> size M = k} = (k - 1) choose (k - card A)\"\nproof -\n  have \"{M. set_mset M = A \\<and> size M = k} = (\\<lambda>M. M + mset_set A) `\n    {M. set_mset M \\<subseteq> A \\<and> size M = k - card A}\" (is \"?S = ?f ` ?T\")\n  proof\n    show \"?S \\<subseteq> ?f ` ?T\"\n    proof\n      fix M\n      assume \"M \\<in> ?S\"\n      from this have \"M = M - mset_set A + mset_set A\"\n        by (auto simp add: mset_set_set_mset_subseteq subset_mset.diff_add)\n      moreover from \\<open>M \\<in> ?S\\<close> have \"M - mset_set A \\<in> ?T\"\n        by (auto simp add: mset_set_set_mset_subseteq size_Diff_submset size_mset_set_eq_card in_diffD)\n      ultimately show \"M \\<in> ?f ` ?T\" by auto\n    qed\n  next\n    from \\<open>finite A\\<close> \\<open>card A \\<le> k\\<close> show \"?f ` ?T \\<subseteq> ?S\"\n      by (auto simp add: size_mset_set_eq_card)+\n  qed\n  moreover have \"inj_on ?f ?T\" by (rule inj_onI) auto\n  ultimately have \"card ?S = card ?T\" by (simp add: card_image)\n  also have \"\\<dots> = card A + (k - card A) - 1 choose (k - card A)\"\n    using \\<open>finite A\\<close> by (simp only: card_multisets)\n  also have \"\\<dots> = (k - 1) choose (k - card A)\"\n    using \\<open>card A \\<le> k\\<close> by auto\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Card_Multisets/Card_Multisets.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8774767794716264, "lm_q1q2_score": 0.7771210481471401}}
{"text": "section \\<open>ListUtilities\\<close>\n\ntext \\<open>\n  \\file{ListUtilities} defines a (proper) prefix relation for lists, and proves some\n  additional lemmata, mostly about lists.\n\\<close>\n\ntheory ListUtilities\nimports Main\nbegin\n\ncontext begin\n\nsubsection \\<open>List Prefixes\\<close>\n\ninductive prefixList ::\n  \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n  \"prefixList [] (x # xs)\"\n| \"prefixList xa xb \\<Longrightarrow> prefixList (x # xa) (x # xb)\"\n\nlemma PrefixListHasTail:\nfixes \n  l1 :: \"'a list\" and\n  l2 :: \"'a list\"\nassumes\n  \"prefixList l1 l2\"\nshows\n  \"\\<exists> l . l2 = l1 @ l \\<and> l \\<noteq> []\"\n  using assms by (induct rule: prefixList.induct, auto)\n\nlemma PrefixListMonotonicity:\nfixes \n  l1 :: \"'a list\" and\n  l2 :: \"'a list\"\nassumes\n  \"prefixList l1 l2\"\nshows\n  \"length l1 < length l2\"\nusing assms by (induct rule: prefixList.induct, auto)\n\nlemma TailIsPrefixList : \nfixes \n  l1 :: \"'a list\" and\n  tail :: \"'a list\"\nassumes \"tail \\<noteq> []\"\nshows \"prefixList l1 (l1 @ tail)\"\nusing assms\nproof (induct l1, auto)\n  have \"\\<exists> x xs . tail = x # xs\"\n    using assms by (metis neq_Nil_conv)\n  thus \"prefixList [] tail\"\n    using assms  by (metis prefixList.intros(1))\nnext\n  fix a l1\n  assume \"prefixList l1 (l1 @ tail)\"\n  thus \"prefixList (a # l1) (a # l1 @ tail)\"\n    by (metis prefixList.intros(2))\nqed\n\nlemma PrefixListTransitive:\nfixes \n  l1 :: \"'a list\" and\n  l2 :: \"'a list\" and\n  l3 :: \"'a list\"\nassumes\n  \"prefixList l1 l2\"\n  \"prefixList l2 l3\"\nshows\n  \"prefixList l1 l3\"\nusing assms\nproof -\n  from assms(1) have \"\\<exists> l12 . l2 = l1 @ l12 \\<and> l12 \\<noteq> []\" \n    using PrefixListHasTail by auto\n  then obtain l12 where Extend1: \"l2 = l1 @ l12 \\<and> l12 \\<noteq> []\" by blast\n  from assms(2) have Extend2: \"\\<exists> l23 . l3 = l2 @ l23 \\<and> l23 \\<noteq> []\" \n    using PrefixListHasTail by auto\n  then obtain l23 where Extend2: \"l3 = l2 @ l23 \\<and> l23 \\<noteq> []\" by blast\n  have \"l3 = l1 @ (l12 @ l23) \\<and> (l12 @ l23) \\<noteq> []\" \n    using Extend1 Extend2 by simp\n  hence \"\\<exists> l . l3 = l1 @ l \\<and> l \\<noteq> []\" by blast\n  thus \"prefixList l1 l3\" using TailIsPrefixList by auto  \nqed\n\nsubsection \\<open>Lemmas for lists and nat predicates\\<close>\n\nlemma NatPredicateTippingPoint:\n  assumes\n    P0: \"P 0\" and NotPN2: \"\\<not>P n2\"\n  shows\n    \"\\<exists>n<n2. P n \\<and> \\<not>P (Suc n)\"\n  by (metis NotPN2 P0 dec_induct zero_le)\n\nlemma MinPredicate:\nfixes \n  P::\"nat \\<Rightarrow> bool\"\nassumes\n  \"\\<exists> n . P n\"\nshows \n  \"(\\<exists> n0 . (P n0) \\<and> (\\<forall> n' . (P n') \\<longrightarrow> (n' \\<ge> n0)))\"\nusing assms\nby (metis LeastI2_wellorder Suc_n_not_le_n)\n\ntext \\<open>\n  The lemma \\isb{MinPredicate2} describes one case of \\isb{MinPredicate}\n  where the aforementioned smallest element is zero.\n\\<close>\n\nlemma MinPredicate2:\nfixes\n  P::\"nat \\<Rightarrow> bool\"\nassumes\n \"\\<exists> n . P n\"\nshows\n  \"\\<exists> n0 . (P n0) \\<and> (n0 = 0 \\<or> \\<not> P (n0 - 1))\"\nusing assms MinPredicate\nby (metis add_diff_cancel_right' diff_is_0_eq diff_mult_distrib mult_eq_if)\n\ntext \\<open>\n  \\isb{PredicatePairFunction} allows to obtain functions mapping two arguments\n  to pairs from 4-ary predicates which are left-total on their first\n  two arguments.\n\\<close>\n\nprivate\nlemma PredicatePairFunction: \nfixes\n  P::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\nassumes\n  A1: \"\\<forall>x1 x2 . \\<exists>y1 y2 . (P x1 x2 y1 y2)\"\nshows \n  \"\\<exists>f . \\<forall>x1 x2 . \\<exists>y1 y2 .\n    (f x1 x2) = (y1, y2) \n    \\<and> (P x1 x2 (fst (f x1 x2)) (snd (f x1 x2)))\"\nproof -\n  define P' where \"P'==\\<lambda>x y . P (fst x) (snd x) (fst y) (snd y)\"\n  hence \"\\<forall>x . \\<exists>y . (P' x  y)\" using A1 by auto\n  hence A3: \"\\<exists>f . \\<forall>x . P' x (f x)\" by metis\n  then obtain f where \"\\<forall>x . P' x (f x)\" by blast\n  moreover define f' where  \"f'==\\<lambda>x1 x2. f (x1, x2)\"\n  ultimately have \"\\<forall>x . P' x (f' (fst x) (snd x))\" by auto\n  hence \"\\<exists>f' . \\<forall>x . P' x (f' (fst x) (snd x))\" by blast\n  thus ?thesis using P'_def by auto\nqed           \n\nlemma PredicatePairFunctions2: \nfixes\n  P::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\nassumes\n  A1: \"\\<forall>x1 x2 . \\<exists>y1 y2 . (P x1 x2 y1 y2)\"\nobtains f1 f2  where\n  \"\\<forall>x1 x2 . \\<exists>y1 y2 .\n    (f1 x1 x2) = y1 \\<and> (f2 x1 x2) = y2 \n    \\<and> (P x1 x2 (f1 x1 x2) (f2 x1 x2))\"\nproof (cases thesis, auto)\n  assume ass: \"\\<And>f1 f2. \\<forall>x1 x2. P x1 x2 (f1 x1 x2) (f2 x1 x2) \\<Longrightarrow> False\"\n  obtain f where F: \"\\<forall>x1 x2. \\<exists>y1 y2. f x1 x2 = (y1, y2) \\<and> P x1 x2 (fst (f x1 x2)) (snd (f x1 x2))\"\n    using PredicatePairFunction[OF A1] by blast\n  define f1 where \"f1 \\<equiv> \\<lambda>x1 x2 . fst (f x1 x2)\"\n  define f2 where \"f2 \\<equiv> \\<lambda>x1 x2 . snd (f x1 x2)\"\n  show False\n    using ass[of f1 f2] F unfolding f1_def f2_def by auto\nqed\n\nlemma PredicatePairFunctions2Inv: \nfixes\n  P::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\nassumes\n  A1: \"\\<forall>x1 x2 . \\<exists>y1 y2 . (P x1 x2 y1 y2)\"\nobtains f1 f2  where\n  \"\\<forall>x1 x2 . (P x1 x2 (f1 x1 x2) (f2 x1 x2))\"\nusing PredicatePairFunctions2[OF A1] by auto\n\nlemma SmallerMultipleStepsWithLimit:\nfixes\n  k A limit\nassumes\n  \"\\<forall> n \\<ge> limit . (A (Suc n)) < (A n)\"\nshows\n  \"\\<forall> n \\<ge> limit . (A (n + k)) \\<le> (A n) - k\"\nproof(induct k,auto)\n  fix n k\n  assume IH: \"\\<forall>n\\<ge>limit. A (n + k) \\<le> A n - k\" \"limit \\<le> n\"\n  hence \"A (Suc (n + k)) < A (n + k)\" using assms by simp \n  hence \"A (Suc (n + k)) < A n - k\" using IH by auto\n  thus \"A (Suc (n + k)) \\<le> A n - Suc k\" \n    by (metis Suc_lessI add_Suc_right add_diff_cancel_left' \n       less_diff_conv less_or_eq_imp_le add.commute)\nqed\n\nlemma PrefixSameOnLow:\nfixes\n  l1 l2\nassumes\n  \"prefixList l1 l2\"\nshows\n  \"\\<forall> index < length l1 . l1 ! index = l2 ! index\"\nusing assms\nproof(induct rule: prefixList.induct, auto)\n  fix xa xb ::\"'a list\" and x index\n  assume AssumpProof: \"prefixList xa xb\" \n        \"\\<forall>index < length xa. xa ! index = xb ! index\"\n        \"prefixList l1 l2\" \"index < Suc (length xa)\"\n  show \"(x # xa) ! index = (x # xb) ! index\" using AssumpProof\n  proof(cases \"index = 0\", auto)\n  qed\nqed\n\nlemma KeepProperty:\nfixes\n  P Q low\nassumes\n  \"\\<forall> i \\<ge> low . P i \\<longrightarrow> (P (Suc i) \\<and> Q i)\" \"P low\"\nshows\n  \"\\<forall> i \\<ge> low . Q i\"\nusing assms\nproof(clarify)\n  fix i\n  assume Assump:\n    \"\\<forall>i\\<ge>low. P i \\<longrightarrow> P (Suc i) \\<and> Q i\"\n    \"P low\"\n    \"low \\<le> i\"\n  hence \"\\<forall>i\\<ge>low. P i \\<longrightarrow> P (Suc i)\" by blast\n  hence \"\\<forall> i \\<ge> low . P i\" using Assump(2) by (metis dec_induct)\n  hence \"P i\" using Assump(3) by blast\n  thus \"Q i\" using Assump by blast\nqed\n\nlemma ListLenDrop:\nfixes\n  i la lb\nassumes\n  \"i < length lb\"\n  \"i \\<ge> la\"\nshows\n  \"lb ! i \\<in> set (drop la lb)\"\nusing assms\nby (metis Cons_nth_drop_Suc in_set_member member_rec(1)\n       set_drop_subset_set_drop set_rev_mp)\n\nprivate\nlemma DropToShift:\nfixes\n  l i list\nassumes\n  \"l + i < length list\"\nshows\n  \"(drop l list) ! i = list ! (l + i)\"\nusing assms\nby (induct l, auto)\n\nlemma SetToIndex:\nfixes\n  a and liste::\"'a list\"\nassumes\n  AssumpSetToIndex: \"a \\<in> set liste\"\nshows\n  \"\\<exists> index < length liste . a = liste ! index\"\n  by (metis assms in_set_conv_nth)\n\nprivate\nlemma DropToIndex:\nfixes\n  a::\"'a\" and l liste \nassumes\n  AssumpDropToIndex: \"a \\<in> set (drop l liste)\"\nshows\n  \"\\<exists> i \\<ge> l . i < length liste \\<and> a = liste ! i\"\nproof-\n  have \"\\<exists> index < length (drop l liste) . a = (drop l liste) ! index\"\n    using AssumpDropToIndex SetToIndex[of \"a\" \"drop l liste\"] by blast\n  then obtain index where Index: \"index < length (drop l liste)\" \n    \"a = (drop l liste) ! index\" by blast\n  have \"l + index < length liste\" using Index(1) \n    by (metis length_drop less_diff_conv add.commute)\n  hence \"a = liste ! (l + index)\" \n    using DropToShift[of \"l\" \"index\"] Index(2) by blast\n  thus \"\\<exists>i\\<ge>l. i < length liste \\<and> a = liste ! i\" \n    by (metis \\<open>l + index < length liste\\<close> le_add1)\nqed\n\nend\n\nend", "meta": {"author": "nano-o", "repo": "Isabelle-FLP", "sha": "248d1da0a38d3beee3bcd44d810b2e3d2e57e04a", "save_path": "github-repos/isabelle/nano-o-Isabelle-FLP", "path": "github-repos/isabelle/nano-o-Isabelle-FLP/Isabelle-FLP-248d1da0a38d3beee3bcd44d810b2e3d2e57e04a/ListUtilities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.777081971429956}}
{"text": "theory ex_4_2\n  imports Main\nbegin\n\nlemma \"\\<exists>ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof -\n  let ?l_zs = \"length xs div 2\"\n  let ?l_ys = \"length xs - ?l_zs\"\n  \n  have \"?l_ys \\<le> length xs\" by simp\n\n  let ?ys = \"take ?l_ys xs\"\n  let ?zs = \"drop ?l_ys xs\"\n  have concat:\"xs = ?ys @ ?zs\" by simp\n  hence \"length xs = length ?ys + length ?zs\" by simp\n  moreover from `?l_ys \\<le> length xs` have l_ys:\"length ?ys = ?l_ys\" by simp\n  ultimately have l_zs:\"length ?zs = ?l_zs\" by simp\n\n  have \"xs = ?ys @ ?zs \\<and> (length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1)\"\n  proof cases\n    assume \"?l_ys = ?l_zs\"\n    with concat l_ys l_zs show ?thesis by auto\n  next\n    assume \"?l_ys \\<noteq> ?l_zs\"\n    hence \"?l_ys = ?l_zs + 1\" by auto\n    with concat l_ys l_zs show ?thesis by auto\n  qed\n  thus ?thesis by blast\nqed\nend", "meta": {"author": "20051615", "repo": "Gale-Shapley-formalization", "sha": "d601131b66c039561f8a72cd4913fcf8c84f08fa", "save_path": "github-repos/isabelle/20051615-Gale-Shapley-formalization", "path": "github-repos/isabelle/20051615-Gale-Shapley-formalization/Gale-Shapley-formalization-d601131b66c039561f8a72cd4913fcf8c84f08fa/tutorials/prog-prove/ex_4_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896715436482, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.7770498961060206}}
{"text": "(*  Title:      HOL/Probability/Independent_Family.thy\n    Author:     Johannes Hölzl, TU München\n    Author:     Sudeep Kanav, TU München\n*)\n\nsection \\<open>Independent families of events, event sets, and random variables\\<close>\n\ntheory Independent_Family\n  imports Infinite_Product_Measure\nbegin\n\ndefinition (in prob_space)\n  \"indep_sets F I \\<longleftrightarrow> (\\<forall>i\\<in>I. F i \\<subseteq> events) \\<and>\n    (\\<forall>J\\<subseteq>I. J \\<noteq> {} \\<longrightarrow> finite J \\<longrightarrow> (\\<forall>A\\<in>Pi J F. prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))))\"\n\ndefinition (in prob_space)\n  \"indep_set A B \\<longleftrightarrow> indep_sets (case_bool A B) UNIV\"\n\ndefinition (in prob_space)\n  indep_events_def_alt: \"indep_events A I \\<longleftrightarrow> indep_sets (\\<lambda>i. {A i}) I\"\n\nlemma (in prob_space) indep_events_def:\n  \"indep_events A I \\<longleftrightarrow> (A`I \\<subseteq> events) \\<and>\n    (\\<forall>J\\<subseteq>I. J \\<noteq> {} \\<longrightarrow> finite J \\<longrightarrow> prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j)))\"\n  unfolding indep_events_def_alt indep_sets_def\n  apply (simp add: Ball_def Pi_iff image_subset_iff_funcset)\n  apply (intro conj_cong refl arg_cong[where f=All] ext imp_cong)\n  apply auto\n  done\n\nlemma (in prob_space) indep_eventsI:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> F i \\<in> sets M) \\<Longrightarrow> (\\<And>J. J \\<subseteq> I \\<Longrightarrow> finite J \\<Longrightarrow> J \\<noteq> {} \\<Longrightarrow> prob (\\<Inter>i\\<in>J. F i) = (\\<Prod>i\\<in>J. prob (F i))) \\<Longrightarrow> indep_events F I\"\n  by (auto simp: indep_events_def)\n\ndefinition (in prob_space)\n  \"indep_event A B \\<longleftrightarrow> indep_events (case_bool A B) UNIV\"\n\nlemma (in prob_space) indep_sets_cong:\n  \"I = J \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> F i = G i) \\<Longrightarrow> indep_sets F I \\<longleftrightarrow> indep_sets G J\"\n  by (simp add: indep_sets_def, intro conj_cong all_cong imp_cong ball_cong) blast+\n\nlemma (in prob_space) indep_events_finite_index_events:\n  \"indep_events F I \\<longleftrightarrow> (\\<forall>J\\<subseteq>I. J \\<noteq> {} \\<longrightarrow> finite J \\<longrightarrow> indep_events F J)\"\n  by (auto simp: indep_events_def)\n\nlemma (in prob_space) indep_sets_finite_index_sets:\n  \"indep_sets F I \\<longleftrightarrow> (\\<forall>J\\<subseteq>I. J \\<noteq> {} \\<longrightarrow> finite J \\<longrightarrow> indep_sets F J)\"\nproof (intro iffI allI impI)\n  assume *: \"\\<forall>J\\<subseteq>I. J \\<noteq> {} \\<longrightarrow> finite J \\<longrightarrow> indep_sets F J\"\n  show \"indep_sets F I\" unfolding indep_sets_def\n  proof (intro conjI ballI allI impI)\n    fix i assume \"i \\<in> I\"\n    with *[THEN spec, of \"{i}\"] show \"F i \\<subseteq> events\"\n      by (auto simp: indep_sets_def)\n  qed (insert *, auto simp: indep_sets_def)\nqed (auto simp: indep_sets_def)\n\nlemma (in prob_space) indep_sets_mono_index:\n  \"J \\<subseteq> I \\<Longrightarrow> indep_sets F I \\<Longrightarrow> indep_sets F J\"\n  unfolding indep_sets_def by auto\n\nlemma (in prob_space) indep_sets_mono_sets:\n  assumes indep: \"indep_sets F I\"\n  assumes mono: \"\\<And>i. i\\<in>I \\<Longrightarrow> G i \\<subseteq> F i\"\n  shows \"indep_sets G I\"\nproof -\n  have \"(\\<forall>i\\<in>I. F i \\<subseteq> events) \\<Longrightarrow> (\\<forall>i\\<in>I. G i \\<subseteq> events)\"\n    using mono by auto\n  moreover have \"\\<And>A J. J \\<subseteq> I \\<Longrightarrow> A \\<in> (\\<Pi> j\\<in>J. G j) \\<Longrightarrow> A \\<in> (\\<Pi> j\\<in>J. F j)\"\n    using mono by (auto simp: Pi_iff)\n  ultimately show ?thesis\n    using indep by (auto simp: indep_sets_def)\nqed\n\nlemma (in prob_space) indep_sets_mono:\n  assumes indep: \"indep_sets F I\"\n  assumes mono: \"J \\<subseteq> I\" \"\\<And>i. i\\<in>J \\<Longrightarrow> G i \\<subseteq> F i\"\n  shows \"indep_sets G J\"\n  apply (rule indep_sets_mono_sets)\n  apply (rule indep_sets_mono_index)\n  apply (fact +)\n  done\n\nlemma (in prob_space) indep_setsI:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> F i \\<subseteq> events\"\n    and \"\\<And>A J. J \\<noteq> {} \\<Longrightarrow> J \\<subseteq> I \\<Longrightarrow> finite J \\<Longrightarrow> (\\<forall>j\\<in>J. A j \\<in> F j) \\<Longrightarrow> prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))\"\n  shows \"indep_sets F I\"\n  using assms unfolding indep_sets_def by (auto simp: Pi_iff)\n\nlemma (in prob_space) indep_setsD:\n  assumes \"indep_sets F I\" and \"J \\<subseteq> I\" \"J \\<noteq> {}\" \"finite J\" \"\\<forall>j\\<in>J. A j \\<in> F j\"\n  shows \"prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))\"\n  using assms unfolding indep_sets_def by auto\n\nlemma (in prob_space) indep_setI:\n  assumes ev: \"A \\<subseteq> events\" \"B \\<subseteq> events\"\n    and indep: \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> prob (a \\<inter> b) = prob a * prob b\"\n  shows \"indep_set A B\"\n  unfolding indep_set_def\nproof (rule indep_setsI)\n  fix F J assume \"J \\<noteq> {}\" \"J \\<subseteq> UNIV\"\n    and F: \"\\<forall>j\\<in>J. F j \\<in> (case j of True \\<Rightarrow> A | False \\<Rightarrow> B)\"\n  have \"J \\<in> Pow UNIV\" by auto\n  with F \\<open>J \\<noteq> {}\\<close> indep[of \"F True\" \"F False\"]\n  show \"prob (\\<Inter>j\\<in>J. F j) = (\\<Prod>j\\<in>J. prob (F j))\"\n    unfolding UNIV_bool Pow_insert by (auto simp: ac_simps)\nqed (auto split: bool.split simp: ev)\n\nlemma (in prob_space) indep_setD:\n  assumes indep: \"indep_set A B\" and ev: \"a \\<in> A\" \"b \\<in> B\"\n  shows \"prob (a \\<inter> b) = prob a * prob b\"\n  using indep[unfolded indep_set_def, THEN indep_setsD, of UNIV \"case_bool a b\"] ev\n  by (simp add: ac_simps UNIV_bool)\n\nlemma (in prob_space)\n  assumes indep: \"indep_set A B\"\n  shows indep_setD_ev1: \"A \\<subseteq> events\"\n    and indep_setD_ev2: \"B \\<subseteq> events\"\n  using indep unfolding indep_set_def indep_sets_def UNIV_bool by auto\n\nlemma (in prob_space) indep_sets_Dynkin:\n  assumes indep: \"indep_sets F I\"\n  shows \"indep_sets (\\<lambda>i. Dynkin (space M) (F i)) I\"\n    (is \"indep_sets ?F I\")\nproof (subst indep_sets_finite_index_sets, intro allI impI ballI)\n  fix J assume \"finite J\" \"J \\<subseteq> I\" \"J \\<noteq> {}\"\n  with indep have \"indep_sets F J\"\n    by (subst (asm) indep_sets_finite_index_sets) auto\n  { fix J K assume \"indep_sets F K\"\n    let ?G = \"\\<lambda>S i. if i \\<in> S then ?F i else F i\"\n    assume \"finite J\" \"J \\<subseteq> K\"\n    then have \"indep_sets (?G J) K\"\n    proof induct\n      case (insert j J)\n      moreover define G where \"G = ?G J\"\n      ultimately have G: \"indep_sets G K\" \"\\<And>i. i \\<in> K \\<Longrightarrow> G i \\<subseteq> events\" and \"j \\<in> K\"\n        by (auto simp: indep_sets_def)\n      let ?D = \"{E\\<in>events. indep_sets (G(j := {E})) K }\"\n      { fix X assume X: \"X \\<in> events\"\n        assume indep: \"\\<And>J A. J \\<noteq> {} \\<Longrightarrow> J \\<subseteq> K \\<Longrightarrow> finite J \\<Longrightarrow> j \\<notin> J \\<Longrightarrow> (\\<forall>i\\<in>J. A i \\<in> G i)\n          \\<Longrightarrow> prob ((\\<Inter>i\\<in>J. A i) \\<inter> X) = prob X * (\\<Prod>i\\<in>J. prob (A i))\"\n        have \"indep_sets (G(j := {X})) K\"\n        proof (rule indep_setsI)\n          fix i assume \"i \\<in> K\" then show \"(G(j:={X})) i \\<subseteq> events\"\n            using G X by auto\n        next\n          fix A J assume J: \"J \\<noteq> {}\" \"J \\<subseteq> K\" \"finite J\" \"\\<forall>i\\<in>J. A i \\<in> (G(j := {X})) i\"\n          show \"prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))\"\n          proof cases\n            assume \"j \\<in> J\"\n            with J have \"A j = X\" by auto\n            show ?thesis\n            proof cases\n              assume \"J = {j}\" then show ?thesis by simp\n            next\n              assume \"J \\<noteq> {j}\"\n              have \"prob (\\<Inter>i\\<in>J. A i) = prob ((\\<Inter>i\\<in>J-{j}. A i) \\<inter> X)\"\n                using \\<open>j \\<in> J\\<close> \\<open>A j = X\\<close> by (auto intro!: arg_cong[where f=prob] split: if_split_asm)\n              also have \"\\<dots> = prob X * (\\<Prod>i\\<in>J-{j}. prob (A i))\"\n              proof (rule indep)\n                show \"J - {j} \\<noteq> {}\" \"J - {j} \\<subseteq> K\" \"finite (J - {j})\" \"j \\<notin> J - {j}\"\n                  using J \\<open>J \\<noteq> {j}\\<close> \\<open>j \\<in> J\\<close> by auto\n                show \"\\<forall>i\\<in>J - {j}. A i \\<in> G i\"\n                  using J by auto\n              qed\n              also have \"\\<dots> = prob (A j) * (\\<Prod>i\\<in>J-{j}. prob (A i))\"\n                using \\<open>A j = X\\<close> by simp\n              also have \"\\<dots> = (\\<Prod>i\\<in>J. prob (A i))\"\n                unfolding prod.insert_remove[OF \\<open>finite J\\<close>, symmetric, of \"\\<lambda>i. prob  (A i)\"]\n                using \\<open>j \\<in> J\\<close> by (simp add: insert_absorb)\n              finally show ?thesis .\n            qed\n          next\n            assume \"j \\<notin> J\"\n            with J have \"\\<forall>i\\<in>J. A i \\<in> G i\" by (auto split: if_split_asm)\n            with J show ?thesis\n              by (intro indep_setsD[OF G(1)]) auto\n          qed\n        qed }\n      note indep_sets_insert = this\n      have \"Dynkin_system (space M) ?D\"\n      proof (rule Dynkin_systemI', simp_all cong del: indep_sets_cong, safe)\n        show \"indep_sets (G(j := {{}})) K\"\n          by (rule indep_sets_insert) auto\n      next\n        fix X assume X: \"X \\<in> events\" and G': \"indep_sets (G(j := {X})) K\"\n        show \"indep_sets (G(j := {space M - X})) K\"\n        proof (rule indep_sets_insert)\n          fix J A assume J: \"J \\<noteq> {}\" \"J \\<subseteq> K\" \"finite J\" \"j \\<notin> J\" and A: \"\\<forall>i\\<in>J. A i \\<in> G i\"\n          then have A_sets: \"\\<And>i. i\\<in>J \\<Longrightarrow> A i \\<in> events\"\n            using G by auto\n          have \"prob ((\\<Inter>j\\<in>J. A j) \\<inter> (space M - X)) =\n              prob ((\\<Inter>j\\<in>J. A j) - (\\<Inter>i\\<in>insert j J. (A(j := X)) i))\"\n            using A_sets sets.sets_into_space[of _ M] X \\<open>J \\<noteq> {}\\<close>\n            by (auto intro!: arg_cong[where f=prob] split: if_split_asm)\n          also have \"\\<dots> = prob (\\<Inter>j\\<in>J. A j) - prob (\\<Inter>i\\<in>insert j J. (A(j := X)) i)\"\n            using J \\<open>J \\<noteq> {}\\<close> \\<open>j \\<notin> J\\<close> A_sets X sets.sets_into_space\n            by (auto intro!: finite_measure_Diff sets.finite_INT split: if_split_asm)\n          finally have \"prob ((\\<Inter>j\\<in>J. A j) \\<inter> (space M - X)) =\n              prob (\\<Inter>j\\<in>J. A j) - prob (\\<Inter>i\\<in>insert j J. (A(j := X)) i)\" .\n          moreover {\n            have \"prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))\"\n              using J A \\<open>finite J\\<close> by (intro indep_setsD[OF G(1)]) auto\n            then have \"prob (\\<Inter>j\\<in>J. A j) = prob (space M) * (\\<Prod>i\\<in>J. prob (A i))\"\n              using prob_space by simp }\n          moreover {\n            have \"prob (\\<Inter>i\\<in>insert j J. (A(j := X)) i) = (\\<Prod>i\\<in>insert j J. prob ((A(j := X)) i))\"\n              using J A \\<open>j \\<in> K\\<close> by (intro indep_setsD[OF G']) auto\n            then have \"prob (\\<Inter>i\\<in>insert j J. (A(j := X)) i) = prob X * (\\<Prod>i\\<in>J. prob (A i))\"\n              using \\<open>finite J\\<close> \\<open>j \\<notin> J\\<close> by (auto intro!: prod.cong) }\n          ultimately have \"prob ((\\<Inter>j\\<in>J. A j) \\<inter> (space M - X)) = (prob (space M) - prob X) * (\\<Prod>i\\<in>J. prob (A i))\"\n            by (simp add: field_simps)\n          also have \"\\<dots> = prob (space M - X) * (\\<Prod>i\\<in>J. prob (A i))\"\n            using X A by (simp add: finite_measure_compl)\n          finally show \"prob ((\\<Inter>j\\<in>J. A j) \\<inter> (space M - X)) = prob (space M - X) * (\\<Prod>i\\<in>J. prob (A i))\" .\n        qed (insert X, auto)\n      next\n        fix F :: \"nat \\<Rightarrow> 'a set\" assume disj: \"disjoint_family F\" and \"range F \\<subseteq> ?D\"\n        then have F: \"\\<And>i. F i \\<in> events\" \"\\<And>i. indep_sets (G(j:={F i})) K\" by auto\n        show \"indep_sets (G(j := {\\<Union>k. F k})) K\"\n        proof (rule indep_sets_insert)\n          fix J A assume J: \"j \\<notin> J\" \"J \\<noteq> {}\" \"J \\<subseteq> K\" \"finite J\" and A: \"\\<forall>i\\<in>J. A i \\<in> G i\"\n          then have A_sets: \"\\<And>i. i\\<in>J \\<Longrightarrow> A i \\<in> events\"\n            using G by auto\n          have \"prob ((\\<Inter>j\\<in>J. A j) \\<inter> (\\<Union>k. F k)) = prob (\\<Union>k. (\\<Inter>i\\<in>insert j J. (A(j := F k)) i))\"\n            using \\<open>J \\<noteq> {}\\<close> \\<open>j \\<notin> J\\<close> \\<open>j \\<in> K\\<close> by (auto intro!: arg_cong[where f=prob] split: if_split_asm)\n          moreover have \"(\\<lambda>k. prob (\\<Inter>i\\<in>insert j J. (A(j := F k)) i)) sums prob (\\<Union>k. (\\<Inter>i\\<in>insert j J. (A(j := F k)) i))\"\n          proof (rule finite_measure_UNION)\n            show \"disjoint_family (\\<lambda>k. \\<Inter>i\\<in>insert j J. (A(j := F k)) i)\"\n              using disj by (rule disjoint_family_on_bisimulation) auto\n            show \"range (\\<lambda>k. \\<Inter>i\\<in>insert j J. (A(j := F k)) i) \\<subseteq> events\"\n              using A_sets F \\<open>finite J\\<close> \\<open>J \\<noteq> {}\\<close> \\<open>j \\<notin> J\\<close> by (auto intro!: sets.Int)\n          qed\n          moreover { fix k\n            from J A \\<open>j \\<in> K\\<close> have \"prob (\\<Inter>i\\<in>insert j J. (A(j := F k)) i) = prob (F k) * (\\<Prod>i\\<in>J. prob (A i))\"\n              by (subst indep_setsD[OF F(2)]) (auto intro!: prod.cong split: if_split_asm)\n            also have \"\\<dots> = prob (F k) * prob (\\<Inter>i\\<in>J. A i)\"\n              using J A \\<open>j \\<in> K\\<close> by (subst indep_setsD[OF G(1)]) auto\n            finally have \"prob (\\<Inter>i\\<in>insert j J. (A(j := F k)) i) = prob (F k) * prob (\\<Inter>i\\<in>J. A i)\" . }\n          ultimately have \"(\\<lambda>k. prob (F k) * prob (\\<Inter>i\\<in>J. A i)) sums (prob ((\\<Inter>j\\<in>J. A j) \\<inter> (\\<Union>k. F k)))\"\n            by simp\n          moreover\n          have \"(\\<lambda>k. prob (F k) * prob (\\<Inter>i\\<in>J. A i)) sums (prob (\\<Union>k. F k) * prob (\\<Inter>i\\<in>J. A i))\"\n            using disj F(1) by (intro finite_measure_UNION sums_mult2) auto\n          then have \"(\\<lambda>k. prob (F k) * prob (\\<Inter>i\\<in>J. A i)) sums (prob (\\<Union>k. F k) * (\\<Prod>i\\<in>J. prob (A i)))\"\n            using J A \\<open>j \\<in> K\\<close> by (subst indep_setsD[OF G(1), symmetric]) auto\n          ultimately\n          show \"prob ((\\<Inter>j\\<in>J. A j) \\<inter> (\\<Union>k. F k)) = prob (\\<Union>k. F k) * (\\<Prod>j\\<in>J. prob (A j))\"\n            by (auto dest!: sums_unique)\n        qed (insert F, auto)\n      qed (insert sets.sets_into_space, auto)\n      then have mono: \"Dynkin (space M) (G j) \\<subseteq> {E \\<in> events. indep_sets (G(j := {E})) K}\"\n      proof (rule Dynkin_system.Dynkin_subset, safe)\n        fix X assume \"X \\<in> G j\"\n        then show \"X \\<in> events\" using G \\<open>j \\<in> K\\<close> by auto\n        from \\<open>indep_sets G K\\<close>\n        show \"indep_sets (G(j := {X})) K\"\n          by (rule indep_sets_mono_sets) (insert \\<open>X \\<in> G j\\<close>, auto)\n      qed\n      have \"indep_sets (G(j:=?D)) K\"\n      proof (rule indep_setsI)\n        fix i assume \"i \\<in> K\" then show \"(G(j := ?D)) i \\<subseteq> events\"\n          using G(2) by auto\n      next\n        fix A J assume J: \"J\\<noteq>{}\" \"J \\<subseteq> K\" \"finite J\" and A: \"\\<forall>i\\<in>J. A i \\<in> (G(j := ?D)) i\"\n        show \"prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))\"\n        proof cases\n          assume \"j \\<in> J\"\n          with A have indep: \"indep_sets (G(j := {A j})) K\" by auto\n          from J A show ?thesis\n            by (intro indep_setsD[OF indep]) auto\n        next\n          assume \"j \\<notin> J\"\n          with J A have \"\\<forall>i\\<in>J. A i \\<in> G i\" by (auto split: if_split_asm)\n          with J show ?thesis\n            by (intro indep_setsD[OF G(1)]) auto\n        qed\n      qed\n      then have \"indep_sets (G(j := Dynkin (space M) (G j))) K\"\n        by (rule indep_sets_mono_sets) (insert mono, auto)\n      then show ?case\n        by (rule indep_sets_mono_sets) (insert \\<open>j \\<in> K\\<close> \\<open>j \\<notin> J\\<close>, auto simp: G_def)\n    qed (insert \\<open>indep_sets F K\\<close>, simp) }\n  from this[OF \\<open>indep_sets F J\\<close> \\<open>finite J\\<close> subset_refl]\n  show \"indep_sets ?F J\"\n    by (rule indep_sets_mono_sets) auto\nqed\n\nlemma (in prob_space) indep_sets_sigma:\n  assumes indep: \"indep_sets F I\"\n  assumes stable: \"\\<And>i. i \\<in> I \\<Longrightarrow> Int_stable (F i)\"\n  shows \"indep_sets (\\<lambda>i. sigma_sets (space M) (F i)) I\"\nproof -\n  from indep_sets_Dynkin[OF indep]\n  show ?thesis\n  proof (rule indep_sets_mono_sets, subst sigma_eq_Dynkin, simp_all add: stable)\n    fix i assume \"i \\<in> I\"\n    with indep have \"F i \\<subseteq> events\" by (auto simp: indep_sets_def)\n    with sets.sets_into_space show \"F i \\<subseteq> Pow (space M)\" by auto\n  qed\nqed\n\nlemma (in prob_space) indep_sets_sigma_sets_iff:\n  assumes \"\\<And>i. i \\<in> I \\<Longrightarrow> Int_stable (F i)\"\n  shows \"indep_sets (\\<lambda>i. sigma_sets (space M) (F i)) I \\<longleftrightarrow> indep_sets F I\"\nproof\n  assume \"indep_sets F I\" then show \"indep_sets (\\<lambda>i. sigma_sets (space M) (F i)) I\"\n    by (rule indep_sets_sigma) fact\nnext\n  assume \"indep_sets (\\<lambda>i. sigma_sets (space M) (F i)) I\" then show \"indep_sets F I\"\n    by (rule indep_sets_mono_sets) (intro subsetI sigma_sets.Basic)\nqed\n\ndefinition (in prob_space)\n  indep_vars_def2: \"indep_vars M' X I \\<longleftrightarrow>\n    (\\<forall>i\\<in>I. random_variable (M' i) (X i)) \\<and>\n    indep_sets (\\<lambda>i. { X i -` A \\<inter> space M | A. A \\<in> sets (M' i)}) I\"\n\ndefinition (in prob_space)\n  \"indep_var Ma A Mb B \\<longleftrightarrow> indep_vars (case_bool Ma Mb) (case_bool A B) UNIV\"\n\nlemma (in prob_space) indep_vars_def:\n  \"indep_vars M' X I \\<longleftrightarrow>\n    (\\<forall>i\\<in>I. random_variable (M' i) (X i)) \\<and>\n    indep_sets (\\<lambda>i. sigma_sets (space M) { X i -` A \\<inter> space M | A. A \\<in> sets (M' i)}) I\"\n  unfolding indep_vars_def2\n  apply (rule conj_cong[OF refl])\n  apply (rule indep_sets_sigma_sets_iff[symmetric])\n  apply (auto simp: Int_stable_def)\n  apply (rule_tac x=\"A \\<inter> Aa\" in exI)\n  apply auto\n  done\n\nlemma (in prob_space) indep_var_eq:\n  \"indep_var S X T Y \\<longleftrightarrow>\n    (random_variable S X \\<and> random_variable T Y) \\<and>\n    indep_set\n      (sigma_sets (space M) { X -` A \\<inter> space M | A. A \\<in> sets S})\n      (sigma_sets (space M) { Y -` A \\<inter> space M | A. A \\<in> sets T})\"\n  unfolding indep_var_def indep_vars_def indep_set_def UNIV_bool\n  by (intro arg_cong2[where f=\"(\\<and>)\"] arg_cong2[where f=indep_sets] ext)\n     (auto split: bool.split)\n\nlemma (in prob_space) indep_sets2_eq:\n  \"indep_set A B \\<longleftrightarrow> A \\<subseteq> events \\<and> B \\<subseteq> events \\<and> (\\<forall>a\\<in>A. \\<forall>b\\<in>B. prob (a \\<inter> b) = prob a * prob b)\"\n  unfolding indep_set_def\nproof (intro iffI ballI conjI)\n  assume indep: \"indep_sets (case_bool A B) UNIV\"\n  { fix a b assume \"a \\<in> A\" \"b \\<in> B\"\n    with indep_setsD[OF indep, of UNIV \"case_bool a b\"]\n    show \"prob (a \\<inter> b) = prob a * prob b\"\n      unfolding UNIV_bool by (simp add: ac_simps) }\n  from indep show \"A \\<subseteq> events\" \"B \\<subseteq> events\"\n    unfolding indep_sets_def UNIV_bool by auto\nnext\n  assume *: \"A \\<subseteq> events \\<and> B \\<subseteq> events \\<and> (\\<forall>a\\<in>A. \\<forall>b\\<in>B. prob (a \\<inter> b) = prob a * prob b)\"\n  show \"indep_sets (case_bool A B) UNIV\"\n  proof (rule indep_setsI)\n    fix i show \"(case i of True \\<Rightarrow> A | False \\<Rightarrow> B) \\<subseteq> events\"\n      using * by (auto split: bool.split)\n  next\n    fix J X assume \"J \\<noteq> {}\" \"J \\<subseteq> UNIV\" and X: \"\\<forall>j\\<in>J. X j \\<in> (case j of True \\<Rightarrow> A | False \\<Rightarrow> B)\"\n    then have \"J = {True} \\<or> J = {False} \\<or> J = {True,False}\"\n      by (auto simp: UNIV_bool)\n    then show \"prob (\\<Inter>j\\<in>J. X j) = (\\<Prod>j\\<in>J. prob (X j))\"\n      using X * by auto\n  qed\nqed\n\nlemma (in prob_space) indep_set_sigma_sets:\n  assumes \"indep_set A B\"\n  assumes A: \"Int_stable A\" and B: \"Int_stable B\"\n  shows \"indep_set (sigma_sets (space M) A) (sigma_sets (space M) B)\"\nproof -\n  have \"indep_sets (\\<lambda>i. sigma_sets (space M) (case i of True \\<Rightarrow> A | False \\<Rightarrow> B)) UNIV\"\n  proof (rule indep_sets_sigma)\n    show \"indep_sets (case_bool A B) UNIV\"\n      by (rule \\<open>indep_set A B\\<close>[unfolded indep_set_def])\n    fix i show \"Int_stable (case i of True \\<Rightarrow> A | False \\<Rightarrow> B)\"\n      using A B by (cases i) auto\n  qed\n  then show ?thesis\n    unfolding indep_set_def\n    by (rule indep_sets_mono_sets) (auto split: bool.split)\nqed\n\nlemma (in prob_space) indep_eventsI_indep_vars:\n  assumes indep: \"indep_vars N X I\"\n  assumes P: \"\\<And>i. i \\<in> I \\<Longrightarrow> {x\\<in>space (N i). P i x} \\<in> sets (N i)\"\n  shows \"indep_events (\\<lambda>i. {x\\<in>space M. P i (X i x)}) I\"\nproof -\n  have \"indep_sets (\\<lambda>i. {X i -` A \\<inter> space M |A. A \\<in> sets (N i)}) I\"\n    using indep unfolding indep_vars_def2 by auto\n  then show ?thesis\n    unfolding indep_events_def_alt\n  proof (rule indep_sets_mono_sets)\n    fix i assume \"i \\<in> I\"\n    then have \"{{x \\<in> space M. P i (X i x)}} = {X i -` {x\\<in>space (N i). P i x} \\<inter> space M}\"\n      using indep by (auto simp: indep_vars_def dest: measurable_space)\n    also have \"\\<dots> \\<subseteq> {X i -` A \\<inter> space M |A. A \\<in> sets (N i)}\"\n      using P[OF \\<open>i \\<in> I\\<close>] by blast\n    finally show \"{{x \\<in> space M. P i (X i x)}} \\<subseteq> {X i -` A \\<inter> space M |A. A \\<in> sets (N i)}\" .\n  qed\nqed\n\nlemma (in prob_space) indep_sets_collect_sigma:\n  fixes I :: \"'j \\<Rightarrow> 'i set\" and J :: \"'j set\" and E :: \"'i \\<Rightarrow> 'a set set\"\n  assumes indep: \"indep_sets E (\\<Union>j\\<in>J. I j)\"\n  assumes Int_stable: \"\\<And>i j. j \\<in> J \\<Longrightarrow> i \\<in> I j \\<Longrightarrow> Int_stable (E i)\"\n  assumes disjoint: \"disjoint_family_on I J\"\n  shows \"indep_sets (\\<lambda>j. sigma_sets (space M) (\\<Union>i\\<in>I j. E i)) J\"\nproof -\n  let ?E = \"\\<lambda>j. {\\<Inter>k\\<in>K. E' k| E' K. finite K \\<and> K \\<noteq> {} \\<and> K \\<subseteq> I j \\<and> (\\<forall>k\\<in>K. E' k \\<in> E k) }\"\n\n  from indep have E: \"\\<And>j i. j \\<in> J \\<Longrightarrow> i \\<in> I j \\<Longrightarrow> E i \\<subseteq> events\"\n    unfolding indep_sets_def by auto\n  { fix j\n    let ?S = \"sigma_sets (space M) (\\<Union>i\\<in>I j. E i)\"\n    assume \"j \\<in> J\"\n    from E[OF this] interpret S: sigma_algebra \"space M\" ?S\n      using sets.sets_into_space[of _ M] by (intro sigma_algebra_sigma_sets) auto\n\n    have \"sigma_sets (space M) (\\<Union>i\\<in>I j. E i) = sigma_sets (space M) (?E j)\"\n    proof (rule sigma_sets_eqI)\n      fix A assume \"A \\<in> (\\<Union>i\\<in>I j. E i)\"\n      then obtain i where \"i \\<in> I j\" \"A \\<in> E i\" ..\n      then show \"A \\<in> sigma_sets (space M) (?E j)\"\n        by (auto intro!: sigma_sets.intros(2-) exI[of _ \"{i}\"] exI[of _ \"\\<lambda>i. A\"])\n    next\n      fix A assume \"A \\<in> ?E j\"\n      then obtain E' K where \"finite K\" \"K \\<noteq> {}\" \"K \\<subseteq> I j\" \"\\<And>k. k \\<in> K \\<Longrightarrow> E' k \\<in> E k\"\n        and A: \"A = (\\<Inter>k\\<in>K. E' k)\"\n        by auto\n      then have \"A \\<in> ?S\" unfolding A\n        by (safe intro!: S.finite_INT) auto\n      then show \"A \\<in> sigma_sets (space M) (\\<Union>i\\<in>I j. E i)\"\n        by simp\n    qed }\n  moreover have \"indep_sets (\\<lambda>j. sigma_sets (space M) (?E j)) J\"\n  proof (rule indep_sets_sigma)\n    show \"indep_sets ?E J\"\n    proof (intro indep_setsI)\n      fix j assume \"j \\<in> J\" with E show \"?E j \\<subseteq> events\" by (force  intro!: sets.finite_INT)\n    next\n      fix K A assume K: \"K \\<noteq> {}\" \"K \\<subseteq> J\" \"finite K\"\n        and \"\\<forall>j\\<in>K. A j \\<in> ?E j\"\n      then have \"\\<forall>j\\<in>K. \\<exists>E' L. A j = (\\<Inter>l\\<in>L. E' l) \\<and> finite L \\<and> L \\<noteq> {} \\<and> L \\<subseteq> I j \\<and> (\\<forall>l\\<in>L. E' l \\<in> E l)\"\n        by simp\n      from bchoice[OF this] obtain E'\n        where \"\\<forall>x\\<in>K. \\<exists>L. A x = \\<Inter> (E' x ` L) \\<and> finite L \\<and> L \\<noteq> {} \\<and> L \\<subseteq> I x \\<and> (\\<forall>l\\<in>L. E' x l \\<in> E l)\"\n        ..\n      from bchoice[OF this] obtain L\n        where A: \"\\<And>j. j\\<in>K \\<Longrightarrow> A j = (\\<Inter>l\\<in>L j. E' j l)\"\n        and L: \"\\<And>j. j\\<in>K \\<Longrightarrow> finite (L j)\" \"\\<And>j. j\\<in>K \\<Longrightarrow> L j \\<noteq> {}\" \"\\<And>j. j\\<in>K \\<Longrightarrow> L j \\<subseteq> I j\"\n        and E': \"\\<And>j l. j\\<in>K \\<Longrightarrow> l \\<in> L j \\<Longrightarrow> E' j l \\<in> E l\"\n        by auto\n      { fix k l j assume \"k \\<in> K\" \"j \\<in> K\" \"l \\<in> L j\" \"l \\<in> L k\"\n        have \"k = j\"\n        proof (rule ccontr)\n          assume \"k \\<noteq> j\"\n          with disjoint \\<open>K \\<subseteq> J\\<close> \\<open>k \\<in> K\\<close> \\<open>j \\<in> K\\<close> have \"I k \\<inter> I j = {}\"\n            unfolding disjoint_family_on_def by auto\n          with L(2,3)[OF \\<open>j \\<in> K\\<close>] L(2,3)[OF \\<open>k \\<in> K\\<close>]\n          show False using \\<open>l \\<in> L k\\<close> \\<open>l \\<in> L j\\<close> by auto\n        qed }\n      note L_inj = this\n\n      define k where \"k l = (SOME k. k \\<in> K \\<and> l \\<in> L k)\" for l\n      { fix x j l assume *: \"j \\<in> K\" \"l \\<in> L j\"\n        have \"k l = j\" unfolding k_def\n        proof (rule some_equality)\n          fix k assume \"k \\<in> K \\<and> l \\<in> L k\"\n          with * L_inj show \"k = j\" by auto\n        qed (insert *, simp) }\n      note k_simp[simp] = this\n      let ?E' = \"\\<lambda>l. E' (k l) l\"\n      have \"prob (\\<Inter>j\\<in>K. A j) = prob (\\<Inter>l\\<in>(\\<Union>k\\<in>K. L k). ?E' l)\"\n        by (auto simp: A intro!: arg_cong[where f=prob])\n      also have \"\\<dots> = (\\<Prod>l\\<in>(\\<Union>k\\<in>K. L k). prob (?E' l))\"\n        using L K E' by (intro indep_setsD[OF indep]) (simp_all add: UN_mono)\n      also have \"\\<dots> = (\\<Prod>j\\<in>K. \\<Prod>l\\<in>L j. prob (E' j l))\"\n        using K L L_inj by (subst prod.UNION_disjoint) auto\n      also have \"\\<dots> = (\\<Prod>j\\<in>K. prob (A j))\"\n        using K L E' by (auto simp add: A intro!: prod.cong indep_setsD[OF indep, symmetric]) blast\n      finally show \"prob (\\<Inter>j\\<in>K. A j) = (\\<Prod>j\\<in>K. prob (A j))\" .\n    qed\n  next\n    fix j assume \"j \\<in> J\"\n    show \"Int_stable (?E j)\"\n    proof (rule Int_stableI)\n      fix a assume \"a \\<in> ?E j\" then obtain Ka Ea\n        where a: \"a = (\\<Inter>k\\<in>Ka. Ea k)\" \"finite Ka\" \"Ka \\<noteq> {}\" \"Ka \\<subseteq> I j\" \"\\<And>k. k\\<in>Ka \\<Longrightarrow> Ea k \\<in> E k\" by auto\n      fix b assume \"b \\<in> ?E j\" then obtain Kb Eb\n        where b: \"b = (\\<Inter>k\\<in>Kb. Eb k)\" \"finite Kb\" \"Kb \\<noteq> {}\" \"Kb \\<subseteq> I j\" \"\\<And>k. k\\<in>Kb \\<Longrightarrow> Eb k \\<in> E k\" by auto\n      let ?f = \"\\<lambda>k. (if k \\<in> Ka \\<inter> Kb then Ea k \\<inter> Eb k else if k \\<in> Kb then Eb k else if k \\<in> Ka then Ea k else {})\"\n      have \"Ka \\<union> Kb = (Ka \\<inter> Kb) \\<union> (Kb - Ka) \\<union> (Ka - Kb)\"\n        by blast\n      moreover have \"(\\<Inter>x\\<in>Ka \\<inter> Kb. Ea x \\<inter> Eb x) \\<inter>\n        (\\<Inter>x\\<in>Kb - Ka. Eb x) \\<inter> (\\<Inter>x\\<in>Ka - Kb. Ea x) = (\\<Inter>k\\<in>Ka. Ea k) \\<inter> (\\<Inter>k\\<in>Kb. Eb k)\"\n        by auto\n      ultimately have \"(\\<Inter>k\\<in>Ka \\<union> Kb. ?f k) = (\\<Inter>k\\<in>Ka. Ea k) \\<inter> (\\<Inter>k\\<in>Kb. Eb k)\" (is \"?lhs = ?rhs\")\n        by (simp only: image_Un Inter_Un_distrib) simp\n      then have \"a \\<inter> b = (\\<Inter>k\\<in>Ka \\<union> Kb. ?f k)\"\n        by (simp only: a(1) b(1))\n      with a b \\<open>j \\<in> J\\<close> Int_stableD[OF Int_stable] show \"a \\<inter> b \\<in> ?E j\"\n        by (intro CollectI exI[of _ \"Ka \\<union> Kb\"] exI[of _ ?f]) auto\n    qed\n  qed\n  ultimately show ?thesis\n    by (simp cong: indep_sets_cong)\nqed\n\nlemma (in prob_space) indep_vars_restrict:\n  assumes ind: \"indep_vars M' X I\" and K: \"\\<And>j. j \\<in> L \\<Longrightarrow> K j \\<subseteq> I\" and J: \"disjoint_family_on K L\"\n  shows \"indep_vars (\\<lambda>j. PiM (K j) M') (\\<lambda>j \\<omega>. restrict (\\<lambda>i. X i \\<omega>) (K j)) L\"\n  unfolding indep_vars_def\nproof safe\n  fix j assume \"j \\<in> L\" then show \"random_variable (Pi\\<^sub>M (K j) M') (\\<lambda>\\<omega>. \\<lambda>i\\<in>K j. X i \\<omega>)\"\n    using K ind by (auto simp: indep_vars_def intro!: measurable_restrict)\nnext\n  have X: \"\\<And>i. i \\<in> I \\<Longrightarrow> X i \\<in> measurable M (M' i)\"\n    using ind by (auto simp: indep_vars_def)\n  let ?proj = \"\\<lambda>j S. {(\\<lambda>\\<omega>. \\<lambda>i\\<in>K j. X i \\<omega>) -` A \\<inter> space M |A. A \\<in> S}\"\n  let ?UN = \"\\<lambda>j. sigma_sets (space M) (\\<Union>i\\<in>K j. { X i -` A \\<inter> space M| A. A \\<in> sets (M' i) })\"\n  show \"indep_sets (\\<lambda>i. sigma_sets (space M) (?proj i (sets (Pi\\<^sub>M (K i) M')))) L\"\n  proof (rule indep_sets_mono_sets)\n    fix j assume j: \"j \\<in> L\"\n    have \"sigma_sets (space M) (?proj j (sets (Pi\\<^sub>M (K j) M'))) =\n      sigma_sets (space M) (sigma_sets (space M) (?proj j (prod_algebra (K j) M')))\"\n      using j K X[THEN measurable_space] unfolding sets_PiM\n      by (subst sigma_sets_vimage_commute) (auto simp add: Pi_iff)\n    also have \"\\<dots> = sigma_sets (space M) (?proj j (prod_algebra (K j) M'))\"\n      by (rule sigma_sets_sigma_sets_eq) auto\n    also have \"\\<dots> \\<subseteq> ?UN j\"\n    proof (rule sigma_sets_mono, safe del: disjE elim!: prod_algebraE)\n      fix J E assume J: \"finite J\" \"J \\<noteq> {} \\<or> K j = {}\"  \"J \\<subseteq> K j\" and E: \"\\<forall>i. i \\<in> J \\<longrightarrow> E i \\<in> sets (M' i)\"\n      show \"(\\<lambda>\\<omega>. \\<lambda>i\\<in>K j. X i \\<omega>) -` prod_emb (K j) M' J (Pi\\<^sub>E J E) \\<inter> space M \\<in> ?UN j\"\n      proof cases\n        assume \"K j = {}\" with J show ?thesis\n          by (auto simp add: sigma_sets_empty_eq prod_emb_def)\n      next\n        assume \"K j \\<noteq> {}\" with J have \"J \\<noteq> {}\"\n          by auto\n        { interpret sigma_algebra \"space M\" \"?UN j\"\n            by (rule sigma_algebra_sigma_sets) auto\n          have \"\\<And>A. (\\<And>i. i \\<in> J \\<Longrightarrow> A i \\<in> ?UN j) \\<Longrightarrow> \\<Inter>(A ` J) \\<in> ?UN j\"\n            using \\<open>finite J\\<close> \\<open>J \\<noteq> {}\\<close> by (rule finite_INT) blast }\n        note INT = this\n\n        from \\<open>J \\<noteq> {}\\<close> J K E[rule_format, THEN sets.sets_into_space] j\n        have \"(\\<lambda>\\<omega>. \\<lambda>i\\<in>K j. X i \\<omega>) -` prod_emb (K j) M' J (Pi\\<^sub>E J E) \\<inter> space M\n          = (\\<Inter>i\\<in>J. X i -` E i \\<inter> space M)\"\n          apply (subst prod_emb_PiE[OF _ ])\n          apply auto []\n          apply auto []\n          apply (auto simp add: Pi_iff intro!: X[THEN measurable_space])\n          apply (erule_tac x=i in ballE)\n          apply auto\n          done\n        also have \"\\<dots> \\<in> ?UN j\"\n          apply (rule INT)\n          apply (rule sigma_sets.Basic)\n          using \\<open>J \\<subseteq> K j\\<close> E\n          apply auto\n          done\n        finally show ?thesis .\n      qed\n    qed\n    finally show \"sigma_sets (space M) (?proj j (sets (Pi\\<^sub>M (K j) M'))) \\<subseteq> ?UN j\" .\n  next\n    show \"indep_sets ?UN L\"\n    proof (rule indep_sets_collect_sigma)\n      show \"indep_sets (\\<lambda>i. {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}) (\\<Union>j\\<in>L. K j)\"\n      proof (rule indep_sets_mono_index)\n        show \"indep_sets (\\<lambda>i. {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}) I\"\n          using ind unfolding indep_vars_def2 by auto\n        show \"(\\<Union>l\\<in>L. K l) \\<subseteq> I\"\n          using K by auto\n      qed\n    next\n      fix l i assume \"l \\<in> L\" \"i \\<in> K l\"\n      show \"Int_stable {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}\"\n        apply (auto simp: Int_stable_def)\n        apply (rule_tac x=\"A \\<inter> Aa\" in exI)\n        apply auto\n        done\n    qed fact\n  qed\nqed\n\nlemma (in prob_space) indep_var_restrict:\n  assumes ind: \"indep_vars M' X I\" and AB: \"A \\<inter> B = {}\" \"A \\<subseteq> I\" \"B \\<subseteq> I\"\n  shows \"indep_var (PiM A M') (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) A) (PiM B M') (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) B)\"\nproof -\n  have *:\n    \"case_bool (Pi\\<^sub>M A M') (Pi\\<^sub>M B M') = (\\<lambda>b. PiM (case_bool A B b) M')\"\n    \"case_bool (\\<lambda>\\<omega>. \\<lambda>i\\<in>A. X i \\<omega>) (\\<lambda>\\<omega>. \\<lambda>i\\<in>B. X i \\<omega>) = (\\<lambda>b \\<omega>. \\<lambda>i\\<in>case_bool A B b. X i \\<omega>)\"\n    by (simp_all add: fun_eq_iff split: bool.split)\n  show ?thesis\n    unfolding indep_var_def * using AB\n    by (intro indep_vars_restrict[OF ind]) (auto simp: disjoint_family_on_def split: bool.split)\nqed\n\nlemma (in prob_space) indep_vars_subset:\n  assumes \"indep_vars M' X I\" \"J \\<subseteq> I\"\n  shows \"indep_vars M' X J\"\n  using assms unfolding indep_vars_def indep_sets_def\n  by auto\n\nlemma (in prob_space) indep_vars_cong:\n  \"I = J \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> X i = Y i) \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> M' i = N' i) \\<Longrightarrow> indep_vars M' X I \\<longleftrightarrow> indep_vars N' Y J\"\n  unfolding indep_vars_def2 by (intro conj_cong indep_sets_cong) auto\n\ndefinition (in prob_space) tail_events where\n  \"tail_events A = (\\<Inter>n. sigma_sets (space M) (\\<Union> (A ` {n..})))\"\n\nlemma (in prob_space) tail_events_sets:\n  assumes A: \"\\<And>i::nat. A i \\<subseteq> events\"\n  shows \"tail_events A \\<subseteq> events\"\nproof\n  fix X assume X: \"X \\<in> tail_events A\"\n  let ?A = \"(\\<Inter>n. sigma_sets (space M) (\\<Union> (A ` {n..})))\"\n  from X have \"\\<And>n::nat. X \\<in> sigma_sets (space M) (\\<Union> (A ` {n..}))\" by (auto simp: tail_events_def)\n  from this[of 0] have \"X \\<in> sigma_sets (space M) (\\<Union>(A ` UNIV))\" by simp\n  then show \"X \\<in> events\"\n    by induct (insert A, auto)\nqed\n\nlemma (in prob_space) sigma_algebra_tail_events:\n  assumes \"\\<And>i::nat. sigma_algebra (space M) (A i)\"\n  shows \"sigma_algebra (space M) (tail_events A)\"\n  unfolding tail_events_def\nproof (simp add: sigma_algebra_iff2, safe)\n  let ?A = \"(\\<Inter>n. sigma_sets (space M) (\\<Union> (A ` {n..})))\"\n  interpret A: sigma_algebra \"space M\" \"A i\" for i by fact\n  { fix X x assume \"X \\<in> ?A\" \"x \\<in> X\"\n    then have \"\\<And>n. X \\<in> sigma_sets (space M) (\\<Union> (A ` {n..}))\" by auto\n    from this[of 0] have \"X \\<in> sigma_sets (space M) (\\<Union>(A ` UNIV))\" by simp\n    then have \"X \\<subseteq> space M\"\n      by induct (insert A.sets_into_space, auto)\n    with \\<open>x \\<in> X\\<close> show \"x \\<in> space M\" by auto }\n  { fix F :: \"nat \\<Rightarrow> 'a set\" and n assume \"range F \\<subseteq> ?A\"\n    then show \"(\\<Union>(F ` UNIV)) \\<in> sigma_sets (space M) (\\<Union> (A ` {n..}))\"\n      by (intro sigma_sets.Union) auto }\nqed (auto intro!: sigma_sets.Compl sigma_sets.Empty)\n\nlemma (in prob_space) kolmogorov_0_1_law:\n  fixes A :: \"nat \\<Rightarrow> 'a set set\"\n  assumes \"\\<And>i::nat. sigma_algebra (space M) (A i)\"\n  assumes indep: \"indep_sets A UNIV\"\n  and X: \"X \\<in> tail_events A\"\n  shows \"prob X = 0 \\<or> prob X = 1\"\nproof -\n  have A: \"\\<And>i. A i \\<subseteq> events\"\n    using indep unfolding indep_sets_def by simp\n\n  let ?D = \"{D \\<in> events. prob (X \\<inter> D) = prob X * prob D}\"\n  interpret A: sigma_algebra \"space M\" \"A i\" for i by fact\n  interpret T: sigma_algebra \"space M\" \"tail_events A\"\n    by (rule sigma_algebra_tail_events) fact\n  have \"X \\<subseteq> space M\" using T.space_closed X by auto\n\n  have X_in: \"X \\<in> events\"\n    using tail_events_sets A X by auto\n\n  interpret D: Dynkin_system \"space M\" ?D\n  proof (rule Dynkin_systemI)\n    fix D assume \"D \\<in> ?D\" then show \"D \\<subseteq> space M\"\n      using sets.sets_into_space by auto\n  next\n    show \"space M \\<in> ?D\"\n      using prob_space \\<open>X \\<subseteq> space M\\<close> by (simp add: Int_absorb2)\n  next\n    fix A assume A: \"A \\<in> ?D\"\n    have \"prob (X \\<inter> (space M - A)) = prob (X - (X \\<inter> A))\"\n      using \\<open>X \\<subseteq> space M\\<close> by (auto intro!: arg_cong[where f=prob])\n    also have \"\\<dots> = prob X - prob (X \\<inter> A)\"\n      using X_in A by (intro finite_measure_Diff) auto\n    also have \"\\<dots> = prob X * prob (space M) - prob X * prob A\"\n      using A prob_space by auto\n    also have \"\\<dots> = prob X * prob (space M - A)\"\n      using X_in A sets.sets_into_space\n      by (subst finite_measure_Diff) (auto simp: field_simps)\n    finally show \"space M - A \\<in> ?D\"\n      using A \\<open>X \\<subseteq> space M\\<close> by auto\n  next\n    fix F :: \"nat \\<Rightarrow> 'a set\" assume dis: \"disjoint_family F\" and \"range F \\<subseteq> ?D\"\n    then have F: \"range F \\<subseteq> events\" \"\\<And>i. prob (X \\<inter> F i) = prob X * prob (F i)\"\n      by auto\n    have \"(\\<lambda>i. prob (X \\<inter> F i)) sums prob (\\<Union>i. X \\<inter> F i)\"\n    proof (rule finite_measure_UNION)\n      show \"range (\\<lambda>i. X \\<inter> F i) \\<subseteq> events\"\n        using F X_in by auto\n      show \"disjoint_family (\\<lambda>i. X \\<inter> F i)\"\n        using dis by (rule disjoint_family_on_bisimulation) auto\n    qed\n    with F have \"(\\<lambda>i. prob X * prob (F i)) sums prob (X \\<inter> (\\<Union>i. F i))\"\n      by simp\n    moreover have \"(\\<lambda>i. prob X * prob (F i)) sums (prob X * prob (\\<Union>i. F i))\"\n      by (intro sums_mult finite_measure_UNION F dis)\n    ultimately have \"prob (X \\<inter> (\\<Union>i. F i)) = prob X * prob (\\<Union>i. F i)\"\n      by (auto dest!: sums_unique)\n    with F show \"(\\<Union>i. F i) \\<in> ?D\"\n      by auto\n  qed\n\n  { fix n\n    have \"indep_sets (\\<lambda>b. sigma_sets (space M) (\\<Union>m\\<in>case_bool {..n} {Suc n..} b. A m)) UNIV\"\n    proof (rule indep_sets_collect_sigma)\n      have *: \"(\\<Union>b. case b of True \\<Rightarrow> {..n} | False \\<Rightarrow> {Suc n..}) = UNIV\" (is \"?U = _\")\n        by (simp split: bool.split add: set_eq_iff) (metis not_less_eq_eq)\n      with indep show \"indep_sets A ?U\" by simp\n      show \"disjoint_family (case_bool {..n} {Suc n..})\"\n        unfolding disjoint_family_on_def by (auto split: bool.split)\n      fix m\n      show \"Int_stable (A m)\"\n        unfolding Int_stable_def using A.Int by auto\n    qed\n    also have \"(\\<lambda>b. sigma_sets (space M) (\\<Union>m\\<in>case_bool {..n} {Suc n..} b. A m)) =\n      case_bool (sigma_sets (space M) (\\<Union>m\\<in>{..n}. A m)) (sigma_sets (space M) (\\<Union>m\\<in>{Suc n..}. A m))\"\n      by (auto intro!: ext split: bool.split)\n    finally have indep: \"indep_set (sigma_sets (space M) (\\<Union>m\\<in>{..n}. A m)) (sigma_sets (space M) (\\<Union>m\\<in>{Suc n..}. A m))\"\n      unfolding indep_set_def by simp\n\n    have \"sigma_sets (space M) (\\<Union>m\\<in>{..n}. A m) \\<subseteq> ?D\"\n    proof (simp add: subset_eq, rule)\n      fix D assume D: \"D \\<in> sigma_sets (space M) (\\<Union>m\\<in>{..n}. A m)\"\n      have \"X \\<in> sigma_sets (space M) (\\<Union>m\\<in>{Suc n..}. A m)\"\n        using X unfolding tail_events_def by simp\n      from indep_setD[OF indep D this] indep_setD_ev1[OF indep] D\n      show \"D \\<in> events \\<and> prob (X \\<inter> D) = prob X * prob D\"\n        by (auto simp add: ac_simps)\n    qed }\n  then have \"(\\<Union>n. sigma_sets (space M) (\\<Union>m\\<in>{..n}. A m)) \\<subseteq> ?D\" (is \"?A \\<subseteq> _\")\n    by auto\n\n  note \\<open>X \\<in> tail_events A\\<close>\n  also {\n    have \"\\<And>n. sigma_sets (space M) (\\<Union>i\\<in>{n..}. A i) \\<subseteq> sigma_sets (space M) ?A\"\n      by (intro sigma_sets_subseteq UN_mono) auto\n   then have \"tail_events A \\<subseteq> sigma_sets (space M) ?A\"\n      unfolding tail_events_def by auto }\n  also have \"sigma_sets (space M) ?A = Dynkin (space M) ?A\"\n  proof (rule sigma_eq_Dynkin)\n    { fix B n assume \"B \\<in> sigma_sets (space M) (\\<Union>m\\<in>{..n}. A m)\"\n      then have \"B \\<subseteq> space M\"\n        by induct (insert A sets.sets_into_space[of _ M], auto) }\n    then show \"?A \\<subseteq> Pow (space M)\" by auto\n    show \"Int_stable ?A\"\n    proof (rule Int_stableI)\n      fix a b assume \"a \\<in> ?A\" \"b \\<in> ?A\" then obtain n m\n        where a: \"n \\<in> UNIV\" \"a \\<in> sigma_sets (space M) (\\<Union> (A ` {..n}))\"\n          and b: \"m \\<in> UNIV\" \"b \\<in> sigma_sets (space M) (\\<Union> (A ` {..m}))\" by auto\n      interpret Amn: sigma_algebra \"space M\" \"sigma_sets (space M) (\\<Union>i\\<in>{..max m n}. A i)\"\n        using A sets.sets_into_space[of _ M] by (intro sigma_algebra_sigma_sets) auto\n      have \"sigma_sets (space M) (\\<Union>i\\<in>{..n}. A i) \\<subseteq> sigma_sets (space M) (\\<Union>i\\<in>{..max m n}. A i)\"\n        by (intro sigma_sets_subseteq UN_mono) auto\n      with a have \"a \\<in> sigma_sets (space M) (\\<Union>i\\<in>{..max m n}. A i)\" by auto\n      moreover\n      have \"sigma_sets (space M) (\\<Union>i\\<in>{..m}. A i) \\<subseteq> sigma_sets (space M) (\\<Union>i\\<in>{..max m n}. A i)\"\n        by (intro sigma_sets_subseteq UN_mono) auto\n      with b have \"b \\<in> sigma_sets (space M) (\\<Union>i\\<in>{..max m n}. A i)\" by auto\n      ultimately have \"a \\<inter> b \\<in> sigma_sets (space M) (\\<Union>i\\<in>{..max m n}. A i)\"\n        using Amn.Int[of a b] by simp\n      then show \"a \\<inter> b \\<in> (\\<Union>n. sigma_sets (space M) (\\<Union>i\\<in>{..n}. A i))\" by auto\n    qed\n  qed\n  also have \"Dynkin (space M) ?A \\<subseteq> ?D\"\n    using \\<open>?A \\<subseteq> ?D\\<close> by (auto intro!: D.Dynkin_subset)\n  finally show ?thesis by auto\nqed\n\nlemma (in prob_space) borel_0_1_law:\n  fixes F :: \"nat \\<Rightarrow> 'a set\"\n  assumes F2: \"indep_events F UNIV\"\n  shows \"prob (\\<Inter>n. \\<Union>m\\<in>{n..}. F m) = 0 \\<or> prob (\\<Inter>n. \\<Union>m\\<in>{n..}. F m) = 1\"\nproof (rule kolmogorov_0_1_law[of \"\\<lambda>i. sigma_sets (space M) { F i }\"])\n  have F1: \"range F \\<subseteq> events\"\n    using F2 by (simp add: indep_events_def subset_eq)\n  { fix i show \"sigma_algebra (space M) (sigma_sets (space M) {F i})\"\n      using sigma_algebra_sigma_sets[of \"{F i}\" \"space M\"] F1 sets.sets_into_space\n      by auto }\n  show \"indep_sets (\\<lambda>i. sigma_sets (space M) {F i}) UNIV\"\n  proof (rule indep_sets_sigma)\n    show \"indep_sets (\\<lambda>i. {F i}) UNIV\"\n      unfolding indep_events_def_alt[symmetric] by fact\n    fix i show \"Int_stable {F i}\"\n      unfolding Int_stable_def by simp\n  qed\n  let ?Q = \"\\<lambda>n. \\<Union>i\\<in>{n..}. F i\"\n  show \"(\\<Inter>n. \\<Union>m\\<in>{n..}. F m) \\<in> tail_events (\\<lambda>i. sigma_sets (space M) {F i})\"\n    unfolding tail_events_def\n  proof\n    fix j\n    interpret S: sigma_algebra \"space M\" \"sigma_sets (space M) (\\<Union>i\\<in>{j..}. sigma_sets (space M) {F i})\"\n      using order_trans[OF F1 sets.space_closed]\n      by (intro sigma_algebra_sigma_sets) (simp add: sigma_sets_singleton subset_eq)\n    have \"(\\<Inter>n. ?Q n) = (\\<Inter>n\\<in>{j..}. ?Q n)\"\n      by (intro decseq_SucI INT_decseq_offset UN_mono) auto\n    also have \"\\<dots> \\<in> sigma_sets (space M) (\\<Union>i\\<in>{j..}. sigma_sets (space M) {F i})\"\n      using order_trans[OF F1 sets.space_closed]\n      by (safe intro!: S.countable_INT S.countable_UN)\n         (auto simp: sigma_sets_singleton intro!: sigma_sets.Basic bexI)\n    finally show \"(\\<Inter>n. ?Q n) \\<in> sigma_sets (space M) (\\<Union>i\\<in>{j..}. sigma_sets (space M) {F i})\"\n      by simp\n  qed\nqed\n\nlemma (in prob_space) borel_0_1_law_AE:\n  fixes P :: \"nat \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes \"indep_events (\\<lambda>m. {x\\<in>space M. P m x}) UNIV\" (is \"indep_events ?P _\")\n  shows \"(AE x in M. infinite {m. P m x}) \\<or> (AE x in M. finite {m. P m x})\"\nproof -\n  have [measurable]: \"\\<And>m. {x\\<in>space M. P m x} \\<in> sets M\"\n    using assms by (auto simp: indep_events_def)\n  have *: \"(\\<Inter>n. \\<Union>m\\<in>{n..}. {x \\<in> space M. P m x}) \\<in> events\"\n    by simp\n  from assms have \"prob (\\<Inter>n. \\<Union>m\\<in>{n..}. ?P m) = 0 \\<or> prob (\\<Inter>n. \\<Union>m\\<in>{n..}. ?P m) = 1\"\n    by (rule borel_0_1_law)\n  also have \"prob (\\<Inter>n. \\<Union>m\\<in>{n..}. ?P m) = 1 \\<longleftrightarrow> (AE x in M. infinite {m. P m x})\"\n    using * by (simp add: prob_eq_1)\n      (simp add: Bex_def infinite_nat_iff_unbounded_le)\n  also have \"prob (\\<Inter>n. \\<Union>m\\<in>{n..}. ?P m) = 0 \\<longleftrightarrow> (AE x in M. finite {m. P m x})\"\n    using * by (simp add: prob_eq_0)\n      (auto simp add: Ball_def finite_nat_iff_bounded not_less [symmetric])\n  finally show ?thesis\n    by blast\nqed\n\nlemma (in prob_space) indep_sets_finite:\n  assumes I: \"I \\<noteq> {}\" \"finite I\"\n    and F: \"\\<And>i. i \\<in> I \\<Longrightarrow> F i \\<subseteq> events\" \"\\<And>i. i \\<in> I \\<Longrightarrow> space M \\<in> F i\"\n  shows \"indep_sets F I \\<longleftrightarrow> (\\<forall>A\\<in>Pi I F. prob (\\<Inter>j\\<in>I. A j) = (\\<Prod>j\\<in>I. prob (A j)))\"\nproof\n  assume *: \"indep_sets F I\"\n  from I show \"\\<forall>A\\<in>Pi I F. prob (\\<Inter>j\\<in>I. A j) = (\\<Prod>j\\<in>I. prob (A j))\"\n    by (intro indep_setsD[OF *] ballI) auto\nnext\n  assume indep: \"\\<forall>A\\<in>Pi I F. prob (\\<Inter>j\\<in>I. A j) = (\\<Prod>j\\<in>I. prob (A j))\"\n  show \"indep_sets F I\"\n  proof (rule indep_setsI[OF F(1)])\n    fix A J assume J: \"J \\<noteq> {}\" \"J \\<subseteq> I\" \"finite J\"\n    assume A: \"\\<forall>j\\<in>J. A j \\<in> F j\"\n    let ?A = \"\\<lambda>j. if j \\<in> J then A j else space M\"\n    have \"prob (\\<Inter>j\\<in>I. ?A j) = prob (\\<Inter>j\\<in>J. A j)\"\n      using subset_trans[OF F(1) sets.space_closed] J A\n      by (auto intro!: arg_cong[where f=prob] split: if_split_asm) blast\n    also\n    from A F have \"(\\<lambda>j. if j \\<in> J then A j else space M) \\<in> Pi I F\" (is \"?A \\<in> _\")\n      by (auto split: if_split_asm)\n    with indep have \"prob (\\<Inter>j\\<in>I. ?A j) = (\\<Prod>j\\<in>I. prob (?A j))\"\n      by auto\n    also have \"\\<dots> = (\\<Prod>j\\<in>J. prob (A j))\"\n      unfolding if_distrib prod.If_cases[OF \\<open>finite I\\<close>]\n      using prob_space \\<open>J \\<subseteq> I\\<close> by (simp add: Int_absorb1 prod.neutral_const)\n    finally show \"prob (\\<Inter>j\\<in>J. A j) = (\\<Prod>j\\<in>J. prob (A j))\" ..\n  qed\nqed\n\nlemma (in prob_space) indep_vars_finite:\n  fixes I :: \"'i set\"\n  assumes I: \"I \\<noteq> {}\" \"finite I\"\n    and M': \"\\<And>i. i \\<in> I \\<Longrightarrow> sets (M' i) = sigma_sets (space (M' i)) (E i)\"\n    and rv: \"\\<And>i. i \\<in> I \\<Longrightarrow> random_variable (M' i) (X i)\"\n    and Int_stable: \"\\<And>i. i \\<in> I \\<Longrightarrow> Int_stable (E i)\"\n    and space: \"\\<And>i. i \\<in> I \\<Longrightarrow> space (M' i) \\<in> E i\" and closed: \"\\<And>i. i \\<in> I \\<Longrightarrow> E i \\<subseteq> Pow (space (M' i))\"\n  shows \"indep_vars M' X I \\<longleftrightarrow>\n    (\\<forall>A\\<in>(\\<Pi> i\\<in>I. E i). prob (\\<Inter>j\\<in>I. X j -` A j \\<inter> space M) = (\\<Prod>j\\<in>I. prob (X j -` A j \\<inter> space M)))\"\nproof -\n  from rv have X: \"\\<And>i. i \\<in> I \\<Longrightarrow> X i \\<in> space M \\<rightarrow> space (M' i)\"\n    unfolding measurable_def by simp\n\n  { fix i assume \"i\\<in>I\"\n    from closed[OF \\<open>i \\<in> I\\<close>]\n    have \"sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}\n      = sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> E i}\"\n      unfolding sigma_sets_vimage_commute[OF X, OF \\<open>i \\<in> I\\<close>, symmetric] M'[OF \\<open>i \\<in> I\\<close>]\n      by (subst sigma_sets_sigma_sets_eq) auto }\n  note sigma_sets_X = this\n\n  { fix i assume \"i\\<in>I\"\n    have \"Int_stable {X i -` A \\<inter> space M |A. A \\<in> E i}\"\n    proof (rule Int_stableI)\n      fix a assume \"a \\<in> {X i -` A \\<inter> space M |A. A \\<in> E i}\"\n      then obtain A where \"a = X i -` A \\<inter> space M\" \"A \\<in> E i\" by auto\n      moreover\n      fix b assume \"b \\<in> {X i -` A \\<inter> space M |A. A \\<in> E i}\"\n      then obtain B where \"b = X i -` B \\<inter> space M\" \"B \\<in> E i\" by auto\n      moreover\n      have \"(X i -` A \\<inter> space M) \\<inter> (X i -` B \\<inter> space M) = X i -` (A \\<inter> B) \\<inter> space M\" by auto\n      moreover note Int_stable[OF \\<open>i \\<in> I\\<close>]\n      ultimately\n      show \"a \\<inter> b \\<in> {X i -` A \\<inter> space M |A. A \\<in> E i}\"\n        by (auto simp del: vimage_Int intro!: exI[of _ \"A \\<inter> B\"] dest: Int_stableD)\n    qed }\n  note indep_sets_X = indep_sets_sigma_sets_iff[OF this]\n\n  { fix i assume \"i \\<in> I\"\n    { fix A assume \"A \\<in> E i\"\n      with M'[OF \\<open>i \\<in> I\\<close>] have \"A \\<in> sets (M' i)\" by auto\n      moreover\n      from rv[OF \\<open>i\\<in>I\\<close>] have \"X i \\<in> measurable M (M' i)\" by auto\n      ultimately\n      have \"X i -` A \\<inter> space M \\<in> sets M\" by (auto intro: measurable_sets) }\n    with X[OF \\<open>i\\<in>I\\<close>] space[OF \\<open>i\\<in>I\\<close>]\n    have \"{X i -` A \\<inter> space M |A. A \\<in> E i} \\<subseteq> events\"\n      \"space M \\<in> {X i -` A \\<inter> space M |A. A \\<in> E i}\"\n      by (auto intro!: exI[of _ \"space (M' i)\"]) }\n  note indep_sets_finite_X = indep_sets_finite[OF I this]\n\n  have \"(\\<forall>A\\<in>\\<Pi> i\\<in>I. {X i -` A \\<inter> space M |A. A \\<in> E i}. prob (\\<Inter>(A ` I)) = (\\<Prod>j\\<in>I. prob (A j))) =\n    (\\<forall>A\\<in>\\<Pi> i\\<in>I. E i. prob ((\\<Inter>j\\<in>I. X j -` A j) \\<inter> space M) = (\\<Prod>x\\<in>I. prob (X x -` A x \\<inter> space M)))\"\n    (is \"?L = ?R\")\n  proof safe\n    fix A assume ?L and A: \"A \\<in> (\\<Pi> i\\<in>I. E i)\"\n    from \\<open>?L\\<close>[THEN bspec, of \"\\<lambda>i. X i -` A i \\<inter> space M\"] A \\<open>I \\<noteq> {}\\<close>\n    show \"prob ((\\<Inter>j\\<in>I. X j -` A j) \\<inter> space M) = (\\<Prod>x\\<in>I. prob (X x -` A x \\<inter> space M))\"\n      by (auto simp add: Pi_iff)\n  next\n    fix A assume ?R and A: \"A \\<in> (\\<Pi> i\\<in>I. {X i -` A \\<inter> space M |A. A \\<in> E i})\"\n    from A have \"\\<forall>i\\<in>I. \\<exists>B. A i = X i -` B \\<inter> space M \\<and> B \\<in> E i\" by auto\n    from bchoice[OF this] obtain B where B: \"\\<forall>i\\<in>I. A i = X i -` B i \\<inter> space M\"\n      \"B \\<in> (\\<Pi> i\\<in>I. E i)\" by auto\n    from \\<open>?R\\<close>[THEN bspec, OF B(2)] B(1) \\<open>I \\<noteq> {}\\<close>\n    show \"prob (\\<Inter>(A ` I)) = (\\<Prod>j\\<in>I. prob (A j))\"\n      by simp\n  qed\n  then show ?thesis using \\<open>I \\<noteq> {}\\<close>\n    by (simp add: rv indep_vars_def indep_sets_X sigma_sets_X indep_sets_finite_X cong: indep_sets_cong)\nqed\n\nlemma (in prob_space) indep_vars_compose:\n  assumes \"indep_vars M' X I\"\n  assumes rv: \"\\<And>i. i \\<in> I \\<Longrightarrow> Y i \\<in> measurable (M' i) (N i)\"\n  shows \"indep_vars N (\\<lambda>i. Y i \\<circ> X i) I\"\n  unfolding indep_vars_def\nproof\n  from rv \\<open>indep_vars M' X I\\<close>\n  show \"\\<forall>i\\<in>I. random_variable (N i) (Y i \\<circ> X i)\"\n    by (auto simp: indep_vars_def)\n\n  have \"indep_sets (\\<lambda>i. sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}) I\"\n    using \\<open>indep_vars M' X I\\<close> by (simp add: indep_vars_def)\n  then show \"indep_sets (\\<lambda>i. sigma_sets (space M) {(Y i \\<circ> X i) -` A \\<inter> space M |A. A \\<in> sets (N i)}) I\"\n  proof (rule indep_sets_mono_sets)\n    fix i assume \"i \\<in> I\"\n    with \\<open>indep_vars M' X I\\<close> have X: \"X i \\<in> space M \\<rightarrow> space (M' i)\"\n      unfolding indep_vars_def measurable_def by auto\n    { fix A assume \"A \\<in> sets (N i)\"\n      then have \"\\<exists>B. (Y i \\<circ> X i) -` A \\<inter> space M = X i -` B \\<inter> space M \\<and> B \\<in> sets (M' i)\"\n        by (intro exI[of _ \"Y i -` A \\<inter> space (M' i)\"])\n           (auto simp: vimage_comp intro!: measurable_sets rv \\<open>i \\<in> I\\<close> funcset_mem[OF X]) }\n    then show \"sigma_sets (space M) {(Y i \\<circ> X i) -` A \\<inter> space M |A. A \\<in> sets (N i)} \\<subseteq>\n      sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}\"\n      by (intro sigma_sets_subseteq) (auto simp: vimage_comp)\n  qed\nqed\n\nlemma (in prob_space) indep_vars_compose2:\n  assumes \"indep_vars M' X I\"\n  assumes rv: \"\\<And>i. i \\<in> I \\<Longrightarrow> Y i \\<in> measurable (M' i) (N i)\"\n  shows \"indep_vars N (\\<lambda>i x. Y i (X i x)) I\"\n  using indep_vars_compose [OF assms] by (simp add: comp_def)\n\nlemma (in prob_space) indep_var_compose:\n  assumes \"indep_var M1 X1 M2 X2\" \"Y1 \\<in> measurable M1 N1\" \"Y2 \\<in> measurable M2 N2\"\n  shows \"indep_var N1 (Y1 \\<circ> X1) N2 (Y2 \\<circ> X2)\"\nproof -\n  have \"indep_vars (case_bool N1 N2) (\\<lambda>b. case_bool Y1 Y2 b \\<circ> case_bool X1 X2 b) UNIV\"\n    using assms\n    by (intro indep_vars_compose[where M'=\"case_bool M1 M2\"])\n       (auto simp: indep_var_def split: bool.split)\n  also have \"(\\<lambda>b. case_bool Y1 Y2 b \\<circ> case_bool X1 X2 b) = case_bool (Y1 \\<circ> X1) (Y2 \\<circ> X2)\"\n    by (simp add: fun_eq_iff split: bool.split)\n  finally show ?thesis\n    unfolding indep_var_def .\nqed\n\nlemma (in prob_space) indep_vars_Min:\n  fixes X :: \"'i \\<Rightarrow> 'a \\<Rightarrow> real\"\n  assumes I: \"finite I\" \"i \\<notin> I\" and indep: \"indep_vars (\\<lambda>_. borel) X (insert i I)\"\n  shows \"indep_var borel (X i) borel (\\<lambda>\\<omega>. Min ((\\<lambda>i. X i \\<omega>)`I))\"\nproof -\n  have \"indep_var\n    borel ((\\<lambda>f. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) {i}))\n    borel ((\\<lambda>f. Min (f`I)) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) I))\"\n    using I by (intro indep_var_compose[OF indep_var_restrict[OF indep]] borel_measurable_Min) auto\n  also have \"((\\<lambda>f. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) {i})) = X i\"\n    by auto\n  also have \"((\\<lambda>f. Min (f`I)) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) I)) = (\\<lambda>\\<omega>. Min ((\\<lambda>i. X i \\<omega>)`I))\"\n    by (auto cong: rev_conj_cong)\n  finally show ?thesis\n    unfolding indep_var_def .\nqed\n\nlemma (in prob_space) indep_vars_sum:\n  fixes X :: \"'i \\<Rightarrow> 'a \\<Rightarrow> real\"\n  assumes I: \"finite I\" \"i \\<notin> I\" and indep: \"indep_vars (\\<lambda>_. borel) X (insert i I)\"\n  shows \"indep_var borel (X i) borel (\\<lambda>\\<omega>. \\<Sum>i\\<in>I. X i \\<omega>)\"\nproof -\n  have \"indep_var\n    borel ((\\<lambda>f. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) {i}))\n    borel ((\\<lambda>f. \\<Sum>i\\<in>I. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) I))\"\n    using I by (intro indep_var_compose[OF indep_var_restrict[OF indep]] ) auto\n  also have \"((\\<lambda>f. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) {i})) = X i\"\n    by auto\n  also have \"((\\<lambda>f. \\<Sum>i\\<in>I. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) I)) = (\\<lambda>\\<omega>. \\<Sum>i\\<in>I. X i \\<omega>)\"\n    by (auto cong: rev_conj_cong)\n  finally show ?thesis .\nqed\n\nlemma (in prob_space) indep_vars_prod:\n  fixes X :: \"'i \\<Rightarrow> 'a \\<Rightarrow> real\"\n  assumes I: \"finite I\" \"i \\<notin> I\" and indep: \"indep_vars (\\<lambda>_. borel) X (insert i I)\"\n  shows \"indep_var borel (X i) borel (\\<lambda>\\<omega>. \\<Prod>i\\<in>I. X i \\<omega>)\"\nproof -\n  have \"indep_var\n    borel ((\\<lambda>f. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) {i}))\n    borel ((\\<lambda>f. \\<Prod>i\\<in>I. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) I))\"\n    using I by (intro indep_var_compose[OF indep_var_restrict[OF indep]] ) auto\n  also have \"((\\<lambda>f. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) {i})) = X i\"\n    by auto\n  also have \"((\\<lambda>f. \\<Prod>i\\<in>I. f i) \\<circ> (\\<lambda>\\<omega>. restrict (\\<lambda>i. X i \\<omega>) I)) = (\\<lambda>\\<omega>. \\<Prod>i\\<in>I. X i \\<omega>)\"\n    by (auto cong: rev_conj_cong)\n  finally show ?thesis .\nqed\n\nlemma (in prob_space) indep_varsD_finite:\n  assumes X: \"indep_vars M' X I\"\n  assumes I: \"I \\<noteq> {}\" \"finite I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> A i \\<in> sets (M' i)\"\n  shows \"prob (\\<Inter>i\\<in>I. X i -` A i \\<inter> space M) = (\\<Prod>i\\<in>I. prob (X i -` A i \\<inter> space M))\"\nproof (rule indep_setsD)\n  show \"indep_sets (\\<lambda>i. sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}) I\"\n    using X by (auto simp: indep_vars_def)\n  show \"I \\<subseteq> I\" \"I \\<noteq> {}\" \"finite I\" using I by auto\n  show \"\\<forall>i\\<in>I. X i -` A i \\<inter> space M \\<in> sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}\"\n    using I by auto\nqed\n\nlemma (in prob_space) indep_varsD:\n  assumes X: \"indep_vars M' X I\"\n  assumes I: \"J \\<noteq> {}\" \"finite J\" \"J \\<subseteq> I\" \"\\<And>i. i \\<in> J \\<Longrightarrow> A i \\<in> sets (M' i)\"\n  shows \"prob (\\<Inter>i\\<in>J. X i -` A i \\<inter> space M) = (\\<Prod>i\\<in>J. prob (X i -` A i \\<inter> space M))\"\nproof (rule indep_setsD)\n  show \"indep_sets (\\<lambda>i. sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}) I\"\n    using X by (auto simp: indep_vars_def)\n  show \"\\<forall>i\\<in>J. X i -` A i \\<inter> space M \\<in> sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)}\"\n    using I by auto\nqed fact+\n\nlemma (in prob_space) indep_vars_iff_distr_eq_PiM:\n  fixes I :: \"'i set\" and X :: \"'i \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  assumes \"I \\<noteq> {}\"\n  assumes rv: \"\\<And>i. random_variable (M' i) (X i)\"\n  shows \"indep_vars M' X I \\<longleftrightarrow>\n    distr M (\\<Pi>\\<^sub>M i\\<in>I. M' i) (\\<lambda>x. \\<lambda>i\\<in>I. X i x) = (\\<Pi>\\<^sub>M i\\<in>I. distr M (M' i) (X i))\"\nproof -\n  let ?P = \"\\<Pi>\\<^sub>M i\\<in>I. M' i\"\n  let ?X = \"\\<lambda>x. \\<lambda>i\\<in>I. X i x\"\n  let ?D = \"distr M ?P ?X\"\n  have X: \"random_variable ?P ?X\" by (intro measurable_restrict rv)\n  interpret D: prob_space ?D by (intro prob_space_distr X)\n\n  let ?D' = \"\\<lambda>i. distr M (M' i) (X i)\"\n  let ?P' = \"\\<Pi>\\<^sub>M i\\<in>I. distr M (M' i) (X i)\"\n  interpret D': prob_space \"?D' i\" for i by (intro prob_space_distr rv)\n  interpret P: product_prob_space ?D' I ..\n\n  show ?thesis\n  proof\n    assume \"indep_vars M' X I\"\n    show \"?D = ?P'\"\n    proof (rule measure_eqI_generator_eq)\n      show \"Int_stable (prod_algebra I M')\"\n        by (rule Int_stable_prod_algebra)\n      show \"prod_algebra I M' \\<subseteq> Pow (space ?P)\"\n        using prod_algebra_sets_into_space by (simp add: space_PiM)\n      show \"sets ?D = sigma_sets (space ?P) (prod_algebra I M')\"\n        by (simp add: sets_PiM space_PiM)\n      show \"sets ?P' = sigma_sets (space ?P) (prod_algebra I M')\"\n        by (simp add: sets_PiM space_PiM cong: prod_algebra_cong)\n      let ?A = \"\\<lambda>i. \\<Pi>\\<^sub>E i\\<in>I. space (M' i)\"\n      show \"range ?A \\<subseteq> prod_algebra I M'\" \"(\\<Union>i. ?A i) = space (Pi\\<^sub>M I M')\"\n        by (auto simp: space_PiM intro!: space_in_prod_algebra cong: prod_algebra_cong)\n      { fix i show \"emeasure ?D (\\<Pi>\\<^sub>E i\\<in>I. space (M' i)) \\<noteq> \\<infinity>\" by auto }\n    next\n      fix E assume E: \"E \\<in> prod_algebra I M'\"\n      from prod_algebraE[OF E] obtain J Y\n        where J:\n          \"E = prod_emb I M' J (Pi\\<^sub>E J Y)\"\n          \"finite J\"\n          \"J \\<noteq> {} \\<or> I = {}\"\n          \"J \\<subseteq> I\"\n          \"\\<And>i. i \\<in> J \\<Longrightarrow> Y i \\<in> sets (M' i)\"\n        by auto\n      from E have \"E \\<in> sets ?P\" by (auto simp: sets_PiM)\n      then have \"emeasure ?D E = emeasure M (?X -` E \\<inter> space M)\"\n        by (simp add: emeasure_distr X)\n      also have \"?X -` E \\<inter> space M = (\\<Inter>i\\<in>J. X i -` Y i \\<inter> space M)\"\n        using J \\<open>I \\<noteq> {}\\<close> measurable_space[OF rv] by (auto simp: prod_emb_def PiE_iff split: if_split_asm)\n      also have \"emeasure M (\\<Inter>i\\<in>J. X i -` Y i \\<inter> space M) = (\\<Prod> i\\<in>J. emeasure M (X i -` Y i \\<inter> space M))\"\n        using \\<open>indep_vars M' X I\\<close> J \\<open>I \\<noteq> {}\\<close> using indep_varsD[of M' X I J]\n        by (auto simp: emeasure_eq_measure prod_ennreal measure_nonneg prod_nonneg)\n      also have \"\\<dots> = (\\<Prod> i\\<in>J. emeasure (?D' i) (Y i))\"\n        using rv J by (simp add: emeasure_distr)\n      also have \"\\<dots> = emeasure ?P' E\"\n        using P.emeasure_PiM_emb[of J Y] J by (simp add: prod_emb_def)\n      finally show \"emeasure ?D E = emeasure ?P' E\" .\n    qed\n  next\n    assume \"?D = ?P'\"\n    show \"indep_vars M' X I\" unfolding indep_vars_def\n    proof (intro conjI indep_setsI ballI rv)\n      fix i show \"sigma_sets (space M) {X i -` A \\<inter> space M |A. A \\<in> sets (M' i)} \\<subseteq> events\"\n        by (auto intro!: sets.sigma_sets_subset measurable_sets rv)\n    next\n      fix J Y' assume J: \"J \\<noteq> {}\" \"J \\<subseteq> I\" \"finite J\"\n      assume Y': \"\\<forall>j\\<in>J. Y' j \\<in> sigma_sets (space M) {X j -` A \\<inter> space M |A. A \\<in> sets (M' j)}\"\n      have \"\\<forall>j\\<in>J. \\<exists>Y. Y' j = X j -` Y \\<inter> space M \\<and> Y \\<in> sets (M' j)\"\n      proof\n        fix j assume \"j \\<in> J\"\n        from Y'[rule_format, OF this] rv[of j]\n        show \"\\<exists>Y. Y' j = X j -` Y \\<inter> space M \\<and> Y \\<in> sets (M' j)\"\n          by (subst (asm) sigma_sets_vimage_commute[symmetric, of _ _ \"space (M' j)\"])\n             (auto dest: measurable_space simp: sets.sigma_sets_eq)\n      qed\n      from bchoice[OF this] obtain Y where\n        Y: \"\\<And>j. j \\<in> J \\<Longrightarrow> Y' j = X j -` Y j \\<inter> space M\" \"\\<And>j. j \\<in> J \\<Longrightarrow> Y j \\<in> sets (M' j)\" by auto\n      let ?E = \"prod_emb I M' J (Pi\\<^sub>E J Y)\"\n      from Y have \"(\\<Inter>j\\<in>J. Y' j) = ?X -` ?E \\<inter> space M\"\n        using J \\<open>I \\<noteq> {}\\<close> measurable_space[OF rv] by (auto simp: prod_emb_def PiE_iff split: if_split_asm)\n      then have \"emeasure M (\\<Inter>j\\<in>J. Y' j) = emeasure M (?X -` ?E \\<inter> space M)\"\n        by simp\n      also have \"\\<dots> = emeasure ?D ?E\"\n        using Y  J by (intro emeasure_distr[symmetric] X sets_PiM_I) auto\n      also have \"\\<dots> = emeasure ?P' ?E\"\n        using \\<open>?D = ?P'\\<close> by simp\n      also have \"\\<dots> = (\\<Prod> i\\<in>J. emeasure (?D' i) (Y i))\"\n        using P.emeasure_PiM_emb[of J Y] J Y by (simp add: prod_emb_def)\n      also have \"\\<dots> = (\\<Prod> i\\<in>J. emeasure M (Y' i))\"\n        using rv J Y by (simp add: emeasure_distr)\n      finally have \"emeasure M (\\<Inter>j\\<in>J. Y' j) = (\\<Prod> i\\<in>J. emeasure M (Y' i))\" .\n      then show \"prob (\\<Inter>j\\<in>J. Y' j) = (\\<Prod> i\\<in>J. prob (Y' i))\"\n        by (auto simp: emeasure_eq_measure prod_ennreal measure_nonneg prod_nonneg)\n    qed\n  qed\nqed\n\nlemma (in prob_space) indep_vars_iff_distr_eq_PiM':\n  fixes I :: \"'i set\" and X :: \"'i \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  assumes \"I \\<noteq> {}\"\n  assumes rv: \"\\<And>i. i \\<in> I \\<Longrightarrow> random_variable (M' i) (X i)\"\n  shows \"indep_vars M' X I \\<longleftrightarrow>\n           distr M (\\<Pi>\\<^sub>M i\\<in>I. M' i) (\\<lambda>x. \\<lambda>i\\<in>I. X i x) = (\\<Pi>\\<^sub>M i\\<in>I. distr M (M' i) (X i))\"\nproof -\n  from assms obtain j where j: \"j \\<in> I\"\n    by auto\n  define N' where \"N' = (\\<lambda>i. if i \\<in> I then M' i else M' j)\"\n  define Y where \"Y = (\\<lambda>i. if i \\<in> I then X i else X j)\"\n  have rv: \"random_variable (N' i) (Y i)\" for i\n    using j by (auto simp: N'_def Y_def intro: assms)\n\n  have \"indep_vars M' X I = indep_vars N' Y I\"\n    by (intro indep_vars_cong) (auto simp: N'_def Y_def)\n  also have \"\\<dots> \\<longleftrightarrow> distr M (\\<Pi>\\<^sub>M i\\<in>I. N' i) (\\<lambda>x. \\<lambda>i\\<in>I. Y i x) = (\\<Pi>\\<^sub>M i\\<in>I. distr M (N' i) (Y i))\"\n    by (intro indep_vars_iff_distr_eq_PiM rv assms)\n  also have \"(\\<Pi>\\<^sub>M i\\<in>I. N' i) = (\\<Pi>\\<^sub>M i\\<in>I. M' i)\"\n    by (intro PiM_cong) (simp_all add: N'_def)\n  also have \"(\\<lambda>x. \\<lambda>i\\<in>I. Y i x) = (\\<lambda>x. \\<lambda>i\\<in>I. X i x)\"\n    by (simp_all add: Y_def fun_eq_iff)\n  also have \"(\\<Pi>\\<^sub>M i\\<in>I. distr M (N' i) (Y i)) = (\\<Pi>\\<^sub>M i\\<in>I. distr M (M' i) (X i))\"\n    by (intro PiM_cong distr_cong) (simp_all add: N'_def Y_def)\n  finally show ?thesis .\nqed\n\nlemma (in prob_space) indep_varD:\n  assumes indep: \"indep_var Ma A Mb B\"\n  assumes sets: \"Xa \\<in> sets Ma\" \"Xb \\<in> sets Mb\"\n  shows \"prob ((\\<lambda>x. (A x, B x)) -` (Xa \\<times> Xb) \\<inter> space M) =\n    prob (A -` Xa \\<inter> space M) * prob (B -` Xb \\<inter> space M)\"\nproof -\n  have \"prob ((\\<lambda>x. (A x, B x)) -` (Xa \\<times> Xb) \\<inter> space M) =\n    prob (\\<Inter>i\\<in>UNIV. (case_bool A B i -` case_bool Xa Xb i \\<inter> space M))\"\n    by (auto intro!: arg_cong[where f=prob] simp: UNIV_bool)\n  also have \"\\<dots> = (\\<Prod>i\\<in>UNIV. prob (case_bool A B i -` case_bool Xa Xb i \\<inter> space M))\"\n    using indep unfolding indep_var_def\n    by (rule indep_varsD) (auto split: bool.split intro: sets)\n  also have \"\\<dots> = prob (A -` Xa \\<inter> space M) * prob (B -` Xb \\<inter> space M)\"\n    unfolding UNIV_bool by simp\n  finally show ?thesis .\nqed\n\nlemma (in prob_space) prob_indep_random_variable:\n  assumes ind[simp]: \"indep_var N X N Y\"\n  assumes [simp]: \"A \\<in> sets N\" \"B \\<in> sets N\"\n  shows \"\\<P>(x in M. X x \\<in> A \\<and> Y x \\<in> B) = \\<P>(x in M. X x \\<in> A) * \\<P>(x in M. Y x \\<in> B)\"\nproof-\n  have  \" \\<P>(x in M. (X x)\\<in>A \\<and>  (Y x)\\<in> B ) = prob ((\\<lambda>x. (X x, Y x)) -` (A \\<times> B) \\<inter> space M)\"\n    by (auto intro!: arg_cong[where f= prob])\n  also have \"...=  prob (X -` A \\<inter> space M) * prob (Y -` B \\<inter> space M)\"\n    by (auto intro!: indep_varD[where Ma=N and Mb=N])\n  also have \"... = \\<P>(x in M. X x \\<in> A) * \\<P>(x in M. Y x \\<in> B)\"\n    by (auto intro!: arg_cong2[where f= \"(*)\"] arg_cong[where f= prob])\n  finally show ?thesis .\nqed\n\nlemma (in prob_space)\n  assumes \"indep_var S X T Y\"\n  shows indep_var_rv1: \"random_variable S X\"\n    and indep_var_rv2: \"random_variable T Y\"\nproof -\n  have \"\\<forall>i\\<in>UNIV. random_variable (case_bool S T i) (case_bool X Y i)\"\n    using assms unfolding indep_var_def indep_vars_def by auto\n  then show \"random_variable S X\" \"random_variable T Y\"\n    unfolding UNIV_bool by auto\nqed\n\nlemma (in prob_space) indep_var_distribution_eq:\n  \"indep_var S X T Y \\<longleftrightarrow> random_variable S X \\<and> random_variable T Y \\<and>\n    distr M S X \\<Otimes>\\<^sub>M distr M T Y = distr M (S \\<Otimes>\\<^sub>M T) (\\<lambda>x. (X x, Y x))\" (is \"_ \\<longleftrightarrow> _ \\<and> _ \\<and> ?S \\<Otimes>\\<^sub>M ?T = ?J\")\nproof safe\n  assume \"indep_var S X T Y\"\n  then show rvs: \"random_variable S X\" \"random_variable T Y\"\n    by (blast dest: indep_var_rv1 indep_var_rv2)+\n  then have XY: \"random_variable (S \\<Otimes>\\<^sub>M T) (\\<lambda>x. (X x, Y x))\"\n    by (rule measurable_Pair)\n\n  interpret X: prob_space ?S by (rule prob_space_distr) fact\n  interpret Y: prob_space ?T by (rule prob_space_distr) fact\n  interpret XY: pair_prob_space ?S ?T ..\n  show \"?S \\<Otimes>\\<^sub>M ?T = ?J\"\n  proof (rule pair_measure_eqI)\n    show \"sigma_finite_measure ?S\" ..\n    show \"sigma_finite_measure ?T\" ..\n\n    fix A B assume A: \"A \\<in> sets ?S\" and B: \"B \\<in> sets ?T\"\n    have \"emeasure ?J (A \\<times> B) = emeasure M ((\\<lambda>x. (X x, Y x)) -` (A \\<times> B) \\<inter> space M)\"\n      using A B by (intro emeasure_distr[OF XY]) auto\n    also have \"\\<dots> = emeasure M (X -` A \\<inter> space M) * emeasure M (Y -` B \\<inter> space M)\"\n      using indep_varD[OF \\<open>indep_var S X T Y\\<close>, of A B] A B\n      by (simp add: emeasure_eq_measure measure_nonneg ennreal_mult)\n    also have \"\\<dots> = emeasure ?S A * emeasure ?T B\"\n      using rvs A B by (simp add: emeasure_distr)\n    finally show \"emeasure ?S A * emeasure ?T B = emeasure ?J (A \\<times> B)\" by simp\n  qed simp\nnext\n  assume rvs: \"random_variable S X\" \"random_variable T Y\"\n  then have XY: \"random_variable (S \\<Otimes>\\<^sub>M T) (\\<lambda>x. (X x, Y x))\"\n    by (rule measurable_Pair)\n\n  let ?S = \"distr M S X\" and ?T = \"distr M T Y\"\n  interpret X: prob_space ?S by (rule prob_space_distr) fact\n  interpret Y: prob_space ?T by (rule prob_space_distr) fact\n  interpret XY: pair_prob_space ?S ?T ..\n\n  assume \"?S \\<Otimes>\\<^sub>M ?T = ?J\"\n\n  { fix S and X\n    have \"Int_stable {X -` A \\<inter> space M |A. A \\<in> sets S}\"\n    proof (safe intro!: Int_stableI)\n      fix A B assume \"A \\<in> sets S\" \"B \\<in> sets S\"\n      then show \"\\<exists>C. (X -` A \\<inter> space M) \\<inter> (X -` B \\<inter> space M) = (X -` C \\<inter> space M) \\<and> C \\<in> sets S\"\n        by (intro exI[of _ \"A \\<inter> B\"]) auto\n    qed }\n  note Int_stable = this\n\n  show \"indep_var S X T Y\" unfolding indep_var_eq\n  proof (intro conjI indep_set_sigma_sets Int_stable rvs)\n    show \"indep_set {X -` A \\<inter> space M |A. A \\<in> sets S} {Y -` A \\<inter> space M |A. A \\<in> sets T}\"\n    proof (safe intro!: indep_setI)\n      { fix A assume \"A \\<in> sets S\" then show \"X -` A \\<inter> space M \\<in> sets M\"\n        using \\<open>X \\<in> measurable M S\\<close> by (auto intro: measurable_sets) }\n      { fix A assume \"A \\<in> sets T\" then show \"Y -` A \\<inter> space M \\<in> sets M\"\n        using \\<open>Y \\<in> measurable M T\\<close> by (auto intro: measurable_sets) }\n    next\n      fix A B assume ab: \"A \\<in> sets S\" \"B \\<in> sets T\"\n      then have \"prob ((X -` A \\<inter> space M) \\<inter> (Y -` B \\<inter> space M)) = emeasure ?J (A \\<times> B)\"\n        using XY by (auto simp add: emeasure_distr emeasure_eq_measure measure_nonneg intro!: arg_cong[where f=\"prob\"])\n      also have \"\\<dots> = emeasure (?S \\<Otimes>\\<^sub>M ?T) (A \\<times> B)\"\n        unfolding \\<open>?S \\<Otimes>\\<^sub>M ?T = ?J\\<close> ..\n      also have \"\\<dots> = emeasure ?S A * emeasure ?T B\"\n        using ab by (simp add: Y.emeasure_pair_measure_Times)\n      finally show \"prob ((X -` A \\<inter> space M) \\<inter> (Y -` B \\<inter> space M)) =\n        prob (X -` A \\<inter> space M) * prob (Y -` B \\<inter> space M)\"\n        using rvs ab by (simp add: emeasure_eq_measure emeasure_distr measure_nonneg ennreal_mult[symmetric])\n    qed\n  qed\nqed\n\nlemma (in prob_space) distributed_joint_indep:\n  assumes S: \"sigma_finite_measure S\" and T: \"sigma_finite_measure T\"\n  assumes X: \"distributed M S X Px\" and Y: \"distributed M T Y Py\"\n  assumes indep: \"indep_var S X T Y\"\n  shows \"distributed M (S \\<Otimes>\\<^sub>M T) (\\<lambda>x. (X x, Y x)) (\\<lambda>(x, y). Px x * Py y)\"\n  using indep_var_distribution_eq[of S X T Y] indep\n  by (intro distributed_joint_indep'[OF S T X Y]) auto\n\nlemma (in prob_space) indep_vars_nn_integral:\n  assumes I: \"finite I\" \"indep_vars (\\<lambda>_. borel) X I\" \"\\<And>i \\<omega>. i \\<in> I \\<Longrightarrow> 0 \\<le> X i \\<omega>\"\n  shows \"(\\<integral>\\<^sup>+\\<omega>. (\\<Prod>i\\<in>I. X i \\<omega>) \\<partial>M) = (\\<Prod>i\\<in>I. \\<integral>\\<^sup>+\\<omega>. X i \\<omega> \\<partial>M)\"\nproof cases\n  assume \"I \\<noteq> {}\"\n  define Y where [abs_def]: \"Y i \\<omega> = (if i \\<in> I then X i \\<omega> else 0)\" for i \\<omega>\n  { fix i have \"i \\<in> I \\<Longrightarrow> random_variable borel (X i)\"\n    using I(2) by (cases \"i\\<in>I\") (auto simp: indep_vars_def) }\n  note rv_X = this\n\n  { fix i have \"random_variable borel (Y i)\"\n    using I(2) by (cases \"i\\<in>I\") (auto simp: Y_def rv_X) }\n  note rv_Y = this[measurable]\n\n  interpret Y: prob_space \"distr M borel (Y i)\" for i\n    using I(2) by (cases \"i \\<in> I\") (auto intro!: prob_space_distr simp: indep_vars_def prob_space_return)\n  interpret product_sigma_finite \"\\<lambda>i. distr M borel (Y i)\"\n    ..\n\n  have indep_Y: \"indep_vars (\\<lambda>i. borel) Y I\"\n    by (rule indep_vars_cong[THEN iffD1, OF _ _ _ I(2)]) (auto simp: Y_def)\n\n  have \"(\\<integral>\\<^sup>+\\<omega>. (\\<Prod>i\\<in>I. X i \\<omega>) \\<partial>M) = (\\<integral>\\<^sup>+\\<omega>. (\\<Prod>i\\<in>I. Y i \\<omega>) \\<partial>M)\"\n    using I(3) by (auto intro!: nn_integral_cong prod.cong simp add: Y_def max_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+\\<omega>. (\\<Prod>i\\<in>I. \\<omega> i) \\<partial>distr M (Pi\\<^sub>M I (\\<lambda>i. borel)) (\\<lambda>x. \\<lambda>i\\<in>I. Y i x))\"\n    by (subst nn_integral_distr) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+\\<omega>. (\\<Prod>i\\<in>I. \\<omega> i) \\<partial>Pi\\<^sub>M I (\\<lambda>i. distr M borel (Y i)))\"\n    unfolding indep_vars_iff_distr_eq_PiM[THEN iffD1, OF \\<open>I \\<noteq> {}\\<close> rv_Y indep_Y] ..\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. (\\<integral>\\<^sup>+\\<omega>. \\<omega> \\<partial>distr M borel (Y i)))\"\n    by (rule product_nn_integral_prod) (auto intro: \\<open>finite I\\<close>)\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. \\<integral>\\<^sup>+\\<omega>. X i \\<omega> \\<partial>M)\"\n    by (intro prod.cong nn_integral_cong) (auto simp: nn_integral_distr Y_def rv_X)\n  finally show ?thesis .\nqed (simp add: emeasure_space_1)\n\nlemma (in prob_space)\n  fixes X :: \"'i \\<Rightarrow> 'a \\<Rightarrow> 'b::{real_normed_field, banach, second_countable_topology}\"\n  assumes I: \"finite I\" \"indep_vars (\\<lambda>_. borel) X I\" \"\\<And>i. i \\<in> I \\<Longrightarrow> integrable M (X i)\"\n  shows indep_vars_lebesgue_integral: \"(\\<integral>\\<omega>. (\\<Prod>i\\<in>I. X i \\<omega>) \\<partial>M) = (\\<Prod>i\\<in>I. \\<integral>\\<omega>. X i \\<omega> \\<partial>M)\" (is ?eq)\n    and indep_vars_integrable: \"integrable M (\\<lambda>\\<omega>. (\\<Prod>i\\<in>I. X i \\<omega>))\" (is ?int)\nproof (induct rule: case_split)\n  assume \"I \\<noteq> {}\"\n  define Y where [abs_def]: \"Y i \\<omega> = (if i \\<in> I then X i \\<omega> else 0)\" for i \\<omega>\n  { fix i have \"i \\<in> I \\<Longrightarrow> random_variable borel (X i)\"\n    using I(2) by (cases \"i\\<in>I\") (auto simp: indep_vars_def) }\n  note rv_X = this[measurable]\n\n  { fix i have \"random_variable borel (Y i)\"\n    using I(2) by (cases \"i\\<in>I\") (auto simp: Y_def rv_X) }\n  note rv_Y = this[measurable]\n\n  { fix i have \"integrable M (Y i)\"\n    using I(3) by (cases \"i\\<in>I\") (auto simp: Y_def) }\n  note int_Y = this\n\n  interpret Y: prob_space \"distr M borel (Y i)\" for i\n    using I(2) by (cases \"i \\<in> I\") (auto intro!: prob_space_distr simp: indep_vars_def prob_space_return)\n  interpret product_sigma_finite \"\\<lambda>i. distr M borel (Y i)\"\n    ..\n\n  have indep_Y: \"indep_vars (\\<lambda>i. borel) Y I\"\n    by (rule indep_vars_cong[THEN iffD1, OF _ _ _ I(2)]) (auto simp: Y_def)\n\n  have \"(\\<integral>\\<omega>. (\\<Prod>i\\<in>I. X i \\<omega>) \\<partial>M) = (\\<integral>\\<omega>. (\\<Prod>i\\<in>I. Y i \\<omega>) \\<partial>M)\"\n    using I(3) by (simp add: Y_def)\n  also have \"\\<dots> = (\\<integral>\\<omega>. (\\<Prod>i\\<in>I. \\<omega> i) \\<partial>distr M (Pi\\<^sub>M I (\\<lambda>i. borel)) (\\<lambda>x. \\<lambda>i\\<in>I. Y i x))\"\n    by (subst integral_distr) auto\n  also have \"\\<dots> = (\\<integral>\\<omega>. (\\<Prod>i\\<in>I. \\<omega> i) \\<partial>Pi\\<^sub>M I (\\<lambda>i. distr M borel (Y i)))\"\n    unfolding indep_vars_iff_distr_eq_PiM[THEN iffD1, OF \\<open>I \\<noteq> {}\\<close> rv_Y indep_Y] ..\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. (\\<integral>\\<omega>. \\<omega> \\<partial>distr M borel (Y i)))\"\n    by (rule product_integral_prod) (auto intro: \\<open>finite I\\<close> simp: integrable_distr_eq int_Y)\n  also have \"\\<dots> = (\\<Prod>i\\<in>I. \\<integral>\\<omega>. X i \\<omega> \\<partial>M)\"\n    by (intro prod.cong integral_cong)\n       (auto simp: integral_distr Y_def rv_X)\n  finally show ?eq .\n\n  have \"integrable (distr M (Pi\\<^sub>M I (\\<lambda>i. borel)) (\\<lambda>x. \\<lambda>i\\<in>I. Y i x)) (\\<lambda>\\<omega>. (\\<Prod>i\\<in>I. \\<omega> i))\"\n    unfolding indep_vars_iff_distr_eq_PiM[THEN iffD1, OF \\<open>I \\<noteq> {}\\<close> rv_Y indep_Y]\n    by (intro product_integrable_prod[OF \\<open>finite I\\<close>])\n       (simp add: integrable_distr_eq int_Y)\n  then show ?int\n    by (simp add: integrable_distr_eq Y_def)\nqed (simp_all add: prob_space)\n\nlemma (in prob_space)\n  fixes X1 X2 :: \"'a \\<Rightarrow> 'b::{real_normed_field, banach, second_countable_topology}\"\n  assumes \"indep_var borel X1 borel X2\" \"integrable M X1\" \"integrable M X2\"\n  shows indep_var_lebesgue_integral: \"(\\<integral>\\<omega>. X1 \\<omega> * X2 \\<omega> \\<partial>M) = (\\<integral>\\<omega>. X1 \\<omega> \\<partial>M) * (\\<integral>\\<omega>. X2 \\<omega> \\<partial>M)\" (is ?eq)\n    and indep_var_integrable: \"integrable M (\\<lambda>\\<omega>. X1 \\<omega> * X2 \\<omega>)\" (is ?int)\nunfolding indep_var_def\nproof -\n  have *: \"(\\<lambda>\\<omega>. X1 \\<omega> * X2 \\<omega>) = (\\<lambda>\\<omega>. \\<Prod>i\\<in>UNIV. (case_bool X1 X2 i \\<omega>))\"\n    by (simp add: UNIV_bool mult.commute)\n  have **: \"(\\<lambda> _. borel) = case_bool borel borel\"\n    by (rule ext, metis (full_types) bool.simps(3) bool.simps(4))\n  show ?eq\n    apply (subst *)\n    apply (subst indep_vars_lebesgue_integral)\n    apply (auto)\n    apply (subst **, subst indep_var_def [symmetric], rule assms)\n    apply (simp split: bool.split add: assms)\n    by (simp add: UNIV_bool mult.commute)\n  show ?int\n    apply (subst *)\n    apply (rule indep_vars_integrable)\n    apply auto\n    apply (subst **, subst indep_var_def [symmetric], rule assms)\n    by (simp split: bool.split add: assms)\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Probability/Independent_Family.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.8872045922259088, "lm_q1q2_score": 0.7770022523071111}}
{"text": "(*\nAuthor: Wenda Li\nUniversity of Cambridge\n\nThis example is addapted from Tobias Nipkow's Insertion Sort \nin \"HOL-Data_Structures.Sorting\".\n*)\n\ntheory Insertion_Sort_Demo imports\n \"HOL-Data_Structures.Sorting\"\nbegin\n\nhide_const (open) insert sort sorted T_isort\n\nsection \\<open>Implementation\\<close>\n\nfun insert :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  insert_base:   \"insert x Nil = [x]\" |\n  insert_induct: \"insert x (Cons y ys) =\n      (if x \\<le> y then Cons x (Cons y ys) \n                else Cons y (insert x ys))\"\n\nvalue \"insert 3 Nil\"   (*returns [3]*)\nvalue \"insert 2 [1,3]\" (*returns [1,2,3]*)\n\nfun sort :: \"int list \\<Rightarrow> int list\" where\n  sort_base:   \"sort Nil = []\" |\n  sort_induct: \"sort (Cons x xs) = insert x (sort xs)\"\n\nvalue \"sort []\"        (*returns []*)\nvalue \"sort [1]\"       (*returns [1]*)\nvalue \"sort [2,3,1,4]\" (*returns [1,2,3,4]*)\n\nfun sorted :: \"int list \\<Rightarrow> bool\" where\n  sorted_base: \"sorted Nil = True\" |\n  sorted_induct: \"sorted (Cons x ys) \n          = ((\\<forall>y \\<in> set ys. x \\<le> y) \\<and> sorted ys)\"\n\nsection \"Functional Correctness\"\n\nlemma mset_insort: \"mset (insert x xs) = {#x#} + mset xs\"\n  by (induction xs) auto\n\nlemma mset_isort: \"mset (sort xs) = mset xs\"\n  by (induction xs) (auto simp add: mset_insort)\n\nlemma set_insort: \"set (insert x xs) = {x} \\<union> set xs\"\n  by(simp add: mset_insort flip: set_mset_mset)\n\n(* (*More compact proof*)\nlemma sorted_insort: \"sorted (insert a xs) = sorted xs\"\nby(induction xs) (auto simp add: set_insort)\n\nlemma sorted_isort: \"sorted (sort xs)\"\n  by(induction xs) (auto simp: sorted_insort)\n*)\n\n(*For demonstration purposes, \n  I deleted those simplification rules*)\ndeclare \n  insert.simps[simp del] \n  sort.simps[simp del] \n  sorted.simps[simp del]\n\nlemma sorted_insert: \"sorted (insert a xs) = sorted xs\"\nproof (induction xs)\n  have \"sorted (insert a []) = sorted [a]\"\n    using insert_base by simp\n  also have \"... = ((\\<forall>y \\<in> set []. a \\<le> y) \\<and> sorted [])\"\n    using sorted_induct by simp\n  also have \"... = (True \\<and> sorted [])\" by simp\n  also have \"... = sorted []\" by simp\n  finally show \"sorted (insert a []) = sorted []\" . \nnext\n  fix x xs \n  assume IH:\"sorted (insert a xs) = sorted xs\"\n  let ?thesis = \"sorted (insert a (Cons x xs)) \n      = sorted (Cons x xs)\"\n  have ?thesis if \"a\\<le>x\"\n  proof -\n    have \"sorted (insert a (Cons x xs))\n            = sorted (Cons a (Cons x xs))\"\n      using \\<open>a\\<le>x\\<close> insert_induct by simp\n    also have \"... = ((\\<forall>y \\<in> set (Cons x xs). a \\<le> y) \n                      \\<and> sorted (Cons x xs))\"\n      using sorted_induct by simp\n    also have \"... = (True \\<and> sorted (Cons x xs))\"\n      using \\<open>a\\<le>x\\<close> sorted_induct by auto \n    also have \"... = sorted (Cons x xs)\" by simp\n    finally show ?thesis .\n  qed\n  moreover have ?thesis if \"\\<not> a\\<le>x\"\n  proof -\n    have \"sorted (insert a (Cons x xs))\n            = sorted (Cons x (insert a xs))\"\n      using \\<open>\\<not> a\\<le>x\\<close> insert_induct by simp\n    also have \"... = ((\\<forall>y \\<in> set (Cons a xs). x \\<le> y) \n                      \\<and> sorted (insert a xs))\"\n      using sorted_induct set_insort by simp\n    also have \"... = ((\\<forall>y \\<in> set (Cons a xs). x \\<le> y) \n                      \\<and> sorted xs)\"\n      using IH by simp\n    also have \"... = ((\\<forall>y \\<in> set xs. x \\<le> y) \\<and> sorted xs)\"\n      using \\<open>\\<not> a\\<le>x\\<close> by simp\n    also have \"... = sorted (Cons x xs)\"\n      using sorted_induct by simp\n    finally show ?thesis .\n  qed\n  ultimately show ?thesis by auto\nqed\n\nlemma sorted_sort: \"sorted (sort xs)\"\nproof (induction xs)\n  have \"sorted (sort Nil) = sorted Nil\"\n    using sort_base by simp\n  also have \"... = True\" using sorted_base by simp\n  finally show \"sorted (sort Nil)\" by simp\nnext\n  fix x xs assume IH: \"sorted (sort xs)\"\n  have \"sorted (sort (Cons x xs)) \n                  = sorted (insert x (sort xs))\"\n    using sort_induct by simp\n  also have \"... = sorted (sort xs)\" \n    using sorted_insert by simp\n  also have \"... = True\"using IH by simp\n  finally show \"sorted (sort (Cons x xs))\" by simp\nqed\n\nsection \"Time Complexity\"\n\ntext \\<open>We count the number of function calls.\\<close>\n\nfun T_insert :: \"int \\<Rightarrow> int list \\<Rightarrow> nat\" where\n  \"T_insert x Nil = 1\" |\n  \"T_insert x (Cons y ys) =\n    (if x \\<le> y then 0 else T_insert x ys) + 1\"\n\nfun T_sort :: \"int list \\<Rightarrow> nat\" where\n  \"T_sort Nil = 1\" |\n  \"T_sort (Cons x xs) = T_sort xs \n                   + T_insert x (sort xs) + 1\"\n\nlemma T_insert_length: \"T_insert x xs \\<le> length xs + 1\"\n  by (induction xs)  auto\n\nlemma length_insert: \"length (insert x xs) = length xs + 1\"\n  by (induction xs)  (auto simp:insert.simps)\n\nlemma length_sort: \"length (sort xs) = length xs\"\n  by (induction xs) (auto simp: length_insert sort.simps)\n\nlemma T_sort_length:\n  \"T_sort xs \\<le> (length xs + 1) ^ 2\"\nproof(induction xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  have \"T_sort (x#xs) = T_sort xs + T_insert x (sort xs) + 1\" by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + T_insert x (sort xs) + 1\"\n    using Cons.IH by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + length xs + 1 + 1\"\n    using T_insert_length[of x \"sort xs\"] by (simp add: length_sort)\n  also have \"\\<dots> \\<le> (length(x#xs) + 1) ^ 2\"\n    by (simp add: power2_eq_square)\n  finally show ?case .\nqed\n\nend", "meta": {"author": "Wenda302", "repo": "Demo", "sha": "170bfa52fd817d4e67b38d5d210ff9233c2977f2", "save_path": "github-repos/isabelle/Wenda302-Demo", "path": "github-repos/isabelle/Wenda302-Demo/Demo-170bfa52fd817d4e67b38d5d210ff9233c2977f2/Insertion_Sort_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8757870029950159, "lm_q1q2_score": 0.7770022469510283}}
{"text": "theory nat_no_text \nimports Main  \n        \"HOL-Library.LaTeXsugar\"\nbegin\n\n \nsubsection\\<open> Definições Básicas\\<close>\n \n\ndatatype Nat = Z | suc Nat\n\n \n\n\nprimrec add::\"Nat \\<Rightarrow> Nat \\<Rightarrow> Nat\" \n  where\n    add01:  \"add x Z = x\" |\n    add02:  \"add x (suc y) = suc (add x y)\"\n\n \nsubsection\\<open> Verificação com scripts de comandos\\<close>\n\n \n\ntheorem th_add01as : \"\\<forall> x y. add (add x y) z = add x (add y z)\"\n \n  apply (induct z)\n  apply (simp) \\<comment> \\<open>resolve o caso base\\<close>\n  apply (simp) \\<comment> \\<open>resolve o caso indutivo\\<close>\n     \ndone \n\nsubsection\\<open> Verificação com  a linguagem Isar \\<close>\n\ntheorem th_add01isA : \"\\<forall> x y.  add (add x y) z = add x (add y z)\"\n  proof(induct z)\n  \\<comment> \\<open>prova do caso base\\<close>\n    show \"\\<forall> x y. add (add x y) Z = add x (add y Z)\" by simp\n  next \n    fix x0::Nat \\<comment> \\<open>elemento arbitrário, mas fixo\\<close>\n    assume IH: \"\\<forall> x y. add (add x y) x0 = add x (add y x0)\"\n    show \"\\<forall> x y. add (add x y) (suc x0) = add x (add y (suc x0))\" by (simp add:IH)\n  qed\n\n\ntheorem th_add01isB:\"\\<forall> x y.  add (add x y) z = add x (add y z)\"\n  proof (induct z)\n    show \"\\<forall> x y. add (add x y) Z = add x (add y Z)\"\n      proof (rule allI, rule allI)\n        fix x0::Nat and y0::Nat\n        have \"add (add x0 y0) Z = add x0 y0\" by (simp only:add01)\n        also have \"...  = add x0 (add y0 Z)\" by (simp only:add01)\n        finally show \"add (add x0 y0) Z = add x0 (add y0 Z)\" by simp\n      qed\n  next \\<comment> \\<open>pega o próximo subojetivo, isto é, o passo de indução\\<close>\n    fix z0::Nat\n    assume IH: \"\\<forall> x y. add (add x y) z0 = add x (add y z0)\"\n    show \"\\<forall> x y. add (add x y) (suc z0) = add x (add y (suc z0))\"\n      proof (rule allI, rule allI)\n        fix x0::Nat and y0::Nat\n        have \"add (add x0 y0) (suc z0) = suc (add (add x0 y0) z0)\" \n         by (simp only:add02) \n        also have \"...  = suc (add x0 (add y0 z0))\" by (simp only:IH)\n        also have \"... = add x0 (suc (add y0 z0))\" by (simp only:add02)\n        also have \"... = add x0 (add y0 (suc z0))\" by (simp only:add02)\n        finally \n        show \"add (add x0 y0) (suc z0) = add x0 (add y0 (suc z0))\" by simp\n     qed\n  qed\n\nprimrec mult::\"Nat \\<Rightarrow> Nat \\<Rightarrow> Nat\" where\n   mult01: \"mult x Z = Z\" |\n   mult02: \"mult x (suc y) = add x (mult x y)\"\n\n \nsubsection\\<open> Pit Stop\\<close>\nend\n", "meta": {"author": "alfiomartini", "repo": "IsaForNewbies", "sha": "3e5ee3d35c347accb40b8b2fabb81efdd26e70e1", "save_path": "github-repos/isabelle/alfiomartini-IsaForNewbies", "path": "github-repos/isabelle/alfiomartini-IsaForNewbies/IsaForNewbies-3e5ee3d35c347accb40b8b2fabb81efdd26e70e1/Theories/nat_no_text.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.918480237330998, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7769814034528195}}
{"text": "theory topological_space imports\n  \"~~/src/HOL/Library/FuncSet\" \n  \"~~/src/HOL/Library/Zorn\"\n\nbegin\n\n(* datatype_new   'a top = \"'a set set\"*)  \n\n\nlocale topological_space =\n  fixes X \n  and T \n  assumes O1[simp]  :  \"T \\<subseteq>  Pow X\"\n  and     O2[simp]  :  \"{} \\<in> T\"\n  and     O3[simp]  :  \"X \\<in> T\"\n  and     O4[simp]  :  \"\\<lbrakk>x \\<in> T ; y \\<in> T \\<rbrakk> \\<Longrightarrow>  x \\<inter> y \\<in> T\"\n  and     O5[simp]  :  \"\\<lbrakk>T1 \\<subseteq> T \\<rbrakk> \\<Longrightarrow>  \\<Union>T1  \\<in> T\"\n\nthm topological_space_def\n\nlemma Un_eq_Union: \"A \\<union> B = \\<Union>{A, B}\"\n  by blast\n\n\nthm Un_eq_Union \n\nlemma  (in topological_space) union_in_T [simp]:\n    \"\\<lbrakk> x \\<in> T ; y \\<in> T \\<rbrakk> \\<Longrightarrow> x \\<union> y \\<in> T\"\napply (subst Un_eq_Union)\napply (rule O5)\napply simp\ndone\n\nlemma (in topological_space) union_in_T2 :\n    assumes  a :\"x \\<in> T \\<and>  y \\<in>  T\"   shows \" x \\<union>  y \\<in>  T\"\nproof- \n   from a have b:  \"{x,y} \\<subseteq>  T\"  apply simp done  \n   from b have c : \"\\<Union>{x,y} \\<in>  T \" apply (simp add: O5) done\n   have d:  \"\\<Union>{x,y} = x \\<union> y\"  apply blast done\n   from c d have e: \"x \\<union> y \\<in>  T\"  apply simp done\n   show ?thesis  apply  (blast intro :e)  done\nqed\n \nlemma (in topological_space) Un_T_in_T:\"\\<Union>T \\<in> T\"\napply (simp add:O5)\ndone\n\nlemma (in topological_space)  Un_T_eq_X [intro,simp] :\n    \"\\<Union> T =X \"\napply (subgoal_tac \"T \\<subseteq> Pow X\")\napply (subgoal_tac \"X \\<in> T\")\napply blast \napply simp+\ndone\n\ndefinition  trivial_topology :: \n  \"'a set \\<Rightarrow> 'a top\" \n      where\n  \"trivial_topology X = {{}, X} \"\n\nlemma trivial_is_top: \n    \"topological_space  X (trivial_topology X) \"\napply (rule topological_space.intro)\napply (simp add:trivial_topology_def)+\napply blast\napply (simp add:trivial_topology_def)\napply blast\ndone\n\ndefinition discrete_topology::\n   \"'a set \\<Rightarrow> 'a top\" \n        where\n   \"discrete_topology X = Pow X\"\n\nlemma discrete_is_top:\n    \"topological_space X (discrete_topology X)\"\napply (rule topological_space.intro)\napply (simp add:discrete_topology_def)+\napply blast\napply (simp add:discrete_topology_def)\napply blast\ndone\n\nlemma (in topological_space)dis_top_1: \n    \"\\<And>x.\\<lbrakk> x\\<in> X \\<Longrightarrow> {x} \\<in> T \\<rbrakk> \\<Longrightarrow>  T = discrete_topology X\"\napply (simp add:discrete_topology_def O3 O4 O5)\napply auto\ndone\n\ndefinition\n   finer ::\"'a top \\<Rightarrow> 'a top \\<Rightarrow> 'a set  \\<Rightarrow> bool \"\n      where\n   \"finer T2 T1 X  == topological_space X T1 \\<and>\n                      topological_space X T2 \\<and>\n                      T1  \\<subseteq> T2\"\n(*lemma \"\\<lbrakk> P ;Q\\<rbrakk> \\<Longrightarrow> P \\<and> Q\"*)\n\nlemma \"finer (discrete_topology X) (trivial_topology X) X \"\napply (simp add :finer_def)\napply (rule conjI)\napply (rule trivial_is_top)\napply (rule conjI)\napply(rule  discrete_is_top)\napply (simp add:trivial_topology_def discrete_topology_def)\ndone\n\nlemma \"\\<lbrakk> X ={a ,b} ; T ={{}, {a} ,X} \\<rbrakk> \\<Longrightarrow> topological_space X T\"\napply (simp add:topological_space_def)\napply blast\ndone\n\nthm finite_def\n\nlemma \"topological_space X ({A. A \\<subseteq> X \\<and> finite A } \\<union> {{}})\"\napply (simp add: topological_space_def)\napply (rule conjI)\napply blast\napply (rule conjI)\napply auto\ndone\n\nsection \"open set\"\n\ndefinition  (in topological_space)\n   open_set :: \" 'a set \\<Rightarrow>  bool\"  where\n  \"open_set s  \\<longleftrightarrow>  s \\<in> T\"\n\nlemma \"\\<lbrakk> topological_space X T; topological_space.open_set T s \\<rbrakk> \\<Longrightarrow>  (s \\<in> T)\"\napply (simp add: topological_space.open_set_def)\ndone\n\n\nlemma (in topological_space) openI:\n  \"m \\<in>  T \\<Longrightarrow> open_set m\"\napply (simp add: open_set_def)\ndone\n\nlemma (in topological_space) openE:\n  \"\\<lbrakk> open_set m; m \\<in>  T \\<Longrightarrow>  R \\<rbrakk>  \\<Longrightarrow>  R\" \napply  (auto simp: open_set_def)\ndone\n\nlemma (in topological_space) empty_is_open:\n   \"open_set {}\"\napply(simp add:open_set_def)\ndone\n\nlemma (in topological_space) X_is_open:\n  \"open_set X\"\napply (simp add:open_set_def)\ndone\n\nlemma (in topological_space) union_is_open :\n    \"\\<lbrakk> open_set A ;open_set B \\<rbrakk> \\<Longrightarrow>  open_set ( A \\<union> B)\"\napply (simp add:open_set_def)\ndone\n\nlemma (in topological_space) inter_is_open:\n   \"\\<lbrakk>open_set A ; open_set B \\<rbrakk> \\<Longrightarrow> open_set (A \\<inter> B)\"\napply (simp add:open_set_def)\ndone\n\nlemma (in topological_space) UN_is_open :\n   \"\\<forall>x \\<in> T'. open_set x  \\<Longrightarrow> open_set  (\\<Union> T') \"\napply (simp add:open_set_def)\napply (subgoal_tac \"T' \\<subseteq> T\")\napply simp\napply (simp add: subsetI)\ndone\n\nlemma (in topological_space)\n  \"[| ALL x : T'. open_set x  |] ==>  open_set ( Union T')\"\napply (simp add: open_set_def)\napply (subgoal_tac \"T' <= T\")\napply simp\napply (simp add: subsetI)\ndone\n\nlemma subset_pow [intro,simp] :\n     \"\\<lbrakk> T \\<subseteq> Pow X ; t \\<in> T ; x \\<in> t\\<rbrakk> \\<Longrightarrow> x \\<in> X \"\napply blast\ndone\n\nthm subsetI\nlemma (in topological_space) openE_in_X [intro,simp]:\n  \"\\<lbrakk> open_set t; x \\<in> t \\<rbrakk> \\<Longrightarrow> x \\<in> X\"\napply (subgoal_tac \"T \\<subseteq>   Pow X\" \"t \\<in> T\")\napply  blast\napply (simp add :open_set_def)+\ndone\n\nlemma (in topological_space) open_set_E [elim]:\n \"\\<lbrakk> x \\<in> X; \\<And>  t. \\<lbrakk>  open_set t; x \\<in>  t \\<rbrakk>  \\<Longrightarrow>  R\\<rbrakk>  \\<Longrightarrow>  R\"\napply (unfold open_set_def)\napply (insert O3)\napply blast\ndone\n\nlemma (in topological_space)\n \"[| x : X; !!  t. [|  open_set t; x :  t |]  ==>  R |]  ==> R\"\napply (unfold open_set_def)\napply (insert O3)\napply blast\ndone\nlemma (in topological_space) subE_is_open:\n  \"[|  t :  M; M <=  T |] ==> open_set t\"\n apply  (unfold open_set_def)\napply (rule_tac A=\"M\" in  set_mp)\napply assumption\napply assumption\ndone\n\nlemma (in topological_space) open_subset_I:\nassumes a1: \"open_set A\"\nshows \"A \\<subseteq> X\"\nproof-\n from a1 have s1:\"A \\<in> T\" by (simp add:open_set_def)\n from a1 show ?thesis using O1 by blast\nqed\n\nlemma (in topological_space) open_subset\n:\"open_set A \\<Longrightarrow> A \\<subseteq> X\"\napply (simp add:open_set_def )\napply (insert O1)\napply blast\ndone\n\n\n\nsection \"neighborhood\"\n\n\ndefinition (in topological_space) neighborhood :: \"'a set \\<Rightarrow> 'a  \\<Rightarrow> bool\"  where\n  \"neighborhood U x == U \\<subseteq> X \\<and> (\\<exists>V \\<in> T .x\\<in> V \\<and> V \\<subseteq> U)\"\n\ndefinition (in topological_space)open_neighborhood ::\"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"open_neighborhood  U x == x \\<in> U   \\<and> U \\<in> T\"\n\n(*definition (in topological_space)open_neighborhood ::\"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"open_neighborhood  U x ==( neighborhood U x) \\<and> U \\<in> T\"\n*)\nlemma (in topological_space) inT_subX: \"U \\<in> T \\<Longrightarrow> U \\<subseteq> X\"\n  apply (subgoal_tac \"T \\<subseteq> Pow X\")\n  apply (subgoal_tac \"U \\<in> Pow X\")\n  apply simp\n  apply blast\n  apply simp\ndone\nlemma exD:  \"\\<exists>x . x\\<in> T \\<and> P x \\<Longrightarrow> \\<exists>x\\<in>T . P x\"\napply  blast\ndone\n\nlemma  (in topological_space)  open_nb_is_nb:\n  \"open_neighborhood U x  \\<Longrightarrow> neighborhood U x \"\nthm bexI\nthm subset_refl\napply (simp add:open_neighborhood_def neighborhood_def)\napply (rule conjI)\napply (drule conjunct2)\n(*apply (drule_tac P=\"x \\<in> U \"  and  Q=\"U \\<in> T\"  in conjunct2*)\n  apply (subgoal_tac \"T \\<subseteq> Pow X\")\n  apply (subgoal_tac \"U \\<in> Pow X\")\n  apply simp\n  apply blast\n  apply simp\napply (rule exD)\napply (rule_tac x=\"U\" in exI)\napply (rule conjI)\napply (drule conjunct2)\napply assumption\napply (rule conjI)\napply (drule conjunct1)\napply (assumption)\napply simp\ndone\n\n\ndefinition (in topological_space) neighborhood_system :: \"'a \\<Rightarrow> 'a set set\" where\n  \"neighborhood_system x = { U. (neighborhood U x) }\"\ndefinition (in topological_space) open_neighborhood_system ::\"'a \\<Rightarrow> 'a set set\" where\n \"open_neighborhood_system x = {U. (open_neighborhood U x)}\"\n       \n(*from GaoGuoShi 8 page*)\nlemma (in topological_space) open_nbs_inc:\n\"U \\<in> ( open_neighborhood_system x) \\<Longrightarrow> U \\<in> (neighborhood_system x) \"\napply (unfold open_neighborhood_system_def) \napply (unfold neighborhood_system_def  ) \napply (simp add:open_nb_is_nb)\ndone\n\nlemma (in topological_space) open_nbs_intro:\n\"\\<forall>U \\<in> (neighborhood_system x). P U x \\<Longrightarrow> \\<forall>U\\<in> (open_neighborhood_system x). P U x\"\napply (insert open_nbs_inc)\napply simp\ndone\n\n\nlemma (in topological_space) X_in_nbs:\n  \"  x\\<in> X \\<Longrightarrow> X \\<in>  neighborhood_system x \"\napply ( simp add:neighborhood_system_def) \napply (simp add:neighborhood_def)\napply (insert O3)\n(*thm exI  ?P ?x \\<Longrightarrow> \\<exists>x. ?P x*)\napply (rule_tac x =\"X\"   in bexI)\napply (rule conjI)\napply assumption\napply (rule subset_refl)\napply assumption\ndone\n\nlemma (in topological_space) nbs_in:\n  \"A \\<in> neighborhood_system x \\<Longrightarrow> x \\<in> A\"\napply (simp add:neighborhood_system_def)\napply (simp add:neighborhood_def) \n(*apply (erule_tac P=\"A \\<subseteq> X\" and Q=\"\\<exists>V\\<in>T. x \\<in> V \\<and> V \\<subseteq> A\" in conjI*)\napply blast\ndone\n\nlemma (in topological_space) nbs_inter:\n     \"[| A : neighborhood_system x;\n         B : neighborhood_system x\n      |] ==>  A Int B : neighborhood_system x\"\n\nproof -\n  assume a1: \"A : neighborhood_system x\"\n    and  a2: \"B : neighborhood_system x\"\nfrom a1 have s1:\" A \\<in> T \"\n         apply (auto simp:neighborhood_system_def neighborhood_def)\n\napply (simp add:neighborhood_system_def)\napply (simp add:neighborhood_def) \napply (rule conjI)\napply (drule conjunct1 )\napply (drule conjunct1 )\napply (erule le_infI1)\napply (drule conjunct2)\napply (drule conjunct2)\napply (drule rev_bexI)\ndone\n\nlemma \n  (in topological_space) nbs_sub_in:\n  \"\\<lbrakk> A \\<in> neighborhood_system x; A \\<subseteq> B ; B \\<subseteq> X \\<rbrakk> \\<Longrightarrow> B \\<in> neighborhood_system x\"\napply (simp add:neighborhood_system_def)\napply (simp add: neighborhood_def)\ndone\n\n\nlemma (in topological_space) open_nb_ex  :\n  \"\\<lbrakk>open_set A ; x \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists>U. neighborhood U x \\<and> U \\<subseteq> A\"\napply (unfold neighborhood_def)\napply (unfold open_set_def)\napply (frule inT_subX)\napply auto\ndone\n\n(*  \\<lbrakk>A \\<subseteq> X; A \\<in> T; x \\<in> A\\<rbrakk> \\<Longrightarrow> \\<exists>U. (U \\<subseteq> X \\<and> (\\<exists>V\\<in>T. x \\<in> V \\<and> V \\<subseteq> U)) \\<and> U \\<subseteq> A *)\n\nlemma (in topological_space) open_nb_ex_a:\n  \"\\<lbrakk>open_set A \\<rbrakk> \\<Longrightarrow> \\<forall>x\\<in> A. \\<exists>U. neighborhood U x \\<and> U \\<subseteq> A  \"\napply (auto simp :open_nb_ex)\ndone\n\nlemma (in topological_space) nbs_open_ex:\n  \"\\<lbrakk>open_set A \\<rbrakk> \\<Longrightarrow> \\<forall>x\\<in> A. \\<exists>U\\<in>neighborhood_system x. U \\<subseteq> A  \"\napply (auto simp :open_nb_ex_a neighborhood_system_def)\ndone \n\nlemma (in topological_space)  x_in_nb :\n\"\\<lbrakk> x\\<in> X ; U \\<in> neighborhood_system x \\<rbrakk> \\<Longrightarrow> x \\<in> U \"\napply ( simp add:neighborhood_system_def) \napply (simp add:neighborhood_def)\napply blast\ndone\n\n\n\nsection \"closeed_set\"\n\ndefinition  (in topological_space)\n   closed_set :: \" 'a set \\<Rightarrow>  bool\"  where\n  \"closed_set s  \\<longleftrightarrow>  open_set (X - s) \\<and> s \\<subseteq> X\"\n\n(*\ndefinition (in topological_space) closed_set_system :: \"'a set set\" where\n  \"closed_set_system = { C. (closed_set C) }\"\n*)\n\nthm topological_space.closed_set_def\nlemma dis_all_is_open: \n    \"\\<And>x. x \\<subseteq> X \\<Longrightarrow> topological_space.open_set (discrete_topology X) x \n                \\<and>  topological_space.closed_set X (discrete_topology X) x\"\napply (insert discrete_is_top[of \"X\" ])\napply (unfold discrete_topology_def\n              topological_space.closed_set_def \n              topological_space.open_set_def)\napply (rule conjI)\napply (rule PowI)\nthm PowI\napply assumption\napply (rule conjI)\napply (rule_tac A =\"X - x\" in  PowI)\napply (rule Diff_subset)\napply assumption\n\ndone\n\nlemma dis_all_is_closed : \n   \"\\<And>x. x \\<subseteq> X \\<Longrightarrow> topological_space.closed_set X (discrete_topology X) x \"\napply (insert discrete_is_top[of \"X\" ])\napply (unfold discrete_topology_def \n              topological_space.closed_set_def\n              topological_space.open_set_def)\napply (rule conjI)\napply (rule_tac A =\"X - x\" in  PowI)\napply (rule Diff_subset)\napply assumption\ndone\n\n\nlemma  (in topological_space) close_sub_X:\n    \"\\<lbrakk> closed_set s\\<rbrakk> \\<Longrightarrow> s \\<subseteq> X\"\napply (simp add : closed_set_def open_set_def)\ndone\n\nlemma (in topological_space) empty_is_closed:\n  \"closed_set {}\"\napply (simp add:closed_set_def)\napply (simp add:open_set_def)\ndone\n\nlemma (in topological_space) X_is_closed:\n \"closed_set X\"\napply(simp add:closed_set_def) \napply(simp add:open_set_def)\ndone\n\nlemma (in topological_space) closed_Union:\n \"\\<lbrakk> closed_set A; closed_set B \\<rbrakk> \\<Longrightarrow> closed_set (A \\<union> B)\"\napply (simp add:closed_set_def)\napply (simp add:open_set_def)\napply (subst  Diff_Un)\napply (erule_tac P=\"X - A \\<in> T\" and Q =\" A \\<subseteq> X\" in  conjE)\napply (erule_tac P=\"X - B \\<in> T\" and Q =\" B \\<subseteq> X\" in  conjE)\napply simp\ndone\n\n(*definition (in topological_space)\n  closure :: \"' a set \\<Rightarrow> 'a set set \"\n    where\n  \"closure A \\<equiv> \\<Inter>{C. A \\<subseteq> C \\<and> closed_set C}\"\n*)\n\n\n(*\nlemma (in topological_space) \nassumes a1: \"open_set A\"\nshows \"A \\<in> neighborhood_system y \\<and>  y\\<in> A \\<and> A \\<subseteq> A\"\nproof-\n  from a1 have s1 :\"A \\<in> neighborhood_sytem y\" \n    apply (auto :open_set_def neighborhood_system_def neighborhood_def)\n\n    done\n\n\n\nlemma (in topological_space) \n   \"open_set A \\<Longrightarrow> A \\<in> neighborhood_system y \\<and>  y\\<in> A \\<and> A \\<subseteq> A\"\n\napply ( simp add:open_set_def neighborhood_system_def neighborhood_def)\napply \n*)\nlemma (in topological_space) \n   \"open_set A \\<Longrightarrow>\\<forall>y\\<in> A. \\<exists> B\\<in> neighborhood_system y. y\\<in> B \\<and> B \\<subseteq> A\"\napply (simp add:open_nb_ex_a nbs_in neighborhood_system_def)                                        \ndone\n\ndefinition (in topological_space)\n   cluster_point :: \" 'a \\<Rightarrow>'a set \\<Rightarrow> bool\"  where\n  \"cluster_point x A == A \\<subseteq> X  \\<and> x \\<in> X \\<and> (\\<forall>U\\<in> neighborhood_system  x.  U \\<inter> (A -{x}) \\<noteq> {}) \"\n\n\ndefinition (in topological_space)\n  derived_set :: \"'a set \\<Rightarrow> 'a set \" where\n  \"derived_set A == {x. (cluster_point x A)}\"\n\n(*lemma \"\\<lbrakk> P \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> P \\<longrightarrow> Q\"*)\n\nlemma (in topological_space) empty_mult_is_empty:\n  \"\\<forall>U\\<in>neighborhood_system x. U \\<inter> ({} - {x}) = {}\"\napply simp\ndone\n(*\nlemma (in topological_space) d_empty_is_empty:\n \"derived_set {} = {}\"\napply (unfold derived_set_def) \napply(unfold cluster_point_def)\napply(auto simp: empty_mult_is_empty)\napply (unfold neighborhood_system_def)\napply (unfold neighborhood_def)\napply auto\napply blast\napply *)\nlemma (in topological_space) closed_is_derived_pre:\nassumes a1:\"closed_set A\"\nand  a2:\"x\\<in> derived_set A\"\nshows \"x \\<in> A\"\n       proof-\n           have a0:\"x \\<notin> A\\<Longrightarrow>False\"\n        proof-\n          assume a3:\"x\\<notin> A\"\n          show \"False\"\n          proof-\n          from a2 have s2:\"A\\<subseteq> X\" by (auto simp:derived_set_def cluster_point_def)\n          from a2 have s3:\"x\\<in> X\" by (auto simp:derived_set_def cluster_point_def)\n          from a2 have s4:\"\\<forall>U\\<in> neighborhood_system  x.  U \\<inter> (A -{x}) \\<noteq> {}\"\n                by (auto simp:derived_set_def cluster_point_def)\n          from a3 s2 s3 have s5: \"x \\<in> X - A\" by blast\n          from a1 s2  have s6: \"open_set (X - A)\" by (simp add:closed_set_def)\n          from s6 have s7:  \"\\<forall>y\\<in> X -A. \\<exists> B\\<in> neighborhood_system y. y\\<in> B \\<and> B \\<subseteq> X - A \" \n                   by (simp add:open_nb_ex_a nbs_in neighborhood_system_def)      \n     \n          from s5 s7 have s8:\"\\<exists> B\\<in> neighborhood_system x. x\\<in> B \\<and> B \\<subseteq> X - A \" by auto\n          from s8  obtain B where  s9:\"B\\<in> neighborhood_system x\" and\n                                  s10:\"x\\<in> B\" and\n                                  s11:\"B\\<subseteq> X -A\" by blast\n          from s11 have s12: \"B \\<inter> A ={}\" by blast\n          from s12 have s13: \"B \\<inter>  (A -{x}) ={}\" by blast\n          from s4 s9 s13 have  s14 :\"False\" by auto\n          from a3 s14 show ?thesis by auto\nqed\nqed\nfrom a0  show ?thesis by auto\nqed\n\n\nlemma (in topological_space) closed_is_derived:\nassumes a1:\"closed_set A\"\nshows \"derived_set A \\<subseteq> A\" \n   proof-\n        from a1 have s0:\"\\<And> x. x \\<in> derived_set A \\<Longrightarrow> x \\<in> A \"  \n        proof-\n        fix x assume a2: \"x\\<in> derived_set A\"\n        show s1: \"x \\<in> A\"\n        proof-\n          from a1 a2 show ?thesis by (auto simp:closed_is_derived_pre)\nqed\nqed\nfrom s0 show ?thesis by auto\nqed\n\n\nlemma \" \\<forall> x\\<in>A. c\\<in> B \\<and> P A c x \\<Longrightarrow> \\<forall>x\\<in> A. \\<exists> a\\<in> B. P A a x \"\napply auto\ndone\n\nlemma (in topological_space)\n \"A \\<in> T \\<Longrightarrow> A \\<subseteq> X\"\napply (insert O1)\napply blast\ndone\n\n\nthm exI\nthm ballI\nthm ballE\n\nlemma all_Ex: \"\\<forall> x. P x \\<Longrightarrow> \\<exists> x. P x\"\napply blast\ndone\n(*\nlemma \"\\<exists>a\\<in> A. P a\"\napply (simp add:Pi)\ndone\nlemma all_ex_1:\nassumes a1: \"\\<forall>x \\<in>A. P x\"\nshows \"\\<exists>a\\<in> A. P a \"\nproof-\n fix x\n from a1 have s1:\"x\\<in> A \\<longrightarrow> P x\" by blast\n from s1 have s2: \"\\<exists>a\\<in> A. P a \" by blast\n\nlemma  \"\\<forall>x \\<in>A. P x \\<Longrightarrow> \\<exists>a\\<in> A. P a \"\napply (rule_tac  exI)\ndone\n*)\n(*\nlemma \"\\<forall>B \\<in> x. (C B x) \\<Longrightarrow>  B0 \\<in> x \\<and> (C B0 X)\"\napply blast\n*)\n\n\nlemma \"\\<exists>x\\<in>A. (\\<forall>B \\<in> x. (C B x)) \\<Longrightarrow> \\<exists>x. x\\<in> A \\<and> (\\<forall>B \\<in> x. (C B x))\"\napply blast\ndone\n\nlemma \"\\<lbrakk> \\<exists>x\\<in> A. x\\<notin> B \\<Longrightarrow> False \\<rbrakk> \\<Longrightarrow>  A \\<subseteq> B \"\napply blast\ndone\n(*\nlemma \"\\<lbrakk> \\<exists>x\\<in> A. \\<forall>B \\<in> (W x).  (F B x) \\<Longrightarrow> False \\<rbrakk> \\<Longrightarrow> \\<forall>x\\<in> A. \\<exists> B \\<in> (W x). \\<not>(F B X)\"\na\ndone*)\n(*\nlemma \"\\<lbrakk>\\<exists>x. x \\<in> A \\<and> (\\<forall>B. B \\<in> (W x) \\<and> (F B X))\\<Longrightarrow> False\\<rbrakk> \\<Longrightarrow> \\<forall> x. x \\<in> A \\<and> (\\<exists> B. B \\<in> (W x) \\<and>  \\<not>(F B X)) \"\napply blast\ndone\n\n\nlemma  \"\\<lbrakk> \\<exists> x\\<in> A. \\<forall> B\\<in> C. x \\<in> B \\<rbrakk> \\<Longrightarrow> \\<exists>x. \\<forall> B. x\\<in>A \\<and> B\\<in> C \\<and> x \\<in> B\"   \napply simp\napply blast\n*)\n\n(*\nlemma (in topological_space) derived_is_closed:\nassumes a1:\"derived_set A \\<subseteq> A\"\nshows \"closed_set A\"\nproof-\n  from a1 have s0:\"\\<exists> x\\<in> (X-A). \\<forall>B\\<in>(neighborhood_system x). B\\<inter> A \\<noteq> {} \\<Longrightarrow> False\"\n  proof-\n     assume a2:\"\\<exists> x\\<in> (X-A). (\\<forall>B\\<in>(neighborhood_system x). B\\<inter> A \\<noteq> {})\"\n     show \"False\"\n     proof-\n       from a2 have s1: \"\\<exists> x. x \\<in> (X-A)\\<and> (\\<forall>B\\<in>(neighborhood_system x). B\\<inter> A \\<noteq> {})\" apply auto done\n       from s1 obtain x where  s2:\" x \\<in> (X - A)\" and \n                          s3:\" \\<forall>B\\<in>(neighborhood_system x). B\\<inter> A \\<noteq> {}\" apply auto done\n       fix B from s3 have s4:\"B \\<in> (neighborhood_system x) \\<longrightarrow>  B\\<inter> A \\<noteq> {}\"\n              by blast \n       fix B from a2 have s1:\"\\<exists> x\\<in> (X-A). B\\<in>(neighborhood_system x) \\<and>  B\\<inter> A \\<noteq> {}\" by blast\n\n\nobtain x where s1:\"x \\<in> (X - A)\" \n                                 and s2:\"B \\<in> (neighborhood_system x)\"\n                                 and s3:\"B \\<inter> A \\<noteq> {}\"                    \n\napply   \n\"\\<lbrakk> derived_set A \\<subseteq> A  \\<rbrakk> \\<Longrightarrow> closed_set A \"\napply (unfold closed_set_def)\napply (unfold derived_set_def)\napply (unfold cluster_point_def)\napply (unfold neighborhood_def)\napply (unfold open_set_def)\napply  auto\napply(simp add:closed_set_def open_set_def neighborhood_def derived_set_def cluster_point_def)\napply blast\n\napply (auto simp:closed_set_def open_set_def neighborhood_def derived_set_def cluster_point_def)\n\n*)\n\n\nlemma  (in topological_space)\n  \"\\<forall> A\\<subseteq> X. closed_set (derived_set A) \\<Longrightarrow> \\<forall> x\\<in> X. closed_set (derived_set {x})\"\napply (auto simp :closed_set_def open_set_def derived_set_def)\ndone\n\n(*\nlemma  (in topological_space)\n  \"\\<forall> x\\<in> X. closed_set (derived_set {x})\\<Longrightarrow> \\<forall> A\\<subseteq> X. closed_set (derived_set A)\"\napply (simp add:closed_set_def open_set_def neighborhood_def derived_set_def cluster_point_def)\napply blast\ndone\n*)\n\n(*lemma in_exI: \"\\<lbrakk> a\\<in>A ; P a \\<rbrakk> \\<Longrightarrow> \\<exists>x\\<in>A. P x  \"*)\n\nlemma  bsubexI:\"\\<lbrakk> a \\<subseteq> A ; P a \\<rbrakk> \\<Longrightarrow>\\<exists>x\\<subseteq>A. P x \"\napply blast\ndone\n\nlemma \"\\<lbrakk> \\<forall>x. A x = B ;\\<forall>x. A x \\<noteq> B\\<rbrakk> \\<Longrightarrow> False\"\n\napply blast\ndone\n(*\nlemma \"\\<lbrakk> \\<forall>x\\<in> C. A x = B ;\\<forall>x\\<in> C. A x \\<noteq> B\\<rbrakk> \\<Longrightarrow> False\"\n*)\n\n(*\nHOL.contrapos_np: \\<lbrakk>\\<not> ?Q; \\<not> ?P \\<Longrightarrow> ?Q\\<rbrakk> \\<Longrightarrow> ?P\n  HOL.contrapos_pp: \\<lbrakk>?Q; \\<not> ?P \\<Longrightarrow> \\<not> ?Q\\<rbrakk> \\<Longrightarrow> ?P\n  HOL.notE: \\<lbrakk>\\<not> ?P; ?P\\<rbrakk> \\<Longrightarrow> ?R\n  HOL.notE': \\<lbrakk>\\<not> ?P; \\<not> ?P \\<Longrightarrow> ?P\\<rbrakk> \\<Longrightarrow> ?R\n  HOL.rev_notE: \\<lbrakk>?P; \\<not> ?R \\<Longrightarrow> \\<not> ?P\\<rbrakk> \\<Longrightarrow> ?R\n bexI \\<lbrakk>?P ?x; ?x \\<in> ?A\\<rbrakk> \\<Longrightarrow> \\<exists>x\\<in>?A. ?P x\n\n*)\n\nlemma (in topological_space) nbs_not_empty:\n\"\\<lbrakk> x\\<in> X\\<rbrakk> \\<Longrightarrow> neighborhood_system x \\<noteq> {}\"\napply(simp add: neighborhood_system_def neighborhood_def)\napply(rule_tac x=\"X\" in exI)\napply(rule conjI)\napply(simp)\napply(rule_tac x=\"X\" in bexI)\napply (rule conjI)\napply assumption\napply simp\napply simp\ndone\n\nlemma (in topological_space) open_nbs_not_empty:\n\"\\<lbrakk> x\\<in> X\\<rbrakk> \\<Longrightarrow> open_neighborhood_system x \\<noteq> {}\"\napply (simp add:open_neighborhood_system_def open_neighborhood_def neighborhood_def)\napply (rule_tac x=\"X\" in exI)\napply (rule conjI)\napply assumption\napply simp\ndone\n\nlemma (in topological_space) sp_notin_dset_pre:\nassumes a1: \"x \\<in>  derived_set {x}\"\nshows False\nproof-\n  from a1 have s1:\"{x} \\<subseteq> X\" by (simp add:derived_set_def cluster_point_def)\n  from a1 have s2:\"x\\<in> X\"  by (simp add:derived_set_def cluster_point_def)\n  from a1 have s3:\"\\<forall>U\\<in> neighborhood_system  x.  U \\<inter> ({x} -{x}) \\<noteq> {}\" \n       by (simp add:derived_set_def cluster_point_def)\n  have s4 : \"U \\<inter> ({x} - {x})={}\" by blast\n  from  s1 s3 s4 show ?thesis by (simp add:nbs_not_empty) \nqed\n\n\n\nlemma (in topological_space) sp_notin_dset:\n\"x \\<notin> derived_set {x}\"\napply (rule_tac Q=\"False\" in contrapos_np)\napply simp+\napply (rule_tac x=x in sp_notin_dset_pre)\napply assumption\ndone\n\nlemma all_in_ex :\"\\<lbrakk>  \\<forall> x\\<in>A. P x;  A \\<noteq> {}\\<rbrakk> \\<Longrightarrow> \\<exists> x\\<in> A. P x \"\napply blast\ndone\n\nlemma \"\\<forall>x. x\\<in>A \\<longrightarrow> P x \\<Longrightarrow> \\<forall> x\\<in> A. P x \" by auto\nlemma \" \\<forall> x\\<in> A. P x  \\<Longrightarrow> \\<forall>x. x\\<in>A \\<longrightarrow> P x\" by auto\n\nlemma  (in topological_space) nb_ex_onb:\n \"\\<lbrakk> U \\<in> neighborhood_system x \\<rbrakk> \\<Longrightarrow> \\<exists> U1. U1 \\<in> open_neighborhood_system x\"\napply (simp add:neighborhood_system_def open_neighborhood_system_def neighborhood_def open_neighborhood_def)\napply auto\ndone\nlemma (in topological_space) open_nbs:\n\"\\<lbrakk> open_set A; A \\<in> neighborhood_system x\\<rbrakk> \\<Longrightarrow>   A \\<in> open_neighborhood_system x\"\napply (simp add:open_neighborhood_system_def \n                neighborhood_system_def \n                open_neighborhood_def \n                neighborhood_def \n                closed_set_def \n                open_set_def)\napply blast\ndone\nlemma (in topological_space) open_nbs_o:\n\"\\<lbrakk>  U \\<in> open_neighborhood_system x \\<rbrakk> \\<Longrightarrow> open_set U\"\napply (simp add:open_neighborhood_system_def\n                neighborhood_def\n                open_neighborhood_def\n                open_set_def)\ndone\n\n(*  \\<lbrakk>A \\<in> T; A \\<subseteq> X; X - B \\<in> T; B \\<subseteq> X\\<rbrakk> \\<Longrightarrow> A - B \\<in> T *)\nlemma  subset_mui :\"\\<lbrakk> A \\<subseteq> X  ; B \\<subseteq> X\\<rbrakk> \\<Longrightarrow> (A - B) =  A \\<inter> (X - B)\"\napply blast\ndone\n\nlemma (in topological_space) open_mui_closed_is_open:\n\"\\<lbrakk> open_set A ; closed_set B\\<rbrakk> \\<Longrightarrow> open_set (A - B)\"\napply (frule_tac A=\"A\" in open_subset)\napply (simp add:open_set_def closed_set_def O4)\napply (subgoal_tac \"A-B = A \\<inter> (X - B)\")\napply (simp)\napply blast\ndone\n\nlemma (in topological_space) open_is_onb:\n\"\\<lbrakk> open_set A; x \\<in> A \\<rbrakk> \\<Longrightarrow>  A \\<in> open_neighborhood_system x\"\napply (simp add: open_neighborhood_system_def open_neighborhood_def open_set_def)\ndone\n\nlemma (in topological_space) onbs_in:\n\"A \\<in> open_neighborhood_system x \\<Longrightarrow> x \\<in> A\"\napply (simp add:open_neighborhood_system_def open_neighborhood_def)  \ndone\n\nlemma (in topological_space) obb_mui_closed_onb:\n\"\\<lbrakk> U \\<in> open_neighborhood_system x ; closed_set A;  x \\<notin> A \\<rbrakk> \\<Longrightarrow> U - A \\<in> open_neighborhood_system x\"\napply(frule open_nbs_o)\napply (frule_tac B=A in open_mui_closed_is_open)\napply assumption\napply (subgoal_tac \"x\\<in> (U - A)\")\napply (simp add: open_is_onb)\napply (simp add: onbs_in)\ndone\n\nlemma (in topological_space)\n YangChungTauTheorem:\nassumes a0:\"A \\<subseteq> X\"\n and a1: \" \\<forall> x\\<in> X. closed_set (derived_set {x})\"\nshows \"derived_set(derived_set A) \\<subseteq> derived_set A\"\nproof-\nfrom a1 have s1:\"\\<And>x. x \\<in> derived_set(derived_set A)\\<Longrightarrow> x \\<in> derived_set A\"\n proof-\n  fix x \n  assume a2:\"x \\<in> derived_set(derived_set A)\"\n  show \"x \\<in> derived_set A\"\n  proof-\n    from a2 have s1:\"derived_set A \\<subseteq> X\" by (simp add:derived_set_def cluster_point_def)\n    from a2 have s2:\"x\\<in> X\"  apply (simp add:derived_set_def cluster_point_def) done\n    from a2 have s3:\"\\<forall>U\\<in> neighborhood_system  x.  U \\<inter> ((derived_set A) -{x}) \\<noteq> {}\"  \n          by (simp add:derived_set_def cluster_point_def)\n    from s3 have s4:\"\\<forall>U\\<in> open_neighborhood_system  x.  U \\<inter> ((derived_set A) -{x}) \\<noteq> {}\"  \n      apply (drule_tac x=\"x\" and P=\"\\<lambda>UU.( \\<lambda>xx. ( UU \\<inter> ((derived_set A) -{xx}) \\<noteq> {}))\" in open_nbs_intro)\n    apply assumption done\n    have s5:\"\\<And> U. U\\<in> neighborhood_system x \\<Longrightarrow>  U \\<inter> (A -{x})\\<noteq> {}\" \n       proof-\n          fix U1\n          assume a3:\"U1\\<in> neighborhood_system  x\"\n          show \" U1 \\<inter> (A -{x})\\<noteq> {}\"\n    proof-\n    from a3 have s6:\"\\<exists>U . U\\<in> open_neighborhood_system  x\" apply (auto simp:nb_ex_onb) done\n    from s6  obtain U where s7:\"U\\<in> open_neighborhood_system  x\" apply auto done\n    from s7 s4 a3 have  s8:\" U \\<inter> ((derived_set A) -{x}) \\<noteq> {}\" by auto\n    let ?V = \"U - (derived_set {x})\"\n    from s2 have s9:\"?V \\<in> open_neighborhood_system x\" \n             apply (rule_tac A =\"(derived_set {x})\" in obb_mui_closed_onb) \n             apply (simp add:s7) \n             apply (simp add:a1)    \n             apply (simp add:sp_notin_dset) done\n    from s4 s9 have s10:\" ?V \\<inter> ((derived_set A) -{x}) \\<noteq> {}\" by blast\n    from s10 have s11: \"\\<exists>y. y\\<in> ?V \\<inter> ((derived_set A) -{x}) \" by auto\n    from s11 obtain y where s12: \"y\\<in> ?V\" and s13:\"y\\<in> ((derived_set A) -{x})\" by blast\n    from s12 s13 have s14:\"y\\<noteq> x\" by auto\n    from s12 s13 s14 have s15:\"y\\<notin> (derived_set {x}) \" by blast\n    from s2 have s16:\"{x}\\<subseteq> X\" by blast\n    from s2 s3 s15 s16 have s17:\"\\<exists>W \\<in> open_neighborhood_system x. W \\<inter> ({x}-{y})= {}\"  by auto\n    from s17 s14 obtain W where s18:\"W \\<in> open_neighborhood_system x\" and s19:\" W \\<inter> {x}= {}\" by auto\n    from s19 have s20:\"x\\<notin> W\" by blast\n    from s18 s9 have s21:\"W \\<inter> ?V  \\<in> (open_neighborhood_system y)\" by auto\n    from s21 have s22:\"W \\<inter> ?V  \\<in> (neighborhood_system y)\" sorry\n    from s13 s14 have s23:\"y\\<in> derived_set A\" by auto\n    from s23 have s24:\"\\<forall>K\\<in> neighborhood_system  y.  K \\<inter> (A -{y}) \\<noteq> {}\" \n         by (auto simp:derived_set_def cluster_point_def)\n    from s22 s24 have s25:\"(W \\<inter> ?V ) \\<inter> (A -{y}) \\<noteq> {}\" by blast\n    from s25 have s26: \"\\<exists>t. t\\<in> (W \\<inter> ?V ) \\<inter> (A -{y}) \" by auto\n    from s26 obtain t where  s27:\" t\\<in> (W \\<inter> ?V ) \\<inter> (A -{y})\" by auto\n    from s27 have s28:\"t\\<in> W\" by auto\n    from s27 s20 have s29:\"t\\<noteq> x\" by auto\n    from s29 s27 s20 have s30:\"t\\<in> U \\<inter> (A -{x})\" by auto\n    from s30 have s31:\"U\\<inter> (A - {x})\\<noteq> {}\" by auto\n    from s31 show ?thesis ..\nqed\nqed\n    from s5 a0  s2 show ?thesis by (simp add:derived_set_def cluster_point_def)\nqed\n\\<and>\nqed\n    show ?thesis by auto\nqed\n\n\ndefinition (in topological_space)\n   base :: \" 'a set set \\<Rightarrow> bool\"  where\n  \"base S == S \\<subseteq> T  \\<and> ( \\<forall>x\\<in>T. \\<exists> F \\<subseteq> S. \\<Union>F = x )\" \n\n\n(*\nlemma (in topology) base_inter[intro,simp]:\n   \"\\<lbrakk> base S ; U1 \\<in> S; U2\\<in> S ; x \\<in> U1 \\<inter> U2 \\<rbrakk> \\<longrightarrow> \\<exists> U3\\<in> S. ( (x\\<in> U3) \\<and> (U3 \\<subseteq>  U1 \\<inter> U2))\"\n*)\ndefinition(in topological_space)\n  neighborhood_base :: \"'a set set \\<Rightarrow> 'a \\<Rightarrow> bool\"  where\n  \"neighborhood_base NB x ==( NB \\<subseteq> (neighborhood_system x )) \\<and> \n      ( \\<forall>U \\<in> (neighborhood_system x). \\<exists>V\\<in> NB. ((x \\<in> V) \\<and> (V \\<subseteq> U))) \"\n\n\ndefinition (in topological_space)\n  interior :: \"'a set => 'a set \" where\n  \"interior A = Union {a. (A <= X & open_set a & A <= a)}\"\n\ndefinition (in topological_space)\n  closure :: \"'a set \\<Rightarrow> 'a set \" where\n  \"closure A = Inter {c. (A \\<subseteq> X \\<and> closed_set c  \\<and> A \\<subseteq>  c) }\"\n\nlemma (in topological_space) open_set_10: \n    \"{a \\<in> T. A \\<subseteq> a} \\<subseteq> T\"\napply blast\ndone\nlemma  (in topological_space) \n  \"A \\<subseteq> X \\<Longrightarrow> open_set (interior A)\"\napply (simp add:open_set_def)\napply (simp add:interior_def)\napply (simp add:open_set_def)\napply (rule O5)\napply (rule open_set_10 )\ndone\n\n(*lemma (in topological_space) \n  \"\\<lbrakk>U \\<subseteq> X ;U \\<in> T; U \\<subseteq> A\\<rbrakk> \\<Longrightarrow> U \\<subseteq> \\<Union>{a. A \\<subseteq> X \\<and> a \\<in> T \\<and> A \\<subseteq> a}\"\napply auto\ndone*)\n\nlemma  (in topological_space) closure_is_closed:\n       \"[| open_set U ;  U <= B |] \n        ==>  U <= interior B\"\napply (unfold interior_def)\napply (unfold open_set_def)\napply auto\ndone\n\n\n\nlemma (in topological_space)\n    \"[| open_set U ; closed_set C |] ==> open_set (U -C)\"\napply (simp add:open_set_def closed_set_def)\napply done\ndone\n\nlemma (in topological_space)\n    \"[| open_set U ; closed_set C |] ==> closed_set (C -U)\"\napply (simp add:open_set_def closed_set_def)\napply blast\ndone\n\n\n\n\nend \n", "meta": {"author": "JianlinWang", "repo": "topology", "sha": "843567e1368d8c9e912e4395b3679ec8ae0b21b7", "save_path": "github-repos/isabelle/JianlinWang-topology", "path": "github-repos/isabelle/JianlinWang-topology/topology-843567e1368d8c9e912e4395b3679ec8ae0b21b7/topological_space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7769811951593986}}
{"text": "(*  Title:      HOL/Metis_Examples/Binary_Tree.thy\n    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory\n    Author:     Jasmin Blanchette, TU Muenchen\n\nMetis example featuring binary trees.\n*)\n\nsection \\<open>Metis Example Featuring Binary Trees\\<close>\n\ntheory Binary_Tree\nimports MainRLT\nbegin\n\ndeclare [[metis_new_skolem]]\n\ndatatype 'a bt =\n    Lf\n  | Br 'a  \"'a bt\"  \"'a bt\"\n\nprimrec n_nodes :: \"'a bt => nat\" where\n  \"n_nodes Lf = 0\"\n| \"n_nodes (Br a t1 t2) = Suc (n_nodes t1 + n_nodes t2)\"\n\nprimrec n_leaves :: \"'a bt => nat\" where\n  \"n_leaves Lf = Suc 0\"\n| \"n_leaves (Br a t1 t2) = n_leaves t1 + n_leaves t2\"\n\nprimrec depth :: \"'a bt => nat\" where\n  \"depth Lf = 0\"\n| \"depth (Br a t1 t2) = Suc (max (depth t1) (depth t2))\"\n\nprimrec reflect :: \"'a bt => 'a bt\" where\n  \"reflect Lf = Lf\"\n| \"reflect (Br a t1 t2) = Br a (reflect t2) (reflect t1)\"\n\nprimrec bt_map :: \"('a => 'b) => ('a bt => 'b bt)\" where\n  \"bt_map f Lf = Lf\"\n| \"bt_map f (Br a t1 t2) = Br (f a) (bt_map f t1) (bt_map f t2)\"\n\nprimrec preorder :: \"'a bt => 'a list\" where\n  \"preorder Lf = []\"\n| \"preorder (Br a t1 t2) = [a] @ (preorder t1) @ (preorder t2)\"\n\nprimrec inorder :: \"'a bt => 'a list\" where\n  \"inorder Lf = []\"\n| \"inorder (Br a t1 t2) = (inorder t1) @ [a] @ (inorder t2)\"\n\nprimrec postorder :: \"'a bt => 'a list\" where\n  \"postorder Lf = []\"\n| \"postorder (Br a t1 t2) = (postorder t1) @ (postorder t2) @ [a]\"\n\nprimrec append :: \"'a bt => 'a bt => 'a bt\" where\n  \"append Lf t = t\"\n| \"append (Br a t1 t2) t = Br a (append t1 t) (append t2 t)\"\n\ntext \\<open>\\medskip BT simplification\\<close>\n\nlemma n_leaves_reflect: \"n_leaves (reflect t) = n_leaves t\"\nproof (induct t)\n  case Lf thus ?case\n  proof -\n    let \"?p\\<^sub>1 x\\<^sub>1\" = \"x\\<^sub>1 \\<noteq> n_leaves (reflect (Lf::'a bt))\"\n    have \"\\<not> ?p\\<^sub>1 (Suc 0)\" by (metis reflect.simps(1) n_leaves.simps(1))\n    hence \"\\<not> ?p\\<^sub>1 (n_leaves (Lf::'a bt))\" by (metis n_leaves.simps(1))\n    thus \"n_leaves (reflect (Lf::'a bt)) = n_leaves (Lf::'a bt)\" by metis\n  qed\nnext\n  case (Br a t1 t2) thus ?case\n    by (metis n_leaves.simps(2) add.commute reflect.simps(2))\nqed\n\nlemma n_nodes_reflect: \"n_nodes (reflect t) = n_nodes t\"\nproof (induct t)\n  case Lf thus ?case by (metis reflect.simps(1))\nnext\n  case (Br a t1 t2) thus ?case\n    by (metis add.commute n_nodes.simps(2) reflect.simps(2))\nqed\n\nlemma depth_reflect: \"depth (reflect t) = depth t\"\napply (induct t)\n apply (metis depth.simps(1) reflect.simps(1))\nby (metis depth.simps(2) max.commute reflect.simps(2))\n\ntext \\<open>\nThe famous relationship between the numbers of leaves and nodes.\n\\<close>\n\nlemma n_leaves_nodes: \"n_leaves t = Suc (n_nodes t)\"\napply (induct t)\n apply (metis n_leaves.simps(1) n_nodes.simps(1))\nby auto\n\nlemma reflect_reflect_ident: \"reflect (reflect t) = t\"\napply (induct t)\n apply (metis reflect.simps(1))\nproof -\n  fix a :: 'a and t1 :: \"'a bt\" and t2 :: \"'a bt\"\n  assume A1: \"reflect (reflect t1) = t1\"\n  assume A2: \"reflect (reflect t2) = t2\"\n  have \"\\<And>V U. reflect (Br U V (reflect t1)) = Br U t1 (reflect V)\"\n    using A1 by (metis reflect.simps(2))\n  hence \"\\<And>V U. Br U t1 (reflect (reflect V)) = reflect (reflect (Br U t1 V))\"\n    by (metis reflect.simps(2))\n  hence \"\\<And>U. reflect (reflect (Br U t1 t2)) = Br U t1 t2\"\n    using A2 by metis\n  thus \"reflect (reflect (Br a t1 t2)) = Br a t1 t2\" by blast\nqed\n\nlemma bt_map_ident: \"bt_map (%x. x) = (%y. y)\"\napply (rule ext)\napply (induct_tac y)\n apply (metis bt_map.simps(1))\nby (metis bt_map.simps(2))\n\nlemma bt_map_append: \"bt_map f (append t u) = append (bt_map f t) (bt_map f u)\"\napply (induct t)\n apply (metis append.simps(1) bt_map.simps(1))\nby (metis append.simps(2) bt_map.simps(2))\n\nlemma bt_map_compose: \"bt_map (f o g) t = bt_map f (bt_map g t)\"\napply (induct t)\n apply (metis bt_map.simps(1))\nby (metis bt_map.simps(2) o_eq_dest_lhs)\n\nlemma bt_map_reflect: \"bt_map f (reflect t) = reflect (bt_map f t)\"\napply (induct t)\n apply (metis bt_map.simps(1) reflect.simps(1))\nby (metis bt_map.simps(2) reflect.simps(2))\n\nlemma preorder_bt_map: \"preorder (bt_map f t) = map f (preorder t)\"\napply (induct t)\n apply (metis bt_map.simps(1) list.map(1) preorder.simps(1))\nby simp\n\nlemma inorder_bt_map: \"inorder (bt_map f t) = map f (inorder t)\"\nproof (induct t)\n  case Lf thus ?case\n  proof -\n    have \"map f [] = []\" by (metis list.map(1))\n    hence \"map f [] = inorder Lf\" by (metis inorder.simps(1))\n    hence \"inorder (bt_map f Lf) = map f []\" by (metis bt_map.simps(1))\n    thus \"inorder (bt_map f Lf) = map f (inorder Lf)\" by (metis inorder.simps(1))\n  qed\nnext\n  case (Br a t1 t2) thus ?case by simp\nqed\n\nlemma postorder_bt_map: \"postorder (bt_map f t) = map f (postorder t)\"\napply (induct t)\n apply (metis Nil_is_map_conv bt_map.simps(1) postorder.simps(1))\nby simp\n\nlemma depth_bt_map [simp]: \"depth (bt_map f t) = depth t\"\napply (induct t)\n apply (metis bt_map.simps(1) depth.simps(1))\nby simp\n\nlemma n_leaves_bt_map [simp]: \"n_leaves (bt_map f t) = n_leaves t\"\napply (induct t)\n apply (metis bt_map.simps(1) n_leaves.simps(1))\nproof -\n  fix a :: 'b and t1 :: \"'b bt\" and t2 :: \"'b bt\"\n  assume A1: \"n_leaves (bt_map f t1) = n_leaves t1\"\n  assume A2: \"n_leaves (bt_map f t2) = n_leaves t2\"\n  have \"\\<And>V U. n_leaves (Br U (bt_map f t1) V) = n_leaves t1 + n_leaves V\"\n    using A1 by (metis n_leaves.simps(2))\n  hence \"\\<And>V U. n_leaves (bt_map f (Br U t1 V)) = n_leaves t1 + n_leaves (bt_map f V)\"\n    by (metis bt_map.simps(2))\n  hence F1: \"\\<And>U. n_leaves (bt_map f (Br U t1 t2)) = n_leaves t1 + n_leaves t2\"\n    using A2 by metis\n  have \"n_leaves t1 + n_leaves t2 = n_leaves (Br a t1 t2)\"\n    by (metis n_leaves.simps(2))\n  thus \"n_leaves (bt_map f (Br a t1 t2)) = n_leaves (Br a t1 t2)\"\n    using F1 by metis\nqed\n\nlemma preorder_reflect: \"preorder (reflect t) = rev (postorder t)\"\napply (induct t)\n apply (metis Nil_is_rev_conv postorder.simps(1) preorder.simps(1)\n              reflect.simps(1))\napply simp\ndone\n\nlemma inorder_reflect: \"inorder (reflect t) = rev (inorder t)\"\napply (induct t)\n apply (metis Nil_is_rev_conv inorder.simps(1) reflect.simps(1))\nby simp\n(* Slow:\nby (metis append.simps(1) append_eq_append_conv2 inorder.simps(2)\n          reflect.simps(2) rev.simps(2) rev_append)\n*)\n\nlemma postorder_reflect: \"postorder (reflect t) = rev (preorder t)\"\napply (induct t)\n apply (metis Nil_is_rev_conv postorder.simps(1) preorder.simps(1)\n              reflect.simps(1))\nby (metis preorder_reflect reflect_reflect_ident rev_swap)\n\ntext \\<open>\nAnalogues of the standard properties of the append function for lists.\n\\<close>\n\nlemma append_assoc [simp]: \"append (append t1 t2) t3 = append t1 (append t2 t3)\"\napply (induct t1)\n apply (metis append.simps(1))\nby (metis append.simps(2))\n\nlemma append_Lf2 [simp]: \"append t Lf = t\"\napply (induct t)\n apply (metis append.simps(1))\nby (metis append.simps(2))\n\ndeclare max_add_distrib_left [simp]\n\nlemma depth_append [simp]: \"depth (append t1 t2) = depth t1 + depth t2\"\napply (induct t1)\n apply (metis append.simps(1) depth.simps(1) plus_nat.simps(1))\nby simp\n\nlemma n_leaves_append [simp]:\n     \"n_leaves (append t1 t2) = n_leaves t1 * n_leaves t2\"\napply (induct t1)\n apply (metis append.simps(1) n_leaves.simps(1) nat_mult_1 plus_nat.simps(1)\n              Suc_eq_plus1)\nby (simp add: distrib_right)\n\nlemma (*bt_map_append:*)\n     \"bt_map f (append t1 t2) = append (bt_map f t1) (bt_map f t2)\"\napply (induct t1)\n apply (metis append.simps(1) bt_map.simps(1))\nby (metis bt_map_append)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Metis_Examples/Binary_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8887587831798665, "lm_q1q2_score": 0.7768438111843524}}
{"text": "(*  Title:      HOL/Finite_Set.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n    Author:     Andrei Popescu\n*)\n\nsection \\<open>Finite sets\\<close>\n\ntheory Finite_Set\n  imports Product_Type Sum_Type Fields\nbegin\n\nsubsection \\<open>Predicate for finite sets\\<close>\n\ncontext notes [[inductive_internals]]\nbegin\n\ninductive finite :: \"'a set \\<Rightarrow> bool\"\n  where\n    emptyI [simp, intro!]: \"finite {}\"\n  | insertI [simp, intro!]: \"finite A \\<Longrightarrow> finite (insert a A)\"\n\nend\n\nsimproc_setup finite_Collect (\"finite (Collect P)\") = \\<open>K Set_Comprehension_Pointfree.simproc\\<close>\n\ndeclare [[simproc del: finite_Collect]]\n\nlemma finite_induct [case_names empty insert, induct set: finite]:\n  \\<comment> \\<open>Discharging \\<open>x \\<notin> F\\<close> entails extra work.\\<close>\n  assumes \"finite F\"\n  assumes \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\n  using \\<open>finite F\\<close>\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume F: \"finite F\" and P: \"P F\"\n  show \"P (insert x F)\"\n  proof cases\n    assume \"x \\<in> F\"\n    then have \"insert x F = F\" by (rule insert_absorb)\n    with P show ?thesis by (simp only:)\n  next\n    assume \"x \\<notin> F\"\n    from F this P show ?thesis by (rule insert)\n  qed\nqed\n\nlemma infinite_finite_induct [case_names infinite empty insert]:\n  assumes infinite: \"\\<And>A. \\<not> finite A \\<Longrightarrow> P A\"\n    and empty: \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P A\"\nproof (cases \"finite A\")\n  case False\n  with infinite show ?thesis .\nnext\n  case True\n  then show ?thesis by (induct A) (fact empty insert)+\nqed\n\n\nsubsubsection \\<open>Choice principles\\<close>\n\nlemma ex_new_if_finite: \\<comment> \"does not depend on def of finite at all\"\n  assumes \"\\<not> finite (UNIV :: 'a set)\" and \"finite A\"\n  shows \"\\<exists>a::'a. a \\<notin> A\"\nproof -\n  from assms have \"A \\<noteq> UNIV\" by blast\n  then show ?thesis by blast\nqed\n\ntext \\<open>A finite choice principle. Does not need the SOME choice operator.\\<close>\n\nlemma finite_set_choice: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. \\<exists>y. P x y \\<Longrightarrow> \\<exists>f. \\<forall>x\\<in>A. P x (f x)\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then obtain f b where f: \"\\<forall>x\\<in>A. P x (f x)\" and ab: \"P a b\"\n    by auto\n  show ?case (is \"\\<exists>f. ?P f\")\n  proof\n    show \"?P (\\<lambda>x. if x = a then b else f x)\"\n      using f ab by auto\n  qed\nqed\n\n\nsubsubsection \\<open>Finite sets are the images of initial segments of natural numbers\\<close>\n\nlemma finite_imp_nat_seg_image_inj_on:\n  assumes \"finite A\"\n  shows \"\\<exists>(n::nat) f. A = f ` {i. i < n} \\<and> inj_on f {i. i < n}\"\n  using assms\nproof induct\n  case empty\n  show ?case\n  proof\n    show \"\\<exists>f. {} = f ` {i::nat. i < 0} \\<and> inj_on f {i. i < 0}\"\n      by simp\n  qed\nnext\n  case (insert a A)\n  have notinA: \"a \\<notin> A\" by fact\n  from insert.hyps obtain n f where \"A = f ` {i::nat. i < n}\" \"inj_on f {i. i < n}\"\n    by blast\n  then have \"insert a A = f(n:=a) ` {i. i < Suc n}\" and \"inj_on (f(n:=a)) {i. i < Suc n}\"\n    using notinA by (auto simp add: image_def Ball_def inj_on_def less_Suc_eq)\n  then show ?case by blast\nqed\n\nlemma nat_seg_image_imp_finite: \"A = f ` {i::nat. i < n} \\<Longrightarrow> finite A\"\nproof (induct n arbitrary: A)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  let ?B = \"f ` {i. i < n}\"\n  have finB: \"finite ?B\" by (rule Suc.hyps[OF refl])\n  show ?case\n  proof (cases \"\\<exists>k<n. f n = f k\")\n    case True\n    then have \"A = ?B\"\n      using Suc.prems by (auto simp:less_Suc_eq)\n    then show ?thesis\n      using finB by simp\n  next\n    case False\n    then have \"A = insert (f n) ?B\"\n      using Suc.prems by (auto simp:less_Suc_eq)\n    then show ?thesis using finB by simp\n  qed\nqed\n\nlemma finite_conv_nat_seg_image: \"finite A \\<longleftrightarrow> (\\<exists>n f. A = f ` {i::nat. i < n})\"\n  by (blast intro: nat_seg_image_imp_finite dest: finite_imp_nat_seg_image_inj_on)\n\nlemma finite_imp_inj_to_nat_seg:\n  assumes \"finite A\"\n  shows \"\\<exists>f n. f ` A = {i::nat. i < n} \\<and> inj_on f A\"\nproof -\n  from finite_imp_nat_seg_image_inj_on [OF \\<open>finite A\\<close>]\n  obtain f and n :: nat where bij: \"bij_betw f {i. i<n} A\"\n    by (auto simp: bij_betw_def)\n  let ?f = \"the_inv_into {i. i<n} f\"\n  have \"inj_on ?f A \\<and> ?f ` A = {i. i<n}\"\n    by (fold bij_betw_def) (rule bij_betw_the_inv_into[OF bij])\n  then show ?thesis by blast\nqed\n\nlemma finite_Collect_less_nat [iff]: \"finite {n::nat. n < k}\"\n  by (fastforce simp: finite_conv_nat_seg_image)\n\nlemma finite_Collect_le_nat [iff]: \"finite {n::nat. n \\<le> k}\"\n  by (simp add: le_eq_less_or_eq Collect_disj_eq)\n\n\nsubsubsection \\<open>Finiteness and common set operations\\<close>\n\nlemma rev_finite_subset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> finite A\"\nproof (induct arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F A)\n  have A: \"A \\<subseteq> insert x F\" and r: \"A - {x} \\<subseteq> F \\<Longrightarrow> finite (A - {x})\"\n    by fact+\n  show \"finite A\"\n  proof cases\n    assume x: \"x \\<in> A\"\n    with A have \"A - {x} \\<subseteq> F\" by (simp add: subset_insert_iff)\n    with r have \"finite (A - {x})\" .\n    then have \"finite (insert x (A - {x}))\" ..\n    also have \"insert x (A - {x}) = A\"\n      using x by (rule insert_Diff)\n    finally show ?thesis .\n  next\n    show ?thesis when \"A \\<subseteq> F\"\n      using that by fact\n    assume \"x \\<notin> A\"\n    with A show \"A \\<subseteq> F\"\n      by (simp add: subset_insert_iff)\n  qed\nqed\n\nlemma finite_subset: \"A \\<subseteq> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  by (rule rev_finite_subset)\n\nlemma finite_UnI:\n  assumes \"finite F\" and \"finite G\"\n  shows \"finite (F \\<union> G)\"\n  using assms by induct simp_all\n\nlemma finite_Un [iff]: \"finite (F \\<union> G) \\<longleftrightarrow> finite F \\<and> finite G\"\n  by (blast intro: finite_UnI finite_subset [of _ \"F \\<union> G\"])\n\nlemma finite_insert [simp]: \"finite (insert a A) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite {a} \\<and> finite A \\<longleftrightarrow> finite A\" by simp\n  then have \"finite ({a} \\<union> A) \\<longleftrightarrow> finite A\" by (simp only: finite_Un)\n  then show ?thesis by simp\nqed\n\nlemma finite_Int [simp, intro]: \"finite F \\<or> finite G \\<Longrightarrow> finite (F \\<inter> G)\"\n  by (blast intro: finite_subset)\n\nlemma finite_Collect_conjI [simp, intro]:\n  \"finite {x. P x} \\<or> finite {x. Q x} \\<Longrightarrow> finite {x. P x \\<and> Q x}\"\n  by (simp add: Collect_conj_eq)\n\nlemma finite_Collect_disjI [simp]:\n  \"finite {x. P x \\<or> Q x} \\<longleftrightarrow> finite {x. P x} \\<and> finite {x. Q x}\"\n  by (simp add: Collect_disj_eq)\n\nlemma finite_Diff [simp, intro]: \"finite A \\<Longrightarrow> finite (A - B)\"\n  by (rule finite_subset, rule Diff_subset)\n\nlemma finite_Diff2 [simp]:\n  assumes \"finite B\"\n  shows \"finite (A - B) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite A \\<longleftrightarrow> finite ((A - B) \\<union> (A \\<inter> B))\"\n    by (simp add: Un_Diff_Int)\n  also have \"\\<dots> \\<longleftrightarrow> finite (A - B)\"\n    using \\<open>finite B\\<close> by simp\n  finally show ?thesis ..\nqed\n\nlemma finite_Diff_insert [iff]: \"finite (A - insert a B) \\<longleftrightarrow> finite (A - B)\"\nproof -\n  have \"finite (A - B) \\<longleftrightarrow> finite (A - B - {a})\" by simp\n  moreover have \"A - insert a B = A - B - {a}\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma finite_compl [simp]:\n  \"finite (A :: 'a set) \\<Longrightarrow> finite (- A) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Compl_eq_Diff_UNIV)\n\nlemma finite_Collect_not [simp]:\n  \"finite {x :: 'a. P x} \\<Longrightarrow> finite {x. \\<not> P x} \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Collect_neg_eq)\n\nlemma finite_Union [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>M. M \\<in> A \\<Longrightarrow> finite M) \\<Longrightarrow> finite (\\<Union>A)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN_I [intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (\\<Union>a\\<in>A. B a)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN [simp]: \"finite A \\<Longrightarrow> finite (UNION A B) \\<longleftrightarrow> (\\<forall>x\\<in>A. finite (B x))\"\n  by (blast intro: finite_subset)\n\nlemma finite_Inter [intro]: \"\\<exists>A\\<in>M. finite A \\<Longrightarrow> finite (\\<Inter>M)\"\n  by (blast intro: Inter_lower finite_subset)\n\nlemma finite_INT [intro]: \"\\<exists>x\\<in>I. finite (A x) \\<Longrightarrow> finite (\\<Inter>x\\<in>I. A x)\"\n  by (blast intro: INT_lower finite_subset)\n\nlemma finite_imageI [simp, intro]: \"finite F \\<Longrightarrow> finite (h ` F)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_image_set [simp]: \"finite {x. P x} \\<Longrightarrow> finite {f x |x. P x}\"\n  by (simp add: image_Collect [symmetric])\n\nlemma finite_image_set2:\n  \"finite {x. P x} \\<Longrightarrow> finite {y. Q y} \\<Longrightarrow> finite {f x y |x y. P x \\<and> Q y}\"\n  by (rule finite_subset [where B = \"\\<Union>x \\<in> {x. P x}. \\<Union>y \\<in> {y. Q y}. {f x y}\"]) auto\n\nlemma finite_imageD:\n  assumes \"finite (f ` A)\" and \"inj_on f A\"\n  shows \"finite A\"\n  using assms\nproof (induct \"f ` A\" arbitrary: A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x B)\n  then have B_A: \"insert x B = f ` A\"\n    by simp\n  then obtain y where \"x = f y\" and \"y \\<in> A\"\n    by blast\n  from B_A \\<open>x \\<notin> B\\<close> have \"B = f ` A - {x}\"\n    by blast\n  with B_A \\<open>x \\<notin> B\\<close> \\<open>x = f y\\<close> \\<open>inj_on f A\\<close> \\<open>y \\<in> A\\<close> have \"B = f ` (A - {y})\"\n    by (simp add: inj_on_image_set_diff Set.Diff_subset)\n  moreover from \\<open>inj_on f A\\<close> have \"inj_on f (A - {y})\"\n    by (rule inj_on_diff)\n  ultimately have \"finite (A - {y})\"\n    by (rule insert.hyps)\n  then show \"finite A\"\n    by simp\nqed\n\nlemma finite_image_iff: \"inj_on f A \\<Longrightarrow> finite (f ` A) \\<longleftrightarrow> finite A\"\n  using finite_imageD by blast\n\nlemma finite_surj: \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> finite B\"\n  by (erule finite_subset) (rule finite_imageI)\n\nlemma finite_range_imageI: \"finite (range g) \\<Longrightarrow> finite (range (\\<lambda>x. f (g x)))\"\n  by (drule finite_imageI) (simp add: range_composition)\n\nlemma finite_subset_image:\n  assumes \"finite B\"\n  shows \"B \\<subseteq> f ` A \\<Longrightarrow> \\<exists>C\\<subseteq>A. finite C \\<and> B = f ` C\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (clarsimp simp del: image_insert simp add: image_insert [symmetric]) blast  (* slow *)\nqed\n\nlemma finite_vimage_IntI: \"finite F \\<Longrightarrow> inj_on h A \\<Longrightarrow> finite (h -` F \\<inter> A)\"\n  apply (induct rule: finite_induct)\n   apply simp_all\n  apply (subst vimage_insert)\n  apply (simp add: finite_subset [OF inj_on_vimage_singleton] Int_Un_distrib2)\n  done\n\nlemma finite_finite_vimage_IntI:\n  assumes \"finite F\"\n    and \"\\<And>y. y \\<in> F \\<Longrightarrow> finite ((h -` {y}) \\<inter> A)\"\n  shows \"finite (h -` F \\<inter> A)\"\nproof -\n  have *: \"h -` F \\<inter> A = (\\<Union> y\\<in>F. (h -` {y}) \\<inter> A)\"\n    by blast\n  show ?thesis\n    by (simp only: * assms finite_UN_I)\nqed\n\nlemma finite_vimageI: \"finite F \\<Longrightarrow> inj h \\<Longrightarrow> finite (h -` F)\"\n  using finite_vimage_IntI[of F h UNIV] by auto\n\nlemma finite_vimageD': \"finite (f -` A) \\<Longrightarrow> A \\<subseteq> range f \\<Longrightarrow> finite A\"\n  by (auto simp add: subset_image_iff intro: finite_subset[rotated])\n\nlemma finite_vimageD: \"finite (h -` F) \\<Longrightarrow> surj h \\<Longrightarrow> finite F\"\n  by (auto dest: finite_vimageD')\n\nlemma finite_vimage_iff: \"bij h \\<Longrightarrow> finite (h -` F) \\<longleftrightarrow> finite F\"\n  unfolding bij_def by (auto elim: finite_vimageD finite_vimageI)\n\nlemma finite_Collect_bex [simp]:\n  assumes \"finite A\"\n  shows \"finite {x. \\<exists>y\\<in>A. Q x y} \\<longleftrightarrow> (\\<forall>y\\<in>A. finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y\\<in>A. Q x y} = (\\<Union>y\\<in>A. {x. Q x y})\" by auto\n  with assms show ?thesis by simp\nqed\n\nlemma finite_Collect_bounded_ex [simp]:\n  assumes \"finite {y. P y}\"\n  shows \"finite {x. \\<exists>y. P y \\<and> Q x y} \\<longleftrightarrow> (\\<forall>y. P y \\<longrightarrow> finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y. P y \\<and> Q x y} = (\\<Union>y\\<in>{y. P y}. {x. Q x y})\"\n    by auto\n  with assms show ?thesis\n    by simp\nqed\n\nlemma finite_Plus: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A <+> B)\"\n  by (simp add: Plus_def)\n\nlemma finite_PlusD:\n  fixes A :: \"'a set\" and B :: \"'b set\"\n  assumes fin: \"finite (A <+> B)\"\n  shows \"finite A\" \"finite B\"\nproof -\n  have \"Inl ` A \\<subseteq> A <+> B\"\n    by auto\n  then have \"finite (Inl ` A :: ('a + 'b) set)\"\n    using fin by (rule finite_subset)\n  then show \"finite A\"\n    by (rule finite_imageD) (auto intro: inj_onI)\nnext\n  have \"Inr ` B \\<subseteq> A <+> B\"\n    by auto\n  then have \"finite (Inr ` B :: ('a + 'b) set)\"\n    using fin by (rule finite_subset)\n  then show \"finite B\"\n    by (rule finite_imageD) (auto intro: inj_onI)\nqed\n\nlemma finite_Plus_iff [simp]: \"finite (A <+> B) \\<longleftrightarrow> finite A \\<and> finite B\"\n  by (auto intro: finite_PlusD finite_Plus)\n\nlemma finite_Plus_UNIV_iff [simp]:\n  \"finite (UNIV :: ('a + 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  by (subst UNIV_Plus_UNIV [symmetric]) (rule finite_Plus_iff)\n\nlemma finite_SigmaI [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a\\<in>A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (SIGMA a:A. B a)\"\n  unfolding Sigma_def by blast\n\nlemma finite_SigmaI2:\n  assumes \"finite {x\\<in>A. B x \\<noteq> {}}\"\n  and \"\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)\"\n  shows \"finite (Sigma A B)\"\nproof -\n  from assms have \"finite (Sigma {x\\<in>A. B x \\<noteq> {}} B)\"\n    by auto\n  also have \"Sigma {x:A. B x \\<noteq> {}} B = Sigma A B\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma finite_cartesian_product: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<times> B)\"\n  by (rule finite_SigmaI)\n\nlemma finite_Prod_UNIV:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> finite (UNIV :: 'b set) \\<Longrightarrow> finite (UNIV :: ('a \\<times> 'b) set)\"\n  by (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product)\n\nlemma finite_cartesian_productD1:\n  assumes \"finite (A \\<times> B)\" and \"B \\<noteq> {}\"\n  shows \"finite A\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"fst ` (A \\<times> B) = fst ` f ` {i::nat. i < n}\"\n    by simp\n  with \\<open>B \\<noteq> {}\\<close> have \"A = (fst \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. A = f ` {i::nat. i < n}\"\n    by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_productD2:\n  assumes \"finite (A \\<times> B)\" and \"A \\<noteq> {}\"\n  shows \"finite B\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"snd ` (A \\<times> B) = snd ` f ` {i::nat. i < n}\"\n    by simp\n  with \\<open>A \\<noteq> {}\\<close> have \"B = (snd \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. B = f ` {i::nat. i < n}\"\n    by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_product_iff:\n  \"finite (A \\<times> B) \\<longleftrightarrow> (A = {} \\<or> B = {} \\<or> (finite A \\<and> finite B))\"\n  by (auto dest: finite_cartesian_productD1 finite_cartesian_productD2 finite_cartesian_product)\n\nlemma finite_prod:\n  \"finite (UNIV :: ('a \\<times> 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  using finite_cartesian_product_iff[of UNIV UNIV] by simp\n\nlemma finite_Pow_iff [iff]: \"finite (Pow A) \\<longleftrightarrow> finite A\"\nproof\n  assume \"finite (Pow A)\"\n  then have \"finite ((\\<lambda>x. {x}) ` A)\"\n    by (blast intro: finite_subset)  (* somewhat slow *)\n  then show \"finite A\"\n    by (rule finite_imageD [unfolded inj_on_def]) simp\nnext\n  assume \"finite A\"\n  then show \"finite (Pow A)\"\n    by induct (simp_all add: Pow_insert)\nqed\n\ncorollary finite_Collect_subsets [simp, intro]: \"finite A \\<Longrightarrow> finite {B. B \\<subseteq> A}\"\n  by (simp add: Pow_def [symmetric])\n\nlemma finite_set: \"finite (UNIV :: 'a set set) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp only: finite_Pow_iff Pow_UNIV[symmetric])\n\nlemma finite_UnionD: \"finite (\\<Union>A) \\<Longrightarrow> finite A\"\n  by (blast intro: finite_subset [OF subset_Pow_Union])\n\nlemma finite_set_of_finite_funs:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {f. \\<forall>x. (x \\<in> A \\<longrightarrow> f x \\<in> B) \\<and> (x \\<notin> A \\<longrightarrow> f x = d)}\" (is \"finite ?S\")\nproof -\n  let ?F = \"\\<lambda>f. {(a,b). a \\<in> A \\<and> b = f a}\"\n  have \"?F ` ?S \\<subseteq> Pow(A \\<times> B)\"\n    by auto\n  from finite_subset[OF this] assms have 1: \"finite (?F ` ?S)\"\n    by simp\n  have 2: \"inj_on ?F ?S\"\n    by (fastforce simp add: inj_on_def set_eq_iff fun_eq_iff)  (* somewhat slow *)\n  show ?thesis\n    by (rule finite_imageD [OF 1 2])\nqed\n\nlemma not_finite_existsD:\n  assumes \"\\<not> finite {a. P a}\"\n  shows \"\\<exists>a. P a\"\nproof (rule classical)\n  assume \"\\<not> ?thesis\"\n  with assms show ?thesis by auto\nqed\n\n\nsubsubsection \\<open>Further induction rules on finite sets\\<close>\n\nlemma finite_ne_induct [case_names singleton insert, consumes 2]:\n  assumes \"finite F\" and \"F \\<noteq> {}\"\n  assumes \"\\<And>x. P {x}\"\n    and \"\\<And>x F. finite F \\<Longrightarrow> F \\<noteq> {} \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F  \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case by cases auto\nqed\n\nlemma finite_subset_induct [consumes 2, case_names empty insert]:\n  assumes \"finite F\" and \"F \\<subseteq> A\"\n    and empty: \"P {}\"\n    and insert: \"\\<And>a F. finite F \\<Longrightarrow> a \\<in> A \\<Longrightarrow> a \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert a F)\"\n  shows \"P F\"\n  using \\<open>finite F\\<close> \\<open>F \\<subseteq> A\\<close>\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume \"finite F\" and \"x \\<notin> F\" and P: \"F \\<subseteq> A \\<Longrightarrow> P F\" and i: \"insert x F \\<subseteq> A\"\n  show \"P (insert x F)\"\n  proof (rule insert)\n    from i show \"x \\<in> A\" by blast\n    from i have \"F \\<subseteq> A\" by blast\n    with P show \"P F\" .\n    show \"finite F\" by fact\n    show \"x \\<notin> F\" by fact\n  qed\nqed\n\nlemma finite_empty_induct:\n  assumes \"finite A\"\n    and \"P A\"\n    and remove: \"\\<And>a A. finite A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> P A \\<Longrightarrow> P (A - {a})\"\n  shows \"P {}\"\nproof -\n  have \"P (A - B)\" if \"B \\<subseteq> A\" for B :: \"'a set\"\n  proof -\n    from \\<open>finite A\\<close> that have \"finite B\"\n      by (rule rev_finite_subset)\n    from this \\<open>B \\<subseteq> A\\<close> show \"P (A - B)\"\n    proof induct\n      case empty\n      from \\<open>P A\\<close> show ?case by simp\n    next\n      case (insert b B)\n      have \"P (A - B - {b})\"\n      proof (rule remove)\n        from \\<open>finite A\\<close> show \"finite (A - B)\"\n          by induct auto\n        from insert show \"b \\<in> A - B\"\n          by simp\n        from insert show \"P (A - B)\"\n          by simp\n      qed\n      also have \"A - B - {b} = A - insert b B\"\n        by (rule Diff_insert [symmetric])\n      finally show ?case .\n    qed\n  qed\n  then have \"P (A - A)\" by blast\n  then show ?thesis by simp\nqed\n\nlemma finite_update_induct [consumes 1, case_names const update]:\n  assumes finite: \"finite {a. f a \\<noteq> c}\"\n    and const: \"P (\\<lambda>a. c)\"\n    and update: \"\\<And>a b f. finite {a. f a \\<noteq> c} \\<Longrightarrow> f a = c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> P f \\<Longrightarrow> P (f(a := b))\"\n  shows \"P f\"\n  using finite\nproof (induct \"{a. f a \\<noteq> c}\" arbitrary: f)\n  case empty\n  with const show ?case by simp\nnext\n  case (insert a A)\n  then have \"A = {a'. (f(a := c)) a' \\<noteq> c}\" and \"f a \\<noteq> c\"\n    by auto\n  with \\<open>finite A\\<close> have \"finite {a'. (f(a := c)) a' \\<noteq> c}\"\n    by simp\n  have \"(f(a := c)) a = c\"\n    by simp\n  from insert \\<open>A = {a'. (f(a := c)) a' \\<noteq> c}\\<close> have \"P (f(a := c))\"\n    by simp\n  with \\<open>finite {a'. (f(a := c)) a' \\<noteq> c}\\<close> \\<open>(f(a := c)) a = c\\<close> \\<open>f a \\<noteq> c\\<close>\n  have \"P ((f(a := c))(a := f a))\"\n    by (rule update)\n  then show ?case by simp\nqed\n\n\n\n\nsubsection \\<open>Class \\<open>finite\\<close>\\<close>\n\nclass finite =\n  assumes finite_UNIV: \"finite (UNIV :: 'a set)\"\nbegin\n\nlemma finite [simp]: \"finite (A :: 'a set)\"\n  by (rule subset_UNIV finite_UNIV finite_subset)+\n\nlemma finite_code [code]: \"finite (A :: 'a set) \\<longleftrightarrow> True\"\n  by simp\n\nend\n\ninstance prod :: (finite, finite) finite\n  by standard (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product finite)\n\nlemma inj_graph: \"inj (\\<lambda>f. {(x, y). y = f x})\"\n  by (rule inj_onI) (auto simp add: set_eq_iff fun_eq_iff)\n\ninstance \"fun\" :: (finite, finite) finite\nproof\n  show \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  proof (rule finite_imageD)\n    let ?graph = \"\\<lambda>f::'a \\<Rightarrow> 'b. {(x, y). y = f x}\"\n    have \"range ?graph \\<subseteq> Pow UNIV\"\n      by simp\n    moreover have \"finite (Pow (UNIV :: ('a * 'b) set))\"\n      by (simp only: finite_Pow_iff finite)\n    ultimately show \"finite (range ?graph)\"\n      by (rule finite_subset)\n    show \"inj ?graph\"\n      by (rule inj_graph)\n  qed\nqed\n\ninstance bool :: finite\n  by standard (simp add: UNIV_bool)\n\ninstance set :: (finite) finite\n  by standard (simp only: Pow_UNIV [symmetric] finite_Pow_iff finite)\n\ninstance unit :: finite\n  by standard (simp add: UNIV_unit)\n\ninstance sum :: (finite, finite) finite\n  by standard (simp only: UNIV_Plus_UNIV [symmetric] finite_Plus finite)\n\n\nsubsection \\<open>A basic fold functional for finite sets\\<close>\n\ntext \\<open>The intended behaviour is\n  \\<open>fold f z {x\\<^sub>1, \\<dots>, x\\<^sub>n} = f x\\<^sub>1 (\\<dots> (f x\\<^sub>n z)\\<dots>)\\<close>\n  if \\<open>f\\<close> is ``left-commutative'':\n\\<close>\n\nlocale comp_fun_commute =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma fun_left_comm: \"f y (f x z) = f x (f y z)\"\n  using comp_fun_commute by (simp add: fun_eq_iff)\n\nlemma commute_left_comp: \"f y \\<circ> (f x \\<circ> g) = f x \\<circ> (f y \\<circ> g)\"\n  by (simp add: o_assoc comp_fun_commute)\n\nend\n\ninductive fold_graph :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  for f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: 'b\n  where\n    emptyI [intro]: \"fold_graph f z {} z\"\n  | insertI [intro]: \"x \\<notin> A \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> fold_graph f z (insert x A) (f x y)\"\n\ninductive_cases empty_fold_graphE [elim!]: \"fold_graph f z {} x\"\n\ndefinition fold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b\"\n  where \"fold f z A = (if finite A then (THE y. fold_graph f z A y) else z)\"\n\ntext \\<open>\n  A tempting alternative for the definiens is\n  @{term \"if finite A then THE y. fold_graph f z A y else e\"}.\n  It allows the removal of finiteness assumptions from the theorems\n  \\<open>fold_comm\\<close>, \\<open>fold_reindex\\<close> and \\<open>fold_distrib\\<close>.\n  The proofs become ugly. It is not worth the effort. (???)\n\\<close>\n\nlemma finite_imp_fold_graph: \"finite A \\<Longrightarrow> \\<exists>x. fold_graph f z A x\"\n  by (induct rule: finite_induct) auto\n\n\nsubsubsection \\<open>From @{const fold_graph} to @{term fold}\\<close>\n\ncontext comp_fun_commute\nbegin\n\n\n\nlemma fold_graph_insertE_aux:\n  \"fold_graph f z A y \\<Longrightarrow> a \\<in> A \\<Longrightarrow> \\<exists>y'. y = f a y' \\<and> fold_graph f z (A - {a}) y'\"\nproof (induct set: fold_graph)\n  case emptyI\n  then show ?case by simp\nnext\n  case (insertI x A y)\n  show ?case\n  proof (cases \"x = a\")\n    case True\n    with insertI show ?thesis by auto\n  next\n    case False\n    then obtain y' where y: \"y = f a y'\" and y': \"fold_graph f z (A - {a}) y'\"\n      using insertI by auto\n    have \"f x y = f a (f x y')\"\n      unfolding y by (rule fun_left_comm)\n    moreover have \"fold_graph f z (insert x A - {a}) (f x y')\"\n      using y' and \\<open>x \\<noteq> a\\<close> and \\<open>x \\<notin> A\\<close>\n      by (simp add: insert_Diff_if fold_graph.insertI)\n    ultimately show ?thesis\n      by fast\n  qed\nqed\n\nlemma fold_graph_insertE:\n  assumes \"fold_graph f z (insert x A) v\" and \"x \\<notin> A\"\n  obtains y where \"v = f x y\" and \"fold_graph f z A y\"\n  using assms by (auto dest: fold_graph_insertE_aux [OF _ insertI1])\n\nlemma fold_graph_determ: \"fold_graph f z A x \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> y = x\"\nproof (induct arbitrary: y set: fold_graph)\n  case emptyI\n  then show ?case by fast\nnext\n  case (insertI x A y v)\n  from \\<open>fold_graph f z (insert x A) v\\<close> and \\<open>x \\<notin> A\\<close>\n  obtain y' where \"v = f x y'\" and \"fold_graph f z A y'\"\n    by (rule fold_graph_insertE)\n  from \\<open>fold_graph f z A y'\\<close> have \"y' = y\"\n    by (rule insertI)\n  with \\<open>v = f x y'\\<close> show \"v = f x y\"\n    by simp\nqed\n\nlemma fold_equality: \"fold_graph f z A y \\<Longrightarrow> fold f z A = y\"\n  by (cases \"finite A\") (auto simp add: fold_def intro: fold_graph_determ dest: fold_graph_finite)\n\nlemma fold_graph_fold:\n  assumes \"finite A\"\n  shows \"fold_graph f z A (fold f z A)\"\nproof -\n  from assms have \"\\<exists>x. fold_graph f z A x\"\n    by (rule finite_imp_fold_graph)\n  moreover note fold_graph_determ\n  ultimately have \"\\<exists>!x. fold_graph f z A x\"\n    by (rule ex_ex1I)\n  then have \"fold_graph f z A (The (fold_graph f z A))\"\n    by (rule theI')\n  with assms show ?thesis\n    by (simp add: fold_def)\nqed\n\ntext \\<open>The base case for \\<open>fold\\<close>:\\<close>\n\nlemma (in -) fold_infinite [simp]: \"\\<not> finite A \\<Longrightarrow> fold f z A = z\"\n  by (auto simp: fold_def)\n\nlemma (in -) fold_empty [simp]: \"fold f z {} = z\"\n  by (auto simp: fold_def)\n\ntext \\<open>The various recursion equations for @{const fold}:\\<close>\n\nlemma fold_insert [simp]:\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"fold f z (insert x A) = f x (fold f z A)\"\nproof (rule fold_equality)\n  fix z\n  from \\<open>finite A\\<close> have \"fold_graph f z A (fold f z A)\"\n    by (rule fold_graph_fold)\n  with \\<open>x \\<notin> A\\<close> have \"fold_graph f z (insert x A) (f x (fold f z A))\"\n    by (rule fold_graph.insertI)\n  then show \"fold_graph f z (insert x A) (f x (fold f z A))\"\n    by simp\nqed\n\ndeclare (in -) empty_fold_graphE [rule del] fold_graph.intros [rule del]\n  \\<comment> \\<open>No more proofs involve these.\\<close>\n\nlemma fold_fun_left_comm: \"finite A \\<Longrightarrow> f x (fold f z A) = fold f (f x z) A\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (simp add: fun_left_comm [of x])\nqed\n\nlemma fold_insert2: \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> fold f z (insert x A)  = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nlemma fold_rec:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"fold f z A = f x (fold f z (A - {x}))\"\nproof -\n  have A: \"A = insert x (A - {x})\"\n    using \\<open>x \\<in> A\\<close> by blast\n  then have \"fold f z A = fold f z (insert x (A - {x}))\"\n    by simp\n  also have \"\\<dots> = f x (fold f z (A - {x}))\"\n    by (rule fold_insert) (simp add: \\<open>finite A\\<close>)+\n  finally show ?thesis .\nqed\n\nlemma fold_insert_remove:\n  assumes \"finite A\"\n  shows \"fold f z (insert x A) = f x (fold f z (A - {x}))\"\nproof -\n  from \\<open>finite A\\<close> have \"finite (insert x A)\"\n    by auto\n  moreover have \"x \\<in> insert x A\"\n    by auto\n  ultimately have \"fold f z (insert x A) = f x (fold f z (insert x A - {x}))\"\n    by (rule fold_rec)\n  then show ?thesis\n    by simp\nqed\n\nlemma fold_set_union_disj:\n  assumes \"finite A\" \"finite B\" \"A \\<inter> B = {}\"\n  shows \"Finite_Set.fold f z (A \\<union> B) = Finite_Set.fold f (Finite_Set.fold f z A) B\"\n  using assms(2,1,3) by induct simp_all\n\nend\n\ntext \\<open>Other properties of @{const fold}:\\<close>\n\nlemma fold_image:\n  assumes \"inj_on g A\"\n  shows \"fold f z (g ` A) = fold (f \\<circ> g) z A\"\nproof (cases \"finite A\")\n  case False\n  with assms show ?thesis\n    by (auto dest: finite_imageD simp add: fold_def)\nnext\n  case True\n  have \"fold_graph f z (g ` A) = fold_graph (f \\<circ> g) z A\"\n  proof\n    fix w\n    show \"fold_graph f z (g ` A) w \\<longleftrightarrow> fold_graph (f \\<circ> g) z A w\" (is \"?P \\<longleftrightarrow> ?Q\")\n    proof\n      assume ?P\n      then show ?Q\n        using assms\n      proof (induct \"g ` A\" w arbitrary: A)\n        case emptyI\n        then show ?case by (auto intro: fold_graph.emptyI)\n      next\n        case (insertI x A r B)\n        from \\<open>inj_on g B\\<close> \\<open>x \\<notin> A\\<close> \\<open>insert x A = image g B\\<close> obtain x' A'\n          where \"x' \\<notin> A'\" and [simp]: \"B = insert x' A'\" \"x = g x'\" \"A = g ` A'\"\n          by (rule inj_img_insertE)\n        from insertI.prems have \"fold_graph (f \\<circ> g) z A' r\"\n          by (auto intro: insertI.hyps)\n        with \\<open>x' \\<notin> A'\\<close> have \"fold_graph (f \\<circ> g) z (insert x' A') ((f \\<circ> g) x' r)\"\n          by (rule fold_graph.insertI)\n        then show ?case\n          by simp\n      qed\n    next\n      assume ?Q\n      then show ?P\n        using assms\n      proof induct\n        case emptyI\n        then show ?case\n          by (auto intro: fold_graph.emptyI)\n      next\n        case (insertI x A r)\n        from \\<open>x \\<notin> A\\<close> insertI.prems have \"g x \\<notin> g ` A\"\n          by auto\n        moreover from insertI have \"fold_graph f z (g ` A) r\"\n          by simp\n        ultimately have \"fold_graph f z (insert (g x) (g ` A)) (f (g x) r)\"\n          by (rule fold_graph.insertI)\n        then show ?case\n          by simp\n      qed\n    qed\n  qed\n  with True assms show ?thesis\n    by (auto simp add: fold_def)\nqed\n\nlemma fold_cong:\n  assumes \"comp_fun_commute f\" \"comp_fun_commute g\"\n    and \"finite A\"\n    and cong: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"fold f s A = fold g t B\"\nproof -\n  have \"fold f s A = fold g s A\"\n    using \\<open>finite A\\<close> cong\n  proof (induct A)\n    case empty\n    then show ?case by simp\n  next\n    case insert\n    interpret f: comp_fun_commute f by (fact \\<open>comp_fun_commute f\\<close>)\n    interpret g: comp_fun_commute g by (fact \\<open>comp_fun_commute g\\<close>)\n    from insert show ?case by simp\n  qed\n  with assms show ?thesis by simp\nqed\n\n\ntext \\<open>A simplified version for idempotent functions:\\<close>\n\nlocale comp_fun_idem = comp_fun_commute +\n  assumes comp_fun_idem: \"f x \\<circ> f x = f x\"\nbegin\n\nlemma fun_left_idem: \"f x (f x z) = f x z\"\n  using comp_fun_idem by (simp add: fun_eq_iff)\n\nlemma fold_insert_idem:\n  assumes fin: \"finite A\"\n  shows \"fold f z (insert x A)  = f x (fold f z A)\"\nproof cases\n  assume \"x \\<in> A\"\n  then obtain B where \"A = insert x B\" and \"x \\<notin> B\"\n    by (rule set_insert)\n  then show ?thesis\n    using assms by (simp add: comp_fun_idem fun_left_idem)\nnext\n  assume \"x \\<notin> A\"\n  then show ?thesis\n    using assms by simp\nqed\n\ndeclare fold_insert [simp del] fold_insert_idem [simp]\n\nlemma fold_insert_idem2: \"finite A \\<Longrightarrow> fold f z (insert x A) = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nend\n\n\nsubsubsection \\<open>Liftings to \\<open>comp_fun_commute\\<close> etc.\\<close>\n\nlemma (in comp_fun_commute) comp_comp_fun_commute: \"comp_fun_commute (f \\<circ> g)\"\n  by standard (simp_all add: comp_fun_commute)\n\nlemma (in comp_fun_idem) comp_comp_fun_idem: \"comp_fun_idem (f \\<circ> g)\"\n  by (rule comp_fun_idem.intro, rule comp_comp_fun_commute, unfold_locales)\n    (simp_all add: comp_fun_idem)\n\nlemma (in comp_fun_commute) comp_fun_commute_funpow: \"comp_fun_commute (\\<lambda>x. f x ^^ g x)\"\nproof\n  show \"f y ^^ g y \\<circ> f x ^^ g x = f x ^^ g x \\<circ> f y ^^ g y\" for x y\n  proof (cases \"x = y\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    show ?thesis\n    proof (induct \"g x\" arbitrary: g)\n      case 0\n      then show ?case by simp\n    next\n      case (Suc n g)\n      have hyp1: \"f y ^^ g y \\<circ> f x = f x \\<circ> f y ^^ g y\"\n      proof (induct \"g y\" arbitrary: g)\n        case 0\n        then show ?case by simp\n      next\n        case (Suc n g)\n        define h where \"h z = g z - 1\" for z\n        with Suc have \"n = h y\"\n          by simp\n        with Suc have hyp: \"f y ^^ h y \\<circ> f x = f x \\<circ> f y ^^ h y\"\n          by auto\n        from Suc h_def have \"g y = Suc (h y)\"\n          by simp\n        then show ?case\n          by (simp add: comp_assoc hyp) (simp add: o_assoc comp_fun_commute)\n      qed\n      define h where \"h z = (if z = x then g x - 1 else g z)\" for z\n      with Suc have \"n = h x\"\n        by simp\n      with Suc have \"f y ^^ h y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ h y\"\n        by auto\n      with False h_def have hyp2: \"f y ^^ g y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ g y\"\n        by simp\n      from Suc h_def have \"g x = Suc (h x)\"\n        by simp\n      then show ?case\n        by (simp del: funpow.simps add: funpow_Suc_right o_assoc hyp2) (simp add: comp_assoc hyp1)\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>Expressing set operations via @{const fold}\\<close>\n\nlemma comp_fun_commute_const: \"comp_fun_commute (\\<lambda>_. f)\"\n  by standard rule\n\nlemma comp_fun_idem_insert: \"comp_fun_idem insert\"\n  by standard auto\n\nlemma comp_fun_idem_remove: \"comp_fun_idem Set.remove\"\n  by standard auto\n\nlemma (in semilattice_inf) comp_fun_idem_inf: \"comp_fun_idem inf\"\n  by standard (auto simp add: inf_left_commute)\n\nlemma (in semilattice_sup) comp_fun_idem_sup: \"comp_fun_idem sup\"\n  by standard (auto simp add: sup_left_commute)\n\nlemma union_fold_insert:\n  assumes \"finite A\"\n  shows \"A \\<union> B = fold insert B A\"\nproof -\n  interpret comp_fun_idem insert\n    by (fact comp_fun_idem_insert)\n  from \\<open>finite A\\<close> show ?thesis\n    by (induct A arbitrary: B) simp_all\nqed\n\nlemma minus_fold_remove:\n  assumes \"finite A\"\n  shows \"B - A = fold Set.remove B A\"\nproof -\n  interpret comp_fun_idem Set.remove\n    by (fact comp_fun_idem_remove)\n  from \\<open>finite A\\<close> have \"fold Set.remove B A = B - A\"\n    by (induct A arbitrary: B) auto  (* slow *)\n  then show ?thesis ..\nqed\n\nlemma comp_fun_commute_filter_fold:\n  \"comp_fun_commute (\\<lambda>x A'. if P x then Set.insert x A' else A')\"\nproof -\n  interpret comp_fun_idem Set.insert by (fact comp_fun_idem_insert)\n  show ?thesis by standard (auto simp: fun_eq_iff)\nqed\n\nlemma Set_filter_fold:\n  assumes \"finite A\"\n  shows \"Set.filter P A = fold (\\<lambda>x A'. if P x then Set.insert x A' else A') {} A\"\n  using assms\n  by induct\n    (auto simp add: Set.filter_def comp_fun_commute.fold_insert[OF comp_fun_commute_filter_fold])\n\nlemma inter_Set_filter:\n  assumes \"finite B\"\n  shows \"A \\<inter> B = Set.filter (\\<lambda>x. x \\<in> A) B\"\n  using assms\n  by induct (auto simp: Set.filter_def)\n\nlemma image_fold_insert:\n  assumes \"finite A\"\n  shows \"image f A = fold (\\<lambda>k A. Set.insert (f k) A) {} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k A. Set.insert (f k) A\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma Ball_fold:\n  assumes \"finite A\"\n  shows \"Ball A P = fold (\\<lambda>k s. s \\<and> P k) True A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<and> P k\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma Bex_fold:\n  assumes \"finite A\"\n  shows \"Bex A P = fold (\\<lambda>k s. s \\<or> P k) False A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<or> P k\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma comp_fun_commute_Pow_fold: \"comp_fun_commute (\\<lambda>x A. A \\<union> Set.insert x ` A)\"\n  by (clarsimp simp: fun_eq_iff comp_fun_commute_def) blast  (* somewhat slow *)\n\nlemma Pow_fold:\n  assumes \"finite A\"\n  shows \"Pow A = fold (\\<lambda>x A. A \\<union> Set.insert x ` A) {{}} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>x A. A \\<union> Set.insert x ` A\"\n    by (rule comp_fun_commute_Pow_fold)\n  show ?thesis\n    using assms by (induct A) (auto simp: Pow_insert)\nqed\n\nlemma fold_union_pair:\n  assumes \"finite B\"\n  shows \"(\\<Union>y\\<in>B. {(x, y)}) \\<union> A = fold (\\<lambda>y. Set.insert (x, y)) A B\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>y. Set.insert (x, y)\"\n    by standard auto\n  show ?thesis\n    using assms by (induct arbitrary: A) simp_all\nqed\n\nlemma comp_fun_commute_product_fold:\n  \"finite B \\<Longrightarrow> comp_fun_commute (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B)\"\n  by standard (auto simp: fold_union_pair [symmetric])\n\nlemma product_fold:\n  assumes \"finite A\" \"finite B\"\n  shows \"A \\<times> B = fold (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B) {} A\"\n  using assms unfolding Sigma_def\n  by (induct A)\n    (simp_all add: comp_fun_commute.fold_insert[OF comp_fun_commute_product_fold] fold_union_pair)\n\ncontext complete_lattice\nbegin\n\nlemma inf_Inf_fold_inf:\n  assumes \"finite A\"\n  shows \"inf (Inf A) B = fold inf B A\"\nproof -\n  interpret comp_fun_idem inf\n    by (fact comp_fun_idem_inf)\n  from \\<open>finite A\\<close> fold_fun_left_comm show ?thesis\n    by (induct A arbitrary: B) (simp_all add: inf_commute fun_eq_iff)\nqed\n\nlemma sup_Sup_fold_sup:\n  assumes \"finite A\"\n  shows \"sup (Sup A) B = fold sup B A\"\nproof -\n  interpret comp_fun_idem sup\n    by (fact comp_fun_idem_sup)\n  from \\<open>finite A\\<close> fold_fun_left_comm show ?thesis\n    by (induct A arbitrary: B) (simp_all add: sup_commute fun_eq_iff)\nqed\n\nlemma Inf_fold_inf: \"finite A \\<Longrightarrow> Inf A = fold inf top A\"\n  using inf_Inf_fold_inf [of A top] by (simp add: inf_absorb2)\n\nlemma Sup_fold_sup: \"finite A \\<Longrightarrow> Sup A = fold sup bot A\"\n  using sup_Sup_fold_sup [of A bot] by (simp add: sup_absorb2)\n\nlemma inf_INF_fold_inf:\n  assumes \"finite A\"\n  shows \"inf B (INFIMUM A f) = fold (inf \\<circ> f) B A\" (is \"?inf = ?fold\")\nproof -\n  interpret comp_fun_idem inf by (fact comp_fun_idem_inf)\n  interpret comp_fun_idem \"inf \\<circ> f\" by (fact comp_comp_fun_idem)\n  from \\<open>finite A\\<close> have \"?fold = ?inf\"\n    by (induct A arbitrary: B) (simp_all add: inf_left_commute)\n  then show ?thesis ..\nqed\n\nlemma sup_SUP_fold_sup:\n  assumes \"finite A\"\n  shows \"sup B (SUPREMUM A f) = fold (sup \\<circ> f) B A\" (is \"?sup = ?fold\")\nproof -\n  interpret comp_fun_idem sup by (fact comp_fun_idem_sup)\n  interpret comp_fun_idem \"sup \\<circ> f\" by (fact comp_comp_fun_idem)\n  from \\<open>finite A\\<close> have \"?fold = ?sup\"\n    by (induct A arbitrary: B) (simp_all add: sup_left_commute)\n  then show ?thesis ..\nqed\n\nlemma INF_fold_inf: \"finite A \\<Longrightarrow> INFIMUM A f = fold (inf \\<circ> f) top A\"\n  using inf_INF_fold_inf [of A top] by simp\n\nlemma SUP_fold_sup: \"finite A \\<Longrightarrow> SUPREMUM A f = fold (sup \\<circ> f) bot A\"\n  using sup_SUP_fold_sup [of A bot] by simp\n\nend\n\n\nsubsection \\<open>Locales as mini-packages for fold operations\\<close>\n\nsubsubsection \\<open>The natural case\\<close>\n\nlocale folding =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: \"'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\ninterpretation fold?: comp_fun_commute f\n  by standard (use comp_fun_commute in \\<open>simp add: fun_eq_iff\\<close>)\n\ndefinition F :: \"'a set \\<Rightarrow> 'b\"\n  where eq_fold: \"F A = fold f z A\"\n\nlemma empty [simp]:\"F {} = z\"\n  by (simp add: eq_fold)\n\nlemma infinite [simp]: \"\\<not> finite A \\<Longrightarrow> F A = z\"\n  by (simp add: eq_fold)\n\nlemma insert [simp]:\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert assms\n  have \"fold f z (insert x A) = f x (fold f z A)\" by simp\n  with \\<open>finite A\\<close> show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nlemma remove:\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"F A = f x (F (A - {x}))\"\nproof -\n  from \\<open>x \\<in> A\\<close> obtain B where A: \"A = insert x B\" and \"x \\<notin> B\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from \\<open>finite A\\<close> A have \"finite B\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma insert_remove: \"finite A \\<Longrightarrow> F (insert x A) = f x (F (A - {x}))\"\n  by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nend\n\n\nsubsubsection \\<open>With idempotency\\<close>\n\nlocale folding_idem = folding +\n  assumes comp_fun_idem: \"f x \\<circ> f x = f x\"\nbegin\n\ndeclare insert [simp del]\n\ninterpretation fold?: comp_fun_idem f\n  by standard (insert comp_fun_commute comp_fun_idem, simp add: fun_eq_iff)\n\nlemma insert_idem [simp]:\n  assumes \"finite A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert_idem assms\n  have \"fold f z (insert x A) = f x (fold f z A)\" by simp\n  with \\<open>finite A\\<close> show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nend\n\n\nsubsection \\<open>Finite cardinality\\<close>\n\ntext \\<open>\n  The traditional definition\n  @{prop \"card A \\<equiv> LEAST n. \\<exists>f. A = {f i |i. i < n}\"}\n  is ugly to work with.\n  But now that we have @{const fold} things are easy:\n\\<close>\n\nglobal_interpretation card: folding \"\\<lambda>_. Suc\" 0\n  defines card = \"folding.F (\\<lambda>_. Suc) 0\"\n  by standard rule\n\nlemma card_infinite: \"\\<not> finite A \\<Longrightarrow> card A = 0\"\n  by (fact card.infinite)\n\nlemma card_empty: \"card {} = 0\"\n  by (fact card.empty)\n\nlemma card_insert_disjoint: \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> card (insert x A) = Suc (card A)\"\n  by (fact card.insert)\n\nlemma card_insert_if: \"finite A \\<Longrightarrow> card (insert x A) = (if x \\<in> A then card A else Suc (card A))\"\n  by auto (simp add: card.insert_remove card.remove)\n\nlemma card_ge_0_finite: \"card A > 0 \\<Longrightarrow> finite A\"\n  by (rule ccontr) simp\n\nlemma card_0_eq [simp]: \"finite A \\<Longrightarrow> card A = 0 \\<longleftrightarrow> A = {}\"\n  by (auto dest: mk_disjoint_insert)\n\nlemma finite_UNIV_card_ge_0: \"finite (UNIV :: 'a set) \\<Longrightarrow> card (UNIV :: 'a set) > 0\"\n  by (rule ccontr) simp\n\nlemma card_eq_0_iff: \"card A = 0 \\<longleftrightarrow> A = {} \\<or> \\<not> finite A\"\n  by auto\n\nlemma card_range_greater_zero: \"finite (range f) \\<Longrightarrow> card (range f) > 0\"\n  by (rule ccontr) (simp add: card_eq_0_iff)\n\nlemma card_gt_0_iff: \"0 < card A \\<longleftrightarrow> A \\<noteq> {} \\<and> finite A\"\n  by (simp add: neq0_conv [symmetric] card_eq_0_iff)\n\nlemma card_Suc_Diff1: \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> Suc (card (A - {x})) = card A\"\n  apply (rule insert_Diff [THEN subst, where t = A])\n   apply assumption\n  apply (simp del: insert_Diff_single)\n  done\n\nlemma card_insert_le_m1: \"n > 0 \\<Longrightarrow> card y \\<le> n - 1 \\<Longrightarrow> card (insert x y) \\<le> n\"\n  apply (cases \"finite y\")\n   apply (cases \"x \\<in> y\")\n    apply (auto simp: insert_absorb)\n  done\n\nlemma card_Diff_singleton: \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> card (A - {x}) = card A - 1\"\n  by (simp add: card_Suc_Diff1 [symmetric])\n\nlemma card_Diff_singleton_if:\n  \"finite A \\<Longrightarrow> card (A - {x}) = (if x \\<in> A then card A - 1 else card A)\"\n  by (simp add: card_Diff_singleton)\n\nlemma card_Diff_insert[simp]:\n  assumes \"finite A\" and \"a \\<in> A\" and \"a \\<notin> B\"\n  shows \"card (A - insert a B) = card (A - B) - 1\"\nproof -\n  have \"A - insert a B = (A - B) - {a}\"\n    using assms by blast\n  then show ?thesis\n    using assms by (simp add: card_Diff_singleton)\nqed\n\nlemma card_insert: \"finite A \\<Longrightarrow> card (insert x A) = Suc (card (A - {x}))\"\n  by (fact card.insert_remove)\n\nlemma card_insert_le: \"finite A \\<Longrightarrow> card A \\<le> card (insert x A)\"\n  by (simp add: card_insert_if)\n\nlemma card_Collect_less_nat[simp]: \"card {i::nat. i < n} = n\"\n  by (induct n) (simp_all add:less_Suc_eq Collect_disj_eq)\n\nlemma card_Collect_le_nat[simp]: \"card {i::nat. i \\<le> n} = Suc n\"\n  using card_Collect_less_nat[of \"Suc n\"] by (simp add: less_Suc_eq_le)\n\nlemma card_mono:\n  assumes \"finite B\" and \"A \\<subseteq> B\"\n  shows \"card A \\<le> card B\"\nproof -\n  from assms have \"finite A\"\n    by (auto intro: finite_subset)\n  then show ?thesis\n    using assms\n  proof (induct A arbitrary: B)\n    case empty\n    then show ?case by simp\n  next\n    case (insert x A)\n    then have \"x \\<in> B\"\n      by simp\n    from insert have \"A \\<subseteq> B - {x}\" and \"finite (B - {x})\"\n      by auto\n    with insert.hyps have \"card A \\<le> card (B - {x})\"\n      by auto\n    with \\<open>finite A\\<close> \\<open>x \\<notin> A\\<close> \\<open>finite B\\<close> \\<open>x \\<in> B\\<close> show ?case\n      by simp (simp only: card.remove)\n  qed\nqed\n\nlemma card_seteq: \"finite B \\<Longrightarrow> (\\<And>A. A \\<subseteq> B \\<Longrightarrow> card B \\<le> card A \\<Longrightarrow> A = B)\"\n  apply (induct rule: finite_induct)\n   apply simp\n  apply clarify\n  apply (subgoal_tac \"finite A \\<and> A - {x} \\<subseteq> F\")\n   prefer 2 apply (blast intro: finite_subset, atomize)\n  apply (drule_tac x = \"A - {x}\" in spec)\n  apply (simp add: card_Diff_singleton_if split: if_split_asm)\n  apply (case_tac \"card A\", auto)\n  done\n\nlemma psubset_card_mono: \"finite B \\<Longrightarrow> A < B \\<Longrightarrow> card A < card B\"\n  apply (simp add: psubset_eq linorder_not_le [symmetric])\n  apply (blast dest: card_seteq)\n  done\n\nlemma card_Un_Int:\n  assumes \"finite A\" \"finite B\"\n  shows \"card A + card B = card (A \\<union> B) + card (A \\<inter> B)\"\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (auto simp add: insert_absorb Int_insert_left)\nqed\n\nlemma card_Un_disjoint: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> A \\<inter> B = {} \\<Longrightarrow> card (A \\<union> B) = card A + card B\"\n  using card_Un_Int [of A B] by simp\n\nlemma card_Un_le: \"card (A \\<union> B) \\<le> card A + card B\"\n  apply (cases \"finite A\")\n   apply (cases \"finite B\")\n    apply (use le_iff_add card_Un_Int in blast)\n   apply simp\n  apply simp\n  done\n\nlemma card_Diff_subset:\n  assumes \"finite B\"\n    and \"B \\<subseteq> A\"\n  shows \"card (A - B) = card A - card B\"\n  using assms\nproof (cases \"finite A\")\n  case False\n  with assms show ?thesis\n    by simp\nnext\n  case True\n  with assms show ?thesis\n    by (induct B arbitrary: A) simp_all\nqed\n\nlemma card_Diff_subset_Int:\n  assumes \"finite (A \\<inter> B)\"\n  shows \"card (A - B) = card A - card (A \\<inter> B)\"\nproof -\n  have \"A - B = A - A \\<inter> B\" by auto\n  with assms show ?thesis\n    by (simp add: card_Diff_subset)\nqed\n\nlemma diff_card_le_card_Diff:\n  assumes \"finite B\"\n  shows \"card A - card B \\<le> card (A - B)\"\nproof -\n  have \"card A - card B \\<le> card A - card (A \\<inter> B)\"\n    using card_mono[OF assms Int_lower2, of A] by arith\n  also have \"\\<dots> = card (A - B)\"\n    using assms by (simp add: card_Diff_subset_Int)\n  finally show ?thesis .\nqed\n\nlemma card_Diff1_less: \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> card (A - {x}) < card A\"\n  by (rule Suc_less_SucD) (simp add: card_Suc_Diff1 del: card_Diff_insert)\n\nlemma card_Diff2_less: \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> card (A - {x} - {y}) < card A\"\n  apply (cases \"x = y\")\n   apply (simp add: card_Diff1_less del:card_Diff_insert)\n  apply (rule less_trans)\n   prefer 2 apply (auto intro!: card_Diff1_less simp del: card_Diff_insert)\n  done\n\nlemma card_Diff1_le: \"finite A \\<Longrightarrow> card (A - {x}) \\<le> card A\"\n  by (cases \"x \\<in> A\") (simp_all add: card_Diff1_less less_imp_le)\n\nlemma card_psubset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> card A < card B \\<Longrightarrow> A < B\"\n  by (erule psubsetI) blast\n\nlemma card_le_inj:\n  assumes fA: \"finite A\"\n    and fB: \"finite B\"\n    and c: \"card A \\<le> card B\"\n  shows \"\\<exists>f. f ` A \\<subseteq> B \\<and> inj_on f A\"\n  using fA fB c\nproof (induct arbitrary: B rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x s t)\n  then show ?case\n  proof (induct rule: finite_induct [OF insert.prems(1)])\n    case 1\n    then show ?case by simp\n  next\n    case (2 y t)\n    from \"2.prems\"(1,2,5) \"2.hyps\"(1,2) have cst: \"card s \\<le> card t\"\n      by simp\n    from \"2.prems\"(3) [OF \"2.hyps\"(1) cst]\n    obtain f where \"f ` s \\<subseteq> t\" \"inj_on f s\"\n      by blast\n    with \"2.prems\"(2) \"2.hyps\"(2) show ?case\n      apply -\n      apply (rule exI[where x = \"\\<lambda>z. if z = x then y else f z\"])\n      apply (auto simp add: inj_on_def)\n      done\n  qed\nqed\n\nlemma card_subset_eq:\n  assumes fB: \"finite B\"\n    and AB: \"A \\<subseteq> B\"\n    and c: \"card A = card B\"\n  shows \"A = B\"\nproof -\n  from fB AB have fA: \"finite A\"\n    by (auto intro: finite_subset)\n  from fA fB have fBA: \"finite (B - A)\"\n    by auto\n  have e: \"A \\<inter> (B - A) = {}\"\n    by blast\n  have eq: \"A \\<union> (B - A) = B\"\n    using AB by blast\n  from card_Un_disjoint[OF fA fBA e, unfolded eq c] have \"card (B - A) = 0\"\n    by arith\n  then have \"B - A = {}\"\n    unfolding card_eq_0_iff using fA fB by simp\n  with AB show \"A = B\"\n    by blast\nqed\n\nlemma insert_partition:\n  \"x \\<notin> F \\<Longrightarrow> \\<forall>c1 \\<in> insert x F. \\<forall>c2 \\<in> insert x F. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {} \\<Longrightarrow> x \\<inter> \\<Union>F = {}\"\n  by auto  (* somewhat slow *)\n\nlemma finite_psubset_induct [consumes 1, case_names psubset]:\n  assumes finite: \"finite A\"\n    and major: \"\\<And>A. finite A \\<Longrightarrow> (\\<And>B. B \\<subset> A \\<Longrightarrow> P B) \\<Longrightarrow> P A\"\n  shows \"P A\"\n  using finite\nproof (induct A taking: card rule: measure_induct_rule)\n  case (less A)\n  have fin: \"finite A\" by fact\n  have ih: \"card B < card A \\<Longrightarrow> finite B \\<Longrightarrow> P B\" for B by fact\n  have \"P B\" if \"B \\<subset> A\" for B\n  proof -\n    from that have \"card B < card A\"\n      using psubset_card_mono fin by blast\n    moreover\n    from that have \"B \\<subseteq> A\"\n      by auto\n    then have \"finite B\"\n      using fin finite_subset by blast\n    ultimately show ?thesis using ih by simp\n  qed\n  with fin show \"P A\" using major by blast\nqed\n\nlemma finite_induct_select [consumes 1, case_names empty select]:\n  assumes \"finite S\"\n    and \"P {}\"\n    and select: \"\\<And>T. T \\<subset> S \\<Longrightarrow> P T \\<Longrightarrow> \\<exists>s\\<in>S - T. P (insert s T)\"\n  shows \"P S\"\nproof -\n  have \"0 \\<le> card S\" by simp\n  then have \"\\<exists>T \\<subseteq> S. card T = card S \\<and> P T\"\n  proof (induct rule: dec_induct)\n    case base with \\<open>P {}\\<close>\n    show ?case\n      by (intro exI[of _ \"{}\"]) auto\n  next\n    case (step n)\n    then obtain T where T: \"T \\<subseteq> S\" \"card T = n\" \"P T\"\n      by auto\n    with \\<open>n < card S\\<close> have \"T \\<subset> S\" \"P T\"\n      by auto\n    with select[of T] obtain s where \"s \\<in> S\" \"s \\<notin> T\" \"P (insert s T)\"\n      by auto\n    with step(2) T \\<open>finite S\\<close> show ?case\n      by (intro exI[of _ \"insert s T\"]) (auto dest: finite_subset)\n  qed\n  with \\<open>finite S\\<close> show \"P S\"\n    by (auto dest: card_subset_eq)\nqed\n\nlemma remove_induct [case_names empty infinite remove]:\n  assumes empty: \"P ({} :: 'a set)\"\n    and infinite: \"\\<not> finite B \\<Longrightarrow> P B\"\n    and remove: \"\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A\"\n  shows \"P B\"\nproof (cases \"finite B\")\n  case False\n  then show ?thesis by (rule infinite)\nnext\n  case True\n  define A where \"A = B\"\n  with True have \"finite A\" \"A \\<subseteq> B\"\n    by simp_all\n  then show \"P A\"\n  proof (induct \"card A\" arbitrary: A)\n    case 0\n    then have \"A = {}\" by auto\n    with empty show ?case by simp\n  next\n    case (Suc n A)\n    from \\<open>A \\<subseteq> B\\<close> and \\<open>finite B\\<close> have \"finite A\"\n      by (rule finite_subset)\n    moreover from Suc.hyps have \"A \\<noteq> {}\" by auto\n    moreover note \\<open>A \\<subseteq> B\\<close>\n    moreover have \"P (A - {x})\" if x: \"x \\<in> A\" for x\n      using x Suc.prems \\<open>Suc n = card A\\<close> by (intro Suc) auto\n    ultimately show ?case by (rule remove)\n  qed\nqed\n\nlemma finite_remove_induct [consumes 1, case_names empty remove]:\n  fixes P :: \"'a set \\<Rightarrow> bool\"\n  assumes \"finite B\"\n    and \"P {}\"\n    and \"\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A\"\n  defines \"B' \\<equiv> B\"\n  shows \"P B'\"\n  by (induct B' rule: remove_induct) (simp_all add: assms)\n\n\ntext \\<open>Main cardinality theorem.\\<close>\nlemma card_partition [rule_format]:\n  \"finite C \\<Longrightarrow> finite (\\<Union>C) \\<Longrightarrow> (\\<forall>c\\<in>C. card c = k) \\<Longrightarrow>\n    (\\<forall>c1 \\<in> C. \\<forall>c2 \\<in> C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}) \\<Longrightarrow>\n    k * card C = card (\\<Union>C)\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case\n    by (simp add: card_Un_disjoint insert_partition finite_subset [of _ \"\\<Union>(insert _ _)\"])\nqed\n\nlemma card_eq_UNIV_imp_eq_UNIV:\n  assumes fin: \"finite (UNIV :: 'a set)\"\n    and card: \"card A = card (UNIV :: 'a set)\"\n  shows \"A = (UNIV :: 'a set)\"\nproof\n  show \"A \\<subseteq> UNIV\" by simp\n  show \"UNIV \\<subseteq> A\"\n  proof\n    show \"x \\<in> A\" for x\n    proof (rule ccontr)\n      assume \"x \\<notin> A\"\n      then have \"A \\<subset> UNIV\" by auto\n      with fin have \"card A < card (UNIV :: 'a set)\"\n        by (fact psubset_card_mono)\n      with card show False by simp\n    qed\n  qed\nqed\n\ntext \\<open>The form of a finite set of given cardinality\\<close>\n\nlemma card_eq_SucD:\n  assumes \"card A = Suc k\"\n  shows \"\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> (k = 0 \\<longrightarrow> B = {})\"\nproof -\n  have fin: \"finite A\"\n    using assms by (auto intro: ccontr)\n  moreover have \"card A \\<noteq> 0\"\n    using assms by auto\n  ultimately obtain b where b: \"b \\<in> A\"\n    by auto\n  show ?thesis\n  proof (intro exI conjI)\n    show \"A = insert b (A - {b})\"\n      using b by blast\n    show \"b \\<notin> A - {b}\"\n      by blast\n    show \"card (A - {b}) = k\" and \"k = 0 \\<longrightarrow> A - {b} = {}\"\n      using assms b fin by (fastforce dest: mk_disjoint_insert)+\n  qed\nqed\n\nlemma card_Suc_eq:\n  \"card A = Suc k \\<longleftrightarrow>\n    (\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> (k = 0 \\<longrightarrow> B = {}))\"\n  apply (auto elim!: card_eq_SucD)\n  apply (subst card.insert)\n    apply (auto simp add: intro:ccontr)\n  done\n\nlemma card_1_singletonE:\n  assumes \"card A = 1\"\n  obtains x where \"A = {x}\"\n  using assms by (auto simp: card_Suc_eq)\n\nlemma is_singleton_altdef: \"is_singleton A \\<longleftrightarrow> card A = 1\"\n  unfolding is_singleton_def\n  by (auto elim!: card_1_singletonE is_singletonE simp del: One_nat_def)\n\nlemma card_le_Suc_iff:\n  \"finite A \\<Longrightarrow> Suc n \\<le> card A = (\\<exists>a B. A = insert a B \\<and> a \\<notin> B \\<and> n \\<le> card B \\<and> finite B)\"\n  by (fastforce simp: card_Suc_eq less_eq_nat.simps(2) insert_eq_iff\n    dest: subset_singletonD split: nat.splits if_splits)\n\nlemma finite_fun_UNIVD2:\n  assumes fin: \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  shows \"finite (UNIV :: 'b set)\"\nproof -\n  from fin have \"finite (range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary))\" for arbitrary\n    by (rule finite_imageI)\n  moreover have \"UNIV = range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary)\" for arbitrary\n    by (rule UNIV_eq_I) auto\n  ultimately show \"finite (UNIV :: 'b set)\"\n    by simp\nqed\n\nlemma card_UNIV_unit [simp]: \"card (UNIV :: unit set) = 1\"\n  unfolding UNIV_unit by simp\n\nlemma infinite_arbitrarily_large:\n  assumes \"\\<not> finite A\"\n  shows \"\\<exists>B. finite B \\<and> card B = n \\<and> B \\<subseteq> A\"\nproof (induction n)\n  case 0\n  show ?case by (intro exI[of _ \"{}\"]) auto\nnext\n  case (Suc n)\n  then obtain B where B: \"finite B \\<and> card B = n \\<and> B \\<subseteq> A\" ..\n  with \\<open>\\<not> finite A\\<close> have \"A \\<noteq> B\" by auto\n  with B have \"B \\<subset> A\" by auto\n  then have \"\\<exists>x. x \\<in> A - B\"\n    by (elim psubset_imp_ex_mem)\n  then obtain x where x: \"x \\<in> A - B\" ..\n  with B have \"finite (insert x B) \\<and> card (insert x B) = Suc n \\<and> insert x B \\<subseteq> A\"\n    by auto\n  then show \"\\<exists>B. finite B \\<and> card B = Suc n \\<and> B \\<subseteq> A\" ..\nqed\n\n\nsubsubsection \\<open>Cardinality of image\\<close>\n\nlemma card_image_le: \"finite A \\<Longrightarrow> card (f ` A) \\<le> card A\"\n  by (induct rule: finite_induct) (simp_all add: le_SucI card_insert_if)\n\nlemma card_image: \"inj_on f A \\<Longrightarrow> card (f ` A) = card A\"\nproof (induct A rule: infinite_finite_induct)\n  case (infinite A)\n  then have \"\\<not> finite (f ` A)\" by (auto dest: finite_imageD)\n  with infinite show ?case by simp\nqed simp_all\n\nlemma bij_betw_same_card: \"bij_betw f A B \\<Longrightarrow> card A = card B\"\n  by (auto simp: card_image bij_betw_def)\n\nlemma endo_inj_surj: \"finite A \\<Longrightarrow> f ` A \\<subseteq> A \\<Longrightarrow> inj_on f A \\<Longrightarrow> f ` A = A\"\n  by (simp add: card_seteq card_image)\n\nlemma eq_card_imp_inj_on:\n  assumes \"finite A\" \"card(f ` A) = card A\"\n  shows \"inj_on f A\"\n  using assms\nproof (induct rule:finite_induct)\n  case empty\n  show ?case by simp\nnext\n  case (insert x A)\n  then show ?case\n    using card_image_le [of A f] by (simp add: card_insert_if split: if_splits)\nqed\n\nlemma inj_on_iff_eq_card: \"finite A \\<Longrightarrow> inj_on f A \\<longleftrightarrow> card (f ` A) = card A\"\n  by (blast intro: card_image eq_card_imp_inj_on)\n\nlemma card_inj_on_le:\n  assumes \"inj_on f A\" \"f ` A \\<subseteq> B\" \"finite B\"\n  shows \"card A \\<le> card B\"\nproof -\n  have \"finite A\"\n    using assms by (blast intro: finite_imageD dest: finite_subset)\n  then show ?thesis\n    using assms by (force intro: card_mono simp: card_image [symmetric])\nqed\n\nlemma surj_card_le: \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> card B \\<le> card A\"\n  by (blast intro: card_image_le card_mono le_trans)\n\nlemma card_bij_eq:\n  \"inj_on f A \\<Longrightarrow> f ` A \\<subseteq> B \\<Longrightarrow> inj_on g B \\<Longrightarrow> g ` B \\<subseteq> A \\<Longrightarrow> finite A \\<Longrightarrow> finite B\n    \\<Longrightarrow> card A = card B\"\n  by (auto intro: le_antisym card_inj_on_le)\n\nlemma bij_betw_finite: \"bij_betw f A B \\<Longrightarrow> finite A \\<longleftrightarrow> finite B\"\n  unfolding bij_betw_def using finite_imageD [of f A] by auto\n\nlemma inj_on_finite: \"inj_on f A \\<Longrightarrow> f ` A \\<le> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  using finite_imageD finite_subset by blast\n\nlemma card_vimage_inj: \"inj f \\<Longrightarrow> A \\<subseteq> range f \\<Longrightarrow> card (f -` A) = card A\"\n  by (auto 4 3 simp: subset_image_iff inj_vimage_image_eq\n      intro: card_image[symmetric, OF subset_inj_on])\n\n\nsubsubsection \\<open>Pigeonhole Principles\\<close>\n\nlemma pigeonhole: \"card A > card (f ` A) \\<Longrightarrow> \\<not> inj_on f A \"\n  by (auto dest: card_image less_irrefl_nat)\n\nlemma pigeonhole_infinite:\n  assumes \"\\<not> finite A\" and \"finite (f`A)\"\n  shows \"\\<exists>a0\\<in>A. \\<not> finite {a\\<in>A. f a = f a0}\"\n  using assms(2,1)\nproof (induct \"f`A\" arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert b F)\n  show ?case\n  proof (cases \"finite {a\\<in>A. f a = b}\")\n    case True\n    with \\<open>\\<not> finite A\\<close> have \"\\<not> finite (A - {a\\<in>A. f a = b})\"\n      by simp\n    also have \"A - {a\\<in>A. f a = b} = {a\\<in>A. f a \\<noteq> b}\"\n      by blast\n    finally have \"\\<not> finite {a\\<in>A. f a \\<noteq> b}\" .\n    from insert(3)[OF _ this] insert(2,4) show ?thesis\n      by simp (blast intro: rev_finite_subset)\n  next\n    case False\n    then have \"{a \\<in> A. f a = b} \\<noteq> {}\" by force\n    with False show ?thesis by blast\n  qed\nqed\n\nlemma pigeonhole_infinite_rel:\n  assumes \"\\<not> finite A\"\n    and \"finite B\"\n    and \"\\<forall>a\\<in>A. \\<exists>b\\<in>B. R a b\"\n  shows \"\\<exists>b\\<in>B. \\<not> finite {a:A. R a b}\"\nproof -\n  let ?F = \"\\<lambda>a. {b\\<in>B. R a b}\"\n  from finite_Pow_iff[THEN iffD2, OF \\<open>finite B\\<close>] have \"finite (?F ` A)\"\n    by (blast intro: rev_finite_subset)\n  from pigeonhole_infinite [where f = ?F, OF assms(1) this]\n  obtain a0 where \"a0 \\<in> A\" and infinite: \"\\<not> finite {a\\<in>A. ?F a = ?F a0}\" ..\n  obtain b0 where \"b0 \\<in> B\" and \"R a0 b0\"\n    using \\<open>a0 \\<in> A\\<close> assms(3) by blast\n  have \"finite {a\\<in>A. ?F a = ?F a0}\" if \"finite {a\\<in>A. R a b0}\"\n    using \\<open>b0 \\<in> B\\<close> \\<open>R a0 b0\\<close> that by (blast intro: rev_finite_subset)\n  with infinite \\<open>b0 \\<in> B\\<close> show ?thesis\n    by blast\nqed\n\n\nsubsubsection \\<open>Cardinality of sums\\<close>\n\nlemma card_Plus:\n  assumes \"finite A\" \"finite B\"\n  shows \"card (A <+> B) = card A + card B\"\nproof -\n  have \"Inl`A \\<inter> Inr`B = {}\" by fast\n  with assms show ?thesis\n    by (simp add: Plus_def card_Un_disjoint card_image)\nqed\n\nlemma card_Plus_conv_if:\n  \"card (A <+> B) = (if finite A \\<and> finite B then card A + card B else 0)\"\n  by (auto simp add: card_Plus)\n\ntext \\<open>Relates to equivalence classes.  Based on a theorem of F. Kammüller.\\<close>\n\nlemma dvd_partition:\n  assumes f: \"finite (\\<Union>C)\"\n    and \"\\<forall>c\\<in>C. k dvd card c\" \"\\<forall>c1\\<in>C. \\<forall>c2\\<in>C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}\"\n  shows \"k dvd card (\\<Union>C)\"\nproof -\n  have \"finite C\"\n    by (rule finite_UnionD [OF f])\n  then show ?thesis\n    using assms\n  proof (induct rule: finite_induct)\n    case empty\n    show ?case by simp\n  next\n    case insert\n    then show ?case\n      apply simp\n      apply (subst card_Un_disjoint)\n         apply (auto simp add: disjoint_eq_subset_Compl)\n      done\n  qed\nqed\n\n\nsubsubsection \\<open>Relating injectivity and surjectivity\\<close>\n\nlemma finite_surj_inj:\n  assumes \"finite A\" \"A \\<subseteq> f ` A\"\n  shows \"inj_on f A\"\nproof -\n  have \"f ` A = A\"\n    by (rule card_seteq [THEN sym]) (auto simp add: assms card_image_le)\n  then show ?thesis using assms\n    by (simp add: eq_card_imp_inj_on)\nqed\n\nlemma finite_UNIV_surj_inj: \"finite(UNIV:: 'a set) \\<Longrightarrow> surj f \\<Longrightarrow> inj f\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  by (blast intro: finite_surj_inj subset_UNIV)\n\nlemma finite_UNIV_inj_surj: \"finite(UNIV:: 'a set) \\<Longrightarrow> inj f \\<Longrightarrow> surj f\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  by (fastforce simp:surj_def dest!: endo_inj_surj)\n\ncorollary infinite_UNIV_nat [iff]: \"\\<not> finite (UNIV :: nat set)\"\nproof\n  assume \"finite (UNIV :: nat set)\"\n  with finite_UNIV_inj_surj [of Suc] show False\n    by simp (blast dest: Suc_neq_Zero surjD)\nqed\n\nlemma infinite_UNIV_char_0: \"\\<not> finite (UNIV :: 'a::semiring_char_0 set)\"\nproof\n  assume \"finite (UNIV :: 'a set)\"\n  with subset_UNIV have \"finite (range of_nat :: 'a set)\"\n    by (rule finite_subset)\n  moreover have \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n    by (simp add: inj_on_def)\n  ultimately have \"finite (UNIV :: nat set)\"\n    by (rule finite_imageD)\n  then show False\n    by simp\nqed\n\nhide_const (open) Finite_Set.fold\n\n\nsubsection \\<open>Infinite Sets\\<close>\n\ntext \\<open>\n  Some elementary facts about infinite sets, mostly by Stephan Merz.\n  Beware! Because \"infinite\" merely abbreviates a negation, these\n  lemmas may not work well with \\<open>blast\\<close>.\n\\<close>\n\nabbreviation infinite :: \"'a set \\<Rightarrow> bool\"\n  where \"infinite S \\<equiv> \\<not> finite S\"\n\ntext \\<open>\n  Infinite sets are non-empty, and if we remove some elements from an\n  infinite set, the result is still infinite.\n\\<close>\n\nlemma infinite_imp_nonempty: \"infinite S \\<Longrightarrow> S \\<noteq> {}\"\n  by auto\n\nlemma infinite_remove: \"infinite S \\<Longrightarrow> infinite (S - {a})\"\n  by simp\n\nlemma Diff_infinite_finite:\n  assumes \"finite T\" \"infinite S\"\n  shows \"infinite (S - T)\"\n  using \\<open>finite T\\<close>\nproof induct\n  from \\<open>infinite S\\<close> show \"infinite (S - {})\"\n    by auto\nnext\n  fix T x\n  assume ih: \"infinite (S - T)\"\n  have \"S - (insert x T) = (S - T) - {x}\"\n    by (rule Diff_insert)\n  with ih show \"infinite (S - (insert x T))\"\n    by (simp add: infinite_remove)\nqed\n\nlemma Un_infinite: \"infinite S \\<Longrightarrow> infinite (S \\<union> T)\"\n  by simp\n\nlemma infinite_Un: \"infinite (S \\<union> T) \\<longleftrightarrow> infinite S \\<or> infinite T\"\n  by simp\n\nlemma infinite_super:\n  assumes \"S \\<subseteq> T\"\n    and \"infinite S\"\n  shows \"infinite T\"\nproof\n  assume \"finite T\"\n  with \\<open>S \\<subseteq> T\\<close> have \"finite S\" by (simp add: finite_subset)\n  with \\<open>infinite S\\<close> show False by simp\nqed\n\nproposition infinite_coinduct [consumes 1, case_names infinite]:\n  assumes \"X A\"\n    and step: \"\\<And>A. X A \\<Longrightarrow> \\<exists>x\\<in>A. X (A - {x}) \\<or> infinite (A - {x})\"\n  shows \"infinite A\"\nproof\n  assume \"finite A\"\n  then show False\n    using \\<open>X A\\<close>\n  proof (induction rule: finite_psubset_induct)\n    case (psubset A)\n    then obtain x where \"x \\<in> A\" \"X (A - {x}) \\<or> infinite (A - {x})\"\n      using local.step psubset.prems by blast\n    then have \"X (A - {x})\"\n      using psubset.hyps by blast\n    show False\n      apply (rule psubset.IH [where B = \"A - {x}\"])\n       apply (use \\<open>x \\<in> A\\<close> in blast)\n      apply (simp add: \\<open>X (A - {x})\\<close>)\n      done\n  qed\nqed\n\ntext \\<open>\n  For any function with infinite domain and finite range there is some\n  element that is the image of infinitely many domain elements.  In\n  particular, any infinite sequence of elements from a finite set\n  contains some element that occurs infinitely often.\n\\<close>\n\nlemma inf_img_fin_dom':\n  assumes img: \"finite (f ` A)\"\n    and dom: \"infinite A\"\n  shows \"\\<exists>y \\<in> f ` A. infinite (f -` {y} \\<inter> A)\"\nproof (rule ccontr)\n  have \"A \\<subseteq> (\\<Union>y\\<in>f ` A. f -` {y} \\<inter> A)\" by auto\n  moreover assume \"\\<not> ?thesis\"\n  with img have \"finite (\\<Union>y\\<in>f ` A. f -` {y} \\<inter> A)\" by blast\n  ultimately have \"finite A\" by (rule finite_subset)\n  with dom show False by contradiction\nqed\n\nlemma inf_img_fin_domE':\n  assumes \"finite (f ` A)\" and \"infinite A\"\n  obtains y where \"y \\<in> f`A\" and \"infinite (f -` {y} \\<inter> A)\"\n  using assms by (blast dest: inf_img_fin_dom')\n\nlemma inf_img_fin_dom:\n  assumes img: \"finite (f`A)\" and dom: \"infinite A\"\n  shows \"\\<exists>y \\<in> f`A. infinite (f -` {y})\"\n  using inf_img_fin_dom'[OF assms] by auto\n\nlemma inf_img_fin_domE:\n  assumes \"finite (f`A)\" and \"infinite A\"\n  obtains y where \"y \\<in> f`A\" and \"infinite (f -` {y})\"\n  using assms by (blast dest: inf_img_fin_dom)\n\nproposition finite_image_absD: \"finite (abs ` S) \\<Longrightarrow> finite S\"\n  for S :: \"'a::linordered_ring set\"\n  by (rule ccontr) (auto simp: abs_eq_iff vimage_def dest: inf_img_fin_dom)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Finite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.9161096198879968, "lm_q1q2_score": 0.7768314208047866}}
{"text": "(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Library Aditions for Set Cardinality\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>In this section some additional simple lemmas about set cardinality are proved.\\<close>\n\ntheory More_Set\nimports Main\nbegin\n\ntext \\<open>Every infinite set has at least two different elements\\<close>\nlemma infinite_contains_2_elems:\n  assumes \"infinite A\"\n  shows \"\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A\"\n  by (metis assms finite.simps is_singletonI' is_singleton_def)\n\ntext \\<open>Every infinite set has at least three different elements\\<close>\nlemma infinite_contains_3_elems:\n  assumes \"infinite A\"\n  shows \"\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A\"\n  by (metis Diff_iff assms infinite_contains_2_elems infinite_remove insertI1)\n\ntext \\<open>Every set with cardinality greater than 1 has at least two different elements\\<close>\nlemma card_geq_2_iff_contains_2_elems:\n  shows \"card A \\<ge> 2 \\<longleftrightarrow> finite A \\<and> (\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A)\"\nproof (intro iffI conjI)\n  assume *: \"finite A \\<and> (\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A)\"\n  thus \"card A \\<ge> 2\"\n    by (metis card_0_eq card_Suc_eq empty_iff leI less_2_cases singletonD)\nnext\n  assume *: \"2 \\<le> card A\"\n  then show \"finite A\"\n    using card.infinite by force\n  show \"\\<exists> x y. x \\<noteq> y \\<and> x \\<in> A \\<and> y \\<in> A\"\n    by (meson \"*\" card_2_iff' in_mono obtain_subset_with_card_n)\nqed\n\ntext \\<open>Set cardinality is at least 3 if and only if it contains three different elements\\<close>\nlemma card_geq_3_iff_contains_3_elems:\n  shows \"card A \\<ge> 3 \\<longleftrightarrow> finite A \\<and> (\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A)\"\nproof (intro iffI conjI)\n  assume *: \"card A \\<ge> 3\"\n  then show \"finite A\"\n    using card.infinite by force\n  show \"\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A\"\n    by (smt (verit, best) \"*\" card_2_iff' card_geq_2_iff_contains_2_elems le_cases3 not_less_eq_eq numeral_2_eq_2 numeral_3_eq_3)\nnext\n  assume *: \"finite A \\<and> (\\<exists> x y z. x \\<noteq> y \\<and> x \\<noteq> z \\<and> y \\<noteq> z \\<and> x \\<in> A \\<and> y \\<in> A \\<and> z \\<in> A)\"\n  thus \"card A \\<ge> 3\"\n    by (metis One_nat_def Suc_le_eq card_2_iff' card_le_Suc0_iff_eq leI numeral_3_eq_3 one_add_one order_class.order.eq_iff plus_1_eq_Suc)\nqed\n\ntext \\<open>Set cardinality of A is equal to 2 if and only if A={x, y} for two different elements x and y\\<close>\nlemma card_eq_2_iff_doubleton: \"card A = 2 \\<longleftrightarrow> (\\<exists> x y. x \\<noteq> y \\<and> A = {x, y})\"\n  using card_geq_2_iff_contains_2_elems[of A]\n  using card_geq_3_iff_contains_3_elems[of A]\n  by auto (rule_tac x=x in exI, rule_tac x=y in exI, auto)\n\nlemma card_eq_2_doubleton:\n  assumes \"card A = 2\" and \"x \\<noteq> y\" and \"x \\<in> A\" and \"y \\<in> A\"\n  shows \"A = {x, y}\"\n  using assms card_eq_2_iff_doubleton[of A]\n  by auto\n\ntext \\<open>Bijections map singleton to singleton sets\\<close>\n\nlemma bij_image_singleton:\n  shows \"\\<lbrakk>f ` A = {b}; f a = b; bij f\\<rbrakk> \\<Longrightarrow> A = {a}\"\n  by (metis bij_betw_def image_empty image_insert inj_image_eq_iff)\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Complex_Geometry/More_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8479677660619633, "lm_q1q2_score": 0.7768314186189524}}
{"text": "(* Title:      Domain Semirings\n   Author:     Victor B. F. Gomes, Walter Guttmann, Peter Höfner, Georg Struth, Tjark Weber\n   Maintainer: Walter Guttmann <walter.guttman at canterbury.ac.nz>\n               Georg Struth <g.struth at sheffield.ac.uk>\n               Tjark Weber <tjark.weber at it.uu.se>\n*)\n\nsection \\<open>Domain Semirings\\<close>\n\ntheory Domain_Semiring\nimports Kleene_Algebra.Kleene_Algebra\n\nbegin\n\nsubsection \\<open>Domain Semigroups and Domain Monoids\\<close>\n\nclass domain_op =\n  fixes domain_op :: \"'a \\<Rightarrow> 'a\" (\"d\")\n\ntext \\<open>First we define the class of domain semigroups. Axioms are taken from~\\cite{DesharnaisJipsenStruth}.\\<close>\n\nclass domain_semigroup = semigroup_mult + domain_op +\n  assumes dsg1 [simp]: \"d x \\<cdot> x = x\"\n  and dsg2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dsg3 [simp]: \"d (d x \\<cdot> y) = d x \\<cdot> d y\"\n  and dsg4: \"d x \\<cdot> d y = d y \\<cdot> d x\"\n\nbegin\n\nlemma domain_invol [simp]: \"d (d x) = d x\"\nproof -\n  have \"d (d x) = d (d (d x \\<cdot> x))\"\n    by simp\n  also have \"... = d (d x \\<cdot> d x)\"\n    using dsg3 by presburger\n  also have \"... = d (d x \\<cdot> x)\"\n    by simp\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>The next lemmas show that domain elements form semilattices.\\<close>\n\nlemma dom_el_idem [simp]: \"d x \\<cdot> d x = d x\"\nproof -\n  have \"d x \\<cdot> d x = d (d x \\<cdot> x)\"\n    using dsg3 by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma dom_mult_closed [simp]: \"d (d x \\<cdot> d y) = d x \\<cdot> d y\"\n  by simp\n\nlemma dom_lc3 [simp]: \"d x \\<cdot> d (x \\<cdot> y) = d (x \\<cdot> y)\"\nproof -\n  have \"d x \\<cdot> d (x \\<cdot> y) = d (d x \\<cdot> x \\<cdot> y)\"\n    using dsg3 mult_assoc by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma d_fixpoint: \"(\\<exists>y. x = d y) \\<longleftrightarrow> x = d x\"\n  by auto\n\nlemma d_type: \"\\<forall>P. (\\<forall>x. x = d x \\<longrightarrow> P x) \\<longleftrightarrow> (\\<forall>x. P (d x))\"\n  by (metis domain_invol)\n\ntext \\<open>We define the semilattice ordering on domain semigroups and explore the semilattice of domain elements from the order point of view.\\<close>\n\ndefinition ds_ord :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"x \\<sqsubseteq> y \\<longleftrightarrow> x = d x \\<cdot> y\"\n\nlemma ds_ord_refl: \"x \\<sqsubseteq> x\"\n  by (simp add: ds_ord_def)\n\nlemma ds_ord_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\nproof -\n  assume \"x \\<sqsubseteq> y\" and a: \"y \\<sqsubseteq> z\"\n  hence b: \"x = d x \\<cdot> y\"\n    using ds_ord_def by blast\n  hence \"x = d x \\<cdot> d y \\<cdot> z\"\n    using a ds_ord_def mult_assoc by force\n  also have \"... = d (d x \\<cdot> y) \\<cdot> z\"\n    by simp\n  also have \"... = d x \\<cdot> z\"\n    using b by auto\n  finally show ?thesis\n    using ds_ord_def by blast\nqed\n\nlemma ds_ord_antisym: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nproof -\n  assume a: \"x \\<sqsubseteq> y\" and \"y \\<sqsubseteq> x\"\n  hence b: \"y = d y \\<cdot> x\"\n    using ds_ord_def by auto\n  have \"x = d x \\<cdot> d y \\<cdot> x\"\n    using a b ds_ord_def mult_assoc by force\n  also have \"... = d y \\<cdot> x\"\n    by (metis (full_types) b dsg3 dsg4)\n  thus ?thesis\n    using b calculation by presburger\nqed\n\ntext \\<open>This relation is indeed an order.\\<close>\n\nsublocale  ds: order \"(\\<sqsubseteq>)\" \"\\<lambda>x y. (x \\<sqsubseteq> y \\<and> x \\<noteq> y)\"\nproof\n  show \"\\<And>x y. (x \\<sqsubseteq> y \\<and> x \\<noteq> y) = (x \\<sqsubseteq> y \\<and> \\<not> y \\<sqsubseteq> x)\"\n    using ds_ord_antisym by blast\n  show \"\\<And>x. x \\<sqsubseteq> x\"\n    by (rule ds_ord_refl)\n  show \"\\<And>x y z. x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n    by (rule ds_ord_trans)\n  show \"\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\n    by (rule ds_ord_antisym)\nqed\n\nlemma ds_ord_eq: \"x \\<sqsubseteq> d x \\<longleftrightarrow> x = d x\"\n  by (simp add: ds_ord_def)\n\nlemma \"x \\<sqsubseteq> y \\<Longrightarrow> z \\<cdot> x \\<sqsubseteq> z \\<cdot> y\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma ds_ord_iso_right: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<cdot> z \\<sqsubseteq> y \\<cdot> z\"\nproof -\n  assume \"x \\<sqsubseteq> y\"\n  hence a: \"x = d x \\<cdot> y\"\n    by (simp add: ds_ord_def)\n  hence \"x \\<cdot> z = d x \\<cdot> y \\<cdot> z\"\n    by auto\n  also have \"... = d (d x \\<cdot> y \\<cdot> z) \\<cdot> d x \\<cdot> y \\<cdot> z\"\n    using dsg1 mult_assoc by presburger\n  also have \"... = d (x \\<cdot> z) \\<cdot> d x \\<cdot> y \\<cdot> z\"\n    using a by presburger\n  finally show ?thesis\n    using ds_ord_def dsg4 mult_assoc by auto\nqed\n\ntext \\<open>The order on domain elements could as well be defined based on multiplication/meet.\\<close>\n\nlemma ds_ord_sl_ord: \"d x \\<sqsubseteq> d y \\<longleftrightarrow> d x \\<cdot> d y = d x\"\n  using ds_ord_def by auto\n\nlemma ds_ord_1: \"d (x \\<cdot> y) \\<sqsubseteq> d x\"\n  by (simp add: ds_ord_sl_ord dsg4)\n\nlemma ds_subid_aux: \"d x \\<cdot> y \\<sqsubseteq> y\"\n  by (simp add: ds_ord_def mult_assoc)\n\nlemma \"y \\<cdot> d x \\<sqsubseteq> y\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma ds_dom_iso: \"x \\<sqsubseteq> y \\<Longrightarrow> d x \\<sqsubseteq> d y\"\nproof -\n  assume \"x \\<sqsubseteq> y\"\n  hence \"x = d x \\<cdot> y\"\n    by (simp add: ds_ord_def)\n  hence \"d x = d (d x \\<cdot> y)\"\n    by presburger\n  also have \"... = d x \\<cdot> d y\"\n    by simp\n  finally show ?thesis\n    using ds_ord_sl_ord by auto\nqed\n\nlemma ds_dom_llp: \"x \\<sqsubseteq> d y \\<cdot> x \\<longleftrightarrow> d x \\<sqsubseteq> d y\"\nproof\n  assume \"x \\<sqsubseteq> d y \\<cdot> x\"\n  hence \"x = d y \\<cdot> x\"\n    by (simp add: ds_subid_aux ds.order.antisym)\n  hence \"d x = d (d y \\<cdot> x)\"\n    by presburger\n  thus \"d x \\<sqsubseteq> d y\"\n    using ds_ord_sl_ord dsg4 by force\nnext\n  assume \"d x \\<sqsubseteq> d y\"\n  thus \"x \\<sqsubseteq> d y \\<cdot> x\"\n    by (metis (no_types) ds_ord_iso_right dsg1)\nqed\n\nlemma ds_dom_llp_strong: \"x = d y \\<cdot> x \\<longleftrightarrow> d x \\<sqsubseteq> d y\"\n  by (simp add: ds_dom_llp ds.eq_iff ds_subid_aux)\n\ndefinition refines :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"refines x y \\<equiv> d y \\<sqsubseteq> d x \\<and> (d y) \\<cdot> x \\<sqsubseteq> y\"\n\nlemma refines_refl: \"refines x x\"\n  using refines_def by simp\n\nlemma refines_trans: \"refines x y \\<Longrightarrow> refines y z \\<Longrightarrow> refines x z\"\n  unfolding refines_def\n  by (metis domain_invol ds.dual_order.trans dsg1 dsg3 ds_ord_def)\n\nlemma refines_antisym: \"refines x y \\<Longrightarrow> refines y x \\<Longrightarrow> x = y\"\n  unfolding refines_def\n  using ds_dom_llp ds_ord_antisym by fastforce\n\nsublocale ref: order \"refines\" \"\\<lambda>x y. (refines x y \\<and> x \\<noteq> y)\"\nproof\n  show \"\\<And>x y. (refines x y \\<and> x \\<noteq> y) = (refines x y \\<and> \\<not> refines y x)\"\n    using refines_antisym by blast\n  show \"\\<And>x. refines x x\"\n    by (rule refines_refl)\n  show \"\\<And>x y z. refines x y \\<Longrightarrow> refines y z \\<Longrightarrow> refines x z\"\n    by (rule refines_trans)\n  show \"\\<And>x y. refines x y \\<Longrightarrow> refines y x \\<Longrightarrow> x = y\"\n    by (rule refines_antisym)\nqed\n\nend\n\ntext \\<open>We expand domain semigroups to domain monoids.\\<close>\n\nclass domain_monoid = monoid_mult + domain_semigroup\nbegin\n\nlemma dom_one [simp]: \"d 1 = 1\"\nproof -\n  have \"1 = d 1 \\<cdot> 1\"\n    using dsg1 by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma ds_subid_eq: \"x \\<sqsubseteq> 1 \\<longleftrightarrow> x = d x\"\n  by (simp add: ds_ord_def)\n\nend\n\nsubsection \\<open>Domain Near-Semirings\\<close>\n\ntext \\<open>The axioms for domain near-semirings are taken from~\\cite{DesharnaisStruthAMAST}.\\<close>\n\nclass domain_near_semiring = ab_near_semiring + plus_ord + domain_op +\n  assumes dns1 [simp]: \"d x \\<cdot> x = x\"\n  and dns2 [simp]: \"d (x \\<cdot> d y) = d(x \\<cdot> y)\"\n  and dns3 [simp]: \"d (x + y) = d x + d y\"\n  and dns4: \"d x \\<cdot> d y = d y \\<cdot> d x\"\n  and dns5 [simp]: \"d x \\<cdot> (d x + d y) = d x\"\n\nbegin\n\ntext \\<open>Domain near-semirings are automatically dioids; addition is idempotent.\\<close>\n\nsubclass near_dioid\nproof\n  show \"\\<And>x. x + x = x\"\n  proof -\n    fix x\n    have a: \"d x = d x \\<cdot> d (x + x)\"\n      using dns3 dns5 by presburger\n    have \"d (x + x) = d (x + x + (x + x)) \\<cdot> d (x + x)\"\n      by (metis (no_types) dns3  dns4 dns5)\n    hence \"d (x + x) = d (x + x) + d (x + x)\"\n      by simp\n    thus \"x + x = x\"\n      by (metis a dns1 dns4 distrib_right')\n  qed\nqed\n\ntext \\<open>Next we prepare to show that domain near-semirings are domain semigroups.\\<close>\n\n\n\nlemma dom_add_closed [simp]: \"d (d x + d y) = d x + d y\"\nproof -\n  have \"d (d x + d y) = d (d x) + d (d y)\"\n    by simp\n  thus ?thesis\n    by (metis dns1 dns2 dns3 dns4)\nqed\n\nlemma dom_absorp_2 [simp]: \"d x + d x \\<cdot> d y = d x\"\nproof -\n  have \"d x + d x \\<cdot> d y = d x \\<cdot> d x + d x \\<cdot> d y\"\n    by (metis add_idem' dns5)\n  also have \"... = (d x + d y) \\<cdot> d x\"\n    by (simp add: dns4)\n  also have \"... = d x \\<cdot> (d x + d y)\"\n    by (metis dom_add_closed dns4)\n  finally show ?thesis\n    by simp\nqed\n\nlemma dom_1: \"d (x \\<cdot> y) \\<le> d x\"\nproof -\n  have \"d (x \\<cdot> y) = d (d x \\<cdot> d (x \\<cdot> y))\"\n    by (metis dns1 dns2 mult_assoc)\n  also have \"... \\<le> d (d x) + d (d x \\<cdot> d (x \\<cdot> y))\"\n    by simp\n  also have \"... = d (d x + d x \\<cdot> d (x \\<cdot> y))\"\n    using dns3  by presburger\n  also have \"... = d (d x)\"\n    by simp\n  finally show ?thesis\n    by (metis dom_add_closed add_idem')\nqed\n\nlemma dom_subid_aux2: \"d x \\<cdot> y \\<le> y\"\nproof -\n  have \"d x \\<cdot> y \\<le> d (x + d y) \\<cdot> y\"\n    by (simp add: mult_isor)\n  also have \"... = (d x + d (d y)) \\<cdot> d y \\<cdot> y\"\n    using dns1 dns3 mult_assoc by presburger\n  also have \"... = (d y + d y \\<cdot> d x) \\<cdot> y\"\n    by (simp add: dns4 add_commute)\n  finally show ?thesis\n    by simp\nqed\n\nlemma dom_glb: \"d x \\<le> d y \\<Longrightarrow> d x \\<le> d z \\<Longrightarrow> d x \\<le> d y \\<cdot> d z\"\n  by (metis dns5 less_eq_def mult_isor)\n\nlemma dom_glb_eq: \"d x \\<le> d y \\<cdot> d z \\<longleftrightarrow> d x \\<le> d y \\<and> d x \\<le> d z\"\nproof -\n  have \"d x \\<le> d z \\<longrightarrow> d x \\<le> d z\"\n    by meson\n  then show ?thesis\n    by (metis (no_types) dom_absorp_2 dom_glb dom_subid_aux2 local.dual_order.trans local.join.sup.coboundedI2)\nqed\n\nlemma dom_ord: \"d x \\<le> d y \\<longleftrightarrow> d x \\<cdot> d y = d x\"\nproof\n  assume \"d x \\<le> d y\"\n  hence \"d x + d y = d y\"\n    by (simp add: less_eq_def)\n  thus \"d x \\<cdot> d y = d x\"\n    by (metis dns5)\nnext\n  assume \"d x \\<cdot> d y = d x\"\n  thus \"d x \\<le> d y\"\n    by (metis dom_subid_aux2)\nqed\n\nlemma dom_export [simp]: \"d (d x \\<cdot> y) = d x \\<cdot> d y\"\nproof (rule antisym)\n  have \"d (d x \\<cdot> y) = d (d (d x \\<cdot> y)) \\<cdot> d (d x \\<cdot> y)\"\n    using dns1 by presburger\n  also have \"... = d (d x \\<cdot> d y) \\<cdot> d (d x \\<cdot> y)\"\n    by (metis dns1 dns2 mult_assoc)\n  finally show a: \"d (d x \\<cdot> y) \\<le> d x \\<cdot> d y\"\n    by (metis (no_types) dom_add_closed dom_glb dom_1 add_idem' dns2 dns4)\n  have \"d (d x \\<cdot> y) = d (d x \\<cdot> y) \\<cdot> d x\"\n    using a dom_glb_eq dom_ord by force\n  hence \"d x \\<cdot> d y = d (d x \\<cdot> y) \\<cdot> d y\"\n    by (metis dns1 dns2 mult_assoc)\n  thus \"d x \\<cdot> d y \\<le> d (d x \\<cdot> y)\"\n    using a dom_glb_eq dom_ord by auto\nqed\n\nsubclass domain_semigroup\n by (unfold_locales, auto simp: dns4)\n\ntext \\<open>We compare the domain semigroup ordering with that of the dioid.\\<close>\n\n\n\nlemma two_orders: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<le> y\"\n  by (metis dom_subid_aux2 ds_ord_def)\n\nlemma \"x \\<le> y \\<Longrightarrow> x \\<sqsubseteq> y\"\n(*nitpick [expect=genuine]*)\noops\n\ntext \\<open>Next we prove additional properties.\\<close>\n\nlemma dom_subdist: \"d x \\<le> d (x + y)\"\n  by simp\n\nlemma dom_distrib: \"d x + d y \\<cdot> d z = (d x + d y) \\<cdot> (d x + d z)\"\nproof -\n  have \"(d x + d y) \\<cdot> (d x + d z) = d x \\<cdot> (d x + d z) + d y \\<cdot> (d x + d z)\"\n    using distrib_right' by blast\n  also have \"... = d x + (d x + d z) \\<cdot> d y\"\n    by (metis (no_types) dns3 dns5 dsg4)\n  also have \"... = d x + d x \\<cdot> d y + d z \\<cdot> d y\"\n    using add_assoc' distrib_right' by presburger\n  finally show ?thesis\n    by (simp add: dsg4)\nqed\n\nlemma dom_llp1: \"x \\<le> d y \\<cdot> x \\<Longrightarrow> d x \\<le> d y\"\nproof -\n  assume \"x \\<le> d y \\<cdot> x\"\n  hence \"d x \\<le> d (d y \\<cdot> x)\"\n    using dom_iso by blast\n  also have \"... = d y \\<cdot> d x\"\n    by simp\n  finally show \"d x \\<le> d y\"\n    by (simp add: dom_glb_eq)\nqed\n\nlemma dom_llp2: \"d x \\<le> d y \\<Longrightarrow> x \\<le> d y \\<cdot> x\"\n  using d_two_orders local.ds_dom_llp two_orders by blast\n\nlemma dom_llp: \"x \\<le> d y \\<cdot> x \\<longleftrightarrow> d x \\<le> d y\"\n  using dom_llp1 dom_llp2 by blast\n\nend\n\ntext \\<open>We expand domain near-semirings by an additive unit, using slightly different axioms.\\<close>\n\nclass domain_near_semiring_one = ab_near_semiring_one + plus_ord + domain_op +\n  assumes dnso1 [simp]: \"x + d x \\<cdot> x = d x \\<cdot> x\"\n  and dnso2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dnso3 [simp]: \"d x + 1 = 1\"\n  and dnso4 [simp]: \"d (x + y) = d x + d y\"\n  and dnso5: \"d x \\<cdot> d y = d y \\<cdot> d x\"\n\nbegin\n\ntext \\<open>The previous axioms are derivable.\\<close>\n\nsubclass domain_near_semiring\nproof\n  show a: \"\\<And>x. d x \\<cdot> x = x\"\n    by (metis add_commute local.dnso3 local.distrib_right' local.dnso1 local.mult_onel)\n  show \"\\<And>x y. d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n    by simp\n  show \"\\<And>x y. d (x + y) = d x + d y\"\n    by simp\n  show \"\\<And>x y. d x \\<cdot> d y = d y \\<cdot> d x\"\n    by (simp add: dnso5)\n  show \"\\<And>x y. d x \\<cdot> (d x + d y) = d x\"\n  proof -\n    fix x y\n    have \"\\<And>x. 1 + d x = 1\"\n      using add_commute dnso3 by presburger\n    thus \"d x \\<cdot> (d x + d y) = d x\"\n      by (metis (no_types) a dnso2 dnso4 dnso5 distrib_right' mult_onel)\n  qed\nqed\n\nsubclass domain_monoid ..\n\nlemma dom_subid: \"d x \\<le> 1\"\n  by (simp add: less_eq_def)\n\nend\n\ntext \\<open>We add a left unit of multiplication.\\<close>\n\nclass domain_near_semiring_one_zerol = ab_near_semiring_one_zerol + domain_near_semiring_one +\n  assumes dnso6 [simp]: \"d 0 = 0\"\n\nbegin\n\nlemma domain_very_strict: \"d x = 0 \\<longleftrightarrow> x = 0\"\n  by (metis annil dns1 dnso6)\n\nlemma dom_weakly_local: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> d y = 0\"\nproof -\n  have \"x \\<cdot> y = 0 \\<longleftrightarrow> d (x \\<cdot> y) = 0\"\n    by (simp add: domain_very_strict)\n  also have \"... \\<longleftrightarrow> d (x \\<cdot> d y) = 0\"\n    by simp\n  finally show ?thesis\n    using domain_very_strict by blast\nqed\n\nend\n\nsubsection \\<open>Domain Pre-Dioids\\<close>\n\ntext \\<open>\n  Pre-semirings with one and a left zero are automatically dioids.\n  Hence there is no point defining domain pre-semirings separately from domain dioids. The axioms\nare once again from~\\cite{DesharnaisStruthAMAST}.\n\\<close>\n\nclass domain_pre_dioid_one = pre_dioid_one + domain_op +\n  assumes dpd1 : \"x \\<le> d x \\<cdot> x\"\n  and dpd2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dpd3 [simp]: \"d x \\<le> 1\"\n  and dpd4 [simp]: \"d (x + y) = d x + d y\"\n\nbegin\n\ntext \\<open>We prepare to show that every domain pre-dioid with one is a domain near-dioid with one.\\<close>\n\nlemma dns1'' [simp]: \"d x \\<cdot> x = x\"\nproof (rule antisym)\n  show \"d x \\<cdot> x \\<le> x\"\n    using dpd3  mult_isor by fastforce\n  show \"x \\<le> d x \\<cdot> x \"\n    by (simp add: dpd1)\nqed\n\nlemma d_iso: \"x \\<le> y \\<Longrightarrow> d x \\<le> d y\"\n  by (metis dpd4 less_eq_def)\n\nlemma domain_1'': \"d (x \\<cdot> y) \\<le> d x\"\nproof -\n  have \"d (x \\<cdot> y) = d (x \\<cdot> d y)\"\n    by simp\n  also have \"... \\<le> d (x \\<cdot> 1)\"\n    by (meson d_iso dpd3 mult_isol)\n  finally show ?thesis\n    by simp\nqed\n\nlemma domain_export'' [simp]: \"d (d x \\<cdot> y) = d x \\<cdot> d y\"\nproof (rule antisym)\n  have one: \"d (d x \\<cdot> y) \\<le> d x\"\n    by (metis dpd2 domain_1'' mult_onel)\n  have two: \"d (d x \\<cdot> y) \\<le> d y\"\n    using d_iso dpd3 mult_isor by fastforce\n  have \"d (d x \\<cdot> y) = d (d (d x \\<cdot> y)) \\<cdot> d (d x \\<cdot> y)\"\n    by simp\n  also have \"... = d (d x \\<cdot> y) \\<cdot> d (d x \\<cdot> y)\"\n    by (metis dns1'' dpd2 mult_assoc)\n  thus \"d (d x \\<cdot> y) \\<le> d x \\<cdot> d y\"\n    using mult_isol_var one two by force\nnext\n  have \"d x \\<cdot> d y \\<le> 1\"\n    by (metis dpd3  mult_1_right mult_isol order.trans)\n  thus \"d x \\<cdot> d y \\<le> d (d x \\<cdot> y)\"\n    by (metis dns1'' dpd2 mult_isol mult_oner)\nqed\n\nlemma dom_subid_aux1'': \"d x \\<cdot> y \\<le> y\"\nproof -\n  have \"d x \\<cdot> y \\<le> 1 \\<cdot> y\"\n    using dpd3 mult_isor by blast\n  thus ?thesis\n    by simp\nqed\n\nlemma dom_subid_aux2'': \"x \\<cdot> d y \\<le> x\"\n  using dpd3 mult_isol by fastforce\n\nlemma d_comm: \"d x \\<cdot> d y = d y \\<cdot> d x\"\nproof (rule antisym)\n  have \"d x \\<cdot> d y = (d x \\<cdot> d y) \\<cdot> (d x \\<cdot> d y)\"\n    by (metis dns1'' domain_export'')\n  thus \"d x \\<cdot> d y \\<le> d y \\<cdot> d x\"\n    by (metis dom_subid_aux1'' dom_subid_aux2'' mult_isol_var)\nnext\n  have \"d y \\<cdot> d x = (d y \\<cdot> d x) \\<cdot> (d y \\<cdot> d x)\"\n    by (metis dns1'' domain_export'')\n  thus \"d y \\<cdot> d x \\<le> d x \\<cdot> d y\"\n    by (metis dom_subid_aux1'' dom_subid_aux2'' mult_isol_var)\nqed\n\nsubclass domain_near_semiring_one\n  by (unfold_locales, auto simp: d_comm local.join.sup.absorb2)\n\nlemma domain_subid: \"x \\<le> 1 \\<Longrightarrow> x \\<le> d x\"\n  by (metis dns1 mult_isol mult_oner)\n\nlemma d_preserves_equation: \"d y \\<cdot> x \\<le> x \\<cdot> d z \\<longleftrightarrow> d y \\<cdot> x = d y \\<cdot> x \\<cdot> d z\"\n  by (metis dom_subid_aux2'' local.antisym local.dom_el_idem local.dom_subid_aux2 local.order_prop local.subdistl mult_assoc)\n\nlemma d_restrict_iff: \"(x \\<le> y) \\<longleftrightarrow> (x \\<le> d x \\<cdot> y)\"\n  by (metis dom_subid_aux2 dsg1 less_eq_def order_trans subdistl)\n\nlemma d_restrict_iff_1: \"(d x \\<cdot> y \\<le> z) \\<longleftrightarrow> (d x \\<cdot> y \\<le> d x \\<cdot> z)\"\n  by (metis dom_subid_aux2 domain_1'' domain_invol dsg1 mult_isol_var order_trans)\n\nend\n\ntext \\<open>We add once more a left unit of multiplication.\\<close>\n\nclass domain_pre_dioid_one_zerol = domain_pre_dioid_one + pre_dioid_one_zerol +\n  assumes dpd5 [simp]: \"d 0 = 0\"\n\nbegin\n\nsubclass domain_near_semiring_one_zerol\n  by (unfold_locales, simp)\n\nend\n\nsubsection \\<open>Domain Semirings\\<close>\n\ntext \\<open>We do not consider domain semirings without units separately at the moment. The axioms are taken from from~\\cite{DesharnaisStruthSCP}\\<close>\n\nclass domain_semiringl = semiring_one_zerol + plus_ord + domain_op +\n  assumes dsr1 [simp]: \"x + d x \\<cdot> x = d x \\<cdot> x\"\n  and dsr2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dsr3 [simp]: \"d x + 1 = 1\"\n  and dsr4 [simp]: \"d 0 = 0\"\n  and dsr5 [simp]: \"d (x + y) = d x + d y\"\n\nbegin\n\ntext \\<open>Every domain semiring is automatically a domain pre-dioid with one and left zero.\\<close>\n\nsubclass dioid_one_zerol\n  by (standard, metis add_commute dsr1 dsr3 distrib_left mult_oner)\n\nsubclass domain_pre_dioid_one_zerol\n  by (standard, auto simp: less_eq_def)\n\nend\n\nclass domain_semiring = domain_semiringl + semiring_one_zero\n\nsubsection \\<open>The Algebra of Domain Elements\\<close>\n\ntext \\<open>We show that the domain elements of a domain semiring form a distributive lattice. Unfortunately we cannot prove this within the type class of domain semirings.\\<close>\n\ntypedef (overloaded)  'a d_element = \"{x :: 'a :: domain_semiring. x = d x}\"\n  by (rule_tac x = 1 in exI, simp add: domain_subid order_class.eq_iff)\n\nsetup_lifting type_definition_d_element\n\ninstantiation d_element :: (domain_semiring) bounded_lattice\n\nbegin\n\nlift_definition less_eq_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> bool\" is \"(\\<le>)\" .\n\nlift_definition less_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> bool\" is \"(<)\" .\n\nlift_definition bot_d_element :: \"'a d_element\" is 0\n  by simp\n\nlift_definition top_d_element :: \"'a d_element\" is 1\n  by simp\n\nlift_definition inf_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> 'a d_element\" is \"(\\<cdot>)\"\n  by (metis dsg3)\n\nlift_definition sup_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> 'a d_element\" is \"(+)\"\n  by simp\n\ninstance\n  apply (standard; transfer)\n  apply (simp add: less_le_not_le)+\n  apply (metis dom_subid_aux2'')\n  apply (metis dom_subid_aux2)\n  apply (metis dom_glb)\n  apply simp+\n  by (metis dom_subid)\n\nend\n\ninstance d_element :: (domain_semiring) distrib_lattice\n  by (standard, transfer, metis dom_distrib)\n\nsubsection \\<open>Domain Semirings with a Greatest Element\\<close>\n\ntext \\<open>If there is a greatest element in the semiring, then we have another equality.\\<close>\n\nclass domain_semiring_top = domain_semiring + order_top\n\nbegin\n\nnotation top (\"\\<top>\")\n\n\n\nend\n\nsubsection \\<open>Forward Diamond Operators\\<close>\n\ncontext domain_semiringl\n\nbegin\n\ntext \\<open>We define a forward diamond operator over a domain semiring. A more modular consideration is not given at the moment.\\<close>\n\ndefinition fd :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"( |_\\<rangle> _)\" [61,81] 82) where\n  \"|x\\<rangle> y = d (x \\<cdot> y)\"\n\nlemma fdia_d_simp [simp]: \"|x\\<rangle> d y = |x\\<rangle> y\"\n  by (simp add: fd_def)\n\nlemma fdia_dom [simp]: \"|x\\<rangle> 1 = d x\"\n  by (simp add: fd_def)\n\nlemma fdia_add1: \"|x\\<rangle> (y + z) = |x\\<rangle> y + |x\\<rangle> z\"\n  by (simp add: fd_def distrib_left)\n\nlemma fdia_add2: \"|x + y\\<rangle> z = |x\\<rangle> z + |y\\<rangle> z\"\n  by (simp add: fd_def distrib_right)\n\nlemma fdia_mult: \"|x \\<cdot> y\\<rangle> z = |x\\<rangle> |y\\<rangle> z\"\n  by (simp add: fd_def mult_assoc)\n\nlemma fdia_one [simp]: \"|1\\<rangle> x = d x\"\n  by (simp add: fd_def)\n\nlemma fdemodalisation1: \"d z \\<cdot> |x\\<rangle> y = 0 \\<longleftrightarrow> d z \\<cdot> x \\<cdot> d y = 0\"\nproof -\n  have \"d z \\<cdot> |x\\<rangle> y = 0 \\<longleftrightarrow> d z \\<cdot> d (x \\<cdot> y) = 0\"\n    by (simp add: fd_def)\n  also have \"... \\<longleftrightarrow> d z \\<cdot> x \\<cdot> y = 0\"\n    by (metis annil dnso6 dsg1 dsg3 mult_assoc)\n  finally show ?thesis\n    using dom_weakly_local by auto\nqed\n\nlemma fdemodalisation2: \"|x\\<rangle> y \\<le> d z \\<longleftrightarrow> x \\<cdot> d y \\<le> d z \\<cdot> x\"\nproof\n  assume \"|x\\<rangle> y \\<le> d z\"\n  hence a: \"d (x \\<cdot> d y) \\<le> d z\"\n    by (simp add: fd_def)\n  have \"x \\<cdot> d y = d (x \\<cdot> d y) \\<cdot> x \\<cdot> d y\"\n    using dsg1 mult_assoc by presburger\n  also have \"... \\<le> d z \\<cdot> x \\<cdot> d y\"\n    using a calculation dom_llp2 mult_assoc by auto\n  finally show \"x \\<cdot> d y \\<le> d z \\<cdot> x\"\n    using dom_subid_aux2'' order_trans by blast\nnext\n  assume \"x \\<cdot> d y \\<le> d z \\<cdot> x\"\n  hence \"d (x \\<cdot> d y) \\<le> d (d z \\<cdot> d x)\"\n    using dom_iso by fastforce\n  also have \"... \\<le> d (d z)\"\n    using domain_1'' by blast\n  finally show \"|x\\<rangle> y \\<le> d z\"\n    by (simp add: fd_def)\nqed\n\nlemma fd_iso1: \"d x \\<le> d y \\<Longrightarrow> |z\\<rangle> x \\<le> |z\\<rangle> y\"\n  using fd_def local.dom_iso local.mult_isol by fastforce\n\nlemma fd_iso2: \"x \\<le> y \\<Longrightarrow> |x\\<rangle> z \\<le> |y\\<rangle> z\"\n  by (simp add: fd_def dom_iso mult_isor)\n\nlemma fd_zero_var [simp]: \"|0\\<rangle> x = 0\"\n  by (simp add: fd_def)\n\nlemma fd_subdist_1: \"|x\\<rangle> y \\<le> |x\\<rangle> (y + z)\"\n  by (simp add: fd_iso1)\n\nlemma fd_subdist_2: \"|x\\<rangle> (d y \\<cdot> d z) \\<le> |x\\<rangle> y\"\n  by (simp add: fd_iso1 dom_subid_aux2'')\n\nlemma fd_subdist: \"|x\\<rangle> (d y \\<cdot> d z) \\<le> |x\\<rangle> y \\<cdot> |x\\<rangle> z\"\n  using fd_def fd_iso1 fd_subdist_2 dom_glb dom_subid_aux2 by auto\n\nlemma fdia_export_1: \"d y \\<cdot> |x\\<rangle> z = |d y \\<cdot> x\\<rangle> z\"\n  by (simp add: fd_def mult_assoc)\n\nend\n\ncontext domain_semiring\n\nbegin\n\n\n\nend\n\nsubsection \\<open>Domain Kleene Algebras\\<close>\n\ntext \\<open>We add the Kleene star to our considerations. Special domain axioms are not needed.\\<close>\n\nclass domain_left_kleene_algebra = left_kleene_algebra_zerol + domain_semiringl\n\nbegin\n\nlemma dom_star [simp]: \"d (x\\<^sup>\\<star>) = 1\"\nproof -\n  have \"d (x\\<^sup>\\<star>) = d (1 + x \\<cdot> x\\<^sup>\\<star>)\"\n    by simp\n  also have \"... = d 1 + d (x \\<cdot> x\\<^sup>\\<star>)\"\n    using dns3 by blast\n  finally show ?thesis\n    using add_commute local.dsr3 by auto\nqed\n\nlemma fdia_star_unfold [simp]: \"|1\\<rangle> y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"|1\\<rangle> y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |1 + x \\<cdot> x\\<^sup>\\<star>\\<rangle> y\"\n    using local.fdia_add2 local.fdia_mult by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma fdia_star_unfoldr [simp]: \"|1\\<rangle> y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"|1\\<rangle> y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |1 + x\\<^sup>\\<star> \\<cdot> x\\<rangle> y\"\n    using fdia_add2 fdia_mult by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma fdia_star_unfold_var [simp]: \"d y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"d y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |1\\<rangle> y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y\"\n    by simp\n  also have \"... = |1 + x \\<cdot> x\\<^sup>\\<star>\\<rangle> y\"\n    using fdia_add2 fdia_mult by presburger\n  finally show ?thesis\n    by simp\nqed\n\nlemma fdia_star_unfoldr_var [simp]: \"d y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"d y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |1\\<rangle> y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y\"\n    by simp\n  also have \"... = |1 + x\\<^sup>\\<star> \\<cdot> x\\<rangle> y\"\n    using fdia_add2 fdia_mult by presburger\n  finally show ?thesis\n    by simp\nqed\n\nlemma fdia_star_induct_var: \"|x\\<rangle> y \\<le> d y \\<Longrightarrow> |x\\<^sup>\\<star>\\<rangle> y \\<le> d y\"\nproof -\n  assume a1: \"|x\\<rangle> y \\<le> d y\"\n  hence \"x \\<cdot> d y \\<le> d y \\<cdot> x\"\n    by (simp add: fdemodalisation2)\n  hence \"x\\<^sup>\\<star> \\<cdot> d y \\<le> d y \\<cdot> x\\<^sup>\\<star>\"\n    by (simp add: star_sim1)\n  thus ?thesis\n    by (simp add: fdemodalisation2)\nqed\n\nlemma fdia_star_induct: \"d z + |x\\<rangle> y \\<le> d y \\<Longrightarrow> |x\\<^sup>\\<star>\\<rangle> z \\<le> d y\"\nproof -\n  assume a: \"d z + |x\\<rangle> y \\<le> d y\"\n  hence b: \"d z \\<le> d y\" and c: \"|x\\<rangle> y \\<le> d y\"\n    apply (simp add: local.join.le_supE)\n    using a by auto\n  hence d: \"|x\\<^sup>\\<star>\\<rangle> z \\<le> |x\\<^sup>\\<star>\\<rangle> y\"\n    using fd_def fd_iso1 by auto\n  have \"|x\\<^sup>\\<star>\\<rangle> y \\<le> d y\"\n    using c fdia_star_induct_var by blast\n  thus ?thesis\n    using d by fastforce\nqed\n\nlemma fdia_star_induct_eq: \"d z + |x\\<rangle> y = d y \\<Longrightarrow> |x\\<^sup>\\<star>\\<rangle> z \\<le> d y\"\n  by (simp add: fdia_star_induct)\n\nend\n\nclass domain_kleene_algebra = kleene_algebra + domain_semiring\n\nbegin\n\nsubclass domain_left_kleene_algebra ..\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/KAD/Domain_Semiring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8723473829749844, "lm_q1q2_score": 0.7766458382352912}}
{"text": "(*\n  File:   Prime_Harmonic.thy\n  Author: Manuel Eberl <eberlm@in.tum.de>\n\n  A lower bound for the partial sums of the prime harmonic series, and a proof of its divergence.\n  (#81 on the list of 100 mathematical theorems)\n*)\n\nsection \\<open>The Prime Harmonic Series\\<close>\ntheory Prime_Harmonic\nimports\n  \"HOL-Analysis.Analysis\"\n  \"HOL-Number_Theory.Number_Theory\"\n  Prime_Harmonic_Misc\n  Squarefree_Nat\nbegin\n\nsubsection \\<open>Auxiliary equalities and inequalities\\<close>\n\ntext \\<open>\n  First of all, we prove the following result about rearranging a product over a set into a sum\n  over all subsets of that set.\n\\<close>\nlemma prime_harmonic_aux1:\n  fixes A :: \"'a :: field set\"\n  shows \"finite A \\<Longrightarrow> (\\<Prod>x\\<in>A. 1 + 1 / x) = (\\<Sum>x\\<in>Pow A. 1 / \\<Prod>x)\"\nproof (induction rule: finite_induct)\n  fix a :: 'a and A :: \"'a set\"\n  assume a: \"a \\<notin> A\" and fin: \"finite A\"\n  assume IH: \"(\\<Prod>x\\<in>A. 1 + 1 / x) = (\\<Sum>x\\<in>Pow A. 1 / \\<Prod>x)\"\n  from a and fin have \"(\\<Prod>x\\<in>insert a A. 1 + 1 / x) = (1 + 1 / a) * (\\<Prod>x\\<in>A. 1 + 1 / x)\" by simp\n  also from fin have \"\\<dots> = (\\<Sum>x\\<in>Pow A. 1 / \\<Prod>x) + (\\<Sum>x\\<in>Pow A. 1 / (a * \\<Prod>x))\"\n    by (subst IH) (auto simp add: algebra_simps sum_divide_distrib)\n  also from fin a have \"(\\<Sum>x\\<in>Pow A. 1 / (a * \\<Prod>x)) = (\\<Sum>x\\<in>Pow A. 1 / \\<Prod>(insert a x))\"\n    by (intro sum.cong refl, subst prod.insert) (auto dest: finite_subset)\n  also from a have \"\\<dots> = (\\<Sum>x\\<in>insert a ` Pow A. 1 / \\<Prod>x)\"\n    by (subst sum.reindex) (auto simp: inj_on_def)\n  also from fin a have \"(\\<Sum>x\\<in>Pow A. 1 / \\<Prod>x) + \\<dots> = (\\<Sum>x\\<in>Pow A \\<union> insert a ` Pow A. 1 / \\<Prod>x)\"\n    by (intro sum.union_disjoint [symmetric]) (simp, simp, blast)\n  also have \"Pow A \\<union> insert a ` Pow A = Pow (insert a A)\" by (simp only: Pow_insert)\n  finally show \" (\\<Prod>x\\<in>insert a A. 1 + 1 / x) = (\\<Sum>x\\<in>Pow (insert a A). 1 / \\<Prod>x)\" .\nqed simp\n\ntext \\<open>\n  Next, we prove a simple and reasonably accurate upper bound for the sum of the squares of any\n  subset of the natural numbers, derived by simple telescoping. Our upper bound is approximately\n  1.67; the exact value is $\\frac{\\pi^2}{6} \\approx 1.64$. (cf. Basel problem)\n\\<close>\nlemma prime_harmonic_aux2:\n  assumes \"finite (A :: nat set)\"\n  shows   \"(\\<Sum>k\\<in>A. 1 / (real k ^ 2)) \\<le> 5/3\"\nproof -\n  define n where \"n = max 2 (Max A)\"\n  have n: \"n \\<ge> Max A\" \"n \\<ge> 2\" by (auto simp: n_def)\n  with assms have \"A \\<subseteq> {0..n}\" by (auto intro: order.trans[OF Max_ge])\n  hence \"(\\<Sum>k\\<in>A. 1 / (real k ^ 2)) \\<le> (\\<Sum>k=0..n. 1 / (real k ^ 2))\" by (intro sum_mono2) auto\n  also from n have \"\\<dots> = 1 + (\\<Sum>k=Suc 1..n. 1 / (real k ^ 2))\" by (simp add: sum.atLeast_Suc_atMost)\n  also have \"(\\<Sum>k=Suc 1..n. 1 / (real k ^ 2)) \\<le>\n          (\\<Sum>k=Suc 1..n. 1 / (real k ^ 2 - 1/4))\" unfolding power2_eq_square\n    by (intro sum_mono divide_left_mono mult_pos_pos)\n       (linarith, simp_all add: field_simps less_1_mult)\n  also have \"\\<dots> = (\\<Sum>k=Suc 1..n. 1 / (real k - 1/2) - 1 / (real (Suc k) - 1/2))\"\n    by (intro sum.cong refl) (simp_all add: field_simps power2_eq_square)\n  also from n have \"\\<dots> = 2 / 3 - 1 / (1 / 2 + real n)\"\n    by (subst sum_telescope') simp_all\n  also have \"1 + \\<dots> \\<le> 5/3\" by simp\n  finally show ?thesis by - simp\nqed\n\n\nsubsection \\<open>Estimating the partial sums of the Prime Harmonic Series\\<close>\n\ntext \\<open>\n  We are now ready to show our main result: the value of the partial prime harmonic sum over\n  all primes no greater than $n$ is bounded from below by the $n$-th harmonic number\n  $H_n$ minus some constant.\n\n  In our case, this constant will be $\\frac{5}{3}$. As mentioned before, using a\n  proof of the Basel problem can improve this to $\\frac{\\pi^2}{6}$, but the improvement is very\n  small and the proof of the Basel problem is a very complex one.\n\n  The exact asymptotic behaviour of the partial sums is actually $\\ln (\\ln n) + M$, where $M$\n  is the Meissel--Mertens constant (approximately 0.261).\n\\<close>\ntheorem prime_harmonic_lower:\n  assumes n: \"n \\<ge> 2\"\n  shows \"(\\<Sum>p\\<leftarrow>primes_upto n. 1 / real p) \\<ge> ln (harm n) - ln (5/3)\"\nproof -\n  \\<comment> \\<open>the set of primes that we will allow in the squarefree part\\<close>\n  define P where \"P n = set (primes_upto n)\" for n\n  {\n    fix n :: nat\n    have \"finite (P n)\" by (simp add: P_def)\n  } note [simp] = this\n\n  \\<comment> \\<open>The function that combines the squarefree part and the square part\\<close>\n  define f where \"f = (\\<lambda>(R, s :: nat). \\<Prod>R * s^2)\"\n\n  \\<comment> \\<open>@{term f} is injective if the squarefree part contains only primes\n      and the square part is positive.\\<close>\n  have inj: \"inj_on f (Pow (P n)\\<times>{1..n})\"\n  proof (rule inj_onI, clarify, rule conjI)\n    fix A1 A2 :: \"nat set\" and s1 s2 :: nat\n    assume A: \"A1 \\<subseteq> P n\" \"A2 \\<subseteq> P n\" \"s1 \\<in> {1..n}\" \"s2 \\<in> {1..n}\" \"f (A1, s1) = f (A2, s2)\"\n    have fin: \"finite A1\" \"finite A2\" by (rule A(1,2)[THEN finite_subset], simp)+\n    show \"A1 = A2\" \"s1 = s2\"\n      by ((rule squarefree_decomposition_unique2'[of A1 s1 A2 s2],\n          insert A fin, auto simp: f_def P_def set_primes_upto)[])+\n  qed\n\n  \\<comment> \\<open>@{term f} hits every number between @{term \"1::nat\"} and @{term \"n\"}. It also hits a lot\n      of other numbers, but we do not care about those, since we only need a lower bound.\\<close>\n  have surj: \"{1..n} \\<subseteq> f ` (Pow (P n)\\<times>{1..n})\"\n  proof\n    fix x assume x: \"x \\<in> {1..n}\"\n    have \"x = f (squarefree_part x, square_part x)\" by (simp add: f_def squarefree_decompose)\n    moreover have \"squarefree_part x \\<in> Pow (P n)\" using squarefree_part_subset[of x] x\n      by (auto simp: P_def set_primes_upto intro: order.trans[OF squarefree_part_le[of _ x]])\n    moreover have \"square_part x \\<in> {1..n}\" using x\n      by (auto simp: Suc_le_eq intro: order.trans[OF square_part_le[of x]])\n    ultimately show \"x \\<in> f ` (Pow (P n)\\<times>{1..n})\" by simp\n  qed\n\n  \\<comment> \\<open>We now show the main result by rearranging the sum over all primes to a product over all\n      all squarefree parts times a sum over all square parts, and then applying some simple-minded\n      approximation\\<close>\n  have \"harm n = (\\<Sum>n=1..n. 1 / real n)\" by (simp add: harm_def field_simps)\n  also from surj have \"\\<dots> \\<le> (\\<Sum>n\\<in>f ` (Pow (P n)\\<times>{1..n}). 1 / real n)\"\n    by (intro sum_mono2 finite_imageI finite_cartesian_product) simp_all\n  also from inj have \"\\<dots> = (\\<Sum>x\\<in>Pow (P n)\\<times>{1..n}. 1 / real (f x))\"\n    by (subst sum.reindex) simp_all\n  also have \"\\<dots> = (\\<Sum>A\\<in>Pow (P n). 1 / real (\\<Prod>A)) * (\\<Sum>k=1..n. 1 / (real k)^2)\" unfolding f_def\n    by (subst sum_product, subst sum.cartesian_product) (simp add: case_prod_beta)\n  also have \"\\<dots> \\<le> (\\<Sum>A\\<in>Pow (P n). 1 / real (\\<Prod>A)) * (5/3)\"\n    by (intro mult_left_mono prime_harmonic_aux2 sum_nonneg)\n       (auto simp: P_def intro!: prod_nonneg)\n  also have \"(\\<Sum>A\\<in>Pow (P n). 1 / real (\\<Prod>A)) = (\\<Sum>A\\<in>((`) real) ` Pow (P n). 1 / \\<Prod>A)\"\n    by (subst sum.reindex) (auto simp: inj_on_def inj_image_eq_iff prod.reindex)\n  also have \"((`) real) ` Pow (P n) = Pow (real ` P n)\" by (intro image_Pow_surj refl)\n  also have \"(\\<Sum>A\\<in>Pow (real ` P n). 1 / \\<Prod>A) = (\\<Prod>x\\<in>real ` P n. 1 + 1 / x)\"\n    by (intro prime_harmonic_aux1 [symmetric] finite_imageI) simp_all\n  also have \"\\<dots> = (\\<Prod>i\\<in>P n. 1 + 1 / real i)\" by (subst prod.reindex) (auto simp: inj_on_def)\n  also have \"\\<dots> \\<le> (\\<Prod>i\\<in>P n. exp (1 / real i))\" by (intro prod_mono) auto\n  also have \"\\<dots> = exp (\\<Sum>i\\<in>P n. 1 / real i)\" by (simp add: exp_sum)\n  finally have \"ln (harm n) \\<le> ln (\\<dots> * (5/3))\" using n\n    by (subst ln_le_cancel_iff) simp_all\n  hence \"ln (harm n) - ln (5/3) \\<le> (\\<Sum>i\\<in>P n. 1 / real i)\"\n    by (subst (asm) ln_mult) (simp_all add: algebra_simps)\n  thus ?thesis unfolding P_def\n    by (subst (asm) sum.distinct_set_conv_list) simp_all\nqed\n\ntext \\<open>\n  We can use the inequality $\\ln (n + 1) \\le H_n$ to estimate the asymptotic growth of the partial\n  prime harmonic series. Note that $H_n \\sim \\ln n + \\gamma$ where $\\gamma$ is the\n  Euler--Mascheroni constant (approximately 0.577), so we lose some accuracy here.\n\\<close>\ncorollary prime_harmonic_lower':\n  assumes n: \"n \\<ge> 2\"\n  shows \"(\\<Sum>p\\<leftarrow>primes_upto n. 1 / real p) \\<ge> ln (ln (n + 1)) - ln (5/3)\"\nproof -\n  from assms ln_le_harm[of n] have \"ln (ln (real n + 1)) \\<le> ln (harm n)\" by simp\n  also from assms have \"\\<dots> - ln (5/3) \\<le> (\\<Sum>p\\<leftarrow>primes_upto n. 1 / real p)\"\n    by (rule prime_harmonic_lower)\n  finally show ?thesis by - simp\nqed\n\n\n(* TODO: Not needed in Isabelle 2016 *)\nlemma Bseq_eventually_mono:\n  assumes \"eventually (\\<lambda>n. norm (f n) \\<le> norm (g n)) sequentially\" \"Bseq g\"\n  shows   \"Bseq f\"\nproof -\n  from assms(1) obtain N where N: \"\\<And>n. n \\<ge> N \\<Longrightarrow> norm (f n) \\<le> norm (g n)\"\n    by (auto simp: eventually_at_top_linorder)\n  from assms(2) obtain K where K: \"\\<And>n. norm (g n) \\<le> K\" by (blast elim!: BseqE)\n  {\n    fix n :: nat\n    have \"norm (f n) \\<le> max K (Max {norm (f n) |n. n < N})\"\n      apply (cases \"n < N\")\n      apply (rule max.coboundedI2, rule Max.coboundedI, auto) []\n      apply (rule max.coboundedI1, force intro: order.trans[OF N K])\n      done\n  }\n  thus ?thesis by (blast intro: BseqI')\nqed\n\nlemma Bseq_add:\n  assumes \"Bseq (f :: nat \\<Rightarrow> 'a :: real_normed_vector)\"\n  shows   \"Bseq (\\<lambda>x. f x + c)\"\nproof -\n  from assms obtain K where K: \"\\<And>x. norm (f x) \\<le> K\" unfolding Bseq_def by blast\n  {\n    fix x :: nat\n    have \"norm (f x + c) \\<le> norm (f x) + norm c\" by (rule norm_triangle_ineq)\n    also have \"norm (f x) \\<le> K\" by (rule K)\n    finally have \"norm (f x + c) \\<le> K + norm c\" by simp\n  }\n  thus ?thesis by (rule BseqI')\nqed\n\nlemma convergent_imp_Bseq: \"convergent f \\<Longrightarrow> Bseq f\"\n  by (simp add: Cauchy_Bseq convergent_Cauchy)\n\n(* END TODO *)\n\ntext \\<open>\n  We now use our last estimate to show that the prime harmonic series diverges. This is obvious,\n  since it is bounded from below by $\\ln (\\ln (n + 1))$ minus some constant, which obviously\n  tends to infinite.\n\n  Directly using the divergence of the harmonic series would also be possible and shorten this\n  proof a bit..\n\\<close>\ncorollary prime_harmonic_series_unbounded:\n  \"\\<not>Bseq (\\<lambda>n. \\<Sum>p\\<leftarrow>primes_upto n. 1 / p)\" (is \"\\<not>Bseq ?f\")\nproof\n  assume \"Bseq ?f\"\n  hence \"Bseq (\\<lambda>n. ?f n + ln (5/3))\" by (rule Bseq_add)\n  have \"Bseq (\\<lambda>n. ln (ln (n + 1)))\"\n  proof (rule Bseq_eventually_mono)\n    from eventually_ge_at_top[of \"2::nat\"]\n      show \"eventually (\\<lambda>n. norm (ln (ln (n + 1))) \\<le> norm (?f n + ln (5/3))) sequentially\"\n    proof eventually_elim\n      fix n :: nat assume n: \"n \\<ge> 2\"\n      hence \"norm (ln (ln (real n + 1))) = ln (ln (real n + 1))\"\n        using ln_ln_nonneg[of \"real n + 1\"] by simp\n      also have \"\\<dots> \\<le> ?f n + ln (5/3)\" using prime_harmonic_lower'[OF n]\n        by (simp add: algebra_simps)\n      also have \"?f n + ln (5/3) \\<ge> 0\" by (intro add_nonneg_nonneg sum_list_nonneg) simp_all\n      hence \"?f n + ln (5/3) = norm (?f n + ln (5/3))\" by simp\n      finally show \"norm (ln (ln (n + 1))) \\<le> norm (?f n + ln (5/3))\"\n        by (simp add: add_ac)\n    qed\n  qed fact\n  then obtain k where k: \"k > 0\" \"\\<And>n. norm (ln (ln (real (n::nat) + 1))) \\<le> k\"\n    by (auto elim!: BseqE simp: add_ac)\n\n  define N where \"N = nat \\<lceil>exp (exp k)\\<rceil>\"\n  have N_pos: \"N > 0\" unfolding N_def by simp\n  have \"real N + 1 > exp (exp k)\" unfolding N_def by linarith\n  hence \"ln (real N + 1) > ln (exp (exp k))\" by (subst ln_less_cancel_iff) simp_all\n  with N_pos have \"ln (ln (real N + 1)) > ln (exp k)\" by (subst ln_less_cancel_iff) simp_all\n  hence \"k < ln (ln (real N + 1))\" by simp\n  also have \"\\<dots> \\<le> norm (ln (ln (real N + 1)))\" by simp\n  finally show False using k(2)[of N] by simp\nqed\n\ncorollary prime_harmonic_series_diverges:\n  \"\\<not>convergent (\\<lambda>n. \\<Sum>p\\<leftarrow>primes_upto n. 1 / p)\"\n  using prime_harmonic_series_unbounded convergent_imp_Bseq by blast\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Prime_Harmonic_Series/Prime_Harmonic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.89029422102812, "lm_q1q2_score": 0.7766458382235751}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\ntheory AExp imports Main begin\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw{*\\snip{AExpaexpdef}{2}{1}{% *}\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw{*}%endsnip*}\n\ntext_raw{*\\snip{AExpavaldef}{1}{2}{% *}\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\ntext_raw{*}%endsnip*}\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext {* The same state more concisely: *}\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext {* A little syntax magic to write larger states compactly: *}\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\n*}\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext {* In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n*}\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext{* Note that this @{text\"<\\<dots>>\"} syntax works for any function space\n@{text\"\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\"} where @{text \"\\<tau>\\<^sub>2\"} has a @{text 0}. *}\n\n\nsubsection \"Constant Folding\"\n\ntext{* Evaluate constant subsexpressions: *}\n\ntext_raw{*\\snip{AExpasimpconstdef}{0}{2}{% *}\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext{* Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors: *}\n\ntext_raw{*\\snip{AExpplusdef}{0}{2}{% *}\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw{*\\snip{AExpasimpdef}{2}{0}{% *}\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntext{* Note that in @{const asimp_const} the optimized constructor was\ninlined. Making it a separate function @{const plus} improves modularity of\nthe code and the proofs. *}\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/IMP/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.8723473614033683, "lm_q1q2_score": 0.7766458088732723}}
{"text": "\n(* Title:      L2 Norm Integral\n   Author:     Omar A. Jasim <oajasim1@sheffield.ac.uk>, Sandor M. Veres <s.veres@sheffield.ac.uk>\n   Maintainer: Omar A. Jasim <oajasim1@sheffield.ac.uk>, Sandor M. Veres <s.veres@sheffield.ac.uk> \n*)\n\ntheory L2Norm_Integral\nimports \n\"~~/src/HOL/Probability/Set_Integral\"\n\"~~/Minkowski_Integral_Inequality\"\nbegin\n\ndefinition L2norm:: \"real measure \\<Rightarrow> (real \\<Rightarrow> real) \\<Rightarrow> real set \\<Rightarrow> real\" where\n  \"L2norm M f A = sqrt (LINT  t:A|M. (f t)\\<^sup>2)\"\n  \nlemma L2norm_cong1:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> L2norm M f A = L2norm M g B\"\n  unfolding L2norm_def by (metis indicator_simps(2) mult_zero_left real_scaleR_def)\n\nlemma strong_L2norm_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B =simp=> f x = g x\\<rbrakk> \\<Longrightarrow> L2norm M f A = L2norm M g B\"\n  unfolding L2norm_def simp_implies_def by (metis (full_types) L2norm_cong1 L2norm_def) \n\nlemma L2norm_nonneg: \n  shows \"L2norm M f A \\<ge> 0\"\nproof -\n  have \"\\<forall>t. (f t)\\<^sup>2 \\<ge> 0\" \n    by simp\n  then have \"(LINT  t:A|M. (f t)\\<^sup>2) \\<ge> 0\" \n    by (simp add: integral_nonneg_AE)\n  then have \"sqrt (LINT  t:A|M. (f t)\\<^sup>2) \\<ge> 0\" \n    by simp\n  from this L2norm_def show ?thesis \n    by metis \nqed\n\nlemma L2norm_zero: \"\\<forall>t\\<in>A. f t = 0 \\<Longrightarrow> L2norm M f A = 0\" unfolding L2norm_def \nproof -\n  assume \"\\<forall>t\\<in>A. f t = 0\"\n  then have \"\\<And>t. indicator A t *\\<^sub>R (f t)\\<^sup>2 = 0\"\n    by auto\n  then show \"sqrt (LINT t:A|M. (f t)\\<^sup>2) = 0\"\n    by (simp add: integral_eq_zero_AE)\nqed \n\nlemma L2norm_right_distrib:\n  fixes M a b c and f :: \"real \\<Rightarrow> real\"\n  assumes \"0 \\<le> c\" \"set_integrable M A f\" \n  shows \"c * L2norm M f A = L2norm M (\\<lambda>t. c * f t) A\"\nproof -\n  have \"c* (sqrt(LINT t:A|M. (f t)\\<^sup>2)) = sqrt(c\\<^sup>2 *(LINT t:A|M. (f t)\\<^sup>2))\" \n    by (simp add: assms real_sqrt_mult_distrib2) \n  then have \"c * sqrt(LINT t:A|M. (f t)\\<^sup>2) = sqrt(LINT t:A|M. c\\<^sup>2 * (f t)\\<^sup>2)\"\n    by (metis (no_types) set_integral_mult_right)\n  then have \"c * sqrt(LINT t:A|M. (f t)\\<^sup>2) = sqrt(LINT t:A|M. (c * f t)\\<^sup>2)\"\n    by (simp add: power_mult_distrib)\n  thus ?thesis\n    by (metis L2norm_def)\nqed\n\nlemma L2norm_left_distrib:\n  fixes M a b c and f :: \"real \\<Rightarrow> real\"\n  assumes \"0 \\<le> c\"  \"set_integrable M A f\" \n  shows \"L2norm M f A * c = L2norm M (\\<lambda>t. f t * c) A\"\nproof -\n  have \"sqrt (LINT t:A|M. (f t)\\<^sup>2) * c = sqrt((LINT t:A|M. (f t)\\<^sup>2) * c\\<^sup>2)\"\n    by (simp add: assms real_sqrt_mult_distrib2) \n  then have \"sqrt(LINT t:A|M. (f t)\\<^sup>2) * c = sqrt((LINT t:A|M. (f t)\\<^sup>2 * c\\<^sup>2))\"\n    by (metis (no_types) set_integral_mult_left)\n  then have \"sqrt (LINT t:A|M. (f t)\\<^sup>2) * c = sqrt((LINT t:A|M. (f t*c)\\<^sup>2 ))\"\n    by (simp add: power_mult_distrib) \n  thus ?thesis \n    by (metis L2norm_def)\nqed\n\nlemma L2norm_empty [simp]: \"L2norm M f {} = 0\"\n  unfolding L2norm_def by simp\n\nlemma L2norm_neq: \"L2norm M (\\<lambda>t. - f t) A = L2norm M (\\<lambda>t. f t) A\"\n  unfolding L2norm_def by fastforce\n\nlemma L2norm_neq1: \"L2norm M (-f) A = L2norm M (\\<lambda>t. f t) A\"\n  unfolding L2norm_def by fastforce\n \nlemma L2norm_triangle_ineq:\n  fixes f g ::  \"real \\<Rightarrow> real\"\n  assumes \"\\<And>t. t \\<in> A\"\n          \"set_integrable M A f\" \n          \"set_integrable M A g\"\n          \"set_integrable M A (\\<lambda>t. (f t)\\<^sup>2)\" \n          \"set_integrable M A (\\<lambda>t. (g t)\\<^sup>2)\"\n          \"set_integrable M A (\\<lambda>t. f t * g t)\"\n          \"(LINT t:A|M. (g t)\\<^sup>2) > 0\"\n  shows \"L2norm M (\\<lambda>t. f t + g t) A \\<le> L2norm M f A + L2norm M g A\"\nproof -\n  have \"sqrt(LINT t:A|M. (f t + g t)\\<^sup>2) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\n    using minkowski_integral_ineq assms by blast \n  thus ?thesis unfolding L2norm_def\n    by blast\nqed\n\nlemma L2norm_triangle_ineq_nq:\n  fixes f g ::  \"real \\<Rightarrow> real\"\n  assumes \"\\<And>t. t \\<in> A\"\n          \"set_integrable M A f\" \n          \"set_integrable M A g\"\n          \"set_integrable M A (\\<lambda>t. (f t)\\<^sup>2)\" \n          \"set_integrable M A (\\<lambda>t. (g t)\\<^sup>2)\"\n          \"set_integrable M A (\\<lambda>t. f t * g t)\"\n          \"(LINT t:A|M. (g t)\\<^sup>2) > 0\"\n  shows \"L2norm M (\\<lambda>t. f t - g t) A \\<le> L2norm M f A + L2norm M g A\"\nproof -\n  have \"sqrt(LINT t:A|M. (f t - g t)\\<^sup>2) \\<le> sqrt(LINT t:A|M. (f t)\\<^sup>2) + sqrt(LINT t:A|M. (g t)\\<^sup>2)\"\n    using assms minkowski_integral_ineq_ng mult_minus_right by blast\n  thus ?thesis unfolding L2norm_def \n    using L2norm_neq by fastforce\nqed\n\nend", "meta": {"author": "Formal-Methods-of-Robotics", "repo": "Small-Gain-theorem", "sha": "03a72aa4c2d794675636829fbf9330fdf884a90d", "save_path": "github-repos/isabelle/Formal-Methods-of-Robotics-Small-Gain-theorem", "path": "github-repos/isabelle/Formal-Methods-of-Robotics-Small-Gain-theorem/Small-Gain-theorem-03a72aa4c2d794675636829fbf9330fdf884a90d/L2Norm_Integral.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485602, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.7766160532802097}}
{"text": "(*  \n  Title:    PMF_OF_List.thy\n  Author:   Manuel Eberl, TU München\n\n  Creating PMFs from lists\n*)\n\nsection \\<open>Creating PMFs from lists\\<close>\n\ntheory PMF_Of_List\nimports Complex_Main \"~~/src/HOL/Probability/Probability\"\nbegin\n\n(* TODO Move *)\nlemma listsum_nonneg: \"(\\<And>x. x \\<in> set xs \\<Longrightarrow> (x :: 'a :: linordered_idom) \\<ge> 0) \\<Longrightarrow> listsum xs \\<ge> 0\"\n  by (induction xs) simp_all\n\nlemma listsum_map_filter:\n  \"listsum (map f (filter P xs)) = listsum (map (\\<lambda>x. if P x then f x else 0) xs)\"\n  by (induction xs) simp_all\n\nlemma listsum_cong:\n  assumes \"\\<And>x. x \\<in> set xs \\<Longrightarrow> f x = g x\"\n  shows    \"listsum (map f xs) = listsum (map g xs)\"\n  using assms by (induction xs) simp_all\n\nlemma ereal_listsum: \"listsum (map (\\<lambda>x. ereal (f x)) xs) = ereal (listsum (map f xs))\"\n  by (induction xs) simp_all\n(* END TODO *)\n\n\ndefinition pmf_of_list ::\" ('a \\<times> real) list \\<Rightarrow> 'a pmf\" where \n  \"pmf_of_list xs = embed_pmf (\\<lambda>x. listsum (map snd (filter (\\<lambda>z. fst z = x) xs)))\"\n\ndefinition pmf_of_list_wf where\n  \"pmf_of_list_wf xs \\<longleftrightarrow> (\\<forall>x\\<in>set (map snd xs) . x \\<ge> 0) \\<and> listsum (map snd xs) = 1\"\n\nlemma pmf_of_list_wfI:\n  \"(\\<And>x. x \\<in> set (map snd xs) \\<Longrightarrow> x \\<ge> 0) \\<Longrightarrow> listsum (map snd xs) = 1 \\<Longrightarrow> pmf_of_list_wf xs\"\n  unfolding pmf_of_list_wf_def by simp\n\nlemma pmf_of_list_aux:\n  assumes \"\\<And>x. x \\<in> set (map snd xs) \\<Longrightarrow> x \\<ge> 0\"\n  assumes \"listsum (map snd xs) = 1\"\n  shows \"(\\<integral>\\<^sup>+ x. ereal (listsum (map snd [z\\<leftarrow>xs . fst z = x])) \\<partial>count_space UNIV) = 1\"\nproof -\n  have \"(\\<integral>\\<^sup>+ x. ereal (listsum (map snd (filter (\\<lambda>z. fst z = x) xs))) \\<partial>count_space UNIV) =\n            (\\<integral>\\<^sup>+ x. ereal (listsum (map (\\<lambda>(x',p). indicator {x'} x * p) xs)) \\<partial>count_space UNIV)\"\n    by (intro nn_integral_cong, subst listsum_map_filter) (auto intro: listsum_cong)\n  also have \"\\<dots> = (\\<Sum>(x',p)\\<leftarrow>xs. (\\<integral>\\<^sup>+ x. ereal (indicator {x'} x * p) \\<partial>count_space UNIV))\"\n    using assms(1)\n  proof (induction xs)\n    case (Cons x xs)\n    have \"(\\<integral>\\<^sup>+ y. ereal (\\<Sum>(x', p)\\<leftarrow>x # xs. indicator {x'} y * p) \\<partial>count_space UNIV) = \n            (\\<integral>\\<^sup>+ y. ereal (indicator {fst x} y * snd x) + \n            ereal (\\<Sum>(x', p)\\<leftarrow>xs. indicator {x'} y * p) \\<partial>count_space UNIV)\"\n      by (simp add: plus_ereal.simps [symmetric] case_prod_unfold del: plus_ereal.simps)\n    also have \"\\<dots> = (\\<integral>\\<^sup>+ y. ereal (indicator {fst x} y * snd x) \\<partial>count_space UNIV) + \n                      (\\<integral>\\<^sup>+ y. ereal (\\<Sum>(x', p)\\<leftarrow>xs. indicator {x'} y * p) \\<partial>count_space UNIV)\"\n      by (intro nn_integral_add)\n         (force intro!: listsum_nonneg AE_I2 intro: Cons simp: indicator_def)+\n    also have \"(\\<integral>\\<^sup>+ y. ereal (\\<Sum>(x', p)\\<leftarrow>xs. indicator {x'} y * p) \\<partial>count_space UNIV) =\n               (\\<Sum>(x', p)\\<leftarrow>xs. (\\<integral>\\<^sup>+ y. ereal (indicator {x'} y * p) \\<partial>count_space UNIV))\"\n      using Cons(1) by (intro Cons) simp_all\n    finally show ?case by (simp add: case_prod_unfold)\n  qed simp\n  also have \"\\<dots> = (\\<Sum>(x',p)\\<leftarrow>xs. ereal p * (\\<integral>\\<^sup>+ x. indicator {x'} x \\<partial>count_space UNIV))\"\n    using assms(1)\n    by (intro listsum_cong, simp only: case_prod_unfold, subst nn_integral_cmult [symmetric])\n       (auto intro!: assms(1) simp: max_def times_ereal.simps [symmetric] mult_ac ereal_indicator\n             simp del: times_ereal.simps)+\n  also have \"\\<dots> = listsum (map snd xs)\" by (simp add: case_prod_unfold ereal_listsum)\n  also have \"\\<dots> = 1\" using assms(2) by simp\n  finally show ?thesis .\nqed\n\nlemma pmf_pmf_of_list:\n  assumes \"pmf_of_list_wf xs\"\n  shows   \"pmf (pmf_of_list xs) x = listsum (map snd (filter (\\<lambda>z. fst z = x) xs))\"\n  using assms pmf_of_list_aux[of xs] unfolding pmf_of_list_def pmf_of_list_wf_def\n  by (subst pmf_embed_pmf) (auto intro!: listsum_nonneg)+\n\nlemma set_pmf_of_list:\n  assumes \"pmf_of_list_wf xs\"\n  shows   \"set_pmf (pmf_of_list xs) \\<subseteq> set (map fst xs)\"\nproof clarify\n  fix x assume A: \"x \\<in> set_pmf (pmf_of_list xs)\"\n  show \"x \\<in> set (map fst xs)\"\n  proof (rule ccontr)\n    assume \"x \\<notin> set (map fst xs)\"\n    hence \"[z\\<leftarrow>xs . fst z = x] = []\" by (auto simp: filter_empty_conv)\n    with A assms show False by (simp add: pmf_pmf_of_list set_pmf_eq)\n  qed\nqed\n\nlemma finite_set_pmf_of_list:\n  assumes \"pmf_of_list_wf xs\"\n  shows   \"finite (set_pmf (pmf_of_list xs))\"\n  using assms by (rule finite_subset[OF set_pmf_of_list]) simp_all\n\nlemma emeasure_Int_set_pmf:\n  \"emeasure (measure_pmf p) (A \\<inter> set_pmf p) = emeasure (measure_pmf p) A\"\n  by (rule emeasure_eq_AE) (auto simp: AE_measure_pmf_iff)\n\nlemma measure_Int_set_pmf:\n  \"measure (measure_pmf p) (A \\<inter> set_pmf p) = measure (measure_pmf p) A\"\n  using emeasure_Int_set_pmf[of p A] by (simp add: Sigma_Algebra.measure_def)\n\nlemma measure_pmf_of_list:\n  assumes \"pmf_of_list_wf xs\"\n  shows   \"measure (pmf_of_list xs) A = listsum (map snd (filter (\\<lambda>x. fst x \\<in> A) xs))\"\nproof -\n  have \"emeasure (pmf_of_list xs) A = nn_integral (measure_pmf (pmf_of_list xs)) (indicator A)\"\n    by simp\n  also have \"\\<dots> = ereal (\\<Sum>x\\<in>set_pmf (pmf_of_list xs). indicator A x * pmf (pmf_of_list xs) x)\"\n    (is \"_ = ereal ?S\") using assms\n    by (subst nn_integral_measure_pmf_finite) \n       (simp_all add: finite_set_pmf_of_list ereal_indicator [symmetric] pmf_pmf_of_list)\n  also have \"?S = (\\<Sum>x\\<in>set (map fst xs). indicator A x * pmf (pmf_of_list xs) x)\"\n    using assms by (intro setsum.mono_neutral_left set_pmf_of_list) (auto simp: set_pmf_eq)\n  also have \"\\<dots> = (\\<Sum>x\\<in>set (map fst xs). indicator A x * \n                      listsum (map snd (filter (\\<lambda>z. fst z = x) xs)))\"\n    using assms by (simp add: pmf_pmf_of_list)\n  also have \"\\<dots> = (\\<Sum>x\\<in>set (map fst xs). listsum (map snd (filter (\\<lambda>z. fst z = x \\<and> x \\<in> A) xs)))\"\n    by (intro setsum.cong) (auto simp: indicator_def)\n  also have \"\\<dots> = (\\<Sum>x\\<in>set (map fst xs). (\\<Sum>xa = 0..<length xs.\n                     if fst (xs ! xa) = x \\<and> x \\<in> A then snd (xs ! xa) else 0))\"\n    by (intro setsum.cong refl, subst listsum_map_filter, subst listsum_setsum_nth) simp\n  also have \"\\<dots> = (\\<Sum>xa = 0..<length xs. (\\<Sum>x\\<in>set (map fst xs). \n                     if fst (xs ! xa) = x \\<and> x \\<in> A then snd (xs ! xa) else 0))\"\n    by (rule setsum.commute)\n  also have \"\\<dots> = (\\<Sum>xa = 0..<length xs. if fst (xs ! xa) \\<in> A then \n                     (\\<Sum>x\\<in>set (map fst xs). if x = fst (xs ! xa) then snd (xs ! xa) else 0) else 0)\"\n    by (auto intro!: setsum.cong setsum.neutral)\n  also have \"\\<dots> = (\\<Sum>xa = 0..<length xs. if fst (xs ! xa) \\<in> A then snd (xs ! xa) else 0)\"\n    by (intro setsum.cong refl) (simp_all add: setsum.delta)\n  also have \"\\<dots> = listsum (map snd (filter (\\<lambda>x. fst x \\<in> A) xs))\"\n    by (subst listsum_map_filter, subst listsum_setsum_nth) simp_all\n  finally show ?thesis by (simp add: Sigma_Algebra.measure_def)\nqed\n\nend", "meta": {"author": "pruvisto", "repo": "SDS", "sha": "e0b280bff615c917314285b374d77416c51ed39c", "save_path": "github-repos/isabelle/pruvisto-SDS", "path": "github-repos/isabelle/pruvisto-SDS/SDS-e0b280bff615c917314285b374d77416c51ed39c/thys/Randomised_Social_Choice/PMF_Of_List.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765210631688, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7765987085149515}}
{"text": "\ntheory Simplicial_complex\n  imports \n    Boolean_functions\nbegin\n\nsection\\<open>Simplicial Complexes\\<close>\n\nlemma Pow_singleton: \"Pow {a} = {{},{a}}\" by auto\n\nlemma Pow_pair: \"Pow {a,b} = {{},{a},{b},{a,b}}\" by auto\n\nlocale simplicial_complex \n  = fixes n::\"nat\"\nbegin\n\ntext\\<open>A simplex (in $n$ vertexes) is any set of vertexes, \n  including the empty set.\\<close>\n\ndefinition simplices :: \"nat set set\"\n  where \"simplices = Pow {0..<n}\"\n\nlemma \"{} \\<in> simplices\"\n  unfolding simplices_def by simp\n\nlemma \"{0..<n} \\<in> simplices\"\n  unfolding simplices_def by simp\n\n\n\ntext\\<open>A simplicial complex (in $n$ vertexes) is a collection of \n  sets of vertexes such that every subset of \n  a set of vertexes also belongs to the simplicial complex.\\<close>\n\ndefinition simplicial_complex :: \"nat set set => bool\"\n  where \"simplicial_complex K \\<equiv>  (\\<forall>\\<sigma>\\<in>K. (\\<sigma> \\<in> simplices) \\<and> (Pow \\<sigma>) \\<subseteq> K)\"\n\nlemma simplicial_complex_empty_set: \"simplicial_complex {}\"\n  unfolding simplicial_complex_def \n  unfolding simplices_def by simp\n\nlemma simplicial_complex_contains_empty_set: \"simplicial_complex {{}}\"\n  unfolding simplicial_complex_def \n  unfolding simplices_def by simp\n\nlemma simplicial_complex_either_empty_or_contains_empty:\n  fixes K::\"nat set set\"\n  assumes k: \"simplicial_complex K\"\n  shows \"K = {} \\<or> {} \\<in> K\" using k unfolding simplicial_complex_def Pow_def by auto\n\nlemma \n  finite_simplicial_complex:\n  assumes \"simplicial_complex K\"\n  shows \"finite K\"\n  by (metis assms finite_Pow_iff finite_atLeastLessThan rev_finite_subset simplices_def simplicial_complex_def subsetI)\n\nlemma finite_simplices:\n  assumes \"simplicial_complex K\"\n  and \"v \\<in> K\"\nshows \"finite v\"\n  using assms finite_simplex simplicial_complex.simplicial_complex_def by blast\n\n\ndefinition simplicial_complex_set :: \"nat set set set\"\n  where \"simplicial_complex_set = (Collect simplicial_complex)\"\n\nlemma\n  simplicial_complex_monotone:\n  fixes K::\"nat set set\"\n  assumes k: \"simplicial_complex K\" and s: \"s \\<in> K\" and rs: \"r \\<subseteq> s\"\n  shows \"r \\<in> K\"\n  using k rs s\n  unfolding simplicial_complex_def Pow_def by auto\n\ntext\\<open>One example of simplicial complex with four simplices.\\<close>\n\nlemma \n  assumes three: \"(3::nat) < n\"\n  shows \"simplicial_complex {{},{0},{1},{2},{3}}\"\n  apply (simp_all add: Pow_singleton simplicial_complex_def simplices_def)\n  using Suc_lessD three by presburger\n\nlemma \"\\<not> simplicial_complex {{0,1},{1}}\"\n  by (simp add: Pow_pair simplicial_complex_def)\n\ntext\\<open>Another example of simplicial complex with five simplices.\\<close>\n\nlemma \n  assumes three: \"(3::nat) < n\"\n  shows \"simplicial_complex {{},{0},{1},{2},{3},{0,1}}\"\n  apply (simp add: Pow_pair Pow_singleton simplicial_complex_def simplices_def)\n  using Suc_lessD three by presburger\n\ntext\\<open>Another example of simplicial complex with ten simplices.\\<close>\n\nlemma \n  assumes three: \"(3::nat) < n\"\n  shows \"simplicial_complex\n    {{2,3},{1,3},{1,2},{0,3},{0,2},{3},{2},{1},{0},{}}\"\n  apply (simp add: Pow_pair Pow_singleton simplicial_complex_def simplices_def)\n  using Suc_lessD three by presburger\n\nend\n\nsection\\<open>Simplicial complex induced by a monotone Boolean function\\<close>\n\ntext\\<open>In this section we introduce the definition of the \n  simplicial complex induced by a monotone Boolean function, \n  following the definition in Scoville~\\cite[Def. 6.9]{SC19}.\\<close>\n\ntext\\<open>First we introduce the set of tuples for which \n  a Boolean function is @{term False}.\\<close>\n\ndefinition ceros_of_boolean_input :: \"bool vec => nat set\"\n  where \"ceros_of_boolean_input v = {x. x < dim_vec v \\<and> vec_index v x = False}\"\n\nlemma\n  ceros_of_boolean_input_l_dim:\n  assumes a: \"a \\<in> ceros_of_boolean_input v\"\n  shows \"a < dim_vec v\"\n  using a unfolding ceros_of_boolean_input_def by simp\n\nlemma \"ceros_of_boolean_input v = {x. x < dim_vec v \\<and> \\<not> vec_index v x}\"\n  unfolding ceros_of_boolean_input_def by simp\n\nlemma\n  ceros_of_boolean_input_complementary:\n  shows \"ceros_of_boolean_input v = {x. x < dim_vec v} - {x. vec_index v x}\"\n  unfolding ceros_of_boolean_input_def by auto\n\nlemma (in simplicial_complex) vec_in_simplices:\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"ceros_of_boolean_input v \\<in> simplices\"\n  using assms unfolding carrier_vec_def simplices_def ceros_of_boolean_input_def\n  by auto\n\n(*lemma ceros_in_UNIV: \"ceros_of_boolean_input f \\<subseteq> (UNIV::nat set)\"\n  using subset_UNIV .*)\n\nlemma monotone_ceros_of_boolean_input:\n  fixes r and s::\"bool vec\"\n  assumes r_le_s: \"r \\<le> s\"\n  shows \"ceros_of_boolean_input s \\<subseteq> ceros_of_boolean_input r\"\nproof (intro subsetI, unfold ceros_of_boolean_input_def, intro CollectI, rule conjI)\n  fix x \n  assume \"x \\<in> {x. x < dim_vec s \\<and> vec_index s x = False}\" \n  hence xl: \"x < dim_vec s\" and nr: \"vec_index s x = False\" by simp_all\n  show \"vec_index r x = False\"\n    using r_le_s nr xl unfolding less_eq_vec_def\n    by auto\n  show \"x < dim_vec r\"\n  using r_le_s xl unfolding less_eq_vec_def\n    by auto\nqed\n\n\ntext\\<open>We introduce here instantiations of the typ\\<open>bool\\<close> \n  type for the type classes class\\<open>zero\\<close> and class\\<open>one\\<close>\n  that will simplify notation at some points:\\<close>\n\ninstantiation bool :: \"{zero,one}\"\nbegin\n\ndefinition\n zero_bool_def: \"0 == False\"\n\ndefinition\n one_bool_def: \"1 == True\"\n\ninstance  proof  qed\n\nend\n\ntext\\<open>Definition of the simplicial complex induced \n  by a Boolean function \\<open>f\\<close> in dimension \\<open>n\\<close>.\\<close>\n\ndefinition\n  simplicial_complex_induced_by_monotone_boolean_function\n    :: \"nat => (bool vec => bool) => nat set set\"\n  where \"simplicial_complex_induced_by_monotone_boolean_function n f =\n        {y. \\<exists>x. dim_vec x = n \\<and> f x \\<and> ceros_of_boolean_input x = y}\"\n\ntext\\<open>The simplicial complex induced by a Boolean function \n  is a subset of the powerset of the set of vertexes.\\<close>\n\nlemma\n  simplicial_complex_induced_by_monotone_boolean_function_subset:\n  \"simplicial_complex_induced_by_monotone_boolean_function n (v::bool vec => bool)\n    \\<subseteq> Pow (({0..n}::nat set))\"\n  using ceros_of_boolean_input_def \n   simplicial_complex_induced_by_monotone_boolean_function_def\n  by force\n\ncorollary\n  \"simplicial_complex_induced_by_monotone_boolean_function n (v::bool vec => bool)\n    \\<subseteq> Pow ((UNIV::nat set))\" by simp\n\ntext\\<open>The simplicial complex induced by a \n  monotone Boolean function is a simplicial complex.\n  This result is proven in Scoville as part of the \n  proof of Proposition 6.16~\\cite[Prop. 6.16]{SC19}.\\<close>\n\ncontext simplicial_complex\nbegin\n\nlemma\n  monotone_bool_fun_induces_simplicial_complex:\n  assumes mon: \"boolean_functions.monotone_bool_fun n f\"\n  shows \"simplicial_complex (simplicial_complex_induced_by_monotone_boolean_function n f)\"\n  unfolding simplicial_complex_def\nproof (rule, unfold simplicial_complex_induced_by_monotone_boolean_function_def, safe)\n    fix \\<sigma> :: \"nat set\" and x :: \"bool vec\"\n    assume fx: \"f x\" and dim_vec_x: \"n = dim_vec x\"\n    show \"ceros_of_boolean_input x \\<in> simplicial_complex.simplices (dim_vec x)\"\n      using ceros_of_boolean_input_def dim_vec_x simplices_def by force\n  next\n    fix \\<sigma> :: \"nat set\" and x :: \"bool vec\" and \\<tau> :: \"nat set\"\n    assume fx: \"f x\" and dim_vec_x: \"n = dim_vec x\" and tau_def: \"\\<tau> \\<subseteq> ceros_of_boolean_input x\"\n    show \"\\<exists>xb. dim_vec xb = dim_vec x \\<and> f xb \\<and> ceros_of_boolean_input xb = \\<tau>\"\n    proof (rule exI [of _ \"vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)\"], intro conjI)\n     show \"dim_vec (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)) = dim_vec x\"\n      unfolding dim_vec using dim_vec_x .\n     from mon have mono: \"mono_on f (carrier_vec n)\" \n      unfolding boolean_functions.monotone_bool_fun_def .\n     show \"f (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True))\"\n     proof -\n      have \"f x \\<le> f (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True))\"\n      proof (rule mono_onD [OF mono])\n        show \"x \\<in> carrier_vec n\" using dim_vec_x by simp\n        show \"vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True) \\<in> carrier_vec n\" by simp\n        show \"x \\<le> vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)\" \n          using tau_def dim_vec_x unfolding ceros_of_boolean_input_def\n          using less_eq_vec_def by fastforce\n      qed\n      thus ?thesis using fx by simp\n    qed\n    show \"ceros_of_boolean_input (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)) = \\<tau>\"\n      using \\<open>\\<tau> \\<subseteq> ceros_of_boolean_input x\\<close> ceros_of_boolean_input_def dim_vec_x by auto\n  qed\nqed\n\nend\n\ntext\\<open>Example 6.10 in Scoville, the threshold function \n  for $2$ in dimension $4$ (with vertexes $0$,$1$,$2$,$3$)\\<close>\n\ndefinition bool_fun_threshold_2_3 :: \"bool vec => bool\"\n  where \"bool_fun_threshold_2_3 = (\\<lambda>v. if 2 \\<le> count_true v then True else False)\"\n\nlemma set_list_four: shows \"{0..<4} = set [0,1,2,3::nat]\" by auto\n\nlemma comp_fun_commute_lambda: \n  \"comp_fun_commute_on UNIV ((+)\n  \\<circ> (\\<lambda>i. if vec 4 f $ i then 1 else (0::nat)))\"\n  unfolding comp_fun_commute_on_def by auto\n\nlemma \"bool_fun_threshold_2_3\n          (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False)) = True\"\n  unfolding bool_fun_threshold_2_3_def \n  unfolding count_true_def \n  unfolding dim_vec\n  unfolding sum.eq_fold\n  using index_vec [of _ 4]\n  apply auto\n  unfolding set_list_four\n  unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n  by simp\n\nlemma\n  \"0 \\<notin> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"1 \\<notin> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"2 \\<in> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"3 \\<in> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"{2,3} \\<subseteq> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  unfolding ceros_of_boolean_input_def by simp_all\n\nlemma \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i = 3 then True else False)) = False\"\n  unfolding bool_fun_threshold_2_3_def \n  unfolding count_true_def\n  unfolding dim_vec\n  unfolding sum.eq_fold\n  using index_vec [of _ 4]\n  apply auto\n  unfolding set_list_four\n  unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n  by simp\n\nlemma \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i = 0 then False else True))\"\n  unfolding bool_fun_threshold_2_3_def \n  unfolding count_true_def\n  unfolding dim_vec\n  unfolding sum.eq_fold\n  using index_vec [of _ 4]\n  apply auto\n  unfolding set_list_four\n  unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n  by simp\n\nsection\\<open>The simplicial complex induced by the threshold function\\<close>\n\nlemma\n  empty_set_in_simplicial_complex_induced:\n  \"{} \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n  unfolding bool_fun_threshold_2_3_def\n  apply rule\n  apply (rule exI [of _ \"vec 4 (\\<lambda>x. True)\"])\n  unfolding count_true_def ceros_of_boolean_input_def by auto\n\nlemma singleton_in_simplicial_complex_induced:\n  assumes x: \"x < 4\"\n  shows \"{x} \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  (is \"?A \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\")\nproof (unfold simplicial_complex_induced_by_monotone_boolean_function_def, rule,\n      rule exI [of _ \"vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)\"], \n      intro conjI)\n  show \"dim_vec (vec 4 (\\<lambda>i. if i \\<in> {x} then False else True)) = 4\" by simp\n  show \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True))\"\n    unfolding bool_fun_threshold_2_3_def \n    unfolding count_true_def\n    unfolding dim_vec\n    unfolding sum.eq_fold\n    using index_vec [of _ 4]\n    apply auto\n    unfolding set_list_four\n    unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n    by simp\n  show \"ceros_of_boolean_input (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)) = ?A\"\n    unfolding ceros_of_boolean_input_def using x by auto\nqed\n\nlemma pair_in_simplicial_complex_induced:\n  assumes x: \"x < 4\" and y: \"y < 4\"\n  shows \"{x,y} \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  (is \"?A \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\")\nproof (unfold simplicial_complex_induced_by_monotone_boolean_function_def, rule,\n      rule exI [of _ \"vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)\"], \n      intro conjI)\n  show \"dim_vec (vec 4 (\\<lambda>i. if i \\<in> {x, y} then False else True)) = 4\" by simp\n  show \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True))\"\n    unfolding bool_fun_threshold_2_3_def \n    unfolding count_true_def\n    unfolding dim_vec\n    unfolding sum.eq_fold\n    using index_vec [of _ 4]\n    apply auto\n    unfolding set_list_four\n    unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n    by simp\n  show \"ceros_of_boolean_input (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)) = ?A\"\n    unfolding ceros_of_boolean_input_def using x y by auto\nqed\n\nlemma finite_False: \"finite {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False}\" by auto\n\nlemma finite_True: \"finite {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True}\" by auto\n\nlemma UNIV_disjoint: \"{x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True} \n  \\<inter> {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False} = {}\"\n  by auto\n\nlemma UNIV_union: \"{x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True} \n  \\<union> {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False} = {x. x < dim_vec a}\"\n  by auto\n\nlemma card_UNIV_union:\n  \"card {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True}\n  + card {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False} \n  = card {x. x < dim_vec a}\"\n  (is \"card ?true + card ?false = _\")\nproof -\n  have \"card ?true + card ?false = card (?true \\<union> ?false) + card (?true \\<inter> ?false)\"\n    using card_Un_Int [OF finite_True [of a] finite_False [of a]] .\n  also have \"... = card {x. x < dim_vec a}\"\n    unfolding UNIV_union UNIV_disjoint by simp\n  finally show ?thesis by simp\nqed\n\nlemma card_complementary:\n  \"card (ceros_of_boolean_input v)\n    + card {x. x < (dim_vec v) \\<and> (vec_index v x = True)} = (dim_vec v)\"\n  unfolding ceros_of_boolean_input_def\n  using card_UNIV_union [of v] by simp\n\ncorollary\n  card_ceros_of_boolean_input:\n  shows \"card (ceros_of_boolean_input a) \\<le> dim_vec a\"\n using card_complementary [of a] by simp\n\nlemma\n  vec_fun:\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"\\<exists>f. v = vec n f\" using assms unfolding carrier_vec_def by fastforce\n\ncorollary\n  assumes \"dim_vec v = n\"\n  shows \"\\<exists>f. v = vec n f\"\n  using carrier_vecI [OF assms] unfolding carrier_vec_def by fastforce\n\nlemma\n  vec_l_eq:\n  assumes \"i < n\"\n  shows \"vec (Suc n) f $ i = vec n f $ i\"\n  by (simp add: assms less_SucI)\n\nlemma\n  card_boolean_function:\n  assumes d: \"v \\<in> carrier_vec n\"\n  shows \"card {x. x < n  \\<and> v $ x = True} = (\\<Sum>i = 0..<n. if v $ i then 1 else (0::nat))\"\nusing d proof (induction n arbitrary: v rule: nat_less_induct)\n  case (1 n)\n  assume hyp: \"\\<forall>m<n. \\<forall>x. x \\<in> carrier_vec m \\<longrightarrow> \n      card {xa. xa < m \\<and> x $ xa = True} = (\\<Sum>i = 0..<m. if x $ i then 1 else 0)\"\n    and d: \"v \\<in> carrier_vec n\"\n  show \"card {x. x < n \\<and> v $ x = True} = (\\<Sum>i = 0..<n. if v $ i then 1 else 0)\"\n  using d proof (cases n)\n    case 0\n    then show ?thesis by simp\n  next\n    case (Suc m)\n    assume v: \"v \\<in> carrier_vec n\"\n    obtain f :: \"nat => bool\" where v_f: \"v = vec n f\" using vec_fun [OF v] by auto\n    have \"card {x. x < m \\<and> (vec m f) $ x = True} = (\\<Sum>i = 0..<m. if (vec m f) $ i then 1 else 0)\"\n      using hyp v Suc by simp\n    show ?thesis unfolding v_f unfolding Suc\n    proof (cases \"vec (Suc m) f $ m = True\") \n      case True\n      have one: \"{x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n          ({x. x < m \\<and> vec (Suc m) f $ x = True} \\<union> {x. x = m \\<and> (vec (Suc m) f) $ x = True})\"\n        by auto\n      have two: \"disjnt {x. x < m \\<and> vec (Suc m) f $ x = True} {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        using disjnt_iff by blast\n      have \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True}\n            = card {x. x < m \\<and> (vec (Suc m) f) $ x = True} + card {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        unfolding one\n        by (rule card_Un_disjnt [OF _ _ two], simp_all)\n      also have \"... = card {x. x < m \\<and> (vec  m f) $ x = True} + 1\"\n      proof -\n        have one: \"{x. x < m \\<and> vec (Suc m) f $ x = True} = {x. x < m \\<and> vec m f $ x = True}\"\n          using vec_l_eq [of _ m] by auto\n        have eq: \"{x. x = m \\<and> vec (Suc m) f $ x = True} = {m}\" using True by auto\n        hence two: \"card {x. x = m \\<and> vec (Suc m) f $ x = True} = 1\" by simp\n        show ?thesis using one two by simp\n      qed\n      finally have lhs: \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} = card {x. x < m \\<and> vec m f $ x = True} + 1\" .\n      have \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) = \n           (\\<Sum>i = 0..<m. if vec (Suc m) f $ i then 1 else 0) + (if vec (Suc m) f $ m then 1 else 0)\"\n        by simp\n      also have \"... = (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0) + 1\"\n        using vec_l_eq [of _ m] True by simp\n      finally have rhs: \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) = \n        (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0) + 1\" .\n      show \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n        (\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0)\"\n        unfolding lhs rhs using hyp Suc by simp\n    next\n      case False\n      have one: \"{x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n          ({x. x < m \\<and> vec (Suc m) f $ x = True} \\<union> {x. x = m \\<and> (vec (Suc m) f) $ x = True})\"\n        by auto\n      have two: \"disjnt {x. x < m \\<and> vec (Suc m) f $ x = True} {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        using disjnt_iff by blast\n      have \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True}\n            = card {x. x < m \\<and> (vec (Suc m) f) $ x = True} + card {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        unfolding one\n        by (rule card_Un_disjnt [OF _ _ two], simp_all)\n      also have \"... = card {x. x < m \\<and> (vec  m f) $ x = True} + 0\"\n      proof -\n        have one: \"{x. x < m \\<and> vec (Suc m) f $ x = True} = {x. x < m \\<and> vec m f $ x = True}\"\n          using vec_l_eq [of _ m] by auto\n        have eq: \"{x. x = m \\<and> vec (Suc m) f $ x = True} = {}\" using False by auto\n        hence two: \"card {x. x = m \\<and> vec (Suc m) f $ x = True} = 0\" by simp\n        show ?thesis using one two by simp\n      qed\n      finally have lhs: \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} = card {x. x < m \\<and> vec m f $ x = True} + 0\" .\n      have \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) = \n           (\\<Sum>i = 0..<m. if vec (Suc m) f $ i then 1 else 0) + (if vec (Suc m) f $ m then 1 else 0)\"\n        by simp\n      also have \"... = (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0)\"\n        using vec_l_eq [of _ m] False by simp\n      finally have rhs: \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) = \n        (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0)\" .\n      show \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n        (\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0)\"\n        unfolding lhs rhs using hyp Suc by simp\n    qed\n  qed\nqed\n\nlemma card_ceros_count_UNIV:\n  shows \"card (ceros_of_boolean_input a) + count_true ((a::bool vec)) = dim_vec a\"\n  using card_complementary [of a]\n  using card_boolean_function\n  unfolding ceros_of_boolean_input_def\n  unfolding count_true_def by simp\n\ntext\\<open>We calculate the carrier set of the @{const ceros_of_boolean_input} \n  function for dimensions $2$, $3$ and $4$.\\<close>\n\n\ntext\\<open>Vectors of dimension $2$.\\<close>\n\nlemma\n  dim_vec_2_cases:\n  assumes dx: \"dim_vec x = 2\"\n  shows \"(x $ 0 = x $ 1 = True) \\<or> (x $ 0 = False \\<and> x $ 1 = True)\n       \\<or> (x $ 0 = True \\<and> x $ 1 = False) \\<or> (x $ 0 = x $ 1 = False)\"\n  by auto\n\nlemma tt_2: assumes dx: \"dim_vec x = 2\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = True\"\n  shows \"ceros_of_boolean_input x = {}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma tf_2: assumes dx: \"dim_vec x = 2\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = False\"\n  shows \"ceros_of_boolean_input x = {1}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma ft_2: assumes dx: \"dim_vec x = 2\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = True\"\n  shows \"ceros_of_boolean_input x = {0}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma ff_2: assumes dx: \"dim_vec x = 2\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = False\"\n  shows \"ceros_of_boolean_input x = {0,1}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma\n  assumes dx: \"dim_vec x = 2\"\n  shows \"ceros_of_boolean_input x \\<in> {{},{0},{1},{0,1}}\"\n  using dim_vec_2_cases [OF ]\n  using tt_2 [OF dx] tf_2 [OF dx] ft_2 [OF dx] ff_2 [OF dx]\n  by (metis insertCI)\n\ntext\\<open>Vectors of dimension $3$.\\<close>\n\nlemma less_3_cases:\n  assumes n: \"n < 3\" shows \"n = 0 \\<or> n = 1 \\<or> n = (2::nat)\" \n  using n by linarith\n\nlemma\n  dim_vec_3_cases:\n  assumes dx: \"dim_vec x = 3\"\n  shows \"(x $ 0 = x $ 1 = x $ 2 = False) \\<or> (x $ 0 = x $ 1 = False \\<and> x $ 2 = True)\n       \\<or> (x $ 0 = x $ 2 = False \\<and> x $ 1 = True) \\<or> (x $ 0 = False \\<and> x $ 1 = x $ 2 = True)\n       \\<or> (x $ 0 = True \\<and> x $ 1 = x $ 2 = False) \\<or> (x $ 0 = x $ 2 = True \\<and> x $ 1 = False)\n       \\<or> (x $ 0 = x $ 1 = True \\<and> x $ 2 = False) \\<or> (x $ 0 = x $ 1 = x $ 2 = True)\"\n  by auto\n\nlemma fff_3: assumes dx: \"dim_vec x = 3\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {0,1,2}\"\n  using dx be \n  unfolding ceros_of_boolean_input_def \n  using less_3_cases by auto\n\nlemma fft_3: assumes dx: \"dim_vec x = 3\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {0,1}\"\n  using dx be unfolding ceros_of_boolean_input_def \n  using less_3_cases by auto\n\nlemma ftf_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {0,2}\"\n  using dx be unfolding ceros_of_boolean_input_def \n  using less_3_cases by fastforce\n\nlemma ftt_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {0}\"\n  using dx be unfolding ceros_of_boolean_input_def \n  using less_3_cases by auto\n\nlemma tff_3: assumes dx: \"dim_vec x = 3\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {1,2}\"\n  using dx be unfolding ceros_of_boolean_input_def \n  using less_3_cases by auto\n\nlemma tft_3: assumes dx: \"dim_vec x = 3\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {1}\"\n  using dx be unfolding ceros_of_boolean_input_def \n  using less_3_cases by auto\n\nlemma ttf_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {2}\"\n  using dx be unfolding ceros_of_boolean_input_def \n  using less_3_cases by fastforce\n\nlemma ttt_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma\n  assumes dx: \"dim_vec x = 3\"\n  shows \"ceros_of_boolean_input x \\<in> {{},{0},{1},{2},{0,1},{0,2},{1,2},{0,1,2}}\"\n  using dim_vec_3_cases [OF ]\n  using fff_3 [OF dx] fft_3 [OF dx] ftf_3 [OF dx] ftt_3 [OF dx]\n  using tff_3 [OF dx] tft_3 [OF dx] ttf_3 [OF dx] ttt_3 [OF dx]\n  by (smt (z3) insertCI)\n\ntext\\<open>Vectors of dimension $4$.\\<close>\n\nlemma less_4_cases:\n  assumes n: \"n < 4\"\n  shows \"n = 0 \\<or> n = 1 \\<or> n = 2 \\<or> n = (3::nat)\"\n  using n by linarith\n\nlemma\n  dim_vec_4_cases:\n  assumes dx: \"dim_vec x = 4\"\n  shows \"(x $ 0 = x $ 1 = x $ 2 = x $ 3 = False) \\<or> (x $ 0 = x $ 1 = x $ 2 = False \\<and> x $ 3 = True)\n       \\<or> (x $ 0 = x $ 1 = x $ 3 = False \\<and> x $ 2 = True) \\<or> (x $ 0 = x $ 1 = False \\<and> x $ 2 = x $ 3 = True)\n       \\<or> (x $ 0 = x $ 2 = x $ 3 = False \\<and> x $ 1 = True) \\<or> (x $ 0 = x $ 2 = False \\<and> x $ 1 = x $ 3 = True)\n       \\<or> (x $ 0 = x $ 3 = False \\<and> x $ 1 = x $ 2 = True) \\<or> (x $ 0 = False \\<and> x $ 1 = x $ 2 = x $ 3 = True) \n       \\<or> (x $ 0 = True \\<and> x $ 1 = x $ 2 = x $ 3 = False) \\<or> (x $ 0 = x $ 3 = True \\<and> x $ 1 = x $ 2 = False)\n       \\<or> (x $ 0 = x $ 2 = True \\<and> x $ 1 = x $ 3 = False) \\<or> (x $ 0 = x $ 2 = x $ 3 = True \\<and> x $ 1 = False)\n       \\<or> (x $ 0 = x $ 1 = True \\<and> x $ 2 = x $ 3 = False) \\<or> (x $ 0 = x $ 1 = x $ 3 = True \\<and> x $ 2 = False)\n       \\<or> (x $ 0 = x $ 1 = x $ 2 = True \\<and> x $ 3 = False) \\<or> (x $ 0 = x $ 1 = x $ 2 = x $ 3 = True)\"\n  by blast\n\nlemma ffff_4: assumes dx: \"dim_vec x = 4\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,1,2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma ffft_4: assumes dx: \"dim_vec x = 4\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0,1,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma fftf_4: assumes dx: \"dim_vec x = 4\" \n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,1,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma fftt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0,1}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma ftff_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma ftft_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma fttf_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma fttt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma tfff_4: assumes dx: \"dim_vec x = 4\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {1,2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma tfft_4: assumes dx: \"dim_vec x = 4\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {1,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma tftf_4: assumes dx: \"dim_vec x = 4\" \n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {1,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma tftt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {1}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma ttff_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma ttft_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma tttf_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma tttt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def \n  using less_4_cases by auto\n\nlemma\n  ceros_of_boolean_input_set:\n  assumes dx: \"dim_vec x = 4\"\n  shows \"ceros_of_boolean_input x \\<in> {{},{0},{1},{2},{3},{0,1},{0,2},{0,3},{1,2},{1,3},{2,3},\n    {0,1,2},{0,1,3},{0,2,3},{1,2,3},{0,1,2,3}}\"\n  using dim_vec_4_cases [OF ]\n  using ffff_4 [OF dx] ffft_4 [OF dx] fftf_4 [OF dx] fftt_4 [OF dx]\n  using ftff_4 [OF dx] ftft_4 [OF dx] fttf_4 [OF dx] fttt_4 [OF dx]\n  using tfff_4 [OF dx] tfft_4 [OF dx] tftf_4 [OF dx] tftt_4 [OF dx]\n  using ttff_4 [OF dx] ttft_4 [OF dx] tttf_4 [OF dx] tttt_4 [OF dx]\n  by (smt (z3) insertCI)\n\ncontext simplicial_complex\nbegin\n\ntext\\<open>The simplicial complex induced by the monotone Boolean function\n  @{const bool_fun_threshold_2_3} has the following explicit expression.\\<close>\n\nlemma\n  simplicial_complex_induced_by_monotone_boolean_function_4_bool_fun_threshold_2_3 [symmetric, code]:\n  shows \"{{},{0},{1},{2},{3},{0,1},{0,2},{0,3},{1,2},{1,3},{2,3}}\n    = simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  (is \"{{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j} = _\")\nproof (rule)\n  show \"{{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\n    \\<subseteq> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n    by (simp add:\n        empty_set_in_simplicial_complex_induced\n        singleton_in_simplicial_complex_induced pair_in_simplicial_complex_induced)+\n  show \"simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\n    \\<subseteq> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding bool_fun_threshold_2_3_def\n    proof\n    fix y::\"nat set\"\n    assume y: \"y \\<in> {y. \\<exists>x. dim_vec x = 4 \\<and> (if 2 \\<le> count_true x then True else False) \\<and> ceros_of_boolean_input x = y}\"\n      then obtain x::\"bool vec\" \n        where ct_ge_2: \"(if 2 \\<le> count_true x then True else False)\" \n          and cx: \"ceros_of_boolean_input x = y\" and dx: \"dim_vec x = 4\" by auto\n      have \"count_true x + card (ceros_of_boolean_input x) = dim_vec x\"\n       using card_ceros_count_UNIV [of x] by simp\n      hence \"card (ceros_of_boolean_input x) \\<le> 2\"\n        using ct_ge_2\n        using card_boolean_function\n        using dx by presburger\n      hence card_le: \"card y \\<le> 2\" using cx by simp\n      have \"y \\<in> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n      proof (rule ccontr)\n        assume \"y \\<notin> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n        then have y_nin: \"y \\<notin> set [{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j]\" by simp\n        have \"y \\<in> set [{0,1,2},{0,1,3},{0,2,3},{1,2,3},{0,1,2,3}]\"\n          using ceros_of_boolean_input_set [OF dx] y_nin\n          unfolding cx by simp\n        hence \"card y \\<ge> 3\" by auto\n        thus False using card_le by simp\n      qed\n      then show \"y \\<in> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n      by simp\n  qed\nqed\n\nend\n\nend\n", "meta": {"author": "jmaransay", "repo": "morse", "sha": "99d05d63fad13f5b4827f2f656ebbad989e90e09", "save_path": "github-repos/isabelle/jmaransay-morse", "path": "github-repos/isabelle/jmaransay-morse/morse-99d05d63fad13f5b4827f2f656ebbad989e90e09/Simplicial_complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7765292932726541}}
{"text": "(* Title:      From Semilattices to Dioids\n   Author:     Alasdair Armstrong, Georg Struth, Tjark Weber\n   Maintainer: Georg Struth <g.struth at sheffield.ac.uk>\n               Tjark Weber <tjark.weber at it.uu.se>\n*)\n\nsection \\<open>Dioids\\<close>\n\ntheory Dioid\nimports Signatures\nbegin\n\nsubsection \\<open>Join Semilattices\\<close> \n\ntext \\<open>Join semilattices can be axiomatised order-theoretically or\nalgebraically. A join semilattice (or upper semilattice) is either a\nposet in which every pair of elements has a join (or least upper\nbound), or a set endowed with an associative, commutative, idempotent\nbinary operation. It is well known that the order-theoretic definition\ninduces the algebraic one and vice versa. We start from the algebraic\naxiomatisation because it is easily expandable to dioids, using\nIsabelle's type class mechanism.\n\nIn Isabelle/HOL, a type class @{class semilattice_sup} is available.\nAlas, we cannot use this type class because we need the symbol~\\<open>+\\<close> for the join operation in the dioid expansion and subclass\nproofs in Isabelle/HOL require the two type classes involved to have\nthe same fixed signature.\n\nUsing {\\em add\\_assoc} as a name for the first assumption in class\n{\\em join\\_semilattice} would lead to name clashes: we will later\ndefine classes that inherit from @{class semigroup_add}, which\nprovides its own assumption {\\em add\\_assoc}, and prove that these are\nsubclasses of {\\em join\\_semilattice}. Hence the primed name.\n\\<close>\n\nclass join_semilattice = plus_ord +\n  assumes add_assoc' [ac_simps]: \"(x + y) + z = x + (y + z)\"\n  and add_comm [ac_simps] : \"x + y = y + x\"\n  and add_idem [simp]: \"x + x = x\"\nbegin\n\nlemma add_left_comm [ac_simps]: \"y + (x + z) = x + (y + z)\"\n  using local.add_assoc' local.add_comm by auto\n\nlemma add_left_idem [ac_simps]: \"x + (x + y) = x + y\"\n  unfolding add_assoc' [symmetric] by simp\n\ntext \\<open>The definition @{term \"x \\<le> y \\<longleftrightarrow> x + y = y\"} of the order is\nhidden in class @{class plus_ord}.\n\nWe show some simple order-based properties of semilattices. The\nfirst one states that every semilattice is a partial order.\\<close>\n\nsubclass order\nproof\n  fix x y z :: 'a\n  show \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> y \\<le> x\"\n    using local.add_comm local.less_def local.less_eq_def by force\n  show \"x \\<le> x\"\n    by (simp add: local.less_eq_def)\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (metis add_assoc' less_eq_def)\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    by (simp add: local.add_comm local.less_eq_def)\nqed\n\ntext \\<open>Next we show that joins are least upper bounds.\\<close>\n\nsublocale join: semilattice_sup \"(+)\"\n  by (unfold_locales; simp add: ac_simps local.less_eq_def)\n\ntext \\<open>Next we prove that joins are isotone (order preserving).\\<close>\n\nlemma add_iso: \"x \\<le> y \\<Longrightarrow> x + z \\<le> y + z\"\n  using join.sup_mono by blast\n\ntext \\<open>\n  The next lemma links the definition of order as @{term \"x \\<le> y \\<longleftrightarrow> x + y = y\"}\n  with a perhaps more conventional one known, e.g., from arithmetics.\n\\<close>\n\nlemma order_prop: \"x \\<le> y \\<longleftrightarrow> (\\<exists>z. x + z = y)\"\nproof\n  assume \"x \\<le> y\"\n  hence \"x + y = y\"\n    by (simp add: less_eq_def)\n  thus \"\\<exists>z. x + z = y\"\n    by auto\nnext\n  assume \"\\<exists>z. x + z = y\"\n  then obtain c where \"x + c = y\"\n    by auto\n  hence \"x + c \\<le> y\"\n    by simp\n  thus \"x \\<le> y\"\n    by simp\nqed\n\nend (* join_semilattice *)\n\n\nsubsection \\<open>Join Semilattices with an Additive Unit\\<close>\n\ntext \\<open>We now expand join semilattices by an additive unit~$0$. Is\nthe least element with respect to the order, and therefore often\ndenoted by~\\<open>\\<bottom>\\<close>. Semilattices with a least element are often\ncalled \\emph{bounded}.\\<close>\n\nclass join_semilattice_zero = join_semilattice + zero +\n  assumes add_zero_l [simp]: \"0 + x = x\"\n\nbegin\n\nsubclass comm_monoid_add\n  by (unfold_locales, simp_all add: add_assoc') (simp add: add_comm)\n\nsublocale join: bounded_semilattice_sup_bot \"(+)\" \"(\\<le>)\" \"(<)\" 0\n  by unfold_locales (simp add: local.order_prop)\n  \nlemma no_trivial_inverse: \"x \\<noteq> 0 \\<Longrightarrow> \\<not>(\\<exists>y. x + y = 0)\"\n  by (metis local.add_0_right local.join.sup_left_idem)\n\nend (* join_semilattice_zero *)\n\n\nsubsection \\<open>Near Semirings\\<close>\n\ntext \\<open>\\emph{Near semirings} (also called seminearrings) are\ngeneralisations of near rings to the semiring case. They have been\nstudied, for instance, in G.~Pilz's book~\\cite{pilz83nearrings} on\nnear rings. According to his definition, a near semiring consists of\nan additive and a multiplicative semigroup that interact via a single\ndistributivity law (left or right). The additive semigroup is not\nrequired to be commutative. The definition is influenced by partial\ntransformation semigroups.\n\nWe only consider near semirings in which addition is commutative, and\nin which the right distributivity law holds. We call such near\nsemirings \\emph{abelian}.\\<close>\n\nclass ab_near_semiring = ab_semigroup_add + semigroup_mult +  \n  assumes distrib_right' [simp]: \"(x + y) \\<cdot> z = x \\<cdot> z + y \\<cdot> z\"\n\nsubclass (in semiring) ab_near_semiring\n  by (unfold_locales, metis distrib_right)\n\nclass ab_pre_semiring = ab_near_semiring +\n  assumes subdistl_eq: \"z \\<cdot> x + z \\<cdot> (x + y) = z \\<cdot> (x + y)\"\n\nsubsection \\<open>Variants of Dioids\\<close>\n\ntext \\<open>A \\emph{near dioid} is an abelian near semiring in which\naddition is idempotent. This generalises the notion of (additively)\nidempotent semirings by dropping one distributivity law. Near dioids\nare a starting point for process algebras.\n\nBy modelling variants of dioids as variants of semirings in which\naddition is idempotent we follow the tradition of\nBirkhoff~\\cite{birkhoff67lattices}, but deviate from the definitions\nin Gondran and Minoux's book~\\cite{gondran10graphs}.\\<close>\n\nclass near_dioid = ab_near_semiring + plus_ord +\n  assumes add_idem' [simp]: \"x + x = x\"\n\nbegin\n\ntext \\<open>Since addition is idempotent, the additive (commutative)\nsemigroup reduct of a near dioid is a semilattice. Near dioids are\ntherefore ordered by the semilattice order.\\<close>\n\nsubclass join_semilattice\n  by unfold_locales (auto simp add: add.commute add.left_commute)\n\ntext \\<open>It follows that multiplication is right-isotone (but not\nnecessarily left-isotone).\\<close>\n\nlemma mult_isor: \"x \\<le> y \\<Longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\nproof -\n  assume \"x \\<le> y\"\n  hence \"x + y = y\"\n    by (simp add: less_eq_def)\n  hence \"(x + y) \\<cdot> z = y \\<cdot> z\"\n    by simp\n  thus \"x \\<cdot> z \\<le> y \\<cdot> z\"\n    by (simp add: less_eq_def)\nqed\n\nlemma \"x \\<le> y \\<Longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\n  (* nitpick [expect=genuine] -- \"3-element counterexample\" *)\noops\n\ntext \\<open>The next lemma states that, in every near dioid, left\nisotonicity and left subdistributivity are equivalent.\\<close>\n\nlemma mult_isol_equiv_subdistl:\n  \"(\\<forall>x y z. x \\<le> y \\<longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y) \\<longleftrightarrow> (\\<forall>x y z. z \\<cdot> x \\<le> z \\<cdot> (x + y))\"\n  by (metis local.join.sup_absorb2 local.join.sup_ge1)\n\ntext \\<open>The following lemma is relevant to propositional Hoare logic.\\<close>\n\nlemma phl_cons1: \"x \\<le> w \\<Longrightarrow> w \\<cdot> y \\<le> y \\<cdot> z \\<Longrightarrow> x \\<cdot> y \\<le> y \\<cdot> z\"\n  using dual_order.trans mult_isor by blast\n\nend (* near_dioid *)\n\n\ntext \\<open>We now make multiplication in near dioids left isotone, which\nis equivalent to left subdistributivity, as we have seen. The\ncorresponding structures form the basis of probabilistic Kleene\nalgebras~\\cite{mciverweber05pka} and game\nalgebras~\\cite{venema03gamealgebra}. We are not aware that these\nstructures have a special name, so we baptise them \\emph{pre-dioids}.\n\nWe do not explicitly define pre-semirings since we have no application\nfor them.\\<close>\n\nclass pre_dioid = near_dioid +\n  assumes subdistl: \"z \\<cdot> x \\<le> z \\<cdot> (x + y)\"\n\nbegin\n\ntext \\<open>Now, obviously, left isotonicity follows from left subdistributivity.\\<close>\n\nlemma subdistl_var: \"z \\<cdot> x + z \\<cdot> y \\<le> z \\<cdot> (x + y)\"\n  using local.mult_isol_equiv_subdistl local.subdistl by auto\n\nsubclass ab_pre_semiring\n  apply unfold_locales\n  by (simp add: local.join.sup_absorb2 local.subdistl)\n\nlemma mult_isol: \"x \\<le> y \\<Longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\nproof -\n  assume \"x \\<le> y\"\n  hence \"x + y = y\"\n    by (simp add: less_eq_def)\n  also have \"z \\<cdot> x + z \\<cdot> y \\<le> z \\<cdot> (x + y)\"\n    using subdistl_var by blast\n  moreover have \"... = z \\<cdot> y\"\n    by (simp add: calculation)\n  ultimately show \"z \\<cdot> x \\<le> z \\<cdot> y\"\n    by auto\nqed\n\nlemma mult_isol_var: \"u \\<le> x \\<Longrightarrow> v \\<le> y \\<Longrightarrow> u \\<cdot> v \\<le> x \\<cdot> y\"\n  by (meson local.dual_order.trans local.mult_isor mult_isol)\n\nlemma mult_double_iso: \"x \\<le> y \\<Longrightarrow> w \\<cdot> x \\<cdot> z \\<le> w \\<cdot> y \\<cdot> z\"\n  by (simp add: local.mult_isor mult_isol)\n\ntext \\<open>The following lemmas are relevant to propositional Hoare logic.\\<close>\n\nlemma phl_cons2: \"w \\<le> x \\<Longrightarrow> z \\<cdot> y \\<le> y \\<cdot> w \\<Longrightarrow> z \\<cdot> y \\<le> y \\<cdot> x\"\n  using local.order_trans mult_isol by blast\n\nlemma phl_seq: \nassumes \"p \\<cdot> x \\<le> x \\<cdot> r\"\nand \"r \\<cdot> y \\<le> y \\<cdot> q\" \nshows \"p \\<cdot> (x \\<cdot> y) \\<le> x \\<cdot> y \\<cdot> q\"\nproof -\n  have \"p \\<cdot> x \\<cdot> y \\<le> x \\<cdot> r \\<cdot> y\"\n    using assms(1) mult_isor by blast\n  thus ?thesis\n    by (metis assms(2) order_prop order_trans subdistl mult_assoc)\nqed\n\nlemma phl_cond: \nassumes \"u \\<cdot> v \\<le> v \\<cdot> u \\<cdot> v\" and \"u \\<cdot> w \\<le> w \\<cdot> u \\<cdot> w\" \nand \"\\<And>x y. u \\<cdot> (x + y) \\<le> u \\<cdot> x + u \\<cdot> y\"\nand \"u \\<cdot> v \\<cdot> x \\<le> x \\<cdot> z\" and \"u \\<cdot> w \\<cdot> y \\<le> y \\<cdot> z\" \nshows \"u \\<cdot> (v \\<cdot> x + w \\<cdot> y) \\<le> (v \\<cdot> x + w \\<cdot> y) \\<cdot> z\"\nproof -\n  have a: \"u \\<cdot> v \\<cdot> x \\<le> v \\<cdot> x \\<cdot> z\" and b: \"u \\<cdot> w \\<cdot> y \\<le> w \\<cdot> y \\<cdot> z\"\n    by (metis assms mult_assoc phl_seq)+\n  have  \"u \\<cdot> (v \\<cdot> x + w \\<cdot> y) \\<le> u \\<cdot> v \\<cdot> x + u \\<cdot> w \\<cdot> y\"\n    using assms(3) mult_assoc by auto\n  also have \"... \\<le> v \\<cdot> x \\<cdot> z + w \\<cdot> y \\<cdot> z\"\n    using a b join.sup_mono by blast\n  finally show ?thesis\n    by simp\nqed\n\nlemma phl_export1:\nassumes \"x \\<cdot> y \\<le> y \\<cdot> x \\<cdot> y\"\nand \"(x \\<cdot> y) \\<cdot> z \\<le> z \\<cdot> w\"\nshows \"x \\<cdot> (y \\<cdot> z) \\<le> (y \\<cdot> z) \\<cdot> w\"\nproof -\n  have \"x \\<cdot> y \\<cdot> z \\<le> y \\<cdot> x \\<cdot> y \\<cdot> z\"\n    by (simp add: assms(1) mult_isor)\n  thus ?thesis\n    using assms(1) assms(2) mult_assoc phl_seq by auto \nqed\n\n\n\nend (* pre_dioid *)\n\ntext \\<open>By adding a full left distributivity law we obtain semirings\n(which are already available in Isabelle/HOL as @{class semiring})\nfrom near semirings, and dioids from near dioids. Dioids are therefore\nidempotent semirings.\\<close>\n\nclass dioid = near_dioid + semiring\n\nsubclass (in dioid) pre_dioid\n  by unfold_locales (simp add: local.distrib_left)\n\nsubsection \\<open>Families of Nearsemirings with a Multiplicative Unit\\<close>\n\ntext \\<open>Multiplicative units are important, for instance, for defining\nan operation of finite iteration or Kleene star on dioids. We do not\nintroduce left and right units separately since we have no application\nfor this.\\<close>\n\nclass ab_near_semiring_one = ab_near_semiring + one +\n  assumes mult_onel [simp]: \"1 \\<cdot> x = x\"\n  and mult_oner [simp]: \"x \\<cdot> 1 = x\"\n\nbegin\n\nsubclass monoid_mult\n  by (unfold_locales, simp_all)\n\nend (* ab_near_semiring_one *)\n\nclass ab_pre_semiring_one = ab_near_semiring_one + ab_pre_semiring\n\nclass near_dioid_one = near_dioid + ab_near_semiring_one\n\nbegin\n\ntext \\<open>The following lemma is relevant to propositional Hoare logic.\\<close>\n\nlemma phl_skip: \"x \\<cdot> 1 \\<le> 1 \\<cdot> x\"\n  by simp\n\nend\n\ntext \\<open>For near dioids with one, it would be sufficient to require\n$1+1=1$. This implies @{term \"x+x=x\"} for arbitray~@{term x} (but that\nwould lead to annoying redundant proof obligations in mutual\nsubclasses of @{class near_dioid_one} and @{class near_dioid} later).\n\\<close>\n\nclass pre_dioid_one = pre_dioid + near_dioid_one\n\nclass dioid_one = dioid + near_dioid_one\n\nsubclass (in dioid_one) pre_dioid_one ..\n\n\nsubsection \\<open>Families of Nearsemirings with Additive Units\\<close>\n\ntext \\<open>\nWe now axiomatise an additive unit~$0$ for nearsemirings. The zero is\nusually required to satisfy annihilation properties with respect to\nmultiplication. Due to applications we distinguish a zero which is\nonly a left annihilator from one that is also a right annihilator.\nMore briefly, we call zero either a left unit or a unit.\n\nSemirings and dioids with a right zero only can be obtained from those\nwith a left unit by duality.\n\\<close>\n\nclass ab_near_semiring_one_zerol = ab_near_semiring_one + zero +\n  assumes add_zerol [simp]: \"0 + x = x\"\n  and annil [simp]: \"0 \\<cdot> x = 0\"\n\nbegin \n\ntext \\<open>Note that we do not require~$0 \\neq 1$.\\<close>\n\nlemma add_zeror [simp]: \"x + 0 = x\"\n  by (subst add_commute) simp\n\nend (* ab_near_semiring_one_zerol *)\n\nclass ab_pre_semiring_one_zerol = ab_near_semiring_one_zerol + ab_pre_semiring\n\nbegin\n\ntext \\<open>The following lemma shows that there is no point defining pre-semirings separately from dioids.\\<close>\n\nlemma \"1 + 1 = 1\"\nproof -\n  have \"1 + 1 = 1 \\<cdot> 1 + 1 \\<cdot> (1 + 0)\"\n    by simp\n  also have \"... = 1 \\<cdot> (1 + 0)\"\n    using subdistl_eq by presburger\n  finally show ?thesis\n    by simp\nqed\n\nend (* ab_pre_semiring_one_zerol *)\n\nclass near_dioid_one_zerol = near_dioid_one + ab_near_semiring_one_zerol\n\nsubclass (in near_dioid_one_zerol) join_semilattice_zero\n  by (unfold_locales, simp)\n\nclass pre_dioid_one_zerol = pre_dioid_one + ab_near_semiring_one_zerol\n\nsubclass (in pre_dioid_one_zerol) near_dioid_one_zerol ..\n\nclass semiring_one_zerol = semiring + ab_near_semiring_one_zerol\n\nclass dioid_one_zerol = dioid_one + ab_near_semiring_one_zerol\n\nsubclass (in dioid_one_zerol) pre_dioid_one_zerol ..\n\ntext \\<open>We now make zero also a right annihilator.\\<close>\n\nclass ab_near_semiring_one_zero = ab_near_semiring_one_zerol +\n  assumes annir [simp]: \"x \\<cdot> 0 = 0\"\n\nclass semiring_one_zero = semiring + ab_near_semiring_one_zero\n\nclass near_dioid_one_zero = near_dioid_one_zerol + ab_near_semiring_one_zero\n\nclass pre_dioid_one_zero = pre_dioid_one_zerol + ab_near_semiring_one_zero\n\nsubclass (in pre_dioid_one_zero) near_dioid_one_zero ..\n\nclass dioid_one_zero = dioid_one_zerol + ab_near_semiring_one_zero\n\nsubclass (in dioid_one_zero) pre_dioid_one_zero ..\n\nsubclass (in dioid_one_zero) semiring_one_zero ..\n\nsubsection \\<open>Duality by Opposition\\<close>\n\ntext \\<open>\nSwapping the order of multiplication in a semiring (or dioid) gives\nanother semiring (or dioid), called its \\emph{dual} or\n\\emph{opposite}.\n\\<close>\n\ndefinition (in times) opp_mult (infixl \"\\<odot>\" 70)\n  where \"x \\<odot> y \\<equiv> y \\<cdot> x\"\n\nlemma (in semiring_1) dual_semiring_1:\n  \"class.semiring_1 1 (\\<odot>) (+) 0\"\n  by unfold_locales (auto simp add: opp_mult_def mult.assoc distrib_right distrib_left)\n\nlemma (in dioid_one_zero) dual_dioid_one_zero:\n  \"class.dioid_one_zero (+) (\\<odot>) 1 0 (\\<le>) (<)\"\n  by unfold_locales (auto simp add: opp_mult_def mult.assoc distrib_right distrib_left)\n\nsubsection \\<open>Selective Near Semirings\\<close>\n\ntext \\<open>In this section we briefly sketch a generalisation of the\nnotion of \\emph{dioid}. Some important models, e.g. max-plus and\nmin-plus semirings, have that property.\\<close>\n\nclass selective_near_semiring = ab_near_semiring + plus_ord +\n  assumes select: \"x + y = x \\<or> x + y = y\"\n\nbegin\n\nlemma select_alt: \"x + y \\<in> {x,y}\"\n  by (simp add: local.select)\n\ntext \\<open>It follows immediately that every selective near semiring is a near dioid.\\<close>\n\nsubclass near_dioid\n  by (unfold_locales, meson select)\n\ntext \\<open>Moreover, the order in a selective near semiring is obviously linear.\\<close>\n\nsubclass linorder\n  by (unfold_locales, metis add.commute join.sup.orderI select)\n\nend (*selective_near_semiring*)\n\nclass selective_semiring = selective_near_semiring + semiring_one_zero\n\nbegin\n\nsubclass dioid_one_zero ..\n\nend (* selective_semiring *)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Kleene_Algebra/Dioid.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.9032942008463507, "lm_q1q2_score": 0.7765292740180033}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nparagraph \\<open>Bijection\\<close>\ntheory Functions_Bijection\n  imports\n    Functions_Inverse\n    Functions_Monotone\nbegin\n\nconsts bijection_on :: \"'a \\<Rightarrow> 'b \\<Rightarrow> ('c \\<Rightarrow> 'd) \\<Rightarrow> ('d \\<Rightarrow> 'c) \\<Rightarrow> bool\"\n\noverloading\n  bijection_on_pred \\<equiv> \"bijection_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> bool) \\<Rightarrow>\n    ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\"\nbegin\n  definition \"bijection_on_pred P P' f g \\<equiv>\n    ([P] \\<Rrightarrow>\\<^sub>m P') f \\<and>\n    ([P'] \\<Rrightarrow>\\<^sub>m P) g \\<and>\n    inverse_on P f g \\<and>\n    inverse_on P' g f\"\nend\n\nlemma bijection_onI [intro]:\n  assumes \"([P] \\<Rrightarrow>\\<^sub>m P') f\"\n  and \"([P'] \\<Rrightarrow>\\<^sub>m P) g\"\n  and \"inverse_on P f g\"\n  and \"inverse_on P' g f\"\n  shows \"bijection_on P P' f g\"\n  using assms unfolding bijection_on_pred_def by blast\n\nlemma bijection_onE:\n  assumes \"bijection_on P P' f g\"\n  obtains \"([P] \\<Rrightarrow>\\<^sub>m P') f\" \"([P'] \\<Rrightarrow>\\<^sub>m P) g\"\n    \"inverse_on P f g\" \"inverse_on P' g f\"\n  using assms unfolding bijection_on_pred_def by blast\n\ncontext\n  fixes P :: \"'a \\<Rightarrow> bool\"\n  and P' :: \"'b \\<Rightarrow> bool\"\n  and f :: \"'a \\<Rightarrow> 'b\"\nbegin\n\nlemma mono_wrt_pred_if_bijection_on_left:\n  assumes \"bijection_on P P' f g\"\n  shows \"([P] \\<Rrightarrow>\\<^sub>m P') f\"\n  using assms by (elim bijection_onE)\n\nlemma mono_wrt_pred_if_bijection_on_right:\n  assumes \"bijection_on P P' f g\"\n  shows \"([P'] \\<Rrightarrow>\\<^sub>m P) g\"\n  using assms by (elim bijection_onE)\n\nlemma bijection_on_pred_right:\n  assumes \"bijection_on P P' f g\"\n  and \"P x\"\n  shows \"P' (f x)\"\n  using assms by (blast elim: bijection_onE)\n\nlemma bijection_on_pred_left:\n  assumes \"bijection_on P P' f g\"\n  and \"P' y\"\n  shows \"P (g y)\"\n  using assms by (blast elim: bijection_onE)\n\nlemma inverse_on_if_bijection_on_left_right:\n  assumes \"bijection_on P P' f g\"\n  shows \"inverse_on P f g\"\n  using assms by (elim bijection_onE)\n\nlemma inverse_on_if_bijection_on_right_left:\n  assumes \"bijection_on P P' f g\"\n  shows \"inverse_on P' g f\"\n  using assms by (elim bijection_onE)\n\nlemma bijection_on_left_right_eq_self:\n  assumes \"bijection_on P P' f g\"\n  and \"P x\"\n  shows \"g (f x) = x\"\n  using assms inverse_on_if_bijection_on_left_right\n  by (intro inverse_onD)\n\nlemma bijection_on_right_left_eq_self':\n  assumes \"bijection_on P P' f g\"\n  and \"P' y\"\n  shows \"f (g y) = y\"\n  using assms inverse_on_if_bijection_on_right_left by (intro inverse_onD)\n\nlemma bijection_on_right_left_if_bijection_on_left_right:\n  assumes \"bijection_on P P' f g\"\n  shows \"bijection_on P' P g f\"\n  using assms by (auto elim: bijection_onE)\n\nlemma injective_on_if_bijection_on_left:\n  assumes \"bijection_on P P' f g\"\n  shows \"injective_on P f\"\n  using assms\n  by (intro injective_on_if_inverse_on inverse_on_if_bijection_on_left_right)\n\nlemma injective_on_if_bijection_on_right:\n  assumes \"bijection_on P P' f g\"\n  shows \"injective_on P' g\"\n  by (intro injective_on_if_inverse_on)\n  (fact inverse_on_if_bijection_on_right_left[OF assms])\n\nend\n\n\ndefinition \"bijection (f :: 'a \\<Rightarrow> 'b) \\<equiv> bijection_on (\\<top> :: 'a \\<Rightarrow> bool) (\\<top> :: 'b \\<Rightarrow> bool) f\"\n\nlemma bijection_eq_bijection_on:\n  \"bijection (f :: 'a \\<Rightarrow> 'b) = bijection_on (\\<top> :: 'a \\<Rightarrow> bool) (\\<top> :: 'b \\<Rightarrow> bool) f\"\n  unfolding bijection_def ..\n\nlemma bijectionI [intro]:\n  assumes \"inverse f g\"\n  and \"inverse g f\"\n  shows \"bijection f g\"\n  unfolding bijection_eq_bijection_on using assms\n  by (intro bijection_onI inverse_on_if_inverse dep_mono_wrt_predI) simp_all\n\nlemma bijectionE [elim]:\n  assumes \"bijection f g\"\n  obtains \"inverse f g\" \"inverse g f\"\n  using assms unfolding bijection_eq_bijection_on inverse_eq_inverse_on\n  by (blast elim: bijection_onE)\n\nlemma inverse_if_bijection_left_right:\n  assumes \"bijection f g\"\n  shows \"inverse f g\"\n  using assms by (elim bijectionE)\n\nlemma inverse_if_bijection_right_left:\n  assumes \"bijection f g\"\n  shows \"inverse g f\"\n  using assms by (elim bijectionE)\n\nlemma bijection_right_left_if_bijection_left_right:\n  assumes \"bijection f g\"\n  shows \"bijection g f\"\n  using assms by auto\n\n\nparagraph \\<open>Instantiations\\<close>\n\nlemma bijection_on_self_id:\n  fixes P :: \"'a \\<Rightarrow> bool\"\n  shows \"bijection_on P P (id :: 'a \\<Rightarrow> _) id\"\n  by (intro bijection_onI inverse_onI dep_mono_wrt_predI) simp_all\n\n\nend", "meta": {"author": "kappelmann", "repo": "transport-isabelle", "sha": "b6d2cb56ea4abf6e496d1c258d5b3d2a816d75ff", "save_path": "github-repos/isabelle/kappelmann-transport-isabelle", "path": "github-repos/isabelle/kappelmann-transport-isabelle/transport-isabelle-b6d2cb56ea4abf6e496d1c258d5b3d2a816d75ff/HOL_Basics/Functions/Properties/Functions_Bijection.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.7764082710898245}}
{"text": "(*  Title:      FOL/ex/First_Order_Logic.thy\n    Author:     Markus Wenzel, TU Munich\n*)\n\nsection {* A simple formulation of First-Order Logic *}\n\ntheory First_Order_Logic imports Pure begin\n\ntext {*\n  The subsequent theory development illustrates single-sorted\n  intuitionistic first-order logic with equality, formulated within\n  the Pure framework.  Actually this is not an example of\n  Isabelle/FOL, but of Isabelle/Pure.\n*}\n\nsubsection {* Syntax *}\n\ntypedecl i\ntypedecl o\n\njudgment\n  Trueprop :: \"o \\<Rightarrow> prop\"    (\"_\" 5)\n\n\nsubsection {* Propositional logic *}\n\naxiomatization\n  false :: o  (\"\\<bottom>\") and\n  imp :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longrightarrow>\" 25) and\n  conj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<and>\" 35) and\n  disj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<or>\" 30)\nwhere\n  falseE [elim]: \"\\<bottom> \\<Longrightarrow> A\" and\n\n  impI [intro]: \"(A \\<Longrightarrow> B) \\<Longrightarrow> A \\<longrightarrow> B\" and\n  mp [dest]: \"A \\<longrightarrow> B \\<Longrightarrow> A \\<Longrightarrow> B\" and\n\n  conjI [intro]: \"A \\<Longrightarrow> B \\<Longrightarrow> A \\<and> B\" and\n  conjD1: \"A \\<and> B \\<Longrightarrow> A\" and\n  conjD2: \"A \\<and> B \\<Longrightarrow> B\" and\n\n  disjE [elim]: \"A \\<or> B \\<Longrightarrow> (A \\<Longrightarrow> C) \\<Longrightarrow> (B \\<Longrightarrow> C) \\<Longrightarrow> C\" and\n  disjI1 [intro]: \"A \\<Longrightarrow> A \\<or> B\" and\n  disjI2 [intro]: \"B \\<Longrightarrow> A \\<or> B\"\n\ntheorem conjE [elim]:\n  assumes \"A \\<and> B\"\n  obtains A and B\nproof\n  from `A \\<and> B` show A by (rule conjD1)\n  from `A \\<and> B` show B by (rule conjD2)\nqed\n\ndefinition\n  true :: o  (\"\\<top>\") where\n  \"\\<top> \\<equiv> \\<bottom> \\<longrightarrow> \\<bottom>\"\n\ndefinition\n  not :: \"o \\<Rightarrow> o\"  (\"\\<not> _\" [40] 40) where\n  \"\\<not> A \\<equiv> A \\<longrightarrow> \\<bottom>\"\n\ndefinition\n  iff :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longleftrightarrow>\" 25) where\n  \"A \\<longleftrightarrow> B \\<equiv> (A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n\n\ntheorem trueI [intro]: \\<top>\nproof (unfold true_def)\n  show \"\\<bottom> \\<longrightarrow> \\<bottom>\" ..\nqed\n\ntheorem notI [intro]: \"(A \\<Longrightarrow> \\<bottom>) \\<Longrightarrow> \\<not> A\"\nproof (unfold not_def)\n  assume \"A \\<Longrightarrow> \\<bottom>\"\n  then show \"A \\<longrightarrow> \\<bottom>\" ..\nqed\n\ntheorem notE [elim]: \"\\<not> A \\<Longrightarrow> A \\<Longrightarrow> B\"\nproof (unfold not_def)\n  assume \"A \\<longrightarrow> \\<bottom>\" and A\n  then have \\<bottom> .. then show B ..\nqed\n\ntheorem iffI [intro]: \"(A \\<Longrightarrow> B) \\<Longrightarrow> (B \\<Longrightarrow> A) \\<Longrightarrow> A \\<longleftrightarrow> B\"\nproof (unfold iff_def)\n  assume \"A \\<Longrightarrow> B\" then have \"A \\<longrightarrow> B\" ..\n  moreover assume \"B \\<Longrightarrow> A\" then have \"B \\<longrightarrow> A\" ..\n  ultimately show \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\" ..\nqed\n\ntheorem iff1 [elim]: \"A \\<longleftrightarrow> B \\<Longrightarrow> A \\<Longrightarrow> B\"\nproof (unfold iff_def)\n  assume \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n  then have \"A \\<longrightarrow> B\" ..\n  then show \"A \\<Longrightarrow> B\" ..\nqed\n\ntheorem iff2 [elim]: \"A \\<longleftrightarrow> B \\<Longrightarrow> B \\<Longrightarrow> A\"\nproof (unfold iff_def)\n  assume \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n  then have \"B \\<longrightarrow> A\" ..\n  then show \"B \\<Longrightarrow> A\" ..\nqed\n\n\nsubsection {* Equality *}\n\naxiomatization\n  equal :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infixl \"=\" 50)\nwhere\n  refl [intro]: \"x = x\" and\n  subst: \"x = y \\<Longrightarrow> P x \\<Longrightarrow> P y\"\n\ntheorem trans [trans]: \"x = y \\<Longrightarrow> y = z \\<Longrightarrow> x = z\"\n  by (rule subst)\n\ntheorem sym [sym]: \"x = y \\<Longrightarrow> y = x\"\nproof -\n  assume \"x = y\"\n  from this and refl show \"y = x\" by (rule subst)\nqed\n\n\nsubsection {* Quantifiers *}\n\naxiomatization\n  All :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<forall>\" 10) and\n  Ex :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<exists>\" 10)\nwhere\n  allI [intro]: \"(\\<And>x. P x) \\<Longrightarrow> \\<forall>x. P x\" and\n  allD [dest]: \"\\<forall>x. P x \\<Longrightarrow> P a\" and\n  exI [intro]: \"P a \\<Longrightarrow> \\<exists>x. P x\" and\n  exE [elim]: \"\\<exists>x. P x \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\n\nlemma \"(\\<exists>x. P (f x)) \\<longrightarrow> (\\<exists>y. P y)\"\nproof\n  assume \"\\<exists>x. P (f x)\"\n  then show \"\\<exists>y. P y\"\n  proof\n    fix x assume \"P (f x)\"\n    then show ?thesis ..\n  qed\nqed\n\nlemma \"(\\<exists>x. \\<forall>y. R x y) \\<longrightarrow> (\\<forall>y. \\<exists>x. R x y)\"\nproof\n  assume \"\\<exists>x. \\<forall>y. R x y\"\n  then show \"\\<forall>y. \\<exists>x. R x y\"\n  proof\n    fix x assume a: \"\\<forall>y. R x y\"\n    show ?thesis\n    proof\n      fix y from a have \"R x y\" ..\n      then show \"\\<exists>x. R x y\" ..\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/FOL/ex/First_Order_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7763579961375956}}
{"text": "(*\n  File:     Complex_Roots_Of_Unity.thy\n  Authors:  Rodrigo Raya, EPFL; Manuel Eberl, TUM\n\n  Complex roots of unity (exp(2i\\<pi>/n)) and sums over them.\n*)\ntheory Complex_Roots_Of_Unity\nimports\n  \"HOL-Analysis.Analysis\"\n  Periodic_Arithmetic\nbegin\n\nsection \\<open>Complex roots of unity\\<close>\n\ndefinition \n  \"unity_root k n = cis (2 * pi * of_int n / of_nat k)\"\n\nlemma \n  unity_root_k_0 [simp]: \"unity_root k 0 = 1\" and\n  unity_root_0_n [simp]: \"unity_root 0 n = 1\"\n  unfolding unity_root_def by simp+\n\nlemma unity_root_conv_exp: \n  \"unity_root k n = exp (of_real (2*pi*n/k) * \\<i>)\"\n  unfolding unity_root_def \n  by (subst cis_conv_exp,subst mult.commute,blast)\n\nlemma unity_root_mod: \n  \"unity_root k (n mod int k) = unity_root k n\"\nproof (cases \"k = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  obtain q :: int where q_def: \"n = q*k + (n mod k)\" \n    using div_mult_mod_eq[symmetric] by blast\n  have \"n / k = q + (n mod k) / k\"\n  proof (auto simp add: divide_simps False)\n    have \"real_of_int n = real_of_int (q*k + (n mod k))\"\n      using q_def by simp\n    also have \"\\<dots> = real_of_int q * real k + real_of_int (n mod k)\"\n      using of_int_add of_int_mult by simp\n    finally show \"real_of_int n = real_of_int q * real k + real_of_int (n mod k)\" \n      by blast\n  qed\n  then have \"(2*pi*n/k) = 2*pi*q + (2*pi*(n mod k)/k)\"\n    using False by (auto simp add: field_simps)\n  then have \"(2*pi*n/k)*\\<i> = 2*pi*q*\\<i> + (2*pi*(n mod k)/k)*\\<i>\" (is \"?l = ?r1 + ?r2\")\n    by (auto simp add: algebra_simps)\n  then have \"exp ?l = exp ?r2\"\n    using exp_plus_2pin by (simp add: exp_add mult.commute)\n  then show ?thesis \n    using unity_root_def unity_root_conv_exp by simp\nqed\n\nlemma unity_root_cong:\n  assumes \"[m = n] (mod int k)\"\n  shows   \"unity_root k m = unity_root k n\"\nproof -\n  from assms have \"m mod int k = n mod int k\"\n    by (auto simp: cong_def)\n  hence \"unity_root k (m mod int k) = unity_root k (n mod int k)\"\n    by simp\n  thus ?thesis by (simp add: unity_root_mod)\nqed\n\nlemma unity_root_mod_nat: \n  \"unity_root k (nat (n mod int k)) = unity_root k n\"\nproof (cases k)\n  case (Suc l)\n  then have \"n mod int k \\<ge> 0\" by auto\n  show ?thesis \n    unfolding int_nat_eq \n    by (simp add: \\<open>n mod int k \\<ge> 0\\<close> unity_root_mod)\nqed auto\n\nlemma unity_root_eqD:\n assumes gr: \"k > 0\"\n assumes eq: \"unity_root k i = unity_root k j\"\n shows \"i mod k = j mod k\"\nproof - \n  let ?arg1 = \"(2*pi*i/k)* \\<i>\"\n  let ?arg2 = \"(2*pi*j/k)* \\<i>\"\n  from eq unity_root_conv_exp have \"exp ?arg1 = exp ?arg2\" by simp\n  from this exp_eq \n  obtain n :: int where \"?arg1 = ?arg2 +(2*n*pi)*\\<i>\" by blast\n  then have e1: \"?arg1 - ?arg2 = 2*n*pi*\\<i>\" by simp\n  have e2: \"?arg1 - ?arg2 = 2*(i-j)*(1/k)*pi*\\<i>\"\n    by (auto simp add: algebra_simps)\n  from e1 e2 have \"2*n*pi*\\<i> = 2*(i-j)*(1/k)*pi*\\<i>\" by simp\n  then have \"2*n*k*pi*\\<i> = 2*(i-j)*pi*\\<i>\"\n    by (simp add: divide_simps \\<open>k > 0\\<close>)(simp add: field_simps)\n  then have \"2*n*k = 2*(i-j)\"\n    by (meson complex_i_not_zero mult_cancel_right of_int_eq_iff of_real_eq_iff pi_neq_zero)\n  then have \"n*k = i-j\" by auto\n  then show ?thesis by Groebner_Basis.algebra\nqed\n\nlemma unity_root_eq_1_iff:\n  fixes k n :: nat\n  assumes \"k > 0\" \n  shows \"unity_root k n = 1 \\<longleftrightarrow> k dvd n\"\nproof -\n  have \"unity_root k n = exp ((2*pi*n/k) * \\<i>)\"\n    by (simp add: unity_root_conv_exp)\n  also have \"exp ((2*pi*n/k)* \\<i>) = 1 \\<longleftrightarrow> k dvd n\"\n    using complex_root_unity_eq_1[of k n] assms\n    by (auto simp add: algebra_simps)\n  finally show ?thesis by simp\nqed\n\nlemma unity_root_pow: \"unity_root k n ^ m = unity_root k (n * m)\"\n  using unity_root_def\n  by (simp add: Complex.DeMoivre mult.commute algebra_split_simps(6))\n\nlemma unity_root_add: \"unity_root k (m + n) = unity_root k m * unity_root k n\"\n  by (simp add: unity_root_conv_exp add_divide_distrib algebra_simps exp_add)\n\nlemma unity_root_uminus: \"unity_root k (-m) = cnj (unity_root k m)\"\n  unfolding unity_root_conv_exp exp_cnj by simp\n\nlemma inverse_unity_root: \"inverse (unity_root k m) = cnj (unity_root k m)\" \n  unfolding unity_root_conv_exp exp_cnj by (simp add: field_simps exp_minus)\n\nlemma unity_root_diff: \"unity_root k (m - n) = unity_root k m * cnj (unity_root k n)\"\n  using unity_root_add[of k m \"-n\"] by (simp add: unity_root_uminus)\n\nlemma unity_root_eq_1_iff_int:\n  fixes k :: nat and n :: int\n  assumes \"k > 0\" \n  shows \"unity_root k n = 1 \\<longleftrightarrow> k dvd n\"\nproof (cases \"n \\<ge> 0\")\n  case True\n  obtain n' where \"n = int n'\" \n    using zero_le_imp_eq_int[OF True] by blast\n  then show ?thesis \n    using unity_root_eq_1_iff[OF \\<open>k > 0\\<close>, of n'] of_nat_dvd_iff by blast\nnext\n  case False\n  then have \"-n \\<ge> 0\" by auto\n  have \"unity_root k n = inverse (unity_root k (-n))\"\n    unfolding inverse_unity_root by (simp add: unity_root_uminus)\n  then have \"(unity_root k n = 1) = (unity_root k (-n) = 1)\" \n    by simp\n  also have \"(unity_root k (-n) = 1) = (k dvd (-n))\"\n    using unity_root_eq_1_iff[of k \"nat (-n)\",OF \\<open>k > 0\\<close>] False \n          int_dvd_int_iff[of k \"nat (-n)\"] nat_0_le[OF \\<open>-n \\<ge> 0\\<close>] by auto\n  finally show ?thesis by simp\nqed\n\nlemma unity_root_eq_1 [simp]: \"int k dvd n \\<Longrightarrow> unity_root k n = 1\"\n  by (cases \"k = 0\") (auto simp: unity_root_eq_1_iff_int)\n\nlemma unity_periodic_arithmetic:\n  \"periodic_arithmetic (unity_root k) k\" \n  unfolding periodic_arithmetic_def \nproof\n  fix n\n  have \"unity_root k (n + k) = unity_root k ((n+k) mod k)\"\n    using unity_root_mod[of k] zmod_int by presburger\n  also have \"unity_root k ((n+k) mod k) = unity_root k n\" \n    using unity_root_mod zmod_int by auto\n  finally show \"unity_root k (n + k) = unity_root k n\" by simp\nqed\n\nlemma unity_periodic_arithmetic_mult:\n  \"periodic_arithmetic (\\<lambda>n. unity_root k (m * int n)) k\"\n  unfolding periodic_arithmetic_def\nproof \n  fix n\n  have \"unity_root k (m * int (n + k)) = \n        unity_root k (m*n + m*k)\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> = unity_root k (m*n)\"\n    using unity_root_mod[of k \"m * int n\"] unity_root_mod[of k \"m * int n + m * int k\"] \n          mod_mult_self3 by presburger\n  finally show \"unity_root k (m * int (n + k)) =\n             unity_root k (m * int n)\" by simp\nqed\n\nlemma unity_root_periodic_arithmetic_mult_minus:\n  shows \"periodic_arithmetic (\\<lambda>i. unity_root k (-int i*int m)) k\" \n  unfolding periodic_arithmetic_def\nproof \n  fix n \n  have \"unity_root k (-(n + k) * m) = cnj (unity_root k (n*m+k*m))\" \n    by (simp add: ring_distribs unity_root_diff unity_root_add unity_root_uminus)\n  also have \"\\<dots> = cnj (unity_root k (n*m))\"\n    using mult_period[of \"unity_root k\" k m] unity_periodic_arithmetic[of k]\n    unfolding periodic_arithmetic_def by presburger\n  also have \"\\<dots> = unity_root k (-n*m)\"\n    by (simp add: unity_root_uminus)\n  finally show \"unity_root k (-(n + k) * m) = unity_root k (-n*m)\"\n    by simp\nqed\n\nlemma unity_div:\n fixes a :: int and d :: nat\n assumes \"d dvd k\"\n shows \"unity_root k (a*d) = unity_root (k div d) a\" \nproof -\n  have 1: \"(2*pi*(a*d)/k) = (2*pi*a)/(k div d)\"\n    using Suc_pred assms by (simp add: divide_simps, fastforce)   \n  have \"unity_root k (a*d) = exp ((2*pi*(a*d)/k)* \\<i>)\"\n    using unity_root_conv_exp by simp\n  also have \"\\<dots> = exp (((2*pi*a)/(k div d))* \\<i>)\"\n    using 1 by simp\n  also have \"\\<dots> = unity_root (k div d) a\"\n    using unity_root_conv_exp by simp\n  finally show ?thesis by simp\nqed\n\nlemma unity_div_num:\n  assumes \"k > 0\" \"d > 0\" \"d dvd k\"\n  shows \"unity_root k (x * (k div d)) = unity_root d x\"\n  using assms dvd_div_mult_self unity_div by auto\n\n\nsection \\<open>Geometric sums of roots of unity\\<close>\n\ntext\\<open>\n  Apostol calls these `geometric sums', which is a bit too generic. We therefore decided\n  to refer to them as `sums of roots of unity'.\n\\<close>\ndefinition \"unity_root_sum k n = (\\<Sum>m<k. unity_root k (n * of_nat m))\"\n\nlemma unity_root_sum_0_left [simp]: \"unity_root_sum 0 n = 0\" and\n      unity_root_sum_0_right [simp]: \"k > 0 \\<Longrightarrow> unity_root_sum k 0 = k\" \n  unfolding unity_root_sum_def by simp_all\n\ntext \\<open>Theorem 8.1\\<close>\ntheorem unity_root_sum:\n  fixes k :: nat and n :: int\n  assumes gr: \"k \\<ge> 1\"\n  shows \"k dvd n \\<Longrightarrow> unity_root_sum k n = k\"\n    and \"\\<not>k dvd n \\<Longrightarrow> unity_root_sum k n = 0\"\nproof -\n  assume dvd: \"k dvd n\"\n  let ?x = \"unity_root k n\"\n  have unit: \"?x = 1\" using dvd gr unity_root_eq_1_iff_int by auto\n  have exp: \"?x^m = unity_root k (n*m)\" for m using unity_root_pow by simp\n  have \"unity_root_sum k n = (\\<Sum>m<k. unity_root k (n*m))\" \n    using unity_root_sum_def by simp \n  also have \"\\<dots> = (\\<Sum>m<k. ?x^m)\" using exp by auto\n  also have \"\\<dots> = (\\<Sum>m<k. 1)\" using unit by simp\n  also have \"\\<dots> = k\" using gr by (induction k, auto)\n  finally show \"unity_root_sum k n = k\" by simp\nnext\n  assume dvd: \"\\<not>k dvd n\"\n  let ?x = \"unity_root k n\"\n  have \"?x \\<noteq> 1\" using dvd gr unity_root_eq_1_iff_int by auto\n  have \"(?x^k - 1)/(?x - 1) = (\\<Sum>m<k. ?x^m)\"\n    using geometric_sum[of ?x k, OF \\<open>?x \\<noteq> 1\\<close>] by auto\n  then have sum: \"unity_root_sum k n = (?x^k - 1)/(?x - 1)\"\n    using unity_root_sum_def unity_root_pow by simp\n  have \"?x^k = 1\" \n    using gr unity_root_eq_1_iff_int unity_root_pow by simp\n  then show \"unity_root_sum k n = 0\" using sum by auto\nqed\n\ncorollary unity_root_sum_periodic_arithmetic: \n \"periodic_arithmetic (unity_root_sum k) k\"\n  unfolding periodic_arithmetic_def\nproof \n  fix n \n  show \"unity_root_sum k (n + k) = unity_root_sum k n\"\n    by (cases \"k = 0\"; cases \"k dvd n\") (auto simp add: unity_root_sum)\nqed\n\nlemma unity_root_sum_nonzero_iff:\n  fixes r :: int\n  assumes \"k \\<ge> 1\" and \"r \\<in> {-k<..<k}\"\n  shows \"unity_root_sum k r \\<noteq> 0 \\<longleftrightarrow> r = 0\"\nproof\n  assume \"unity_root_sum k r \\<noteq> 0\"\n  then have \"k dvd r\" using unity_root_sum assms by blast\n  then show \"r = 0\" using assms(2) \n    using dvd_imp_le_int by force\nnext\n  assume \"r = 0\"\n  then have \"k dvd r\" by auto\n  then have \"unity_root_sum k r = k\" \n    using assms(1) unity_root_sum by blast\n  then show \"unity_root_sum k r \\<noteq> 0\" using assms(1) by simp\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gauss_Sums/Complex_Roots_Of_Unity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7762821094384236}}
{"text": "(*  Title:      HOL/Number_Theory/Eratosthenes.thy\n    Author:     Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>The sieve of Eratosthenes\\<close>\n\ntheory Eratosthenes\nimports Main Primes\nbegin\n\n\nsubsection \\<open>Preliminary: strict divisibility\\<close>\n\ncontext dvd\nbegin\n\nabbreviation dvd_strict :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"dvd'_strict\" 50)\nwhere\n  \"b dvd_strict a \\<equiv> b dvd a \\<and> \\<not> a dvd b\"\n\nend\n\n\nsubsection \\<open>Main corpus\\<close>\n\ntext \\<open>The sieve is modelled as a list of booleans, where @{const False} means \\emph{marked out}.\\<close>\n\ntype_synonym marks = \"bool list\"\n\ndefinition numbers_of_marks :: \"nat \\<Rightarrow> marks \\<Rightarrow> nat set\"\nwhere\n  \"numbers_of_marks n bs = fst ` {x \\<in> set (enumerate n bs). snd x}\"\n\nlemma numbers_of_marks_simps [simp, code]:\n  \"numbers_of_marks n [] = {}\"\n  \"numbers_of_marks n (True # bs) = insert n (numbers_of_marks (Suc n) bs)\"\n  \"numbers_of_marks n (False # bs) = numbers_of_marks (Suc n) bs\"\n  by (auto simp add: numbers_of_marks_def intro!: image_eqI)\n\nlemma numbers_of_marks_Suc:\n  \"numbers_of_marks (Suc n) bs = Suc ` numbers_of_marks n bs\"\n  by (auto simp add: numbers_of_marks_def enumerate_Suc_eq image_iff Bex_def)\n\nlemma numbers_of_marks_replicate_False [simp]:\n  \"numbers_of_marks n (replicate m False) = {}\"\n  by (auto simp add: numbers_of_marks_def enumerate_replicate_eq)\n\nlemma numbers_of_marks_replicate_True [simp]:\n  \"numbers_of_marks n (replicate m True) = {n..<n+m}\"\n  by (auto simp add: numbers_of_marks_def enumerate_replicate_eq image_def)\n\nlemma in_numbers_of_marks_eq:\n  \"m \\<in> numbers_of_marks n bs \\<longleftrightarrow> m \\<in> {n..<n + length bs} \\<and> bs ! (m - n)\"\n  by (simp add: numbers_of_marks_def in_set_enumerate_eq image_iff add.commute)\n\nlemma sorted_list_of_set_numbers_of_marks:\n  \"sorted_list_of_set (numbers_of_marks n bs) = map fst (filter snd (enumerate n bs))\"\n  by (auto simp add: numbers_of_marks_def distinct_map\n    intro!: sorted_filter distinct_filter inj_onI sorted_distinct_set_unique)\n\n\ntext \\<open>Marking out multiples in a sieve\\<close>\n\ndefinition mark_out :: \"nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"mark_out n bs = map (\\<lambda>(q, b). b \\<and> \\<not> Suc n dvd Suc (Suc q)) (enumerate n bs)\"\n\nlemma mark_out_Nil [simp]: \"mark_out n [] = []\"\n  by (simp add: mark_out_def)\n\nlemma length_mark_out [simp]: \"length (mark_out n bs) = length bs\"\n  by (simp add: mark_out_def)\n\nlemma numbers_of_marks_mark_out:\n    \"numbers_of_marks n (mark_out m bs) = {q \\<in> numbers_of_marks n bs. \\<not> Suc m dvd Suc q - n}\"\n  by (auto simp add: numbers_of_marks_def mark_out_def in_set_enumerate_eq image_iff\n    nth_enumerate_eq less_eq_dvd_minus)\n\n\ntext \\<open>Auxiliary operation for efficient implementation\\<close>\n\ndefinition mark_out_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"mark_out_aux n m bs =\n    map (\\<lambda>(q, b). b \\<and> (q < m + n \\<or> \\<not> Suc n dvd Suc (Suc q) + (n - m mod Suc n))) (enumerate n bs)\"\n\nlemma mark_out_code [code]: \"mark_out n bs = mark_out_aux n n bs\"\nproof -\n  have aux: False\n    if A: \"Suc n dvd Suc (Suc a)\"\n    and B: \"a < n + n\"\n    and C: \"n \\<le> a\"\n    for a\n  proof (cases \"n = 0\")\n    case True\n    with A B C show ?thesis by simp\n  next\n    case False\n    define m where \"m = Suc n\"\n    then have \"m > 0\" by simp\n    from False have \"n > 0\" by simp\n    from A obtain q where q: \"Suc (Suc a) = Suc n * q\" by (rule dvdE)\n    have \"q > 0\"\n    proof (rule ccontr)\n      assume \"\\<not> q > 0\"\n      with q show False by simp\n    qed\n    with \\<open>n > 0\\<close> have \"Suc n * q \\<ge> 2\" by (auto simp add: gr0_conv_Suc)\n    with q have a: \"a = Suc n * q - 2\" by simp\n    with B have \"q + n * q < n + n + 2\" by auto\n    then have \"m * q < m * 2\" by (simp add: m_def)\n    with \\<open>m > 0\\<close> have \"q < 2\" by simp\n    with \\<open>q > 0\\<close> have \"q = 1\" by simp\n    with a have \"a = n - 1\" by simp\n    with \\<open>n > 0\\<close> C show False by simp\n  qed\n  show ?thesis\n    by (auto simp add: mark_out_def mark_out_aux_def in_set_enumerate_eq intro: aux)\nqed\n\nlemma mark_out_aux_simps [simp, code]:\n  \"mark_out_aux n m [] = []\"\n  \"mark_out_aux n 0 (b # bs) = False # mark_out_aux n n bs\"\n  \"mark_out_aux n (Suc m) (b # bs) = b # mark_out_aux n m bs\"\nproof goal_cases\n  case 1\n  show ?case\n    by (simp add: mark_out_aux_def)\nnext\n  case 2\n  show ?case\n    by (auto simp add: mark_out_code [symmetric] mark_out_aux_def mark_out_def\n      enumerate_Suc_eq in_set_enumerate_eq less_eq_dvd_minus)\nnext\n  case 3\n  { define v where \"v = Suc m\"\n    define w where \"w = Suc n\"\n    fix q\n    assume \"m + n \\<le> q\"\n    then obtain r where q: \"q = m + n + r\" by (auto simp add: le_iff_add)\n    { fix u\n      from w_def have \"u mod w < w\" by simp\n      then have \"u + (w - u mod w) = w + (u - u mod w)\"\n        by simp\n      then have \"u + (w - u mod w) = w + u div w * w\"\n        by (simp add: minus_mod_eq_div_mult)\n    }\n    then have \"w dvd v + w + r + (w - v mod w) \\<longleftrightarrow> w dvd m + w + r + (w - m mod w)\"\n      by (simp add: add.assoc add.left_commute [of m] add.left_commute [of v]\n        dvd_add_left_iff dvd_add_right_iff)\n    moreover from q have \"Suc q = m + w + r\" by (simp add: w_def)\n    moreover from q have \"Suc (Suc q) = v + w + r\" by (simp add: v_def w_def)\n    ultimately have \"w dvd Suc (Suc (q + (w - v mod w))) \\<longleftrightarrow> w dvd Suc (q + (w - m mod w))\"\n      by (simp only: add_Suc [symmetric])\n    then have \"Suc n dvd Suc (Suc (Suc (q + n) - Suc m mod Suc n)) \\<longleftrightarrow>\n      Suc n dvd Suc (Suc (q + n - m mod Suc n))\"\n      by (simp add: v_def w_def Suc_diff_le trans_le_add2)\n  }\n  then show ?case\n    by (auto simp add: mark_out_aux_def\n      enumerate_Suc_eq in_set_enumerate_eq not_less)\nqed\n\n\ntext \\<open>Main entry point to sieve\\<close>\n\nfun sieve :: \"nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"sieve n [] = []\"\n| \"sieve n (False # bs) = False # sieve (Suc n) bs\"\n| \"sieve n (True # bs) = True # sieve (Suc n) (mark_out n bs)\"\n\ntext \\<open>\n  There are the following possible optimisations here:\n\n  \\begin{itemize}\n\n    \\item @{const sieve} can abort as soon as @{term n} is too big to let\n      @{const mark_out} have any effect.\n\n    \\item Search for further primes can be given up as soon as the search\n      position exceeds the square root of the maximum candidate.\n\n  \\end{itemize}\n\n  This is left as an constructive exercise to the reader.\n\\<close>\n\nlemma numbers_of_marks_sieve:\n  \"numbers_of_marks (Suc n) (sieve n bs) =\n    {q \\<in> numbers_of_marks (Suc n) bs. \\<forall>m \\<in> numbers_of_marks (Suc n) bs. \\<not> m dvd_strict q}\"\nproof (induct n bs rule: sieve.induct)\n  case 1\n  show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 n bs)\n  have aux: \"n \\<in> Suc ` M \\<longleftrightarrow> n > 0 \\<and> n - 1 \\<in> M\" (is \"?lhs \\<longleftrightarrow> ?rhs\") for M n\n  proof\n    show ?rhs if ?lhs using that by auto\n    show ?lhs if ?rhs\n    proof -\n      from that have \"n > 0\" and \"n - 1 \\<in> M\" by auto\n      then have \"Suc (n - 1) \\<in> Suc ` M\" by blast\n      with \\<open>n > 0\\<close> show \"n \\<in> Suc ` M\" by simp\n    qed\n  qed\n  have aux1: False if \"Suc (Suc n) \\<le> m\" and \"m dvd Suc n\" for m :: nat\n  proof -\n    from \\<open>m dvd Suc n\\<close> obtain q where \"Suc n = m * q\" ..\n    with \\<open>Suc (Suc n) \\<le> m\\<close> have \"Suc (m * q) \\<le> m\" by simp\n    then have \"m * q < m\" by arith\n    then have \"q = 0\" by simp\n    with \\<open>Suc n = m * q\\<close> show ?thesis by simp\n  qed\n  have aux2: \"m dvd q\"\n    if 1: \"\\<forall>q>0. 1 < q \\<longrightarrow> Suc n < q \\<longrightarrow> q \\<le> Suc (n + length bs) \\<longrightarrow>\n      bs ! (q - Suc (Suc n)) \\<longrightarrow> \\<not> Suc n dvd q \\<longrightarrow> q dvd m \\<longrightarrow> m dvd q\"\n    and 2: \"\\<not> Suc n dvd m\" \"q dvd m\"\n    and 3: \"Suc n < q\" \"q \\<le> Suc (n + length bs)\" \"bs ! (q - Suc (Suc n))\"\n    for m q :: nat\n  proof -\n    from 1 have *: \"\\<And>q. Suc n < q \\<Longrightarrow> q \\<le> Suc (n + length bs) \\<Longrightarrow>\n      bs ! (q - Suc (Suc n)) \\<Longrightarrow> \\<not> Suc n dvd q \\<Longrightarrow> q dvd m \\<Longrightarrow> m dvd q\"\n      by auto\n    from 2 have \"\\<not> Suc n dvd q\" by (auto elim: dvdE)\n    moreover note 3\n    moreover note \\<open>q dvd m\\<close>\n    ultimately show ?thesis by (auto intro: *)\n  qed\n  from 3 show ?case\n    apply (simp_all add: numbers_of_marks_mark_out numbers_of_marks_Suc Compr_image_eq\n      inj_image_eq_iff in_numbers_of_marks_eq Ball_def imp_conjL aux)\n    apply safe\n    apply (simp_all add: less_diff_conv2 le_diff_conv2 dvd_minus_self not_less)\n    apply (clarsimp dest!: aux1)\n    apply (simp add: Suc_le_eq less_Suc_eq_le)\n    apply (rule aux2)\n    apply (clarsimp dest!: aux1)+\n    done\nqed\n\n\ntext \\<open>Relation of the sieve algorithm to actual primes\\<close>\n\ndefinition primes_upto :: \"nat \\<Rightarrow> nat list\"\nwhere\n  \"primes_upto n = sorted_list_of_set {m. m \\<le> n \\<and> prime m}\"\n\nlemma set_primes_upto: \"set (primes_upto n) = {m. m \\<le> n \\<and> prime m}\"\n  by (simp add: primes_upto_def)\n\nlemma sorted_primes_upto [iff]: \"sorted (primes_upto n)\"\n  by (simp add: primes_upto_def)\n\nlemma distinct_primes_upto [iff]: \"distinct (primes_upto n)\"\n  by (simp add: primes_upto_def)\n\nlemma set_primes_upto_sieve:\n  \"set (primes_upto n) = numbers_of_marks 2 (sieve 1 (replicate (n - 1) True))\"\nproof -\n  consider \"n = 0 \\<or> n = 1\" | \"n > 1\" by arith\n  then show ?thesis\n  proof cases\n    case 1\n    then show ?thesis\n      by (auto simp add: numbers_of_marks_sieve numeral_2_eq_2 set_primes_upto\n        dest: prime_gt_Suc_0_nat)\n  next\n    case 2\n    {\n      fix m q\n      assume \"Suc (Suc 0) \\<le> q\"\n        and \"q < Suc n\"\n        and \"m dvd q\"\n      then have \"m < Suc n\" by (auto dest: dvd_imp_le)\n      assume *: \"\\<forall>m\\<in>{Suc (Suc 0)..<Suc n}. m dvd q \\<longrightarrow> q dvd m\"\n        and \"m dvd q\" and \"m \\<noteq> 1\"\n      have \"m = q\"\n      proof (cases \"m = 0\")\n        case True with \\<open>m dvd q\\<close> show ?thesis by simp\n      next\n        case False with \\<open>m \\<noteq> 1\\<close> have \"Suc (Suc 0) \\<le> m\" by arith\n        with \\<open>m < Suc n\\<close> * \\<open>m dvd q\\<close> have \"q dvd m\" by simp\n        with \\<open>m dvd q\\<close> show ?thesis by (simp add: dvd_antisym)\n      qed\n    }\n    then have aux: \"\\<And>m q. Suc (Suc 0) \\<le> q \\<Longrightarrow>\n      q < Suc n \\<Longrightarrow>\n      m dvd q \\<Longrightarrow>\n      \\<forall>m\\<in>{Suc (Suc 0)..<Suc n}. m dvd q \\<longrightarrow> q dvd m \\<Longrightarrow>\n      m dvd q \\<Longrightarrow> m \\<noteq> q \\<Longrightarrow> m = 1\" by auto\n    from 2 show ?thesis\n      apply (auto simp add: numbers_of_marks_sieve numeral_2_eq_2 set_primes_upto\n        dest: prime_gt_Suc_0_nat)\n      apply (metis One_nat_def Suc_le_eq less_not_refl prime_nat_iff)\n      apply (metis One_nat_def Suc_le_eq aux prime_nat_iff)\n      done\n  qed\nqed\n\nlemma primes_upto_sieve [code]:\n  \"primes_upto n = map fst (filter snd (enumerate 2 (sieve 1 (replicate (n - 1) True))))\"\nproof -\n  have \"primes_upto n = sorted_list_of_set (numbers_of_marks 2 (sieve 1 (replicate (n - 1) True)))\"\n    apply (rule sorted_distinct_set_unique)\n    apply (simp_all only: set_primes_upto_sieve numbers_of_marks_def)\n    apply auto\n    done\n  then show ?thesis\n    by (simp add: sorted_list_of_set_numbers_of_marks)\nqed\n\nlemma prime_in_primes_upto: \"prime n \\<longleftrightarrow> n \\<in> set (primes_upto n)\"\n  by (simp add: set_primes_upto)\n\n\nsubsection \\<open>Application: smallest prime beyond a certain number\\<close>\n\ndefinition smallest_prime_beyond :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"smallest_prime_beyond n = (LEAST p. prime p \\<and> p \\<ge> n)\"\n\nlemma prime_smallest_prime_beyond [iff]: \"prime (smallest_prime_beyond n)\" (is ?P)\n  and smallest_prime_beyond_le [iff]: \"smallest_prime_beyond n \\<ge> n\" (is ?Q)\nproof -\n  let ?least = \"LEAST p. prime p \\<and> p \\<ge> n\"\n  from primes_infinite obtain q where \"prime q \\<and> q \\<ge> n\"\n    by (metis finite_nat_set_iff_bounded_le mem_Collect_eq nat_le_linear)\n  then have \"prime ?least \\<and> ?least \\<ge> n\"\n    by (rule LeastI)\n  then show ?P and ?Q\n    by (simp_all add: smallest_prime_beyond_def)\nqed\n\nlemma smallest_prime_beyond_smallest: \"prime p \\<Longrightarrow> p \\<ge> n \\<Longrightarrow> smallest_prime_beyond n \\<le> p\"\n  by (simp only: smallest_prime_beyond_def) (auto intro: Least_le)\n\nlemma smallest_prime_beyond_eq:\n  \"prime p \\<Longrightarrow> p \\<ge> n \\<Longrightarrow> (\\<And>q. prime q \\<Longrightarrow> q \\<ge> n \\<Longrightarrow> q \\<ge> p) \\<Longrightarrow> smallest_prime_beyond n = p\"\n  by (simp only: smallest_prime_beyond_def) (auto intro: Least_equality)\n\ndefinition smallest_prime_between :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat option\"\nwhere\n  \"smallest_prime_between m n =\n    (if (\\<exists>p. prime p \\<and> m \\<le> p \\<and> p \\<le> n) then Some (smallest_prime_beyond m) else None)\"\n\nlemma smallest_prime_between_None:\n  \"smallest_prime_between m n = None \\<longleftrightarrow> (\\<forall>q. m \\<le> q \\<and> q \\<le> n \\<longrightarrow> \\<not> prime q)\"\n  by (auto simp add: smallest_prime_between_def)\n\nlemma smallest_prime_betwen_Some:\n  \"smallest_prime_between m n = Some p \\<longleftrightarrow> smallest_prime_beyond m = p \\<and> p \\<le> n\"\n  by (auto simp add: smallest_prime_between_def dest: smallest_prime_beyond_smallest [of _ m])\n\n\n\ndefinition smallest_prime_beyond_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"smallest_prime_beyond_aux k n = smallest_prime_beyond n\"\n\nlemma [code]:\n  \"smallest_prime_beyond_aux k n =\n    (case smallest_prime_between n (k * n) of\n      Some p \\<Rightarrow> p\n    | None \\<Rightarrow> smallest_prime_beyond_aux (Suc k) n)\"\n  by (simp add: smallest_prime_beyond_aux_def smallest_prime_betwen_Some split: option.split)\n\nlemma [code]: \"smallest_prime_beyond n = smallest_prime_beyond_aux 2 n\"\n  by (simp add: smallest_prime_beyond_aux_def)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Number_Theory/Eratosthenes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7762821080691372}}
{"text": "section\\<open>Basics needed\\<close>\n\ntheory PerfectBasics\nimports Main \"HOL-Computational_Algebra.Primes\" \"HOL-Algebra.Exponent\"\nbegin\n\nlemma exp_is_max_div:\n   assumes m0: \"m \\<noteq> 0\" and p: \"prime p\"\n   shows \"~ p dvd (m div (p^(multiplicity p m)))\"\nproof (rule ccontr)\n  assume \"~ ~ p dvd (m div (p^(multiplicity p m)))\"\n  hence a:\"p dvd (m div (p^(multiplicity p m)))\" by auto\n  from m0 have \"p^(multiplicity p m) dvd m\" by (auto simp add: multiplicity_dvd)\n  with a have \"p^Suc (multiplicity p m) dvd m\"\n    by (subst (asm) dvd_div_iff_mult) auto\n  with m0 p show False\n    by (subst (asm) power_dvd_iff_le_multiplicity) auto\nqed\n\nlemma coprime_multiplicity:\n  assumes \"prime (p::nat)\" and \"m > 0\"\n  shows \"coprime p (m div (p ^ multiplicity p m))\"\nproof (rule ccontr)\n  assume \"\\<not> coprime p (m div p ^ multiplicity p m)\"\n  with \\<open>prime p\\<close> have \"\\<exists>q. prime q \\<and> q dvd p \\<and> q dvd m div p ^ multiplicity p m\"\n    by (metis dvd_refl prime_imp_coprime)\n  with \\<open>prime p\\<close> have \"\\<exists>q. q = p \\<and> q dvd m div p ^ multiplicity p m\"\n    by (metis not_prime_1 prime_nat_iff)\n  then have \"p dvd m div p ^ multiplicity p m\"\n    by auto\n  with assms show False\n    by (auto simp add: exp_is_max_div)\nqed\n\ntheorem simplify_sum_of_powers: \"(x - 1::nat) * (\\<Sum>i=0 .. n . x^i)  = x^(n + 1) - 1\" (is \"?l = ?r\")\nproof (cases)\n  assume \"n = 0\"\n  thus \"?l = x^(n+1) - 1\" by auto\nnext\n  assume \"n\\<noteq>0\"\n  hence n0: \"n>0\" by auto \n  have \"?l  = (x::nat)*(\\<Sum>i=0 .. n . x^i) - (\\<Sum>i=0 .. n . x^i)\"\n    by (metis diff_mult_distrib nat_mult_1)\n  also have \"... = (\\<Sum>i=0 .. n . x^(Suc i))    - (\\<Sum>i=0 .. n . x^i)\"\n    by (simp add: sum_distrib_left)\n  also have \"... = (\\<Sum>i=Suc 0 .. Suc n . x^i)  - (\\<Sum>i=0 .. n . x^i)\"\n    by (metis sum.shift_bounds_cl_Suc_ivl)\n  also have \"... = ((\\<Sum>i=Suc 0 .. n. x^i)+x^(Suc n)) - (x^0 + (\\<Sum>i=Suc 0 .. n. x^i))\"\n    by (simp add: sum.union_disjoint diff_add_inverse sum.atLeast_Suc_atMost)\n  finally show \"?thesis\" by auto\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Perfect-Number-Thm/PerfectBasics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7762821056710287}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_MSortBU2Sorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(Nat list) list => (Nat list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(Nat list) list => Nat list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun ordered :: \"Nat list => bool\" where\n  \"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun risers :: \"Nat list => (Nat list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if le y y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun msortbu2 :: \"Nat list => Nat list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\ntheorem property0 :\n  \"ordered (msortbu2 xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_MSortBU2Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7762821053287072}}
{"text": "(*  Title:      HOL/Finite_Set.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Jeremy Avigad\n    Author:     Andrei Popescu\n*)\n\nsection \\<open>Finite sets\\<close>\n\ntheory Finite_Set\n  imports Product_Type Sum_Type Fields\nbegin\n\nsubsection \\<open>Predicate for finite sets\\<close>\n\ncontext notes [[inductive_internals]]\nbegin\n\ninductive finite :: \"'a set \\<Rightarrow> bool\"\n  where\n    emptyI [simp, intro!]: \"finite {}\"\n  | insertI [simp, intro!]: \"finite A \\<Longrightarrow> finite (insert a A)\"\n\nend\n\nsimproc_setup finite_Collect (\"finite (Collect P)\") = \\<open>K Set_Comprehension_Pointfree.simproc\\<close>\n\ndeclare [[simproc del: finite_Collect]]\n\nlemma finite_induct [case_names empty insert, induct set: finite]:\n  \\<comment> \\<open>Discharging \\<open>x \\<notin> F\\<close> entails extra work.\\<close>\n  assumes \"finite F\"\n  assumes \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\n  using \\<open>finite F\\<close>\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume F: \"finite F\" and P: \"P F\"\n  show \"P (insert x F)\"\n  proof cases\n    assume \"x \\<in> F\"\n    then have \"insert x F = F\" by (rule insert_absorb)\n    with P show ?thesis by (simp only:)\n  next\n    assume \"x \\<notin> F\"\n    from F this P show ?thesis by (rule insert)\n  qed\nqed\n\nlemma infinite_finite_induct [case_names infinite empty insert]:\n  assumes infinite: \"\\<And>A. \\<not> finite A \\<Longrightarrow> P A\"\n    and empty: \"P {}\"\n    and insert: \"\\<And>x F. finite F \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert x F)\"\n  shows \"P A\"\nproof (cases \"finite A\")\n  case False\n  with infinite show ?thesis .\nnext\n  case True\n  then show ?thesis by (induct A) (fact empty insert)+\nqed\n\n\nsubsubsection \\<open>Choice principles\\<close>\n\nlemma ex_new_if_finite: \\<comment> \\<open>does not depend on def of finite at all\\<close>\n  assumes \"\\<not> finite (UNIV :: 'a set)\" and \"finite A\"\n  shows \"\\<exists>a::'a. a \\<notin> A\"\nproof -\n  from assms have \"A \\<noteq> UNIV\" by blast\n  then show ?thesis by blast\nqed\n\ntext \\<open>A finite choice principle. Does not need the SOME choice operator.\\<close>\n\nlemma finite_set_choice: \"finite A \\<Longrightarrow> \\<forall>x\\<in>A. \\<exists>y. P x y \\<Longrightarrow> \\<exists>f. \\<forall>x\\<in>A. P x (f x)\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  then obtain f b where f: \"\\<forall>x\\<in>A. P x (f x)\" and ab: \"P a b\"\n    by auto\n  show ?case (is \"\\<exists>f. ?P f\")\n  proof\n    show \"?P (\\<lambda>x. if x = a then b else f x)\"\n      using f ab by auto\n  qed\nqed\n\n\nsubsubsection \\<open>Finite sets are the images of initial segments of natural numbers\\<close>\n\nlemma finite_imp_nat_seg_image_inj_on:\n  assumes \"finite A\"\n  shows \"\\<exists>(n::nat) f. A = f ` {i. i < n} \\<and> inj_on f {i. i < n}\"\n  using assms\nproof induct\n  case empty\n  show ?case\n  proof\n    show \"\\<exists>f. {} = f ` {i::nat. i < 0} \\<and> inj_on f {i. i < 0}\"\n      by simp\n  qed\nnext\n  case (insert a A)\n  have notinA: \"a \\<notin> A\" by fact\n  from insert.hyps obtain n f where \"A = f ` {i::nat. i < n}\" \"inj_on f {i. i < n}\"\n    by blast\n  then have \"insert a A = f(n:=a) ` {i. i < Suc n}\" and \"inj_on (f(n:=a)) {i. i < Suc n}\"\n    using notinA by (auto simp add: image_def Ball_def inj_on_def less_Suc_eq)\n  then show ?case by blast\nqed\n\nlemma nat_seg_image_imp_finite: \"A = f ` {i::nat. i < n} \\<Longrightarrow> finite A\"\nproof (induct n arbitrary: A)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  let ?B = \"f ` {i. i < n}\"\n  have finB: \"finite ?B\" by (rule Suc.hyps[OF refl])\n  show ?case\n  proof (cases \"\\<exists>k<n. f n = f k\")\n    case True\n    then have \"A = ?B\"\n      using Suc.prems by (auto simp:less_Suc_eq)\n    then show ?thesis\n      using finB by simp\n  next\n    case False\n    then have \"A = insert (f n) ?B\"\n      using Suc.prems by (auto simp:less_Suc_eq)\n    then show ?thesis using finB by simp\n  qed\nqed\n\nlemma finite_conv_nat_seg_image: \"finite A \\<longleftrightarrow> (\\<exists>n f. A = f ` {i::nat. i < n})\"\n  by (blast intro: nat_seg_image_imp_finite dest: finite_imp_nat_seg_image_inj_on)\n\nlemma finite_imp_inj_to_nat_seg:\n  assumes \"finite A\"\n  shows \"\\<exists>f n. f ` A = {i::nat. i < n} \\<and> inj_on f A\"\nproof -\n  from finite_imp_nat_seg_image_inj_on [OF \\<open>finite A\\<close>]\n  obtain f and n :: nat where bij: \"bij_betw f {i. i<n} A\"\n    by (auto simp: bij_betw_def)\n  let ?f = \"the_inv_into {i. i<n} f\"\n  have \"inj_on ?f A \\<and> ?f ` A = {i. i<n}\"\n    by (fold bij_betw_def) (rule bij_betw_the_inv_into[OF bij])\n  then show ?thesis by blast\nqed\n\nlemma finite_Collect_less_nat [iff]: \"finite {n::nat. n < k}\"\n  by (fastforce simp: finite_conv_nat_seg_image)\n\nlemma finite_Collect_le_nat [iff]: \"finite {n::nat. n \\<le> k}\"\n  by (simp add: le_eq_less_or_eq Collect_disj_eq)\n\n\nsubsection \\<open>Finiteness and common set operations\\<close>\n\nlemma rev_finite_subset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> finite A\"\nproof (induct arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F A)\n  have A: \"A \\<subseteq> insert x F\" and r: \"A - {x} \\<subseteq> F \\<Longrightarrow> finite (A - {x})\"\n    by fact+\n  show \"finite A\"\n  proof cases\n    assume x: \"x \\<in> A\"\n    with A have \"A - {x} \\<subseteq> F\" by (simp add: subset_insert_iff)\n    with r have \"finite (A - {x})\" .\n    then have \"finite (insert x (A - {x}))\" ..\n    also have \"insert x (A - {x}) = A\"\n      using x by (rule insert_Diff)\n    finally show ?thesis .\n  next\n    show ?thesis when \"A \\<subseteq> F\"\n      using that by fact\n    assume \"x \\<notin> A\"\n    with A show \"A \\<subseteq> F\"\n      by (simp add: subset_insert_iff)\n  qed\nqed\n\nlemma finite_subset: \"A \\<subseteq> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  by (rule rev_finite_subset)\n\nlemma finite_UnI:\n  assumes \"finite F\" and \"finite G\"\n  shows \"finite (F \\<union> G)\"\n  using assms by induct simp_all\n\nlemma finite_Un [iff]: \"finite (F \\<union> G) \\<longleftrightarrow> finite F \\<and> finite G\"\n  by (blast intro: finite_UnI finite_subset [of _ \"F \\<union> G\"])\n\nlemma finite_insert [simp]: \"finite (insert a A) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite {a} \\<and> finite A \\<longleftrightarrow> finite A\" by simp\n  then have \"finite ({a} \\<union> A) \\<longleftrightarrow> finite A\" by (simp only: finite_Un)\n  then show ?thesis by simp\nqed\n\nlemma finite_Int [simp, intro]: \"finite F \\<or> finite G \\<Longrightarrow> finite (F \\<inter> G)\"\n  by (blast intro: finite_subset)\n\nlemma finite_Collect_conjI [simp, intro]:\n  \"finite {x. P x} \\<or> finite {x. Q x} \\<Longrightarrow> finite {x. P x \\<and> Q x}\"\n  by (simp add: Collect_conj_eq)\n\nlemma finite_Collect_disjI [simp]:\n  \"finite {x. P x \\<or> Q x} \\<longleftrightarrow> finite {x. P x} \\<and> finite {x. Q x}\"\n  by (simp add: Collect_disj_eq)\n\nlemma finite_Diff [simp, intro]: \"finite A \\<Longrightarrow> finite (A - B)\"\n  by (rule finite_subset, rule Diff_subset)\n\nlemma finite_Diff2 [simp]:\n  assumes \"finite B\"\n  shows \"finite (A - B) \\<longleftrightarrow> finite A\"\nproof -\n  have \"finite A \\<longleftrightarrow> finite ((A - B) \\<union> (A \\<inter> B))\"\n    by (simp add: Un_Diff_Int)\n  also have \"\\<dots> \\<longleftrightarrow> finite (A - B)\"\n    using \\<open>finite B\\<close> by simp\n  finally show ?thesis ..\nqed\n\nlemma finite_Diff_insert [iff]: \"finite (A - insert a B) \\<longleftrightarrow> finite (A - B)\"\nproof -\n  have \"finite (A - B) \\<longleftrightarrow> finite (A - B - {a})\" by simp\n  moreover have \"A - insert a B = A - B - {a}\" by auto\n  ultimately show ?thesis by simp\nqed\n\nlemma finite_compl [simp]:\n  \"finite (A :: 'a set) \\<Longrightarrow> finite (- A) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Compl_eq_Diff_UNIV)\n\nlemma finite_Collect_not [simp]:\n  \"finite {x :: 'a. P x} \\<Longrightarrow> finite {x. \\<not> P x} \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp add: Collect_neg_eq)\n\nlemma finite_Union [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>M. M \\<in> A \\<Longrightarrow> finite M) \\<Longrightarrow> finite (\\<Union>A)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN_I [intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (\\<Union>a\\<in>A. B a)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_UN [simp]: \"finite A \\<Longrightarrow> finite (\\<Union>(B ` A)) \\<longleftrightarrow> (\\<forall>x\\<in>A. finite (B x))\"\n  by (blast intro: finite_subset)\n\nlemma finite_Inter [intro]: \"\\<exists>A\\<in>M. finite A \\<Longrightarrow> finite (\\<Inter>M)\"\n  by (blast intro: Inter_lower finite_subset)\n\nlemma finite_INT [intro]: \"\\<exists>x\\<in>I. finite (A x) \\<Longrightarrow> finite (\\<Inter>x\\<in>I. A x)\"\n  by (blast intro: INT_lower finite_subset)\n\nlemma finite_imageI [simp, intro]: \"finite F \\<Longrightarrow> finite (h ` F)\"\n  by (induct rule: finite_induct) simp_all\n\nlemma finite_image_set [simp]: \"finite {x. P x} \\<Longrightarrow> finite {f x |x. P x}\"\n  by (simp add: image_Collect [symmetric])\n\nlemma finite_image_set2:\n  \"finite {x. P x} \\<Longrightarrow> finite {y. Q y} \\<Longrightarrow> finite {f x y |x y. P x \\<and> Q y}\"\n  by (rule finite_subset [where B = \"\\<Union>x \\<in> {x. P x}. \\<Union>y \\<in> {y. Q y}. {f x y}\"]) auto\n\nlemma finite_imageD:\n  assumes \"finite (f ` A)\" and \"inj_on f A\"\n  shows \"finite A\"\n  using assms\nproof (induct \"f ` A\" arbitrary: A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x B)\n  then have B_A: \"insert x B = f ` A\"\n    by simp\n  then obtain y where \"x = f y\" and \"y \\<in> A\"\n    by blast\n  from B_A \\<open>x \\<notin> B\\<close> have \"B = f ` A - {x}\"\n    by blast\n  with B_A \\<open>x \\<notin> B\\<close> \\<open>x = f y\\<close> \\<open>inj_on f A\\<close> \\<open>y \\<in> A\\<close> have \"B = f ` (A - {y})\"\n    by (simp add: inj_on_image_set_diff)\n  moreover from \\<open>inj_on f A\\<close> have \"inj_on f (A - {y})\"\n    by (rule inj_on_diff)\n  ultimately have \"finite (A - {y})\"\n    by (rule insert.hyps)\n  then show \"finite A\"\n    by simp\nqed\n\nlemma finite_image_iff: \"inj_on f A \\<Longrightarrow> finite (f ` A) \\<longleftrightarrow> finite A\"\n  using finite_imageD by blast\n\nlemma finite_surj: \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> finite B\"\n  by (erule finite_subset) (rule finite_imageI)\n\nlemma finite_range_imageI: \"finite (range g) \\<Longrightarrow> finite (range (\\<lambda>x. f (g x)))\"\n  by (drule finite_imageI) (simp add: range_composition)\n\nlemma finite_subset_image:\n  assumes \"finite B\"\n  shows \"B \\<subseteq> f ` A \\<Longrightarrow> \\<exists>C\\<subseteq>A. finite C \\<and> B = f ` C\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (clarsimp simp del: image_insert simp add: image_insert [symmetric]) blast\nqed\n\nlemma all_subset_image: \"(\\<forall>B. B \\<subseteq> f ` A \\<longrightarrow> P B) \\<longleftrightarrow> (\\<forall>B. B \\<subseteq> A \\<longrightarrow> P(f ` B))\"\n  by (safe elim!: subset_imageE) (use image_mono in \\<open>blast+\\<close>) (* slow *)\n\nlemma all_finite_subset_image:\n  \"(\\<forall>B. finite B \\<and> B \\<subseteq> f ` A \\<longrightarrow> P B) \\<longleftrightarrow> (\\<forall>B. finite B \\<and> B \\<subseteq> A \\<longrightarrow> P (f ` B))\"\nproof safe\n  fix B :: \"'a set\"\n  assume B: \"finite B\" \"B \\<subseteq> f ` A\" and P: \"\\<forall>B. finite B \\<and> B \\<subseteq> A \\<longrightarrow> P (f ` B)\"\n  show \"P B\"\n    using finite_subset_image [OF B] P by blast\nqed blast\n\nlemma ex_finite_subset_image:\n  \"(\\<exists>B. finite B \\<and> B \\<subseteq> f ` A \\<and> P B) \\<longleftrightarrow> (\\<exists>B. finite B \\<and> B \\<subseteq> A \\<and> P (f ` B))\"\nproof safe\n  fix B :: \"'a set\"\n  assume B: \"finite B\" \"B \\<subseteq> f ` A\" and \"P B\"\n  show \"\\<exists>B. finite B \\<and> B \\<subseteq> A \\<and> P (f ` B)\"\n    using finite_subset_image [OF B] \\<open>P B\\<close> by blast\nqed blast\n\nlemma finite_vimage_IntI: \"finite F \\<Longrightarrow> inj_on h A \\<Longrightarrow> finite (h -` F \\<inter> A)\"\nproof (induct rule: finite_induct)\n  case (insert x F)\n  then show ?case\n    by (simp add: vimage_insert [of h x F] finite_subset [OF inj_on_vimage_singleton] Int_Un_distrib2)\nqed simp\n\nlemma finite_finite_vimage_IntI:\n  assumes \"finite F\"\n    and \"\\<And>y. y \\<in> F \\<Longrightarrow> finite ((h -` {y}) \\<inter> A)\"\n  shows \"finite (h -` F \\<inter> A)\"\nproof -\n  have *: \"h -` F \\<inter> A = (\\<Union> y\\<in>F. (h -` {y}) \\<inter> A)\"\n    by blast\n  show ?thesis\n    by (simp only: * assms finite_UN_I)\nqed\n\nlemma finite_vimageI: \"finite F \\<Longrightarrow> inj h \\<Longrightarrow> finite (h -` F)\"\n  using finite_vimage_IntI[of F h UNIV] by auto\n\nlemma finite_vimageD': \"finite (f -` A) \\<Longrightarrow> A \\<subseteq> range f \\<Longrightarrow> finite A\"\n  by (auto simp add: subset_image_iff intro: finite_subset[rotated])\n\nlemma finite_vimageD: \"finite (h -` F) \\<Longrightarrow> surj h \\<Longrightarrow> finite F\"\n  by (auto dest: finite_vimageD')\n\nlemma finite_vimage_iff: \"bij h \\<Longrightarrow> finite (h -` F) \\<longleftrightarrow> finite F\"\n  unfolding bij_def by (auto elim: finite_vimageD finite_vimageI)\n\nlemma finite_inverse_image_gen:\n  assumes \"finite A\" \"inj_on f D\"\n  shows \"finite {j\\<in>D. f j \\<in> A}\"\n  using finite_vimage_IntI [OF assms]\n  by (simp add: Collect_conj_eq inf_commute vimage_def)\n\nlemma finite_inverse_image:\n  assumes \"finite A\" \"inj f\"\n  shows \"finite {j. f j \\<in> A}\"\n  using finite_inverse_image_gen [OF assms] by simp\n\nlemma finite_Collect_bex [simp]:\n  assumes \"finite A\"\n  shows \"finite {x. \\<exists>y\\<in>A. Q x y} \\<longleftrightarrow> (\\<forall>y\\<in>A. finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y\\<in>A. Q x y} = (\\<Union>y\\<in>A. {x. Q x y})\" by auto\n  with assms show ?thesis by simp\nqed\n\nlemma finite_Collect_bounded_ex [simp]:\n  assumes \"finite {y. P y}\"\n  shows \"finite {x. \\<exists>y. P y \\<and> Q x y} \\<longleftrightarrow> (\\<forall>y. P y \\<longrightarrow> finite {x. Q x y})\"\nproof -\n  have \"{x. \\<exists>y. P y \\<and> Q x y} = (\\<Union>y\\<in>{y. P y}. {x. Q x y})\"\n    by auto\n  with assms show ?thesis\n    by simp\nqed\n\nlemma finite_Plus: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A <+> B)\"\n  by (simp add: Plus_def)\n\nlemma finite_PlusD:\n  fixes A :: \"'a set\" and B :: \"'b set\"\n  assumes fin: \"finite (A <+> B)\"\n  shows \"finite A\" \"finite B\"\nproof -\n  have \"Inl ` A \\<subseteq> A <+> B\"\n    by auto\n  then have \"finite (Inl ` A :: ('a + 'b) set)\"\n    using fin by (rule finite_subset)\n  then show \"finite A\"\n    by (rule finite_imageD) (auto intro: inj_onI)\nnext\n  have \"Inr ` B \\<subseteq> A <+> B\"\n    by auto\n  then have \"finite (Inr ` B :: ('a + 'b) set)\"\n    using fin by (rule finite_subset)\n  then show \"finite B\"\n    by (rule finite_imageD) (auto intro: inj_onI)\nqed\n\nlemma finite_Plus_iff [simp]: \"finite (A <+> B) \\<longleftrightarrow> finite A \\<and> finite B\"\n  by (auto intro: finite_PlusD finite_Plus)\n\nlemma finite_Plus_UNIV_iff [simp]:\n  \"finite (UNIV :: ('a + 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  by (subst UNIV_Plus_UNIV [symmetric]) (rule finite_Plus_iff)\n\nlemma finite_SigmaI [simp, intro]:\n  \"finite A \\<Longrightarrow> (\\<And>a. a\\<in>A \\<Longrightarrow> finite (B a)) \\<Longrightarrow> finite (SIGMA a:A. B a)\"\n  unfolding Sigma_def by blast\n\nlemma finite_SigmaI2:\n  assumes \"finite {x\\<in>A. B x \\<noteq> {}}\"\n  and \"\\<And>a. a \\<in> A \\<Longrightarrow> finite (B a)\"\n  shows \"finite (Sigma A B)\"\nproof -\n  from assms have \"finite (Sigma {x\\<in>A. B x \\<noteq> {}} B)\"\n    by auto\n  also have \"Sigma {x:A. B x \\<noteq> {}} B = Sigma A B\"\n    by auto\n  finally show ?thesis .\nqed\n\nlemma finite_cartesian_product: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> finite (A \\<times> B)\"\n  by (rule finite_SigmaI)\n\nlemma finite_Prod_UNIV:\n  \"finite (UNIV :: 'a set) \\<Longrightarrow> finite (UNIV :: 'b set) \\<Longrightarrow> finite (UNIV :: ('a \\<times> 'b) set)\"\n  by (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product)\n\nlemma finite_cartesian_productD1:\n  assumes \"finite (A \\<times> B)\" and \"B \\<noteq> {}\"\n  shows \"finite A\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"fst ` (A \\<times> B) = fst ` f ` {i::nat. i < n}\"\n    by simp\n  with \\<open>B \\<noteq> {}\\<close> have \"A = (fst \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. A = f ` {i::nat. i < n}\"\n    by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_productD2:\n  assumes \"finite (A \\<times> B)\" and \"A \\<noteq> {}\"\n  shows \"finite B\"\nproof -\n  from assms obtain n f where \"A \\<times> B = f ` {i::nat. i < n}\"\n    by (auto simp add: finite_conv_nat_seg_image)\n  then have \"snd ` (A \\<times> B) = snd ` f ` {i::nat. i < n}\"\n    by simp\n  with \\<open>A \\<noteq> {}\\<close> have \"B = (snd \\<circ> f) ` {i::nat. i < n}\"\n    by (simp add: image_comp)\n  then have \"\\<exists>n f. B = f ` {i::nat. i < n}\"\n    by blast\n  then show ?thesis\n    by (auto simp add: finite_conv_nat_seg_image)\nqed\n\nlemma finite_cartesian_product_iff:\n  \"finite (A \\<times> B) \\<longleftrightarrow> (A = {} \\<or> B = {} \\<or> (finite A \\<and> finite B))\"\n  by (auto dest: finite_cartesian_productD1 finite_cartesian_productD2 finite_cartesian_product)\n\nlemma finite_prod:\n  \"finite (UNIV :: ('a \\<times> 'b) set) \\<longleftrightarrow> finite (UNIV :: 'a set) \\<and> finite (UNIV :: 'b set)\"\n  using finite_cartesian_product_iff[of UNIV UNIV] by simp\n\nlemma finite_Pow_iff [iff]: \"finite (Pow A) \\<longleftrightarrow> finite A\"\nproof\n  assume \"finite (Pow A)\"\n  then have \"finite ((\\<lambda>x. {x}) ` A)\"\n    by (blast intro: finite_subset)  (* somewhat slow *)\n  then show \"finite A\"\n    by (rule finite_imageD [unfolded inj_on_def]) simp\nnext\n  assume \"finite A\"\n  then show \"finite (Pow A)\"\n    by induct (simp_all add: Pow_insert)\nqed\n\ncorollary finite_Collect_subsets [simp, intro]: \"finite A \\<Longrightarrow> finite {B. B \\<subseteq> A}\"\n  by (simp add: Pow_def [symmetric])\n\nlemma finite_set: \"finite (UNIV :: 'a set set) \\<longleftrightarrow> finite (UNIV :: 'a set)\"\n  by (simp only: finite_Pow_iff Pow_UNIV[symmetric])\n\nlemma finite_UnionD: \"finite (\\<Union>A) \\<Longrightarrow> finite A\"\n  by (blast intro: finite_subset [OF subset_Pow_Union])\n\nlemma finite_bind:\n  assumes \"finite S\"\n  assumes \"\\<forall>x \\<in> S. finite (f x)\"\n  shows \"finite (Set.bind S f)\"\nusing assms by (simp add: bind_UNION)\n\nlemma finite_filter [simp]: \"finite S \\<Longrightarrow> finite (Set.filter P S)\"\nunfolding Set.filter_def by simp\n\nlemma finite_set_of_finite_funs:\n  assumes \"finite A\" \"finite B\"\n  shows \"finite {f. \\<forall>x. (x \\<in> A \\<longrightarrow> f x \\<in> B) \\<and> (x \\<notin> A \\<longrightarrow> f x = d)}\" (is \"finite ?S\")\nproof -\n  let ?F = \"\\<lambda>f. {(a,b). a \\<in> A \\<and> b = f a}\"\n  have \"?F ` ?S \\<subseteq> Pow(A \\<times> B)\"\n    by auto\n  from finite_subset[OF this] assms have 1: \"finite (?F ` ?S)\"\n    by simp\n  have 2: \"inj_on ?F ?S\"\n    by (fastforce simp add: inj_on_def set_eq_iff fun_eq_iff)  (* somewhat slow *)\n  show ?thesis\n    by (rule finite_imageD [OF 1 2])\nqed\n\nlemma not_finite_existsD:\n  assumes \"\\<not> finite {a. P a}\"\n  shows \"\\<exists>a. P a\"\nproof (rule classical)\n  assume \"\\<not> ?thesis\"\n  with assms show ?thesis by auto\nqed\n\n\nsubsection \\<open>Further induction rules on finite sets\\<close>\n\nlemma finite_ne_induct [case_names singleton insert, consumes 2]:\n  assumes \"finite F\" and \"F \\<noteq> {}\"\n  assumes \"\\<And>x. P {x}\"\n    and \"\\<And>x F. finite F \\<Longrightarrow> F \\<noteq> {} \\<Longrightarrow> x \\<notin> F \\<Longrightarrow> P F  \\<Longrightarrow> P (insert x F)\"\n  shows \"P F\"\n  using assms\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case by cases auto\nqed\n\nlemma finite_subset_induct [consumes 2, case_names empty insert]:\n  assumes \"finite F\" and \"F \\<subseteq> A\"\n    and empty: \"P {}\"\n    and insert: \"\\<And>a F. finite F \\<Longrightarrow> a \\<in> A \\<Longrightarrow> a \\<notin> F \\<Longrightarrow> P F \\<Longrightarrow> P (insert a F)\"\n  shows \"P F\"\n  using \\<open>finite F\\<close> \\<open>F \\<subseteq> A\\<close>\nproof induct\n  show \"P {}\" by fact\nnext\n  fix x F\n  assume \"finite F\" and \"x \\<notin> F\" and P: \"F \\<subseteq> A \\<Longrightarrow> P F\" and i: \"insert x F \\<subseteq> A\"\n  show \"P (insert x F)\"\n  proof (rule insert)\n    from i show \"x \\<in> A\" by blast\n    from i have \"F \\<subseteq> A\" by blast\n    with P show \"P F\" .\n    show \"finite F\" by fact\n    show \"x \\<notin> F\" by fact\n  qed\nqed\n\nlemma finite_empty_induct:\n  assumes \"finite A\"\n    and \"P A\"\n    and remove: \"\\<And>a A. finite A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> P A \\<Longrightarrow> P (A - {a})\"\n  shows \"P {}\"\nproof -\n  have \"P (A - B)\" if \"B \\<subseteq> A\" for B :: \"'a set\"\n  proof -\n    from \\<open>finite A\\<close> that have \"finite B\"\n      by (rule rev_finite_subset)\n    from this \\<open>B \\<subseteq> A\\<close> show \"P (A - B)\"\n    proof induct\n      case empty\n      from \\<open>P A\\<close> show ?case by simp\n    next\n      case (insert b B)\n      have \"P (A - B - {b})\"\n      proof (rule remove)\n        from \\<open>finite A\\<close> show \"finite (A - B)\"\n          by induct auto\n        from insert show \"b \\<in> A - B\"\n          by simp\n        from insert show \"P (A - B)\"\n          by simp\n      qed\n      also have \"A - B - {b} = A - insert b B\"\n        by (rule Diff_insert [symmetric])\n      finally show ?case .\n    qed\n  qed\n  then have \"P (A - A)\" by blast\n  then show ?thesis by simp\nqed\n\nlemma finite_update_induct [consumes 1, case_names const update]:\n  assumes finite: \"finite {a. f a \\<noteq> c}\"\n    and const: \"P (\\<lambda>a. c)\"\n    and update: \"\\<And>a b f. finite {a. f a \\<noteq> c} \\<Longrightarrow> f a = c \\<Longrightarrow> b \\<noteq> c \\<Longrightarrow> P f \\<Longrightarrow> P (f(a := b))\"\n  shows \"P f\"\n  using finite\nproof (induct \"{a. f a \\<noteq> c}\" arbitrary: f)\n  case empty\n  with const show ?case by simp\nnext\n  case (insert a A)\n  then have \"A = {a'. (f(a := c)) a' \\<noteq> c}\" and \"f a \\<noteq> c\"\n    by auto\n  with \\<open>finite A\\<close> have \"finite {a'. (f(a := c)) a' \\<noteq> c}\"\n    by simp\n  have \"(f(a := c)) a = c\"\n    by simp\n  from insert \\<open>A = {a'. (f(a := c)) a' \\<noteq> c}\\<close> have \"P (f(a := c))\"\n    by simp\n  with \\<open>finite {a'. (f(a := c)) a' \\<noteq> c}\\<close> \\<open>(f(a := c)) a = c\\<close> \\<open>f a \\<noteq> c\\<close>\n  have \"P ((f(a := c))(a := f a))\"\n    by (rule update)\n  then show ?case by simp\nqed\n\n\n\n\nsubsection \\<open>Class \\<open>finite\\<close>\\<close>\n\nclass finite =\n  assumes finite_UNIV: \"finite (UNIV :: 'a set)\"\nbegin\n\nlemma finite [simp]: \"finite (A :: 'a set)\"\n  by (rule subset_UNIV finite_UNIV finite_subset)+\n\nlemma finite_code [code]: \"finite (A :: 'a set) \\<longleftrightarrow> True\"\n  by simp\n\nend\n\ninstance prod :: (finite, finite) finite\n  by standard (simp only: UNIV_Times_UNIV [symmetric] finite_cartesian_product finite)\n\nlemma inj_graph: \"inj (\\<lambda>f. {(x, y). y = f x})\"\n  by (rule inj_onI) (auto simp add: set_eq_iff fun_eq_iff)\n\ninstance \"fun\" :: (finite, finite) finite\nproof\n  show \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  proof (rule finite_imageD)\n    let ?graph = \"\\<lambda>f::'a \\<Rightarrow> 'b. {(x, y). y = f x}\"\n    have \"range ?graph \\<subseteq> Pow UNIV\"\n      by simp\n    moreover have \"finite (Pow (UNIV :: ('a * 'b) set))\"\n      by (simp only: finite_Pow_iff finite)\n    ultimately show \"finite (range ?graph)\"\n      by (rule finite_subset)\n    show \"inj ?graph\"\n      by (rule inj_graph)\n  qed\nqed\n\ninstance bool :: finite\n  by standard (simp add: UNIV_bool)\n\ninstance set :: (finite) finite\n  by standard (simp only: Pow_UNIV [symmetric] finite_Pow_iff finite)\n\ninstance unit :: finite\n  by standard (simp add: UNIV_unit)\n\ninstance sum :: (finite, finite) finite\n  by standard (simp only: UNIV_Plus_UNIV [symmetric] finite_Plus finite)\n\n\nsubsection \\<open>A basic fold functional for finite sets\\<close>\n\ntext \\<open>\n  The intended behaviour is \\<open>fold f z {x\\<^sub>1, \\<dots>, x\\<^sub>n} = f x\\<^sub>1 (\\<dots> (f x\\<^sub>n z)\\<dots>)\\<close>\n  if \\<open>f\\<close> is ``left-commutative''.\n  The commutativity requirement is relativised to the carrier set \\<open>S\\<close>:\n\\<close>\n\nlocale comp_fun_commute_on =\n  fixes S :: \"'a set\"\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  assumes comp_fun_commute_on: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma fun_left_comm: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y (f x z) = f x (f y z)\"\n  using comp_fun_commute_on by (simp add: fun_eq_iff)\n\nlemma commute_left_comp: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y \\<circ> (f x \\<circ> g) = f x \\<circ> (f y \\<circ> g)\"\n  by (simp add: o_assoc comp_fun_commute_on)\n\nend\n\ninductive fold_graph :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  for f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: 'b\n  where\n    emptyI [intro]: \"fold_graph f z {} z\"\n  | insertI [intro]: \"x \\<notin> A \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> fold_graph f z (insert x A) (f x y)\"\n\ninductive_cases empty_fold_graphE [elim!]: \"fold_graph f z {} x\"\n\nlemma fold_graph_closed_lemma:\n  \"fold_graph f z A x \\<and> x \\<in> B\"\n  if \"fold_graph g z A x\"\n    \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> f a b = g a b\"\n    \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> g a b \\<in> B\"\n    \"z \\<in> B\"\n  using that(1-3)\nproof (induction rule: fold_graph.induct)\n  case (insertI x A y)\n  have \"fold_graph f z A y\" \"y \\<in> B\"\n    unfolding atomize_conj\n    by (rule insertI.IH) (auto intro: insertI.prems)\n  then have \"g x y \\<in> B\" and f_eq: \"f x y = g x y\"\n    by (auto simp: insertI.prems)\n  moreover have \"fold_graph f z (insert x A) (f x y)\"\n    by (rule fold_graph.insertI; fact)\n  ultimately\n  show ?case\n    by (simp add: f_eq)\nqed (auto intro!: that)\n\nlemma fold_graph_closed_eq:\n  \"fold_graph f z A = fold_graph g z A\"\n  if \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> f a b = g a b\"\n     \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> g a b \\<in> B\"\n     \"z \\<in> B\"\n  using fold_graph_closed_lemma[of f z A _ B g] fold_graph_closed_lemma[of g z A _ B f] that\n  by auto\n\ndefinition fold :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'b \\<Rightarrow> 'a set \\<Rightarrow> 'b\"\n  where \"fold f z A = (if finite A then (THE y. fold_graph f z A y) else z)\"\n\nlemma fold_closed_eq: \"fold f z A = fold g z A\"\n  if \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> f a b = g a b\"\n     \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> B \\<Longrightarrow> g a b \\<in> B\"\n     \"z \\<in> B\"\n  unfolding Finite_Set.fold_def\n  by (subst fold_graph_closed_eq[where B=B and g=g]) (auto simp: that)\n\ntext \\<open>\n  A tempting alternative for the definition is\n  \\<^term>\\<open>if finite A then THE y. fold_graph f z A y else e\\<close>.\n  It allows the removal of finiteness assumptions from the theorems\n  \\<open>fold_comm\\<close>, \\<open>fold_reindex\\<close> and \\<open>fold_distrib\\<close>.\n  The proofs become ugly. It is not worth the effort. (???)\n\\<close>\n\nlemma finite_imp_fold_graph: \"finite A \\<Longrightarrow> \\<exists>x. fold_graph f z A x\"\n  by (induct rule: finite_induct) auto\n\n\nsubsubsection \\<open>From \\<^const>\\<open>fold_graph\\<close> to \\<^term>\\<open>fold\\<close>\\<close>\n\ncontext comp_fun_commute_on\nbegin\n\n\n\nlemma fold_graph_insertE_aux:\n  assumes \"A \\<subseteq> S\"\n  assumes \"fold_graph f z A y\" \"a \\<in> A\"\n  shows \"\\<exists>y'. y = f a y' \\<and> fold_graph f z (A - {a}) y'\"\n  using assms(2-,1)\nproof (induct set: fold_graph)\n  case emptyI\n  then show ?case by simp\nnext\n  case (insertI x A y)\n  show ?case\n  proof (cases \"x = a\")\n    case True\n    with insertI show ?thesis by auto\n  next\n    case False\n    then obtain y' where y: \"y = f a y'\" and y': \"fold_graph f z (A - {a}) y'\"\n      using insertI by auto\n    from insertI have \"x \\<in> S\" \"a \\<in> S\" by auto\n    then have \"f x y = f a (f x y')\"\n      unfolding y by (intro fun_left_comm; simp)\n    moreover have \"fold_graph f z (insert x A - {a}) (f x y')\"\n      using y' and \\<open>x \\<noteq> a\\<close> and \\<open>x \\<notin> A\\<close>\n      by (simp add: insert_Diff_if fold_graph.insertI)\n    ultimately show ?thesis\n      by fast\n  qed\nqed\n\nlemma fold_graph_insertE:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes \"fold_graph f z (insert x A) v\" and \"x \\<notin> A\"\n  obtains y where \"v = f x y\" and \"fold_graph f z A y\"\n  using assms by (auto dest: fold_graph_insertE_aux[OF \\<open>insert x A \\<subseteq> S\\<close> _ insertI1])\n\nlemma fold_graph_determ:\n  assumes \"A \\<subseteq> S\"\n  assumes \"fold_graph f z A x\" \"fold_graph f z A y\"\n  shows \"y = x\"\n  using assms(2-,1)\nproof (induct arbitrary: y set: fold_graph)\n  case emptyI\n  then show ?case by fast\nnext\n  case (insertI x A y v)\n  from \\<open>insert x A \\<subseteq> S\\<close> and \\<open>fold_graph f z (insert x A) v\\<close> and \\<open>x \\<notin> A\\<close>\n  obtain y' where \"v = f x y'\" and \"fold_graph f z A y'\"\n    by (rule fold_graph_insertE)\n  from \\<open>fold_graph f z A y'\\<close> insertI have \"y' = y\"\n    by simp\n  with \\<open>v = f x y'\\<close> show \"v = f x y\"\n    by simp\nqed\n\nlemma fold_equality: \"A \\<subseteq> S \\<Longrightarrow> fold_graph f z A y \\<Longrightarrow> fold f z A = y\"\n  by (cases \"finite A\") (auto simp add: fold_def intro: fold_graph_determ dest: fold_graph_finite)\n\nlemma fold_graph_fold:\n  assumes \"A \\<subseteq> S\"\n  assumes \"finite A\"\n  shows \"fold_graph f z A (fold f z A)\"\nproof -\n  from \\<open>finite A\\<close> have \"\\<exists>x. fold_graph f z A x\"\n    by (rule finite_imp_fold_graph)\n  moreover note fold_graph_determ[OF \\<open>A \\<subseteq> S\\<close>]\n  ultimately have \"\\<exists>!x. fold_graph f z A x\"\n    by (rule ex_ex1I)\n  then have \"fold_graph f z A (The (fold_graph f z A))\"\n    by (rule theI')\n  with assms show ?thesis\n    by (simp add: fold_def)\nqed\n\ntext \\<open>The base case for \\<open>fold\\<close>:\\<close>\n\nlemma (in -) fold_infinite [simp]: \"\\<not> finite A \\<Longrightarrow> fold f z A = z\"\n  by (auto simp: fold_def)\n\nlemma (in -) fold_empty [simp]: \"fold f z {} = z\"\n  by (auto simp: fold_def)\n\ntext \\<open>The various recursion equations for \\<^const>\\<open>fold\\<close>:\\<close>\n\nlemma fold_insert [simp]:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes \"finite A\" and \"x \\<notin> A\"\n  shows \"fold f z (insert x A) = f x (fold f z A)\"\nproof (rule fold_equality[OF \\<open>insert x A \\<subseteq> S\\<close>])\n  fix z\n  from \\<open>insert x A \\<subseteq> S\\<close> \\<open>finite A\\<close> have \"fold_graph f z A (fold f z A)\"\n    by (blast intro: fold_graph_fold)\n  with \\<open>x \\<notin> A\\<close> have \"fold_graph f z (insert x A) (f x (fold f z A))\"\n    by (rule fold_graph.insertI)\n  then show \"fold_graph f z (insert x A) (f x (fold f z A))\"\n    by simp\nqed\n\ndeclare (in -) empty_fold_graphE [rule del] fold_graph.intros [rule del]\n  \\<comment> \\<open>No more proofs involve these.\\<close>\n\nlemma fold_fun_left_comm:\n  assumes \"insert x A \\<subseteq> S\" \"finite A\" \n  shows \"f x (fold f z A) = fold f (f x z) A\"\n  using assms(2,1)\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert y F)\n  then have \"fold f (f x z) (insert y F) = f y (fold f (f x z) F)\"\n    by simp\n  also have \"\\<dots> = f x (f y (fold f z F))\"\n    using insert by (simp add: fun_left_comm[where ?y=x])\n  also have \"\\<dots> = f x (fold f z (insert y F))\"\n  proof -\n    from insert have \"insert y F \\<subseteq> S\" by simp\n    from fold_insert[OF this] insert show ?thesis by simp\n  qed\n  finally show ?case ..\nqed\n\nlemma fold_insert2:\n  \"insert x A \\<subseteq> S \\<Longrightarrow> finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> fold f z (insert x A)  = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nlemma fold_rec:\n  assumes \"A \\<subseteq> S\"\n  assumes \"finite A\" and \"x \\<in> A\"\n  shows \"fold f z A = f x (fold f z (A - {x}))\"\nproof -\n  have A: \"A = insert x (A - {x})\"\n    using \\<open>x \\<in> A\\<close> by blast\n  then have \"fold f z A = fold f z (insert x (A - {x}))\"\n    by simp\n  also have \"\\<dots> = f x (fold f z (A - {x}))\"\n    by (rule fold_insert) (use assms in \\<open>auto\\<close>)\n  finally show ?thesis .\nqed\n\nlemma fold_insert_remove:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes \"finite A\"\n  shows \"fold f z (insert x A) = f x (fold f z (A - {x}))\"\nproof -\n  from \\<open>finite A\\<close> have \"finite (insert x A)\"\n    by auto\n  moreover have \"x \\<in> insert x A\"\n    by auto\n  ultimately have \"fold f z (insert x A) = f x (fold f z (insert x A - {x}))\"\n    using \\<open>insert x A \\<subseteq> S\\<close> by (blast intro: fold_rec)\n  then show ?thesis\n    by simp\nqed\n\nlemma fold_set_union_disj:\n  assumes \"A \\<subseteq> S\" \"B \\<subseteq> S\"\n  assumes \"finite A\" \"finite B\" \"A \\<inter> B = {}\"\n  shows \"Finite_Set.fold f z (A \\<union> B) = Finite_Set.fold f (Finite_Set.fold f z A) B\"\n  using \\<open>finite B\\<close> assms(1,2,3,5)\nproof induct\n  case (insert x F)\n  have \"fold f z (A \\<union> insert x F) = f x (fold f (fold f z A) F)\"\n    using insert by auto\n  also have \"\\<dots> = fold f (fold f z A) (insert x F)\"\n    using insert by (blast intro: fold_insert[symmetric])\n  finally show ?case .\nqed simp\n\n\nend\n\ntext \\<open>Other properties of \\<^const>\\<open>fold\\<close>:\\<close>\n\nlemma fold_graph_image:\n  assumes \"inj_on g A\"\n  shows \"fold_graph f z (g ` A) = fold_graph (f \\<circ> g) z A\"\nproof\n  fix w\n  show \"fold_graph f z (g ` A) w = fold_graph (f o g) z A w\"\n  proof\n    assume \"fold_graph f z (g ` A) w\"\n    then show \"fold_graph (f \\<circ> g) z A w\"\n      using assms\n    proof (induct \"g ` A\" w arbitrary: A)\n      case emptyI\n      then show ?case by (auto intro: fold_graph.emptyI)\n    next\n      case (insertI x A r B)\n      from \\<open>inj_on g B\\<close> \\<open>x \\<notin> A\\<close> \\<open>insert x A = image g B\\<close> obtain x' A'\n        where \"x' \\<notin> A'\" and [simp]: \"B = insert x' A'\" \"x = g x'\" \"A = g ` A'\"\n        by (rule inj_img_insertE)\n      from insertI.prems have \"fold_graph (f \\<circ> g) z A' r\"\n        by (auto intro: insertI.hyps)\n      with \\<open>x' \\<notin> A'\\<close> have \"fold_graph (f \\<circ> g) z (insert x' A') ((f \\<circ> g) x' r)\"\n        by (rule fold_graph.insertI)\n      then show ?case\n        by simp\n    qed\n  next\n    assume \"fold_graph (f \\<circ> g) z A w\"\n    then show \"fold_graph f z (g ` A) w\"\n      using assms\n    proof induct\n      case emptyI\n      then show ?case\n        by (auto intro: fold_graph.emptyI)\n    next\n      case (insertI x A r)\n      from \\<open>x \\<notin> A\\<close> insertI.prems have \"g x \\<notin> g ` A\"\n        by auto\n      moreover from insertI have \"fold_graph f z (g ` A) r\"\n        by simp\n      ultimately have \"fold_graph f z (insert (g x) (g ` A)) (f (g x) r)\"\n        by (rule fold_graph.insertI)\n      then show ?case\n        by simp\n    qed\n  qed\nqed\n\nlemma fold_image:\n  assumes \"inj_on g A\"\n  shows \"fold f z (g ` A) = fold (f \\<circ> g) z A\"\nproof (cases \"finite A\")\n  case False\n  with assms show ?thesis\n    by (auto dest: finite_imageD simp add: fold_def)\nnext\n  case True\n  then show ?thesis\n    by (auto simp add: fold_def fold_graph_image[OF assms])\nqed\n\nlemma fold_cong:\n  assumes \"comp_fun_commute_on S f\" \"comp_fun_commute_on S g\"\n    and \"A \\<subseteq> S\" \"finite A\"\n    and cong: \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x\"\n    and \"s = t\" and \"A = B\"\n  shows \"fold f s A = fold g t B\"\nproof -\n  have \"fold f s A = fold g s A\"\n    using \\<open>finite A\\<close> \\<open>A \\<subseteq> S\\<close> cong\n  proof (induct A)\n    case empty\n    then show ?case by simp\n  next\n    case insert\n    interpret f: comp_fun_commute_on S f by (fact \\<open>comp_fun_commute_on S f\\<close>)\n    interpret g: comp_fun_commute_on S g by (fact \\<open>comp_fun_commute_on S g\\<close>)\n    from insert show ?case by simp\n  qed\n  with assms show ?thesis by simp\nqed\n\n\ntext \\<open>A simplified version for idempotent functions:\\<close>\n\nlocale comp_fun_idem_on = comp_fun_commute_on +\n  assumes comp_fun_idem_on: \"x \\<in> S \\<Longrightarrow> f x \\<circ> f x = f x\"\nbegin\n\nlemma fun_left_idem: \"x \\<in> S \\<Longrightarrow> f x (f x z) = f x z\"\n  using comp_fun_idem_on by (simp add: fun_eq_iff)\n\nlemma fold_insert_idem:\n  assumes \"insert x A \\<subseteq> S\"\n  assumes fin: \"finite A\"\n  shows \"fold f z (insert x A)  = f x (fold f z A)\"\nproof cases\n  assume \"x \\<in> A\"\n  then obtain B where \"A = insert x B\" and \"x \\<notin> B\"\n    by (rule set_insert)\n  then show ?thesis\n    using assms by (simp add: comp_fun_idem_on fun_left_idem)\nnext\n  assume \"x \\<notin> A\"\n  then show ?thesis\n    using assms by auto\nqed\n\ndeclare fold_insert [simp del] fold_insert_idem [simp]\n\nlemma fold_insert_idem2: \"insert x A \\<subseteq> S \\<Longrightarrow> finite A \\<Longrightarrow> fold f z (insert x A) = fold f (f x z) A\"\n  by (simp add: fold_fun_left_comm)\n\nend\n\n\nsubsubsection \\<open>Liftings to \\<open>comp_fun_commute_on\\<close> etc.\\<close>\n                   \nlemma (in comp_fun_commute_on) comp_comp_fun_commute_on:\n  \"range g \\<subseteq> S \\<Longrightarrow> comp_fun_commute_on R (f \\<circ> g)\"\n  by standard (force intro: comp_fun_commute_on)\n\nlemma (in comp_fun_idem_on) comp_comp_fun_idem_on:\n  assumes \"range g \\<subseteq> S\"\n  shows \"comp_fun_idem_on R (f \\<circ> g)\"\nproof\n  interpret f_g: comp_fun_commute_on R \"f o g\"\n    by (fact comp_comp_fun_commute_on[OF \\<open>range g \\<subseteq> S\\<close>])\n  show \"x \\<in> R \\<Longrightarrow> y \\<in> R \\<Longrightarrow> (f \\<circ> g) y \\<circ> (f \\<circ> g) x = (f \\<circ> g) x \\<circ> (f \\<circ> g) y\" for x y\n    by (fact f_g.comp_fun_commute_on)\nqed (use \\<open>range g \\<subseteq> S\\<close> in \\<open>force intro: comp_fun_idem_on\\<close>)\n\nlemma (in comp_fun_commute_on) comp_fun_commute_on_funpow:\n  \"comp_fun_commute_on S (\\<lambda>x. f x ^^ g x)\"\nproof\n  fix x y assume \"x \\<in> S\" \"y \\<in> S\"\n  show \"f y ^^ g y \\<circ> f x ^^ g x = f x ^^ g x \\<circ> f y ^^ g y\"\n  proof (cases \"x = y\")\n    case True\n    then show ?thesis by simp\n  next\n    case False\n    show ?thesis\n    proof (induct \"g x\" arbitrary: g)\n      case 0\n      then show ?case by simp\n    next\n      case (Suc n g)\n      have hyp1: \"f y ^^ g y \\<circ> f x = f x \\<circ> f y ^^ g y\"\n      proof (induct \"g y\" arbitrary: g)\n        case 0\n        then show ?case by simp\n      next\n        case (Suc n g)\n        define h where \"h z = g z - 1\" for z\n        with Suc have \"n = h y\"\n          by simp\n        with Suc have hyp: \"f y ^^ h y \\<circ> f x = f x \\<circ> f y ^^ h y\"\n          by auto\n        from Suc h_def have \"g y = Suc (h y)\"\n          by simp\n        with \\<open>x \\<in> S\\<close> \\<open>y \\<in> S\\<close> show ?case\n          by (simp add: comp_assoc hyp) (simp add: o_assoc comp_fun_commute_on)\n      qed\n      define h where \"h z = (if z = x then g x - 1 else g z)\" for z\n      with Suc have \"n = h x\"\n        by simp\n      with Suc have \"f y ^^ h y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ h y\"\n        by auto\n      with False h_def have hyp2: \"f y ^^ g y \\<circ> f x ^^ h x = f x ^^ h x \\<circ> f y ^^ g y\"\n        by simp\n      from Suc h_def have \"g x = Suc (h x)\"\n        by simp\n      then show ?case\n        by (simp del: funpow.simps add: funpow_Suc_right o_assoc hyp2) (simp add: comp_assoc hyp1)\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>\\<^term>\\<open>UNIV\\<close> as carrier set\\<close>\n\nlocale comp_fun_commute =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma (in -) comp_fun_commute_def': \"comp_fun_commute f = comp_fun_commute_on UNIV f\"\n  unfolding comp_fun_commute_def comp_fun_commute_on_def by blast\n\ntext \\<open>\n  We abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale comp_fun_commute_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"comp_fun_commute_on UNIV f\"\n    by standard  (simp add: comp_fun_commute)\nqed simp_all\n\nend\n\nlemma (in comp_fun_commute) comp_comp_fun_commute: \"comp_fun_commute (f o g)\"\n  unfolding comp_fun_commute_def' by (fact comp_comp_fun_commute_on)\n\nlemma (in comp_fun_commute) comp_fun_commute_funpow: \"comp_fun_commute (\\<lambda>x. f x ^^ g x)\"\n  unfolding comp_fun_commute_def' by (fact comp_fun_commute_on_funpow)\n\nlocale comp_fun_idem = comp_fun_commute +\n  assumes comp_fun_idem: \"f x o f x = f x\"\nbegin\n\nlemma (in -) comp_fun_idem_def': \"comp_fun_idem f = comp_fun_idem_on UNIV f\"\n  unfolding comp_fun_idem_on_def comp_fun_idem_def comp_fun_commute_def'\n  unfolding comp_fun_idem_axioms_def comp_fun_idem_on_axioms_def\n  by blast\n\ntext \\<open>\n  Again, we abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale comp_fun_idem_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"comp_fun_idem_on UNIV f\"\n    by standard (simp_all add: comp_fun_idem comp_fun_commute)\nqed simp_all\n\nend\n\nlemma (in comp_fun_idem) comp_comp_fun_idem: \"comp_fun_idem (f o g)\"\n  unfolding comp_fun_idem_def' by (fact comp_comp_fun_idem_on)\n\n\nsubsubsection \\<open>Expressing set operations via \\<^const>\\<open>fold\\<close>\\<close>\n\nlemma comp_fun_commute_const: \"comp_fun_commute (\\<lambda>_. f)\"\n  by standard (rule refl)\n\nlemma comp_fun_idem_insert: \"comp_fun_idem insert\"\n  by standard auto\n\nlemma comp_fun_idem_remove: \"comp_fun_idem Set.remove\"\n  by standard auto\n\nlemma (in semilattice_inf) comp_fun_idem_inf: \"comp_fun_idem inf\"\n  by standard (auto simp add: inf_left_commute)\n\nlemma (in semilattice_sup) comp_fun_idem_sup: \"comp_fun_idem sup\"\n  by standard (auto simp add: sup_left_commute)\n\nlemma union_fold_insert:\n  assumes \"finite A\"\n  shows \"A \\<union> B = fold insert B A\"\nproof -\n  interpret comp_fun_idem insert\n    by (fact comp_fun_idem_insert)\n  from \\<open>finite A\\<close> show ?thesis\n    by (induct A arbitrary: B) simp_all\nqed\n\nlemma minus_fold_remove:\n  assumes \"finite A\"\n  shows \"B - A = fold Set.remove B A\"\nproof -\n  interpret comp_fun_idem Set.remove\n    by (fact comp_fun_idem_remove)\n  from \\<open>finite A\\<close> have \"fold Set.remove B A = B - A\"\n    by (induct A arbitrary: B) auto  (* slow *)\n  then show ?thesis ..\nqed\n\nlemma comp_fun_commute_filter_fold:\n  \"comp_fun_commute (\\<lambda>x A'. if P x then Set.insert x A' else A')\"\nproof -\n  interpret comp_fun_idem Set.insert by (fact comp_fun_idem_insert)\n  show ?thesis by standard (auto simp: fun_eq_iff)\nqed\n\nlemma Set_filter_fold:\n  assumes \"finite A\"\n  shows \"Set.filter P A = fold (\\<lambda>x A'. if P x then Set.insert x A' else A') {} A\"\n  using assms\nproof -\n  interpret commute_insert: comp_fun_commute \"(\\<lambda>x A'. if P x then Set.insert x A' else A')\"\n    by (fact comp_fun_commute_filter_fold)\n  from \\<open>finite A\\<close> show ?thesis\n    by induct (auto simp add: Set.filter_def)\nqed\n\nlemma inter_Set_filter:\n  assumes \"finite B\"\n  shows \"A \\<inter> B = Set.filter (\\<lambda>x. x \\<in> A) B\"\n  using assms\n  by induct (auto simp: Set.filter_def)\n\nlemma image_fold_insert:\n  assumes \"finite A\"\n  shows \"image f A = fold (\\<lambda>k A. Set.insert (f k) A) {} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k A. Set.insert (f k) A\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma Ball_fold:\n  assumes \"finite A\"\n  shows \"Ball A P = fold (\\<lambda>k s. s \\<and> P k) True A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<and> P k\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma Bex_fold:\n  assumes \"finite A\"\n  shows \"Bex A P = fold (\\<lambda>k s. s \\<or> P k) False A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>k s. s \\<or> P k\"\n    by standard auto\n  show ?thesis\n    using assms by (induct A) auto\nqed\n\nlemma comp_fun_commute_Pow_fold: \"comp_fun_commute (\\<lambda>x A. A \\<union> Set.insert x ` A)\"\n  by (clarsimp simp: fun_eq_iff comp_fun_commute_def) blast\n\nlemma Pow_fold:\n  assumes \"finite A\"\n  shows \"Pow A = fold (\\<lambda>x A. A \\<union> Set.insert x ` A) {{}} A\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>x A. A \\<union> Set.insert x ` A\"\n    by (rule comp_fun_commute_Pow_fold)\n  show ?thesis\n    using assms by (induct A) (auto simp: Pow_insert)\nqed\n\nlemma fold_union_pair:\n  assumes \"finite B\"\n  shows \"(\\<Union>y\\<in>B. {(x, y)}) \\<union> A = fold (\\<lambda>y. Set.insert (x, y)) A B\"\nproof -\n  interpret comp_fun_commute \"\\<lambda>y. Set.insert (x, y)\"\n    by standard auto\n  show ?thesis\n    using assms by (induct arbitrary: A) simp_all\nqed\n\nlemma comp_fun_commute_product_fold:\n  \"finite B \\<Longrightarrow> comp_fun_commute (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B)\"\n  by standard (auto simp: fold_union_pair [symmetric])\n\nlemma product_fold:\n  assumes \"finite A\" \"finite B\"\n  shows \"A \\<times> B = fold (\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B) {} A\"\nproof -\n  interpret commute_product: comp_fun_commute \"(\\<lambda>x z. fold (\\<lambda>y. Set.insert (x, y)) z B)\"\n    by (fact comp_fun_commute_product_fold[OF \\<open>finite B\\<close>])\n  from assms show ?thesis unfolding Sigma_def\n    by (induct A) (simp_all add: fold_union_pair)\nqed\n\ncontext complete_lattice\nbegin\n\nlemma inf_Inf_fold_inf:\n  assumes \"finite A\"\n  shows \"inf (Inf A) B = fold inf B A\"\nproof -\n  interpret comp_fun_idem inf\n    by (fact comp_fun_idem_inf)\n  from \\<open>finite A\\<close> fold_fun_left_comm show ?thesis\n    by (induct A arbitrary: B) (simp_all add: inf_commute fun_eq_iff)\nqed\n\nlemma sup_Sup_fold_sup:\n  assumes \"finite A\"\n  shows \"sup (Sup A) B = fold sup B A\"\nproof -\n  interpret comp_fun_idem sup\n    by (fact comp_fun_idem_sup)\n  from \\<open>finite A\\<close> fold_fun_left_comm show ?thesis\n    by (induct A arbitrary: B) (simp_all add: sup_commute fun_eq_iff)\nqed\n\nlemma Inf_fold_inf: \"finite A \\<Longrightarrow> Inf A = fold inf top A\"\n  using inf_Inf_fold_inf [of A top] by (simp add: inf_absorb2)\n\nlemma Sup_fold_sup: \"finite A \\<Longrightarrow> Sup A = fold sup bot A\"\n  using sup_Sup_fold_sup [of A bot] by (simp add: sup_absorb2)\n\nlemma inf_INF_fold_inf:\n  assumes \"finite A\"\n  shows \"inf B (\\<Sqinter>(f ` A)) = fold (inf \\<circ> f) B A\" (is \"?inf = ?fold\")\nproof -\n  interpret comp_fun_idem inf by (fact comp_fun_idem_inf)\n  interpret comp_fun_idem \"inf \\<circ> f\" by (fact comp_comp_fun_idem)\n  from \\<open>finite A\\<close> have \"?fold = ?inf\"\n    by (induct A arbitrary: B) (simp_all add: inf_left_commute)\n  then show ?thesis ..\nqed\n\nlemma sup_SUP_fold_sup:\n  assumes \"finite A\"\n  shows \"sup B (\\<Squnion>(f ` A)) = fold (sup \\<circ> f) B A\" (is \"?sup = ?fold\")\nproof -\n  interpret comp_fun_idem sup by (fact comp_fun_idem_sup)\n  interpret comp_fun_idem \"sup \\<circ> f\" by (fact comp_comp_fun_idem)\n  from \\<open>finite A\\<close> have \"?fold = ?sup\"\n    by (induct A arbitrary: B) (simp_all add: sup_left_commute)\n  then show ?thesis ..\nqed\n\nlemma INF_fold_inf: \"finite A \\<Longrightarrow> \\<Sqinter>(f ` A) = fold (inf \\<circ> f) top A\"\n  using inf_INF_fold_inf [of A top] by simp\n\nlemma SUP_fold_sup: \"finite A \\<Longrightarrow> \\<Squnion>(f ` A) = fold (sup \\<circ> f) bot A\"\n  using sup_SUP_fold_sup [of A bot] by simp\n\nlemma finite_Inf_in:\n  assumes \"finite A\" \"A\\<noteq>{}\" and inf: \"\\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> inf x y \\<in> A\"\n  shows \"Inf A \\<in> A\"\nproof -\n  have \"Inf B \\<in> A\" if \"B \\<le> A\" \"B\\<noteq>{}\" for B\n    using finite_subset [OF \\<open>B \\<subseteq> A\\<close> \\<open>finite A\\<close>] that\n  by (induction B) (use inf in \\<open>force+\\<close>)\n  then show ?thesis\n    by (simp add: assms)\nqed\n\nlemma finite_Sup_in:\n  assumes \"finite A\" \"A\\<noteq>{}\" and sup: \"\\<And>x y. \\<lbrakk>x \\<in> A; y \\<in> A\\<rbrakk> \\<Longrightarrow> sup x y \\<in> A\"\n  shows \"Sup A \\<in> A\"\nproof -\n  have \"Sup B \\<in> A\" if \"B \\<le> A\" \"B\\<noteq>{}\" for B\n    using finite_subset [OF \\<open>B \\<subseteq> A\\<close> \\<open>finite A\\<close>] that\n  by (induction B) (use sup in \\<open>force+\\<close>)\n  then show ?thesis\n    by (simp add: assms)\nqed\n\nend\n\n\nsubsection \\<open>Locales as mini-packages for fold operations\\<close>\n\nsubsubsection \\<open>The natural case\\<close>\n\nlocale folding_on =\n  fixes S :: \"'a set\"\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: \"'b\"\n  assumes comp_fun_commute_on: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f y o f x = f x o f y\"\nbegin\n\ninterpretation fold?: comp_fun_commute_on S f\n  by standard (simp add: comp_fun_commute_on)\n\ndefinition F :: \"'a set \\<Rightarrow> 'b\"\n  where eq_fold: \"F A = Finite_Set.fold f z A\"\n\nlemma empty [simp]: \"F {} = z\"\n  by (simp add: eq_fold)\n\nlemma infinite [simp]: \"\\<not> finite A \\<Longrightarrow> F A = z\"\n  by (simp add: eq_fold)\n\nlemma insert [simp]:\n  assumes \"insert x A \\<subseteq> S\" and \"finite A\" and \"x \\<notin> A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert assms\n  have \"Finite_Set.fold f z (insert x A) \n      = f x (Finite_Set.fold f z A)\"\n    by simp\n  with \\<open>finite A\\<close> show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nlemma remove:\n  assumes \"A \\<subseteq> S\" and \"finite A\" and \"x \\<in> A\"\n  shows \"F A = f x (F (A - {x}))\"\nproof -\n  from \\<open>x \\<in> A\\<close> obtain B where A: \"A = insert x B\" and \"x \\<notin> B\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from \\<open>finite A\\<close> A have \"finite B\" by simp\n  ultimately show ?thesis\n    using \\<open>A \\<subseteq> S\\<close> by auto\nqed\n\nlemma insert_remove:\n  assumes \"insert x A \\<subseteq> S\" and \"finite A\"\n  shows \"F (insert x A) = f x (F (A - {x}))\"\n  using assms by (cases \"x \\<in> A\") (simp_all add: remove insert_absorb)\n\nend\n\n\nsubsubsection \\<open>With idempotency\\<close>\n\nlocale folding_idem_on = folding_on +\n  assumes comp_fun_idem_on: \"x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> f x \\<circ> f x = f x\"\nbegin\n\ndeclare insert [simp del]\n\ninterpretation fold?: comp_fun_idem_on S f\n  by standard (simp_all add: comp_fun_commute_on comp_fun_idem_on)\n\nlemma insert_idem [simp]:\n  assumes \"insert x A \\<subseteq> S\" and \"finite A\"\n  shows \"F (insert x A) = f x (F A)\"\nproof -\n  from fold_insert_idem assms\n  have \"fold f z (insert x A) = f x (fold f z A)\" by simp\n  with \\<open>finite A\\<close> show ?thesis by (simp add: eq_fold fun_eq_iff)\nqed\n\nend\n\nsubsubsection \\<open>\\<^term>\\<open>UNIV\\<close> as the carrier set\\<close>\n\nlocale folding =\n  fixes f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\" and z :: \"'b\"\n  assumes comp_fun_commute: \"f y \\<circ> f x = f x \\<circ> f y\"\nbegin\n\nlemma (in -) folding_def': \"folding f = folding_on UNIV f\"\n  unfolding folding_def folding_on_def by blast\n\ntext \\<open>\n  Again, we abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale folding_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"folding_on UNIV f\"\n    by standard (simp add: comp_fun_commute)\nqed simp_all\n\nend\n\nlocale folding_idem = folding +\n  assumes comp_fun_idem: \"f x \\<circ> f x = f x\"\nbegin\n\nlemma (in -) folding_idem_def': \"folding_idem f = folding_idem_on UNIV f\"\n  unfolding folding_idem_def folding_def' folding_idem_on_def\n  unfolding folding_idem_axioms_def folding_idem_on_axioms_def\n  by blast\n\ntext \\<open>\n  Again, we abuse the \\<open>rewrites\\<close> functionality of locales to remove trivial assumptions that\n  result from instantiating the carrier set to \\<^term>\\<open>UNIV\\<close>.\n\\<close>\nsublocale folding_idem_on UNIV f\n  rewrites \"\\<And>X. (X \\<subseteq> UNIV) \\<equiv> True\"\n       and \"\\<And>x. x \\<in> UNIV \\<equiv> True\"\n       and \"\\<And>P. (True \\<Longrightarrow> P) \\<equiv> Trueprop P\"\n       and \"\\<And>P Q. (True \\<Longrightarrow> PROP P \\<Longrightarrow> PROP Q) \\<equiv> (PROP P \\<Longrightarrow> True \\<Longrightarrow> PROP Q)\"\nproof -\n  show \"folding_idem_on UNIV f\"\n    by standard (simp add: comp_fun_idem)\nqed simp_all\n\nend\n\n\nsubsection \\<open>Finite cardinality\\<close>\n\ntext \\<open>\n  The traditional definition\n  \\<^prop>\\<open>card A \\<equiv> LEAST n. \\<exists>f. A = {f i |i. i < n}\\<close>\n  is ugly to work with.\n  But now that we have \\<^const>\\<open>fold\\<close> things are easy:\n\\<close>\n\nglobal_interpretation card: folding \"\\<lambda>_. Suc\" 0\n  defines card = \"folding_on.F (\\<lambda>_. Suc) 0\"\n  by standard (rule refl)\n\nlemma card_insert_disjoint: \"finite A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> card (insert x A) = Suc (card A)\"\n  by (fact card.insert)\n\nlemma card_insert_if: \"finite A \\<Longrightarrow> card (insert x A) = (if x \\<in> A then card A else Suc (card A))\"\n  by auto (simp add: card.insert_remove card.remove)\n\nlemma card_ge_0_finite: \"card A > 0 \\<Longrightarrow> finite A\"\n  by (rule ccontr) simp\n\nlemma card_0_eq [simp]: \"finite A \\<Longrightarrow> card A = 0 \\<longleftrightarrow> A = {}\"\n  by (auto dest: mk_disjoint_insert)\n\nlemma finite_UNIV_card_ge_0: \"finite (UNIV :: 'a set) \\<Longrightarrow> card (UNIV :: 'a set) > 0\"\n  by (rule ccontr) simp\n\nlemma card_eq_0_iff: \"card A = 0 \\<longleftrightarrow> A = {} \\<or> \\<not> finite A\"\n  by auto\n\nlemma card_range_greater_zero: \"finite (range f) \\<Longrightarrow> card (range f) > 0\"\n  by (rule ccontr) (simp add: card_eq_0_iff)\n\nlemma card_gt_0_iff: \"0 < card A \\<longleftrightarrow> A \\<noteq> {} \\<and> finite A\"\n  by (simp add: neq0_conv [symmetric] card_eq_0_iff)\n\nlemma card_Suc_Diff1:\n  assumes \"finite A\" \"x \\<in> A\" shows \"Suc (card (A - {x})) = card A\"\nproof -\n  have \"Suc (card (A - {x})) = card (insert x (A - {x}))\"\n    using assms by (simp add: card.insert_remove)\n  also have \"... = card A\"\n    using assms by (simp add: card_insert_if)\n  finally show ?thesis .\nqed\n\nlemma card_insert_le_m1:\n  assumes \"n > 0\" \"card y \\<le> n - 1\" shows  \"card (insert x y) \\<le> n\"\n  using assms\n  by (cases \"finite y\") (auto simp: card_insert_if)\n\nlemma card_Diff_singleton:\n  assumes \"x \\<in> A\" shows \"card (A - {x}) = card A - 1\"\nproof (cases \"finite A\")\n  case True\n  with assms show ?thesis\n    by (simp add: card_Suc_Diff1 [symmetric])\nqed auto\n\nlemma card_Diff_singleton_if:\n  \"card (A - {x}) = (if x \\<in> A then card A - 1 else card A)\"\n  by (simp add: card_Diff_singleton)\n\nlemma card_Diff_insert[simp]:\n  assumes \"a \\<in> A\" and \"a \\<notin> B\"\n  shows \"card (A - insert a B) = card (A - B) - 1\"\nproof -\n  have \"A - insert a B = (A - B) - {a}\"\n    using assms by blast\n  then show ?thesis\n    using assms by (simp add: card_Diff_singleton)\nqed\n\nlemma card_insert_le: \"card A \\<le> card (insert x A)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis   by (simp add: card_insert_if)\nqed auto\n\nlemma card_Collect_less_nat[simp]: \"card {i::nat. i < n} = n\"\n  by (induct n) (simp_all add:less_Suc_eq Collect_disj_eq)\n\nlemma card_Collect_le_nat[simp]: \"card {i::nat. i \\<le> n} = Suc n\"\n  using card_Collect_less_nat[of \"Suc n\"] by (simp add: less_Suc_eq_le)\n\nlemma card_mono:\n  assumes \"finite B\" and \"A \\<subseteq> B\"\n  shows \"card A \\<le> card B\"\nproof -\n  from assms have \"finite A\"\n    by (auto intro: finite_subset)\n  then show ?thesis\n    using assms\n  proof (induct A arbitrary: B)\n    case empty\n    then show ?case by simp\n  next\n    case (insert x A)\n    then have \"x \\<in> B\"\n      by simp\n    from insert have \"A \\<subseteq> B - {x}\" and \"finite (B - {x})\"\n      by auto\n    with insert.hyps have \"card A \\<le> card (B - {x})\"\n      by auto\n    with \\<open>finite A\\<close> \\<open>x \\<notin> A\\<close> \\<open>finite B\\<close> \\<open>x \\<in> B\\<close> show ?case\n      by simp (simp only: card.remove)\n  qed\nqed\n\nlemma card_seteq: \n  assumes \"finite B\" and A: \"A \\<subseteq> B\" \"card B \\<le> card A\"\n  shows \"A = B\"\n  using assms\nproof (induction arbitrary: A rule: finite_induct)\n  case (insert b B)\n  then have A: \"finite A\" \"A - {b} \\<subseteq> B\" \n    by force+\n  then have \"card B \\<le> card (A - {b})\"\n    using insert by (auto simp add: card_Diff_singleton_if)\n  then have \"A - {b} = B\"\n    using A insert.IH by auto\n  then show ?case \n    using insert.hyps insert.prems by auto\nqed auto\n\nlemma psubset_card_mono: \"finite B \\<Longrightarrow> A < B \\<Longrightarrow> card A < card B\"\n  using card_seteq [of B A] by (auto simp add: psubset_eq)\n\nlemma card_Un_Int:\n  assumes \"finite A\" \"finite B\"\n  shows \"card A + card B = card (A \\<union> B) + card (A \\<inter> B)\"\n  using assms\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case insert\n  then show ?case\n    by (auto simp add: insert_absorb Int_insert_left)\nqed\n\nlemma card_Un_disjoint: \"finite A \\<Longrightarrow> finite B \\<Longrightarrow> A \\<inter> B = {} \\<Longrightarrow> card (A \\<union> B) = card A + card B\"\n  using card_Un_Int [of A B] by simp\n\nlemma card_Un_disjnt: \"\\<lbrakk>finite A; finite B; disjnt A B\\<rbrakk> \\<Longrightarrow> card (A \\<union> B) = card A + card B\"\n  by (simp add: card_Un_disjoint disjnt_def)\n\nlemma card_Un_le: \"card (A \\<union> B) \\<le> card A + card B\"\nproof (cases \"finite A \\<and> finite B\")\n  case True\n  then show ?thesis\n    using le_iff_add card_Un_Int [of A B] by auto\nqed auto\n\nlemma card_Diff_subset:\n  assumes \"finite B\"\n    and \"B \\<subseteq> A\"\n  shows \"card (A - B) = card A - card B\"\n  using assms\nproof (cases \"finite A\")\n  case False\n  with assms show ?thesis\n    by simp\nnext\n  case True\n  with assms show ?thesis\n    by (induct B arbitrary: A) simp_all\nqed\n\nlemma card_Diff_subset_Int:\n  assumes \"finite (A \\<inter> B)\"\n  shows \"card (A - B) = card A - card (A \\<inter> B)\"\nproof -\n  have \"A - B = A - A \\<inter> B\" by auto\n  with assms show ?thesis\n    by (simp add: card_Diff_subset)\nqed\n\nlemma diff_card_le_card_Diff:\n  assumes \"finite B\"\n  shows \"card A - card B \\<le> card (A - B)\"\nproof -\n  have \"card A - card B \\<le> card A - card (A \\<inter> B)\"\n    using card_mono[OF assms Int_lower2, of A] by arith\n  also have \"\\<dots> = card (A - B)\"\n    using assms by (simp add: card_Diff_subset_Int)\n  finally show ?thesis .\nqed\n\nlemma card_le_sym_Diff:\n  assumes \"finite A\" \"finite B\" \"card A \\<le> card B\"\n  shows \"card(A - B) \\<le> card(B - A)\"\nproof -\n  have \"card(A - B) = card A - card (A \\<inter> B)\" using assms(1,2) by(simp add: card_Diff_subset_Int)\n  also have \"\\<dots> \\<le> card B - card (A \\<inter> B)\" using assms(3) by linarith\n  also have \"\\<dots> = card(B - A)\" using assms(1,2) by(simp add: card_Diff_subset_Int Int_commute)\n  finally show ?thesis .\nqed\n\nlemma card_less_sym_Diff:\n  assumes \"finite A\" \"finite B\" \"card A < card B\"\n  shows \"card(A - B) < card(B - A)\"\nproof -\n  have \"card(A - B) = card A - card (A \\<inter> B)\" using assms(1,2) by(simp add: card_Diff_subset_Int)\n  also have \"\\<dots> < card B - card (A \\<inter> B)\" using assms(1,3) by (simp add: card_mono diff_less_mono)\n  also have \"\\<dots> = card(B - A)\" using assms(1,2) by(simp add: card_Diff_subset_Int Int_commute)\n  finally show ?thesis .\nqed\n\nlemma card_Diff1_less_iff: \"card (A - {x}) < card A \\<longleftrightarrow> finite A \\<and> x \\<in> A\"\nproof (cases \"finite A \\<and> x \\<in> A\")\n  case True\n  then show ?thesis\n    by (auto simp: card_gt_0_iff intro: diff_less)\nqed auto\n\nlemma card_Diff1_less: \"finite A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> card (A - {x}) < card A\"\n  unfolding card_Diff1_less_iff by auto\n\nlemma card_Diff2_less:\n  assumes \"finite A\" \"x \\<in> A\" \"y \\<in> A\" shows \"card (A - {x} - {y}) < card A\"\nproof (cases \"x = y\")\n  case True\n  with assms show ?thesis\n    by (simp add: card_Diff1_less del: card_Diff_insert)\nnext\n  case False\n  then have \"card (A - {x} - {y}) < card (A - {x})\" \"card (A - {x}) < card A\"\n    using assms by (intro card_Diff1_less; simp)+\n  then show ?thesis\n    by (blast intro: less_trans)\nqed\n\nlemma card_Diff1_le: \"card (A - {x}) \\<le> card A\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis  \n    by (cases \"x \\<in> A\") (simp_all add: card_Diff1_less less_imp_le)\nqed auto\n\nlemma card_psubset: \"finite B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> card A < card B \\<Longrightarrow> A < B\"\n  by (erule psubsetI) blast\n\nlemma card_le_inj:\n  assumes fA: \"finite A\"\n    and fB: \"finite B\"\n    and c: \"card A \\<le> card B\"\n  shows \"\\<exists>f. f ` A \\<subseteq> B \\<and> inj_on f A\"\n  using fA fB c\nproof (induct arbitrary: B rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x s t)\n  then show ?case\n  proof (induct rule: finite_induct [OF insert.prems(1)])\n    case 1\n    then show ?case by simp\n  next\n    case (2 y t)\n    from \"2.prems\"(1,2,5) \"2.hyps\"(1,2) have cst: \"card s \\<le> card t\"\n      by simp\n    from \"2.prems\"(3) [OF \"2.hyps\"(1) cst]\n    obtain f where *: \"f ` s \\<subseteq> t\" \"inj_on f s\"\n      by blast\n    let ?g = \"(\\<lambda>a. if a = x then y else f a)\"\n    have \"?g ` insert x s \\<subseteq> insert y t \\<and> inj_on ?g (insert x s)\"\n      using * \"2.prems\"(2) \"2.hyps\"(2) unfolding inj_on_def by auto\n    then show ?case by (rule exI[where ?x=\"?g\"])\n  qed\nqed\n\nlemma card_subset_eq:\n  assumes fB: \"finite B\"\n    and AB: \"A \\<subseteq> B\"\n    and c: \"card A = card B\"\n  shows \"A = B\"\nproof -\n  from fB AB have fA: \"finite A\"\n    by (auto intro: finite_subset)\n  from fA fB have fBA: \"finite (B - A)\"\n    by auto\n  have e: \"A \\<inter> (B - A) = {}\"\n    by blast\n  have eq: \"A \\<union> (B - A) = B\"\n    using AB by blast\n  from card_Un_disjoint[OF fA fBA e, unfolded eq c] have \"card (B - A) = 0\"\n    by arith\n  then have \"B - A = {}\"\n    unfolding card_eq_0_iff using fA fB by simp\n  with AB show \"A = B\"\n    by blast\nqed\n\nlemma insert_partition:\n  \"x \\<notin> F \\<Longrightarrow> \\<forall>c1 \\<in> insert x F. \\<forall>c2 \\<in> insert x F. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {} \\<Longrightarrow> x \\<inter> \\<Union>F = {}\"\n  by auto\n\nlemma finite_psubset_induct [consumes 1, case_names psubset]:\n  assumes finite: \"finite A\"\n    and major: \"\\<And>A. finite A \\<Longrightarrow> (\\<And>B. B \\<subset> A \\<Longrightarrow> P B) \\<Longrightarrow> P A\"\n  shows \"P A\"\n  using finite\nproof (induct A taking: card rule: measure_induct_rule)\n  case (less A)\n  have fin: \"finite A\" by fact\n  have ih: \"card B < card A \\<Longrightarrow> finite B \\<Longrightarrow> P B\" for B by fact\n  have \"P B\" if \"B \\<subset> A\" for B\n  proof -\n    from that have \"card B < card A\"\n      using psubset_card_mono fin by blast\n    moreover\n    from that have \"B \\<subseteq> A\"\n      by auto\n    then have \"finite B\"\n      using fin finite_subset by blast\n    ultimately show ?thesis using ih by simp\n  qed\n  with fin show \"P A\" using major by blast\nqed\n\nlemma finite_induct_select [consumes 1, case_names empty select]:\n  assumes \"finite S\"\n    and \"P {}\"\n    and select: \"\\<And>T. T \\<subset> S \\<Longrightarrow> P T \\<Longrightarrow> \\<exists>s\\<in>S - T. P (insert s T)\"\n  shows \"P S\"\nproof -\n  have \"0 \\<le> card S\" by simp\n  then have \"\\<exists>T \\<subseteq> S. card T = card S \\<and> P T\"\n  proof (induct rule: dec_induct)\n    case base with \\<open>P {}\\<close>\n    show ?case\n      by (intro exI[of _ \"{}\"]) auto\n  next\n    case (step n)\n    then obtain T where T: \"T \\<subseteq> S\" \"card T = n\" \"P T\"\n      by auto\n    with \\<open>n < card S\\<close> have \"T \\<subset> S\" \"P T\"\n      by auto\n    with select[of T] obtain s where \"s \\<in> S\" \"s \\<notin> T\" \"P (insert s T)\"\n      by auto\n    with step(2) T \\<open>finite S\\<close> show ?case\n      by (intro exI[of _ \"insert s T\"]) (auto dest: finite_subset)\n  qed\n  with \\<open>finite S\\<close> show \"P S\"\n    by (auto dest: card_subset_eq)\nqed\n\nlemma remove_induct [case_names empty infinite remove]:\n  assumes empty: \"P ({} :: 'a set)\"\n    and infinite: \"\\<not> finite B \\<Longrightarrow> P B\"\n    and remove: \"\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A\"\n  shows \"P B\"\nproof (cases \"finite B\")\n  case False\n  then show ?thesis by (rule infinite)\nnext\n  case True\n  define A where \"A = B\"\n  with True have \"finite A\" \"A \\<subseteq> B\"\n    by simp_all\n  then show \"P A\"\n  proof (induct \"card A\" arbitrary: A)\n    case 0\n    then have \"A = {}\" by auto\n    with empty show ?case by simp\n  next\n    case (Suc n A)\n    from \\<open>A \\<subseteq> B\\<close> and \\<open>finite B\\<close> have \"finite A\"\n      by (rule finite_subset)\n    moreover from Suc.hyps have \"A \\<noteq> {}\" by auto\n    moreover note \\<open>A \\<subseteq> B\\<close>\n    moreover have \"P (A - {x})\" if x: \"x \\<in> A\" for x\n      using x Suc.prems \\<open>Suc n = card A\\<close> by (intro Suc) auto\n    ultimately show ?case by (rule remove)\n  qed\nqed\n\nlemma finite_remove_induct [consumes 1, case_names empty remove]:\n  fixes P :: \"'a set \\<Rightarrow> bool\"\n  assumes \"finite B\"\n    and \"P {}\"\n    and \"\\<And>A. finite A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> P (A - {x})) \\<Longrightarrow> P A\"\n  defines \"B' \\<equiv> B\"\n  shows \"P B'\"\n  by (induct B' rule: remove_induct) (simp_all add: assms)\n\n\ntext \\<open>Main cardinality theorem.\\<close>\nlemma card_partition [rule_format]:\n  \"finite C \\<Longrightarrow> finite (\\<Union>C) \\<Longrightarrow> (\\<forall>c\\<in>C. card c = k) \\<Longrightarrow>\n    (\\<forall>c1 \\<in> C. \\<forall>c2 \\<in> C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}) \\<Longrightarrow>\n    k * card C = card (\\<Union>C)\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  then show ?case\n    by (simp add: card_Un_disjoint insert_partition finite_subset [of _ \"\\<Union>(insert _ _)\"])\nqed\n\nlemma card_eq_UNIV_imp_eq_UNIV:\n  assumes fin: \"finite (UNIV :: 'a set)\"\n    and card: \"card A = card (UNIV :: 'a set)\"\n  shows \"A = (UNIV :: 'a set)\"\nproof\n  show \"A \\<subseteq> UNIV\" by simp\n  show \"UNIV \\<subseteq> A\"\n  proof\n    show \"x \\<in> A\" for x\n    proof (rule ccontr)\n      assume \"x \\<notin> A\"\n      then have \"A \\<subset> UNIV\" by auto\n      with fin have \"card A < card (UNIV :: 'a set)\"\n        by (fact psubset_card_mono)\n      with card show False by simp\n    qed\n  qed\nqed\n\ntext \\<open>The form of a finite set of given cardinality\\<close>\n\nlemma card_eq_SucD:\n  assumes \"card A = Suc k\"\n  shows \"\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> (k = 0 \\<longrightarrow> B = {})\"\nproof -\n  have fin: \"finite A\"\n    using assms by (auto intro: ccontr)\n  moreover have \"card A \\<noteq> 0\"\n    using assms by auto\n  ultimately obtain b where b: \"b \\<in> A\"\n    by auto\n  show ?thesis\n  proof (intro exI conjI)\n    show \"A = insert b (A - {b})\"\n      using b by blast\n    show \"b \\<notin> A - {b}\"\n      by blast\n    show \"card (A - {b}) = k\" and \"k = 0 \\<longrightarrow> A - {b} = {}\"\n      using assms b fin by (fastforce dest: mk_disjoint_insert)+\n  qed\nqed\n\nlemma card_Suc_eq:\n  \"card A = Suc k \\<longleftrightarrow>\n    (\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> (k = 0 \\<longrightarrow> B = {}))\"\n  by (auto simp: card_insert_if card_gt_0_iff elim!: card_eq_SucD)\n\nlemma card_Suc_eq_finite:\n  \"card A = Suc k \\<longleftrightarrow> (\\<exists>b B. A = insert b B \\<and> b \\<notin> B \\<and> card B = k \\<and> finite B)\"\n  unfolding card_Suc_eq using card_gt_0_iff by fastforce\n\nlemma card_1_singletonE:\n  assumes \"card A = 1\"\n  obtains x where \"A = {x}\"\n  using assms by (auto simp: card_Suc_eq)\n\nlemma is_singleton_altdef: \"is_singleton A \\<longleftrightarrow> card A = 1\"\n  unfolding is_singleton_def\n  by (auto elim!: card_1_singletonE is_singletonE simp del: One_nat_def)\n\nlemma card_1_singleton_iff: \"card A = Suc 0 \\<longleftrightarrow> (\\<exists>x. A = {x})\"\n  by (simp add: card_Suc_eq)\n\nlemma card_le_Suc0_iff_eq:\n  assumes \"finite A\"\n  shows \"card A \\<le> Suc 0 \\<longleftrightarrow> (\\<forall>a1 \\<in> A. \\<forall>a2 \\<in> A. a1 = a2)\" (is \"?C = ?A\")\nproof\n  assume ?C thus ?A using assms by (auto simp: le_Suc_eq dest: card_eq_SucD)\nnext\n  assume ?A\n  show ?C\n  proof cases\n    assume \"A = {}\" thus ?C using \\<open>?A\\<close> by simp\n  next\n    assume \"A \\<noteq> {}\"\n    then obtain a where \"A = {a}\" using \\<open>?A\\<close> by blast\n    thus ?C by simp\n  qed\nqed\n\nlemma card_le_Suc_iff:\n  \"Suc n \\<le> card A = (\\<exists>a B. A = insert a B \\<and> a \\<notin> B \\<and> n \\<le> card B \\<and> finite B)\"\nproof (cases \"finite A\")\n  case True\n  then show ?thesis\n    by (fastforce simp: card_Suc_eq less_eq_nat.simps split: nat.splits)\nqed auto\n\nlemma finite_fun_UNIVD2:\n  assumes fin: \"finite (UNIV :: ('a \\<Rightarrow> 'b) set)\"\n  shows \"finite (UNIV :: 'b set)\"\nproof -\n  from fin have \"finite (range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary))\" for arbitrary\n    by (rule finite_imageI)\n  moreover have \"UNIV = range (\\<lambda>f :: 'a \\<Rightarrow> 'b. f arbitrary)\" for arbitrary\n    by (rule UNIV_eq_I) auto\n  ultimately show \"finite (UNIV :: 'b set)\"\n    by simp\nqed\n\nlemma card_UNIV_unit [simp]: \"card (UNIV :: unit set) = 1\"\n  unfolding UNIV_unit by simp\n\nlemma infinite_arbitrarily_large:\n  assumes \"\\<not> finite A\"\n  shows \"\\<exists>B. finite B \\<and> card B = n \\<and> B \\<subseteq> A\"\nproof (induction n)\n  case 0\n  show ?case by (intro exI[of _ \"{}\"]) auto\nnext\n  case (Suc n)\n  then obtain B where B: \"finite B \\<and> card B = n \\<and> B \\<subseteq> A\" ..\n  with \\<open>\\<not> finite A\\<close> have \"A \\<noteq> B\" by auto\n  with B have \"B \\<subset> A\" by auto\n  then have \"\\<exists>x. x \\<in> A - B\"\n    by (elim psubset_imp_ex_mem)\n  then obtain x where x: \"x \\<in> A - B\" ..\n  with B have \"finite (insert x B) \\<and> card (insert x B) = Suc n \\<and> insert x B \\<subseteq> A\"\n    by auto\n  then show \"\\<exists>B. finite B \\<and> card B = Suc n \\<and> B \\<subseteq> A\" ..\nqed\n\ntext \\<open>Sometimes, to prove that a set is finite, it is convenient to work with finite subsets\nand to show that their cardinalities are uniformly bounded. This possibility is formalized in\nthe next criterion.\\<close>\n\nlemma finite_if_finite_subsets_card_bdd:\n  assumes \"\\<And>G. G \\<subseteq> F \\<Longrightarrow> finite G \\<Longrightarrow> card G \\<le> C\"\n  shows \"finite F \\<and> card F \\<le> C\"\nproof (cases \"finite F\")\n  case False\n  obtain n::nat where n: \"n > max C 0\" by auto\n  obtain G where G: \"G \\<subseteq> F\" \"card G = n\" using infinite_arbitrarily_large[OF False] by auto\n  hence \"finite G\" using \\<open>n > max C 0\\<close> using card.infinite gr_implies_not0 by blast\n  hence False using assms G n not_less by auto\n  thus ?thesis ..\nnext\n  case True thus ?thesis using assms[of F] by auto\nqed\n\nlemma obtain_subset_with_card_n:\n  assumes \"n \\<le> card S\"\n  obtains T where \"T \\<subseteq> S\" \"card T = n\" \"finite T\"\nproof -\n  obtain n' where \"card S = n + n'\"\n    using le_Suc_ex[OF assms] by blast\n  with that show thesis\n  proof (induct n' arbitrary: S)\n    case 0 \n    thus ?case by (cases \"finite S\") auto\n  next\n    case Suc \n    thus ?case by (auto simp add: card_Suc_eq)\n  qed\nqed\n\nlemma exists_subset_between: \n  assumes \n    \"card A \\<le> n\" \n    \"n \\<le> card C\"\n    \"A \\<subseteq> C\"\n    \"finite C\"\n  shows \"\\<exists>B. A \\<subseteq> B \\<and> B \\<subseteq> C \\<and> card B = n\" \n  using assms \nproof (induct n arbitrary: A C)\n  case 0\n  thus ?case using finite_subset[of A C] by (intro exI[of _ \"{}\"], auto)\nnext\n  case (Suc n A C)\n  show ?case\n  proof (cases \"A = {}\")\n    case True\n    from obtain_subset_with_card_n[OF Suc(3)]\n    obtain B where \"B \\<subseteq> C\" \"card B = Suc n\" by blast\n    thus ?thesis unfolding True by blast\n  next\n    case False\n    then obtain a where a: \"a \\<in> A\" by auto\n    let ?A = \"A - {a}\" \n    let ?C = \"C - {a}\" \n    have 1: \"card ?A \\<le> n\" using Suc(2-) a \n      using finite_subset by fastforce \n    have 2: \"card ?C \\<ge> n\" using Suc(2-) a by auto\n    from Suc(1)[OF 1 2 _ finite_subset[OF _ Suc(5)]] Suc(2-)\n    obtain B where \"?A \\<subseteq> B\" \"B \\<subseteq> ?C\" \"card B = n\" by blast\n    thus ?thesis using a Suc(2-) \n      by (intro exI[of _ \"insert a B\"], auto intro!: card_insert_disjoint finite_subset[of B C])\n  qed\nqed\n\n\nsubsubsection \\<open>Cardinality of image\\<close>\n\nlemma card_image_le: \"finite A \\<Longrightarrow> card (f ` A) \\<le> card A\"\n  by (induct rule: finite_induct) (simp_all add: le_SucI card_insert_if)\n\nlemma card_image: \"inj_on f A \\<Longrightarrow> card (f ` A) = card A\"\nproof (induct A rule: infinite_finite_induct)\n  case (infinite A)\n  then have \"\\<not> finite (f ` A)\" by (auto dest: finite_imageD)\n  with infinite show ?case by simp\nqed simp_all\n\nlemma bij_betw_same_card: \"bij_betw f A B \\<Longrightarrow> card A = card B\"\n  by (auto simp: card_image bij_betw_def)\n\nlemma endo_inj_surj: \"finite A \\<Longrightarrow> f ` A \\<subseteq> A \\<Longrightarrow> inj_on f A \\<Longrightarrow> f ` A = A\"\n  by (simp add: card_seteq card_image)\n\nlemma eq_card_imp_inj_on:\n  assumes \"finite A\" \"card(f ` A) = card A\"\n  shows \"inj_on f A\"\n  using assms\nproof (induct rule:finite_induct)\n  case empty\n  show ?case by simp\nnext\n  case (insert x A)\n  then show ?case\n    using card_image_le [of A f] by (simp add: card_insert_if split: if_splits)\nqed\n\nlemma inj_on_iff_eq_card: \"finite A \\<Longrightarrow> inj_on f A \\<longleftrightarrow> card (f ` A) = card A\"\n  by (blast intro: card_image eq_card_imp_inj_on)\n\nlemma card_inj_on_le:\n  assumes \"inj_on f A\" \"f ` A \\<subseteq> B\" \"finite B\"\n  shows \"card A \\<le> card B\"\nproof -\n  have \"finite A\"\n    using assms by (blast intro: finite_imageD dest: finite_subset)\n  then show ?thesis\n    using assms by (force intro: card_mono simp: card_image [symmetric])\nqed\n\nlemma inj_on_iff_card_le:\n  \"\\<lbrakk> finite A; finite B \\<rbrakk> \\<Longrightarrow> (\\<exists>f. inj_on f A \\<and> f ` A \\<le> B) = (card A \\<le> card B)\"\nusing card_inj_on_le[of _ A B] card_le_inj[of A B] by blast\n\nlemma surj_card_le: \"finite A \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> card B \\<le> card A\"\n  by (blast intro: card_image_le card_mono le_trans)\n\nlemma card_bij_eq:\n  \"inj_on f A \\<Longrightarrow> f ` A \\<subseteq> B \\<Longrightarrow> inj_on g B \\<Longrightarrow> g ` B \\<subseteq> A \\<Longrightarrow> finite A \\<Longrightarrow> finite B\n    \\<Longrightarrow> card A = card B\"\n  by (auto intro: le_antisym card_inj_on_le)\n\nlemma bij_betw_finite: \"bij_betw f A B \\<Longrightarrow> finite A \\<longleftrightarrow> finite B\"\n  unfolding bij_betw_def using finite_imageD [of f A] by auto\n\nlemma inj_on_finite: \"inj_on f A \\<Longrightarrow> f ` A \\<le> B \\<Longrightarrow> finite B \\<Longrightarrow> finite A\"\n  using finite_imageD finite_subset by blast\n\nlemma card_vimage_inj_on_le:\n  assumes \"inj_on f D\" \"finite A\"\n  shows \"card (f-`A \\<inter> D) \\<le> card A\"\nproof (rule card_inj_on_le)\n  show \"inj_on f (f -` A \\<inter> D)\"\n    by (blast intro: assms inj_on_subset)\nqed (use assms in auto)\n\nlemma card_vimage_inj: \"inj f \\<Longrightarrow> A \\<subseteq> range f \\<Longrightarrow> card (f -` A) = card A\"\n  by (auto 4 3 simp: subset_image_iff inj_vimage_image_eq\n      intro: card_image[symmetric, OF subset_inj_on])\n\nsubsubsection \\<open>Pigeonhole Principles\\<close>\n\nlemma pigeonhole: \"card A > card (f ` A) \\<Longrightarrow> \\<not> inj_on f A \"\n  by (auto dest: card_image less_irrefl_nat)\n\nlemma pigeonhole_infinite:\n  assumes \"\\<not> finite A\" and \"finite (f`A)\"\n  shows \"\\<exists>a0\\<in>A. \\<not> finite {a\\<in>A. f a = f a0}\"\n  using assms(2,1)\nproof (induct \"f`A\" arbitrary: A rule: finite_induct)\n  case empty\n  then show ?case by simp\nnext\n  case (insert b F)\n  show ?case\n  proof (cases \"finite {a\\<in>A. f a = b}\")\n    case True\n    with \\<open>\\<not> finite A\\<close> have \"\\<not> finite (A - {a\\<in>A. f a = b})\"\n      by simp\n    also have \"A - {a\\<in>A. f a = b} = {a\\<in>A. f a \\<noteq> b}\"\n      by blast\n    finally have \"\\<not> finite {a\\<in>A. f a \\<noteq> b}\" .\n    from insert(3)[OF _ this] insert(2,4) show ?thesis\n      by simp (blast intro: rev_finite_subset)\n  next\n    case False\n    then have \"{a \\<in> A. f a = b} \\<noteq> {}\" by force\n    with False show ?thesis by blast\n  qed\nqed\n\nlemma pigeonhole_infinite_rel:\n  assumes \"\\<not> finite A\"\n    and \"finite B\"\n    and \"\\<forall>a\\<in>A. \\<exists>b\\<in>B. R a b\"\n  shows \"\\<exists>b\\<in>B. \\<not> finite {a:A. R a b}\"\nproof -\n  let ?F = \"\\<lambda>a. {b\\<in>B. R a b}\"\n  from finite_Pow_iff[THEN iffD2, OF \\<open>finite B\\<close>] have \"finite (?F ` A)\"\n    by (blast intro: rev_finite_subset)\n  from pigeonhole_infinite [where f = ?F, OF assms(1) this]\n  obtain a0 where \"a0 \\<in> A\" and infinite: \"\\<not> finite {a\\<in>A. ?F a = ?F a0}\" ..\n  obtain b0 where \"b0 \\<in> B\" and \"R a0 b0\"\n    using \\<open>a0 \\<in> A\\<close> assms(3) by blast\n  have \"finite {a\\<in>A. ?F a = ?F a0}\" if \"finite {a\\<in>A. R a b0}\"\n    using \\<open>b0 \\<in> B\\<close> \\<open>R a0 b0\\<close> that by (blast intro: rev_finite_subset)\n  with infinite \\<open>b0 \\<in> B\\<close> show ?thesis\n    by blast\nqed\n\n\nsubsubsection \\<open>Cardinality of sums\\<close>\n\nlemma card_Plus:\n  assumes \"finite A\" \"finite B\"\n  shows \"card (A <+> B) = card A + card B\"\nproof -\n  have \"Inl`A \\<inter> Inr`B = {}\" by fast\n  with assms show ?thesis\n    by (simp add: Plus_def card_Un_disjoint card_image)\nqed\n\nlemma card_Plus_conv_if:\n  \"card (A <+> B) = (if finite A \\<and> finite B then card A + card B else 0)\"\n  by (auto simp add: card_Plus)\n\ntext \\<open>Relates to equivalence classes.  Based on a theorem of F. Kammüller.\\<close>\n\nlemma dvd_partition:\n  assumes f: \"finite (\\<Union>C)\"\n    and \"\\<forall>c\\<in>C. k dvd card c\" \"\\<forall>c1\\<in>C. \\<forall>c2\\<in>C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}\"\n  shows \"k dvd card (\\<Union>C)\"\nproof -\n  have \"finite C\"\n    by (rule finite_UnionD [OF f])\n  then show ?thesis\n    using assms\n  proof (induct rule: finite_induct)\n    case empty\n    show ?case by simp\n  next\n    case (insert c C)\n    then have \"c \\<inter> \\<Union>C = {}\"\n      by auto\n    with insert show ?case\n      by (simp add: card_Un_disjoint)\n  qed\nqed\n\nsubsubsection \\<open>Finite orders\\<close>\n\ncontext order\nbegin\n\nlemma finite_has_maximal:\n  \"\\<lbrakk> finite A; A \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \\<exists> m \\<in> A. \\<forall> b \\<in> A. m \\<le> b \\<longrightarrow> m = b\"\nproof (induction rule: finite_psubset_induct)\n  case (psubset A)\n  from \\<open>A \\<noteq> {}\\<close> obtain a where \"a \\<in> A\" by auto\n  let ?B = \"{b \\<in> A. a < b}\"\n  show ?case\n  proof cases\n    assume \"?B = {}\"\n    hence \"\\<forall> b \\<in> A. a \\<le> b \\<longrightarrow> a = b\" using le_neq_trans by blast\n    thus ?thesis using \\<open>a \\<in> A\\<close> by blast\n  next\n    assume \"?B \\<noteq> {}\"\n    have \"a \\<notin> ?B\" by auto\n    hence \"?B \\<subset> A\" using \\<open>a \\<in> A\\<close> by blast\n    from psubset.IH[OF this \\<open>?B \\<noteq> {}\\<close>] show ?thesis using order.strict_trans2 by blast\n  qed\nqed\n\nlemma finite_has_maximal2:\n  \"\\<lbrakk> finite A; a \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists> m \\<in> A. a \\<le> m \\<and> (\\<forall> b \\<in> A. m \\<le> b \\<longrightarrow> m = b)\"\nusing finite_has_maximal[of \"{b \\<in> A. a \\<le> b}\"] by fastforce\n\nlemma finite_has_minimal:\n  \"\\<lbrakk> finite A; A \\<noteq> {} \\<rbrakk> \\<Longrightarrow> \\<exists> m \\<in> A. \\<forall> b \\<in> A. b \\<le> m \\<longrightarrow> m = b\"\nproof (induction rule: finite_psubset_induct)\n  case (psubset A)\n  from \\<open>A \\<noteq> {}\\<close> obtain a where \"a \\<in> A\" by auto\n  let ?B = \"{b \\<in> A. b < a}\"\n  show ?case\n  proof cases\n    assume \"?B = {}\"\n    hence \"\\<forall> b \\<in> A. b \\<le> a \\<longrightarrow> a = b\" using le_neq_trans by blast\n    thus ?thesis using \\<open>a \\<in> A\\<close> by blast\n  next\n    assume \"?B \\<noteq> {}\"\n    have \"a \\<notin> ?B\" by auto\n    hence \"?B \\<subset> A\" using \\<open>a \\<in> A\\<close> by blast\n    from psubset.IH[OF this \\<open>?B \\<noteq> {}\\<close>] show ?thesis using order.strict_trans1 by blast\n  qed\nqed\n\nlemma finite_has_minimal2:\n  \"\\<lbrakk> finite A; a \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists> m \\<in> A. m \\<le> a \\<and> (\\<forall> b \\<in> A. b \\<le> m \\<longrightarrow> m = b)\"\nusing finite_has_minimal[of \"{b \\<in> A. b \\<le> a}\"] by fastforce\n\nend\n\nsubsubsection \\<open>Relating injectivity and surjectivity\\<close>\n\nlemma finite_surj_inj:\n  assumes \"finite A\" \"A \\<subseteq> f ` A\"\n  shows \"inj_on f A\"\nproof -\n  have \"f ` A = A\"\n    by (rule card_seteq [THEN sym]) (auto simp add: assms card_image_le)\n  then show ?thesis using assms\n    by (simp add: eq_card_imp_inj_on)\nqed\n\nlemma finite_UNIV_surj_inj: \"finite(UNIV:: 'a set) \\<Longrightarrow> surj f \\<Longrightarrow> inj f\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  by (blast intro: finite_surj_inj subset_UNIV)\n\nlemma finite_UNIV_inj_surj: \"finite(UNIV:: 'a set) \\<Longrightarrow> inj f \\<Longrightarrow> surj f\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  by (fastforce simp:surj_def dest!: endo_inj_surj)\n\nlemma surjective_iff_injective_gen:\n  assumes fS: \"finite S\"\n    and fT: \"finite T\"\n    and c: \"card S = card T\"\n    and ST: \"f ` S \\<subseteq> T\"\n  shows \"(\\<forall>y \\<in> T. \\<exists>x \\<in> S. f x = y) \\<longleftrightarrow> inj_on f S\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume h: \"?lhs\"\n  {\n    fix x y\n    assume x: \"x \\<in> S\"\n    assume y: \"y \\<in> S\"\n    assume f: \"f x = f y\"\n    from x fS have S0: \"card S \\<noteq> 0\"\n      by auto\n    have \"x = y\"\n    proof (rule ccontr)\n      assume xy: \"\\<not> ?thesis\"\n      have th: \"card S \\<le> card (f ` (S - {y}))\"\n        unfolding c\n      proof (rule card_mono)\n        show \"finite (f ` (S - {y}))\"\n          by (simp add: fS)\n        have \"\\<lbrakk>x \\<noteq> y; x \\<in> S; z \\<in> S; f x = f y\\<rbrakk>\n         \\<Longrightarrow> \\<exists>x \\<in> S. x \\<noteq> y \\<and> f z = f x\" for z\n          by (cases \"z = y \\<longrightarrow> z = x\") auto\n        then show \"T \\<subseteq> f ` (S - {y})\"\n          using h xy x y f by fastforce\n      qed\n      also have \" \\<dots> \\<le> card (S - {y})\"\n        by (simp add: card_image_le fS)\n      also have \"\\<dots> \\<le> card S - 1\" using y fS by simp\n      finally show False using S0 by arith\n    qed\n  }\n  then show ?rhs\n    unfolding inj_on_def by blast\nnext\n  assume h: ?rhs\n  have \"f ` S = T\"\n    by (simp add: ST c card_image card_subset_eq fT h)\n  then show ?lhs by blast\nqed\n\nhide_const (open) Finite_Set.fold\n\n\nsubsection \\<open>Infinite Sets\\<close>\n\ntext \\<open>\n  Some elementary facts about infinite sets, mostly by Stephan Merz.\n  Beware! Because \"infinite\" merely abbreviates a negation, these\n  lemmas may not work well with \\<open>blast\\<close>.\n\\<close>\n\nabbreviation infinite :: \"'a set \\<Rightarrow> bool\"\n  where \"infinite S \\<equiv> \\<not> finite S\"\n\ntext \\<open>\n  Infinite sets are non-empty, and if we remove some elements from an\n  infinite set, the result is still infinite.\n\\<close>\n\nlemma infinite_UNIV_nat [iff]: \"infinite (UNIV :: nat set)\"\nproof\n  assume \"finite (UNIV :: nat set)\"\n  with finite_UNIV_inj_surj [of Suc] show False\n    by simp (blast dest: Suc_neq_Zero surjD)\nqed\n\nlemma infinite_UNIV_char_0: \"infinite (UNIV :: 'a::semiring_char_0 set)\"\nproof\n  assume \"finite (UNIV :: 'a set)\"\n  with subset_UNIV have \"finite (range of_nat :: 'a set)\"\n    by (rule finite_subset)\n  moreover have \"inj (of_nat :: nat \\<Rightarrow> 'a)\"\n    by (simp add: inj_on_def)\n  ultimately have \"finite (UNIV :: nat set)\"\n    by (rule finite_imageD)\n  then show False\n    by simp\nqed\n\nlemma infinite_imp_nonempty: \"infinite S \\<Longrightarrow> S \\<noteq> {}\"\n  by auto\n\nlemma infinite_remove: \"infinite S \\<Longrightarrow> infinite (S - {a})\"\n  by simp\n\nlemma Diff_infinite_finite:\n  assumes \"finite T\" \"infinite S\"\n  shows \"infinite (S - T)\"\n  using \\<open>finite T\\<close>\nproof induct\n  from \\<open>infinite S\\<close> show \"infinite (S - {})\"\n    by auto\nnext\n  fix T x\n  assume ih: \"infinite (S - T)\"\n  have \"S - (insert x T) = (S - T) - {x}\"\n    by (rule Diff_insert)\n  with ih show \"infinite (S - (insert x T))\"\n    by (simp add: infinite_remove)\nqed\n\nlemma Un_infinite: \"infinite S \\<Longrightarrow> infinite (S \\<union> T)\"\n  by simp\n\nlemma infinite_Un: \"infinite (S \\<union> T) \\<longleftrightarrow> infinite S \\<or> infinite T\"\n  by simp\n\nlemma infinite_super:\n  assumes \"S \\<subseteq> T\"\n    and \"infinite S\"\n  shows \"infinite T\"\nproof\n  assume \"finite T\"\n  with \\<open>S \\<subseteq> T\\<close> have \"finite S\" by (simp add: finite_subset)\n  with \\<open>infinite S\\<close> show False by simp\nqed\n\nproposition infinite_coinduct [consumes 1, case_names infinite]:\n  assumes \"X A\"\n    and step: \"\\<And>A. X A \\<Longrightarrow> \\<exists>x\\<in>A. X (A - {x}) \\<or> infinite (A - {x})\"\n  shows \"infinite A\"\nproof\n  assume \"finite A\"\n  then show False\n    using \\<open>X A\\<close>\n  proof (induction rule: finite_psubset_induct)\n    case (psubset A)\n    then obtain x where \"x \\<in> A\" \"X (A - {x}) \\<or> infinite (A - {x})\"\n      using local.step psubset.prems by blast\n    then have \"X (A - {x})\"\n      using psubset.hyps by blast\n    show False\n    proof (rule psubset.IH [where B = \"A - {x}\"])\n      show \"A - {x} \\<subset> A\"\n        using \\<open>x \\<in> A\\<close> by blast\n    qed fact\n  qed\nqed\n\ntext \\<open>\n  For any function with infinite domain and finite range there is some\n  element that is the image of infinitely many domain elements.  In\n  particular, any infinite sequence of elements from a finite set\n  contains some element that occurs infinitely often.\n\\<close>\n\nlemma inf_img_fin_dom':\n  assumes img: \"finite (f ` A)\"\n    and dom: \"infinite A\"\n  shows \"\\<exists>y \\<in> f ` A. infinite (f -` {y} \\<inter> A)\"\nproof (rule ccontr)\n  have \"A \\<subseteq> (\\<Union>y\\<in>f ` A. f -` {y} \\<inter> A)\" by auto\n  moreover assume \"\\<not> ?thesis\"\n  with img have \"finite (\\<Union>y\\<in>f ` A. f -` {y} \\<inter> A)\" by blast\n  ultimately have \"finite A\" by (rule finite_subset)\n  with dom show False by contradiction\nqed\n\nlemma inf_img_fin_domE':\n  assumes \"finite (f ` A)\" and \"infinite A\"\n  obtains y where \"y \\<in> f`A\" and \"infinite (f -` {y} \\<inter> A)\"\n  using assms by (blast dest: inf_img_fin_dom')\n\nlemma inf_img_fin_dom:\n  assumes img: \"finite (f`A)\" and dom: \"infinite A\"\n  shows \"\\<exists>y \\<in> f`A. infinite (f -` {y})\"\n  using inf_img_fin_dom'[OF assms] by auto\n\nlemma inf_img_fin_domE:\n  assumes \"finite (f`A)\" and \"infinite A\"\n  obtains y where \"y \\<in> f`A\" and \"infinite (f -` {y})\"\n  using assms by (blast dest: inf_img_fin_dom)\n\nproposition finite_image_absD: \"finite (abs ` S) \\<Longrightarrow> finite S\"\n  for S :: \"'a::linordered_ring set\"\n  by (rule ccontr) (auto simp: abs_eq_iff vimage_def dest: inf_img_fin_dom)\n\n\nsubsection \\<open>The finite powerset operator\\<close>\n\ndefinition Fpow :: \"'a set \\<Rightarrow> 'a set set\"\nwhere \"Fpow A \\<equiv> {X. X \\<subseteq> A \\<and> finite X}\"\n\nlemma Fpow_mono: \"A \\<subseteq> B \\<Longrightarrow> Fpow A \\<subseteq> Fpow B\"\nunfolding Fpow_def by auto\n\nlemma empty_in_Fpow: \"{} \\<in> Fpow A\"\nunfolding Fpow_def by auto\n\nlemma Fpow_not_empty: \"Fpow A \\<noteq> {}\"\nusing empty_in_Fpow by blast\n\nlemma Fpow_subset_Pow: \"Fpow A \\<subseteq> Pow A\"\nunfolding Fpow_def by auto\n\nlemma Fpow_Pow_finite: \"Fpow A = Pow A Int {A. finite A}\"\nunfolding Fpow_def Pow_def by blast\n\nlemma inj_on_image_Fpow:\n  assumes \"inj_on f A\"\n  shows \"inj_on (image f) (Fpow A)\"\n  using assms Fpow_subset_Pow[of A] subset_inj_on[of \"image f\" \"Pow A\"]\n    inj_on_image_Pow by blast\n\nlemma image_Fpow_mono:\n  assumes \"f ` A \\<subseteq> B\"\n  shows \"(image f) ` (Fpow A) \\<subseteq> Fpow B\"\n  using assms by(unfold Fpow_def, auto)\n\nend\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Finite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.9111797118207756, "lm_q1q2_score": 0.7762821017322407}}
{"text": "(* Martin Kleppmann, University of Cambridge\n   Victor B. F. Gomes, University of Cambridge\n   Dominic P. Mulligan, Arm Research, Cambridge\n   Alastair Beresford, University of Cambridge\n*)\n\nsection\\<open>Abstract OpSet\\<close>\n\ntext\\<open>In this section, we define a general-purpose OpSet abstraction that is not\nspecific to any one particular datatype. We develop a library of useful lemmas\nthat we can build upon later when reasoning about a specific datatype.\\<close>\n\ntheory OpSet\n  imports Main\nbegin\n\nsubsection\\<open>OpSet definition\\<close>\n\ntext\\<open>An OpSet is a set of (ID, operation) pairs with an associated total order\non IDs (represented here with the \\isa{linorder} typeclass), and satisfying the\nfollowing properties:\n\\begin{enumerate}\n\\item The ID is unique (that is, if any two pairs in the set have the same ID,\nthen their operation is also the same).\n\\item If the operation references the IDs of any other operations, those\nreferenced IDs are less than that of the operation itself, according to the\ntotal order on IDs. To avoid assuming anything about the structure of operations\nhere, we use a function \\isa{deps} that returns the set of dependent IDs for a\ngiven operation. This requirement is a weak expression of causality: an operation\ncan only depend on causally prior operations, and by making the total order on\nIDs a linear extension of the causal order, we can easily ensure that any\nreferenced IDs are less than that of the operation itself.\n\\item The OpSet is finite (but we do not assume any particular maximum size).\n\\end{enumerate}\\<close>\n\nlocale opset =\n  fixes opset :: \"('oid::{linorder} \\<times> 'oper) set\"\n    and deps  :: \"'oper \\<Rightarrow> 'oid set\"\n  assumes unique_oid: \"(oid, op1) \\<in> opset \\<Longrightarrow> (oid, op2) \\<in> opset \\<Longrightarrow> op1 = op2\"\n    and ref_older: \"(oid, oper) \\<in> opset \\<Longrightarrow> ref \\<in> deps oper \\<Longrightarrow> ref < oid\"\n    and finite_opset: \"finite opset\"\n\ntext\\<open>We prove that any subset of an OpSet is also a valid OpSet. This is the\ncase because, although an operation can depend on causally prior operations,\nthe OpSet does not require those prior operations to actually exist. This weak\nassumption makes the OpSet model more general and simplifies reasoning about\nOpSets.\\<close>\n\nlemma opset_subset:\n  assumes \"opset Y deps\"\n    and \"X \\<subseteq> Y\"\n  shows \"opset X deps\"\nproof\n  fix oid op1 op2\n  assume \"(oid, op1) \\<in> X\" and \"(oid, op2) \\<in> X\"\n  thus \"op1 = op2\"\n    using assms by (meson opset.unique_oid subsetD)\nnext\n  fix oid oper ref\n  assume \"(oid, oper) \\<in> X\" and \"ref \\<in> deps oper\"\n  thus \"ref < oid\"\n    using assms by (meson opset.ref_older rev_subsetD)\nnext\n  show \"finite X\"\n    using assms opset.finite_opset finite_subset by blast\nqed\n\nlemma opset_insert:\n  assumes \"opset (insert x ops) deps\"\n  shows \"opset ops deps\"\n  using assms opset_subset by blast\n\nlemma opset_sublist:\n  assumes \"opset (set (xs @ ys @ zs)) deps\"\n  shows \"opset (set (xs @ zs)) deps\"\nproof -\n  have \"set (xs @ zs) \\<subseteq> set (xs @ ys @ zs)\"\n    by auto\n  thus \"opset (set (xs @ zs)) deps\"\n    using assms opset_subset by blast\nqed\n\n\nsubsection\\<open>Helper lemmas about lists\\<close>\n\ntext\\<open>Some general-purpose lemas about lists and sets that are helpful for\nsubsequent proofs.\\<close>\n\nlemma distinct_rem_mid:\n  assumes \"distinct (xs @ [x] @ ys)\"\n  shows \"distinct (xs @ ys)\"\n  using assms by (induction ys rule: rev_induct, simp_all)\n\nlemma distinct_fst_append:\n  assumes \"x \\<in> set (map fst xs)\"\n    and \"distinct (map fst (xs @ ys))\"\n  shows \"x \\<notin> set (map fst ys)\"\n  using assms by (induction ys, force+)\n\nlemma distinct_set_remove_last:\n  assumes \"distinct (xs @ [x])\"\n  shows \"set xs = set (xs @ [x]) - {x}\"\n  using assms by force\n\nlemma distinct_set_remove_mid:\n  assumes \"distinct (xs @ [x] @ ys)\"\n  shows \"set (xs @ ys) = set (xs @ [x] @ ys) - {x}\"\n  using assms by force\n\nlemma distinct_list_split:\n  assumes \"distinct xs\"\n    and \"xs = xa @ x # ya\"\n    and \"xs = xb @ x # yb\"\n  shows \"xa = xb \\<and> ya = yb\"\n  using assms proof(induction xs arbitrary: xa xb x)\n  fix xa xb x\n  assume \"[] = xa @ x # ya\"\n  thus \"xa = xb \\<and> ya = yb\"\n    by auto\nnext\n  fix a xs xa xb x\n  assume IH: \"\\<And>xa xb x. distinct xs \\<Longrightarrow> xs = xa @ x # ya \\<Longrightarrow> xs = xb @ x # yb \\<Longrightarrow> xa = xb \\<and> ya = yb\"\n    and \"distinct (a # xs)\" and \"a # xs = xa @ x # ya\" and \"a # xs = xb @ x # yb\"\n  thus \"xa = xb \\<and> ya = yb\"\n    by(case_tac xa; case_tac xb) auto\nqed\n\nlemma distinct_append_swap:\n  assumes \"distinct (xs @ ys)\"\n  shows \"distinct (ys @ xs)\"\n  using assms by (induction ys, auto)\n\nlemma append_subset:\n  assumes \"set xs = set (ys @ zs)\"\n  shows \"set ys \\<subseteq> set xs\" and \"set zs \\<subseteq> set xs\"\n  by (metis Un_iff assms set_append subsetI)+\n\nlemma append_set_rem_last:\n  assumes \"set (xs @ [x]) = set (ys @ [x] @ zs)\"\n    and \"distinct (xs @ [x])\" and \"distinct (ys @ [x] @ zs)\"\n  shows \"set xs = set (ys @ zs)\"\nproof -\n  have \"distinct xs\"\n    using assms distinct_append by blast\n  moreover from this have \"set xs = set (xs @ [x]) - {x}\"\n    by (meson assms distinct_set_remove_last)\n  moreover have \"distinct (ys @ zs)\"\n    using assms distinct_rem_mid by simp\n  ultimately show \"set xs = set (ys @ zs)\"\n    using assms distinct_set_remove_mid by metis\nqed\n\nlemma distinct_map_fst_remove1:\n  assumes \"distinct (map fst xs)\"\n  shows \"distinct (map fst (remove1 x xs))\"\n  using assms proof(induction xs)\n  case Nil\n  then show \"distinct (map fst (remove1 x []))\"\n    by simp\nnext\n  case (Cons a xs)\n  hence IH: \"distinct (map fst (remove1 x xs))\"\n    by simp\n  then show \"distinct (map fst (remove1 x (a # xs)))\"\n  proof(cases \"a = x\")\n    case True\n    then show ?thesis\n      using Cons.prems by auto\n  next\n    case False\n    moreover have \"fst a \\<notin> fst ` set (remove1 x xs)\"\n      by (metis (no_types, lifting) Cons.prems distinct.simps(2) image_iff\n          list.simps(9) notin_set_remove1 set_map)\n    ultimately show ?thesis\n      using IH by auto\n  qed\nqed\n\n\nsubsection\\<open>The \\isa{spec-ops} predicate\\<close>\n\ntext\\<open>The \\isa{spec-ops} predicate describes a list of (ID, operation) pairs that\ncorresponds to the linearisation of an OpSet, and which we use for sequentially\ninterpreting the OpSet. A list satisfies \\isa{spec-ops} iff it is sorted in ascending\norder of IDs, if the IDs are unique, and if every operation's dependencies have\nlower IDs than the operation itself. A list is implicitly finite in Isabelle/HOL.\nThese requirements correspond to the OpSet definition above, and indeed we prove\nlater that every OpSet has a linearisation that satisfies \\isa{spec-ops}.\\<close>\n\ndefinition spec_ops :: \"('oid::{linorder} \\<times> 'oper) list \\<Rightarrow> ('oper \\<Rightarrow> 'oid set) \\<Rightarrow> bool\" where\n  \"spec_ops ops deps \\<equiv> (sorted (map fst ops) \\<and> distinct (map fst ops) \\<and>\n           (\\<forall>oid oper ref. (oid, oper) \\<in> set ops \\<and> ref \\<in> deps oper \\<longrightarrow> ref < oid))\"\n\nlemma spec_ops_empty:\n  shows \"spec_ops [] deps\"\n  by (simp add: spec_ops_def)\n\nlemma spec_ops_distinct:\n  assumes \"spec_ops ops deps\"\n  shows \"distinct ops\"\n  using assms distinct_map spec_ops_def by blast\n\nlemma spec_ops_distinct_fst:\n  assumes \"spec_ops ops deps\"\n  shows \"distinct (map fst ops)\"\n  using assms by (simp add: spec_ops_def)\n\nlemma spec_ops_sorted:\n  assumes \"spec_ops ops deps\"\n  shows \"sorted (map fst ops)\"\n  using assms by (simp add: spec_ops_def)\n\nlemma spec_ops_rem_cons:\n  assumes \"spec_ops (x # xs) deps\"\n  shows \"spec_ops xs deps\"\nproof -\n  have \"sorted (map fst (x # xs))\" and \"distinct (map fst (x # xs))\"\n    using assms spec_ops_def by blast+\n  moreover from this have \"sorted (map fst xs)\"\n    by simp\n  moreover have \"\\<forall>oid oper ref. (oid, oper) \\<in> set xs \\<and> ref \\<in> deps oper \\<longrightarrow> ref < oid\"\n    by (meson assms set_subset_Cons spec_ops_def subsetCE)\n  ultimately show \"spec_ops xs deps\"\n    by (simp add: spec_ops_def)\nqed\n\nlemma spec_ops_rem_last:\n  assumes \"spec_ops (xs @ [x]) deps\"\n  shows \"spec_ops xs deps\"\nproof -\n  have \"sorted (map fst (xs @ [x]))\" and \"distinct (map fst (xs @ [x]))\"\n    using assms spec_ops_def by blast+\n  moreover from this have \"sorted (map fst xs)\" and \"distinct xs\"\n    by (auto simp add: sorted_append distinct_butlast distinct_map)\n  moreover have \"\\<forall>oid oper ref. (oid, oper) \\<in> set xs \\<and> ref \\<in> deps oper \\<longrightarrow> ref < oid\"\n    by (metis assms butlast_snoc in_set_butlastD spec_ops_def)\n  ultimately show \"spec_ops xs deps\"\n    by (simp add: spec_ops_def)\nqed\n\nlemma spec_ops_remove1:\n  assumes \"spec_ops xs deps\"\n  shows \"spec_ops (remove1 x xs) deps\"\n  using assms distinct_map_fst_remove1 spec_ops_def\n  by (metis notin_set_remove1 sorted_map_remove1 spec_ops_def)\n\nlemma spec_ops_ref_less:\n  assumes \"spec_ops xs deps\"\n    and \"(oid, oper) \\<in> set xs\"\n    and \"r \\<in> deps oper\"\n  shows \"r < oid\"\n  using assms spec_ops_def by force\n\nlemma spec_ops_ref_less_last:\n  assumes \"spec_ops (xs @ [(oid, oper)]) deps\"\n    and \"r \\<in> deps oper\"\n  shows \"r < oid\"\n  using assms spec_ops_ref_less by fastforce\n\nlemma spec_ops_id_inc:\n  assumes \"spec_ops (xs @ [(oid, oper)]) deps\"\n    and \"x \\<in> set (map fst xs)\"\n  shows \"x < oid\"\nproof -\n  have \"sorted ((map fst xs) @ (map fst [(oid, oper)]))\"\n    using assms(1) by (simp add: spec_ops_def)\n  hence \"\\<forall>i \\<in> set (map fst xs). i \\<le> oid\"\n    by (simp add: sorted_append)\n  moreover have \"distinct ((map fst xs) @ (map fst [(oid, oper)]))\"\n    using assms(1) by (simp add: spec_ops_def)\n  hence \"\\<forall>i \\<in> set (map fst xs). i \\<noteq> oid\"\n    by auto\n  ultimately show \"x < oid\"\n    using assms(2) le_neq_trans by auto\nqed\n\nlemma spec_ops_add_last:\n  assumes \"spec_ops xs deps\"\n    and \"\\<forall>i \\<in> set (map fst xs). i < oid\"\n    and \"\\<forall>ref \\<in> deps oper. ref < oid\"\n  shows \"spec_ops (xs @ [(oid, oper)]) deps\"\nproof -\n  have \"sorted ((map fst xs) @ [oid])\"\n    using assms sorted_append spec_ops_sorted by fastforce\n  moreover have \"distinct ((map fst xs) @ [oid])\"\n    using assms spec_ops_distinct_fst by fastforce\n  moreover have \"\\<forall>oid oper ref. (oid, oper) \\<in> set xs \\<and> ref \\<in> deps oper \\<longrightarrow> ref < oid\"\n    using assms(1) spec_ops_def by fastforce\n  hence \"\\<forall>i opr r. (i, opr) \\<in> set (xs @ [(oid, oper)]) \\<and> r \\<in> deps opr \\<longrightarrow> r < i\"\n    using assms(3) by auto\n  ultimately show \"spec_ops (xs @ [(oid, oper)]) deps\"\n    by (simp add: spec_ops_def)\nqed\n\nlemma spec_ops_add_any:\n  assumes \"spec_ops (xs @ ys) deps\"\n    and \"\\<forall>i \\<in> set (map fst xs). i < oid\"\n    and \"\\<forall>i \\<in> set (map fst ys). oid < i\"\n    and \"\\<forall>ref \\<in> deps oper. ref < oid\"\n  shows \"spec_ops (xs @ [(oid, oper)] @ ys) deps\"\n  using assms proof(induction ys rule: rev_induct)\n  case Nil\n  then show \"spec_ops (xs @ [(oid, oper)] @ []) deps\"\n    by (simp add: spec_ops_add_last)\nnext\n  case (snoc y ys)\n  have IH: \"spec_ops (xs @ [(oid, oper)] @ ys) deps\"\n  proof -\n    from snoc have \"spec_ops (xs @ ys) deps\"\n      by (metis append_assoc spec_ops_rem_last)\n    thus \"spec_ops (xs @ [(oid, oper)] @ ys) deps\"\n      using assms(2) snoc by auto\n  qed\n  obtain yi yo where y_pair: \"y = (yi, yo)\"\n    by force\n  have oid_yi: \"oid < yi\"\n    by (simp add: snoc.prems(3) y_pair)\n  have yi_biggest: \"\\<forall>i \\<in> set (map fst (xs @ [(oid, oper)] @ ys)). i < yi\"\n  proof -\n    have \"\\<forall>i \\<in> set (map fst xs). i < yi\"\n      using oid_yi assms(2) less_trans by blast\n    moreover have \"\\<forall>i \\<in> set (map fst ys). i < yi\"\n      by (metis UnCI append_assoc map_append set_append snoc.prems(1) spec_ops_id_inc y_pair)\n    ultimately show ?thesis\n      using oid_yi by auto\n  qed\n  have \"sorted (map fst (xs @ [(oid, oper)] @ ys @ [y]))\"\n  proof -\n    from IH have \"sorted (map fst (xs @ [(oid, oper)] @ ys))\"\n      using spec_ops_def by blast\n    hence \"sorted (map fst (xs @ [(oid, oper)] @ ys) @ [yi])\"\n      using yi_biggest\n      by (simp add: sorted_append dual_order.strict_implies_order)\n    thus \"sorted (map fst (xs @ [(oid, oper)] @ ys @ [y]))\"\n      by (simp add: y_pair)\n  qed\n  moreover have \"distinct (map fst (xs @ [(oid, oper)] @ ys @ [y]))\"\n  proof -\n    have \"distinct (map fst (xs @ [(oid, oper)] @ ys) @ [yi])\"\n      using IH yi_biggest spec_ops_def\n      by (metis distinct.simps(2) distinct1_rotate order_less_irrefl rotate1.simps(2))\n    thus \"distinct (map fst (xs @ [(oid, oper)] @ ys @ [y]))\"\n      by (simp add: y_pair)\n  qed\n  moreover have \"\\<forall>i opr r. (i, opr) \\<in> set (xs @ [(oid, oper)] @ ys @ [y])\n                     \\<and> r \\<in> deps opr \\<longrightarrow> r < i\"\n  proof -\n    have \"\\<forall>i opr r. (i, opr) \\<in> set (xs @ [(oid, oper)] @ ys) \\<and> r \\<in> deps opr \\<longrightarrow> r < i\"\n      by (meson IH spec_ops_def)\n    moreover have \"\\<forall>ref. ref \\<in> deps yo \\<longrightarrow> ref < yi\"\n      by (metis spec_ops_ref_less append_is_Nil_conv last_appendR last_in_set last_snoc\n          list.simps(3) snoc.prems(1) y_pair)\n    ultimately show ?thesis\n      using y_pair by auto\n  qed\n  ultimately show \"spec_ops (xs @ [(oid, oper)] @ ys @ [y]) deps\"\n    using spec_ops_def by blast\nqed\n\nlemma spec_ops_split:\n  assumes \"spec_ops xs deps\"\n    and \"oid \\<notin> set (map fst xs)\"\n  shows \"\\<exists>pre suf. xs = pre @ suf \\<and>\n            (\\<forall>i \\<in> set (map fst pre). i < oid) \\<and>\n            (\\<forall>i \\<in> set (map fst suf). oid < i)\"\n  using assms proof(induction xs rule: rev_induct)\n  case Nil\n  then show ?case by force\nnext\n  case (snoc x xs)\n  obtain xi xr where y_pair: \"x = (xi, xr)\"\n    by force\n  obtain pre suf where IH: \"xs = pre @ suf \\<and>\n               (\\<forall>a\\<in>set (map fst pre). a < oid) \\<and>\n               (\\<forall>a\\<in>set (map fst suf). oid < a)\"\n    by (metis UnCI map_append set_append snoc spec_ops_rem_last)\n  then show ?case\n  proof(cases \"xi < oid\")\n    case xi_less: True\n    have \"\\<forall>x \\<in> set (map fst (pre @ suf)). x < xi\"\n      using IH spec_ops_id_inc snoc.prems(1) y_pair by metis\n    hence \"\\<forall>x \\<in> set suf. fst x < xi\"\n      by simp\n    hence \"\\<forall>x \\<in> set suf. fst x < oid\"\n      using xi_less by auto\n    hence \"suf = []\"\n      using IH last_in_set by fastforce\n    hence \"xs @ [x] = (pre @ [(xi, xr)]) @ [] \\<and>\n              (\\<forall>a\\<in>set (map fst ((pre @ [(xi, xr)]))). a < oid) \\<and>\n              (\\<forall>a\\<in>set (map fst []). oid < a)\"\n      by (simp add: IH xi_less y_pair)\n    then show ?thesis by force\n  next\n    case False\n    hence \"oid < xi\" using snoc.prems(2) y_pair by auto\n    hence \"xs @ [x] = pre @ (suf @ [(xi, xr)]) \\<and>\n              (\\<forall>i \\<in> set (map fst pre). i < oid) \\<and>\n              (\\<forall>i \\<in> set (map fst (suf @ [(xi, xr)])). oid < i)\"\n      by (simp add: IH y_pair)\n    then show ?thesis by blast\n  qed\nqed\n\nlemma spec_ops_exists_base:\n  assumes \"finite ops\"\n    and \"\\<And>oid op1 op2. (oid, op1) \\<in> ops \\<Longrightarrow> (oid, op2) \\<in> ops \\<Longrightarrow> op1 = op2\"\n    and \"\\<And>oid oper ref. (oid, oper) \\<in> ops \\<Longrightarrow> ref \\<in> deps oper \\<Longrightarrow> ref < oid\"\n  shows \"\\<exists>op_list. set op_list = ops \\<and> spec_ops op_list deps\"\n  using assms proof(induct ops rule: Finite_Set.finite_induct_select)\n  case empty\n  then show \"\\<exists>op_list. set op_list = {} \\<and> spec_ops op_list deps\"\n    by (simp add: spec_ops_empty)\nnext\n  case (select subset)\n  from this obtain op_list where \"set op_list = subset\" and \"spec_ops op_list deps\"\n    using assms by blast\n  moreover obtain oid oper where select: \"(oid, oper) \\<in> ops - subset\"\n    using select.hyps(1) by auto\n  moreover from this have \"\\<And>op2. (oid, op2) \\<in> ops \\<Longrightarrow> op2 = oper\"\n    using assms(2) by auto\n  hence \"oid \\<notin> fst ` subset\"\n    by (metis (no_types, lifting) DiffD2 select image_iff prod.collapse psubsetD select.hyps(1))\n  from this obtain pre suf\n    where \"op_list = pre @ suf\"\n      and \"\\<forall>i \\<in> set (map fst pre). i < oid\"\n      and \"\\<forall>i \\<in> set (map fst suf). oid < i\"\n    using spec_ops_split calculation by (metis (no_types, lifting) set_map)\n  moreover have \"set (pre @ [(oid, oper)] @ suf) = insert (oid, oper) subset\"\n    using calculation by auto\n  moreover have \"spec_ops (pre @ [(oid, oper)] @ suf) deps\"\n    using calculation spec_ops_add_any assms(3) by (metis DiffD1)\n  ultimately show ?case by blast\nqed\n\ntext\\<open>We prove that for any given OpSet, a \\isa{spec-ops} linearisation exists:\\<close>\n\nlemma spec_ops_exists:\n  assumes \"opset ops deps\"\n  shows \"\\<exists>op_list. set op_list = ops \\<and> spec_ops op_list deps\"\nproof -\n  have \"finite ops\"\n    using assms opset.finite_opset by force\n  moreover have \"\\<And>oid op1 op2. (oid, op1) \\<in> ops \\<Longrightarrow> (oid, op2) \\<in> ops \\<Longrightarrow> op1 = op2\"\n    using assms opset.unique_oid by force\n  moreover have \"\\<And>oid oper ref. (oid, oper) \\<in> ops \\<Longrightarrow> ref \\<in> deps oper \\<Longrightarrow> ref < oid\"\n    using assms opset.ref_older by force\n  ultimately show \"\\<exists>op_list. set op_list = ops \\<and> spec_ops op_list deps\"\n    by (simp add: spec_ops_exists_base)\nqed\n\nlemma spec_ops_oid_unique:\n  assumes \"spec_ops op_list deps\"\n    and \"(oid, op1) \\<in> set op_list\"\n    and \"(oid, op2) \\<in> set op_list\"\n  shows \"op1 = op2\"\n  using assms proof(induction op_list, simp)\n  case (Cons x op_list)\n  have \"distinct (map fst (x # op_list))\"\n    using Cons.prems(1) spec_ops_def by blast\n  hence notin: \"fst x \\<notin> set (map fst op_list)\"\n    by simp\n  then show \"op1 = op2\"\n  proof(cases \"fst x = oid\")\n    case True\n    then show \"op1 = op2\"\n      using Cons.prems notin by (metis Pair_inject in_set_zipE set_ConsD zip_map_fst_snd)\n  next\n    case False\n    then have \"(oid, op1) \\<in> set op_list\" and \"(oid, op2) \\<in> set op_list\"\n      using Cons.prems by auto\n    then show \"op1 = op2\"\n      using Cons.IH Cons.prems(1) spec_ops_rem_cons by blast\n  qed\nqed\n\ntext\\<open>Conversely, for any given \\isa{spec-ops} list, the set of pairs in the\nlist is an OpSet:\\<close>\n\nlemma spec_ops_is_opset:\n  assumes \"spec_ops op_list deps\"\n  shows \"opset (set op_list) deps\"\nproof -\n  have \"\\<And>oid op1 op2. (oid, op1) \\<in> set op_list \\<Longrightarrow> (oid, op2) \\<in> set op_list \\<Longrightarrow> op1 = op2\"\n    using assms spec_ops_oid_unique by fastforce\n  moreover have \"\\<And>oid oper ref. (oid, oper) \\<in> set op_list \\<Longrightarrow> ref \\<in> deps oper \\<Longrightarrow> ref < oid\"\n    by (meson assms spec_ops_ref_less)\n  moreover have \"finite (set op_list)\"\n    by simp\n  ultimately show \"opset (set op_list) deps\"\n    by (simp add: opset_def)\nqed\n\n\nsubsection\\<open>The \\isa{crdt-ops} predicate\\<close>\n\ntext\\<open>Like \\isa{spec-ops}, the \\isa{crdt-ops} predicate describes the linearisation of\nan OpSet into a list. Like \\isa{spec-ops}, it requires IDs to be unique. However,\nits other properties are different: \\isa{crdt-ops} does not require operations to\nappear in sorted order, but instead, whenever any operation references the\nID of a prior operation, that prior operation must appear previously in the\n\\isa{crdt-ops} list. Thus, the order of operations is partially constrained:\noperations must appear in causal order, but concurrent operations can be\nordered arbitrarily.\n\nThis list describes the operation sequence in the order it is typically applied to\nan operation-based CRDT. Applying operations in the order they appear in\n\\isa{crdt-ops} requires that concurrent operations commute. For any \\isa{crdt-ops}\noperation sequence, there is a permutation that satisfies the \\isa{spec-ops}\npredicate. Thus, to check whether a CRDT satisfies its sequential specification,\nwe can prove that interpreting any \\isa{crdt-ops} operation sequence with the\ncommutative operation interpretation results in the same end result as\ninterpreting the \\isa{spec-ops} permutation of that operation sequence with the\nsequential operation interpretation.\\<close>\n\ninductive crdt_ops :: \"('oid::{linorder} \\<times> 'oper) list \\<Rightarrow> ('oper \\<Rightarrow> 'oid set) \\<Rightarrow> bool\" where\n  \"crdt_ops [] deps\" |\n  \"\\<lbrakk>crdt_ops xs deps;\n    oid \\<notin> set (map fst xs);\n    \\<forall>ref \\<in> deps oper. ref \\<in> set (map fst xs) \\<and> ref < oid\n   \\<rbrakk> \\<Longrightarrow> crdt_ops (xs @ [(oid, oper)]) deps\"\n\ninductive_cases crdt_ops_last: \"crdt_ops (xs @ [x]) deps\"\n\nlemma crdt_ops_intro:\n  assumes \"\\<And>r. r \\<in> deps oper \\<Longrightarrow> r \\<in> fst ` set xs \\<and> r < oid\"\n    and \"oid \\<notin> fst ` set xs\"\n    and \"crdt_ops xs deps\"\n  shows \"crdt_ops (xs @ [(oid, oper)]) deps\"\n  using assms crdt_ops.simps by force\n\nlemma crdt_ops_rem_last:\n  assumes \"crdt_ops (xs @ [x]) deps\"\n  shows \"crdt_ops xs deps\"\n  using assms crdt_ops.cases snoc_eq_iff_butlast by blast\n\nlemma crdt_ops_ref_less:\n  assumes \"crdt_ops xs deps\"\n    and \"(oid, oper) \\<in> set xs\"\n    and \"r \\<in> deps oper\"\n  shows \"r < oid\"\n  using assms by (induction rule: crdt_ops.induct, auto)\n\nlemma crdt_ops_ref_less_last:\n  assumes \"crdt_ops (xs @ [(oid, oper)]) deps\"\n    and \"r \\<in> deps oper\"\n  shows \"r < oid\"\n  using assms crdt_ops_ref_less by fastforce\n\nlemma crdt_ops_distinct_fst:\n  assumes \"crdt_ops xs deps\"\n  shows \"distinct (map fst xs)\"\n  using assms proof (induction xs rule: List.rev_induct, simp)\n  case (snoc x xs)\n  hence \"distinct (map fst xs)\"\n    using crdt_ops_last by blast\n  moreover have \"fst x \\<notin> set (map fst xs)\"\n    using snoc by (metis crdt_ops_last fstI image_set)\n  ultimately show \"distinct (map fst (xs @ [x]))\"\n    by simp\nqed\n\nlemma crdt_ops_distinct:\n  assumes \"crdt_ops xs deps\"\n  shows \"distinct xs\"\n  using assms crdt_ops_distinct_fst distinct_map by blast\n\nlemma crdt_ops_unique_last:\n  assumes \"crdt_ops (xs @ [(oid, oper)]) deps\"\n  shows \"oid \\<notin> set (map fst xs)\"\n  using assms crdt_ops.cases by blast\n\nlemma crdt_ops_unique_mid:\n  assumes \"crdt_ops (xs @ [(oid, oper)] @ ys) deps\"\n  shows \"oid \\<notin> set (map fst xs) \\<and> oid \\<notin> set (map fst ys)\"\n  using assms proof(induction ys rule: rev_induct)\n  case Nil\n  then show \"oid \\<notin> set (map fst xs) \\<and> oid \\<notin> set (map fst [])\"\n    by (metis crdt_ops_unique_last Nil_is_map_conv append_Nil2 empty_iff empty_set)\nnext\n  case (snoc y ys)\n  obtain yi yr where y_pair: \"y = (yi, yr)\"\n    by fastforce\n  have IH: \"oid \\<notin> set (map fst xs) \\<and> oid \\<notin> set (map fst ys)\"\n    using crdt_ops_rem_last snoc by (metis append_assoc)\n  have \"(xs @ (oid, oper) # ys) @ [(yi, yr)] = xs @ (oid, oper) # ys @ [(yi, yr)]\"\n    by simp\n  hence \"yi \\<notin> set (map fst (xs @ (oid, oper) # ys))\"\n    using crdt_ops_unique_last by (metis append_Cons append_self_conv2 snoc.prems y_pair)\n  thus \"oid \\<notin> set (map fst xs) \\<and> oid \\<notin> set (map fst (ys @ [y]))\"\n    using IH y_pair by auto\nqed\n\nlemma crdt_ops_ref_exists:\n  assumes \"crdt_ops (pre @ (oid, oper) # suf) deps\"\n    and \"ref \\<in> deps oper\"\n  shows \"ref \\<in> fst ` set pre\"\n  using assms proof(induction suf rule: List.rev_induct)\n  case Nil thus ?case\n    by (metis crdt_ops_last prod.sel(2))\nnext\n  case (snoc x xs) thus ?case\n    using crdt_ops.cases by force\nqed\n\nlemma crdt_ops_no_future_ref:\n  assumes \"crdt_ops (xs @ [(oid, oper)] @ ys) deps\"\n  shows \"\\<And>ref. ref \\<in> deps oper \\<Longrightarrow> ref \\<notin> fst ` set ys\"\nproof -\n  from assms(1) have \"\\<And>ref. ref \\<in> deps oper \\<Longrightarrow> ref \\<in> set (map fst xs)\"\n    by (simp add: crdt_ops_ref_exists)\n  moreover have \"distinct (map fst (xs @ [(oid, oper)] @ ys))\"\n    using assms crdt_ops_distinct_fst by blast\n  ultimately have \"\\<And>ref. ref \\<in> deps oper \\<Longrightarrow> ref \\<notin> set (map fst ([(oid, oper)] @ ys))\"\n    using distinct_fst_append by metis\n  thus \"\\<And>ref. ref \\<in> deps oper \\<Longrightarrow> ref \\<notin> fst ` set ys\"\n    by simp\nqed\n\nlemma crdt_ops_reorder:\n  assumes \"crdt_ops (xs @ [(oid, oper)] @ ys) deps\"\n    and \"\\<And>op2 r. op2 \\<in> snd ` set ys \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r \\<noteq> oid\"\n  shows \"crdt_ops (xs @ ys @ [(oid, oper)]) deps\"\n  using assms proof(induction ys rule: rev_induct)\n  case Nil\n  then show \"crdt_ops (xs @ [] @ [(oid, oper)]) deps\"\n    using crdt_ops_rem_last by auto\nnext\n  case (snoc y ys)\n  then obtain yi yo where y_pair: \"y = (yi, yo)\"\n    by fastforce\n  have IH: \"crdt_ops (xs @ ys @ [(oid, oper)]) deps\"\n  proof -\n    have \"crdt_ops (xs @ [(oid, oper)] @ ys) deps\"\n      by (metis snoc(2) append.assoc crdt_ops_rem_last)\n    thus \"crdt_ops (xs @ ys @ [(oid, oper)]) deps\"\n      using snoc.IH snoc.prems(2) by auto\n  qed\n  have \"crdt_ops (xs @ ys @ [y]) deps\"\n  proof -\n    have \"yi \\<notin> fst ` set (xs @ [(oid, oper)] @ ys)\"\n      by (metis y_pair append_assoc crdt_ops_unique_last set_map snoc.prems(1))\n    hence \"yi \\<notin> fst ` set (xs @ ys)\"\n      by auto\n    moreover have \"\\<And>r. r \\<in> deps yo \\<Longrightarrow> r \\<in> fst ` set (xs @ ys) \\<and> r < yi\"\n    proof -\n      have \"\\<And>r. r \\<in> deps yo \\<Longrightarrow> r \\<noteq> oid\"\n        using snoc.prems(2) y_pair by fastforce\n      moreover have \"\\<And>r. r \\<in> deps yo \\<Longrightarrow> r \\<in> fst ` set (xs @ [(oid, oper)] @ ys)\"\n        by (metis y_pair append_assoc snoc.prems(1) crdt_ops_ref_exists)\n      moreover have \"\\<And>r. r \\<in> deps yo \\<Longrightarrow> r < yi\"\n        using crdt_ops_ref_less snoc.prems(1) y_pair by fastforce\n      ultimately show \"\\<And>r. r \\<in> deps yo \\<Longrightarrow> r \\<in> fst ` set (xs @ ys) \\<and> r < yi\"\n        by simp\n    qed\n    moreover from IH have \"crdt_ops (xs @ ys) deps\"\n      using crdt_ops_rem_last by force\n    ultimately show \"crdt_ops (xs @ ys @ [y]) deps\"\n      using y_pair crdt_ops_intro by (metis append.assoc)\n  qed\n  moreover have \"oid \\<notin> fst ` set (xs @ ys @ [y])\"\n    using crdt_ops_unique_mid by (metis (no_types, lifting) UnE image_Un\n        image_set set_append snoc.prems(1))\n  moreover have \"\\<And>r. r \\<in> deps oper \\<Longrightarrow> r \\<in> fst ` set (xs @ ys @ [y])\"\n    using crdt_ops_ref_exists\n    by (metis UnCI append_Cons image_Un set_append snoc.prems(1))\n  moreover have \"\\<And>r. r \\<in> deps oper \\<Longrightarrow> r < oid\"\n    using IH crdt_ops_ref_less by fastforce\n  ultimately show \"crdt_ops (xs @ (ys @ [y]) @ [(oid, oper)]) deps\"\n    using crdt_ops_intro by (metis append_assoc)\nqed\n\nlemma crdt_ops_rem_middle:\n  assumes \"crdt_ops (xs @ [(oid, ref)] @ ys) deps\"\n    and \"\\<And>op2 r. op2 \\<in> snd ` set ys \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r \\<noteq> oid\"\n  shows \"crdt_ops (xs @ ys) deps\"\n  using assms crdt_ops_rem_last crdt_ops_reorder append_assoc by metis\n\nlemma crdt_ops_independent_suf:\n  assumes \"spec_ops (xs @ [(oid, oper)]) deps\"\n    and \"crdt_ops (ys @ [(oid, oper)] @ zs) deps\"\n    and \"set (xs @ [(oid, oper)]) = set (ys @ [(oid, oper)] @ zs)\"\n  shows \"\\<And>op2 r. op2 \\<in> snd ` set zs \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r \\<noteq> oid\"\nproof -\n  have \"\\<And>op2 r. op2 \\<in> snd ` set xs \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r < oid\"\n  proof -\n    from assms(1) have \"\\<And>i. i \\<in> fst ` set xs \\<Longrightarrow> i < oid\"\n      using spec_ops_id_inc by fastforce\n    moreover have \"\\<And>i2 op2 r. (i2, op2) \\<in> set xs \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r < i2\"\n      using assms(1) spec_ops_ref_less spec_ops_rem_last by fastforce\n    ultimately show \"\\<And>op2 r. op2 \\<in> snd ` set xs \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r < oid\"\n      by fastforce\n  qed\n  moreover have \"set zs \\<subseteq> set xs\"\n  proof -\n    have \"distinct (xs @ [(oid, oper)])\" and \"distinct (ys @ [(oid, oper)] @ zs)\"\n      using assms spec_ops_distinct crdt_ops_distinct by blast+\n    hence \"set xs = set (ys @ zs)\"\n      by (meson append_set_rem_last assms(3))\n    then show \"set zs \\<subseteq> set xs\"\n      using append_subset(2) by simp\n  qed\n  ultimately show \"\\<And>op2 r. op2 \\<in> snd ` set zs \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r \\<noteq> oid\"\n    by fastforce\nqed\n\nlemma crdt_ops_reorder_spec:\n  assumes \"spec_ops (xs @ [x]) deps\"\n    and \"crdt_ops (ys @ [x] @ zs) deps\"\n    and \"set (xs @ [x]) = set (ys @ [x] @ zs)\"\n  shows \"crdt_ops (ys @ zs @ [x]) deps\"\n  using assms proof -\n  obtain oid oper where x_pair: \"x = (oid, oper)\" by force\n  hence \"\\<And>op2 r. op2 \\<in> snd ` set zs \\<Longrightarrow> r \\<in> deps op2 \\<Longrightarrow> r \\<noteq> oid\"\n    using assms crdt_ops_independent_suf by fastforce\n  thus \"crdt_ops (ys @ zs @ [x]) deps\"\n    using assms(2) crdt_ops_reorder x_pair by metis\nqed\n\nlemma crdt_ops_rem_spec:\n  assumes \"spec_ops (xs @ [x]) deps\"\n    and \"crdt_ops (ys @ [x] @ zs) deps\"\n    and \"set (xs @ [x]) = set (ys @ [x] @ zs)\"\n  shows \"crdt_ops (ys @ zs) deps\"\n  using assms crdt_ops_rem_last crdt_ops_reorder_spec append_assoc by metis\n\nlemma crdt_ops_rem_penultimate:\n  assumes \"crdt_ops (xs @ [(i1, r1)] @ [(i2, r2)]) deps\"\n    and \"\\<And>r. r \\<in> deps r2 \\<Longrightarrow> r \\<noteq> i1\"\n  shows \"crdt_ops (xs @ [(i2, r2)]) deps\"\nproof -\n  have \"crdt_ops (xs @ [(i1, r1)]) deps\"\n    using assms(1) crdt_ops_rem_last by force\n  hence \"crdt_ops xs deps\"\n    using crdt_ops_rem_last by force\n  moreover have \"distinct (map fst (xs @ [(i1, r1)] @ [(i2, r2)]))\"\n    using assms(1) crdt_ops_distinct_fst by blast\n  hence \"i2 \\<notin> set (map fst xs)\"\n    by auto\n  moreover have \"crdt_ops ((xs @ [(i1, r1)]) @ [(i2, r2)]) deps\"\n    using assms(1) by auto\n  hence \"\\<And>r. r \\<in> deps r2 \\<Longrightarrow> r \\<in> fst ` set (xs @ [(i1, r1)])\"\n    using crdt_ops_ref_exists by metis\n  hence \"\\<And>r. r \\<in> deps r2 \\<Longrightarrow> r \\<in> set (map fst xs)\"\n    using assms(2) by auto\n  moreover have \"\\<And>r. r \\<in> deps r2 \\<Longrightarrow> r < i2\"\n    using assms(1) crdt_ops_ref_less by fastforce\n  ultimately show \"crdt_ops (xs @ [(i2, r2)]) deps\"\n    by (simp add: crdt_ops_intro)\nqed\n\nlemma crdt_ops_spec_ops_exist:\n  assumes \"crdt_ops xs deps\"\n  shows \"\\<exists>ys. set xs = set ys \\<and> spec_ops ys deps\"\n  using assms proof(induction xs rule: List.rev_induct)\n  case Nil\n  then show \"\\<exists>ys. set [] = set ys \\<and> spec_ops ys deps\"\n    by (simp add: spec_ops_empty)\nnext\n  case (snoc x xs)\n  hence IH: \"\\<exists>ys. set xs = set ys \\<and> spec_ops ys deps\"\n    using crdt_ops_rem_last by blast\n  then obtain ys oid ref\n    where \"set xs = set ys\" and \"spec_ops ys deps\" and \"x = (oid, ref)\"\n    by force\n  moreover have \"\\<exists>pre suf. ys = pre@suf \\<and>\n                       (\\<forall>i \\<in> set (map fst pre). i < oid) \\<and>\n                       (\\<forall>i \\<in> set (map fst suf). oid < i)\"\n  proof -\n    have \"oid \\<notin> set (map fst xs)\"\n      using calculation(3) crdt_ops_unique_last snoc.prems by force\n    hence \"oid \\<notin> set (map fst ys)\"\n      by (simp add: calculation(1))\n    thus ?thesis\n      using spec_ops_split \\<open>spec_ops ys deps\\<close> by blast\n  qed\n  from this obtain pre suf where \"ys = pre @ suf\" and\n    \"\\<forall>i \\<in> set (map fst pre). i < oid\" and\n    \"\\<forall>i \\<in> set (map fst suf). oid < i\" by force\n  moreover have \"set (xs @ [(oid, ref)]) = set (pre @ [(oid, ref)] @ suf)\"\n    using crdt_ops_distinct calculation snoc.prems by simp\n  moreover have \"spec_ops (pre @ [(oid, ref)] @ suf) deps\"\n  proof -\n    have \"\\<forall>r \\<in> deps ref. r < oid\"\n      using calculation(3) crdt_ops_ref_less_last snoc.prems by fastforce\n    hence \"spec_ops (pre @ [(oid, ref)] @ suf) deps\"\n      using spec_ops_add_any calculation by metis\n    thus ?thesis by simp\n  qed\n  ultimately show \"\\<exists>ys. set (xs @ [x]) = set ys \\<and> spec_ops ys deps\"\n    by blast\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/OpSets/OpSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.8438951045175642, "lm_q1q2_score": 0.776081831825672}}
{"text": "(* Title: Isomorphisms Betweeen Predicates, Sets and Relations *}\n   Author: Victor Gomes, Georg Struth\n   Maintainer: Victor Gomes <victor.gomes@cl.cam.ac.uk>\n               Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Isomorphisms Between Predicates, Sets and Relations\\<close>\n\ntheory P2S2R\nimports Main\n\nbegin    \n\nnotation relcomp (infixl \";\" 70)\nnotation inf (infixl \"\\<sqinter>\" 70)  \nnotation sup (infixl \"\\<squnion>\" 65)\nnotation Id_on (\"s2r\")\nnotation Domain (\"r2s\")\nnotation Collect (\"p2s\")\n\ndefinition rel_n :: \"'a rel \\<Rightarrow> 'a rel\" where \n  \"rel_n  \\<equiv> (\\<lambda>X. Id \\<inter> - X)\"  \n\nlemma subid_meet: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> R \\<inter> S = R ; S\"\n  by blast\n\nsubsection\\<open>Isomorphism Between Sets and Relations\\<close>\n\nlemma srs: \"r2s \\<circ> s2r = id\"\n  by auto\n\nlemma rsr: \"R \\<subseteq> Id \\<Longrightarrow> s2r (r2s R) = R\"\n  by (auto simp: Id_def Id_on_def Domain_def) \n\nlemma s2r_inj: \"inj s2r\"\n  by (metis Domain_Id_on injI)\n\nlemma r2s_inj: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2s R = r2s S \\<Longrightarrow> R = S\"\n  by (metis rsr)\n\nlemma s2r_surj: \"\\<forall>R \\<subseteq> Id. \\<exists>A. R = s2r A\"\n  using rsr by auto\n \nlemma r2s_surj: \"\\<forall>A. \\<exists>R \\<subseteq> Id. A = r2s R\"\n  by (metis Domain_Id_on Id_onE pair_in_Id_conv subsetI)\n\nlemma s2r_union_hom: \"s2r (A \\<union> B) = s2r A \\<union> s2r B\"\n  by (simp add: Id_on_def)\n\nlemma s2r_inter_hom: \"s2r (A \\<inter> B) = s2r A \\<inter> s2r B\"\n  by (auto simp: Id_on_def)  \n\nlemma s2r_inter_hom_var: \"s2r (A \\<inter> B) = s2r A ; s2r B\"\n  by (auto simp: Id_on_def)\n\nlemma s2r_compl_hom: \"s2r (- A) = rel_n (s2r A)\"\n  by (auto simp add: rel_n_def)\n\nlemma r2s_union_hom: \"r2s (R \\<union> S) = r2s R \\<union> r2s S\"\n  by auto\n\nlemma r2s_inter_hom: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2s (R \\<inter> S) = r2s R \\<inter> r2s S\"\n  by auto\n\nlemma r2s_inter_hom_var: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2s (R ; S) = r2s R \\<inter> r2s S\"\n  by (metis r2s_inter_hom subid_meet)\n\nlemma r2s_ad_hom: \"R \\<subseteq> Id \\<Longrightarrow> r2s (rel_n R) = - r2s R\"\n  by (metis r2s_surj rsr s2r_compl_hom)\n\nsubsection \\<open>Isomorphism Between Predicates and Sets\\<close>\n\ntype_synonym 'a pred = \"'a \\<Rightarrow> bool\"\n\ndefinition s2p :: \"'a set \\<Rightarrow> 'a pred\" where\n  \"s2p S = (\\<lambda>x. x \\<in> S)\"\n\nlemma sps [simp]: \"s2p \\<circ> p2s = id\" \n  by (intro ext, simp add: s2p_def)\n\nlemma psp [simp]: \"p2s \\<circ> s2p = id\"\n  by (intro ext, simp add: s2p_def)\n\nlemma s2p_bij: \"bij s2p\"\n  using o_bij psp sps by blast\n\nlemma p2s_bij: \"bij p2s\"\n  using o_bij psp sps by blast\n\nlemma s2p_compl_hom: \"s2p (- A) = - (s2p A)\"\n  by (metis Collect_mem_eq comp_eq_dest_lhs id_apply sps uminus_set_def)\n \nlemma s2p_inter_hom: \"s2p (A \\<inter> B) = (s2p A) \\<sqinter> (s2p B)\"\n  by (metis Collect_mem_eq comp_eq_dest_lhs id_apply inf_set_def sps)\n\nlemma s2p_union_hom: \"s2p (A \\<union> B) = (s2p A) \\<squnion> (s2p B)\"\n  by (auto simp: s2p_def)\n\nlemma p2s_neg_hom: \"p2s (- P) = - (p2s P)\"\n  by fastforce\n\nlemma p2s_conj_hom: \"p2s (P \\<sqinter> Q) = p2s P \\<inter> p2s Q\"\n  by blast\n\nlemma p2s_disj_hom: \"p2s (P \\<squnion> Q) = p2s P \\<union> p2s Q\"\n  by blast\n\nsubsection \\<open>Isomorphism Between Predicates and Relations\\<close>\n\ndefinition p2r :: \"'a pred \\<Rightarrow> 'a rel\" where\n  \"p2r P = {(s,s) |s. P s}\"\n\ndefinition r2p :: \"'a rel \\<Rightarrow> 'a pred\" where\n  \"r2p R = (\\<lambda>x. x \\<in> Domain R)\"\n\nlemma p2r_subid: \"p2r P \\<subseteq> Id\"\n  by (simp add: p2r_def subset_eq)\n\nlemma p2s2r: \"p2r = s2r \\<circ> p2s\"\nproof (intro ext)\n  fix P :: \"'a pred\"\n  have \"{(a, a) |a. P a} = {(b, a). b = a \\<and> P b}\"\n    by blast\n  thus \"p2r P = (s2r \\<circ> p2s) P\"\n    by (simp add: Id_on_def' p2r_def)\nqed\n\nlemma r2s2p: \"r2p = s2p \\<circ> r2s\"\n  by (intro ext, simp add: r2p_def s2p_def)\n\nlemma prp [simp]: \"r2p \\<circ> p2r = id\"\n  by (intro ext, simp add: p2s2r r2p_def)\n\nlemma rpr: \"R \\<subseteq> Id \\<Longrightarrow> p2r (r2p R) = R\"\n  by (metis comp_apply id_apply p2s2r psp r2s2p rsr)\n\nlemma p2r_inj: \"inj p2r\"\n  by (metis comp_eq_dest_lhs id_apply injI prp)\n\nlemma r2p_inj: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2p R = r2p S \\<Longrightarrow> R = S\"\n  by (metis rpr)\n\nlemma p2r_surj: \"\\<forall> R \\<subseteq> Id. \\<exists>P. R = p2r P\"\n  using rpr by auto\n\nlemma r2p_surj: \"\\<forall>P. \\<exists>R \\<subseteq> Id. P = r2p R\"\n  by (metis comp_apply id_apply p2r_subid prp)\n\nlemma p2r_neg_hom: \"p2r (- P) = rel_n (p2r P)\"\n  by (simp add: p2s2r p2s_neg_hom s2r_compl_hom)\n\nlemma p2r_conj_hom [simp]: \"p2r P \\<inter> p2r Q = p2r (P \\<sqinter> Q)\"\n  by (simp add: p2s2r p2s_conj_hom s2r_inter_hom)\n\nlemma p2r_conj_hom_var [simp]: \"p2r P ; p2r Q = p2r (P \\<sqinter> Q)\"\n  by (simp add: p2s2r p2s_conj_hom s2r_inter_hom_var)\n\nlemma p2r_id_neg [simp]: \"Id \\<inter> - p2r p = p2r (-p)\"\n  by (auto simp: p2r_def)\n\n\n\nlemma p2r_disj_hom [simp]: \"p2r P \\<union> p2r Q = p2r (P \\<squnion> Q)\"\n  by (simp add: p2s2r p2s_disj_hom s2r_union_hom)\n\nlemma r2p_ad_hom: \"R \\<subseteq> Id \\<Longrightarrow> r2p (rel_n R) = - (r2p R)\"\n  by (simp add: r2s2p r2s_ad_hom s2p_compl_hom)\n\nlemma r2p_inter_hom: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2p (R \\<inter> S) = (r2p R) \\<sqinter> (r2p S)\"\n  by (simp add: r2s2p r2s_inter_hom s2p_inter_hom)\n\nlemma r2p_inter_hom_var: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2p (R ; S) = (r2p R) \\<sqinter> (r2p S)\"\n  by (simp add: r2s2p r2s_inter_hom_var s2p_inter_hom)\n\nlemma rel_to_pred_union_hom: \"R \\<subseteq> Id \\<Longrightarrow> S \\<subseteq> Id \\<Longrightarrow> r2p (R \\<union> S) = (r2p R) \\<squnion> (r2p S)\"\n  by (simp add: Domain_Un_eq r2s2p s2p_union_hom)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Algebraic_VCs/P2S2R.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7759803807027298}}
{"text": "theory a1\nimports Main\nbegin\n\nsection \"Question 1: Lambda-Calculus\"\n\ntext {* submit as part of a .txt or .pdf file *}\n\nsection \"Question 2: Higher Order Unification\"\n\ntext {* submit as part of a .txt or .pdf file *}\n\nsection \"Question 3: Propositional Logic\"\n\nlemma prop_a:\n  \"B \\<longrightarrow> (B \\<or> A)\"\n  apply (rule impI)\n  apply (rule disjI1)\n  apply assumption\n  done\n\nlemma prop_b:\n  \"(A = True) = A\"\n  apply (rule iffI)\n  apply (erule iffE)\n  apply (erule impE)\n  apply (erule impE)\n  apply (rule TrueI)\n  apply assumption\n  apply (erule impE)\n  apply assumption+\n  apply (rule iffI)\n  apply (rule TrueI)\n  apply assumption\n  done\n\nlemma prop_c:\n  \"(A = False) = (\\<not> A)\"\n  apply (rule iffI)\n  apply (erule iffE)\n  apply (rule notI)\n  apply (erule impE)\n  apply assumption+\n  apply (rule iffI)\n  apply (erule notE)\n  apply assumption+\n  apply (rule ccontr)\n  apply assumption\n  done\n\nlemma prop_d: \"P \\<longrightarrow> \\<not>\\<not>P\"\n  apply (rule impI)\n  apply (rule notI)\n  apply (erule notE)\n  apply assumption\n  done\n\nlemma prop_e: \"\\<not>\\<not>P \\<longrightarrow> P\"\n  apply (rule impI)\n  apply (case_tac P)\n  apply assumption\n  apply (erule notE)\n  apply assumption\n  done\n\ntext {* \nWhich of the above statements are provable only in a classical logic? \ne\n*}\n\nsection \"Question 4: Higher Order Logic\"\n\nlemma hol_a:\n  \"(\\<forall>x. P x) \\<or> (\\<forall>x. Q x) \\<longrightarrow> (\\<forall>x. P x \\<or> Q x)\"\n  apply (rule impI)\n  apply (rule allI)\n  apply (erule disjE)\n  apply (rule disjI1)\n  apply (erule spec)\n  apply (rule disjI2)\n  apply (erule spec)\n  done\n\nlemma hol_b:\n  \"(\\<forall>P. P) = False\"\n  apply (rule iffI)\n  apply (erule_tac x=False in allE)\n  apply assumption\n  apply (erule FalseE)\n  done\n\nlemma hol_c:\n  \"(\\<forall>x. Q x = P x) \\<and> ((\\<exists>x. P x) \\<longrightarrow> C) \\<and> (\\<exists>x. Q x) \\<longrightarrow> C\"\n  apply (rule impI) \n  apply (erule conjE)+\n  apply (erule impE)\n  apply (erule exE)\n  apply (erule_tac x=x in allE)\n  apply (rule_tac x=x in exI)\n  apply (erule iffE)\n  apply (erule impE)\n  apply assumption+\n  done\n\nlemma hol_d:\n  \"(\\<forall>x. \\<not> (R x) \\<longrightarrow> R (M x)) \\<Longrightarrow> (\\<forall>x. \\<not> R (M x) \\<longrightarrow> R x)\"\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule_tac x=x in allE)\n  apply (rule classical)\n  apply (erule impE)\n  apply assumption\n  apply (erule notE)\n  apply assumption\n  done\n\nlemma hol_e:\n  \"\\<lbrakk>(\\<forall>x. \\<not> (R x) \\<longrightarrow> R (M x)); (\\<exists>x. R x)\\<rbrakk> \\<Longrightarrow> (\\<exists>x. R x \\<and> R (M (M x)))\"\n  apply (erule exE)\n  apply (rule classical)\n  apply (rule_tac x=x in exI)\n  apply (rule conjI)\n  apply (erule_tac x=x in allE)\n  apply assumption\n  apply (erule notE)\n  apply (rule classical)\n  apply (erule notE)\n  apply (rule classical)\n  apply (rule exI)\n  apply (rule conjI)\n  apply  assumption\n  apply (rule classical)\n  apply (erule notE)\n  apply (rule_tac x=\"M x\" in exI)\n  apply (rule conjI)\n  apply (erule_tac x=\"M x\" in allE)\n  apply (rule classical)\n  apply (erule impE)\n  apply assumption\n  apply (erule notE)\n  apply assumption\n  apply (erule allE)\n  apply (erule impE)\n  apply assumption+\n  done\n\ntext {* \nFormalise and prove the following statement using only the proof methods and rules as earlier in this question.\n\nIf every poor person has a rich mother, then there is a rich person\nwith a rich grandmother.\n*}\n\nlemma \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (M x) \\<Longrightarrow> \\<exists>x. rich x \\<longrightarrow> rich (M (M x))\"\n  apply (erule allE)\n  apply (rule classical)\n  apply (erule impE)\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule exI)\n  apply (rule impI)\n  apply assumption\n  apply (rule exI)\n  apply (erule notE)\n  apply (rule exI)\n  apply (rule impI)\n  apply assumption\n  done\n\nend\n", "meta": {"author": "SongtingYU", "repo": "Advanced-Topics-in-Software-Verification", "sha": "91474c89c16bfba9c14e9744c98324b3d825a687", "save_path": "github-repos/isabelle/SongtingYU-Advanced-Topics-in-Software-Verification", "path": "github-repos/isabelle/SongtingYU-Advanced-Topics-in-Software-Verification/Advanced-Topics-in-Software-Verification-91474c89c16bfba9c14e9744c98324b3d825a687/a1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7759803680328347}}
{"text": "text\\<open> 21 October 2021: Exercise for Homework Assignment 07 in CS 511 \\<close> \ntext\\<open> Your task to remove the invocations of the pre-defined method \n      'blast' by an equivalent sequence of 'apply' steps \\<close>\n\ntheory HW07_solution\n  imports Main\nbegin\n\ntext\\<open> 'blast' is invoked three times, once in the proof of each of\n      lemmas B1, C1, and D1 below \\<close>\n\n(* The proof of the next lemma is just an example of how to use the\n   rules for manipulating quantifiers *)\nlemma preliminary : \" (\\<exists>z. P z) \\<and> Q \\<longrightarrow> (\\<exists>y. P y \\<and> Q)\"\napply (rule impI)\napply (erule conjE)\napply (erule exE)\napply (rule_tac x=\"z\" in exI)\napply (rule conjI)\napply assumption+\ndone\n\n(* Lemma A1 is the same in Exercise 2.3.9 (a), page 161, in [LCS] *)\nlemma A1 : \"(\\<exists>x. S \\<longrightarrow> Q x) \\<Longrightarrow> S \\<longrightarrow> (\\<exists>x. Q x)\" \n  apply (erule exE)\n  apply (rule impI)\n  apply (erule impE)\n   apply assumption\n  apply (rule_tac x=\"x\" in exI)\n  apply assumption\n  done\n\n(* Lemma A2 is the same as lemma A1 but with a different proof *)\nlemma A2 : \"(\\<exists>x. S \\<longrightarrow> Q x) \\<Longrightarrow> S \\<longrightarrow> (\\<exists>x. Q x)\" \n  apply clarify\n  apply (rule_tac x=\"x\" in exI)\n  apply assumption\n  done\n\n(* Lemma B1 is the same in Exercise 2.3.9 (b), page 161, in [LCS] *)\nlemma B1 : \"S \\<longrightarrow> (\\<exists>x. Q x) \\<Longrightarrow> (\\<exists>x. S \\<longrightarrow> Q x)\" \n  by blast\n\ntext \\<open>\nlemma B1_by_Mattia : \"S \\<longrightarrow> (\\<exists>x. Q x) \\<Longrightarrow> (\\<exists>x. S \\<longrightarrow> Q x)\"\n\tapply(rule_tac x=\"x\" in exI)  (* Sledgehammer fails or says it is unprovable *)\n\tapply(rule impI)\n\tapply(erule impE)\n\t apply assumption\n\tapply(erule exE)\n\\<close>\ntext\\<open> Note: Copying in the secondary windows/panels works via the keyboard shortcuts \n  Ctrl+c or Ctrl+INSERT, while jEdit menu actions always refer to the primary windown/panel. \\<close>\n\ntext\\<open> The proof below consists of 'apply' steps only. The inserted comment\n      after every step is the resulting 'proof state'. This proof is not\n      the shortest or the most elegant, but understanding every step is a\n      good exercise for how to apply the available pre-defined rules. \\<close>\nlemma B2 : \"S \\<longrightarrow> (\\<exists>x. Q x) \\<Longrightarrow> (\\<exists>x. S \\<longrightarrow> Q x)\" \n  apply (rule exCI)  \n(* S \\<longrightarrow> (\\<exists>x. Q x) \\<Longrightarrow> \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n  apply (erule impE)\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> S\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n   apply (erule allE)\n(*  1. \\<not> (S \\<longrightarrow> Q ?x5) \\<Longrightarrow> S\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n   apply (rule contrapos_np)\n(*  1. \\<not> (S \\<longrightarrow> Q ?x5) \\<Longrightarrow> \\<not> ?Q7\n    2. \\<not> (S \\<longrightarrow> Q ?x5) \\<Longrightarrow> \\<not> S \\<Longrightarrow> ?Q7\n    3. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n    apply assumption\n(*  1. \\<not> (S \\<longrightarrow> Q ?x5) \\<Longrightarrow> \\<not> S \\<Longrightarrow> S \\<longrightarrow> Q ?x5\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n   apply (rule impI)\n(*  1. \\<not> (S \\<longrightarrow> Q ?x5) \\<Longrightarrow> \\<not> S \\<Longrightarrow> S \\<Longrightarrow> Q ?x5\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n   apply (erule notE)+\n(*  1. S \\<Longrightarrow> S\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n   apply assumption\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<longrightarrow> Q ?a *)\n  apply (rule impI)\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> Q ?a *)\n  apply (rule notE) \n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> ?P18\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> ?P18 *)\n   apply (rule notI) \n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> ?P18 \\<Longrightarrow> False\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> ?P18 *)\n   apply (erule FalseE) \n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> False *)\n  apply (rule contrapos_np)\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> ?Q24\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> False \\<Longrightarrow> ?Q24 *)\n   apply (rule notI)\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> ?Q24 \\<Longrightarrow> False\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> False \\<Longrightarrow> ?Q24 *)\n   apply (erule notE)\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> ?P29\n    2. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> False \\<Longrightarrow> \\<not> ?P29 *)\n   apply assumption\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> False \\<Longrightarrow> \\<not> (\\<forall>x. \\<not> (S \\<longrightarrow> Q x)) *)\n  apply (rule notI)\n(*  1. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> \\<exists>x. Q x \\<Longrightarrow> S \\<Longrightarrow> \\<not> False \\<Longrightarrow> \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> False *)\n  apply (erule exE)\n(*  1. \\<And>x. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> S \\<Longrightarrow> \\<not> False \\<Longrightarrow> \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> Q x \\<Longrightarrow> False *)\n  apply (erule notE) \n(*  1. \\<And>x. \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> S \\<Longrightarrow> \\<forall>x. \\<not> (S \\<longrightarrow> Q x) \\<Longrightarrow> Q x \\<Longrightarrow> False *)\n  apply (erule allE)+ \n(*  1. \\<And>x. S \\<Longrightarrow> Q x \\<Longrightarrow> \\<not> (S \\<longrightarrow> Q (?x37 x)) \\<Longrightarrow> \\<not> (S \\<longrightarrow> Q (?x39 x)) \\<Longrightarrow> False *)\n  apply (erule notE)+ \n(*  1. \\<And>x. S \\<Longrightarrow> Q x \\<Longrightarrow> S \\<longrightarrow> Q (?x39 x) *)\n  apply (rule impI) \n(*  1. \\<And>x. S \\<Longrightarrow> Q x \\<Longrightarrow> S \\<Longrightarrow> Q (?x39 x) *)\n  apply assumption\n(* No subgoals! *)\n  done\n(* Lemma C1 is the same in Exercise 2.3.9 (c), page 161, in [LCS] *)\nlemma C1 : \"(\\<exists>x. P x) \\<longrightarrow> S \\<Longrightarrow> \\<forall>x. (P x \\<longrightarrow> S)\"\n  by blast\ntext\\<open> The proof below consists of 'apply' steps only. \\<close>\nlemma C2 : \"(\\<exists>x. P x) \\<longrightarrow> S \\<Longrightarrow> \\<forall>x. (P x \\<longrightarrow> S)\"\n  apply (rule allI)\n  apply (rule impI)\n  apply (erule impE)\n  apply (rule_tac x=\"x\" in exI)\n   apply assumption+\n  done\n\n(* Lemma D1 is the same in Exercise 2.3.9 (d), page 161, in [LCS] *)\nlemma D1 : \" (\\<forall>x. P x) \\<longrightarrow> S \\<Longrightarrow> \\<exists>x. (P x \\<longrightarrow> S)\"\n  by blast\ntext\\<open> The proof below consists of 'apply' steps. The inserted comment\n      after every step is the resulting 'proof state'. This proof is not\n      the shortest or the most elegant, but understanding every step is a\n      good exercise for how to apply the available pre-defined rules. \\<close>\nlemma D2 : \" (\\<forall>x. P x) \\<longrightarrow> S \\<Longrightarrow> \\<exists>x. (P x \\<longrightarrow> S)\"\n  apply (rule exCI)\n(* 1. (\\<forall>x. P x) \\<longrightarrow> S \\<Longrightarrow> \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n  apply (erule impE)\n(*  1. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> \\<forall>x. P x\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply (rule allI)\n(*  1. \\<And>x. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> P x\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply (erule_tac x=\"x\" in allE)\n(*  1. \\<And>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> P x\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply  (rule contrapos_np)\n(*  1. \\<And>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> \\<not> ?Q8 x\n    2. \\<And>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> \\<not> P x \\<Longrightarrow> ?Q8 x\n    3. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n    apply assumption\n(*  1. \\<And>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> \\<not> P x \\<Longrightarrow> P x \\<longrightarrow> S\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply (rule impI)\n(*  1. \\<And>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> \\<not> P x \\<Longrightarrow> P x \\<Longrightarrow> S\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply (erule notE)\n(*  1. \\<And>x. \\<not> P x \\<Longrightarrow> P x \\<Longrightarrow> P x \\<longrightarrow> S\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply (rule impI)\n(*  1. \\<And>x. \\<not> P x \\<Longrightarrow> P x \\<Longrightarrow> P x \\<Longrightarrow> S\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply (erule notE)\n(*  1. \\<And>x. P x \\<Longrightarrow> P x \\<Longrightarrow> P x\n    2. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n   apply assumption\n(*  1. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<longrightarrow> S *)\n  apply (rule impI)\n(*  1. \\<forall>x. \\<not> (P x \\<longrightarrow> S) \\<Longrightarrow> S \\<Longrightarrow> P ?a \\<Longrightarrow> S *)\n  apply assumption\n(* No subgoals! *)\n  done\nend", "meta": {"author": "decltypeme", "repo": "cs511", "sha": "be4f4ba351ff94ac35316c1228c0242e1c3449d0", "save_path": "github-repos/isabelle/decltypeme-cs511", "path": "github-repos/isabelle/decltypeme-cs511/cs511-be4f4ba351ff94ac35316c1228c0242e1c3449d0/HW07_solution.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.9086179025005187, "lm_q1q2_score": 0.7758804145054211}}
{"text": "(*  Title:      HOL/Lattice/Lattice.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection {* Lattices *}\n\ntheory Lattice imports Bounds begin\n\nsubsection {* Lattice operations *}\n\ntext {*\n  A \\emph{lattice} is a partial order with infimum and supremum of any\n  two elements (thus any \\emph{finite} number of elements have bounds\n  as well).\n*}\n\nclass lattice =\n  assumes ex_inf: \"\\<exists>inf. is_inf x y inf\"\n  assumes ex_sup: \"\\<exists>sup. is_sup x y sup\"\n\ntext {*\n  The @{text \\<sqinter>} (meet) and @{text \\<squnion>} (join) operations select such\n  infimum and supremum elements.\n*}\n\ndefinition\n  meet :: \"'a::lattice \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"&&\" 70) where\n  \"x && y = (THE inf. is_inf x y inf)\"\ndefinition\n  join :: \"'a::lattice \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixl \"||\" 65) where\n  \"x || y = (THE sup. is_sup x y sup)\"\n\nnotation (xsymbols)\n  meet  (infixl \"\\<sqinter>\" 70) and\n  join  (infixl \"\\<squnion>\" 65)\n\ntext {*\n  Due to unique existence of bounds, the lattice operations may be\n  exhibited as follows.\n*}\n\nlemma meet_equality [elim?]: \"is_inf x y inf \\<Longrightarrow> x \\<sqinter> y = inf\"\nproof (unfold meet_def)\n  assume \"is_inf x y inf\"\n  then show \"(THE inf. is_inf x y inf) = inf\"\n    by (rule the_equality) (rule is_inf_uniq [OF _ `is_inf x y inf`])\nqed\n\nlemma meetI [intro?]:\n    \"inf \\<sqsubseteq> x \\<Longrightarrow> inf \\<sqsubseteq> y \\<Longrightarrow> (\\<And>z. z \\<sqsubseteq> x \\<Longrightarrow> z \\<sqsubseteq> y \\<Longrightarrow> z \\<sqsubseteq> inf) \\<Longrightarrow> x \\<sqinter> y = inf\"\n  by (rule meet_equality, rule is_infI) blast+\n\nlemma join_equality [elim?]: \"is_sup x y sup \\<Longrightarrow> x \\<squnion> y = sup\"\nproof (unfold join_def)\n  assume \"is_sup x y sup\"\n  then show \"(THE sup. is_sup x y sup) = sup\"\n    by (rule the_equality) (rule is_sup_uniq [OF _ `is_sup x y sup`])\nqed\n\nlemma joinI [intro?]: \"x \\<sqsubseteq> sup \\<Longrightarrow> y \\<sqsubseteq> sup \\<Longrightarrow>\n    (\\<And>z. x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> sup \\<sqsubseteq> z) \\<Longrightarrow> x \\<squnion> y = sup\"\n  by (rule join_equality, rule is_supI) blast+\n\n\ntext {*\n  \\medskip The @{text \\<sqinter>} and @{text \\<squnion>} operations indeed determine\n  bounds on a lattice structure.\n*}\n\nlemma is_inf_meet [intro?]: \"is_inf x y (x \\<sqinter> y)\"\nproof (unfold meet_def)\n  from ex_inf obtain inf where \"is_inf x y inf\" ..\n  then show \"is_inf x y (THE inf. is_inf x y inf)\"\n    by (rule theI) (rule is_inf_uniq [OF _ `is_inf x y inf`])\nqed\n\nlemma meet_greatest [intro?]: \"z \\<sqsubseteq> x \\<Longrightarrow> z \\<sqsubseteq> y \\<Longrightarrow> z \\<sqsubseteq> x \\<sqinter> y\"\n  by (rule is_inf_greatest) (rule is_inf_meet)\n\nlemma meet_lower1 [intro?]: \"x \\<sqinter> y \\<sqsubseteq> x\"\n  by (rule is_inf_lower) (rule is_inf_meet)\n\nlemma meet_lower2 [intro?]: \"x \\<sqinter> y \\<sqsubseteq> y\"\n  by (rule is_inf_lower) (rule is_inf_meet)\n\n\nlemma is_sup_join [intro?]: \"is_sup x y (x \\<squnion> y)\"\nproof (unfold join_def)\n  from ex_sup obtain sup where \"is_sup x y sup\" ..\n  then show \"is_sup x y (THE sup. is_sup x y sup)\"\n    by (rule theI) (rule is_sup_uniq [OF _ `is_sup x y sup`])\nqed\n\nlemma join_least [intro?]: \"x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<squnion> y \\<sqsubseteq> z\"\n  by (rule is_sup_least) (rule is_sup_join)\n\nlemma join_upper1 [intro?]: \"x \\<sqsubseteq> x \\<squnion> y\"\n  by (rule is_sup_upper) (rule is_sup_join)\n\nlemma join_upper2 [intro?]: \"y \\<sqsubseteq> x \\<squnion> y\"\n  by (rule is_sup_upper) (rule is_sup_join)\n\n\nsubsection {* Duality *}\n\ntext {*\n  The class of lattices is closed under formation of dual structures.\n  This means that for any theorem of lattice theory, the dualized\n  statement holds as well; this important fact simplifies many proofs\n  of lattice theory.\n*}\n\ninstance dual :: (lattice) lattice\nproof\n  fix x' y' :: \"'a::lattice dual\"\n  show \"\\<exists>inf'. is_inf x' y' inf'\"\n  proof -\n    have \"\\<exists>sup. is_sup (undual x') (undual y') sup\" by (rule ex_sup)\n    then have \"\\<exists>sup. is_inf (dual (undual x')) (dual (undual y')) (dual sup)\"\n      by (simp only: dual_inf)\n    then show ?thesis by (simp add: dual_ex [symmetric])\n  qed\n  show \"\\<exists>sup'. is_sup x' y' sup'\"\n  proof -\n    have \"\\<exists>inf. is_inf (undual x') (undual y') inf\" by (rule ex_inf)\n    then have \"\\<exists>inf. is_sup (dual (undual x')) (dual (undual y')) (dual inf)\"\n      by (simp only: dual_sup)\n    then show ?thesis by (simp add: dual_ex [symmetric])\n  qed\nqed\n\ntext {*\n  Apparently, the @{text \\<sqinter>} and @{text \\<squnion>} operations are dual to each\n  other.\n*}\n\ntheorem dual_meet [intro?]: \"dual (x \\<sqinter> y) = dual x \\<squnion> dual y\"\nproof -\n  from is_inf_meet have \"is_sup (dual x) (dual y) (dual (x \\<sqinter> y))\" ..\n  then have \"dual x \\<squnion> dual y = dual (x \\<sqinter> y)\" ..\n  then show ?thesis ..\nqed\n\ntheorem dual_join [intro?]: \"dual (x \\<squnion> y) = dual x \\<sqinter> dual y\"\nproof -\n  from is_sup_join have \"is_inf (dual x) (dual y) (dual (x \\<squnion> y))\" ..\n  then have \"dual x \\<sqinter> dual y = dual (x \\<squnion> y)\" ..\n  then show ?thesis ..\nqed\n\n\nsubsection {* Algebraic properties \\label{sec:lattice-algebra} *}\n\ntext {*\n  The @{text \\<sqinter>} and @{text \\<squnion>} operations have the following\n  characteristic algebraic properties: associative (A), commutative\n  (C), and absorptive (AB).\n*}\n\ntheorem meet_assoc: \"(x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\nproof\n  show \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> x \\<sqinter> y\"\n  proof\n    show \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> x\" ..\n    show \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> y\"\n    proof -\n      have \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> y \\<sqinter> z\" ..\n      also have \"\\<dots> \\<sqsubseteq> y\" ..\n      finally show ?thesis .\n    qed\n  qed\n  show \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> z\"\n  proof -\n    have \"x \\<sqinter> (y \\<sqinter> z) \\<sqsubseteq> y \\<sqinter> z\" ..\n    also have \"\\<dots> \\<sqsubseteq> z\" ..\n    finally show ?thesis .\n  qed\n  fix w assume \"w \\<sqsubseteq> x \\<sqinter> y\" and \"w \\<sqsubseteq> z\"\n  show \"w \\<sqsubseteq> x \\<sqinter> (y \\<sqinter> z)\"\n  proof\n    show \"w \\<sqsubseteq> x\"\n    proof -\n      have \"w \\<sqsubseteq> x \\<sqinter> y\" by fact\n      also have \"\\<dots> \\<sqsubseteq> x\" ..\n      finally show ?thesis .\n    qed\n    show \"w \\<sqsubseteq> y \\<sqinter> z\"\n    proof\n      show \"w \\<sqsubseteq> y\"\n      proof -\n        have \"w \\<sqsubseteq> x \\<sqinter> y\" by fact\n        also have \"\\<dots> \\<sqsubseteq> y\" ..\n        finally show ?thesis .\n      qed\n      show \"w \\<sqsubseteq> z\" by fact\n    qed\n  qed\nqed\n\ntheorem join_assoc: \"(x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\nproof -\n  have \"dual ((x \\<squnion> y) \\<squnion> z) = (dual x \\<sqinter> dual y) \\<sqinter> dual z\"\n    by (simp only: dual_join)\n  also have \"\\<dots> = dual x \\<sqinter> (dual y \\<sqinter> dual z)\"\n    by (rule meet_assoc)\n  also have \"\\<dots> = dual (x \\<squnion> (y \\<squnion> z))\"\n    by (simp only: dual_join)\n  finally show ?thesis ..\nqed\n\ntheorem meet_commute: \"x \\<sqinter> y = y \\<sqinter> x\"\nproof\n  show \"y \\<sqinter> x \\<sqsubseteq> x\" ..\n  show \"y \\<sqinter> x \\<sqsubseteq> y\" ..\n  fix z assume \"z \\<sqsubseteq> y\" and \"z \\<sqsubseteq> x\"\n  then show \"z \\<sqsubseteq> y \\<sqinter> x\" ..\nqed\n\ntheorem join_commute: \"x \\<squnion> y = y \\<squnion> x\"\nproof -\n  have \"dual (x \\<squnion> y) = dual x \\<sqinter> dual y\" ..\n  also have \"\\<dots> = dual y \\<sqinter> dual x\"\n    by (rule meet_commute)\n  also have \"\\<dots> = dual (y \\<squnion> x)\"\n    by (simp only: dual_join)\n  finally show ?thesis ..\nqed\n\ntheorem meet_join_absorb: \"x \\<sqinter> (x \\<squnion> y) = x\"\nproof\n  show \"x \\<sqsubseteq> x\" ..\n  show \"x \\<sqsubseteq> x \\<squnion> y\" ..\n  fix z assume \"z \\<sqsubseteq> x\" and \"z \\<sqsubseteq> x \\<squnion> y\"\n  show \"z \\<sqsubseteq> x\" by fact\nqed\n\ntheorem join_meet_absorb: \"x \\<squnion> (x \\<sqinter> y) = x\"\nproof -\n  have \"dual x \\<sqinter> (dual x \\<squnion> dual y) = dual x\"\n    by (rule meet_join_absorb)\n  then have \"dual (x \\<squnion> (x \\<sqinter> y)) = dual x\"\n    by (simp only: dual_meet dual_join)\n  then show ?thesis ..\nqed\n\ntext {*\n  \\medskip Some further algebraic properties hold as well.  The\n  property idempotent (I) is a basic algebraic consequence of (AB).\n*}\n\ntheorem meet_idem: \"x \\<sqinter> x = x\"\nproof -\n  have \"x \\<sqinter> (x \\<squnion> (x \\<sqinter> x)) = x\" by (rule meet_join_absorb)\n  also have \"x \\<squnion> (x \\<sqinter> x) = x\" by (rule join_meet_absorb)\n  finally show ?thesis .\nqed\n\ntheorem join_idem: \"x \\<squnion> x = x\"\nproof -\n  have \"dual x \\<sqinter> dual x = dual x\"\n    by (rule meet_idem)\n  then have \"dual (x \\<squnion> x) = dual x\"\n    by (simp only: dual_join)\n  then show ?thesis ..\nqed\n\ntext {*\n  Meet and join are trivial for related elements.\n*}\n\ntheorem meet_related [elim?]: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<sqinter> y = x\"\nproof\n  assume \"x \\<sqsubseteq> y\"\n  show \"x \\<sqsubseteq> x\" ..\n  show \"x \\<sqsubseteq> y\" by fact\n  fix z assume \"z \\<sqsubseteq> x\" and \"z \\<sqsubseteq> y\"\n  show \"z \\<sqsubseteq> x\" by fact\nqed\n\ntheorem join_related [elim?]: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<squnion> y = y\"\nproof -\n  assume \"x \\<sqsubseteq> y\" then have \"dual y \\<sqsubseteq> dual x\" ..\n  then have \"dual y \\<sqinter> dual x = dual y\" by (rule meet_related)\n  also have \"dual y \\<sqinter> dual x = dual (y \\<squnion> x)\" by (simp only: dual_join)\n  also have \"y \\<squnion> x = x \\<squnion> y\" by (rule join_commute)\n  finally show ?thesis ..\nqed\n\n\nsubsection {* Order versus algebraic structure *}\n\ntext {*\n  The @{text \\<sqinter>} and @{text \\<squnion>} operations are connected with the\n  underlying @{text \\<sqsubseteq>} relation in a canonical manner.\n*}\n\ntheorem meet_connection: \"(x \\<sqsubseteq> y) = (x \\<sqinter> y = x)\"\nproof\n  assume \"x \\<sqsubseteq> y\"\n  then have \"is_inf x y x\" ..\n  then show \"x \\<sqinter> y = x\" ..\nnext\n  have \"x \\<sqinter> y \\<sqsubseteq> y\" ..\n  also assume \"x \\<sqinter> y = x\"\n  finally show \"x \\<sqsubseteq> y\" .\nqed\n\ntheorem join_connection: \"(x \\<sqsubseteq> y) = (x \\<squnion> y = y)\"\nproof\n  assume \"x \\<sqsubseteq> y\"\n  then have \"is_sup x y y\" ..\n  then show \"x \\<squnion> y = y\" ..\nnext\n  have \"x \\<sqsubseteq> x \\<squnion> y\" ..\n  also assume \"x \\<squnion> y = y\"\n  finally show \"x \\<sqsubseteq> y\" .\nqed\n\ntext {*\n  \\medskip The most fundamental result of the meta-theory of lattices\n  is as follows (we do not prove it here).\n\n  Given a structure with binary operations @{text \\<sqinter>} and @{text \\<squnion>}\n  such that (A), (C), and (AB) hold (cf.\\\n  \\S\\ref{sec:lattice-algebra}).  This structure represents a lattice,\n  if the relation @{term \"x \\<sqsubseteq> y\"} is defined as @{term \"x \\<sqinter> y = x\"}\n  (alternatively as @{term \"x \\<squnion> y = y\"}).  Furthermore, infimum and\n  supremum with respect to this ordering coincide with the original\n  @{text \\<sqinter>} and @{text \\<squnion>} operations.\n*}\n\n\nsubsection {* Example instances *}\n\nsubsubsection {* Linear orders *}\n\ntext {*\n  Linear orders with @{term minimum} and @{term maximum} operations\n  are a (degenerate) example of lattice structures.\n*}\n\ndefinition\n  minimum :: \"'a::linear_order \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"minimum x y = (if x \\<sqsubseteq> y then x else y)\"\ndefinition\n  maximum :: \"'a::linear_order \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"maximum x y = (if x \\<sqsubseteq> y then y else x)\"\n\nlemma is_inf_minimum: \"is_inf x y (minimum x y)\"\nproof\n  let ?min = \"minimum x y\"\n  from leq_linear show \"?min \\<sqsubseteq> x\" by (auto simp add: minimum_def)\n  from leq_linear show \"?min \\<sqsubseteq> y\" by (auto simp add: minimum_def)\n  fix z assume \"z \\<sqsubseteq> x\" and \"z \\<sqsubseteq> y\"\n  with leq_linear show \"z \\<sqsubseteq> ?min\" by (auto simp add: minimum_def)\nqed\n\nlemma is_sup_maximum: \"is_sup x y (maximum x y)\"      (* FIXME dualize!? *)\nproof\n  let ?max = \"maximum x y\"\n  from leq_linear show \"x \\<sqsubseteq> ?max\" by (auto simp add: maximum_def)\n  from leq_linear show \"y \\<sqsubseteq> ?max\" by (auto simp add: maximum_def)\n  fix z assume \"x \\<sqsubseteq> z\" and \"y \\<sqsubseteq> z\"\n  with leq_linear show \"?max \\<sqsubseteq> z\" by (auto simp add: maximum_def)\nqed\n\ninstance linear_order \\<subseteq> lattice\nproof\n  fix x y :: \"'a::linear_order\"\n  from is_inf_minimum show \"\\<exists>inf. is_inf x y inf\" ..\n  from is_sup_maximum show \"\\<exists>sup. is_sup x y sup\" ..\nqed\n\ntext {*\n  The lattice operations on linear orders indeed coincide with @{term\n  minimum} and @{term maximum}.\n*}\n\ntheorem meet_mimimum: \"x \\<sqinter> y = minimum x y\"\n  by (rule meet_equality) (rule is_inf_minimum)\n\ntheorem meet_maximum: \"x \\<squnion> y = maximum x y\"\n  by (rule join_equality) (rule is_sup_maximum)\n\n\n\nsubsubsection {* Binary products *}\n\ntext {*\n  The class of lattices is closed under direct binary products (cf.\\\n  \\S\\ref{sec:prod-order}).\n*}\n\nlemma is_inf_prod: \"is_inf p q (fst p \\<sqinter> fst q, snd p \\<sqinter> snd q)\"\nproof\n  show \"(fst p \\<sqinter> fst q, snd p \\<sqinter> snd q) \\<sqsubseteq> p\"\n  proof -\n    have \"fst p \\<sqinter> fst q \\<sqsubseteq> fst p\" ..\n    moreover have \"snd p \\<sqinter> snd q \\<sqsubseteq> snd p\" ..\n    ultimately show ?thesis by (simp add: leq_prod_def)\n  qed\n  show \"(fst p \\<sqinter> fst q, snd p \\<sqinter> snd q) \\<sqsubseteq> q\"\n  proof -\n    have \"fst p \\<sqinter> fst q \\<sqsubseteq> fst q\" ..\n    moreover have \"snd p \\<sqinter> snd q \\<sqsubseteq> snd q\" ..\n    ultimately show ?thesis by (simp add: leq_prod_def)\n  qed\n  fix r assume rp: \"r \\<sqsubseteq> p\" and rq: \"r \\<sqsubseteq> q\"\n  show \"r \\<sqsubseteq> (fst p \\<sqinter> fst q, snd p \\<sqinter> snd q)\"\n  proof -\n    have \"fst r \\<sqsubseteq> fst p \\<sqinter> fst q\"\n    proof\n      from rp show \"fst r \\<sqsubseteq> fst p\" by (simp add: leq_prod_def)\n      from rq show \"fst r \\<sqsubseteq> fst q\" by (simp add: leq_prod_def)\n    qed\n    moreover have \"snd r \\<sqsubseteq> snd p \\<sqinter> snd q\"\n    proof\n      from rp show \"snd r \\<sqsubseteq> snd p\" by (simp add: leq_prod_def)\n      from rq show \"snd r \\<sqsubseteq> snd q\" by (simp add: leq_prod_def)\n    qed\n    ultimately show ?thesis by (simp add: leq_prod_def)\n  qed\nqed\n\nlemma is_sup_prod: \"is_sup p q (fst p \\<squnion> fst q, snd p \\<squnion> snd q)\"  (* FIXME dualize!? *)\nproof\n  show \"p \\<sqsubseteq> (fst p \\<squnion> fst q, snd p \\<squnion> snd q)\"\n  proof -\n    have \"fst p \\<sqsubseteq> fst p \\<squnion> fst q\" ..\n    moreover have \"snd p \\<sqsubseteq> snd p \\<squnion> snd q\" ..\n    ultimately show ?thesis by (simp add: leq_prod_def)\n  qed\n  show \"q \\<sqsubseteq> (fst p \\<squnion> fst q, snd p \\<squnion> snd q)\"\n  proof -\n    have \"fst q \\<sqsubseteq> fst p \\<squnion> fst q\" ..\n    moreover have \"snd q \\<sqsubseteq> snd p \\<squnion> snd q\" ..\n    ultimately show ?thesis by (simp add: leq_prod_def)\n  qed\n  fix r assume \"pr\": \"p \\<sqsubseteq> r\" and qr: \"q \\<sqsubseteq> r\"\n  show \"(fst p \\<squnion> fst q, snd p \\<squnion> snd q) \\<sqsubseteq> r\"\n  proof -\n    have \"fst p \\<squnion> fst q \\<sqsubseteq> fst r\"\n    proof\n      from \"pr\" show \"fst p \\<sqsubseteq> fst r\" by (simp add: leq_prod_def)\n      from qr show \"fst q \\<sqsubseteq> fst r\" by (simp add: leq_prod_def)\n    qed\n    moreover have \"snd p \\<squnion> snd q \\<sqsubseteq> snd r\"\n    proof\n      from \"pr\" show \"snd p \\<sqsubseteq> snd r\" by (simp add: leq_prod_def)\n      from qr show \"snd q \\<sqsubseteq> snd r\" by (simp add: leq_prod_def)\n    qed\n    ultimately show ?thesis by (simp add: leq_prod_def)\n  qed\nqed\n\ninstance prod :: (lattice, lattice) lattice\nproof\n  fix p q :: \"'a::lattice \\<times> 'b::lattice\"\n  from is_inf_prod show \"\\<exists>inf. is_inf p q inf\" ..\n  from is_sup_prod show \"\\<exists>sup. is_sup p q sup\" ..\nqed\n\ntext {*\n  The lattice operations on a binary product structure indeed coincide\n  with the products of the original ones.\n*}\n\ntheorem meet_prod: \"p \\<sqinter> q = (fst p \\<sqinter> fst q, snd p \\<sqinter> snd q)\"\n  by (rule meet_equality) (rule is_inf_prod)\n\ntheorem join_prod: \"p \\<squnion> q = (fst p \\<squnion> fst q, snd p \\<squnion> snd q)\"\n  by (rule join_equality) (rule is_sup_prod)\n\n\nsubsubsection {* General products *}\n\ntext {*\n  The class of lattices is closed under general products (function\n  spaces) as well (cf.\\ \\S\\ref{sec:fun-order}).\n*}\n\nlemma is_inf_fun: \"is_inf f g (\\<lambda>x. f x \\<sqinter> g x)\"\nproof\n  show \"(\\<lambda>x. f x \\<sqinter> g x) \\<sqsubseteq> f\"\n  proof\n    fix x show \"f x \\<sqinter> g x \\<sqsubseteq> f x\" ..\n  qed\n  show \"(\\<lambda>x. f x \\<sqinter> g x) \\<sqsubseteq> g\"\n  proof\n    fix x show \"f x \\<sqinter> g x \\<sqsubseteq> g x\" ..\n  qed\n  fix h assume hf: \"h \\<sqsubseteq> f\" and hg: \"h \\<sqsubseteq> g\"\n  show \"h \\<sqsubseteq> (\\<lambda>x. f x \\<sqinter> g x)\"\n  proof\n    fix x\n    show \"h x \\<sqsubseteq> f x \\<sqinter> g x\"\n    proof\n      from hf show \"h x \\<sqsubseteq> f x\" ..\n      from hg show \"h x \\<sqsubseteq> g x\" ..\n    qed\n  qed\nqed\n\nlemma is_sup_fun: \"is_sup f g (\\<lambda>x. f x \\<squnion> g x)\"   (* FIXME dualize!? *)\nproof\n  show \"f \\<sqsubseteq> (\\<lambda>x. f x \\<squnion> g x)\"\n  proof\n    fix x show \"f x \\<sqsubseteq> f x \\<squnion> g x\" ..\n  qed\n  show \"g \\<sqsubseteq> (\\<lambda>x. f x \\<squnion> g x)\"\n  proof\n    fix x show \"g x \\<sqsubseteq> f x \\<squnion> g x\" ..\n  qed\n  fix h assume fh: \"f \\<sqsubseteq> h\" and gh: \"g \\<sqsubseteq> h\"\n  show \"(\\<lambda>x. f x \\<squnion> g x) \\<sqsubseteq> h\"\n  proof\n    fix x\n    show \"f x \\<squnion> g x \\<sqsubseteq> h x\"\n    proof\n      from fh show \"f x \\<sqsubseteq> h x\" ..\n      from gh show \"g x \\<sqsubseteq> h x\" ..\n    qed\n  qed\nqed\n\ninstance \"fun\" :: (type, lattice) lattice\nproof\n  fix f g :: \"'a \\<Rightarrow> 'b::lattice\"\n  show \"\\<exists>inf. is_inf f g inf\" by rule (rule is_inf_fun) (* FIXME @{text \"from \\<dots> show \\<dots> ..\"} does not work!? unification incompleteness!? *)\n  show \"\\<exists>sup. is_sup f g sup\" by rule (rule is_sup_fun)\nqed\n\ntext {*\n  The lattice operations on a general product structure (function\n  space) indeed emerge by point-wise lifting of the original ones.\n*}\n\ntheorem meet_fun: \"f \\<sqinter> g = (\\<lambda>x. f x \\<sqinter> g x)\"\n  by (rule meet_equality) (rule is_inf_fun)\n\ntheorem join_fun: \"f \\<squnion> g = (\\<lambda>x. f x \\<squnion> g x)\"\n  by (rule join_equality) (rule is_sup_fun)\n\n\nsubsection {* Monotonicity and semi-morphisms *}\n\ntext {*\n  The lattice operations are monotone in both argument positions.  In\n  fact, monotonicity of the second position is trivial due to\n  commutativity.\n*}\n\ntheorem meet_mono: \"x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> w \\<Longrightarrow> x \\<sqinter> y \\<sqsubseteq> z \\<sqinter> w\"\nproof -\n  {\n    fix a b c :: \"'a::lattice\"\n    assume \"a \\<sqsubseteq> c\" have \"a \\<sqinter> b \\<sqsubseteq> c \\<sqinter> b\"\n    proof\n      have \"a \\<sqinter> b \\<sqsubseteq> a\" ..\n      also have \"\\<dots> \\<sqsubseteq> c\" by fact\n      finally show \"a \\<sqinter> b \\<sqsubseteq> c\" .\n      show \"a \\<sqinter> b \\<sqsubseteq> b\" ..\n    qed\n  } note this [elim?]\n  assume \"x \\<sqsubseteq> z\" then have \"x \\<sqinter> y \\<sqsubseteq> z \\<sqinter> y\" ..\n  also have \"\\<dots> = y \\<sqinter> z\" by (rule meet_commute)\n  also assume \"y \\<sqsubseteq> w\" then have \"y \\<sqinter> z \\<sqsubseteq> w \\<sqinter> z\" ..\n  also have \"\\<dots> = z \\<sqinter> w\" by (rule meet_commute)\n  finally show ?thesis .\nqed\n\ntheorem join_mono: \"x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> w \\<Longrightarrow> x \\<squnion> y \\<sqsubseteq> z \\<squnion> w\"\nproof -\n  assume \"x \\<sqsubseteq> z\" then have \"dual z \\<sqsubseteq> dual x\" ..\n  moreover assume \"y \\<sqsubseteq> w\" then have \"dual w \\<sqsubseteq> dual y\" ..\n  ultimately have \"dual z \\<sqinter> dual w \\<sqsubseteq> dual x \\<sqinter> dual y\"\n    by (rule meet_mono)\n  then have \"dual (z \\<squnion> w) \\<sqsubseteq> dual (x \\<squnion> y)\"\n    by (simp only: dual_join)\n  then show ?thesis ..\nqed\n\ntext {*\n  \\medskip A semi-morphisms is a function @{text f} that preserves the\n  lattice operations in the following manner: @{term \"f (x \\<sqinter> y) \\<sqsubseteq> f x\n  \\<sqinter> f y\"} and @{term \"f x \\<squnion> f y \\<sqsubseteq> f (x \\<squnion> y)\"}, respectively.  Any of\n  these properties is equivalent with monotonicity.\n*}\n\ntheorem meet_semimorph:\n  \"(\\<And>x y. f (x \\<sqinter> y) \\<sqsubseteq> f x \\<sqinter> f y) \\<equiv> (\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y)\"\nproof\n  assume morph: \"\\<And>x y. f (x \\<sqinter> y) \\<sqsubseteq> f x \\<sqinter> f y\"\n  fix x y :: \"'a::lattice\"\n  assume \"x \\<sqsubseteq> y\"\n  then have \"x \\<sqinter> y = x\" ..\n  then have \"x = x \\<sqinter> y\" ..\n  also have \"f \\<dots> \\<sqsubseteq> f x \\<sqinter> f y\" by (rule morph)\n  also have \"\\<dots> \\<sqsubseteq> f y\" ..\n  finally show \"f x \\<sqsubseteq> f y\" .\nnext\n  assume mono: \"\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\"\n  show \"\\<And>x y. f (x \\<sqinter> y) \\<sqsubseteq> f x \\<sqinter> f y\"\n  proof -\n    fix x y\n    show \"f (x \\<sqinter> y) \\<sqsubseteq> f x \\<sqinter> f y\"\n    proof\n      have \"x \\<sqinter> y \\<sqsubseteq> x\" .. then show \"f (x \\<sqinter> y) \\<sqsubseteq> f x\" by (rule mono)\n      have \"x \\<sqinter> y \\<sqsubseteq> y\" .. then show \"f (x \\<sqinter> y) \\<sqsubseteq> f y\" by (rule mono)\n    qed\n  qed\nqed\n\nlemma join_semimorph:\n  \"(\\<And>x y. f x \\<squnion> f y \\<sqsubseteq> f (x \\<squnion> y)) \\<equiv> (\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y)\"\nproof\n  assume morph: \"\\<And>x y. f x \\<squnion> f y \\<sqsubseteq> f (x \\<squnion> y)\"\n  fix x y :: \"'a::lattice\"\n  assume \"x \\<sqsubseteq> y\" then have \"x \\<squnion> y = y\" ..\n  have \"f x \\<sqsubseteq> f x \\<squnion> f y\" ..\n  also have \"\\<dots> \\<sqsubseteq> f (x \\<squnion> y)\" by (rule morph)\n  also from `x \\<sqsubseteq> y` have \"x \\<squnion> y = y\" ..\n  finally show \"f x \\<sqsubseteq> f y\" .\nnext\n  assume mono: \"\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\"\n  show \"\\<And>x y. f x \\<squnion> f y \\<sqsubseteq> f (x \\<squnion> y)\"\n  proof -\n    fix x y\n    show \"f x \\<squnion> f y \\<sqsubseteq> f (x \\<squnion> y)\"\n    proof\n      have \"x \\<sqsubseteq> x \\<squnion> y\" .. then show \"f x \\<sqsubseteq> f (x \\<squnion> y)\" by (rule mono)\n      have \"y \\<sqsubseteq> x \\<squnion> y\" .. then show \"f y \\<sqsubseteq> f (x \\<squnion> y)\" by (rule mono)\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Lattice/Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8539127492339907, "lm_q1q2_score": 0.7758804084861504}}
{"text": "(*  Title:      Open Induction\n    Author:     Mizuhito Ogawa\n                Christian Sternagel <c.sternagel@gmail.com>\n    Maintainer: Christian Sternagel\n    License:    LGPL\n*)\n\nsection \\<open>Open Induction\\<close>\n\ntheory Open_Induction\nimports Restricted_Predicates\nbegin\n\nsubsection \\<open>(Greatest) Lower Bounds and Chains\\<close>\n\ntext \\<open>\n  A set \\<open>B\\<close> has the \\emph{lower bound} \\<open>x\\<close> iff \\<open>x\\<close> is\n  less than or equal to every element of \\<open>B\\<close>.\n\\<close>\ndefinition \"lb P B x \\<longleftrightarrow> (\\<forall>y\\<in>B. P\\<^sup>=\\<^sup>= x y)\"\n\nlemma lbI [Pure.intro]:\n  \"(\\<And>y. y \\<in> B \\<Longrightarrow> P\\<^sup>=\\<^sup>= x y) \\<Longrightarrow> lb P B x\"\nby (auto simp: lb_def)\n\ntext \\<open>\n  A set \\<open>B\\<close> has the \\emph{greatest lower bound} \\<open>x\\<close> iff \\<open>x\\<close> is\n  a lower bound of \\<open>B\\<close> \\emph{and} less than or equal to every\n  other lower bound of \\<open>B\\<close>.\n\\<close>\ndefinition \"glb P B x \\<longleftrightarrow> lb P B x \\<and> (\\<forall>y. lb P B y \\<longrightarrow> P\\<^sup>=\\<^sup>= y x)\"\n\nlemma glbI [Pure.intro]:\n  \"lb P B x \\<Longrightarrow> (\\<And>y. lb P B y \\<Longrightarrow> P\\<^sup>=\\<^sup>= y x) \\<Longrightarrow> glb P B x\"\nby (auto simp: glb_def)\n\ntext \\<open>Antisymmetric relations have unique glbs.\\<close>\nlemma glb_unique:\n  \"antisymp_on P A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> glb P B x \\<Longrightarrow> glb P B y \\<Longrightarrow> x = y\"\nby (auto simp: glb_def antisymp_on_def)\n\ncontext pred_on\nbegin\n\nlemma chain_glb:\n  assumes \"transp_on (\\<sqsubset>) A\"\n  shows \"chain C \\<Longrightarrow> glb (\\<sqsubset>) C x \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> y \\<sqsubset> x \\<Longrightarrow> chain ({y} \\<union> C)\"\nusing assms [unfolded transp_on_def]\nunfolding chain_def glb_def lb_def\nby (cases \"C = {}\") blast+\n\n\nsubsection \\<open>Open Properties\\<close>\n\ndefinition \"open Q \\<longleftrightarrow> (\\<forall>C. chain C \\<and> C \\<noteq> {} \\<and> (\\<exists>x\\<in>A. glb (\\<sqsubset>) C x \\<and> Q x) \\<longrightarrow> (\\<exists>y\\<in>C. Q y))\"\n\nlemma openI [Pure.intro]:\n  \"(\\<And>C. chain C \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> \\<exists>x\\<in>A. glb (\\<sqsubset>) C x \\<and> Q x \\<Longrightarrow> \\<exists>y\\<in>C. Q y) \\<Longrightarrow> open Q\"\nby (auto simp: open_def)\n\nlemma open_glb:\n  \"\\<lbrakk>chain C; C \\<noteq> {}; open Q; \\<forall>x\\<in>C. \\<not> Q x; x \\<in> A; glb (\\<sqsubset>) C x\\<rbrakk> \\<Longrightarrow> \\<not> Q x\"\nby (auto simp: open_def)\n\n\nsubsection \\<open>Downward Completeness\\<close>\n\ntext \\<open>\n  A relation \\<open>\\<sqsubset>\\<close> is \\emph{downward-complete} iff\n  every non-empty \\<open>\\<sqsubset>\\<close>-chain has a greatest lower bound.\n\\<close>\ndefinition \"downward_complete \\<longleftrightarrow> (\\<forall>C. chain C \\<and> C \\<noteq> {} \\<longrightarrow> (\\<exists>x\\<in>A. glb (\\<sqsubset>) C x))\"\n\nlemma downward_completeI [Pure.intro]:\n  assumes \"\\<And>C. chain C \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> \\<exists>x\\<in>A. glb (\\<sqsubset>) C x\"\n  shows \"downward_complete\"\nusing assms by (auto simp: downward_complete_def)\n\nend\n\nabbreviation \"open_on P Q A \\<equiv> pred_on.open A P Q\"\nabbreviation \"dc_on P A \\<equiv> pred_on.downward_complete A P\"\nlemmas open_on_def = pred_on.open_def\n  and dc_on_def = pred_on.downward_complete_def\n\nlemma dc_onI [Pure.intro]:\n  assumes \"\\<And>C. chain_on P C A \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> \\<exists>x\\<in>A. glb P C x\"\n  shows \"dc_on P A\"\nusing assms by (auto simp: dc_on_def)\n\nlemma open_onI [Pure.intro]:\n  \"(\\<And>C. chain_on P C A \\<Longrightarrow> C \\<noteq> {} \\<Longrightarrow> \\<exists>x\\<in>A. glb P C x \\<and> Q x \\<Longrightarrow> \\<exists>y\\<in>C. Q y) \\<Longrightarrow> open_on P Q A\"\nby (auto simp: open_on_def)\n\nlemma chain_on_reflclp:\n  \"chain_on P\\<^sup>=\\<^sup>= A C \\<longleftrightarrow> chain_on P A C\"\nby (auto simp: pred_on.chain_def)\n\nlemma lb_reflclp:\n  \"lb P\\<^sup>=\\<^sup>= B x \\<longleftrightarrow> lb P B x\"\nby (auto simp: lb_def)\n\nlemma glb_reflclp:\n  \"glb P\\<^sup>=\\<^sup>= B x \\<longleftrightarrow> glb P B x\"\nby (auto simp: glb_def lb_reflclp)\n\nlemma dc_on_reflclp:\n  \"dc_on P\\<^sup>=\\<^sup>= A \\<longleftrightarrow> dc_on P A\"\nby (auto simp: dc_on_def chain_on_reflclp glb_reflclp)\n\n\nsubsection \\<open>The Open Induction Principle\\<close>\n\nlemma open_induct_on [consumes 4, case_names less]:\n  assumes qo: \"qo_on P A\" and \"dc_on P A\" and \"open_on P Q A\"\n    and \"x \\<in> A\"\n    and ind: \"\\<And>x. \\<lbrakk>x \\<in> A; \\<And>y. \\<lbrakk>y \\<in> A; strict P y x\\<rbrakk> \\<Longrightarrow> Q y\\<rbrakk> \\<Longrightarrow> Q x\"\n  shows \"Q x\"\nproof (rule ccontr)\n  assume \"\\<not> Q x\"\n  let ?B = \"{x\\<in>A. \\<not> Q x}\"\n  have \"?B \\<subseteq> A\" by blast\n  interpret B: pred_on ?B P .\n  from B.Hausdorff obtain M\n    where chain: \"B.chain M\"\n    and max: \"\\<And>C. B.chain C \\<Longrightarrow> M \\<subseteq> C \\<Longrightarrow> M = C\" by (auto simp: B.maxchain_def)\n  then have \"M \\<subseteq> ?B\" by (auto simp: B.chain_def)\n  show False\n  proof (cases \"M = {}\")\n    assume \"M = {}\"\n    moreover have \"B.chain {x}\" using \\<open>x \\<in> A\\<close> and \\<open>\\<not> Q x\\<close> by (simp add: B.chain_def)\n    ultimately show False using max by blast\n  next\n    interpret A: pred_on A P .\n    assume \"M \\<noteq> {}\"\n    have \"A.chain M\" using chain by (auto simp: A.chain_def B.chain_def)\n    moreover with \\<open>dc_on P A\\<close> and \\<open>M \\<noteq> {}\\<close> obtain m\n      where \"m \\<in> A\" and \"glb P M m\" by (auto simp: A.downward_complete_def)\n    ultimately have \"\\<not> Q m\" and \"m \\<in> ?B\"\n      using A.open_glb [OF _ \\<open>M \\<noteq> {}\\<close> \\<open>open_on P Q A\\<close> _ _ \\<open>glb P M m\\<close>]\n      and \\<open>M \\<subseteq> ?B\\<close> by auto\n    from ind [OF \\<open>m \\<in> A\\<close>] and \\<open>\\<not> Q m\\<close> obtain y\n      where \"y \\<in> A\" and \"strict P y m\" and \"\\<not> Q y\" by blast\n    then have \"P y m\" and \"y \\<in> ?B\" by simp+\n    from transp_on_subset [OF \\<open>?B \\<subseteq> A\\<close> qo_on_imp_transp_on [OF qo]]\n      have \"transp_on P ?B\" .\n    from B.chain_glb [OF this chain \\<open>glb P M m\\<close> \\<open>m \\<in> ?B\\<close> \\<open>y \\<in> ?B\\<close> \\<open>P y m\\<close>]\n      have \"B.chain ({y} \\<union> M)\" .\n    then show False\n      using \\<open>glb P M m\\<close> and \\<open>strict P y m\\<close> by (cases \"y \\<in> M\") (auto dest: max simp: glb_def lb_def)\n  qed\nqed\n\n\nsubsection \\<open>Open Induction on Universal Domains\\<close>\n\ntext \\<open>Open induction on quasi-orders (i.e., @{class preorder}).\\<close>\nlemma (in preorder) dc_open_induct [consumes 2, case_names less]:\n  assumes \"dc_on (\\<le>) UNIV\"\n    and \"open_on (\\<le>) Q UNIV\"\n    and \"\\<And>x. (\\<And>y. y < x \\<Longrightarrow> Q y) \\<Longrightarrow> Q x\"\n  shows \"Q x\"\nproof -\n  have \"qo_on (\\<le>) UNIV\" by (auto simp: qo_on_def transp_on_def reflp_on_def dest: order_trans)\n  from open_induct_on [OF this assms(1,2)]\n    show \"Q x\" using assms(3) unfolding less_le_not_le by blast\nqed\n\n\nsubsection \\<open>Type Class of Downward Complete Orders\\<close>\n\nclass dcorder = preorder +\n  assumes dc_on_UNIV: \"dc_on (\\<le>) UNIV\"\nbegin\n\ntext \\<open>Open induction on downward-complete orders.\\<close>\nlemmas open_induct [consumes 1, case_names less] = dc_open_induct [OF dc_on_UNIV]\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Open_Induction/Open_Induction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.8539127455162773, "lm_q1q2_score": 0.7758804029951376}}
{"text": "section \\<open>Rank Annotated Tree\\<close>\n\ntheory RankAnnotatedTree\nimports Main\n\nbegin\n\nsubsection \\<open>Type definition and operations\\<close>\n\ndatatype 'a rtree = Leaf (\"\\<langle>/ \\<rangle>\")| Node \"'a rtree\" nat 'a \"'a rtree\" (\"(1\\<langle> _,/ _,/ _,/ _ \\<rangle>)\")\n\nfun num_nodes :: \"'a rtree \\<Rightarrow> nat\" where\n\"num_nodes \\<langle>\\<rangle> = 0\" |\n\"num_nodes \\<langle>l, _, _, r\\<rangle> = 1 + num_nodes l + num_nodes r\"\n\nvalue  \"num_nodes \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\"\n\nfun set_rtree :: \"'a rtree \\<Rightarrow> 'a set\" where\n  \"set_rtree \\<langle>\\<rangle> = {}\"\n| \"set_rtree \\<langle>l,n,x,r\\<rangle> = set_rtree l \\<union> set_rtree r \\<union> {x}\"\n\nfun rbst :: \"('a::linorder) rtree \\<Rightarrow> bool\" where\n\"rbst \\<langle>\\<rangle> = True\" |\n\"rbst \\<langle>l, n, x, r\\<rangle> = ((\\<forall>a \\<in> set_rtree l. a < x) \\<and> (\\<forall>a \\<in> set_rtree r. x < a) \\<and> rbst l \\<and> rbst r \\<and> n = num_nodes l)\"\n\nvalue \"rbst \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\"\nvalue \"rbst \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 2, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\"\n\nlemma set_rtree_rbst: \"rbst \\<langle>l, n, x, r\\<rangle> \\<Longrightarrow> a \\<in> set_rtree \\<langle>l, n, x, r\\<rangle> \\<Longrightarrow> a < x \\<Longrightarrow> a \\<in> set_rtree l\"\n  by force\n\nfun rins :: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> 'a rtree\" where\n\"rins a \\<langle>\\<rangle> = \\<langle>\\<langle>\\<rangle>, 0, a, \\<langle>\\<rangle>\\<rangle>\" |\n\"rins a \\<langle>l, n, x, r\\<rangle> = (if a \\<in> set_rtree \\<langle>l, n, x, r\\<rangle> then \\<langle>l, n, x, r\\<rangle>\n                      else if a < x then \\<langle>rins a l, n + 1, x, r\\<rangle>\n                      else \\<langle>l, n, x, rins a r\\<rangle>)\"\n\nvalue \"rins 9 \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<rangle>\\<rangle>\\<rangle>\"\n\nlemma rins_set[simp]: \"set_rtree (rins x t) = insert x (set_rtree t)\"\n  by (induction t arbitrary: x rule: set_rtree.induct) auto\n\nlemma num_nodes_rins_notin[simp]: \"x \\<notin> set_rtree t \\<Longrightarrow> rbst t \\<Longrightarrow> num_nodes (rins x t) = 1 + num_nodes t\"\n  by (induction t rule: rbst.induct) simp+\n\nlemma rins_invar[simp]: \"x \\<notin> set_rtree t \\<Longrightarrow> rbst t \\<Longrightarrow> rbst (rins x t)\"\nproof (induction t rule: rbst.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 l n a r)\n  then show ?case\n    by auto\nqed\n\nlemma rins_invar_in[simp]: \"x \\<in> set_rtree t \\<Longrightarrow> rbst t \\<Longrightarrow> rbst (rins x t)\"\n  using rbst.elims(2) by force\n\n\nsubsection \\<open>Inorder traversal and getting rank\\<close>\n\nfun inorder:: \"'a rtree \\<Rightarrow> 'a list\" where\n\"inorder \\<langle>\\<rangle> = []\" |\n\"inorder \\<langle>l, _, x, r\\<rangle> = inorder l  @ (x # inorder r)\"\n\nvalue  \"inorder \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\"\n\nfun rank:: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> nat\" where\n\"rank a \\<langle>\\<rangle> = 0\" |\n\"rank a \\<langle>l, n, x, r\\<rangle> = (if a = x then n\n                       else if a > x then 1 + n + rank a r\n                       else rank a l)\"\n\nvalue  \"rank 9 \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\"\n\ndefinition \"at_index i l x \\<equiv> i < length l \\<and> l!i=x\"\n\nlemma num_nodes_inorder[simp]: \"num_nodes t = length (inorder t)\"\n  by (induction t) simp+\n\nlemma set_rtree_inorder_in[simp]:\"x \\<in> set_rtree t \\<longleftrightarrow> x \\<in> set(inorder t)\"\n  by (induction t) auto\n\nlemma inorder_index: \"rbst t \\<Longrightarrow> a \\<in> set_rtree t \\<Longrightarrow> at_index (rank a t) (inorder t) a\"\nproof (induction t)\n  case Leaf\n  then show ?case by simp\nnext\n  case (Node l n x r)\n  then show ?case\n  proof (cases \"a = x\")\n    case True\n    hence \"rank a \\<langle>l, n, x, r\\<rangle> = n\"\n      by simp\n    have \"n = num_nodes l\"\n      using Node.prems(1) rbst.simps(2) by blast\n    then have \"... = length (inorder l)\"\n      by simp\n    then show ?thesis using True by (auto split: if_splits simp add: \\<open>n = num_nodes l\\<close> at_index_def)\n  next\n    case False\n    then show ?thesis\n    proof (cases \"a > x\")\n      case True\n      hence \"rank a \\<langle>l, n, x, r\\<rangle> = 1 + n + rank a r\"\n        using Node.prems(2) by auto\n      from True have \"a \\<in> set_rtree r\"\n        using Node.prems(1) Node.prems(2) order_less_imp_not_less by fastforce\n      then show ?thesis using True\n        apply (auto split: if_splits simp add: at_index_def)\n         apply (metis Node.IH(2) Node.prems(1) \\<open>a \\<in> set_rtree r\\<close> at_index_def nat_add_left_cancel_less num_nodes_inorder rbst.simps(2))\n        by (metis (no_types, lifting) Node.IH(2) Node.prems(1) \\<open>a \\<in> RankAnnotatedTree.set_rtree r\\<close> add_Suc_right add_diff_cancel_left' at_index_def not_add_less1 nth_Cons_Suc nth_append num_nodes_inorder rbst.simps(2))\n    next\n      case False\n      hence \"rank a \\<langle>l, n, x, r\\<rangle> = rank a l\" using \\<open>a \\<noteq> x\\<close>\n        using Node.prems(2) by auto\n      from False \\<open>a \\<noteq>x\\<close> have \"a \\<in> set_rtree l\"\n        by (meson Node.prems(1) Node.prems(2) antisym_conv3 set_rtree_rbst)\n      then show ?thesis using False \\<open>a \\<noteq> x\\<close>\n        apply (auto split: if_splits simp add: at_index_def)\n         apply (metis Node.IH(1) Node.prems(1) \\<open>a \\<in> RankAnnotatedTree.set_rtree l\\<close> at_index_def less_Suc_eq rbst.simps(2) trans_less_add1)\n        by (metis Node.IH(1) Node.prems(1) \\<open>a \\<in> RankAnnotatedTree.set_rtree l\\<close> at_index_def nth_append rbst.simps(2))\n    qed\n  qed\n\nqed\n\nsubsection \\<open>Selection in a rank annotated tree\\<close>\n\nfun sel:: \"nat \\<Rightarrow> 'a::linorder rtree \\<Rightarrow>'a\" where\n\"sel _ \\<langle>\\<rangle> = undefined\" |\n\"sel i \\<langle>l, n, x, r\\<rangle> = (if i = n then x\n                      else if i < n then sel i l\n                      else sel (i - n - 1) r)\"\n\nvalue  \"sel 5 \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\" \n\n\nlemma sel_in_set_rtree:\"\\<And> i. sel i t = a \\<Longrightarrow> a \\<noteq> undefined \\<Longrightarrow> a \\<in> set_rtree t\"\nproof(induction t)\n  case Leaf\n  then show ?case\n    by simp\nnext\n  case (Node l n x r)\n  then show ?case\n  proof (cases \"i = n\")\n    case True\n    then show ?thesis\n      using Node.prems(1) by auto\n  next\n    case False\n    then show ?thesis\n    proof (cases \"i<n\")\n      case True\n      hence \"sel i \\<langle>l, n, x, r\\<rangle> = sel i l\"\n        by simp\n      then show ?thesis using Node.IH\n        using Node.prems(1) Node.prems(2) by auto\n    next\n      case False\n      hence \"sel i \\<langle>l, n, x, r\\<rangle> = sel (i-n-1) r\" using \\<open>i\\<noteq>n\\<close>\n        by simp\n      then show ?thesis using \\<open>i\\<noteq>n\\<close>\n        using Node.IH(2) Node.prems(1) Node.prems(2) by auto\n    qed\n  qed\nqed\n\nlemma select_correct: \"rbst t \\<Longrightarrow> i < length (inorder t) \\<Longrightarrow> sel i t = inorder t!i\"\nproof (induction t arbitrary: i)\n  case Leaf\n  then show ?case\n    by simp\nnext\n  case (Node l n x r)\n  then show ?case\n  proof (cases \"i = n\")\n    case True\n    then show ?thesis\n      using Node.prems(1) by auto\n  next\n    case False\n    then show ?thesis\n    proof (cases \"i < n\")\n      case True\n      then show ?thesis\n        by (metis False Node.IH(1) Node.prems(1) inorder.simps(2) nth_append num_nodes_inorder rbst.simps(2) sel.simps(2))\n    next\n      case False\n      then have \"sel i \\<langle>l, n, x, r\\<rangle> = sel (i - n - 1) r\" using \\<open>i \\<noteq> n\\<close>\n        by simp\n      moreover have \"i - n - 1 < length (inorder r)\" using False \\<open>i \\<noteq> n\\<close>\n        using Node.prems(1) Node.prems(2) by force\n      moreover have \"sel (i - n - 1) r = inorder r ! (i - n - 1)\" using False \\<open>i \\<noteq> n\\<close> Node.IH\n        using Node.prems(1) calculation(2) rbst.simps(2) by blast\n      then show ?thesis using False \\<open>i \\<noteq> n\\<close>\n        by (metis Node.prems(1) antisym_conv3 calculation(1) inorder.simps(2) nth_Cons_pos nth_append num_nodes_inorder rbst.simps(2) zero_less_diff)\n    qed\n  qed\nqed\n\nlemma rank_sel_id: \"rbst t \\<Longrightarrow> i < length (inorder t) \\<Longrightarrow> rank (sel i t) t = i\"\nproof (induction t arbitrary: i)\n  case Leaf\n  then show ?case by simp\nnext\n  case (Node l n x r)\n  then show ?case using select_correct\n    apply auto\n       apply (simp add: order_less_not_sym select_correct)\n    by fastforce+\nqed\n\nlemma set_rtree_set_inorder_eq[simp]: \"rbst t \\<Longrightarrow> set_rtree t = set(inorder t)\"\n  by auto\n\nlemma card_set_rtree[simp]: \"rbst t \\<Longrightarrow> num_nodes t = card (set_rtree t)\"\nproof (induction t rule:rtree.induct)\n  case Leaf\n  then show ?case by simp\nnext\n  case (Node l n a r)\n  have a_not_in:\"a \\<notin> set_rtree l \\<and> a \\<notin> set_rtree r\"\n    by (metis Node.prems not_less_iff_gr_or_eq rbst.simps(2))\n  then show ?case using card_def Node.IH a_not_in apply auto\n    using Node.prems card_Un_disjoint by fastforce\nqed\n\n\n\nfun rmerge :: \"'a::linorder rtree \\<Rightarrow> 'a rtree \\<Rightarrow> 'a rtree\" where\n\"rmerge t \\<langle>\\<rangle> = t\" |\n\"rmerge t \\<langle>l, _, a, r\\<rangle> = rins a (rmerge (rmerge t r) l)\"\n\nlemma rmerge_inv[simp]: \"rbst u \\<Longrightarrow> rbst t \\<Longrightarrow> rbst (rmerge t u)\"\n  proof (induction u arbitrary: t rule: rmerge.induct)\n    case (1 t)\n    then show ?case by simp\n  next\n    case (2 t l n a r)\n    then show ?case using 2 apply auto\n      by (meson rins_invar rins_invar_in) \n  qed\n\nlemma rmerge_set[simp]: \"rbst u \\<Longrightarrow> rbst t \\<Longrightarrow> set_rtree (rmerge t u) = set_rtree t \\<union> set_rtree u\"\n  by (induction u arbitrary: t rule: rmerge.induct) auto\n\nlemma card_rmerge[simp]: \n  assumes \"rbst t\" and \"rbst u\"\n  shows \"card (set_rtree (rmerge t u)) = card (set_rtree t \\<union> set_rtree u)\"\nusing assms proof (induction u arbitrary: t rule:rtree.induct)\n  case Leaf\n  then show ?case by simp\nnext\n  case (Node l n x r)\n  then show ?case\n    by (cases \"x \\<in> set_rtree t\")(metis Node.prems(1) Node.prems(2) rmerge_set)+\nqed\n\nfun rdel :: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> 'a rtree\" where\n\"rdel x \\<langle>\\<rangle> = \\<langle>\\<rangle>\" |\n\"rdel x \\<langle>l, n, a, r\\<rangle> = (if x \\<in> set_rtree \\<langle>l, n, a, r\\<rangle> then\n  (if x < a then \\<langle>rdel x l, n-1, a, r\\<rangle> else\n    (if x > a then \\<langle>l, n, a, rdel x r\\<rangle> else\n      rmerge l r))\n  else \\<langle>l, n, a, r\\<rangle>)\"\n\nvalue  \"rdel 5 \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\" \nvalue  \"rdel 6 \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\" \nvalue  \"rdel 10 \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\n  = \\<langle>\\<langle>\\<langle>\\<langle>\\<rangle>, 0, 3, \\<langle>\\<rangle>\\<rangle> , 1, 4, \\<langle>\\<langle>\\<rangle>, 0, 5, \\<langle>\\<rangle>\\<rangle>\\<rangle>, 3, 6::nat, \\<langle>\\<langle>\\<langle>\\<rangle>, 0, 7,\\<langle>\\<rangle>\\<rangle>, 1, 8, \\<langle>\\<langle>\\<rangle>, 0, 9,\\<langle>\\<rangle>\\<rangle>\\<rangle>\\<rangle>\" \n\n\nlemma rdel_set[simp]:\"rbst t \\<Longrightarrow> set_rtree (rdel x t) = (set_rtree t) - {x}\"\nproof (induction t arbitrary: x rule:rtree.induct)\n  case Leaf\n  then show ?case by simp\nnext\n  case (Node l n a r)\n  then show ?case apply auto\n    apply fastforce\n    apply fastforce\n       apply (metis Un_iff rmerge_set  set_rtree_inorder_in)\n    apply (metis Un_iff not_less_iff_gr_or_eq rmerge_set set_rtree_inorder_in)\n    apply (metis Un_iff rmerge_set set_rtree_inorder_in)\n    by (metis Un_iff rmerge_set set_rtree_inorder_in)\nqed\n\n\nlemma rdel_inv: \"rbst t \\<Longrightarrow> rbst (rdel x t)\"\nproof (induct t rule: rtree.induct)\n  case Leaf\n  then show ?case by simp\nnext\n  case ind:(Node l n a r)\n  then show ?case\n  proof (cases \"x \\<in> set_rtree \\<langle>l, n, a, r\\<rangle>\")\n    case in_tree:True\n    then show ?thesis\n    proof (cases \"x = a\")\n      case True\n      then show ?thesis using ind rmerge_inv by auto\n    next\n      case x_neq_a:False\n      then show ?thesis\n      proof (cases \"x < a\")\n        case True\n        have \"rbst (rdel x l)\" using ind by simp\n        moreover have \"set_rtree (rdel x l) = set_rtree l - {x}\"\n          by (meson ind.prems rbst.simps(2) rdel_set)\n        moreover have x_in_l: \"x \\<in> set_rtree l\" using in_tree x_neq_a ind.prems True set_rtree_rbst\n          by blast\n        moreover have \"card (set_rtree l - {x}) = n - 1\"\n          by (metis card_Diff_singleton card_set_rtree ind.prems rbst.simps(2) x_in_l)\n        moreover have \"length (inorder (rdel x l)) = n - 1\" using ind rbst.simps x_in_l apply auto\n          by (metis One_nat_def calculation(4) card_set_rtree num_nodes_inorder rdel_set)\n        then show ?thesis using ind apply auto \n            apply (metis Diff_iff rdel_set set_rtree_set_inorder_eq)\n          using order.asym apply blast\n          using True by blast\n      next\n        case x_geq_a: False\n        have x_in_r: \"x \\<in> set_rtree r\" using ind in_tree x_neq_a x_geq_a by auto\n        then show ?thesis using ind in_tree x_in_r x_geq_a x_neq_a rbst.simps apply auto\n          by (metis Diff_iff rdel_set set_rtree_set_inorder_eq)\n      qed\n    qed\n  next\n    case False\n    then show ?thesis using ind by auto\n  qed\nqed\n\n\nend", "meta": {"author": "VTrelat", "repo": "SecureCoding", "sha": "9641a6cddc37d741f026562c4662ad95c7b82626", "save_path": "github-repos/isabelle/VTrelat-SecureCoding", "path": "github-repos/isabelle/VTrelat-SecureCoding/SecureCoding-9641a6cddc37d741f026562c4662ad95c7b82626/RankAnnotatedTree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.933430803622103, "lm_q2_score": 0.8311430541321951, "lm_q1q2_score": 0.775814528943544}}
{"text": "(*\n  File:     Indep_System.thy\n  Author:   Jonas Keinholz\n\nIndependence systems\n*)\nsection \\<open>Independence systems\\<close>\ntheory Indep_System\n  imports Main\nbegin\n\nlemma finite_psubset_inc_induct:\n  assumes \"finite A\" \"X \\<subseteq> A\"\n  assumes \"\\<And>X. (\\<And>Y. X \\<subset> Y \\<Longrightarrow> Y \\<subseteq> A \\<Longrightarrow> P Y) \\<Longrightarrow> P X\"\n  shows \"P X\"\nproof -\n  have wf: \"wf {(X,Y). Y \\<subset> X \\<and> X \\<subseteq> A}\"\n    by (rule wf_bounded_set[where ub = \"\\<lambda>_. A\" and f = id]) (auto simp add: \\<open>finite A\\<close>)\n  show ?thesis\n  proof (induction X rule: wf_induct[OF wf, case_names step])\n    case (step X)\n    then show ?case using assms(3)[of X] by blast\n  qed\nqed\n\ntext \\<open>\n  An \\emph{independence system} consists of a finite ground set together with an independence\n  predicate over the sets of this ground set. At least one set of the carrier is independent and\n  subsets of independent sets are also independent.\n\\<close>\n\nlocale indep_system =\n  fixes carrier :: \"'a set\"\n  fixes indep :: \"'a set \\<Rightarrow> bool\"\n  assumes carrier_finite: \"finite carrier\"\n  assumes indep_subset_carrier: \"indep X \\<Longrightarrow> X \\<subseteq> carrier\"\n  assumes indep_ex: \"\\<exists>X. indep X\"\n  assumes indep_subset: \"indep X \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> indep Y\"\nbegin\n\nlemmas psubset_inc_induct [case_names carrier step] = finite_psubset_inc_induct[OF carrier_finite]\nlemmas indep_finite [simp] = finite_subset[OF indep_subset_carrier carrier_finite]\n\ntext \\<open>\n  The empty set is independent.\n\\<close>\n\nlemma indep_empty [simp]: \"indep {}\"\n  using indep_ex indep_subset by auto\n\nsubsection \\<open>Sub-independence systems\\<close>\n\ntext \\<open>\n  A subset of the ground set induces an independence system.\n\\<close>\n\ndefinition indep_in where \"indep_in \\<E> X \\<longleftrightarrow> X \\<subseteq> \\<E> \\<and> indep X\"\n\nlemma indep_inI:\n  assumes \"X \\<subseteq> \\<E>\"\n  assumes \"indep X\"\n  shows \"indep_in \\<E> X\"\n  using assms unfolding indep_in_def by auto\n\nlemma indep_in_subI: \"indep_in \\<E> X \\<Longrightarrow> indep_in \\<E>' (X \\<inter> \\<E>')\"\n  using indep_subset unfolding indep_in_def by auto\n\nlemma dep_in_subI:\n  assumes \"X \\<subseteq> \\<E>'\"\n  shows \"\\<not> indep_in \\<E>' X \\<Longrightarrow> \\<not> indep_in \\<E> X\"\n  using assms unfolding indep_in_def by auto\n\nlemma indep_in_subset_carrier: \"indep_in \\<E> X \\<Longrightarrow> X \\<subseteq> \\<E>\"\n  unfolding indep_in_def by auto\n\nlemma indep_in_subI_subset:\n  assumes \"\\<E>' \\<subseteq> \\<E>\"\n  assumes \"indep_in \\<E>' X\"\n  shows \"indep_in \\<E> X\"\nproof -\n  have \"indep_in \\<E> (X \\<inter> \\<E>)\" using assms indep_in_subI by auto\n  moreover have \"X \\<inter> \\<E> = X\" using assms indep_in_subset_carrier by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma indep_in_supI:\n  assumes \"X \\<subseteq> \\<E>'\" \"\\<E>' \\<subseteq> \\<E>\"\n  assumes \"indep_in \\<E> X\"\n  shows \"indep_in \\<E>' X\"\nproof -\n  have \"X \\<inter> \\<E>' = X\" using assms by auto\n  then show ?thesis using assms indep_in_subI[where \\<E> = \\<E> and \\<E>' = \\<E>' and X = X] by auto\nqed\n\nlemma indep_in_indep: \"indep_in \\<E> X \\<Longrightarrow> indep X\"\n  unfolding indep_in_def by auto\n\nlemmas indep_inD = indep_in_subset_carrier indep_in_indep\n\nlemma indep_system_subset [simp, intro]:\n  assumes \"\\<E> \\<subseteq> carrier\"\n  shows \"indep_system \\<E> (indep_in \\<E>)\"\n  unfolding indep_system_def indep_in_def\n  using finite_subset[OF assms carrier_finite] indep_subset by auto\n\ntext \\<open>\n  We will work a lot with different sub structures. Therefore, every definition `foo' will have\n  a counterpart `foo\\_in' which has the ground set as an additional parameter. Furthermore, every\n  result about `foo' will have another result about `foo\\_in'. With this, we usually don't have to\n  work with @{command interpretation} in proofs.\n\\<close>\n\ncontext\n  fixes \\<E>\n  assumes \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using \\<open>\\<E> \\<subseteq> carrier\\<close> by auto\n\nlemma indep_in_sub_cong:\n  assumes \"\\<E>' \\<subseteq> \\<E>\"\n  shows \"\\<E>.indep_in \\<E>' X \\<longleftrightarrow> indep_in \\<E>' X\"\n  unfolding \\<E>.indep_in_def indep_in_def using assms by auto\n\nlemmas indep_in_ex = \\<E>.indep_ex\nlemmas indep_in_subset = \\<E>.indep_subset\nlemmas indep_in_empty = \\<E>.indep_empty\n\nend\n\nsubsection \\<open>Bases\\<close>\n\ntext \\<open>\n  A \\emph{basis} is a maximal independent set, i.\\,e.\\ an independent set which becomes dependent on\n  inserting any element of the ground set.\n\\<close>\n\ndefinition basis where \"basis X \\<longleftrightarrow> indep X \\<and> (\\<forall>x \\<in> carrier - X. \\<not> indep (insert x X))\"\n\nlemma basisI:\n  assumes \"indep X\"\n  assumes \"\\<And>x. x \\<in> carrier - X \\<Longrightarrow> \\<not> indep (insert x X)\"\n  shows \"basis X\"\n  using assms unfolding basis_def by auto\n\nlemma basis_indep: \"basis X \\<Longrightarrow> indep X\"\n  unfolding basis_def by auto\n\nlemma basis_max_indep: \"basis X \\<Longrightarrow> x \\<in> carrier - X \\<Longrightarrow> \\<not> indep (insert x X)\"\n  unfolding basis_def by auto\n\nlemmas basisD = basis_indep basis_max_indep\nlemmas basis_subset_carrier = indep_subset_carrier[OF basis_indep]\nlemmas basis_finite [simp] = indep_finite[OF basis_indep]\n\nlemma indep_not_basis:\n  assumes \"indep X\"\n  assumes \"\\<not> basis X\"\n  shows \"\\<exists>x \\<in> carrier - X. indep (insert x X)\"\n  using assms basisI by auto\n\nlemma basis_subset_eq:\n  assumes \"basis B\\<^sub>1\"\n  assumes \"basis B\\<^sub>2\"\n  assumes \"B\\<^sub>1 \\<subseteq> B\\<^sub>2\"\n  shows \"B\\<^sub>1 = B\\<^sub>2\"\nproof (rule ccontr)\n  assume \"B\\<^sub>1 \\<noteq> B\\<^sub>2\"\n  then obtain x where x: \"x \\<in> B\\<^sub>2 - B\\<^sub>1\" using assms by auto\n  then have \"insert x B\\<^sub>1 \\<subseteq> B\\<^sub>2\" using assms by auto\n  then have \"indep (insert x B\\<^sub>1)\" using assms basis_indep[of B\\<^sub>2] indep_subset by auto\n  moreover have \"x \\<in> carrier - B\\<^sub>1\" using assms x basis_subset_carrier by auto\n  ultimately show False using assms basisD by auto\nqed\n\ndefinition basis_in where\n  \"basis_in \\<E> X \\<longleftrightarrow> indep_system.basis \\<E> (indep_in \\<E>) X\"\n\nlemma basis_iff_basis_in: \"basis B \\<longleftrightarrow> basis_in carrier B\"\nproof -\n  interpret \\<E>: indep_system carrier \"indep_in carrier\"\n    by auto\n\n  show \"basis B \\<longleftrightarrow> basis_in carrier B\"\n    unfolding basis_in_def\n  proof (standard, goal_cases LTR RTL)\n    case LTR\n    show ?case\n    proof (rule \\<E>.basisI)\n      show \"indep_in carrier B\" using LTR basisD indep_subset_carrier indep_inI by auto\n    next\n      fix x\n      assume \"x \\<in> carrier - B\"\n      then have \"\\<not> indep (insert x B)\" using LTR basisD by auto\n      then show \"\\<not> indep_in carrier (insert x B)\" using indep_inD by auto\n    qed\n  next\n    case RTL\n    show ?case\n    proof (rule basisI)\n      show \"indep B\" using RTL \\<E>.basis_indep indep_inD by blast\n    next\n      fix x\n      assume \"x \\<in> carrier - B\"\n      then have \"\\<not> indep_in carrier (insert x B)\" using RTL \\<E>.basisD by auto\n      then show \"\\<not> indep (insert x B)\" using indep_subset_carrier indep_inI by blast\n    qed\n  qed\nqed\n\ncontext\n  fixes \\<E>\n  assumes \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using \\<open>\\<E> \\<subseteq> carrier\\<close> by auto\n\nlemma basis_inI_aux: \"\\<E>.basis X \\<Longrightarrow> basis_in \\<E> X\"\n  unfolding basis_in_def by auto\n\nlemma basis_inD_aux: \"basis_in \\<E> X \\<Longrightarrow> \\<E>.basis X\"\n  unfolding basis_in_def by auto\n\nlemma not_basis_inD_aux: \"\\<not> basis_in \\<E> X \\<Longrightarrow> \\<not> \\<E>.basis X\"\n  using basis_inI_aux by auto\n\nlemmas basis_inI = basis_inI_aux[OF \\<E>.basisI]\nlemmas basis_in_indep_in = \\<E>.basis_indep[OF basis_inD_aux]\nlemmas basis_in_max_indep_in = \\<E>.basis_max_indep[OF basis_inD_aux]\nlemmas basis_inD = \\<E>.basisD[OF basis_inD_aux]\nlemmas basis_in_subset_carrier = \\<E>.basis_subset_carrier[OF basis_inD_aux]\nlemmas basis_in_finite = \\<E>.basis_finite[OF basis_inD_aux]\nlemmas indep_in_not_basis_in = \\<E>.indep_not_basis[OF _ not_basis_inD_aux]\nlemmas basis_in_subset_eq = \\<E>.basis_subset_eq[OF basis_inD_aux basis_inD_aux]\n\nend\n\ncontext\n  fixes \\<E>\n  assumes *: \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using * by auto\n\nlemma basis_in_sub_cong:\n  assumes \"\\<E>' \\<subseteq> \\<E>\"\n  shows \"\\<E>.basis_in \\<E>' B \\<longleftrightarrow> basis_in \\<E>' B\"\nproof (safe, goal_cases LTR RTL)\n  case LTR\n  show ?case\n  proof (rule basis_inI)\n    show \"\\<E>' \\<subseteq> carrier\" using assms * by auto\n  next\n    show \"indep_in \\<E>' B\"\n      using * assms LTR \\<E>.basis_in_subset_carrier \\<E>.basis_in_indep_in indep_in_sub_cong by auto\n  next\n    fix x\n    assume \"x \\<in> \\<E>' - B\"\n    then show \"\\<not> indep_in \\<E>' (insert x B)\"\n      using * assms LTR \\<E>.basis_in_max_indep_in \\<E>.basis_in_subset_carrier indep_in_sub_cong by auto\n  qed\nnext\n  case RTL\n  show ?case\n  proof (rule \\<E>.basis_inI)\n    show \"\\<E>' \\<subseteq> \\<E>\" using assms by auto\n  next\n    show \"\\<E>.indep_in \\<E>' B\"\n      using * assms RTL basis_in_subset_carrier basis_in_indep_in indep_in_sub_cong by auto\n  next\n    fix x\n    assume \"x \\<in> \\<E>' - B\"\n    then show \"\\<not> \\<E>.indep_in \\<E>' (insert x B)\"\n      using * assms RTL basis_in_max_indep_in basis_in_subset_carrier indep_in_sub_cong by auto\n  qed\nqed\n\nend\n\nsubsection \\<open>Circuits\\<close>\n\ntext \\<open>\n  A \\emph{circuit} is a minimal dependent set, i.\\,e.\\ a set which becomes independent on removing\n  any element of the ground set.\n\\<close>\n\ndefinition circuit where \"circuit X \\<longleftrightarrow> X \\<subseteq> carrier \\<and> \\<not> indep X \\<and> (\\<forall>x \\<in> X. indep (X - {x}))\"\n\nlemma circuitI:\n  assumes \"X \\<subseteq> carrier\"\n  assumes \"\\<not> indep X\"\n  assumes \"\\<And>x. x \\<in> X \\<Longrightarrow> indep (X - {x})\"\n  shows \"circuit X\"\n  using assms unfolding circuit_def by auto\n\nlemma circuit_subset_carrier: \"circuit X \\<Longrightarrow> X \\<subseteq> carrier\"\n  unfolding circuit_def by auto\nlemmas circuit_finite [simp] = finite_subset[OF circuit_subset_carrier carrier_finite]\n\nlemma circuit_dep: \"circuit X \\<Longrightarrow> \\<not> indep X\"\n  unfolding circuit_def by auto\n\nlemma circuit_min_dep: \"circuit X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> indep (X - {x})\"\n  unfolding circuit_def by auto\n\nlemmas circuitD = circuit_subset_carrier circuit_dep circuit_min_dep\n\nlemma circuit_nonempty: \"circuit X \\<Longrightarrow> X \\<noteq> {}\"\n  using circuit_dep indep_empty by blast\n\nlemma dep_not_circuit:\n  assumes \"X \\<subseteq> carrier\"\n  assumes \"\\<not> indep X\"\n  assumes \"\\<not> circuit X\"\n  shows \"\\<exists>x \\<in> X. \\<not> indep (X - {x})\"\n  using assms circuitI by auto\n\nlemma circuit_subset_eq:\n  assumes \"circuit C\\<^sub>1\"\n  assumes \"circuit C\\<^sub>2\"\n  assumes \"C\\<^sub>1 \\<subseteq> C\\<^sub>2\"\n  shows \"C\\<^sub>1 = C\\<^sub>2\"\nproof (rule ccontr)\n  assume \"C\\<^sub>1 \\<noteq> C\\<^sub>2\"\n  then obtain x where \"x \\<notin> C\\<^sub>1\" \"x \\<in> C\\<^sub>2\" using assms by auto\n  then have \"indep C\\<^sub>1\" using indep_subset \\<open>C\\<^sub>1 \\<subseteq> C\\<^sub>2\\<close> circuit_min_dep[OF \\<open>circuit C\\<^sub>2\\<close>, of x] by auto\n  then show False using assms circuitD by auto\nqed\n\ndefinition circuit_in where\n  \"circuit_in \\<E> X \\<longleftrightarrow> indep_system.circuit \\<E> (indep_in \\<E>) X\"\n\ncontext\n  fixes \\<E>\n  assumes \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using \\<open>\\<E> \\<subseteq> carrier\\<close> by auto\n\nlemma circuit_inI_aux: \"\\<E>.circuit X \\<Longrightarrow> circuit_in \\<E> X\"\n  unfolding circuit_in_def by auto\n\nlemma circuit_inD_aux: \"circuit_in \\<E> X \\<Longrightarrow> \\<E>.circuit X\"\n  unfolding circuit_in_def by auto\n\nlemma not_circuit_inD_aux: \"\\<not> circuit_in \\<E> X \\<Longrightarrow> \\<not> \\<E>.circuit X\"\n  using circuit_inI_aux by auto\n\nlemmas circuit_inI = circuit_inI_aux[OF \\<E>.circuitI]\n\nlemmas circuit_in_subset_carrier = \\<E>.circuit_subset_carrier[OF circuit_inD_aux]\nlemmas circuit_in_finite = \\<E>.circuit_finite[OF circuit_inD_aux]\nlemmas circuit_in_dep_in = \\<E>.circuit_dep[OF circuit_inD_aux]\nlemmas circuit_in_min_dep_in = \\<E>.circuit_min_dep[OF circuit_inD_aux]\nlemmas circuit_inD = \\<E>.circuitD[OF circuit_inD_aux]\nlemmas circuit_in_nonempty = \\<E>.circuit_nonempty[OF circuit_inD_aux]\nlemmas dep_in_not_circuit_in = \\<E>.dep_not_circuit[OF _ _ not_circuit_inD_aux]\nlemmas circuit_in_subset_eq = \\<E>.circuit_subset_eq[OF circuit_inD_aux circuit_inD_aux]\n\nend\n\nlemma circuit_in_subI:\n  assumes \"\\<E>' \\<subseteq> \\<E>\" \"\\<E> \\<subseteq> carrier\"\n  assumes \"circuit_in \\<E>' C\"\n  shows \"circuit_in \\<E> C\"\nproof (rule circuit_inI)\n  show \"\\<E> \\<subseteq> carrier\" using assms by auto\nnext\n  show \"C \\<subseteq> \\<E>\" using assms circuit_in_subset_carrier[of \\<E>' C] by auto\nnext\n  show \"\\<not> indep_in \\<E> C\"\n    using assms\n      circuit_in_dep_in[where \\<E> = \\<E>' and X = C]\n      circuit_in_subset_carrier dep_in_subI[where \\<E>' = \\<E>' and \\<E> = \\<E>]\n    by auto\nnext\n  fix x\n  assume \"x \\<in> C\"\n  then show \"indep_in \\<E> (C - {x})\"\n    using assms circuit_in_min_dep_in indep_in_subI_subset by auto\nqed\n\nlemma circuit_in_supI:\n  assumes \"\\<E>' \\<subseteq> \\<E>\" \"\\<E> \\<subseteq> carrier\" \"C \\<subseteq> \\<E>'\"\n  assumes \"circuit_in \\<E> C\"\n  shows \"circuit_in \\<E>' C\"\nproof (rule circuit_inI)\n  show \"\\<E>' \\<subseteq> carrier\" using assms by auto\nnext\n  show \"C \\<subseteq> \\<E>'\" using assms by auto\nnext\n  have \"\\<not> indep_in \\<E> C\" using assms circuit_in_dep_in by auto\n  then show \"\\<not> indep_in \\<E>' C\" using assms dep_in_subI[of C \\<E>] by auto\nnext\n  fix x\n  assume \"x \\<in> C\"\n  then have \"indep_in \\<E> (C - {x})\" using assms circuit_in_min_dep_in by auto\n  then have \"indep_in \\<E>' ((C - {x}) \\<inter> \\<E>')\" using indep_in_subI by auto\n  moreover have \"(C - {x}) \\<inter> \\<E>' = C - {x}\" using assms circuit_in_subset_carrier by auto\n  ultimately show \"indep_in \\<E>' (C - {x})\" by auto\nqed\n\ncontext\n  fixes \\<E>\n  assumes *: \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using * by auto\n\nlemma circuit_in_sub_cong:\n  assumes \"\\<E>' \\<subseteq> \\<E>\"\n  shows \"\\<E>.circuit_in \\<E>' C \\<longleftrightarrow> circuit_in \\<E>' C\"\nproof (safe, goal_cases LTR RTL)\n  case LTR\n  show ?case\n  proof (rule circuit_inI)\n    show \"\\<E>' \\<subseteq> carrier\" using assms * by auto\n  next\n    show \"C \\<subseteq> \\<E>'\"\n      using assms LTR \\<E>.circuit_in_subset_carrier by auto\n  next\n    show \"\\<not> indep_in \\<E>' C\"\n      using assms LTR \\<E>.circuit_in_dep_in indep_in_sub_cong[OF *] by auto\n  next\n    fix x\n    assume \"x \\<in> C\"\n    then show \"indep_in \\<E>' (C - {x})\"\n      using assms LTR \\<E>.circuit_in_min_dep_in indep_in_sub_cong[OF *] by auto\n  qed\nnext\n  case RTL\n  show ?case\n  proof (rule \\<E>.circuit_inI)\n    show \"\\<E>' \\<subseteq> \\<E>\" using assms * by auto\n  next\n    show \"C \\<subseteq> \\<E>'\"\n      using assms * RTL circuit_in_subset_carrier by auto\n  next\n    show \"\\<not> \\<E>.indep_in \\<E>' C\"\n      using assms * RTL circuit_in_dep_in indep_in_sub_cong[OF *] by auto\n  next\n    fix x\n    assume \"x \\<in> C\"\n    then show \"\\<E>.indep_in \\<E>' (C - {x})\"\n      using assms * RTL circuit_in_min_dep_in indep_in_sub_cong[OF *] by auto\n  qed\nqed\n\nend\n\nlemma circuit_imp_circuit_in:\n  assumes \"circuit C\"\n  shows \"circuit_in carrier C\"\nproof (rule circuit_inI)\n  show \"C \\<subseteq> carrier\" using circuit_subset_carrier[OF assms] .\nnext\n  show \"\\<not> indep_in carrier C\" using circuit_dep[OF assms] indep_in_indep by auto\nnext\n  fix x\n  assume \"x \\<in> C\"\n  then have \"indep (C - {x})\" using circuit_min_dep[OF assms] by auto\n  then show \"indep_in carrier (C - {x})\" using circuit_subset_carrier[OF assms] by (auto intro: indep_inI)\nqed auto\n\nsubsection \\<open>Relation between independence and bases\\<close>\n\ntext \\<open>\n  A set is independent iff it is a subset of a basis.\n\\<close>\n\nlemma indep_imp_subset_basis:\n  assumes \"indep X\"\n  shows \"\\<exists>B. basis B \\<and> X \\<subseteq> B\"\n  using assms\nproof (induction X rule: psubset_inc_induct)\n  case carrier\n  show ?case using indep_subset_carrier[OF assms] .\nnext\n  case (step X)\n  {\n    assume \"\\<not> basis X\"\n    then obtain x where \"x \\<in> carrier\" \"x \\<notin> X\" \"indep (insert x X)\"\n      using step.prems indep_not_basis by auto\n    then have ?case using step.IH[of \"insert x X\"] indep_subset_carrier by auto\n  }\n  then show ?case by auto\nqed\n\nlemmas subset_basis_imp_indep = indep_subset[OF basis_indep]\n\nlemma indep_iff_subset_basis: \"indep X \\<longleftrightarrow> (\\<exists>B. basis B \\<and> X \\<subseteq> B)\"\n  using indep_imp_subset_basis subset_basis_imp_indep by auto\n\nlemma basis_ex: \"\\<exists>B. basis B\"\n  using indep_imp_subset_basis[OF indep_empty] by auto\n\ncontext\n  fixes \\<E>\n  assumes *: \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using * by auto\n\nlemma indep_in_imp_subset_basis_in:\n  assumes \"indep_in \\<E> X\"\n  shows \"\\<exists>B. basis_in \\<E> B \\<and> X \\<subseteq> B\"\n  unfolding basis_in_def using \\<E>.indep_imp_subset_basis[OF assms] .\n\nlemmas subset_basis_in_imp_indep_in = indep_in_subset[OF * basis_in_indep_in[OF *]]\n\nlemma indep_in_iff_subset_basis_in: \"indep_in \\<E> X \\<longleftrightarrow> (\\<exists>B. basis_in \\<E> B \\<and> X \\<subseteq> B)\"\n  using indep_in_imp_subset_basis_in subset_basis_in_imp_indep_in by auto\n\nlemma basis_in_ex: \"\\<exists>B. basis_in \\<E> B\"\n  unfolding basis_in_def using \\<E>.basis_ex .\n\nlemma basis_in_subI:\n  assumes \"\\<E>' \\<subseteq> \\<E>\" \"\\<E> \\<subseteq> carrier\"\n  assumes \"basis_in \\<E>' B\"\n  shows \"\\<exists>B' \\<subseteq> \\<E> - \\<E>'. basis_in \\<E> (B \\<union> B')\"\nproof -\n  have \"indep_in \\<E> B\" using assms basis_in_indep_in indep_in_subI_subset by auto\n  then obtain B' where B': \"basis_in \\<E> B'\" \"B \\<subseteq> B'\"\n    using assms indep_in_imp_subset_basis_in[of B] by auto\n  show ?thesis\n  proof (rule exI)\n    have \"B' - B \\<subseteq> \\<E> - \\<E>'\"\n    proof\n      fix x\n      assume *: \"x \\<in> B' - B\"\n      then have \"x \\<in> \\<E>\" \"x \\<notin> B\"\n        using assms \\<open>basis_in \\<E> B'\\<close> basis_in_subset_carrier[of \\<E>] by auto\n      moreover {\n        assume \"x \\<in> \\<E>'\"\n        moreover have \"indep_in \\<E> (insert x B)\"\n          using * assms indep_in_subset[OF _ basis_in_indep_in] B' by auto\n        ultimately have \"indep_in \\<E>' (insert x B)\"\n          using assms basis_in_subset_carrier unfolding indep_in_def by auto\n        then have False using assms * \\<open>x \\<in> \\<E>'\\<close> basis_in_max_indep_in by auto\n      }\n      ultimately show \"x \\<in> \\<E> - \\<E>'\"  by auto\n    qed\n    moreover have \"B \\<union> (B' - B) = B'\" using \\<open>B \\<subseteq> B'\\<close> by auto\n    ultimately show \"B' - B \\<subseteq> \\<E> - \\<E>' \\<and> basis_in \\<E> (B \\<union> (B' - B))\"\n      using \\<open>basis_in \\<E> B'\\<close> by auto\n  qed\nqed\n\nlemma basis_in_supI:\n  assumes \"B \\<subseteq> \\<E>'\" \"\\<E>' \\<subseteq> \\<E>\" \"\\<E> \\<subseteq> carrier\"\n  assumes \"basis_in \\<E> B\"\n  shows \"basis_in \\<E>' B\"\nproof (rule basis_inI)\n  show \"\\<E>' \\<subseteq> carrier\" using assms by auto\nnext\n  show \"indep_in \\<E>' B\"\n  proof -\n    have \"indep_in \\<E>' (B \\<inter> \\<E>')\"\n      using assms basis_in_indep_in[of \\<E> B] indep_in_subI by auto\n    moreover have \"B \\<inter> \\<E>' = B\" using assms by auto\n    ultimately show ?thesis by auto\n  qed\nnext\n  show \"\\<And>x. x \\<in> \\<E>' - B \\<Longrightarrow> \\<not> indep_in \\<E>' (insert x B)\"\n    using assms basis_in_subset_carrier basis_in_max_indep_in dep_in_subI[of _ \\<E> \\<E>'] by auto\nqed\n\nend\n\nsubsection \\<open>Relation between dependence and circuits\\<close>\n\ntext \\<open>\n  A set is dependent iff it contains a circuit.\n\\<close>\n\nlemma dep_imp_supset_circuit:\n  assumes \"X \\<subseteq> carrier\"\n  assumes \"\\<not> indep X\"\n  shows \"\\<exists>C. circuit C \\<and> C \\<subseteq> X\"\n  using assms\nproof (induction X rule: remove_induct)\n  case (remove X)\n  {\n    assume \"\\<not> circuit X\"\n    then obtain x where \"x \\<in> X\" \"\\<not> indep (X - {x})\"\n      using remove.prems dep_not_circuit by auto\n    then obtain C where \"circuit C\" \"C \\<subseteq> X - {x}\"\n      using remove.prems remove.IH[of x] by auto\n    then have ?case by auto\n  }\n  then show ?case using remove.prems by auto\nqed (auto simp add: carrier_finite finite_subset)\n\nlemma supset_circuit_imp_dep:\n  assumes \"circuit C \\<and> C \\<subseteq> X\"\n  shows \"\\<not> indep X\"\n  using assms indep_subset circuit_dep by auto\n\nlemma dep_iff_supset_circuit:\n  assumes \"X \\<subseteq> carrier\"\n  shows \"\\<not> indep X \\<longleftrightarrow> (\\<exists>C. circuit C \\<and> C \\<subseteq> X)\"\n  using assms dep_imp_supset_circuit supset_circuit_imp_dep by auto\n\ncontext\n  fixes \\<E>\n  assumes \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using \\<open>\\<E> \\<subseteq> carrier\\<close> by auto\n\nlemma dep_in_imp_supset_circuit_in:\n  assumes \"X \\<subseteq> \\<E>\"\n  assumes \"\\<not> indep_in \\<E> X\"\n  shows \"\\<exists>C. circuit_in \\<E> C \\<and> C \\<subseteq> X\"\n  unfolding circuit_in_def using \\<E>.dep_imp_supset_circuit[OF assms] .\n\nlemma supset_circuit_in_imp_dep_in:\n  assumes \"circuit_in \\<E> C \\<and> C \\<subseteq> X\"\n  shows \"\\<not> indep_in \\<E> X\"\n  using assms \\<E>.supset_circuit_imp_dep unfolding circuit_in_def by auto\n\nlemma dep_in_iff_supset_circuit_in:\n  assumes \"X \\<subseteq> \\<E>\"\n  shows \"\\<not> indep_in \\<E> X \\<longleftrightarrow> (\\<exists>C. circuit_in \\<E> C \\<and> C \\<subseteq> X)\"\n  using assms dep_in_imp_supset_circuit_in supset_circuit_in_imp_dep_in by auto\n\nend\n\nsubsection \\<open>Ranks\\<close>\n\ndefinition lower_rank_of :: \"'a set \\<Rightarrow> nat\" where\n  \"lower_rank_of carrier' \\<equiv> Min {card B | B. basis_in carrier' B}\"\n\ndefinition upper_rank_of :: \"'a set \\<Rightarrow> nat\" where\n  \"upper_rank_of carrier' \\<equiv> Max {card B | B. basis_in carrier' B}\"\n\nlemma collect_basis_finite: \"finite (Collect basis)\"\nproof -\n  have \"Collect basis \\<subseteq> {X. X \\<subseteq> carrier}\"\n    using basis_subset_carrier by auto\n  moreover have \"finite \\<dots>\"\n    using carrier_finite by auto\n  ultimately show ?thesis using finite_subset by auto\nqed\n\ncontext\n  fixes \\<E>\n  assumes *: \"\\<E> \\<subseteq> carrier\"\nbegin\n\ninterpretation \\<E>: indep_system \\<E> \"indep_in \\<E>\"\n  using * by auto\n\nlemma collect_basis_in_finite: \"finite (Collect (basis_in \\<E>))\"\n  unfolding basis_in_def using \\<E>.collect_basis_finite .\n\nlemma lower_rank_of_le: \"lower_rank_of \\<E> \\<le> card \\<E>\"\nproof -\n  have \"\\<exists>n \\<in> {card B | B. basis_in \\<E> B}. n \\<le> card \\<E>\"\n    using card_mono[OF \\<E>.carrier_finite basis_in_subset_carrier[OF *]] basis_in_ex[OF *] by auto\n  moreover have \"finite {card B | B. basis_in \\<E> B}\"\n    using collect_basis_in_finite by auto\n  ultimately show ?thesis\n    unfolding lower_rank_of_def using basis_ex Min_le_iff by auto\nqed\n\nlemma upper_rank_of_le: \"upper_rank_of \\<E> \\<le> card \\<E>\"\nproof -\n  have \"\\<forall>n \\<in> {card B | B. basis_in \\<E> B}. n \\<le> card \\<E>\"\n    using card_mono[OF \\<E>.carrier_finite basis_in_subset_carrier[OF *]] by auto\n  then show ?thesis\n    unfolding upper_rank_of_def using basis_in_ex[OF *] collect_basis_in_finite by auto\nqed\n\ncontext\n  fixes \\<E>'\n  assumes **: \"\\<E>' \\<subseteq> \\<E>\"\nbegin\n\ninterpretation \\<E>'\\<^sub>1: indep_system \\<E>' \"indep_in \\<E>'\"\n  using * ** by auto\ninterpretation \\<E>'\\<^sub>2: indep_system \\<E>' \"\\<E>.indep_in \\<E>'\"\n  using * ** by auto\n\nlemma lower_rank_of_sub_cong:\n  shows \"\\<E>.lower_rank_of \\<E>' = lower_rank_of \\<E>'\"\nproof -\n  have \"\\<And>B. \\<E>'\\<^sub>1.basis B \\<longleftrightarrow> \\<E>'\\<^sub>2.basis B\"\n    using ** basis_in_sub_cong[OF *, of \\<E>']\n    unfolding basis_in_def \\<E>.basis_in_def by auto\n  then show ?thesis\n    unfolding lower_rank_of_def \\<E>.lower_rank_of_def\n    using basis_in_sub_cong[OF * **]\n    by auto\nqed\n\nlemma upper_rank_of_sub_cong:\n  shows \"\\<E>.upper_rank_of \\<E>' = upper_rank_of \\<E>'\"\nproof -\n  have \"\\<And>B. \\<E>'\\<^sub>1.basis B \\<longleftrightarrow> \\<E>'\\<^sub>2.basis B\"\n    using ** basis_in_sub_cong[OF *, of \\<E>']\n    unfolding basis_in_def \\<E>.basis_in_def by auto\n  then show ?thesis\n    unfolding upper_rank_of_def \\<E>.upper_rank_of_def\n    using basis_in_sub_cong[OF * **]\n    by auto\nqed\n\nend\n\nend\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Matroids/Indep_System.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.8947894717137997, "lm_q1q2_score": 0.7758144694703574}}
{"text": "theory Chapter3\nimports \"HOL-IMP.BExp\"\n        \"HOL-IMP.ASM\"\n        \"Short_Theory\"\nbegin\n\ntext{*\n\\section*{Chapter 3}\n\n\\exercise\nTo show that @{const asimp_const} really folds all subexpressions of the form\n@{term \"Plus (N i) (N j)\"}, define a function\n*}\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{*\nthat checks that its argument does not contain a subexpression of the form\n@{term \"Plus (N i) (N j)\"}. Then prove that the result of @{const asimp_const}\nis optimal:\n*}\n\nlemma \"optimal (asimp_const a)\"\n(* your definition/proof here *)\n\ntext{*\nThis proof needs the same @{text \"split:\"} directive as the correctness proof of\n@{const asimp_const}. This increases the chance of nontermination\nof the simplifier. Therefore @{const optimal} should be defined purely by\npattern matching on the left-hand side,\nwithout @{text case} expressions on the right-hand side.\n\\endexercise\n\n\n\\exercise\nIn this exercise we verify constant folding for @{typ aexp}\nwhere we sum up all constants, even if they are not next to each other.\nFor example, @{term \"Plus (N 1) (Plus (V x) (N 2))\"} becomes\n@{term \"Plus (V x) (N 3)\"}. This goes beyond @{const asimp}.\nBelow we follow a particular solution strategy but there are many others.\n\nFirst, define a function @{text sumN} that returns the sum of all\nconstants in an expression and a function @{text zeroN} that replaces all\nconstants in an expression by zeroes (they will be optimized away later):\n*}\n\nfun sumN :: \"aexp \\<Rightarrow> int\" where\n(* your definition/proof here *)\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\ntext {*\nNext, define a function @{text sepN} that produces an arithmetic expression\nthat adds the results of @{const sumN} and @{const zeroN}. Prove that\n@{text sepN} preserves the value of an expression.\n*}\n\ndefinition sepN :: \"aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\nlemma aval_sepN: \"aval (sepN t) s = aval t s\"\n(* your definition/proof here *)\n\ntext {*\nFinally, define a function @{text full_asimp} that uses @{const asimp}\nto eliminate the zeroes left over by @{const sepN}.\nProve that it preserves the value of an arithmetic expression.\n*}\n\ndefinition full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\nlemma aval_full_asimp: \"aval (full_asimp t) s = aval t s\"\n(* your definition/proof here *)\n\n\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:subst}\nSubstitution is the process of replacing a variable\nby an expression in an expression. Define a substitution function\n*}\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\ntext{*\nsuch that @{term \"subst x a e\"} is the result of replacing\nevery occurrence of variable @{text x} by @{text a} in @{text e}.\nFor example:\n@{lemma[display] \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\" by simp}\n\nProve the so-called \\concept{substitution lemma} that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\n*}\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n(* your definition/proof here *)\n\ntext {*\nAs a consequence prove that we can substitute equal expressions by equal expressions\nand obtain the same result under evaluation:\n*}\nlemma \"aval a1 s = aval a2 s\n  \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nTake a copy of theory @{short_theory \"AExp\"} and modify it as follows.\nExtend type @{typ aexp} with a binary constructor @{text Times} that\nrepresents multiplication. Modify the definition of the functions @{const aval}\nand @{const asimp} accordingly. You can remove @{const asimp_const}.\nFunction @{const asimp} should eliminate 0 and 1 from multiplications\nas well as evaluate constant subterms. Update all proofs concerned.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a datatype @{text aexp2} of extended arithmetic expressions that has,\nin addition to the constructors of @{typ aexp}, a constructor for\nmodelling a C-like post-increment operation $x{++}$, where $x$ must be a\nvariable. Define an evaluation function @{text \"aval2 :: aexp2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state\"}\nthat returns both the value of the expression and the new state.\nThe latter is required because post-increment changes the state.\n\nExtend @{text aexp2} and @{text aval2} with a division operation. Model partiality of\ndivision by changing the return type of @{text aval2} to\n@{typ \"(val \\<times> state) option\"}. In case of division by 0 let @{text aval2}\nreturn @{const None}. Division on @{typ int} is the infix @{text div}.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nThe following type adds a @{text LET} construct to arithmetic expressions:\n*}\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\ntext{* The @{const LET} constructor introduces a local variable:\nthe value of @{term \"LET x e\\<^sub>1 e\\<^sub>2\"} is the value of @{text e\\<^sub>2}\nin the state where @{text x} is bound to the value of @{text e\\<^sub>1} in the original state.\nDefine a function @{const lval} @{text\"::\"} @{typ \"lexp \\<Rightarrow> state \\<Rightarrow> int\"}\nthat evaluates @{typ lexp} expressions. Remember @{term\"s(x := i)\"}.\n\nDefine a conversion @{const inline} @{text\"::\"} @{typ \"lexp \\<Rightarrow> aexp\"}.\nThe expression \\mbox{@{term \"LET x e\\<^sub>1 e\\<^sub>2\"}} is inlined by substituting\nthe converted form of @{text e\\<^sub>1} for @{text x} in the converted form of @{text e\\<^sub>2}.\nSee Exercise~\\ref{exe:subst} for more on substitution.\nProve that @{const inline} is correct w.r.t.\\ evaluation.\n\\endexercise\n\n\n\\exercise\nShow that equality and less-or-equal tests on @{text aexp} are definable\n*}\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ntext{*\nand prove that they do what they are supposed to:\n*}\n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n(* your definition/proof here *)\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider an alternative type of boolean expressions featuring a conditional: *}\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\ntext {*  First define an evaluation function analogously to @{const bval}: *}\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{* Then define two translation functions *}\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n(* your definition/proof here *)\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ntext{* and prove their correctness: *}\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\n(* your definition/proof here *)\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nWe define a new type of purely boolean expressions without any arithmetic\n*}\n\ndatatype pbexp =\n  VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\ntext{*\nwhere variables range over values of type @{typ bool},\nas can be seen from the evaluation function:\n*}\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\"  |\n\"pbval (NOT b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b1 b2) s = (pbval b1 s \\<and> pbval b2 s)\" |\n\"pbval (OR b1 b2) s = (pbval b1 s \\<or> pbval b2 s)\"\n\ntext {* Define a function that checks whether a boolean exression is in NNF\n(negation normal form), i.e., if @{const NOT} is only applied directly\nto @{const VAR}s: *}\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{*\nNow define a function that converts a @{text bexp} into NNF by pushing\n@{const NOT} inwards as much as possible:\n*}\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n(* your definition/proof here *)\n\ntext{*\nProve that @{const nnf} does what it is supposed to do:\n*}\n\nlemma pbval_nnf: \"pbval (nnf b) s = pbval b s\"\n(* your definition/proof here *)\n\nlemma is_nnf_nnf: \"is_nnf (nnf b)\"\n(* your definition/proof here *)\n\ntext{*\nAn expression is in DNF (disjunctive normal form) if it is in NNF\nand if no @{const OR} occurs below an @{const AND}. Define a corresponding\ntest:\n*}\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext {*\nAn NNF can be converted into a DNF in a bottom-up manner.\nThe critical case is the conversion of @{term (sub) \"AND b1 b2\"}.\nHaving converted @{text b\\<^sub>1} and @{text b\\<^sub>2}, apply distributivity of @{const AND}\nover @{const OR}. If we write @{const OR} as a multi-argument function,\nwe can express the distributivity step as follows:\n@{text \"dist_AND (OR a\\<^sub>1 ... a\\<^sub>n) (OR b\\<^sub>1 ... b\\<^sub>m)\"}\n= @{text \"OR (AND a\\<^sub>1 b\\<^sub>1) (AND a\\<^sub>1 b\\<^sub>2) ... (AND a\\<^sub>n b\\<^sub>m)\"}. Define\n*}\n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n(* your definition/proof here *)\n\ntext {* and prove that it behaves as follows: *}\n\nlemma pbval_dist: \"pbval (dist_AND b1 b2) s = pbval (AND b1 b2) s\"\n(* your definition/proof here *)\n\nlemma is_dnf_dist: \"is_dnf b1 \\<Longrightarrow> is_dnf b2 \\<Longrightarrow> is_dnf (dist_AND b1 b2)\"\n(* your definition/proof here *)\n\ntext {* Use @{const dist_AND} to write a function that converts an NNF\n  to a DNF in the above bottom-up manner.\n*}\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n(* your definition/proof here *)\n\ntext {* Prove the correctness of your function: *}\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n(* your definition/proof here *)\n\nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:stack-underflow}\nA \\concept{stack underflow} occurs when executing an @{text ADD}\ninstruction on a stack of size less than 2. In our semantics\na term @{term \"exec1 ADD s stk\"} where @{prop \"length stk < 2\"}\nis simply some unspecified value, not an error or exception --- HOL does not have those concepts.\nModify theory @{short_theory \"ASM\"}\nsuch that stack underflow is modelled by @{const None}\nand normal execution by @{text Some}, i.e., the execution functions\nhave return type @{typ \"stack option\"}. Modify all theorems and proofs\naccordingly.\nHint: you may find @{text\"split: option.split\"} useful in your proofs.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:register-machine}\nThis exercise is about a register machine\nand compiler for @{typ aexp}. The machine instructions are\n*}\ntype_synonym reg = nat\ndatatype instr = LDI val reg | LD vname reg | ADD reg reg\n\ntext {*\nwhere type @{text reg} is a synonym for @{typ nat}.\nInstruction @{term \"LDI i r\"} loads @{text i} into register @{text r},\n@{term \"LD x r\"} loads the value of @{text x} into register @{text r},\nand @{term[names_short] \"ADD r\\<^sub>1 r\\<^sub>2\"} adds register @{text r\\<^sub>2} to register @{text r\\<^sub>1}.\n\nDefine the execution of an instruction given a state and a register state;\nthe result is the new register state: *}\n\ntype_synonym rstate = \"reg \\<Rightarrow> val\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n(* your definition/proof here *)\n\ntext{*\nDefine the execution @{const[source] exec} of a list of instructions as for the stack machine.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto @{text r}. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"< r\"} should be left alone.\nDefine the compiler and prove it correct:\n*}\n\ntheorem \"exec (comp a r) s rs r = aval a s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:accumulator}\nThis exercise is a variation of the previous one\nwith a different instruction set:\n*}\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\ntext{*\nAll instructions refer implicitly to register 0 as a source or target:\n@{const LDI0} and @{const LD0} load a value into register 0, @{term \"MV0 r\"}\ncopies the value in register 0 into register @{text r}, and @{term \"ADD0 r\"}\nadds the value in register @{text r} to the value in register 0;\n@{term \"MV0 0\"} and @{term \"ADD0 0\"} are legal. Define the execution functions\n*}\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n(* your definition/proof here *)\n\ntext{*\nand @{const exec0} for instruction lists.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto register 0. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"\\<le> r\"} should be left alone\n(with the exception of 0). Define the compiler and prove it correct:\n*}\n\ntheorem \"exec0 (comp0 a r) s rs 0 = aval a s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "brando90", "repo": "isabelle-gym", "sha": "f4d231cb9f625422e873aa2c9c2c6f22b7da4b27", "save_path": "github-repos/isabelle/brando90-isabelle-gym", "path": "github-repos/isabelle/brando90-isabelle-gym/isabelle-gym-f4d231cb9f625422e873aa2c9c2c6f22b7da4b27/isar_brandos_resources/templates/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.8947894632969137, "lm_q1q2_score": 0.7758144498755122}}
{"text": "(* Title: Group_Divisible_Designs.thy\n   Author: Chelsea Edmonds\n*)\n\nsection \\<open>Group Divisible Designs\\<close>\ntext \\<open>Definitions in this section taken from the handbook \\cite{colbournHandbookCombinatorialDesigns2007}\nand Stinson \\cite{stinsonCombinatorialDesignsConstructions2004} \\<close>\ntheory Group_Divisible_Designs imports Resolvable_Designs\nbegin\n\nsubsection \\<open>Group design \\<close>\ntext \\<open>We define a group design to have an additional paramater $G$ which is a partition on the point \nset $V$. This is not defined in the handbook, but is a precursor to GDD's without index constraints\\<close>\n\nlocale group_design = proper_design + \n  fixes groups :: \"'a set set\" (\"\\<G>\")\n  assumes group_partitions: \"partition_on \\<V> \\<G>\"\n  assumes groups_size: \"card \\<G> > 1\" \nbegin\n\nlemma groups_not_empty: \"\\<G> \\<noteq> {}\"\n  using groups_size by auto\n\nlemma num_groups_lt_points: \"card \\<G> \\<le> \\<v>\"\n  by (simp add: partition_on_le_set_elements finite_sets group_partitions) \n\nlemma groups_disjoint: \"disjoint \\<G>\"\n  using group_partitions partition_onD2 by auto\n\nlemma groups_disjoint_pairwise: \"G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> disjnt G1 G2\"\n  using group_partitions partition_onD2 pairwiseD by fastforce \n\nlemma point_in_one_group: \"x \\<in> G1 \\<Longrightarrow> G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> x \\<notin> G2\"\n  using groups_disjoint_pairwise by (simp add: disjnt_iff) \n\nlemma point_has_unique_group: \"x \\<in> \\<V> \\<Longrightarrow> \\<exists>!G. x \\<in> G \\<and> G \\<in> \\<G>\"\n  using partition_on_partition_on_unique group_partitions\n  by fastforce \n\nlemma rep_number_point_group_one: \n  assumes \"x \\<in> \\<V>\"\n  shows  \"card {g \\<in> \\<G> . x \\<in> g} = 1\" \nproof -\n  obtain g' where \"g' \\<in> \\<G>\" and \"x \\<in> g'\"\n    using assms point_has_unique_group by blast \n  then have \"{g \\<in> \\<G> . x \\<in> g} = {g'}\"\n    using  group_partitions partition_onD4 by force \n  thus ?thesis\n    by simp \nqed\n\nlemma point_in_group: \"G \\<in> \\<G> \\<Longrightarrow> x \\<in> G \\<Longrightarrow> x \\<in> \\<V>\"\n  using group_partitions partition_onD1 by auto \n\nlemma point_subset_in_group: \"G \\<in> \\<G> \\<Longrightarrow> ps \\<subseteq> G \\<Longrightarrow> ps \\<subseteq> \\<V>\"\n  using point_in_group by auto\n\nlemma group_subset_point_subset: \"G \\<in> \\<G> \\<Longrightarrow> G' \\<subseteq> G \\<Longrightarrow> ps \\<subseteq> G' \\<Longrightarrow> ps \\<subseteq> \\<V>\"\n  using point_subset_in_group by auto\n\nlemma groups_finite: \"finite \\<G>\"\n  using finite_elements finite_sets group_partitions by auto\n\nlemma group_elements_finite: \"G \\<in> \\<G> \\<Longrightarrow> finite G\"\n  using groups_finite finite_sets group_partitions\n  by (meson finite_subset point_in_group subset_iff)\n\nlemma v_equals_sum_group_sizes: \"\\<v> = (\\<Sum>G \\<in> \\<G>. card G)\"\n  using group_partitions groups_disjoint partition_onD1 card_Union_disjoint group_elements_finite \n  by fastforce \n\nlemma gdd_min_v: \"\\<v> \\<ge> 2\"\nproof - \n  have assm: \"card \\<G> \\<ge> 2\" using groups_size by simp\n  then have \"\\<And> G . G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}\" using partition_onD3 group_partitions by auto\n  then have \"\\<And> G . G \\<in> \\<G> \\<Longrightarrow> card G \\<ge> 1\"\n    using group_elements_finite card_0_eq by fastforce \n  then have \" (\\<Sum>G \\<in> \\<G>. card G) \\<ge> 2\" using assm\n    using sum_mono by force \n  thus ?thesis using v_equals_sum_group_sizes\n    by linarith \nqed\n\nlemma min_group_size: \"G \\<in> \\<G> \\<Longrightarrow> card G \\<ge> 1\"\n  using partition_onD3 group_partitions\n  using group_elements_finite not_le_imp_less by fastforce  \n\nlemma group_size_lt_v: \n  assumes \"G \\<in> \\<G>\"\n  shows \"card G < \\<v>\"\nproof - \n  have \"(\\<Sum>G' \\<in> \\<G>. card G') = \\<v>\" using gdd_min_v v_equals_sum_group_sizes\n    by linarith \n  then have split_sum: \"card G + (\\<Sum>G' \\<in> (\\<G> - {G}). card G') = \\<v>\" using assms sum.remove\n    by (metis groups_finite v_equals_sum_group_sizes) \n  have \"card (\\<G> - {G}) \\<ge> 1\" using groups_size\n    by (simp add: assms groups_finite)\n  then obtain G' where gin: \"G' \\<in> (\\<G> - {G})\"\n    by (meson elem_exists_non_empty_set less_le_trans less_numeral_extra(1)) \n  then have \"card G' \\<ge> 1\" using min_group_size by auto \n  then have \"(\\<Sum>G' \\<in> (\\<G> - {G}). card G') \\<ge> 1\"\n    by (metis gin finite_Diff groups_finite leI less_one sum_eq_0_iff) \n  thus ?thesis using split_sum\n    by linarith\nqed\n\nsubsubsection \\<open>Group Type \\<close>\n\ntext \\<open>GDD's have a \"type\", which is defined by a sequence of group sizes $g_i$, and the number \nof groups of that size $a_i$: $g_1^{a_1}g2^{a_2}...g_n^{a_n}$ \\<close>\ndefinition group_sizes :: \"nat set\" where\n\"group_sizes \\<equiv> {card G | G . G \\<in> \\<G>}\"\n\ndefinition groups_of_size :: \"nat \\<Rightarrow> nat\" where\n\"groups_of_size g \\<equiv> card { G \\<in> \\<G> . card G = g }\"\n\ndefinition group_type :: \"(nat \\<times> nat) set\" where\n\"group_type \\<equiv> {(g, groups_of_size g) | g . g \\<in> group_sizes }\"\n\nlemma group_sizes_min: \"x \\<in> group_sizes \\<Longrightarrow> x \\<ge> 1 \" \n  unfolding group_sizes_def using min_group_size group_size_lt_v by auto \n\nlemma group_sizes_max: \"x \\<in> group_sizes \\<Longrightarrow> x < \\<v> \" \n  unfolding group_sizes_def using min_group_size group_size_lt_v by auto \n\nlemma group_size_implies_group_existance: \"x \\<in> group_sizes \\<Longrightarrow> \\<exists>G. G \\<in> \\<G> \\<and> card G = x\"\n  unfolding group_sizes_def by auto\n\nlemma groups_of_size_zero: \"groups_of_size 0 = 0\"\nproof -\n  have empty: \"{G \\<in> \\<G> . card G = 0} = {}\" using min_group_size\n    by fastforce \n  thus ?thesis unfolding groups_of_size_def\n    by (simp add: empty) \nqed\n\nlemma groups_of_size_max: \n  assumes \"g \\<ge> \\<v>\"\n  shows \"groups_of_size g = 0\"\nproof -\n  have \"{G \\<in> \\<G> . card G = g} = {}\" using group_size_lt_v assms by fastforce \n  thus ?thesis unfolding groups_of_size_def\n    by (simp add: \\<open>{G \\<in> \\<G>. card G = g} = {}\\<close>) \nqed\n\nlemma group_type_contained_sizes: \"(g, a) \\<in> group_type \\<Longrightarrow> g \\<in> group_sizes\" \n  unfolding group_type_def by simp\n\nlemma group_type_contained_count: \"(g, a) \\<in> group_type \\<Longrightarrow> card {G \\<in> \\<G> . card G = g} = a\"\n  unfolding group_type_def groups_of_size_def by simp\n\nlemma group_card_in_sizes: \"g \\<in> \\<G> \\<Longrightarrow> card g \\<in> group_sizes\"\n  unfolding group_sizes_def by auto\n\nlemma group_card_non_zero_groups_of_size_min: \n  assumes \"g \\<in> \\<G>\"\n  assumes \"card g = a\"\n  shows \"groups_of_size a \\<ge> 1\"\nproof - \n  have \"g \\<in> {G \\<in> \\<G> . card G = a}\" using assms by simp\n  then have \"{G \\<in> \\<G> . card G = a} \\<noteq> {}\" by auto\n  then have \"card {G \\<in> \\<G> . card G = a} \\<noteq> 0\"\n    by (simp add: groups_finite) \n  thus ?thesis unfolding groups_of_size_def by simp \nqed\n\nlemma elem_in_group_sizes_min_of_size: \n  assumes \"a \\<in> group_sizes\"\n  shows \"groups_of_size a \\<ge> 1\"\n  using assms group_card_non_zero_groups_of_size_min group_size_implies_group_existance by blast\n\nlemma group_card_non_zero_groups_of_size_max: \n  shows \"groups_of_size a \\<le> \\<v>\"\nproof -\n  have \"{G \\<in> \\<G> . card G = a} \\<subseteq> \\<G>\" by simp\n  then have \"card {G \\<in> \\<G> . card G = a} \\<le> card \\<G>\"\n    by (simp add: card_mono groups_finite)\n  thus ?thesis\n    using groups_of_size_def num_groups_lt_points by auto \nqed\n\nlemma group_card_in_type: \"g \\<in> \\<G> \\<Longrightarrow> \\<exists> x . (card g, x) \\<in> group_type \\<and> x \\<ge> 1\"\n  unfolding group_type_def using group_card_non_zero_groups_of_size_min\n  by (simp add: group_card_in_sizes)\n\nlemma partition_groups_on_size: \"partition_on \\<G> {{ G \\<in> \\<G> . card G = g } | g . g \\<in> group_sizes}\"\nproof (intro partition_onI, auto)\n  fix g\n  assume a1: \"g \\<in> group_sizes\"\n  assume \" \\<forall>x. x \\<in> \\<G> \\<longrightarrow> card x \\<noteq> g\"\n  then show False using a1 group_size_implies_group_existance by auto \nnext\n  fix x\n  assume \"x \\<in> \\<G>\"\n  then show \"\\<exists>xa. (\\<exists>g. xa = {G \\<in> \\<G>. card G = g} \\<and> g \\<in> group_sizes) \\<and> x \\<in> xa\"\n    using  group_card_in_sizes by auto \nqed\n\nlemma group_size_partition_covers_points: \"\\<Union>(\\<Union>{{ G \\<in> \\<G> . card G = g } | g . g \\<in> group_sizes}) = \\<V>\"\n  by (metis (no_types, lifting) group_partitions partition_groups_on_size partition_onD1)\n\nlemma groups_of_size_alt_def_count: \"groups_of_size g = count {# card G . G \\<in># mset_set \\<G> #} g\" \nproof -\n  have a: \"groups_of_size g =  card { G \\<in> \\<G> . card G = g }\" unfolding groups_of_size_def by simp\n  then have \"groups_of_size g =  size {# G \\<in># (mset_set \\<G>) . card G = g #}\"\n    using groups_finite by auto \n  then have size_repr: \"groups_of_size g =  size {# x \\<in># {# card G . G \\<in># mset_set \\<G> #} . x = g #}\"\n    using groups_finite by (simp add: filter_mset_image_mset)\n  have \"group_sizes = set_mset ({# card G . G \\<in># mset_set \\<G> #})\" \n    using group_sizes_def groups_finite by auto \n  thus ?thesis using size_repr by (simp add: count_size_set_repr) \nqed\n\nlemma v_sum_type_rep: \"\\<v> = (\\<Sum> g \\<in> group_sizes . g * (groups_of_size g))\"\nproof -\n  have gs: \"set_mset {# card G . G \\<in># mset_set \\<G> #} = group_sizes\" \n    unfolding group_sizes_def using groups_finite by auto \n  have \"\\<v> = card (\\<Union>(\\<Union>{{ G \\<in> \\<G> . card G = g } | g . g \\<in> group_sizes}))\"\n    using group_size_partition_covers_points by simp\n  have v1: \"\\<v> = (\\<Sum>x \\<in># {# card G . G \\<in># mset_set \\<G> #}. x)\"\n    by (simp add: sum_unfold_sum_mset v_equals_sum_group_sizes)\n  then have \"\\<v> = (\\<Sum>x \\<in> set_mset {# card G . G \\<in># mset_set \\<G> #} . x * (count {# card G . G \\<in># mset_set \\<G> #} x))\" \n    using mset_set_size_card_count by (simp add: v1)\n  thus ?thesis using gs groups_of_size_alt_def_count by auto \nqed\n\nend\n\nsubsubsection \\<open>Uniform Group designs\\<close>\ntext \\<open>A group design requiring all groups are the same size\\<close>\nlocale uniform_group_design = group_design + \n  fixes u_group_size :: nat (\"\\<m>\")\n  assumes uniform_groups: \"G \\<in> \\<G> \\<Longrightarrow> card G = \\<m>\"\n\nbegin\n\nlemma m_positive: \"\\<m> \\<ge> 1\"\nproof -\n  obtain G where \"G \\<in> \\<G>\" using groups_size elem_exists_non_empty_set gr_implies_not_zero by blast \n  thus ?thesis using uniform_groups min_group_size by fastforce\nqed\n\nlemma uniform_groups_alt: \" \\<forall> G \\<in> \\<G> . card G = \\<m>\"\n  using uniform_groups by blast \n\nlemma uniform_groups_group_sizes: \"group_sizes = {\\<m>}\"\n  using design_points_nempty group_card_in_sizes group_size_implies_group_existance \n    point_has_unique_group uniform_groups_alt by force\n\nlemma uniform_groups_group_size_singleton: \"is_singleton (group_sizes)\"\n  using uniform_groups_group_sizes by auto\n\nlemma set_filter_eq_P_forall:\"\\<forall> x \\<in> X . P x \\<Longrightarrow> Set.filter P X = X\"\n  by (simp add: Collect_conj_eq Int_absorb2 Set.filter_def subsetI)\n\nlemma uniform_groups_groups_of_size_m: \"groups_of_size \\<m> = card \\<G>\"\nproof(simp add: groups_of_size_def)\n  have \"{G \\<in> \\<G>. card G = \\<m>} = \\<G>\" using uniform_groups_alt set_filter_eq_P_forall by auto\n  thus \"card {G \\<in> \\<G>. card G = \\<m>} = card \\<G>\" by simp\nqed\n\nlemma uniform_groups_of_size_not_m: \"x \\<noteq> \\<m> \\<Longrightarrow> groups_of_size x = 0\"\n  by (simp add: groups_of_size_def card_eq_0_iff uniform_groups)\n\nend\n\nsubsection \\<open>GDD\\<close>\ntext \\<open>A GDD extends a group design with an additional index parameter.\nEach pair of elements must occur either \\Lambda times if in diff groups, or 0 times if in the same \ngroup \\<close>\n\nlocale GDD = group_design + \n  fixes index :: int (\"\\<Lambda>\")\n  assumes index_ge_1: \"\\<Lambda> \\<ge> 1\"\n  assumes index_together: \"G \\<in> \\<G> \\<Longrightarrow> x \\<in> G \\<Longrightarrow> y \\<in> G \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> \\<B> index {x, y} = 0\"\n  assumes index_distinct: \"G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> x \\<in> G1 \\<Longrightarrow> y \\<in> G2 \\<Longrightarrow> \n    \\<B> index {x, y} = \\<Lambda>\"\nbegin\n\nlemma points_sep_groups_ne: \"G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> x \\<in> G1 \\<Longrightarrow> y \\<in> G2 \\<Longrightarrow> x \\<noteq> y\"\n  by (meson point_in_one_group)\n\nlemma index_together_alt_ss: \"ps \\<subseteq> G \\<Longrightarrow> G \\<in> \\<G> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0\"\n  using index_together by (metis card_2_iff insert_subset) \n\nlemma index_distinct_alt_ss: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> (\\<And> G . G \\<in> \\<G> \\<Longrightarrow> \\<not> ps \\<subseteq> G) \\<Longrightarrow> \n    \\<B> index ps = \\<Lambda>\"\n  using index_distinct by (metis card_2_iff empty_subsetI insert_subset point_has_unique_group) \n\nlemma gdd_index_options: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0 \\<or> \\<B> index ps = \\<Lambda>\"\n  using index_distinct_alt_ss index_together_alt_ss by blast\n\nlemma index_zero_implies_same_group: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0 \\<Longrightarrow> \n    \\<exists> G \\<in> \\<G> . ps \\<subseteq> G\" using index_distinct_alt_ss gr_implies_not_zero\n  by (metis index_ge_1 less_one of_nat_0 of_nat_1 of_nat_le_0_iff)\n\nlemma index_zero_implies_same_group_unique: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0 \\<Longrightarrow> \n    \\<exists>! G \\<in> \\<G> . ps \\<subseteq> G\" \n  by (meson GDD.index_zero_implies_same_group GDD_axioms card_2_iff' group_design.point_in_one_group \n      group_design_axioms in_mono)\n\nlemma index_not_zero_impl_diff_group: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = \\<Lambda> \\<Longrightarrow>  \n    (\\<And> G . G \\<in> \\<G> \\<Longrightarrow> \\<not> ps \\<subseteq> G)\"\n  using index_ge_1 index_together_alt_ss by auto\n\nlemma index_zero_implies_one_group: \n  assumes \"ps \\<subseteq> \\<V>\" \n  and \"card ps = 2\" \n  and \"\\<B> index ps = 0\" \n  shows \"size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 1\"\nproof -\n  obtain G where ging: \"G \\<in> \\<G>\" and psin: \"ps \\<subseteq> G\" \n    using index_zero_implies_same_group groups_size assms by blast\n  then have unique: \"\\<And> G2 . G2 \\<in> \\<G> \\<Longrightarrow> G \\<noteq> G2 \\<Longrightarrow> \\<not> ps \\<subseteq> G2\" \n    using index_zero_implies_same_group_unique by (metis assms) \n  have \"\\<And> G'. G' \\<in> \\<G> \\<longleftrightarrow> G' \\<in># mset_set \\<G>\"\n    by (simp add: groups_finite) \n  then have eq_mset: \"{#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = mset_set {b \\<in> \\<G> . ps \\<subseteq> b}\"\n    using filter_mset_mset_set groups_finite by blast \n  then have \"{b \\<in> \\<G> . ps \\<subseteq> b} = {G}\" using unique psin\n    by (smt Collect_cong ging singleton_conv)\n  thus ?thesis by (simp add: eq_mset) \nqed\n\nlemma index_distinct_group_num_alt_def: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \n    size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 0 \\<Longrightarrow> \\<B> index ps = \\<Lambda>\"\n  by (metis gdd_index_options index_zero_implies_one_group numeral_One zero_neq_numeral)\n\nlemma index_non_zero_implies_no_group: \n  assumes \"ps \\<subseteq> \\<V>\" \n    and  \"card ps = 2\" \n    and \"\\<B> index ps = \\<Lambda>\" \n  shows \"size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 0\"\nproof -\n  have \"\\<And> G . G \\<in> \\<G> \\<Longrightarrow>  \\<not> ps \\<subseteq> G\" using index_not_zero_impl_diff_group assms by simp\n  then have \"{#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = {#}\"\n    using filter_mset_empty_if_finite_and_filter_set_empty by force\n  thus ?thesis by simp\nqed\n\nlemma gdd_index_non_zero_iff: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \n    \\<B> index ps = \\<Lambda> \\<longleftrightarrow> size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 0\"\n  using index_non_zero_implies_no_group index_distinct_group_num_alt_def by auto\n\nlemma gdd_index_zero_iff: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \n    \\<B> index ps = 0 \\<longleftrightarrow> size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 1\"\n  apply (auto simp add: index_zero_implies_one_group)\n  by (metis GDD.gdd_index_options GDD_axioms index_non_zero_implies_no_group old.nat.distinct(2))\n\nlemma points_index_upper_bound: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps \\<le> \\<Lambda>\"\n  using gdd_index_options index_ge_1\n  by (metis int_one_le_iff_zero_less le_refl of_nat_0 of_nat_0_le_iff of_nat_le_iff zero_less_imp_eq_int) \n\nlemma index_1_imp_mult_1: \n  assumes \"\\<Lambda> = 1\"\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"card bl \\<ge> 2\"\n  shows \"multiplicity bl = 1\"\nproof (rule ccontr)\n  assume \"\\<not> (multiplicity bl = 1)\"\n  then have \"multiplicity bl \\<noteq> 1\" and \"multiplicity bl \\<noteq> 0\" using assms by simp_all \n  then have m: \"multiplicity bl \\<ge> 2\" by linarith\n  obtain ps where ps: \"ps \\<subseteq> bl \\<and> card ps = 2\"\n    using nat_int_comparison(3) obtain_subset_with_card_n by (metis assms(3))  \n  then have \"\\<B> index ps \\<ge> 2\"\n    using m points_index_count_min ps by blast\n  then show False using assms index_distinct ps antisym_conv2 not_numeral_less_zero \n      numeral_le_one_iff points_index_ps_nin semiring_norm(69) zero_neq_numeral\n    by (metis gdd_index_options int_int_eq int_ops(2))\nqed\n\nlemma simple_if_block_size_gt_2:\n  assumes \"\\<And> bl . card bl \\<ge> 2\"\n  assumes \"\\<Lambda> = 1\"\n  shows \"simple_design \\<V> \\<B>\"\n  using index_1_imp_mult_1 assms apply (unfold_locales)\n  by (metis card.empty not_numeral_le_zero) \n\nend\n\nsubsubsection \\<open>Sub types of GDD's \\<close>\n\ntext \\<open>In literature, a GDD is usually defined in a number of different ways, \nincluding factors such as block size limitations \\<close>\nlocale K_\\<Lambda>_GDD = K_block_design + GDD\n\nlocale k_\\<Lambda>_GDD = block_design + GDD\n\nsublocale k_\\<Lambda>_GDD \\<subseteq> K_\\<Lambda>_GDD \\<V> \\<B> \"{\\<k>}\" \\<G> \\<Lambda>\n  by (unfold_locales)\n\nlocale K_GDD = K_\\<Lambda>_GDD \\<V> \\<B> \\<K> \\<G> 1 \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and sizes (\"\\<K>\") and groups (\"\\<G>\")\n\nlocale k_GDD = k_\\<Lambda>_GDD \\<V> \\<B> \\<k> \\<G> 1 \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and u_block_size (\"\\<k>\") and groups (\"\\<G>\")\n\nsublocale k_GDD \\<subseteq> K_GDD \\<V> \\<B> \"{\\<k>}\" \\<G>\n  by (unfold_locales)\n\nlemma (in K_GDD) multiplicity_1:  \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2 \\<Longrightarrow> multiplicity bl = 1\"\n  using index_1_imp_mult_1 by simp\n\nlocale RGDD = GDD + resolvable_design\n\nsubsection \\<open> GDD and PBD Constructions \\<close>\ntext \\<open> GDD's are commonly studied alongside PBD's (pairwise balanced designs). Many constructions\nhave been developed for designs to create a GDD from a PBD and vice versa. In particular, \nWilsons Construction is a well known construction, which is formalised in this section. It\nshould be noted that many of the more basic constructions in this section are often stated without\nproof/all the necessary assumptions in textbooks/course notes.\\<close>\n\ncontext GDD\nbegin\n\nsubsubsection \\<open>GDD Delete Point construction\\<close>\nlemma delete_point_index_zero: \n  assumes \"G \\<in> {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\n  and \"y \\<in> G\" and \"z \\<in> G\" and \"z\\<noteq> y\"\nshows \"(del_point_blocks x) index {y, z} = 0\"\nproof -\n  have \"y \\<noteq> x\" using assms(1) assms(2) by blast \n  have \"z \\<noteq> x\" using assms(1) assms(3) by blast \n  obtain G' where ing: \"G' \\<in> \\<G>\" and ss: \"G \\<subseteq> G'\"\n    using assms(1) by auto\n  have \"{y, z} \\<subseteq> G\" by (simp add: assms(2) assms(3)) \n  then have \"{y, z} \\<subseteq> \\<V>\"\n    by (meson ss ing group_subset_point_subset) \n  then have \"{y, z} \\<subseteq> (del_point x)\"\n    using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> del_point_def by fastforce \n  thus ?thesis using delete_point_index_eq index_together\n    by (metis assms(2) assms(3) assms(4) in_mono ing ss) \nqed\n\nlemma delete_point_index: \n  assumes \"G1 \\<in> {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\n  assumes \"G2 \\<in> {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\n  assumes \"G1 \\<noteq> G2\" and \"y \\<in> G1\" and \"z \\<in> G2\"\n  shows \"del_point_blocks x index {y, z} = \\<Lambda>\"\nproof -\n  have \"y \\<noteq> x\" using assms by blast \n  have \"z \\<noteq> x\" using assms by blast \n  obtain G1' where ing1: \"G1' \\<in> \\<G>\" and t1: \"G1 = G1' - {x}\"\n    using assms(1) by auto\n  obtain G2' where ing2: \"G2' \\<in> \\<G>\" and t2: \"G2 = G2' - {x}\"\n    using assms(2) by auto\n  then have ss1: \"G1 \\<subseteq> G1'\" and ss2: \"G2 \\<subseteq> G2'\" using t1 by auto\n  then have \"{y, z} \\<subseteq> \\<V>\" using ing1 ing2 ss1 ss2 assms(4) assms(5)\n    by (metis empty_subsetI insert_absorb insert_subset point_in_group) \n  then have \"{y, z} \\<subseteq> del_point x\"\n    using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> del_point_def by auto \n  then have indx: \"del_point_blocks x index {y, z} = \\<B> index {y, z}\" \n    using delete_point_index_eq by auto\n  have \"G1' \\<noteq> G2'\" using assms t1 t2 by fastforce \n  thus ?thesis using index_distinct\n    using indx assms(4) assms(5) ing1 ing2 t1 t2 by auto \nqed\n\nlemma delete_point_group_size: \n  assumes \"{x} \\<in> \\<G> \\<Longrightarrow> card \\<G> > 2\" \n  shows \"1 < card {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\nproof (cases \"{x} \\<in> \\<G>\")\n  case True\n  then have \"\\<And> g . g \\<in> (\\<G> - {{x}}) \\<Longrightarrow> x \\<notin> g\"\n    by (meson disjnt_insert1 groups_disjoint pairwise_alt)\n  then have simpg: \"\\<And> g . g \\<in> (\\<G> - {{x}}) \\<Longrightarrow> g - {x} = g\"\n    by simp \n  have \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = {g - {x} |g. (g \\<in> \\<G> - {{x}})}\" using True\n    by force \n  then have \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = {g |g. (g \\<in> \\<G> - {{x}})}\" using simpg \n    by (smt (verit) Collect_cong)\n  then have eq: \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} =  \\<G> - {{x}}\" using set_self_img_compr by blast\n  have \"card (\\<G> - {{x}}) = card \\<G> - 1\" using True\n    by (simp add: groups_finite) \n  then show ?thesis using True assms eq diff_is_0_eq' by force \nnext\n  case False\n  then have \"\\<And>g' y. {x} \\<notin> \\<G> \\<Longrightarrow> g' \\<in> \\<G> \\<Longrightarrow> y \\<in> \\<G> \\<Longrightarrow> g' - {x} = y - {x} \\<Longrightarrow> g' = y\" \n    by (metis all_not_in_conv insert_Diff_single insert_absorb insert_iff points_sep_groups_ne)\n  then have inj: \"inj_on (\\<lambda> g . g - {x}) \\<G>\" by (simp add: inj_onI False) \n  have \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = {g - {x} |g. g \\<in> \\<G>}\" using False by auto\n  then have \"card {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = card \\<G>\" using inj groups_finite card_image\n    by (auto simp add: card_image setcompr_eq_image) \n  then show ?thesis using groups_size by presburger \nqed\n\nlemma GDD_by_deleting_point: \n  assumes \"\\<And>bl. bl \\<in># \\<B> \\<Longrightarrow> x \\<in> bl \\<Longrightarrow> 2 \\<le> card bl\"\n  assumes \"{x} \\<in> \\<G> \\<Longrightarrow> card \\<G> > 2\"\n  shows \"GDD (del_point x) (del_point_blocks x) {g - {x} | g . g \\<in> \\<G> \\<and> g \\<noteq> {x}} \\<Lambda>\"\nproof -\n  interpret pd: proper_design \"del_point x\" \"del_point_blocks x\"\n    using delete_point_proper assms by blast\n  show ?thesis using delete_point_index_zero delete_point_index assms delete_point_group_size\n    by(unfold_locales) (simp_all add: partition_on_remove_pt group_partitions index_ge_1 del_point_def)\nqed\n\nend\n\ncontext K_GDD begin \n\nsubsubsection \\<open>PBD construction from GDD\\<close>\ntext \\<open>Two well known PBD constructions involve taking a GDD and either combining the groups and\nblocks to form a new block collection, or by adjoining a point \\<close>\n\ntext \\<open>First prove that combining the groups and block set results in a constant index \\<close>\nlemma kgdd1_points_index_group_block: \n  assumes \"ps \\<subseteq> \\<V>\"\n  and \"card ps = 2\"\n  shows \"(\\<B> + mset_set \\<G>) index ps = 1\"\nproof -\n  have index1: \"(\\<And> G . G \\<in> \\<G> \\<Longrightarrow> \\<not> ps \\<subseteq> G) \\<Longrightarrow> \\<B> index ps = 1\"\n    using index_distinct_alt_ss assms by fastforce \n  have groups1: \"\\<B> index ps = 0 \\<Longrightarrow> size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 1\"  \n    using index_zero_implies_one_group assms by simp \n  then have \"(\\<B> + mset_set \\<G>) index ps = size (filter_mset ((\\<subseteq>) ps) (\\<B> + mset_set \\<G>))\" \n    by (simp add: points_index_def)\n  thus ?thesis using index1 groups1 gdd_index_non_zero_iff gdd_index_zero_iff assms \n      gdd_index_options points_index_def filter_union_mset union_commute\n    by (smt (z3) empty_neutral(1) less_irrefl_nat nonempty_has_size of_nat_1_eq_iff) \nqed\n\ntext \\<open>Combining blocks and the group set forms a PBD \\<close>\nlemma combine_block_groups_pairwise: \"pairwise_balance \\<V> (\\<B> + mset_set \\<G>) 1\"\nproof -\n  let ?B = \"\\<B> + mset_set \\<G>\"\n  have ss: \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> G \\<subseteq> \\<V>\"\n    by (simp add: point_in_group subsetI)\n  have \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}\" using group_partitions\n    using partition_onD3 by auto \n  then interpret inc: design \\<V> ?B \n  proof (unfold_locales)\n    show \"\\<And>b. (\\<And>G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}) \\<Longrightarrow> b \\<in># \\<B> + mset_set \\<G> \\<Longrightarrow> b \\<subseteq> \\<V>\"\n      by (metis finite_set_mset_mset_set groups_finite ss union_iff wellformed)\n    show \"(\\<And>G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}) \\<Longrightarrow> finite \\<V>\" by (simp add: finite_sets)\n    show \"\\<And>bl. (\\<And>G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}) \\<Longrightarrow> bl \\<in># \\<B> + mset_set \\<G> \\<Longrightarrow> bl \\<noteq> {}\"\n      using blocks_nempty groups_finite by auto\n  qed\n  show ?thesis proof (unfold_locales)\n    show \"inc.\\<b> \\<noteq> 0\" using b_positive by auto\n    show \"(1 ::nat) \\<le> 2\" by simp\n    show \"2 \\<le> inc.\\<v>\" by (simp add: gdd_min_v)\n    then show \"\\<And>ps. ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> ((\\<B> + mset_set \\<G>) index ps) = 1\" \n      using kgdd1_points_index_group_block by simp\n  qed\nqed\n\nlemma combine_block_groups_PBD:\n  assumes \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> card G \\<in> \\<K>\"\n  assumes \"\\<And> k . k \\<in> \\<K> \\<Longrightarrow> k \\<ge> 2\"\n  shows \"PBD \\<V> (\\<B> + mset_set \\<G>) \\<K>\"\nproof -\n  let ?B = \"\\<B> + mset_set \\<G>\"\n  interpret inc: pairwise_balance \\<V> ?B 1 using combine_block_groups_pairwise by simp\n  show ?thesis using assms block_sizes groups_finite positive_ints \n    by (unfold_locales) auto\nqed\n\ntext \\<open>Prove adjoining a point to each group set results in a constant points index \\<close>\nlemma kgdd1_index_adjoin_group_block:\n  assumes \"x \\<notin> \\<V>\"\n  assumes \"ps \\<subseteq> insert x \\<V>\"\n  assumes \"card ps = 2\"\n  shows \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = 1\"\nproof -\n  have \"inj_on ((insert) x) \\<G>\"\n    by (meson assms(1) inj_onI insert_ident point_in_group) \n  then have eq: \"mset_set {insert x g |g. g \\<in> \\<G>} = {# insert x g . g \\<in># mset_set \\<G>#}\"\n    by (simp add: image_mset_mset_set setcompr_eq_image)\n  thus ?thesis \n  proof (cases \"x \\<in> ps\")\n    case True\n    then obtain y where y_ps: \"ps = {x, y}\" using assms(3)\n      by (metis card_2_iff doubleton_eq_iff insertE singletonD)\n    then have ynex: \"y \\<noteq> x\" using assms by fastforce \n    have yinv: \"y \\<in> \\<V>\"\n      using assms(2) y_ps ynex by auto \n    have all_g: \"\\<And> g. g \\<in># (mset_set {insert x g |g. g \\<in> \\<G>}) \\<Longrightarrow> x \\<in> g\"\n      using eq by force\n    have iff: \"\\<And> g . g \\<in> \\<G> \\<Longrightarrow> y \\<in> (insert x g) \\<longleftrightarrow> y \\<in> g\" using ynex by simp \n    have b: \"\\<B> index ps = 0\"\n      using True assms(1) points_index_ps_nin by fastforce \n    then have \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = \n        (mset_set {insert x g |g. g \\<in> \\<G>}) index ps\"\n      using eq by (simp add: point_index_distrib)\n    also have  \"... = (mset_set {insert x g |g. g \\<in> \\<G>}) rep y\" using points_index_pair_rep_num\n      by (metis (no_types, lifting) all_g y_ps) \n    also have 0: \"... = card {b \\<in> {insert x g |g. g \\<in> \\<G>} . y \\<in> b}\" \n      by (simp add: groups_finite rep_number_on_set_def)\n    also have 1: \"... = card {insert x g |g. g \\<in> \\<G> \\<and> y \\<in> insert x g}\"\n      by (smt (verit) Collect_cong mem_Collect_eq)\n    also have 2: \" ... = card {insert x g |g. g \\<in> \\<G> \\<and> y \\<in> g}\" \n      using iff by metis \n    also have \"... = card {g \\<in> \\<G> . y \\<in> g}\" using 1 2 0 empty_iff eq groups_finite ynex insert_iff\n      by (metis points_index_block_image_add_eq points_index_single_rep_num rep_number_on_set_def)  \n    finally have \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = 1\" \n      using rep_number_point_group_one yinv by simp \n    then show ?thesis\n      by simp \n  next\n    case False\n    then have v: \"ps \\<subseteq> \\<V>\" using assms(2) by auto \n    then have \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = (\\<B> + mset_set \\<G>) index ps\"\n      using eq by (simp add: points_index_block_image_add_eq False point_index_distrib) \n    then show ?thesis using v assms kgdd1_points_index_group_block by simp\n  qed\nqed\n\nlemma pairwise_by_adjoining_point: \n  assumes \"x \\<notin> \\<V>\"\n  shows \"pairwise_balance (add_point x) (\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}) 1\"\nproof -\n  let ?B = \"\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}\"\n  let ?V = \"add_point x\"\n  have vdef: \"?V = \\<V> \\<union> {x}\" using add_point_def by simp\n  show ?thesis unfolding add_point_def using finite_sets design_blocks_nempty\n  proof (unfold_locales, simp_all)\n    have \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> insert x G \\<subseteq> ?V\"\n      by (simp add: point_in_group subsetI vdef)\n    then have \"\\<And> G. G \\<in># (mset_set { insert x g | g. g \\<in> \\<G>}) \\<Longrightarrow> G \\<subseteq> ?V\"\n      by (smt (verit, del_insts) elem_mset_set empty_iff infinite_set_mset_mset_set mem_Collect_eq)\n    then show \"\\<And>b. b \\<in># \\<B> \\<or> b \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> b \\<subseteq> insert x \\<V>\" \n      using wellformed add_point_def by fastforce\n  next \n    have \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> insert x G \\<noteq> {}\" using group_partitions\n      using partition_onD3 by auto \n    then have gnempty: \"\\<And> G. G \\<in># (mset_set { insert x g | g. g \\<in> \\<G>}) \\<Longrightarrow> G \\<noteq> {}\"\n      by (smt (verit, del_insts) elem_mset_set empty_iff infinite_set_mset_mset_set mem_Collect_eq)\n    then show \"\\<And>bl. bl \\<in># \\<B> \\<or> bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> bl \\<noteq> {}\" \n      using blocks_nempty by auto\n  next\n    have \"card \\<V> \\<ge> 2\" using gdd_min_v by simp \n    then have \"card (insert x \\<V>) \\<ge> 2\"\n      by (meson card_insert_le dual_order.trans finite_sets) \n    then show \"2 \\<le> (card (insert x \\<V>))\" by auto\n  next\n    show \"\\<And>ps. ps \\<subseteq> insert x \\<V> \\<Longrightarrow>\n          card ps = 2 \\<Longrightarrow> (\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = Suc 0\" \n      using kgdd1_index_adjoin_group_block by (simp add: assms) \n  qed\nqed\n\nlemma PBD_by_adjoining_point: \n  assumes \"x \\<notin> \\<V>\"\n  assumes \"\\<And> k . k \\<in> \\<K> \\<Longrightarrow> k \\<ge> 2\"\n  shows \"PBD (add_point x) (\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}) (\\<K> \\<union> {(card g) + 1 | g . g \\<in> \\<G>})\"\nproof -\n  let ?B = \"\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}\"\n  let ?V = \"(add_point x)\"\n  interpret inc: pairwise_balance ?V ?B 1 using pairwise_by_adjoining_point assms by auto \n  show ?thesis using  block_sizes positive_ints proof (unfold_locales)\n    have xg: \"\\<And> g. g \\<in> \\<G> \\<Longrightarrow> x \\<notin> g\"\n      using assms point_in_group by auto \n    have \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> card bl \\<in> \\<K>\" by (simp add: block_sizes) \n    have \"\\<And> bl . bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> bl \\<in> {insert x g | g . g \\<in> \\<G>}\"\n      by (simp add: groups_finite) \n    then have \"\\<And> bl . bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> \n      card bl \\<in>  {(card g + 1) |g. g \\<in> \\<G>}\" \n    proof -\n      fix bl \n      assume \"bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>}\"\n      then have \"bl \\<in> {insert x g | g . g \\<in> \\<G>}\" by (simp add: groups_finite)\n      then obtain g where gin: \"g \\<in> \\<G>\" and i: \"bl = insert x g\" by auto \n      thus \"card bl \\<in>  {(card g + 1) |g. g \\<in> \\<G>}\"\n        using gin group_elements_finite i xg by auto\n    qed\n    then show \"\\<And>bl. bl \\<in># \\<B> + mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> \n        (card bl) \\<in> \\<K> \\<union> {(card g + 1) |g. g \\<in> \\<G>}\"\n      using  UnI1 UnI2 block_sizes union_iff by (smt (z3) mem_Collect_eq)\n    show \"\\<And>x. x \\<in> \\<K> \\<union> { (card g + 1) |g. g \\<in> \\<G>} \\<Longrightarrow> 0 < x\" \n      using min_group_size positive_ints by auto\n    show \"\\<And>k.  k \\<in> \\<K> \\<union> {(card g + 1) |g. g \\<in> \\<G>} \\<Longrightarrow> 2 \\<le> k\" \n      using min_group_size positive_ints assms by fastforce\n  qed\nqed\n\nsubsubsection \\<open>Wilson's Construction\\<close>\ntext \\<open>Wilson's construction involves the combination of multiple k-GDD's. This proof was\nbased of Stinson \\cite{stinsonCombinatorialDesignsConstructions2004}\\<close>\n\nlemma wilsons_construction_proper: \n  assumes \"card I = w\"\n  assumes \"w > 0\"\n  assumes \"\\<And> n. n \\<in> \\<K>' \\<Longrightarrow> n \\<ge> 2\"\n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  shows \"proper_design (\\<V> \\<times> I) (\\<Sum>B \\<in># \\<B>. (f B))\" (is \"proper_design ?Y ?B\")\nproof (unfold_locales, simp_all)\n  show \"\\<And>b. \\<exists>x\\<in>#\\<B>. b \\<in># f x \\<Longrightarrow> b \\<subseteq> \\<V> \\<times> I\"\n  proof -\n    fix b\n    assume \"\\<exists>x\\<in>#\\<B>. b \\<in># f x\"\n    then obtain B where \"B \\<in># \\<B>\" and \"b \\<in># (f B)\" by auto\n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by auto\n    show \"b \\<subseteq> \\<V> \\<times> I\" using kgdd.wellformed\n      using \\<open>B \\<in># \\<B>\\<close> \\<open>b \\<in># f B\\<close> wellformed by fastforce \n  qed\n  show \"finite (\\<V> \\<times> I)\" using finite_sets assms bot_nat_0.not_eq_extremum card.infinite by blast \n  show \"\\<And>bl. \\<exists>x\\<in>#\\<B>. bl \\<in># f x \\<Longrightarrow> bl \\<noteq> {}\"\n  proof -\n    fix bl\n    assume \"\\<exists>x\\<in>#\\<B>. bl \\<in># f x\"\n    then obtain B where \"B \\<in># \\<B>\" and \"bl \\<in># (f B)\" by auto\n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by auto\n    show \"bl \\<noteq> {}\" using kgdd.blocks_nempty by (simp add: \\<open>bl \\<in># f B\\<close>) \n  qed\n  show \"\\<exists>i\\<in>#\\<B>. f i \\<noteq> {#}\"\n  proof -\n    obtain B where \"B \\<in># \\<B>\"\n      using design_blocks_nempty by auto \n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by auto\n    have \"f B \\<noteq> {#}\" using kgdd.design_blocks_nempty by simp \n    then show \"\\<exists>i\\<in>#\\<B>. f i \\<noteq> {#}\" using \\<open>B \\<in># \\<B>\\<close> by auto \n  qed\nqed\n\nlemma pair_construction_block_sizes: \n  assumes \"K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  assumes \"B \\<in># \\<B>\"\n  assumes \"b \\<in># (f B)\"\n  shows \"card b \\<in> \\<K>'\"\nproof -\n  interpret bkgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\"\n    using assms by simp\n  show \"card b \\<in> \\<K>'\" using bkgdd.block_sizes by (simp add:assms) \nqed\n\nlemma wilsons_construction_index_0: \n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  assumes \"G \\<in> {GG \\<times> I |GG. GG \\<in> \\<G>}\"\n  assumes \"X \\<in> G\" \n  assumes \"Y \\<in> G\" \n  assumes \"X \\<noteq> Y\"\n  shows \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y} = 0\"\nproof -\n  obtain G' where gi: \"G = G' \\<times> I\" and ging: \"G' \\<in> \\<G>\" using assms by auto\n  obtain x y ix iy where xpair: \"X = (x, ix)\" and ypair: \"Y = (y, iy)\" using assms by auto\n  then have ixin: \"ix \\<in> I\" and xing: \"x \\<in> G'\" using assms gi by auto \n  have iyin: \"iy \\<in> I\" and ying: \"y \\<in> G'\" using assms ypair gi by auto\n  have ne_index_0: \"x \\<noteq> y \\<Longrightarrow> \\<B> index {x, y} = 0\" \n    using ying xing index_together ging by simp\n  have \"\\<And> B. B \\<in># \\<B> \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\" \n  proof -\n    fix B\n    assume assm: \"B \\<in># \\<B>\"\n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by simp\n    have not_ss_0: \"\\<not> ({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I)) \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\"\n      by (metis kgdd.points_index_ps_nin) \n    have \"x \\<noteq> y \\<Longrightarrow> \\<not> {x, y} \\<subseteq> B\" using ne_index_0 assm points_index_0_left_imp by auto \n    then have \"x \\<noteq> y \\<Longrightarrow> \\<not> ({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I))\" using assms\n      by (meson empty_subsetI insert_subset mem_Sigma_iff)\n    then have nexy: \"x \\<noteq> y \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\" using not_ss_0 by simp\n    have \"x = y \\<Longrightarrow> ({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I)) \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\"\n    proof -\n      assume eq: \"x = y\"\n      assume \"({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I))\"\n      then obtain g where \"g \\<in> {{x} \\<times> I |x . x \\<in> B }\" and \"(x, ix) \\<in> g\" and \"(y, ix) \\<in> g\"\n        using eq  by auto \n      then show ?thesis using kgdd.index_together\n        by (smt (verit, best) SigmaD1 SigmaD2 SigmaI assms(4) assms(5) gi mem_Collect_eq xpair ypair)\n    qed\n    then show \"(f B) index {(x, ix), (y, iy)} = 0\" using not_ss_0 nexy by auto\n  qed\n  then have \"\\<And> B. B \\<in># (image_mset f \\<B>) \\<Longrightarrow> B index {(x, ix), (y, iy)} = 0\" by auto\n  then show \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y} = 0\" \n    by (simp add: points_index_sum xpair ypair)\nqed\n\nlemma wilsons_construction_index_1: \n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  assumes \"G1 \\<in> {G \\<times> I |G. G \\<in> \\<G>}\"\n  assumes \"G2 \\<in> {G \\<times> I |G. G \\<in> \\<G>}\"\n  assumes \"G1 \\<noteq> G2\"\n  and \"(x, ix) \\<in> G1\" and \"(y, iy) \\<in> G2\" \n  shows \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {(x, ix), (y, iy)} = (1 ::int)\"\nproof -\n  obtain G1' where gi1: \"G1 = G1' \\<times> I\" and ging1: \"G1' \\<in> \\<G>\" using assms by auto\n  obtain G2' where gi2: \"G2 = G2' \\<times> I\" and ging2: \"G2' \\<in> \\<G>\" using assms by auto\n  have xing: \"x \\<in> G1'\" using assms gi1 by simp\n  have ying: \"y \\<in> G2'\" using assms gi2 by simp\n  have gne: \"G1' \\<noteq> G2'\" using assms gi1 gi2 by auto\n  then have xyne: \"x \\<noteq> y\" using xing ying ging1 ging2 point_in_one_group by blast\n  have \"\\<exists>! bl . bl \\<in># \\<B> \\<and> {x, y} \\<subseteq> bl\" using index_distinct points_index_one_unique_block\n    by (metis ging1 ging2 gne of_nat_1_eq_iff xing ying) \n  then obtain bl where blinb:\"bl \\<in># \\<B>\" and xyblss: \"{x, y} \\<subseteq> bl\" by auto \n  then have \"\\<And> b . b \\<in># \\<B> - {#bl#} \\<Longrightarrow> \\<not> {x, y} \\<subseteq> b\" using points_index_one_not_unique_block\n    by (metis ging1 ging2 gne index_distinct int_ops(2) nat_int_comparison(1) xing ying) \n  then have not_ss: \"\\<And> b . b \\<in># \\<B> - {#bl#} \\<Longrightarrow> \\<not> ({(x, ix), (y, iy)} \\<subseteq> (b \\<times> I))\" using assms\n    by (meson SigmaD1 empty_subsetI insert_subset)\n  then have pi0: \"\\<And> b . b \\<in># \\<B> - {#bl#} \\<Longrightarrow> (f b) index {(x, ix), (y, iy)}  = 0\"\n  proof -\n    fix b\n    assume assm: \"b \\<in># \\<B> - {#bl#}\"\n    then have \"b \\<in># \\<B>\" by (meson in_diffD) \n    then interpret kgdd: K_GDD \"(b \\<times> I)\" \"(f b)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> b }\" using assms by simp\n    show \"(f b) index {(x, ix), (y, iy)} = 0\"\n      using assm not_ss by (metis kgdd.points_index_ps_nin) \n  qed\n  let ?G = \"{{x} \\<times> I |x . x \\<in> bl }\"\n  interpret bkgdd: K_GDD \"(bl \\<times> I)\" \"(f bl)\" \\<K>' ?G using assms blinb by simp\n  obtain g1 g2 where xing1: \"(x, ix) \\<in> g1\" and ying2: \"(y, iy) \\<in> g2\" and g1g: \"g1 \\<in> ?G\" \n      and g2g: \"g2 \\<in> ?G\" using assms(5) assms(6) gi1 gi2\n    by (metis (no_types, lifting) bkgdd.point_has_unique_group insert_subset mem_Sigma_iff xyblss) \n  then have \"g1 \\<noteq> g2\" using xyne by blast \n  then have pi1: \"(f bl) index {(x, ix), (y, iy)} = 1\" \n    using bkgdd.index_distinct xing1 ying2 g1g g2g by simp\n  have \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {(x, ix), (y, iy)} = \n      (\\<Sum>B \\<in># \\<B>. (f B) index {(x, ix), (y, iy)} )\" \n    by (simp add: points_index_sum)\n  then have \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {(x, ix), (y, iy)} = \n      (\\<Sum>B \\<in># (\\<B> - {#bl#}). (f B) index {(x, ix), (y, iy)}) + (f bl) index {(x, ix), (y, iy)}\"\n    by (metis (no_types, lifting) add.commute blinb insert_DiffM sum_mset.insert) \n  thus ?thesis using pi0 pi1 by simp\nqed\n\ntheorem Wilsons_Construction:\n  assumes \"card I = w\"\n  assumes \"w > 0\"\n  assumes \"\\<And> n. n \\<in> \\<K>' \\<Longrightarrow> n \\<ge> 2\"\n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  shows \"K_GDD (\\<V> \\<times> I) (\\<Sum>B \\<in># \\<B>. (f B)) \\<K>' {G \\<times> I | G . G \\<in> \\<G>}\"\nproof -\n  let ?Y = \"\\<V> \\<times> I\" and ?H = \"{G \\<times> I | G . G \\<in> \\<G>}\" and ?B = \"\\<Sum>B \\<in># \\<B>. (f B)\"\n  interpret pd: proper_design ?Y ?B using wilsons_construction_proper assms by auto\n  have \"\\<And> bl . bl \\<in># (\\<Sum>B \\<in># \\<B>. (f B)) \\<Longrightarrow> card bl \\<in> \\<K>'\"  \n    using assms pair_construction_block_sizes by blast \n  then interpret kdes: K_block_design ?Y ?B \\<K>' \n    using assms(3) by (unfold_locales) (simp_all,fastforce)\n  interpret gdd: GDD ?Y ?B ?H \"1:: int\" \n  proof (unfold_locales)\n    show \"partition_on (\\<V> \\<times> I) {G \\<times> I |G. G \\<in> \\<G>}\" \n      using assms groups_not_empty design_points_nempty group_partitions\n      by (simp add: partition_on_cart_prod) \n    have \"inj_on (\\<lambda> G. G \\<times> I) \\<G>\"\n      using inj_on_def pd.design_points_nempty by auto \n    then have \"card {G \\<times> I |G. G \\<in> \\<G>} = card \\<G>\" using card_image by (simp add: Setcompr_eq_image) \n    then show \"1 < card {G \\<times> I |G. G \\<in> \\<G>}\" using groups_size by linarith \n    show \"(1::int) \\<le> 1\" by simp\n    have gdd_fact: \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\" \n      using assms by simp\n    show \"\\<And>G X Y. G \\<in> {GG \\<times> I |GG. GG \\<in> \\<G>} \\<Longrightarrow> X \\<in> G \\<Longrightarrow> Y \\<in> G \\<Longrightarrow> X \\<noteq> Y \n        \\<Longrightarrow> (\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y} = 0\"\n      using wilsons_construction_index_0[OF assms(4)] by auto\n    show \"\\<And>G1 G2 X Y. G1 \\<in> {G \\<times> I |G. G \\<in> \\<G>} \\<Longrightarrow> G2 \\<in> {G \\<times> I |G. G \\<in> \\<G>} \n      \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> X \\<in> G1 \\<Longrightarrow> Y \\<in> G2 \\<Longrightarrow> ((\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y}) = (1 ::int)\"\n      using wilsons_construction_index_1[OF assms(4)] by blast \n  qed\n  show ?thesis by (unfold_locales)\nqed\n\nend\n\ncontext pairwise_balance\nbegin\n\nlemma PBD_by_deleting_point: \n  assumes \"\\<v> > 2\"\n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2\"\n  shows \"pairwise_balance (del_point x) (del_point_blocks x) \\<Lambda>\"\nproof (cases \"x \\<in> \\<V>\")\n  case True\n  interpret des: design \"del_point x\" \"del_point_blocks x\"\n    using delete_point_design assms by blast \n  show ?thesis using assms design_blocks_nempty del_point_def del_point_blocks_def\n  proof (unfold_locales, simp_all)\n    show \"2 < \\<v> \\<Longrightarrow> (\\<And>bl. bl \\<in># \\<B> \\<Longrightarrow> 2 \\<le> card bl) \\<Longrightarrow> 2 \\<le> (card (\\<V> - {x}))\"\n      using card_Diff_singleton_if diff_diff_cancel diff_le_mono2 finite_sets less_one\n      by fastforce\n    have \"\\<And> ps . ps  \\<subseteq> \\<V> - {x} \\<Longrightarrow> ps \\<subseteq> \\<V>\" by auto\n    then show \"\\<And>ps. ps \\<subseteq> \\<V> - {x} \\<Longrightarrow> card ps = 2  \\<Longrightarrow> {#bl - {x}. bl \\<in># \\<B>#} index ps = \\<Lambda>\"\n      using delete_point_index_eq del_point_def del_point_blocks_def by simp\n  qed\nnext\n  case False\n  then show ?thesis\n    by (simp add: del_invalid_point del_invalid_point_blocks pairwise_balance_axioms)\nqed\nend\n\ncontext k_GDD\nbegin\n\nlemma bibd_from_kGDD:\n  assumes \"\\<k> > 1\"\n  assumes \"\\<And> g. g \\<in> \\<G> \\<Longrightarrow> card g = \\<k> - 1\"\n  assumes \" x \\<notin> \\<V>\"\n  shows \"bibd (add_point x) (\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}) (\\<k>) 1\"\nproof - \n  have \"\\<And> k . k\\<in> {\\<k>} \\<Longrightarrow> k = \\<k>\"\n    by blast \n  then have kge: \"\\<And> k . k\\<in> {\\<k>} \\<Longrightarrow> k \\<ge> 2\" using assms(1) by simp\n  have \"\\<And> g . g \\<in> \\<G> \\<Longrightarrow> card g + 1 = \\<k>\" using assms k_non_zero\n    by auto \n  then have s: \"({\\<k>} \\<union> {(card g) + 1 | g . g \\<in> \\<G>}) = {\\<k>}\"\n    by auto\n  then interpret pbd: PBD \"(add_point x)\" \"\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}\" \"{\\<k>}\"\n    using PBD_by_adjoining_point[of \"x\"] kge assms by (smt (z3) Collect_cong)\n  show ?thesis using assms pbd.block_sizes block_size_lt_v finite_sets add_point_def\n    by (unfold_locales) (simp_all)\nqed\n\nend\n\ncontext PBD \nbegin\n\nlemma pbd_points_index1: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 1\"\n  using balanced by simp\n\nlemma pbd_index1_points_imply_unique_block: \n  assumes \"b1 \\<in># \\<B>\" and \"b2 \\<in># \\<B>\" and \"b1 \\<noteq> b2\"\n  assumes \"x \\<noteq> y\" and \"{x, y} \\<subseteq> b1\" and \"x \\<in> b2\" \n  shows \"y \\<notin> b2\"\nproof (rule ccontr)\n  let ?ps = \"{# b \\<in># \\<B> . {x, y} \\<subseteq> b#}\"\n  assume \"\\<not> y \\<notin> b2\"\n  then have a: \"y \\<in> b2\" by linarith\n  then have \"{x, y} \\<subseteq> b2\"\n    by (simp add: assms(6)) \n  then have \"b1 \\<in># ?ps\" and \"b2 \\<in># ?ps\" using assms by auto\n  then have ss: \"{#b1, b2#} \\<subseteq># ?ps\" using assms\n    by (metis insert_noteq_member mset_add mset_subset_eq_add_mset_cancel single_subset_iff) \n  have \"size {#b1, b2#} = 2\" using assms by auto\n  then have ge2: \"size ?ps \\<ge> 2\" using assms ss by (metis size_mset_mono) \n  have pair: \"card {x, y} = 2\" using assms by auto\n  have \"{x, y} \\<subseteq> \\<V>\" using assms wellformed by auto\n  then have \"\\<B> index {x, y} = 1\" using pbd_points_index1 pair by simp\n  then show False using points_index_def ge2\n    by (metis numeral_le_one_iff semiring_norm(69)) \nqed\n\nlemma strong_delete_point_groups_index_zero: \n  assumes \"G \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n  assumes \"xa \\<in> G\" and \"y \\<in> G\" and \"xa \\<noteq> y\"\n  shows \"(str_del_point_blocks x) index {xa, y} = 0\"\nproof (auto simp add: points_index_0_iff str_del_point_blocks_def)\n  fix b\n  assume a1: \"b \\<in># \\<B>\" and a2: \"x \\<notin> b\" and a3: \"xa \\<in> b\" and a4: \"y \\<in> b\"\n  obtain b' where \"G = b' - {x}\" and \"b' \\<in># \\<B>\" and  \"x \\<in> b'\" using assms by blast\n  then show False using a1 a2 a3 a4 assms pbd_index1_points_imply_unique_block\n    by fastforce \nqed\n\nlemma strong_delete_point_groups_index_one: \n  assumes \"G1 \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n  assumes \"G2 \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n  assumes \"G1 \\<noteq> G2\" and \"xa \\<in> G1\" and \"y \\<in> G2\"\n  shows  \"(str_del_point_blocks x) index {xa, y} = 1\"\nproof -\n  obtain b1 where gb1: \"G1 = b1 - {x}\" and b1in: \"b1 \\<in># \\<B>\" and xin1: \"x \\<in> b1\" using assms by blast\n  obtain b2 where gb2: \"G2 = b2 - {x}\" and b2in: \"b2 \\<in># \\<B>\" and xin2:\"x \\<in> b2\" using assms by blast\n  have bneq: \"b1 \\<noteq> b2 \" using assms(3) gb1 gb2 by auto\n  have \"xa \\<noteq> y\" using gb1 b1in xin1 gb2 b2in xin2 assms(3) assms(4) assms(5) insert_subset\n    by (smt (verit, best) Diff_eq_empty_iff Diff_iff empty_Diff insertCI pbd_index1_points_imply_unique_block) \n  then have pair: \"card {xa, y} = 2\" by simp \n  have inv: \"{xa, y} \\<subseteq> \\<V>\" using gb1 b1in gb2 b2in assms(4) assms(5)\n    by (metis Diff_cancel Diff_subset insert_Diff insert_subset wellformed) \n  have \"{# bl \\<in># \\<B> . x \\<in> bl#} index {xa, y} = 0\"\n  proof (auto simp add: points_index_0_iff)\n    fix b assume a1: \"b \\<in># \\<B>\" and a2: \"x \\<in> b\" and a3: \"xa \\<in> b\" and a4: \"y \\<in> b\"\n    then have yxss: \"{y, x} \\<subseteq> b2\"\n      using assms(5) gb2 xin2 by blast \n    have \"{xa, x} \\<subseteq> b1\"\n      using assms(4) gb1 xin1 by auto \n    then have \"xa \\<notin> b2\" using pbd_index1_points_imply_unique_block\n      by (metis DiffE assms(4) b1in b2in bneq gb1 singletonI xin2) \n    then have \"b2 \\<noteq> b\" using a3 by auto \n    then show False using pbd_index1_points_imply_unique_block\n      by (metis DiffD2 yxss a1 a2 a4 assms(5) b2in gb2 insertI1) \n  qed\n  then have \"(str_del_point_blocks x) index {xa, y} = \\<B> index {xa, y}\" \n    by (metis multiset_partition plus_nat.add_0 point_index_distrib str_del_point_blocks_def) \n  thus ?thesis using pbd_points_index1 pair inv by fastforce\nqed\n\nlemma blocks_with_x_partition: \n  assumes \"x \\<in> \\<V>\"\n  shows \"partition_on (\\<V> - {x}) {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\nproof (intro partition_onI )\n  have gtt: \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2\" using block_size_gt_t\n    by (simp add: block_sizes nat_int_comparison(3)) \n  show \"\\<And>p. p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} \\<Longrightarrow> p \\<noteq> {}\"\n  proof -\n    fix p assume \"p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n    then obtain b where ptx: \"p = b - {x}\" and \"b \\<in># \\<B>\" and xinb: \"x \\<in> b\" by blast\n    then have ge2: \"card b \\<ge> 2\" using gtt by (simp add: nat_int_comparison(3)) \n    then have \"finite b\" by (metis card.infinite not_numeral_le_zero) \n    then have \"card p = card b - 1\" using xinb ptx by simp\n    then have \"card p \\<ge> 1\" using ge2 by linarith\n    thus \"p \\<noteq> {}\" by auto\n  qed\n  show \"\\<Union> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} = \\<V> - {x}\"\n  proof (intro subset_antisym subsetI)\n    fix xa\n    assume \"xa \\<in> \\<Union> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" \n    then obtain b where \"xa \\<in> b\" and \"b \\<in># \\<B>\" and \"x \\<in> b\" and \"xa \\<noteq> x\" by auto\n    then show \"xa \\<in> \\<V> - {x}\" using wf_invalid_point by blast \n  next \n    fix xa\n    assume a: \"xa \\<in> \\<V> - {x}\"\n    then have nex: \"xa \\<noteq> x\" by simp\n    then have pair: \"card {xa, x} = 2\" by simp \n    have \"{xa, x} \\<subseteq> \\<V>\" using a assms by auto \n    then have \"card {b \\<in> design_support . {xa, x} \\<subseteq> b} = 1\" \n      using balanced points_index_simple_def pbd_points_index1 assms by (metis pair) \n    then obtain b where des: \"b \\<in> design_support\" and ss: \"{xa, x} \\<subseteq> b\"\n      by (metis (no_types, lifting) card_1_singletonE mem_Collect_eq singletonI)\n    then show \"xa \\<in> \\<Union> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n      using des ss nex design_support_def by auto\n  qed\n  show \"\\<And>p p'. p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} \\<Longrightarrow> p' \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} \\<Longrightarrow> \n    p \\<noteq> p' \\<Longrightarrow> p \\<inter> p' = {}\" \n  proof -\n    fix p p'\n    assume p1: \"p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" and p2: \"p' \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" \n      and pne: \"p \\<noteq> p'\"\n    then obtain b where b1: \"p = b - {x}\" and b1in:\"b \\<in># \\<B>\" and xinb1:\"x \\<in> b\" by blast \n    then obtain b' where b2: \"p' = b' - {x}\" and b2in: \"b' \\<in># \\<B>\" and xinb2: \"x \\<in> b'\"\n      using p2 by blast\n    then have \"b \\<noteq> b'\" using pne b1 by auto\n    then have \"\\<And> y. y \\<in> b \\<Longrightarrow> y \\<noteq> x \\<Longrightarrow> y \\<notin> b'\" \n      using b1in b2in xinb1 xinb2 pbd_index1_points_imply_unique_block\n      by (meson empty_subsetI insert_subset) \n    then have \"\\<And> y. y \\<in> p \\<Longrightarrow> y \\<notin> p'\"\n      by (metis Diff_iff b1 b2 insertI1) \n    then show \"p \\<inter> p' = {}\" using disjoint_iff by auto\n  qed\nqed\n\nlemma KGDD_by_deleting_point:\n  assumes \"x \\<in> \\<V>\"\n  assumes \"\\<B> rep x < \\<b>\"\n  assumes \"\\<B> rep x > 1\" \n  shows \"K_GDD (del_point x) (str_del_point_blocks x) \\<K> { b - {x} | b . b \\<in># \\<B> \\<and> x \\<in> b}\"\nproof -\n  have \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2\" using block_size_gt_t \n    by (simp add: block_sizes nat_int_comparison(3))\n  then interpret des: proper_design \"(del_point x)\" \"(str_del_point_blocks x)\" \n    using strong_delete_point_proper assms by blast\n  show ?thesis using blocks_with_x_partition strong_delete_point_groups_index_zero \n      strong_delete_point_groups_index_one str_del_point_blocks_def del_point_def\n  proof (unfold_locales, simp_all add: block_sizes positive_ints assms) \n    have ge1: \"card {b . b \\<in># \\<B> \\<and> x \\<in> b} > 1\" \n      using assms(3) replication_num_simple_def design_support_def by auto\n    have fin: \"finite {b . b \\<in># \\<B> \\<and> x \\<in> b}\" by simp \n    have inj: \"inj_on (\\<lambda> b . b - {x}) {b . b \\<in># \\<B> \\<and> x \\<in> b}\" \n      using assms(2) inj_on_def mem_Collect_eq by auto \n    then have \"card {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} = card {b . b \\<in># \\<B> \\<and> x \\<in> b}\" \n      using card_image fin by (simp add: inj card_image setcompr_eq_image)\n    then show \"Suc 0 < card {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" using ge1\n      by presburger \n  qed\nqed\n\nlemma card_singletons_eq: \"card {{a} | a . a \\<in> A} = card A\"\n  by (simp add: card_image Setcompr_eq_image)\n\nlemma KGDD_from_PBD: \"K_GDD \\<V> \\<B> \\<K> {{x} | x . x \\<in> \\<V>}\"\nproof (unfold_locales,auto simp add: Setcompr_eq_image partition_on_singletons)\n  have \"card ((\\<lambda>x. {x}) ` \\<V>) \\<ge> 2\" using t_lt_order card_singletons_eq\n    by (metis Collect_mem_eq setcompr_eq_image) \n  then show \"Suc 0 < card ((\\<lambda>x. {x}) ` \\<V>)\" by linarith\n  show \"\\<And>xa xb. xa \\<in> \\<V> \\<Longrightarrow> xb \\<in> \\<V> \\<Longrightarrow> \\<B> index {xa, xb} \\<noteq> Suc 0 \\<Longrightarrow> xa = xb\"\n  proof (rule ccontr)\n    fix xa xb\n    assume ain: \"xa \\<in> \\<V>\" and bin: \"xb \\<in> \\<V>\" and ne1: \"\\<B> index {xa, xb} \\<noteq> Suc 0\"\n    assume \"xa \\<noteq> xb\"\n    then have \"card {xa, xb} = 2\" by auto\n    then have \"\\<B> index {xa, xb} = 1\"\n      by (simp add: ain bin) \n    thus False using ne1 by linarith\n  qed \nqed\n\nend\n\ncontext bibd\nbegin\nlemma kGDD_from_bibd:\n  assumes \"\\<Lambda> = 1\"\n  assumes \"x \\<in> \\<V>\"\n  shows \"k_GDD (del_point x) (str_del_point_blocks x) \\<k> { b - {x} | b . b \\<in># \\<B> \\<and> x \\<in> b}\"\nproof -\n  interpret pbd: PBD \\<V> \\<B> \"{\\<k>}\" using assms\n    using PBD.intro \\<Lambda>_PBD_axioms by auto \n  have lt: \"\\<B> rep x < \\<b>\" using block_num_gt_rep\n    by (simp add: assms(2)) \n  have \"\\<B> rep x > 1\" using r_ge_two assms by simp\n  then interpret kgdd: K_GDD \"(del_point x)\" \"str_del_point_blocks x\" \n    \"{\\<k>}\" \"{ b - {x} | b . b \\<in># \\<B> \\<and> x \\<in> b}\"\n    using pbd.KGDD_by_deleting_point lt assms by blast \n  show ?thesis using del_point_def str_del_point_blocks_def by (unfold_locales) (simp_all)\nqed\n\nend\nend", "meta": {"author": "cledmonds", "repo": "design-theory", "sha": "399b979e974b4a894d2c8803f6761836dffbec7a", "save_path": "github-repos/isabelle/cledmonds-design-theory", "path": "github-repos/isabelle/cledmonds-design-theory/design-theory-399b979e974b4a894d2c8803f6761836dffbec7a/src/Group_Divisible_Designs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8670357477770337, "lm_q1q2_score": 0.7758144465474892}}
{"text": "section \\<open>Differentiable/Smooth Manifolds\\<close>\ntheory Differentiable_Manifold\n  imports\n    Smooth\n    Topological_Manifold\nbegin\n\nsubsection \\<open>Smooth compatibility\\<close>\n\ndefinition smooth_compat::\"enat \\<Rightarrow> ('a::topological_space, 'e::euclidean_space)chart\\<Rightarrow>('a, 'e)chart\\<Rightarrow>bool\"\n  (\"_-smooth'_compat\" [1000])\n  where\n  \"smooth_compat k c1 c2 \\<longleftrightarrow>\n    (k-smooth_on (c1 ` (domain c1 \\<inter> domain c2)) (c2 \\<circ> inv_chart c1) \\<and>\n     k-smooth_on (c2 ` (domain c1 \\<inter> domain c2)) (c1 \\<circ> inv_chart c2) )\"\n\nlemma smooth_compat_D1:\n  \"k-smooth_on (c1 ` (domain c1 \\<inter> domain c2)) (c2 \\<circ> inv_chart c1)\"\n  if \"k-smooth_compat c1 c2\"\nproof -\n  have \"open (c1 ` (domain c1 \\<inter> domain c2))\"\n    by (rule open_chart_image) auto\n  moreover have \"k-smooth_on (c1 ` (domain c1 \\<inter> domain c2)) (c2 \\<circ> inv_chart c1)\"\n    using that(1) by (auto simp: smooth_compat_def)\n  ultimately show ?thesis by blast\nqed\n\nlemma smooth_compat_D2:\n  \"k-smooth_on (c2 ` (domain c1 \\<inter> domain c2)) (c1 \\<circ> inv_chart c2)\"\n  if \"k-smooth_compat c1 c2\"\nproof -\n  have \"open (c2 ` (domain c1 \\<inter> domain c2))\"\n    by (rule open_chart_image) auto\n  moreover have \"k-smooth_on (c2 ` (domain c1 \\<inter> domain c2)) (c1 \\<circ> inv_chart c2) \"\n    using that(1) by (auto simp: smooth_compat_def)\n  ultimately show ?thesis by blast\nqed\n\nlemma smooth_compat_refl: \"k-smooth_compat x x\"\n  unfolding smooth_compat_def\n  by (auto intro: smooth_on_cong[where g=\"\\<lambda>x. x\"] simp: smooth_on_id)\n\nlemma smooth_compat_commute: \"k-smooth_compat x y \\<longleftrightarrow> k-smooth_compat y x\"\n  by (auto simp: smooth_compat_def inf_commute)\n\nlemma smooth_compat_restrict_chartI:\n  \"k-smooth_compat (restrict_chart S c) c'\"\n  if \"k-smooth_compat c c'\"\n  using that\n  by (auto simp: smooth_compat_def domain_restrict_chart_if intro: smooth_on_subset)\n\nlemma smooth_compat_restrict_chartI2:\n  \"k-smooth_compat c' (restrict_chart S c)\"\n  if \"k-smooth_compat c' c\"\n  using smooth_compat_restrict_chartI[of k c c'] that\n  by (auto simp: smooth_compat_commute)\n\nlemma smooth_compat_restrict_chartD:\n  \"domain c1 \\<subseteq> U \\<Longrightarrow> open U \\<Longrightarrow> k-smooth_compat c1 (restrict_chart U c2) \\<Longrightarrow> k-smooth_compat c1 c2\"\n  by (auto simp: smooth_compat_def domain_restrict_chart_if intro: smooth_on_subset)\n\nlemma smooth_compat_restrict_chartD2:\n  \"domain c1 \\<subseteq> U \\<Longrightarrow> open U \\<Longrightarrow> k-smooth_compat (restrict_chart U c2) c1 \\<Longrightarrow> k-smooth_compat c2 c1\"\n  using smooth_compat_restrict_chartD[of c1 U k c2]\n  by (auto simp: smooth_compat_commute)\n\nlemma smooth_compat_le:\n  \"l-smooth_compat c1 c2\" if \"k-smooth_compat c1 c2\" \"l \\<le> k\"\n  using that\n  by (auto simp: smooth_compat_def smooth_on_le)\n\n\nsubsection \\<open>\\<open>C^k\\<close>-Manifold\\<close>\n\nlocale c_manifold = manifold +\n  fixes k::enat\n  assumes pairwise_compat: \"c1 \\<in> charts \\<Longrightarrow> c2 \\<in> charts \\<Longrightarrow> k-smooth_compat c1 c2\"\nbegin\n\n\nsubsubsection \\<open>Atlas\\<close>\n\ndefinition atlas :: \"('a, 'b) chart set\" where\n  \"atlas = {c. domain c \\<subseteq> carrier \\<and> (\\<forall>c' \\<in> charts. k-smooth_compat c c')}\"\n\nlemma charts_subset_atlas: \"charts \\<subseteq> atlas\"\n  by (auto simp: atlas_def pairwise_compat)\n\nlemma in_charts_in_atlas[intro]: \"x \\<in> charts \\<Longrightarrow> x \\<in> atlas\"\n  by (auto simp: atlas_def pairwise_compat)\n\nlemma maximal_atlas:\n  \"c \\<in> atlas\"\n  if \"\\<And>c'. c' \\<in> atlas \\<Longrightarrow> k-smooth_compat c c'\"\n    \"domain c \\<subseteq> carrier\"\n  using that charts_subset_atlas\n  by (auto simp: atlas_def)\n\nlemma chart_compose_lemma:\n  fixes c1 c2\n  defines [simp]: \"U \\<equiv> domain c1\"\n  defines [simp]: \"V \\<equiv> domain c2\"\n  assumes subsets: \"U \\<inter> V \\<subseteq> carrier\"\n  assumes \"\\<And>c. c \\<in> charts \\<Longrightarrow> k-smooth_compat c1 c\"\n    \"\\<And>c. c \\<in> charts \\<Longrightarrow> k-smooth_compat c2 c\"\n  shows \"k-smooth_on (c1 ` (U \\<inter> V)) (c2 \\<circ> inv_chart c1)\"\nproof (rule smooth_on_open_subsetsI)\n  fix w' assume \"w' \\<in> c1 ` (U \\<inter> V)\"\n  then obtain w where w': \"w' = c1 w\" and \"w \\<in> U\" \"w \\<in> V\" by auto\n  then have \"w \\<in> carrier\" using subsets\n    by auto\n  then obtain c3 where c3: \"w \\<in> domain c3\" \"c3 \\<in> charts\"\n    by (rule carrierE)\n  then have c13: \"k-smooth_compat c1 c3\" and c23: \"k-smooth_compat c2 c3\"\n    using assms by auto\n  define W where [simp]: \"W = domain c3\"\n  have diff1: \"k-smooth_on (c1 ` (U \\<inter> W)) (c3 \\<circ> inv_chart c1)\"\n  proof -\n    have 1: \"open (c1 ` (U \\<inter> W))\"\n      by (rule open_chart_image) auto\n    have 2: \"w' \\<in> c1 ` (U \\<inter> W)\"\n      using \\<open>w \\<in> U\\<close> by (auto simp: c3 w')\n    from c13 show ?thesis\n      by (auto simp: smooth_compat_def)\n  qed\n\n  define y where \"y = (c3 \\<circ> inv_chart c1) w'\"\n  have diff2: \"k-smooth_on (c3 ` (V \\<inter> W)) (c2 \\<circ> inv_chart c3)\"\n  proof -\n    have 1: \"open (c3 ` (V \\<inter> W))\"\n      by (rule open_chart_image) auto\n    have 2: \"y \\<in> c3 ` (V \\<inter> W)\"\n      using \\<open>w \\<in> U\\<close> \\<open>w \\<in> V\\<close> by (auto simp: y_def c3 w')\n    from c23 show ?thesis\n      by (auto simp: smooth_compat_def)\n  qed\n  \n  have \"k-smooth_on (c1 ` (U \\<inter> V \\<inter> W)) ((c2 \\<circ> inv_chart c3) o (c3 \\<circ> inv_chart c1))\"\n    using diff2 diff1\n    by (rule smooth_on_compose2) auto\n  then have \"k-smooth_on (c1 ` (U \\<inter> V \\<inter> W)) (c2 \\<circ> inv_chart c1)\"\n    by (rule smooth_on_cong) auto\n  moreover have \"w' \\<in> c1 ` (U \\<inter> V \\<inter> W)\" \"open (c1 ` (U \\<inter> V \\<inter> W))\"\n    using \\<open>w \\<in> U\\<close> \\<open>w \\<in> V\\<close>\n    by (auto simp: w' c3)\n  ultimately show \"\\<exists>T. w' \\<in> T \\<and> open T \\<and> k-smooth_on T (apply_chart c2 \\<circ> inv_chart c1)\"\n    by (intro exI[where x=\"c1 ` (U \\<inter> V \\<inter> W)\"]) simp\nqed\n\nlemma smooth_compat_trans: \"k-smooth_compat c1 c2\"\n  if \"\\<And>c. c \\<in> charts \\<Longrightarrow> k-smooth_compat c1 c\"\n    \"\\<And>c. c \\<in> charts \\<Longrightarrow> k-smooth_compat c2 c\"\n    \"domain c1 \\<inter> domain c2 \\<subseteq> carrier\"\n  unfolding smooth_compat_def\nproof\n  show \"k-smooth_on (c1 ` (domain c1 \\<inter> domain c2)) (c2 \\<circ> inv_chart c1)\"\n    by (auto intro!: that chart_compose_lemma)\n  show \"k-smooth_on (c2 ` (domain c1 \\<inter> domain c2)) (c1 \\<circ> inv_chart c2)\"\n    using that\n    by (subst inf_commute) (auto intro!: chart_compose_lemma)\nqed\n\nlemma maximal_atlas':\n  \"c \\<in> atlas\"\n  if \"\\<And>c'. c' \\<in> charts \\<Longrightarrow> k-smooth_compat c c'\"\n    \"domain c \\<subseteq> carrier\"\nproof (rule maximal_atlas)\n  fix c' assume \"c' \\<in> atlas\"\n  show \"k-smooth_compat c c'\"\n    apply (rule smooth_compat_trans)\n      apply (rule that(1)) apply assumption\n    using atlas_def \\<open>c' \\<in> atlas\\<close> by auto\nqed fact\n\nlemma atlas_is_atlas: \"k-smooth_compat a1 a2\"\n  if \"a1 \\<in> atlas\" \"a2 \\<in> atlas\"\n  using that atlas_def smooth_compat_trans by blast\n\nlemma domain_atlas_subset_carrier: \"c \\<in> atlas \\<Longrightarrow> domain c \\<subseteq> carrier\"\n  and in_carrier_atlasI[intro, simp]: \"c \\<in> atlas \\<Longrightarrow> x \\<in> domain c \\<Longrightarrow> x \\<in> carrier\"\n  by (auto simp: atlas_def)\n\nlemma atlasE:\n  assumes \"x \\<in> carrier\"\n  obtains c where \"c \\<in> atlas\" \"x \\<in> domain c\"\n  using carrierE[OF assms] charts_subset_atlas\n  by blast\n\nlemma restrict_chart_in_atlas: \"restrict_chart S c \\<in> atlas\" if \"c \\<in> atlas\"\nproof (rule maximal_atlas)\n  fix c' assume \"c' \\<in> atlas\"\n  then have \"k-smooth_compat c c'\" using \\<open>c \\<in> atlas\\<close> by (auto simp: atlas_is_atlas)\n  then show \"k-smooth_compat (restrict_chart S c) c'\"\n    by (rule smooth_compat_restrict_chartI)\nnext\n  have \"domain (restrict_chart S c) \\<subseteq> domain c\"\n    by (simp add: domain_restrict_chart_if)\n  also have \"\\<dots> \\<subseteq> carrier\"\n    using that\n    by (rule domain_atlas_subset_carrier)\n  finally\n  show \"domain (restrict_chart S c) \\<subseteq> carrier\"\n    by auto\nqed\n\nlemma atlas_restrictE:\n  assumes \"x \\<in> carrier\" \"x \\<in> X\" \"open X\"\n  obtains c where \"c \\<in> atlas\" \"x \\<in> domain c\" \"domain c \\<subseteq> X\"\nproof -\n  from assms(1) obtain c where c: \"c \\<in> atlas\" \"x \\<in> domain c\"\n    by (blast elim!: carrierE)\n  define d where \"d = restrict_chart X c\"\n  from c have \"d \\<in> atlas\" \"x \\<in> domain d\" \"domain d \\<subseteq> X\"\n    using assms(2,3)\n    by (auto simp: d_def restrict_chart_in_atlas)\n  then show ?thesis ..\nqed\n\n\nlemma open_ball_chartE:\n  assumes \"x \\<in> U\" \"open U\" \"U \\<subseteq> carrier\"\n  obtains c r where\n    \"c \\<in> atlas\"\n    \"x \\<in> domain c\" \"domain c \\<subseteq> U\" \"codomain c = ball (c x) r\" \"r > 0\"\nproof -\n  from assms have \"x \\<in> carrier\" by auto\n  from carrierE[OF this] obtain c where c: \"c \\<in> charts\" \"x \\<in> domain c\" by auto\n  then have \"x \\<in> domain c \\<inter> U\" using assms by auto\n  then have \"open (apply_chart c ` (domain c \\<inter> U))\" \"c x \\<in> c ` (domain c \\<inter> U)\"\n    by (auto intro!: assms)\n  from openE[OF this]\n  obtain e where e: \"0 < e\" \"ball (c x) e \\<subseteq> c ` (domain c \\<inter> U)\"\n    by auto\n  define C where \"C = inv_chart c ` ball (c x) e\"\n  have \"open C\"\n    using e\n    by (auto simp: C_def)\n  define c' where \"c' = restrict_chart C c\"\n  from c have \"c \\<in> atlas\" by auto\n  then have \"c' \\<in> atlas\" by (auto simp: c'_def restrict_chart_in_atlas)\n  moreover\n  have \"x \\<in> C\"\n    using c \\<open>e > 0\\<close>\n    unfolding C_def\n    by (auto intro!: image_eqI[where x=\"apply_chart c x\"])\n  have \"x \\<in> domain c'\"\n    by (auto simp: c'_def \\<open>open C\\<close> c \\<open>x \\<in> C\\<close>)\n  moreover\n  have \"C \\<subseteq> U\"\n    using e by (auto simp: C_def)\n  then have \"domain c' \\<subseteq> U\"\n    by (auto simp: c'_def \\<open>open C\\<close>)\n  moreover have \"codomain c' = ball (c' x) e\"\n    using e \\<open>open C\\<close>\n    by (force simp: c'_def codomain_restrict_chart_if C_def)\n  moreover\n  have \"e > 0\"\n    by fact\n  ultimately show ?thesis ..\nqed\n\nlemma smooth_compat_compose_chart:\n  fixes c'\n  assumes \"k-smooth_compat c c'\"\n  assumes diffeo: \"diffeomorphism k UNIV UNIV p p'\"\n  shows \"k-smooth_compat (compose_chart p p' c) c'\"\nproof -\n  note dD[simp] = diffeomorphismD[OF diffeo]\n  note homeo[simp] = diffeomorphism_imp_homeomorphism[OF diffeo]\n  from assms(1) have c: \"k-smooth_on (apply_chart c ` (domain c \\<inter> domain c')) (apply_chart c' \\<circ> inv_chart c)\"\n    and c': \"k-smooth_on (apply_chart c' ` (domain c \\<inter> domain c')) (apply_chart c \\<circ> inv_chart c')\"\n    by (auto simp: smooth_compat_def)\n  from homeo have *: \"open (p ` apply_chart c ` (domain c \\<inter> domain c'))\"\n    by (rule homeomorphism_UNIV_imp_open_map) auto\n  have \"k-smooth_on ((p \\<circ> apply_chart c) ` (domain c \\<inter> domain c')) (apply_chart c' \\<circ> inv_chart c \\<circ> p')\"\n    apply (rule smooth_on_compose2) prefer 2\n         apply (rule dD)\n        apply (rule c)\n       apply (auto simp add: assms image_comp [symmetric] * cong del: image_cong_simp)\n    done\n  moreover\n  have \"k-smooth_on (apply_chart c' ` (domain c \\<inter> domain c')) (p \\<circ> (apply_chart c \\<circ> inv_chart c'))\"\n    apply (rule smooth_on_compose2)\n         apply (rule dD)\n        apply fact\n    by (auto simp: assms image_comp[symmetric])\n  ultimately show ?thesis\n    unfolding smooth_compat_def\n    by (auto intro!: simp: o_assoc)\nqed\n\nlemma compose_chart_in_atlas:\n  assumes \"c \\<in> atlas\"\n  assumes diffeo: \"diffeomorphism k UNIV UNIV p p'\"\n  shows \"compose_chart p p' c \\<in> atlas\"\nproof (rule maximal_atlas)\n  note [simp] = diffeomorphism_imp_homeomorphism[OF diffeo]\n  show \"domain (compose_chart p p' c) \\<subseteq> carrier\"\n    using assms\n    by auto\n  fix c' assume \"c' \\<in> atlas\"\n  with \\<open>c \\<in> atlas\\<close> have \"k-smooth_compat c c'\"\n    by (rule atlas_is_atlas)\n  then show \"k-smooth_compat (compose_chart p p' c) c'\"\n    using diffeo\n    by (rule smooth_compat_compose_chart)\nqed\n\nlemma open_centered_ball_chartE:\n  assumes \"x \\<in> U\" \"open U\" \"U \\<subseteq> carrier\" \"e > 0\"\n  obtains c where\n    \"c \\<in> atlas\" \"x \\<in> domain c\" \"c x = x0\" \"domain c \\<subseteq> U\" \"codomain c = ball x0 e\"\nproof -\n  from open_ball_chartE[OF assms(1-3)] obtain c r where c:\n    \"c \\<in> atlas\"\n    \"x \\<in> domain c\" \"domain c \\<subseteq> U\" \"codomain c = ball (c x) r\"\n    and r: \"r > 0\"\n    by auto\n  have nz: \"e / r \\<noteq> 0\" using \\<open>e > 0\\<close> \\<open>r > 0\\<close> by auto\n  have 1: \"diffeomorphism k UNIV UNIV (\\<lambda>y. y + (- c x)) (\\<lambda>y. y - (- c x))\"\n    using diffeomorphism_add[of k \"(- c x)\"] by auto\n  have 2: \"diffeomorphism k UNIV UNIV (\\<lambda>y. (e / r) *\\<^sub>R y) (\\<lambda>y. y /\\<^sub>R (e / r))\"\n    using diffeomorphism_scaleR[of \"e / r\" k] \\<open>e > 0\\<close> \\<open>r > 0\\<close> by auto\n  have 3: \"diffeomorphism k UNIV UNIV (\\<lambda>y. y + x0) (\\<lambda>y. y - x0)\"\n    using diffeomorphism_add[of k x0] by auto\n  define t where \"t = (\\<lambda>y. (e / r) *\\<^sub>R (y + - c x) + x0)\"\n  define t' where \"t' = (\\<lambda>y. (y - x0) /\\<^sub>R (e / r) + c x)\"\n  from diffeomorphism_compose[OF diffeomorphism_compose[OF 1 2] 3, unfolded o_def]\n  have diffeo: \"diffeomorphism k UNIV UNIV t t'\"\n    by (auto simp: t_def t'_def o_def)\n  from compose_chart_in_atlas[OF \\<open>c \\<in> atlas\\<close> this]\n  have \"compose_chart t t' c \\<in> atlas\" .\n  moreover\n  note [simp] = diffeomorphism_imp_homeomorphism[OF diffeo]\n  have \"x \\<in> domain (compose_chart t t' c)\" by (auto simp: \\<open>x \\<in> domain c\\<close>)\n  moreover\n  have \"t (c x) = x0\"\n    by (auto simp: t_def)\n  then have \"compose_chart t t' c x = x0\"\n    by simp\n  moreover have \"domain (compose_chart t t' c) \\<subseteq> U\"\n    using \\<open>domain c \\<subseteq> U\\<close>\n    by auto\n  moreover\n  have \"t ` codomain c = ball x0 e\"\n  proof -\n    have \"t ` codomain c = (+) x0 ` (*\\<^sub>R) (e / r) ` (\\<lambda>y. - apply_chart c x + y) ` ball (c x) r\"\n      by (auto simp add: c t_def image_image)\n    also have \"\\<dots> = ball x0 e\"\n      using \\<open>e > 0\\<close> \\<open>r > 0\\<close>\n      unfolding image_add_ball image_scaleR_ball[OF nz]\n      by simp\n    finally show ?thesis .\n  qed\n  then have \"codomain (compose_chart t t' c) = ball x0 e\"\n    by auto\n  ultimately show ?thesis ..\nqed\n\nend\n\nsubsubsection \\<open>Submanifold\\<close>\n\ndefinition (in manifold) \"charts_submanifold S = (restrict_chart S ` charts)\"\n\nlocale c_manifold' = c_manifold\n\nlocale submanifold = c_manifold' charts k \\<comment>\\<open>breaks infinite loop for sublocale sub\\<close>\n  for charts::\"('a::{t2_space,second_countable_topology}, 'b::euclidean_space) chart set\" and k +\n  fixes S::\"'a set\"\n  assumes open_submanifold: \"open S\"\nbegin\n\nlemma charts_submanifold: \"c_manifold (charts_submanifold S) k\" \n  by unfold_locales\n    (auto simp: charts_submanifold_def atlas_is_atlas in_charts_in_atlas restrict_chart_in_atlas)\n\nsublocale sub: c_manifold \"(charts_submanifold S)\" k\n  by (rule charts_submanifold)\n\nlemma carrier_submanifold[simp]: \"sub.carrier = S \\<inter> carrier\"\n  using open_submanifold\n  by (auto simp: manifold.carrier_def charts_submanifold_def domain_restrict_chart_if split: if_splits)\n\nlemma restrict_chart_carrier[simp]:\n  \"restrict_chart carrier x = x\"\n  if \"x \\<in> charts\"\n  using that\n  by (auto intro!: chart_eqI)\n\nlemma charts_submanifold_carrier[simp]: \"charts_submanifold carrier = charts\"\n  by (force simp: charts_submanifold_def)\n\nlemma charts_submanifold_Int_carrier:\n  \"charts_submanifold (S \\<inter> carrier) = charts_submanifold S\"\n  using open_submanifold\n  by (force simp: charts_submanifold_def restrict_chart_restrict_chart[symmetric])\n\nlemma submanifold_atlasE:\n  assumes \"c \\<in> sub.atlas\"\n  shows \"c \\<in> atlas\"\nproof (rule maximal_atlas')\n  have dc: \"domain c \\<subseteq> S \\<inter> carrier\"\n    using assms sub.domain_atlas_subset_carrier\n    by auto\n  then show \"domain c \\<subseteq> carrier\"\n    using open_submanifold by auto\n  fix c' assume \"c' \\<in> charts\"\n  then have \"restrict_chart S c' \\<in> (charts_submanifold S)\"\n    by (auto simp: charts_submanifold_def)\n  then have \"restrict_chart S c' \\<in> sub.atlas\"\n    by auto\n  have \"k-smooth_compat c (restrict_chart S c')\"\n    by (rule sub.atlas_is_atlas) fact+\n  show \"k-smooth_compat c c'\"\n    apply (rule smooth_compat_restrict_chartD[where U=S])\n    subgoal using dc by auto\n    subgoal by (rule open_submanifold)\n    subgoal by fact\n    done\nqed\n\nlemma submanifold_atlasI:\n  \"restrict_chart S c \\<in> sub.atlas\"\n  if \"c \\<in> atlas\"\nproof (rule sub.maximal_atlas')\n  fix c' assume \"c' \\<in> (charts_submanifold S)\"\n  then obtain c'' where c'': \"c' = restrict_chart S c''\" \"c'' \\<in> charts\"\n    unfolding charts_submanifold_def by auto\n  show \"k-smooth_compat (restrict_chart S c) c'\"\n    unfolding c''\n    apply (rule smooth_compat_restrict_chartI)\n    apply (rule smooth_compat_restrict_chartI2)\n    apply (rule atlas_is_atlas)\n     apply fact using \\<open>c'' \\<in> charts\\<close> by auto\nnext\n  show \"domain (restrict_chart S c) \\<subseteq> sub.carrier\"\n    using domain_atlas_subset_carrier[OF that]\n    by (auto simp: open_submanifold )\nqed\n\nend\n\n\n\nlemma (in c_manifold) restrict_chart_carrier[simp]:\n  \"restrict_chart carrier x = x\"\n  if \"x \\<in> charts\"\n  using that\n  by (auto intro!: chart_eqI)\n\nlemma (in c_manifold) charts_submanifold_carrier[simp]: \"charts_submanifold carrier = charts\"\n  by (force simp: charts_submanifold_def)\n\n\nsubsection \\<open>Differentiable maps\\<close>\n\nlocale c_manifolds =\n  src: c_manifold charts1 k + \n  dest: c_manifold charts2 k for k charts1 charts2\n\nlocale diff = c_manifolds k charts1 charts2\n  for k\n    and charts1 :: \"('a::{t2_space,second_countable_topology}, 'e::euclidean_space) chart set\"\n    and charts2 :: \"('b::{t2_space,second_countable_topology}, 'f::euclidean_space) chart set\"\n    +\n  fixes f :: \"('a \\<Rightarrow> 'b)\"\n  assumes exists_smooth_on: \"x \\<in> src.carrier \\<Longrightarrow>\n    \\<exists>c1\\<in>src.atlas. \\<exists>c2\\<in>dest.atlas.\n      x \\<in> domain c1 \\<and>\n      f ` domain c1 \\<subseteq> domain c2 \\<and>\n      k-smooth_on (codomain c1) (c2 \\<circ> f \\<circ> inv_chart c1)\"\nbegin\n\nlemma defined: \"f ` src.carrier \\<subseteq> dest.carrier\"\n  using exists_smooth_on\n  by auto\n\nend\n\ncontext c_manifolds begin\n\nlemma diff_iff: \"diff k charts1 charts2 f \\<longleftrightarrow>\n  (\\<forall>x\\<in>src.carrier. \\<exists>c1\\<in>src.atlas. \\<exists>c2\\<in>dest.atlas.\n    x \\<in> domain c1 \\<and>\n    f ` domain c1 \\<subseteq> domain c2 \\<and>\n    k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1))\"\n  (is \"?l \\<longleftrightarrow> (\\<forall>x\\<in>_. ?r x)\")\nproof safe\n  assume ?l\n  interpret diff k charts1 charts2 f by fact\n  show \"x \\<in> src.carrier \\<Longrightarrow> ?r x\" for x\n    by (rule exists_smooth_on)\nnext\n  assume \"\\<forall>x\\<in>src.carrier. ?r x\"\n  then show ?l\n    by unfold_locales auto\nqed\n\nend\n\ncontext diff begin\n\nlemma diffE:\n  assumes \"x \\<in> src.carrier\"\n  obtains c1::\"('a, 'e) chart\"\n    and c2::\"('b, 'f) chart\"\n  where\n    \"c1 \\<in> src.atlas\" \"c2 \\<in> dest.atlas\" \"x \\<in> domain c1\" \"f ` domain c1 \\<subseteq> domain c2\"\n    \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n  using exists_smooth_on assms by force\n\nlemma continuous_at: \"continuous (at x within T) f\" if \"x \\<in> src.carrier\"\nproof -\n  from that obtain c1 c2 where \"c1 \\<in> src.atlas\" \"c2 \\<in> dest.atlas\" \"x \\<in> domain c1\"\n    \"f ` domain c1 \\<subseteq> domain c2\"\n    \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n    by (rule diffE)\n  from smooth_on_imp_continuous_on[OF this(5)]\n  have \"continuous_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\" .\n  then have \"continuous_on (c1 ` domain c1) (f \\<circ> inv_chart c1)\"\n    using \\<open>f ` domain c1 \\<subseteq> domain c2\\<close> continuous_on_chart_inv by (fastforce simp: image_domain_eq)\n  then have \"continuous_on (domain c1) f\"\n    by (rule continuous_on_chart_inv') simp\n  then have \"isCont f x\"\n    using \\<open>x \\<in> domain c1\\<close>\n    unfolding continuous_on_eq_continuous_at[OF open_domain] \n    by auto\n  then show \"continuous (at x within T) f\"\n    by (simp add: \\<open>isCont f x\\<close> continuous_at_imp_continuous_within)\nqed\n\nlemma continuous_on: \"continuous_on src.carrier f\"\n  unfolding continuous_on_eq_continuous_within\n  by (auto intro: continuous_at)\n\nlemmas continuous_on_intro[continuous_intros] = continuous_on_compose2[OF continuous_on _]\n\nlemmas continuous_within[continuous_intros] = continuous_within_compose3[OF continuous_at]\n\nlemmas tendsto[tendsto_intros] = isCont_tendsto_compose[OF continuous_at]\n\nlemma diff_chartsD:\n  assumes \"d1 \\<in> src.atlas\" \"d2 \\<in> dest.atlas\"\n  shows \"k-smooth_on (codomain d1 \\<inter> inv_chart d1 -` (src.carrier \\<inter> f -` domain d2))\n      (apply_chart d2 \\<circ> f \\<circ> inv_chart d1)\"\nproof (rule smooth_on_open_subsetsI)\n  fix y assume \"y \\<in> codomain d1 \\<inter> inv_chart d1 -` (src.carrier \\<inter> f -` domain d2)\"\n  then have y: \"f (inv_chart d1 y) \\<in> domain d2\" \"y \\<in> codomain d1\"\n    by auto\n  then obtain x where x: \"d1 x = y\" \"x \\<in> domain d1\"\n    by force\n  then have \"x \\<in> src.carrier\" using assms by force\n  obtain c1 c2 where \"c1 \\<in> src.atlas\" \"c2 \\<in> dest.atlas\"\n    and fc1: \"f ` domain c1 \\<subseteq> domain c2\"\n    and xc1: \"x \\<in> domain c1\"\n    and d: \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n    using diffE[OF \\<open>x \\<in> src.carrier\\<close>]\n    by metis\n  have [simp]: \"x \\<in> domain c1 \\<Longrightarrow> f x \\<in> domain c2\" for x using fc1 by auto\n  have r1: \"k-smooth_on (d1 ` (domain d1 \\<inter> domain c1)) (c1 \\<circ> inv_chart d1)\"\n    using src.atlas_is_atlas[OF \\<open>d1 \\<in> src.atlas\\<close> \\<open>c1 \\<in> src.atlas\\<close>, THEN smooth_compat_D1] .\n  have r2: \"k-smooth_on (c2 ` (domain d2 \\<inter> domain c2)) (d2 \\<circ> inv_chart c2)\"\n    using dest.atlas_is_atlas[OF \\<open>d2 \\<in> dest.atlas\\<close> \\<open>c2 \\<in> dest.atlas\\<close>, THEN smooth_compat_D2] .\n  define T where \"T = (d1 ` (domain d1 \\<inter> domain c1) \\<inter> inv_chart d1 -` (src.carrier \\<inter> (f -` domain d2)))\"\n  have \"open T\"\n    unfolding T_def\n    by (rule open_continuous_vimage')\n      (auto intro!: continuous_intros open_continuous_vimage' src.open_carrier)\n  have T_subset: \"T \\<subseteq> apply_chart d1 ` (domain d1 \\<inter> domain c1)\"\n    by (auto simp: T_def)\n  have opens: \"open (c1 ` inv_chart d1 ` T)\" \"open (c2 ` (domain d2 \\<inter> domain c2))\"\n    using fc1 \\<open>open T\\<close>\n    by (force simp: T_def)+\n  have \"k-smooth_on ((apply_chart c1 \\<circ> inv_chart d1) ` T) (d2 \\<circ> inv_chart c2 \\<circ> (c2 \\<circ> f \\<circ> inv_chart c1))\"\n    using r2 d opens\n    unfolding image_comp[symmetric]\n    by (rule smooth_on_compose2) (auto simp: T_def)\n  from this r1 \\<open>open T\\<close> opens(1) have \"k-smooth_on T\n      ((d2 \\<circ> inv_chart c2) \\<circ> (c2 \\<circ> f \\<circ> inv_chart c1) \\<circ> (c1 \\<circ> inv_chart d1))\"\n    unfolding image_comp[symmetric]\n    by (rule smooth_on_compose2) (force simp: T_def)+\n  then have \"k-smooth_on T (d2 \\<circ> f \\<circ> inv_chart d1)\"\n    using \\<open>open T\\<close>\n    by (rule smooth_on_cong) (auto simp: T_def)\n  moreover have \"y \\<in> T\" \n    using x xc1 fc1 y \\<open>c1 \\<in> src.atlas\\<close>\n    by (auto simp: T_def)\n  ultimately show \"\\<exists>T. y \\<in> T \\<and> open T \\<and> k-smooth_on T (apply_chart d2 \\<circ> f \\<circ> inv_chart d1)\"\n    using \\<open>open T\\<close>\n    by metis\nqed\n\nlemma diff_between_chartsE:\n  assumes \"d1 \\<in> src.atlas\" \"d2 \\<in> dest.atlas\"\n  assumes \"y \\<in> domain d1\" \"y \\<in> src.carrier\" \"f y \\<in> domain d2\"\n  obtains X where\n    \"k-smooth_on X (apply_chart d2 \\<circ> f \\<circ> inv_chart d1)\"\n    \"d1 y \\<in> X\"\n    \"open X\"\n    \"X = codomain d1 \\<inter> inv_chart d1 -` (src.carrier \\<inter> f -` domain d2)\"\nproof -\n  define X where \"X = (codomain d1 \\<inter> inv_chart d1 -` (src.carrier \\<inter> f -` domain d2))\"\n  from diff_chartsD[OF assms(1,2)]\n  have \"k-smooth_on X (apply_chart d2 \\<circ> f \\<circ> inv_chart d1)\"\n    by (simp add: X_def)\n  moreover have \"d1 y \\<in> X\"\n    using assms(3-5)\n    by (auto simp: X_def)\n  moreover have \"open X\"\n    unfolding X_def\n    by (auto intro!: open_continuous_vimage' continuous_intros src.open_carrier)\n  moreover note X_def\n  ultimately show ?thesis ..\nqed\n\nend\n\nlemma diff_compose:\n  \"diff k M1 M3 (g \\<circ> f)\"\n  if \"diff k M1 M2 f\" \"diff k M2 M3 g\"\nproof -\n  interpret f: diff k M1 M2 f by fact\n  interpret g: diff k M2 M3 g by fact\n  interpret fg: c_manifolds k M1 M3 by unfold_locales\n  show ?thesis\n    unfolding fg.diff_iff\n  proof safe\n    fix x assume \"x \\<in> f.src.carrier\"\n    then obtain c1 c2 where c1: \"c1 \\<in> f.src.atlas\"\n      and c2: \"c2 \\<in> f.dest.atlas\"\n      and fc1: \"f ` domain c1 \\<subseteq> domain c2\"\n      and x: \"x \\<in> domain c1\"\n      and df: \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n      using f.diffE by metis\n\n    have \"f x \\<in> f.dest.carrier\" using f.defined \\<open>x \\<in> f.src.carrier\\<close> by auto\n    then obtain c2' c3 where c2': \"c2' \\<in> f.dest.atlas\"\n      and c3: \"c3 \\<in> g.dest.atlas\"\n      and gc2': \"g ` domain c2' \\<subseteq> domain c3\"\n      and fx: \"f x \\<in> domain c2'\"\n      and dg: \"k-smooth_on (codomain c2') (apply_chart c3 \\<circ> g \\<circ> inv_chart c2')\"\n      using g.diffE by metis\n\n    define D where \"D = (g \\<circ> f) -` domain c3 \\<inter> domain c1\"\n    have \"open D\"\n      using f.defined c1\n      by (auto intro!: continuous_intros open_continuous_vimage simp: D_def)\n    \n    have \"x \\<in> D\"\n      using fc1 fx gc2'\n      by (auto simp: D_def \\<open>x \\<in> domain c1\\<close>)\n\n    define d1 where \"d1 = restrict_chart D c1\"\n\n    have \"d1 \\<in> f.src.atlas\"\n      by (auto simp: d1_def intro!: f.src.restrict_chart_in_atlas c1)\n    moreover have \"c3 \\<in> g.dest.atlas\" by fact\n    moreover have \"x \\<in> domain d1\" by (auto simp: d1_def \\<open>open D\\<close> \\<open>x \\<in> D\\<close> x)\n    moreover have sub_c3: \"(g \\<circ> f) ` domain d1 \\<subseteq> domain c3\"\n      using \\<open>open D\\<close> by (auto simp: d1_def D_def)\n    moreover have \"k-smooth_on (codomain d1) (c3 \\<circ> (g \\<circ> f) \\<circ> inv_chart d1)\"\n    proof (rule smooth_on_open_subsetsI)\n      fix y assume y: \"y \\<in> codomain d1\"\n      then obtain iy where y_def: \"y = d1 iy\" and iy: \"iy \\<in> domain d1\" by force\n      note iy\n      also note f.src.domain_atlas_subset_carrier[OF \\<open>d1 \\<in> f.src.atlas\\<close>]\n      finally have iS: \"iy \\<in> f.src.carrier\" .\n      then have \"f iy \\<in> f.dest.carrier\"\n        using f.defined by (auto simp: d1_def)\n      with f.dest.atlasE obtain d2 where d2: \"d2 \\<in> f.dest.atlas\"\n        and fy: \"f iy \\<in> domain d2\"\n        by blast\n      from f.diff_between_chartsE[OF \\<open>d1 \\<in> f.src.atlas\\<close> \\<open>d2 \\<in> f.dest.atlas\\<close> iy iS fy]\n      obtain T where 1: \"k-smooth_on T (apply_chart d2 \\<circ> f \\<circ> inv_chart d1)\"\n        and T: \"d1 iy \\<in> T\" \"open T\"\n        and T_def: \"T = codomain d1 \\<inter> inv_chart d1 -` (f.src.carrier \\<inter> f -` domain d2)\"\n        by auto\n\n      have gf: \"g (f (iy)) \\<in> domain c3\" using sub_c3 iy by auto\n      from iS f.defined have \"f (iy) \\<in> f.dest.carrier\" by auto\n      from g.diff_between_chartsE[OF \\<open>d2 \\<in> f.dest.atlas\\<close> \\<open>c3 \\<in> g.dest.atlas\\<close> fy this gf]\n      obtain X where 2: \"k-smooth_on X (apply_chart c3 \\<circ> g \\<circ> inv_chart d2)\"\n        and X: \"apply_chart d2 (f iy) \\<in> X\" \"open X\"\n        and X_def: \"X = codomain d2 \\<inter> inv_chart d2 -` (f.dest.carrier \\<inter> g -` domain c3)\"\n        by auto\n      have \"y \\<in> T\" using T by (simp add: y_def)\n      moreover\n      note \\<open>open T\\<close>\n      moreover\n      have \"k-smooth_on T (apply_chart c3 \\<circ> g \\<circ> inv_chart d2 \\<circ> (apply_chart d2 \\<circ> f \\<circ> inv_chart d1))\"\n        using 2 1 \\<open>open T\\<close> \\<open>open X\\<close>\n        by (rule smooth_on_compose) (use sub_c3 f.defined in \\<open>force simp: T_def X_def\\<close>)\n      then have \"k-smooth_on T (apply_chart c3 \\<circ> (g \\<circ> f) \\<circ> inv_chart d1)\"\n        using \\<open>open T\\<close>\n        by (rule smooth_on_cong) (auto simp: T_def)\n      ultimately show \"\\<exists>T. y \\<in> T \\<and> open T \\<and> k-smooth_on T (apply_chart c3 \\<circ> (g \\<circ> f) \\<circ> inv_chart d1)\"\n        by metis\n    qed\n    ultimately show \"\\<exists>c1\\<in>f.src.atlas.\n            \\<exists>c2\\<in>g.dest.atlas.\n               x \\<in> domain c1 \\<and>\n               (g \\<circ> f) ` domain c1 \\<subseteq> domain c2 \\<and> k-smooth_on (codomain c1) (apply_chart c2 \\<circ> (g \\<circ> f) \\<circ> inv_chart c1)\"\n      by blast\n  qed\nqed\n\ncontext diff begin\n\nlemma diff_submanifold: \"diff k (src.charts_submanifold S) charts2 f\"\n  if \"open S\"\nproof -\n  interpret submanifold charts1 k S\n    by unfold_locales (auto intro!: that)\n  show ?thesis\n    unfolding that src.charts_submanifold_def[symmetric]\n  proof unfold_locales\n    fix x assume \"x \\<in> sub.carrier\"\n    then have \"x \\<in> src.carrier\" \"x \\<in> S\" using that\n      by auto\n    from diffE[OF \\<open>x \\<in> src.carrier\\<close>] obtain c1 c2 where c1c2:\n      \"c1 \\<in> src.atlas\" \"c2 \\<in> dest.atlas\" \"x \\<in> domain c1\"\n      \"f ` domain c1 \\<subseteq> domain c2\" \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n      by auto\n    have rc1: \"restrict_chart S c1 \\<in> sub.atlas\"\n      using c1c2(1) by (rule submanifold_atlasI)\n    show \"\\<exists>c1\\<in>sub.atlas. \\<exists>c2\\<in>dest.atlas. x \\<in> domain c1 \\<and> f ` domain c1 \\<subseteq> domain c2 \\<and>\n      k-smooth_on (codomain c1) (c2 \\<circ> f \\<circ> inv_chart c1)\"\n      using rc1\n      apply (rule rev_bexI)\n      using c1c2(2)\n      apply (rule rev_bexI)\n      using c1c2 \\<open>x \\<in> S\\<close> \\<open>open S\\<close>\n      by (auto simp: smooth_on_subset)\n  qed\nqed\n\nlemma diff_submanifold2: \"diff k charts1 (dest.charts_submanifold S) f\"\n  if \"open S\" \"f ` src.carrier \\<subseteq> S\"\nproof -\n  interpret submanifold charts2 k S\n    by unfold_locales (auto intro!: that)\n  show ?thesis\n    unfolding that src.charts_submanifold_def[symmetric]\n  proof unfold_locales\n    fix x assume \"x \\<in> src.carrier\"\n    from diffE[OF this]\n    obtain c1 c2 where c1c2:\n      \"c1 \\<in> src.atlas\" \"c2 \\<in> dest.atlas\" \"x \\<in> domain c1\"\n      \"f ` domain c1 \\<subseteq> domain c2\" \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n      by auto\n    have r: \"restrict_chart S c2 \\<in> sub.atlas\"\n      using c1c2(2) by (rule submanifold_atlasI)\n    show \"\\<exists>c1\\<in>src.atlas. \\<exists>c2\\<in>sub.atlas. x \\<in> domain c1 \\<and> f ` domain c1 \\<subseteq> domain c2 \\<and>\n      k-smooth_on (codomain c1) (c2 \\<circ> f \\<circ> inv_chart c1)\"\n      using c1c2(1)\n      apply (rule rev_bexI)\n      using r\n      apply (rule rev_bexI)\n      using c1c2 \\<open>open S\\<close> that(2)\n      by (auto simp: smooth_on_subset)\n  qed\nqed\n\nend\n\ncontext c_manifolds begin\n\nlemma diff_localI: \"diff k charts1 charts2 f\"\n  if \"\\<And>x. x \\<in> src.carrier \\<Longrightarrow> diff k (src.charts_submanifold (U x)) charts2 f\"\n    \"\\<And>x. x \\<in> src.carrier \\<Longrightarrow> open (U x)\"\n    \"\\<And>x. x \\<in> src.carrier \\<Longrightarrow> x \\<in> (U x)\"\nproof unfold_locales\n  fix x assume x: \"x \\<in> src.carrier\"\n  have open_U[simp]: \"open (U x)\" by (rule that) fact\n  have in_U[simp]: \"x \\<in> U x\" by (rule that) fact\n  interpret submanifold charts1 k \"U x\"\n    using that x\n    by unfold_locales auto\n  from x interpret l: diff k \"src.charts_submanifold (U x)\" charts2 f\n    by (rule that)\n  have \"x \\<in> sub.carrier\" using x\n    by auto\n  from l.diffE[OF this] obtain c1 c2 where c1c2: \"c1 \\<in> sub.atlas\"\n    \"c2 \\<in> dest.atlas\" \"x \\<in> domain c1\" \"f ` domain c1 \\<subseteq> domain c2\"\n    \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n    by auto\n  have \"c1 \\<in> src.atlas\"\n    by (rule submanifold_atlasE[OF c1c2(1)])\n  show \"\\<exists>c1\\<in>src.atlas. \\<exists>c2\\<in>dest.atlas. x \\<in> domain c1 \\<and> f ` domain c1 \\<subseteq> domain c2 \\<and>\n    k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n    by (intro bexI[where x=c1] bexI[where x=c2] conjI \\<open>c1 \\<in> src.atlas\\<close> \\<open>c2 \\<in> dest.atlas\\<close> c1c2)\nqed\n\nlemma diff_open_coverI: \"diff k charts1 charts2 f\"\n  if diff: \"\\<And>u. u \\<in> U \\<Longrightarrow> diff k (src.charts_submanifold u) charts2 f\"\n    and op: \"\\<And>u. u \\<in> U \\<Longrightarrow> open u\"\n    and cover: \"src.carrier \\<subseteq> \\<Union>U\"\nproof -\n  obtain V where V: \"\\<forall>x\\<in>src.carrier. V x \\<in> U \\<and> x \\<in> V x\"\n    apply (atomize_elim, rule bchoice)\n    using cover\n    by blast\n  have \"diff k (src.charts_submanifold (V x)) charts2 f\"\n    \"open (V x)\"\n    \"x \\<in> V x\"\n    if \"x \\<in> src.carrier\" for x\n    using that diff op V\n    by auto\n  then show ?thesis\n    by (rule diff_localI)\nqed\n\nlemma diff_open_Un: \"diff k charts1 charts2 f\"\n  if \"diff k (src.charts_submanifold U) charts2 f\"\n    \"diff k (src.charts_submanifold V) charts2 f\"\n    and \"open U\" \"open V\" \"src.carrier \\<subseteq> U \\<union> V\"\n  using diff_open_coverI[of \"{U, V}\" f] that\n  by auto\n\nend\n\ncontext c_manifold begin\n\nsublocale self: c_manifolds k charts charts\n  by unfold_locales\n\nlemma diff_id: \"diff k charts charts (\\<lambda>x. x)\"\n  by (force simp: self.diff_iff elim!: atlasE intro: smooth_on_cong)\n\nlemma c_manifold_order_le: \"c_manifold charts l\" if \"l \\<le> k\"\n  by unfold_locales (use pairwise_compat smooth_compat_le[OF _ \\<open>l \\<le> k\\<close>] in blast)\n\nlemma in_atlas_order_le: \"c \\<in> c_manifold.atlas charts l\" if \"l \\<le> k\" \"c \\<in> atlas\"\nproof -\n  interpret l: c_manifold charts l\n    using \\<open>l \\<le> k\\<close>\n    by (rule c_manifold_order_le)\n  show ?thesis\n    using that\n    by (auto simp: l.atlas_def atlas_def smooth_compat_le[OF _ \\<open>l \\<le> k\\<close>])\nqed\n\nend\n\ncontext c_manifolds begin\n\nlemma c_manifolds_order_le: \"c_manifolds l charts1 charts2\" if \"l \\<le> k\"\n  by unfold_locales\n    (use src.pairwise_compat dest.pairwise_compat smooth_compat_le[OF _ that] in blast)+\n\nend\n\ncontext diff begin\n\nlemma diff_order_le: \"diff l charts1 charts2 f\" if \"l \\<le> k\"\nproof -\n  interpret l: c_manifolds l charts1 charts2\n    by (rule c_manifolds_order_le) fact\n  show \"diff l charts1 charts2 f\"\n    using diff_axioms\n    unfolding l.diff_iff diff_iff\n    by (auto dest!: smooth_on_le[OF _ that] src.in_atlas_order_le[OF that]\n        dest.in_atlas_order_le[OF that] dest!: bspec)\nqed\n\nend\n\n\nsubsection \\<open>Differentiable functions\\<close>\n\nlift_definition chart_eucl::\"('a::euclidean_space, 'a) chart\" is\n  \"(UNIV, UNIV, \\<lambda>x. x, \\<lambda>x. x)\"\n  by (auto simp: homeomorphism_def)\n\nabbreviation \"charts_eucl \\<equiv> {chart_eucl}\"\n\nlemma chart_eucl_simps[simp]:\n  \"domain chart_eucl = UNIV\"\n  \"codomain chart_eucl = UNIV\"\n  \"apply_chart chart_eucl = (\\<lambda>x. x)\"\n  \"inv_chart chart_eucl = (\\<lambda>x. x)\"\n  by (transfer, simp)+\n\nlocale diff_fun = diff k charts charts_eucl f\n  for k charts and f::\"'a::{t2_space,second_countable_topology} \\<Rightarrow> 'b::euclidean_space\"\n\nlemma diff_fun_compose:\n  \"diff_fun k M1 (g \\<circ> f)\"\n  if \"diff k M1 M2 f\" \"diff_fun k M2 g\"\n  unfolding diff_fun_def\n  by (rule diff_compose[OF that[unfolded diff_fun_def]])\n\nlemma c1_manifold_atlas_eucl: \"c_manifold charts_eucl k\"\n  by unfold_locales (auto simp: smooth_compat_refl)\n\ninterpretation manifold_eucl: c_manifold \"charts_eucl\" k\n  by (rule c1_manifold_atlas_eucl)\n\nlemma chart_eucl_in_atlas[intro,simp]: \"chart_eucl \\<in> manifold_eucl.atlas k\"\n  using manifold_eucl.charts_subset_atlas\n  by auto\n\nlemma apply_chart_smooth_on:\n  \"k-smooth_on (domain c) c\" if \"c \\<in> manifold_eucl.atlas k\"\nproof -\n  have \"k-smooth_compat c chart_eucl\"\n    using that\n    by (auto intro!: manifold_eucl.atlas_is_atlas)\n  from smooth_compat_D2[OF this]\n  show ?thesis\n    by (auto simp: o_def)\nqed\n\nlemma inv_chart_smooth_on: \"k-smooth_on (codomain c) (inv_chart c)\" if \"c \\<in> manifold_eucl.atlas k\"\nproof -\n  have \"k-smooth_compat c chart_eucl\"\n    using that\n    by (auto intro!: manifold_eucl.atlas_is_atlas)\n  from smooth_compat_D1[OF this]\n  show ?thesis\n    by (auto simp: o_def image_domain_eq)\nqed\n\nlemma smooth_on_chart_inv:\n  fixes c::\"('a::euclidean_space, 'a) chart\"\n  assumes \"k-smooth_on X (apply_chart c \\<circ> f)\"\n  assumes \"continuous_on X f\"\n  assumes \"c \\<in> manifold_eucl.atlas k\" \"open X\" \"f ` X \\<subseteq> domain c\"\n  shows \"k-smooth_on X f\"\nproof -\n  have \"k-smooth_on X (inv_chart c \\<circ> (apply_chart c \\<circ> f))\"\n    using assms\n    by (auto intro!: smooth_on_compose inv_chart_smooth_on)\n  with assms show ?thesis\n    by (force intro!: open_continuous_vimage intro: smooth_on_cong)\nqed\n\nlemma smooth_on_chart_inv2:\n  fixes c::\"('a::euclidean_space, 'a) chart\"\n  assumes \"k-smooth_on (c ` X) (f o inv_chart c)\"\n  assumes \"c \\<in> manifold_eucl.atlas k\" \"open X\" \"X \\<subseteq> domain c\"\n  shows \"k-smooth_on X f\"\nproof -\n  have \"k-smooth_on X ((f o inv_chart c) \\<circ> apply_chart c)\"\n    using assms(1) apply_chart_smooth_on\n    by (rule smooth_on_compose2) (auto simp: assms)\n  with assms show ?thesis\n    by (force intro!: open_continuous_vimage intro: smooth_on_cong)\nqed\n\ncontext diff_fun begin\n\nlemma diff_fun_order_le: \"diff_fun l charts f\" if \"l \\<le> k\"\n  using diff_order_le[OF that]\n  by (simp add: diff_fun_def)\n\nend\n\n\nsubsection \\<open>Diffeormorphism\\<close>\n\nlocale diffeomorphism = diff k charts1 charts2 f + inv: diff k charts2 charts1 f'\n  for k charts1 charts2 f f' +\n  assumes f_inv[simp]:  \"\\<And>x. x \\<in> src.carrier \\<Longrightarrow> f' (f x) = x\"\n      and f'_inv[simp]: \"\\<And>y. y \\<in> dest.carrier \\<Longrightarrow> f (f' y) = y\"\n\ncontext c_manifold begin\n\nsublocale manifold_eucl: c_manifolds k charts \"{chart_eucl}\"\n  rewrites \"diff k charts {chart_eucl} = diff_fun k charts\"\n  by unfold_locales (simp add: diff_fun_def[abs_def])\n\nlemma diff_funI:\n  \"diff_fun k charts f\"\n  if \"(\\<And>x. x\\<in>carrier \\<Longrightarrow> \\<exists>c1\\<in>atlas. x \\<in> domain c1 \\<and> (k-smooth_on (codomain c1) (f \\<circ> inv_chart c1)))\"\n  unfolding manifold_eucl.diff_iff\n  by (auto dest!: that intro!: bexI[where x=chart_eucl] simp: o_def)\n\nend\n\nlemma (in diff) diff_cong: \"diff k charts1 charts2 g\" if \"\\<And>x. x \\<in> src.carrier \\<Longrightarrow> f x = g x\"\n  unfolding diff_iff\nproof (rule ballI)\n  fix x assume \"x \\<in> src.carrier\"\n  from diff_axioms[unfolded diff_iff, rule_format, OF this]\n  obtain c1::\"('a, 'e) chart\" and c2::\"('b, 'f) chart\" where\n    \"c1\\<in>src.atlas\" \"c2 \\<in> dest.atlas\"\n     \"x \\<in> domain c1\" \"f ` domain c1 \\<subseteq> domain c2\" \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> f \\<circ> inv_chart c1)\"\n    by auto\n  then show \"\\<exists>c1\\<in>src.atlas. \\<exists>c2\\<in>dest.atlas.\n      x \\<in> domain c1 \\<and> g ` domain c1 \\<subseteq> domain c2 \\<and> k-smooth_on (codomain c1) (apply_chart c2 \\<circ> g \\<circ> inv_chart c1)\"\n    using that\n    by (intro bexI[where x=c1] bexI[where x=c2]) (auto simp: intro: smooth_on_cong)\nqed\n\n\ncontext diff_fun begin\n\nlemma diff_fun_cong: \"diff_fun k charts g\" if \"\\<And>x. x \\<in> src.carrier \\<Longrightarrow> f x = g x\"\n  using diff_cong[OF that]\n  by (auto simp: diff_fun_def)\n\nlemma diff_funD:\n  \"\\<exists>c1\\<in>src.atlas. x \\<in> domain c1 \\<and> (k-smooth_on (codomain c1) (f \\<circ> inv_chart c1))\"\n  if x: \"x \\<in> src.carrier\"\nproof -\n  from diff_fun_axioms[unfolded src.manifold_eucl.diff_iff, rule_format, OF x]\n  obtain c1 c2 where a: \"c1 \\<in> src.atlas\" \"c2 \\<in> manifold_eucl.atlas k\" \"x \\<in> domain c1\" \"f ` domain c1 \\<subseteq> domain c2\"\n    and s: \"k-smooth_on (codomain c1) (apply_chart c2 \\<circ> (f \\<circ> inv_chart c1))\"\n    by (auto simp: o_assoc)\n  from smooth_on_chart_inv[OF s] a\n  show ?thesis\n    by (force intro!: bexI[where x=c1] a continuous_intros)\nqed\n\nlemma diff_funE:\n  assumes \"x \\<in> src.carrier\"\n  obtains c1 where\n    \"c1\\<in>src.atlas\" \"x \\<in> domain c1\" \"k-smooth_on (codomain c1) (f \\<circ> inv_chart c1)\"\n  using diff_funD[OF assms]\n  by blast\n\nlemma diff_fun_between_chartsD:\n  assumes \"c \\<in> src.atlas\" \"x \\<in> domain c\"\n  shows \"k-smooth_on (codomain c) (f \\<circ> inv_chart c)\"\nproof -\n  have \"x \\<in> src.carrier\" \"f x \\<in> domain chart_eucl\" using assms by auto\n  from diff_between_chartsE[OF assms(1) chart_eucl_in_atlas assms(2) this]\n  obtain X where s: \"k-smooth_on X (f \\<circ> inv_chart c)\"\n    and X_def: \"X = codomain c \\<inter> inv_chart c -` (src.carrier \\<inter> f -` UNIV)\"\n    by (auto simp: o_def)\n  then have X_def: \"X = codomain c\" using assms\n    by (auto simp: X_def)\n  with s show ?thesis by auto\nqed\n\nlemma diff_fun_submanifold: \"diff_fun k (src.charts_submanifold S) f\"\n  if [simp]: \"open S\"\n  using diff_submanifold\n  unfolding diff_fun_def\n  by simp\n\nend\n\ncontext c_manifold begin\n\nlemma diff_fun_zero: \"diff_fun k charts 0\"\n  by (rule diff_funI) (auto simp: o_def elim!: carrierE)\n\nlemma diff_fun_const: \"diff_fun k charts (\\<lambda>x. c)\"\n  by (rule diff_funI) (auto simp: o_def elim!: carrierE)\n\nlemma diff_fun_add: \"diff_fun k charts (a + b)\" if \"diff_fun k charts a\" \"diff_fun k charts b\"\nproof (rule diff_funI)\n  fix x\n  assume x: \"x \\<in> carrier\"\n  interpret a: diff_fun k charts a by fact\n  interpret b: diff_fun k charts b by fact\n  from a.diff_funE[OF x]\n  obtain c where ca: \"c \\<in> atlas\" \"x \\<in> domain c\" \"k-smooth_on (codomain c) (a \\<circ> inv_chart c)\"\n    by blast\n  show \"\\<exists>c1\\<in>atlas. x \\<in> domain c1 \\<and> k-smooth_on (codomain c1) (a + b \\<circ> inv_chart c1)\"\n    using ca\n    by (auto intro!: bexI[where x=c] ca smooth_on_add_fun simp: plus_compose b.diff_fun_between_chartsD)\nqed\n\nlemma diff_fun_sum: \"diff_fun k charts (\\<lambda>x. \\<Sum>i\\<in>S. f i x)\" if \"\\<And>i. i \\<in> S \\<Longrightarrow> diff_fun k charts (f i)\"\n  using that\n  apply (induction S rule: infinite_finite_induct)\n  subgoal by (simp add: diff_fun_const)\n  subgoal by (simp add: diff_fun_const)\n  subgoal by (simp add: diff_fun_add[unfolded plus_fun_def])\n  done\n\nlemma diff_fun_scaleR: \"diff_fun k charts (\\<lambda>x. a x *\\<^sub>R b x)\"\n    if \"diff_fun k charts a\" \"diff_fun k charts b\"\nproof (rule diff_funI)\n  fix x\n  assume x: \"x \\<in> carrier\"\n  interpret a: diff_fun k charts a by fact\n  interpret b: diff_fun k charts b by fact\n  from a.diff_funE[OF x]\n  obtain c where ca: \"c \\<in> atlas\" \"x \\<in> domain c\" \"k-smooth_on (codomain c) (a \\<circ> inv_chart c)\"\n    by blast\n  have *: \"(\\<lambda>x. a x *\\<^sub>R b x) \\<circ> inv_chart c = (\\<lambda>x. (a o inv_chart c) x *\\<^sub>R (b o inv_chart c) x)\"\n    by auto\n  show \"\\<exists>c1\\<in>atlas. x \\<in> domain c1 \\<and> k-smooth_on (codomain c1) ((\\<lambda>x. a x *\\<^sub>R b x) \\<circ> inv_chart c1)\"\n    using ca\n    by (auto intro!: bexI[where x=c] smooth_on_scaleR\n        simp: mult_compose b.diff_fun_between_chartsD[unfolded o_def] * o_def)\nqed\n\nlemma diff_fun_scaleR_left: \"diff_fun k charts (c *\\<^sub>R b)\"\n  if \"diff_fun k charts b\"\n  by (auto simp: scaleR_fun_def intro!: diff_fun_scaleR that diff_fun_const)\n\nlemma diff_fun_times: \"diff_fun k charts (a * b)\" if \"diff_fun k charts a\" \"diff_fun k charts b\"\n  for a b::\"_ \\<Rightarrow> _::real_normed_algebra\"\nproof (rule diff_funI)\n  fix x\n  assume x: \"x \\<in> carrier\"\n  interpret a: diff_fun k charts a by fact\n  interpret b: diff_fun k charts b by fact\n  from a.diff_funE[OF x]\n  obtain c where ca: \"c \\<in> atlas\" \"x \\<in> domain c\" \"k-smooth_on (codomain c) (a \\<circ> inv_chart c)\"\n    by blast\n  show \"\\<exists>c1\\<in>atlas. x \\<in> domain c1 \\<and> k-smooth_on (codomain c1) (a * b \\<circ> inv_chart c1)\"\n    using ca\n    by (auto intro!: bexI[where x=c] ca smooth_on_times_fun simp: mult_compose b.diff_fun_between_chartsD)\nqed\n\nlemma diff_fun_divide: \"diff_fun k charts (\\<lambda>x. a x / b x)\"\n  if \"diff_fun k charts a\" \"diff_fun k charts b\"\n    and nz: \"\\<And>x. x \\<in> carrier \\<Longrightarrow> b x \\<noteq> 0\"\n  for a b::\"_ \\<Rightarrow> _::real_normed_field\"\nproof (rule diff_funI)\n  fix x\n  assume x: \"x \\<in> carrier\"\n  interpret a: diff_fun k charts a by fact\n  interpret b: diff_fun k charts b by fact\n  from a.diff_funE[OF x]\n  obtain c where ca: \"c \\<in> atlas\" \"x \\<in> domain c\" \"k-smooth_on (codomain c) (a \\<circ> inv_chart c)\"\n    by blast\n  show \"\\<exists>c1\\<in>atlas. x \\<in> domain c1 \\<and> k-smooth_on (codomain c1) ((\\<lambda>x. a x / b x) \\<circ> inv_chart c1)\"\n    using ca nz\n    by (auto intro!: bexI[where x=c] ca smooth_on_mult smooth_on_inverse\n        dest: b.diff_fun_between_chartsD\n        simp: mult_compose o_def\n        divide_inverse)\nqed\n\nlemma subspace_Collect_diff_fun:\n  \"subspace (Collect (diff_fun k charts))\"\n  by (auto simp: subspace_def diff_fun_zero diff_fun_add diff_fun_scaleR_left)\n\nend\n\nlemma manifold_eucl_carrier[simp]: \"manifold_eucl.carrier = UNIV\"\n  by (simp add: manifold_eucl.carrier_def)\n\nlemma diff_fun_charts_euclD: \"k-smooth_on UNIV g\" if \"diff_fun k charts_eucl g\"\nproof (rule smooth_on_open_subsetsI)\n  fix x::'a\n  interpret diff_fun k charts_eucl g by fact\n  have \"x \\<in> manifold_eucl.carrier\" by simp\n  from diff_funE[OF this] obtain c1\n    where c: \"c1 \\<in> manifold_eucl.atlas k\" \"x \\<in> domain c1\"\n      \"k-smooth_on (codomain c1) (g \\<circ> inv_chart c1)\" by auto\n  have \"k-smooth_on (domain c1) g\"\n    apply (rule smooth_on_chart_inv2)\n       apply (rule smooth_on_subset)\n        apply (rule c)\n    using c by auto\n  then show \"\\<exists>T. x \\<in> T \\<and> open T \\<and> k-smooth_on T g\"\n    using c by auto\nqed\n\nlemma diff_fun_charts_euclI: \"diff_fun k charts_eucl g\" if \"k-smooth_on UNIV g\"\n  apply (rule manifold_eucl.diff_funI)\n  apply auto\n  apply (rule bexI[where x=chart_eucl])\n  using that\n  by (auto simp: o_def)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Smooth_Manifolds/Differentiable_Manifold.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8479677602988602, "lm_q1q2_score": 0.7758065196033683}}
{"text": "theory Ex2\nimports Main\nbegin\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count n [] = 0\" |\n\"count n (x # xs) = (if x = n then 1 + count n xs else count n xs)\"\n\nvalue \"count 1 []\"\nvalue \"count 1 [1]\"\n\nlemma count_lt_length [simp]: \"count x xs \\<le> length xs\"\napply(induction xs)\napply(auto)\ndone\n\n(* Ex 2.4 *)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] x = [x]\" | \n\"snoc (x # xs) y = (x # (snoc xs y))\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\" |\n\"reverse (x # xs) = snoc (reverse xs) x\"\n\nvalue \"reverse [1,2,3]\"\n\nlemma snoc_rev [simp]: \"reverse (snoc xs a) = a # (reverse xs)\"\napply(induction xs)\napply(auto)\ndone\n\nlemma rev_rev [simp]: \"reverse (reverse xs) = xs\"\napply(induction xs)\napply(auto)\ndone\n\n(* Ex 2.5 *)\nfun sum :: \"nat \\<Rightarrow> nat\" where\n\"sum 0 = 0\" |\n\"sum (Suc n) = (Suc n) + (sum n)\"\n\nvalue \"(sum 3)\"\nvalue \"(4 div 2)::nat\"\n\nlemma sum_bin [simp]: \"sum n = n * (n + 1) div 2\"\napply(induction n)\napply(auto)\ndone\n\nend\n", "meta": {"author": "masateruk", "repo": "isabelle_concrete_semantics", "sha": "fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab", "save_path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics", "path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics/isabelle_concrete_semantics-fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab/chapter2/Ex2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7758065132806755}}
{"text": "(*  Title:       Projective geometry\n    Author:      Tim Makarios <tjm1983 at gmail.com>, 2012\n    Maintainer:  Tim Makarios <tjm1983 at gmail.com>\n*)\n\nsection \"Projective geometry\"\n\ntheory Projective\n  imports Linear_Algebra2\n  Euclid_Tarski\n  Action\nbegin\n\nsubsection \"Proportionality on non-zero vectors\"\n\ncontext vector_space\nbegin\n\n  definition proportionality :: \"('b \\<times> 'b) set\" where\n    \"proportionality \\<equiv> {(x, y). x \\<noteq> 0 \\<and> y \\<noteq> 0 \\<and> (\\<exists>k. x = scale k y)}\"\n\n  definition non_zero_vectors :: \"'b set\" where\n    \"non_zero_vectors \\<equiv> {x. x \\<noteq> 0}\"\n\n  lemma proportionality_refl_on: \"refl_on local.non_zero_vectors local.proportionality\"\n  proof -\n    have \"local.proportionality \\<subseteq> local.non_zero_vectors \\<times> local.non_zero_vectors\"\n      unfolding proportionality_def non_zero_vectors_def\n      by auto\n    moreover have \"\\<forall>x\\<in>local.non_zero_vectors. (x, x) \\<in> local.proportionality\"\n    proof\n      fix x\n      assume \"x \\<in> local.non_zero_vectors\"\n      hence \"x \\<noteq> 0\" unfolding non_zero_vectors_def ..\n      moreover have \"x = scale 1 x\" by simp\n      ultimately show \"(x, x) \\<in> local.proportionality\"\n        unfolding proportionality_def\n        by blast\n    qed\n    ultimately show \"refl_on local.non_zero_vectors local.proportionality\"\n      unfolding refl_on_def ..\n  qed\n\n  lemma proportionality_sym: \"sym local.proportionality\"\n  proof -\n    { fix x y\n      assume \"(x, y) \\<in> local.proportionality\"\n      hence \"x \\<noteq> 0\" and \"y \\<noteq> 0\" and \"\\<exists>k. x = scale k y\"\n        unfolding proportionality_def\n        by simp+\n      from \\<open>\\<exists>k. x = scale k y\\<close> obtain k where \"x = scale k y\" by auto\n      with \\<open>x \\<noteq> 0\\<close> have \"k \\<noteq> 0\" by simp\n      with \\<open>x = scale k y\\<close> have \"y = scale (1/k) x\" by simp\n      with \\<open>x \\<noteq> 0\\<close> and \\<open>y \\<noteq> 0\\<close> have \"(y, x) \\<in> local.proportionality\"\n        unfolding proportionality_def\n        by auto\n    }\n    thus \"sym local.proportionality\"\n      unfolding sym_def\n      by blast\n  qed\n\n  lemma proportionality_trans: \"trans local.proportionality\"\n  proof -\n    { fix x y z\n      assume \"(x, y) \\<in> local.proportionality\" and \"(y, z) \\<in> local.proportionality\"\n      hence \"x \\<noteq> 0\" and \"z \\<noteq> 0\" and \"\\<exists>j. x = scale j y\" and \"\\<exists>k. y = scale k z\"\n        unfolding proportionality_def\n        by simp+\n      from \\<open>\\<exists>j. x = scale j y\\<close> and \\<open>\\<exists>k. y = scale k z\\<close>\n      obtain j and k where \"x = scale j y\" and \"y = scale k z\" by auto+\n      hence \"x = scale (j * k) z\" by simp\n      with \\<open>x \\<noteq> 0\\<close> and \\<open>z \\<noteq> 0\\<close> have \"(x, z) \\<in> local.proportionality\"\n        unfolding proportionality_def\n        by auto\n    }\n    thus \"trans local.proportionality\"\n      unfolding trans_def\n      by blast\n  qed\n\n  theorem proportionality_equiv: \"equiv local.non_zero_vectors local.proportionality\"\n    unfolding equiv_def\n    by (simp add:\n      proportionality_refl_on\n      proportionality_sym\n      proportionality_trans)\n\nend\n\ndefinition invertible_proportionality ::\n  \"((real^('n::finite)^'n) \\<times> (real^'n^'n)) set\" where\n  \"invertible_proportionality \\<equiv>\n  real_vector.proportionality \\<inter> (Collect invertible \\<times> Collect invertible)\"\n\nlemma invertible_proportionality_equiv:\n  \"equiv (Collect invertible :: (real^('n::finite)^'n) set)\n  invertible_proportionality\"\n  (is \"equiv ?invs _\")\nproof -\n  from zero_not_invertible\n  have \"real_vector.non_zero_vectors \\<inter> ?invs = ?invs\"\n    unfolding real_vector.non_zero_vectors_def\n    by auto\n  from equiv_restrict and real_vector.proportionality_equiv\n  have \"equiv (real_vector.non_zero_vectors \\<inter> ?invs) invertible_proportionality\"\n    unfolding invertible_proportionality_def\n    by auto\n  with \\<open>real_vector.non_zero_vectors \\<inter> ?invs = ?invs\\<close>\n  show \"equiv ?invs invertible_proportionality\"\n    by simp\nqed\n\nsubsection \"Points of the real projective plane\"\n\ntypedef proj2 = \"(real_vector.non_zero_vectors :: (real^3) set)//real_vector.proportionality\"\nproof\n  have \"(axis 1 1 :: real^3) \\<in> real_vector.non_zero_vectors\"\n    unfolding real_vector.non_zero_vectors_def \n    by (simp add: axis_def vec_eq_iff[where 'a=\"real\"])\n  thus \"real_vector.proportionality `` {axis 1 1} \\<in> (real_vector.non_zero_vectors :: (real^3) set)//real_vector.proportionality\"\n    unfolding quotient_def \n    by auto\nqed\n\ndefinition proj2_rep :: \"proj2 \\<Rightarrow> real^3\" where\n  \"proj2_rep x \\<equiv> \\<some> v. v \\<in> Rep_proj2 x\"\n\ndefinition proj2_abs :: \"real^3 \\<Rightarrow> proj2\" where\n  \"proj2_abs v \\<equiv> Abs_proj2 (real_vector.proportionality `` {v})\"\n\nlemma proj2_rep_in: \"proj2_rep x \\<in> Rep_proj2 x\"\nproof -\n  let ?v = \"proj2_rep x\"\n  from quotient_element_nonempty and\n    real_vector.proportionality_equiv and\n    Rep_proj2 [of x]\n  have \"\\<exists> w. w \\<in> Rep_proj2 x\"\n    by auto\n  with someI_ex [of \"\\<lambda> z. z \\<in> Rep_proj2 x\"]\n  show \"?v \\<in> Rep_proj2 x\"\n    unfolding proj2_rep_def\n    by simp\nqed\n\nlemma proj2_rep_non_zero: \"proj2_rep x \\<noteq> 0\"\nproof -\n  from\n    Union_quotient [of real_vector.non_zero_vectors real_vector.proportionality]\n    and real_vector.proportionality_equiv\n    and Rep_proj2 [of x] and proj2_rep_in [of x]\n  have \"proj2_rep x \\<in> real_vector.non_zero_vectors\"\n    unfolding quotient_def\n    by auto\n  thus \"proj2_rep x \\<noteq> 0\"\n    unfolding real_vector.non_zero_vectors_def\n    by simp\nqed\n\nlemma proj2_rep_abs:\n  fixes v :: \"real^3\"\n  assumes \"v \\<in> real_vector.non_zero_vectors\"\n  shows \"(v, proj2_rep (proj2_abs v)) \\<in> real_vector.proportionality\"\nproof -\n  from \\<open>v \\<in> real_vector.non_zero_vectors\\<close>\n  have \"real_vector.proportionality `` {v} \\<in> (real_vector.non_zero_vectors :: (real^3) set)//real_vector.proportionality\"\n    unfolding quotient_def\n    by auto \n  with Abs_proj2_inverse\n  have \"Rep_proj2 (proj2_abs v) = real_vector.proportionality `` {v}\"\n    unfolding proj2_abs_def\n    by simp\n  with proj2_rep_in\n  have \"proj2_rep (proj2_abs v) \\<in> real_vector.proportionality `` {v}\" by auto\n  thus \"(v, proj2_rep (proj2_abs v)) \\<in> real_vector.proportionality\" by simp\nqed\n\nlemma proj2_abs_rep: \"proj2_abs (proj2_rep x) = x\"\nproof -\n  from partition_Image_element\n  [of real_vector.non_zero_vectors\n    real_vector.proportionality\n    \"Rep_proj2 x\"\n    \"proj2_rep x\"]\n    and real_vector.proportionality_equiv\n    and Rep_proj2 [of x] and proj2_rep_in [of x]\n  have \"real_vector.proportionality `` {proj2_rep x} = Rep_proj2 x\"\n    by simp\n  with Rep_proj2_inverse show \"proj2_abs (proj2_rep x) = x\"\n    unfolding proj2_abs_def\n    by simp\nqed\n\nlemma proj2_abs_mult:\n  assumes \"c \\<noteq> 0\"\n  shows \"proj2_abs (c *\\<^sub>R v) = proj2_abs v\"\nproof cases\n  assume \"v = 0\"\n  thus \"proj2_abs (c *\\<^sub>R v) = proj2_abs v\" by simp\nnext\n  assume \"v \\<noteq> 0\"\n  with \\<open>c \\<noteq> 0\\<close>\n  have \"(c *\\<^sub>R v, v) \\<in> real_vector.proportionality\"\n    and \"c *\\<^sub>R v \\<in> real_vector.non_zero_vectors\"\n    and \"v \\<in> real_vector.non_zero_vectors\"\n    unfolding real_vector.proportionality_def\n      and real_vector.non_zero_vectors_def\n    by simp_all\n  with eq_equiv_class_iff\n  [of real_vector.non_zero_vectors\n    real_vector.proportionality\n    \"c *\\<^sub>R v\"\n    v]\n    and real_vector.proportionality_equiv\n  have \"real_vector.proportionality `` {c *\\<^sub>R v} =\n    real_vector.proportionality `` {v}\"\n    by simp\n  thus \"proj2_abs (c *\\<^sub>R v) = proj2_abs v\"\n    unfolding proj2_abs_def\n    by simp\nqed\n\nlemma proj2_abs_mult_rep:\n  assumes \"c \\<noteq> 0\"\n  shows \"proj2_abs (c *\\<^sub>R proj2_rep x) = x\"\n  using proj2_abs_mult and proj2_abs_rep and assms\n  by simp\n\nlemma proj2_rep_inj: \"inj proj2_rep\"\n  by (simp add: inj_on_inverseI [of UNIV proj2_abs proj2_rep] proj2_abs_rep)\n\nlemma proj2_rep_abs2:\n  assumes \"v \\<noteq> 0\"\n  shows \"\\<exists> k. k \\<noteq> 0 \\<and> proj2_rep (proj2_abs v) = k *\\<^sub>R v\"\nproof -\n  from proj2_rep_abs [of v] and \\<open>v \\<noteq> 0\\<close>\n  have \"(v, proj2_rep (proj2_abs v)) \\<in> real_vector.proportionality\"\n    unfolding real_vector.non_zero_vectors_def\n    by simp\n  then obtain c where \"v = c *\\<^sub>R proj2_rep (proj2_abs v)\"\n    unfolding real_vector.proportionality_def\n    by auto\n  with \\<open>v \\<noteq> 0\\<close> have \"c \\<noteq> 0\" by auto\n  hence \"1/c \\<noteq> 0\" by simp\n\n  from \\<open>v = c *\\<^sub>R proj2_rep (proj2_abs v)\\<close>\n  have \"(1/c) *\\<^sub>R v = (1/c) *\\<^sub>R c *\\<^sub>R proj2_rep (proj2_abs v)\"\n    by simp\n  with \\<open>c \\<noteq> 0\\<close> have \"proj2_rep (proj2_abs v) = (1/c) *\\<^sub>R v\" by simp\n\n  with \\<open>1/c \\<noteq> 0\\<close> show \"\\<exists> k. k \\<noteq> 0 \\<and> proj2_rep (proj2_abs v) = k *\\<^sub>R v\"\n    by blast\nqed\n\nlemma proj2_abs_abs_mult:\n  assumes \"proj2_abs v = proj2_abs w\" and \"w \\<noteq> 0\"\n  shows \"\\<exists> c. v = c *\\<^sub>R w\"\nproof cases\n  assume \"v = 0\"\n  hence \"v = 0 *\\<^sub>R w\" by simp\n  thus \"\\<exists> c. v = c *\\<^sub>R w\" ..\nnext\n  assume \"v \\<noteq> 0\"\n  from \\<open>proj2_abs v = proj2_abs w\\<close>\n  have \"proj2_rep (proj2_abs v) = proj2_rep (proj2_abs w)\" by simp\n  with proj2_rep_abs2 and \\<open>w \\<noteq> 0\\<close>\n  obtain k where \"proj2_rep (proj2_abs v) = k *\\<^sub>R w\" by auto\n  with proj2_rep_abs2 [of v] and \\<open>v \\<noteq> 0\\<close>\n  obtain j where \"j \\<noteq> 0\" and \"j *\\<^sub>R v = k *\\<^sub>R w\" by auto\n  hence \"(1/j) *\\<^sub>R j *\\<^sub>R v = (1/j) *\\<^sub>R k *\\<^sub>R w\" by simp\n  with \\<open>j \\<noteq> 0\\<close> have \"v = (k/j) *\\<^sub>R w\" by simp\n  thus \"\\<exists> c. v = c *\\<^sub>R w\" ..\nqed\n\nlemma dependent_proj2_abs:\n  assumes \"p \\<noteq> 0\" and \"q \\<noteq> 0\" and \"i \\<noteq> 0 \\<or> j \\<noteq> 0\" and \"i *\\<^sub>R p + j *\\<^sub>R q = 0\"\n  shows \"proj2_abs p = proj2_abs q\"\nproof -\n  have \"i \\<noteq> 0\"\n  proof\n    assume \"i = 0\"\n    with \\<open>i \\<noteq> 0 \\<or> j \\<noteq> 0\\<close> have \"j \\<noteq> 0\" by simp\n    with \\<open>i *\\<^sub>R p + j *\\<^sub>R q = 0\\<close> and \\<open>q \\<noteq> 0\\<close> have \"i *\\<^sub>R p \\<noteq> 0\" by auto\n    with \\<open>i = 0\\<close> show False by simp\n  qed\n  with \\<open>p \\<noteq> 0\\<close> and \\<open>i *\\<^sub>R p + j *\\<^sub>R q = 0\\<close> have \"j \\<noteq> 0\" by auto\n\n  from \\<open>i \\<noteq> 0\\<close>\n  have \"proj2_abs p = proj2_abs (i *\\<^sub>R p)\" by (rule proj2_abs_mult [symmetric])\n  also from \\<open>i *\\<^sub>R p + j *\\<^sub>R q = 0\\<close> and proj2_abs_mult [of \"-1\" \"j *\\<^sub>R q\"]\n  have \"\\<dots> = proj2_abs (j *\\<^sub>R q)\" by (simp add: algebra_simps [symmetric])\n  also from \\<open>j \\<noteq> 0\\<close> have \"\\<dots> = proj2_abs q\" by (rule proj2_abs_mult)\n  finally show \"proj2_abs p = proj2_abs q\" .\nqed\n\nlemma proj2_rep_dependent:\n  assumes \"i *\\<^sub>R proj2_rep v + j *\\<^sub>R proj2_rep w = 0\"\n  (is \"i *\\<^sub>R ?p + j *\\<^sub>R ?q = 0\")\n  and \"i \\<noteq> 0 \\<or> j \\<noteq> 0\"\n  shows \"v = w\"\nproof -\n  have \"?p \\<noteq> 0\" and \"?q \\<noteq> 0\" by (rule proj2_rep_non_zero)+\n  with \\<open>i \\<noteq> 0 \\<or> j \\<noteq> 0\\<close> and \\<open>i *\\<^sub>R ?p + j *\\<^sub>R ?q = 0\\<close>\n  have \"proj2_abs ?p = proj2_abs ?q\" by (simp add: dependent_proj2_abs)\n  thus \"v = w\" by (simp add: proj2_abs_rep)\nqed\n\nlemma proj2_rep_independent:\n  assumes \"p \\<noteq> q\"\n  shows \"independent {proj2_rep p, proj2_rep q}\"\nproof\n  let ?p' = \"proj2_rep p\"\n  let ?q' = \"proj2_rep q\"\n  let ?S = \"{?p', ?q'}\"\n  assume \"dependent ?S\"\n  from proj2_rep_inj and \\<open>p \\<noteq> q\\<close> have \"?p' \\<noteq> ?q'\"\n    unfolding inj_on_def\n    by auto\n  with dependent_explicit_2 [of ?p' ?q'] and \\<open>dependent ?S\\<close>\n  obtain i and j where \"i *\\<^sub>R ?p' + j *\\<^sub>R ?q' = 0\" and \"i \\<noteq> 0 \\<or> j \\<noteq> 0\"\n    by (simp add: scalar_equiv) auto\n  with proj2_rep_dependent have \"p = q\" by simp\n  with \\<open>p \\<noteq> q\\<close> show False ..\nqed\n\nsubsection \"Lines of the real projective plane\"\n\ndefinition proj2_Col :: \"[proj2, proj2, proj2] \\<Rightarrow> bool\" where\n  \"proj2_Col p q r \\<equiv>\n  (\\<exists> i j k. i *\\<^sub>R proj2_rep p + j *\\<^sub>R proj2_rep q + k *\\<^sub>R proj2_rep r = 0\n  \\<and> (i\\<noteq>0 \\<or> j\\<noteq>0 \\<or> k\\<noteq>0))\"\n\nlemma proj2_Col_abs:\n  assumes \"p \\<noteq> 0\" and \"q \\<noteq> 0\" and \"r \\<noteq> 0\" and \"i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\"\n  and \"i *\\<^sub>R p + j *\\<^sub>R q + k *\\<^sub>R r = 0\"\n  shows \"proj2_Col (proj2_abs p) (proj2_abs q) (proj2_abs r)\"\n  (is \"proj2_Col ?pp ?pq ?pr\")\nproof -\n  from \\<open>p \\<noteq> 0\\<close> and proj2_rep_abs2\n  obtain i' where \"i' \\<noteq> 0\" and \"proj2_rep ?pp = i' *\\<^sub>R p\" (is \"?rp = _\") by auto\n  from \\<open>q \\<noteq> 0\\<close> and proj2_rep_abs2\n  obtain j' where \"j' \\<noteq> 0\" and \"proj2_rep ?pq = j' *\\<^sub>R q\" (is \"?rq = _\") by auto\n  from \\<open>r \\<noteq> 0\\<close> and proj2_rep_abs2\n  obtain k' where \"k' \\<noteq> 0\" and \"proj2_rep ?pr = k' *\\<^sub>R r\" (is \"?rr = _\") by auto\n  with \\<open>i *\\<^sub>R p + j *\\<^sub>R q + k *\\<^sub>R r = 0\\<close>\n    and \\<open>i' \\<noteq> 0\\<close> and \\<open>proj2_rep ?pp = i' *\\<^sub>R p\\<close>\n    and \\<open>j' \\<noteq> 0\\<close> and \\<open>proj2_rep ?pq = j' *\\<^sub>R q\\<close>\n  have \"(i/i') *\\<^sub>R ?rp + (j/j') *\\<^sub>R ?rq + (k/k') *\\<^sub>R ?rr = 0\" by simp\n\n  from \\<open>i' \\<noteq> 0\\<close> and \\<open>j' \\<noteq> 0\\<close> and \\<open>k' \\<noteq> 0\\<close> and \\<open>i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\\<close>\n  have \"i/i' \\<noteq> 0 \\<or> j/j' \\<noteq> 0 \\<or> k/k' \\<noteq> 0\" by simp\n  with \\<open>(i/i') *\\<^sub>R ?rp + (j/j') *\\<^sub>R ?rq + (k/k') *\\<^sub>R ?rr = 0\\<close>\n  show \"proj2_Col ?pp ?pq ?pr\" by (unfold proj2_Col_def, best)\nqed\n\nlemma proj2_Col_permute:\n  assumes \"proj2_Col a b c\"\n  shows \"proj2_Col a c b\"\n  and \"proj2_Col b a c\"\nproof -\n  let ?a' = \"proj2_rep a\"\n  let ?b' = \"proj2_rep b\"\n  let ?c' = \"proj2_rep c\"\n  from \\<open>proj2_Col a b c\\<close>\n  obtain i and j and k where\n    \"i *\\<^sub>R ?a' + j *\\<^sub>R ?b' + k *\\<^sub>R ?c' = 0\"\n    and \"i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\"\n    unfolding proj2_Col_def\n    by auto\n\n  from \\<open>i *\\<^sub>R ?a' + j *\\<^sub>R ?b' + k *\\<^sub>R ?c' = 0\\<close>\n  have \"i *\\<^sub>R ?a' + k *\\<^sub>R ?c' + j *\\<^sub>R ?b' = 0\"\n    and \"j *\\<^sub>R ?b' + i *\\<^sub>R ?a' + k *\\<^sub>R ?c' = 0\"\n    by (simp_all add: ac_simps)\n  moreover from \\<open>i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\\<close>\n  have \"i \\<noteq> 0 \\<or> k \\<noteq> 0 \\<or> j \\<noteq> 0\" and \"j \\<noteq> 0 \\<or> i \\<noteq> 0 \\<or> k \\<noteq> 0\" by auto\n  ultimately show \"proj2_Col a c b\" and \"proj2_Col b a c\"\n    unfolding proj2_Col_def\n    by auto\nqed\n\nlemma proj2_Col_coincide: \"proj2_Col a a c\"\nproof -\n  have \"1 *\\<^sub>R proj2_rep a + (-1) *\\<^sub>R proj2_rep a + 0 *\\<^sub>R proj2_rep c = 0\"\n    by simp\n  moreover have \"(1::real) \\<noteq> 0\" by simp\n  ultimately show \"proj2_Col a a c\"\n    unfolding proj2_Col_def\n    by blast\nqed\n\nlemma proj2_Col_iff:\n  assumes \"a \\<noteq> r\"\n  shows \"proj2_Col a r t \\<longleftrightarrow>\n  t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R (proj2_rep a) + (proj2_rep r)))\"\nproof\n  let ?a' = \"proj2_rep a\"\n  let ?r' = \"proj2_rep r\"\n  let ?t' = \"proj2_rep t\"\n\n  { assume \"proj2_Col a r t\"\n    then obtain h and j and k where\n      \"h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0\"\n      and \"h \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\"\n      unfolding proj2_Col_def\n      by auto\n    \n    show \"t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r'))\"\n    proof cases\n      assume \"j = 0\"\n      with \\<open>h \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\\<close> have \"h \\<noteq> 0 \\<or> k \\<noteq> 0\" by simp\n      with proj2_rep_dependent\n        and \\<open>h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0\\<close>\n        and \\<open>j = 0\\<close>\n      have \"t = a\" by auto\n      thus \"t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r'))\" ..\n    next\n      assume \"j \\<noteq> 0\"\n      have \"k \\<noteq> 0\"\n      proof (rule ccontr)\n        assume \"\\<not> k \\<noteq> 0\"\n        with proj2_rep_dependent\n          and \\<open>h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0\\<close>\n          and \\<open>j \\<noteq> 0\\<close>\n        have \"a = r\" by simp\n        with \\<open>a \\<noteq> r\\<close> show False ..\n      qed\n      \n      from \\<open>h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0\\<close>\n      have \"h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' - k *\\<^sub>R ?t' = -k *\\<^sub>R ?t'\" by simp\n      hence \"h *\\<^sub>R ?a' + j *\\<^sub>R ?r' = -k *\\<^sub>R ?t'\" by simp\n      with proj2_abs_mult_rep [of \"-k\"] and \\<open>k \\<noteq> 0\\<close>\n      have \"proj2_abs (h *\\<^sub>R ?a' + j *\\<^sub>R ?r') = t\" by simp\n      with proj2_abs_mult [of \"1/j\" \"h *\\<^sub>R ?a' + j *\\<^sub>R ?r'\"] and \\<open>j \\<noteq> 0\\<close>\n      have \"proj2_abs ((h/j) *\\<^sub>R ?a' + ?r') = t\"\n        by (simp add: scaleR_right_distrib)\n      hence \"\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r')\" by auto\n      thus \"t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r'))\" ..\n    qed\n  }\n\n  { assume \"t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r'))\"\n    show \"proj2_Col a r t\"\n    proof cases\n      assume \"t = a\"\n      with proj2_Col_coincide and proj2_Col_permute\n      show \"proj2_Col a r t\" by blast\n    next\n      assume \"t \\<noteq> a\"\n      with \\<open>t = a \\<or> (\\<exists> i. t = proj2_abs (i *\\<^sub>R ?a' + ?r'))\\<close>\n      obtain i where \"t = proj2_abs (i *\\<^sub>R ?a' + ?r')\" by auto\n      from proj2_rep_dependent [of i a 1 r] and \\<open>a \\<noteq> r\\<close>\n      have \"i *\\<^sub>R ?a' + ?r' \\<noteq> 0\" by auto\n      with proj2_rep_abs2 and \\<open>t = proj2_abs (i *\\<^sub>R ?a' + ?r')\\<close>\n      obtain j where \"?t' = j *\\<^sub>R (i *\\<^sub>R ?a' + ?r')\" by auto\n      hence \"?t' - ?t' = (j * i) *\\<^sub>R ?a' + j *\\<^sub>R ?r' + (-1) *\\<^sub>R ?t'\"\n        by (simp add: scaleR_right_distrib)\n      hence \"(j * i) *\\<^sub>R ?a' + j *\\<^sub>R ?r' + (-1) *\\<^sub>R ?t' = 0\" by simp\n      have \"\\<exists> h j k. h *\\<^sub>R ?a' + j *\\<^sub>R ?r' + k *\\<^sub>R ?t' = 0\n        \\<and> (h \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0)\"\n      proof standard+\n        from \\<open>(j * i) *\\<^sub>R ?a' + j *\\<^sub>R ?r' + (-1) *\\<^sub>R ?t' = 0\\<close>\n        show \"(j * i) *\\<^sub>R ?a' + j *\\<^sub>R ?r' + (-1) *\\<^sub>R ?t' = 0\" .\n        show \"j * i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> (-1::real) \\<noteq> 0\" by simp\n      qed\n      thus \"proj2_Col a r t\"\n        unfolding proj2_Col_def .\n    qed\n  }\nqed\n\ndefinition proj2_Col_coeff :: \"proj2 \\<Rightarrow> proj2 \\<Rightarrow> proj2 \\<Rightarrow> real\" where\n  \"proj2_Col_coeff a r t \\<equiv> \\<some> i. t = proj2_abs (i *\\<^sub>R proj2_rep a + proj2_rep r)\"\n\nlemma proj2_Col_coeff:\n  assumes \"proj2_Col a r t\" and \"a \\<noteq> r\" and \"t \\<noteq> a\"\n  shows \"t = proj2_abs ((proj2_Col_coeff a r t) *\\<^sub>R proj2_rep a + proj2_rep r)\"\nproof -\n  from \\<open>a \\<noteq> r\\<close> and \\<open>proj2_Col a r t\\<close> and \\<open>t \\<noteq> a\\<close> and proj2_Col_iff\n  have \"\\<exists> i. t = proj2_abs (i *\\<^sub>R proj2_rep a + proj2_rep r)\" by simp\n  thus \"t = proj2_abs ((proj2_Col_coeff a r t) *\\<^sub>R proj2_rep a + proj2_rep r)\"\n    by (unfold proj2_Col_coeff_def) (rule someI_ex)\nqed\n\nlemma proj2_Col_coeff_unique':\n  assumes \"a \\<noteq> 0\" and \"r \\<noteq> 0\" and \"proj2_abs a \\<noteq> proj2_abs r\"\n  and \"proj2_abs (i *\\<^sub>R a + r) = proj2_abs (j *\\<^sub>R a + r)\"\n  shows \"i = j\"\nproof -\n  from \\<open>a \\<noteq> 0\\<close> and \\<open>r \\<noteq> 0\\<close> and \\<open>proj2_abs a \\<noteq> proj2_abs r\\<close>\n    and dependent_proj2_abs [of a r _ 1]\n  have \"i *\\<^sub>R a + r \\<noteq> 0\" and \"j *\\<^sub>R a + r \\<noteq> 0\" by auto\n  with proj2_rep_abs2 [of \"i *\\<^sub>R a + r\"]\n    and proj2_rep_abs2 [of \"j *\\<^sub>R a + r\"]\n  obtain k and l where \"k \\<noteq> 0\"\n    and \"proj2_rep (proj2_abs (i *\\<^sub>R a + r)) = k *\\<^sub>R (i *\\<^sub>R a + r)\"\n    and \"proj2_rep (proj2_abs (j *\\<^sub>R a + r)) = l *\\<^sub>R (j *\\<^sub>R a + r)\"\n    by auto\n  with \\<open>proj2_abs (i *\\<^sub>R a + r) = proj2_abs (j *\\<^sub>R a + r)\\<close>\n  have \"(k * i) *\\<^sub>R a + k *\\<^sub>R r = (l * j) *\\<^sub>R a + l *\\<^sub>R r\"\n    by (simp add: scaleR_right_distrib)\n  hence \"(k * i - l * j) *\\<^sub>R a + (k - l) *\\<^sub>R r = 0\"\n    by (simp add: algebra_simps vec_eq_iff)\n  with \\<open>a \\<noteq> 0\\<close> and \\<open>r \\<noteq> 0\\<close> and \\<open>proj2_abs a \\<noteq> proj2_abs r\\<close>\n    and dependent_proj2_abs [of a r \"k * i - l * j\" \"k - l\"]\n  have \"k * i - l * j = 0\" and \"k - l = 0\" by auto\n  from \\<open>k - l = 0\\<close> have \"k = l\" by simp\n  with \\<open>k * i - l * j = 0\\<close> have \"k * i = k * j\" by simp\n  with \\<open>k \\<noteq> 0\\<close> show \"i = j\" by simp\nqed\n\nlemma proj2_Col_coeff_unique:\n  assumes \"a \\<noteq> r\"\n  and \"proj2_abs (i *\\<^sub>R proj2_rep a + proj2_rep r)\n  = proj2_abs (j *\\<^sub>R proj2_rep a + proj2_rep r)\"\n  shows \"i = j\"\nproof -\n  let ?a' = \"proj2_rep a\"\n  let ?r' = \"proj2_rep r\"\n  have \"?a' \\<noteq> 0\" and \"?r' \\<noteq> 0\" by (rule proj2_rep_non_zero)+\n\n  from \\<open>a \\<noteq> r\\<close> have \"proj2_abs ?a' \\<noteq> proj2_abs ?r'\" by (simp add: proj2_abs_rep)\n  with \\<open>?a' \\<noteq> 0\\<close> and \\<open>?r' \\<noteq> 0\\<close>\n    and \\<open>proj2_abs (i *\\<^sub>R ?a' + ?r') = proj2_abs (j *\\<^sub>R ?a' + ?r')\\<close>\n    and proj2_Col_coeff_unique'\n  show \"i = j\" by simp\nqed\n\ndatatype proj2_line = P2L proj2\n\ndefinition L2P :: \"proj2_line \\<Rightarrow> proj2\" where\n  \"L2P l \\<equiv> case l of P2L p \\<Rightarrow> p\"\n\nlemma L2P_P2L [simp]: \"L2P (P2L p) = p\"\n  unfolding L2P_def\n  by simp\n\nlemma P2L_L2P [simp]: \"P2L (L2P l) = l\"\n  by (induct l) simp\n\nlemma L2P_inj [simp]:\n  assumes \"L2P l = L2P m\"\n  shows \"l = m\"\n  using P2L_L2P [of l] and assms\n  by simp\n\nlemma P2L_to_L2P: \"P2L p = l \\<longleftrightarrow> p = L2P l\"\nproof\n  assume \"P2L p = l\"\n  hence \"L2P (P2L p) = L2P l\" by simp\n  thus \"p = L2P l\" by simp\nnext\n  assume \"p = L2P l\"\n  thus \"P2L p = l\" by simp\nqed\n\ndefinition proj2_line_abs :: \"real^3 \\<Rightarrow> proj2_line\" where\n  \"proj2_line_abs v \\<equiv> P2L (proj2_abs v)\"\n\ndefinition proj2_line_rep :: \"proj2_line \\<Rightarrow> real^3\" where\n  \"proj2_line_rep l \\<equiv> proj2_rep (L2P l)\"\n\nlemma proj2_line_rep_abs:\n  assumes \"v \\<noteq> 0\"\n  shows \"\\<exists> k. k \\<noteq> 0 \\<and> proj2_line_rep (proj2_line_abs v) = k *\\<^sub>R v\"\n  unfolding proj2_line_rep_def and proj2_line_abs_def\n  using proj2_rep_abs2 and \\<open>v \\<noteq> 0\\<close>\n  by simp\n\nlemma proj2_line_abs_rep [simp]: \"proj2_line_abs (proj2_line_rep l) = l\"\n  unfolding proj2_line_abs_def and proj2_line_rep_def\n  by (simp add: proj2_abs_rep)\n\nlemma proj2_line_rep_non_zero: \"proj2_line_rep l \\<noteq> 0\"\n  unfolding proj2_line_rep_def\n  using proj2_rep_non_zero\n  by simp\n\nlemma proj2_line_rep_dependent:\n  assumes \"i *\\<^sub>R proj2_line_rep l + j *\\<^sub>R proj2_line_rep m = 0\"\n  and \"i \\<noteq> 0 \\<or> j \\<noteq> 0\"\n  shows \"l = m\"\n  using proj2_rep_dependent [of i \"L2P l\" j \"L2P m\"] and assms\n  unfolding proj2_line_rep_def\n  by simp\n\nlemma proj2_line_abs_mult:\n  assumes \"k \\<noteq> 0\"\n  shows \"proj2_line_abs (k *\\<^sub>R v) = proj2_line_abs v\"\n  unfolding proj2_line_abs_def\n  using \\<open>k \\<noteq> 0\\<close>\n  by (subst proj2_abs_mult) simp_all\n\nlemma proj2_line_abs_abs_mult:\n  assumes \"proj2_line_abs v = proj2_line_abs w\" and \"w \\<noteq> 0\"\n  shows \"\\<exists> k. v = k *\\<^sub>R w\"\n  using assms\n  by (unfold proj2_line_abs_def) (simp add: proj2_abs_abs_mult)\n\ndefinition proj2_incident :: \"proj2 \\<Rightarrow> proj2_line \\<Rightarrow> bool\" where\n  \"proj2_incident p l \\<equiv> (proj2_rep p) \\<bullet> (proj2_line_rep l) = 0\"\n\nlemma proj2_points_define_line:\n  shows \"\\<exists> l. proj2_incident p l \\<and> proj2_incident q l\"\nproof -\n  let ?p' = \"proj2_rep p\"\n  let ?q' = \"proj2_rep q\"\n  let ?B = \"{?p', ?q'}\"\n  from card_suc_ge_insert [of ?p' \"{?q'}\"] have \"card ?B \\<le> 2\" by simp\n  with dim_le_card' [of ?B] have \"dim ?B < 3\" by simp\n  with lowdim_subset_hyperplane [of ?B]\n  obtain l' where \"l' \\<noteq> 0\" and \"span ?B \\<subseteq> {x. l' \\<bullet> x = 0}\" by auto\n  let ?l = \"proj2_line_abs l'\"\n  let ?l'' = \"proj2_line_rep ?l\"\n  from proj2_line_rep_abs and \\<open>l' \\<noteq> 0\\<close>\n  obtain k where \"?l'' = k *\\<^sub>R l'\" by auto\n\n  have \"?p' \\<in> ?B\" and \"?q' \\<in> ?B\" by simp_all\n  with span_superset [of ?B] and \\<open>span ?B \\<subseteq> {x. l' \\<bullet> x = 0}\\<close>\n  have \"l' \\<bullet> ?p' = 0\" and \"l' \\<bullet> ?q' = 0\" by auto\n  hence \"?p' \\<bullet> l' = 0\" and \"?q' \\<bullet> l' = 0\" by (simp_all add: inner_commute)\n  with dot_scaleR_mult(2) [of _ k l'] and \\<open>?l'' = k *\\<^sub>R l'\\<close>\n  have \"proj2_incident p ?l \\<and> proj2_incident q ?l\"\n    unfolding proj2_incident_def\n    by simp\n  thus \"\\<exists> l. proj2_incident p l \\<and> proj2_incident q l\" by auto\nqed\n\ndefinition proj2_line_through :: \"proj2 \\<Rightarrow> proj2 \\<Rightarrow> proj2_line\" where\n  \"proj2_line_through p q \\<equiv> \\<some> l. proj2_incident p l \\<and> proj2_incident q l\"\n\nlemma proj2_line_through_incident:\n  shows \"proj2_incident p (proj2_line_through p q)\"\n  and \"proj2_incident q (proj2_line_through p q)\"\n  unfolding proj2_line_through_def\n  using proj2_points_define_line\n    and someI_ex [of \"\\<lambda> l. proj2_incident p l \\<and> proj2_incident q l\"]\n  by simp_all\n\nlemma proj2_line_through_unique:\n  assumes \"p \\<noteq> q\" and \"proj2_incident p l\" and \"proj2_incident q l\"\n  shows \"l = proj2_line_through p q\"\nproof -\n  let ?l' = \"proj2_line_rep l\"\n  let ?m = \"proj2_line_through p q\"\n  let ?m' = \"proj2_line_rep ?m\"\n  let ?p' = \"proj2_rep p\"\n  let ?q' = \"proj2_rep q\"\n  let ?A = \"{?p', ?q'}\"\n  let ?B = \"insert ?m' ?A\"\n  from proj2_line_through_incident\n  have \"proj2_incident p ?m\" and \"proj2_incident q ?m\" by simp_all\n  with \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close>\n  have ortho: \"\\<And>w. w\\<in>?A \\<Longrightarrow> orthogonal ?m' w\" \"\\<And>w. w\\<in>?A \\<Longrightarrow> orthogonal ?l' w\"\n    unfolding proj2_incident_def and orthogonal_def\n    by (metis empty_iff inner_commute insert_iff)+\n  from proj2_rep_independent and \\<open>p \\<noteq> q\\<close> have \"independent ?A\" by simp\n  from proj2_line_rep_non_zero have \"?m' \\<noteq> 0\" by simp\n  with orthogonal_independent \\<open>independent ?A\\<close> ortho\n  have \"independent ?B\" by auto\n\n  from proj2_rep_inj and \\<open>p \\<noteq> q\\<close> have \"?p' \\<noteq> ?q'\"\n    unfolding inj_on_def\n    by auto\n  hence \"card ?A = 2\" by simp\n  moreover have \"?m' \\<notin> ?A\"\n    using ortho(1) orthogonal_self proj2_line_rep_non_zero by auto\n  ultimately have \"card ?B = 3\" by simp\n  with independent_is_basis [of ?B] and \\<open>independent ?B\\<close>\n  have \"is_basis ?B\" by simp\n  with basis_expand obtain c where \"?l' = (\\<Sum> v\\<in>?B. c v *\\<^sub>R v)\" by auto\n  let ?l'' = \"?l' - c ?m' *\\<^sub>R ?m'\"\n  from \\<open>?l' = (\\<Sum> v\\<in>?B. c v *\\<^sub>R v)\\<close> and \\<open>?m' \\<notin> ?A\\<close>\n  have \"?l'' = (\\<Sum> v\\<in>?A. c v *\\<^sub>R v)\" by simp\n  with orthogonal_sum [of ?A] ortho\n  have \"orthogonal ?l' ?l''\" and \"orthogonal ?m' ?l''\"\n    by (simp_all add: scalar_equiv)\n  from \\<open>orthogonal ?m' ?l''\\<close>\n  have \"orthogonal (c ?m' *\\<^sub>R ?m') ?l''\" by (simp add: orthogonal_clauses)\n  with \\<open>orthogonal ?l' ?l''\\<close>\n  have \"orthogonal ?l'' ?l''\" by (simp add: orthogonal_clauses)\n  with orthogonal_self_eq_0 [of ?l''] have \"?l'' = 0\" by simp\n  with proj2_line_rep_dependent [of 1 l \"- c ?m'\" ?m] show \"l = ?m\" by simp\nqed\n\nlemma proj2_incident_unique:\n  assumes \"proj2_incident p l\"\n  and \"proj2_incident q l\"\n  and \"proj2_incident p m\"\n  and \"proj2_incident q m\"\n  shows \"p = q \\<or> l = m\"\nproof cases\n  assume \"p = q\"\n  thus \"p = q \\<or> l = m\" ..\nnext\n  assume \"p \\<noteq> q\"\n  with \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close>\n    and proj2_line_through_unique\n  have \"l = proj2_line_through p q\" by simp\n  moreover from \\<open>p \\<noteq> q\\<close> and \\<open>proj2_incident p m\\<close> and \\<open>proj2_incident q m\\<close>\n  have \"m = proj2_line_through p q\" by (rule proj2_line_through_unique)\n  ultimately show \"p = q \\<or> l = m\" by simp\nqed\n\nlemma proj2_lines_define_point: \"\\<exists> p. proj2_incident p l \\<and> proj2_incident p m\"\nproof -\n  let ?l' = \"L2P l\"\n  let ?m' = \"L2P m\"\n  from proj2_points_define_line [of ?l' ?m']\n  obtain p' where \"proj2_incident ?l' p' \\<and> proj2_incident ?m' p'\" by auto\n  hence \"proj2_incident (L2P p') l \\<and> proj2_incident (L2P p') m\"\n    unfolding proj2_incident_def and proj2_line_rep_def\n    by (simp add: inner_commute)\n  thus \"\\<exists> p. proj2_incident p l \\<and> proj2_incident p m\" by auto\nqed\n\ndefinition proj2_intersection :: \"proj2_line \\<Rightarrow> proj2_line \\<Rightarrow> proj2\" where\n  \"proj2_intersection l m \\<equiv> L2P (proj2_line_through (L2P l) (L2P m))\"\n\nlemma proj2_incident_switch:\n  assumes \"proj2_incident p l\"\n  shows \"proj2_incident (L2P l) (P2L p)\"\n  using assms\n  unfolding proj2_incident_def and proj2_line_rep_def\n  by (simp add: inner_commute)\n\nlemma proj2_intersection_incident:\n  shows \"proj2_incident (proj2_intersection l m) l\"\n  and \"proj2_incident (proj2_intersection l m) m\"\n  using proj2_line_through_incident(1) [of \"L2P l\" \"L2P m\"]\n    and proj2_line_through_incident(2) [of \"L2P m\" \"L2P l\"]\n    and proj2_incident_switch [of \"L2P l\"]\n    and proj2_incident_switch [of \"L2P m\"]\n  unfolding proj2_intersection_def\n  by simp_all\n\nlemma proj2_intersection_unique:\n  assumes \"l \\<noteq> m\" and \"proj2_incident p l\" and \"proj2_incident p m\"\n  shows \"p = proj2_intersection l m\"\nproof -\n  from \\<open>l \\<noteq> m\\<close> have \"L2P l \\<noteq> L2P m\" by auto\n  from \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident p m\\<close>\n    and proj2_incident_switch\n  have \"proj2_incident (L2P l) (P2L p)\" and \"proj2_incident (L2P m) (P2L p)\"\n    by simp_all\n  with \\<open>L2P l \\<noteq> L2P m\\<close> and proj2_line_through_unique\n  have \"P2L p = proj2_line_through (L2P l) (L2P m)\" by simp\n  thus \"p = proj2_intersection l m\"\n    unfolding proj2_intersection_def\n    by (simp add: P2L_to_L2P)\nqed\n\nlemma proj2_not_self_incident:\n  \"\\<not> (proj2_incident p (P2L p))\"\n  unfolding proj2_incident_def and proj2_line_rep_def\n  using proj2_rep_non_zero and inner_eq_zero_iff [of \"proj2_rep p\"]\n  by simp\n\nlemma proj2_another_point_on_line:\n  \"\\<exists> q. q \\<noteq> p \\<and> proj2_incident q l\"\nproof -\n  let ?m = \"P2L p\"\n  let ?q = \"proj2_intersection l ?m\"\n  from proj2_intersection_incident\n  have \"proj2_incident ?q l\" and \"proj2_incident ?q ?m\" by simp_all\n  from \\<open>proj2_incident ?q ?m\\<close> and proj2_not_self_incident have \"?q \\<noteq> p\" by auto\n  with \\<open>proj2_incident ?q l\\<close> show \"\\<exists> q. q \\<noteq> p \\<and> proj2_incident q l\" by auto\nqed\n\nlemma proj2_another_line_through_point:\n  \"\\<exists> m. m \\<noteq> l \\<and> proj2_incident p m\"\nproof -\n  from proj2_another_point_on_line\n  obtain q where \"q \\<noteq> L2P l \\<and> proj2_incident q (P2L p)\" by auto\n  with proj2_incident_switch [of q \"P2L p\"]\n  have \"P2L q \\<noteq> l \\<and> proj2_incident p (P2L q)\" by auto\n  thus \"\\<exists> m. m \\<noteq> l \\<and> proj2_incident p m\" ..\nqed\n\nlemma proj2_incident_abs:\n  assumes \"v \\<noteq> 0\" and \"w \\<noteq> 0\"\n  shows \"proj2_incident (proj2_abs v) (proj2_line_abs w) \\<longleftrightarrow> v \\<bullet> w = 0\"\nproof -\n  from \\<open>v \\<noteq> 0\\<close> and proj2_rep_abs2\n  obtain j where \"j \\<noteq> 0\" and \"proj2_rep (proj2_abs v) = j *\\<^sub>R v\" by auto\n\n  from \\<open>w \\<noteq> 0\\<close> and proj2_line_rep_abs\n  obtain k where \"k \\<noteq> 0\"\n    and \"proj2_line_rep (proj2_line_abs w) = k *\\<^sub>R w\"\n    by auto\n  with \\<open>j \\<noteq> 0\\<close> and \\<open>proj2_rep (proj2_abs v) = j *\\<^sub>R v\\<close>\n  show \"proj2_incident (proj2_abs v) (proj2_line_abs w) \\<longleftrightarrow> v \\<bullet> w = 0\"\n    unfolding proj2_incident_def\n    by (simp add: dot_scaleR_mult)\nqed\n\nlemma proj2_incident_left_abs:\n  assumes \"v \\<noteq> 0\"\n  shows \"proj2_incident (proj2_abs v) l \\<longleftrightarrow> v \\<bullet> (proj2_line_rep l) = 0\"\nproof -\n  have \"proj2_line_rep l \\<noteq> 0\" by (rule proj2_line_rep_non_zero)\n  with \\<open>v \\<noteq> 0\\<close> and proj2_incident_abs [of v \"proj2_line_rep l\"]\n  show \"proj2_incident (proj2_abs v) l \\<longleftrightarrow> v \\<bullet> (proj2_line_rep l) = 0\" by simp\nqed\n\nlemma proj2_incident_right_abs:\n  assumes \"v \\<noteq> 0\"\n  shows \"proj2_incident p (proj2_line_abs v) \\<longleftrightarrow> (proj2_rep p) \\<bullet> v = 0\"\nproof -\n  have \"proj2_rep p \\<noteq> 0\" by (rule proj2_rep_non_zero)\n  with \\<open>v \\<noteq> 0\\<close> and proj2_incident_abs [of \"proj2_rep p\" v]\n  show \"proj2_incident p (proj2_line_abs v) \\<longleftrightarrow> (proj2_rep p) \\<bullet> v = 0\"\n    by (simp add: proj2_abs_rep)\nqed\n\ndefinition proj2_set_Col :: \"proj2 set \\<Rightarrow> bool\" where\n  \"proj2_set_Col S \\<equiv> \\<exists> l. \\<forall> p\\<in>S. proj2_incident p l\"\n\nlemma proj2_subset_Col:\n  assumes \"T \\<subseteq> S\" and \"proj2_set_Col S\"\n  shows \"proj2_set_Col T\"\n  using \\<open>T \\<subseteq> S\\<close> and \\<open>proj2_set_Col S\\<close>\n  by (unfold proj2_set_Col_def) auto\n\ndefinition proj2_no_3_Col :: \"proj2 set \\<Rightarrow> bool\" where\n  \"proj2_no_3_Col S \\<equiv> card S = 4 \\<and> (\\<forall> p\\<in>S. \\<not> proj2_set_Col (S - {p}))\"\n\nlemma proj2_Col_iff_not_invertible:\n  \"proj2_Col p q r\n  \\<longleftrightarrow> \\<not> invertible (vector [proj2_rep p, proj2_rep q, proj2_rep r] :: real^3^3)\"\n  (is \"_ \\<longleftrightarrow> \\<not> invertible (vector [?u, ?v, ?w])\")\nproof -\n  let ?M = \"vector [?u,?v,?w] :: real^3^3\"\n  have \"proj2_Col p q r \\<longleftrightarrow> (\\<exists> x. x \\<noteq> 0 \\<and> x v* ?M = 0)\"\n  proof\n    assume \"proj2_Col p q r\"\n    then obtain i and j and k\n      where \"i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\" and \"i *\\<^sub>R ?u + j *\\<^sub>R ?v + k *\\<^sub>R ?w = 0\"\n      unfolding proj2_Col_def\n      by auto\n    let ?x = \"vector [i,j,k] :: real^3\"\n    from \\<open>i \\<noteq> 0 \\<or> j \\<noteq> 0 \\<or> k \\<noteq> 0\\<close>\n    have \"?x \\<noteq> 0\"\n      unfolding vector_def\n      by (simp add: vec_eq_iff forall_3)\n    moreover {\n      from \\<open>i *\\<^sub>R ?u + j *\\<^sub>R ?v + k *\\<^sub>R ?w = 0\\<close>\n      have \"?x v* ?M = 0\"\n        unfolding vector_def and vector_matrix_mult_def\n        by (simp add: sum_3 vec_eq_iff algebra_simps) }\n    ultimately show \"\\<exists> x. x \\<noteq> 0 \\<and> x v* ?M = 0\" by auto\n  next\n    assume \"\\<exists> x. x \\<noteq> 0 \\<and> x v* ?M = 0\"\n    then obtain x where \"x \\<noteq> 0\" and \"x v* ?M = 0\" by auto\n    let ?i = \"x$1\"\n    let ?j = \"x$2\"\n    let ?k = \"x$3\"\n    from \\<open>x \\<noteq> 0\\<close> have \"?i \\<noteq> 0 \\<or> ?j \\<noteq> 0 \\<or> ?k \\<noteq> 0\" by (simp add: vec_eq_iff forall_3)\n    moreover {\n      from \\<open>x v* ?M = 0\\<close>\n      have \"?i *\\<^sub>R ?u + ?j *\\<^sub>R ?v + ?k *\\<^sub>R ?w = 0\"\n        unfolding vector_matrix_mult_def and sum_3 and vector_def\n        by (simp add: vec_eq_iff algebra_simps) }\n    ultimately show \"proj2_Col p q r\"\n      unfolding proj2_Col_def\n      by auto\n  qed\n  also from matrix_right_invertible_ker [of ?M]\n  have \"\\<dots> \\<longleftrightarrow> \\<not> (\\<exists> M'. ?M ** M' = mat 1)\" by auto\n  also from matrix_left_right_inverse\n  have \"\\<dots> \\<longleftrightarrow> \\<not> invertible ?M\"\n    unfolding invertible_def\n    by auto\n  finally show \"proj2_Col p q r \\<longleftrightarrow> \\<not> invertible ?M\" .\nqed\n\nlemma not_invertible_iff_proj2_set_Col:\n  \"\\<not> invertible (vector [proj2_rep p, proj2_rep q, proj2_rep r] :: real^3^3)\n  \\<longleftrightarrow> proj2_set_Col {p,q,r}\"\n  (is \"\\<not> invertible ?M \\<longleftrightarrow> _\")\nproof -\n  from left_invertible_iff_invertible\n  have \"\\<not> invertible ?M  \\<longleftrightarrow> \\<not> (\\<exists> M'. M' ** ?M = mat 1)\" by auto\n  also from matrix_left_invertible_ker [of ?M]\n  have \"\\<dots> \\<longleftrightarrow> (\\<exists> y. y \\<noteq> 0 \\<and> ?M *v y = 0)\" by auto\n  also have \"\\<dots> \\<longleftrightarrow> (\\<exists> l. \\<forall> s\\<in>{p,q,r}. proj2_incident s l)\"\n  proof\n    assume \"\\<exists> y. y \\<noteq> 0 \\<and> ?M *v y = 0\"\n    then obtain y where \"y \\<noteq> 0\" and \"?M *v y = 0\" by auto\n    let ?l = \"proj2_line_abs y\"\n    from \\<open>?M *v y = 0\\<close>\n    have \"\\<forall> s\\<in>{p,q,r}. proj2_rep s \\<bullet> y = 0\"\n      unfolding vector_def\n        and matrix_vector_mult_def\n        and inner_vec_def\n        and sum_3\n      by (simp add: vec_eq_iff forall_3)\n    with \\<open>y \\<noteq> 0\\<close> and proj2_incident_right_abs\n    have \"\\<forall> s\\<in>{p,q,r}. proj2_incident s ?l\" by simp\n    thus \"\\<exists> l. \\<forall> s\\<in>{p,q,r}. proj2_incident s l\" ..\n  next\n    assume \"\\<exists> l. \\<forall> s\\<in>{p,q,r}. proj2_incident s l\"\n    then obtain l where \"\\<forall> s\\<in>{p,q,r}. proj2_incident s l\" ..\n    let ?y = \"proj2_line_rep l\"\n    have \"?y \\<noteq> 0\" by (rule proj2_line_rep_non_zero)\n    moreover {\n      from \\<open>\\<forall> s\\<in>{p,q,r}. proj2_incident s l\\<close>\n      have \"?M *v ?y = 0\"\n        unfolding vector_def\n          and matrix_vector_mult_def\n          and inner_vec_def\n          and sum_3\n          and proj2_incident_def\n        by (simp add: vec_eq_iff) }\n    ultimately show \"\\<exists> y. y \\<noteq> 0 \\<and> ?M *v y = 0\" by auto\n  qed\n  finally show \"\\<not> invertible ?M \\<longleftrightarrow> proj2_set_Col {p,q,r}\"\n    unfolding proj2_set_Col_def .\nqed\n\nlemma proj2_Col_iff_set_Col:\n  \"proj2_Col p q r \\<longleftrightarrow> proj2_set_Col {p,q,r}\"\n  by (simp add: proj2_Col_iff_not_invertible\n    not_invertible_iff_proj2_set_Col)\n\nlemma proj2_incident_Col:\n  assumes \"proj2_incident p l\" and \"proj2_incident q l\" and \"proj2_incident r l\"\n  shows \"proj2_Col p q r\"\nproof -\n  from \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close> and \\<open>proj2_incident r l\\<close>\n  have \"proj2_set_Col {p,q,r}\" by (unfold proj2_set_Col_def) auto\n  thus \"proj2_Col p q r\" by (subst proj2_Col_iff_set_Col)\nqed\n\nlemma proj2_incident_iff_Col:\n  assumes \"p \\<noteq> q\" and \"proj2_incident p l\" and \"proj2_incident q l\"\n  shows \"proj2_incident r l \\<longleftrightarrow> proj2_Col p q r\"\nproof\n  assume \"proj2_incident r l\"\n  with \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close>\n  show \"proj2_Col p q r\" by (rule proj2_incident_Col)\nnext\n  assume \"proj2_Col p q r\"\n  hence \"proj2_set_Col {p,q,r}\" by (simp add: proj2_Col_iff_set_Col)\n  then obtain m where \"\\<forall> s\\<in>{p,q,r}. proj2_incident s m\"\n    unfolding proj2_set_Col_def ..\n  hence \"proj2_incident p m\" and \"proj2_incident q m\" and \"proj2_incident r m\"\n    by simp_all\n  from \\<open>p \\<noteq> q\\<close> and \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close>\n    and \\<open>proj2_incident p m\\<close> and \\<open>proj2_incident q m\\<close>\n    and proj2_incident_unique\n  have \"m = l\" by auto\n  with \\<open>proj2_incident r m\\<close> show \"proj2_incident r l\" by simp\nqed\n\nlemma proj2_incident_iff:\n  assumes \"p \\<noteq> q\" and \"proj2_incident p l\" and \"proj2_incident q l\"\n  shows \"proj2_incident r l\n  \\<longleftrightarrow> r = p \\<or> (\\<exists> k. r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q))\"\nproof -\n  from \\<open>p \\<noteq> q\\<close> and \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close>\n  have \"proj2_incident r l \\<longleftrightarrow> proj2_Col p q r\" by (rule proj2_incident_iff_Col)\n  with \\<open>p \\<noteq> q\\<close> and proj2_Col_iff\n  show \"proj2_incident r l\n    \\<longleftrightarrow> r = p \\<or> (\\<exists> k. r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q))\"\n    by simp\nqed\n\nlemma not_proj2_set_Col_iff_span:\n  assumes \"card S = 3\"\n  shows \"\\<not> proj2_set_Col S \\<longleftrightarrow> span (proj2_rep ` S) = UNIV\"\nproof -\n  from \\<open>card S = 3\\<close> and choose_3 [of S]\n  obtain p and q and r where \"S = {p,q,r}\" by auto\n  let ?u = \"proj2_rep p\"\n  let ?v = \"proj2_rep q\"\n  let ?w = \"proj2_rep r\"\n  let ?M = \"vector [?u, ?v, ?w] :: real^3^3\"\n  from \\<open>S = {p,q,r}\\<close> and not_invertible_iff_proj2_set_Col [of p q r]\n  have \"\\<not> proj2_set_Col S \\<longleftrightarrow> invertible ?M\" by auto\n  also from left_invertible_iff_invertible\n  have \"\\<dots> \\<longleftrightarrow> (\\<exists> N. N ** ?M = mat 1)\" ..\n  also from matrix_left_invertible_span_rows\n  have \"\\<dots> \\<longleftrightarrow> span (rows ?M) = UNIV\" by auto\n  finally have \"\\<not> proj2_set_Col S \\<longleftrightarrow> span (rows ?M) = UNIV\" .\n\n  have \"rows ?M = {?u, ?v, ?w}\"\n  proof\n    { fix x\n      assume \"x \\<in> rows ?M\"\n      then obtain i :: 3  where \"x = ?M $ i\"\n        unfolding rows_def and row_def\n        by (auto simp add: vec_lambda_beta vec_lambda_eta)\n      with exhaust_3 have \"x = ?u \\<or> x = ?v \\<or> x = ?w\"\n        unfolding vector_def\n        by auto\n      hence \"x \\<in> {?u, ?v, ?w}\" by simp }\n    thus \"rows ?M \\<subseteq> {?u, ?v, ?w}\" ..\n    { fix x\n      assume \"x \\<in> {?u, ?v, ?w}\"\n      hence \"x = ?u \\<or> x = ?v \\<or> x = ?w\" by simp\n      hence \"x = ?M $ 1 \\<or> x = ?M $ 2 \\<or> x = ?M $ 3\"\n        unfolding vector_def\n        by simp\n      hence \"x \\<in> rows ?M\"\n        unfolding rows_def row_def vec_lambda_eta\n        by blast }\n    thus \"{?u, ?v, ?w} \\<subseteq> rows ?M\" ..\n  qed\n  with \\<open>S = {p,q,r}\\<close>\n  have \"rows ?M = proj2_rep ` S\"\n    unfolding image_def\n    by auto\n  with \\<open>\\<not> proj2_set_Col S \\<longleftrightarrow> span (rows ?M) = UNIV\\<close>\n  show \"\\<not> proj2_set_Col S \\<longleftrightarrow> span (proj2_rep ` S) = UNIV\" by simp\nqed\n\n\n\n  from \\<open>proj2_no_3_Col S\\<close> and \\<open>p \\<in> S\\<close>\n  have \"\\<not> proj2_set_Col (S - {p})\"\n    unfolding proj2_no_3_Col_def\n    by simp\n  with \\<open>card (S - {p}) = 3\\<close> and not_proj2_set_Col_iff_span\n  show \"span (proj2_rep ` (S - {p})) = UNIV\" by simp\nqed\n\nlemma fourth_proj2_no_3_Col:\n  assumes \"\\<not> proj2_Col p q r\"\n  shows \"\\<exists> s. proj2_no_3_Col {s,r,p,q}\"\nproof -\n  from \\<open>\\<not> proj2_Col p q r\\<close> and proj2_Col_coincide have \"p \\<noteq> q\" by auto\n  hence \"card {p,q} = 2\" by simp\n\n  from \\<open>\\<not> proj2_Col p q r\\<close> and proj2_Col_coincide and proj2_Col_permute\n  have \"r \\<notin> {p,q}\" by fast\n  with \\<open>card {p,q} = 2\\<close> have \"card {r,p,q} = 3\" by simp\n\n  have \"finite {r,p,q}\" by simp\n\n  let ?s = \"proj2_abs (\\<Sum> t\\<in>{r,p,q}. proj2_rep t)\"\n  have \"\\<exists> j. (\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s\"\n  proof cases\n    assume \"(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = 0\"\n    hence \"(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = 0 *\\<^sub>R proj2_rep ?s\" by simp\n    thus \"\\<exists> j. (\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s\" ..\n  next\n    assume \"(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) \\<noteq> 0\"\n    with proj2_rep_abs2\n    obtain k where \"k \\<noteq> 0\"\n      and \"proj2_rep ?s = k *\\<^sub>R (\\<Sum> t\\<in>{r,p,q}. proj2_rep t)\"\n      by auto\n    hence \"(1/k) *\\<^sub>R proj2_rep ?s = (\\<Sum> t\\<in>{r,p,q}. proj2_rep t)\" by simp\n    from this [symmetric]\n    show \"\\<exists> j. (\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s\" ..\n  qed\n  then obtain j where \"(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s\" ..\n  let ?c = \"\\<lambda> t. if t = ?s then 1 - j else 1\"\n  from \\<open>p \\<noteq> q\\<close> have \"?c p \\<noteq> 0 \\<or> ?c q \\<noteq> 0\" by simp\n\n  let ?d = \"\\<lambda> t. if t = ?s then j else -1\"\n\n  let ?S = \"{?s,r,p,q}\"\n\n  have \"?s \\<notin> {r,p,q}\"\n  proof\n    assume \"?s \\<in> {r,p,q}\"\n\n    from \\<open>r \\<notin> {p,q}\\<close> and \\<open>p \\<noteq> q\\<close>\n    have \"?c r *\\<^sub>R proj2_rep r + ?c p *\\<^sub>R proj2_rep p + ?c q *\\<^sub>R proj2_rep q\n      = (\\<Sum> t\\<in>{r,p,q}. ?c t *\\<^sub>R proj2_rep t)\"\n      by (simp add: sum.insert [of _ _ \"\\<lambda> t. ?c t *\\<^sub>R proj2_rep t\"])\n    also from \\<open>finite {r,p,q}\\<close> and \\<open>?s \\<in> {r,p,q}\\<close>\n    have \"\\<dots> = ?c ?s *\\<^sub>R proj2_rep ?s + (\\<Sum> t\\<in>{r,p,q}-{?s}. ?c t *\\<^sub>R proj2_rep t)\"\n      by (simp only:\n        sum.remove [of \"{r,p,q}\" ?s \"\\<lambda> t. ?c t *\\<^sub>R proj2_rep t\"])\n    also have \"\\<dots>\n      = -j *\\<^sub>R proj2_rep ?s + (proj2_rep ?s + (\\<Sum> t\\<in>{r,p,q}-{?s}. proj2_rep t))\"\n      by (simp add: algebra_simps)\n    also from \\<open>finite {r,p,q}\\<close> and \\<open>?s \\<in> {r,p,q}\\<close>\n    have \"\\<dots> = -j *\\<^sub>R proj2_rep ?s + (\\<Sum> t\\<in>{r,p,q}. proj2_rep t)\"\n      by (simp only:\n        sum.remove [of \"{r,p,q}\" ?s \"\\<lambda> t. proj2_rep t\",symmetric])\n    also from \\<open>(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s\\<close>\n    have \"\\<dots> = 0\" by simp\n    finally\n    have \"?c r *\\<^sub>R proj2_rep r + ?c p *\\<^sub>R proj2_rep p + ?c q *\\<^sub>R proj2_rep q = 0\"\n      .\n    with \\<open>?c p \\<noteq> 0 \\<or> ?c q \\<noteq> 0\\<close>\n    have \"proj2_Col p q r\"\n      by (unfold proj2_Col_def) (auto simp add: algebra_simps)\n    with \\<open>\\<not> proj2_Col p q r\\<close> show False ..\n  qed\n  with \\<open>card {r,p,q} = 3\\<close> have \"card ?S = 4\" by simp\n\n  from \\<open>\\<not> proj2_Col p q r\\<close> and proj2_Col_permute\n  have \"\\<not> proj2_Col r p q\" by fast\n  hence \"\\<not> proj2_set_Col {r,p,q}\" by (subst proj2_Col_iff_set_Col [symmetric])\n\n  have \"\\<forall> u\\<in>?S. \\<not> proj2_set_Col (?S - {u})\"\n  proof\n    fix u\n    assume \"u \\<in> ?S\"\n    with \\<open>card ?S = 4\\<close> have \"card (?S - {u}) = 3\" by simp\n    show \"\\<not> proj2_set_Col (?S - {u})\"\n    proof cases\n      assume \"u = ?s\"\n      with \\<open>?s \\<notin> {r,p,q}\\<close> have \"?S - {u} = {r,p,q}\" by simp\n      with \\<open>\\<not> proj2_set_Col {r,p,q}\\<close> show \"\\<not> proj2_set_Col (?S - {u})\" by simp\n    next\n      assume \"u \\<noteq> ?s\"\n      hence \"insert ?s ({r,p,q} - {u}) = ?S - {u}\" by auto\n\n      from \\<open>finite {r,p,q}\\<close> have \"finite ({r,p,q} - {u})\" by simp\n\n      from \\<open>?s \\<notin> {r,p,q}\\<close> have \"?s \\<notin> {r,p,q} - {u}\" by simp\n      hence \"\\<forall> t\\<in>{r,p,q}-{u}. ?d t = -1\" by auto\n\n      from \\<open>u \\<noteq> ?s\\<close> and  \\<open>u \\<in> ?S\\<close> have \"u \\<in> {r,p,q}\" by simp\n      hence \"(\\<Sum> t\\<in>{r,p,q}. proj2_rep t)\n        = proj2_rep u + (\\<Sum> t\\<in>{r,p,q}-{u}. proj2_rep t)\"\n        by (simp add: sum.remove)\n      with \\<open>(\\<Sum> t\\<in>{r,p,q}. proj2_rep t) = j *\\<^sub>R proj2_rep ?s\\<close>\n      have \"proj2_rep u\n        = j *\\<^sub>R proj2_rep ?s - (\\<Sum> t\\<in>{r,p,q}-{u}. proj2_rep t)\"\n        by simp\n      also from \\<open>\\<forall> t\\<in>{r,p,q}-{u}. ?d t = -1\\<close>\n      have \"\\<dots> = j *\\<^sub>R proj2_rep ?s + (\\<Sum> t\\<in>{r,p,q}-{u}. ?d t *\\<^sub>R proj2_rep t)\"\n        by (simp add: sum_negf)\n      also from \\<open>finite ({r,p,q} - {u})\\<close>  and \\<open>?s \\<notin> {r,p,q} - {u}\\<close>\n      have \"\\<dots> = (\\<Sum> t\\<in>insert ?s ({r,p,q}-{u}). ?d t *\\<^sub>R proj2_rep t)\"\n        by (simp add: sum.insert)\n      also from \\<open>insert ?s ({r,p,q} - {u}) = ?S - {u}\\<close>\n      have \"\\<dots> = (\\<Sum> t\\<in>?S-{u}. ?d t *\\<^sub>R proj2_rep t)\" by simp\n      finally have \"proj2_rep u = (\\<Sum> t\\<in>?S-{u}. ?d t *\\<^sub>R proj2_rep t)\" .\n      moreover\n      have \"\\<forall> t\\<in>?S-{u}. ?d t *\\<^sub>R proj2_rep t \\<in> span (proj2_rep ` (?S - {u}))\"\n        by (simp add: span_clauses)\n      ultimately have \"proj2_rep u \\<in> span (proj2_rep ` (?S - {u}))\"\n        by (metis (no_types, lifting) span_sum)\n\n      have \"\\<forall> t\\<in>{r,p,q}. proj2_rep t \\<in> span (proj2_rep ` (?S - {u}))\"\n      proof\n        fix t\n        assume \"t \\<in> {r,p,q}\"\n        show \"proj2_rep t \\<in> span (proj2_rep ` (?S - {u}))\"\n        proof cases\n          assume \"t = u\"\n          from \\<open>proj2_rep u \\<in> span (image proj2_rep (?S - {u}))\\<close>\n          show \"proj2_rep t \\<in> span (proj2_rep ` (?S - {u}))\"\n            by (subst \\<open>t = u\\<close>)\n        next\n          assume \"t \\<noteq> u\"\n          with \\<open>t \\<in> {r,p,q}\\<close>\n          have \"proj2_rep t \\<in> proj2_rep ` (?S - {u})\" by simp\n          with span_superset [of \"proj2_rep ` (?S - {u})\"]\n          show \"proj2_rep t \\<in> span (proj2_rep ` (?S - {u}))\" by fast\n        qed\n      qed\n      hence \"proj2_rep ` {r,p,q} \\<subseteq> span (proj2_rep ` (?S - {u}))\"\n        by (simp only: image_subset_iff)\n      hence\n        \"span (proj2_rep ` {r,p,q}) \\<subseteq> span (span (proj2_rep ` (?S - {u})))\"\n        by (simp only: span_mono)\n      hence \"span (proj2_rep ` {r,p,q}) \\<subseteq> span (proj2_rep ` (?S - {u}))\"\n        by (simp only: span_span)\n      moreover\n      from \\<open>\\<not> proj2_set_Col {r,p,q}\\<close>\n        and \\<open>card {r,p,q} = 3\\<close>\n        and not_proj2_set_Col_iff_span\n      have \"span (proj2_rep ` {r,p,q}) = UNIV\" by simp\n      ultimately have \"span (proj2_rep ` (?S - {u})) = UNIV\" by auto\n      with \\<open>card (?S - {u}) = 3\\<close> and not_proj2_set_Col_iff_span\n      show \"\\<not> proj2_set_Col (?S - {u})\" by simp\n    qed\n  qed\n  with \\<open>card ?S = 4\\<close>\n  have \"proj2_no_3_Col ?S\" by (unfold proj2_no_3_Col_def) fast\n  thus \"\\<exists> s. proj2_no_3_Col {s,r,p,q}\" ..\nqed\n\nlemma proj2_set_Col_expand:\n  assumes \"proj2_set_Col S\" and \"{p,q,r} \\<subseteq> S\" and \"p \\<noteq> q\" and \"r \\<noteq> p\"\n  shows \"\\<exists> k. r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\"\nproof -\n  from \\<open>proj2_set_Col S\\<close>\n  obtain l where \"\\<forall> t\\<in>S. proj2_incident t l\" unfolding proj2_set_Col_def ..\n  with \\<open>{p,q,r} \\<subseteq> S\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and proj2_incident_iff [of p q l r]\n  show \"\\<exists> k. r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\" by simp\nqed\n\nsubsection \"Collineations of the real projective plane\"\n\ntypedef cltn2 =\n  \"(Collect invertible :: (real^3^3) set)//invertible_proportionality\"\nproof\n  from matrix_id_invertible have \"(mat 1 :: real^3^3) \\<in> Collect invertible\"\n    by simp\n  thus \"invertible_proportionality `` {mat 1} \\<in>\n    (Collect invertible :: (real^3^3) set)//invertible_proportionality\"\n    unfolding quotient_def\n    by auto\nqed\n\ndefinition cltn2_rep :: \"cltn2 \\<Rightarrow> real^3^3\" where\n  \"cltn2_rep A \\<equiv> \\<some> B. B \\<in> Rep_cltn2 A\"\n\ndefinition cltn2_abs :: \"real^3^3 \\<Rightarrow> cltn2\" where\n  \"cltn2_abs B \\<equiv> Abs_cltn2 (invertible_proportionality `` {B})\"\n\ndefinition cltn2_independent :: \"cltn2 set \\<Rightarrow> bool\" where\n  \"cltn2_independent X \\<equiv> independent {cltn2_rep A | A. A \\<in> X}\"\n\ndefinition apply_cltn2 :: \"proj2 \\<Rightarrow> cltn2 \\<Rightarrow> proj2\" where\n  \"apply_cltn2 x A \\<equiv> proj2_abs (proj2_rep x v* cltn2_rep A)\"\n\nlemma cltn2_rep_in: \"cltn2_rep B \\<in> Rep_cltn2 B\"\nproof -\n  let ?A = \"cltn2_rep B\"\n  from quotient_element_nonempty and\n    invertible_proportionality_equiv and\n    Rep_cltn2 [of B]\n  have \"\\<exists> C. C \\<in> Rep_cltn2 B\"\n    by auto\n  with someI_ex [of \"\\<lambda> C. C \\<in> Rep_cltn2 B\"]\n  show \"?A \\<in> Rep_cltn2 B\"\n    unfolding cltn2_rep_def\n    by simp\nqed\n\nlemma cltn2_rep_invertible: \"invertible (cltn2_rep A)\"\nproof -\n  from\n    Union_quotient [of \"Collect invertible\" invertible_proportionality]\n    and invertible_proportionality_equiv\n    and Rep_cltn2 [of A] and cltn2_rep_in [of A]\n  have \"cltn2_rep A \\<in> Collect invertible\"\n    unfolding quotient_def\n    by auto\n  thus \"invertible (cltn2_rep A)\"\n    unfolding invertible_proportionality_def\n    by simp\nqed\n\nlemma cltn2_rep_abs:\n  fixes A :: \"real^3^3\"\n  assumes \"invertible A\"\n  shows \"(A, cltn2_rep (cltn2_abs A)) \\<in> invertible_proportionality\"\nproof -\n  from \\<open>invertible A\\<close>\n  have \"invertible_proportionality `` {A} \\<in> (Collect invertible :: (real^3^3) set)//invertible_proportionality\"\n    unfolding quotient_def\n    by auto \n  with Abs_cltn2_inverse\n  have \"Rep_cltn2 (cltn2_abs A) = invertible_proportionality `` {A}\"\n    unfolding cltn2_abs_def\n    by simp\n  with cltn2_rep_in\n  have \"cltn2_rep (cltn2_abs A) \\<in> invertible_proportionality `` {A}\" by auto\n  thus \"(A, cltn2_rep (cltn2_abs A)) \\<in> invertible_proportionality\" by simp\nqed\n\nlemma cltn2_rep_abs2:\n  assumes \"invertible A\"\n  shows \"\\<exists> k. k \\<noteq> 0 \\<and> cltn2_rep (cltn2_abs A) = k *\\<^sub>R A\"\nproof -\n  from \\<open>invertible A\\<close> and cltn2_rep_abs\n  have \"(A, cltn2_rep (cltn2_abs A)) \\<in> invertible_proportionality\" by simp\n  then obtain c where \"A = c *\\<^sub>R cltn2_rep (cltn2_abs A)\"\n    unfolding invertible_proportionality_def and real_vector.proportionality_def\n    by auto\n  with \\<open>invertible A\\<close> and zero_not_invertible have \"c \\<noteq> 0\" by auto\n  hence \"1/c \\<noteq> 0\" by simp\n\n  let ?k = \"1/c\"\n  from \\<open>A = c *\\<^sub>R cltn2_rep (cltn2_abs A)\\<close>\n  have \"?k *\\<^sub>R A = ?k *\\<^sub>R c *\\<^sub>R cltn2_rep (cltn2_abs A)\" by simp\n  with \\<open>c \\<noteq> 0\\<close> have \"cltn2_rep (cltn2_abs A) = ?k *\\<^sub>R A\" by simp\n  with \\<open>?k \\<noteq> 0\\<close>\n  show \"\\<exists> k. k \\<noteq> 0 \\<and> cltn2_rep (cltn2_abs A) = k *\\<^sub>R A\" by blast\nqed\n\nlemma cltn2_abs_rep: \"cltn2_abs (cltn2_rep A) = A\"\nproof -\n  from partition_Image_element\n  [of \"Collect invertible\"\n    invertible_proportionality\n    \"Rep_cltn2 A\"\n    \"cltn2_rep A\"]\n    and invertible_proportionality_equiv\n    and Rep_cltn2 [of A] and cltn2_rep_in [of A]\n  have \"invertible_proportionality `` {cltn2_rep A} = Rep_cltn2 A\"\n    by simp\n  with Rep_cltn2_inverse\n  show \"cltn2_abs (cltn2_rep A) = A\"\n    unfolding cltn2_abs_def\n    by simp\nqed\n\nlemma cltn2_abs_mult:\n  assumes \"k \\<noteq> 0\" and \"invertible A\"\n  shows \"cltn2_abs (k *\\<^sub>R A) = cltn2_abs A\"\nproof -\n  from \\<open>k \\<noteq> 0\\<close> and \\<open>invertible A\\<close> and scalar_invertible\n  have \"invertible (k *\\<^sub>R A)\" by auto\n  with \\<open>invertible A\\<close>\n  have \"(k *\\<^sub>R A, A) \\<in> invertible_proportionality\"\n    unfolding invertible_proportionality_def\n      and real_vector.proportionality_def\n    by (auto simp add: zero_not_invertible)\n  with eq_equiv_class_iff\n  [of \"Collect invertible\" invertible_proportionality \"k *\\<^sub>R A\" A]\n    and invertible_proportionality_equiv\n    and \\<open>invertible A\\<close> and \\<open>invertible (k *\\<^sub>R A)\\<close>\n  have \"invertible_proportionality `` {k *\\<^sub>R A}\n    = invertible_proportionality `` {A}\"\n    by simp\n  thus \"cltn2_abs (k *\\<^sub>R A) = cltn2_abs A\"\n    unfolding cltn2_abs_def\n    by simp\nqed\n\nlemma cltn2_abs_mult_rep:\n  assumes \"k \\<noteq> 0\"\n  shows \"cltn2_abs (k *\\<^sub>R cltn2_rep A) = A\"\n  using cltn2_rep_invertible and cltn2_abs_mult and cltn2_abs_rep and assms\n  by simp\n\nlemma apply_cltn2_abs:\n  assumes \"x \\<noteq> 0\" and \"invertible A\"\n  shows \"apply_cltn2 (proj2_abs x) (cltn2_abs A) = proj2_abs (x v* A)\"\nproof -\n  from proj2_rep_abs2 and \\<open>x \\<noteq> 0\\<close>\n  obtain k where \"k \\<noteq> 0\" and \"proj2_rep (proj2_abs x) = k *\\<^sub>R x\" by auto\n\n  from cltn2_rep_abs2 and \\<open>invertible A\\<close>\n  obtain c where \"c \\<noteq> 0\" and \"cltn2_rep (cltn2_abs A) = c *\\<^sub>R A\" by auto\n\n  from \\<open>k \\<noteq> 0\\<close> and \\<open>c \\<noteq> 0\\<close> have \"k * c \\<noteq> 0\" by simp\n\n  from \\<open>proj2_rep (proj2_abs x) = k *\\<^sub>R x\\<close> and \\<open>cltn2_rep (cltn2_abs A) = c *\\<^sub>R A\\<close>\n  have \"proj2_rep (proj2_abs x) v* cltn2_rep (cltn2_abs A) = (k*c) *\\<^sub>R (x v* A)\"\n    by (simp add: scaleR_vector_matrix_assoc vector_scaleR_matrix_ac)\n  with \\<open>k * c \\<noteq> 0\\<close> \n  show \"apply_cltn2 (proj2_abs x) (cltn2_abs A) = proj2_abs (x v* A)\"\n    unfolding apply_cltn2_def\n    by (simp add: proj2_abs_mult)\nqed\n\nlemma apply_cltn2_left_abs:\n  assumes \"v \\<noteq> 0\"\n  shows \"apply_cltn2 (proj2_abs v) C = proj2_abs (v v* cltn2_rep C)\"\nproof -\n  have \"cltn2_abs (cltn2_rep C) = C\" by (rule cltn2_abs_rep)\n  with \\<open>v \\<noteq> 0\\<close> and cltn2_rep_invertible and apply_cltn2_abs [of v \"cltn2_rep C\"]\n  show \"apply_cltn2 (proj2_abs v) C = proj2_abs (v v* cltn2_rep C)\"\n    by simp\nqed\n\nlemma apply_cltn2_right_abs:\n  assumes \"invertible M\"\n  shows \"apply_cltn2 p (cltn2_abs M) = proj2_abs (proj2_rep p v* M)\"\nproof -\n  from proj2_rep_non_zero and \\<open>invertible M\\<close> and apply_cltn2_abs\n  have \"apply_cltn2 (proj2_abs (proj2_rep p)) (cltn2_abs M)\n    = proj2_abs (proj2_rep p v* M)\"\n    by simp\n  thus \"apply_cltn2 p (cltn2_abs M) = proj2_abs (proj2_rep p v* M)\"\n    by (simp add: proj2_abs_rep)\nqed\n\nlemma non_zero_mult_rep_non_zero:\n  assumes \"v \\<noteq> 0\"\n  shows \"v v* cltn2_rep C \\<noteq> 0\"\n  using \\<open>v \\<noteq> 0\\<close> and cltn2_rep_invertible and times_invertible_eq_zero\n  by auto\n\nlemma rep_mult_rep_non_zero: \"proj2_rep p v* cltn2_rep A \\<noteq> 0\"\n  using proj2_rep_non_zero\n  by (rule non_zero_mult_rep_non_zero)\n\ndefinition cltn2_image :: \"proj2 set \\<Rightarrow> cltn2 \\<Rightarrow> proj2 set\" where\n  \"cltn2_image P A \\<equiv> {apply_cltn2 p A | p. p \\<in> P}\"\n\nsubsubsection \"As a group\"\n\ndefinition cltn2_id :: cltn2 where\n  \"cltn2_id \\<equiv> cltn2_abs (mat 1)\"\n\ndefinition cltn2_compose :: \"cltn2 \\<Rightarrow> cltn2 \\<Rightarrow> cltn2\" where\n  \"cltn2_compose A B \\<equiv> cltn2_abs (cltn2_rep A ** cltn2_rep B)\"\n\ndefinition cltn2_inverse :: \"cltn2 \\<Rightarrow> cltn2\" where\n  \"cltn2_inverse A \\<equiv> cltn2_abs (matrix_inv (cltn2_rep A))\"\n\nlemma cltn2_compose_abs:\n  assumes \"invertible M\" and \"invertible N\"\n  shows \"cltn2_compose (cltn2_abs M) (cltn2_abs N) = cltn2_abs (M ** N)\"\nproof -\n  from \\<open>invertible M\\<close> and \\<open>invertible N\\<close> and invertible_mult\n  have \"invertible (M ** N)\" by auto\n\n  from \\<open>invertible M\\<close> and \\<open>invertible N\\<close> and cltn2_rep_abs2\n  obtain j and k where \"j \\<noteq> 0\" and \"k \\<noteq> 0\"\n    and \"cltn2_rep (cltn2_abs M) = j *\\<^sub>R M\"\n    and \"cltn2_rep (cltn2_abs N) = k *\\<^sub>R N\"\n    by blast\n\n  from \\<open>j \\<noteq> 0\\<close> and \\<open>k \\<noteq> 0\\<close> have \"j * k \\<noteq> 0\" by simp\n\n  from \\<open>cltn2_rep (cltn2_abs M) = j *\\<^sub>R M\\<close> and \\<open>cltn2_rep (cltn2_abs N) = k *\\<^sub>R N\\<close>\n  have \"cltn2_rep (cltn2_abs M) ** cltn2_rep (cltn2_abs N)\n    = (j * k) *\\<^sub>R (M ** N)\"\n    by (simp add: matrix_scalar_ac scalar_matrix_assoc [symmetric])\n  with \\<open>j * k \\<noteq> 0\\<close> and \\<open>invertible (M ** N)\\<close>\n  show \"cltn2_compose (cltn2_abs M) (cltn2_abs N) = cltn2_abs (M ** N)\"\n    unfolding cltn2_compose_def\n    by (simp add: cltn2_abs_mult)\nqed\n\nlemma cltn2_compose_left_abs:\n  assumes \"invertible M\"\n  shows \"cltn2_compose (cltn2_abs M) A = cltn2_abs (M ** cltn2_rep A)\"\nproof -\n  from \\<open>invertible M\\<close> and cltn2_rep_invertible and cltn2_compose_abs\n  have \"cltn2_compose (cltn2_abs M) (cltn2_abs (cltn2_rep A))\n    = cltn2_abs (M ** cltn2_rep A)\"\n    by simp\n  thus \"cltn2_compose (cltn2_abs M) A = cltn2_abs (M ** cltn2_rep A)\"\n    by (simp add: cltn2_abs_rep)\nqed\n\nlemma cltn2_compose_right_abs:\n  assumes \"invertible M\"\n  shows \"cltn2_compose A (cltn2_abs M) = cltn2_abs (cltn2_rep A ** M)\"\nproof -\n  from \\<open>invertible M\\<close> and cltn2_rep_invertible and cltn2_compose_abs\n  have \"cltn2_compose (cltn2_abs (cltn2_rep A)) (cltn2_abs M)\n    = cltn2_abs (cltn2_rep A ** M)\"\n    by simp\n  thus \"cltn2_compose A (cltn2_abs M) = cltn2_abs (cltn2_rep A ** M)\"\n    by (simp add: cltn2_abs_rep)\nqed\n\nlemma cltn2_abs_rep_abs_mult:\n  assumes \"invertible M\" and \"invertible N\"\n  shows \"cltn2_abs (cltn2_rep (cltn2_abs M) ** N) = cltn2_abs (M ** N)\"\nproof -\n  from \\<open>invertible M\\<close> and \\<open>invertible N\\<close>\n  have \"invertible (M ** N)\" by (simp add: invertible_mult)\n\n  from \\<open>invertible M\\<close> and cltn2_rep_abs2\n  obtain k where \"k \\<noteq> 0\" and \"cltn2_rep (cltn2_abs M) = k *\\<^sub>R M\" by auto\n  from \\<open>cltn2_rep (cltn2_abs M) = k *\\<^sub>R M\\<close>\n  have \"cltn2_rep (cltn2_abs M) ** N = k *\\<^sub>R M ** N\" by simp\n  with \\<open>k \\<noteq> 0\\<close> and \\<open>invertible (M ** N)\\<close> and cltn2_abs_mult\n  show \"cltn2_abs (cltn2_rep (cltn2_abs M) ** N) = cltn2_abs (M ** N)\"\n    by (simp add: scalar_matrix_assoc [symmetric])\nqed\n\nlemma cltn2_assoc:\n  \"cltn2_compose (cltn2_compose A B) C = cltn2_compose A (cltn2_compose B C)\"\nproof -\n  let ?A' = \"cltn2_rep A\"\n  let ?B' = \"cltn2_rep B\"\n  let ?C' = \"cltn2_rep C\"\n  from cltn2_rep_invertible\n  have \"invertible ?A'\" and \"invertible ?B'\" and \"invertible ?C'\" by simp_all\n  with invertible_mult\n  have \"invertible (?A' ** ?B')\" and \"invertible (?B' ** ?C')\"\n    and \"invertible (?A' ** ?B' ** ?C')\"\n    by auto\n  from \\<open>invertible (?A' ** ?B')\\<close> and \\<open>invertible ?C'\\<close> and cltn2_abs_rep_abs_mult\n  have \"cltn2_abs (cltn2_rep (cltn2_abs (?A' ** ?B')) ** ?C')\n    = cltn2_abs (?A' ** ?B' ** ?C')\"\n    by simp\n\n  from \\<open>invertible (?B' ** ?C')\\<close> and cltn2_rep_abs2 [of \"?B' ** ?C'\"]\n  obtain k where \"k \\<noteq> 0\"\n    and \"cltn2_rep (cltn2_abs (?B' ** ?C')) = k *\\<^sub>R (?B' ** ?C')\"\n    by auto\n  from \\<open>cltn2_rep (cltn2_abs (?B' ** ?C')) = k *\\<^sub>R (?B' ** ?C')\\<close>\n  have \"?A' ** cltn2_rep (cltn2_abs (?B' ** ?C')) = k *\\<^sub>R (?A' ** ?B' ** ?C')\"\n    by (simp add: matrix_scalar_ac matrix_mul_assoc scalar_matrix_assoc)\n  with \\<open>k \\<noteq> 0\\<close> and \\<open>invertible (?A' ** ?B' ** ?C')\\<close>\n    and cltn2_abs_mult [of k \"?A' ** ?B' ** ?C'\"]\n  have \"cltn2_abs (?A' ** cltn2_rep (cltn2_abs (?B' ** ?C')))\n    = cltn2_abs (?A' ** ?B' ** ?C')\"\n    by simp\n  with \\<open>cltn2_abs (cltn2_rep (cltn2_abs (?A' ** ?B')) ** ?C')\n    = cltn2_abs (?A' ** ?B' ** ?C')\\<close>\n  show\n    \"cltn2_compose (cltn2_compose A B) C = cltn2_compose A (cltn2_compose B C)\"\n    unfolding cltn2_compose_def\n    by simp\nqed\n\nlemma cltn2_left_id: \"cltn2_compose cltn2_id A = A\"\nproof -\n  let ?A' = \"cltn2_rep A\"\n  from cltn2_rep_invertible have \"invertible ?A'\" by simp\n  with matrix_id_invertible and cltn2_abs_rep_abs_mult [of \"mat 1\" ?A']\n  have \"cltn2_compose cltn2_id A = cltn2_abs (cltn2_rep A)\"\n    unfolding cltn2_compose_def and cltn2_id_def\n    by (auto simp add: matrix_mul_lid)\n  with cltn2_abs_rep show \"cltn2_compose cltn2_id A = A\" by simp\nqed\n\nlemma cltn2_left_inverse: \"cltn2_compose (cltn2_inverse A) A = cltn2_id\"\nproof -\n  let ?M = \"cltn2_rep A\"\n  let ?M' = \"matrix_inv ?M\"\n  from cltn2_rep_invertible have \"invertible ?M\" by simp\n  with matrix_inv_invertible have \"invertible ?M'\" by auto\n  with \\<open>invertible ?M\\<close> and cltn2_abs_rep_abs_mult\n  have \"cltn2_compose (cltn2_inverse A) A = cltn2_abs (?M' ** ?M)\"\n    unfolding cltn2_compose_def and cltn2_inverse_def\n    by simp\n  with \\<open>invertible ?M\\<close>\n  show \"cltn2_compose (cltn2_inverse A) A = cltn2_id\"\n    unfolding cltn2_id_def\n    by (simp add: matrix_inv)\nqed\n\nlemma cltn2_left_inverse_ex:\n  \"\\<exists> B. cltn2_compose B A = cltn2_id\"\n  using cltn2_left_inverse ..\n\ninterpretation cltn2:\n  group \"(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\"\n  using cltn2_assoc and cltn2_left_id and cltn2_left_inverse_ex\n    and groupI [of \"(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\"]\n  by simp_all\n\nlemma cltn2_inverse_inv [simp]:\n  \"inv\\<^bsub>(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\\<^esub> A\n  = cltn2_inverse A\"\n  using cltn2_left_inverse [of A] and cltn2.inv_equality\n  by simp\n\nlemmas cltn2_inverse_id [simp] = cltn2.inv_one [simplified]\n  and cltn2_inverse_compose = cltn2.inv_mult_group [simplified]\n\nsubsubsection \"As a group action\"\n\nlemma apply_cltn2_id [simp]: \"apply_cltn2 p cltn2_id = p\"\nproof -\n  from matrix_id_invertible and apply_cltn2_right_abs\n  have \"apply_cltn2 p cltn2_id = proj2_abs (proj2_rep p v* mat 1)\"\n    unfolding cltn2_id_def by blast\n  thus \"apply_cltn2 p cltn2_id = p\"\n    by (simp add: proj2_abs_rep)\nqed\n\nlemma apply_cltn2_compose:\n  \"apply_cltn2 (apply_cltn2 p A) B = apply_cltn2 p (cltn2_compose A B)\"\nproof -\n  from rep_mult_rep_non_zero and cltn2_rep_invertible and apply_cltn2_abs\n  have \"apply_cltn2 (apply_cltn2 p A) (cltn2_abs (cltn2_rep B))\n    = proj2_abs ((proj2_rep p v* cltn2_rep A) v* cltn2_rep B)\"\n    unfolding apply_cltn2_def [of p A]\n    by simp\n  hence \"apply_cltn2 (apply_cltn2 p A) B\n    = proj2_abs (proj2_rep p v* (cltn2_rep A ** cltn2_rep B))\"\n    by (simp add: cltn2_abs_rep vector_matrix_mul_assoc)\n\n  from cltn2_rep_invertible and invertible_mult\n  have \"invertible (cltn2_rep A ** cltn2_rep B)\" by auto\n  with apply_cltn2_right_abs\n  have \"apply_cltn2 p (cltn2_compose A B)\n    = proj2_abs (proj2_rep p v* (cltn2_rep A ** cltn2_rep B))\"\n    unfolding cltn2_compose_def\n    by simp\n  with \\<open>apply_cltn2 (apply_cltn2 p A) B\n    = proj2_abs (proj2_rep p v* (cltn2_rep A ** cltn2_rep B))\\<close>\n  show \"apply_cltn2 (apply_cltn2 p A) B = apply_cltn2 p (cltn2_compose A B)\"\n    by simp\nqed\n\ninterpretation cltn2:\n  action \"(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\" apply_cltn2\nproof\n  let ?G = \"(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\"\n  fix p\n  show \"apply_cltn2 p \\<one>\\<^bsub>?G\\<^esub> = p\" by simp\n  fix A B\n  have \"apply_cltn2 (apply_cltn2 p A) B = apply_cltn2 p (A \\<otimes>\\<^bsub>?G\\<^esub> B)\"\n    by simp (rule apply_cltn2_compose)\n  thus \"A \\<in> carrier ?G \\<and> B \\<in> carrier ?G\n    \\<longrightarrow> apply_cltn2 (apply_cltn2 p A) B = apply_cltn2 p (A \\<otimes>\\<^bsub>?G\\<^esub> B)\"\n    ..\nqed\n\ndefinition cltn2_transpose :: \"cltn2 \\<Rightarrow> cltn2\" where\n  \"cltn2_transpose A \\<equiv> cltn2_abs (transpose (cltn2_rep A))\"\n\ndefinition apply_cltn2_line :: \"proj2_line \\<Rightarrow> cltn2 \\<Rightarrow> proj2_line\" where\n  \"apply_cltn2_line l A\n  \\<equiv> P2L (apply_cltn2 (L2P l) (cltn2_transpose (cltn2_inverse A)))\"\n\nlemma cltn2_transpose_abs:\n  assumes \"invertible M\"\n  shows \"cltn2_transpose (cltn2_abs M) = cltn2_abs (transpose M)\"\nproof -\n  from \\<open>invertible M\\<close> and transpose_invertible have \"invertible (transpose M)\" by auto\n\n  from \\<open>invertible M\\<close> and cltn2_rep_abs2\n  obtain k where \"k \\<noteq> 0\" and \"cltn2_rep (cltn2_abs M) = k *\\<^sub>R M\" by auto\n\n  from \\<open>cltn2_rep (cltn2_abs M) = k *\\<^sub>R M\\<close>\n  have \"transpose (cltn2_rep (cltn2_abs M)) = k *\\<^sub>R transpose M\"\n    by (simp add: transpose_scalar)\n  with \\<open>k \\<noteq> 0\\<close> and \\<open>invertible (transpose M)\\<close>\n  show \"cltn2_transpose (cltn2_abs M) = cltn2_abs (transpose M)\"\n    unfolding cltn2_transpose_def\n    by (simp add: cltn2_abs_mult)\nqed\n\nlemma cltn2_transpose_compose:\n  \"cltn2_transpose (cltn2_compose A B)\n  = cltn2_compose (cltn2_transpose B) (cltn2_transpose A)\"\nproof -\n  from cltn2_rep_invertible\n  have \"invertible (cltn2_rep A)\" and \"invertible (cltn2_rep B)\"\n    by simp_all\n  with transpose_invertible\n  have \"invertible (transpose (cltn2_rep A))\"\n    and \"invertible (transpose (cltn2_rep B))\"\n    by auto\n\n  from \\<open>invertible (cltn2_rep A)\\<close> and \\<open>invertible (cltn2_rep B)\\<close>\n    and invertible_mult\n  have \"invertible (cltn2_rep A ** cltn2_rep B)\" by auto\n  with \\<open>invertible (cltn2_rep A ** cltn2_rep B)\\<close> and cltn2_transpose_abs\n  have \"cltn2_transpose (cltn2_compose A B)\n    = cltn2_abs (transpose (cltn2_rep A ** cltn2_rep B))\"\n    unfolding cltn2_compose_def\n    by simp\n  also have \"\\<dots> = cltn2_abs (transpose (cltn2_rep B) ** transpose (cltn2_rep A))\"\n    by (simp add: matrix_transpose_mul)\n  also from \\<open>invertible (transpose (cltn2_rep B))\\<close>\n    and \\<open>invertible (transpose (cltn2_rep A))\\<close>\n    and cltn2_compose_abs\n  have \"\\<dots> = cltn2_compose (cltn2_transpose B) (cltn2_transpose A)\"\n    unfolding cltn2_transpose_def\n    by simp\n  finally show \"cltn2_transpose (cltn2_compose A B)\n    = cltn2_compose (cltn2_transpose B) (cltn2_transpose A)\" .\nqed\n\nlemma cltn2_transpose_transpose: \"cltn2_transpose (cltn2_transpose A) = A\"\nproof -\n  from cltn2_rep_invertible have \"invertible (cltn2_rep A)\" by simp\n  with transpose_invertible have \"invertible (transpose (cltn2_rep A))\" by auto\n  with cltn2_transpose_abs [of \"transpose (cltn2_rep A)\"]\n  have\n    \"cltn2_transpose (cltn2_transpose A) = cltn2_abs (transpose (transpose (cltn2_rep A)))\"\n    unfolding cltn2_transpose_def [of A]\n    by simp\n  with cltn2_abs_rep and transpose_transpose [of \"cltn2_rep A\"]\n  show \"cltn2_transpose (cltn2_transpose A) = A\" by simp\nqed\n\nlemma cltn2_transpose_id [simp]: \"cltn2_transpose cltn2_id = cltn2_id\"\n  using cltn2_transpose_abs\n  unfolding cltn2_id_def\n  by (simp add: transpose_mat matrix_id_invertible)\n\nlemma apply_cltn2_line_id [simp]: \"apply_cltn2_line l cltn2_id = l\"\n  unfolding apply_cltn2_line_def\n  by simp\n\nlemma apply_cltn2_line_compose:\n  \"apply_cltn2_line (apply_cltn2_line l A) B\n  = apply_cltn2_line l (cltn2_compose A B)\"\nproof -\n  have \"cltn2_compose\n    (cltn2_transpose (cltn2_inverse A)) (cltn2_transpose (cltn2_inverse B))\n    = cltn2_transpose (cltn2_inverse (cltn2_compose A B))\"\n    by (simp add: cltn2_transpose_compose cltn2_inverse_compose)\n  thus \"apply_cltn2_line (apply_cltn2_line l A) B\n    = apply_cltn2_line l (cltn2_compose A B)\"\n    unfolding apply_cltn2_line_def\n    by (simp add: apply_cltn2_compose)\nqed\n\ninterpretation cltn2_line:\n  action\n  \"(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\"\n  apply_cltn2_line\nproof\n  let ?G = \"(|carrier = UNIV, mult = cltn2_compose, one = cltn2_id|)\"\n  fix l\n  show \"apply_cltn2_line l \\<one>\\<^bsub>?G\\<^esub> = l\" by simp\n  fix A B\n  have \"apply_cltn2_line (apply_cltn2_line l A) B\n    = apply_cltn2_line l (A \\<otimes>\\<^bsub>?G\\<^esub> B)\"\n    by simp (rule apply_cltn2_line_compose)\n  thus \"A \\<in> carrier ?G \\<and> B \\<in> carrier ?G\n    \\<longrightarrow> apply_cltn2_line (apply_cltn2_line l A) B\n    = apply_cltn2_line l (A \\<otimes>\\<^bsub>?G\\<^esub> B)\"\n    ..\nqed\n\nlemmas apply_cltn2_inv [simp] = cltn2.act_act_inv [simplified]\nlemmas apply_cltn2_line_inv [simp] = cltn2_line.act_act_inv [simplified]\n\nlemma apply_cltn2_line_alt_def:\n  \"apply_cltn2_line l A\n  = proj2_line_abs (cltn2_rep (cltn2_inverse A) *v proj2_line_rep l)\"\nproof -\n  have \"invertible (cltn2_rep (cltn2_inverse A))\" by (rule cltn2_rep_invertible)\n  hence \"invertible (transpose (cltn2_rep (cltn2_inverse A)))\"\n    by (rule transpose_invertible)\n  hence\n    \"apply_cltn2 (L2P l) (cltn2_transpose (cltn2_inverse A))\n    = proj2_abs (proj2_rep (L2P l) v* transpose (cltn2_rep (cltn2_inverse A)))\"\n    unfolding cltn2_transpose_def\n    by (rule apply_cltn2_right_abs)\n  hence \"apply_cltn2 (L2P l) (cltn2_transpose (cltn2_inverse A))\n    = proj2_abs (cltn2_rep (cltn2_inverse A) *v proj2_line_rep l)\"\n    unfolding proj2_line_rep_def\n    by simp\n  thus \"apply_cltn2_line l A\n    = proj2_line_abs (cltn2_rep (cltn2_inverse A) *v proj2_line_rep l)\"\n    unfolding apply_cltn2_line_def and proj2_line_abs_def ..\nqed\n\n\n\nlemma apply_cltn2_incident:\n  \"proj2_incident p (apply_cltn2_line l A)\n  \\<longleftrightarrow> proj2_incident (apply_cltn2 p (cltn2_inverse A)) l\"\nproof -\n  have \"proj2_rep p v* cltn2_rep (cltn2_inverse A) \\<noteq> 0\"\n    by (rule rep_mult_rep_non_zero)\n  with proj2_rep_abs2\n  obtain j where \"j \\<noteq> 0\"\n    and \"proj2_rep (proj2_abs (proj2_rep p v* cltn2_rep (cltn2_inverse A)))\n    = j *\\<^sub>R (proj2_rep p v* cltn2_rep (cltn2_inverse A))\"\n    by auto\n\n  let ?v = \"cltn2_rep (cltn2_inverse A) *v proj2_line_rep l\"\n  have \"?v \\<noteq> 0\" by (rule rep_mult_line_rep_non_zero)\n  with proj2_line_rep_abs [of ?v]\n  obtain k where \"k \\<noteq> 0\"\n    and \"proj2_line_rep (proj2_line_abs ?v) = k *\\<^sub>R ?v\"\n    by auto\n  hence \"proj2_incident p (apply_cltn2_line l A)\n    \\<longleftrightarrow> proj2_rep p \\<bullet> (cltn2_rep (cltn2_inverse A) *v proj2_line_rep l) = 0\"\n    unfolding proj2_incident_def and apply_cltn2_line_alt_def\n    by (simp add: dot_scaleR_mult)\n  also from dot_lmul_matrix [of \"proj2_rep p\" \"cltn2_rep (cltn2_inverse A)\"]\n  have\n    \"\\<dots> \\<longleftrightarrow> (proj2_rep p v* cltn2_rep (cltn2_inverse A)) \\<bullet> proj2_line_rep l = 0\"\n    by simp\n  also from \\<open>j \\<noteq> 0\\<close>\n    and \\<open>proj2_rep (proj2_abs (proj2_rep p v* cltn2_rep (cltn2_inverse A)))\n    = j *\\<^sub>R (proj2_rep p v* cltn2_rep (cltn2_inverse A))\\<close>\n  have \"\\<dots> \\<longleftrightarrow> proj2_incident (apply_cltn2 p (cltn2_inverse A)) l\"\n    unfolding proj2_incident_def and apply_cltn2_def\n    by (simp add: dot_scaleR_mult)\n  finally show ?thesis .\nqed\n\nlemma apply_cltn2_preserve_incident [iff]:\n  \"proj2_incident (apply_cltn2 p A) (apply_cltn2_line l A)\n  \\<longleftrightarrow> proj2_incident p l\"\n  by (simp add: apply_cltn2_incident)\n\nlemma apply_cltn2_preserve_set_Col:\n  assumes \"proj2_set_Col S\"\n  shows \"proj2_set_Col {apply_cltn2 p C | p. p \\<in> S}\"\nproof -\n  from \\<open>proj2_set_Col S\\<close>\n  obtain l where \"\\<forall> p\\<in>S. proj2_incident p l\" unfolding proj2_set_Col_def ..\n  hence \"\\<forall> q \\<in> {apply_cltn2 p C | p. p \\<in> S}.\n    proj2_incident q (apply_cltn2_line l C)\"\n    by auto\n  thus \"proj2_set_Col {apply_cltn2 p C | p. p \\<in> S}\"\n    unfolding proj2_set_Col_def ..\nqed\n\n\n\nlemma apply_cltn2_line_injective:\n  assumes \"apply_cltn2_line l C = apply_cltn2_line m C\"\n  shows \"l = m\"\nproof -\n  from \\<open>apply_cltn2_line l C = apply_cltn2_line m C\\<close>\n  have \"apply_cltn2_line (apply_cltn2_line l C) (cltn2_inverse C)\n    = apply_cltn2_line (apply_cltn2_line m C) (cltn2_inverse C)\"\n    by simp\n  thus \"l = m\" by simp\nqed\n\nlemma apply_cltn2_line_unique:\n  assumes \"p \\<noteq> q\" and \"proj2_incident p l\" and \"proj2_incident q l\"\n  and \"proj2_incident (apply_cltn2 p C) m\"\n  and \"proj2_incident (apply_cltn2 q C) m\"\n  shows \"apply_cltn2_line l C = m\"\nproof -\n  from \\<open>proj2_incident p l\\<close>\n  have \"proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)\" by simp\n\n  from \\<open>proj2_incident q l\\<close>\n  have \"proj2_incident (apply_cltn2 q C) (apply_cltn2_line l C)\" by simp\n\n  from \\<open>p \\<noteq> q\\<close> and apply_cltn2_injective [of p C q]\n  have \"apply_cltn2 p C \\<noteq> apply_cltn2 q C\" by auto\n  with \\<open>proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)\\<close>\n    and \\<open>proj2_incident (apply_cltn2 q C) (apply_cltn2_line l C)\\<close>\n    and \\<open>proj2_incident (apply_cltn2 p C) m\\<close>\n    and \\<open>proj2_incident (apply_cltn2 q C) m\\<close>\n    and proj2_incident_unique\n  show \"apply_cltn2_line l C = m\" by fast\nqed\n\nlemma apply_cltn2_unique:\n  assumes \"l \\<noteq> m\" and \"proj2_incident p l\" and \"proj2_incident p m\"\n  and \"proj2_incident q (apply_cltn2_line l C)\"\n  and \"proj2_incident q (apply_cltn2_line m C)\"\n  shows \"apply_cltn2 p C = q\"\nproof -\n  from \\<open>proj2_incident p l\\<close>\n  have \"proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)\" by simp\n\n  from \\<open>proj2_incident p m\\<close>\n  have \"proj2_incident (apply_cltn2 p C) (apply_cltn2_line m C)\" by simp\n\n  from \\<open>l \\<noteq> m\\<close> and apply_cltn2_line_injective [of l C m]\n  have \"apply_cltn2_line l C \\<noteq> apply_cltn2_line m C\" by auto\n  with \\<open>proj2_incident (apply_cltn2 p C) (apply_cltn2_line l C)\\<close>\n    and \\<open>proj2_incident (apply_cltn2 p C) (apply_cltn2_line m C)\\<close>\n    and \\<open>proj2_incident q (apply_cltn2_line l C)\\<close>\n    and \\<open>proj2_incident q (apply_cltn2_line m C)\\<close>\n    and proj2_incident_unique\n  show \"apply_cltn2 p C = q\" by fast\nqed\n\nsubsubsection \\<open>Parts of some Statements from \\cite{borsuk}\\<close>\ntext \\<open>All theorems with names beginning with \\emph{statement} are based\n  on corresponding theorems in \\cite{borsuk}.\\<close>\n\nlemma statement52_existence:\n  fixes a :: \"proj2^3\" and a3 :: \"proj2\"\n  assumes \"proj2_no_3_Col (insert a3 (range (($) a)))\"\n  shows \"\\<exists> A. apply_cltn2 (proj2_abs (vector [1,1,1])) A = a3 \\<and>\n  (\\<forall> j. apply_cltn2 (proj2_abs (axis j 1)) A = a$j)\"\nproof -\n  let ?v = \"proj2_rep a3\"\n  let ?B = \"proj2_rep ` range (($) a)\"\n\n  from \\<open>proj2_no_3_Col (insert a3 (range (($) a)))\\<close>\n  have \"card (insert a3 (range (($) a))) = 4\" unfolding proj2_no_3_Col_def ..\n\n  from card_image_le [of UNIV \"($) a\"]\n  have \"card (range (($) a)) \\<le> 3\" by simp\n  with card_insert_if [of \"range (($) a)\" a3]\n    and \\<open>card (insert a3 (range (($) a))) = 4\\<close>\n  have \"a3 \\<notin> range (($) a)\" by auto\n  hence \"(insert a3 (range (($) a))) - {a3} = range (($) a)\" by simp\n  with \\<open>proj2_no_3_Col (insert a3 (range (($) a)))\\<close>\n    and proj2_no_3_Col_span [of \"insert a3 (range (($) a))\" a3]\n  have \"span ?B = UNIV\" by simp\n\n  from card_suc_ge_insert [of a3 \"range (($) a)\"]\n    and \\<open>card (insert a3 (range (($) a))) = 4\\<close>\n    and \\<open>card (range (($) a)) \\<le> 3\\<close>\n  have \"card (range (($) a)) = 3\" by simp\n  with card_image [of proj2_rep \"range (($) a)\"]\n    and proj2_rep_inj\n    and subset_inj_on\n  have \"card ?B = 3\" by auto\n  hence \"finite ?B\" by simp\n  with \\<open>span ?B = UNIV\\<close> and span_finite [of ?B]\n  obtain c where \"(\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) = ?v\"\n    by (auto simp add: scalar_equiv) (metis (no_types, lifting) UNIV_I rangeE)\n  let ?C = \"\\<chi> i. c (proj2_rep (a$i)) *\\<^sub>R (proj2_rep (a$i))\"\n  let ?A = \"cltn2_abs ?C\"\n\n  from proj2_rep_inj and \\<open>a3 \\<notin> range (($) a)\\<close> have \"?v \\<notin> ?B\"\n    unfolding inj_on_def\n    by auto\n\n  have \"\\<forall> i. c (proj2_rep (a$i)) \\<noteq> 0\"\n  proof\n    fix i\n    let ?Bi = \"proj2_rep ` (range (($) a) - {a$i})\"\n\n    have \"a$i \\<in> insert a3 (range (($) a))\" by simp\n\n    have \"proj2_rep (a$i) \\<in> ?B\" by auto\n\n    from image_set_diff [of proj2_rep] and proj2_rep_inj\n    have \"?Bi = ?B - {proj2_rep (a$i)}\" by simp\n    with sum_diff1 [of ?B \"\\<lambda> w. (c w) *\\<^sub>R w\"]\n      and \\<open>finite ?B\\<close>\n      and \\<open>proj2_rep (a$i) \\<in> ?B\\<close>\n    have \"(\\<Sum> w \\<in> ?Bi. (c w) *\\<^sub>R w) =\n      (\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) - c (proj2_rep (a$i)) *\\<^sub>R proj2_rep (a$i)\"\n      by simp\n\n    from \\<open>a3 \\<notin> range (($) a)\\<close> have \"a3 \\<noteq> a$i\" by auto\n    hence \"insert a3 (range (($) a)) - {a$i} =\n      insert a3 (range (($) a) - {a$i})\" by auto\n    hence \"proj2_rep ` (insert a3 (range (($) a)) - {a$i}) = insert ?v ?Bi\"\n      by simp\n    moreover from \\<open>proj2_no_3_Col (insert a3 (range (($) a)))\\<close>\n      and \\<open>a$i \\<in> insert a3 (range (($) a))\\<close>\n    have \"span (proj2_rep ` (insert a3 (range (($) a)) - {a$i})) = UNIV\"\n      by (rule proj2_no_3_Col_span)\n    ultimately have \"span (insert ?v ?Bi) = UNIV\" by simp\n\n    from \\<open>?Bi = ?B - {proj2_rep (a$i)}\\<close>\n      and \\<open>proj2_rep (a$i) \\<in> ?B\\<close>\n      and \\<open>card ?B = 3\\<close>\n    have \"card ?Bi = 2\" by (simp add: card_gt_0_diff_singleton)\n    hence \"finite ?Bi\" by simp\n    with \\<open>card ?Bi = 2\\<close> and dim_le_card' [of ?Bi] have \"dim ?Bi \\<le> 2\" by simp\n    hence \"dim (span ?Bi) \\<le> 2\" by (subst dim_span)\n    then have \"span ?Bi \\<noteq> UNIV\"\n      by clarify (auto simp: dim_UNIV)\n    with \\<open>span (insert ?v ?Bi) = UNIV\\<close> and span_redundant\n    have \"?v \\<notin> span ?Bi\" by auto\n\n    { assume \"c (proj2_rep (a$i)) = 0\"\n      with \\<open>(\\<Sum> w \\<in> ?Bi. (c w) *\\<^sub>R w) =\n        (\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) - c (proj2_rep (a$i)) *\\<^sub>R proj2_rep (a$i)\\<close>\n        and \\<open>(\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) = ?v\\<close>\n      have \"?v = (\\<Sum> w \\<in> ?Bi. (c w) *\\<^sub>R w)\"\n        by simp\n      with span_finite [of ?Bi] and \\<open>finite ?Bi\\<close>\n      have \"?v \\<in> span ?Bi\" by (simp add: scalar_equiv)\n      with \\<open>?v \\<notin> span ?Bi\\<close> have False .. }\n    thus \"c (proj2_rep (a$i)) \\<noteq> 0\" ..\n  qed\n  hence \"\\<forall> w\\<in>?B. c w \\<noteq> 0\"\n    unfolding image_def\n    by auto\n\n  have \"rows ?C = (\\<lambda> w. (c w) *\\<^sub>R w) ` ?B\"\n    unfolding rows_def\n      and row_def\n      and image_def\n    by (auto simp: vec_lambda_eta)\n\n  have \"\\<forall> x. x \\<in> span (rows ?C)\"\n  proof\n    fix x :: \"real^3\"\n    from \\<open>finite ?B\\<close> and span_finite [of ?B] and \\<open>span ?B = UNIV\\<close>\n    obtain ub where \"(\\<Sum> w\\<in>?B. (ub w) *\\<^sub>R w) = x\"\n      by (auto simp add: scalar_equiv) (metis (no_types, lifting) UNIV_I rangeE)\n    have \"\\<forall> w\\<in>?B. (ub w) *\\<^sub>R w \\<in> span (rows ?C)\"\n    proof\n      fix w\n      assume \"w \\<in> ?B\"\n      with span_superset [of \"rows ?C\"] and \\<open>rows ?C = image (\\<lambda> w. (c w) *\\<^sub>R w) ?B\\<close>\n      have \"(c w) *\\<^sub>R w \\<in> span (rows ?C)\" by auto\n      with span_mul [of \"(c w) *\\<^sub>R w\" \"rows ?C\" \"(ub w)/(c w)\"]\n      have \"((ub w)/(c w)) *\\<^sub>R ((c w) *\\<^sub>R w) \\<in> span (rows ?C)\"\n        by (simp add: scalar_equiv)\n      with \\<open>\\<forall> w\\<in>?B. c w \\<noteq> 0\\<close> and \\<open>w \\<in> ?B\\<close>\n      show \"(ub w) *\\<^sub>R w \\<in> span (rows ?C)\" by auto\n    qed\n    with span_sum [of ?B \"\\<lambda> w. (ub w) *\\<^sub>R w\"] and \\<open>finite ?B\\<close>\n    have \"(\\<Sum> w\\<in>?B. (ub w) *\\<^sub>R w) \\<in> span (rows ?C)\" by blast\n    with \\<open>(\\<Sum> w\\<in>?B. (ub w) *\\<^sub>R w) = x\\<close> show \"x \\<in> span (rows ?C)\" by simp\n  qed\n  hence \"span (rows ?C) = UNIV\" by auto\n  with matrix_left_invertible_span_rows [of ?C]\n  have \"\\<exists> C'. C' ** ?C = mat 1\" ..\n  with left_invertible_iff_invertible\n  have \"invertible ?C\" ..\n\n  have \"(vector [1,1,1] :: real^3) \\<noteq> 0\"\n    unfolding vector_def\n    by (simp add: vec_eq_iff forall_3)\n  with apply_cltn2_abs and \\<open>invertible ?C\\<close>\n  have \"apply_cltn2 (proj2_abs (vector [1,1,1])) ?A =\n    proj2_abs (vector [1,1,1] v* ?C)\"\n    by simp\n  from inj_on_iff_eq_card [of UNIV \"($) a\"] and \\<open>card (range (($) a)) = 3\\<close>\n  have \"inj (($) a)\" by simp\n  from exhaust_3 have \"\\<forall> i::3. (vector [1::real,1,1])$i = 1\"\n    unfolding vector_def\n    by auto\n  with vector_matrix_row [of \"vector [1,1,1]\" ?C]\n  have \"(vector [1,1,1]) v* ?C =\n    (\\<Sum> i\\<in>UNIV. (c (proj2_rep (a$i))) *\\<^sub>R (proj2_rep (a$i)))\"\n    by simp\n  also from sum.reindex\n  [of \"($) a\" UNIV \"\\<lambda> x. (c (proj2_rep x)) *\\<^sub>R (proj2_rep x)\"]\n    and \\<open>inj (($) a)\\<close>\n  have \"\\<dots> = (\\<Sum> x\\<in>(range (($) a)). (c (proj2_rep x)) *\\<^sub>R (proj2_rep x))\"\n    by simp\n  also from sum.reindex\n  [of proj2_rep \"range (($) a)\" \"\\<lambda> w. (c w) *\\<^sub>R w\"]\n    and proj2_rep_inj and subset_inj_on [of proj2_rep UNIV \"range (($) a)\"]\n  have \"\\<dots> = (\\<Sum> w\\<in>?B. (c w) *\\<^sub>R w)\" by simp\n  also from \\<open>(\\<Sum> w \\<in> ?B. (c w) *\\<^sub>R w) = ?v\\<close> have \"\\<dots> = ?v\" by simp\n  finally have \"(vector [1,1,1]) v* ?C = ?v\" .\n  with \\<open>apply_cltn2 (proj2_abs (vector [1,1,1])) ?A =\n    proj2_abs (vector [1,1,1] v* ?C)\\<close>\n  have \"apply_cltn2 (proj2_abs (vector [1,1,1])) ?A = proj2_abs ?v\" by simp\n  with proj2_abs_rep have \"apply_cltn2 (proj2_abs (vector [1,1,1])) ?A = a3\"\n    by simp\n  have \"\\<forall> j. apply_cltn2 (proj2_abs (axis j 1)) ?A = a$j\"\n  proof\n    fix j :: \"3\"\n    have \"((axis j 1)::real^3) \\<noteq> 0\" by (simp add: vec_eq_iff axis_def)\n    with apply_cltn2_abs and \\<open>invertible ?C\\<close>\n    have \"apply_cltn2 (proj2_abs (axis j 1)) ?A = proj2_abs (axis j 1 v* ?C)\"\n      by simp\n\n    have \"\\<forall> i\\<in>(UNIV-{j}).\n      ((axis j 1)$i * c (proj2_rep (a$i))) *\\<^sub>R (proj2_rep (a$i)) = 0\"\n      by (simp add: axis_def)\n    with sum.mono_neutral_left [of UNIV \"{j}\"\n      \"\\<lambda> i. ((axis j 1)$i * c (proj2_rep (a$i))) *\\<^sub>R (proj2_rep (a$i))\"]\n      and vector_matrix_row [of \"axis j 1\" ?C]\n    have \"(axis j 1) v* ?C = ?C$j\" by (simp add: scalar_equiv)\n    hence \"(axis j 1) v* ?C = c (proj2_rep (a$j)) *\\<^sub>R (proj2_rep (a$j))\" by simp\n    with proj2_abs_mult_rep and \\<open>\\<forall> i. c (proj2_rep (a$i)) \\<noteq> 0\\<close>\n      and \\<open>apply_cltn2 (proj2_abs (axis j 1)) ?A = proj2_abs (axis j 1 v* ?C)\\<close>\n    show \"apply_cltn2 (proj2_abs (axis j 1)) ?A = a$j\"\n      by simp\n  qed\n  with \\<open>apply_cltn2 (proj2_abs (vector [1,1,1])) ?A = a3\\<close>\n  show \"\\<exists> A. apply_cltn2 (proj2_abs (vector [1,1,1])) A = a3 \\<and>\n    (\\<forall> j. apply_cltn2 (proj2_abs (axis j 1)) A = a$j)\"\n    by auto\nqed\n\nlemma statement53_existence:\n  fixes p :: \"proj2^4^2\"\n  assumes \"\\<forall> i. proj2_no_3_Col (range (($) (p$i)))\"\n  shows \"\\<exists> C. \\<forall> j. apply_cltn2 (p$0$j) C = p$1$j\"\nproof -\n  let ?q = \"\\<chi> i. \\<chi> j::3. p$i $ (of_int (Rep_bit1 j))\"\n  let ?D = \"\\<chi> i. \\<some> D. apply_cltn2 (proj2_abs (vector [1,1,1])) D = p$i$3\n    \\<and> (\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) D = ?q$i$j')\"\n  have \"\\<forall> i. apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$i) = p$i$3\n    \\<and> (\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) (?D$i) = ?q$i$j')\"\n  proof\n    fix i\n    have \"range (($) (p$i)) = insert (p$i$3) (range (($) (?q$i)))\"\n    proof\n      show \"range (($) (p$i)) \\<supseteq> insert (p$i$3) (range (($) (?q$i)))\" by auto\n      show \"range (($) (p$i)) \\<subseteq> insert (p$i$3) (range (($) (?q$i)))\"\n      proof\n        fix r\n        assume \"r \\<in> range (($) (p$i))\"\n        then obtain j where \"r = p$i$j\" by auto\n        with eq_3_or_of_3 [of j]\n        show \"r \\<in> insert (p$i$3) (range (($) (?q$i)))\" by auto\n      qed\n    qed\n    moreover from \\<open>\\<forall> i. proj2_no_3_Col (range (($) (p$i)))\\<close>\n    have \"proj2_no_3_Col (range (($) (p$i)))\" ..\n    ultimately have \"proj2_no_3_Col (insert (p$i$3) (range (($) (?q$i))))\"\n      by simp\n    hence \"\\<exists> D. apply_cltn2 (proj2_abs (vector [1,1,1])) D = p$i$3\n      \\<and> (\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) D = ?q$i$j')\"\n      by (rule statement52_existence)\n    with someI_ex [of \"\\<lambda> D. apply_cltn2 (proj2_abs (vector [1,1,1])) D = p$i$3\n      \\<and> (\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) D = ?q$i$j')\"]\n    show \"apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$i) = p$i$3\n      \\<and> (\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) (?D$i) = ?q$i$j')\"\n      by simp\n  qed\n  hence \"apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$0) = p$0$3\"\n    and \"apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$1) = p$1$3\"\n    and \"\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) (?D$0) = ?q$0$j'\"\n    and \"\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) (?D$1) = ?q$1$j'\"\n    by simp_all\n\n  let ?C = \"cltn2_compose (cltn2_inverse (?D$0)) (?D$1)\"\n  have \"\\<forall> j. apply_cltn2 (p$0$j) ?C = p$1$j\"\n  proof\n    fix j\n    show \"apply_cltn2 (p$0$j) ?C = p$1$j\"\n    proof cases\n      assume \"j = 3\"\n      with \\<open>apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$0) = p$0$3\\<close>\n        and  cltn2.act_inv_iff\n      have\n        \"apply_cltn2 (p$0$j) (cltn2_inverse (?D$0)) = proj2_abs (vector [1,1,1])\"\n        by simp\n      with \\<open>apply_cltn2 (proj2_abs (vector [1,1,1])) (?D$1) = p$1$3\\<close>\n        and \\<open>j = 3\\<close>\n        and cltn2.act_act [of \"cltn2_inverse (?D$0)\" \"?D$1\" \"p$0$j\"]\n      show \"apply_cltn2 (p$0$j) ?C = p$1$j\" by simp\n    next\n      assume \"j \\<noteq> 3\"\n      with eq_3_or_of_3 obtain j' :: 3 where \"j = of_int (Rep_bit1 j')\"\n        by metis\n      with \\<open>\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) (?D$0) = ?q$0$j'\\<close>\n        and \\<open>\\<forall> j'. apply_cltn2 (proj2_abs (axis j' 1)) (?D$1) = ?q$1$j'\\<close>\n      have \"p$0$j = apply_cltn2 (proj2_abs (axis j' 1)) (?D$0)\"\n        and \"p$1$j = apply_cltn2 (proj2_abs (axis j' 1)) (?D$1)\"\n        by simp_all\n      from \\<open>p$0$j = apply_cltn2 (proj2_abs (axis j' 1)) (?D$0)\\<close>\n        and cltn2.act_inv_iff\n      have \"apply_cltn2 (p$0$j) (cltn2_inverse (?D$0)) = proj2_abs (axis j' 1)\"\n        by simp\n      with \\<open>p$1$j = apply_cltn2 (proj2_abs (axis j' 1)) (?D$1)\\<close>\n        and cltn2.act_act [of \"cltn2_inverse (?D$0)\" \"?D$1\" \"p$0$j\"]\n      show \"apply_cltn2 (p$0$j) ?C = p$1$j\" by simp\n    qed\n  qed\n  thus \"\\<exists> C. \\<forall> j. apply_cltn2 (p$0$j) C = p$1$j\" by (rule exI [of _ ?C])\nqed\n\nlemma apply_cltn2_linear:\n  assumes \"j *\\<^sub>R v + k *\\<^sub>R w \\<noteq> 0\"\n  shows \"j *\\<^sub>R (v v* cltn2_rep C) + k *\\<^sub>R (w v* cltn2_rep C) \\<noteq> 0\"\n  (is \"?u \\<noteq> 0\")\n  and \"apply_cltn2 (proj2_abs (j *\\<^sub>R v + k *\\<^sub>R w)) C\n  = proj2_abs (j *\\<^sub>R (v v* cltn2_rep C) + k *\\<^sub>R (w v* cltn2_rep C))\"\nproof -\n  have \"?u = (j *\\<^sub>R v + k *\\<^sub>R w) v* cltn2_rep C\"\n    by (simp only: vector_matrix_left_distrib scaleR_vector_matrix_assoc)\n  with \\<open>j *\\<^sub>R v + k *\\<^sub>R w \\<noteq> 0\\<close> and non_zero_mult_rep_non_zero\n  show \"?u \\<noteq> 0\" by simp\n\n  from \\<open>?u = (j *\\<^sub>R v + k *\\<^sub>R w) v* cltn2_rep C\\<close>\n    and \\<open>j *\\<^sub>R v + k *\\<^sub>R w \\<noteq> 0\\<close>\n    and apply_cltn2_left_abs\n  show \"apply_cltn2 (proj2_abs (j *\\<^sub>R v + k *\\<^sub>R w)) C = proj2_abs ?u\"\n    by simp\nqed\n\nlemma apply_cltn2_imp_mult:\n  assumes \"apply_cltn2 p C = q\"\n  shows \"\\<exists> k. k \\<noteq> 0 \\<and> proj2_rep p v* cltn2_rep C = k *\\<^sub>R proj2_rep q\"\nproof -\n  have \"proj2_rep p v* cltn2_rep C \\<noteq> 0\" by (rule rep_mult_rep_non_zero)\n\n  from \\<open>apply_cltn2 p C = q\\<close>\n  have \"proj2_abs (proj2_rep p v* cltn2_rep C) = q\" by (unfold apply_cltn2_def)\n  hence \"proj2_rep (proj2_abs (proj2_rep p v* cltn2_rep C)) = proj2_rep q\"\n    by simp\n  with \\<open>proj2_rep p v* cltn2_rep C \\<noteq> 0\\<close> and proj2_rep_abs2 [of \"proj2_rep p v* cltn2_rep C\"]\n  have \"\\<exists> j. j \\<noteq> 0 \\<and> proj2_rep q = j *\\<^sub>R (proj2_rep p v* cltn2_rep C)\" by simp\n  then obtain j where \"j \\<noteq> 0\"\n    and \"proj2_rep q = j *\\<^sub>R (proj2_rep p v* cltn2_rep C)\" by auto\n  hence \"proj2_rep p v* cltn2_rep C = (1/j) *\\<^sub>R proj2_rep q\"\n    by (simp add: field_simps)\n  with \\<open>j \\<noteq> 0\\<close>\n  show \"\\<exists> k. k \\<noteq> 0 \\<and> proj2_rep p v* cltn2_rep C = k *\\<^sub>R proj2_rep q\"\n    by (simp add: exI [of _ \"1/j\"])\nqed\n\nlemma statement55:\n  assumes \"p \\<noteq> q\"\n  and \"apply_cltn2 p C = q\"\n  and \"apply_cltn2 q C = p\"\n  and \"proj2_incident p l\"\n  and \"proj2_incident q l\"\n  and \"proj2_incident r l\"\n  shows \"apply_cltn2 (apply_cltn2 r C) C = r\"\nproof cases\n  assume \"r = p\"\n  with \\<open>apply_cltn2 p C = q\\<close> and \\<open>apply_cltn2 q C = p\\<close>\n  show \"apply_cltn2 (apply_cltn2 r C) C = r\" by simp\nnext\n  assume \"r \\<noteq> p\"\n\n  from \\<open>apply_cltn2 p C = q\\<close> and apply_cltn2_imp_mult [of p C q]\n  obtain i where \"i \\<noteq> 0\" and \"proj2_rep p v* cltn2_rep C = i *\\<^sub>R proj2_rep q\"\n    by auto\n\n  from \\<open>apply_cltn2 q C = p\\<close> and apply_cltn2_imp_mult [of q C p]\n  obtain j where \"j \\<noteq> 0\" and \"proj2_rep q v* cltn2_rep C = j *\\<^sub>R proj2_rep p\"\n    by auto\n\n  from \\<open>p \\<noteq> q\\<close>\n    and \\<open>proj2_incident p l\\<close>\n    and \\<open>proj2_incident q l\\<close>\n    and \\<open>proj2_incident r l\\<close>\n    and proj2_incident_iff\n  have \"r = p \\<or> (\\<exists> k. r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q))\"\n    by fast\n  with \\<open>r \\<noteq> p\\<close>\n  obtain k where \"r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\" by auto\n\n  from \\<open>p \\<noteq> q\\<close> and proj2_rep_dependent [of k p 1 q]\n  have \"k *\\<^sub>R proj2_rep p + proj2_rep q \\<noteq> 0\" by auto\n  with \\<open>r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\\<close>\n    and apply_cltn2_linear [of k \"proj2_rep p\" 1 \"proj2_rep q\"]\n  have \"k *\\<^sub>R (proj2_rep p v* cltn2_rep C) + proj2_rep q v* cltn2_rep C \\<noteq> 0\"\n    and \"apply_cltn2 r C\n    = proj2_abs\n    (k *\\<^sub>R (proj2_rep p v* cltn2_rep C) + proj2_rep q v* cltn2_rep C)\"\n    by simp_all\n  with \\<open>proj2_rep p v* cltn2_rep C = i *\\<^sub>R proj2_rep q\\<close>\n    and \\<open>proj2_rep q v* cltn2_rep C = j *\\<^sub>R proj2_rep p\\<close>\n  have \"(k * i) *\\<^sub>R proj2_rep q + j *\\<^sub>R proj2_rep p \\<noteq> 0\"\n    and \"apply_cltn2 r C\n    = proj2_abs ((k * i) *\\<^sub>R proj2_rep q + j *\\<^sub>R proj2_rep p)\"\n    by simp_all\n  with apply_cltn2_linear\n  have \"apply_cltn2 (apply_cltn2 r C) C\n    = proj2_abs\n    ((k * i) *\\<^sub>R (proj2_rep q v* cltn2_rep C)\n    + j *\\<^sub>R (proj2_rep p v* cltn2_rep C))\"\n    by simp\n  with \\<open>proj2_rep p v* cltn2_rep C = i *\\<^sub>R proj2_rep q\\<close>\n    and \\<open>proj2_rep q v* cltn2_rep C = j *\\<^sub>R proj2_rep p\\<close>\n  have \"apply_cltn2 (apply_cltn2 r C) C\n    = proj2_abs ((k * i * j) *\\<^sub>R proj2_rep p + (j * i) *\\<^sub>R proj2_rep q)\"\n    by simp\n  also have \"\\<dots> = proj2_abs ((i * j) *\\<^sub>R (k *\\<^sub>R proj2_rep p + proj2_rep q))\"\n    by (simp add: algebra_simps)\n  also from \\<open>i \\<noteq> 0\\<close> and \\<open>j \\<noteq> 0\\<close> and proj2_abs_mult\n  have \"\\<dots> = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\" by simp\n  also from \\<open>r = proj2_abs (k *\\<^sub>R proj2_rep p + proj2_rep q)\\<close>\n  have \"\\<dots> = r\" by simp\n  finally show \"apply_cltn2 (apply_cltn2 r C) C = r\" .\nqed\n\nsubsection \"Cross ratios\"\n\ndefinition cross_ratio :: \"proj2 \\<Rightarrow> proj2 \\<Rightarrow> proj2 \\<Rightarrow> proj2 \\<Rightarrow> real\" where\n  \"cross_ratio p q r s \\<equiv> proj2_Col_coeff p q s / proj2_Col_coeff p q r\"\n\ndefinition cross_ratio_correct :: \"proj2 \\<Rightarrow> proj2 \\<Rightarrow> proj2 \\<Rightarrow> proj2 \\<Rightarrow> bool\" where\n  \"cross_ratio_correct p q r s \\<equiv>\n  proj2_set_Col {p,q,r,s} \\<and> p \\<noteq> q \\<and> r \\<noteq> p \\<and> s \\<noteq> p \\<and> r \\<noteq> q\"\n\nlemma proj2_Col_coeff_abs:\n  assumes \"p \\<noteq> q\" and \"j \\<noteq> 0\"\n  shows \"proj2_Col_coeff p q (proj2_abs (i *\\<^sub>R proj2_rep p + j *\\<^sub>R proj2_rep q))\n  = i/j\"\n  (is \"proj2_Col_coeff p q ?r = i/j\")\nproof -\n  from \\<open>j \\<noteq> 0\\<close>\n    and proj2_abs_mult [of \"1/j\" \"i *\\<^sub>R proj2_rep p + j *\\<^sub>R proj2_rep q\"]\n  have \"?r = proj2_abs ((i/j) *\\<^sub>R proj2_rep p + proj2_rep q)\"\n    by (simp add: scaleR_right_distrib)\n\n  from \\<open>p \\<noteq> q\\<close> and proj2_rep_dependent [of _ p 1 q]\n  have \"(i/j) *\\<^sub>R proj2_rep p + proj2_rep q \\<noteq> 0\" by auto\n  with \\<open>?r = proj2_abs ((i/j) *\\<^sub>R proj2_rep p + proj2_rep q)\\<close>\n    and proj2_rep_abs2\n  obtain k where \"k \\<noteq> 0\"\n    and \"proj2_rep ?r = k *\\<^sub>R ((i/j) *\\<^sub>R proj2_rep p + proj2_rep q)\"\n    by auto\n  hence \"(k*i/j) *\\<^sub>R proj2_rep p + k *\\<^sub>R proj2_rep q - proj2_rep ?r = 0\"\n    by (simp add: scaleR_right_distrib)\n  hence \"\\<exists> l. (k*i/j) *\\<^sub>R proj2_rep p + k *\\<^sub>R proj2_rep q + l *\\<^sub>R proj2_rep ?r = 0\n    \\<and> (k*i/j \\<noteq> 0 \\<or> k \\<noteq> 0 \\<or> l \\<noteq> 0)\"\n    by (simp add: exI [of _ \"-1\"])\n  hence \"proj2_Col p q ?r\" by (unfold proj2_Col_def) auto\n\n  have \"?r \\<noteq> p\"\n  proof\n    assume \"?r = p\"\n    with \\<open>(k*i/j) *\\<^sub>R proj2_rep p + k *\\<^sub>R proj2_rep q - proj2_rep ?r = 0\\<close>\n    have \"(k*i/j - 1) *\\<^sub>R proj2_rep p + k *\\<^sub>R proj2_rep q = 0\"\n      by (simp add: algebra_simps)\n    with \\<open>k \\<noteq> 0\\<close> and proj2_rep_dependent have \"p = q\" by simp\n    with \\<open>p \\<noteq> q\\<close> show False ..\n  qed\n  with \\<open>proj2_Col p q ?r\\<close> and \\<open>p \\<noteq> q\\<close>\n  have \"?r = proj2_abs (proj2_Col_coeff p q ?r *\\<^sub>R proj2_rep p + proj2_rep q)\"\n    by (rule proj2_Col_coeff)\n  with \\<open>p \\<noteq> q\\<close> and \\<open>?r = proj2_abs ((i/j) *\\<^sub>R proj2_rep p + proj2_rep q)\\<close>\n    and proj2_Col_coeff_unique\n  show \"proj2_Col_coeff p q ?r = i/j\" by simp\nqed\n\nlemma proj2_set_Col_coeff:\n  assumes \"proj2_set_Col S\" and \"{p,q,r} \\<subseteq> S\" and \"p \\<noteq> q\" and \"r \\<noteq> p\"\n  shows \"r = proj2_abs (proj2_Col_coeff p q r *\\<^sub>R proj2_rep p + proj2_rep q)\"\n  (is \"r = proj2_abs (?i *\\<^sub>R ?u + ?v)\")\nproof -\n  from \\<open>{p,q,r} \\<subseteq> S\\<close> and \\<open>proj2_set_Col S\\<close>\n  have \"proj2_set_Col {p,q,r}\" by (rule proj2_subset_Col)\n  hence \"proj2_Col p q r\" by (subst proj2_Col_iff_set_Col)\n  with \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and proj2_Col_coeff\n  show \"r = proj2_abs (?i *\\<^sub>R ?u + ?v)\" by simp\nqed\n\nlemma cross_ratio_abs:\n  fixes u v :: \"real^3\" and i j k l :: real\n  assumes \"u \\<noteq> 0\" and \"v \\<noteq> 0\" and \"proj2_abs u \\<noteq> proj2_abs v\"\n  and \"j \\<noteq> 0\" and \"l \\<noteq> 0\"\n  shows \"cross_ratio (proj2_abs u) (proj2_abs v)\n  (proj2_abs (i *\\<^sub>R u + j *\\<^sub>R v))\n  (proj2_abs (k *\\<^sub>R u + l *\\<^sub>R v))\n  = j * k / (i * l)\"\n  (is \"cross_ratio ?p ?q ?r ?s = _\")\nproof -\n  from \\<open>u \\<noteq> 0\\<close> and proj2_rep_abs2\n  obtain g where \"g \\<noteq> 0\" and \"proj2_rep ?p = g *\\<^sub>R u\" by auto\n\n  from \\<open>v \\<noteq> 0\\<close> and proj2_rep_abs2\n  obtain h where \"h \\<noteq> 0\" and \"proj2_rep ?q = h *\\<^sub>R v\" by auto\n  with \\<open>g \\<noteq> 0\\<close> and \\<open>proj2_rep ?p = g *\\<^sub>R u\\<close>\n  have \"?r = proj2_abs ((i/g) *\\<^sub>R proj2_rep ?p + (j/h) *\\<^sub>R proj2_rep ?q)\"\n    and \"?s = proj2_abs ((k/g) *\\<^sub>R proj2_rep ?p + (l/h) *\\<^sub>R proj2_rep ?q)\"\n    by (simp_all add: field_simps)\n  with \\<open>?p \\<noteq> ?q\\<close> and \\<open>h \\<noteq> 0\\<close> and \\<open>j \\<noteq> 0\\<close> and \\<open>l \\<noteq> 0\\<close> and proj2_Col_coeff_abs\n  have \"proj2_Col_coeff ?p ?q ?r = h*i/(g*j)\"\n    and \"proj2_Col_coeff ?p ?q ?s = h*k/(g*l)\"\n    by simp_all\n  with \\<open>g \\<noteq> 0\\<close> and \\<open>h \\<noteq> 0\\<close>\n  show \"cross_ratio ?p ?q ?r ?s = j*k/(i*l)\"\n    by (unfold cross_ratio_def) (simp add: field_simps)\nqed\n\nlemma cross_ratio_abs2:\n  assumes \"p \\<noteq> q\"\n  shows \"cross_ratio p q\n  (proj2_abs (i *\\<^sub>R proj2_rep p + proj2_rep q))\n  (proj2_abs (j *\\<^sub>R proj2_rep p + proj2_rep q))\n  = j/i\"\n  (is \"cross_ratio p q ?r ?s = _\")\nproof -\n  let ?u = \"proj2_rep p\"\n  let ?v = \"proj2_rep q\"\n  have \"?u \\<noteq> 0\" and \"?v \\<noteq> 0\" by (rule proj2_rep_non_zero)+\n\n  have \"proj2_abs ?u = p\" and \"proj2_abs ?v = q\" by (rule proj2_abs_rep)+\n  with \\<open>?u \\<noteq> 0\\<close> and \\<open>?v \\<noteq> 0\\<close> and \\<open>p \\<noteq> q\\<close> and cross_ratio_abs [of ?u ?v 1 1 i j]\n  show \"cross_ratio p q ?r ?s = j/i\" by simp\nqed\n\nlemma cross_ratio_correct_cltn2:\n  assumes \"cross_ratio_correct p q r s\"\n  shows \"cross_ratio_correct (apply_cltn2 p C) (apply_cltn2 q C)\n  (apply_cltn2 r C) (apply_cltn2 s C)\"\n  (is \"cross_ratio_correct ?pC ?qC ?rC ?sC\")\nproof -\n  from \\<open>cross_ratio_correct p q r s\\<close>\n  have \"proj2_set_Col {p,q,r,s}\"\n    and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"s \\<noteq> p\" and \"r \\<noteq> q\"\n    by (unfold cross_ratio_correct_def) simp_all\n\n  have \"{apply_cltn2 t C | t. t \\<in> {p,q,r,s}} = {?pC,?qC,?rC,?sC}\" by auto\n  with \\<open>proj2_set_Col {p,q,r,s}\\<close>\n    and apply_cltn2_preserve_set_Col [of \"{p,q,r,s}\" C]\n  have \"proj2_set_Col {?pC,?qC,?rC,?sC}\" by simp\n\n  from \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>s \\<noteq> p\\<close> and \\<open>r \\<noteq> q\\<close> and apply_cltn2_injective\n  have \"?pC \\<noteq> ?qC\" and \"?rC \\<noteq> ?pC\" and \"?sC \\<noteq> ?pC\" and \"?rC \\<noteq> ?qC\" by fast+\n  with \\<open>proj2_set_Col {?pC,?qC,?rC,?sC}\\<close>\n  show \"cross_ratio_correct ?pC ?qC ?rC ?sC\"\n    by (unfold cross_ratio_correct_def) simp\nqed\n\nlemma cross_ratio_cltn2:\n  assumes \"proj2_set_Col {p,q,r,s}\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"s \\<noteq> p\"\n  shows \"cross_ratio (apply_cltn2 p C) (apply_cltn2 q C)\n  (apply_cltn2 r C) (apply_cltn2 s C)\n  = cross_ratio p q r s\"\n  (is \"cross_ratio ?pC ?qC ?rC ?sC = _\")\nproof -\n  let ?u = \"proj2_rep p\"\n  let ?v = \"proj2_rep q\"\n  let ?i = \"proj2_Col_coeff p q r\"\n  let ?j = \"proj2_Col_coeff p q s\"\n  from \\<open>proj2_set_Col {p,q,r,s}\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>s \\<noteq> p\\<close>\n    and proj2_set_Col_coeff\n  have \"r = proj2_abs (?i *\\<^sub>R ?u + ?v)\" and \"s = proj2_abs (?j *\\<^sub>R ?u + ?v)\"\n    by simp_all\n\n  let ?uC = \"?u v* cltn2_rep C\"\n  let ?vC = \"?v v* cltn2_rep C\"\n  have \"?uC \\<noteq> 0\" and \"?vC \\<noteq> 0\" by (rule rep_mult_rep_non_zero)+\n\n  have \"proj2_abs ?uC = ?pC\" and \"proj2_abs ?vC = ?qC\"\n    by (unfold apply_cltn2_def) simp_all\n\n  from \\<open>p \\<noteq> q\\<close> and apply_cltn2_injective have \"?pC \\<noteq> ?qC\" by fast\n\n  from \\<open>p \\<noteq> q\\<close> and proj2_rep_dependent [of _ p 1 q]\n  have \"?i *\\<^sub>R ?u + ?v \\<noteq> 0\" and \"?j *\\<^sub>R ?u + ?v \\<noteq> 0\" by auto\n  with \\<open>r = proj2_abs (?i *\\<^sub>R ?u + ?v)\\<close> and \\<open>s = proj2_abs (?j *\\<^sub>R ?u + ?v)\\<close>\n    and apply_cltn2_linear [of ?i ?u 1 ?v]\n    and apply_cltn2_linear [of ?j ?u 1 ?v]\n  have \"?rC = proj2_abs (?i *\\<^sub>R ?uC + ?vC)\"\n    and \"?sC = proj2_abs (?j *\\<^sub>R ?uC + ?vC)\"\n    by simp_all\n  with \\<open>?uC \\<noteq> 0\\<close> and \\<open>?vC \\<noteq> 0\\<close> and \\<open>proj2_abs ?uC = ?pC\\<close>\n    and \\<open>proj2_abs ?vC = ?qC\\<close> and \\<open>?pC \\<noteq> ?qC\\<close>\n    and cross_ratio_abs [of ?uC ?vC 1 1 ?i ?j]\n  have \"cross_ratio ?pC ?qC ?rC ?sC = ?j/?i\" by simp\n  thus \"cross_ratio ?pC ?qC ?rC ?sC = cross_ratio p q r s\"\n    unfolding cross_ratio_def [of p q r s] .\nqed\n\nlemma cross_ratio_unique:\n  assumes \"cross_ratio_correct p q r s\" and \"cross_ratio_correct p q r t\"\n  and \"cross_ratio p q r s = cross_ratio p q r t\"\n  shows \"s = t\"\nproof -\n  from \\<open>cross_ratio_correct p q r s\\<close> and \\<open>cross_ratio_correct p q r t\\<close>\n  have \"proj2_set_Col {p,q,r,s}\" and \"proj2_set_Col {p,q,r,t}\"\n    and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"r \\<noteq> q\" and \"s \\<noteq> p\" and \"t \\<noteq> p\"\n    by (unfold cross_ratio_correct_def) simp_all\n\n  let ?u = \"proj2_rep p\"\n  let ?v = \"proj2_rep q\"\n  let ?i = \"proj2_Col_coeff p q r\"\n  let ?j = \"proj2_Col_coeff p q s\"\n  let ?k = \"proj2_Col_coeff p q t\"\n  from \\<open>proj2_set_Col {p,q,r,s}\\<close> and \\<open>proj2_set_Col {p,q,r,t}\\<close>\n    and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>s \\<noteq> p\\<close> and \\<open>t \\<noteq> p\\<close> and proj2_set_Col_coeff\n  have \"r = proj2_abs (?i *\\<^sub>R ?u + ?v)\"\n    and \"s = proj2_abs (?j *\\<^sub>R ?u + ?v)\"\n    and \"t = proj2_abs (?k *\\<^sub>R ?u + ?v)\"\n    by simp_all\n\n  from \\<open>r \\<noteq> q\\<close> and \\<open>r = proj2_abs (?i *\\<^sub>R ?u + ?v)\\<close>\n  have \"?i \\<noteq> 0\" by (auto simp add: proj2_abs_rep)\n  with \\<open>cross_ratio p q r s = cross_ratio p q r t\\<close>\n  have \"?j = ?k\" by (unfold cross_ratio_def) simp\n  with \\<open>s = proj2_abs (?j *\\<^sub>R ?u + ?v)\\<close> and \\<open>t = proj2_abs (?k *\\<^sub>R ?u + ?v)\\<close>\n  show \"s = t\" by simp\nqed\n\nlemma cltn2_three_point_line:\n  assumes \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"r \\<noteq> q\"\n  and \"proj2_incident p l\" and \"proj2_incident q l\" and \"proj2_incident r l\"\n  and \"apply_cltn2 p C = p\" and \"apply_cltn2 q C = q\" and \"apply_cltn2 r C = r\"\n  and \"proj2_incident s l\"\n  shows \"apply_cltn2 s C = s\" (is \"?sC = s\")\nproof cases\n  assume \"s = p\"\n  with \\<open>apply_cltn2 p C = p\\<close> show \"?sC = s\" by simp\nnext\n  assume \"s \\<noteq> p\"\n\n  let ?pC = \"apply_cltn2 p C\"\n  let ?qC = \"apply_cltn2 q C\"\n  let ?rC = \"apply_cltn2 r C\"\n\n  from \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close> and \\<open>proj2_incident r l\\<close>\n    and \\<open>proj2_incident s l\\<close>\n  have \"proj2_set_Col {p,q,r,s}\" by (unfold proj2_set_Col_def) auto\n  with \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>s \\<noteq> p\\<close> and \\<open>r \\<noteq> q\\<close>\n  have \"cross_ratio_correct p q r s\" by (unfold cross_ratio_correct_def) simp\n  hence \"cross_ratio_correct ?pC ?qC ?rC ?sC\"\n    by (rule cross_ratio_correct_cltn2)\n  with \\<open>?pC = p\\<close> and \\<open>?qC = q\\<close> and \\<open>?rC = r\\<close>\n  have \"cross_ratio_correct p q r ?sC\" by simp\n\n  from \\<open>proj2_set_Col {p,q,r,s}\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>s \\<noteq> p\\<close>\n  have \"cross_ratio ?pC ?qC ?rC ?sC = cross_ratio p q r s\"\n    by (rule cross_ratio_cltn2)\n  with \\<open>?pC = p\\<close> and \\<open>?qC = q\\<close> and \\<open>?rC = r\\<close>\n  have \"cross_ratio p q r ?sC = cross_ratio p q r s\" by simp\n  with \\<open>cross_ratio_correct p q r ?sC\\<close> and \\<open>cross_ratio_correct p q r s\\<close>\n  show \"?sC = s\" by (rule cross_ratio_unique)\nqed\n\nlemma cross_ratio_equal_cltn2:\n  assumes \"cross_ratio_correct p q r s\"\n  and \"cross_ratio_correct (apply_cltn2 p C) (apply_cltn2 q C)\n  (apply_cltn2 r C) t\"\n  (is \"cross_ratio_correct ?pC ?qC ?rC t\")\n  and \"cross_ratio (apply_cltn2 p C) (apply_cltn2 q C) (apply_cltn2 r C) t\n    = cross_ratio p q r s\"\n  shows \"t = apply_cltn2 s C\" (is \"t = ?sC\")\nproof -\n  from \\<open>cross_ratio_correct p q r s\\<close>\n  have \"cross_ratio_correct ?pC ?qC ?rC ?sC\" by (rule cross_ratio_correct_cltn2)\n\n  from \\<open>cross_ratio_correct p q r s\\<close>\n  have \"proj2_set_Col {p,q,r,s}\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"s \\<noteq> p\"\n    by (unfold cross_ratio_correct_def) simp_all\n  hence \"cross_ratio ?pC ?qC ?rC ?sC = cross_ratio p q r s\"\n    by (rule cross_ratio_cltn2)\n  with \\<open>cross_ratio ?pC ?qC ?rC t = cross_ratio p q r s\\<close>\n  have \"cross_ratio ?pC ?qC ?rC t = cross_ratio ?pC ?qC ?rC ?sC\" by simp\n  with \\<open>cross_ratio_correct ?pC ?qC ?rC t\\<close>\n    and \\<open>cross_ratio_correct ?pC ?qC ?rC ?sC\\<close>\n  show \"t = ?sC\" by (rule cross_ratio_unique)\nqed\n\nlemma proj2_Col_distinct_coeff_non_zero:\n  assumes \"proj2_Col p q r\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"r \\<noteq> q\"\n  shows \"proj2_Col_coeff p q r \\<noteq> 0\"\nproof\n  assume \"proj2_Col_coeff p q r = 0\"\n\n  from \\<open>proj2_Col p q r\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close>\n  have \"r = proj2_abs ((proj2_Col_coeff p q r) *\\<^sub>R proj2_rep p + proj2_rep q)\"\n    by (rule proj2_Col_coeff)\n  with \\<open>proj2_Col_coeff p q r = 0\\<close> have \"r = q\" by (simp add: proj2_abs_rep)\n  with \\<open>r \\<noteq> q\\<close> show False ..\nqed\n\nlemma cross_ratio_product:\n  assumes \"proj2_Col p q s\" and \"p \\<noteq> q\" and \"s \\<noteq> p\" and \"s \\<noteq> q\"\n  shows \"cross_ratio p q r s * cross_ratio p q s t = cross_ratio p q r t\"\nproof -\n  from \\<open>proj2_Col p q s\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>s \\<noteq> p\\<close> and \\<open>s \\<noteq> q\\<close>\n  have \"proj2_Col_coeff p q s \\<noteq> 0\" by (rule proj2_Col_distinct_coeff_non_zero)\n  thus \"cross_ratio p q r s * cross_ratio p q s t = cross_ratio p q r t\"\n    by (unfold cross_ratio_def) simp\nqed\n\nlemma cross_ratio_equal_1:\n  assumes \"proj2_Col p q r\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"r \\<noteq> q\"\n  shows \"cross_ratio p q r r = 1\"\nproof -\n  from \\<open>proj2_Col p q r\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>r \\<noteq> q\\<close>\n  have \"proj2_Col_coeff p q r \\<noteq> 0\" by (rule proj2_Col_distinct_coeff_non_zero)\n  thus \"cross_ratio p q r r = 1\" by (unfold cross_ratio_def) simp\nqed\n\nlemma cross_ratio_1_equal:\n  assumes \"cross_ratio_correct p q r s\" and \"cross_ratio p q r s = 1\"\n  shows \"r = s\"\nproof -\n  from \\<open>cross_ratio_correct p q r s\\<close>\n  have \"proj2_set_Col {p,q,r,s}\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"r \\<noteq> q\"\n    by (unfold cross_ratio_correct_def) simp_all\n\n  from \\<open>proj2_set_Col {p,q,r,s}\\<close>\n  have \"proj2_set_Col {p,q,r}\"\n    by (simp add: proj2_subset_Col [of \"{p,q,r}\" \"{p,q,r,s}\"])\n  with \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>r \\<noteq> q\\<close>\n  have \"cross_ratio_correct p q r r\" by (unfold cross_ratio_correct_def) simp\n\n  from \\<open>proj2_set_Col {p,q,r}\\<close>\n  have \"proj2_Col p q r\" by (subst proj2_Col_iff_set_Col)\n  with \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>r \\<noteq> q\\<close>\n  have \"cross_ratio p q r r = 1\" by (simp add: cross_ratio_equal_1)\n  with \\<open>cross_ratio p q r s = 1\\<close>\n  have \"cross_ratio p q r r = cross_ratio p q r s\" by simp\n  with \\<open>cross_ratio_correct p q r r\\<close> and \\<open>cross_ratio_correct p q r s\\<close>\n  show \"r = s\" by (rule cross_ratio_unique)\nqed\n\nlemma cross_ratio_swap_34:\n  shows \"cross_ratio p q s r = 1 / (cross_ratio p q r s)\"\n  by (unfold cross_ratio_def) simp\n\nlemma cross_ratio_swap_13_24:\n  assumes \"cross_ratio_correct p q r s\" and \"r \\<noteq> s\"\n  shows \"cross_ratio r s p q = cross_ratio p q r s\"\nproof -\n  from \\<open>cross_ratio_correct p q r s\\<close>\n  have \"proj2_set_Col {p,q,r,s}\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"s \\<noteq> p\" and \"r \\<noteq> q\"\n    by (unfold cross_ratio_correct_def, simp_all)\n\n  have \"proj2_rep p \\<noteq> 0\" (is \"?u \\<noteq> 0\") and \"proj2_rep q \\<noteq> 0\" (is \"?v \\<noteq> 0\")\n    by (rule proj2_rep_non_zero)+\n\n  have \"p = proj2_abs ?u\" and \"q = proj2_abs ?v\"\n    by (simp_all add: proj2_abs_rep)\n  with \\<open>p \\<noteq> q\\<close> have \"proj2_abs ?u \\<noteq> proj2_abs ?v\" by simp\n\n  let ?i = \"proj2_Col_coeff p q r\"\n  let ?j = \"proj2_Col_coeff p q s\"\n  from \\<open>proj2_set_Col {p,q,r,s}\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>s \\<noteq> p\\<close>\n  have \"r = proj2_abs (?i *\\<^sub>R ?u + ?v)\" (is \"r = proj2_abs ?w\")\n    and \"s = proj2_abs (?j *\\<^sub>R ?u + ?v)\" (is \"s = proj2_abs ?x\")\n    by (simp_all add: proj2_set_Col_coeff)\n  with \\<open>r \\<noteq> s\\<close> have \"?i \\<noteq> ?j\" by auto\n\n  from \\<open>?u \\<noteq> 0\\<close> and \\<open>?v \\<noteq> 0\\<close> and \\<open>proj2_abs ?u \\<noteq> proj2_abs ?v\\<close>\n    and dependent_proj2_abs [of ?u ?v _ 1]\n  have \"?w \\<noteq> 0\" and \"?x \\<noteq> 0\" by auto\n\n  from \\<open>r = proj2_abs (?i *\\<^sub>R ?u + ?v)\\<close> and \\<open>r \\<noteq> q\\<close>\n  have \"?i \\<noteq> 0\" by (auto simp add: proj2_abs_rep)\n\n  have \"?w - ?x = (?i - ?j) *\\<^sub>R ?u\" by (simp add: algebra_simps)\n  with \\<open>?i \\<noteq> ?j\\<close>\n  have \"p = proj2_abs (?w - ?x)\" by (simp add: proj2_abs_mult_rep)\n\n  have \"?j *\\<^sub>R ?w - ?i *\\<^sub>R ?x = (?j - ?i) *\\<^sub>R ?v\" by (simp add: algebra_simps)\n  with \\<open>?i \\<noteq> ?j\\<close>\n  have \"q = proj2_abs (?j *\\<^sub>R ?w - ?i *\\<^sub>R ?x)\" by (simp add: proj2_abs_mult_rep)\n  with \\<open>?w \\<noteq> 0\\<close> and \\<open>?x \\<noteq> 0\\<close> and \\<open>r \\<noteq> s\\<close> and \\<open>?i \\<noteq> 0\\<close> and \\<open>r = proj2_abs ?w\\<close>\n    and \\<open>s = proj2_abs ?x\\<close> and \\<open>p = proj2_abs (?w - ?x)\\<close>\n    and cross_ratio_abs [of ?w ?x \"-1\" \"-?i\" 1 ?j]\n  have \"cross_ratio r s p q = ?j / ?i\" by (simp add: algebra_simps)\n  thus \"cross_ratio r s p q = cross_ratio p q r s\"\n    by (unfold cross_ratio_def [of p q r s], simp)\nqed\n\nlemma cross_ratio_swap_12:\n  assumes \"cross_ratio_correct p q r s\" and \"cross_ratio_correct q p r s\"\n  shows \"cross_ratio q p r s = 1 / (cross_ratio p q r s)\"\nproof cases\n  assume \"r = s\"\n\n  from \\<open>cross_ratio_correct p q r s\\<close>\n  have \"proj2_set_Col {p,q,r,s}\" and \"p \\<noteq> q\" and \"r \\<noteq> p\" and \"r \\<noteq> q\"\n    by (unfold cross_ratio_correct_def) simp_all\n\n  from \\<open>proj2_set_Col {p,q,r,s}\\<close> and \\<open>r = s\\<close>\n  have \"proj2_Col p q r\" by (simp_all add: proj2_Col_iff_set_Col)\n  hence \"proj2_Col q p r\" by (rule proj2_Col_permute)\n  with \\<open>proj2_Col p q r\\<close> and \\<open>p \\<noteq> q\\<close> and \\<open>r \\<noteq> p\\<close> and \\<open>r \\<noteq> q\\<close> and \\<open>r = s\\<close>\n  have \"cross_ratio p q r s = 1\" and \"cross_ratio q p r s = 1\"\n    by (simp_all add: cross_ratio_equal_1)\n  thus \"cross_ratio q p r s = 1 / (cross_ratio p q r s)\" by simp\nnext\n  assume \"r \\<noteq> s\"\n  with \\<open>cross_ratio_correct q p r s\\<close>\n  have \"cross_ratio q p r s = cross_ratio r s q p\"\n    by (simp add: cross_ratio_swap_13_24)\n  also have \"\\<dots> = 1 / (cross_ratio r s p q)\" by (rule cross_ratio_swap_34)\n  also from \\<open>cross_ratio_correct p q r s\\<close> and \\<open>r \\<noteq> s\\<close>\n  have \"\\<dots> = 1 / (cross_ratio p q r s)\" by (simp add: cross_ratio_swap_13_24)\n  finally show \"cross_ratio q p r s = 1 / (cross_ratio p q r s)\" .\nqed\n\nsubsection \"Cartesian subspace of the real projective plane\"\n\ndefinition vector2_append1 :: \"real^2 \\<Rightarrow> real^3\" where\n  \"vector2_append1 v = vector [v$1, v$2, 1]\"\n\nlemma vector2_append1_non_zero: \"vector2_append1 v \\<noteq> 0\"\nproof -\n  have \"(vector2_append1 v)$3 \\<noteq> 0$3\"\n    unfolding vector2_append1_def and vector_def\n    by simp\n  thus \"vector2_append1 v \\<noteq> 0\" by auto\nqed\n\ndefinition proj2_pt :: \"real^2 \\<Rightarrow> proj2\" where\n  \"proj2_pt v \\<equiv> proj2_abs (vector2_append1 v)\"\n\nlemma proj2_pt_scalar:\n  \"\\<exists> c. c \\<noteq> 0 \\<and> proj2_rep (proj2_pt v) = c *\\<^sub>R vector2_append1 v\"\n  unfolding proj2_pt_def\n  by (simp add: proj2_rep_abs2 vector2_append1_non_zero)\n\nabbreviation z_non_zero :: \"proj2 \\<Rightarrow> bool\" where\n  \"z_non_zero p \\<equiv> (proj2_rep p)$3 \\<noteq> 0\"\n\ndefinition cart2_pt :: \"proj2 \\<Rightarrow> real^2\" where\n  \"cart2_pt p \\<equiv>\n  vector [(proj2_rep p)$1 / (proj2_rep p)$3, (proj2_rep p)$2 / (proj2_rep p)$3]\"\n\ndefinition cart2_append1 :: \"proj2 \\<Rightarrow> real^3\" where\n  \"cart2_append1 p \\<equiv>  (1 / ((proj2_rep p)$3)) *\\<^sub>R proj2_rep p\"\n\nlemma cart2_append1_z:\n  assumes \"z_non_zero p\"\n  shows \"(cart2_append1 p)$3 = 1\"\n  using \\<open>z_non_zero p\\<close>\n  by (unfold cart2_append1_def) simp\n\nlemma cart2_append1_non_zero:\n  assumes \"z_non_zero p\"\n  shows \"cart2_append1 p \\<noteq> 0\"\nproof -\n  from \\<open>z_non_zero p\\<close> have \"(cart2_append1 p)$3 = 1\" by (rule cart2_append1_z)\n  thus \"cart2_append1 p \\<noteq> 0\" by (simp add: vec_eq_iff exI [of _ 3])\nqed\n\nlemma proj2_rep_cart2_append1:\n  assumes \"z_non_zero p\"\n  shows \"proj2_rep p = ((proj2_rep p)$3) *\\<^sub>R cart2_append1 p\"\n  using \\<open>z_non_zero p\\<close>\n  by (unfold cart2_append1_def) simp\n\nlemma proj2_abs_cart2_append1:\n  assumes \"z_non_zero p\"\n  shows \"proj2_abs (cart2_append1 p) = p\"\nproof -\n  from \\<open>z_non_zero p\\<close>\n  have \"proj2_abs (cart2_append1 p) = proj2_abs (proj2_rep p)\"\n    by (unfold cart2_append1_def) (simp add: proj2_abs_mult)\n  thus \"proj2_abs (cart2_append1 p) = p\" by (simp add: proj2_abs_rep)\nqed\n\nlemma cart2_append1_inj:\n  assumes \"z_non_zero p\" and \"cart2_append1 p = cart2_append1 q\"\n  shows \"p = q\"\nproof -\n  from \\<open>z_non_zero p\\<close> have \"(cart2_append1 p)$3 = 1\" by (rule cart2_append1_z)\n  with \\<open>cart2_append1 p = cart2_append1 q\\<close>\n  have \"(cart2_append1 q)$3 = 1\" by simp\n  hence \"z_non_zero q\" by (unfold cart2_append1_def) auto\n\n  from \\<open>cart2_append1 p = cart2_append1 q\\<close>\n  have \"proj2_abs (cart2_append1 p) = proj2_abs (cart2_append1 q)\" by simp\n  with \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close>\n  show \"p = q\" by (simp add: proj2_abs_cart2_append1)\nqed\n\nlemma cart2_append1:\n  assumes \"z_non_zero p\"\n  shows \"vector2_append1 (cart2_pt p) = cart2_append1 p\"\n  using \\<open>z_non_zero p\\<close>\n  unfolding vector2_append1_def\n    and cart2_append1_def\n    and cart2_pt_def\n    and vector_def\n  by (simp add: vec_eq_iff forall_3)\n\nlemma cart2_proj2: \"cart2_pt (proj2_pt v) = v\"\nproof -\n  let ?v' = \"vector2_append1 v\"\n  let ?p = \"proj2_pt v\"\n  from proj2_pt_scalar\n  obtain c where \"c \\<noteq> 0\" and \"proj2_rep ?p = c *\\<^sub>R ?v'\" by auto\n  hence \"(cart2_pt ?p)$1 = v$1\" and \"(cart2_pt ?p)$2 = v$2\"\n    unfolding cart2_pt_def and vector2_append1_def and vector_def\n    by simp+\n  thus \"cart2_pt ?p = v\" by (simp add: vec_eq_iff forall_2)\nqed\n\nlemma z_non_zero_proj2_pt: \"z_non_zero (proj2_pt v)\"\nproof -\n  from proj2_pt_scalar\n  obtain c where \"c \\<noteq> 0\" and \"proj2_rep (proj2_pt v) = c *\\<^sub>R (vector2_append1 v)\"\n    by auto\n  from \\<open>proj2_rep (proj2_pt v) = c *\\<^sub>R (vector2_append1 v)\\<close>\n  have \"(proj2_rep (proj2_pt v))$3 = c\"\n    unfolding vector2_append1_def and vector_def\n    by simp\n  with \\<open>c \\<noteq> 0\\<close> show \"z_non_zero (proj2_pt v)\" by simp\nqed\n\nlemma cart2_append1_proj2: \"cart2_append1 (proj2_pt v) = vector2_append1 v\"\nproof -\n  from z_non_zero_proj2_pt\n  have \"cart2_append1 (proj2_pt v) = vector2_append1 (cart2_pt (proj2_pt v))\"\n    by (simp add: cart2_append1)\n  thus \"cart2_append1 (proj2_pt v) = vector2_append1 v\"\n    by (simp add: cart2_proj2)\nqed\n\nlemma proj2_pt_inj: \"inj proj2_pt\"\n  by (simp add: inj_on_inverseI [of UNIV cart2_pt proj2_pt] cart2_proj2)\n\nlemma proj2_cart2:\n  assumes \"z_non_zero p\"\n  shows \"proj2_pt (cart2_pt p) = p\"\nproof -\n  from \\<open>z_non_zero p\\<close>\n  have \"(proj2_rep p)$3 *\\<^sub>R vector2_append1 (cart2_pt p) = proj2_rep p\"\n    unfolding vector2_append1_def and cart2_pt_def and vector_def\n    by (simp add: vec_eq_iff forall_3)\n  with \\<open>z_non_zero p\\<close>\n    and proj2_abs_mult [of \"(proj2_rep p)$3\" \"vector2_append1 (cart2_pt p)\"]\n  have \"proj2_abs (vector2_append1 (cart2_pt p)) = proj2_abs (proj2_rep p)\"\n    by simp\n  thus \"proj2_pt (cart2_pt p) = p\"\n    by (unfold proj2_pt_def) (simp add: proj2_abs_rep)\nqed\n\nlemma cart2_injective:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"cart2_pt p = cart2_pt q\"\n  shows \"p = q\"\nproof -\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close>\n  have \"proj2_pt (cart2_pt p) = p\" and \"proj2_pt (cart2_pt q) = q\"\n    by (simp_all add: proj2_cart2)\n\n  from \\<open>proj2_pt (cart2_pt p) = p\\<close> and \\<open>cart2_pt p = cart2_pt q\\<close>\n  have \"proj2_pt (cart2_pt q) = p\" by simp\n  with \\<open>proj2_pt (cart2_pt q) = q\\<close> show \"p = q\" by simp\nqed\n\nlemma proj2_Col_iff_euclid:\n  \"proj2_Col (proj2_pt a) (proj2_pt b) (proj2_pt c) \\<longleftrightarrow> real_euclid.Col a b c\"\n  (is \"proj2_Col ?p ?q ?r \\<longleftrightarrow> _\")\nproof\n  let ?a' = \"vector2_append1 a\"\n  let ?b' = \"vector2_append1 b\"\n  let ?c' = \"vector2_append1 c\"\n  let ?a'' = \"proj2_rep ?p\"\n  let ?b'' = \"proj2_rep ?q\"\n  let ?c'' = \"proj2_rep ?r\"\n  from proj2_pt_scalar obtain i and j and k where\n    \"i \\<noteq> 0\" and \"?a'' = i *\\<^sub>R ?a'\"\n    and \"j \\<noteq> 0\" and \"?b'' = j *\\<^sub>R ?b'\"\n    and \"k \\<noteq> 0\" and \"?c'' = k *\\<^sub>R ?c'\"\n    by metis\n  hence \"?a' = (1/i) *\\<^sub>R ?a''\"\n    and \"?b' = (1/j) *\\<^sub>R ?b''\"\n    and \"?c' = (1/k) *\\<^sub>R ?c''\"\n    by simp_all\n\n  { assume \"proj2_Col ?p ?q ?r\"\n    then obtain i' and j' and k' where\n      \"i' *\\<^sub>R ?a'' + j' *\\<^sub>R ?b'' + k' *\\<^sub>R ?c'' = 0\" and \"i'\\<noteq>0 \\<or> j'\\<noteq>0 \\<or> k'\\<noteq>0\"\n      unfolding proj2_Col_def\n      by auto\n\n    let ?i'' = \"i * i'\"\n    let ?j'' = \"j * j'\"\n    let ?k'' = \"k * k'\"\n    from \\<open>i\\<noteq>0\\<close> and \\<open>j\\<noteq>0\\<close> and \\<open>k\\<noteq>0\\<close> and \\<open>i'\\<noteq>0 \\<or> j'\\<noteq>0 \\<or> k'\\<noteq>0\\<close>\n    have \"?i''\\<noteq>0 \\<or> ?j''\\<noteq>0 \\<or> ?k''\\<noteq>0\" by simp\n\n    from \\<open>i' *\\<^sub>R ?a'' + j' *\\<^sub>R ?b'' + k' *\\<^sub>R ?c'' = 0\\<close>\n      and \\<open>?a'' = i *\\<^sub>R ?a'\\<close>\n      and \\<open>?b'' = j *\\<^sub>R ?b'\\<close>\n      and \\<open>?c'' = k *\\<^sub>R ?c'\\<close>\n    have \"?i'' *\\<^sub>R ?a' + ?j'' *\\<^sub>R ?b' + ?k'' *\\<^sub>R ?c' = 0\"\n      by (simp add: ac_simps)\n    hence \"(?i'' *\\<^sub>R ?a' + ?j'' *\\<^sub>R ?b' + ?k'' *\\<^sub>R ?c')$3 = 0\"\n      by simp\n    hence \"?i'' + ?j'' + ?k'' = 0\"\n      unfolding vector2_append1_def and vector_def\n      by simp\n\n    have \"(?i'' *\\<^sub>R ?a' + ?j'' *\\<^sub>R ?b' + ?k'' *\\<^sub>R ?c')$1 =\n      (?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c)$1\"\n      and \"(?i'' *\\<^sub>R ?a' + ?j'' *\\<^sub>R ?b' + ?k'' *\\<^sub>R ?c')$2 =\n      (?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c)$2\"\n      unfolding vector2_append1_def and vector_def\n      by simp+\n    with \\<open>?i'' *\\<^sub>R ?a' + ?j'' *\\<^sub>R ?b' + ?k'' *\\<^sub>R ?c' = 0\\<close>\n    have \"?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c = 0\"\n      by (simp add: vec_eq_iff forall_2)\n\n    have \"dep2 (b - a) (c - a)\"\n    proof cases\n      assume \"?k'' = 0\"\n      with \\<open>?i'' + ?j'' + ?k'' = 0\\<close> have \"?j'' = -?i''\" by simp\n      with \\<open>?i''\\<noteq>0 \\<or> ?j''\\<noteq>0 \\<or> ?k''\\<noteq>0\\<close> and \\<open>?k'' = 0\\<close> have \"?i'' \\<noteq> 0\" by simp\n      \n      from \\<open>?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c = 0\\<close>\n        and \\<open>?k'' = 0\\<close> and \\<open>?j'' = -?i''\\<close>\n      have \"?i'' *\\<^sub>R a + (-?i'' *\\<^sub>R b) = 0\" by simp\n      with \\<open>?i'' \\<noteq> 0\\<close> have \"a = b\" by (simp add: algebra_simps)\n      hence \"b - a = 0 *\\<^sub>R (c - a)\" by simp\n      moreover have \"c - a = 1 *\\<^sub>R (c - a)\" by simp\n      ultimately have \"\\<exists> x t s. b - a = t *\\<^sub>R x \\<and> c - a = s *\\<^sub>R x\"\n        by blast\n      thus \"dep2 (b - a) (c - a)\" unfolding dep2_def .\n    next\n      assume \"?k'' \\<noteq> 0\"\n      from \\<open>?i'' + ?j'' + ?k'' = 0\\<close> have \"?i'' = -(?j'' + ?k'')\" by simp\n      with \\<open>?i'' *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c = 0\\<close>\n      have \"-(?j'' + ?k'') *\\<^sub>R a + ?j'' *\\<^sub>R b + ?k'' *\\<^sub>R c = 0\" by simp\n      hence \"?k'' *\\<^sub>R (c - a) = - ?j'' *\\<^sub>R (b - a)\"\n        by (simp add: scaleR_left_distrib\n          scaleR_right_diff_distrib\n          scaleR_left_diff_distrib\n          algebra_simps)\n      hence \"(1/?k'') *\\<^sub>R ?k'' *\\<^sub>R (c - a) = (-?j'' / ?k'') *\\<^sub>R (b - a)\"\n        by simp\n      with \\<open>?k'' \\<noteq> 0\\<close> have \"c - a = (-?j'' / ?k'') *\\<^sub>R (b - a)\" by simp\n      moreover have \"b - a = 1 *\\<^sub>R (b - a)\" by simp\n      ultimately have \"\\<exists> x t s. b - a = t *\\<^sub>R x \\<and> c - a = s *\\<^sub>R x\" by blast\n      thus \"dep2 (b - a) (c - a)\" unfolding dep2_def .\n    qed\n    with Col_dep2 show \"real_euclid.Col a b c\" by auto\n  }\n\n  { assume \"real_euclid.Col a b c\"\n    with Col_dep2 have \"dep2 (b - a) (c - a)\" by auto\n    then obtain x and t and s where \"b - a = t *\\<^sub>R x\" and \"c - a = s *\\<^sub>R x\"\n      unfolding dep2_def\n      by auto\n\n    show \"proj2_Col ?p ?q ?r\"\n    proof cases\n      assume \"t = 0\"\n      with \\<open>b - a = t *\\<^sub>R x\\<close> have \"a = b\" by simp\n      with proj2_Col_coincide show \"proj2_Col ?p ?q ?r\" by simp\n    next\n      assume \"t \\<noteq> 0\"\n\n      from \\<open>b - a = t *\\<^sub>R x\\<close> and \\<open>c - a = s *\\<^sub>R x\\<close>\n      have \"s *\\<^sub>R (b - a) = t *\\<^sub>R (c - a)\" by simp\n      hence \"(s - t) *\\<^sub>R a + (-s) *\\<^sub>R b + t *\\<^sub>R c = 0\"\n        by (simp add: scaleR_right_diff_distrib\n          scaleR_left_diff_distrib\n          algebra_simps)\n      hence \"((s - t) *\\<^sub>R ?a' + (-s) *\\<^sub>R ?b' + t *\\<^sub>R ?c')$1 = 0\"\n        and \"((s - t) *\\<^sub>R ?a' + (-s) *\\<^sub>R ?b' + t *\\<^sub>R ?c')$2 = 0\"\n        unfolding vector2_append1_def and vector_def\n        by (simp_all add: vec_eq_iff)\n      moreover have \"((s - t) *\\<^sub>R ?a' + (-s) *\\<^sub>R ?b' + t *\\<^sub>R ?c')$3 = 0\"\n        unfolding vector2_append1_def and vector_def\n        by simp\n      ultimately have \"(s - t) *\\<^sub>R ?a' + (-s) *\\<^sub>R ?b' + t *\\<^sub>R ?c' = 0\"\n        by (simp add: vec_eq_iff forall_3)\n      with \\<open>?a' = (1/i) *\\<^sub>R ?a''\\<close>\n        and \\<open>?b' = (1/j) *\\<^sub>R ?b''\\<close>\n        and \\<open>?c' = (1/k) *\\<^sub>R ?c''\\<close>\n      have \"((s - t)/i) *\\<^sub>R ?a'' + (-s/j) *\\<^sub>R ?b'' + (t/k) *\\<^sub>R ?c'' = 0\"\n        by simp\n      moreover from \\<open>t \\<noteq> 0\\<close> and \\<open>k \\<noteq> 0\\<close> have \"t/k \\<noteq> 0\" by simp\n      ultimately show \"proj2_Col ?p ?q ?r\"\n        unfolding proj2_Col_def\n        by blast\n    qed\n  }\nqed\n\nlemma proj2_Col_iff_euclid_cart2:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"z_non_zero r\"\n  shows\n  \"proj2_Col p q r \\<longleftrightarrow> real_euclid.Col (cart2_pt p) (cart2_pt q) (cart2_pt r)\"\n  (is \"_ \\<longleftrightarrow> real_euclid.Col ?a ?b ?c\")\nproof -\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close> and \\<open>z_non_zero r\\<close>\n  have \"proj2_pt ?a = p\" and \"proj2_pt ?b = q\" and \"proj2_pt ?c = r\"\n    by (simp_all add: proj2_cart2)\n  with proj2_Col_iff_euclid [of ?a ?b ?c]\n  show \"proj2_Col p q r \\<longleftrightarrow> real_euclid.Col ?a ?b ?c\" by simp\nqed\n\nlemma euclid_Col_cart2_incident:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"z_non_zero r\" and \"p \\<noteq> q\"\n  and \"proj2_incident p l\" and \"proj2_incident q l\"\n  and \"real_euclid.Col (cart2_pt p) (cart2_pt q) (cart2_pt r)\"\n  (is \"real_euclid.Col ?cp ?cq ?cr\")\n  shows \"proj2_incident r l\"\nproof -\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close> and \\<open>z_non_zero r\\<close>\n    and \\<open>real_euclid.Col ?cp ?cq ?cr\\<close>\n  have \"proj2_Col p q r\" by (subst proj2_Col_iff_euclid_cart2, simp_all)\n  hence \"proj2_set_Col {p,q,r}\" by (simp add: proj2_Col_iff_set_Col)\n  then obtain m where\n    \"proj2_incident p m\" and \"proj2_incident q m\" and \"proj2_incident r m\"\n    by (unfold proj2_set_Col_def, auto)\n\n  from \\<open>p \\<noteq> q\\<close> and \\<open>proj2_incident p l\\<close> and \\<open>proj2_incident q l\\<close>\n    and \\<open>proj2_incident p m\\<close> and \\<open>proj2_incident q m\\<close> and proj2_incident_unique\n  have \"l = m\" by auto\n  with \\<open>proj2_incident r m\\<close> show \"proj2_incident r l\" by simp\nqed\n\nlemma euclid_B_cart2_common_line:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"z_non_zero r\"\n  and \"B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\"\n  (is \"B\\<^sub>\\<real> ?cp ?cq ?cr\")\n  shows \"\\<exists> l. proj2_incident p l \\<and> proj2_incident q l \\<and> proj2_incident r l\"\nproof -\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close> and \\<open>z_non_zero r\\<close>\n    and \\<open>B\\<^sub>\\<real> ?cp ?cq ?cr\\<close> and proj2_Col_iff_euclid_cart2\n  have \"proj2_Col p q r\" by (unfold real_euclid.Col_def) simp\n  hence \"proj2_set_Col {p,q,r}\" by (simp add: proj2_Col_iff_set_Col)\n  thus \"\\<exists> l. proj2_incident p l \\<and> proj2_incident q l \\<and> proj2_incident r l\"\n    by (unfold proj2_set_Col_def) simp\nqed\n\nlemma cart2_append1_between:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"z_non_zero r\"\n  shows \"B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\n  \\<longleftrightarrow> (\\<exists> k\\<ge>0. k \\<le> 1\n  \\<and> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p)\"\nproof -\n  let ?cp = \"cart2_pt p\"\n  let ?cq = \"cart2_pt q\"\n  let ?cr = \"cart2_pt r\"\n  let ?cp1 = \"vector2_append1 ?cp\"\n  let ?cq1 = \"vector2_append1 ?cq\"\n  let ?cr1 = \"vector2_append1 ?cr\"\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close> and \\<open>z_non_zero r\\<close>\n  have \"?cp1 = cart2_append1 p\"\n    and \"?cq1 = cart2_append1 q\"\n    and \"?cr1 = cart2_append1 r\"\n    by (simp_all add: cart2_append1)\n\n  have \"\\<forall> k. ?cq - ?cp = k *\\<^sub>R (?cr - ?cp) \\<longleftrightarrow> ?cq = k *\\<^sub>R ?cr + (1 - k) *\\<^sub>R ?cp\"\n    by (simp add: algebra_simps)\n  hence \"\\<forall> k. ?cq - ?cp = k *\\<^sub>R (?cr - ?cp)\n    \\<longleftrightarrow> ?cq1 = k *\\<^sub>R ?cr1 + (1 - k) *\\<^sub>R ?cp1\"\n    unfolding vector2_append1_def and vector_def\n    by (simp add: vec_eq_iff forall_2 forall_3)\n  with \\<open>?cp1 = cart2_append1 p\\<close>\n    and \\<open>?cq1 = cart2_append1 q\\<close>\n    and \\<open>?cr1 = cart2_append1 r\\<close>\n  have \"\\<forall> k. ?cq - ?cp = k *\\<^sub>R (?cr - ?cp)\n    \\<longleftrightarrow> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\n    by simp\n  thus \"B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\n    \\<longleftrightarrow> (\\<exists> k\\<ge>0. k \\<le> 1\n    \\<and> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p)\"\n    by (unfold real_euclid_B_def) simp\nqed\n\nlemma cart2_append1_between_right_strict:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"z_non_zero r\"\n  and \"B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\" and \"q \\<noteq> r\"\n  shows \"\\<exists> k\\<ge>0. k < 1\n  \\<and> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\nproof -\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close> and \\<open>z_non_zero r\\<close>\n    and \\<open>B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\\<close> and cart2_append1_between\n  obtain k where \"k \\<ge> 0\" and \"k \\<le> 1\"\n    and \"cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\n    by auto\n\n  have \"k \\<noteq> 1\"\n  proof\n    assume \"k = 1\"\n    with \\<open>cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\\<close>\n    have \"cart2_append1 q = cart2_append1 r\" by simp\n    with \\<open>z_non_zero q\\<close> have \"q = r\" by (rule cart2_append1_inj)\n    with \\<open>q \\<noteq> r\\<close> show False ..\n  qed\n  with \\<open>k \\<le> 1\\<close> have \"k < 1\" by simp\n  with \\<open>k \\<ge> 0\\<close>\n    and \\<open>cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\\<close>\n  show \"\\<exists> k\\<ge>0. k < 1\n    \\<and> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\n    by (simp add: exI [of _ k])\nqed\n\nlemma cart2_append1_between_strict:\n  assumes \"z_non_zero p\" and \"z_non_zero q\" and \"z_non_zero r\"\n  and \"B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\" and \"q \\<noteq> p\" and \"q \\<noteq> r\"\n  shows \"\\<exists> k>0. k < 1\n  \\<and> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\nproof -\n  from \\<open>z_non_zero p\\<close> and \\<open>z_non_zero q\\<close> and \\<open>z_non_zero r\\<close>\n    and \\<open>B\\<^sub>\\<real> (cart2_pt p) (cart2_pt q) (cart2_pt r)\\<close> and \\<open>q \\<noteq> r\\<close>\n    and cart2_append1_between_right_strict [of p q r]\n  obtain k where \"k \\<ge> 0\" and \"k < 1\"\n    and \"cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\n    by auto\n\n  have \"k \\<noteq> 0\"\n  proof\n    assume \"k = 0\"\n    with \\<open>cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\\<close>\n    have \"cart2_append1 q = cart2_append1 p\" by simp\n    with \\<open>z_non_zero q\\<close> have \"q = p\" by (rule cart2_append1_inj)\n    with \\<open>q \\<noteq> p\\<close> show False ..\n  qed\n  with \\<open>k \\<ge> 0\\<close> have \"k > 0\" by simp\n  with \\<open>k < 1\\<close>\n    and \\<open>cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\\<close>\n  show \"\\<exists> k>0. k < 1\n    \\<and> cart2_append1 q = k *\\<^sub>R cart2_append1 r + (1 - k) *\\<^sub>R cart2_append1 p\"\n    by (simp add: exI [of _ k])\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Tarskis_Geometry/Projective.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7758065117331241}}
{"text": "theory P25 imports Main begin\n\ndatatype bintree = Tip | Node bintree nat bintree\n\nfun tge :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bool\" where\n\"tge n Tip = True\" |\n\"tge n (Node l m r) = ((tge n l) \\<and> (n \\<ge> m) \\<and> (tge n r))\"\n\nfun tle :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bool\" where\n\"tle n Tip = True\" |\n\"tle n (Node l m r) = ((tle n l) \\<and> (n \\<le> m) \\<and> (tle n r))\"\n\nfun tsorted :: \"bintree \\<Rightarrow> bool\" where\n\"tsorted Tip = True\" |\n\"tsorted (Node l m r) = ((tsorted l) \\<and> (tsorted r) \\<and> (tge m l) \\<and> (tle m r))\"\n\nfun ins :: \"nat \\<Rightarrow> bintree \\<Rightarrow> bintree\" where\n\"ins n Tip = (Node Tip n Tip)\" |\n\"ins n (Node l m r) = (if (n \\<le> m) then (Node (ins n l) m r) else (Node l m (ins n r)))\"\n\ndefinition tree_of :: \"nat list \\<Rightarrow> bintree\" where\n\"tree_of xs = (foldr ins xs Tip)\"\n\nlemma tge_inva: \"tge x xt \\<Longrightarrow> a \\<le> x \\<Longrightarrow> tge x (ins a xt)\"\n  apply (induct xt)\n   apply auto\n  done\n\nlemma tle_inva: \"tle x xt \\<Longrightarrow> \\<not>(a \\<le> x) \\<Longrightarrow> tle x (ins a xt)\"\n  apply (induct xt)\n   apply auto\n  done\n\n\n\ntheorem [simp]: \"tsorted (tree_of xs)\"\n  apply (induct xs)\n   apply (auto simp add: tree_of_def)\n  done\n\nprimrec count :: \"nat list => nat => nat\" where\n\"count [] y = 0\" | \n\"count (x#xs) y = (if x=y then Suc(count xs y) else count xs y)\"\n\nlemma [simp]: \"count (a # xs) x = (count xs x) + (if (x=a) then 1 else 0)\"\n  apply (induct xs)\n   apply auto\n  done\n\nfun tcount :: \"bintree \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"tcount Tip n = 0\" |\n\"tcount (Node l x r) n = (tcount l n) + (tcount r n) + (if (x=n) then 1 else 0)\"\n\nlemma [simp]: \"tcount (ins a xs) x = (tcount xs x) + (if x=a then 1 else 0)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma [simp]: \"tcount (tree_of (a # xs)) x = (tcount (tree_of xs) x + (if (x=a) then 1 else 0))\"\n  apply (induct xs)\n   apply (auto simp add: tree_of_def)\n  done\n\ntheorem \"tcount (tree_of xs) x = count xs x\"\nproof (induct xs)\ncase Nil\nthen show ?case by (simp add: tree_of_def)\nnext\n  case (Cons a xs)\n  then show ?case by simp\nqed\n\nprimrec le :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"le n Nil = True\" |\n\"le n (x # xs) = (n \\<le> x \\<and> le n xs)\"\n\nprimrec ge :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"ge n Nil = True\" | \n\"ge n (x # xs) = (x \\<le> n \\<and> ge n xs)\"\n\nprimrec sorted :: \"nat list \\<Rightarrow> bool\" where\n\"sorted [] = True\"\n| \"sorted (x#xs) = (le x xs & sorted xs)\"\n\nlemma [simp]: \"le x (a@b) = (le x a \\<and> le x b)\"\n  apply (induct a)\n  apply auto\n  done\n\nlemma [simp]: \"ge x (a@b) = (ge x a \\<and> ge x b)\"\n  apply (induct a)\n  apply auto\n  done\n\nlemma [simp]: \"x \\<le> y \\<Longrightarrow> le y xs \\<Longrightarrow> le x xs\"\n  apply (induct xs)\n  apply auto\n  done\n\nlemma [simp]: \"sorted (a@x#b) = (sorted a \\<and> sorted b \\<and> ge x a \\<and> le x b)\"\n  apply (induct a)\n  apply auto\n  done\n\nfun list_of :: \"bintree \\<Rightarrow> nat list\" where\n\"list_of Tip = Nil\" |\n\"list_of (Node l x r) = (list_of l) @ [x] @ (list_of r)\"\n\nlemma [simp]: \"ge n (list_of t) = tge n t\"\n  apply (induct t)\n  apply auto\n  done\n\nlemma [simp]: \"le n (list_of t) = tle n t\"\n  apply (induct t)\n   apply auto\n  done\n\nlemma [simp]: \"sorted (list_of t) = tsorted t\"\n  apply (induct t)\n  apply auto\n  done\n\ntheorem \"sorted (list_of (tree_of xs))\"\n  apply (induct xs)\n   apply (auto simp add: tree_of_def)\n  done\n\nlemma count_append [simp]: \"count (a@b) n = count a n + count b n\"\n  apply (induct a)\n  apply auto\n  done\n\nlemma [simp]: \"count (list_of b) n = tcount b n\"\n  apply (induct b)\n  apply auto\n  done\n\ntheorem \"count (list_of (tree_of xs)) n = count xs n\"\n  apply (induct xs)\n   apply (auto simp add: tree_of_def)\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P25.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.8479677545357568, "lm_q1q2_score": 0.7758065064604555}}
{"text": "(*\n  File:    Descartes_Sign_Rule.thy\n  Author:  Manuel Eberl <eberlm@in.tum.de>\n\n  Descartes' Rule of Signs, which relates the number of positive real roots of a polynomial\n  with the number of sign changes in its coefficient list.\n*)\nsection \\<open>Sign changes and Descartes' Rule of Signs\\<close>\n\ntheory Descartes_Sign_Rule\nimports \n  Complex_Main\n  \"HOL-Computational_Algebra.Polynomial\"\nbegin\n\n\n\nlemma filter_dropWhile: \n  \"filter (\\<lambda>x. \\<not>P x) (dropWhile P xs) = filter (\\<lambda>x. \\<not>P x) xs\"\n  by (induction xs) simp_all\n\n\nsubsection \\<open>Polynomials\\<close> \n\ntext\\<open>\n  A real polynomial whose leading and constant coefficients have opposite\n  non-zero signs must have a positive root.\n\\<close>\nlemma pos_root_exI:\n  assumes \"poly p 0 * lead_coeff p < (0 :: real)\"\n  obtains x where \"x > 0\" \"poly p x = 0\"\nproof -\n  have P: \"\\<exists>x>0. poly p x = (0::real)\" if \"lead_coeff p > 0\" \"poly p 0 < 0\" for p\n  proof -\n    note that(1)\n    also from poly_pinfty_gt_lc[OF \\<open>lead_coeff p > 0\\<close>] obtain x0 \n      where \"\\<And>x. x \\<ge> x0 \\<Longrightarrow> poly p x \\<ge> lead_coeff p\" by auto\n    hence \"poly p (max x0 1) \\<ge> lead_coeff p\" by auto\n    finally have \"poly p (max x0 1) > 0\" .\n    with that have \"\\<exists>x. x > 0 \\<and> x < max x0 1 \\<and> poly p x = 0\"\n      by (intro poly_IVT mult_neg_pos) auto\n    thus \"\\<exists>x>0. poly p x = 0\"  by auto\n  qed\n\n  show ?thesis\n  proof (cases \"lead_coeff p > 0\")\n    case True\n    with assms have \"poly p 0 < 0\" \n      by (auto simp: mult_less_0_iff)\n    from P[OF True this] that show ?thesis \n      by blast\n  next\n    case False\n    from False assms have \"poly (-p) 0 < 0\" \n      by (auto simp: mult_less_0_iff)\n    moreover from assms have \"p \\<noteq> 0\"\n      by auto\n    with False have \"lead_coeff (-p) > 0\" \n      by (cases rule: linorder_cases[of \"lead_coeff p\" 0]) \n         (simp_all add:)\n    ultimately show ?thesis using that P[of \"-p\"] by auto\n  qed\nqed\n\ntext \\<open>\n  Substitute $X$ with $aX$ in a polynomial $p(X)$. This turns all the $X - a$ factors in $p$\n  into factors of the form $X - 1$.\n\\<close>\ndefinition reduce_root where\n  \"reduce_root a p = pcompose p [:0, a:]\"\n\nlemma reduce_root_pCons: \n  \"reduce_root a (pCons c p) = pCons c (smult a (reduce_root a p))\"\n  by (simp add: reduce_root_def pcompose_pCons)\n\nlemma reduce_root_nonzero [simp]: \n  \"a \\<noteq> 0 \\<Longrightarrow> p \\<noteq> 0 \\<Longrightarrow> reduce_root a p \\<noteq> (0 :: 'a :: idom poly)\"\n  unfolding reduce_root_def using pcompose_eq_0[of p \"[:0, a:]\"] \n  by auto\n\n\nsubsection \\<open>List of partial sums\\<close>\n\ntext \\<open>\n  We first define, for a given list, the list of accumulated partial sums from left to right: \n  the list @{term \"psums xs\"} has as its $i$-th entry $\\sum_{j=0}^i \\mathrm{xs}_i$.\n\\<close>\n\nfun psums where\n  \"psums [] = []\"\n| \"psums [x] = [x]\"\n| \"psums (x#y#xs) = x # psums ((x+y) # xs)\"\n\nlemma length_psums [simp]: \"length (psums xs) = length xs\"\n  by (induction xs rule: psums.induct) simp_all\n\nlemma psums_Cons: \n  \"psums (x#xs) = (x :: 'a :: semigroup_add) # map ((+) x) (psums xs)\"\n  by (induction xs rule: psums.induct) (simp_all add: algebra_simps)\n\nlemma last_psums: \n  \"(xs :: 'a :: monoid_add list) \\<noteq> [] \\<Longrightarrow> last (psums xs) = sum_list xs\"\n  by (induction xs rule: psums.induct) \n     (auto simp add: add.assoc [symmetric] psums_Cons o_def)\n\nlemma psums_0_Cons [simp]: \n  \"psums (0#xs :: 'a :: monoid_add list) = 0 # psums xs\"\n  by (induction xs rule: psums.induct) (simp_all add: algebra_simps)\n\nlemma map_uminus_psums: \n  fixes xs :: \"'a :: ab_group_add list\"\n  shows \"map uminus (psums xs) = psums (map uminus xs)\"\n  by (induction xs rule: psums.induct) (simp_all)\n\nlemma psums_replicate_0_append:\n  \"psums (replicate n (0 :: 'a :: monoid_add) @ xs) = \n     replicate n 0 @ psums xs\"\n  by (induction n) (simp_all add: psums_Cons op_plus_0)\n\nlemma psums_nth: \"n < length xs \\<Longrightarrow> psums xs ! n = (\\<Sum>i\\<le>n. xs ! i)\"\nproof (induction xs arbitrary: n rule: psums.induct[case_names Nil sng rec])\n  case (rec x y xs n)\n  show ?case\n  proof (cases n)\n    case (Suc m)\n    from Suc have \"psums (x # y # xs) ! n = psums ((x+y) # xs) ! m\" by simp\n    also from rec.prems Suc have \"\\<dots> = (\\<Sum>i\\<le>m. ((x+y) # xs) ! i)\" \n      by (intro rec.IH) simp_all\n    also have \"\\<dots> = x + y + (\\<Sum>i=1..m. (y#xs) ! i)\"\n      by (auto simp: atLeast0AtMost [symmetric] sum.atLeast_Suc_atMost[of 0])\n    also have \"(\\<Sum>i=1..m. (y#xs) ! i) = (\\<Sum>i=Suc 1..Suc m. (x#y#xs) ! i)\"\n      by (subst sum.shift_bounds_cl_Suc_ivl) simp\n    also from Suc have \"x + y + \\<dots> = (\\<Sum>i\\<le>n. (x#y#xs) ! i)\"\n      by (auto simp: atLeast0AtMost [symmetric] sum.atLeast_Suc_atMost add_ac)\n    finally show ?thesis .\n  qed simp\nqed simp_all\n\n\nsubsection \\<open>Sign changes in a list\\<close>\n\ntext \\<open>\n  Next, we define the number of sign changes in a sequence. Intuitively, this is the number \n  of times that, when passing through the list, a sign change between one element and the next \n  element occurs (while ignoring all zero entries).\n\n  We implement this by filtering all zeros from the list of signs, removing all adjacent equal \n  elements and taking the length of the resulting list minus one.\n\\<close>\ndefinition sign_changes :: \"('a :: {sgn,zero} list) \\<Rightarrow> nat\" where\n  \"sign_changes xs = length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map sgn xs))) - 1\"\n\nlemma sign_changes_Nil [simp]: \"sign_changes [] = 0\" \n  by (simp add: sign_changes_def)\n\nlemma sign_changes_singleton [simp]: \"sign_changes [x] = 0\" \n  by (simp add: sign_changes_def)\n\nlemma sign_changes_cong:\n  assumes \"map sgn xs = map sgn ys\"\n  shows   \"sign_changes xs = sign_changes ys\"\n  using assms unfolding sign_changes_def by simp\n\nlemma sign_changes_Cons_ge: \"sign_changes (x # xs) \\<ge> sign_changes xs\"\n  unfolding sign_changes_def by (simp add: remdups_adj_Cons split: list.split)\n\nlemma sign_changes_Cons_Cons_different: \n  fixes x y :: \"'a :: linordered_idom\"\n  assumes \"x * y < 0\"\n  shows \"sign_changes (x # y # xs) = 1 + sign_changes (y # xs)\"\nproof -\n  from assms have \"sgn x = -1 \\<and> sgn y = 1 \\<or> sgn x = 1 \\<and> sgn y = -1\"\n    by (auto simp: mult_less_0_iff)\n  thus ?thesis by (fastforce simp: sign_changes_def)\nqed\n\nlemma sign_changes_Cons_Cons_same: \n  fixes x y :: \"'a :: linordered_idom\"\n  shows \"x * y > 0 \\<Longrightarrow> sign_changes (x # y # xs) = sign_changes (y # xs)\"\n  by (subst (asm) zero_less_mult_iff) (fastforce simp: sign_changes_def)\n\nlemma sign_changes_0_Cons [simp]: \n  \"sign_changes (0 # xs :: 'a :: idom_abs_sgn list) = sign_changes xs\"\n  by (simp add: sign_changes_def)\n\nlemma sign_changes_two: \n  fixes x y :: \"'a :: linordered_idom\"\n  shows \"sign_changes [x,y] = \n           (if x > 0 \\<and> y < 0 \\<or> x < 0 \\<and> y > 0 then 1 else 0)\"\n  by (auto simp: sgn_if sign_changes_def mult_less_0_iff)\n\nlemma sign_changes_induct [case_names nil sing zero nonzero]:\n  assumes \"P []\" \"\\<And>x. P [x]\" \"\\<And>xs. P xs \\<Longrightarrow> P (0#xs)\"\n          \"\\<And>x y xs. x \\<noteq> 0 \\<Longrightarrow> P ((x + y) # xs) \\<Longrightarrow> P (x # y # xs)\"\n  shows   \"P xs\"\nproof (induction \"length xs\" arbitrary: xs rule: less_induct)\n  case (less xs)\n  show ?case\n  proof (cases xs rule: psums.cases)\n    fix x y xs' assume \"xs = x # y # xs'\"\n    with assms less show ?thesis by (cases \"x = 0\") auto\n  qed (insert less assms, auto)\nqed \n\nlemma sign_changes_filter: \n  fixes xs :: \"'a :: linordered_idom list\"\n  shows \"sign_changes (filter (\\<lambda>x. x \\<noteq> 0) xs) = sign_changes xs\"\n  by (simp add: sign_changes_def filter_map o_def sgn_0_0)\n\nlemma sign_changes_Cons_Cons_0: \n  fixes xs :: \"'a :: linordered_idom list\"\n  shows \"sign_changes (x # 0 # xs) = sign_changes (x # xs)\"\n  by (subst (1 2) sign_changes_filter [symmetric]) simp_all\n\nlemma sign_changes_uminus: \n  fixes xs :: \"'a :: linordered_idom list\"\n  shows   \"sign_changes (map uminus xs) = sign_changes xs\"\nproof -\n  have \"sign_changes (map uminus xs) = \n          length (remdups_adj [x\\<leftarrow>map sgn (map uminus xs) . x \\<noteq> 0]) - 1\" \n   unfolding sign_changes_def ..\n  also have \"map sgn (map uminus xs) = map uminus (map sgn xs)\" \n    by (auto simp: sgn_minus)\n  also have \"remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) \\<dots>) = \n                 map uminus (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map sgn xs)))\"\n    by (subst filter_map, subst remdups_adj_map_injective) \n       (simp_all add: o_def)\n  also have \"length \\<dots> - 1 = sign_changes xs\" by (simp add: sign_changes_def)\n  finally show ?thesis .\nqed\n\nlemma sign_changes_replicate: \"sign_changes (replicate n x) = 0\"\n  by (simp add: sign_changes_def remdups_adj_replicate filter_replicate)\n\nlemma sign_changes_decompose:\n  assumes \"x \\<noteq> (0 :: 'a :: linordered_idom)\"\n  shows   \"sign_changes (xs @ x # ys) = \n             sign_changes (xs @ [x]) + sign_changes (x # ys)\"\nproof -\n  have \"sign_changes (xs @ x # ys) = \n            length (remdups_adj ([x\\<leftarrow>map sgn xs . x \\<noteq> 0] @ \n                      sgn x # [x\\<leftarrow>map sgn ys . x \\<noteq> 0])) - 1\"\n    by (simp add: sgn_0_0 assms sign_changes_def)\n  also have \"\\<dots> = sign_changes (xs @ [x]) + sign_changes (x # ys)\"\n    by (subst remdups_adj_append) (simp add: sign_changes_def assms sgn_0_0)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  If the first and the last entry of a list are non-zero, its number of sign changes is even \n  if and only if the first and the last element have the same sign. This will be important \n  later to establish the base case of Descartes' Rule. (if there are no positive roots, \n  the number of sign changes is even)\n\\<close>\nlemma even_sign_changes_iff:\n  assumes \"xs \\<noteq> ([] :: 'a :: linordered_idom list)\" \"hd xs \\<noteq> 0\" \"last xs \\<noteq> 0\"\n  shows   \"even (sign_changes xs) \\<longleftrightarrow> sgn (hd xs) = sgn (last xs)\"\nusing assms\nproof (induction \"length xs\" arbitrary: xs rule: less_induct)\n  case (less xs)\n  show ?case\n  proof (cases xs)\n    case (Cons x xs')\n    note x = this\n    show ?thesis\n    proof (cases xs')\n      case (Cons y xs'')\n      note y = this\n      show ?thesis\n      proof (rule linorder_cases[of \"x*y\" 0])\n        assume xy: \"x*y = 0\"\n        with x y less(1,3,4) show ?thesis by (auto simp: sign_changes_Cons_Cons_0)\n      next\n        assume xy: \"x*y > 0\"\n        with less(1,4) show ?thesis\n          by (auto simp add: x y sign_changes_Cons_Cons_same zero_less_mult_iff)\n      next\n        assume xy: \"x*y < 0\"\n        moreover from xy have \"sgn x = - sgn y\" by (auto simp: mult_less_0_iff)\n        moreover have \"even (sign_changes (y # xs'')) \\<longleftrightarrow> \n                         sgn (hd (y # xs'')) = sgn (last (y # xs''))\"\n          using xy less.prems by (intro less) (auto simp: x y)\n        moreover from xy less.prems \n          have \"sgn y = sgn (last xs) \\<longleftrightarrow> -sgn y \\<noteq> sgn (last xs)\"\n          by (auto simp: sgn_if)\n        ultimately show ?thesis by (auto simp: sign_changes_Cons_Cons_different x y)\n      qed\n    qed (auto simp: x)\n  qed (insert less.prems, simp_all)\nqed\n\n\nsubsection \\<open>Arthan's lemma\\<close>\n\ncontext\nbegin\n\ntext \\<open>\n  We first prove an auxiliary lemma that allows us to assume w.l.o.g. that the first element of \n  the list is non-negative, similarly to what Arthan does in his proof.\n\\<close>\nprivate lemma arthan_wlog [consumes 3, case_names nonneg lift]:\n  fixes xs :: \"'a :: linordered_idom list\"\n  assumes \"xs \\<noteq> []\" \"last xs \\<noteq> 0\" \"x + y + sum_list xs = 0\"\n  assumes \"\\<And>x y xs. xs \\<noteq> [] \\<Longrightarrow> last xs \\<noteq> 0 \\<Longrightarrow> \n               x + y + sum_list xs = 0 \\<Longrightarrow> x \\<ge> 0 \\<Longrightarrow> P x y xs\"\n  assumes \"\\<And>x y xs. xs \\<noteq> [] \\<Longrightarrow> P x y xs \\<Longrightarrow> P (-x) (-y) (map uminus xs)\"\n  shows   \"P x y xs\"\nproof (cases \"x \\<ge> 0\")\n  assume x: \"\\<not>(x \\<ge> 0)\"\n  from assms have \"map uminus xs \\<noteq> []\" by simp\n  moreover from x assms(1,2,3) have\"P (-x) (-y) (map uminus xs)\"\n    using uminus_sum_list_map[of \"\\<lambda>x. x\" xs, symmetric]\n    by (intro assms) (auto simp: last_map algebra_simps o_def neg_eq_iff_add_eq_0)\n  ultimately have \"P (- (-x)) (- (-y)) (map uminus (map uminus xs))\" by (rule assms)\n  thus ?thesis by (simp add: o_def)\nqed (simp_all add: assms)\n\ntext \\<open>\n  We now show that the $\\alpha$ and $\\beta$ in Arthan's proof have the necessary properties:\n  their difference is non-negative and even.\n\\<close>\nprivate lemma arthan_aux1:\n  fixes xs :: \"'a :: {linordered_idom} list\"\n  assumes \"xs \\<noteq> []\" \"last xs \\<noteq> 0\" \"x + y + sum_list xs = 0\"\n  defines \"v \\<equiv> \\<lambda>xs. int (sign_changes xs)\"\n  shows \"v (x # y # xs) - v ((x + y) # xs) \\<ge> \n             v (psums (x # y # xs)) - v (psums ((x + y) # xs)) \\<and> \n         even (v (x # y # xs) - v ((x + y) # xs) - \n                  (v (psums (x # y # xs)) - v (psums ((x + y) # xs))))\"\nusing assms(1-3)\nproof (induction rule: arthan_wlog)\n  have uminus_v: \"v (map uminus xs) = v xs\" for xs by (simp add: v_def sign_changes_uminus)\n\n  case (lift x y xs)\n  note lift(2)\n  also have \"v (psums (x#y#xs)) - v (psums ((x+y)#xs)) =\n                 v (psums (- x # - y # map uminus xs)) - \n                 v (psums ((- x + - y) # map uminus xs))\"\n    by (subst (1 2) uminus_v [symmetric]) (simp add: map_uminus_psums)\n  also have \"v (x # y # xs) - v ((x + y) # xs) = \n                 v (-x # -y # map uminus xs) - v ((-x + -y) # map uminus xs)\"\n    by (subst (1 2) uminus_v [symmetric]) simp\n  finally show ?case .\nnext\n  case (nonneg x y xs)\n  define p where \"p = (LEAST n. xs ! n \\<noteq> 0)\"\n  define xs1 :: \"'a list\" where \"xs1 = replicate p 0\"\n  define xs2 where \"xs2 = drop (Suc p) xs\"\n  from nonneg have \"xs ! (length xs - 1) \\<noteq> 0\" by (simp add: last_conv_nth)\n  hence p_nz: \"xs ! p \\<noteq> 0\" unfolding p_def by (rule LeastI)\n  {\n    fix q assume \"q < p\" hence \"xs ! q = 0\"\n      using Least_le[of \"\\<lambda>n. xs ! n \\<noteq> 0\" q] unfolding p_def by force\n  } note less_p_zero = this\n  from Least_le[of \"\\<lambda>n. xs ! n \\<noteq> 0\" \"length xs - 1\"] nonneg \n    have \"p \\<le> length xs - 1\" unfolding p_def by (auto simp: last_conv_nth)\n  with nonneg have p_less_length: \"p < length xs\" by (cases xs) simp_all\n\n  from p_less_length less_p_zero have \"take p xs = replicate p 0\" \n    by (subst list_eq_iff_nth_eq) auto\n  with p_less_length have xs_decompose: \"xs = xs1 @ xs ! p # xs2\" \n    unfolding xs1_def xs2_def\n    by (subst append_take_drop_id [of p, symmetric], \n        subst Cons_nth_drop_Suc) simp_all\n\n  have v_decompose: \"v (xs' @ xs) = v (xs' @ [xs ! p]) + v (xs ! p # xs2)\" for xs'\n  proof -\n    have \"xs' @ xs = (xs' @ xs1) @ xs ! p # xs2\" by (subst xs_decompose) simp\n    also have \"v \\<dots> = v (xs' @ [xs ! p]) + v (xs ! p # xs2)\" unfolding v_def\n      by (subst sign_changes_decompose[OF p_nz], \n          subst (1 2 3 4) sign_changes_filter [symmetric]) (simp_all add: xs1_def)\n    finally show ?thesis .\n  qed\n\n  have psums_decompose: \"psums xs = replicate p 0 @ psums (xs!p # xs2)\" \n    by (subst xs_decompose) (simp add: xs1_def psums_replicate_0_append)\n  have v_psums_decompose: \"sign_changes (xs' @ psums xs) = sign_changes (xs' @ [xs!p]) + \n         sign_changes (xs!p # map ((+) (xs!p)) (psums xs2))\" for xs'\n  proof -\n    fix xs' :: \"'a list\"\n    have \"sign_changes (xs' @ psums xs) = \n            sign_changes (xs' @ xs ! p # map ((+) (xs!p)) (psums xs2))\"\n      by (subst psums_decompose, subst (1 2) sign_changes_filter [symmetric]) \n         (simp_all add: psums_Cons)\n    also have \"\\<dots> = sign_changes (xs' @ [xs!p]) + \n                      sign_changes (xs!p # map ((+) (xs!p)) (psums xs2))\"\n      by (subst sign_changes_decompose[OF p_nz]) simp_all\n    finally show \"sign_changes (xs' @ psums xs) = \\<dots>\" .\n  qed\n\n  show ?case\n  proof (cases \"x > 0\")\n    assume \"\\<not>(x > 0)\"\n    with nonneg show ?thesis by (auto simp: v_def)\n  next\n    assume x: \"x > 0\"\n    show ?thesis\n    proof (rule linorder_cases[of y 0])\n      assume y: \"y > 0\"\n      from x and this have xy: \"x + y > 0\" by (rule add_pos_pos)\n      with y have \"sign_changes ((x + y) # xs) = sign_changes (y # xs)\"\n        by (intro sign_changes_cong) auto\n      moreover have \"sign_changes (x # psums ((x + y) # xs)) = \n                       sign_changes (psums ((x+y) # xs))\"\n        using x xy by (subst (1 2) psums_Cons) (simp_all add: sign_changes_Cons_Cons_same)\n      ultimately show ?thesis using x y \n        by (simp add: v_def algebra_simps sign_changes_Cons_Cons_same)\n    next\n      assume y: \"y = 0\"\n      with x show ?thesis\n        by (simp add: v_def sign_changes_Cons_Cons_0 psums_Cons \n                      o_def sign_changes_Cons_Cons_same)\n    next\n      assume y: \"y < 0\"\n      with x have different: \"x * y < 0\" by (rule mult_pos_neg)\n      show ?thesis\n      proof (rule linorder_cases[of \"x + y\" 0])\n        assume xy: \"x + y < 0\"\n        with x have different': \"x * (x + y) < 0\" by (rule mult_pos_neg)\n        have \"(\\<lambda>t. t + (x + y)) = ((+) (x + y))\" by (rule ext) simp\n        moreover from y xy have \"sign_changes ((x+y) # xs) = sign_changes (y # xs)\" \n          by (intro sign_changes_cong) auto\n        ultimately show ?thesis using xy different different' y\n          by (simp add: v_def sign_changes_Cons_Cons_different psums_Cons o_def add_ac)\n      next\n        assume xy: \"x + y = 0\"\n        show ?case\n        proof (cases \"xs ! p > 0\")\n          assume p: \"xs ! p > 0\"\n          from p y have different': \"y * xs ! p < 0\" by (intro mult_neg_pos)\n          with v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] x xy p different different' \n               v_psums_decompose[of \"[x]\"] v_psums_decompose[of \"[]\"]\n          show ?thesis by (auto simp add: algebra_simps v_def sign_changes_Cons_Cons_0 \n                             sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        next\n          assume \"\\<not>(xs ! p > 0)\"\n          with p_nz have p: \"xs ! p < 0\" by simp\n          from p y have same: \"y * xs ! p > 0\" by (intro mult_neg_neg)\n          from p x have different': \"x * xs ! p < 0\" by (intro mult_pos_neg)\n          from v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] xy different different' same \n               v_psums_decompose[of \"[x]\"] v_psums_decompose[of \"[]\"]\n          show ?thesis by (auto simp add: algebra_simps v_def sign_changes_Cons_Cons_0 \n                             sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        qed\n      next\n        assume xy: \"x + y > 0\"\n        from x and this have same: \"x * (x + y) > 0\" by (rule mult_pos_pos)\n        show ?case\n        proof (cases \"xs ! p > 0\")\n          assume p: \"xs ! p > 0\"\n          from xy p have same': \"(x + y) * xs ! p > 0\" by (intro mult_pos_pos)\n          from p y have different': \"y * xs ! p < 0\" by (intro mult_neg_pos)\n          have \"(\\<lambda>t. t + (x + y)) = ((+) (x + y))\" by (rule ext) simp\n          with v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] different different' same same'\n          show ?thesis by (auto simp add: algebra_simps v_def psums_Cons o_def\n                             sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        next\n          assume \"\\<not>(xs ! p > 0)\"\n          with p_nz have p: \"xs ! p < 0\" by simp\n          from xy p have different': \"(x + y) * xs ! p < 0\" by (rule mult_pos_neg)\n          from y p have same': \"y * xs ! p > 0\" by (rule mult_neg_neg)\n          have \"(\\<lambda>t. t + (x + y)) = ((+) (x + y))\" by (rule ext) simp\n          with v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] different different' same same'\n          show ?thesis by (auto simp add: algebra_simps v_def psums_Cons o_def\n                              sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        qed\n      qed\n    qed\n  qed\nqed\n\n\ntext \\<open>\n  Now we can prove the main lemma of the proof by induction over the list with our specialised\n  induction rule for @{term \"sign_changes\"}. It states that for a non-empty list whose last element \n  is non-zero and whose sum is zero, the difference of the sign changes in the list and in the list \n  of its partial sums is odd and positive. \n\\<close>\nlemma arthan:\n  fixes xs :: \"'a :: linordered_idom list\"\n  assumes \"xs \\<noteq> []\" \"last xs \\<noteq> 0\" \"sum_list xs = 0\"\n  shows   \"sign_changes xs > sign_changes (psums xs) \\<and> \n           odd (sign_changes xs - sign_changes (psums xs))\"\nusing assms\nproof (induction xs rule: sign_changes_induct)\n  case (nonzero x y xs)\n  show ?case\n  proof (cases \"xs = []\")\n    case False\n    define \\<alpha> where \"\\<alpha> = int (sign_changes (x # y # xs)) - int (sign_changes ((x + y) # xs))\"\n    define \\<beta> where \"\\<beta> = int (sign_changes (psums (x # y # xs))) - int (sign_changes (psums ((x+y) # xs)))\"\n    from nonzero False have \"\\<alpha> \\<ge> \\<beta> \\<and> even (\\<alpha> - \\<beta>)\" unfolding \\<alpha>_def \\<beta>_def\n      by (intro arthan_aux1) auto\n    from False and nonzero.prems have\n       \"sign_changes (psums ((x + y) # xs)) < sign_changes ((x + y) # xs) \\<and>\n        odd (sign_changes ((x + y) # xs) - sign_changes (psums ((x + y) # xs)))\"\n      by (intro nonzero.IH) (auto simp: add.assoc)\n    with arthan_aux1[of xs x y] nonzero(4,5) False(1) show ?thesis by force\n  qed (insert nonzero.prems, auto split: if_split_asm simp: sign_changes_two add_eq_0_iff)\nqed (auto split: if_split_asm simp: add_eq_0_iff)\n\nend\n\n\nsubsection \\<open>Roots of a polynomial with a certain property\\<close>\n\ntext \\<open>\n  The set of roots of a polynomial @{term \"p\"} that fulfil a given property @{term \"P\"}:\n\\<close>\ndefinition \"roots_with P p = {x. P x \\<and> poly p x = 0}\"\n\ntext \\<open>\n  The number of roots of a polynomial @{term \"p\"} with a given property @{term \"P\"}, where \n  multiple roots are counted multiple times.\n \\<close>\ndefinition \"count_roots_with P p = (\\<Sum>x\\<in>roots_with P p. order x p)\"\n\nabbreviation \"pos_roots \\<equiv> roots_with (\\<lambda>x. x > 0)\"\nabbreviation \"count_pos_roots \\<equiv> count_roots_with (\\<lambda>x. x > 0)\"\n\n\nlemma finite_roots_with [simp]: \n  \"(p :: 'a :: linordered_idom poly) \\<noteq> 0 \\<Longrightarrow> finite (roots_with P p)\"\n  by (rule finite_subset[OF _ poly_roots_finite[of p]]) (auto simp: roots_with_def)\n\nlemma count_roots_with_times_root:\n  assumes \"p \\<noteq> 0\" \"P (a :: 'a :: linordered_idom)\"\n  shows   \"count_roots_with P ([:a, -1:] * p) = Suc (count_roots_with P p)\"\nproof -\n  define q where \"q = [:a, -1:] * p\"\n  from assms have a: \"a \\<in> roots_with P q\" by (simp_all add: roots_with_def q_def)\n  have q_nz: \"q \\<noteq> 0\" unfolding q_def by (rule no_zero_divisors) (simp_all add: assms)\n\n  have \"count_roots_with P q = (\\<Sum>x\\<in>roots_with P q. order x q)\" by (simp add: count_roots_with_def)\n  also from a q_nz have \"\\<dots> = order a q + (\\<Sum>x\\<in>roots_with P q - {a}. order x q)\"\n    by (subst sum.remove) simp_all\n  also have \"order a q = order a [:a, -1:] + order a p\" unfolding q_def\n    by (subst order_mult[OF no_zero_divisors]) (simp_all add: assms)\n  also have \"order a [:a, -1:] = 1\"\n    by (subst order_smult [of \"-1\", symmetric])\n       (insert order_power_n_n[of a 1], simp_all add: order_1)\n  also have \"(\\<Sum>x\\<in>roots_with P q - {a}. order x q) = (\\<Sum>x\\<in>roots_with P q - {a}. order x p)\"\n  proof (intro sum.cong refl)\n    fix x assume x: \"x \\<in> roots_with P q - {a}\"\n    from assms have \"order x q = order x [:a, -1:] + order x p\" unfolding q_def\n      by (subst order_mult[OF no_zero_divisors]) (simp_all add: assms)\n    also from x have \"order x [:a, -1:] = 0\" by (intro order_0I) simp_all\n    finally show \"order x q = order x p\" by simp\n  qed\n  also from a q_nz have \"1 + order a p + (\\<Sum>x\\<in>roots_with P q - {a}. order x p) = \n                           1 + (\\<Sum>x\\<in>roots_with P q. order x p)\"\n    by (subst add.assoc, subst sum.remove[symmetric]) simp_all\n  also from q_nz have \"(\\<Sum>x\\<in>roots_with P q. order x p) = (\\<Sum>x\\<in>roots_with P p. order x p)\"\n  proof (intro sum.mono_neutral_right)\n    show \"roots_with P p \\<subseteq> roots_with P q\" \n      by (auto simp: roots_with_def q_def simp del: mult_pCons_left)\n    show \"\\<forall>x\\<in>roots_with P q - roots_with P p. order x p = 0\"\n      by (auto simp: roots_with_def q_def order_root simp del: mult_pCons_left)\n  qed simp_all\n  finally show ?thesis by (simp add: q_def count_roots_with_def)\nqed\n\n\nsubsection \\<open>Coefficient sign changes of a polynomial\\<close>\n\nabbreviation (input) \"coeff_sign_changes f \\<equiv> sign_changes (coeffs f)\"\n\ntext \\<open>\n  We first show that when building a polynomial from a coefficient list, the coefficient sign\n  sign changes of the resulting polynomial are the same as the same sign changes in the list.\n\n  Note that constructing a polynomial from a list removes all trailing zeros.\n\\<close>\nlemma sign_changes_coeff_sign_changes:\n  assumes \"Poly xs = (p :: 'a :: linordered_idom poly)\"\n  shows   \"sign_changes xs = coeff_sign_changes p\"\nproof -\n  have \"coeffs p = coeffs (Poly xs)\" by (subst assms) (rule refl)\n  also have \"\\<dots> = strip_while ((=) 0) xs\" by simp\n  also have \"filter ((\\<noteq>) 0) \\<dots> = filter ((\\<noteq>) 0) xs\" unfolding strip_while_def o_def\n    by (subst rev_filter [symmetric], subst filter_dropWhile) (simp_all add: rev_filter)\n  also have \"sign_changes \\<dots> = sign_changes xs\" by (simp add: sign_changes_filter)\n  finally show ?thesis by (simp add: sign_changes_filter)\nqed\n\ntext \\<open>\n  By applying @{term \"reduce_root a\"}, we can assume w.l.o.g. that the root in\n  question is 1, since applying root reduction does not change the number of \n  sign changes.\n\\<close>\nlemma coeff_sign_changes_reduce_root: \n  assumes \"a > (0 :: 'a :: linordered_idom)\"\n  shows   \"coeff_sign_changes (reduce_root a p) = coeff_sign_changes p\"\nproof (intro sign_changes_cong, induction p)\n  case (pCons c p)\n  have \"map sgn (coeffs (reduce_root a (pCons c p))) = \n             cCons (sgn c) (map sgn (coeffs (reduce_root a p)))\"\n    using assms by (auto simp add: cCons_def sgn_0_0 sgn_mult reduce_root_pCons coeffs_smult)\n  also note pCons.IH\n  also have \"cCons (sgn c) (map sgn (coeffs p)) = map sgn (coeffs (pCons c p))\"\n    using assms by (auto simp add: cCons_def sgn_0_0)\n  finally show ?case .\nqed (simp_all add: reduce_root_def)\n\ntext \\<open>\n  Multiplying a polynomial with a positive constant also does not change the number \n  of sign changes. (in fact, any non-zero constant would also work, but the proof \n  is slightly more difficult and positive constants suffice in our use case)\n\\<close>\nlemma coeff_sign_changes_smult: \n  assumes \"a > (0 :: 'a :: linordered_idom)\"\n  shows   \"coeff_sign_changes (smult a p) = coeff_sign_changes p\"\n  using assms by (auto intro!: sign_changes_cong simp: sgn_mult coeffs_smult)\n\n\ncontext\nbegin\n\ntext \\<open>\n  We now show that a polynomial with an odd number of sign changes contains a \n  positive root. We first assume that the constant coefficient is non-zero. Then it is \n  clear that the polynomial's sign at 0 will be the sign of the constant coefficient, whereas \n  the polynomial's sign for sufficiently large inputs will be the sign of the leading coefficient.\n\n  Moreover, we have shown before that in a list with an odd number of sign changes and \n  non-zero initial and last coefficients, the initial coefficient and the last coefficient have \n  opposite and non-zero signs. Then, the polynomial obviously has a positive root.\n\\<close>\nprivate lemma odd_coeff_sign_changes_imp_pos_roots_aux:\n  assumes [simp]: \"p \\<noteq> (0 :: real poly)\" \"poly p 0 \\<noteq> 0\"\n  assumes \"odd (coeff_sign_changes p)\"\n  obtains x where \"x > 0\" \"poly p x = 0\"\nproof -\n  from \\<open>poly p 0 \\<noteq> 0\\<close>\n  have [simp]: \"hd (coeffs p) \\<noteq> 0\"\n    by (induct p) auto\n  from assms have  \"\\<not> even (coeff_sign_changes p)\"\n    by blast\n  also have \"even (coeff_sign_changes p) \\<longleftrightarrow> sgn (hd (coeffs p)) = sgn (lead_coeff p)\"\n    by (auto simp add: even_sign_changes_iff last_coeffs_eq_coeff_degree)\n  finally have \"sgn (hd (coeffs p)) * sgn (lead_coeff p) < 0\" \n    by (auto simp: sgn_if split: if_split_asm)\n  also from \\<open>p \\<noteq> 0\\<close> have \"hd (coeffs p) = poly p 0\" by (induction p) auto\n  finally have \"poly p 0 * lead_coeff p < 0\" by (auto simp: mult_less_0_iff)\n\n  from pos_root_exI[OF this] that show ?thesis by blast\nqed\n\ntext \\<open>\n  We can now show the statement without the restriction to a non-zero constant coefficient.\n  We can do this by simply factoring $p$ into the form $p \\cdot x^n$, where $n$ is chosen as\n  large as possible. This corresponds to stripping all initial zeros of the coefficient list,\n  which obviously changes neither the existence of positive roots nor the number of coefficient \n  sign changes.\n\\<close>\nlemma odd_coeff_sign_changes_imp_pos_roots:\n  assumes \"p \\<noteq> (0 :: real poly)\"\n  assumes \"odd (coeff_sign_changes p)\"\n  obtains x where \"x > 0\" \"poly p x = 0\"\nproof -\n  define s where \"s = sgn (lead_coeff p)\"\n  define n where \"n = order 0 p\"\n  define r where \"r = p div [:0, 1:] ^ n\"\n  have p: \"p = [:0, 1:] ^ n * r\" unfolding r_def n_def\n    using order_1[of 0 p] by (simp del: mult_pCons_left)\n  from assms p have r_nz: \"r \\<noteq> 0\" by auto\n\n  obtain x where \"x > 0\" \"poly r x = 0\"\n  proof (rule odd_coeff_sign_changes_imp_pos_roots_aux)\n    show \"r \\<noteq> 0\" by fact\n    have \"order 0 p = order 0 p + order 0 r\"\n      by (subst p, insert order_power_n_n[of \"0::real\" n] r_nz)\n         (simp del: mult_pCons_left add: order_mult n_def)\n    hence \"order 0 r = 0\" by simp\n    with r_nz show nz: \"poly r 0 \\<noteq> 0\" by (simp add: order_root)\n\n    note \\<open>odd (coeff_sign_changes p)\\<close> \n    also have \"p = [:0, 1:] ^ n * r\" by (simp add: p)\n    also have \"[:0, 1:] ^ n = monom 1 n\" \n      by (induction n) (simp_all add: monom_Suc monom_0)\n    also have \"coeffs (monom 1 n * r) = replicate n 0 @ coeffs r\"\n      by (induction n) (simp_all add: monom_Suc cCons_def r_nz monom_0)\n    also have \"sign_changes \\<dots> = coeff_sign_changes r\"\n      by (subst (1 2) sign_changes_filter [symmetric]) simp\n    finally show \"odd (coeff_sign_changes r)\" .\n  qed\n  thus ?thesis by (intro that[of x]) (simp_all add: p)\nqed\n\nend\n\n\nsubsection \\<open>Proof of Descartes' sign rule\\<close>\n\ntext \\<open>\n  For a polynomial $p(X) = a_0 + \\ldots + a_n X^n$, we have \n  $[X^i] (1-X)p(X) = (\\sum\\limits_{j=0}^i a_j)$.\n\\<close>\nlemma coeff_poly_times_one_minus_x:\n  fixes g :: \"'a :: linordered_idom poly\"\n  shows \"coeff g n = (\\<Sum>i\\<le>n. coeff (g * [:1, -1:]) i)\"\n  by (induction n) simp_all\n\ntext \\<open>\n  We apply the previous lemma to the coefficient list of a polynomial and show: \n  given a polynomial $p(X)$ and $q(X) = (1 - X)p(X)$, the coefficient list of $p(X)$ is the \n  list of partial sums of the coefficient list of $q(X)$.\n\\<close>\nlemma Poly_times_one_minus_x_eq_psums:\n  fixes xs :: \"'a :: linordered_idom list\"\n  assumes [simp]: \"length xs = length ys\"\n  assumes \"Poly xs = Poly ys * [:1, -1:]\"\n  shows   \"ys = psums xs\"\nproof (rule nth_equalityI; safe?)\n  fix i assume i: \"i < length ys\"\n  hence \"ys ! i = coeff (Poly ys) i\"\n    by (simp add: nth_default_def)\n  also from coeff_poly_times_one_minus_x[of \"Poly ys\" i] assms\n    have \"\\<dots> = (\\<Sum>j\\<le>i. coeff (Poly xs) j)\" by simp\n    also from i have \"\\<dots> = psums xs ! i\"\n      by (auto simp: nth_default_def psums_nth)\n  finally show \"ys ! i = psums xs ! i\" .\nqed simp_all\n\ntext \\<open>\n  We can now apply our main lemma on the sign changes in lists to the coefficient lists of \n  a nonzero polynomial $p(X)$ and $(1-X)p(X)$: the difference of the changes in the \n  coefficient lists is odd and positive.\n\\<close>\nlemma sign_changes_poly_times_one_minus_x:\n  fixes g :: \"'a :: linordered_idom poly\" and a :: 'a\n  assumes nz: \"g \\<noteq> 0\"\n  defines \"v \\<equiv> coeff_sign_changes\"\n  shows \"v ([:1, -1:] * g) - v g > 0 \\<and> odd (v ([:1, -1:] * g) - v g)\"\nproof -\n  define xs where \"xs = coeffs ([:1, -1:] * g)\"\n  define ys where \"ys = coeffs g @ [0]\"\n  have ys: \"ys = psums xs\"\n  proof (rule Poly_times_one_minus_x_eq_psums)\n    show \"length xs = length ys\" unfolding xs_def ys_def\n      by (simp add: length_coeffs nz degree_mult_eq no_zero_divisors del: mult_pCons_left)\n    show \"Poly xs = Poly ys * [:1, - 1:]\" unfolding xs_def ys_def\n      by (simp only: Poly_snoc Poly_coeffs) simp\n  qed\n  have \"sign_changes (psums xs) < sign_changes xs \\<and> \n        odd (sign_changes xs - sign_changes (psums xs))\"\n  proof (rule arthan)\n    show \"xs \\<noteq> []\"\n      by (auto simp: xs_def nz simp del: mult_pCons_left)\n    then show \"sum_list xs = 0\" by (simp add: last_psums [symmetric] ys [symmetric] ys_def)\n    show \"last xs \\<noteq> 0\"\n      by (auto simp: xs_def nz last_coeffs_eq_coeff_degree simp del: mult_pCons_left)\n  qed\n  with ys have \"sign_changes ys < sign_changes xs \\<and> \n                odd (sign_changes xs - sign_changes ys)\" by simp\n  also have \"sign_changes xs = v ([:1, -1:] * g)\" unfolding v_def\n    by (intro sign_changes_coeff_sign_changes) (simp_all add: xs_def)\n  also have \"sign_changes ys = v g\" unfolding v_def\n    by (intro sign_changes_coeff_sign_changes) (simp_all add: ys_def Poly_snoc)\n  finally show ?thesis by simp\nqed\n\ntext \\<open>\n  We can now lift the previous lemma to the case of $p(X)$ and $(a-X)p(X)$ by substituting $X$ \n  with $aX$, yielding the polynomials $p(aX)$ and $a \\cdot (1-X) \\cdot p(aX)$.\n\\<close>\nlemma sign_changes_poly_times_root_minus_x:\n  fixes g :: \"'a :: linordered_idom poly\" and a :: 'a\n  assumes nz: \"g \\<noteq> 0\" and pos: \"a > 0\"\n  defines \"v \\<equiv> coeff_sign_changes\"\n  shows \"v ([:a, -1:] * g) - v g > 0 \\<and> odd (v ([:a, -1:] * g) - v g)\"\nproof -\n  have \"0 < v ([:1, - 1:] * reduce_root a g) - v (reduce_root a g) \\<and>\n            odd (v ([:1, - 1:] * reduce_root a g) - v (reduce_root a g))\"\n    using nz pos unfolding v_def by (intro sign_changes_poly_times_one_minus_x) simp_all\n  also have \"v ([:1, -1:] * reduce_root a g) = v (smult a ([:1, -1:] * reduce_root a g))\"\n    unfolding v_def by (simp add: coeff_sign_changes_smult pos)\n  also have \"smult a ([:1, -1:] * reduce_root a g) = [:a:] * [:1, -1:] * reduce_root a g\" \n    by (subst mult.assoc) simp\n  also have \"[:a:] * [:1, -1:] = reduce_root a [:a, -1:]\" \n    by (simp add: reduce_root_def pcompose_pCons)\n  also have \"\\<dots> * reduce_root a g = reduce_root a ([:a, -1:] * g)\" \n    unfolding reduce_root_def by (simp only: pcompose_mult)\n  also have \"v \\<dots> = v ([:a, -1:] * g)\" by (simp add: v_def coeff_sign_changes_reduce_root pos)\n  also have \"v (reduce_root a g) = v g\" by (simp add: v_def coeff_sign_changes_reduce_root pos)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Finally, the difference of the number of coefficient sign changes and the number of\n  positive roots is non-negative and even. This follows straightforwardly by induction \n  over the roots.\n\\<close>\nlemma descartes_sign_rule_aux:\n  fixes p :: \"real poly\"\n  assumes \"p \\<noteq> 0\"\n  shows   \"coeff_sign_changes p \\<ge> count_pos_roots p \\<and> \n           even (coeff_sign_changes p - count_pos_roots p)\"\nusing assms\nproof (induction p rule: poly_root_induct[where P = \"\\<lambda>a. a > 0\"])\n  case (root a p)\n  define q where \"q = [:a, -1:] * p\"\n  from root.prems have p: \"p \\<noteq> 0\" by auto\n  with root p sign_changes_poly_times_root_minus_x[of p a] \n       count_roots_with_times_root[of p \"\\<lambda>x. x > 0\" a] show ?case by (fold q_def) fastforce\nnext\n  case (no_roots p)\n  from no_roots have \"pos_roots p = {}\" by (auto simp: roots_with_def)\n  hence [simp]: \"count_pos_roots p = 0\" by (simp add: count_roots_with_def)\n  thus ?case using no_roots \\<open>p \\<noteq> 0\\<close> odd_coeff_sign_changes_imp_pos_roots[of p]\n    by (auto simp: roots_with_def)\nqed simp_all\n\ntext \\<open>\n  The main theorem is then an obvious consequence\n\\<close>\ntheorem descartes_sign_rule:\n  fixes p :: \"real poly\"\n  assumes \"p \\<noteq> 0\"\n  shows \"\\<exists>d. even d \\<and> coeff_sign_changes p = count_pos_roots p + d\"\nproof\n  define d where \"d = coeff_sign_changes p - count_pos_roots p\"\n  show \"even d \\<and> coeff_sign_changes p = count_pos_roots p + d\"\n    unfolding d_def using descartes_sign_rule_aux[OF assms] by auto\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Descartes_Sign_Rule/Descartes_Sign_Rule.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.775783615943656}}
{"text": "theory Palindrome\nimports Main\nbegin\n(*\n  Palindromes are words that read the same backward as forward.\n  \n  Lemma: Exactly the palindromes can be constructed by the following rules\n*)\n\ninductive pal :: \"'a list \\<Rightarrow> bool\" where\n  empty: \"pal []\"\n| single: \"pal [x]\"  \n| append: \"pal xs \\<Longrightarrow> pal (x#xs@[x])\"  \n\n(* One direction of the proof is easy. *)\nlemma pal_sound: \"pal xs \\<Longrightarrow> rev xs = xs\" by (induction rule: pal.induct) auto\n\n(* Let's focus on the other direction *)\nlemma pal_complete:\n  assumes \"rev xs = xs\" \n  shows \"pal xs\"\n  oops\n(*\n  Proof sketch\n  \n    induction on length of xs\n      PREM: rev xs = xs\n      IH: for all ys shorter than xs and with rev ys = ys, we have pal ys\n      To show: pal xs\n\n      If xs is empty or the singleton list, the goal follows by empty/single rule\n      So assume xs = x#zs@[y]. \n      From PREM, we get that y=x and rev zs = zs.\n      Moreover, zs is shorter than xs\n      hence, by IH, we have pal zs\n      and, by pal.append, we get pal (x#zs@[x])\n      with the equalities form above, we have xs = x#zs@[x], and thus pal xs. \n      QED\n      \n\n*)\n\n\n\nlemma pal_complete:\n  assumes \"rev xs = xs\" \n  shows \"pal xs\"\n  using assms  \nproof (induction xs rule: length_induct)\n  case (1 xs)\n  \n  note IH=\"1.IH\" note PREM=\"1.prems\"\n  \n  show ?case proof (cases xs)\n    case Nil\n    then show ?thesis \n      by (simp add: pal.empty)\n  next\n    case (Cons x ys)\n    then show ?thesis proof (cases ys rule: rev_cases)\n      case Nil\n      then show ?thesis\n        using Cons by (simp add: pal.single)\n    next\n      case (snoc zs y)\n      from PREM have \"y=x\" \"rev zs = zs\"\n        by (auto simp: local.Cons snoc snoc_eq_iff_butlast)\n        (* Simplifier loops, used sledgehammer to find the following proof *)\n        (*apply (simp add: Cons snoc) \n        apply (unfold snoc) *)\n        \n      moreover have \"length zs < length xs\" by (simp add: Cons snoc)\n      ultimately have \"pal zs\" using IH by blast\n      hence \"pal (x#zs@[x])\" by (rule pal.append)\n      then show ?thesis by (simp add: Cons snoc \\<open>y=x\\<close>)\n    qed\n  qed\nqed\n\n(* Same lemma, but adding simplifier setup *)\n\n(* Adding a reasonable simplifier setup *)\nlemmas [simp]  = pal.empty pal.single\n\nlemma \n  assumes \"rev xs = xs\" \n  shows \"pal xs\"\n  using assms  \nproof (induction xs rule: length_induct)\n  case (1 xs)\n  \n  note IH=\"1.IH\" note PREM=\"1.prems\"\n  \n  show ?case proof (cases xs)\n    case Nil\n    then show ?thesis by simp\n  next\n    case [simp]: (Cons x ys) (* Adding local simp-lemma *)\n    then show ?thesis proof (cases ys rule: rev_cases)\n      case Nil\n      then show ?thesis by (simp)\n    next\n      case [simp]: (snoc zs y)\n      from PREM have [simp]: \"y=x\" and \"rev zs = zs\"  \n        (* Names and attributes apply only to their part in \"and\" list, i.e.,\n          the above declares \\<open>y=x\\<close> as simp lemma, but not \\<open>rev zs = zs\\<close> *)\n        by (auto simp: snoc_eq_iff_butlast)\n      moreover have \"length zs < length xs\" by simp\n      ultimately have \"pal zs\" using IH by blast\n      hence \"pal (x#zs@[x])\" by (rule pal.append)\n      then show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma pal_correct: \"pal xs \\<longleftrightarrow> rev xs = xs\"\n  using pal_sound pal_complete by auto\n\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Demos/Palindrome.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278757303678, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7757836075232901}}
{"text": "(*  Title       : Series.thy\n    Author      : Jacques D. Fleuriot\n    Copyright   : 1998  University of Cambridge\n\nConverted to Isar and polished by lcp\nConverted to setsum and polished yet more by TNN\nAdditional contributions by Jeremy Avigad\n*)\n\nsection {* Infinite Series *}\n\ntheory Series\nimports Limits\nbegin\n\nsubsection {* Definition of infinite summability *}\n\ndefinition\n  sums :: \"(nat \\<Rightarrow> 'a::{topological_space, comm_monoid_add}) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  (infixr \"sums\" 80)\nwhere\n  \"f sums s \\<longleftrightarrow> (\\<lambda>n. \\<Sum>i<n. f i) ----> s\"\n\ndefinition summable :: \"(nat \\<Rightarrow> 'a::{topological_space, comm_monoid_add}) \\<Rightarrow> bool\" where\n   \"summable f \\<longleftrightarrow> (\\<exists>s. f sums s)\"\n\ndefinition\n  suminf :: \"(nat \\<Rightarrow> 'a::{topological_space, comm_monoid_add}) \\<Rightarrow> 'a\"\n  (binder \"\\<Sum>\" 10)\nwhere\n  \"suminf f = (THE s. f sums s)\"\n\nsubsection {* Infinite summability on topological monoids *}\n\nlemma sums_subst[trans]: \"f = g \\<Longrightarrow> g sums z \\<Longrightarrow> f sums z\"\n  by simp\n\nlemma sums_summable: \"f sums l \\<Longrightarrow> summable f\"\n  by (simp add: sums_def summable_def, blast)\n\nlemma summable_iff_convergent: \"summable f \\<longleftrightarrow> convergent (\\<lambda>n. \\<Sum>i<n. f i)\"\n  by (simp add: summable_def sums_def convergent_def)\n\nlemma suminf_eq_lim: \"suminf f = lim (\\<lambda>n. \\<Sum>i<n. f i)\"\n  by (simp add: suminf_def sums_def lim_def)\n\nlemma sums_zero[simp, intro]: \"(\\<lambda>n. 0) sums 0\"\n  unfolding sums_def by simp\n\nlemma summable_zero[simp, intro]: \"summable (\\<lambda>n. 0)\"\n  by (rule sums_zero [THEN sums_summable])\n\nlemma sums_group: \"f sums s \\<Longrightarrow> 0 < k \\<Longrightarrow> (\\<lambda>n. setsum f {n * k ..< n * k + k}) sums s\"\n  apply (simp only: sums_def setsum_nat_group tendsto_def eventually_sequentially)\n  apply safe\n  apply (erule_tac x=S in allE)\n  apply safe\n  apply (rule_tac x=\"N\" in exI, safe)\n  apply (drule_tac x=\"n*k\" in spec)\n  apply (erule mp)\n  apply (erule order_trans)\n  apply simp\n  done\n\nlemma sums_finite:\n  assumes [simp]: \"finite N\" and f: \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 0\"\n  shows \"f sums (\\<Sum>n\\<in>N. f n)\"\nproof -\n  { fix n\n    have \"setsum f {..<n + Suc (Max N)} = setsum f N\"\n    proof cases\n      assume \"N = {}\"\n      with f have \"f = (\\<lambda>x. 0)\" by auto\n      then show ?thesis by simp\n    next\n      assume [simp]: \"N \\<noteq> {}\"\n      show ?thesis\n      proof (safe intro!: setsum.mono_neutral_right f)\n        fix i assume \"i \\<in> N\"\n        then have \"i \\<le> Max N\" by simp\n        then show \"i < n + Suc (Max N)\" by simp\n      qed\n    qed }\n  note eq = this\n  show ?thesis unfolding sums_def\n    by (rule LIMSEQ_offset[of _ \"Suc (Max N)\"])\n       (simp add: eq atLeast0LessThan del: add_Suc_right)\nqed\n\nlemma summable_finite: \"finite N \\<Longrightarrow> (\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 0) \\<Longrightarrow> summable f\"\n  by (rule sums_summable) (rule sums_finite)\n\nlemma sums_If_finite_set: \"finite A \\<Longrightarrow> (\\<lambda>r. if r \\<in> A then f r else 0) sums (\\<Sum>r\\<in>A. f r)\"\n  using sums_finite[of A \"(\\<lambda>r. if r \\<in> A then f r else 0)\"] by simp\n\nlemma summable_If_finite_set[simp, intro]: \"finite A \\<Longrightarrow> summable (\\<lambda>r. if r \\<in> A then f r else 0)\"\n  by (rule sums_summable) (rule sums_If_finite_set)\n\nlemma sums_If_finite: \"finite {r. P r} \\<Longrightarrow> (\\<lambda>r. if P r then f r else 0) sums (\\<Sum>r | P r. f r)\"\n  using sums_If_finite_set[of \"{r. P r}\"] by simp\n\nlemma summable_If_finite[simp, intro]: \"finite {r. P r} \\<Longrightarrow> summable (\\<lambda>r. if P r then f r else 0)\"\n  by (rule sums_summable) (rule sums_If_finite)\n\nlemma sums_single: \"(\\<lambda>r. if r = i then f r else 0) sums f i\"\n  using sums_If_finite[of \"\\<lambda>r. r = i\"] by simp\n\nlemma summable_single[simp, intro]: \"summable (\\<lambda>r. if r = i then f r else 0)\"\n  by (rule sums_summable) (rule sums_single)\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::{t2_space, comm_monoid_add}\"\nbegin\n\nlemma summable_sums[intro]: \"summable f \\<Longrightarrow> f sums (suminf f)\"\n  by (simp add: summable_def sums_def suminf_def)\n     (metis convergent_LIMSEQ_iff convergent_def lim_def)\n\nlemma summable_LIMSEQ: \"summable f \\<Longrightarrow> (\\<lambda>n. \\<Sum>i<n. f i) ----> suminf f\"\n  by (rule summable_sums [unfolded sums_def])\n\nlemma sums_unique: \"f sums s \\<Longrightarrow> s = suminf f\"\n  by (metis limI suminf_eq_lim sums_def)\n\nlemma sums_iff: \"f sums x \\<longleftrightarrow> summable f \\<and> (suminf f = x)\"\n  by (metis summable_sums sums_summable sums_unique)\n\nlemma suminf_finite:\n  assumes N: \"finite N\" and f: \"\\<And>n. n \\<notin> N \\<Longrightarrow> f n = 0\"\n  shows \"suminf f = (\\<Sum>n\\<in>N. f n)\"\n  using sums_finite[OF assms, THEN sums_unique] by simp\n\nend\n\nlemma suminf_zero[simp]: \"suminf (\\<lambda>n. 0::'a::{t2_space, comm_monoid_add}) = 0\"\n  by (rule sums_zero [THEN sums_unique, symmetric])\n\n\nsubsection {* Infinite summability on ordered, topological monoids *}\n\nlemma sums_le:\n  fixes f g :: \"nat \\<Rightarrow> 'a::{ordered_comm_monoid_add, linorder_topology}\"\n  shows \"\\<forall>n. f n \\<le> g n \\<Longrightarrow> f sums s \\<Longrightarrow> g sums t \\<Longrightarrow> s \\<le> t\"\n  by (rule LIMSEQ_le) (auto intro: setsum_mono simp: sums_def)\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::{ordered_comm_monoid_add, linorder_topology}\"\nbegin\n\nlemma suminf_le: \"\\<lbrakk>\\<forall>n. f n \\<le> g n; summable f; summable g\\<rbrakk> \\<Longrightarrow> suminf f \\<le> suminf g\"\n  by (auto dest: sums_summable intro: sums_le)\n\nlemma setsum_le_suminf: \"summable f \\<Longrightarrow> \\<forall>m\\<ge>n. 0 \\<le> f m \\<Longrightarrow> setsum f {..<n} \\<le> suminf f\"\n  by (rule sums_le[OF _ sums_If_finite_set summable_sums]) auto\n\nlemma suminf_nonneg: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> 0 \\<le> suminf f\"\n  using setsum_le_suminf[of 0] by simp\n\nlemma setsum_less_suminf2: \"summable f \\<Longrightarrow> \\<forall>m\\<ge>n. 0 \\<le> f m \\<Longrightarrow> n \\<le> i \\<Longrightarrow> 0 < f i \\<Longrightarrow> setsum f {..<n} < suminf f\"\n  using\n    setsum_le_suminf[of \"Suc i\"]\n    add_strict_increasing[of \"f i\" \"setsum f {..<n}\" \"setsum f {..<i}\"]\n    setsum_mono2[of \"{..<i}\" \"{..<n}\" f]\n  by (auto simp: less_imp_le ac_simps)\n\nlemma setsum_less_suminf: \"summable f \\<Longrightarrow> \\<forall>m\\<ge>n. 0 < f m \\<Longrightarrow> setsum f {..<n} < suminf f\"\n  using setsum_less_suminf2[of n n] by (simp add: less_imp_le)\n\nlemma suminf_pos2: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> 0 < f i \\<Longrightarrow> 0 < suminf f\"\n  using setsum_less_suminf2[of 0 i] by simp\n\nlemma suminf_pos: \"summable f \\<Longrightarrow> \\<forall>n. 0 < f n \\<Longrightarrow> 0 < suminf f\"\n  using suminf_pos2[of 0] by (simp add: less_imp_le)\n\nlemma suminf_le_const: \"summable f \\<Longrightarrow> (\\<And>n. setsum f {..<n} \\<le> x) \\<Longrightarrow> suminf f \\<le> x\"\n  by (metis LIMSEQ_le_const2 summable_LIMSEQ)\n\nlemma suminf_eq_zero_iff: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> suminf f = 0 \\<longleftrightarrow> (\\<forall>n. f n = 0)\"\nproof\n  assume \"summable f\" \"suminf f = 0\" and pos: \"\\<forall>n. 0 \\<le> f n\"\n  then have f: \"(\\<lambda>n. \\<Sum>i<n. f i) ----> 0\"\n    using summable_LIMSEQ[of f] by simp\n  then have \"\\<And>i. (\\<Sum>n\\<in>{i}. f n) \\<le> 0\"\n  proof (rule LIMSEQ_le_const)\n    fix i show \"\\<exists>N. \\<forall>n\\<ge>N. (\\<Sum>n\\<in>{i}. f n) \\<le> setsum f {..<n}\"\n      using pos by (intro exI[of _ \"Suc i\"] allI impI setsum_mono2) auto\n  qed\n  with pos show \"\\<forall>n. f n = 0\"\n    by (auto intro!: antisym)\nqed (metis suminf_zero fun_eq_iff)\n\nlemma suminf_pos_iff: \"summable f \\<Longrightarrow> \\<forall>n. 0 \\<le> f n \\<Longrightarrow> 0 < suminf f \\<longleftrightarrow> (\\<exists>i. 0 < f i)\"\n  using setsum_le_suminf[of 0] suminf_eq_zero_iff by (simp add: less_le)\n\nend\n\nlemma summableI_nonneg_bounded:\n  fixes f:: \"nat \\<Rightarrow> 'a::{ordered_comm_monoid_add, linorder_topology, conditionally_complete_linorder}\"\n  assumes pos[simp]: \"\\<And>n. 0 \\<le> f n\" and le: \"\\<And>n. (\\<Sum>i<n. f i) \\<le> x\"\n  shows \"summable f\"\n  unfolding summable_def sums_def[abs_def]\nproof (intro exI order_tendstoI)\n  have [simp, intro]: \"bdd_above (range (\\<lambda>n. \\<Sum>i<n. f i))\"\n    using le by (auto simp: bdd_above_def)\n  { fix a assume \"a < (SUP n. \\<Sum>i<n. f i)\"\n    then obtain n where \"a < (\\<Sum>i<n. f i)\"\n      by (auto simp add: less_cSUP_iff)\n    then have \"\\<And>m. n \\<le> m \\<Longrightarrow> a < (\\<Sum>i<m. f i)\"\n      by (rule less_le_trans) (auto intro!: setsum_mono2)\n    then show \"eventually (\\<lambda>n. a < (\\<Sum>i<n. f i)) sequentially\"\n      by (auto simp: eventually_sequentially) }\n  { fix a assume \"(SUP n. \\<Sum>i<n. f i) < a\"\n    moreover have \"\\<And>n. (\\<Sum>i<n. f i) \\<le> (SUP n. \\<Sum>i<n. f i)\"\n      by (auto intro: cSUP_upper)\n    ultimately show \"eventually (\\<lambda>n. (\\<Sum>i<n. f i) < a) sequentially\"\n      by (auto intro: le_less_trans simp: eventually_sequentially) }\nqed\n\nsubsection {* Infinite summability on real normed vector spaces *}\n\nlemma sums_Suc_iff:\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  shows \"(\\<lambda>n. f (Suc n)) sums s \\<longleftrightarrow> f sums (s + f 0)\"\nproof -\n  have \"f sums (s + f 0) \\<longleftrightarrow> (\\<lambda>i. \\<Sum>j<Suc i. f j) ----> s + f 0\"\n    by (subst LIMSEQ_Suc_iff) (simp add: sums_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>i. (\\<Sum>j<i. f (Suc j)) + f 0) ----> s + f 0\"\n    by (simp add: ac_simps setsum.reindex image_iff lessThan_Suc_eq_insert_0)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>n. f (Suc n)) sums s\"\n  proof\n    assume \"(\\<lambda>i. (\\<Sum>j<i. f (Suc j)) + f 0) ----> s + f 0\"\n    with tendsto_add[OF this tendsto_const, of \"- f 0\"]\n    show \"(\\<lambda>i. f (Suc i)) sums s\"\n      by (simp add: sums_def)\n  qed (auto intro: tendsto_add simp: sums_def)\n  finally show ?thesis ..\nqed\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\nbegin\n\nlemma sums_add: \"f sums a \\<Longrightarrow> g sums b \\<Longrightarrow> (\\<lambda>n. f n + g n) sums (a + b)\"\n  unfolding sums_def by (simp add: setsum.distrib tendsto_add)\n\nlemma summable_add: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. f n + g n)\"\n  unfolding summable_def by (auto intro: sums_add)\n\nlemma suminf_add: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> suminf f + suminf g = (\\<Sum>n. f n + g n)\"\n  by (intro sums_unique sums_add summable_sums)\n\nlemma sums_diff: \"f sums a \\<Longrightarrow> g sums b \\<Longrightarrow> (\\<lambda>n. f n - g n) sums (a - b)\"\n  unfolding sums_def by (simp add: setsum_subtractf tendsto_diff)\n\nlemma summable_diff: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. f n - g n)\"\n  unfolding summable_def by (auto intro: sums_diff)\n\nlemma suminf_diff: \"summable f \\<Longrightarrow> summable g \\<Longrightarrow> suminf f - suminf g = (\\<Sum>n. f n - g n)\"\n  by (intro sums_unique sums_diff summable_sums)\n\nlemma sums_minus: \"f sums a \\<Longrightarrow> (\\<lambda>n. - f n) sums (- a)\"\n  unfolding sums_def by (simp add: setsum_negf tendsto_minus)\n\nlemma summable_minus: \"summable f \\<Longrightarrow> summable (\\<lambda>n. - f n)\"\n  unfolding summable_def by (auto intro: sums_minus)\n\nlemma suminf_minus: \"summable f \\<Longrightarrow> (\\<Sum>n. - f n) = - (\\<Sum>n. f n)\"\n  by (intro sums_unique [symmetric] sums_minus summable_sums)\n\nlemma sums_Suc: \"(\\<lambda> n. f (Suc n)) sums l \\<Longrightarrow> f sums (l + f 0)\"\n  by (simp add: sums_Suc_iff)\n\nlemma sums_iff_shift: \"(\\<lambda>i. f (i + n)) sums s \\<longleftrightarrow> f sums (s + (\\<Sum>i<n. f i))\"\nproof (induct n arbitrary: s)\n  case (Suc n)\n  moreover have \"(\\<lambda>i. f (Suc i + n)) sums s \\<longleftrightarrow> (\\<lambda>i. f (i + n)) sums (s + f n)\"\n    by (subst sums_Suc_iff) simp\n  ultimately show ?case\n    by (simp add: ac_simps)\nqed simp\n\nlemma summable_iff_shift: \"summable (\\<lambda>n. f (n + k)) \\<longleftrightarrow> summable f\"\n  by (metis diff_add_cancel summable_def sums_iff_shift[abs_def])\n\nlemma sums_split_initial_segment: \"f sums s \\<Longrightarrow> (\\<lambda>i. f (i + n)) sums (s - (\\<Sum>i<n. f i))\"\n  by (simp add: sums_iff_shift)\n\nlemma summable_ignore_initial_segment: \"summable f \\<Longrightarrow> summable (\\<lambda>n. f(n + k))\"\n  by (simp add: summable_iff_shift)\n\nlemma suminf_minus_initial_segment: \"summable f \\<Longrightarrow> (\\<Sum>n. f (n + k)) = (\\<Sum>n. f n) - (\\<Sum>i<k. f i)\"\n  by (rule sums_unique[symmetric]) (auto simp: sums_iff_shift)\n\nlemma suminf_split_initial_segment: \"summable f \\<Longrightarrow> suminf f = (\\<Sum>n. f(n + k)) + (\\<Sum>i<k. f i)\"\n  by (auto simp add: suminf_minus_initial_segment)\n\nlemma suminf_exist_split: \n  fixes r :: real assumes \"0 < r\" and \"summable f\"\n  shows \"\\<exists>N. \\<forall>n\\<ge>N. norm (\\<Sum>i. f (i + n)) < r\"\nproof -\n  from LIMSEQ_D[OF summable_LIMSEQ[OF `summable f`] `0 < r`]\n  obtain N :: nat where \"\\<forall> n \\<ge> N. norm (setsum f {..<n} - suminf f) < r\" by auto\n  thus ?thesis\n    by (auto simp: norm_minus_commute suminf_minus_initial_segment[OF `summable f`])\nqed\n\nlemma summable_LIMSEQ_zero: \"summable f \\<Longrightarrow> f ----> 0\"\n  apply (drule summable_iff_convergent [THEN iffD1])\n  apply (drule convergent_Cauchy)\n  apply (simp only: Cauchy_iff LIMSEQ_iff, safe)\n  apply (drule_tac x=\"r\" in spec, safe)\n  apply (rule_tac x=\"M\" in exI, safe)\n  apply (drule_tac x=\"Suc n\" in spec, simp)\n  apply (drule_tac x=\"n\" in spec, simp)\n  done\n\nend\n\ncontext\n  fixes f :: \"'i \\<Rightarrow> nat \\<Rightarrow> 'a::real_normed_vector\" and I :: \"'i set\"\nbegin\n\nlemma sums_setsum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) sums (x i)) \\<Longrightarrow> (\\<lambda>n. \\<Sum>i\\<in>I. f i n) sums (\\<Sum>i\\<in>I. x i)\"\n  by (induct I rule: infinite_finite_induct) (auto intro!: sums_add)\n\nlemma suminf_setsum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> summable (f i)) \\<Longrightarrow> (\\<Sum>n. \\<Sum>i\\<in>I. f i n) = (\\<Sum>i\\<in>I. \\<Sum>n. f i n)\"\n  using sums_unique[OF sums_setsum, OF summable_sums] by simp\n\nlemma summable_setsum: \"(\\<And>i. i \\<in> I \\<Longrightarrow> summable (f i)) \\<Longrightarrow> summable (\\<lambda>n. \\<Sum>i\\<in>I. f i n)\"\n  using sums_summable[OF sums_setsum[OF summable_sums]] .\n\nend\n\nlemma (in bounded_linear) sums: \"(\\<lambda>n. X n) sums a \\<Longrightarrow> (\\<lambda>n. f (X n)) sums (f a)\"\n  unfolding sums_def by (drule tendsto, simp only: setsum)\n\nlemma (in bounded_linear) summable: \"summable (\\<lambda>n. X n) \\<Longrightarrow> summable (\\<lambda>n. f (X n))\"\n  unfolding summable_def by (auto intro: sums)\n\nlemma (in bounded_linear) suminf: \"summable (\\<lambda>n. X n) \\<Longrightarrow> f (\\<Sum>n. X n) = (\\<Sum>n. f (X n))\"\n  by (intro sums_unique sums summable_sums)\n\nlemmas sums_of_real = bounded_linear.sums [OF bounded_linear_of_real]\nlemmas summable_of_real = bounded_linear.summable [OF bounded_linear_of_real]\nlemmas suminf_of_real = bounded_linear.suminf [OF bounded_linear_of_real]\n\nlemmas sums_scaleR_left = bounded_linear.sums[OF bounded_linear_scaleR_left]\nlemmas summable_scaleR_left = bounded_linear.summable[OF bounded_linear_scaleR_left]\nlemmas suminf_scaleR_left = bounded_linear.suminf[OF bounded_linear_scaleR_left]\n\nlemmas sums_scaleR_right = bounded_linear.sums[OF bounded_linear_scaleR_right]\nlemmas summable_scaleR_right = bounded_linear.summable[OF bounded_linear_scaleR_right]\nlemmas suminf_scaleR_right = bounded_linear.suminf[OF bounded_linear_scaleR_right]\n\nsubsection {* Infinite summability on real normed algebras *}\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::real_normed_algebra\"\nbegin\n\nlemma sums_mult: \"f sums a \\<Longrightarrow> (\\<lambda>n. c * f n) sums (c * a)\"\n  by (rule bounded_linear.sums [OF bounded_linear_mult_right])\n\nlemma summable_mult: \"summable f \\<Longrightarrow> summable (\\<lambda>n. c * f n)\"\n  by (rule bounded_linear.summable [OF bounded_linear_mult_right])\n\nlemma suminf_mult: \"summable f \\<Longrightarrow> suminf (\\<lambda>n. c * f n) = c * suminf f\"\n  by (rule bounded_linear.suminf [OF bounded_linear_mult_right, symmetric])\n\nlemma sums_mult2: \"f sums a \\<Longrightarrow> (\\<lambda>n. f n * c) sums (a * c)\"\n  by (rule bounded_linear.sums [OF bounded_linear_mult_left])\n\nlemma summable_mult2: \"summable f \\<Longrightarrow> summable (\\<lambda>n. f n * c)\"\n  by (rule bounded_linear.summable [OF bounded_linear_mult_left])\n\nlemma suminf_mult2: \"summable f \\<Longrightarrow> suminf f * c = (\\<Sum>n. f n * c)\"\n  by (rule bounded_linear.suminf [OF bounded_linear_mult_left])\n\nend\n\nsubsection {* Infinite summability on real normed fields *}\n\ncontext\n  fixes c :: \"'a::real_normed_field\"\nbegin\n\nlemma sums_divide: \"f sums a \\<Longrightarrow> (\\<lambda>n. f n / c) sums (a / c)\"\n  by (rule bounded_linear.sums [OF bounded_linear_divide])\n\nlemma summable_divide: \"summable f \\<Longrightarrow> summable (\\<lambda>n. f n / c)\"\n  by (rule bounded_linear.summable [OF bounded_linear_divide])\n\nlemma suminf_divide: \"summable f \\<Longrightarrow> suminf (\\<lambda>n. f n / c) = suminf f / c\"\n  by (rule bounded_linear.suminf [OF bounded_linear_divide, symmetric])\n\ntext{*Sum of a geometric progression.*}\n\nlemma geometric_sums: \"norm c < 1 \\<Longrightarrow> (\\<lambda>n. c^n) sums (1 / (1 - c))\"\nproof -\n  assume less_1: \"norm c < 1\"\n  hence neq_1: \"c \\<noteq> 1\" by auto\n  hence neq_0: \"c - 1 \\<noteq> 0\" by simp\n  from less_1 have lim_0: \"(\\<lambda>n. c^n) ----> 0\"\n    by (rule LIMSEQ_power_zero)\n  hence \"(\\<lambda>n. c ^ n / (c - 1) - 1 / (c - 1)) ----> 0 / (c - 1) - 1 / (c - 1)\"\n    using neq_0 by (intro tendsto_intros)\n  hence \"(\\<lambda>n. (c ^ n - 1) / (c - 1)) ----> 1 / (1 - c)\"\n    by (simp add: nonzero_minus_divide_right [OF neq_0] diff_divide_distrib)\n  thus \"(\\<lambda>n. c ^ n) sums (1 / (1 - c))\"\n    by (simp add: sums_def geometric_sum neq_1)\nqed\n\nlemma summable_geometric: \"norm c < 1 \\<Longrightarrow> summable (\\<lambda>n. c^n)\"\n  by (rule geometric_sums [THEN sums_summable])\n\nlemma suminf_geometric: \"norm c < 1 \\<Longrightarrow> suminf (\\<lambda>n. c^n) = 1 / (1 - c)\"\n  by (rule sums_unique[symmetric]) (rule geometric_sums)\n\nend\n\nlemma power_half_series: \"(\\<lambda>n. (1/2::real)^Suc n) sums 1\"\nproof -\n  have 2: \"(\\<lambda>n. (1/2::real)^n) sums 2\" using geometric_sums [of \"1/2::real\"]\n    by auto\n  have \"(\\<lambda>n. (1/2::real)^Suc n) = (\\<lambda>n. (1 / 2) ^ n / 2)\"\n    by simp\n  thus ?thesis using sums_divide [OF 2, of 2]\n    by simp\nqed\n\nsubsection {* Infinite summability on Banach spaces *}\n\ntext{*Cauchy-type criterion for convergence of series (c.f. Harrison)*}\n\nlemma summable_Cauchy:\n  fixes f :: \"nat \\<Rightarrow> 'a::banach\"\n  shows \"summable f \\<longleftrightarrow> (\\<forall>e>0. \\<exists>N. \\<forall>m\\<ge>N. \\<forall>n. norm (setsum f {m..<n}) < e)\"\n  apply (simp only: summable_iff_convergent Cauchy_convergent_iff [symmetric] Cauchy_iff, safe)\n  apply (drule spec, drule (1) mp)\n  apply (erule exE, rule_tac x=\"M\" in exI, clarify)\n  apply (rule_tac x=\"m\" and y=\"n\" in linorder_le_cases)\n  apply (frule (1) order_trans)\n  apply (drule_tac x=\"n\" in spec, drule (1) mp)\n  apply (drule_tac x=\"m\" in spec, drule (1) mp)\n  apply (simp_all add: setsum_diff [symmetric])\n  apply (drule spec, drule (1) mp)\n  apply (erule exE, rule_tac x=\"N\" in exI, clarify)\n  apply (rule_tac x=\"m\" and y=\"n\" in linorder_le_cases)\n  apply (subst norm_minus_commute)\n  apply (simp_all add: setsum_diff [symmetric])\n  done\n\ncontext\n  fixes f :: \"nat \\<Rightarrow> 'a::banach\"\nbegin  \n\ntext{*Absolute convergence imples normal convergence*}\n\nlemma summable_norm_cancel: \"summable (\\<lambda>n. norm (f n)) \\<Longrightarrow> summable f\"\n  apply (simp only: summable_Cauchy, safe)\n  apply (drule_tac x=\"e\" in spec, safe)\n  apply (rule_tac x=\"N\" in exI, safe)\n  apply (drule_tac x=\"m\" in spec, safe)\n  apply (rule order_le_less_trans [OF norm_setsum])\n  apply (rule order_le_less_trans [OF abs_ge_self])\n  apply simp\n  done\n\nlemma summable_norm: \"summable (\\<lambda>n. norm (f n)) \\<Longrightarrow> norm (suminf f) \\<le> (\\<Sum>n. norm (f n))\"\n  by (auto intro: LIMSEQ_le tendsto_norm summable_norm_cancel summable_LIMSEQ norm_setsum)\n\ntext {* Comparison tests *}\n\nlemma summable_comparison_test: \"\\<exists>N. \\<forall>n\\<ge>N. norm (f n) \\<le> g n \\<Longrightarrow> summable g \\<Longrightarrow> summable f\"\n  apply (simp add: summable_Cauchy, safe)\n  apply (drule_tac x=\"e\" in spec, safe)\n  apply (rule_tac x = \"N + Na\" in exI, safe)\n  apply (rotate_tac 2)\n  apply (drule_tac x = m in spec)\n  apply (auto, rotate_tac 2, drule_tac x = n in spec)\n  apply (rule_tac y = \"\\<Sum>k=m..<n. norm (f k)\" in order_le_less_trans)\n  apply (rule norm_setsum)\n  apply (rule_tac y = \"setsum g {m..<n}\" in order_le_less_trans)\n  apply (auto intro: setsum_mono simp add: abs_less_iff)\n  done\n\n(*A better argument order*)\nlemma summable_comparison_test': \"summable g \\<Longrightarrow> (\\<And>n. n \\<ge> N \\<Longrightarrow> norm(f n) \\<le> g n) \\<Longrightarrow> summable f\"\n  by (rule summable_comparison_test) auto\n\nsubsection {* The Ratio Test*}\n\nlemma summable_ratio_test: \n  assumes \"c < 1\" \"\\<And>n. n \\<ge> N \\<Longrightarrow> norm (f (Suc n)) \\<le> c * norm (f n)\"\n  shows \"summable f\"\nproof cases\n  assume \"0 < c\"\n  show \"summable f\"\n  proof (rule summable_comparison_test)\n    show \"\\<exists>N'. \\<forall>n\\<ge>N'. norm (f n) \\<le> (norm (f N) / (c ^ N)) * c ^ n\"\n    proof (intro exI allI impI)\n      fix n assume \"N \\<le> n\" then show \"norm (f n) \\<le> (norm (f N) / (c ^ N)) * c ^ n\"\n      proof (induct rule: inc_induct)\n        case (step m)\n        moreover have \"norm (f (Suc m)) / c ^ Suc m * c ^ n \\<le> norm (f m) / c ^ m * c ^ n\"\n          using `0 < c` `c < 1` assms(2)[OF `N \\<le> m`] by (simp add: field_simps)\n        ultimately show ?case by simp\n      qed (insert `0 < c`, simp)\n    qed\n    show \"summable (\\<lambda>n. norm (f N) / c ^ N * c ^ n)\"\n      using `0 < c` `c < 1` by (intro summable_mult summable_geometric) simp\n  qed\nnext\n  assume c: \"\\<not> 0 < c\"\n  { fix n assume \"n \\<ge> N\"\n    then have \"norm (f (Suc n)) \\<le> c * norm (f n)\"\n      by fact\n    also have \"\\<dots> \\<le> 0\"\n      using c by (simp add: not_less mult_nonpos_nonneg)\n    finally have \"f (Suc n) = 0\"\n      by auto }\n  then show \"summable f\"\n    by (intro sums_summable[OF sums_finite, of \"{.. Suc N}\"]) (auto simp: not_le Suc_less_eq2)\nqed\n\nend\n\ntext{*Relations among convergence and absolute convergence for power series.*}\n\nlemma abel_lemma:\n  fixes a :: \"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes r: \"0 \\<le> r\" and r0: \"r < r0\" and M: \"\\<And>n. norm (a n) * r0^n \\<le> M\"\n    shows \"summable (\\<lambda>n. norm (a n) * r^n)\"\nproof (rule summable_comparison_test')\n  show \"summable (\\<lambda>n. M * (r / r0) ^ n)\"\n    using assms \n    by (auto simp add: summable_mult summable_geometric)\nnext\n  fix n\n  show \"norm (norm (a n) * r ^ n) \\<le> M * (r / r0) ^ n\"\n    using r r0 M [of n]\n    apply (auto simp add: abs_mult field_simps power_divide)\n    apply (cases \"r=0\", simp)\n    apply (cases n, auto)\n    done\nqed\n\n\ntext{*Summability of geometric series for real algebras*}\n\nlemma complete_algebra_summable_geometric:\n  fixes x :: \"'a::{real_normed_algebra_1,banach}\"\n  shows \"norm x < 1 \\<Longrightarrow> summable (\\<lambda>n. x ^ n)\"\nproof (rule summable_comparison_test)\n  show \"\\<exists>N. \\<forall>n\\<ge>N. norm (x ^ n) \\<le> norm x ^ n\"\n    by (simp add: norm_power_ineq)\n  show \"norm x < 1 \\<Longrightarrow> summable (\\<lambda>n. norm x ^ n)\"\n    by (simp add: summable_geometric)\nqed\n\nsubsection {* Cauchy Product Formula *}\n\ntext {*\n  Proof based on Analysis WebNotes: Chapter 07, Class 41\n  @{url \"http://www.math.unl.edu/~webnotes/classes/class41/prp77.htm\"}\n*}\n\nlemma setsum_triangle_reindex:\n  fixes n :: nat\n  shows \"(\\<Sum>(i,j)\\<in>{(i,j). i+j < n}. f i j) = (\\<Sum>k<n. \\<Sum>i\\<le>k. f i (k - i))\"\n  apply (simp add: setsum.Sigma)\n  apply (rule setsum.reindex_bij_witness[where j=\"\\<lambda>(i, j). (i+j, i)\" and i=\"\\<lambda>(k, i). (i, k - i)\"])\n  apply auto\n  done\n\nlemma Cauchy_product_sums:\n  fixes a b :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,banach}\"\n  assumes a: \"summable (\\<lambda>k. norm (a k))\"\n  assumes b: \"summable (\\<lambda>k. norm (b k))\"\n  shows \"(\\<lambda>k. \\<Sum>i\\<le>k. a i * b (k - i)) sums ((\\<Sum>k. a k) * (\\<Sum>k. b k))\"\nproof -\n  let ?S1 = \"\\<lambda>n::nat. {..<n} \\<times> {..<n}\"\n  let ?S2 = \"\\<lambda>n::nat. {(i,j). i + j < n}\"\n  have S1_mono: \"\\<And>m n. m \\<le> n \\<Longrightarrow> ?S1 m \\<subseteq> ?S1 n\" by auto\n  have S2_le_S1: \"\\<And>n. ?S2 n \\<subseteq> ?S1 n\" by auto\n  have S1_le_S2: \"\\<And>n. ?S1 (n div 2) \\<subseteq> ?S2 n\" by auto\n  have finite_S1: \"\\<And>n. finite (?S1 n)\" by simp\n  with S2_le_S1 have finite_S2: \"\\<And>n. finite (?S2 n)\" by (rule finite_subset)\n\n  let ?g = \"\\<lambda>(i,j). a i * b j\"\n  let ?f = \"\\<lambda>(i,j). norm (a i) * norm (b j)\"\n  have f_nonneg: \"\\<And>x. 0 \\<le> ?f x\" by (auto)\n  hence norm_setsum_f: \"\\<And>A. norm (setsum ?f A) = setsum ?f A\"\n    unfolding real_norm_def\n    by (simp only: abs_of_nonneg setsum_nonneg [rule_format])\n\n  have \"(\\<lambda>n. (\\<Sum>k<n. a k) * (\\<Sum>k<n. b k)) ----> (\\<Sum>k. a k) * (\\<Sum>k. b k)\"\n    by (intro tendsto_mult summable_LIMSEQ summable_norm_cancel [OF a] summable_norm_cancel [OF b])\n  hence 1: \"(\\<lambda>n. setsum ?g (?S1 n)) ----> (\\<Sum>k. a k) * (\\<Sum>k. b k)\"\n    by (simp only: setsum_product setsum.Sigma [rule_format] finite_lessThan)\n\n  have \"(\\<lambda>n. (\\<Sum>k<n. norm (a k)) * (\\<Sum>k<n. norm (b k))) ----> (\\<Sum>k. norm (a k)) * (\\<Sum>k. norm (b k))\"\n    using a b by (intro tendsto_mult summable_LIMSEQ)\n  hence \"(\\<lambda>n. setsum ?f (?S1 n)) ----> (\\<Sum>k. norm (a k)) * (\\<Sum>k. norm (b k))\"\n    by (simp only: setsum_product setsum.Sigma [rule_format] finite_lessThan)\n  hence \"convergent (\\<lambda>n. setsum ?f (?S1 n))\"\n    by (rule convergentI)\n  hence Cauchy: \"Cauchy (\\<lambda>n. setsum ?f (?S1 n))\"\n    by (rule convergent_Cauchy)\n  have \"Zfun (\\<lambda>n. setsum ?f (?S1 n - ?S2 n)) sequentially\"\n  proof (rule ZfunI, simp only: eventually_sequentially norm_setsum_f)\n    fix r :: real\n    assume r: \"0 < r\"\n    from CauchyD [OF Cauchy r] obtain N\n    where \"\\<forall>m\\<ge>N. \\<forall>n\\<ge>N. norm (setsum ?f (?S1 m) - setsum ?f (?S1 n)) < r\" ..\n    hence \"\\<And>m n. \\<lbrakk>N \\<le> n; n \\<le> m\\<rbrakk> \\<Longrightarrow> norm (setsum ?f (?S1 m - ?S1 n)) < r\"\n      by (simp only: setsum_diff finite_S1 S1_mono)\n    hence N: \"\\<And>m n. \\<lbrakk>N \\<le> n; n \\<le> m\\<rbrakk> \\<Longrightarrow> setsum ?f (?S1 m - ?S1 n) < r\"\n      by (simp only: norm_setsum_f)\n    show \"\\<exists>N. \\<forall>n\\<ge>N. setsum ?f (?S1 n - ?S2 n) < r\"\n    proof (intro exI allI impI)\n      fix n assume \"2 * N \\<le> n\"\n      hence n: \"N \\<le> n div 2\" by simp\n      have \"setsum ?f (?S1 n - ?S2 n) \\<le> setsum ?f (?S1 n - ?S1 (n div 2))\"\n        by (intro setsum_mono2 finite_Diff finite_S1 f_nonneg\n                  Diff_mono subset_refl S1_le_S2)\n      also have \"\\<dots> < r\"\n        using n div_le_dividend by (rule N)\n      finally show \"setsum ?f (?S1 n - ?S2 n) < r\" .\n    qed\n  qed\n  hence \"Zfun (\\<lambda>n. setsum ?g (?S1 n - ?S2 n)) sequentially\"\n    apply (rule Zfun_le [rule_format])\n    apply (simp only: norm_setsum_f)\n    apply (rule order_trans [OF norm_setsum setsum_mono])\n    apply (auto simp add: norm_mult_ineq)\n    done\n  hence 2: \"(\\<lambda>n. setsum ?g (?S1 n) - setsum ?g (?S2 n)) ----> 0\"\n    unfolding tendsto_Zfun_iff diff_0_right\n    by (simp only: setsum_diff finite_S1 S2_le_S1)\n\n  with 1 have \"(\\<lambda>n. setsum ?g (?S2 n)) ----> (\\<Sum>k. a k) * (\\<Sum>k. b k)\"\n    by (rule LIMSEQ_diff_approach_zero2)\n  thus ?thesis by (simp only: sums_def setsum_triangle_reindex)\nqed\n\nlemma Cauchy_product:\n  fixes a b :: \"nat \\<Rightarrow> 'a::{real_normed_algebra,banach}\"\n  assumes a: \"summable (\\<lambda>k. norm (a k))\"\n  assumes b: \"summable (\\<lambda>k. norm (b k))\"\n  shows \"(\\<Sum>k. a k) * (\\<Sum>k. b k) = (\\<Sum>k. \\<Sum>i\\<le>k. a i * b (k - i))\"\n  using a b\n  by (rule Cauchy_product_sums [THEN sums_unique])\n\nsubsection {* Series on @{typ real}s *}\n\nlemma summable_norm_comparison_test: \"\\<exists>N. \\<forall>n\\<ge>N. norm (f n) \\<le> g n \\<Longrightarrow> summable g \\<Longrightarrow> summable (\\<lambda>n. norm (f n))\"\n  by (rule summable_comparison_test) auto\n\nlemma summable_rabs_comparison_test: \"\\<lbrakk>\\<exists>N. \\<forall>n\\<ge>N. \\<bar>f n\\<bar> \\<le> g n; summable g\\<rbrakk> \\<Longrightarrow> summable (\\<lambda>n. \\<bar>f n :: real\\<bar>)\"\n  by (rule summable_comparison_test) auto\n\nlemma summable_rabs_cancel: \"summable (\\<lambda>n. \\<bar>f n :: real\\<bar>) \\<Longrightarrow> summable f\"\n  by (rule summable_norm_cancel) simp\n\nlemma summable_rabs: \"summable (\\<lambda>n. \\<bar>f n :: real\\<bar>) \\<Longrightarrow> \\<bar>suminf f\\<bar> \\<le> (\\<Sum>n. \\<bar>f n\\<bar>)\"\n  by (fold real_norm_def) (rule summable_norm)\n\nlemma summable_power_series:\n  fixes z :: real\n  assumes le_1: \"\\<And>i. f i \\<le> 1\" and nonneg: \"\\<And>i. 0 \\<le> f i\" and z: \"0 \\<le> z\" \"z < 1\"\n  shows \"summable (\\<lambda>i. f i * z^i)\"\nproof (rule summable_comparison_test[OF _ summable_geometric])\n  show \"norm z < 1\" using z by (auto simp: less_imp_le)\n  show \"\\<And>n. \\<exists>N. \\<forall>na\\<ge>N. norm (f na * z ^ na) \\<le> z ^ na\"\n    using z by (auto intro!: exI[of _ 0] mult_left_le_one_le simp: abs_mult nonneg power_abs less_imp_le le_1)\nqed\n\nlemma\n   fixes f :: \"nat \\<Rightarrow> real\"\n   assumes \"summable f\"\n   and \"inj g\"\n   and pos: \"!!x. 0 \\<le> f x\"\n   shows summable_reindex: \"summable (f o g)\"\n   and suminf_reindex_mono: \"suminf (f o g) \\<le> suminf f\"\n   and suminf_reindex: \"(\\<And>x. x \\<notin> range g \\<Longrightarrow> f x = 0) \\<Longrightarrow> suminf (f \\<circ> g) = suminf f\"\nproof -\n  from \\<open>inj g\\<close> have [simp]: \"\\<And>A. inj_on g A\" by(rule subset_inj_on) simp\n\n  have smaller: \"\\<forall>n. (\\<Sum>i<n. (f \\<circ> g) i) \\<le> suminf f\"\n  proof\n    fix n\n    have \"\\<forall> n' \\<in> (g ` {..<n}). n' < Suc (Max (g ` {..<n}))\" \n      by(metis Max_ge finite_imageI finite_lessThan not_le not_less_eq)\n    then obtain m where n: \"\\<And>n'. n' < n \\<Longrightarrow> g n' < m\" by blast\n\n    have \"(\\<Sum>i<n. f (g i)) = setsum f (g ` {..<n})\"\n      by (simp add: setsum.reindex)\n    also have \"\\<dots> \\<le> (\\<Sum>i<m. f i)\"\n      by (rule setsum_mono3) (auto simp add: pos n[rule_format])\n    also have \"\\<dots> \\<le> suminf f\"\n      using `summable f` \n      by (rule setsum_le_suminf) (simp add: pos)\n    finally show \"(\\<Sum>i<n. (f \\<circ>  g) i) \\<le> suminf f\" by simp\n  qed\n\n  have \"incseq (\\<lambda>n. \\<Sum>i<n. (f \\<circ> g) i)\"\n    by (rule incseq_SucI) (auto simp add: pos)\n  then obtain  L where L: \"(\\<lambda> n. \\<Sum>i<n. (f \\<circ> g) i) ----> L\"\n    using smaller by(rule incseq_convergent)\n  hence \"(f \\<circ> g) sums L\" by (simp add: sums_def)\n  thus \"summable (f o g)\" by (auto simp add: sums_iff)\n\n  hence \"(\\<lambda>n. \\<Sum>i<n. (f \\<circ> g) i) ----> suminf (f \\<circ> g)\"\n    by(rule summable_LIMSEQ)\n  thus le: \"suminf (f \\<circ> g) \\<le> suminf f\"\n    by(rule LIMSEQ_le_const2)(blast intro: smaller[rule_format])\n\n  assume f: \"\\<And>x. x \\<notin> range g \\<Longrightarrow> f x = 0\"\n\n  from \\<open>summable f\\<close> have \"suminf f \\<le> suminf (f \\<circ> g)\"\n  proof(rule suminf_le_const)\n    fix n\n    have \"\\<forall> n' \\<in> (g -` {..<n}). n' < Suc (Max (g -` {..<n}))\"\n      by(auto intro: Max_ge simp add: finite_vimageI less_Suc_eq_le)\n    then obtain m where n: \"\\<And>n'. g n' < n \\<Longrightarrow> n' < m\" by blast\n\n    have \"(\\<Sum>i<n. f i) = (\\<Sum>i\\<in>{..<n} \\<inter> range g. f i)\"\n      using f by(auto intro: setsum.mono_neutral_cong_right)\n    also have \"\\<dots> = (\\<Sum>i\\<in>g -` {..<n}. (f \\<circ> g) i)\"\n      by(rule setsum.reindex_cong[where l=g])(auto)\n    also have \"\\<dots> \\<le> (\\<Sum>i<m. (f \\<circ> g) i)\"\n      by(rule setsum_mono3)(auto simp add: pos n)\n    also have \"\\<dots> \\<le> suminf (f \\<circ> g)\"\n      using \\<open>summable (f o g)\\<close>\n      by(rule setsum_le_suminf)(simp add: pos)\n    finally show \"setsum f {..<n} \\<le> suminf (f \\<circ> g)\" .\n  qed\n  with le show \"suminf (f \\<circ> g) = suminf f\" by(rule antisym)\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Series.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.7757239283170874}}
{"text": "(*  Title:      Sigma_Algebra.thy\n\n    Author:     Stefan Richter, Markus Wenzel, TU Muenchen\n    License:    LGPL\n\nChanges for Accordance to Joe Hurd's conventions\nand additions by Stefan Richter 2002\n*)\n\nsubsection \\<open>Sigma algebras \\label{sec:sigma}\\<close>\n\ntheory Sigma_Algebra imports Main begin\n\ntext \\<open>The $\\isacommand {theory}$ command commences a formal document and enumerates the\n  theories it depends on. With the \\<open>Main\\<close> theory, a standard\n  selection of useful HOL theories excluding the real\n  numbers is loaded. This theory includes and builds upon a tiny theory of the\n  same name by Markus Wenzel. This theory as well as \\<open>Measure\\<close>\n  in \\ref{sec:measure-spaces} is heavily\n  influenced by Joe Hurd's thesis \\cite{hurd2002} and has been designed to keep the terminology as\n  consistent as possible with that work.\n\n  Sigma algebras are an elementary concept in measure\n  theory. To measure --- that is to integrate --- functions, we first have\n  to measure sets. Unfortunately, when dealing with a large universe,\n  it is often not possible to consistently assign a measure to every\n  subset. Therefore it is necessary to define the set of measurable\n  subsets of the universe. A sigma algebra is such a set that has\n  three very natural and desirable properties.\\<close>\n\ndefinition\n  sigma_algebra:: \"'a set set \\<Rightarrow> bool\" where\n  \"sigma_algebra A \\<longleftrightarrow>\n  {} \\<in> A \\<and> (\\<forall>a. a \\<in> A \\<longrightarrow> -a \\<in> A) \\<and>\n  (\\<forall>a. (\\<forall> i::nat. a i \\<in> A) \\<longrightarrow> (\\<Union>i. a i) \\<in> A)\"\n\ntext \\<open>\n  The $\\isacommand {definition}$ command defines new constants, which\n  are just named functions in HOL. Mind that the third condition\n  expresses the fact that the union of countably many sets in $A$ is\n  again a set in $A$ without explicitly defining the notion of\n  countability.\n\n  Sigma algebras can naturally be created as the closure of any set of\n  sets with regard to the properties just postulated. Markus Wenzel\n  wrote the following\n  inductive definition of the $\\isa {sigma}$ operator.\\<close>\n\n\ninductive_set\n  sigma :: \"'a set set \\<Rightarrow> 'a set set\"\n  for A :: \"'a set set\"\n  where\n    basic: \"a \\<in> A \\<Longrightarrow> a \\<in> sigma A\"\n  | empty: \"{} \\<in> sigma A\"\n  | complement: \"a \\<in> sigma A \\<Longrightarrow> -a \\<in> sigma A\"\n  | Union: \"(\\<And>i::nat. a i \\<in> sigma A) \\<Longrightarrow> (\\<Union>i. a i) \\<in> sigma A\"\n\n\ntext \\<open>He also proved the following basic facts. The easy proofs are omitted.\n\\<close>\n\ntheorem sigma_UNIV: \"UNIV \\<in> sigma A\"\n(*<*)proof -\n  have \"{} \\<in> sigma A\" by (rule sigma.empty)\n  hence \"-{} \\<in> sigma A\" by (rule sigma.complement)\n  also have \"-{} = UNIV\" by simp\n  finally show ?thesis .\nqed(*>*)\n\n\ntheorem sigma_Inter:\n  \"(\\<And>i::nat. a i \\<in> sigma A) \\<Longrightarrow> (\\<Inter>i. a i) \\<in> sigma A\"\n(*<*) proof -\n  assume \"\\<And>i::nat. a i \\<in> sigma A\"\n  hence \"\\<And>i::nat. -(a i) \\<in> sigma A\" by (rule sigma.complement)\n  hence \"(\\<Union>i. -(a i)) \\<in> sigma A\" by (rule sigma.Union)\n  hence \"-(\\<Union>i. -(a i)) \\<in> sigma A\" by (rule sigma.complement)\n  also have \"-(\\<Union>i. -(a i)) = (\\<Inter>i. a i)\" by simp\n  finally show ?thesis .\nqed(*>*)\n\ntext \\<open>It is trivial to show the connection between our first\n  definitions. We use the opportunity to introduce the proof syntax.\\<close>\n\n\ntheorem assumes sa: \"sigma_algebra A\"\n  \\<comment> \\<open>Named premises are introduced like this.\\<close>\n\n  shows sigma_sigma_algebra: \"sigma A = A\"\nproof\n\n  txt \\<open>The $\\isacommand {proof}$ command alone invokes a single standard rule to\n    simplify the goal. Here the following two subgoals emerge.\\<close>\n\n  show \"A \\<subseteq> sigma A\"\n    \\<comment> \\<open>The $\\isacommand {show}$ command starts the proof of a subgoal.\\<close>\n\n    by (auto simp add: sigma.basic)\n\n  txt \\<open>This is easy enough to be solved by an automatic step,\n    indicated by the keyword $\\isacommand {by}$. The method $\\isacommand {auto}$ is stated in parentheses, with attributes to it following.  In\n    this case, the first introduction rule for the $\\isacommand {sigma}$\n    operator is given as an extra simplification rule.\\<close>\n\n  show \"sigma A \\<subseteq> A\"\n  proof\n\n    txt \\<open>Because this goal is not quite as trivial, another proof is\n      invoked, delimiting a block as in a programming language.\\<close>\n\n    fix x\n    \\<comment> \\<open>A new named variable is introduced.\\<close>\n\n    assume \"x \\<in> sigma A\"\n\n    txt \\<open>An assumption is made that must be justified by the current proof\n      context. In this case the corresponding fact had been generated\n      by a rule automatically invoked by the inner $\\isacommand {proof}$\n      command.\\<close>\n\n    from this sa show \"x \\<in> A\"\n\n      txt \\<open>Named facts can explicitly be given to the proof methods using\n        $\\isacommand {from}$. A special name is \\<open>this\\<close>, which denotes\n        current facts generated by the last command. Usually $\\isacommand\n        {from}$ \\<open>this sa\\<close> --- remember that \\<open>sa\\<close> is an assumption from above\n        --- is abbreviated to $\\isacommand {with}$ \\<open>sa\\<close>, but in this case the order of\n        facts is relevant for the following method and $\\isacommand\n        {with}$\n        would have put the current facts last.\\<close>\n\n      by (induct rule: sigma.induct) (auto simp add: sigma_algebra_def)\n\n    txt \\<open>Two methods may be carried out at $\\isacommand {by}$. The first\n      one applies induction here via the canonical rule generated by the\n      inductive definition above, while the latter solves the\n      resulting subgoals by an automatic step involving\n      simplification.\\<close>\n\n  qed\nqed\n\ntext \"These two steps finish their respective proofs, checking\n  that all subgoals have been proven.\"\n\ntext \\<open>To end this theory we prove a special case of the \\<open>sigma_Inter\\<close> theorem above. It seems trivial that\n  the fact holds for two sets as well as for countably many.\n  We get a first taste of the cost of formal reasoning here, however. The\n  idea must be made precise by exhibiting a concrete sequence of\n  sets.\\<close>\n\nprimrec trivial_series:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> (nat \\<Rightarrow> 'a set)\"\nwhere\n  \"trivial_series a b 0 = a\"\n| \"trivial_series a b (Suc n) = b\"\n\ntext \\<open>Using $\\isacommand {primrec}$, primitive recursive functions over\n  inductively defined data types --- the natural numbers in this case ---\n  may be constructed.\\<close>\n\n\ntheorem assumes s: \"sigma_algebra A\" and a: \"a \\<in> A\" and b: \"b \\<in> A\"\n  shows sigma_algebra_inter: \"a \\<inter> b \\<in> A\"\nproof -\n    \\<comment> \\<open>This form of $\\isacommand {proof}$ foregoes the application of a rule.\\<close>\n\n  have \"a \\<inter> b = (\\<Inter>i::nat. trivial_series a b i)\"\n\n    txt \\<open>Intermediate facts that do not solve any subgoals yet are established this way.\\<close>\n\n  proof (rule set_eqI)\n\n    txt \\<open>The  $\\isacommand {proof}$ command may also take one explicit method\n      as an argument like the single rule application in this instance.\\<close>\n\n    fix x\n\n    {\n      fix i\n      assume \"x \\<in> a \\<inter> b\"\n      hence \"x \\<in> trivial_series a b i\" by (cases i) auto\n        \\<comment> \\<open>This is just an abbreviation for $\\isacommand {\"from this have\"}$.\\<close>\n    }\n\n    txt \\<open>Curly braces can be used to explicitly delimit\n      blocks. In conjunction with $\\isacommand {fix}$, universal\n      quantification over the fixed variable $i$ is achieved\n      for the last statement in the block, which is exported to the\n      enclosing block.\\<close>\n\n    hence \"x \\<in> a \\<inter> b \\<Longrightarrow> \\<forall>i. x \\<in> trivial_series a b i\"\n      by fast\n    also\n\n    txt \\<open>The statement $\\isacommand {also}$ introduces calculational\n      reasoning. This basically amounts to collecting facts. With\n      $\\isacommand {also}$, the current fact is added to a special list of\n      theorems called the calculation and\n      an automatically selected transitivity rule\n      is additionally applied from the second collected fact on.\\<close>\n\n    { assume \"\\<And>i. x \\<in> trivial_series a b i\"\n      hence \"x \\<in> trivial_series a b 0\" and \"x \\<in> trivial_series a b 1\"\n        by this+\n      hence \"x \\<in> a \\<inter> b\"\n        by simp\n    }\n    hence \"\\<forall>i. x \\<in> trivial_series a b i \\<Longrightarrow> x \\<in> a \\<inter> b\"\n      by blast\n\n    ultimately have \"x \\<in> a \\<inter> b = (\\<forall>i::nat. x \\<in> trivial_series a b i)\" ..\n\n    txt \\<open>The accumulated calculational facts including the current one\n      are exposed to the next statement by  $\\isacommand {ultimately}$ and\n      the calculation list is then erased. The two dots after the\n      statement here indicate proof by a single automatically\n      selected rule.\\<close>\n\n    also have \"\\<dots> =  (x \\<in> (\\<Inter>i::nat. trivial_series a b i))\"\n      by simp\n    finally show \"x \\<in> a \\<inter> b = (x \\<in> (\\<Inter>i::nat. trivial_series a b i))\" .\n\n    txt \\<open>The $\\isacommand {finally}$ directive behaves like $\\isacommand {ultimately}$\n      with the addition of a further transitivity rule application. A\n      single dot stands for proof by assumption.\\<close>\n\n  qed\n\n  moreover have \"(\\<Inter>i::nat. trivial_series a b i) \\<in> A\"\n  proof -\n    { fix i\n      from a b have \"trivial_series a b i \\<in> A\"\n        by (cases i) auto\n    }\n    hence \"\\<And>i. trivial_series a b i \\<in> sigma A\"\n      by (simp only: sigma.basic)\n    hence \"(\\<Inter>i::nat. trivial_series a b i) \\<in> sigma A\"\n      by (simp only: sigma_Inter)\n    with s show ?thesis\n      by (simp only: sigma_sigma_algebra)\n  qed\n\n  ultimately show ?thesis by simp\nqed\n\ntext \\<open>Of course, a like theorem holds for union instead of\n  intersection.  But as we will not need it in what follows, the\n  theory is finished with the following easy properties instead.\n  Note that the former is a kind of generalization of the last result and\n  could be used to  shorten its proof. Unfortunately, this one was needed ---\n  and therefore found --- only late in the development.\n\\<close>\n\ntheorem sigma_INTER:\n  assumes a:\"(\\<And>i::nat. i \\<in> S \\<Longrightarrow> a i \\<in> sigma A)\"\n  shows \"(\\<Inter>i\\<in>S. a i) \\<in> sigma A\"(*<*)\nproof -\n  from a have \"\\<And>i. (if i\\<in>S then {} else UNIV) \\<union> a i \\<in> sigma A\"\n    by (simp add: sigma.intros sigma_UNIV)\n  hence \"(\\<Inter>i. (if i\\<in>S then {} else UNIV) \\<union> a i) \\<in> sigma A\"\n    by (rule sigma_Inter)\n  also have \"(\\<Inter>i. (if i\\<in>S then {} else UNIV) \\<union> a i) = (\\<Inter>i\\<in>S. a i)\"\n    by force\n  finally show ?thesis .\nqed(*>*)\n\n\nlemma assumes s: \"sigma_algebra a\" shows sigma_algebra_UNIV: \"UNIV \\<in> a\"(*<*)\nproof -\n  from s have \"{}\\<in>a\" by (unfold sigma_algebra_def) blast\n  with s show ?thesis by (unfold sigma_algebra_def) auto\nqed(*>*)\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Integration/Sigma_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8856314798554445, "lm_q1q2_score": 0.7756245237088489}}
{"text": "(*  Title:      HOL/ex/Set_Theory.thy\n    Author:     Tobias Nipkow and Lawrence C Paulson\n    Copyright   1991  University of Cambridge\n*)\n\nsection \\<open>Set Theory examples: Cantor's Theorem, Schröder-Bernstein Theorem, etc.\\<close>\n\ntheory Set_Theory\nimports Main\nbegin\n\ntext\\<open>\n  These two are cited in Benzmueller and Kohlhase's system description\n  of LEO, CADE-15, 1998 (pages 139-143) as theorems LEO could not\n  prove.\n\\<close>\n\nlemma \"(X = Y \\<union> Z) =\n    (Y \\<subseteq> X \\<and> Z \\<subseteq> X \\<and> (\\<forall>V. Y \\<subseteq> V \\<and> Z \\<subseteq> V \\<longrightarrow> X \\<subseteq> V))\"\n  by blast\n\nlemma \"(X = Y \\<inter> Z) =\n    (X \\<subseteq> Y \\<and> X \\<subseteq> Z \\<and> (\\<forall>V. V \\<subseteq> Y \\<and> V \\<subseteq> Z \\<longrightarrow> V \\<subseteq> X))\"\n  by blast\n\ntext \\<open>\n  Trivial example of term synthesis: apparently hard for some provers!\n\\<close>\n\nschematic_goal \"a \\<noteq> b \\<Longrightarrow> a \\<in> ?X \\<and> b \\<notin> ?X\"\n  by blast\n\n\nsubsection \\<open>Examples for the \\<open>blast\\<close> paper\\<close>\n\nlemma \"(\\<Union>x \\<in> C. f x \\<union> g x) = \\<Union>(f ` C)  \\<union>  \\<Union>(g ` C)\"\n  \\<comment> \\<open>Union-image, called \\<open>Un_Union_image\\<close> in Main HOL\\<close>\n  by blast\n\nlemma \"(\\<Inter>x \\<in> C. f x \\<inter> g x) = \\<Inter>(f ` C) \\<inter> \\<Inter>(g ` C)\"\n  \\<comment> \\<open>Inter-image, called \\<open>Int_Inter_image\\<close> in Main HOL\\<close>\n  by blast\n\nlemma singleton_example_1:\n     \"\\<And>S::'a set set. \\<forall>x \\<in> S. \\<forall>y \\<in> S. x \\<subseteq> y \\<Longrightarrow> \\<exists>z. S \\<subseteq> {z}\"\n  by blast\n\nlemma singleton_example_2:\n     \"\\<forall>x \\<in> S. \\<Union>S \\<subseteq> x \\<Longrightarrow> \\<exists>z. S \\<subseteq> {z}\"\n  \\<comment> \\<open>Variant of the problem above.\\<close>\n  by blast\n\nlemma \"\\<exists>!x. f (g x) = x \\<Longrightarrow> \\<exists>!y. g (f y) = y\"\n  \\<comment> \\<open>A unique fixpoint theorem --- \\<open>fast\\<close>/\\<open>best\\<close>/\\<open>meson\\<close> all fail.\\<close>\n  by metis\n\n\nsubsection \\<open>Cantor's Theorem: There is no surjection from a set to its powerset\\<close>\n\nlemma cantor1: \"\\<not> (\\<exists>f:: 'a \\<Rightarrow> 'a set. \\<forall>S. \\<exists>x. f x = S)\"\n  \\<comment> \\<open>Requires best-first search because it is undirectional.\\<close>\n  by best\n\nschematic_goal \"\\<forall>f:: 'a \\<Rightarrow> 'a set. \\<forall>x. f x \\<noteq> ?S f\"\n  \\<comment> \\<open>This form displays the diagonal term.\\<close>\n  by best\n\nschematic_goal \"?S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  \\<comment> \\<open>This form exploits the set constructs.\\<close>\n  by (rule notI, erule rangeE, best)\n\nschematic_goal \"?S \\<notin> range (f :: 'a \\<Rightarrow> 'a set)\"\n  \\<comment> \\<open>Or just this!\\<close>\n  by best\n\n\nsubsection \\<open>The Schröder-Bernstein Theorem\\<close>\n\nlemma disj_lemma: \"- (f ` X) = g' ` (-X) \\<Longrightarrow> f a = g' b \\<Longrightarrow> a \\<in> X \\<Longrightarrow> b \\<in> X\"\n  by blast\n\nlemma surj_if_then_else:\n  \"-(f ` X) = g' ` (-X) \\<Longrightarrow> surj (\\<lambda>z. if z \\<in> X then f z else g' z)\"\n  by (simp add: surj_def) blast\n\nlemma bij_if_then_else:\n  \"inj_on f X \\<Longrightarrow> inj_on g' (-X) \\<Longrightarrow> -(f ` X) = g' ` (-X) \\<Longrightarrow>\n    h = (\\<lambda>z. if z \\<in> X then f z else g' z) \\<Longrightarrow> inj h \\<and> surj h\"\n  apply (unfold inj_on_def)\n  apply (simp add: surj_if_then_else)\n  apply (blast dest: disj_lemma sym)\n  done\n\nlemma decomposition: \"\\<exists>X. X = - (g ` (- (f ` X)))\"\n  apply (rule exI)\n  apply (rule lfp_unfold)\n  apply (rule monoI, blast)\n  done\n\ntheorem Schroeder_Bernstein:\n  \"inj (f :: 'a \\<Rightarrow> 'b) \\<Longrightarrow> inj (g :: 'b \\<Rightarrow> 'a)\n    \\<Longrightarrow> \\<exists>h:: 'a \\<Rightarrow> 'b. inj h \\<and> surj h\"\n  apply (rule decomposition [where f=f and g=g, THEN exE])\n  apply (rule_tac x = \"(\\<lambda>z. if z \\<in> x then f z else inv g z)\" in exI) \n    \\<comment> \\<open>The term above can be synthesized by a sufficiently detailed proof.\\<close>\n  apply (rule bij_if_then_else)\n     apply (rule_tac [4] refl)\n    apply (rule_tac [2] inj_on_inv_into)\n    apply (erule subset_inj_on [OF _ subset_UNIV])\n   apply blast\n  apply (erule ssubst, subst double_complement, erule image_inv_f_f [symmetric])\n  done\n\n\nsubsection \\<open>A simple party theorem\\<close>\n\ntext\\<open>\\emph{At any party there are two people who know the same\nnumber of people}. Provided the party consists of at least two people\nand the knows relation is symmetric. Knowing yourself does not count\n--- otherwise knows needs to be reflexive. (From Freek Wiedijk's talk\nat TPHOLs 2007.)\\<close>\n\nlemma equal_number_of_acquaintances:\nassumes \"Domain R <= A\" and \"sym R\" and \"card A \\<ge> 2\"\nshows \"\\<not> inj_on (%a. card(R `` {a} - {a})) A\"\nproof -\n  let ?N = \"%a. card(R `` {a} - {a})\"\n  let ?n = \"card A\"\n  have \"finite A\" using \\<open>card A \\<ge> 2\\<close> by(auto intro:ccontr)\n  have 0: \"R `` A <= A\" using \\<open>sym R\\<close> \\<open>Domain R <= A\\<close>\n    unfolding Domain_unfold sym_def by blast\n  have h: \"\\<forall>a\\<in>A. R `` {a} <= A\" using 0 by blast\n  hence 1: \"\\<forall>a\\<in>A. finite(R `` {a})\" using \\<open>finite A\\<close>\n    by(blast intro: finite_subset)\n  have sub: \"?N ` A <= {0..<?n}\"\n  proof -\n    have \"\\<forall>a\\<in>A. R `` {a} - {a} < A\" using h by blast\n    thus ?thesis using psubset_card_mono[OF \\<open>finite A\\<close>] by auto\n  qed\n  show \"~ inj_on ?N A\" (is \"~ ?I\")\n  proof\n    assume ?I\n    hence \"?n = card(?N ` A)\" by(rule card_image[symmetric])\n    with sub \\<open>finite A\\<close> have 2[simp]: \"?N ` A = {0..<?n}\"\n      using subset_card_intvl_is_intvl[of _ 0] by(auto)\n    have \"0 \\<in> ?N ` A\" and \"?n - 1 \\<in> ?N ` A\"  using \\<open>card A \\<ge> 2\\<close> by simp+\n    then obtain a b where ab: \"a\\<in>A\" \"b\\<in>A\" and Na: \"?N a = 0\" and Nb: \"?N b = ?n - 1\"\n      by (auto simp del: 2)\n    have \"a \\<noteq> b\" using Na Nb \\<open>card A \\<ge> 2\\<close> by auto\n    have \"R `` {a} - {a} = {}\" by (metis 1 Na ab card_eq_0_iff finite_Diff)\n    hence \"b \\<notin> R `` {a}\" using \\<open>a\\<noteq>b\\<close> by blast\n    hence \"a \\<notin> R `` {b}\" by (metis Image_singleton_iff assms(2) sym_def)\n    hence 3: \"R `` {b} - {b} <= A - {a,b}\" using 0 ab by blast\n    have 4: \"finite (A - {a,b})\" using \\<open>finite A\\<close> by simp\n    have \"?N b <= ?n - 2\" using ab \\<open>a\\<noteq>b\\<close> \\<open>finite A\\<close> card_mono[OF 4 3] by simp\n    then show False using Nb \\<open>card A \\<ge>  2\\<close> by arith\n  qed\nqed\n\ntext \\<open>\n  From W. W. Bledsoe and Guohui Feng, SET-VAR. JAR 11 (3), 1993, pages\n  293-314.\n\n  Isabelle can prove the easy examples without any special mechanisms,\n  but it can't prove the hard ones.\n\\<close>\n\nlemma \"\\<exists>A. (\\<forall>x \\<in> A. x \\<le> (0::int))\"\n  \\<comment> \\<open>Example 1, page 295.\\<close>\n  by force\n\nlemma \"D \\<in> F \\<Longrightarrow> \\<exists>G. \\<forall>A \\<in> G. \\<exists>B \\<in> F. A \\<subseteq> B\"\n  \\<comment> \\<open>Example 2.\\<close>\n  by force\n\nlemma \"P a \\<Longrightarrow> \\<exists>A. (\\<forall>x \\<in> A. P x) \\<and> (\\<exists>y. y \\<in> A)\"\n  \\<comment> \\<open>Example 3.\\<close>\n  by force\n\nlemma \"a < b \\<and> b < (c::int) \\<Longrightarrow> \\<exists>A. a \\<notin> A \\<and> b \\<in> A \\<and> c \\<notin> A\"\n  \\<comment> \\<open>Example 4.\\<close>\n  by auto \\<comment> \\<open>slow\\<close>\n\nlemma \"P (f b) \\<Longrightarrow> \\<exists>s A. (\\<forall>x \\<in> A. P x) \\<and> f s \\<in> A\"\n  \\<comment> \\<open>Example 5, page 298.\\<close>\n  by force\n\nlemma \"P (f b) \\<Longrightarrow> \\<exists>s A. (\\<forall>x \\<in> A. P x) \\<and> f s \\<in> A\"\n  \\<comment> \\<open>Example 6.\\<close>\n  by force\n\nlemma \"\\<exists>A. a \\<notin> A\"\n  \\<comment> \\<open>Example 7.\\<close>\n  by force\n\nlemma \"(\\<forall>u v. u < (0::int) \\<longrightarrow> u \\<noteq> \\<bar>v\\<bar>)\n    \\<longrightarrow> (\\<exists>A::int set. -2 \\<in> A & (\\<forall>y. \\<bar>y\\<bar> \\<notin> A))\"\n  \\<comment> \\<open>Example 8 needs a small hint.\\<close>\n  by force\n    \\<comment> \\<open>not \\<open>blast\\<close>, which can't simplify \\<open>-2 < 0\\<close>\\<close>\n\ntext \\<open>Example 9 omitted (requires the reals).\\<close>\n\ntext \\<open>The paper has no Example 10!\\<close>\n\nlemma \"(\\<forall>A. 0 \\<in> A \\<and> (\\<forall>x \\<in> A. Suc x \\<in> A) \\<longrightarrow> n \\<in> A) \\<and>\n  P 0 \\<and> (\\<forall>x. P x \\<longrightarrow> P (Suc x)) \\<longrightarrow> P n\"\n  \\<comment> \\<open>Example 11: needs a hint.\\<close>\nby(metis nat.induct)\n\nlemma\n  \"(\\<forall>A. (0, 0) \\<in> A \\<and> (\\<forall>x y. (x, y) \\<in> A \\<longrightarrow> (Suc x, Suc y) \\<in> A) \\<longrightarrow> (n, m) \\<in> A)\n    \\<and> P n \\<longrightarrow> P m\"\n  \\<comment> \\<open>Example 12.\\<close>\n  by auto\n\nlemma\n  \"(\\<forall>x. (\\<exists>u. x = 2 * u) = (\\<not> (\\<exists>v. Suc x = 2 * v))) \\<longrightarrow>\n    (\\<exists>A. \\<forall>x. (x \\<in> A) = (Suc x \\<notin> A))\"\n  \\<comment> \\<open>Example EO1: typo in article, and with the obvious fix it seems\n      to require arithmetic reasoning.\\<close>\n  apply clarify\n  apply (rule_tac x = \"{x. \\<exists>u. x = 2 * u}\" in exI, auto)\n   apply metis+\n  done\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/Set_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.8856314813647587, "lm_q1q2_score": 0.7756245221594514}}
{"text": "(*<*)\ntheory Table\n  imports Main\nbegin\n(*>*)\n\nsection \\<open>Finite tables\\<close>\n\ntype_synonym 'a tuple = \"'a option list\"\ntype_synonym 'a table = \"'a tuple set\"\n\n\nsubsection \\<open> Well-formed tuples and tables \\<close>\n\ndefinition wf_tuple :: \"nat \\<Rightarrow> nat set \\<Rightarrow> 'a tuple \\<Rightarrow> bool\" where\n  \"wf_tuple n V x \\<longleftrightarrow> length x = n \\<and> (\\<forall>i<n. x!i = None \\<longleftrightarrow> i \\<notin> V)\"\n\nlemma wf_tuple_length: \"wf_tuple n V x \\<Longrightarrow> length x = n\"\n  unfolding wf_tuple_def by simp\n\nlemma wf_tuple_Nil[simp]: \"wf_tuple n A [] = (n = 0)\"\n  unfolding wf_tuple_def by auto\n\nlemma Suc_pred': \"Suc (x - Suc 0) = (case x of 0 \\<Rightarrow> Suc 0 | _ \\<Rightarrow> x)\"\n  by (auto split: nat.splits)\n\nlemma wf_tuple_Cons[simp]:\n  \"wf_tuple n A (x # xs) \\<longleftrightarrow> ((if x = None then 0 \\<notin> A else 0 \\<in> A) \\<and>\n   (\\<exists>m. n = Suc m \\<and> wf_tuple m ((\\<lambda>x. x - 1) ` (A - {0})) xs))\"\n  unfolding wf_tuple_def\n  by (auto 0 3 simp: nth_Cons image_iff Ball_def gr0_conv_Suc Suc_pred' split: nat.splits)\n\nlemma wf_tuple_Suc: \"wf_tuple (Suc m) A a \\<longleftrightarrow> a \\<noteq> [] \\<and>\n   wf_tuple m ((\\<lambda>x. x - 1) ` (A - {0})) (tl a) \\<and> (0 \\<in> A \\<longleftrightarrow> hd a \\<noteq> None)\"\n  by (cases a) (auto simp: nth_Cons image_iff split: nat.splits)\n\nlemma wf_tuple_cong:\n  assumes \"wf_tuple n A v\" \"wf_tuple n A w\" \"\\<forall>x \\<in> A. map the v ! x = map the w ! x\"\n  shows \"v = w\"\nproof -\n  from assms(1,2) have \"length v = length w\" unfolding wf_tuple_def by simp\n  from this assms show \"v = w\"\n  proof (induct v w arbitrary: n A rule: list_induct2)\n    case (Cons x xs y ys)\n    let ?n = \"n - 1\" and ?A = \"(\\<lambda>x. x - 1) ` (A - {0})\"\n    have *: \"map the xs ! z = map the ys ! z\" if \"z \\<in> ?A\" for z\n      using that Cons(5)[THEN bspec, of \"Suc z\"]\n      by (cases z) (auto simp: le_Suc_eq split: if_splits)\n    from Cons(1,3-5) show ?case\n      by (auto intro!: Cons(2)[of ?n ?A] * split: if_splits)\n  qed simp\nqed\n\nlemma eq_replicate_None_iff:\n  \"v = replicate n None \\<longleftrightarrow> length v = n \\<and> (\\<forall>i<n. v ! i = None)\"\n  by (metis length_replicate nth_equalityI nth_replicate)\n\nlemma wf_tuple_empty_iff:\n  \"wf_tuple n {} v \\<longleftrightarrow> v = replicate n None\"\n  unfolding eq_replicate_None_iff by (simp add: wf_tuple_def)\n\nlemma wf_tuple_replicate_None_iff: \n  \"wf_tuple n X (replicate n None) \\<longleftrightarrow> X \\<subseteq> {m. n \\<le> m}\"\n  unfolding wf_tuple_def \n  using leI by (auto simp add: subset_eq)\n\nlemma wf_tuple_nemptyD:\n  \"X \\<noteq> {} \\<Longrightarrow> X \\<subseteq> {m. m < n} \\<Longrightarrow> wf_tuple n X v \\<Longrightarrow> v \\<noteq> replicate n None\"\n  by (subst wf_tuple_empty_iff[symmetric]) \n    (auto simp: wf_tuple_def subset_eq)\n\ndefinition table :: \"nat \\<Rightarrow> nat set \\<Rightarrow> 'a table \\<Rightarrow> bool\" where\n  \"table n V X \\<longleftrightarrow> (\\<forall>x\\<in>X. wf_tuple n V x)\"\n\nlemma table_Un[simp]: \"table n V X \\<Longrightarrow> table n V Y \\<Longrightarrow> table n V (X \\<union> Y)\"\n  unfolding table_def by auto\n\nlemma table_InterI: \"\\<R> \\<noteq> {} \\<Longrightarrow> \\<forall>R\\<in>\\<R>. table n X R \\<Longrightarrow> table n X (\\<Inter> \\<R>)\"\n  unfolding table_def by auto\n\nlemma table_project: \"table (Suc n) A X \\<Longrightarrow> table n ((\\<lambda>x. x - Suc 0) ` (A - {0})) (tl ` X)\"\n  unfolding table_def\n  by (auto simp: wf_tuple_Suc)\n\n\nsubsection \\<open> Tuple restriction \\<close>\n\ndefinition restrict where\n  \"restrict A v = map (\\<lambda>i. if i \\<in> A then v ! i else None) [0 ..< length v]\"\n\nlemma restrict_Nil[simp]: \"restrict A [] = []\"\n  unfolding restrict_def by auto\n\nlemma restrict_Cons[simp]: \"restrict A (x # xs) =\n  (if 0 \\<in> A then x # restrict ((\\<lambda>x. x - 1) ` (A - {0})) xs else None # restrict ((\\<lambda>x. x - 1) ` A) xs)\"\n  unfolding restrict_def\n  by (auto simp: map_upt_Suc image_iff Suc_pred' Ball_def simp del: upt_Suc split: nat.splits)\n\nlemma restrict_empty_eq: \"length v = n \\<Longrightarrow> restrict {} v = replicate n None\"\n  by (induct v arbitrary: n)\n    (simp_all add: restrict_def map_replicate_trivial)\n\nlemma restrict_restrict: \"restrict A (restrict B v) = restrict (A \\<inter> B) v\"\n  by (simp add: restrict_def)\n\nlemma sub_restrict_restrict: \"A \\<subseteq> B \\<Longrightarrow> restrict A (restrict B v) = restrict A v\"\n  by (simp add: restrict_restrict Int_absorb2)\n\nlemma restrict_update: \"y \\<notin> A \\<Longrightarrow> y < length x \\<Longrightarrow> restrict A (x[y:=z]) = restrict A x\"\n  unfolding restrict_def by (auto simp add: nth_list_update)\n\nlemma restrict_idle: \"wf_tuple n A v \\<Longrightarrow> restrict A v = v\"\n  by (induct v arbitrary: n A) (auto split: if_splits)\n\nlemma length_restrict[simp]: \"length (restrict A v) = length v\"\n  unfolding restrict_def by auto\n\nlemma map_the_restrict:\n  \"i \\<in> A \\<Longrightarrow> map the (restrict A v) ! i = map the v ! i\"\n  by (induct v arbitrary: A i) (auto simp: nth_Cons' gr0_conv_Suc split: option.splits)\n\nlemma nth_restrict': \"i < length z \\<Longrightarrow> (restrict A z)!i = (if i \\<in> A then z!i else None)\"\n  by(simp add: restrict_def)\n\nlemma wf_tuple_restrict: \"wf_tuple n B v \\<Longrightarrow> A \\<inter> B = C \\<Longrightarrow> wf_tuple n C (restrict A v)\"\n  unfolding restrict_def wf_tuple_def by auto\n\nlemma wf_tuple_restrict_simple: \"wf_tuple n B v \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> wf_tuple n A (restrict A v)\"\n  unfolding restrict_def wf_tuple_def by auto\n\nlemma nth_restrict: \"i \\<in> A \\<Longrightarrow> i < length v \\<Longrightarrow> restrict A v ! i = v ! i\"\n  unfolding restrict_def by auto\n\nlemma restrict_eq_Nil[simp]: \"restrict A v = [] \\<longleftrightarrow> v = []\"\n  unfolding restrict_def by auto\n\n\nsubsection \\<open> Empty and unit tables \\<close>\n\ndefinition \"empty_table = {}\"\n\nlemma in_empty_table[simp]: \"\\<not> x \\<in> empty_table\"\n  unfolding empty_table_def by simp\n\nlemma empty_table[simp]: \"table n V empty_table\"\n  unfolding table_def empty_table_def by simp\n\nlemma table_empty[simp]: \"table n X {}\"\n  by (simp add: table_def)\n\ndefinition \"unit_table n = {replicate n None}\"\n\nlemma unit_table_wf_tuple[simp]: \"V = {} \\<Longrightarrow> x \\<in> unit_table n \\<Longrightarrow> wf_tuple n V x\"\n  unfolding unit_table_def wf_tuple_def by simp\n\nlemma unit_table[simp]: \"V = {} \\<Longrightarrow> table n V (unit_table n)\"\n  unfolding table_def by simp\n\nlemma in_unit_table: \"v \\<in> unit_table n \\<longleftrightarrow> wf_tuple n {} v\"\n  unfolding unit_table_def wf_tuple_def by (auto intro!: nth_equalityI)\n\nlemma empty_neq_unit_table [simp]: \"empty_table \\<noteq> unit_table n\"\n  by (simp add: empty_table_def unit_table_def)\n\nlemma union_empty_table_eq [simp]: \n  \"empty_table \\<union> R = R\"\n  \"R \\<union> empty_table = R\"\n  by (simp_all add: empty_table_def)\n\nlemma table_empty_vars_iff: \n  \"table n {} R \\<longleftrightarrow> R = empty_table \\<or> R = unit_table n\"\n  unfolding table_def wf_tuple_empty_iff unit_table_def \n  by force\n\nlemmas table_empty_varsD = iffD1[OF table_empty_vars_iff, rule_format]\n\nlemma table_unit_table_iff: \"table n X (unit_table n) \\<longleftrightarrow> X \\<subseteq> {m. m \\<ge> n}\"\n  unfolding table_def unit_table_def \n  using leI by (auto simp: subset_eq wf_tuple_def)\n\nlemmas table_unitD = iffD1[OF table_unit_table_iff]\n\nlemma table_unitD2: \"table n X (unit_table n) \\<Longrightarrow> X \\<subseteq> {m. m < n} \\<Longrightarrow> X = {}\"\n  unfolding table_def \n  by (auto simp: unit_table_def wf_tuple_def subset_eq)\n\n\nsubsection \\<open> Singleton table \\<close>\n\nprimrec tabulate :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"tabulate f x 0 = []\"\n| \"tabulate f x (Suc n) = f x # tabulate f (Suc x) n\"\n\nlemma tabulate_alt: \"tabulate f x n = map f [x ..< x + n]\"\n  by (induct n arbitrary: x) (auto simp: not_le Suc_le_eq upt_rec)\n\nlemma length_tabulate[simp]: \"length (tabulate f x n) = n\"\n  by (induction n arbitrary: x) simp_all\n\nlemma map_tabulate[simp]: \"map f (tabulate g x n) = tabulate (\\<lambda>x. f (g x)) x n\"\n  by (induction n arbitrary: x) simp_all\n\nlemma nth_tabulate[simp]: \"k < n \\<Longrightarrow> tabulate f x n ! k = f (x + k)\"\nproof (induction n arbitrary: x k)\n  case (Suc n)\n  then show ?case by (cases k) simp_all\nqed simp\n\ndefinition \"singleton_table n i x = {tabulate (\\<lambda>j. if i = j then Some x else None) 0 n}\"\n\nlemma singleton_table_wf_tuple[simp]: \"V = {i} \\<Longrightarrow> x \\<in> singleton_table n i z \\<Longrightarrow> wf_tuple n V x\"\n  unfolding singleton_table_def wf_tuple_def by simp\n\nlemma singleton_table[simp]: \"V = {i} \\<Longrightarrow> table n V (singleton_table n i z)\"\n  unfolding table_def by simp\n\n\nsubsection \\<open> Join \\<close>\n\nsubsubsection \\<open> Joining tuples \\<close>\n\nfun join1 :: \"'a tuple \\<times> 'a tuple \\<Rightarrow> 'a tuple option\" where\n  \"join1 ([], []) = Some []\"\n| \"join1 (None # xs, None # ys) = map_option (Cons None) (join1 (xs, ys))\"\n| \"join1 (Some x # xs, None # ys) = map_option (Cons (Some x)) (join1 (xs, ys))\"\n| \"join1 (None # xs, Some y # ys) = map_option (Cons (Some y)) (join1 (xs, ys))\"\n| \"join1 (Some x # xs, Some y # ys) = (if x = y\n    then map_option (Cons (Some x)) (join1 (xs, ys))\n    else None)\"\n| \"join1 _ = None\"\n\nlemma join1_Some_iff: \"(\\<exists>v. join1 (x, y) = Some v) \\<longleftrightarrow> (length x = length y \n  \\<and> (\\<forall>i<length x. (x ! i = None \\<or> y ! i = None) \\<or> (\\<exists>a. x ! i = Some a \\<and> y ! i = Some a)))\"\n  apply (induct \"(x, y)\" arbitrary: x y rule: join1.induct)\n  using less_Suc_eq_0_disj by auto\n\nlemma join1_Some_wf_tuple_eqD:\n  assumes \"join1 (v1, v2) = Some v\" \n    and \"wf_tuple n X v1\" \n    and \"wf_tuple n X v2\"\n  shows \"v1 = v2\" \n    and \"v = v1\" \n    and \"v = v2\"\n  using assms \n  by (induct \"(v1, v2)\" arbitrary: v1 v2 v n X rule: join1.induct; \n      force split: if_splits)+\n\nlemma join1_eq_lengths: \"join1 (x, y) = Some z \\<Longrightarrow> length x = length y\"\n  by (induct \"(x, y)\" arbitrary: z x y rule: join1.induct) (auto split: if_splits)\n\nlemma join1_replicate_None_iff_nth: \"join1 (v1, v2) = Some (replicate n None) \n  \\<longleftrightarrow> (length v1 = length v2 \\<and> length v1 = n \\<and>  (\\<forall>i<length v1. (v1 ! i = None \\<and> v2 ! i = None)))\"\nproof (induct \"(v1, v2)\" arbitrary: v1 v2 n rule: join1.induct)\n  case (2 xs ys)\n  then show ?case\n    apply (intro iffI conjI; clarsimp)\n    using join1_eq_lengths apply blast\n    apply (metis length_Cons length_replicate list.inject replicate_Suc)\n    apply (metis eq_replicate_None_iff length_Cons list.inject replicate_Suc)\n    by auto\nnext\n  case (3 x xs ys)\n  then show ?case \n    apply (intro iffI conjI; clarsimp)\n    using join1_Some_iff apply blast\n    apply (metis length_Cons length_replicate list.inject replicate_Suc)\n    apply (metis eq_replicate_None_iff length_Cons list.inject replicate_Suc)\n    by force\nnext\n  case (4 xs y ys)\n  then show ?case \n    apply (intro iffI conjI; clarsimp)\n    using join1_Some_iff apply blast\n    apply (metis length_Cons length_replicate list.inject replicate_Suc)\n    apply (metis eq_replicate_None_iff length_Cons list.inject replicate_Suc)\n    by force\nnext\n  case (5 x xs y ys)\n  then show ?case \n    apply (intro iffI conjI; clarsimp split: if_splits)\n    using join1_Some_iff apply blast\n    apply (metis length_Cons length_replicate list.inject replicate_Suc)\n    apply (metis eq_replicate_None_iff length_Cons list.inject replicate_Suc)\n    by force\nqed simp_all\n\nlemma join1_replicate_None_iff: \"join1 (v1, v2) = Some (replicate n None) \n  \\<longleftrightarrow> v1 = replicate n None \\<and> v2 = replicate n None\"\n  using eq_replicate_None_iff\n  by (auto simp: join1_replicate_None_iff_nth)\n\nlemma join1_self: \"join1 (x, x) = Some x\"\n  by (induct \"(x, x)\" arbitrary: x rule: join1.induct) auto\n\n\n\nlemma join1_commute: \"join1 (x, y) = join1 (y, x)\"\n  by (induct \"(x, y)\" arbitrary: x y rule: join1.induct) auto\n\nlemma join1_Cons_None [simp]: \n  \"join1 (None # as, b # bs) = map_option ((#) b) (join1 (as, bs))\"\n  \"join1 (a # as, None # bs) = map_option ((#) a) (join1 (as, bs))\"\n  apply (induct \"(None # as, b # bs)\" rule: join1.induct; clarsimp)\n  by (induct \"(a # as, None # bs)\" rule: join1.induct; clarsimp)\n\nlemma join1_Cons_SomeD1: \n  \"join1 (a # as, b # bs) = Some (z # zs) \\<Longrightarrow> join1 (as, bs) = Some zs\"\n  by (induct \"(a # as, b # bs)\" arbitrary: a b as bs z zs rule: join1.induct)\n    (simp_all split: if_splits)\n\nlemma join1_Cons_SomeD2: \n  \"join1 (a # as, b # bs) = Some (z # zs) \\<Longrightarrow> (a = z \\<and> b = None) \\<or> (a = None \\<and> b = z) \\<or> (a = b \\<and> b = z)\"\n  by (induct \"(a # as, b # bs)\" arbitrary: a b as bs z zs rule: join1.induct)\n    (simp_all split: if_splits)\n\nlemma join1_Cons_Some_exI: \"join1 (a # as, bs) = Some zs \n  \\<Longrightarrow> \\<exists>b bs' z zs'. bs = b # bs' \\<and> zs = z # zs' \\<and> join1 (as, bs') = Some zs'\"\nproof-\n  assume hyp: \"join1 (a # as, bs) = Some zs\"\n  then obtain b bs' where bs_eq: \"bs = b # bs'\"\n    by (metis join1.simps(7) list.exhaust option.discI)\n  moreover obtain z zs' where zs_eq: \"zs = z # zs'\"\n    using hyp by (metis join1.simps(8) join1_commute \n        neq_Nil_conv option.distinct(1) self_join1) \n  ultimately have \"join1 (as, bs') = Some (zs')\"\n    using join1_Cons_SomeD1 hyp by auto\n  thus ?thesis\n    using bs_eq zs_eq by blast\nqed\n\n\nlemma join1_assoc1: \"Some jabc = join1 (a, jbc) \\<Longrightarrow> join1 (b, c) = Some jbc \n  \\<Longrightarrow> \\<exists>y. join1 (a, b) = Some y\"\nproof ((induct \"(a,b)\" arbitrary: a b c jbc jabc rule: join1.induct), \n    goal_cases NilNil Nones SNone NSome SSome Nil1 Nil2 Nil3 Nil4)\n  case (Nones as bs c jbc jabc)\n  then show ?case\n    by (metis join1.simps(2) join1_Cons_Some_exI \n        list.inject option.simps(9))\nnext\n  case (SNone a as bs c jbc jabc)\n  then show ?case\n    by (metis (no_types, lifting) join1.simps(3) join1_Cons_Some_exI \n        list.inject option.simps(9)) \nnext\n  case (NSome as b bs c jbc jabc)\n  then show ?case\n    by (metis (no_types, lifting) join1.simps(4) join1_Cons_Some_exI \n        list.inject option.simps(9))\nnext\n  case (SSome a as b bs c jbc jabc)\n  obtain bc bcs abc abcs c' cs \n    where jbc_eq: \"jbc = bc # bcs\" \n    and jabc_eq: \"jabc = abc # abcs\"\n    and c_eq: \"c = c' # cs\"\n    and eq1: \"join1 (as, bcs) = Some abcs\"\n    and eq2: \"join1 (bs, cs) = Some bcs\"\n    using join1_Cons_Some_exI[OF SSome(3)] \n      join1_Cons_Some_exI[OF SSome(2)[symmetric]]\n    by auto\n  note join1_Cons_SomeD2[OF SSome(3)[unfolded c_eq jbc_eq], simplified]\n    join1_Cons_SomeD2[OF SSome(2)[symmetric, unfolded jabc_eq jbc_eq], simplified]\n  hence \"a = b\"\n    by blast\n  thus ?case \n    using SSome(1)[OF _ eq1[symmetric] eq2]\n    by auto\nnext\n  case (Nil1 a as c jbc jabc)\n  then show ?case\n    using join1_eq_lengths by force\nnext\n  case (Nil2 a as c jbc jabc)\n  then show ?case \n    using join1_eq_lengths by force\nqed (auto dest: join1_Cons_Some_exI)\n\nlemma join1_assoc2: \"Some jabc = join1 (a, jbc) \\<Longrightarrow> join1 (b, c) = Some jbc \n  \\<Longrightarrow> join1 (a, jbc) = join1 (the (join1 (a, b)), c)\"\nproof ((induct \"(a,b)\" arbitrary: a b c jbc jabc rule: join1.induct), \n    goal_cases NilNil Nones SNone NSome SSome Nil1 Nil2 Nil3 Nil4)\n  case (NilNil c jbc jabc)\n  then show ?case\n    by clarsimp (metis join1_commute self_join1)\nnext\n  case (Nones as bs c jbc jabc)\n  then obtain abc abcs bc bcs c' cs\n    where jbc_eq: \"jbc = bc # bcs\" \n    and jabc_eq: \"jabc = abc # abcs\"\n    and c_eq: \"c = c' # cs\"\n    and eq1: \"join1 (as, bcs) = Some abcs\"\n    and eq2: \"join1 (bs, cs) = Some bcs\"\n    using join1_Cons_Some_exI[OF Nones(3)] \n      join1_Cons_Some_exI[OF Nones(2)[symmetric]]\n    by auto \n  hence \"c' = bc\"\n    using Nones(3) by simp\n  then show ?case\n    using Nones(1)[OF eq1[symmetric] eq2] Nones(2,3)\n    apply (clarsimp simp: c_eq jbc_eq)\n    by (metis (no_types, lifting) eq1 join1_Cons_None(1) join1_assoc1 \n        option.discI option.map_sel)\nnext\n  case (SNone a as bs c jbc jabc)\n  then obtain abc abcs bc bcs c' cs\n    where jbc_eq: \"jbc = bc # bcs\"\n    and jabc_eq: \"jabc = abc # abcs\"\n    and c_eq: \"c = c' # cs\"\n    and eq1: \"join1 (as, bcs) = Some abcs\"\n    and eq2: \"join1 (bs, cs) = Some bcs\"\n    using join1_Cons_Some_exI[OF SNone(3)] \n      join1_Cons_Some_exI[OF SNone(2)[symmetric]]\n    by auto \n  hence \"c' = bc\" \"abc = Some a\"\n    using SNone(2,3) \n    by simp_all (metis join1_Cons_SomeD2 not_None_eq)\n  then show ?case\n    using SNone(1)[OF eq1[symmetric] eq2] SNone(2,3)\n    apply (clarsimp simp: c_eq jbc_eq)\n    by (smt (z3) join1.simps(1,3,5,6) join1_Cons_SomeD2 \n        join1_Cons_Some_exI join1_assoc1 list.inject option.distinct(1)  \n        option.exhaust_sel option.inject option.map_disc_iff)\nnext\n  case (NSome as b bs c jbc jabc)\n  then obtain abc abcs bc bcs c' cs\n    where jbc_eq: \"jbc = bc # bcs\"\n    and jabc_eq: \"jabc = abc # abcs\"\n    and c_eq: \"c = c' # cs\"\n    and eq1: \"join1 (as, bcs) = Some abcs\"\n    and eq2: \"join1 (bs, cs) = Some bcs\"\n    using join1_Cons_Some_exI[OF NSome(3)] \n      join1_Cons_Some_exI[OF NSome(2)[symmetric]]\n    by auto \n  note join1_Cons_SomeD2[OF NSome(3)[unfolded c_eq jbc_eq], simplified]\n    join1_Cons_SomeD2[OF NSome(2)[symmetric, unfolded jabc_eq jbc_eq], simplified]\n  hence \"abc = bc\" and \"bc = Some b\" \n    and \"c' = None \\<or> c' = Some b\"\n    by blast+\n  then show ?case\n    using NSome(1)[OF eq1[symmetric] eq2] NSome(2,3)\n    unfolding c_eq jbc_eq\n    apply (elim disjE; clarsimp simp: c_eq jbc_eq)\n    by (metis (no_types, lifting) eq1 join1_Cons_None(2) join1_assoc1 option.distinct(1) option.map_sel)\n      (metis eq1 join1.simps(5) join1_assoc1 option.map_sel option.simps(3))\nnext\n  case (SSome a as b bs c jbc jabc)\n    then obtain abc abcs bc bcs c' cs\n    where jbc_eq: \"jbc = bc # bcs\"\n    and jabc_eq: \"jabc = abc # abcs\"\n    and c_eq: \"c = c' # cs\"\n    and eq1: \"join1 (as, bcs) = Some abcs\"\n    and eq2: \"join1 (bs, cs) = Some bcs\"\n    using join1_Cons_Some_exI[OF SSome(3)] \n      join1_Cons_Some_exI[OF SSome(2)[symmetric]]\n    by auto \n  note join1_Cons_SomeD2[OF SSome(3)[unfolded c_eq jbc_eq], simplified]\n    join1_Cons_SomeD2[OF SSome(2)[symmetric, unfolded jabc_eq jbc_eq], simplified]\n  hence \"a = b\" and \"abc = bc\" \n    and \"bc = Some b\" and \"c' = None \\<or> c' = Some b\"\n    by blast+\n  then show ?case\n    using SSome(1)[OF _ eq1[symmetric] eq2] SSome(2,3)\n    unfolding c_eq jbc_eq\n    apply (elim disjE; clarsimp simp: c_eq jbc_eq)\n    by (metis (no_types, lifting) eq1 join1_Cons_None(2) join1_assoc1 option.distinct(1) option.map_sel)\n      (metis eq1 join1.simps(5) join1_assoc1 option.map_sel option.simps(3))\nqed (auto dest: join1_assoc1)\n\nlemma join1_wf_tuple:\n  \"join1 (v1, v2) = Some v \\<Longrightarrow> wf_tuple n A v1 \\<Longrightarrow> wf_tuple n B v2 \\<Longrightarrow> wf_tuple n (A \\<union> B) v\"\n  by (induct \"(v1, v2)\" arbitrary: n v v1 v2 A B rule: join1.induct)\n    (auto simp: image_Un Un_Diff split: if_splits)\n\nlemma wf_tuple_join1I: \"wf_tuple n X v1 \\<Longrightarrow> wf_tuple n Y v2 \\<Longrightarrow> Z = X \\<union> Y \n  \\<Longrightarrow> join1 (v1, v2) = Some v \\<Longrightarrow> wf_tuple n Z v\"\n  using join1_wf_tuple by blast\n\nlemma join1_replicate_None:\n  assumes \"length x = n\"\n  defines \"y \\<equiv> replicate n None\"\n  shows \"join1 (x, y) = Some x\"\n    and \"join1 (y, x) = Some x\"\n  using assms\n  by (induct \"(x,y)\" arbitrary: n x y \n      rule: join1.induct; clarsimp)+\n\nlemma join1_Some_sub_tuples1:\n  \"join1 (x, y) = Some z \\<Longrightarrow> wf_tuple n X x \\<Longrightarrow> wf_tuple n Y y \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> x = z\"\n  apply (induct \"(x, y)\" arbitrary: x y z n X Y rule: join1.induct; clarsimp split: if_splits)\nproof (goal_cases NoneNone SomeNone NoneSome SomeSome)\n  case nn: (NoneNone xs ys X Y w m)\n  show ?case \n    apply(rule nn(1)[OF refl nn(6,7)])\n    using nn(2,3,4) leI zero_less_iff_neq_zero \n    by (fastforce simp: subset_eq)+\nnext\n  case sn: (SomeNone xs ys X Y w m)\n  show ?case\n    apply (rule sn(1)[OF refl sn(6,7)])\n    using sn(2,3,4,5) \n    by (auto simp: subset_eq image_iff)\nnext\n  case ns: (NoneSome xs ys X Y w m)\n  thus ?case \n    by auto\nnext\n  case ss: (SomeSome x xs X Y w m)\n  show ?case \n    apply(rule ss(2)[OF refl ss(5,6)])\n    using ss(1,2,4,5)\n    by (auto simp: subset_eq image_iff)\nqed\n\nlemma join1_Some_sub_tuples2:\n  \"join1 (x, y) = Some z \\<Longrightarrow> wf_tuple n X x \\<Longrightarrow> wf_tuple n Y y \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> y = restrict Y z\"\n  apply (induct \"(x, y)\" arbitrary: x y z n X Y rule: join1.induct; clarsimp split: if_splits)\nproof (goal_cases NoneNone SomeNone NoneSome SomeSome)\n  case nn: (NoneNone xs ys X Y w m)\n  show ?case \n    apply(rule nn(1)[OF refl nn(6,7)])\n    using nn(2,3,4) leI zero_less_iff_neq_zero \n    by (fastforce simp: subset_eq)+\nnext\n  case sn: (SomeNone xs ys X Y w m)\n  show ?case\n    apply (rule sn(1)[OF refl sn(6,7)])\n    using sn(2,3,4,5) \n    by (auto simp: subset_eq image_iff)\nnext\n  case ns: (NoneSome xs ys X Y w m)\n  show ?case \n    apply (rule ns(1)[OF refl ns(6,7)])\n    using ns(2,3,4,5) \n    by (auto simp: subset_eq image_iff)\nnext\n  case ss: (SomeSome x xs X Y w m)\n  show ?case \n    apply(rule ss(2)[OF refl ss(5,6)])\n    using ss(1,2,4,5)\n    by (auto simp: subset_eq image_iff)\nqed\n\n\nsubsubsection \\<open> Joining tables \\<close>\n\ndefinition join :: \"'a table \\<Rightarrow> bool \\<Rightarrow> 'a table \\<Rightarrow> 'a table\" \n  where \"join A pos B = (if pos then Option.these (join1 ` (A \\<times> B))\n    else A - Option.these (join1 ` (A \\<times> B)))\"\n\nabbreviation nat_join :: \"'a option list set \\<Rightarrow> 'a option list set \n  \\<Rightarrow> 'a option list set\" (infixl \"\\<bowtie>\" 70)\n  where \"R1 \\<bowtie> R2 \\<equiv> join R1 True R2\"\n\nlemma join_True_code[code]: \"A \\<bowtie> B = (\\<Union>a \\<in> A. \\<Union>b \\<in> B. set_option (join1 (a, b)))\"\n  unfolding join_def by (force simp: Option.these_def image_iff)\n\nlemma join_False_alt: \"join X False Y = X - X \\<bowtie> Y\"\n  unfolding join_def by auto\n\nlemma join_False_code[code]: \"join A False B = {a \\<in> A. \\<forall>b \\<in> B. join1 (a, b) \\<noteq> Some a}\"\n  unfolding join_False_alt join_True_code\n  by (auto simp: Option.these_def image_iff dest: self_join1)\n\nlemma join_commute: \"R1 \\<bowtie> R2 = R2 \\<bowtie> R1\"\n  unfolding join_def \n  using join1_commute\n  by (auto simp: image_def Option.these_def)\n    fastforce+\n\nlemma join_assoc: \"R1 \\<bowtie> (R2 \\<bowtie> R3) = R1 \\<bowtie> R2 \\<bowtie> R3\"\n  unfolding join_def \n  apply (clarsimp simp: Option.these_def)\n  apply (intro set_eqI iffI; clarsimp simp: image_iff)\n   apply (rename_tac a jabc b c jbc)\n   apply (rule_tac x=\"Some jabc\" in exI, clarsimp)\n  apply (intro conjI)\n    apply (rule_tac x=\"join1 (a,b)\" in exI; intro conjI; clarsimp?)\n     apply (rule_tac x=a in bexI; clarsimp?)\n      apply (rule_tac x=b in bexI; clarsimp)\n  using join1_assoc1 apply force\n    apply (rule_tac x=c in bexI; clarsimp?)\n  using join1_assoc2 apply force\n   apply metis\n   apply (rename_tac jabc a b c jab)\n   apply (rule_tac x=\"Some jabc\" in exI, clarsimp)\n  apply (intro conjI)\n   apply (rule_tac x=a in bexI; clarsimp?)\n    apply (rule_tac x=\"join1 (b,c)\" in exI; intro conjI; clarsimp?)\n     apply (rule_tac x=b in bexI; clarsimp?)\n     apply (rule_tac x=c in bexI; clarsimp?)\n    apply (metis join1_assoc1 join1_commute)\n  apply (smt (verit, best) join1_assoc2 join1_commute)\n  using join1_assoc1 by force\n\nlemma join_wf_tuple: \"x \\<in> join X b Y \\<Longrightarrow> \\<forall>v \\<in> X. wf_tuple n A v \\<Longrightarrow> \\<forall>v \\<in> Y. wf_tuple n B v \n  \\<Longrightarrow> (\\<not> b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow> A \\<union> B = C \\<Longrightarrow> wf_tuple n C x\"\n  unfolding join_def\n  by (fastforce simp: Option.these_def image_iff sup_absorb1 dest: join1_wf_tuple split: if_splits)\n\nlemma join_table: \"table n A X \\<Longrightarrow> table n B Y \\<Longrightarrow> (\\<not> b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow> A \\<union> B = C \\<Longrightarrow>\n  table n C (join X b Y)\"\n  unfolding table_def by (auto elim!: join_wf_tuple)\n\nlemma join1_Some_restrict:\n  fixes x y :: \"'a tuple\"\n  assumes \"wf_tuple n A x\" \"wf_tuple n B y\"\n  shows \"join1 (x, y) = Some z \\<longleftrightarrow> wf_tuple n (A \\<union> B) z \\<and> restrict A z = x \\<and> restrict B z = y\"\n  using assms\nproof (induct \"(x, y)\" arbitrary: n x y z A B rule: join1.induct)\n  case (2 xs ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nnext\n  case (3 x xs ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nnext\n  case (4 xs y ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nnext\n  case (5 x xs y ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nqed auto\n\n\n\nlemma in_joinI: \"table n A X \\<Longrightarrow> table n B Y \\<Longrightarrow> (\\<not>b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow> wf_tuple n (A \\<union> B) v \\<Longrightarrow>\n  restrict A v \\<in> X \\<Longrightarrow> (b \\<Longrightarrow> restrict B v \\<in> Y) \\<Longrightarrow> (\\<not>b \\<Longrightarrow> restrict B v \\<notin> Y) \\<Longrightarrow> v \\<in> join X b Y\"\n  unfolding table_def\n  by (subst join_restrict) (auto)\n\nlemma in_joinE: \"v \\<in> join X b Y \\<Longrightarrow> table n A X \\<Longrightarrow> table n B Y \\<Longrightarrow> (\\<not> b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow>\n  (wf_tuple n (A \\<union> B) v \\<Longrightarrow> restrict A v \\<in> X \\<Longrightarrow> if b then restrict B v \\<in> Y else restrict B v \\<notin> Y \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding table_def\n  by (subst (asm) join_restrict) (auto)\n\nlemma join_restrict_table:\n  assumes \"table n A X\" \"table n B Y\" \"\\<not> b \\<Longrightarrow> B \\<subseteq> A\"\n  shows \"v \\<in> join X b Y \\<longleftrightarrow>\n    wf_tuple n (A \\<union> B) v \\<and> restrict A v \\<in> X \\<and> (if b then restrict B v \\<in> Y else restrict B v \\<notin> Y)\"\n  using assms unfolding table_def\n  by (simp add: join_restrict)\n\nlemma join_restrict_annotated:\n  fixes X Y :: \"'a tuple set\"\n  assumes \"\\<not> b =simp=> B \\<subseteq> A\"\n  shows \"join {v. wf_tuple n A v \\<and> P v} b {v. wf_tuple n B v \\<and> Q v} =\n    {v. wf_tuple n (A \\<union> B) v \\<and> P (restrict A v) \\<and> (if b then Q (restrict B v) else \\<not> Q (restrict B v))}\"\n  using assms\n  by (intro set_eqI, subst join_restrict) (auto simp: wf_tuple_restrict_simple simp_implies_def)\n\nlemma join_unit_table:\n  \"table n X R \\<Longrightarrow> R \\<bowtie> unit_table n = R\"\n  \"table n X R \\<Longrightarrow> unit_table n \\<bowtie> R = R\"\n  by (auto simp: join_def image_def unit_table_def table_def \n      wf_tuple_def join1_replicate_None Option.these_def)\n\nlemma join_unit_unit [simp]: \"join (unit_table n) True (unit_table n) = unit_table n\"\n  by (rule join_unit_table[OF unit_table[OF refl]])\n\nlemma join_unitD: \"table n X R1 \\<Longrightarrow> table n Y R2 \\<Longrightarrow> join R1 True R2 = unit_table n \n  \\<Longrightarrow> R1 = unit_table n \\<and> R2 = unit_table n\"\n  by (clarsimp simp: unit_table_def join_def Option.these_def image_def set_eq_iff)\n    (metis (no_types, opaque_lifting) join1_replicate_None join1_replicate_None_iff \n      option.sel table_def wf_tuple_def)\n\nlemma join_empty [simp]:\n  \"R \\<bowtie> {} = {}\"\n  \"{} \\<bowtie> R = {}\"\n  by (auto simp: join_def Option.these_def)\n\nlemma join_empty_table:\n  \"R \\<bowtie> empty_table = empty_table\"\n  \"empty_table \\<bowtie> R = empty_table\"\n  by (auto simp: empty_table_def)\n\nlemma join_sub_tables_eq:\n  \"table n X R\\<^sub>1 \\<Longrightarrow> table n Y R\\<^sub>2 \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> R\\<^sub>1 \\<bowtie> R\\<^sub>2 = {v \\<in> R\\<^sub>1. (restrict Y v) \\<in> R\\<^sub>2 }\"\n  using join1_Some_sub_tuples1 join1_Some_sub_tuples2\n  unfolding table_def join_def \n  by (auto simp: Option.these_def image_iff)\n    (smt (z3) Un_absorb2 join1_Some_restrict option.sel restrict_idle)+\n\nlemma join_eq_interI: \n  \"table n X R1 \\<Longrightarrow> table n X R2 \\<Longrightarrow> R1 \\<bowtie> R2 = R1 \\<inter> R2\"\n  apply (intro set_eqI iffI; clarsimp simp: join_def image_def Option.these_def table_def)\n  using join1_Some_wf_tuple_eqD(2,3) apply blast\n  using join1_self by (metis option.sel)\n\nlemma foldr_join_tables_eq_InterI:\n  \"\\<forall>R\\<in>set Rs. table n X R \\<Longrightarrow> foldr (\\<bowtie>) Rs (unit_table n) = \n  (if Rs = [] then unit_table n else (\\<Inter> (set Rs)))\"\n  apply (induct Rs arbitrary: n X; clarsimp simp: join_unit_table(1))\n  using table_InterI[of \"set _\"] join_eq_interI\n  by (metis set_empty2)\n\nlemma join_union_distrib: \n  \"R1 \\<bowtie> (R2 \\<union> R3) = R1 \\<bowtie> R2 \\<union> R1 \\<bowtie> R3\"\n  \"(R1 \\<union> R2) \\<bowtie> R3 = R1 \\<bowtie> R3 \\<union> R2 \\<bowtie> R3\"\n  by (auto simp: join_True_code)\n\nlemma join_Un_distrib:\n  \"R \\<bowtie> (\\<Union>i\\<in>\\<I>. \\<R> i) = (\\<Union>i\\<in>\\<I>. R \\<bowtie> (\\<R> i))\"\n  \"(\\<Union>i\\<in>\\<I>. \\<R> i) \\<bowtie> R = (\\<Union>i\\<in>\\<I>. (\\<R> i) \\<bowtie> R)\"\n  unfolding Union_eq \n  by (auto; smt (verit, best) UN_E UN_I join_True_code mem_Collect_eq)+\n\n\nsubsection \\<open> Union of tables \\<close>\n\nlemma table_union_must_subset:\n  \"R\\<^sub>1 \\<noteq> {} \\<Longrightarrow> \\<forall>x\\<in>X\\<union>Y. x < n \\<Longrightarrow> table n X R\\<^sub>1 \\<Longrightarrow> table n (X \\<union> Y) (R\\<^sub>1 \\<union> R\\<^sub>2) \\<Longrightarrow> Y \\<subseteq> X\"\n  \"R\\<^sub>2 \\<noteq> {} \\<Longrightarrow> \\<forall>x\\<in>X\\<union>Y. x < n \\<Longrightarrow> table n Y R\\<^sub>2 \\<Longrightarrow> table n (X \\<union> Y) (R\\<^sub>1 \\<union> R\\<^sub>2) \\<Longrightarrow> X \\<subseteq> Y\"\n  by (clarsimp simp: table_def) (clarsimp simp: table_def wf_tuple_def, blast)+\n\nlemma union_unit_iff: \"R1 \\<union> R2 = unit_table n \n  \\<longleftrightarrow> (R1 = unit_table n \\<and> R2 = {}) \\<or> (R1 = {} \\<and> R2 = unit_table n) \\<or> (R1 = unit_table n \\<and> R2 = unit_table n)\"\n  apply (clarsimp simp: unit_table_def, intro iffI)\n  by (metis singleton_Un_iff) auto\n\nlemma union_unitD: \n  assumes \"R1 \\<union> R2 = unit_table n\"\n  shows \"R1 = unit_table n \\<or> R2 = unit_table n\"\n    and \"R1 = {} \\<longrightarrow> R2 = unit_table n\"\n    and \"R2 = {} \\<longrightarrow> R1 = unit_table n\"\n  using assms unfolding union_unit_iff\n  by blast+\n\ncorollary \n  \"R\\<^sub>1 \\<noteq> {} \\<Longrightarrow> R\\<^sub>2 \\<noteq> {} \\<Longrightarrow> \\<forall>x\\<in>X\\<union>Y. x < n \\<Longrightarrow> table n X R\\<^sub>1 \\<Longrightarrow> table n Y R\\<^sub>2 \n  \\<Longrightarrow> X = Y \\<longleftrightarrow> table n (X \\<union> Y) (R\\<^sub>1 \\<union> R\\<^sub>2)\"\n  apply (rule iffI)\n  apply (auto simp: table_def wf_tuple_def)[1]\n  using table_union_must_subset(1,2)[of _ X Y n _] by auto blast\n\n\nsubsection \\<open> N-ary join \\<close>\n\nterm sum\nterm comm_monoid_set.F\nterm Finite_Set.fold\n\ninterpretation join_comp_fun: comp_fun_commute_on \"UNIV\" \"(\\<bowtie>)\"\n  apply standard\n  apply (rule ext; clarsimp)\n  apply (subst join_assoc)\n  apply (subst join_assoc)\n  apply (subst join_commute)\n  by simp\n\ninterpretation join_ab_semigroup: ab_semigroup_mult \"(\\<bowtie>)\"\n  by (standard, clarsimp simp: join_assoc, clarsimp simp: join_commute)\n\ninterpretation join_monoid: comm_monoid_set \"(\\<bowtie>)\" \"unit_table n\"\n  apply (standard)\n  oops\n\nlemma join_idemp[simp]: \"table n X R \\<Longrightarrow> R \\<bowtie> R = R\"\n  apply (intro set_eqI iffI; clarsimp simp: join_def Option.these_def image_iff table_def)\n  using join1_Some_wf_tuple_eqD(2)\n  by blast (metis join1_self option.sel)\n\ndefinition nary_join :: \"nat \\<Rightarrow> 'a option list set set \\<Rightarrow> 'a option list set\"\n  where eq_fold: \"nary_join n \\<R> = Finite_Set.fold (\\<bowtie>) (unit_table n) \\<R>\"\n\nlemma infinite_nary_join [simp]: \"\\<not> finite \\<R> \\<Longrightarrow> nary_join n \\<R> = unit_table n\"\n  by (simp add: eq_fold)\n\nlemma nary_join_empty [simp]: \"nary_join n {} = unit_table n\"\n  by (simp add: eq_fold)\n\nlemma nary_join_insert [simp]: \n  \"finite \\<R> \\<Longrightarrow> R \\<notin> \\<R> \\<Longrightarrow> nary_join n (insert R \\<R>) = R \\<bowtie> nary_join n \\<R>\"\n  \"finite \\<R> \\<Longrightarrow> R \\<in> \\<R> \\<Longrightarrow> nary_join n (insert R \\<R>) = nary_join n \\<R>\"\n  by (simp add: eq_fold)\n    (induct \\<R> arbitrary: R rule: infinite_finite_induct, simp_all add: insert_absorb)\n\nlemma nary_join_set: \"nary_join n (set (R # Rs)) \n  = (if R \\<in> set Rs then nary_join n (set Rs) else R \\<bowtie> nary_join n (set Rs))\"\n  by (simp split: if_splits)\n\nlemma nary_join_with_empty: \"finite \\<R> \\<Longrightarrow> {} \\<in> \\<R> \\<Longrightarrow> nary_join n \\<R> = {}\"\n  by (induct \\<R> rule: infinite_finite_induct) auto\n\nlemma join_nary_join_elem: \"\\<forall>R\\<in>\\<R>. table n (X R) R \\<Longrightarrow> finite \\<R> \\<Longrightarrow> R \\<in> \\<R> \n  \\<Longrightarrow> R \\<bowtie> nary_join n \\<R> = nary_join n \\<R>\"\nproof (induct \\<R> arbitrary: R rule: infinite_finite_induct)\n  case (insert C \\<C>)\n  hence \"C \\<bowtie> (C \\<bowtie> nary_join n \\<C>) = C \\<bowtie> nary_join n \\<C>\"\n    by (simp add: join_assoc)\n      (subst join_idemp, auto)\n  hence \"R = C \\<Longrightarrow> ?case\"\n    using insert by simp\n  moreover have \"R \\<in> \\<C> \\<Longrightarrow> ?case\"\n    using insert.hyps insert.prems\n    by (clarsimp, subst join_assoc, subst join_commute)\n      (clarsimp simp: join_assoc[symmetric])\n  ultimately show ?case \n    using insert.prems by blast\nqed simp_all\n\nlemma nary_join_insert_table: \n  \"\\<forall>R\\<in>\\<R>. \\<exists>X. table n X R \\<Longrightarrow> finite \\<R> \\<Longrightarrow> nary_join n (insert R \\<R>) = R \\<bowtie> nary_join n \\<R>\"\n  apply (induct \\<R> arbitrary: R rule: infinite_finite_induct)\n  by (simp, simp) (metis insert_absorb join_nary_join_elem nary_join_insert(1))\n\nlemma nary_join_remove:\n  assumes \"finite \\<R>\" and \"R \\<in> \\<R>\"\n  shows \"nary_join n \\<R> = R \\<bowtie> nary_join n (\\<R> - {R})\"\nproof -\n  from \\<open>R \\<in> \\<R>\\<close> obtain \\<R>' where R_eq: \"\\<R> = insert R \\<R>'\" and \"R \\<notin> \\<R>'\"\n    by (auto dest: mk_disjoint_insert)\n  moreover from \\<open>finite \\<R>\\<close> R_eq have \"finite \\<R>'\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma nary_join_insert_remove: \n  \"finite \\<R> \\<Longrightarrow> nary_join n (insert R \\<R>) = R \\<bowtie> nary_join n (\\<R> - {R})\"\n  by (cases \"R \\<in> \\<R>\") (simp_all add: nary_join_remove insert_absorb)\n\nlemma nary_join_insert_if: \"finite \\<R> \n  \\<Longrightarrow> nary_join n (insert R \\<R>) = (if R \\<in> \\<R> then nary_join n \\<R> else R \\<bowtie> nary_join n \\<R>)\"\n  by (cases \"R \\<in> \\<R>\") (simp_all add: insert_absorb)\n\nlemma nary_join_neutral: \"\\<forall>R\\<in>\\<R>. R = unit_table n \\<Longrightarrow> nary_join n \\<R> = unit_table n\"\n  by (induct \\<R> rule: infinite_finite_induct) simp_all\n\nlemma table_nary_joinI: \"finite \\<R> \\<Longrightarrow> \\<forall>R\\<in>\\<R>. table n (X R) R \n  \\<Longrightarrow> table n (\\<Union>R\\<in>\\<R>. X R) (nary_join n \\<R>)\"\n  by (induct \\<R> rule: infinite_finite_induct) (simp_all, metis join_table)\n\nlemma nary_join_union_inter:\n  assumes \"finite \\<C>\" and \"finite \\<D>\"\n  shows \"nary_join n (\\<C> \\<union> \\<D>) \\<bowtie> nary_join n (\\<C> \\<inter> \\<D>) = nary_join n \\<C> \\<bowtie> nary_join n \\<D>\"\n  using assms\nproof (induct \\<C>)\n  case empty\n  then show ?case \n    by (simp add: join_commute)\nnext\n  case (insert x \\<C>)\n  then show ?case\n    by (auto simp: insert_absorb Int_insert_left; \n        simp add: join_ab_semigroup.mult.left_commute join_ab_semigroup.mult_assoc)\nqed\n\ncorollary nary_join_union_inter_neutral:\n  assumes \"finite \\<C>\" and \"finite \\<D>\" \n    and \"\\<forall>R\\<in>\\<C>\\<inter>\\<D>. R = unit_table n\"\n    and \"\\<forall>R\\<in>\\<C>\\<union>\\<D>. table n (X R) R\"\n  shows \"nary_join n (\\<C> \\<union> \\<D>) = nary_join n \\<C> \\<bowtie> nary_join n \\<D>\"\n  using nary_join_union_inter[OF assms(1,2)] \n    nary_join_neutral[OF assms(3)]\n    table_nary_joinI[OF _ assms(4)]\n  by (metis assms(1,2) finite_Un join_unit_table(1))\n\ncorollary nary_join_union_disjoint:\n  assumes \"finite \\<C>\" and \"finite \\<D>\"     \n    and \"\\<forall>R\\<in>\\<C>\\<union>\\<D>. table n (X R) R\"\n    and \"\\<C> \\<inter> \\<D> = {}\"\n  shows \"nary_join n (\\<C> \\<union> \\<D>) = nary_join n \\<C> \\<bowtie> nary_join n \\<D>\"\n  using assms by (simp add: nary_join_union_inter_neutral)\n\nlemma nary_join_union_diff:\n  assumes \"finite \\<C>\" and \"finite \\<D>\" and \"\\<forall>R\\<in>\\<C>\\<union>\\<D>. table n (X R) R\"\n  shows \"nary_join n (\\<C> \\<union> \\<D>) = nary_join n (\\<C> - \\<D>) \\<bowtie> nary_join n (\\<D> - \\<C>) \\<bowtie> nary_join n (\\<C> \\<inter> \\<D>)\"\nproof -\n  have \"\\<C> \\<union> \\<D> = (\\<C> - \\<D>) \\<union> (\\<D> - \\<C>) \\<union> \\<C> \\<inter> \\<D>\"\n    by auto\n  with assms show ?thesis\n    apply simp\n    by (subst nary_join_union_disjoint, simp_all; (subst nary_join_union_disjoint)?) auto\nqed\n\nlemma nary_join_subset_diff:\n  assumes \"\\<D> \\<subseteq> \\<C>\" and \"finite \\<C>\" and \"\\<forall>R\\<in>\\<C>. table n (X R) R\"\n  shows \"nary_join n \\<C> = nary_join n (\\<C> - \\<D>) \\<bowtie> nary_join n \\<D>\"\nproof -\n  from assms have \"finite (\\<C> - \\<D>)\" \n    by auto\n  moreover have \"finite \\<D>\"\n    using assms(1,2) by (rule finite_subset)\n  moreover from assms have \"(\\<C> - \\<D>) \\<inter> \\<D> = {}\"\n    using assms by auto\n  ultimately have \"nary_join n (\\<C> - \\<D> \\<union> \\<D>) = nary_join n(\\<C> - \\<D>) \\<bowtie> nary_join n \\<D>\" \n    using assms\n    by (subst nary_join_union_disjoint) auto\n  moreover from assms have \"\\<C> \\<union> \\<D> = \\<C>\" \n    by auto\n  ultimately show ?thesis \n    by simp\nqed\n\nlemma nary_join_inter_diff:\n  assumes \"finite \\<C>\" and \"\\<forall>R\\<in>\\<C>. table n (X R) R\"\n  shows \"nary_join n \\<C> = nary_join n (\\<C> \\<inter> \\<D>) \\<bowtie> nary_join n (\\<C> - \\<D>)\"\n  using assms\n  by (subst nary_join_subset_diff[where \\<D>=\"\\<C> - \\<D>\" and X=X])\n    (auto simp:  Diff_Diff_Int assms)\n\nlemma nary_join_setdiff_irrelevant:\n  assumes \"finite \\<C>\" and \"\\<forall>R\\<in>\\<C>. table n (X R) R\"\n  shows \"nary_join n (\\<C> - {unit_table n}) = nary_join n \\<C>\"\n  using assms \n  apply (induct \\<C>) \n  by (simp_all add: insert_Diff_if)\n    (metis boolean_algebra.conj_zero_right empty_table_def finite.emptyI \n      join_commute nary_join_empty nary_join_union_disjoint union_empty_table_eq(2))\n\nlemma nary_join_not_neutral_contains_not_neutral:\n  assumes \"nary_join n \\<C> \\<noteq> unit_table n\"\n  obtains R where \"R \\<in> \\<C>\" and \"R \\<noteq> unit_table n\"\nproof -\n  from assms have \"\\<exists>R\\<in>\\<C>. R \\<noteq> unit_table n\"\n  proof (induct \\<C> rule: infinite_finite_induct)\n    case infinite\n    then show ?case by simp\n  next\n    case empty\n    then show ?case by simp\n  next\n    case (insert R \\<C>)\n    then show ?case by fastforce\n  qed\n  with that show thesis by blast\nqed\n\nlemma UNION_disjoint:\n  assumes \"finite I\" and \"\\<forall>i\\<in>I. finite (\\<C> i)\"\n    and \"\\<forall>i\\<in>I. \\<forall>j\\<in>I. i \\<noteq> j \\<longrightarrow> \\<C> i \\<inter> \\<C> j = {}\"\n    and \"\\<forall>R\\<in>(\\<Union>i\\<in>I. \\<C> i). table n (X R) R\"\n  shows \"nary_join n (\\<Union>(\\<C> ` I)) = nary_join n ((\\<lambda>x. nary_join n (\\<C> x)) ` I)\"\n  using assms\nproof (induction rule: finite_induct)\n  case (insert i I)\n  hence \"\\<forall>j\\<in>I. j \\<noteq> i\"\n    by blast\n  hence obs1: \"\\<C> i \\<inter> \\<Union>(\\<C> ` I) = {}\"\n    using insert.prems by blast\n  have obs2: \"finite (\\<Union> (\\<C> ` I))\"\n    using insert by auto\n  have obs3: \"\\<forall>R\\<in>\\<C> i \\<union> \\<Union> (\\<C> ` I). table n (X R) R\"\n    using insert by auto\n  hence obs4: \"\\<forall>R\\<in>(\\<lambda>x. nary_join n (\\<C> x)) ` I. \\<exists>X. table n X R\"\n    apply (clarsimp, rename_tac j)\n    apply (rule_tac x=\"\\<Union>R\\<in>(\\<C> j). X R\" in exI)\n    using insert by (auto intro!: table_nary_joinI)\n  thus ?case\n    apply (simp, subst nary_join_union_disjoint[OF insert(4)[rule_format] obs2 obs3 obs1]; clarsimp)\n    apply(subst nary_join_insert_table)\n    using insert by force+\nqed auto\n\nlemma foldr_join_tables_eq_nary_join[simp]: \"\\<forall>R\\<in>set Rs. \\<exists>X. table n X R \n  \\<Longrightarrow> foldr (\\<lambda>r1 r2. join r1 True r2) Rs (unit_table n) = (nary_join n (set Rs))\"\n  by (induct Rs arbitrary: n) (auto simp: nary_join_insert_table)\n\nsubsection \\<open> Correctness predicate \\<close>\n\ndefinition qtable :: \"nat \\<Rightarrow> nat set \\<Rightarrow> ('a tuple \\<Rightarrow> bool) \\<Rightarrow> ('a tuple \\<Rightarrow> bool) \\<Rightarrow>\n  'a table \\<Rightarrow> bool\" where\n  \"qtable n A P Q X \\<longleftrightarrow> table n A X \\<and> (\\<forall>x. (x \\<in> X \\<and> P x \\<longrightarrow> Q x) \\<and> (wf_tuple n A x \\<and> P x \\<and> Q x \\<longrightarrow> x \\<in> X))\"\n\nlemma qtable_iff: \"qtable n X P Q R \\<longleftrightarrow> \n  (table n X R \\<and> (\\<forall>v. P v \\<longrightarrow> v \\<in> R \\<longleftrightarrow> (Q v \\<and> wf_tuple n X v)))\"\n  by (auto simp: qtable_def table_def)\n\nlemma qtable_cong: \"qtable n A P Q X \\<Longrightarrow> A = B \\<Longrightarrow> (\\<And>v. P v \\<Longrightarrow> Q v \\<longleftrightarrow> Q' v) \n  \\<Longrightarrow> qtable n B P Q' X\"\n  by (auto simp: qtable_def)\n\nlemma qtable_cong_strong: \"A = B \\<Longrightarrow> (\\<And>v. wf_tuple n A v \\<Longrightarrow> P v \\<Longrightarrow> Q v \\<longleftrightarrow> Q' v) \n  \\<Longrightarrow> qtable n A P Q = qtable n B P Q'\"\n  apply (auto simp: qtable_def fun_eq_iff)\n  using table_def by blast+\n\nlemma qtable_unique_vars:\n  \"R \\<noteq> {} \\<Longrightarrow> X \\<subseteq> {m. m < n} \\<Longrightarrow> Y \\<subseteq> {m. m < n} \\<Longrightarrow> table n X R \\<Longrightarrow> table n Y R \\<Longrightarrow> X = Y\"\n  by (auto simp: table_def wf_tuple_def subset_eq)\n\nlemma qtable_unique_pred:\n  \"qtable n X P Q1 R \\<Longrightarrow> qtable n X P Q2 R \\<Longrightarrow> (\\<forall>v. P v \\<longrightarrow> wf_tuple n X v \\<longrightarrow> Q1 v = Q2 v)\"\n  by (auto simp: qtable_iff fun_eq_iff)\n\nabbreviation wf_table where\n  \"wf_table n A Q X \\<equiv> qtable n A (\\<lambda>_. True) Q X\"\n\nlemma wf_table_iff: \"wf_table n A Q X \\<longleftrightarrow> (\\<forall>x. x \\<in> X \\<longleftrightarrow> (Q x \\<and> wf_tuple n A x))\"\n  unfolding qtable_def table_def by auto\n\nlemma table_wf_table: \"table n A X = wf_table n A (\\<lambda>v. v \\<in> X) X\"\n  unfolding table_def wf_table_iff by auto\n\nlemma qtableI: \"table n A X \\<Longrightarrow>\n  (\\<And>x. x \\<in> X \\<Longrightarrow> wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow>\n  (\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> x \\<in> X) \\<Longrightarrow>\n  qtable n A P Q X\"\n  unfolding qtable_def table_def by auto\n\nlemma in_qtableI: \"qtable n A P Q X \\<Longrightarrow> wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> x \\<in> X\"\n  unfolding qtable_def by blast\n\nlemma in_qtableE: \"qtable n A P Q X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> P x \\<Longrightarrow> (wf_tuple n A x \\<Longrightarrow> Q x \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  unfolding qtable_def table_def by blast\n\nlemma qtableD:\n  assumes \"qtable n X P Q R\"\n  shows \"table n X R\"\n    and \"P v \\<Longrightarrow> v \\<in> R \\<Longrightarrow> Q v\"\n    and \"P v \\<Longrightarrow> v \\<in> R \\<Longrightarrow> wf_tuple n X v\"\n    and \"P v \\<Longrightarrow> Q v \\<Longrightarrow> wf_tuple n X v \\<Longrightarrow> v \\<in> R\"\n  using assms unfolding qtable_iff by auto\n\nlemma qtable_empty_vars_iff: \n  \"qtable n {} P Q R \\<longleftrightarrow> (R = empty_table \\<or> R = unit_table n) \n    \\<and> (\\<forall>v. P v \\<longrightarrow> (v \\<in> R) = (Q v \\<and> v = replicate n None))\"\n  unfolding qtable_iff table_empty_vars_iff wf_tuple_empty_iff by simp\n\nlemma qtable_empty_varsI:\n  \"(\\<And>v. P v \\<Longrightarrow> Q v \\<Longrightarrow> v \\<noteq> replicate n None) \\<Longrightarrow> qtable n {} P Q empty_table\"\n  \"(\\<And>v. P v \\<Longrightarrow> (v = replicate n None) = Q v) \\<Longrightarrow> qtable n {} P Q (unit_table n)\"\n  unfolding qtable_iff table_empty_vars_iff wf_tuple_empty_iff \n  by (auto simp: unit_table_def)\n\nlemmas qtable_empty_varsD = \n  iffD1[OF qtable_empty_vars_iff, THEN conjunct1, rule_format]\n  iffD1[OF qtable_empty_vars_iff, THEN conjunct2, rule_format]\n\nlemma nullary_qtable_cases: \"qtable n {} P Q X \\<Longrightarrow> (X = empty_table \\<or> X = unit_table n)\"\n  by (simp add: qtable_empty_vars_iff) (* replace everywhere with qtable_empty_varsD(1) *)\n\nlemma qtable_empty_unit_table:\n  \"qtable n {} R P empty_table \\<Longrightarrow> qtable n {} R (\\<lambda>v. \\<not> P v) (unit_table n)\"\n  by (auto simp: qtable_iff wf_tuple_empty_iff unit_table_def table_empty_vars_iff)\n\nlemma qtable_unit_empty_table:\n  \"qtable n {} R P (unit_table n) \\<Longrightarrow> qtable n {} R (\\<lambda>v. \\<not> P v) empty_table\"\n  by (auto simp: qtable_iff wf_tuple_empty_iff unit_table_def table_empty_vars_iff)\n\nlemma qtable_nonempty_empty_table:\n  \"qtable n {} R P X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> qtable n {} R (\\<lambda>v. \\<not> P v) empty_table\"\n  by (frule qtable_empty_varsD(1)) (auto dest: qtable_unit_empty_table)\n\n\nsubsubsection \\<open> Empty and unit table \\<close>\n\nlemma qtable_empty: \"(\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> False) \\<Longrightarrow> qtable n A P Q empty_table\"\n  unfolding qtable_def table_def empty_table_def by auto\n\nlemma qtable_empty_iff: \"qtable n A P Q empty_table = (\\<forall>x. wf_tuple n A x \\<longrightarrow> P x \\<longrightarrow> Q x \\<longrightarrow> False)\"\n  unfolding qtable_def table_def empty_table_def by auto\n\nlemma qtable_unit_iff: \"qtable n X P Q (unit_table n) \n  \\<longleftrightarrow> (X \\<subseteq> {m. n \\<le> m} \\<and> (P (replicate n None) \\<longrightarrow> Q (replicate n None)))\"\n  unfolding qtable_iff table_unit_table_iff \n  by (auto simp: unit_table_def leD subset_eq wf_tuple_def)\n    (meson eq_replicate_None_iff leD)+\n\nlemma qtable_unitI: \"(P (replicate n None) \\<Longrightarrow> Q (replicate n None)) \n  \\<Longrightarrow> X = {} \\<Longrightarrow> qtable n X P Q (unit_table n)\"\n  by (subst qtable_unit_iff; clarsimp)\n\nlemma qtable_unit_table: \"(\\<And>x. wf_tuple n {} x \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow> qtable n {} P Q (unit_table n)\"\n  unfolding qtable_def table_def in_unit_table by auto\n\n\nsubsubsection \\<open> Union \\<close>\n\nlemma qtable_union_iff: \"qtable n Z P Q1 R1 \\<Longrightarrow> qtable n Z P Q2 R2\n  \\<Longrightarrow> qtable n Z P Q (R1 \\<union> R2)\n  \\<longleftrightarrow> (\\<forall>v. P v \\<longrightarrow> wf_tuple n Z v \\<longrightarrow> Q v = (Q1 v \\<or> Q2 v))\"\n  by (auto simp: qtable_iff)\n\nlemma qtable_union: \"qtable n A P Q1 X \\<Longrightarrow> qtable n A P Q2 Y \\<Longrightarrow>\n  (\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> Q1 x \\<or> Q2 x) \\<Longrightarrow> qtable n A P Q (X \\<union> Y)\"\n  unfolding qtable_def table_def by blast\n\nlemma qtable_union_emptyI: \n  \"qtable n X P Q R \\<Longrightarrow> qtable n X P Q (R \\<union> empty_table)\"\n  \"qtable n X P Q R \\<Longrightarrow> qtable n X P Q (empty_table \\<union> R)\"\n  unfolding qtable_iff by auto\n\nlemma qtable_Union: \"finite I \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> qtable n A P (Qi i) (Xi i)) \\<Longrightarrow>\n  (\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> (\\<exists>i \\<in> I. Qi i x)) \\<Longrightarrow> qtable n A P Q (\\<Union>i \\<in> I. Xi i)\"\nproof (induct I arbitrary: Q rule: finite_induct)\n  case (insert i F)\n  then show ?case\n    by (auto intro!: qtable_union[where ?Q1.0 = \"Qi i\" and ?Q2.0 = \"\\<lambda>x. \\<exists>i\\<in>F. Qi i x\"])\nqed (auto intro!: qtable_empty[unfolded empty_table_def])\n\n\nsubsubsection \\<open> Join \\<close>\n\nlemma qtable_inter: \"qtable n X P Q1 R1 \\<Longrightarrow> qtable n X P Q2 R2 \n  \\<Longrightarrow> (\\<And>x. wf_tuple n X x \\<Longrightarrow> P x \\<Longrightarrow> Q x = (Q1 x \\<and> Q2 x)) \n  \\<Longrightarrow> qtable n X P Q (R1 \\<inter> R2)\"\n  unfolding qtable_def table_def by blast\n\nlemma qtable_join: \n  assumes \"qtable n A P Q1 X\" \"qtable n B P Q2 Y\" \"\\<not> b \\<Longrightarrow> B \\<subseteq> A\" \"C = A \\<union> B\"\n  \"\\<And>x. wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> P (restrict A x) \\<and> P (restrict B x)\"\n  \"\\<And>x. b \\<Longrightarrow> wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> Q1 (restrict A x) \\<and> Q2 (restrict B x)\"\n  \"\\<And>x. \\<not> b \\<Longrightarrow> wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> Q1 (restrict A x) \\<and> \\<not> Q2 (restrict B x)\"\n  shows \"qtable n C P Q (join X b Y)\"\nproof (rule qtableI)\n  from assms(1-4) show \"table n C (join X b Y)\" \n    unfolding qtable_def by (auto simp: join_table)\nnext\n  fix x assume \"x \\<in> join X b Y\" \"wf_tuple n C x\" \"P x\"\n  with assms(1-3) assms(5-7)[of x] show \"Q x\" unfolding qtable_def\n    by (auto 0 2 simp: wf_tuple_restrict_simple elim!: in_joinE split: if_splits)\nnext\n  fix x assume \"wf_tuple n C x\" \"P x\" \"Q x\"\n  with assms(1-4) assms(5-7)[of x] show \"x \\<in> join X b Y\" unfolding qtable_def\n    by (auto dest: wf_tuple_restrict_simple intro!: in_joinI[of n A X B Y])\nqed\n\nlemma qtable_join_fixed: \n  assumes \"qtable n A P Q1 X\" \"qtable n B P Q2 Y\" \"\\<not> b \\<Longrightarrow> B \\<subseteq> A\" \"C = A \\<union> B\"\n  \"\\<And>x. wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> P (restrict A x) \\<and> P (restrict B x)\"\n  shows \"qtable n C P (\\<lambda>x. Q1 (restrict A x) \\<and> (if b then Q2 (restrict B x) else \\<not> Q2 (restrict B x))) (join X b Y)\"\n  by (rule qtable_join[OF assms]) auto\n\nlemma qtable_assign:\n  assumes \"qtable n A P Q X\"\n    \"y < n\" \"insert y A = A'\" \"y \\<notin> A\"\n    \"\\<And>x'. wf_tuple n A' x' \\<Longrightarrow> P x' \\<Longrightarrow> P (restrict A x')\"\n    \"\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> Q' (x[y:=Some (f x)])\"\n    \"\\<And>x'. wf_tuple n A' x' \\<Longrightarrow> P x' \\<Longrightarrow> Q' x' \n  \\<Longrightarrow> Q (restrict A x') \\<and> x' ! y = Some (f (restrict A x'))\"\n  shows \"qtable n A' P Q' ((\\<lambda>x. x[y:=Some (f x)]) ` X)\" (is \"qtable _ _ _ _ ?Y\")\nproof (rule qtableI)\n  from assms(1) have \"table n A X\" unfolding qtable_def by simp\n  then show \"table n A' ?Y\"\n    unfolding table_def wf_tuple_def using assms(2,3)\n    by (auto simp: nth_list_update)\nnext\n  fix x'\n  assume \"x' \\<in> ?Y\" \"wf_tuple n A' x'\" \"P x'\"\n  then obtain x where \"x \\<in> X\" and x'_eq: \"x' = x[y:=Some (f x)]\" by blast\n  then have \"wf_tuple n A x\"\n    using assms(1) unfolding qtable_def table_def by blast\n  then have \"y < length x\" using assms(2) by (simp add: wf_tuple_def)\n  with \\<open>wf_tuple n A x\\<close> have \"restrict A x' = x\"\n    unfolding x'_eq by (simp add: restrict_update[OF assms(4)] restrict_idle)\n  with \\<open>wf_tuple n A' x'\\<close> \\<open>P x'\\<close> have \"P x\"\n    using assms(5) by blast\n  with \\<open>wf_tuple n A x\\<close> \\<open>x \\<in> X\\<close> have \"Q x\"\n    using assms(1) by (elim in_qtableE)\n  with \\<open>wf_tuple n A x\\<close> \\<open>P x\\<close> show \"Q' x'\"\n    unfolding x'_eq by (rule assms(6))\nnext\n  fix x'\n  assume \"wf_tuple n A' x'\" \"P x'\" \"Q' x'\"\n  then have \"wf_tuple n A (restrict A x')\"\n    using assms(3) by (auto intro!: wf_tuple_restrict_simple)\n  moreover have \"P (restrict A x')\"\n    using \\<open>wf_tuple n A' x'\\<close> \\<open>P x'\\<close> by (rule assms(5))\n  moreover have \"Q (restrict A x')\" and y: \"x' ! y = Some (f (restrict A x'))\"\n    using \\<open>wf_tuple n A' x'\\<close> \\<open>P x'\\<close> \\<open>Q' x'\\<close> by (auto dest!: assms(7))\n  ultimately have \"restrict A x' \\<in> X\" by (intro in_qtableI[OF assms(1)])\n  moreover have \"x' = (restrict A x')[y:=Some (f (restrict A x'))]\"\n    using y assms(2,3) \\<open>wf_tuple n A (restrict A x')\\<close> \\<open>wf_tuple n A' x'\\<close>\n    by (auto simp: list_eq_iff_nth_eq wf_tuple_def nth_list_update nth_restrict)\n  ultimately show \"x' \\<in> ?Y\" by simp\nqed\n\nlemma qtable_filter:\n  assumes \"qtable n A P Q X\"\n    \"\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<and> R x \\<longleftrightarrow> Q' x\"\n  shows \"qtable n A P Q' (Set.filter R X)\" (is \"qtable _ _ _ _ ?Y\")\nproof (rule qtableI)\n  from assms(1) have \"table n A X\"\n    unfolding qtable_def by simp\n  then show \"table n A ?Y\"\n    unfolding table_def wf_tuple_def by simp\nnext\n  fix x\n  assume \"x \\<in> ?Y\" \"wf_tuple n A x\" \"P x\"\n  with assms show \"Q' x\" by (auto elim!: in_qtableE)\nnext\n  fix x\n  assume \"wf_tuple n A x\" \"P x\" \"Q' x\"\n  with assms show \"x \\<in> Set.filter R X\" by (auto intro!: in_qtableI)\nqed\n\nlemma qtable_Inter_list:\n  \"Rs \\<noteq> [] \\<Longrightarrow> (\\<And>i. i < length Rs \\<Longrightarrow> qtable n X P (Qi i) (Rs ! i)) \n  \\<Longrightarrow> (\\<And>x. wf_tuple n X x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> (\\<forall>i<length Rs. Qi i x)) \n  \\<Longrightarrow> qtable n X P Q (\\<Inter> (set Rs))\"\nproof (induct Rs arbitrary: n X Q Qi)\n  case (Cons R Rs)\n  hence \"Rs = [] \\<Longrightarrow> ?case\"\n    by clarsimp (metis qtable_cong_strong)\n  moreover have \"Rs \\<noteq> [] \\<Longrightarrow> ?case\"\n    apply (simp, rule_tac qtable_inter[OF Cons.prems(2)[of 0, simplified]])\n     apply (rule Cons.hyps[of n X \"\\<lambda>i. Qi (Suc i)\"]; clarsimp?)\n    using Cons.prems(2,3) by (force, auto simp: less_Suc_eq_0_disj)\n  ultimately show ?case\n    by blast\nqed simp\n\nlemma qtable_Inter:\n  assumes \"finite I\" \"I \\<noteq> {}\" \n    and \"(\\<And>i. i \\<in> I \\<Longrightarrow> qtable n X P (Qi i) (Ri i))\"\n    and \"(\\<And>x. wf_tuple n X x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> (\\<forall>i \\<in> I. Qi i x))\"\n  shows \"qtable n X P Q (\\<Inter>i \\<in> I. Ri i)\"\nproof-\n  obtain m::nat and f \n    where I_eq: \"I = f ` {i. i < m}\" \n      and \"m > 0\"\n    using \\<open>finite I\\<close> \\<open>I \\<noteq> {}\\<close>\n    by (metis Collect_empty_eq finite_imp_nat_seg_image_inj_on \n        gr0I image_is_empty less_nat_zero_code)\n  then obtain \"Rs\" \n    where Rs_def: \"\\<And>i. i < length Rs \\<Longrightarrow> Rs ! i = Ri (f i)\"\n    and len_Rs: \"length Rs = m\"\n    by (atomize_elim, rule_tac x=\"map (Ri \\<circ> f) [0..<m]\" in exI, force)\n  hence to_set: \"set Rs = Ri ` I\"\n    by (clarsimp simp: I_eq, safe) \n      (metis image_eqI in_set_conv_nth mem_Collect_eq,\n        metis in_set_conv_nth)\n  hence \"Rs \\<noteq> []\"\n    using I_eq \\<open>I \\<noteq> {}\\<close> by force\n  moreover have \"\\<And>i. i < length Rs \\<Longrightarrow> qtable n X P ((Qi \\<circ> f) i) (Rs ! i)\"\n    and \"\\<And>x. wf_tuple n X x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> (\\<forall>i<length Rs. (Qi \\<circ> f) i x)\"\n    using assms(3,4) Rs_def len_Rs\n    by (simp add: I_eq)+\n  ultimately have \"qtable n X P Q (\\<Inter> (set Rs))\"\n    using qtable_Inter_list[of Rs n X P \"Qi \\<circ> f\"] by force\n  thus \"qtable n X P Q (\\<Inter>i \\<in> I. Ri i)\"\n    unfolding to_set .\nqed\n\n\nsubsubsection \\<open> Projection \\<close>\n\ndefinition mem_restr :: \"'a list set \\<Rightarrow> 'a tuple \\<Rightarrow> bool\" where\n  \"mem_restr A x \\<longleftrightarrow> (\\<exists>y\\<in>A. list_all2 (\\<lambda>a b. a \\<noteq> None \\<longrightarrow> a = Some b) x y)\"\n\nlemma mem_restrI: \"y \\<in> A \\<Longrightarrow> length y = n \\<Longrightarrow> wf_tuple n V x \\<Longrightarrow> \\<forall>i\\<in>V. x ! i = Some (y ! i) \\<Longrightarrow> mem_restr A x\"\n  unfolding mem_restr_def wf_tuple_def by (force simp add: list_all2_conv_all_nth)\n\nlemma mem_restrE: \"mem_restr A x \\<Longrightarrow> wf_tuple n V x \\<Longrightarrow> \\<forall>i\\<in>V. i < n \\<Longrightarrow>\n  (\\<And>y. y \\<in> A \\<Longrightarrow> \\<forall>i\\<in>V. x ! i = Some (y ! i) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding mem_restr_def wf_tuple_def by (fastforce simp add: list_all2_conv_all_nth)\n\nlemma mem_restr_IntD: \"mem_restr (A \\<inter> B) v \\<Longrightarrow> mem_restr A v \\<and> mem_restr B v\"\n  unfolding mem_restr_def by auto\n\nlemma mem_restr_Un_iff: \"mem_restr (A \\<union> B) x \\<longleftrightarrow> mem_restr A x \\<or> mem_restr B x\"\n  unfolding mem_restr_def by blast\n\nlemma mem_restr_UNIV [simp]: \"mem_restr UNIV x\"\n  unfolding mem_restr_def\n  by (auto simp add: list.rel_map intro!: exI[of _ \"map the x\"] list.rel_refl)\n\nlemma restrict_mem_restr[simp]: \"mem_restr A x \\<Longrightarrow> mem_restr A (restrict V x)\"\n  unfolding mem_restr_def restrict_def\n  by (auto simp: list_all2_conv_all_nth elim!: bexI[rotated])\n\nlemma mem_restr_join1l: \"mem_restr U z \\<Longrightarrow> join1 (x, y) = Some z \\<Longrightarrow> mem_restr U x\"\n  apply (induct \"(x, y)\" arbitrary: x y z U rule: join1.induct)\n  by (auto simp: list_all2_Cons1 mem_restr_def split: if_splits) blast+\n\nlemma mem_restr_join1r: \"mem_restr U z \\<Longrightarrow> join1 (x, y) = Some z \\<Longrightarrow> mem_restr U y\"\n  apply (induct \"(x, y)\" arbitrary: x y z U rule: join1.induct)\n  by (auto simp: list_all2_Cons1 mem_restr_def split: if_splits) blast+\n\nlemma qtable_mem_restr_UNIV: \"qtable n X (mem_restr UNIV) Q R = wf_table n X Q R\"\n  unfolding qtable_def by auto\n\ndefinition lift_envs :: \"'a list set \\<Rightarrow> 'a list set\" where\n  \"lift_envs R = (\\<lambda>(a,b). a # b) ` (UNIV \\<times> R)\"\n\nlemma lift_envs_mem_restr[simp]: \"mem_restr A x \\<Longrightarrow> mem_restr (lift_envs A) (a # x)\"\n  by (auto simp: mem_restr_def lift_envs_def)\n\nlemma qtable_project:\n  assumes \"qtable (Suc n) A (mem_restr (lift_envs R)) P X\"\n  shows \"qtable n ((\\<lambda>x. x - Suc 0) ` (A - {0})) (mem_restr R)\n      (\\<lambda>v. \\<exists>x. P ((if 0 \\<in> A then Some x else None) # v)) (tl ` X)\"\n      (is \"qtable n ?A (mem_restr R) ?P ?X\")\nproof ((rule qtableI; (elim exE)?), goal_cases table left right)\n  case table\n  with assms show ?case\n    unfolding qtable_def by (simp add: table_project) \nnext\n  case (left v)\n  from assms have \"[] \\<notin> X\"\n    unfolding qtable_def table_def by fastforce\n  with left(1) obtain x where \"x # v \\<in> X\"\n    by (metis (no_types, opaque_lifting) image_iff hd_Cons_tl)\n  with assms show ?case\n    by (rule in_qtableE) (auto simp: left(3) split: if_splits)\nnext\n  case (right v x)\n  with assms have \"(if 0 \\<in> A then Some x else None) # v \\<in> X\"\n    by (elim in_qtableI) auto\n  then show ?case\n    by (auto simp: image_iff elim: bexI[rotated])\nqed\n\n\nsubsubsection \\<open> N-ary join \\<close>\n\nlemma qtable_nary_join_list:\n  \"(\\<And>i. i < length Rs \\<Longrightarrow> qtable n (X i) P (Qi i) (Rs ! i)) \n  \\<Longrightarrow> (\\<And>i. i < length Rs \\<Longrightarrow> X i \\<subseteq> {m. m < n})\n  \\<Longrightarrow> (\\<And>X Y v i. P v \\<Longrightarrow> wf_tuple n Y v \\<Longrightarrow> X \\<subseteq> Y \\<Longrightarrow> P (restrict X v))\n  \\<Longrightarrow> (\\<And>v. P v \\<Longrightarrow> wf_tuple n (\\<Union>i<length Rs. X i) v \n    \\<Longrightarrow> Q v \\<longleftrightarrow> (\\<forall>i<length Rs. Qi i (restrict (X i) v))) \n  \\<Longrightarrow> qtable n (\\<Union>i<length Rs. X i) P Q (nary_join n (set Rs))\"\nproof (induct Rs arbitrary: n X Q Qi)\n  case Nil\n  then show ?case\n    apply (clarsimp simp: qtable_unit_iff)\n    using wf_tuple_empty_iff by blast\nnext\n  case (Cons R Rs)\n  let ?U = \"\\<Union> (X ` {..<Suc (length Rs)})\"\n  have \"\\<Union> (X ` {..<Suc 0}) = X 0\"\n    by auto\n  hence \"Rs = [] \\<Longrightarrow> ?case\"\n    using Cons.prems(1,4)\n      join_unit_table(1)[OF qtableD(1)[of n \"X 0\" P \"Qi 0\" R]]\n    by clarsimp (smt (verit, best) qtable_cong_strong restrict_idle)\n  moreover have \"{} \\<in> set (R # Rs) \\<Longrightarrow> ?case\"\n  proof-\n    assume hyp: \"{} \\<in> set (R # Rs)\"\n    then obtain i \n      where i_le: \"i < length (R # Rs)\" \n        and \"(R # Rs) ! i = {}\"\n        and \"qtable n (X i) P (Qi i) {}\"\n      unfolding in_set_conv_nth[of \"{}\" \"R # Rs\"]\n      using Cons.prems(1) by force\n    hence \"\\<forall>v. P v \\<longrightarrow> wf_tuple n (X i) v \\<longrightarrow> \\<not> Qi i v\"\n      unfolding qtable_iff by auto\n    moreover have \"\\<forall>v. P v \\<longrightarrow> wf_tuple n ?U v \\<longrightarrow> P (restrict (X i) v)\"\n      using i_le Cons.prems(3)[of _ ?U \"X i\"] \n      by auto\n    moreover have \"\\<forall>v. P v \\<longrightarrow> wf_tuple n ?U v \\<longrightarrow> wf_tuple n (X i) (restrict (X i) v)\"\n      using i_le wf_tuple_restrict_simple[of n ?U _ \"X i\"] \n      by auto\n    moreover have nary_simp: \"nary_join n (set (R # Rs)) = {}\"\n      using hyp\n      by (subst nary_join_with_empty) \n        simp_all\n    ultimately show ?thesis\n      apply (clarsimp simp: qtable_iff)\n      apply (erule_tac x=\"restrict (X i) v\" in allE)\n      using Cons.prems(4) i_le by auto\n  qed\n  moreover have \"Rs \\<noteq> [] \\<Longrightarrow> {} \\<notin> set (R # Rs) \\<Longrightarrow> ?case\"\n  proof-\n    assume \"Rs \\<noteq> []\" \n      and no_empty: \"{} \\<notin> set (R # Rs)\"\n    hence qtableR: \"qtable n (X 0) P (Qi 0) R\"\n      and qtables: \"\\<And>i. i < length Rs \\<Longrightarrow> qtable n (X (Suc i)) P (Qi (Suc i)) (Rs ! i)\" \n      and wf_vars: \"\\<And>i. i < length Rs \\<Longrightarrow> (X \\<circ> Suc) i \\<subseteq> {m. m < n}\"\n      and empty_case: \"\\<And>i. i < length Rs \\<Longrightarrow> Rs ! i = {} \\<Longrightarrow> length Rs \\<noteq> 1 \n        \\<Longrightarrow> (X \\<circ> Suc) i \\<in> {(X \\<circ> Suc) j |j. j \\<noteq> i \\<and> j < length Rs}\"\n      using Cons.prems(1,2) \\<open>Rs \\<noteq> []\\<close> \n      by (fastforce, fastforce, fastforce, metis list.set_intros(2) nth_mem)\n    then show ?thesis\n    proof(cases \"R \\<in> set Rs\")\n      case True\n      then obtain i where i_def: \"Rs ! i = R\" \n        and i_le: \"i < length Rs\"\n        by (meson in_set_conv_nth)\n      hence \"table n (X 0) R\" \"table n (X (Suc i)) R\"\n        using qtableD(1)[OF qtableR]\n          qtableD(1)[OF Cons.prems(1)[of \"Suc i\"]]\n        by auto\n      hence eq_vars: \"X 0 = X (Suc i)\"\n        using no_empty Cons.prems(2)[of 0]\n          Cons.prems(2)[of \"Suc i\"] \\<open>i < length Rs\\<close>\n        by (auto simp: table_def wf_tuple_def subset_eq)\n      hence rw_vars: \"?U = \\<Union> ((X \\<circ> Suc) ` {..<length Rs})\" (is \"_ = ?U'\")\n        apply (rule_tac f=\\<Union> in arg_cong)\n        using i_le less_Suc_eq_0_disj by auto\n      show ?thesis\n        using True\n        apply simp\n        unfolding rw_vars\n        apply (rule Cons.hyps[of n \"X \\<circ> Suc\" \"Qi \\<circ> Suc\"])\n        using qtables apply force\n        using wf_vars apply force\n        using Cons.prems(3) apply force\n        subgoal for v\n          using Cons.prems(4)[simplified, unfolded rw_vars, of v]\n          apply clarsimp\n          apply (intro conjI impI allI iffI)\n           apply force\n          subgoal for j\n            apply (cases \"j=0\"; clarsimp)\n             apply (erule_tac x=i in allE)\n            using i_le apply clarsimp\n            using qtable_unique_pred[OF qtables[OF i_le, unfolded i_def] qtableR[unfolded eq_vars]]\n              wf_tuple_restrict_simple[of n ?U' v \"X 0\", simplified]\n              Cons.prems(3)[of v ?U' \"X 0\", simplified]\n            apply (metis SUP_upper eq_vars lessThan_iff)\n            using less_Suc_eq_0_disj by auto\n          done\n        done\n    next\n      case False\n      then show ?thesis\n        using \\<open>Rs \\<noteq> []\\<close>\n        apply simp\n        apply (rule qtable_join[OF qtableR, where b=True, simplified])\n           apply (rule Cons.hyps[of n \"X \\<circ> Suc\" \"Qi \\<circ> Suc\"])\n        using qtables apply force\n        using wf_vars apply force\n        using Cons.prems(3) apply force\n        apply force\n           prefer 2 subgoal for v\n          using Cons.prems(3)[of v ?U \"\\<Union>((X \\<circ> Suc) ` {..<length Rs})\"]\n            Cons.prems(3)[of v \"\\<Union> (X ` _)\" \"X 0\"] by force\n         subgoal\n          apply (intro set_eqI iffI; clarsimp)\n          using less_Suc_eq_0_disj by force blast\n        subgoal for v\n          using Cons.prems(4)[of v, simplified] apply clarsimp\n          apply (intro conjI impI allI iffI; clarsimp)\n           apply (subst sub_restrict_restrict)\n          apply force\n           apply force\n          subgoal for j\n            apply (cases \"j=length Rs\", clarsimp)\n            apply (erule_tac x=\"j-1\" in allE)\n            apply clarsimp\n            apply (subst (asm) sub_restrict_restrict)\n              apply auto[1]\n            apply (metis Suc_pred length_greater_0_conv lessI lessThan_iff)\n            apply (metis length_0_conv lessI lessThan_iff less_Suc_eq_0_disj)\n            apply fastforce\n            apply (erule_tac x=\"j-1\" in allE)\n            apply clarsimp\n            apply (subst (asm) sub_restrict_restrict)\n             apply (clarsimp simp: subset_eq)\n            apply (metis lessThan_iff less_Suc_eq less_imp_diff_less)\n            by (metis Suc_pred gr0I less_SucE less_imp_diff_less)\n          done\n        done\n    qed\n  qed\n  ultimately show ?case\n    by blast\nqed\n\nno_notation nat_join (infixl \"\\<bowtie>\" 70)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "remolueoend", "repo": "monpoly", "sha": "f0941c3a6683e7faef96106e8a78833795fc84dd", "save_path": "github-repos/isabelle/remolueoend-monpoly", "path": "github-repos/isabelle/remolueoend-monpoly/monpoly-f0941c3a6683e7faef96106e8a78833795fc84dd/thys/MFOTL_Monitor_Devel/Table.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7755444334290935}}
{"text": "(*  Title:      HOL/Euclidean_Division.thy\n    Author:     Manuel Eberl, TU Muenchen\n    Author:     Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>Division in euclidean (semi)rings\\<close>\n\ntheory Euclidean_Division\n  imports Int Lattices_Big\nbegin\n\nsubsection \\<open>Euclidean (semi)rings with explicit division and remainder\\<close>\n  \nclass euclidean_semiring = semidom_modulo + \n  fixes euclidean_size :: \"'a \\<Rightarrow> nat\"\n  assumes size_0 [simp]: \"euclidean_size 0 = 0\"\n  assumes mod_size_less: \n    \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size (a mod b) < euclidean_size b\"\n  assumes size_mult_mono:\n    \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size a \\<le> euclidean_size (a * b)\"\nbegin\n\nlemma euclidean_size_eq_0_iff [simp]:\n  \"euclidean_size b = 0 \\<longleftrightarrow> b = 0\"\nproof\n  assume \"b = 0\"\n  then show \"euclidean_size b = 0\"\n    by simp\nnext\n  assume \"euclidean_size b = 0\"\n  show \"b = 0\"\n  proof (rule ccontr)\n    assume \"b \\<noteq> 0\"\n    with mod_size_less have \"euclidean_size (b mod b) < euclidean_size b\" .\n    with \\<open>euclidean_size b = 0\\<close> show False\n      by simp\n  qed\nqed\n\nlemma euclidean_size_greater_0_iff [simp]:\n  \"euclidean_size b > 0 \\<longleftrightarrow> b \\<noteq> 0\"\n  using euclidean_size_eq_0_iff [symmetric, of b] by safe simp\n\nlemma size_mult_mono': \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size a \\<le> euclidean_size (b * a)\"\n  by (subst mult.commute) (rule size_mult_mono)\n\nlemma dvd_euclidean_size_eq_imp_dvd:\n  assumes \"a \\<noteq> 0\" and \"euclidean_size a = euclidean_size b\"\n    and \"b dvd a\" \n  shows \"a dvd b\"\nproof (rule ccontr)\n  assume \"\\<not> a dvd b\"\n  hence \"b mod a \\<noteq> 0\" using mod_0_imp_dvd [of b a] by blast\n  then have \"b mod a \\<noteq> 0\" by (simp add: mod_eq_0_iff_dvd)\n  from \\<open>b dvd a\\<close> have \"b dvd b mod a\" by (simp add: dvd_mod_iff)\n  then obtain c where \"b mod a = b * c\" unfolding dvd_def by blast\n    with \\<open>b mod a \\<noteq> 0\\<close> have \"c \\<noteq> 0\" by auto\n  with \\<open>b mod a = b * c\\<close> have \"euclidean_size (b mod a) \\<ge> euclidean_size b\"\n    using size_mult_mono by force\n  moreover from \\<open>\\<not> a dvd b\\<close> and \\<open>a \\<noteq> 0\\<close>\n  have \"euclidean_size (b mod a) < euclidean_size a\"\n    using mod_size_less by blast\n  ultimately show False using \\<open>euclidean_size a = euclidean_size b\\<close>\n    by simp\nqed\n\nlemma euclidean_size_times_unit:\n  assumes \"is_unit a\"\n  shows   \"euclidean_size (a * b) = euclidean_size b\"\nproof (rule antisym)\n  from assms have [simp]: \"a \\<noteq> 0\" by auto\n  thus \"euclidean_size (a * b) \\<ge> euclidean_size b\" by (rule size_mult_mono')\n  from assms have \"is_unit (1 div a)\" by simp\n  hence \"1 div a \\<noteq> 0\" by (intro notI) simp_all\n  hence \"euclidean_size (a * b) \\<le> euclidean_size ((1 div a) * (a * b))\"\n    by (rule size_mult_mono')\n  also from assms have \"(1 div a) * (a * b) = b\"\n    by (simp add: algebra_simps unit_div_mult_swap)\n  finally show \"euclidean_size (a * b) \\<le> euclidean_size b\" .\nqed\n\nlemma euclidean_size_unit:\n  \"is_unit a \\<Longrightarrow> euclidean_size a = euclidean_size 1\"\n  using euclidean_size_times_unit [of a 1] by simp\n\nlemma unit_iff_euclidean_size: \n  \"is_unit a \\<longleftrightarrow> euclidean_size a = euclidean_size 1 \\<and> a \\<noteq> 0\"\nproof safe\n  assume A: \"a \\<noteq> 0\" and B: \"euclidean_size a = euclidean_size 1\"\n  show \"is_unit a\"\n    by (rule dvd_euclidean_size_eq_imp_dvd [OF A B]) simp_all\nqed (auto intro: euclidean_size_unit)\n\nlemma euclidean_size_times_nonunit:\n  assumes \"a \\<noteq> 0\" \"b \\<noteq> 0\" \"\\<not> is_unit a\"\n  shows   \"euclidean_size b < euclidean_size (a * b)\"\nproof (rule ccontr)\n  assume \"\\<not>euclidean_size b < euclidean_size (a * b)\"\n  with size_mult_mono'[OF assms(1), of b] \n    have eq: \"euclidean_size (a * b) = euclidean_size b\" by simp\n  have \"a * b dvd b\"\n    by (rule dvd_euclidean_size_eq_imp_dvd [OF _ eq]) (insert assms, simp_all)\n  hence \"a * b dvd 1 * b\" by simp\n  with \\<open>b \\<noteq> 0\\<close> have \"is_unit a\" by (subst (asm) dvd_times_right_cancel_iff)\n  with assms(3) show False by contradiction\nqed\n\nlemma dvd_imp_size_le:\n  assumes \"a dvd b\" \"b \\<noteq> 0\" \n  shows   \"euclidean_size a \\<le> euclidean_size b\"\n  using assms by (auto elim!: dvdE simp: size_mult_mono)\n\nlemma dvd_proper_imp_size_less:\n  assumes \"a dvd b\" \"\\<not> b dvd a\" \"b \\<noteq> 0\" \n  shows   \"euclidean_size a < euclidean_size b\"\nproof -\n  from assms(1) obtain c where \"b = a * c\" by (erule dvdE)\n  hence z: \"b = c * a\" by (simp add: mult.commute)\n  from z assms have \"\\<not>is_unit c\" by (auto simp: mult.commute mult_unit_dvd_iff)\n  with z assms show ?thesis\n    by (auto intro!: euclidean_size_times_nonunit)\nqed\n\nlemma unit_imp_mod_eq_0:\n  \"a mod b = 0\" if \"is_unit b\"\n  using that by (simp add: mod_eq_0_iff_dvd unit_imp_dvd)\n\nlemma mod_eq_self_iff_div_eq_0:\n  \"a mod b = a \\<longleftrightarrow> a div b = 0\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  with div_mult_mod_eq [of a b] show ?Q\n    by auto\nnext\n  assume ?Q\n  with div_mult_mod_eq [of a b] show ?P\n    by simp\nqed\n\nlemma coprime_mod_left_iff [simp]:\n  \"coprime (a mod b) b \\<longleftrightarrow> coprime a b\" if \"b \\<noteq> 0\"\n  by (rule; rule coprimeI)\n    (use that in \\<open>auto dest!: dvd_mod_imp_dvd coprime_common_divisor simp add: dvd_mod_iff\\<close>)\n\nlemma coprime_mod_right_iff [simp]:\n  \"coprime a (b mod a) \\<longleftrightarrow> coprime a b\" if \"a \\<noteq> 0\"\n  using that coprime_mod_left_iff [of a b] by (simp add: ac_simps)\n\nend\n\nclass euclidean_ring = idom_modulo + euclidean_semiring\nbegin\n\nlemma dvd_diff_commute [ac_simps]:\n  \"a dvd c - b \\<longleftrightarrow> a dvd b - c\"\nproof -\n  have \"a dvd c - b \\<longleftrightarrow> a dvd (c - b) * - 1\"\n    by (subst dvd_mult_unit_iff) simp_all\n  then show ?thesis\n    by simp\nqed\n \nend\n\n\nsubsection \\<open>Euclidean (semi)rings with cancel rules\\<close>\n\nclass euclidean_semiring_cancel = euclidean_semiring +\n  assumes div_mult_self1 [simp]: \"b \\<noteq> 0 \\<Longrightarrow> (a + c * b) div b = c + a div b\"\n  and div_mult_mult1 [simp]: \"c \\<noteq> 0 \\<Longrightarrow> (c * a) div (c * b) = a div b\"\nbegin\n\nlemma div_mult_self2 [simp]:\n  assumes \"b \\<noteq> 0\"\n  shows \"(a + b * c) div b = c + a div b\"\n  using assms div_mult_self1 [of b a c] by (simp add: mult.commute)\n\nlemma div_mult_self3 [simp]:\n  assumes \"b \\<noteq> 0\"\n  shows \"(c * b + a) div b = c + a div b\"\n  using assms by (simp add: add.commute)\n\nlemma div_mult_self4 [simp]:\n  assumes \"b \\<noteq> 0\"\n  shows \"(b * c + a) div b = c + a div b\"\n  using assms by (simp add: add.commute)\n\nlemma mod_mult_self1 [simp]: \"(a + c * b) mod b = a mod b\"\nproof (cases \"b = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  have \"a + c * b = (a + c * b) div b * b + (a + c * b) mod b\"\n    by (simp add: div_mult_mod_eq)\n  also from False div_mult_self1 [of b a c] have\n    \"\\<dots> = (c + a div b) * b + (a + c * b) mod b\"\n      by (simp add: algebra_simps)\n  finally have \"a = a div b * b + (a + c * b) mod b\"\n    by (simp add: add.commute [of a] add.assoc distrib_right)\n  then have \"a div b * b + (a + c * b) mod b = a div b * b + a mod b\"\n    by (simp add: div_mult_mod_eq)\n  then show ?thesis by simp\nqed\n\nlemma mod_mult_self2 [simp]:\n  \"(a + b * c) mod b = a mod b\"\n  by (simp add: mult.commute [of b])\n\nlemma mod_mult_self3 [simp]:\n  \"(c * b + a) mod b = a mod b\"\n  by (simp add: add.commute)\n\nlemma mod_mult_self4 [simp]:\n  \"(b * c + a) mod b = a mod b\"\n  by (simp add: add.commute)\n\nlemma mod_mult_self1_is_0 [simp]:\n  \"b * a mod b = 0\"\n  using mod_mult_self2 [of 0 b a] by simp\n\nlemma mod_mult_self2_is_0 [simp]:\n  \"a * b mod b = 0\"\n  using mod_mult_self1 [of 0 a b] by simp\n\nlemma div_add_self1:\n  assumes \"b \\<noteq> 0\"\n  shows \"(b + a) div b = a div b + 1\"\n  using assms div_mult_self1 [of b a 1] by (simp add: add.commute)\n\nlemma div_add_self2:\n  assumes \"b \\<noteq> 0\"\n  shows \"(a + b) div b = a div b + 1\"\n  using assms div_add_self1 [of b a] by (simp add: add.commute)\n\nlemma mod_add_self1 [simp]:\n  \"(b + a) mod b = a mod b\"\n  using mod_mult_self1 [of a 1 b] by (simp add: add.commute)\n\nlemma mod_add_self2 [simp]:\n  \"(a + b) mod b = a mod b\"\n  using mod_mult_self1 [of a 1 b] by simp\n\nlemma mod_div_trivial [simp]:\n  \"a mod b div b = 0\"\nproof (cases \"b = 0\")\n  assume \"b = 0\"\n  thus ?thesis by simp\nnext\n  assume \"b \\<noteq> 0\"\n  hence \"a div b + a mod b div b = (a mod b + a div b * b) div b\"\n    by (rule div_mult_self1 [symmetric])\n  also have \"\\<dots> = a div b\"\n    by (simp only: mod_div_mult_eq)\n  also have \"\\<dots> = a div b + 0\"\n    by simp\n  finally show ?thesis\n    by (rule add_left_imp_eq)\nqed\n\nlemma mod_mod_trivial [simp]:\n  \"a mod b mod b = a mod b\"\nproof -\n  have \"a mod b mod b = (a mod b + a div b * b) mod b\"\n    by (simp only: mod_mult_self1)\n  also have \"\\<dots> = a mod b\"\n    by (simp only: mod_div_mult_eq)\n  finally show ?thesis .\nqed\n\nlemma mod_mod_cancel:\n  assumes \"c dvd b\"\n  shows \"a mod b mod c = a mod c\"\nproof -\n  from \\<open>c dvd b\\<close> obtain k where \"b = c * k\"\n    by (rule dvdE)\n  have \"a mod b mod c = a mod (c * k) mod c\"\n    by (simp only: \\<open>b = c * k\\<close>)\n  also have \"\\<dots> = (a mod (c * k) + a div (c * k) * k * c) mod c\"\n    by (simp only: mod_mult_self1)\n  also have \"\\<dots> = (a div (c * k) * (c * k) + a mod (c * k)) mod c\"\n    by (simp only: ac_simps)\n  also have \"\\<dots> = a mod c\"\n    by (simp only: div_mult_mod_eq)\n  finally show ?thesis .\nqed\n\nlemma div_mult_mult2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) div (b * c) = a div b\"\n  by (drule div_mult_mult1) (simp add: mult.commute)\n\nlemma div_mult_mult1_if [simp]:\n  \"(c * a) div (c * b) = (if c = 0 then 0 else a div b)\"\n  by simp_all\n\nlemma mod_mult_mult1:\n  \"(c * a) mod (c * b) = c * (a mod b)\"\nproof (cases \"c = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  from div_mult_mod_eq\n  have \"((c * a) div (c * b)) * (c * b) + (c * a) mod (c * b) = c * a\" .\n  with False have \"c * ((a div b) * b + a mod b) + (c * a) mod (c * b)\n    = c * a + c * (a mod b)\" by (simp add: algebra_simps)\n  with div_mult_mod_eq show ?thesis by simp\nqed\n\nlemma mod_mult_mult2:\n  \"(a * c) mod (b * c) = (a mod b) * c\"\n  using mod_mult_mult1 [of c a b] by (simp add: mult.commute)\n\nlemma mult_mod_left: \"(a mod b) * c = (a * c) mod (b * c)\"\n  by (fact mod_mult_mult2 [symmetric])\n\nlemma mult_mod_right: \"c * (a mod b) = (c * a) mod (c * b)\"\n  by (fact mod_mult_mult1 [symmetric])\n\nlemma dvd_mod: \"k dvd m \\<Longrightarrow> k dvd n \\<Longrightarrow> k dvd (m mod n)\"\n  unfolding dvd_def by (auto simp add: mod_mult_mult1)\n\nlemma div_plus_div_distrib_dvd_left:\n  \"c dvd a \\<Longrightarrow> (a + b) div c = a div c + b div c\"\n  by (cases \"c = 0\") (auto elim: dvdE)\n\nlemma div_plus_div_distrib_dvd_right:\n  \"c dvd b \\<Longrightarrow> (a + b) div c = a div c + b div c\"\n  using div_plus_div_distrib_dvd_left [of c b a]\n  by (simp add: ac_simps)\n\nlemma sum_div_partition:\n  \\<open>(\\<Sum>a\\<in>A. f a) div b = (\\<Sum>a\\<in>A \\<inter> {a. b dvd f a}. f a div b) + (\\<Sum>a\\<in>A \\<inter> {a. \\<not> b dvd f a}. f a) div b\\<close>\n    if \\<open>finite A\\<close>\nproof -\n  have \\<open>A = A \\<inter> {a. b dvd f a} \\<union> A \\<inter> {a. \\<not> b dvd f a}\\<close>\n    by auto\n  then have \\<open>(\\<Sum>a\\<in>A. f a) = (\\<Sum>a\\<in>A \\<inter> {a. b dvd f a} \\<union> A \\<inter> {a. \\<not> b dvd f a}. f a)\\<close>\n    by simp\n  also have \\<open>\\<dots> = (\\<Sum>a\\<in>A \\<inter> {a. b dvd f a}. f a) + (\\<Sum>a\\<in>A \\<inter> {a. \\<not> b dvd f a}. f a)\\<close>\n    using \\<open>finite A\\<close> by (auto intro: sum.union_inter_neutral)\n  finally have *: \\<open>sum f A = sum f (A \\<inter> {a. b dvd f a}) + sum f (A \\<inter> {a. \\<not> b dvd f a})\\<close> .\n  define B where B: \\<open>B = A \\<inter> {a. b dvd f a}\\<close>\n  with \\<open>finite A\\<close> have \\<open>finite B\\<close> and \\<open>a \\<in> B \\<Longrightarrow> b dvd f a\\<close> for a\n    by simp_all\n  then have \\<open>(\\<Sum>a\\<in>B. f a) div b = (\\<Sum>a\\<in>B. f a div b)\\<close> and \\<open>b dvd (\\<Sum>a\\<in>B. f a)\\<close>\n    by induction (simp_all add: div_plus_div_distrib_dvd_left)\n  then show ?thesis using *\n    by (simp add: B div_plus_div_distrib_dvd_left)\nqed\n\nnamed_theorems mod_simps\n\ntext \\<open>Addition respects modular equivalence.\\<close>\n\nlemma mod_add_left_eq [mod_simps]:\n  \"(a mod c + b) mod c = (a + b) mod c\"\nproof -\n  have \"(a + b) mod c = (a div c * c + a mod c + b) mod c\"\n    by (simp only: div_mult_mod_eq)\n  also have \"\\<dots> = (a mod c + b + a div c * c) mod c\"\n    by (simp only: ac_simps)\n  also have \"\\<dots> = (a mod c + b) mod c\"\n    by (rule mod_mult_self1)\n  finally show ?thesis\n    by (rule sym)\nqed\n\nlemma mod_add_right_eq [mod_simps]:\n  \"(a + b mod c) mod c = (a + b) mod c\"\n  using mod_add_left_eq [of b c a] by (simp add: ac_simps)\n\nlemma mod_add_eq:\n  \"(a mod c + b mod c) mod c = (a + b) mod c\"\n  by (simp add: mod_add_left_eq mod_add_right_eq)\n\nlemma mod_sum_eq [mod_simps]:\n  \"(\\<Sum>i\\<in>A. f i mod a) mod a = sum f A mod a\"\nproof (induct A rule: infinite_finite_induct)\n  case (insert i A)\n  then have \"(\\<Sum>i\\<in>insert i A. f i mod a) mod a\n    = (f i mod a + (\\<Sum>i\\<in>A. f i mod a)) mod a\"\n    by simp\n  also have \"\\<dots> = (f i + (\\<Sum>i\\<in>A. f i mod a) mod a) mod a\"\n    by (simp add: mod_simps)\n  also have \"\\<dots> = (f i + (\\<Sum>i\\<in>A. f i) mod a) mod a\"\n    by (simp add: insert.hyps)\n  finally show ?case\n    by (simp add: insert.hyps mod_simps)\nqed simp_all\n\nlemma mod_add_cong:\n  assumes \"a mod c = a' mod c\"\n  assumes \"b mod c = b' mod c\"\n  shows \"(a + b) mod c = (a' + b') mod c\"\nproof -\n  have \"(a mod c + b mod c) mod c = (a' mod c + b' mod c) mod c\"\n    unfolding assms ..\n  then show ?thesis\n    by (simp add: mod_add_eq)\nqed\n\ntext \\<open>Multiplication respects modular equivalence.\\<close>\n\nlemma mod_mult_left_eq [mod_simps]:\n  \"((a mod c) * b) mod c = (a * b) mod c\"\nproof -\n  have \"(a * b) mod c = ((a div c * c + a mod c) * b) mod c\"\n    by (simp only: div_mult_mod_eq)\n  also have \"\\<dots> = (a mod c * b + a div c * b * c) mod c\"\n    by (simp only: algebra_simps)\n  also have \"\\<dots> = (a mod c * b) mod c\"\n    by (rule mod_mult_self1)\n  finally show ?thesis\n    by (rule sym)\nqed\n\nlemma mod_mult_right_eq [mod_simps]:\n  \"(a * (b mod c)) mod c = (a * b) mod c\"\n  using mod_mult_left_eq [of b c a] by (simp add: ac_simps)\n\nlemma mod_mult_eq:\n  \"((a mod c) * (b mod c)) mod c = (a * b) mod c\"\n  by (simp add: mod_mult_left_eq mod_mult_right_eq)\n\nlemma mod_prod_eq [mod_simps]:\n  \"(\\<Prod>i\\<in>A. f i mod a) mod a = prod f A mod a\"\nproof (induct A rule: infinite_finite_induct)\n  case (insert i A)\n  then have \"(\\<Prod>i\\<in>insert i A. f i mod a) mod a\n    = (f i mod a * (\\<Prod>i\\<in>A. f i mod a)) mod a\"\n    by simp\n  also have \"\\<dots> = (f i * ((\\<Prod>i\\<in>A. f i mod a) mod a)) mod a\"\n    by (simp add: mod_simps)\n  also have \"\\<dots> = (f i * ((\\<Prod>i\\<in>A. f i) mod a)) mod a\"\n    by (simp add: insert.hyps)\n  finally show ?case\n    by (simp add: insert.hyps mod_simps)\nqed simp_all\n\nlemma mod_mult_cong:\n  assumes \"a mod c = a' mod c\"\n  assumes \"b mod c = b' mod c\"\n  shows \"(a * b) mod c = (a' * b') mod c\"\nproof -\n  have \"(a mod c * (b mod c)) mod c = (a' mod c * (b' mod c)) mod c\"\n    unfolding assms ..\n  then show ?thesis\n    by (simp add: mod_mult_eq)\nqed\n\ntext \\<open>Exponentiation respects modular equivalence.\\<close>\n\nlemma power_mod [mod_simps]: \n  \"((a mod b) ^ n) mod b = (a ^ n) mod b\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(a mod b) ^ Suc n mod b = (a mod b) * ((a mod b) ^ n mod b) mod b\"\n    by (simp add: mod_mult_right_eq)\n  with Suc show ?case\n    by (simp add: mod_mult_left_eq mod_mult_right_eq)\nqed\n\nlemma power_diff_power_eq:\n  \\<open>a ^ m div a ^ n = (if n \\<le> m then a ^ (m - n) else 1 div a ^ (n - m))\\<close>\n    if \\<open>a \\<noteq> 0\\<close>\nproof (cases \\<open>n \\<le> m\\<close>)\n  case True\n  with that power_diff [symmetric, of a n m] show ?thesis by simp\nnext\n  case False\n  then obtain q where n: \\<open>n = m + Suc q\\<close>\n    by (auto simp add: not_le dest: less_imp_Suc_add)\n  then have \\<open>a ^ m div a ^ n = (a ^ m * 1) div (a ^ m * a ^ Suc q)\\<close>\n    by (simp add: power_add ac_simps)\n  moreover from that have \\<open>a ^ m \\<noteq> 0\\<close>\n    by simp\n  ultimately have \\<open>a ^ m div a ^ n = 1 div a ^ Suc q\\<close>\n    by (subst (asm) div_mult_mult1) simp\n  with False n show ?thesis\n    by simp\nqed\n\nend\n\n\nclass euclidean_ring_cancel = euclidean_ring + euclidean_semiring_cancel\nbegin\n\nsubclass idom_divide ..\n\nlemma div_minus_minus [simp]: \"(- a) div (- b) = a div b\"\n  using div_mult_mult1 [of \"- 1\" a b] by simp\n\nlemma mod_minus_minus [simp]: \"(- a) mod (- b) = - (a mod b)\"\n  using mod_mult_mult1 [of \"- 1\" a b] by simp\n\nlemma div_minus_right: \"a div (- b) = (- a) div b\"\n  using div_minus_minus [of \"- a\" b] by simp\n\nlemma mod_minus_right: \"a mod (- b) = - ((- a) mod b)\"\n  using mod_minus_minus [of \"- a\" b] by simp\n\nlemma div_minus1_right [simp]: \"a div (- 1) = - a\"\n  using div_minus_right [of a 1] by simp\n\nlemma mod_minus1_right [simp]: \"a mod (- 1) = 0\"\n  using mod_minus_right [of a 1] by simp\n\ntext \\<open>Negation respects modular equivalence.\\<close>\n\nlemma mod_minus_eq [mod_simps]:\n  \"(- (a mod b)) mod b = (- a) mod b\"\nproof -\n  have \"(- a) mod b = (- (a div b * b + a mod b)) mod b\"\n    by (simp only: div_mult_mod_eq)\n  also have \"\\<dots> = (- (a mod b) + - (a div b) * b) mod b\"\n    by (simp add: ac_simps)\n  also have \"\\<dots> = (- (a mod b)) mod b\"\n    by (rule mod_mult_self1)\n  finally show ?thesis\n    by (rule sym)\nqed\n\nlemma mod_minus_cong:\n  assumes \"a mod b = a' mod b\"\n  shows \"(- a) mod b = (- a') mod b\"\nproof -\n  have \"(- (a mod b)) mod b = (- (a' mod b)) mod b\"\n    unfolding assms ..\n  then show ?thesis\n    by (simp add: mod_minus_eq)\nqed\n\ntext \\<open>Subtraction respects modular equivalence.\\<close>\n\nlemma mod_diff_left_eq [mod_simps]:\n  \"(a mod c - b) mod c = (a - b) mod c\"\n  using mod_add_cong [of a c \"a mod c\" \"- b\" \"- b\"]\n  by simp\n\nlemma mod_diff_right_eq [mod_simps]:\n  \"(a - b mod c) mod c = (a - b) mod c\"\n  using mod_add_cong [of a c a \"- b\" \"- (b mod c)\"] mod_minus_cong [of \"b mod c\" c b]\n  by simp\n\nlemma mod_diff_eq:\n  \"(a mod c - b mod c) mod c = (a - b) mod c\"\n  using mod_add_cong [of a c \"a mod c\" \"- b\" \"- (b mod c)\"] mod_minus_cong [of \"b mod c\" c b]\n  by simp\n\nlemma mod_diff_cong:\n  assumes \"a mod c = a' mod c\"\n  assumes \"b mod c = b' mod c\"\n  shows \"(a - b) mod c = (a' - b') mod c\"\n  using assms mod_add_cong [of a c a' \"- b\" \"- b'\"] mod_minus_cong [of b c \"b'\"]\n  by simp\n\nlemma minus_mod_self2 [simp]:\n  \"(a - b) mod b = a mod b\"\n  using mod_diff_right_eq [of a b b]\n  by (simp add: mod_diff_right_eq)\n\nlemma minus_mod_self1 [simp]:\n  \"(b - a) mod b = - a mod b\"\n  using mod_add_self2 [of \"- a\" b] by simp\n\nlemma mod_eq_dvd_iff:\n  \"a mod c = b mod c \\<longleftrightarrow> c dvd a - b\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then have \"(a mod c - b mod c) mod c = 0\"\n    by simp\n  then show ?Q\n    by (simp add: dvd_eq_mod_eq_0 mod_simps)\nnext\n  assume ?Q\n  then obtain d where d: \"a - b = c * d\" ..\n  then have \"a = c * d + b\"\n    by (simp add: algebra_simps)\n  then show ?P by simp\nqed\n\nlemma mod_eqE:\n  assumes \"a mod c = b mod c\"\n  obtains d where \"b = a + c * d\"\nproof -\n  from assms have \"c dvd a - b\"\n    by (simp add: mod_eq_dvd_iff)\n  then obtain d where \"a - b = c * d\" ..\n  then have \"b = a + c * - d\"\n    by (simp add: algebra_simps)\n  with that show thesis .\nqed\n\nlemma invertible_coprime:\n  \"coprime a c\" if \"a * b mod c = 1\"\n  by (rule coprimeI) (use that dvd_mod_iff [of _ c \"a * b\"] in auto)\n\nend\n\n  \nsubsection \\<open>Uniquely determined division\\<close>\n  \nclass unique_euclidean_semiring = euclidean_semiring + \n  assumes euclidean_size_mult: \"euclidean_size (a * b) = euclidean_size a * euclidean_size b\"\n  fixes division_segment :: \"'a \\<Rightarrow> 'a\"\n  assumes is_unit_division_segment [simp]: \"is_unit (division_segment a)\"\n    and division_segment_mult:\n    \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> division_segment (a * b) = division_segment a * division_segment b\"\n    and division_segment_mod:\n    \"b \\<noteq> 0 \\<Longrightarrow> \\<not> b dvd a \\<Longrightarrow> division_segment (a mod b) = division_segment b\"\n  assumes div_bounded:\n    \"b \\<noteq> 0 \\<Longrightarrow> division_segment r = division_segment b\n    \\<Longrightarrow> euclidean_size r < euclidean_size b\n    \\<Longrightarrow> (q * b + r) div b = q\"\nbegin\n\nlemma division_segment_not_0 [simp]:\n  \"division_segment a \\<noteq> 0\"\n  using is_unit_division_segment [of a] is_unitE [of \"division_segment a\"] by blast\n\nlemma divmod_cases [case_names divides remainder by0]:\n  obtains \n    (divides) q where \"b \\<noteq> 0\"\n      and \"a div b = q\"\n      and \"a mod b = 0\"\n      and \"a = q * b\"\n  | (remainder) q r where \"b \\<noteq> 0\"\n      and \"division_segment r = division_segment b\"\n      and \"euclidean_size r < euclidean_size b\"\n      and \"r \\<noteq> 0\"\n      and \"a div b = q\"\n      and \"a mod b = r\"\n      and \"a = q * b + r\"\n  | (by0) \"b = 0\"\nproof (cases \"b = 0\")\n  case True\n  then show thesis\n  by (rule by0)\nnext\n  case False\n  show thesis\n  proof (cases \"b dvd a\")\n    case True\n    then obtain q where \"a = b * q\" ..\n    with \\<open>b \\<noteq> 0\\<close> divides\n    show thesis\n      by (simp add: ac_simps)\n  next\n    case False\n    then have \"a mod b \\<noteq> 0\"\n      by (simp add: mod_eq_0_iff_dvd)\n    moreover from \\<open>b \\<noteq> 0\\<close> \\<open>\\<not> b dvd a\\<close> have \"division_segment (a mod b) = division_segment b\"\n      by (rule division_segment_mod)\n    moreover have \"euclidean_size (a mod b) < euclidean_size b\"\n      using \\<open>b \\<noteq> 0\\<close> by (rule mod_size_less)\n    moreover have \"a = a div b * b + a mod b\"\n      by (simp add: div_mult_mod_eq)\n    ultimately show thesis\n      using \\<open>b \\<noteq> 0\\<close> by (blast intro!: remainder)\n  qed\nqed\n\nlemma div_eqI:\n  \"a div b = q\" if \"b \\<noteq> 0\" \"division_segment r = division_segment b\"\n    \"euclidean_size r < euclidean_size b\" \"q * b + r = a\"\nproof -\n  from that have \"(q * b + r) div b = q\"\n    by (auto intro: div_bounded)\n  with that show ?thesis\n    by simp\nqed\n\nlemma mod_eqI:\n  \"a mod b = r\" if \"b \\<noteq> 0\" \"division_segment r = division_segment b\"\n    \"euclidean_size r < euclidean_size b\" \"q * b + r = a\" \nproof -\n  from that have \"a div b = q\"\n    by (rule div_eqI)\n  moreover have \"a div b * b + a mod b = a\"\n    by (fact div_mult_mod_eq)\n  ultimately have \"a div b * b + a mod b = a div b * b + r\"\n    using \\<open>q * b + r = a\\<close> by simp\n  then show ?thesis\n    by simp\nqed\n\nsubclass euclidean_semiring_cancel\nproof\n  show \"(a + c * b) div b = c + a div b\" if \"b \\<noteq> 0\" for a b c\n  proof (cases a b rule: divmod_cases)\n    case by0\n    with \\<open>b \\<noteq> 0\\<close> show ?thesis\n      by simp\n  next\n    case (divides q)\n    then show ?thesis\n      by (simp add: ac_simps)\n  next\n    case (remainder q r)\n    then show ?thesis\n      by (auto intro: div_eqI simp add: algebra_simps)\n  qed\nnext\n  show\"(c * a) div (c * b) = a div b\" if \"c \\<noteq> 0\" for a b c\n  proof (cases a b rule: divmod_cases)\n    case by0\n    then show ?thesis\n      by simp\n  next\n    case (divides q)\n    with \\<open>c \\<noteq> 0\\<close> show ?thesis\n      by (simp add: mult.left_commute [of c])\n  next\n    case (remainder q r)\n    from \\<open>b \\<noteq> 0\\<close> \\<open>c \\<noteq> 0\\<close> have \"b * c \\<noteq> 0\"\n      by simp\n    from remainder \\<open>c \\<noteq> 0\\<close>\n    have \"division_segment (r * c) = division_segment (b * c)\"\n      and \"euclidean_size (r * c) < euclidean_size (b * c)\"\n      by (simp_all add: division_segment_mult division_segment_mod euclidean_size_mult)\n    with remainder show ?thesis\n      by (auto intro!: div_eqI [of _ \"c * (a mod b)\"] simp add: algebra_simps)\n        (use \\<open>b * c \\<noteq> 0\\<close> in simp)\n  qed\nqed\n\nlemma div_mult1_eq:\n  \"(a * b) div c = a * (b div c) + a * (b mod c) div c\"\nproof (cases \"a * (b mod c)\" c rule: divmod_cases)\n  case (divides q)\n  have \"a * b = a * (b div c * c + b mod c)\"\n    by (simp add: div_mult_mod_eq)\n  also have \"\\<dots> = (a * (b div c) + q) * c\"\n    using divides by (simp add: algebra_simps)\n  finally have \"(a * b) div c = \\<dots> div c\"\n    by simp\n  with divides show ?thesis\n    by simp\nnext\n  case (remainder q r)\n  from remainder(1-3) show ?thesis\n  proof (rule div_eqI)\n    have \"a * b = a * (b div c * c + b mod c)\"\n      by (simp add: div_mult_mod_eq)\n    also have \"\\<dots> = a * c * (b div c) + q * c + r\"\n      using remainder by (simp add: algebra_simps)\n    finally show \"(a * (b div c) + a * (b mod c) div c) * c + r = a * b\"\n      using remainder(5-7) by (simp add: algebra_simps)\n  qed\nnext\n  case by0\n  then show ?thesis\n    by simp\nqed\n\nlemma div_add1_eq:\n  \"(a + b) div c = a div c + b div c + (a mod c + b mod c) div c\"\nproof (cases \"a mod c + b mod c\" c rule: divmod_cases)\n  case (divides q)\n  have \"a + b = (a div c * c + a mod c) + (b div c * c + b mod c)\"\n    using mod_mult_div_eq [of a c] mod_mult_div_eq [of b c] by (simp add: ac_simps)\n  also have \"\\<dots> = (a div c + b div c) * c + (a mod c + b mod c)\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> = (a div c + b div c + q) * c\"\n    using divides by (simp add: algebra_simps)\n  finally have \"(a + b) div c = (a div c + b div c + q) * c div c\"\n    by simp\n  with divides show ?thesis\n    by simp\nnext\n  case (remainder q r)\n  from remainder(1-3) show ?thesis\n  proof (rule div_eqI)\n    have \"(a div c + b div c + q) * c + r + (a mod c + b mod c) =\n        (a div c * c + a mod c) + (b div c * c + b mod c) + q * c + r\"\n      by (simp add: algebra_simps)\n    also have \"\\<dots> = a + b + (a mod c + b mod c)\"\n      by (simp add: div_mult_mod_eq remainder) (simp add: ac_simps)\n    finally show \"(a div c + b div c + (a mod c + b mod c) div c) * c + r = a + b\"\n      using remainder by simp\n  qed\nnext\n  case by0\n  then show ?thesis\n    by simp\nqed\n\nlemma div_eq_0_iff:\n  \"a div b = 0 \\<longleftrightarrow> euclidean_size a < euclidean_size b \\<or> b = 0\" (is \"_ \\<longleftrightarrow> ?P\")\n  if \"division_segment a = division_segment b\"\nproof\n  assume ?P\n  with that show \"a div b = 0\"\n    by (cases \"b = 0\") (auto intro: div_eqI)\nnext\n  assume \"a div b = 0\"\n  then have \"a mod b = a\"\n    using div_mult_mod_eq [of a b] by simp\n  with mod_size_less [of b a] show ?P\n    by auto\nqed\n\nend\n\nclass unique_euclidean_ring = euclidean_ring + unique_euclidean_semiring\nbegin\n  \nsubclass euclidean_ring_cancel ..\n\nend\n\n\nsubsection \\<open>Euclidean division on \\<^typ>\\<open>nat\\<close>\\<close>\n\ninstantiation nat :: normalization_semidom\nbegin\n\ndefinition normalize_nat :: \"nat \\<Rightarrow> nat\"\n  where [simp]: \"normalize = (id :: nat \\<Rightarrow> nat)\"\n\ndefinition unit_factor_nat :: \"nat \\<Rightarrow> nat\"\n  where \"unit_factor n = (if n = 0 then 0 else 1 :: nat)\"\n\nlemma unit_factor_simps [simp]:\n  \"unit_factor 0 = (0::nat)\"\n  \"unit_factor (Suc n) = 1\"\n  by (simp_all add: unit_factor_nat_def)\n\ndefinition divide_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"m div n = (if n = 0 then 0 else Max {k::nat. k * n \\<le> m})\"\n\ninstance\n  by standard (auto simp add: divide_nat_def ac_simps unit_factor_nat_def intro: Max_eqI)\n\nend\n\nlemma coprime_Suc_0_left [simp]:\n  \"coprime (Suc 0) n\"\n  using coprime_1_left [of n] by simp\n\nlemma coprime_Suc_0_right [simp]:\n  \"coprime n (Suc 0)\"\n  using coprime_1_right [of n] by simp\n\nlemma coprime_common_divisor_nat: \"coprime a b \\<Longrightarrow> x dvd a \\<Longrightarrow> x dvd b \\<Longrightarrow> x = 1\"\n  for a b :: nat\n  by (drule coprime_common_divisor [of _ _ x]) simp_all\n\ninstantiation nat :: unique_euclidean_semiring\nbegin\n\ndefinition euclidean_size_nat :: \"nat \\<Rightarrow> nat\"\n  where [simp]: \"euclidean_size_nat = id\"\n\ndefinition division_segment_nat :: \"nat \\<Rightarrow> nat\"\n  where [simp]: \"division_segment_nat n = 1\"\n\ndefinition modulo_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"m mod n = m - (m div n * (n::nat))\"\n\ninstance proof\n  fix m n :: nat\n  have ex: \"\\<exists>k. k * n \\<le> l\" for l :: nat\n    by (rule exI [of _ 0]) simp\n  have fin: \"finite {k. k * n \\<le> l}\" if \"n > 0\" for l\n  proof -\n    from that have \"{k. k * n \\<le> l} \\<subseteq> {k. k \\<le> l}\"\n      by (cases n) auto\n    then show ?thesis\n      by (rule finite_subset) simp\n  qed\n  have mult_div_unfold: \"n * (m div n) = Max {l. l \\<le> m \\<and> n dvd l}\"\n  proof (cases \"n = 0\")\n    case True\n    moreover have \"{l. l = 0 \\<and> l \\<le> m} = {0::nat}\"\n      by auto\n    ultimately show ?thesis\n      by simp\n  next\n    case False\n    with ex [of m] fin have \"n * Max {k. k * n \\<le> m} = Max (times n ` {k. k * n \\<le> m})\"\n      by (auto simp add: nat_mult_max_right intro: hom_Max_commute)\n    also have \"times n ` {k. k * n \\<le> m} = {l. l \\<le> m \\<and> n dvd l}\"\n      by (auto simp add: ac_simps elim!: dvdE)\n    finally show ?thesis\n      using False by (simp add: divide_nat_def ac_simps)\n  qed\n  have less_eq: \"m div n * n \\<le> m\"\n    by (auto simp add: mult_div_unfold ac_simps intro: Max.boundedI)\n  then show \"m div n * n + m mod n = m\"\n    by (simp add: modulo_nat_def)\n  assume \"n \\<noteq> 0\" \n  show \"euclidean_size (m mod n) < euclidean_size n\"\n  proof -\n    have \"m < Suc (m div n) * n\"\n    proof (rule ccontr)\n      assume \"\\<not> m < Suc (m div n) * n\"\n      then have \"Suc (m div n) * n \\<le> m\"\n        by (simp add: not_less)\n      moreover from \\<open>n \\<noteq> 0\\<close> have \"Max {k. k * n \\<le> m} < Suc (m div n)\"\n        by (simp add: divide_nat_def)\n      with \\<open>n \\<noteq> 0\\<close> ex fin have \"\\<And>k. k * n \\<le> m \\<Longrightarrow> k < Suc (m div n)\"\n        by auto\n      ultimately have \"Suc (m div n) < Suc (m div n)\"\n        by blast\n      then show False\n        by simp\n    qed\n    with \\<open>n \\<noteq> 0\\<close> show ?thesis\n      by (simp add: modulo_nat_def)\n  qed\n  show \"euclidean_size m \\<le> euclidean_size (m * n)\"\n    using \\<open>n \\<noteq> 0\\<close> by (cases n) simp_all\n  fix q r :: nat\n  show \"(q * n + r) div n = q\" if \"euclidean_size r < euclidean_size n\"\n  proof -\n    from that have \"r < n\"\n      by simp\n    have \"k \\<le> q\" if \"k * n \\<le> q * n + r\" for k\n    proof (rule ccontr)\n      assume \"\\<not> k \\<le> q\"\n      then have \"q < k\"\n        by simp\n      then obtain l where \"k = Suc (q + l)\"\n        by (auto simp add: less_iff_Suc_add)\n      with \\<open>r < n\\<close> that show False\n        by (simp add: algebra_simps)\n    qed\n    with \\<open>n \\<noteq> 0\\<close> ex fin show ?thesis\n      by (auto simp add: divide_nat_def Max_eq_iff)\n  qed\nqed simp_all\n\nend\n\ntext \\<open>Tool support\\<close>\n\nML \\<open>\nstructure Cancel_Div_Mod_Nat = Cancel_Div_Mod\n(\n  val div_name = \\<^const_name>\\<open>divide\\<close>;\n  val mod_name = \\<^const_name>\\<open>modulo\\<close>;\n  val mk_binop = HOLogic.mk_binop;\n  val dest_plus = HOLogic.dest_bin \\<^const_name>\\<open>Groups.plus\\<close> HOLogic.natT;\n  val mk_sum = Arith_Data.mk_sum;\n  fun dest_sum tm =\n    if HOLogic.is_zero tm then []\n    else\n      (case try HOLogic.dest_Suc tm of\n        SOME t => HOLogic.Suc_zero :: dest_sum t\n      | NONE =>\n          (case try dest_plus tm of\n            SOME (t, u) => dest_sum t @ dest_sum u\n          | NONE => [tm]));\n\n  val div_mod_eqs = map mk_meta_eq @{thms cancel_div_mod_rules};\n\n  val prove_eq_sums = Arith_Data.prove_conv2 all_tac\n    (Arith_Data.simp_all_tac @{thms add_0_left add_0_right ac_simps})\n)\n\\<close>\n\nsimproc_setup cancel_div_mod_nat (\"(m::nat) + n\") =\n  \\<open>K Cancel_Div_Mod_Nat.proc\\<close>\n\nlemma div_nat_eqI:\n  \"m div n = q\" if \"n * q \\<le> m\" and \"m < n * Suc q\" for m n q :: nat\n  by (rule div_eqI [of _ \"m - n * q\"]) (use that in \\<open>simp_all add: algebra_simps\\<close>)\n\nlemma mod_nat_eqI:\n  \"m mod n = r\" if \"r < n\" and \"r \\<le> m\" and \"n dvd m - r\" for m n r :: nat\n  by (rule mod_eqI [of _ _ \"(m - r) div n\"]) (use that in \\<open>simp_all add: algebra_simps\\<close>)\n\nlemma div_mult_self_is_m [simp]:\n  \"m * n div n = m\" if \"n > 0\" for m n :: nat\n  using that by simp\n\nlemma div_mult_self1_is_m [simp]:\n  \"n * m div n = m\" if \"n > 0\" for m n :: nat\n  using that by simp\n\nlemma mod_less_divisor [simp]:\n  \"m mod n < n\" if \"n > 0\" for m n :: nat\n  using mod_size_less [of n m] that by simp\n\nlemma mod_le_divisor [simp]:\n  \"m mod n \\<le> n\" if \"n > 0\" for m n :: nat\n  using that by (auto simp add: le_less)\n\nlemma div_times_less_eq_dividend [simp]:\n  \"m div n * n \\<le> m\" for m n :: nat\n  by (simp add: minus_mod_eq_div_mult [symmetric])\n\nlemma times_div_less_eq_dividend [simp]:\n  \"n * (m div n) \\<le> m\" for m n :: nat\n  using div_times_less_eq_dividend [of m n]\n  by (simp add: ac_simps)\n\nlemma dividend_less_div_times:\n  \"m < n + (m div n) * n\" if \"0 < n\" for m n :: nat\nproof -\n  from that have \"m mod n < n\"\n    by simp\n  then show ?thesis\n    by (simp add: minus_mod_eq_div_mult [symmetric])\nqed\n\nlemma dividend_less_times_div:\n  \"m < n + n * (m div n)\" if \"0 < n\" for m n :: nat\n  using dividend_less_div_times [of n m] that\n  by (simp add: ac_simps)\n\nlemma mod_Suc_le_divisor [simp]:\n  \"m mod Suc n \\<le> n\"\n  using mod_less_divisor [of \"Suc n\" m] by arith\n\nlemma mod_less_eq_dividend [simp]:\n  \"m mod n \\<le> m\" for m n :: nat\nproof (rule add_leD2)\n  from div_mult_mod_eq have \"m div n * n + m mod n = m\" .\n  then show \"m div n * n + m mod n \\<le> m\" by auto\nqed\n\nlemma\n  div_less [simp]: \"m div n = 0\"\n  and mod_less [simp]: \"m mod n = m\"\n  if \"m < n\" for m n :: nat\n  using that by (auto intro: div_eqI mod_eqI) \n\nlemma le_div_geq:\n  \"m div n = Suc ((m - n) div n)\" if \"0 < n\" and \"n \\<le> m\" for m n :: nat\nproof -\n  from \\<open>n \\<le> m\\<close> obtain q where \"m = n + q\"\n    by (auto simp add: le_iff_add)\n  with \\<open>0 < n\\<close> show ?thesis\n    by (simp add: div_add_self1)\nqed\n\nlemma le_mod_geq:\n  \"m mod n = (m - n) mod n\" if \"n \\<le> m\" for m n :: nat\nproof -\n  from \\<open>n \\<le> m\\<close> obtain q where \"m = n + q\"\n    by (auto simp add: le_iff_add)\n  then show ?thesis\n    by simp\nqed\n\nlemma div_if:\n  \"m div n = (if m < n \\<or> n = 0 then 0 else Suc ((m - n) div n))\"\n  by (simp add: le_div_geq)\n\nlemma mod_if:\n  \"m mod n = (if m < n then m else (m - n) mod n)\" for m n :: nat\n  by (simp add: le_mod_geq)\n\nlemma div_eq_0_iff:\n  \"m div n = 0 \\<longleftrightarrow> m < n \\<or> n = 0\" for m n :: nat\n  by (simp add: div_eq_0_iff)\n\nlemma div_greater_zero_iff:\n  \"m div n > 0 \\<longleftrightarrow> n \\<le> m \\<and> n > 0\" for m n :: nat\n  using div_eq_0_iff [of m n] by auto\n\nlemma mod_greater_zero_iff_not_dvd:\n  \"m mod n > 0 \\<longleftrightarrow> \\<not> n dvd m\" for m n :: nat\n  by (simp add: dvd_eq_mod_eq_0)\n\nlemma div_by_Suc_0 [simp]:\n  \"m div Suc 0 = m\"\n  using div_by_1 [of m] by simp\n\nlemma mod_by_Suc_0 [simp]:\n  \"m mod Suc 0 = 0\"\n  using mod_by_1 [of m] by simp\n\nlemma div2_Suc_Suc [simp]:\n  \"Suc (Suc m) div 2 = Suc (m div 2)\"\n  by (simp add: numeral_2_eq_2 le_div_geq)\n\nlemma Suc_n_div_2_gt_zero [simp]:\n  \"0 < Suc n div 2\" if \"n > 0\" for n :: nat\n  using that by (cases n) simp_all\n\nlemma div_2_gt_zero [simp]:\n  \"0 < n div 2\" if \"Suc 0 < n\" for n :: nat\n  using that Suc_n_div_2_gt_zero [of \"n - 1\"] by simp\n\nlemma mod2_Suc_Suc [simp]:\n  \"Suc (Suc m) mod 2 = m mod 2\"\n  by (simp add: numeral_2_eq_2 le_mod_geq)\n\nlemma add_self_div_2 [simp]:\n  \"(m + m) div 2 = m\" for m :: nat\n  by (simp add: mult_2 [symmetric])\n\nlemma add_self_mod_2 [simp]:\n  \"(m + m) mod 2 = 0\" for m :: nat\n  by (simp add: mult_2 [symmetric])\n\nlemma mod2_gr_0 [simp]:\n  \"0 < m mod 2 \\<longleftrightarrow> m mod 2 = 1\" for m :: nat\nproof -\n  have \"m mod 2 < 2\"\n    by (rule mod_less_divisor) simp\n  then have \"m mod 2 = 0 \\<or> m mod 2 = 1\"\n    by arith\n  then show ?thesis\n    by auto     \nqed\n\nlemma mod_Suc_eq [mod_simps]:\n  \"Suc (m mod n) mod n = Suc m mod n\"\nproof -\n  have \"(m mod n + 1) mod n = (m + 1) mod n\"\n    by (simp only: mod_simps)\n  then show ?thesis\n    by simp\nqed\n\nlemma mod_Suc_Suc_eq [mod_simps]:\n  \"Suc (Suc (m mod n)) mod n = Suc (Suc m) mod n\"\nproof -\n  have \"(m mod n + 2) mod n = (m + 2) mod n\"\n    by (simp only: mod_simps)\n  then show ?thesis\n    by simp\nqed\n\nlemma\n  Suc_mod_mult_self1 [simp]: \"Suc (m + k * n) mod n = Suc m mod n\"\n  and Suc_mod_mult_self2 [simp]: \"Suc (m + n * k) mod n = Suc m mod n\"\n  and Suc_mod_mult_self3 [simp]: \"Suc (k * n + m) mod n = Suc m mod n\"\n  and Suc_mod_mult_self4 [simp]: \"Suc (n * k + m) mod n = Suc m mod n\"\n  by (subst mod_Suc_eq [symmetric], simp add: mod_simps)+\n\nlemma Suc_0_mod_eq [simp]:\n  \"Suc 0 mod n = of_bool (n \\<noteq> Suc 0)\"\n  by (cases n) simp_all\n\ncontext\n  fixes m n q :: nat\nbegin\n\nprivate lemma eucl_rel_mult2:\n  \"m mod n + n * (m div n mod q) < n * q\"\n  if \"n > 0\" and \"q > 0\"\nproof -\n  from \\<open>n > 0\\<close> have \"m mod n < n\"\n    by (rule mod_less_divisor)\n  from \\<open>q > 0\\<close> have \"m div n mod q < q\"\n    by (rule mod_less_divisor)\n  then obtain s where \"q = Suc (m div n mod q + s)\"\n    by (blast dest: less_imp_Suc_add)\n  moreover have \"m mod n + n * (m div n mod q) < n * Suc (m div n mod q + s)\"\n    using \\<open>m mod n < n\\<close> by (simp add: add_mult_distrib2)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma div_mult2_eq:\n  \"m div (n * q) = (m div n) div q\"\nproof (cases \"n = 0 \\<or> q = 0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  with eucl_rel_mult2 show ?thesis\n    by (auto intro: div_eqI [of _ \"n * (m div n mod q) + m mod n\"]\n      simp add: algebra_simps add_mult_distrib2 [symmetric])\nqed\n\nlemma mod_mult2_eq:\n  \"m mod (n * q) = n * (m div n mod q) + m mod n\"\nproof (cases \"n = 0 \\<or> q = 0\")\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  with eucl_rel_mult2 show ?thesis\n    by (auto intro: mod_eqI [of _ _ \"(m div n) div q\"]\n      simp add: algebra_simps add_mult_distrib2 [symmetric])\nqed\n\nend\n\nlemma div_le_mono:\n  \"m div k \\<le> n div k\" if \"m \\<le> n\" for m n k :: nat\nproof -\n  from that obtain q where \"n = m + q\"\n    by (auto simp add: le_iff_add)\n  then show ?thesis\n    by (simp add: div_add1_eq [of m q k])\nqed\n\ntext \\<open>Antimonotonicity of \\<^const>\\<open>divide\\<close> in second argument\\<close>\n\nlemma div_le_mono2:\n  \"k div n \\<le> k div m\" if \"0 < m\" and \"m \\<le> n\" for m n k :: nat\nusing that proof (induct k arbitrary: m rule: less_induct)\n  case (less k)\n  show ?case\n  proof (cases \"n \\<le> k\")\n    case False\n    then show ?thesis\n      by simp\n  next\n    case True\n    have \"(k - n) div n \\<le> (k - m) div n\"\n      using less.prems\n      by (blast intro: div_le_mono diff_le_mono2)\n    also have \"\\<dots> \\<le> (k - m) div m\"\n      using \\<open>n \\<le> k\\<close> less.prems less.hyps [of \"k - m\" m]\n      by simp\n    finally show ?thesis\n      using \\<open>n \\<le> k\\<close> less.prems\n      by (simp add: le_div_geq)\n  qed\nqed\n\nlemma div_le_dividend [simp]:\n  \"m div n \\<le> m\" for m n :: nat\n  using div_le_mono2 [of 1 n m] by (cases \"n = 0\") simp_all\n\nlemma div_less_dividend [simp]:\n  \"m div n < m\" if \"1 < n\" and \"0 < m\" for m n :: nat\nusing that proof (induct m rule: less_induct)\n  case (less m)\n  show ?case\n  proof (cases \"n < m\")\n    case False\n    with less show ?thesis\n      by (cases \"n = m\") simp_all\n  next\n    case True\n    then show ?thesis\n      using less.hyps [of \"m - n\"] less.prems\n      by (simp add: le_div_geq)\n  qed\nqed\n\nlemma div_eq_dividend_iff:\n  \"m div n = m \\<longleftrightarrow> n = 1\" if \"m > 0\" for m n :: nat\nproof\n  assume \"n = 1\"\n  then show \"m div n = m\"\n    by simp\nnext\n  assume P: \"m div n = m\"\n  show \"n = 1\"\n  proof (rule ccontr)\n    have \"n \\<noteq> 0\"\n      by (rule ccontr) (use that P in auto)\n    moreover assume \"n \\<noteq> 1\"\n    ultimately have \"n > 1\"\n      by simp\n    with that have \"m div n < m\"\n      by simp\n    with P show False\n      by simp\n  qed\nqed\n\nlemma less_mult_imp_div_less:\n  \"m div n < i\" if \"m < i * n\" for m n i :: nat\nproof -\n  from that have \"i * n > 0\"\n    by (cases \"i * n = 0\") simp_all\n  then have \"i > 0\" and \"n > 0\"\n    by simp_all\n  have \"m div n * n \\<le> m\"\n    by simp\n  then have \"m div n * n < i * n\"\n    using that by (rule le_less_trans)\n  with \\<open>n > 0\\<close> show ?thesis\n    by simp\nqed\n\ntext \\<open>A fact for the mutilated chess board\\<close>\n\nlemma mod_Suc:\n  \"Suc m mod n = (if Suc (m mod n) = n then 0 else Suc (m mod n))\" (is \"_ = ?rhs\")\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  have \"Suc m mod n = Suc (m mod n) mod n\"\n    by (simp add: mod_simps)\n  also have \"\\<dots> = ?rhs\"\n    using False by (auto intro!: mod_nat_eqI intro: neq_le_trans simp add: Suc_le_eq)\n  finally show ?thesis .\nqed\n\nlemma Suc_times_mod_eq:\n  \"Suc (m * n) mod m = 1\" if \"Suc 0 < m\"\n  using that by (simp add: mod_Suc)\n\nlemma Suc_times_numeral_mod_eq [simp]:\n  \"Suc (numeral k * n) mod numeral k = 1\" if \"numeral k \\<noteq> (1::nat)\"\n  by (rule Suc_times_mod_eq) (use that in simp)\n\nlemma Suc_div_le_mono [simp]:\n  \"m div n \\<le> Suc m div n\"\n  by (simp add: div_le_mono)\n\ntext \\<open>These lemmas collapse some needless occurrences of Suc:\n  at least three Sucs, since two and fewer are rewritten back to Suc again!\n  We already have some rules to simplify operands smaller than 3.\\<close>\n\nlemma div_Suc_eq_div_add3 [simp]:\n  \"m div Suc (Suc (Suc n)) = m div (3 + n)\"\n  by (simp add: Suc3_eq_add_3)\n\nlemma mod_Suc_eq_mod_add3 [simp]:\n  \"m mod Suc (Suc (Suc n)) = m mod (3 + n)\"\n  by (simp add: Suc3_eq_add_3)\n\nlemma Suc_div_eq_add3_div:\n  \"Suc (Suc (Suc m)) div n = (3 + m) div n\"\n  by (simp add: Suc3_eq_add_3)\n\nlemma Suc_mod_eq_add3_mod:\n  \"Suc (Suc (Suc m)) mod n = (3 + m) mod n\"\n  by (simp add: Suc3_eq_add_3)\n\nlemmas Suc_div_eq_add3_div_numeral [simp] =\n  Suc_div_eq_add3_div [of _ \"numeral v\"] for v\n\nlemmas Suc_mod_eq_add3_mod_numeral [simp] =\n  Suc_mod_eq_add3_mod [of _ \"numeral v\"] for v\n\nlemma (in field_char_0) of_nat_div:\n  \"of_nat (m div n) = ((of_nat m - of_nat (m mod n)) / of_nat n)\"\nproof -\n  have \"of_nat (m div n) = ((of_nat (m div n * n + m mod n) - of_nat (m mod n)) / of_nat n :: 'a)\"\n    unfolding of_nat_add by (cases \"n = 0\") simp_all\n  then show ?thesis\n    by simp\nqed\n\ntext \\<open>An ``induction'' law for modulus arithmetic.\\<close>\n\nlemma mod_induct [consumes 3, case_names step]:\n  \"P m\" if \"P n\" and \"n < p\" and \"m < p\"\n    and step: \"\\<And>n. n < p \\<Longrightarrow> P n \\<Longrightarrow> P (Suc n mod p)\"\nusing \\<open>m < p\\<close> proof (induct m)\n  case 0\n  show ?case\n  proof (rule ccontr)\n    assume \"\\<not> P 0\"\n    from \\<open>n < p\\<close> have \"0 < p\"\n      by simp\n    from \\<open>n < p\\<close> obtain m where \"0 < m\" and \"p = n + m\"\n      by (blast dest: less_imp_add_positive)\n    with \\<open>P n\\<close> have \"P (p - m)\"\n      by simp\n    moreover have \"\\<not> P (p - m)\"\n    using \\<open>0 < m\\<close> proof (induct m)\n      case 0\n      then show ?case\n        by simp\n    next\n      case (Suc m)\n      show ?case\n      proof\n        assume P: \"P (p - Suc m)\"\n        with \\<open>\\<not> P 0\\<close> have \"Suc m < p\"\n          by (auto intro: ccontr) \n        then have \"Suc (p - Suc m) = p - m\"\n          by arith\n        moreover from \\<open>0 < p\\<close> have \"p - Suc m < p\"\n          by arith\n        with P step have \"P ((Suc (p - Suc m)) mod p)\"\n          by blast\n        ultimately show False\n          using \\<open>\\<not> P 0\\<close> Suc.hyps by (cases \"m = 0\") simp_all\n      qed\n    qed\n    ultimately show False\n      by blast\n  qed\nnext\n  case (Suc m)\n  then have \"m < p\" and mod: \"Suc m mod p = Suc m\"\n    by simp_all\n  from \\<open>m < p\\<close> have \"P m\"\n    by (rule Suc.hyps)\n  with \\<open>m < p\\<close> have \"P (Suc m mod p)\"\n    by (rule step)\n  with mod show ?case\n    by simp\nqed\n\nlemma split_div:\n  \"P (m div n) \\<longleftrightarrow> (n = 0 \\<longrightarrow> P 0) \\<and> (n \\<noteq> 0 \\<longrightarrow>\n     (\\<forall>i j. j < n \\<longrightarrow> m = n * i + j \\<longrightarrow> P i))\"\n     (is \"?P = ?Q\") for m n :: nat\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?P\n    with False show ?Q\n      by auto\n  next\n    assume ?Q\n    with False have *: \"\\<And>i j. j < n \\<Longrightarrow> m = n * i + j \\<Longrightarrow> P i\"\n      by simp\n    with False show ?P\n      by (auto intro: * [of \"m mod n\"])\n  qed\nqed\n\nlemma split_div':\n  \"P (m div n) \\<longleftrightarrow> n = 0 \\<and> P 0 \\<or> (\\<exists>q. (n * q \\<le> m \\<and> m < n * Suc q) \\<and> P q)\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  then have \"n * q \\<le> m \\<and> m < n * Suc q \\<longleftrightarrow> m div n = q\" for q\n    by (auto intro: div_nat_eqI dividend_less_times_div)\n  then show ?thesis\n    by auto\nqed\n\nlemma split_mod:\n  \"P (m mod n) \\<longleftrightarrow> (n = 0 \\<longrightarrow> P m) \\<and> (n \\<noteq> 0 \\<longrightarrow>\n     (\\<forall>i j. j < n \\<longrightarrow> m = n * i + j \\<longrightarrow> P j))\"\n     (is \"?P \\<longleftrightarrow> ?Q\") for m n :: nat\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?P\n    with False show ?Q\n      by auto\n  next\n    assume ?Q\n    with False have *: \"\\<And>i j. j < n \\<Longrightarrow> m = n * i + j \\<Longrightarrow> P j\"\n      by simp\n    with False show ?P\n      by (auto intro: * [of _ \"m div n\"])\n  qed\nqed\n\n\nsubsection \\<open>Euclidean division on \\<^typ>\\<open>int\\<close>\\<close>\n\ninstantiation int :: normalization_semidom\nbegin\n\ndefinition normalize_int :: \"int \\<Rightarrow> int\"\n  where [simp]: \"normalize = (abs :: int \\<Rightarrow> int)\"\n\ndefinition unit_factor_int :: \"int \\<Rightarrow> int\"\n  where [simp]: \"unit_factor = (sgn :: int \\<Rightarrow> int)\"\n\ndefinition divide_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  where \"k div l = (if l = 0 then 0\n    else if sgn k = sgn l\n      then int (nat \\<bar>k\\<bar> div nat \\<bar>l\\<bar>)\n      else - int (nat \\<bar>k\\<bar> div nat \\<bar>l\\<bar> + of_bool (\\<not> l dvd k)))\"\n\nlemma divide_int_unfold:\n  \"(sgn k * int m) div (sgn l * int n) =\n   (if sgn l = 0 \\<or> sgn k = 0 \\<or> n = 0 then 0\n    else if sgn k = sgn l\n      then int (m div n)\n      else - int (m div n + of_bool (\\<not> n dvd m)))\"\n  by (auto simp add: divide_int_def sgn_0_0 sgn_1_pos sgn_mult abs_mult\n    nat_mult_distrib)\n\ninstance proof\n  fix k :: int show \"k div 0 = 0\"\n  by (simp add: divide_int_def)\nnext\n  fix k l :: int\n  assume \"l \\<noteq> 0\"\n  obtain n m and s t where k: \"k = sgn s * int n\" and l: \"l = sgn t * int m\" \n    by (blast intro: int_sgnE elim: that)\n  then have \"k * l = sgn (s * t) * int (n * m)\"\n    by (simp add: ac_simps sgn_mult)\n  with k l \\<open>l \\<noteq> 0\\<close> show \"k * l div l = k\"\n    by (simp only: divide_int_unfold)\n      (auto simp add: algebra_simps sgn_mult sgn_1_pos sgn_0_0)\nqed (auto simp add: sgn_mult mult_sgn_abs abs_eq_iff')\n\nend\n\nlemma coprime_int_iff [simp]:\n  \"coprime (int m) (int n) \\<longleftrightarrow> coprime m n\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  show ?Q\n  proof (rule coprimeI)\n    fix q\n    assume \"q dvd m\" \"q dvd n\"\n    then have \"int q dvd int m\" \"int q dvd int n\"\n      by simp_all\n    with \\<open>?P\\<close> have \"is_unit (int q)\"\n      by (rule coprime_common_divisor)\n    then show \"is_unit q\"\n      by simp\n  qed\nnext\n  assume ?Q\n  show ?P\n  proof (rule coprimeI)\n    fix k\n    assume \"k dvd int m\" \"k dvd int n\"\n    then have \"nat \\<bar>k\\<bar> dvd m\" \"nat \\<bar>k\\<bar> dvd n\"\n      by simp_all\n    with \\<open>?Q\\<close> have \"is_unit (nat \\<bar>k\\<bar>)\"\n      by (rule coprime_common_divisor)\n    then show \"is_unit k\"\n      by simp\n  qed\nqed\n\nlemma coprime_abs_left_iff [simp]:\n  \"coprime \\<bar>k\\<bar> l \\<longleftrightarrow> coprime k l\" for k l :: int\n  using coprime_normalize_left_iff [of k l] by simp\n\nlemma coprime_abs_right_iff [simp]:\n  \"coprime k \\<bar>l\\<bar> \\<longleftrightarrow> coprime k l\" for k l :: int\n  using coprime_abs_left_iff [of l k] by (simp add: ac_simps)\n\nlemma coprime_nat_abs_left_iff [simp]:\n  \"coprime (nat \\<bar>k\\<bar>) n \\<longleftrightarrow> coprime k (int n)\"\nproof -\n  define m where \"m = nat \\<bar>k\\<bar>\"\n  then have \"\\<bar>k\\<bar> = int m\"\n    by simp\n  moreover have \"coprime k (int n) \\<longleftrightarrow> coprime \\<bar>k\\<bar> (int n)\"\n    by simp\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma coprime_nat_abs_right_iff [simp]:\n  \"coprime n (nat \\<bar>k\\<bar>) \\<longleftrightarrow> coprime (int n) k\"\n  using coprime_nat_abs_left_iff [of k n] by (simp add: ac_simps)\n\nlemma coprime_common_divisor_int: \"coprime a b \\<Longrightarrow> x dvd a \\<Longrightarrow> x dvd b \\<Longrightarrow> \\<bar>x\\<bar> = 1\"\n  for a b :: int\n  by (drule coprime_common_divisor [of _ _ x]) simp_all\n\ninstantiation int :: idom_modulo\nbegin\n\ndefinition modulo_int :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  where \"k mod l = (if l = 0 then k\n    else if sgn k = sgn l\n      then sgn l * int (nat \\<bar>k\\<bar> mod nat \\<bar>l\\<bar>)\n      else sgn l * (\\<bar>l\\<bar> * of_bool (\\<not> l dvd k) - int (nat \\<bar>k\\<bar> mod nat \\<bar>l\\<bar>)))\"\n\nlemma modulo_int_unfold:\n  \"(sgn k * int m) mod (sgn l * int n) =\n   (if sgn l = 0 \\<or> sgn k = 0 \\<or> n = 0 then sgn k * int m\n    else if sgn k = sgn l\n      then sgn l * int (m mod n)\n      else sgn l * (int (n * of_bool (\\<not> n dvd m)) - int (m mod n)))\"\n  by (auto simp add: modulo_int_def sgn_0_0 sgn_1_pos sgn_mult abs_mult\n    nat_mult_distrib)\n\ninstance proof\n  fix k l :: int\n  obtain n m and s t where \"k = sgn s * int n\" and \"l = sgn t * int m\" \n    by (blast intro: int_sgnE elim: that)\n  then show \"k div l * l + k mod l = k\"\n    by (auto simp add: divide_int_unfold modulo_int_unfold algebra_simps dest!: sgn_not_eq_imp)\n       (simp_all add: of_nat_mult [symmetric] of_nat_add [symmetric]\n         distrib_left [symmetric] minus_mult_right\n         del: of_nat_mult minus_mult_right [symmetric])\nqed\n\nend\n\ninstantiation int :: unique_euclidean_ring\nbegin\n\ndefinition euclidean_size_int :: \"int \\<Rightarrow> nat\"\n  where [simp]: \"euclidean_size_int = (nat \\<circ> abs :: int \\<Rightarrow> nat)\"\n\ndefinition division_segment_int :: \"int \\<Rightarrow> int\"\n  where \"division_segment_int k = (if k \\<ge> 0 then 1 else - 1)\"\n\nlemma division_segment_eq_sgn:\n  \"division_segment k = sgn k\" if \"k \\<noteq> 0\" for k :: int\n  using that by (simp add: division_segment_int_def)\n\nlemma abs_division_segment [simp]:\n  \"\\<bar>division_segment k\\<bar> = 1\" for k :: int\n  by (simp add: division_segment_int_def)\n\nlemma abs_mod_less:\n  \"\\<bar>k mod l\\<bar> < \\<bar>l\\<bar>\" if \"l \\<noteq> 0\" for k l :: int\nproof -\n  obtain n m and s t where \"k = sgn s * int n\" and \"l = sgn t * int m\" \n    by (blast intro: int_sgnE elim: that)\n  with that show ?thesis\n    by (simp add: modulo_int_unfold sgn_0_0 sgn_1_pos sgn_1_neg\n      abs_mult mod_greater_zero_iff_not_dvd)\nqed\n\nlemma sgn_mod:\n  \"sgn (k mod l) = sgn l\" if \"l \\<noteq> 0\" \"\\<not> l dvd k\" for k l :: int\nproof -\n  obtain n m and s t where \"k = sgn s * int n\" and \"l = sgn t * int m\" \n    by (blast intro: int_sgnE elim: that)\n  with that show ?thesis\n    by (simp add: modulo_int_unfold sgn_0_0 sgn_1_pos sgn_1_neg\n      sgn_mult mod_eq_0_iff_dvd)\nqed\n\ninstance proof\n  fix k l :: int\n  show \"division_segment (k mod l) = division_segment l\" if\n    \"l \\<noteq> 0\" and \"\\<not> l dvd k\"\n    using that by (simp add: division_segment_eq_sgn dvd_eq_mod_eq_0 sgn_mod)\nnext\n  fix l q r :: int\n  obtain n m and s t\n     where l: \"l = sgn s * int n\" and q: \"q = sgn t * int m\"\n    by (blast intro: int_sgnE elim: that)\n  assume \\<open>l \\<noteq> 0\\<close>\n  with l have \"s \\<noteq> 0\" and \"n > 0\"\n    by (simp_all add: sgn_0_0)\n  assume \"division_segment r = division_segment l\"\n  moreover have \"r = sgn r * \\<bar>r\\<bar>\"\n    by (simp add: sgn_mult_abs)\n  moreover define u where \"u = nat \\<bar>r\\<bar>\"\n  ultimately have \"r = sgn l * int u\"\n    using division_segment_eq_sgn \\<open>l \\<noteq> 0\\<close> by (cases \"r = 0\") simp_all\n  with l \\<open>n > 0\\<close> have r: \"r = sgn s * int u\"\n    by (simp add: sgn_mult)\n  assume \"euclidean_size r < euclidean_size l\"\n  with l r \\<open>s \\<noteq> 0\\<close> have \"u < n\"\n    by (simp add: abs_mult)\n  show \"(q * l + r) div l = q\"\n  proof (cases \"q = 0 \\<or> r = 0\")\n    case True\n    then show ?thesis\n    proof\n      assume \"q = 0\"\n      then show ?thesis\n        using l r \\<open>u < n\\<close> by (simp add: divide_int_unfold)\n    next\n      assume \"r = 0\"\n      from \\<open>r = 0\\<close> have *: \"q * l + r = sgn (t * s) * int (n * m)\"\n        using q l by (simp add: ac_simps sgn_mult)\n      from \\<open>s \\<noteq> 0\\<close> \\<open>n > 0\\<close> show ?thesis\n        by (simp only: *, simp only: q l divide_int_unfold)\n          (auto simp add: sgn_mult sgn_0_0 sgn_1_pos)\n    qed\n  next\n    case False\n    with q r have \"t \\<noteq> 0\" and \"m > 0\" and \"s \\<noteq> 0\" and \"u > 0\"\n      by (simp_all add: sgn_0_0)\n    moreover from \\<open>0 < m\\<close> \\<open>u < n\\<close> have \"u \\<le> m * n\"\n      using mult_le_less_imp_less [of 1 m u n] by simp\n    ultimately have *: \"q * l + r = sgn (s * t)\n      * int (if t < 0 then m * n - u else m * n + u)\"\n      using l q r\n      by (simp add: sgn_mult algebra_simps of_nat_diff)\n    have \"(m * n - u) div n = m - 1\" if \"u > 0\"\n      using \\<open>0 < m\\<close> \\<open>u < n\\<close> that\n      by (auto intro: div_nat_eqI simp add: algebra_simps)\n    moreover have \"n dvd m * n - u \\<longleftrightarrow> n dvd u\"\n      using \\<open>u \\<le> m * n\\<close> dvd_diffD1 [of n \"m * n\" u]\n      by auto\n    ultimately show ?thesis\n      using \\<open>s \\<noteq> 0\\<close> \\<open>m > 0\\<close> \\<open>u > 0\\<close> \\<open>u < n\\<close> \\<open>u \\<le> m * n\\<close>\n      by (simp only: *, simp only: l q divide_int_unfold)\n        (auto simp add: sgn_mult sgn_0_0 sgn_1_pos algebra_simps dest: dvd_imp_le)\n  qed\nqed (use mult_le_mono2 [of 1] in \\<open>auto simp add: division_segment_int_def not_le zero_less_mult_iff mult_less_0_iff abs_mult sgn_mult abs_mod_less sgn_mod nat_mult_distrib\\<close>)\n\nend\n\nlemma pos_mod_bound [simp]:\n  \"k mod l < l\" if \"l > 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain n where \"l = sgn 1 * int n\"\n    by (cases l) simp_all\n  moreover from this that have \"n > 0\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold)\n      (simp add: mod_greater_zero_iff_not_dvd)\nqed\n\nlemma neg_mod_bound [simp]:\n  \"l < k mod l\" if \"l < 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain q where \"l = sgn (- 1) * int (Suc q)\"\n    by (cases l) simp_all\n  moreover define n where \"n = Suc q\"\n  then have \"Suc q = n\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold)\n      (simp add: mod_greater_zero_iff_not_dvd)\nqed\n\nlemma pos_mod_sign [simp]:\n  \"0 \\<le> k mod l\" if \"l > 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain n where \"l = sgn 1 * int n\"\n    by (cases l) auto\n  moreover from this that have \"n > 0\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold) simp\nqed\n\nlemma neg_mod_sign [simp]:\n  \"k mod l \\<le> 0\" if \"l < 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain q where \"l = sgn (- 1) * int (Suc q)\"\n    by (cases l) simp_all\n  moreover define n where \"n = Suc q\"\n  then have \"Suc q = n\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold) simp\nqed\n\n\nsubsection \\<open>Special case: euclidean rings containing the natural numbers\\<close>\n\nclass unique_euclidean_semiring_with_nat = semidom + semiring_char_0 + unique_euclidean_semiring +\n  assumes of_nat_div: \"of_nat (m div n) = of_nat m div of_nat n\"\n    and division_segment_of_nat [simp]: \"division_segment (of_nat n) = 1\"\n    and division_segment_euclidean_size [simp]: \"division_segment a * of_nat (euclidean_size a) = a\"\nbegin\n\nlemma division_segment_eq_iff:\n  \"a = b\" if \"division_segment a = division_segment b\"\n    and \"euclidean_size a = euclidean_size b\"\n  using that division_segment_euclidean_size [of a] by simp\n\nlemma euclidean_size_of_nat [simp]:\n  \"euclidean_size (of_nat n) = n\"\nproof -\n  have \"division_segment (of_nat n) * of_nat (euclidean_size (of_nat n)) = of_nat n\"\n    by (fact division_segment_euclidean_size)\n  then show ?thesis by simp\nqed\n\nlemma of_nat_euclidean_size:\n  \"of_nat (euclidean_size a) = a div division_segment a\"\nproof -\n  have \"of_nat (euclidean_size a) = division_segment a * of_nat (euclidean_size a) div division_segment a\"\n    by (subst nonzero_mult_div_cancel_left) simp_all\n  also have \"\\<dots> = a div division_segment a\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma division_segment_1 [simp]:\n  \"division_segment 1 = 1\"\n  using division_segment_of_nat [of 1] by simp\n\nlemma division_segment_numeral [simp]:\n  \"division_segment (numeral k) = 1\"\n  using division_segment_of_nat [of \"numeral k\"] by simp\n\nlemma euclidean_size_1 [simp]:\n  \"euclidean_size 1 = 1\"\n  using euclidean_size_of_nat [of 1] by simp\n\nlemma euclidean_size_numeral [simp]:\n  \"euclidean_size (numeral k) = numeral k\"\n  using euclidean_size_of_nat [of \"numeral k\"] by simp\n\nlemma of_nat_dvd_iff:\n  \"of_nat m dvd of_nat n \\<longleftrightarrow> m dvd n\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?Q\n    then show ?P\n      by auto\n  next\n    assume ?P\n    with False have \"of_nat n = of_nat n div of_nat m * of_nat m\"\n      by simp\n    then have \"of_nat n = of_nat (n div m * m)\"\n      by (simp add: of_nat_div)\n    then have \"n = n div m * m\"\n      by (simp only: of_nat_eq_iff)\n    then have \"n = m * (n div m)\"\n      by (simp add: ac_simps)\n    then show ?Q ..\n  qed\nqed\n\nlemma of_nat_mod:\n  \"of_nat (m mod n) = of_nat m mod of_nat n\"\nproof -\n  have \"of_nat m div of_nat n * of_nat n + of_nat m mod of_nat n = of_nat m\"\n    by (simp add: div_mult_mod_eq)\n  also have \"of_nat m = of_nat (m div n * n + m mod n)\"\n    by simp\n  finally show ?thesis\n    by (simp only: of_nat_div of_nat_mult of_nat_add) simp\nqed\n\nlemma one_div_two_eq_zero [simp]:\n  \"1 div 2 = 0\"\nproof -\n  from of_nat_div [symmetric] have \"of_nat 1 div of_nat 2 = of_nat 0\"\n    by (simp only:) simp\n  then show ?thesis\n    by simp\nqed\n\nlemma one_mod_two_eq_one [simp]:\n  \"1 mod 2 = 1\"\nproof -\n  from of_nat_mod [symmetric] have \"of_nat 1 mod of_nat 2 = of_nat 1\"\n    by (simp only:) simp\n  then show ?thesis\n    by simp\nqed\n\nlemma one_mod_2_pow_eq [simp]:\n  \"1 mod (2 ^ n) = of_bool (n > 0)\"\nproof -\n  have \"1 mod (2 ^ n) = of_nat (1 mod (2 ^ n))\"\n    using of_nat_mod [of 1 \"2 ^ n\"] by simp\n  also have \"\\<dots> = of_bool (n > 0)\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma one_div_2_pow_eq [simp]:\n  \"1 div (2 ^ n) = of_bool (n = 0)\"\n  using div_mult_mod_eq [of 1 \"2 ^ n\"] by auto\n\nlemma div_mult2_eq':\n  \"a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\"\nproof (cases a \"of_nat m * of_nat n\" rule: divmod_cases)\n  case (divides q)\n  then show ?thesis\n    using nonzero_mult_div_cancel_right [of \"of_nat m\" \"q * of_nat n\"]\n    by (simp add: ac_simps)\nnext\n  case (remainder q r)\n  then have \"division_segment r = 1\"\n    using division_segment_of_nat [of \"m * n\"] by simp\n  with division_segment_euclidean_size [of r]\n  have \"of_nat (euclidean_size r) = r\"\n    by simp\n  have \"a mod (of_nat m * of_nat n) div (of_nat m * of_nat n) = 0\"\n    by simp\n  with remainder(6) have \"r div (of_nat m * of_nat n) = 0\"\n    by simp\n  with \\<open>of_nat (euclidean_size r) = r\\<close>\n  have \"of_nat (euclidean_size r) div (of_nat m * of_nat n) = 0\"\n    by simp\n  then have \"of_nat (euclidean_size r div (m * n)) = 0\"\n    by (simp add: of_nat_div)\n  then have \"of_nat (euclidean_size r div m div n) = 0\"\n    by (simp add: div_mult2_eq)\n  with \\<open>of_nat (euclidean_size r) = r\\<close> have \"r div of_nat m div of_nat n = 0\"\n    by (simp add: of_nat_div)\n  with remainder(1)\n  have \"q = (r div of_nat m + q * of_nat n * of_nat m div of_nat m) div of_nat n\"\n    by simp\n  with remainder(5) remainder(7) show ?thesis\n    using div_plus_div_distrib_dvd_right [of \"of_nat m\" \"q * (of_nat m * of_nat n)\" r]\n    by (simp add: ac_simps)\nnext\n  case by0\n  then show ?thesis\n    by auto\nqed\n\nlemma mod_mult2_eq':\n  \"a mod (of_nat m * of_nat n) = of_nat m * (a div of_nat m mod of_nat n) + a mod of_nat m\"\nproof -\n  have \"a div (of_nat m * of_nat n) * (of_nat m * of_nat n) + a mod (of_nat m * of_nat n) = a div of_nat m div of_nat n * of_nat n * of_nat m + (a div of_nat m mod of_nat n * of_nat m + a mod of_nat m)\"\n    by (simp add: combine_common_factor div_mult_mod_eq)\n  moreover have \"a div of_nat m div of_nat n * of_nat n * of_nat m = of_nat n * of_nat m * (a div of_nat m div of_nat n)\"\n    by (simp add: ac_simps)\n  ultimately show ?thesis\n    by (simp add: div_mult2_eq' mult_commute)\nqed\n\nlemma div_mult2_numeral_eq:\n  \"a div numeral k div numeral l = a div numeral (k * l)\" (is \"?A = ?B\")\nproof -\n  have \"?A = a div of_nat (numeral k) div of_nat (numeral l)\"\n    by simp\n  also have \"\\<dots> = a div (of_nat (numeral k) * of_nat (numeral l))\"\n    by (fact div_mult2_eq' [symmetric])\n  also have \"\\<dots> = ?B\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma numeral_Bit0_div_2:\n  \"numeral (num.Bit0 n) div 2 = numeral n\"\nproof -\n  have \"numeral (num.Bit0 n) = numeral n + numeral n\"\n    by (simp only: numeral.simps)\n  also have \"\\<dots> = numeral n * 2\"\n    by (simp add: mult_2_right)\n  finally have \"numeral (num.Bit0 n) div 2 = numeral n * 2 div 2\"\n    by simp\n  also have \"\\<dots> = numeral n\"\n    by (rule nonzero_mult_div_cancel_right) simp\n  finally show ?thesis .\nqed\n\nlemma numeral_Bit1_div_2:\n  \"numeral (num.Bit1 n) div 2 = numeral n\"\nproof -\n  have \"numeral (num.Bit1 n) = numeral n + numeral n + 1\"\n    by (simp only: numeral.simps)\n  also have \"\\<dots> = numeral n * 2 + 1\"\n    by (simp add: mult_2_right)\n  finally have \"numeral (num.Bit1 n) div 2 = (numeral n * 2 + 1) div 2\"\n    by simp\n  also have \"\\<dots> = numeral n * 2 div 2 + 1 div 2\"\n    using dvd_triv_right by (rule div_plus_div_distrib_dvd_left)\n  also have \"\\<dots> = numeral n * 2 div 2\"\n    by simp\n  also have \"\\<dots> = numeral n\"\n    by (rule nonzero_mult_div_cancel_right) simp\n  finally show ?thesis .\nqed\n\nlemma exp_mod_exp:\n  \\<open>2 ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\\<close>\nproof -\n  have \\<open>(2::nat) ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\\<close> (is \\<open>?lhs = ?rhs\\<close>)\n    by (auto simp add: not_less monoid_mult_class.power_add dest!: le_Suc_ex)\n  then have \\<open>of_nat ?lhs = of_nat ?rhs\\<close>\n    by simp\n  then show ?thesis\n    by (simp add: of_nat_mod)\nqed\n\nlemma mask_mod_exp:\n  \\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - 1\\<close>\nproof -\n  have \\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - (1::nat)\\<close> (is \\<open>?lhs = ?rhs\\<close>)\n  proof (cases \\<open>n \\<le> m\\<close>)\n    case True\n    then show ?thesis\n      by (simp add: Suc_le_lessD min.absorb2)\n  next\n    case False\n    then have \\<open>m < n\\<close>\n      by simp\n    then obtain q where n: \\<open>n = Suc q + m\\<close>\n      by (auto dest: less_imp_Suc_add)\n    then have \\<open>min m n = m\\<close>\n      by simp\n    moreover have \\<open>(2::nat) ^ m \\<le> 2 * 2 ^ q * 2 ^ m\\<close>\n      using mult_le_mono1 [of 1 \\<open>2 * 2 ^ q\\<close> \\<open>2 ^ m\\<close>] by simp\n    with n have \\<open>2 ^ n - 1 = (2 ^ Suc q - 1) * 2 ^ m + (2 ^ m - (1::nat))\\<close>\n      by (simp add: monoid_mult_class.power_add algebra_simps)\n    ultimately show ?thesis\n      by (simp only: euclidean_semiring_cancel_class.mod_mult_self3) simp\n  qed\n  then have \\<open>of_nat ?lhs = of_nat ?rhs\\<close>\n    by simp\n  then show ?thesis\n    by (simp add: of_nat_mod of_nat_diff)\nqed\n\nlemma of_bool_half_eq_0 [simp]:\n  \\<open>of_bool b div 2 = 0\\<close>\n  by simp\n\nend\n\nclass unique_euclidean_ring_with_nat = ring + unique_euclidean_semiring_with_nat\n\ninstance nat :: unique_euclidean_semiring_with_nat\n  by standard (simp_all add: dvd_eq_mod_eq_0)\n\ninstance int :: unique_euclidean_ring_with_nat\n  by standard (simp_all add: dvd_eq_mod_eq_0 divide_int_def division_segment_int_def)\n\n\nsubsection \\<open>Code generation\\<close>\n\ncode_identifier\n  code_module Euclidean_Division \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Euclidean_Division.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8740772384450967, "lm_q1q2_score": 0.7754853490325857}}
{"text": "theory \"chapter2\"\n  imports Main\nbegin\n\n(* 2.1 *)\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(* 2.2 *)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add 0 n = n\" |\n  \"add (Suc m) n = Suc(add m n)\"\n\ntheorem add_assoc [simp]: \"add (add x y) z = add x (add y z)\"\n  apply (induction x)\n  apply auto\n  done\n\nlemma add_zero2 [simp]: \"add x 0 = x\"\n  apply (induction x)\n  apply auto\n  done\n\nlemma add_suc2 [simp]: \"add x (Suc y) = Suc(add x y)\"\n  apply (induction x)\n  apply auto\n  done\n\ntheorem add_commut [simp]: \"add x y = add y x\"\n  apply (induction x)\n  apply auto\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n  \"double 0 = 0\" |\n  \"double (Suc n) = Suc(Suc(double n))\"\n\ntheorem double_add [simp]: \"double x = add x x\"\n  apply (induction x)\n  apply auto\n  done\n\n(* 2.3 *)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count y [] = 0\" |\n  \"count y (x # xs) = (if x = y then Suc(count y xs) else count y xs)\"\n\n(* Nonlinear patterns not allowed in sequential mode.\n  \"count x (Cons x xs) = Suc(count x xs)\"\n*)\n\ntheorem count_length [simp]: \"count x xs \\<le> length xs\"\n  apply (induction xs)\n  apply auto\n  done\n\n(* 2.4 *)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc [] y = [y]\" |\n  \"snoc (x # xs) y = x # (snoc xs y)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\" |\n  \"reverse (x # xs) = snoc (reverse xs) x\"\n\n(*\nlemma rev_snoc: \"reverse (snoc xs x) = x # xs\"\nAuto Quickcheck found a counterexample:\n  xs = [a\\<^sub>1, a\\<^sub>2]\n  x = a\\<^sub>1\nEvaluated terms:\n  reverse (snoc xs x) = [a\\<^sub>1, a\\<^sub>2, a\\<^sub>1]\n  x # xs = [a\\<^sub>1, a\\<^sub>1, a\\<^sub>2]\n*)\n\n(* don't forget [simp] for later lemma/theorems! *)\nlemma rev_snoc [simp]: \"reverse (snoc xs x) =  x # reverse xs\"\n  apply (induction xs)\n  apply auto\n  done\n\ntheorem rev_rev [simp]: \"reverse (reverse xs) = xs\"\n  apply (induction xs)\n  apply auto\n  done\n\n(* 2.5 *)\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n  \"sum_upto 0 = 0\" |\n  \"sum_upto (Suc n) = (Suc n) + sum_upto n\"\n\ntheorem sum_formula [simp]: \"sum_upto x = x * (x + 1) div 2\"\n  apply (induction x)\n  apply auto\n  done\n\n(* 2.6 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\n(* list @ list or elem # list *)\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"contents Tip = []\" |\n  \"contents (Node l a r) =  a # (contents l) @ (contents r)\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n  \"sum_tree Tip = 0\" |\n  \"sum_tree (Node l a r) = (sum_tree l) + a + (sum_tree r)\"\n\ntheorem sum_tree_list [simp]: \"sum_tree t = sum_list (contents t)\"\n  apply (induction t)\n  apply auto\n  done\n\n(* 2.7 *)\nfun preorder :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"preorder Tip = []\" |\n  \"preorder (Node l a r) = a # (preorder l) @ (preorder r)\"\n\nfun postorder :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"postorder Tip = []\" |\n  \"postorder (Node l a r) = (postorder l) @ (postorder r) @ [a]\"\n\n(* \ntheorem fails to prove but doesn't complain with\npreorder (Node l a r) = (preorder l) @ (preorder r)\npostorder (Node l a r) = (postorder r) @ (postorder l)\n\nI'm forgetting to include the \"a\" part of a node, but interesting\nthat I don't get a counter-example (because an empty list is\nequal to an empty list).\n\nafter induction on t and apply auto, left with this goal.\ngoal (1 subgoal):\n 1. \\<And>t1 t2.\n       preorder (mirror t1) = rev (postorder t1) \\<Longrightarrow>\n       preorder (mirror t2) = rev (postorder t2) \\<Longrightarrow>\n       rev (postorder t2) @ rev (postorder t1) =\n       rev (postorder t1) @ rev (postorder t2\n*)\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n  \"mirror Tip = Tip\" |\n  \"mirror (Node l a r ) = Node (mirror r ) a (mirror l)\"\n\ntheorem mirror_ordering [simp]: \"preorder (mirror t) = rev (postorder t)\"\n  apply (induction t)\n  apply auto\n  done\n\n(* 2.8 *)\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intersperse a [] = []\" |\n  \"intersperse a (x # xs) = (x # [a]) @ (intersperse a xs)\"\n\n(* \nApplying a function to an interspersed list is the same as applying the function\nto the elements, then interspersing.\n*)\ntheorem intersperse_over_map [simp]: \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply (induction xs)\n  apply auto\n  done\n\n(* 2.9 *)\n\n(* How do I identify that a function is tail-recursive? \nThe only difference between this and add is where the Suc goes. \n\nAh, the example says \"in the recursive case, itadd needs to call\nitself directly\". So no shenanigans on the outermost expression. *)\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"itadd 0 n = n\" |\n  \"itadd (Suc m) n = itadd m (Suc n)\"\n\ntheorem itadd_is_add [simp]: \"itadd m n = add m n\"\n(* Fancy argument sorcery? Why include a colon? *)\n  apply (induction m arbitrary: n)\n  apply auto\n  done\n\n(* So now I'm told not to litter [simp] everywhere, only for\nactual simplifying equations, at risk of exponential blow up! *)\n\n(* 2.10 *)\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Tip = 1\" |\n  \"nodes (Node l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n  \"explode 0 t = t\" |\n  \"explode (Suc n) t = explode n (Node t t)\"\n\n(* create 2^n copies of t and then 2^n-1 nodes to connect all the\n   copies *)\ntheorem explode_size: \"nodes (explode n t) = 2 ^ n * nodes t + 2 ^ n - 1\"\n  apply (induction n arbitrary: t)\n  (* boost auto with the algebra_simps deduction *)\n  apply (auto simp add: algebra_simps)\n  done\n\n(* 2.11 *)\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"eval Var n = n\" |\n  \"eval (Const x) n = x\" |\n  \"eval (Add x y) n = (eval x n) + (eval y n)\" |\n  \"eval (Mult x y) n = (eval x n) * (eval y n)\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"evalp [] n = 0\" |\n  \"evalp (x # xs) n = x + n * (evalp xs n)\"\n\n(* sum corresponding indices of lists *)\nfun elem_sum :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"elem_sum [] y = y\" |\n  \"elem_sum x [] = x\" |\n  \"elem_sum (x # xs) (y # ys) = (x + y) # elem_sum xs ys\"\n\n(* multiply each index by n *)\nfun scalar_mult :: \"int  \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"scalar_mult k [] = []\" |\n  \"scalar_mult k (x # xs) = (k * x) # scalar_mult k xs\"\n\n(* shift and multiply *)\nfun poly_mult :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"poly_mult [] ys = []\" |\n  \"poly_mult (x # xs) ys = elem_sum (scalar_mult x ys) (poly_mult xs (0 # ys))\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n  \"coeffs Var = [0, 1]\" |\n  \"coeffs (Const x) = [x]\" |\n  \"coeffs (Add x y) = elem_sum (coeffs x) (coeffs y)\" |\n  \"coeffs (Mult x y) = poly_mult (coeffs x) (coeffs y)\"\n\nlemma evalp_elem_sum [simp]: \"evalp (elem_sum xs ys) n = evalp xs n + evalp ys n\"\n  apply (induction rule: elem_sum.induct)\n  apply (auto simp add: algebra_simps)\n  done\n\nlemma evalp_scalar_mult [simp]: \"evalp (scalar_mult k xs) n = k * evalp xs n\"\n  (* Doesn't work with\n  apply (induction rule: scalar_mult.induct) *)\n  apply (induction xs arbitrary:k)\n  apply (auto simp add: algebra_simps)\n  done\n\nlemma evalp_poly_mult [simp]: \"evalp (poly_mult xs ys) n = evalp xs n * evalp ys n\"\n  apply (induction rule: poly_mult.induct)\n  apply (auto simp add: algebra_simps)\n  done\n\ntheorem coeffs_preserves_eval: \"evalp (coeffs e) x = eval e x\"\n  apply (induction e)\n  apply auto\n  done\n\n(*\nFunction writing through counter-examples:\n\nProblem 1:\nAuto Quickcheck found a counterexample:\n  e = Var\n  x = - 1\nEvaluated terms:\n  evalp (coeffs e) x = 1\n  eval e x = - 1\nMy investigation:\n  culprit: \"evalp (x # xs) n = n * x + n * (evalp xs n)\"\n  example: \n    \"evalp [0, 1]\" expands to \n    \"(n * 0 + n * (n * 1 + n * (0)))\"; simplifies to\n    \"n^2\"\n  reason: I have too many n's in my definition.\n  fix: \"evalp (x # xs) n = x + n * (evalp xs n)\"\n\nProblem 2:\nAuto Quickcheck found a counterexample:\n  e = Add Var Var\n  x = - 2\nEvaluated terms:\n  evalp (coeffs e) x = 0\n  eval e x = - 4\nMy investigation:\n  cool, the counterexample is using add; I must have the Var and\n  Const cases right. Back in math class, adding polynomials is\n  the same as adding matching coefficients, so write elem_sum.\n\nProblem 3:\nAuto Quickcheck found a counterexample:\n  e = Mult Var Var\n  x = - 2\nEvaluated terms:\n  evalp (coeffs e) x = 0\n  eval e x = 4\nMy investigation:\n  cool, the counterexample is using mult; I must have Add right.\n  Back in math class, multiplying polynomials requires some\n  FOIL-ing. Right shift N and multiply by index N. Write\n  scalar_mult and poly_mult.\n\nNo more problems, time to prove. Apply auto doesn't work. Onto\nthe lemmas:\n\nLemma 1: \"evalp (elem_sum xs ys) n = evalp xs n + evalp ys n\"\n\nLemma 2: \"evalp (poly_mult xs ys) n = evalp xs n * evalp ys n\n  requires a scalar_mult lemma\n\nLemma 1.5: \"evalp (scalar_mult k xs) n = k * evalp xs n\"\n  for some reason, this doesn't solve when using rule:scalar_mult.induct\n\nAfter the lemmas are in place, the theorem is proved with \n*)\n\nend", "meta": {"author": "nnooney", "repo": "isabelle-theories", "sha": "194126c8eaca0c87e9e714bf7be7e0b1b9a448be", "save_path": "github-repos/isabelle/nnooney-isabelle-theories", "path": "github-repos/isabelle/nnooney-isabelle-theories/isabelle-theories-194126c8eaca0c87e9e714bf7be7e0b1b9a448be/concrete-semantics/chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240721511739, "lm_q2_score": 0.8962513772903669, "lm_q1q2_score": 0.7754582663302694}}
{"text": "chapter {* R10: Formalización y argumentación con Isabelle/HOL *}\n\ntheory R10_Formalizacion_y_argmentacion\nimports Main \nbegin\n\ntext {*\n  --------------------------------------------------------------------- \n  El objetivo de esta es relación formalizar y demostrar la corrección\n  de los argumentos automáticamente y detalladamente usando sólo las reglas\n  básicas de deducción natural. \n\n  · conjI:      \\<lbrakk>P; Q\\<rbrakk> \\<Longrightarrow> P \\<and> Q\n  · conjunct1:  P \\<and> Q \\<Longrightarrow> P\n  · conjunct2:  P \\<and> Q \\<Longrightarrow> Q  \n  · notnotD:    \\<not>\\<not> P \\<Longrightarrow> P\n  · mp:         \\<lbrakk>P \\<longrightarrow> Q; P\\<rbrakk> \\<Longrightarrow> Q \n  · impI:       (P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<longrightarrow> Q\n  · disjI1:     P \\<Longrightarrow> P \\<or> Q\n  · disjI2:     Q \\<Longrightarrow> P \\<or> Q\n  · disjE:      \\<lbrakk>P \\<or> Q; P \\<Longrightarrow> R; Q \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R \n  · FalseE:     False \\<Longrightarrow> P\n  · notE:       \\<lbrakk>\\<not>P; P\\<rbrakk> \\<Longrightarrow> R\n  · notI:       (P \\<Longrightarrow> False) \\<Longrightarrow> \\<not>P\n  · iffI:       \\<lbrakk>P \\<Longrightarrow> Q; Q \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P = Q\n  · iffD1:      \\<lbrakk>Q = P; Q\\<rbrakk> \\<Longrightarrow> P \n  · iffD2:      \\<lbrakk>P = Q; Q\\<rbrakk> \\<Longrightarrow> P\n  · ccontr:     (\\<not>P \\<Longrightarrow> False) \\<Longrightarrow> P\n\n  · allI:       \\<lbrakk>\\<forall>x. P x; P x \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\n  · allE:       (\\<And>x. P x) \\<Longrightarrow> \\<forall>x. P x\n  · exI:        P x \\<Longrightarrow> \\<exists>x. P x\n  · exE:        \\<lbrakk>\\<exists>x. P x; \\<And>x. P x \\<Longrightarrow> Q\\<rbrakk> \\<Longrightarrow> Q\n\n  · refl:       t = t\n  · subst:      \\<lbrakk>s = t; P s\\<rbrakk> \\<Longrightarrow> P t\n  · trans:      \\<lbrakk>r = s; s = t\\<rbrakk> \\<Longrightarrow> r = t\n  · sym:        s = t \\<Longrightarrow> t = s\n  · not_sym:    t \\<noteq> s \\<Longrightarrow> s \\<noteq> t\n  · ssubst:     \\<lbrakk>t = s; P s\\<rbrakk> \\<Longrightarrow> P t\n  · box_equals: \\<lbrakk>a = b; a = c; b = d\\<rbrakk> \\<Longrightarrow> a: = d\n  · arg_cong:   x = y \\<Longrightarrow> f x = f y\n  · fun_cong:   f = g \\<Longrightarrow> f x = g x\n  · cong:       \\<lbrakk>f = g; x = y\\<rbrakk> \\<Longrightarrow> f x = g y\n  --------------------------------------------------------------------- \n*}\n\ntext {*\n  Se usarán las reglas notnotI, mt, no_ex y no_para_todo que demostramos\n  a continuación. \n  *}\n\nlemma notnotI: \"P \\<Longrightarrow> \\<not>\\<not> P\"\nby auto\n\nlemma mt: \"\\<lbrakk>F \\<longrightarrow> G; \\<not>G\\<rbrakk> \\<Longrightarrow> \\<not>F\"\nby auto\n\nlemma no_ex: \"\\<not>(\\<exists>x. P(x)) \\<Longrightarrow> \\<forall>x. \\<not>P(x)\"\nby auto\n\nlemma no_para_todo: \"\\<not>(\\<forall>x. P(x)) \\<Longrightarrow> \\<exists>x. \\<not>P(x)\"\nby auto\n\ntext {* --------------------------------------------------------------- \n  Ejercicio 1. Formalizar, y demostrar la corrección, del siguiente\n  argumento \n     Si la válvula está abierta o la monitorización está preparada,\n     entonces se envía una señal de reconocimiento y un mensaje de\n     funcionamiento al controlador del ordenador. Si se envía un mensaje \n     de funcionamiento al controlador del ordenador o el sistema está en \n     estado normal, entonces se aceptan las órdenes del operador. Por lo\n     tanto, si la válvula está abierta, entonces se aceptan las órdenes\n     del operador. \n  Usar A : La válvula está abierta.\n       P : La monitorización está preparada.\n       R : Envía una señal de reconocimiento.\n       F : Envía un mensaje de funcionamiento.\n       N : El sistema está en estado normal.\n       O : Se aceptan órdenes del operador.\n  ------------------------------------------------------------------ *}\n\nlemma ejer_1:\n  assumes 1: \"A \\<or> P \\<longrightarrow> R \\<and> F\" \n  assumes 2: \"F \\<or> N \\<longrightarrow> OK\"\n  shows \"A \\<longrightarrow> OK\"\nproof -\n  {assume 3: \"A\"\n   have 4: \"A \\<or> P\" using 3 by (rule disjI1)\n   have 5: \"R \\<and> F\" using 1 4 by (rule mp)\n   have 6: \"F\" using 5 by (rule conjunct2)\n   have 7: \"F \\<or> N\" using 6 by (rule disjI1)\n   have 8: \"OK\" using 2 7 by (rule mp)}\n  then show \"A \\<longrightarrow> OK\" by (rule impI)\nqed  \n\ntext {* --------------------------------------------------------------- \n  Ejercicio 2. Formalizar, y decidir la corrección, del siguiente\n  argumento \n     Hay estudiantes inteligentes y hay estudiantes trabajadores. Por\n     tanto, hay estudiantes inteligentes y trabajadores.\n  Usar I(x) para x es inteligente\n       T(x) para x es trabajador\n  ------------------------------------------------------------------ *}\n\nlemma ejer_2:\n  assumes \"(\\<exists>x. I(x)) \\<and> (\\<exists>x. T(x))\"\n  shows   \"\\<exists>x. (I(x) \\<and> T(x))\"\n  quickcheck\noops\n\ntext {* --------------------------------------------------------------- \n  Ejercicio 3. Formalizar, y decidir la corrección, del siguiente\n  argumento \n     Los hermanos tienen el mismo padre. Juan es hermano de Luis. Carlos\n     es padre de Luis. Por tanto, Carlos es padre de Juan.\n  Usar H(x,y) para x es hermano de y\n       P(x,y) para x es padre de y\n       j      para Juan\n       l      para Luis\n       c      para Carlos\n  ------------------------------------------------------------------ *}\n\nlemma ejer_3:\n  assumes 1: \"\\<forall>x y. P(x,y) \\<longrightarrow> (\\<forall>z. (H(z,y) \\<longrightarrow> P(x,z)))\" \n  assumes 2: \"H(j,l)\"\n  assumes 3: \"P(c,l)\"\n  shows \"P(c,j)\"\nproof -\n  have 4 : \"\\<forall>y. P(c,y) \\<longrightarrow> (\\<forall>z. (H(z,y) \\<longrightarrow> P(c,z)))\" using 1 by (rule allE)\n  have 5 : \"P(c,l) \\<longrightarrow> (\\<forall>z. (H(z,l) \\<longrightarrow> P(c,z)))\" using 4 by (rule allE)\n  then have 6 : \"(\\<forall>z. (H(z,l) \\<longrightarrow> P(c,z)))\" using 3 by (rule mp)\n  have 7 : \"H(j,l) \\<longrightarrow> P(c,j)\" using 6 by (rule allE)\n  then show \"P(c,j)\" using 2 by (rule mp)\nqed \n\ntext {* --------------------------------------------------------------- \n  Ejercicio 4. Formalizar, y decidir la corrección, del siguiente\n  argumento \n     Los aficionados al fútbol aplauden a cualquier futbolista\n     extranjero. Juanito no aplaude a futbolistas extranjeros. Por\n     tanto, si hay algún futbolista extranjero nacionalizado español,\n     Juanito no es aficionado al fútbol.\n  Usar Af(x)   para x es aficicionado al fútbol\n       Ap(x,y) para x aplaude a y\n       E(x)    para x es un futbolista extranjero\n       N(x)    para x es un futbolista nacionalizado español\n       j       para Juanito\n  ------------------------------------------------------------------ *}\n\nlemma ejer_4:\n  assumes 1: \"\\<forall>x y. Af(x) \\<and> E(y) \\<longrightarrow> Ap(x,y)\"\n  assumes 2: \"\\<not>(\\<exists>x. E(x) \\<and> Ap(j,x))\"\n  shows \"(\\<exists>x. E(x) \\<and> N(x)) \\<longrightarrow> \\<not>Af(j)\"  \n  proof (rule impI)\n  assume 3: \"\\<exists>x. E(x) \\<and> N(x)\"\n    then obtain a where 4: \"E(a) \\<and> N(a)\" by (rule exE)\n    then have 5: \"E(a)\" by (rule conjunct1)\n    show 6: \"\\<not>Af(j)\"\n    proof (rule notI)\n      assume 7: \"Af(j)\"\n      then have 8: \"Af(j) \\<and> E(a)\" using 5 by (rule conjI)\n      have 9: \"\\<forall>y. Af(j) \\<and> E(y) \\<longrightarrow> Ap(j,y)\" using 1 by (rule allE)\n      have 10: \"Af(j) \\<and> E(a) \\<longrightarrow> Ap(j,a)\" using 9 by (rule allE)\n      have 11: \"Ap(j,a)\" using 10 8 by (rule mp)\n      have 12: \"E(a) \\<and> Ap(j,a)\" using 5 11 by (rule conjI)\n      have 13: \"\\<exists>x. E(x) \\<and> Ap(j,x)\" using 12 by (rule exI)\n      show \"False\" using 2 13 by (rule notE)\n    qed\nqed  \n\ntext {* --------------------------------------------------------------- \n  Ejercicio 5. Formalizar, y decidir la corrección, del siguiente\n  argumento \n     El esposo de la hermana de Toni es Roberto. La hermana de Toni es\n     María. Por tanto, el esposo de María es Roberto. \n  Usar e(x) para el esposo de x\n       h    para la hermana de Toni\n       m    para María\n       r    para Roberto\n  ------------------------------------------------------------------ *}\n\nlemma ejer_5:\n  assumes 1: \"e(h) = r\"\n  assumes 2: \"h = m\"\n  shows   \"e(m) = r\"\n  proof -\n    show \"e(m) = r\" using 2 1 by (rule subst)\nqed\n\nend", "meta": {"author": "serrodcal-MULCIA", "repo": "RAIsabelleHOL", "sha": "2f551971b248b3dac6009d09b74f5b3e16e0d12f", "save_path": "github-repos/isabelle/serrodcal-MULCIA-RAIsabelleHOL", "path": "github-repos/isabelle/serrodcal-MULCIA-RAIsabelleHOL/RAIsabelleHOL-2f551971b248b3dac6009d09b74f5b3e16e0d12f/R10_Formalizacion_y_argmentacion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.8652240756264638, "lm_q1q2_score": 0.7754582586554506}}
{"text": "header{*Addition, Sequences and their Concatenation*}\n\ntheory OrdArith imports Rank\nbegin\n\nsection {*Generalised Addition --- Also for Ordinals *}\ntext{*Source: Laurence Kirby, Addition and multiplication of sets\n      Math. Log. Quart. 53, No. 1, 52-65 (2007) / DOI 10.1002/malq.200610026\n      @{url \"http://faculty.baruch.cuny.edu/lkirby/mlqarticlejan2007.pdf\"}*}\n\ndefinition\n  hadd      :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"           (infixl \"@+\" 65)  where\n    \"hadd x \\<equiv> hmemrec (\\<lambda>f z. x \\<squnion> RepFun z f)\"\n\nlemma hadd: \"x @+ y = x \\<squnion> RepFun y (\\<lambda>z. x @+ z)\"\n  by (metis def_hmemrec RepFun_ecut hadd_def order_refl)\n\nlemma hmem_hadd_E:\n  assumes l: \"l \\<^bold>\\<in> x @+ y\"\n  obtains \"l \\<^bold>\\<in> x\" | z where \"z \\<^bold>\\<in> y\" \"l = x @+ z\"\n  using l\n  by (auto simp: hadd [of x y])\n\nlemma hadd_0_right [simp]: \"x @+ 0 = x\"\n  by (subst hadd) simp\n\nlemma hadd_hinsert_right: \"x @+ hinsert y z = hinsert (x @+ y) (x @+ z)\"\n  by (metis hadd hunion_hinsert_right RepFun_hinsert)\n\nlemma hadd_succ_right [simp]: \"x @+ succ y = succ (x @+ y)\"\n  by (metis hadd_hinsert_right succ_def)\n\nlemma not_add_less_right: \"~ (x @+ y < x)\"\n  apply (induct y, auto)\n  apply (metis less_supI1 hadd order_less_le)\n  done\n\nlemma not_add_mem_right: \"~ (x @+ y \\<^bold>\\<in> x)\"\n  by (metis hadd hmem_not_refl hunion_iff)\n\nlemma hadd_0_left [simp]: \"0 @+ x = x\"\n  by (induct x) (auto simp: hadd_hinsert_right)\n\nlemma hadd_succ_left [simp]: \"Ord y \\<Longrightarrow> succ x @+ y = succ (x @+ y)\"\n  by (induct y rule: Ord_induct2) auto\n\nlemma hadd_assoc: \"(x @+ y) @+ z = x @+ (y @+ z)\"\n  by (induct z) (auto simp: hadd_hinsert_right)\n\nlemma RepFun_hadd_disjoint: \"x \\<sqinter> RepFun y (op @+ x) = 0\"\n  by (metis hf_equalityI RepFun_iff hinter_iff not_add_mem_right hmem_hempty)\n\nsubsection {*Cancellation laws for addition*}\n\nlemma Rep_le_Cancel: \"x \\<squnion> RepFun y (op @+ x) \\<le> x \\<squnion> RepFun z (op @+ x)\n                      \\<Longrightarrow> RepFun y (op @+ x) \\<le> RepFun z (op @+ x)\"\n  by (auto simp add: not_add_mem_right)\n\nlemma hadd_cancel_right [simp]: \"x @+ y = x @+ z \\<longleftrightarrow> y=z\"\nproof (induct y arbitrary: z rule: hmem_induct)\n  case (step y z) show ?case\n  proof auto\n    assume eq: \"x @+ y = x @+ z\"\n    hence  \"RepFun y (op @+ x) = RepFun z (op @+ x)\"\n      by (metis hadd Rep_le_Cancel order_antisym order_refl)\n    thus  \"y = z\"\n      by (metis hf_equalityI RepFun_iff step)\n  qed\nqed\n\nlemma RepFun_hadd_cancel: \"RepFun y (\\<lambda>z. x @+ z) = RepFun z (\\<lambda>z. x @+ z) \\<longleftrightarrow> y=z\"\n  by (metis hadd hadd_cancel_right)\n\nlemma hadd_hmem_cancel [simp]: \"x @+ y \\<^bold>\\<in> x @+ z \\<longleftrightarrow> y \\<^bold>\\<in> z\"\n  apply (auto simp: hadd [of _ y] hadd [of _ z] not_add_mem_right)\n  apply (metis hmem_not_refl hunion_iff)\n  apply (metis hadd hadd_cancel_right)\n  done\n\nlemma ord_of_add: \"ord_of (i+j) = ord_of i @+ ord_of j\"\n  by (induct j) auto\n\nlemma Ord_hadd: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> Ord (x @+ y)\"\n  by (induct x rule: Ord_induct2) auto\n\nlemma hmem_self_hadd [simp]: \"k1 \\<^bold>\\<in> k1 @+ k2 \\<longleftrightarrow> 0 \\<^bold>\\<in> k2\"\n  by (metis hadd_0_right hadd_hmem_cancel)\n\nlemma hadd_commute: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> x @+ y = y @+ x\"\n  by (induct x rule: Ord_induct2) auto\n\nlemma hadd_cancel_left [simp]: \"Ord x \\<Longrightarrow> y @+ x = z @+ x \\<longleftrightarrow> y=z\"\n  by (induct x rule: Ord_induct2) auto\n\nsubsection {*The predecessor function*}\n\ndefinition pred :: \"hf \\<Rightarrow> hf\"\n  where \"pred x \\<equiv> (THE y. succ y = x \\<or> x=0 \\<and> y=0)\"\n\nlemma pred_succ [simp]: \"pred (succ x) = x\"\n  by (simp add: pred_def)\n\nlemma pred_0 [simp]: \"pred 0 = 0\"\n  by (simp add: pred_def)\n\nlemma succ_pred [simp]: \"Ord x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> succ (pred x) = x\"\n  by (metis Ord_cases pred_succ)\n\nlemma pred_mem [simp]: \"Ord x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> pred x \\<^bold>\\<in> x\"\n  by (metis succ_iff succ_pred)\n\nlemma Ord_pred [simp]: \"Ord x \\<Longrightarrow> Ord (pred x)\"\n  by (metis Ord_in_Ord pred_0 pred_mem)\n\nlemma hadd_pred_right: \"Ord y \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> x @+ pred y = pred (x @+ y)\"\n  by (metis hadd_succ_right pred_succ succ_pred)\n\nlemma Ord_pred_HUnion: \"Ord(k) \\<Longrightarrow> pred k = \\<Squnion>k\"\n  by (metis HUnion_hempty Ordinal.Ord_pred pred_0 pred_succ)\n\n\nsection {*A Concatentation Operation for Sequences*}\n\ndefinition shift :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"shift f delta = \\<lbrace>v . u \\<^bold>\\<in> f, \\<exists>n y. u = \\<langle>n, y\\<rangle> \\<and> v = \\<langle>delta @+ n, y\\<rangle>\\<rbrace>\"\n\nlemma shiftD: \"x \\<^bold>\\<in> shift f delta \\<Longrightarrow> \\<exists>u. u \\<^bold>\\<in> f \\<and> x = \\<langle>delta @+ hfst u, hsnd u\\<rangle>\"\n  by (auto simp: shift_def hsplit_def)\n\nlemma hmem_shift_iff: \"\\<langle>m, y\\<rangle> \\<^bold>\\<in> shift f delta \\<longleftrightarrow> (\\<exists>n. m = delta @+ n \\<and> \\<langle>n, y\\<rangle> \\<^bold>\\<in> f)\"\n  by (auto simp: shift_def hrelation_def is_hpair_def)\n\nlemma hmem_shift_add_iff [simp]: \"\\<langle>delta @+ n, y\\<rangle> \\<^bold>\\<in> shift f delta \\<longleftrightarrow> \\<langle>n, y\\<rangle> \\<^bold>\\<in> f\"\n  by (metis hadd_cancel_right hmem_shift_iff)\n\nlemma hrelation_shift [simp]: \"hrelation (shift f delta)\"\n  by (auto simp: shift_def hrelation_def hsplit_def)\n\nlemma app_shift [simp]: \"app (shift f k) (k @+ j) = app f j\"\n  by (simp add: app_def)\n\nlemma hfunction_shift_iff [simp]: \"hfunction (shift f delta) = hfunction f\"\n  by (auto simp: hfunction_def hmem_shift_iff)\n\nlemma hdomain_shift_add: \"hdomain (shift f delta) = \\<lbrace>delta @+ n . n \\<^bold>\\<in> hdomain f\\<rbrace>\"\n  by  (rule hf_equalityI) (force simp add: hdomain_def hmem_shift_iff)\n\n\n\ndefinition seq_append :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"seq_append k f g \\<equiv> hrestrict f k \\<squnion> shift g k\"\n\nlemma hrelation_seq_append [simp]: \"hrelation (seq_append k f g)\"\n  by (simp add: seq_append_def)\n\nlemma Seq_append: \"Seq s1 k1 \\<Longrightarrow> Seq s2 k2 \\<Longrightarrow> Seq (seq_append k1 s1 s2) (k1 @+ k2)\"\n  apply (auto simp: Seq_def seq_append_def)\n  apply (metis hdomain_restr hdomain_shift_disjoint hfunction_hunion hfunction_restr hfunction_shift_iff inf_absorb2 seq_append_def)\n  apply (simp add: hdomain_shift_add)\n  apply (metis hmem_hadd_E rev_hsubsetD)\n  apply (erule hmem_hadd_E, assumption, auto)\n  apply (metis Seq_def Seq_iff_app hdomainI hmem_shift_add_iff)\n  done\n\nlemma app_hunion1: \"~ x \\<^bold>\\<in> hdomain g \\<Longrightarrow> app (f \\<squnion> g) x = app f x\"\n  by (auto simp: app_def) (metis hdomainI)\n\nlemma app_hunion2: \"~ x \\<^bold>\\<in> hdomain f \\<Longrightarrow> app (f \\<squnion> g) x = app g x\"\n  by (auto simp: app_def) (metis hdomainI)\n\nlemma Seq_append_app1: \"Seq s k \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> app (seq_append k s s') l = app s l\"\n  apply (auto simp: Seq_def seq_append_def)\n  apply (metis app_hunion1 hdomain_shift_disjoint hemptyE hinter_iff app_hrestrict)\n  done\n\nlemma Seq_append_app2: \"Seq s1 k1 \\<Longrightarrow> Seq s2 k2 \\<Longrightarrow> l = k1 @+ j \\<Longrightarrow> app (seq_append k1 s1 s2) l = app s2 j\"\n  by (metis seq_append_def app_hunion2 app_shift hdomain_restr hinter_iff not_add_mem_right)\n\nsection {*Nonempty sequences indexed by ordinals*}\n\ndefinition OrdDom where\n \"OrdDom r \\<equiv> \\<forall>x y. \\<langle>x,y\\<rangle> \\<^bold>\\<in> r \\<longrightarrow> Ord x\"\n\nlemma OrdDom_insf: \"\\<lbrakk>OrdDom s; Ord k\\<rbrakk> \\<Longrightarrow> OrdDom (insf s (succ k) y)\"\n  by (auto simp: insf_def OrdDom_def)\n\nlemma OrdDom_hunion [simp]: \"OrdDom (s1 \\<squnion> s2) \\<longleftrightarrow> OrdDom s1 & OrdDom s2\"\n  by (auto simp: OrdDom_def)\n\nlemma OrdDom_hrestrict: \"OrdDom s \\<Longrightarrow> OrdDom (hrestrict s A)\"\n  by (auto simp: OrdDom_def)\n\nlemma OrdDom_shift: \"\\<lbrakk>OrdDom s; Ord k\\<rbrakk> \\<Longrightarrow> OrdDom (shift s k)\"\n  by (auto simp: OrdDom_def shift_def Ord_hadd)\n\n\ntext{*A sequence of positive length ending with @{term y} *}\ndefinition LstSeq :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"LstSeq s k y \\<equiv> Seq s (succ k) & Ord k & \\<langle>k,y\\<rangle> \\<^bold>\\<in> s & OrdDom s\"\n\n\n\nlemma LstSeq_imp_Seq_same: \"LstSeq s k y \\<Longrightarrow> Seq s k\"\n  by (metis LstSeq_imp_Seq_succ Seq_succ_D)\n\nlemma LstSeq_imp_Ord: \"LstSeq s k y \\<Longrightarrow> Ord k\"\n  by (metis LstSeq_def)\n\nlemma LstSeq_trunc: \"LstSeq s k y \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> LstSeq s l (app s l)\"\n  apply (auto simp: LstSeq_def Seq_iff_app)\n  apply (metis Ord_succ Seq_Ord_D mem_succ_iff)\n  apply (metis Ord_in_Ord)\n  done\n\nlemma LstSeq_insf: \"LstSeq s k z \\<Longrightarrow> LstSeq (insf s (succ k) y) (succ k) y\"\n  by (metis OrdDom_insf LstSeq_def Ord_succ_iff Seq_imp_eq_app Seq_insf Seq_succ_iff app_insf_Seq)\n\nlemma app_insf_LstSeq: \"LstSeq s k z \\<Longrightarrow> app (insf s (succ k) y) (succ k) = y\"\n  by (metis LstSeq_imp_Seq_succ app_insf_Seq)\n\nlemma app_insf2_LstSeq: \"LstSeq s k z \\<Longrightarrow> k' \\<noteq> succ k \\<Longrightarrow> app (insf s (succ k) y) k' = app s k'\"\n  by (metis LstSeq_imp_Seq_succ app_insf2_Seq)\n\nlemma app_insf_LstSeq_if: \"LstSeq s k z \\<Longrightarrow> app (insf s (succ k) y) k' = (if k' = succ k then y else app s k')\"\n  by (metis app_insf2_LstSeq app_insf_LstSeq)\n\nlemma LstSeq_append_app1:\n  \"LstSeq s k y \\<Longrightarrow> l \\<^bold>\\<in> succ k \\<Longrightarrow> app (seq_append (succ k) s s') l = app s l\"\n  by (metis LstSeq_imp_Seq_succ Seq_append_app1)\n\nlemma LstSeq_append_app2:\n  \"\\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2; l = succ k1 @+ j\\<rbrakk>\n   \\<Longrightarrow> app (seq_append (succ k1) s1 s2) l = app s2 j\"\n   by (metis LstSeq_imp_Seq_succ Seq_append_app2)\n\nlemma Seq_append_pair:\n  \"\\<lbrakk>Seq s1 k1; Seq s2 (succ n);  \\<langle>n, y\\<rangle> \\<^bold>\\<in> s2; Ord n\\<rbrakk> \\<Longrightarrow> \\<langle>k1 @+ n, y\\<rangle> \\<^bold>\\<in> (seq_append k1 s1 s2)\"\n  by (metis hmem_shift_add_iff hunion_iff seq_append_def)\n\nlemma Seq_append_OrdDom: \"\\<lbrakk>Ord k; OrdDom s1; OrdDom s2\\<rbrakk> \\<Longrightarrow> OrdDom (seq_append k s1 s2)\"\n  by (auto simp: seq_append_def OrdDom_hrestrict OrdDom_shift)\n\nlemma LstSeq_append:\n  \"\\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2\\<rbrakk> \\<Longrightarrow> LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n  apply (auto simp: LstSeq_def Seq_append Ord_hadd Seq_append_pair)\n  apply (metis Seq_append hadd_succ_left hadd_succ_right)\n  apply (metis Seq_append_pair hadd_succ_left)\n  apply (metis Ord_succ Seq_append_OrdDom)\n  done\n\nlemma LstSeq_app [simp]: \"LstSeq s k y \\<Longrightarrow> app s k = y\"\n  by (metis LstSeq_def Seq_imp_eq_app)\n\nsubsection {*Sequence-building operators*}\n\ndefinition Builds :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"Builds B C s l \\<equiv> B (app s l) \\<or> (\\<exists>m \\<^bold>\\<in> l. \\<exists>n \\<^bold>\\<in> l. C (app s l) (app s m) (app s n))\"\n\ndefinition BuildSeq :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"BuildSeq B C s k y \\<equiv> LstSeq s k y \\<and> (\\<forall>l \\<^bold>\\<in> succ k. Builds B C s l)\"\n\nlemma BuildSeqI: \"LstSeq s k y \\<Longrightarrow> (\\<And>l. l \\<^bold>\\<in> succ k \\<Longrightarrow> Builds B C s l) \\<Longrightarrow> BuildSeq B C s k y\"\n  by (simp add: BuildSeq_def)\n\nlemma BuildSeq_imp_LstSeq: \"BuildSeq B C s k y \\<Longrightarrow> LstSeq s k y\"\n  by (metis BuildSeq_def)\n\nlemma BuildSeq_imp_Seq: \"BuildSeq B C s k y \\<Longrightarrow> Seq s (succ k)\"\n  by (metis LstSeq_imp_Seq_succ BuildSeq_imp_LstSeq)\n\nlemma BuildSeq_conj_distrib:\n \"BuildSeq (\\<lambda>x. B x \\<and> P x) (\\<lambda>x y z. C x y z \\<and> P x) s k y \\<longleftrightarrow>\n  BuildSeq B C s k y \\<and> (\\<forall>l \\<^bold>\\<in> succ k. P (app s l))\"\n  by (auto simp: BuildSeq_def Builds_def)\n\nlemma BuildSeq_mono:\n  assumes y: \"BuildSeq B C s k y\"\n      and B: \"\\<And>x. B x \\<Longrightarrow> B' x\" and C: \"\\<And>x y z. C x y z \\<Longrightarrow> C' x y z\"\n  shows \"BuildSeq B' C' s k y\"\nusing y\n  by (auto simp: BuildSeq_def Builds_def intro!: B C)\n\nlemma BuildSeq_trunc:\n  assumes b: \"BuildSeq B C s k y\"\n      and l: \"l \\<^bold>\\<in> k\"\n  shows \"BuildSeq B C s l (app s l)\"\nproof -\n  { fix j\n    assume j: \"j \\<^bold>\\<in> succ l\"\n    have k: \"Ord k\"\n      by (metis BuildSeq_imp_LstSeq LstSeq_def b)\n    hence \"Builds B C s j\"\n      by (metis BuildSeq_def OrdmemD b hballE hsubsetD j l succ_iff)\n }\n thus ?thesis using b l\n  by (auto simp: BuildSeq_def LstSeq_trunc)\nqed\n\nsubsection{*Showing that Sequences can be Constructed*}\n\nlemma Builds_insf: \"Builds B C s l \\<Longrightarrow> LstSeq s k z \\<Longrightarrow> l \\<^bold>\\<in> succ k \\<Longrightarrow> Builds B C (insf s (succ k) y) l\"\nby (auto simp: HBall_def hmem_not_refl Builds_def app_insf_LstSeq_if simp del: succ_iff)\n   (metis hmem_not_sym)\n\nlemma BuildSeq_insf:\n  assumes b: \"BuildSeq B C s k z\"\n      and m: \"m \\<^bold>\\<in> succ k\"\n      and n: \"n \\<^bold>\\<in> succ k\"\n      and y: \"B y \\<or> C y (app s m) (app s n)\"\nshows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\nproof (rule BuildSeqI)\n  show \"LstSeq (insf s (succ k) y) (succ k) y\"\n  by (metis BuildSeq_imp_LstSeq LstSeq_insf b)\nnext\n  fix l\n  assume l: \"l \\<^bold>\\<in> succ (succ k)\"\n  thus \"Builds B C (insf s (succ k) y) l\"\n  proof\n    assume l: \"l = succ k\"\n    have \"B (app (insf s l y) l) \\<or> C (app (insf s l y) l) (app (insf s l y) m) (app (insf s l y) n)\"\n      by (metis BuildSeq_imp_Seq app_insf_Seq_if b hmem_not_refl l m n y)\n    thus \"Builds B C (insf s (succ k) y) l\" using m n\n      by (auto simp: Builds_def l)\n  next\n    assume l: \"l \\<^bold>\\<in> succ k\"\n    have  \"LstSeq s k z\"\n      by (metis BuildSeq_imp_LstSeq b)\n    thus \"Builds B C (insf s (succ k) y) l\" using b l\n      by (metis hballE Builds_insf BuildSeq_def)\n  qed\nqed\n\nlemma BuildSeq_insf1:\n  assumes b: \"BuildSeq B C s k z\"\n      and y: \"B y\"\n  shows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\nby (metis BuildSeq_insf b succ_iff y)\n\nlemma BuildSeq_insf2:\n  assumes b: \"BuildSeq B C s k z\"\n      and m: \"m \\<^bold>\\<in> k\"\n      and n: \"n \\<^bold>\\<in> k\"\n      and y: \"C y (app s m) (app s n)\"\n  shows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\n  by (metis BuildSeq_insf b m n succ_iff y)\n\nlemma BuildSeq_append:\n  assumes s1: \"BuildSeq B C s1 k1 y1\" and s2: \"BuildSeq B C s2 k2 y2\"\n  shows \"BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\nproof (rule BuildSeqI)\n  show \"LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n    using assms\n    by (metis BuildSeq_imp_LstSeq LstSeq_append)\nnext\n  fix l\n  have s1L: \"LstSeq s1 k1 y1\"\n   and s1BC: \"\\<And>l. l \\<^bold>\\<in> succ k1 \\<Longrightarrow> Builds B C s1 l\"\n   and s2L: \"LstSeq s2 k2 y2\"\n   and s2BC: \"\\<And>l. l \\<^bold>\\<in> succ k2 \\<Longrightarrow> Builds B C s2 l\"\n    using s1 s2 by (auto simp: BuildSeq_def)\n  assume l: \"l \\<^bold>\\<in> succ (succ (k1 @+ k2))\"\n  hence  \"l \\<^bold>\\<in> succ k1 @+ succ k2\"\n    by (metis LstSeq_imp_Ord hadd_succ_left hadd_succ_right s2L)\n  thus \"Builds B C (seq_append (succ k1) s1 s2) l\"\n  proof (rule hmem_hadd_E)\n    assume l1: \"l \\<^bold>\\<in> succ k1\"\n    hence \"B (app s1 l) \\<or> (\\<exists>m\\<^bold>\\<in>l. \\<exists>n\\<^bold>\\<in>l. C (app s1 l) (app s1 m) (app s1 n))\" using s1BC\n      by (simp add: Builds_def)\n    thus ?thesis\n    proof\n      assume \"B (app s1 l)\"\n      thus ?thesis\n        by (metis Builds_def LstSeq_append_app1 l1 s1L)\n    next\n      assume \"\\<exists>m\\<^bold>\\<in>l. \\<exists>n\\<^bold>\\<in>l. C (app s1 l) (app s1 m) (app s1 n)\"\n      then obtain m n where mn: \"m \\<^bold>\\<in> l\" \"n \\<^bold>\\<in> l\" and C: \"C (app s1 l) (app s1 m) (app s1 n)\"\n        by blast\n      also have \"m \\<^bold>\\<in> succ k1\" \"n \\<^bold>\\<in> succ k1\"\n        by (metis LstSeq_def Ord_trans l1 mn s1L succ_iff)+\n      ultimately have \"C (app (seq_append (succ k1) s1 s2) l)\n                         (app (seq_append (succ k1) s1 s2) m)\n                         (app (seq_append (succ k1) s1 s2) n)\"\n        using s1L l1\n        by (simp add: LstSeq_append_app1)\n      thus \"Builds B C (seq_append (succ k1) s1 s2) l\" using mn\n        by (auto simp: Builds_def)\n    qed\n  next\n    fix z\n    assume z: \"z \\<^bold>\\<in> succ k2\" and l2: \"l = succ k1 @+ z\"\n    hence \"B (app s2 z) \\<or> (\\<exists>m\\<^bold>\\<in>z. \\<exists>n\\<^bold>\\<in>z. C (app s2 z) (app s2 m) (app s2 n))\" using s2BC\n      by (simp add: Builds_def)\n    thus ?thesis\n    proof\n      assume \"B (app s2 z)\"\n      thus ?thesis\n        by (metis Builds_def LstSeq_append_app2 l2 s1L s2L)\n    next\n      assume \"\\<exists>m\\<^bold>\\<in>z. \\<exists>n\\<^bold>\\<in>z. C (app s2 z) (app s2 m) (app s2 n)\"\n      then obtain m n where mn: \"m \\<^bold>\\<in> z\" \"n \\<^bold>\\<in> z\" and C: \"C (app s2 z) (app s2 m) (app s2 n)\"\n        by blast\n      also have \"m \\<^bold>\\<in> succ k2\" \"n \\<^bold>\\<in> succ k2\" using mn\n        by (metis LstSeq_def Ord_trans z s2L succ_iff)+\n      ultimately have \"C (app (seq_append (succ k1) s1 s2) l)\n                         (app (seq_append (succ k1) s1 s2) (succ k1 @+ m))\n                         (app (seq_append (succ k1) s1 s2) (succ k1 @+ n))\"\n        using s1L s2L l2 z\n        by (simp add: LstSeq_append_app2)\n      thus \"Builds B C (seq_append (succ k1) s1 s2) l\" using mn l2\n        by (auto simp: Builds_def HBall_def)\n    qed\n  qed\nqed\n\nlemma BuildSeq_combine:\n  assumes b1: \"BuildSeq B C s1 k1 y1\" and b2: \"BuildSeq B C s2 k2 y2\"\n      and y: \"C y y1 y2\"\n  shows \"BuildSeq B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) y) (succ (succ (k1 @+ k2))) y\"\nproof -\n  have k2: \"Ord k2\"  using b2\n    by (auto simp: BuildSeq_def LstSeq_def)\n  show ?thesis\n  proof (rule BuildSeq_insf [where m=k1 and n=\"succ(k1@+k2)\"])\n    show \"BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n      by (rule BuildSeq_append [OF b1 b2])\n  next\n    show \"k1 \\<^bold>\\<in> succ (succ (k1 @+ k2))\" using k2\n      by (metis hadd_0_right hmem_0_Ord hmem_self_hadd succ_iff)\n  next\n    show \"succ (k1 @+ k2) \\<^bold>\\<in> succ (succ (k1 @+ k2))\"\n      by (metis succ_iff)\n  next\n    have [simp]: \"app (seq_append (succ k1) s1 s2) k1 = y1\"\n      by (metis b1 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app1 succ_iff)\n    have [simp]: \"app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) = y2\"\n      by (metis b1 b2 k2 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app2 hadd_succ_left)\n    show \"B y \\<or>\n          C y (app (seq_append (succ k1) s1 s2) k1)\n              (app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)))\"\n      using y by simp\n  qed\nqed\n\nlemma LstSeq_1: \"LstSeq \\<lbrace>\\<langle>0, y\\<rangle>\\<rbrace> 0 y\"\n by (auto simp: LstSeq_def One_hf_eq_succ Seq_ins OrdDom_def)\n\nlemma BuildSeq_1: \"B y \\<Longrightarrow> BuildSeq B C \\<lbrace>\\<langle>0, y\\<rangle>\\<rbrace> 0 y\"\n  by (auto simp: BuildSeq_def Builds_def LstSeq_1)\n\nlemma BuildSeq_exI: \"B t \\<Longrightarrow> \\<exists>s k. BuildSeq B C s k t\"\n  by (metis BuildSeq_1)\n\nsubsection{*Proving Properties of Given Sequences*}\n\n\n\nlemma BuildSeq_induct [consumes 1, case_names B C]:\n  assumes major: \"BuildSeq B C s k a\"\n      and B: \"\\<And>x. B x \\<Longrightarrow> P x\"\n      and C: \"\\<And>x y z. C x y z \\<Longrightarrow> P y \\<Longrightarrow> P z \\<Longrightarrow> P x\"\n  shows \"P a\"\nproof -\n  have \"Ord k\" using assms\n    by (auto simp: BuildSeq_def LstSeq_def)\n  hence \"\\<And>a s. BuildSeq B C s k a \\<Longrightarrow> P a\"\n    by (induction k rule: Ord_induct) (metis BuildSeq_trunc BuildSeq_succ_E B C)\n  thus ?thesis\n    by (metis major)\nqed\n\ndefinition BuildSeq2 :: \"[[hf,hf] \\<Rightarrow> bool, [hf,hf,hf,hf,hf,hf] \\<Rightarrow> bool, hf, hf, hf, hf] \\<Rightarrow> bool\"\n  where \"BuildSeq2 B C s k y y' \\<equiv>\n         BuildSeq (\\<lambda>p. \\<exists>x x'. p = \\<langle>x,x'\\<rangle> \\<and> B x x')\n                  (\\<lambda>p q r. \\<exists>x x' y y' z z'. p = \\<langle>x,x'\\<rangle> \\<and> q = \\<langle>y,y'\\<rangle> \\<and> r = \\<langle>z,z'\\<rangle> \\<and> C x x' y y' z z')\n                  s k \\<langle>y,y'\\<rangle>\"\n\nlemma BuildSeq2_combine:\n  assumes b1: \"BuildSeq2 B C s1 k1 y1 y1'\" and b2: \"BuildSeq2 B C s2 k2 y2 y2'\"\n      and y: \"C y y' y1 y1' y2 y2'\"\n  shows \"BuildSeq2 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \\<langle>y, y'\\<rangle>)\n                       (succ (succ (k1 @+ k2))) y y'\"\n  using assms\n  apply (unfold BuildSeq2_def)\n  apply (blast intro: BuildSeq_combine)\n  done\n\nlemma BuildSeq2_1: \"B y y' \\<Longrightarrow> BuildSeq2 B C \\<lbrace>\\<langle>0, y, y'\\<rangle>\\<rbrace> 0 y y'\"\n  by (auto simp: BuildSeq2_def BuildSeq_1)\n\n\n\nlemma BuildSeq2_induct [consumes 1, case_names B C]:\n  assumes \"BuildSeq2 B C s k a a'\"\n      and B: \"\\<And>x x'. B x x' \\<Longrightarrow> P x x'\"\n      and C: \"\\<And>x x' y y' z z'. C x x' y y' z z' \\<Longrightarrow> P y y' \\<Longrightarrow> P z z' \\<Longrightarrow> P x x'\"\n  shows \"P a a'\"\nusing assms\napply (simp add: BuildSeq2_def)\napply (drule BuildSeq_induct [where P = \"\\<lambda>\\<langle>x,x'\\<rangle>. P x x'\"])\napply (auto intro: B C)\ndone\n\ndefinition BuildSeq3\n   :: \"[[hf,hf,hf] \\<Rightarrow> bool, [hf,hf,hf,hf,hf,hf,hf,hf,hf] \\<Rightarrow> bool, hf, hf, hf, hf, hf] \\<Rightarrow> bool\"\n  where \"BuildSeq3 B C s k y y' y'' \\<equiv>\n         BuildSeq (\\<lambda>p. \\<exists>x x' x''. p = \\<langle>x,x',x''\\<rangle> \\<and> B x x' x'')\n                  (\\<lambda>p q r. \\<exists>x x' x'' y y' y'' z z' z''.\n                           p = \\<langle>x,x',x''\\<rangle> \\<and> q = \\<langle>y,y',y''\\<rangle> \\<and> r = \\<langle>z,z',z''\\<rangle> \\<and>\n                           C x x' x'' y y' y'' z z' z'')\n                  s k \\<langle>y,y',y''\\<rangle>\"\n\nlemma BuildSeq3_combine:\n  assumes b1: \"BuildSeq3 B C s1 k1 y1 y1' y1''\" and b2: \"BuildSeq3 B C s2 k2 y2 y2' y2''\"\n      and y: \"C y y' y'' y1 y1' y1'' y2 y2' y2''\"\n  shows \"BuildSeq3 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \\<langle>y, y', y''\\<rangle>)\n                       (succ (succ (k1 @+ k2))) y y' y''\"\n  using assms\n  apply (unfold BuildSeq3_def)\n  apply (blast intro: BuildSeq_combine)\n  done\n\nlemma BuildSeq3_1: \"B y y' y'' \\<Longrightarrow> BuildSeq3 B C \\<lbrace>\\<langle>0, y, y', y''\\<rangle>\\<rbrace> 0 y y' y''\"\n  by (auto simp: BuildSeq3_def BuildSeq_1)\n\nlemma BuildSeq3_exI: \"B t t' t'' \\<Longrightarrow> \\<exists>s k. BuildSeq3 B C s k t t' t''\"\n  by (metis BuildSeq3_1)\n\nlemma BuildSeq3_induct [consumes 1, case_names B C]:\n  assumes \"BuildSeq3 B C s k a a' a''\"\n      and B: \"\\<And>x x' x''. B x x' x'' \\<Longrightarrow> P x x' x''\"\n      and C: \"\\<And>x x' x'' y y' y'' z z' z''. C x x' x'' y y' y'' z z' z'' \\<Longrightarrow> P y y' y'' \\<Longrightarrow> P z z' z'' \\<Longrightarrow> P x x' x''\"\n  shows \"P a a' a''\"\nusing assms\napply (simp add: BuildSeq3_def)\napply (drule BuildSeq_induct [where P = \"\\<lambda>\\<langle>x,x',x''\\<rangle>. P x x' x''\"])\napply (auto intro: B C)\ndone\n\n\nsection{*A Unique Predecessor for every non-empty set*}\n\nlemma Rep_hf_0 [simp]: \"Rep_hf 0 = 0\"\n  by (metis Abs_hf_inverse HF.HF_def UNIV_I Zero_hf_def image_empty set_encode_empty)\n\nlemma hmem_imp_less: \"x \\<^bold>\\<in> y \\<Longrightarrow> Rep_hf x < Rep_hf y\"\napply (auto simp: hmem_def hfset_def set_decode_def Abs_hf_inverse)\napply (metis div_less even_zero le_less_trans less_two_power not_less)\ndone\n\nlemma hsubset_imp_le: \"x \\<le> y \\<Longrightarrow> Rep_hf x \\<le> Rep_hf y\"\n  apply (auto simp: less_eq_hf_def hmem_def hfset_def Abs_hf_inverse)\n  apply (cases x rule: Abs_hf_cases)\n  apply (cases y rule: Abs_hf_cases, auto)\n  apply (rule subset_decode_imp_le)\n  apply (auto simp: Abs_hf_inverse [OF UNIV_I])\n  apply (metis Abs_hf_inverse UNIV_I imageE imageI)\n  done\n\nlemma diff_hmem_imp_less: assumes \"x \\<^bold>\\<in> y\" shows \"Rep_hf (y - \\<lbrace>x\\<rbrace>) < Rep_hf y\"\nproof -\n  have  \"Rep_hf (y - \\<lbrace>x\\<rbrace>) \\<le> Rep_hf y\"\n    by (metis hdiff_iff hsubsetI hsubset_imp_le)\n  moreover\n  have \"Rep_hf (y - \\<lbrace>x\\<rbrace>) \\<noteq> Rep_hf y\" using assms\n    by (metis Rep_hf_inject hdiff_iff hinsert_iff)\n  ultimately show ?thesis\n    by (metis le_neq_implies_less)\nqed\n\ndefinition least :: \"hf \\<Rightarrow> hf\"\n  where \"least a \\<equiv> (THE x. x \\<^bold>\\<in> a \\<and> (\\<forall>y. y \\<^bold>\\<in> a \\<longrightarrow> Rep_hf x \\<le> Rep_hf y))\"\n\nlemma least_equality:\n  assumes \"x \\<^bold>\\<in> a\" and \"\\<And>y. y \\<^bold>\\<in> a \\<Longrightarrow> Rep_hf x \\<le> Rep_hf y\"\n  shows \"least a = x\"\nunfolding least_def\napply (rule the_equality)\napply (metis assms)\napply (metis Rep_hf_inverse assms eq_iff)\ndone\n\n\n\nlemma nonempty_imp_ex_least: \"a \\<noteq> 0 \\<Longrightarrow> \\<exists>x. x \\<^bold>\\<in> a \\<and> (\\<forall>y. y \\<^bold>\\<in> a \\<longrightarrow> Rep_hf x \\<le> Rep_hf y)\"\nproof (induction a rule: hf_induct)\n  case 0 thus ?case by simp\nnext\n  case (hinsert u v)\n  show ?case\n    proof (cases \"v=0\")\n     case True thus ?thesis\n       by (rule_tac x=u in exI, simp)\n    next\n      case False\n      thus ?thesis\n        by (metis dual_order.trans eq_iff hinsert.IH(2) hmem_hinsert\n                  less_eq_insert1_iff linear)\n    qed\nqed\n\nlemma least_hmem: \"a \\<noteq> 0 \\<Longrightarrow> least a \\<^bold>\\<in> a\"\napply (frule nonempty_imp_ex_least, clarify)\napply (rule leastI2_order, auto)\ndone\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/HereditarilyFinite/OrdArith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7753924367641821}}
{"text": "(*\n  Copyright (c) 2014-2019 by Clemens Ballarin\n  This file is licensed under the 3-clause BSD license.\n*)\n\ntheory Group_Theory imports Set_Theory begin\n\nhide_const monoid\nhide_const group\nhide_const inverse\n\nno_notation quotient (infixl \"'/'/\" 90)\n\n\nsection \\<open>Monoids and Groups\\<close>\n\nsubsection \\<open>Monoids of Transformations and Abstract Monoids\\<close>\n\ntext \\<open>Def 1.1\\<close>\ntext \\<open>p 28, ll 28--30\\<close>\nlocale monoid =\n  fixes M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n  assumes composition_closed [intro, simp]: \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> a \\<cdot> b \\<in> M\"\n    and unit_closed [intro, simp]: \"\\<one> \\<in> M\"\n    and associative [intro]: \"\\<lbrakk> a \\<in> M; b \\<in> M; c \\<in> M \\<rbrakk> \\<Longrightarrow> (a \\<cdot> b) \\<cdot> c = a \\<cdot> (b \\<cdot> c)\"\n    and left_unit [intro, simp]: \"a \\<in> M \\<Longrightarrow> \\<one> \\<cdot> a = a\"\n    and right_unit [intro, simp]: \"a \\<in> M \\<Longrightarrow> a \\<cdot> \\<one> = a\"\n\ntext \\<open>p 29, ll 27--28\\<close>\nlocale submonoid = monoid M \"(\\<cdot>)\" \\<one>\n  for N and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes subset: \"N \\<subseteq> M\"\n    and sub_composition_closed: \"\\<lbrakk> a \\<in> N; b \\<in> N \\<rbrakk> \\<Longrightarrow> a \\<cdot> b \\<in> N\"\n    and sub_unit_closed: \"\\<one> \\<in> N\"\nbegin\n\ntext \\<open>p 29, ll 27--28\\<close>\nlemma sub [intro, simp]:\n  \"a \\<in> N \\<Longrightarrow> a \\<in> M\"\n  using subset by blast\n\ntext \\<open>p 29, ll 32--33\\<close>\nsublocale sub: monoid N \"(\\<cdot>)\" \\<one>\n  by unfold_locales (auto simp: sub_composition_closed sub_unit_closed)\n\nend (* submonoid *)\n\ntext \\<open>p 29, ll 33--34\\<close>\ntheorem submonoid_transitive:\n  assumes \"submonoid K N composition unit\"\n    and \"submonoid N M composition unit\"\n  shows \"submonoid K M composition unit\"\nproof -\n  interpret K: submonoid K N composition unit by fact\n  interpret M: submonoid N M composition unit by fact\n  show ?thesis by unfold_locales auto\nqed\n\ntext \\<open>p 28, l 23\\<close>\nlocale transformations =\n  fixes S :: \"'a set\"\n\n(*  assumes non_vacuous: \"S \\<noteq> {}\" *) (* Jacobson requires this but we don't need it, strange. *)\n\ntext \\<open>Monoid of all transformations\\<close>\ntext \\<open>p 28, ll 23--24\\<close>\nsublocale transformations \\<subseteq> monoid \"S \\<rightarrow>\\<^sub>E S\" \"compose S\" \"identity S\"\n  by unfold_locales (auto simp: PiE_def compose_eq compose_assoc Id_compose compose_Id)\n\ntext \\<open>@{term N} is a monoid of transformations of the set @{term S}.\\<close>\ntext \\<open>p 29, ll 34--36\\<close>\nlocale transformation_monoid =\n  transformations S + submonoid M \"S \\<rightarrow>\\<^sub>E S\" \"compose S\" \"identity S\" for M and S\nbegin\n\ntext \\<open>p 29, ll 34--36\\<close>\nlemma transformation_closed [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> M; x \\<in> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x \\<in> S\"\n  by (metis PiE_iff sub)\n\ntext \\<open>p 29, ll 34--36\\<close>\nlemma transformation_undefined [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> M; x \\<notin> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x = undefined\"\n  by (metis PiE_arb sub)\n\nend (* transformation_monoid *)\n\n\nsubsection \\<open>Groups of Transformations and Abstract Groups\\<close>\n\ncontext monoid begin\n\ntext \\<open>Invertible elements\\<close>\n\ntext \\<open>p 31, ll 3--5\\<close>\ndefinition invertible where \"u \\<in> M \\<Longrightarrow> invertible u \\<longleftrightarrow> (\\<exists>v \\<in> M. u \\<cdot> v = \\<one> \\<and> v \\<cdot> u = \\<one>)\"\n\ntext \\<open>p 31, ll 3--5\\<close>\nlemma invertibleI [intro]:\n  \"\\<lbrakk> u \\<cdot> v = \\<one>; v \\<cdot> u = \\<one>; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> invertible u\"\n  unfolding invertible_def by fast\n\ntext \\<open>p 31, ll 3--5\\<close>\nlemma invertibleE [elim]:\n  \"\\<lbrakk> invertible u; \\<And>v. \\<lbrakk> u \\<cdot> v = \\<one> \\<and> v \\<cdot> u = \\<one>; v \\<in> M \\<rbrakk> \\<Longrightarrow> P; u \\<in> M \\<rbrakk> \\<Longrightarrow> P\"\n  unfolding invertible_def by fast\n\ntext \\<open>p 31, ll 6--7\\<close>\ntheorem inverse_unique:\n  \"\\<lbrakk> u \\<cdot> v' = \\<one>; v \\<cdot> u = \\<one>; u \\<in> M;  v \\<in> M; v' \\<in> M \\<rbrakk> \\<Longrightarrow> v = v'\"\n  by (metis associative left_unit right_unit)\n\ntext \\<open>p 31, l 7\\<close>\ndefinition inverse where \"inverse = (\\<lambda>u \\<in> M. THE v. v \\<in> M \\<and> u \\<cdot> v = \\<one> \\<and> v \\<cdot> u = \\<one>)\"\n\ntext \\<open>p 31, l 7\\<close>\ntheorem inverse_equality:\n  \"\\<lbrakk> u \\<cdot> v = \\<one>; v \\<cdot> u = \\<one>; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u = v\"\n  unfolding inverse_def using inverse_unique by simp blast\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_inverse_closed [intro, simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u \\<in> M\"\n  using inverse_equality by auto\n\ntext \\<open>p 31, l 7\\<close>\nlemma inverse_undefined [intro, simp]:\n  \"u \\<notin> M \\<Longrightarrow> inverse u = undefined\"\n  by (simp add: inverse_def)\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_left_inverse [simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u \\<cdot> u = \\<one>\"\n  using inverse_equality by auto\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_right_inverse [simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> u \\<cdot> inverse u = \\<one>\"\n  using inverse_equality by auto\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_left_cancel [simp]:\n  \"\\<lbrakk> invertible x; x \\<in> M; y \\<in> M; z \\<in> M \\<rbrakk> \\<Longrightarrow> x \\<cdot> y = x \\<cdot> z \\<longleftrightarrow> y = z\"\n  by (metis associative invertible_def left_unit)\n\ntext \\<open>p 31, l 7\\<close>\nlemma invertible_right_cancel [simp]:\n  \"\\<lbrakk> invertible x; x \\<in> M; y \\<in> M; z \\<in> M \\<rbrakk> \\<Longrightarrow> y \\<cdot> x = z \\<cdot> x \\<longleftrightarrow> y = z\"\n  by (metis associative invertible_def right_unit)\n\ntext \\<open>p 31, l 7\\<close>\nlemma inverse_unit [simp]: \"inverse \\<one> = \\<one>\"\n  using inverse_equality by blast\n\ntext \\<open>p 31, ll 7--8\\<close>\ntheorem invertible_inverse_invertible [intro, simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> invertible (inverse u)\"\n  using invertible_left_inverse invertible_right_inverse by blast\n\ntext \\<open>p 31, l 8\\<close>\ntheorem invertible_inverse_inverse [simp]:\n  \"\\<lbrakk> invertible u; u \\<in> M \\<rbrakk> \\<Longrightarrow> inverse (inverse u) = u\"\n  by (simp add: inverse_equality)\n\nend (* monoid *)\n\ncontext submonoid begin\n\ntext \\<open>Reasoning about @{term invertible} and @{term inverse} in submonoids.\\<close>\n\ntext \\<open>p 31, l 7\\<close>\nlemma submonoid_invertible [intro, simp]:\n  \"\\<lbrakk> sub.invertible u; u \\<in> N \\<rbrakk> \\<Longrightarrow> invertible u\"\n  using invertibleI by blast\n\ntext \\<open>p 31, l 7\\<close>\nlemma submonoid_inverse_closed [intro, simp]:\n  \"\\<lbrakk> sub.invertible u; u \\<in> N \\<rbrakk> \\<Longrightarrow> inverse u \\<in> N\"\n  using inverse_equality by auto\n\nend (* submonoid *)\n\ntext \\<open>Def 1.2\\<close>\ntext \\<open>p 31, ll 9--10\\<close>\nlocale group =\n  monoid G \"(\\<cdot>)\" \\<one> for G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes invertible [simp, intro]: \"u \\<in> G \\<Longrightarrow> invertible u\"\n\ntext \\<open>p 31, ll 11--12\\<close>\nlocale subgroup = submonoid G M \"(\\<cdot>)\" \\<one> + sub: group G \"(\\<cdot>)\" \\<one>\n  for G and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\nbegin\n\ntext \\<open>Reasoning about @{term invertible} and @{term inverse} in subgroups.\\<close>\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma subgroup_inverse_equality [simp]:\n  \"u \\<in> G \\<Longrightarrow> inverse u = sub.inverse u\"\n  by (simp add: inverse_equality)\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma subgroup_inverse_iff [simp]:\n  \"\\<lbrakk> invertible x; x \\<in> M \\<rbrakk> \\<Longrightarrow> inverse x \\<in> G \\<longleftrightarrow> x \\<in> G\"\n  using invertible_inverse_inverse sub.invertible_inverse_closed by fastforce\n\nend (* subgroup *)\n\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma subgroup_transitive [trans]:\n  assumes \"subgroup K H composition unit\"\n    and \"subgroup H G composition unit\"\n  shows \"subgroup K G composition unit\"\nproof -\n  interpret K: subgroup K H composition unit by fact\n  interpret H: subgroup H G composition unit by fact\n  show ?thesis by unfold_locales auto\nqed\n\ncontext monoid begin\n\ntext \\<open>Jacobson states both directions, but the other one is trivial.\\<close>\ntext \\<open>p 31, ll 12--15\\<close>\ntheorem subgroupI:\n  fixes G\n  assumes subset [THEN subsetD, intro]: \"G \\<subseteq> M\"\n    and [intro]: \"\\<one> \\<in> G\"\n    and [intro]: \"\\<And>g h. \\<lbrakk> g \\<in> G; h \\<in> G \\<rbrakk> \\<Longrightarrow> g \\<cdot> h \\<in> G\"\n    and [intro]: \"\\<And>g. g \\<in> G \\<Longrightarrow> invertible g\"\n    and [intro]: \"\\<And>g. g \\<in> G \\<Longrightarrow> inverse g \\<in> G\"\n  shows \"subgroup G M (\\<cdot>) \\<one>\"\nproof -\n  interpret sub: monoid G \"(\\<cdot>)\" \\<one> by unfold_locales auto\n  show ?thesis\n  proof unfold_locales\n    fix u assume [intro]: \"u \\<in> G\" show \"sub.invertible u\"\n    using invertible_left_inverse invertible_right_inverse by blast\n  qed auto\nqed\n\ntext \\<open>p 31, l 16\\<close>\ndefinition \"Units = {u \\<in> M. invertible u}\"\n\ntext \\<open>p 31, l 16\\<close>\n\n\ntext \\<open>p 31, l 16\\<close>\nlemma mem_UnitsD:\n  \"\\<lbrakk> u \\<in> Units \\<rbrakk> \\<Longrightarrow> invertible u \\<and> u \\<in> M\"\n  unfolding Units_def by clarify\n\ntext \\<open>p 31, ll 16--21\\<close>\ninterpretation units: subgroup Units M\nproof (rule subgroupI)\n  fix u1 u2\n  assume Units [THEN mem_UnitsD, simp]: \"u1 \\<in> Units\" \"u2 \\<in> Units\"\n  have \"(u1 \\<cdot> u2) \\<cdot> (inverse u2 \\<cdot> inverse u1) = (u1 \\<cdot> (u2 \\<cdot> inverse u2)) \\<cdot> inverse u1\"\n    by (simp add: associative del: invertible_left_inverse invertible_right_inverse)\n  also have \"\\<dots> = \\<one>\" by simp\n  finally have inv1: \"(u1 \\<cdot> u2) \\<cdot> (inverse u2 \\<cdot> inverse u1) = \\<one>\" by simp  \\<comment> \\<open>ll 16--18\\<close>\n  have \"(inverse u2 \\<cdot> inverse u1) \\<cdot> (u1 \\<cdot> u2) = (inverse u2 \\<cdot> (inverse u1 \\<cdot> u1)) \\<cdot> u2\"\n    by (simp add: associative del: invertible_left_inverse invertible_right_inverse)\n  also have \"\\<dots> = \\<one>\" by simp\n  finally have inv2: \"(inverse u2 \\<cdot> inverse u1) \\<cdot> (u1 \\<cdot> u2) = \\<one>\" by simp  \\<comment> \\<open>l 9, ``and similarly''\\<close>\n  show \"u1 \\<cdot> u2 \\<in> Units\" using inv1 inv2 invertibleI mem_UnitsI by auto\nqed (auto simp: Units_def)\n\ntext \\<open>p 31, ll 21--22\\<close>\ntheorem group_of_Units [intro, simp]:\n  \"group Units (\\<cdot>) \\<one>\"\n  ..\n\ntext \\<open>p 31, l 19\\<close>\nlemma composition_invertible [simp, intro]:\n  \"\\<lbrakk> invertible x; invertible y; x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> invertible (x \\<cdot> y)\"\n  using mem_UnitsD mem_UnitsI by blast\n\ntext \\<open>p 31, l 20\\<close>\nlemma unit_invertible:\n  \"invertible \\<one>\"\n  by fast\n\ntext \\<open>Useful simplification rules\\<close>\ntext \\<open>p 31, l 22\\<close>\nlemma invertible_right_inverse2:\n  \"\\<lbrakk> invertible u; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> u \\<cdot> (inverse u \\<cdot> v) = v\"\n  by (simp add: associative [THEN sym])\n\ntext \\<open>p 31, l 22\\<close>\nlemma invertible_left_inverse2:\n  \"\\<lbrakk> invertible u; u \\<in> M; v \\<in> M \\<rbrakk> \\<Longrightarrow> inverse u \\<cdot> (u \\<cdot> v) = v\"\n  by (simp add: associative [THEN sym])\n\ntext \\<open>p 31, l 22\\<close>\nlemma inverse_composition_commute:\n  assumes [simp]: \"invertible x\" \"invertible y\" \"x \\<in> M\" \"y \\<in> M\"\n  shows \"inverse (x \\<cdot> y) = inverse y \\<cdot> inverse x\"\nproof -\n  have \"inverse (x \\<cdot> y) \\<cdot> (x \\<cdot> y) = (inverse y \\<cdot> inverse x) \\<cdot> (x \\<cdot> y)\"\n  by (simp add: invertible_left_inverse2 associative)\n  then show ?thesis by (simp del: invertible_left_inverse)\nqed\n\nend (* monoid *)\n\ntext \\<open>p 31, l 24\\<close>\ncontext transformations begin\n\ntext \\<open>p 31, ll 25--26\\<close>\ntheorem invertible_is_bijective:\n  assumes dom: \"\\<alpha> \\<in> S \\<rightarrow>\\<^sub>E S\"\n  shows \"invertible \\<alpha> \\<longleftrightarrow> bij_betw \\<alpha> S S\"\nproof -\n  from dom interpret map \\<alpha> S S by unfold_locales\n  show ?thesis by (auto simp add: bij_betw_iff_has_inverse invertible_def)\nqed\n\ntext \\<open>p 31, ll 26--27\\<close>\ntheorem Units_bijective:\n  \"Units = {\\<alpha> \\<in> S \\<rightarrow>\\<^sub>E S. bij_betw \\<alpha> S S}\"\n  unfolding Units_def by (auto simp add: invertible_is_bijective)\n\ntext \\<open>p 31, ll 26--27\\<close>\nlemma Units_bij_betwI [intro, simp]:\n  \"\\<alpha> \\<in> Units \\<Longrightarrow> bij_betw \\<alpha> S S\"\n  by (simp add: Units_bijective)\n\ntext \\<open>p 31, ll 26--27\\<close>\nlemma Units_bij_betwD [dest, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> S \\<rightarrow>\\<^sub>E S; bij_betw \\<alpha> S S \\<rbrakk> \\<Longrightarrow> \\<alpha> \\<in> Units\"\n  unfolding Units_bijective by simp\n\ntext \\<open>p 31, ll 28--29\\<close>\nabbreviation \"Sym \\<equiv> Units\"\n\ntext \\<open>p 31, ll 26--28\\<close>\nsublocale symmetric: group \"Sym\" \"compose S\" \"identity S\"\n  by (fact group_of_Units)\n\nend (* transformations *)\n\ntext \\<open>p 32, ll 18--19\\<close>\nlocale transformation_group =\n  transformations S + symmetric: subgroup G Sym \"compose S\" \"identity S\" for G and S\nbegin\n\ntext \\<open>p 32, ll 18--19\\<close>\nlemma transformation_group_closed [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> G; x \\<in> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x \\<in> S\"\n  using bij_betwE by blast\n\ntext \\<open>p 32, ll 18--19\\<close>\nlemma transformation_group_undefined [intro, simp]:\n  \"\\<lbrakk> \\<alpha> \\<in> G; x \\<notin> S \\<rbrakk> \\<Longrightarrow> \\<alpha> x = undefined\"\n  by (metis compose_def symmetric.sub.right_unit restrict_apply)\n\nend (* transformation_group *)\n\n\nsubsection \\<open>Isomorphisms.  Cayley's Theorem\\<close>\n\ntext \\<open>Def 1.3\\<close>\ntext \\<open>p 37, ll 7--11\\<close>\nlocale monoid_isomorphism =\n  bijective_map \\<eta> M M' +  source: monoid M \"(\\<cdot>)\" \\<one> + target: monoid M' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and M' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\") +\n  assumes commutes_with_composition: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> x \\<cdot>' \\<eta> y = \\<eta> (x \\<cdot> y)\"\n    and commutes_with_unit: \"\\<eta> \\<one> = \\<one>'\"\n\ntext \\<open>p 37, l 10\\<close>\ndefinition isomorphic_as_monoids (infixl \"\\<cong>\\<^sub>M\" 50)\n  where \"\\<M> \\<cong>\\<^sub>M \\<M>' \\<longleftrightarrow> (let (M, composition, unit) = \\<M>; (M', composition', unit') = \\<M>' in\n  (\\<exists>\\<eta>. monoid_isomorphism \\<eta> M composition unit M' composition' unit'))\"\n\ntext \\<open>p 37, ll 11--12\\<close>\nlocale monoid_isomorphism' =\n  bijective_map \\<eta> M M' +  source: monoid M \"(\\<cdot>)\" \\<one> + target: monoid M' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and M' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\") +\n  assumes commutes_with_composition: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> x \\<cdot>' \\<eta> y = \\<eta> (x \\<cdot> y)\"\n\ntext \\<open>p 37, ll 11--12\\<close>\nsublocale monoid_isomorphism \\<subseteq> monoid_isomorphism'\n  by unfold_locales (simp add: commutes_with_composition)\n\ntext \\<open>Both definitions are equivalent.\\<close>\ntext \\<open>p 37, ll 12--15\\<close>\nsublocale monoid_isomorphism' \\<subseteq> monoid_isomorphism\nproof unfold_locales\n  {\n    fix y assume \"y \\<in> M'\"\n    then obtain x where \"\\<eta> x = y\" \"x \\<in> M\" by (metis image_iff surjective)\n    then have \"y \\<cdot>' \\<eta> \\<one> = y\" using commutes_with_composition by auto\n  }\n  then show \"\\<eta> \\<one> = \\<one>'\" by fastforce\nqed (simp add: commutes_with_composition)\n\ncontext monoid_isomorphism begin\n\ntext \\<open>p 37, ll 30--33\\<close>\n\n\nend (* monoid_isomorphism *)\n\ntext \\<open>We only need that @{term \\<eta>} is symmetric.\\<close>\ntext \\<open>p 37, ll 28--29\\<close>\ntheorem isomorphic_as_monoids_symmetric:\n  \"(M, composition, unit) \\<cong>\\<^sub>M (M', composition', unit') \\<Longrightarrow> (M', composition', unit') \\<cong>\\<^sub>M (M, composition, unit)\"\n  by (simp add: isomorphic_as_monoids_def) (meson monoid_isomorphism.inverse_monoid_isomorphism)\n\ntext \\<open>p 38, l 4\\<close>\nlocale left_translations_of_monoid = monoid begin\n\n(*\n  We take the liberty of omitting \"left_\" from the name of the translation operation.  The derived\n  transformation monoid and group won't be qualified with \"left\" either.  This avoids qualifications\n  such as \"left.left_...\".  In contexts where left and right translations are used simultaneously,\n  notably subgroup_of_group, qualifiers are needed.\n*)\n\ntext \\<open>p 38, ll 5--7\\<close>\ndefinition translation (\"'(_')\\<^sub>L\") where \"translation = (\\<lambda>a \\<in> M. \\<lambda>x \\<in> M. a \\<cdot> x)\"\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemma translation_map [intro, simp]:\n  \"a \\<in> M \\<Longrightarrow> (a)\\<^sub>L \\<in> M \\<rightarrow>\\<^sub>E M\"\n  unfolding translation_def by simp\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemma Translations_maps [intro, simp]:\n  \"translation ` M \\<subseteq> M \\<rightarrow>\\<^sub>E M\"\n  by (simp add: image_subsetI)\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemma translation_apply:\n  \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> (a)\\<^sub>L b = a \\<cdot> b\"\n  unfolding translation_def by auto\n\ntext \\<open>p 38, ll 5--7\\<close>\n\n\ntext \\<open>p 38, ll 5--7\\<close>\nlemmas Translations_E [elim] = translation_exist [THEN bexE]\n\ntext \\<open>p 38, l 10\\<close>\ntheorem translation_unit_eq [simp]:\n  \"identity M = (\\<one>)\\<^sub>L\"\n  unfolding translation_def by auto\n\ntext \\<open>p 38, ll 10--11\\<close>\ntheorem translation_composition_eq [simp]:\n  assumes [simp]: \"a \\<in> M\" \"b \\<in> M\"\n  shows \"compose M (a)\\<^sub>L (b)\\<^sub>L = (a \\<cdot> b)\\<^sub>L\"\n  unfolding translation_def by rule (simp add: associative compose_def)\n\n(* Activate @{locale monoid} to simplify subsequent proof. *)\ntext \\<open>p 38, ll 7--9\\<close>\nsublocale transformation: transformations M .\n\ntext \\<open>p 38, ll 7--9\\<close>\ntheorem Translations_transformation_monoid:\n  \"transformation_monoid (translation ` M) M\"\n  by unfold_locales auto\n\ntext \\<open>p 38, ll 7--9\\<close>\nsublocale transformation: transformation_monoid \"translation ` M\" M\n  by (fact Translations_transformation_monoid)\n\ntext \\<open>p 38, l 12\\<close>\nsublocale map translation M \"translation ` M\"\n  by unfold_locales (simp add: translation_def)\n\ntext \\<open>p 38, ll 12--16\\<close>\ntheorem translation_isomorphism [intro]:\n  \"monoid_isomorphism translation M (\\<cdot>) \\<one> (translation ` M) (compose M) (identity M)\"\nproof unfold_locales\n  have \"inj_on translation M\"\n  proof (rule inj_onI)\n    fix a b\n    assume [simp]: \"a \\<in> M\" \"b \\<in> M\" \"(a)\\<^sub>L = (b)\\<^sub>L\"\n    have \"(a)\\<^sub>L \\<one> = (b)\\<^sub>L \\<one>\" by simp\n    then show \"a = b\" by (simp add: translation_def)\n  qed\n  then show \"bij_betw translation M (translation ` M)\"\n    by (simp add: inj_on_imp_bij_betw)\nqed simp_all\n\ntext \\<open>p 38, ll 12--16\\<close>\nsublocale monoid_isomorphism translation M \"(\\<cdot>)\" \\<one> \"translation ` M\" \"compose M\" \"identity M\" ..\n\nend (* left_translations_of_monoid *)\n\ncontext monoid begin\n\ntext \\<open>p 38, ll 1--2\\<close>\ninterpretation left_translations_of_monoid ..\n\ntext \\<open>p 38, ll 1--2\\<close>\ntheorem cayley_monoid:\n  \"\\<exists>M' composition' unit'. transformation_monoid M' M \\<and> (M, (\\<cdot>), \\<one>) \\<cong>\\<^sub>M (M', composition', unit')\"\n  by (simp add: isomorphic_as_monoids_def) (fast intro: Translations_transformation_monoid)\n\nend (* monoid *)\n\ntext \\<open>p 38, l 17\\<close>\nlocale left_translations_of_group = group begin\n\ntext \\<open>p 38, ll 17--18\\<close>\nsublocale left_translations_of_monoid where M = G ..\n\ntext \\<open>p 38, ll 17--18\\<close>\nnotation translation (\"'(_')\\<^sub>L\")\n\ntext \\<open>\n  The group of left translations is a subgroup of the symmetric group,\n  hence @{term transformation.sub.invertible}.\n\\<close>\ntext \\<open>p 38, ll 20--22\\<close>\ntheorem translation_invertible [intro, simp]:\n  assumes [simp]: \"a \\<in> G\"\n  shows \"transformation.sub.invertible (a)\\<^sub>L\"\nproof\n  show \"compose G (a)\\<^sub>L (inverse a)\\<^sub>L = identity G\" by simp\nnext\n  show \"compose G (inverse a)\\<^sub>L (a)\\<^sub>L = identity G\" by simp\nqed auto\n\ntext \\<open>p 38, ll 19--20\\<close>\ntheorem translation_bijective [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> bij_betw (a)\\<^sub>L G G\"\n  by (blast intro: transformation.invertible_is_bijective [THEN iffD1])\n\ntext \\<open>p 38, ll 18--20\\<close>\ntheorem Translations_transformation_group:\n  \"transformation_group (translation ` G) G\"\nproof unfold_locales\n  show \"(translation ` G) \\<subseteq> transformation.Sym\"\n    unfolding transformation.Units_bijective by auto\nnext\n  fix \\<alpha>\n  assume \\<alpha>: \"\\<alpha> \\<in> translation ` G\"\n  then obtain a where a: \"a \\<in> G\" and eq: \"\\<alpha> = (a)\\<^sub>L\" ..\n  with translation_invertible show \"transformation.sub.invertible \\<alpha>\" by simp\nqed auto\n\ntext \\<open>p 38, ll 18--20\\<close>\nsublocale transformation: transformation_group \"translation ` G\" G\n  by (fact Translations_transformation_group)\n\nend (* left_translations_of_group *)\n\ncontext group begin\n\ntext \\<open>p 38, ll 2--3\\<close>\ninterpretation left_translations_of_group ..\n\ntext \\<open>p 38, ll 2--3\\<close>\ntheorem cayley_group:\n  \"\\<exists>G' composition' unit'. transformation_group G' G \\<and> (G, (\\<cdot>), \\<one>) \\<cong>\\<^sub>M (G', composition', unit')\"\n  by (simp add: isomorphic_as_monoids_def) (fast intro: Translations_transformation_group)\n\nend (* group *)\n\ntext \\<open>Exercise 3\\<close>\n\ntext \\<open>p 39, ll 9--10\\<close>\nlocale right_translations_of_group = group begin\n\ntext \\<open>p 39, ll 9--10\\<close>\ndefinition translation (\"'(_')\\<^sub>R\") where \"translation = (\\<lambda>a \\<in> G. \\<lambda>x \\<in> G. x \\<cdot> a)\"\n\ntext \\<open>p 39, ll 9--10\\<close>\nabbreviation \"Translations \\<equiv> translation ` G\"\n\ntext \\<open>The isomorphism that will be established is a map different from @{term translation}.\\<close>\ntext \\<open>p 39, ll 9--10\\<close>\ninterpretation aux: map translation G Translations\n  by unfold_locales (simp add: translation_def)\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_map [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> (a)\\<^sub>R \\<in> G \\<rightarrow>\\<^sub>E G\"\n  unfolding translation_def by simp\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma Translation_maps [intro, simp]:\n  \"Translations \\<subseteq> G \\<rightarrow>\\<^sub>E G\"\n  by (simp add: image_subsetI)\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_apply:\n  \"\\<lbrakk> a \\<in> G; b \\<in> G \\<rbrakk> \\<Longrightarrow> (a)\\<^sub>R b = b \\<cdot> a\"\n  unfolding translation_def by auto\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_exist:\n  \"f \\<in> Translations \\<Longrightarrow> \\<exists>a \\<in> G. f = (a)\\<^sub>R\"\n  by auto\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemmas Translations_E [elim] = translation_exist [THEN bexE]\n\ntext \\<open>p 39, ll 9--10\\<close>\nlemma translation_unit_eq [simp]:\n  \"identity G = (\\<one>)\\<^sub>R\"\n  unfolding translation_def by auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_composition_eq [simp]:\n  assumes [simp]: \"a \\<in> G\" \"b \\<in> G\"\n  shows \"compose G (a)\\<^sub>R (b)\\<^sub>R = (b \\<cdot> a)\\<^sub>R\"\n  unfolding translation_def by rule (simp add: associative compose_def)\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale transformation: transformations G .\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma Translations_transformation_monoid:\n  \"transformation_monoid Translations G\"\n  by unfold_locales auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale transformation: transformation_monoid Translations G\n  by (fact Translations_transformation_monoid)\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_invertible [intro, simp]:\n  assumes [simp]: \"a \\<in> G\"\n  shows \"transformation.sub.invertible (a)\\<^sub>R\"\nproof\n  show \"compose G (a)\\<^sub>R (inverse a)\\<^sub>R = identity G\" by simp\nnext\n  show \"compose G (inverse a)\\<^sub>R (a)\\<^sub>R = identity G\" by simp\nqed auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_bijective [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> bij_betw (a)\\<^sub>R G G\"\n  by (blast intro: transformation.invertible_is_bijective [THEN iffD1])\n\ntext \\<open>p 39, ll 10--11\\<close>\ntheorem Translations_transformation_group:\n  \"transformation_group Translations G\"\nproof unfold_locales\n  show \"Translations \\<subseteq> transformation.Sym\"\n  unfolding transformation.Units_bijective by auto\nnext\n  fix \\<alpha>\n  assume \\<alpha>: \"\\<alpha> \\<in> Translations\"\n  then obtain a where a: \"a \\<in> G\" and eq: \"\\<alpha> = (a)\\<^sub>R\" ..\n  with translation_invertible show \"transformation.sub.invertible \\<alpha>\" by simp\nqed auto\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale transformation: transformation_group Translations G\n  by (rule Translations_transformation_group)\n\ntext \\<open>p 39, ll 10--11\\<close>\nlemma translation_inverse_eq [simp]:\n  assumes [simp]: \"a \\<in> G\"\n  shows \"transformation.sub.inverse (a)\\<^sub>R = (inverse a)\\<^sub>R\"\nproof (rule transformation.sub.inverse_equality)\n  show \"compose G (a)\\<^sub>R (inverse a)\\<^sub>R = identity G\" by simp\nnext\n  show \"compose G (inverse a)\\<^sub>R (a)\\<^sub>R = identity G\" by simp\nqed auto\n\ntext \\<open>p 39, ll 10--11\\<close>\ntheorem translation_inverse_monoid_isomorphism [intro]:\n  \"monoid_isomorphism (\\<lambda>a\\<in>G. transformation.symmetric.inverse (a)\\<^sub>R) G (\\<cdot>) \\<one> Translations (compose G) (identity G)\"\n  (is \"monoid_isomorphism ?inv _ _ _ _ _ _\")\nproof unfold_locales\n  show \"?inv \\<in> G \\<rightarrow>\\<^sub>E Translations\" by (simp del: translation_unit_eq)\nnext\n  note bij_betw_compose [trans]\n  have \"bij_betw inverse G G\"\n    by (rule bij_betwI [where g = inverse]) auto\n  also have \"bij_betw translation G Translations\"\n    by (rule bij_betwI [where g = \"\\<lambda>\\<alpha>\\<in>Translations. \\<alpha> \\<one>\"]) (auto simp: translation_apply)\n  finally show \"bij_betw ?inv G Translations\"\n    by (simp cong: bij_betw_cong add: compose_eq del: translation_unit_eq)\nnext\n  fix x and y\n  assume [simp]: \"x \\<in> G\" \"y \\<in> G\"\n  show \"compose G (?inv x) (?inv y) = (?inv (x \\<cdot> y))\" by (simp add: inverse_composition_commute del: translation_unit_eq)\nnext\n  show \"?inv \\<one> = identity G\" by (simp del: translation_unit_eq) simp\nqed\n\ntext \\<open>p 39, ll 10--11\\<close>\nsublocale monoid_isomorphism\n  \"\\<lambda>a\\<in>G. transformation.symmetric.inverse (a)\\<^sub>R\" G \"(\\<cdot>)\" \\<one> Translations \"compose G\" \"identity G\" ..\n\nend (* right_translations_of_group *)\n\n\nsubsection \\<open>Generalized Associativity.  Commutativity\\<close>\n\ntext \\<open>p 40, l 27; p 41, ll 1--2\\<close>\nlocale commutative_monoid = monoid +\n  assumes commutative: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> x \\<cdot> y = y \\<cdot> x\"\n  \ntext \\<open>p 41, l 2\\<close>\nlocale abelian_group = group + commutative_monoid G \"(\\<cdot>)\" \\<one>\n\n\nsubsection \\<open>Orbits.  Cosets of a Subgroup\\<close>\n\ncontext transformation_group begin\n\ntext \\<open>p 51, ll 18--20\\<close>\ndefinition Orbit_Relation\n  where \"Orbit_Relation = {(x, y). x \\<in> S \\<and> y \\<in> S \\<and> (\\<exists>\\<alpha> \\<in> G. y = \\<alpha> x)}\"\n\ntext \\<open>p 51, ll 18--20\\<close>\nlemma Orbit_Relation_memI [intro]:\n  \"\\<lbrakk> \\<exists>\\<alpha> \\<in> G. y = \\<alpha> x; x \\<in> S \\<rbrakk> \\<Longrightarrow> (x, y) \\<in> Orbit_Relation\"\n  unfolding Orbit_Relation_def by auto\n\ntext \\<open>p 51, ll 18--20\\<close>\nlemma Orbit_Relation_memE [elim]:\n  \"\\<lbrakk> (x, y) \\<in> Orbit_Relation; \\<And>\\<alpha>. \\<lbrakk> \\<alpha> \\<in> G; x \\<in> S; y = \\<alpha> x \\<rbrakk> \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> Q\"\n  unfolding Orbit_Relation_def by auto\n\ntext \\<open>p 51, ll 20--23, 26--27\\<close>\nsublocale orbit: equivalence S Orbit_Relation\nproof (unfold_locales, auto simp: Orbit_Relation_def)\n  fix x\n  assume x: \"x \\<in> S\"\n  then have id: \"x = identity S x\" by simp\n  with x show \"\\<exists>\\<alpha> \\<in> G. x = \\<alpha> x\" by fast\n  fix \\<alpha>\n  assume \\<alpha>: \"\\<alpha> \\<in> G\"\n  with x id have y: \"x = compose S (symmetric.inverse \\<alpha>) \\<alpha> x\" by auto\n  with x \\<alpha> show \"\\<exists>\\<alpha>' \\<in> G. x = \\<alpha>' (\\<alpha> x)\"\n    by (metis compose_eq symmetric.sub.invertible symmetric.submonoid_inverse_closed)\n  fix \\<beta>\n  assume \\<beta>: \"\\<beta> \\<in> G\"\n  with x have \"\\<beta> (\\<alpha> x) = compose S \\<beta> \\<alpha> x\" by (simp add: compose_eq)\n  with \\<alpha> \\<beta> show \"\\<exists>\\<gamma> \\<in> G. \\<beta> (\\<alpha> x) = \\<gamma> x\" by fast\nqed\n\ntext \\<open>p 51, ll 23--24\\<close>\ntheorem orbit_equality:\n  \"x \\<in> S \\<Longrightarrow> orbit.Class x = {\\<alpha> x | \\<alpha>. \\<alpha> \\<in> G}\"\nby (simp add: orbit.Class_def) (blast intro: orbit.symmetric dest: orbit.symmetric)\n\nend (* transformation_group *)\n\ncontext monoid_isomorphism begin\n\ntext \\<open>p 52, ll 16--17\\<close>\ntheorem image_subgroup:\n  assumes \"subgroup G M (\\<cdot>) \\<one>\"\n  shows \"subgroup (\\<eta> ` G) M' (\\<cdot>') \\<one>'\"\nproof -\n  interpret subgroup G M \"(\\<cdot>)\" \\<one> by fact\n  interpret image: monoid \"\\<eta> ` G\" \"(\\<cdot>')\" \"\\<one>'\"\n    by unfold_locales (auto simp add: commutes_with_composition commutes_with_unit [symmetric])\n  show ?thesis\n  proof (unfold_locales, auto)\n    fix x\n    assume x: \"x \\<in> G\"\n    show \"image.invertible (\\<eta> x)\"\n    proof\n      show \"\\<eta> (sub.inverse x) \\<in> \\<eta> ` G\" using x by simp\n    qed (auto simp: x commutes_with_composition commutes_with_unit)\n  qed\nqed\n\nend (* monoid_isomorphism *)\n\ntext \\<open>\n  Technical device to achieve Jacobson's notation for @{text Right_Coset} and @{text Left_Coset}.  The\n  definitions are pulled out of @{text subgroup_of_group} to a context where @{text H} is not a parameter.\n\\<close>\ntext \\<open>p 52, l 20\\<close>\nlocale coset_notation = fixes composition (infixl \"\\<cdot>\" 70)  begin\n\ntext \\<open>Equation 23\\<close>\ntext \\<open>p 52, l 20\\<close>\ndefinition Right_Coset (infixl \"|\\<cdot>\" 70) where \"H |\\<cdot> x = {h \\<cdot> x | h. h \\<in> H}\"\n\ntext \\<open>p 53, ll 8--9\\<close>\ndefinition Left_Coset (infixl \"\\<cdot>|\" 70) where \"x \\<cdot>| H = {x \\<cdot> h | h. h \\<in> H}\"\n\ntext \\<open>p 52, l 20\\<close>\nlemma Right_Coset_memI [intro]:\n  \"h \\<in> H \\<Longrightarrow> h \\<cdot> x \\<in> H |\\<cdot> x\"\n  unfolding Right_Coset_def by blast\n\ntext \\<open>p 52, l 20\\<close>\nlemma Right_Coset_memE [elim]:\n  \"\\<lbrakk> a \\<in> H |\\<cdot> x; \\<And>h. \\<lbrakk> h \\<in> H; a = h \\<cdot> x \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  unfolding Right_Coset_def by blast\n\ntext \\<open>p 53, ll 8--9\\<close>\nlemma Left_Coset_memI [intro]:\n  \"h \\<in> H \\<Longrightarrow> x \\<cdot> h \\<in> x \\<cdot>| H\"\n  unfolding Left_Coset_def by blast\n\ntext \\<open>p 53, ll 8--9\\<close>\nlemma Left_Coset_memE [elim]:\n  \"\\<lbrakk> a \\<in> x \\<cdot>| H; \\<And>h. \\<lbrakk> h \\<in> H; a = x \\<cdot> h \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  unfolding Left_Coset_def by blast\n\nend (* coset_notation *)\n\ntext \\<open>p 52, l 12\\<close>\nlocale subgroup_of_group = subgroup H G \"(\\<cdot>)\" \\<one> + coset_notation \"(\\<cdot>)\" + group G \"(\\<cdot>)\" \\<one>\n  for H and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\nbegin\n\ntext \\<open>p 52, ll 12--14\\<close>\ninterpretation left: left_translations_of_group ..\ninterpretation right: right_translations_of_group ..\n\ntext \\<open>\n  @{term \"left.translation ` H\"} denotes Jacobson's @{text \"H\\<^sub>L(G)\"} and\n  @{term \"left.translation ` G\"} denotes Jacobson's @{text \"G\\<^sub>L\"}.\n\\<close>\n\ntext \\<open>p 52, ll 16--18\\<close>\ntheorem left_translations_of_subgroup_are_transformation_group [intro]:\n  \"transformation_group (left.translation ` H) G\"\nproof -\n  have \"subgroup (left.translation ` H) (left.translation ` G) (compose G) (identity G)\"\n    by (rule left.image_subgroup) unfold_locales\n  also have \"subgroup (left.translation ` G) left.transformation.Sym (compose G) (identity G)\" ..\n  finally interpret right_coset: subgroup \"left.translation ` H\" left.transformation.Sym \"compose G\" \"identity G\" .\n  show ?thesis ..\nqed\n\ntext \\<open>p 52, l 18\\<close>\ninterpretation transformation_group \"left.translation ` H\" G ..\n\ntext \\<open>p 52, ll 19--20\\<close>\ntheorem Right_Coset_is_orbit:\n  \"x \\<in> G \\<Longrightarrow> H |\\<cdot> x = orbit.Class x\"\n  using left.translation_apply by (auto simp: orbit_equality Right_Coset_def) (metis imageI sub)\n\ntext \\<open>p 52, ll 24--25\\<close>\ntheorem Right_Coset_Union:\n  \"(\\<Union>x\\<in>G. H |\\<cdot> x) = G\"\n  by (simp add: Right_Coset_is_orbit)\n\ntext \\<open>p 52, l 26\\<close>\ntheorem Right_Coset_bij:\n  assumes G [simp]: \"x \\<in> G\" \"y \\<in> G\"\n  shows \"bij_betw (inverse x \\<cdot> y)\\<^sub>R (H |\\<cdot> x) (H |\\<cdot> y)\"\nproof (rule bij_betw_imageI)\n  show \"inj_on (inverse x \\<cdot> y)\\<^sub>R (H |\\<cdot> x)\"\n    by (fastforce intro: inj_onI simp add: Right_Coset_is_orbit right.translation_apply orbit.block_closed)\nnext\n  show \"(inverse x \\<cdot> y)\\<^sub>R ` (H |\\<cdot> x) = H |\\<cdot> y\"\n    by (force simp add: right.translation_apply associative invertible_right_inverse2)\nqed\n\ntext \\<open>p 52, ll 25--26\\<close>\ntheorem Right_Cosets_cardinality:\n  \"\\<lbrakk> x \\<in> G; y \\<in> G \\<rbrakk> \\<Longrightarrow> card (H |\\<cdot> x) = card (H |\\<cdot> y)\"\n  by (fast intro: bij_betw_same_card Right_Coset_bij)\n\ntext \\<open>p 52, l 27\\<close>\ntheorem Right_Coset_unit:\n  \"H |\\<cdot> \\<one> = H\"\n  by (force simp add: Right_Coset_def)\n\ntext \\<open>p 52, l 27\\<close>\ntheorem Right_Coset_cardinality:\n  \"x \\<in> G \\<Longrightarrow> card (H |\\<cdot> x) = card H\"\n  using Right_Coset_unit Right_Cosets_cardinality unit_closed by presburger\n\ntext \\<open>p 52, ll 31--32\\<close>\ndefinition \"index = card orbit.Partition\"\n\ntext \\<open>Theorem 1.5\\<close>\ntext \\<open>p 52, ll 33--35; p 53, ll 1--2\\<close>\ntheorem lagrange:\n  \"finite G \\<Longrightarrow> card G = card H * index\"\n  unfolding index_def\n  apply (subst card_partition)\n      apply (auto simp: finite_UnionD orbit.complete orbit.disjoint)\n  apply (metis Right_Coset_cardinality Right_Coset_is_orbit orbit.Block_self orbit.element_exists)\n  done\n\nend (* subgroup_of_group *)\n\ntext \\<open>Left cosets\\<close>\n\ncontext subgroup begin\n\ntext \\<open>p 31, ll 11--12\\<close>\nlemma image_of_inverse [intro, simp]:\n  \"x \\<in> G \\<Longrightarrow> x \\<in> inverse ` G\"\n  by (metis image_eqI sub.invertible sub.invertible_inverse_closed sub.invertible_inverse_inverse subgroup_inverse_equality)\n\nend (* subgroup *)\n\ncontext group begin\n\n(* Does Jacobson show this somewhere? *)\ntext \\<open>p 53, ll 6--7\\<close>\nlemma inverse_subgroupI:\n  assumes sub: \"subgroup H G (\\<cdot>) \\<one>\"\n  shows \"subgroup (inverse ` H) G (\\<cdot>) \\<one>\"\nproof -\n  from sub interpret subgroup H G \"(\\<cdot>)\" \\<one> .\n  interpret inv: monoid \"inverse ` H\" \"(\\<cdot>)\" \\<one>\n    by unfold_locales (auto simp del: subgroup_inverse_equality)\n  interpret inv: group \"inverse ` H\" \"(\\<cdot>)\" \\<one>\n    by unfold_locales (force simp del: subgroup_inverse_equality)\n  show ?thesis\n    by unfold_locales (auto simp del: subgroup_inverse_equality)\nqed\n\ntext \\<open>p 53, ll 6--7\\<close>\nlemma inverse_subgroupD:\n  assumes sub: \"subgroup (inverse ` H) G (\\<cdot>) \\<one>\"\n    and inv: \"H \\<subseteq> Units\"\n  shows \"subgroup H G (\\<cdot>) \\<one>\"\nproof -\n  from sub have \"subgroup (inverse ` inverse ` H) G (\\<cdot>) \\<one>\" by (rule inverse_subgroupI)\n  moreover from inv [THEN subsetD, simplified Units_def] have \"inverse ` inverse ` H = H\"\n    by (simp cong: image_cong add: image_comp)\n  ultimately show ?thesis by simp\nqed\n\nend (* group *)\n\ncontext subgroup_of_group begin\n\ntext \\<open>p 53, l 6\\<close>\ninterpretation right_translations_of_group ..\n\ntext \\<open>\n  @{term \"translation ` H\"} denotes Jacobson's @{text \"H\\<^sub>R(G)\"} and\n  @{term \"Translations\"} denotes Jacobson's @{text \"G\\<^sub>R\"}.\n\\<close>\n\ntext \\<open>p 53, ll 6--7\\<close>\ntheorem right_translations_of_subgroup_are_transformation_group [intro]:\n  \"transformation_group (translation ` H) G\"\nproof -\n  have \"subgroup ((\\<lambda>a\\<in>G. transformation.symmetric.inverse (a)\\<^sub>R) ` H) Translations (compose G) (identity G)\"\n    by (rule image_subgroup) unfold_locales\n  also have \"subgroup Translations transformation.Sym (compose G) (identity G)\" ..\n  finally interpret left_coset: subgroup \"translation ` H\" transformation.Sym \"compose G\" \"identity G\"\n    by (auto intro: transformation.symmetric.inverse_subgroupD cong: image_cong\n      simp: image_image transformation.symmetric.Units_def simp del: translation_unit_eq)\n  show ?thesis ..\nqed\n\ntext \\<open>p 53, ll 6--7\\<close>\ninterpretation transformation_group \"translation ` H\" G ..\n\ntext \\<open>Equation 23 for left cosets\\<close>\ntext \\<open>p 53, ll 7--8\\<close>\ntheorem Left_Coset_is_orbit:\n  \"x \\<in> G \\<Longrightarrow> x \\<cdot>| H = orbit.Class x\"\n  using translation_apply\n  by (auto simp: orbit_equality Left_Coset_def) (metis imageI sub)\n\nend (* subgroup_of_group *)\n\n\nsubsection \\<open>Congruences.  Quotient Monoids and Groups\\<close>\n\ntext \\<open>Def 1.4\\<close>\ntext \\<open>p 54, ll 19--22\\<close>\nlocale monoid_congruence = monoid + equivalence where S = M +\n  assumes cong: \"\\<lbrakk> (a, a') \\<in> E; (b, b') \\<in> E \\<rbrakk> \\<Longrightarrow> (a \\<cdot> b, a' \\<cdot> b') \\<in> E\"\nbegin\n\ntext \\<open>p 54, ll 26--28\\<close>\ntheorem Class_cong:\n  \"\\<lbrakk> Class a = Class a'; Class b = Class b'; a \\<in> M; a' \\<in> M; b \\<in> M; b' \\<in> M \\<rbrakk> \\<Longrightarrow> Class (a \\<cdot> b) = Class (a' \\<cdot> b')\"\n  by (simp add: Class_equivalence cong)\n\ntext \\<open>p 54, ll 28--30\\<close>\ndefinition quotient_composition (infixl \"[\\<cdot>]\" 70)\n  where \"quotient_composition = (\\<lambda>A \\<in> M / E. \\<lambda>B \\<in> M / E. THE C. \\<exists>a \\<in> A. \\<exists>b \\<in> B. C = Class (a \\<cdot> b))\"\n\ntext \\<open>p 54, ll 28--30\\<close>\ntheorem Class_commutes_with_composition:\n  \"\\<lbrakk> a \\<in> M; b \\<in> M \\<rbrakk> \\<Longrightarrow> Class a [\\<cdot>] Class b = Class (a \\<cdot> b)\"\n  by (auto simp: quotient_composition_def intro: Class_cong [OF Class_eq Class_eq] del: equalityI)\n\ntext \\<open>p 54, ll 30--31\\<close>\ntheorem quotient_composition_closed [intro, simp]:\n  \"\\<lbrakk> A \\<in> M / E; B \\<in> M / E \\<rbrakk> \\<Longrightarrow> A [\\<cdot>] B \\<in> M / E\"\n  by (erule quotient_ClassE)+ (simp add: Class_commutes_with_composition)\n\ntext \\<open>p 54, l 32; p 55, ll 1--3\\<close>\nsublocale quotient: monoid \"M / E\" \"([\\<cdot>])\" \"Class \\<one>\"\n  by unfold_locales (auto simp: Class_commutes_with_composition associative elim!: quotient_ClassE)\n\nend (* monoid_congruence *)\n\ntext \\<open>p 55, ll 16--17\\<close>\nlocale group_congruence = group + monoid_congruence where M = G begin\n\ntext \\<open>p 55, ll 16--17\\<close>\nnotation quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_right_inverse:\n  \"a \\<in> G \\<Longrightarrow> Class a [\\<cdot>] Class (inverse a) = Class \\<one>\"\n  by (simp add: Class_commutes_with_composition)\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_left_inverse:\n  \"a \\<in> G \\<Longrightarrow> Class (inverse a) [\\<cdot>] Class a = Class \\<one>\"\n  by (simp add: Class_commutes_with_composition)\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_invertible:\n  \"a \\<in> G \\<Longrightarrow> quotient.invertible (Class a)\"\n  by (blast intro!: Class_right_inverse Class_left_inverse)+\n\ntext \\<open>p 55, l 18\\<close>\ntheorem Class_commutes_with_inverse:\n  \"a \\<in> G \\<Longrightarrow> quotient.inverse (Class a) = Class (inverse a)\"\n  by (rule quotient.inverse_equality) (auto simp: Class_right_inverse Class_left_inverse)\n\ntext \\<open>p 55, l 17\\<close>\nsublocale quotient: group \"G / E\" \"([\\<cdot>])\" \"Class \\<one>\"\n  by unfold_locales (metis Block_self Class_invertible element_exists)\n\nend (* group_congruence *)\n\ntext \\<open>Def 1.5\\<close>\ntext \\<open>p 55, ll 22--25\\<close>\nlocale normal_subgroup =\n  subgroup_of_group K G \"(\\<cdot>)\" \\<one> for K and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\") +\n  assumes normal: \"\\<lbrakk> g \\<in> G; k \\<in> K \\<rbrakk> \\<Longrightarrow> inverse g \\<cdot> k \\<cdot> g \\<in> K\"\n\ntext \\<open>Lemmas from the proof of Thm 1.6\\<close>\n\ncontext subgroup_of_group begin\n\ntext \\<open>We use @{term H} for @{term K}.\\<close>\ntext \\<open>p 56, ll 14--16\\<close>\ntheorem Left_equals_Right_coset_implies_normality:\n  assumes [simp]: \"\\<And>g. g \\<in> G \\<Longrightarrow> g \\<cdot>| H = H |\\<cdot> g\"\n  shows \"normal_subgroup H G (\\<cdot>) \\<one>\"\nproof\n  fix g k\n  assume [simp]: \"g \\<in> G\" \"k \\<in> H\"\n  have \"k \\<cdot> g \\<in> g \\<cdot>| H\" by auto\n  then obtain k' where \"k \\<cdot> g = g \\<cdot> k'\" and \"k' \\<in> H\" by blast\n  then show \"inverse g \\<cdot> k \\<cdot> g \\<in> H\" by (simp add: associative invertible_left_inverse2)\nqed\n\nend (* subgroup_of_group *)\n\ntext \\<open>Thm 1.6, first part\\<close>\n\ncontext group_congruence begin\n\ntext \\<open>Jacobson's $K$\\<close>\ntext \\<open>p 56, l 29\\<close>\ndefinition \"Normal = Class \\<one>\"\n\ntext \\<open>p 56, ll 3--6\\<close>\ninterpretation subgroup \"Normal\" G \"(\\<cdot>)\" \\<one>\n  unfolding Normal_def\nproof (rule subgroupI)\n  fix k1 and k2\n  assume K: \"k1 \\<in> Class \\<one>\" \"k2 \\<in> Class \\<one>\"\n  then have \"k1 \\<cdot> k2 \\<in> Class (k1 \\<cdot> k2)\" by blast\n  also have \"\\<dots> = Class k1 [\\<cdot>] Class k2\" using K by (auto simp add: Class_commutes_with_composition Class_closed)\n  also have \"\\<dots> = Class \\<one> [\\<cdot>] Class \\<one>\" using K by (metis ClassD Class_eq unit_closed)\n  also have \"\\<dots> = Class \\<one>\" by simp\n  finally show \"k1 \\<cdot> k2 \\<in> Class \\<one>\" .\nnext\n  fix k\n  assume K: \"k \\<in> Class \\<one>\"\n  then have \"inverse k \\<in> Class (inverse k)\" by blast\n  also have \"\\<dots> = quotient.inverse (Class k)\" using Class_commutes_with_inverse K by blast\n  also have \"\\<dots> = quotient.inverse (Class \\<one>)\" using Block_self K by auto\n  also have \"\\<dots> = Class \\<one>\" using quotient.inverse_unit by blast\n  finally show \"inverse k \\<in> Class \\<one>\" .\nqed auto\n\ntext \\<open>Coset notation\\<close>\ntext \\<open>p 56, ll 5--6\\<close>\ninterpretation subgroup_of_group \"Normal\" G \"(\\<cdot>)\" \\<one> ..\n\ntext \\<open>Equation 25 for right cosets\\<close>\ntext \\<open>p 55, ll 29--30; p 56, ll 6--11\\<close>\ntheorem Right_Coset_Class_unit:\n  assumes g: \"g \\<in> G\" shows \"Normal |\\<cdot> g = Class g\"\n  unfolding Normal_def\nproof auto\n  fix a  \\<comment> \\<open>ll 6--8\\<close>\n  assume a: \"a \\<in> Class g\"\n  from a g have \"a \\<cdot> inverse g \\<in> Class (a \\<cdot> inverse g)\" by blast\n  also from a g have \"\\<dots> = Class a [\\<cdot>] Class (inverse g)\"\n    by (simp add: Class_commutes_with_composition block_closed)\n  also from a g have \"\\<dots> = Class g [\\<cdot>] quotient.inverse (Class g)\"\n    using Block_self Class_commutes_with_inverse by auto\n  also from g have \"\\<dots> = Class \\<one>\" by simp\n  finally show \"a \\<in> Class \\<one> |\\<cdot> g\"\n    unfolding Right_Coset_def\n    by simp (metis Class_closed a associative g inverse_equality invertible invertible_def right_unit) \nnext\n  fix a  \\<comment> \\<open>ll 8--9\\<close>\n  assume a: \"a \\<in> Class \\<one> |\\<cdot> g\"\n  then obtain k where eq: \"a = k \\<cdot> g\" and k: \"k \\<in> Class \\<one>\" by blast\n  with g have \"Class a = Class k [\\<cdot>] Class g\" using Class_commutes_with_composition by auto\n  also from k have \"\\<dots> = Class \\<one> [\\<cdot>] Class g\" using Block_self by auto\n  also from g have \"\\<dots> = Class g\" by simp\n  finally show \"a \\<in> Class g\" using g eq k composition_closed quotient.unit_closed by blast\nqed\n\ntext \\<open>Equation 25 for left cosets\\<close>\ntext \\<open>p 55, ll 29--30; p 56, ll 6--11\\<close>\ntheorem Left_Coset_Class_unit:\n  assumes g: \"g \\<in> G\" shows \"g \\<cdot>| Normal = Class g\"\n  unfolding Normal_def\nproof auto\n  fix a  \\<comment> \\<open>ll 6--8\\<close>\n  assume a: \"a \\<in> Class g\"\n  from a g have \"inverse g \\<cdot> a \\<in> Class (inverse g \\<cdot> a)\" by blast\n  also from a g have \"\\<dots> = Class (inverse g) [\\<cdot>] Class a\"\n    by (simp add: Class_commutes_with_composition block_closed)\n  also from a g have \"\\<dots> = quotient.inverse (Class g) [\\<cdot>] Class g\"\n    using Block_self Class_commutes_with_inverse by auto\n  also from g have \"\\<dots> = Class \\<one>\" by simp\n  finally show \"a \\<in> g \\<cdot>| Class \\<one>\"\n    unfolding Left_Coset_def\n    by simp (metis Class_closed a associative g inverse_equality invertible invertible_def right_unit) \nnext\n  fix a  \\<comment> \\<open>ll 8--9, ``the same thing holds''\\<close>\n  assume a: \"a \\<in> g \\<cdot>| Class \\<one>\"\n  then obtain k where eq: \"a = g \\<cdot> k\" and k: \"k \\<in> Class \\<one>\" by blast\n  with g have \"Class a = Class g [\\<cdot>] Class k\" using Class_commutes_with_composition by auto\n  also from k have \"\\<dots> = Class g [\\<cdot>] Class \\<one>\" using Block_self by auto\n  also from g have \"\\<dots> = Class g\" by simp\n  finally show \"a \\<in> Class g\" using g eq k composition_closed quotient.unit_closed by blast\nqed\n\ntext \\<open>Thm 1.6, statement of first part\\<close>\ntext \\<open>p 55, ll 28--29; p 56, ll 12--16\\<close>\ntheorem Class_unit_is_normal:\n  \"normal_subgroup Normal G (\\<cdot>) \\<one>\"\nproof -\n  {\n    fix g\n    assume \"g \\<in> G\"\n    then have \"g \\<cdot>| Normal = Normal |\\<cdot> g\" by (simp add: Right_Coset_Class_unit Left_Coset_Class_unit)\n  }\n  then show ?thesis by (rule Left_equals_Right_coset_implies_normality)\nqed\n\nsublocale normal: normal_subgroup Normal G \"(\\<cdot>)\" \\<one>\n  by (fact Class_unit_is_normal)\n\nend (* group_congruence *)\n\ncontext normal_subgroup begin\n\ntext \\<open>p 56, ll 16--19\\<close>\ntheorem Left_equals_Right_coset:\n  \"g \\<in> G \\<Longrightarrow> g \\<cdot>| K = K |\\<cdot> g\"\nproof\n  assume [simp]: \"g \\<in> G\"\n  show \"K |\\<cdot> g \\<subseteq> g \\<cdot>| K\"\n  proof\n    fix x\n    assume x: \"x \\<in> K |\\<cdot> g\"\n    then obtain k where \"x = k \\<cdot> g\" and [simp]: \"k \\<in> K\" by (auto simp add: Right_Coset_def)\n    then have \"x = g \\<cdot> (inverse g \\<cdot> k \\<cdot> g)\" by (simp add: associative invertible_right_inverse2)\n    also from normal have \"\\<dots> \\<in> g \\<cdot>| K\" by (auto simp add: Left_Coset_def)\n    finally show \"x \\<in> g \\<cdot>| K\" .\n  qed\nnext\n  assume [simp]: \"g \\<in> G\"\n  show \"g \\<cdot>| K \\<subseteq> K |\\<cdot> g\"\n  proof\n    fix x\n    assume x: \"x \\<in> g \\<cdot>| K\"\n    then obtain k where \"x = g \\<cdot> k\" and [simp]: \"k \\<in> K\" by (auto simp add: Left_Coset_def)\n    then have \"x = (inverse (inverse g) \\<cdot> k \\<cdot> inverse g) \\<cdot> g\" by (simp add: associative del: invertible_right_inverse)\n    also from normal [where g = \"inverse g\"] have \"\\<dots> \\<in> K |\\<cdot> g\" by (auto simp add: Right_Coset_def)\n    finally show \"x \\<in> K |\\<cdot> g\" .\n  qed\nqed\n\ntext \\<open>Thm 1.6, second part\\<close>\n\ntext \\<open>p 55, ll 31--32; p 56, ll 20--21\\<close>\ndefinition \"Congruence = {(a, b). a \\<in> G \\<and> b \\<in> G \\<and> inverse a \\<cdot> b \\<in> K}\"\n\ntext \\<open>p 56, ll 21--22\\<close>\ninterpretation right_translations_of_group ..\n\ntext \\<open>p 56, ll 21--22\\<close>\ninterpretation transformation_group \"translation ` K\" G rewrites \"Orbit_Relation = Congruence\"\nproof -\n  interpret transformation_group \"translation ` K\" G ..\n  show \"Orbit_Relation = Congruence\"\n    unfolding Orbit_Relation_def Congruence_def\n    by (force simp: invertible_left_inverse2 invertible_right_inverse2 translation_apply simp del: restrict_apply)\nqed rule\n\ntext \\<open>p 56, ll 20--21\\<close>\nlemma CongruenceI: \"\\<lbrakk> a = b \\<cdot> k; a \\<in> G; b \\<in> G; k \\<in> K \\<rbrakk> \\<Longrightarrow> (a, b) \\<in> Congruence\"\n  by (clarsimp simp: Congruence_def associative inverse_composition_commute)\n\ntext \\<open>p 56, ll 20--21\\<close>\nlemma CongruenceD: \"(a, b) \\<in> Congruence \\<Longrightarrow> \\<exists>k\\<in>K. a = b \\<cdot> k\"\n  by (drule orbit.symmetric) (force simp: Congruence_def invertible_right_inverse2)\n\ntext \\<open>\n  ``We showed in the last section that the relation we are considering is an equivalence relation in\n  @{term G} for any subgroup @{term K} of @{term G}.  We now proceed to show that normality of @{term K}\n  ensures that [...] $a \\equiv b \\pmod{K}$ is a congruence.''\n\\<close>\ntext \\<open>p 55, ll 30--32; p 56, ll 1, 22--28\\<close>\nsublocale group_congruence where E = Congruence rewrites \"Normal = K\"\nproof -\n  show \"group_congruence G (\\<cdot>) \\<one> Congruence\"\n  proof unfold_locales\n    note CongruenceI [intro] CongruenceD [dest]\n    fix a g b h\n    assume 1: \"(a, g) \\<in> Congruence\" and 2: \"(b, h) \\<in> Congruence\"\n    then have G: \"a \\<in> G\" \"g \\<in> G\" \"b \\<in> G\" \"h \\<in> G\" unfolding Congruence_def by clarify+\n    from 1 obtain k1 where a: \"a = g \\<cdot> k1\" and k1: \"k1 \\<in> K\" by blast\n    from 2 obtain k2 where b: \"b = h \\<cdot> k2\" and k2: \"k2 \\<in> K\" by blast\n    from G Left_equals_Right_coset have \"K |\\<cdot> h = h \\<cdot>| K\" by blast\n    with k1 obtain k3 where c: \"k1 \\<cdot> h = h \\<cdot> k3\" and k3: \"k3 \\<in> K\"\n      unfolding Left_Coset_def Right_Coset_def by blast\n    from G k1 k2 a b have \"a \\<cdot> b = g \\<cdot> k1 \\<cdot> h \\<cdot> k2\" by (simp add: associative)\n    also from G k1 k3 c have \"\\<dots> = g \\<cdot> h \\<cdot> k3 \\<cdot> k2\" by (simp add: associative)\n    also have \"\\<dots> = (g \\<cdot> h) \\<cdot> (k3 \\<cdot> k2)\" using G k2 k3 by (simp add: associative)\n    finally show \"(a \\<cdot> b, g \\<cdot> h) \\<in> Congruence\" using G k2 k3 by blast\n  qed\n  then interpret group_congruence where E = Congruence .\n  show \"Normal = K\"\n    unfolding Normal_def orbit.Class_def unfolding Congruence_def\n    using invertible_inverse_inverse submonoid_inverse_closed by fastforce \nqed\n\nend (* normal_subgroup *)  (* deletes translations and orbits, recovers Class for congruence class *)\n\ncontext group begin\n\ntext \\<open>Pulled out of @{locale normal_subgroup} to achieve standard notation.\\<close>\ntext \\<open>p 56, ll 31--32\\<close>\nabbreviation Factor_Group (infixl \"'/'/\" 75)\n  where \"S // K \\<equiv> S / (normal_subgroup.Congruence K G (\\<cdot>) \\<one>)\"\n\nend (* group *)\n\ncontext normal_subgroup begin\n\ntext \\<open>p 56, ll 28--29\\<close>\ntheorem Class_unit_normal_subgroup: \"Class \\<one> = K\"\n  unfolding Class_def unfolding Congruence_def\n  using invertible_inverse_inverse submonoid_inverse_closed by fastforce\n\ntext \\<open>p 56, ll 1--2; p 56, l 29\\<close>\ntheorem Class_is_Left_Coset:\n  \"g \\<in> G \\<Longrightarrow> Class g = g \\<cdot>| K\"\n  using Left_Coset_Class_unit Class_unit_normal_subgroup by simp\n\ntext \\<open>p 56, l 29\\<close>\nlemma Left_CosetE: \"\\<lbrakk> A \\<in> G // K; \\<And>a. a \\<in> G \\<Longrightarrow> P (a \\<cdot>| K) \\<rbrakk> \\<Longrightarrow> P A\"\n  by (metis Class_is_Left_Coset quotient_ClassE)\n\ntext \\<open>Equation 26\\<close>\ntext \\<open>p 56, ll 32--34\\<close>\ntheorem factor_composition [simp]:\n  \"\\<lbrakk> g \\<in> G; h \\<in> G \\<rbrakk> \\<Longrightarrow> (g \\<cdot>| K) [\\<cdot>] (h \\<cdot>| K) = g \\<cdot> h \\<cdot>| K\"\n  using Class_commutes_with_composition Class_is_Left_Coset by auto\n\ntext \\<open>p 56, l 35\\<close>\ntheorem factor_unit:\n  \"K = \\<one> \\<cdot>| K\"\n  using Class_is_Left_Coset Class_unit_normal_subgroup by blast\n\ntext \\<open>p 56, l 35\\<close>\ntheorem factor_inverse [simp]:\n  \"g \\<in> G \\<Longrightarrow> quotient.inverse (g \\<cdot>| K) = (inverse g \\<cdot>| K)\"\n  using Class_commutes_with_inverse Class_is_Left_Coset by auto\n\nend (* normal_subgroup *)\n\ntext \\<open>p 57, ll 4--5\\<close>\nlocale subgroup_of_abelian_group = subgroup_of_group H G \"(\\<cdot>)\" \\<one> + abelian_group G \"(\\<cdot>)\" \\<one>\n  for H and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n\ntext \\<open>p 57, ll 4--5\\<close>\nsublocale subgroup_of_abelian_group \\<subseteq> normal_subgroup H G \"(\\<cdot>)\" \\<one>\n  using commutative invertible_right_inverse2 by unfold_locales auto\n\n\nsubsection \\<open>Homomorphims\\<close>\n\ntext \\<open>Def 1.6\\<close>\ntext \\<open>p 58, l 33; p 59, ll 1--2\\<close>\nlocale monoid_homomorphism =\n  map \\<eta> M M'+  source: monoid M \"(\\<cdot>)\" \\<one> + target: monoid M' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and M and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and M' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\") +\n  assumes commutes_with_composition: \"\\<lbrakk> x \\<in> M; y \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> (x \\<cdot> y) = \\<eta> x \\<cdot>' \\<eta> y\"\n    and commutes_with_unit: \"\\<eta> \\<one> = \\<one>'\"\nbegin\n\ntext \\<open>Jacobson notes that @{thm [source] commutes_with_unit} is not necessary for groups, but doesn't make use of that later.\\<close>\n\ntext \\<open>p 58, l 33; p 59, ll 1--2\\<close>\nnotation source.invertible (\"invertible _\" [100] 100)\nnotation source.inverse (\"inverse _\" [100] 100)\nnotation target.invertible (\"invertible'' _\" [100] 100)\nnotation target.inverse (\"inverse'' _\" [100] 100)\n\nend (* monoid_homomorphism *)\n\ntext \\<open>p 59, ll 29--30\\<close>\nlocale monoid_epimorphism = monoid_homomorphism + surjective_map \\<eta> M M'\n\ntext \\<open>p 59, l 30\\<close>\nlocale monoid_monomorphism = monoid_homomorphism + injective_map \\<eta> M M'\n\ntext \\<open>p 59, ll 30--31\\<close>\nsublocale monoid_isomorphism \\<subseteq> monoid_epimorphism\n  by unfold_locales (auto simp: commutes_with_composition commutes_with_unit)\n\ntext \\<open>p 59, ll 30--31\\<close>\nsublocale monoid_isomorphism \\<subseteq> monoid_monomorphism\n  by unfold_locales (auto simp: commutes_with_composition commutes_with_unit)\n\ncontext monoid_homomorphism begin\n\ntext \\<open>p 59, ll 33--34\\<close>\ntheorem invertible_image_lemma:\n  assumes \"invertible a\" \"a \\<in> M\"\n  shows \"\\<eta> a \\<cdot>' \\<eta> (inverse a) = \\<one>'\" and \"\\<eta> (inverse a) \\<cdot>' \\<eta> a = \\<one>'\"\n  using assms commutes_with_composition commutes_with_unit source.inverse_equality\n  by auto (metis source.invertible_inverse_closed source.invertible_left_inverse)\n\ntext \\<open>p 59, l 34; p 60, l 1\\<close>\ntheorem invertible_target_invertible [intro, simp]:\n  \"\\<lbrakk> invertible a; a \\<in> M \\<rbrakk> \\<Longrightarrow> invertible' (\\<eta> a)\"\n  using invertible_image_lemma by blast\n\ntext \\<open>p 60, l 1\\<close>\ntheorem invertible_commutes_with_inverse:\n  \"\\<lbrakk> invertible a; a \\<in> M \\<rbrakk> \\<Longrightarrow> \\<eta> (inverse a) = inverse' (\\<eta> a)\"\n  using invertible_image_lemma target.inverse_equality by fastforce\n\nend (* monoid_homomorphism *)\n\ntext \\<open>p 60, ll 32--34; p 61, l 1\\<close>\nsublocale monoid_congruence \\<subseteq> natural: monoid_homomorphism Class M \"(\\<cdot>)\" \\<one> \"M / E\" \"([\\<cdot>])\" \"Class \\<one>\"\n  by unfold_locales (auto simp: PiE_I Class_commutes_with_composition)\n\ntext \\<open>Fundamental Theorem of Homomorphisms of Monoids\\<close>\n\ntext \\<open>p 61, ll 5, 14--16\\<close>\nsublocale monoid_homomorphism \\<subseteq> image: submonoid \"\\<eta> ` M\" M' \"(\\<cdot>')\" \"\\<one>'\"\n  by unfold_locales (auto simp: commutes_with_composition [symmetric] commutes_with_unit [symmetric])\n\ntext \\<open>p 61, l 4\\<close>\nlocale monoid_homomorphism_fundamental = monoid_homomorphism begin\n\ntext \\<open>p 61, ll 17--18\\<close>\nsublocale fiber_relation \\<eta> M M' ..\nnotation Fiber_Relation (\"E'(_')\")\n\ntext \\<open>p 61, ll 6--7, 18--20\\<close>\nsublocale monoid_congruence where E = \"E(\\<eta>)\"\n  using Class_eq\n  by unfold_locales (rule Class_equivalence [THEN iffD1],\n    auto simp: left_closed right_closed commutes_with_composition Fiber_equality)\n\ntext \\<open>p 61, ll 7--9\\<close>\ntext \\<open>\n  @{term induced} denotes Jacobson's $\\bar{\\eta}$.  We have the commutativity of the diagram, where\n  @{term induced} is unique: @{thm [display] factorization} @{thm [display] uniqueness}.\n\\<close>\n\ntext \\<open>p 61, l 20\\<close>\nnotation quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>p 61, ll 7--8, 22--25\\<close>\nsublocale induced: monoid_homomorphism induced \"M / E(\\<eta>)\" \"([\\<cdot>])\" \"Class \\<one>\" \"M'\" \"(\\<cdot>')\" \"\\<one>'\"\n  apply unfold_locales\n    apply (auto simp: commutes_with_unit)\n  apply (fastforce simp: commutes_with_composition commutes_with_unit Class_commutes_with_composition)\n  done\n\ntext \\<open>p 61, ll 9, 26\\<close>\nsublocale natural: monoid_epimorphism Class M \"(\\<cdot>)\" \\<one> \"M / E(\\<eta>)\" \"([\\<cdot>])\" \"Class \\<one>\" ..\n\ntext \\<open>p 61, ll 9, 26--27\\<close>\nsublocale induced: monoid_monomorphism induced \"M / E(\\<eta>)\" \"([\\<cdot>])\" \"Class \\<one>\" \"M'\" \"(\\<cdot>')\" \"\\<one>'\" ..\n\nend (* monoid_homomorphism_fundamental *)\n\ntext \\<open>p 62, ll 12--13\\<close>\nlocale group_homomorphism =\n  monoid_homomorphism \\<eta> G \"(\\<cdot>)\" \\<one> G' \"(\\<cdot>')\" \"\\<one>'\" +\n  source: group G \"(\\<cdot>)\" \\<one> + target: group G' \"(\\<cdot>')\" \"\\<one>'\"\n  for \\<eta> and G and composition (infixl \"\\<cdot>\" 70) and unit (\"\\<one>\")\n    and G' and composition' (infixl \"\\<cdot>''\" 70) and unit' (\"\\<one>''\")\nbegin\n\ntext \\<open>p 62, l 13\\<close>\nsublocale image: subgroup \"\\<eta> ` G\" G' \"(\\<cdot>')\" \"\\<one>'\"\n  using invertible_image_lemma by unfold_locales auto\n\ntext \\<open>p 62, ll 13--14\\<close>\ndefinition \"Ker = \\<eta> -` {\\<one>'} \\<inter> G\"\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_equality:\n  \"Ker = {a | a. a \\<in> G \\<and> \\<eta> a = \\<one>'}\"\n  unfolding Ker_def by auto\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_closed [intro, simp]:\n  \"a \\<in> Ker \\<Longrightarrow> a \\<in> G\"\n  unfolding Ker_def by simp\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_image [intro]: (* loops as a simprule *)\n  \"a \\<in> Ker \\<Longrightarrow> \\<eta> a = \\<one>'\"\n  unfolding Ker_def by simp\n\ntext \\<open>p 62, ll 13--14\\<close>\nlemma Ker_memI [intro]: (* loops as a simprule *)\n  \"\\<lbrakk> \\<eta> a = \\<one>'; a \\<in> G \\<rbrakk> \\<Longrightarrow> a \\<in> Ker\"\n  unfolding Ker_def by simp\n\ntext \\<open>p 62, ll 15--16\\<close>\nsublocale kernel: normal_subgroup Ker G\nproof -\n  interpret kernel: submonoid Ker G\n    unfolding Ker_def by unfold_locales (auto simp: commutes_with_composition commutes_with_unit)\n  interpret kernel: subgroup Ker G\n    by unfold_locales (force intro: source.invertible_right_inverse simp: Ker_image invertible_commutes_with_inverse)\n  show \"normal_subgroup Ker G (\\<cdot>) \\<one>\"\n    apply unfold_locales\n    unfolding Ker_def\n    by (auto simp: commutes_with_composition invertible_image_lemma(2))\nqed\n\ntext \\<open>p 62, ll 17--20\\<close>\ntheorem injective_iff_kernel_unit:\n  \"inj_on \\<eta> G \\<longleftrightarrow> Ker = {\\<one>}\"\nproof (rule Not_eq_iff [THEN iffD1, OF iffI])\n  assume \"Ker \\<noteq> {\\<one>}\"\n  then obtain b where b: \"b \\<in> Ker\" \"b \\<noteq> \\<one>\" by blast\n  then have \"\\<eta> b = \\<eta> \\<one>\" by (simp add: Ker_image)\n  with b show \"\\<not> inj_on \\<eta> G\"  by (meson inj_onD kernel.sub source.unit_closed)\nnext\n  assume \"\\<not> inj_on \\<eta> G\"\n  then obtain a b where \"a \\<noteq> b\" and ab: \"a \\<in> G\" \"b \\<in> G\" \"\\<eta> a = \\<eta> b\" by (meson inj_onI)\n  then have \"inverse a \\<cdot> b \\<noteq> \\<one>\" \"\\<eta> (inverse a \\<cdot> b) = \\<one>'\"\n    using ab source.invertible_right_inverse2\n    by force (metis ab commutes_with_composition invertible_image_lemma(2) source.invertible source.invertible_inverse_closed)\n  then have \"inverse a \\<cdot> b \\<in> Ker\" using Ker_memI ab by blast\n  then show \"Ker \\<noteq> {\\<one>}\" using \\<open>inverse a \\<cdot> b \\<noteq> \\<one>\\<close> by blast\nqed\n\nend (* group_homomorphism *)\n\ntext \\<open>p 62, l 24\\<close>\nlocale group_epimorphism = group_homomorphism + monoid_epimorphism \\<eta> G \"(\\<cdot>)\" \\<one> G' \"(\\<cdot>')\" \"\\<one>'\"\n\ntext \\<open>p 62, l 21\\<close>\nlocale normal_subgroup_in_kernel =\n  group_homomorphism + contained: normal_subgroup L G \"(\\<cdot>)\" \\<one> for L +\n  assumes subset: \"L \\<subseteq> Ker\"\nbegin\n\ntext \\<open>p 62, l 21\\<close>\nnotation contained.quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>\"homomorphism onto @{term \"G // L\"}\"\\<close>\ntext \\<open>p 62, ll 23--24\\<close>\nsublocale natural: group_epimorphism contained.Class G \"(\\<cdot>)\" \\<one> \"G // L\" \"([\\<cdot>])\" \"contained.Class \\<one>\" ..\n\ntext \\<open>p 62, ll 25--26\\<close>\ntheorem left_coset_equality:\n  assumes eq: \"a \\<cdot>| L = b \\<cdot>| L\" and [simp]: \"a \\<in> G\" and b: \"b \\<in> G\"\n  shows \"\\<eta> a = \\<eta> b\"\nproof -\n  obtain l where l: \"b = a \\<cdot> l\" \"l \\<in> L\"\n    by (metis b contained.Class_is_Left_Coset contained.Class_self eq kernel.Left_Coset_memE)\n  then have \"\\<eta> a = \\<eta> a \\<cdot>' \\<eta> l\" using Ker_image monoid_homomorphism.commutes_with_composition subset by auto\n  also have \"\\<dots> = \\<eta> b\" by (simp add: commutes_with_composition l)\n  finally show ?thesis .\nqed\n\ntext \\<open>$\\bar{\\eta}$\\<close>\ntext \\<open>p 62, ll 26--27\\<close>\ndefinition \"induced = (\\<lambda>A \\<in> G // L. THE b. \\<exists>a \\<in> G. a \\<cdot>| L = A \\<and> b = \\<eta> a)\"\n\ntext \\<open>p 62, ll 26--27\\<close>\nlemma induced_closed [intro, simp]:\n  assumes [simp]: \"A \\<in> G // L\" shows \"induced A \\<in> G'\"\nproof -\n  obtain a where a: \"a \\<in> G\" \"a \\<cdot>| L = A\" using contained.Class_is_Left_Coset contained.Partition_def assms by auto\n  have \"(THE b. \\<exists>a \\<in> G. a \\<cdot>| L = A \\<and> b = \\<eta> a) \\<in> G'\"\n    apply (rule theI2)\n    using a by (auto intro: left_coset_equality)\n  then show ?thesis unfolding induced_def by simp\nqed\n\ntext \\<open>p 62, ll 26--27\\<close>\nlemma induced_undefined [intro, simp]:\n  \"A \\<notin> G // L \\<Longrightarrow> induced A = undefined\"\n  unfolding induced_def by simp\n\ntext \\<open>p 62, ll 26--27\\<close>\ntheorem induced_left_coset_closed [intro, simp]:\n  \"a \\<in> G \\<Longrightarrow> induced (a \\<cdot>| L) \\<in> G'\"\n  using contained.Class_is_Left_Coset contained.Class_in_Partition by auto \n\ntext \\<open>p 62, ll 26--27\\<close>\ntheorem induced_left_coset_equality [simp]:\n  assumes [simp]: \"a \\<in> G\" shows \"induced (a \\<cdot>| L) = \\<eta> a\"\nproof -\n  have \"(THE b. \\<exists>a' \\<in> G. a' \\<cdot>| L = a \\<cdot>| L \\<and> b = \\<eta> a') = \\<eta> a\"\n    by (rule the_equality) (auto intro: left_coset_equality)\n  then show ?thesis unfolding induced_def\n    using contained.Class_is_Left_Coset contained.Class_in_Partition by auto \nqed\n\ntext \\<open>p 62, l 27\\<close>\ntheorem induced_Left_Coset_commutes_with_composition [simp]:\n  \"\\<lbrakk> a \\<in> G; b \\<in> G \\<rbrakk> \\<Longrightarrow> induced ((a \\<cdot>| L) [\\<cdot>] (b \\<cdot>| L)) = induced (a \\<cdot>| L) \\<cdot>' induced (b \\<cdot>| L)\"\n  by (simp add: commutes_with_composition)\n\ntext \\<open>p 62, ll 27--28\\<close>\ntheorem induced_group_homomorphism:\n  \"group_homomorphism induced (G // L) ([\\<cdot>]) (contained.Class \\<one>) G' (\\<cdot>') \\<one>'\"\n  apply unfold_locales\n    apply (auto elim!: contained.Left_CosetE simp: commutes_with_composition commutes_with_unit)\n  using contained.factor_unit induced_left_coset_equality apply (fastforce simp: contained.Class_unit_normal_subgroup)\n  done\n\ntext \\<open>p 62, l 28\\<close>\nsublocale induced: group_homomorphism induced \"G // L\" \"([\\<cdot>])\" \"contained.Class \\<one>\" G' \"(\\<cdot>')\" \"\\<one>'\"\n  by (fact induced_group_homomorphism)\n\ntext \\<open>p 62, ll 28--29\\<close>\ntheorem factorization_lemma: \"a \\<in> G \\<Longrightarrow> compose G induced contained.Class a = \\<eta> a\"\n  unfolding compose_def by (simp add: contained.Class_is_Left_Coset)\n\ntext \\<open>p 62, ll 29--30\\<close>\ntheorem factorization [simp]: \"compose G induced contained.Class = \\<eta>\"\n  by rule (simp add: compose_def contained.Class_is_Left_Coset map_undefined)\n\ntext \\<open>\n  Jacobson does not state the uniqueness of @{term induced} explicitly but he uses it later,\n  for rings, on p 107.\n\\<close>\ntext \\<open>p 62, l 30\\<close>\ntheorem uniqueness:\n  assumes map: \"\\<beta> \\<in> G // L \\<rightarrow>\\<^sub>E G'\"\n    and factorization: \"compose G \\<beta> contained.Class = \\<eta>\"\n  shows \"\\<beta> = induced\"\nproof\n  fix A\n  show \"\\<beta> A = induced A\"\n  proof (cases \"A \\<in> G // L\")\n    case True\n    then obtain a where [simp]: \"A = contained.Class a\" \"a \\<in> G\" by fast\n    then have \"\\<beta> (contained.Class a) = \\<eta> a\" by (metis compose_eq factorization)\n    also have \"\\<dots> = induced (contained.Class a)\" by (simp add: contained.Class_is_Left_Coset)\n    finally show ?thesis by simp\n  qed (simp add: induced_def PiE_arb [OF map])\nqed\n\ntext \\<open>p 62, l 31\\<close>\ntheorem induced_image:\n  \"induced ` (G // L) = \\<eta> ` G\"\n  by (metis factorization contained.natural.surjective surj_compose)\n\ntext \\<open>p 62, l 33\\<close>\ninterpretation L: normal_subgroup L Ker\n  by unfold_locales (auto simp: subset, metis kernel.sub kernel.subgroup_inverse_equality contained.normal)\n\ntext \\<open>p 62, ll 31--33\\<close>\ntheorem induced_kernel:\n  \"induced.Ker = Ker / L.Congruence\" (* Ker // L is apparently not the right thing *)\nproof -\n  have \"induced.Ker = { a \\<cdot>| L | a. a \\<in> G \\<and> a \\<in> Ker }\"\n    unfolding induced.Ker_equality\n    by simp (metis (opaque_lifting) contained.Class_is_Left_Coset Ker_image Ker_memI\n        induced_left_coset_equality contained.Class_in_Partition contained.representant_exists)\n  also have \"\\<dots> = Ker / L.Congruence\"\n    using L.Class_is_Left_Coset L.Class_in_Partition\n    by auto (metis L.Class_is_Left_Coset L.representant_exists kernel.sub)\n  finally show ?thesis .\nqed\n\ntext \\<open>p 62, ll 34--35\\<close>\ntheorem induced_inj_on:\n  \"inj_on induced (G // L) \\<longleftrightarrow> L = Ker\"\n  apply (simp add: induced.injective_iff_kernel_unit induced_kernel contained.Class_unit_normal_subgroup)\n  apply rule\n  using L.block_exists apply auto [1]\n  using L.Block_self L.Class_unit_normal_subgroup L.quotient.unit_closed L.representant_exists\n  apply auto\n  done\n\nend (* normal_subgroup_in_kernel *)\n\ntext \\<open>Fundamental Theorem of Homomorphisms of Groups\\<close>\n\ntext \\<open>p 63, l 1\\<close>\nlocale group_homomorphism_fundamental = group_homomorphism begin\n\ntext \\<open>p 63, l 1\\<close>\nnotation kernel.quotient_composition (infixl \"[\\<cdot>]\" 70)\n\ntext \\<open>p 63, l 1\\<close>\nsublocale normal_subgroup_in_kernel where L = Ker by unfold_locales rule\n\ntext \\<open>p 62, ll 36--37; p 63, l 1\\<close>\ntext \\<open>\n  @{term induced} denotes Jacobson's $\\bar{\\eta}$.  We have the commutativity of the diagram, where\n  @{term induced} is unique: @{thm [display] factorization} @{thm [display] uniqueness}\n\\<close>\n\nend (* group_homomorphism_fundamental *)\n\ntext \\<open>p 63, l 5\\<close>\nlocale group_isomorphism = group_homomorphism + bijective_map \\<eta> G G' begin\n\ntext \\<open>p 63, l 5\\<close>\nsublocale monoid_isomorphism \\<eta> G \"(\\<cdot>)\" \\<one> G' \"(\\<cdot>')\" \"\\<one>'\" \n  by unfold_locales (auto simp: commutes_with_composition)\n\ntext \\<open>p 63, l 6\\<close>\nlemma inverse_group_isomorphism:\n  \"group_isomorphism (restrict (inv_into G \\<eta>) G') G' (\\<cdot>') \\<one>' G (\\<cdot>) \\<one>\"\n  using commutes_with_composition commutes_with_unit surjective by unfold_locales auto\n\nend (* group_isomorphism *)\n\ntext \\<open>p 63, l 6\\<close>\ndefinition isomorphic_as_groups (infixl \"\\<cong>\\<^sub>G\" 50)\n  where \"\\<G> \\<cong>\\<^sub>G \\<G>' \\<longleftrightarrow> (let (G, composition, unit) = \\<G>; (G', composition', unit') = \\<G>' in\n  (\\<exists>\\<eta>. group_isomorphism \\<eta> G composition unit G' composition' unit'))\"\n\ntext \\<open>p 63, l 6\\<close>\nlemma isomorphic_as_groups_symmetric:\n  \"(G, composition, unit) \\<cong>\\<^sub>G (G', composition', unit') \\<Longrightarrow> (G', composition', unit') \\<cong>\\<^sub>G (G, composition, unit)\"\n  by (simp add: isomorphic_as_groups_def) (meson group_isomorphism.inverse_group_isomorphism)\n\ntext \\<open>p 63, l 1\\<close>\nsublocale group_isomorphism \\<subseteq> group_epimorphism ..\n\ntext \\<open>p 63, l 1\\<close>\nlocale group_epimorphism_fundamental = group_homomorphism_fundamental + group_epimorphism begin\n\ntext \\<open>p 63, ll 1--2\\<close>\ninterpretation image: group_homomorphism induced \"G // Ker\" \"([\\<cdot>])\" \"kernel.Class \\<one>\" \"(\\<eta> ` G)\" \"(\\<cdot>')\" \"\\<one>'\"\n  by (simp add: surjective group_homomorphism_fundamental.intro induced_group_homomorphism)\n\ntext \\<open>p 63, ll 1--2\\<close>\nsublocale image: group_isomorphism induced \"G // Ker\" \"([\\<cdot>])\" \"kernel.Class \\<one>\" \"(\\<eta> ` G)\" \"(\\<cdot>')\" \"\\<one>'\"\n  using induced_group_homomorphism\n  by unfold_locales (auto simp: bij_betw_def induced_image induced_inj_on induced.commutes_with_composition)\n\nend (* group_epimorphism_fundamental *)\n\ncontext group_homomorphism begin\n\ntext \\<open>p 63, ll 5--7\\<close>\ntheorem image_isomorphic_to_factor_group:\n  \"\\<exists>K composition unit. normal_subgroup K G (\\<cdot>) \\<one> \\<and> (\\<eta> ` G, (\\<cdot>'), \\<one>') \\<cong>\\<^sub>G (G // K, composition, unit)\"\nproof -\n  interpret image: group_epimorphism_fundamental where G' = \"\\<eta> ` G\"\n    by unfold_locales (auto simp: commutes_with_composition)\n  have \"group_isomorphism image.induced (G // Ker) ([\\<cdot>]) (kernel.Class \\<one>) (\\<eta> ` G) (\\<cdot>') \\<one>'\" ..\n  then have \"(\\<eta> ` G, (\\<cdot>'), \\<one>') \\<cong>\\<^sub>G (G // Ker, ([\\<cdot>]), kernel.Class \\<one>)\"\n    by (simp add: isomorphic_as_groups_def) (meson group_isomorphism.inverse_group_isomorphism)\n  moreover have \"normal_subgroup Ker G (\\<cdot>) \\<one>\" ..\n  ultimately show ?thesis by blast\nqed\n\nend (* group_homomorphism *)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Jacobson_Basic_Algebra/Group_Theory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898102301019, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7753924232226769}}
{"text": "theory Tangle_Relation\nimports  Main\nbegin\n\n\n\nlemma symmetry1: assumes \"symp R\" \nshows \"\\<forall>x y. (x, y) \\<in> {(x, y). R x y}\\<^sup>* \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\\<^sup>*\" \nproof-\nhave  \"R x y \\<longrightarrow>  R y x\" by (metis assms sympD)\nthen have \" (x, y) \\<in> {(x, y). R x y} \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\" by auto\nthen have 2:\"\\<forall> x y. (x, y) \\<in> {(x, y). R x y} \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\"\n by (metis (full_types) assms mem_Collect_eq split_conv sympE)\nthen have \"sym {(x, y). R x y}\" unfolding sym_def by auto\nthen have 3: \"sym (rtrancl {(x, y). R x y})\" using sym_rtrancl by auto\nthen show ?thesis by (metis symE)\nqed\n\nlemma symmetry2: assumes \"\\<forall>x y. (x, y) \\<in> {(x, y). R x y}\\<^sup>* \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\\<^sup>* \"\nshows \"symp R^**\" \nunfolding symp_def Enum.rtranclp_rtrancl_eq assms by (metis assms)\n\nlemma symmetry3: assumes \"symp R\" shows \"symp R^**\" using assms symmetry1 symmetry2 by metis\n\nlemma symm_trans: assumes \"symp R\" shows \"symp R^++\" by (metis assms rtranclpD symmetry3 symp_def tranclp_into_rtranclp)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Knot_Theory/Tangle_Relation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7749759996785477}}
{"text": "theory SetTheory1\nimports Main \nbegin \n\n\n\nlemma \"A = B \\<Longrightarrow> A \\<subseteq> B \\<and> B \\<subseteq> A\" \nproof (rule conjI)\n  assume \"A = B\"\n  thus \"A \\<subseteq> B\" by (rule equalityD1)\n next\n  assume \"A = B\"\n  thus \"B \\<subseteq> A\" by (rule equalityD2)\nqed\n\n    \nlemma helper : \" A \\<subset> B \\<and> B \\<subset> A  \\<Longrightarrow> A = B\" \nproof (rule subset_antisym) \n  assume a:\"A \\<subset> B \\<and> B \\<subset> A\"\n  hence b:\"A \\<subset> B\" ..\n  thus \"A \\<subseteq> B\"  by simp\nnext\n  assume \"A \\<subset> B \\<and> B \\<subset> A\"\n  hence \"B \\<subset> A\" ..\n  thus \"B \\<subseteq> A\" by simp\nqed\n       \nlemma \"A \\<subset> B \\<Longrightarrow> A \\<subseteq> B\" by simp\n\n    (*this one is non sensical*)\nlemma helper2 : \"(\\<forall>x. (x \\<in> A \\<longleftrightarrow> x \\<in> B)) \\<Longrightarrow> (A = B)\" \nproof -\n  assume a:\"\\<forall>x. (x \\<in> A) = (x \\<in> B)\"\n  {\n    assume \"A \\<noteq> B\"\n    from this obtain y where b:\"y \\<in> A  \\<and> y \\<notin> B\" using a by auto\n    hence c:\"y \\<in> A\" ..\n    from b have d:\"y \\<notin> B\" ..\n    from a have \"(y \\<in> A) = (y \\<in> B)\" by (rule allE)\n    with d and c have False by simp\n  }\n  hence \"\\<not> (A \\<noteq> B)\" by (rule notI)\n  thus ?thesis by simp\nqed\n\nlemma \"\\<forall>x. (x \\<in> A) \\<longleftrightarrow> (x \\<in> B) \\<Longrightarrow> (A = B)\" \nproof -\n  assume \"\\<forall>x. (x \\<in> A) \\<longleftrightarrow> (x \\<in> B)\"\n  hence \"\\<And>y. (y \\<in> A) \\<longleftrightarrow> (y \\<in> B)\" by (rule allE)\n  hence \"{y. y \\<in> A} = {y . y \\<in> B}\" by simp\n  thus \"A = B\" by simp\nqed\n  \nlemma \"A \\<inter> B = {x . x \\<in> A \\<and>  x \\<in> B}\" by (rule Int_def)\n    \nlemma \"A \\<noteq> B  \\<Longrightarrow> \\<exists>y. y \\<in> A  \\<and> y \\<notin> B \\<or> y \\<notin> A \\<and> y \\<in> B  \"\nproof - \n  assume a:\"A \\<noteq> B\"\n  {\n    assume b:\"\\<not>(\\<exists>y. y \\<in> A  \\<and> y \\<notin> B \\<or> y \\<notin> A \\<and> y \\<in> B)\"\n    {\n      fix y\n      from b have  \"(y \\<in> A \\<longrightarrow> y \\<in> B)  \\<and> ((y \\<in> A) \\<or> (y \\<notin> B))\" by simp\n      hence \"(y \\<in> A \\<longrightarrow> y \\<in> B)  \\<and> (y \\<in> B \\<longrightarrow> y \\<in> A)\" by auto\n      hence \"y \\<in> A \\<longleftrightarrow> y \\<in> B\" by auto\n    }\n    hence \"\\<forall>y. y \\<in> A \\<longleftrightarrow> y \\<in> B\" by (rule allI)\n    hence \"{y. y \\<in> A} = {y. y \\<in> B}\" by simp\n    hence \"A = B\" by simp\n    with a have False by contradiction\n  }\n  thus \"\\<exists>y. y \\<in> A  \\<and> y \\<notin> B \\<or> y \\<notin> A \\<and> y \\<in> B\" by auto\nqed\n            \nlemma \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\" by blast\n          \n  \nlemma \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\" \nproof -\n  {\n    fix x\n    have \"(x \\<in> (A \\<inter> (B \\<union> C))) =  (x \\<in> A \\<and> x \\<in> (B \\<union> C))\" by simp\n    also have \"\\<dots> = (x \\<in> A \\<and> (x \\<in> B \\<or> x \\<in> C))\" by simp\n    also have \"\\<dots> = ((x \\<in> A \\<and> x \\<in> B) \\<or> (x \\<in> A \\<and> x \\<in> C))\" \n    proof -\n      have \"(x \\<in> A \\<and> (x \\<in> B \\<or> x \\<in> C)) \\<Longrightarrow> (x \\<in> A \\<and> x \\<in> B \\<or> x \\<in> A \\<and> x \\<in> C)\" by simp\n      moreover\n      {\n        assume \"x \\<in> A \\<and> x \\<in> B \\<or> x \\<in> A \\<and> x \\<in> C\"\n        hence \"x \\<in> A \\<and> (x \\<in> B \\<or> x \\<in> C)\" by blast\n      }\n      ultimately show ?thesis by (rule iffI)\n    qed\n    also have \"\\<dots> = (x \\<in> (A \\<inter> B) \\<or> x \\<in> (A \\<inter> C))\" by simp\n    also have \"\\<dots> = (x \\<in> ((A \\<inter> B) \\<union> (A \\<inter> C)))\" by simp\n    finally have \"(x \\<in> (A \\<inter> (B \\<union> C))) = (x \\<in> ((A \\<inter> B) \\<union> (A \\<inter> C)))\" by assumption      \n  }\n  hence \"\\<forall>x. (x \\<in> (A \\<inter> (B \\<union> C))) = (x \\<in> (A \\<inter> B) \\<union> (A \\<inter> C))\" by (rule allI)\n  thus ?thesis by (simp add : helper2)    \nqed\n \nlemma \"A \\<subset> B \\<Longrightarrow> B \\<subset> C \\<Longrightarrow> A \\<subset> C\" by (rule order.strict_trans)\n  \nlemma \"A \\<subseteq> B \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> A \\<subseteq> C\" \nproof -\n  assume a:\"A \\<subseteq> B\"\n  assume b:\"B \\<subseteq> C\"\n  show ?thesis \n  proof (cases \"A = B\")\n    case True\n    assume \"A = B\"\n    with b show ?thesis by simp\n  next\n    case False\n    assume \"A \\<noteq> B\"\n    with a have c:\"A \\<subset> B\" by simp\n    then show ?thesis \n    proof (cases \"B = C\")\n      case True\n      with c have \"A \\<subset> C\" by simp\n      then show ?thesis by simp\n    next\n      case False\n      with b have \"B \\<subset> C\" by simp\n      with c show ?thesis by simp\n    qed\n  qed\nqed\n\n  \nlemma \"A \\<subseteq> B \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> C \\<subseteq> A \\<Longrightarrow> A = B \\<and>  B = C \\<and> C = A\" \nproof - \n  assume a:\"A \\<subseteq> B\"\n  assume b:\"B \\<subseteq> C\" \n  assume c:\"C \\<subseteq> A\" \n  from a and b have \"A \\<subseteq> C\" by simp\n  with c have d:\"A = C\" by simp\n  with a and b have e:\"A = B\" by simp\n  with d have \"B = C\" by simp\n  with d and e show ?thesis by simp\nqed\n\nlemma \"{x. False}= {}\" \nproof - \n  have \"{x . False} = (if False then UNIV else {})\" unfolding Collect_const by (rule subst; rule refl)\n  also have \"\\<dots> = {}\" by simp\n  finally show ?thesis by assumption\nqed\n\nlemma \"A \\<inter> B = A - (A - B)\" by blast\n    \nlemma \"A \\<inter> B = A - (A - B)\"\nproof -\n  {\n    assume \"A \\<inter> B\"\n      \n\nlemma \"A \\<in> \\<A> \\<Longrightarrow> B \\<in> \\<A> \\<Longrightarrow> \"  \n  \nlemma \"\\<exists>x. x \\<in> {n::nat . n \\<noteq> 5}\" \n  using [[simp_trace_new mode=full]]\nproof -\n  obtain y::nat where \"y \\<noteq> (5::nat)\"  \n  proof - \n    assume a:\"\\<And>y. y \\<noteq> (5::nat) \\<Longrightarrow> thesis\"\n      thus thesis using one_eq_numeral_iff by blast\n\n   \n\n  \nlemma \"A \\<noteq> {} = (\\<exists>x . x \\<in> A)\" \nproof -\n  {\n    assume \"A \\<noteq> {}\"\n      \n      \n\n    \nlemma \"\\<exists>x. x \\<in> A \\<Longrightarrow> card A > 0\" \nproof - \n  assume \"\\<exists>x . x \\<in> A\"\n  {\n    assume \"card A \\<le> 0\"\n    hence \"card A = 0\" by simp\n        hence \"A = {}\" \n      \n  \nlemma \"A = {} \\<Longrightarrow> \\<forall>x. x \\<notin> A\"\nproof (rule allI)\n  fix x\n  assume \"A = {}\"\n\n\n      \n\nlemma \"A = {} = (\\<forall>x. x \\<notin> A)\" \nproof -\n  {\n    assume a:\"A = {}\"\n    hence b:\"card A = 0\" by simp\n    {\n      assume c:\"\\<exists>x. x \\<in> A\"\n      {\n        fix x \n        assume \"x \\<in> A\" \n        with a have False by simp\n      }\n      with c have False by (rule exE)\n    }\n    hence \"\\<forall>x. x \\<notin> A\" by auto\n  }\n  moreover\n  {\n    assume \"\\<forall>x. x \\<notin> A\"\n    {\n      \n        \n    \n      \n  \nlemma helper3: \"B \\<noteq> {} = (\\<exists>x. x \\<in> B)\" \nproof -\n  {\n    assume a:\"B \\<noteq> {}\"\n    {\n      assume \"\\<not>(\\<exists>x. x \\<in> B)\"\n      hence \"B = {}\" by simp \n      with a have False by contradiction\n    }\n    hence \"\\<not>\\<not>(\\<exists>x. x \\<in> B)\" by (rule notI)\n    hence \"\\<exists>x. x \\<in> B\" by (rule notnotD)\n  }\n  moreover\n  {\n    assume a:\"\\<exists>x. x \\<in> B\" \n    {\n      assume \"B = {}\"\n      hence \"\\<forall>x. x \\<notin> B\" by (subst all_not_in_conv) \n      hence \"\\<not>(\\<exists>x. x \\<in> B)\" by simp\n      with a have False by contradiction\n    }\n    hence \"B \\<noteq> {}\" by auto\n  }\n    ultimately show ?thesis by (rule iffI)\nqed\n  \n        \n\nlemma \"A \\<inter> B = {} \\<Longrightarrow> \\<exists>x. x \\<in> A \\<and> x \\<notin> B \\<or> x \\<notin> A \\<and> x \\<in> B \\<or> A = {} \\<and> B = {}\" \n  using [[simp_trace_new mode=full]]\nproof - \n  assume \"A \\<inter> B = {}\"\n  show ?thesis \n  proof (cases \"A = {}\")\n    case True\n    assume a:\"A = {}\"\n    then show ?thesis\n    proof (cases \"B = {}\")\n      case True\n      with a  show ?thesis by simp\n    next\n      case False\n      assume b:\"B \\<noteq> {}\"\n      from b have  \"(\\<exists>x. x \\<in> A \\<and> x \\<notin> B \\<or> x \\<notin> A \\<and> x \\<in> B \\<or> A = {} \\<and> B = {}) = (\\<exists>x. x \\<in> A \\<and> x \\<notin> B \\<or> x \\<notin> A \\<and> x \\<in> B \\<or> False)\" by simp\n      also from a have \"\\<dots> = (\\<exists>x. False \\<or> x \\<notin> A \\<and> x \\<in> B)\" by simp\n      also have \"\\<dots> = (\\<exists>x. x \\<notin> A \\<and> x \\<in> B)\" by simp\n      also from a have \"\\<dots> = (\\<exists>x. True \\<and> x \\<in> B)\" by simp\n      also have \"\\<dots> = (\\<exists>x. x \\<in> B)\" by simp\n      also have \"\\<dots> = (B \\<noteq> {})\" unfolding helper3  by (rule subst; rule refl)\n      finally show ?thesis using b by simp\n    qed\n  next\n    case False\n    assume a:\"A \\<noteq> {}\"\n    then show ?thesis \n    proof (cases \"B = {}\")\n      case True\n      with a show ?thesis by auto \n    next\n      case False\n        \n      then show ?thesis sorry\n    qed\n      \n  qed\n \n\n  \n  \n  \nlemma \"A \\<inter> B = {} \\<Longrightarrow> card(A \\<union> B) = card A + card B\" \nproof -\n  assume a:\"A \\<inter> B = {}\"\n  {\n    assume \"card(A \\<union> B) \\<noteq> card A + card B\"\n\n      \n      \n\n      \n\nlemma \"card (a:: 'a set) + card (b::'a set)  \\<ge> card (a \\<union> b)\" \nproof (cases \"a \\<inter> b = {}\")\n  case True\n  then show ?thesis \nnext\n  case False\n  then show ?thesis sorry\nqed\n  \nlemma \"A \\<union> B = A \\<inter> -B \\<union> A \\<inter> B \\<union> -A \\<inter> B\" \nproof - \n  {\n    fix x\n    assume \"x \\<in> (A \\<union> B)\"\n      \n      \n  ", "meta": {"author": "SvenWille", "repo": "ProvingStuff", "sha": "ffc7914d23ffa7353406f7baf839d83383ad8787", "save_path": "github-repos/isabelle/SvenWille-ProvingStuff", "path": "github-repos/isabelle/SvenWille-ProvingStuff/ProvingStuff-ffc7914d23ffa7353406f7baf839d83383ad8787/Isabelle/SetTheory/SetTheory1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7749759937074533}}
{"text": "section \\<open>Challenge 3\\<close>\ntheory Challenge3\n  imports Parallel_Multiset_Fold Refine_Imperative_HOL.IICF\nbegin\n\ntext \\<open>Problem definition:\n\\<^url>\\<open>https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Verify%20This/Challenges%202019/sparse_matrix_multiplication.pdf\\<close>\\<close>\n\nsubsection \\<open>Single-Threaded Implementation\\<close>\ntext \\<open>We define type synonyms for values (which we fix to integers here) and \n  triplets, which are a pair of coordinates and a value.\n\\<close>\ntype_synonym val = int\ntype_synonym triplet = \"(nat \\<times> nat) \\<times> val\"\n\ntext \\<open>We fix a size \\<open>n\\<close> for the vector.\\<close>\ncontext \n  fixes n :: nat \nbegin\n\n  text \\<open>An algorithm finishing triples in any order.\n  \\<close>\n  definition\n    \"alg (ts :: triplet list) x = fold_mset (\\<lambda>((r,c),v) y. y(c:=y c + x r * v)) (\\<lambda>_. 0 :: int) (mset ts)\"\n\n  text \\<open>\n    We show that the folding function is commutative, i.e., the order of the folding does not matter.\n    We will use this below to show that the computation can be parallelized.\n  \\<close>  \n  interpretation comp_fun_commute \"(\\<lambda>((r, c), v) y. y(c := (y c :: val) + x r * v))\"\n    apply unfold_locales\n    apply (auto intro!: ext)\n    done\n\n  subsection \\<open>Specification\\<close>\n  text \\<open>Abstraction function, mapping a sparse matrix to a function from coordinates to values.\\<close>\n  definition \\<alpha> :: \"triplet list \\<Rightarrow> (nat \\<times> nat) \\<Rightarrow> val\" where \n    \"\\<alpha> = the_default 0 oo map_of\"\n\n  text \\<open>Abstract product.\\<close>\n  definition \"pr m x i \\<equiv> \\<Sum>k=0..<n. x k * m (k, i)\"    \n\n  subsection \\<open>Correctness\\<close>\n\n  lemma aux: \n    \"\n    distinct (map fst (ts1@ts2)) \\<Longrightarrow>\n    the_default (0::val) (case map_of ts1 (k, i) of None \\<Rightarrow> map_of ts2 (k, i) | Some x \\<Rightarrow> Some x)\n    \n    = the_default 0 (map_of ts1 (k, i)) + the_default 0 (map_of ts2 (k, i))\n    \"    \n    apply (auto split: option.splits)\n    by (metis disjoint_iff_not_equal img_fst map_of_eq_None_iff the_default.simps(2))\n    \n  lemma 1[simp]: \"distinct (map fst (ts1@ts2)) \\<Longrightarrow> \n    pr (\\<alpha> (ts1@ts2)) x i = pr (\\<alpha> ts1) x i + pr (\\<alpha> ts2) x i\"\n    apply (auto simp: pr_def \\<alpha>_def map_add_def aux split: option.splits)\n    apply (auto simp: algebra_simps)\n    by (simp add: sum.distrib)\n\n  lemmas 2 = 1[of \"[((r,c),v)]\" \"ts\", simplified] for r c v ts \n    \n  \n\n    \n  lemma correct_fold: \n    assumes \"distinct (map fst ts)\"\n    assumes \"\\<forall>((r,c),_)\\<in>set ts. r<n\"\n    shows \"fold (\\<lambda>((r,c),v) y. y(c:=y c + x r * v)) ts (\\<lambda>_. 0) = pr (\\<alpha> ts) x\"\n    apply (rule ext)\n    using correct_aux[OF assms, rule_format, where m = \"\\<lambda>_. 0\", simplified]\n    by simp\n\n  lemma alg_by_fold: \"alg ts x = fold (\\<lambda>((r,c),v) y. y(c:=y c + x r * v)) ts (\\<lambda>_. 0)\"    \n    unfolding alg_def by (simp add: fold_mset_rewr)\n          \n  theorem correct: \n    assumes \"distinct (map fst ts)\"\n    assumes \"\\<forall>((r,c),_)\\<in>set ts. r<n\"\n    shows \"alg ts x = pr (\\<alpha> ts) x\"\n    using alg_by_fold correct_fold[OF assms] by simp \n\n  subsection \\<open>Multi-Threaded Implementation\\<close>\n  text \\<open>Correctness of the parallel implementation:\\<close>\n  theorem parallel_correct:\n    assumes \"distinct (map fst ts)\" \"\\<forall>((r,c),_)\\<in>set ts. r<n\"\n        and \"0 < n\" \\<comment> \\<open>At least on thread\\<close>\n        \\<comment>\\<open>We have reached a final state.\\<close>\n        and \"reachable x n ts (\\<lambda>_. 0) (ts', ms, r)\" \"final n (ts', ms, r)\"\n      shows \"r = pr (\\<alpha> ts) x\"\n    unfolding final_state_correct[OF assms(3-)] correct[OF assms(1,2)] alg_by_fold[symmetric] ..\n\n  text \\<open>We also know that the computation will always terminate.\\<close>\n  theorem parallel_termination:\n    assumes \"0 < n\"\n      and \"reachable x n ts (\\<lambda>_. 0) s\"\n    shows \"\\<exists>s'. final n s' \\<and> (step x n)\\<^sup>*\\<^sup>* s s'\"\n    using assms by (rule \"termination\")\n\nend \\<comment> \\<open>Context for fixed \\<open>n\\<close>.\\<close>\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/VerifyThis2019/Challenge3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8918110526265555, "lm_q1q2_score": 0.774829321867112}}
{"text": "theory heap_SortSorts\nimports Main\n        \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\ndatatype 'a list = Nil2 | Cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Heap = Node \"Heap\" \"Nat\" \"Heap\" | Nil2\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) y = y\"\n| \"plus (S n) y = S (plus n y)\"\n\nfun le :: \"Nat => Nat => bool\" where\n\"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun merge :: \"Heap => Heap => Heap\" where\n\"merge (Node z x2 x3) (Node x4 x5 x6) =\n   (if le x2 x5 then Node (merge x3 (Node x4 x5 x6)) x2 z else\n      Node (merge (Node z x2 x3) x6) x5 x4)\"\n| \"merge (Node z x2 x3) (Nil2) = Node z x2 x3\"\n| \"merge (Nil2) y = y\"\n\nfun toList :: \"Nat => Heap => Nat list\" where\n\"toList (Z) y = Nil2\"\n| \"toList (S z) (Node x2 x3 x4) =\n     Cons2 x3 (toList z (merge x2 x4))\"\n| \"toList (S z) (Nil2) = Nil2\"\n\nfun insert2 :: \"Nat => Heap => Heap\" where\n\"insert2 x y = merge (Node Nil2 x Nil2) y\"\n\nfun toHeap :: \"Nat list => Heap\" where\n\"toHeap (Nil2) = Nil2\"\n| \"toHeap (Cons2 y xs) = insert2 y (toHeap xs)\"\n\nfun heapSize :: \"Heap => Nat\" where\n\"heapSize (Node l y r) = S (plus (heapSize l) (heapSize r))\"\n| \"heapSize (Nil2) = Z\"\n\nfun toList2 :: \"Heap => Nat list\" where\n\"toList2 x = toList (heapSize x) x\"\n\nfun dot :: \"('b => 'c) => ('a => 'b) => 'a => 'c\" where\n\"dot x y z = x (y z)\"\n\nfun hsort :: \"Nat list => Nat list\" where\n\"hsort x =\n   dot (% (y :: Heap) => toList2 y) (% (z :: Nat list) => toHeap z) x\"\n\nfun and2 :: \"bool => bool => bool\" where\n\"and2 True y = y\"\n| \"and2 False y = False\"\n\nfun ordered :: \"Nat list => bool\" where\n\"ordered (Nil2) = True\"\n| \"ordered (Cons2 y (Nil2)) = True\"\n| \"ordered (Cons2 y (Cons2 y2 xs)) =\n     and2 (le y y2) (ordered (Cons2 y2 xs))\"\n\n(*hipster plus\n          le\n          merge\n          toList\n          insert2\n          toHeap\n          heapSize\n          toList2\n          dot\n          hsort\n          and2\n          ordered *)\n\ntheorem x0 :\n  \"!! (x :: Nat list) . ordered (hsort x)\"\n  by (tactic \\<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\\<close>)\n\nend\n", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/tip2015/heap_SortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9585377308419051, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.7745629198924061}}
{"text": "(* Author: Tobias Nipkow, Daniel Stüwe *)\n\nsection {* Three-Way Comparison *}\n\ntheory Cmp\nimports Main\nbegin\n\ndatatype cmp_val = LT | EQ | GT\n\ndefinition cmp :: \"'a:: linorder \\<Rightarrow> 'a \\<Rightarrow> cmp_val\" where\n\"cmp x y = (if x < y then LT else if x=y then EQ else GT)\"\n\nlemma \n    LT[simp]: \"cmp x y = LT \\<longleftrightarrow> x < y\"\nand EQ[simp]: \"cmp x y = EQ \\<longleftrightarrow> x = y\"\nand GT[simp]: \"cmp x y = GT \\<longleftrightarrow> x > y\"\nby (auto simp: cmp_def)\n\nlemma case_cmp_if[simp]: \"(case c of EQ \\<Rightarrow> e | LT \\<Rightarrow> l | GT \\<Rightarrow> g) =\n  (if c = LT then l else if c = GT then g else e)\"\nby(simp split: cmp_val.split)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Data_Structures/Cmp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8670357615200474, "lm_q1q2_score": 0.7745312036140741}}
{"text": "(*  Title:      HOL/Library/Infinite_Set.thy\n    Author:     Stephan Merz\n*)\n\nsection \\<open>Infinite Sets and Related Concepts\\<close>\n\ntheory Infinite_Set\n  imports Main\nbegin\n\nsubsection \\<open>The set of natural numbers is infinite\\<close>\n\nlemma infinite_nat_iff_unbounded_le: \"infinite S \\<longleftrightarrow> (\\<forall>m. \\<exists>n\\<ge>m. n \\<in> S)\"\n  for S :: \"nat set\"\n  using frequently_cofinite[of \"\\<lambda>x. x \\<in> S\"]\n  by (simp add: cofinite_eq_sequentially frequently_def eventually_sequentially)\n\nlemma infinite_nat_iff_unbounded: \"infinite S \\<longleftrightarrow> (\\<forall>m. \\<exists>n>m. n \\<in> S)\"\n  for S :: \"nat set\"\n  using frequently_cofinite[of \"\\<lambda>x. x \\<in> S\"]\n  by (simp add: cofinite_eq_sequentially frequently_def eventually_at_top_dense)\n\nlemma finite_nat_iff_bounded: \"finite S \\<longleftrightarrow> (\\<exists>k. S \\<subseteq> {..<k})\"\n  for S :: \"nat set\"\n  using infinite_nat_iff_unbounded_le[of S] by (simp add: subset_eq) (metis not_le)\n\nlemma finite_nat_iff_bounded_le: \"finite S \\<longleftrightarrow> (\\<exists>k. S \\<subseteq> {.. k})\"\n  for S :: \"nat set\"\n  using infinite_nat_iff_unbounded[of S] by (simp add: subset_eq) (metis not_le)\n\nlemma finite_nat_bounded: \"finite S \\<Longrightarrow> \\<exists>k. S \\<subseteq> {..<k}\"\n  for S :: \"nat set\"\n  by (simp add: finite_nat_iff_bounded)\n\n\ntext \\<open>\n  For a set of natural numbers to be infinite, it is enough to know\n  that for any number larger than some \\<open>k\\<close>, there is some larger\n  number that is an element of the set.\n\\<close>\n\nlemma unbounded_k_infinite: \"\\<forall>m>k. \\<exists>n>m. n \\<in> S \\<Longrightarrow> infinite (S::nat set)\"\n  apply (clarsimp simp add: finite_nat_set_iff_bounded)\n  apply (drule_tac x=\"Suc (max m k)\" in spec)\n  using less_Suc_eq apply fastforce\n  done\n\nlemma nat_not_finite: \"finite (UNIV::nat set) \\<Longrightarrow> R\"\n  by simp\n\nlemma range_inj_infinite:\n  fixes f :: \"nat \\<Rightarrow> 'a\"\n  assumes \"inj f\"\n  shows \"infinite (range f)\"\nproof\n  assume \"finite (range f)\"\n  from this assms have \"finite (UNIV::nat set)\"\n    by (rule finite_imageD)\n  then show False by simp\nqed\n\n\nsubsection \\<open>The set of integers is also infinite\\<close>\n\nlemma infinite_int_iff_infinite_nat_abs: \"infinite S \\<longleftrightarrow> infinite ((nat \\<circ> abs) ` S)\"\n  for S :: \"int set\"\nproof (unfold Not_eq_iff, rule iffI)\n  assume \"finite ((nat \\<circ> abs) ` S)\"\n  then have \"finite (nat ` (abs ` S))\"\n    by (simp add: image_image cong: image_cong)\n  moreover have \"inj_on nat (abs ` S)\"\n    by (rule inj_onI) auto\n  ultimately have \"finite (abs ` S)\"\n    by (rule finite_imageD)\n  then show \"finite S\"\n    by (rule finite_image_absD)\nqed simp\n\nproposition infinite_int_iff_unbounded_le: \"infinite S \\<longleftrightarrow> (\\<forall>m. \\<exists>n. \\<bar>n\\<bar> \\<ge> m \\<and> n \\<in> S)\"\n  for S :: \"int set\"\n  by (simp add: infinite_int_iff_infinite_nat_abs infinite_nat_iff_unbounded_le o_def image_def)\n    (metis abs_ge_zero nat_le_eq_zle le_nat_iff)\n\nproposition infinite_int_iff_unbounded: \"infinite S \\<longleftrightarrow> (\\<forall>m. \\<exists>n. \\<bar>n\\<bar> > m \\<and> n \\<in> S)\"\n  for S :: \"int set\"\n  by (simp add: infinite_int_iff_infinite_nat_abs infinite_nat_iff_unbounded o_def image_def)\n    (metis (full_types) nat_le_iff nat_mono not_le)\n\nproposition finite_int_iff_bounded: \"finite S \\<longleftrightarrow> (\\<exists>k. abs ` S \\<subseteq> {..<k})\"\n  for S :: \"int set\"\n  using infinite_int_iff_unbounded_le[of S] by (simp add: subset_eq) (metis not_le)\n\nproposition finite_int_iff_bounded_le: \"finite S \\<longleftrightarrow> (\\<exists>k. abs ` S \\<subseteq> {.. k})\"\n  for S :: \"int set\"\n  using infinite_int_iff_unbounded[of S] by (simp add: subset_eq) (metis not_le)\n\n\nsubsection \\<open>Infinitely Many and Almost All\\<close>\n\ntext \\<open>\n  We often need to reason about the existence of infinitely many\n  (resp., all but finitely many) objects satisfying some predicate, so\n  we introduce corresponding binders and their proof rules.\n\\<close>\n\nlemma not_INFM [simp]: \"\\<not> (INFM x. P x) \\<longleftrightarrow> (MOST x. \\<not> P x)\"\n  by (rule not_frequently)\n\nlemma not_MOST [simp]: \"\\<not> (MOST x. P x) \\<longleftrightarrow> (INFM x. \\<not> P x)\"\n  by (rule not_eventually)\n\nlemma INFM_const [simp]: \"(INFM x::'a. P) \\<longleftrightarrow> P \\<and> infinite (UNIV::'a set)\"\n  by (simp add: frequently_const_iff)\n\nlemma MOST_const [simp]: \"(MOST x::'a. P) \\<longleftrightarrow> P \\<or> finite (UNIV::'a set)\"\n  by (simp add: eventually_const_iff)\n\nlemma INFM_imp_distrib: \"(INFM x. P x \\<longrightarrow> Q x) \\<longleftrightarrow> ((MOST x. P x) \\<longrightarrow> (INFM x. Q x))\"\n  by (rule frequently_imp_iff)\n\nlemma MOST_imp_iff: \"MOST x. P x \\<Longrightarrow> (MOST x. P x \\<longrightarrow> Q x) \\<longleftrightarrow> (MOST x. Q x)\"\n  by (auto intro: eventually_rev_mp eventually_mono)\n\nlemma INFM_conjI: \"INFM x. P x \\<Longrightarrow> MOST x. Q x \\<Longrightarrow> INFM x. P x \\<and> Q x\"\n  by (rule frequently_rev_mp[of P]) (auto elim: eventually_mono)\n\n\ntext \\<open>Properties of quantifiers with injective functions.\\<close>\n\nlemma INFM_inj: \"INFM x. P (f x) \\<Longrightarrow> inj f \\<Longrightarrow> INFM x. P x\"\n  using finite_vimageI[of \"{x. P x}\" f] by (auto simp: frequently_cofinite)\n\nlemma MOST_inj: \"MOST x. P x \\<Longrightarrow> inj f \\<Longrightarrow> MOST x. P (f x)\"\n  using finite_vimageI[of \"{x. \\<not> P x}\" f] by (auto simp: eventually_cofinite)\n\n\ntext \\<open>Properties of quantifiers with singletons.\\<close>\n\nlemma not_INFM_eq [simp]:\n  \"\\<not> (INFM x. x = a)\"\n  \"\\<not> (INFM x. a = x)\"\n  unfolding frequently_cofinite by simp_all\n\nlemma MOST_neq [simp]:\n  \"MOST x. x \\<noteq> a\"\n  \"MOST x. a \\<noteq> x\"\n  unfolding eventually_cofinite by simp_all\n\nlemma INFM_neq [simp]:\n  \"(INFM x::'a. x \\<noteq> a) \\<longleftrightarrow> infinite (UNIV::'a set)\"\n  \"(INFM x::'a. a \\<noteq> x) \\<longleftrightarrow> infinite (UNIV::'a set)\"\n  unfolding frequently_cofinite by simp_all\n\nlemma MOST_eq [simp]:\n  \"(MOST x::'a. x = a) \\<longleftrightarrow> finite (UNIV::'a set)\"\n  \"(MOST x::'a. a = x) \\<longleftrightarrow> finite (UNIV::'a set)\"\n  unfolding eventually_cofinite by simp_all\n\nlemma MOST_eq_imp:\n  \"MOST x. x = a \\<longrightarrow> P x\"\n  \"MOST x. a = x \\<longrightarrow> P x\"\n  unfolding eventually_cofinite by simp_all\n\n\ntext \\<open>Properties of quantifiers over the naturals.\\<close>\n\nlemma MOST_nat: \"(\\<forall>\\<^sub>\\<infinity>n. P n) \\<longleftrightarrow> (\\<exists>m. \\<forall>n>m. P n)\"\n  for P :: \"nat \\<Rightarrow> bool\"\n  by (auto simp add: eventually_cofinite finite_nat_iff_bounded_le subset_eq simp flip: not_le)\n\nlemma MOST_nat_le: \"(\\<forall>\\<^sub>\\<infinity>n. P n) \\<longleftrightarrow> (\\<exists>m. \\<forall>n\\<ge>m. P n)\"\n  for P :: \"nat \\<Rightarrow> bool\"\n  by (auto simp add: eventually_cofinite finite_nat_iff_bounded subset_eq simp flip: not_le)\n\nlemma INFM_nat: \"(\\<exists>\\<^sub>\\<infinity>n. P n) \\<longleftrightarrow> (\\<forall>m. \\<exists>n>m. P n)\"\n  for P :: \"nat \\<Rightarrow> bool\"\n  by (simp add: frequently_cofinite infinite_nat_iff_unbounded)\n\nlemma INFM_nat_le: \"(\\<exists>\\<^sub>\\<infinity>n. P n) \\<longleftrightarrow> (\\<forall>m. \\<exists>n\\<ge>m. P n)\"\n  for P :: \"nat \\<Rightarrow> bool\"\n  by (simp add: frequently_cofinite infinite_nat_iff_unbounded_le)\n\nlemma MOST_INFM: \"infinite (UNIV::'a set) \\<Longrightarrow> MOST x::'a. P x \\<Longrightarrow> INFM x::'a. P x\"\n  by (simp add: eventually_frequently)\n\nlemma MOST_Suc_iff: \"(MOST n. P (Suc n)) \\<longleftrightarrow> (MOST n. P n)\"\n  by (simp add: cofinite_eq_sequentially)\n\nlemma MOST_SucI: \"MOST n. P n \\<Longrightarrow> MOST n. P (Suc n)\"\n  and MOST_SucD: \"MOST n. P (Suc n) \\<Longrightarrow> MOST n. P n\"\n  by (simp_all add: MOST_Suc_iff)\n\nlemma MOST_ge_nat: \"MOST n::nat. m \\<le> n\"\n  by (simp add: cofinite_eq_sequentially)\n\n\\<comment> \\<open>legacy names\\<close>\nlemma Inf_many_def: \"Inf_many P \\<longleftrightarrow> infinite {x. P x}\" by (fact frequently_cofinite)\nlemma Alm_all_def: \"Alm_all P \\<longleftrightarrow> \\<not> (INFM x. \\<not> P x)\" by simp\nlemma INFM_iff_infinite: \"(INFM x. P x) \\<longleftrightarrow> infinite {x. P x}\" by (fact frequently_cofinite)\nlemma MOST_iff_cofinite: \"(MOST x. P x) \\<longleftrightarrow> finite {x. \\<not> P x}\" by (fact eventually_cofinite)\nlemma INFM_EX: \"(\\<exists>\\<^sub>\\<infinity>x. P x) \\<Longrightarrow> (\\<exists>x. P x)\" by (fact frequently_ex)\nlemma ALL_MOST: \"\\<forall>x. P x \\<Longrightarrow> \\<forall>\\<^sub>\\<infinity>x. P x\" by (fact always_eventually)\nlemma INFM_mono: \"\\<exists>\\<^sub>\\<infinity>x. P x \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> \\<exists>\\<^sub>\\<infinity>x. Q x\" by (fact frequently_elim1)\nlemma MOST_mono: \"\\<forall>\\<^sub>\\<infinity>x. P x \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> \\<forall>\\<^sub>\\<infinity>x. Q x\" by (fact eventually_mono)\nlemma INFM_disj_distrib: \"(\\<exists>\\<^sub>\\<infinity>x. P x \\<or> Q x) \\<longleftrightarrow> (\\<exists>\\<^sub>\\<infinity>x. P x) \\<or> (\\<exists>\\<^sub>\\<infinity>x. Q x)\" by (fact frequently_disj_iff)\nlemma MOST_rev_mp: \"\\<forall>\\<^sub>\\<infinity>x. P x \\<Longrightarrow> \\<forall>\\<^sub>\\<infinity>x. P x \\<longrightarrow> Q x \\<Longrightarrow> \\<forall>\\<^sub>\\<infinity>x. Q x\" by (fact eventually_rev_mp)\nlemma MOST_conj_distrib: \"(\\<forall>\\<^sub>\\<infinity>x. P x \\<and> Q x) \\<longleftrightarrow> (\\<forall>\\<^sub>\\<infinity>x. P x) \\<and> (\\<forall>\\<^sub>\\<infinity>x. Q x)\" by (fact eventually_conj_iff)\nlemma MOST_conjI: \"MOST x. P x \\<Longrightarrow> MOST x. Q x \\<Longrightarrow> MOST x. P x \\<and> Q x\" by (fact eventually_conj)\nlemma INFM_finite_Bex_distrib: \"finite A \\<Longrightarrow> (INFM y. \\<exists>x\\<in>A. P x y) \\<longleftrightarrow> (\\<exists>x\\<in>A. INFM y. P x y)\" by (fact frequently_bex_finite_distrib)\nlemma MOST_finite_Ball_distrib: \"finite A \\<Longrightarrow> (MOST y. \\<forall>x\\<in>A. P x y) \\<longleftrightarrow> (\\<forall>x\\<in>A. MOST y. P x y)\" by (fact eventually_ball_finite_distrib)\nlemma INFM_E: \"INFM x. P x \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\" by (fact frequentlyE)\nlemma MOST_I: \"(\\<And>x. P x) \\<Longrightarrow> MOST x. P x\" by (rule eventuallyI)\nlemmas MOST_iff_finiteNeg = MOST_iff_cofinite\n\n\nsubsection \\<open>Enumeration of an Infinite Set\\<close>\n\ntext \\<open>The set's element type must be wellordered (e.g. the natural numbers).\\<close>\n\ntext \\<open>\n  Could be generalized to\n    \\<^prop>\\<open>enumerate' S n = (SOME t. t \\<in> s \\<and> finite {s\\<in>S. s < t} \\<and> card {s\\<in>S. s < t} = n)\\<close>.\n\\<close>\n\nprimrec (in wellorder) enumerate :: \"'a set \\<Rightarrow> nat \\<Rightarrow> 'a\"\n  where\n    enumerate_0: \"enumerate S 0 = (LEAST n. n \\<in> S)\"\n  | enumerate_Suc: \"enumerate S (Suc n) = enumerate (S - {LEAST n. n \\<in> S}) n\"\n\nlemma enumerate_Suc': \"enumerate S (Suc n) = enumerate (S - {enumerate S 0}) n\"\n  by simp\n\nlemma enumerate_in_set: \"infinite S \\<Longrightarrow> enumerate S n \\<in> S\"\nproof (induct n arbitrary: S)\n  case 0\n  then show ?case\n    by (fastforce intro: LeastI dest!: infinite_imp_nonempty)\nnext\n  case (Suc n)\n  then show ?case\n    by simp (metis DiffE infinite_remove)\nqed\n\ndeclare enumerate_0 [simp del] enumerate_Suc [simp del]\n\nlemma enumerate_step: \"infinite S \\<Longrightarrow> enumerate S n < enumerate S (Suc n)\"\nproof (induction n arbitrary: S)\n  case 0\n  then have \"enumerate S 0 \\<le> enumerate S (Suc 0)\"\n    by (simp add: enumerate_0 Least_le enumerate_in_set)\n  moreover have \"enumerate (S - {enumerate S 0}) 0 \\<in> S - {enumerate S 0}\"\n    by (meson \"0.prems\" enumerate_in_set infinite_remove)\n  then have \"enumerate S 0 \\<noteq> enumerate (S - {enumerate S 0}) 0\"\n    by auto\n  ultimately show ?case\n    by (simp add: enumerate_Suc')\nnext\n  case (Suc n)\n  then show ?case \n    by (simp add: enumerate_Suc')\nqed\n\nlemma enumerate_mono: \"m < n \\<Longrightarrow> infinite S \\<Longrightarrow> enumerate S m < enumerate S n\"\n  by (induct m n rule: less_Suc_induct) (auto intro: enumerate_step)\n\nlemma enumerate_mono_iff [simp]:\n  \"infinite S \\<Longrightarrow> enumerate S m < enumerate S n \\<longleftrightarrow> m < n\"\n  by (metis enumerate_mono less_asym less_linear)\n\nlemma enumerate_mono_le_iff [simp]:\n  \"infinite S \\<Longrightarrow> enumerate S m \\<le> enumerate S n \\<longleftrightarrow> m \\<le> n\"\n  by (meson enumerate_mono_iff not_le)\n\nlemma le_enumerate:\n  assumes S: \"infinite S\"\n  shows \"n \\<le> enumerate S n\"\n  using S\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have \"n \\<le> enumerate S n\" by simp\n  also note enumerate_mono[of n \"Suc n\", OF _ \\<open>infinite S\\<close>]\n  finally show ?case by simp\nqed\n\nlemma infinite_enumerate:\n  assumes fS: \"infinite S\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (\\<forall>n. r n \\<in> S)\"\n  unfolding strict_mono_def\n  using enumerate_in_set[OF fS] enumerate_mono[of _ _ S] fS by blast\n\nlemma enumerate_Suc'':\n  fixes S :: \"'a::wellorder set\"\n  assumes \"infinite S\"\n  shows \"enumerate S (Suc n) = (LEAST s. s \\<in> S \\<and> enumerate S n < s)\"\n  using assms\nproof (induct n arbitrary: S)\n  case 0\n  then have \"\\<forall>s \\<in> S. enumerate S 0 \\<le> s\"\n    by (auto simp: enumerate.simps intro: Least_le)\n  then show ?case\n    unfolding enumerate_Suc' enumerate_0[of \"S - {enumerate S 0}\"]\n    by (intro arg_cong[where f = Least] ext) auto\nnext\n  case (Suc n S)\n  show ?case\n    using enumerate_mono[OF zero_less_Suc \\<open>infinite S\\<close>, of n] \\<open>infinite S\\<close>\n    apply (subst (1 2) enumerate_Suc')\n    apply (subst Suc)\n     apply (use \\<open>infinite S\\<close> in simp)\n    apply (intro arg_cong[where f = Least] ext)\n    apply (auto simp flip: enumerate_Suc')\n    done\nqed\n\nlemma enumerate_Ex:\n  fixes S :: \"nat set\"\n  assumes S: \"infinite S\"\n    and s: \"s \\<in> S\"\n  shows \"\\<exists>n. enumerate S n = s\"\n  using s\nproof (induct s rule: less_induct)\n  case (less s)\n  show ?case\n  proof (cases \"\\<exists>y\\<in>S. y < s\")\n    case True\n    let ?y = \"Max {s'\\<in>S. s' < s}\"\n    from True have y: \"\\<And>x. ?y < x \\<longleftrightarrow> (\\<forall>s'\\<in>S. s' < s \\<longrightarrow> s' < x)\"\n      by (subst Max_less_iff) auto\n    then have y_in: \"?y \\<in> {s'\\<in>S. s' < s}\"\n      by (intro Max_in) auto\n    with less.hyps[of ?y] obtain n where \"enumerate S n = ?y\"\n      by auto\n    with S have \"enumerate S (Suc n) = s\"\n      by (auto simp: y less enumerate_Suc'' intro!: Least_equality)\n    then show ?thesis by auto\n  next\n    case False\n    then have \"\\<forall>t\\<in>S. s \\<le> t\" by auto\n    with \\<open>s \\<in> S\\<close> show ?thesis\n      by (auto intro!: exI[of _ 0] Least_equality simp: enumerate_0)\n  qed\nqed\n\nlemma inj_enumerate:\n  fixes S :: \"'a::wellorder set\"\n  assumes S: \"infinite S\"\n  shows \"inj (enumerate S)\"\n  unfolding inj_on_def\nproof clarsimp\n  show \"\\<And>x y. enumerate S x = enumerate S y \\<Longrightarrow> x = y\"\n    by (metis neq_iff enumerate_mono[OF _ \\<open>infinite S\\<close>]) \nqed\n\ntext \\<open>To generalise this, we'd need a condition that all initial segments were finite\\<close>\nlemma bij_enumerate:\n  fixes S :: \"nat set\"\n  assumes S: \"infinite S\"\n  shows \"bij_betw (enumerate S) UNIV S\"\nproof -\n  have \"\\<forall>s \\<in> S. \\<exists>i. enumerate S i = s\"\n    using enumerate_Ex[OF S] by auto\n  moreover note \\<open>infinite S\\<close> inj_enumerate\n  ultimately show ?thesis\n    unfolding bij_betw_def by (auto intro: enumerate_in_set)\nqed\n\nlemma \n  fixes S :: \"nat set\"\n  assumes S: \"infinite S\"\n  shows range_enumerate: \"range (enumerate S) = S\" \n    and strict_mono_enumerate: \"strict_mono (enumerate S)\"\n  by (auto simp add: bij_betw_imp_surj_on bij_enumerate assms strict_mono_def)\n\ntext \\<open>A pair of weird and wonderful lemmas from HOL Light.\\<close>\nlemma finite_transitivity_chain:\n  assumes \"finite A\"\n    and R: \"\\<And>x. \\<not> R x x\" \"\\<And>x y z. \\<lbrakk>R x y; R y z\\<rbrakk> \\<Longrightarrow> R x z\"\n    and A: \"\\<And>x. x \\<in> A \\<Longrightarrow> \\<exists>y. y \\<in> A \\<and> R x y\"\n  shows \"A = {}\"\n  using \\<open>finite A\\<close> A\nproof (induct A)\n  case empty\n  then show ?case by simp\nnext\n  case (insert a A)\n  have False\n    using R(1)[of a] R(2)[of _ a] insert(3,4) by blast   \n  thus ?case ..\nqed\n\ncorollary Union_maximal_sets:\n  assumes \"finite \\<F>\"\n  shows \"\\<Union>{T \\<in> \\<F>. \\<forall>U\\<in>\\<F>. \\<not> T \\<subset> U} = \\<Union>\\<F>\"\n    (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<subseteq> ?rhs\" by force\n  show \"?rhs \\<subseteq> ?lhs\"\n  proof (rule Union_subsetI)\n    fix S\n    assume \"S \\<in> \\<F>\"\n    have \"{T \\<in> \\<F>. S \\<subseteq> T} = {}\"\n      if \"\\<not> (\\<exists>y. y \\<in> {T \\<in> \\<F>. \\<forall>U\\<in>\\<F>. \\<not> T \\<subset> U} \\<and> S \\<subseteq> y)\"\n    proof -\n      have \\<section>: \"\\<And>x. x \\<in> \\<F> \\<and> S \\<subseteq> x \\<Longrightarrow> \\<exists>y. y \\<in> \\<F> \\<and> S \\<subseteq> y \\<and> x \\<subset> y\"\n        using that by (blast intro: dual_order.trans psubset_imp_subset)\n      show ?thesis\n      proof (rule finite_transitivity_chain [of _ \"\\<lambda>T U. S \\<subseteq> T \\<and> T \\<subset> U\"])\n      qed (use assms in \\<open>auto intro: \\<section>\\<close>)\n    qed\n    with \\<open>S \\<in> \\<F>\\<close> show \"\\<exists>y. y \\<in> {T \\<in> \\<F>. \\<forall>U\\<in>\\<F>. \\<not> T \\<subset> U} \\<and> S \\<subseteq> y\"\n      by blast\n  qed\nqed\n\nsubsection \\<open>Properties of @{term enumerate} on finite sets\\<close>\n\nlemma finite_enumerate_in_set: \"\\<lbrakk>finite S; n < card S\\<rbrakk> \\<Longrightarrow> enumerate S n \\<in> S\"\nproof (induction n arbitrary: S)\n  case 0\n  then show ?case\n    by (metis all_not_in_conv card.empty enumerate.simps(1) not_less0 wellorder_Least_lemma(1))\nnext\n  case (Suc n)\n  show ?case\n    using Suc.prems Suc.IH [of \"S - {LEAST n. n \\<in> S}\"]\n    apply (simp add: enumerate.simps)\n    by (metis Diff_empty Diff_insert0 Suc_lessD card.remove less_Suc_eq)\nqed\n\nlemma finite_enumerate_step: \"\\<lbrakk>finite S; Suc n < card S\\<rbrakk> \\<Longrightarrow> enumerate S n < enumerate S (Suc n)\"\nproof (induction n arbitrary: S)\n  case 0\n  then have \"enumerate S 0 \\<le> enumerate S (Suc 0)\"\n    by (simp add: Least_le enumerate.simps(1) finite_enumerate_in_set)\n  moreover have \"enumerate (S - {enumerate S 0}) 0 \\<in> S - {enumerate S 0}\"\n    by (metis 0 Suc_lessD Suc_less_eq card_Suc_Diff1 enumerate_in_set finite_enumerate_in_set)\n  then have \"enumerate S 0 \\<noteq> enumerate (S - {enumerate S 0}) 0\"\n    by auto\n  ultimately show ?case\n    by (simp add: enumerate_Suc')\nnext\n  case (Suc n)\n  then show ?case\n    by (simp add: enumerate_Suc' finite_enumerate_in_set)\nqed\n\nlemma finite_enumerate_mono: \"\\<lbrakk>m < n; finite S; n < card S\\<rbrakk> \\<Longrightarrow> enumerate S m < enumerate S n\"\n  by (induct m n rule: less_Suc_induct) (auto intro: finite_enumerate_step)\n\nlemma finite_enumerate_mono_iff [simp]:\n  \"\\<lbrakk>finite S; m < card S; n < card S\\<rbrakk> \\<Longrightarrow> enumerate S m < enumerate S n \\<longleftrightarrow> m < n\"\n  by (metis finite_enumerate_mono less_asym less_linear)\n\nlemma finite_le_enumerate:\n  assumes \"finite S\" \"n < card S\"\n  shows \"n \\<le> enumerate S n\"\n  using assms\nproof (induction n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have \"n \\<le> enumerate S n\" by simp\n  also note finite_enumerate_mono[of n \"Suc n\", OF _ \\<open>finite S\\<close>]\n  finally show ?case\n    using Suc.prems(2) Suc_leI by blast\nqed\n\nlemma finite_enumerate:\n  assumes fS: \"finite S\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono_on {..<card S} r \\<and> (\\<forall>n<card S. r n \\<in> S)\"\n  unfolding strict_mono_def\n  using finite_enumerate_in_set[OF fS] finite_enumerate_mono[of _ _ S] fS\n  by (metis lessThan_iff strict_mono_on_def)\n\nlemma finite_enumerate_Suc'':\n  fixes S :: \"'a::wellorder set\"\n  assumes \"finite S\" \"Suc n < card S\"\n  shows \"enumerate S (Suc n) = (LEAST s. s \\<in> S \\<and> enumerate S n < s)\"\n  using assms\nproof (induction n arbitrary: S)\n  case 0\n  then have \"\\<forall>s \\<in> S. enumerate S 0 \\<le> s\"\n    by (auto simp: enumerate.simps intro: Least_le)\n  then show ?case\n    unfolding enumerate_Suc' enumerate_0[of \"S - {enumerate S 0}\"]\n    by (metis Diff_iff dual_order.strict_iff_order singletonD singletonI)\nnext\n  case (Suc n S)\n  then have \"Suc n < card (S - {enumerate S 0})\"\n    using Suc.prems(2) finite_enumerate_in_set by force\n  then show ?case\n    apply (subst (1 2) enumerate_Suc')\n    apply (simp add: Suc)\n    apply (intro arg_cong[where f = Least] HOL.ext)\n    using finite_enumerate_mono[OF zero_less_Suc \\<open>finite S\\<close>, of n] Suc.prems\n    by (auto simp flip: enumerate_Suc')\nqed\n\nlemma finite_enumerate_initial_segment:\n  fixes S :: \"'a::wellorder set\"\n  assumes \"finite S\" and n: \"n < card (S \\<inter> {..<s})\"\n  shows \"enumerate (S \\<inter> {..<s}) n = enumerate S n\"\n  using n\nproof (induction n)\n  case 0\n  have \"(LEAST n. n \\<in> S \\<and> n < s) = (LEAST n. n \\<in> S)\"\n  proof (rule Least_equality)\n    have \"\\<exists>t. t \\<in> S \\<and> t < s\"\n      by (metis \"0\" card_gt_0_iff disjoint_iff_not_equal lessThan_iff)\n    then show \"(LEAST n. n \\<in> S) \\<in> S \\<and> (LEAST n. n \\<in> S) < s\"\n      by (meson LeastI Least_le le_less_trans)\n  qed (simp add: Least_le)\n  then show ?case\n    by (auto simp: enumerate_0)\nnext\n  case (Suc n)\n  then have less_card: \"Suc n < card S\"\n    by (meson assms(1) card_mono inf_sup_ord(1) leD le_less_linear order.trans)\n  obtain T where T: \"T \\<in> {s \\<in> S. enumerate S n < s}\"\n    by (metis Infinite_Set.enumerate_step enumerate_in_set finite_enumerate_in_set finite_enumerate_step less_card mem_Collect_eq)\n  have \"(LEAST x. x \\<in> S \\<and> x < s \\<and> enumerate S n < x) = (LEAST x. x \\<in> S \\<and> enumerate S n < x)\"\n       (is \"_ = ?r\")\n  proof (intro Least_equality conjI)\n    show \"?r \\<in> S\"\n      by (metis (mono_tags, lifting) LeastI mem_Collect_eq T)\n    have \"\\<not> s \\<le> ?r\"\n      using not_less_Least [of _ \"\\<lambda>x. x \\<in> S \\<and> enumerate S n < x\"] Suc assms\n      by (metis (mono_tags, lifting) Int_Collect Suc_lessD finite_Int finite_enumerate_in_set finite_enumerate_step lessThan_def less_le_trans)\n    then show \"?r < s\"\n      by auto\n    show \"enumerate S n < ?r\"\n      by (metis (no_types, lifting) LeastI mem_Collect_eq T)\n  qed (auto simp: Least_le)\n  then show ?case\n    using Suc assms by (simp add: finite_enumerate_Suc'' less_card)\nqed\n\nlemma finite_enumerate_Ex:\n  fixes S :: \"'a::wellorder set\"\n  assumes S: \"finite S\"\n    and s: \"s \\<in> S\"\n  shows \"\\<exists>n<card S. enumerate S n = s\"\n  using s S\nproof (induction s arbitrary: S rule: less_induct)\n  case (less s)\n  show ?case\n  proof (cases \"\\<exists>y\\<in>S. y < s\")\n    case True\n    let ?T = \"S \\<inter> {..<s}\"\n    have \"finite ?T\"\n      using less.prems(2) by blast\n    have TS: \"card ?T < card S\"\n      using less.prems by (blast intro: psubset_card_mono [OF \\<open>finite S\\<close>])\n    from True have y: \"\\<And>x. Max ?T < x \\<longleftrightarrow> (\\<forall>s'\\<in>S. s' < s \\<longrightarrow> s' < x)\"\n      by (subst Max_less_iff) (auto simp: \\<open>finite ?T\\<close>)\n    then have y_in: \"Max ?T \\<in> {s'\\<in>S. s' < s}\"\n      using Max_in \\<open>finite ?T\\<close> by fastforce\n    with less.IH[of \"Max ?T\" ?T] obtain n where n: \"enumerate ?T n = Max ?T\" \"n < card ?T\"\n      using \\<open>finite ?T\\<close> by blast\n    then have \"Suc n < card S\"\n      using TS less_trans_Suc by blast\n    with S n have \"enumerate S (Suc n) = s\"\n      by (subst finite_enumerate_Suc'') (auto simp: y finite_enumerate_initial_segment less finite_enumerate_Suc'' intro!: Least_equality)\n    then show ?thesis\n      using \\<open>Suc n < card S\\<close> by blast\n  next\n    case False\n    then have \"\\<forall>t\\<in>S. s \\<le> t\" by auto\n    moreover have \"0 < card S\"\n      using card_0_eq less.prems by blast\n    ultimately show ?thesis\n      using \\<open>s \\<in> S\\<close>\n      by (auto intro!: exI[of _ 0] Least_equality simp: enumerate_0)\n  qed\nqed\n\nlemma finite_enum_subset:\n  assumes \"\\<And>i. i < card X \\<Longrightarrow> enumerate X i = enumerate Y i\" and \"finite X\" \"finite Y\" \"card X \\<le> card Y\"\n  shows \"X \\<subseteq> Y\"\n  by (metis assms finite_enumerate_Ex finite_enumerate_in_set less_le_trans subsetI)\n\nlemma finite_enum_ext:\n  assumes \"\\<And>i. i < card X \\<Longrightarrow> enumerate X i = enumerate Y i\" and \"finite X\" \"finite Y\" \"card X = card Y\"\n  shows \"X = Y\"\n  by (intro antisym finite_enum_subset) (auto simp: assms)\n\nlemma finite_bij_enumerate:\n  fixes S :: \"'a::wellorder set\"\n  assumes S: \"finite S\"\n  shows \"bij_betw (enumerate S) {..<card S} S\"\nproof -\n  have \"\\<And>n m. \\<lbrakk>n \\<noteq> m; n < card S; m < card S\\<rbrakk> \\<Longrightarrow> enumerate S n \\<noteq> enumerate S m\"\n    using finite_enumerate_mono[OF _ \\<open>finite S\\<close>] by (auto simp: neq_iff)\n  then have \"inj_on (enumerate S) {..<card S}\"\n    by (auto simp: inj_on_def)\n  moreover have \"\\<forall>s \\<in> S. \\<exists>i<card S. enumerate S i = s\"\n    using finite_enumerate_Ex[OF S] by auto\n  moreover note \\<open>finite S\\<close>\n  ultimately show ?thesis\n    unfolding bij_betw_def by (auto intro: finite_enumerate_in_set)\nqed\n\nlemma ex_bij_betw_strict_mono_card:\n  fixes M :: \"'a::wellorder set\"\n  assumes \"finite M\" \n  obtains h where \"bij_betw h {..<card M} M\" and \"strict_mono_on {..<card M} h\"\nproof\n  show \"bij_betw (enumerate M) {..<card M} M\"\n    by (simp add: assms finite_bij_enumerate)\n  show \"strict_mono_on {..<card M} (enumerate M)\"\n    by (simp add: assms finite_enumerate_mono strict_mono_on_def)\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Infinite_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970748488297, "lm_q2_score": 0.8791467706759584, "lm_q1q2_score": 0.774349903974179}}
{"text": "chapter {* R4: Cuantificadores sobre listas *}\n\ntheory R4_Cuantificadores_sobre_listas\nimports Main\nbegin\n\ntext {* \n  --------------------------------------------------------------------- \n  Ejercicio 1. Definir la función \n     todos :: ('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\n  tal que (todos p xs) se verifica si todos los elementos de la lista \n  xs cumplen la propiedad p. Por ejemplo, se verifica \n     todos (\\<lambda>x. 1<length x) [[2,1,4],[1,3]]\n     \\<not>todos (\\<lambda>x. 1<length x) [[2,1,4],[3]]\n\n  Nota: La función todos es equivalente a la predefinida list_all. \n  --------------------------------------------------------------------- \n*}\n\nfun todos :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"todos p [] = True\"\n| \"todos p (x#xs) = (p x \\<and> todos p xs)\"\n\ntext {* \n  --------------------------------------------------------------------- \n  Ejercicio 2. Definir la función \n     algunos :: ('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\n  tal que (algunos p xs) se verifica si algunos elementos de la lista \n  xs cumplen la propiedad p. Por ejemplo, se verifica \n     algunos (\\<lambda>x. 1<length x) [[2,1,4],[3]]\n     \\<not>algunos (\\<lambda>x. 1<length x) [[],[3]]\"\n\n  Nota: La función algunos es equivalente a la predefinida list_ex. \n  --------------------------------------------------------------------- \n*}\n\nfun algunos :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n   \"algunos p []     = False\"\n| \"algunos p (x#xs) = (p x \\<or> algunos p xs)\"\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 3.1. Demostrar o refutar automáticamente \n     todos (\\<lambda>x. P x \\<and> Q x) xs = (todos P xs \\<and> todos Q xs)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"todos (\\<lambda>x. P x \\<and> Q x) xs = (todos P xs \\<and> todos Q xs)\"\nby (induct xs) auto\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 3.2. Demostrar o refutar detalladamente\n     todos (\\<lambda>x. P x \\<and> Q x) xs = (todos P xs \\<and> todos Q xs)\n  --------------------------------------------------------------------- \n*}\n\n\nlemma \"todos (\\<lambda>x. P x \\<and> Q x) xs = (todos P xs \\<and> todos Q xs)\"\nproof (induct xs)\n  show \"todos (\\<lambda>x. P x \\<and> Q x) [] = (todos P [] \\<and> todos Q [])\" by simp\nnext\n  fix a xs\n  assume HI: \"todos (\\<lambda>x. P x \\<and> Q x) xs = (todos P xs \\<and> todos Q xs)\" \n  have \"todos (\\<lambda>x. P x \\<and> Q x) (a # xs) =  ((P a \\<and> Q a) \\<and> (todos P xs \\<and> todos Q xs))\" using HI by simp\n  also have \"... = ((P a \\<and> todos P xs) \\<and> (Q a \\<and> todos Q xs))\" by blast\n  also have \"... = (todos P (a#xs) \\<and> todos Q (a#xs)) \" by simp\n finally show \"todos (\\<lambda>x. P x \\<and> Q x) (a#xs) = (todos P (a#xs) \\<and> todos Q (a#xs))\" by simp \nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 4.1. Demostrar o refutar automáticamente\n     todos P (x @ y) = (todos P x \\<and> todos P y)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"todos P (x @ y) = (todos P x \\<and> todos P y)\"\nby (induct x) auto\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 4.2. Demostrar o refutar detalladamente\n     todos P (x @ y) = (todos P x \\<and> todos P y)\n  --------------------------------------------------------------------- \n*}\n\nlemma todos_append: \"todos P (x @ y) = (todos P x \\<and> todos P y)\"\nproof (induct x)\n  show \"todos P ([] @ y) = (todos P [] \\<and> todos P y)\" by simp\nnext \n  fix a x\n  assume HI: \"todos P (x @ y) = (todos P x \\<and> todos P y)\"\n  have \"todos P ((a#x) @ y) = (P a \\<and> (todos P (x @ y)))\" by simp\n  also have \"... = (P a \\<and> (todos P x \\<and> todos P y))\" using HI by simp\n  finally show \"todos P ((a # x) @ y) = (todos P (a # x) \\<and> todos P y)\" by simp\nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 5.1. Demostrar o refutar automáticamente \n     todos P (rev xs) = todos P xs\n  --------------------------------------------------------------------- \n*}\n\nlemma \"todos P (rev xs) = todos P xs\" \napply (induct xs)\napply simp\napply (simp add: todos_append)\napply auto\ndone\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 5.2. Demostrar o refutar detalladamente\n     todos P (rev xs) = todos P xs\n  --------------------------------------------------------------------- \n*}\n\nlemma \"todos P (rev xs) = todos P xs\"\nproof (induct xs)\nshow \"todos P (rev []) = todos P []\" by simp\nnext\nfix a xs\n  assume HI: \"todos P (rev xs) = todos P xs\"\n  have \"todos P (rev (a # xs)) = (todos P ((rev xs)@[a]))\" by simp\n  also have \"... = (todos P (rev xs) \\<and> todos P [a])\" by (simp add:todos_append)\n  also have \"... = (todos P xs \\<and> P a)\" using HI by simp\n  also have \"... = (P a \\<and> todos P xs)\" by arith\n  also have \"... = (todos P (a#xs))\" by simp\n  finally show \"todos P (rev (a # xs)) = (todos P (a#xs))\" by simp    \nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 6. Demostrar o refutar:\n    algunos (\\<lambda>x. P x \\<and> Q x) xs = (algunos P xs \\<and> algunos Q xs)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos (\\<lambda>x. P x \\<and> Q x) xs = (algunos P xs \\<and> algunos Q xs)\"\nquickcheck\noops\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 7.1. Demostrar o refutar automáticamente \n     algunos P (map f xs) = algunos (P \\<circ> f) xs\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P (map f xs) = algunos (P o f) xs\"\napply (induct xs)\napply auto\ndone\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 7.2. Demostrar o refutar datalladamente\n     algunos P (map f xs) = algunos (P \\<circ> f) xs\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P (map f xs) = algunos (P o f) xs\"\nproof (induct xs)\n  show \"algunos P (map f []) = algunos (P \\<circ> f) []\"  by simp\nnext\n  fix a xs\n  assume H1: \"algunos P (map f xs) = algunos (P \\<circ> f) xs\"\n  have  \"algunos P (map f (a # xs)) = (algunos P (map f [a]) \\<or> algunos P (map f xs))\" by simp\n  also have \"\\<dots> = (algunos (P \\<circ> f) [a] \\<or>  algunos (P \\<circ> f) xs )\" using H1 by simp\n  also have \"\\<dots> = algunos (P \\<circ> f) (a#xs)\" by simp\n  finally show \"algunos P (map f (a # xs)) = algunos (P \\<circ> f) (a#xs)\" by simp\nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 8.1. Demostrar o refutar automáticamente \n     algunos P (xs @ ys) = (algunos P xs \\<or> algunos P ys)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P (xs @ ys) = (algunos P xs \\<or> algunos P ys)\"\nby (induct xs) auto\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 8.2. Demostrar o refutar detalladamente\n     algunos P (xs @ ys) = (algunos P xs \\<or> algunos P ys)\n  --------------------------------------------------------------------- \n*}\n\nlemma algunos_append: \"algunos P (xs @ ys) = (algunos P xs \\<or> algunos P ys)\"\nproof (induct xs)\n  show \"algunos P ([] @ ys) = (algunos P [] \\<or> algunos P ys)\" by simp\nnext \n  fix a xs\n  assume HI: \"algunos P (xs @ ys) = (algunos P xs \\<or> algunos P ys)\"\n  have \"algunos P ((a # xs) @ ys) = (P a \\<or> (algunos P (xs @ ys)))\" by simp\n  also have \"... = (P a \\<or> (algunos P xs \\<or> algunos P ys))\" using HI by simp\n  finally show \"algunos P ((a # xs) @ ys) = (algunos P (a # xs) \\<or> algunos P ys)\" by simp\nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 9.1. Demostrar o refutar automáticamente\n     algunos P (rev xs) = algunos P xs\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P (rev xs) = algunos P xs\"\napply (induct xs)\napply simp\napply (simp add: algunos_append)\napply auto\ndone\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 9.2. Demostrar o refutar detalladamente\n     algunos P (rev xs) = algunos P xs\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P (rev xs) = algunos P xs\"\nproof (induct xs)\n  show \"algunos P (rev []) = algunos P []\" by simp\nnext\n  fix a xs\n  assume HI:\"algunos P (rev xs) = algunos P xs\"\n  have \"algunos P (rev (a # xs)) = algunos P ((rev xs) @ [a])\" by simp\n  also have \"... = ((algunos P (rev xs)) \\<or> (algunos P [a]))\" by (simp add: algunos_append)\n  also have \"... = ((algunos P xs) \\<or> (algunos P [a]))\" using HI by simp\n  also have \"... = ((algunos P [a]) \\<or> (algunos P xs))\" by arith\n  finally show \"algunos P (rev (a # xs)) = algunos P (a # xs)\" by simp\nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 10. Encontrar un término no trivial Z tal que sea cierta la \n  siguiente ecuación:\n     algunos (\\<lambda>x. P x \\<or> Q x) xs = Z\n  y demostrar la equivalencia de forma automática y detallada.\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos (\\<lambda>x. P x \\<or> Q x) xs = (algunos P xs \\<or> algunos Q xs)\"\nby (induct xs) auto\n\nlemma \"algunos (\\<lambda>x. P x \\<or> Q x) xs = (algunos P xs \\<or> algunos Q xs) \"\nproof (induct xs)\n  show \"algunos (\\<lambda>x. P x \\<or> Q x) [] = (algunos P [] \\<or> algunos Q []) \" by simp\nnext\n  fix a xs\n  assume HI: \" algunos (\\<lambda>x. P x \\<or> Q x) xs = (algunos P xs \\<or> algunos Q xs)\"\n  have \" algunos (\\<lambda>x. P x \\<or> Q x) (a # xs) = ( P a \\<or> Q a \\<or> algunos (\\<lambda>x. P x \\<or> Q x) xs)\" by simp\n  also have \"... = (P a \\<or> Q a \\<or> (algunos P xs \\<or> algunos Q xs))\" using HI by simp\n  also have \"\\<dots> = (((P a) \\<or> algunos P xs) \\<or> ((Q a) \\<or> algunos Q xs))\" by arith \n  also have \"\\<dots> = (algunos P (a#xs) \\<or> algunos Q (a#xs))\" by simp\n  finally show \"algunos (\\<lambda>x. P x \\<or> Q x) (a # xs) = (algunos P (a # xs) \\<or> algunos Q (a # xs)) \" by simp\nqed\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 11.1. Demostrar o refutar automáticamente\n     algunos P xs = (\\<not> todos (\\<lambda>x. (\\<not> P x)) xs)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P xs = (\\<not> todos (\\<lambda>x. (\\<not> P x)) xs)\"\nby (induct xs) auto\n     \ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 11.2. Demostrar o refutar datalladamente\n     algunos P xs = (\\<not> todos (\\<lambda>x. (\\<not> P x)) xs)\n  --------------------------------------------------------------------- \n*}\n\nlemma \"algunos P xs = (\\<not> todos (\\<lambda>x. (\\<not> P x)) xs)\"\nproof (induct xs)\n  show \"algunos P [] = (\\<not> todos (\\<lambda>x. \\<not> P x) [])\" by simp\nnext \n  fix a xs\n  assume HI: \"algunos P xs = (\\<not> todos (\\<lambda>x. \\<not> P x) xs)\"\n  have \"algunos P (a # xs) = (P a \\<or> (algunos P xs))\" by simp\n  also have \"... = (P a \\<or> (\\<not> todos (\\<lambda>x. \\<not> P x) xs))\" using HI by simp\n  finally show \"algunos P (a # xs) = (\\<not> todos (\\<lambda>x. \\<not> P x) (a # xs))\" by simp\nqed\n     \ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 12. Definir la funcion primitiva recursiva \n     estaEn :: 'a \\<Rightarrow> 'a list \\<Rightarrow> bool\n  tal que (estaEn x xs) se verifica si el elemento x está en la lista\n  xs. Por ejemplo, \n     estaEn (2::nat) [3,2,4] = True\n     estaEn (1::nat) [3,2,4] = False\n  --------------------------------------------------------------------- \n*}\n\nfun estaEn :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"estaEn x [] = False\"\n| \"estaEn x (a#xs) = ((a = x) \\<or> (estaEn x xs))\"\n\ntext {*\n  --------------------------------------------------------------------- \n  Ejercicio 13. Expresar la relación existente entre estaEn y algunos. \n  Demostrar dicha relación de forma automática y detallada.\n  --------------------------------------------------------------------- \n*}\n\nlemma \"estaEn a xs = algunos (\\<lambda>x. x = a) xs\"\nby (induct xs) auto\n\nlemma \"estaEn x xs = (algunos (\\<lambda>a. a=x) xs)\" \nproof (induct xs)\n  show \" estaEn x [] = algunos (\\<lambda>a. a = x) []\" by simp\nnext\n  fix a xs\n  assume HI: \"estaEn x xs = algunos (\\<lambda>a. a = x) xs\"\n  have \"estaEn x (a # xs) = (a = x \\<or> estaEn x xs)\" by simp\n  also have \"... = (a = x \\<or> algunos (\\<lambda>a. a = x) xs)\" using HI by simp\n  finally show \" estaEn x (a # xs) = algunos (\\<lambda>a. a = x) (a # xs)\" by simp\nqed\n\nend", "meta": {"author": "serrodcal-MULCIA", "repo": "RAIsabelleHOL", "sha": "2f551971b248b3dac6009d09b74f5b3e16e0d12f", "save_path": "github-repos/isabelle/serrodcal-MULCIA-RAIsabelleHOL", "path": "github-repos/isabelle/serrodcal-MULCIA-RAIsabelleHOL/RAIsabelleHOL-2f551971b248b3dac6009d09b74f5b3e16e0d12f/R4_Cuantificadores_sobre_listas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8791467564270272, "lm_q1q2_score": 0.7743498996764516}}
{"text": "section \\<open>Basis Extension\\<close>\n\ntext \\<open>We prove that every linear indepent set/list of vectors can be extended into a basis.\n  Similarly, from every set of vectors one can extract a linear independent set of vectors\n  that spans the same space.\\<close>\n\ntheory Basis_Extension\n  imports\n    LLL_Basis_Reduction.Gram_Schmidt_2\nbegin\n\n\ncontext cof_vec_space\nbegin\n\nlemma lin_indpt_list_length_le_n: assumes \"lin_indpt_list xs\"\n  shows \"length xs \\<le> n\"\nproof -\n  from assms[unfolded lin_indpt_list_def]\n  have xs: \"set xs \\<subseteq> carrier_vec n\" and dist: \"distinct xs\" and lin: \"lin_indpt (set xs)\" by auto\n  from dist have \"card (set xs) = length xs\" by (rule distinct_card)\n  moreover have \"card (set xs) \\<le> n\"\n    using lin xs dim_is_n li_le_dim(2) by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma lin_indpt_list_length_eq_n: assumes \"lin_indpt_list xs\"\n  and \"length xs = n\"\nshows \"span (set xs) = carrier_vec n\" \"basis (set xs)\"\nproof -\n  from assms[unfolded lin_indpt_list_def]\n  have xs: \"set xs \\<subseteq> carrier_vec n\" and dist: \"distinct xs\" and lin: \"lin_indpt (set xs)\" by auto\n  from dist have \"card (set xs) = length xs\" by (rule distinct_card)\n  with assms have \"card (set xs) = n\" by auto\n  with lin xs show \"span (set xs) = carrier_vec n\" \"basis (set xs)\"  using dim_is_n\n    by (metis basis_def dim_basis dim_li_is_basis fin_dim finite_basis_exists gen_ge_dim li_le_dim(1))+\nqed\n\nlemma expand_to_basis: assumes lin: \"lin_indpt_list xs\"\n  shows \"\\<exists> ys. set ys \\<subseteq> set (unit_vecs n) \\<and> lin_indpt_list (xs @ ys) \\<and> length (xs @ ys) = n\"\nproof -\n  define y where \"y = n - length xs\"\n  from lin have \"length xs \\<le> n\" by (rule lin_indpt_list_length_le_n)\n  hence \"length xs + y = n\" unfolding y_def by auto\n  thus \"\\<exists> ys. set ys \\<subseteq> set (unit_vecs n) \\<and> lin_indpt_list (xs @ ys) \\<and> length (xs @ ys) = n\"\n    using lin\n  proof (induct y arbitrary: xs)\n    case (0 xs)\n    thus ?case by (intro exI[of _ Nil], auto)\n  next\n    case (Suc y xs)\n    hence \"length xs < n\" by auto\n    from Suc(3)[unfolded lin_indpt_list_def]\n    have xs: \"set xs \\<subseteq> carrier_vec n\" and dist: \"distinct xs\" and lin: \"lin_indpt (set xs)\" by auto\n    from distinct_card[OF dist] Suc(2) have card: \"card (set xs) < n\" by auto\n    have \"span (set xs) \\<noteq> carrier_vec n\" using card dim_is_n xs basis_def dim_basis lin by auto\n    with span_closed[OF xs] have \"span (set xs) \\<subset> carrier_vec n\" by auto\n    also have \"carrier_vec n = span (set (unit_vecs n))\"\n      unfolding span_unit_vecs_is_carrier ..\n    finally have sub: \"span (set xs) \\<subset> span (set (unit_vecs n))\" .\n    have \"\\<exists> u. u \\<in> set (unit_vecs n) \\<and> u \\<notin> span (set xs)\"\n      using span_subsetI[OF xs, of \"set (unit_vecs n)\"] sub by force\n    then obtain u where uu: \"u \\<in> set (unit_vecs n)\" and usxs: \"u \\<notin> span (set xs)\" by auto\n    then have u: \"u \\<in> carrier_vec n\" unfolding unit_vecs_def by auto\n    let ?xs = \"xs @ [u]\"\n    from span_mem[OF xs, of u] usxs have uxs: \"u \\<notin> set xs\" by auto\n    with dist have dist: \"distinct ?xs\" by auto\n    have lin: \"lin_indpt (set ?xs)\" using lin_dep_iff_in_span[OF xs lin u uxs] usxs by auto\n    from lin dist u xs have lin: \"lin_indpt_list ?xs\" unfolding lin_indpt_list_def by auto\n    from Suc(2) have \"length ?xs + y = n\" by auto\n    from Suc(1)[OF this lin] obtain ys where\n      \"set ys \\<subseteq> set (unit_vecs n)\" \"lin_indpt_list (?xs @ ys)\" \"length (?xs @ ys) = n\" by auto\n    thus ?case using uu\n      by (intro exI[of _ \"u # ys\"], auto)\n  qed\nqed\n\ndefinition \"basis_extension xs = (SOME ys.\n  set ys \\<subseteq> set (unit_vecs n) \\<and> lin_indpt_list (xs @ ys) \\<and> length (xs @ ys) = n)\"\n\nlemma basis_extension: assumes \"lin_indpt_list xs\"\n  shows \"set (basis_extension xs) \\<subseteq> set (unit_vecs n)\"\n    \"lin_indpt_list (xs @ basis_extension xs)\"\n    \"length (xs @ basis_extension xs) = n\"\n  using someI_ex[OF expand_to_basis[OF assms], folded basis_extension_def] by auto\n\nlemma exists_lin_indpt_sublist: assumes X: \"X \\<subseteq> carrier_vec n\"\n  shows \"\\<exists> Ls. lin_indpt_list Ls \\<and> span (set Ls) = span X \\<and> set Ls \\<subseteq> X\"\nproof -\n  let ?T = ?thesis\n  have \"(\\<exists> Ls. lin_indpt_list Ls \\<and> span (set Ls) \\<subseteq> span X \\<and> set Ls \\<subseteq> X \\<and> length Ls = k) \\<or> ?T\" for k\n  proof (induct k)\n    case 0\n    have \"lin_indpt {}\" by (simp add: lindep_span)\n    thus ?case using span_is_monotone by (auto simp: lin_indpt_list_def)\n  next\n    case (Suc k)\n    show ?case\n    proof (cases ?T)\n      case False\n      with Suc obtain Ls where lin: \"lin_indpt_list Ls\"\n        and span: \"span (set Ls) \\<subseteq> span X\" and Ls: \"set Ls \\<subseteq> X\"  and len: \"length Ls = k\" by auto\n      from Ls X have LsC: \"set Ls \\<subseteq> carrier_vec n\" by auto\n      show ?thesis\n      proof (cases \"X \\<subseteq> span (set Ls)\")\n        case True\n        hence \"span X \\<subseteq> span (set Ls)\" using LsC X by (metis span_subsetI)\n        with span have \"span (set Ls) = span X\" by auto\n        hence ?T by (intro exI[of _ Ls] conjI True lin Ls)\n        thus ?thesis by auto\n      next\n        case False\n        with span obtain x where xX: \"x \\<in> X\" and xSLs: \"x \\<notin> span (set Ls)\" by auto\n        from Ls X have LsC: \"set Ls \\<subseteq> carrier_vec n\" by auto\n        from span_mem[OF this, of x] xSLs have xLs: \"x \\<notin> set Ls\" by auto\n        let ?Ls = \"x # Ls\"\n        show ?thesis\n        proof (intro disjI1 exI[of _ ?Ls] conjI)\n          show \"length ?Ls = Suc k\" using len by auto\n          show \"lin_indpt_list ?Ls\" using lin xSLs xLs unfolding lin_indpt_list_def\n            using lin_dep_iff_in_span[OF LsC _ _ xLs] xX X by auto\n          show \"set ?Ls \\<subseteq> X\" using xX Ls by auto\n          from span_is_monotone[OF this]\n          show \"span (set ?Ls) \\<subseteq> span X\" .\n        qed\n      qed\n    qed auto\n  qed\n  from this[of \"n + 1\"] lin_indpt_list_length_le_n show ?thesis by fastforce\nqed\n\nlemma exists_lin_indpt_subset: assumes \"X \\<subseteq> carrier_vec n\"\n  shows \"\\<exists> Ls. lin_indpt Ls \\<and> span (Ls) = span X \\<and> Ls \\<subseteq> X\"\nproof -\n  from exists_lin_indpt_sublist[OF assms]\n  obtain Ls where \"lin_indpt_list Ls \\<and> span (set Ls) = span X \\<and> set Ls \\<subseteq> X\" by auto\n  thus ?thesis by (intro exI[of _ \"set Ls\"], auto simp: lin_indpt_list_def)\nqed\nend\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Linear_Inequalities/Basis_Extension.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7743498914618472}}
{"text": "(*\n  File:     Random_BSTs.thy\n  Author:   Manuel Eberl <eberlm@in.tum.de>\n\n  Expected shape of random Binary Search Trees\n*)\nsection \\<open>Expected shape of random Binary Search Trees\\<close>\ntheory Random_BSTs\n  imports\n    Complex_Main\n    \"HOL-Probability.Random_Permutations\"\n    \"HOL-Data_Structures.Tree_Set\"\n    Quick_Sort_Cost.Quick_Sort_Average_Case\nbegin\n\n(* TODO: Hide this in the proper place *)\nhide_const (open) Tree_Set.insert\n\nsubsection \\<open>Auxiliary lemmas\\<close>\n\n(* TODO: Move? *)\nlemma linorder_on_linorder_class [intro]:\n  \"linorder_on UNIV {(x, y). x \\<le> (y :: 'a :: linorder)}\"\n  by (auto simp: linorder_on_def refl_on_def antisym_def trans_def total_on_def)\n\nlemma Nil_in_permutations_of_set_iff [simp]: \"[] \\<in> permutations_of_set A \\<longleftrightarrow> A = {}\"\n  by (auto simp: permutations_of_set_def)\n\nlemma max_power_distrib_right:\n  fixes a :: \"'a :: linordered_semidom\"\n  shows \"a > 1 \\<Longrightarrow> max (a ^ b) (a ^ c) = a ^ max b c\"\n  by (auto simp: max_def)\n\nlemma set_tree_empty_iff [simp]: \"set_tree t = {} \\<longleftrightarrow> t = Leaf\"\n  by (cases t) auto\n\nlemma card_set_tree_bst: \"bst t \\<Longrightarrow> card (set_tree t) = size t\"\nproof (induction t)\n  case (Node l x r)\n  have \"set_tree \\<langle>l, x, r\\<rangle> = insert x (set_tree l \\<union> set_tree r)\" by simp\n  also from Node.prems have \"card \\<dots> = Suc (card (set_tree l \\<union> set_tree r))\"\n    by (intro card_insert_disjoint) auto\n  also from Node have \"card (set_tree l \\<union> set_tree r) = size l + size r\"\n    by (subst card_Un_disjoint) force+\n  finally show ?case by simp\nqed simp_all\n\nlemma pair_pmf_cong:\n  \"p = p' \\<Longrightarrow> q = q' \\<Longrightarrow> pair_pmf p q = pair_pmf p' q'\"\n  by simp\n\nlemma expectation_add_pair_pmf:\n  fixes f :: \"'a \\<Rightarrow> 'c::{banach, second_countable_topology}\"\n  assumes \"finite (set_pmf p)\" and \"finite (set_pmf q)\"\n  shows \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>(x,y). f x + g y) =\n           measure_pmf.expectation p f + measure_pmf.expectation q g\"\nproof -\n  have \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>(x,y). f x + g y) =\n          measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. f (fst z) + g (snd z))\"\n    by (simp add: case_prod_unfold)\n  also have \"\\<dots> = measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. f (fst z)) +\n                  measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. g (snd z))\"\n    by (intro Bochner_Integration.integral_add integrable_measure_pmf_finite) (auto intro: assms)\n  also have \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. f (fst z)) =\n               measure_pmf.expectation (map_pmf fst (pair_pmf p q)) f\" by simp\n  also have \"map_pmf fst (pair_pmf p q) = p\" by (rule map_fst_pair_pmf)\n  also have \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. g (snd z)) =\n               measure_pmf.expectation (map_pmf snd (pair_pmf p q)) g\" by simp\n  also have \"map_pmf snd (pair_pmf p q) = q\" by (rule map_snd_pair_pmf)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Creating a BST from a list\\<close>\n\ntext \\<open>\n  The following recursive function creates a binary search tree from a given list of\n  elements by inserting them into an initially empty BST from left to right. We will prove\n  that this is the case later, but the recursive definition has the advantage of giving us\n  a useful induction rule, so we chose that definition and prove the alternative definitions later.\n\n  This recursion, which already almost looks like QuickSort, will be key in analysing the\n  shape distributions of random BSTs.\n\\<close>\nfun bst_of_list :: \"'a :: linorder list \\<Rightarrow> 'a tree\" where\n  \"bst_of_list [] = Leaf\"\n| \"bst_of_list (x # xs) =\n     Node (bst_of_list [y \\<leftarrow> xs. y < x]) x (bst_of_list [y \\<leftarrow> xs. y > x])\"\n\nlemma bst_of_list_eq_Leaf_iff [simp]: \"bst_of_list xs = Leaf \\<longleftrightarrow> xs = []\"\n  by (induction xs) auto\n\nlemma bst_of_list_snoc [simp]:\n  \"bst_of_list (xs @ [y]) = Tree_Set.insert y (bst_of_list xs)\"\n  by (induction xs rule: bst_of_list.induct) auto\n\nlemma bst_of_list_append:\n  \"bst_of_list (xs @ ys) = fold Tree_Set.insert ys (bst_of_list xs)\"\nproof (induction ys arbitrary: xs)\n  case (Cons y ys)\n  have \"bst_of_list (xs @ (y # ys)) = bst_of_list ((xs @ [y]) @ ys)\" by simp\n  also have \"\\<dots> = fold Tree_Set.insert ys (bst_of_list (xs @ [y]))\"\n    by (rule Cons.IH)\n  finally show ?case by simp\nqed simp_all\n\ntext \\<open>\n  The following now shows that the recursive function indeed corresponds to the\n  notion of inserting the elements from the list from left to right.\n\\<close>\nlemma bst_of_list_altdef: \"bst_of_list xs = fold Tree_Set.insert xs Leaf\"\n  using bst_of_list_append[of \"[]\" xs] by simp\n\nlemma size_bst_insert: \"x \\<notin> set_tree t \\<Longrightarrow> size (Tree_Set.insert x t) = Suc (size t)\"\n  by (induction t) auto\n\nlemma set_bst_insert [simp]: \"set_tree (Tree_Set.insert x t) = insert x (set_tree t)\"\n  by (induction t) auto\n\nlemma set_bst_of_list [simp]: \"set_tree (bst_of_list xs) = set xs\"\n  by (induction xs rule: rev_induct) simp_all\n\nlemma size_bst_of_list_distinct [simp]:\n  assumes \"distinct xs\"\n  shows   \"size (bst_of_list xs) = length xs\"\n  using assms by (induction xs rule: rev_induct) (auto simp: size_bst_insert)\n\nlemma strict_mono_on_imp_less_iff:\n  assumes \"strict_mono_on f A\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"f x < (f y :: 'b :: linorder) \\<longleftrightarrow> x < (y :: 'a :: linorder)\"\n  using assms by (cases x y rule: linorder_cases; force simp: strict_mono_on_def)+\n\nlemma bst_of_list_map: \n  fixes f :: \"'a :: linorder \\<Rightarrow> 'b :: linorder\"\n  assumes \"strict_mono_on f A\" \"set xs \\<subseteq> A\"\n  shows   \"bst_of_list (map f xs) = map_tree f (bst_of_list xs)\"\n  using assms\nproof (induction xs rule: bst_of_list.induct)\n  case (2 x xs)\n  have \"[xa\\<leftarrow>xs . f xa < f x] = [xa\\<leftarrow>xs . xa < x]\" and \"[xa\\<leftarrow>xs . f xa > f x] = [xa\\<leftarrow>xs . xa > x]\"\n    using \"2.prems\" by (auto simp: strict_mono_on_imp_less_iff intro!: filter_cong)\n  with 2 show ?case by (auto simp: filter_map o_def)\nqed auto  \n\n\nsubsection \\<open>Random BSTs\\<close>\n\ntext \\<open>\n  Analogously to the previous section, we can now view the concept of a random BST\n  (i.\\,e.\\ a BST obtained by inserting a given set of elements in random order) in two\n  different ways.\n\n  We again start with the recursive variant:\n\\<close>\nfunction random_bst :: \"'a :: linorder set \\<Rightarrow> 'a tree pmf\" where\n  \"random_bst A =\n     (if \\<not>finite A \\<or> A = {} then\n        return_pmf Leaf\n      else do {\n        x \\<leftarrow> pmf_of_set A;\n        l \\<leftarrow> random_bst {y \\<in> A. y < x};\n        r \\<leftarrow> random_bst {y \\<in> A. y > x};\n        return_pmf (Node l x r)\n     })\"\n  by auto\ntermination by (relation finite_psubset) auto\n\ndeclare random_bst.simps [simp del]\n\nlemma random_bst_empty [simp]: \"random_bst {} = return_pmf Leaf\"\n  by (simp add: random_bst.simps)\n\nlemma set_pmf_random_permutation [simp]:\n  \"finite A \\<Longrightarrow> set_pmf (pmf_of_set (permutations_of_set A)) = {xs. distinct xs \\<and> set xs = A}\"\n  by (subst set_pmf_of_set) (auto dest: permutations_of_setD)\n\ntext \\<open>\n  The alternative characterisation is the more intuitive one where we simply pick a\n  random permutation of the set elements uniformly at random and insert them into an empty\n  tree from left to right:\n\\<close>\nlemma random_bst_altdef:\n  assumes \"finite A\"\n  shows   \"random_bst A = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\nusing assms\nproof (induction A rule: finite_psubset_induct)\n  case (psubset A)\n  define L R where \"L = (\\<lambda>x. {y\\<in>A. y < x})\" and \"R = (\\<lambda>x. {y\\<in>A. y > x})\"\n  {\n    fix x assume x: \"x \\<in> A\"\n    hence *: \"L x \\<subset> A\" \"R x \\<subset> A\" by (auto simp: L_def R_def)\n    note this [THEN psubset.IH]\n  } note IH = this\n\n  show ?case\n  proof (cases \"A = {}\")\n    case False\n    note A = \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    have \"random_bst A =\n            do {\n              x \\<leftarrow> pmf_of_set A;\n              (l, r) \\<leftarrow> pair_pmf (random_bst (L x)) (random_bst (R x));\n              return_pmf (Node l x r)\n            }\" using A unfolding pair_pmf_def L_def R_def\n      by (subst random_bst.simps) (simp add: bind_return_pmf bind_assoc_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (l, r) \\<leftarrow> pair_pmf\n                        (map_pmf bst_of_list (pmf_of_set (permutations_of_set (L x))))\n                        (map_pmf bst_of_list (pmf_of_set (permutations_of_set (R x))));\n                      return_pmf (Node l x r)\n                    }\"\n     using A by (intro bind_pmf_cong refl) (simp_all add: IH)\n    also have \"\\<dots> = do {\n                     x \\<leftarrow> pmf_of_set A;\n                     (ls, rs) \\<leftarrow> pair_pmf (pmf_of_set (permutations_of_set (L x)))\n                                          (pmf_of_set (permutations_of_set (R x)));\n                     return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n                   }\" unfolding map_pair [symmetric]\n      by (simp add: map_pmf_def case_prod_unfold bind_return_pmf bind_assoc_pmf)\n    also have \"L = (\\<lambda>x. {y \\<in> A - {x}. y \\<le> x})\" by (auto simp: L_def)\n    also have \"R = (\\<lambda>x. {y \\<in> A - {x}. \\<not>y \\<le> x})\" by (auto simp: R_def)\n    also have \"do {\n                 x \\<leftarrow> pmf_of_set A;\n                 (ls, rs) \\<leftarrow> pair_pmf (pmf_of_set (permutations_of_set {y \\<in> A - {x}. y \\<le> x}))\n                                      (pmf_of_set (permutations_of_set {y \\<in> A - {x}. \\<not>y \\<le> x}));\n                 return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n               } =\n               do {\n                 x \\<leftarrow> pmf_of_set A;\n                 (ls, rs) \\<leftarrow> map_pmf (partition (\\<lambda>y. y \\<le> x))\n                               (pmf_of_set (permutations_of_set (A - {x})));\n                 return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n               }\" using \\<open>finite A\\<close>\n      by (intro bind_pmf_cong refl partition_random_permutations [symmetric]) auto\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (ls, rs) \\<leftarrow> map_pmf (\\<lambda>xs. ([y\\<leftarrow>xs. y < x], [y\\<leftarrow>xs. y > x]))\n                                    (pmf_of_set (permutations_of_set (A - {x})));\n                      return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n                    }\" using A\n      by (intro bind_pmf_cong refl map_pmf_cong)\n         (auto intro!: filter_cong dest: permutations_of_setD simp: order.strict_iff_order)\n    also have \"\\<dots> = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\n      using A by (subst random_permutation_of_set[of A])\n                 (auto simp: map_pmf_def bind_return_pmf o_def bind_assoc_pmf not_le)\n    finally show ?thesis .\n  qed (simp_all add: pmf_of_set_singleton)\nqed\n\nlemma finite_set_random_bst [simp, intro]:\n  \"finite A \\<Longrightarrow> finite (set_pmf (random_bst A))\"\n  by (simp add: random_bst_altdef)\n\nlemma random_bst_code [code]:\n  \"random_bst (set xs) = map_pmf bst_of_list (pmf_of_set (permutations_of_set (set xs)))\"\n  by (rule random_bst_altdef) simp_all\n\nlemma random_bst_singleton [simp]: \"random_bst {x} = return_pmf (Node Leaf x Leaf)\"\n  by (simp add: random_bst_altdef pmf_of_set_singleton)\n\nlemma size_random_bst:\n  assumes \"t \\<in> set_pmf (random_bst A)\" \"finite A\"\n  shows   \"size t = card A\"\nproof -\n  from assms obtain xs where \"distinct xs\" \"A = set xs\" \"t = bst_of_list xs\"\n    by (auto simp: random_bst_altdef dest: permutations_of_setD)\n  thus ?thesis using \\<open>finite A\\<close> by (simp add: distinct_card)\nqed\n\nlemma random_bst_image:\n  assumes \"finite A\" \"strict_mono_on f A\"\n  shows   \"random_bst (f ` A) = map_pmf (map_tree f) (random_bst A)\"\nproof -\n  from assms(2) have inj: \"inj_on f A\" by (rule strict_mono_on_imp_inj_on)\n  with assms have \"inj_on (map f) (permutations_of_set A)\"\n    by (intro inj_on_mapI) auto\n  with assms inj have \"random_bst (f ` A) = \n                         map_pmf (\\<lambda>x. bst_of_list (map f x)) (pmf_of_set (permutations_of_set A))\"\n    by (simp add: random_bst_altdef permutations_of_set_image_inj map_pmf_of_set_inj [symmetric]\n                  pmf.map_comp o_def)\n  also have \"\\<dots> = map_pmf (map_tree f) (random_bst A)\"\n    unfolding random_bst_altdef[OF \\<open>finite A\\<close>] pmf.map_comp o_def using assms\n    by (intro map_pmf_cong refl bst_of_list_map[of f A]) (auto dest: permutations_of_setD)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  We can also re-phrase the non-recursive definition using the @{const fold_random_permutation}\n  combinator from the HOL-Probability library, which folds over a given set in random order.\n\\<close>\nlemma random_bst_altdef':\n  assumes \"finite A\"\n  shows   \"random_bst A = fold_random_permutation Tree_Set.insert Leaf A\"\nproof -\n  have \"random_bst A = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\n    using assms by (simp add: random_bst_altdef)\n  also have \"\\<dots> = map_pmf (\\<lambda>xs. fold Tree_Set.insert xs Leaf) (pmf_of_set (permutations_of_set A))\"\n    using assms by (intro map_pmf_cong refl) (auto simp: bst_of_list_altdef)\n  also from assms have \"\\<dots> = fold_random_permutation Tree_Set.insert Leaf A\"\n    by (simp add: fold_random_permutation_fold)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Expected height\\<close>\n\ntext \\<open>\n  For the purposes of the analysis of the expected height, we define the following notion\n  of `expected height', which is essentially two to the power of the height (as defined\n  by Cormen \\textit{et al.}) with a special treatment for the empty tree, which has exponential\n  height 0.\n\n  Note that the height defined by Cormen \\textit{et al.}\\ differs from the @{const height}\n  function here in Isabelle in that for them, the height of the empty tree is undefined and\n  the height of a singleton tree is 0 etc., whereas in Isabelle, the height of the empty tree is\n  0 and the height of a singleton tree is 1.\n\\<close>\ndefinition eheight :: \"'a tree \\<Rightarrow> nat\" where\n  \"eheight t = (if t = Leaf then 0 else 2 ^ (height t - 1))\"\n\nlemma eheight_Leaf [simp]: \"eheight Leaf = 0\"\n  by (simp add: eheight_def)\n\nlemma eheight_Node_singleton [simp]: \"eheight (Node Leaf x Leaf) = 1\"\n  by (simp add: eheight_def)\n\nlemma eheight_Node:\n  \"l \\<noteq> Leaf \\<or> r \\<noteq> Leaf \\<Longrightarrow> eheight (Node l x r) = 2 * max (eheight l) (eheight r)\"\n  by (cases l; cases r) (simp_all add: eheight_def max_power_distrib_right)\n\n\nfun eheight_rbst :: \"nat \\<Rightarrow> nat pmf\" where\n  \"eheight_rbst 0 = return_pmf 0\"\n| \"eheight_rbst (Suc 0) = return_pmf 1\"\n| \"eheight_rbst (Suc n) =\n     do {\n       k \\<leftarrow> pmf_of_set {..n};\n       h1 \\<leftarrow> eheight_rbst k;\n       h2 \\<leftarrow> eheight_rbst (n - k);\n       return_pmf (2 * max h1 h2)}\"\n\ndefinition eheight_exp :: \"nat \\<Rightarrow> real\" where\n  \"eheight_exp n = measure_pmf.expectation (eheight_rbst n) real\"\n\nlemma eheight_rbst_reduce:\n  assumes \"n > 1\"\n  shows   \"eheight_rbst n =\n             do {k \\<leftarrow> pmf_of_set {..<n}; h1 \\<leftarrow> eheight_rbst k; h2 \\<leftarrow> eheight_rbst (n - k - 1);\n                 return_pmf (2 * max h1 h2)}\"\n  using assms by (cases n rule: eheight_rbst.cases) (simp_all add: lessThan_Suc_atMost)\n\nlemma Leaf_in_set_random_bst_iff:\n  assumes \"finite A\"\n  shows   \"Leaf \\<in> set_pmf (random_bst A) \\<longleftrightarrow> A = {}\"\nproof\n  assume \"Leaf \\<in> set_pmf (random_bst A)\"\n  from size_random_bst[OF this] and assms show \"A = {}\" by auto\nqed auto  \n\n\n\n    hence \"map_pmf eheight (random_bst A) = \n             do {\n               x \\<leftarrow> pmf_of_set A;\n               l \\<leftarrow> random_bst {y \\<in> A. y < x};\n               r \\<leftarrow> random_bst {y \\<in> A. y > x};\n               return_pmf (eheight (Node l x r))\n             }\"\n      using \\<open>finite A\\<close> by (subst random_bst.simps) (auto simp: map_bind_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l \\<leftarrow> random_bst {y \\<in> A. y < x};\n                      r \\<leftarrow> random_bst {y \\<in> A. y > x};\n                      return_pmf (2 * max (eheight l) (eheight r))\n                    }\"\n      using 3 \\<open>finite A\\<close> exists_other\n      by (intro bind_pmf_cong refl, subst eheight_Node)\n         (force simp: Leaf_in_set_random_bst_iff not_less nonempty eheight_Node)+\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      h1 \\<leftarrow> map_pmf eheight (random_bst {y \\<in> A. y < x});\n                      h2 \\<leftarrow> map_pmf eheight (random_bst {y \\<in> A. y > x});\n                      return_pmf (2 * max h1 h2)\n                    }\"\n      by (simp add: bind_map_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      h1 \\<leftarrow> eheight_rbst (card {y \\<in> A. y < x});\n                      h2 \\<leftarrow> eheight_rbst (card {y \\<in> A. y > x});\n                      return_pmf (2 * max h1 h2)\n                    }\"\n      using \\<open>A \\<noteq> {}\\<close> \\<open>finite A\\<close> by (intro bind_pmf_cong psubset.IH [symmetric] refl) auto\n    also have \"\\<dots> = do {\n                      k \\<leftarrow> map_pmf rank (pmf_of_set A);\n                      h1 \\<leftarrow> eheight_rbst k;\n                      h2 \\<leftarrow> eheight_rbst (card A - k - 1);\n                      return_pmf (2 * max h1 h2)\n                    }\"\n      unfolding bind_map_pmf\n    proof (intro bind_pmf_cong refl, goal_cases)\n      case (1 x)\n      have \"rank x = card {y\\<in>A-{x}. y \\<le> x}\" by (simp add: rank_def linorder_rank_def)\n      also have \"{y\\<in>A-{x}. y \\<le> x} = {y\\<in>A. y < x}\" by auto\n      finally show ?case by simp\n    next\n      case (2 x)\n      have \"A - {x} = {y\\<in>A-{x}. y \\<le> x} \\<union> {y\\<in>A. y > x}\" by auto\n      also have \"card \\<dots> = rank x + card {y\\<in>A. y > x}\"\n        using \\<open>finite A\\<close> by (subst card_Un_disjoint) (auto simp: rank_def linorder_rank_def)\n      finally have \"card {y\\<in>A. y > x} = card A - rank x - 1\"\n        using 2 \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> by simp\n      thus ?case by simp\n    qed\n    also have \"map_pmf rank (pmf_of_set A) = pmf_of_set {..<card A}\"\n      using \\<open>A \\<noteq> {}\\<close> \\<open>finite A\\<close> unfolding rank_def\n      by (intro map_pmf_of_set_bij_betw bij_betw_linorder_rank[of UNIV]) auto\n    also have \"do {\n                 k \\<leftarrow> pmf_of_set {..<card A};\n                 h1 \\<leftarrow> eheight_rbst k;\n                 h2 \\<leftarrow> eheight_rbst (card A - k - 1);\n                 return_pmf (2 * max h1 h2)\n               } = eheight_rbst (card A)\"\n      by (rule eheight_rbst_reduce [symmetric]) fact+\n    finally show ?thesis ..\n  qed (auto simp: is_singleton_def)\nqed\n\nlemma finite_pmf_set_eheight_rbst [simp, intro]: \"finite (set_pmf (eheight_rbst n))\"\nproof -\n  have \"eheight_rbst n = map_pmf eheight (random_bst {..<n})\"\n    by (subst eheight_rbst [symmetric]) auto\n  also have \"finite (set_pmf \\<dots>)\" by simp\n  finally show ?thesis .\nqed\n\n\n\nlemma eheight_exp_1 [simp]: \"eheight_exp (Suc 0) = 1\"\n  by (simp add: eheight_exp_def lessThan_Suc)\n\nlemma eheight_exp_reduce_bound:\n  assumes \"n > 1\"\n  shows   \"eheight_exp n \\<le> 4 / n * (\\<Sum>k<n. eheight_exp k)\"\nproof -\n  have [simp]: \"real (max a b) = max (real a) (real b)\" for a b\n    by (simp add: max_def)\n  let ?f = \"\\<lambda>(h1,h2). max h1 h2\"\n  let ?p = \"\\<lambda>k. pair_pmf (eheight_rbst k) (eheight_rbst (n - Suc k))\"\n  have \"eheight_exp n = measure_pmf.expectation (eheight_rbst n) real\"\n    by (simp add: eheight_exp_def)\n  also have \"\\<dots> = 1 / real n * (\\<Sum>k<n. measure_pmf.expectation\n                                         (map_pmf (\\<lambda>(h1,h2). 2 * max h1 h2) (?p k)) real)\"\n    (is \"_ = _ * ?S\") unfolding pair_pmf_def map_bind_pmf\n    by (subst eheight_rbst_reduce [OF assms], subst pmf_expectation_bind_pmf_of_set)\n       (insert assms, auto simp: sum_divide_distrib divide_simps)\n  also have \"?S = (\\<Sum>k<n. measure_pmf.expectation (map_pmf (\\<lambda>x. 2 * x) (map_pmf ?f (?p k))) real)\"\n    by (simp only: pmf.map_comp o_def case_prod_unfold)\n  also have \"\\<dots> = 2 * (\\<Sum>k<n. measure_pmf.expectation (map_pmf ?f (?p k)) real)\" (is \"_ = _ * ?S'\")\n    by (subst integral_map_pmf) (simp add: sum_distrib_left)\n  also have \"?S' = (\\<Sum>k<n. measure_pmf.expectation (?p k) (\\<lambda>(h1,h2). max (real h1) (real h2)))\"\n    by (simp add: case_prod_unfold)\n  also have \"\\<dots> \\<le> (\\<Sum>k<n. measure_pmf.expectation (?p k) (\\<lambda>(h1,h2). real h1 + real h2))\"\n    unfolding integral_map_pmf case_prod_unfold\n    by (intro sum_mono Bochner_Integration.integral_mono integrable_measure_pmf_finite) auto\n  also have \"\\<dots> = (\\<Sum>k<n. eheight_exp k) + (\\<Sum>k<n. eheight_exp (n - Suc k))\"\n    by (subst expectation_add_pair_pmf) (auto simp: sum.distrib eheight_exp_def)\n  also have \"(\\<Sum>k<n. eheight_exp (n - Suc k)) = (\\<Sum>k<n. eheight_exp k)\"\n    by (intro sum.reindex_bij_witness[of _ \"\\<lambda>k. n - Suc k\" \"\\<lambda>k. n - Suc k\"]) auto\n  also have \"1 / real n * (2 * (\\<dots> + \\<dots>)) = 4 / real n * \\<dots>\" by simp\n  finally show ?thesis using assms by (simp_all add: mult_left_mono divide_right_mono)\nqed\n\n\ntext \\<open>\n  We now define the following upper bound on the expected exponential height due to\n  Cormen\\ \\textit{et\\ al.}~\\cite{cormen}:\n\\<close>\nlemma eheight_exp_bound: \"eheight_exp n \\<le> real ((n + 3) choose 3) / 4\"\nproof (induction n rule: less_induct)\n  case (less n)\n  consider \"n = 0\" | \"n = 1\" | \"n > 1\" by force\n  thus ?case\n  proof cases\n    case 3\n    hence \"eheight_exp n \\<le> 4 / n * (\\<Sum>k<n. eheight_exp k)\"\n      by (rule eheight_exp_reduce_bound)\n    also have \"(\\<Sum>k<n. eheight_exp k) \\<le> (\\<Sum>k<n. real ((k + 3) choose 3) / 4)\"\n      by (intro sum_mono less.IH) auto\n    also have \"\\<dots> = real (\\<Sum>k<n. ((k + 3) choose 3)) / 4\"\n      by (simp add: sum_divide_distrib)\n    also have \"(\\<Sum>k<n. ((k + 3) choose 3)) = (\\<Sum>k\\<le>n - 1. ((k + 3) choose 3))\"\n      using \\<open>n > 1\\<close> by (intro sum.cong) auto\n    also have \"\\<dots> = ((n + 3) choose 4)\"\n      using choose_rising_sum(1)[of 3 \"n - 1\"] and \\<open>n > 1\\<close> by (simp add: add_ac Suc3_eq_add_3)\n    also have \"4 / real n * (\\<dots> / 4) = real ((n + 3) choose 3) / 4\" using \\<open>n > 1\\<close>\n      by (cases n) (simp_all add: binomial_fact fact_numeral divide_simps)\n    finally show ?thesis using \\<open>n > 1\\<close> by (simp add: mult_left_mono divide_right_mono)\n  qed (auto simp: eval_nat_numeral)\nqed\n\n\ntext \\<open>\n  We then show that this is indeed an upper bound on the expected exponential height by induction\n  over the set of elements. This proof mostly follows that by Cormen\\ \\textit{et al.}~\\cite{cormen},\n  and partially an answer on the Computer Science Stack Exchange~\\cite{sofl}.\n\\<close>\n\ntext \\<open>\n  Since the function $\\uplambda x.\\ 2 ^ x$ is convex, we can then easily derive a bound on the\n  actual height using Jensen's inequality:\n\\<close>\ndefinition height_exp_approx :: \"nat \\<Rightarrow> real\" where\n  \"height_exp_approx n = log 2 (real ((n + 3) choose 3) / 4) + 1\"\n\ntheorem height_expectation_bound:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   \"measure_pmf.expectation (random_bst A) height\n             \\<le> height_exp_approx (card A)\"\nproof -\n  have \"convex_on UNIV ((powr) 2)\"\n    by (intro convex_on_realI[where f' = \"\\<lambda>x. ln 2 * 2 powr x\"])\n       (auto intro!: derivative_eq_intros DERIV_powr simp: powr_def [abs_def])\n  hence \"2 powr measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t - 1)) \\<le>\n          measure_pmf.expectation (random_bst A) (\\<lambda>t. 2 powr real (height t - 1))\"\n    using assms\n    by (intro measure_pmf.jensens_inequality[where I = UNIV])\n       (auto intro!: integrable_measure_pmf_finite)\n  also have \"(\\<lambda>t. 2 powr real (height t - 1)) = (\\<lambda>t. 2 ^ (height t - 1))\"\n    by (simp add: powr_realpow)\n  also have \"measure_pmf.expectation (random_bst A) (\\<lambda>t. 2 ^ (height t - 1)) =\n               measure_pmf.expectation (random_bst A) (\\<lambda>t. real (eheight t))\"\n    using assms\n    by (intro integral_cong_AE)\n       (auto simp: AE_measure_pmf_iff random_bst_altdef eheight_def)\n  also have \"\\<dots> = measure_pmf.expectation (map_pmf eheight (random_bst A)) real\"\n    by simp\n  also have \"map_pmf eheight (random_bst A) = eheight_rbst (card A)\"\n    by (rule eheight_rbst [symmetric]) fact+\n  also have \"measure_pmf.expectation \\<dots> real = eheight_exp (card A)\"\n    by (simp add: eheight_exp_def)\n  also have \"\\<dots> \\<le> real ((card A + 3) choose 3) / 4\" by (rule eheight_exp_bound)\n  also have \"measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t - 1)) =\n               measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)\"\n  proof (intro integral_cong_AE AE_pmfI, goal_cases)\n    case (3 t)\n    with \\<open>A \\<noteq> {}\\<close> and assms show ?case\n      by (subst of_nat_diff) (auto simp: Suc_le_eq random_bst_altdef)\n  qed auto\n  finally have \"2 powr measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)\n                  \\<le> real ((card A + 3) choose 3) / 4\" .\n  hence \"log 2 (2 powr measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)) \\<le>\n           log 2 (real ((card A + 3) choose 3) / 4)\" (is \"?lhs \\<le> ?rhs\")\n    by (subst log_le_cancel_iff) (auto simp: )\n  also have \"?lhs = measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)\"\n    by simp\n  also have \"\\<dots> = measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t)) - 1\"\n    using assms\n    by (subst Bochner_Integration.integral_diff) (auto intro!: integrable_measure_pmf_finite)\n  finally show ?thesis by (simp add: height_exp_approx_def)\nqed\n\ntext \\<open>\n  This upper bound is asymptotically equivalent to $c \\ln n$ with\n  $c = \\frac{3}{\\ln 2} \\approx 4.328$. This is actually a relatively tight upper bound, since\n  the exact asymptotics of the expected height of a random BST is $c \\ln n$ with\n  $c \\approx 4.311$.~\\cite{reed} However, the proof of these precise asymptotics is very intricate\n  and we will therefore be content with the upper bound.\n\n  In particular, we can now show that the expected height is $O(\\log n)$.\n\\<close>\nlemma ln_sum_bigo_ln: \"(\\<lambda>x::real. ln (x + c)) \\<in> O(ln)\"\nproof (rule bigoI_tendsto)\n  from eventually_gt_at_top[of \"1::real\"] show \"eventually (\\<lambda>x::real. ln x \\<noteq> 0) at_top\"\n    by eventually_elim simp_all\nnext\n  show \"((\\<lambda>x. ln (x + c) / ln x) \\<longlongrightarrow> 1) at_top\"\n  proof (rule lhospital_at_top_at_top)\n    show \"eventually (\\<lambda>x. ((\\<lambda>x. ln (x + c)) has_real_derivative inverse (x + c)) (at x)) at_top\"\n      using eventually_gt_at_top[of \"-c\"]\n      by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\n    show \"eventually (\\<lambda>x. ((\\<lambda>x. ln x) has_real_derivative inverse x) (at x)) at_top\"\n      using eventually_gt_at_top[of 0]\n      by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\n    show \"((\\<lambda>x. inverse (x + c) / inverse x) \\<longlongrightarrow> 1) at_top\"\n    proof (rule Lim_transform_eventually)\n      show \"eventually (\\<lambda>x. inverse (1 + c / x) = inverse (x + c) / inverse x) at_top\"\n        using eventually_gt_at_top[of \"0::real\"] eventually_gt_at_top[of \"-c\"]\n        by eventually_elim (simp add: field_simps)\n      have \"((\\<lambda>x. inverse (1 + c / x)) \\<longlongrightarrow> inverse (1 + 0)) at_top\"\n        by (intro tendsto_inverse tendsto_add tendsto_const\n              real_tendsto_divide_at_top[OF tendsto_const] filterlim_ident) simp_all\n      thus \"((\\<lambda>x. inverse (1 + c / x)) \\<longlongrightarrow> 1) at_top\" by simp\n    qed\n  qed (auto simp: ln_at_top eventually_at_top_not_equal)\nqed\n\ncorollary height_expectation_bigo: \"height_exp_approx \\<in> O(ln)\"\nproof -\n  let ?T = \"\\<lambda>x::real. log 2 (x + 1) + log 2 (x + 2) + log 2 (x + 3) + (1 - log 2 24)\"\n  have \"eventually (\\<lambda>n. height_exp_approx n =\n          log 2 (real n + 1) + log 2 (real n + 2) + log 2 (real n + 3) + (1 - log 2 24)) at_top\"\n    (is \"eventually (\\<lambda>n. _ = ?T n) at_top\") using eventually_gt_at_top[of \"0::nat\"]\n  proof eventually_elim\n    case (elim n)\n    have \"height_exp_approx n = log 2 (real (n + 3 choose 3) / 4) + 1\"\n      by (simp add: height_exp_approx_def log_divide)\n    also have \"real ((n + 3) choose 3) = real (n + 3) gchoose 3\"\n      by (simp add: binomial_gbinomial)\n    also have \"\\<dots> / 4 = (real n + 1) * (real n + 2) * (real n + 3) / 24\"\n      by (simp add: gbinomial_pochhammer' numeral_3_eq_3 pochhammer_Suc add_ac)\n    also have \"log 2 \\<dots> = log 2 (real n + 1) + log 2 (real n + 2) + log 2 (real n + 3) - log 2 24\"\n      by (simp add: log_divide log_mult)\n    finally show ?case by simp\n  qed\n  hence \"height_exp_approx \\<in> \\<Theta>(?T)\" by (rule bigthetaI_cong)\n  also have *: \"(\\<lambda>x. ln (x + c) / ln 2) \\<in> O(ln)\" for c :: real\n    by (subst landau_o.big.cdiv_in_iff') (auto intro!: ln_sum_bigo_ln)\n  have \"?T \\<in> O(\\<lambda>n. ln (real n))\" unfolding log_def\n    by (intro bigo_real_nat_transfer sum_in_bigo ln_sum_bigo_ln *) simp_all\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Lookup costs\\<close>\n\ntext \\<open>\n  The following function describes the cost incurred when looking up a specific element\n  in a specific BST. The cost corresponds to the number of edges traversed in the lookup.\n\\<close>\n\nprimrec lookup_cost :: \"'a :: linorder \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n  \"lookup_cost x Leaf = 0\"\n| \"lookup_cost x (Node l y r) =\n     (if x = y then 0\n      else if x < y then Suc (lookup_cost x l)\n      else Suc (lookup_cost x r))\"\n\ntext \\<open>\n  Some of the literature defines these costs as 1 in the case that the current node is\n  the correct one, i.\\,e.\\ their costs are our costs plus 1. These alternative costs are\n  exactly the number of comparisons performed in the lookup. Our cost function has the\n  advantage of precisely summing up to the internal path length and therefore gives us\n  slightly nicer results, and since the difference is only a ${}+1$ in the end, this\n  variant seemed more reasonable.\n\\<close>\n\ntext \\<open>\n  It can be shown with a simple induction that The sum of all lookup costs in a tree is the\n  internal path length of the tree.\n\\<close>\ntheorem sum_lookup_costs:\n  fixes t :: \"'a :: linorder tree\"\n  assumes \"bst t\"\n  shows   \"(\\<Sum>x\\<in>set_tree t. lookup_cost x t) = ipl t\"\nusing assms\nproof (induction t)\n  case (Node l x r)\n  from Node.prems\n    have disj: \"x \\<notin> set_tree l\" \"x \\<notin> set_tree r\" \"set_tree l \\<inter> set_tree r = {}\" by force+\n  have \"set_tree (Node l x r) = insert x (set_tree l \\<union> set_tree r)\" by simp\n  also have \"(\\<Sum>y\\<in>\\<dots>. lookup_cost y (Node l x r)) = lookup_cost x \\<langle>l, x, r\\<rangle> +\n               (\\<Sum>y\\<in>set_tree l. lookup_cost y \\<langle>l, x, r\\<rangle>) + (\\<Sum>y\\<in>set_tree r. lookup_cost y \\<langle>l, x, r\\<rangle>)\"\n    using disj by (simp add: sum.union_disjoint)\n  also have \"(\\<Sum>y\\<in>set_tree l. lookup_cost y \\<langle>l, x, r\\<rangle>) = (\\<Sum>y\\<in>set_tree l. 1 + lookup_cost y l)\"\n    using disj and Node by (intro sum.cong refl) auto\n  also have \"\\<dots> = size l + ipl l\" using Node\n    by (subst sum.distrib) (simp_all add: card_set_tree_bst)\n  also have \"(\\<Sum>y\\<in>set_tree r. lookup_cost y \\<langle>l, x, r\\<rangle>) = (\\<Sum>y\\<in>set_tree r. 1 + lookup_cost y r)\"\n    using disj and Node by (intro sum.cong refl) auto\n  also have \"\\<dots> = size r + ipl r\" using Node\n    by (subst sum.distrib) (simp_all add: card_set_tree_bst)\n  finally show ?case by simp\nqed simp_all\n\ntext \\<open>\n  This allows us to easily show that the expected cost of looking up a random element in a\n  fixed tree is the internal path length divided by the number of elements.\n\\<close>\ntheorem expected_lookup_cost:\n  assumes \"bst t\" \"t \\<noteq> Leaf\"\n  shows   \"measure_pmf.expectation (pmf_of_set (set_tree t)) (\\<lambda>x. lookup_cost x t) =\n             ipl t / size t\"\n  using assms by (subst integral_pmf_of_set)\n                 (simp_all add: sum_lookup_costs of_nat_sum [symmetric] card_set_tree_bst)\n\ntext \\<open>\n  Therefore, we will now turn to analysing the internal path length of a random BST. This\n  then clearly related to the expected lookup costs of a random element in a random BST by\n  the above result.\n\\<close>\n\n\nsubsection \\<open>Average Path Length\\<close>\n\ntext \\<open>\n  The internal path length satisfies the recursive equation @{thm ipl.simps(2)[of l x r]}.\n  This is quite similar to the number of comparisons performed by QuickSort, and indeed, we can\n  reduce the internal path length of a random BST to the number of comparisons performed by\n  QuickSort on a randomly-ordered list relatively easily:\n\\<close>\ntheorem map_pmf_random_bst_eq_rqs_cost:\n  assumes \"finite A\"\n  shows   \"map_pmf ipl (random_bst A) = rqs_cost (card A)\"\nusing assms\nproof (induction A rule: finite_psubset_induct)\n  case (psubset A)\n  show ?case\n  proof (cases \"A = {}\")\n    case False\n    note A = \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    define n where \"n = card A - 1\"\n    define rank :: \"'a \\<Rightarrow> nat\" where \"rank = linorder_rank {(x,y). x \\<le> y} A\"\n    from A have card: \"card A = Suc n\" by (cases \"card A\") (auto simp: n_def)\n    from A have \"map_pmf ipl (random_bst A) =\n                   do {\n                     x \\<leftarrow> pmf_of_set A;\n                     (l,r) \\<leftarrow> pair_pmf (random_bst {y \\<in> A. y < x}) (random_bst {y \\<in> A. y > x});\n                     return_pmf (ipl (Node l x r))\n                   }\"\n      by (subst random_bst.simps)\n         (simp_all add: pair_pmf_def card map_pmf_def bind_assoc_pmf bind_return_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (l,r) \\<leftarrow> pair_pmf (random_bst {y \\<in> A. y < x}) (random_bst {y \\<in> A. y > x});\n                      return_pmf (n + ipl l + ipl r)\n                    }\"\n    proof (intro bind_pmf_cong refl, clarify, goal_cases)\n      case (1 x l r)\n      from 1 and A have \"n = card (A - {x})\" by (simp add: n_def)\n      also have \"A - {x} = {y\\<in>A. y < x} \\<union> {y\\<in>A. y > x}\" by auto\n      also have \"card \\<dots> = card {y\\<in>A. y < x} + card {y\\<in>A. y > x}\"\n        using \\<open>finite A\\<close> by (intro card_Un_disjoint) auto\n      also from 1 and A have \"card {y\\<in>A. y < x} = size l\" by (auto dest: size_random_bst)\n      also from 1 and A have \"card {y\\<in>A. y > x} = size r\" by (auto dest: size_random_bst)\n      finally show ?case by simp\n    qed\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (l,r) \\<leftarrow> pair_pmf (map_pmf ipl (random_bst {y \\<in> A. y < x}))\n                                        (map_pmf ipl (random_bst {y \\<in> A. y > x}));\n                      return_pmf (n + l + r)\n                    }\" by (simp add: map_pair [symmetric] case_prod_unfold bind_map_pmf)\n    also have \"\\<dots> = do {\n                      i \\<leftarrow> map_pmf rank (pmf_of_set A);\n                      (l,r) \\<leftarrow> pair_pmf (rqs_cost i) (rqs_cost (n - i));\n                      return_pmf (n + l + r)\n                    }\" (is \"_ = bind_pmf _ ?f\") unfolding bind_map_pmf\n    proof (intro bind_pmf_cong refl pair_pmf_cong, goal_cases)\n      case (1 x)\n      have \"map_pmf ipl (random_bst {y \\<in> A. y < x}) = rqs_cost (card {y \\<in> A. y < x})\"\n        using 1 and A by (intro psubset.IH) auto\n      also have \"{y \\<in> A. y < x} = {y \\<in> A - {x}. y \\<le> x}\" by auto\n      hence \"card {y \\<in> A. y < x} = rank x\" by (simp add: rank_def linorder_rank_def)\n      finally show ?case .\n    next\n      case (2 x)\n      have \"map_pmf ipl (random_bst {y \\<in> A. y > x}) = rqs_cost (card {y \\<in> A. y > x})\"\n        using 2 and A by (intro psubset.IH) auto\n      also have \"{y \\<in> A. y > x} = A - {x} - {y \\<in> A - {x}. y \\<le> x}\" by auto\n      hence \"card {y \\<in> A. y > x} = card \\<dots>\" by (simp only:)\n      also from 2 and A have \"\\<dots> = n - rank x\"\n        by (subst card_Diff_subset) (auto simp: rank_def linorder_rank_def n_def)\n      finally show ?case .\n    qed\n    also from A have \"map_pmf rank (pmf_of_set A) = pmf_of_set {..<card A}\"\n      unfolding rank_def by (intro map_pmf_of_set_bij_betw bij_betw_linorder_rank[of UNIV]) auto\n    also have \"{..<card A} = {..n}\" by (auto simp: card)\n    also have \"pmf_of_set \\<dots> \\<bind> ?f = rqs_cost (card A)\"\n      by (simp add: pair_pmf_def bind_assoc_pmf bind_return_pmf card)\n    finally show ?thesis .\n  qed simp_all\nqed\n\ntext \\<open>\n  In particular, this means that the expected values are the same:\n\\<close>\ncorollary expected_ipl_random_bst_eq:\n  assumes \"finite A\"\n  shows   \"measure_pmf.expectation (random_bst A) ipl = rqs_cost_exp (card A)\"\nproof -\n  have \"measure_pmf.expectation (random_bst A) ipl =\n          measure_pmf.expectation (map_pmf ipl (random_bst A)) real\" by simp\n  also from assms have \"map_pmf ipl (random_bst A) = rqs_cost (card A)\"\n    by (rule map_pmf_random_bst_eq_rqs_cost)\n  also have \"measure_pmf.expectation \\<dots> real = rqs_cost_exp (card A)\"\n    by (rule expectation_rqs_cost)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Therefore, the results about the expected number of comparisons of QuickSort carry over\n  to the expected internal path length:\n\\<close>\ncorollary expected_ipl_random_bst_eq':\n  assumes \"finite A\"\n  shows   \"measure_pmf.expectation (random_bst A) ipl =\n             2 * real (card A + 1) * harm (card A) - 4 * real (card A)\"\n  by (simp add: expected_ipl_random_bst_eq rqs_cost_exp_eq assms)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Random_BSTs/Random_BSTs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767938900121, "lm_q2_score": 0.8824278680004707, "lm_q1q2_score": 0.7743099764522519}}
{"text": "(*  Title:      HOL/Multivariate_Analysis/Operator_Norm.thy\n    Author:     Amine Chaieb, University of Cambridge\n    Author:     Brian Huffman\n*)\n\nsection {* Operator Norm *}\n\ntheory Operator_Norm\nimports Complex_Main\nbegin\n\ntext {* This formulation yields zero if @{text 'a} is the trivial vector space. *}\n\ndefinition onorm :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> real\"\n  where \"onorm f = (SUP x. norm (f x) / norm x)\"\n\nlemma onorm_bound:\n  assumes \"0 \\<le> b\" and \"\\<And>x. norm (f x) \\<le> b * norm x\"\n  shows \"onorm f \\<le> b\"\n  unfolding onorm_def\nproof (rule cSUP_least)\n  fix x\n  show \"norm (f x) / norm x \\<le> b\"\n    using assms by (cases \"x = 0\") (simp_all add: pos_divide_le_eq)\nqed simp\n\ntext {* In non-trivial vector spaces, the first assumption is redundant. *}\n\nlemma onorm_le:\n  fixes f :: \"'a::{real_normed_vector, perfect_space} \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>x. norm (f x) \\<le> b * norm x\"\n  shows \"onorm f \\<le> b\"\nproof (rule onorm_bound [OF _ assms])\n  have \"{0::'a} \\<noteq> UNIV\" by (metis not_open_singleton open_UNIV)\n  then obtain a :: 'a where \"a \\<noteq> 0\" by fast\n  have \"0 \\<le> b * norm a\"\n    by (rule order_trans [OF norm_ge_zero assms])\n  with `a \\<noteq> 0` show \"0 \\<le> b\"\n    by (simp add: zero_le_mult_iff)\nqed\n\nlemma le_onorm:\n  assumes \"bounded_linear f\"\n  shows \"norm (f x) / norm x \\<le> onorm f\"\nproof -\n  interpret f: bounded_linear f by fact\n  obtain b where \"0 \\<le> b\" and \"\\<forall>x. norm (f x) \\<le> norm x * b\"\n    using f.nonneg_bounded by auto\n  then have \"\\<forall>x. norm (f x) / norm x \\<le> b\"\n    by (clarify, case_tac \"x = 0\",\n      simp_all add: f.zero pos_divide_le_eq mult.commute)\n  then have \"bdd_above (range (\\<lambda>x. norm (f x) / norm x))\"\n    unfolding bdd_above_def by fast\n  with UNIV_I show ?thesis\n    unfolding onorm_def by (rule cSUP_upper)\nqed\n\nlemma onorm:\n  assumes \"bounded_linear f\"\n  shows \"norm (f x) \\<le> onorm f * norm x\"\nproof -\n  interpret f: bounded_linear f by fact\n  show ?thesis\n  proof (cases)\n    assume \"x = 0\"\n    then show ?thesis by (simp add: f.zero)\n  next\n    assume \"x \\<noteq> 0\"\n    have \"norm (f x) / norm x \\<le> onorm f\"\n      by (rule le_onorm [OF assms])\n    then show \"norm (f x) \\<le> onorm f * norm x\"\n      by (simp add: pos_divide_le_eq `x \\<noteq> 0`)\n  qed\nqed\n\nlemma onorm_pos_le:\n  assumes f: \"bounded_linear f\"\n  shows \"0 \\<le> onorm f\"\n  using le_onorm [OF f, where x=0] by simp\n\nlemma onorm_zero: \"onorm (\\<lambda>x. 0) = 0\"\nproof (rule order_antisym)\n  show \"onorm (\\<lambda>x. 0) \\<le> 0\"\n    by (simp add: onorm_bound)\n  show \"0 \\<le> onorm (\\<lambda>x. 0)\"\n    using bounded_linear_zero by (rule onorm_pos_le)\nqed\n\nlemma onorm_eq_0:\n  assumes f: \"bounded_linear f\"\n  shows \"onorm f = 0 \\<longleftrightarrow> (\\<forall>x. f x = 0)\"\n  using onorm [OF f] by (auto simp: fun_eq_iff [symmetric] onorm_zero)\n\nlemma onorm_pos_lt:\n  assumes f: \"bounded_linear f\"\n  shows \"0 < onorm f \\<longleftrightarrow> \\<not> (\\<forall>x. f x = 0)\"\n  by (simp add: less_le onorm_pos_le [OF f] onorm_eq_0 [OF f])\n\nlemma onorm_compose:\n  assumes f: \"bounded_linear f\"\n  assumes g: \"bounded_linear g\"\n  shows \"onorm (f \\<circ> g) \\<le> onorm f * onorm g\"\nproof (rule onorm_bound)\n  show \"0 \\<le> onorm f * onorm g\"\n    by (intro mult_nonneg_nonneg onorm_pos_le f g)\nnext\n  fix x\n  have \"norm (f (g x)) \\<le> onorm f * norm (g x)\"\n    by (rule onorm [OF f])\n  also have \"onorm f * norm (g x) \\<le> onorm f * (onorm g * norm x)\"\n    by (rule mult_left_mono [OF onorm [OF g] onorm_pos_le [OF f]])\n  finally show \"norm ((f \\<circ> g) x) \\<le> onorm f * onorm g * norm x\"\n    by (simp add: mult.assoc)\nqed\n\nlemma onorm_scaleR_lemma:\n  assumes f: \"bounded_linear f\"\n  shows \"onorm (\\<lambda>x. r *\\<^sub>R f x) \\<le> \\<bar>r\\<bar> * onorm f\"\nproof (rule onorm_bound)\n  show \"0 \\<le> \\<bar>r\\<bar> * onorm f\"\n    by (intro mult_nonneg_nonneg onorm_pos_le abs_ge_zero f)\nnext\n  fix x\n  have \"\\<bar>r\\<bar> * norm (f x) \\<le> \\<bar>r\\<bar> * (onorm f * norm x)\"\n    by (intro mult_left_mono onorm abs_ge_zero f)\n  then show \"norm (r *\\<^sub>R f x) \\<le> \\<bar>r\\<bar> * onorm f * norm x\"\n    by (simp only: norm_scaleR mult.assoc)\nqed\n\nlemma onorm_scaleR:\n  assumes f: \"bounded_linear f\"\n  shows \"onorm (\\<lambda>x. r *\\<^sub>R f x) = \\<bar>r\\<bar> * onorm f\"\nproof (cases \"r = 0\")\n  assume \"r \\<noteq> 0\"\n  show ?thesis\n  proof (rule order_antisym)\n    show \"onorm (\\<lambda>x. r *\\<^sub>R f x) \\<le> \\<bar>r\\<bar> * onorm f\"\n      using f by (rule onorm_scaleR_lemma)\n  next\n    have \"bounded_linear (\\<lambda>x. r *\\<^sub>R f x)\"\n      using bounded_linear_scaleR_right f by (rule bounded_linear_compose)\n    then have \"onorm (\\<lambda>x. inverse r *\\<^sub>R r *\\<^sub>R f x) \\<le> \\<bar>inverse r\\<bar> * onorm (\\<lambda>x. r *\\<^sub>R f x)\"\n      by (rule onorm_scaleR_lemma)\n    with `r \\<noteq> 0` show \"\\<bar>r\\<bar> * onorm f \\<le> onorm (\\<lambda>x. r *\\<^sub>R f x)\"\n      by (simp add: inverse_eq_divide pos_le_divide_eq mult.commute)\n  qed\nqed (simp add: onorm_zero)\n\nlemma onorm_neg:\n  shows \"onorm (\\<lambda>x. - f x) = onorm f\"\n  unfolding onorm_def by simp\n\nlemma onorm_triangle:\n  assumes f: \"bounded_linear f\"\n  assumes g: \"bounded_linear g\"\n  shows \"onorm (\\<lambda>x. f x + g x) \\<le> onorm f + onorm g\"\nproof (rule onorm_bound)\n  show \"0 \\<le> onorm f + onorm g\"\n    by (intro add_nonneg_nonneg onorm_pos_le f g)\nnext\n  fix x\n  have \"norm (f x + g x) \\<le> norm (f x) + norm (g x)\"\n    by (rule norm_triangle_ineq)\n  also have \"norm (f x) + norm (g x) \\<le> onorm f * norm x + onorm g * norm x\"\n    by (intro add_mono onorm f g)\n  finally show \"norm (f x + g x) \\<le> (onorm f + onorm g) * norm x\"\n    by (simp only: distrib_right)\nqed\n\nlemma onorm_triangle_le:\n  assumes \"bounded_linear f\"\n  assumes \"bounded_linear g\"\n  assumes \"onorm f + onorm g \\<le> e\"\n  shows \"onorm (\\<lambda>x. f x + g x) \\<le> e\"\n  using assms by (rule onorm_triangle [THEN order_trans])\n\nlemma onorm_triangle_lt:\n  assumes \"bounded_linear f\"\n  assumes \"bounded_linear g\"\n  assumes \"onorm f + onorm g < e\"\n  shows \"onorm (\\<lambda>x. f x + g x) < e\"\n  using assms by (rule onorm_triangle [THEN order_le_less_trans])\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Multivariate_Analysis/Operator_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.8824278710924296, "lm_q1q2_score": 0.7743099763379995}}
{"text": "(*  Title:      HOL/Lattice/Bounds.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Bounds\\<close>\n\ntheory Bounds imports Orders begin\n\nhide_const (open) inf sup\n\nsubsection \\<open>Infimum and supremum\\<close>\n\ntext \\<open>\n  Given a partial order, we define infimum (greatest lower bound) and\n  supremum (least upper bound) wrt.\\ \\<open>\\<sqsubseteq>\\<close> for two and for any\n  number of elements.\n\\<close>\n\ndefinition\n  is_inf :: \"'a::partial_order \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"is_inf x y inf = (inf \\<sqsubseteq> x \\<and> inf \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> inf))\"\n\ndefinition\n  is_sup :: \"'a::partial_order \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"is_sup x y sup = (x \\<sqsubseteq> sup \\<and> y \\<sqsubseteq> sup \\<and> (\\<forall>z. x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z \\<longrightarrow> sup \\<sqsubseteq> z))\"\n\ndefinition\n  is_Inf :: \"'a::partial_order set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"is_Inf A inf = ((\\<forall>x \\<in> A. inf \\<sqsubseteq> x) \\<and> (\\<forall>z. (\\<forall>x \\<in> A. z \\<sqsubseteq> x) \\<longrightarrow> z \\<sqsubseteq> inf))\"\n\ndefinition\n  is_Sup :: \"'a::partial_order set \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"is_Sup A sup = ((\\<forall>x \\<in> A. x \\<sqsubseteq> sup) \\<and> (\\<forall>z. (\\<forall>x \\<in> A. x \\<sqsubseteq> z) \\<longrightarrow> sup \\<sqsubseteq> z))\"\n\ntext \\<open>\n  These definitions entail the following basic properties of boundary\n  elements.\n\\<close>\n\nlemma is_infI [intro?]: \"inf \\<sqsubseteq> x \\<Longrightarrow> inf \\<sqsubseteq> y \\<Longrightarrow>\n    (\\<And>z. z \\<sqsubseteq> x \\<Longrightarrow> z \\<sqsubseteq> y \\<Longrightarrow> z \\<sqsubseteq> inf) \\<Longrightarrow> is_inf x y inf\"\n  by (unfold is_inf_def) blast\n\nlemma is_inf_greatest [elim?]:\n    \"is_inf x y inf \\<Longrightarrow> z \\<sqsubseteq> x \\<Longrightarrow> z \\<sqsubseteq> y \\<Longrightarrow> z \\<sqsubseteq> inf\"\n  by (unfold is_inf_def) blast\n\nlemma is_inf_lower [elim?]:\n    \"is_inf x y inf \\<Longrightarrow> (inf \\<sqsubseteq> x \\<Longrightarrow> inf \\<sqsubseteq> y \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (unfold is_inf_def) blast\n\n\nlemma is_supI [intro?]: \"x \\<sqsubseteq> sup \\<Longrightarrow> y \\<sqsubseteq> sup \\<Longrightarrow>\n    (\\<And>z. x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> sup \\<sqsubseteq> z) \\<Longrightarrow> is_sup x y sup\"\n  by (unfold is_sup_def) blast\n\nlemma is_sup_least [elim?]:\n    \"is_sup x y sup \\<Longrightarrow> x \\<sqsubseteq> z \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> sup \\<sqsubseteq> z\"\n  by (unfold is_sup_def) blast\n\nlemma is_sup_upper [elim?]:\n    \"is_sup x y sup \\<Longrightarrow> (x \\<sqsubseteq> sup \\<Longrightarrow> y \\<sqsubseteq> sup \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (unfold is_sup_def) blast\n\n\nlemma is_InfI [intro?]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> inf \\<sqsubseteq> x) \\<Longrightarrow>\n    (\\<And>z. (\\<forall>x \\<in> A. z \\<sqsubseteq> x) \\<Longrightarrow> z \\<sqsubseteq> inf) \\<Longrightarrow> is_Inf A inf\"\n  by (unfold is_Inf_def) blast\n\nlemma is_Inf_greatest [elim?]:\n    \"is_Inf A inf \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> z \\<sqsubseteq> x) \\<Longrightarrow> z \\<sqsubseteq> inf\"\n  by (unfold is_Inf_def) blast\n\nlemma is_Inf_lower [dest?]:\n    \"is_Inf A inf \\<Longrightarrow> x \\<in> A \\<Longrightarrow> inf \\<sqsubseteq> x\"\n  by (unfold is_Inf_def) blast\n\n\nlemma is_SupI [intro?]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<sqsubseteq> sup) \\<Longrightarrow>\n    (\\<And>z. (\\<forall>x \\<in> A. x \\<sqsubseteq> z) \\<Longrightarrow> sup \\<sqsubseteq> z) \\<Longrightarrow> is_Sup A sup\"\n  by (unfold is_Sup_def) blast\n\nlemma is_Sup_least [elim?]:\n    \"is_Sup A sup \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> x \\<sqsubseteq> z) \\<Longrightarrow> sup \\<sqsubseteq> z\"\n  by (unfold is_Sup_def) blast\n\nlemma is_Sup_upper [dest?]:\n    \"is_Sup A sup \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<sqsubseteq> sup\"\n  by (unfold is_Sup_def) blast\n\n\nsubsection \\<open>Duality\\<close>\n\ntext \\<open>\n  Infimum and supremum are dual to each other.\n\\<close>\n\ntheorem dual_inf [iff?]:\n    \"is_inf (dual x) (dual y) (dual sup) = is_sup x y sup\"\n  by (simp add: is_inf_def is_sup_def dual_all [symmetric] dual_leq)\n\ntheorem dual_sup [iff?]:\n    \"is_sup (dual x) (dual y) (dual inf) = is_inf x y inf\"\n  by (simp add: is_inf_def is_sup_def dual_all [symmetric] dual_leq)\n\ntheorem dual_Inf [iff?]:\n    \"is_Inf (dual ` A) (dual sup) = is_Sup A sup\"\n  by (simp add: is_Inf_def is_Sup_def dual_all [symmetric] dual_leq)\n\ntheorem dual_Sup [iff?]:\n    \"is_Sup (dual ` A) (dual inf) = is_Inf A inf\"\n  by (simp add: is_Inf_def is_Sup_def dual_all [symmetric] dual_leq)\n\n\nsubsection \\<open>Uniqueness\\<close>\n\ntext \\<open>\n  Infima and suprema on partial orders are unique; this is mainly due\n  to anti-symmetry of the underlying relation.\n\\<close>\n\ntheorem is_inf_uniq: \"is_inf x y inf \\<Longrightarrow> is_inf x y inf' \\<Longrightarrow> inf = inf'\"\nproof -\n  assume inf: \"is_inf x y inf\"\n  assume inf': \"is_inf x y inf'\"\n  show ?thesis\n  proof (rule leq_antisym)\n    from inf' show \"inf \\<sqsubseteq> inf'\"\n    proof (rule is_inf_greatest)\n      from inf show \"inf \\<sqsubseteq> x\" ..\n      from inf show \"inf \\<sqsubseteq> y\" ..\n    qed\n    from inf show \"inf' \\<sqsubseteq> inf\"\n    proof (rule is_inf_greatest)\n      from inf' show \"inf' \\<sqsubseteq> x\" ..\n      from inf' show \"inf' \\<sqsubseteq> y\" ..\n    qed\n  qed\nqed\n\ntheorem is_sup_uniq: \"is_sup x y sup \\<Longrightarrow> is_sup x y sup' \\<Longrightarrow> sup = sup'\"\nproof -\n  assume sup: \"is_sup x y sup\" and sup': \"is_sup x y sup'\"\n  have \"dual sup = dual sup'\"\n  proof (rule is_inf_uniq)\n    from sup show \"is_inf (dual x) (dual y) (dual sup)\" ..\n    from sup' show \"is_inf (dual x) (dual y) (dual sup')\" ..\n  qed\n  then show \"sup = sup'\" ..\nqed\n\ntheorem is_Inf_uniq: \"is_Inf A inf \\<Longrightarrow> is_Inf A inf' \\<Longrightarrow> inf = inf'\"\nproof -\n  assume inf: \"is_Inf A inf\"\n  assume inf': \"is_Inf A inf'\"\n  show ?thesis\n  proof (rule leq_antisym)\n    from inf' show \"inf \\<sqsubseteq> inf'\"\n    proof (rule is_Inf_greatest)\n      fix x assume \"x \\<in> A\"\n      with inf show \"inf \\<sqsubseteq> x\" ..\n    qed\n    from inf show \"inf' \\<sqsubseteq> inf\"\n    proof (rule is_Inf_greatest)\n      fix x assume \"x \\<in> A\"\n      with inf' show \"inf' \\<sqsubseteq> x\" ..\n    qed\n  qed\nqed\n\ntheorem is_Sup_uniq: \"is_Sup A sup \\<Longrightarrow> is_Sup A sup' \\<Longrightarrow> sup = sup'\"\nproof -\n  assume sup: \"is_Sup A sup\" and sup': \"is_Sup A sup'\"\n  have \"dual sup = dual sup'\"\n  proof (rule is_Inf_uniq)\n    from sup show \"is_Inf (dual ` A) (dual sup)\" ..\n    from sup' show \"is_Inf (dual ` A) (dual sup')\" ..\n  qed\n  then show \"sup = sup'\" ..\nqed\n\n\nsubsection \\<open>Related elements\\<close>\n\ntext \\<open>\n  The binary bound of related elements is either one of the argument.\n\\<close>\n\ntheorem is_inf_related [elim?]: \"x \\<sqsubseteq> y \\<Longrightarrow> is_inf x y x\"\nproof -\n  assume \"x \\<sqsubseteq> y\"\n  show ?thesis\n  proof\n    show \"x \\<sqsubseteq> x\" ..\n    show \"x \\<sqsubseteq> y\" by fact\n    fix z assume \"z \\<sqsubseteq> x\" and \"z \\<sqsubseteq> y\" show \"z \\<sqsubseteq> x\" by fact\n  qed\nqed\n\ntheorem is_sup_related [elim?]: \"x \\<sqsubseteq> y \\<Longrightarrow> is_sup x y y\"\nproof -\n  assume \"x \\<sqsubseteq> y\"\n  show ?thesis\n  proof\n    show \"x \\<sqsubseteq> y\" by fact\n    show \"y \\<sqsubseteq> y\" ..\n    fix z assume \"x \\<sqsubseteq> z\" and \"y \\<sqsubseteq> z\"\n    show \"y \\<sqsubseteq> z\" by fact\n  qed\nqed\n\n\nsubsection \\<open>General versus binary bounds \\label{sec:gen-bin-bounds}\\<close>\n\ntext \\<open>\n  General bounds of two-element sets coincide with binary bounds.\n\\<close>\n\ntheorem is_Inf_binary: \"is_Inf {x, y} inf = is_inf x y inf\"\nproof -\n  let ?A = \"{x, y}\"\n  show ?thesis\n  proof\n    assume is_Inf: \"is_Inf ?A inf\"\n    show \"is_inf x y inf\"\n    proof\n      have \"x \\<in> ?A\" by simp\n      with is_Inf show \"inf \\<sqsubseteq> x\" ..\n      have \"y \\<in> ?A\" by simp\n      with is_Inf show \"inf \\<sqsubseteq> y\" ..\n      fix z assume zx: \"z \\<sqsubseteq> x\" and zy: \"z \\<sqsubseteq> y\"\n      from is_Inf show \"z \\<sqsubseteq> inf\"\n      proof (rule is_Inf_greatest)\n        fix a assume \"a \\<in> ?A\"\n        then have \"a = x \\<or> a = y\" by blast\n        then show \"z \\<sqsubseteq> a\"\n        proof\n          assume \"a = x\"\n          with zx show ?thesis by simp\n        next\n          assume \"a = y\"\n          with zy show ?thesis by simp\n        qed\n      qed\n    qed\n  next\n    assume is_inf: \"is_inf x y inf\"\n    show \"is_Inf {x, y} inf\"\n    proof\n      fix a assume \"a \\<in> ?A\"\n      then have \"a = x \\<or> a = y\" by blast\n      then show \"inf \\<sqsubseteq> a\"\n      proof\n        assume \"a = x\"\n        also from is_inf have \"inf \\<sqsubseteq> x\" ..\n        finally show ?thesis .\n      next\n        assume \"a = y\"\n        also from is_inf have \"inf \\<sqsubseteq> y\" ..\n        finally show ?thesis .\n      qed\n    next\n      fix z assume z: \"\\<forall>a \\<in> ?A. z \\<sqsubseteq> a\"\n      from is_inf show \"z \\<sqsubseteq> inf\"\n      proof (rule is_inf_greatest)\n        from z show \"z \\<sqsubseteq> x\" by blast\n        from z show \"z \\<sqsubseteq> y\" by blast\n      qed\n    qed\n  qed\nqed\n\ntheorem is_Sup_binary: \"is_Sup {x, y} sup = is_sup x y sup\"\nproof -\n  have \"is_Sup {x, y} sup = is_Inf (dual ` {x, y}) (dual sup)\"\n    by (simp only: dual_Inf)\n  also have \"dual ` {x, y} = {dual x, dual y}\"\n    by simp\n  also have \"is_Inf \\<dots> (dual sup) = is_inf (dual x) (dual y) (dual sup)\"\n    by (rule is_Inf_binary)\n  also have \"\\<dots> = is_sup x y sup\"\n    by (simp only: dual_inf)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Connecting general bounds \\label{sec:connect-bounds}\\<close>\n\ntext \\<open>\n  Either kind of general bounds is sufficient to express the other.\n  The least upper bound (supremum) is the same as the the greatest\n  lower bound of the set of all upper bounds; the dual statements\n  holds as well; the dual statement holds as well.\n\\<close>\n\ntheorem Inf_Sup: \"is_Inf {b. \\<forall>a \\<in> A. a \\<sqsubseteq> b} sup \\<Longrightarrow> is_Sup A sup\"\nproof -\n  let ?B = \"{b. \\<forall>a \\<in> A. a \\<sqsubseteq> b}\"\n  assume is_Inf: \"is_Inf ?B sup\"\n  show \"is_Sup A sup\"\n  proof\n    fix x assume x: \"x \\<in> A\"\n    from is_Inf show \"x \\<sqsubseteq> sup\"\n    proof (rule is_Inf_greatest)\n      fix y assume \"y \\<in> ?B\"\n      then have \"\\<forall>a \\<in> A. a \\<sqsubseteq> y\" ..\n      from this x show \"x \\<sqsubseteq> y\" ..\n    qed\n  next\n    fix z assume \"\\<forall>x \\<in> A. x \\<sqsubseteq> z\"\n    then have \"z \\<in> ?B\" ..\n    with is_Inf show \"sup \\<sqsubseteq> z\" ..\n  qed\nqed\n\ntheorem Sup_Inf: \"is_Sup {b. \\<forall>a \\<in> A. b \\<sqsubseteq> a} inf \\<Longrightarrow> is_Inf A inf\"\nproof -\n  assume \"is_Sup {b. \\<forall>a \\<in> A. b \\<sqsubseteq> a} inf\"\n  then have \"is_Inf (dual ` {b. \\<forall>a \\<in> A. dual a \\<sqsubseteq> dual b}) (dual inf)\"\n    by (simp only: dual_Inf dual_leq)\n  also have \"dual ` {b. \\<forall>a \\<in> A. dual a \\<sqsubseteq> dual b} = {b'. \\<forall>a' \\<in> dual ` A. a' \\<sqsubseteq> b'}\"\n    by (auto iff: dual_ball dual_Collect simp add: image_Collect)  (* FIXME !? *)\n  finally have \"is_Inf \\<dots> (dual inf)\" .\n  then have \"is_Sup (dual ` A) (dual inf)\"\n    by (rule Inf_Sup)\n  then show ?thesis ..\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Lattice/Bounds.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302034, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.774246197533586}}
{"text": "(*  \n    Title:      Determinants2.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Computing determinants of matrices using the Gauss Jordan algorithm*}\n\ntheory Determinants2\nimports\n  Gauss_Jordan_PA\nbegin\n\nsubsection{*Some previous properties*}\n\nsubsubsection{*Relationships between determinants and elementary row operations*}\n\nlemma det_interchange_rows:\nshows \"det (interchange_rows A i j) = of_int (if i = j then 1 else -1) * det A\"\nproof -\n  have \"(interchange_rows A i j) = (\\<chi> a. A $ (Fun.swap i j id) a)\" unfolding interchange_rows_def Fun.swap_def by vector\n  hence \"det(interchange_rows A i j) = det(\\<chi> a. A$(Fun.swap i j id) a)\" by simp\n  also have \"... = of_int (sign (Fun.swap i j id)) * det A\" by (rule det_permute_rows[of \"Fun.swap i j id\" A], simp add: permutes_swap_id)\n  finally show ?thesis unfolding sign_swap_id .\nqed\n\ncorollary det_interchange_different_rows:\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (interchange_rows A i j) = - det A\" unfolding det_interchange_rows using i_not_j by simp\n\ncorollary det_interchange_same_rows:\nassumes i_eq_j: \"i = j\"\nshows \"det (interchange_rows A i j) = det A\" unfolding det_interchange_rows using i_eq_j by simp\n\nlemma det_mult_row:\nshows \"det (mult_row A a k) = k * det A\"\nproof -\nhave A_rw: \"(\\<chi> i. if i = a then A$a else A$i) = A\" by vector\nhave \"(mult_row A a k) = (\\<chi> i. if i = a then k *s A $ a else A $ i)\" unfolding mult_row_def by vector\nhence \"det(mult_row A a k) = det(\\<chi> i. if i = a then k *s A $ a else A $ i)\" by simp\nalso have \"... =  k * det(\\<chi> i. if i = a then A$a else A$i)\" unfolding det_row_mul ..\nalso have \"... = k * det A\" unfolding A_rw ..\nfinally show ?thesis .\nqed\n\n(*The name det_row_add is already used in the Determinants.thy file of the standard library*)\nlemma det_row_add':\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (row_add A i j q) = det A\"\nproof -\nhave \"(row_add A i j q) = (\\<chi> k. if k = i then row i A + q *s row j A else row k A)\"\nunfolding row_add_def row_def by vector\nhence \"det(row_add A i j q) = det(\\<chi> k. if k = i then row i A + q *s row j A else row k A)\" by simp\nalso have \"... = det A\" unfolding det_row_operation[OF i_not_j] ..\nfinally show ?thesis .\nqed\n\n\nsubsubsection{*Relationships between determinants and elementary column operations*}\n\nlemma det_interchange_columns:\nshows \"det (interchange_columns A i j) = of_int (if i = j then 1 else -1) * det A\"\nproof - \nhave \"(interchange_columns A i j) = (\\<chi> a b. A $ a $ (Fun.swap i j id) b)\" unfolding interchange_columns_def Fun.swap_def by vector\nhence \"det(interchange_columns A i j) = det(\\<chi> a b. A $ a $ (Fun.swap i j id) b)\" by simp\nalso have \"... = of_int (sign (Fun.swap i j id)) * det A\" by (rule det_permute_columns[of \"Fun.swap i j id\" A], simp add: permutes_swap_id)\nfinally show ?thesis unfolding sign_swap_id .\nqed\n\ncorollary det_interchange_different_columns:\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (interchange_columns A i j) = - det A\" unfolding det_interchange_columns using i_not_j by simp\n\ncorollary det_interchange_same_columns:\nassumes i_eq_j: \"i = j\"\nshows \"det (interchange_columns A i j) = det A\" unfolding det_interchange_columns using i_eq_j by simp\n\nlemma det_mult_columns:\nshows \"det (mult_column A a k) = k * det A\"\nproof -\nhave \"mult_column A a k = transpose (mult_row (transpose A) a k)\" unfolding transpose_def mult_row_def mult_column_def by vector\nhence \"det (mult_column A a k) = det (transpose (mult_row (transpose A) a k))\" by simp\nalso have \"... = det (mult_row (transpose A) a k)\" unfolding det_transpose ..\nalso have \"... = k * det (transpose A)\" unfolding det_mult_row ..\nalso have \"... = k * det A\" unfolding det_transpose ..\nfinally show ?thesis .\nqed\n\nlemma det_column_add:\nassumes i_not_j: \"i \\<noteq> j\"\nshows \"det (column_add A i j q) = det A\"\nproof -\nhave \"(column_add A i j q) = (transpose (row_add (transpose A) i j q))\" unfolding transpose_def column_add_def row_add_def by vector\nhence \"det (column_add A i j q) = det (transpose (row_add (transpose A) i j q))\" by simp\nalso have \"... = det (row_add (transpose A) i j q)\" unfolding det_transpose ..\nalso have \"... = det A\" unfolding det_row_add'[OF i_not_j] det_transpose ..\nfinally show ?thesis .\nqed\n\nsubsection{*Proving that the determinant can be computed by means of the Gauss Jordan algorithm*}\n\nsubsubsection{*Previous properties*}\n\nlemma det_row_add_iterate_upt_n:\nfixes A::\"'a::{comm_ring_1}^'n::{mod_type}^'n::{mod_type}\"\nassumes n: \"n<nrows A\"\nshows \"det (row_add_iterate A n i j) = det A\"\nusing n\nproof (induct n arbitrary: A)\ncase 0\nshow ?case unfolding row_add_iterate.simps using det_row_add'[of 0 i A] by auto\nnext\ncase (Suc n)\nshow ?case  unfolding row_add_iterate.simps\nproof (auto)\nshow \"det (row_add_iterate A n i j) = det A\" using Suc.hyps Suc.prems by simp\nassume Suc_n_not_i: \"Suc n \\<noteq> to_nat i\"\nhave \"det (row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j) \n= det (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j))\"\nproof (rule Suc.hyps, unfold nrows_def)\nshow \" n < CARD('n)\" using Suc.prems unfolding nrows_def by auto\nqed\nalso have \"... = det A\"\n  proof (rule det_row_add',rule ccontr, simp)\n    assume \"from_nat (Suc n) = i\"\n      hence \"to_nat (from_nat (Suc n)::'n) = to_nat i\" by simp\n      hence \"(Suc n) = to_nat i\" unfolding to_nat_from_nat_id[OF Suc.prems[unfolded nrows_def]] .\n      thus False using Suc_n_not_i by contradiction\n    qed\nfinally show \"det (row_add_iterate (row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)) n i j) = det A\" .\nqed\nqed\n\n\ncorollary det_row_add_iterate:\nfixes A::\"'a::{comm_ring_1}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det (row_add_iterate A (nrows A - 1) i j) = det A\"\nby (metis det_row_add_iterate_upt_n diff_less neq0_conv nrows_not_0 zero_less_one)\n\n\n\nlemma det_Gauss_Jordan_in_ij:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\ndefines A': \"A'== mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) $ i $ j)\"\nshows \"det (Gauss_Jordan_in_ij A i j) = det A' \"\nproof -\nhave nrows_eq: \"nrows A' = nrows A\" unfolding nrows_def by simp\nhave \"row_add_iterate A' (nrows A - 1) i j  =  Gauss_Jordan_in_ij A i j\" using row_add_iterate_eq_Gauss_Jordan_in_ij  unfolding A' .\nhence \"det (Gauss_Jordan_in_ij A i j) = det (row_add_iterate A' (nrows A - 1) i j)\" by simp\nalso have \"... = det A'\" by (rule det_row_add_iterate[of A', unfolded nrows_eq])\nfinally show ?thesis .\nqed\n\n\nlemma det_Gauss_Jordan_in_ij_1:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\ndefines A': \"A'== mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) $ i $ j)\"\nassumes i: \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) = i\"\nshows \"det (Gauss_Jordan_in_ij A i j) = 1/(A$i$j) * det A\"\nproof -\nhave \"det (Gauss_Jordan_in_ij A i j) = det A' \" using det_Gauss_Jordan_in_ij unfolding A' by auto\nalso have \"... = 1/(A$i$j) * det A\" unfolding A' det_mult_row unfolding i det_interchange_rows by auto\nfinally show ?thesis .\nqed\n\n\nlemma det_Gauss_Jordan_in_ij_2:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\ndefines A': \"A'== mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) $ i $ j)\"\nassumes i: \"(LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) \\<noteq> i\"\nshows \"det (Gauss_Jordan_in_ij A i j) = - 1/(A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) * det A\"\nproof -\nhave \"det (Gauss_Jordan_in_ij A i j) = det A' \" using det_Gauss_Jordan_in_ij unfolding A' by auto\nalso have \"... = - 1/(A$ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $j) * det A\" unfolding A' det_mult_row unfolding det_interchange_rows using i by auto\nfinally show ?thesis .\nqed\n\nsubsubsection{*Definitions*}\n\ntext{*The following definitions allow the computation of the determinant of a matrix using the Gauss-Jordan algorithm. In the first component the determinant of each transformation\nis accumulated and the second component contains the matrix transformed into a reduced row echelon form matrix*}\n\ndefinition Gauss_Jordan_in_ij_det_P :: \"'a::{semiring_1, inverse, one, uminus}^'m^'n::{finite, ord}=> 'n=>'m=>('a \\<times> ('a^'m^'n::{finite, ord}))\"\n  where \"Gauss_Jordan_in_ij_det_P A i j = (let n = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) in (if i = n then 1/(A $ i $ j) else - 1/(A $ n $ j), Gauss_Jordan_in_ij A i j))\"\n\ndefinition Gauss_Jordan_column_k_det_P where \"Gauss_Jordan_column_k_det_P A' k =\n(let det_P= fst A'; i = fst (snd A'); A = snd (snd A'); from_nat_i = from_nat i; from_nat_k = from_nat k\n in if (\\<forall>m\\<ge>from_nat_i. A $ m $ from_nat_k = 0) \\<or> i = nrows A then (det_P, i, A)\n    else let gauss = Gauss_Jordan_in_ij_det_P A (from_nat_i) (from_nat_k) in (fst gauss * det_P, i + 1, snd gauss))\"\n\ndefinition Gauss_Jordan_upt_k_det_P \n  where \"Gauss_Jordan_upt_k_det_P A k = (let foldl = foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k] in (fst foldl, snd (snd foldl)))\"\ndefinition Gauss_Jordan_det_P \n  where \"Gauss_Jordan_det_P A = Gauss_Jordan_upt_k_det_P A (ncols A - 1)\"\n\nsubsubsection{*Proofs*}\n\ntext{*This is an equivalent definition created to achieve a more efficient computation.*}\nlemma Gauss_Jordan_in_ij_det_P_code[code]:\nshows \"Gauss_Jordan_in_ij_det_P A i j = \n    (let n = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n);\n         interchange_A = interchange_rows A i n;\n         A' = mult_row interchange_A i (1 / interchange_A $ i $ j) in (if i = n then 1/(A $ i $ j) else - 1/(A $ n $ j), Gauss_Jordan_wrapper i j A' interchange_A))\"\n         unfolding Gauss_Jordan_in_ij_det_P_def Gauss_Jordan_in_ij_def Gauss_Jordan_wrapper_def Let_def by auto\n\n\nlemma det_Gauss_Jordan_in_ij_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\" and i j::\"'n\"\nshows \"(fst (Gauss_Jordan_in_ij_det_P A i j)) * det A  = det (snd (Gauss_Jordan_in_ij_det_P A i j))\"\nunfolding Gauss_Jordan_in_ij_det_P_def Let_def fst_conv snd_conv\nusing det_Gauss_Jordan_in_ij_1[of A j i]\nusing det_Gauss_Jordan_in_ij_2[of A j i] by auto\n\n\nlemma det_Gauss_Jordan_column_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes det: \"det_P * det B = det A\"\nshows \"(fst (Gauss_Jordan_column_k_det_P (det_P,i,A) k)) * det B = det (snd (snd (Gauss_Jordan_column_k_det_P (det_P,i,A) k)))\"\nproof (unfold Gauss_Jordan_column_k_det_P_def Let_def, auto simp add: assms)\nfix m\nassume i_not_nrows: \"i \\<noteq> nrows A\"\nand i_less_m: \"from_nat i \\<le> m\"\nand Amk_not_0: \"A $ m $ from_nat k \\<noteq> 0\"\nshow  \"fst (Gauss_Jordan_in_ij_det_P A (from_nat i) (from_nat k)) * det_P * det B =\n        det (snd (Gauss_Jordan_in_ij_det_P A (from_nat i) (from_nat k)))\" unfolding mult.assoc det \n        unfolding det_Gauss_Jordan_in_ij_det_P ..\nqed\n\n\nlemma det_Gauss_Jordan_upt_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"(fst (Gauss_Jordan_upt_k_det_P A k)) * det A = det (snd (Gauss_Jordan_upt_k_det_P A k))\"\nproof (induct k)\ncase 0\nshow ?case\nunfolding Gauss_Jordan_upt_k_det_P_def Let_def unfolding fst_conv snd_conv by (simp add:det_Gauss_Jordan_column_k_det_P)\nnext\ncase (Suc k)\nhave suc_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [Suc k]\" by simp\nhave fold_expand: \"(foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k]) \n= (fst (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k]), fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])),\n  snd (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])))\" by simp\nshow ?case unfolding Gauss_Jordan_upt_k_det_P_def Let_def \nunfolding suc_rw foldl_append List.foldl.simps fst_conv snd_conv\nby(subst (1 2) fold_expand, rule det_Gauss_Jordan_column_k_det_P, rule Suc.hyps[unfolded Gauss_Jordan_upt_k_det_P_def Let_def fst_conv snd_conv])\nqed\n\n\nlemma det_Gauss_Jordan_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"(fst (Gauss_Jordan_det_P A)) * det A = det (snd (Gauss_Jordan_det_P A))\"\nusing det_Gauss_Jordan_upt_k_det_P unfolding Gauss_Jordan_det_P_def by simp\n\n\ndefinition upper_triangular_upt_k where \"upper_triangular_upt_k A k = (\\<forall>i j. j<i \\<and> to_nat j < k \\<longrightarrow> A $ i $ j = 0)\"\ndefinition upper_triangular where \"upper_triangular A = (\\<forall>i j. j<i \\<longrightarrow> A $ i $ j = 0)\"\n\nlemma upper_triangular_upt_imp_upper_triangular:\nassumes \"upper_triangular_upt_k A (nrows A)\"\nshows \"upper_triangular A\"\nusing assms unfolding upper_triangular_upt_k_def upper_triangular_def nrows_def\nusing to_nat_less_card[where ?'a='b] by blast\n\nlemma rref_imp_upper_triagular_upt:\nfixes A::\"'a::{one, zero}^'n::{mod_type}^'n::{mod_type}\"\nassumes \"reduced_row_echelon_form A\"\nshows \"upper_triangular_upt_k A k\"\nproof (induct k)\ncase 0\nshow ?case unfolding upper_triangular_upt_k_def by simp\nnext\ncase (Suc k)\nshow ?case unfolding upper_triangular_upt_k_def proof (clarify)\nfix i j::'n\nassume j_less_i: \"j < i\" and j_less_suc_k: \"to_nat j < Suc k\"\nshow \"A $ i $ j = 0\"\n  proof (cases \"to_nat j < k\")\n  case True\n  thus ?thesis using Suc.hyps unfolding upper_triangular_upt_k_def using j_less_i True by auto\n  next\n  case False\n  hence j_eq_k: \"to_nat j = k\" using j_less_suc_k by simp\n  have rref_suc: \"reduced_row_echelon_form_upt_k A (Suc k)\" by (metis assms rref_implies_rref_upt)\n \n  show ?thesis\n    proof (cases \"A $ i $ from_nat k = 0\")\n      case True\n      have \"from_nat k = j\" by (metis from_nat_to_nat_id j_eq_k)\n      thus ?thesis using True by simp\n      next\n      case False\n      have zero_i_k: \"is_zero_row_upt_k i k A\" unfolding is_zero_row_upt_k_def\n      by (metis (hide_lams, mono_tags) Suc.hyps dual_linorder.leD dual_linorder.le_less_linear dual_order.less_imp_le j_eq_k j_less_i le_trans to_nat_mono' upper_triangular_upt_k_def)\n      have not_zero_i_suc_k: \"\\<not> is_zero_row_upt_k i (Suc k) A\" unfolding is_zero_row_upt_k_def using False by (metis j_eq_k lessI to_nat_from_nat)      \n      have Least_eq: \"(LEAST n. A $ i $ n \\<noteq> 0) = from_nat k\"\n        proof (rule Least_equality)\n           show \"A $ i $ from_nat k \\<noteq> 0\" using False by simp\n           show \"\\<And>y. A $ i $ y \\<noteq> 0 \\<Longrightarrow> from_nat k \\<le> y\" by (metis (full_types) is_zero_row_upt_k_def not_leE to_nat_le zero_i_k)\n        qed\n      have i_not_k: \"i \\<noteq> from_nat k\" by (metis less_irrefl from_nat_to_nat_id j_eq_k j_less_i)\n      show ?thesis using rref_upt_condition4_explicit[OF rref_suc not_zero_i_suc_k i_not_k] unfolding Least_eq \n      using rref_upt_condition1_explicit[OF rref_suc]\n      using Suc.hyps unfolding upper_triangular_upt_k_def \n      by (metis (mono_tags) leD dual_linorder.not_leE is_zero_row_upt_k_def is_zero_row_upt_k_suc j_eq_k j_less_i not_zero_i_suc_k to_nat_from_nat to_nat_mono')  \nqed\nqed\nqed\nqed\n\nlemma rref_imp_upper_triagular:\nassumes \"reduced_row_echelon_form A\"\nshows \"upper_triangular A\" \nby (metis assms rref_imp_upper_triagular_upt upper_triangular_upt_imp_upper_triangular)\n\n\nlemma det_Gauss_Jordan[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det (Gauss_Jordan A) = setprod (\\<lambda>i. (Gauss_Jordan A)$i$i) (UNIV:: 'n set)\"\nusing det_upperdiagonal rref_imp_upper_triagular[OF rref_Gauss_Jordan[of A]] unfolding upper_triangular_def by blast\n\n\nlemma snd_Gauss_Jordan_in_ij_det_P_is_snd_Gauss_Jordan_in_ij_PA:\nshows \"snd (Gauss_Jordan_in_ij_det_P A i j) = snd (Gauss_Jordan_in_ij_PA (P,A) i j)\"\nunfolding Gauss_Jordan_in_ij_det_P_def Gauss_Jordan_in_ij_PA_def \nunfolding  Gauss_Jordan_in_ij_def Let_def snd_conv fst_conv ..\n\n\nlemma snd_Gauss_Jordan_column_k_det_P_is_snd_Gauss_Jordan_column_k_PA:\nshows \"snd (Gauss_Jordan_column_k_det_P (n,i,A) k) = snd (Gauss_Jordan_column_k_PA (P,i,A) k)\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def Let_def snd_conv unfolding fst_conv\nusing snd_Gauss_Jordan_in_ij_det_P_is_snd_Gauss_Jordan_in_ij_PA by auto\n\n\nlemma det_fst_row_add_iterate_PA:\nfixes A::\"'a::{comm_ring_1}^'n::{mod_type}^'n::{mod_type}\"\nassumes n: \"n<nrows A\"\nshows \"det (fst (row_add_iterate_PA (P,A) n i j)) = det P\"\nusing n\nproof (induct n arbitrary: P A)\ncase 0\nshow ?case unfolding row_add_iterate_PA.simps using det_row_add'[of 0 i P] by simp\nnext\ncase (Suc n)\nhave n: \"n<nrows A\" using Suc.prems by simp\nshow ?case\nproof (cases \"Suc n = to_nat i\")\ncase True show ?thesis unfolding row_add_iterate_PA.simps if_P[OF True] using Suc.hyps[OF n] .\nnext\ncase False \ndef P'==\"row_add P (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\ndef A'==\"row_add A (from_nat (Suc n)) i (- A $ from_nat (Suc n) $ j)\"\nhave n2: \"n< nrows A'\" using n unfolding nrows_def .\nhave \"det (fst (row_add_iterate_PA (P, A) (Suc n) i j)) = det (fst (row_add_iterate_PA (P', A') n i j))\" unfolding row_add_iterate_PA.simps if_not_P[OF False] P'_def A'_def ..\nalso have \"... = det P'\" using Suc.hyps[OF n2] .\nalso have \"... = det P\" unfolding P'_def \nproof (rule det_row_add', rule ccontr, simp)\n    assume \"from_nat (Suc n) = i\"\n      hence \"to_nat (from_nat (Suc n)::'n) = to_nat i\" by simp\n      hence \"(Suc n) = to_nat i\" unfolding to_nat_from_nat_id[OF Suc.prems[unfolded nrows_def]] .\n      thus False using False by contradiction\n    qed\nfinally show ?thesis .\nqed\nqed\n\n\n\nlemma det_fst_Gauss_Jordan_in_ij_PA_eq_fst_Gauss_Jordan_in_ij_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_in_ij_det_P A i j) * det P = det (fst (Gauss_Jordan_in_ij_PA (P,A) i j))\"\nproof -\ndef P'\\<equiv>\"mult_row (interchange_rows P i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j)\"\ndef A'\\<equiv>\"mult_row (interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)) i (1 / interchange_rows A i (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ i $ j)\"\nhave \"det (fst (Gauss_Jordan_in_ij_PA (P,A) i j)) = det (fst (row_add_iterate_PA (P',A') (nrows A - 1) i j))\"\nunfolding fst_row_add_iterate_PA_eq_fst_Gauss_Jordan_in_ij_PA[symmetric] A'_def P'_def ..\nalso have \"...= det P'\" by (rule det_fst_row_add_iterate_PA, simp add: nrows_def)\nalso have \"... = (if i = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) then 1 / A $ i $ j else - 1 / A $ (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n) $ j) * det P\"\nproof (cases \"i = (LEAST n. A $ n $ j \\<noteq> 0 \\<and> i \\<le> n)\")\ncase True show ?thesis \nunfolding if_P[OF True] P'_def unfolding True[symmetric] unfolding interchange_same_rows unfolding det_mult_row ..\nnext\ncase False\nshow ?thesis unfolding if_not_P[OF False] P'_def unfolding det_mult_row unfolding det_interchange_different_rows[OF False] by simp\nqed\nalso have \"... = fst (Gauss_Jordan_in_ij_det_P A i j) * det P\"\nunfolding Gauss_Jordan_in_ij_det_P_def by simp\nfinally show ?thesis ..\nqed\n\n\nlemma det_fst_Gauss_Jordan_column_k_PA_eq_fst_Gauss_Jordan_column_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_column_k_det_P (det P,i,A) k) = det (fst (Gauss_Jordan_column_k_PA (P,i,A) k))\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def Let_def snd_conv fst_conv\nusing det_fst_Gauss_Jordan_in_ij_PA_eq_fst_Gauss_Jordan_in_ij_det_P by auto\n\n\nlemma fst_snd_Gauss_Jordan_column_k_det_P_eq_fst_snd_Gauss_Jordan_column_k_PA:\nshows \"fst (snd (Gauss_Jordan_column_k_det_P (n,i,A) k)) = fst (snd (Gauss_Jordan_column_k_PA (P,i,A) k))\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def Let_def snd_conv fst_conv\nby auto\n\n\ntext{*The way of proving the following lemma is very similar to the demonstration of @{thm \"rref_and_index_Gauss_Jordan_upt_k\"}.*}\n\nlemma foldl_Gauss_Jordan_column_k_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows det_fst_Gauss_Jordan_upt_k_PA_eq_fst_Gauss_Jordan_upt_k_det_P: \"fst (Gauss_Jordan_upt_k_det_P A k) = det (fst (Gauss_Jordan_upt_k_PA A k))\"\nand snd_Gauss_Jordan_upt_k_det_P_is_snd_Gauss_Jordan_upt_k_PA: \"snd (Gauss_Jordan_upt_k_det_P A k) = snd (Gauss_Jordan_upt_k_PA A k)\"\nand fst_snd_foldl_Gauss_det_P_PA: \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k]))\"\nproof (induct k)\ncase 0\nshow \"fst (Gauss_Jordan_upt_k_det_P A 0) = det (fst (Gauss_Jordan_upt_k_PA A 0))\"\nunfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def\nby (simp, metis det_fst_Gauss_Jordan_column_k_PA_eq_fst_Gauss_Jordan_column_k_det_P det_I)\nshow \"snd (Gauss_Jordan_upt_k_det_P A 0) = snd (Gauss_Jordan_upt_k_PA A 0)\"\nunfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def snd_conv\napply auto using snd_Gauss_Jordan_column_k_det_P_is_snd_Gauss_Jordan_column_k_PA by metis\nshow \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc 0])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc 0]))\"\nunfolding Gauss_Jordan_column_k_det_P_def Gauss_Jordan_column_k_PA_def apply auto\nusing fst_snd_Gauss_Jordan_column_k_det_P_eq_fst_snd_Gauss_Jordan_column_k_PA by metis\nnext\nfix k\nassume hyp1: \"fst (Gauss_Jordan_upt_k_det_P A k) = det (fst (Gauss_Jordan_upt_k_PA A k))\"\nand hyp2: \"snd (Gauss_Jordan_upt_k_det_P A k) = snd (Gauss_Jordan_upt_k_PA A k)\"\nand hyp3: \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k]))\"\nhave list_rw: \"[0..<Suc (Suc k)] = [0..<Suc k] @ [Suc k]\" by simp\nhave det_mat_nn: \"det (mat 1::'a^'n::{mod_type}^'n::{mod_type}) = 1\" using det_I by simp\ndef f==\"foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k]\"\ndef g==\"foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k]\"\nhave f_rw: \"f = (fst f, fst (snd f), snd(snd f))\" by simp\nhave g_rw: \"g = (fst g, fst (snd g), snd(snd g))\" by simp\nhave fst_snd: \"fst (snd f) = fst (snd g)\" unfolding f_def g_def using hyp3 unfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv .\nhave snd_snd: \"snd (snd f) = snd (snd g)\" unfolding f_def g_def using hyp2 unfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def fst_conv snd_conv .\nhave fst_det: \"fst f = det (fst g)\" unfolding f_def g_def using hyp1 unfolding Gauss_Jordan_upt_k_det_P_def Gauss_Jordan_upt_k_PA_def Let_def fst_conv by simp\nshow \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc k])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc k])) \\<Longrightarrow>\n        fst (Gauss_Jordan_upt_k_det_P A (Suc k)) = det (fst (Gauss_Jordan_upt_k_PA A (Suc k)))\"\nunfolding Gauss_Jordan_upt_k_det_P_def  \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw foldl_append unfolding List.foldl.simps\nunfolding f_def[symmetric] g_def[symmetric]\napply (subst f_rw)\napply (subst g_rw)\nunfolding fst_snd snd_snd fst_det\nby (rule det_fst_Gauss_Jordan_column_k_PA_eq_fst_Gauss_Jordan_column_k_det_P)\nshow \"snd (Gauss_Jordan_upt_k_det_P A (Suc k)) = snd (Gauss_Jordan_upt_k_PA A (Suc k))\"\nunfolding Gauss_Jordan_upt_k_det_P_def  \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw foldl_append unfolding List.foldl.simps\nunfolding f_def[symmetric] g_def[symmetric]\napply (subst f_rw)\napply (subst g_rw)\nunfolding fst_snd snd_snd fst_det\nby (metis fst_snd pair_collapse snd_Gauss_Jordan_column_k_det_P_is_snd_Gauss_Jordan_column_k_PA snd_eqD snd_snd)\nshow \"fst (snd (foldl Gauss_Jordan_column_k_det_P (1, 0, A) [0..<Suc (Suc k)])) = fst (snd (foldl Gauss_Jordan_column_k_PA (mat 1, 0, A) [0..<Suc (Suc k)]))\"\nunfolding Gauss_Jordan_upt_k_det_P_def  \nunfolding Gauss_Jordan_upt_k_PA_def Let_def fst_conv\nunfolding list_rw foldl_append unfolding List.foldl.simps\nunfolding f_def[symmetric] g_def[symmetric]\napply (subst f_rw)\napply (subst g_rw)\nunfolding fst_snd snd_snd fst_det by (rule fst_snd_Gauss_Jordan_column_k_det_P_eq_fst_snd_Gauss_Jordan_column_k_PA)\nqed\n\n\n\nlemma snd_Gauss_Jordan_det_P_is_Gauss_Jordan:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"snd (Gauss_Jordan_det_P A) = (Gauss_Jordan A)\"\nunfolding Gauss_Jordan_det_P_def Gauss_Jordan_def unfolding snd_Gauss_Jordan_upt_k_det_P_is_snd_Gauss_Jordan_upt_k_PA \nsnd_Gauss_Jordan_upt_k_PA ..\n\n\nlemma det_snd_Gauss_Jordan_det_P[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det (snd (Gauss_Jordan_det_P A)) = setprod (\\<lambda>i. (snd (Gauss_Jordan_det_P A))$i$i) (UNIV:: 'n set)\"\nunfolding snd_Gauss_Jordan_det_P_is_Gauss_Jordan det_Gauss_Jordan ..\n\n\nlemma det_fst_Gauss_Jordan_PA_eq_fst_Gauss_Jordan_det_P:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_det_P A) = det (fst (Gauss_Jordan_PA A))\"\nby (unfold Gauss_Jordan_det_P_def Gauss_Jordan_PA_def, rule det_fst_Gauss_Jordan_upt_k_PA_eq_fst_Gauss_Jordan_upt_k_det_P)\n\n\nlemma fst_Gauss_Jordan_det_P_not_0:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"fst (Gauss_Jordan_det_P A) \\<noteq> 0\"\nunfolding det_fst_Gauss_Jordan_PA_eq_fst_Gauss_Jordan_det_P \nby (metis (mono_tags) det_I det_mul invertible_fst_Gauss_Jordan_PA matrix_inv_right mult_zero_left zero_neq_one)\n\n\nlemma det_code_equation[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"det A = (let A' = Gauss_Jordan_det_P A in setprod (\\<lambda>i. (snd (A'))$i$i) (UNIV::'n set)/(fst (A')))\"\nunfolding Let_def using det_Gauss_Jordan_det_P[of A]\nunfolding det_snd_Gauss_Jordan_det_P\nby (metis comm_semiring_1_class.normalizing_semiring_rules(7) fst_Gauss_Jordan_det_P_not_0 nonzero_eq_divide_eq)\n\n\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Gauss_Jordan/Determinants2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7742461964075726}}
{"text": "(*  Title:      HOL/Number_Theory/Cong.thy\n    Author:     Christophe Tabacznyj\n    Author:     Lawrence C. Paulson\n    Author:     Amine Chaieb\n    Author:     Thomas M. Rasmussen\n    Author:     Jeremy Avigad\n\nDefines congruence (notation: [x = y] (mod z)) for natural numbers and\nintegers.\n\nThis file combines and revises a number of prior developments.\n\nThe original theories \"GCD\" and \"Primes\" were by Christophe Tabacznyj\nand Lawrence C. Paulson, based on @{cite davenport92}. They introduced\ngcd, lcm, and prime for the natural numbers.\n\nThe original theory \"IntPrimes\" was by Thomas M. Rasmussen, and\nextended gcd, lcm, primes to the integers. Amine Chaieb provided\nanother extension of the notions to the integers, and added a number\nof results to \"Primes\" and \"GCD\".\n\nThe original theory, \"IntPrimes\", by Thomas M. Rasmussen, defined and\ndeveloped the congruence relations on the integers. The notion was\nextended to the natural numbers by Chaieb. Jeremy Avigad combined\nthese, revised and tidied them, made the development uniform for the\nnatural numbers and the integers, and added a number of new theorems.\n*)\n\nsection \\<open>Congruence\\<close>\n\ntheory Cong\n  imports \"HOL-Computational_Algebra.Primes\"\nbegin\n\nsubsection \\<open>Generic congruences\\<close>\n \ncontext unique_euclidean_semiring\nbegin\n\ndefinition cong :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (\\<open>(1[_ = _] '(' mod _'))\\<close>)\n  where \"cong b c a \\<longleftrightarrow> b mod a = c mod a\"\n  \nabbreviation notcong :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (\\<open>(1[_ \\<noteq> _] '(' mod _'))\\<close>)\n  where \"notcong b c a \\<equiv> \\<not> cong b c a\"\n\nlemma cong_refl [simp]:\n  \"[b = b] (mod a)\"\n  by (simp add: cong_def)\n\nlemma cong_sym: \n  \"[b = c] (mod a) \\<Longrightarrow> [c = b] (mod a)\"\n  by (simp add: cong_def)\n\nlemma cong_sym_eq:\n  \"[b = c] (mod a) \\<longleftrightarrow> [c = b] (mod a)\"\n  by (auto simp add: cong_def)\n\nlemma cong_trans [trans]:\n  \"[b = c] (mod a) \\<Longrightarrow> [c = d] (mod a) \\<Longrightarrow> [b = d] (mod a)\"\n  by (simp add: cong_def)\n\nlemma cong_mult_self_right:\n  \"[b * a = 0] (mod a)\"\n  by (simp add: cong_def)\n\nlemma cong_mult_self_left:\n  \"[a * b = 0] (mod a)\"\n  by (simp add: cong_def)\n\nlemma cong_mod_left [simp]:\n  \"[b mod a = c] (mod a) \\<longleftrightarrow> [b = c] (mod a)\"\n  by (simp add: cong_def)  \n\nlemma cong_mod_right [simp]:\n  \"[b = c mod a] (mod a) \\<longleftrightarrow> [b = c] (mod a)\"\n  by (simp add: cong_def)  \n\nlemma cong_0 [simp, presburger]:\n  \"[b = c] (mod 0) \\<longleftrightarrow> b = c\"\n  by (simp add: cong_def)\n\nlemma cong_1 [simp, presburger]:\n  \"[b = c] (mod 1)\"\n  by (simp add: cong_def)\n\nlemma cong_dvd_iff:\n  \"a dvd b \\<longleftrightarrow> a dvd c\" if \"[b = c] (mod a)\"\n  using that by (auto simp: cong_def dvd_eq_mod_eq_0)\n\nlemma cong_0_iff: \"[b = 0] (mod a) \\<longleftrightarrow> a dvd b\"\n  by (simp add: cong_def dvd_eq_mod_eq_0)\n\nlemma cong_add:\n  \"[b = c] (mod a) \\<Longrightarrow> [d = e] (mod a) \\<Longrightarrow> [b + d = c + e] (mod a)\"\n  by (auto simp add: cong_def intro: mod_add_cong)\n\nlemma cong_mult:\n  \"[b = c] (mod a) \\<Longrightarrow> [d = e] (mod a) \\<Longrightarrow> [b * d = c * e] (mod a)\"\n  by (auto simp add: cong_def intro: mod_mult_cong)\n\nlemma cong_scalar_right:\n  \"[b = c] (mod a) \\<Longrightarrow> [b * d = c * d] (mod a)\"\n  by (simp add: cong_mult)\n\nlemma cong_scalar_left:\n  \"[b = c] (mod a) \\<Longrightarrow> [d * b = d * c] (mod a)\"\n  by (simp add: cong_mult)\n\nlemma cong_pow:\n  \"[b = c] (mod a) \\<Longrightarrow> [b ^ n = c ^ n] (mod a)\"\n  by (simp add: cong_def power_mod [symmetric, of b n a] power_mod [symmetric, of c n a])\n\nlemma cong_sum:\n  \"[sum f A = sum g A] (mod a)\" if \"\\<And>x. x \\<in> A \\<Longrightarrow> [f x = g x] (mod a)\"\n  using that by (induct A rule: infinite_finite_induct) (auto intro: cong_add)\n\nlemma cong_prod:\n  \"[prod f A = prod g A] (mod a)\" if \"(\\<And>x. x \\<in> A \\<Longrightarrow> [f x = g x] (mod a))\"\n  using that by (induct A rule: infinite_finite_induct) (auto intro: cong_mult)\n\nlemma mod_mult_cong_right:\n  \"[c mod (a * b) = d] (mod a) \\<longleftrightarrow> [c = d] (mod a)\"\n  by (simp add: cong_def mod_mod_cancel mod_add_left_eq)\n\nlemma mod_mult_cong_left:\n  \"[c mod (b * a) = d] (mod a) \\<longleftrightarrow> [c = d] (mod a)\"\n  using mod_mult_cong_right [of c a b d] by (simp add: ac_simps)\n\nend\n\ncontext unique_euclidean_ring\nbegin\n\nlemma cong_diff:\n  \"[b = c] (mod a) \\<Longrightarrow> [d = e] (mod a) \\<Longrightarrow> [b - d = c - e] (mod a)\"\n  by (auto simp add: cong_def intro: mod_diff_cong)\n\nlemma cong_diff_iff_cong_0:\n  \"[b - c = 0] (mod a) \\<longleftrightarrow> [b = c] (mod a)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then have \"[b - c + c = 0 + c] (mod a)\"\n    by (rule cong_add) simp\n  then show ?Q\n    by simp\nnext\n  assume ?Q\n  with cong_diff [of b c a c c] show ?P\n    by simp\nqed\n\nlemma cong_minus_minus_iff:\n  \"[- b = - c] (mod a) \\<longleftrightarrow> [b = c] (mod a)\"\n  using cong_diff_iff_cong_0 [of b c a] cong_diff_iff_cong_0 [of \"- b\" \"- c\" a]\n  by (simp add: cong_0_iff dvd_diff_commute)\n\nlemma cong_modulus_minus_iff [iff]:\n  \"[b = c] (mod - a) \\<longleftrightarrow> [b = c] (mod a)\"\n  using cong_diff_iff_cong_0 [of b c a] cong_diff_iff_cong_0 [of b c \" -a\"]\n  by (simp add: cong_0_iff)\n\nlemma cong_iff_dvd_diff:\n  \"[a = b] (mod m) \\<longleftrightarrow> m dvd (a - b)\"\n  by (simp add: cong_0_iff [symmetric] cong_diff_iff_cong_0)\n\nlemma cong_iff_lin:\n  \"[a = b] (mod m) \\<longleftrightarrow> (\\<exists>k. b = a + m * k)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof -\n  have \"?P \\<longleftrightarrow> m dvd b - a\"\n    by (simp add: cong_iff_dvd_diff dvd_diff_commute)\n  also have \"\\<dots> \\<longleftrightarrow> ?Q\"\n    by (auto simp add: algebra_simps elim!: dvdE)\n  finally show ?thesis\n    by simp\nqed\n\nlemma cong_add_lcancel:\n  \"[a + x = a + y] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin algebra_simps)\n\nlemma cong_add_rcancel:\n  \"[x + a = y + a] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin algebra_simps)\n\nlemma cong_add_lcancel_0:\n  \"[a + x = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  using cong_add_lcancel [of a x 0 n] by simp\n\nlemma cong_add_rcancel_0:\n  \"[x + a = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  using cong_add_rcancel [of x a 0 n] by simp\n\nlemma cong_dvd_modulus:\n  \"[x = y] (mod n)\" if \"[x = y] (mod m)\" and \"n dvd m\"\n  using that by (auto intro: dvd_trans simp add: cong_iff_dvd_diff)\n\nlemma cong_modulus_mult:\n  \"[x = y] (mod m)\" if \"[x = y] (mod m * n)\"\n  using that by (simp add: cong_iff_dvd_diff) (rule dvd_mult_left)\n\nend\n\nlemma cong_abs [simp]:\n  \"[x = y] (mod \\<bar>m\\<bar>) \\<longleftrightarrow> [x = y] (mod m)\"\n  for x y :: \"'a :: {unique_euclidean_ring, linordered_idom}\"\n  by (simp add: cong_iff_dvd_diff)\n\nlemma cong_square:\n  \"prime p \\<Longrightarrow> 0 < a \\<Longrightarrow> [a * a = 1] (mod p) \\<Longrightarrow> [a = 1] (mod p) \\<or> [a = - 1] (mod p)\"\n  for a p :: \"'a :: {normalization_semidom, linordered_idom, unique_euclidean_ring}\"\n  by (auto simp add: cong_iff_dvd_diff square_diff_one_factored dest: prime_dvd_multD)\n\nlemma cong_mult_rcancel:\n  \"[a * k = b * k] (mod m) \\<longleftrightarrow> [a = b] (mod m)\"\n  if \"coprime k m\" for a k m :: \"'a::{unique_euclidean_ring, ring_gcd}\"\n  using that by (auto simp add: cong_iff_dvd_diff left_diff_distrib [symmetric] ac_simps coprime_dvd_mult_right_iff)\n\nlemma cong_mult_lcancel:\n  \"[k * a = k * b] (mod m) = [a = b] (mod m)\"\n  if \"coprime k m\" for a k m :: \"'a::{unique_euclidean_ring, ring_gcd}\"\n  using that cong_mult_rcancel [of k m a b] by (simp add: ac_simps)\n\nlemma coprime_cong_mult:\n  \"[a = b] (mod m) \\<Longrightarrow> [a = b] (mod n) \\<Longrightarrow> coprime m n \\<Longrightarrow> [a = b] (mod m * n)\"\n  for a b :: \"'a :: {unique_euclidean_ring, semiring_gcd}\"\n  by (simp add: cong_iff_dvd_diff divides_mult)\n\nlemma cong_gcd_eq:\n  \"gcd a m = gcd b m\" if \"[a = b] (mod m)\"\n  for a b :: \"'a :: {unique_euclidean_semiring, euclidean_semiring_gcd}\"\nproof (cases \"m = 0\")\n  case True\n  with that show ?thesis\n    by simp\nnext\n  case False\n  moreover have \"gcd (a mod m) m = gcd (b mod m) m\"\n    using that by (simp add: cong_def)\n  ultimately show ?thesis\n    by simp\nqed \n\nlemma cong_imp_coprime:\n  \"[a = b] (mod m) \\<Longrightarrow> coprime a m \\<Longrightarrow> coprime b m\"\n  for a b :: \"'a :: {unique_euclidean_semiring, euclidean_semiring_gcd}\"\n  by (auto simp add: coprime_iff_gcd_eq_1 dest: cong_gcd_eq)\n\nlemma cong_cong_prod_coprime:\n  \"[x = y] (mod (\\<Prod>i\\<in>A. m i))\" if\n    \"(\\<forall>i\\<in>A. [x = y] (mod m i))\"\n    \"(\\<forall>i\\<in>A. (\\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j)))\"\n  for x y :: \"'a :: {unique_euclidean_ring, semiring_gcd}\"\n  using that by (induct A rule: infinite_finite_induct)\n    (auto intro!: coprime_cong_mult prod_coprime_right)\n\n\nsubsection \\<open>Congruences on \\<^typ>\\<open>nat\\<close> and \\<^typ>\\<open>int\\<close>\\<close>\n\nlemma cong_int_iff:\n  \"[int m = int q] (mod int n) \\<longleftrightarrow> [m = q] (mod n)\"\n  by (simp add: cong_def of_nat_mod [symmetric])\n\nlemma cong_Suc_0 [simp, presburger]:\n  \"[m = n] (mod Suc 0)\"\n  using cong_1 [of m n] by simp\n\nlemma cong_diff_nat:\n  \"[a - c = b - d] (mod m)\" if \"[a = b] (mod m)\" \"[c = d] (mod m)\"\n    and \"a \\<ge> c\" \"b \\<ge> d\" for a b c d m :: nat\nproof -\n  have \"[c + (a - c) = d + (b - d)] (mod m)\"\n    using that by simp\n  with \\<open>[c = d] (mod m)\\<close> have \"[c + (a - c) = c + (b - d)] (mod m)\"\n    using mod_add_cong by (auto simp add: cong_def) fastforce\n  then show ?thesis\n    by (simp add: cong_def nat_mod_eq_iff)\nqed\n\nlemma cong_diff_iff_cong_0_nat:\n  \"[a - b = 0] (mod m) \\<longleftrightarrow> [a = b] (mod m)\" if \"a \\<ge> b\" for a b :: nat\n  using that by (simp add: cong_0_iff) (simp add: cong_def mod_eq_dvd_iff_nat)\n\nlemma cong_diff_iff_cong_0_nat':\n  \"[nat \\<bar>int a - int b\\<bar> = 0] (mod m) \\<longleftrightarrow> [a = b] (mod m)\"\nproof (cases \"b \\<le> a\")\n  case True\n  then show ?thesis\n    by (simp add: nat_diff_distrib' cong_diff_iff_cong_0_nat [of b a m])\nnext\n  case False\n  then have \"a \\<le> b\"\n    by simp\n  then show ?thesis\n    by (simp add: nat_diff_distrib' cong_diff_iff_cong_0_nat [of a b m])\n      (auto simp add: cong_def)\nqed\n\nlemma cong_altdef_nat:\n  \"a \\<ge> b \\<Longrightarrow> [a = b] (mod m) \\<longleftrightarrow> m dvd (a - b)\"\n  for a b :: nat\n  by (simp add: cong_0_iff [symmetric] cong_diff_iff_cong_0_nat)\n\nlemma cong_altdef_nat':\n  \"[a = b] (mod m) \\<longleftrightarrow> m dvd nat \\<bar>int a - int b\\<bar>\"\n  using cong_diff_iff_cong_0_nat' [of a b m]\n  by (simp only: cong_0_iff [symmetric])\n\nlemma cong_mult_rcancel_nat:\n  \"[a * k = b * k] (mod m) \\<longleftrightarrow> [a = b] (mod m)\"\n  if \"coprime k m\" for a k m :: nat\nproof -\n  have \"[a * k = b * k] (mod m) \\<longleftrightarrow> m dvd nat \\<bar>int (a * k) - int (b * k)\\<bar>\"\n    by (simp add: cong_altdef_nat')\n  also have \"\\<dots> \\<longleftrightarrow> m dvd nat \\<bar>(int a - int b) * int k\\<bar>\"\n    by (simp add: algebra_simps)\n  also have \"\\<dots> \\<longleftrightarrow> m dvd nat \\<bar>int a - int b\\<bar> * k\"\n    by (simp add: abs_mult nat_times_as_int)\n  also have \"\\<dots> \\<longleftrightarrow> m dvd nat \\<bar>int a - int b\\<bar>\"\n    by (rule coprime_dvd_mult_left_iff) (use \\<open>coprime k m\\<close> in \\<open>simp add: ac_simps\\<close>)\n  also have \"\\<dots> \\<longleftrightarrow> [a = b] (mod m)\"\n    by (simp add: cong_altdef_nat')\n  finally show ?thesis .\nqed\n\nlemma cong_mult_lcancel_nat:\n  \"[k * a = k * b] (mod m) = [a = b] (mod m)\"\n  if \"coprime k m\" for a k m :: nat\n  using that by (simp add: cong_mult_rcancel_nat ac_simps)\n\nlemma coprime_cong_mult_nat:\n  \"[a = b] (mod m) \\<Longrightarrow> [a = b] (mod n) \\<Longrightarrow> coprime m n \\<Longrightarrow> [a = b] (mod m * n)\"\n  for a b :: nat\n  by (simp add: cong_altdef_nat' divides_mult)\n\nlemma cong_less_imp_eq_nat: \"0 \\<le> a \\<Longrightarrow> a < m \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> b < m \\<Longrightarrow> [a = b] (mod m) \\<Longrightarrow> a = b\"\n  for a b :: nat\n  by (auto simp add: cong_def)\n\nlemma cong_less_imp_eq_int: \"0 \\<le> a \\<Longrightarrow> a < m \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> b < m \\<Longrightarrow> [a = b] (mod m) \\<Longrightarrow> a = b\"\n  for a b :: int\n  by (auto simp add: cong_def)\n\nlemma cong_less_unique_nat: \"0 < m \\<Longrightarrow> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  for a m :: nat\n  by (auto simp: cong_def) (metis mod_mod_trivial mod_less_divisor)\n\nlemma cong_less_unique_int: \"0 < m \\<Longrightarrow> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  for a m :: int\n  by (auto simp add: cong_def) (metis mod_mod_trivial pos_mod_bound pos_mod_sign)\n\nlemma cong_iff_lin_nat: \"[a = b] (mod m) \\<longleftrightarrow> (\\<exists>k1 k2. b + k1 * m = a + k2 * m)\"\n  for a b :: nat\n  apply (auto simp add: cong_def nat_mod_eq_iff)\n   apply (metis mult.commute)\n  apply (metis mult.commute)\n  done\n\nlemma cong_cong_mod_nat: \"[a = b] (mod m) \\<longleftrightarrow> [a mod m = b mod m] (mod m)\"\n  for a b :: nat\n  by simp\n\nlemma cong_cong_mod_int: \"[a = b] (mod m) \\<longleftrightarrow> [a mod m = b mod m] (mod m)\"\n  for a b :: int\n  by simp\n\nlemma cong_add_lcancel_nat: \"[a + x = a + y] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  for a x y :: nat\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_rcancel_nat: \"[x + a = y + a] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  for a x y :: nat\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_lcancel_0_nat: \"[a + x = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  for a x :: nat\n  using cong_add_lcancel_nat [of a x 0 n] by simp\n\nlemma cong_add_rcancel_0_nat: \"[x + a = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  for a x :: nat\n  using cong_add_rcancel_nat [of x a 0 n] by simp\n\nlemma cong_dvd_modulus_nat: \"[x = y] (mod m) \\<Longrightarrow> n dvd m \\<Longrightarrow> [x = y] (mod n)\"\n  for x y :: nat\n  by (auto simp add: cong_altdef_nat')\n\nlemma cong_to_1_nat:\n  fixes a :: nat\n  assumes \"[a = 1] (mod n)\"\n  shows \"n dvd (a - 1)\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis by force\nnext\n  case False\n  with assms show ?thesis by (metis cong_altdef_nat leI less_one)\nqed\n\nlemma cong_0_1_nat': \"[0 = Suc 0] (mod n) \\<longleftrightarrow> n = Suc 0\"\n  by (auto simp: cong_def)\n\nlemma cong_0_1_nat: \"[0 = 1] (mod n) \\<longleftrightarrow> n = 1\"\n  for n :: nat\n  by (auto simp: cong_def)\n\nlemma cong_0_1_int: \"[0 = 1] (mod n) \\<longleftrightarrow> n = 1 \\<or> n = - 1\"\n  for n :: int\n  by (auto simp: cong_def zmult_eq_1_iff)\n\nlemma cong_to_1'_nat: \"[a = 1] (mod n) \\<longleftrightarrow> a = 0 \\<and> n = 1 \\<or> (\\<exists>m. a = 1 + m * n)\"\n  for a :: nat\n  by (metis add.right_neutral cong_0_1_nat cong_iff_lin_nat cong_to_1_nat\n      dvd_div_mult_self leI le_add_diff_inverse less_one mult_eq_if)\n\nlemma cong_le_nat: \"y \\<le> x \\<Longrightarrow> [x = y] (mod n) \\<longleftrightarrow> (\\<exists>q. x = q * n + y)\"\n  for x y :: nat\n  by (auto simp add: cong_altdef_nat le_imp_diff_is_add)\n\nlemma cong_solve_nat:\n  fixes a :: nat\n  shows \"\\<exists>x. [a * x = gcd a n] (mod n)\"\nproof (cases \"a = 0 \\<or> n = 0\")\n  case True\n  then show ?thesis\n    by (force simp add: cong_0_iff cong_sym)\nnext\n  case False\n  then show ?thesis\n    using bezout_nat [of a n]\n    by auto (metis cong_add_rcancel_0_nat cong_mult_self_left)\nqed\n\nlemma cong_solve_int:\n  fixes a :: int\n  shows \"\\<exists>x. [a * x = gcd a n] (mod n)\"\n    by (metis bezout_int cong_iff_lin mult.commute)\n\nlemma cong_solve_dvd_nat:\n  fixes a :: nat\n  assumes \"gcd a n dvd d\"\n  shows \"\\<exists>x. [a * x = d] (mod n)\"\nproof -\n  from cong_solve_nat [of a] obtain x where \"[a * x = gcd a n](mod n)\"\n    by auto\n  then have \"[(d div gcd a n) * (a * x) = (d div gcd a n) * gcd a n] (mod n)\"\n    using cong_scalar_left by blast\n  also from assms have \"(d div gcd a n) * gcd a n = d\"\n    by (rule dvd_div_mult_self)\n  also have \"(d div gcd a n) * (a * x) = a * (d div gcd a n * x)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma cong_solve_dvd_int:\n  fixes a::int\n  assumes b: \"gcd a n dvd d\"\n  shows \"\\<exists>x. [a * x = d] (mod n)\"\nproof -\n  from cong_solve_int [of a] obtain x where \"[a * x = gcd a n](mod n)\"\n    by auto\n  then have \"[(d div gcd a n) * (a * x) = (d div gcd a n) * gcd a n] (mod n)\"\n    using cong_scalar_left by blast\n  also from b have \"(d div gcd a n) * gcd a n = d\"\n    by (rule dvd_div_mult_self)\n  also have \"(d div gcd a n) * (a * x) = a * (d div gcd a n * x)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma cong_solve_coprime_nat:\n  \"\\<exists>x. [a * x = Suc 0] (mod n)\" if \"coprime a n\"\n  using that cong_solve_nat [of a n] by auto\n\nlemma cong_solve_coprime_int:\n  \"\\<exists>x. [a * x = 1] (mod n)\" if \"coprime a n\" for a n x :: int\n  using that cong_solve_int [of a n] by (auto simp add: zabs_def split: if_splits)\n\nlemma coprime_iff_invertible_nat:\n  \"coprime a m \\<longleftrightarrow> (\\<exists>x. [a * x = Suc 0] (mod m))\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P then show ?Q\n    by (auto dest!: cong_solve_coprime_nat)\nnext\n  assume ?Q\n  then obtain b where \"[a * b = Suc 0] (mod m)\"\n    by blast\n  with coprime_mod_left_iff [of m \"a * b\"] show ?P\n    by (cases \"m = 0 \\<or> m = 1\")\n      (unfold cong_def, auto simp add: cong_def)\nqed\n\nlemma coprime_iff_invertible_int:\n  \"coprime a m \\<longleftrightarrow> (\\<exists>x. [a * x = 1] (mod m))\" (is \"?P \\<longleftrightarrow> ?Q\") for m :: int\nproof\n  assume ?P then show ?Q\n    by (auto dest: cong_solve_coprime_int)\nnext\n  assume ?Q\n  then obtain b where \"[a * b = 1] (mod m)\"\n    by blast\n  with coprime_mod_left_iff [of m \"a * b\"] show ?P\n    by (cases \"m = 0 \\<or> m = 1\")\n      (unfold cong_def, auto simp add: zmult_eq_1_iff)\nqed\n\nlemma coprime_iff_invertible'_nat:\n  assumes \"m > 0\"\n  shows \"coprime a m \\<longleftrightarrow> (\\<exists>x. 0 \\<le> x \\<and> x < m \\<and> [a * x = Suc 0] (mod m))\"\nproof -\n  have \"\\<And>b. \\<lbrakk>0 < m; [a * b = Suc 0] (mod m)\\<rbrakk> \\<Longrightarrow> \\<exists>b'<m. [a * b' = Suc 0] (mod m)\"\n    by (metis cong_def mod_less_divisor [OF assms] mod_mult_right_eq)\n  then show ?thesis\n    using assms coprime_iff_invertible_nat by auto\nqed\n\nlemma coprime_iff_invertible'_int:\n  fixes m :: int\n  assumes \"m > 0\"\n  shows \"coprime a m \\<longleftrightarrow> (\\<exists>x. 0 \\<le> x \\<and> x < m \\<and> [a * x = 1] (mod m))\"\n  using assms by (simp add: coprime_iff_invertible_int)\n    (metis assms cong_mod_left mod_mult_right_eq pos_mod_bound pos_mod_sign)\n\nlemma cong_cong_lcm_nat: \"[x = y] (mod a) \\<Longrightarrow> [x = y] (mod b) \\<Longrightarrow> [x = y] (mod lcm a b)\"\n  for x y :: nat\n  by (meson cong_altdef_nat' lcm_least)\n\nlemma cong_cong_lcm_int: \"[x = y] (mod a) \\<Longrightarrow> [x = y] (mod b) \\<Longrightarrow> [x = y] (mod lcm a b)\"\n  for x y :: int\n  by (auto simp add: cong_iff_dvd_diff lcm_least)\n\nlemma cong_cong_prod_coprime_nat:\n  \"[x = y] (mod (\\<Prod>i\\<in>A. m i))\" if\n    \"(\\<forall>i\\<in>A. [x = y] (mod m i))\"\n    \"(\\<forall>i\\<in>A. (\\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j)))\"\n  for x y :: nat\n  using that by (induct A rule: infinite_finite_induct)\n    (auto intro!: coprime_cong_mult_nat prod_coprime_right)\n\nlemma binary_chinese_remainder_nat:\n  fixes m1 m2 :: nat\n  assumes a: \"coprime m1 m2\"\n  shows \"\\<exists>x. [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  have \"\\<exists>b1 b2. [b1 = 1] (mod m1) \\<and> [b1 = 0] (mod m2) \\<and> [b2 = 0] (mod m1) \\<and> [b2 = 1] (mod m2)\"\n  proof -\n    from cong_solve_coprime_nat [OF a] obtain x1 where 1: \"[m1 * x1 = 1] (mod m2)\"\n      by auto\n    from a have b: \"coprime m2 m1\"\n      by (simp add: ac_simps)\n    from cong_solve_coprime_nat [OF b] obtain x2 where 2: \"[m2 * x2 = 1] (mod m1)\"\n      by auto\n    have \"[m1 * x1 = 0] (mod m1)\"\n      by (simp add: cong_mult_self_left)\n    moreover have \"[m2 * x2 = 0] (mod m2)\"\n      by (simp add: cong_mult_self_left)\n    ultimately show ?thesis\n      using 1 2 by blast\n  qed\n  then obtain b1 b2\n    where \"[b1 = 1] (mod m1)\" and \"[b1 = 0] (mod m2)\"\n      and \"[b2 = 0] (mod m1)\" and \"[b2 = 1] (mod m2)\"\n    by blast\n  let ?x = \"u1 * b1 + u2 * b2\"\n  have \"[?x = u1 * 1 + u2 * 0] (mod m1)\"\n    using \\<open>[b1 = 1] (mod m1)\\<close> \\<open>[b2 = 0] (mod m1)\\<close> cong_add cong_scalar_left by blast\n  then have \"[?x = u1] (mod m1)\" by simp\n  have \"[?x = u1 * 0 + u2 * 1] (mod m2)\"\n    using \\<open>[b1 = 0] (mod m2)\\<close> \\<open>[b2 = 1] (mod m2)\\<close> cong_add cong_scalar_left by blast\n  then have \"[?x = u2] (mod m2)\"\n    by simp\n  with \\<open>[?x = u1] (mod m1)\\<close> show ?thesis\n    by blast\nqed\n\nlemma binary_chinese_remainder_int:\n  fixes m1 m2 :: int\n  assumes a: \"coprime m1 m2\"\n  shows \"\\<exists>x. [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  have \"\\<exists>b1 b2. [b1 = 1] (mod m1) \\<and> [b1 = 0] (mod m2) \\<and> [b2 = 0] (mod m1) \\<and> [b2 = 1] (mod m2)\"\n  proof -\n    from cong_solve_coprime_int [OF a] obtain x1 where 1: \"[m1 * x1 = 1] (mod m2)\"\n      by auto\n    from a have b: \"coprime m2 m1\"\n      by (simp add: ac_simps)\n    from cong_solve_coprime_int [OF b] obtain x2 where 2: \"[m2 * x2 = 1] (mod m1)\"\n      by auto\n    have \"[m1 * x1 = 0] (mod m1)\"\n     by (simp add: cong_mult_self_left)\n    moreover have \"[m2 * x2 = 0] (mod m2)\"\n      by (simp add: cong_mult_self_left)\n    ultimately show ?thesis\n      using 1 2 by blast\n  qed\n  then obtain b1 b2\n    where \"[b1 = 1] (mod m1)\" and \"[b1 = 0] (mod m2)\"\n      and \"[b2 = 0] (mod m1)\" and \"[b2 = 1] (mod m2)\"\n    by blast\n  let ?x = \"u1 * b1 + u2 * b2\"\n  have \"[?x = u1 * 1 + u2 * 0] (mod m1)\"\n    using \\<open>[b1 = 1] (mod m1)\\<close> \\<open>[b2 = 0] (mod m1)\\<close> cong_add cong_scalar_left by blast\n  then have \"[?x = u1] (mod m1)\" by simp\n  have \"[?x = u1 * 0 + u2 * 1] (mod m2)\"\n    using \\<open>[b1 = 0] (mod m2)\\<close> \\<open>[b2 = 1] (mod m2)\\<close> cong_add cong_scalar_left by blast\n  then have \"[?x = u2] (mod m2)\" by simp\n  with \\<open>[?x = u1] (mod m1)\\<close> show ?thesis\n    by blast\nqed\n\nlemma cong_modulus_mult_nat: \"[x = y] (mod m * n) \\<Longrightarrow> [x = y] (mod m)\"\n  for x y :: nat\n  by (metis cong_def mod_mult_cong_right)\n\nlemma cong_less_modulus_unique_nat: \"[x = y] (mod m) \\<Longrightarrow> x < m \\<Longrightarrow> y < m \\<Longrightarrow> x = y\"\n  for x y :: nat\n  by (simp add: cong_def)\n\nlemma binary_chinese_remainder_unique_nat:\n  fixes m1 m2 :: nat\n  assumes a: \"coprime m1 m2\"\n    and nz: \"m1 \\<noteq> 0\" \"m2 \\<noteq> 0\"\n  shows \"\\<exists>!x. x < m1 * m2 \\<and> [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  obtain y where y1: \"[y = u1] (mod m1)\" and y2: \"[y = u2] (mod m2)\"\n    using binary_chinese_remainder_nat [OF a] by blast\n  let ?x = \"y mod (m1 * m2)\"\n  from nz have less: \"?x < m1 * m2\"\n    by auto\n  have 1: \"[?x = u1] (mod m1)\"\n    using y1 mod_mult_cong_right by blast\n  have 2: \"[?x = u2] (mod m2)\"\n    using y2 mod_mult_cong_left by blast\n  have \"z = ?x\" if \"z < m1 * m2\" \"[z = u1] (mod m1)\"  \"[z = u2] (mod m2)\" for z\n  proof -\n    have \"[?x = z] (mod m1)\"\n      by (metis \"1\" cong_def that(2))\n    moreover have \"[?x = z] (mod m2)\"\n      by (metis \"2\" cong_def that(3))\n    ultimately have \"[?x = z] (mod m1 * m2)\"\n      using a by (auto intro: coprime_cong_mult_nat simp add: mod_mult_cong_left mod_mult_cong_right)\n    with \\<open>z < m1 * m2\\<close> \\<open>?x < m1 * m2\\<close> show \"z = ?x\"\n      by (auto simp add: cong_def)\n  qed\n  with less 1 2 show ?thesis\n    by blast\n qed\n\nlemma chinese_remainder_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n    and u :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and cop: \"\\<forall>i \\<in> A. \\<forall>j \\<in> A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j)\"\n  shows \"\\<exists>x. \\<forall>i \\<in> A. [x = u i] (mod m i)\"\nproof -\n  have \"\\<exists>b. (\\<forall>i \\<in> A. [b i = 1] (mod m i) \\<and> [b i = 0] (mod (\\<Prod>j \\<in> A - {i}. m j)))\"\n  proof (rule finite_set_choice, rule fin, rule ballI)\n    fix i\n    assume \"i \\<in> A\"\n    with cop have \"coprime (\\<Prod>j \\<in> A - {i}. m j) (m i)\"\n      by (intro prod_coprime_left) auto\n    then have \"\\<exists>x. [(\\<Prod>j \\<in> A - {i}. m j) * x = Suc 0] (mod m i)\"\n      by (elim cong_solve_coprime_nat)\n    then obtain x where \"[(\\<Prod>j \\<in> A - {i}. m j) * x = 1] (mod m i)\"\n      by auto\n    moreover have \"[(\\<Prod>j \\<in> A - {i}. m j) * x = 0] (mod (\\<Prod>j \\<in> A - {i}. m j))\"\n      by (simp add: cong_0_iff)\n    ultimately show \"\\<exists>a. [a = 1] (mod m i) \\<and> [a = 0] (mod prod m (A - {i}))\"\n      by blast\n  qed\n  then obtain b where b: \"\\<And>i. i \\<in> A \\<Longrightarrow> [b i = 1] (mod m i) \\<and> [b i = 0] (mod (\\<Prod>j \\<in> A - {i}. m j))\"\n    by blast\n  let ?x = \"\\<Sum>i\\<in>A. (u i) * (b i)\"\n  show ?thesis\n  proof (rule exI, clarify)\n    fix i\n    assume a: \"i \\<in> A\"\n    show \"[?x = u i] (mod m i)\"\n    proof -\n      from fin a have \"?x = (\\<Sum>j \\<in> {i}. u j * b j) + (\\<Sum>j \\<in> A - {i}. u j * b j)\"\n        by (subst sum.union_disjoint [symmetric]) (auto intro: sum.cong)\n      then have \"[?x = u i * b i + (\\<Sum>j \\<in> A - {i}. u j * b j)] (mod m i)\"\n        by auto\n      also have \"[u i * b i + (\\<Sum>j \\<in> A - {i}. u j * b j) =\n                  u i * 1 + (\\<Sum>j \\<in> A - {i}. u j * 0)] (mod m i)\"\n      proof (intro cong_add cong_scalar_left cong_sum)\n        show \"[b i = 1] (mod m i)\"\n          using a b by blast\n        show \"[b x = 0] (mod m i)\" if \"x \\<in> A - {i}\" for x\n        proof -\n          have \"x \\<in> A\" \"x \\<noteq> i\"\n            using that by auto\n          then show ?thesis\n            using a b [OF \\<open>x \\<in> A\\<close>] cong_dvd_modulus_nat fin by blast\n        qed\n      qed\n      finally show ?thesis\n        by simp\n    qed\n  qed\nqed\n\nlemma coprime_cong_prod_nat: \"[x = y] (mod (\\<Prod>i\\<in>A. m i))\"\n  if \"\\<And>i j. \\<lbrakk>i \\<in> A; j \\<in> A; i \\<noteq> j\\<rbrakk> \\<Longrightarrow> coprime (m i) (m j)\"\n    and \"\\<And>i. i \\<in> A \\<Longrightarrow> [x = y] (mod m i)\" for x y :: nat\n  using that \nproof (induct A rule: infinite_finite_induct)\n  case (insert x A)\n  then show ?case\n    by simp (metis coprime_cong_mult_nat prod_coprime_right)\nqed auto\n\nlemma chinese_remainder_unique_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n    and u :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and nz: \"\\<forall>i\\<in>A. m i \\<noteq> 0\"\n    and cop: \"\\<forall>i\\<in>A. \\<forall>j\\<in>A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j)\"\n  shows \"\\<exists>!x. x < (\\<Prod>i\\<in>A. m i) \\<and> (\\<forall>i\\<in>A. [x = u i] (mod m i))\"\nproof -\n  from chinese_remainder_nat [OF fin cop]\n  obtain y where one: \"(\\<forall>i\\<in>A. [y = u i] (mod m i))\"\n    by blast\n  let ?x = \"y mod (\\<Prod>i\\<in>A. m i)\"\n  from fin nz have prodnz: \"(\\<Prod>i\\<in>A. m i) \\<noteq> 0\"\n    by auto\n  then have less: \"?x < (\\<Prod>i\\<in>A. m i)\"\n    by auto\n  have cong: \"\\<forall>i\\<in>A. [?x = u i] (mod m i)\"\n    using fin one\n    by (auto simp add: cong_def dvd_prod_eqI mod_mod_cancel) \n  have unique: \"\\<forall>z. z < (\\<Prod>i\\<in>A. m i) \\<and> (\\<forall>i\\<in>A. [z = u i] (mod m i)) \\<longrightarrow> z = ?x\"\n  proof clarify\n    fix z\n    assume zless: \"z < (\\<Prod>i\\<in>A. m i)\"\n    assume zcong: \"(\\<forall>i\\<in>A. [z = u i] (mod m i))\"\n    have \"\\<forall>i\\<in>A. [?x = z] (mod m i)\"\n      using cong zcong by (auto simp add: cong_def)\n    with fin cop have \"[?x = z] (mod (\\<Prod>i\\<in>A. m i))\"\n      by (intro coprime_cong_prod_nat) auto\n    with zless less show \"z = ?x\"\n      by (auto simp add: cong_def)\n  qed\n  from less cong unique show ?thesis\n    by blast\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Number_Theory/Cong.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8840392863287585, "lm_q1q2_score": 0.774230112804607}}
{"text": "(*  Title:       Defintion and basics facts about Cantor pairing function\n    Author:      Michael Nedzelsky <MichaelNedzelsky at yandex.ru>, 2008\n    Maintainer:  Michael Nedzelsky <MichaelNedzelsky at yandex.ru>\n*)\n\nsection \\<open>Cantor pairing function\\<close>\n\ntheory CPair\nimports Main\nbegin\n\ntext \\<open>\n  We introduce a particular coding \\<open>c_pair\\<close> from ordered pairs\n  of natural numbers to natural numbers.  See \\<^cite>\\<open>\"Rogers\"\\<close> and the\n  Isabelle documentation for more information.\n\\<close>\n\nsubsection \\<open>Pairing function\\<close>\n\ndefinition\n  sf :: \"nat \\<Rightarrow> nat\" where\n  sf_def: \"sf x = x * (x+1) div 2\"\n\ndefinition\n  c_pair :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"c_pair x y = sf (x+y) + x\"\n\nlemma sf_at_0: \"sf 0 = 0\" by (simp add: sf_def)\n\nlemma sf_at_1: \"sf 1 = 1\" by (simp add: sf_def)\n\nlemma sf_at_Suc: \"sf (x+1) = sf x + x + 1\"\nproof -\n  have S1: \"sf(x+1) = ((x+1)*(x+2)) div 2\" by (simp add: sf_def)\n  have S2: \"(x+1)*(x+2) = x*(x+1) + 2*(x+1)\" by (auto)\n  have S2_1: \"\\<And> x y. x=y \\<Longrightarrow> x div 2 = y div 2\" by auto\n  from S2 have S3: \"(x+1)*(x+2) div 2 = (x*(x+1) + 2*(x+1)) div 2\" by (rule S2_1)\n  have S4: \"(0::nat) < 2\" by (auto)\n  from S4 have S5: \"(x*(x+1) + 2*(x+1)) div 2 = (x+1) + x*(x+1) div 2\" by simp\n  from S1 S3 S5 show ?thesis by (simp add: sf_def)\nqed\n\nlemma arg_le_sf: \"x \\<le> sf x\"\nproof -\n  have \"x + x \\<le> x*(x + 1)\" by simp\n  hence \"(x + x) div 2 \\<le> x*(x+1) div 2\" by (rule div_le_mono)\n  hence \"x \\<le> x*(x+1) div 2\" by simp\n  thus ?thesis by (simp add: sf_def)\nqed\n\nlemma sf_mono: \"x \\<le> y \\<Longrightarrow> sf x \\<le> sf y\"\nproof -\n  assume A1: \"x \\<le> y\"\n  then have \"x+1 \\<le> y+1\" by (auto)\n  with A1 have \"x*(x+1) \\<le> y*(y+1)\" by (rule mult_le_mono)\n  then have \"x*(x+1) div 2 \\<le> y*(y+1) div 2\" by (rule div_le_mono)\n  thus ?thesis by (simp add: sf_def)\nqed\n\nlemma sf_strict_mono: \"x < y \\<Longrightarrow> sf x < sf y\"\nproof -\n  assume A1: \"x < y\"\n  from A1 have S1: \"x+1 \\<le> y\" by simp\n  from S1 sf_mono have S2: \"sf (x+1) \\<le> sf y\" by (auto)\n  from sf_at_Suc have S3: \"sf x < sf (x+1)\" by (auto)\n  from S2 S3 show ?thesis by (auto)\nqed\n\nlemma sf_posI: \"x > 0 \\<Longrightarrow> sf(x) > 0\"\nproof -\n  assume A1: \"x > 0\"\n  then have \"sf(0) < sf(x)\" by (rule sf_strict_mono)\n  then show ?thesis by simp\nqed\n\nlemma arg_less_sf: \"x > 1 \\<Longrightarrow> x < sf(x)\"\nproof -\n  assume A1: \"x > 1\"\n  let ?y = \"x-(1::nat)\"\n  from A1 have S1: \"x = ?y+1\" by simp\n  from A1 have \"?y > 0\" by simp\n  then have S2: \"sf(?y) > 0\" by (rule sf_posI)\n  have \"sf(?y+1) = sf(?y) + ?y + 1\" by (rule sf_at_Suc)\n  with S1 have \"sf(x) = sf(?y) + x\" by simp\n  with S2  show ?thesis by simp\nqed\n\nlemma sf_eq_arg: \"sf x = x \\<Longrightarrow> x \\<le> 1\"\nproof -\n  assume \"sf(x) = x\"\n  then have \"\\<not> (x < sf(x))\" by simp\n  then have \"(\\<not> (x > 1))\" by (auto simp add: arg_less_sf)\n  then show ?thesis by simp\nqed\n\nlemma sf_le_sfD: \"sf x \\<le> sf y \\<Longrightarrow> x \\<le> y\"\nproof -\n  assume A1: \"sf x \\<le> sf y\"\n  have S1: \"y < x \\<Longrightarrow> sf y < sf x\" by (rule sf_strict_mono)\n  have S2: \"y < x \\<or> x \\<le> y\" by (auto)\n  from A1 S1 S2 show ?thesis by (auto)\nqed\n\nlemma sf_less_sfD: \"sf x < sf y \\<Longrightarrow> x < y\"\nproof -\n  assume A1: \"sf x < sf y\"\n  have S1: \"y \\<le> x \\<Longrightarrow> sf y \\<le> sf x\" by (rule sf_mono)\n  have S2: \"y \\<le> x \\<or> x < y\" by (auto)\n  from A1 S1 S2 show ?thesis by (auto)\nqed\n\nlemma sf_inj: \"sf x = sf y \\<Longrightarrow> x = y\"\nproof -\n  assume A1: \"sf x = sf y\"\n  have S1: \"sf x \\<le> sf y \\<Longrightarrow> x \\<le> y\" by (rule sf_le_sfD)\n  have S2: \"sf y \\<le> sf x \\<Longrightarrow> y \\<le> x\" by (rule sf_le_sfD)\n  from A1 have S3: \"sf x \\<le> sf y \\<and> sf y \\<le> sf x\" by (auto)\n  from S3 S1 S2 have S4: \"x \\<le> y \\<and> y \\<le> x\" by (auto)\n  from S4 show ?thesis by (auto)\nqed\n\ntext \\<open>Auxiliary lemmas\\<close>\n\nlemma sf_aux1: \"x + y < z \\<Longrightarrow> sf(x+y) + x < sf(z)\"\nproof -\n  assume A1: \"x+y < z\"\n  from A1 have S1: \"x+y+1 \\<le> z\" by (auto)\n  from S1 have S2: \"sf(x+y+1) \\<le> sf(z)\" by (rule sf_mono)\n  have S3: \"sf(x+y+1) = sf(x+y) + (x+y)+1\" by (rule sf_at_Suc)\n  from S3 S2 have S4: \"sf(x+y) + (x+y) + 1 \\<le> sf(z)\" by (auto)\n  from S4 show ?thesis by (auto)\nqed\n\nlemma sf_aux2: \"sf(z) \\<le> sf(x+y) + x \\<Longrightarrow> z \\<le> x+y\"\nproof -\n  assume A1: \"sf(z) \\<le> sf(x+y) + x\"\n  from A1 have S1: \"\\<not> sf(x+y) +x < sf(z)\" by (auto)\n  from S1 sf_aux1 have S2: \"\\<not> x+y < z\" by (auto)\n  from S2 show ?thesis by (auto)\nqed\n\nlemma sf_aux3: \"sf(z) + m < sf(z+1) \\<Longrightarrow> m \\<le> z\"\nproof -\n  assume A1: \"sf(z) + m < sf(z+1)\"\n  have S1: \"sf(z+1) = sf(z) + z + 1\" by (rule sf_at_Suc)\n  from A1 S1 have S2: \"sf(z) + m < sf(z) + z + 1\" by (auto)\n  from S2 have S3: \"m < z + 1\" by (auto)\n  from S3 show ?thesis by (auto)\nqed\n\nlemma sf_aux4: \"(s::nat) < t \\<Longrightarrow> (sf s) + s < sf t\"\nproof -\n  assume A1: \"(s::nat) < t\"\n  have \"s*(s + 1) + 2*(s+1) \\<le> t*(t+1)\"\n  proof -\n    from A1 have S1: \"(s::nat) + 1 \\<le> t\" by (auto)\n    from A1 have \"(s::nat) + 2 \\<le> t+1\" by (auto)\n    with S1 have \"((s::nat)+1)*(s+2) \\<le> t*(t+1)\" by (rule mult_le_mono)\n    thus ?thesis by (auto)\n  qed\n  then have S1: \"(s*(s+1) + 2*(s+1)) div 2 \\<le>  t*(t+1) div 2\" by (rule div_le_mono)\n  have \"(0::nat) < 2\" by (auto)\n  then have \"(s*(s+1) + 2*(s+1)) div 2 = (s+1) + (s*(s+1)) div 2\" by simp\n  with S1 have \"(s*(s+1)) div 2 + (s+1) \\<le> t*(t+1) div 2\" by (auto)\n  then have \"(s*(s+1)) div 2 + s < t*(t+1) div 2\" by (auto)\n  thus ?thesis by (simp add: sf_def)  \nqed\n\ntext \\<open>Basic properties of c\\_pair function\\<close>\n\nlemma sum_le_c_pair: \"x + y \\<le> c_pair x y\"\nproof -\n  have \"x+y \\<le> sf(x+y)\" by (rule arg_le_sf)\n  thus ?thesis by (simp add: c_pair_def)\nqed\n\nlemma arg1_le_c_pair: \"x \\<le> c_pair x y\"\nproof -\n  have \"(x::nat) \\<le> x + y\" by (simp)\n  moreover have \"x + y \\<le> c_pair x y\" by (rule sum_le_c_pair)\n  ultimately show ?thesis by (simp)\nqed\n\nlemma arg2_le_c_pair: \"y \\<le> c_pair x y\"\nproof -\n  have \"(y::nat) \\<le> x + y\" by (simp)\n  moreover have \"x + y \\<le> c_pair x y\" by (rule sum_le_c_pair)\n  ultimately show ?thesis by (simp)\nqed\n\nlemma c_pair_sum_mono: \"(x1::nat) + y1 < x2 + y2 \\<Longrightarrow> c_pair x1 y1 < c_pair x2 y2\"\nproof -\n  assume \"(x1::nat) + y1 < x2 + y2\"\n  hence \"sf (x1+y1) + (x1+y1) < sf(x2+y2)\" by (rule sf_aux4)\n  hence \"sf (x1+y1) + x1 < sf(x2+y2) + x2\" by (auto)\n  thus ?thesis by (simp add: c_pair_def)\nqed\n\nlemma c_pair_sum_inj: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> x1 + y1 = x2 + y2\"\nproof -\n  assume A1: \"c_pair x1 y1 = c_pair x2 y2\"\n  have S1: \"(x1::nat) + y1 < x2 + y2 \\<Longrightarrow> c_pair x1 y1 \\<noteq> c_pair x2 y2\" by (rule less_not_refl3, rule c_pair_sum_mono, auto)\n  have S2: \"(x2::nat) + y2 < x1 + y1 \\<Longrightarrow> c_pair x1 y1 \\<noteq> c_pair x2 y2\" by (rule less_not_refl2, rule c_pair_sum_mono, auto)\n  from S1 S2 have \"(x1::nat) + y1 \\<noteq> x2 + y2 \\<Longrightarrow> c_pair x1 y1 \\<noteq> c_pair x2 y2\" by (arith)\n  with A1 show ?thesis by (auto)\nqed\n\nlemma c_pair_inj: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> x1 = x2 \\<and> y1 = y2\"\nproof -\n  assume A1: \"c_pair x1 y1 = c_pair x2 y2\"\n  from A1 have S1: \"x1 + y1 = x2 + y2\" by (rule c_pair_sum_inj)\n  from A1 have S2: \"sf (x1+y1) + x1 = sf (x2+y2) + x2\" by (unfold c_pair_def)\n  from S1 S2 have S3: \"x1 = x2\" by (simp)\n  from S1 S3 have S4: \"y1 = y2\" by (simp)\n  from S3 S4 show ?thesis by (auto)\nqed\n\nlemma c_pair_inj1: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> x1 = x2\" by (frule c_pair_inj, drule conjunct1)\n\nlemma c_pair_inj2: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> y1 = y2\" by (frule c_pair_inj, drule conjunct2)\n\nlemma c_pair_strict_mono1: \"x1 < x2 \\<Longrightarrow> c_pair x1 y < c_pair x2 y\"\nproof -\n  assume \"x1 < x2\"\n  then have \"x1 + y < x2 + y\" by simp\n  then show ?thesis by (rule c_pair_sum_mono)\nqed\n\nlemma c_pair_mono1: \"x1 \\<le> x2 \\<Longrightarrow> c_pair x1 y \\<le> c_pair x2 y\"\nproof -\n  assume A1: \"x1 \\<le> x2\"\n  show ?thesis\n  proof cases\n    assume \"x1 < x2\"\n    then have \"c_pair x1 y < c_pair x2 y\" by (rule c_pair_strict_mono1)\n    then show ?thesis by simp\n  next\n    assume \"\\<not> x1 < x2\"\n    with A1 have \"x1 = x2\" by simp\n    then show ?thesis by simp\n  qed\nqed\n\nlemma c_pair_strict_mono2: \"y1 < y2 \\<Longrightarrow> c_pair x y1 < c_pair x y2\"\nproof -\n  assume A1: \"y1 < y2\"\n  from A1 have S1: \"x + y1 < x + y2\" by simp\n  then show ?thesis by (rule c_pair_sum_mono)\nqed\n\nlemma c_pair_mono2: \"y1 \\<le> y2 \\<Longrightarrow> c_pair x y1 \\<le> c_pair x y2\"\nproof -\n  assume A1: \"y1 \\<le> y2\"\n  show ?thesis\n  proof cases\n    assume \"y1 < y2\"\n    then have \"c_pair x y1 < c_pair x y2\" by (rule c_pair_strict_mono2)\n    then show ?thesis by simp\n  next\n    assume \"\\<not> y1 < y2\"\n    with A1 have \"y1 = y2\" by simp\n    then show ?thesis by simp\n  qed\nqed\n\nsubsection \\<open>Inverse mapping\\<close>\n\ntext \\<open>\n  \\<open>c_fst\\<close> and \\<open>c_snd\\<close> are the functions which yield\n  the inverse mapping to \\<open>c_pair\\<close>.\n\\<close>\n\ndefinition\n  c_sum :: \"nat \\<Rightarrow> nat\" where\n  \"c_sum u = (LEAST z. u < sf (z+1))\"\n\ndefinition\n  c_fst :: \"nat \\<Rightarrow> nat\" where\n  \"c_fst u = u - sf (c_sum u)\"\n\ndefinition\n  c_snd :: \"nat \\<Rightarrow> nat\" where\n  \"c_snd u = c_sum u - c_fst u\"\n\nlemma arg_less_sf_at_Suc_of_c_sum: \"u < sf ((c_sum u) + 1)\"\nproof -\n  have \"u+1 \\<le> sf(u+1)\" by (rule arg_le_sf)\n  hence \"u < sf(u+1)\" by simp\n  thus ?thesis by (unfold c_sum_def, rule LeastI)\nqed\n\nlemma arg_less_sf_imp_c_sum_less_arg: \"u < sf(x) \\<Longrightarrow> c_sum u < x\"\nproof -\n  assume A1: \"u < sf(x)\"\n  then show ?thesis\n  proof (cases x)\n    assume \"x=0\"\n    with A1 show ?thesis by (simp add: sf_def)\n  next\n    fix y\n    assume A2: \"x = Suc y\"\n    show ?thesis\n    proof -\n      from A1 A2 have \"u < sf(y+1)\" by simp\n      hence \"(Least (%z. u < sf (z+1))) \\<le> y\" by (rule Least_le)\n      hence \"c_sum u \\<le> y\" by (fold c_sum_def)\n      with A2 show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma sf_c_sum_le_arg: \"u \\<ge> sf (c_sum u)\"\nproof -\n  let ?z = \"c_sum u\"\n  from arg_less_sf_at_Suc_of_c_sum have S1: \"u < sf (?z+1)\" by (auto)\n  have S2: \"\\<not> c_sum u < c_sum u\" by (auto)\n  from arg_less_sf_imp_c_sum_less_arg S2 have S3: \"\\<not> u < sf (c_sum u) \" by (auto)\n  from S3 show ?thesis by (auto)\nqed\n\nlemma c_sum_le_arg: \"c_sum u \\<le> u\"\nproof -\n  have \"c_sum u \\<le> sf (c_sum u)\" by (rule arg_le_sf)\n  moreover have \"sf(c_sum u) \\<le> u\" by (rule sf_c_sum_le_arg)\n  ultimately show ?thesis by simp\nqed\n\nlemma c_sum_of_c_pair [simp]: \"c_sum (c_pair x y) = x + y\"\nproof -\n  let ?u = \"c_pair x y\"\n  let ?z = \"c_sum ?u\"\n  have S1: \"?u < sf(?z+1)\" by (rule arg_less_sf_at_Suc_of_c_sum)\n  have S2: \"sf(?z) \\<le> ?u\" by (rule sf_c_sum_le_arg)\n  from S1 have S3: \"sf(x+y)+x < sf(?z+1)\" by (simp add: c_pair_def)\n  from S2 have S4: \"sf(?z) \\<le> sf(x+y) + x\" by (simp add: c_pair_def)\n  from S3 have S5: \"sf(x+y) < sf(?z+1)\" by (auto)\n  from S5 have S6: \"x+y < ?z+1\" by (rule sf_less_sfD)\n  from S6 have S7: \"x+y \\<le> ?z\" by (auto)\n  from S4 have S8: \"?z \\<le> x+y\" by (rule sf_aux2)\n  from S7 S8 have S9: \"?z = x+y\" by (auto)\n  from S9 show ?thesis by (simp)\nqed\n\nlemma c_fst_of_c_pair[simp]: \"c_fst (c_pair x y) = x\"\nproof -\n  let ?u = \"c_pair x y\"\n  have \"c_sum ?u = x + y\" by simp\n  hence \"c_fst ?u = ?u - sf(x+y)\" by (simp add: c_fst_def)\n  moreover have \"?u = sf(x+y) + x\" by (simp add: c_pair_def)\n  ultimately show ?thesis by (simp)\nqed\n\nlemma c_snd_of_c_pair[simp]: \"c_snd (c_pair x y) = y\"\nproof -\n  let ?u = \"c_pair x y\"\n  have \"c_sum ?u = x + y\" by simp\n  moreover have \"c_fst ?u = x\" by simp\n  ultimately show ?thesis by (simp add: c_snd_def)\nqed\n\nlemma c_pair_at_0: \"c_pair 0 0 = 0\" by (simp add: sf_def c_pair_def)\n\nlemma c_fst_at_0: \"c_fst 0 = 0\"\nproof -\n  have \"c_pair 0 0 = 0\" by (rule c_pair_at_0)\n  hence \"c_fst 0 = c_fst (c_pair 0 0)\" by simp\n  thus ?thesis by simp\nqed\n\nlemma c_snd_at_0: \"c_snd 0 = 0\"\nproof -\n  have \"c_pair 0 0 = 0\" by (rule c_pair_at_0)\n  hence \"c_snd 0 = c_snd (c_pair 0 0)\" by simp\n  thus ?thesis by simp\nqed\n\nlemma sf_c_sum_plus_c_fst: \"sf(c_sum u) + c_fst u = u\"\nproof -\n  have S1: \"sf(c_sum u) \\<le> u\" by (rule sf_c_sum_le_arg)\n  have S2: \"c_fst u = u - sf(c_sum u)\" by (simp add: c_fst_def)\n  from S1 S2 show ?thesis by (auto)\nqed\n\nlemma c_fst_le_c_sum: \"c_fst u \\<le> c_sum u\"\nproof -\n  have S1: \"sf(c_sum u) + c_fst u = u\" by (rule sf_c_sum_plus_c_fst)\n  have S2: \"u < sf((c_sum u) + 1)\" by (rule arg_less_sf_at_Suc_of_c_sum)\n  from S1 S2 sf_aux3 show ?thesis by (auto)\nqed\n\nlemma c_snd_le_c_sum: \"c_snd u \\<le> c_sum u\" by (simp add: c_snd_def)\n\nlemma c_fst_le_arg: \"c_fst u \\<le> u\"\nproof -\n  have \"c_fst u \\<le> c_sum u\" by (rule c_fst_le_c_sum)\n  moreover have \"c_sum u \\<le> u\" by (rule c_sum_le_arg)\n  ultimately show ?thesis by simp\nqed\n\nlemma c_snd_le_arg: \"c_snd u \\<le> u\"\nproof -\n  have \"c_snd u \\<le> c_sum u\" by (rule c_snd_le_c_sum)\n  moreover have \"c_sum u \\<le> u\" by (rule c_sum_le_arg)\n  ultimately show ?thesis by simp\nqed\n\nlemma c_sum_is_sum: \"c_sum u = c_fst u + c_snd u\" by (simp add: c_snd_def c_fst_le_c_sum)\n \nlemma proj_eq_imp_arg_eq: \"\\<lbrakk> c_fst u = c_fst v; c_snd u = c_snd v\\<rbrakk> \\<Longrightarrow> u = v\"\nproof -\n  assume A1: \"c_fst u = c_fst v\"\n  assume A2: \"c_snd u = c_snd v\"\n  from A1 A2 c_sum_is_sum have S1: \"c_sum u = c_sum v\" by (auto)\n  have S2: \"sf(c_sum u) + c_fst u = u\" by (rule sf_c_sum_plus_c_fst)\n  from A1 S1 S2 have S3: \"sf(c_sum v) + c_fst v = u\" by (auto)\n  from S3 sf_c_sum_plus_c_fst show ?thesis by (auto)\nqed\n\nlemma c_pair_of_c_fst_c_snd[simp]: \"c_pair (c_fst u) (c_snd u) = u\"\nproof -\n  let ?x = \"c_fst u\"\n  let ?y = \"c_snd u\"\n  have S1: \"c_pair ?x ?y = sf(?x + ?y) + ?x\" by (simp add: c_pair_def)\n  have S2: \"c_sum u = ?x + ?y\" by (rule c_sum_is_sum)\n  from S1 S2 have \"c_pair ?x ?y = sf(c_sum u) + c_fst u\" by (auto)\n  thus ?thesis by (simp add: sf_c_sum_plus_c_fst)\nqed\n\nlemma c_sum_eq_arg: \"c_sum x = x \\<Longrightarrow> x \\<le> 1\"\nproof -\n  assume A1: \"c_sum x = x\"\n  have S1: \"sf(c_sum x) + c_fst x = x\" by (rule sf_c_sum_plus_c_fst)\n  from A1 S1 have S2: \"sf x + c_fst x = x\" by simp\n  have S3: \"x \\<le> sf x\" by (rule arg_le_sf)\n  from S2 S3 have \"sf(x)=x\" by simp\n  thus ?thesis by (rule sf_eq_arg)\nqed\n\nlemma c_sum_eq_arg_2: \"c_sum x = x \\<Longrightarrow> c_fst x = 0\"\nproof -\n  assume A1: \"c_sum x = x\"\n  have S1: \"sf(c_sum x) + c_fst x = x\" by (rule sf_c_sum_plus_c_fst)\n  from A1 S1 have S2: \"sf x + c_fst x = x\" by simp\n  have S3: \"x \\<le> sf x\" by (rule arg_le_sf)\n  from S2 S3 show ?thesis by simp\nqed\n\nlemma c_fst_eq_arg: \"c_fst x = x \\<Longrightarrow> x = 0\"\nproof -\n  assume A1: \"c_fst x = x\"\n  have S1: \"c_fst x \\<le> c_sum x\" by (rule c_fst_le_c_sum)\n  have S2: \"c_sum x \\<le> x\" by (rule c_sum_le_arg)\n  from A1 S1 S2 have \"c_sum x = x\" by simp\n  then have \"c_fst x = 0\" by (rule c_sum_eq_arg_2)\n  with A1 show ?thesis by simp\nqed\n\n\n\nlemma c_snd_eq_arg: \"c_snd x = x \\<Longrightarrow> x \\<le> 1\"\nproof -\n  assume A1: \"c_snd x = x\"\n  have S1: \"c_snd x \\<le> c_sum x\" by (rule c_snd_le_c_sum)\n  have S2: \"c_sum x \\<le> x\" by (rule c_sum_le_arg)\n  from A1 S1 S2 have \"c_sum x = x\" by simp  \n  then show ?thesis by (rule c_sum_eq_arg)\nqed\n\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Recursion-Theory-I/CPair.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7741933969546391}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_MSortBU2Count\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(Nat list) list => (Nat list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(Nat list) list => Nat list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun risers :: \"Nat list => (Nat list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if le y y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun msortbu2 :: \"Nat list => Nat list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\nfun count :: \"'a => 'a list => Nat\" where\n  \"count x (nil2) = Z\"\n| \"count x (cons2 z ys) =\n     (if (x = z) then plus (S Z) (count x ys) else count x ys)\"\n\ntheorem property0 :\n  \"((count x (msortbu2 xs)) = (count x xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_MSortBU2Count.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8418256512199033, "lm_q1q2_score": 0.7741786726982657}}
{"text": "\\<^marker>\\<open>creator Bernhard Pöttinger\\<close>\n\nchapter \\<open>Pigeonhole\\<close>\ntheory Pigeonhole\n  imports Main\nbegin\n\nparagraph \\<open>Summary\\<close>\ntext \\<open>We introduce the generalized pigeonhole principle (which is/was not available in\nIsabelle when formalizing it here).\n\nAdditionally, we introduce an auxiliary lemma that uses the simple pigeonhole principle\nto find a reoccurring element in a list and to decompose the list into three lists with\nthe reoccurring element as a split element.\\<close>\n\nlemma generalized_pigeonhole:\n  assumes \"dom f \\<noteq> {}\" \"finite (dom f)\" \"card (dom f) \\<ge> card (ran f) * k + 1\"\n  shows \"\\<exists>y \\<in> ran f. card (f -` {Some y}) \\<ge> k + 1\"\nproof (rule ccontr)\n  assume \"\\<not> (\\<exists>y\\<in>ran f. k + 1 \\<le> card (f -` {Some y}))\"\n  then have A: \"\\<And>y. y \\<in> ran f \\<Longrightarrow> card (f -` {Some y}) \\<le> k\"\n    by auto\n\n  have \"finite (ran f)\"\n    using assms finite_ran by simp\n  moreover have \"dom f = (\\<Union>y \\<in> ran f. f -` {Some y})\"\n    unfolding dom_def ran_def by auto\n  ultimately have \"card (dom f) = (\\<Sum>y \\<in> ran f. card (f -` {Some y}))\"\n    using assms by (auto intro: card_UN_disjoint)\n  also have \"... \\<le> (\\<Sum>y \\<in> ran f. k)\"\n    using sum_mono[OF A] by simp\n  also have \"... < card (ran f) * k + 1\"\n    by simp\n  also have \"... \\<le> card (dom f)\"\n    using assms by simp\n  finally show False ..\nqed\n\nlemma pigeonhole_ex:\n  assumes \"length fs \\<ge> card N + 1\" \"set fs \\<subseteq> N\" \"finite N\"\n  shows \"\\<exists>i j. i < j \\<and> j < length fs \\<and> fs!i = fs!j\"\nproof -\n  let ?f = \"\\<lambda>n. if n < length fs then fs!n else undefined\"\n  let ?d = \"{0..<length fs}\"\n  have \"?f ` ?d \\<subseteq> set fs\"\n    by auto\n  then have \"?f ` ?d \\<subseteq> N\"\n    using assms by blast\n  then have \"card (?f ` ?d) + 1 \\<le> length fs\"\n    using card_mono[of \"N\" \"?f ` ?d\"] assms by simp\n  moreover have \"card (set fs) \\<le> card ?d\"\n    by (simp add: card_length)\n  ultimately have \"\\<not> inj_on ?f ?d\"\n    using pigeonhole[of ?f ?d] by simp\n  then obtain x y where *: \"x \\<in> ?d\" \"y \\<in> ?d\" \"x \\<noteq> y\" \"?f x = ?f y\"\n    unfolding inj_on_def by blast\n  then have \"fs!x = fs !y\"\n    by auto\n  then show \"\\<exists>i j. i < j \\<and> j < length fs \\<and> fs ! i = fs ! j\"\n    using *\n    apply (cases \"x < y\")\n     apply auto[1]\n    by (rule exI[where x=\"y\"], rule exI[where x=\"x\"], simp)\nqed\n\nlemma pigeonhole_split_list:\n  assumes \"length fs \\<ge> card N + 1\" \"set fs \\<subseteq> N\" \"finite N\"\n  shows \"\\<exists>x xs ys zs. fs = xs @ x # ys @ x # zs\"\nproof -\n  obtain i j where \"i < j\" \"j < length fs\" \"fs!i = fs!j\"\n    using pigeonhole_ex assms by blast\n  then have \"\\<not> distinct fs\"\n    using distinct_conv_nth[of fs] by auto\n  then obtain xs ys zs y where **: \"fs = xs @ [y] @ ys @ [y] @ zs\"\n    using not_distinct_decomp[of fs] by blast\n  then show ?thesis\n    by auto\nqed\n\nend\n", "meta": {"author": "bpoettinger", "repo": "Flow", "sha": "c95ea5f88a0a3d39e44421e0cc36139a3c3687de", "save_path": "github-repos/isabelle/bpoettinger-Flow", "path": "github-repos/isabelle/bpoettinger-Flow/Flow-c95ea5f88a0a3d39e44421e0cc36139a3c3687de/Pigeonhole.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.8856314783461302, "lm_q1q2_score": 0.7741103255880557}}
{"text": "text\\<open> 4 Nov 2021: Two lemmas for Homework 09 in CS 511 \\<close> \n\ntheory HW09_solution\n  imports Main\nbegin\n\ntext \\<open> Exercise 1 on the last page of Lecture Slides 28, Analytic Tableaux\n       Part I  \\<close>\n\nlemma A1 : \" (\\<forall>x. \\<forall>y. \\<forall>z. P(x,y) \\<and> P(y,z) \\<longrightarrow> P(x,z)) \\<and> (\\<forall>x. \\<forall>y. P(x,y) \\<longrightarrow> P(y,x)) \n            \\<Longrightarrow> \\<forall>x. \\<forall>y. \\<forall>z. P(x,y) \\<and> P(z,y) \\<longrightarrow> P(x,z) \"\n  by blast \n\nlemma A2 : \" (\\<forall>x. \\<forall>y. \\<forall>z. P(x,y) \\<and> P(y,z) \\<longrightarrow> P(x,z)) \\<and> (\\<forall>x. \\<forall>y. P(x,y) \\<longrightarrow> P(y,x)) \n               \\<Longrightarrow> \\<forall>x. \\<forall>y. \\<forall>z. P(x,y) \\<and> P(z,y) \\<longrightarrow> P(x,z) \"\n  apply (erule conjE)\n  apply (rule allI)+\n  apply (rule impI)\n  apply (erule conjE)\n  apply (erule_tac x=\"x\" in allE)\n  apply (erule_tac x=\"z\" in allE)\n  apply (erule_tac x=\"y\" in allE)\n  apply (erule_tac x=\"y\" in allE)\n  apply (erule_tac x=\"z\" in allE)\n  apply (erule impE)\n   apply assumption\n  apply (erule impE)\n   apply (rule conjI)\n  apply assumption+\n  done\n\ntext \\<open> Exercise 2 on the last page of Lecture Slides 28, Analytic Tableaux\n       Part I  \\<close>\nlemma B1: \"\\<forall>x. Q(a,x,x) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x) \"\n  by blast \n\ntext \\<open> A bloated proof of Lemma B1 with several unnecessary 'apply' steps \\<close>\nlemma B2: \"(\\<forall>x. Q(a,x,x)) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x)\"\n  apply (erule conjE)\n  apply (erule conjE)\n  apply (rule_tac x=\"s(s(s(s(s(a)))))\" in exI)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"a\" in allE)\n  apply (frule_tac x=\"a\" in spec)\n  apply (frule_tac x=\"s(a)\" in spec)\n  apply (frule_tac x=\"s(s(a))\" in spec)\n  apply (erule_tac x=\"a\" in allE) \n  apply (frule_tac x=\"a\" in spec)\n  apply (frule_tac x=\"s(s(a))\" in spec) \n  apply (erule_tac x=\"a\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"s(s(s(a)))\" in allE)\n  apply (erule_tac x=\"s(s(s(s(a))))\" in allE)\n  apply (erule_tac x=\"a\" in allE)  \n  apply (erule_tac x=\"a\" in allE) \n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"a\" in allE) \n  apply (erule impE)\n   apply (erule mp)\n   apply assumption\n  apply (erule mp)\n  apply (erule mp)\n  apply assumption\n  done\n\ntext \\<open> The following proof is essentially the same as that for B2 above, \n       the difference being that all explicit substitutions, except for one,\n       are omitted. As a result, Isabelle will replace every quantified variable\n       by a schematic variable, also trusting Isabelle's unification engine\n       to figure out appropriate substitutions. \\<close>\nlemma B2_bis: \"(\\<forall>x. Q(a,x,x)) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x)\"\n  apply (erule conjE)\n  apply (erule conjE)\n  apply (rule exI)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (frule_tac x=\"a\" in spec)\n  apply (frule spec)\n  apply (frule spec)\n  apply (frule spec)\n  apply (erule allE)\n  apply (frule spec) \n  apply (frule spec)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule allE)\n  apply (erule impE)\n   apply (erule mp)\n   apply assumption\n  apply (erule mp)\n  apply (erule mp)\n  apply assumption\n  done\n\ntext\\<open> In the proofs to follow we use commands of the form: 'apply (rotate_tac n)'\n      which rotates the premises of a subgoal by n positions, from RIGHT to LEFT\n      if n is positive, and from LEFT to RIGHT if n is negative. \\<close>\n\ntext \\<open> Shortest proofs below are for Lemmas B3 and B4 \\<close>\n\ntext \\<open> A streamlined proof of Lemmas B1 and B2 with 12 'apply' steps \\<close>\nlemma B3: \" (\\<forall>x. Q(a,x,x)) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x)\"\n  apply (erule conjE)+\n  apply (rule_tac x=\"s(s(s(s(s(a)))))\" in exI)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"a\" in allE)\n      (* rotate premises RIGHT to LEFT by 2 before applying rule 'allE' *)\n  apply (rotate_tac 2, erule_tac x=\"s(s(a))\" in allE)\n      (* rotate premises RIGHT to LEFT by 2 before applying rule 'allE' *)\n  apply (rotate_tac 2, erule_tac x=\"s(s(a))\" in allE)\n  apply (frule_tac x=\"a\" in spec)\n      (* rotate premises RIGHT to LEFT by 3 before applying rule 'allE' *)\n  apply (rotate_tac 3, erule_tac x=\"s(s(a))\" in allE)\n  apply (frule_tac x=\"s(a)\" in spec, rotate_tac 2, erule_tac x=\"s(s(s(a)))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE, erule_tac x=\"s(s(s(s(a))))\" in allE)\n  apply (erule impE, assumption)+\n  by assumption\n\ntext \\<open> A slight variation of the proof of Lemma B3 with 13 'apply' steps \\<close>\nlemma B4: \" (\\<forall>x. Q(a,x,x)) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x)\"\n  apply (erule conjE)+\n  apply (rule exI)\n  apply (erule allE)\n  apply (erule_tac x=\"s(s(a))\" in allE) \n  apply (erule_tac x=\"a\" in allE) \n      (* rotate premises LEFT to RIGHT by 1 before applying rule 'allE' *)\n  apply (rotate_tac -1, erule_tac x=\"s(s(a))\" in allE) \n      (* rotate premises LEFT to RIGHT by 1 before applying rule 'allE' *)\n  apply (rotate_tac -1, erule_tac x=\"s(s(a))\" in allE)\n  apply (frule_tac x=\"a\" in spec)\n      (* rotate premises RIGHT to LEFT by 3 before applying rule 'allE' *)\n  apply (rotate_tac 3, erule_tac x=\"s(s(a))\" in allE)\n  apply (frule_tac x=\"s(a)\" in spec, rotate_tac 2, erule_tac x=\"s(s(s(a)))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE, erule_tac x=\"s(s(s(s(a))))\" in allE)\n  apply (erule impE, assumption)+\n  apply assumption\n  done\n\ntext \\<open> The proofs of Lemmas B5 and B6 are obtained from the proof of B2 by \n       repeated trial-error-backtrack steps \\<close>\n\ntext \\<open> A shorter proof of Lemmas B1 and B2 with 19 'apply' steps, but still bloated \\<close>\nlemma B5: \" (\\<forall>x. Q(a,x,x)) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x)\"\n  apply (erule conjE)+\n  apply (rule_tac x=\"s(s(s(s(s(a)))))\" in exI)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"a\" in allE)\n  apply (frule_tac x=\"a\" in spec)\n  apply (frule_tac x=\"s(a)\" in spec)\n  apply (erule_tac x=\"s(s(a))\" in allE)  \n  apply (frule_tac x=\"a\" in spec)\n  apply (erule_tac x=\"s(s(a))\" in allE) \n  apply (erule_tac x=\"s(s(a))\" in allE) \n  apply (erule_tac x=\"s(s(s(a)))\" in allE)\n  apply (erule_tac x=\"s(s(s(s(a))))\" in allE)\n  apply (erule_tac x=\"s(s(s(s(a))))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule impE)\n   apply (erule mp)\n   apply assumption\n  apply (erule mp)+\n  by assumption\n\ntext \\<open> A shorter proof of Lemmas B1 and B2 with 21 'apply' steps, but still bloated \\<close>\nlemma B6: \" (\\<forall>x. Q(a,x,x)) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> \n    Q(x,s(y),s(z))) \\<and> (\\<forall>x y z. Q(x,y,z) \\<longrightarrow> Q(y,x,z)) \\<Longrightarrow> \\<exists> x. Q( s(s(a)), s(s(s(a))), x)\"\n  apply (erule conjE)+\n  apply (rule_tac x=\"s(s(s(s(s(a)))))\" in exI)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (rotate_tac 2) \n  apply (frule_tac x=\"a\" in spec)\n  apply (frule_tac x=\"s(a)\" in spec)\n  apply (erule_tac x=\"s(s(a))\" in allE)  \n  apply (frule_tac x=\"a\" in spec)\n  apply (erule_tac x=\"s(s(a))\" in allE) \n  apply (erule_tac x=\"s(s(a))\" in allE) \n  apply (erule_tac x=\"s(s(s(a)))\" in allE)\n  apply (erule_tac x=\"s(s(s(s(a))))\" in allE)\n  apply (erule_tac x=\"s(s(a))\" in allE)\n  apply (erule impE)\n   apply (rotate_tac 4)\n   apply (erule_tac x=\"s(s(a))\" in allE)\n   apply (erule mp)\n  apply assumption \n   apply (erule mp)\n  apply (erule mp)\n  by assumption\n\nend", "meta": {"author": "snigdhakalathur", "repo": "CS511", "sha": "55d4e0f8c31639ea5cf0f148fe4e825ba796735e", "save_path": "github-repos/isabelle/snigdhakalathur-CS511", "path": "github-repos/isabelle/snigdhakalathur-CS511/CS511-55d4e0f8c31639ea5cf0f148fe4e825ba796735e/HW09_solution.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8856314768368161, "lm_q1q2_score": 0.7741103039332802}}
{"text": "section \\<open>Uniform Sampling\\<close>\n\ntext\\<open>Here we prove different one time pad lemmas based on uniform sampling we require throughout our proofs.\\<close>\n\ntheory Uniform_Sampling\n  imports \n    CryptHOL.Cyclic_Group_SPMF \n    \"HOL-Number_Theory.Cong\"\n    CryptHOL.List_Bits\nbegin \n\ntext \\<open>If q is a prime we can sample from the units.\\<close>\n\ndefinition sample_uniform_units :: \"nat \\<Rightarrow> nat spmf\"\n  where \"sample_uniform_units q = spmf_of_set ({..< q} - {0})\"\n\nlemma set_spmf_sampl_uni_units [simp]: \"set_spmf (sample_uniform_units q) = {..< q} - {0}\" \n  by(simp add: sample_uniform_units_def)\n\nlemma lossless_sample_uniform_units: \n  assumes \"q > 1\"\n  shows \"lossless_spmf (sample_uniform_units q)\"\n  apply(simp add: sample_uniform_units_def) \n  using assms by auto\n\ntext \\<open>General lemma for mapping using uniform sampling from units.\\<close>\n\nlemma one_time_pad_units: \n  assumes inj_on: \"inj_on f ({..<q} - {0})\" \n    and sur: \"f ` ({..<q} - {0}) = ({..<q} - {0})\"  \n  shows \"map_spmf f (sample_uniform_units q) = (sample_uniform_units q)\"\n    (is \"?lhs = ?rhs\")\nproof-\n  have rhs: \"?rhs = spmf_of_set (({..<q} - {0}))\" \n    by(auto simp add: sample_uniform_units_def)\n  also have \"map_spmf(\\<lambda>s. f s) (spmf_of_set ({..<q} - {0})) = spmf_of_set ((\\<lambda>s. f s) ` ({..<q} - {0}))\"\n    by(simp add: inj_on)\n  also have \"f ` ({..<q} - {0}) = ({..<q} - {0})\"\n    apply(rule endo_inj_surj) by(simp, simp add: sur, simp add: inj_on)\n  ultimately show ?thesis using rhs by simp\nqed\n\ntext \\<open>General lemma for mapping using uniform sampling.\\<close>\n\nlemma one_time_pad: \n  assumes inj_on: \"inj_on f {..<q}\" \n    and sur: \"f ` {..<q} = {..<q}\"  \n  shows \"map_spmf f (sample_uniform q) = (sample_uniform q)\"\n    (is \"?lhs = ?rhs\")\nproof-\n  have rhs: \"?rhs = spmf_of_set ({..< q})\" \n    by(auto simp add: sample_uniform_def)\n  also have \"map_spmf(\\<lambda>s. f s) (spmf_of_set {..<q}) = spmf_of_set ((\\<lambda>s. f s) ` {..<q})\"\n    by(simp add: inj_on)\n  also have \"f ` {..<q} = {..<q}\"\n    apply(rule endo_inj_surj) by(simp, simp add: sur, simp add: inj_on)\n  ultimately show ?thesis using rhs by simp\nqed\n\ntext \\<open>The addition map case.\\<close>\n\nlemma inj_add: \n  assumes x:  \"x < q\" \n    and x': \"x' < q\" \n    and map: \"((y :: nat) + x) mod q = (y + x') mod q\"  \n  shows \"x = x'\"\nproof-\n  have aa: \"((y :: nat) + x) mod q = (y + x') mod q \\<Longrightarrow> x mod q = x' mod q\"\n  proof-\n    have 4: \"((y:: nat) + x) mod q = (y + x') mod q \\<Longrightarrow> [((y:: nat) + x) = (y + x')] (mod q)\"\n      by(simp add: cong_def)\n    have 5: \"[((y:: nat) + x) = (y + x')] (mod q) \\<Longrightarrow> [x = x'] (mod q)\"\n      by (simp add: cong_add_lcancel_nat)\n    have 6: \"[x = x'] (mod q) \\<Longrightarrow> x mod q = x' mod q\"\n      by(simp add: cong_def)\n    then show ?thesis by(simp add: map 4 5 6)\n  qed\n  also have bb: \"x mod q = x' mod q \\<Longrightarrow> x = x'\"\n    by(simp add: x x')\n  ultimately show ?thesis by(simp add: map) \nqed\n\nlemma inj_uni_samp_add: \"inj_on (\\<lambda>(b :: nat). (y + b) mod q ) {..<q}\"\n  by(simp add: inj_on_def)(auto simp only: inj_add)\n\nlemma surj_uni_samp: \n  assumes inj: \"inj_on  (\\<lambda>(b :: nat). (y + b) mod q ) {..<q}\" \n  shows \"(\\<lambda>(b :: nat). (y + b) mod q) ` {..< q} =  {..< q}\" \n  apply(rule endo_inj_surj) using inj by auto\n\nlemma samp_uni_plus_one_time_pad: \n  shows \"map_spmf (\\<lambda>b. (y + b) mod q) (sample_uniform q) = (sample_uniform q)\"\n  using inj_uni_samp_add surj_uni_samp one_time_pad by simp\n\ntext \\<open>The multiplicaton map case.\\<close>\n\nlemma inj_mult: \n  assumes coprime: \"coprime x (q::nat)\" \n    and y: \"y < q\" \n    and y': \"y' < q\" \n  and map: \"x * y mod q = x * y' mod q\" \nshows \"y = y'\"\nproof-\n  have \"x*y mod q = x*y' mod q \\<Longrightarrow> y mod q = y' mod q\"\n  proof-\n    have \"x*y mod q = x*y' mod q \\<Longrightarrow> [x*y = x*y'] (mod q)\"\n      by(simp add: cong_def)\n    also have \"[x*y = x*y'] (mod q) = [y = y'] (mod q)\"\n      by(simp add: cong_mult_lcancel_nat coprime)\n    also have \"[y = y'] (mod q) \\<Longrightarrow> y mod q = y' mod q\"\n      by(simp add: cong_def)\n    ultimately show ?thesis by(simp add: map)\n  qed\n  also have \"y mod q = y' mod q \\<Longrightarrow> y = y'\"\n    by(simp add: y y')\n  ultimately show ?thesis by(simp add: map) \nqed\n\nlemma inj_on_mult: \n  assumes coprime: \"coprime x (q::nat)\" \n  shows \"inj_on (\\<lambda> b. x*b mod q) {..<q}\"\n  apply(auto simp add: inj_on_def)\n  using coprime by(simp only: inj_mult)\n\nlemma surj_on_mult: \n  assumes coprime: \"coprime x (q::nat)\" \n    and inj: \"inj_on (\\<lambda> b. x*b mod q) {..<q}\"\n  shows \"(\\<lambda> b. x*b mod q) ` {..< q} = {..< q}\"\n  apply(rule endo_inj_surj) using coprime inj by auto\n\nlemma mult_one_time_pad: \n  assumes coprime: \"coprime x q\" \n  shows \"map_spmf (\\<lambda> b. x*b mod q) (sample_uniform q) = (sample_uniform q)\"\n  using inj_on_mult surj_on_mult one_time_pad coprime by simp\n\ntext \\<open>The multiplication map for sampling from units.\\<close>\n\nlemma inj_on_mult_units: \n  assumes 1: \"coprime x (q::nat)\" shows \"inj_on (\\<lambda> b. x*b mod q) ({..<q} - {0})\"\n  apply(auto simp add: inj_on_def)\n  using 1 by(simp only: inj_mult)\n\nlemma surj_on_mult_units: \n  assumes coprime: \"coprime x (q::nat)\" \n    and inj: \"inj_on (\\<lambda> b. x*b mod q) ({..<q} - {0})\"\n  shows \"(\\<lambda> b. x*b mod q) ` ({..<q} - {0}) = ({..<q} - {0})\"\nproof(rule endo_inj_surj)\n  show \"finite ({..<q} - {0})\" using coprime inj by(simp)\n  show \"(\\<lambda>b. x * b mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0}\" \n  proof -\n    obtain n :: \"nat set \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> nat set \\<Rightarrow> nat\" where\n      \"\\<forall>x0 x1 x2. (\\<exists>v3. v3 \\<in> x2 \\<and> x1 v3 \\<notin> x0) = (n x0 x1 x2 \\<in> x2 \\<and> x1 (n x0 x1 x2) \\<notin> x0)\"\n      by moura\n    then have subset: \"\\<forall>N f Na. n Na f N \\<in> N \\<and> f (n Na f N) \\<notin> Na \\<or> f ` N \\<subseteq> Na\"\n      by (meson image_subsetI)\n    have mem_insert: \"x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<notin> {..<q} \\<or> x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> insert 0 {..<q}\"\n      by force\n    have map_eq: \"(x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> insert 0 {..<q} - {0}) = (x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> {..<q} - {0})\"\n      by simp\n    { assume \"x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q = x * 0 mod q\"\n      then have \"(0 \\<le> q) = (0 = q) \\<or> (n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<notin> {..<q} \\<or> n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<in> {0}) \\<or> n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<notin> {..<q} - {0} \\<or> x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> {..<q} - {0}\"\n        by (metis antisym_conv1 insertCI lessThan_iff local.coprime inj_mult) }\n    moreover\n    { assume \"0 \\<noteq> x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q\"\n      moreover\n      { assume \"x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> insert 0 {..<q} \\<and> x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<notin> {0}\"\n        then have \"(\\<lambda>n. x * n mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0}\"\n          using map_eq subset by (meson Diff_iff) }\n      ultimately have \"(\\<lambda>n. x * n mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0} \\<or> (0 \\<le> q) = (0 = q)\"\n        using mem_insert by (metis antisym_conv1 lessThan_iff mod_less_divisor singletonD) }\n    ultimately have \"(\\<lambda>n. x * n mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0} \\<or> n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) \\<notin> {..<q} - {0} \\<or> x * n ({..<q} - {0}) (\\<lambda>n. x * n mod q) ({..<q} - {0}) mod q \\<in> {..<q} - {0}\"\n      by force\n    then show \"(\\<lambda>n. x * n mod q) ` ({..<q} - {0}) \\<subseteq> {..<q} - {0}\"\n      using subset by meson\n  qed\n  show \"inj_on (\\<lambda>b. x * b mod q) ({..<q} - {0})\" using assms by(simp) \nqed\n\nlemma mult_one_time_pad_units: \n  assumes coprime: \"coprime x q\" \n  shows \"map_spmf (\\<lambda> b. x*b mod q) (sample_uniform_units q) = sample_uniform_units q\"\n  using inj_on_mult_units surj_on_mult_units one_time_pad_units coprime by simp\n\ntext \\<open>Addition and multiplication map.\\<close>\n\nlemma samp_uni_add_mult: \n  assumes coprime: \"coprime x (q::nat)\" \n    and xa: \"xa < q\" \n    and ya: \"ya < q\" \n    and map: \"(y + x * xa) mod q = (y + x * ya) mod q\" \n  shows \"xa = ya\"\nproof-\n  have \"(y + x * xa) mod q = (y + x * ya) mod q \\<Longrightarrow> xa mod q = ya mod q\"\n  proof-\n    have \"(y + x * xa) mod q = (y + x * ya) mod q \\<Longrightarrow> [y + x*xa = y + x *ya] (mod q)\"\n      using cong_def by blast\n    also have \"[y + x*xa = y + x *ya] (mod q) \\<Longrightarrow> [xa = ya] (mod q)\"\n      by(simp add: cong_add_lcancel_nat)(simp add: coprime cong_mult_lcancel_nat)\n    ultimately show ?thesis by(simp add: cong_def map)\n  qed\n  also have \"xa mod q = ya mod q \\<Longrightarrow> xa = ya\"\n    by(simp add: xa ya)\n  ultimately show ?thesis by(simp add: map)\nqed\n\nlemma inj_on_add_mult: \n  assumes coprime: \"coprime x (q::nat)\" \n  shows \"inj_on (\\<lambda> b. (y + x*b) mod q) {..<q}\"\n  apply(auto simp add: inj_on_def)\n  using coprime by(simp only: samp_uni_add_mult)\n\nlemma surj_on_add_mult: assumes coprime: \"coprime x (q::nat)\" and inj: \"inj_on (\\<lambda> b. (y + x*b) mod q) {..<q}\" \n  shows \"(\\<lambda> b. (y + x*b) mod q) ` {..< q} = {..< q}\" \n  apply(rule endo_inj_surj) using coprime inj by auto\n\nlemma add_mult_one_time_pad: assumes coprime: \"coprime x q\" \n  shows \"map_spmf (\\<lambda> b. (y + x*b) mod q) (sample_uniform q) = (sample_uniform q)\"\n  using inj_on_add_mult surj_on_add_mult one_time_pad coprime by simp\n\ntext \\<open>Subtraction Map.\\<close>\n\nlemma inj_minus: \n  assumes x: \"(x :: nat) < q\" \n    and ya: \"ya < q\" \n    and map: \"(y + q - x) mod q = (y + q - ya) mod q\" \n  shows  \"x = ya\"\nproof-\n  have \"(y + q - x) mod q = (y + q - ya) mod q \\<Longrightarrow> x mod q = ya mod q\"\n  proof-\n    have \"(y + q - x) mod q = (y + q - ya) mod q \\<Longrightarrow> [y + q - x = y + q - ya] (mod q)\"\n      using cong_def by blast\n    moreover have \"[y + q - x = y + q - ya] (mod q) \\<Longrightarrow> [q - x = q - ya] (mod q)\"\n      using x ya cong_add_lcancel_nat by fastforce\n    moreover have \"[y + q - x = y + q - ya] (mod q) \\<Longrightarrow> [q + x = q + ya] (mod q)\" \n      by (metis add_diff_inverse_nat calculation(2) cong_add_lcancel_nat cong_add_rcancel_nat cong_sym less_imp_le_nat not_le x ya)\n    ultimately show ?thesis \n      by (simp add: cong_def map)\n  qed\n  moreover have \"x mod q = ya mod q \\<Longrightarrow> x = ya\"\n    by(simp add: x ya)\n  ultimately show ?thesis by(simp add: map)\nqed\n\nlemma inj_on_minus: \"inj_on  (\\<lambda>(b :: nat). (y + (q - b)) mod q ) {..<q}\"\n  by(auto simp add: inj_on_def inj_minus) \n\nlemma surj_on_minus: \n  assumes inj: \"inj_on  (\\<lambda>(b :: nat). (y + (q - b)) mod q ) {..<q}\" \n  shows \"(\\<lambda>(b :: nat). (y + (q - b)) mod q) ` {..< q} = {..< q}\"\n  apply(rule endo_inj_surj) \n  using inj by auto\n\nlemma samp_uni_minus_one_time_pad: \n  shows \"map_spmf(\\<lambda> b. (y + (q - b)) mod q) (sample_uniform q) = (sample_uniform q)\"\n  using inj_on_minus surj_on_minus one_time_pad by simp\n\nlemma not_coin_flip: \"map_spmf (\\<lambda> a. \\<not> a) coin_spmf = coin_spmf\" \nproof-\n  have \"inj_on Not {True, False}\" \n    by simp\n  also have  \"Not ` {True, False} = {True, False}\" \n    by auto \n  ultimately show ?thesis using one_time_pad \n    by (simp add: UNIV_bool)\nqed\n\nlemma xor_uni_samp: \"map_spmf(\\<lambda> b. y \\<oplus> b) (coin_spmf) = map_spmf(\\<lambda> b. b) (coin_spmf)\"\n  (is \"?lhs = ?rhs\")\nproof-\n  have rhs: \"?rhs = spmf_of_set {True, False}\"\n    by (simp add: UNIV_bool insert_commute)\n  also have \"map_spmf(\\<lambda> b. y \\<oplus> b) (spmf_of_set {True, False}) = spmf_of_set((\\<lambda> b. y \\<oplus> b) ` {True, False})\"\n    by (simp add: xor_def)\n  also have \"(\\<lambda> b. xor y b) ` {True, False} = {True, False}\"\n    using xor_def by auto\n  finally show ?thesis using rhs by(simp)\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Multi_Party_Computation/Uniform_Sampling.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7741072180618002}}
{"text": "theory BinarySearchTree\n  imports Main\nbegin\n\ndeclare [[names_short]]\n\ntype_synonym key = nat\n\ndatatype 'v bst = Leaf | Node \"'v bst\" key 'v \"'v bst\"\n\ndefinition ex1 where\n\"ex1 \\<equiv> (Node (Node Leaf 2 ''two'' Leaf) 4 ''four'' (Node Leaf 5 ''five'' Leaf))\"\n\nfun insert :: \"'v bst \\<Rightarrow> key \\<Rightarrow> 'v \\<Rightarrow> 'v bst\" where\n\"insert Leaf x v = Node Leaf x v Leaf\" |\n\"insert (Node l y v' r) x v = (if x < y then Node (insert l x v) y v' r\n                               else if x > y then Node l y v' (insert r x v)\n                               else (Node l x v r))\"\n\nfun forallT :: \"(key \\<Rightarrow> 'v \\<Rightarrow> bool) \\<Rightarrow> 'v bst \\<Rightarrow> bool\" where\n\"forallT P Leaf = True\" |\n\"forallT P (Node l k v r) = (P k v \\<and> forallT P l \\<and> forallT P r)\"\n\ninductive is_bst :: \"'v bst \\<Rightarrow> bool\" where\nis_bst_leaf: \"is_bst Leaf\" |\nis_bst_node: \"\\<lbrakk> forallT (\\<lambda> y _. y < x) l; forallT (\\<lambda> y _. y > x) r; is_bst l; is_bst r \\<rbrakk> \n  \\<Longrightarrow>  is_bst (Node l x v r)\"\n\nlemma \"is_bst ex1\"\n  unfolding ex1_def\n  apply (rule is_bst_node)\n     apply simp+\n   apply (rule is_bst_node)\n      apply simp+\n    apply (rule is_bst_leaf)\n   apply (rule is_bst_leaf)\n  apply (rule is_bst_node)\n     apply simp+\n   apply (rule is_bst_leaf)\n  apply (rule is_bst_leaf)\n  done\n\nlemma forallT_insert: \"\\<lbrakk> forallT P t; P k v \\<rbrakk> \\<Longrightarrow> forallT P (insert t k v)\"\n  apply (induction t)\n   apply auto\n  done\n\ntheorem \"is_bst t \\<Longrightarrow> is_bst (insert t k v)\"\nproof (induction t)\n  case Leaf\n  then show ?case\n    by (simp add: is_bst_node) \nnext\n  case (Node l y v' r)\n  then show ?case\n    using forallT_insert\n    by (smt (z3) bst.distinct(1) bst.inject insert.simps(2) is_bst.simps not_less_iff_gr_or_eq) \nqed\n\nend", "meta": {"author": "waynee95", "repo": "isabelle-hol-playground", "sha": "6ed735e98e99b475088e59932d0bae43dbd314d8", "save_path": "github-repos/isabelle/waynee95-isabelle-hol-playground", "path": "github-repos/isabelle/waynee95-isabelle-hol-playground/isabelle-hol-playground-6ed735e98e99b475088e59932d0bae43dbd314d8/BinarySearchTree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026482819238, "lm_q2_score": 0.843895098628499, "lm_q1q2_score": 0.7741072088440574}}
{"text": "chapter {* camr project *}\n\ntheory Unification imports Main begin\n\n\n(****************************** ( 1A ) ******************************)\n\ndatatype ('f, 'v) \"term\" = Var 'v | Fun 'f \"('f, 'v) term list\"\n\nfun fv :: \"('f, 'v) term \\<Rightarrow> 'v set\" where\n  \"fv (Var x) = {x}\"\n| \"fv (Fun f xs) = (\\<Union>x \\<in> (set xs). fv x)\"\n\n(****************************** ( 1B ) ******************************)\ntype_synonym ('f, 'v) subst = \"'v \\<Rightarrow> ('f, 'v) term\"\n\nfun sapply :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) term \\<Rightarrow> ('f, 'v) term\" (infixr \"\\<cdot>\" 67) where \n  \"sapply \\<sigma> (Var x) = \\<sigma> x\"\n| \"sapply \\<sigma> (Fun g xs) = Fun g (map (sapply \\<sigma>) xs)\"\n\ndefinition scomp :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> ('f, 'v) subst\" (infixl \"\\<circ>s\" 75) where\n  \"scomp \\<sigma> \\<tau> = (\\<lambda>x. \\<sigma> \\<cdot> (\\<tau> x))\"\n\nlemma sapply_sapply: \"a \\<cdot> b \\<cdot> t = (scomp a b) \\<cdot> t\"\n  by(induction t,simp_all add:scomp_def)\n\n\n(********************************* size argument ****************************)\n(* The following section contains lemmas used to show the completeness of Robinson's algorithm \nfurther down. The main lemma proved is in_fv_not_unifies, stating that there can't be a unifier\nfor ((Var x, b) # xs) is x \\<in> fv b *)\n\nfun msize :: \"('f, 'v) term \\<Rightarrow> nat\" where\n  \"msize (Var x) = 1\"\n| \"msize (Fun f xs) = 1 + sum_list (map msize xs)\"\n\ninductive ssube :: \"('f, 'v) term \\<Rightarrow> ('f, 'v) term \\<Rightarrow> bool\" where\n  \"\\<lbrakk> x \\<in> set xs \\<or> (\\<exists>y \\<in> set xs. ssube x y) \\<rbrakk> \\<Longrightarrow> ssube x (Fun f xs)\"\n\n\nlemma ssube_size: \"ssube e1 e2 \\<Longrightarrow> msize e1 < msize e2\"\nproof (induction e1 e2 rule: ssube.induct)\n  case (1 x xs f)\n  then show ?case \n  proof (rule disjE)\n    assume \"x \\<in> set xs\"\n    then have \"msize x \\<in> set (map msize xs)\" by auto\n    then have 2: \"msize x \\<le> sum_list (map msize xs)\" by (auto simp add: member_le_sum_list)\n    have \"msize (Fun f xs) = 1 + sum_list (map msize xs)\" by simp\n    then show \"msize x < msize (Fun f xs)\" using 2 by auto\n  next\n    assume \"\\<exists>y\\<in>set xs. ssube x y \\<and> msize x < msize y\"\n    then obtain y where 3: \"y \\<in> set xs \\<and> ssube x y \\<and> msize x < msize y\" by blast\n    then have \"msize y \\<in> set (map msize xs)\" by auto\n    then have 4: \"msize y \\<le> sum_list (map msize xs)\" by (auto simp add: member_le_sum_list)\n    have \"msize (Fun f xs) = 1 + sum_list (map msize xs)\" by simp\n    then show \"msize x < msize (Fun f xs)\" using 3 4 by auto\n  qed\nqed\n\nlemma msize_term_diff: \"\\<lbrakk> msize a \\<noteq> msize b \\<rbrakk> \\<Longrightarrow> a \\<noteq> b\"\n  apply (rule notI)\n  by (auto)\n\nlemma msize_gt_zero: \"msize x > 0\"\n  apply (cases x)\n  by (auto)\n\nlemma ssube_subst_stable: \"ssube e1 e2 \\<Longrightarrow> ssube (\\<sigma> \\<cdot> e1) (\\<sigma> \\<cdot> e2)\"\nproof (induction e1 e2 rule: ssube.induct)\n  case (1 x xs f)\n  then show ?case\n  proof (rule disjE)\n    assume \"x \\<in> set xs\"\n    then have \"\\<sigma> \\<cdot> x \\<in> set (map (sapply \\<sigma>) xs)\" by auto\n    then have \"ssube (\\<sigma> \\<cdot> x) (Fun f (map (sapply \\<sigma>) xs))\" by (auto intro: ssube.intros)\n    then show ?thesis by simp\n  next\n    assume \"\\<exists>y\\<in>set xs. ssube x y \\<and> ssube (\\<sigma> \\<cdot> x) (\\<sigma> \\<cdot> y)\" \n    then obtain y where 2: \"y \\<in> set xs \\<and> ssube x y \\<and> ssube (\\<sigma> \\<cdot> x) (\\<sigma> \\<cdot> y)\" by blast\n    then have \"\\<sigma> \\<cdot> y \\<in> set (map (sapply \\<sigma>) xs)\" by auto\n    then show ?thesis using 2 by (auto intro: ssube.intros)\n  qed\nqed\n\nlemma fv_ssube: \"\\<lbrakk> x \\<in> fv b; b \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> (ssube (Var x) b)\"\n  by (induction b) (auto intro: ssube.intros)\n\nlemma fv_msize_diff: \"\\<lbrakk> x \\<in> fv b; b \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> msize (Var x) < msize b\"\nproof -\n  assume 1: \"x \\<in> fv b\" \"b \\<noteq> Var x\"\n  then have \"ssube (Var x) b\" by (simp add: fv_ssube)\n  then show ?thesis using ssube_size by fastforce\nqed\n\nlemma fv_msize_sapply_diff: \"\\<lbrakk> x \\<in> fv b; b \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> msize (\\<sigma> x) < msize (\\<sigma> \\<cdot> b)\"\nproof -\n  assume \"x \\<in> fv b\" and \"b \\<noteq> Var x\"\n  then have \"ssube (Var x) b\" by (simp add: fv_ssube)\n  then have \"ssube (\\<sigma> x) (\\<sigma> \\<cdot> b)\" using ssube_subst_stable by fastforce\n  then show ?thesis using ssube_size by fastforce\nqed\n\n\n(****************************** ( 1C ) ******************************)\nlemma fv_sapply: \"fv (\\<sigma> \\<cdot> t) = (\\<Union>x \\<in> fv t. fv (\\<sigma> x))\"\n  apply (induction t rule: fv.induct)\n   apply (auto)\n  done\n\nlemma sapply_cong: \"\\<lbrakk>\\<And>x. x \\<in> fv t \\<Longrightarrow> \\<sigma> x = \\<tau> x \\<rbrakk> \\<Longrightarrow> \\<sigma> \\<cdot> t = \\<tau> \\<cdot> t\"\n  apply (induction t rule: fv.induct)\n   apply (auto)\n  done\n\nlemma scomp_sapply [simp]: \"(\\<sigma> \\<circ>s \\<tau>) x = \\<sigma> \\<cdot> (\\<tau> x)\"\n  by (simp add: scomp_def)\n\nlemma sapply_scomp_distr [simp]: \"(\\<sigma> \\<circ>s \\<tau>) \\<cdot> t = \\<sigma> \\<cdot> (\\<tau> \\<cdot> t)\"\n  apply (simp add: scomp_def)\n  apply (induction t rule: fv.induct)\n   apply auto\n  done\n\nlemma scomp_assoc: \"(\\<sigma> \\<circ>s \\<tau>) \\<circ>s \\<rho> = \\<sigma> \\<circ>s (\\<tau> \\<circ>s \\<rho>)\"\nproof -\n  have \"(\\<sigma> \\<circ>s \\<tau>) \\<circ>s \\<rho> = (\\<lambda>x. (\\<sigma> \\<circ>s \\<tau>) \\<cdot> \\<rho> x)\" by (simp add: scomp_def)\n  also have \"... = (\\<lambda>x. \\<sigma> \\<cdot> \\<tau> \\<cdot> \\<rho> x)\" by (simp only: sapply_scomp_distr)\n  also have \"... = \\<sigma> \\<circ>s (\\<tau> \\<circ>s \\<rho>)\" by (simp add: scomp_def)\n  finally show ?thesis .\nqed\n\nlemma scomp_var [simp]: \"\\<sigma> \\<circ>s Var = \\<sigma>\"\n  by (simp add: scomp_def)\n\nlemma var_sapply [simp]: \"Var \\<cdot> t = t\"\n  apply (induction t rule: fv.induct)\n  by (auto simp add: map_idI)\n\nlemma var_scomp [simp]: \"Var \\<circ>s \\<sigma> = \\<sigma>\"\n  by (simp add: scomp_def)\n\n\n(****************************** ( 1D ) ******************************)\n(* definitions *)\n\ndefinition sdom :: \"('f, 'v) subst \\<Rightarrow> 'v set\" where\n  \"sdom \\<sigma> = {x | x. \\<sigma> x \\<noteq> Var x}\"\n\ndefinition sran :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) term set\" where\n  \"sran \\<sigma> = {\\<sigma> x | x. x \\<in> sdom \\<sigma>}\"\n\ndefinition svran :: \"('f, 'v) subst \\<Rightarrow> 'v set\" where\n  \"svran \\<sigma> = (\\<Union> t \\<in> sran \\<sigma>. fv t)\"\n\n(* helpers *)\nlemma sdom_intro [intro]: \"\\<sigma> x \\<noteq> Var x \\<Longrightarrow> x \\<in> sdom \\<sigma>\"\n  by (simp add: sdom_def)\n\nlemma sdom_dest [dest]: \"x \\<in> sdom \\<sigma> \\<Longrightarrow> \\<sigma> x \\<noteq> Var x\"\n  by (simp add: sdom_def) \n\nlemma svran_intro [intro]: \"\\<lbrakk> x \\<in> sdom \\<sigma>; y \\<in> fv (\\<sigma> x) \\<rbrakk> \\<Longrightarrow> y \\<in> svran \\<sigma>\"\n  by (auto simp add: sdom_def sran_def svran_def)\n\nlemma svran_elim [elim]: \"y \\<in> svran \\<sigma> \\<Longrightarrow> (\\<And>x. x \\<in> sdom \\<sigma> \\<Longrightarrow> y \\<in> fv (\\<sigma> x) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (auto simp add: sdom_def sran_def svran_def)\n\nlemma svran_dest [dest]: \"y \\<in> svran \\<sigma> \\<Longrightarrow> (\\<exists>x \\<in> sdom \\<sigma>. y \\<in> fv (\\<sigma> x))\"\n  by (auto simp add: sdom_def sran_def svran_def)\n\n(* lemmata *)\nlemma sdom_var [simp]: \"sdom Var = {}\"\n  by (simp add: sdom_def)\n\nlemma svran_var [simp]: \"svran Var = {}\"\n  by (simp add: svran_def sran_def)\n\nlemma sdom_single_non_trivial [simp]: \"t \\<noteq> Var x \\<Longrightarrow> sdom (Var (x := t)) = {x}\"\n  by (simp add: sdom_def)\n\nlemma svran_single_non_trivial [simp]: \"t \\<noteq> Var x \\<Longrightarrow> svran (Var (x := t)) = fv t\"\n  by (simp add: svran_def sran_def)\n\nlemma fv_sapply_sdom_svran: \"x \\<in> fv (\\<sigma> \\<cdot> t) \\<Longrightarrow> x \\<in> (fv t - sdom \\<sigma>) \\<union> svran \\<sigma>\"\nproof (induction t)\n  case (Var y)\n  then have \"x \\<in> (\\<Union>x \\<in> fv (Var y). fv (\\<sigma> x))\" by (simp add: fv_sapply)\n  then have \"x \\<in> fv (\\<sigma> y)\" by simp\n  then show ?case \nproof (cases \"\\<sigma> y = Var y\")\n  case True\n  then have \"x \\<in> {y}\" using \\<open>x \\<in> fv (\\<sigma> y)\\<close> by simp\n  then have 1: \"x = y\" by simp\n  have 2: \"y \\<in> fv (Var y)\" by simp\n  have 3: \"y \\<notin> sdom \\<sigma>\" using \\<open>\\<sigma> y = Var y\\<close> by (simp add: sdom_def)\n  from 1 2 3 have \"x \\<in> fv (Var y) - sdom \\<sigma>\" by simp\n  then show ?thesis by auto\nnext\n  case False\n  then have \"y \\<in> sdom \\<sigma>\" by (simp add: sdom_def)\n  then have \"x \\<in> svran \\<sigma>\" using \\<open>x \\<in> fv (\\<sigma> y)\\<close> by auto\n  then show ?thesis by simp\nqed\nnext\n  case (Fun x1a x2)\n  then show ?case by auto\nqed\n\nlemma sdom_scomp: \"sdom (\\<sigma> \\<circ>s \\<tau>) \\<subseteq> sdom \\<sigma> \\<union> sdom \\<tau>\"\n  by (auto simp add: sdom_def)\n\nlemma svran_scomp: \"svran (\\<sigma> \\<circ>s \\<tau>) \\<subseteq> svran \\<sigma> \\<union> svran \\<tau>\"\nproof (rule subsetI)\n  fix x\n  assume \"x \\<in> svran (\\<sigma> \\<circ>s \\<tau>)\"\n  then obtain y where 0: \"y \\<in> sdom (\\<sigma> \\<circ>s \\<tau>)\" \"x \\<in> fv ((\\<sigma> \\<circ>s \\<tau>) y)\" by auto\n  then have \"x \\<in> fv (\\<sigma> \\<cdot> (\\<tau> y))\" by (simp only: scomp_def)\n  then have 1: \"x \\<in> (fv (\\<tau> y) - sdom \\<sigma>) \\<or> x \\<in> svran \\<sigma>\" by (blast dest: fv_sapply_sdom_svran)\n  show \"x \\<in> svran \\<sigma> \\<union> svran \\<tau>\"\n  proof(subst Un_commute, rule UnCI)\n    assume \"x \\<notin> svran \\<sigma>\"\n    then have \"x \\<in> (fv (\\<tau> y) - sdom \\<sigma>)\" using 1 by simp\n    then have 2: \"x \\<in> fv (\\<tau> y)\" by simp\n    then show \"x \\<in> svran \\<tau>\"\n    proof (cases \"y \\<in> sdom \\<tau>\")\n      case True\n      then have \"x \\<in> svran \\<tau>\" using \\<open>x \\<in> fv (\\<tau> y)\\<close> by (auto)\n      then show ?thesis by simp\n    next\n      case False\n      then have \"\\<tau> y = Var y\" by (simp add: sdom_def)\n      then have \"x = y\" using 2 by auto\n      then have False  using \\<open>x \\<in> (fv (\\<tau> y) - sdom \\<sigma>)\\<close> using \\<open>x = y\\<close> \\<open>y \\<notin> sdom \\<tau>\\<close> sdom_scomp[of \\<sigma> \\<tau>] 0 by auto\n      then show ?thesis by simp\n    qed\n  qed\nqed\n\n\n(****************************** ( 2 ) ******************************)\ntype_synonym ('f, 'v) equation = \"('f, 'v) term \\<times> ('f, 'v) term\"\n\ntype_synonym ('f, 'v) equations = \"('f, 'v) equation list\"\n\nfun fv_eq :: \"('f, 'v) equation \\<Rightarrow> 'v set\" where\n  \"fv_eq (a, b) = fv a \\<union> fv b\"\n\nfun fv_eqs :: \"('f, 'v) equations \\<Rightarrow> 'v set\" where\n  \"fv_eqs l = (\\<Union>x \\<in> set l. fv_eq x)\"\n\nfun sapply_eq :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> ('f, 'v) equation\" where\n  \"sapply_eq \\<sigma> (a,b) = (sapply \\<sigma> a, sapply \\<sigma> b)\"\n\nfun sapply_eqs :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> ('f, 'v) equations\" where\n  \"sapply_eqs \\<sigma> l = map (sapply_eq \\<sigma>) l\"\n\n\n(****************************** ( 2A ) ******************************)\nlemma fv_sapply_eq: \"fv_eq (sapply_eq \\<sigma> (a,b)) = fv (\\<sigma> \\<cdot> a) \\<union> fv (\\<sigma> \\<cdot> b)\"\n  by auto\n\nlemma fv_sapply_eqs: \"fv_eqs (sapply_eqs \\<sigma> l) = (\\<Union>x \\<in> set l. fv_eq (sapply_eq \\<sigma> x))\"\n  by (auto)\n\nlemma sapply_scomp_distrib_eq: \"sapply_eq (\\<sigma> \\<circ>s \\<tau>) (a,b) = (\\<sigma> \\<cdot> (\\<tau> \\<cdot> a), \\<sigma> \\<cdot> (\\<tau> \\<cdot> b))\"\n  by (simp)\n\nlemma sapply_scomp_distrib_eqs: \"sapply_eqs (\\<sigma> \\<circ>s \\<tau>) l = map (\\<lambda>x. sapply_eq (\\<sigma> \\<circ>s \\<tau>) x) l\"\n  apply (induction l)\n  by auto\n\n(* helpers used for lemma 3 *)\nlemma fv_sapply_eq_sdom_svran: \"x \\<in> fv_eq (sapply_eq \\<sigma> t) \\<Longrightarrow> x \\<in> (fv_eq t - sdom \\<sigma>) \\<union> svran \\<sigma>\"\nproof -\n  assume \"x \\<in> fv_eq (sapply_eq \\<sigma> t)\"\n  moreover obtain a b where \"t = (a,b)\" using fv_eq.cases by blast\n  ultimately have \"x \\<in> fv (\\<sigma> \\<cdot> a) \\<union> fv (\\<sigma> \\<cdot> b)\" by auto\n  then have \"x \\<in> (fv a - sdom \\<sigma>) \\<union> svran \\<sigma> \\<union> (fv b - sdom \\<sigma>) \\<union> svran \\<sigma>\" using fv_sapply_sdom_svran by (metis Un_iff)\n  then have \"x \\<in> (fv a \\<union> fv b - sdom \\<sigma>) \\<union> svran \\<sigma>\" by blast\n  then show ?thesis by (simp add: \\<open>t = (a, b)\\<close>)\nqed\n\nlemma fv_sapply_eqs_sdom_svran: \"x \\<in> fv_eqs (sapply_eqs \\<sigma> t) \\<Longrightarrow> x \\<in> (fv_eqs t - sdom \\<sigma>) \\<union> svran \\<sigma>\"\nproof -\n  assume \"x \\<in> fv_eqs (sapply_eqs \\<sigma> t)\"\n  then have \"x \\<in> (\\<Union>y \\<in> set t. fv_eq (sapply_eq \\<sigma> y))\" by (auto simp add: fv_sapply_eqs)\n  then have \"x \\<in> (\\<Union>y \\<in> set t. fv_eq y - sdom \\<sigma>) \\<union> svran \\<sigma>\" using fv_sapply_eq_sdom_svran by (metis (no_types, lifting) UN_iff UnE UnI1 UnI2)\n  then show ?thesis by auto \nqed\n\nlemma fv_sapply_var: \"\\<lbrakk> b \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> fv_eqs (sapply_eqs (Var (x := b)) xs) \\<subseteq> fv b \\<union> fv_eqs xs\"\nproof (rule subsetI)\n  fix y\n  assume \"b \\<noteq> Var x\"\n  then have \"svran (Var (x := b)) = fv b\" by simp\n  then show \"y \\<in> fv_eqs (sapply_eqs (Var(x := b)) xs) \\<Longrightarrow> y \\<in> fv b \\<union> fv_eqs xs\" using fv_sapply_eqs_sdom_svran by (metis Diff_iff UnE UnI1 UnI2)\nqed\n\n\n(****************************** ( 2B ) ******************************)\ninductive unifies :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> bool\" where\n  \"\\<lbrakk> \\<sigma> \\<cdot> a = \\<sigma> \\<cdot> b \\<rbrakk> \\<Longrightarrow> unifies \\<sigma> (a, b)\"\n\ndefinition unifiess :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"unifiess \\<sigma> l =  (\\<forall> x \\<in> set l. unifies \\<sigma> x)\"\n\n(* some helper lemmas about unifies / unifiess *)\nlemma unifiess_empty: \"unifiess \\<sigma> []\"\n  by (auto simp add: unifiess_def)\n\nlemma unifiess_list: \"\\<lbrakk> unifies \\<sigma> x; unifiess \\<sigma> xs \\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> (x # xs)\"\n  by (auto simp add: unifies.intros unifiess_def)\n\nlemma unifies_zip: \"\\<lbrakk> length l1 = length l2; (\\<And>a b. (a,b) \\<in> set (zip l1 l2) \\<Longrightarrow> unifies \\<sigma> (a,b)) \\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> (zip l1 l2)\"\n  apply (induction \"zip l1 l2\")\n  by (auto simp add: unifiess_def)\n\nlemma in_fv_not_unifies: \"\\<lbrakk> x \\<in> fv b; b \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> \\<not>(\\<exists>\\<sigma>. unifies \\<sigma> (Var x, b))\"\nproof (rule notI)\n  assume 1: \"x \\<in> fv b\"\n     and 2: \"b \\<noteq> Var x\"\n     and 3: \"\\<exists>\\<sigma>. unifies \\<sigma> (Var x, b)\"\n  then obtain \\<sigma> where \"unifies \\<sigma> (Var x, b)\" by blast\n  then have \"\\<sigma> x = \\<sigma> \\<cdot> b\" by (auto simp add: unifies.simps)\n  then show \"False\"\n  proof (cases b)\n    case (Var x1)\n    have \"fv b = {x1}\" using \\<open>b = Var x1\\<close> by simp\n    then have \"x1 = x\" using \\<open>x \\<in> fv b\\<close> by simp\n    then have \"b = Var x\" using \\<open>b = Var x1\\<close> by simp\n    then show ?thesis using \\<open>b \\<noteq> Var x\\<close> by simp\n  next\n    case (Fun f xs)\n    obtain \\<sigma> where \"unifies \\<sigma> (Var x, b)\" using 3 by blast\n    then have \"\\<sigma> x = \\<sigma> \\<cdot> b\" by (simp add: unifies.simps)\n    have \"msize (\\<sigma> x) < msize (\\<sigma> \\<cdot> b)\" using 1 2 by (simp add: fv_msize_sapply_diff)\n    then have \"\\<sigma> x \\<noteq> \\<sigma> \\<cdot> b\" by (simp add: msize_term_diff)\n    then have False using \\<open>\\<sigma> x = \\<sigma> \\<cdot> b\\<close> by blast\n    then show ?thesis by simp\n  qed\nqed\n\nlemma length_zip: \"\\<lbrakk> length l1 = length l2 \\<rbrakk> \\<Longrightarrow> (\\<forall>(a,b) \\<in> set (zip l1 l2). f a = f b) \\<longleftrightarrow> map f l1 = map f l2\"\nproof (induction l1 l2 rule: list_induct2)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs y ys)\n  then show ?case by auto\nqed\n\nlemma unify_zip_fun: \"\\<lbrakk> length l1 = length l2 \\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> (zip l1 l2) \\<longleftrightarrow> unifies \\<sigma> (Fun f l1, Fun f l2)\"\nproof (rule iffI)\n  assume \"length l1 = length l2\"\n     and \"unifiess \\<sigma> (zip l1 l2)\"\n  then have \"\\<forall>(a,b) \\<in> set (zip l1 l2). \\<sigma> \\<cdot> a = \\<sigma> \\<cdot> b\" by (auto simp add: unifiess_def unifies.simps)\n  then have \"map (sapply \\<sigma>) l1 = map (sapply \\<sigma>) l2\" using \\<open>length l1 = length l2\\<close> by (simp add: length_zip)\n  then have \"\\<sigma> \\<cdot> (Fun f l1) = \\<sigma> \\<cdot> (Fun f l2)\" by auto\n  then show  \"unifies \\<sigma> (Fun f l1, Fun f l2)\" using unifies.intros by blast\nnext\n  assume \"length l1 = length l2\"\n     and \"unifies \\<sigma> (Fun f l1, Fun f l2)\"\n  then have \"\\<sigma> \\<cdot> (Fun f l1) = \\<sigma> \\<cdot> (Fun f l2)\" by (auto simp add: unifies.simps)\n  then have \"map (sapply \\<sigma>) l1 = map (sapply \\<sigma>) l2\" by auto\n  then have \"\\<forall>(a,b) \\<in> set (zip l1 l2). \\<sigma> \\<cdot> a = \\<sigma> \\<cdot> b\" using \\<open>length l1 = length l2\\<close> by (simp add: length_zip)\n  then show \"unifiess \\<sigma> (zip l1 l2)\" using \\<open>length l1 = length l2\\<close> unifies_zip unifies.intros by fastforce\nqed\n\nlemma ex_unifier_fun: \n  assumes \"(\\<exists>\\<tau>. unifiess \\<tau> ((Fun f l1, Fun g l2) # xs))\"\n  shows \"f = g\"\n    and \"length l1 = length l2\"\n    and \"\\<exists>\\<tau>. unifiess \\<tau> (xs @ zip l1 l2)\"\nproof -\n  obtain \\<tau> where \"unifiess \\<tau> ((Fun f l1, Fun g l2) # xs)\" using assms by auto\n  then have \"unifies \\<tau> (Fun f l1, Fun g l2)\" by (simp add: unifiess_def)\n  then have \"Fun f (map (sapply \\<tau>) l1) = Fun g (map (sapply \\<tau>) l2)\" by (auto simp add: unifies.simps)\n  then show \"f = g\" by simp\nnext\n  obtain \\<tau> where 3: \"unifiess \\<tau> ((Fun f l1, Fun g l2) # xs)\" using assms by auto\n  then have 1: \"unifies \\<tau> (Fun f l1, Fun g l2)\" by (simp add: unifiess_def)\n  then have \"Fun f (map (sapply \\<tau>) l1) = Fun g (map (sapply \\<tau>) l2)\" by (auto simp add: unifies.simps)\n  then have \"map (sapply \\<tau>) l1 = map (sapply \\<tau>) l2\" by simp\n  then show 2: \"length l1 = length l2\" using map_eq_imp_length_eq by blast\n  have \"unifiess \\<tau> (zip l1 l2)\" using 1 2 unify_zip_fun[OF 2] \\<open>Fun f (map (op \\<cdot> \\<tau>) l1) = Fun g (map (op \\<cdot> \\<tau>) l2)\\<close> by blast\n  moreover have \"unifiess \\<tau> xs\" using 3 by (auto simp add: unifiess_def)\n  ultimately have \"unifiess \\<tau> (xs @ zip l1 l2)\" by (auto simp add: unifiess_def)\n  then show \"\\<exists>\\<tau>. unifiess \\<tau> (xs @ zip l1 l2)\" by blast\nqed\n\n(* end of helper lemmas *)\n\nfun is_mgu :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"is_mgu \\<sigma> l \\<longleftrightarrow> (unifiess \\<sigma> l \\<and> (\\<forall> \\<tau>. unifiess \\<tau> l \\<longrightarrow> (\\<exists> \\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>)))\"\n\n\n(****************************** ( 2C ) ******************************)\nlemma lambda_simp:  \"\\<sigma> \\<cdot> \\<tau> \\<cdot> a = (\\<lambda>x. \\<sigma> \\<cdot> \\<tau> x) \\<cdot> a\"\n  apply (induction a rule: fv.induct)\n  by auto\n\nlemma unifies_sapply_eq [simp]: \"unifies \\<sigma> (sapply_eq \\<tau> eq) \\<longleftrightarrow> unifies (\\<sigma> \\<circ>s \\<tau>) eq\"\n  apply (rule iffI)\n  apply (cases eq)\n  by (auto simp add: unifies.simps lambda_simp)\n\nlemma unifiess_sapply_eqs [simp]: \"unifiess \\<sigma> (sapply_eqs \\<tau> eqs) \\<longleftrightarrow> unifiess (\\<sigma> \\<circ>s \\<tau>) eqs\"\n  apply (induction eqs)\n  apply (auto simp add: unifiess_def lambda_simp) \n  by (metis (no_types, lifting) Unification.scomp_def sapply_cong unifies.simps)+\n\n\n(**** UNIFY ALGORITHM **** UNIFY ALGORITHM **** UNIFY ALGORITHM **** UNIFY ALGORITHM ****)\n\n(* helper function for robinson algorithm *)\nfun scomp_opt :: \"('f, 'v) subst option \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> ('f, 'v) subst option\" where\n  \"scomp_opt (Some \\<sigma>) \\<tau> = Some (\\<sigma> \\<circ>s \\<tau>)\"\n| \"scomp_opt None _ = None\"\n\n(* measure function to show termination of robinson *)\nfun size_exp :: \"('f, 'v) term \\<Rightarrow> nat\" where\n  \"size_exp (Var _) = 0\"\n| \"size_exp (Fun _ l) = 1 + sum_list (map size_exp l)\"\n\nfun eqs_size :: \"('f, 'v) equations \\<Rightarrow> nat\" where\n  \"eqs_size [] = 0\"\n| \"eqs_size ((e, _) # eqs) = size_exp e + eqs_size eqs\"\n\n(* helper lemmas to show termination of robinson *)\nlemma eqs_size_append: \"eqs_size (xs @ ys) = eqs_size xs + eqs_size ys\"\n  apply (induction xs)\n  by auto\n\nlemma eqs_size_zip [simp]: \"\\<lbrakk> length l1 = length l2 \\<rbrakk> \\<Longrightarrow> eqs_size (xs @ zip l1 l2) = eqs_size xs + sum_list (map size_exp l1)\"\nproof (induction l1 l2 rule: list_induct2) \n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs y ys)\n  then show ?case by (auto simp add: eqs_size_append)\nqed\n\nlemma scomp_some: \"scomp_opt a b = Some c \\<Longrightarrow> \\<exists>\\<sigma>. a = Some \\<sigma>\"\n  apply (cases a)\n  by auto\n\nlemma finite_fv [simp]: \"finite (fv e)\"\n  apply (induction e)\n  by auto\n\nlemma finite_fv_eq [simp]: \"finite (fv_eq e)\"\n  apply (cases e)\n  by auto\n\nlemma finite_fv_eqs [simp]: \"finite (fv_eqs l)\"\n  apply (induction l)\n  by (auto)\n\nlemma fv_eqs_cons [simp]: \"fv_eqs (eq # eqs) = fv_eq eq \\<union> fv_eqs eqs\"\n  by (auto) \n\nlemma fv_eq_subst_eq: \"fv_eq (sapply_eq \\<sigma> eq) = (\\<Union>x\\<in>fv_eq eq. fv (\\<sigma> x))\"\n  by(cases eq)(simp add: fv_sapply)\n\nlemma fv_eqs_subst_eqs: \"fv_eqs (map (sapply_eq \\<sigma>) eqs) = (\\<Union> x\\<in>fv_eqs eqs. fv (\\<sigma> x))\"\n  by(simp add: fv_eq_subst_eq)\n\nlemma fv_eqs_zip [simp]: \"\\<lbrakk> length l1 = length l2 \\<rbrakk> \\<Longrightarrow> fv_eqs (xs @ zip l1 l2) = (\\<Union>x\\<in>set l1. fv x) \\<union> (\\<Union>x\\<in>set l2. fv x) \\<union> fv_eqs xs\"\n  apply (induction l1 l2 rule: list_induct2)\n  by (auto)\n\n(****************************** ( 3A ) ******************************)\nfunction (sequential) unify :: \"('f, 'v) equations \\<Rightarrow> ('f, 'v) subst option\" where\n  \"unify [] = Some Var\"\n| \"unify ((Var x, b) # xs) = (if b = Var x then unify xs else (if x \\<in> fv b then None else scomp_opt (unify (sapply_eqs (Var (x := b)) xs)) (Var (x := b))))\"\n| \"unify ((b, Var x) # xs) = unify ((Var x, b) # xs)\"\n| \"unify ((Fun f l1, Fun g l2) # xs) = (if g = f then (if length l2 = length l1 then unify (xs @ (zip l1 l2)) else None) else None)\"\nby pat_completeness auto\ntermination\n  apply (relation \"measures [\n  (\\<lambda>U. card (fv_eqs U)), eqs_size, length]\") \n  by (auto intro!: psubset_card_mono card_mono split: if_split_asm simp add: fv_eqs_subst_eqs simp del: fv_eqs.simps) \n\n\n(* helper lemmas to show soundness and or completeness *)\nlemma unifies_scomp_fst: \"unifies a b \\<Longrightarrow> unifies (c \\<circ>s a) b\"\n  by (auto simp add: scomp_def unifies.intros unifies.simps lambda_simp[symmetric])\n\nlemma sapply_notin_fv: \"\\<lbrakk> x \\<notin> fv t \\<rbrakk> \\<Longrightarrow> (Var (x := s)) \\<cdot> t = t\"\nproof (induction t arbitrary: s rule: term.induct)\n  case (Var x)\n  then show ?case by auto\nnext\n  case 2: (Fun f xs)\n  have \"x \\<notin> (\\<Union>y \\<in> (set xs). fv y)\" using \\<open>x \\<notin> fv (Fun f xs)\\<close> by simp\n  then have \"(\\<forall>y \\<in> (set xs). x \\<notin> fv y)\" by simp\n  then have \"(\\<forall>y \\<in> (set xs). (Var (x := Fun f xs)) \\<cdot> y = y)\" using 2 by blast\n  moreover have \"Var (x := (Fun f xs)) \\<cdot> (Fun f xs) = Fun f (map (sapply (Var (x := Fun f xs))) xs)\" by simp\n  ultimately show ?case by (metis \"2.IH\" \\<open>\\<forall>y\\<in>set xs. x \\<notin> fv y\\<close> map_idI sapply.simps(2))\nqed\n\nlemma unifies_triv: \"\\<lbrakk> x \\<notin> fv t \\<rbrakk> \\<Longrightarrow> unifies (Var (x := t)) (Var x, t)\"\nproof -\n  assume \"x \\<notin> fv t\" \n  have \"(Var (x := t)) \\<cdot> Var x = t\" by simp\n  moreover have \"(Var (x := t)) \\<cdot> t = t\" using \\<open>x \\<notin> fv t\\<close> by (simp add: sapply_notin_fv)\n  ultimately show ?thesis by (simp add: unifies.intros)\nqed\n\nlemma unify_notin_fv: \"\\<lbrakk> x \\<notin> fv t \\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> (sapply_eqs (Var (x := t)) xs) \\<longleftrightarrow> unifiess (\\<sigma> \\<circ>s (Var (x := t))) ((Var x, t) # xs)\"\n  by (auto simp add: unifiess_def unifies_scomp_fst unifies_triv)\n\nlemma unifier_invariant: \"\\<lbrakk> x \\<notin> fv b; unifies \\<tau> (Var x, b) \\<rbrakk> \\<Longrightarrow> \\<tau> \\<circ>s (Var (x := b)) = \\<tau>\"\nproof (rule ext)\n  assume \"x \\<notin> fv b\" and \"unifies \\<tau> (Var x, b)\"\n  fix xa\n  show \"(\\<tau> \\<circ>s (Var (x := b))) xa = \\<tau> xa\" \n  proof (cases \"xa = x\")\n    case True\n    have \"(\\<tau> \\<circ>s (Var (x := b))) xa = \\<tau> \\<cdot> b\" using \\<open>xa = x\\<close> by simp\n    then have \"... = \\<tau> x\" using \\<open>unifies \\<tau> (Var x, b)\\<close> by (simp add: unifies.simps)\n    then show ?thesis by simp\n  next\n    case False\n    have \"(\\<tau> \\<circ>s (Var (x := b))) xa = \\<tau> xa\" using \\<open>xa \\<noteq> x\\<close> by simp\n    then show ?thesis by simp\n  qed \nqed\n\nlemma unify_notin_fv_spec:\n  assumes \"x \\<notin> fv t\"\n      and \"unifiess \\<sigma> ((Var x, t) # xs)\"\n    shows \"unifiess \\<sigma> (sapply_eqs (Var (x := t)) xs)\"\n  apply (simp add: unifiess_def)\nproof (safe)\n  fix a b\n  assume \"(a, b) \\<in> set xs\"\n  have \"unifies \\<sigma> (Var x, t)\" using assms by (simp add: unifiess_def)\n  then have \"\\<sigma> \\<circ>s (Var (x := t)) = \\<sigma>\" using assms by (simp add: unifier_invariant)\n  moreover have \"unifies \\<sigma> (a, b)\" using \\<open>(a,b) \\<in> set xs\\<close>  assms by (simp add: unifiess_def) \n  ultimately show \"unifies (\\<sigma> \\<circ>s Var(x := t)) (a, b)\" by simp\nqed\n\n\nlemma unify_notin: \"\\<lbrakk> unify ((Var x, b) # xs) = Some \\<sigma>;  b \\<noteq> Var x \\<rbrakk> \\<Longrightarrow> x \\<notin> fv b\"\n  by auto\n\n\n(**** SOUNDNESS **** SOUNDNESS **** SOUNDNESS **** SOUNDNESS **** SOUNDNESS ****)\n\nlemma unify_return: \"unify l = Some \\<sigma> \\<Longrightarrow> unifiess \\<sigma> l\"\nproof (induction l arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by (simp only: unifiess_empty)\nnext\n  case Var_Var: (2 x b xs)\n  then show ?case\n  proof (cases \"b = Var x\")\n    case True \n    then have 1: \"unify xs = Some \\<sigma> \\<Longrightarrow> unifiess \\<sigma> xs\" using \\<open>b = Var x\\<close> using Var_Var by blast\n    have \"unify ((Var x, b) # xs) = unify xs\" using \\<open>b = Var x\\<close> by simp\n    then have \"unify xs = Some \\<sigma>\" using \\<open>unify ((Var x, b) # xs) = Some \\<sigma>\\<close> by simp\n    then have \"unifiess \\<sigma> xs\" using 1 by blast\n    then show ?thesis using \\<open>b = Var x\\<close> by (simp add: unifiess_list unifies.intros)\n  next \n    case False\n    have \"x \\<notin> fv b\" using unify_notin Var_Var False by auto \n    let ?term = \"sapply_eqs (Var(x := b)) xs\"\n    have 3: \"unify ?term = Some \\<sigma> \\<Longrightarrow> unifiess \\<sigma> ?term\" using Var_Var \\<open>x \\<notin> fv b\\<close> \\<open>b \\<noteq> Var x\\<close> by simp\n    have \"unify ((Var x, b) # xs) =  scomp_opt (unify ?term) (Var (x := b))\" using \\<open>b \\<noteq> Var x\\<close> \\<open>x \\<notin> fv b\\<close> by simp\n    then have \"scomp_opt (unify ?term) (Var (x := b)) = Some \\<sigma>\" using Var_Var by simp\n    then obtain \\<tau> where 4: \"unify ?term = Some \\<tau>\" by (auto dest: scomp_some)\n    have \"(\\<tau> \\<circ>s (Var (x := b))) \\<cdot> (Var x) = \\<tau> \\<cdot> b\" by (simp)\n    also have \"... = (\\<tau> \\<circ>s (Var (x := b))) \\<cdot> b\" using \\<open>x \\<notin> fv b\\<close> by (simp add: sapply_notin_fv)\n    have \"unifiess \\<tau> ?term\" using 3 4 False Var_Var.IH(2) \\<open>x \\<notin> fv b\\<close> by force\n    then show ?thesis using Var_Var \"4\" False \\<open>scomp_opt (unify (sapply_eqs (Var(x := b)) xs)) (Var(x := b)) = Some \\<sigma>\\<close> unify_notin_fv by fastforce \n  qed\nnext\n  case (3 v va x xs)\n  have \"unify ((Fun v va, Var x) # xs) = unify ((Var x, Fun v va) # xs)\" by simp\n  then have \"unify ((Var x, Fun v va) # xs) = Some \\<sigma>\" using 3 by simp\n  then have 7: \"unifiess \\<sigma> ((Var x, Fun v va) # xs)\" using 3 by simp\n  then have \"unifies \\<sigma> (Fun v va, Var x)\" by (simp add: unifies.intros unifies.simps unifiess_def)\n  then show ?case using 7 by (auto simp add: unifiess_def) \nnext\n  case (4 f l1 g l2 xs)\n  have 10: \"g = f\" \"length l2 = length l1\" \"unify (xs @ zip l1 l2) = Some \\<sigma>\" using 4 by (simp_all split: if_splits)\n  then have \"length l1 = length l2\" using 4 by simp\n  have \"unifiess \\<sigma> (xs @ zip l1 l2)\" using 4 10 by blast\n  then have \"unifiess \\<sigma> xs\" \"unifiess \\<sigma> (zip l1 l2)\" by (auto simp add: unifiess_def)\n  then have \"unifies \\<sigma> (Fun f l1, Fun g l2)\" using \\<open>unifiess \\<sigma> (zip l1 l2)\\<close> unify_zip_fun[OF \\<open>length l1 = length l2\\<close>] using \"10\"(1) by blast\n  then show ?case using \\<open>unifiess \\<sigma> xs\\<close> by (auto simp add: unifiess_list unifiess_def)\nqed\n\n\nlemma unify_mgu: \"\\<lbrakk>unify l = Some \\<sigma>; unifiess \\<tau> l\\<rbrakk> \\<Longrightarrow> \\<exists> \\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\"\nproof (induction l arbitrary: \\<sigma> \\<tau> rule: unify.induct)\n  case 1\n  have \"unify [] = Some Var\" by simp\n  then have \"\\<sigma> = Var\" using \\<open>unify [] = Some \\<sigma>\\<close> by simp\n  then have \"\\<tau> = \\<tau> \\<circ>s \\<sigma>\" by simp\n  then show ?case by (rule exI[where ?x = \\<tau>])\nnext\n  case (2 x b xs)\n  then show ?case\n  proof (cases \"b = Var x\")\n    case b_var: True\n    then have \"unify ((Var x, b) # xs) = unify xs\" by simp\n    then have \"unify xs = Some \\<sigma>\" using 2 by simp\n    moreover have \"unifiess \\<tau> xs\" using 2 by (simp add: unifiess_def)\n    ultimately have \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\" using \\<open>b = Var x\\<close> 2 by blast\n    then show ?thesis .\n  next\n    case b_fun: False\n    then have x_free: \"x \\<notin> fv b\" using 2 b_fun unify_notin by auto\n    let ?term = \"sapply_eqs (Var(x := b)) xs\"\n    have \"unify ((Var x, b) # xs) = scomp_opt (unify ?term) (Var (x := b))\" using x_free b_fun by simp\n    then have 3: \"scomp_opt (unify ?term) (Var (x := b)) = Some \\<sigma>\" using 2 by simp\n    then have \"\\<exists>\\<tau>. unify ?term = Some \\<tau>\" by (auto simp add: scomp_some)\n    then obtain \\<sigma>\\<^sub>2 where 4: \"unify ?term = Some \\<sigma>\\<^sub>2\" by blast\n    moreover have \"unifiess \\<tau> ?term\" using 2 \\<open>x \\<notin> fv b\\<close> unify_notin_fv_spec by auto\n    ultimately have \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\\<^sub>2\" using 2 \\<open>x \\<notin> fv b\\<close> \\<open>b \\<noteq> Var x\\<close> by blast\n    then show ?thesis by (metis \"2.prems\"(2) \"3\" \"4\" list.set_intros(1) option.inject scomp_assoc scomp_opt.simps(1) unifier_invariant unifiess_def x_free)\n  qed\nnext\n  case (3 v va x xs)\n  then have \"unifiess \\<tau> ((Var x, Fun v va) # xs)\" by (simp add: unifiess_def unifies.simps)\n  moreover have \"unify ((Var x, Fun v va) # xs) = Some \\<sigma>\" using 3 by simp\n  ultimately have \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\" using 3 by blast\nthen show ?case .\nnext\n  case Fun_Case: (4 f l1 g l2 xs)\n  then have 5: \"f = g\" \"length l1 = length l2\" \"unify (xs @ zip l1 l2) = Some \\<sigma>\" by (simp_all split: if_splits)\n  have \"unifiess \\<tau> xs\" \"unifies \\<tau> (Fun f l1, Fun g l2)\" using Fun_Case by (auto simp add: unifiess_def)\n  then have \"unifiess \\<tau> (zip l1 l2)\" using Fun_Case unify_zip_fun[OF \\<open>length l1 = length l2\\<close>] \\<open>f = g\\<close> by blast\n  then have \"unifiess \\<tau> (xs @ zip l1 l2)\" using \\<open>unifiess \\<tau> xs\\<close> by (auto simp add: unifiess_def)\n  then have \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\" using Fun_Case 5 by (simp add: Fun_Case.IH) \n  then show ?case .\nqed\n\n\nlemma unify_sound: \"unify l = Some \\<sigma> \\<Longrightarrow> is_mgu \\<sigma> l\"\n  by (auto simp add: unify_mgu unify_return)\n\n\n(**** COMPLETENESS **** COMPLETENESS **** COMPLETENESS **** COMPLETENESS ****)\n\n\nlemma unifier_exists_unify: \"\\<exists>\\<tau>. unifiess \\<tau> l \\<Longrightarrow> \\<exists>\\<sigma>. unify l = Some \\<sigma>\"\nproof (induction l rule: unify.induct)\n  case 1\n  have \"unify [] = Some Var\" by simp\n  then show ?case by (rule exI[where ?x = Var])\nnext\ncase (2 x b xs)\n  then show ?case\n  proof (cases \"b = Var x\")\n    case True\n    assume 1: \"b = Var x \\<Longrightarrow> \\<exists>\\<tau>. unifiess \\<tau> xs \\<Longrightarrow> \\<exists>\\<sigma>. unify xs = Some \\<sigma>\"\n       and \"\\<exists>\\<tau>. unifiess \\<tau> ((Var x, b) # xs)\"\n    then obtain \\<tau> where \"unifiess \\<tau> ((Var x, b) # xs)\" by auto\n    then have \"unifiess \\<tau> xs\" by (auto simp add: unifiess_def)\n    then have \"\\<exists>\\<tau>. unifiess \\<tau> xs\" by blast\n    then have \"\\<exists>\\<sigma>. unify xs = Some \\<sigma>\" using \\<open>b = Var x\\<close> 1 by simp\n    have \"unify ((Var x, b) # xs) = unify xs\" using \\<open>b = Var x\\<close> by simp \n    then show ?thesis using \\<open>\\<exists>\\<sigma>. unify xs = Some \\<sigma>\\<close> by simp\n  next\n    case b_notvar: False\n    then show ?thesis\n    proof (cases \"x \\<in> fv b\")\n      case True\n      obtain \\<tau> where \"unifiess \\<tau> ((Var x, b) # xs)\" using 2 by blast\n      then have \"unifies \\<tau> (Var x, b)\" by (simp add: unifiess_def)\n      then have \"\\<exists>\\<tau>. unifies \\<tau> (Var x, b)\" by blast\n      moreover have \"\\<nexists>\\<tau>. unifies \\<tau> (Var x, b)\" using \\<open>x \\<in> fv b\\<close> \\<open>b \\<noteq> Var x\\<close> by (simp add: in_fv_not_unifies)\n      ultimately have False by simp\n      then show ?thesis by simp\n    next\n      let ?term = \"(sapply_eqs (Var(x := b)) xs)\"\n      case x_free: False\n      obtain \\<tau> where \"unifiess \\<tau> ((Var x, b) # xs)\" using 2 by blast \n      then have \"unifiess \\<tau> ?term\" using \\<open>x \\<notin> fv b\\<close>  unify_notin_fv_spec by simp\n      then have \"\\<exists>\\<sigma>. unify (sapply_eqs (Var(x := b)) xs) = Some \\<sigma>\" using 2 \\<open>x \\<notin> fv b\\<close> \\<open>b \\<noteq> Var x\\<close> by blast\n      then obtain \\<sigma> where \"unify (sapply_eqs (Var(x := b)) xs) = Some \\<sigma>\" by blast\n      moreover have \"unify ((Var x, b) # xs) = scomp_opt (unify (sapply_eqs (Var (x := b)) xs)) (Var (x := b))\" using x_free b_notvar by simp\n      ultimately have \"unify ((Var x, b) # xs) = scomp_opt (Some \\<sigma>) (Var (x := b))\" by auto\n      then have \"unify ((Var x, b) # xs) = Some (\\<sigma> \\<circ>s (Var (x := b)))\" by simp\n      then show ?thesis by simp\n    qed\n  qed\nnext\n  case (3 v va x xs)\n  assume 2: \"\\<exists>\\<tau>. unifiess \\<tau> ((Var x, Fun v va) # xs) \\<Longrightarrow> \\<exists>\\<sigma>. unify ((Var x, Fun v va) # xs) = Some \\<sigma>\"\n     and \"\\<exists>\\<tau>. unifiess \\<tau> ((Fun v va, Var x) # xs)\"\n  then obtain \\<tau> where \"unifiess \\<tau> ((Fun v va, Var x) # xs)\" by blast\n  then have \"unifiess \\<tau> xs\" \"unifies \\<tau> (Fun v va, Var x)\" by (auto simp add: unifiess_def)\n  then have \"\\<tau> \\<cdot> (Var x) = \\<tau> \\<cdot> (Fun v va)\" by (auto simp add: unifies.simps)\n  then have \"unifies \\<tau> (Var x, Fun v va)\" by (auto simp add: unifies.intros)\n  then have \"unifiess \\<tau> ((Var x, Fun v va) # xs)\" using \\<open>unifiess \\<tau> xs\\<close> by (auto simp add: unifiess_def)\n  then have \"\\<exists>\\<sigma>. unify ((Var x, Fun v va) # xs) = Some \\<sigma>\" using 2 by blast\n  moreover have \"unify ((Fun v va, Var x) # xs) = unify ((Var x, Fun v va) # xs)\" by simp\n  ultimately show ?case by simp\nnext\n  case (4 f l1 g l2 xs)\n  then have 5: \"f = g\" \"length l1 = length l2\" \"\\<exists>\\<tau>. unifiess \\<tau> (xs @ zip l1 l2)\" by (auto simp add: ex_unifier_fun)\n  then have \"\\<exists>\\<sigma>. unify (xs @ zip l1 l2) = Some \\<sigma>\" using 4 by simp\n  then obtain \\<sigma> where 6: \"unify (xs @ zip l1 l2) = Some \\<sigma>\" by blast\n  have \"unify ((Fun f l1, Fun g l2) # xs) = unify (xs @ (zip l1 l2))\" using 5 by simp\n  then have \"unify ((Fun f l1, Fun g l2) # xs) = Some \\<sigma>\" using 6 by simp \n  then show ?case by blast\nqed\n\nlemma unify_complete: \"\\<exists> \\<sigma>. unifiess \\<sigma> l \\<Longrightarrow> (\\<exists>\\<tau>. unify l = Some \\<tau> \\<and> unifiess \\<tau> l)\"\nproof -\n  assume \"\\<exists> \\<sigma>. unifiess \\<sigma> l\"\n  then have \"\\<exists>\\<rho>. unify l = Some \\<rho>\" by (simp add: unifier_exists_unify)\n  then obtain x where 1: \"unify l = Some x\" by auto\n  then have \"unifiess x l\" using 1 by (simp add: unify_return)\n  then have \"unify l = Some x \\<and> unifiess x l\" using 1 by simp\n  then show ?thesis by (rule exI[where ?x = x])\nqed\n\n\n(********* LEMMA 3 ************* LEMMA 3 ************ LEMMA 3 *************)\n\nlemma three_one:   \n  fixes \\<sigma> :: \"('f, 'v) subst\" \n    and l :: \"('f, 'v) equations\"\n  assumes \"unify l = Some \\<sigma>\"\n  shows \"fv_eqs (sapply_eqs \\<sigma> l) \\<subseteq> fv_eqs l \\<and> sdom \\<sigma> \\<subseteq> fv_eqs l \\<and> svran \\<sigma> \\<subseteq> fv_eqs l\"\nusing assms proof (induction l arbitrary: \\<sigma> rule: unify.induct[case_names empty Var flip Fun]) \n  case empty print_cases\n  assume \"unify [] = Some \\<sigma>\" \n  then have \"\\<sigma> = Var\" using \\<open>unify [] = Some \\<sigma>\\<close> by simp\n  then show ?case by auto\nnext\n  case (Var x b xs)\n  assume unif: \"unify ((Var x, b) # xs) = Some \\<sigma>\"\n  show ?case\n  proof (cases \"b = Var x\")\n      case b_var: True\n      have f0: \"unify xs = Some \\<sigma>\" using Var \\<open>b = Var x\\<close> unif by simp\n      then have f1: \"fv_eqs (sapply_eqs \\<sigma> xs) \\<subseteq> fv_eqs xs\" using \\<open>b = Var x\\<close> Var by simp\n      then have f2: \"svran \\<sigma> \\<subseteq> fv_eqs xs\" using \\<open>b = Var x\\<close> Var f0 by simp\n      have \"fv_eqs ((Var x, b) # xs) = fv_eqs xs \\<union> {x}\" using \\<open>b = Var x\\<close> by simp\n      then have f3: \"fv_eqs (sapply_eqs \\<sigma> ((Var x, b) # xs)) = fv (\\<sigma> x) \\<union> fv_eqs (sapply_eqs \\<sigma> xs)\" using \\<open>b = Var x\\<close> by simp\n      have \"(fv (Var x) - sdom \\<sigma>) \\<subseteq> {x}\" by auto\n      moreover have \"fv (\\<sigma> x) \\<subseteq> fv (Var x) - sdom \\<sigma> \\<union> svran \\<sigma>\" using  fv_sapply_sdom_svran\n        by (metis UnCI calculation fv.simps(1) insert_Diff_if insert_not_empty sdom_intro subsetI subset_singletonD svran_intro)\n      ultimately have \"fv (\\<sigma> x) \\<subseteq> {x} \\<union> fv_eqs xs\" using f2 by auto\n      then have \"fv_eqs (sapply_eqs \\<sigma> ((Var x, b) # xs)) \\<subseteq> {x} \\<union> fv_eqs xs \\<union> fv_eqs xs\" using f3 f1 Var by auto\n      then show ?thesis using f0 Var \\<open>b = Var x\\<close> by auto\n    next\n      case False\n      then have x_notfree: \"x \\<notin> fv b\" using Var \\<open>b \\<noteq> Var x\\<close> unify_notin by auto\n      have 4: \"fv_eqs ((Var x, b) # xs) = {x} \\<union> fv_eqs xs \\<union> fv b\" by auto\n      have 1: \"scomp_opt (unify (sapply_eqs (Var(x := b)) xs)) (Var (x := b)) = Some \\<sigma>\" using Var \\<open>b \\<noteq> Var x\\<close> \\<open>x \\<notin> fv b\\<close> by auto\n      then obtain \\<sigma>\\<^sub>2 where 2: \"unify (sapply_eqs (Var(x := b)) xs) = Some \\<sigma>\\<^sub>2\" using scomp_some by blast\n      then have IH1: \"fv_eqs (sapply_eqs \\<sigma>\\<^sub>2 (sapply_eqs (Var(x := b)) xs)) \\<subseteq> fv_eqs (sapply_eqs (Var(x := b)) xs)\"\n        and IH2: \"sdom \\<sigma>\\<^sub>2 \\<subseteq> fv_eqs (sapply_eqs (Var(x := b)) xs)\"\n        and IH3: \"svran \\<sigma>\\<^sub>2 \\<subseteq> fv_eqs (sapply_eqs (Var(x := b)) xs)\" using Var \\<open>b \\<noteq> Var x\\<close> \\<open>x \\<notin> fv b\\<close> by auto\n      then have a1: \"fv_eqs (sapply_eqs \\<sigma>\\<^sub>2 (sapply_eqs (Var(x := b)) xs)) \\<subseteq> fv b \\<union> fv_eqs xs\"\n        and a2: \"sdom \\<sigma>\\<^sub>2 \\<subseteq> fv b \\<union> fv_eqs xs\" \n        and a3: \"svran \\<sigma>\\<^sub>2 \\<subseteq> fv b \\<union> fv_eqs xs\" using fv_sapply_var False by (metis (mono_tags, lifting) Un_subset_iff fv.simps(1) singletonI sup.absorb_iff2)+\n      let ?\\<sigma>' = \"\\<sigma>\\<^sub>2 \\<circ>s (Var (x := b))\"\n      have 3: \"\\<sigma> = ?\\<sigma>'\" using 1 2 by simp\n      have f1: \"sdom \\<sigma> \\<subseteq> sdom \\<sigma>\\<^sub>2 \\<union> {x}\" using \\<open>\\<sigma> = \\<sigma>\\<^sub>2 \\<circ>s Var(x := b)\\<close> by fastforce\n      have f2: \"svran \\<sigma> \\<subseteq> svran \\<sigma>\\<^sub>2 \\<union> fv b\" by (metis False \\<open>\\<sigma> = \\<sigma>\\<^sub>2 \\<circ>s Var(x := b)\\<close> fv.simps(1) singletonI svran_scomp svran_single_non_trivial)\n      have \"fv_eqs (sapply_eqs \\<sigma> ((Var x, b) # xs)) = fv_eqs (sapply_eqs ?\\<sigma>' ((Var x, b) # xs))\" using 3 by simp\n      also have \"... = fv (\\<sigma>\\<^sub>2 \\<cdot> b) \\<union> fv_eqs (sapply_eqs \\<sigma>\\<^sub>2 (sapply_eqs (Var (x := b)) xs))\" by (auto simp add: x_notfree sapply_notin_fv)\n      moreover have \"fv (\\<sigma>\\<^sub>2 \\<cdot> b) \\<subseteq> fv b - sdom \\<sigma>\\<^sub>2 \\<union> svran \\<sigma>\\<^sub>2\" using fv_sapply_sdom_svran by fastforce\n      ultimately have \"fv_eqs (sapply_eqs \\<sigma> ((Var x, b) # xs)) \\<subseteq> fv_eqs ((Var x, b) # xs)\" using 4 a1 a3 fv_sapply_sdom_svran by auto\n      moreover have \"sdom \\<sigma> \\<subseteq> fv_eqs ((Var x, b) # xs)\" \" svran \\<sigma> \\<subseteq> fv_eqs ((Var x, b) # xs)\" using a2 a3 f1 f2 by auto\n      ultimately show ?thesis by blast\n    qed\n  next \n  case (flip v va x xs)\n  assume \"unify ((Fun v va, Var x) # xs) = Some \\<sigma>\"\n  then have \"unify ((Var x, Fun v va) # xs) = Some \\<sigma>\" by simp \n  moreover have \"fv_eqs (sapply_eqs \\<sigma> ((Fun v va, Var x) # xs)) = fv_eqs (sapply_eqs \\<sigma> ((Var x, Fun v va) # xs))\" by (auto) \n  moreover have \"fv_eqs ((Fun v va, Var x) # xs) = fv_eqs ((Var x, Fun v va) # xs)\" by auto\n  ultimately show ?case using flip by auto\nnext\n  case (Fun f l1 g l2 xs)\n  assume \"unify ((Fun f l1, Fun g l2) # xs) = Some \\<sigma>\" \n  then have \"f = g\" \"length l1 = length l2\" \"unify (xs @ zip l1 l2) = Some \\<sigma>\" using ex_unifier_fun unify_complete \n    by (metis option.distinct(1) unify.simps(4))+\n  moreover have \"fv_eqs (sapply_eqs \\<sigma> ((Fun f l1, Fun g l2) # xs)) = fv_eqs (sapply_eqs \\<sigma> (xs @ zip l1 l2))\" using fv_eqs_zip[OF \\<open>length l1 = length l2\\<close>] fv_sapply_eqs fv_sapply_eq\n    by (metis fv.simps(2) fv_eq.simps fv_eqs_cons fv_eqs_subst_eqs sapply_eqs.simps)\n  moreover have \"fv_eqs ((Fun f l1, Fun g l2) # xs) = fv_eqs (xs @ zip l1 l2)\" using fv_eqs_zip[OF \\<open>length l1 = length l2\\<close>] by simp\n  ultimately show ?case using Fun by auto\nqed\n\n\nlemma 3:\n  fixes \\<sigma> :: \"('f, 'v) subst\" \n    and l :: \"('f, 'v) equations\"\n  assumes 1: \"unify l = Some \\<sigma>\"\n  shows subst_subs: \"fv_eqs (sapply_eqs \\<sigma> l) \\<subseteq> fv_eqs l\"\n    and sdom_fv: \"sdom \\<sigma> \\<subseteq> fv_eqs l\"\n    and svran_fv: \"svran \\<sigma> \\<subseteq> fv_eqs l\"\n    and sdom_svran_disj: \"sdom \\<sigma> \\<inter> svran \\<sigma> = {}\"\nproof -\n  show \"fv_eqs (sapply_eqs \\<sigma> l) \\<subseteq> fv_eqs l\" \"sdom \\<sigma> \\<subseteq> fv_eqs l\" \"svran \\<sigma> \\<subseteq> fv_eqs l\" using three_one[OF assms] by auto\nnext\n  show \"sdom \\<sigma> \\<inter> svran \\<sigma> = {}\"\n  using assms proof (induction l arbitrary: \\<sigma> rule: unify.induct)\n    case 1\n    then have \"\\<sigma> = Var\" using assms by simp\n    then show \"sdom \\<sigma> \\<inter> svran \\<sigma> = {}\" by simp\n  next\n    case (2 x b xs)print_cases\n    then show ?case\n    proof (cases \"b = Var x\")\n      case True\n      then have \"unify xs = Some \\<sigma>\" using 2 by simp\n      then show ?thesis using 2 \\<open>b = Var x\\<close> by simp\n    next\n      case False\n      then have \"x \\<notin> fv b\" using 2 \\<open>b \\<noteq> Var x\\<close> unify_notin by auto\n      obtain \\<sigma>\\<^sub>2 where 3: \"unify (sapply_eqs (Var(x := b)) xs) = Some \\<sigma>\\<^sub>2\" using \"2.prems\" scomp_some False \\<open>x \\<notin> fv b\\<close> by fastforce\n      then have 4: \"\\<sigma> = \\<sigma>\\<^sub>2 \\<circ>s (Var (x := b))\" using 2 False \\<open>x \\<notin> fv b\\<close> by (simp add: \\<open>\\<And>\\<sigma>. \\<lbrakk>b = Var x; unify xs = Some \\<sigma>\\<rbrakk> \\<Longrightarrow> sdom \\<sigma> \\<inter> svran \\<sigma> = {}\\<close>)\n      then have \"sdom \\<sigma>\\<^sub>2 \\<inter> svran \\<sigma>\\<^sub>2 = {}\" using \"2.IH\" False \\<open>x \\<notin> fv b\\<close> 3 by simp\n      have \"svran \\<sigma>\\<^sub>2 \\<subseteq> fv_eqs (sapply_eqs (Var (x := b)) ((Var x, b) # xs))\" using three_one[of \"sapply_eqs (Var(x := b)) xs\" \"\\<sigma>\\<^sub>2\"] 3 by auto\n      moreover have \"x \\<notin> fv_eqs (sapply_eqs (Var (x := b)) ((Var x, b) # xs))\" by (metis Diff_iff False UnE \\<open>x \\<notin> fv b\\<close> fv_sapply_eqs_sdom_svran sdom_single_non_trivial singletonI svran_single_non_trivial)\n      ultimately have \"x \\<notin> svran \\<sigma>\\<^sub>2\" by blast\n      show ?thesis\n      proof (rule Int_emptyI)\n        fix y\n        assume 6: \"y \\<in> sdom \\<sigma>\" \"y \\<in> svran \\<sigma>\"\n        have \"sdom \\<sigma> \\<subseteq> sdom \\<sigma>\\<^sub>2 \\<union> sdom (Var (x := b))\" using 4 by (auto simp add: sdom_def)\n        then have \"y \\<in> sdom \\<sigma>\\<^sub>2 \\<union> {x}\" using 6 \\<open>b \\<noteq> Var x\\<close> sdom_single_non_trivial by auto\n        have \"svran \\<sigma> \\<subseteq> svran \\<sigma>\\<^sub>2 \\<union> svran (Var (x := b))\" using 4 by (simp add: svran_scomp)\n        then have \"y \\<in> svran \\<sigma>\\<^sub>2 \\<union> fv b\" using 6 \\<open>b \\<noteq> Var x\\<close> svran_single_non_trivial by auto\n        then have \"y \\<noteq> x\" using \\<open>x \\<notin> svran \\<sigma>\\<^sub>2\\<close> \\<open>x \\<notin> fv b\\<close> by blast\n        then have \"y \\<in> sdom \\<sigma>\\<^sub>2\" using \\<open>y \\<in> sdom \\<sigma>\\<^sub>2 \\<union> {x}\\<close> by blast\n        obtain z where 7: \"z \\<in> sdom \\<sigma> \\<and> y \\<in> fv(\\<sigma> z)\" using 6 by auto \n        then show \"False\" \n        proof (cases \"z = x\")\n          case True\n          then have \"\\<sigma> z = \\<sigma>\\<^sub>2 \\<cdot> t\" using 4 \\<open>sdom \\<sigma>\\<^sub>2 \\<inter> svran \\<sigma>\\<^sub>2 = {}\\<close> \\<open>y \\<in> sdom \\<sigma>\\<^sub>2\\<close> \\<open>z \\<in> sdom \\<sigma> \\<and> y \\<in> fv (\\<sigma> z)\\<close> fv_sapply_sdom_svran by fastforce \n          then have \"y \\<in> fv(\\<sigma>\\<^sub>2 \\<cdot> t)\" using 7 by auto\n          then have \"y \\<in> fv t - sdom \\<sigma>\\<^sub>2 \\<union> svran \\<sigma>\\<^sub>2\" using fv_sapply_sdom_svran by fastforce\n          then have \"y \\<in> svran \\<sigma>\\<^sub>2\" using \\<open>y \\<in> sdom \\<sigma>\\<^sub>2\\<close> by blast\n          then show ?thesis using \\<open>y \\<in> sdom \\<sigma>\\<^sub>2\\<close> \\<open>sdom \\<sigma>\\<^sub>2 \\<inter> svran \\<sigma>\\<^sub>2 = {}\\<close> by blast\n        next\n          case False\n          then have \"\\<sigma> z = \\<sigma>\\<^sub>2 z\" using 4 by simp\n          then have \"z \\<in> sdom \\<sigma>\\<^sub>2\" using 7 by fastforce\n          then have \"y \\<in> svran \\<sigma>\\<^sub>2\" using 7  \\<open>\\<sigma> z = \\<sigma>\\<^sub>2 z\\<close> by auto\n          then show ?thesis using \\<open>y \\<in> sdom \\<sigma>\\<^sub>2\\<close> \\<open>sdom \\<sigma>\\<^sub>2 \\<inter> svran \\<sigma>\\<^sub>2 = {}\\<close> by blast\n        qed\n      qed\n    qed\n  next\n    case (3 v va x xs) print_cases\n    then have \"unify ((Var x, Fun v va) # xs) = Some \\<sigma>\" by simp\n    then show ?case using \"3.IH\" by simp \n  next\n    case (4 f l1 g l2 xs) print_cases\n    then have \"unifiess \\<sigma> ((Fun f l1, Fun g l2) # xs)\" by (simp add: unify_return)\n    then have 5: \"g = f\" \"length l1 = length l2\" using ex_unifier_fun by fastforce+\n    then have \"unify (xs @ zip l1 l2) = Some \\<sigma>\" using \"4.prems\" by simp \n    then show ?case using \"4.IH\" 5 assms by auto\n  qed\nqed\n\n\n(****************************** ( 4A ) ***************************)\ninductive wf_term :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) term \\<Rightarrow> bool\"\n  for arity :: \"'f \\<Rightarrow> nat\"\n  where\n  wf_term_intro_var:\"wf_term arity (Var _)\"\n| wf_term_intro_fun:\"(length l = arity f) \\<Longrightarrow> \\<forall> x \\<in> set l. wf_term arity x \\<Longrightarrow> wf_term arity (Fun f l)\"\n\ninductive wf_subst :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> bool\"\n  for arity :: \"'f \\<Rightarrow> nat\" where\n  \"\\<lbrakk> \\<forall>x. wf_term arity (\\<sigma> x) \\<rbrakk> \\<Longrightarrow> wf_subst arity \\<sigma>\"\n\nlemma wf_subst_var: \"\\<lbrakk> wf_term arity t; x \\<notin> fv t \\<rbrakk> \\<Longrightarrow> wf_subst arity (Var (x := t))\"\n  by (auto simp add: wf_subst.simps wf_term.intros)\n\ninductive wf_eq :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> bool\" where\n  \"\\<lbrakk> wf_term arity a; wf_term arity b \\<rbrakk> \\<Longrightarrow> wf_eq arity (a,b)\"\n\nlemma wf_eqE: \"wf_eq arity (a, b) \\<Longrightarrow> (wf_term arity a \\<Longrightarrow> wf_term arity b \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  using wf_eq.cases by auto\n\ninductive wf_eqs :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"\\<lbrakk> \\<forall>x \\<in> set l. wf_eq arity x \\<rbrakk> \\<Longrightarrow> wf_eqs arity l\" \n\n\n(********************************** ( 4B )  **********************************)\nlemma eq_comm: \"Var y = x \\<Longrightarrow> wf_term arity x\"\n  by (auto simp add: wf_term.intros)\n\nlemma eq_comm1: \"x = y \\<Longrightarrow> wf_term arity x \\<longleftrightarrow> wf_term arity y\"\n  by auto\n\nlemma wf_term_sapply: \"\\<lbrakk> wf_term arity t; wf_subst arity \\<sigma> \\<rbrakk> \\<Longrightarrow> wf_term arity (\\<sigma> \\<cdot> t)\"\nproof (induction t)\n  case (Var x)\n  then show ?case\n    by(auto simp add:wf_subst.simps intro: wf_term.intros)\nnext\n  case (Fun s ts)\n  let ?t = \"Fun s ts\"\n  have x:\"\\<sigma> \\<cdot> ?t = Fun s (map (sapply \\<sigma>) ts)\" (is \"_ = Fun _ ?elts\") by(simp)\n  have \"wf_term arity (Fun s ?elts)\"\n  proof(rule wf_term_intro_fun)\n    have \"length (map (op \\<cdot> \\<sigma>) ts) = length ts\" by simp\n    also have \"... = arity s\" \n      using `wf_term arity ?t`\n      by(cases rule:wf_term.cases)\n    finally show \"length (map (op \\<cdot> \\<sigma>) ts) = arity s \".\n  next\n    have \"\\<And>x. x\\<in>set (map (op \\<cdot> \\<sigma>) ts) \\<Longrightarrow> wf_term arity x \"\n    proof -\n      fix x\n      assume \"x\\<in>set (map (op \\<cdot> \\<sigma>) ts)\"\n      then obtain z where \"z\\<in>set ts\" and \"x = \\<sigma> \\<cdot> z\" by auto\n      have \"wf_term arity z\"\n        using `wf_term arity ?t`\n        by(cases rule:wf_term.cases)(auto simp add:`z\\<in>set ts`)\n      from `z\\<in> set ts` and `wf_term arity z` and `wf_subst arity \\<sigma>` have \"wf_term arity (\\<sigma> \\<cdot> z)\" by(rule Fun.IH)\n      then show \"wf_term arity x\" by(simp add:`x = \\<sigma>\\<cdot>z`)\n    qed\n    then show \"\\<forall>x\\<in>set (map (op \\<cdot> \\<sigma>) ts). wf_term arity x\" by blast\n  qed\n  then show \"wf_term arity (\\<sigma> \\<cdot> ?t)\" by(simp add:x)\nqed\n\nlemma wf_eq_sapply_eq: \"\\<lbrakk> wf_eq arity eq; wf_subst arity \\<sigma> \\<rbrakk> \\<Longrightarrow> wf_eq arity (sapply_eq \\<sigma> eq)\"\n  by(cases eq; auto simp add:wf_term_sapply elim!:wf_eqE intro!:wf_eq.intros)\n\nlemma wf_eqs_sapply_eqs: \"\\<lbrakk> wf_eqs arity eqs; wf_subst arity \\<sigma> \\<rbrakk> \\<Longrightarrow> wf_eqs arity (sapply_eqs \\<sigma> eqs)\"\n  apply (induction eqs)\n  by (simp_all add: wf_eq_sapply_eq wf_eqs.simps)\n\nlemma wf_subst_scomp: \"\\<lbrakk> wf_subst arity \\<sigma>; wf_subst arity \\<tau> \\<rbrakk> \\<Longrightarrow> wf_subst arity (\\<sigma> \\<circ>s \\<tau>)\"\n  by (simp add: wf_subst.simps wf_term_sapply)\n\n\nlemma wf_subst_unify: \"\\<lbrakk> unify l = Some \\<sigma>; wf_eqs arity l \\<rbrakk> \\<Longrightarrow> wf_subst arity \\<sigma>\"\nproof (induction l arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by (auto intro: wf_term.intros wf_subst.intros)\nnext\ncase (2 x b xs)\n  then show ?case\n  proof (cases \"b = Var x\")\n    case True\n    then have \"unify xs = Some \\<sigma>\" using 2 by simp\n    moreover have \"wf_eqs arity xs\" using 2 by (simp add: wf_eqs.simps)\n    ultimately show ?thesis using \\<open>b = Var x\\<close> 2 by simp\n  next\n    case False\n    then show ?thesis \n    proof (cases \"x \\<in> fv b\")\n      case True\n      then have \"unify ((Var x, b) # xs) = None\" using \\<open>b \\<noteq> Var x\\<close> by simp\n      moreover have \"unify ((Var x, b) # xs) = Some \\<sigma>\" using 2 by simp\n      ultimately have False by simp\n      then show ?thesis by simp\n    next\n      case False\n      let ?term = \"sapply_eqs (Var(x := b)) xs\"\n      have \"unify ((Var x, b) # xs) = scomp_opt (unify ?term) (Var (x := b))\" using \\<open>x \\<notin> fv b\\<close> \\<open>b \\<noteq> Var x\\<close> by simp\n      then have 3: \"scomp_opt (unify ?term) (Var (x := b)) = Some \\<sigma>\" using 2 by simp \n      then have \"\\<exists>\\<tau>. unify ?term = Some \\<tau>\" by (auto simp add: scomp_some)\n      then obtain \\<sigma>\\<^sub>2 where 4: \"unify ?term = Some \\<sigma>\\<^sub>2\" by blast\n      have \"wf_term arity b\" using 2 by (simp add: wf_term.intros wf_eqs.simps wf_eq.simps)\n      then have \"wf_subst arity (Var (x := b))\" using \\<open>x \\<notin> fv b\\<close> by (simp add: wf_subst_var)\n      moreover have \"wf_eqs arity xs\" using 2 by (simp add: wf_eqs.simps)\n      ultimately have \"wf_eqs arity ?term\" using wf_eqs_sapply_eqs by simp \n      then show ?thesis using \\<open>b \\<noteq> Var x\\<close> \\<open>x \\<notin> fv b\\<close> 2 4 \\<open>wf_subst arity (Var(x := b))\\<close> wf_subst_scomp by fastforce\n    qed\n  qed\nnext\n  case (3 v va x xs)\n  have \"wf_eqs arity ((Var x, Fun v va) # xs)\" using 3 wf_eqs.intros wf_eq.intros wf_term.intros by (metis insert_iff list.set(2) wf_eqE wf_eqs.cases)\n  moreover have \"unify ((Var x, Fun v va) # xs) = Some \\<sigma>\" using 3 by simp\n  ultimately show ?case using 3 by simp\nnext\n  case (4 f l1 g l2 xs)\n  then have 5: \"f = g\" \"length l1 = length l2\" \"unify (xs @ zip l1 l2) = Some \\<sigma>\" by (simp_all split: if_splits)\n  have \"wf_eq arity (Fun f l1, Fun g l2)\" using 4 by (simp add: wf_eqs.simps)\n  then have \"\\<forall>x\\<in>set l1. wf_term arity x\" \"\\<forall>x\\<in>set l2. wf_term arity x\" using wf_term.simps by (metis term.distinct(1) term.inject(2) wf_eqE)+\n  then have \"wf_eqs arity (zip l1 l2)\" using wf_eqs.intros by (simp add: \\<open>\\<And>l arity. \\<forall>x\\<in>set l. wf_eq arity x \\<Longrightarrow> wf_eqs arity l\\<close> set_zip set_zip_leftD set_zip_rightD wf_eq.simps)\n  moreover have \"wf_eqs arity (xs)\" using 4 by (simp add: wf_eqs.simps)\n  ultimately have \"wf_eqs arity (xs @ zip l1 l2)\" by (metis Un_iff set_append wf_eqs.simps)\n  then show ?case using 4 5 by simp\nqed\nend\n", "meta": {"author": "symphorien", "repo": "camr-project", "sha": "303a4f66f91c5ad36f5907b684f8969799a3e2e5", "save_path": "github-repos/isabelle/symphorien-camr-project", "path": "github-repos/isabelle/symphorien-camr-project/camr-project-303a4f66f91c5ad36f5907b684f8969799a3e2e5/Unification.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178895092414, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7740995534704873}}
{"text": "theory exercise_2_2\n  imports Main\nbegin\n(*set add function*)\nfun add::\"nat\\<Rightarrow>nat\\<Rightarrow>nat\"\n  where\n\"add m 0  =m\"|\n\"add m  (Suc n)=Suc(add m n)\"\n\n(*set association*)\ntheorem add_assoc:\"add x (add y z) =add (add x y) z\"\n  apply(induction z)\n  apply(auto)\n  done\n(*set add 0 x*)\nlemma add_zero:\"add 0 x=x\"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma suc_add:\"Suc(add y x) = add (Suc y)  x\"\n  apply(induction x)\n  apply(auto)\n  done\ntheorem add_com:\"add x y=add y x\"\n  apply(induction y)(*the different with using x or y as value ? ?*)\n  apply(auto)\n  apply(simp add:add_zero)\n  apply(simp add:suc_add)\n  done\n\n(*fun double*)\nfun double::\"nat\\<Rightarrow>nat\" \n  where\n\"double 0=0\"|\n\"double (Suc m) =2+(double m)\"(*Why here is add ,not mutl? ?*)\ntheorem double_add:\"double m=add m m\"\n  apply(induction m)\n   apply(auto)\n  apply(simp add:add_com)\n  done\nend", "meta": {"author": "Strongman86", "repo": "Isabelle_Learning", "sha": "721bc6b04735f03a3bc1788c5970f681d78f1b47", "save_path": "github-repos/isabelle/Strongman86-Isabelle_Learning", "path": "github-repos/isabelle/Strongman86-Isabelle_Learning/Isabelle_Learning-721bc6b04735f03a3bc1788c5970f681d78f1b47/Isabelle_Learning/formal/Concrete-Semantics/exercises/2/exercise_2_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8267117898012104, "lm_q1q2_score": 0.7740378499264233}}
{"text": "(*  Title:       HOL/Library/Quadratic_Discriminant.thy\n    Author:      Tim Makarios <tjm1983 at gmail.com>, 2012\n\nOriginally from the AFP entry Tarskis_Geometry\n*)\n\nsection \"Roots of real quadratics\"\n\ntheory Quadratic_Discriminant\nimports Complex_Main\nbegin\n\ndefinition discrim :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real\"\n  where \"discrim a b c \\<equiv> b\\<^sup>2 - 4 * a * c\"\n\nlemma complete_square:\n  fixes a b c x :: \"real\"\n  assumes \"a \\<noteq> 0\"\n  shows \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> (2 * a * x + b)\\<^sup>2 = discrim a b c\"\nproof -\n  have \"4 * a\\<^sup>2 * x\\<^sup>2 + 4 * a * b * x + 4 * a * c = 4 * a * (a * x\\<^sup>2 + b * x + c)\"\n    by (simp add: algebra_simps power2_eq_square)\n  with \\<open>a \\<noteq> 0\\<close>\n  have \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> 4 * a\\<^sup>2 * x\\<^sup>2 + 4 * a * b * x + 4 * a * c = 0\"\n    by simp\n  then show \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> (2 * a * x + b)\\<^sup>2 = discrim a b c\"\n    by (simp add: discrim_def power2_eq_square algebra_simps)\nqed\n\nlemma discriminant_negative:\n  fixes a b c x :: real\n  assumes \"a \\<noteq> 0\"\n    and \"discrim a b c < 0\"\n  shows \"a * x\\<^sup>2 + b * x + c \\<noteq> 0\"\nproof -\n  have \"(2 * a * x + b)\\<^sup>2 \\<ge> 0\"\n    by simp\n  with \\<open>discrim a b c < 0\\<close> have \"(2 * a * x + b)\\<^sup>2 \\<noteq> discrim a b c\"\n    by arith\n  with complete_square and \\<open>a \\<noteq> 0\\<close> show \"a * x\\<^sup>2 + b * x + c \\<noteq> 0\"\n    by simp\nqed\n\nlemma plus_or_minus_sqrt:\n  fixes x y :: real\n  assumes \"y \\<ge> 0\"\n  shows \"x\\<^sup>2 = y \\<longleftrightarrow> x = sqrt y \\<or> x = - sqrt y\"\nproof\n  assume \"x\\<^sup>2 = y\"\n  then have \"sqrt (x\\<^sup>2) = sqrt y\"\n    by simp\n  then have \"sqrt y = \\<bar>x\\<bar>\"\n    by simp\n  then show \"x = sqrt y \\<or> x = - sqrt y\"\n    by auto\nnext\n  assume \"x = sqrt y \\<or> x = - sqrt y\"\n  then have \"x\\<^sup>2 = (sqrt y)\\<^sup>2 \\<or> x\\<^sup>2 = (- sqrt y)\\<^sup>2\"\n    by auto\n  with \\<open>y \\<ge> 0\\<close> show \"x\\<^sup>2 = y\"\n    by simp\nqed\n\nlemma divide_non_zero:\n  fixes x y z :: real\n  assumes \"x \\<noteq> 0\"\n  shows \"x * y = z \\<longleftrightarrow> y = z / x\"\nproof\n  show \"y = z / x\" if \"x * y = z\"\n    using \\<open>x \\<noteq> 0\\<close> that by (simp add: field_simps)\n  show \"x * y = z\" if \"y = z / x\"\n    using \\<open>x \\<noteq> 0\\<close> that by simp\nqed\n\nlemma discriminant_nonneg:\n  fixes a b c x :: real\n  assumes \"a \\<noteq> 0\"\n    and \"discrim a b c \\<ge> 0\"\n  shows \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow>\n    x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n    x = (-b - sqrt (discrim a b c)) / (2 * a)\"\nproof -\n  from complete_square and plus_or_minus_sqrt and assms\n  have \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow>\n    (2 * a) * x + b = sqrt (discrim a b c) \\<or>\n    (2 * a) * x + b = - sqrt (discrim a b c)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> (2 * a) * x = (-b + sqrt (discrim a b c)) \\<or>\n    (2 * a) * x = (-b - sqrt (discrim a b c))\"\n    by auto\n  also from \\<open>a \\<noteq> 0\\<close> and divide_non_zero [of \"2 * a\" x]\n  have \"\\<dots> \\<longleftrightarrow> x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n    x = (-b - sqrt (discrim a b c)) / (2 * a)\"\n    by simp\n  finally show \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow>\n    x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n    x = (-b - sqrt (discrim a b c)) / (2 * a)\" .\nqed\n\nlemma discriminant_zero:\n  fixes a b c x :: real\n  assumes \"a \\<noteq> 0\"\n    and \"discrim a b c = 0\"\n  shows \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow> x = -b / (2 * a)\"\n  by (simp add: discriminant_nonneg assms)\n\ntheorem discriminant_iff:\n  fixes a b c x :: real\n  assumes \"a \\<noteq> 0\"\n  shows \"a * x\\<^sup>2 + b * x + c = 0 \\<longleftrightarrow>\n    discrim a b c \\<ge> 0 \\<and>\n    (x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n     x = (-b - sqrt (discrim a b c)) / (2 * a))\"\nproof\n  assume \"a * x\\<^sup>2 + b * x + c = 0\"\n  with discriminant_negative and \\<open>a \\<noteq> 0\\<close> have \"\\<not>(discrim a b c < 0)\"\n    by auto\n  then have \"discrim a b c \\<ge> 0\"\n    by simp\n  with discriminant_nonneg and \\<open>a * x\\<^sup>2 + b * x + c = 0\\<close> and \\<open>a \\<noteq> 0\\<close>\n  have \"x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n      x = (-b - sqrt (discrim a b c)) / (2 * a)\"\n    by simp\n  with \\<open>discrim a b c \\<ge> 0\\<close>\n  show \"discrim a b c \\<ge> 0 \\<and>\n    (x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n     x = (-b - sqrt (discrim a b c)) / (2 * a))\" ..\nnext\n  assume \"discrim a b c \\<ge> 0 \\<and>\n    (x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n     x = (-b - sqrt (discrim a b c)) / (2 * a))\"\n  then have \"discrim a b c \\<ge> 0\" and\n    \"x = (-b + sqrt (discrim a b c)) / (2 * a) \\<or>\n     x = (-b - sqrt (discrim a b c)) / (2 * a)\"\n    by simp_all\n  with discriminant_nonneg and \\<open>a \\<noteq> 0\\<close> show \"a * x\\<^sup>2 + b * x + c = 0\"\n    by simp\nqed\n\nlemma discriminant_nonneg_ex:\n  fixes a b c :: real\n  assumes \"a \\<noteq> 0\"\n    and \"discrim a b c \\<ge> 0\"\n  shows \"\\<exists> x. a * x\\<^sup>2 + b * x + c = 0\"\n  by (auto simp: discriminant_nonneg assms)\n\nlemma discriminant_pos_ex:\n  fixes a b c :: real\n  assumes \"a \\<noteq> 0\"\n    and \"discrim a b c > 0\"\n  shows \"\\<exists>x y. x \\<noteq> y \\<and> a * x\\<^sup>2 + b * x + c = 0 \\<and> a * y\\<^sup>2 + b * y + c = 0\"\nproof -\n  let ?x = \"(-b + sqrt (discrim a b c)) / (2 * a)\"\n  let ?y = \"(-b - sqrt (discrim a b c)) / (2 * a)\"\n  from \\<open>discrim a b c > 0\\<close> have \"sqrt (discrim a b c) \\<noteq> 0\"\n    by simp\n  then have \"sqrt (discrim a b c) \\<noteq> - sqrt (discrim a b c)\"\n    by arith\n  with \\<open>a \\<noteq> 0\\<close> have \"?x \\<noteq> ?y\"\n    by simp\n  moreover from assms have \"a * ?x\\<^sup>2 + b * ?x + c = 0\" and \"a * ?y\\<^sup>2 + b * ?y + c = 0\"\n    using discriminant_nonneg [of a b c ?x]\n      and discriminant_nonneg [of a b c ?y]\n    by simp_all\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma discriminant_pos_distinct:\n  fixes a b c x :: real\n  assumes \"a \\<noteq> 0\"\n    and \"discrim a b c > 0\"\n  shows \"\\<exists> y. x \\<noteq> y \\<and> a * y\\<^sup>2 + b * y + c = 0\"\nproof -\n  from discriminant_pos_ex and \\<open>a \\<noteq> 0\\<close> and \\<open>discrim a b c > 0\\<close>\n  obtain w and z where \"w \\<noteq> z\"\n    and \"a * w\\<^sup>2 + b * w + c = 0\" and \"a * z\\<^sup>2 + b * z + c = 0\"\n    by blast\n  show \"\\<exists>y. x \\<noteq> y \\<and> a * y\\<^sup>2 + b * y + c = 0\"\n  proof (cases \"x = w\")\n    case True\n    with \\<open>w \\<noteq> z\\<close> have \"x \\<noteq> z\"\n      by simp\n    with \\<open>a * z\\<^sup>2 + b * z + c = 0\\<close> show ?thesis\n      by auto\n  next\n    case False\n    with \\<open>a * w\\<^sup>2 + b * w + c = 0\\<close> show ?thesis\n      by auto\n  qed\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/Quadratic_Discriminant.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320035, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7739535414274957}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\nsubsection \"Arithmetic Expressions\"\n\ntheory AExp imports MainRLT begin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw\\<open>\\snip{AExpaexpdef}{2}{1}{%\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\ntext_raw\\<open>\\snip{AExpavaldef}{1}{2}{%\\<close>\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>\\noindent\n  We can now write a series of updates to the function \\<open>\\<lambda>x. 0\\<close> compactly:\n\\<close>\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext\\<open>Note that this \\<open><\\<dots>>\\<close> syntax works for any function space\n\\<open>\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\\<close> where \\<open>\\<tau>\\<^sub>2\\<close> has a \\<open>0\\<close>.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Evaluate constant subsexpressions:\\<close>\n\ntext_raw\\<open>\\snip{AExpasimpconstdef}{0}{2}{%\\<close>\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext\\<open>Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors:\\<close>\n\ntext_raw\\<open>\\snip{AExpplusdef}{0}{2}{%\\<close>\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw\\<open>\\snip{AExpasimpdef}{2}{0}{%\\<close>\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntext\\<open>Note that in \\<^const>\\<open>asimp_const\\<close> the optimized constructor was\ninlined. Making it a separate function \\<^const>\\<open>plus\\<close> improves modularity of\nthe code and the proofs.\\<close>\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/IMP/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.8723473730188543, "lm_q1q2_score": 0.7739505914560073}}
{"text": "theory Eplus\n  imports Main \"$HIPSTER_HOME/IsaHipster\"\n    \"types/ENat\"\nbegin\nsetup Tactic_Data.set_coinduct_sledgehammer \nsetup Misc_Data.set_noisy\n\nprimcorec eplus :: \"ENat \\<Rightarrow> ENat \\<Rightarrow> ENat\" where\n\"eplus m n = (if is_zero m then n else ESuc (eplus (epred m) n))\"\n\n(*cohipster eplus*)\n(* Discovers and proves the following in just under 2 minutes *)\n\n(* identity *)\nlemma lemma_a [thy_expl]: \"eplus x EZ = x\"\n by (coinduction arbitrary: x rule: ENat.ENat.coinduct_strong)\n    simp\n\nlemma lemma_aa [thy_expl]: \"eplus EZ x = x\"\n by (coinduction arbitrary: x rule: ENat.ENat.coinduct_strong)\n    simp\n\nlemma lemma_ab [thy_expl]: \"eplus (ESuc x) y = eplus x (ESuc y)\"\n by (coinduction arbitrary: x y rule: ENat.ENat.coinduct_strong)\n    (metis ENat.discI(2) ENat.sel eplus.code)\n\nlemma lemma_ac [thy_expl]: \"ESuc (eplus x y) = eplus x (ESuc y)\"\n by (coinduction arbitrary: x y rule: ENat.ENat.coinduct_strong)\n    (metis ENat.distinct(1) ENat.sel eplus.code is_zero_def)\n\nlemma lemma_ad [thy_expl]: \"eplus x (ESuc EZ) = ESuc x\"\n by (coinduction arbitrary: x rule: ENat.ENat.coinduct_strong)\n    (metis lemma_a lemma_ac)\n\n(* associativity *)    \nlemma lemma_ae [thy_expl]: \"eplus (eplus x y) z = eplus x (eplus y z)\"\n by (coinduction arbitrary: x y z rule: ENat.ENat.coinduct_strong)\n    auto\n\nlemma lemma_af [thy_expl]: \"epred (eplus x (ESuc y)) = eplus x y\"\n by (coinduction arbitrary: x y rule: ENat.ENat.coinduct_strong)\n    auto\n\nlemma lemma_ag [thy_expl]: \"eplus y (eplus x z) = eplus x (eplus y z)\"\n by (coinduction arbitrary: x y z rule: ENat.ENat.coinduct_strong)\n    (smt eplus.code eplus.disc_iff(1) eplus.sel lemma_af)\n\nlemma lemma_ah [thy_expl]: \"eplus y (ESuc (ESuc x)) = eplus x (ESuc (ESuc y))\"\n by (coinduction arbitrary: x y rule: ENat.ENat.coinduct_strong)\n    (metis ENat.discI(2) eplus.disc_iff(2) lemma_ad lemma_af lemma_ag)\n\n(* commutativity *)    \nlemma lemma_ai [thy_expl]: \"eplus y x = eplus x y\"\n by (coinduction arbitrary: x y rule: ENat.ENat.coinduct_strong)\n    (metis lemma_a lemma_ag)\n\nlemma lemma_aj [thy_expl]: \"eplus y (ESuc x) = eplus x (ESuc y)\"\n by (coinduction arbitrary: x y rule: ENat.ENat.coinduct_strong)\n    (metis ENat.discI(2) eplus.disc_iff(2) lemma_a lemma_af lemma_ag)\nend", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/she/itp2018/Eplus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7739115132236316}}
{"text": "section \\<open>Digit functions\\<close>\n\ntheory Bits_Digits\n  imports Main\nbegin\n\ntext \\<open>We define the n-th bit of a number in base 2 representation \\<close>\ndefinition nth_bit :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" (infix \"\\<exclamdown>\" 100) where\n  \"nth_bit num k = (num div (2 ^ k)) mod 2\"\n\ntext \\<open>as well as the n-th digit of a number in an arbitrary base \\<close>\ndefinition nth_digit :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"nth_digit num k base = (num div (base ^ k)) mod base\"\n\ntext \\<open>In base 2, the two definitions coincide. \\<close>\nlemma nth_digit_base2_equiv:\"nth_bit a k = nth_digit a k (2::nat)\"\n  by (auto simp add:nth_bit_def nth_digit_def)\n\nlemma general_digit_base:\n  assumes \"t1 > t2\" and \"b>1\"\n  shows \"nth_digit (a * b^t1) t2 b = 0\" \nproof -\n  have 1: \"b^t1 div b^t2 = b^(t1-t2)\" using assms apply auto\n    by (metis Suc_lessD less_imp_le less_numeral_extra(3) power_diff)\n  have \"b^t2 dvd b^t1\" using `t1 > t2`\n    by (simp add: le_imp_power_dvd)\n  hence \"(a * b^t1) div b^t2 = a * b^(t1-t2)\" using div_mult_swap[of \"b^t2\" \"b^t1\" \"a\"] 1 by auto\n  thus ?thesis using nth_digit_def assms by auto\nqed\n\nlemma nth_bit_bounded: \"nth_bit a k \\<le> 1\"\n  by (auto simp add: nth_bit_def)\n\nlemma nth_digit_bounded: \"b>1 \\<Longrightarrow> nth_digit a k b \\<le> b-1\"\n  apply (auto simp add: nth_digit_def)\n  using less_Suc_eq_le by fastforce\n\nlemma obtain_smallest: \"P (n::nat) \\<Longrightarrow> \\<exists>k\\<le>n. P k \\<and> (\\<forall>a<k.\\<not>(P a))\"\n  by (metis ex_least_nat_le not_less_zero zero_le)\n\nsubsection \\<open>Simple properties and equivalences\\<close>\n\ntext \\<open>Reduce the @{term nth_digit} function to @{term nth_bit} if the base is a power of 2\\<close>\n\nlemma digit_gen_pow2_reduct:\n  \\<open>(nth_digit a t (2 ^ c)) \\<exclamdown> k = a \\<exclamdown> (c * t + k)\\<close> if \\<open>k < c\\<close>\nproof -\n  have moddiv: \"(x mod 2 ^ c) \\<exclamdown> k = x \\<exclamdown> k\" for x\n  proof-\n    define n where \\<open>n = c - k\\<close>\n    with \\<open>k < c\\<close> have c_nk: \\<open>c = n + k\\<close>\n      by simp\n    obtain a b where x_def: \"x = a * 2 ^ c + b\" and \"b < 2 ^ c\" \n      by (meson mod_div_decomp mod_less_divisor zero_less_numeral zero_less_power)\n    then have bk: \"(x mod 2 ^ c) \\<exclamdown> k = b \\<exclamdown> k\" by simp\n    from \\<open>b < 2 ^ c\\<close> have \\<open>x div 2 ^ k = a * 2 ^ (c - k) + b div 2 ^ k\\<close>\n      by (simp add: x_def c_nk power_add flip: mult.commute [of \\<open>2 ^ k\\<close>] mult.left_commute [of \\<open>2 ^ k\\<close>])\n    then have \"x \\<exclamdown> k = (a*2^(c-k) + b div 2^k) mod 2\" by (simp add: nth_bit_def)\n    then have \"x \\<exclamdown> k = b \\<exclamdown> k\" using nth_bit_def \\<open>k < c\\<close> by (simp add: mod2_eq_if)\n    then show ?thesis using nth_bit_def bk by linarith\n  qed\n  have \"a div ((2 ^ c) ^ t * 2 ^ k) = a div (2 ^ c) ^ t div 2 ^ k\" using div_mult2_eq by blast\n  moreover have \"a div (2 ^ c) ^ t mod 2 ^ c div 2 ^ k mod 2 = a div (2 ^ c) ^ t div 2 ^ k mod 2\"\n    using moddiv nth_bit_def by auto \n  ultimately show \"(nth_digit a t (2^c)) \\<exclamdown> k = a \\<exclamdown> (c*t+k)\"\n    using nth_digit_def nth_bit_def by (auto simp: power_add power_mult)\nqed\n\ntext \\<open>Show equivalence of numbers by equivalence of all their bits (digits)\\<close>\n\nlemma aux_even_pow2_factor: \"a > 0 \\<Longrightarrow> \\<exists>k b. ((a::nat) = (2^k) * b \\<and> odd b)\"\nproof(induction  a rule: full_nat_induct)\n  case (1 n)\n  then show ?case\n  proof (cases \"odd n\")\n    case True\n    then show ?thesis by (metis nat_power_eq_Suc_0_iff power_Suc power_Suc0_right power_commutes)\n  next\n    case False\n    have \"(\\<exists>t. n = 2 * t)\" using False by auto\n    then obtain t where n_def:\"n = 2 * t\" ..\n    then have \"t < n\" using \"1.prems\" by linarith\n    then have ih:\"\\<exists>r s. t = 2^r * s \\<and> odd s\" using 1 n_def by simp\n    then have \"\\<exists>r s. n = 2^(Suc r) * s\" using n_def by auto\n    then show ?thesis by (metis ih n_def power_commutes semiring_normalization_rules(18)\n                          semiring_normalization_rules(28))\n  qed\nqed\n\nlemma aux0_digit_wise_equiv:\"a > 0 \\<Longrightarrow> (\\<exists>k. nth_bit a k = 1)\"\nproof -\n  assume a_geq_0: \"a > 0\"\n  consider (odd) \"a mod 2 = 1\" | (even) \"a mod 2 = 0\" by force\n  then show ?thesis\n  proof(cases)\n    case odd\n    then show ?thesis by (metis div_by_1 nth_bit_def power_0)\n  next\n    case even\n    then have bk_def:\"\\<exists>k b. (a = (2^k) * b \\<and> odd b)\"\n      using aux_even_pow2_factor a_geq_0 by simp\n    then obtain b k where bk_cond:\"(a = (2^k) * b \\<and> odd b)\" by blast\n    then have \"b = a div (2^k)\" by simp\n    then have digi_b:\"nth_bit b 0 = 1\" using bk_def\n      using bk_cond nth_bit_def odd_iff_mod_2_eq_one by fastforce\n    then have \"nth_bit a k = (nth_bit b 0)\" using nth_bit_def bk_cond by force\n    then have \"nth_bit a k = 1\" using digi_b by simp\n    then show ?thesis by blast\n  qed\nqed\n\nlemma aux1_digit_wise_equiv:\"(\\<forall>k.(nth_bit a k = 0)) \\<longleftrightarrow> a = 0\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?Q\"\n  then show \"?P\" by (simp add: nth_bit_def)\nnext\n  {\n    assume a_neq_0:\"\\<not>?Q\"\n    then have \"a > 0\" by blast\n    then have \"\\<not>?P\" using aux0_digit_wise_equiv by (metis zero_neq_one)\n  }\n  thus \"?P \\<Longrightarrow> ?Q\" by blast\nqed\n\nlemma aux2_digit_wise_equiv: \"(\\<forall>r<k. nth_bit a r = 0) \\<longrightarrow> (a mod 2^k = 0)\"\nproof(induct k)\n  case 0\n  then show ?case\n    by (auto simp add: nth_bit_def)\nnext\n  case (Suc k)\n  then show ?case\n    by (auto simp add: nth_bit_def)\n       (metis dvd_imp_mod_0 dvd_mult_div_cancel dvd_refl even_iff_mod_2_eq_zero\n        lessI minus_mod_eq_div_mult minus_mod_eq_mult_div mult_dvd_mono)\nqed\n\nlemma digit_wise_equiv: \"(a = b) \\<longleftrightarrow> (\\<forall>k. nth_bit a k = nth_bit b k)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?P\"\n  then show \"?Q\" by simp\nnext\n  {\n    assume notP: \"\\<not>?P\"\n    have \"\\<not>(\\<forall>k. nth_bit a k = nth_bit b k)\" if ab: \"a<b\" for a b\n    proof-\n      define c::nat where \"c = b - a\"\n      have b: \"a+c=b\" by (auto simp add: c_def \"ab\" less_imp_le)\n      have  \"\\<exists>k.(nth_bit c k = 1)\" using nth_bit_def aux1_digit_wise_equiv\n        by (metis c_def not_less0 not_mod_2_eq_1_eq_0 that zero_less_diff)\n      then obtain k where k1:\"nth_bit c k = 1\" and k2:\"\\<forall>r < k. (nth_bit c r \\<noteq> 1)\"\n        by (auto dest: obtain_smallest)\n      then have cr0: \"\\<forall>r < k. (nth_bit c r = 0)\" by (simp add: nth_bit_def)\n      from aux2_digit_wise_equiv cr0 have \"c mod 2^k = 0\" by auto\n      then have \"a div 2 ^ k mod 2 \\<noteq> b div 2 ^ k mod 2\"\n        by auto (metis b div_plus_div_distrib_dvd_right even_add k1 nth_bit_def odd_iff_mod_2_eq_one)\n      then show ?thesis by (auto simp add: nth_bit_def)\n    qed\n    from this [of a b] this [of b a] notP have \"\\<forall>k. nth_bit a k = nth_bit b k \\<Longrightarrow> a = b\"\n      using linorder_neqE_nat by auto\n  }\n  then show \"?Q ==> ?P\" by auto\nqed\n\ntext \\<open>Represent natural numbers in their binary expansion\\<close>\n\nlemma aux3_digit_sum_repr:\n  assumes \"b < 2^r\"\n  shows \"(a*2^r + b) \\<exclamdown> r = (a*2^r) \\<exclamdown> r\"\n  by (auto simp add: nth_bit_def assms)\n\nlemma aux2_digit_sum_repr:\n  assumes \"n < 2^c\" \"r < c\"\n  shows \"(a*2^c+n) \\<exclamdown> r = n \\<exclamdown> r\"\nproof -\n  have [simp]: \\<open>a*(2::nat) ^ c div 2 ^ r = a*2 ^ (c - r)\\<close>\n    using assms(2)\n    by (auto simp: less_iff_Suc_add\n          monoid_mult_class.power_add ac_simps)\n  show ?thesis\n    using assms\n    by (auto simp add: nth_bit_def\n            div_plus_div_distrib_dvd_left\n            le_imp_power_dvd\n          simp flip: mod_add_left_eq)\nqed\n\nlemma aux1_digit_sum_repr:\nassumes \"n < 2^c\" \"r<c\"\nshows \"(\\<Sum>k<c.((n \\<exclamdown> k)*2^k)) \\<exclamdown> r = n \\<exclamdown> r\"\nproof-\n  define a where \"a \\<equiv> (\\<Sum>k=0..<Suc(r).((n \\<exclamdown> k)*2^k))\"\n  define d where \"d \\<equiv> (\\<Sum>k=Suc(r)..<c.((n \\<exclamdown> k)*2^k))\"\n  define e where \"e \\<equiv> (\\<Sum>k=Suc r..<c.((n \\<exclamdown> k)*2^(k-Suc(r))))\"\n  define b where \"b \\<equiv> (\\<Sum>k=0..<r.((n \\<exclamdown> k)*2^k))\"\n  have ad: \"(\\<Sum>k=0..<c.((n \\<exclamdown> k)*2^k)) = a + d\"\n    using a_def d_def assms\n    by (metis (no_types, lifting) Suc_leI a_def assms(2) d_def sum.atLeastLessThan_concat zero_le)\n  have \"d = (\\<Sum>k=Suc(r)..<c.(2^(Suc r) * (n \\<exclamdown> k *  2^(k - Suc r))))\"\n    using d_def apply (simp)\n    apply (rule sum.cong; auto simp: algebra_simps)\n    by (metis add_Suc le_add_diff_inverse numerals(2) power_Suc power_add)\n  hence d2r: \"d = 2^Suc(r)*e\" using d_def e_def\n     sum_distrib_left[of \"2^(Suc r)\" \"\\<lambda>k. (n \\<exclamdown> k) *  2^(k - Suc r)\" \"{Suc r..<c}\"] by auto\n  have \"(\\<Sum>k<c.((n \\<exclamdown> k)*2^k)) = a +2^Suc(r)*e\" by (simp add: d2r ad lessThan_atLeast0)\n  moreover have \"(\\<Sum>k=0..<Suc(r).((n \\<exclamdown> k)*2^k)) < 2 ^ Suc(r)\" using assms\n  proof(induct r)\n    case 0\n    then show ?case\n    proof -\n      have \"n \\<exclamdown> 0 < Suc 1\" \n        by (metis (no_types) atLeastLessThan_empty atLeastLessThan_iff lessI linorder_not_less \n                  nth_bit_bounded)\n      then show ?thesis\n        by simp\n    qed\n    next\n      case (Suc r)\n      have r2: \"n \\<exclamdown> Suc(r) *  2 ^ Suc(r) \\<le>  2 ^ Suc(r)\" using nth_bit_bounded by simp\n      have \"(\\<Sum>k=0..<Suc(r).((n \\<exclamdown> k)*2^k)) < 2 ^ Suc(r)\" \n        using Suc.hyps using Suc.prems(2) Suc_lessD assms(1) by blast\n      then show ?case using \"r2\" \n        by (smt Suc_leI Suc_le_lessD add_Suc add_le_mono mult_2 power_Suc sum.atLeast0_lessThan_Suc)\n    qed\n    then have \"a < 2 ^Suc(r)\" using a_def by blast\n  ultimately have ar:\"(a+d) \\<exclamdown> r = a \\<exclamdown> r\" using d2r\n    by (metis (no_types, lifting) aux2_digit_sum_repr lessI semiring_normalization_rules(24) \n              semiring_normalization_rules(7))\n    (* Second part of proof *)\n  have ab: \"a =(n \\<exclamdown> r)*2^r + b\" using a_def b_def d_def by simp\n  have \"(\\<Sum>k=0..<r.((n \\<exclamdown> k)*2^k)) <2^r\"\n  proof(induct r)\n    case 0\n      then show ?case by auto\n    next\n      case (Suc r)\n      have r2: \"n \\<exclamdown> r *  2 ^ r \\<le>  2 ^ r\" using nth_bit_bounded by simp\n      have \"(\\<Sum>k = 0..<r. n \\<exclamdown> k * 2 ^ k) < 2^r\" using Suc.hyps by auto\n      then show ?case apply simp using \"r2\" by linarith\n  qed\n  then have b: \"b < 2^r\" using b_def by blast\n  then have \"a \\<exclamdown> r = ((n \\<exclamdown> r)*2^r) \\<exclamdown> r\" using ab aux3_digit_sum_repr by simp\n  then have \"a \\<exclamdown> r = (n \\<exclamdown> r)\" using nth_bit_def by simp\n  then show ?thesis using ar a_def by (simp add: ad lessThan_atLeast0)\nqed\n\nlemma digit_sum_repr:\n  assumes \"n < 2^c\"\n  shows \"n = (\\<Sum>k < c.((n \\<exclamdown> k) * 2^k))\"\nproof -\n  have \"\\<forall>k. (c\\<le>k \\<longrightarrow> n<2^k)\" using assms less_le_trans by fastforce\n  then have nik: \"\\<forall>k.( k\\<ge> c \\<longrightarrow> (n \\<exclamdown> k = 0))\"  by (auto simp add: nth_bit_def)\n  have \"(\\<Sum>r<c.((n \\<exclamdown> r)*(2::nat)^r))<(2::nat)^c\"\n  proof (induct c)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc c)\n    then show ?case\n      using nth_bit_bounded\n            add_mono_thms_linordered_field[of \"(n \\<exclamdown> c)* 2 ^ c\" \" 2 ^ c\" \"(\\<Sum>r<c. n \\<exclamdown> r * 2 ^ r)\" \"2^c\"]\n      by simp\n  qed\n  then have \"\\<forall>k. k\\<ge> c \\<longrightarrow> (\\<Sum>r<c.((n \\<exclamdown> r)*2^r)) \\<exclamdown> k = 0\"\n    using less_le_trans by (auto simp add: nth_bit_def) fastforce\n  then have \"\\<forall>r\\<ge>c.(n \\<exclamdown> r  = (\\<Sum>k<c.((n \\<exclamdown> k)*2^k)) \\<exclamdown> r)\" by (simp add: nik)\n  moreover have \"\\<forall>r<c.(n \\<exclamdown> r  = (\\<Sum>k<c.((n \\<exclamdown> k)*2^k)) \\<exclamdown> r)\" using aux1_digit_sum_repr assms by simp\n  ultimately have \"\\<forall>r.(\\<Sum>k<c.((nth_bit n k)*2^k)) \\<exclamdown> r = n \\<exclamdown> r \" by (metis not_less)\n  then show ?thesis using digit_wise_equiv by presburger\nqed\n\nlemma digit_sum_repr_variant:\n  \"n =(\\<Sum>k<n.((nth_bit n k)*2^k))\"\n  using less_exp digit_sum_repr by auto\n\nlemma digit_sum_index_variant:\n  \"r>n \\<longrightarrow> ((\\<Sum>k< n.((n \\<exclamdown> k)*2^k)) = (\\<Sum>k< r.(n \\<exclamdown> k)*2^k))\"\nproof-\n  have \"\\<forall>r.(2^r > r)\" using less_exp by simp\n  then have pow2: \"\\<forall>r.(r>n \\<longrightarrow> 2^r>n)\" using less_trans by blast\n  then have \"\\<forall>r.(r > n \\<longrightarrow> (n \\<exclamdown> r = 0))\" by (auto simp add: nth_bit_def)\n  then have \"\\<forall>r. r > n \\<longrightarrow> (n \\<exclamdown> r)*2^r = 0\" by auto\n  then show ?thesis using digit_sum_repr digit_sum_repr_variant pow2 by auto\nqed\n\ntext \\<open>Digits are preserved under shifts\\<close>\n\nlemma digit_shift_preserves_digits:\n  assumes \"b>1\" \n  shows \"nth_digit (b * y) (Suc t) b = nth_digit y t b\" \n  using nth_digit_def assms by auto\n\nlemma digit_shift_inserts_zero_least_siginificant_digit:\n  assumes \"t>0\" and \"b>1\"\n  shows \"nth_digit (1 + b * y) t b = nth_digit (b * y) t b\" \n  using nth_digit_def assms apply auto\nproof -\n  assume \"0 < t\"\n  assume \"Suc 0 < b\"\n  hence \"Suc (b * y) mod b = 1\"\n    by (simp add: Suc_times_mod_eq)\n  hence \"b * y div b = Suc (b * y) div b\"\n    using \\<open>b>1\\<close> by (metis (no_types) One_nat_def diff_Suc_Suc gr_implies_not0 minus_mod_eq_div_mult \n                 mod_mult_self1_is_0 nonzero_mult_div_cancel_right)\n  then show \"Suc (b * y) div b ^ t mod b = b * y div b ^ t mod b\"\n    using \\<open>t>0\\<close> by (metis Suc_pred div_mult2_eq power_Suc)\nqed\n\ntext \\<open>Represent natural numbers in their base-b digitwise expansion\\<close>\n\nlemma aux3_digit_gen_sum_repr:\n  assumes \"d < b^r\" and \"b > 1\"\n  shows \"nth_digit (a*b^r + d) r b = nth_digit (a*b^r) r b\"\n  using \\<open>b>1\\<close> by (auto simp: nth_digit_def assms)\n\nlemma aux2_digit_gen_sum_repr:\n  assumes \"n < b^c\" \"r < c\"\n  shows \"nth_digit (a*b^c+n) r b = nth_digit n r b\"\nproof -\n  have [simp]: \\<open>a*b ^ c div b ^ r = a*b ^ (c - r)\\<close>\n    using assms(2)\n    by (auto simp: less_iff_Suc_add\n          monoid_mult_class.power_add ac_simps)\n  show ?thesis\n    using assms\n    by (auto simp add: nth_digit_def\n            div_plus_div_distrib_dvd_left\n            le_imp_power_dvd\n          simp flip: mod_add_left_eq) \nqed\n\nlemma aux1_digit_gen_sum_repr:\nassumes \"n < b^c\" \"r<c\" and \"b>1\"\nshows \"nth_digit (\\<Sum>k<c.((nth_digit n k b)*b^k)) r b = nth_digit n r b\"\nproof-\n  define a where \"a \\<equiv> (\\<Sum>k=0..<Suc(r).((nth_digit n k b)*b^k))\"\n  define d where \"d \\<equiv> (\\<Sum>k=Suc(r)..<c.((nth_digit n k b)*b^k))\"\n  define e where \"e \\<equiv> (\\<Sum>k=Suc r..<c.((nth_digit n k b)*b^(k-Suc(r))))\"\n  define f where \"f \\<equiv> (\\<Sum>k=0..<r.((nth_digit n k b)*b^k))\"\n  have ad: \"(\\<Sum>k=0..<c.((nth_digit n k b)*b^k)) = a + d\"\n    using a_def d_def assms\n    by (metis (no_types, lifting) Suc_leI a_def assms(2) d_def sum.atLeastLessThan_concat zero_le)\n  have \"d = (\\<Sum>k=Suc(r)..<c.(b^(Suc r) * (nth_digit n k b * b^(k - Suc r))))\" \n    using d_def apply (auto) apply (rule sum.cong; auto simp: algebra_simps)\n    by (metis add_Suc le_add_diff_inverse power_Suc power_add)\n  hence d2r: \"d = b^Suc(r)*e\" using d_def e_def sum_distrib_left[of \"b^(Suc r)\" \n                          \"\\<lambda>k. (nth_digit n k b) *  b^(k - Suc r)\" \"{Suc r..<c}\"] by auto\n  have \"(\\<Sum>k<c.((nth_digit n k b)*b^k)) = a +b^Suc(r)*e\" \n    by (simp add: d2r ad lessThan_atLeast0)\n  moreover have \"(\\<Sum>k=0..<Suc(r).((nth_digit n k b)*b^k)) < b ^ Suc(r)\" using assms\n  proof(induct r)\n    case 0\n    then show ?case\n    proof -\n      have \"nth_digit n 0 b < b\" \n        using nth_digit_bounded[of \"b\" \"n\" \"0\"] \\<open>b>1\\<close> by auto\n      then show ?thesis\n        by simp\n    qed\n    next\n      case (Suc r)\n      have r2: \"(nth_digit n (Suc r) b) * b ^ Suc(r) \\<le> (b-1) * b ^ Suc(r)\" \n        using nth_digit_bounded[of \"b\" \"n\" \"Suc r\"] \\<open>b>1\\<close> by auto\n      moreover have \"(\\<Sum>k=0..<Suc(r).((nth_digit n k b)*b^k)) < b ^ Suc(r)\" \n        using Suc.hyps using Suc.prems(2) Suc_lessD assms(1) \\<open>b>1\\<close> by blast\n      ultimately have \"(nth_digit n (Suc r) b) * b ^ Suc(r) \n                     + (\\<Sum>k=0..<Suc(r).((nth_digit n k b)*b^k)) < b ^ Suc (Suc r)\" \n        using assms(3) mult_eq_if by auto \n      then show ?case by auto\n    qed\n    hence \"a < b^Suc(r)\" using a_def by blast\n  ultimately have ar:\"nth_digit (a+d) r b = nth_digit a r b\" using d2r\n    by (metis (no_types, lifting) aux2_digit_gen_sum_repr lessI semiring_normalization_rules(24) \n              semiring_normalization_rules(7))\n    (* Second part of proof *)\n  have ab: \"a =(nth_digit n r b)*b^r + f\" using a_def f_def d_def by simp\n  have \"(\\<Sum>k=0..<r.((nth_digit n k b)*b^k)) < b^r\"\n  proof(induct r)\n    case 0\n      then show ?case by auto\n    next\n      case (Suc r)\n      have r2: \"nth_digit n r b * b ^ r \\<le> (b-1) * b ^ r\" \n        using nth_digit_bounded[of \"b\"] \\<open>b>1\\<close> by auto\n      have \"(\\<Sum>k = 0..<r. nth_digit n k b * b ^ k) < b^r\" using Suc.hyps by auto\n      then show ?case using \"r2\" assms(3) mult_eq_if by auto\n  qed\n  hence f: \"f < b^r\" using f_def by blast\n  hence \"nth_digit a r b = (nth_digit (nth_digit n r b * b^r) r b)\" \n    using ab aux3_digit_gen_sum_repr \\<open>b>1\\<close> by simp\n  hence \"nth_digit a r b = nth_digit n r b\" \n    using nth_digit_def \\<open>b>1\\<close> by simp\n  then show ?thesis using ar a_def by (simp add: ad lessThan_atLeast0)\nqed\n\nlemma aux_gen_b_factor: \"a > 0 \\<Longrightarrow> b>1 \\<Longrightarrow> \\<exists>k c. ((a::nat) = (b^k) * c \\<and> \\<not>(c mod b = 0))\"\nproof(induction  a rule: full_nat_induct)\n  case (1 n)\n  show ?case \n  proof(cases \"n mod b = 0\")\n    case True\n    then obtain t where n_def: \"n = b * t\" by blast\n    hence \"t < n\"\n      using 1 by auto \n    with 1 have ih:\"\\<exists>r s. t = b^r * s \\<and> \\<not>(s mod b = 0)\"\n      by (metis Suc_leI gr0I mult_0_right n_def) \n    hence \"\\<exists>r s. n = b^(Suc r) * s\" using n_def by auto\n    then show ?thesis by (metis ih mult.commute mult.left_commute n_def power_Suc)\n  next\n    case False\n    then show ?thesis by (metis mult.commute power_0 power_Suc power_Suc0_right)\n  qed\nqed\n\nlemma aux0_digit_wise_gen_equiv:\n  assumes \"b>1\" and a_geq_0: \"a > 0\"\n  shows \"(\\<exists>k. nth_digit a k b \\<noteq> 0)\"\nproof(cases \"a mod b = 0\")\n  case True\n  hence \"\\<exists>k c. a = (b^k) * c \\<and> \\<not>(c mod b = 0)\"\n    using aux_gen_b_factor a_geq_0 assms by simp\n  then obtain c k where ck_cond:\"a = (b^k) * c \\<and> \\<not>(c mod b = 0)\" by blast\n  hence c_cond:\"c = a div (b^k)\" using a_geq_0 by auto\n  hence digi_b:\"nth_digit c 0 b \\<noteq> 0\"\n    using ck_cond nth_digit_def by force\n  hence \"nth_digit a k b = nth_digit c 0 b\" \n    using nth_digit_def c_cond by simp\n  hence \"nth_digit a k b \\<noteq> 0\" using digi_b by simp\n  then show ?thesis by blast next\n  case False\n  then show ?thesis\n    by (metis div_by_1 nth_digit_def power.simps(1))\nqed\n\nlemma aux1_digit_wise_gen_equiv:\n  assumes \"b>1\"\n  shows \"(\\<forall>k.(nth_digit a k b = 0)) \\<longleftrightarrow> a = 0\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?Q\"\n  then show \"?P\" by (simp add: nth_digit_def)\nnext\n  {\n    assume a_neq_0:\"\\<not>?Q\"\n    hence \"a > 0\" by blast\n    hence \"\\<not>?P\" using aux0_digit_wise_gen_equiv \\<open>b>1\\<close> by auto\n  } from this show \"?P \\<Longrightarrow> ?Q\" by blast\nqed\n\nlemma aux2_digit_wise_gen_equiv: \"(\\<forall>r<k. nth_digit a r b = 0) \\<longrightarrow> (a mod b^k = 0)\"\nproof(induct k)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc k)\n  then show ?case apply(auto simp add: nth_digit_def)\n    using dvd_imp_mod_0 dvd_mult_div_cancel dvd_refl\n        lessI minus_mod_eq_div_mult minus_mod_eq_mult_div mult_dvd_mono\n    by (metis mod_0_imp_dvd)\nqed\n\ntext \\<open>Two numbers are the same if and only if their digits are the same\\<close>\n\nlemma digit_wise_gen_equiv: \n  assumes \"b>1\"\n  shows \"(x = y) \\<longleftrightarrow> (\\<forall>k. nth_digit x k b = nth_digit y k b)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?P\"\n  then show \"?Q\" by simp\nnext{\n    assume notP: \"\\<not>?P\"\n    have\"\\<not>(\\<forall>k. nth_digit x k b = nth_digit y k b)\" if xy: \"x<y\" for x y\n    proof-\n      define c::nat where \"c = y - x\"\n      have y: \"x+c=y\" by (auto simp add: c_def \"xy\" less_imp_le)\n      have  \"\\<exists>k.(nth_digit c k b \\<noteq> 0)\" \n        using nth_digit_def \\<open>b>1\\<close> aux0_digit_wise_gen_equiv \n        by (metis c_def that zero_less_diff)\n      then obtain k where k1:\"nth_digit c k b \\<noteq> 0\" \n                      and k2:\"\\<forall>r < k. (nth_digit c r b = 0)\"\n        apply(auto dest: obtain_smallest) done\n      hence cr0: \"\\<forall>r < k. (nth_digit c r b = 0)\" by (simp add: nth_digit_def)\n      from aux2_digit_wise_gen_equiv cr0 have \"c mod b^k = 0\" by auto\n      hence \"x div b ^ k mod b \\<noteq> y div b ^ k mod b\"\n        using y k1 \\<open>b>1\\<close> aux1_digit_wise_gen_equiv[of \"b\" \"c\"] nth_digit_def apply auto\n                proof - (* this ISAR proof was found by sledgehammer  *)\n                        fix ka :: nat\n                        assume a1: \"b ^ k dvd c\"\n                        assume a2: \"x div b ^ k mod b = (x + c) div b ^ k mod b\"\n                        assume a3: \"y = x + c\"\n                        assume a4: \"\\<And>num k base. nth_digit num k base \n                                    = num div base ^ k mod base\"\n                have f5: \"\\<forall>n na. (na::nat) + n - na = n\"\n                  by simp\n                  have f6: \"x div b ^ k + c div b ^ k = y div b ^ k\"\n                    using a3 a1 by (simp add: add.commute div_plus_div_distrib_dvd_left)\n                  have f7: \"\\<forall>n. (x div b ^ k + n) mod b = (y div b ^ k + n) mod b\"\n                    using a3 a2 by (metis add.commute mod_add_right_eq)\n                  have \"\\<forall>n na nb. ((nb::nat) mod na + n - (nb + n) mod na) mod na = 0\"\n                    by (metis (no_types) add.commute minus_mod_eq_mult_div mod_add_right_eq \n                        mod_mult_self1_is_0)\n                  then show \"c div b ^ ka mod b = 0\"\n                    using f7 f6 f5 a4 by (metis (no_types) k1)\n                qed\n      then show ?thesis by (auto simp add: nth_digit_def)\n    qed\n    from this [of x y] this [of y x] notP \n      have \"\\<forall>k. nth_digit x k b = nth_digit y k b \\<Longrightarrow> x = y\" apply(auto)\n      using linorder_neqE_nat by blast}then show \"?Q ==> ?P\" by auto\nqed\n\ntext \\<open>A number is equal to the sum of its digits multiplied by powers of two\\<close>\n\nlemma digit_gen_sum_repr:\n  assumes \"n < b^c\" and \"b>1\"\n  shows \"n = (\\<Sum>k < c.((nth_digit n k b) * b^k))\"\nproof -\n  have 1: \"(c\\<le>k \\<longrightarrow> n<b^k)\" for k using assms less_le_trans by fastforce\n  hence nik: \"c\\<le>k \\<longrightarrow> (nth_digit n k b = 0)\" for k \n    by (auto simp add: nth_digit_def)\n  have \"(\\<Sum>r<c.((nth_digit n r b)*b^r))<b^c\" apply(induct c, auto)\n    subgoal for c\n    proof -\n      assume IH: \"(\\<Sum>r<c. nth_digit n r b * b ^ r) < b ^ c\"\n      have bound: \"(nth_digit n c b) * b ^ c \\<le> (b-1) * b^c\" \n        using nth_digit_bounded \\<open>b>1\\<close> by auto\n      thus ?thesis using assms IH\n        by (metis (no_types, lifting) bound add_mono_thms_linordered_field(1) \n            add_mono_thms_linordered_field(5) le_less mult_eq_if not_one_le_zero)\n    qed\n    done\n  hence \"k\\<ge>c \\<longrightarrow> nth_digit (\\<Sum>r<c.((nth_digit n r b)*b^r)) k b = 0\" for k\n    apply(auto simp add: nth_digit_def) using less_le_trans assms(2) by fastforce \n  hence \"\\<forall>r\\<ge>c.(nth_digit n r b \n    = nth_digit (\\<Sum>k<c.((nth_digit n k b)*b^k)) r b)\" by (simp add: nik)\n  moreover have \"\\<forall>r<c.(nth_digit n r b \n               = nth_digit (\\<Sum>k<c.((nth_digit n k b) * b^k)) r b)\" \n    using aux1_digit_gen_sum_repr assms by simp\n  ultimately have \"\\<forall>r. nth_digit (\\<Sum>k<c.((nth_digit n k b)*b^k)) r b \n                    = nth_digit n r b\" by (metis not_less)\n  then show ?thesis \n    using digit_wise_gen_equiv[of \"b\" \"(\\<Sum>k<c. nth_digit n k b * b ^ k)\" \"n\"] \\<open>b>1\\<close> by auto \nqed\n\nlemma digit_gen_sum_repr_variant:\n  assumes \"b>1\"\n  shows \"n = (\\<Sum>k<n.((nth_digit n k b)*b^k))\"\nproof-\n  have \"n < b^n\" using \\<open>b>1\\<close> apply (induct n, auto) by (simp add: less_trans_Suc) \n  then show ?thesis using digit_gen_sum_repr \\<open>b>1\\<close> by auto\nqed\n\nlemma digit_gen_sum_index_variant:\n  assumes \"b>1\" shows \"r>n \\<Longrightarrow> \n  (\\<Sum>k< n.((nth_digit n k b )*b^k)) = (\\<Sum>k< r.(nth_digit n k b)*b^k)\"\nproof -\n  assume \"r>n\"\n  have \"b^r > r\" for r using \\<open>b>1\\<close>  by (induction r, auto simp add: less_trans_Suc)\n  hence powb: \"\\<forall>r.(r>n \\<longrightarrow> b^r>n)\" using less_trans by auto\n  hence \"r > n \\<longrightarrow> (nth_digit n r b = 0)\" for r \n    by (auto simp add: nth_digit_def)\n  hence \"r > n \\<longrightarrow> (nth_digit n r b) * b^r = 0\" for r by auto\n  then show ?thesis using digit_gen_sum_repr digit_gen_sum_repr_variant powb \\<open>n < r\\<close> assms by auto\nqed\n\ntext \\<open>@{text nth_digit} extracts coefficients from a base-b digitwise expansion\\<close>\n\nlemma nth_digit_gen_power_series:\n  fixes c b k q\n  defines \"b \\<equiv> 2^(Suc c)\"\n  assumes bound: \"\\<forall>k. (f k) < b\" (* < 2^c makes proof easier, but is too strong for const f *)\n  shows \"nth_digit (\\<Sum>k=0..q. (f k) * b^k) t b = (if t\\<le>q then (f t) else 0)\"\nproof (induction q arbitrary: t)\n  case 0\n  have \"b>1\" using b_def\n    using one_less_numeral_iff power_gt1 semiring_norm(76) by blast\n  have \"f 0 < b\" using bound by auto\n  hence \"t>0 \\<longrightarrow> f 0 < b^t\" using \\<open>b>1\\<close>\n    using bound less_imp_le_nat less_le_trans by (metis self_le_power)\n  thus ?case using nth_digit_def bound by auto \nnext\n  case (Suc q)\n  thus ?case \n  proof (cases \"t \\<le> Suc q\")\n    case True\n    have f_le_bound: \"f k \\<le> b-1\" for k using bound apply auto \n      by (metis Suc_pred b_def less_Suc_eq_le numeral_2_eq_2 zero_less_Suc zero_less_power)\n    have series_bound: \"(\\<Sum>k = 0..q. f k * b ^ k) < b^(Suc q)\"\n      apply (induct q)\n        subgoal using bound by (simp add: less_imp_le_nat) \n        subgoal for q\n          proof -\n            assume asm: \"(\\<Sum>k = 0..q. f k * b ^ k) < b ^ Suc q\"\n            have \"(\\<Sum>k = 0..q. f k * b ^ k) + f (Suc q) * (b * b ^ q) \n                \\<le> (\\<Sum>k = 0..q. f k * b ^ k) + (b-1) * (b * b ^ q)\" using f_le_bound by auto  \n            also have \"... < b^(Suc q) + (b-1) * (b * b ^ q)\" using asm by auto\n            also have \"... \\<le> b * b * b^q\" apply auto\n              by (metis One_nat_def Suc_neq_Zero b_def eq_imp_le mult.assoc mult_eq_if numerals(2) \n                  power_not_zero)\n            finally show ?thesis using asm by auto\n          qed \n        done\n    hence \"nth_digit ((\\<Sum>k = 0..q. f k * b ^ k) + f (Suc q) * (b * b ^ q)) t b = f t\" \n      using Suc nth_digit_def apply (cases \"t = Suc q\", auto)\n        subgoal using  Suc_n_not_le_n add.commute add.left_neutral b_def bound div_mult_self1 \n              less_imp_le_nat less_mult_imp_div_less mod_less not_one_le_zero one_less_numeral_iff \n              one_less_power power_Suc semiring_norm(76) zero_less_Suc by auto\n        subgoal \n          proof -\n            assume \"t \\<noteq> Suc q\"\n            hence \"t < Suc q\" using True by auto\n            hence \"nth_digit (f (Suc q) * b ^ Suc q + (\\<Sum>k = 0..q. f k * b ^ k)) t b \n                = nth_digit (\\<Sum>k = 0..q. f k * b ^ k) t b\"\n              using aux2_digit_gen_sum_repr[of \"\\<Sum>k = 0..q. f k * b ^ k\" \"b\" \"Suc q\" \"t\" \n                    \"f (Suc q)\"] series_bound by auto\n            hence \"((\\<Sum>k = 0..q. f k * b ^ k) + f (Suc q) * (b * b ^ q)) div b ^ t mod b\n                  = (\\<Sum>k = 0..q. f k * b ^ k) div b ^ t mod b\" \n              using nth_digit_def by (auto simp:add.commute)\n            thus ?thesis using Suc[of \"t\"] nth_digit_def True \\<open>t \\<noteq> Suc q\\<close> by auto\n          qed\n        done\n    thus ?thesis using True by auto\n  next\n    case False (* t > Suc q *)\n    hence \"t \\<ge> Suc (Suc q)\" by auto\n    have f_le_bound: \"f k \\<le> b-1\" for k using bound apply auto \n      by (metis Suc_pred b_def less_Suc_eq_le numeral_2_eq_2 zero_less_Suc zero_less_power)\n    have bound: \"(\\<Sum>k = 0..q. f k * b ^ k) < b^(Suc q)\" for q\n      apply (induct q)\n        subgoal using bound by (simp add: less_imp_le_nat) \n        subgoal for q\n          proof -\n            assume asm: \"(\\<Sum>k = 0..q. f k * b ^ k) < b ^ Suc q\"\n            have \"(\\<Sum>k = 0..q. f k * b ^ k) + f (Suc q) * (b * b ^ q) \n                \\<le> (\\<Sum>k = 0..q. f k * b ^ k) + (b-1) * (b * b ^ q)\" using f_le_bound by auto  \n            also have \"... < b^(Suc q) + (b-1) * (b * b ^ q)\" using asm by auto\n            also have \"... \\<le> b * b * b^q\" apply auto\n              by (metis One_nat_def Suc_neq_Zero b_def eq_imp_le mult.assoc mult_eq_if numerals(2) \n                  power_not_zero)\n            finally show ?thesis using asm by auto\n          qed \n        done\n    have \"(\\<Sum>k = 0..q. f k * b ^ k) + f (Suc q) * (b * b ^ q) < (b ^ Suc (Suc q))\" \n      using bound[of \"Suc q\"] by auto \n    also have \"... \\<le> b^t\" using \\<open>t \\<ge> Suc (Suc q)\\<close> \n      apply auto by (metis b_def nat_power_less_imp_less not_le numeral_2_eq_2 power_Suc \n                     zero_less_Suc zero_less_power)\n    finally show ?thesis using \\<open>t \\<ge> Suc (Suc q)\\<close> bound[of \"Suc q\"] nth_digit_def by auto\n  qed\nqed\n\ntext \\<open>Equivalence condition for the @{text nth_digit} function \\<^cite>\\<open>\"h10lecturenotes\"\\<close>\n      (see equation 2.29)\\<close>\n\nlemma digit_gen_equiv:\n  assumes \"b>1\"\n  shows \"d = nth_digit a k b \\<longleftrightarrow> (\\<exists>x.\\<exists>y.(a = x * b^(k+1) + d*b^k +y \\<and> d < b \\<and> y < b^k))\"\n  (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume p: ?P\n  then show ?Q\n  proof(cases \"k<a\")\n    case True\n\n    (* 3rd condition *)\n    have \"(\\<Sum>i<k.((nth_digit a i b)*b^i)) < b^k\"\n    proof(induct k)\n      case 0\n      then show ?case by auto\n    next\n      case (Suc k)\n      have \"(\\<Sum>i<Suc k. nth_digit a i b * b ^ i) = (nth_digit a k b) * b^k  \n            + (\\<Sum>i<k.((nth_digit a i b)*b^i))\" by simp\n      moreover have \" (nth_digit a k b) * b^k \\<le> (b-1) * b^ k\"\n        using assms mult_le_mono nth_digit_bounded by auto\n      moreover have \"(\\<Sum>i<k.((nth_digit a i b)*b^i)) < b ^ (Suc k)\" \n        using Suc.hyps assms order.strict_trans2 by fastforce\n      ultimately show ?case using assms using Suc.hyps mult_eq_if by auto\n    qed\n    moreover define y where \"y = (\\<Sum>i<k.((nth_digit a i b)*b^i))\"\n    ultimately have 3: \"y < b^k\"  by blast\n\n    (* 2nd condition*)\n     have 2: \"d < b\" using nth_digit_bounded[of b a k] p assms by linarith\n\n    (* 1st condition *)\n    define x where \"x =  (\\<Sum>i=Suc k..<a. ((nth_digit a i b)*b^(i-Suc k)))\"\n    have \"a = (\\<Sum>i<a.((nth_digit a i b)*b^i))\" using assms digit_gen_sum_repr_variant by blast\n    hence s:\"a = y + d * b^k  \n            + (\\<Sum>i=Suc k..<a.((nth_digit a i b)*b^i))\" using True y_def p\n      by (metis (no_types, lifting) Suc_leI atLeast0LessThan gr_implies_not0 \n          linorder_not_less sum.atLeastLessThan_concat sum.lessThan_Suc)\n    have \"(\\<Sum>n = Suc k..<a. nth_digit a n b * b ^ (n - Suc k) * b ^ Suc k) \n          =  (\\<Sum>i = Suc k..<a. nth_digit a i b * b ^ i)\"\n      apply (rule sum.cong; auto simp: algebra_simps)\n      by (metis Suc_le_lessD Zero_not_Suc add_diff_cancel_left' diff_Suc_1 diff_Suc_Suc \n          less_imp_Suc_add power_add power_eq_if)\n    hence \"x * b^(k+1) = (\\<Sum>i=Suc k..<a.((nth_digit a i b)*b^i))\" \n      using x_def sum_distrib_right[of \"\\<lambda>i. (nth_digit a i b) *  b^(i - Suc k)\"] by simp\n    hence \"a = x * b^(k+1) + d*b^k +y\" using s by auto\n    thus ?thesis using 2 3 by blast\n  next\n    case False\n    then have \"a < b^k\" using assms power_gt_expt[of b k] by auto\n    moreover have \"d = 0\" by (simp add: calculation nth_digit_def p)\n    ultimately show ?thesis\n      using assms by force   \n  qed\nnext\n  assume ?Q\n  then obtain x y where conds: \"a = x * b^(k+1) + d*b^k +y \\<and> d < b \\<and> y < b^k\" by auto\n  hence \"nth_digit a k b = nth_digit(x * b^(k+1) + d*b^k) k b\"\n    using aux3_digit_gen_sum_repr[of y b \"k\" \"x*b + d\"] assms by (auto simp: algebra_simps)\n  hence \"nth_digit a k b = nth_digit(d*b^k) k b\" \n    using aux2_digit_gen_sum_repr[of \"d*b^k\" \"b\" \"k+1\" k x] conds by auto\n  then show ?P using conds nth_digit_def by simp\nqed\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Digit_Expansions/Bits_Digits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.773815898544657}}
{"text": "(* Author: Tobias Nipkow, based on work by Daniel Somogyi *)\n\nsection \\<open>Optimal BSTs: The `Cubic' Algorithm\\label{sec:cubic}\\<close>\n\ntheory Optimal_BST\nimports Weighted_Path_Length\nbegin\n\nsubsection \\<open>Function \\<open>argmin\\<close>\\<close>\n\ntext \\<open>Function \\<open>argmin\\<close> iterates over a list and returns the rightmost element\nthat minimizes a given function:\\<close>\n\nfun argmin :: \"('a \\<Rightarrow> ('b::linorder)) \\<Rightarrow> 'a list \\<Rightarrow> 'a\" where\n\"argmin f (x#xs) =\n  (if xs = [] then x else\n   let m = argmin f xs in if f x < f m then x else m)\"\n\ntext \\<open>An optimized version that avoids repeated computation of \\<open>f x\\<close>:\\<close>\n\nfun argmin2 :: \"('a \\<Rightarrow> ('b::linorder)) \\<Rightarrow> 'a list \\<Rightarrow> 'a * 'b\" where\n\"argmin2 f (x#xs) =\n  (let fx = f x\n   in if xs = [] then (x, fx)\n      else let mfm = argmin2 f xs\n           in if fx < snd mfm then (x,fx) else mfm)\"\n\n\n\nlemma argmin_argmin2[code]: \"argmin f xs = (if xs = [] then undefined else fst(argmin2 f xs))\"\napply(auto simp: argmin2_argmin)\napply (meson argmin.elims list.distinct(1))\ndone\n\n\nlemma argmin_forall: \"xs \\<noteq> [] \\<Longrightarrow> (\\<And>x. x\\<in>set xs \\<Longrightarrow> P x) \\<Longrightarrow> P (argmin f xs)\"\nby(induction xs) (auto simp: Let_def)\n\nlemma argmin_in: \"xs \\<noteq> [] \\<Longrightarrow> argmin f xs \\<in> set xs\"\nusing argmin_forall[of xs \"\\<lambda>x. x\\<in>set xs\"] by blast\n\nlemma argmin_Min: \"xs \\<noteq> [] \\<Longrightarrow> f (argmin f xs) = Min (f ` set xs)\"\nby(induction xs) (auto simp: min_def intro!: antisym)\n\nlemma argmin_pairs: \"xs \\<noteq> [] \\<Longrightarrow>\n  (argmin f xs,f (argmin f xs)) = argmin snd (map (\\<lambda>x. (x,f x)) xs)\"\nby (induction f xs rule:argmin.induct) (auto, smt snd_conv)\n\nlemma argmin_map: \"xs \\<noteq> [] \\<Longrightarrow> argmin c (map f xs) = f(argmin (c o f) xs)\"\nby(induction xs) (simp_all add: Let_def)\n\n\nsubsection \\<open>The `Cubic' Algorithm\\<close>\n\ntext \\<open>We hide the details of the access frequencies \\<open>a\\<close> and \\<open>b\\<close> by working with an abstract\nversion of function \\<open>w\\<close> definied above (summing \\<open>a\\<close> and \\<open>b\\<close>). Later we interpret \\<open>w\\<close> accordingly.\\<close>\n\nlocale Optimal_BST =\nfixes w :: \"int \\<Rightarrow> int \\<Rightarrow> nat\"\nbegin\n\nsubsubsection \\<open>Functions \\<open>wpl\\<close> and \\<open>min_wpl\\<close>\\<close>\n\nsublocale wpl where w = w .\n\ntext \\<open>Function \\<open>min_wpl i j\\<close> computes the minimal weighted path length of any tree \\<open>t\\<close>\nwhere @{prop\"inorder t = [i..j]\"}. It simply tries all possible indices between \\<open>i\\<close> and \\<open>j\\<close>\nas the root. Thus it implicitly constructs all possible trees.\\<close>\n\ndeclare conj_cong [fundef_cong]\nfunction min_wpl :: \"int \\<Rightarrow> int \\<Rightarrow> nat\" where\n\"min_wpl i j =\n  (if i > j then 0\n   else Min ((\\<lambda>k. min_wpl i (k-1) + min_wpl (k+1) j) ` {i..j}) + w i j)\"\nby auto\ntermination by (relation \"measure (\\<lambda>(i,j). nat(j-i+1))\") auto\ndeclare min_wpl.simps[simp del]\n\ntext \\<open>Note that for efficiency reasons we have pulled \\<open>+ w i j\\<close> out of \\<open>Min\\<close>.\nIn the lemma below this is reversed because it simplifies the proofs.\nSimilar optimizations are possible in other functions below.\\<close>\n\nlemma min_wpl_simps[simp]:\n  \"i > j \\<Longrightarrow> min_wpl i j = 0\"\n  \"i \\<le> j \\<Longrightarrow> min_wpl i j =\n     Min ((\\<lambda>k. min_wpl i (k-1) + min_wpl (k+1) j + w i j) ` {i..j})\"\nby(auto simp add: min_wpl.simps[of i j] Min_add_commute)\n\nlemma upto_split1: \n  \"\\<lbrakk> i \\<le> j;  j \\<le> k \\<rbrakk> \\<Longrightarrow> [i..k] = [i..j-1] @ [j..k]\"\nproof (induction j rule: int_ge_induct)\n  case base thus ?case by (simp add: upto_rec1)\nnext\n  case step thus ?case using upto_rec1 upto_rec2 by simp\nqed\n\ntext\\<open>Function @{const min_wpl} returns a lower bound for all possible BSTs:\\<close>\n\ntheorem min_wpl_is_optimal:\n  \"inorder t = [i..j] \\<Longrightarrow> min_wpl i j \\<le> wpl i j t\"\nproof(induction i j t rule: wpl.induct)\n  case 1\n  thus ?case by(simp add: upto.simps split: if_splits)\nnext\n  case (2 i j l k r)\n  then show ?case \n  proof cases\n    assume \"i > j\" thus ?thesis by(simp)\n  next\n    assume [arith]: \"\\<not> i > j\"\n\n    note inorder = inorder_upto_split[OF \"2.prems\"]\n        \n    let ?M = \"(\\<lambda>k. min_wpl i (k-1) + min_wpl (k+1) j + w i j) ` {i..j}\"\n    let ?w = \"min_wpl i (k-1) + min_wpl (k+1) j + w i j\"\n \n    have aux_min:\"Min ?M \\<le> ?w\"\n    proof (rule Min_le)\n      show \"finite ?M\" by simp\n      show \"?w \\<in> ?M\" using inorder(3,4) by simp\n    qed\n\n    have \"min_wpl i j = Min ?M\" by(simp)\n    also have \"... \\<le> ?w\" by (rule aux_min)    \n    also have \"... \\<le> wpl i (k-1) l + wpl (k+1) j r + w i j\"\n      using inorder(1,2) \"2.IH\" by simp\n    also have \"... = wpl i j \\<langle>l,k,r\\<rangle>\" by simp\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>Now we show that the lower bound computed by @{const min_wpl}\nis the wpl of an optimal tree that can be computed in the same manner.\\<close>\n\nsubsubsection \\<open>Function \\<open>opt_bst\\<close>\\<close>\n\ntext\\<open>This is the functional equivalent of the standard cubic imperative algorithm.\nUnless it is memoized, the complexity is again exponential.\nThe pattern of recursion is the same as for @{const min_wpl} but instead of the minimal weight\nit computes a tree with the minimal weight:\\<close>\n\nfunction opt_bst :: \"int \\<Rightarrow> int \\<Rightarrow> int tree\" where\n\"opt_bst i j =\n  (if i > j then Leaf\n   else argmin (wpl i j) [\\<langle>opt_bst i (k-1), k, opt_bst (k+1) j\\<rangle>. k \\<leftarrow> [i..j]])\"\nby auto\ntermination by (relation \"measure (\\<lambda>(i,j) . nat(j-i+1))\") auto\ndeclare opt_bst.simps[simp del]\n\ncorollary opt_bst_simps[simp]:\n  \"i > j \\<Longrightarrow> opt_bst i j = Leaf\"\n  \"i \\<le> j \\<Longrightarrow> opt_bst i j =\n     (argmin (wpl i j) [\\<langle>opt_bst i (k-1), k, opt_bst (k+1) j\\<rangle>. k \\<leftarrow> [i..j]])\"\nby(auto simp add: opt_bst.simps[of i j])\n\ntext \\<open>As promised, @{const opt_bst} computes a tree with the minimal wpl:\\<close>\n\ntheorem wpl_opt_bst: \"wpl i j (opt_bst i j) = min_wpl i j\"\nproof(induction i j rule: min_wpl.induct)\n  case (1 i j)\n  show ?case\n  proof cases\n    assume \"i > j\" \n    thus ?thesis by(simp)\n  next\n    assume [arith]: \"\\<not> i > j\"\n    let ?ts = \"[\\<langle>opt_bst i (k-1), k, opt_bst (k+1) j\\<rangle>. k \\<leftarrow> [i..j]]\"\n    let ?M = \"((\\<lambda>k. min_wpl i (k-1) + min_wpl (k+1) j + w i j) ` {i..j})\"\n    have 1: \"?ts \\<noteq> []\" by (auto simp add: upto.simps)\n    have \"wpl i j (opt_bst i j) = wpl i j (argmin (wpl i j) ?ts)\" by simp\n    also have \"\\<dots> = Min (wpl i j ` (set ?ts))\"\n      by(rule argmin_Min[OF 1])\n    also have \"\\<dots> = Min ?M\"\n    proof (rule arg_cong[where f=Min])\n      show \"wpl i j ` (set ?ts) = ?M\" using \"1.IH\"\n        by (force simp: Bex_def image_iff \"1.IH\")\n    qed\n    also have \"\\<dots> = min_wpl i j\" by simp\n    finally show ?thesis .\n  qed\nqed\n\ncorollary opt_bst_is_optimal:\n  \"inorder t = [i..j] \\<Longrightarrow> wpl i j (opt_bst i j) \\<le> wpl i j t\"\nby (simp add: min_wpl_is_optimal wpl_opt_bst)\n\nsubsubsection \\<open>Function \\<open>opt_bst_wpl\\<close>\\<close>\n\ntext \\<open>Function @{const opt_bst} is simplistic because it computes the wpl\nof each tree anew rather than returning it with the tree. That is what \\<open>opt_bst_wpl\\<close> does:\\<close>\n\nfunction opt_bst_wpl :: \"int \\<Rightarrow> int \\<Rightarrow> int tree \\<times> nat\" where\n\"opt_bst_wpl i j = \n  (if i > j then (Leaf, 0)\n   else argmin snd [let (t1,c1) = opt_bst_wpl i (k-1);\n                        (t2,c2) = opt_bst_wpl (k+1) j\n                     in (\\<langle>t1,k,t2\\<rangle>, c1 + c2 + w i j). k \\<leftarrow> [i..j]])\"\nby auto\ntermination\n  by (relation \"measure (\\<lambda>(i,j). nat(j-i+1))\")(auto)\ndeclare opt_bst_wpl.simps[simp del]\n\ntext\\<open>Function @{const opt_bst_wpl} returns an optimal tree and its wpl:\\<close>\n\nlemma opt_bst_wpl_eq_pair:\n  \"opt_bst_wpl i j = (opt_bst i j, wpl i j (opt_bst i j))\"\nproof(induction i j rule: opt_bst_wpl.induct)\n  case (1 i j)\n  note [simp] = opt_bst_wpl.simps[of i j]\n  show ?case \n  proof cases\n    assume \"i > j\" thus ?thesis using \"1.prems\" by auto\n  next\n    assume \"\\<not> i > j\"\n    thus ?thesis by (simp add: argmin_pairs comp_def \"1.IH\" cong: list.map_cong_simp)\n  qed\nqed\n\ncorollary opt_bst_wpl_eq_pair': \"opt_bst_wpl i j = (opt_bst i j, min_wpl i j)\"\nby (simp add: opt_bst_wpl_eq_pair wpl_opt_bst)\n\nend (* locale Optimal_BST *)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Optimal_BST/Optimal_BST.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587846530938, "lm_q2_score": 0.8705972700870909, "lm_q1q2_score": 0.7737509716849041}}
{"text": "theory ex2_07 imports Main begin\n\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror (Tip v) = Tip v\" |\n\"mirror (Node l v r) = Node (mirror r) v (mirror l)\"\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\"  where\n\"pre_order (Tip v) = [v]\" |\n\"pre_order (Node l v r) = v # (pre_order l) @ (pre_order r)\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Tip v) = [v]\" |\n\"post_order (Node l v r) = (post_order l) @ (post_order r) @ [v]\"\n\nvalue \"pre_order (Node (Tip 2) 1 (Node (Tip 4) 3 (Tip 5)))\"\nvalue \"post_order (Node (Tip 2) 1 (Node (Tip 4) 3 (Tip 5)))\"\n\ntheorem \"pre_order (mirror t) = rev (post_order t)\"\napply(induction t)\napply auto\ndone\n\nend", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter2/ex2_07.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361652391385, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7737164479478704}}
{"text": "theory Graph_Definitions\n  imports \"Graph_Theory.Digraph_Component\" \"Graph_Theory.Shortest_Path\"\n    \"Misc\" \"Graph_Theory_Batteries\"\nbegin\n\ncontext wf_digraph\nbegin\n\nsection \\<open>K-neighborhood definition\\<close>\ndefinition k_neighborhood :: \"'b weight_fun \\<Rightarrow> 'a \\<Rightarrow> real \\<Rightarrow> 'a set\" where\n  \"k_neighborhood w v k = {u \\<in> verts G. \\<mu> w v u \\<le> k } - {v}\"\n\nlemma k_nh_reachable: \"u \\<in> k_neighborhood w v k \\<Longrightarrow> v \\<rightarrow>\\<^sup>* u\"\n  unfolding k_neighborhood_def\n  using shortest_path_inf by fastforce\n\nlemma source_nmem_k_nh: \"v \\<notin> k_neighborhood w v k\"\n  unfolding k_neighborhood_def by simp\n\nsection \\<open>Diameter and finite diameter\\<close>\ntext \\<open>\nThe diameter is defined as the longest shortest path in the corresponding graph. If there is no path\nbetween any two vertices in the graph, then the diameter is infinite.\nWe also make use of the notion of a @{text fin_diameter} which only considers the shortest path\nbetween connected nodes.\n\\<close>\n\ndefinition sp_costs :: \"'b weight_fun \\<Rightarrow> ereal set\" where\n  \"sp_costs f = {c | u v c. u \\<in> verts G \\<and> v \\<in> verts G \\<and> \\<mu> f u v = c}\"\n\ndefinition diameter :: \"'b weight_fun \\<Rightarrow> ereal\" where\n  \"diameter f = Sup (sp_costs f)\"\n\ndefinition fin_sp_costs :: \"'b weight_fun \\<Rightarrow> ereal set\" where\n  \"fin_sp_costs f = {c | u v c. u \\<in> verts G \\<and> v \\<in> verts G \\<and> \\<mu> f u v = c \\<and> c < \\<infinity>}\"\n\ndefinition fin_diameter :: \"'b weight_fun \\<Rightarrow> ereal\" where\n  \"fin_diameter f = Sup (fin_sp_costs f)\"\n\n\nsubsection \\<open>In general graphs\\<close>\n\nlemma empty_imp_dia_minf: \"verts G = {} \\<Longrightarrow> diameter w = -\\<infinity>\"\n  unfolding diameter_def sp_costs_def\n  by (simp add: bot_ereal_def)\n\nlemma empty_imp_fin_dia_minf: \"verts G = {} \\<Longrightarrow> fin_diameter w = -\\<infinity>\"\n  unfolding fin_diameter_def fin_sp_costs_def\n  by (simp add: bot_ereal_def)\n\nlemma dia_eq_fin_dia_if_finite: \"diameter f < \\<infinity> \\<Longrightarrow> diameter f = fin_diameter f\"\nproof -\n  assume \"diameter f < \\<infinity>\"\n  then have \"\\<infinity> \\<notin> sp_costs f\"\n    unfolding diameter_def using Sup_eq_PInfty by auto\n  then have \"sp_costs f = fin_sp_costs f\"\n    unfolding sp_costs_def fin_sp_costs_def by auto\n  then show ?thesis\n    unfolding diameter_def fin_diameter_def by simp\nqed\n\nlemma fin_dia_lowerB: \"\\<lbrakk> u \\<in> verts G; v \\<in> verts G; \\<mu> w u v < \\<infinity>\\<rbrakk>\n  \\<Longrightarrow> fin_diameter w \\<ge> \\<mu> w u v\"\n  unfolding fin_diameter_def fin_sp_costs_def\n  by (metis (mono_tags, lifting) Sup_upper mem_Collect_eq)\n\nlemma dia_lowerB: \"\\<lbrakk> u \\<in> verts G; v \\<in> verts G \\<rbrakk>\n  \\<Longrightarrow> diameter w \\<ge> \\<mu> w u v\"\n  unfolding diameter_def sp_costs_def\n  by (metis (mono_tags, lifting) Sup_upper mem_Collect_eq)\n\n\nsubsection \\<open>In finite graphs\\<close>\n\nlemma (in fin_digraph) sp_costs_finite: \"finite (sp_costs f)\"\n  unfolding sp_costs_def by auto\n\nlemma (in fin_digraph) fin_sp_costs_finite: \"finite (fin_sp_costs f)\"\n  unfolding fin_sp_costs_def by auto\n\nlemma (in fin_digraph) ex_sp_eq_dia:\n  \"verts G \\<noteq> {} \\<Longrightarrow> \\<exists>u \\<in> verts G. \\<exists>v \\<in> verts G. \\<mu> f u v = diameter f\"\nproof -\n  assume \"verts G \\<noteq> {}\"\n  then have \"sp_costs f \\<noteq> {}\"\n    unfolding sp_costs_def using \\<mu>_reach_conv by fastforce\n\n  with sp_costs_finite have \"\\<exists>c \\<in> sp_costs f. c = diameter f\"\n    by (simp add: Sup_in_set diameter_def)\n  then show \"?thesis\" unfolding diameter_def\n    unfolding sp_costs_def by auto\nqed\n\ntext \\<open>Analogous to the proof of @{thm fin_digraph.ex_sp_eq_dia}.\\<close>\nlemma (in fin_digraph) ex_sp_eq_fin_dia:\n  \"verts G \\<noteq> {} \\<Longrightarrow> \\<exists>u \\<in> verts G. \\<exists>v \\<in> verts G. \\<mu> f u v = fin_diameter f\"\nproof -\n  assume \"verts G \\<noteq> {}\"\n  then have \"fin_sp_costs f \\<noteq> {}\"\n    unfolding fin_sp_costs_def using \\<mu>_reach_conv by fastforce\n\n  with fin_sp_costs_finite have \"\\<exists>c \\<in> fin_sp_costs f. c = fin_diameter f\"\n    by (simp add: Sup_in_set fin_diameter_def)\n  then show \"?thesis\" unfolding fin_diameter_def\n    unfolding fin_sp_costs_def by auto\nqed\n\n\nlemma (in fin_digraph) fin_diameter_finite: \"fin_diameter f < \\<infinity>\"\nproof(rule ccontr)\n  fix f assume dia_infty: \"\\<not> fin_diameter f < \\<infinity>\"\n\n  then have infty_cont: \"\\<infinity> \\<in> fin_sp_costs f\" if *: \"fin_sp_costs f \\<noteq> {}\"\n    unfolding fin_diameter_def using *\n    by (metis ereal_infty_less(1) fin_sp_costs_finite infinite_growing less_Sup_iff)\n\n  then show \"False\"\n  proof(cases \"fin_sp_costs f = {}\")\n    case True\n    then have \"fin_diameter f = -\\<infinity>\"\n      unfolding fin_diameter_def by (simp add: bot_ereal_def)\n    with dia_infty show ?thesis by simp\n  next\n    case False\n    from infty_cont[OF this] dia_infty show ?thesis\n      unfolding fin_diameter_def fin_sp_costs_def by auto\n  qed\nqed\n\nlemma (in fin_digraph) ex_min_apath_eq_fin_dia:\n  \"\\<lbrakk> verts G \\<noteq> {}; \\<forall>e \\<in> arcs G. f e \\<ge> 0 \\<rbrakk>\n  \\<Longrightarrow> \\<exists>u \\<in> verts G. \\<exists>v \\<in> verts G. \\<exists>p. apath u p v \\<and> awalk_cost f p = fin_diameter f\"\nproof -\n  assume \"verts G \\<noteq> {}\" and w_non_neg: \"\\<forall>e \\<in> arcs G. f e \\<ge> 0\"\n  from ex_sp_eq_fin_dia[OF this(1)] obtain u v\n    where u_v: \"u \\<in> verts G\" \"v \\<in> verts G\" and sp_eq_dia: \"\\<mu> f u v = fin_diameter f\"\n    by blast\n  from sp_eq_dia have \"\\<mu> f u v < \\<infinity>\" using fin_diameter_finite by auto\n  then have \"u \\<rightarrow>\\<^sup>* v\" using \\<mu>_reach_conv by blast\n  from min_cost_awalk[OF this] w_non_neg obtain p\n    where \"apath u p v\" \"\\<mu> f u v = awalk_cost f p\"\n    by auto\n  with u_v sp_eq_dia show ?thesis by auto\nqed\n\nsubsection \\<open>Relation between diameter and finite diameter\\<close>\n\ntheorem dia_eq_fin_dia_if_strongly_con: \"strongly_connected G \\<Longrightarrow> diameter = fin_diameter\"\nproof\n  fix f assume strongly_con: \"strongly_connected G\"\n  then have \"\\<infinity> \\<notin> sp_costs f\"\n    unfolding sp_costs_def using \\<mu>_reach_conv by auto\n  then have \"sp_costs f = fin_sp_costs f\"\n    unfolding fin_sp_costs_def sp_costs_def by auto\n  then show \"diameter f = fin_diameter f\"\n    unfolding diameter_def fin_diameter_def by auto\nqed\n\nend\n\nsection \\<open>N-nearest vertices\\<close>\ntext \\<open>\nThe definition of @{text n_nearest_verts} is used to formalize the abstract behaviour of the\nDijkstra algorithm which iteratively visits the nearest undiscovered vertex until all\nvertices are discovered.\n\\<close>\ncontext wf_digraph begin\n\ndefinition unvisited_verts :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a set\" where\n\"unvisited_verts u U = {x. x \\<in> verts G - U \\<and> u \\<rightarrow>\\<^sup>* x}\"\n\ndefinition nearest_vert :: \"'b weight_fun \\<Rightarrow> 'a \\<Rightarrow> 'a set \\<Rightarrow> 'a\" where\n\"nearest_vert w u U =\n  (SOME x. x \\<in> unvisited_verts u U \\<and> (\\<forall>y \\<in> unvisited_verts u U. \\<mu> w u y \\<ge> \\<mu> w u x))\"\n\ninductive n_nearest_verts :: \"'b weight_fun \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where\nzero_nnvs: \"u \\<in> verts G \\<Longrightarrow> n_nearest_verts _ u 0 {u}\" |\nn_nnvs_unvis: \"\\<lbrakk> n_nearest_verts w u n U; unvisited_verts u U \\<noteq> {}\\<rbrakk>\n   \\<Longrightarrow> n_nearest_verts w u (Suc n) (insert (nearest_vert w u U) U)\" |\nn_nnvs_vis: \"\\<lbrakk> n_nearest_verts w u n U; unvisited_verts u U = {} \\<rbrakk>\n   \\<Longrightarrow> n_nearest_verts w u (Suc n) U\"\n\ninductive_cases nnvs_ind_cases: \"n_nearest_verts w u n U\"\nthm nnvs_ind_cases\n\n\nsubsection \\<open>In general graphs\\<close>\n\nlemma source_mem_nnvs: \"n_nearest_verts w u n U \\<Longrightarrow> u \\<in> verts G\"\n  by (induction rule: n_nearest_verts.induct) auto\n\nlemma unvis_insert: \"unvisited_verts u (insert x U) = (unvisited_verts u U) - {x}\"\n  unfolding unvisited_verts_def by auto\n\nlemma disj_unvis_vis: \"unvisited_verts u U \\<inter> U = {}\"\n  unfolding unvisited_verts_def by auto\n\nlemma nnvs_finite: \"n_nearest_verts w u n U \\<Longrightarrow> finite U\"\n  by (induction rule: n_nearest_verts.induct) auto\n\nlemma nnvs_card_le_n: \"n_nearest_verts w u n U \\<Longrightarrow> card U \\<le> Suc n\"\n  by (induction rule: n_nearest_verts.induct) (auto simp: card_insert_le_m1)\n\nlemma nnvs_mem: \"n_nearest_verts w u n U \\<Longrightarrow> u \\<in> U\"\n  by (induction rule: n_nearest_verts.induct) auto\n\nlemma unvis_empty: \"unvisited_verts u {a. u \\<rightarrow>\\<^sup>* a} = {}\"\n  unfolding unvisited_verts_def by auto\n\nend\n\nsubsection \\<open>In finite graphs\\<close>\ncontext fin_digraph begin\n\nlemma k_nh_finite: \"finite (k_neighborhood w v k)\"\n  unfolding k_neighborhood_def using finite_verts by force\n\nlemma unvis_finite: \"finite (unvisited_verts u U)\"\n  unfolding unvisited_verts_def using finite_verts by auto\n\nlemma ex_unvis_vert:\"\\<lbrakk> unvisited_verts u U \\<noteq> {} \\<rbrakk> \\<Longrightarrow>\n   \\<exists>x \\<in> unvisited_verts u U. (\\<forall>y \\<in> unvisited_verts u U. \\<mu> w u y \\<ge> \\<mu> w u x)\"\n  unfolding nearest_vert_def using unvis_finite\nproof(induction \"unvisited_verts u U\" arbitrary: u U rule: finite_induct)\n  case (insert x F)\n  then have \"F = unvisited_verts u U - {x}\"\n    by auto\n  then have F: \"F = unvisited_verts u (insert x U)\"\n    using unvis_insert[symmetric] by simp\n\n  show ?case\n  proof(cases \"unvisited_verts u (insert x U) = {}\")\n    case True\n    with insert.prems show ?thesis using unvis_insert by auto\n  next\n    case False\n    from insert(3)[OF F this] obtain x' where \"x' \\<in> unvisited_verts u (insert x U)\"\n      and \"\\<forall>y\\<in>unvisited_verts u (insert x U). \\<mu> w u x' \\<le> \\<mu> w u y\" by blast\n    note x' = this\n\n    show ?thesis\n    proof(cases \"\\<mu> w u x' \\<le> \\<mu> w u x\")\n      case True\n      from x' F insert.hyps(4) have \"x' \\<in> unvisited_verts u U\" by blast\n      moreover\n      have \"\\<forall>y \\<in> unvisited_verts u U. \\<mu> w u x' \\<le> \\<mu> w u y\"\n        using F True insert.hyps(4) x' by auto\n      ultimately show ?thesis by blast\n    next\n      case False\n      with x' have \"\\<forall>y \\<in> unvisited_verts u (insert x U). \\<mu> w u x \\<le> \\<mu> w u y\"\n        by fastforce\n      with F insert.hyps(4) have \"\\<forall>y \\<in> unvisited_verts u U. \\<mu> w u x \\<le> \\<mu> w u y\"\n        by fastforce\n      with insert.hyps(4) show ?thesis by blast\n    qed\n  qed\nqed blast\n\nlemma some_unvis_vert:\n  fixes x\n  assumes \"unvisited_verts u U \\<noteq> {}\" and \"x = nearest_vert w u U\"\n  shows \"x \\<in> unvisited_verts u U\"\n    and \"\\<forall>y \\<in> unvisited_verts u U. \\<mu> w u y \\<ge> \\<mu> w u x\"\nproof -\n  define nv where \"nv \\<equiv> \\<lambda>x. x \\<in> unvisited_verts u U\n    \\<and> (\\<forall>y\\<in>unvisited_verts u U. \\<mu> w u x \\<le> \\<mu> w u y)\"\n\n  from ex_unvis_vert[OF assms(1)]\n  obtain x' where \"nv x'\" unfolding nv_def\n    by blast\n  then have \"nv (SOME x. nv x)\" using some_eq_ex by blast\n  with assms(2) have \"nv x\" unfolding nearest_vert_def nv_def by blast\n  then show\n    \"x \\<in> unvisited_verts u U\" and\n    \"\\<forall>y \\<in> unvisited_verts u U. \\<mu> w u y \\<ge> \\<mu> w u x\"\n    unfolding nv_def by blast+\nqed\n\nlemma nearest_vert_unvis: \"unvisited_verts u U \\<noteq> {}\n  \\<Longrightarrow> nearest_vert w u U \\<in> unvisited_verts u U\"\n  using some_unvis_vert by simp\n\nlemma nearest_vert_not_mem: \"unvisited_verts u U \\<noteq> {}\n  \\<Longrightarrow> nearest_vert w u U \\<notin> U\"\n  using disj_unvis_vis some_unvis_vert(1) by fastforce\n\nlemma nearest_vert_reachable: \"unvisited_verts u U \\<noteq> {}\n  \\<Longrightarrow> u \\<rightarrow>\\<^sup>* nearest_vert w u U\"\n  using some_unvis_vert(1) unvisited_verts_def by auto\n\nlemma nnvs_card_ge_n: \"\\<lbrakk> n_nearest_verts w u n U; unvisited_verts u U \\<noteq> {} \\<rbrakk>\n  \\<Longrightarrow> card U \\<ge> Suc n\"\nproof(induction rule: n_nearest_verts.induct)\n  case (n_nnvs_unvis w u n U)\n  have \"nearest_vert w u U \\<notin> U\"\n    using nearest_vert_unvis[OF n_nnvs_unvis.hyps(2)] disj_unvis_vis by auto\n  then have \"card (insert (nearest_vert w u U) U) = Suc (card U)\"\n    using n_nnvs_unvis.hyps(1) nnvs_finite by auto\n  with n_nnvs_unvis.IH[OF n_nnvs_unvis.hyps(2)] show ?case by simp\nqed simp_all\n\ncorollary nnvs_card_eq_n: \"\\<lbrakk> n_nearest_verts w u n U; unvisited_verts u U \\<noteq> {} \\<rbrakk>\n  \\<Longrightarrow> card U = Suc n\"\n  using nnvs_card_le_n nnvs_card_ge_n le_antisym by blast\n\n\nsubsubsection \\<open>Reachability and n-nearest vertices\\<close>\n\nlemma reachable_subs_nnvs: \"\\<lbrakk> u \\<in> verts G; Suc n \\<le> card {x. u \\<rightarrow>\\<^sup>* x} \\<rbrakk>\n \\<Longrightarrow> \\<exists>A \\<subseteq> {x. u \\<rightarrow>\\<^sup>* x}. card A = Suc n \\<and> n_nearest_verts w u n A\"\nproof(induction n)\n  case 0\n  then have \"{u} \\<subseteq> {x. u \\<rightarrow>\\<^sup>* x}\" by simp\n  with zero_nnvs[OF \\<open>u \\<in> verts G\\<close>] show ?case\n    by (metis card_Suc_eq card.empty empty_iff)\nnext\n  case (Suc n)\n  from Suc.IH[OF Suc.prems(1)] obtain A\n    where \"A \\<subseteq> {a. u \\<rightarrow>\\<^sup>* a}\" and \"card A = Suc n\" and \"n_nearest_verts w u n A\"\n    using Suc.prems(2) Suc_leD by blast\n  note A = this\n\n  show ?case\n  proof(cases \"Suc n = card {a. u \\<rightarrow>\\<^sup>* a}\")\n    case True\n    with A Suc.prems(2) show ?thesis by linarith\n  next\n    case False\n    with Suc.prems(2) have \"Suc n < card {a. u \\<rightarrow>\\<^sup>* a}\" by simp\n    with A have \"\\<exists>x \\<in> {a. u \\<rightarrow>\\<^sup>* a}. x \\<notin> A\"\n      using subset_antisym by fastforce\n    then have unvis_non_empty: \"unvisited_verts u A \\<noteq> {}\"\n      unfolding unvisited_verts_def using reachable_in_verts(2) by auto\n\n    let ?A' = \"insert (nearest_vert w u A) A\"\n\n    note n_nnvs_unvis[OF A(3) unvis_non_empty]\n    moreover\n    from A(1) have \"?A' \\<subseteq> {a. u \\<rightarrow>\\<^sup>* a}\"\n      using some_unvis_vert[OF unvis_non_empty]\n      by (simp add: unvisited_verts_def)\n    moreover\n    note nearest_vert_not_mem[OF unvis_non_empty]\n    with A(2) card.insert[OF nnvs_finite[OF A(3)]] nnvs_finite\n    have \"card ?A' = Suc (Suc n)\" by auto\n\n    ultimately show ?thesis by blast\n  qed\nqed\n\ncorollary all_reachable_eq_nnvs: \"\\<lbrakk> U = {x. u \\<rightarrow>\\<^sup>* x}; card U = Suc n \\<rbrakk>\n \\<Longrightarrow> n_nearest_verts w u n U\"\n  using reachable_subs_nnvs reachable_verts_finite reachable_in_verts(1)\n  by (metis card_Suc_eq card_subset_eq insertI1 le_Suc_eq mem_Collect_eq)\n\nlemma all_reachable_eq_nnvs_Suc:\n  assumes \"u \\<in> verts G\" and \"U = {x. u \\<rightarrow>\\<^sup>* x}\" and \"Suc n \\<ge> card U\"\n  shows \"n_nearest_verts w u n U\"\nproof -\n  note * = all_reachable_eq_nnvs le_Suc_eq\n  show ?thesis using assms\n  proof(induction n)\n    case 0\n    then show ?case using * reachable_verts_finite by auto\n  next\n    case (Suc n)\n    then show ?case using  * n_nnvs_vis unvis_empty by auto\n  qed\nqed\n\n\nlemma nnvs_imp_reachable:\"\\<lbrakk> n_nearest_verts w u n A; Suc n \\<le> card {x. u \\<rightarrow>\\<^sup>* x} \\<rbrakk>\n \\<Longrightarrow> A \\<subseteq> {x. u \\<rightarrow>\\<^sup>* x} \\<and> card A = Suc n\"\nproof(induction rule: n_nearest_verts.induct)\n  case (zero_nnvs u)\n  then show ?case using nearest_vert_reachable by simp\nnext\n  case (n_nnvs_unvis w u n U)\n  then show ?case using nearest_vert_reachable\n    by (simp add: nearest_vert_not_mem nnvs_finite)\nnext\n  case (n_nnvs_vis w u n U)\n  from n_nnvs_vis.hyps(2) have \"{a. u \\<rightarrow>\\<^sup>* a} \\<subseteq> U\"\n    unfolding unvisited_verts_def using reachable_in_verts(2) by auto\n  moreover\n  from n_nnvs_vis have \"U \\<subseteq> {a. u \\<rightarrow>\\<^sup>* a}\"\n    using Suc_leD by blast\n  ultimately show ?case\n    using n_nnvs_vis by auto\nqed\n\ncorollary nnvs_imp_all_reachable:\n  \"\\<lbrakk> n_nearest_verts w u n U; Suc n = card {x. u \\<rightarrow>\\<^sup>* x} \\<rbrakk>\n  \\<Longrightarrow> U = {x. u \\<rightarrow>\\<^sup>* x}\"\n  using nnvs_imp_reachable\n  by (simp add: card_subset_eq reachable_verts_finite)\n\nlemma nnvs_imp_all_reachable_Suc:\n  assumes \"n_nearest_verts w u n U\"  \"Suc n \\<ge> card {x. u \\<rightarrow>\\<^sup>* x}\"\n  shows \"U = {x. u \\<rightarrow>\\<^sup>* x}\"\n  using assms\nproof(induction rule: n_nearest_verts.induct)\n  case (zero_nnvs u)\n  have u_mem: \"u \\<in> {a. u \\<rightarrow>\\<^sup>* a}\" by (simp add: zero_nnvs.hyps)\n  moreover\n  from u_mem have \"card {a. u \\<rightarrow>\\<^sup>* a} = 1\"\n    using le_Suc_eq reachable_verts_finite zero_nnvs.prems by force\n  ultimately show ?case by (metis card_1_singletonE singletonD)\nnext\n  case (n_nnvs_unvis w u n U)\n  then show ?case\n    by (metis le_Suc_eq n_nearest_verts.n_nnvs_unvis\n        nnvs_imp_all_reachable unvis_empty)\nnext\n  case (n_nnvs_vis w u n U)\n  then show ?case\n    by (metis le_Suc_eq n_nearest_verts.n_nnvs_vis\n        nnvs_imp_all_reachable)\nqed\n\nlemma nnvs_subs_verts: \"n_nearest_verts w u n U \\<Longrightarrow> U \\<subseteq> verts G\"\nproof(induction rule: n_nearest_verts.induct)\n  case (n_nnvs_unvis w u n U)\n  then have \"nearest_vert w u U \\<in> unvisited_verts u U\"\n    by (simp add: nearest_vert_unvis)\n  then have \"nearest_vert w u U \\<in> verts G\"\n    unfolding unvisited_verts_def by simp\n  with n_nnvs_unvis show ?case by blast\nqed auto\n\nsubsubsection \\<open>Relation between n-nearest vertices and k-neighborhood\\<close>\n\n\nlemma unvis_nearest_vert_contr:\n  \"\\<lbrakk> n_nearest_verts w u n U; x \\<in> U; x \\<noteq> u; y \\<in> unvisited_verts u U; \\<mu> w u y < \\<mu> w u x \\<rbrakk>\n  \\<Longrightarrow> False\"\nproof(induction rule: n_nearest_verts.induct)\n  case (n_nnvs_unvis w u n U)\n  then obtain x where x: \"x \\<in> insert (nearest_vert w u U) U - {u}\"\n    \"\\<exists>y\\<in>unvisited_verts u (insert (nearest_vert w u U) U). \\<mu> w u y < \\<mu> w u x\" by blast\n  then show ?case\n  proof(cases \"x = nearest_vert w u U\")\n    case True\n    with n_nnvs_unvis x show ?thesis\n      using some_unvis_vert unvis_insert by (metis DiffD1 not_le)\n  next\n    case False\n    with n_nnvs_unvis x show ?thesis\n      using unvis_insert by (auto, metis not_le some_unvis_vert(2))\n  qed\nqed blast\n\nlemma nnvs_subs_k_nh:\n  assumes nnvs: \"n_nearest_verts w u n U\"\n      and card_N: \"card (k_neighborhood w u k) \\<ge> n\"\n    shows \"U - {u} \\<subseteq> k_neighborhood w u k\"\nproof -\n  from nnvs_card_le_n[OF nnvs] have card_U: \"card (U - {u}) \\<le> n\"\n    using nnvs_mem[OF nnvs] nnvs_finite[OF nnvs] by auto\n  show ?thesis\n  proof(rule ccontr, auto, rule ccontr)\n    fix x assume x: \"x \\<in> U\" \"x \\<notin> k_neighborhood w u k\" \"x \\<noteq> u\"\n    then have \"{x, u} \\<subseteq> U\" using nnvs_mem[OF nnvs] by auto\n    from card_mono[OF nnvs_finite[OF nnvs], OF this] have \"card U \\<ge> 2\"\n      using x(3) by auto\n    then have \"card (U - {u} - {x}) < card (U - {u})\"\n      using nnvs nnvs_finite nnvs_mem x(1,3) by auto\n    also have \"\\<dots> \\<le> card (k_neighborhood w u k)\"\n      using card_N card_U by linarith\n    finally have \"card (U - {u} - {x}) < card (k_neighborhood w u k)\" .\n    then obtain y where y: \"y \\<in> k_neighborhood w u k\" \"y \\<notin> U - {u} - {x}\"\n      using nnvs_finite[OF nnvs] by (meson card_mono finite_Diff not_le subset_iff)\n    from k_nh_reachable[OF y(1)] y x(2) have y_unvis: \"y \\<in> unvisited_verts u U\"\n      unfolding unvisited_verts_def k_neighborhood_def by blast\n\n    from y have \"\\<mu> w u y \\<le> k\" unfolding k_neighborhood_def by simp\n    moreover\n    from x have \"\\<mu> w u x > k\" unfolding k_neighborhood_def\n      using nnvs_subs_verts[OF nnvs] by fastforce\n    ultimately have \"\\<mu> w u y < \\<mu> w u x\" by simp\n    from unvis_nearest_vert_contr[OF nnvs \\<open>x \\<in> U\\<close> \\<open>x \\<noteq> u\\<close> y_unvis this] show \"False\" .\n  qed\nqed\n\nlemma k_nh_subs_nnvs:\n  assumes nnvs: \"n_nearest_verts w u n U\"\n      and card_nh: \"card (k_neighborhood w u k) < card U\"\n    shows \"k_neighborhood w u k \\<subseteq> U\"\nproof(rule ccontr)\n  assume \"\\<not> k_neighborhood w u k \\<subseteq> U\"\n  then obtain v where v: \"v \\<in> verts G\" \"v \\<noteq> u\" \"\\<mu> w u v \\<le> k\" \"v \\<notin> U\"\n    unfolding k_neighborhood_def by auto\n  then have v_unvis: \"v \\<in> unvisited_verts u U\"\n    unfolding unvisited_verts_def\n    using \\<mu>_reach_conv[of w u v] PInfty_neq_ereal(1)[of k] by force\n\n  let ?close_verts = \"{v \\<in> verts G. \\<mu> w u v \\<le> k} - {u}\"\n  let ?far_verts = \"{v \\<in> verts G. \\<mu> w u v > k} - {u}\"\n\n  have vert_part: \"verts G - {u} = ?close_verts \\<union> ?far_verts\"\n    \"?close_verts \\<inter> ?far_verts = {}\" by auto\n  with finite_verts have \"finite ?close_verts\" and \"finite ?far_verts\"\n    by auto\n\n  have \"card (k_neighborhood w u k) \\<le> card (U - {u})\"\n    using card_nh nnvs nnvs_finite nnvs_mem by auto\n  then have \"card ?close_verts \\<le> card (U - {u})\"\n    unfolding k_neighborhood_def\n    by (cases \"\\<mu> w u u \\<le> k\") (auto simp: insert_absorb source_mem_nnvs[OF nnvs])\n\n  have \"?far_verts \\<inter> (U - {u}) \\<noteq> {}\"\n  proof(rule ccontr, simp)\n    assume \"?far_verts \\<inter> (U - {u}) = {}\"\n    then have \"U - {u} \\<subseteq> ?close_verts\"\n      using nnvs_subs_verts[OF nnvs] by auto\n    then have \"card (U - {u}) \\<le> card ?close_verts\"\n      by (simp add: card_mono)\n    with \\<open>card ?close_verts \\<le> card (U - {u})\\<close> have \"?close_verts = U - {u}\"\n      using card_seteq[OF \\<open>finite ?close_verts\\<close> \\<open>U - {u} \\<subseteq> ?close_verts\\<close>]\n      by blast\n    then show \"False\" using v by auto\n  qed\n  then obtain x where x: \"x \\<in> ?far_verts\" \"x \\<in> U\" \"x \\<noteq> u\"\n    by auto\n  then have \"\\<mu> w u v < \\<mu> w u x\" using \\<open>\\<mu> w u v \\<le> k\\<close> by auto\n  from unvis_nearest_vert_contr[OF nnvs x(2,3) v_unvis this]\n  show \"False\" .\nqed\n\nend\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Query_Optimization/Graph_Definitions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7736658830549455}}
{"text": "theory Ch02\n  imports Main\nbegin\n\n(* Exercise 2.1 *)\nvalue \"1 + (2 :: nat)\"\nvalue \"1 + (2 :: int)\"\nvalue \"(1 - (2 :: nat))\"\nvalue \"1 - (2 :: int)\"\nvalue \"[a,b] @ [c,d]\"\n\n(* Exercise 2.2 *)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc (add m  n)\"\n\n\n\nlemma add_0[simp]: \"add n 0 = n\"\n  apply (induction n)\n  apply (auto)\n  done\n\nlemma add_succ[simp]: \"add n (Suc m) = Suc (add n m)\"\n  apply (induction n)\n  apply (auto)\n  done\n\nlemma add_comm: \"add m n = add n m\"\n  apply (induction m)\n  apply (auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc n) = Suc (Suc (double n))\"\n\nvalue \"double 42\"\n\nlemma double_add: \"double m = add m m\"\n  apply (induction m)\n  apply (auto)\n  done\n\n(* Exercise 2.3 *)\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n\"count [] n = 0\" |\n\"count (x # xs) n = (if x = n then Suc (count xs n) else count xs n)\"\n\ntheorem \"count xs x \\<le> length xs\"\n  apply (induction xs)\n  apply (auto)\n  done\n\n(* Exercise 2.4 *)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] y = [y]\" |\n\"snoc (x # xs) y = x # snoc xs y\"\n\nvalue \"snoc [] a\"\nvalue \"snoc [a,b,c,d] e\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\" |\n\"reverse (x # xs) = snoc (reverse xs) x\"\n\nvalue \"rerverse []\"\nvalue \"reverse [a,b,c]\"\n\nlemma rev_snoc[simp]: \"reverse (snoc xs x) = x # reverse xs\"\n  apply (induction xs)\n  apply (auto)\n  done\n\ntheorem \"reverse (reverse xs) = xs\"\n  apply (induction xs)\n  apply (auto)\n  done\n\n(* Exercise 2.5 *)\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\" |\n\"sum_upto (Suc n) = (Suc n) + (sum_upto n)\"\n\nvalue \"(sum_upto 3)\"\nvalue \"(sum_upto 10)\"\n\nlemma \"sum_upto n = n * (n+1) div 2\"\n  apply (induction n)\n  apply (auto)\n  done\n\n(* Exercise 2.6 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nvalue \"(Node (Node Tip a Tip) b (Node Tip c Tip))\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node t1 x t2) = x # (contents t1) @ (contents t2)\"\n\nvalue \"contents ((Node (Node Tip a Tip) b (Node Tip c Tip)))\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node t1 x t2) = x + (sum_tree t1) + (sum_tree t2)\"\n\nvalue \"sum_tree (Node (Node Tip 1 Tip) 2 (Node Tip 3 Tip))\"\n\nlemma \"sum_tree t = sum_list (contents t)\"\n  apply (induction t)\n  apply (auto)\n  done\n\n(* Exercise 2.7 *)\ndatatype 'a tree2 = Leaf 'a | Node \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror (Leaf x) = Leaf x\" |\n\"mirror (Node t1 x t2) = Node (mirror t2) x (mirror t1)\"\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order (Leaf x) = [x]\" |\n\"pre_order (Node t1 x t2) = x # pre_order t1 @ pre_order t2\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Leaf x) = [x]\" |\n\"post_order (Node t1 x t2) = post_order t1 @ post_order t2 @ [x]\"\n\nlemma \"pre_order (mirror t) = rev (post_order t)\"\n  apply (induction t)\n  apply (auto)\n  done\n\n(* Exercise 2.8 *)\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse x [] = []\" |\n\"intersperse x (y # ys) = [y, x] @ intersperse x ys\"\n\nvalue \"intersperse a [a,b,c]\"\nvalue \"intersperse 1 [1,2,3] :: int list\"\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply (induction xs)\n  apply (auto)\n  done\n\n(* Exercise 2.9 *)\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 n = n\" |\n\"itadd (Suc m) n = itadd m (Suc n)\"\n\nlemma \"itadd m n = add m n\"\n  apply (induction m arbitrary: n)\n  apply (auto)\n  done\n\n(* Exercise 2.10 *)\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 1\" |\n\"nodes (Node t1 t2) = 1 + (nodes t1) + (nodes t2)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\n(* Exercise 2.11 *)\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var n = n\" |\n\"eval (Const c) _ = c\" |\n\"eval (Add l r) n = (eval l n) + (eval r n)\" |\n\"eval (Mult l r) n = (eval l n) * (eval r n)\"\n\nvalue \"eval (Add (Mult (Const 2) Var) (Const 3)) i\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] _ = 0\" |\n\"evalp [a0] _ = a0\" |\n\"evalp (ai # as) x = ai + x * (evalp as x)\"\n\nvalue \"evalp [4,2,-1,3] 2\"\n\n(* TODO: fun coeffs :: \"exp \\<Rightarrow> int list\" *)\n\n(* TODO: theorem evalp_coeffs: \"evalp (coeffs e) x = eval e x\" *)\n\nend\n", "meta": {"author": "waynee95", "repo": "isabelle-exercises", "sha": "cfb5a4d031e5da799fcec87d5987e849219e8124", "save_path": "github-repos/isabelle/waynee95-isabelle-exercises", "path": "github-repos/isabelle/waynee95-isabelle-exercises/isabelle-exercises-cfb5a4d031e5da799fcec87d5987e849219e8124/Ch02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7736387860534479}}
{"text": "theory primes_mod_four\nimports \"Main\"\n        \"HOL-Computational_Algebra.Primes\"\nbegin \n\nlemma aux1: \n  fixes m k :: \"nat\"\n  assumes \"(m * k) mod 4 = 3\"\n  shows \"m mod 4 = 3 \\<or> k mod 4 = 3\"\n  by (smt One_nat_def add_Suc_right assms mod_double_modulus mod_mod_trivial \n       mod_mult_right_eq mult.right_neutral mult_0_right mult_2_right \n       not_mod2_eq_Suc_0_eq_0 numeral_2_eq_2 numeral_3_eq_3 \n       numeral_Bit0 one_add_one zero_le zero_less_Suc zero_neq_numeral)\n\n\\<comment> \\<open>an alternative proof\\<close> \nlemma aux1': \n  fixes m k :: \"nat\"\n  assumes \"(m * k) mod 4 = 3\"\n  shows \"m mod 4 = 3 \\<or> k mod 4 = 3\"\nproof (rule ccontr)\n  assume \"\\<not> (m mod 4 = 3 \\<or> k mod 4 = 3)\"\n  moreover have \"m mod 4 = 0 \\<or> m mod 4 = 1 \\<or> m mod 4 = 2 \\<or> m mod 4 = 3\"\n    by linarith\n  moreover have \"k mod 4 = 0 \\<or> k mod 4 = 1 \\<or> k mod 4 = 2 \\<or> k mod 4 = 3\"\n    by linarith\n  moreover have \"(m * k) mod 4 = ((m mod 4) * (k mod 4)) mod 4\"\n    by (simp add: mod_mult_eq)\n  ultimately show False\n    using \\<open>(m * k) mod 4 = 3\\<close> by auto\nqed\n\nlemma aux2:\n  fixes n :: \"nat\"\n  shows \"n mod 4 = 3 \\<longrightarrow> (\\<exists> p. prime p \\<and> p dvd n \\<and> p mod 4 = 3)\"\nproof (induct n rule: less_induct)\n  case (less n)\n  then have IH: \"\\<And> m. m < n \\<Longrightarrow> m mod 4 = 3 \\<longrightarrow> \n                    (\\<exists> p. prime p \\<and> p dvd m \\<and> p mod 4 = 3)\" by simp\n  show \"n mod 4 = 3 \\<longrightarrow> (\\<exists> p. prime p \\<and> p dvd n \\<and> p mod 4 = 3)\" \n  proof (clarify)\n    assume h: \"n mod 4 = 3\"\n    show \"(\\<exists> p. prime p \\<and> p dvd n \\<and> p mod 4 = 3)\"\n    proof cases\n      assume \"prime n\"\n      with h show ?thesis by auto\n    next\n      assume \"\\<not> prime n\"\n      moreover from h have \"n \\<ge> 2\" by linarith\n      ultimately obtain m k where \"m < n\" and \"k < n\" and \"n = m * k\"\n        by (metis Suc_1 dvd_def dvd_imp_le le_neq_implies_less \n              less_le_trans mult.commute mult.right_neutral \n              nat_mult_eq_cancel_disj prime_nat_naiveI zero_less_Suc)       \n      have \"m mod 4 = 3 \\<or> k mod 4 = 3\"\n        using \\<open>n = m * k\\<close> aux1 h by blast\n      show \"\\<exists>p. prime p \\<and> p dvd n \\<and> p mod 4 = 3\"\n        using IH \\<open>k < n\\<close> \\<open>m < n\\<close> \\<open>m mod 4 = 3 \\<or> k mod 4 = 3\\<close> \\<open>n = m * k\\<close>\n              prime_dvd_mult_eq_nat by blast\n    qed\n  qed\nqed\n\ntheorem infinite_primes_three_mod_four: \"infinite {p :: nat. prime p \\<and> p mod 4 = 3}\"\nproof\n  let ?S = \"{p :: nat. prime p \\<and> p mod 4 = 3}\"\n  assume fS: \"finite ?S\"\n  let ?u = \"4 * (\\<Prod> x \\<in> ?S. x) - 1\"\n  have h1: \"(\\<Prod> x \\<in> ?S. x) \\<ge> 1\"\n    by (metis (no_types, lifting) mem_Collect_eq prime_ge_1_nat prod_ge_1)\n  hence h2: \"(\\<Prod> x \\<in> ?S. x) = (\\<Prod> x \\<in> ?S. x) - 1 + 1\"\n    by linarith \n  have \"?u mod 4 = 3\"\n    by (subst h2) (simp add: ring_distribs)\n  then obtain p where \"prime p\" and \"p dvd ?u\" and \"p mod 4 = 3\"\n    using aux2 by blast\n  have \"p \\<notin> ?S\"\n  proof\n    assume \"p \\<in> ?S\"\n    hence \"p dvd 4 * (\\<Prod> x \\<in> ?S. x)\"\n      by (simp add: dvd_prod_eqI fS)\n    with \\<open>p dvd ?u\\<close> have \"p dvd 1\"\n      by (metis (no_types, lifting) dvd_diffD1 h1 less_one \n          mult_eq_0_iff not_le zero_neq_numeral)\n    thus False\n      using \\<open>prime p\\<close> not_prime_unit by blast\n  qed\n  moreover with \\<open>prime p\\<close> \\<open>p mod 4 = 3\\<close> have \"p \\<in> ?S\" by auto\n  ultimately show False by simp\nqed\n\nend", "meta": {"author": "avigad", "repo": "arwm", "sha": "c5e9654a07c7ec0b03959fce0ea98e0f9e76ce49", "save_path": "github-repos/isabelle/avigad-arwm", "path": "github-repos/isabelle/avigad-arwm/arwm-c5e9654a07c7ec0b03959fce0ea98e0f9e76ce49/isabelle_experiments/primes_mod_four.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7736387844137822}}
{"text": "(*\n  File:    Triangle.thy\n  Author:  Manuel Eberl <eberlm@in.tum.de>\n\n  Sine and cosine laws, angle sum in a triangle, congruence theorems,\n  Isosceles Triangle Theorem\n*)\n\nsection \\<open>Basic Properties of Triangles\\<close>\ntheory Triangle\nimports\n  Angles\nbegin\n\ntext \\<open>\n  We prove a number of basic geometric properties of triangles. All theorems hold\n  in any real inner product space.\n\\<close>\nsubsection \\<open>Thales' theorem\\<close>\n\ntheorem thales:\n  fixes A B C :: \"'a :: real_inner\"\n  assumes \"dist B (midpoint A C) = dist A C / 2\"\n  shows   \"orthogonal (A - B) (C - B)\"\nproof -\n  have \"dist A C ^ 2 = dist B (midpoint A C) ^ 2 * 4\"\n    by (subst assms) (simp add: field_simps power2_eq_square)\n  thus ?thesis\n    by (auto simp: orthogonal_def dist_norm power2_norm_eq_inner midpoint_def\n                   algebra_simps inner_commute)\nqed\n\nsubsection \\<open>Sine and cosine laws\\<close>\n\ntext \\<open>\n  The proof of the Law of Cosines follows trivially from the definition of the angle,\n  the definition of the norm in vector spaces with an inner product and the bilinearity\n  of the inner product.\n\\<close>\n\nlemma cosine_law_vector:\n  \"norm (u - v) ^ 2 = norm u ^ 2 + norm v ^ 2 - 2 * norm u * norm v * cos (vangle u v)\"\n  by (simp add: power2_norm_eq_inner cos_vangle algebra_simps inner_commute)\n\nlemma cosine_law_triangle:\n  \"dist b c ^ 2 = dist a b ^ 2 + dist a c ^ 2 - 2 * dist a b * dist a c * cos (angle b a c)\"\n  using cosine_law_vector[of \"b - a\" \"c - a\"]\n  by (simp add: dist_norm angle_def vangle_commute norm_minus_commute)\n\n\ntext \\<open>\n  According to our definition, angles are always between $0$ and $\\pi$ and therefore,\n  the sign of an angle is always non-negative. We can therefore look at\n  $\\sin(\\alpha)^2$, which we can express in terms of $\\cos(\\alpha)$ using the\n  identity $\\sin(\\alpha)^2 + \\cos(\\alpha)^2 = 1$. The remaining proof is then a\n  trivial consequence of the definitions.\n\\<close>\nlemma sine_law_triangle:\n  \"sin (angle a b c) * dist b c = sin (angle b a c) * dist a c\" (is \"?A = ?B\")\nproof (cases \"a = b\")\n  assume neq: \"a \\<noteq> b\"\n  show ?thesis\n  proof (rule power2_eq_imp_eq)\n    from neq have \"(sin (angle a b c) * dist b c) ^ 2 * dist a b ^ 2 =\n                     dist a b ^ 2 * dist b c ^ 2 - ((a - b) \\<bullet> (c - b)) ^ 2\"\n      by (simp add: sin_squared_eq cos_angle dist_commute field_simps)\n    also have \"\\<dots> = dist a b ^ 2 * dist a c ^ 2 - ((b - a) \\<bullet> (c - a)) ^ 2\"\n      by (simp only: dist_norm power2_norm_eq_inner)\n         (simp add: power2_eq_square algebra_simps inner_commute)\n    also from neq have \"\\<dots> = (sin (angle b a c) * dist a c) ^ 2 * dist a b ^ 2\"\n      by (simp add: sin_squared_eq cos_angle dist_commute field_simps)\n    finally show \"?A^2 = ?B^2\" using neq by (subst (asm) mult_cancel_right) simp_all\n  qed (auto intro!: mult_nonneg_nonneg sin_angle_nonneg)\nqed simp_all\n\n\ntext \\<open>\n  The following forms of the Law of Sines/Cosines are more convenient for eliminating\n  sines/cosines from a goal completely.\n\\<close>\n\nlemma cosine_law_triangle':\n  \"2 * dist a b * dist a c * cos (angle b a c) = (dist a b ^ 2 + dist a c ^ 2 - dist b c ^ 2)\"\n  using cosine_law_triangle[of b c a] by simp\n\nlemma cosine_law_triangle'':\n  \"cos (angle b a c) = (dist a b ^ 2 + dist a c ^ 2 - dist b c ^ 2) / (2 * dist a b * dist a c)\"\n  using cosine_law_triangle[of b c a] by simp\n\nlemma sine_law_triangle':\n  \"b \\<noteq> c \\<Longrightarrow> sin (angle a b c) = sin (angle b a c) * dist a c / dist b c\"\n  using sine_law_triangle[of a b c] by (simp add: divide_simps)\n\nlemma sine_law_triangle'':\n  \"b \\<noteq> c \\<Longrightarrow> sin (angle c b a) = sin (angle b a c) * dist a c / dist b c\"\n  using sine_law_triangle[of a b c] by (simp add: divide_simps angle_commute)\n\n\nsubsection \\<open>Sum of angles\\<close>\n\ncontext\nbegin\n\nprivate lemma gather_squares: \"a * (a * b) = a^2 * (b :: real)\"\n  by (simp_all add: power2_eq_square)\n\nprivate lemma eval_power: \"x ^ numeral n = x * x ^ pred_numeral n\"\n  by (subst numeral_eq_Suc, subst power_Suc) simp\n\ntext \\<open>\n  The proof that the sum of the angles in a triangle is $\\pi$ is somewhat more\n  involved. Following the HOL Light proof by John Harrison, we first prove\n  that $\\cos(\\alpha + \\beta + \\gamma) = -1$ and $\\alpha + \\beta + \\gamma \\in [0;3\\pi)$,\n  which then implies the theorem.\n\n  The main work is proving $\\cos(\\alpha + \\beta + \\gamma)$. This is done using the\n  addition theorems for the sine and cosine, then using the Laws of Sines to eliminate\n  all $\\sin$ terms save $\\sin(\\gamma)^2$, which only appears squared in the remaining goal.\n  We then use $\\sin(\\gamma)^2 = 1 - \\cos(\\gamma)^2$ to eliminate this term and apply\n  the law of cosines to eliminate this term as well.\n\n  The remaining goal is a non-linear equation containing only the length of the sides\n  of the triangle. It can be shown by simple algebraic rewriting.\n\\<close>\nlemma angle_sum_triangle:\n  assumes \"a \\<noteq> b \\<or> b \\<noteq> c \\<or> a \\<noteq> c\"\n  shows   \"angle c a b + angle a b c + angle b c a = pi\"\nproof (rule cos_minus1_imp_pi)\n  show \"cos (angle c a b + angle a b c + angle b c a) = - 1\"\n  proof (cases \"a \\<noteq> b\")\n    case True\n    thus \"cos (angle c a b + angle a b c + angle b c a) = -1\"\n      apply (simp add: cos_add sin_add cosine_law_triangle'' field_simps\n                       sine_law_triangle''[of a b c] sine_law_triangle''[of b a c]\n                       angle_commute dist_commute gather_squares sin_squared_eq)\n      apply (simp add: eval_power algebra_simps dist_commute)\n      done\n  qed (insert assms, auto)\n\n  show \"angle c a b + angle a b c + angle b c a < 3 * pi\"\n  proof (rule ccontr)\n    assume \"\\<not>(angle c a b + angle a b c + angle b c a < 3 * pi)\"\n    with angle_le_pi[of c a b] angle_le_pi[of a b c] angle_le_pi[of b c a]\n      have A: \"angle c a b = pi\" \"angle a b c = pi\" by simp_all\n    thus False using angle_eq_pi_imp_dist_additive[of c a b]\n                     angle_eq_pi_imp_dist_additive[of a b c] by (simp add: dist_commute)\n  qed\nqed (auto intro!: add_nonneg_nonneg angle_nonneg)\n\nend\n\n\nsubsection \\<open>Congruence Theorems\\<close>\n\ntext \\<open>\n  If two triangles agree on two angles at a non-degenerate side, the third angle\n  must also be equal.\n\\<close>\nlemma similar_triangle_aa:\n  assumes \"b1 \\<noteq> c1\" \"b2 \\<noteq> c2\"\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  assumes \"angle b1 c1 a1 = angle b2 c2 a2\"\n  shows   \"angle b1 a1 c1 = angle b2 a2 c2\"\nproof -\n  from assms angle_sum_triangle[of a1 b1 c1] angle_sum_triangle[of a2 b2 c2, symmetric]\n    show ?thesis by (auto simp: algebra_simps angle_commute)\nqed\n\ntext \\<open>\n  A triangle is defined by its three angles and the lengths of three sides up to congruence.\n  Two triangles are congruent if they have their angles are the same and their sides have\n  the same length.\n\\<close>\n\nlocale congruent_triangle =\n  fixes a1 b1 c1 :: \"'a :: real_inner\" and a2 b2 c2 :: \"'b :: real_inner\"\n  assumes sides':  \"dist a1 b1 = dist a2 b2\" \"dist a1 c1 = dist a2 c2\" \"dist b1 c1 = dist b2 c2\"\n      and angles': \"angle b1 a1 c1 = angle b2 a2 c2\" \"angle a1 b1 c1 = angle a2 b2 c2\"\n                   \"angle a1 c1 b1 = angle a2 c2 b2\"\nbegin\n\n\n\nlemma angles:\n  \"angle b1 a1 c1 = angle b2 a2 c2\" \"angle a1 b1 c1 = angle a2 b2 c2\" \"angle a1 c1 b1 = angle a2 c2 b2\"\n  \"angle c1 a1 b1 = angle b2 a2 c2\" \"angle c1 b1 a1 = angle a2 b2 c2\" \"angle b1 c1 a1 = angle a2 c2 b2\"\n  \"angle b1 a1 c1 = angle c2 a2 b2\" \"angle a1 b1 c1 = angle c2 b2 a2\" \"angle a1 c1 b1 = angle b2 c2 a2\"\n  \"angle c1 a1 b1 = angle c2 a2 b2\" \"angle c1 b1 a1 = angle c2 b2 a2\" \"angle b1 c1 a1 = angle b2 c2 a2\"\n  using angles' by (simp_all add: angle_commute)\n\nend\n\nlemmas congruent_triangleD = congruent_triangle.sides congruent_triangle.angles\n\n\n\ntext \\<open>\n  Given two triangles that agree on a subset of its side lengths and angles that are\n  sufficient to define a triangle uniquely up to congruence, one can conclude that they\n  must also agree on all remaining quantities, i.e. that they are congruent.\n\n  The following four congruence theorems state what constitutes such a uniquely-defining\n  subset of quantities. Each theorem states in its name which quantities are required and\n  in which order (clockwise or counter-clockwise): an ``s'' stands for a side,\n  an ``a'' stands for an angle.\n\n  The lemma ``congruent-triangleI-sas, for example, requires that two adjacent sides and the\n  angle inbetween are the same in both triangles.\n\\<close>\n\nlemma congruent_triangleI_sss:\n  fixes a1 b1 c1 :: \"'a :: real_inner\" and a2 b2 c2 :: \"'b :: real_inner\"\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"dist b1 c1 = dist b2 c2\"\n  assumes \"dist a1 c1 = dist a2 c2\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof -\n  have A: \"angle a1 b1 c1 = angle a2 b2 c2\"\n    if \"dist a1 b1 = dist a2 b2\" \"dist b1 c1 = dist b2 c2\" \"dist a1 c1 = dist a2 c2\"\n    for a1 b1 c1 :: 'a and a2 b2 c2 :: 'b\n  proof -\n    from that cosine_law_triangle''[of a1 b1 c1] cosine_law_triangle''[of a2 b2 c2]\n      show ?thesis by (intro cos_angle_eqD) (simp add: dist_commute)\n  qed\n  from assms show ?thesis by unfold_locales (auto intro!: A simp: dist_commute)\nqed\n\nlemmas congruent_triangle_sss = congruent_triangleD[OF congruent_triangleI_sss]\n\nlemma congruent_triangleI_sas:\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"dist b1 c1 = dist b2 c2\"\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof (rule congruent_triangleI_sss)\n  show \"dist a1 c1 = dist a2 c2\"\n  proof (rule power2_eq_imp_eq)\n    from cosine_law_triangle[of a1 c1 b1] cosine_law_triangle[of a2 c2 b2] assms\n      show \"(dist a1 c1)\\<^sup>2 = (dist a2 c2)\\<^sup>2\" by (simp add: dist_commute)\n  qed simp_all\nqed fact+\n\nlemmas congruent_triangle_sas = congruent_triangleD[OF congruent_triangleI_sas]\n\nlemma congruent_triangleI_aas:\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  assumes \"angle b1 c1 a1 = angle b2 c2 a2\"\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"\\<not>collinear {a1,b1,c1}\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof (rule congruent_triangleI_sas)\n  from \\<open>\\<not>collinear {a1,b1,c1}\\<close> have neq: \"a1 \\<noteq> b1\" by auto\n  with assms(3) have neq': \"a2 \\<noteq> b2\" by auto\n  have A: \"angle c1 a1 b1 = angle c2 a2 b2\" using neq neq' assms\n    using angle_sum_triangle[of a1 b1 c1] angle_sum_triangle[of a2 b2 c2]\n    by simp\n  from assms have B: \"angle b1 a1 c1 \\<in> {0<..<pi}\"\n    by (intro not_collinear_angle) (simp_all add: insert_commute)\n  from sine_law_triangle[of c1 a1 b1] sine_law_triangle[of c2 a2 b2] assms A B\n    show \"dist b1 c1 = dist b2 c2\"\n    by (auto simp: angle_commute dist_commute sin_angle_zero_iff)\nqed fact+\n\nlemmas congruent_triangle_aas = congruent_triangleD[OF congruent_triangleI_aas]\n\nlemma congruent_triangleI_asa:\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"angle b1 a1 c1 = angle b2 a2 c2\"\n  assumes \"\\<not>collinear {a1, b1, c1}\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof (rule congruent_triangleI_aas)\n  from assms have neq: \"a1 \\<noteq> b1\" \"a2 \\<noteq> b2\" by auto\n  show \"angle b1 c1 a1 = angle b2 c2 a2\"\n    by (rule similar_triangle_aa) (insert assms neq, simp_all add: angle_commute)\nqed fact+\n\nlemmas congruent_triangle_asa = congruent_triangleD[OF congruent_triangleI_asa]\n\n\nsubsection \\<open>Isosceles Triangle Theorem\\<close>\n\ntext \\<open>\n  We now prove the Isosceles Triangle Theorem: in a triangle where two sides have\n  the same length, the two angles that are adjacent to only one of the two sides\n  must be equal.\n\\<close>\nlemma isosceles_triangle:\n  assumes \"dist a c = dist b c\"\n  shows   \"angle b a c = angle a b c\"\n  by (rule congruent_triangle_sss) (insert assms, simp_all add: dist_commute)\n\n\ntext \\<open>\n  For the non-degenerate case (i.e. the three points are not collinear), We also\n  prove the converse.\n\\<close>\nlemma isosceles_triangle_converse:\n  assumes \"angle a b c = angle b a c\" \"\\<not>collinear {a,b,c}\"\n  shows   \"dist a c = dist b c\"\n  by (rule congruent_triangle_asa[OF assms(1) _ _ assms(2)])\n     (simp_all add: dist_commute angle_commute assms)\n\n\nsubsection\\<open>Contributions by Lukas Bulwahn\\<close>\n  \nlemma Pythagoras:\n  fixes A B C :: \"'a :: real_inner\"\n  assumes \"orthogonal (A - C) (B - C)\"\n  shows \"(dist B C) ^ 2 + (dist C A) ^ 2 = (dist A B) ^ 2\"\nproof -\n  from assms have \"cos (angle A C B) = 0\"\n    by (metis orthogonal_iff_angle cos_pi_half)\n  from this show ?thesis\n    by (simp add: cosine_law_triangle[of A B C] dist_commute)\nqed\n\nlemma isosceles_triangle_orthogonal_on_midpoint:\n  fixes A B C :: \"'a :: euclidean_space\"\n  assumes \"dist C A = dist C B\"\n  shows \"orthogonal (C - midpoint A B) (A - midpoint A B)\"\nproof (cases \"A = B\")\n  assume \"A \\<noteq> B\"\n  let ?M = \"midpoint A B\"\n  from \\<open>A \\<noteq> B\\<close> have \"angle A ?M C = pi - angle B ?M C\"\n    by (intro angle_inverse between_midpoint)\n       (auto simp: between_midpoint eq_commute[of _ \"midpoint A B\" for A B])\n  moreover have \"angle A ?M C = angle C ?M B\"\n  proof -\n    have congruence: \"congruent_triangle C A ?M C B ?M\"\n    proof (rule congruent_triangleI_sss)\n      show \"dist C A = dist C B\" using assms .\n      show \"dist A ?M = dist B ?M\" by (simp add: dist_midpoint)\n      show \"dist C (midpoint A B) = dist C (midpoint A B)\" ..\n    qed\n    from this show ?thesis by (simp add: congruent_triangle.angles(6))\n  qed\n  ultimately have \"angle A ?M C = pi / 2\" by (simp add: angle_commute)\n  from this show ?thesis\n    by (simp add: orthogonal_iff_angle orthogonal_commute)\nnext\n  assume \"A = B\"\n  from this show ?thesis\n    by (simp add: orthogonal_clauses(1))\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Triangle/Triangle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680940822761, "lm_q2_score": 0.9019206811430763, "lm_q1q2_score": 0.7736387836774848}}
{"text": "section \"N-Permutations\"\n\ntheory n_Permutations\n  imports\n    \"HOL-Combinatorics.Multiset_Permutations\"\n    Common_Lemmas\n    \"Falling_Factorial_Sum.Falling_Factorial_Sum_Combinatorics\"\nbegin\nsubsection\"Definition\"\n\ndefinition n_permutations :: \"'a set \\<Rightarrow> nat \\<Rightarrow> 'a list set\" where\n  \"n_permutations A n = {xs. set xs \\<subseteq> A \\<and> distinct xs \\<and> length xs = n}\"\ntext \"Permutations with a maximum length. They are different from \\<open>HOL-Combinatorics.Multiset_Permutations\\<close>\nbecause the entries must all be distinct.\"\ntext \"Cardinality: \\<open>'falling factorial' (card A) n\\<close>\"\ntext \"Example: \\<open>n_permutations {0,1,2} 2 = {[0,1], [0,2], [1,0], [1,2], [2,0], [2,1]}\\<close>\"\n\nlemma \"permutations_of_set A \\<subseteq> n_permutations A (card A)\"\n  by (simp add: length_finite_permutations_of_set n_permutations_def permutations_of_setD subsetI)\n\n\nsubsection\"Algorithm\"\n(*algorithm for permutations with arbitrary length exists in HOL-Combinatorics.Multiset_Permutations*)\nfun n_permutation_enum :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list list\" where\n  \"n_permutation_enum xs 0 = [[]]\"\n| \"n_permutation_enum xs (Suc n) = [x#r . x \\<leftarrow> xs, r \\<leftarrow> n_permutation_enum (remove1 x xs) n]\"\n\nsubsection\"Verification\"\n\nsubsubsection\"Correctness\"\n\nlemma n_permutation_enum_subset: \"ys \\<in> set (n_permutation_enum xs n) \\<Longrightarrow> set ys \\<subseteq> set xs \"\nproof(induct n arbitrary: ys xs)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  obtain x where o1: \"x\\<in>set xs\" and o2: \" ys \\<in> (#) x ` set (n_permutation_enum (remove1 x xs) n)\"\n    using Suc by auto\n\n  have \"y \\<in> set (n_permutation_enum (remove1 x xs) n) \\<Longrightarrow> set y \\<subseteq> set xs\" for y\n    using Suc set_remove1_subset by fast\n    \n  then show ?case using o1 o2\n    by fastforce\nqed\n\nlemma n_permutation_enum_length: \"ys \\<in> set (n_permutation_enum xs n) \\<Longrightarrow> length ys = n\"\n  by (induct n arbitrary: ys xs) auto\n\nlemma n_permutation_enum_elem_distinct: \"distinct xs \\<Longrightarrow> ys \\<in> set (n_permutation_enum xs n) \\<Longrightarrow> distinct ys\"\nproof (induct n arbitrary: ys xs)\n  case 0\n  then show ?case \n    by simp\nnext\n  case (Suc n)\n  then obtain z zs where o: \"ys = z # zs\"\n    by auto\n  from this Suc have t: \"zs \\<in> set (n_permutation_enum (remove1 z xs) n)\"\n    by auto\n\n  then have \"distinct zs\"\n    using Suc distinct_remove1 by fast\n\n  also have \"z \\<notin> set zs\"\n    using o t n_permutation_enum_subset Suc by fastforce\n\n  ultimately show ?case\n    using o by simp\nqed\n\nlemma n_permutation_enum_correct1: \"distinct xs \\<Longrightarrow> set (n_permutation_enum xs n) \\<subseteq> n_permutations (set xs) n\"\n  unfolding n_permutations_def\n  using n_permutation_enum_subset n_permutation_enum_elem_distinct n_permutation_enum_length\n  by fast\n\nlemma n_permutation_enum_correct2: \"ys \\<in> n_permutations (set xs) n \\<Longrightarrow> ys \\<in> set (n_permutation_enum xs n)\"\nproof(induct n arbitrary: xs ys)\n  case 0\n  then show ?case unfolding n_permutations_def by simp\nnext\n  case (Suc n)\n  show ?case proof(cases ys)\n    case Nil\n    then show ?thesis using Suc\n      by (simp add: n_permutations_def) \n  next\n    case (Cons z zs)\n\n    have z_in: \"z \\<in> set xs\"\n      using Suc Cons unfolding n_permutations_def by simp\n    \n    have 1: \"set zs \\<subseteq> set xs\"\n      using Suc Cons unfolding n_permutations_def by simp\n\n    have 2: \"length zs = n\"\n      using Suc Cons unfolding n_permutations_def by simp\n\n    have 3: \"distinct zs\"\n      using Suc Cons unfolding n_permutations_def by simp\n\n    show ?thesis proof(cases \"z \\<in> set zs\")\n      case True\n      then have \"zs \\<in> set (n_permutation_enum (remove1 z xs) n)\" \n        using Suc Cons unfolding n_permutations_def by auto\n      then show ?thesis\n        using True Cons z_in by auto\n    next\n      case False\n      then have \"x \\<in> set zs \\<Longrightarrow> x \\<in> set (remove1 z xs)\" for x\n        using 1 by(cases \"x = z\") auto\n\n      then have \"zs \\<in> n_permutations (set (remove1 z xs)) n\"\n        unfolding n_permutations_def using 2 3 by auto\n      then have \"zs \\<in> set (n_permutation_enum (remove1 z xs) n)\"\n        using Suc by simp\n      then have \"\\<exists>x\\<in>set xs. z # zs \\<in> (#) x ` set (n_permutation_enum (remove1 x xs) n)\"\n        unfolding image_def using z_in by simp\n      then show ?thesis\n        using False Cons by simp\n    qed\n  qed \nqed\n\ntheorem n_permutation_enum_correct: \"distinct xs \\<Longrightarrow> set (n_permutation_enum xs n) = n_permutations (set xs) n\"\nproof standard\n  show \"distinct xs \\<Longrightarrow> set (n_permutation_enum xs n) \\<subseteq> n_permutations (set xs) n\"\n    by (simp add: n_permutation_enum_correct1)\nnext\n  show \"distinct xs \\<Longrightarrow> n_permutations (set xs) n \\<subseteq> set (n_permutation_enum xs n)\"\n    by (simp add: n_permutation_enum_correct2 subsetI)\nqed\n\n\nsubsubsection\"Distinctness\"\n\ntheorem n_permutation_distinct: \"distinct xs \\<Longrightarrow> distinct (n_permutation_enum xs n)\"\nproof(induct n arbitrary: xs)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  let ?f = \"\\<lambda>x. (n_permutation_enum (remove1 x xs) n)\"\n  from Suc have \"distinct (?f x)\" for x\n    by simp\n\n  from this Suc show ?case\n    by (auto simp: Cons_distinct_concat_map_function_distinct_on_all [of ?f xs])\nqed\n\n\nsubsubsection\"Cardinality\"\nthm card_lists_distinct_length_eq\ntheorem \"finite A \\<Longrightarrow> card (n_permutations A n) = ffact n (card A)\"\n  unfolding n_permutations_def using card_lists_distinct_length_eq\n  by (metis (no_types, lifting) Collect_cong) \n\n\n\nsubsection\"\\<open>n_multiset\\<close> extension (with remdups)\"\n\ndefinition n_multiset_permutations :: \"'a multiset \\<Rightarrow> nat \\<Rightarrow> 'a list set\" where\n  \"n_multiset_permutations A n = {xs. mset xs \\<subseteq># A \\<and> length xs = n}\"\n\nfun n_multiset_permutation_enum :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list list\" where\n  \"n_multiset_permutation_enum xs n = remdups (n_permutation_enum xs n)\"\n\nlemma \"distinct (n_multiset_permutation_enum xs n)\"\n  by auto\n\nlemma n_multiset_permutation_enum_correct1:\n  \"mset ys \\<subseteq># mset xs \\<Longrightarrow> ys \\<in> set (n_permutation_enum xs (length ys))\" \nproof(induct \"ys\" arbitrary: xs)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons y ys)\n  then have \"y \\<in> set xs\"\n    by (simp add: insert_subset_eq_iff)\n  moreover have \"ys \\<in> set (n_permutation_enum (remove1 y xs) (length ys))\"\n    using Cons by (simp add: insert_subset_eq_iff)\n  ultimately show ?case\n    using Cons by auto\nqed\n\nlemma n_multiset_permutation_enum_correct2:\n  \"ys \\<in> set (n_permutation_enum xs n) \\<Longrightarrow> mset ys \\<subseteq># mset xs\"\nproof(induct \"n\" arbitrary: xs ys)\n  case 0\n  then show ?case\n    by simp\nnext\n  case (Suc n)\n  then show ?case\n    using insert_subset_eq_iff mset_remove1 by fastforce\nqed\n\nlemma n_multiset_permutation_enum_correct:\n  \"set (n_multiset_permutation_enum xs n) = n_multiset_permutations (mset xs) n\"\n  unfolding n_multiset_permutations_def\nproof(standard)\n  show \"set (n_multiset_permutation_enum xs n) \\<subseteq> {xsa. mset xsa \\<subseteq># mset xs \\<and> length xsa = n}\"\n    by (simp add: n_multiset_permutation_enum_correct2 n_permutation_enum_length subsetI) \nnext\n  show \"{xsa. mset xsa \\<subseteq># mset xs \\<and> length xsa = n} \\<subseteq> set (n_multiset_permutation_enum xs n)\"\n    using n_multiset_permutation_enum_correct1 by auto\nqed\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Combinatorial_Enumeration_Algorithms/n_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7735114780265616}}
{"text": "theory prog_prov_ch02\nimports Main\nbegin\n\ntext{*\nSection 2: Programming and Proving\n*}\n\nfun add :: \"nat\\<Rightarrow>nat\\<Rightarrow>nat\" where\n\"add 0 m = m\"\n| \"add (Suc m) n = Suc (add m n)\"\n\ndatatype 'a list = Nil | Cons 'a \"'a  list\"\n\nfun app:: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil ys = ys\"\n| \"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun rev:: \"'a list \\<Rightarrow> 'a list\" where\n\" rev Nil = Nil\"\n| \" rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\nlemma app_Nil2 [simp]: \"app xs Nil = xs\"\napply (induction xs)\napply(auto)\ndone\n\nlemma app_assoc [simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply (induction xs)\napply(auto)\ndone\n\nlemma rev_app [simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"  \napply(induction xs)\napply(auto)\ndone\n\n(* exercise 2.1 *)\nvalue \"1+(2::nat)\"\nvalue \"1+(2::int)\"\nvalue \"1-(2::nat)\"\nvalue \"1-(2::int)\"\n\nlemma add_assoc [simp]: \"add (add a b) c = add a (add b c)\"\napply(induction a)\napply(auto)\ndone\n\nlemma add_right_0 [simp]: \"b = add b 0\"\napply(induction b)\napply(auto)\ndone\n\nlemma add_suc [simp]: \"add b (Suc a) = Suc (add b a)\"\napply(induction b)\napply(auto)\ndone\n\nlemma add_comm [simp]: \"add a b = add b a\"\napply(induction a)\napply(auto)\ndone\n\nfun double:: \"nat\\<Rightarrow>nat\" where\n\"double 0 = 0\"\n| \"double (Suc a) = Suc (Suc (double a))\"\n\nlemma double_eq_add_twice: \"double m = add m m\"\napply(induction m)\napply(auto)\ndone\n\n(*exercise 2.3*)\nfun length:: \"'a list \\<Rightarrow> nat\" where\n\"length Nil = 0\"\n| \"length (Cons x xs) = Suc (length xs)\"\n\nfun count:: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count m Nil = 0\"\n| \"count m (Cons x xs) = (if m = x then Suc (count m xs) else count m xs)\"\n\nlemma count_leq_length: \"count a l \\<le> length l\"\napply(induction l)\napply(auto)\ndone\n\n(* exercise 2.4 *)\nfun snoc:: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc Nil a = Cons a Nil\"\n| \"snoc (Cons x xs) a = Cons x (snoc xs a)\"\n\nfun reverse:: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse Nil = Nil\"\n| \"reverse (Cons x xs) = snoc (reverse xs) x\"\n\nlemma rev_snoc [simp]: \"reverse (snoc xs x) = Cons x (reverse xs)\"\napply(induction xs)\napply(auto)\ndone\n\nlemma rev_rev_is_origin: \"reverse (reverse l) = l\"\napply(induction l)\napply(auto)\ndone\n\n(* exercise 2.5 *)\nfun sum_upto:: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\"\n| \"sum_upto (Suc n) = (Suc n) + (sum_upto n)\"\n\nlemma sum_upto_res: \"sum_upto n = n * (n + 1) div 2\"\napply(induction n)\napply(auto)\ndone\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun mirror:: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l a r) = Node (mirror r) a (mirror l)\"\n\nlemma \"mirror (mirror t) = t\"\napply(induction t)\napply(auto)\ndone\n\ndatatype 'a option = None | Some 'a\n\nfun lookup:: \"('a \\<times> 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup Nil x = None\" |\n\"lookup (Cons (a, b) ps) x = (if a=x then Some b else lookup ps x)\"\n\ndefinition sq :: \"nat \\<Rightarrow> nat\" where\n\"sq n = n * n\"\n\nabbreviation sq' :: \"nat \\<Rightarrow> nat\" where\n\"sq' n \\<equiv> n * n\"\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0 = 0\"\n| \"div2 (Suc 0) = 0\"\n| \"div2 (Suc(Suc n)) = Suc (div2 n)\"\n\nlemma \"div2(n) = n div 2\"\napply(induction n rule: div2.induct)\napply(auto)\ndone\n\n(* exercise 2.6 *)\n\nfun contents:: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = Nil\"\n| \"contents (Node l a r) = app (app (contents l) (Cons a Nil) ) (contents r)\"\n\nfun listsum:: \"nat list \\<Rightarrow> nat\" where\n\"listsum Nil = 0\"\n| \"listsum (Cons x xs) = x + (listsum xs)\"\n\nfun treesum:: \"nat tree \\<Rightarrow> nat\" where\n\"treesum Tip = 0\"\n| \"treesum (Node l a r) = (treesum l) + a + (treesum r)\"\n\nlemma listsum_app [simp]: \"listsum (app x1 x2) = listsum x1 + listsum x2\"\napply(induction x1)\napply(auto)\ndone\n\nlemma tree_list_sum: \"(treesum t) = listsum (contents t)\"\napply(induction t rule: tree.induct)\napply(auto)\ndone\n\n(* exercise 2.7 *)\ndatatype 'a tree2 = Tip2 | Node2 \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror2:: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror2 Tip2 = Tip2\"\n| \"mirror2 (Node2 l a r) = Node2 (mirror2 r) a (mirror2 l)\"\n\nfun pre_order:: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order Tip2 = Nil\"\n| \"pre_order (Node2 l a r) = Cons a (app (pre_order l) (pre_order r))\"\n\nfun post_order:: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order Tip2 = Nil\"\n| \"post_order (Node2 l a r) = app (app (post_order l) (post_order r)) (Cons a Nil)\"\n\nlemma mirror_pre_post: \"pre_order (mirror2 t) = rev (post_order t)\"\napply(induction t rule: tree2.induct)\napply(auto)\ndone\n\n(*exercise 2.8 *)\nfun intersperse:: \"'a \\<Rightarrow> 'a List.list \\<Rightarrow> 'a List.list\" where\n\"intersperse a [] = []\"\n| \"intersperse a [x] = [x]\"\n| \"intersperse a (x1 # x2 # xs) = [x1, a] @ (intersperse a (x2 # xs))\"\n\nvalue \"intersperse 0 []\"\nvalue \"intersperse 0 [1]\"\nvalue \"intersperse 0 [1,2,3]\"\n\nlemma intersperse_map: \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\napply(induction xs rule: intersperse.induct)\napply(auto)\ndone\n\nfun itrev :: \"'a List.list \\<Rightarrow> 'a List.list \\<Rightarrow> 'a List.list\" where\n\"itrev [] ys = ys\"\n| \"itrev (x # xs) ys = itrev xs (x#ys)\"\n\nlemma itrev_rev_app [simp]: \"itrev xs ys = (List.rev xs) @ ys\"\napply(induction xs arbitrary:ys)\napply(auto)\ndone\n\nlemma itrev_rev: \"itrev xs [] = List.rev xs\"\napply(induction xs)\napply(auto)\ndone\n\n(* exercise 2.9*)\nfun itadd :: \"nat\\<Rightarrow>nat\\<Rightarrow>nat\" where\n\"itadd 0 acc = acc\"\n| \"itadd (Suc a) acc = itadd a (Suc acc)\"\n\nvalue \"itadd 2  3\"\n\nlemma itadd_add: \"itadd m n = add m n\"\napply(induction m arbitrary:n)\napply(auto)\ndone\n\n(* exercise 2.10 *)\ndatatype tree0 = Leaf | Inner tree0 tree0\n\nfun nodes:: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Leaf = 1\"\n| \"nodes (Inner l r) = (nodes l) + (nodes r)\"\n\nfun explode:: \"nat\\<Rightarrow>tree0\\<Rightarrow>tree0\" where\n\"explode 0 t = t\"\n| \"explode (Suc n) t = explode n (Inner t t)\"\n\nvalue \"nodes (explode 1 t)\" \nvalue \"nodes (explode 2 t)\"\nvalue \"nodes (explode 3 t)\"\nvalue \"nodes (explode 5 t)\"\n\nlemma nodes_explode: \"nodes (explode n t) = (2^n) * (nodes t)\"\napply(induction n arbitrary:t)\napply(auto simp add:algebra_simps)\ndone\n\n(* exercise 2.11; always assume the polynomial is of regular form *)\n(* only 1 Var; coefficients are from 0 to N-1, no omits *)\n(* ref; https://github.com/lunaryorn/exercises/blob/master/concrete-semantics/02.thy#L332 *)\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval:: \"exp\\<Rightarrow>int\\<Rightarrow>int\" where\n\"eval Var x = x\"\n| \"eval (Const i) x = i\"\n| \"eval (Add e1 e2) x = (eval e1 x) + (eval e2 x)\"\n| \"eval (Mult e1 e2) x = (eval e1 x) * (eval e2 x)\"\n\n(* ((4+2x)+(-x^2))+3x^3 *)\nvalue \"eval (Add (Const 4) (Mult (Const 2) Var)) 1\"\nvalue \"eval (Mult Var Var) 1\"\nvalue \"eval (Const (-1)) 1\"\nvalue \"eval (Mult (Const (-1)) (Mult Var Var)) 1\"\nvalue \"eval (Add (Add (Const 4) (Mult (Const 2) Var)) (Mult (Const (-1)) (Mult Var Var))) 3\"\n\ndefinition myterm:: \"exp\" where\n\"myterm \\<equiv> (Add\n  (Add \n   (Add (Const 4) (Mult (Const 2) Var))\n   (Mult (Const (-1)) (Mult Var Var))\n  )\n  (Mult (Const 3) (Mult (Mult Var Var) Var)))\"\n\nvalue \"eval myterm 2\"\n\nfun evalp' :: \"int List.list \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp' [] e x = 0\" |\n\"evalp' (h#t) e x = (h * (x ^ e)) + (evalp' t (Suc e) x)\"\n\nfun evalp:: \"int List.list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp coeffs x = evalp' coeffs 0 x\"\n\nlemma evalp_suc: \"x * (evalp' l e x) = (evalp' (0#l) e x)\"\n  apply (induction l arbitrary: e)\n  apply (auto simp add: algebra_simps)\ndone\n\nlemma evalp_factorise_simple: \"evalp' l (Suc e) x = x * evalp' l e x\"\napply (induction e arbitrary:l)\napply (auto simp add: algebra_simps evalp_suc)\ndone\n\nlemma evalp_commut_simple: \"(evalp' l 0 x) * (evalp' r e x) = (evalp' r 0 x) * (evalp' l e x)\"\napply(induction e)\napply(auto simp add:algebra_simps evalp_factorise_simple)\ndone\n\nvalue \"evalp [4,2,-1,3] 2\"\n\nfun addp:: \"int List.list \\<Rightarrow> int List.list \\<Rightarrow> int List.list\" where\n\"addp [] r = r\"\n| \"addp l [] = l\"\n| \"addp (lh#lt) (rh#rt) = (lh+rh) # (addp lt rt)\"\n\nlemma addp_evalp: \"evalp' (addp l r) e x = (evalp' l e x) + (evalp' r e x)\"\napply(induction l r arbitrary:e rule:addp.induct)\napply(auto simp add:algebra_simps)\ndone\n\nfun multc :: \"int \\<Rightarrow> int List.list \\<Rightarrow> int List.list\" where\n  \"multc c [] = []\" |\n  \"multc c (h#t) = (c * h)#(multc c t)\"\n\nlemma evalp_multc: \"evalp' (multc c l) e x = c * (evalp' l e x)\"\n  apply (induction l arbitrary:e)\n  apply (auto simp add: algebra_simps)\ndone\n\nvalue \"multc 3 [1,2,3]\"\n\nfun multp:: \"int List.list \\<Rightarrow> int List.list \\<Rightarrow> int List.list\" where\n\"multp [] r = []\"\n| \"multp (h#t) r = addp (multc h r) (multp t (0 # r))\"\n\nlemma multp_evalp: \"evalp' (multp l r) 0 x = (evalp' l 0 x) * (evalp' r 0 x)\"\napply(induction l r rule:multp.induct)\napply(auto simp add:algebra_simps evalp_multc addp_evalp evalp_commut_simple)\ndone\n\nfun coeffs:: \"exp \\<Rightarrow> int List.list\" where\n\"coeffs (Const i) = [i]\"\n| \"coeffs Var = [0,1]\"\n| \"coeffs (Add l r) = addp (coeffs l) (coeffs r)\"\n| \"coeffs (Mult l r) =  multp (coeffs l) (coeffs r)\"\n\nvalue \"coeffs myterm\"\n\nlemma eval_evalp: \"evalp (coeffs e) x = eval e x\"\napply(induction e rule:coeffs.induct)\napply(auto simp add:algebra_simps multp_evalp addp_evalp)\ndone\n\nend", "meta": {"author": "The-Wallfacer-Plan", "repo": "yes-isabelle", "sha": "0ead6c036a3e6f0e06c46d8fbbd7ea802af1db8f", "save_path": "github-repos/isabelle/The-Wallfacer-Plan-yes-isabelle", "path": "github-repos/isabelle/The-Wallfacer-Plan-yes-isabelle/yes-isabelle-0ead6c036a3e6f0e06c46d8fbbd7ea802af1db8f/tutorials/prog_prov_ch02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.868826784729373, "lm_q1q2_score": 0.7735114724737137}}
{"text": "(* Author: Chelsea Edmonds\nTheory: Incidence_Matrices.thy \n*)\n\nsection \\<open> Incidence Vectors and Matrices \\<close>\ntext \\<open>Incidence Matrices are an important representation for any incidence set system. The majority\nof basic definitions and properties proved in this theory are based on Stinson \\cite{stinsonCombinatorialDesignsConstructions2004}\nand Colbourn \\cite{colbournHandbookCombinatorialDesigns2007}.\\<close>\n\ntheory Incidence_Matrices imports \"Design_Extras\" Matrix_Vector_Extras \"List-Index.List_Index\"\n \"Design_Theory.Design_Isomorphisms\"\nbegin\n\nsubsection \\<open>Incidence Vectors \\<close>\ntext \\<open>A function which takes an ordered list of points, and a block, \nreturning a 0-1 vector $v$ where there is a 1 in the ith position if point i is in that block \\<close>\n\ndefinition inc_vec_of :: \"'a list \\<Rightarrow> 'a set \\<Rightarrow> ('b :: {ring_1}) vec\" where\n\"inc_vec_of Vs bl \\<equiv> vec (length Vs) (\\<lambda> i . if (Vs ! i) \\<in> bl then 1 else 0)\"\n\nlemma inc_vec_one_zero_elems: \"set\\<^sub>v (inc_vec_of Vs bl) \\<subseteq> {0, 1}\"\n  by (auto simp add: vec_set_def inc_vec_of_def)\n\nlemma finite_inc_vec_elems: \"finite (set\\<^sub>v (inc_vec_of Vs bl))\"\n  using finite_subset inc_vec_one_zero_elems by blast\n\nlemma inc_vec_elems_max_two: \"card (set\\<^sub>v (inc_vec_of Vs bl)) \\<le> 2\"\n  using card_mono inc_vec_one_zero_elems finite.insertI card_0_eq card_2_iff\n  by (smt (verit)  insert_absorb2 linorder_le_cases linordered_nonzero_semiring_class.zero_le_one \n      obtain_subset_with_card_n one_add_one subset_singletonD trans_le_add1) \n\nlemma inc_vec_dim: \"dim_vec (inc_vec_of Vs bl) = length Vs\"\n  by (simp add: inc_vec_of_def)\n\nlemma inc_vec_index: \"i < length Vs \\<Longrightarrow> inc_vec_of Vs bl $ i = (if (Vs ! i) \\<in> bl then 1 else 0)\"\n  by (simp add: inc_vec_of_def)\n\nlemma inc_vec_index_one_iff:  \"i < length Vs \\<Longrightarrow> inc_vec_of Vs bl $ i = 1 \\<longleftrightarrow> Vs ! i \\<in> bl\"\n  by (auto simp add: inc_vec_of_def ) \n\nlemma inc_vec_index_zero_iff: \"i < length Vs \\<Longrightarrow> inc_vec_of Vs bl $ i = 0 \\<longleftrightarrow> Vs ! i \\<notin> bl\"\n  by (auto simp add: inc_vec_of_def)\n\nlemma inc_vec_of_bij_betw: \n  assumes \"inj_on f (set Vs)\"\n  assumes \"bl \\<subseteq> (set Vs)\"\n  shows \"inc_vec_of Vs bl = inc_vec_of (map f Vs) (f ` bl)\"\nproof (intro eq_vecI, simp_all add: inc_vec_dim)\n  fix i assume \"i < length Vs\"\n  then have \"Vs ! i \\<in> bl \\<longleftrightarrow> (map f Vs) ! i \\<in> (f ` bl)\"\n    by (metis assms(1) assms(2) inj_on_image_mem_iff nth_map nth_mem)\n  then show \"inc_vec_of Vs bl $ i = inc_vec_of (map f Vs) (f ` bl) $ i\"\n    using inc_vec_index by (metis \\<open>i < length Vs\\<close> length_map) \nqed\n\nsubsection \\<open> Incidence Matrices \\<close>\n\ntext \\<open> A function which takes a list of points, and list of sets of points, and returns \na $v \\times b$ 0-1 matrix $M$, where $v$ is the number of points, and $b$ the number of sets, such \nthat there is a 1 in the i, j position if and only if point i is in block j. The matrix has \ntype @{typ \"('b :: ring_1) mat\"} to allow for operations commonly used on matrices \\cite{stinsonCombinatorialDesignsConstructions2004}\\<close>\n\ndefinition inc_mat_of :: \"'a list \\<Rightarrow> 'a set list \\<Rightarrow> ('b :: {ring_1}) mat\" where\n\"inc_mat_of Vs Bs \\<equiv> mat (length Vs) (length Bs) (\\<lambda> (i,j) . if (Vs ! i) \\<in> (Bs ! j) then 1 else 0)\"\n\ntext \\<open> Basic lemmas on the @{term \"inc_mat_of\"} matrix result (elements/dimensions/indexing)\\<close>\n\nlemma inc_mat_one_zero_elems: \"elements_mat (inc_mat_of Vs Bs) \\<subseteq> {0, 1}\"\n  by (auto simp add: inc_mat_of_def elements_mat_def)\n\nlemma fin_incidence_mat_elems: \"finite (elements_mat (inc_mat_of Vs Bs))\"\n  using finite_subset inc_mat_one_zero_elems by auto \n\nlemma inc_matrix_elems_max_two: \"card (elements_mat (inc_mat_of Vs Bs)) \\<le> 2\"\n  using inc_mat_one_zero_elems order_trans card_2_iff\n  by (smt (verit, del_insts) antisym bot.extremum card.empty insert_commute insert_subsetI \n      is_singletonI is_singleton_altdef linorder_le_cases not_one_le_zero one_le_numeral  subset_insert) \n\nlemma inc_mat_of_index [simp]: \"i < dim_row (inc_mat_of Vs Bs) \\<Longrightarrow> j < dim_col (inc_mat_of Vs Bs) \\<Longrightarrow> \n  inc_mat_of Vs Bs $$ (i, j) = (if (Vs ! i) \\<in> (Bs ! j) then 1 else 0)\"\n  by (simp add: inc_mat_of_def)\n\nlemma inc_mat_dim_row: \"dim_row (inc_mat_of Vs Bs) = length Vs\"\n  by (simp add: inc_mat_of_def)\n\nlemma inc_mat_dim_vec_row: \"dim_vec (row (inc_mat_of Vs Bs) i) = length Bs\"\n  by (simp add:  inc_mat_of_def)\n\nlemma inc_mat_dim_col: \"dim_col (inc_mat_of Vs Bs) = length Bs\"\n  by (simp add:  inc_mat_of_def)\n\nlemma inc_mat_dim_vec_col: \"dim_vec (col (inc_mat_of Vs Bs) i) = length Vs\"\n  by (simp add:  inc_mat_of_def)\n\nlemma inc_matrix_point_in_block_one: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> Vs ! i \\<in> Bs ! j\n    \\<Longrightarrow> (inc_mat_of Vs Bs) $$ (i, j) = 1\"\n  by (simp add: inc_mat_of_def)   \n\nlemma inc_matrix_point_not_in_block_zero: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> Vs ! i \\<notin> Bs ! j \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0\"\n  by(simp add: inc_mat_of_def)\n\nlemma inc_matrix_point_in_block: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> (inc_mat_of Vs Bs) $$ (i, j) = 1 \n    \\<Longrightarrow> Vs ! i \\<in> Bs ! j\"\n  using inc_matrix_point_not_in_block_zero by (metis zero_neq_one) \n\nlemma inc_matrix_point_not_in_block:  \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0 \\<Longrightarrow> Vs ! i \\<notin> Bs ! j\"\n  using inc_matrix_point_in_block_one by (metis zero_neq_one)\n\nlemma inc_matrix_point_not_in_block_iff:  \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0 \\<longleftrightarrow> Vs ! i \\<notin> Bs ! j\"\n  using inc_matrix_point_not_in_block inc_matrix_point_not_in_block_zero by blast\n\nlemma inc_matrix_point_in_block_iff:  \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow>\n    (inc_mat_of Vs Bs) $$ (i, j) = 1 \\<longleftrightarrow> Vs ! i \\<in> Bs ! j\"\n  using inc_matrix_point_in_block inc_matrix_point_in_block_one by blast\n\nlemma inc_matrix_subset_implies_one: \n  assumes \"I \\<subseteq> {..< length Vs}\"\n  assumes \"j < length Bs\"\n  assumes \"(!) Vs ` I \\<subseteq> Bs ! j\"\n  assumes \"i \\<in> I\"\n  shows \"(inc_mat_of Vs Bs) $$ (i, j) = 1\"\nproof - \n  have iin: \"Vs ! i \\<in> Bs ! j\" using assms(3) assms(4) by auto\n  have \"i < length Vs\" using assms(1) assms(4) by auto\n  thus ?thesis using iin inc_matrix_point_in_block_iff assms(2) by blast  \nqed\n\nlemma inc_matrix_one_implies_membership: \"I \\<subseteq> {..< length Vs} \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (\\<And> i. i\\<in>I \\<Longrightarrow> (inc_mat_of Vs Bs) $$ (i, j) = 1) \\<Longrightarrow> i \\<in> I \\<Longrightarrow> Vs ! i \\<in> Bs ! j\"\n  using inc_matrix_point_in_block subset_iff by blast \n\nlemma inc_matrix_elems_one_zero: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0 \\<or> (inc_mat_of Vs Bs) $$ (i, j) = 1\"\n  using inc_matrix_point_in_block_one inc_matrix_point_not_in_block_zero by blast\n\ntext \\<open>Reasoning on Rows/Columns of the incidence matrix \\<close>\n\nlemma inc_mat_col_def:  \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    (col (inc_mat_of Vs Bs) j) $ i = (if (Vs ! i \\<in> Bs ! j) then 1 else 0)\"\n  by (simp add: inc_mat_of_def) \n\nlemma inc_mat_col_list_map_elem: \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    col (inc_mat_of Vs Bs) j $ i = map_vec (\\<lambda> x . if (x \\<in> (Bs ! j)) then 1 else 0) (vec_of_list Vs) $ i\"\n  by (simp add: inc_mat_of_def index_vec_of_list)\n\nlemma inc_mat_col_list_map:  \"j < length Bs \\<Longrightarrow> \n    col (inc_mat_of Vs Bs) j = map_vec (\\<lambda> x . if (x \\<in> (Bs ! j)) then 1 else 0) (vec_of_list Vs)\"\n  by (intro eq_vecI) \n    (simp_all add: inc_mat_dim_row inc_mat_dim_col inc_mat_col_list_map_elem index_vec_of_list)\n\nlemma inc_mat_row_def: \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    (row (inc_mat_of Vs Bs) i) $ j = (if (Vs ! i \\<in> Bs ! j) then 1 else 0)\"\n  by (simp add: inc_mat_of_def)\n\nlemma inc_mat_row_list_map_elem: \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    row (inc_mat_of Vs Bs) i $ j = map_vec (\\<lambda> bl . if ((Vs ! i) \\<in> bl) then 1 else 0) (vec_of_list Bs) $ j\"\n  by (simp add: inc_mat_of_def vec_of_list_index)\n\nlemma inc_mat_row_list_map: \"i < length Vs \\<Longrightarrow> \n    row (inc_mat_of Vs Bs) i = map_vec (\\<lambda> bl . if ((Vs ! i) \\<in> bl) then 1 else 0) (vec_of_list Bs)\"\n  by (intro eq_vecI) \n    (simp_all add: inc_mat_dim_row inc_mat_dim_col inc_mat_row_list_map_elem index_vec_of_list)\n\ntext \\<open> Connecting @{term \"inc_vec_of\"} and @{term \"inc_mat_of\"} \\<close>\n\nlemma inc_mat_col_inc_vec: \"j < length Bs \\<Longrightarrow> col (inc_mat_of Vs Bs) j = inc_vec_of Vs (Bs ! j)\"\n  by (auto simp add: inc_mat_of_def inc_vec_of_def)\n\nlemma inc_mat_of_cols_inc_vecs: \"cols (inc_mat_of Vs Bs) = map (\\<lambda> j . inc_vec_of Vs j) Bs\"\nproof (intro nth_equalityI)\n  have l1: \"length (cols (inc_mat_of Vs Bs)) = length Bs\"\n    using inc_mat_dim_col by simp\n  have l2: \"length (map (\\<lambda> j . inc_vec_of Vs j) Bs) = length Bs\"\n    using length_map by simp\n  then show \"length (cols (inc_mat_of Vs Bs)) = length (map (inc_vec_of Vs) Bs)\" \n    using l1 l2 by simp\n  show \"\\<And> i. i < length (cols (inc_mat_of Vs Bs)) \\<Longrightarrow> \n    (cols (inc_mat_of Vs Bs) ! i) = (map (\\<lambda> j . inc_vec_of Vs j) Bs) ! i\"\n    using inc_mat_col_inc_vec l1 by (metis cols_nth inc_mat_dim_col nth_map) \nqed\n\nlemma inc_mat_of_bij_betw: \n  assumes \"inj_on f (set Vs)\"\n  assumes \"\\<And> bl . bl \\<in> (set Bs) \\<Longrightarrow> bl \\<subseteq> (set Vs)\"\n  shows \"inc_mat_of Vs Bs = inc_mat_of (map f Vs) (map ((`) f) Bs)\"\nproof (intro eq_matI, simp_all add: inc_mat_dim_row inc_mat_dim_col, intro impI)\n  fix i j assume ilt: \"i < length Vs\" and jlt: \" j < length Bs\" and \"Vs ! i \\<notin> Bs ! j\"\n  then show \"f (Vs ! i) \\<notin> f ` Bs ! j\"\n    by (meson assms(1) assms(2) ilt inj_on_image_mem_iff jlt nth_mem) \nqed\n\ntext \\<open>Definitions for the incidence matrix representation of common incidence system properties \\<close>\n\ndefinition non_empty_col :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"non_empty_col M j \\<equiv> \\<exists> k. k \\<noteq> 0 \\<and> k \\<in>$ col M j\"\n\ndefinition proper_inc_mat :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> bool\" where\n\"proper_inc_mat M \\<equiv> (dim_row M > 0 \\<and> dim_col M > 0)\"\n\ntext \\<open>Matrix version of the representation number property @{term \"point_replication_number\"}\\<close>\ndefinition mat_rep_num :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mat_rep_num M i \\<equiv> count_vec (row M i) 1\"\n\ntext \\<open>Matrix version of the points index property @{term \"points_index\"}\\<close>\ndefinition mat_point_index :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat set \\<Rightarrow> nat\" where\n\"mat_point_index M I \\<equiv> card {j . j < dim_col M \\<and> (\\<forall> i \\<in> I. M $$ (i, j) = 1)}\"\n\ndefinition mat_inter_num :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mat_inter_num M j1 j2 \\<equiv> card {i . i < dim_row M \\<and> M $$ (i, j1) = 1 \\<and>  M $$ (i, j2) = 1}\"\n\ntext \\<open>Matrix version of the block size property\\<close>\ndefinition mat_block_size :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mat_block_size M j \\<equiv> count_vec (col M j) 1\"\n\nlemma non_empty_col_obtains: \n  assumes \"non_empty_col M j\"\n  obtains i where \"i < dim_row M\" and \"(col M j) $ i \\<noteq> 0\"\nproof -\n  have d: \"dim_vec (col M j) = dim_row M\" by simp\n  from assms obtain k where \"k \\<noteq> 0\" and \"k \\<in>$ col M j\" \n    by (auto simp add: non_empty_col_def)\n  thus ?thesis using vec_contains_obtains_index d\n    by (metis that) \nqed\n\nlemma non_empty_col_alt_def: \n  assumes \"j < dim_col M\" \n  shows \"non_empty_col M j \\<longleftrightarrow> (\\<exists> i. i < dim_row M \\<and> M $$ (i, j) \\<noteq> 0)\"\nproof (intro iffI)\n  show \"non_empty_col M j \\<Longrightarrow> \\<exists>i<dim_row M. M $$ (i, j) \\<noteq> 0\"\n    by(metis assms index_col non_empty_col_obtains)\nnext \n  assume \"\\<exists>i<dim_row M. M $$ (i, j) \\<noteq> 0\"\n  then obtain i where ilt: \" i < dim_row M\" and ne: \"M $$ (i, j) \\<noteq> 0\" by blast\n  then have ilt2: \" i < dim_vec (col M j)\" by simp\n  then have \"(col M j) $ i \\<noteq> 0\" using ne by (simp add: assms) \n  then obtain k where \"(col M j) $ i = k\" and \"k \\<noteq> 0\"\n    by simp\n  then show \"non_empty_col M j \" using non_empty_col_def\n    by (metis ilt2 vec_setI) \nqed\n\nlemma proper_inc_mat_map: \"proper_inc_mat M \\<Longrightarrow> proper_inc_mat (map_mat f M)\"\n  by (simp add: proper_inc_mat_def)\n\nlemma mat_point_index_alt: \"mat_point_index M I = card {j \\<in> {0..<dim_col M} . (\\<forall> i \\<in> I . M $$(i, j) = 1)}\"\n  by (simp add: mat_point_index_def)\n\nlemma mat_block_size_sum_alt: \n  fixes M :: \"'a :: {ring_1} mat\"\n  shows \"elements_mat M \\<subseteq> {0, 1} \\<Longrightarrow> j < dim_col M \\<Longrightarrow> of_nat (mat_block_size M j) = sum_vec (col M j)\"\n  unfolding mat_block_size_def using count_vec_sum_ones_alt col_elems_subset_mat subset_trans\n  by metis  \n\nlemma mat_rep_num_sum_alt: \n  fixes M :: \"'a :: {ring_1} mat\"\n  shows \"elements_mat M \\<subseteq> {0, 1} \\<Longrightarrow> i < dim_row M \\<Longrightarrow> of_nat (mat_rep_num M i) = sum_vec (row M i)\"\n  using count_vec_sum_ones_alt\n  by (metis mat_rep_num_def row_elems_subset_mat subset_trans) \n\nlemma mat_point_index_two_alt: \n  assumes \"i1 < dim_row M\"\n  assumes \"i2 < dim_row M\"\n  shows \"mat_point_index M {i1, i2} = card {j . j < dim_col M \\<and> M $$(i1, j) = 1 \\<and> M $$ (i2, j) = 1}\"\nproof -\n  let ?I = \"{i1, i2}\"\n  have ss: \"{i1, i2} \\<subseteq> {..<dim_row M}\" using assms by blast\n  have filter: \"\\<And> j . j < dim_col M \\<Longrightarrow> (\\<forall> i \\<in> ?I . M $$(i, j) = 1) \\<longleftrightarrow> M $$(i1, j) = 1 \\<and> M $$ (i2, j) = 1\"\n    by auto\n  have \"?I \\<subseteq> {..< dim_row M}\" using assms(1) assms(2) by fastforce\n  thus ?thesis using filter ss unfolding mat_point_index_def\n    by meson \nqed\n\ntext \\<open> Transpose symmetries \\<close>\n\nlemma trans_mat_rep_block_size_sym: \"j < dim_col M \\<Longrightarrow> mat_block_size M j = mat_rep_num M\\<^sup>T j\"\n  \"i < dim_row M \\<Longrightarrow> mat_rep_num M i = mat_block_size M\\<^sup>T i\"\n  unfolding mat_block_size_def mat_rep_num_def by simp_all\n\nlemma trans_mat_point_index_inter_sym: \n  \"i1 < dim_row M \\<Longrightarrow> i2 < dim_row M \\<Longrightarrow> mat_point_index M {i1, i2} = mat_inter_num M\\<^sup>T i1 i2\"\n  \"j1 < dim_col M \\<Longrightarrow> j2 < dim_col M \\<Longrightarrow> mat_inter_num M j1 j2 = mat_point_index M\\<^sup>T {j1, j2}\"\n   apply (simp_all add: mat_inter_num_def mat_point_index_two_alt)\n   apply (metis (no_types, lifting) index_transpose_mat(1))\n  by (metis (no_types, lifting) index_transpose_mat(1))\n\nsubsection \\<open>0-1 Matrices \\<close>\ntext \\<open>Incidence matrices contain only two elements: 0 and 1. We define a locale which provides\na context to work in for matrices satisfying this condition for any @{typ \"'b :: zero_neq_one\"} type.\\<close>\nlocale zero_one_matrix = \n  fixes matrix :: \"'b :: {zero_neq_one} mat\" (\"M\")\n  assumes elems01: \"elements_mat M \\<subseteq> {0, 1}\"\nbegin\n\ntext \\<open> Row and Column Properties of the Matrix \\<close>\n\nlemma row_elems_ss01:\"i < dim_row M \\<Longrightarrow> vec_set (row M i) \\<subseteq> {0, 1}\"\n  using row_elems_subset_mat elems01 by blast\n\nlemma col_elems_ss01: \n  assumes \"j < dim_col M\"\n  shows \"vec_set (col M j) \\<subseteq> {0, 1}\"\nproof -\n  have \"vec_set (col M j) \\<subseteq> elements_mat M\" using assms \n    by (simp add: col_elems_subset_mat assms) \n  thus ?thesis using elems01 by blast\nqed\n\nlemma col_nth_0_or_1_iff: \n  assumes \"j < dim_col M\"\n  assumes \"i < dim_row M\"\n  shows \"col M j $ i = 0 \\<longleftrightarrow> col M j $ i \\<noteq> 1\"\nproof (intro iffI)\n  have dv: \"i < dim_vec (col M j)\" using assms by simp\n  have sv: \"set\\<^sub>v (col M j) \\<subseteq> {0, 1}\" using col_elems_ss01 assms by simp\n  then show \"col M j $ i = 0 \\<Longrightarrow> col M j $ i \\<noteq> 1\" using dv by simp\n  show \"col M j $ i \\<noteq> 1 \\<Longrightarrow> col M j $ i = 0\" using dv sv\n    by (meson insertE singletonD subset_eq vec_setI) \nqed\n\nlemma row_nth_0_or_1_iff: \n  assumes \"j < dim_col M\"\n  assumes \"i < dim_row M\"\n  shows \"row M i $ j = 0 \\<longleftrightarrow> row M i $ j \\<noteq> 1\"\nproof (intro iffI)\n  have dv: \"j < dim_vec (row M i)\" using assms by simp\n  have sv: \"set\\<^sub>v (row M i) \\<subseteq> {0, 1}\" using row_elems_ss01 assms by simp\n  then show \"row M i $ j = 0 \\<Longrightarrow> row M i $ j \\<noteq> 1\" by simp\n  show \"row M i $ j \\<noteq> 1 \\<Longrightarrow> row M i $ j = 0\" using dv sv\n    by (meson insertE singletonD subset_eq vec_setI) \nqed\n\nlemma transpose_entries: \"elements_mat (M\\<^sup>T) \\<subseteq> {0, 1}\"\n  using elems01 transpose_mat_elems by metis \n\nlemma M_not_zero_simp: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> M $$ (i, j) \\<noteq> 0 \\<Longrightarrow> M $$ (i, j) = 1\"\n  using elems01 by auto\n\nlemma M_not_one_simp: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> M $$ (i, j) \\<noteq> 1 \\<Longrightarrow> M $$ (i, j) = 0\"\n  using elems01 by auto\n\ntext \\<open>Definition for mapping a column to a block \\<close>\ndefinition map_col_to_block :: \"'a :: {zero_neq_one} vec  \\<Rightarrow> nat set\" where\n\"map_col_to_block c \\<equiv> { i \\<in> {..<dim_vec c} . c $ i = 1}\"\n\nlemma map_col_to_block_alt: \"map_col_to_block c = {i . i < dim_vec c \\<and> c$ i = 1}\"\n  by (simp add: map_col_to_block_def)\n\nlemma map_col_to_block_elem: \"i < dim_vec c \\<Longrightarrow> i \\<in> map_col_to_block c \\<longleftrightarrow>  c $ i = 1\"\n  by (simp add: map_col_to_block_alt)\n\nlemma in_map_col_valid_index: \"i \\<in> map_col_to_block c \\<Longrightarrow> i < dim_vec c\"\n  by (simp add: map_col_to_block_alt)\n\nlemma map_col_to_block_size: \"j < dim_col M \\<Longrightarrow> card (map_col_to_block (col M j)) = mat_block_size M j\"\n  unfolding mat_block_size_def map_col_to_block_alt using count_vec_alt[of \"col M j\" \"1\"] Collect_cong\n  by (metis (no_types, lifting))\n\nlemma in_map_col_valid_index_M: \"j < dim_col M \\<Longrightarrow> i \\<in> map_col_to_block (col M j) \\<Longrightarrow> i < dim_row M\"\n  using in_map_col_valid_index by (metis dim_col) \n\nlemma map_col_to_block_elem_not: \"c \\<in> set (cols M) \\<Longrightarrow> i < dim_vec c \\<Longrightarrow> i \\<notin> map_col_to_block c \\<longleftrightarrow> c $ i = 0\"\n  apply (auto simp add: map_col_to_block_alt)\n  using elems01 by (metis col_nth_0_or_1_iff dim_col obtain_col_index) \n\nlemma obtain_block_index_map_block_set: \n  assumes \"bl \\<in># {# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  obtains j where \"j < dim_col M\" and \"bl = map_col_to_block (col M j)\"\nproof -\n  obtain c where bleq: \"bl = map_col_to_block c\" and \"c \\<in># mset (cols M)\"\n    using assms by blast\n  then have \"c \\<in> set (cols M)\" by simp\n  thus ?thesis using bleq obtain_col_index\n    by (metis that)\nqed\n\nlemma mat_ord_inc_sys_point[simp]: \"x < dim_row M \\<Longrightarrow> [0..<(dim_row M)] ! x = x\"\n  by simp\n\nlemma mat_ord_inc_sys_block[simp]: \"j < dim_col M \\<Longrightarrow> \n  (map (map_col_to_block) (cols M)) ! j = map_col_to_block (col M j)\"\n  by auto\n\nlemma ordered_to_mset_col_blocks:\n  \"{# map_col_to_block c . c \\<in># mset (cols M)#} = mset (map (map_col_to_block) (cols M))\"\n  by simp\n\ntext \\<open> Lemmas on incidence matrix properties \\<close>\nlemma non_empty_col_01: \n  assumes \"j < dim_col M\"\n  shows \"non_empty_col M j \\<longleftrightarrow> 1 \\<in>$ col M j\"\nproof (intro iffI)\n  assume \"non_empty_col M j\"\n  then obtain k where kn0: \"k \\<noteq> 0\" and kin: \"k \\<in>$ col M j\" using non_empty_col_def\n    by blast\n  then have \"k \\<in> elements_mat M\" using vec_contains_col_elements_mat assms\n    by metis \n  then have \"k = 1\" using kn0\n    using elems01 by blast \n  thus \"1 \\<in>$ col M j\" using kin by simp\nnext\n  assume \"1 \\<in>$ col M j\"\n  then show \"non_empty_col M j\" using non_empty_col_def\n    by (metis zero_neq_one)\nqed\n\nlemma mat_rep_num_alt: \n  assumes \"i < dim_row M\"\n  shows \"mat_rep_num M i = card {j . j < dim_col M \\<and> M $$ (i, j) = 1}\"\nproof (simp add: mat_rep_num_def)\n  have eq: \"\\<And> j. (j < dim_col M \\<and> M $$ (i, j) = 1) = (row M i $ j = 1 \\<and> j < dim_vec (row M i))\" \n    using assms by auto\n  have \"count_vec (row M i) 1 = card {j. (row M i) $ j = 1 \\<and>  j < dim_vec (row M i)}\"\n    using count_vec_alt[of \"row M i\" \"1\"] by simp\n  thus \"count_vec (row M i) 1 = card {j. j < dim_col M \\<and> M $$ (i, j) = 1}\"\n    using eq Collect_cong by simp\nqed\n\nlemma mat_rep_num_alt_col: \"i < dim_row M \\<Longrightarrow> mat_rep_num M i = size {#c \\<in># (mset (cols M)) . c $ i = 1#}\"\n  using mat_rep_num_alt index_to_col_card_size_prop[of i M] by auto\n\ntext \\<open> A zero one matrix is an incidence system \\<close>\n\nlemma map_col_to_block_wf: \"\\<And>c. c \\<in> set (cols M) \\<Longrightarrow> map_col_to_block c \\<subseteq> {0..<dim_row M}\"\n  by (auto simp add: map_col_to_block_def)(metis dim_col obtain_col_index)\n\nlemma one_implies_block_nempty: \"j < dim_col M \\<Longrightarrow> 1 \\<in>$ (col M j) \\<Longrightarrow> map_col_to_block (col M j) \\<noteq> {}\"\n  unfolding map_col_to_block_def using vec_setE by force \n\ninterpretation incidence_sys: incidence_system \"{0..<dim_row M}\" \n    \"{# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  using map_col_to_block_wf by (unfold_locales) auto \n\ninterpretation fin_incidence_sys: finite_incidence_system \"{0..<dim_row M}\" \n    \"{# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  by (unfold_locales) (simp)\n\nlemma block_nempty_implies_all_zeros: \"j < dim_col M \\<Longrightarrow> map_col_to_block (col M j) = {} \\<Longrightarrow> \n    i < dim_row M \\<Longrightarrow> col M j $ i = 0\"\n  by (metis col_nth_0_or_1_iff dim_col one_implies_block_nempty vec_setI)\n\nlemma block_nempty_implies_no_one: \"j < dim_col M \\<Longrightarrow> map_col_to_block (col M j) = {} \\<Longrightarrow> \\<not> (1 \\<in>$ (col M j))\"\n  using one_implies_block_nempty by blast\n\nlemma mat_is_design:\n  assumes \"\\<And>j. j < dim_col M\\<Longrightarrow> 1 \\<in>$ (col M j)\"\n  shows \"design {0..<dim_row M} {# map_col_to_block c . c \\<in># mset (cols M)#}\"\nproof (unfold_locales)\n  fix bl \n  assume \"bl \\<in># {# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  then obtain j where \"j < dim_col M\" and map: \"bl = map_col_to_block (col M j)\"\n    using obtain_block_index_map_block_set by auto\n  thus \"bl \\<noteq> {}\" using assms one_implies_block_nempty\n    by simp \nqed\n\nlemma mat_is_proper_design: \n  assumes \"\\<And>j. j < dim_col M \\<Longrightarrow> 1 \\<in>$ (col M j)\"\n  assumes \"dim_col M > 0\"\n  shows \"proper_design {0..<dim_row M} {# map_col_to_block c . c \\<in># mset (cols M)#}\"\nproof -\n  interpret des: design \"{0..<dim_row M}\" \"{# map_col_to_block c . c \\<in># mset (cols M)#}\"\n    using mat_is_design assms by simp\n  show ?thesis proof (unfold_locales)\n    have \"length (cols M) \\<noteq> 0\" using assms(2) by auto\n    then have \"size {# map_col_to_block c . c \\<in># mset (cols M)#} \\<noteq> 0\" by auto\n    then show \"incidence_sys.\\<b> \\<noteq> 0\" by simp\n  qed\nqed\n\ntext \\<open> Show the 01 injective function preserves system properties \\<close>\n\nlemma inj_on_01_hom_index:\n  assumes \"inj_on_01_hom f\"\n  assumes \"i < dim_row M\" \"j < dim_col M\"\n  shows \"M $$ (i, j) = 1  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 1\"\n    and \"M $$ (i, j) = 0  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 0\"\nproof -\n  interpret hom: inj_on_01_hom f using assms by simp\n  show \"M $$ (i, j) = 1  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 1\" \n    using assms col_nth_0_or_1_iff\n    by (simp add: hom.inj_1_iff) \n  show \"M $$ (i, j) = 0  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 0\"\n    using assms col_nth_0_or_1_iff\n    by (simp add: hom.inj_0_iff) \nqed\n\nlemma preserve_non_empty: \n  assumes \"inj_on_01_hom f\" \n  assumes \"j < dim_col M\"\n  shows \"non_empty_col M j \\<longleftrightarrow> non_empty_col (map_mat f M) j\"\nproof(simp add: non_empty_col_def, intro iffI) \n  interpret hom: inj_on_01_hom f using assms(1) by simp\n  assume \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col M j\"\n  then obtain k where kneq: \"k \\<noteq> 0\" and kin: \"k \\<in>$ col M j\" by blast\n  then have \"f k \\<in>$ col (map_mat f M) j\" using vec_contains_img\n    by (metis assms(2) col_map_mat) \n  then have \"f k \\<noteq> 0\" using assms(1) kneq kin assms(2) col_elems_ss01 hom.inj_0_iff by blast\n  thus \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col (map_mat f M) j\"\n    using \\<open>f k \\<in>$ col (map_mat f M) j\\<close> by blast\nnext\n  interpret hom: inj_on_01_hom f using assms(1) by simp\n  assume \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col (map_mat f M) j\"\n  then obtain k where kneq: \"k \\<noteq> 0\" and kin: \"k \\<in>$ col (map_mat f M) j\" by blast\n  then have \"k \\<in>$ map_vec f (col M j)\" using assms(2) col_map_mat by simp\n  then have \"k \\<in> f ` set\\<^sub>v (col M j)\"\n    by (smt (verit) image_eqI index_map_vec(1) index_map_vec(2) vec_setE vec_setI) \n  then obtain k' where keq: \"k = f k'\" and kin2: \"k' \\<in> set\\<^sub>v (col M j)\"\n    by blast \n  then have \"k' \\<noteq> 0\" using assms(1) kneq hom.inj_0_iff by blast \n  thus  \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col M j\" using kin2 by auto\nqed\n\nlemma preserve_mat_rep_num:\n  assumes \"inj_on_01_hom f\"\n  assumes \"i < dim_row M\"\n  shows \"mat_rep_num M i = mat_rep_num (map_mat f M) i\"\n  unfolding mat_rep_num_def using injective_lim.lim_inj_hom_count_vec inj_on_01_hom_def row_map_mat\n  by (metis assms(1) assms(2) inj_on_01_hom.inj_1_iff insert_iff row_elems_ss01)\n\nlemma preserve_mat_block_size: \n  assumes \"inj_on_01_hom f\"\n  assumes \"j < dim_col M\"\n  shows \"mat_block_size M j = mat_block_size (map_mat f M) j\"\n  unfolding mat_block_size_def using injective_lim.lim_inj_hom_count_vec inj_on_01_hom_def col_map_mat\n  by (metis assms(1) assms(2) inj_on_01_hom.inj_1_iff insert_iff col_elems_ss01)\n\n\nlemma preserve_mat_point_index: \n  assumes \"inj_on_01_hom f\"\n  assumes \"\\<And> i. i \\<in> I \\<Longrightarrow> i < dim_row M\"\n  shows \"mat_point_index M I = mat_point_index (map_mat f M) I\"\nproof -\n  have \"\\<And> i j. i \\<in> I \\<Longrightarrow> j < dim_col M \\<and> M $$ (i, j) = 1 \\<longleftrightarrow> \n      j < dim_col (map_mat f M) \\<and> (map_mat f M) $$ (i, j) = 1\"\n    using assms(2) inj_on_01_hom_index(1) assms(1) by (metis index_map_mat(3)) \n  thus ?thesis unfolding mat_point_index_def\n    by (metis (no_types, opaque_lifting) index_map_mat(3)) \nqed\n\nlemma preserve_mat_inter_num: \n  assumes \"inj_on_01_hom f\"\n  assumes \"j1 < dim_col M\" \"j2 < dim_col M\"\n  shows \"mat_inter_num M j1 j2 = mat_inter_num (map_mat f M) j1 j2\"\n  unfolding mat_inter_num_def using assms\n  by (metis (no_types, opaque_lifting) index_map_mat(2) inj_on_01_hom_index(1)) \n\nlemma lift_mat_01_index_iff: \n  \"i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> (lift_01_mat M) $$ (i, j) = 0 \\<longleftrightarrow> M $$ (i, j) = 0\"\n  \"i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> (lift_01_mat M) $$ (i, j) = 1 \\<longleftrightarrow> M $$ (i, j) = 1\"\n  by (simp) (metis col_nth_0_or_1_iff index_col lift_01_mat_simp(3) of_zero_neq_one_def zero_neq_one) \n\nlemma lift_mat_elems: \"elements_mat (lift_01_mat M) \\<subseteq> {0, 1}\"\nproof -\n  have \"elements_mat (lift_01_mat M) = of_zero_neq_one ` (elements_mat M)\"\n    by (simp add: lift_01_mat_def map_mat_elements)\n  then have \"elements_mat (lift_01_mat M) \\<subseteq> of_zero_neq_one ` {0, 1}\" using elems01\n    by fastforce \n  thus ?thesis\n    by simp \nqed\n\nlemma lift_mat_is_0_1: \"zero_one_matrix (lift_01_mat M)\"\n  using lift_mat_elems by (unfold_locales)\n\nlemma lift_01_mat_distinct_cols: \"distinct (cols M) \\<Longrightarrow> distinct (cols (lift_01_mat M))\"\n  using of_injective_lim.mat_cols_hom_lim_distinct_iff lift_01_mat_def\n  by (metis elems01 map_vec_mat_cols) \n\nend\n\ntext \\<open>Some properties must be further restricted to matrices having a @{typ \"'a :: ring_1\"} type \\<close>\nlocale zero_one_matrix_ring_1 = zero_one_matrix M for M :: \"'b :: {ring_1} mat\"\nbegin\n\nlemma map_col_block_eq: \n  assumes \"c \\<in> set(cols M)\"\n  shows \"inc_vec_of [0..<dim_vec c] (map_col_to_block c) = c\"\nproof (intro eq_vecI, simp add: map_col_to_block_def inc_vec_of_def, intro impI)\n  show \"\\<And>i. i < dim_vec c \\<Longrightarrow> c $ i \\<noteq> 1 \\<Longrightarrow> c $ i = 0\"\n    using assms map_col_to_block_elem map_col_to_block_elem_not by auto \n  show \"dim_vec (inc_vec_of [0..<dim_vec c] (map_col_to_block c)) = dim_vec c\"\n    unfolding inc_vec_of_def by simp \nqed\n\nlemma inc_mat_of_map_rev: \"inc_mat_of [0..<dim_row M] (map map_col_to_block (cols M)) = M\"\nproof (intro eq_matI, simp_all add: inc_mat_of_def, intro conjI impI)\n  show \"\\<And>i j. i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> i \\<in> map_col_to_block (col M j) \\<Longrightarrow> M $$ (i, j) = 1\"\n    by (simp add: map_col_to_block_elem)\n  show \"\\<And>i j. i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> i \\<notin> map_col_to_block (col M j) \\<Longrightarrow> M $$ (i, j) = 0\"\n    by (metis col_nth_0_or_1_iff dim_col index_col map_col_to_block_elem)\nqed\n\nlemma M_index_square_itself: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> (M $$ (i, j))^2 = M $$ (i, j)\"\n  using M_not_zero_simp by (cases \"M $$ (i, j) = 0\")(simp_all, metis power_one) \n\nlemma M_col_index_square_itself: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> ((col M j) $ i)^2 = (col M j) $ i\"\n  using index_col M_index_square_itself by auto \n\n\ntext \\<open> Scalar Prod Alternative definitions for matrix properties \\<close>\n\nlemma scalar_prod_inc_vec_block_size_mat:\n  assumes \"j < dim_col M\"\n  shows \"(col M j) \\<bullet> (col M j) = of_nat (mat_block_size M j)\"\nproof -\n  have \"(col M j) \\<bullet> (col M j) = (\\<Sum> i \\<in> {0..<dim_row M} . (col M j) $ i * (col M j) $ i)\" \n     using assms  scalar_prod_def sum.cong by (smt (verit, ccfv_threshold) dim_col) \n  also have \"... = (\\<Sum> i \\<in> {0..<dim_row M} . ((col M j) $ i)^2)\"\n    by (simp add: power2_eq_square ) \n  also have \"... = (\\<Sum> i \\<in> {0..<dim_row M} . ((col M j) $ i))\"\n    using M_col_index_square_itself assms by auto\n  finally show ?thesis using sum_vec_def mat_block_size_sum_alt\n    by (metis assms dim_col elems01) \nqed\n\nlemma scalar_prod_inc_vec_mat_inter_num: \n  assumes \"j1 < dim_col M\" \"j2 < dim_col M\"\n  shows \"(col M j1) \\<bullet> (col M j2) = of_nat (mat_inter_num M j1 j2)\"\nproof -\n  have split: \"{0..<dim_row M} = {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } \\<union> \n    {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0}\" using assms M_not_zero_simp by auto\n  have inter: \"{i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } \\<inter> \n    {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0} = {}\" by auto\n  have \"(col M j1) \\<bullet> (col M j2) = (\\<Sum> i \\<in> {0..<dim_row M} . (col M j1) $ i * (col M j2) $ i)\" \n    using assms scalar_prod_def by (metis (full_types) dim_col) \n  also have \"... = (\\<Sum> i \\<in> {0..<dim_row M} . M $$ (i, j1) * M $$ (i, j2))\" \n    using assms by simp\n  also have \"... = (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } . M $$ (i, j1) * M $$ (i, j2)) \n      + (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0} . M $$ (i, j1) * M $$ (i, j2))\" \n    using split inter sum.union_disjoint[of \" {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1)}\" \n      \"{i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0}\" \"\\<lambda> i . M $$ (i, j1) * M $$ (i, j2)\"]\n    by (metis (no_types, lifting) finite_Un finite_atLeastLessThan) \n  also have \"... = (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } . 1) \n      + (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0} . 0)\" \n    using sum.cong mem_Collect_eq by (smt (z3) mult.right_neutral mult_not_zero) \n  finally have \"(col M j1) \\<bullet> (col M j2) = \n      of_nat (card {i . i < dim_row M \\<and> (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1)})\"\n    by simp \n  then show ?thesis using mat_inter_num_def[of M j1 j2] by simp\nqed\n\nend\n\ntext \\<open> Any matrix generated by @{term \"inc_mat_of\"} is a 0-1 matrix.\\<close>\nlemma inc_mat_of_01_mat: \"zero_one_matrix_ring_1 (inc_mat_of Vs Bs)\"\n  by (unfold_locales) (simp add: inc_mat_one_zero_elems) \n\nsubsection \\<open>Ordered Incidence Systems \\<close>\ntext \\<open>We impose an arbitrary ordering on the point set and block collection to enable\nmatrix reasoning. Note that this is also common in computer algebra representations of designs \\<close>\n\nlocale ordered_incidence_system =\n  fixes \\<V>s :: \"'a list\" and \\<B>s :: \"'a set list\"\n  assumes wf_list: \"b \\<in># (mset \\<B>s) \\<Longrightarrow> b \\<subseteq> set \\<V>s\"\n  assumes distinct: \"distinct \\<V>s\"\n\ntext \\<open>An ordered incidence system, as it is defined on lists, can only represent finite incidence systems \\<close>\nsublocale ordered_incidence_system \\<subseteq> finite_incidence_system \"set \\<V>s\" \"mset \\<B>s\"\n  by(unfold_locales) (auto simp add: wf_list)\n\nlemma ordered_incidence_sysI: \n  assumes \"finite_incidence_system \\<V> \\<B>\" \n  assumes \"\\<V>s \\<in> permutations_of_set \\<V>\" and \"\\<B>s \\<in> permutations_of_multiset \\<B>\"\n  shows \"ordered_incidence_system \\<V>s \\<B>s\"\nproof -\n  have veq: \"\\<V> = set \\<V>s\" using assms permutations_of_setD(1) by auto \n  have beq: \"\\<B> = mset \\<B>s\" using assms permutations_of_multisetD by auto\n  interpret fisys: finite_incidence_system \"set \\<V>s\" \"mset \\<B>s\" using assms(1) veq beq by simp\n  show ?thesis proof (unfold_locales)\n    show \"\\<And>b. b \\<in># mset \\<B>s \\<Longrightarrow> b \\<subseteq> set \\<V>s\" using fisys.wellformed\n      by simp \n    show \"distinct \\<V>s\" using assms permutations_of_setD(2) by auto\n  qed\nqed\n\nlemma ordered_incidence_sysII: \n  assumes \"finite_incidence_system \\<V> \\<B>\" and \"set \\<V>s = \\<V>\" and \"distinct \\<V>s\" and \"mset \\<B>s = \\<B>\"\n  shows \"ordered_incidence_system \\<V>s \\<B>s\"\nproof -\n  interpret fisys: finite_incidence_system \"set \\<V>s\" \"mset \\<B>s\" using assms by simp\n  show ?thesis using fisys.wellformed assms by (unfold_locales) (simp_all)\nqed\n\ncontext ordered_incidence_system \nbegin\ntext \\<open>For ease of notation, establish the same notation as for incidence systems \\<close>\n\nabbreviation \"\\<V> \\<equiv> set \\<V>s\"\nabbreviation \"\\<B> \\<equiv> mset \\<B>s\"\n\ntext \\<open>Basic properties on ordered lists \\<close>\nlemma points_indexing: \"\\<V>s \\<in> permutations_of_set \\<V>\"\n  by (simp add: permutations_of_set_def distinct)\n\nlemma blocks_indexing: \"\\<B>s \\<in> permutations_of_multiset \\<B>\"\n  by (simp add: permutations_of_multiset_def)\n\nlemma points_list_empty_iff: \"\\<V>s = [] \\<longleftrightarrow> \\<V> = {}\"\n  using finite_sets points_indexing\n  by (simp add: elem_permutation_of_set_empty_iff) \n\nlemma points_indexing_inj: \"\\<forall> i \\<in> I . i < length \\<V>s \\<Longrightarrow> inj_on ((!) \\<V>s) I\"\n  by (simp add: distinct inj_on_nth)\n\nlemma blocks_list_empty_iff: \"\\<B>s = [] \\<longleftrightarrow> \\<B> = {#}\"\n  using blocks_indexing by (simp) \n\nlemma blocks_list_nempty: \"proper_design \\<V> \\<B> \\<Longrightarrow> \\<B>s \\<noteq> []\"\n  using mset.simps(1) proper_design.design_blocks_nempty by blast\n\nlemma points_list_nempty: \"proper_design \\<V> \\<B> \\<Longrightarrow> \\<V>s \\<noteq> []\"\n  using proper_design.design_points_nempty points_list_empty_iff by blast\n\nlemma points_list_length: \"length \\<V>s = \\<v>\"\n  using points_indexing\n  by (simp add: length_finite_permutations_of_set) \n\nlemma blocks_list_length: \"length \\<B>s = \\<b>\"\n  using blocks_indexing length_finite_permutations_of_multiset by blast\n\nlemma valid_points_index: \"i < \\<v> \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>\"\n  using points_list_length by simp \n\nlemma valid_points_index_cons: \"x \\<in> \\<V> \\<Longrightarrow> \\<exists> i. \\<V>s ! i = x \\<and> i < \\<v>\"\n  using points_list_length by (auto simp add: in_set_conv_nth)\n\nlemma valid_points_index_obtains: \n  assumes \"x \\<in> \\<V>\"\n  obtains i where \"\\<V>s ! i = x \\<and> i < \\<v>\"\n  using valid_points_index_cons assms by auto\n\nlemma valid_blocks_index: \"j < \\<b> \\<Longrightarrow> \\<B>s ! j \\<in># \\<B>\"\n  using blocks_list_length by (metis nth_mem_mset)\n\nlemma valid_blocks_index_cons: \"bl \\<in># \\<B> \\<Longrightarrow> \\<exists> j . \\<B>s ! j = bl \\<and> j < \\<b>\"\n  by (auto simp add: in_set_conv_nth)\n\nlemma valid_blocks_index_obtains: \n  assumes \"bl \\<in># \\<B>\"\n  obtains j where  \"\\<B>s ! j = bl \\<and> j < \\<b>\"\n  using assms valid_blocks_index_cons by auto\n\nlemma block_points_valid_point_index: \n  assumes \"bl \\<in># \\<B>\" \"x \\<in> bl\"\n  obtains i where \"i < length \\<V>s \\<and> \\<V>s ! i = x\"\n  using wellformed valid_points_index_obtains assms\n  by (metis points_list_length wf_invalid_point) \n\nlemma points_set_index_img: \"\\<V> = image(\\<lambda> i . (\\<V>s ! i)) ({..<\\<v>})\"\n  using valid_points_index_cons valid_points_index by auto\n\nlemma blocks_mset_image: \"\\<B> = image_mset (\\<lambda> i . (\\<B>s ! i)) (mset_set {..<\\<b>})\"\n  by (simp add: mset_list_by_index)\n\nlemma incidence_cond_indexed[simp]: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> incident (\\<V>s ! i) (\\<B>s ! j) \\<longleftrightarrow> (\\<V>s ! i) \\<in> (\\<B>s ! j)\"\n  using incidence_alt_def valid_points_index valid_blocks_index by simp\n\nlemma bij_betw_points_index: \"bij_betw (\\<lambda> i. \\<V>s ! i) {0..<\\<v>} \\<V>\"\nproof (simp add: bij_betw_def, intro conjI)\n  show \"inj_on ((!) \\<V>s) {0..<\\<v>}\"\n    by (simp add: points_indexing_inj points_list_length) \n  show \"(!) \\<V>s ` {0..<\\<v>} = \\<V>\" \n  proof (intro subset_antisym subsetI)\n    fix x assume \"x \\<in> (!) \\<V>s ` {0..<\\<v>}\" \n    then obtain i where \"x = \\<V>s ! i\" and \"i < \\<v>\" by auto\n    then show \"x \\<in> \\<V>\"\n      by (simp add: valid_points_index) \n  next \n    fix x assume \"x \\<in> \\<V>\"\n    then obtain i where \"\\<V>s ! i = x\" and \"i <\\<v>\"\n      using valid_points_index_cons by auto \n    then show \"x \\<in> (!) \\<V>s ` {0..<\\<v>}\" by auto\n  qed\nqed\n\ntext \\<open>Some lemmas on cardinality due to different set descriptor filters \\<close>\nlemma card_filter_point_indices: \"card {i \\<in> {0..<\\<v>}. P (\\<V>s ! i)} = card {v \\<in> \\<V> . P v }\"\nproof -\n  have \"{v \\<in> \\<V> . P v }= (\\<lambda> i. \\<V>s ! i) ` {i \\<in> {0..<\\<v>}. P (\\<V>s ! i)}\"\n    by (metis Compr_image_eq lessThan_atLeast0 points_set_index_img)\n  thus ?thesis using inj_on_nth points_list_length\n    by (metis (no_types, lifting) card_image distinct lessThan_atLeast0 lessThan_iff mem_Collect_eq)\nqed\n\nlemma card_block_points_filter: \n  assumes \"j < \\<b>\"\n  shows \"card (\\<B>s ! j) = card {i \\<in> {0..<\\<v>} . (\\<V>s ! i) \\<in> (\\<B>s ! j)}\"\nproof -\n  obtain bl where \"bl \\<in># \\<B>\" and blis: \"bl = \\<B>s ! j\"\n    using assms by auto\n  then have cbl: \"card bl = card {v \\<in> \\<V> . v \\<in> bl}\" using block_size_alt by simp\n  have \"\\<V> = (\\<lambda> i. \\<V>s ! i) ` {0..<\\<v>}\" using bij_betw_points_index\n    using lessThan_atLeast0 points_set_index_img by presburger\n  then have \"Set.filter (\\<lambda> v . v \\<in> bl) \\<V> = Set.filter (\\<lambda> v . v \\<in> bl) ((\\<lambda> i. \\<V>s ! i) ` {0..<\\<v>})\"\n    by presburger \n  have \"card {i \\<in> {0..<\\<v>} . (\\<V>s ! i) \\<in> bl} = card {v \\<in> \\<V> . v \\<in> bl}\" \n    using card_filter_point_indices by simp\n  thus ?thesis using cbl blis by simp\nqed\n\nlemma obtains_two_diff_block_indexes: \n  assumes \"j1 < \\<b>\"\n  assumes \"j2 < \\<b>\"\n  assumes \"j1 \\<noteq> j2\"\n  assumes \"\\<b> \\<ge> 2\"\n  obtains bl1 bl2 where \"bl1 \\<in># \\<B>\" and \"\\<B>s ! j1 = bl1\" and \"bl2 \\<in># \\<B> - {#bl1#}\" and \"\\<B>s ! j2 = bl2\"\nproof -\n  have j1lt: \"min j1 (length \\<B>s) = j1\" using assms by auto\n  obtain bl1 where bl1in: \"bl1 \\<in># \\<B>\" and bl1eq: \"\\<B>s ! j1 = bl1\"\n    using assms(1) valid_blocks_index by blast\n  then have split: \"\\<B>s = take j1 \\<B>s @ \\<B>s!j1 # drop (Suc j1) \\<B>s\" \n    using assms id_take_nth_drop by auto\n  then have lj1: \"length (take j1 \\<B>s) = j1\" using j1lt by (simp add: length_take[of j1 \\<B>s]) \n  have \"\\<B> = mset (take j1 \\<B>s @ \\<B>s!j1 # drop (Suc j1) \\<B>s)\" using split assms(1) by presburger \n  then have bsplit: \"\\<B> = mset (take j1 \\<B>s) + {#bl1#} + mset (drop (Suc j1) \\<B>s)\" by (simp add: bl1eq)\n  then have btake: \"\\<B> - {#bl1#} = mset (take j1 \\<B>s) + mset (drop (Suc j1) \\<B>s)\" by simp\n  thus ?thesis proof (cases \"j2 < j1\")\n    case True\n    then have \"j2 < length (take j1 \\<B>s)\" using lj1 by simp\n    then obtain bl2 where bl2eq: \"bl2 = (take j1 \\<B>s) ! j2\" by auto\n    then have bl2eq2: \"bl2 = \\<B>s ! j2\"\n      by (simp add: True) \n    then have \"bl2 \\<in># \\<B> - {#bl1#}\" using btake\n      by (metis bl2eq \\<open>j2 < length (take j1 \\<B>s)\\<close> nth_mem_mset union_iff) \n    then show ?thesis using bl2eq2 bl1in bl1eq that by auto\n  next\n    case False\n    then have j2gt: \"j2 \\<ge> Suc j1\" using assms by simp\n    then obtain i where ieq: \"i = j2 - Suc j1\"\n      by simp \n    then have j2eq: \"j2 = (Suc j1) + i\" using j2gt by presburger\n    have \"length (drop (Suc j1) \\<B>s) = \\<b> - (Suc j1)\" using blocks_list_length by auto\n    then have \"i < length (drop (Suc j1) \\<B>s)\" using ieq assms blocks_list_length\n      using diff_less_mono j2gt by presburger \n    then obtain bl2 where bl2eq: \"bl2 = (drop (Suc j1) \\<B>s) ! i\" by auto\n    then have bl2in: \"bl2 \\<in># \\<B> - {#bl1#}\" using btake nth_mem_mset union_iff\n      by (metis \\<open>i < length (drop (Suc j1) \\<B>s)\\<close>) \n    then have \"bl2 = \\<B>s ! j2\" using bl2eq nth_drop blocks_list_length assms j2eq\n      by (metis Suc_leI)\n    then show ?thesis using bl1in bl1eq bl2in that by auto\n  qed\nqed\n\nlemma filter_size_blocks_eq_card_indexes: \"size {# b \\<in># \\<B> . P b #} = card {j \\<in> {..<(\\<b>)}. P (\\<B>s ! j)}\"\nproof -\n  have \"\\<B> = image_mset (\\<lambda> j . \\<B>s ! j) (mset_set {..<(\\<b>)})\" \n    using blocks_mset_image by simp\n  then have helper: \"{# b \\<in># \\<B> . P b #} = image_mset (\\<lambda> j . \\<B>s ! j) {# j \\<in># (mset_set {..< \\<b>}). P (\\<B>s ! j) #} \"\n    by (simp add: filter_mset_image_mset)\n  have \"card {j \\<in> {..<\\<b>}. P (\\<B>s ! j)} = size {# j \\<in># (mset_set {..< \\<b>}). P (\\<B>s ! j) #}\"\n    using card_size_filter_eq [of \"{..<\\<b>}\"] by simp\n  thus ?thesis using helper by simp\nqed\n\nlemma blocks_index_ne_belong: \n  assumes \"i1 < length \\<B>s\"\n  assumes \"i2 < length \\<B>s\"\n  assumes \"i1 \\<noteq> i2\"\n  shows \"\\<B>s ! i2 \\<in># \\<B> - {#(\\<B>s ! i1)#}\"\nproof (cases \"\\<B>s ! i1 = \\<B>s ! i2\")\n  case True\n  then have \"count (mset \\<B>s) (\\<B>s ! i1) \\<ge> 2\" using count_min_2_indices assms by fastforce\n  then have \"count ((mset \\<B>s) - {#(\\<B>s ! i1)#}) (\\<B>s ! i1) \\<ge> 1\"\n    by (metis Nat.le_diff_conv2 add_leD2 count_diff count_single nat_1_add_1) \n  then show ?thesis\n    by (metis True count_inI not_one_le_zero)\nnext\n  case False\n  have \"\\<B>s ! i2 \\<in># \\<B>\" using assms\n    by simp \n  then show ?thesis using False\n    by (metis in_remove1_mset_neq)\nqed\n\nlemma inter_num_points_filter_def: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\" \"j1 \\<noteq> j2\"\n  shows \"card {x \\<in> {0..<\\<v>} . ((\\<V>s ! x) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! x) \\<in> (\\<B>s ! j2)) } = (\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2)\"\nproof - \n  have inter: \"\\<And> v. v \\<in> \\<V> \\<Longrightarrow> v \\<in> (\\<B>s ! j1) \\<and> v \\<in> (\\<B>s ! j2) \\<longleftrightarrow> v \\<in> (\\<B>s ! j1) \\<inter> (\\<B>s ! j2)\"\n    by simp \n  obtain bl1 bl2 where bl1in: \"bl1 \\<in># \\<B>\" and bl1eq: \"\\<B>s ! j1 = bl1\" and bl2in: \"bl2 \\<in># \\<B> - {#bl1#}\" \n    and bl2eq: \"\\<B>s ! j2 = bl2\" \n    using assms obtains_two_diff_block_indexes\n    by (metis blocks_index_ne_belong size_mset valid_blocks_index) \n  have \"card {x \\<in> {0..<\\<v>} . (\\<V>s ! x) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! x) \\<in> (\\<B>s ! j2) } = \n      card {v \\<in> \\<V> . v \\<in> (\\<B>s ! j1) \\<and> v \\<in> (\\<B>s ! j2) }\" \n    using card_filter_point_indices by simp\n  also have \"... = card {v \\<in> \\<V> . v \\<in> bl1 \\<and> v \\<in> bl2 }\" using bl1eq bl2eq by simp\n  finally show ?thesis using points_inter_num_rep bl1in bl2in\n    by (simp add: bl1eq bl2eq) \nqed\n\ntext \\<open>Define an incidence matrix for this ordering of an incidence system \\<close>\n\nabbreviation N :: \"int mat\" where\n\"N \\<equiv> inc_mat_of \\<V>s \\<B>s\"\n\nsublocale zero_one_matrix_ring_1 \"N\"\n  using inc_mat_of_01_mat .\n\nlemma N_alt_def_dim: \"N = mat \\<v> \\<b> (\\<lambda> (i,j) . if (incident (\\<V>s ! i) (\\<B>s ! j)) then 1 else 0) \" \n  using incidence_cond_indexed inc_mat_of_def \n  by (intro eq_matI) (simp_all add: inc_mat_dim_row inc_mat_dim_col inc_matrix_point_in_block_one \n      inc_matrix_point_not_in_block_zero points_list_length)\n\ntext \\<open>Matrix Dimension related lemmas \\<close>\n \nlemma N_carrier_mat: \"N \\<in> carrier_mat \\<v> \\<b>\" \n  by (simp add: N_alt_def_dim)\n\nlemma dim_row_is_v[simp]: \"dim_row N = \\<v>\"\n  by (simp add: N_alt_def_dim)\n\nlemma dim_col_is_b[simp]: \"dim_col N = \\<b>\"\n  by (simp add:  N_alt_def_dim)\n\nlemma dim_vec_row_N: \"dim_vec (row N i) = \\<b>\"\n  by (simp add:  N_alt_def_dim)\n\nlemma dim_vec_col_N: \"dim_vec (col N i) = \\<v>\" by simp \n\nlemma dim_vec_N_col: \n  assumes \"j < \\<b>\"\n  shows \"dim_vec (cols N ! j) = \\<v>\"\nproof -\n  have \"cols N ! j = col N j\" using assms dim_col_is_b by simp\n  then have \"dim_vec (cols N ! j) = dim_vec (col N j)\" by simp\n  thus ?thesis using dim_col assms by (simp) \nqed\n\nlemma N_carrier_mat_01_lift: \"lift_01_mat N \\<in> carrier_mat \\<v> \\<b>\"\n  by auto\n\ntext \\<open>Transpose properties \\<close>\n\nlemma transpose_N_mult_dim: \"dim_row (N * N\\<^sup>T) = \\<v>\" \"dim_col (N * N\\<^sup>T) = \\<v>\"\n  by (simp_all)\n\nlemma N_trans_index_val: \"i < dim_col N \\<Longrightarrow> j < dim_row N \\<Longrightarrow> \n    N\\<^sup>T $$ (i, j) = (if (\\<V>s ! j) \\<in> (\\<B>s ! i) then 1 else 0)\"\n  by (simp add: inc_mat_of_def)\n\ntext \\<open>Matrix element and index related lemmas \\<close>\nlemma mat_row_elems: \"i < \\<v> \\<Longrightarrow> vec_set (row N i) \\<subseteq> {0, 1}\"\n  using points_list_length\n  by (simp add: row_elems_ss01) \n\nlemma mat_col_elems: \"j < \\<b> \\<Longrightarrow> vec_set (col N j) \\<subseteq> {0, 1}\"\n  using blocks_list_length by (metis col_elems_ss01 dim_col_is_b)\n\nlemma matrix_elems_one_zero: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 0 \\<or> N $$ (i, j) = 1\"\n  by (metis blocks_list_length inc_matrix_elems_one_zero points_list_length)\n\nlemma matrix_point_in_block_one: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> (\\<V>s ! i)\\<in> (\\<B>s ! j) \\<Longrightarrow>N $$ (i, j) = 1\"\n  by (metis inc_matrix_point_in_block_one points_list_length blocks_list_length )   \n\nlemma matrix_point_not_in_block_zero: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j \\<Longrightarrow> N $$ (i, j) = 0\"\n  by(metis inc_matrix_point_not_in_block_zero points_list_length blocks_list_length)\n\nlemma matrix_point_in_block: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 1 \\<Longrightarrow> \\<V>s ! i \\<in> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length  inc_matrix_point_in_block)\n\nlemma matrix_point_not_in_block: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 0 \\<Longrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length inc_matrix_point_not_in_block)\n\nlemma matrix_point_not_in_block_iff: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 0 \\<longleftrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length inc_matrix_point_not_in_block_iff)\n\nlemma matrix_point_in_block_iff: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 1 \\<longleftrightarrow> \\<V>s ! i \\<in> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length inc_matrix_point_in_block_iff)\n\nlemma matrix_subset_implies_one: \"I \\<subseteq> {..< \\<v>} \\<Longrightarrow> j < \\<b> \\<Longrightarrow> (!) \\<V>s ` I \\<subseteq> \\<B>s ! j \\<Longrightarrow> i \\<in> I \\<Longrightarrow> \n  N $$ (i, j) = 1\"\n  by (metis blocks_list_length points_list_length inc_matrix_subset_implies_one)\n\nlemma matrix_one_implies_membership: \n\"I \\<subseteq> {..< \\<v>} \\<Longrightarrow> j < size \\<B> \\<Longrightarrow> \\<forall>i\\<in>I. N $$ (i, j) = 1 \\<Longrightarrow> i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<B>s ! j\"\n  by (simp add: matrix_point_in_block_iff subset_iff)\n\ntext \\<open>Incidence Vector's of Incidence Matrix columns \\<close>\n\nlemma col_inc_vec_of: \"j < length \\<B>s \\<Longrightarrow> inc_vec_of \\<V>s (\\<B>s ! j) = col N j\"\n  by (simp add: inc_mat_col_inc_vec) \n\nlemma inc_vec_eq_iff_blocks: \n  assumes \"bl \\<in># \\<B>\"\n  assumes \"bl' \\<in># \\<B>\"\n  shows \"inc_vec_of \\<V>s bl = inc_vec_of \\<V>s bl' \\<longleftrightarrow> bl = bl'\"\nproof (intro iffI eq_vecI, simp_all add: inc_vec_dim assms)\n  define v1 :: \"'c :: {ring_1} vec\" where \"v1 = inc_vec_of \\<V>s bl\"\n  define v2 :: \"'c :: {ring_1} vec\" where \"v2 = inc_vec_of \\<V>s bl'\"\n  assume a: \"v1 = v2\"\n  then have \"dim_vec v1 = dim_vec v2\"\n    by (simp add: inc_vec_dim) \n  then have \"\\<And> i. i < dim_vec v1 \\<Longrightarrow> v1 $ i = v2 $ i\" using a by simp\n  then have \"\\<And> i. i < length \\<V>s \\<Longrightarrow> v1 $ i = v2 $ i\" by (simp add: v1_def inc_vec_dim)\n  then have \"\\<And> i. i < length \\<V>s \\<Longrightarrow> (\\<V>s ! i)  \\<in> bl \\<longleftrightarrow> (\\<V>s ! i)  \\<in> bl'\"\n    using  inc_vec_index_one_iff v1_def v2_def by metis \n  then have \"\\<And> x. x \\<in> \\<V> \\<Longrightarrow> x \\<in> bl \\<longleftrightarrow> x \\<in> bl'\"\n    using points_list_length valid_points_index_cons by auto \n  then show \"bl = bl'\" using wellformed assms\n    by (meson subset_antisym subset_eq)\nqed\n\ntext \\<open>Incidence matrix column properties\\<close>\n\nlemma N_col_def: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> (col N j) $ i = (if (\\<V>s ! i \\<in> \\<B>s ! j) then 1 else 0)\"\n  by (metis inc_mat_col_def points_list_length blocks_list_length) \n\nlemma N_col_def_indiv: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \\<V>s ! i \\<in> \\<B>s ! j \\<Longrightarrow> (col N j) $ i = 1\"\n     \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j \\<Longrightarrow> (col N j) $ i = 0\"\n  by(simp_all add: inc_matrix_point_in_block_one inc_matrix_point_not_in_block_zero points_list_length)\n\nlemma N_col_list_map_elem: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \n    col N j $ i = map_vec (\\<lambda> x . if (x \\<in> (\\<B>s ! j)) then 1 else 0) (vec_of_list \\<V>s) $ i\"\n  by (metis inc_mat_col_list_map_elem points_list_length blocks_list_length) \n\nlemma N_col_list_map: \"j < \\<b> \\<Longrightarrow> col N j = map_vec (\\<lambda> x . if (x \\<in> (\\<B>s ! j)) then 1 else 0) (vec_of_list \\<V>s)\"\n  by (metis inc_mat_col_list_map blocks_list_length) \n\nlemma N_col_mset_point_set_img: \"j < \\<b> \\<Longrightarrow> \n    vec_mset (col N j) = image_mset (\\<lambda> x. if (x \\<in> (\\<B>s ! j)) then 1 else 0) (mset_set \\<V>)\"\n  using vec_mset_img_map N_col_list_map points_indexing\n  by (metis (no_types, lifting) finite_sets permutations_of_multisetD permutations_of_set_altdef) \n\nlemma matrix_col_to_block: \n  assumes \"j < \\<b>\"\n  shows \"\\<B>s ! j = (\\<lambda> k . \\<V>s ! k) ` {i \\<in> {..< \\<v>} . (col N j) $ i = 1}\"\nproof (intro subset_antisym subsetI)\n  fix x assume assm1: \"x \\<in> \\<B>s ! j\"\n  then have \"x \\<in> \\<V>\" using wellformed assms valid_blocks_index by blast \n  then obtain i where vs: \"\\<V>s ! i = x\" and \"i < \\<v>\"\n    using valid_points_index_cons by auto \n  then have inset: \"i \\<in> {..< \\<v>}\"\n    by fastforce\n  then have \"col N j $ i = 1\" using assm1 N_col_def assms vs\n    using \\<open>i < \\<v>\\<close> by presburger \n  then have \"i \\<in> {i. i \\<in> {..< \\<v>} \\<and> col N j $ i = 1}\"\n    using inset by blast\n  then show \"x \\<in> (!) \\<V>s ` {i.  i \\<in> {..<\\<v>} \\<and> col N j $ i = 1}\" using vs by blast\nnext\n  fix x assume assm2: \"x \\<in> ((\\<lambda> k . \\<V>s ! k) ` {i \\<in> {..< \\<v>} . col N j $ i = 1})\"\n  then obtain k where \"x = \\<V>s !k\" and inner: \"k \\<in>{i \\<in> {..< \\<v>} . col N j $ i = 1}\"\n    by blast \n  then have ilt: \"k < \\<v>\" by auto\n  then have \"N $$ (k, j) = 1\" using inner\n    by (metis (mono_tags) N_col_def assms matrix_point_in_block_iff matrix_point_not_in_block_zero mem_Collect_eq) \n  then show \"x \\<in> \\<B>s ! j\" using ilt\n    using \\<open>x = \\<V>s ! k\\<close> assms matrix_point_in_block_iff by blast\nqed\n\nlemma matrix_col_to_block_v2: \"j < \\<b> \\<Longrightarrow> \\<B>s ! j = (\\<lambda> k . \\<V>s ! k) ` map_col_to_block (col N j)\"\n  using matrix_col_to_block map_col_to_block_def by fastforce\n\nlemma matrix_col_in_blocks: \"j < \\<b> \\<Longrightarrow> (!) \\<V>s ` map_col_to_block (col N j) \\<in># \\<B>\"\n  using matrix_col_to_block_v2 by (metis (no_types, lifting) valid_blocks_index) \n\nlemma inc_matrix_col_block: \n  assumes \"c \\<in> set (cols N)\"\n  shows \"(\\<lambda> x. \\<V>s ! x) ` (map_col_to_block c) \\<in># \\<B>\"\nproof -\n  obtain j where \"c = col N j\" and \"j < \\<b>\" using assms cols_length cols_nth in_mset_conv_nth \n    ordered_incidence_system_axioms set_mset_mset by (metis dim_col_is_b)  \n  thus ?thesis\n    using matrix_col_in_blocks by blast \nqed\n\ntext \\<open> Incidence Matrix Row Definitions \\<close>\nlemma N_row_def: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> (row N i) $ j = (if (\\<V>s ! i \\<in> \\<B>s ! j) then 1 else 0)\"\n  by (metis inc_mat_row_def points_list_length blocks_list_length) \n\nlemma N_row_list_map_elem: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \n    row N i $ j = map_vec (\\<lambda> bl . if ((\\<V>s ! i) \\<in> bl) then 1 else 0) (vec_of_list \\<B>s) $ j\"\n  by (metis inc_mat_row_list_map_elem points_list_length blocks_list_length) \n\nlemma N_row_list_map: \"i < \\<v> \\<Longrightarrow> \n    row N i = map_vec (\\<lambda> bl . if ((\\<V>s ! i) \\<in> bl) then 1 else 0) (vec_of_list \\<B>s)\"\n  by (simp add: inc_mat_row_list_map points_list_length blocks_list_length) \n\nlemma N_row_mset_blocks_img: \"i < \\<v> \\<Longrightarrow> \n    vec_mset (row N i) = image_mset (\\<lambda> x . if ((\\<V>s ! i) \\<in> x) then 1 else 0) \\<B>\"\n  using vec_mset_img_map N_row_list_map by metis\n\ntext \\<open>Alternate Block representations \\<close>\n\nlemma block_mat_cond_rep:\n  assumes \"j < length \\<B>s\"\n  shows \"(\\<B>s ! j) = {\\<V>s ! i | i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\nproof -\n  have cond: \"\\<And> i. i < length \\<V>s \\<and> N $$ (i, j) = 1 \\<longleftrightarrow>i \\<in> {..< \\<v>} \\<and> (col N j) $ i = 1\"\n    using assms points_list_length by auto\n  have \"(\\<B>s ! j) = (\\<lambda> k . \\<V>s ! k) ` {i \\<in> {..< \\<v>} . (col N j) $ i = 1}\" \n    using matrix_col_to_block assms by simp\n  also have \"... = {\\<V>s ! i | i. i \\<in> {..< \\<v>} \\<and> (col N j) $ i = 1}\" by auto\n  finally show \"(\\<B>s ! j) = {\\<V>s ! i | i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\n    using Collect_cong cond by auto\nqed\n\nlemma block_mat_cond_rep': \"j < length \\<B>s \\<Longrightarrow> (\\<B>s ! j) = ((!) \\<V>s) ` {i . i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\n  by (simp add: block_mat_cond_rep setcompr_eq_image)\n\nlemma block_mat_cond_rev: \n  assumes \"j < length \\<B>s\"\n  shows \"{i . i < length \\<V>s \\<and> N $$ (i, j) = 1} = ((List_Index.index) \\<V>s) ` (\\<B>s ! j)\"\nproof (intro Set.set_eqI iffI)\n  fix i assume a1: \"i \\<in> {i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\n  then have ilt1: \"i < length \\<V>s\" and Ni1: \"N $$ (i, j) = 1\" by auto\n  then obtain x where \"\\<V>s ! i = x\" and \"x \\<in> (\\<B>s ! j)\"\n    using assms inc_matrix_point_in_block by blast  \n  then have \"List_Index.index \\<V>s x = i\" using distinct  index_nth_id ilt1 by auto\n  then show \"i \\<in> List_Index.index \\<V>s ` \\<B>s ! j\" by (metis \\<open>x \\<in> \\<B>s ! j\\<close> imageI) \nnext\n  fix i assume a2: \"i \\<in> List_Index.index \\<V>s ` \\<B>s ! j\"\n  then obtain x where ieq: \"i = List_Index.index \\<V>s x\" and xin: \"x \\<in> \\<B>s !j\"\n    by blast \n  then have ilt: \"i < length \\<V>s\"\n    by (smt (z3) assms index_first index_le_size nat_less_le nth_mem_mset points_list_length \n        valid_points_index_cons wf_invalid_point)\n  then have \"N $$ (i, j) = 1\" using xin inc_matrix_point_in_block_one\n    by (metis ieq assms index_conv_size_if_notin less_irrefl_nat nth_index)\n  then show \"i \\<in> {i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\" using ilt by simp\nqed\n\ntext \\<open>Incidence Matrix incidence system properties \\<close>\nlemma incomplete_block_col:\n  assumes \"j < \\<b>\"\n  assumes \"incomplete_block (\\<B>s ! j)\"\n  shows \"0 \\<in>$ (col N j)\" \nproof -\n  obtain x where \"x \\<in> \\<V>\" and \"x \\<notin> (\\<B>s ! j)\"\n    by (metis Diff_iff assms(2) incomplete_block_proper_subset psubset_imp_ex_mem)\n  then obtain i where \"\\<V>s ! i = x\" and \"i< \\<v>\" \n    using valid_points_index_cons by blast \n  then have \"N $$ (i, j) = 0\"\n    using \\<open>x \\<notin> \\<B>s ! j\\<close> assms(1) matrix_point_not_in_block_zero by blast \n  then have \"col N j $ i = 0\"\n    using N_col_def \\<open>\\<V>s ! i = x\\<close> \\<open>i < \\<v>\\<close> \\<open>x \\<notin> \\<B>s ! j\\<close> assms(1) by fastforce \n  thus ?thesis using vec_setI\n    by (smt (z3) \\<open>i < \\<v>\\<close> dim_col dim_row_is_v)\nqed\n\nlemma mat_rep_num_N_row: \n  assumes \"i < \\<v>\"\n  shows \"mat_rep_num N i = \\<B> rep (\\<V>s ! i)\"\nproof -\n  have \"count (image_mset (\\<lambda> x . if ((\\<V>s ! i) \\<in> x) then 1 else (0 :: int )) \\<B>) 1 = \n    size (filter_mset (\\<lambda> x . (\\<V>s ! i) \\<in> x) \\<B>)\"\n    using count_mset_split_image_filter[of \"\\<B>\" \"1\" \"\\<lambda> x . (0 :: int)\" \"\\<lambda> x . (\\<V>s ! i) \\<in> x\"] by simp\n  then have \"count (image_mset (\\<lambda> x . if ((\\<V>s ! i) \\<in> x) then 1 else (0 :: int )) \\<B>) 1\n    = \\<B> rep (\\<V>s ! i)\" by (simp add: point_rep_number_alt_def)\n  thus ?thesis using N_row_mset_blocks_img assms\n    by (simp add: mat_rep_num_def) \nqed\n\nlemma point_rep_mat_row_sum:  \"i < \\<v> \\<Longrightarrow> sum_vec (row N i) = \\<B> rep (\\<V>s ! i)\"\n  using count_vec_sum_ones_alt mat_rep_num_N_row mat_row_elems mat_rep_num_def by metis \n\nlemma mat_block_size_N_col: \n  assumes \"j < \\<b>\"\n  shows \"mat_block_size N j = card (\\<B>s ! j)\"\nproof -\n  have val_b: \"\\<B>s ! j \\<in># \\<B>\" using assms valid_blocks_index by auto \n  have \"\\<And> x. x \\<in># mset_set \\<V> \\<Longrightarrow> (\\<lambda>x . (0 :: int)) x \\<noteq> 1\" using zero_neq_one by simp\n  then have \"count (image_mset (\\<lambda> x. if (x \\<in> (\\<B>s ! j)) then 1 else (0 :: int)) (mset_set \\<V>)) 1 = \n    size (filter_mset (\\<lambda> x . x \\<in> (\\<B>s ! j)) (mset_set \\<V>))\"\n    using count_mset_split_image_filter [of \"mset_set \\<V>\" \"1\" \"(\\<lambda> x . (0 :: int))\" \"\\<lambda> x . x \\<in> \\<B>s ! j\"] \n    by simp\n  then have \"count (image_mset (\\<lambda> x. if (x \\<in> (\\<B>s ! j)) then 1 else (0 :: int)) (mset_set \\<V>)) 1 = card (\\<B>s ! j)\"\n    using val_b block_size_alt by (simp add: finite_sets)\n  thus ?thesis using N_col_mset_point_set_img assms mat_block_size_def by metis \nqed\n\nlemma block_size_mat_rep_sum: \"j < \\<b> \\<Longrightarrow> sum_vec (col N j) = mat_block_size N j\"\n  using count_vec_sum_ones_alt mat_block_size_N_col mat_block_size_def by (metis mat_col_elems) \n\nlemma mat_point_index_rep:\n  assumes \"I \\<subseteq> {..<\\<v>}\"\n  shows \"mat_point_index N I = \\<B> index ((\\<lambda> i. \\<V>s ! i) ` I)\"\nproof - \n  have \"\\<And> i . i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>\" using assms valid_points_index by auto \n  then have eqP: \"\\<And> j. j < dim_col N \\<Longrightarrow> ((\\<lambda> i. \\<V>s ! i) ` I) \\<subseteq> (\\<B>s ! j) \\<longleftrightarrow> (\\<forall> i \\<in> I . N $$ (i, j) = 1)\"\n  proof (intro iffI subsetI, simp_all)\n    show \"\\<And>j i. j < length \\<B>s \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>) \\<Longrightarrow> (!) \\<V>s ` I \\<subseteq> \\<B>s ! j \\<Longrightarrow> \n        \\<forall>i\\<in>I. N $$ (i, j) = 1\"\n      using matrix_subset_implies_one assms by simp\n    have \"\\<And>x.  x\\<in> (!) \\<V>s ` I \\<Longrightarrow> \\<exists> i \\<in> I. \\<V>s ! i = x\"\n      by auto \n    then show \"\\<And>j x. j < length \\<B>s \\<Longrightarrow> \\<forall>i\\<in>I. N $$ (i, j) = 1 \\<Longrightarrow> x \\<in> (!) \\<V>s ` I \n        \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>) \\<Longrightarrow> x \\<in> \\<B>s ! j\"\n      using assms matrix_one_implies_membership by (metis blocks_list_length) \n  qed\n  have \"card {j . j < dim_col N \\<and> (\\<forall> i \\<in> I . N $$(i, j) = 1)} = \n      card {j . j < dim_col N \\<and> ((\\<lambda> i . \\<V>s ! i) ` I) \\<subseteq> \\<B>s ! j}\"\n    using eqP by (metis (mono_tags, lifting))\n  also have \"... = size {# b \\<in># \\<B> . ((\\<lambda> i . \\<V>s ! i) ` I) \\<subseteq> b #}\"\n    using filter_size_blocks_eq_card_indexes by auto\n  also have \"... = points_index \\<B> ((\\<lambda> i . \\<V>s ! i) ` I)\"\n    by (simp add: points_index_def)\n  finally have \"card {j . j < dim_col N \\<and> (\\<forall> i \\<in> I . N $$(i, j) = 1)} = \\<B> index ((\\<lambda> i . \\<V>s ! i) ` I)\"\n    by blast\n  thus ?thesis unfolding mat_point_index_def by simp\nqed\n\nlemma incidence_mat_two_index: \"i1 < \\<v> \\<Longrightarrow> i2 < \\<v> \\<Longrightarrow> \n    mat_point_index N {i1, i2} = \\<B> index {\\<V>s ! i1, \\<V>s ! i2}\"\n  using mat_point_index_two_alt[of  i1 N i2 ] mat_point_index_rep[of \"{i1, i2}\"] dim_row_is_v\n  by (metis (no_types, lifting) empty_subsetI image_empty image_insert insert_subset lessThan_iff) \n\nlemma ones_incidence_mat_block_size: \n  assumes \"j < \\<b>\"\n  shows \"((u\\<^sub>v \\<v>) \\<^sub>v* N) $ j = mat_block_size N j\"\nproof - \n  have \"dim_vec ((u\\<^sub>v \\<v>) \\<^sub>v* N) = \\<b>\" by (simp) \n  then have \"((u\\<^sub>v \\<v>) \\<^sub>v* N) $ j = (u\\<^sub>v \\<v>) \\<bullet> col N j\" using assms by simp \n  also have \"... = (\\<Sum> i \\<in> {0 ..< \\<v>}. (u\\<^sub>v \\<v>) $ i * (col N j) $ i)\" \n    by (simp add: scalar_prod_def)\n  also have \"... = sum_vec (col N j)\" using dim_row_is_v by (simp add: sum_vec_def)\n  finally show ?thesis  using block_size_mat_rep_sum assms by simp\nqed\n\nlemma mat_block_size_conv:  \"j < dim_col N \\<Longrightarrow> card (\\<B>s ! j) = mat_block_size N j\"\n  by (simp add: mat_block_size_N_col)\n\nlemma mat_inter_num_conv: \n  assumes \"j1 < dim_col N\" \"j2 < dim_col N\"\n  shows \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = mat_inter_num N j1 j2\"\nproof -\n  have eq_sets: \"\\<And> P. (\\<lambda> i . \\<V>s ! i) ` {i \\<in> {0..<\\<v>}. P (\\<V>s ! i)} = {x \\<in> \\<V> . P x}\"\n    by (metis Compr_image_eq lessThan_atLeast0 points_set_index_img)\n  have bin: \"\\<B>s ! j1 \\<in># \\<B>\" \"\\<B>s ! j2 \\<in># \\<B>\" using assms dim_col_is_b by simp_all\n  have \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = card ((\\<B>s ! j1) \\<inter> (\\<B>s ! j2))\" \n    by (simp add: intersection_number_def)\n  also have \"... = card {x . x \\<in> (\\<B>s ! j1) \\<and> x \\<in> (\\<B>s ! j2)}\"\n    by (simp add: Int_def) \n  also have \"... = card {x \\<in> \\<V>. x \\<in> (\\<B>s ! j1) \\<and> x \\<in> (\\<B>s ! j2)}\" using wellformed bin\n    by (meson wf_invalid_point) \n  also have \"... = card ((\\<lambda> i . \\<V>s ! i) ` {i \\<in> {0..<\\<v>}. (\\<V>s ! i) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j2)})\" \n    using eq_sets[of \"\\<lambda> x. x \\<in> (\\<B>s ! j1) \\<and> x \\<in> (\\<B>s ! j2)\"] by simp\n  also have \"... = card ({i \\<in> {0..<\\<v>}. (\\<V>s ! i) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j2)})\"\n    using points_indexing_inj card_image\n    by (metis (no_types, lifting) lessThan_atLeast0 lessThan_iff mem_Collect_eq points_list_length) \n  also have \"... = card ({i . i < \\<v> \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j2)})\" by auto\n  also have \"... = card ({i . i < \\<v> \\<and> N $$ (i, j1) = 1 \\<and> N $$ (i, j2) = 1})\" using assms\n    by (metis (no_types, opaque_lifting) inc_mat_dim_col inc_matrix_point_in_block_iff points_list_length) \n  finally have \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = card {i . i < dim_row N \\<and> N $$ (i, j1) = 1 \\<and> N $$ (i, j2) = 1}\"\n    using dim_row_is_v by presburger\n  thus ?thesis using assms by (simp add: mat_inter_num_def)\nqed\n\nlemma non_empty_col_map_conv: \n  assumes \"j < dim_col N\"\n  shows \"non_empty_col N j \\<longleftrightarrow> \\<B>s ! j \\<noteq> {}\"\nproof (intro iffI)\n  assume \"non_empty_col N j\"\n  then obtain i where ilt: \"i < dim_row N\" and \"(col N j) $ i \\<noteq> 0\"\n    using non_empty_col_obtains assms by blast\n  then have \"(col N j) $ i = 1\"\n    using assms\n    by (metis N_col_def_indiv(1) N_col_def_indiv(2) dim_col_is_b dim_row_is_v) \n  then have \"\\<V>s ! i \\<in> \\<B>s ! j\"\n    by (smt (verit, best) assms ilt inc_mat_col_def dim_col_is_b inc_mat_dim_col inc_mat_dim_row) \n  thus \"\\<B>s ! j \\<noteq> {}\" by blast\nnext\n  assume a: \"\\<B>s ! j \\<noteq> {}\"\n  have \"\\<B>s ! j \\<in># \\<B>\" using assms dim_col_is_b by simp\n  then obtain x where \"x \\<in> \\<B>s ! j\" and \"x \\<in> \\<V>\" using wellformed a by auto\n  then obtain i where \"\\<V>s ! i \\<in> \\<B>s ! j\" and \"i < dim_row N\" using dim_row_is_v\n    using valid_points_index_cons by auto \n  then have \"N $$ (i, j) = 1\"\n    using assms by (meson inc_mat_of_index)  \n  then show \"non_empty_col N j\" using non_empty_col_alt_def\n    using \\<open>i < dim_row N\\<close> assms by fastforce \nqed\n\nlemma scalar_prod_inc_vec_inter_num: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\"\n  shows \"(col N j1) \\<bullet> (col N j2) = (\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2)\"\n  using scalar_prod_inc_vec_mat_inter_num assms N_carrier_mat\n  by (simp add: mat_inter_num_conv)\n\nlemma scalar_prod_block_size_lift_01: \n  assumes \"i < \\<b>\"\n  shows \"((col (lift_01_mat N) i) \\<bullet> (col (lift_01_mat N) i)) = (of_nat (card (\\<B>s ! i)) :: ('b :: {ring_1}))\"\nproof -\n  interpret z1: zero_one_matrix_ring_1 \"(lift_01_mat N)\"\n    by (intro_locales) (simp add: lift_mat_is_0_1)\n  show ?thesis using assms z1.scalar_prod_inc_vec_block_size_mat preserve_mat_block_size \n      mat_block_size_N_col lift_01_mat_def\n    by (metis inc_mat_dim_col lift_01_mat_simp(2) of_inj_on_01_hom.inj_on_01_hom_axioms size_mset)\nqed\n\nlemma scalar_prod_inter_num_lift_01: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\"\n  shows \"((col (lift_01_mat N) j1) \\<bullet> (col (lift_01_mat N) j2)) = (of_nat ((\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2)) :: ('b :: {ring_1}))\"\nproof -\n  interpret z1: zero_one_matrix_ring_1 \"(lift_01_mat N)\"\n    by (intro_locales) (simp add: lift_mat_is_0_1)\n  show ?thesis using assms z1.scalar_prod_inc_vec_mat_inter_num preserve_mat_inter_num \n    mat_inter_num_conv lift_01_mat_def blocks_list_length inc_mat_dim_col\n    by (metis  lift_01_mat_simp(2) of_inj_on_01_hom.inj_on_01_hom_axioms)\nqed\n\ntext \\<open> The System complement's incidence matrix flips 0's and 1's \\<close>\n\nlemma map_block_complement_entry: \"j < \\<b> \\<Longrightarrow> (map block_complement \\<B>s) ! j = block_complement (\\<B>s ! j)\"\n  using blocks_list_length by (metis nth_map) \n\nlemma complement_mat_entries: \n  assumes \"i < \\<v>\" and \"j < \\<b>\"\n  shows \"(\\<V>s ! i \\<notin> \\<B>s ! j) \\<longleftrightarrow> (\\<V>s ! i \\<in> (map block_complement \\<B>s) ! j)\"\n  using assms block_complement_def map_block_complement_entry valid_points_index by simp\n\nlemma length_blocks_complement: \"length (map block_complement \\<B>s) = \\<b>\"\n  by auto \n\nlemma ordered_complement: \"ordered_incidence_system \\<V>s (map block_complement \\<B>s)\"\nproof -\n  interpret inc: finite_incidence_system \\<V> \"complement_blocks\"\n    by (simp add: complement_finite)\n  have \"map inc.block_complement \\<B>s \\<in> permutations_of_multiset complement_blocks\"\n    using complement_image by (simp add: permutations_of_multiset_def)\n  then show ?thesis using ordered_incidence_sysI[of \"\\<V>\" \"complement_blocks\" \"\\<V>s\" \"(map block_complement \\<B>s)\"]\n    by (simp add: inc.finite_incidence_system_axioms points_indexing) \nqed\n\ninterpretation ordered_comp: ordered_incidence_system \"\\<V>s\" \"(map block_complement \\<B>s)\"\n  using ordered_complement by simp\n\nlemma complement_mat_entries_val: \n  assumes \"i < \\<v>\" and \"j < \\<b>\"\n  shows \"ordered_comp.N $$ (i, j) = (if \\<V>s ! i \\<in> \\<B>s ! j then 0 else 1)\"\nproof -\n  have cond: \"(\\<V>s ! i \\<notin> \\<B>s ! j) \\<longleftrightarrow> (\\<V>s ! i \\<in> (map block_complement \\<B>s) ! j)\"\n    using complement_mat_entries assms by simp\n  then have \"ordered_comp.N $$ (i, j) = (if (\\<V>s ! i \\<in> (map block_complement \\<B>s) ! j) then 1 else 0)\"\n    using assms ordered_comp.matrix_point_in_block_one ordered_comp.matrix_point_not_in_block_iff \n    by force \n  then show ?thesis using cond by simp\nqed\n\nlemma ordered_complement_mat: \"ordered_comp.N = mat \\<v> \\<b> (\\<lambda> (i,j) . if (\\<V>s ! i) \\<in> (\\<B>s ! j) then 0 else 1)\"\n  using complement_mat_entries_val by (intro eq_matI, simp_all)\n\nlemma ordered_complement_mat_map: \"ordered_comp.N = map_mat (\\<lambda>x. if x = 1 then 0 else 1) N\"\n  apply (intro eq_matI, simp_all)\n  using ordered_incidence_system.matrix_point_in_block_iff ordered_incidence_system_axioms \n    complement_mat_entries_val by (metis blocks_list_length) \n\n\nend\n\ntext \\<open>Establishing connection between incidence system and ordered incidence system locale \\<close>\n\nlemma (in incidence_system) alt_ordering_sysI: \"Vs \\<in> permutations_of_set \\<V> \\<Longrightarrow> Bs \\<in> permutations_of_multiset \\<B> \\<Longrightarrow> \n    ordered_incidence_system Vs Bs\"\n  by (unfold_locales) (simp_all add: permutations_of_multisetD permutations_of_setD wellformed)\n\nlemma (in finite_incidence_system) exists_ordering_sysI: \"\\<exists> Vs Bs . Vs \\<in> permutations_of_set \\<V> \\<and> \n  Bs \\<in> permutations_of_multiset \\<B> \\<and> ordered_incidence_system Vs Bs\"\nproof -\n  obtain Vs where \"Vs \\<in> permutations_of_set \\<V>\"\n    by (meson all_not_in_conv finite_sets permutations_of_set_empty_iff) \n  obtain Bs where \"Bs \\<in> permutations_of_multiset \\<B>\"\n    by (meson all_not_in_conv permutations_of_multiset_not_empty) \n  then show ?thesis using alt_ordering_sysI \\<open>Vs \\<in> permutations_of_set \\<V>\\<close> by blast \nqed\n\nlemma inc_sys_orderedI: \n  assumes \"incidence_system V B\" and \"distinct Vs\" and \"set Vs = V\" and \"mset Bs = B\" \n  shows \"ordered_incidence_system Vs Bs\"\nproof -\n  interpret inc: incidence_system V B using assms by simp\n  show ?thesis proof (unfold_locales)\n    show \"\\<And>b. b \\<in># mset Bs \\<Longrightarrow> b \\<subseteq> set Vs\" using inc.wellformed assms by simp\n    show \"distinct Vs\" using assms(2)permutations_of_setD(2) by auto \n  qed\nqed\n\ntext \\<open>Generalise the idea of an incidence matrix to an unordered context \\<close>\n\ndefinition is_incidence_matrix :: \"'c :: {ring_1} mat \\<Rightarrow> 'a set \\<Rightarrow> 'a set multiset \\<Rightarrow> bool\" where\n\"is_incidence_matrix N V B \\<longleftrightarrow> \n  (\\<exists> Vs Bs . (Vs \\<in> permutations_of_set V \\<and> Bs \\<in> permutations_of_multiset B \\<and> N = (inc_mat_of Vs Bs)))\"\n\nlemma (in incidence_system) is_incidence_mat_alt: \"is_incidence_matrix N \\<V> \\<B> \\<longleftrightarrow> \n  (\\<exists> Vs Bs. (set Vs = \\<V> \\<and> mset Bs = \\<B> \\<and> ordered_incidence_system Vs Bs \\<and> N = (inc_mat_of Vs Bs)))\"\nproof (intro iffI, simp add: is_incidence_matrix_def)\n  assume \"\\<exists>Vs. Vs \\<in> permutations_of_set \\<V> \\<and> (\\<exists>Bs. Bs \\<in> permutations_of_multiset \\<B> \\<and> N = inc_mat_of Vs Bs)\"\n  then obtain Vs Bs where \"Vs \\<in> permutations_of_set \\<V> \\<and> Bs \\<in> permutations_of_multiset \\<B> \\<and> N = inc_mat_of Vs Bs\"\n    by auto\n  then show \"\\<exists>Vs. set Vs = \\<V> \\<and> (\\<exists>Bs. mset Bs = \\<B> \\<and> ordered_incidence_system Vs Bs \\<and> N = inc_mat_of Vs Bs)\"\n    using incidence_system.alt_ordering_sysI incidence_system_axioms permutations_of_multisetD permutations_of_setD(1) \n    by blast \nnext\n  assume \"\\<exists>Vs Bs. set Vs = \\<V> \\<and> mset Bs = \\<B> \\<and> ordered_incidence_system Vs Bs \\<and> N = inc_mat_of Vs Bs\"\n  then obtain Vs Bs where s: \"set Vs = \\<V>\" and ms: \"mset Bs = \\<B>\" and \"ordered_incidence_system Vs Bs\" \n    and n: \"N = inc_mat_of Vs Bs\" by auto \n  then interpret ois: ordered_incidence_system Vs Bs by simp \n  have vs: \"Vs \\<in> permutations_of_set \\<V>\"\n    using ois.points_indexing s by blast \n  have \"Bs \\<in> permutations_of_multiset \\<B>\" using ois.blocks_indexing ms by blast\n  then show \"is_incidence_matrix N \\<V> \\<B> \" using n vs\n    using is_incidence_matrix_def by blast \nqed\n\nlemma (in ordered_incidence_system) is_incidence_mat_true: \"is_incidence_matrix N \\<V> \\<B> = True\"\n  using blocks_indexing is_incidence_matrix_def points_indexing by blast\n\nsubsection\\<open>Incidence Matrices on Design Subtypes \\<close>\n\nlocale ordered_design = ordered_incidence_system \\<V>s \\<B>s + design \"set \\<V>s\" \"mset \\<B>s\" \n  for \\<V>s and \\<B>s\nbegin\n\nlemma incidence_mat_non_empty_blocks: \n  assumes \"j < \\<b>\"\n  shows \"1 \\<in>$ (col N j)\" \nproof -\n  obtain bl where isbl: \"\\<B>s ! j = bl\" by simp\n  then have \"bl \\<in># \\<B>\"\n    using assms valid_blocks_index by auto \n  then obtain x where inbl: \"x \\<in> bl\"\n    using blocks_nempty by blast\n  then obtain i where isx: \"\\<V>s ! i = x\" and vali: \"i < \\<v>\"\n    using \\<open>bl \\<in># \\<B>\\<close> valid_points_index_cons wf_invalid_point by blast\n  then have \"N $$ (i, j) = 1\"\n    using \\<open>\\<B>s ! j = bl\\<close> \\<open>x \\<in> bl\\<close> assms matrix_point_in_block_one by blast\n  thus ?thesis using vec_setI\n    by (smt (verit, ccfv_SIG) N_col_def isx vali isbl inbl assms dim_vec_col_N of_nat_less_imp_less) \nqed\n\nlemma all_cols_non_empty: \"j < dim_col N \\<Longrightarrow> non_empty_col N j\"\n  using blocks_nempty non_empty_col_map_conv dim_col_is_b by simp \nend\n\nlocale ordered_simple_design = ordered_design \\<V>s \\<B>s + simple_design \"(set \\<V>s)\" \"mset \\<B>s\" for \\<V>s \\<B>s\nbegin\n\nlemma block_list_distinct: \"distinct \\<B>s\"\n  using block_mset_distinct by auto\n  \nlemma distinct_cols_N: \"distinct (cols N)\"\nproof -\n  have \"inj_on (\\<lambda> bl . inc_vec_of \\<V>s bl) (set \\<B>s)\" using inc_vec_eq_iff_blocks \n    by (simp add: inc_vec_eq_iff_blocks inj_on_def) \n  then show ?thesis using distinct_map inc_mat_of_cols_inc_vecs block_list_distinct\n    by (simp add: distinct_map inc_mat_of_cols_inc_vecs ) \nqed\n\nlemma simp_blocks_length_card: \"length \\<B>s = card (set \\<B>s)\"\n  using design_support_def simple_block_size_eq_card by fastforce\n\nlemma blocks_index_inj_on: \"inj_on (\\<lambda> i . \\<B>s ! i) {0..<length \\<B>s}\"\n  by (auto simp add: inj_on_def) (metis simp_blocks_length_card card_distinct nth_eq_iff_index_eq)\n\nlemma x_in_block_set_img: assumes \"x \\<in> set \\<B>s\" shows \"x \\<in> (!) \\<B>s ` {0..<length \\<B>s}\"\nproof -\n  obtain i where \"\\<B>s ! i = x\" and \"i < length \\<B>s\" using assms\n    by (meson in_set_conv_nth) \n  thus ?thesis by auto\nqed\n\nlemma blocks_index_simp_bij_betw: \"bij_betw (\\<lambda> i . \\<B>s ! i) {0..<length \\<B>s} (set \\<B>s)\"\n  using blocks_index_inj_on x_in_block_set_img by (auto simp add: bij_betw_def) \n\nlemma blocks_index_simp_unique:  \"i1 < length \\<B>s \\<Longrightarrow> i2 < length \\<B>s \\<Longrightarrow> i1 \\<noteq> i2 \\<Longrightarrow> \\<B>s ! i1 \\<noteq> \\<B>s ! i2\"\n  using block_list_distinct nth_eq_iff_index_eq by blast \n\nlemma lift_01_distinct_cols_N: \"distinct (cols (lift_01_mat N))\"\n  using  lift_01_mat_distinct_cols distinct_cols_N by simp\n\nend\n\nlocale ordered_proper_design = ordered_design \\<V>s \\<B>s + proper_design \"set \\<V>s\" \"mset \\<B>s\" \n  for \\<V>s and \\<B>s\nbegin\n\nlemma mat_is_proper: \"proper_inc_mat N\"\n  using design_blocks_nempty v_non_zero \n  by (auto simp add: proper_inc_mat_def)\n\nend\n\nlocale ordered_constant_rep = ordered_proper_design \\<V>s \\<B>s + constant_rep_design \"set \\<V>s\" \"mset \\<B>s\" \\<r> \n  for \\<V>s and \\<B>s and \\<r>\n\nbegin\n\nlemma incidence_mat_rep_num: \"i < \\<v> \\<Longrightarrow> mat_rep_num N i = \\<r>\"\n  using mat_rep_num_N_row rep_number valid_points_index by simp \n\nlemma incidence_mat_rep_num_sum: \"i < \\<v> \\<Longrightarrow> sum_vec (row N i) = \\<r>\"\n  using incidence_mat_rep_num  mat_rep_num_N_row\n  by (simp add: point_rep_mat_row_sum)  \n\nlemma transpose_N_mult_diag: \n  assumes \"i = j\" and \"i < \\<v>\" and \"j < \\<v>\" \n  shows \"(N * N\\<^sup>T) $$ (i, j) = \\<r>\"\nproof -\n  have unsq: \"\\<And> k . k < \\<b> \\<Longrightarrow> (N $$ (i, k))^2 = N $$ (i, k)\"\n    using assms(2) matrix_elems_one_zero by fastforce\n  then have \"(N * N\\<^sup>T) $$ (i, j) = (\\<Sum>k \\<in>{0..<\\<b>} . N $$ (i, k) * N $$ (j, k))\"\n    using assms(2) assms(3) transpose_mat_mult_entries[of \"i\" \"N\" \"j\"] by (simp) \n  also have \"... = (\\<Sum>k \\<in>{0..<\\<b>} . (N $$ (i, k))^2)\" using assms(1)\n    by (simp add: power2_eq_square)\n  also have \"... = (\\<Sum>k \\<in>{0..<\\<b>} . N $$ (i, k))\"\n    by (meson atLeastLessThan_iff sum.cong unsq) \n  also have \"... = (\\<Sum>k \\<in>{0..<\\<b>} . (row N i) $ k)\"\n    using assms(2) dim_col_is_b dim_row_is_v by auto \n  finally have \"(N * N\\<^sup>T) $$ (i, j) = sum_vec (row N i)\"\n    by (simp add: sum_vec_def)\n  thus ?thesis using incidence_mat_rep_num_sum\n    using assms(2) by presburger \nqed\n\nend\n\nlocale ordered_block_design = ordered_proper_design \\<V>s \\<B>s + block_design \"set \\<V>s\" \"mset \\<B>s\" \\<k>\n  for \\<V>s and \\<B>s and \\<k>\n\nbegin \n\n(* Every col has k ones *)\nlemma incidence_mat_block_size: \"j < \\<b> \\<Longrightarrow> mat_block_size N j = \\<k>\"\n  using mat_block_size_N_col uniform valid_blocks_index by fastforce\n\nlemma incidence_mat_block_size_sum: \"j < \\<b> \\<Longrightarrow> sum_vec (col N j) = \\<k>\"\n  using incidence_mat_block_size block_size_mat_rep_sum by presburger \n\nlemma ones_mult_incidence_mat_k_index: \"j < \\<b> \\<Longrightarrow> ((u\\<^sub>v \\<v>) \\<^sub>v* N) $ j = \\<k>\"\n  using ones_incidence_mat_block_size uniform incidence_mat_block_size by blast \n\nlemma ones_mult_incidence_mat_k: \"((u\\<^sub>v \\<v>) \\<^sub>v* N) = \\<k> \\<cdot>\\<^sub>v (u\\<^sub>v \\<b>)\"\n  using ones_mult_incidence_mat_k_index dim_col_is_b by (intro eq_vecI) (simp_all)\n\nend\n\nlocale ordered_incomplete_design = ordered_block_design \\<V>s \\<B>s \\<k> + incomplete_design \\<V> \\<B> \\<k>\n  for \\<V>s and \\<B>s and \\<k>\n\nbegin \n\nlemma incidence_mat_incomplete:  \"j < \\<b> \\<Longrightarrow> 0 \\<in>$ (col N j)\"\n  using valid_blocks_index incomplete_block_col incomplete_imp_incomp_block by blast \n\nend\n\nlocale ordered_t_wise_balance = ordered_proper_design \\<V>s \\<B>s + t_wise_balance \"set \\<V>s\" \"mset \\<B>s\" \\<t> \\<Lambda>\\<^sub>t\n  for \\<V>s and \\<B>s and \\<t> and \\<Lambda>\\<^sub>t\n\nbegin\n\nlemma incidence_mat_des_index: \n  assumes \"I \\<subseteq> {0..<\\<v>}\"\n  assumes \"card I = \\<t>\"\n  shows \"mat_point_index N I = \\<Lambda>\\<^sub>t\"\nproof -\n  have card: \"card ((!) \\<V>s ` I) = \\<t>\" using assms points_indexing_inj\n    by (metis (mono_tags, lifting) card_image ex_nat_less_eq not_le points_list_length subset_iff) \n  have \"((!) \\<V>s ` I) \\<subseteq> \\<V>\" using assms\n    by (metis atLeastLessThan_iff image_subset_iff subsetD valid_points_index)\n  then have \"\\<B> index ((!) \\<V>s ` I) = \\<Lambda>\\<^sub>t\" using balanced assms(2) card by simp\n  thus ?thesis using mat_point_index_rep assms(1) lessThan_atLeast0 by presburger \nqed\n\nend\n\nlocale ordered_pairwise_balance = ordered_t_wise_balance \\<V>s \\<B>s 2 \\<Lambda> + pairwise_balance \"set \\<V>s\" \"mset \\<B>s\" \\<Lambda>\n  for \\<V>s and \\<B>s and \\<Lambda>\nbegin\n\nlemma incidence_mat_des_two_index: \n  assumes \"i1 < \\<v>\"\n  assumes \"i2 < \\<v>\"\n  assumes \"i1 \\<noteq> i2\"\n  shows \"mat_point_index N {i1, i2} = \\<Lambda>\"\n  using incidence_mat_des_index incidence_mat_two_index \nproof -\n  have \"\\<V>s ! i1 \\<noteq> \\<V>s ! i2\" using assms(3)\n    by (simp add: assms(1) assms(2) distinct nth_eq_iff_index_eq points_list_length) \n  then have pair: \"card {\\<V>s ! i1, \\<V>s ! i2} = 2\" using card_2_iff by blast\n  have \"{\\<V>s ! i1, \\<V>s ! i2} \\<subseteq> \\<V>\" using assms\n    by (simp add: valid_points_index) \n  then have \"\\<B> index {\\<V>s ! i1, \\<V>s ! i2} = \\<Lambda>\" using pair\n    using balanced by blast \n  thus ?thesis using incidence_mat_two_index assms by simp\nqed\n\nlemma transpose_N_mult_off_diag: \n  assumes \"i \\<noteq> j\" and \"i < \\<v>\" and \"j < \\<v>\"\n  shows \"(N * N\\<^sup>T) $$ (i, j) = \\<Lambda>\"\nproof -\n  have rev: \"\\<And> k. k \\<in> {0..<\\<b>} \\<Longrightarrow> \\<not> (N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1) \\<longleftrightarrow> N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0\"\n    using assms matrix_elems_one_zero by auto\n  then have split: \"{0..<\\<b>} = {k \\<in> {0..<\\<b>}. N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1} \\<union> \n      {k \\<in> {0..<\\<b>}. N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0}\"\n    by blast\n  have zero: \"\\<And> k . k \\<in> {0..<\\<b>} \\<Longrightarrow> N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0 \\<Longrightarrow> N $$ (i, k) * N$$ (j, k) = 0\"\n    by simp \n  have djnt: \"{k \\<in> {0..<\\<b>}. N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1} \\<inter> \n    {k \\<in> {0..<\\<b>}. N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0} = {}\" using rev by auto\n  have fin1: \"finite {k \\<in> {0..<\\<b>}. N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1}\" by simp\n  have fin2: \"finite {k \\<in> {0..<\\<b>}. N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0}\" by simp\n  have \"(N * N\\<^sup>T) $$ (i, j) = (\\<Sum>k \\<in>{0..<\\<b>} . N $$ (i, k) * N $$ (j, k))\"\n    using assms(2) assms(3) transpose_mat_mult_entries[of \"i\" \"N\" \"j\"] by (simp)\n  also have \"... = (\\<Sum>k \\<in>({k' \\<in> {0..<\\<b>}. N $$ (i, k') = 1 \\<and> N $$ (j, k') = 1} \\<union> \n    {k' \\<in> {0..<\\<b>}. N $$ (i, k') = 0 \\<or> N $$ (j, k') = 0}) . N $$ (i, k) * N $$ (j, k))\"\n    using split by metis\n  also have \"... = (\\<Sum>k \\<in>{k' \\<in> {0..<\\<b>}. N $$ (i, k') = 1 \\<and> N $$ (j, k') = 1} . N $$ (i, k) * N $$ (j, k)) + \n    (\\<Sum>k \\<in>{k' \\<in> {0..<\\<b>}. N $$ (i, k') = 0 \\<or> N $$ (j, k') = 0} . N $$ (i, k) * N $$ (j, k))\"\n    using fin1 fin2 djnt sum.union_disjoint by blast \n  also have \"... = card {k' \\<in> {0..<\\<b>}. N $$ (i, k') = 1 \\<and> N $$ (j, k') = 1}\" \n    by (simp add: zero)\n  also have \"... = mat_point_index N {i, j}\" \n    using assms mat_point_index_two_alt[of i N j] by simp\n  finally show ?thesis using incidence_mat_des_two_index assms by simp\nqed\n\nend\n\ncontext pairwise_balance\nbegin\n\nlemma ordered_pbdI: \n  assumes \"\\<B> = mset \\<B>s\" and \"\\<V> = set \\<V>s\" and \"distinct \\<V>s\"\n  shows \"ordered_pairwise_balance \\<V>s \\<B>s \\<Lambda>\"\nproof -\n  interpret ois: ordered_incidence_system \\<V>s \\<B>s \n    using ordered_incidence_sysII assms finite_incidence_system_axioms by blast \n  show ?thesis using b_non_zero blocks_nempty assms t_lt_order balanced \n    by (unfold_locales)(simp_all)\nqed\nend\n\nlocale ordered_regular_pairwise_balance = ordered_pairwise_balance \"\\<V>s\" \"\\<B>s\" \\<Lambda> + \n  regular_pairwise_balance \"set \\<V>s\" \"mset \\<B>s\" \\<Lambda> \\<r> for \\<V>s and \\<B>s and \\<Lambda> and \\<r>\n\nsublocale ordered_regular_pairwise_balance \\<subseteq> ordered_constant_rep\n  by unfold_locales\n\ncontext ordered_regular_pairwise_balance\nbegin\n\ntext \\<open> Stinson's Theorem 1.15. Stinson \\cite{stinsonCombinatorialDesignsConstructions2004} \ngives an iff condition for incidence matrices of regular pairwise \nbalanced designs. The other direction is proven in the @{term \"zero_one_matrix\"} context \\<close>\nlemma rpbd_incidence_matrix_cond: \"N * (N\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m \\<v>) + (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m \\<v>)\"\nproof (intro eq_matI)\n  fix i j\n  assume ilt: \"i < dim_row (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\" \n    and jlt: \"j < dim_col (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\"\n  then have \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \n    (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v>) $$(i, j) + (int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j)\" \n    by simp\n  then have split: \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \n    (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v>) $$(i, j) + (\\<r> - \\<Lambda>) * ((1\\<^sub>m \\<v>) $$ (i, j))\"\n    using ilt jlt by simp\n  have lhs: \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v>) $$(i, j) = \\<Lambda>\" using ilt jlt by simp\n  show \"(N * N\\<^sup>T) $$ (i, j) = (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j)\"\n  proof (cases \"i = j\")\n    case True\n    then have rhs: \"(int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = (\\<r> - \\<Lambda>)\" using ilt by fastforce \n    have \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \\<Lambda> + (\\<r> - \\<Lambda>)\"\n      using True jlt by auto\n    then have \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \\<r>\" \n      using reg_index_lt_rep by (simp add: nat_diff_split)\n    then show ?thesis using lhs split rhs True transpose_N_mult_diag ilt jlt by simp\n  next\n    case False\n    then have \"(1\\<^sub>m \\<v>) $$ (i, j) = 0\" using ilt jlt by simp\n    then have \"(\\<r> - \\<Lambda>) * ((1\\<^sub>m \\<v>) $$ (i, j)) = 0\" using ilt jlt\n      by (simp add: \\<open>1\\<^sub>m \\<v> $$ (i, j) = 0\\<close>) \n    then show ?thesis using lhs transpose_N_mult_off_diag ilt jlt False by simp\n  qed\nnext\n  show \"dim_row (N * N\\<^sup>T) = dim_row (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\"\n    using transpose_N_mult_dim(1) by auto\nnext\n  show \"dim_col (N * N\\<^sup>T) = dim_col (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\"\n    using transpose_N_mult_dim(1) by auto\nqed\nend\n\nlocale ordered_bibd = ordered_proper_design \\<V>s \\<B>s + bibd \"set \\<V>s\" \"mset \\<B>s\" \\<k> \\<Lambda> \n  for \\<V>s and \\<B>s and \\<k> and \\<Lambda>\n\nsublocale ordered_bibd \\<subseteq> ordered_incomplete_design\n  by unfold_locales\n\nsublocale ordered_bibd \\<subseteq> ordered_constant_rep \\<V>s \\<B>s \\<r>\n  by unfold_locales\n\nsublocale ordered_bibd \\<subseteq> ordered_pairwise_balance\n  by unfold_locales\n\nlocale ordered_sym_bibd = ordered_bibd \\<V>s \\<B>s \\<k> \\<Lambda> + symmetric_bibd \"set \\<V>s\" \"mset \\<B>s\" \\<k> \\<Lambda> \n  for \\<V>s and \\<B>s and \\<k> and \\<Lambda>\n\n\nsublocale ordered_sym_bibd \\<subseteq> ordered_simple_design\n  by (unfold_locales)\n\nlocale ordered_const_intersect_design = ordered_proper_design \\<V>s \\<B>s + const_intersect_design \"set \\<V>s\" \"mset \\<B>s\" \\<m>\n  for \\<V>s \\<B>s \\<m>\n\n\nlocale simp_ordered_const_intersect_design = ordered_const_intersect_design + ordered_simple_design\nbegin \n\nlemma max_one_block_size_inter: \n  assumes \"\\<b> \\<ge> 2\"\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"card bl = \\<m>\"\n  assumes \"bl2 \\<in># \\<B> - {#bl#}\"\n  shows \"\\<m> < card bl2\"\nproof -\n  have sd: \"simple_design \\<V> \\<B>\"\n    by (simp add: simple_design_axioms) \n  have bl2in: \"bl2 \\<in># \\<B>\" using assms(4)\n    by (meson in_diffD)\n  have blin: \"bl \\<in># {#b \\<in># \\<B> . card b = \\<m>#}\" using assms(3) assms(2) by simp\n  then have slt: \"size {#b \\<in># \\<B> . card b = \\<m>#} = 1\" using simple_const_inter_iff sd assms(1)\n    by (metis count_empty count_eq_zero_iff less_one nat_less_le size_eq_0_iff_empty) \n  then have \"size {#b \\<in># (\\<B> - {#bl#}) . card b = \\<m>#} = 0\" using blin\n    by (smt (verit) add_mset_eq_singleton_iff count_eq_zero_iff count_filter_mset \n        filter_mset_add_mset insert_DiffM size_1_singleton_mset size_eq_0_iff_empty) \n  then have ne: \"card bl2 \\<noteq> \\<m>\" using assms(4)\n    by (metis (mono_tags, lifting) filter_mset_empty_conv size_eq_0_iff_empty) \n  thus ?thesis using inter_num_le_block_size assms bl2in nat_less_le by presburger \nqed\n\nlemma block_size_inter_num_cases:\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"\\<b> \\<ge> 2\"\n  shows \"\\<m> < card bl \\<or> (card bl = \\<m> \\<and> (\\<forall> bl' \\<in># (\\<B> - {#bl#}) . \\<m> < card bl'))\"\nproof (cases \"card bl = \\<m>\")\n  case True\n  have \"(\\<And> bl'. bl' \\<in># (\\<B> - {#bl#}) \\<Longrightarrow> \\<m> < card bl')\"\n    using max_one_block_size_inter True assms by simp\n  then show ?thesis using True by simp\nnext\n  case False\n  then have \"\\<m> < card bl\" using assms inter_num_le_block_size nat_less_le by presburger\n  then show ?thesis by simp\nqed\n\nlemma indexed_const_intersect: \n  assumes \"j1 < \\<b>\"\n  assumes \"j2 < \\<b>\"\n  assumes \"j1 \\<noteq> j2\"\n  shows \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = \\<m>\"\nproof -\n  obtain bl1 bl2 where \"bl1 \\<in># \\<B>\" and \"\\<B>s ! j1 = bl1\" and \"bl2 \\<in># \\<B> - {#bl1#}\" and \"\\<B>s ! j2 = bl2\" \n    using obtains_two_diff_block_indexes assms by fastforce \n  thus ?thesis by (simp add: const_intersect)\nqed\n\nlemma const_intersect_block_size_diff: \n  assumes \"j' < \\<b>\" and \"j < \\<b>\" and \"j \\<noteq> j'\" and \"card (\\<B>s ! j') = \\<m>\" and \"\\<b> \\<ge> 2\"\n  shows \"card (\\<B>s ! j) - \\<m> > 0\"\nproof -\n  obtain bl1 bl2 where \"bl1 \\<in># \\<B>\" and \"\\<B>s ! j' = bl1\" and \"bl2 \\<in># \\<B> - {#bl1#}\" and \"\\<B>s ! j = bl2\"\n    using assms(1) assms(2) assms(3) obtains_two_diff_block_indexes by fastforce \n  then have \"\\<m> < card (bl2)\" \n    using max_one_block_size_inter assms(4) assms(5) by blast  \n  thus ?thesis\n    by (simp add: \\<open>\\<B>s ! j = bl2\\<close>) \nqed\n\nlemma scalar_prod_inc_vec_const_inter: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\" \"j1 \\<noteq> j2\"\n  shows \"(col N j1) \\<bullet> (col N j2) = \\<m>\"\n  using scalar_prod_inc_vec_inter_num indexed_const_intersect assms by simp\n\nend\n\nsubsection \\<open> Zero One Matrix Incidence System Existence \\<close>\ntext \\<open>We prove 0-1 matrices with certain properties imply the existence of an incidence system\nwith particular properties. This leads to Stinson's theorem in the other direction \\cite{stinsonCombinatorialDesignsConstructions2004} \\<close>\n\ncontext zero_one_matrix\nbegin\n\nlemma mat_is_ordered_incidence_sys: \"ordered_incidence_system [0..<(dim_row M)] (map (map_col_to_block) (cols M))\"\n  apply (unfold_locales, simp_all)\n  using map_col_to_block_wf atLeastLessThan_upt by blast\n\ninterpretation mat_ord_inc_sys: ordered_incidence_system \"[0..<(dim_row M)]\" \"(map (map_col_to_block) (cols M))\"\n  by (simp add: mat_is_ordered_incidence_sys)\n\nlemma mat_ord_inc_sys_N: \"mat_ord_inc_sys.N = lift_01_mat M\" \n  by (intro eq_matI, simp_all add: inc_mat_of_def map_col_to_block_elem) \n    (metis lift_01_mat_simp(3) lift_mat_01_index_iff(2) of_zero_neq_one_def)\n\nlemma map_col_to_block_mat_rep_num:\n  assumes \"x <dim_row M\"\n  shows \"({# map_col_to_block c . c \\<in># mset (cols M)#} rep x) = mat_rep_num M x\"\nproof -\n  have \"mat_rep_num M x = mat_rep_num (lift_01_mat M) x\" \n    using preserve_mat_rep_num mat_ord_inc_sys_N\n    by (metis assms lift_01_mat_def of_inj_on_01_hom.inj_on_01_hom_axioms)\n  then have \"mat_rep_num M x = (mat_rep_num mat_ord_inc_sys.N x)\" using mat_ord_inc_sys_N by (simp) \n  then have \"mat_rep_num M x = mset (map (map_col_to_block) (cols M)) rep x\"\n    using assms atLeastLessThan_upt card_atLeastLessThan mat_ord_inc_sys.mat_rep_num_N_row \n      mat_ord_inc_sys_point minus_nat.diff_0 by presburger\n  thus ?thesis using ordered_to_mset_col_blocks\n    by presburger \nqed\n\nend \n\ncontext zero_one_matrix_ring_1\nbegin\n\nlemma transpose_cond_index_vals: \n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"i < dim_row (M * (M\\<^sup>T))\"\n  assumes \"j < dim_col (M * (M\\<^sup>T))\"\n  shows \"i = j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = r\" \"i \\<noteq> j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = \\<Lambda>\"\n  using assms by auto\n\nend\n\nlocale zero_one_matrix_int = zero_one_matrix_ring_1 M for M :: \"int mat\"\nbegin\n\ntext \\<open>Some useful conditions on the transpose product for matrix system properties \\<close>\nlemma transpose_cond_diag_r:\n  assumes \"i < dim_row (M * (M\\<^sup>T))\"\n  assumes \"\\<And> j. i = j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = r\"\n  shows \"mat_rep_num M i = r\"\nproof -\n  have eqr: \"(M * M\\<^sup>T) $$ (i, i) = r\" using assms(2)\n    by simp\n  have unsq: \"\\<And> k . k < dim_col M \\<Longrightarrow> (M $$ (i, k))^2 = M $$ (i, k)\"\n    using assms elems01 by fastforce\n  have \"sum_vec (row M i) = (\\<Sum>k \\<in>{0..<(dim_col M)} . (row M i) $ k)\"\n    using assms by (simp add: sum_vec_def)\n  also have \"... = (\\<Sum>k \\<in>{0..<(dim_col M)} . M $$ (i, k))\"\n    using assms by auto\n  also have \"... = (\\<Sum>k \\<in>{0..<(dim_col M)} . M $$ (i, k)^2)\"\n    using atLeastLessThan_iff sum.cong unsq by simp\n  also have \"... = (\\<Sum>k \\<in>{0..<(dim_col M)} . M $$ (i, k) * M $$ (i, k))\"\n    using assms by (simp add: power2_eq_square)\n  also have \"... = (M * M\\<^sup>T) $$ (i, i)\" \n    using assms transpose_mat_mult_entries[of \"i\" \"M\" \"i\"] by simp\n  finally have \"sum_vec (row M i) = r\" using eqr by simp\n  thus ?thesis using mat_rep_num_sum_alt\n    by (metis assms(1) elems01 index_mult_mat(2) of_nat_eq_iff) \nqed\n\n\nlemma transpose_cond_non_diag:\n  assumes \"i1 < dim_row (M * (M\\<^sup>T))\"\n  assumes \"i2 < dim_row (M * (M\\<^sup>T))\"\n  assumes \"i1 \\<noteq> i2\"\n  assumes \"\\<And> j i. j \\<noteq> i \\<Longrightarrow> i < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> j < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = \\<Lambda>\"\n  shows \"\\<Lambda> = mat_point_index M {i1, i2}\"\nproof -\n  have ilt: \"i1 < dim_row M\" \"i2 < dim_row M\"\n    using assms(1) assms (2) by auto\n  have rev: \"\\<And> k. k \\<in> {0..<dim_col M} \\<Longrightarrow> \n      \\<not> (M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1) \\<longleftrightarrow> M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0\"\n    using assms elems01 by fastforce \n  then have split: \"{0..<dim_col M} = {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1} \\<union> \n      {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0}\"\n    by blast\n  have zero: \"\\<And> k . k \\<in> {0..<dim_col M} \\<Longrightarrow> M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0 \\<Longrightarrow> M $$ (i1, k) * M$$ (i2, k) = 0\"\n    by simp \n  have djnt: \"{k \\<in> {0..<dim_col M}. M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1} \\<inter> \n      {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0} = {}\" \n    using rev by auto\n  have fin1: \"finite {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1}\" by simp\n  have fin2: \"finite {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0}\" by simp\n  have \"mat_point_index M {i1, i2} = card {k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 1 \\<and>M $$ (i2, k') = 1}\"\n    using mat_point_index_two_alt ilt assms(3) by auto\n  then have \"mat_point_index M {i1, i2} = \n    (\\<Sum>k \\<in>{k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 1 \\<and> M $$ (i2, k') = 1} . M $$ (i1, k) * M $$ (i2, k)) + \n    (\\<Sum>k \\<in>{k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 0 \\<or> M $$ (i2, k') = 0} . M $$ (i1, k) * M $$ (i2, k))\"\n    by (simp add: zero) (* Odd behaviour if I use also have here *)\n  also have \"... = (\\<Sum>k \\<in>({k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 1 \\<and> M $$ (i2, k') = 1} \\<union> \n    {k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 0 \\<or> M $$ (i2, k') = 0}) . M $$ (i1, k) * M $$ (i2, k))\"\n    using fin1 fin2 djnt sum.union_disjoint by (metis (no_types, lifting)) \n  also have \"... =  (\\<Sum>k \\<in>{0..<dim_col M} . M $$ (i1, k) * M $$ (i2, k))\"\n    using split by metis\n  finally have \"mat_point_index M {i1, i2} = (M * (M\\<^sup>T)) $$ (i1, i2)\"\n    using assms(1) assms(2) transpose_mat_mult_entries[of \"i1\" \"M\" \"i2\"] by simp\n  thus ?thesis using assms by presburger \nqed\n\nlemma trans_cond_implies_map_rep_num:\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"x < dim_row M\"\n  shows \"(image_mset map_col_to_block (mset (cols M))) rep x = r\"\nproof -\n  interpret ois: ordered_incidence_system \"[0..<dim_row M]\" \"map map_col_to_block (cols M)\"\n    using mat_is_ordered_incidence_sys by simp\n  have eq: \"ois.\\<B> rep x = sum_vec (row M x)\" using ois.point_rep_mat_row_sum\n    by (simp add: assms(2) inc_mat_of_map_rev) \n  then have \"\\<And> j. x = j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (x, j) = r\" using assms(1) transpose_cond_index_vals\n    by (metis assms(2) index_mult_mat(2) index_mult_mat(3) index_transpose_mat(3)) \n  thus ?thesis using eq transpose_cond_diag_r assms(2) index_mult_mat(2)\n    by (metis map_col_to_block_mat_rep_num) \nqed\n\nlemma trans_cond_implies_map_index:\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"ps \\<subseteq> {0..<dim_row M}\"\n  assumes \"card ps = 2\"\n  shows \"(image_mset map_col_to_block (mset (cols M))) index ps = \\<Lambda>\"\nproof - \n  interpret ois: ordered_incidence_system \"[0..<dim_row M]\" \"map map_col_to_block (cols M)\"\n    using mat_is_ordered_incidence_sys by simp\n  obtain i1 i2 where i1in: \"i1 <dim_row M\" and i2in: \"i2 <dim_row M\" and psis: \"ps = {i1, i2}\" and neqi: \"i1 \\<noteq> i2\"\n    using assms(2) assms(3) card_2_iff insert_subset by (metis atLeastLessThan_iff) \n  have cond: \"\\<And> j i. j \\<noteq> i \\<Longrightarrow> i < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> j < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = \\<Lambda>\"\n    using assms(1) by simp\n  then have \"(image_mset map_col_to_block (mset (cols M))) index ps = mat_point_index M ps\"\n     using ois.incidence_mat_two_index psis i1in i2in by (simp add: neqi inc_mat_of_map_rev)\n  thus ?thesis using cond transpose_cond_non_diag[of i1 i2 \\<Lambda>] i1in i2in index_mult_mat(2)[of \"M\" \"M\\<^sup>T\"] \n       neqi of_nat_eq_iff psis by simp\nqed\n\ntext \\<open> Stinson Theorem 1.15 existence direction \\<close>\nlemma rpbd_exists: \n  assumes \"dim_row M \\<ge> 2\" \\<comment> \\<open>Min two points\\<close>\n  assumes \"dim_col M \\<ge> 1\" \\<comment> \\<open>Min one block\\<close>\n  assumes \"\\<And> j. j < dim_col M \\<Longrightarrow> 1 \\<in>$ col M j\" \\<comment> \\<open>no empty blocks \\<close>\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  shows \"ordered_regular_pairwise_balance [0..<dim_row M] (map map_col_to_block (cols M)) \\<Lambda> r\"\nproof -\n  interpret ois: ordered_incidence_system \"[0..<dim_row M]\" \"(map map_col_to_block (cols M))\"\n    using mat_is_ordered_incidence_sys by simp\n  interpret pdes: ordered_design \"[0..<dim_row M]\" \"(map map_col_to_block (cols M))\"\n    using assms(2) mat_is_design assms(3)\n    by (simp add: ordered_design_def ois.ordered_incidence_system_axioms)  \n  show ?thesis using assms trans_cond_implies_map_index trans_cond_implies_map_rep_num \n    by (unfold_locales) (simp_all)\nqed\n\nlemma vec_k_uniform_mat_block_size: \n  assumes \"((u\\<^sub>v (dim_row M)) \\<^sub>v* M) = k \\<cdot>\\<^sub>v (u\\<^sub>v (dim_col M))\"\n  assumes \"j < dim_col M\"\n  shows \"mat_block_size M j = k\"\nproof -\n  have \"mat_block_size M j = sum_vec (col M j)\" using assms(2)\n    by (simp add: elems01 mat_block_size_sum_alt) \n  also have \"... = ((u\\<^sub>v (dim_row M)) \\<^sub>v* M) $ j\" using assms(2) \n    by (simp add: sum_vec_def scalar_prod_def)\n  finally show ?thesis using  assms(1) assms(2) by (simp)\nqed\n\nlemma vec_k_impl_uniform_block_size: \n  assumes \"((u\\<^sub>v (dim_row M)) \\<^sub>v* M) = k \\<cdot>\\<^sub>v (u\\<^sub>v (dim_col M))\"\n  assumes \"bl \\<in># (image_mset map_col_to_block (mset (cols M)))\"\n  shows \"card bl = k\"\nproof -\n  obtain j where jlt: \"j < dim_col M\" and bleq: \"bl = map_col_to_block (col M j)\"\n    using assms(2) obtain_block_index_map_block_set by blast \n  then have \"card (map_col_to_block (col M j)) = mat_block_size M j\"\n    by (simp add: map_col_to_block_size) \n  thus ?thesis using vec_k_uniform_mat_block_size assms(1) bleq jlt by blast \nqed\n\nlemma bibd_exists: \n  assumes \"dim_col M \\<ge> 1\" \\<comment> \\<open>Min one block\\<close>\n  assumes \"\\<And> j. j < dim_col M \\<Longrightarrow> 1 \\<in>$ col M j\" \\<comment> \\<open>no empty blocks \\<close>\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"((u\\<^sub>v (dim_row M)) \\<^sub>v* M) = k \\<cdot>\\<^sub>v (u\\<^sub>v (dim_col M))\"\n  assumes \"(r ::nat) \\<ge> 0\"\n  assumes \"k \\<ge> 2\" \"k < dim_row M\"\n  shows \"ordered_bibd [0..<dim_row M] (map map_col_to_block (cols M)) k \\<Lambda>\"\nproof -\n  interpret ipbd: ordered_regular_pairwise_balance \"[0..<dim_row M]\" \"(map map_col_to_block (cols M))\" \\<Lambda> r\n    using rpbd_exists assms by simp\n  show ?thesis using vec_k_impl_uniform_block_size by (unfold_locales, simp_all add: assms)\nqed\n\nend\n\nsubsection \\<open>Isomorphisms and Incidence Matrices \\<close>\ntext \\<open>If two incidence systems have the same incidence matrix, they are isomorphic. Similarly\nif two incidence systems are isomorphic there exists an ordering such that they have the same\nincidence matrix \\<close>\nlocale two_ordered_sys = D1: ordered_incidence_system \\<V>s \\<B>s + D2: ordered_incidence_system \\<V>s' \\<B>s'\n  for \"\\<V>s\" and \"\\<B>s\" and \"\\<V>s'\" and \"\\<B>s'\" \n\nbegin\n\nlemma equal_inc_mat_isomorphism: \n  assumes \"D1.N = D2.N\"\n  shows \"incidence_system_isomorphism D1.\\<V> D1.\\<B> D2.\\<V> D2.\\<B> (\\<lambda> x . \\<V>s' ! (List_Index.index \\<V>s x))\"\nproof (unfold_locales)\n  show \"bij_betw (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x) D1.\\<V> D2.\\<V>\" \n  proof -\n    have comp: \"(\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x) = (\\<lambda> i. \\<V>s' ! i) \\<circ> (\\<lambda> y . List_Index.index \\<V>s y)\"\n      by (simp add: comp_def)\n    have leq: \"length \\<V>s = length \\<V>s'\" \n      using assms D1.dim_row_is_v D1.points_list_length D2.dim_row_is_v D2.points_list_length by force \n    have bij1: \"bij_betw (\\<lambda> i. \\<V>s' !i) {..<length \\<V>s} (set \\<V>s') \" using leq\n      by (simp add: bij_betw_nth D2.distinct) \n    have \"bij_betw (List_Index.index \\<V>s) (set \\<V>s) {..<length \\<V>s}\" using D1.distinct\n      by (simp add: bij_betw_index lessThan_atLeast0) \n    thus ?thesis using bij_betw_trans comp bij1 by simp\n  qed\nnext\n  have len:  \"length (map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) = length \\<B>s'\"\n    using length_map assms D1.dim_col_is_b by force \n  have mat_eq: \"\\<And> i j . D1.N $$ (i, j) = D2.N $$ (i, j)\" using assms\n    by simp \n  have vslen: \"length \\<V>s = length \\<V>s'\" using assms\n      using D1.dim_row_is_v D1.points_list_length D2.dim_row_is_v D2.points_list_length by force \n  have \"\\<And> j. j < length \\<B>s' \\<Longrightarrow> (map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = \\<B>s' ! j\"\n  proof -\n    fix j assume a: \"j < length \\<B>s'\" \n    then have \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x) ` (\\<B>s ! j)\"\n      by (metis D1.blocks_list_length D1.dim_col_is_b D2.blocks_list_length D2.dim_col_is_b assms nth_map) \n    also have \"... = (\\<lambda> i . \\<V>s' ! i) ` ((\\<lambda> x. List_Index.index \\<V>s x) ` (\\<B>s ! j))\" \n      by blast\n    also have \"... = ((\\<lambda> i . \\<V>s' ! i) ` {i . i < length \\<V>s \\<and> D1.N $$ (i, j) = 1})\" \n      using D1.block_mat_cond_rev a assms\n      by (metis (no_types, lifting) D1.blocks_list_length D1.dim_col_is_b D2.blocks_list_length D2.dim_col_is_b) \n    also have \"... = ((\\<lambda> i . \\<V>s' ! i) ` {i . i < length \\<V>s' \\<and> D2.N $$ (i, j) = 1})\" \n      using vslen mat_eq by simp\n    finally have \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = (\\<B>s' ! j)\" \n      using D2.block_mat_cond_rep' a by presburger\n    then show \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = (\\<B>s' ! j)\" by simp\n  qed\n  then have \"map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s = \\<B>s'\" \n    using len nth_equalityI[of \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s)\" \"\\<B>s'\"] by simp\n  then show \"image_mset ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) D1.\\<B> = D2.\\<B>\"\n    using mset_map by auto\nqed\n\nlemma equal_inc_mat_isomorphism_ex: \"D1.N = D2.N \\<Longrightarrow> \\<exists> \\<pi> . incidence_system_isomorphism D1.\\<V> D1.\\<B> D2.\\<V> D2.\\<B> \\<pi>\"\n  using equal_inc_mat_isomorphism by auto \n\nlemma equal_inc_mat_isomorphism_obtain: \n  assumes \"D1.N = D2.N\"\n  obtains \\<pi> where \"incidence_system_isomorphism D1.\\<V> D1.\\<B> D2.\\<V> D2.\\<B> \\<pi>\"\n  using equal_inc_mat_isomorphism assms by auto \n\nend\n\ncontext incidence_system_isomorphism\nbegin\n\nlemma exists_eq_inc_mats:\n  assumes \"finite \\<V>\" \"finite \\<V>'\"\n  obtains N where \"is_incidence_matrix N \\<V> \\<B>\" and \"is_incidence_matrix N \\<V>' \\<B>'\"\nproof -\n  obtain Vs where vsis: \"Vs \\<in> permutations_of_set \\<V>\" using assms\n    by (meson all_not_in_conv permutations_of_set_empty_iff) \n  obtain Bs where bsis: \"Bs \\<in> permutations_of_multiset \\<B>\"\n    by (meson all_not_in_conv permutations_of_multiset_not_empty) \n  have inj: \"inj_on \\<pi> \\<V>\" using bij\n    by (simp add: bij_betw_imp_inj_on) \n  then have mapvs: \"map \\<pi> Vs \\<in> permutations_of_set \\<V>'\" using permutations_of_set_image_inj\n    using \\<open>Vs \\<in> permutations_of_set \\<V>\\<close> iso_points_map by blast \n  have \"permutations_of_multiset (image_mset ((`)\\<pi>) \\<B>) = map ((`) \\<pi>) ` permutations_of_multiset \\<B>\"\n    using block_img permutations_of_multiset_image by blast \n  then have mapbs: \"map ((`) \\<pi>) Bs \\<in> permutations_of_multiset \\<B>'\" using bsis block_img by blast \n  define N :: \"'c :: {ring_1} mat\" where \"N \\<equiv> inc_mat_of Vs Bs\" \n  have \"is_incidence_matrix N \\<V> \\<B>\"\n    using N_def bsis is_incidence_matrix_def vsis by blast\n  have \"\\<And> bl . bl \\<in> (set Bs) \\<Longrightarrow> bl \\<subseteq> (set Vs)\"\n    by (meson bsis in_multiset_in_set ordered_incidence_system.wf_list source.alt_ordering_sysI vsis) \n  then have \"N = inc_mat_of (map \\<pi> Vs) (map ((`) \\<pi>) Bs)\" \n    using inc_mat_of_bij_betw inj\n    by (metis N_def permutations_of_setD(1) vsis) \n  then have \"is_incidence_matrix N \\<V>' \\<B>'\"\n    using mapbs mapvs is_incidence_matrix_def by blast \n  thus ?thesis\n    using \\<open>is_incidence_matrix N \\<V> \\<B>\\<close> that by auto \nqed\n\nend\n\nend", "meta": {"author": "cledmonds", "repo": "incidence_systems_linear_algebra", "sha": "043b84a38c6f8370afce52f98b8e0d8520c44a4f", "save_path": "github-repos/isabelle/cledmonds-incidence_systems_linear_algebra", "path": "github-repos/isabelle/cledmonds-incidence_systems_linear_algebra/incidence_systems_linear_algebra-043b84a38c6f8370afce52f98b8e0d8520c44a4f/src/Incidence_Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8902942203004186, "lm_q1q2_score": 0.7735114633748256}}
{"text": "theory Oalist imports Main\nbegin\n\n(* Implementation of association lists with ordered keys\n * This is based somewhat on the implementation of association lists from\n * HOL/Library/AList.thy and HOL/Library/DAlist.thy, with the twist that\n * keys are required to be in strictly increasing order.\n * This gives us the property that all sets of (key, value) pairs have a canonical representation,\n * which is necessary to satisfy the ordering laws used by Gazelle\n * (see Mergeable/Pord.thy, Mergeable/Mergeable.thy)\n *\n * TODO: Implementations given here are not necessarily as efficient as they could be\n *)\n\ndefinition strict_order ::\n  \"('a :: linorder) list \\<Rightarrow> bool\" where\n\"strict_order l =\n  (\\<forall> i j . j < length l \\<longrightarrow> i < j \\<longrightarrow>\n     (l ! i) < (l ! j))\"\n\nlemma strict_order_unfold :\n  fixes l :: \"('a :: linorder) list\"\n  fixes i j :: nat\n  assumes H  : \"strict_order l\"\n  assumes Hln : \"j < length l\"\n  assumes Hij : \"i < j\"\n  shows \"l ! i < l ! j\" using H Hln Hij\n  by(auto simp add:strict_order_def)\n\nlemma strict_order_intro :\n  fixes l :: \"('a :: linorder) list\"\n  assumes H : \"\\<And> i j . j < length l \\<Longrightarrow> i < j \\<Longrightarrow> (l ! i) < (l ! j)\"\n  shows \"strict_order l\" using H\n  by(auto simp add:strict_order_def)\n\n(* inspired by HOL-Library.DAList *)\n\nlemma strict_order_tl :\n  fixes l :: \"('a :: linorder) list\"\n  fixes x :: \"'a\"\n  assumes H : \"strict_order (x#l)\"\n  shows \"strict_order l\"\nproof(rule strict_order_intro)\n  fix i j :: nat\n  assume Hlen : \"j < length l\"\n  assume Hij : \"i < j\"\n  show \"l ! i < l ! j\"\n    using strict_order_unfold[OF H, of \"1 + j\" \"1 + i\"] Hlen Hij\n    by(auto)\nqed\n\nlemma strict_order_distinct :\n  fixes l :: \"('a :: linorder) list\"\n  assumes Hs : \"strict_order l\"\n  shows \"distinct l\" using Hs\nproof(induction l)\n  case Nil\n  then show ?case by(auto simp add:strict_order_def)\nnext\n  case (Cons a l)\n  then show ?case\n  proof(cases \"a \\<in> set l\")\n    assume Hin1 : \"(strict_order l \\<Longrightarrow> distinct l)\"\n    assume Hin2 : \"strict_order (a#l)\"\n    assume Hin3 : \"a \\<in> set l\"\n    then obtain i where Hi: \"l ! i = a\" and Hil : \"1 + i < length (a#l)\" by(auto simp add:in_set_conv_nth)\n    hence Hfound : \"(a # l)!(1 + i) = a\" by(auto)\n    have \"(a#l)! 0 < (a#l) ! (1 + i)\"\n      using strict_order_unfold[OF Hin2 Hil, of 0] by auto\n    hence \"a < a\" using Hfound by auto\n    hence False using less_le by auto\n    then show ?thesis by auto\n  next\n    assume Hin1 : \"(strict_order l \\<Longrightarrow> distinct l)\"\n    assume Hin2 : \"strict_order (a#l)\"\n    assume Hin3 : \"a \\<notin> set l\"\n    then show ?thesis using Hin1 strict_order_tl[OF Hin2] Hin3\n      by auto\n  qed\nqed\n\nlemma strict_order_cons :\n  fixes h1 h2 :: \"('a :: linorder)\"\n  fixes l :: \"'a list\"\n  assumes Hleq : \"h1 < h2\"\n  assumes Hs : \"strict_order (h2 # l)\"\n  shows \"strict_order (h1 # h2 # l)\"\nproof(rule strict_order_intro)\n  fix i j :: nat\n  assume Hj : \"j < length (h1 # h2 # l)\"\n  assume Hij : \"i < j\"\n  \n  show \"(h1 # h2 # l) ! i < (h1 # h2 # l) ! j\"\n  proof(cases i)\n    case 0\n    have H0' : \"1 \\<le> j\" using Hij by(cases j; auto)\n    then show ?thesis (*using strict_order_unfold[OF Hs] 0 *)\n    proof(cases \"j = 1\")\n      case True\n      then show ?thesis using Hleq 0 by auto\n    next\n      case False\n      hence Hfalse' : \"2 \\<le> j\" using H0' by auto\n      then obtain j' where \"j = Suc j'\" by(cases j; auto)\n      then show ?thesis using 0 Hfalse' Hj Hleq strict_order_unfold[OF Hs, of j', of 0]\n        by(auto)\n    qed\n  next\n    case (Suc i')\n    hence Hsuc' : \"2 \\<le> j\" using Hij by auto\n    then obtain j' where \"j = Suc j'\" by(cases j; auto)\n    then show ?thesis using Suc Hsuc' Hj Hij Hleq strict_order_unfold[OF Hs, of j', of i']\n      by(auto)\n  qed\nqed\n\ntypedef (overloaded) ('key, 'value) oalist =\n  \"{xs :: (('key :: linorder) * 'value) list .\n       strict_order (map fst xs)}\"\n  morphisms impl_of Oalist\nproof\n  show \"[] \\<in> {xs :: ('key * 'value) list . strict_order (map fst xs)}\"\n    by(auto simp add:strict_order_def)\nqed\n\nsetup_lifting type_definition_oalist\n\ntype_synonym ('key) kmap =\n  \"('key, unit) oalist\"\n\nlemma alist_ext: \"impl_of xs = impl_of ys \\<Longrightarrow> xs = ys\"\n  by (simp add: impl_of_inject)\n\nlemma alist_eq_iff: \"xs = ys \\<longleftrightarrow> impl_of xs = impl_of ys\"\n  by (simp add: impl_of_inject)\n\nlemma impl_of_distinct [simp, intro]: \"distinct (map fst (impl_of xs))\"\n  using impl_of[of xs] strict_order_distinct[of \"map fst (impl_of xs)\"] by simp\n\nlemma Alist_impl_of [code abstype]: \"Oalist (impl_of xs) = xs\"\n  by (rule impl_of_inverse)\n\n(* primitives *)\n\nfun str_ord_update :: \"('key :: linorder) \\<Rightarrow> 'value \\<Rightarrow> ('key * 'value) list \\<Rightarrow> ('key * 'value) list\" where\n\"str_ord_update k v [] = [(k, v)]\"\n| \"str_ord_update k v ((k', v')#t) =\n    (if k < k'\n     then (k, v) # (k', v') # t\n     else (if k = k'\n           then (k, v) # t\n           else (k', v') # (str_ord_update k v t)))\"\n\nlemma str_ord_update_head :\n  fixes l :: \"(('key :: linorder) * 'value) list\"\n  shows \"(hd (str_ord_update k v ((hk, hv)#l)) = (k, v) \\<and> k \\<le> hk) \\<or>\n         (hd (str_ord_update k v ((hk, hv)#l)) = (hk, hv) \\<and> hk \\<le> k)\"\nproof(-)\n  consider (1) \"k < hk\" |\n           (2) \"k = hk\" |\n           (3) \"hk < k\"\n    using less_linear[of k hk] by auto\n  then show \"(hd (str_ord_update k v ((hk, hv) # l)) = (k, v) \\<and> (k \\<le> hk)) \\<or> (hd (str_ord_update k v ((hk, hv) # l)) = (hk, hv) \\<and> hk \\<le> k)\"\n  proof cases\n    case 1\n    then show ?thesis by auto\n  next\n    case 2 thus ?thesis by auto\n  next\n    case 3 thus ?thesis by auto\n  qed\nqed\n\n\nlemma str_ord_update_correct :\n  fixes l :: \"(('key :: linorder) * 'value) list\"\n  fixes k :: 'key\n  fixes v :: 'value\n  assumes H : \"strict_order (map fst l)\"\n  shows \"strict_order (map fst (str_ord_update k v l))\" using H\nproof(induction l arbitrary: k v)\n  case Nil\n  then show ?case by(auto simp add:strict_order_def)\nnext\n  fix a :: \"'key * 'value\"\n  fix l' :: \"('key * 'value) list\"\n  fix k :: 'key\n  fix v :: 'value\n  obtain ak and av where Ha: \"a = (ak, av)\" by(cases a; auto)\n  assume Hin1 : \"\\<And> k v .(strict_order (map fst l') \\<Longrightarrow>\n                  strict_order (map fst (str_ord_update k v l')))\"\n  assume Hin2: \"strict_order (map fst (a # l'))\"\n  hence Hin2' : \"strict_order (ak # map fst l')\" using Ha by auto\n  have Hord_l' : \"strict_order (map fst l')\" using strict_order_tl[OF Hin2'] by auto\n  have Hin1': \"strict_order (map fst (str_ord_update k v l'))\" using Hin1[OF Hord_l'] by auto\n\n  consider (1) \"k < ak\" |\n           (2) \"k = ak\" |\n           (3) \"ak < k\"\n    using Ha less_linear[of k ak] by auto\n\n  then show \"strict_order (map fst (str_ord_update k v (a # l')))\"\n  proof cases\n    case 1\n    then show ?thesis using Ha Hin2' strict_order_cons[OF 1, of \"map fst l'\"]\n      by(auto)\n  next\n    case 2\n    then show ?thesis using Ha Hin2'\n      by(auto)\n  next\n    case 3\n    then show ?thesis\n    proof(cases \"(str_ord_update k v l')\")\n      case Nil\n      show ?thesis\n      proof(rule strict_order_intro)\n        fix i j :: nat\n        show \"j < length (map fst (str_ord_update k v (a # l'))) \\<Longrightarrow> i < j \\<Longrightarrow>\n                          map fst (str_ord_update k v (a # l')) ! i < \n                          map fst (str_ord_update k v (a # l')) ! j\"\n          using 3 Ha Nil by(cases i; auto)\n      qed\n    next\n      fix a' :: \"'key * 'value\"\n      fix l'' :: \"('key * 'value) list\"\n      obtain a'k and a'v where Ha' : \"a' = (a'k, a'v)\" by(cases a'; auto) \n      assume Hcons : \"(str_ord_update k v l') = a'#l''\"\n      show ?thesis\n      proof(cases l')\n        case Nil\n        show ?thesis\n        proof(rule strict_order_intro)\n          fix i j :: nat\n          show \" j < length (map fst (str_ord_update k v (a # l'))) \\<Longrightarrow> i < j \\<Longrightarrow>\n                  map fst (str_ord_update k v (a # l')) ! i <\n                  map fst (str_ord_update k v (a # l')) ! j\"\n            using 3 Ha Nil by(cases i; auto)\n        qed\n      next\n        fix x :: \"'key * 'value\"\n        fix m :: \"('key * 'value) list\"\n        obtain xk and xv where Hx : \"x = (xk, xv)\" by (cases x; auto)\n        assume Hcons2 : \"l' = x#m\"\n        consider (C3_1) \"(hd (str_ord_update k v l') = (xk, xv))\" and \"xk \\<le> k\" |\n                 (C3_2) \"(hd (str_ord_update k v l')) = (k, v)\" and \"k \\<le> xk\"\n          using Hcons Ha' Hcons2 Hx str_ord_update_head[of k v xk xv m]\n          by( auto simp del:str_ord_update.simps)\n        then show ?thesis\n        proof cases\n          case C3_1\n          have \"ak < xk\" using Ha Ha' Hx Hcons2 strict_order_unfold[OF Hin2', of 1 0] by auto\n          then show ?thesis using C3_1 3 Ha Ha' Hx Hcons Hcons2 Hin1' apply(auto)\n            apply(rule_tac strict_order_cons) apply(auto)\n            done\n        next\n          case C3_2\n          then show ?thesis using 3 Ha Ha' Hx Hcons Hcons2 Hin1' apply(auto)\n            apply(rule_tac strict_order_cons) apply(auto)\n            done\n        qed\n      qed\n    qed\n  qed\nqed\n     \n\nlift_definition empty :: \"('key :: linorder, 'value) oalist\" is \"[]\"\n  by(simp add:strict_order_def)\n\nlift_definition update :: \"('key :: linorder) \\<Rightarrow> 'value \\<Rightarrow> ('key, 'value) oalist \\<Rightarrow> ('key, 'value) oalist\"\n  is str_ord_update\nproof(-)\n  fix k :: \"'key :: linorder\"\n  fix v :: \"'value\"\n  fix l :: \"('key * 'value) list\"\n  assume H : \"strict_order (map fst l)\"\n  show \"strict_order (map fst (str_ord_update k v l))\" using str_ord_update_correct[OF H] by auto\nqed\n\n\nfun str_ord_delete :: \"('key :: linorder) \\<Rightarrow> ('key * 'value) list \\<Rightarrow> ('key * 'value) list\" where\n\"str_ord_delete k [] = []\"\n| \"str_ord_delete k ((k', v')#t) =\n    (if k < k'\n     then (k', v')#t\n     else (if k = k'\n           then t\n           else (k', v') # (str_ord_delete k t)))\"\n\n\nlemma str_ord_delete_head :\n  fixes l :: \"(('key :: linorder) * 'value) list\"\n  assumes H : \"strict_order (hk # map fst l)\"\n  shows \"(hd (str_ord_delete k ((hk, hv)#l)) = (hk, hv) \\<and> hk \\<noteq> k) \\<or>\n         (\\<exists> k' v' . hd (str_ord_delete k ((hk, hv)#l)) = (k', v') \\<and> k = hk \\<and> hk < k') \\<or>\n         (l = [])\"\nproof(cases l)\n  case Nil\n  then show ?thesis by auto\nnext\n  fix a l'\n  assume Hcons : \"l = a # l'\"\n  obtain ak and av where Ha: \"a = (ak, av)\" by(cases a; auto)\n  consider (1) \"k < hk\" |\n           (2) \"k = hk\" |\n           (3) \"hk < k\"\n    using less_linear[of k hk] by auto\n  then show \"hd (str_ord_delete k ((hk, hv) # l)) = (hk, hv) \\<and> hk \\<noteq> k \\<or>\n    (\\<exists>k' v'. hd (str_ord_delete k ((hk, hv) # l)) = (k', v') \\<and> k = hk \\<and> hk < k') \\<or> l = []\"\n  proof cases\n    case 1\n    then show ?thesis by auto\n  next\n    case 2 thus ?thesis using H Hcons Ha strict_order_unfold[OF H, of 1 0] by(auto)\n  next\n    case 3 thus ?thesis by auto\n  qed\nqed\n\nlemma strict_order_2nd :\n  assumes H : \"strict_order (h1 # h2 # t)\"\n  shows \"strict_order (h1 # t)\"\nproof(rule strict_order_intro)\n  fix i j :: nat\n  assume Hlen : \"j < length (h1 # t)\"\n  assume Hlt : \"i < j\"\n  show \"(h1 # t) ! i < (h1 # t) ! j\"\n  proof(cases i)\n    case 0\n    obtain j' where \"j = 1 + j'\" using Hlt by (cases j; auto)\n    then show ?thesis using 0 Hlen strict_order_unfold[OF H, of \"1 + j\" \"0\"] by(auto)\n  next\n    case (Suc nat)\n    obtain j' where \"j = 1 + j'\" using Hlt by (cases j; auto)\n    then show ?thesis using Suc Hlen Hlt strict_order_unfold[OF H, of \"1 + j\" \"1 + i\"] by(auto)  \n  qed\nqed\n\n(* need a similar cons lemma for this one. *)\nlemma str_ord_delete_correct :\n  fixes k :: \"'key :: linorder\"\n  fixes l :: \"('key * 'value) list\"\n  assumes H : \"strict_order (map fst l)\"\n  shows \"strict_order (map fst (str_ord_delete k l))\" using H\nproof(induction l)\n  case Nil\n  then show ?case by(auto simp add:strict_order_def)\nnext\n  fix a :: \"('key * 'value)\"\n  fix l' :: \"('key * 'value) list\"\n  assume Hi1 : \"(strict_order (map fst l') \\<Longrightarrow> strict_order (map fst (str_ord_delete k l')))\"\n  assume Hi2 : \"strict_order (map fst (a # l'))\"\n  obtain ak and av where Ha: \"a = (ak, av)\" by(cases a; auto)\n  \n  have Hi1' : \"strict_order (map fst (str_ord_delete k l'))\" using Ha Hi1 Hi2 strict_order_tl[of ak \"map fst l'\"]\n    by(auto)\n\n  consider (1) \"k < ak\" |\n           (2) \"k = ak\" |\n           (3) \"ak < k\"\n    using less_linear[of k ak] by auto\n  then show \"strict_order (map fst (str_ord_delete k (a # l')))\"\n  proof cases\n    case 1\n    then show ?thesis using Ha Hi2 by(auto)\n  next\n    case 2\n    have Hi2' : \"strict_order (map fst l')\" using Ha Hi2 strict_order_tl[of ak \"map fst l'\"] by auto\n    then show ?thesis using 2 Ha by(auto)\n  next\n    case 3\n    have Hi2' : \"strict_order (map fst l')\" using Ha Hi2 strict_order_tl[of ak \"map fst l'\"] by auto\n    show ?thesis using 3\n    proof(cases \"(str_ord_delete k l')\")\n      case Nil\n      show ?thesis\n      proof(rule strict_order_intro)\n        fix i j :: nat\n        show \"j < length (map fst (str_ord_delete k (a # l'))) \\<Longrightarrow>\n           i < j \\<Longrightarrow> map fst (str_ord_delete k (a # l')) ! i < map fst (str_ord_delete k (a # l')) ! j\"\n          using 3 Ha Nil by(cases i; auto)\n      qed\n    next\n      fix a' :: \"'key * 'value\"\n      fix l'' :: \"('key * 'value) list\"\n      obtain a'k and a'v where Ha' : \"a' = (a'k, a'v)\" by(cases a'; auto) \n      assume Hcons : \"(str_ord_delete k l') = a'#l''\"\n      show ?thesis\n      proof(cases l')\n        case Nil\n        show ?thesis\n        proof(rule strict_order_intro)\n          fix i j :: nat\n          show \"j < length (map fst (str_ord_delete k (a # l'))) \\<Longrightarrow>\n           i < j \\<Longrightarrow> map fst (str_ord_delete k (a # l')) ! i < map fst (str_ord_delete k (a # l')) ! j\"\n            using 3 Ha Nil by(cases i; auto split:if_split_asm)\n        qed\n      next\n        fix x :: \"'key * 'value\"\n        fix m :: \"('key * 'value) list\"\n        obtain xk and xv where Hx : \"x = (xk, xv)\" by (cases x; auto)\n        assume Hcons2 : \"l' = x#m\"\n        have Hi2'' : \"strict_order (xk # map fst m)\" using Hcons2 Hx Hi2' by auto\n        consider (C3_1) \"hd (str_ord_delete k ((xk, xv)#m)) = (xk, xv)\" and \"xk \\<noteq> k\" |\n                 (C3_2) k' v' where \"hd (str_ord_delete k ((xk, xv)#m)) = (k', v')\" and \"k = xk\" and \"xk < k'\" |\n                 (C3_3) \"(l' = [])\"\n          using str_ord_delete_head[OF Hi2'', of k xv] Hcons Hcons2 Ha Hi2' Hx by(auto split:if_split_asm)\n        then show ?thesis\n        proof cases\n          case C3_1\n          have Hcons_a_x : \"strict_order (ak # xk # map fst m)\" using Hcons2 Hx Ha Hi2 by(auto)\n          show ?thesis using C3_1 3 Ha  Ha' Hx Hi1' strict_order_unfold[OF Hcons_a_x, of 1 0] Hcons Hcons2\n            apply(auto)\n            apply(rule_tac strict_order_cons) apply(auto split:if_splits)\n            done\n        next\n          case C3_2\n          have Hcons_a_x : \"strict_order (ak # xk # map fst m)\" using Hcons2 Hx Ha Hi2 by(auto)\n          show ?thesis using 3 Ha  Ha' Hx Hi1' Hcons2 Hcons_a_x strict_order_2nd[OF Hcons_a_x]\n            strict_order_unfold[OF Hcons_a_x, of 1 0]\n            apply(auto)\n            apply(rule_tac strict_order_cons) apply(auto split:if_splits)\n            done\n        next\n          case C3_3\n          then show ?thesis using Ha by(auto simp add:strict_order_def)\n        qed\n      qed\n    qed\n  qed\nqed\n\nlift_definition delete :: \"('key :: linorder) \\<Rightarrow> ('key, 'value) oalist \\<Rightarrow> ('key, 'value) oalist\"\nis str_ord_delete\nproof(-)\n  fix k :: \"'key :: linorder\"\n  fix l :: \"('key * 'value) list\"\n  assume H : \"strict_order (map fst l)\"\n  show \"strict_order (map fst (str_ord_delete k l))\" using str_ord_delete_correct[OF H] by auto\nqed\n\nfun to_oalist :: \"(('a :: linorder) * 'b) list \\<Rightarrow> ('a, 'b) oalist\" where\n\"to_oalist [] = empty\"\n| \"to_oalist ((a, b)#l) = \n     update a b (to_oalist l)\"\n\nlift_definition get :: \"('key, 'value) oalist \\<Rightarrow> ('key :: linorder) \\<Rightarrow>  'value option\"\nis map_of .\n\ndefinition has_key :: \"('key) kmap \\<Rightarrow> 'key :: linorder \\<Rightarrow> bool\" where\n\"has_key l k = (get l k = Some ())\"\n\n(* possibly useful for semantics - if a key map describing updated values\n   has only one entry, we can pull it out. *)\ndefinition kmap_singleton :: \"('key :: linorder) kmap \\<Rightarrow> 'key\" where\n\"kmap_singleton l =\n  (case impl_of l of\n    [k] \\<Rightarrow> fst k)\"\n\ndefinition add_key :: \"('key) kmap \\<Rightarrow> 'key :: linorder \\<Rightarrow> 'key kmap\" where\n\"add_key l k = update k () l\"\n\n(* some useful functions for combining oalists *)\nfun oalist_merge' :: \"(('key :: linorder) * 'value) list \\<Rightarrow> ('key, 'value) oalist \\<Rightarrow> ('key, 'value) oalist\"\n  where\n\"oalist_merge' [] l2 = l2\"\n| \"oalist_merge' ((k,v)#t) l2 =\n   update k v (oalist_merge' t l2)\"\n\nlift_definition oalist_merge ::\n\"('key :: linorder, 'value) oalist \\<Rightarrow> ('key, 'value) oalist \\<Rightarrow> ('key, 'value) oalist\"\nis oalist_merge' .\n\nlemma strict_order_singleton :\n  \"strict_order [x]\"\nproof(rule strict_order_intro)\n  fix i j\n  assume H1 : \"j < length [x]\"\n  assume H2 : \"i < j\" \n  show \"[x] ! i < [x] ! j\" using H1 H2\n    by(auto)\nqed\n\nfun alist_map_val ::\n  \"('v1 \\<Rightarrow> 'v2) \\<Rightarrow> ('key * 'v1) list \\<Rightarrow> ('key * 'v2) list\" where\n\"alist_map_val f l =\n  map (map_prod id f) l\"\n\nlemma strict_order_nil : \"strict_order []\"\n  by(rule strict_order_intro; auto)\n\nlift_definition\n  oalist_map_val ::\n  \"('v1 \\<Rightarrow> 'v2) \\<Rightarrow> ('key :: linorder, 'v1) oalist \\<Rightarrow> ('key, 'v2) oalist\"\n is alist_map_val\n  by (auto intro: strict_order_nil)\n\ndefinition alist_all_val ::\n  \"('v1 \\<Rightarrow> bool) \\<Rightarrow> ('key * 'v1) list \\<Rightarrow> bool\" where\n\"alist_all_val P l =\n  list_all P (map snd l)\"\n\nlift_definition oalist_all_val :: \"('v \\<Rightarrow> bool) \\<Rightarrow> ('key :: linorder, 'v) oalist \\<Rightarrow> bool\"\nis alist_all_val .\n\nlift_definition oaset :: \"('key :: linorder, 'v) oalist \\<Rightarrow> ('key * 'v) set\"\nis set .\n\n(* zip two oalists together using the given functions -\n * one for both keys present, one for left key present, one for right key present *)\nfun str_ord_zip ::\n  \"('key \\<Rightarrow> 'value1 \\<Rightarrow> 'value2 \\<Rightarrow> 'value3 ) \\<Rightarrow>\n   ('key \\<Rightarrow> 'value1 \\<Rightarrow> 'value3) \\<Rightarrow>\n   ('key \\<Rightarrow> 'value2 \\<Rightarrow> 'value3) \\<Rightarrow>\n   (('key :: linorder) * 'value1) list \\<Rightarrow> ('key * 'value2) list \\<Rightarrow>\n   ('key * 'value3) list\" where\n\"str_ord_zip flr fl fr [] [] = []\"\n| \"str_ord_zip flr fl fr ((lk, lh)#lt) [] =\n    (lk, fl lk lh)#str_ord_zip flr fl fr lt []\"\n| \"str_ord_zip flr fl fr [] ((rk, rh)#rt) =\n    (rk, fr rk rh)#str_ord_zip flr fl fr [] rt\"\n| \"str_ord_zip flr fl fr ((lk, lh)#lt) ((rk, rh)#rt) =\n  (if (lk < rk)\n   then (lk, fl lk lh) # str_ord_zip flr fl fr lt ((rk, rh)#rt)\n   else (if lk = rk\n         then (lk, flr lk lh rh) # str_ord_zip flr fl fr lt rt\n         else (rk, fr rk rh) # str_ord_zip flr fl fr ((lk, lh) # lt) (rt)))\"\n\nlemma str_ord_zip_head_key :\n  shows\n    \"(\\<exists> res_l res_v .\n     str_ord_zip flr fl fr ((lk, lv)#ll) ((rk, rv)#lr) = ((lk, res_v)#res_l)) \\<or>\n    (\\<exists> res_l res_v .\n     str_ord_zip flr fl fr ((lk, lv)#ll) ((rk, rv)#lr) = ((rk, res_v)#res_l))\"\nproof-\n\n  consider (A) \"lk < rk\" |\n           (B) \"lk = rk\" |\n           (C) \"rk < lk\"\n    using less_linear[of lk rk] by auto\n\n  then show \"(\\<exists>res_l res_v.\n        str_ord_zip flr fl fr ((lk, lv) # ll) ((rk, rv) # lr) =\n        (lk, res_v) # res_l) \\<or>\n    (\\<exists>res_l res_v.\n        str_ord_zip flr fl fr ((lk, lv) # ll) ((rk, rv) # lr) =\n        (rk, res_v) # res_l)\" \n    by(cases; auto)\nqed\n\nlemma str_ord_zip_leftonly :\n  assumes H : \"strict_order (map fst ll)\"\n  shows \"strict_order (map fst (str_ord_zip flr fl fr ll []))\" using H\nproof(induction ll)\n  case Nil\n  then show ?case using strict_order_nil\n    by auto\nnext\n  case (Cons lh lt)\n\n  obtain lk lv where Lh : \"lh = (lk, lv)\"\n    by(cases lh; auto)\n\n  then show ?case\n  proof(cases lt)\n    case Nil' : Nil\n    then show ?thesis using Lh strict_order_singleton\n      by(auto)\n  next\n    case Cons' : (Cons lh1 lt1)\n\n    have Ord' : \"strict_order (map fst lt)\"\n      using strict_order_tl[of lk \"map fst lt\"] Cons.prems(1) unfolding Lh\n      by auto\n\n    obtain lk1 lv1 where Lh1 : \"lh1 = (lk1, lv1)\"\n      by(cases lh1; auto)\n\n    have Lk_lt : \"lk < lk1\"\n      using strict_order_unfold[OF Cons.prems(1), of 1 0]\n      unfolding Cons' Lh Lh1\n      by auto\n\n    have Conc' : \"strict_order (lk1 # map fst (str_ord_zip flr fl fr lt1 []))\"\n      using Cons.IH[OF Ord'] Cons.prems Cons' Lh Lh1\n      by(auto)\n\n    show ?thesis\n      using strict_order_cons[OF Lk_lt Conc'] Cons.prems Cons' Lh Lh1\n      by auto\n  qed\nqed\n\nlemma str_ord_zip_rightonly :\n  assumes H : \"strict_order (map fst lr)\"\n  shows \"strict_order (map fst (str_ord_zip flr fl fr [] lr))\" using H\nproof(induction lr)\n  case Nil\n  then show ?case using strict_order_nil\n    by auto\nnext\n  case (Cons rh rt)\n\n  obtain rk rv where Rh : \"rh = (rk, rv)\"\n    by(cases rh; auto)\n\n  then show ?case\n  proof(cases rt)\n    case Nil' : Nil\n    then show ?thesis using Rh strict_order_singleton\n      by(auto)\n  next\n    case Cons' : (Cons rh1 rt1)\n\n    have Ord' : \"strict_order (map fst rt)\"\n      using strict_order_tl[of rk \"map fst rt\"] Cons.prems(1) unfolding Rh\n      by auto\n\n    obtain rk1 rv1 where Rh1 : \"rh1 = (rk1, rv1)\"\n      by(cases rh1; auto)\n\n    have Rk_lt : \"rk < rk1\"\n      using strict_order_unfold[OF Cons.prems(1), of 1 0]\n      unfolding Cons' Rh Rh1\n      by auto\n\n    have Conc' : \"strict_order (rk1 # map fst (str_ord_zip flr fl fr [] rt1))\"\n      using Cons.IH[OF Ord'] Cons.prems Cons' Rh Rh1\n      by(auto)\n\n    show ?thesis\n      using strict_order_cons[OF Rk_lt Conc'] Cons.prems Cons' Rh Rh1\n      by auto\n  qed\nqed\n\nlemma str_ord_zip_correct' :\n  shows \"strict_order (map fst ll) \\<longrightarrow>\n         strict_order (map fst lr) \\<longrightarrow>\n         strict_order (map fst (str_ord_zip flr fl fr ll lr))\"\nproof(induction rule:\n      str_ord_zip.induct\n        [of \"(\\<lambda> flr fl fr ll lr . \n              strict_order (map fst ll) \\<longrightarrow>\n              strict_order (map fst lr) \\<longrightarrow>\n              strict_order (map fst (str_ord_zip flr fl fr ll lr)))\"])\n  case (1 flr fl fr)\n  then show ?case \n    by auto\nnext\n  case (2 flr fl fr lk lv lt)\n\n  have Conc' : \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow> strict_order (map fst []) \\<Longrightarrow> strict_order (map fst (str_ord_zip flr fl fr ((lk, lv) # lt) []))\"\n  proof-\n    assume Ord1 : \"strict_order (map fst ((lk, lv) # lt))\"\n    assume Ord2 : \"strict_order (map fst [])\"\n\n    show \"strict_order (map fst (str_ord_zip flr fl fr ((lk, lv) # lt) []))\"\n      using str_ord_zip_leftonly[OF Ord1] by auto\n  qed\n\n  then show ?case by auto\nnext\n  case (3 flr fl fr rk rv rt)\n\n  have Conc' : \"strict_order (map fst []) \\<Longrightarrow> strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow> strict_order (map fst (str_ord_zip flr fl fr [] ((rk, rv) # rt)))\"\n  proof-\n    assume Ord1 : \"strict_order (map fst ((rk, rv) # rt))\"\n    assume Ord2 : \"strict_order (map fst [])\"\n\n    show \"strict_order (map fst (str_ord_zip flr fl fr [] ((rk, rv) # rt)))\"\n      using str_ord_zip_rightonly[OF Ord1] by auto\n  qed\n\n  then show ?case by auto\n\nnext\n  case (4 flr fl fr lk lv lt rk rv rt)\n\n  have Conc' : \n    \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow>\n       strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow>\n       strict_order (map fst (str_ord_zip flr fl fr ((lk, lv) # lt) ((rk, rv) # rt)))\"\n  proof-\n    assume Ord1 : \"strict_order (map fst ((lk, lv) # lt))\"\n    assume Ord2 : \"strict_order (map fst ((rk, rv) # rt))\"\n\n    have Ord1_tl : \"strict_order (map fst (lt))\"\n      using strict_order_tl[of lk \"map fst lt\"] Ord1 by auto\n    have Ord2_tl : \"strict_order (map fst (rt))\"\n      using strict_order_tl[of rk \"map fst rt\"] Ord2 by auto\n\n    consider (A) \"lk < rk\" |\n             (B) \"rk < lk\" |\n             (C) \"lk = rk\"\n      using less_linear[of lk rk] by auto\n  \n    then show ?thesis \n    proof cases\n      case A\n\n      have IH : \"strict_order (map fst lt) \\<Longrightarrow>\n                 strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow>\n                 strict_order (map fst (str_ord_zip flr fl fr lt ((rk, rv) # rt)))\"\n        using 4(1)[OF A] by blast\n\n      show ?thesis\n      proof(cases lt)\n        case Nil\n\n        have Conc' : \"strict_order (rk # map fst (str_ord_zip flr fl fr [] rt))\"\n          using IH[OF Ord1_tl Ord2] Nil\n          by auto\n\n        then show ?thesis \n          using strict_order_cons[OF A Conc'] A Nil\n          by(auto)\n      next\n        case (Cons lh1 lt1)\n\n        obtain lk1 lv1 where Lh1 : \"lh1 = (lk1, lv1)\" by(cases lh1; auto)\n  \n        have Lk_lt: \"lk < lk1\" \n          using strict_order_unfold[OF Ord1, of 1 0] Cons Lh1\n          by auto\n\n        consider (L) res_v res_l where \"str_ord_zip flr fl fr ((lk1, lv1) # lt1) ((rk, rv) # rt) = \n              (lk1, res_v) # res_l\" \"lk1 \\<le> rk\"\n          | (R) res_v res_l where \"str_ord_zip flr fl fr ((lk1, lv1) # lt1) ((rk, rv) # rt) = (rk, res_v) # res_l\" \"rk \\<le> lk1\"\n          using str_ord_zip_head_key[of flr fl fr lk1 lv1 lt1 rk rv rt ]\n          by(auto split:if_splits)\n  \n        then show ?thesis\n        proof cases\n          case L\n\n          have Lk1_head : \"strict_order (lk1 # map fst (res_l))\"\n            using IH[OF Ord1_tl Ord2] unfolding Cons Lh1 L(1) by auto\n\n          have Lk_head : \"strict_order (lk # map fst ((lk1, res_v) # res_l))\"\n            using strict_order_cons[OF Lk_lt Lk1_head] by auto\n\n          show ?thesis using Lk_head A L(1) unfolding  Cons Lh1\n            by(auto)\n        next\n          case R\n\n          have Rk_head : \"strict_order (rk # map fst (res_l))\"\n            using IH[OF Ord1_tl Ord2] unfolding Cons Lh1 R(1) by auto\n\n          have Lk_head : \"strict_order (lk # rk # map fst res_l)\"\n            using strict_order_cons[OF A Rk_head] by simp\n\n          show ?thesis using Lk_head A R(1) unfolding  Cons Lh1\n            by(auto)\n        qed\n      qed\n    next\n      case B\n      \n      have IH : \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow>\n                 strict_order (map fst rt) \\<Longrightarrow>\n                 strict_order (map fst (str_ord_zip flr fl fr ((lk, lv) # lt) rt))\"\n        using 4(3) B\n        by auto\n\n      show ?thesis\n      proof(cases rt)\n        case Nil\n\n        have Conc' : \"strict_order (lk # map fst (str_ord_zip flr fl fr lt []))\"\n          using IH[OF Ord1 Ord2_tl] Nil strict_order_singleton\n          by(auto)\n\n        then show ?thesis \n          using strict_order_cons[OF B Conc'] B Nil\n          by(auto)\n      next\n        case (Cons rh1 rt1)\n        obtain rk1 rv1 where Rh1 : \"rh1 = (rk1, rv1)\" by(cases rh1; auto)\n  \n        have Rk_lt: \"rk < rk1\" \n          using strict_order_unfold[OF Ord2, of 1 0] Cons Rh1\n          by auto\n\n        consider (L) res_v res_l where \"str_ord_zip flr fl fr ((lk, lv) # lt) ((rk1, rv1) # rt1) = \n              (rk1, res_v) # res_l\" \"rk1 \\<le> lk\"\n          | (R) res_v res_l where \"str_ord_zip flr fl fr ((lk, lv) # lt) ((rk1, rv1) # rt1) = (lk, res_v) # res_l\" \"lk \\<le> rk1\"\n          using str_ord_zip_head_key[of flr fl fr lk lv lt rk1 rv1 rt1]\n          by(auto split:if_splits)\n  \n        then show ?thesis\n        proof cases\n          case L\n\n          have Rk1_head : \"strict_order (rk1 # map fst (res_l))\"\n            using IH[OF Ord1 Ord2_tl] unfolding Cons Rh1 L(1) by auto\n\n          have Rk_head : \"strict_order (rk # map fst ((rk1, res_v) # res_l))\"\n            using strict_order_cons[OF Rk_lt Rk1_head] by auto\n\n          show ?thesis using Rk_head B L(1) unfolding Cons Rh1\n            by(auto)\n        next\n          case R\n\n          have Lk_head : \"strict_order (lk # map fst (res_l))\"\n            using IH[OF Ord1 Ord2_tl] unfolding Cons Rh1 R(1) by auto\n\n          have Rk_head : \"strict_order (rk # lk # map fst res_l)\"\n            using strict_order_cons[OF B Lk_head] by simp\n\n          show ?thesis using Rk_head B R(1) unfolding Cons Rh1\n            by(auto)\n        qed\n      qed\n    next\n      case C\n\n      have IH : \"strict_order (map fst lt) \\<Longrightarrow> strict_order (map fst rt) \\<Longrightarrow> strict_order (map fst (str_ord_zip flr fl fr lt rt))\"\n        using 4(2) C\n        by auto\n\n      show ?thesis\n      proof(cases lt)\n        case Nil_L : Nil\n\n        show ?thesis\n        proof(cases rt)\n          case Nil_R : Nil\n\n          then show ?thesis using C Nil_L strict_order_singleton\n            by(auto)\n        next\n          case Cons_R : (Cons rh1 rt1)\n\n          obtain rk1 rv1 where Rh1 : \"rh1 = (rk1, rv1)\" by(cases rh1; auto)\n\n          have Rk_lt: \"rk < rk1\" \n            using strict_order_unfold[OF Ord2, of 1 0] Cons_R Rh1\n            by(auto)\n\n          have Conc' : \"strict_order (rk1 # map fst (str_ord_zip flr fl fr [] rt1))\"\n            using IH[OF Ord1_tl Ord2_tl] Nil_L Cons_R unfolding Rh1\n            by(auto)\n\n          show ?thesis\n            using strict_order_cons[OF Rk_lt Conc'] Nil_L Cons_R C Rh1\n            by(auto)\n        qed\n      next\n        case Cons_L : (Cons lh1 lt1)\n\n        obtain lk1 lv1 where Lh1 : \"lh1 = (lk1, lv1)\" by(cases lh1; auto)\n\n        have Lk_lt: \"lk < lk1\" \n          using strict_order_unfold[OF Ord1, of 1 0] Cons_L Lh1\n          by(auto)\n\n        show ?thesis\n        proof(cases rt)\n          case Nil_R : Nil\n\n          have Conc' : \"strict_order (lk1 # map fst (str_ord_zip flr fl fr lt1 []))\"\n            using IH[OF Ord1_tl Ord2_tl] Cons_L Nil_R unfolding Lh1\n            by(auto)\n\n          show ?thesis\n            using strict_order_cons[OF Lk_lt Conc'] Nil_R Cons_L C Lh1\n            by(auto)\n        next\n          case Cons_R : (Cons rh1 rt1)\n\n          obtain rk1 rv1 where Rh1 : \"rh1 = (rk1, rv1)\" by(cases rh1; auto)\n\n          have Rk_lt: \"rk < rk1\" \n            using strict_order_unfold[OF Ord2, of 1 0] Cons_R Rh1\n            by(auto)\n  \n          consider (L) res_v res_l where \"str_ord_zip flr fl fr ((lk1, lv1) # lt1) ((rk1, rv1) # rt1) = \n                (rk1, res_v) # res_l\" \"rk1 \\<le> lk1\"\n            | (R) res_v res_l where \"str_ord_zip flr fl fr ((lk1, lv1) # lt1) ((rk1, rv1) # rt1) = (lk1, res_v) # res_l\" \"lk1 \\<le> rk1\"\n            using str_ord_zip_head_key[of flr fl fr lk1 lv1 lt1 rk1 rv1 rt1]\n            by(auto split:if_splits)\n    \n          then show ?thesis\n          proof cases\n            case L\n  \n            have Rk1_head : \"strict_order (rk1 # map fst (res_l))\"\n              using IH[OF Ord1_tl Ord2_tl] unfolding Cons_L Cons_R Rh1 Lh1 L(1)\n              by (auto)\n  \n            have Rk_head : \"strict_order (rk # map fst ((rk1, res_v) # res_l))\"\n              using strict_order_cons[OF Rk_lt Rk1_head] by auto\n  \n            show ?thesis using Rk_head C L(1) unfolding Cons_L Cons_R Lh1 Rh1\n              by(auto)\n          next\n            case R\n\n            have Lk_lt': \"lk < rk1\" \n              using Lk_lt Rk_lt C \n              by simp\n  \n            have Lk_head : \"strict_order (lk1 # map fst (res_l))\"\n              using IH[OF Ord1_tl Ord2_tl] unfolding Cons_L Cons_R Rh1 Lh1 R(1) by auto\n\n            have Lk_head' : \"strict_order (lk # lk1 # map fst res_l)\" \n              using strict_order_cons[OF Lk_lt Lk_head] by simp\n\n            show ?thesis using Lk_head' C R(1) unfolding Cons_L Cons_R Lh1 Rh1\n              by(auto)\n          qed\n        qed\n      qed\n    qed\n  qed\n\n  then show ?case by blast\nqed\n\nlemma str_ord_zip_correct :\n  shows \"strict_order (map fst ll) \\<Longrightarrow>\n         strict_order (map fst lr) \\<Longrightarrow>\n         strict_order (map fst (str_ord_zip flr fl fr ll lr))\"\n  using str_ord_zip_correct'\n  by blast\n\n\n(* finally, we get our zip function *)\n\nlift_definition oalist_zip :: \n  \"('key \\<Rightarrow> 'value1 \\<Rightarrow> 'value2 \\<Rightarrow> 'value3 ) \\<Rightarrow>\n   ('key \\<Rightarrow> 'value1 \\<Rightarrow> 'value3) \\<Rightarrow>\n   ('key \\<Rightarrow> 'value2 \\<Rightarrow> 'value3) \\<Rightarrow>\n   (('key :: linorder), 'value1) oalist \\<Rightarrow> ('key, 'value2) oalist \\<Rightarrow>\n   ('key, 'value3) oalist\"\nis str_ord_zip\n  using str_ord_zip_correct\n  by blast\n\nlemma str_ord_zip_get' :\n  shows \"strict_order (map fst ll) \\<longrightarrow> \n   strict_order (map fst lr) \\<longrightarrow>\n    map_of (str_ord_zip flr fl fr ll lr) k =\n    (case (map_of ll k, map_of lr k) of\n     (None, None) \\<Rightarrow> None\n     | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n     | (None, Some vr) \\<Rightarrow> Some (fr k vr)\n     | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\nproof(induction ll lr rule:str_ord_zip.induct\n    [of \"(\\<lambda> flr fl fr ll lr . \n              strict_order (map fst ll) \\<longrightarrow>\n              strict_order (map fst lr) \\<longrightarrow>\n              map_of (str_ord_zip flr fl fr ll lr) k =\n                (case (map_of ll k, map_of lr k) of\n                 (None, None) \\<Rightarrow> None\n                 | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n                 | (None, Some vr) \\<Rightarrow> Some (fr k vr)\n                 | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr)))\"])\ncase (1 flr fl fr)\n  then show ?case \n    by(auto)\nnext\n  case (2 flr fl fr lk lv lt)\n\n  have Conc' :\n    \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow>\n    strict_order (map fst []) \\<Longrightarrow>\n    map_of (str_ord_zip flr fl fr ((lk, lv) # lt) []) k =\n    (case (map_of ((lk, lv) # lt) k, map_of [] k) of (None, None) \\<Rightarrow> None\n     | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n     | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n  proof-\n    assume Ord1 : \"strict_order (map fst ((lk, lv) # lt))\"\n    assume Ord2 : \"strict_order (map fst [])\"\n\n    have Ord1' : \"strict_order (map fst lt)\"\n      using strict_order_tl[of lk \"map fst lt\"] Ord1\n      by auto\n\n    show \"map_of (str_ord_zip flr fl fr ((lk, lv) # lt) []) k =\n    (case (map_of ((lk, lv) # lt) k, map_of [] k) of (None, None) \\<Rightarrow> None\n     | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n     | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n      using 2 Ord1' strict_order_nil\n      by auto\n  qed\n\n  then show ?case by blast\nnext\n  case (3 flr fl fr rk rv rt)\n\n  have Conc' :\n    \"strict_order (map fst []) \\<Longrightarrow>\n    strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow>\n     map_of (str_ord_zip flr fl fr [] ((rk, rv) # rt)) k =\n       (case (map_of [] k, map_of ((rk, rv) # rt) k) of (None, None) \\<Rightarrow> None\n        | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n        | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n  proof-\n    assume Ord1 : \"strict_order (map fst [])\"\n\n    assume Ord2 : \"strict_order (map fst ((rk, rv) # rt))\"\n\n    have Ord2' : \"strict_order (map fst rt)\"\n      using strict_order_tl[of rk \"map fst rt\"] Ord2\n      by auto\n\n    show \"map_of (str_ord_zip flr fl fr [] ((rk, rv) # rt)) k =\n       (case (map_of [] k, map_of ((rk, rv) # rt) k) of (None, None) \\<Rightarrow> None\n        | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n        | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n      using 3 Ord2' strict_order_nil\n      by auto\n  qed\n\n  then show ?case by blast\nnext\n  case (4 flr fl fr lk lv lt rk rv rt)\n\n  consider (A) \"lk < rk\" |\n           (B) \"rk < lk\" |\n           (C) \"lk = rk\"\n    using less_linear[of lk rk] by auto\n\n  then show ?case\n  proof cases\n    case A\n\n    have Conc' : \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow>\n      strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow>\n      map_of (str_ord_zip flr fl fr ((lk, lv) # lt) ((rk, rv) # rt)) k =\n      (case (map_of ((lk, lv) # lt) k, map_of ((rk, rv) # rt) k) of (None, None) \\<Rightarrow> None\n       | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n       | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n    proof-\n\n      assume Ord1 : \"strict_order (map fst ((lk, lv) # lt))\"\n      assume Ord2 : \"strict_order (map fst ((rk, rv) # rt))\"\n\n      have Ord1' : \"strict_order (map fst lt)\"\n        using strict_order_tl[of lk \"map fst lt\"] Ord1 by auto\n\n      have Ord2' : \"strict_order (map fst rt)\"\n        using strict_order_tl[of rk \"map fst rt\"] Ord2 by auto\n\n      consider\n        (NN) \"map_of ((lk, lv) # lt) k = None\"  \"map_of ((rk, rv) # rt) k = None\" |\n        (SN) vl where \"map_of ((lk, lv) # lt) k = Some vl\" \"map_of ((rk, rv) # rt) k = None\" |\n        (NS) vr where \"map_of ((lk, lv) # lt) k = None\" \"map_of ((rk, rv) # rt) k = Some vr\" |\n        (SS) vl vr where \"map_of ((lk, lv) # lt) k = Some vl\" \"map_of ((rk, rv) # rt) k = Some vr\"\n        by(cases \"map_of ((lk, lv) # lt) k\"; cases \"map_of ((rk, rv) # rt) k\"; auto)\n\n      then show ?thesis\n      proof cases\n        case NN\n        then show ?thesis using A 4(1)[OF A] Ord1 Ord2 Ord1'\n          by(auto split:if_split_asm)\n      next\n        case SN\n        then show ?thesis using A 4(1)[OF A] Ord1 Ord2 Ord1'\n          by(auto split:if_split_asm)\n      next\n        case NS\n        then show ?thesis using A 4(1)[OF A] Ord1 Ord2 Ord1'\n          by(auto split:if_split_asm)\n      next\n        case SS\n\n        have Contr : \"map_of rt lk = None\"\n        proof(cases \"map_of rt lk\")\n          case None\n          then show ?thesis by auto\n        next\n          case (Some bad)\n\n          have Bad_in : \"(lk, bad) \\<in> set rt\" using map_of_SomeD[OF Some] by simp\n\n          obtain idx where Idx : \"idx < length rt\" \"rt ! idx = (lk, bad)\" \n            using Bad_in\n            unfolding in_set_conv_nth \n            by blast\n\n          then show ?thesis using strict_order_unfold[OF Ord2, of \"1 + idx\" 0] A\n            by(simp)\n        qed\n\n        then show ?thesis using A 4(1)[OF A] Ord1 Ord2 Ord1' Ord2'\n          by(auto split: if_split_asm option.split_asm)\n      qed\n    qed\n\n    then show ?thesis by blast\n  next\n    case B \n\n    have Conc' : \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow>\n      strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow>\n      map_of (str_ord_zip flr fl fr ((lk, lv) # lt) ((rk, rv) # rt)) k =\n      (case (map_of ((lk, lv) # lt) k, map_of ((rk, rv) # rt) k) of (None, None) \\<Rightarrow> None\n       | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n       | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n    proof-\n      assume Ord1 : \"strict_order (map fst ((lk, lv) # lt))\"\n      assume Ord2 : \"strict_order (map fst ((rk, rv) # rt))\"\n\n      have Ord1' : \"strict_order (map fst lt)\"\n        using strict_order_tl[of lk \"map fst lt\"] Ord1 by auto\n\n      have Ord2' : \"strict_order (map fst rt)\"\n        using strict_order_tl[of rk \"map fst rt\"] Ord2 by auto\n\n      consider\n        (NN) \"map_of ((lk, lv) # lt) k = None\"  \"map_of ((rk, rv) # rt) k = None\" |\n        (SN) vl where \"map_of ((lk, lv) # lt) k = Some vl\" \"map_of ((rk, rv) # rt) k = None\" |\n        (NS) vr where \"map_of ((lk, lv) # lt) k = None\" \"map_of ((rk, rv) # rt) k = Some vr\" |\n        (SS) vl vr where \"map_of ((lk, lv) # lt) k = Some vl\" \"map_of ((rk, rv) # rt) k = Some vr\"\n        by(cases \"map_of ((lk, lv) # lt) k\"; cases \"map_of ((rk, rv) # rt) k\"; auto)\n\n      then show ?thesis\n      proof cases\n        case NN\n        then show ?thesis using B 4(3) Ord1 Ord2 Ord2'\n          by(auto split:if_split_asm)\n      next\n        case SN\n        then show ?thesis using B 4(3) Ord1 Ord2 Ord2'\n          by(auto split:if_split_asm)\n      next\n        case NS\n        then show ?thesis using B 4(3) Ord1 Ord2 Ord2'\n          by(auto split:if_split_asm)\n      next\n        case SS\n\n        have Contr : \"map_of lt rk = None\"\n        proof(cases \"map_of lt rk\")\n          case None\n          then show ?thesis by auto\n        next\n          case (Some bad)\n\n          have Bad_in : \"(rk, bad) \\<in> set lt\" using map_of_SomeD[OF Some] by simp\n\n          obtain idx where Idx : \"idx < length lt\" \"lt ! idx = (rk, bad)\" \n            using Bad_in\n            unfolding in_set_conv_nth \n            by blast\n\n          then show ?thesis using strict_order_unfold[OF Ord1, of \"1 + idx\" 0] B\n            by(simp)\n        qed\n\n        then show ?thesis using B 4(3) Ord1 Ord2 Ord1' Ord2'\n          by(auto split: if_split_asm option.split_asm)\n      qed\n    qed\n\n    then show ?thesis by blast\n  next\n    case C \n\n    have Conc' : \"strict_order (map fst ((lk, lv) # lt)) \\<Longrightarrow>\n                  strict_order (map fst ((rk, rv) # rt)) \\<Longrightarrow>\n                    map_of (str_ord_zip flr fl fr ((lk, lv) # lt) ((rk, rv) # rt)) k =\n                  (case (map_of ((lk, lv) # lt) k, map_of ((rk, rv) # rt) k) of (None, None) \\<Rightarrow> None\n                   | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n                   | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n    proof-\n      assume Ord1 : \"strict_order (map fst ((lk, lv) # lt))\"\n      assume Ord2 : \"strict_order (map fst ((rk, rv) # rt))\"\n\n      have Ord1' : \"strict_order (map fst lt)\"\n        using strict_order_tl[of lk \"map fst lt\"] Ord1 by auto\n\n      have Ord2' : \"strict_order (map fst rt)\"\n        using strict_order_tl[of rk \"map fst rt\"] Ord2 by auto\n\n      consider\n        (NN) \"map_of ((lk, lv) # lt) k = None\"  \"map_of ((rk, rv) # rt) k = None\" |\n        (SN) vl where \"map_of ((lk, lv) # lt) k = Some vl\" \"map_of ((rk, rv) # rt) k = None\" |\n        (NS) vr where \"map_of ((lk, lv) # lt) k = None\" \"map_of ((rk, rv) # rt) k = Some vr\" |\n        (SS) vl vr where \"map_of ((lk, lv) # lt) k = Some vl\" \"map_of ((rk, rv) # rt) k = Some vr\"\n        by(cases \"map_of ((lk, lv) # lt) k\"; cases \"map_of ((rk, rv) # rt) k\"; auto)\n\n      then show ?thesis\n      proof cases\n        case NN\n        then show ?thesis using C 4(2) Ord1 Ord2 Ord1' Ord2'\n          by(auto split:if_split_asm)\n      next\n        case SN\n        then show ?thesis using C 4(2) Ord1 Ord2 Ord1' Ord2'\n          by(auto split:if_split_asm)\n      next\n        case NS\n        then show ?thesis using C 4(2) Ord1 Ord2 Ord1' Ord2'\n          by(auto split:if_split_asm)\n      next\n        case SS\n\n        then show ?thesis using C 4(2) Ord1 Ord2 Ord1' Ord2'\n          by(auto split:if_split_asm)\n      qed\n    qed\n\n    then show ?thesis using C 4(2)\n      by(auto split: if_split_asm option.split_asm)\n  qed\nqed\n\n\nlemma str_ord_update_str_ord_update :\n  assumes H: \"strict_order (map fst l)\"\n  shows \"str_ord_update k v' (str_ord_update k v l) = str_ord_update k v' l\"\nproof(induction l)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons lh lt)\n\n  obtain lk lv where Lh : \"lh = (lk, lv)\"\n    by(cases lh; auto)\n\n  show ?case using Cons Lh\n    by(auto)\nqed\n\nlemma update_update :\n  \"update k v' (update k v l) = update k v' l\"\n  by(transfer; auto simp add: str_ord_update_str_ord_update)\n\n\nlemma alist_all_val_get :\n  assumes H : \"alist_all_val P l\"\n  assumes K : \"map_of l k = Some r\"\n  shows \"P r\" using assms\nproof(induction l arbitrary: k)\n  case Nil\n  then show ?case \n    by(auto)\nnext\n  case (Cons lh lt)\n\n  obtain lhk lhv where Lh :  \"lh = (lhk, lhv)\"\n    by(cases lh; auto)\n\n  show ?case \n  proof(cases \"lhk = k\")\n    case True\n    then show ?thesis using Cons Lh\n      by(auto simp add: alist_all_val_def)\n  next\n    case False\n\n    have Ind : \"alist_all_val P lt\" using Cons\n      by(auto simp add: alist_all_val_def)\n\n    show ?thesis using Cons.prems Cons.IH[OF Ind] Lh False\n      by(auto)\n  qed\nqed\n\nlemma oalist_all_val_get :\n  assumes H : \"oalist_all_val P l\"\n  assumes K : \"get l k = Some r\"\n  shows \"P r\"\n  using assms\nproof(transfer)\n  fix P l k r\n  show \"strict_order (map fst l) \\<Longrightarrow> alist_all_val P l \\<Longrightarrow> map_of l k = Some r \\<Longrightarrow> P r\"\n    using assms alist_all_val_get[of P l k r]\n    by auto\nqed\n\nlemma alist_all_val_get_conv :\n  assumes H0 : \"strict_order (map fst l)\"\n  assumes H : \"\\<And> k r . map_of l k = Some r \\<Longrightarrow> P r\"\n  shows \"alist_all_val P l\"\n  using assms\nproof(induction l)\n  case Nil\n  then show ?case by (auto simp add: alist_all_val_def)\nnext\n  case (Cons lh lt)\n\n  obtain lhk lhv where Lh :  \"lh = (lhk, lhv)\"\n    by(cases lh; auto)\n\n  show ?case \n  proof(cases \"P lhv\")\n    case True\n\n    have Ord_tl : \"strict_order (map fst lt)\"\n      using strict_order_tl[of lhk \"map fst lt\"] Cons.prems Lh\n      by auto\n\n    have Hyp : \"(\\<And>k r. map_of lt k = Some r \\<Longrightarrow> P r)\"\n    proof-\n      fix k r\n      assume M : \"map_of lt k = Some r\"\n\n      then have Neq : \"k \\<noteq> lhk\"\n      proof(cases \"k = lhk\")\n        case True' : True\n\n        then have In : \"k \\<in> set (map fst lt)\" using imageI[OF map_of_SomeD[OF M], of fst]\n          by auto\n\n        then have  False\n          using strict_order_distinct[OF Cons.prems(1)] Lh True'\n          by(auto)\n\n        thus ?thesis by auto\n      next\n        case False' : False\n        then show ?thesis by auto\n      qed\n\n      then have Conc' : \"map_of (lh # lt) k = Some r\"\n        using Lh M\n        by(auto)\n\n      show \"P r\" using Cons.prems(2)[OF Conc']\n        by(auto)\n    qed\n\n    show ?thesis using Cons.IH[OF Ord_tl Hyp] True Lh\n      by(auto simp add: alist_all_val_def)\n  next\n    case False\n\n    have \"P lhv\"\n      using Lh Cons.prems(2)[of lhk lhv]\n      by auto\n\n    hence False using False by auto\n\n    thus ?thesis by auto\n  qed\nqed\n\nlemma oalist_all_val_get_eq :\n  \"oalist_all_val P l = (\\<forall> k r . get l k = Some r \\<longrightarrow> P r)\"\nproof(transfer)\n  fix P l\n  assume Ord : \"strict_order (map fst l)\"\n  show \"alist_all_val P l = (\\<forall>k r. map_of l k = Some r \\<longrightarrow> P r)\"\n  proof\n    assume \"alist_all_val P l\"\n    then show \"\\<forall>k r. map_of l k = Some r \\<longrightarrow> P r\"\n      using alist_all_val_get\n      by auto\n  next\n    assume \" \\<forall>k r. map_of l k = Some r \\<longrightarrow> P r\"\n    then show \"alist_all_val P l\"\n      using alist_all_val_get_conv[OF Ord]\n      by auto\n  qed\nqed\n    \n\n(*\n\n  \"('v1 \\<Rightarrow> bool) \\<Rightarrow> ('key * 'v1) list \\<Rightarrow> bool\" where\n\"alist_all_val P l =\n  list_all P (map snd l)\"\n*)\n\nlemma str_ord_zip_get :\n  assumes \"strict_order (map fst l1)\"\n  assumes \"strict_order (map fst l2)\"\n  shows \"map_of (str_ord_zip flr fl fr l1 l2) k =\n    (case (map_of l1 k, map_of l2 k) of (None, None) \\<Rightarrow> None | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl) | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\n  using assms str_ord_zip_get' by blast\n\nlemma oalist_zip_get :\n  shows \"get (oalist_zip flr fl fr l1 l2) k =\n    (case (get l1 k, get l2 k) of (None, None) \\<Rightarrow> None | (None, Some vr) \\<Rightarrow> Some (fr k vr) | (Some vl, None) \\<Rightarrow> Some (fl k vl) | (Some vl, Some vr) \\<Rightarrow> Some (flr k vl vr))\"\nproof(transfer)\n  fix flr fl fr l1 l2 k\n  show \"strict_order (map fst l1) \\<Longrightarrow>\n       strict_order (map fst l2) \\<Longrightarrow>\n       map_of (str_ord_zip flr fl fr l1 l2) k =\n       (case (map_of l1 k, map_of l2 k) of\n        (None, None) \\<Rightarrow> None\n        | (None, Some vr) \\<Rightarrow> Some (fr k vr)\n        | (Some vl, None) \\<Rightarrow> Some (fl k vl)\n        | (Some vl, Some vr) \\<Rightarrow>\n            Some (flr k vl vr))\"\n    using str_ord_zip_get\n    by blast\nqed\n\nlemma strict_order_cons' :\n  assumes H1 : \"strict_order (hk#t)\"\n  assumes H2 : \"k' \\<in> set t\"\n  shows \"hk < k'\"\nproof-\n  obtain k'_idx where \"t ! k'_idx = k'\" \"k'_idx < length t\"\n    using H2\n    unfolding in_set_conv_nth \n    by(blast)\n\n  then show ?thesis\n    using strict_order_unfold[OF H1, of \"1 + k'_idx\" 0]\n    by auto\nqed\n\nlemma str_ord_eq1 :\n  assumes \"l1 = l2\"\n  shows\n    \"map_of l1 k = map_of l2 k\"\n  using assms\n  by auto\n\nlemma str_ord_eq2 :\n  assumes H1 : \"strict_order (map fst l1)\"\n  assumes H2 : \"strict_order (map fst l2)\"\n  assumes H : \"\\<And> k . map_of l1 k = map_of l2 k\"\n  shows \"l1 = l2\" using assms\nproof(induction l1 arbitrary: l2)\n  case Nil\n  show ?case\n  proof(cases l2)\n    case Nil' : Nil\n    then show ?thesis using Nil by auto\n  next\n    case Cons' : (Cons l2h l2t)\n\n    obtain l2hk l2hv where L2h : \"l2h = (l2hk, l2hv)\"\n      by(cases l2h; auto)\n\n    have False using Nil(3)[of l2hk] L2h Cons'\n      by(auto)\n\n    then show ?thesis by auto\n  qed\nnext\n  case (Cons l1h l1t)\n\n  obtain l1hk l1hv where L1h : \"l1h = (l1hk, l1hv)\"\n    by(cases l1h; auto)\n\n  show ?case\n  proof(cases l2)\n    case Nil' : Nil\n    then show ?thesis using Cons.prems(3)[of \"l1hk\"] L1h\n      by auto\n  next\n    case Cons' : (Cons l2h l2t)\n\n    obtain l2hk l2hv where L2h : \"l2h = (l2hk, l2hv)\"\n      by(cases l2h; auto)\n\n    consider (1) \"l1hk < l2hk\" |\n             (2) \"l2hk < l1hk\" |\n             (3) \"l1hk = l2hk\"\n      using linorder_class.less_linear\n      by auto\n\n    then show ?thesis\n    proof cases\n      case 1\n\n      have L1hv : \"map_of (l1h # l1t) l1hk = Some l1hv\"\n        using L1h\n        by auto\n\n      hence L2v : \"map_of l2t l1hk = Some l1hv\"\n        using Cons.prems(3)[of l1hk] 1 L2h Cons' by auto\n\n      hence L2v' : \"l1hk \\<in> set (map fst l2t)\"\n        using imageI[OF map_of_SomeD[OF L2v], of fst]\n        by auto\n\n      then have False using strict_order_cons'[of l2hk \"map fst l2t\" \"l1hk\"] 1\n        Cons.prems(2) Cons' L2h\n        by auto\n\n      then show ?thesis\n        by auto\n    next\n      case 2\n\n      have L2hv : \"map_of l2 l2hk = Some l2hv\"\n        using L2h Cons'\n        by auto\n\n      hence L1v : \"map_of (l1h # l1t) l2hk = Some l2hv\"\n        using Cons.prems(3)[of l2hk]\n        by auto\n\n      hence L1v' : \"map_of l1t l2hk = Some l2hv\"\n        using 2 L1h\n        by(auto split: if_split_asm)\n\n      hence L1v'' : \"l2hk \\<in> set (map fst (l1t))\"\n        using imageI[OF map_of_SomeD[OF L1v'], of fst]\n        by auto\n\n      then have False using strict_order_cons'[of l1hk \"map fst (l1t)\" \"l2hk\"] 2\n        Cons.prems(1) Cons' L1h\n        by auto\n\n      then show ?thesis\n        by auto\n    next\n      case 3\n\n      have Ord1' : \"strict_order (map fst l1t)\"\n        using strict_order_tl Cons.prems(1) L1h\n        by auto\n\n      have Ord2' : \"strict_order (map fst l2t)\"\n        using strict_order_tl Cons.prems(2) L2h Cons'\n        by auto\n\n      have Ind_Arg : \" (\\<And>k. map_of l1t k = map_of l2t k)\"\n      proof-\n        fix k\n\n        show \"map_of l1t k = map_of l2t k\"\n        proof(cases \"k = l1hk\")\n          case True\n\n          have C1 : \"map_of l1t k = None\"\n          proof(cases \"map_of l1t k\")\n            case None\n            then show ?thesis by simp\n          next\n            case (Some bad)\n\n            have Bad1 :  \"(k, bad) \\<in> set l1t\"\n              using map_of_SomeD[OF Some] by simp\n\n            hence Bad2 : \"k \\<in> set (map fst l1t)\"\n              using imageI[OF Bad1, of fst]\n              by simp\n\n            then have False \n              using strict_order_cons'[of l1hk \"map fst l1t\", of k] Cons.prems(1) L1h True\n              by auto\n\n            thus ?thesis by auto\n          qed\n\n          have C2 : \"map_of l2t k = None\"\n          proof(cases \"map_of l2t k\")\n            case None\n            then show ?thesis by simp\n          next\n            case (Some bad)\n\n            have Bad1 :  \"(k, bad) \\<in> set l2t\"\n              using map_of_SomeD[OF Some] by simp\n\n            hence Bad2 : \"k \\<in> set (map fst l2t)\"\n              using imageI[OF Bad1, of fst]\n              by simp\n\n            then have False \n              using strict_order_cons'[of l2hk \"map fst l2t\", of k] Cons.prems(2) True 3 L2h Cons'\n              by auto\n\n            thus ?thesis by auto\n          qed\n\n          show \"map_of l1t k = map_of l2t k\"\n            using C1 C2\n            by auto\n        next\n          case False\n\n          then show \"map_of l1t k = map_of l2t k\"\n            using Cons.prems(3)[of k] 3 L2h L1h Cons'\n            by(simp)\n        qed\n      qed\n\n      have Vs : \"l1hv = l2hv\"\n        using Cons.prems(3)[of l1hk] 3 L1h L2h Cons'\n        by auto\n\n      show ?thesis \n        using Cons.IH[OF Ord1' Ord2' Ind_Arg] Cons.prems 3 L1h L2h Cons' Vs\n        by auto\n    qed\n  qed\nqed\n\nlemma oalist_eq2 :\n  assumes H : \"\\<And> k . get l1 k = get l2 k\"\n  shows \"l1 = l2\" using assms\nproof(transfer)\n  show \"\\<And>l1 l2.\n       strict_order (map fst l1) \\<Longrightarrow>\n       strict_order (map fst l2) \\<Longrightarrow>\n       (\\<And>k. map_of l1 k = map_of l2 k) \\<Longrightarrow> l1 = l2\"\n    using str_ord_eq2\n    by blast\nqed\n\nlemma oalist_get_eq :\n  shows \"(l1 = l2) = (\\<forall> k . get l1 k = get l2 k)\"\n  using oalist_eq2\n  by blast\n\nlemma alist_map_val_get :\n  shows\n  \"map_of (alist_map_val f l) k =\n      (case map_of l k of\n        None \\<Rightarrow> None\n        | Some v \\<Rightarrow> Some (f v))\"\nproof(induction l arbitrary: f k)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons lh lt)\n  then show ?case \n    by(auto)\nqed\n\nlemma oalist_map_val_get :\n  shows \"get (oalist_map_val f l) k =\n    (case get l k of\n      None \\<Rightarrow> None\n      | Some v \\<Rightarrow> Some (f v))\"\nproof(transfer)\n  fix f l k\n  show \"strict_order (map fst l) \\<Longrightarrow>\n        map_of (alist_map_val f l) k =\n        (case map_of l k of None \\<Rightarrow> None | Some v \\<Rightarrow> Some (f v))\"\n    using alist_map_val_get[of f l k]\n    by auto\nqed\n\nfun alist_somes :: \"('k :: linorder * 'v option) list \\<Rightarrow> ('k * 'v) list\"\n  where\n\"alist_somes [] = []\"\n| \"alist_somes ((hk, None)#t) = alist_somes t\"\n| \"alist_somes ((hk, Some hv)#t) = (hk, hv) # alist_somes t\"\n\n(* TODO: implement alist_fuse... *)\n\nlift_definition oalist_eq :: \"('k :: linorder, 'v) oalist \\<Rightarrow> ('k, 'v) oalist \\<Rightarrow> bool\"\nis \"\\<lambda> x y . x = y\"\n  .\n\ninstantiation oalist :: (linorder, _) equal\nbegin\ndefinition eq_oalist :\n\"(HOL.equal l1 l2) = (oalist_eq l1 l2)\"\ninstance proof\n  fix x y :: \"('a, 'b) oalist\"\n  show \"equal_class.equal x y = (x = y)\"\n    unfolding eq_oalist\n    by(transfer; auto)\nqed\nend\n\n\n\nend", "meta": {"author": "mmalvarez", "repo": "Gazelle", "sha": "0a80144107b3ec7487725bd88d658843beb6cb82", "save_path": "github-repos/isabelle/mmalvarez-Gazelle", "path": "github-repos/isabelle/mmalvarez-Gazelle/Gazelle-0a80144107b3ec7487725bd88d658843beb6cb82/Lib/Oalist/Oalist.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380481, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7733947328482361}}
{"text": "(*  Title:      HOL/Hahn_Banach/Function_Order.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>An order on functions\\<close>\n\ntheory Function_Order\nimports Subspace Linearform\nbegin\n\nsubsection \\<open>The graph of a function\\<close>\n\ntext \\<open>\n  We define the \\emph{graph} of a (real) function @{text f} with\n  domain @{text F} as the set\n  \\begin{center}\n  @{text \"{(x, f x). x \\<in> F}\"}\n  \\end{center}\n  So we are modeling partial functions by specifying the domain and\n  the mapping function. We use the term ``function'' also for its\n  graph.\n\\<close>\n\ntype_synonym 'a graph = \"('a \\<times> real) set\"\n\ndefinition graph :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> 'a graph\"\n  where \"graph F f = {(x, f x) | x. x \\<in> F}\"\n\nlemma graphI [intro]: \"x \\<in> F \\<Longrightarrow> (x, f x) \\<in> graph F f\"\n  unfolding graph_def by blast\n\nlemma graphI2 [intro?]: \"x \\<in> F \\<Longrightarrow> \\<exists>t \\<in> graph F f. t = (x, f x)\"\n  unfolding graph_def by blast\n\nlemma graphE [elim?]:\n  assumes \"(x, y) \\<in> graph F f\"\n  obtains \"x \\<in> F\" and \"y = f x\"\n  using assms unfolding graph_def by blast\n\n\nsubsection \\<open>Functions ordered by domain extension\\<close>\n\ntext \\<open>\n  A function @{text h'} is an extension of @{text h}, iff the graph of\n  @{text h} is a subset of the graph of @{text h'}.\n\\<close>\n\nlemma graph_extI:\n  \"(\\<And>x. x \\<in> H \\<Longrightarrow> h x = h' x) \\<Longrightarrow> H \\<subseteq> H'\n    \\<Longrightarrow> graph H h \\<subseteq> graph H' h'\"\n  unfolding graph_def by blast\n\nlemma graph_extD1 [dest?]: \"graph H h \\<subseteq> graph H' h' \\<Longrightarrow> x \\<in> H \\<Longrightarrow> h x = h' x\"\n  unfolding graph_def by blast\n\nlemma graph_extD2 [dest?]: \"graph H h \\<subseteq> graph H' h' \\<Longrightarrow> H \\<subseteq> H'\"\n  unfolding graph_def by blast\n\n\nsubsection \\<open>Domain and function of a graph\\<close>\n\ntext \\<open>\n  The inverse functions to @{text graph} are @{text domain} and @{text\n  funct}.\n\\<close>\n\ndefinition domain :: \"'a graph \\<Rightarrow> 'a set\"\n  where \"domain g = {x. \\<exists>y. (x, y) \\<in> g}\"\n\ndefinition funct :: \"'a graph \\<Rightarrow> ('a \\<Rightarrow> real)\"\n  where \"funct g = (\\<lambda>x. (SOME y. (x, y) \\<in> g))\"\n\ntext \\<open>\n  The following lemma states that @{text g} is the graph of a function\n  if the relation induced by @{text g} is unique.\n\\<close>\n\nlemma graph_domain_funct:\n  assumes uniq: \"\\<And>x y z. (x, y) \\<in> g \\<Longrightarrow> (x, z) \\<in> g \\<Longrightarrow> z = y\"\n  shows \"graph (domain g) (funct g) = g\"\n  unfolding domain_def funct_def graph_def\nproof auto  (* FIXME !? *)\n  fix a b assume g: \"(a, b) \\<in> g\"\n  from g show \"(a, SOME y. (a, y) \\<in> g) \\<in> g\" by (rule someI2)\n  from g show \"\\<exists>y. (a, y) \\<in> g\" ..\n  from g show \"b = (SOME y. (a, y) \\<in> g)\"\n  proof (rule some_equality [symmetric])\n    fix y assume \"(a, y) \\<in> g\"\n    with g show \"y = b\" by (rule uniq)\n  qed\nqed\n\n\nsubsection \\<open>Norm-preserving extensions of a function\\<close>\n\ntext \\<open>\n  Given a linear form @{text f} on the space @{text F} and a seminorm\n  @{text p} on @{text E}. The set of all linear extensions of @{text\n  f}, to superspaces @{text H} of @{text F}, which are bounded by\n  @{text p}, is defined as follows.\n\\<close>\n\ndefinition\n  norm_pres_extensions ::\n    \"'a::{plus,minus,uminus,zero} set \\<Rightarrow> ('a \\<Rightarrow> real) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<Rightarrow> real)\n      \\<Rightarrow> 'a graph set\"\nwhere\n  \"norm_pres_extensions E p F f\n    = {g. \\<exists>H h. g = graph H h\n        \\<and> linearform H h\n        \\<and> H \\<unlhd> E\n        \\<and> F \\<unlhd> H\n        \\<and> graph F f \\<subseteq> graph H h\n        \\<and> (\\<forall>x \\<in> H. h x \\<le> p x)}\"\n\nlemma norm_pres_extensionE [elim]:\n  assumes \"g \\<in> norm_pres_extensions E p F f\"\n  obtains H h\n    where \"g = graph H h\"\n    and \"linearform H h\"\n    and \"H \\<unlhd> E\"\n    and \"F \\<unlhd> H\"\n    and \"graph F f \\<subseteq> graph H h\"\n    and \"\\<forall>x \\<in> H. h x \\<le> p x\"\n  using assms unfolding norm_pres_extensions_def by blast\n\nlemma norm_pres_extensionI2 [intro]:\n  \"linearform H h \\<Longrightarrow> H \\<unlhd> E \\<Longrightarrow> F \\<unlhd> H\n    \\<Longrightarrow> graph F f \\<subseteq> graph H h \\<Longrightarrow> \\<forall>x \\<in> H. h x \\<le> p x\n    \\<Longrightarrow> graph H h \\<in> norm_pres_extensions E p F f\"\n  unfolding norm_pres_extensions_def by blast\n\nlemma norm_pres_extensionI:  (* FIXME ? *)\n  \"\\<exists>H h. g = graph H h\n    \\<and> linearform H h\n    \\<and> H \\<unlhd> E\n    \\<and> F \\<unlhd> H\n    \\<and> graph F f \\<subseteq> graph H h\n    \\<and> (\\<forall>x \\<in> H. h x \\<le> p x) \\<Longrightarrow> g \\<in> norm_pres_extensions E p F f\"\n  unfolding norm_pres_extensions_def by blast\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Hahn_Banach/Function_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.8670357683915538, "lm_q1q2_score": 0.773232082520705}}
{"text": "(* EXTRACT from HOL/ex/Primes.thy*)\n\n(*Euclid's algorithm \n  This material now appears AFTER that of Forward.thy *)\ntheory TPrimes imports Main begin\n\nfun gcd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"gcd m n = (if n=0 then m else gcd n (m mod n))\"\n\n\ntext {*Now in Basic.thy!\n@{thm[display]\"dvd_def\"}\n\\rulename{dvd_def}\n*}\n\n\n(*** Euclid's Algorithm ***)\n\nlemma gcd_0 [simp]: \"gcd m 0 = m\"\napply (simp)\ndone\n\nlemma gcd_non_0 [simp]: \"0<n \\<Longrightarrow> gcd m n = gcd n (m mod n)\"\napply (simp)\ndone\n\ndeclare gcd.simps [simp del]\n\n(*gcd(m,n) divides m and n.  The conjunctions don't seem provable separately*)\nlemma gcd_dvd_both: \"(gcd m n dvd m) \\<and> (gcd m n dvd n)\"\napply (induct_tac m n rule: gcd.induct)\n  --{* @{subgoals[display,indent=0,margin=65]} *}\napply (case_tac \"n=0\")\ntxt{*subgoals after the case tac\n@{subgoals[display,indent=0,margin=65]}\n*}\napply (simp_all) \n  --{* @{subgoals[display,indent=0,margin=65]} *}\nby (blast dest: dvd_mod_imp_dvd)\n\n\n\ntext {*\n@{thm[display] dvd_mod_imp_dvd}\n\\rulename{dvd_mod_imp_dvd}\n\n@{thm[display] dvd_trans}\n\\rulename{dvd_trans}\n*}\n\nlemmas gcd_dvd1 [iff] = gcd_dvd_both [THEN conjunct1]\nlemmas gcd_dvd2 [iff] = gcd_dvd_both [THEN conjunct2]\n\n\ntext {*\n\\begin{quote}\n@{thm[display] gcd_dvd1}\n\\rulename{gcd_dvd1}\n\n@{thm[display] gcd_dvd2}\n\\rulename{gcd_dvd2}\n\\end{quote}\n*}\n\n(*Maximality: for all m,n,k naturals, \n                if k divides m and k divides n then k divides gcd(m,n)*)\nlemma gcd_greatest [rule_format]:\n      \"k dvd m \\<longrightarrow> k dvd n \\<longrightarrow> k dvd gcd m n\"\napply (induct_tac m n rule: gcd.induct)\napply (case_tac \"n=0\")\ntxt{*subgoals after the case tac\n@{subgoals[display,indent=0,margin=65]}\n*}\napply (simp_all add: dvd_mod)\ndone\n\ntext {*\n@{thm[display] dvd_mod}\n\\rulename{dvd_mod}\n*}\n\n(*just checking the claim that case_tac \"n\" works too*)\nlemma \"k dvd m \\<longrightarrow> k dvd n \\<longrightarrow> k dvd gcd m n\"\napply (induct_tac m n rule: gcd.induct)\napply (case_tac \"n\")\napply (simp_all add: dvd_mod)\ndone\n\n\ntheorem gcd_greatest_iff [iff]: \n        \"(k dvd gcd m n) = (k dvd m \\<and> k dvd n)\"\nby (blast intro!: gcd_greatest intro: dvd_trans)\n\n\n(**** The material below was omitted from the book ****)\n\ndefinition is_gcd :: \"[nat,nat,nat] \\<Rightarrow> bool\" where        (*gcd as a relation*)\n    \"is_gcd p m n == p dvd m  \\<and>  p dvd n  \\<and>\n                     (ALL d. d dvd m \\<and> d dvd n \\<longrightarrow> d dvd p)\"\n\n(*Function gcd yields the Greatest Common Divisor*)\nlemma is_gcd: \"is_gcd (gcd m n) m n\"\napply (simp add: is_gcd_def gcd_greatest)\ndone\n\n(*uniqueness of GCDs*)\nlemma is_gcd_unique: \"\\<lbrakk> is_gcd m a b; is_gcd n a b \\<rbrakk> \\<Longrightarrow> m=n\"\napply (simp add: is_gcd_def)\napply (blast intro: dvd_antisym)\ndone\n\n\ntext {*\n@{thm[display] dvd_antisym}\n\\rulename{dvd_antisym}\n\n\\begin{isabelle}\nproof\\ (prove):\\ step\\ 1\\isanewline\n\\isanewline\ngoal\\ (lemma\\ is_gcd_unique):\\isanewline\n\\isasymlbrakk is_gcd\\ m\\ a\\ b;\\ is_gcd\\ n\\ a\\ b\\isasymrbrakk \\ \\isasymLongrightarrow \\ m\\ =\\ n\\isanewline\n\\ 1.\\ \\isasymlbrakk m\\ dvd\\ a\\ \\isasymand \\ m\\ dvd\\ b\\ \\isasymand \\ (\\isasymforall d.\\ d\\ dvd\\ a\\ \\isasymand \\ d\\ dvd\\ b\\ \\isasymlongrightarrow \\ d\\ dvd\\ m);\\isanewline\n\\ \\ \\ \\ \\ \\ \\ n\\ dvd\\ a\\ \\isasymand \\ n\\ dvd\\ b\\ \\isasymand \\ (\\isasymforall d.\\ d\\ dvd\\ a\\ \\isasymand \\ d\\ dvd\\ b\\ \\isasymlongrightarrow \\ d\\ dvd\\ n)\\isasymrbrakk \\isanewline\n\\ \\ \\ \\ \\isasymLongrightarrow \\ m\\ =\\ n\n\\end{isabelle}\n*}\n\nlemma gcd_assoc: \"gcd (gcd k m) n = gcd k (gcd m n)\"\n  apply (rule is_gcd_unique)\n  apply (rule is_gcd)\n  apply (simp add: is_gcd_def)\n  apply (blast intro: dvd_trans)\n  done\n\ntext{*\n\\begin{isabelle}\nproof\\ (prove):\\ step\\ 3\\isanewline\n\\isanewline\ngoal\\ (lemma\\ gcd_assoc):\\isanewline\ngcd\\ (gcd\\ (k,\\ m),\\ n)\\ =\\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\isanewline\n\\ 1.\\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\ dvd\\ k\\ \\isasymand \\isanewline\n\\ \\ \\ \\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\ dvd\\ m\\ \\isasymand \\ gcd\\ (k,\\ gcd\\ (m,\\ n))\\ dvd\\ n\n\\end{isabelle}\n*}\n\n\nlemma gcd_dvd_gcd_mult: \"gcd m n dvd gcd (k*m) n\"\n  apply (auto intro: dvd_trans [of _ m])\n  done\n\n(*This is half of the proof (by dvd_antisym) of*)\nlemma gcd_mult_cancel: \"gcd k n = 1 \\<Longrightarrow> gcd (k*m) n = gcd m n\"\n  oops\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/Rules/TPrimes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8670357512127872, "lm_q1q2_score": 0.7732320597211364}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Function \\textit{isin} for Tree2\\<close>\n\ntheory Isin2\nimports\n  Tree2\n  Cmp\n  Set_Specs\nbegin\n\nfun isin :: \"('a::linorder*'b) tree \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"isin Leaf x = False\" |\n\"isin (Node l (a,_) r) x =\n  (case cmp x a of\n     LT \\<Rightarrow> isin l x |\n     EQ \\<Rightarrow> True |\n     GT \\<Rightarrow> isin r x)\"\n\nlemma isin_set_inorder: \"sorted(inorder t) \\<Longrightarrow> isin t x = (x \\<in> set(inorder t))\"\nby (induction t rule: tree2_induct) (auto simp: isin_simps)\n\nlemma isin_set_tree: \"bst t \\<Longrightarrow> isin t x \\<longleftrightarrow> x \\<in> set_tree t\"\nby(induction t rule: tree2_induct) auto\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/Isin2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7730853851263956}}
{"text": "(*  Title:      HOL/Number_Theory/Residues.thy\n    Author:     Jeremy Avigad\n\nAn algebraic treatment of residue rings, and resulting proofs of\nEuler's theorem and Wilson's theorem.\n*)\n\nsection \\<open>Residue rings\\<close>\n\ntheory Residues\nimports\n  Cong\n  \"HOL-Algebra.Multiplicative_Group\"\n  Totient\nbegin\n\ndefinition QuadRes :: \"int \\<Rightarrow> int \\<Rightarrow> bool\"\n  where \"QuadRes p a = (\\<exists>y. ([y^2 = a] (mod p)))\"\n\ndefinition Legendre :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  where \"Legendre a p =\n    (if ([a = 0] (mod p)) then 0\n     else if QuadRes p a then 1\n     else -1)\"\n\n\nsubsection \\<open>A locale for residue rings\\<close>\n\ndefinition residue_ring :: \"int \\<Rightarrow> int ring\"\n  where\n    \"residue_ring m =\n      \\<lparr>carrier = {0..m - 1},\n       monoid.mult = \\<lambda>x y. (x * y) mod m,\n       one = 1,\n       zero = 0,\n       add = \\<lambda>x y. (x + y) mod m\\<rparr>\"\n\nlocale residues =\n  fixes m :: int and R (structure)\n  assumes m_gt_one: \"m > 1\"\n  defines R_m_def: \"R \\<equiv> residue_ring m\"\nbegin\n\nlemma abelian_group: \"abelian_group R\"\nproof -\n  have \"\\<exists>y\\<in>{0..m - 1}. (x + y) mod m = 0\" if \"0 \\<le> x\" \"x < m\" for x\n  proof (cases \"x = 0\")\n    case True\n    with m_gt_one show ?thesis by simp\n  next\n    case False\n    then have \"(x + (m - x)) mod m = 0\"\n      by simp\n    with m_gt_one that show ?thesis\n      by (metis False atLeastAtMost_iff diff_ge_0_iff_ge diff_left_mono int_one_le_iff_zero_less less_le)\n  qed\n  with m_gt_one show ?thesis\n    by (fastforce simp add: R_m_def residue_ring_def mod_add_right_eq ac_simps  intro!: abelian_groupI)\nqed\n\nlemma comm_monoid: \"comm_monoid R\"\n  unfolding R_m_def residue_ring_def\n  apply (rule comm_monoidI)\n    using m_gt_one  apply auto\n  apply (metis mod_mult_right_eq mult.assoc mult.commute)\n  apply (metis mult.commute)\n  done\n\nlemma cring: \"cring R\"\n  apply (intro cringI abelian_group comm_monoid)\n  unfolding R_m_def residue_ring_def\n  apply (auto simp add: comm_semiring_class.distrib mod_add_eq mod_mult_left_eq)\n  done\n\nend\n\nsublocale residues < cring\n  by (rule cring)\n\n\ncontext residues\nbegin\n\ntext \\<open>\n  These lemmas translate back and forth between internal and\n  external concepts.\n\\<close>\n\nlemma res_carrier_eq: \"carrier R = {0..m - 1}\"\n  by (auto simp: R_m_def residue_ring_def)\n\nlemma res_add_eq: \"x \\<oplus> y = (x + y) mod m\"\n  by (auto simp: R_m_def residue_ring_def)\n\nlemma res_mult_eq: \"x \\<otimes> y = (x * y) mod m\"\n  by (auto simp: R_m_def residue_ring_def)\n\nlemma res_zero_eq: \"\\<zero> = 0\"\n  by (auto simp: R_m_def residue_ring_def)\n\nlemma res_one_eq: \"\\<one> = 1\"\n  by (auto simp: R_m_def residue_ring_def units_of_def)\n\nlemma res_units_eq: \"Units R = {x. 0 < x \\<and> x < m \\<and> coprime x m}\"\n  using m_gt_one\n  apply (auto simp add: Units_def R_m_def residue_ring_def ac_simps invertible_coprime intro: ccontr)\n  apply (subst (asm) coprime_iff_invertible'_int)\n   apply (auto simp add: cong_def)\n  done\n\nlemma res_neg_eq: \"\\<ominus> x = (- x) mod m\"\n  using m_gt_one unfolding R_m_def a_inv_def m_inv_def residue_ring_def\n  apply simp\n  apply (rule the_equality)\n   apply (simp add: mod_add_right_eq)\n   apply (simp add: add.commute mod_add_right_eq)\n  apply (metis add.right_neutral minus_add_cancel mod_add_right_eq mod_pos_pos_trivial)\n  done\n\nlemma finite [iff]: \"finite (carrier R)\"\n  by (simp add: res_carrier_eq)\n\nlemma finite_Units [iff]: \"finite (Units R)\"\n  by (simp add: finite_ring_finite_units)\n\ntext \\<open>\n  The function \\<open>a \\<mapsto> a mod m\\<close> maps the integers to the\n  residue classes. The following lemmas show that this mapping\n  respects addition and multiplication on the integers.\n\\<close>\n\nlemma mod_in_carrier [iff]: \"a mod m \\<in> carrier R\"\n  unfolding res_carrier_eq\n  using insert m_gt_one by auto\n\nlemma add_cong: \"(x mod m) \\<oplus> (y mod m) = (x + y) mod m\"\n  by (auto simp: R_m_def residue_ring_def mod_simps)\n\nlemma mult_cong: \"(x mod m) \\<otimes> (y mod m) = (x * y) mod m\"\n  by (auto simp: R_m_def residue_ring_def mod_simps)\n\nlemma zero_cong: \"\\<zero> = 0\"\n  by (auto simp: R_m_def residue_ring_def)\n\nlemma one_cong: \"\\<one> = 1 mod m\"\n  using m_gt_one by (auto simp: R_m_def residue_ring_def)\n\n(* FIXME revise algebra library to use 1? *)\nlemma pow_cong: \"(x mod m) [^] n = x^n mod m\"\n  using m_gt_one\n  apply (induct n)\n  apply (auto simp add: nat_pow_def one_cong)\n  apply (metis mult.commute mult_cong)\n  done\n\nlemma neg_cong: \"\\<ominus> (x mod m) = (- x) mod m\"\n  by (metis mod_minus_eq res_neg_eq)\n\nlemma (in residues) prod_cong: \"finite A \\<Longrightarrow> (\\<Otimes>i\\<in>A. (f i) mod m) = (\\<Prod>i\\<in>A. f i) mod m\"\n  by (induct set: finite) (auto simp: one_cong mult_cong)\n\nlemma (in residues) sum_cong: \"finite A \\<Longrightarrow> (\\<Oplus>i\\<in>A. (f i) mod m) = (\\<Sum>i\\<in>A. f i) mod m\"\n  by (induct set: finite) (auto simp: zero_cong add_cong)\n\nlemma mod_in_res_units [simp]:\n  assumes \"1 < m\" and \"coprime a m\"\n  shows \"a mod m \\<in> Units R\"\nproof (cases \"a mod m = 0\")\n  case True\n  with assms show ?thesis\n    by (auto simp add: res_units_eq gcd_red_int [symmetric])\nnext\n  case False\n  from assms have \"0 < m\" by simp\n  then have \"0 \\<le> a mod m\" by (rule pos_mod_sign [of m a])\n  with False have \"0 < a mod m\" by simp\n  with assms show ?thesis\n    by (auto simp add: res_units_eq gcd_red_int [symmetric] ac_simps)\nqed\n\nlemma res_eq_to_cong: \"(a mod m) = (b mod m) \\<longleftrightarrow> [a = b] (mod m)\"\n  by (auto simp: cong_def)\n\n\ntext \\<open>Simplifying with these will translate a ring equation in R to a congruence.\\<close>\nlemmas res_to_cong_simps =\n  add_cong mult_cong pow_cong one_cong\n  prod_cong sum_cong neg_cong res_eq_to_cong\n\ntext \\<open>Other useful facts about the residue ring.\\<close>\nlemma one_eq_neg_one: \"\\<one> = \\<ominus> \\<one> \\<Longrightarrow> m = 2\"\n  apply (simp add: res_one_eq res_neg_eq)\n  apply (metis add.commute add_diff_cancel mod_mod_trivial one_add_one uminus_add_conv_diff\n    zero_neq_one zmod_zminus1_eq_if)\n  done\n\nend\n\n\nsubsection \\<open>Prime residues\\<close>\n\nlocale residues_prime =\n  fixes p :: nat and R (structure)\n  assumes p_prime [intro]: \"prime p\"\n  defines \"R \\<equiv> residue_ring (int p)\"\n\nsublocale residues_prime < residues p\n  unfolding R_def residues_def\n  using p_prime apply auto\n  apply (metis (full_types) of_nat_1 of_nat_less_iff prime_gt_1_nat)\n  done\n\ncontext residues_prime\nbegin\n\nlemma p_coprime_left:\n  \"coprime p a \\<longleftrightarrow> \\<not> p dvd a\"\n  using p_prime by (auto intro: prime_imp_coprime dest: coprime_common_divisor)\n\nlemma p_coprime_right:\n  \"coprime a p  \\<longleftrightarrow> \\<not> p dvd a\"\n  using p_coprime_left [of a] by (simp add: ac_simps)\n\nlemma p_coprime_left_int:\n  \"coprime (int p) a \\<longleftrightarrow> \\<not> int p dvd a\"\n  using p_prime by (auto intro: prime_imp_coprime dest: coprime_common_divisor)\n\nlemma p_coprime_right_int:\n  \"coprime a (int p) \\<longleftrightarrow> \\<not> int p dvd a\"\n  using p_coprime_left_int [of a] by (simp add: ac_simps)\n\nlemma is_field: \"field R\"\nproof -\n  have \"0 < x \\<Longrightarrow> x < int p \\<Longrightarrow> coprime (int p) x\" for x\n    by (rule prime_imp_coprime) (auto simp add: zdvd_not_zless)\n  then show ?thesis\n    by (intro cring.field_intro2 cring)\n      (auto simp add: res_carrier_eq res_one_eq res_zero_eq res_units_eq ac_simps)\nqed\n\nlemma res_prime_units_eq: \"Units R = {1..p - 1}\"\n  apply (subst res_units_eq)\n  apply (auto simp add: p_coprime_right_int zdvd_not_zless)\n  done\n\nend\n\nsublocale residues_prime < field\n  by (rule is_field)\n\n\nsection \\<open>Test cases: Euler's theorem and Wilson's theorem\\<close>\n\nsubsection \\<open>Euler's theorem\\<close>\n\nlemma (in residues) totatives_eq:\n  \"totatives (nat m) = nat ` Units R\"\nproof -\n  from m_gt_one have \"\\<bar>m\\<bar> > 1\"\n    by simp\n  then have \"totatives (nat \\<bar>m\\<bar>) = nat ` abs ` Units R\"\n    by (auto simp add: totatives_def res_units_eq image_iff le_less)\n      (use m_gt_one zless_nat_eq_int_zless in force)\n  moreover have \"\\<bar>m\\<bar> = m\" \"abs ` Units R = Units R\"\n    using m_gt_one by (auto simp add: res_units_eq image_iff)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma (in residues) totient_eq:\n  \"totient (nat m) = card (Units R)\"\nproof  -\n  have *: \"inj_on nat (Units R)\"\n    by (rule inj_onI) (auto simp add: res_units_eq)\n  then show ?thesis\n    by (simp add: totient_def totatives_eq card_image)\nqed\n\nlemma (in residues_prime) prime_totient_eq: \"totient p = p - 1\"\n  using totient_eq by (simp add: res_prime_units_eq)\n\nlemma (in residues) euler_theorem:\n  assumes \"coprime a m\"\n  shows \"[a ^ totient (nat m) = 1] (mod m)\"\nproof -\n  have \"a ^ totient (nat m) mod m = 1 mod m\"\n    by (metis assms finite_Units m_gt_one mod_in_res_units one_cong totient_eq pow_cong units_power_order_eq_one)\n  then show ?thesis\n    using res_eq_to_cong by blast\nqed\n\nlemma euler_theorem:\n  fixes a m :: nat\n  assumes \"coprime a m\"\n  shows \"[a ^ totient m = 1] (mod m)\"\nproof (cases \"m = 0 \\<or> m = 1\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  with assms show ?thesis\n    using residues.euler_theorem [of \"int m\" \"int a\"] cong_int_iff\n    by (auto simp add: residues_def gcd_int_def) fastforce\nqed\n\nlemma fermat_theorem:\n  fixes p a :: nat\n  assumes \"prime p\" and \"\\<not> p dvd a\"\n  shows \"[a ^ (p - 1) = 1] (mod p)\"\nproof -\n  from assms prime_imp_coprime [of p a] have \"coprime a p\"\n    by (auto simp add: ac_simps)\n  then have \"[a ^ totient p = 1] (mod p)\"\n     by (rule euler_theorem)\n  also have \"totient p = p - 1\"\n    by (rule totient_prime) (rule assms)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Wilson's theorem\\<close>\n\nlemma (in field) inv_pair_lemma: \"x \\<in> Units R \\<Longrightarrow> y \\<in> Units R \\<Longrightarrow>\n    {x, inv x} \\<noteq> {y, inv y} \\<Longrightarrow> {x, inv x} \\<inter> {y, inv y} = {}\"\n  apply auto\n  apply (metis Units_inv_inv)+\n  done\n\nlemma (in residues_prime) wilson_theorem1:\n  assumes a: \"p > 2\"\n  shows \"[fact (p - 1) = (-1::int)] (mod p)\"\nproof -\n  let ?Inverse_Pairs = \"{{x, inv x}| x. x \\<in> Units R - {\\<one>, \\<ominus> \\<one>}}\"\n  have UR: \"Units R = {\\<one>, \\<ominus> \\<one>} \\<union> \\<Union>?Inverse_Pairs\"\n    by auto\n  have \"(\\<Otimes>i\\<in>Units R. i) = (\\<Otimes>i\\<in>{\\<one>, \\<ominus> \\<one>}. i) \\<otimes> (\\<Otimes>i\\<in>\\<Union>?Inverse_Pairs. i)\"\n    apply (subst UR)\n    apply (subst finprod_Un_disjoint)\n         apply (auto intro: funcsetI)\n    using inv_one apply auto[1]\n    using inv_eq_neg_one_eq apply auto\n    done\n  also have \"(\\<Otimes>i\\<in>{\\<one>, \\<ominus> \\<one>}. i) = \\<ominus> \\<one>\"\n    apply (subst finprod_insert)\n        apply auto\n    apply (frule one_eq_neg_one)\n    using a apply force\n    done\n  also have \"(\\<Otimes>i\\<in>(\\<Union>?Inverse_Pairs). i) = (\\<Otimes>A\\<in>?Inverse_Pairs. (\\<Otimes>y\\<in>A. y))\"\n    apply (subst finprod_Union_disjoint)\n       apply (auto simp: pairwise_def disjnt_def)\n     apply (metis Units_inv_inv)+\n    done\n  also have \"\\<dots> = \\<one>\"\n    apply (rule finprod_one_eqI)\n     apply auto\n    apply (subst finprod_insert)\n        apply auto\n    apply (metis inv_eq_self)\n    done\n  finally have \"(\\<Otimes>i\\<in>Units R. i) = \\<ominus> \\<one>\"\n    by simp\n  also have \"(\\<Otimes>i\\<in>Units R. i) = (\\<Otimes>i\\<in>Units R. i mod p)\"\n    by (rule finprod_cong') (auto simp: res_units_eq)\n  also have \"\\<dots> = (\\<Prod>i\\<in>Units R. i) mod p\"\n    by (rule prod_cong) auto\n  also have \"\\<dots> = fact (p - 1) mod p\"\n    apply (simp add: fact_prod)\n    using assms\n    apply (subst res_prime_units_eq)\n    apply (simp add: int_prod zmod_int prod_int_eq)\n    done\n  finally have \"fact (p - 1) mod p = \\<ominus> \\<one>\" .\n  then show ?thesis\n    by (simp add: cong_def res_neg_eq res_one_eq zmod_int)\nqed\n\nlemma wilson_theorem:\n  assumes \"prime p\"\n  shows \"[fact (p - 1) = - 1] (mod p)\"\nproof (cases \"p = 2\")\n  case True\n  then show ?thesis\n    by (simp add: cong_def fact_prod)\nnext\n  case False\n  then show ?thesis\n    using assms prime_ge_2_nat\n    by (metis residues_prime.wilson_theorem1 residues_prime.intro le_eq_less_or_eq)\nqed\n\ntext \\<open>\n  This result can be transferred to the multiplicative group of\n  \\<open>\\<int>/p\\<int>\\<close> for \\<open>p\\<close> prime.\\<close>\n\nlemma mod_nat_int_pow_eq:\n  fixes n :: nat and p a :: int\n  shows \"a \\<ge> 0 \\<Longrightarrow> p \\<ge> 0 \\<Longrightarrow> (nat a ^ n) mod (nat p) = nat ((a ^ n) mod p)\"\n  by (simp add: int_one_le_iff_zero_less nat_mod_distrib order_less_imp_le nat_power_eq[symmetric])\n\ntheorem residue_prime_mult_group_has_gen:\n fixes p :: nat\n assumes prime_p : \"prime p\"\n shows \"\\<exists>a \\<in> {1 .. p - 1}. {1 .. p - 1} = {a^i mod p|i . i \\<in> UNIV}\"\nproof -\n  have \"p \\<ge> 2\"\n    using prime_gt_1_nat[OF prime_p] by simp\n  interpret R: residues_prime p \"residue_ring p\"\n    by (simp add: residues_prime_def prime_p)\n  have car: \"carrier (residue_ring (int p)) - {\\<zero>\\<^bsub>residue_ring (int p)\\<^esub>} = {1 .. int p - 1}\"\n    by (auto simp add: R.zero_cong R.res_carrier_eq)\n\n  have \"x [^]\\<^bsub>residue_ring (int p)\\<^esub> i = x ^ i mod (int p)\"\n    if \"x \\<in> {1 .. int p - 1}\" for x and i :: nat\n    using that R.pow_cong[of x i] by auto\n  moreover\n  obtain a where a: \"a \\<in> {1 .. int p - 1}\"\n    and a_gen: \"{1 .. int p - 1} = {a[^]\\<^bsub>residue_ring (int p)\\<^esub>i|i::nat . i \\<in> UNIV}\"\n    using field.finite_field_mult_group_has_gen[OF R.is_field]\n    by (auto simp add: car[symmetric] carrier_mult_of)\n  moreover\n  have \"nat ` {1 .. int p - 1} = {1 .. p - 1}\" (is \"?L = ?R\")\n  proof\n    have \"n \\<in> ?R\" if \"n \\<in> ?L\" for n\n      using that \\<open>p\\<ge>2\\<close> by force\n    then show \"?L \\<subseteq> ?R\" by blast\n    have \"n \\<in> ?L\" if \"n \\<in> ?R\" for n\n      using that \\<open>p\\<ge>2\\<close> by (auto intro: rev_image_eqI [of \"int n\"])\n    then show \"?R \\<subseteq> ?L\" by blast\n  qed\n  moreover\n  have \"nat ` {a^i mod (int p) | i::nat. i \\<in> UNIV} = {nat a^i mod p | i . i \\<in> UNIV}\" (is \"?L = ?R\")\n  proof\n    have \"x \\<in> ?R\" if \"x \\<in> ?L\" for x\n    proof -\n      from that obtain i where i: \"x = nat (a^i mod (int p))\"\n        by blast\n      then have \"x = nat a ^ i mod p\"\n        using mod_nat_int_pow_eq[of a \"int p\" i] a \\<open>p\\<ge>2\\<close> by auto\n      with i show ?thesis by blast\n    qed\n    then show \"?L \\<subseteq> ?R\" by blast\n    have \"x \\<in> ?L\" if \"x \\<in> ?R\" for x\n    proof -\n      from that obtain i where i: \"x = nat a^i mod p\"\n        by blast\n      with mod_nat_int_pow_eq[of a \"int p\" i] a \\<open>p\\<ge>2\\<close> show ?thesis\n        by auto\n    qed\n    then show \"?R \\<subseteq> ?L\" by blast\n  qed\n  ultimately have \"{1 .. p - 1} = {nat a^i mod p | i. i \\<in> UNIV}\"\n    by presburger\n  moreover from a have \"nat a \\<in> {1 .. p - 1}\" by force\n  ultimately show ?thesis ..\nqed\n\n\nsubsection \\<open>Upper bound for the number of $n$-th roots\\<close>\n\nlemma roots_mod_prime_bound:\n  fixes n c p :: nat\n  assumes \"prime p\" \"n > 0\"\n  defines \"A \\<equiv> {x\\<in>{..<p}. [x ^ n = c] (mod p)}\"\n  shows   \"card A \\<le> n\"\nproof -\n  define R where \"R = residue_ring (int p)\"\n  from assms(1) interpret residues_prime p R\n    by unfold_locales (simp_all add: R_def)\n  interpret R: UP_domain R \"UP R\" by (unfold_locales)\n\n  let ?f = \"UnivPoly.monom (UP R) \\<one>\\<^bsub>R\\<^esub> n \\<ominus>\\<^bsub>(UP R)\\<^esub> UnivPoly.monom (UP R) (int (c mod p)) 0\"\n  have in_carrier: \"int (c mod p) \\<in> carrier R\"\n    using prime_gt_1_nat[OF assms(1)] by (simp add: R_def residue_ring_def)\n  \n  have \"deg R ?f = n\"\n    using assms in_carrier by (simp add: R.deg_minus_eq)\n  hence f_not_zero: \"?f \\<noteq> \\<zero>\\<^bsub>UP R\\<^esub>\" using assms by (auto simp add : R.deg_nzero_nzero)\n  have roots_bound: \"finite {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>} \\<and>\n                     card {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>} \\<le> deg R ?f\"\n                    using finite in_carrier by (intro R.roots_bound[OF _ f_not_zero]) simp\n  have subs: \"{x \\<in> carrier R. x [^]\\<^bsub>R\\<^esub> n = int (c mod p)} \\<subseteq>\n                {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>}\"\n    using in_carrier by (auto simp: R.evalRR_simps)\n  then have \"card {x \\<in> carrier R. x [^]\\<^bsub>R\\<^esub> n = int (c mod p)} \\<le>\n               card {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>}\"\n    using finite by (intro card_mono) auto\n  also have \"\\<dots> \\<le> n\"\n    using \\<open>deg R ?f = n\\<close> roots_bound by linarith\n  also {\n    fix x assume \"x \\<in> carrier R\"\n    hence \"x [^]\\<^bsub>R\\<^esub> n = (x ^ n) mod (int p)\"\n      by (subst pow_cong [symmetric]) (auto simp: R_def residue_ring_def)\n  }\n  hence \"{x \\<in> carrier R. x [^]\\<^bsub>R\\<^esub> n = int (c mod p)} = {x \\<in> carrier R. [x ^ n = int c] (mod p)}\"\n    by (fastforce simp: cong_def zmod_int)\n  also have \"bij_betw int A {x \\<in> carrier R. [x ^ n = int c] (mod p)}\"\n    by (rule bij_betwI[of int _ _ nat])\n       (use cong_int_iff in \\<open>force simp: R_def residue_ring_def A_def\\<close>)+\n  from bij_betw_same_card[OF this] have \"card {x \\<in> carrier R. [x ^ n = int c] (mod p)} = card A\" ..\n  finally show ?thesis .\nqed\n\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Number_Theory/Residues.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7730853833819703}}
{"text": "(*\n  File: Homotopy.thy\n  Author: Bohua Zhan\n\n  Definition of homotopy between two paths.\n*)\n\ntheory Homotopy\n  imports FOL_Topology.RealTopology\nbegin\n\nsection \\<open>Automation for intervals\\<close>\n  \nlemma closed_interval_memI:\n  \"is_ord_field(R) \\<Longrightarrow> a \\<le>\\<^sub>R x \\<Longrightarrow> x \\<le>\\<^sub>R b \\<Longrightarrow> x \\<in> closed_interval(R,a,b)\" by auto2\n\nlemma closed_interval_not_memI:\n  \"is_ord_field(R) \\<Longrightarrow> x <\\<^sub>R a \\<Longrightarrow> x \\<in> closed_interval(R,a,b) \\<Longrightarrow> False\"\n  \"is_ord_field(R) \\<Longrightarrow> b <\\<^sub>R x \\<Longrightarrow> x \\<in> closed_interval(R,a,b) \\<Longrightarrow> False\" by auto2+\n\nlemma closed_interval_subset [backward]:\n  \"is_ord_field(R) \\<Longrightarrow> c \\<le>\\<^sub>R a \\<Longrightarrow> b \\<le>\\<^sub>R d \\<Longrightarrow> closed_interval(R,a,b) \\<subseteq> closed_interval(R,c,d)\" by auto2  \n\nlemma closed_interval_plus:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow>\n   x +\\<^sub>R c \\<notin> closed_interval(R,a,b) \\<Longrightarrow> x \\<notin> closed_interval(R, a -\\<^sub>R c, b -\\<^sub>R c)\" by auto2\n\nlemma closed_interval_minus:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c \\<in>. R \\<Longrightarrow>\n   x -\\<^sub>R c \\<notin> closed_interval(R,a,b) \\<Longrightarrow> x \\<notin> closed_interval(R, a +\\<^sub>R c, b +\\<^sub>R c)\" by auto2\n\nlemma closed_interval_times:\n  \"is_ord_field(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> a \\<in>. R \\<Longrightarrow> b \\<in>. R \\<Longrightarrow> c >\\<^sub>R 0\\<^sub>R \\<Longrightarrow>\n   c *\\<^sub>R x \\<notin> closed_interval(R,a,b) \\<Longrightarrow> x \\<notin> closed_interval(R, a /\\<^sub>R c, b /\\<^sub>R c)\" by auto2\n\nML_file \"interval_steps.ML\"\n\nsection \\<open>Commonly used intervals\\<close>\n\ndefinition interval :: i   (\"I\") where [rewrite]:\n  \"interval = subspace(\\<real>, closed_interval(\\<real>,0\\<^sub>\\<real>,1\\<^sub>\\<real>))\"\n\nlemma interval_is_top [forward]: \"is_top_space(I)\" by auto2\nlemma interval_carrier [rewrite]: \"carrier(I) = closed_interval(\\<real>,0\\<^sub>\\<real>,1\\<^sub>\\<real>)\" by auto2\n\ndefinition interval_left :: i  (\"I1\") where [rewrite]:\n  \"I1 = subspace(\\<real>, closed_interval(\\<real>,0\\<^sub>\\<real>,1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real>))\"\n\ndefinition interval_right :: i  (\"I2\") where [rewrite]:\n  \"I2 = subspace(\\<real>, closed_interval(\\<real>,1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real>,1\\<^sub>\\<real>))\"\n\nlemma interval_left_type [typing]: \"I1 \\<in> raw_top_spaces(closed_interval(\\<real>,0\\<^sub>\\<real>,1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real>))\" by auto2\nlemma interval_right_type [typing]: \"I2 \\<in> raw_top_spaces(closed_interval(\\<real>,1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real>,1\\<^sub>\\<real>))\" by auto2\nlemma interval_left_is_top [forward]: \"is_top_space(I1)\" by auto2\nlemma interval_right_is_top [forward]: \"is_top_space(I2)\" by auto2\nlemma I1_subspace [rewrite]: \"I1 = subspace(I,carrier(I1)) \\<and> carrier(I1) \\<subseteq> carrier(I)\" by auto2\nlemma I2_subspace [rewrite]: \"I2 = subspace(I,carrier(I2)) \\<and> carrier(I2) \\<subseteq> carrier(I)\" by auto2\nsetup {* fold del_prfstep_thm [@{thm interval_left_def}, @{thm interval_right_def}] *}\n\nlemma real_topology_sub_closed_interval_closed [backward]:\n  \"a \\<in>. \\<real> \\<Longrightarrow> b \\<in>. \\<real> \\<Longrightarrow> c \\<in>. \\<real> \\<Longrightarrow> d \\<in>. \\<real> \\<Longrightarrow> A = closed_interval(\\<real>,a,b) \\<Longrightarrow>\n   B = closed_interval(\\<real>,c,d) \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> is_closed(subspace(\\<real>,A),B)\"\n@proof\n  @have \"is_closed(\\<real>,A)\" @have \"is_closed(\\<real>,B)\"\n@qed\n\nlemma I1_closed [resolve]: \"is_closed(I,carrier(I1))\" by auto2\nlemma I2_closed [resolve]: \"is_closed(I,carrier(I2))\" by auto2\n\nlemma restrict_real_fun [backward]:\n  \"B \\<subseteq> carrier(\\<real>) \\<Longrightarrow> B' = subspace(\\<real>,B) \\<Longrightarrow>\n   Mor(A,B',f) \\<in> A \\<rightharpoonup> B' \\<Longrightarrow> Mor(A,\\<real>,f) \\<in> A \\<rightharpoonup>\\<^sub>T \\<real> \\<Longrightarrow> continuous(Mor(A,B',f))\"\n@proof\n  @have (@rule) \"\\<forall>x\\<in>.A. Mor(A,B',f)`x = f(x)\"\n  @have \"Mor(A,B',f) = mor_restrict_image_top(Mor(A,\\<real>,f),B)\"\n@qed\n\ndefinition interval_inv :: i where [rewrite]:\n  \"interval_inv = Mor(I,I,\\<lambda>t. 1\\<^sub>\\<real> -\\<^sub>\\<real> t)\"\n\nlemma interval_inv_continuous [typing]: \"interval_inv \\<in> I \\<rightharpoonup>\\<^sub>T I\" by auto2\nlemma interval_inv_eval [rewrite]: \"t \\<in> source(interval_inv) \\<Longrightarrow> interval_inv`t = 1\\<^sub>\\<real> -\\<^sub>\\<real> t\" by auto2\nsetup {* del_prfstep_thm @{thm interval_inv_def} *}\n\ndefinition interval_lower :: i where [rewrite]:\n  \"interval_lower = Mor(I1,I,\\<lambda>t. 2\\<^sub>\\<real> *\\<^sub>\\<real> t)\"\n  \nlemma interval_lower_continuous [typing]: \"interval_lower \\<in> I1 \\<rightharpoonup>\\<^sub>T I\" by auto2\nlemma interval_lower_eval [rewrite]: \"t \\<in> source(interval_lower) \\<Longrightarrow> interval_lower`t = 2\\<^sub>\\<real> *\\<^sub>\\<real> t\" by auto2\nsetup {* del_prfstep_thm @{thm interval_lower_def} *}\n\ndefinition interval_upper :: i where [rewrite]:\n  \"interval_upper = Mor(I2,I,\\<lambda>t. 2\\<^sub>\\<real> *\\<^sub>\\<real> t -\\<^sub>\\<real> 1\\<^sub>\\<real>)\"\n  \nlemma interval_upper_continuous [typing]: \"interval_upper \\<in> I2 \\<rightharpoonup>\\<^sub>T I\" by auto2\nlemma interval_upper_eval [rewrite]: \"t \\<in> source(interval_upper) \\<Longrightarrow> interval_upper`t = 2\\<^sub>\\<real> *\\<^sub>\\<real> t -\\<^sub>\\<real> 1\\<^sub>\\<real>\" by auto2\nsetup {* del_prfstep_thm @{thm interval_upper_def} *}\n\nsetup {* del_prfstep_thm @{thm interval_def} *}\nsetup {* add_rewrite_rule_back @{thm interval_def} *}\n\nsection \\<open>Homotopy between two continuous functions from X to Y\\<close>\n\ndefinition is_homotopy :: \"[i, i, i] \\<Rightarrow> o\" where [rewrite]:\n  \"is_homotopy(f,g,F) \\<longleftrightarrow> (let S = source_str(f) in let T = target_str(f) in\n                           continuous(f) \\<and> continuous(g) \\<and> S = source_str(g) \\<and> T = target_str(g) \\<and>\n                           F \\<in> S \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T T \\<and> (\\<forall>x\\<in>.S. F`\\<langle>x,0\\<^sub>\\<real>\\<rangle> = f`x \\<and> F`\\<langle>x,1\\<^sub>\\<real>\\<rangle> = g`x))\"\nsetup {* register_wellform_data (\"is_homotopy(f,g,F)\",\n  [\"source_str(f) = source_str(g)\", \"target_str(f) = target_str(g)\"]) *}\n\nlemma is_homotopyD1 [rewrite]:\n  \"is_morphism_top(f) \\<Longrightarrow> \\<langle>x,0\\<^sub>\\<real>\\<rangle> \\<in> source(F) \\<Longrightarrow> is_homotopy(f,g,F) \\<Longrightarrow> F`\\<langle>x,0\\<^sub>\\<real>\\<rangle> = f`x\"\n  \"is_morphism_top(f) \\<Longrightarrow> \\<langle>x,1\\<^sub>\\<real>\\<rangle> \\<in> source(F) \\<Longrightarrow> is_homotopy(f,g,F) \\<Longrightarrow> F`\\<langle>x,1\\<^sub>\\<real>\\<rangle> = g`x\" by auto2+\n    \nlemma is_homotopyD2 [forward]:\n  \"is_homotopy(f,g,F) \\<Longrightarrow> continuous(f) \\<and> continuous(g) \\<and> source_str(f) = source_str(g) \\<and>\n                          target_str(f) = target_str(g) \\<and> F \\<in> source_str(f) \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(f)\" by auto2\n    \nlemma is_homotopyI [backward2]:\n  \"continuous(f) \\<Longrightarrow> continuous(g) \\<Longrightarrow> source_str(f) = source_str(g) \\<Longrightarrow> target_str(f) = target_str(g) \\<Longrightarrow>\n   F \\<in> source_str(f) \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(f) \\<Longrightarrow>\n   \\<forall>x\\<in>source(f). \\<langle>x,0\\<^sub>\\<real>\\<rangle> \\<in> source(F) \\<longrightarrow> F`\\<langle>x,0\\<^sub>\\<real>\\<rangle> = f`x \\<Longrightarrow>\n   \\<forall>x\\<in>source(f). \\<langle>x,1\\<^sub>\\<real>\\<rangle> \\<in> source(F) \\<longrightarrow> F`\\<langle>x,1\\<^sub>\\<real>\\<rangle> = g`x \\<Longrightarrow> is_homotopy(f,g,F)\" by auto2\nsetup {* del_prfstep_thm @{thm is_homotopy_def} *}\n\ndefinition homotopic :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"homotopic(f,g) \\<longleftrightarrow> (\\<exists>F. is_homotopy(f,g,F))\"\n\nlemma homotopicI [forward]:\n   \"is_homotopy(f,g,F) \\<Longrightarrow> homotopic(f,g)\" by auto2\n\nlemma homotopicE1 [forward]:\n  \"homotopic(f,g) \\<Longrightarrow> continuous(f) \\<and> continuous(g)\"\n  \"homotopic(f,g) \\<Longrightarrow> source_str(f) = source_str(g) \\<and> target_str(f) = target_str(g)\" by auto2+\n    \nlemma homotopicE2 [backward]:\n  \"homotopic(f,g) \\<Longrightarrow> \\<exists>F. is_homotopy(f,g,F)\" by auto2\nsetup {* del_prfstep_thm @{thm homotopic_def} *}\n\ndefinition id_homotopy :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"id_homotopy(f) = f \\<circ>\\<^sub>m proj1_top(source_str(f),I)\"\n\nlemma id_is_homotopy:\n  \"continuous(f) \\<Longrightarrow> is_homotopy(f,f,id_homotopy(f))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm id_is_homotopy} [with_term \"id_homotopy(?f)\"] *}\n\nlemma homotopic_id [resolve]:\n  \"continuous(f) \\<Longrightarrow> homotopic(f,f)\"\n@proof @have \"is_homotopy(f,f,id_homotopy(f))\" @qed\n\ndefinition inv_homotopy :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"inv_homotopy(f,g,F) = F \\<circ>\\<^sub>m prod_top_map(id_mor(source_str(f)),interval_inv)\"\nsetup {* register_wellform_data (\"inv_homotopy(f,g,F)\", [\"is_homotopy(f,g,F)\"]) *}\n\nlemma inv_homotopy_eval [rewrite]:\n  \"\\<langle>x,t\\<rangle> \\<in> source(inv_homotopy(f,g,F)) \\<Longrightarrow> is_homotopy(f,g,F) \\<Longrightarrow>\n   inv_homotopy(f,g,F)`\\<langle>x,t\\<rangle> = F`\\<langle>x, 1\\<^sub>\\<real> -\\<^sub>\\<real> t\\<rangle>\" by auto2\n\nlemma inv_is_homotopy:\n  \"is_homotopy(f,g,F) \\<Longrightarrow> is_homotopy(g,f,inv_homotopy(f,g,F))\"\n@proof @have \"inv_homotopy(f,g,F) \\<in> source_str(f) \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(f)\" @qed\nsetup {* add_forward_prfstep_cond @{thm inv_is_homotopy} [with_term \"inv_homotopy(?f,?g,?F)\"] *}\nsetup {* del_prfstep_thm @{thm inv_homotopy_def} *}\n\nlemma homotopic_inv [resolve]:\n  \"homotopic(f,g) \\<Longrightarrow> homotopic(g,f)\"\n@proof\n  @obtain F where \"is_homotopy(f,g,F)\"\n  @have \"is_homotopy(g,f,inv_homotopy(f,g,F))\"\n@qed\n\ndefinition homotopy_lower_half :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"homotopy_lower_half(X,F) = F \\<circ>\\<^sub>m prod_top_map(id_mor(X),interval_lower)\"\nsetup {* register_wellform_data (\"homotopy_lower_half(X,F)\", [\"F \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(F)\"]) *}\n\nlemma homotopy_lower_half_type [typing]:\n  \"is_top_space(X) \\<Longrightarrow> F \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(F) \\<Longrightarrow>\n   homotopy_lower_half(X,F) \\<in> X \\<times>\\<^sub>T I1 \\<rightharpoonup>\\<^sub>T target_str(F)\" by auto2\n      \nlemma homotopy_lower_half_eval [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> \\<langle>x,t\\<rangle> \\<in> source(F') \\<Longrightarrow> F \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(F) \\<Longrightarrow>\n   F' = homotopy_lower_half(X,F) \\<Longrightarrow> F'`\\<langle>x,t\\<rangle> = F`\\<langle>x, 2\\<^sub>\\<real> *\\<^sub>\\<real> t\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm homotopy_lower_half_def} *}\n  \ndefinition homotopy_upper_half :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"homotopy_upper_half(X,F) = F \\<circ>\\<^sub>m prod_top_map(id_mor(X),interval_upper)\"\nsetup {* register_wellform_data (\"homotopy_upper_half(X,F)\", [\"F \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(F)\"]) *}\n\nlemma homotopy_upper_half_type [typing]:\n  \"is_top_space(X) \\<Longrightarrow> F \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(F) \\<Longrightarrow>\n   homotopy_upper_half(X,F) \\<in> X \\<times>\\<^sub>T I2 \\<rightharpoonup>\\<^sub>T target_str(F)\" by auto2\n      \nlemma homotopy_upper_half_eval [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> \\<langle>x,t\\<rangle> \\<in> source(F') \\<Longrightarrow> F \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T target_str(F) \\<Longrightarrow>\n   F' = homotopy_upper_half(X,F) \\<Longrightarrow> F'`\\<langle>x,t\\<rangle> = F`\\<langle>x, 2\\<^sub>\\<real> *\\<^sub>\\<real> t -\\<^sub>\\<real> 1\\<^sub>\\<real>\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm homotopy_upper_half_def} *}\n\ndefinition compose_homotopy :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"compose_homotopy(f,g,h,F,G) = glue_morphism(source_str(f) \\<times>\\<^sub>T I,\n     homotopy_lower_half(source_str(f),F), homotopy_upper_half(source_str(f),G))\"\nsetup {* register_wellform_data (\"compose_homotopy(f,g,h,F,G)\",\n  [\"F \\<in> homotopy_maps(f,g)\", \"G \\<in> homotopy_maps(g,h)\"]) *}\n\nlemma I1_I2_inter [rewrite]: \"X \\<times> carrier(I1) \\<inter> X \\<times> carrier(I2) = X \\<times> {1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real>}\" by auto2\nlemma I1_I2_union [rewrite]: \"X \\<times> carrier(I1) \\<union> X \\<times> carrier(I2) = X \\<times> carrier(I)\" by auto2\n\nlemma compose_is_homotopy:\n  \"is_homotopy(f,g,F) \\<Longrightarrow> is_homotopy(g,h,G) \\<Longrightarrow> is_homotopy(f,h,compose_homotopy(f,g,h,F,G))\"\n@proof\n  @let \"X = source_str(f)\" \"Y = target_str(f)\"\n  @have \"compose_homotopy(f,g,h,F,G) \\<in> X \\<times>\\<^sub>T I \\<rightharpoonup>\\<^sub>T Y\"\n@qed\nsetup {* add_forward_prfstep_cond @{thm compose_is_homotopy} [with_term \"compose_homotopy(?f,?g,?h,?F,?G)\"] *}\n\nlemma compose_homotopy_eval [rewrite]:\n  \"is_homotopy(f,g,F) \\<Longrightarrow> is_homotopy(g,h,G) \\<Longrightarrow> H = compose_homotopy(f,g,h,F,G) \\<Longrightarrow> \n   \\<langle>x,t\\<rangle> \\<in> source(H) \\<Longrightarrow> H`\\<langle>x,t\\<rangle> = (if t \\<le>\\<^sub>\\<real> 1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real> then F`\\<langle>x, 2\\<^sub>\\<real> *\\<^sub>\\<real> t\\<rangle> else G`\\<langle>x, 2\\<^sub>\\<real> *\\<^sub>\\<real> t -\\<^sub>\\<real> 1\\<^sub>\\<real>\\<rangle>)\"\n@proof\n  @case \"t \\<le>\\<^sub>\\<real> 1\\<^sub>\\<real> /\\<^sub>\\<real> 2\\<^sub>\\<real>\" @with @have \"\\<langle>x,t\\<rangle> \\<in> source(f) \\<times> carrier(I1)\" @end\n@qed\nsetup {* del_prfstep_thm @{thm compose_homotopy_def} *}\n\nlemma homotopic_trans [forward]:\n  \"homotopic(f,g) \\<Longrightarrow> homotopic(g,h) \\<Longrightarrow> homotopic(f,h)\"\n@proof\n  @obtain F where \"is_homotopy(f,g,F)\"\n  @obtain G where \"is_homotopy(g,h,G)\"\n  @have \"is_homotopy(f,h,compose_homotopy(f,g,h,F,G))\"\n@qed\n\nlemma homotopy_maps_comp1 [backward]:\n  \"continuous(h) \\<Longrightarrow> target_str(h) = source_str(f) \\<Longrightarrow> is_homotopy(f,g,F) \\<Longrightarrow>\n   is_homotopy(f \\<circ>\\<^sub>m h, g \\<circ>\\<^sub>m h, F \\<circ>\\<^sub>m prod_top_map(h,id_mor(I)))\" by auto2\n\nlemma homotopic_comp1 [backward]:\n  \"continuous(h) \\<Longrightarrow> target_str(h) = source_str(f) \\<Longrightarrow> homotopic(f,g) \\<Longrightarrow> homotopic(f \\<circ>\\<^sub>m h, g \\<circ>\\<^sub>m h)\"\n@proof\n  @obtain F where \"is_homotopy(f,g,F)\"\n  @have \"is_homotopy(f \\<circ>\\<^sub>m h, g \\<circ>\\<^sub>m h, F \\<circ>\\<^sub>m prod_top_map(h,id_mor(I)))\"\n@qed\n\nlemma homotopy_maps_comp2 [backward]:\n  \"continuous(h) \\<Longrightarrow> target_str(f) = source_str(h) \\<Longrightarrow> is_homotopy(f,g,F) \\<Longrightarrow>\n   is_homotopy(h \\<circ>\\<^sub>m f, h \\<circ>\\<^sub>m g, h \\<circ>\\<^sub>m F)\" by auto2\n    \nlemma homotopic_comp2 [backward]:\n  \"continuous(h) \\<Longrightarrow> target_str(f) = source_str(h) \\<Longrightarrow> homotopic(f,g) \\<Longrightarrow> homotopic(h \\<circ>\\<^sub>m f, h \\<circ>\\<^sub>m g)\"\n@proof\n  @obtain F where \"is_homotopy(f,g,F)\"\n  @have \"is_homotopy(h \\<circ>\\<^sub>m f, h \\<circ>\\<^sub>m g, h \\<circ>\\<^sub>m F)\"\n@qed\n    \nsection \\<open>Homotopy equivalence between two spaces\\<close>\n  \ndefinition homotopy_equiv_pair :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"homotopy_equiv_pair(f,g) \\<longleftrightarrow> (continuous(f) \\<and> continuous(g) \\<and>\n    source_str(f) = target_str(g) \\<and> target_str(f) = source_str(g) \\<and>\n    homotopic(g \\<circ>\\<^sub>m f, id_mor(source_str(f))) \\<and>\n    homotopic(f \\<circ>\\<^sub>m g, id_mor(source_str(g))))\"\n  \nlemma homotopy_equiv_pairI [backward]:\n  \"continuous(f) \\<Longrightarrow> continuous(g) \\<Longrightarrow> source_str(f) = target_str(g) \\<Longrightarrow> target_str(f) = source_str(g) \\<Longrightarrow>\n   homotopic(g \\<circ>\\<^sub>m f, id_mor(source_str(f))) \\<Longrightarrow> homotopic(f \\<circ>\\<^sub>m g, id_mor(source_str(g))) \\<Longrightarrow>\n   homotopy_equiv_pair(f, g)\" by auto2\n\nlemma homotopy_equiv_pairD [forward]:\n  \"homotopy_equiv_pair(f, g) \\<Longrightarrow> continuous(f) \\<and> continuous(g) \\<and> source_str(f) = target_str(g) \\<and>\n   target_str(f) = source_str(g) \\<and> homotopic(g \\<circ>\\<^sub>m f, id_mor(source_str(f))) \\<and>\n   homotopic(f \\<circ>\\<^sub>m g, id_mor(source_str(g)))\" by auto2\nsetup {* del_prfstep_thm @{thm homotopy_equiv_pair_def} *}\n  \nlemma homotopy_equiv_pair_sym [forward]:\n  \"homotopy_equiv_pair(f,g) \\<Longrightarrow> homotopy_equiv_pair(g,f)\" by auto2\n    \nlemma homotopy_equiv_pair_id [resolve]:\n  \"is_top_space(X) \\<Longrightarrow> homotopy_equiv_pair(id_mor(X),id_mor(X))\" by auto2\n  \ndefinition homotopy_equiv_space :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"homotopy_equiv_space(X,Y) = {f \\<in> X \\<rightharpoonup>\\<^sub>T Y. \\<exists>g\\<in>Y \\<rightharpoonup>\\<^sub>T X. homotopy_equiv_pair(f,g)}\"\n\nlemma homotopy_equiv_spaceI [forward]:\n  \"mor_form(f) \\<Longrightarrow> mor_form(g) \\<Longrightarrow> homotopy_equiv_pair(f,g) \\<Longrightarrow>\n   f \\<in> homotopy_equiv_space(source_str(f),target_str(f))\" by auto2\n\nlemma homotopy_equiv_spaceD1 [forward]:\n  \"f \\<in> homotopy_equiv_space(X,Y) \\<Longrightarrow> f \\<in> X \\<rightharpoonup>\\<^sub>T Y\" by auto2\n    \nlemma homotopy_equiv_spaceD2 [backward]:\n  \"f \\<in> homotopy_equiv_space(X,Y) \\<Longrightarrow> \\<exists>g\\<in>Y \\<rightharpoonup>\\<^sub>T X. homotopy_equiv_pair(f,g)\" by auto2\nsetup {* del_prfstep_thm @{thm homotopy_equiv_space_def} *}\n\ndefinition homotopy_equivalent :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"homotopy_equivalent(X,Y) \\<longleftrightarrow> (is_top_space(X) \\<and> is_top_space(Y) \\<and> homotopy_equiv_space(X,Y) \\<noteq> \\<emptyset>)\"\n\nlemma homotpy_equivalentI [forward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> f \\<in> homotopy_equiv_space(X,Y) \\<Longrightarrow> homotopy_equivalent(X,Y)\" by auto2\n    \nlemma homotopy_equivalentD1 [forward]:\n  \"homotopy_equivalent(X,Y) \\<Longrightarrow> is_top_space(X) \\<and> is_top_space(Y)\" by auto2\n    \nlemma homotopy_equivalentD2 [backward]:\n  \"homotopy_equivalent(X,Y) \\<Longrightarrow> \\<exists>f. f \\<in> homotopy_equiv_space(X,Y)\" by auto2\n    \nlemma homotopy_equivalentD2' [backward]:\n  \"homotopy_equivalent(X,Y) \\<Longrightarrow> \\<exists>f\\<in>X\\<rightharpoonup>\\<^sub>TY. \\<exists>g\\<in>Y\\<rightharpoonup>\\<^sub>TX. homotopy_equiv_pair(f,g)\"\n@proof\n  @obtain f where \"f \\<in> homotopy_equiv_space(X,Y)\"\n  @obtain \"g\\<in>Y \\<rightharpoonup>\\<^sub>T X\" where \"homotopy_equiv_pair(f,g)\"\n@qed\nsetup {* del_prfstep_thm @{thm homotopy_equivalent_def} *}\n  \nlemma homotopy_equivalent_refl [resolve]:\n  \"is_top_space(X) \\<Longrightarrow> homotopy_equivalent(X,X)\"\n@proof @have \"homotopy_equiv_pair(id_mor(X),id_mor(X))\" @qed\n      \nlemma homotopy_equivalent_sym [forward]:\n  \"homotopy_equivalent(X,Y) \\<Longrightarrow> homotopy_equivalent(Y,X)\"\n@proof\n  @obtain \"f\\<in>X\\<rightharpoonup>\\<^sub>TY\" \"g\\<in>Y\\<rightharpoonup>\\<^sub>TX\" where \"homotopy_equiv_pair(f,g)\"\n@qed\n\nlemma homotopy_equivalent_trans [forward]:\n  \"homotopy_equivalent(X,Y) \\<Longrightarrow> homotopy_equivalent(Y,Z) \\<Longrightarrow> homotopy_equivalent(X,Z)\"\n@proof\n  @obtain \"f\\<in>X\\<rightharpoonup>\\<^sub>TY\" \"f'\\<in>Y\\<rightharpoonup>\\<^sub>TX\" where \"homotopy_equiv_pair(f,f')\"\n  @obtain \"g\\<in>Y\\<rightharpoonup>\\<^sub>TZ\" \"g'\\<in>Z\\<rightharpoonup>\\<^sub>TY\" where \"homotopy_equiv_pair(g,g')\"\n  @have \"homotopy_equiv_pair(g \\<circ>\\<^sub>m f, f' \\<circ>\\<^sub>m g')\" @with\n    @have \"homotopic((g \\<circ>\\<^sub>m f) \\<circ>\\<^sub>m (f' \\<circ>\\<^sub>m g'), id_mor(Z))\" @with\n      @have \"homotopic(g \\<circ>\\<^sub>m (f \\<circ>\\<^sub>m f') \\<circ>\\<^sub>m g', g \\<circ>\\<^sub>m id_mor(Y) \\<circ>\\<^sub>m g')\" @end\n    @have \"homotopic((f' \\<circ>\\<^sub>m g') \\<circ>\\<^sub>m (g \\<circ>\\<^sub>m f), id_mor(X))\" @with\n      @have \"homotopic(f' \\<circ>\\<^sub>m (g' \\<circ>\\<^sub>m g) \\<circ>\\<^sub>m f, f' \\<circ>\\<^sub>m id_mor(Y) \\<circ>\\<^sub>m f)\" @end\n  @end\n@qed\n\nend", "meta": {"author": "bzhan", "repo": "auto2", "sha": "2e83c30b095f2ed9fa5257f79570eb354ed6e6a7", "save_path": "github-repos/isabelle/bzhan-auto2", "path": "github-repos/isabelle/bzhan-auto2/auto2-2e83c30b095f2ed9fa5257f79570eb354ed6e6a7/FOL/Homotopy/Homotopy.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942041005328, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7730853806283188}}
{"text": "(* Authors: Heiko Loetzbeyer, Robert Sandner, Tobias Nipkow *)\n\nsection \"Denotational Semantics of Commands\"\n\ntheory Denotational imports Big_Step begin\n\ntype_synonym com_den = \"(state \\<times> state) set\"\n\ndefinition W :: \"(state \\<Rightarrow> bool) \\<Rightarrow> com_den \\<Rightarrow> (com_den \\<Rightarrow> com_den)\" where\n\"W db dc = (\\<lambda>dw. {(s,t). if db s then (s,t) \\<in> dc O dw else s=t})\"\n\nfun D :: \"com \\<Rightarrow> com_den\" where\n\"D SKIP   = Id\" |\n\"D (x ::= a) = {(s,t). t = s(x := aval a s)}\" |\n\"D (c1;;c2)  = D(c1) O D(c2)\" |\n\"D (IF b THEN c1 ELSE c2)\n = {(s,t). if bval b s then (s,t) \\<in> D c1 else (s,t) \\<in> D c2}\" |\n\"D (WHILE b DO c) = lfp (W (bval b) (D c))\"\n\nlemma W_mono: \"mono (W b r)\"\nby (unfold W_def mono_def) auto\n\nlemma D_While_If:\n  \"D(WHILE b DO c) = D(IF b THEN c;;WHILE b DO c ELSE SKIP)\"\nproof-\n  let ?w = \"WHILE b DO c\" let ?f = \"W (bval b) (D c)\"\n  have \"D ?w = lfp ?f\" by simp\n  also have \"\\<dots> = ?f (lfp ?f)\" by(rule lfp_unfold [OF W_mono])\n  also have \"\\<dots> = D(IF b THEN c;;?w ELSE SKIP)\" by (simp add: W_def)\n  finally show ?thesis .\nqed\n\ntext{* Equivalence of denotational and big-step semantics: *}\n\nlemma D_if_big_step:  \"(c,s) \\<Rightarrow> t \\<Longrightarrow> (s,t) \\<in> D(c)\"\nproof (induction rule: big_step_induct)\n  case WhileFalse\n  with D_While_If show ?case by auto\nnext\n  case WhileTrue\n  show ?case unfolding D_While_If using WhileTrue by auto\nqed auto\n\nabbreviation Big_step :: \"com \\<Rightarrow> com_den\" where\n\"Big_step c \\<equiv> {(s,t). (c,s) \\<Rightarrow> t}\"\n\nlemma Big_step_if_D:  \"(s,t) \\<in> D(c) \\<Longrightarrow> (s,t) : Big_step c\"\nproof (induction c arbitrary: s t)\n  case Seq thus ?case by fastforce\nnext\n  case (While b c)\n  let ?B = \"Big_step (WHILE b DO c)\" let ?f = \"W (bval b) (D c)\"\n  have \"?f ?B \\<subseteq> ?B\" using While.IH by (auto simp: W_def)\n  from lfp_lowerbound[where ?f = \"?f\", OF this] While.prems\n  show ?case by auto\nqed (auto split: if_splits)\n\ntheorem denotational_is_big_step:\n  \"(s,t) \\<in> D(c)  =  ((c,s) \\<Rightarrow> t)\"\nby (metis D_if_big_step Big_step_if_D[simplified])\n\ncorollary equiv_c_iff_equal_D: \"(c1 \\<sim> c2) \\<longleftrightarrow> D c1 = D c2\"\nby(simp add: denotational_is_big_step[symmetric] set_eq_iff)\n\n\nsubsection \"Continuity\"\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\" where\n\"chain S = (\\<forall>i. S i \\<subseteq> S(Suc i))\"\n\nlemma chain_total: \"chain S \\<Longrightarrow> S i \\<le> S j \\<or> S j \\<le> S i\"\nby (metis chain_def le_cases lift_Suc_mono_le)\n\ndefinition cont :: \"('a set \\<Rightarrow> 'b set) \\<Rightarrow> bool\" where\n\"cont f = (\\<forall>S. chain S \\<longrightarrow> f(UN n. S n) = (UN n. f(S n)))\"\n\nlemma mono_if_cont: fixes f :: \"'a set \\<Rightarrow> 'b set\"\n  assumes \"cont f\" shows \"mono f\"\nproof\n  fix a b :: \"'a set\" assume \"a \\<subseteq> b\"\n  let ?S = \"\\<lambda>n::nat. if n=0 then a else b\"\n  have \"chain ?S\" using `a \\<subseteq> b` by(auto simp: chain_def)\n  hence \"f(UN n. ?S n) = (UN n. f(?S n))\"\n    using assms by(simp add: cont_def)\n  moreover have \"(UN n. ?S n) = b\" using `a \\<subseteq> b` by (auto split: if_splits)\n  moreover have \"(UN n. f(?S n)) = f a \\<union> f b\" by (auto split: if_splits)\n  ultimately show \"f a \\<subseteq> f b\" by (metis Un_upper1)\nqed\n\nlemma chain_iterates: fixes f :: \"'a set \\<Rightarrow> 'a set\"\n  assumes \"mono f\" shows \"chain(\\<lambda>n. (f^^n) {})\"\nproof-\n  { fix n have \"(f ^^ n) {} \\<subseteq> (f ^^ Suc n) {}\" using assms\n    by(induction n) (auto simp: mono_def) }\n  thus ?thesis by(auto simp: chain_def)\nqed\n\ntheorem lfp_if_cont:\n  assumes \"cont f\" shows \"lfp f = (UN n. (f^^n) {})\" (is \"_ = ?U\")\nproof\n  from assms mono_if_cont\n  have mono: \"(f ^^ n) {} \\<subseteq> (f ^^ Suc n) {}\" for n\n    using funpow_decreasing [of n \"Suc n\"] by auto\n  show \"lfp f \\<subseteq> ?U\"\n  proof (rule lfp_lowerbound)\n    have \"f ?U = (UN n. (f^^Suc n){})\"\n      using chain_iterates[OF mono_if_cont[OF assms]] assms\n      by(simp add: cont_def)\n    also have \"\\<dots> = (f^^0){} \\<union> \\<dots>\" by simp\n    also have \"\\<dots> = ?U\"\n      using mono by auto (metis funpow_simps_right(2) funpow_swap1 o_apply)\n    finally show \"f ?U \\<subseteq> ?U\" by simp\n  qed\nnext\n  { fix n p assume \"f p \\<subseteq> p\"\n    have \"(f^^n){} \\<subseteq> p\"\n    proof(induction n)\n      case 0 show ?case by simp\n    next\n      case Suc\n      from monoD[OF mono_if_cont[OF assms] Suc] `f p \\<subseteq> p`\n      show ?case by simp\n    qed\n  }\n  thus \"?U \\<subseteq> lfp f\" by(auto simp: lfp_def)\nqed\n\nlemma cont_W: \"cont(W b r)\"\nby(auto simp: cont_def W_def)\n\n\nsubsection{*The denotational semantics is deterministic*}\n\nlemma single_valued_UN_chain:\n  assumes \"chain S\" \"(\\<And>n. single_valued (S n))\"\n  shows \"single_valued(UN n. S n)\"\nproof(auto simp: single_valued_def)\n  fix m n x y z assume \"(x, y) \\<in> S m\" \"(x, z) \\<in> S n\"\n  with chain_total[OF assms(1), of m n] assms(2)\n  show \"y = z\" by (auto simp: single_valued_def)\nqed\n\nlemma single_valued_lfp: fixes f :: \"com_den \\<Rightarrow> com_den\"\nassumes \"cont f\" \"\\<And>r. single_valued r \\<Longrightarrow> single_valued (f r)\"\nshows \"single_valued(lfp f)\"\nunfolding lfp_if_cont[OF assms(1)]\nproof(rule single_valued_UN_chain[OF chain_iterates[OF mono_if_cont[OF assms(1)]]])\n  fix n show \"single_valued ((f ^^ n) {})\"\n  by(induction n)(auto simp: assms(2))\nqed\n\nlemma single_valued_D: \"single_valued (D c)\"\nproof(induction c)\n  case Seq thus ?case by(simp add: single_valued_relcomp)\nnext\n  case (While b c)\n  let ?f = \"W (bval b) (D c)\"\n  have \"single_valued (lfp ?f)\"\n  proof(rule single_valued_lfp[OF cont_W])\n    show \"\\<And>r. single_valued r \\<Longrightarrow> single_valued (?f r)\"\n      using While.IH by(force simp: single_valued_def W_def)\n  qed\n  thus ?case by simp\nqed (auto simp add: single_valued_def)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/IMP/Denotational.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122213606241, "lm_q2_score": 0.8519528000888387, "lm_q1q2_score": 0.7729871875430079}}
{"text": "(*\n  File: Lattice.thy\n  Author: Bohua Zhan\n\n  Basics of lattice theory.\n*)\n\ntheory Lattice\n  imports OrderRel\nbegin\n\n(* First, we define join-semilattice. Note this is declared as a property. *)\ndefinition join_semilattice :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"join_semilattice(R) \\<longleftrightarrow> order(R) \\<and>\n    (\\<forall>x\\<in>.R. \\<forall>y\\<in>.R. \\<exists>z. z \\<ge>\\<^sub>R x \\<and> z \\<ge>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>R x \\<longrightarrow> z' \\<ge>\\<^sub>R y \\<longrightarrow> z' \\<ge>\\<^sub>R z))\"\n\n(* Next, we prove two results on how to *use* the join-semilattice property. *)\nlemma join_semilatticeD1 [forward]: \"join_semilattice(R) \\<Longrightarrow> order(R)\" by auto2\n\n(* In this case, we add the lemma as a *backward* reasoning rule. This rule is\n   only applied when the conclusion is needed. If we add this as a forward\n   reasoning rule instead, a join element will be created for every pair of\n   elements in R.\n *)\nlemma join_semilatticeD2 [backward]:\n  \"join_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow>\n   \\<exists>z. z \\<ge>\\<^sub>R x \\<and> z \\<ge>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>R x \\<longrightarrow> z' \\<ge>\\<^sub>R y \\<longrightarrow> z' \\<ge>\\<^sub>R z)\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm join_semilattice_def} *}\n  \n(* The *unique* existence of join can be proved automatically. *)\nlemma join_semilattice_unique [backward]:\n  \"join_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow>\n   \\<exists>!z. z \\<ge>\\<^sub>R x \\<and> z \\<ge>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>R x \\<longrightarrow> z' \\<ge>\\<^sub>R y \\<longrightarrow> z' \\<ge>\\<^sub>R z)\" by auto2\n\n(* Define the join function and specify its notation. *)\ndefinition join :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"join(R,x,y) = (THE z. z \\<ge>\\<^sub>R x \\<and> z \\<ge>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>R x \\<longrightarrow> z' \\<ge>\\<^sub>R y \\<longrightarrow> z' \\<ge>\\<^sub>R z))\"\nabbreviation join_notation (\"(_/ \\<squnion>\\<^sub>_ _)\" [66,66,66] 65) where \"x \\<squnion>\\<^sub>R y \\<equiv> join(R,x,y)\"\nsetup {* register_wellform_data (\"x \\<squnion>\\<^sub>R y\", [\"x \\<in>. R\", \"y \\<in>. R\"]) *}\n\n(* The main properties of join are proved. The first one is added whenever the\n   term join(R,x,y) appears in the proof.\n *)\nlemma joinD1:\n  \"join_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R y \\<ge>\\<^sub>R x \\<and> x \\<squnion>\\<^sub>R y \\<ge>\\<^sub>R y\" by auto2\nsetup {* add_forward_prfstep_cond @{thm joinD1} [with_term \"join(?R,?x,?y)\"] *}\n\n(* The second one is invoked whenever we want to prove something is greater than\n   or equal to the join.\n *)\nlemma joinD2 [backward]:\n  \"join_semilattice(R) \\<Longrightarrow> z \\<ge>\\<^sub>R x \\<Longrightarrow> z \\<ge>\\<^sub>R y \\<Longrightarrow> z \\<ge>\\<^sub>R x \\<squnion>\\<^sub>R y\" by auto2\n\n(* Finally, a third property on how to show the join of x and y is equal to something. *)\nlemma joinI [backward]:\n  \"join_semilattice(R) \\<Longrightarrow> z \\<ge>\\<^sub>R x \\<Longrightarrow> z \\<ge>\\<^sub>R y \\<Longrightarrow> \\<forall>z'. z' \\<ge>\\<^sub>R x \\<longrightarrow> z' \\<ge>\\<^sub>R y \\<longrightarrow> z' \\<ge>\\<^sub>R z \\<Longrightarrow> x \\<squnion>\\<^sub>R y = z\" by auto2\nsetup {* del_prfstep_thm @{thm join_def} *}\n\n(* A few algebraic rules for join. *)\nlemma join_idem [rewrite]:\n  \"join_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R x = x\" by auto2\n\nlemma join_comm [rewrite]:\n  \"join_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R y = y \\<squnion>\\<^sub>R x\" by auto2\n    \nlemma join_assoc [rewrite]:\n  \"join_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> (x \\<squnion>\\<^sub>R y) \\<squnion>\\<^sub>R z = x \\<squnion>\\<^sub>R (y \\<squnion>\\<^sub>R z)\" by auto2\n\n(* Meet is defined in a completely analogous manner. *)\ndefinition meet_semilattice :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"meet_semilattice(R) \\<longleftrightarrow> order(R) \\<and>\n    (\\<forall>x\\<in>.R. \\<forall>y\\<in>.R. \\<exists>z. z \\<le>\\<^sub>R x \\<and> z \\<le>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<le>\\<^sub>R x \\<longrightarrow> z' \\<le>\\<^sub>R y \\<longrightarrow> z' \\<le>\\<^sub>R z))\"\n  \nlemma meet_semilatticeD1 [forward]: \"meet_semilattice(R) \\<Longrightarrow> order(R)\" by auto2\n    \nlemma meet_semilatticeD2 [backward]:\n  \"meet_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow>\n   \\<exists>z. z \\<le>\\<^sub>R x \\<and> z \\<le>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<le>\\<^sub>R x \\<longrightarrow> z' \\<le>\\<^sub>R y \\<longrightarrow> z' \\<le>\\<^sub>R z)\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm meet_semilattice_def} *}\n  \nlemma meet_semilattice_unique [backward]:\n  \"meet_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow>\n   \\<exists>!z. z \\<le>\\<^sub>R x \\<and> z \\<le>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<le>\\<^sub>R x \\<longrightarrow> z' \\<le>\\<^sub>R y \\<longrightarrow> z' \\<le>\\<^sub>R z)\" by auto2\n\ndefinition meet :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"meet(R,x,y) = (THE z. z \\<le>\\<^sub>R x \\<and> z \\<le>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<le>\\<^sub>R x \\<longrightarrow> z' \\<le>\\<^sub>R y \\<longrightarrow> z' \\<le>\\<^sub>R z))\"\nabbreviation meet_notation (\"(_/ \\<sqinter>\\<^sub>_ _)\" [66,66,66] 65) where \"x \\<sqinter>\\<^sub>R y \\<equiv> meet(R,x,y)\"\nsetup {* register_wellform_data (\"meet(R,x,y)\", [\"x \\<in>. R\", \"y \\<in>. R\"]) *}\n\nlemma meetD1:\n  \"meet_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<sqinter>\\<^sub>R y \\<le>\\<^sub>R x \\<and> x \\<sqinter>\\<^sub>R y \\<le>\\<^sub>R y\" by auto2\nsetup {* add_forward_prfstep_cond @{thm meetD1} [with_term \"meet(?R,?x,?y)\"] *}\n  \nlemma meetD2 [backward]:\n  \"meet_semilattice(R) \\<Longrightarrow> z' \\<le>\\<^sub>R x \\<Longrightarrow> z' \\<le>\\<^sub>R y \\<Longrightarrow> z' \\<le>\\<^sub>R x \\<sqinter>\\<^sub>R y\" by auto2\n    \nlemma meetI [backward]:\n  \"meet_semilattice(R) \\<Longrightarrow> z \\<le>\\<^sub>R x \\<Longrightarrow> z \\<le>\\<^sub>R y \\<Longrightarrow> \\<forall>z'. z' \\<le>\\<^sub>R x \\<longrightarrow> z' \\<le>\\<^sub>R y \\<longrightarrow> z' \\<le>\\<^sub>R z \\<Longrightarrow> x \\<sqinter>\\<^sub>R y = z\" by auto2\nsetup {* del_prfstep_thm @{thm meet_def} *}\n\nlemma meet_idem [rewrite]:\n  \"meet_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> x \\<sqinter>\\<^sub>R x = x\" by auto2\n\n(* Adding commutativity and associativity as rewrite rules is NOT a good idea.\n   TODO: use special rules for AC functions instead.\n *)\nlemma meet_comm [rewrite]:\n  \"meet_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<sqinter>\\<^sub>R y = y \\<sqinter>\\<^sub>R x\" by auto2\n    \nlemma meet_assoc [rewrite]:\n  \"meet_semilattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> (x \\<sqinter>\\<^sub>R y) \\<sqinter>\\<^sub>R z = x \\<sqinter>\\<^sub>R (y \\<sqinter>\\<^sub>R z)\" by auto2\n\n(* An ordering is a lattice if it is both join-semilattice and meet-semilattice. *)\ndefinition lattice :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"lattice(R) \\<longleftrightarrow> join_semilattice(R) \\<and> meet_semilattice(R)\"\n  \n(* The absorption rules. *)\nlemma lattice_absorb1 [rewrite]:\n  \"lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R (x \\<sqinter>\\<^sub>R y) = x\" by auto2\n    \nlemma lattice_absorb2 [rewrite]:\n  \"lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<sqinter>\\<^sub>R (x \\<squnion>\\<^sub>R y) = x\" by auto2\n\n(* Distributive lattices. *)\ndefinition distributive_lattice :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"distributive_lattice(R) \\<longleftrightarrow> (lattice(R) \\<and> (\\<forall>x\\<in>.R. \\<forall>y\\<in>.R. \\<forall>z\\<in>.R. x \\<sqinter>\\<^sub>R (y \\<squnion>\\<^sub>R z) = (x \\<sqinter>\\<^sub>R y) \\<squnion>\\<^sub>R (x \\<sqinter>\\<^sub>R z)))\"\n\nlemma distributive_latticeD1 [forward]:\n  \"distributive_lattice(R) \\<Longrightarrow> lattice(R)\" by auto2\n\nlemma distributive_latticeD2 [rewrite_back]:\n  \"distributive_lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> x \\<sqinter>\\<^sub>R (y \\<squnion>\\<^sub>R z) = (x \\<sqinter>\\<^sub>R y) \\<squnion>\\<^sub>R (x \\<sqinter>\\<^sub>R z)\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm distributive_lattice_def} *}\n  \n(* An equivalent formulation of distributive lattices. Their equivalence requires\n   several equality steps.\n *)\nlemma distributive_latticeD2' [rewrite_bidir]:\n  \"distributive_lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z) = (x \\<squnion>\\<^sub>R y) \\<sqinter>\\<^sub>R (x \\<squnion>\\<^sub>R z)\"\n@proof\n  @have \"x \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z) = (x \\<squnion>\\<^sub>R (x \\<sqinter>\\<^sub>R z)) \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z)\"\n  @have \"x \\<squnion>\\<^sub>R ((x \\<squnion>\\<^sub>R y) \\<sqinter>\\<^sub>R z) = (x \\<sqinter>\\<^sub>R (x \\<squnion>\\<^sub>R y)) \\<squnion>\\<^sub>R ((x \\<squnion>\\<^sub>R y) \\<sqinter>\\<^sub>R z)\"\n@qed\n\n(* Part of distributivity is true for all lattices. This can be shown automatically. *)\nlemma lattice_distributive1 [resolve]:\n  \"lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> (x \\<sqinter>\\<^sub>R y) \\<squnion>\\<^sub>R (x \\<sqinter>\\<^sub>R z) \\<le>\\<^sub>R x \\<sqinter>\\<^sub>R (y \\<squnion>\\<^sub>R z)\" by auto2\n\nlemma lattice_distributive2 [resolve]:\n  \"lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z) \\<le>\\<^sub>R (x \\<squnion>\\<^sub>R y) \\<sqinter>\\<^sub>R (x \\<squnion>\\<^sub>R z)\" by auto2\n\nsection \\<open>Examples of lattices\\<close>\n\n(* The subset ordering on the power set of S is a lattice. Join and meet\n   is given by union and intersection, respectively.\n *)\nlemma subset_order_is_lattice: \"lattice(subset_order(Pow(S)))\"\n@proof\n  @let \"R = subset_order(Pow(S))\"\n  @have \"join_semilattice(R)\" @with\n    @have \"\\<forall>x\\<in>.R. \\<forall>y\\<in>.R. \\<exists>z. z \\<ge>\\<^sub>R x \\<and> z \\<ge>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>R x \\<longrightarrow> z' \\<ge>\\<^sub>R y \\<longrightarrow> z' \\<ge>\\<^sub>R z)\" @with\n      @have \"x \\<union> y \\<ge>\\<^sub>R x\"\n    @end\n  @end\n  @have \"meet_semilattice(R)\" @with\n    @have \"\\<forall>x\\<in>.R. \\<forall>y\\<in>.R. \\<exists>z. z \\<le>\\<^sub>R x \\<and> z \\<le>\\<^sub>R y \\<and> (\\<forall>z'. z' \\<le>\\<^sub>R x \\<longrightarrow> z' \\<le>\\<^sub>R y \\<longrightarrow> z' \\<le>\\<^sub>R z)\" @with\n      @have \"x \\<inter> y \\<le>\\<^sub>R x\"\n    @end\n  @end\n@qed\nsetup {* add_forward_prfstep_cond @{thm subset_order_is_lattice} [with_term \"subset_order(Pow(?S))\"] *}\n\nlemma subset_order_join_eval [rewrite]:\n  \"R = subset_order(Pow(S)) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<squnion>\\<^sub>R y = x \\<union> y\" by auto2\nlemma subset_order_meet_eval [rewrite]:\n  \"R = subset_order(Pow(S)) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> x \\<sqinter>\\<^sub>R y = x \\<inter> y\" by auto2\n\nlemma subset_order_is_distrib_lattice:\n  \"distributive_lattice(subset_order(Pow(S)))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm subset_order_is_distrib_lattice} [with_term \"subset_order(Pow(?S))\"] *}\n\n(* We define the product ordering on any two orders *)\ndefinition product_ord :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixr \"\\<times>\\<^sub>O\" 80) where [rewrite]:\n  \"R \\<times>\\<^sub>O S = Order(carrier(R)\\<times>carrier(S), \\<lambda>p q. fst(p) \\<le>\\<^sub>R fst(q) \\<and> snd(p) \\<le>\\<^sub>S snd(q))\"\n\nlemma product_ord_type [typing]: \"R \\<times>\\<^sub>O S \\<in> raworder_space(carrier(R)\\<times>carrier(S))\" by auto2\n\nlemma product_ord_is_order [forward]:\n  \"order(R) \\<Longrightarrow> order(S) \\<Longrightarrow> order(R \\<times>\\<^sub>O S)\" by auto2\n\nlemma product_ord_eval [rewrite]:\n  \"T = R \\<times>\\<^sub>O S \\<Longrightarrow> x \\<in>. T \\<Longrightarrow> y \\<in>. T \\<Longrightarrow> x \\<le>\\<^sub>T y \\<longleftrightarrow> (fst(x) \\<le>\\<^sub>R fst(y) \\<and> snd(x) \\<le>\\<^sub>S snd(y))\" by auto2\nsetup {* del_prfstep_thm @{thm product_ord_def} *}\n\n(* Product of two lattices is a lattice. *)\nlemma product_ord_is_lattice [forward]:\n  \"lattice(R) \\<Longrightarrow> lattice(S) \\<Longrightarrow> lattice(R \\<times>\\<^sub>O S)\"\n@proof\n  @let \"T = R \\<times>\\<^sub>O S\"\n  @have \"join_semilattice(T)\" @with\n    @have \"\\<forall>x\\<in>.T. \\<forall>y\\<in>.T. \\<exists>z. z \\<ge>\\<^sub>T x \\<and> z \\<ge>\\<^sub>T y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>T x \\<longrightarrow> z' \\<ge>\\<^sub>T y \\<longrightarrow> z' \\<ge>\\<^sub>T z)\" @with\n      @have \"\\<langle>fst(x) \\<squnion>\\<^sub>R fst(y), snd(x) \\<squnion>\\<^sub>S snd(y)\\<rangle> \\<ge>\\<^sub>T x\"\n    @end\n  @end\n  @have \"meet_semilattice(T)\" @with\n    @have \"\\<forall>x\\<in>.T. \\<forall>y\\<in>.T. \\<exists>z. z \\<le>\\<^sub>T x \\<and> z \\<le>\\<^sub>T y \\<and> (\\<forall>z'. z' \\<le>\\<^sub>T x \\<longrightarrow> z' \\<le>\\<^sub>T y \\<longrightarrow> z' \\<le>\\<^sub>T z)\" @with\n      @have \"\\<langle>fst(x) \\<sqinter>\\<^sub>R fst(y), snd(x) \\<sqinter>\\<^sub>S snd(y)\\<rangle> \\<le>\\<^sub>T x\"\n    @end\n  @end\n@qed  \n\nlemma product_ord_join_eval [rewrite]:\n  \"lattice(R) \\<Longrightarrow> lattice(S) \\<Longrightarrow> T = R \\<times>\\<^sub>O S \\<Longrightarrow> x \\<in>. T \\<Longrightarrow> y \\<in>. T \\<Longrightarrow>\n   x \\<squnion>\\<^sub>T y = \\<langle>fst(x) \\<squnion>\\<^sub>R fst(y), snd(x) \\<squnion>\\<^sub>S snd(y)\\<rangle>\"\n@proof\n  @have \"\\<langle>fst(x) \\<squnion>\\<^sub>R fst(y), snd(x) \\<squnion>\\<^sub>S snd(y)\\<rangle> \\<ge>\\<^sub>T x\"\n  @have \"\\<langle>fst(x) \\<squnion>\\<^sub>R fst(y), snd(x) \\<squnion>\\<^sub>S snd(y)\\<rangle> \\<ge>\\<^sub>T y\"\n@qed\n\nlemma product_ord_meet_eval [rewrite]:\n  \"lattice(R) \\<Longrightarrow> lattice(S) \\<Longrightarrow> T = R \\<times>\\<^sub>O S \\<Longrightarrow> x \\<in>. T \\<Longrightarrow> y \\<in>. T \\<Longrightarrow>\n   x \\<sqinter>\\<^sub>T y = \\<langle>fst(x) \\<sqinter>\\<^sub>R fst(y), snd(x) \\<sqinter>\\<^sub>S snd(y)\\<rangle>\"\n@proof\n  @have \"\\<langle>fst(x) \\<sqinter>\\<^sub>R fst(y), snd(x) \\<sqinter>\\<^sub>S snd(y)\\<rangle> \\<le>\\<^sub>T x\"\n  @have \"\\<langle>fst(x) \\<sqinter>\\<^sub>R fst(y), snd(x) \\<sqinter>\\<^sub>S snd(y)\\<rangle> \\<le>\\<^sub>T y\"\n@qed\n\nlemma product_ord_distrib_lattice [forward]:\n  \"distributive_lattice(R) \\<Longrightarrow> distributive_lattice(S) \\<Longrightarrow> distributive_lattice(R \\<times>\\<^sub>O S)\" by auto2\n\nsection \\<open>Other examples\\<close>\n\nlemma join_eq_str [forward]:\n  \"join_semilattice(R) \\<Longrightarrow> eq_str_order(R,S) \\<Longrightarrow> join_semilattice(S)\"\n@proof\n  @have \"\\<forall>x\\<in>.S. \\<forall>y\\<in>.S. \\<exists>z. z \\<ge>\\<^sub>S x \\<and> z \\<ge>\\<^sub>S y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>S x \\<longrightarrow> z' \\<ge>\\<^sub>S y \\<longrightarrow> z' \\<ge>\\<^sub>S z)\" @with\n    @have \"x \\<squnion>\\<^sub>R y \\<ge>\\<^sub>S x\"\n  @end\n@qed\n\nlemma join_ord_isomorphism [forward]:\n  \"join_semilattice(R) \\<Longrightarrow> ord_isomorphic(R,S) \\<Longrightarrow> join_semilattice(S)\"\n@proof\n  @obtain \"f \\<in> R \\<cong>\\<^sub>O S\"\n  @have (@rule) \"\\<forall>y\\<in>.S. \\<exists>x\\<in>.R. f`x = y\"\n  @let \"g = inverse(f)\"\n  @have \"\\<forall>x\\<in>.S. \\<forall>y\\<in>.S. \\<exists>z. z \\<ge>\\<^sub>S x \\<and> z \\<ge>\\<^sub>S y \\<and> (\\<forall>z'. z' \\<ge>\\<^sub>S x \\<longrightarrow> z' \\<ge>\\<^sub>S y \\<longrightarrow> z' \\<ge>\\<^sub>S z)\" @with\n    @have \"f ` (g ` x \\<squnion>\\<^sub>R g ` y) \\<ge>\\<^sub>S x\"\n  @end\n@qed\n    \nlemma join_eval_ord_isomorphism [rewrite]:\n  \"join_semilattice(R) \\<Longrightarrow> f \\<in> R \\<cong>\\<^sub>O S \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> f ` (x \\<squnion>\\<^sub>R y) = f ` x \\<squnion>\\<^sub>S f ` y\"\n@proof\n  @have (@rule) \"\\<forall>y'\\<in>.S. \\<exists>x\\<in>.R. f`x = y'\"\n  @let \"g = inverse(f)\" \n  @have \"x \\<squnion>\\<^sub>R y = g ` (f ` x \\<squnion>\\<^sub>S f ` y)\" @with\n    @have \"\\<forall>z. z \\<ge>\\<^sub>R x \\<longrightarrow> z \\<ge>\\<^sub>R y \\<longrightarrow> z \\<ge>\\<^sub>R g ` (f ` x \\<squnion>\\<^sub>S f ` y)\"  @with\n      @have \"f ` z \\<ge>\\<^sub>S f ` x \\<squnion>\\<^sub>S f ` y\" \n    @end\n  @end\n@qed\n\nsection \\<open>Modular lattices\\<close>\n\ndefinition modular_lattice :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"modular_lattice(R) \\<longleftrightarrow> (lattice(R) \\<and> (\\<forall>x y. x \\<le>\\<^sub>R y \\<longrightarrow> (\\<forall>z\\<in>.R. x \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z) = y \\<sqinter>\\<^sub>R (x \\<squnion>\\<^sub>R z))))\"\n  \nlemma modular_latticeD1 [forward]:\n  \"modular_lattice(R) \\<Longrightarrow> lattice(R)\" by auto2\n\nlemma modular_latticeD2 [rewrite_bidir]:\n  \"modular_lattice(R) \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> x \\<le>\\<^sub>R y \\<Longrightarrow> x \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z) = y \\<sqinter>\\<^sub>R (x \\<squnion>\\<^sub>R z)\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm modular_lattice_def} *}\n  \nlemma modular_latticeD3:\n  \"modular_lattice(R) \\<Longrightarrow> x \\<in>. R \\<Longrightarrow> y \\<in>. R \\<Longrightarrow> z \\<in>. R \\<Longrightarrow> (x \\<sqinter>\\<^sub>R y) \\<squnion>\\<^sub>R (y \\<sqinter>\\<^sub>R z) = y \\<sqinter>\\<^sub>R ((x \\<sqinter>\\<^sub>R y) \\<squnion>\\<^sub>R z)\" by auto2\n\nend\n", "meta": {"author": "bzhan", "repo": "auto2", "sha": "2e83c30b095f2ed9fa5257f79570eb354ed6e6a7", "save_path": "github-repos/isabelle/bzhan-auto2", "path": "github-repos/isabelle/bzhan-auto2/auto2-2e83c30b095f2ed9fa5257f79570eb354ed6e6a7/FOL/Lattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213664574069, "lm_q2_score": 0.8596637577007394, "lm_q1q2_score": 0.772942052517798}}
{"text": "theory OrderTheory\n  imports Main\nbegin\n\ndeclare [[ smt_solver = z3]]\ndeclare [[ smt_timeout = 60 ]]\ndeclare [[ z3_options = \"-memory:500\" ]]\n\ncontext order\nbegin\n\n(* Pointfree ordering *)\n\ndefinition pleq :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"pleq f g \\<equiv> \\<forall>x. f x \\<le> g x\"\n\ndefinition isotone :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"isotone f \\<equiv> \\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y\"\n\nlemma isotoneD: \"\\<lbrakk>isotone f; x \\<le> y\\<rbrakk> \\<Longrightarrow> f x \\<le> f y\"\n  by (metis isotone_def)\n\ndefinition idempotent :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"idempotent f \\<equiv> f \\<circ> f = f\"\n\n(* Lub *)\n\ndefinition is_ub :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"is_ub x A \\<longleftrightarrow> (\\<forall>y\\<in>A. y \\<le> x)\"\n\ndefinition is_lub :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"is_lub x A \\<longleftrightarrow> is_ub x A \\<and> (\\<forall>y.(\\<forall>z\\<in>A. z \\<le> y) \\<longrightarrow> x \\<le> y)\"\n\nlemma is_lub_equiv: \"is_lub x A \\<longleftrightarrow> (\\<forall>z. (x \\<le> z \\<longleftrightarrow> (\\<forall>y\\<in>A. y \\<le> z)))\"\n  by (metis is_lub_def is_ub_def order_refl order_trans)\n\nlemma is_lub_unique: \"is_lub x A \\<longrightarrow> is_lub y A \\<longrightarrow> x = y\"\n  by (metis antisym is_lub_def is_ub_def)\n\ndefinition lub :: \"'a set \\<Rightarrow> 'a\" (\"\\<Sigma>\") where\n  \"\\<Sigma> A = (THE x. is_lub x A)\"\n\nlemma the_lub_leq: \"\\<lbrakk>\\<exists>z. is_lub z X; \\<And>z. is_lub z X \\<longrightarrow> z \\<le> x\\<rbrakk> \\<Longrightarrow> \\<Sigma> X \\<le> x\"\n  by (metis is_lub_unique lub_def the_equality)\n\nlemma the_lub_geq: \"\\<lbrakk>\\<exists>z. is_lub z X; \\<And>z. is_lub z X \\<Longrightarrow> x \\<le> z\\<rbrakk> \\<Longrightarrow> x \\<le> \\<Sigma> X\"\n  by (metis is_lub_unique lub_def the_equality)\n\nlemma singleton_lub: \"\\<Sigma> {y} = y\"\n  by (simp only: lub_def, rule the_equality, simp_all add: is_lub_def is_ub_def, metis eq_iff)\n\nlemma surjective_lub: \"surj \\<Sigma>\"\n  by (metis singleton_lub surj_def)\n\nlemma lub_subset: \"\\<lbrakk>X \\<subseteq> Y; is_lub x X; is_lub y Y\\<rbrakk> \\<Longrightarrow> x \\<le> y\" by (metis in_mono is_lub_def is_ub_def)\n\nlemma lub_is_lub [elim?]: \"is_lub w A \\<Longrightarrow> \\<Sigma> A = w\"\n  by (metis is_lub_unique lub_def the_equality)\n\ndefinition is_lb :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"is_lb x A \\<longleftrightarrow> (\\<forall>y\\<in>A. x \\<le> y)\"\n\ndefinition is_glb :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"is_glb x A \\<longleftrightarrow> is_lb x A \\<and> (\\<forall>y.(\\<forall>z\\<in>A. y \\<le> z) \\<longrightarrow> y \\<le> x)\"\n\nlemma is_glb_equiv: \"is_glb x A \\<longleftrightarrow> (\\<forall>z. (z \\<le> x \\<longleftrightarrow> (\\<forall>y\\<in>A. z \\<le> y)))\"\n  by (metis is_glb_def is_lb_def order_refl order_trans)\n\nlemma is_glb_unique: \"is_glb x A \\<longrightarrow> is_glb y A \\<longrightarrow> x = y\"\n  by (metis antisym is_glb_def is_lb_def)\n\ndefinition glb :: \"'a set \\<Rightarrow> 'a\" (\"\\<Pi>\") where\n  \"\\<Pi> A = (THE x. is_glb x A)\"\n\nlemma the_glb_leq: \"\\<lbrakk>\\<exists>z. is_glb z X; \\<And>z. is_glb z X \\<longrightarrow> x \\<le> z\\<rbrakk> \\<Longrightarrow> x \\<le> \\<Pi> X\"\n  by (metis glb_def is_glb_unique the_equality)\n\nlemma glb_is_glb [elim?]: \"is_glb w A \\<Longrightarrow> \\<Pi> A = w\"\n  by (metis is_glb_unique glb_def the_equality)\n\nlemma is_glb_from_is_lub: \"\\<lbrakk>is_lub x {b. \\<forall>a\\<in>A. b \\<le> a}\\<rbrakk> \\<Longrightarrow> is_glb x A\"\n  by (smt mem_Collect_eq is_glb_def is_lb_def is_lub_equiv order_refl)\n\nlemma is_lub_from_is_glb: \"\\<lbrakk>is_glb x {b. \\<forall>a\\<in>A. a \\<le> b}\\<rbrakk> \\<Longrightarrow> is_lub x A\"\n  by (smt mem_Collect_eq is_lub_def is_ub_def is_glb_equiv order_refl)\n\ndefinition join :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<squnion>\" 70) where\n  \"x \\<squnion> y = \\<Sigma> {x,y}\"\n\ndefinition meet :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<sqinter>\" 70) where\n  \"x \\<sqinter> y = \\<Pi> {x,y}\"\n\n(* Join and meet preserving maps *)\n\ndefinition ex_join_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"ex_join_preserving f \\<equiv> \\<forall>X\\<subseteq>UNIV. (\\<exists>x. is_lub x X) \\<longrightarrow> \\<Sigma> (f ` X) = f (\\<Sigma> X)\"\n\ndefinition ex_meet_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"ex_meet_preserving g \\<equiv> \\<forall>X\\<subseteq>UNIV. (\\<exists>x. is_glb x X) \\<longrightarrow> \\<Pi> (g ` X) = g (\\<Pi> X)\"\n\ndefinition join_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"join_preserving f \\<equiv> \\<forall>X\\<subseteq>UNIV. \\<Sigma> (f ` X) = f (\\<Sigma> X)\"\n\ndefinition meet_preserving :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"meet_preserving g \\<equiv> \\<forall>X\\<subseteq>UNIV. \\<Pi> (g ` X) = g (\\<Pi> X)\"\n\nlemma is_lub_to_is_glb_var: \"order.is_lub (\\<lambda>x y. y \\<le> x) z {x, y} = is_glb z {x, y}\"\nproof -\n  interpret int: order \"\\<lambda>(x::'a) y. y \\<le> x\" \"\\<lambda>x y. y < x\" apply unfold_locales\n    apply (metis less_le_not_le)\n    apply (metis eq_refl)\n    apply (metis order_trans)\n    by (metis eq_iff)\n  show ?thesis by (simp add: int.is_lub_def int.is_ub_def is_glb_def is_lb_def)\nqed\n\nend\n\n(* Join and meet semilattices *)\n\nclass join_semilattice = order +\n  assumes join_ex: \"\\<forall>x y. \\<exists>z. is_lub z {x,y}\"\n\nbegin\n\n  lemma leq_def_join: \"x \\<le> y \\<longleftrightarrow> x\\<squnion>y = y\"\n    by (smt emptyE insertCI insertE is_lub_def is_ub_def join_ex le_less less_le_not_le lub_is_lub ord_eq_le_trans join_def)\n\n  lemma join_idem: \"x \\<squnion> x = x\" by (metis leq_def_join order_refl)\n\n  lemma join_comm: \"x \\<squnion> y = y \\<squnion> x\" by (metis insert_commute join_def)\n\n  lemma join_assoc: \"(x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n  proof -\n    have \"(x \\<squnion> y) \\<squnion> z \\<le> x \\<squnion> (y \\<squnion> z)\"\n      by (simp add: join_def, smt insertCI insertE is_lub_def is_lub_equiv is_ub_def join_ex lub_is_lub singletonE)\n    thus ?thesis\n      by (simp add: join_def, smt insertCI insertE is_lub_def is_ub_def join_ex lub_is_lub order_trans singletonE eq_iff)\n  qed\n\n  lemma ex_join_preserving_iso: \"ex_join_preserving f \\<Longrightarrow> isotone f\"\n  proof (rule classical)\n    assume not_iso: \"\\<not> isotone f\" and join_pres: \"ex_join_preserving f\"\n    obtain x and y where xy: \"x \\<le> y \\<and> \\<not> (f x \\<le> f y)\" by (metis isotone_def not_iso)\n    have \"\\<exists>z. is_lub z {x,y}\" by (metis join_ex)\n    hence \"f (\\<Sigma> {x,y}) = \\<Sigma> {f x, f y}\"\n      by (smt ex_join_preserving_def join_pres subset_UNIV image_empty image_insert)\n    hence \"x = y\" by (metis join_def leq_def_join xy)\n    thus \"isotone f\" by (metis order_refl xy)\n  qed\n\nend\n\nclass meet_semilattice = order +\n  assumes meet_ex: \"\\<forall>x y. \\<exists>z. is_glb z {x,y}\"\n\nsublocale meet_semilattice \\<subseteq> dual!: join_semilattice\n  \"op \\<ge>\" \"op >\"\nproof\n  fix x y z :: 'a\n  show \"(y < x) = (y \\<le> x \\<and> \\<not> x \\<le> y)\" using less_le_not_le .\n  show \"x \\<le> x\" by simp\n  show \"\\<lbrakk>y \\<le> x; z \\<le> y\\<rbrakk> \\<Longrightarrow> z \\<le> x\" by simp\n  show \"\\<lbrakk>y \\<le> x; x \\<le> y\\<rbrakk> \\<Longrightarrow> x = y\" by simp\n  have \"\\<forall>x y. \\<exists>z. order.is_glb (\\<lambda>x y. x \\<le> y) z {x, y}\" by (metis meet_ex)\n  thus \"\\<forall>x y. \\<exists>z. order.is_lub (\\<lambda>x y. y \\<le> x) z {x, y}\" by (metis is_lub_to_is_glb_var)\nqed\n\ncontext meet_semilattice\nbegin\n\n  lemma leq_def2: \"x \\<le> y \\<longleftrightarrow> y\\<sqinter>x = x\"\n    by (smt antisym emptyE glb_is_glb insertCI insertE is_glb_def is_lb_def meet_def meet_ex ord_le_eq_trans order_refl)\n\n  lemma mult_idem: \"x \\<sqinter> x = x\"\n    by (metis leq_def2 order_refl)\n\n  lemma mult_comm: \"x \\<sqinter> y = y \\<sqinter> x\"\n    by (metis insert_commute meet_def)\n\n  lemma bin_glb_var: \"x\\<sqinter>y \\<ge> z \\<longleftrightarrow> x \\<ge> z \\<and> y \\<ge> z\"\n  proof\n    assume a: \"z \\<le> x\\<sqinter>y\"\n    hence \"\\<Pi> {x,z} = z\" by (metis leq_def2 glb_is_glb insertI1 is_glb_equiv meet_ex meet_def)\n    moreover have \"\\<Pi> {y,z} = z\" by (metis a leq_def2 glb_is_glb insertI1 is_glb_equiv meet_ex mult_comm meet_def)\n    ultimately show \"z \\<le> x \\<and> z \\<le> y\" by (metis leq_def2 meet_def)\n  next\n    assume \"z \\<le> x \\<and> z \\<le> y\"\n    thus \"z \\<le> x \\<sqinter> y\"\n      by (smt emptyE glb_is_glb insertE is_glb_equiv meet_ex meet_def ord_le_eq_trans)\n  qed\n\n  lemma mult_assoc: \"(x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n  proof -\n    have \"(x \\<sqinter> y) \\<sqinter> z \\<le> x \\<sqinter> (y \\<sqinter> z)\"\n      by (metis eq_refl bin_glb_var)\n    thus ?thesis\n      by (metis antisym bin_glb_var order_refl)\n  qed\n\n  lemma ex_meet_preserving_iso: \"ex_meet_preserving f \\<Longrightarrow> isotone f\"\n  proof (rule classical)\n    assume not_iso: \"\\<not> isotone f\" and meet_pres: \"ex_meet_preserving f\"\n    obtain x and y where xy: \"x \\<le> y \\<and> \\<not> (f x \\<le> f y)\" by (metis isotone_def not_iso)\n    have \"\\<exists>z. is_glb z {x,y}\" by (metis meet_ex)\n    hence \"f (\\<Pi> {x,y}) = \\<Pi> {f x, f y}\"\n      by (smt ex_meet_preserving_def meet_pres subset_UNIV image_empty image_insert)\n    hence \"x = y\" by (metis leq_def2 meet_def mult_comm xy)\n    thus \"isotone f\" by (metis order_refl xy)\n  qed\n\nend\n\n(* Lattices *)\n\nclass lattice = join_semilattice + meet_semilattice\n\nbegin\n\n  lemma absorb1: \"x \\<squnion> (x \\<sqinter> y) = x\" by (metis join_comm leq_def2 leq_def_join mult_assoc mult_idem)\n\n  lemma absorb2: \"x \\<sqinter> (x \\<squnion> y) = x\" by (metis join_assoc join_idem leq_def2 leq_def_join mult_comm)\n\n  lemma order_change: \"x\\<sqinter>y = y \\<longleftrightarrow> y\\<squnion>x = x\" by (metis leq_def2 leq_def_join)\n\nend\n\n(* Complete join semilattices *)\n\nclass complete_join_semilattice = order +\n  assumes  lub_ex: \"\\<exists>x. is_lub x A\"\n\nsublocale complete_join_semilattice \\<subseteq> join_semilattice\n  by (unfold_locales, metis lub_ex)\n\ncontext complete_join_semilattice\nbegin\n\n  lemma bot_ax: \"\\<exists>!b. \\<forall>x. b \\<le> x\" by (metis empty_iff eq_iff is_lub_def lub_ex)\n\n  definition bot :: \"'a\" (\"\\<bottom>\") where \"\\<bottom> \\<equiv> THE x. \\<forall> y. x \\<le> y\"\n\n  lemma prop_bot: \"\\<forall>x. \\<bottom> \\<le> x\"\n    by (simp only: bot_def, rule the1I2, smt bot_ax, metis)\n\n  lemma is_lub_lub [intro?]: \"is_lub (\\<Sigma> X) X\"\n    by (metis lub_ex lub_is_lub)\n\n  lemma lub_greatest [intro?]: \"(\\<And>y. y \\<in> X \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> \\<Sigma> X \\<le> x\"\n    by (metis is_lub_equiv is_lub_lub)\n\n  lemma lub_least [intro?]: \"x \\<in> X \\<Longrightarrow> x \\<le> \\<Sigma> X\"\n    by (metis is_lub_def is_lub_lub is_ub_def)\n\n  lemma empty_lub [simp]: \"\\<Sigma> {} = \\<bottom>\" by (metis emptyE is_lub_equiv lub_is_lub prop_bot)\n\n  lemma bot_oner [simp]: \"x \\<squnion> \\<bottom> = x\" by (metis join_comm leq_def_join prop_bot)\n  lemma bot_onel [simp]: \"\\<bottom> \\<squnion> x = x\" by (metis leq_def_join prop_bot)\n\nend\n\n\n(* Complete meet semilattice *)\n\nclass complete_meet_semilattice = order +\n  assumes glb_ex: \"\\<exists>x. is_glb x A\"\n\nsublocale complete_meet_semilattice \\<subseteq> meet_semilattice\n  by (unfold_locales, metis glb_ex)\n\ncontext complete_meet_semilattice\nbegin\n\n  lemma top_ax: \"\\<exists>!t. \\<forall>x. x \\<le> t\" by (metis empty_iff eq_iff glb_ex is_glb_def)\n\n  definition top :: \"'a\" (\"\\<top>\") where \"\\<top> \\<equiv> THE x. \\<forall> y. y \\<le> x\"\n\n  lemma prop_top: \"\\<forall>x. x \\<le> \\<top>\"\n    by (simp only: top_def, rule the1I2, metis top_ax, metis)\n\n lemma is_glb_glb [intro?]: \"is_glb (\\<Pi> X) X\"\n   by (metis glb_ex glb_is_glb)\n\n  lemma glb_greatest [intro?]: \"(\\<And>y. y \\<in> X \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> x \\<le> \\<Pi> X\"\n    by (metis is_glb_def is_glb_glb)\n\n  lemma glb_least [intro?]: \"x \\<in> X \\<Longrightarrow> \\<Pi> X \\<le> x\"\n    by (metis is_glb_def is_glb_glb is_lb_def)\n\n  lemma empty_glb [simp]: \"\\<Pi> {} = \\<top>\" by (metis empty_iff glb_is_glb is_glb_def is_lb_def prop_top)\n\nend\n\nclass complete_lattice = complete_join_semilattice + complete_meet_semilattice\n\nbegin\n\n  lemma univ_lub: \"\\<Sigma> UNIV = \\<top>\" by (metis eq_iff is_lub_equiv iso_tuple_UNIV_I lub_is_lub prop_top)\n\n  lemma univ_glb: \"\\<Pi> UNIV = \\<bottom>\" by (metis eq_iff glb_is_glb is_glb_equiv iso_tuple_UNIV_I prop_bot)\n\nend\n\nsublocale complete_lattice \\<subseteq> lattice\n  by unfold_locales\n\n(*\nsublocale complete_join_semilattice \\<subseteq> complete_lattice\n  by (unfold_locales, smt is_lub_lub mem_Collect_eq is_glb_from_is_lub)\n\nsublocale complete_meet_semilattice \\<subseteq> complete_lattice\n  by (unfold_locales, smt is_glb_glb mem_Collect_eq is_lub_from_is_glb)\n*)\n\ndefinition order_monomorphism :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"order_monomorphism f \\<equiv> \\<forall>x y. (f x \\<le> f y) \\<longleftrightarrow> (x \\<le> y)\"\n\ndefinition order_isomorphism :: \"('a::order \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"order_isomorphism f \\<equiv> order_monomorphism f \\<and> surj f\"\n\nlemma order_monomorphism_inj: \"order_monomorphism f \\<Longrightarrow> inj f\"\n  by (simp add: order_monomorphism_def inj_on_def order_eq_iff)\n\nlemma order_monomorphism_iso: \"order_monomorphism f \\<Longrightarrow> isotone f\"\n  by (simp add: order_monomorphism_def isotone_def)\n\n(* +------------------------------------------------------------------------+\n   | Fixpoints and Prefix Points                                            |\n   +------------------------------------------------------------------------+ *)\n\ncontext complete_lattice\nbegin\n\ndefinition is_pre_fp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_pre_fp x f \\<equiv> f x \\<le> x\"\n\ndefinition is_post_fp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_post_fp x f \\<equiv> x \\<le> f x\"\n\ndefinition is_fp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_fp x f \\<equiv> f x = x\"\n\nlemma is_fp_def_var: \"is_fp x f = (is_pre_fp x f \\<and> is_post_fp x f)\"\n  by (metis antisym eq_refl is_fp_def is_post_fp_def is_pre_fp_def)\n\ndefinition is_lpp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lpp x f \\<equiv> (is_pre_fp x f) \\<and> (\\<forall>y. f y \\<le> y \\<longrightarrow> x \\<le> y)\"\n\nlemma is_lpp_def_var: \"is_lpp x f = (f x \\<le> x \\<and> (\\<forall>y. f y \\<le> y \\<longrightarrow> x \\<le> y))\"\n  by (metis is_lpp_def is_pre_fp_def)\n\ndefinition is_gpp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gpp x f \\<equiv> (is_post_fp x f) \\<and> (\\<forall>y. y \\<le> f y \\<longrightarrow> y \\<le> x)\"\n\nlemma is_gpp_def_var: \"is_gpp x f = (x \\<le> f x \\<and> (\\<forall>y. y \\<le> f y \\<longrightarrow> y \\<le> x))\"\n  by (metis is_gpp_def is_post_fp_def)\n\ndefinition is_lfp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_lfp x f \\<equiv> is_fp x f \\<and> (\\<forall>y. is_fp y f \\<longrightarrow> x \\<le> y)\"\n\ndefinition is_gfp :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"is_gfp x f \\<equiv> is_fp x f \\<and> (\\<forall>y. is_fp y f \\<longrightarrow> y \\<le> x)\"\n\ndefinition least_prefix_point :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<mu>\\<^sub>\\<le>\") where\n  \"least_prefix_point f \\<equiv> THE x. is_lpp x f\"\n\ndefinition greatest_postfix_point :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<nu>\\<^sub>\\<le>\") where\n  \"greatest_postfix_point f \\<equiv> THE x. is_gpp x f\"\n\ndefinition least_fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<mu>\") where\n  \"least_fixpoint f \\<equiv> THE x. is_lfp x f\"\n\ndefinition greatest_fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\" (\"\\<nu>\") where\n  \"greatest_fixpoint f \\<equiv> THE x. is_gfp x f\"\n\nlemma lpp_unique: \"\\<lbrakk>is_lpp x f; is_lpp y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (metis eq_iff is_lpp_def_var)\n\nlemma gpp_unique: \"\\<lbrakk>is_gpp x f; is_gpp y f\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (metis eq_iff is_gpp_def_var)\n\nlemma lpp_equality [intro?]: \"is_lpp x f \\<Longrightarrow> \\<mu>\\<^sub>\\<le> f = x\"\n  by (simp add: least_prefix_point_def, rule the_equality, auto, metis antisym is_lpp_def is_pre_fp_def)\n\nlemma gpp_equality [intro?]: \"is_gpp x f \\<Longrightarrow> \\<nu>\\<^sub>\\<le> f = x\"\n  by (simp add: greatest_postfix_point_def, rule the_equality, auto, metis antisym is_gpp_def is_post_fp_def)\n\nlemma lfp_equality: \"is_lfp x f \\<Longrightarrow> \\<mu> f = x\"\n  by (simp add: least_fixpoint_def, rule the_equality, auto, metis antisym is_lfp_def)\n\nlemma lfp_equality_var [intro?]: \"\\<lbrakk>f x = x; \\<And>y. f y = y \\<Longrightarrow> x \\<le> y\\<rbrakk> \\<Longrightarrow> x = \\<mu> f\"\nby (metis is_fp_def is_lfp_def lfp_equality)\n\nlemma gfp_equality: \"is_gfp x f \\<Longrightarrow> \\<nu> f = x\"\n  by (simp add: greatest_fixpoint_def, rule the_equality, auto, metis antisym is_gfp_def)\n\nlemma gfp_equality_var [intro?]: \"\\<lbrakk>f x = x; \\<And>y. f y = y \\<Longrightarrow> y \\<le> x\\<rbrakk> \\<Longrightarrow> x = \\<nu> f\"\nby (metis gfp_equality is_fp_def is_gfp_def)\n\nlemma lpp_is_lfp: \"\\<lbrakk>isotone f; is_lpp x f\\<rbrakk> \\<Longrightarrow> is_lfp x f\"\nby (metis dual.antisym dual.eq_refl is_fp_def is_lfp_def is_lpp_def_var isotoneD)\n\nlemma gpp_is_gfp: \"\\<lbrakk>isotone f; is_gpp x f\\<rbrakk> \\<Longrightarrow> is_gfp x f\"\nby (metis dual.antisym dual.order_refl is_fp_def is_gfp_def is_gpp_def_var isotoneD)\n\n(* +------------------------------------------------------------------------+\n   | Knaster-Tarski                                                         |\n   +------------------------------------------------------------------------+ *)\n\n(* Modified version of Wenzel's proof of the Knaster-Tarski theorem *)\n\ntheorem knaster_tarski_lpp:\n  assumes fmon: \"isotone f\"\n  obtains a where \"is_lpp a f\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Pi> ?H\"\n  have \"is_pre_fp ?a f\"\n  proof -\n    have \"\\<forall>x\\<in>?H. ?a \\<le> x\" by (metis glb_least)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<le> f x\" by (metis assms glb_least isotoneD)\n    hence \"\\<forall>x\\<in>?H. f ?a \\<le> x\" by (metis mem_Collect_eq order_trans)\n    hence \"f ?a \\<le> \\<Pi> ?H\" by (smt glb_greatest)\n    thus ?thesis by (metis is_pre_fp_def)\n  qed\n  moreover have \"f y \\<le> y \\<Longrightarrow> ?a \\<le> y\"\n    by (metis mem_Collect_eq glb_least)\n  ultimately show \"is_lpp ?a f\"\n    by (smt is_lpp_def mem_Collect_eq glb_least)\nqed\n\ncorollary is_lpp_lpp [intro?]: \"isotone f \\<Longrightarrow> is_lpp (\\<mu>\\<^sub>\\<le> f) f\"\n  using knaster_tarski_lpp by (metis lpp_equality)\n\ntheorem knaster_tarski:\n  assumes fmon: \"isotone f\"\n  obtains a where \"is_lfp a f\"\n  by (metis assms is_lpp_lpp lpp_is_lfp)\n\ncorollary knaster_tarski_var: \"isotone f \\<Longrightarrow> \\<exists>!x. is_lfp x f\"\n  using knaster_tarski by (metis lfp_equality)\n\ncorollary is_lfp_lfp [intro?]: \"isotone f \\<Longrightarrow> is_lfp (\\<mu> f) f\"\n  using knaster_tarski by (metis lfp_equality)\n\n(* Knaster-Tarski for greatest fixpoints *)\n\ntheorem knaster_tarski_gpp:\n  assumes fmon: \"isotone f\"\n  obtains a :: \"'a\" where \"is_gpp a f\"\nproof\n  let ?H = \"{u. u \\<le> f u}\"\n  let ?a = \"\\<Sigma> ?H\"\n  have \"is_post_fp ?a f\"\n  proof -\n    have \"\\<forall>x\\<in>?H. x \\<le> ?a\" by (metis lub_least)\n    hence \"\\<forall>x\\<in>?H. x \\<le> f ?a\"\n      by (metis (full_types) mem_Collect_eq assms lub_least isotoneD order_trans)\n    hence \"\\<Sigma> ?H \\<le> f ?a\" by (smt lub_greatest)\n    thus ?thesis by (metis is_post_fp_def)\n  qed\n  moreover have \"y \\<le> f y \\<Longrightarrow> y \\<le> ?a\"\n    by (metis mem_Collect_eq lub_least order_refl)\n  ultimately show \"is_gpp ?a f\"\n    by (smt is_gpp_def mem_Collect_eq lub_least)\nqed\n\ncorollary is_gpp_gpp [intro?]: \"isotone f \\<Longrightarrow> is_gpp (\\<nu>\\<^sub>\\<le> f) f\"\nby (metis gpp_equality knaster_tarski_gpp)\n\ntheorem knaster_tarski_greatest:\n  assumes fmon: \"isotone f\"\n  obtains a :: \"'a\" where \"is_gfp a f\"\n  by (metis assms is_gpp_gpp gpp_is_gfp)\n\ncorollary knaster_tarski_greatest_var: \"isotone f \\<Longrightarrow> \\<exists>!x. is_gfp x f\"\nby (metis gfp_equality knaster_tarski_greatest)\n\ncorollary is_gfp_gfp [intro?]: \"isotone f \\<Longrightarrow> is_gfp (\\<nu> f) f\"\nby (metis gfp_equality knaster_tarski_greatest_var)\n\nlemma lfp_is_lpp: \"\\<lbrakk>isotone f; is_lfp x f\\<rbrakk> \\<Longrightarrow>  is_lpp x f\"\n  by (metis lfp_equality lpp_is_lfp is_lpp_lpp)\n\nlemma lfp_is_lpp_var: \"isotone f \\<Longrightarrow> \\<mu> f = \\<mu>\\<^sub>\\<le> f\"\n  by (metis lfp_is_lpp lpp_equality is_lfp_lfp)\n\nlemma gfp_is_gpp: \"\\<lbrakk>isotone f; is_gfp x f\\<rbrakk> \\<Longrightarrow>  is_gpp x f\"\n  by (metis gfp_equality gpp_is_gfp is_gpp_gpp)\n\nlemma gfp_is_gpp_var: \"isotone f \\<Longrightarrow> \\<nu> f = \\<nu>\\<^sub>\\<le> f\"\n  by (metis gfp_is_gpp gpp_equality is_gfp_gfp)\n\n(* We now show some more properties of fixpoints *)\n\n(* +------------------------------------------------------------------------+\n   | Fixpoint Computation                                                   |\n   +------------------------------------------------------------------------+ *)\n\nlemma prefix_point_computation [simp]: \"isotone f \\<Longrightarrow> f (\\<mu>\\<^sub>\\<le> f) = \\<mu>\\<^sub>\\<le> f\"\n  by (metis is_lpp_lpp lpp_is_lfp is_lfp_def is_fp_def)\n\nlemma fixpoint_computation [simp]: \"isotone f \\<Longrightarrow> f (\\<mu> f) = \\<mu> f\"\n  by (metis is_lpp_lpp lfp_equality lpp_is_lfp prefix_point_computation)\n\nlemma greatest_prefix_point_computation [simp]: \"isotone f \\<Longrightarrow> f (\\<nu>\\<^sub>\\<le> f) = \\<nu>\\<^sub>\\<le> f\"\n  by (metis is_gpp_gpp gpp_is_gfp is_gfp_def is_fp_def)\n\nlemma greatest_fixpoint_computation [simp]: \"isotone f \\<Longrightarrow> f (\\<nu> f) = \\<nu> f\"\n  by (metis is_gpp_gpp gfp_equality gpp_is_gfp greatest_prefix_point_computation)\n\n(* +------------------------------------------------------------------------+\n   | Fixpoint Induction                                                     |\n   +------------------------------------------------------------------------+ *)\n\nlemma prefix_point_induction [intro?]:\n  assumes fmon: \"isotone f\"\n  and pp: \"f x \\<le> x\"\n  shows \"\\<mu>\\<^sub>\\<le> f \\<le> x\"\n  by (metis fmon is_lpp_def_var is_lpp_lpp pp)\n\nlemma fixpoint_induction [intro?]:\n  assumes fmon: \"isotone f\"\n  and fp: \"f x \\<le> x\" shows \"\\<mu> f \\<le> x\"\nby (metis fmon fp lfp_is_lpp_var prefix_point_induction)\n\n\nlemma greatest_postfix_point_induction [intro?]:\n  assumes fmon: \"isotone f\"\n  and pp: \"x \\<le> f x\" shows \"x \\<le> \\<nu>\\<^sub>\\<le> f\"\n  by (metis fmon is_gpp_def is_gpp_gpp pp)\n\nlemma greatest_fixpoint_induction [intro?]:\n  assumes fmon: \"isotone f\"\n  and fp: \"x \\<le> f x\" shows \"x \\<le> \\<nu> f\"\n  by (metis fmon fp gfp_is_gpp_var greatest_postfix_point_induction)\n\nlemma fixpoint_compose:\n  assumes kmon: \"isotone k\" and comp: \"g\\<circ>k = k\\<circ>h\" and fp: \"is_fp x h\"\n  shows \"is_fp (k x) g\"\n  by (metis comp fp is_fp_def o_apply)\n\nlemma fixpoint_mono:\n  assumes fmon: \"isotone f\" and gmon: \"isotone g\"\n  and fg: \"f \\<sqsubseteq> g\" shows \"\\<mu> f \\<le> \\<mu> g\"\n  by (metis fg fixpoint_induction fmon gmon lfp_is_lpp_var pleq_def prefix_point_computation)\n\nlemma greatest_fixpoint_mono:\n  assumes fmon: \"isotone f\" and gmon: \"isotone g\"\n  and fg: \"f \\<sqsubseteq> g\" shows \"\\<nu> f \\<le> \\<nu> g\"\n  by (metis fg fmon gfp_is_gpp_var gmon greatest_fixpoint_induction greatest_prefix_point_computation pleq_def)\n\nend\n\n(* +------------------------------------------------------------------------+\n   | Galois Connections                                                     |\n   +------------------------------------------------------------------------+ *)\n\ncontext order\nbegin\n\ndefinition galois_connection :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"galois_connection f g \\<equiv> \\<forall>x y. (f x \\<le> y) \\<longleftrightarrow> (x \\<le> g y)\"\n\ndefinition dual_galois_connection :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"dual_galois_connection f g \\<equiv> \\<forall>x y. (f x \\<ge> y) \\<longleftrightarrow> (x \\<ge> g y)\"\n\ndefinition lower_adjoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"lower_adjoint f \\<equiv> \\<exists>g. galois_connection f g\"\n\ndefinition upper_adjoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"upper_adjoint g \\<equiv> \\<exists>f. galois_connection f g\"\n\nlemma deflation: \"galois_connection f g \\<Longrightarrow> f (g y) \\<le> y\"\n  by (metis galois_connection_def le_less)\n\nlemma inflation: \"galois_connection f g \\<Longrightarrow> x \\<le> g (f x)\"\n  by (metis galois_connection_def le_less)\n\nlemma lower_iso: \"galois_connection f g \\<Longrightarrow> isotone f\"\n  by (metis galois_connection_def inflation isotone_def order_trans)\n\n\nlemma upper_iso: \"galois_connection f g \\<Longrightarrow> isotone g\"\n  by (metis deflation galois_connection_def isotone_def order_trans)\n\nlemma lower_comp: \"galois_connection f g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\nproof\n  fix x\n  assume \"galois_connection f g\"\n  thus \"(f \\<circ> g \\<circ> f) x = f x\"\n    by (metis (full_types) antisym deflation inflation isotone_def lower_iso o_apply)\nqed\n\nlemma upper_comp: \"galois_connection f g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\nproof\n  fix x\n  assume \"galois_connection f g\"\n  thus \"(g \\<circ> f \\<circ> g) x = g x\"\n    by (metis (full_types) antisym deflation inflation isotone_def o_apply upper_iso)\nqed\n\nlemma upper_idempotency1: \"galois_connection f g \\<Longrightarrow> idempotent (f \\<circ> g)\"\n  by (metis idempotent_def o_assoc upper_comp)\n\nlemma upper_idempotency2: \"galois_connection f g \\<Longrightarrow> idempotent (g \\<circ> f)\"\n  by (metis idempotent_def o_assoc lower_comp)\n\nlemma galois_dual: \"galois_connection f g \\<Longrightarrow> dual_galois_connection g f\"\n  by (metis dual_galois_connection_def galois_connection_def)\n\nlemma dual_galois_dual: \"dual_galois_connection f g \\<Longrightarrow> galois_connection g f\"\n  by (metis dual_galois_connection_def galois_connection_def)\n\nlemma galois_dualize: \"\\<lbrakk>galois_connection F G \\<Longrightarrow> P F G; dual_galois_connection G F\\<rbrakk> \\<Longrightarrow> P F G\"\n  by (metis dual_galois_dual)\n\nlemma dual_galois_dualize: \"\\<lbrakk>dual_galois_connection F G \\<Longrightarrow> P F G; galois_connection G F\\<rbrakk> \\<Longrightarrow> P F G\"\n  by (metis galois_dual)\n\nlemma galois_comp: assumes g1: \"galois_connection F G\" and g2 :\"galois_connection H K\"\n  shows \"galois_connection (F \\<circ> H) (K \\<circ> G)\"\n  by (smt g1 g2 galois_connection_def o_apply)\n\nlemma galois_id: \"galois_connection id id\" by (metis galois_connection_def id_def)\n\nlemma galois_isotone1: \"galois_connection f g \\<Longrightarrow> isotone (g \\<circ> f)\"\n  by (smt galois_connection_def inflation isotoneD isotone_def o_apply order_trans upper_iso)\n\nlemma galois_isotone2: \"galois_connection f g \\<Longrightarrow> isotone (f \\<circ> g)\"\nby (metis isotone_def lower_iso o_apply upper_iso)\n\nlemma point_id1: \"galois_connection f g \\<Longrightarrow> id \\<sqsubseteq> g \\<circ> f\"\n  by (metis inflation id_apply o_apply pleq_def)\n\nlemma point_id2: \"galois_connection f g \\<Longrightarrow> f \\<circ> g \\<sqsubseteq> id\"\n  by (metis deflation id_apply o_apply pleq_def)\n\nlemma point_cancel: assumes g: \"galois_connection f g\" shows \"f \\<circ> g \\<sqsubseteq> g \\<circ> f\"\nby (metis assms order_trans pleq_def point_id1 point_id2)\n\nlemma cancel: assumes g: \"galois_connection f g\" shows \"f (g x) \\<le> g (f x)\"\nby (metis assms deflation inflation order_trans)\n\nlemma cancel_cor1: assumes g: \"galois_connection f g\"\n  shows \"(g x = g y) \\<longleftrightarrow> (f (g x) = f (g y))\"\n  by (metis assms upper_comp o_apply)\n\nlemma cancel_cor2: assumes g: \"galois_connection f g\"\n  shows \"(f x = f y) \\<longleftrightarrow> (g (f x) = g (f y))\"\n  by (metis assms lower_comp o_apply)\n\nlemma semi_inverse1: \"galois_connection f g \\<Longrightarrow> f x = f (g (f x))\"\n  by (metis o_def lower_comp)\n\nlemma semi_inverse2: \"galois_connection f g \\<Longrightarrow> g x = g (f (g x))\"\n  by (metis o_def upper_comp)\n\nlemma universal_mapping_property1:\n  assumes a: \"isotone g\" and b: \"\\<forall>x. x \\<le> g (f x)\"\n  and c: \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n  shows \"galois_connection f g\"\n  by (metis a b c galois_connection_def isotoneD order_trans)\n\nlemma universal_mapping_property2:\n  assumes a: \"isotone f\" and b: \"\\<forall>x. f (g x) \\<le> x\"\n  and c: \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n  shows \"galois_connection f g\"\n  by (metis a b c galois_connection_def isotoneD order_trans)\n\nlemma galois_ump2: \"galois_connection f g = (isotone f \\<and> (\\<forall>y. f (g y) \\<le> y) \\<and> (\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y))\"\n  by (metis deflation dual_galois_connection_def galois_dual lower_iso universal_mapping_property2)\n\nlemma galois_ump1: \"galois_connection f g = (isotone g \\<and> (\\<forall>x. x \\<le> g (f x)) \\<and> (\\<forall>x y. x \\<le> g y \\<longrightarrow> f x \\<le> y))\"\n  by (metis galois_connection_def inflation universal_mapping_property1 upper_iso)\n\n(* +------------------------------------------------------------------------+\n   | Theorem 4.10(a)                                                        |\n   +------------------------------------------------------------------------+ *)\n\nlemma ore_galois:\n  assumes\"\\<forall>x. x \\<le> g (f x)\" and \"\\<forall>x. f (g x) \\<le> x\"\n  and \"isotone f\" and  \"isotone g\"\n  shows \"galois_connection f g\"\n  by (metis assms isotoneD order_trans universal_mapping_property1)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.32(a) and 4.32(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\nlemma perfect1: \"galois_connection f g \\<Longrightarrow> g (f x) = x \\<longleftrightarrow> x \\<in> range g\"\n  by (metis (full_types) image_iff range_eqI semi_inverse2)\n\nlemma perfect2: \"galois_connection f g \\<Longrightarrow> f (g x) = x \\<longleftrightarrow> x \\<in> range f\"\n  by (metis (full_types) image_iff range_eqI semi_inverse1)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.20(a) and 4.20(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\ndefinition is_max :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"is_max x X \\<equiv> x \\<in> X \\<and> is_lub x X\"\n\ndefinition is_min :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"is_min x X \\<equiv> x \\<in> X \\<and> is_glb x X\"\n\nlemma galois_max: assumes conn: \"galois_connection f g\" shows \"is_max (g y) {x. f x \\<le> y}\"\n  by (simp add: is_max_def is_lub_equiv, metis assms galois_ump2 order_trans)\n\nlemma galois_min: assumes conn: \"galois_connection f g\" shows \"is_min (f x) {y. x \\<le> g y}\"\n  by (simp add: is_min_def is_glb_equiv, metis assms galois_ump1 order_trans)\n\ntheorem max_galois: \"galois_connection f g = (isotone f \\<and> (\\<forall>y. is_max (g y) {x. f x \\<le> y}))\"\nproof\n  assume conn: \"galois_connection f g\"\n  show \"isotone f \\<and> (\\<forall>y. is_max (g y) {x. f x \\<le> y})\"\n  proof\n    show \"isotone f\" by (metis conn lower_iso)\n  next\n    show \"\\<forall>y. is_max (g y) {x. f x \\<le> y}\" by (metis conn galois_max)\n  qed\nnext\n  assume \"isotone f \\<and> (\\<forall>y. is_max (g y) {x. f x \\<le> y})\"\n  hence fmon: \"isotone f\" and max: \"\\<forall>y. is_max (g y) {x. f x \\<le> y}\" by auto+\n  show \"galois_connection f g\"\n  proof (rule universal_mapping_property2)\n    show \"isotone f\" by (metis fmon)\n  next\n    have max2: \"\\<forall>y. g y \\<in> {x. f x \\<le> y}\" by (smt is_max_def max)\n    hence \"(g y \\<in> {x. f x \\<le> y}) = (f (g y) \\<le> y)\" by (simp only: mem_Collect_eq)\n    thus p: \"\\<forall>y. f (g y) \\<le> y\" using max2 by auto\n  next\n    show \"\\<forall>x y. f x \\<le> y \\<longrightarrow> x \\<le> g y\"\n    proof clarify\n      fix x and y\n      have lub1: \"is_lub (g y) {x. f x \\<le> y}\"\n        by (smt is_max_def max mem_Collect_eq is_lub_equiv)\n      assume \"f x \\<le> y\"\n      thus \"x \\<le> g y\" by (metis lub1 mem_Collect_eq is_lub_equiv order_refl)\n    qed\n  qed\nqed\n\ncorollary max_galois_rule: \"\\<lbrakk>isotone f; \\<forall>y. is_max (g y) {x. f x \\<le> y}\\<rbrakk> \\<Longrightarrow> galois_connection f g\"\n  by (metis max_galois)\n\ntheorem min_galois: \"galois_connection f g = (isotone g \\<and> (\\<forall>x. is_min (f x) {y. x \\<le> g y}))\"\nproof\n  assume conn: \"galois_connection f g\"\n  show \"isotone g \\<and> (\\<forall>x. is_min (f x) {y. x \\<le> g y})\"\n  proof\n    show \"isotone g\" by (metis conn upper_iso)\n  next\n    show \"\\<forall>x. is_min (f x) {y. x \\<le> g y}\" by (metis conn galois_min)\n  qed\nnext\n  assume \"isotone g \\<and> (\\<forall>x. is_min (f x) {y. x \\<le> g y})\"\n  hence gmon: \"isotone g\" and min: \"\\<forall>x. is_min (f x) {y. x \\<le> g y}\" by auto+\n  show \"galois_connection f g\"\n  proof (rule universal_mapping_property1)\n    show \"isotone g\" by (metis gmon)\n  next\n    have \"\\<forall>x. f x \\<in> {y. x \\<le> g y}\" by (smt is_min_def min)\n    moreover have \"(f x \\<in> {y. x \\<le> g y}) = (x \\<le> g (f x))\" by (simp only: mem_Collect_eq)\n    ultimately show \"\\<forall>x. x \\<le> g (f x)\" by auto\n  next\n    show \"\\<forall>x y. x \\<le> g y \\<longrightarrow> f x \\<le> y\"\n    proof clarify\n      fix x and y\n      have glb1: \"is_glb (f x) {y. x \\<le> g y}\" using is_min_def min\n        by (smt mem_Collect_eq is_glb_equiv)\n      assume \"x \\<le> g y\"\n      thus \"f x \\<le> y\" by (metis glb1 mem_Collect_eq is_glb_equiv order_refl)\n    qed\n  qed\nqed\n\ncorollary min_galois_rule: \"\\<lbrakk>isotone g; \\<forall>x. is_min (f x) {y. x \\<le> g y}\\<rbrakk> \\<Longrightarrow> galois_connection f g\"\n  by (metis min_galois)\n\n(* Corollary 4.21 *)\n\nlemma galois_lub: \"galois_connection f g \\<Longrightarrow> is_lub (g y) {x. f x \\<le> y}\"\n  by (metis galois_max is_max_def)\n\nlemma galois_glb: \"galois_connection f g \\<Longrightarrow> is_glb (f x) {y. x \\<le> g y}\"\n  by (metis galois_min is_min_def)\n\nlemma galois_lub_var: \"galois_connection f g \\<Longrightarrow> g y = \\<Sigma> {x. f x \\<le> y}\"\n  by (metis galois_lub lub_is_lub)\n\nlemma galois_glb_var: \"galois_connection f g \\<Longrightarrow> f x = \\<Pi> {y. x \\<le> g y}\"\n  by (metis galois_glb glb_is_glb)\n\n(* +------------------------------------------------------------------------+\n   | Lemma 4.24(a) and 4.24(b)                                              |\n   +------------------------------------------------------------------------+ *)\n\nlemma lower_lub: \"\\<lbrakk>is_lub x X; lower_adjoint f\\<rbrakk> \\<Longrightarrow> is_lub (f x) (f ` X)\"\n  by (smt galois_ump1 galois_ump2 image_iff is_lub_equiv lower_adjoint_def)\n\nlemma upper_glb: \"\\<lbrakk>is_glb x X; upper_adjoint g\\<rbrakk> \\<Longrightarrow> is_glb (g x) (g ` X)\"\n  apply (simp add: is_glb_def upper_adjoint_def is_lb_def galois_connection_def)\n  by (metis order_refl order_trans)\n\nlemma lower_preserves_joins: assumes lower: \"lower_adjoint f\" shows \"ex_join_preserving f\"\n  by (metis assms ex_join_preserving_def lower_lub lub_is_lub)\n\nlemma upper_preserves_meets: assumes upper: \"upper_adjoint g\" shows \"ex_meet_preserving g\"\n  by (metis assms ex_meet_preserving_def upper_glb glb_is_glb)\n\nend\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.25(a) and 4.25(b)                                           |\n   +------------------------------------------------------------------------+ *)\n\ncontext complete_lattice\nbegin\n\ntheorem suprema_galois: \"galois_connection f g = (ex_join_preserving f \\<and> (\\<forall>y. is_lub (g y) {x. f x \\<le> y}))\"\nproof\n  assume \"galois_connection f g\"\n  thus \"ex_join_preserving f \\<and> (\\<forall>y. is_lub (g y) {x. f x \\<le> y})\"\n    by (metis galois_lub lower_adjoint_def lower_preserves_joins)\nnext\n  assume assms: \"ex_join_preserving f \\<and> (\\<forall>y. is_lub (g y) {x. f x \\<le> y})\"\n  hence elj: \"ex_join_preserving f\" and a2: \"\\<forall>y. is_lub (g y) {x. f x \\<le> y}\" by metis+\n  hence fmon: \"isotone f\" by (metis ex_join_preserving_iso)\n  thus \"galois_connection f g\"\n  proof (simp add: galois_connection_def)\n    have left: \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n      by (metis mem_Collect_eq a2 is_lub_equiv order_refl)\n    moreover have \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n    proof clarify\n      fix x and y\n      assume gr: \"x \\<le> g y\"\n      show \"f x \\<le> y\"\n      proof -\n        have lem: \"\\<Sigma> (f ` {x. f x \\<le> y}) \\<le> y\"\n        proof (rule the_lub_leq)\n          show \"\\<exists>z. is_lub z (f ` {x\\<Colon>'a. f x \\<le> y})\" by (metis lub_ex)\n        next\n          fix z\n          show \"is_lub z (f ` {x\\<Colon>'a. f x \\<le> y}) \\<longrightarrow> z \\<le> y\"\n            by (smt mem_Collect_eq imageE is_lub_equiv)\n        qed\n\n        have \"f x \\<le> y \\<Longrightarrow> x \\<le> \\<Sigma> {z. f z \\<le> y}\" by (metis a2 gr lub_is_lub)\n        moreover have \"x \\<le> \\<Sigma> {z. f z \\<le> y} \\<Longrightarrow> f x \\<le> f (\\<Sigma> {z. f z \\<le> y})\" by (metis fmon isotoneD)\n        moreover have \"(f x \\<le> f (\\<Sigma> {z. f z \\<le> y})) = (f x \\<le> \\<Sigma> (f ` {z. f z \\<le> y}))\"\n          by (metis a2 elj ex_join_preserving_def top_greatest)\n        moreover have \"... \\<Longrightarrow> f x \\<le> y\" using lem by (metis order_trans)\n        ultimately show ?thesis by (metis a2 gr lub_is_lub)\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\" by auto\n  qed\nqed\n\ncorollary suprema_galois_rule:\n  \"\\<lbrakk>ex_join_preserving f; \\<forall>y. is_lub (g y) {x. f x \\<le> y}\\<rbrakk> \\<Longrightarrow> galois_connection f g\"\n  by (metis suprema_galois)\n\ntheorem infima_galois: \"galois_connection f g = (ex_meet_preserving g \\<and> (\\<forall>x. is_glb (f x) {y. x \\<le> g y}))\"\nproof\n  assume \"galois_connection f g\"\n  thus \"ex_meet_preserving g \\<and> (\\<forall>x. is_glb (f x) {y. x \\<le> g y})\"\n    by (metis galois_glb upper_adjoint_def upper_preserves_meets)\nnext\n  assume assms: \"ex_meet_preserving g \\<and> (\\<forall>x. is_glb (f x) {y. x \\<le> g y})\"\n  hence elj: \"ex_meet_preserving g\" and a2: \"\\<forall>x. is_glb (f x) {y. x \\<le> g y}\"  by auto+\n  hence gmon: \"isotone g\" by (metis ex_meet_preserving_iso)\n  thus \"galois_connection f g\"\n  proof (simp add: galois_connection_def)\n    have right: \"\\<forall>x y. (x \\<le> g y) \\<longrightarrow> (f x \\<le> y)\"\n      by (metis mem_Collect_eq a2 is_glb_equiv order_refl)\n    moreover have \"\\<forall>x y. (f x \\<le> y) \\<longrightarrow> (x \\<le> g y)\"\n    proof clarify\n      fix x and y\n      assume gr: \"f x \\<le> y\"\n      show \"x \\<le> g y\"\n      proof -\n        have lem: \"x \\<le> \\<Pi> (g ` {y. x \\<le> g y})\"\n        proof (rule the_glb_leq)\n          show \"\\<exists>z. is_glb z (g ` {y. x \\<le> g y})\" by (metis glb_ex)\n        next\n          fix z\n          show \"is_glb z (g ` {y. x \\<le> g y}) \\<longrightarrow> x \\<le> z\"\n            by (smt mem_Collect_eq imageE is_glb_equiv)\n        qed\n\n        have \"x \\<le> g y \\<Longrightarrow> \\<Pi> {z. x \\<le> g z} \\<le> y\" by (metis a2 gr glb_is_glb)\n        moreover have \"\\<Pi> {z. x \\<le> g z} \\<le> y \\<Longrightarrow> g (\\<Pi> {z. x \\<le> g z}) \\<le> g y\" by (metis gmon isotoneD)\n        moreover have \"(g (\\<Pi> {z. x \\<le> g z}) \\<le> g y) = (\\<Pi> (g ` {z. x \\<le> g z}) \\<le> g y)\"\n          by (metis a2 elj ex_meet_preserving_def top_greatest)\n        moreover have \"... \\<Longrightarrow> x \\<le> g y\" using lem by (metis order_trans)\n        ultimately show ?thesis by (metis a2 gr glb_is_glb)\n      qed\n    qed\n    ultimately show \"\\<forall>x y. (f x \\<le> y) = (x \\<le> g y)\" by auto\n  qed\nqed\n\ncorollary infima_galois_rule:\n  \"\\<lbrakk>ex_meet_preserving g; \\<forall>x. is_glb (f x) {y. x \\<le> g y}\\<rbrakk> \\<Longrightarrow> galois_connection f g\"\n  by (metis infima_galois)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.26 and 4.27                                                 |\n   +------------------------------------------------------------------------+ *)\n\ntheorem cl_lower_join_preserving: \"lower_adjoint f = ex_join_preserving f\"\nproof\n  assume \"lower_adjoint f\" thus \"ex_join_preserving f\"\n    by (metis lower_adjoint_def lower_iso lower_preserves_joins)\nnext\n  assume ejp: \"ex_join_preserving f\"\n  have \"\\<exists>g. \\<forall>y. is_lub (g y) {x. f x \\<le> y}\"\n  proof\n    show \"\\<forall>y. is_lub (\\<Sigma> {x. f x \\<le> y}) {x. f x \\<le> y}\" by (metis lub_ex lub_is_lub)\n  qed\n  thus \"lower_adjoint f\" by (metis lower_adjoint_def ejp suprema_galois)\nqed\n\ntheorem cl_upper_join_preserving: \"upper_adjoint g = ex_meet_preserving g\"\nproof\n  assume \"upper_adjoint g\" thus \"ex_meet_preserving g\"\n    by (metis upper_preserves_meets)\nnext\n  assume emp: \"ex_meet_preserving g\"\n  have \"\\<exists>f. \\<forall>x. is_glb (f x) {y. x \\<le> g y}\"\n  proof\n    show \"\\<forall>x. is_glb (\\<Pi> {y. x \\<le> g y}) {y. x \\<le> g y}\" by (metis glb_ex glb_is_glb)\n  qed\n  thus \"upper_adjoint g\" by (metis emp infima_galois upper_adjoint_def)\nqed\n\nlemma join_preserving_is_ex: \"join_preserving f \\<Longrightarrow> ex_join_preserving f\"\n  by (metis ex_join_preserving_def join_preserving_def)\n\nlemma join_pres2: \"ex_join_preserving f = join_preserving f\"\n  by (metis lub_ex ex_join_preserving_def subset_UNIV join_preserving_def)\n\nlemma meet_preserving_is_ex: \"meet_preserving f = ex_meet_preserving f\"\n  by (metis glb_ex ex_meet_preserving_def subset_UNIV meet_preserving_def)\n\nlemma galois_join_preserving: \"galois_connection f g \\<Longrightarrow> join_preserving f\"\n  by (metis ex_join_preserving_def lub_ex subset_UNIV suprema_galois join_preserving_def)\n\nlemma galois_meet_preserving: \"galois_connection f g \\<Longrightarrow> meet_preserving g\"\n  by (metis ex_meet_preserving_def glb_ex subset_UNIV infima_galois meet_preserving_def)\n\n(* +------------------------------------------------------------------------+\n   | Theorems 4.36 and 4.37                                                 |\n   +------------------------------------------------------------------------+ *)\n\ntheorem upper_exists: \"lower_adjoint f = join_preserving f\"\n  by (metis lower_adjoint_def cl_lower_join_preserving galois_join_preserving join_preserving_is_ex)\n\ntheorem lower_exists: \"upper_adjoint g = meet_preserving g\"\n  by (metis cl_upper_join_preserving meet_preserving_is_ex)\n\n(* +------------------------------------------------------------------------+\n   | Fixpoints and Galois connections                                       |\n   +------------------------------------------------------------------------+ *)\n\nlemma fixpoint_rolling: assumes conn: \"galois_connection f g\"\n  shows \"f (\\<mu> (g \\<circ> f)) = \\<mu> (f \\<circ> g)\"\nproof\n  show \"(f \\<circ> g) (f (\\<mu> (g \\<circ> f))) = f (\\<mu> (g \\<circ> f))\"\n    by (metis assms o_def semi_inverse1)\nnext\n  fix y assume fgy: \"(f \\<circ> g) y = y\"\n  have \"\\<mu> (g \\<circ> f) \\<le> g y\"\n    by (metis assms dual.order_refl fgy fixpoint_induction galois_isotone1 o_eq_dest_lhs)\n  thus \"f (\\<mu> (g \\<circ> f)) \\<le> y\" by (metis conn galois_connection_def)\nqed\n\nlemma greatest_fixpoint_rolling: assumes conn: \"galois_connection f g\"\n  shows \"g (\\<nu> (f \\<circ> g)) = \\<nu> (g \\<circ> f)\"\nproof\n  show \"(g \\<circ> f) (g (\\<nu> (f \\<circ> g))) = g (\\<nu> (f \\<circ> g))\" by (metis assms o_def semi_inverse2)\nnext\n  fix y assume gfy: \"(g \\<circ> f) y = y\"\n  have \"f y \\<le> \\<nu> (f \\<circ> g)\"\nby (metis assms dual.order_refl galois_isotone2 gfy greatest_fixpoint_induction o_eq_dest_lhs)\n  thus \"y \\<le> g (\\<nu> (f \\<circ> g))\" by (metis conn galois_connection_def)\nqed\n\n(* +------------------------------------------------------------------------+\n   | Fixpoint Fusion                                                        |\n   +------------------------------------------------------------------------+ *)\n\n(* uses lfp_equality_var then fixpoint_induction *)\n\ntheorem fixpoint_fusion [simp]:\n  assumes upper_ex: \"lower_adjoint f\"\n  and hiso: \"isotone h\" and kiso: \"isotone k\"\n  and comm: \"f\\<circ>h = k\\<circ>f\"\n  shows \"f (\\<mu> h) = \\<mu> k\"\nproof\n  show \"k (f (\\<mu> h)) = f (\\<mu> h)\" by (metis comm fixpoint_computation hiso o_def)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain g where conn: \"galois_connection f g\" by (metis lower_adjoint_def upper_ex)\n  have \"\\<mu> h \\<le> g y\" using hiso\n  proof (rule fixpoint_induction)\n    have \"f (g y) \\<le> y\" by (metis conn deflation)\n    hence \"f (h (g y)) \\<le> y\" by (metis comm kiso ky isotoneD o_def)\n    thus \"h (g y) \\<le> g y\" by (metis conn galois_connection_def)\n  qed\n  thus \"f (\\<mu> h) \\<le> y\" by (metis conn galois_connection_def)\nqed\n\ntheorem greatest_fixpoint_fusion [simp]:\n  assumes lower_ex: \"upper_adjoint g\"\n  and hiso: \"isotone h\" and kiso: \"isotone k\"\n  and comm: \"g\\<circ>h = k\\<circ>g\"\n  shows \"g (\\<nu> h) = \\<nu> k\"\nproof\n  show \"k (g (\\<nu> h)) = g (\\<nu> h)\" by (metis comm greatest_fixpoint_computation hiso o_def)\nnext\n  fix y assume ky: \"k y = y\"\n  obtain f where conn: \"galois_connection f g\" by (metis lower_ex upper_adjoint_def)\n  have \"f y \\<le> \\<nu> h\" using hiso\n  proof (rule greatest_fixpoint_induction)\n    have \"y \\<le> g (f y)\" by (metis conn inflation)\n    hence \"y \\<le> g (h (f y))\" by (metis comm kiso ky isotoneD o_def)\n    thus \"f y \\<le> h (f y)\" by (metis conn galois_connection_def)\n  qed\n  thus \"y \\<le> g (\\<nu> h)\" by (metis conn galois_connection_def)\nqed\n\nend\n\n(* +------------------------------------------------------------------------+\n   | Join semilattices with zero                              |\n   +------------------------------------------------------------------------+ *)\n\nclass join_semilattice_zero = join_semilattice + zero +\n  assumes join_zerol: \"0 \\<squnion> x = x\"\n\nbegin\n\n  lemma join_iso: \"x \\<le> y \\<longrightarrow> x\\<squnion>z \\<le> y\\<squnion>z\"\n    by (smt join_assoc join_comm join_idem leq_def_join)\n\n  lemma join_ub: \"x \\<le> x\\<squnion>y\"\n    by (metis join_assoc join_idem leq_def_join)\n\n  lemma join_lub: \"x\\<squnion>y \\<le> z \\<longleftrightarrow> x \\<le> z \\<and> y \\<le> z\"\n    by (metis join_comm join_iso join_ub leq_def_join)\n\n  lemma min_zero: \"0 \\<le> x\"\n    by (metis join_zerol leq_def_join)\n\n  lemma lub_un: \"is_lub w A \\<Longrightarrow> is_lub (x\\<squnion>w) ({x}\\<union>A)\"\n    by (simp add: is_lub_equiv join_lub)\n\nend\n\nend\n", "meta": {"author": "Alasdair", "repo": "FM2014", "sha": "967b9a0d1903d90fffba49524cd217dcef8797c5", "save_path": "github-repos/isabelle/Alasdair-FM2014", "path": "github-repos/isabelle/Alasdair-FM2014/FM2014-967b9a0d1903d90fffba49524cd217dcef8797c5/WeakTrioid/OrderTheory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699433, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7729420504984544}}
{"text": "theory compactness\n  imports relativization\nbegin\n\n(**The \"finite intersection property\" (FIP)*)\ndefinition \"FIP S \\<equiv> \\<forall>D. nonEmpty D \\<and> D \\<sqsubseteq> S \\<and> finite D \\<longrightarrow> \\<not>(\\<^bold>\\<And>D \\<approx> \\<^bold>\\<bottom>)\"\n(**It can be shown that for meet-closed collections FIP is equivalent to the following \"binary intersection property\" (BIP)*)\ndefinition \"BIP S \\<equiv> \\<forall>A B. S A \\<and> S B \\<longrightarrow> \\<not>(A \\<^bold>\\<and> B \\<approx> \\<^bold>\\<bottom>)\"\n(**Both definitions are equivalent (for meet-closed collections) *)\nlemma FBIP_equiv: \"meet_closed S \\<Longrightarrow> BIP S = FIP S\" oops (*Exercise: prove this*)\n\n(**For convenience, we can dualize the FIP towards some sort of \"finite union property\" (FUP)*)\ndefinition \"FUP S \\<equiv> \\<exists>D. nonEmpty D \\<and> D \\<sqsubseteq> S \\<and> finite D \\<and> \\<^bold>\\<Or>D \\<approx> \\<^bold>\\<top>\"\n(**and, similarly, the FUP is equivalent to its binary counterpart (BUP) for join-closed collections*)\ndefinition \"BUP S \\<equiv> \\<exists>A B. S A \\<and> S B \\<and> (A \\<^bold>\\<or> B \\<approx> \\<^bold>\\<top>)\"\n(**Both definitions are equivalent (for join-closed collections)*)\nlemma FBUP_equiv: \"join_closed S \\<Longrightarrow> BUP S = FUP S\" oops (*Exercise: prove this*)\n\n(**BIP-BUP and FIP-FUP are dual in a sense*)\nlemma BIUP_dual1: \"(\\<not>BIP S) = BUP S\\<^sup>-\" using BA_deMorgan1 BA_deMorgan2 unfolding BIP_def BUP_def by (smt (z3) BA_dn L13 L14 L2 L4 L5 L9 compl_def dom_compl_def setequ_char setequ_def setequ_equ subset_def)\nlemma BIUP_dual2: \"(\\<not>BUP S) = BIP S\\<^sup>-\" by (metis BIUP_dual1 dom_compl_invol)\n\nlemma FIUP_dual1: \"(\\<not>FIP S) = FUP S\\<^sup>-\" using dom_compl_1to1 finite1to1 by (smt (z3) FIP_def FUP_def bottom_def compl_def dom_compl_def dom_compl_invol iDM_a iDM_b setequ_char top_def)\nlemma FIUP_dual2: \"(\\<not>FUP S) = FIP S\\<^sup>-\" by (metis FIUP_dual1 dom_compl_invol)\n\n\n(**Below we can state several definitions of compactness and show them equivalent\n (eventually modulo certain conditions on \\<C>). We can also employ BIP/BUP for FIP/FUP.*)\n\n(**The definition of compactness using closed sets*)\ndefinition compact_cl::\"('a \\<sigma> \\<Rightarrow> 'a \\<sigma>) \\<Rightarrow> bool\" (\"compact\\<^sup>c\\<^sup>l\")\n  where \"compact\\<^sup>c\\<^sup>l \\<C> \\<equiv> \\<forall>S. S \\<sqsubseteq> Cl[\\<C>] \\<and> FIP S \\<longrightarrow> \\<not>(\\<^bold>\\<And>S \\<approx> \\<^bold>\\<bottom>)\"\n\n(**The more usual (dual) definition using open sets (i.e. 'every open cover has a finite subcover')*)\ndefinition compact_op::\"('a \\<sigma> \\<Rightarrow> 'a \\<sigma>) \\<Rightarrow> bool\" (\"compact\\<^sup>o\\<^sup>p\")\n  where \"compact\\<^sup>o\\<^sup>p \\<C> \\<equiv> \\<forall>S. S \\<sqsubseteq> Op[\\<C>] \\<and> \\<^bold>\\<Or>S \\<approx> \\<^bold>\\<top> \\<longrightarrow> FUP S\"\n\n(**Both definitions above are equivalent (without assuming any condition on \\<C>)*)\nlemma \"compact\\<^sup>c\\<^sup>l \\<C> = compact\\<^sup>o\\<^sup>p \\<C>\" unfolding compact_cl_def compact_op_def by (smt (verit) ClOpdual FIUP_dual1 FIUP_dual2 OpCldual bottom_def compl_def dom_compl_def iDM_a iDM_b setequ_char top_def) \n\n(**Exercise: define and interrelate other definitions of compactness*)\n(**Exercise: use compactness to further relate different separation axioms*)\n\nend", "meta": {"author": "davfuenmayor", "repo": "basic-topology", "sha": "45e6791becf6a2dfb174c9f8641b8c6816773529", "save_path": "github-repos/isabelle/davfuenmayor-basic-topology", "path": "github-repos/isabelle/davfuenmayor-basic-topology/basic-topology-45e6791becf6a2dfb174c9f8641b8c6816773529/Topology/compactness.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213745668095, "lm_q2_score": 0.8596637451167995, "lm_q1q2_score": 0.7729420481746682}}
{"text": "(* Title:      (More) Relation Algebra\n   Author:     Walter Guttmann, Peter Hoefner\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n               Peter Hoefner <peter at hoefner-online.de>\n*)\n\nsection \\<open>(More) Relation Algebra\\<close>\n\ntext \\<open>\nThis theory presents fundamental properties of relation algebras, which are not present in the AFP entry on relation algebras but could be integrated there \\<^cite>\\<open>\"ArmstrongFosterStruthWeber2014\"\\<close>.\nMany theorems concern vectors and points.\n\\<close>\n\ntheory More_Relation_Algebra\n\nimports Relation_Algebra.Relation_Algebra_RTC Relation_Algebra.Relation_Algebra_Functions\n\nbegin\n\nno_notation\n  trancl (\"(_\\<^sup>+)\" [1000] 999)\n\ncontext relation_algebra\nbegin\n\nnotation\n  converse (\"(_\\<^sup>T)\" [102] 101)\n\nabbreviation bijective\n  where \"bijective x \\<equiv> is_inj x \\<and> is_sur x\"\n\nabbreviation reflexive\n  where \"reflexive R \\<equiv> 1' \\<le> R\"\n\nabbreviation symmetric\n  where \"symmetric R \\<equiv> R = R\\<^sup>T\"\n\nabbreviation transitive\n  where \"transitive R \\<equiv> R;R \\<le> R\"\n\ntext \\<open>General theorems\\<close>\n\nlemma x_leq_triple_x:\n  \"x \\<le> x;x\\<^sup>T;x\"\nproof -\n  have \"x = x;1' \\<cdot> 1\"\n    by simp\n  also have \"... \\<le> (x \\<cdot> 1;1'\\<^sup>T);(1' \\<cdot> x\\<^sup>T;1)\"\n    by (rule dedekind)\n  also have \"... = x;(x\\<^sup>T;1 \\<cdot> 1')\"\n    by (simp add: inf.commute)\n  also have \"... \\<le> x;(x\\<^sup>T \\<cdot> 1';1\\<^sup>T);(1 \\<cdot> (x\\<^sup>T)\\<^sup>T;1')\"\n    by (metis comp_assoc dedekind mult_isol)\n  also have \"... \\<le> x;x\\<^sup>T;x\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma inj_triple:\n  assumes \"is_inj x\"\n    shows \"x = x;x\\<^sup>T;x\"\nby (metis assms order.eq_iff inf_absorb2 is_inj_def mult_1_left mult_subdistr x_leq_triple_x)\n\nlemma p_fun_triple:\n  assumes \"is_p_fun x\"\n    shows \"x = x;x\\<^sup>T;x\"\nby (metis assms comp_assoc order.eq_iff is_p_fun_def mult_isol mult_oner x_leq_triple_x)\n\nlemma loop_backward_forward:\n  \"x\\<^sup>T \\<le> -(1') + x\"\nby (metis conv_e conv_times inf.cobounded2 test_dom test_domain test_eq_conv galois_2 inf.commute\n           sup.commute)\n\nlemma inj_sur_semi_swap:\n  assumes \"is_sur z\"\n      and \"is_inj x\"\n    shows \"z \\<le> y;x \\<Longrightarrow> x \\<le> y\\<^sup>T;z\"\nproof -\n  assume \"z \\<le> y;x\"\n  hence \"z;x\\<^sup>T \\<le> y;(x;x\\<^sup>T)\"\n    by (metis mult_isor mult_assoc)\n  hence \"z;x\\<^sup>T \\<le> y\"\n    using \\<open>is_inj x\\<close> unfolding is_inj_def\n    by (metis mult_isol order.trans mult_1_right)\n  hence \"(z\\<^sup>T;z);x\\<^sup>T \\<le> z\\<^sup>T;y\"\n    by (metis mult_isol mult_assoc)\n  hence \"x\\<^sup>T \\<le> z\\<^sup>T;y\"\n    using \\<open>is_sur z\\<close> unfolding is_sur_def\n    by (metis mult_isor order.trans mult_1_left)\n  thus ?thesis\n    using conv_iso by fastforce\nqed\n\nlemma inj_sur_semi_swap_short:\n  assumes \"is_sur z\"\n      and \"is_inj x\"\n    shows \"z \\<le> y\\<^sup>T;x \\<Longrightarrow> x \\<le> y;z\"\nproof -\n  assume as: \"z \\<le> y\\<^sup>T;x\"\n  hence \"z;x\\<^sup>T \\<le> y\\<^sup>T\"\n    using \\<open>z \\<le> y\\<^sup>T;x\\<close> \\<open>is_inj x\\<close> unfolding is_inj_def\n    by (metis assms(2) conv_invol inf.orderI inf_absorb1 inj_p_fun ss_422iii)\n  hence \"x\\<^sup>T \\<le> z\\<^sup>T;y\\<^sup>T\"\n    using \\<open>is_sur z\\<close> unfolding is_sur_def\n    by (metis as assms inj_sur_semi_swap conv_contrav conv_invol conv_iso)\n  thus \"x \\<le> y;z\"\n    using conv_iso by fastforce\nqed\n\nlemma bij_swap:\n  assumes \"bijective z\"\n      and \"bijective x\"\n    shows \"z \\<le> y\\<^sup>T;x \\<longleftrightarrow> x \\<le> y;z\"\nby (metis assms inj_sur_semi_swap conv_invol)\n\ntext \\<open>The following result is \\<^cite>\\<open>\\<open>Proposition 4.2.2(iv)\\<close> in \"SchmidtStroehlein1993\"\\<close>.\\<close>\n\n\n\ntext \\<open>The following results are variants of \\<^cite>\\<open>\\<open>Proposition 4.2.3\\<close> in \"SchmidtStroehlein1993\"\\<close>.\\<close>\n\nlemma ss423conv:\n  assumes \"bijective x\"\n    shows \"x ; y \\<le> z \\<longleftrightarrow> y \\<le> x\\<^sup>T ; z\"\nby (metis assms conv_contrav conv_iso inj_p_fun is_map_def ss423 sur_total)\n\nlemma ss423bij:\n  assumes \"bijective x\"\n    shows \"y ; x\\<^sup>T \\<le> z \\<longleftrightarrow> y \\<le> z ; x\"\nby (simp add: assms is_map_def p_fun_inj ss423 total_sur)\n\nlemma inj_distr:\n  assumes \"is_inj z\"\n    shows \"(x\\<cdot>y);z = (x;z)\\<cdot>(y;z)\"\napply (rule order.antisym)\n using mult_subdistr_var apply blast\nusing assms conv_iso inj_p_fun p_fun_distl by fastforce\n\nlemma test_converse:\n  \"x \\<cdot> 1' = x\\<^sup>T \\<cdot> 1'\"\nby (metis conv_e conv_times inf_le2 is_test_def test_eq_conv)\n\nlemma injective_down_closed:\n  assumes \"is_inj x\"\n      and \"y \\<le> x\"\n    shows \"is_inj y\"\nby (meson assms conv_iso dual_order.trans is_inj_def mult_isol_var)\n\nlemma injective_sup:\n  assumes \"is_inj t\"\n      and \"e;t\\<^sup>T \\<le> 1'\"\n      and \"is_inj e\"\n    shows \"is_inj (t + e)\"\nproof -\n  have 1: \"t;e\\<^sup>T \\<le> 1'\"\n    using assms(2) conv_contrav conv_e conv_invol conv_iso by fastforce\n  have \"(t + e);(t + e)\\<^sup>T = t;t\\<^sup>T + t;e\\<^sup>T + e;t\\<^sup>T + e;e\\<^sup>T\"\n    by (metis conv_add distrib_left distrib_right' sup_assoc)\n  also have \"... \\<le> 1'\"\n    using 1 assms by (simp add: is_inj_def le_supI)\n  finally show ?thesis\n    unfolding is_inj_def .\nqed\n\ntext \\<open>Some (more) results about vectors\\<close>\n\nlemma vector_meet_comp:\n  assumes \"is_vector v\"\n      and \"is_vector w\"\n    shows \"v;w\\<^sup>T = v\\<cdot>w\\<^sup>T\"\nby (metis assms conv_contrav conv_one inf_top_right is_vector_def vector_1)\n\nlemma vector_meet_comp':\n  assumes \"is_vector v\"\n    shows \"v;v\\<^sup>T = v\\<cdot>v\\<^sup>T\"\nusing assms vector_meet_comp by blast\n\nlemma vector_meet_comp_x:\n  \"x;1;x\\<^sup>T = x;1\\<cdot>1;x\\<^sup>T\"\nby (metis comp_assoc inf_top.right_neutral is_vector_def one_idem_mult vector_1)\n\nlemma vector_meet_comp_x':\n  \"x;1;x = x;1\\<cdot>1;x\"\nby (metis inf_commute inf_top.right_neutral ra_1)\n\nlemma vector_prop1:\n  assumes \"is_vector v\"\n    shows \"-v\\<^sup>T;v = 0\"\nby (metis assms compl_inf_bot inf_top.right_neutral one_compl one_idem_mult vector_2)\n\ntext \\<open>The following results and a number of others in this theory are from \\<^cite>\\<open>\"Guttmann2017a\"\\<close>.\\<close>\n\nlemma ee:\n  assumes \"is_vector v\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n    shows \"e;e = 0\"\nproof -\n  have \"e;v \\<le> 0\"\n    by (metis assms annir mult_isor vector_prop1 comp_assoc)\n  thus ?thesis\n    by (metis assms(2) annil order.antisym bot_least comp_assoc mult_isol)\nqed\n\nlemma et:\n  assumes \"is_vector v\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n      and \"t \\<le> v;v\\<^sup>T\"\n    shows \"e;t = 0\"\n      and \"e;t\\<^sup>T = 0\"\nproof -\n  have \"e;t \\<le> v;-v\\<^sup>T;v;v\\<^sup>T\"\n    by (metis assms(2-3) mult_isol_var comp_assoc)\n  thus \"e;t = 0\"\n    by (simp add: assms(1) comp_assoc le_bot vector_prop1)\nnext\n  have \"t\\<^sup>T \\<le> v;v\\<^sup>T\"\n    using assms(3) conv_iso by fastforce\n  hence \"e;t\\<^sup>T \\<le> v;-v\\<^sup>T;v;v\\<^sup>T\"\n    by (metis assms(2) mult_isol_var comp_assoc)\n  thus \"e;t\\<^sup>T = 0\"\n    by (simp add: assms(1) comp_assoc le_bot vector_prop1)\nqed\n\ntext \\<open>Some (more) results about points\\<close>\n\ndefinition point\n  where \"point x \\<equiv> is_vector x \\<and> bijective x\"\n\nlemma point_swap:\n  assumes \"point p\"\n      and \"point q\"\n    shows \"p \\<le> x;q \\<longleftrightarrow> q \\<le> x\\<^sup>T;p\"\nby (metis assms conv_invol inj_sur_semi_swap point_def)\n\ntext \\<open>Some (more) results about singletons\\<close>\n\nabbreviation singleton\n  where \"singleton x \\<equiv> bijective (x;1) \\<and> bijective (x\\<^sup>T;1)\"\n\nlemma singleton_injective:\n  assumes \"singleton x\"\n    shows \"is_inj x\"\nusing assms injective_down_closed maddux_20 by blast\n\nlemma injective_inv:\n  assumes \"is_vector v\"\n      and \"singleton e\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n      and \"t \\<le> v;v\\<^sup>T\"\n      and \"is_inj t\"\n    shows \"is_inj (t + e)\"\nby (metis assms singleton_injective injective_sup bot_least et(2))\n\nlemma singleton_is_point:\n  assumes \"singleton p\"\n    shows \"point (p;1)\"\nby (simp add: assms comp_assoc is_vector_def point_def)\n\nlemma singleton_transp:\n  assumes \"singleton p\"\n    shows \"singleton (p\\<^sup>T)\"\nby (simp add: assms)\n\nlemma point_to_singleton:\n  assumes \"singleton p\"\n    shows \"singleton (1'\\<cdot>p;p\\<^sup>T)\"\nusing assms dom_def_aux_var dom_one is_vector_def point_def by fastforce\n\nlemma singleton_singletonT:\n  assumes \"singleton p\"\n    shows \"p;p\\<^sup>T \\<le> 1'\"\nusing assms singleton_injective is_inj_def by blast\n\ntext \\<open>Minimality\\<close>\n\nabbreviation minimum\n  where \"minimum x v \\<equiv> v \\<cdot> -(x\\<^sup>T;v)\"\n\ntext \\<open>Regressively finite\\<close>\n\nabbreviation regressively_finite\n  where \"regressively_finite x \\<equiv> \\<forall>v . is_vector v \\<and> v \\<le> x\\<^sup>T;v \\<longrightarrow> v = 0\"\n\nlemma regressively_finite_minimum:\n  \"regressively_finite R \\<Longrightarrow> is_vector v \\<Longrightarrow> v \\<noteq> 0 \\<Longrightarrow> minimum R v \\<noteq> 0\"\nusing galois_aux2 by blast\n\nlemma regressively_finite_irreflexive:\n  assumes \"regressively_finite x\"\n    shows \"x \\<le> -1'\"\nproof -\n  have 1: \"is_vector ((x\\<^sup>T \\<cdot> 1');1)\"\n    by (simp add: is_vector_def mult_assoc)\n  have \"(x\\<^sup>T \\<cdot> 1');1 = (x\\<^sup>T \\<cdot> 1');(x\\<^sup>T \\<cdot> 1');1\"\n    by (simp add: is_test_def test_comp_eq_mult)\n  with 1 have \"(x\\<^sup>T \\<cdot> 1');1 = 0\"\n    by (metis assms comp_assoc mult_subdistr)\n  thus ?thesis\n    by (metis conv_e conv_invol conv_times conv_zero galois_aux ss_p18)\nqed\n\nend (* relation_algebra *)\n\nsubsection \\<open>Relation algebras satisfying the Tarski rule\\<close>\n\nclass relation_algebra_tarski = relation_algebra +\n  assumes tarski: \"x \\<noteq> 0 \\<longleftrightarrow> 1;x;1 = 1\"\nbegin\n\ntext \\<open>Some (more) results about points\\<close>\n\nlemma point_equations:\n  assumes \"is_point p\"\n  shows \"p;1=p\"\n    and \"1;p=1\"\n    and \"p\\<^sup>T;1=1\"\n    and \"1;p\\<^sup>T=p\\<^sup>T\"\n   apply (metis assms is_point_def is_vector_def)\n  using assms is_point_def is_vector_def tarski vector_comp apply fastforce\n apply (metis assms conv_contrav conv_one conv_zero is_point_def is_vector_def tarski)\nby (metis assms conv_contrav conv_one is_point_def is_vector_def)\n\ntext \\<open>The following result is \\<^cite>\\<open>\\<open>Proposition 2.4.5(i)\\<close> in \"SchmidtStroehlein1993\"\\<close>.\\<close>\n\nlemma point_singleton:\n  assumes \"is_point p\"\n      and \"is_vector v\"\n      and \"v \\<noteq> 0\"\n      and \"v \\<le> p\"\n    shows \"v = p\"\nproof -\n  have \"1;v = 1\"\n    using assms(2,3) comp_assoc is_vector_def tarski by fastforce\n  hence \"p = 1;v \\<cdot> p\"\n    by simp\n  also have \"... \\<le> (1 \\<cdot> p;v\\<^sup>T);(v \\<cdot> 1\\<^sup>T;p)\"\n    using dedekind by blast\n  also have \"... \\<le> p;v\\<^sup>T;v\"\n    by (simp add: mult_subdistl)\n  also have \"... \\<le> p;p\\<^sup>T;v\"\n    using assms(4) conv_iso mult_double_iso by blast\n  also have \"... \\<le> v\"\n    by (metis assms(1) is_inj_def is_point_def mult_isor mult_onel)\n  finally show ?thesis\n    using assms(4) by simp\nqed\n\nlemma point_not_equal_aux:\n  assumes \"is_point p\"\n      and \"is_point q\"\n    shows \"p\\<noteq>q \\<longleftrightarrow> p \\<cdot> -q \\<noteq> 0\"\nproof\n  show \"p \\<noteq> q \\<Longrightarrow> p \\<cdot> - q \\<noteq> 0\"\n  proof (rule contrapos_nn)\n    assume \"p \\<cdot> -q = 0\"\n    thus \"p = q\"\n     using assms galois_aux2 is_point_def point_singleton by fastforce\n  qed\nnext\n  show \"p \\<cdot> - q \\<noteq> 0 \\<Longrightarrow> p \\<noteq> q\"\n    using inf_compl_bot by blast\nqed\n\ntext \\<open>The following result is part of \\<^cite>\\<open>\\<open>Proposition 2.4.5(ii)\\<close> in \"SchmidtStroehlein1993\"\\<close>.\\<close>\n\nlemma point_not_equal:\n  assumes \"is_point p\"\n      and \"is_point q\"\n    shows \"p\\<noteq>q \\<longleftrightarrow> p\\<le>-q\"\n      and \"p\\<le>-q \\<longleftrightarrow> p;q\\<^sup>T \\<le> -1'\"\n      and \"p;q\\<^sup>T \\<le> -1' \\<longleftrightarrow> p\\<^sup>T;q \\<le> 0\"\nproof -\n  have \"p \\<noteq> q \\<Longrightarrow> p \\<le> - q\"\n    by (metis assms point_not_equal_aux is_point_def vector_compl vector_mult point_singleton\n              inf.orderI inf.cobounded1)\n  thus \"p\\<noteq>q \\<longleftrightarrow> p\\<le>-q\"\n    by (metis assms(1) galois_aux inf.orderE is_point_def order.refl)\nnext\n  show \"(p \\<le> - q) = (p ; q\\<^sup>T \\<le> - 1')\"\n    by (simp add: conv_galois_2)\nnext\n  show \"(p ; q\\<^sup>T \\<le> - 1') = (p\\<^sup>T ; q \\<le> 0)\"\n    by (metis assms(2) compl_bot_eq conv_galois_2 galois_aux maddux_141 mult_1_right\n              point_equations(4))\nqed\n\nlemma point_is_point:\n  \"point x \\<longleftrightarrow> is_point x\"\napply (rule iffI)\n apply (simp add: is_point_def point_def surj_one tarski)\nusing is_point_def is_vector_def mult_assoc point_def sur_def_var1 tarski by fastforce\n\nlemma point_in_vector_or_complement:\n  assumes \"point p\"\n      and \"is_vector v\"\n    shows \"p \\<le> v \\<or> p \\<le> -v\"\nproof (cases \"p \\<le> -v\")\n  assume \"p \\<le> -v\"\n  thus ?thesis\n    by simp\nnext\n  assume \"\\<not>(p \\<le> -v)\"\n  hence \"p\\<cdot>v \\<noteq> 0\"\n    by (simp add: galois_aux)\n  hence \"1;(p\\<cdot>v) = 1\"\n    using assms comp_assoc is_vector_def point_def tarski vector_mult by fastforce\n  hence \"p \\<le> p;(p\\<cdot>v)\\<^sup>T;(p\\<cdot>v)\"\n    by (metis inf_top.left_neutral modular_2_var)\n  also have \"... \\<le> p;p\\<^sup>T;v\"\n    by (simp add: mult_isol_var)\n  also have \"... \\<le> v\"\n    using assms(1) comp_assoc point_def ss423conv by fastforce\n  finally show ?thesis ..\nqed\n\nlemma point_in_vector_or_complement_iff:\n  assumes \"point p\"\n      and \"is_vector v\"\n    shows \"p \\<le> v \\<longleftrightarrow> \\<not>(p \\<le> -v)\"\nby (metis assms annir compl_top_eq galois_aux inf.orderE one_compl point_def ss423conv tarski\n          top_greatest point_in_vector_or_complement)\n\nlemma different_points_consequences:\n  assumes \"point p\"\n      and \"point q\"\n      and \"p\\<noteq>q\"\n    shows \"p\\<^sup>T;-q=1\"\n      and \"-q\\<^sup>T;p=1\"\n      and \"-(p\\<^sup>T;-q)=0\"\n      and \"-(-q\\<^sup>T;p)=0\"\nproof -\n  have \"p \\<le> -q\"\n    by (metis assms compl_le_swap1 inf.absorb1 inf.absorb2 point_def point_in_vector_or_complement)\n  thus 1: \"p\\<^sup>T;-q=1\"\n    using assms(1) by (metis is_vector_def point_def ss423conv top_le)\n  thus 2: \"-q\\<^sup>T;p=1\"\n    using conv_compl conv_one by force\n  from 1 show \"-(p\\<^sup>T;-q)=0\"\n    by simp\n  from 2 show \"-(-q\\<^sup>T;p)=0\"\n    by simp\nqed\n\ntext \\<open>Some (more) results about singletons\\<close>\n\nlemma singleton_pq:\n  assumes \"point p\"\n      and \"point q\"\n    shows \"singleton (p;q\\<^sup>T)\"\nusing assms comp_assoc point_def point_equations(1,3) point_is_point by fastforce\n\nlemma singleton_equal_aux:\n  assumes \"singleton p\"\n      and \"singleton q\"\n      and \"q\\<le>p\"\n    shows \"p \\<le> q;1\"\nproof -\n  have pLp: \"p;1;p\\<^sup>T \\<le>1'\"\n    by (simp add: assms(1) maddux_21 ss423conv)\n\n  have \"p = 1;(q\\<^sup>T;q;1) \\<cdot> p\"\n    using tarski\n    by (metis assms(2) annir singleton_injective inf.commute inf_top.right_neutral inj_triple\n              mult_assoc surj_one)\n  also have \"... \\<le> (1 \\<cdot> p;(q\\<^sup>T;q;1)\\<^sup>T);(q\\<^sup>T;q;1 \\<cdot> 1;p)\"\n    using dedekind by (metis conv_one)\n  also have \"... \\<le> p;1;q\\<^sup>T;q;q\\<^sup>T;q;1\"\n    by (simp add: comp_assoc mult_isol)\n  also have \"... \\<le> p;1;p\\<^sup>T;q;q\\<^sup>T;q;1\"\n    using assms(3) by (metis comp_assoc conv_iso mult_double_iso)\n  also have \"... \\<le> 1';q;q\\<^sup>T;q;1\"\n    using pLp using mult_isor by blast\n  also have \"... \\<le> q;1\"\n    using assms(2) singleton_singletonT by (simp add: comp_assoc mult_isol)\n  finally show ?thesis .\nqed\n\nlemma singleton_equal:\n assumes \"singleton p\"\n     and \"singleton q\"\n     and \"q\\<le>p\"\n   shows \"q=p\"\nproof -\n  have p1: \"p \\<le> q;1\"\n    using assms by (rule singleton_equal_aux)\n  have \"p\\<^sup>T \\<le> q\\<^sup>T;1\"\n    using assms singleton_equal_aux singleton_transp conv_iso by fastforce\n  hence p2: \"p \\<le> 1;q\"\n    using conv_iso by force\n\n  have \"p \\<le> q;1 \\<cdot> 1;q\"\n    using p1 p2 inf.boundedI by blast\n  also have \"... \\<le> (q \\<cdot> 1;q;1);(1 \\<cdot> q\\<^sup>T;1;q)\"\n    using dedekind by (metis comp_assoc conv_one)\n  also have \"... \\<le> q;q\\<^sup>T;1;q\"\n    by (simp add: mult_isor comp_assoc)\n  also have \"... \\<le> q;1'\"\n    by (metis assms(2) conv_contrav conv_invol conv_one is_inj_def mult_assoc mult_isol\n              one_idem_mult)\n  also have \"... \\<le> q\"\n    by simp\n  finally have \"p \\<le> q\" .\n  thus \"q=p\"\n  using assms(3) by simp\nqed\n\nlemma singleton_nonsplit:\n  assumes \"singleton p\"\n      and \"x\\<le>p\"\n    shows \"x=0 \\<or> x=p\"\nproof (cases \"x=0\")\n  assume \"x=0\"\n  thus ?thesis ..\nnext\n  assume 1: \"x\\<noteq>0\"\n  have \"singleton x\"\n  proof (safe)\n    show \"is_inj (x;1)\"\n      using assms injective_down_closed mult_isor by blast\n    show \"is_inj (x\\<^sup>T;1)\"\n      using assms conv_iso injective_down_closed mult_isol_var by blast\n    show \"is_sur (x;1)\"\n      using 1 comp_assoc sur_def_var1 tarski by fastforce\n    thus \"is_sur (x\\<^sup>T;1)\"\n      by (metis conv_contrav conv_one mult.semigroup_axioms sur_def_var1 semigroup.assoc)\n  qed\n  thus ?thesis\n    using assms singleton_equal by blast\nqed\n\nlemma singleton_nonzero:\n  assumes \"singleton p\"\n    shows \"p\\<noteq>0\"\nproof\n  assume \"p = 0\"\n  hence \"point 0\"\n    using assms singleton_is_point by fastforce\n  thus False\n    by (simp add: is_point_def point_is_point)\nqed\n\nlemma singleton_sum:\n  assumes \"singleton p\"\n    shows \"p \\<le> x+y \\<longleftrightarrow> (p\\<le>x \\<or> p\\<le>y)\"\nproof\n  show \"p \\<le> x + y \\<Longrightarrow> p \\<le> x \\<or> p \\<le> y\"\n  proof -\n    assume as: \"p \\<le> x + y\"\n    show \"p \\<le> x \\<or> p \\<le> y\"\n    proof (cases \"p\\<le>x\")\n      assume \"p\\<le>x\"\n      thus ?thesis ..\n    next\n      assume a:\"\\<not>(p\\<le>x)\"\n      hence \"p\\<cdot>x \\<noteq> p\"\n        using a inf.orderI by fastforce\n      hence \"p \\<le> -x\"\n        using assms singleton_nonsplit galois_aux inf_le1 by blast\n      hence \"p\\<le>y\"\n        using as by (metis galois_1 inf.orderE)\n      thus ?thesis\n        by simp\n    qed\n  qed\nnext\n  show \"p \\<le> x \\<or> p \\<le> y \\<Longrightarrow> p \\<le> x + y\"\n    using sup.coboundedI1 sup.coboundedI2 by blast\nqed\n\nlemma singleton_iff:\n \"singleton x \\<longleftrightarrow> x \\<noteq> 0 \\<and> x\\<^sup>T;1;x + x;1;x\\<^sup>T \\<le> 1'\"\nby (smt comp_assoc conv_contrav conv_invol conv_one is_inj_def le_sup_iff one_idem_mult\n        sur_def_var1 tarski)\n\nlemma singleton_not_atom_in_relation_algebra_tarski:\n assumes \"p\\<noteq>0\"\n     and \"\\<forall>x . x\\<le>p \\<longrightarrow> x=0 \\<or> x=p\"\n   shows \"singleton p\"\nnitpick [expect=genuine] oops\n\nend (* relation_algebra_tarski *)\n\nsubsection \\<open>Relation algebras satisfying the point axiom\\<close>\n\nclass relation_algebra_point = relation_algebra +\n  assumes point_axiom: \"x \\<noteq> 0 \\<longrightarrow> (\\<exists>y z . point y \\<and> point z \\<and> y;z\\<^sup>T \\<le> x)\"\nbegin\n\ntext \\<open>Some (more) results about points\\<close>\n\nlemma point_exists:\n  \"\\<exists>x . point x\"\nby (metis (full_types) order.eq_iff is_inj_def is_sur_def is_vector_def point_axiom point_def)\n\nlemma point_below_vector:\n  assumes \"is_vector v\"\n      and \"v \\<noteq> 0\"\n    shows \"\\<exists>x . point x \\<and> x \\<le> v\"\nproof -\n  from assms(2) obtain y and z where 1: \"point y \\<and> point z \\<and> y;z\\<^sup>T \\<le> v\"\n    using point_axiom by blast\n  have \"z\\<^sup>T;1 = (1;z)\\<^sup>T\"\n    using conv_contrav conv_one by simp\n  hence \"y;(1;z)\\<^sup>T \\<le> v\"\n    using 1 by (metis assms(1) comp_assoc is_vector_def mult_isor)\n  thus ?thesis\n    using 1 by (metis conv_one is_vector_def point_def sur_def_var1)\nqed\n\nend (* relation_algebra_point *)\n\nclass relation_algebra_tarski_point = relation_algebra_tarski + relation_algebra_point\nbegin\n\nlemma atom_is_singleton:\n  assumes \"p\\<noteq>0\"\n      and \"\\<forall>x . x\\<le>p \\<longrightarrow> x=0 \\<or> x=p\"\n    shows \"singleton p\"\nby (metis assms singleton_nonzero singleton_pq point_axiom)\n\nlemma singleton_iff_atom:\n  \"singleton p \\<longleftrightarrow> p\\<noteq>0 \\<and> (\\<forall>x . x\\<le>p \\<longrightarrow> x=0 \\<or> x=p)\"\nusing singleton_nonsplit singleton_nonzero atom_is_singleton by blast\n\nlemma maddux_tarski:\n  assumes \"x\\<noteq>0\"\n  shows \"\\<exists>y . y\\<noteq>0 \\<and> y\\<le>x \\<and> is_p_fun y\"\nproof -\n  obtain p q where 1: \"point p \\<and> point q \\<and> p;q\\<^sup>T \\<le> x\"\n    using assms point_axiom by blast\n  hence 2: \"p;q\\<^sup>T\\<noteq>0\"\n    by (simp add: singleton_nonzero singleton_pq)\n  have \"is_p_fun (p;q\\<^sup>T)\"\n    using 1 by (meson singleton_singletonT singleton_pq singleton_transp is_inj_def p_fun_inj)\n  thus ?thesis\n    using 1 2 by force\nqed\n\ntext \\<open>Intermediate Point Theorem \\<^cite>\\<open>\\<open>Proposition 2.4.8\\<close> in \"SchmidtStroehlein1993\"\\<close>\\<close>\n\nlemma intermediate_point_theorem:\n  assumes \"point p\"\n      and \"point r\"\n    shows \"p \\<le> x;y;r \\<longleftrightarrow> (\\<exists>q . point q \\<and> p \\<le> x;q \\<and> q \\<le> y;r)\"\nproof\n  assume 1: \"p \\<le> x;y;r\"\n  let ?v = \"x\\<^sup>T;p \\<cdot> y;r\"\n  have 2: \"is_vector ?v\"\n    using assms comp_assoc is_vector_def point_def vector_mult by fastforce\n  have \"?v \\<noteq> 0\"\n    using 1 by (metis assms(1) inf.absorb2 is_point_def maddux_141 point_is_point mult.assoc)\n  hence \"\\<exists>q . point q \\<and> q \\<le> ?v\"\n    using 2 point_below_vector by blast\n  thus \"\\<exists>q . point q \\<and> p \\<le> x;q \\<and> q \\<le> y;r\"\n    using assms(1) point_swap by auto\nnext\n  assume \"\\<exists>q . point q \\<and> p \\<le> x;q \\<and> q \\<le> y;r\"\n  thus \"p \\<le> x;y;r\"\n    using comp_assoc mult_isol order_trans by fastforce\nqed\n\nend (* relation_algebra_tarski_point *)\n\n(*\nThe following shows that rtc can be defined with only 2 axioms.\nThis should eventually go into AFP/Relation_Algebra_RTC.relation_algebra_rtc.\nThere the class definition should be replaced with:\n\nclass relation_algebra_rtc = relation_algebra + star_op +\n  assumes rtc_unfoldl: \"1' + x ; x\\<^sup>\\<star> \\<le> x\\<^sup>\\<star>\"\n      and rtc_inductl: \"z + x ; y \\<le> y \\<longrightarrow> x\\<^sup>\\<star> ; z \\<le> y\"\n\nand the following lemmas:\n*)\n\ncontext relation_algebra\nbegin\n\nlemma unfoldl_inductl_implies_unfoldr:\n  assumes \"\\<And>x. 1' + x;(rtc x) \\<le> rtc x\"\n      and \"\\<And>x y z. x+y;z \\<le> z \\<Longrightarrow> rtc(y);x \\<le> z\"\n    shows \"1' + rtc(x);x \\<le> rtc x\"\nby (metis assms le_sup_iff mult_oner order.trans subdistl_eq sup_absorb2 sup_ge1)\n\nlemma star_transpose_swap:\n  assumes \"\\<And>x. 1' + x;(rtc x) \\<le> rtc x\"\n      and \"\\<And>x y z. x+y;z \\<le> z \\<Longrightarrow> rtc(y);x \\<le> z\"\n    shows \"rtc(x\\<^sup>T) = (rtc x)\\<^sup>T\"\napply(simp only: order.eq_iff; rule conjI)\n  apply (metis assms conv_add conv_contrav conv_e conv_iso mult_1_right\n             unfoldl_inductl_implies_unfoldr )\nby (metis assms conv_add conv_contrav conv_e conv_invol conv_iso mult_1_right\n          unfoldl_inductl_implies_unfoldr)\n\nlemma unfoldl_inductl_implies_inductr:\n  assumes \"\\<And>x. 1' + x;(rtc x) \\<le> rtc x\"\n      and \"\\<And>x y z. x+y;z \\<le> z \\<Longrightarrow> rtc(y);x \\<le> z\"\n    shows \"x+z;y \\<le> z \\<Longrightarrow> x;rtc(y) \\<le> z\"\nby (metis assms conv_add conv_contrav conv_iso star_transpose_swap)\n\nend (* relation_algebra *)\n\ncontext relation_algebra_rtc\nbegin\n\nabbreviation tc (\"(_\\<^sup>+)\" [101] 100) where \"tc x \\<equiv> x;x\\<^sup>\\<star>\"\n\nabbreviation is_acyclic\n  where \"is_acyclic x \\<equiv> x\\<^sup>+ \\<le> -1'\"\n\ntext \\<open>General theorems\\<close>\n\nlemma star_denest_10:\n  assumes \"x;y=0\"\n    shows \"(x+y)\\<^sup>\\<star> = y;y\\<^sup>\\<star>;x\\<^sup>\\<star>+x\\<^sup>\\<star>\"\nusing assms bubble_sort sup.commute by auto\n\n\n\ntext \\<open>The following two lemmas are from \\<^cite>\\<open>\"Guttmann2018b\"\\<close>.\\<close>\n\nlemma cancel_separate:\n  assumes \"x ; y \\<le> 1'\"\n  shows \"x\\<^sup>\\<star> ; y\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> + y\\<^sup>\\<star>\"\nproof -\n  have \"x ; y\\<^sup>\\<star> = x + x ; y ; y\\<^sup>\\<star>\"\n    by (metis comp_assoc conway.dagger_unfoldl_distr distrib_left mult_oner)\n  also have \"... \\<le> x + y\\<^sup>\\<star>\"\n    by (metis assms join_isol star_invol star_plus_one star_subdist_var_2 sup.absorb2 sup.assoc)\n  also have \"... \\<le> x\\<^sup>\\<star> + y\\<^sup>\\<star>\"\n    using join_iso by fastforce\n  finally have \"x ; (x\\<^sup>\\<star> + y\\<^sup>\\<star>) \\<le> x\\<^sup>\\<star> + y\\<^sup>\\<star>\"\n    by (simp add: distrib_left le_supI1)\n  thus ?thesis\n    by (simp add: rtc_inductl)\nqed\n\nlemma cancel_separate_inj_converse:\n  assumes \"is_inj x\"\n    shows \"x\\<^sup>\\<star> ; x\\<^sup>T\\<^sup>\\<star> = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\n apply (rule order.antisym)\n  using assms cancel_separate is_inj_def apply blast\nby (metis conway.dagger_unfoldl_distr le_supI mult_1_right mult_isol sup.cobounded1)\n\nlemma cancel_separate_p_fun_converse:\n  assumes \"is_p_fun x\"\n    shows \"x\\<^sup>T\\<^sup>\\<star> ; x\\<^sup>\\<star> = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nusing sup_commute assms cancel_separate_inj_converse p_fun_inj by fastforce\n\nlemma cancel_separate_converse_idempotent:\n  assumes \"is_inj x\"\n      and \"is_p_fun x\"\n    shows \"(x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>);(x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>) = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nby (metis assms cancel_separate cancel_separate_p_fun_converse church_rosser_equiv is_inj_def\n          star_denest_var_6)\n\nlemma triple_star:\n  assumes \"is_inj x\"\n      and \"is_p_fun x\"\n    shows \"x\\<^sup>\\<star>;x\\<^sup>T\\<^sup>\\<star>;x\\<^sup>\\<star> = x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nby (simp add: assms cancel_separate_inj_converse cancel_separate_p_fun_converse)\n\nlemma inj_xxts:\n  assumes \"is_inj x\"\n    shows \"x;x\\<^sup>T\\<^sup>\\<star> \\<le> x\\<^sup>\\<star> + x\\<^sup>T\\<^sup>\\<star>\"\nby (metis assms cancel_separate_inj_converse distrib_right less_eq_def star_ext)\n\nlemma plus_top:\n  \"x\\<^sup>+;1 = x;1\"\nby (metis comp_assoc conway.dagger_unfoldr_distr sup_top_left)\n\nlemma top_plus:\n  \"1;x\\<^sup>+ = 1;x\"\nby (metis comp_assoc conway.dagger_unfoldr_distr star_denest_var_2 star_ext star_slide_var\n           sup_top_left top_unique)\n\nlemma plus_conv:\n  \"(x\\<^sup>+)\\<^sup>T = x\\<^sup>T\\<^sup>+\"\nby (simp add: star_conv star_slide_var)\n\nlemma inj_implies_step_forwards_backwards:\n  assumes \"is_inj x\"\n    shows \"x\\<^sup>\\<star>;(x\\<^sup>+\\<cdot>1');1 \\<le> x\\<^sup>T;1\"\nproof -\n  have \"(x\\<^sup>+\\<cdot>1');1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);(x\\<cdot>(x\\<^sup>\\<star>)\\<^sup>T);1\"\n    by (metis conv_contrav conv_e dedekind mult_1_right mult_isor star_slide_var)\n  also have \"... \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\"\n    by (simp add: comp_assoc mult_isol)\n  finally have 1: \"(x\\<^sup>+\\<cdot>1');1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\" .\n\n  have \"x;(x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1 \\<le> (x\\<^sup>+\\<cdot>x;x\\<^sup>T);1\"\n    by (metis inf_idem meet_interchange mult_isor)\n  also have \"... \\<le> (x\\<^sup>+\\<cdot>1');1\"\n    using assms is_inj_def meet_isor mult_isor by fastforce\n  finally have \"x;(x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\"\n    using 1 by fastforce\n  hence \"x\\<^sup>\\<star>;(x\\<^sup>+\\<cdot>1');1 \\<le> (x\\<^sup>\\<star>\\<cdot>x\\<^sup>T);1\"\n    using 1 by (simp add: comp_assoc rtc_inductl)\n  thus \"x\\<^sup>\\<star>;(x\\<^sup>+\\<cdot>1');1 \\<le> x\\<^sup>T;1\"\n    using inf.cobounded2 mult_isor order_trans by blast\nqed\n\ntext \\<open>Acyclic relations\\<close>\n\ntext \\<open>The following result is from \\<^cite>\\<open>\"Guttmann2017c\"\\<close>.\\<close>\n\nlemma acyclic_inv:\n  assumes \"is_acyclic t\"\n      and \"is_vector v\"\n      and \"e \\<le> v;-v\\<^sup>T\"\n      and \"t \\<le> v;v\\<^sup>T\"\n    shows \"is_acyclic (t + e)\"\nproof -\n  have \"t\\<^sup>+;e \\<le> t\\<^sup>+;v;-v\\<^sup>T\"\n    by (simp add: assms(3) mult_assoc mult_isol)\n  also have \"... \\<le> v;v\\<^sup>T;t\\<^sup>\\<star>;v;-v\\<^sup>T\"\n    by (simp add: assms(4) mult_isor)\n  also have \"... \\<le> v;-v\\<^sup>T\"\n    by (metis assms(2) mult_double_iso top_greatest is_vector_def mult_assoc)\n  also have \"... \\<le> -1'\"\n    by (simp add: conv_galois_1)\n  finally have 1: \"t\\<^sup>+;e \\<le> -1'\" .\n  have \"e \\<le> v;-v\\<^sup>T\"\n    using assms(3) by simp\n  also have \"... \\<le> -1'\"\n    by (simp add: conv_galois_1)\n  finally have 2: \"t\\<^sup>+;e + e \\<le> -1'\"\n    using 1 by simp\n  have 3: \"e;t\\<^sup>\\<star> = e\"\n    by (metis assms(2-4) et(1) independence2)\n  have 4: \"e\\<^sup>\\<star> = 1' + e\"\n    using assms(2-3) ee boffa_var bot_least by blast\n  have \"(t + e)\\<^sup>+ = (t + e);t\\<^sup>\\<star>;(e;t\\<^sup>\\<star>)\\<^sup>\\<star>\"\n    by (simp add: comp_assoc)\n  also have \"... = (t + e);t\\<^sup>\\<star>;(1' + e)\"\n    using 3 4 by simp\n  also have \"... = t\\<^sup>+;(1' + e) + e;t\\<^sup>\\<star>;(1' + e)\"\n    by simp\n  also have \"... = t\\<^sup>+;(1' + e) + e;(1' + e)\"\n    using 3 by simp\n  also have \"... = t\\<^sup>+;(1' + e) + e\"\n    using 4 assms(2-3) ee independence2 by fastforce\n  also have \"... = t\\<^sup>+ + t\\<^sup>+;e + e\"\n    by (simp add: distrib_left)\n  also have \"... \\<le> -1'\"\n    using assms(1) 2 by simp\n  finally show ?thesis .\nqed\n\nlemma acyclic_single_step:\n  assumes \"is_acyclic x\"\n    shows \"x \\<le> -1'\"\nby (metis assms dual_order.trans mult_isol mult_oner star_ref)\n\nlemma acyclic_reachable_points:\n  assumes \"is_point p\"\n      and \"is_point q\"\n      and \"p \\<le> x;q\"\n      and \"is_acyclic x\"\n    shows \"p\\<noteq>q\"\nproof\n  assume \"p=q\"\n  hence \"p \\<le> x;q \\<cdot> q\"\n    by (simp add: assms(3) order.eq_iff inf.absorb2)\n  also have \"... = (x \\<cdot> 1');q\"\n    using assms(2) inj_distr is_point_def by simp\n  also have \"... \\<le> (-1' \\<cdot> 1');q\"\n    using acyclic_single_step assms(4) by (metis abel_semigroup.commute inf.abel_semigroup_axioms\n          meet_isor mult_isor)\n also have \"... = 0\"\n  by simp\n finally have \"p \\<le> 0\" .\n thus False\n  using assms(1) bot_unique is_point_def by blast\nqed\n\nlemma acyclic_trans:\n assumes \"is_acyclic x\"\n   shows \"x \\<le> -(x\\<^sup>T\\<^sup>+)\"\nproof -\n have \"\\<exists>c\\<ge>x. c \\<le> - (x\\<^sup>+)\\<^sup>T\"\n  by (metis assms compl_mono conv_galois_2 conv_iso double_compl mult_onel star_1l)\n thus ?thesis\n  by (metis dual_order.trans plus_conv)\nqed\n\nlemma acyclic_trans':\n assumes \"is_acyclic x\"\n   shows \"x\\<^sup>\\<star> \\<le> -(x\\<^sup>T\\<^sup>+)\"\nproof -\n have \"x\\<^sup>\\<star> \\<le> - (- (- (x\\<^sup>T ; - (- 1'))) ; (x\\<^sup>\\<star>)\\<^sup>T)\"\n  by (metis assms conv_galois_1 conv_galois_2 order_trans star_trans)\n then show ?thesis\n  by (simp add: star_conv)\nqed\n\ntext \\<open>Regressively finite\\<close>\n\nlemma regressively_finite_acyclic:\n  assumes \"regressively_finite x\"\n    shows \"is_acyclic x\"\nproof -\n  have 1: \"is_vector ((x\\<^sup>+ \\<cdot> 1');1)\"\n    by (simp add: is_vector_def mult_assoc)\n  have \"(x\\<^sup>+ \\<cdot> 1');1 = (x\\<^sup>T\\<^sup>+ \\<cdot> 1');1\"\n    by (metis plus_conv test_converse)\n  also have \"... \\<le> x\\<^sup>T;(1';x\\<^sup>T\\<^sup>\\<star> \\<cdot> x);1\"\n    by (metis conv_invol modular_1_var mult_isor mult_oner mult_onel)\n  also have \"... \\<le> x\\<^sup>T;(1' \\<cdot> x\\<^sup>+);x\\<^sup>T\\<^sup>\\<star>;1\"\n    by (metis comp_assoc conv_invol modular_2_var mult_isol mult_isor star_conv)\n  also have \"... = x\\<^sup>T;(x\\<^sup>+ \\<cdot> 1');1\"\n    by (metis comp_assoc conway.dagger_unfoldr_distr inf.commute sup.cobounded1 top_le)\n  finally have \"(x\\<^sup>+ \\<cdot> 1');1 = 0\"\n    using 1 assms by (simp add: comp_assoc)\n  thus ?thesis\n    by (simp add: galois_aux ss_p18)\nqed\n\nnotation power (infixr \"\\<up>\" 80)\n\nlemma power_suc_below_plus:\n  \"x \\<up> Suc n \\<le> x\\<^sup>+\"\n  apply (induct n)\n using mult_isol star_ref apply fastforce\nby (simp add: mult_isol_var order_trans)\n\nend (* relation_algebra_rtc *)\n\nclass relation_algebra_rtc_tarski = relation_algebra_rtc + relation_algebra_tarski\nbegin\n\nlemma point_loop_not_acyclic:\n  assumes \"is_point p\"\n      and \"p \\<le> x \\<up> Suc n ; p\"\n    shows \"\\<not> is_acyclic x\"\nproof -\n  have \"p \\<le> x\\<^sup>+ ; p\"\n    by (meson assms dual_order.trans point_def point_is_point ss423bij power_suc_below_plus)\n  hence \"p ; p\\<^sup>T \\<le> x\\<^sup>+\"\n    using assms(1) point_def point_is_point ss423bij by blast\n  thus ?thesis\n    using assms(1) order.trans point_not_equal(1) point_not_equal(2) by blast\nqed\n\nend\n\nclass relation_algebra_rtc_point = relation_algebra_rtc + relation_algebra_point\n\nclass relation_algebra_rtc_tarski_point = relation_algebra_rtc_tarski + relation_algebra_rtc_point +\n                                          relation_algebra_tarski_point\n\ntext \\<open>\nFinite graphs: the axiom says the algebra has finitely many elements.\nThis means the relations have a finite base set.\n\\<close>\n\nclass relation_algebra_rtc_tarski_point_finite = relation_algebra_rtc_tarski_point + finite\nbegin\n\ntext \\<open>For a finite acyclic relation, the powers eventually vanish.\\<close>\n\nlemma acyclic_power_vanishes:\n  assumes \"is_acyclic x\"\n    shows \"\\<exists>n . x \\<up> Suc n = 0\"\nproof -\n  let ?n = \"card { p . is_point p }\"\n  let ?p = \"x \\<up> ?n\"\n  have \"?p = 0\"\n  proof (rule ccontr)\n    assume \"?p \\<noteq> 0\"\n    from this obtain p q where 1: \"point p \\<and> point q \\<and> p;q\\<^sup>T \\<le> ?p\"\n      using point_axiom by blast\n    hence 2: \"p \\<le> ?p;q\"\n      using point_def ss423bij by blast\n    have \"\\<forall>n\\<le>?n . (\\<exists>f. \\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x\\<up>(?n-i) ; f i \\<and> f i \\<le> x\\<up>(i-j) ; f j))\"\n    proof\n      fix n\n      show \"n\\<le>?n \\<longrightarrow> (\\<exists>f. \\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x\\<up>(?n-i) ; f i \\<and> f i \\<le> x\\<up>(i-j) ; f j))\"\n      proof (induct n)\n        case 0\n        thus ?case\n          using 1 2 point_is_point by fastforce\n      next\n        case (Suc n)\n        fix n\n        assume 3: \"n\\<le>?n \\<longrightarrow> (\\<exists>f . \\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j))\"\n        show \"Suc n\\<le>?n \\<longrightarrow> (\\<exists>f . \\<forall>i\\<le>Suc n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j))\"\n        proof\n          assume 4: \"Suc n\\<le>?n\"\n          from this obtain f where 5: \"\\<forall>i\\<le>n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j)\"\n            using 3 by auto\n          have \"p \\<le> x \\<up> (?n-n) ; f n\"\n            using 5 by blast\n          also have \"... = x \\<up> (?n-n-one_class.one) ; x ; f n\"\n            using 4 by (metis (no_types) Suc_diff_le diff_Suc_1 diff_Suc_Suc power_Suc2)\n          finally obtain r where 6: \"point r \\<and> p \\<le> x \\<up> (?n-Suc n) ; r \\<and> r \\<le> x ; f n\"\n            using 1 5 intermediate_point_theorem point_is_point by fastforce\n          let ?g = \"\\<lambda>m . if m = Suc n then r else f m\"\n          have \"\\<forall>i\\<le>Suc n . is_point (?g i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; ?g i \\<and> ?g i \\<le> x \\<up> (i-j) ; ?g j)\"\n          proof\n            fix i\n            show \"i\\<le>Suc n \\<longrightarrow> is_point (?g i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; ?g i \\<and> ?g i \\<le> x \\<up> (i-j) ; ?g j)\"\n            proof (cases \"i\\<le>n\")\n              case True\n              thus ?thesis\n                using 5 by simp\n            next\n              case False\n              have \"is_point (?g (Suc n)) \\<and> (\\<forall>j\\<le>Suc n . p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j)\"\n              proof\n                show \"is_point (?g (Suc n))\"\n                  using 6 point_is_point by fastforce\n              next\n                show \"\\<forall>j\\<le>Suc n . p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                proof\n                  fix j\n                  show \"j\\<le>Suc n \\<longrightarrow> p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                  proof\n                    assume 7: \"j\\<le>Suc n\"\n                    show \"p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n) \\<and> ?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                    proof\n                      show \"p \\<le> x \\<up> (?n-Suc n) ; ?g (Suc n)\"\n                        using 6 by simp\n                    next\n                      show \"?g (Suc n) \\<le> x \\<up> (Suc n-j) ; ?g j\"\n                      proof (cases \"j = Suc n\")\n                        case True\n                        thus ?thesis\n                          by simp\n                      next\n                        case False\n                        hence \"f n \\<le> x \\<up> (n-j) ; f j\"\n                          using 5 7 by fastforce\n                        hence \"x ; f n \\<le> x \\<up> (Suc n-j) ; f j\"\n                          using 7 False Suc_diff_le comp_assoc mult_isol by fastforce\n                        thus ?thesis\n                          using 6 False by fastforce\n                      qed\n                    qed\n                  qed\n                qed\n              qed\n              thus ?thesis\n                by (simp add: False le_Suc_eq)\n            qed\n          qed\n          thus \"\\<exists>f . \\<forall>i\\<le>Suc n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j)\"\n            by auto\n        qed\n      qed\n    qed\n    from this obtain f where 8: \"\\<forall>i\\<le>?n . is_point (f i) \\<and> (\\<forall>j\\<le>i . p \\<le> x \\<up> (?n-i) ; f i \\<and> f i \\<le> x \\<up> (i-j) ; f j)\"\n      by fastforce\n    let ?A = \"{ k . k\\<le>?n }\"\n    have \"f ` ?A \\<subseteq> { p . is_point p }\"\n      using 8 by blast\n    hence \"card (f ` ?A) \\<le> ?n\"\n      by (simp add: card_mono)\n    hence \"\\<not> inj_on f ?A\"\n      by (simp add: pigeonhole)\n    from this obtain i j where 9: \"i \\<le> ?n \\<and> j \\<le> ?n \\<and> i \\<noteq> j \\<and> f i = f j\"\n      by (metis (no_types, lifting) inj_on_def mem_Collect_eq)\n    show False\n      apply (cases \"i < j\")\n     using 8 9 apply (metis Suc_diff_le Suc_leI assms diff_Suc_Suc order_less_imp_le\n                            point_loop_not_acyclic)\n    using 8 9 by (metis assms neqE point_loop_not_acyclic Suc_diff_le Suc_leI assms diff_Suc_Suc\n                        order_less_imp_le)\n    qed\n    thus ?thesis\n      by (metis annir power.simps(2))\nqed\n\ntext \\<open>Hence finite acyclic relations are regressively finite.\\<close>\n\nlemma acyclic_regressively_finite:\n  assumes \"is_acyclic x\"\n    shows \"regressively_finite x\"\nproof\n  have \"is_acyclic (x\\<^sup>T)\"\n    using assms acyclic_trans' compl_le_swap1 order_trans star_ref by blast\n  from this obtain n where 1: \"x\\<^sup>T \\<up> Suc n = 0\"\n    using acyclic_power_vanishes by fastforce\n  fix v\n  show \"is_vector v \\<and> v \\<le> x\\<^sup>T;v \\<longrightarrow> v = 0\"\n  proof\n    assume 2: \"is_vector v \\<and> v \\<le> x\\<^sup>T;v\"\n    have \"v \\<le> x\\<^sup>T \\<up> Suc n ; v\"\n    proof (induct n)\n      case 0\n      thus ?case\n        using 2 by simp\n    next\n      case (Suc n)\n      hence \"x\\<^sup>T ; v \\<le> x\\<^sup>T \\<up> Suc (Suc n) ; v\"\n        by (simp add: comp_assoc mult_isol)\n      thus ?case\n        using 2 dual_order.trans by blast\n    qed\n    thus \"v = 0\"\n      using 1 by (simp add: le_bot)\n  qed\n qed\n\nlemma acyclic_is_regressively_finite:\n  \"is_acyclic x \\<longleftrightarrow> regressively_finite x\"\nusing acyclic_regressively_finite regressively_finite_acyclic by blast\n\nend (* end relation_algebra_rtc_tarski_point_finite *)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Relational_Paths/More_Relation_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765234137296, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7729177486768569}}
{"text": "(*  Title:      HOL/Parity.thy\n    Author:     Jeremy Avigad\n    Author:     Jacques D. Fleuriot\n*)\n\nsection \\<open>Parity in rings and semirings\\<close>\n\ntheory Parity\n  imports Euclidean_Rings\nbegin\n\nsubsection \\<open>Ring structures with parity and \\<open>even\\<close>/\\<open>odd\\<close> predicates\\<close>\n\nclass semiring_parity = comm_semiring_1 + semiring_modulo +\n  assumes even_iff_mod_2_eq_zero: \"2 dvd a \\<longleftrightarrow> a mod 2 = 0\"\n    and odd_iff_mod_2_eq_one: \"\\<not> 2 dvd a \\<longleftrightarrow> a mod 2 = 1\"\n    and odd_one [simp]: \"\\<not> 2 dvd 1\"\nbegin\n\nabbreviation even :: \"'a \\<Rightarrow> bool\"\n  where \"even a \\<equiv> 2 dvd a\"\n\nabbreviation odd :: \"'a \\<Rightarrow> bool\"\n  where \"odd a \\<equiv> \\<not> 2 dvd a\"\n\nend\n\nclass ring_parity = ring + semiring_parity\nbegin\n\nsubclass comm_ring_1 ..\n\nend\n\ninstance nat :: semiring_parity\n  by standard (simp_all add: dvd_eq_mod_eq_0)\n\ninstance int :: ring_parity\n  by standard (auto simp add: dvd_eq_mod_eq_0)\n\ncontext semiring_parity\nbegin\n\nlemma parity_cases [case_names even odd]:\n  assumes \"even a \\<Longrightarrow> a mod 2 = 0 \\<Longrightarrow> P\"\n  assumes \"odd a \\<Longrightarrow> a mod 2 = 1 \\<Longrightarrow> P\"\n  shows P\n  using assms by (cases \"even a\")\n    (simp_all add: even_iff_mod_2_eq_zero [symmetric] odd_iff_mod_2_eq_one [symmetric])\n\nlemma odd_of_bool_self [simp]:\n  \\<open>odd (of_bool p) \\<longleftrightarrow> p\\<close>\n  by (cases p) simp_all\n\nlemma not_mod_2_eq_0_eq_1 [simp]:\n  \"a mod 2 \\<noteq> 0 \\<longleftrightarrow> a mod 2 = 1\"\n  by (cases a rule: parity_cases) simp_all\n\nlemma not_mod_2_eq_1_eq_0 [simp]:\n  \"a mod 2 \\<noteq> 1 \\<longleftrightarrow> a mod 2 = 0\"\n  by (cases a rule: parity_cases) simp_all\n\nlemma evenE [elim?]:\n  assumes \"even a\"\n  obtains b where \"a = 2 * b\"\n  using assms by (rule dvdE)\n\nlemma oddE [elim?]:\n  assumes \"odd a\"\n  obtains b where \"a = 2 * b + 1\"\nproof -\n  have \"a = 2 * (a div 2) + a mod 2\"\n    by (simp add: mult_div_mod_eq)\n  with assms have \"a = 2 * (a div 2) + 1\"\n    by (simp add: odd_iff_mod_2_eq_one)\n  then show ?thesis ..\nqed\n\nlemma mod_2_eq_odd:\n  \"a mod 2 = of_bool (odd a)\"\n  by (auto elim: oddE simp add: even_iff_mod_2_eq_zero)\n\nlemma of_bool_odd_eq_mod_2:\n  \"of_bool (odd a) = a mod 2\"\n  by (simp add: mod_2_eq_odd)\n\nlemma even_mod_2_iff [simp]:\n  \\<open>even (a mod 2) \\<longleftrightarrow> even a\\<close>\n  by (simp add: mod_2_eq_odd)\n\nlemma mod2_eq_if:\n  \"a mod 2 = (if even a then 0 else 1)\"\n  by (simp add: mod_2_eq_odd)\n\nlemma even_zero [simp]:\n  \"even 0\"\n  by (fact dvd_0_right)\n\nlemma odd_even_add:\n  \"even (a + b)\" if \"odd a\" and \"odd b\"\nproof -\n  from that obtain c d where \"a = 2 * c + 1\" and \"b = 2 * d + 1\"\n    by (blast elim: oddE)\n  then have \"a + b = 2 * c + 2 * d + (1 + 1)\"\n    by (simp only: ac_simps)\n  also have \"\\<dots> = 2 * (c + d + 1)\"\n    by (simp add: algebra_simps)\n  finally show ?thesis ..\nqed\n\nlemma even_add [simp]:\n  \"even (a + b) \\<longleftrightarrow> (even a \\<longleftrightarrow> even b)\"\n  by (auto simp add: dvd_add_right_iff dvd_add_left_iff odd_even_add)\n\nlemma odd_add [simp]:\n  \"odd (a + b) \\<longleftrightarrow> \\<not> (odd a \\<longleftrightarrow> odd b)\"\n  by simp\n\nlemma even_plus_one_iff [simp]:\n  \"even (a + 1) \\<longleftrightarrow> odd a\"\n  by (auto simp add: dvd_add_right_iff intro: odd_even_add)\n\nlemma even_mult_iff [simp]:\n  \"even (a * b) \\<longleftrightarrow> even a \\<or> even b\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?Q\n  then show ?P\n    by auto\nnext\n  assume ?P\n  show ?Q\n  proof (rule ccontr)\n    assume \"\\<not> (even a \\<or> even b)\"\n    then have \"odd a\" and \"odd b\"\n      by auto\n    then obtain r s where \"a = 2 * r + 1\" and \"b = 2 * s + 1\"\n      by (blast elim: oddE)\n    then have \"a * b = (2 * r + 1) * (2 * s + 1)\"\n      by simp\n    also have \"\\<dots> = 2 * (2 * r * s + r + s) + 1\"\n      by (simp add: algebra_simps)\n    finally have \"odd (a * b)\"\n      by simp\n    with \\<open>?P\\<close> show False\n      by auto\n  qed\nqed\n\nlemma even_numeral [simp]: \"even (numeral (Num.Bit0 n))\"\nproof -\n  have \"even (2 * numeral n)\"\n    unfolding even_mult_iff by simp\n  then have \"even (numeral n + numeral n)\"\n    unfolding mult_2 .\n  then show ?thesis\n    unfolding numeral.simps .\nqed\n\nlemma odd_numeral [simp]: \"odd (numeral (Num.Bit1 n))\"\nproof\n  assume \"even (numeral (num.Bit1 n))\"\n  then have \"even (numeral n + numeral n + 1)\"\n    unfolding numeral.simps .\n  then have \"even (2 * numeral n + 1)\"\n    unfolding mult_2 .\n  then have \"2 dvd numeral n * 2 + 1\"\n    by (simp add: ac_simps)\n  then have \"2 dvd 1\"\n    using dvd_add_times_triv_left_iff [of 2 \"numeral n\" 1] by simp\n  then show False by simp\nqed\n\nlemma odd_numeral_BitM [simp]:\n  \\<open>odd (numeral (Num.BitM w))\\<close>\n  by (cases w) simp_all\n\nlemma even_power [simp]: \"even (a ^ n) \\<longleftrightarrow> even a \\<and> n > 0\"\n  by (induct n) auto\n\nlemma even_prod_iff:\n  \\<open>even (prod f A) \\<longleftrightarrow> (\\<exists>a\\<in>A. even (f a))\\<close> if \\<open>finite A\\<close>\n  using that by (induction A) simp_all\n\nlemma mask_eq_sum_exp:\n  \\<open>2 ^ n - 1 = (\\<Sum>m\\<in>{q. q < n}. 2 ^ m)\\<close>\nproof -\n  have *: \\<open>{q. q < Suc m} = insert m {q. q < m}\\<close> for m\n    by auto\n  have \\<open>2 ^ n = (\\<Sum>m\\<in>{q. q < n}. 2 ^ m) + 1\\<close>\n    by (induction n) (simp_all add: ac_simps mult_2 *)\n  then have \\<open>2 ^ n - 1 = (\\<Sum>m\\<in>{q. q < n}. 2 ^ m) + 1 - 1\\<close>\n    by simp\n  then show ?thesis\n    by simp\nqed\n\nlemma (in -) mask_eq_sum_exp_nat:\n  \\<open>2 ^ n - Suc 0 = (\\<Sum>m\\<in>{q. q < n}. 2 ^ m)\\<close>\n  using mask_eq_sum_exp [where ?'a = nat] by simp\n\nend\n\ncontext ring_parity\nbegin\n\nlemma even_minus:\n  \"even (- a) \\<longleftrightarrow> even a\"\n  by (fact dvd_minus_iff)\n\nlemma even_diff [simp]:\n  \"even (a - b) \\<longleftrightarrow> even (a + b)\"\n  using even_add [of a \"- b\"] by simp\n\nend\n\n\nsubsection \\<open>Instance for \\<^typ>\\<open>nat\\<close>\\<close>\n\nlemma even_Suc_Suc_iff [simp]:\n  \"even (Suc (Suc n)) \\<longleftrightarrow> even n\"\n  using dvd_add_triv_right_iff [of 2 n] by simp\n\nlemma even_Suc [simp]: \"even (Suc n) \\<longleftrightarrow> odd n\"\n  using even_plus_one_iff [of n] by simp\n\nlemma even_diff_nat [simp]:\n  \"even (m - n) \\<longleftrightarrow> m < n \\<or> even (m + n)\" for m n :: nat\nproof (cases \"n \\<le> m\")\n  case True\n  then have \"m - n + n * 2 = m + n\" by (simp add: mult_2_right)\n  moreover have \"even (m - n) \\<longleftrightarrow> even (m - n + n * 2)\" by simp\n  ultimately have \"even (m - n) \\<longleftrightarrow> even (m + n)\" by (simp only:)\n  then show ?thesis by auto\nnext\n  case False\n  then show ?thesis by simp\nqed\n\nlemma odd_pos:\n  \"odd n \\<Longrightarrow> 0 < n\" for n :: nat\n  by (auto elim: oddE)\n\nlemma Suc_double_not_eq_double:\n  \"Suc (2 * m) \\<noteq> 2 * n\"\nproof\n  assume \"Suc (2 * m) = 2 * n\"\n  moreover have \"odd (Suc (2 * m))\" and \"even (2 * n)\"\n    by simp_all\n  ultimately show False by simp\nqed\n\nlemma double_not_eq_Suc_double:\n  \"2 * m \\<noteq> Suc (2 * n)\"\n  using Suc_double_not_eq_double [of n m] by simp\n\nlemma odd_Suc_minus_one [simp]: \"odd n \\<Longrightarrow> Suc (n - Suc 0) = n\"\n  by (auto elim: oddE)\n\nlemma even_Suc_div_two [simp]:\n  \"even n \\<Longrightarrow> Suc n div 2 = n div 2\"\n  by auto\n\nlemma odd_Suc_div_two [simp]:\n  \"odd n \\<Longrightarrow> Suc n div 2 = Suc (n div 2)\"\n  by (auto elim: oddE)\n\nlemma odd_two_times_div_two_nat [simp]:\n  assumes \"odd n\"\n  shows \"2 * (n div 2) = n - (1 :: nat)\"\nproof -\n  from assms have \"2 * (n div 2) + 1 = n\"\n    by (auto elim: oddE)\n  then have \"Suc (2 * (n div 2)) - 1 = n - 1\"\n    by simp\n  then show ?thesis\n    by simp\nqed\n\nlemma not_mod2_eq_Suc_0_eq_0 [simp]:\n  \"n mod 2 \\<noteq> Suc 0 \\<longleftrightarrow> n mod 2 = 0\"\n  using not_mod_2_eq_1_eq_0 [of n] by simp\n\nlemma odd_card_imp_not_empty:\n  \\<open>A \\<noteq> {}\\<close> if \\<open>odd (card A)\\<close>\n  using that by auto\n\nlemma nat_induct2 [case_names 0 1 step]:\n  assumes \"P 0\" \"P 1\" and step: \"\\<And>n::nat. P n \\<Longrightarrow> P (n + 2)\"\n  shows \"P n\"\nproof (induct n rule: less_induct)\n  case (less n)\n  show ?case\n  proof (cases \"n < Suc (Suc 0)\")\n    case True\n    then show ?thesis\n      using assms by (auto simp: less_Suc_eq)\n  next\n    case False\n    then obtain k where k: \"n = Suc (Suc k)\"\n      by (force simp: not_less nat_le_iff_add)\n    then have \"k<n\"\n      by simp\n    with less assms have \"P (k+2)\"\n      by blast\n    then show ?thesis\n      by (simp add: k)\n  qed\nqed\n\ncontext semiring_parity\nbegin\n\nlemma even_sum_iff:\n  \\<open>even (sum f A) \\<longleftrightarrow> even (card {a\\<in>A. odd (f a)})\\<close> if \\<open>finite A\\<close>\nusing that proof (induction A)\n  case empty\n  then show ?case\n    by simp\nnext\n  case (insert a A)\n  moreover have \\<open>{b \\<in> insert a A. odd (f b)} = (if odd (f a) then {a} else {}) \\<union> {b \\<in> A. odd (f b)}\\<close>\n    by auto\n  ultimately show ?case\n    by simp\nqed\n\nlemma even_mask_iff [simp]:\n  \\<open>even (2 ^ n - 1) \\<longleftrightarrow> n = 0\\<close>\nproof (cases \\<open>n = 0\\<close>)\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  then have \\<open>{a. a = 0 \\<and> a < n} = {0}\\<close>\n    by auto\n  then show ?thesis\n    by (auto simp add: mask_eq_sum_exp even_sum_iff)\nqed\n\nlemma even_of_nat_iff [simp]:\n  \"even (of_nat n) \\<longleftrightarrow> even n\"\n  by (induction n) simp_all\n\nend\n\n\nsubsection \\<open>Parity and powers\\<close>\n\ncontext ring_1\nbegin\n\nlemma power_minus_even [simp]: \"even n \\<Longrightarrow> (- a) ^ n = a ^ n\"\n  by (auto elim: evenE)\n\nlemma power_minus_odd [simp]: \"odd n \\<Longrightarrow> (- a) ^ n = - (a ^ n)\"\n  by (auto elim: oddE)\n\nlemma uminus_power_if:\n  \"(- a) ^ n = (if even n then a ^ n else - (a ^ n))\"\n  by auto\n\nlemma neg_one_even_power [simp]: \"even n \\<Longrightarrow> (- 1) ^ n = 1\"\n  by simp\n\nlemma neg_one_odd_power [simp]: \"odd n \\<Longrightarrow> (- 1) ^ n = - 1\"\n  by simp\n\nlemma neg_one_power_add_eq_neg_one_power_diff: \"k \\<le> n \\<Longrightarrow> (- 1) ^ (n + k) = (- 1) ^ (n - k)\"\n  by (cases \"even (n + k)\") auto\n\nlemma minus_one_power_iff: \"(- 1) ^ n = (if even n then 1 else - 1)\"\n  by (induct n) auto\n\nend\n\ncontext linordered_idom\nbegin\n\nlemma zero_le_even_power: \"even n \\<Longrightarrow> 0 \\<le> a ^ n\"\n  by (auto elim: evenE)\n\nlemma zero_le_odd_power: \"odd n \\<Longrightarrow> 0 \\<le> a ^ n \\<longleftrightarrow> 0 \\<le> a\"\n  by (auto simp add: power_even_eq zero_le_mult_iff elim: oddE)\n\nlemma zero_le_power_eq: \"0 \\<le> a ^ n \\<longleftrightarrow> even n \\<or> odd n \\<and> 0 \\<le> a\"\n  by (auto simp add: zero_le_even_power zero_le_odd_power)\n\nlemma zero_less_power_eq: \"0 < a ^ n \\<longleftrightarrow> n = 0 \\<or> even n \\<and> a \\<noteq> 0 \\<or> odd n \\<and> 0 < a\"\nproof -\n  have [simp]: \"0 = a ^ n \\<longleftrightarrow> a = 0 \\<and> n > 0\"\n    unfolding power_eq_0_iff [of a n, symmetric] by blast\n  show ?thesis\n    unfolding less_le zero_le_power_eq by auto\nqed\n\nlemma power_less_zero_eq [simp]: \"a ^ n < 0 \\<longleftrightarrow> odd n \\<and> a < 0\"\n  unfolding not_le [symmetric] zero_le_power_eq by auto\n\nlemma power_le_zero_eq: \"a ^ n \\<le> 0 \\<longleftrightarrow> n > 0 \\<and> (odd n \\<and> a \\<le> 0 \\<or> even n \\<and> a = 0)\"\n  unfolding not_less [symmetric] zero_less_power_eq by auto\n\nlemma power_even_abs: \"even n \\<Longrightarrow> \\<bar>a\\<bar> ^ n = a ^ n\"\n  using power_abs [of a n] by (simp add: zero_le_even_power)\n\nlemma power_mono_even:\n  assumes \"even n\" and \"\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\n  shows \"a ^ n \\<le> b ^ n\"\nproof -\n  have \"0 \\<le> \\<bar>a\\<bar>\" by auto\n  with \\<open>\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\\<close> have \"\\<bar>a\\<bar> ^ n \\<le> \\<bar>b\\<bar> ^ n\"\n    by (rule power_mono)\n  with \\<open>even n\\<close> show ?thesis\n    by (simp add: power_even_abs)\nqed\n\nlemma power_mono_odd:\n  assumes \"odd n\" and \"a \\<le> b\"\n  shows \"a ^ n \\<le> b ^ n\"\nproof (cases \"b < 0\")\n  case True\n  with \\<open>a \\<le> b\\<close> have \"- b \\<le> - a\" and \"0 \\<le> - b\" by auto\n  then have \"(- b) ^ n \\<le> (- a) ^ n\" by (rule power_mono)\n  with \\<open>odd n\\<close> show ?thesis by simp\nnext\n  case False\n  then have \"0 \\<le> b\" by auto\n  show ?thesis\n  proof (cases \"a < 0\")\n    case True\n    then have \"n \\<noteq> 0\" and \"a \\<le> 0\" using \\<open>odd n\\<close> [THEN odd_pos] by auto\n    then have \"a ^ n \\<le> 0\" unfolding power_le_zero_eq using \\<open>odd n\\<close> by auto\n    moreover from \\<open>0 \\<le> b\\<close> have \"0 \\<le> b ^ n\" by auto\n    ultimately show ?thesis by auto\n  next\n    case False\n    then have \"0 \\<le> a\" by auto\n    with \\<open>a \\<le> b\\<close> show ?thesis\n      using power_mono by auto\n  qed\nqed\n\ntext \\<open>Simplify, when the exponent is a numeral\\<close>\n\nlemma zero_le_power_eq_numeral [simp]:\n  \"0 \\<le> a ^ numeral w \\<longleftrightarrow> even (numeral w :: nat) \\<or> odd (numeral w :: nat) \\<and> 0 \\<le> a\"\n  by (fact zero_le_power_eq)\n\nlemma zero_less_power_eq_numeral [simp]:\n  \"0 < a ^ numeral w \\<longleftrightarrow>\n    numeral w = (0 :: nat) \\<or>\n    even (numeral w :: nat) \\<and> a \\<noteq> 0 \\<or>\n    odd (numeral w :: nat) \\<and> 0 < a\"\n  by (fact zero_less_power_eq)\n\nlemma power_le_zero_eq_numeral [simp]:\n  \"a ^ numeral w \\<le> 0 \\<longleftrightarrow>\n    (0 :: nat) < numeral w \\<and>\n    (odd (numeral w :: nat) \\<and> a \\<le> 0 \\<or> even (numeral w :: nat) \\<and> a = 0)\"\n  by (fact power_le_zero_eq)\n\nlemma power_less_zero_eq_numeral [simp]:\n  \"a ^ numeral w < 0 \\<longleftrightarrow> odd (numeral w :: nat) \\<and> a < 0\"\n  by (fact power_less_zero_eq)\n\nlemma power_even_abs_numeral [simp]:\n  \"even (numeral w :: nat) \\<Longrightarrow> \\<bar>a\\<bar> ^ numeral w = a ^ numeral w\"\n  by (fact power_even_abs)\n\nend\n\n\nsubsection \\<open>Instance for \\<^typ>\\<open>int\\<close>\\<close>\n  \nlemma even_diff_iff:\n  \"even (k - l) \\<longleftrightarrow> even (k + l)\" for k l :: int\n  by (fact even_diff)\n\nlemma even_abs_add_iff:\n  \"even (\\<bar>k\\<bar> + l) \\<longleftrightarrow> even (k + l)\" for k l :: int\n  by simp\n\nlemma even_add_abs_iff:\n  \"even (k + \\<bar>l\\<bar>) \\<longleftrightarrow> even (k + l)\" for k l :: int\n  by simp\n\nlemma even_nat_iff: \"0 \\<le> k \\<Longrightarrow> even (nat k) \\<longleftrightarrow> even k\"\n  by (simp add: even_of_nat_iff [of \"nat k\", where ?'a = int, symmetric])\n\ncontext\n  assumes \"SORT_CONSTRAINT('a::division_ring)\"\nbegin\n\nlemma power_int_minus_left:\n  \"power_int (-a :: 'a) n = (if even n then power_int a n else -power_int a n)\"\n  by (auto simp: power_int_def minus_one_power_iff even_nat_iff)\n\nlemma power_int_minus_left_even [simp]: \"even n \\<Longrightarrow> power_int (-a :: 'a) n = power_int a n\"\n  by (simp add: power_int_minus_left)\n\nlemma power_int_minus_left_odd [simp]: \"odd n \\<Longrightarrow> power_int (-a :: 'a) n = -power_int a n\"\n  by (simp add: power_int_minus_left)\n\nlemma power_int_minus_left_distrib:\n  \"NO_MATCH (-1) x \\<Longrightarrow> power_int (-a :: 'a) n = power_int (-1) n * power_int a n\"\n  by (simp add: power_int_minus_left)\n\nlemma power_int_minus_one_minus: \"power_int (-1 :: 'a) (-n) = power_int (-1) n\"\n  by (simp add: power_int_minus_left)\n\nlemma power_int_minus_one_diff_commute: \"power_int (-1 :: 'a) (a - b) = power_int (-1) (b - a)\"\n  by (subst power_int_minus_one_minus [symmetric]) auto\n\nlemma power_int_minus_one_mult_self [simp]:\n  \"power_int (-1 :: 'a) m * power_int (-1) m = 1\"\n  by (simp add: power_int_minus_left)\n\nlemma power_int_minus_one_mult_self' [simp]:\n  \"power_int (-1 :: 'a) m * (power_int (-1) m * b) = b\"\n  by (simp add: power_int_minus_left)\n\nend\n\n\nsubsection \\<open>Special case: euclidean rings containing the natural numbers\\<close>\n\nclass unique_euclidean_semiring_with_nat = semidom + semiring_char_0 + unique_euclidean_semiring +\n  assumes of_nat_div: \"of_nat (m div n) = of_nat m div of_nat n\"\n    and division_segment_of_nat [simp]: \"division_segment (of_nat n) = 1\"\n    and division_segment_euclidean_size [simp]: \"division_segment a * of_nat (euclidean_size a) = a\"\nbegin\n\nlemma division_segment_eq_iff:\n  \"a = b\" if \"division_segment a = division_segment b\"\n    and \"euclidean_size a = euclidean_size b\"\n  using that division_segment_euclidean_size [of a] by simp\n\nlemma euclidean_size_of_nat [simp]:\n  \"euclidean_size (of_nat n) = n\"\nproof -\n  have \"division_segment (of_nat n) * of_nat (euclidean_size (of_nat n)) = of_nat n\"\n    by (fact division_segment_euclidean_size)\n  then show ?thesis by simp\nqed\n\nlemma of_nat_euclidean_size:\n  \"of_nat (euclidean_size a) = a div division_segment a\"\nproof -\n  have \"of_nat (euclidean_size a) = division_segment a * of_nat (euclidean_size a) div division_segment a\"\n    by (subst nonzero_mult_div_cancel_left) simp_all\n  also have \"\\<dots> = a div division_segment a\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma division_segment_1 [simp]:\n  \"division_segment 1 = 1\"\n  using division_segment_of_nat [of 1] by simp\n\nlemma division_segment_numeral [simp]:\n  \"division_segment (numeral k) = 1\"\n  using division_segment_of_nat [of \"numeral k\"] by simp\n\nlemma euclidean_size_1 [simp]:\n  \"euclidean_size 1 = 1\"\n  using euclidean_size_of_nat [of 1] by simp\n\nlemma euclidean_size_numeral [simp]:\n  \"euclidean_size (numeral k) = numeral k\"\n  using euclidean_size_of_nat [of \"numeral k\"] by simp\n\nlemma of_nat_dvd_iff:\n  \"of_nat m dvd of_nat n \\<longleftrightarrow> m dvd n\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?Q\n    then show ?P\n      by auto\n  next\n    assume ?P\n    with False have \"of_nat n = of_nat n div of_nat m * of_nat m\"\n      by simp\n    then have \"of_nat n = of_nat (n div m * m)\"\n      by (simp add: of_nat_div)\n    then have \"n = n div m * m\"\n      by (simp only: of_nat_eq_iff)\n    then have \"n = m * (n div m)\"\n      by (simp add: ac_simps)\n    then show ?Q ..\n  qed\nqed\n\nlemma of_nat_mod:\n  \"of_nat (m mod n) = of_nat m mod of_nat n\"\nproof -\n  have \"of_nat m div of_nat n * of_nat n + of_nat m mod of_nat n = of_nat m\"\n    by (simp add: div_mult_mod_eq)\n  also have \"of_nat m = of_nat (m div n * n + m mod n)\"\n    by simp\n  finally show ?thesis\n    by (simp only: of_nat_div of_nat_mult of_nat_add) simp\nqed\n\nlemma one_div_two_eq_zero [simp]:\n  \"1 div 2 = 0\"\nproof -\n  from of_nat_div [symmetric] have \"of_nat 1 div of_nat 2 = of_nat 0\"\n    by (simp only:) simp\n  then show ?thesis\n    by simp\nqed\n\nlemma one_mod_two_eq_one [simp]:\n  \"1 mod 2 = 1\"\nproof -\n  from of_nat_mod [symmetric] have \"of_nat 1 mod of_nat 2 = of_nat 1\"\n    by (simp only:) simp\n  then show ?thesis\n    by simp\nqed\n\nlemma one_mod_2_pow_eq [simp]:\n  \"1 mod (2 ^ n) = of_bool (n > 0)\"\nproof -\n  have \"1 mod (2 ^ n) = of_nat (1 mod (2 ^ n))\"\n    using of_nat_mod [of 1 \"2 ^ n\"] by simp\n  also have \"\\<dots> = of_bool (n > 0)\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma one_div_2_pow_eq [simp]:\n  \"1 div (2 ^ n) = of_bool (n = 0)\"\n  using div_mult_mod_eq [of 1 \"2 ^ n\"] by auto\n\nlemma div_mult2_eq':\n  \\<open>a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\\<close>\nproof (cases \\<open>m = 0 \\<or> n = 0\\<close>)\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  then have \\<open>m > 0\\<close> \\<open>n > 0\\<close>\n    by simp_all\n  show ?thesis\n  proof (cases \\<open>of_nat m * of_nat n dvd a\\<close>)\n    case True\n    then obtain b where \\<open>a = (of_nat m * of_nat n) * b\\<close> ..\n    then have \\<open>a = of_nat m * (of_nat n * b)\\<close>\n      by (simp add: ac_simps)\n    then show ?thesis\n      by simp\n  next\n    case False\n    define q where \\<open>q = a div (of_nat m * of_nat n)\\<close>\n    define r where \\<open>r = a mod (of_nat m * of_nat n)\\<close>\n    from \\<open>m > 0\\<close> \\<open>n > 0\\<close> \\<open>\\<not> of_nat m * of_nat n dvd a\\<close> r_def have \"division_segment r = 1\"\n      using division_segment_of_nat [of \"m * n\"] by (simp add: division_segment_mod)\n    with division_segment_euclidean_size [of r]\n    have \"of_nat (euclidean_size r) = r\"\n      by simp\n    have \"a mod (of_nat m * of_nat n) div (of_nat m * of_nat n) = 0\"\n      by simp\n    with \\<open>m > 0\\<close> \\<open>n > 0\\<close> r_def have \"r div (of_nat m * of_nat n) = 0\"\n      by simp\n    with \\<open>of_nat (euclidean_size r) = r\\<close>\n    have \"of_nat (euclidean_size r) div (of_nat m * of_nat n) = 0\"\n      by simp\n    then have \"of_nat (euclidean_size r div (m * n)) = 0\"\n      by (simp add: of_nat_div)\n    then have \"of_nat (euclidean_size r div m div n) = 0\"\n      by (simp add: div_mult2_eq)\n    with \\<open>of_nat (euclidean_size r) = r\\<close> have \"r div of_nat m div of_nat n = 0\"\n      by (simp add: of_nat_div)\n    with \\<open>m > 0\\<close> \\<open>n > 0\\<close> q_def\n    have \"q = (r div of_nat m + q * of_nat n * of_nat m div of_nat m) div of_nat n\"\n      by simp\n    moreover have \\<open>a = q * (of_nat m * of_nat n) + r\\<close>\n      by (simp add: q_def r_def div_mult_mod_eq)\n    ultimately show \\<open>a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\\<close>\n      using q_def [symmetric] div_plus_div_distrib_dvd_right [of \\<open>of_nat m\\<close> \\<open>q * (of_nat m * of_nat n)\\<close> r]\n      by (simp add: ac_simps)\n  qed\nqed\n\nlemma mod_mult2_eq':\n  \"a mod (of_nat m * of_nat n) = of_nat m * (a div of_nat m mod of_nat n) + a mod of_nat m\"\nproof -\n  have \"a div (of_nat m * of_nat n) * (of_nat m * of_nat n) + a mod (of_nat m * of_nat n) = a div of_nat m div of_nat n * of_nat n * of_nat m + (a div of_nat m mod of_nat n * of_nat m + a mod of_nat m)\"\n    by (simp add: combine_common_factor div_mult_mod_eq)\n  moreover have \"a div of_nat m div of_nat n * of_nat n * of_nat m = of_nat n * of_nat m * (a div of_nat m div of_nat n)\"\n    by (simp add: ac_simps)\n  ultimately show ?thesis\n    by (simp add: div_mult2_eq' mult_commute)\nqed\n\nlemma div_mult2_numeral_eq:\n  \"a div numeral k div numeral l = a div numeral (k * l)\" (is \"?A = ?B\")\nproof -\n  have \"?A = a div of_nat (numeral k) div of_nat (numeral l)\"\n    by simp\n  also have \"\\<dots> = a div (of_nat (numeral k) * of_nat (numeral l))\"\n    by (fact div_mult2_eq' [symmetric])\n  also have \"\\<dots> = ?B\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma numeral_Bit0_div_2:\n  \"numeral (num.Bit0 n) div 2 = numeral n\"\nproof -\n  have \"numeral (num.Bit0 n) = numeral n + numeral n\"\n    by (simp only: numeral.simps)\n  also have \"\\<dots> = numeral n * 2\"\n    by (simp add: mult_2_right)\n  finally have \"numeral (num.Bit0 n) div 2 = numeral n * 2 div 2\"\n    by simp\n  also have \"\\<dots> = numeral n\"\n    by (rule nonzero_mult_div_cancel_right) simp\n  finally show ?thesis .\nqed\n\nlemma numeral_Bit1_div_2:\n  \"numeral (num.Bit1 n) div 2 = numeral n\"\nproof -\n  have \"numeral (num.Bit1 n) = numeral n + numeral n + 1\"\n    by (simp only: numeral.simps)\n  also have \"\\<dots> = numeral n * 2 + 1\"\n    by (simp add: mult_2_right)\n  finally have \"numeral (num.Bit1 n) div 2 = (numeral n * 2 + 1) div 2\"\n    by simp\n  also have \"\\<dots> = numeral n * 2 div 2 + 1 div 2\"\n    using dvd_triv_right by (rule div_plus_div_distrib_dvd_left)\n  also have \"\\<dots> = numeral n * 2 div 2\"\n    by simp\n  also have \"\\<dots> = numeral n\"\n    by (rule nonzero_mult_div_cancel_right) simp\n  finally show ?thesis .\nqed\n\nlemma exp_mod_exp:\n  \\<open>2 ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\\<close>\nproof -\n  have \\<open>(2::nat) ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\\<close> (is \\<open>?lhs = ?rhs\\<close>)\n    by (auto simp add: not_less monoid_mult_class.power_add dest!: le_Suc_ex)\n  then have \\<open>of_nat ?lhs = of_nat ?rhs\\<close>\n    by simp\n  then show ?thesis\n    by (simp add: of_nat_mod)\nqed\n\nlemma mask_mod_exp:\n  \\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - 1\\<close>\nproof -\n  have \\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - (1::nat)\\<close> (is \\<open>?lhs = ?rhs\\<close>)\n  proof (cases \\<open>n \\<le> m\\<close>)\n    case True\n    then show ?thesis\n      by (simp add: Suc_le_lessD)\n  next\n    case False\n    then have \\<open>m < n\\<close>\n      by simp\n    then obtain q where n: \\<open>n = Suc q + m\\<close>\n      by (auto dest: less_imp_Suc_add)\n    then have \\<open>min m n = m\\<close>\n      by simp\n    moreover have \\<open>(2::nat) ^ m \\<le> 2 * 2 ^ q * 2 ^ m\\<close>\n      using mult_le_mono1 [of 1 \\<open>2 * 2 ^ q\\<close> \\<open>2 ^ m\\<close>] by simp\n    with n have \\<open>2 ^ n - 1 = (2 ^ Suc q - 1) * 2 ^ m + (2 ^ m - (1::nat))\\<close>\n      by (simp add: monoid_mult_class.power_add algebra_simps)\n    ultimately show ?thesis\n      by (simp only: euclidean_semiring_cancel_class.mod_mult_self3) simp\n  qed\n  then have \\<open>of_nat ?lhs = of_nat ?rhs\\<close>\n    by simp\n  then show ?thesis\n    by (simp add: of_nat_mod of_nat_diff)\nqed\n\nlemma of_bool_half_eq_0 [simp]:\n  \\<open>of_bool b div 2 = 0\\<close>\n  by simp\n\nend\n\nclass unique_euclidean_ring_with_nat = ring + unique_euclidean_semiring_with_nat\n\ninstance nat :: unique_euclidean_semiring_with_nat\n  by standard (simp_all add: dvd_eq_mod_eq_0)\n\ninstance int :: unique_euclidean_ring_with_nat\n  by standard (auto simp add: divide_int_def division_segment_int_def elim: contrapos_np)\n\n\ncontext unique_euclidean_semiring_with_nat\nbegin\n\nsubclass semiring_parity\nproof\n  show \"2 dvd a \\<longleftrightarrow> a mod 2 = 0\" for a\n    by (fact dvd_eq_mod_eq_0)\n  show \"\\<not> 2 dvd a \\<longleftrightarrow> a mod 2 = 1\" for a\n  proof\n    assume \"a mod 2 = 1\"\n    then show \"\\<not> 2 dvd a\"\n      by auto\n  next\n    assume \"\\<not> 2 dvd a\"\n    have eucl: \"euclidean_size (a mod 2) = 1\"\n    proof (rule order_antisym)\n      show \"euclidean_size (a mod 2) \\<le> 1\"\n        using mod_size_less [of 2 a] by simp\n      show \"1 \\<le> euclidean_size (a mod 2)\"\n        using \\<open>\\<not> 2 dvd a\\<close> by (simp add: Suc_le_eq dvd_eq_mod_eq_0)\n    qed \n    from \\<open>\\<not> 2 dvd a\\<close> have \"\\<not> of_nat 2 dvd division_segment a * of_nat (euclidean_size a)\"\n      by simp\n    then have \"\\<not> of_nat 2 dvd of_nat (euclidean_size a)\"\n      by (auto simp only: dvd_mult_unit_iff' is_unit_division_segment)\n    then have \"\\<not> 2 dvd euclidean_size a\"\n      using of_nat_dvd_iff [of 2] by simp\n    then have \"euclidean_size a mod 2 = 1\"\n      by (simp add: semidom_modulo_class.dvd_eq_mod_eq_0)\n    then have \"of_nat (euclidean_size a mod 2) = of_nat 1\"\n      by simp\n    then have \"of_nat (euclidean_size a) mod 2 = 1\"\n      by (simp add: of_nat_mod)\n    from \\<open>\\<not> 2 dvd a\\<close> eucl\n    show \"a mod 2 = 1\"\n      by (auto intro: division_segment_eq_iff simp add: division_segment_mod)\n  qed\n  show \"\\<not> is_unit 2\"\n  proof (rule notI)\n    assume \"is_unit 2\"\n    then have \"of_nat 2 dvd of_nat 1\"\n      by simp\n    then have \"is_unit (2::nat)\"\n      by (simp only: of_nat_dvd_iff)\n    then show False\n      by simp\n  qed\nqed\n\nlemma even_succ_div_two [simp]:\n  \"even a \\<Longrightarrow> (a + 1) div 2 = a div 2\"\n  by (cases \"a = 0\") (auto elim!: evenE dest: mult_not_zero)\n\nlemma odd_succ_div_two [simp]:\n  \"odd a \\<Longrightarrow> (a + 1) div 2 = a div 2 + 1\"\n  by (auto elim!: oddE simp add: add.assoc)\n\nlemma even_two_times_div_two:\n  \"even a \\<Longrightarrow> 2 * (a div 2) = a\"\n  by (fact dvd_mult_div_cancel)\n\nlemma odd_two_times_div_two_succ [simp]:\n  \"odd a \\<Longrightarrow> 2 * (a div 2) + 1 = a\"\n  using mult_div_mod_eq [of 2 a]\n  by (simp add: even_iff_mod_2_eq_zero)\n\nlemma coprime_left_2_iff_odd [simp]:\n  \"coprime 2 a \\<longleftrightarrow> odd a\"\nproof\n  assume \"odd a\"\n  show \"coprime 2 a\"\n  proof (rule coprimeI)\n    fix b\n    assume \"b dvd 2\" \"b dvd a\"\n    then have \"b dvd a mod 2\"\n      by (auto intro: dvd_mod)\n    with \\<open>odd a\\<close> show \"is_unit b\"\n      by (simp add: mod_2_eq_odd)\n  qed\nnext\n  assume \"coprime 2 a\"\n  show \"odd a\"\n  proof (rule notI)\n    assume \"even a\"\n    then obtain b where \"a = 2 * b\" ..\n    with \\<open>coprime 2 a\\<close> have \"coprime 2 (2 * b)\"\n      by simp\n    moreover have \"\\<not> coprime 2 (2 * b)\"\n      by (rule not_coprimeI [of 2]) simp_all\n    ultimately show False\n      by blast\n  qed\nqed\n\nlemma coprime_right_2_iff_odd [simp]:\n  \"coprime a 2 \\<longleftrightarrow> odd a\"\n  using coprime_left_2_iff_odd [of a] by (simp add: ac_simps)\n\nend\n\ncontext unique_euclidean_ring_with_nat\nbegin\n\nsubclass ring_parity ..\n\nlemma minus_1_mod_2_eq [simp]:\n  \"- 1 mod 2 = 1\"\n  by (simp add: mod_2_eq_odd)\n\nlemma minus_1_div_2_eq [simp]:\n  \"- 1 div 2 = - 1\"\nproof -\n  from div_mult_mod_eq [of \"- 1\" 2]\n  have \"- 1 div 2 * 2 = - 1 * 2\"\n    using add_implies_diff by fastforce\n  then show ?thesis\n    using mult_right_cancel [of 2 \"- 1 div 2\" \"- 1\"] by simp\nqed\n\nend\n\ncontext unique_euclidean_semiring_with_nat\nbegin\n\nlemma even_mask_div_iff':\n  \\<open>even ((2 ^ m - 1) div 2 ^ n) \\<longleftrightarrow> m \\<le> n\\<close>\nproof -\n  have \\<open>even ((2 ^ m - 1) div 2 ^ n) \\<longleftrightarrow> even (of_nat ((2 ^ m - Suc 0) div 2 ^ n))\\<close>\n    by (simp only: of_nat_div) (simp add: of_nat_diff)\n  also have \\<open>\\<dots> \\<longleftrightarrow> even ((2 ^ m - Suc 0) div 2 ^ n)\\<close>\n    by simp\n  also have \\<open>\\<dots> \\<longleftrightarrow> m \\<le> n\\<close>\n  proof (cases \\<open>m \\<le> n\\<close>)\n    case True\n    then show ?thesis\n      by (simp add: Suc_le_lessD)\n  next\n    case False\n    then obtain r where r: \\<open>m = n + Suc r\\<close>\n      using less_imp_Suc_add by fastforce\n    from r have \\<open>{q. q < m} \\<inter> {q. 2 ^ n dvd (2::nat) ^ q} = {q. n \\<le> q \\<and> q < m}\\<close>\n      by (auto simp add: dvd_power_iff_le)\n    moreover from r have \\<open>{q. q < m} \\<inter> {q. \\<not> 2 ^ n dvd (2::nat) ^ q} = {q. q < n}\\<close>\n      by (auto simp add: dvd_power_iff_le)\n    moreover from False have \\<open>{q. n \\<le> q \\<and> q < m \\<and> q \\<le> n} = {n}\\<close>\n      by auto\n    then have \\<open>odd ((\\<Sum>a\\<in>{q. n \\<le> q \\<and> q < m}. 2 ^ a div (2::nat) ^ n) + sum ((^) 2) {q. q < n} div 2 ^ n)\\<close>\n      by (simp_all add: euclidean_semiring_cancel_class.power_diff_power_eq semiring_parity_class.even_sum_iff not_less mask_eq_sum_exp_nat [symmetric])\n    ultimately have \\<open>odd (sum ((^) (2::nat)) {q. q < m} div 2 ^ n)\\<close>\n      by (subst euclidean_semiring_cancel_class.sum_div_partition) simp_all\n    with False show ?thesis\n      by (simp add: mask_eq_sum_exp_nat)\n  qed\n  finally show ?thesis .\nqed\n\nend\n\n\nsubsection \\<open>Generic symbolic computations\\<close>\n\ntext \\<open>\n  The following type class contains everything necessary to formulate\n  a division algorithm in ring structures with numerals, restricted\n  to its positive segments.\n\\<close>\n\nclass unique_euclidean_semiring_with_nat_division = unique_euclidean_semiring_with_nat +\n  fixes divmod :: \\<open>num \\<Rightarrow> num \\<Rightarrow> 'a \\<times> 'a\\<close>\n    and divmod_step :: \\<open>'a \\<Rightarrow> 'a \\<times> 'a \\<Rightarrow> 'a \\<times> 'a\\<close> \\<comment> \\<open>\n      These are conceptually definitions but force generated code\n      to be monomorphic wrt. particular instances of this class which\n      yields a significant speedup.\\<close>\n  assumes divmod_def: \\<open>divmod m n = (numeral m div numeral n, numeral m mod numeral n)\\<close>\n    and divmod_step_def [simp]: \\<open>divmod_step l (q, r) =\n      (if euclidean_size l \\<le> euclidean_size r then (2 * q + 1, r - l)\n       else (2 * q, r))\\<close> \\<comment> \\<open>\n         This is a formulation of one step (referring to one digit position)\n         in school-method division: compare the dividend at the current\n         digit position with the remainder from previous division steps\n         and evaluate accordingly.\\<close>\nbegin\n\nlemma fst_divmod:\n  \\<open>fst (divmod m n) = numeral m div numeral n\\<close>\n  by (simp add: divmod_def)\n\nlemma snd_divmod:\n  \\<open>snd (divmod m n) = numeral m mod numeral n\\<close>\n  by (simp add: divmod_def)\n\ntext \\<open>\n  Following a formulation of school-method division.\n  If the divisor is smaller than the dividend, terminate.\n  If not, shift the dividend to the right until termination\n  occurs and then reiterate single division steps in the\n  opposite direction.\n\\<close>\n\nlemma divmod_divmod_step:\n  \\<open>divmod m n = (if m < n then (0, numeral m)\n    else divmod_step (numeral n) (divmod m (Num.Bit0 n)))\\<close>\nproof (cases \\<open>m < n\\<close>)\n  case True\n  then show ?thesis\n    by (simp add: prod_eq_iff fst_divmod snd_divmod flip: of_nat_numeral of_nat_div of_nat_mod)\nnext\n  case False\n  define r s t where \\<open>r = (numeral m :: nat)\\<close> \\<open>s = (numeral n :: nat)\\<close> \\<open>t = 2 * s\\<close>\n  then have *: \\<open>numeral m = of_nat r\\<close> \\<open>numeral n = of_nat s\\<close> \\<open>numeral (num.Bit0 n) = of_nat t\\<close>\n    and \\<open>\\<not> s \\<le> r mod s\\<close>\n    by (simp_all add: not_le)\n  have t: \\<open>2 * (r div t) = r div s - r div s mod 2\\<close>\n    \\<open>r mod t = s * (r div s mod 2) + r mod s\\<close>\n    by (simp add: Rings.minus_mod_eq_mult_div Groups.mult.commute [of 2] Euclidean_Rings.div_mult2_eq \\<open>t = 2 * s\\<close>)\n      (use mod_mult2_eq [of r s 2] in \\<open>simp add: ac_simps \\<open>t = 2 * s\\<close>\\<close>)\n  have rs: \\<open>r div s mod 2 = 0 \\<or> r div s mod 2 = Suc 0\\<close>\n    by auto\n  from \\<open>\\<not> s \\<le> r mod s\\<close> have \\<open>s \\<le> r mod t \\<Longrightarrow>\n     r div s = Suc (2 * (r div t)) \\<and>\n     r mod s = r mod t - s\\<close>\n    using rs\n    by (auto simp add: t)\n  moreover have \\<open>r mod t < s \\<Longrightarrow>\n     r div s = 2 * (r div t) \\<and>\n     r mod s = r mod t\\<close>\n    using rs\n    by (auto simp add: t)\n  ultimately show ?thesis\n    by (simp add: divmod_def prod_eq_iff split_def Let_def\n        not_less mod_eq_0_iff_dvd Rings.mod_eq_0_iff_dvd False not_le *)\n    (simp add: flip: of_nat_numeral of_nat_mult add.commute [of 1] of_nat_div of_nat_mod of_nat_Suc of_nat_diff)\nqed\n\ntext \\<open>The division rewrite proper -- first, trivial results involving \\<open>1\\<close>\\<close>\n\nlemma divmod_trivial [simp]:\n  \"divmod m Num.One = (numeral m, 0)\"\n  \"divmod num.One (num.Bit0 n) = (0, Numeral1)\"\n  \"divmod num.One (num.Bit1 n) = (0, Numeral1)\"\n  using divmod_divmod_step [of \"Num.One\"] by (simp_all add: divmod_def)\n\ntext \\<open>Division by an even number is a right-shift\\<close>\n\nlemma divmod_cancel [simp]:\n  \\<open>divmod (Num.Bit0 m) (Num.Bit0 n) = (case divmod m n of (q, r) \\<Rightarrow> (q, 2 * r))\\<close> (is ?P)\n  \\<open>divmod (Num.Bit1 m) (Num.Bit0 n) = (case divmod m n of (q, r) \\<Rightarrow> (q, 2 * r + 1))\\<close> (is ?Q)\nproof -\n  define r s where \\<open>r = (numeral m :: nat)\\<close> \\<open>s = (numeral n :: nat)\\<close>\n  then have *: \\<open>numeral m = of_nat r\\<close> \\<open>numeral n = of_nat s\\<close>\n    \\<open>numeral (num.Bit0 m) = of_nat (2 * r)\\<close> \\<open>numeral (num.Bit0 n) = of_nat (2 * s)\\<close>\n    \\<open>numeral (num.Bit1 m) = of_nat (Suc (2 * r))\\<close>\n    by simp_all\n  have **: \\<open>Suc (2 * r) div 2 = r\\<close>\n    by simp\n  show ?P and ?Q\n    by (simp_all add: divmod_def *)\n      (simp_all flip: of_nat_numeral of_nat_div of_nat_mod of_nat_mult add.commute [of 1] of_nat_Suc\n       add: Euclidean_Rings.mod_mult_mult1 div_mult2_eq [of _ 2] mod_mult2_eq [of _ 2] **)\nqed\n\ntext \\<open>The really hard work\\<close>\n\nlemma divmod_steps [simp]:\n  \"divmod (num.Bit0 m) (num.Bit1 n) =\n      (if m \\<le> n then (0, numeral (num.Bit0 m))\n       else divmod_step (numeral (num.Bit1 n))\n             (divmod (num.Bit0 m)\n               (num.Bit0 (num.Bit1 n))))\"\n  \"divmod (num.Bit1 m) (num.Bit1 n) =\n      (if m < n then (0, numeral (num.Bit1 m))\n       else divmod_step (numeral (num.Bit1 n))\n             (divmod (num.Bit1 m)\n               (num.Bit0 (num.Bit1 n))))\"\n  by (simp_all add: divmod_divmod_step)\n\nlemmas divmod_algorithm_code = divmod_trivial divmod_cancel divmod_steps\n\ntext \\<open>Special case: divisibility\\<close>\n\ndefinition divides_aux :: \"'a \\<times> 'a \\<Rightarrow> bool\"\nwhere\n  \"divides_aux qr \\<longleftrightarrow> snd qr = 0\"\n\nlemma divides_aux_eq [simp]:\n  \"divides_aux (q, r) \\<longleftrightarrow> r = 0\"\n  by (simp add: divides_aux_def)\n\nlemma dvd_numeral_simp [simp]:\n  \"numeral m dvd numeral n \\<longleftrightarrow> divides_aux (divmod n m)\"\n  by (simp add: divmod_def mod_eq_0_iff_dvd)\n\ntext \\<open>Generic computation of quotient and remainder\\<close>\n\nlemma numeral_div_numeral [simp]:\n  \"numeral k div numeral l = fst (divmod k l)\"\n  by (simp add: fst_divmod)\n\nlemma numeral_mod_numeral [simp]:\n  \"numeral k mod numeral l = snd (divmod k l)\"\n  by (simp add: snd_divmod)\n\nlemma one_div_numeral [simp]:\n  \"1 div numeral n = fst (divmod num.One n)\"\n  by (simp add: fst_divmod)\n\nlemma one_mod_numeral [simp]:\n  \"1 mod numeral n = snd (divmod num.One n)\"\n  by (simp add: snd_divmod)\n\nend\n\ninstantiation nat :: unique_euclidean_semiring_with_nat_division\nbegin\n\ndefinition divmod_nat :: \"num \\<Rightarrow> num \\<Rightarrow> nat \\<times> nat\"\nwhere\n  divmod'_nat_def: \"divmod_nat m n = (numeral m div numeral n, numeral m mod numeral n)\"\n\ndefinition divmod_step_nat :: \"nat \\<Rightarrow> nat \\<times> nat \\<Rightarrow> nat \\<times> nat\"\nwhere\n  \"divmod_step_nat l qr = (let (q, r) = qr\n    in if r \\<ge> l then (2 * q + 1, r - l)\n    else (2 * q, r))\"\n\ninstance\n  by standard (simp_all add: divmod'_nat_def divmod_step_nat_def)\n\nend\n\ndeclare divmod_algorithm_code [where ?'a = nat, code]\n\nlemma Suc_0_div_numeral [simp]:\n  \\<open>Suc 0 div numeral Num.One = 1\\<close>\n  \\<open>Suc 0 div numeral (Num.Bit0 n) = 0\\<close>\n  \\<open>Suc 0 div numeral (Num.Bit1 n) = 0\\<close>\n  by simp_all\n\nlemma Suc_0_mod_numeral [simp]:\n  \\<open>Suc 0 mod numeral Num.One = 0\\<close>\n  \\<open>Suc 0 mod numeral (Num.Bit0 n) = 1\\<close>\n  \\<open>Suc 0 mod numeral (Num.Bit1 n) = 1\\<close>\n  by simp_all\n\ninstantiation int :: unique_euclidean_semiring_with_nat_division\nbegin\n\ndefinition divmod_int :: \"num \\<Rightarrow> num \\<Rightarrow> int \\<times> int\"\nwhere\n  \"divmod_int m n = (numeral m div numeral n, numeral m mod numeral n)\"\n\ndefinition divmod_step_int :: \"int \\<Rightarrow> int \\<times> int \\<Rightarrow> int \\<times> int\"\nwhere\n  \"divmod_step_int l qr = (let (q, r) = qr\n    in if \\<bar>l\\<bar> \\<le> \\<bar>r\\<bar> then (2 * q + 1, r - l)\n    else (2 * q, r))\"\n\ninstance\n  by standard (auto simp add: divmod_int_def divmod_step_int_def)\n\nend\n\ndeclare divmod_algorithm_code [where ?'a = int, code]\n\ncontext\nbegin\n\nqualified definition adjust_div :: \"int \\<times> int \\<Rightarrow> int\"\nwhere\n  \"adjust_div qr = (let (q, r) = qr in q + of_bool (r \\<noteq> 0))\"\n\nqualified lemma adjust_div_eq [simp, code]:\n  \"adjust_div (q, r) = q + of_bool (r \\<noteq> 0)\"\n  by (simp add: adjust_div_def)\n\nqualified definition adjust_mod :: \"num \\<Rightarrow> int \\<Rightarrow> int\"\nwhere\n  [simp]: \"adjust_mod l r = (if r = 0 then 0 else numeral l - r)\"\n\nlemma minus_numeral_div_numeral [simp]:\n  \"- numeral m div numeral n = - (adjust_div (divmod m n) :: int)\"\nproof -\n  have \"int (fst (divmod m n)) = fst (divmod m n)\"\n    by (simp only: fst_divmod divide_int_def) auto\n  then show ?thesis\n    by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def)\nqed\n\nlemma minus_numeral_mod_numeral [simp]:\n  \"- numeral m mod numeral n = adjust_mod n (snd (divmod m n) :: int)\"\nproof (cases \"snd (divmod m n) = (0::int)\")\n  case True\n  then show ?thesis\n    by (simp add: mod_eq_0_iff_dvd divides_aux_def)\nnext\n  case False\n  then have \"int (snd (divmod m n)) = snd (divmod m n)\" if \"snd (divmod m n) \\<noteq> (0::int)\"\n    by (simp only: snd_divmod modulo_int_def) auto\n  then show ?thesis\n    by (simp add: divides_aux_def adjust_div_def)\n      (simp add: divides_aux_def modulo_int_def)\nqed\n\nlemma numeral_div_minus_numeral [simp]:\n  \"numeral m div - numeral n = - (adjust_div (divmod m n) :: int)\"\nproof -\n  have \"int (fst (divmod m n)) = fst (divmod m n)\"\n    by (simp only: fst_divmod divide_int_def) auto\n  then show ?thesis\n    by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def)\nqed\n\nlemma numeral_mod_minus_numeral [simp]:\n  \"numeral m mod - numeral n = - adjust_mod n (snd (divmod m n) :: int)\"\nproof (cases \"snd (divmod m n) = (0::int)\")\n  case True\n  then show ?thesis\n    by (simp add: mod_eq_0_iff_dvd divides_aux_def)\nnext\n  case False\n  then have \"int (snd (divmod m n)) = snd (divmod m n)\" if \"snd (divmod m n) \\<noteq> (0::int)\"\n    by (simp only: snd_divmod modulo_int_def) auto\n  then show ?thesis\n    by (simp add: divides_aux_def adjust_div_def)\n      (simp add: divides_aux_def modulo_int_def)\nqed\n\nlemma minus_one_div_numeral [simp]:\n  \"- 1 div numeral n = - (adjust_div (divmod Num.One n) :: int)\"\n  using minus_numeral_div_numeral [of Num.One n] by simp\n\nlemma minus_one_mod_numeral [simp]:\n  \"- 1 mod numeral n = adjust_mod n (snd (divmod Num.One n) :: int)\"\n  using minus_numeral_mod_numeral [of Num.One n] by simp\n\nlemma one_div_minus_numeral [simp]:\n  \"1 div - numeral n = - (adjust_div (divmod Num.One n) :: int)\"\n  using numeral_div_minus_numeral [of Num.One n] by simp\n\nlemma one_mod_minus_numeral [simp]:\n  \"1 mod - numeral n = - adjust_mod n (snd (divmod Num.One n) :: int)\"\n  using numeral_mod_minus_numeral [of Num.One n] by simp\n\n\n\nend\n\nlemma divmod_BitM_2_eq [simp]:\n  \\<open>divmod (Num.BitM m) (Num.Bit0 Num.One) = (numeral m - 1, (1 :: int))\\<close>\n  by (cases m) simp_all\n\n\nsubsubsection \\<open>Computation by simplification\\<close>\n\nlemma euclidean_size_nat_less_eq_iff:\n  \\<open>euclidean_size m \\<le> euclidean_size n \\<longleftrightarrow> m \\<le> n\\<close> for m n :: nat\n  by simp\n\nlemma euclidean_size_int_less_eq_iff:\n  \\<open>euclidean_size k \\<le> euclidean_size l \\<longleftrightarrow> \\<bar>k\\<bar> \\<le> \\<bar>l\\<bar>\\<close> for k l :: int\n  by auto\n\nsimproc_setup numeral_divmod\n  (\"0 div 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"0 mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"0 div 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"0 mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"0 div - 1 :: int\" | \"0 mod - 1 :: int\" |\n   \"0 div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"0 mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"0 div - numeral b :: int\" | \"0 mod - numeral b :: int\" |\n   \"1 div 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"1 mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"1 div 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"1 mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"1 div - 1 :: int\" | \"1 mod - 1 :: int\" |\n   \"1 div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"1 mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"1 div - numeral b :: int\" |\"1 mod - numeral b :: int\" |\n   \"- 1 div 0 :: int\" | \"- 1 mod 0 :: int\" | \"- 1 div 1 :: int\" | \"- 1 mod 1 :: int\" |\n   \"- 1 div - 1 :: int\" | \"- 1 mod - 1 :: int\" | \"- 1 div numeral b :: int\" | \"- 1 mod numeral b :: int\" |\n   \"- 1 div - numeral b :: int\" | \"- 1 mod - numeral b :: int\" |\n   \"numeral a div 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"numeral a mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"numeral a div 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"numeral a mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"numeral a div - 1 :: int\" | \"numeral a mod - 1 :: int\" |\n   \"numeral a div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"numeral a mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"numeral a div - numeral b :: int\" | \"numeral a mod - numeral b :: int\" |\n   \"- numeral a div 0 :: int\" | \"- numeral a mod 0 :: int\" |\n   \"- numeral a div 1 :: int\" | \"- numeral a mod 1 :: int\" |\n   \"- numeral a div - 1 :: int\" | \"- numeral a mod - 1 :: int\" |\n   \"- numeral a div numeral b :: int\" | \"- numeral a mod numeral b :: int\" |\n   \"- numeral a div - numeral b :: int\" | \"- numeral a mod - numeral b :: int\") = \\<open>\n  let\n    val if_cong = the (Code.get_case_cong \\<^theory> \\<^const_name>\\<open>If\\<close>);\n    fun successful_rewrite ctxt ct =\n      let\n        val thm = Simplifier.rewrite ctxt ct\n      in if Thm.is_reflexive thm then NONE else SOME thm end;\n  in fn phi =>\n    let\n      val simps = Morphism.fact phi (@{thms div_0 mod_0 div_by_0 mod_by_0 div_by_1 mod_by_1\n        one_div_numeral one_mod_numeral minus_one_div_numeral minus_one_mod_numeral\n        one_div_minus_numeral one_mod_minus_numeral\n        numeral_div_numeral numeral_mod_numeral minus_numeral_div_numeral minus_numeral_mod_numeral\n        numeral_div_minus_numeral numeral_mod_minus_numeral\n        div_minus_minus mod_minus_minus Parity.adjust_div_eq of_bool_eq one_neq_zero\n        numeral_neq_zero neg_equal_0_iff_equal arith_simps arith_special divmod_trivial\n        divmod_cancel divmod_steps divmod_step_def fst_conv snd_conv numeral_One\n        case_prod_beta rel_simps Parity.adjust_mod_def div_minus1_right mod_minus1_right\n        minus_minus numeral_times_numeral mult_zero_right mult_1_right\n        euclidean_size_nat_less_eq_iff euclidean_size_int_less_eq_iff diff_nat_numeral nat_numeral}\n        @ [@{lemma \"0 = 0 \\<longleftrightarrow> True\" by simp}]);\n      fun prepare_simpset ctxt = HOL_ss |> Simplifier.simpset_map ctxt\n        (Simplifier.add_cong if_cong #> fold Simplifier.add_simp simps)\n    in fn ctxt => successful_rewrite (Simplifier.put_simpset (prepare_simpset ctxt) ctxt) end\n  end\n\\<close> \\<comment> \\<open>\n  There is space for improvement here: the calculation itself\n  could be carried out outside the logic, and a generic simproc\n  (simplifier setup) for generic calculation would be helpful.\n\\<close>\n\n\nsubsection \\<open>Computing congruences modulo \\<open>2 ^ q\\<close>\\<close>\n\ncontext unique_euclidean_semiring_with_nat_division\nbegin\n\nlemma cong_exp_iff_simps:\n  \"numeral n mod numeral Num.One = 0\n    \\<longleftrightarrow> True\"\n  \"numeral (Num.Bit0 n) mod numeral (Num.Bit0 q) = 0\n    \\<longleftrightarrow> numeral n mod numeral q = 0\"\n  \"numeral (Num.Bit1 n) mod numeral (Num.Bit0 q) = 0\n    \\<longleftrightarrow> False\"\n  \"numeral m mod numeral Num.One = (numeral n mod numeral Num.One)\n    \\<longleftrightarrow> True\"\n  \"numeral Num.One mod numeral (Num.Bit0 q) = (numeral Num.One mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> True\"\n  \"numeral Num.One mod numeral (Num.Bit0 q) = (numeral (Num.Bit0 n) mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> False\"\n  \"numeral Num.One mod numeral (Num.Bit0 q) = (numeral (Num.Bit1 n) mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> (numeral n mod numeral q) = 0\"\n  \"numeral (Num.Bit0 m) mod numeral (Num.Bit0 q) = (numeral Num.One mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> False\"\n  \"numeral (Num.Bit0 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit0 n) mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> numeral m mod numeral q = (numeral n mod numeral q)\"\n  \"numeral (Num.Bit0 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit1 n) mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> False\"\n  \"numeral (Num.Bit1 m) mod numeral (Num.Bit0 q) = (numeral Num.One mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> (numeral m mod numeral q) = 0\"\n  \"numeral (Num.Bit1 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit0 n) mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> False\"\n  \"numeral (Num.Bit1 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit1 n) mod numeral (Num.Bit0 q))\n    \\<longleftrightarrow> numeral m mod numeral q = (numeral n mod numeral q)\"\n  by (auto simp add: case_prod_beta dest: arg_cong [of _ _ even])\n\nend\n\n\ncode_identifier\n  code_module Parity \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nlemmas even_of_nat = even_of_nat_iff\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Parity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8933094159957173, "lm_q1q2_score": 0.7729128261213465}}
{"text": "section \"Derivatives of regular expressions\"\n\n(* Author: Christian Urban *)\n\ntheory Derivatives\nimports Regular_Exp\nbegin\n\ntext\\<open>This theory is based on work by Brozowski \\cite{Brzozowski64} and Antimirov \\cite{Antimirov95}.\\<close>\n\nsubsection \\<open>Brzozowski's derivatives of regular expressions\\<close>\n\nprimrec\n  deriv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"deriv c (Zero) = Zero\"\n| \"deriv c (One) = Zero\"\n| \"deriv c (Atom c') = (if c = c' then One else Zero)\"\n| \"deriv c (Plus r1 r2) = Plus (deriv c r1) (deriv c r2)\"\n| \"deriv c (Times r1 r2) = \n    (if nullable r1 then Plus (Times (deriv c r1) r2) (deriv c r2) else Times (deriv c r1) r2)\"\n| \"deriv c (Star r) = Times (deriv c r) (Star r)\"\n\nprimrec \n  derivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"derivs [] r = r\"\n| \"derivs (c # s) r = derivs s (deriv c r)\"\n\n\nlemma atoms_deriv_subset: \"atoms (deriv x r) \\<subseteq> atoms r\"\nby (induction r) (auto)\n\nlemma atoms_derivs_subset: \"atoms (derivs w r) \\<subseteq> atoms r\"\nby (induction w arbitrary: r) (auto dest: atoms_deriv_subset[THEN subsetD])\n\nlemma lang_deriv: \"lang (deriv c r) = Deriv c (lang r)\"\nby (induct r) (simp_all add: nullable_iff)\n\nlemma lang_derivs: \"lang (derivs s r) = Derivs s (lang r)\"\nby (induct s arbitrary: r) (simp_all add: lang_deriv)\n\ntext \\<open>A regular expression matcher:\\<close>\n\ndefinition matcher :: \"'a rexp \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"matcher r s = nullable (derivs s r)\"\n\nlemma matcher_correctness: \"matcher r s \\<longleftrightarrow> s \\<in> lang r\"\nby (induct s arbitrary: r)\n   (simp_all add: nullable_iff lang_deriv matcher_def Deriv_def)\n\n\nsubsection \\<open>Antimirov's partial derivatives\\<close>\n\nabbreviation\n  \"Timess rs r \\<equiv> (\\<Union>r' \\<in> rs. {Times r' r})\"\n\nlemma Timess_eq_image:\n  \"Timess rs r = (\\<lambda>r'. Times r' r) ` rs\"\n  by auto\n\nprimrec\n  pderiv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderiv c Zero = {}\"\n| \"pderiv c One = {}\"\n| \"pderiv c (Atom c') = (if c = c' then {One} else {})\"\n| \"pderiv c (Plus r1 r2) = (pderiv c r1) \\<union> (pderiv c r2)\"\n| \"pderiv c (Times r1 r2) = \n    (if nullable r1 then Timess (pderiv c r1) r2 \\<union> pderiv c r2 else Timess (pderiv c r1) r2)\"\n| \"pderiv c (Star r) = Timess (pderiv c r) (Star r)\"\n\nprimrec\n  pderivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> ('a rexp) set\"\nwhere\n  \"pderivs [] r = {r}\"\n| \"pderivs (c # s) r = \\<Union> (pderivs s ` pderiv c r)\"\n\nabbreviation\n pderiv_set :: \"'a \\<Rightarrow> 'a rexp set \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderiv_set c rs \\<equiv> \\<Union> (pderiv c ` rs)\"\n\nabbreviation\n  pderivs_set :: \"'a list \\<Rightarrow> 'a rexp set \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderivs_set s rs \\<equiv> \\<Union> (pderivs s ` rs)\"\n\nlemma pderivs_append:\n  \"pderivs (s1 @ s2) r = \\<Union> (pderivs s2 ` pderivs s1 r)\"\nby (induct s1 arbitrary: r) (simp_all)\n\nlemma pderivs_snoc:\n  shows \"pderivs (s @ [c]) r = pderiv_set c (pderivs s r)\"\nby (simp add: pderivs_append)\n\nlemma pderivs_simps [simp]:\n  shows \"pderivs s Zero = (if s = [] then {Zero} else {})\"\n  and   \"pderivs s One = (if s = [] then {One} else {})\"\n  and   \"pderivs s (Plus r1 r2) = (if s = [] then {Plus r1 r2} else (pderivs s r1) \\<union> (pderivs s r2))\"\nby (induct s) (simp_all)\n\nlemma pderivs_Atom:\n  shows \"pderivs s (Atom c) \\<subseteq> {Atom c, One}\"\nby (induct s) (simp_all)\n\nsubsection \\<open>Relating left-quotients and partial derivatives\\<close>\n\nlemma Deriv_pderiv:\n  shows \"Deriv c (lang r) = \\<Union> (lang ` pderiv c r)\"\nby (induct r) (auto simp add: nullable_iff conc_UNION_distrib)\n\nlemma Derivs_pderivs:\n  shows \"Derivs s (lang r) = \\<Union> (lang ` pderivs s r)\"\nproof (induct s arbitrary: r)\n  case (Cons c s)\n  have ih: \"\\<And>r. Derivs s (lang r) = \\<Union> (lang ` pderivs s r)\" by fact\n  have \"Derivs (c # s) (lang r) = Derivs s (Deriv c (lang r))\" by simp\n  also have \"\\<dots> = Derivs s (\\<Union> (lang ` pderiv c r))\" by (simp add: Deriv_pderiv)\n  also have \"\\<dots> = Derivss s (lang ` (pderiv c r))\"\n    by (auto simp add:  Derivs_def)\n  also have \"\\<dots> = \\<Union> (lang ` (pderivs_set s (pderiv c r)))\"\n    using ih by auto\n  also have \"\\<dots> = \\<Union> (lang ` (pderivs (c # s) r))\" by simp\n  finally show \"Derivs (c # s) (lang r) = \\<Union> (lang ` pderivs (c # s) r)\" .\nqed (simp add: Derivs_def)\n\nsubsection \\<open>Relating derivatives and partial derivatives\\<close>\n\nlemma deriv_pderiv:\n  shows \"\\<Union> (lang ` (pderiv c r)) = lang (deriv c r)\"\nunfolding lang_deriv Deriv_pderiv by simp\n\nlemma derivs_pderivs:\n  shows \"\\<Union> (lang ` (pderivs s r)) = lang (derivs s r)\"\nunfolding lang_derivs Derivs_pderivs by simp\n\n\nsubsection \\<open>Finiteness property of partial derivatives\\<close>\n\ndefinition\n  pderivs_lang :: \"'a lang \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderivs_lang A r \\<equiv> \\<Union>x \\<in> A. pderivs x r\"\n\nlemma pderivs_lang_subsetI:\n  assumes \"\\<And>s. s \\<in> A \\<Longrightarrow> pderivs s r \\<subseteq> C\"\n  shows \"pderivs_lang A r \\<subseteq> C\"\nusing assms unfolding pderivs_lang_def by (rule UN_least)\n\nlemma pderivs_lang_union:\n  shows \"pderivs_lang (A \\<union> B) r = (pderivs_lang A r \\<union> pderivs_lang B r)\"\nby (simp add: pderivs_lang_def)\n\nlemma pderivs_lang_subset:\n  shows \"A \\<subseteq> B \\<Longrightarrow> pderivs_lang A r \\<subseteq> pderivs_lang B r\"\nby (auto simp add: pderivs_lang_def)\n\ndefinition\n  \"UNIV1 \\<equiv> UNIV - {[]}\"\n\nlemma pderivs_lang_Zero [simp]:\n  shows \"pderivs_lang UNIV1 Zero = {}\"\nunfolding UNIV1_def pderivs_lang_def by auto\n\nlemma pderivs_lang_One [simp]:\n  shows \"pderivs_lang UNIV1 One = {}\"\nunfolding UNIV1_def pderivs_lang_def by (auto split: if_splits)\n\nlemma pderivs_lang_Atom [simp]:\n  shows \"pderivs_lang UNIV1 (Atom c) = {One}\"\nunfolding UNIV1_def pderivs_lang_def \napply(auto)\napply(frule rev_subsetD)\napply(rule pderivs_Atom)\napply(simp)\napply(case_tac xa)\napply(auto split: if_splits)\ndone\n\nlemma pderivs_lang_Plus [simp]:\n  shows \"pderivs_lang UNIV1 (Plus r1 r2) = pderivs_lang UNIV1 r1 \\<union> pderivs_lang UNIV1 r2\"\nunfolding UNIV1_def pderivs_lang_def by auto\n\n\ntext \\<open>Non-empty suffixes of a string (needed for the cases of @{const Times} and @{const Star} below)\\<close>\n\ndefinition\n  \"PSuf s \\<equiv> {v. v \\<noteq> [] \\<and> (\\<exists>u. u @ v = s)}\"\n\nlemma PSuf_snoc:\n  shows \"PSuf (s @ [c]) = (PSuf s) @@ {[c]} \\<union> {[c]}\"\nunfolding PSuf_def conc_def\nby (auto simp add: append_eq_append_conv2 append_eq_Cons_conv)\n\nlemma PSuf_Union:\n  shows \"(\\<Union>v \\<in> PSuf s @@ {[c]}. f v) = (\\<Union>v \\<in> PSuf s. f (v @ [c]))\"\nby (auto simp add: conc_def)\n\nlemma pderivs_lang_snoc:\n  shows \"pderivs_lang (PSuf s @@ {[c]}) r = (pderiv_set c (pderivs_lang (PSuf s) r))\"\nunfolding pderivs_lang_def\nby (simp add: PSuf_Union pderivs_snoc)\n\nlemma pderivs_Times:\n  shows \"pderivs s (Times r1 r2) \\<subseteq> Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2)\"\nproof (induct s rule: rev_induct)\n  case (snoc c s)\n  have ih: \"pderivs s (Times r1 r2) \\<subseteq> Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2)\" \n    by fact\n  have \"pderivs (s @ [c]) (Times r1 r2) = pderiv_set c (pderivs s (Times r1 r2))\" \n    by (simp add: pderivs_snoc)\n  also have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2))\"\n    using ih by fastforce\n  also have \"\\<dots> = pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderiv_set c (pderivs_lang (PSuf s) r2)\"\n    by (simp)\n  also have \"\\<dots> = pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (simp add: pderivs_lang_snoc)\n  also \n  have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by auto\n  also \n  have \"\\<dots> \\<subseteq> Timess (pderiv_set c (pderivs s r1)) r2 \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (auto simp add: if_splits)\n  also have \"\\<dots> = Timess (pderivs (s @ [c]) r1) r2 \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (simp add: pderivs_snoc)\n  also have \"\\<dots> \\<subseteq> Timess (pderivs (s @ [c]) r1) r2 \\<union> pderivs_lang (PSuf (s @ [c])) r2\"\n    unfolding pderivs_lang_def by (auto simp add: PSuf_snoc)  \n  finally show ?case .\nqed (simp) \n\nlemma pderivs_lang_Times_aux1:\n  assumes a: \"s \\<in> UNIV1\"\n  shows \"pderivs_lang (PSuf s) r \\<subseteq> pderivs_lang UNIV1 r\"\nusing a unfolding UNIV1_def PSuf_def pderivs_lang_def by auto\n\n\n\nlemma pderivs_lang_Times:\n  shows \"pderivs_lang UNIV1 (Times r1 r2) \\<subseteq> Timess (pderivs_lang UNIV1 r1) r2 \\<union> pderivs_lang UNIV1 r2\"\napply(rule pderivs_lang_subsetI)\napply(rule subset_trans)\napply(rule pderivs_Times)\nusing pderivs_lang_Times_aux1 pderivs_lang_Times_aux2\napply auto\napply blast\ndone\n\nlemma pderivs_Star:\n  assumes a: \"s \\<noteq> []\"\n  shows \"pderivs s (Star r) \\<subseteq> Timess (pderivs_lang (PSuf s) r) (Star r)\"\nusing a\nproof (induct s rule: rev_induct)\n  case (snoc c s)\n  have ih: \"s \\<noteq> [] \\<Longrightarrow> pderivs s (Star r) \\<subseteq> Timess (pderivs_lang (PSuf s) r) (Star r)\" by fact\n  { assume asm: \"s \\<noteq> []\"\n    have \"pderivs (s @ [c]) (Star r) = pderiv_set c (pderivs s (Star r))\" by (simp add: pderivs_snoc)\n    also have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs_lang (PSuf s) r) (Star r))\"\n      using ih[OF asm] by fast\n    also have \"\\<dots> \\<subseteq> Timess (pderiv_set c (pderivs_lang (PSuf s) r)) (Star r) \\<union> pderiv c (Star r)\"\n      by (auto split: if_splits)\n    also have \"\\<dots> \\<subseteq> Timess (pderivs_lang (PSuf (s @ [c])) r) (Star r) \\<union> (Timess (pderiv c r) (Star r))\"\n      by (simp only: PSuf_snoc pderivs_lang_snoc pderivs_lang_union)\n         (auto simp add: pderivs_lang_def)\n    also have \"\\<dots> = Timess (pderivs_lang (PSuf (s @ [c])) r) (Star r)\"\n      by (auto simp add: PSuf_snoc PSuf_Union pderivs_snoc pderivs_lang_def)\n    finally have ?case .\n  }\n  moreover\n  { assume asm: \"s = []\"\n    then have ?case by (auto simp add: pderivs_lang_def pderivs_snoc PSuf_def)\n  }\n  ultimately show ?case by blast\nqed (simp)\n\nlemma pderivs_lang_Star:\n  shows \"pderivs_lang UNIV1 (Star r) \\<subseteq> Timess (pderivs_lang UNIV1 r) (Star r)\"\napply(rule pderivs_lang_subsetI)\napply(rule subset_trans)\napply(rule pderivs_Star)\napply(simp add: UNIV1_def)\napply(simp add: UNIV1_def PSuf_def)\napply(auto simp add: pderivs_lang_def)\ndone\n\nlemma finite_Timess [simp]:\n  assumes a: \"finite A\"\n  shows \"finite (Timess A r)\"\nusing a by auto\n\nlemma finite_pderivs_lang_UNIV1:\n  shows \"finite (pderivs_lang UNIV1 r)\"\napply(induct r)\napply(simp_all add: \n  finite_subset[OF pderivs_lang_Times]\n  finite_subset[OF pderivs_lang_Star])\ndone\n    \nlemma pderivs_lang_UNIV:\n  shows \"pderivs_lang UNIV r = pderivs [] r \\<union> pderivs_lang UNIV1 r\"\nunfolding UNIV1_def pderivs_lang_def\nby blast\n\nlemma finite_pderivs_lang_UNIV:\n  shows \"finite (pderivs_lang UNIV r)\"\nunfolding pderivs_lang_UNIV\nby (simp add: finite_pderivs_lang_UNIV1)\n\nlemma finite_pderivs_lang:\n  shows \"finite (pderivs_lang A r)\"\nby (metis finite_pderivs_lang_UNIV pderivs_lang_subset rev_finite_subset subset_UNIV)\n\n\ntext\\<open>The following relationship between the alphabetic width of regular expressions\n(called \\<open>awidth\\<close> below) and the number of partial derivatives was proved\nby Antimirov~\\cite{Antimirov95} and formalized by Max Haslbeck.\\<close>\n\nfun awidth :: \"'a rexp \\<Rightarrow> nat\" where\n\"awidth Zero = 0\" |\n\"awidth One = 0\" |\n\"awidth (Atom a) = 1\" |\n\"awidth (Plus r1 r2) = awidth r1 + awidth r2\" |\n\"awidth (Times r1 r2) = awidth r1 + awidth r2\" |\n\"awidth (Star r1) = awidth r1\"\n\nlemma card_Timess_pderivs_lang_le:\n  \"card (Timess (pderivs_lang A r) s) \\<le> card (pderivs_lang A r)\"\n  using finite_pderivs_lang unfolding Timess_eq_image by (rule card_image_le)\n\nlemma card_pderivs_lang_UNIV1_le_awidth: \"card (pderivs_lang UNIV1 r) \\<le> awidth r\"\nproof (induction r)\n  case (Plus r1 r2)\n  have \"card (pderivs_lang UNIV1 (Plus r1 r2)) = card (pderivs_lang UNIV1 r1 \\<union> pderivs_lang UNIV1 r2)\" by simp\n  also have \"\\<dots> \\<le> card (pderivs_lang UNIV1 r1) + card (pderivs_lang UNIV1 r2)\"\n    by(simp add: card_Un_le)\n  also have \"\\<dots> \\<le> awidth (Plus r1 r2)\" using Plus.IH by simp\n  finally show ?case .\nnext\n  case (Times r1 r2)\n  have \"card (pderivs_lang UNIV1 (Times r1 r2)) \\<le> card (Timess (pderivs_lang UNIV1 r1) r2 \\<union> pderivs_lang UNIV1 r2)\"\n    by (simp add: card_mono finite_pderivs_lang pderivs_lang_Times)\n  also have \"\\<dots> \\<le> card (Timess (pderivs_lang UNIV1 r1) r2) + card (pderivs_lang UNIV1 r2)\"\n    by (simp add: card_Un_le)\n  also have \"\\<dots> \\<le> card (pderivs_lang UNIV1 r1) + card (pderivs_lang UNIV1 r2)\"\n    by (simp add: card_Timess_pderivs_lang_le)\n  also have \"\\<dots> \\<le> awidth (Times r1 r2)\" using Times.IH by simp\n  finally show ?case .\nnext\n  case (Star r)\n  have \"card (pderivs_lang UNIV1 (Star r)) \\<le> card (Timess (pderivs_lang UNIV1 r) (Star r))\"\n    by (simp add: card_mono finite_pderivs_lang pderivs_lang_Star)\n  also have \"\\<dots> \\<le> card (pderivs_lang UNIV1 r)\" by (rule card_Timess_pderivs_lang_le)\n  also have \"\\<dots> \\<le> awidth (Star r)\" by (simp add: Star.IH)\n  finally show ?case .\nqed (auto)\n\ntext\\<open>Antimirov's Theorem 3.4:\\<close>\ntheorem card_pderivs_lang_UNIV_le_awidth: \"card (pderivs_lang UNIV r) \\<le> awidth r + 1\"\nproof -\n  have \"card (insert r (pderivs_lang UNIV1 r)) \\<le> Suc (card (pderivs_lang UNIV1 r))\"\n    by(auto simp: card_insert_if[OF finite_pderivs_lang_UNIV1])\n  also have \"\\<dots> \\<le> Suc (awidth r)\" by(simp add: card_pderivs_lang_UNIV1_le_awidth)\n  finally show ?thesis by(simp add: pderivs_lang_UNIV)\nqed \n\ntext\\<open>Antimirov's Corollary 3.5:\\<close>\ncorollary card_pderivs_lang_le_awidth: \"card (pderivs_lang A r) \\<le> awidth r + 1\"\nby(rule order_trans[OF\n  card_mono[OF finite_pderivs_lang_UNIV pderivs_lang_subset[OF subset_UNIV]]\n  card_pderivs_lang_UNIV_le_awidth])\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Regular-Sets/Derivatives.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.772912817131287}}
{"text": "(*  Title:      ZF/ex/Primes.thy\n    Author:     Christophe Tabacznyj and Lawrence C Paulson\n    Copyright   1996  University of Cambridge\n*)\n\nsection\\<open>The Divides Relation and Euclid's algorithm for the GCD\\<close>\n\ntheory Primes imports ZF begin\n\ndefinition\n  divides :: \"[i,i]=>o\"              (infixl \\<open>dvd\\<close> 50)  where\n    \"m dvd n == m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\n\ndefinition\n  is_gcd  :: \"[i,i,i]=>o\"     \\<comment> \\<open>definition of great common divisor\\<close>  where\n    \"is_gcd(p,m,n) == ((p dvd m) & (p dvd n))   &\n                       (\\<forall>d\\<in>nat. (d dvd m) & (d dvd n) \\<longrightarrow> d dvd p)\"\n\ndefinition\n  gcd     :: \"[i,i]=>i\"       \\<comment> \\<open>Euclid's algorithm for the gcd\\<close>  where\n    \"gcd(m,n) == transrec(natify(n),\n                        %n f. \\<lambda>m \\<in> nat.\n                                if n=0 then m else f`(m mod n)`n) ` natify(m)\"\n\ndefinition\n  coprime :: \"[i,i]=>o\"       \\<comment> \\<open>the coprime relation\\<close>  where\n    \"coprime(m,n) == gcd(m,n) = 1\"\n  \ndefinition\n  prime   :: i                \\<comment> \\<open>the set of prime numbers\\<close>  where\n   \"prime == {p \\<in> nat. 1<p & (\\<forall>m \\<in> nat. m dvd p \\<longrightarrow> m=1 | m=p)}\"\n\n\nsubsection\\<open>The Divides Relation\\<close>\n\nlemma dvdD: \"m dvd n ==> m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\nby (unfold divides_def, assumption)\n\nlemma dvdE:\n     \"[|m dvd n;  !!k. [|m \\<in> nat; n \\<in> nat; k \\<in> nat; n = m#*k|] ==> P|] ==> P\"\nby (blast dest!: dvdD)\n\nlemmas dvd_imp_nat1 = dvdD [THEN conjunct1]\nlemmas dvd_imp_nat2 = dvdD [THEN conjunct2, THEN conjunct1]\n\n\nlemma dvd_0_right [simp]: \"m \\<in> nat ==> m dvd 0\"\napply (simp add: divides_def)\napply (fast intro: nat_0I mult_0_right [symmetric])\ndone\n\nlemma dvd_0_left: \"0 dvd m ==> m = 0\"\nby (simp add: divides_def)\n\nlemma dvd_refl [simp]: \"m \\<in> nat ==> m dvd m\"\napply (simp add: divides_def)\napply (fast intro: nat_1I mult_1_right [symmetric])\ndone\n\nlemma dvd_trans: \"[| m dvd n; n dvd p |] ==> m dvd p\"\nby (auto simp add: divides_def intro: mult_assoc mult_type)\n\nlemma dvd_anti_sym: \"[| m dvd n; n dvd m |] ==> m=n\"\napply (simp add: divides_def)\napply (force dest: mult_eq_self_implies_10\n             simp add: mult_assoc mult_eq_1_iff)\ndone\n\nlemma dvd_mult_left: \"[|(i#*j) dvd k; i \\<in> nat|] ==> i dvd k\"\nby (auto simp add: divides_def mult_assoc)\n\nlemma dvd_mult_right: \"[|(i#*j) dvd k; j \\<in> nat|] ==> j dvd k\"\napply (simp add: divides_def, clarify)\napply (rule_tac x = \"i#*ka\" in bexI)\napply (simp add: mult_ac)\napply (rule mult_type)\ndone\n\n\nsubsection\\<open>Euclid's Algorithm for the GCD\\<close>\n\nlemma gcd_0 [simp]: \"gcd(m,0) = natify(m)\"\napply (simp add: gcd_def)\napply (subst transrec, simp)\ndone\n\nlemma gcd_natify1 [simp]: \"gcd(natify(m),n) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_natify2 [simp]: \"gcd(m, natify(n)) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_non_0_raw: \n    \"[| 0<n;  n \\<in> nat |] ==> gcd(m,n) = gcd(n, m mod n)\"\napply (simp add: gcd_def)\napply (rule_tac P = \"%z. left (z) = right\" for left right in transrec [THEN ssubst])\napply (simp add: ltD [THEN mem_imp_not_eq, THEN not_sym] \n                 mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_non_0: \"0 < natify(n) ==> gcd(m,n) = gcd(n, m mod n)\"\napply (cut_tac m = m and n = \"natify (n) \" in gcd_non_0_raw)\napply auto\ndone\n\nlemma gcd_1 [simp]: \"gcd(m,1) = 1\"\nby (simp (no_asm_simp) add: gcd_non_0)\n\nlemma dvd_add: \"[| k dvd a; k dvd b |] ==> k dvd (a #+ b)\"\napply (simp add: divides_def)\napply (fast intro: add_mult_distrib_left [symmetric] add_type)\ndone\n\nlemma dvd_mult: \"k dvd n ==> k dvd (m #* n)\"\napply (simp add: divides_def)\napply (fast intro: mult_left_commute mult_type)\ndone\n\nlemma dvd_mult2: \"k dvd m ==> k dvd (m #* n)\"\napply (subst mult_commute)\napply (blast intro: dvd_mult)\ndone\n\n(* k dvd (m*k) *)\nlemmas dvdI1 [simp] = dvd_refl [THEN dvd_mult]\nlemmas dvdI2 [simp] = dvd_refl [THEN dvd_mult2]\n\nlemma dvd_mod_imp_dvd_raw:\n     \"[| a \\<in> nat; b \\<in> nat; k dvd b; k dvd (a mod b) |] ==> k dvd a\"\napply (case_tac \"b=0\") \n apply (simp add: DIVISION_BY_ZERO_MOD)\napply (blast intro: mod_div_equality [THEN subst]\n             elim: dvdE \n             intro!: dvd_add dvd_mult mult_type mod_type div_type)\ndone\n\nlemma dvd_mod_imp_dvd: \"[| k dvd (a mod b); k dvd b; a \\<in> nat |] ==> k dvd a\"\napply (cut_tac b = \"natify (b)\" in dvd_mod_imp_dvd_raw)\napply auto\napply (simp add: divides_def)\ndone\n\n(*Imitating TFL*)\nlemma gcd_induct_lemma [rule_format (no_asm)]: \"[| n \\<in> nat;  \n         \\<forall>m \\<in> nat. P(m,0);  \n         \\<forall>m \\<in> nat. \\<forall>n \\<in> nat. 0<n \\<longrightarrow> P(n, m mod n) \\<longrightarrow> P(m,n) |]  \n      ==> \\<forall>m \\<in> nat. P (m,n)\"\napply (erule_tac i = n in complete_induct)\napply (case_tac \"x=0\")\napply (simp (no_asm_simp))\napply clarify\napply (drule_tac x1 = m and x = x in bspec [THEN bspec])\napply (simp_all add: Ord_0_lt_iff)\napply (blast intro: mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_induct: \"!!P. [| m \\<in> nat; n \\<in> nat;  \n         !!m. m \\<in> nat ==> P(m,0);  \n         !!m n. [|m \\<in> nat; n \\<in> nat; 0<n; P(n, m mod n)|] ==> P(m,n) |]  \n      ==> P (m,n)\"\nby (blast intro: gcd_induct_lemma)\n\n\nsubsection\\<open>Basic Properties of \\<^term>\\<open>gcd\\<close>\\<close>\n\ntext\\<open>type of gcd\\<close>\nlemma gcd_type [simp,TC]: \"gcd(m, n) \\<in> nat\"\napply (subgoal_tac \"gcd (natify (m), natify (n)) \\<in> nat\")\napply simp\napply (rule_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_induct)\napply auto\napply (simp add: gcd_non_0)\ndone\n\n\ntext\\<open>Property 1: gcd(a,b) divides a and b\\<close>\n\nlemma gcd_dvd_both:\n     \"[| m \\<in> nat; n \\<in> nat |] ==> gcd (m, n) dvd m & gcd (m, n) dvd n\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0)\napply (blast intro: dvd_mod_imp_dvd_raw nat_into_Ord [THEN Ord_0_lt])\ndone\n\nlemma gcd_dvd1 [simp]: \"m \\<in> nat ==> gcd(m,n) dvd m\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\nlemma gcd_dvd2 [simp]: \"n \\<in> nat ==> gcd(m,n) dvd n\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\ntext\\<open>if f divides a and b then f divides gcd(a,b)\\<close>\n\nlemma dvd_mod: \"[| f dvd a; f dvd b |] ==> f dvd (a mod b)\"\napply (simp add: divides_def)\napply (case_tac \"b=0\")\n apply (simp add: DIVISION_BY_ZERO_MOD, auto)\napply (blast intro: mod_mult_distrib2 [symmetric])\ndone\n\ntext\\<open>Property 2: for all a,b,f naturals, \n               if f divides a and f divides b then f divides gcd(a,b)\\<close>\n\nlemma gcd_greatest_raw [rule_format]:\n     \"[| m \\<in> nat; n \\<in> nat; f \\<in> nat |]    \n      ==> (f dvd m) \\<longrightarrow> (f dvd n) \\<longrightarrow> f dvd gcd(m,n)\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0 dvd_mod)\ndone\n\nlemma gcd_greatest: \"[| f dvd m;  f dvd n;  f \\<in> nat |] ==> f dvd gcd(m,n)\"\napply (rule gcd_greatest_raw)\napply (auto simp add: divides_def)\ndone\n\nlemma gcd_greatest_iff [simp]: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> (k dvd gcd (m, n)) \\<longleftrightarrow> (k dvd m & k dvd n)\"\nby (blast intro!: gcd_greatest gcd_dvd1 gcd_dvd2 intro: dvd_trans)\n\n\nsubsection\\<open>The Greatest Common Divisor\\<close>\n\ntext\\<open>The GCD exists and function gcd computes it.\\<close>\n\nlemma is_gcd: \"[| m \\<in> nat; n \\<in> nat |] ==> is_gcd(gcd(m,n), m, n)\"\nby (simp add: is_gcd_def)\n\ntext\\<open>The GCD is unique\\<close>\n\nlemma is_gcd_unique: \"[|is_gcd(m,a,b); is_gcd(n,a,b); m\\<in>nat; n\\<in>nat|] ==> m=n\"\napply (simp add: is_gcd_def)\napply (blast intro: dvd_anti_sym)\ndone\n\nlemma is_gcd_commute: \"is_gcd(k,m,n) \\<longleftrightarrow> is_gcd(k,n,m)\"\nby (simp add: is_gcd_def, blast)\n\nlemma gcd_commute_raw: \"[| m \\<in> nat; n \\<in> nat |] ==> gcd(m,n) = gcd(n,m)\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (rule_tac [3] is_gcd_commute [THEN iffD1])\napply (rule_tac [3] is_gcd, auto)\ndone\n\nlemma gcd_commute: \"gcd(m,n) = gcd(n,m)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_commute_raw)\napply auto\ndone\n\nlemma gcd_assoc_raw: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (simp_all add: is_gcd_def)\napply (blast intro: gcd_dvd1 gcd_dvd2 gcd_type intro: dvd_trans)\ndone\n\nlemma gcd_assoc: \"gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_assoc_raw)\napply auto\ndone\n\nlemma gcd_0_left [simp]: \"gcd (0, m) = natify(m)\"\nby (simp add: gcd_commute [of 0])\n\nlemma gcd_1_left [simp]: \"gcd (1, m) = 1\"\nby (simp add: gcd_commute [of 1])\n\n\nsubsection\\<open>Addition laws\\<close>\n\nlemma gcd_add1 [simp]: \"gcd (m #+ n, n) = gcd (m, n)\"\napply (subgoal_tac \"gcd (m #+ natify (n), natify (n)) = gcd (m, natify (n))\")\napply simp\napply (case_tac \"natify (n) = 0\")\napply (auto simp add: Ord_0_lt_iff gcd_non_0)\ndone\n\nlemma gcd_add2 [simp]: \"gcd (m, m #+ n) = gcd (m, n)\"\napply (rule gcd_commute [THEN trans])\napply (subst add_commute, simp)\napply (rule gcd_commute)\ndone\n\nlemma gcd_add2' [simp]: \"gcd (m, n #+ m) = gcd (m, n)\"\nby (subst add_commute, rule gcd_add2)\n\nlemma gcd_add_mult_raw: \"k \\<in> nat ==> gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (erule nat_induct)\napply (auto simp add: gcd_add2 add_assoc)\ndone\n\nlemma gcd_add_mult: \"gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (cut_tac k = \"natify (k)\" in gcd_add_mult_raw)\napply auto\ndone\n\n\nsubsection\\<open>Multiplication Laws\\<close>\n\nlemma gcd_mult_distrib2_raw:\n     \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (erule_tac m = m and n = n in gcd_induct, assumption)\napply simp\napply (case_tac \"k = 0\", simp)\napply (simp add: mod_geq gcd_non_0 mod_mult_distrib2 Ord_0_lt_iff)\ndone\n\nlemma gcd_mult_distrib2: \"k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_mult_distrib2_raw)\napply auto\ndone\n\nlemma gcd_mult [simp]: \"gcd (k, k #* n) = natify(k)\"\nby (cut_tac k = k and m = 1 and n = n in gcd_mult_distrib2, auto)\n\nlemma gcd_self [simp]: \"gcd (k, k) = natify(k)\"\nby (cut_tac k = k and n = 1 in gcd_mult, auto)\n\nlemma relprime_dvd_mult:\n     \"[| gcd (k,n) = 1;  k dvd (m #* n);  m \\<in> nat |] ==> k dvd m\"\napply (cut_tac k = m and m = k and n = n in gcd_mult_distrib2, auto)\napply (erule_tac b = m in ssubst)\napply (simp add: dvd_imp_nat1)\ndone\n\nlemma relprime_dvd_mult_iff:\n     \"[| gcd (k,n) = 1;  m \\<in> nat |] ==> k dvd (m #* n) \\<longleftrightarrow> k dvd m\"\nby (blast intro: dvdI2 relprime_dvd_mult dvd_trans)\n\nlemma prime_imp_relprime: \n     \"[| p \\<in> prime;  ~ (p dvd n);  n \\<in> nat |] ==> gcd (p, n) = 1\"\napply (simp add: prime_def, clarify)\napply (drule_tac x = \"gcd (p,n)\" in bspec)\napply auto\napply (cut_tac m = p and n = n in gcd_dvd2, auto)\ndone\n\nlemma prime_into_nat: \"p \\<in> prime ==> p \\<in> nat\"\nby (simp add: prime_def)\n\nlemma prime_nonzero: \"p \\<in> prime \\<Longrightarrow> p\\<noteq>0\"\nby (auto simp add: prime_def)\n\n\ntext\\<open>This theorem leads immediately to a proof of the uniqueness of\n  factorization.  If \\<^term>\\<open>p\\<close> divides a product of primes then it is\n  one of those primes.\\<close>\n\nlemma prime_dvd_mult:\n     \"[|p dvd m #* n; p \\<in> prime; m \\<in> nat; n \\<in> nat |] ==> p dvd m \\<or> p dvd n\"\nby (blast intro: relprime_dvd_mult prime_imp_relprime prime_into_nat)\n\n\nlemma gcd_mult_cancel_raw:\n     \"[|gcd (k,n) = 1; m \\<in> nat; n \\<in> nat|] ==> gcd (k #* m, n) = gcd (m, n)\"\napply (rule dvd_anti_sym)\n apply (rule gcd_greatest)\n  apply (rule relprime_dvd_mult [of _ k])\napply (simp add: gcd_assoc)\napply (simp add: gcd_commute)\napply (simp_all add: mult_commute)\napply (blast intro: dvdI1 gcd_dvd1 dvd_trans)\ndone\n\nlemma gcd_mult_cancel: \"gcd (k,n) = 1 ==> gcd (k #* m, n) = gcd (m, n)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_mult_cancel_raw)\napply auto\ndone\n\n\nsubsection\\<open>The Square Root of a Prime is Irrational: Key Lemma\\<close>\n\nlemma prime_dvd_other_side:\n     \"\\<lbrakk>n#*n = p#*(k#*k); p \\<in> prime; n \\<in> nat\\<rbrakk> \\<Longrightarrow> p dvd n\"\napply (subgoal_tac \"p dvd n#*n\")\n apply (blast dest: prime_dvd_mult)\napply (rule_tac j = \"k#*k\" in dvd_mult_left)\n apply (auto simp add: prime_def)\ndone\n\nlemma reduction:\n     \"\\<lbrakk>k#*k = p#*(j#*j); p \\<in> prime; 0 < k; j \\<in> nat; k \\<in> nat\\<rbrakk>  \n      \\<Longrightarrow> k < p#*j & 0 < j\"\napply (rule ccontr)\napply (simp add: not_lt_iff_le prime_into_nat)\napply (erule disjE)\n apply (frule mult_le_mono, assumption+)\napply (simp add: mult_ac)\napply (auto dest!: natify_eqE \n            simp add: not_lt_iff_le prime_into_nat mult_le_cancel_le1)\napply (simp add: prime_def)\napply (blast dest: lt_trans1)\ndone\n\nlemma rearrange: \"j #* (p#*j) = k#*k \\<Longrightarrow> k#*k = p#*(j#*j)\"\nby (simp add: mult_ac)\n\nlemma prime_not_square:\n     \"\\<lbrakk>m \\<in> nat; p \\<in> prime\\<rbrakk> \\<Longrightarrow> \\<forall>k \\<in> nat. 0<k \\<longrightarrow> m#*m \\<noteq> p#*(k#*k)\"\napply (erule complete_induct, clarify)\napply (frule prime_dvd_other_side, assumption)\napply assumption\napply (erule dvdE)\napply (simp add: mult_assoc mult_cancel1 prime_nonzero prime_into_nat)\napply (blast dest: rearrange reduction ltD)\ndone\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/ZF/ex/Primes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7729128144153262}}
{"text": "(*<*)theory Advanced imports Even begin\nML_file \\<open>../../antiquote_setup.ML\\<close>\n(*>*)\n\ntext \\<open>\nThe premises of introduction rules may contain universal quantifiers and\nmonotone functions.  A universal quantifier lets the rule \nrefer to any number of instances of \nthe inductively defined set.  A monotone function lets the rule refer\nto existing constructions (such as ``list of'') over the inductively defined\nset.  The examples below show how to use the additional expressiveness\nand how to reason from the resulting definitions.\n\\<close>\n\nsubsection\\<open>Universal Quantifiers in Introduction Rules \\label{sec:gterm-datatype}\\<close>\n\ntext \\<open>\n\\index{ground terms example|(}%\n\\index{quantifiers!and inductive definitions|(}%\nAs a running example, this section develops the theory of \\textbf{ground\nterms}: terms constructed from constant and function \nsymbols but not variables. To simplify matters further, we regard a\nconstant as a function applied to the null argument  list.  Let us declare a\ndatatype \\<open>gterm\\<close> for the type of ground  terms. It is a type constructor\nwhose argument is a type of  function symbols. \n\\<close>\n\ndatatype 'f gterm = Apply 'f \"'f gterm list\"\n\ntext \\<open>\nTo try it out, we declare a datatype of some integer operations: \ninteger constants, the unary minus operator and the addition \noperator.\n\\<close>\n\ndatatype integer_op = Number int | UnaryMinus | Plus\n\ntext \\<open>\nNow the type \\<^typ>\\<open>integer_op gterm\\<close> denotes the ground \nterms built over those symbols.\n\nThe type constructor \\<open>gterm\\<close> can be generalized to a function \nover sets.  It returns \nthe set of ground terms that can be formed over a set \\<open>F\\<close> of function symbols. For\nexample,  we could consider the set of ground terms formed from the finite \nset \\<open>{Number 2, UnaryMinus, Plus}\\<close>.\n\nThis concept is inductive. If we have a list \\<open>args\\<close> of ground terms \nover~\\<open>F\\<close> and a function symbol \\<open>f\\<close> in \\<open>F\\<close>, then we \ncan apply \\<open>f\\<close> to \\<open>args\\<close> to obtain another ground term. \nThe only difficulty is that the argument list may be of any length. Hitherto, \neach rule in an inductive definition referred to the inductively \ndefined set a fixed number of times, typically once or twice. \nA universal quantifier in the premise of the introduction rule \nexpresses that every element of \\<open>args\\<close> belongs\nto our inductively defined set: is a ground term \nover~\\<open>F\\<close>.  The function \\<^term>\\<open>set\\<close> denotes the set of elements in a given \nlist. \n\\<close>\n\ninductive_set\n  gterms :: \"'f set \\<Rightarrow> 'f gterm set\"\n  for F :: \"'f set\"\nwhere\nstep[intro!]: \"\\<lbrakk>\\<forall>t \\<in> set args. t \\<in> gterms F;  f \\<in> F\\<rbrakk>\n               \\<Longrightarrow> (Apply f args) \\<in> gterms F\"\n\ntext \\<open>\nTo demonstrate a proof from this definition, let us \nshow that the function \\<^term>\\<open>gterms\\<close>\nis \\textbf{monotone}.  We shall need this concept shortly.\n\\<close>\n\nlemma gterms_mono: \"F\\<subseteq>G \\<Longrightarrow> gterms F \\<subseteq> gterms G\"\napply clarify\napply (erule gterms.induct)\napply blast\ndone\n(*<*)\nlemma gterms_mono: \"F\\<subseteq>G \\<Longrightarrow> gterms F \\<subseteq> gterms G\"\napply clarify\napply (erule gterms.induct)\n(*>*)\ntxt\\<open>\nIntuitively, this theorem says that\nenlarging the set of function symbols enlarges the set of ground \nterms. The proof is a trivial rule induction.\nFirst we use the \\<open>clarify\\<close> method to assume the existence of an element of\n\\<^term>\\<open>gterms F\\<close>.  (We could have used \\<open>intro subsetI\\<close>.)  We then\napply rule induction. Here is the resulting subgoal:\n@{subgoals[display,indent=0]}\nThe assumptions state that \\<open>f\\<close> belongs \nto~\\<open>F\\<close>, which is included in~\\<open>G\\<close>, and that every element of the list \\<open>args\\<close> is\na ground term over~\\<open>G\\<close>.  The \\<open>blast\\<close> method finds this chain of reasoning easily.  \n\\<close>\n(*<*)oops(*>*)\ntext \\<open>\n\\begin{warn}\nWhy do we call this function \\<open>gterms\\<close> instead \nof \\<open>gterm\\<close>?  A constant may have the same name as a type.  However,\nname  clashes could arise in the theorems that Isabelle generates. \nOur choice of names keeps \\<open>gterms.induct\\<close> separate from \n\\<open>gterm.induct\\<close>.\n\\end{warn}\n\nCall a term \\textbf{well-formed} if each symbol occurring in it is applied\nto the correct number of arguments.  (This number is called the symbol's\n\\textbf{arity}.)  We can express well-formedness by\ngeneralizing the inductive definition of\n\\isa{gterms}.\nSuppose we are given a function called \\<open>arity\\<close>, specifying the arities\nof all symbols.  In the inductive step, we have a list \\<open>args\\<close> of such\nterms and a function  symbol~\\<open>f\\<close>. If the length of the list matches the\nfunction's arity  then applying \\<open>f\\<close> to \\<open>args\\<close> yields a well-formed\nterm.\n\\<close>\n\ninductive_set\n  well_formed_gterm :: \"('f \\<Rightarrow> nat) \\<Rightarrow> 'f gterm set\"\n  for arity :: \"'f \\<Rightarrow> nat\"\nwhere\nstep[intro!]: \"\\<lbrakk>\\<forall>t \\<in> set args. t \\<in> well_formed_gterm arity;  \n                length args = arity f\\<rbrakk>\n               \\<Longrightarrow> (Apply f args) \\<in> well_formed_gterm arity\"\n\ntext \\<open>\nThe inductive definition neatly captures the reasoning above.\nThe universal quantification over the\n\\<open>set\\<close> of arguments expresses that all of them are well-formed.%\n\\index{quantifiers!and inductive definitions|)}\n\\<close>\n\nsubsection\\<open>Alternative Definition Using a Monotone Function\\<close>\n\ntext \\<open>\n\\index{monotone functions!and inductive definitions|(}% \nAn inductive definition may refer to the\ninductively defined  set through an arbitrary monotone function.  To\ndemonstrate this powerful feature, let us\nchange the  inductive definition above, replacing the\nquantifier by a use of the function \\<^term>\\<open>lists\\<close>. This\nfunction, from the Isabelle theory of lists, is analogous to the\nfunction \\<^term>\\<open>gterms\\<close> declared above: if \\<open>A\\<close> is a set then\n\\<^term>\\<open>lists A\\<close> is the set of lists whose elements belong to\n\\<^term>\\<open>A\\<close>.  \n\nIn the inductive definition of well-formed terms, examine the one\nintroduction rule.  The first premise states that \\<open>args\\<close> belongs to\nthe \\<open>lists\\<close> of well-formed terms.  This formulation is more\ndirect, if more obscure, than using a universal quantifier.\n\\<close>\n\ninductive_set\n  well_formed_gterm' :: \"('f \\<Rightarrow> nat) \\<Rightarrow> 'f gterm set\"\n  for arity :: \"'f \\<Rightarrow> nat\"\nwhere\nstep[intro!]: \"\\<lbrakk>args \\<in> lists (well_formed_gterm' arity);  \n                length args = arity f\\<rbrakk>\n               \\<Longrightarrow> (Apply f args) \\<in> well_formed_gterm' arity\"\nmonos lists_mono\n\ntext \\<open>\nWe cite the theorem \\<open>lists_mono\\<close> to justify \nusing the function \\<^term>\\<open>lists\\<close>.%\n\\footnote{This particular theorem is installed by default already, but we\ninclude the \\isakeyword{monos} declaration in order to illustrate its syntax.}\n@{named_thms [display,indent=0] lists_mono [no_vars] (lists_mono)}\nWhy must the function be monotone?  An inductive definition describes\nan iterative construction: each element of the set is constructed by a\nfinite number of introduction rule applications.  For example, the\nelements of \\isa{even} are constructed by finitely many applications of\nthe rules\n@{thm [display,indent=0] even.intros [no_vars]}\nAll references to a set in its\ninductive definition must be positive.  Applications of an\nintroduction rule cannot invalidate previous applications, allowing the\nconstruction process to converge.\nThe following pair of rules do not constitute an inductive definition:\n\\begin{trivlist}\n\\item \\<^term>\\<open>0 \\<in> even\\<close>\n\\item \\<^term>\\<open>n \\<notin> even \\<Longrightarrow> (Suc n) \\<in> even\\<close>\n\\end{trivlist}\nShowing that 4 is even using these rules requires showing that 3 is not\neven.  It is far from trivial to show that this set of rules\ncharacterizes the even numbers.  \n\nEven with its use of the function \\isa{lists}, the premise of our\nintroduction rule is positive:\n@{thm [display,indent=0] (prem 1) step [no_vars]}\nTo apply the rule we construct a list \\<^term>\\<open>args\\<close> of previously\nconstructed well-formed terms.  We obtain a\nnew term, \\<^term>\\<open>Apply f args\\<close>.  Because \\<^term>\\<open>lists\\<close> is monotone,\napplications of the rule remain valid as new terms are constructed.\nFurther lists of well-formed\nterms become available and none are taken away.%\n\\index{monotone functions!and inductive definitions|)} \n\\<close>\n\nsubsection\\<open>A Proof of Equivalence\\<close>\n\ntext \\<open>\nWe naturally hope that these two inductive definitions of ``well-formed'' \ncoincide.  The equality can be proved by separate inclusions in \neach direction.  Each is a trivial rule induction. \n\\<close>\n\nlemma \"well_formed_gterm arity \\<subseteq> well_formed_gterm' arity\"\napply clarify\napply (erule well_formed_gterm.induct)\napply auto\ndone\n(*<*)\nlemma \"well_formed_gterm arity \\<subseteq> well_formed_gterm' arity\"\napply clarify\napply (erule well_formed_gterm.induct)\n(*>*)\ntxt \\<open>\nThe \\<open>clarify\\<close> method gives\nus an element of \\<^term>\\<open>well_formed_gterm arity\\<close> on which to perform \ninduction.  The resulting subgoal can be proved automatically:\n@{subgoals[display,indent=0]}\nThis proof resembles the one given in\n{\\S}\\ref{sec:gterm-datatype} above, especially in the form of the\ninduction hypothesis.  Next, we consider the opposite inclusion:\n\\<close>\n(*<*)oops(*>*)\nlemma \"well_formed_gterm' arity \\<subseteq> well_formed_gterm arity\"\napply clarify\napply (erule well_formed_gterm'.induct)\napply auto\ndone\n(*<*)\nlemma \"well_formed_gterm' arity \\<subseteq> well_formed_gterm arity\"\napply clarify\napply (erule well_formed_gterm'.induct)\n(*>*)\ntxt \\<open>\nThe proof script is virtually identical,\nbut the subgoal after applying induction may be surprising:\n@{subgoals[display,indent=0,margin=65]}\nThe induction hypothesis contains an application of \\<^term>\\<open>lists\\<close>.  Using a\nmonotone function in the inductive definition always has this effect.  The\nsubgoal may look uninviting, but fortunately \n\\<^term>\\<open>lists\\<close> distributes over intersection:\n@{named_thms [display,indent=0] lists_Int_eq [no_vars] (lists_Int_eq)}\nThanks to this default simplification rule, the induction hypothesis \nis quickly replaced by its two parts:\n\\begin{trivlist}\n\\item \\<^term>\\<open>args \\<in> lists (well_formed_gterm' arity)\\<close>\n\\item \\<^term>\\<open>args \\<in> lists (well_formed_gterm arity)\\<close>\n\\end{trivlist}\nInvoking the rule \\<open>well_formed_gterm.step\\<close> completes the proof.  The\ncall to \\<open>auto\\<close> does all this work.\n\nThis example is typical of how monotone functions\n\\index{monotone functions} can be used.  In particular, many of them\ndistribute over intersection.  Monotonicity implies one direction of\nthis set equality; we have this theorem:\n@{named_thms [display,indent=0] mono_Int [no_vars] (mono_Int)}\n\\<close>\n(*<*)oops(*>*)\n\n\nsubsection\\<open>Another Example of Rule Inversion\\<close>\n\ntext \\<open>\n\\index{rule inversion|(}%\nDoes \\<^term>\\<open>gterms\\<close> distribute over intersection?  We have proved that this\nfunction is monotone, so \\<open>mono_Int\\<close> gives one of the inclusions.  The\nopposite inclusion asserts that if \\<^term>\\<open>t\\<close> is a ground term over both of the\nsets\n\\<^term>\\<open>F\\<close> and~\\<^term>\\<open>G\\<close> then it is also a ground term over their intersection,\n\\<^term>\\<open>F \\<inter> G\\<close>.\n\\<close>\n\nlemma gterms_IntI:\n     \"t \\<in> gterms F \\<Longrightarrow> t \\<in> gterms G \\<longrightarrow> t \\<in> gterms (F\\<inter>G)\"\n(*<*)oops(*>*)\ntext \\<open>\nAttempting this proof, we get the assumption \n\\<^term>\\<open>Apply f args \\<in> gterms G\\<close>, which cannot be broken down. \nIt looks like a job for rule inversion:\\cmmdx{inductive\\protect\\_cases}\n\\<close>\n\ninductive_cases gterm_Apply_elim [elim!]: \"Apply f args \\<in> gterms F\"\n\ntext \\<open>\nHere is the result.\n@{named_thms [display,indent=0,margin=50] gterm_Apply_elim [no_vars] (gterm_Apply_elim)}\nThis rule replaces an assumption about \\<^term>\\<open>Apply f args\\<close> by \nassumptions about \\<^term>\\<open>f\\<close> and~\\<^term>\\<open>args\\<close>.  \nNo cases are discarded (there was only one to begin\nwith) but the rule applies specifically to the pattern \\<^term>\\<open>Apply f args\\<close>.\nIt can be applied repeatedly as an elimination rule without looping, so we\nhave given the \\<open>elim!\\<close> attribute. \n\nNow we can prove the other half of that distributive law.\n\\<close>\n\nlemma gterms_IntI [rule_format, intro!]:\n     \"t \\<in> gterms F \\<Longrightarrow> t \\<in> gterms G \\<longrightarrow> t \\<in> gterms (F\\<inter>G)\"\napply (erule gterms.induct)\napply blast\ndone\n(*<*)\nlemma \"t \\<in> gterms F \\<Longrightarrow> t \\<in> gterms G \\<longrightarrow> t \\<in> gterms (F\\<inter>G)\"\napply (erule gterms.induct)\n(*>*)\ntxt \\<open>\nThe proof begins with rule induction over the definition of\n\\<^term>\\<open>gterms\\<close>, which leaves a single subgoal:  \n@{subgoals[display,indent=0,margin=65]}\nTo prove this, we assume \\<^term>\\<open>Apply f args \\<in> gterms G\\<close>.  Rule inversion,\nin the form of \\<open>gterm_Apply_elim\\<close>, infers\nthat every element of \\<^term>\\<open>args\\<close> belongs to \n\\<^term>\\<open>gterms G\\<close>; hence (by the induction hypothesis) it belongs\nto \\<^term>\\<open>gterms (F \\<inter> G)\\<close>.  Rule inversion also yields\n\\<^term>\\<open>f \\<in> G\\<close> and hence \\<^term>\\<open>f \\<in> F \\<inter> G\\<close>. \nAll of this reasoning is done by \\<open>blast\\<close>.\n\n\\smallskip\nOur distributive law is a trivial consequence of previously-proved results:\n\\<close>\n(*<*)oops(*>*)\nlemma gterms_Int_eq [simp]:\n     \"gterms (F \\<inter> G) = gterms F \\<inter> gterms G\"\nby (blast intro!: mono_Int monoI gterms_mono)\n\ntext_raw \\<open>\n\\index{rule inversion|)}%\n\\index{ground terms example|)}\n\n\n\\begin{isamarkuptext}\n\\begin{exercise}\nA function mapping function symbols to their \ntypes is called a \\textbf{signature}.  Given a type \nranging over type symbols, we can represent a function's type by a\nlist of argument types paired with the result type. \nComplete this inductive definition:\n\\begin{isabelle}\n\\<close>\n\ninductive_set\n  well_typed_gterm :: \"('f \\<Rightarrow> 't list * 't) \\<Rightarrow> ('f gterm * 't)set\"\n  for sig :: \"'f \\<Rightarrow> 't list * 't\"\n(*<*)\nwhere\nstep[intro!]: \n    \"\\<lbrakk>\\<forall>pair \\<in> set args. pair \\<in> well_typed_gterm sig; \n      sig f = (map snd args, rtype)\\<rbrakk>\n     \\<Longrightarrow> (Apply f (map fst args), rtype) \n         \\<in> well_typed_gterm sig\"\n(*>*)\ntext_raw \\<open>\n\\end{isabelle}\n\\end{exercise}\n\\end{isamarkuptext}\n\\<close>\n\n(*<*)\n\ntext\\<open>the following declaration isn't actually used\\<close>\nprimrec\n  integer_arity :: \"integer_op \\<Rightarrow> nat\"\nwhere\n  \"integer_arity (Number n)        = 0\"\n| \"integer_arity UnaryMinus        = 1\"\n| \"integer_arity Plus              = 2\"\n\ntext\\<open>the rest isn't used: too complicated.  OK for an exercise though.\\<close>\n\ninductive_set\n  integer_signature :: \"(integer_op * (unit list * unit)) set\"\nwhere\n  Number:     \"(Number n,   ([], ())) \\<in> integer_signature\"\n| UnaryMinus: \"(UnaryMinus, ([()], ())) \\<in> integer_signature\"\n| Plus:       \"(Plus,       ([(),()], ())) \\<in> integer_signature\"\n\ninductive_set\n  well_typed_gterm' :: \"('f \\<Rightarrow> 't list * 't) \\<Rightarrow> ('f gterm * 't)set\"\n  for sig :: \"'f \\<Rightarrow> 't list * 't\"\nwhere\nstep[intro!]: \n    \"\\<lbrakk>args \\<in> lists(well_typed_gterm' sig); \n      sig f = (map snd args, rtype)\\<rbrakk>\n     \\<Longrightarrow> (Apply f (map fst args), rtype) \n         \\<in> well_typed_gterm' sig\"\nmonos lists_mono\n\n\nlemma \"well_typed_gterm sig \\<subseteq> well_typed_gterm' sig\"\napply clarify\napply (erule well_typed_gterm.induct)\napply auto\ndone\n\nlemma \"well_typed_gterm' sig \\<subseteq> well_typed_gterm sig\"\napply clarify\napply (erule well_typed_gterm'.induct)\napply auto\ndone\n\n\nend\n(*>*)\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/Doc/Tutorial/Inductive/Advanced.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8791467770088163, "lm_q1q2_score": 0.7728990443899659}}
{"text": "section \\<open>\\<open>Complex_L2\\<close> -- Hilbert space of square-summable functions\\<close>\n\n(*\nAuthors:\n\n  Dominique Unruh, University of Tartu, unruh@ut.ee\n  Jose Manuel Rodriguez Caballero, University of Tartu, jose.manuel.rodriguez.caballero@ut.ee\n\n*)\n\ntheory Complex_L2\n  imports \n    Complex_Bounded_Linear_Function\n\n    \"HOL-Analysis.L2_Norm\"\n    \"HOL-Library.Rewrite\"\n    \"HOL-Analysis.Infinite_Sum\"\nbegin\n\nunbundle cblinfun_notation\nunbundle no_notation_blinfun_apply\n\nsubsection \\<open>l2 norm of functions\\<close>\n\ndefinition \"has_ell2_norm (x::_\\<Rightarrow>complex) \\<longleftrightarrow> (\\<lambda>i. (x i)\\<^sup>2) abs_summable_on UNIV\"\n\nlemma has_ell2_norm_bdd_above: \\<open>has_ell2_norm x \\<longleftrightarrow> bdd_above (sum (\\<lambda>xa. norm ((x xa)\\<^sup>2)) ` Collect finite)\\<close>\n  by (simp add: has_ell2_norm_def abs_summable_bdd_above)\n\nlemma has_ell2_norm_L2_set: \"has_ell2_norm x = bdd_above (L2_set (norm o x) ` Collect finite)\"\nproof (rule iffI)\n  have \\<open>mono sqrt\\<close>\n    using monoI real_sqrt_le_mono by blast\n  assume \\<open>has_ell2_norm x\\<close>\n  then have *: \\<open>bdd_above (sum (\\<lambda>xa. norm ((x xa)\\<^sup>2)) ` Collect finite)\\<close>\n    by (subst (asm) has_ell2_norm_bdd_above)\n  have \\<open>bdd_above ((\\<lambda>F. sqrt (sum (\\<lambda>xa. norm ((x xa)\\<^sup>2)) F)) ` Collect finite)\\<close>\n    using bdd_above_image_mono[OF \\<open>mono sqrt\\<close> *]\n    by (auto simp: image_image)\n  then show \\<open>bdd_above (L2_set (norm o x) ` Collect finite)\\<close>\n    by (auto simp: L2_set_def norm_power)\nnext\n  define p2 where \\<open>p2 x = (if x < 0 then 0 else x^2)\\<close> for x :: real\n  have \\<open>mono p2\\<close>\n    by (simp add: monoI p2_def)\n  have [simp]: \\<open>p2 (L2_set f F) = (\\<Sum>i\\<in>F. (f i)\\<^sup>2)\\<close> for f and F :: \\<open>'a set\\<close>\n    by (smt (verit) L2_set_def L2_set_nonneg p2_def power2_less_0 real_sqrt_pow2 sum.cong sum_nonneg)\n  assume *: \\<open>bdd_above (L2_set (norm o x) ` Collect finite)\\<close>\n  have \\<open>bdd_above (p2 ` L2_set (norm o x) ` Collect finite)\\<close>\n    using bdd_above_image_mono[OF \\<open>mono p2\\<close> *]\n    by auto\n  then show \\<open>has_ell2_norm x\\<close>\n    apply (simp add: image_image has_ell2_norm_def abs_summable_bdd_above)\n    by (simp add: norm_power)\nqed\n\ndefinition ell2_norm :: \\<open>('a \\<Rightarrow> complex) \\<Rightarrow> real\\<close> where \\<open>ell2_norm x = sqrt (\\<Sum>\\<^sub>\\<infinity>i. norm (x i)^2)\\<close>\n\nlemma ell2_norm_SUP:\n  assumes \\<open>has_ell2_norm x\\<close>\n  shows \"ell2_norm x = sqrt (SUP F\\<in>{F. finite F}. sum (\\<lambda>i. norm (x i)^2) F)\"\n  using assms apply (auto simp add: ell2_norm_def has_ell2_norm_def)\n  apply (subst infsum_nonneg_is_SUPREMUM_real)\n  by (auto simp: norm_power)\n\nlemma ell2_norm_L2_set: \n  assumes \"has_ell2_norm x\"\n  shows \"ell2_norm x = (SUP F\\<in>{F. finite F}. L2_set (norm o x) F)\"\nproof-\n  have \"sqrt (\\<Squnion> (sum (\\<lambda>i. (cmod (x i))\\<^sup>2) ` Collect finite)) =\n      (SUP F\\<in>{F. finite F}. sqrt (\\<Sum>i\\<in>F. (cmod (x i))\\<^sup>2))\"\n  proof (subst continuous_at_Sup_mono)\n    show \"mono sqrt\"\n      by (simp add: mono_def)      \n    show \"continuous (at_left (\\<Squnion> (sum (\\<lambda>i. (cmod (x i))\\<^sup>2) ` Collect finite))) sqrt\"\n      using continuous_at_split isCont_real_sqrt by blast    \n    show \"sum (\\<lambda>i. (cmod (x i))\\<^sup>2) ` Collect finite \\<noteq> {}\"\n      by auto      \n    show \"bdd_above (sum (\\<lambda>i. (cmod (x i))\\<^sup>2) ` Collect finite)\"\n      using has_ell2_norm_bdd_above[THEN iffD1, OF assms] by (auto simp: norm_power)\n    show \"\\<Squnion> (sqrt ` sum (\\<lambda>i. (cmod (x i))\\<^sup>2) ` Collect finite) = (SUP F\\<in>Collect finite. sqrt (\\<Sum>i\\<in>F. (cmod (x i))\\<^sup>2))\"\n      by (metis image_image)      \n  qed  \n  thus ?thesis \n    using assms by (auto simp: ell2_norm_SUP L2_set_def)\nqed\n\nlemma has_ell2_norm_finite[simp]: \"has_ell2_norm (x::'a::finite\\<Rightarrow>_)\"\n  unfolding has_ell2_norm_def by simp\n\nlemma ell2_norm_finite: \n  \"ell2_norm (x::'a::finite\\<Rightarrow>complex) = sqrt (sum (\\<lambda>i. (norm(x i))^2) UNIV)\"\n  by (simp add: ell2_norm_def)\n\nlemma ell2_norm_finite_L2_set: \"ell2_norm (x::'a::finite\\<Rightarrow>complex) = L2_set (norm o x) UNIV\"\n  by (simp add: ell2_norm_finite L2_set_def)\n\nlemma ell2_ket:\n  fixes a\n  defines \\<open>f \\<equiv> (\\<lambda>i. if a = i then 1 else 0)\\<close>\n  shows has_ell2_norm_ket: \\<open>has_ell2_norm f\\<close>\n    and ell2_norm_ket: \\<open>ell2_norm f = 1\\<close>\nproof -\n  have \\<open>(\\<lambda>x. (f x)\\<^sup>2) abs_summable_on {a}\\<close>\n    apply (rule summable_on_finite) by simp\n  then show \\<open>has_ell2_norm f\\<close>\n    unfolding has_ell2_norm_def\n    apply (rule summable_on_cong_neutral[THEN iffD1, rotated -1])\n    unfolding f_def by auto\n\n  have \\<open>(\\<Sum>\\<^sub>\\<infinity>x\\<in>{a}. (f x)\\<^sup>2) = 1\\<close>\n    apply (subst infsum_finite)\n    by (auto simp: f_def)\n  then show \\<open>ell2_norm f = 1\\<close>\n    unfolding ell2_norm_def\n    apply (subst infsum_cong_neutral[where T=\\<open>{a}\\<close> and g=\\<open>\\<lambda>x. (cmod (f x))\\<^sup>2\\<close>])\n    by (auto simp: f_def)\nqed\n\nlemma ell2_norm_geq0: \\<open>ell2_norm x \\<ge> 0\\<close>\n  by (auto simp: ell2_norm_def intro!: infsum_nonneg)\n\nlemma ell2_norm_point_bound:\n  assumes \\<open>has_ell2_norm x\\<close>\n  shows \\<open>ell2_norm x \\<ge> cmod (x i)\\<close>\nproof -\n  have \\<open>(cmod (x i))\\<^sup>2 = norm ((x i)\\<^sup>2)\\<close>\n    by (simp add: norm_power)\n  also have \\<open>norm ((x i)\\<^sup>2) = sum (\\<lambda>i. (norm ((x i)\\<^sup>2))) {i}\\<close>\n    by auto\n  also have \\<open>\\<dots> = infsum (\\<lambda>i. (norm ((x i)\\<^sup>2))) {i}\\<close>\n    by (rule infsum_finite[symmetric], simp)\n  also have \\<open>\\<dots> \\<le> infsum (\\<lambda>i. (norm ((x i)\\<^sup>2))) UNIV\\<close>\n    apply (rule infsum_mono_neutral)\n    using assms by (auto simp: has_ell2_norm_def)\n  also have \\<open>\\<dots> = (ell2_norm x)\\<^sup>2\\<close>\n    by (metis (no_types, lifting) ell2_norm_def ell2_norm_geq0 infsum_cong norm_power real_sqrt_eq_iff real_sqrt_unique)\n  finally show ?thesis\n    using ell2_norm_geq0 power2_le_imp_le by blast\nqed\n\nlemma ell2_norm_0:\n  assumes \"has_ell2_norm x\"\n  shows \"(ell2_norm x = 0) = (x = (\\<lambda>_. 0))\"\nproof\n  assume u1: \"x = (\\<lambda>_. 0)\"\n  have u2: \"(SUP x::'a set\\<in>Collect finite. (0::real)) = 0\"\n    if \"x = (\\<lambda>_. 0)\"\n    by (metis cSUP_const empty_Collect_eq finite.emptyI)\n  show \"ell2_norm x = 0\"\n    unfolding ell2_norm_def\n    using u1 u2 by auto \nnext\n  assume norm0: \"ell2_norm x = 0\"\n  show \"x = (\\<lambda>_. 0)\"\n  proof\n    fix i\n    have \\<open>cmod (x i) \\<le> ell2_norm x\\<close>\n      using assms by (rule ell2_norm_point_bound)\n    also have \\<open>\\<dots> = 0\\<close>\n      by (fact norm0)\n    finally show \"x i = 0\" by auto\n  qed\nqed\n\n\nlemma ell2_norm_smult:\n  assumes \"has_ell2_norm x\"\n  shows \"has_ell2_norm (\\<lambda>i. c * x i)\" and \"ell2_norm (\\<lambda>i. c * x i) = cmod c * ell2_norm x\"\nproof -\n  have L2_set_mul: \"L2_set (cmod \\<circ> (\\<lambda>i. c * x i)) F = cmod c * L2_set (cmod \\<circ> x) F\" for F\n  proof-\n    have \"L2_set (cmod \\<circ> (\\<lambda>i. c * x i)) F = L2_set (\\<lambda>i. (cmod c * (cmod o x) i)) F\"\n      by (metis comp_def norm_mult)\n    also have \"\\<dots> = cmod c * L2_set (cmod o x) F\"\n      by (metis norm_ge_zero L2_set_right_distrib)\n    finally show ?thesis .\n  qed\n\n  from assms obtain M where M: \"M \\<ge> L2_set (cmod o x) F\" if \"finite F\" for F\n    unfolding has_ell2_norm_L2_set bdd_above_def by auto\n  hence \"cmod c * M \\<ge> L2_set (cmod o (\\<lambda>i. c * x i)) F\" if \"finite F\" for F\n    unfolding L2_set_mul\n    by (simp add: ordered_comm_semiring_class.comm_mult_left_mono that) \n  thus has: \"has_ell2_norm (\\<lambda>i. c * x i)\"\n    unfolding has_ell2_norm_L2_set bdd_above_def using L2_set_mul[symmetric] by auto\n  have \"ell2_norm (\\<lambda>i. c * x i) = (SUP F \\<in> Collect finite. (L2_set (cmod \\<circ> (\\<lambda>i. c * x i)) F))\"\n    by (simp add: ell2_norm_L2_set has)\n  also have \"\\<dots> = (SUP F \\<in> Collect finite. (cmod c * L2_set (cmod \\<circ> x) F))\"\n    using L2_set_mul by auto   \n  also have \"\\<dots> = cmod c * ell2_norm x\" \n  proof (subst ell2_norm_L2_set)\n    show \"has_ell2_norm x\"\n      by (simp add: assms)      \n    show \"(SUP F\\<in>Collect finite. cmod c * L2_set (cmod \\<circ> x) F) = cmod c * \\<Squnion> (L2_set (cmod \\<circ> x) ` Collect finite)\"\n    proof (subst continuous_at_Sup_mono [where f = \"\\<lambda>x. cmod c * x\"])\n      show \"mono ((*) (cmod c))\"\n        by (simp add: mono_def ordered_comm_semiring_class.comm_mult_left_mono)\n      show \"continuous (at_left (\\<Squnion> (L2_set (cmod \\<circ> x) ` Collect finite))) ((*) (cmod c))\"\n      proof (rule continuous_mult)\n        show \"continuous (at_left (\\<Squnion> (L2_set (cmod \\<circ> x) ` Collect finite))) (\\<lambda>x. cmod c)\"\n          by simp\n        show \"continuous (at_left (\\<Squnion> (L2_set (cmod \\<circ> x) ` Collect finite))) (\\<lambda>x. x)\"\n          by simp\n      qed    \n      show \"L2_set (cmod \\<circ> x) ` Collect finite \\<noteq> {}\"\n        by auto        \n      show \"bdd_above (L2_set (cmod \\<circ> x) ` Collect finite)\"\n        by (meson assms has_ell2_norm_L2_set)        \n      show \"(SUP F\\<in>Collect finite. cmod c * L2_set (cmod \\<circ> x) F) = \\<Squnion> ((*) (cmod c) ` L2_set (cmod \\<circ> x) ` Collect finite)\"\n        by (metis image_image)        \n    qed   \n  qed     \n  finally show \"ell2_norm (\\<lambda>i. c * x i) = cmod c * ell2_norm x\".\nqed\n\n\nlemma ell2_norm_triangle:\n  assumes \"has_ell2_norm x\" and \"has_ell2_norm y\"\n  shows \"has_ell2_norm (\\<lambda>i. x i + y i)\" and \"ell2_norm (\\<lambda>i. x i + y i) \\<le> ell2_norm x + ell2_norm y\"\nproof -\n  have triangle: \"L2_set (cmod \\<circ> (\\<lambda>i. x i + y i)) F \\<le> L2_set (cmod \\<circ> x) F + L2_set (cmod \\<circ> y) F\" \n    (is \"?lhs\\<le>?rhs\") \n    if \"finite F\" for F\n  proof -\n    have \"?lhs \\<le> L2_set (\\<lambda>i. (cmod o x) i + (cmod o y) i) F\"\n    proof (rule L2_set_mono)\n      show \"(cmod \\<circ> (\\<lambda>i. x i + y i)) i \\<le> (cmod \\<circ> x) i + (cmod \\<circ> y) i\"\n        if \"i \\<in> F\"\n        for i :: 'a\n        using that norm_triangle_ineq by auto \n      show \"0 \\<le> (cmod \\<circ> (\\<lambda>i. x i + y i)) i\"\n        if \"i \\<in> F\"\n        for i :: 'a\n        using that\n        by simp \n    qed\n    also have \"\\<dots> \\<le> ?rhs\"\n      by (rule L2_set_triangle_ineq)\n    finally show ?thesis .\n  qed\n  obtain Mx My where Mx: \"Mx \\<ge> L2_set (cmod o x) F\" and My: \"My \\<ge> L2_set (cmod o y) F\" \n    if \"finite F\" for F\n    using assms unfolding has_ell2_norm_L2_set bdd_above_def by auto\n  hence MxMy: \"Mx + My \\<ge> L2_set (cmod \\<circ> x) F + L2_set (cmod \\<circ> y) F\" if \"finite F\" for F\n    using that by fastforce\n  hence bdd_plus: \"bdd_above ((\\<lambda>xa. L2_set (cmod \\<circ> x) xa + L2_set (cmod \\<circ> y) xa) ` Collect finite)\"\n    unfolding bdd_above_def by auto\n  from MxMy have MxMy': \"Mx + My \\<ge> L2_set (cmod \\<circ> (\\<lambda>i. x i + y i)) F\" if \"finite F\" for F \n    using triangle that by fastforce\n  thus has: \"has_ell2_norm (\\<lambda>i. x i + y i)\"\n    unfolding has_ell2_norm_L2_set bdd_above_def by auto\n  have SUP_plus: \"(SUP x\\<in>A. f x + g x) \\<le> (SUP x\\<in>A. f x) + (SUP x\\<in>A. g x)\" \n    if notempty: \"A\\<noteq>{}\" and bddf: \"bdd_above (f`A)\"and bddg: \"bdd_above (g`A)\"\n    for f g :: \"'a set \\<Rightarrow> real\" and A\n  proof-\n    have xleq: \"x \\<le> (SUP x\\<in>A. f x) + (SUP x\\<in>A. g x)\" if x: \"x \\<in> (\\<lambda>x. f x + g x) ` A\" for x\n    proof -\n      obtain a where aA: \"a:A\" and ax: \"x = f a + g a\"\n        using x by blast\n      have fa: \"f a \\<le> (SUP x\\<in>A. f x)\"\n        by (simp add: bddf aA cSUP_upper)\n      moreover have \"g a \\<le> (SUP x\\<in>A. g x)\"\n        by (simp add: bddg aA cSUP_upper)\n      ultimately have \"f a + g a \\<le> (SUP x\\<in>A. f x) + (SUP x\\<in>A. g x)\" by simp\n      with ax show ?thesis by simp\n    qed\n    have \"(\\<lambda>x. f x + g x) ` A \\<noteq> {}\"\n      using notempty by auto        \n    moreover have \"x \\<le> \\<Squnion> (f ` A) + \\<Squnion> (g ` A)\"\n      if \"x \\<in> (\\<lambda>x. f x + g x) ` A\"\n      for x :: real\n      using that\n      by (simp add: xleq) \n    ultimately show ?thesis\n      by (meson bdd_above_def cSup_le_iff)      \n  qed\n  have a2: \"bdd_above (L2_set (cmod \\<circ> x) ` Collect finite)\"\n    by (meson assms(1) has_ell2_norm_L2_set)    \n  have a3: \"bdd_above (L2_set (cmod \\<circ> y) ` Collect finite)\"\n    by (meson assms(2) has_ell2_norm_L2_set)    \n  have a1: \"Collect finite \\<noteq> {}\"\n    by auto    \n  have a4: \"\\<Squnion> (L2_set (cmod \\<circ> (\\<lambda>i. x i + y i)) ` Collect finite)\n    \\<le> (SUP xa\\<in>Collect finite.\n           L2_set (cmod \\<circ> x) xa + L2_set (cmod \\<circ> y) xa)\"\n    by (metis (mono_tags, lifting) a1 bdd_plus cSUP_mono mem_Collect_eq triangle)    \n  have \"\\<forall>r. \\<Squnion> (L2_set (cmod \\<circ> (\\<lambda>a. x a + y a)) ` Collect finite) \\<le> r \\<or> \\<not> (SUP A\\<in>Collect finite. L2_set (cmod \\<circ> x) A + L2_set (cmod \\<circ> y) A) \\<le> r\"\n    using a4 by linarith\n  hence \"\\<Squnion> (L2_set (cmod \\<circ> (\\<lambda>i. x i + y i)) ` Collect finite)\n    \\<le> \\<Squnion> (L2_set (cmod \\<circ> x) ` Collect finite) +\n       \\<Squnion> (L2_set (cmod \\<circ> y) ` Collect finite)\"\n    by (metis (no_types) SUP_plus a1 a2 a3)\n  hence \"\\<Squnion> (L2_set (cmod \\<circ> (\\<lambda>i. x i + y i)) ` Collect finite) \\<le> ell2_norm x + ell2_norm y\"\n    by (simp add: assms(1) assms(2) ell2_norm_L2_set)\n  thus \"ell2_norm (\\<lambda>i. x i + y i) \\<le> ell2_norm x + ell2_norm y\"\n    by (simp add: ell2_norm_L2_set has)  \nqed\n\nlemma ell2_norm_uminus:\n  assumes \"has_ell2_norm x\"\n  shows \\<open>has_ell2_norm (\\<lambda>i. - x i)\\<close> and \\<open>ell2_norm (\\<lambda>i. - x i) = ell2_norm x\\<close>\n  using assms by (auto simp: has_ell2_norm_def ell2_norm_def)\n\nsubsection \\<open>The type \\<open>ell2\\<close> of square-summable functions\\<close>\n\ntypedef 'a ell2 = \"{x::'a\\<Rightarrow>complex. has_ell2_norm x}\"\n  unfolding has_ell2_norm_def by (rule exI[of _ \"\\<lambda>_.0\"], auto)\nsetup_lifting type_definition_ell2\n\ninstantiation ell2 :: (type)complex_vector begin\nlift_definition zero_ell2 :: \"'a ell2\" is \"\\<lambda>_. 0\" by (auto simp: has_ell2_norm_def)\nlift_definition uminus_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2\" is uminus by (simp add: has_ell2_norm_def)\nlift_definition plus_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>f g x. f x + g x\"\n  by (rule ell2_norm_triangle) \nlift_definition minus_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>f g x. f x - g x\"\n  apply (subst add_uminus_conv_diff[symmetric])\n  apply (rule ell2_norm_triangle)\n  by (auto simp add: ell2_norm_uminus)\nlift_definition scaleR_ell2 :: \"real \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>r f x. complex_of_real r * f x\"\n  by (rule ell2_norm_smult)\nlift_definition scaleC_ell2 :: \"complex \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>c f x. c * f x\"\n  by (rule ell2_norm_smult)\n\ninstance\nproof\n  fix a b c :: \"'a ell2\"\n\n  show \"((*\\<^sub>R) r::'a ell2 \\<Rightarrow> _) = (*\\<^sub>C) (complex_of_real r)\" for r\n    apply (rule ext) apply transfer by auto\n  show \"a + b + c = a + (b + c)\"\n    by (transfer; rule ext; simp)\n  show \"a + b = b + a\"\n    by (transfer; rule ext; simp)\n  show \"0 + a = a\"\n    by (transfer; rule ext; simp)\n  show \"- a + a = 0\"\n    by (transfer; rule ext; simp)\n  show \"a - b = a + - b\"\n    by (transfer; rule ext; simp)\n  show \"r *\\<^sub>C (a + b) = r *\\<^sub>C a + r *\\<^sub>C b\" for r\n    apply (transfer; rule ext)\n    by (simp add: vector_space_over_itself.scale_right_distrib)\n  show \"(r + r') *\\<^sub>C a = r *\\<^sub>C a + r' *\\<^sub>C a\" for r r'\n    apply (transfer; rule ext)\n    by (simp add: ring_class.ring_distribs(2)) \n  show \"r *\\<^sub>C r' *\\<^sub>C a = (r * r') *\\<^sub>C a\" for r r'\n    by (transfer; rule ext; simp)\n  show \"1 *\\<^sub>C a = a\"\n    by (transfer; rule ext; simp)\nqed\nend\n\ninstantiation ell2 :: (type)complex_normed_vector begin\nlift_definition norm_ell2 :: \"'a ell2 \\<Rightarrow> real\" is ell2_norm .\ndeclare norm_ell2_def[code del]\ndefinition \"dist x y = norm (x - y)\" for x y::\"'a ell2\"\ndefinition \"sgn x = x /\\<^sub>R norm x\" for x::\"'a ell2\"\ndefinition [code del]: \"uniformity = (INF e\\<in>{0<..}. principal {(x::'a ell2, y). norm (x - y) < e})\"\ndefinition [code del]: \"open U = (\\<forall>x\\<in>U. \\<forall>\\<^sub>F (x', y) in INF e\\<in>{0<..}. principal {(x, y). norm (x - y) < e}. x' = x \\<longrightarrow> y \\<in> U)\" for U :: \"'a ell2 set\"\ninstance\nproof\n  fix a b :: \"'a ell2\"\n  show \"dist a b = norm (a - b)\"\n    by (simp add: dist_ell2_def)    \n  show \"sgn a = a /\\<^sub>R norm a\"\n    by (simp add: sgn_ell2_def)    \n  show \"uniformity = (INF e\\<in>{0<..}. principal {(x, y). dist (x::'a ell2) y < e})\"\n    unfolding dist_ell2_def  uniformity_ell2_def by simp\n  show \"open U = (\\<forall>x\\<in>U. \\<forall>\\<^sub>F (x', y) in uniformity. (x'::'a ell2) = x \\<longrightarrow> y \\<in> U)\" for U :: \"'a ell2 set\"\n    unfolding uniformity_ell2_def open_ell2_def by simp_all        \n  show \"(norm a = 0) = (a = 0)\"\n    apply transfer by (fact ell2_norm_0)    \n  show \"norm (a + b) \\<le> norm a + norm b\"\n    apply transfer by (fact ell2_norm_triangle)\n  show \"norm (r *\\<^sub>R (a::'a ell2)) = \\<bar>r\\<bar> * norm a\" for r\n    and a :: \"'a ell2\"\n    apply transfer\n    by (simp add: ell2_norm_smult(2)) \n  show \"norm (r *\\<^sub>C a) = cmod r * norm a\" for r\n    apply transfer\n    by (simp add: ell2_norm_smult(2)) \nqed  \nend\n\nlemma norm_point_bound_ell2: \"norm (Rep_ell2 x i) \\<le> norm x\"\n  apply transfer\n  by (simp add: ell2_norm_point_bound)\n\nlemma ell2_norm_finite_support:\n  assumes \\<open>finite S\\<close> \\<open>\\<And> i. i \\<notin> S \\<Longrightarrow> Rep_ell2 x i = 0\\<close>\n  shows \\<open>norm x = sqrt ((sum (\\<lambda>i. (cmod (Rep_ell2 x i))\\<^sup>2)) S)\\<close>\nproof (insert assms(2), transfer fixing: S)\n  fix x :: \\<open>'a \\<Rightarrow> complex\\<close>\n  assume zero: \\<open>\\<And>i. i \\<notin> S \\<Longrightarrow> x i = 0\\<close>\n  have \\<open>ell2_norm x = sqrt (\\<Sum>\\<^sub>\\<infinity>i. (cmod (x i))\\<^sup>2)\\<close>\n    by (auto simp: ell2_norm_def)\n  also have \\<open>\\<dots> = sqrt (\\<Sum>\\<^sub>\\<infinity>i\\<in>S. (cmod (x i))\\<^sup>2)\\<close>\n    apply (subst infsum_cong_neutral[where g=\\<open>\\<lambda>i. (cmod (x i))\\<^sup>2\\<close> and S=UNIV and T=S])\n    using zero by auto\n  also have \\<open>\\<dots> = sqrt (\\<Sum>i\\<in>S. (cmod (x i))\\<^sup>2)\\<close>\n    using \\<open>finite S\\<close> by simp\n  finally show \\<open>ell2_norm x = sqrt (\\<Sum>i\\<in>S. (cmod (x i))\\<^sup>2)\\<close>\n    by -\nqed\n\ninstantiation ell2 :: (type) complex_inner begin\nlift_definition cinner_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2 \\<Rightarrow> complex\" is \n  \"\\<lambda>x y. infsum (\\<lambda>i. (cnj (x i) * y i)) UNIV\" .\ndeclare cinner_ell2_def[code del]\n\ninstance\nproof standard\n  fix x y z :: \"'a ell2\" fix c :: complex\n  show \"cinner x y = cnj (cinner y x)\"\n  proof transfer\n    fix x y :: \"'a\\<Rightarrow>complex\" assume \"has_ell2_norm x\" and \"has_ell2_norm y\"\n    have \"(\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * y i) = (\\<Sum>\\<^sub>\\<infinity>i. cnj (cnj (y i) * x i))\"\n      by (metis complex_cnj_cnj complex_cnj_mult mult.commute)\n    also have \"\\<dots> = cnj (\\<Sum>\\<^sub>\\<infinity>i. cnj (y i) * x i)\"\n      by (metis infsum_cnj) \n    finally show \"(\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * y i) = cnj (\\<Sum>\\<^sub>\\<infinity>i. cnj (y i) * x i)\" .\n  qed\n\n  show \"cinner (x + y) z = cinner x z + cinner y z\"\n  proof transfer\n    fix x y z :: \"'a \\<Rightarrow> complex\"\n    assume \"has_ell2_norm x\"\n    hence cnj_x: \"(\\<lambda>i. cnj (x i) * cnj (x i)) abs_summable_on UNIV\"\n      by (simp del: complex_cnj_mult add: norm_mult[symmetric] complex_cnj_mult[symmetric] has_ell2_norm_def power2_eq_square)\n    assume \"has_ell2_norm y\"\n    hence cnj_y: \"(\\<lambda>i. cnj (y i) * cnj (y i)) abs_summable_on UNIV\"\n      by (simp del: complex_cnj_mult add: norm_mult[symmetric] complex_cnj_mult[symmetric] has_ell2_norm_def power2_eq_square)\n    assume \"has_ell2_norm z\"\n    hence z: \"(\\<lambda>i. z i * z i) abs_summable_on UNIV\" \n      by (simp add: norm_mult[symmetric] has_ell2_norm_def power2_eq_square)\n    have cnj_x_z:\"(\\<lambda>i. cnj (x i) * z i) abs_summable_on UNIV\"\n      using cnj_x z by (rule abs_summable_product) \n    have cnj_y_z:\"(\\<lambda>i. cnj (y i) * z i) abs_summable_on UNIV\"\n      using cnj_y z by (rule abs_summable_product) \n    show \"(\\<Sum>\\<^sub>\\<infinity>i. cnj (x i + y i) * z i) = (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * z i) + (\\<Sum>\\<^sub>\\<infinity>i. cnj (y i) * z i)\"\n      apply (subst infsum_add [symmetric])\n      using cnj_x_z cnj_y_z \n      by (auto simp add: summable_on_iff_abs_summable_on_complex distrib_left mult.commute)\n  qed\n\n  show \"cinner (c *\\<^sub>C x) y = cnj c * cinner x y\"\n  proof transfer\n    fix x y :: \"'a \\<Rightarrow> complex\" and c :: complex\n    assume \"has_ell2_norm x\"\n    hence cnj_x: \"(\\<lambda>i. cnj (x i) * cnj (x i)) abs_summable_on UNIV\"\n      by (simp del: complex_cnj_mult add: norm_mult[symmetric] complex_cnj_mult[symmetric] has_ell2_norm_def power2_eq_square)\n    assume \"has_ell2_norm y\"\n    hence y: \"(\\<lambda>i. y i * y i) abs_summable_on UNIV\" \n      by (simp add: norm_mult[symmetric] has_ell2_norm_def power2_eq_square)\n    have cnj_x_y:\"(\\<lambda>i. cnj (x i) * y i) abs_summable_on UNIV\"\n      using cnj_x y by (rule abs_summable_product) \n    thus \"(\\<Sum>\\<^sub>\\<infinity>i. cnj (c * x i) * y i) = cnj c * (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * y i)\"\n      by (auto simp flip: infsum_cmult_right simp add: abs_summable_summable mult.commute vector_space_over_itself.scale_left_commute)\n  qed\n\n  show \"0 \\<le> cinner x x\"\n  proof transfer\n    fix x :: \"'a \\<Rightarrow> complex\"\n    assume \"has_ell2_norm x\"\n    hence \"(\\<lambda>i. cmod (cnj (x i) * x i)) abs_summable_on UNIV\"\n      by (simp add: norm_mult has_ell2_norm_def power2_eq_square)\n    hence \"(\\<lambda>i. cnj (x i) * x i) abs_summable_on UNIV\"\n      by auto\n    hence sum: \"(\\<lambda>i. cnj (x i) * x i) abs_summable_on UNIV\"\n      unfolding has_ell2_norm_def power2_eq_square.\n    have \"0 = (\\<Sum>\\<^sub>\\<infinity>i::'a. 0)\" by auto\n    also have \"\\<dots> \\<le> (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * x i)\"\n      apply (rule infsum_mono_complex)\n      by (auto simp add: abs_summable_summable sum)\n    finally show \"0 \\<le> (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * x i)\" by assumption\n  qed\n\n  show \"(cinner x x = 0) = (x = 0)\"\n  proof (transfer, auto)\n    fix x :: \"'a \\<Rightarrow> complex\"\n    assume \"has_ell2_norm x\"\n    hence \"(\\<lambda>i::'a. cmod (cnj (x i) * x i)) abs_summable_on UNIV\"\n      by (smt (verit, del_insts) complex_mod_mult_cnj has_ell2_norm_def mult.commute norm_ge_zero norm_power real_norm_def summable_on_cong)\n    hence cmod_x2: \"(\\<lambda>i. cnj (x i) * x i) abs_summable_on UNIV\"\n      unfolding has_ell2_norm_def power2_eq_square\n      by simp\n    assume eq0: \"(\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * x i) = 0\"\n    show \"x = (\\<lambda>_. 0)\"\n    proof (rule ccontr)\n      assume \"x \\<noteq> (\\<lambda>_. 0)\"\n      then obtain i where \"x i \\<noteq> 0\" by auto\n      hence \"0 < cnj (x i) * x i\"\n        by (metis le_less cnj_x_x_geq0 complex_cnj_zero_iff vector_space_over_itself.scale_eq_0_iff)\n      also have \"\\<dots> = (\\<Sum>\\<^sub>\\<infinity>i\\<in>{i}. cnj (x i) * x i)\" by auto\n      also have \"\\<dots> \\<le> (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * x i)\"\n        apply (rule infsum_mono_neutral_complex)\n        by (auto simp add: abs_summable_summable cmod_x2)\n      also from eq0 have \"\\<dots> = 0\" by assumption\n      finally show False by simp\n    qed\n  qed\n\n  show \"norm x = sqrt (cmod (cinner x x))\"\n  proof transfer \n    fix x :: \"'a \\<Rightarrow> complex\" \n    assume x: \"has_ell2_norm x\"\n    have \"(\\<lambda>i::'a. cmod (x i) * cmod (x i)) abs_summable_on UNIV \\<Longrightarrow>\n    (\\<lambda>i::'a. cmod (cnj (x i) * x i)) abs_summable_on UNIV\"\n      by (simp add: norm_mult has_ell2_norm_def power2_eq_square)\n    hence sum: \"(\\<lambda>i. cnj (x i) * x i) abs_summable_on UNIV\"\n      by (metis (no_types, lifting) complex_mod_mult_cnj has_ell2_norm_def mult.commute norm_power summable_on_cong x)\n    from x have \"ell2_norm x = sqrt (\\<Sum>\\<^sub>\\<infinity>i. (cmod (x i))\\<^sup>2)\"\n      unfolding ell2_norm_def by simp\n    also have \"\\<dots> = sqrt (\\<Sum>\\<^sub>\\<infinity>i. cmod (cnj (x i) * x i))\"\n      unfolding norm_complex_def power2_eq_square by auto\n    also have \"\\<dots> = sqrt (cmod (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * x i))\"\n      by (auto simp: infsum_cmod abs_summable_summable sum)\n    finally show \"ell2_norm x = sqrt (cmod (\\<Sum>\\<^sub>\\<infinity>i. cnj (x i) * x i))\" by assumption\n  qed\nqed\nend\n\ninstance ell2 :: (type) chilbert_space\nproof\n  fix X :: \\<open>nat \\<Rightarrow> 'a ell2\\<close>\n  define x where \\<open>x n a = Rep_ell2 (X n) a\\<close> for n a\n  have [simp]: \\<open>has_ell2_norm (x n)\\<close> for n\n    using Rep_ell2 x_def[abs_def] by simp\n\n  assume \\<open>Cauchy X\\<close>\n  moreover have \"dist (x n a) (x m a) \\<le> dist (X n) (X m)\" for n m a\n    by (metis Rep_ell2 x_def dist_norm ell2_norm_point_bound mem_Collect_eq minus_ell2.rep_eq norm_ell2.rep_eq)\n  ultimately have \\<open>Cauchy (\\<lambda>n. x n a)\\<close> for a\n    by (meson Cauchy_def le_less_trans)\n  then obtain l where x_lim: \\<open>(\\<lambda>n. x n a) \\<longlonglongrightarrow> l a\\<close> for a\n    apply atomize_elim apply (rule choice)\n    by (simp add: convergent_eq_Cauchy)\n  define L where \\<open>L = Abs_ell2 l\\<close>\n  define normF where \\<open>normF F x = L2_set (cmod \\<circ> x) F\\<close> for F :: \\<open>'a set\\<close> and x\n  have normF_triangle: \\<open>normF F (\\<lambda>a. x a + y a) \\<le> normF F x + normF F y\\<close> if \\<open>finite F\\<close> for F x y\n  proof -\n    have \\<open>normF F (\\<lambda>a. x a + y a) = L2_set (\\<lambda>a. cmod (x a + y a)) F\\<close>\n      by (metis (mono_tags, lifting) L2_set_cong comp_apply normF_def)\n    also have \\<open>\\<dots> \\<le> L2_set (\\<lambda>a. cmod (x a) + cmod (y a)) F\\<close>\n      by (meson L2_set_mono norm_ge_zero norm_triangle_ineq)\n    also have \\<open>\\<dots> \\<le> L2_set (\\<lambda>a. cmod (x a)) F + L2_set (\\<lambda>a. cmod (y a)) F\\<close>\n      by (simp add: L2_set_triangle_ineq)\n    also have \\<open>\\<dots> \\<le> normF F x + normF F y\\<close>\n      by (smt (verit, best) L2_set_cong normF_def comp_apply)\n    finally show ?thesis\n      by -\n  qed\n  have normF_negate: \\<open>normF F (\\<lambda>a. - x a) = normF F x\\<close> if \\<open>finite F\\<close> for F x\n    unfolding normF_def o_def by simp\n  have normF_ell2norm: \\<open>normF F x \\<le> ell2_norm x\\<close> if \\<open>finite F\\<close> and \\<open>has_ell2_norm x\\<close> for F x\n    apply (auto intro!: cSUP_upper2[where x=F] simp: that normF_def ell2_norm_L2_set)\n    by (meson has_ell2_norm_L2_set that(2))\n\n  note Lim_bounded2[rotated, rule_format, trans]\n\n  from \\<open>Cauchy X\\<close>\n  obtain I where cauchyX: \\<open>norm (X n - X m) \\<le> \\<epsilon>\\<close> if \\<open>\\<epsilon>>0\\<close> \\<open>n\\<ge>I \\<epsilon>\\<close> \\<open>m\\<ge>I \\<epsilon>\\<close> for \\<epsilon> n m\n    by (metis Cauchy_def dist_norm less_eq_real_def)\n  have normF_xx: \\<open>normF F (\\<lambda>a. x n a - x m a) \\<le> \\<epsilon>\\<close> if \\<open>finite F\\<close> \\<open>\\<epsilon>>0\\<close> \\<open>n\\<ge>I \\<epsilon>\\<close> \\<open>m\\<ge>I \\<epsilon>\\<close> for \\<epsilon> n m F\n    apply (subst asm_rl[of \\<open>(\\<lambda>a. x n a - x m a) = Rep_ell2 (X n - X m)\\<close>])\n     apply (simp add: x_def minus_ell2.rep_eq)\n    using that cauchyX by (metis Rep_ell2 mem_Collect_eq normF_ell2norm norm_ell2.rep_eq order_trans)\n  have normF_xl_lim: \\<open>(\\<lambda>m. normF F (\\<lambda>a. x m a - l a)) \\<longlonglongrightarrow> 0\\<close> if \\<open>finite F\\<close> for F\n  proof -\n    have \\<open>(\\<lambda>xa. cmod (x xa m - l m)) \\<longlonglongrightarrow> 0\\<close> for m\n      using x_lim by (simp add: LIM_zero_iff tendsto_norm_zero)\n    then have \\<open>(\\<lambda>m. \\<Sum>i\\<in>F. ((cmod \\<circ> (\\<lambda>a. x m a - l a)) i)\\<^sup>2) \\<longlonglongrightarrow> 0\\<close>\n      by (auto intro: tendsto_null_sum)\n    then show ?thesis\n      unfolding normF_def L2_set_def\n      using tendsto_real_sqrt by force\n  qed\n  have normF_xl: \\<open>normF F (\\<lambda>a. x n a - l a) \\<le> \\<epsilon>\\<close>\n    if \\<open>n \\<ge> I \\<epsilon>\\<close> and \\<open>\\<epsilon> > 0\\<close> and \\<open>finite F\\<close> for n \\<epsilon> F\n  proof -\n    have \\<open>normF F (\\<lambda>a. x n a - l a) - \\<epsilon> \\<le> normF F (\\<lambda>a. x n a - x m a) + normF F (\\<lambda>a. x m a - l a) - \\<epsilon>\\<close> for m\n      using normF_triangle[OF \\<open>finite F\\<close>, where x=\\<open>(\\<lambda>a. x n a - x m a)\\<close> and y=\\<open>(\\<lambda>a. x m a - l a)\\<close>]\n      by auto\n    also have \\<open>\\<dots> m \\<le> normF F (\\<lambda>a. x m a - l a)\\<close> if \\<open>m \\<ge> I \\<epsilon>\\<close> for m\n      using normF_xx[OF \\<open>finite F\\<close> \\<open>\\<epsilon>>0\\<close> \\<open>n \\<ge> I \\<epsilon>\\<close> \\<open>m \\<ge> I \\<epsilon>\\<close>]\n      by auto\n    also have \\<open>(\\<lambda>m. \\<dots> m) \\<longlonglongrightarrow> 0\\<close>\n      using \\<open>finite F\\<close> by (rule normF_xl_lim)\n    finally show ?thesis\n      by auto\n  qed\n  have \\<open>normF F l \\<le> 1 + normF F (x (I 1))\\<close> if [simp]: \\<open>finite F\\<close> for F\n    using normF_xl[where F=F and \\<epsilon>=1 and n=\\<open>I 1\\<close>]\n    using normF_triangle[where F=F and x=\\<open>x (I 1)\\<close> and y=\\<open>\\<lambda>a. l a - x (I 1) a\\<close>]\n    using normF_negate[where F=F and x=\\<open>(\\<lambda>a. x (I 1) a - l a)\\<close>]\n    by auto\n  also have \\<open>\\<dots> F \\<le> 1 + ell2_norm (x (I 1))\\<close> if \\<open>finite F\\<close> for F\n    using normF_ell2norm that by simp\n  finally have [simp]: \\<open>has_ell2_norm l\\<close>\n    unfolding has_ell2_norm_L2_set\n    by (auto intro!: bdd_aboveI simp flip: normF_def)\n  then have \\<open>l = Rep_ell2 L\\<close>\n    by (simp add: Abs_ell2_inverse L_def)\n  have [simp]: \\<open>has_ell2_norm (\\<lambda>a. x n a - l a)\\<close> for n\n    apply (subst diff_conv_add_uminus)\n    apply (rule ell2_norm_triangle)\n    by (auto intro!: ell2_norm_uminus)\n  from normF_xl have ell2norm_xl: \\<open>ell2_norm (\\<lambda>a. x n a - l a) \\<le> \\<epsilon>\\<close>\n    if \\<open>n \\<ge> I \\<epsilon>\\<close> and \\<open>\\<epsilon> > 0\\<close> for n \\<epsilon>\n    apply (subst ell2_norm_L2_set)\n    using that by (auto intro!: cSUP_least simp: normF_def)\n  have \\<open>norm (X n - L) \\<le> \\<epsilon>\\<close> if \\<open>n \\<ge> I \\<epsilon>\\<close> and \\<open>\\<epsilon> > 0\\<close> for n \\<epsilon>\n    using ell2norm_xl[OF that]\n    by (simp add: x_def norm_ell2.rep_eq \\<open>l = Rep_ell2 L\\<close> minus_ell2.rep_eq)\n  then have \\<open>X \\<longlonglongrightarrow> L\\<close>\n    unfolding tendsto_iff\n    apply (auto simp: dist_norm eventually_sequentially)\n    by (meson field_lbound_gt_zero le_less_trans)\n  then show \\<open>convergent X\\<close>\n    by (rule convergentI)\nqed\n\ninstantiation ell2 :: (CARD_1) complex_algebra_1 \nbegin\nlift_definition one_ell2 :: \"'a ell2\" is \"\\<lambda>_. 1\" by simp\nlift_definition times_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>a b x. a x * b x\"\n  by simp   \ninstance \nproof\n  fix a b c :: \"'a ell2\" and r :: complex\n  show \"a * b * c = a * (b * c)\"\n    by (transfer, auto)\n  show \"(a + b) * c = a * c + b * c\"\n    apply (transfer, rule ext)\n    by (simp add: distrib_left mult.commute)\n  show \"a * (b + c) = a * b + a * c\"\n    apply transfer\n    by (simp add: ring_class.ring_distribs(1))\n  show \"r *\\<^sub>C a * b = r *\\<^sub>C (a * b)\"\n    by (transfer, auto)\n  show \"(a::'a ell2) * r *\\<^sub>C b = r *\\<^sub>C (a * b)\"\n    by (transfer, auto)\n  show \"1 * a = a\"\n    by (transfer, rule ext, auto)\n  show \"a * 1 = a\"\n    by (transfer, rule ext, auto)\n  show \"(0::'a ell2) \\<noteq> 1\"\n    apply transfer\n    by (meson zero_neq_one)\nqed\nend\n\ninstantiation ell2 :: (CARD_1) field begin\nlift_definition divide_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>a b x. a x / b x\"\n  by simp   \nlift_definition inverse_ell2 :: \"'a ell2 \\<Rightarrow> 'a ell2\" is \"\\<lambda>a x. inverse (a x)\"\n  by simp\ninstance\nproof (intro_classes; transfer)\n  fix a :: \"'a \\<Rightarrow> complex\"\n  assume \"a \\<noteq> (\\<lambda>_. 0)\"\n  then obtain y where ay: \"a y \\<noteq> 0\"\n    by auto\n  show \"(\\<lambda>x. inverse (a x) * a x) = (\\<lambda>_. 1)\"\n  proof (rule ext)\n    fix x\n    have \"x = y\"\n      by auto\n    with ay have \"a x \\<noteq> 0\"\n      by metis\n    then show \"inverse (a x) * a x = 1\"\n      by auto\n  qed\nqed (auto simp add: divide_complex_def mult.commute ring_class.ring_distribs)\nend\n\n\nsubsection \\<open>Orthogonality\\<close>\n\nlemma ell2_pointwise_ortho:\n  assumes \\<open>\\<And> i. Rep_ell2 x i = 0 \\<or> Rep_ell2 y i = 0\\<close>\n  shows \\<open>is_orthogonal x y\\<close>\n  using assms apply transfer\n  by (simp add: infsum_0)\n\nsubsection \\<open>Truncated vectors\\<close>\n\nlift_definition trunc_ell2:: \\<open>'a set \\<Rightarrow> 'a ell2 \\<Rightarrow> 'a ell2\\<close>\n  is \\<open>\\<lambda> S x. (\\<lambda> i. (if i \\<in> S then x i else 0))\\<close>\nproof (rename_tac S x)\n  fix x :: \\<open>'a \\<Rightarrow> complex\\<close> and S :: \\<open>'a set\\<close>\n  assume \\<open>has_ell2_norm x\\<close>\n  then have \\<open>(\\<lambda>i. (x i)\\<^sup>2) abs_summable_on UNIV\\<close>\n    unfolding has_ell2_norm_def by -\n  then have \\<open>(\\<lambda>i. (x i)\\<^sup>2) abs_summable_on S\\<close>\n    using summable_on_subset_banach by blast\n  then have \\<open>(\\<lambda>xa. (if xa \\<in> S then x xa else 0)\\<^sup>2) abs_summable_on UNIV\\<close>\n    apply (rule summable_on_cong_neutral[THEN iffD1, rotated -1])\n    by auto\n  then show \\<open>has_ell2_norm (\\<lambda>i. if i \\<in> S then x i else 0)\\<close>\n    unfolding has_ell2_norm_def by -\nqed\n\nlemma trunc_ell2_empty[simp]: \\<open>trunc_ell2 {} x = 0\\<close>\n  apply transfer by simp\n\nlemma norm_id_minus_trunc_ell2:\n  \\<open>(norm (x - trunc_ell2 S x))^2 = (norm x)^2 - (norm (trunc_ell2 S x))^2\\<close>\nproof-\n  have \\<open>Rep_ell2 (trunc_ell2 S x) i = 0 \\<or> Rep_ell2 (x - trunc_ell2 S x) i = 0\\<close> for i\n    apply transfer\n    by auto\n  hence \\<open>\\<langle> (trunc_ell2 S x), (x - trunc_ell2 S x) \\<rangle> = 0\\<close>\n    using ell2_pointwise_ortho by blast\n  hence \\<open>(norm x)^2 = (norm (trunc_ell2 S x))^2 + (norm (x - trunc_ell2 S x))^2\\<close>\n    using pythagorean_theorem by fastforce    \n  thus ?thesis by simp\nqed\n\nlemma norm_trunc_ell2_finite:\n  \\<open>finite S \\<Longrightarrow> (norm (trunc_ell2 S x)) = sqrt ((sum (\\<lambda>i. (cmod (Rep_ell2 x i))\\<^sup>2)) S)\\<close>\nproof-\n  assume \\<open>finite S\\<close>\n  moreover have \\<open>\\<And> i. i \\<notin> S \\<Longrightarrow> Rep_ell2 ((trunc_ell2 S x)) i = 0\\<close>\n    by (simp add: trunc_ell2.rep_eq)    \n  ultimately have \\<open>(norm (trunc_ell2 S x)) = sqrt ((sum (\\<lambda>i. (cmod (Rep_ell2 ((trunc_ell2 S x)) i))\\<^sup>2)) S)\\<close>\n    using ell2_norm_finite_support\n    by blast \n  moreover have \\<open>\\<And> i. i \\<in> S \\<Longrightarrow> Rep_ell2 ((trunc_ell2 S x)) i = Rep_ell2 x i\\<close>\n    by (simp add: trunc_ell2.rep_eq)\n  ultimately show ?thesis by simp\nqed\n\nlemma trunc_ell2_lim_at_UNIV:\n  \\<open>((\\<lambda>S. trunc_ell2 S \\<psi>) \\<longlongrightarrow> \\<psi>) (finite_subsets_at_top UNIV)\\<close>\nproof -\n  define f where \\<open>f i = (cmod (Rep_ell2 \\<psi> i))\\<^sup>2\\<close> for i\n\n  have has: \\<open>has_ell2_norm (Rep_ell2 \\<psi>)\\<close>\n    using Rep_ell2 by blast\n  then have summable: \"f abs_summable_on UNIV\"\n    by (smt (verit, del_insts) f_def has_ell2_norm_def norm_ge_zero norm_power real_norm_def summable_on_cong)\n\n  have \\<open>norm \\<psi> = (ell2_norm (Rep_ell2 \\<psi>))\\<close>\n    apply transfer by simp\n  also have \\<open>\\<dots> = sqrt (infsum f UNIV)\\<close>\n    by (simp add: ell2_norm_def f_def[symmetric])\n  finally have norm\\<psi>: \\<open>norm \\<psi> = sqrt (infsum f UNIV)\\<close>\n    by -\n\n  have norm_trunc: \\<open>norm (trunc_ell2 S \\<psi>) = sqrt (sum f S)\\<close> if \\<open>finite S\\<close> for S\n    using f_def that norm_trunc_ell2_finite by fastforce\n\n  have \\<open>(sum f \\<longlongrightarrow> infsum f UNIV) (finite_subsets_at_top UNIV)\\<close>\n    using f_def[abs_def] infsum_tendsto local.summable by fastforce\n  then have \\<open>((\\<lambda>S. sqrt (sum f S)) \\<longlongrightarrow> sqrt (infsum f UNIV)) (finite_subsets_at_top UNIV)\\<close>\n    using tendsto_real_sqrt by blast\n  then have \\<open>((\\<lambda>S. norm (trunc_ell2 S \\<psi>)) \\<longlongrightarrow> norm \\<psi>) (finite_subsets_at_top UNIV)\\<close>\n    apply (subst tendsto_cong[where g=\\<open>\\<lambda>S. sqrt (sum f S)\\<close>])\n    by (auto simp add: eventually_finite_subsets_at_top_weakI norm_trunc norm\\<psi>)\n  then have \\<open>((\\<lambda>S. (norm (trunc_ell2 S \\<psi>))\\<^sup>2) \\<longlongrightarrow> (norm \\<psi>)\\<^sup>2) (finite_subsets_at_top UNIV)\\<close>\n    by (simp add: tendsto_power)\n  then have \\<open>((\\<lambda>S. (norm \\<psi>)\\<^sup>2 - (norm (trunc_ell2 S \\<psi>))\\<^sup>2) \\<longlongrightarrow> 0) (finite_subsets_at_top UNIV)\\<close>\n    apply (rule tendsto_diff[where a=\\<open>(norm \\<psi>)^2\\<close> and b=\\<open>(norm \\<psi>)^2\\<close>, simplified, rotated])\n    by auto\n  then have \\<open>((\\<lambda>S. (norm (\\<psi> - trunc_ell2 S \\<psi>))\\<^sup>2) \\<longlongrightarrow> 0) (finite_subsets_at_top UNIV)\\<close>\n    unfolding norm_id_minus_trunc_ell2 by simp\n  then have \\<open>((\\<lambda>S. norm (\\<psi> - trunc_ell2 S \\<psi>)) \\<longlongrightarrow> 0) (finite_subsets_at_top UNIV)\\<close>\n    by auto\n  then have \\<open>((\\<lambda>S. \\<psi> - trunc_ell2 S \\<psi>) \\<longlongrightarrow> 0) (finite_subsets_at_top UNIV)\\<close>\n    by (rule tendsto_norm_zero_cancel)\n  then show ?thesis\n    apply (rule Lim_transform2[where f=\\<open>\\<lambda>_. \\<psi>\\<close>, rotated])\n    by simp\nqed\n\nsubsection \\<open>Kets and bras\\<close>\n\nlift_definition ket :: \"'a \\<Rightarrow> 'a ell2\" is \"\\<lambda>x y. if x=y then 1 else 0\"\n  by (rule has_ell2_norm_ket)\n\nabbreviation bra :: \"'a \\<Rightarrow> (_,complex) cblinfun\" where \"bra i \\<equiv> vector_to_cblinfun (ket i)*\" for i\n\ninstance ell2 :: (type) not_singleton\nproof standard\n  have \"ket undefined \\<noteq> (0::'a ell2)\"\n  proof transfer\n    show \"(\\<lambda>y. if (undefined::'a) = y then 1::complex else 0) \\<noteq> (\\<lambda>_. 0)\"\n      by (meson one_neq_zero)\n  qed   \n  thus \\<open>\\<exists>x y::'a ell2. x \\<noteq> y\\<close>\n    by blast    \nqed\n\nlemma cinner_ket_left: \\<open>\\<langle>ket i, \\<psi>\\<rangle> = Rep_ell2 \\<psi> i\\<close>\n  apply (transfer fixing: i)\n  apply (subst infsum_cong_neutral[where T=\\<open>{i}\\<close>])\n  by auto\n\nlemma cinner_ket_right: \\<open>\\<langle>\\<psi>, ket i\\<rangle> = cnj (Rep_ell2 \\<psi> i)\\<close>\n  apply (transfer fixing: i)\n  apply (subst infsum_cong_neutral[where T=\\<open>{i}\\<close>])\n  by auto\n\nlemma cinner_ket_eqI:\n  assumes \\<open>\\<And>i. cinner (ket i) \\<psi> = cinner (ket i) \\<phi>\\<close>\n  shows \\<open>\\<psi> = \\<phi>\\<close>\n  by (metis Rep_ell2_inject assms cinner_ket_left ext)\n\nlemma norm_ket[simp]: \"norm (ket i) = 1\"\n  apply transfer by (rule ell2_norm_ket)\n\nlemma cinner_ket_same[simp]:\n  \\<open>\\<langle>ket i, ket i\\<rangle> = 1\\<close>\nproof-\n  have \\<open>norm (ket i) = 1\\<close>\n    by simp\n  hence \\<open>sqrt (cmod \\<langle>ket i, ket i\\<rangle>) = 1\\<close>\n    by (metis norm_eq_sqrt_cinner)\n  hence \\<open>cmod \\<langle>ket i, ket i\\<rangle> = 1\\<close>\n    using real_sqrt_eq_1_iff by blast\n  moreover have \\<open>\\<langle>ket i, ket i\\<rangle> = cmod \\<langle>ket i, ket i\\<rangle>\\<close>\n  proof-\n    have \\<open>\\<langle>ket i, ket i\\<rangle> \\<in> \\<real>\\<close>\n      by (simp add: cinner_real)      \n    thus ?thesis \n      by (metis cinner_ge_zero complex_of_real_cmod) \n  qed\n  ultimately show ?thesis by simp\nqed\n\nlemma orthogonal_ket[simp]:\n  \\<open>is_orthogonal (ket i) (ket j) \\<longleftrightarrow> i \\<noteq> j\\<close>\n  by (simp add: cinner_ket_left ket.rep_eq)\n\nlemma cinner_ket: \\<open>\\<langle>ket i, ket j\\<rangle> = (if i=j then 1 else 0)\\<close>\n  by (simp add: cinner_ket_left ket.rep_eq)\n\nlemma ket_injective[simp]: \\<open>ket i = ket j \\<longleftrightarrow> i = j\\<close>\n  by (metis cinner_ket one_neq_zero)\n\nlemma inj_ket[simp]: \\<open>inj ket\\<close>\n  by (simp add: inj_on_def)\n\n\nlemma trunc_ell2_ket_cspan:\n  \\<open>trunc_ell2 S x \\<in> (cspan (range ket))\\<close> if \\<open>finite S\\<close>\nproof (use that in induction)\n  case empty\n  then show ?case \n    by (auto intro: complex_vector.span_zero)\nnext\n  case (insert a F)\n  from insert.hyps have \\<open>trunc_ell2 (insert a F) x = trunc_ell2 F x + Rep_ell2 x a *\\<^sub>C ket a\\<close>\n    apply (transfer fixing: F a)\n    by auto\n  with insert.IH\n  show ?case\n    by (simp add: complex_vector.span_add_eq complex_vector.span_base complex_vector.span_scale)\nqed\n\nlemma closed_cspan_range_ket[simp]:\n  \\<open>closure (cspan (range ket)) = UNIV\\<close>\nproof (intro set_eqI iffI UNIV_I closure_approachable[THEN iffD2] allI impI)\n  fix \\<psi> :: \\<open>'a ell2\\<close>\n  fix e :: real assume \\<open>e > 0\\<close>\n  have \\<open>((\\<lambda>S. trunc_ell2 S \\<psi>) \\<longlongrightarrow> \\<psi>) (finite_subsets_at_top UNIV)\\<close>\n    by (rule trunc_ell2_lim_at_UNIV)\n  then obtain F where \\<open>finite F\\<close> and \\<open>dist (trunc_ell2 F \\<psi>) \\<psi> < e\\<close>\n    apply (drule_tac tendstoD[OF _ \\<open>e > 0\\<close>])\n    by (auto dest: simp: eventually_finite_subsets_at_top)\n  moreover have \\<open>trunc_ell2 F \\<psi> \\<in> cspan (range ket)\\<close>\n    using \\<open>finite F\\<close> trunc_ell2_ket_cspan by blast\n  ultimately show \\<open>\\<exists>\\<phi>\\<in>cspan (range ket). dist \\<phi> \\<psi> < e\\<close>\n    by auto\nqed\n\nlemma ccspan_range_ket[simp]: \"ccspan (range ket) = (top::('a ell2 ccsubspace))\"\nproof-\n  have \\<open>closure (complex_vector.span (range ket)) = (UNIV::'a ell2 set)\\<close>\n    using Complex_L2.closed_cspan_range_ket by blast\n  thus ?thesis\n    by (simp add: ccspan.abs_eq top_ccsubspace.abs_eq)\nqed\n\nlemma cspan_range_ket_finite[simp]: \"cspan (range ket :: 'a::finite ell2 set) = UNIV\"\n  by (metis closed_cspan_range_ket closure_finite_cspan finite_class.finite_UNIV finite_imageI)\n\ninstance ell2 :: (finite) cfinite_dim\nproof\n  define basis :: \\<open>'a ell2 set\\<close> where \\<open>basis = range ket\\<close>\n  have \\<open>finite basis\\<close>\n    unfolding basis_def by simp\n  moreover have \\<open>cspan basis = UNIV\\<close>\n    by (simp add: basis_def)\n  ultimately show \\<open>\\<exists>basis::'a ell2 set. finite basis \\<and> cspan basis = UNIV\\<close>\n    by auto\nqed\n\ninstantiation ell2 :: (enum) onb_enum begin\ndefinition \"canonical_basis_ell2 = map ket Enum.enum\"\ninstance\nproof\n  show \"distinct (canonical_basis::'a ell2 list)\"\n  proof-\n    have \\<open>finite (UNIV::'a set)\\<close>\n      by simp\n    have \\<open>distinct (enum_class.enum::'a list)\\<close>\n      using enum_distinct by blast\n    moreover have \\<open>inj_on ket (set enum_class.enum)\\<close>\n      by (meson inj_onI ket_injective)         \n    ultimately show ?thesis\n      unfolding canonical_basis_ell2_def\n      using distinct_map\n      by blast\n  qed    \n\n  show \"is_ortho_set (set (canonical_basis::'a ell2 list))\"\n    apply (auto simp: canonical_basis_ell2_def enum_UNIV)\n    by (smt (z3) norm_ket f_inv_into_f is_ortho_set_def orthogonal_ket norm_zero)\n\n  show \"cindependent (set (canonical_basis::'a ell2 list))\"\n    apply (auto simp: canonical_basis_ell2_def enum_UNIV)\n    by (smt (verit, best) norm_ket f_inv_into_f is_ortho_set_def is_ortho_set_cindependent orthogonal_ket norm_zero)\n\n  show \"cspan (set (canonical_basis::'a ell2 list)) = UNIV\"\n    by (auto simp: canonical_basis_ell2_def enum_UNIV)\n\n  show \"norm (x::'a ell2) = 1\"\n    if \"(x::'a ell2) \\<in> set canonical_basis\"\n    for x :: \"'a ell2\"\n    using that unfolding canonical_basis_ell2_def \n    by auto\nqed\n\nend\n\nlemma canonical_basis_length_ell2[code_unfold, simp]:\n  \"length (canonical_basis ::'a::enum ell2 list) = CARD('a)\"\n  unfolding canonical_basis_ell2_def apply simp\n  using card_UNIV_length_enum by metis\n\nlemma ket_canonical_basis: \"ket x = canonical_basis ! enum_idx x\"\nproof-\n  have \"x = (enum_class.enum::'a list) ! enum_idx x\"\n    using enum_idx_correct[where i = x] by simp\n  hence p1: \"ket x = ket ((enum_class.enum::'a list) ! enum_idx x)\"\n    by simp\n  have \"enum_idx x < length (enum_class.enum::'a list)\"\n    using enum_idx_bound[where x = x].\n  hence \"(map ket (enum_class.enum::'a list)) ! enum_idx x \n        = ket ((enum_class.enum::'a list) ! enum_idx x)\"\n    by auto      \n  thus ?thesis\n    unfolding canonical_basis_ell2_def using p1 by auto    \nqed\n\nlemma clinear_equal_ket:\n  fixes f g :: \\<open>'a::finite ell2 \\<Rightarrow> _\\<close>\n  assumes \\<open>clinear f\\<close>\n  assumes \\<open>clinear g\\<close>\n  assumes \\<open>\\<And>i. f (ket i) = g (ket i)\\<close>\n  shows \\<open>f = g\\<close>\n  apply (rule ext)\n  apply (rule complex_vector.linear_eq_on_span[where f=f and g=g and B=\\<open>range ket\\<close>])\n  using assms by auto\n\nlemma equal_ket:\n  fixes A B :: \\<open>('a ell2, 'b::complex_normed_vector) cblinfun\\<close>\n  assumes \\<open>\\<And> x. cblinfun_apply A (ket x) = cblinfun_apply B (ket x)\\<close>\n  shows \\<open>A = B\\<close>\n  apply (rule cblinfun_eq_gen_eqI[where G=\\<open>range ket\\<close>])\n  using assms by auto\n\nlemma antilinear_equal_ket:\n  fixes f g :: \\<open>'a::finite ell2 \\<Rightarrow> _\\<close>\n  assumes \\<open>antilinear f\\<close>\n  assumes \\<open>antilinear g\\<close>\n  assumes \\<open>\\<And>i. f (ket i) = g (ket i)\\<close>\n  shows \\<open>f = g\\<close>\nproof -\n  have [simp]: \\<open>clinear (f \\<circ> from_conjugate_space)\\<close>\n    apply (rule antilinear_o_antilinear)\n    using assms by (simp_all add: antilinear_from_conjugate_space)\n  have [simp]: \\<open>clinear (g \\<circ> from_conjugate_space)\\<close>\n    apply (rule antilinear_o_antilinear)\n    using assms by (simp_all add: antilinear_from_conjugate_space)\n  have [simp]: \\<open>cspan (to_conjugate_space ` (range ket :: 'a ell2 set)) = UNIV\\<close>\n    by simp\n  have \"f o from_conjugate_space = g o from_conjugate_space\"\n    apply (rule ext)\n    apply (rule complex_vector.linear_eq_on_span[where f=\"f o from_conjugate_space\" and g=\"g o from_conjugate_space\" and B=\\<open>to_conjugate_space ` range ket\\<close>])\n       apply (simp, simp)\n    using assms(3) by (auto simp: to_conjugate_space_inverse)\n  then show \"f = g\"\n    by (smt (verit) UNIV_I from_conjugate_space_inverse surj_def surj_fun_eq to_conjugate_space_inject) \nqed\n\nlemma cinner_ket_adjointI:\n  fixes F::\"'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _\" and G::\"'b ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L_\"\n  assumes \"\\<And> i j. \\<langle>F *\\<^sub>V ket i, ket j\\<rangle> = \\<langle>ket i, G *\\<^sub>V ket j\\<rangle>\"\n  shows \"F = G*\"\nproof -\n  from assms\n  have \\<open>(F *\\<^sub>V x) \\<bullet>\\<^sub>C y = x \\<bullet>\\<^sub>C (G *\\<^sub>V y)\\<close> if \\<open>x \\<in> range ket\\<close> and \\<open>y \\<in> range ket\\<close> for x y\n    using that by auto\n  then have \\<open>(F *\\<^sub>V x) \\<bullet>\\<^sub>C y = x \\<bullet>\\<^sub>C (G *\\<^sub>V y)\\<close> if \\<open>x \\<in> range ket\\<close> for x y\n    apply (rule bounded_clinear_eq_on[where G=\\<open>range ket\\<close> and t=y, rotated 2])\n    using that by (auto intro!: bounded_linear_intros)\n  then have \\<open>(F *\\<^sub>V x) \\<bullet>\\<^sub>C y = x \\<bullet>\\<^sub>C (G *\\<^sub>V y)\\<close> for x y\n    apply (rule bounded_antilinear_eq_on[where G=\\<open>range ket\\<close> and t=x, rotated 2])\n    by (auto intro!: bounded_linear_intros)\n  then show ?thesis\n    by (rule adjoint_eqI)\nqed\n\nlemma ket_nonzero[simp]: \"ket i \\<noteq> 0\"\n  using norm_ket[of i] by force\n\n\nlemma cindependent_ket:\n  \"cindependent (range (ket::'a\\<Rightarrow>_))\"\nproof-\n  define S where \"S = range (ket::'a\\<Rightarrow>_)\"\n  have \"is_ortho_set S\"\n    unfolding S_def is_ortho_set_def by auto\n  moreover have \"0 \\<notin> S\"\n    unfolding S_def\n    using ket_nonzero\n    by (simp add: image_iff)\n  ultimately show ?thesis\n    using is_ortho_set_cindependent[where A = S] unfolding S_def \n    by blast\nqed\n\nlemma cdim_UNIV_ell2[simp]: \\<open>cdim (UNIV::'a::finite ell2 set) = CARD('a)\\<close>\n  apply (subst cspan_range_ket_finite[symmetric])\n  by (metis card_image cindependent_ket complex_vector.dim_span_eq_card_independent inj_ket)\n\nlemma is_ortho_set_ket[simp]: \\<open>is_ortho_set (range ket)\\<close>\n  using is_ortho_set_def by fastforce\n\nsubsection \\<open>Butterflies\\<close>\n\nlemma cspan_butterfly_ket: \\<open>cspan {butterfly (ket i) (ket j)| (i::'b::finite) (j::'a::finite). True} = UNIV\\<close>\nproof -\n  have *: \\<open>{butterfly (ket i) (ket j)| (i::'b::finite) (j::'a::finite). True} = {butterfly a b |a b. a \\<in> range ket \\<and> b \\<in> range ket}\\<close>\n    by auto\n  show ?thesis\n    apply (subst *)\n    apply (rule cspan_butterfly_UNIV)\n    by auto\nqed\n\nlemma cindependent_butterfly_ket: \\<open>cindependent {butterfly (ket i) (ket j)| (i::'b) (j::'a). True}\\<close>\nproof -\n  have *: \\<open>{butterfly (ket i) (ket j)| (i::'b) (j::'a). True} = {butterfly a b |a b. a \\<in> range ket \\<and> b \\<in> range ket}\\<close>\n    by auto\n  show ?thesis\n    apply (subst *)\n    apply (rule cindependent_butterfly)\n    by auto\nqed\n\nlemma clinear_eq_butterfly_ketI:\n  fixes F G :: \\<open>('a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::finite ell2) \\<Rightarrow> 'c::complex_vector\\<close>\n  assumes \"clinear F\" and \"clinear G\"\n  assumes \"\\<And>i j. F (butterfly (ket i) (ket j)) = G (butterfly (ket i) (ket j))\"\n  shows \"F = G\"\n  apply (rule complex_vector.linear_eq_on_span[where f=F, THEN ext, rotated 3])\n     apply (subst cspan_butterfly_ket)\n  using assms by auto\n\nlemma sum_butterfly_ket[simp]: \\<open>(\\<Sum>(i::'a::finite)\\<in>UNIV. butterfly (ket i) (ket i)) = id_cblinfun\\<close>\n  apply (rule equal_ket)\n  apply (subst complex_vector.linear_sum[where f=\\<open>\\<lambda>y. y *\\<^sub>V ket _\\<close>])\n   apply (auto simp add: scaleC_cblinfun.rep_eq cblinfun.add_left clinearI butterfly_def cblinfun_compose_image cinner_ket)\n  apply (subst sum.mono_neutral_cong_right[where S=\\<open>{_}\\<close>])\n  by auto\n\nsubsection \\<open>One-dimensional spaces\\<close>\n\ninstantiation ell2 :: (\"{enum,CARD_1}\") one_dim begin\ntext \\<open>Note: enum is not needed logically, but without it this instantiation\n            clashes with \\<open>instantiation ell2 :: (enum) onb_enum\\<close>\\<close>\ninstance\nproof\n  show \"canonical_basis = [1::'a ell2]\"\n    unfolding canonical_basis_ell2_def\n    apply transfer\n    by (simp add: enum_CARD_1[of undefined])\n  show \"a *\\<^sub>C 1 * b *\\<^sub>C 1 = (a * b) *\\<^sub>C (1::'a ell2)\" for a b\n    apply (transfer fixing: a b) by simp\n  show \"x / y = x * inverse y\" for x y :: \"'a ell2\"\n    by (simp add: divide_inverse)\n  show \"inverse (c *\\<^sub>C 1) = inverse c *\\<^sub>C (1::'a ell2)\" for c :: complex\n    apply transfer by auto\nqed\nend\n\n\nsubsection \\<open>Classical operators\\<close>\n\ntext \\<open>We call an operator mapping \\<^term>\\<open>ket x\\<close> to \\<^term>\\<open>ket (\\<pi> x)\\<close> or \\<^term>\\<open>0\\<close> \"classical\".\n(The meaning is inspired by the fact that in quantum mechanics, such operators usually correspond\nto operations with classical interpretation (such as Pauli-X, CNOT, measurement in the computational\nbasis, etc.))\\<close>\n\ndefinition classical_operator :: \"('a\\<Rightarrow>'b option) \\<Rightarrow> 'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L'b ell2\" where\n  \"classical_operator \\<pi> = \n    (let f = (\\<lambda>t. (case \\<pi> (inv (ket::'a\\<Rightarrow>_) t) \n                           of None \\<Rightarrow> (0::'b ell2) \n                          | Some i \\<Rightarrow> ket i))\n     in\n      cblinfun_extension (range (ket::'a\\<Rightarrow>_)) f)\"\n\n\ndefinition \"classical_operator_exists \\<pi> \\<longleftrightarrow>\n  cblinfun_extension_exists (range ket)\n    (\\<lambda>t. case \\<pi> (inv ket t) of None \\<Rightarrow> 0 | Some i \\<Rightarrow> ket i)\"\n\nlemma classical_operator_existsI:\n  assumes \"\\<And>x. B *\\<^sub>V (ket x) = (case \\<pi> x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\"\n  shows \"classical_operator_exists \\<pi>\"\n  unfolding classical_operator_exists_def\n  apply (rule cblinfun_extension_existsI[of _ B])\n  using assms \n  by (auto simp: inv_f_f[OF inj_ket])\n\nlemma classical_operator_exists_inj:\n  assumes \"inj_map \\<pi>\"\n  shows \"classical_operator_exists \\<pi>\"\nproof -\n  define f where \\<open>f t = (case \\<pi> (inv ket t) of None \\<Rightarrow> 0 | Some x \\<Rightarrow> ket x)\\<close> for t\n  define g where \\<open>g = cconstruct (range ket) f\\<close>\n  have g_f: \\<open>g (ket x) = f (ket x)\\<close> for x\n    unfolding g_def apply (rule complex_vector.construct_basis)\n    using cindependent_ket by auto\n  have \\<open>clinear g\\<close>\n    unfolding g_def apply (rule complex_vector.linear_construct)\n    using cindependent_ket by blast\n  then have \\<open>g (x + y) = g x + g y\\<close> if \\<open>x \\<in> cspan (range ket)\\<close> and \\<open>y \\<in> cspan (range ket)\\<close> for x y\n    using clinear_iff by blast\n  moreover from \\<open>clinear g\\<close> have \\<open>g (c *\\<^sub>C x) = c *\\<^sub>C g x\\<close> if \\<open>x \\<in> cspan (range ket)\\<close> for x c\n    by (simp add: complex_vector.linear_scale)\n  moreover have \\<open>norm (g x) \\<le> norm x\\<close> if \\<open>x \\<in> cspan (range ket)\\<close> for x\n  proof -\n    from that obtain t r where x_sum: \\<open>x = (\\<Sum>a\\<in>t. r a *\\<^sub>C a)\\<close> and \\<open>finite t\\<close> and \\<open>t \\<subseteq> range ket\\<close>\n      unfolding complex_vector.span_explicit by auto\n    then obtain T where tT: \\<open>t = ket ` T\\<close> and [simp]: \\<open>finite T\\<close>\n      by (meson finite_subset_image)\n    define R where \\<open>R i = r (ket i)\\<close> for i\n    have x_sum: \\<open>x = (\\<Sum>i\\<in>T. R i *\\<^sub>C ket i)\\<close>\n      unfolding R_def tT x_sum\n      apply (rule sum.reindex_cong)\n      by (auto simp add: inj_on_def)\n\n    define T' \\<pi>' \\<pi>T \\<pi>R where \\<open>T' = {i\\<in>T. \\<pi> i \\<noteq> None}\\<close> and \\<open>\\<pi>' = the o \\<pi>\\<close> and \\<open>\\<pi>T = \\<pi>' ` T'\\<close> and \\<open>\\<pi>R i = R (inv_into T' \\<pi>' i)\\<close> for i\n    have \\<open>inj_on \\<pi>' T'\\<close>\n      by (smt (z3) T'_def \\<pi>'_def assms comp_apply inj_map_def inj_on_def mem_Collect_eq option.expand)\n    have [simp]: \\<open>finite \\<pi>T\\<close>\n      by (simp add: T'_def \\<pi>T_def)\n\n    have \\<open>g x = (\\<Sum>i\\<in>T. R i *\\<^sub>C g (ket i))\\<close>\n      by (smt (verit, ccfv_threshold) \\<open>clinear g\\<close> complex_vector.linear_scale complex_vector.linear_sum sum.cong x_sum)\n    also have \\<open>\\<dots> = (\\<Sum>i\\<in>T. R i *\\<^sub>C f (ket i))\\<close>\n      using g_f by presburger\n    also have \\<open>\\<dots> = (\\<Sum>i\\<in>T. R i *\\<^sub>C (case \\<pi> i of None \\<Rightarrow> 0 | Some x \\<Rightarrow> ket x))\\<close>\n      unfolding f_def by auto\n    also have \\<open>\\<dots> = (\\<Sum>i\\<in>T'. R i *\\<^sub>C ket (\\<pi>' i))\\<close>\n      apply (rule sum.mono_neutral_cong_right)\n      unfolding T'_def \\<pi>'_def\n      by auto\n    also have \\<open>\\<dots> = (\\<Sum>i\\<in>\\<pi>' ` T'. R (inv_into T' \\<pi>' i) *\\<^sub>C ket i)\\<close>\n      apply (subst sum.reindex)\n      using \\<open>inj_on \\<pi>' T'\\<close> apply assumption\n      apply (rule sum.cong)\n      using \\<open>inj_on \\<pi>' T'\\<close> by auto\n    finally have gx_sum: \\<open>g x = (\\<Sum>i\\<in>\\<pi>T. \\<pi>R i *\\<^sub>C ket i)\\<close>\n      using \\<pi>R_def \\<pi>T_def by auto\n\n    have \\<open>(norm (g x))\\<^sup>2 = (\\<Sum>a\\<in>\\<pi>T. (cmod (\\<pi>R a))\\<^sup>2)\\<close>\n      unfolding gx_sum \n      apply (subst pythagorean_theorem_sum)\n      by auto\n    also have \\<open>\\<dots> = (\\<Sum>i\\<in>T'. (cmod (R i))\\<^sup>2)\\<close>\n      unfolding \\<pi>R_def \\<pi>T_def\n      apply (subst sum.reindex)\n      using \\<open>inj_on \\<pi>' T'\\<close> apply assumption\n      apply (rule sum.cong)\n      using \\<open>inj_on \\<pi>' T'\\<close> by auto\n    also have \\<open>\\<dots> \\<le> (\\<Sum>a\\<in>T. (cmod (R a))\\<^sup>2)\\<close>\n      apply (rule sum_mono2)\n      using T'_def by auto\n    also have \\<open>\\<dots> = (norm x)\\<^sup>2\\<close>\n      unfolding x_sum \n      apply (subst pythagorean_theorem_sum)\n      using \\<open>finite T\\<close> by auto\n    finally show \\<open>norm (g x) \\<le> norm x\\<close>\n      by auto\n  qed\n  ultimately have \\<open>cblinfun_extension_exists (cspan (range ket)) g\\<close>\n    apply (rule_tac cblinfun_extension_exists_bounded_dense[where B=1])\n    by auto\n\n  then have \\<open>cblinfun_extension_exists (range ket) f\\<close>\n    by (metis (mono_tags, opaque_lifting) g_f cblinfun_extension_apply cblinfun_extension_existsI complex_vector.span_base rangeE)\n  then show \\<open>classical_operator_exists \\<pi>\\<close>\n    unfolding classical_operator_exists_def f_def by simp\nqed\n\nlemma classical_operator_exists_finite[simp]: \"classical_operator_exists (\\<pi> :: _::finite \\<Rightarrow> _)\"\n  unfolding classical_operator_exists_def\n  apply (rule cblinfun_extension_exists_finite_dim)\n  using cindependent_ket apply blast\n  using finite_class.finite_UNIV finite_imageI closed_cspan_range_ket closure_finite_cspan by blast\n\nlemma classical_operator_ket:\n  assumes \"classical_operator_exists \\<pi>\"\n  shows \"(classical_operator \\<pi>) *\\<^sub>V (ket x) = (case \\<pi> x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\"\n  unfolding classical_operator_def \n  using f_inv_into_f ket_injective rangeI\n  by (metis assms cblinfun_extension_apply classical_operator_exists_def)\n\nlemma classical_operator_ket_finite:\n  \"(classical_operator \\<pi>) *\\<^sub>V (ket (x::'a::finite)) = (case \\<pi> x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\"\n  by (rule classical_operator_ket, simp)\n\nlemma classical_operator_adjoint[simp]:\n  fixes \\<pi> :: \"'a \\<Rightarrow> 'b option\"\n  assumes a1: \"inj_map \\<pi>\"\n  shows  \"(classical_operator \\<pi>)* = classical_operator (inv_map \\<pi>)\"\nproof-\n  define F where \"F = classical_operator (inv_map \\<pi>)\"\n  define G where \"G = classical_operator \\<pi>\"\n  have \"\\<langle>F *\\<^sub>V ket i, ket j\\<rangle> = \\<langle>ket i, G *\\<^sub>V ket j\\<rangle>\" for i j\n  proof-\n    have w1: \"(classical_operator (inv_map \\<pi>)) *\\<^sub>V (ket i)\n     = (case inv_map \\<pi> i of Some k \\<Rightarrow> ket k | None \\<Rightarrow> 0)\"\n      by (simp add: classical_operator_ket classical_operator_exists_inj)\n    have w2: \"(classical_operator \\<pi>) *\\<^sub>V (ket j)\n     = (case \\<pi> j of Some k \\<Rightarrow> ket k | None \\<Rightarrow> 0)\"\n      by (simp add: assms classical_operator_ket classical_operator_exists_inj)\n    have \"\\<langle>F *\\<^sub>V ket i, ket j\\<rangle> = \\<langle>classical_operator (inv_map \\<pi>) *\\<^sub>V ket i, ket j\\<rangle>\"\n      unfolding F_def by blast\n    also have \"\\<dots> = \\<langle>(case inv_map \\<pi> i of Some k \\<Rightarrow> ket k | None \\<Rightarrow> 0), ket j\\<rangle>\"\n      using w1 by simp\n    also have \"\\<dots> = \\<langle>ket i, (case \\<pi> j of Some k \\<Rightarrow> ket k | None \\<Rightarrow> 0)\\<rangle>\"\n    proof(induction \"inv_map \\<pi> i\")\n      case None\n      hence pi1: \"None = inv_map \\<pi> i\".\n      show ?case \n      proof (induction \"\\<pi> j\")\n        case None\n        thus ?case\n          using pi1 by auto\n      next\n        case (Some c)\n        have \"c \\<noteq> i\"\n        proof(rule classical)\n          assume \"\\<not>(c \\<noteq> i)\"\n          hence \"c = i\"\n            by blast\n          hence \"inv_map \\<pi> c = inv_map \\<pi> i\"\n            by simp\n          hence \"inv_map \\<pi> c = None\"\n            by (simp add: pi1)\n          moreover have \"inv_map \\<pi> c = Some j\"\n            using Some.hyps unfolding inv_map_def\n            apply auto\n            by (metis a1 f_inv_into_f inj_map_def option.distinct(1) rangeI)\n          ultimately show ?thesis by simp\n        qed\n        thus ?thesis\n          by (metis None.hyps Some.hyps cinner_zero_left orthogonal_ket option.simps(4) \n              option.simps(5)) \n      qed       \n    next\n      case (Some d)\n      hence s1: \"Some d = inv_map \\<pi> i\".\n      show \"\\<langle>case inv_map \\<pi> i of \n            None \\<Rightarrow> 0\n        | Some a \\<Rightarrow> ket a, ket j\\<rangle> =\n       \\<langle>ket i, case \\<pi> j of \n            None \\<Rightarrow> 0 \n        | Some a \\<Rightarrow> ket a\\<rangle>\" \n      proof(induction \"\\<pi> j\")\n        case None\n        have \"d \\<noteq> j\"\n        proof(rule classical)\n          assume \"\\<not>(d \\<noteq> j)\"\n          hence \"d = j\"\n            by blast\n          hence \"\\<pi> d = \\<pi> j\"\n            by simp\n          hence \"\\<pi> d = None\"\n            by (simp add: None.hyps)\n          moreover have \"\\<pi> d = Some i\"\n            using Some.hyps unfolding inv_map_def\n            apply auto\n            by (metis f_inv_into_f option.distinct(1) option.inject)\n          ultimately show ?thesis \n            by simp\n        qed\n        thus ?case\n          by (metis None.hyps Some.hyps cinner_zero_right orthogonal_ket option.case_eq_if \n              option.simps(5)) \n      next\n        case (Some c)\n        hence s2: \"\\<pi> j = Some c\" by simp\n        have \"\\<langle>ket d, ket j\\<rangle> = \\<langle>ket i, ket c\\<rangle>\"\n        proof(cases \"\\<pi> j = Some i\")\n          case True\n          hence ij: \"Some j = inv_map \\<pi> i\"\n            unfolding inv_map_def apply auto\n             apply (metis a1 f_inv_into_f inj_map_def option.discI range_eqI)\n            by (metis range_eqI)\n          have \"i = c\"\n            using True s2 by auto\n          moreover have \"j = d\"\n            by (metis option.inject s1 ij)\n          ultimately show ?thesis\n            by (simp add: cinner_ket_same) \n        next\n          case False\n          moreover have \"\\<pi> d = Some i\"\n            using s1 unfolding inv_map_def\n            by (metis f_inv_into_f option.distinct(1) option.inject)            \n          ultimately have \"j \\<noteq> d\"\n            by auto            \n          moreover have \"i \\<noteq> c\"\n            using False s2 by auto            \n          ultimately show ?thesis\n            by (metis orthogonal_ket) \n        qed\n        hence \"\\<langle>case Some d of None \\<Rightarrow> 0\n        | Some a \\<Rightarrow> ket a, ket j\\<rangle> =\n       \\<langle>ket i, case Some c of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a\\<rangle>\"\n          by simp          \n        thus \"\\<langle>case inv_map \\<pi> i of None \\<Rightarrow> 0\n        | Some a \\<Rightarrow> ket a, ket j\\<rangle> =\n       \\<langle>ket i, case \\<pi> j of None \\<Rightarrow> 0 | Some a \\<Rightarrow> ket a\\<rangle>\"\n          by (simp add: Some.hyps s1)          \n      qed\n    qed\n    also have \"\\<dots> = \\<langle>ket i, classical_operator \\<pi> *\\<^sub>V ket j\\<rangle>\"\n      by (simp add: w2)\n    also have \"\\<dots> = \\<langle>ket i, G *\\<^sub>V ket j\\<rangle>\"\n      unfolding G_def by blast\n    finally show ?thesis .\n  qed\n  hence \"G* = F\"\n    using cinner_ket_adjointI\n    by auto\n  thus ?thesis unfolding G_def F_def .\nqed\n\nlemma\n  fixes \\<pi>::\"'b \\<Rightarrow> 'c option\" and \\<rho>::\"'a \\<Rightarrow> 'b option\"\n  assumes \"classical_operator_exists \\<pi>\"\n  assumes \"classical_operator_exists \\<rho>\"\n  shows classical_operator_exists_comp[simp]: \"classical_operator_exists (\\<pi> \\<circ>\\<^sub>m \\<rho>)\"\n    and classical_operator_mult[simp]: \"classical_operator \\<pi> o\\<^sub>C\\<^sub>L classical_operator \\<rho> = classical_operator (\\<pi> \\<circ>\\<^sub>m \\<rho>)\"\nproof -\n  define C\\<pi> C\\<rho> C\\<pi>\\<rho> where \"C\\<pi> = classical_operator \\<pi>\" and \"C\\<rho> = classical_operator \\<rho>\" \n    and \"C\\<pi>\\<rho> = classical_operator (\\<pi> \\<circ>\\<^sub>m \\<rho>)\"\n  have C\\<pi>x: \"C\\<pi> *\\<^sub>V (ket x) = (case \\<pi> x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\" for x\n    unfolding C\\<pi>_def using \\<open>classical_operator_exists \\<pi>\\<close> by (rule classical_operator_ket)\n  have C\\<rho>x: \"C\\<rho> *\\<^sub>V (ket x) = (case \\<rho> x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\" for x\n    unfolding C\\<rho>_def using \\<open>classical_operator_exists \\<rho>\\<close> by (rule classical_operator_ket)\n  have C\\<pi>\\<rho>x': \"(C\\<pi> o\\<^sub>C\\<^sub>L C\\<rho>) *\\<^sub>V (ket x) = (case (\\<pi> \\<circ>\\<^sub>m \\<rho>) x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\" for x\n    apply (simp add: scaleC_cblinfun.rep_eq C\\<rho>x)\n    apply (cases \"\\<rho> x\")\n    by (auto simp: C\\<pi>x)\n  thus \\<open>classical_operator_exists (\\<pi> \\<circ>\\<^sub>m \\<rho>)\\<close>\n    by (rule classical_operator_existsI)\n  hence \"C\\<pi>\\<rho> *\\<^sub>V (ket x) = (case (\\<pi> \\<circ>\\<^sub>m \\<rho>) x of Some i \\<Rightarrow> ket i | None \\<Rightarrow> 0)\" for x\n    unfolding C\\<pi>\\<rho>_def\n    by (rule classical_operator_ket)\n  with C\\<pi>\\<rho>x' have \"(C\\<pi> o\\<^sub>C\\<^sub>L C\\<rho>) *\\<^sub>V (ket x) = C\\<pi>\\<rho> *\\<^sub>V (ket x)\" for x\n    by simp\n  thus \"C\\<pi> o\\<^sub>C\\<^sub>L C\\<rho> = C\\<pi>\\<rho>\"\n    by (simp add: equal_ket)\nqed\n\nlemma classical_operator_Some[simp]: \"classical_operator (Some::'a\\<Rightarrow>_) = id_cblinfun\"\nproof-\n  have \"(classical_operator Some) *\\<^sub>V (ket i)  = id_cblinfun *\\<^sub>V (ket i)\"\n    for i::'a\n    apply (subst classical_operator_ket)\n     apply (rule classical_operator_exists_inj)\n    by auto\n  thus ?thesis\n    using equal_ket[where A = \"classical_operator (Some::'a \\<Rightarrow> _ option)\"\n        and B = \"id_cblinfun::'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _\"]\n    by blast\nqed\n\nlemma isometry_classical_operator[simp]:\n  fixes \\<pi>::\"'a \\<Rightarrow> 'b\"\n  assumes a1: \"inj \\<pi>\"\n  shows \"isometry (classical_operator (Some o \\<pi>))\"\nproof -\n  have b0: \"inj_map (Some \\<circ> \\<pi>)\"\n    by (simp add: a1)\n  have b0': \"inj_map (inv_map (Some \\<circ> \\<pi>))\"\n    by simp\n  have b1: \"inv_map (Some \\<circ> \\<pi>) \\<circ>\\<^sub>m (Some \\<circ> \\<pi>) = Some\" \n    apply (rule ext) unfolding inv_map_def o_def \n    using assms unfolding inj_def inv_def by auto\n  have b3: \"classical_operator (inv_map (Some \\<circ> \\<pi>)) o\\<^sub>C\\<^sub>L\n            classical_operator (Some \\<circ> \\<pi>) = classical_operator (inv_map (Some \\<circ> \\<pi>) \\<circ>\\<^sub>m (Some \\<circ> \\<pi>))\"\n    by (metis b0 b0' b1 classical_operator_Some classical_operator_exists_inj \n        classical_operator_mult)\n  show ?thesis\n    unfolding isometry_def\n    apply (subst classical_operator_adjoint)\n    using b0 by (auto simp add: b1 b3)\nqed\n\nlemma unitary_classical_operator[simp]:\n  fixes \\<pi>::\"'a \\<Rightarrow> 'b\"\n  assumes a1: \"bij \\<pi>\"\n  shows \"unitary (classical_operator (Some o \\<pi>))\"\nproof (unfold unitary_def, rule conjI)\n  have \"inj \\<pi>\"\n    using a1 bij_betw_imp_inj_on by auto\n  hence \"isometry (classical_operator (Some o \\<pi>))\"\n    by simp\n  hence \"classical_operator (Some \\<circ> \\<pi>)* o\\<^sub>C\\<^sub>L classical_operator (Some \\<circ> \\<pi>) = id_cblinfun\"\n    unfolding isometry_def by simp\n  thus \\<open>classical_operator (Some \\<circ> \\<pi>)* o\\<^sub>C\\<^sub>L classical_operator (Some \\<circ> \\<pi>) = id_cblinfun\\<close>\n    by simp \nnext\n  have \"inj \\<pi>\"\n    by (simp add: assms bij_is_inj)\n  have comp: \"Some \\<circ> \\<pi> \\<circ>\\<^sub>m inv_map (Some \\<circ> \\<pi>) = Some\"\n    apply (rule ext)\n    unfolding inv_map_def o_def map_comp_def\n    unfolding inv_def apply auto\n     apply (metis \\<open>inj \\<pi>\\<close> inv_def inv_f_f)\n    using bij_def image_iff range_eqI\n    by (metis a1)\n  have \"classical_operator (Some \\<circ> \\<pi>) o\\<^sub>C\\<^sub>L classical_operator (Some \\<circ> \\<pi>)*\n      = classical_operator (Some \\<circ> \\<pi>) o\\<^sub>C\\<^sub>L classical_operator (inv_map (Some \\<circ> \\<pi>))\"\n    by (simp add: \\<open>inj \\<pi>\\<close>)\n  also have \"\\<dots> = classical_operator ((Some \\<circ> \\<pi>) \\<circ>\\<^sub>m (inv_map (Some \\<circ> \\<pi>)))\"\n    by (simp add: \\<open>inj \\<pi>\\<close> classical_operator_exists_inj)\n  also have \"\\<dots> = classical_operator (Some::'b\\<Rightarrow>_)\"\n    using comp\n    by simp \n  also have \"\\<dots> = (id_cblinfun:: 'b ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _)\"\n    by simp\n  finally show \"classical_operator (Some \\<circ> \\<pi>) o\\<^sub>C\\<^sub>L classical_operator (Some \\<circ> \\<pi>)* = id_cblinfun\".\nqed\n\n\n\nunbundle no_cblinfun_notation\n\nend\n", "meta": {"author": "dominique-unruh", "repo": "bounded-operators", "sha": "a6e1e85d207f6cd2d8ef043672c45fa4755f05aa", "save_path": "github-repos/isabelle/dominique-unruh-bounded-operators", "path": "github-repos/isabelle/dominique-unruh-bounded-operators/bounded-operators-a6e1e85d207f6cd2d8ef043672c45fa4755f05aa/Complex_L2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7728790015430653}}
{"text": "(*  Title:      InfiniteSet2.thy\n    Date:       Aug 2008\n    Author:     David Trachtenherz\n*)\n\nheader {* Set operations with results of type enat *}\n\ntheory InfiniteSet2\nimports SetInterval2\nbegin\n\nsubsection {* Set operations with @{typ enat} *} \n\nsubsubsection {* Basic definitions *}\n\ndefinition\n  icard :: \"'a set \\<Rightarrow> enat\"\nwhere\n  \"icard A \\<equiv> if finite A then enat (card A) else \\<infinity>\"\n\nsubsection {* Results for @{text icard} *}\n\nlemma icard_UNIV_nat: \"icard (UNIV::nat set) = \\<infinity>\"\nby (simp add: icard_def)\n\nlemma icard_finite_conv: \"(icard A = enat (card A)) = finite A\"\nby (case_tac \"finite A\", simp_all add: icard_def)\nlemma icard_infinite_conv: \"(icard A = \\<infinity>) = infinite A\"\nby (case_tac \"finite A\", simp_all add: icard_def)\n\ncorollary icard_finite: \"finite A \\<Longrightarrow> icard A = enat (card A)\"\nby (rule icard_finite_conv[THEN iffD2])\ncorollary icard_infinite[simp]: \"infinite A \\<Longrightarrow> icard A = \\<infinity>\"\nby (rule icard_infinite_conv[THEN iffD2])\n\nlemma icard_eq_enat_imp: \"icard A = enat n \\<Longrightarrow> finite A\"\nby (case_tac \"finite A\", simp_all)\nlemma icard_eq_Infty_imp: \"icard A = \\<infinity> \\<Longrightarrow> infinite A\"\nby (rule icard_infinite_conv[THEN iffD1])\n\nlemma icard_the_enat: \"finite A \\<Longrightarrow> the_enat (icard A) = card A\"\nby (simp add: icard_def)\n\nlemma icard_eq_enat_imp_card: \"icard A = enat n \\<Longrightarrow> card A = n\"\nby (frule icard_eq_enat_imp, simp add: icard_finite)\n\nlemma icard_eq_enat_card_conv: \"0 < n \\<Longrightarrow> (icard A = enat n) = (card A = n)\"\napply (rule iffI)\n apply (simp add: icard_eq_enat_imp_card)\napply (drule sym, simp)\napply (frule card_gr0_imp_finite)\napply (rule icard_finite, assumption)\ndone\n\nlemma icard_empty[simp]: \"icard {} = 0\"\nby (simp add: icard_finite[OF finite.emptyI])\nlemma icard_empty_iff: \"(icard A = 0) = (A = {})\"\napply (unfold zero_enat_def)\napply (rule iffI)\n apply (frule icard_eq_enat_imp)\n apply (simp add: icard_finite)\napply simp\ndone\nlemmas icard_empty_iff_enat = icard_empty_iff[unfolded zero_enat_def]\n\nlemma icard_not_empty_iff: \"(0 < icard A) = (A \\<noteq> {})\"\nby (simp add: icard_empty_iff[symmetric])\nlemmas icard_not_empty_iff_enat = icard_not_empty_iff[unfolded zero_enat_def]\n\nlemma icard_singleton: \"icard {a} = eSuc 0\"\nby (simp add: icard_finite eSuc_enat)\nlemmas icard_singleton_enat[simp] = icard_singleton[unfolded zero_enat_def]\n\n\n\n\nthm Finite_Set.card_insert_disjoint\nlemma icard_insert_disjoint: \"x \\<notin> A \\<Longrightarrow> icard (insert x A) = eSuc (icard A)\"\napply (case_tac \"finite A\")\n apply (simp add: icard_finite eSuc_enat card_insert_disjoint)\napply (simp add: infinite_insert)\ndone\nthm Finite_Set.card_insert_if\nlemma icard_insert_if: \"icard (insert x A) = (if x \\<in> A then icard A else eSuc (icard A))\"\napply (case_tac \"x \\<in> A\")\n apply (simp add: insert_absorb)\napply (simp add: icard_insert_disjoint)\ndone\nthm Finite_Set.card_0_eq\nlemmas icard_0_eq = icard_empty_iff\n\nthm Finite_Set.card_Suc_Diff1\nlemma icard_Suc_Diff1: \"x \\<in> A \\<Longrightarrow> eSuc (icard (A - {x})) = icard A\"\napply (case_tac \"finite A\")\n apply (simp add: icard_finite eSuc_enat in_imp_not_empty not_empty_card_gr0_conv[THEN iffD1])\napply (simp add: Diff_infinite_finite[OF singleton_finite])\ndone\n\nthm Finite_Set.card_Diff_singleton\nlemma icard_Diff_singleton: \"x \\<in> A \\<Longrightarrow> icard (A - {x}) = icard A - 1\"\napply (rule eSuc_inject[THEN iffD1])\napply (frule in_imp_not_empty, drule icard_not_empty_iff[THEN iffD2])\napply (simp add: icard_Suc_Diff1 eSuc_pred_enat one_eSuc)\ndone\n\nthm Finite_Set.card_Diff_singleton_if\nlemma icard_Diff_singleton_if: \"icard (A - {x}) = (if x \\<in> A then icard A - 1 else icard A)\"\nby (simp add: icard_Diff_singleton)\n\nthm Finite_Set.card_insert\nlemma icard_insert: \"icard (insert x A) = eSuc (icard (A - {x}))\"\nby (metis icard_Diff_singleton_if icard_Suc_Diff1 icard_insert_disjoint insert_absorb)\n\nthm Finite_Set.card_insert_le\nlemma icard_insert_le: \"icard A \\<le> icard (insert x A)\"\nby (simp add: icard_insert_if)\n\nthm Finite_Set.card_mono\nlemma icard_mono: \"A \\<subseteq> B \\<Longrightarrow> icard A \\<le> icard B\"\napply (case_tac \"finite B\")\n apply (frule subset_finite_imp_finite, simp)\n apply (simp add: icard_finite card_mono)\napply simp\ndone\n\nthm Finite_Set.card_seteq\nlemma not_icard_seteq: \"\\<exists>(A::nat set) B. (A \\<subseteq> B \\<and> icard B \\<le> icard A \\<and> \\<not> A = B)\"\napply (rule_tac x=\"{1..}\" in exI)\napply (rule_tac x=\"{0..}\" in exI)\napply (fastforce simp add: infinite_atLeast)\ndone\n\nthm Finite_Set.psubset_card_mono\nlemma not_psubset_icard_mono: \"\\<exists>(A::nat set) B. A \\<subset> B \\<and> \\<not> icard A < icard B\"\napply (rule_tac x=\"{1..}\" in exI)\napply (rule_tac x=\"{0..}\" in exI)\napply (fastforce simp add: infinite_atLeast)\ndone\n\nthm Finite_Set.card_Un_Int\nlemma icard_Un_Int: \"icard A + icard B = icard (A \\<union> B) + icard (A \\<inter> B)\"\napply (case_tac \"finite A\", case_tac \"finite B\")\n thm card_Un_Int\n apply (simp add: icard_finite card_Un_Int[of A])\napply simp_all\ndone\n\nthm Finite_Set.card_Un_disjoint\nlemma icard_Un_disjoint: \"A \\<inter> B = {} \\<Longrightarrow> icard (A \\<union> B) = icard A + icard B\"\nby (simp add: icard_Un_Int[of A])\n\nthm Finite_Set.card_Diff_subset\nlemma not_icard_Diff_subset: \"\\<exists>(A::nat set) B. B \\<subseteq> A \\<and> \\<not> icard (A - B) = icard A - icard B\"\napply (rule_tac x=\"{0..}\" in exI)\napply (rule_tac x=\"{1..}\" in exI)\napply (simp add: set_diff_eq linorder_not_le icard_UNIV_nat eSuc_enat)\ndone\n\n\nthm \n  Finite_Set.card_Diff1_less\n  Finite_Set.card_Diff2_less\nlemma not_icard_Diff1_less: \"\\<exists>(A::nat set)x. x \\<in> A \\<and> \\<not> icard (A - {x}) < icard A\"\nby (rule_tac x=\"{0..}\" in exI, simp)\nlemma not_icard_Diff2_less: \"\\<exists>(A::nat set)x y. x \\<in> A \\<and> y \\<in> A \\<and> \\<not> icard (A - {x} - {y}) < icard A\"\nby (rule_tac x=\"{0..}\" in exI, simp)\n\nthm Finite_Set.card_Diff1_le\nlemma icard_Diff1_le: \"icard (A - {x}) \\<le> icard A\"\nby (rule icard_mono, rule Diff_subset)\n\nthm Finite_Set.card_psubset\nlemma icard_psubset: \"\\<lbrakk> A \\<subseteq> B; icard A < icard B \\<rbrakk> \\<Longrightarrow> A \\<subset> B\"\nby (metis less_le psubset_eq)\n\nthm SetInterval2.card_partition\nlemma icard_partition: \"\n  \\<lbrakk> \\<And>c. c \\<in> C \\<Longrightarrow> icard c = k; \\<And>c1 c2. \\<lbrakk>c1 \\<in> C; c2 \\<in> C; c1 \\<noteq> c2\\<rbrakk> \\<Longrightarrow> c1 \\<inter> c2 = {} \\<rbrakk> \\<Longrightarrow> \n  icard (\\<Union>C) = k * icard C\"\napply (case_tac \"C = {}\", simp)\napply (case_tac \"k = 0\")\n apply (simp add: icard_empty_iff_enat)\napply simp\napply (case_tac k, rename_tac k1)\n apply (subgoal_tac \"0 < k1\")\n  prefer 2\n  apply simp\n apply (case_tac \"finite C\")\n  apply (simp add: icard_finite)\n  thm SetInterval2.card_partition\n  thm icard_eq_enat_imp_card\n  apply (subgoal_tac \"\\<And>c. c \\<in> C \\<Longrightarrow> card c = k1\")\n   prefer 2\n   apply (rule icard_eq_enat_imp_card, simp)\n  thm SetInterval2.card_partition\n  apply (frule_tac C=C and k=k1 in SetInterval2.card_partition, simp+)\n  apply (subgoal_tac \"finite (\\<Union>C)\")\n   prefer 2\n   apply (rule card_gr0_imp_finite)\n   apply (simp add: not_empty_card_gr0_conv)\n  apply (simp add: icard_finite)\n apply simp\n apply (rule icard_infinite)\n thm finite_UnionD\n apply (rule ccontr, simp)\n apply (drule finite_UnionD, simp)\napply (frule icard_not_empty_iff[THEN iffD2])\napply (simp add: icard_infinite_conv)\napply (frule not_empty_imp_ex, erule exE, rename_tac c)\nthm Union_upper\napply (frule Union_upper)\nthm infinite_super\napply (rule infinite_super, assumption)\napply simp\ndone\n \nthm Finite_Set.card_image_le\nlemma icard_image_le: \"icard (f ` A) \\<le> icard A\"\napply (case_tac \"finite A\")\n apply (simp add: icard_finite card_image_le)\napply simp\ndone\n \nthm Finite_Set.card_image\nlemma icard_image: \"inj_on f A \\<Longrightarrow> icard (f ` A) = icard A\"\napply (case_tac \"finite A\")\n apply (simp add: icard_finite card_image)\napply (simp add: icard_infinite_conv inj_on_imp_infinite_image)\ndone\n\nthm Finite_Set.eq_card_imp_inj_on\nlemma not_eq_icard_imp_inj_on: \"\\<exists>(f::nat\\<Rightarrow>nat) (A::nat set). icard (f ` A) = icard A \\<and> \\<not> inj_on f A\"\napply (rule_tac x=\"\\<lambda>n. (if n = 0 then Suc 0 else n)\" in exI)\napply (rule_tac x=\"{0..}\" in exI)\napply (rule conjI)\n apply (rule subst[of \"{1..}\" \"((\\<lambda>n. if n = 0 then Suc 0 else n) ` {0..})\"])\n  apply (simp add: set_eq_iff)\n  apply (rule allI, rename_tac n)\n  apply (case_tac \"n = 0\", simp)\n  apply simp\n apply (simp only: icard_infinite[OF infinite_atLeast])\napply (simp add: inj_on_def)\napply blast\ndone\n\nthm Finite_Set.inj_on_iff_eq_card\nlemma not_inj_on_iff_eq_icard: \"\\<exists>(f::nat\\<Rightarrow>nat) (A::nat set). \\<not> (inj_on f A = (icard (f ` A) = icard A))\"\nby (insert not_eq_icard_imp_inj_on, blast)\n\nthm Finite_Set.card_inj_on_le\nlemma icard_inj_on_le: \"\\<lbrakk> inj_on f A; f ` A \\<subseteq> B \\<rbrakk> \\<Longrightarrow> icard A \\<le> icard B\"\napply (case_tac \"finite B\")\n apply (metis icard_image icard_mono)\napply simp\ndone\n\n\nthm Finite_Set.card_bij_eq\nthm Finite_Set.card_bij_eq[no_vars]\nlemma icard_bij_eq: \"\n  \\<lbrakk> inj_on f A; f ` A \\<subseteq> B; inj_on g B; g ` B \\<subseteq> A \\<rbrakk> \\<Longrightarrow> \n  icard A = icard B\"\nby (simp add: order_eq_iff icard_inj_on_le)\n\nlemma icard_cartesian_product: \"icard (A \\<times> B) = icard A * icard B\"\napply (case_tac \"A = {} \\<or> B = {}\", fastforce)\napply clarsimp\napply (case_tac \"finite A \\<and> finite B\")\n apply (simp add: icard_finite)\napply (simp only: de_Morgan_conj, erule disjE)\napply (simp_all add: \n  icard_not_empty_iff[symmetric]\n  cartesian_product_infiniteL_imp_infinite cartesian_product_infiniteR_imp_infinite)\ndone\n\nthm card_cartesian_product_singleton\nlemma icard_cartesian_product_singleton: \"icard ({x} \\<times> A) = icard A\"\nby (simp add: icard_cartesian_product mult_eSuc)\n\nthm card_cartesian_product_singleton_right\nlemma icard_cartesian_product_singleton_right: \"icard (A \\<times> {x}) = icard A\"\nby (simp add: icard_cartesian_product mult_eSuc_right)\n\n\n\nthm Power.card_Pow\n\nthm Finite_Set.dvd_partition\n\nthm Equiv_Relations.equiv_imp_dvd_card\n\nthm Equiv_Relations.card_quotient_disjoint\n\n\n\nthm\n  Set_Interval.card_lessThan\n  Set_Interval.card_atMost\n  Set_Interval.card_atLeastLessThan\n  Set_Interval.card_atLeastAtMost\n  Set_Interval.card_greaterThanAtMost\n  Set_Interval.card_greaterThanLessThan\nlemma \n  icard_lessThan: \"icard {..<u} = enat u\" and\n  icard_atMost: \"icard {..u} = enat (Suc u)\" and\n  icard_atLeastLessThan: \"icard {l..<u} = enat (u - l)\" and\n  icard_atLeastAtMost: \"icard {l..u} = enat (Suc u - l)\" and\n  icard_greaterThanAtMost: \"icard {l<..u} = enat (u - l)\" and\n  icard_greaterThanLessThan: \"icard {l<..<u} = enat (u - Suc l)\"\nby (simp_all add: icard_finite)\n\nlemma icard_atLeast: \"icard {(u::nat)..} = \\<infinity>\"\nby (simp add: infinite_atLeast)\nlemma icard_greaterThan: \"icard {(u::nat)<..} = \\<infinity>\"\nby (simp add: infinite_greaterThan)\n\n\n\nthm \n  Set_Interval.card_atLeastZeroLessThan_int\n  Set_Interval.card_atLeastLessThan_int\n  Set_Interval.card_atLeastAtMost_int\n  Set_Interval.card_greaterThanAtMost_int\nlemma \n  icard_atLeastZeroLessThan_int: \"icard {0..<u} = enat (nat u)\" and\n  icard_atLeastLessThan_int: \"icard {l..<u} = enat (nat (u - l))\" and\n  icard_atLeastAtMost_int: \"icard {l..u} = enat (nat (u - l + 1))\" and\n  icard_greaterThanAtMost_int: \"icard {l<..u} = enat (nat (u - l))\"\nby (simp_all add: icard_finite)\n\nlemma icard_atLeast_int: \"icard {(u::int)..} = \\<infinity>\"\nby (simp add: infinite_atLeast_int)\n\nlemma icard_greaterThan_int: \"icard {(u::int)<..} = \\<infinity>\"\nby (simp add: infinite_greaterThan_int)\n\nlemma icard_atMost_int: \"icard {..(u::int)} = \\<infinity>\"\nby (simp add: infinite_atMost_int)\n\nlemma icard_lessThan_int: \"icard {..<(u::int)} = \\<infinity>\"\nby (simp add: infinite_lessThan_int)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/List-Infinite/CommonSet/InfiniteSet2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8757869997529961, "lm_q1q2_score": 0.7728188482448213}}
{"text": "theory P17 imports Main begin\n\ndatatype paren = leftP | rightP\n\n\n\ninductive_set S :: \"paren list set\" where\nS1: \"Nil : S\" |\nS2: \"w : S \\<Longrightarrow> leftP # w @ [rightP] : S\" |\nS3: \"w0 : S \\<Longrightarrow> w1 : S \\<Longrightarrow> w0 @ w1 : S\"\n\ndeclare S1 [iff] S2[intro!,simp]\n\ninductive_set T :: \"paren list set\" where\nT1: \"Nil : T\" |\nT2: \"v0 : T \\<Longrightarrow> v1 : T \\<Longrightarrow> v0 @ (leftP # v1 @ [rightP]) : T\"\n\ndeclare T1 [iff]\n\nlemma T2S : \"w : T \\<Longrightarrow> w : S\"\n  apply (erule T.induct)\n   apply simp\n  apply (simp add: S.S3)\n  done\n\nlemma TT[simp]: \"\\<forall>v1. v0 : T \\<Longrightarrow> v1 : T \\<Longrightarrow> v0 @ v1 : T\"\n  apply (erule T.induct)\n  apply auto\n  apply (metis T.simps append_assoc)\n  done\n\nlemma S2T : assumes w: \"w : S\" shows \"w : T\"\n  using w\nproof (induct)\n  case S1\n  then show ?case by simp\nnext\n  case (S2 w)\n  then show ?case using T.T2 by force\nnext\n  case (S3 w0 w1)\n  then show ?case by simp\nqed\n\nfun paren_counter :: \"paren list \\<Rightarrow> int\" where\n\"paren_counter Nil = 0\" |\n\"paren_counter (x # xs) = (if (x=leftP) then (paren_counter xs + 1) else (paren_counter xs - 1))\"\n\nfun valid_paren :: \"paren list \\<Rightarrow> bool\" where\n\"valid_paren xs = (if (paren_counter xs = 0) then True else False)\"\n\nlemma [simp]: \"paren_counter (xs @ ys) = (paren_counter xs + paren_counter ys)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma S_valid:\n  assumes w: \"w : S\" shows \"valid_paren w\"\n  using w\nproof (induct)\ncase S1\n  then show ?case by simp\nnext\n  case (S2 w)\n  then show ?case by simp\nnext\n  case (S3 w0 w1)\n  then show ?case\n  proof -\n    assume 1: \"valid_paren w0\" \"valid_paren w1\"\n    have 2: \"paren_counter w0 = 0\"\n      by (meson S3.hyps(2) valid_paren.simps)\n    also have 3: \"paren_counter w1 = 0\"\n      by (meson S3.hyps(4) valid_paren.simps)\n    hence \"paren_counter (w0 @ w1) = 0\" using 1 2 by simp\n    thus ?thesis by simp\n  qed\nqed\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P17.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632856092014, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7727946423649434}}
{"text": "\\<^marker>\\<open>creator Bilel Ghorbel, Florian Kessler\\<close>\n\nsection \"Inductive definition of relation power\"\ntheory Rel_Pow imports Main begin\n\nparagraph \"Summary\"\ntext\\<open>We provide an inductive definition for applying a relation n times.\\<close>\n\ninductive rel_pow:: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"rel_pow r 0 x x\"|\nstep:\"r x y \\<Longrightarrow> rel_pow r n y z \\<Longrightarrow> rel_pow r (Suc n) x z\"\nhide_fact (open) refl step\n\nlemma rel_pow_rhs: \"rel_pow r n x y \\<Longrightarrow> r y z \\<Longrightarrow> rel_pow r (Suc n) x z\"\n  by (induction rule:rel_pow.induct)  (auto simp add: rel_pow.refl rel_pow.step)\n\nlemma rel_pow_sum: \"rel_pow r n1 x y \\<Longrightarrow> rel_pow r n2 y z \\<Longrightarrow> rel_pow r (n1+n2) x z\"\n  apply (induction rule:rel_pow.induct)\n   apply (auto simp add: rel_pow.refl rel_pow.step)\n  done\n\nlemmas rel_pow_induct =\n  rel_pow.induct[of \"r:: 'a*'b \\<Rightarrow> 'a*'b \\<Rightarrow> bool\", split_format(complete)]\nlemmas rel_pow_intros =\n  rel_pow.intros[of \"r:: 'a*'b \\<Rightarrow> 'a*'b \\<Rightarrow> bool\",split_format(complete)]\ndeclare rel_pow.intros[simp,intro]\n\nlemma rel_pow_step1[simp, intro]: \"r x y \\<Longrightarrow> rel_pow r 1 x y\"\n  using rel_pow.simps by fastforce\n\ninductive_cases  reflE[elim!]: \"rel_pow r 0 x y\"\ninductive_cases  stepE[elim!]: \"rel_pow r (Suc n) x y\"\n\ncode_pred rel_pow .\n\nlemma rel_pow_Suc_E_util: \"rel_pow r n' x z \\<Longrightarrow> n' = Suc n \\<Longrightarrow> (\\<exists>y. rel_pow r n x y \\<and> r y z)\"\nproof (induction n' x z arbitrary: n rule: rel_pow.induct)\n  case (step x y n z)\n  then show ?case by (cases n) blast+\nqed auto\n\nlemma rel_pow_Suc_E: \"rel_pow r (Suc n) x z  \\<Longrightarrow> (\\<exists>y. rel_pow r n x y \\<and> r y z)\"\n  using rel_pow_Suc_E_util by metis\n\nlemma rel_pow_sum_decomp:\n  assumes \"rel_pow r (a + b) x z\"\n  obtains y where \"rel_pow r a x y \\<and> rel_pow r b y z\"\n  using assms\nproof(induction b arbitrary: z thesis)\n  case (Suc b)\n  obtain y' where \"rel_pow r (a + b) x y'\" \"r y' z\" \n    using  \\<open>rel_pow r (a + Suc b) x z\\<close>\n      exE[OF rel_pow_Suc_E[where ?n = \"a + b\" and ?x = x and ?z = z]]\n    by auto\n  obtain y where \"rel_pow r a x y\" \"rel_pow r b y y'\"\n    using Suc.IH \\<open>rel_pow r (a + b) x y'\\<close>\n    by auto\n  have \"rel_pow r (Suc b) y z\" \n    using \\<open>rel_pow r b y y'\\<close> \\<open>r y' z\\<close> rel_pow_rhs\n    by fastforce\n  thus ?case\n    using \\<open>rel_pow r a x y\\<close> Suc.prems \n    by blast\nqed auto\n\nend", "meta": {"author": "wimmers", "repo": "poly-reductions", "sha": "b2d7c584bcda9913dd5c3785817a5d63b14d1455", "save_path": "github-repos/isabelle/wimmers-poly-reductions", "path": "github-repos/isabelle/wimmers-poly-reductions/poly-reductions-b2d7c584bcda9913dd5c3785817a5d63b14d1455/IMP-/Rel_Pow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7726510275650438}}
{"text": "section {*\\isaheader{Implementing Priority Queues by Annotated Lists}*}\ntheory PrioByAnnotatedList\nimports \n  \"../spec/AnnotatedListSpec\"\n  \"../spec/PrioSpec\"\nbegin\n\ntext {*\n  In this theory, we implement priority queues by annotated lists.\n\n  The implementation is realized as a generic adapter from the\n  AnnotatedList to the priority queue interface.\n\n  Priority queues are realized as a sequence of pairs of\n  elements and associated priority. The monoids operation\n  takes the element with minimum priority.\n\n  The element with minimum priority is extracted from the\n  sum over all elements.\n  Deleting the element with minimum priority is done by\n  splitting the sequence at the point where the minimum priority\n  of the elements read so far becomes equal to the minimum priority of \n  all elements.\n*}\n\nsubsection \"Definitions\"\nsubsubsection \"Monoid\"\ndatatype ('e, 'a) Prio = Infty | Prio 'e 'a\n\nfun p_unwrap :: \"('e,'a) Prio \\<Rightarrow> ('e \\<times> 'a)\" where\n\"p_unwrap (Prio e a) = (e , a)\"\n\nfun p_min :: \"('e, 'a::linorder) Prio \\<Rightarrow> ('e, 'a) Prio \\<Rightarrow> ('e, 'a) Prio\"  where\n  \"p_min Infty Infty = Infty\"|\n  \"p_min Infty (Prio e a) = Prio e a\"|\n  \"p_min (Prio e a) Infty = Prio e a\"|\n  \"p_min (Prio e1 a) (Prio e2 b) = (if a \\<le> b then Prio e1 a else Prio e2 b)\"\n\n\nlemma p_min_re_neut[simp]: \"p_min a Infty = a\" by (induct a) auto\nlemma p_min_le_neut[simp]: \"p_min Infty a = a\" by (induct a) auto\nlemma p_min_asso: \"p_min (p_min a b) c = p_min a (p_min b c)\"\n  apply(induct a b  rule: p_min.induct )\n  apply auto \n  apply (induct c)\n  apply auto\n  apply (induct c)\n  apply auto\n  done\nlemma lp_mono: \"class.monoid_add p_min Infty\" \n  by unfold_locales (auto simp add: p_min_asso)\n\ninstantiation Prio :: (type,linorder) monoid_add\nbegin\ndefinition zero_def: \"0 == Infty\" \ndefinition plus_def: \"a+b == p_min a b\"\n  \ninstance by \n  intro_classes \n(auto simp add: p_min_asso zero_def plus_def)\nend\n\nfun p_less_eq :: \"('e, 'a::linorder) Prio \\<Rightarrow> ('e, 'a) Prio \\<Rightarrow> bool\" where\n  \"p_less_eq (Prio e a) (Prio f b) = (a \\<le> b)\"|\n  \"p_less_eq  _ Infty = True\"|\n  \"p_less_eq Infty (Prio e a) = False\"\n\nfun p_less :: \"('e, 'a::linorder) Prio \\<Rightarrow> ('e, 'a) Prio \\<Rightarrow> bool\" where\n  \"p_less (Prio e a) (Prio f b) = (a < b)\"|\n  \"p_less (Prio e a) Infty = True\"|\n  \"p_less Infty _ = False\"\n\nlemma p_less_le_not_le : \"p_less x y \\<longleftrightarrow> p_less_eq x y \\<and> \\<not> (p_less_eq y x)\"\n  by (induct x y rule: p_less.induct) auto\n\nlemma p_order_refl : \"p_less_eq x x\"\n  by (induct x) auto\n\nlemma p_le_inf : \"p_less_eq Infty x \\<Longrightarrow> x = Infty\"\n  by (induct x) auto\n\nlemma p_order_trans : \"\\<lbrakk>p_less_eq x y; p_less_eq y z\\<rbrakk> \\<Longrightarrow> p_less_eq x z\"\n  apply (induct y z rule: p_less.induct)\n  apply auto\n  apply (induct x)\n  apply auto\n  apply (cases x)\n  apply auto\n  apply(induct x)\n  apply (auto simp add: p_le_inf)\n  apply (metis p_le_inf p_less_eq.simps(2))\n  done\n\nlemma p_linear2 : \"p_less_eq x y \\<or> p_less_eq y x\"\n  apply (induct x y rule: p_less_eq.induct)\n  apply auto\n  done\n\ninstantiation Prio :: (type, linorder) preorder\nbegin\ndefinition plesseq_def: \"less_eq = p_less_eq\"\ndefinition pless_def: \"less = p_less\"\n\ninstance \n  apply (intro_classes)\n  apply (simp only: p_less_le_not_le pless_def plesseq_def)\n  apply (simp only: p_order_refl plesseq_def pless_def)\n  apply (simp only: plesseq_def)\n  apply (metis p_order_trans)\n  done\n\nend\n\n\nsubsubsection \"Operations\"\ndefinition alprio_\\<alpha> :: \"('s \\<Rightarrow> (unit \\<times> ('e,'a::linorder) Prio) list) \n  \\<Rightarrow> 's \\<Rightarrow> ('e \\<times> 'a::linorder) multiset\"\n  where \n  \"alprio_\\<alpha> \\<alpha> al == (mset (map p_unwrap (map snd (\\<alpha> al))))\"\n\ndefinition alprio_invar :: \"('s \\<Rightarrow> (unit \\<times> ('c, 'd::linorder) Prio) list) \n  \\<Rightarrow> ('s \\<Rightarrow> bool) \\<Rightarrow> 's \\<Rightarrow> bool\" \n  where\n  \"alprio_invar \\<alpha> invar al == invar al \\<and> (\\<forall> x\\<in>set (\\<alpha> al). snd x\\<noteq>Infty)\"\n\ndefinition alprio_empty  where \n  \"alprio_empty empt = empt\"\n\ndefinition alprio_isEmpty  where \n  \"alprio_isEmpty isEmpty = isEmpty\"\n\ndefinition alprio_insert :: \"(unit \\<Rightarrow> ('e,'a) Prio \\<Rightarrow> 's \\<Rightarrow> 's) \n  \\<Rightarrow> 'e \\<Rightarrow> 'a::linorder \\<Rightarrow> 's  \\<Rightarrow> 's\"  \n  where\n  \"alprio_insert consl e a s = consl () (Prio e a) s\"\n\ndefinition alprio_find :: \"('s \\<Rightarrow> ('e,'a::linorder) Prio) \\<Rightarrow> 's \\<Rightarrow> ('e \\<times> 'a)\" \nwhere\n\"alprio_find annot s = p_unwrap (annot s)\"\n\ndefinition alprio_delete :: \"((('e,'a::linorder) Prio \\<Rightarrow> bool) \n  \\<Rightarrow> ('e,'a) Prio \\<Rightarrow> 's \\<Rightarrow> ('s \\<times> (unit \\<times> ('e,'a) Prio) \\<times> 's)) \n                      \\<Rightarrow> ('s \\<Rightarrow> ('e,'a) Prio) \\<Rightarrow> ('s \\<Rightarrow> 's \\<Rightarrow> 's) \\<Rightarrow> 's \\<Rightarrow> 's\" \n  where\n  \"alprio_delete splits annot app s = (let (l, _ , r) \n    = splits (\\<lambda> x. x\\<le>(annot s)) Infty s in app l r) \"\n\ndefinition alprio_meld where\n  \"alprio_meld app = app\"\n\nlemmas alprio_defs =\n  alprio_invar_def\n  alprio_\\<alpha>_def\n  alprio_empty_def\n  alprio_isEmpty_def\n  alprio_insert_def\n  alprio_find_def\n  alprio_delete_def\n  alprio_meld_def\n\nsubsection \"Correctness\"\n\nsubsubsection \"Auxiliary Lemmas\"\nlemma listsum_split: \"listsum (l @ (a::'a::monoid_add) # r) = (listsum l) + a + (listsum r)\"\n  by (induct l) (auto simp add: add.assoc)\n\n\nlemma p_linear: \"(x::('e, 'a::linorder) Prio) \\<le> y \\<or> y \\<le> x\"\n  by (unfold plesseq_def) (simp only: p_linear2)\n\n\nlemma p_min_mon: \"(x::(('e,'a::linorder) Prio)) \\<le> y \\<Longrightarrow> (z + x) \\<le> y\"\napply (unfold plus_def plesseq_def)\napply (induct x y rule: p_less_eq.induct)\napply (auto)\napply (induct z)\napply (auto)\ndone\n\nlemma p_min_mon2: \"p_less_eq x y \\<Longrightarrow> p_less_eq (p_min z x) y\"\napply (induct x y rule: p_less_eq.induct)\napply (auto)\napply (induct z)\napply (auto)\ndone\n\nlemma ls_min: \" \\<forall>x \\<in> set (xs:: ('e,'a::linorder) Prio list) . listsum xs \\<le> x\"\nproof (induct xs)\ncase Nil thus ?case by auto\nnext\ncase (Cons a ins) thus ?case\n  apply (auto simp add: plus_def plesseq_def)\n  apply (cases a)\n  apply auto\n  apply (cases \"listsum ins\")\n  apply auto\n  apply (case_tac x)\n  apply auto\n  apply (cases a)\n  apply auto\n  apply (cases \"listsum ins\")\n  apply auto\n  done\nqed    \n\nlemma infadd: \"x \\<noteq> Infty \\<Longrightarrow>x + y \\<noteq> Infty\"\napply (unfold plus_def)\napply (induct x y rule: p_min.induct)\napply auto\ndone\n\n\nlemma prio_selects_one: \"a+b = a \\<or> a+b=(b::('e,'a::linorder) Prio)\"\n  apply (simp add: plus_def)\n  apply (cases \"(a,b)\" rule: p_min.cases)\n  apply simp_all\n  done\n\n\nlemma listsum_in_set: \"(l::('x \\<times> ('e,'a::linorder) Prio) list)\\<noteq>[] \\<Longrightarrow> \n  listsum (map snd l) \\<in> set (map snd l)\"\n  apply (induct l)\n  apply simp\n  apply (case_tac l)\n  apply simp\n  using prio_selects_one\n  apply auto\n  apply force\n  apply force\n  done\n\nlemma p_unwrap_less_sum: \"snd (p_unwrap ((Prio e aa) + b)) \\<le> aa\"\n  apply (cases b)\n  apply (auto simp add: plus_def)\ndone\n\nlemma prio_add_alb: \"\\<not> b \\<le> (a::('e,'a::linorder)Prio)  \\<Longrightarrow> b + a = a\"\n  by (auto simp add: plus_def, cases \"(a,b)\" rule: p_min.cases) (auto simp add: plesseq_def)\n\nlemma prio_add_alb2: \" (a::('e,'a::linorder)Prio)  \\<le> a + b \\<Longrightarrow>  a + b = a\"\n  by (auto simp add: plus_def, cases \"(a,b)\" rule: p_min.cases) (auto simp add: plesseq_def)\n\nlemma prio_add_abc:\n  assumes \"(l::('e,'a::linorder)Prio) + a \\<le> c\" \n  and \"\\<not> l \\<le> c\"\n  shows  \"\\<not> l \\<le> a\"\nproof (rule ccontr)\n  assume \"\\<not> \\<not> l \\<le> a\"\n  with assms have \"l + a = l\"\n    apply (auto simp add: plus_def plesseq_def)\n    apply (cases \"(l,a)\" rule: p_less_eq.cases)\n    apply auto\n    done\n  with assms show False by simp\nqed\n\nlemma prio_add_abc2:\n  assumes \"(a::('e,'a::linorder)Prio) \\<le> a + b\" \n  shows \"a \\<le> b\"\nproof (rule ccontr)\n  assume ann: \"\\<not> a \\<le> b\"\n  hence \"a + b = b\" \n    apply (auto simp add: plus_def plesseq_def)\n    apply (cases \"(a,b)\" rule: p_min.cases)\n    apply auto\n    done\n  thus False using assms ann by simp\nqed\n\n\nsubsubsection \"Empty\"\nlemma alprio_empty_correct: \n  assumes \"al_empty \\<alpha> invar empt\"\n  shows \"prio_empty (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_empty empt)\"\nproof -\n  interpret al_empty \\<alpha> invar empt by fact\n  show ?thesis\n    apply (unfold_locales)\n    apply (unfold alprio_invar_def)\n    apply auto\n    apply (unfold alprio_empty_def)\n    apply (auto simp add: empty_correct)\n    apply (unfold alprio_\\<alpha>_def)\n    apply auto\n    apply (simp only: empty_correct)\n    done\nqed\n\n\nsubsubsection \"Is Empty\"\n\nlemma alprio_isEmpty_correct: \n  assumes \"al_isEmpty \\<alpha> invar isEmpty\"\n  shows \"prio_isEmpty (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_isEmpty isEmpty)\"\nproof -\n  interpret al_isEmpty \\<alpha> invar isEmpty by fact\n  show ?thesis by (unfold_locales) (auto simp add: alprio_defs isEmpty_correct)\nqed\n\n\nsubsubsection \"Insert\"\nlemma alprio_insert_correct: \n  assumes \"al_consl \\<alpha> invar consl\"\n  shows \"prio_insert (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_insert consl)\"\nproof -\n  interpret al_consl \\<alpha> invar consl by fact\n  show ?thesis by unfold_locales (auto simp add: alprio_defs consl_correct)\nqed\n\n\nsubsubsection \"Meld\"\n\nlemma alprio_meld_correct: \n  assumes \"al_app \\<alpha> invar app\"\n  shows \"prio_meld (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_meld app)\"\nproof -\n  interpret al_app \\<alpha> invar app by fact\n  show ?thesis by unfold_locales (auto simp add: alprio_defs app_correct)\nqed\n\nsubsubsection \"Find\"\n\nlemma annot_not_inf :\n  assumes \"(alprio_invar \\<alpha> invar) s\" \n  and \"(alprio_\\<alpha> \\<alpha>) s \\<noteq> {#}\"\n  and \"al_annot \\<alpha> invar annot\"\n  shows \"annot s \\<noteq> Infty\"\nproof -\n  interpret al_annot \\<alpha> invar annot by fact\n  show ?thesis\n  proof -\n    from assms(1) have invs: \"invar s\" by (simp add: alprio_defs)\n    from assms(2) have sne: \"set (\\<alpha> s) \\<noteq> {}\"\n    proof (cases \"set (\\<alpha> s) = {}\")\n      case True \n      hence \"\\<alpha> s = []\" by simp\n      hence \"(alprio_\\<alpha> \\<alpha>) s = {#}\" by (simp add: alprio_defs)\n      from this assms(2) show ?thesis by simp\n    next\n      case False thus ?thesis by simp\n    qed\n    hence \"(\\<alpha> s) \\<noteq> []\" by simp\n    hence \" \\<exists>x xs. (\\<alpha> s) = x # xs\" by (cases \"\\<alpha> s\") auto\n    from this obtain x xs where [simp]: \"(\\<alpha> s) = x # xs\" by blast\n    from this assms(1) have \"snd x \\<noteq> Infty\" by (auto simp add: alprio_defs)\n    hence \"listsum (map snd (\\<alpha> s)) \\<noteq> Infty\" by (auto simp add: infadd)\n    thus \"annot s \\<noteq> Infty\" using annot_correct invs by simp\n  qed\nqed\n\nlemma annot_in_set: \n  assumes \"(alprio_invar \\<alpha> invar) s\" \n  and \"(alprio_\\<alpha> \\<alpha>) s \\<noteq> {#}\"\n  and \"al_annot \\<alpha> invar annot\"\n  shows \"p_unwrap (annot s) \\<in># ((alprio_\\<alpha> \\<alpha>) s)\"         \nproof - \n  interpret al_annot \\<alpha> invar annot by fact\n  from assms(2) have snn: \"\\<alpha> s \\<noteq> []\" by (auto simp add: alprio_defs)\n  from assms(1) have invs: \"invar s\" by (simp add: alprio_defs)\n  hence ans: \"annot s = listsum (map snd (\\<alpha> s))\" by (simp add: annot_correct)\n  let ?P = \"map snd (\\<alpha> s)\"\n  have \"annot s \\<in> set ?P\"\n    by (unfold ans) (rule listsum_in_set[OF snn])\n  hence \"p_unwrap (annot s) \\<in> set (map p_unwrap ?P)\"\n    by (metis image_iff in_set_conv_decomp set_map split_list_last)\n  thus ?thesis\n    by (metis mem_set_multiset_eq alprio_\\<alpha>_def)\nqed\n\nlemma  listsum_less_elems: \"\\<forall>x\\<in>set xs. snd x \\<noteq> Infty \\<Longrightarrow>\n   \\<forall>y\\<in>set_mset (mset (map p_unwrap (map snd xs))).\n              snd (p_unwrap (listsum (map snd xs))) \\<le> snd y\"          \n    proof (induct xs)\n    case Nil thus ?case by simp\n    next\n    case (Cons a as) thus ?case\n      apply auto\n      apply (cases \"(snd a)\" rule: p_unwrap.cases)\n      apply auto\n      apply (cases \"listsum (map snd as)\")\n      apply auto\n      apply (metis linorder_linear p_min_re_neut \n        p_unwrap.simps plus_def [abs_def] snd_eqD)\n      apply (auto simp add: p_unwrap_less_sum)\n      apply (unfold plus_def)\n      apply (cases \"(snd a, listsum (map snd as))\" rule: p_min.cases)\n      apply auto\n      apply (cases \"map snd as\")\n      apply (auto simp add: infadd)\n      done\nqed  \n  \nlemma alprio_find_correct: \n  assumes  \"al_annot \\<alpha> invar annot\"\n  shows \"prio_find (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) (alprio_find annot)\"\nproof -\n  interpret al_annot \\<alpha> invar annot by fact\n  show ?thesis\n    apply unfold_locales\n    apply (rule conjI)\n    apply (insert assms)\n    apply (unfold alprio_find_def)\n    apply (simp add:annot_in_set)\n    apply (unfold alprio_defs)\n    apply (simp add: annot_correct)\n    apply (auto simp add: listsum_less_elems)\n    done\nqed\n\n\nsubsubsection \"Delete\"\n\nlemma delpred_mon: \n  \"\\<forall>(a:: ('e, 'a::linorder) Prio) b. ((\\<lambda> x. x \\<le> y) a \n    \\<longrightarrow> (\\<lambda> x. x \\<le> y) (a + b)) \"\nproof (intro impI allI) \n  fix a b \n  show \"a \\<le> y \\<Longrightarrow> a + b \\<le> y\"\n    apply (induct a b rule: p_less.induct)\n    apply (auto simp add: plus_def)\n    apply (metis linorder_linear order_trans \n      p_linear p_min.simps(4) p_min_mon plus_def prio_selects_one)\n    apply (metis order_trans p_linear p_min_mon p_min_re_neut plus_def)\n    done \nqed\n\n(* alprio_delete erhält die Invariante *)\nlemma alpriodel_invar: \n  assumes \"alprio_invar \\<alpha> invar s\"\n  and \"al_annot \\<alpha> invar annot\"\n  and \"alprio_\\<alpha> \\<alpha> s \\<noteq> {#}\"\n  and \"al_splits \\<alpha> invar splits\"\n  and \"al_app \\<alpha> invar app\"\n  shows \"alprio_invar \\<alpha> invar (alprio_delete splits annot app s)\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  let ?P = \"\\<lambda>x. x \\<le> annot s\"\n  obtain l p r where \n    [simp]:\"splits ?P Infty s = (l, p, r)\" \n    by (cases \"splits ?P Infty s\")  auto\n  obtain e a where \n    \"p = (e, a)\" \n    by (cases p, blast)\n  hence \n    lear:\"splits ?P Infty s = (l, (e,a), r)\" \n    by simp\n  from annot_not_inf[OF assms(1) assms(3) assms(2)] have \n    \"annot s \\<noteq> Infty\" .\n  hence \n    sv1: \"\\<not> Infty \\<le> annot s\" \n    by (simp add: plesseq_def, cases \"annot s\", auto)\n  from assms(1) have \n    invs: \"invar s\" \n    unfolding alprio_invar_def by simp\n  interpret al_annot \\<alpha> invar annot by fact\n  from invs have \n    sv2: \"Infty + listsum (map snd (\\<alpha> s)) \\<le> annot s\" \n    by (auto simp add: annot_correct plus_def \n      plesseq_def p_min_le_neut p_order_refl)\n  note sp = splits_correct[of s \"?P\" Infty l e a r]\n  note dp = delpred_mon[of \"annot s\"]\n  from sp[OF invs dp sv1 sv2 lear] have \n    invlr: \"invar l \\<and> invar r\" and \n    alr: \"\\<alpha> s = \\<alpha> l @ (e, a) # \\<alpha> r\" \n    by auto\n  interpret al_app \\<alpha> invar app by fact\n  from invlr app_correct have \n    invapplr: \"invar (app l r)\" \n    by simp\n  from invlr app_correct have \n    sr: \"\\<alpha> (app l r) = (\\<alpha> l) @ (\\<alpha> r)\" \n    by simp\n  from alr have  \n    \"set (\\<alpha> s) \\<supseteq> (set (\\<alpha> l) Un set (\\<alpha> r))\" \n    by auto\n  with app_correct[of l r] invlr have \n    \"set (\\<alpha> s) \\<supseteq> set (\\<alpha> (app l r))\" by auto\n  with invapplr assms(1) \n  show ?thesis \n    unfolding alprio_defs by auto\nqed\n\n\nlemma listsum_elem:\n  assumes \" ins = l @ (a::('e,'a::linorder)Prio) # r\"  \n  and \"\\<not> listsum l \\<le> listsum ins\"  \n  and \"listsum l + a \\<le> listsum ins \"\n  shows \" a = listsum ins\"\nproof -\n  have \"\\<not> listsum l \\<le> a\" using assms prio_add_abc by simp\n  hence lpa: \"listsum l + a = a\" using prio_add_alb by auto\n  hence als: \"a \\<le> listsum ins\" using assms(3) by simp\n  have \"listsum ins = a + listsum r\" \n    using lpa listsum_split[of l a r] assms(1) by auto\n  thus ?thesis using prio_add_alb2[of a \"listsum r\"] prio_add_abc2 als  \n    by auto\nqed\n\nlemma alpriodel_right:\n  assumes \"alprio_invar \\<alpha> invar s\"\n  and \"al_annot \\<alpha> invar annot\"\n  and \"alprio_\\<alpha> \\<alpha> s \\<noteq> {#}\"\n  and \"al_splits \\<alpha> invar splits\"\n  and \"al_app \\<alpha> invar app\"\n  shows \"alprio_\\<alpha> \\<alpha> (alprio_delete splits annot app s) = \n          alprio_\\<alpha> \\<alpha> s - {#p_unwrap (annot s)#}\"\nproof -\n  interpret al_splits \\<alpha> invar splits by fact\n  let ?P = \"\\<lambda>x. x \\<le> annot s\"\n  obtain l p r where \n    [simp]:\"splits ?P Infty s = (l, p, r)\" \n    by (cases \"splits ?P Infty s\")  auto\n  obtain e a where \n    \"p = (e, a)\" \n    by (cases p, blast)\n  hence \n    lear:\"splits ?P Infty s = (l, (e,a), r)\" \n    by simp\n  from annot_not_inf[OF assms(1) assms(3) assms(2)] have \n    \"annot s \\<noteq> Infty\" .\n  hence \n    sv1: \"\\<not> Infty \\<le> annot s\" \n    by (simp add: plesseq_def, cases \"annot s\", auto)\n  from assms(1) have \n    invs: \"invar s\" \n    unfolding alprio_invar_def by simp\n  interpret al_annot \\<alpha> invar annot by fact\n  from invs have \n    sv2: \"Infty + listsum (map snd (\\<alpha> s)) \\<le> annot s\" \n    by (auto simp add: annot_correct plus_def \n      plesseq_def p_min_le_neut p_order_refl)\n  note sp = splits_correct[of s \"?P\" Infty l e a r]\n  note dp = delpred_mon[of \"annot s\"]\n  \n  from sp[OF invs dp sv1 sv2 lear] have \n    invlr: \"invar l \\<and> invar r\" and \n    alr: \"\\<alpha> s = \\<alpha> l @ (e, a) # \\<alpha> r\" and\n    anlel: \"\\<not> listsum (map snd (\\<alpha> l)) \\<le> annot s\" and \n    aneqa: \"(listsum (map snd (\\<alpha> l)) + a) \\<le> annot s\"\n    by (auto simp add: plus_def zero_def)\n  have mapalr: \"map snd (\\<alpha> s) = (map snd (\\<alpha> l)) @ a # (map snd (\\<alpha> r))\" \n    using alr by simp\n  note lsa = listsum_elem[of \"map snd (\\<alpha> s)\" \"map snd (\\<alpha> l)\" a \"map snd (\\<alpha> r)\"]\n  note lsa2 = lsa[OF mapalr]\n  hence a_is_annot: \"a = annot s\" \n    using annot_correct[OF invs] anlel aneqa by auto\n  have \"map p_unwrap (map snd (\\<alpha> s)) = \n    (map p_unwrap (map snd (\\<alpha> l))) @ (p_unwrap a) \n      # (map p_unwrap (map snd (\\<alpha> r)))\" \n    using alr by simp\n  hence alpriolst: \"(alprio_\\<alpha> \\<alpha> s) = (alprio_\\<alpha> \\<alpha> l) +{# p_unwrap a #}+ (alprio_\\<alpha> \\<alpha> r)\" \n    unfolding alprio_defs\n    by (simp add: algebra_simps)\n  interpret al_app \\<alpha> invar app by fact\n  from alpriolst show ?thesis using app_correct[of l r] invlr a_is_annot \n    by (auto simp add: alprio_defs algebra_simps)\nqed  \n\nlemma alprio_delete_correct: \n  assumes \"al_annot \\<alpha> invar annot\"\n  and \"al_splits \\<alpha> invar splits\"\n  and \"al_app \\<alpha> invar app\"\n  shows \"prio_delete (alprio_\\<alpha> \\<alpha>) (alprio_invar \\<alpha> invar) \n           (alprio_find annot) (alprio_delete splits annot app)\"\nproof-\n  interpret al_annot \\<alpha> invar annot by fact\n  interpret al_splits \\<alpha> invar splits by fact\n  interpret al_app \\<alpha> invar app by fact\n  show ?thesis\n    apply intro_locales\n    apply (rule alprio_find_correct,simp add: assms) \n    apply unfold_locales\n    apply (insert assms)\n    apply (simp add: alpriodel_invar)\n    apply (simp add: alpriodel_right alprio_find_def)   \n    done\nqed  \n\nlemmas alprio_correct =\n  alprio_empty_correct\n  alprio_isEmpty_correct\n  alprio_insert_correct\n  alprio_delete_correct\n  alprio_find_correct\n  alprio_meld_correct\n\nlocale alprio_defs = StdALDefs ops \n  for ops :: \"(unit,('e,'a::linorder) Prio,'s) alist_ops\"\nbegin\n  definition [icf_rec_def]: \"alprio_ops \\<equiv> \\<lparr>\n    prio_op_\\<alpha> = alprio_\\<alpha> \\<alpha>,\n    prio_op_invar = alprio_invar \\<alpha> invar,\n    prio_op_empty = alprio_empty empty,\n    prio_op_isEmpty = alprio_isEmpty isEmpty,\n    prio_op_insert = alprio_insert consl,\n    prio_op_find = alprio_find annot,\n    prio_op_delete = alprio_delete splits annot app,\n    prio_op_meld = alprio_meld app\n    \\<rparr>\"\n  \nend\n\nlocale alprio = alprio_defs ops + StdAL ops \n  for ops :: \"(unit,('e,'a::linorder) Prio,'s) alist_ops\"\nbegin\n  lemma alprio_ops_impl: \"StdPrio alprio_ops\"\n    apply (rule StdPrio.intro)\n    apply (simp_all add: icf_rec_unf)\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    apply (rule alprio_correct, unfold_locales) []\n    done\nend\n    \nend\n", "meta": {"author": "andredidier", "repo": "phd", "sha": "113f7c8b360a3914a571db13d9513e313954f4b2", "save_path": "github-repos/isabelle/andredidier-phd", "path": "github-repos/isabelle/andredidier-phd/phd-113f7c8b360a3914a571db13d9513e313954f4b2/thesis/Collections/ICF/gen_algo/PrioByAnnotatedList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7726510120875881}}
{"text": "theory IMPExpressions\n\nimports Main\n\nbegin\n\ntype_synonym vname = string\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a1 a2) s = aval a1 s + aval a2 s\"\n\ndefinition exp :: \"aexp\" where \"exp = (Plus (N 5) (V ''x''))\"\n\nvalue \"aval exp ((\\<lambda> x. 0)(''x'' := 1))\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a1 a2) = \n  (case (asimp_const a1, asimp_const a2) of\n    (N n1, N n2) \\<Rightarrow> N(n1 + n2) |\n    (b1, b2) \\<Rightarrow> Plus b1 b2)\"\n\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply(induction a)\n    apply(auto split: aexp.split)\n  done\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow>  aexp\" where\n\"plus (N i1) (N i2) = N(i1 + i2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a1 a2 = Plus a1 a2\"\n\nlemma aval_plus: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply(induction rule: plus.induct)\n    apply(auto)\n  done\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)\"\n\nlemma \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n    apply(auto simp add: aval_plus)\n  done\n\nfun optimal_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bool\" where\n\"optimal_plus (N _) (N _) = False\" |\n\"optimal_plus a1 a2 = True\"\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N _) = True\" |\n\"optimal (V _) = True\" |\n\"optimal (Plus a1 a2) = ((optimal a1) \\<and> (optimal a2) \\<and> (optimal_plus a1 a2))\"\n\ntheorem \"optimal(asimp_const a)\"\n  apply(induction a)\n    apply(auto split: aexp.split)\n  done\n\nfun full_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"full_plus (N n1) (N n2) = N (n1 + n2)\" |\n\"full_plus (N n1) (Plus a (N n2)) = (Plus a (N (n1 + n2)))\" |\n\"full_plus (Plus a (N n1)) (N n2) = (Plus a (N (n1 + n2)))\" |\n\"full_plus a1 a2 = (Plus a1 a2)\"\n\nlemma full_plus_aval: \"aval (full_plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply(induction rule: full_plus.induct)\n    apply(auto)\n  done\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp (N n) = N n\" |\n\"full_asimp (V x) = V x\" |\n\"full_asimp (Plus a1 a2) = full_plus (full_asimp a1) (full_asimp a2)\"\n\nvalue \"full_asimp (Plus (N 1) (Plus (V ''x'') (N 2)))\"\n    \ntheorem \"aval (full_asimp a) s = aval a s\"\n  apply(induction a arbitrary: s)\n    apply(auto simp add: full_plus_aval)\n  done\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst v e (V x) = (if v = x then e else (V x))\" |\n\"subst v e (Plus a1 a2) = (Plus (subst v e a1) (subst v e a2))\" |\n\"subst v e a = a\"\n\nvalue \"subst ''x''  (N 2) (Plus (V ''x'') (N 1))\"\n\nlemma subst_preserves_semantics: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply(induction e)\n    apply(auto)\n  done\n\ntheorem \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply(simp add: subst_preserves_semantics)\n  done\n\nend", "meta": {"author": "amw-zero", "repo": "concrete_semantics", "sha": "b486ec4950cdb8ee83d222e9b8abff4663021e77", "save_path": "github-repos/isabelle/amw-zero-concrete_semantics", "path": "github-repos/isabelle/amw-zero-concrete_semantics/concrete_semantics-b486ec4950cdb8ee83d222e9b8abff4663021e77/IMPExpressions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7724926361272234}}
{"text": "theory symmetry\n  imports Main\nbegin\n\ndatatype 'a palindrome = Nil | Merge \"'a palindrome\" \"'a palindrome\"\n\nfun left :: \"'a palindrome ⇒ 'a palindrome\" where\n  \"left Nil = Nil\" |\n  \"left (Merge l r) = l\"\n\nfun right :: \"'a palindrome ⇒ 'a palindrome\" where\n  \"right Nil = Nil\" |\n  \"right (Merge l r) = r\"\n\nfun reversed :: \"'a palindrome ⇒ 'a palindrome\" where\n  \"reversed Nil = Nil\" |\n  \"reversed (Merge l r) = Merge (reversed r) (reversed l)\"\n\nfun connect :: \"'a palindrome ⇒ 'a palindrome ⇒ 'a palindrome\"  where\n \"connect Nil nw = Nil\" |\n \"connect (Merge l r) m = Merge (Merge l m) (Merge (reversed m) (reversed l))\"\n\nlemma double_reverse: \"reversed (reversed a) = a\"\n  apply (induct_tac a)\n  apply (auto)\n  done\n\nlemma reversed_commutativity: \n  assumes \"reversed a = b\"\n  shows \"reversed b = a\"\n\nproof (cases \"a\")\n  case (Merge l r)\n  then have  \"b = Merge (reversed r) (reversed l)\" using assms by simp\n  then have \"reversed b = Merge (reversed (reversed l)) (reversed (reversed r))\" by auto\n  then have \"reversed b = Merge l r\" using double_reverse by auto\n  thus ?thesis using Merge by auto\nnext \n  case Nil\n  then have \"reversed a = Nil\" by auto\n  then have \"b = Nil\" using assms by auto\n  then have \"reversed b = Nil\" by auto\n  thus ?thesis using local.Nil by simp\nqed\n\ntheorem recurrence_is_symmetric:\n  fixes a b\n  assumes \"p = connect a b\"\n  shows \"reversed (right p) = left p\"\n\nproof (cases \"a\")\n  case (Merge l r)\n    from assms have \"p = connect a b\" by auto\n    then have \"p = Merge (Merge l b) (Merge (reversed b) (reversed l))\" by (simp add: Merge)\n    also have \"reversed (Merge l b) = Merge (reversed b) (reversed l)\" by auto\n    then have \"reversed (left p) = right p\" by (simp add: calculation)\n    then have \"reversed (right p) = left p\" using reversed_commutativity by auto\n    thus ?thesis by auto\n  next\n    case Nil\n    then have \"p = Nil\" using assms by auto\n    then have \"left p = Nil\" and \"right p = Nil\" and \"reversed (right p) = Nil\" by auto\n    thus ?thesis by auto\n qed\n\nend\n    \n  \n", "meta": {"author": "s-nandi", "repo": "automated-proofs", "sha": "719103028f53ded647e34fa88fff0383b09865e9", "save_path": "github-repos/isabelle/s-nandi-automated-proofs", "path": "github-repos/isabelle/s-nandi-automated-proofs/automated-proofs-719103028f53ded647e34fa88fff0383b09865e9/symmetry.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.772492633932081}}
{"text": "theory Binary_Operations\n  imports Bits_Digits Carries\nbegin\n\nsection \\<open>Digit-wise Operations\\<close>\n\nsubsection \\<open>Binary AND\\<close>\n\nfun bitAND_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" (infix \"&&\" 64) where\n  \"0 && _ = 0\" |\n  \"m && n = 2 * ((m div 2) && (n div 2)) + (m mod 2) * (n mod 2)\"\n\nlemma bitAND_zero[simp]: \"n = 0 \\<Longrightarrow> m && n = 0\"\n  by (induct m n rule:bitAND_nat.induct, auto)\n\nlemma bitAND_1: \"a && 1 = (a mod 2)\"\n  by (induction a; auto)\n\nlemma bitAND_rec: \"m && n = 2 * ((m div 2) && (n div 2)) + (m mod 2) * (n mod 2)\"\n  by (cases m; simp_all)\n\nlemma bitAND_commutes:\"m && n = n && m\"\n  by (induct m n rule: bitAND_nat.induct, simp) (metis bitAND_rec mult.commute)\n\nlemma nth_digit_0: \"x \\<le> 1 \\<Longrightarrow> nth_bit x 0 = x\" by (simp add: nth_bit_def)\n\nlemma bitAND_zeroone: \"a \\<le> 1 \\<Longrightarrow> b \\<le> 1 \\<Longrightarrow> a && b \\<le> 1\"\n  using nth_bit_def nth_digit_0 nat_le_linear bitAND_nat.elims\n  by (metis (no_types, lifting) One_nat_def add.left_neutral bitAND_zero div_less le_zero_eq lessI\n             mult.right_neutral mult_0_right not_mod2_eq_Suc_0_eq_0 numeral_2_eq_2)\n\nlemma aux1_bitAND_digit_mult:\n  fixes a b c :: nat\n  shows \"k > 0 \\<and> a mod 2 = 0 \\<and> b \\<le> 1 \\<Longrightarrow> (a + b) div 2^k = a div 2^k\"\n  by (induction k, auto)\n     (metis One_nat_def add_cancel_left_right div_mult2_eq even_succ_div_two le_0_eq le_Suc_eq)\n\nlemma bitAND_digit_mult:\"(nth_bit (a && b) k) = (nth_bit a k) * (nth_bit b k)\"\nproof(induction k arbitrary: a b)\n  case 0\n  show ?case\n    using nth_bit_def\n    by auto (metis (no_types, opaque_lifting) Groups.add_ac(2) bitAND_rec mod_mod_trivial\n              mod_mult_self2 mult_numeral_1_right mult_zero_right not_mod_2_eq_1_eq_0 numeral_One)\nnext\n  case (Suc k)\n  have \"nth_bit (a && b) (Suc k)\n        = (2 * (a div 2 && b div 2) + a mod 2 * (b mod 2)) div 2 ^(Suc k) mod 2\"\n    using bitAND_rec by (metis nth_bit_def)\n\n  moreover have \"(a mod 2) * (b mod 2) < (2 ^ Suc(k))\"\n    by (metis One_nat_def lessI mult_numeral_1_right mult_zero_right not_mod_2_eq_1_eq_0\n              numeral_2_eq_2 numeral_One power_gt1 zero_less_numeral zero_less_power)\n\n  ultimately have \"nth_bit (a && b) (Suc k) = (2 * (a div 2 && b div 2)) div 2 ^(Suc k) mod 2\"\n    using aux1_bitAND_digit_mult\n    by (metis le_numeral_extra(1) le_numeral_extra(4) mod_mult_self1_is_0 mult_numeral_1_right\n              mult_zero_right not_mod_2_eq_1_eq_0 numeral_One zero_less_Suc)\n\n  then have \"nth_bit (a && b) (Suc k) = (nth_bit (a div 2 && b div 2) k)\"\n    by (auto simp add: nth_bit_def)\n\n  then have \"nth_bit (a && b) (Suc k) = (nth_bit (a div 2) k) * (nth_bit (b div 2) k)\"\n    using Suc\n    by presburger\n\n  then show ?case\n    by (metis div_mult2_eq nth_bit_def power_Suc)\nqed\n\nlemma bitAND_single_bit_mult_equiv: \"a \\<le> 1 \\<Longrightarrow> b \\<le> 1 \\<Longrightarrow> a * b = a && b\"\n  using bitAND_digit_mult[of a b 0] bitAND_zeroone by (auto simp: nth_digit_0)\n\nlemma bitAND_mult_equiv:\n  \"(\\<forall>k. (nth_bit c k) = (nth_bit a k) * (nth_bit b k)) \\<longleftrightarrow> c = a && b\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?Q\"\n  then show \"?P\" using bitAND_digit_mult by simp\nnext\n  assume \"?P\"\n  then show \"?Q\" using bitAND_digit_mult digit_wise_equiv by presburger\nqed\n\nlemma bitAND_linear:\n  fixes k::nat\n  shows \"(b < 2^k) \\<and> (d < 2^k) \\<Longrightarrow> (a * 2^k + b) && (c * 2^k + d) = (a && c) * 2^k + (b && d)\"\nproof(induction k arbitrary: a b c d)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc k)\n  define m where \"m = a * 2^(Suc k) + b\"\n  define n where \"n = c * 2^(Suc k) + d\"\n\n  have \"m && n = 2 * (bitAND_nat (m div 2) (n div 2)) + (m mod 2) * (n mod 2)\"\n    using bitAND_rec\n    by blast\n\n  moreover have \"d mod 2 = n mod 2 \\<and> b mod 2 = m mod 2\"\n    by (metis m_def n_def add.commute mod_mult_self2 power_Suc semiring_normalization_rules(19))\n\n  ultimately have f0:\"m && n\n                      = 2 * ((a * 2^k + (b div 2)) && (c * 2^k + (d div 2))) + (b mod 2)*(d mod 2)\"\n    by (metis add.commute div_mult_self2 m_def n_def power_Suc semiring_normalization_rules(19)\n              zero_neq_numeral)\n\n  have \"b div 2 < (2 ^ k) \\<and> d div 2 < (2 ^ k)\"\n    using Suc.prems\n    by auto\n\n  then have f1:\"m && n\n                = ((a && c) * 2^(Suc k)) + 2 * ((b div 2) && (d div 2)) + (b mod 2) * (d mod 2)\"\n    using f0 Suc.IH\n    by simp\n\n  have \"b && d = 2 * ((b div 2) && (d div 2)) + (b mod 2) * (d mod 2)\"\n    using bitAND_rec\n    by blast\n\n  then show ?case\n    using f1\n    by (auto simp add: m_def n_def)\nqed\n\nsubsection \\<open>Binary orthogonality\\<close>\ntext \\<open>cf. \\<^cite>\\<open>h10lecturenotes\\<close> section 2.6.1 on \"Binary orthogonality\"\\<close>\ntext \\<open>The following definition differs slightly from the one in the paper. However, we later prove the \n     equivalence of the two definitions.\\<close>\n\nfun orthogonal :: \"nat => nat => bool\" (infix \"\\<bottom>\" 49) where\n  \"(orthogonal a b) = (a && b = 0)\"\n\nlemma ortho_mult_equiv: \"a \\<bottom> b \\<longleftrightarrow> (\\<forall>k. (nth_bit a k) * (nth_bit b k) = 0)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?P\"\n  then show \"?Q\" using bitAND_digit_mult nth_bit_def by (metis div_0 mod_0 orthogonal.simps)\nnext\n  assume \"?Q\"\n  then show \"?P\" using bitAND_mult_equiv nth_bit_def by (metis div_0 mod_0 orthogonal.simps)\nqed\n\nlemma aux1_1_digit_lt_linear:\n  assumes \"b < 2^r\" \"k \\<ge> r\"\n  shows  \"bin_carry (a*2^r) b k = 0\"\nproof-\n  have \"b < 2^r \\<longrightarrow>(a*2^r) \\<bottom> b\"\n  proof(induct a  b rule: bitAND_nat.induct)\n    case (1 uu)\n    then show ?case by simp\n  next\n    case (2 v n)\n    show ?case apply auto using bitAND_linear[of n r 0 0 \"Suc(v)\"] bitAND_commutes by auto\n  qed\n  then show ?thesis using ortho_mult_equiv no_carry_mult_equiv assms(1) by auto\nqed\n\nlemma aux1_digit_lt_linear:\n  assumes \"b < 2^r\" and \"k \\<ge> r\"\n  shows \"(a*2^r + b) \\<exclamdown> k = (a*2^r) \\<exclamdown> k\"\nproof-\n  have \"b div 2 ^ k = 0\" using assms by (simp add: order.strict_trans2)\n  moreover have \"(a * 2 ^ r mod 2 ^ k +  b mod 2 ^ k) div 2 ^ k = 0\" using assms\n  proof-\n    have \"bin_carry (a*2^r) b k = 0\" using assms aux1_1_digit_lt_linear by auto\n    then show ?thesis using assms by (auto simp add: bin_carry_def)\n  qed\n  ultimately show ?thesis\n    by (auto simp add: nth_bit_def div_add1_eq[of \"a*2^r\" \"b\" \"2^k\"])\nqed\n\nlemma aux_digit_shift: \"(a * 2^t) \\<exclamdown> (l+t) = a \\<exclamdown> l\"\n  using nth_bit_def\n  by (induct l; auto)\n     (smt div_mult2_eq mult.commute nonzero_mult_div_cancel_right power_add power_not_zero zero_neq_numeral)\n\nlemma aux_digit_lt_linear:\n  assumes b: \"b < (2::nat)^t\"\n  assumes d: \"d < (2::nat)^t\"\n  shows \"(a * 2^t + b) \\<exclamdown> k \\<le> (c * 2^t + d) \\<exclamdown> k \\<longleftrightarrow> ((a * 2^t) \\<exclamdown> k \\<le> (c * 2^t) \\<exclamdown> k \\<and> b \\<exclamdown> k \\<le> d \\<exclamdown> k)\"\nproof (cases \"k < t\")\n  case True\n  from True have \"(a * 2^t + b) \\<exclamdown> k = b \\<exclamdown> k\"\n    using aux2_digit_sum_repr assms(1) by auto\n  moreover from True have \"(c * 2^t + d) \\<exclamdown> k = d \\<exclamdown> k\"\n    using aux2_digit_sum_repr assms(2) by auto\n  moreover from True have \"(a * 2^t) \\<exclamdown> k = 0\"\n    using aux2_digit_sum_repr[of \"0\"] nth_bit_def by auto\n  ultimately show ?thesis\n    using aux2_digit_sum_repr assms by auto\nnext\n  case False\n  from False have \"(a * 2^t + b) \\<exclamdown> k = (a * 2^t) \\<exclamdown> k\"\n    using aux1_digit_lt_linear assms(1) by auto\n  moreover from False have \"(c * 2^t + d) \\<exclamdown> k = (c * 2^t) \\<exclamdown> k\" using aux1_digit_lt_linear assms(2) by auto\n  moreover from False have \"b \\<exclamdown> k = 0\"\n    using aux1_digit_lt_linear[of _ _ _ \"0\"] nth_bit_def assms(1) by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma aux2_digit_lt_linear:\n  fixes a b c d t l :: nat\n  shows \"\\<exists>k. (a * 2^t) \\<exclamdown> k \\<le> (c * 2^t) \\<exclamdown> k \\<longrightarrow> a \\<exclamdown> l \\<le> c \\<exclamdown> l\"\nproof -\n  define k where \"k = l + t\"\n  have \"(a * 2^t) \\<exclamdown> k = a \\<exclamdown> l\" using nth_bit_def k_def\n    using aux_digit_shift by auto\n  moreover have \"(c * 2^t) \\<exclamdown> k = c \\<exclamdown> l\" using nth_bit_def k_def\n    using aux_digit_shift by auto\n  ultimately show ?thesis by metis\nqed\n\nlemma aux3_digit_lt_linear:\n  fixes a b c d t k :: nat\n  shows \"\\<exists>l. a \\<exclamdown> l \\<le> c \\<exclamdown> l \\<longrightarrow> (a * 2^t) \\<exclamdown> k \\<le> (c * 2^t) \\<exclamdown> k\"\nproof (cases \"k < t\")\n  case True\n  hence \"(a * 2^t) \\<exclamdown> k = 0\"\n    using aux2_digit_sum_repr[of \"0\"] nth_bit_def by auto\n  then show ?thesis by auto\nnext\n  case False\n  define l where \"l = k - t\"\n  hence k: \"k = l + t\" using False by auto\n  have \"(a * 2^t) \\<exclamdown> k = a \\<exclamdown> l\" using nth_bit_def l_def\n    using aux_digit_shift k by auto\n  moreover have \"(c * 2^t) \\<exclamdown> k = c \\<exclamdown> l\" using nth_bit_def l_def\n    using aux_digit_shift k by auto\n  ultimately show ?thesis by auto\nqed\n\nlemma digit_lt_linear:\n  fixes a b c d t :: nat\n  assumes b: \"b < (2::nat)^t\"\n  assumes d: \"d < (2::nat)^t\"\n  shows \"(\\<forall>k. (a * 2^t + b) \\<exclamdown> k \\<le> (c * 2^t + d) \\<exclamdown> k) \\<longleftrightarrow> (\\<forall>l. a \\<exclamdown> l \\<le> c \\<exclamdown> l \\<and> b \\<exclamdown> l \\<le> d \\<exclamdown> l)\"\nproof -\n  have shift: \"(\\<forall>k. (a * 2^t) \\<exclamdown> k \\<le> (c * 2^t) \\<exclamdown> k) \\<longleftrightarrow> (\\<forall>l. a \\<exclamdown> l \\<le> c \\<exclamdown> l)\" (is \"?P \\<longleftrightarrow> ?Q\")\n  proof\n    assume P: ?P\n    show ?Q using P aux2_digit_lt_linear by auto\n  next\n    assume Q: ?Q\n    show ?P using Q aux3_digit_lt_linear by auto\n  qed\n\n  have main: \"(\\<forall>k. (a * 2^t + b) \\<exclamdown> k \\<le> (c * 2^t + d) \\<exclamdown> k \\<longleftrightarrow> ((a * 2^t) \\<exclamdown> k \\<le> (c * 2^t) \\<exclamdown> k \\<and> b \\<exclamdown> k \\<le> d \\<exclamdown> k))\"\n    using aux_digit_lt_linear b d by auto\n\n  from main shift show ?thesis by auto\nqed\n\ntext \\<open>Sufficient bitwise (digitwise) condition for the non-strict standard order of natural numbers\\<close>\n\nlemma digitwise_leq: \n  assumes \"b>1\"\n  shows \"\\<forall>t. nth_digit x t b \\<le> nth_digit y t b \\<Longrightarrow> x \\<le> y\"\nproof -\n  assume asm: \"\\<forall>t. nth_digit x t b \\<le> nth_digit y t b\"\n  define r where \"r \\<equiv>(if x>y then x else y)\"\n  have \"x = (\\<Sum>k<x. (nth_digit x k b) * b ^ k)\" \n    using digit_gen_sum_repr_variant \\<open>b>1\\<close> by auto\n  hence x: \"x = (\\<Sum>k=0..<r. (nth_digit x k b) * b ^ k)\" \n    using atLeast0LessThan r_def digit_gen_sum_index_variant \\<open>b>1\\<close> \n    by (metis (full_types) linorder_neqE_nat)\n  have \"y = (\\<Sum>k<y. (nth_digit y k b) * b ^ k)\" \n    using digit_gen_sum_repr_variant \\<open>b>1\\<close> by auto\n  hence y: \"y = (\\<Sum>k=0..<r. (nth_digit y k b) * b ^ k)\"\n    using atLeast0LessThan r_def digit_gen_sum_index_variant \\<open>b>1\\<close> by auto\n  show ?thesis using asm x y \n    sum_mono[of \"{0..<r}\" \"\\<lambda>k. nth_digit x k b * b^k\" \"\\<lambda>k. nth_digit y k b * b^k\"] \n    by auto\nqed\n\nsubsection \\<open>Binary masking\\<close>\n\ntext \\<open>Preliminary result on the standard non-strict of natural numbers\\<close>\n\nlemma bitwise_leq: \"(\\<forall>k. a \\<exclamdown> k \\<le>  b \\<exclamdown> k) \\<longrightarrow> a \\<le> b\"\n  using digitwise_leq[of 2] by (simp add: nth_digit_base2_equiv)\n\ntext \\<open>cf. \\<^cite>\\<open>h10lecturenotes\\<close> section 2.6.2 on \"Binary Masking\"\\<close>\ntext \\<open>Again, the equivalence to the definition there will be proved in a later lemma.\\<close>\n\nfun masks :: \"nat => nat => bool\" (infix \"\\<preceq>\" 49) where\n  \"masks 0 _ = True\" |\n  \"masks a b = ((a div 2 \\<preceq> b div 2) \\<and> (a mod 2 \\<le> b mod 2))\"\n\nlemma masks_substr: \"a \\<preceq> b \\<Longrightarrow> (a div (2^k) \\<preceq> b div (2^k))\"\nproof (induction k)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc k)\n  moreover\n  {\n    fix ka :: nat\n    assume a1: \"a div 2 ^ ka \\<preceq> b div 2 ^ ka\"\n\n    have f2: \"\\<forall>n na nb. (nb::nat) div na div n = nb div n div na\"\n      by (metis (no_types) div_mult2_eq semiring_normalization_rules(7))\n\n    then have f3: \"\\<forall>n na nb nc.\n                    (nc div nb = 0 \\<or> nc div 2 div nb \\<preceq> na div 2 div n) \\<or> \\<not> nc div nb \\<preceq> na div n\"\n      by (metis (no_types) masks.elims(2))\n\n    {\n      assume \"\\<exists>n. a div n div 2 ^ ka \\<noteq> 0\" then have \"a div 2 ^ ka \\<noteq> 0\" using f2 by (metis div_0)\n      then have \"a div 2 div 2 ^ ka \\<preceq> b div 2 div 2 ^ ka\" using f3 a1 by meson\n    }\n    then have \"a div (2 * 2 ^ ka) \\<preceq> b div (2 * 2 ^ ka)\"\n      by (metis (no_types) div_mult2_eq masks.simps(1))\n  }\n  ultimately show ?case by simp\nqed\n\nlemma masks_digit_leq:\"(a \\<preceq> b) \\<Longrightarrow> (nth_bit a k) \\<le> (nth_bit b k)\"\nproof (induction k arbitrary: a b)\n  case 0\n  then show ?case\n    by (metis add_cancel_left_right bitAND_nat.elims div_by_1 le0 masks.simps(2) power_0\n              mod_mult_self1_is_0 mod_mult_self4 nth_bit_def)\nnext\n  case (Suc k)\n  then show ?case\n    by (simp add: nth_bit_def)\n       (metis div_mult2_eq masks_substr nth_bit_def pow.simps(1) power_numeral)\nqed\n\nlemma masks_leq_equiv:\"(a \\<preceq> b) \\<longleftrightarrow> (\\<forall>k. (nth_bit a k) \\<le> (nth_bit b k))\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?P\"\n  then show \"?Q\" using masks_digit_leq by auto\nnext\n  assume \"?Q\"\n  then show \"?P\" using nth_bit_def\n  proof (induct a b rule: masks.induct)\n    case (1 uu)\n    then show ?case by simp\n  next\n    case (2 v b)\n    then show ?case by simp (metis drop_bit_Suc drop_bit_eq_div div_by_1 power.simps(1))\n  qed\nqed\n\nlemma masks_leq:\"a \\<preceq> b \\<longrightarrow> a \\<le> b\"\n  using masks_leq_equiv bitwise_leq by simp\n\nlemma mask_linear:\n  fixes a b c d t :: nat\n  assumes b: \"b < (2::nat)^t\"\n  assumes d: \"d < (2::nat)^t\"\n  shows \"((a * 2^t + b \\<preceq> c * 2^t + d) \\<longleftrightarrow> (a \\<preceq> c \\<and> b \\<preceq> d))\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof -\n  have \"?P \\<longleftrightarrow> (\\<forall>k. (a * 2^t + b) \\<exclamdown> k \\<le> (c * 2^t + d) \\<exclamdown> k)\" using masks_leq_equiv by auto\n  also have \"... \\<longleftrightarrow> (\\<forall>k. a \\<exclamdown> k \\<le> c \\<exclamdown> k \\<and> b \\<exclamdown> k \\<le> d \\<exclamdown> k)\" using b d digit_lt_linear by auto\n  also have \"... \\<longleftrightarrow> a \\<preceq> c \\<and> b \\<preceq> d\" using masks_leq_equiv by auto\n  finally show ?thesis by auto\nqed\n\nlemma aux1_lm0241_pow2_up_bound:\"(\\<exists>(p::nat). (a::nat) < 2^(Suc p))\"\n  by (induction a) (use less_exp in fastforce)+\n\nlemma aux2_lm0241_single_digit_binom:\n  assumes \"1 \\<ge> (a::nat)\"\n  assumes \"1 \\<ge> (b::nat)\"\n  shows \"\\<not>(a = 1 \\<and> b = 1) \\<longleftrightarrow> ((a + b) choose b) = 1\" (is \"?P \\<longleftrightarrow> ?Q\")\n  using assms(1) assms(2)\n  by (metis Suc_eq_plus1 add.commute add_cancel_right_left add_eq_if\n              binomial_n_0 choose_one le_add2 le_antisym zero_neq_one)\n\nlemma aux3_lm0241_binom_bounds:\n  assumes \"1 \\<ge> (m::nat)\"\n  assumes \"1 \\<ge> (n::nat)\"\n  shows \"1 \\<ge> m choose n\"\n  using assms(1) assms(2) le_Suc_eq by auto\n\nlemma aux4_lm0241_prod_one:\n  fixes f::\"(nat \\<Rightarrow> nat)\"\n  assumes \"(\\<forall>x. (1 \\<ge> f x))\"\n  shows \"(\\<Prod>k \\<le> n. (f k)) = 1 \\<longrightarrow> (\\<forall>k. k \\<le> n \\<longrightarrow> f k = 1)\" (is \"?P \\<longrightarrow> ?Q\")\nproof(rule ccontr)\n  assume assm:\"\\<not>(?P \\<longrightarrow> ?Q)\"\n  hence f_zero:\"\\<exists>r. r \\<le> n \\<and> f r \\<noteq> 1\" by simp\n  then obtain r where \"f r \\<noteq> 1\"  and \"r \\<le> n\" by blast\n  hence \"f r = 0\" using assms le_antisym not_less by blast\n  hence contr:\"(\\<Prod>k \\<le> n. f k) = 0\" using \\<open>r \\<le> n\\<close> by auto\n  then show False using assm contr by simp\nqed\n\nlemma aux5_lm0241:\n  \"(\\<forall>i. (nth_bit (a + b) i) choose (nth_bit b i) = 1) \\<longrightarrow>\n   \\<not>(nth_bit a i = 1 \\<and> nth_bit b i = 1)\"\n   (is \"?P \\<longrightarrow> ?Q i\")\nproof(rule ccontr)\n  assume assm:\"\\<not>(?P \\<longrightarrow> ?Q i)\"\n  hence \"(\\<exists>i. \\<not>?Q i)\" by blast\n  then obtain i where contr:\"\\<not>?Q i\" and i_minimal:\"(\\<forall>j < i. ?Q j)\" \n    using obtain_smallest[of \\<open>\\<lambda>i. \\<not>?Q i\\<close>] by auto\n  hence \"\\<forall>j. j < i \\<longrightarrow> nth_bit a j * nth_bit b j = 0\" by (simp add: nth_bit_def)\n  hence \"\\<forall>j. j < i \\<longrightarrow> ((nth_bit a j = 0 \\<and> nth_bit b j = 1) \\<or>\n                            (nth_bit a j = 1 \\<and> nth_bit b j = 0) \\<or>\n                            (nth_bit a j = 0 \\<and> nth_bit b j = 0))\"\n      by (auto simp add: nth_bit_def)\n  hence \"\\<forall>j. j < i \\<longrightarrow> nth_bit a j + nth_bit b j \\<le> 1\" by auto\n  hence \"bin_carry a b i = 0\"\n    using no_carry by (metis contr add_self_mod_2 assm choose_one one_neq_zero)\n  hence f0:\"nth_bit (a + b) i = (nth_bit a i + nth_bit b i) mod 2\"\n    by(auto simp add:sum_digit_formula)\n  have \"... = 0\" using contr by auto\n  hence \"(nth_bit (a + b) i) choose (nth_bit b i) = 0\" using f0 contr by auto\n  then show False using assm by fastforce\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Digit_Expansions/Binary_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7724926216472441}}
{"text": "theory Matching\nimports Main\nbegin\n\ntype_synonym label = nat\n\nsection \\<open>Definitions\\<close>\n\ndefinition finite_graph :: \"'v set => ('v * 'v) set \\<Rightarrow> bool\" where\n  \"finite_graph V E = (finite V \\<and> finite E \\<and> \n  (\\<forall> e \\<in> E. fst e \\<in> V \\<and> snd e \\<in> V \\<and> fst e ~= snd e))\"\n\ndefinition degree :: \"('v * 'v) set \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n  \"degree E v = card {e \\<in> E. fst e = v \\<or> snd e = v}\"\n\ndefinition edge_as_set :: \"('v * 'v) \\<Rightarrow> 'v set\" where\n  \"edge_as_set e = {fst e, snd e}\"\n\ndefinition N :: \"'v set \\<Rightarrow> ('v \\<Rightarrow> label) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"N V L i = card {v \\<in> V. L v = i}\"\n\ndefinition weight:: \"label set \\<Rightarrow> (label \\<Rightarrow> nat) \\<Rightarrow> nat\" where\n  \"weight LV f = f 1 + (\\<Sum>i\\<in>LV. (f i) div 2)\"\n\ndefinition OSC :: \"('v \\<Rightarrow> label) \\<Rightarrow> ('v * 'v) set \\<Rightarrow> bool\" where\n  \"OSC L E = (\\<forall>e \\<in> E. L (fst e) = 1 \\<or> L (snd e) = 1 \\<or> \n                     L (fst e) = L (snd e) \\<and> L (fst e) > 1)\"\n\ndefinition disjoint_edges :: \"('v * 'v) \\<Rightarrow> ('v * 'v) \\<Rightarrow> bool\" where\n  \"disjoint_edges e1 e2 = (fst e1 \\<noteq> fst e2 \\<and> fst e1 \\<noteq> snd e2 \\<and> \n                          snd e1 \\<noteq> fst e2 \\<and> snd e1 \\<noteq> snd e2)\"\n\ndefinition matching :: \"'v set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> bool\" where\n  \"matching V E M = (M \\<subseteq> E \\<and> finite_graph V E \\<and> \n  (\\<forall>e1 \\<in> M. \\<forall> e2 \\<in> M. e1 \\<noteq> e2 \\<longrightarrow> disjoint_edges e1 e2))\"\n\ndefinition matching_i :: \"nat \\<Rightarrow> 'v set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> ('v * 'v) set \\<Rightarrow>\n  ('v \\<Rightarrow> label) \\<Rightarrow> ('v * 'v) set\" where\n  \"matching_i i V E M L = {e \\<in> M. i=1 \\<and> (L (fst e) = i \\<or> L (snd e) = i) \n  \\<or> i>1 \\<and> L (fst e) = i \\<and> L (snd e) = i}\"\n\ndefinition V_i:: \"nat \\<Rightarrow> 'v set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> ('v * 'v) set \\<Rightarrow> \n                  ('v \\<Rightarrow> label) \\<Rightarrow> 'v set\" where\n  \"V_i i V E M L = \\<Union> (edge_as_set ` matching_i i V E M L)\"\n\ndefinition endpoint_inV :: \"'v set \\<Rightarrow> ('v * 'v) \\<Rightarrow> 'v\" where \n  \"endpoint_inV V e = (if fst e \\<in> V then fst e else snd e)\" \n\ndefinition relevant_endpoint :: \"('v \\<Rightarrow> label) \\<Rightarrow> 'v set \\<Rightarrow> \n                                 ('v * 'v) \\<Rightarrow> 'v\" where \n  \"relevant_endpoint L V e = (if L (fst e) = 1 then fst e else snd e)\"\n\nsection \\<open>Lemmas\\<close>\n\nlemma definition_of_range:\n  \"endpoint_inV V1 ` matching_i 1 V E M L = \n  { v. \\<exists> e \\<in> matching_i 1 V E M L. endpoint_inV V1 e = v }\" by auto\n\nlemma matching_i_edges_as_sets:\n  \"edge_as_set ` matching_i i V E M L = \n  { e1. \\<exists> (u, v) \\<in> matching_i i V E M L. edge_as_set (u, v) = e1}\" by auto\n\nlemma matching_disjointness:\n  assumes \"matching V E M\"\n  assumes \"e1 \\<in> M\"\n  assumes \"e2 \\<in> M\"\n  assumes \"e1 \\<noteq> e2\"\n  shows  \"edge_as_set e1 \\<inter> edge_as_set e2 = {}\"\n  using assms \n  by (auto simp add: edge_as_set_def disjoint_edges_def matching_def)\n\nlemma expand_set_containment:\n  assumes \"matching V E M\"\n  assumes \"e \\<in> M\"\n  shows \"e \\<in> E\"\n  using assms\n  by (auto simp add:matching_def)\n\ntheorem injectivity:\n  assumes is_osc: \"OSC L E\"\n  assumes is_m: \"matching V E M\"\n  assumes e1_in_M1: \"e1 \\<in> matching_i 1 V E M L\"\n      and e2_in_M1: \"e2 \\<in> matching_i 1 V E M L\"\n  assumes diff: \"(e1 \\<noteq> e2)\"\n  shows \"endpoint_inV {v \\<in> V. L v = 1} e1 \\<noteq> endpoint_inV {v \\<in> V. L v = 1} e2\"\nproof -\n  from e1_in_M1 have \"e1 \\<in> M\" by (auto simp add: matching_i_def)\n  moreover\n  from e2_in_M1 have \"e2 \\<in> M\" by (auto simp add: matching_i_def)\n  ultimately\n  have disjoint_edge_sets: \"edge_as_set e1 \\<inter> edge_as_set e2 = {}\" \n    using diff is_m matching_disjointness by fast\n  then show ?thesis by (auto simp add: edge_as_set_def endpoint_inV_def)\nqed\n\nsubsection \\<open>\\<open>|M1| \\<le> n1\\<close>\\<close>\n\nlemma card_M1_le_NVL1: \n  assumes \"matching V E M\"\n  assumes \"OSC L E\"\n  shows \"card (matching_i 1 V E M L) \\<le> ( N V L 1)\"\nproof -\n  let ?f = \"endpoint_inV {v \\<in> V. L v = 1}\"\n  let ?A = \"matching_i 1 V E M L\"\n  let ?B = \"{v \\<in> V. L v = 1}\"\n  have \"inj_on ?f ?A\" using assms injectivity\n    unfolding inj_on_def by blast\n  moreover have \"?f ` ?A \\<subseteq> ?B\"\n  proof -\n    {\n      fix e assume \"e \\<in> matching_i 1 V E M L\"\n      then have \"endpoint_inV {v \\<in> V. L v = 1} e \\<in> {v \\<in> V. L v = 1}\"\n        using assms\n        by (auto simp add: endpoint_inV_def matching_def\n          matching_i_def OSC_def finite_graph_def definition_of_range)\n    }\n    then show ?thesis using assms definition_of_range by blast\n  qed\n  moreover have \"finite ?B\" using assms\n    by (simp add: matching_def finite_graph_def)\n  ultimately show ?thesis unfolding N_def by (rule card_inj_on_le)\nqed\n\nlemma edge_as_set_inj_on_Mi: \n  assumes \"matching V E M\"\n  shows \"inj_on edge_as_set (matching_i i V E M L)\"\n  using assms\n  unfolding inj_on_def edge_as_set_def matching_def\n    disjoint_edges_def matching_i_def \n  by blast\n\nlemma card_Mi_eq_card_edge_as_set_Mi:\n  assumes \"matching V E M\"\n  shows \"card (matching_i i V E M L) = card (edge_as_set` matching_i i V E M L)\"\n  (is \"card ?Mi = card (?f ` _)\")\nproof -\n  from assms have \"bij_betw ?f ?Mi (?f ` ?Mi)\"\n    by (simp add: bij_betw_def matching_i_edges_as_sets edge_as_set_inj_on_Mi)\n  then show ?thesis by (rule bij_betw_same_card)\nqed\n\nlemma card_edge_as_set_Mi_twice_card_partitions:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"2 * card (edge_as_set`matching_i i V E M L) \n  = card (V_i i V E M L)\" (is \"2 * card ?C = card ?Vi\")\nproof -\n  from assms have 1: \"finite (\\<Union> ?C)\" \n    by (auto simp add: matching_def finite_graph_def \n      matching_i_def edge_as_set_def finite_subset)\n  show ?thesis unfolding V_i_def\n  proof (rule card_partition)\n    show \"finite ?C\" using 1 by (rule finite_UnionD)\n  next\n    show \"finite (\\<Union> ?C)\" using 1 .\n  next\n    fix c assume \"c \\<in> ?C\" then show \"card c = 2\"\n    proof (rule imageE)\n      fix x \n      assume 2: \"c = edge_as_set x\" and 3: \"x \\<in> matching_i i V E M L\"\n      with assms have \"x \\<in> E\" \n        unfolding matching_i_def matching_def by blast\n      then have \"fst x \\<noteq> snd x\" using assms 3 \n        by (auto simp add: matching_def finite_graph_def)\n      with 2 show ?thesis by (auto simp add: edge_as_set_def)\n    qed\n  next\n    fix x1 x2\n    assume 4: \"x1 \\<in> ?C\" and 5: \"x2 \\<in> ?C\" and 6: \"x1 \\<noteq> x2\"\n    {\n      fix e1 e2\n      assume 7: \"x1 = edge_as_set e1\" \"e1 \\<in> matching_i i V E M L\"\n        \"x2 = edge_as_set e2\" \"e2 \\<in> matching_i i V E M L\"\n      from assms have \"matching V E M\" by simp\n      moreover\n      from 7 assms have \"e1 \\<in> M\" and \"e2 \\<in> M\"\n        by (simp_all add: matching_i_def)\n      moreover from 6 7 have \"e1 \\<noteq> e2\" by blast\n      ultimately have \"x1 \\<inter> x2 = {}\" unfolding 7 \n        by (rule matching_disjointness)\n    }\n    with 4 5 show \"x1 \\<inter> x2 = {}\" by clarsimp\n  qed\nqed\n\nlemma card_Mi_twice_card_Vi:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"2 * card (matching_i i V E M L) = card (V_i i V E M L)\"\nproof -\n  from assms have \"finite (V_i i V E M L)\"\n    by (auto simp add: edge_as_set_def finite_subset\n      matching_def finite_graph_def V_i_def matching_i_def )\n  with assms show ?thesis \n    by (simp add: card_Mi_eq_card_edge_as_set_Mi \n      card_edge_as_set_Mi_twice_card_partitions V_i_def)\nqed\n\nlemma card_Mi_le_floor_div_2_Vi:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"card (matching_i i V E M L) \\<le> (card (V_i i V E M L)) div 2\"\n  using card_Mi_twice_card_Vi[OF assms]\n  by arith\n\nlemma card_Vi_le_NVLi:\n  assumes \"i>1 \\<and> matching V E M\"\n  shows \"card (V_i i V E M L) \\<le> N V L i\"\n  unfolding N_def\nproof (rule card_mono)\n  show \"finite {v \\<in> V. L v = i}\" using assms \n    by (simp add: matching_def finite_graph_def)\nnext\n  let ?A = \"edge_as_set ` matching_i i V E M L\"\n  let ?C = \"{v \\<in> V. L v = i}\" \n  show \"V_i i V E M L \\<subseteq> ?C\" using assms unfolding V_i_def\n  proof (intro Union_least)\n    fix X assume \"X \\<in> ?A\"\n    with assms have \"\\<exists>x \\<in> matching_i i V E M L. edge_as_set x = X\"\n      by (simp add: matching_i_edges_as_sets)\n    with assms show \"X \\<subseteq> ?C\" \n      unfolding finite_graph_def matching_def\n        matching_i_def edge_as_set_def by blast\n  qed\nqed\n\nsubsection \\<open>\\<open>|Mi| \\<le> \\<lfloor>ni/2\\<rfloor>\\<close>\\<close>\n\nlemma card_Mi_le_floor_div_2_NVLi:\n  assumes \"OSC L E \\<and> matching V E M \\<and> i > 1\"\n  shows \"card (matching_i i V E M L) \\<le> (N V L i) div 2\"\nproof -  \n  from assms have \"card (V_i i V E M L) \\<le> (N V L i)\"\n    by (simp add: card_Vi_le_NVLi) \n  then have \"card (V_i i V E M L) div 2 \\<le> (N V L i) div 2\"\n    by simp\n  moreover from assms have \n    \"card (matching_i i V E M L) \\<le> card (V_i i V E M L) div 2\"\n    by (intro card_Mi_le_floor_div_2_Vi)\n  ultimately show ?thesis by auto\nqed\nsubsection \\<open>\\<open>|M| \\<le> \\<Sum>|Mi|\\<close>\\<close>\nlemma card_M_le_sum_card_Mi: \nassumes \"matching V E M\" and \"OSC L E\"\nshows \"card M \\<le> (\\<Sum> i \\<in> L`V. card (matching_i i V E M L))\"\n  (is \"card _ \\<le> ?CardMi\")\nproof -\n  let ?UnMi = \"\\<Union>x \\<in> L`V. matching_i x V E M L\"\n  from assms have 1: \"finite ?UnMi\"\n    by (auto simp add: matching_def \n      finite_graph_def matching_i_def finite_subset)\n  {\n    fix e assume e_inM: \"e \\<in> M\"\n    let ?v = \"relevant_endpoint L V e\"\n    have 1: \"e \\<in> matching_i (L ?v) V E M L\" using assms e_inM\n      proof cases\n        assume \"L (fst e) = 1\"\n        thus ?thesis using assms e_inM \n          by (simp add: relevant_endpoint_def matching_i_def)\n      next\n        assume a: \"L (fst e) \\<noteq> 1\" \n        have \"L (fst e) = 1 \\<or> L (snd e) = 1 \n          \\<or>  (L (fst e) = L (snd e) \\<and> L (fst e) >1)\"\n          using assms e_inM unfolding OSC_def \n          by (blast intro: expand_set_containment)\n        thus ?thesis using assms e_inM a \n          by (auto simp add: relevant_endpoint_def matching_i_def)\n      qed\n      have 2: \"?v \\<in> V\" using assms e_inM \n        by (auto simp add: matching_def \n          relevant_endpoint_def matching_i_def finite_graph_def)\n      then have \"\\<exists> v \\<in> V. e \\<in> matching_i (L v) V E M L\" using assms 1 2\n        by (intro bexI) \n    }\n    with assms have \"M \\<subseteq> ?UnMi\" by (auto)\n    with assms and 1 have \"card M \\<le> card ?UnMi\" by (intro card_mono)\n    moreover from assms have \"card ?UnMi = ?CardMi\"\n    proof (intro card_UN_disjoint) \n      show \"finite (L`V)\" using assms \n        by (simp add: matching_def finite_graph_def)\n    next \n      show \"\\<forall>i\\<in>L`V. finite (matching_i i V E M L)\" using assms\n        unfolding matching_def finite_graph_def matching_i_def\n        by (blast intro: finite_subset)\n    next \n      show \"\\<forall>i \\<in> L`V. \\<forall>j \\<in> L`V. i \\<noteq> j \\<longrightarrow> \n        matching_i i V E M L \\<inter> matching_i j V E M L = {}\" using assms\n        by (auto simp add: matching_i_def)\n    qed\n  ultimately show ?thesis by simp\nqed\n\ntheorem card_M_le_weight_NVLi:\n  assumes \"matching V E M\" and \"OSC L E\"\n  shows \"card M \\<le> weight {i \\<in> L ` V. i > 1} (N V L)\" (is \"_ \\<le> ?W\")\nproof -\n  let ?M01 = \"\\<Sum>i| i \\<in> L`V \\<and> (i=1 \\<or> i=0). card (matching_i i V E M L)\"\n  let ?Mgr1 = \"\\<Sum>i| i \\<in> L`V \\<and> 1 < i. card (matching_i i V E M L)\"\n  let ?Mi = \"\\<Sum> i\\<in>L`V. card (matching_i i V E M L)\"\n  have \"card M \\<le> ?Mi\" using assms by (rule card_M_le_sum_card_Mi) \n  moreover\n  have \"?Mi \\<le> ?W\"\n  proof -\n    let ?A = \"{i \\<in> L ` V. i = 1 \\<or> i = 0}\"\n    let ?B = \"{i \\<in> L ` V. 1 < i}\"\n    let ?g = \"\\<lambda> i. card (matching_i i V E M L)\"\n    let ?set01 = \"{ i. i : L ` V & (i = 1 | i = 0)}\"\n    have a: \"L ` V = ?A \\<union> ?B\" using assms by auto\n    have \"finite V\" using assms \n      by (simp add: matching_def finite_graph_def)\n    have b: \"sum ?g (?A \\<union> ?B) = sum ?g ?A + sum ?g ?B\"\n      using assms \\<open>finite V\\<close> by (auto intro: sum.union_disjoint)    \n    have 1: \"?Mi = ?M01+ ?Mgr1\" using assms a b \n      by (simp add: matching_def finite_graph_def)\n    moreover\n    have 0: \"card (matching_i 0 V E M L) = 0\" using assms\n      by (simp add: matching_i_def)\n      have 2: \"?M01 \\<le> N V L 1\" \n      proof cases\n        assume a: \"1 \\<in> L`V\"\n        have \"?M01 = card (matching_i 1 V E M L)\" \n        proof cases\n          assume b: \"0 \\<in> L`V\"\n          with a assms have  \"?set01 = {0, 1}\" by blast\n          thus ?thesis using assms 0 by simp\n        next\n          assume b: \"0 \\<notin> L`V\"\n          with a have \"?set01 = {1}\" by (auto simp del:One_nat_def)\n          thus ?thesis by simp\n        qed\n        thus ?thesis using assms a \n          by (simp del: One_nat_def, intro card_M1_le_NVL1)\n      next\n        assume a: \"1 \\<notin> L`V\"\n        show ?thesis\n        proof cases\n          assume b: \"0 \\<in> L`V\"\n          with a assms have  \"?set01 = {0}\" by (auto simp del:One_nat_def)\n          thus ?thesis using assms 0 by auto\n        next\n          assume b: \"0 \\<notin> L`V\"\n          with a have \"?set01 = {}\" by (auto simp del:One_nat_def)\n            then have \"?M01 = (\\<Sum>i\\<in>{}. card (matching_i i V E M L))\" by auto\n            thus ?thesis by simp\n          qed\n        qed\n      moreover\n      have 3: \"?Mgr1 \\<le> (\\<Sum>i|i\\<in>L`V \\<and> 1 < i. N V L i div 2)\" using assms \n        by (intro sum_mono card_Mi_le_floor_div_2_NVLi, simp)\n    ultimately\n    show ?thesis using 1 2 3 assms by (simp add: weight_def)\n  qed\n  ultimately show ?thesis by simp\nqed\n\nsection \\<open>Final Theorem\\<close>\ntext\\<open>The following theorem is due to Edmond~\\cite{Edmonds:matching}:\\<close>\n\ntheorem maximum_cardinality_matching:\n  assumes \"matching V E M\" and \"OSC L E\"\n  and \"card M = weight {i \\<in> L ` V. i > 1} (N V L)\"\n  and \"matching V E M'\"\n  shows \"card M' \\<le> card M\"\n  using assms card_M_le_weight_NVLi\n  by simp\n\ntext\\<open>The widely used algorithmic library LEDA has a certifying algorithm for maximum cardinality matching.\nThis Isabelle proof is part of the work done to verify the checker of this certifying algorithm. For more information see \\cite{VerificationofCertifyingComputations}.\\<close>\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Max-Card-Matching/Matching.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7724457340106998}}
{"text": "theory Chapter13_7\nimports \"HOL-IMP.Abs_Int2\" \"Short_Theory\"\nbegin\n\ntext{*\n\\setcounter{exercise}{15}\n\\exercise\nGive a readable proof that if @{text \"\\<gamma> ::\"} \\noquotes{@{typ[source]\"'a::lattice \\<Rightarrow> 'b::lattice\"}}\nis a monotone function, then @{prop \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"}:\n*}\n\nlemma fixes \\<gamma> :: \"'a::lattice \\<Rightarrow> 'b :: lattice\"\nassumes mono: \"\\<And>x y. x \\<le> y \\<Longrightarrow> \\<gamma> x \\<le> \\<gamma> y\"\nshows \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"\n(* your definition/proof here *)\n\ntext{*\nGive an example of two lattices and a monotone @{text \\<gamma>}\nwhere @{prop\"\\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2 \\<le> \\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2)\"} does not hold.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider a simple sign analysis based on this abstract domain:\n*}\n\ndatatype sign = None | Neg | Pos0 | Any\n\nfun \\<gamma> :: \"sign \\<Rightarrow> val set\" where\n\"\\<gamma> None = {}\" |\n\"\\<gamma> Neg = {i. i < 0}\" |\n\"\\<gamma> Pos0 = {i. i \\<ge> 0}\" |\n\"\\<gamma> Any = UNIV\"\n\ntext{*\nDefine inverse analyses for ``@{text\"+\"}'' and ``@{text\"<\"}''\nand prove the required correctness properties:\n*}\n\nfun inv_plus' :: \"sign \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n(* your definition/proof here *)\n\nlemma\n  \"\\<lbrakk> inv_plus' a a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; i1+i2 \\<in> \\<gamma> a \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2' \"\n(* your definition/proof here *)\n\nfun inv_less' :: \"bool \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n(* your definition/proof here *)\n\nlemma\n  \"\\<lbrakk> inv_less' bv a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; (i1<i2) = bv \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2'\"\n(* your definition/proof here *)\n\ntext{*\n\\indent\nFor the ambitious: turn the above fragment into a full-blown abstract interpreter\nby replacing the interval analysis in theory @{short_theory \"Abs_Int2\"}@{text\"_ivl\"}\nby a sign analysis.\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "brando90", "repo": "isabelle-gym", "sha": "f4d231cb9f625422e873aa2c9c2c6f22b7da4b27", "save_path": "github-repos/isabelle/brando90-isabelle-gym", "path": "github-repos/isabelle/brando90-isabelle-gym/isabelle-gym-f4d231cb9f625422e873aa2c9c2c6f22b7da4b27/isar_brandos_resources/templates/Chapter13_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7724457317208285}}
{"text": "(*  Title:      HOL/Number_Theory/Residues.thy\n    Author:     Jeremy Avigad\n\nAn algebraic treatment of residue rings, and resulting proofs of\nEuler's theorem and Wilson's theorem.\n*)\n\nsection \\<open>Residue rings\\<close>\n\ntheory Residues\nimports\n  Cong\n  \"HOL-Algebra.Multiplicative_Group\"\n  Totient\nbegin\n\ndefinition QuadRes :: \"int \\<Rightarrow> int \\<Rightarrow> bool\"\n  where \"QuadRes p a = (\\<exists>y. ([y^2 = a] (mod p)))\"\n\ndefinition Legendre :: \"int \\<Rightarrow> int \\<Rightarrow> int\"\n  where \"Legendre a p =\n    (if ([a = 0] (mod p)) then 0\n     else if QuadRes p a then 1\n     else -1)\"\n\n\nsubsection \\<open>A locale for residue rings\\<close>\n\ndefinition residue_ring :: \"int \\<Rightarrow> int ring\"\n  where\n    \"residue_ring m =\n      \\<lparr>carrier = {0..m - 1},\n       monoid.mult = \\<lambda>x y. (x * y) mod m,\n       one = 1,\n       zero = 0,\n       add = \\<lambda>x y. (x + y) mod m\\<rparr>\"\n\nlocale residues =\n  fixes m :: int and R (structure)\n  assumes m_gt_one: \"m > 1\"\n  defines \"R \\<equiv> residue_ring m\"\nbegin\n\nlemma abelian_group: \"abelian_group R\"\nproof -\n  have \"\\<exists>y\\<in>{0..m - 1}. (x + y) mod m = 0\" if \"0 \\<le> x\" \"x < m\" for x\n  proof (cases \"x = 0\")\n    case True\n    with m_gt_one show ?thesis by simp\n  next\n    case False\n    then have \"(x + (m - x)) mod m = 0\"\n      by simp\n    with m_gt_one that show ?thesis\n      by (metis False atLeastAtMost_iff diff_ge_0_iff_ge diff_left_mono int_one_le_iff_zero_less less_le)\n  qed\n  with m_gt_one show ?thesis\n    by (fastforce simp add: R_def residue_ring_def mod_add_right_eq ac_simps  intro!: abelian_groupI)\nqed\n\nlemma comm_monoid: \"comm_monoid R\"\n  unfolding R_def residue_ring_def\n  apply (rule comm_monoidI)\n    using m_gt_one  apply auto\n  apply (metis mod_mult_right_eq mult.assoc mult.commute)\n  apply (metis mult.commute)\n  done\n\nlemma cring: \"cring R\"\n  apply (intro cringI abelian_group comm_monoid)\n  unfolding R_def residue_ring_def\n  apply (auto simp add: comm_semiring_class.distrib mod_add_eq mod_mult_left_eq)\n  done\n\nend\n\nsublocale residues < cring\n  by (rule cring)\n\n\ncontext residues\nbegin\n\ntext \\<open>\n  These lemmas translate back and forth between internal and\n  external concepts.\n\\<close>\n\nlemma res_carrier_eq: \"carrier R = {0..m - 1}\"\n  by (auto simp: R_def residue_ring_def)\n\nlemma res_add_eq: \"x \\<oplus> y = (x + y) mod m\"\n  by (auto simp: R_def residue_ring_def)\n\nlemma res_mult_eq: \"x \\<otimes> y = (x * y) mod m\"\n  by (auto simp: R_def residue_ring_def)\n\nlemma res_zero_eq: \"\\<zero> = 0\"\n  by (auto simp: R_def residue_ring_def)\n\nlemma res_one_eq: \"\\<one> = 1\"\n  by (auto simp: R_def residue_ring_def units_of_def)\n\nlemma res_units_eq: \"Units R = {x. 0 < x \\<and> x < m \\<and> coprime x m}\"\n  using m_gt_one\n  apply (auto simp add: Units_def R_def residue_ring_def ac_simps invertible_coprime intro: ccontr)\n  apply (subst (asm) coprime_iff_invertible'_int)\n   apply (auto simp add: cong_def)\n  done\n\nlemma res_neg_eq: \"\\<ominus> x = (- x) mod m\"\n  using m_gt_one unfolding R_def a_inv_def m_inv_def residue_ring_def\n  apply simp\n  apply (rule the_equality)\n   apply (simp add: mod_add_right_eq)\n   apply (simp add: add.commute mod_add_right_eq)\n  apply (metis add.right_neutral minus_add_cancel mod_add_right_eq mod_pos_pos_trivial)\n  done\n\nlemma finite [iff]: \"finite (carrier R)\"\n  by (simp add: res_carrier_eq)\n\nlemma finite_Units [iff]: \"finite (Units R)\"\n  by (simp add: finite_ring_finite_units)\n\ntext \\<open>\n  The function \\<open>a \\<mapsto> a mod m\\<close> maps the integers to the\n  residue classes. The following lemmas show that this mapping\n  respects addition and multiplication on the integers.\n\\<close>\n\nlemma mod_in_carrier [iff]: \"a mod m \\<in> carrier R\"\n  unfolding res_carrier_eq\n  using insert m_gt_one by auto\n\nlemma add_cong: \"(x mod m) \\<oplus> (y mod m) = (x + y) mod m\"\n  by (auto simp: R_def residue_ring_def mod_simps)\n\nlemma mult_cong: \"(x mod m) \\<otimes> (y mod m) = (x * y) mod m\"\n  by (auto simp: R_def residue_ring_def mod_simps)\n\nlemma zero_cong: \"\\<zero> = 0\"\n  by (auto simp: R_def residue_ring_def)\n\nlemma one_cong: \"\\<one> = 1 mod m\"\n  using m_gt_one by (auto simp: R_def residue_ring_def)\n\n(* FIXME revise algebra library to use 1? *)\nlemma pow_cong: \"(x mod m) [^] n = x^n mod m\"\n  using m_gt_one\n  apply (induct n)\n  apply (auto simp add: nat_pow_def one_cong)\n  apply (metis mult.commute mult_cong)\n  done\n\nlemma neg_cong: \"\\<ominus> (x mod m) = (- x) mod m\"\n  by (metis mod_minus_eq res_neg_eq)\n\nlemma (in residues) prod_cong: \"finite A \\<Longrightarrow> (\\<Otimes>i\\<in>A. (f i) mod m) = (\\<Prod>i\\<in>A. f i) mod m\"\n  by (induct set: finite) (auto simp: one_cong mult_cong)\n\nlemma (in residues) sum_cong: \"finite A \\<Longrightarrow> (\\<Oplus>i\\<in>A. (f i) mod m) = (\\<Sum>i\\<in>A. f i) mod m\"\n  by (induct set: finite) (auto simp: zero_cong add_cong)\n\nlemma mod_in_res_units [simp]:\n  assumes \"1 < m\" and \"coprime a m\"\n  shows \"a mod m \\<in> Units R\"\nproof (cases \"a mod m = 0\")\n  case True\n  with assms show ?thesis\n    by (auto simp add: res_units_eq gcd_red_int [symmetric])\nnext\n  case False\n  from assms have \"0 < m\" by simp\n  then have \"0 \\<le> a mod m\" by (rule pos_mod_sign [of m a])\n  with False have \"0 < a mod m\" by simp\n  with assms show ?thesis\n    by (auto simp add: res_units_eq gcd_red_int [symmetric] ac_simps)\nqed\n\nlemma res_eq_to_cong: \"(a mod m) = (b mod m) \\<longleftrightarrow> [a = b] (mod m)\"\n  by (auto simp: cong_def)\n\n\ntext \\<open>Simplifying with these will translate a ring equation in R to a congruence.\\<close>\nlemmas res_to_cong_simps =\n  add_cong mult_cong pow_cong one_cong\n  prod_cong sum_cong neg_cong res_eq_to_cong\n\ntext \\<open>Other useful facts about the residue ring.\\<close>\nlemma one_eq_neg_one: \"\\<one> = \\<ominus> \\<one> \\<Longrightarrow> m = 2\"\n  apply (simp add: res_one_eq res_neg_eq)\n  apply (metis add.commute add_diff_cancel mod_mod_trivial one_add_one uminus_add_conv_diff\n    zero_neq_one zmod_zminus1_eq_if)\n  done\n\nend\n\n\nsubsection \\<open>Prime residues\\<close>\n\nlocale residues_prime =\n  fixes p :: nat and R (structure)\n  assumes p_prime [intro]: \"prime p\"\n  defines \"R \\<equiv> residue_ring (int p)\"\n\nsublocale residues_prime < residues p\n  unfolding R_def residues_def\n  using p_prime apply auto\n  apply (metis (full_types) of_nat_1 of_nat_less_iff prime_gt_1_nat)\n  done\n\ncontext residues_prime\nbegin\n\nlemma p_coprime_left:\n  \"coprime p a \\<longleftrightarrow> \\<not> p dvd a\"\n  using p_prime by (auto intro: prime_imp_coprime dest: coprime_common_divisor)\n\nlemma p_coprime_right:\n  \"coprime a p  \\<longleftrightarrow> \\<not> p dvd a\"\n  using p_coprime_left [of a] by (simp add: ac_simps)\n\nlemma p_coprime_left_int:\n  \"coprime (int p) a \\<longleftrightarrow> \\<not> int p dvd a\"\n  using p_prime by (auto intro: prime_imp_coprime dest: coprime_common_divisor)\n\nlemma p_coprime_right_int:\n  \"coprime a (int p) \\<longleftrightarrow> \\<not> int p dvd a\"\n  using p_coprime_left_int [of a] by (simp add: ac_simps)\n\nlemma is_field: \"field R\"\nproof -\n  have \"0 < x \\<Longrightarrow> x < int p \\<Longrightarrow> coprime (int p) x\" for x\n    by (rule prime_imp_coprime) (auto simp add: zdvd_not_zless)\n  then show ?thesis\n    by (intro cring.field_intro2 cring)\n      (auto simp add: res_carrier_eq res_one_eq res_zero_eq res_units_eq ac_simps)\nqed\n\nlemma res_prime_units_eq: \"Units R = {1..p - 1}\"\n  apply (subst res_units_eq)\n  apply (auto simp add: p_coprime_right_int zdvd_not_zless)\n  done\n\nend\n\nsublocale residues_prime < field\n  by (rule is_field)\n\n\nsection \\<open>Test cases: Euler's theorem and Wilson's theorem\\<close>\n\nsubsection \\<open>Euler's theorem\\<close>\n\nlemma (in residues) totatives_eq:\n  \"totatives (nat m) = nat ` Units R\"\nproof -\n  from m_gt_one have \"\\<bar>m\\<bar> > 1\"\n    by simp\n  then have \"totatives (nat \\<bar>m\\<bar>) = nat ` abs ` Units R\"\n    by (auto simp add: totatives_def res_units_eq image_iff le_less)\n      (use m_gt_one zless_nat_eq_int_zless in force)\n  moreover have \"\\<bar>m\\<bar> = m\" \"abs ` Units R = Units R\"\n    using m_gt_one by (auto simp add: res_units_eq image_iff)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma (in residues) totient_eq:\n  \"totient (nat m) = card (Units R)\"\nproof  -\n  have *: \"inj_on nat (Units R)\"\n    by (rule inj_onI) (auto simp add: res_units_eq)\n  then show ?thesis\n    by (simp add: totient_def totatives_eq card_image)\nqed\n\nlemma (in residues_prime) totient_eq: \"totient p = p - 1\"\n  using totient_eq by (simp add: res_prime_units_eq)\n\nlemma (in residues) euler_theorem:\n  assumes \"coprime a m\"\n  shows \"[a ^ totient (nat m) = 1] (mod m)\"\nproof -\n  have \"a ^ totient (nat m) mod m = 1 mod m\"\n    by (metis assms finite_Units m_gt_one mod_in_res_units one_cong totient_eq pow_cong units_power_order_eq_one)\n  then show ?thesis\n    using res_eq_to_cong by blast\nqed\n\nlemma euler_theorem:\n  fixes a m :: nat\n  assumes \"coprime a m\"\n  shows \"[a ^ totient m = 1] (mod m)\"\nproof (cases \"m = 0 \\<or> m = 1\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  with assms show ?thesis\n    using residues.euler_theorem [of \"int m\" \"int a\"] cong_int_iff\n    by (auto simp add: residues_def gcd_int_def) fastforce\nqed\n\nlemma fermat_theorem:\n  fixes p a :: nat\n  assumes \"prime p\" and \"\\<not> p dvd a\"\n  shows \"[a ^ (p - 1) = 1] (mod p)\"\nproof -\n  from assms prime_imp_coprime [of p a] have \"coprime a p\"\n    by (auto simp add: ac_simps)\n  then have \"[a ^ totient p = 1] (mod p)\"\n     by (rule euler_theorem)\n  also have \"totient p = p - 1\"\n    by (rule totient_prime) (rule assms)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Wilson's theorem\\<close>\n\nlemma (in field) inv_pair_lemma: \"x \\<in> Units R \\<Longrightarrow> y \\<in> Units R \\<Longrightarrow>\n    {x, inv x} \\<noteq> {y, inv y} \\<Longrightarrow> {x, inv x} \\<inter> {y, inv y} = {}\"\n  apply auto\n  apply (metis Units_inv_inv)+\n  done\n\nlemma (in residues_prime) wilson_theorem1:\n  assumes a: \"p > 2\"\n  shows \"[fact (p - 1) = (-1::int)] (mod p)\"\nproof -\n  let ?Inverse_Pairs = \"{{x, inv x}| x. x \\<in> Units R - {\\<one>, \\<ominus> \\<one>}}\"\n  have UR: \"Units R = {\\<one>, \\<ominus> \\<one>} \\<union> \\<Union>?Inverse_Pairs\"\n    by auto\n  have \"(\\<Otimes>i\\<in>Units R. i) = (\\<Otimes>i\\<in>{\\<one>, \\<ominus> \\<one>}. i) \\<otimes> (\\<Otimes>i\\<in>\\<Union>?Inverse_Pairs. i)\"\n    apply (subst UR)\n    apply (subst finprod_Un_disjoint)\n         apply (auto intro: funcsetI)\n    using inv_one apply auto[1]\n    using inv_eq_neg_one_eq apply auto\n    done\n  also have \"(\\<Otimes>i\\<in>{\\<one>, \\<ominus> \\<one>}. i) = \\<ominus> \\<one>\"\n    apply (subst finprod_insert)\n        apply auto\n    apply (frule one_eq_neg_one)\n    using a apply force\n    done\n  also have \"(\\<Otimes>i\\<in>(\\<Union>?Inverse_Pairs). i) = (\\<Otimes>A\\<in>?Inverse_Pairs. (\\<Otimes>y\\<in>A. y))\"\n    apply (subst finprod_Union_disjoint)\n       apply (auto simp: pairwise_def disjnt_def)\n     apply (metis Units_inv_inv)+\n    done\n  also have \"\\<dots> = \\<one>\"\n    apply (rule finprod_one_eqI)\n     apply auto\n    apply (subst finprod_insert)\n        apply auto\n    apply (metis inv_eq_self)\n    done\n  finally have \"(\\<Otimes>i\\<in>Units R. i) = \\<ominus> \\<one>\"\n    by simp\n  also have \"(\\<Otimes>i\\<in>Units R. i) = (\\<Otimes>i\\<in>Units R. i mod p)\"\n    by (rule finprod_cong') (auto simp: res_units_eq)\n  also have \"\\<dots> = (\\<Prod>i\\<in>Units R. i) mod p\"\n    by (rule prod_cong) auto\n  also have \"\\<dots> = fact (p - 1) mod p\"\n    apply (simp add: fact_prod)\n    using assms\n    apply (subst res_prime_units_eq)\n    apply (simp add: int_prod zmod_int prod_int_eq)\n    done\n  finally have \"fact (p - 1) mod p = \\<ominus> \\<one>\" .\n  then show ?thesis\n    by (simp add: cong_def res_neg_eq res_one_eq zmod_int)\nqed\n\nlemma wilson_theorem:\n  assumes \"prime p\"\n  shows \"[fact (p - 1) = - 1] (mod p)\"\nproof (cases \"p = 2\")\n  case True\n  then show ?thesis\n    by (simp add: cong_def fact_prod)\nnext\n  case False\n  then show ?thesis\n    using assms prime_ge_2_nat\n    by (metis residues_prime.wilson_theorem1 residues_prime.intro le_eq_less_or_eq)\nqed\n\ntext \\<open>\n  This result can be transferred to the multiplicative group of\n  \\<open>\\<int>/p\\<int>\\<close> for \\<open>p\\<close> prime.\\<close>\n\nlemma mod_nat_int_pow_eq:\n  fixes n :: nat and p a :: int\n  shows \"a \\<ge> 0 \\<Longrightarrow> p \\<ge> 0 \\<Longrightarrow> (nat a ^ n) mod (nat p) = nat ((a ^ n) mod p)\"\n  by (simp add: int_one_le_iff_zero_less nat_mod_distrib order_less_imp_le nat_power_eq[symmetric])\n\ntheorem residue_prime_mult_group_has_gen:\n fixes p :: nat\n assumes prime_p : \"prime p\"\n shows \"\\<exists>a \\<in> {1 .. p - 1}. {1 .. p - 1} = {a^i mod p|i . i \\<in> UNIV}\"\nproof -\n  have \"p \\<ge> 2\"\n    using prime_gt_1_nat[OF prime_p] by simp\n  interpret R: residues_prime p \"residue_ring p\"\n    by (simp add: residues_prime_def prime_p)\n  have car: \"carrier (residue_ring (int p)) - {\\<zero>\\<^bsub>residue_ring (int p)\\<^esub>} = {1 .. int p - 1}\"\n    by (auto simp add: R.zero_cong R.res_carrier_eq)\n\n  have \"x [^]\\<^bsub>residue_ring (int p)\\<^esub> i = x ^ i mod (int p)\"\n    if \"x \\<in> {1 .. int p - 1}\" for x and i :: nat\n    using that R.pow_cong[of x i] by auto\n  moreover\n  obtain a where a: \"a \\<in> {1 .. int p - 1}\"\n    and a_gen: \"{1 .. int p - 1} = {a[^]\\<^bsub>residue_ring (int p)\\<^esub>i|i::nat . i \\<in> UNIV}\"\n    using field.finite_field_mult_group_has_gen[OF R.is_field]\n    by (auto simp add: car[symmetric] carrier_mult_of)\n  moreover\n  have \"nat ` {1 .. int p - 1} = {1 .. p - 1}\" (is \"?L = ?R\")\n  proof\n    have \"n \\<in> ?R\" if \"n \\<in> ?L\" for n\n      using that \\<open>p\\<ge>2\\<close> by force\n    then show \"?L \\<subseteq> ?R\" by blast\n    have \"n \\<in> ?L\" if \"n \\<in> ?R\" for n\n      using that \\<open>p\\<ge>2\\<close> by (auto intro: rev_image_eqI [of \"int n\"])\n    then show \"?R \\<subseteq> ?L\" by blast\n  qed\n  moreover\n  have \"nat ` {a^i mod (int p) | i::nat. i \\<in> UNIV} = {nat a^i mod p | i . i \\<in> UNIV}\" (is \"?L = ?R\")\n  proof\n    have \"x \\<in> ?R\" if \"x \\<in> ?L\" for x\n    proof -\n      from that obtain i where i: \"x = nat (a^i mod (int p))\"\n        by blast\n      then have \"x = nat a ^ i mod p\"\n        using mod_nat_int_pow_eq[of a \"int p\" i] a \\<open>p\\<ge>2\\<close> by auto\n      with i show ?thesis by blast\n    qed\n    then show \"?L \\<subseteq> ?R\" by blast\n    have \"x \\<in> ?L\" if \"x \\<in> ?R\" for x\n    proof -\n      from that obtain i where i: \"x = nat a^i mod p\"\n        by blast\n      with mod_nat_int_pow_eq[of a \"int p\" i] a \\<open>p\\<ge>2\\<close> show ?thesis\n        by auto\n    qed\n    then show \"?R \\<subseteq> ?L\" by blast\n  qed\n  ultimately have \"{1 .. p - 1} = {nat a^i mod p | i. i \\<in> UNIV}\"\n    by presburger\n  moreover from a have \"nat a \\<in> {1 .. p - 1}\" by force\n  ultimately show ?thesis ..\nqed\n\n\nsubsection \\<open>Upper bound for the number of $n$-th roots\\<close>\n\nlemma roots_mod_prime_bound:\n  fixes n c p :: nat\n  assumes \"prime p\" \"n > 0\"\n  defines \"A \\<equiv> {x\\<in>{..<p}. [x ^ n = c] (mod p)}\"\n  shows   \"card A \\<le> n\"\nproof -\n  define R where \"R = residue_ring (int p)\"\n  from assms(1) interpret residues_prime p R\n    by unfold_locales (simp_all add: R_def)\n  interpret R: UP_domain R \"UP R\" by (unfold_locales)\n\n  let ?f = \"UnivPoly.monom (UP R) \\<one>\\<^bsub>R\\<^esub> n \\<ominus>\\<^bsub>(UP R)\\<^esub> UnivPoly.monom (UP R) (int (c mod p)) 0\"\n  have in_carrier: \"int (c mod p) \\<in> carrier R\"\n    using prime_gt_1_nat[OF assms(1)] by (simp add: R_def residue_ring_def)\n  \n  have \"deg R ?f = n\"\n    using assms in_carrier by (simp add: R.deg_minus_eq)\n  hence f_not_zero: \"?f \\<noteq> \\<zero>\\<^bsub>UP R\\<^esub>\" using assms by (auto simp add : R.deg_nzero_nzero)\n  have roots_bound: \"finite {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>} \\<and>\n                     card {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>} \\<le> deg R ?f\"\n                    using finite in_carrier by (intro R.roots_bound[OF _ f_not_zero]) simp\n  have subs: \"{x \\<in> carrier R. x [^]\\<^bsub>R\\<^esub> n = int (c mod p)} \\<subseteq>\n                {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>}\"\n    using in_carrier by (auto simp: R.evalRR_simps)\n  then have \"card {x \\<in> carrier R. x [^]\\<^bsub>R\\<^esub> n = int (c mod p)} \\<le>\n               card {a \\<in> carrier R. UnivPoly.eval R R id a ?f = \\<zero>\\<^bsub>R\\<^esub>}\"\n    using finite by (intro card_mono) auto\n  also have \"\\<dots> \\<le> n\"\n    using \\<open>deg R ?f = n\\<close> roots_bound by linarith\n  also {\n    fix x assume \"x \\<in> carrier R\"\n    hence \"x [^]\\<^bsub>R\\<^esub> n = (x ^ n) mod (int p)\"\n      by (subst pow_cong [symmetric]) (auto simp: R_def residue_ring_def)\n  }\n  hence \"{x \\<in> carrier R. x [^]\\<^bsub>R\\<^esub> n = int (c mod p)} = {x \\<in> carrier R. [x ^ n = int c] (mod p)}\"\n    by (fastforce simp: cong_def zmod_int)\n  also have \"bij_betw int A {x \\<in> carrier R. [x ^ n = int c] (mod p)}\"\n    by (rule bij_betwI[of int _ _ nat])\n       (use cong_int_iff in \\<open>force simp: R_def residue_ring_def A_def\\<close>)+\n  from bij_betw_same_card[OF this] have \"card {x \\<in> carrier R. [x ^ n = int c] (mod p)} = card A\" ..\n  finally show ?thesis .\nqed\n\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Number_Theory/Residues.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8705972801594706, "lm_q1q2_score": 0.7723979062351013}}
{"text": "section \\<open>Challenge 2.A\\<close>\ntheory Challenge2A\nimports \"lib/VTcomp\"\nbegin\n\ntext \\<open>Problem definition:\n\\<^url>\\<open>https://ethz.ch/content/dam/ethz/special-interest/infk/chair-program-method/pm/documents/Verify%20This/Challenges%202019/cartesian_trees.pdf\\<close>\\<close>\n\ntext \\<open>Polished and worked-over version.\\<close>\n\nsubsection \\<open>Specification\\<close>\n\ntext \\<open>We first fix the input, a list of integers\\<close>\ncontext fixes xs :: \"int list\" begin\n\ntext \\<open>We then specify the desired output: \n  For each index \\<open>j\\<close>, return the greatest index \\<open>i<j\\<close> such that \\<open>xs!i < xs!j\\<close>, or \\<open>None\\<close> if\n  no such index exists.\n  \n  Note that our indexes start at zero, and we use an option datatype to model that \n  no left-smaller value may exists.\n\\<close>  \ndefinition\n  \"left_spec j = (if (\\<exists>i<j. xs ! i < xs ! j) then Some (GREATEST i. i < j \\<and> xs ! i < xs ! j) else None)\"\n\ntext \\<open>The output of the algorithm should be an array \\<open>lf\\<close>, containing the indexes of the \n  left-smaller values:\n\\<close>\ndefinition \"all_left_spec lf \\<equiv> length lf = length xs \\<and> (\\<forall>i<length xs. lf!i = left_spec i)\"\n      \nsubsection \\<open>Auxiliary Theory\\<close>\ntext \\<open>We derive some theory specific to this algorithm\\<close>\n\nsubsubsection \\<open>Has-Left and The-Left\\<close>\ntext \\<open>We split the specification of nearest left value into a predicate and a total function\\<close>\ndefinition \"has_left j = (\\<exists>i<j. xs ! i < xs ! j)\"\ndefinition \"the_left j = (GREATEST i. i < j \\<and> xs ! i < xs ! j)\"\n\nlemma left_alt: \"left_spec j = (if has_left j then Some (the_left j) else None)\"\n  by (auto simp: left_spec_def has_left_def the_left_def)\n\nlemma the_leftI: \"has_left j \\<Longrightarrow> the_left j < j \\<and> xs!the_left j < xs!j\"\n  apply (clarsimp simp: has_left_def the_left_def)\n  by (metis (no_types, lifting) GreatestI_nat less_le_not_le nat_le_linear pinf(5))\n\nlemma the_left_decr[simp]: \"has_left i \\<Longrightarrow> the_left i < i\"  \n  by (simp add: the_leftI)\n\nlemma le_the_leftI:\n  assumes \"i\\<le>j\" \"xs!i < xs!j\"\n  shows \"i \\<le> the_left j\"\n  using assms unfolding the_left_def\n  by (metis (no_types, lifting)\n      Greatest_le_nat le_less_linear less_imp_not_less less_irrefl\n      order.not_eq_order_implies_strict)\n\nlemma the_left_leI:  \n  assumes \"\\<forall>k. j<k \\<and> k<i \\<longrightarrow> \\<not>xs!k<xs!i\"\n  assumes \"has_left i\"\n  shows \"the_left i \\<le> j\"\n  using assms\n  unfolding the_left_def has_left_def\n  apply auto\n  by (metis (full_types) the_leftI assms(2) not_le the_left_def)\n\nsubsubsection \\<open>Derived Stack\\<close>    \ntext \\<open>We note that the stack in the algorithm doesn't contain any \n  extra information. It can be derived from the left neighbours that have been \n  computed so far:\n  The first element of the stack is the current index - 1, and each next element is\n  the nearest left smaller value of the previous element:\n\\<close>\n\nfun der_stack where\n  \"der_stack i = (if has_left i then the_left i # der_stack (the_left i) else [])\"  \ndeclare der_stack.simps[simp del]  \n\ntext \\<open>\n  Although the refinement framework would allow us to phrase the \n  algorithm without a stack first, and then introduce the stack in a subsequent \n  refinement step (or omit it altogether), for simplicity of presentation, we decided\n  to model the algorithm with a stack in first place. However, the invariant will account for\n  the stack being derived.\n\\<close>\n\nlemma set_der_stack_lt: \"k \\<in> set (der_stack i\\<^sub>0) \\<Longrightarrow> k<i\\<^sub>0\"  \n  apply (induction i\\<^sub>0 rule: der_stack.induct)\n  apply (subst (asm) der_stack.simps)\n  apply auto\n  using less_trans the_leftI by blast\n  \n\n\nsubsection \\<open>Abstract Implementation\\<close>\ntext \\<open>We first implement the algorithm on lists. \n  The assertions that we annotated into the algorithm ensure\n  that all list index accesses are in bounds.\n\\<close>\ndefinition \"pop stk v \\<equiv> dropWhile (\\<lambda>j. xs!j\\<ge>v) stk\"\n\nlemma pop_Nil[simp]: \"pop [] v = []\" by (auto simp: pop_def)\nlemma pop_cons: \"pop (j#js) v = (if xs!j \\<ge> v then pop js v else j#js)\"\n  by (simp add: pop_def)\n\n\ndefinition \"all_left \\<equiv> doN {\n  (_,lf) \\<leftarrow> nfoldli [0..<length xs] (\\<lambda>_. True) (\\<lambda>i (stk,lf). doN {\n    ASSERT (set stk \\<subseteq> {0..<length xs} );\n    let stk = pop stk (xs!i);\n    ASSERT (stk = der_stack i);\n    ASSERT (i<length lf);\n    if (stk = []) then doN {\n      let lf = lf[i:=None];\n      RETURN (i#stk,lf)\n    } else doN {\n      let lf = lf[i:= Some (hd stk)];\n      RETURN (i#stk,lf)\n    }\n  }) ([],replicate (length xs) None);\n  RETURN lf\n}\"\n\n\nsubsection \\<open>Correctness Proof\\<close>\n\nsubsubsection \\<open>Popping From the Stack\\<close>\n\ntext \\<open>We show that the abstract algorithm implements its specification.\n  The main idea here is the popping of the stack.\n  Top obtain a left smaller value, it is enough to follow the left-values of\n  the left-neighbour, until we have found the value or there are no more left-values.\n  \n  The following theorem formalizes this idea:\n\\<close>\ntheorem find_left_rl:\n  assumes \"i\\<^sub>0 < length xs\"\n  assumes \"i<i\\<^sub>0\"\n  assumes \"left_spec i\\<^sub>0 \\<le> Some i\"\n  shows \"if xs!i < xs!i\\<^sub>0 then left_spec i\\<^sub>0 = Some i\n         else left_spec i\\<^sub>0 \\<le> left_spec i\"\n  using assms           \n  apply (simp; intro impI conjI; clarsimp)\n  subgoal\n    apply (auto simp: left_alt split: if_splits)\n    apply (simp add: le_antisym le_the_leftI)\n    apply (auto simp: has_left_def)\n    done\n  subgoal\n    apply (auto simp: left_alt split: if_splits)\n    subgoal\n      apply (drule the_leftI)\n      using nat_less_le by (auto simp: has_left_def)\n    subgoal  \n      using le_the_leftI the_leftI by fastforce\n    done  \n  done  \n\ntext \\<open>Using this lemma, we can show that the stack popping procedure preserves the form of the stack.\\<close>\nlemma pop_aux: \"\\<lbrakk> k<i\\<^sub>0; i\\<^sub>0<length xs; left_spec i\\<^sub>0 \\<le> Some k \\<rbrakk> \\<Longrightarrow> pop (k # der_stack k) (xs!i\\<^sub>0) = der_stack i\\<^sub>0\"\n  apply (induction k rule: nat_less_induct)\n  apply (clarsimp)\n  by (smt der_stack.simps left_alt pop_def the_leftI dropWhile.simps(1) find_left_rl leD less_option_None_Some option.inject pop_cons)\n  \n  \nsubsubsection \\<open>Main Algorithm\\<close>  \n\ntext \\<open>Ad-Hoc lemmas\\<close>\nlemma swap_adhoc[simp]: \n  \"None = left i \\<longleftrightarrow> left i = None\"\n  \"Some j = left i \\<longleftrightarrow> left i = Some j\" by auto\n\nlemma left_spec_None_iff[simp]: \"left_spec i = None \\<longleftrightarrow> \\<not>has_left i\" by (auto simp: left_alt)\n\n\nsubsection \\<open>Implementation With Arrays\\<close>    \ntext \\<open>We refine the algorithm to use actual arrays for the input and output. \n  The stack remains a list, as pushing and popping from a (functional) list is efficient.\n\\<close>\n\nsubsubsection \\<open>Implementation of Pop\\<close>   \ntext \\<open>In a first step, we refine the pop function to an explicit loop.\\<close>\n\ndefinition \"pop2 stk v \\<equiv> \n  monadic_WHILEIT \n    (\\<lambda>_. set stk \\<subseteq> {0..<length xs}) \n    (\\<lambda>[] \\<Rightarrow> RETURN False | k#stk \\<Rightarrow> doN { ASSERT (k<length xs); RETURN (v \\<le> xs!k) })\n    (\\<lambda>stk. mop_list_tl stk)\n    stk\"\n  \nlemma pop2_refine_aux: \"set stk \\<subseteq> {0..<length xs} \\<Longrightarrow> pop2 stk v \\<le> RETURN (pop stk v)\"\n  apply (induction stk)\n  unfolding pop_def pop2_def\n  subgoal\n    apply (subst monadic_WHILEIT_unfold)\n    by auto\n  subgoal\n    apply (subst monadic_WHILEIT_unfold)\n    unfolding mop_list_tl_def op_list_tl_def by auto\n  done\n        \nend \\<comment> \\<open>Context fixing the input \\<open>xs\\<close>.\\<close>\n\n\ntext \\<open>The refinement lemma written in higher-order form.\\<close>\n\n\ntext \\<open>Next, we use the Sepref tool to synthesize an implementation on arrays.\\<close>\nsepref_definition pop2_impl is \"uncurry2 pop2\" :: \"(array_assn id_assn)\\<^sup>k *\\<^sub>a (list_assn id_assn)\\<^sup>k *\\<^sub>a id_assn\\<^sup>k \\<rightarrow>\\<^sub>a list_assn id_assn\"\n  unfolding pop2_def\n  by sepref\nlemmas [sepref_fr_rules] = pop2_impl.refine[FCOMP pop2_refine]  \n\nsubsubsection \\<open>Implementation of Main Algorithm\\<close>  \n\nsepref_definition all_left_impl is all_left :: \"(array_assn id_assn)\\<^sup>k \\<rightarrow>\\<^sub>a array_assn (option_assn id_assn)\"\n  unfolding all_left_def\n  apply (rewrite at \"nfoldli _ _ _ (\\<hole>,_)\" HOL_list.fold_custom_empty)\n  apply (rewrite in \"nfoldli _ _ _ (_,\\<hole>)\" array_fold_custom_replicate)\n  by sepref\n\nsubsubsection \\<open>Correctness Theorem for Concrete Algorithm\\<close>\ntext \\<open>We compose the correctness theorem and the refinement theorem, to get a correctness\n  theorem for the final implementation.\\<close>\n  \ntext \\<open>Abstract correctness theorem in higher-order form.\\<close>\nlemma algo_correct': \"(all_left, SPEC o all_left_spec) \n  \\<in> \\<langle>Id\\<rangle>list_rel \\<rightarrow> \\<langle>\\<langle>\\<langle>Id\\<rangle>option_rel\\<rangle>list_rel\\<rangle>nres_rel\"\n  using algo_correct by (auto simp: nres_relI)  \n\ntext \\<open>Main correctness theorem in higher-order form.\\<close>   \ntheorem algo_impl_correct:\n    \"(all_left_impl, SPEC o all_left_spec)\n    \\<in> (array_assn int_assn, array_assn int_assn) \\<rightarrow>\\<^sub>a array_assn (option_assn nat_assn)\"      \n  using all_left_impl.refine[FCOMP algo_correct', simplified] .\n    \ntext \\<open>Main correctness theorem as Hoare-Triple\\<close>  \ntheorem algo_impl_correct': \"\n  <array_assn int_assn xs xsi> \n    all_left_impl xsi \n  <\\<lambda>lfi. \\<exists>\\<^sub>Alf. array_assn int_assn xs xsi \n        * array_assn (option_assn id_assn) lf lfi \n        * \\<up>(all_left_spec xs lf)>\\<^sub>t\" \n  apply (rule cons_rule[OF _ _ algo_impl_correct[to_hnr, THEN hn_refineD, unfolded autoref_tag_defs]])\n  apply (simp add: hn_ctxt_def, rule ent_refl) \n  by (auto simp: hn_ctxt_def)\n\n\nsubsection \\<open>Code Generation\\<close>\n    \nexport_code all_left_impl checking SML Scala Haskell? OCaml?\n\n\ntext \\<open>The example from the problem description, in ML using the verified algorithm\\<close>\nML_val \\<open>\n  (* Convert from option to 1-based indexes *)\n  fun cnv NONE = 0\n    | cnv (SOME i) = @{code integer_of_nat} i + 1\n\n  (* The verified algorithm, boxing the input list into an array, \n    and unboxing the output to a list, and converting it from option to 1-based *)\n  fun all_left xs = \n       @{code all_left_impl} (Array.fromList (map @{code int_of_integer} xs)) ()\n    |> Array.foldr (op ::) []\n    |> map cnv\n\n  val test = all_left [ 4, 7, 8, 1, 2, 3, 9, 5, 6 ]  \n\\<close>\n \nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/VerifyThis2019/Challenge2A.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.7723978976413517}}
{"text": "section \\<open> Algebraic Laws \\<close>\n\ntheory ISQ_Algebra\n  imports ISQ_Proof\nbegin\n\nsubsection \\<open> Quantity Scale \\<close>\n\nlemma scaleQ_add_right: \"a *\\<^sub>Q x + y = (a *\\<^sub>Q x) + (a *\\<^sub>Q y)\"\n  by (si_simp add: distrib_left)\n\nlemma scaleQ_add_left: \"a + b *\\<^sub>Q x = (a *\\<^sub>Q x) + (b *\\<^sub>Q x)\"\n  by (si_simp add: distrib_right)\n\nlemma scaleQ_scaleQ [simp]: \"a *\\<^sub>Q b *\\<^sub>Q x = a \\<cdot> b *\\<^sub>Q x\"\n  by si_simp\n\nlemma scaleQ_one [simp]: \"1 *\\<^sub>Q x = x\"\n  by si_simp\n\nlemma scaleQ_zero [simp]: \"0 *\\<^sub>Q x = 0\"\n  by si_simp\n\nlemma scaleQ_inv: \"-a *\\<^sub>Q x = a *\\<^sub>Q -x\"\n  by si_calc\n\nlemma scaleQ_as_qprod: \"a *\\<^sub>Q x \\<cong>\\<^sub>Q (a *\\<^sub>Q \\<one>) \\<^bold>\\<cdot> x\"\n  by si_simp\n\nlemma mult_scaleQ_left [simp]: \"(a *\\<^sub>Q x) \\<^bold>\\<cdot> y = a *\\<^sub>Q x \\<^bold>\\<cdot> y\"\n  by si_simp\n\nlemma mult_scaleQ_right [simp]: \"x \\<^bold>\\<cdot> (a *\\<^sub>Q y) = a *\\<^sub>Q x \\<^bold>\\<cdot> y\"\n  by si_simp\n\nsubsection \\<open> Field Laws \\<close>\n\nlemma qtimes_commute: \"x \\<^bold>\\<cdot> y \\<cong>\\<^sub>Q y \\<^bold>\\<cdot> x\"\n  by si_calc\n\nlemma qtimes_assoc: \"(x \\<^bold>\\<cdot> y) \\<^bold>\\<cdot> z  \\<cong>\\<^sub>Q  x \\<^bold>\\<cdot> (y \\<^bold>\\<cdot> z)\"\n  by (si_calc)\n\nlemma qtimes_left_unit: \"\\<one> \\<^bold>\\<cdot> x \\<cong>\\<^sub>Q x\"\n  by (si_calc)\n\nlemma qtimes_right_unit: \"x \\<^bold>\\<cdot> \\<one> \\<cong>\\<^sub>Q x\"\n  by (si_calc)\n\ntext\\<open>The following weak congruences will allow for replacing equivalences in contexts\n     built from product and inverse. \\<close>\n\nlemma qtimes_weak_cong_left:\n  assumes \"x \\<cong>\\<^sub>Q y\"\n  shows  \"x\\<^bold>\\<cdot>z \\<cong>\\<^sub>Q y\\<^bold>\\<cdot>z\"\n  using assms by si_simp\n\nlemma qtimes_weak_cong_right:\n  assumes \"x \\<cong>\\<^sub>Q y\"\n  shows  \"z\\<^bold>\\<cdot>x \\<cong>\\<^sub>Q z\\<^bold>\\<cdot>y\"\n  using assms by si_calc\n\n\n\nlemma scaleQ_cong:\n  assumes \"y \\<cong>\\<^sub>Q z\"\n  shows \"x *\\<^sub>Q y \\<cong>\\<^sub>Q x *\\<^sub>Q z\"\n  using assms by si_calc\n\nlemma qinverse_qinverse: \"x\\<^sup>-\\<^sup>\\<one>\\<^sup>-\\<^sup>\\<one> \\<cong>\\<^sub>Q x\"\n  by si_calc\n\nlemma qinverse_nonzero_iff_nonzero: \"x\\<^sup>-\\<^sup>\\<one> = 0 \\<longleftrightarrow> x = 0\"\n  by (auto, si_calc+)\n\nlemma qinverse_qtimes: \"(x \\<^bold>\\<cdot> y)\\<^sup>-\\<^sup>\\<one> \\<cong>\\<^sub>Q x\\<^sup>-\\<^sup>\\<one> \\<^bold>\\<cdot> y\\<^sup>-\\<^sup>\\<one>\"\n  by (si_simp add: inverse_distrib)\n\nlemma qinverse_qdivide: \"(x \\<^bold>/ y)\\<^sup>-\\<^sup>\\<one> \\<cong>\\<^sub>Q y \\<^bold>/ x\"\n  by si_simp\n\nlemma qtimes_cancel: \"x \\<noteq> 0 \\<Longrightarrow> x \\<^bold>/ x \\<cong>\\<^sub>Q \\<one>\"\n  by si_calc\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Physical_Quantities/ISQ_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921834855049, "lm_q2_score": 0.8376199714402813, "lm_q1q2_score": 0.7722201409814579}}
{"text": "theory Exe4p3\n  imports Main\nbegin\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS : \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\nlemma \"ev (Suc m) \\<Longrightarrow> \\<not> ev m\"\nproof (induction \"Suc m\" arbitrary: m rule: ev.induct)\n  fix n assume IH: \"\\<And>m. n = Suc m \\<Longrightarrow> \\<not>ev m\"\n  show \"\\<not>ev (Suc n)\"\n  proof\n    assume \"ev(Suc n)\"\n    thus False\n    proof cases\n      fix k assume \"n = Suc k\" \"ev k\"\n      thus False using IH by auto\n    qed\n  qed\nqed\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\nproof -\n  have \"ev(Suc(Suc n)) \\<Longrightarrow> ev n\"\n  proof (induction \"Suc(Suc n)\" arbitrary: n rule: ev.induct)\n    case ev0\n    fix n assume \"ev n\"\n    thus \"ev n\" by simp\n  qed\n  thus ?thesis using a by simp\nqed\n\nend\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/prog-prove/Exe4p3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026641072387, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7722089107577463}}
{"text": "theory Funpow\nimports\n  \"HOL-Library.FuncSet\"\n  \"HOL-Library.Permutations\"\nbegin\n\nsection \\<open>Auxiliary Lemmas about @{term \"(^^)\"}\\<close>\n\nlemma funpow_simp_l: \"f ((f ^^ n) x) = (f ^^ Suc n) x\"\n  by (metis comp_apply funpow.simps(2))\n\nlemma funpow_add_app: \"(f ^^ n) ((f ^^ m) x) = (f ^^ (n + m)) x\"\n  by (metis comp_apply funpow_add)\n\nlemma funpow_mod_eq:\n  assumes \"(f ^^ n) x = x\" \"0 < n\" shows \"(f ^^ (m mod n)) x = (f ^^ m) x\"\nproof (induct m rule: less_induct)\n  case (less m)\n  { assume \"m < n\" then have ?case by simp }\n  moreover\n  { assume \"m = n\" then have ?case by (simp add: \\<open>_ = x\\<close>)}\n  moreover\n  { assume \"n < m\"\n    then have \"m - n < m\" \"0 < m - n\"  using \\<open>0 < n\\<close> by arith+\n\n    have \"(f ^^ (m mod n)) x = (f ^^ ((m - n) mod n)) x\"\n      using \\<open>0 < m - n\\<close> by (simp add: mod_geq)\n    also have \"\\<dots> = (f ^^ (m - n)) x\"\n      using \\<open>m - n < m\\<close> by (rule less)\n    also have \"\\<dots> = (f ^^ (m - n)) ((f ^^ n) x)\"\n      by (simp add: assms)\n    also have \"\\<dots> = (f ^^ m) x\"\n      using \\<open>0 < m - n\\<close> by (simp add: funpow_add_app)\n    finally have ?case . }\n  ultimately show ?case by (metis linorder_neqE_nat)\nqed\n\nlemma id_funpow_id:\n  assumes \"f x = x\" shows \"(f ^^ n) x = x\"\n  using assms by (induct n) auto\n\nlemma inv_id_abs[simp]: \"inv (\\<lambda>a. a) = id\" unfolding id_def[symmetric] by simp\n\nlemma inj_funpow:\n  fixes f :: \"'a \\<Rightarrow> 'a\"\n  assumes \"inj f\" shows \"inj (f ^^ n)\"\nproof (induct n)\n  case 0 then show ?case by (auto simp: id_def[symmetric])\nnext\n  case (Suc n) with assms show ?case unfolding funpow.simps by (rule inj_compose)\nqed\n\nlemma funpow_inj_finite:\n  assumes \"inj p\" \"finite {(p ^^ n) x |n. True}\"\n  shows \"\\<exists>n>0. (p ^^ n) x = x\"\nproof -\n  have \"\\<not>finite {0::nat..}\" by simp\n  moreover\n  have \"{(p ^^ n) x |n. True} = (\\<lambda>n. (p ^^ n) x) ` {0..}\" by auto\n  with assms have \"finite \\<dots>\" by simp\n  ultimately have \"\\<exists>n\\<in>{0..}. \\<not> finite {m \\<in> {0..}. (p ^^ m) x = (p ^^ n) x}\"\n    by (rule pigeonhole_infinite)\n  then obtain n where \"\\<not>finite {m. (p ^^ m) x = (p ^^ n) x}\" by auto\n  then have \"\\<not>finite ({m. (p ^^ m) x = (p ^^ n) x} - {n})\" by auto\n  then have \"({m. (p ^^ m) x = (p ^^ n) x} - {n}) \\<noteq> {}\"\n    by (metis finite.emptyI)\n  then obtain m where m: \"(p ^^ m) x = (p ^^ n) x\" \"m \\<noteq> n\" by auto\n\n  { fix m n assume \"(p ^^ n) x = (p ^^ m) x\" \"m < n\"\n    have \"(p ^^ (n - m)) x = inv (p ^^ m) ((p ^^ m) ((p ^^ (n - m)) x))\"\n      using \\<open>inj p\\<close> by (simp add: inv_f_f inj_funpow)\n    also have \"((p ^^ m) ((p ^^ (n - m)) x)) = (p ^^ n) x\"\n      using \\<open>m < n\\<close> by (simp add: funpow_add_app)\n    also have \"inv (p ^^ m) \\<dots> = x\"\n      using \\<open>inj p\\<close>  by (simp add: \\<open>(p ^^ n) x = _\\<close> inj_funpow)\n    finally have \"(p ^^ (n - m)) x = x\" \"0 < n - m\"\n      using \\<open>m < n\\<close> by auto }\n  note general = this\n\n  show ?thesis\n  proof (cases m n rule: linorder_cases)\n    case less\n    then show ?thesis using general m by metis\n  next\n    case equal\n    then show ?thesis using m by metis\n  next\n    case greater\n    then show ?thesis using general m by metis\n  qed\nqed\n\nlemma permutes_in_funpow_image:\n  assumes \"f permutes S\" \"x \\<in> S\"\n  shows \"(f ^^ n) x \\<in> S\"\n  using assms by (induct n) (auto simp: permutes_in_image)\n\n(* XXX move*)\nlemma permutation_self:\n  assumes \"permutation p\" shows \"\\<exists>n>0. (p ^^ n) x = x\"\nproof cases\n  assume \"p x = x\" then show ?thesis by auto\nnext\n  assume \"p x \\<noteq> x\"\n  from assms have \"inj p\" by (intro permutation_bijective bij_is_inj)\n  { fix n\n    from \\<open>p x \\<noteq> x\\<close> have \"(p ^^ Suc n) x \\<noteq> (p ^^ n) x\"\n    proof (induct n arbitrary: x)\n      case 0 then show ?case by simp\n    next\n      case (Suc n)\n      have \"p (p x) \\<noteq> p x\"\n      proof (rule notI)\n        assume \"p (p x) = p x\"\n        then show False using \\<open>p x \\<noteq> x\\<close> \\<open>inj p\\<close> by (simp add: inj_eq)\n      qed\n      have \"(p ^^ Suc (Suc n)) x = (p ^^ Suc n) (p x)\"\n        by (metis funpow_simp_l funpow_swap1)\n      also have \"\\<dots> \\<noteq> (p ^^ n) (p x)\"\n        by (rule Suc) fact\n      also have \"(p ^^ n) (p x) = (p ^^ Suc n) x\"\n        by (metis funpow_simp_l funpow_swap1)\n      finally show ?case by simp\n    qed }\n  then have \"{(p ^^ n) x | n. True} \\<subseteq> {x. p x \\<noteq> x}\"\n    by auto\n  then have \"finite {(p ^^ n) x | n. True}\"\n    using permutation_finite_support[OF assms] by (rule finite_subset)\n  with \\<open>inj p\\<close> show ?thesis by (rule funpow_inj_finite)\nqed\n\n(* XXX move *)\nlemma (in -) funpow_invs:\n  assumes \"m \\<le> n\" and inv: \"\\<And>x. f (g x) = x\"\n  shows \"(f ^^ m) ((g ^^ n) x) = (g ^^ (n - m)) x\"\n  using \\<open>m \\<le> n\\<close>\nproof (induction m)\n  case (Suc m)\n  moreover then have \"n - m = Suc (n - Suc m)\" by auto\n  ultimately show ?case by (auto simp: inv)\nqed simp\n\n\n\n\nsection \\<open>Function-power distance between values\\<close>\n\n(* xxx move *)\ndefinition funpow_dist :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"funpow_dist f x y \\<equiv> LEAST n. (f ^^ n) x = y\"\n\nabbreviation funpow_dist1 :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"funpow_dist1 f x y \\<equiv> Suc (funpow_dist f (f x) y)\"\n\nlemma funpow_dist_0:\n  assumes \"x = y\" shows \"funpow_dist f x y = 0\"\n  using assms unfolding funpow_dist_def by (intro Least_eq_0) simp\n\nlemma funpow_dist_least:\n  assumes \"n < funpow_dist f x y\" shows \"(f ^^ n) x \\<noteq> y\"\nproof (rule notI)\n  assume \"(f ^^ n) x = y\"\n  then have \"funpow_dist f x y \\<le> n\" unfolding funpow_dist_def by (rule Least_le)\n  with assms show False by linarith\nqed\n\nlemma funpow_dist1_least:\n  assumes \"0 < n\" \"n < funpow_dist1 f x y\" shows \"(f ^^ n) x \\<noteq> y\"\nproof (rule notI)\n  assume \"(f ^^ n) x = y\"\n  then have \"(f ^^ (n - 1)) (f x) = y\"\n    using \\<open>0 < n\\<close> by (cases n) (simp_all add: funpow_swap1)\n  then have \"funpow_dist f (f x) y \\<le> n - 1\" unfolding funpow_dist_def by (rule Least_le)\n  with assms show False by simp\nqed\n\n\nsection \\<open>Cyclic Permutations\\<close>\n\ninductive_set orbit :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a set\" for f x where\n  base: \"f x \\<in> orbit f x\" |\n  step: \"y \\<in> orbit f x \\<Longrightarrow> f y \\<in> orbit f x\"\n\ndefinition cyclic_on :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"cyclic_on f S \\<longleftrightarrow> (\\<exists>s\\<in>S. S = orbit f s)\"\n\nlemma orbit_altdef: \"orbit f x = {(f ^^ n) x | n. 0 < n}\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix y assume \"y \\<in> ?L\" then show \"y \\<in> ?R\"\n    by (induct rule: orbit.induct) (auto simp: exI[where x=1] exI[where x=\"Suc n\" for n])\nnext\n  fix y assume \"y \\<in> ?R\"\n  then obtain n where \"y = (f ^^ n) x\" \"0 < n\" by blast\n  then show \"y \\<in> ?L\"\n  proof (induction n arbitrary: y)\n    case (Suc n) then show ?case by (cases \"n = 0\") (auto intro: orbit.intros)\n  qed simp\nqed\n\nlemma orbit_trans:\n  assumes \"s \\<in> orbit f t\" \"t \\<in> orbit f u\" shows \"s \\<in> orbit f u\"\n  using assms by induct (auto intro: orbit.intros)\n\nlemma orbit_subset:\n  assumes \"s \\<in> orbit f (f t)\" shows \"s \\<in> orbit f t\"\n  using assms by (induct) (auto intro: orbit.intros)\n\nlemma orbit_sim_step:\n  assumes \"s \\<in> orbit f t\" shows \"f s \\<in> orbit f (f t)\"\n  using assms by induct (auto intro: orbit.intros)\n\nlemma orbit_step:\n  assumes \"y \\<in> orbit f x\" \"f x \\<noteq> y\" shows \"y \\<in> orbit f (f x)\"\n  using assms\nproof induction\n  case (step y) then show ?case by (cases \"x = y\") (auto intro: orbit.intros)\nqed simp\n\nlemma self_in_orbit_trans:\n  assumes \"s \\<in> orbit f s\" \"t \\<in> orbit f s\" shows \"t \\<in> orbit f t\"\n  using assms(2,1) by induct (auto intro: orbit_sim_step)\n\nlemma orbit_swap:\n  assumes \"s \\<in> orbit f s\" \"t \\<in> orbit f s\" shows \"s \\<in> orbit f t\"\n  using assms(2,1)\nproof induction\n  case base then show ?case by (cases \"f s = s\") (auto intro: orbit_step)\nnext\n  case (step x) then show ?case by (cases \"f x = s\") (auto intro: orbit_step)\nqed\n\nlemma permutation_self_in_orbit:\n  assumes \"permutation f\" shows \"s \\<in> orbit f s\"\n  unfolding orbit_altdef using permutation_self[OF assms, of s] by simp metis\n\nlemma orbit_altdef_self_in:\n  assumes \"s \\<in> orbit f s\" shows \"orbit f s = {(f ^^ n) s | n. True}\"\nproof (intro set_eqI iffI)\n  fix x assume \"x \\<in> {(f ^^ n) s | n. True}\"\n  then obtain n where \"x = (f ^^ n) s\" by auto\n  then show \"x \\<in> orbit f s\" using assms by (cases \"n = 0\") (auto simp: orbit_altdef)\nqed (auto simp: orbit_altdef)\n\nlemma orbit_altdef_permutation:\n  assumes \"permutation f\" shows \"orbit f s = {(f ^^ n) s | n. True}\"\n  using assms by (intro orbit_altdef_self_in permutation_self_in_orbit)\n\nlemma orbit_altdef_bounded:\n  assumes \"(f ^^ n) s = s\" \"0 < n\" shows \"orbit f s = {(f ^^ m) s| m. m < n}\"\nproof -\n  from assms have \"s \\<in> orbit f s\" unfolding orbit_altdef by auto metis\n  then have \"orbit f s = {(f ^^ m) s|m. True}\" by (rule orbit_altdef_self_in)\n  also have \"\\<dots> = {(f ^^ m) s| m. m < n}\"\n    using assms by (auto simp: funpow_mod_eq intro: exI[where x=\"m mod n\" for m])\n  finally show ?thesis .\nqed\n\nlemma funpow_in_orbit:\n  assumes \"s \\<in> orbit f t\" shows \"(f ^^ n) s \\<in> orbit f t\"\n  using assms by (induct n) (auto intro: orbit.intros)\n\nlemma finite_orbit:\n  assumes \"s \\<in> orbit f s\" shows \"finite (orbit f s)\"\nproof -\n  from assms obtain n where n: \"0 < n\" \"(f ^^n) s = s\" by (auto simp: orbit_altdef)\n  then show ?thesis by (auto simp: orbit_altdef_bounded)\nqed\n\nlemma self_in_orbit_step:\n  assumes \"s \\<in> orbit f s\" shows \"orbit f (f s) = orbit f s\"\nproof (intro set_eqI iffI)\n  fix t assume \"t \\<in> orbit f s\" then show \"t \\<in> orbit f (f s)\"\n    using assms by (auto intro: orbit_step orbit_sim_step)\nqed (auto intro: orbit_subset)\n\nlemma permutation_orbit_step:\n  assumes \"permutation f\" shows \"orbit f (f s) = orbit f s\"\n  using assms by (intro self_in_orbit_step permutation_self_in_orbit)\n\nlemma orbit_nonempty:\n  \"orbit f s \\<noteq> {}\"\n  using orbit.base by fastforce\n\nlemma orbit_inv_eq:\n  assumes \"permutation f\"\n  shows \"orbit (inv f) x = orbit f x\" (is \"?L = ?R\")\nproof -\n  { fix g y assume A: \"permutation g\" \"y \\<in> orbit (inv g) x\"\n    have \"y \\<in> orbit g x\"\n    proof -\n      have inv_g: \"\\<And>y. x = g y \\<Longrightarrow> inv g x = y\" \"\\<And>y. inv g (g y) = y\"\n        by (metis A(1) bij_inv_eq_iff permutation_bijective)+\n\n      { fix y assume \"y \\<in> orbit g x\"\n        then have \"inv g y \\<in> orbit g x\"\n          by (cases) (simp_all add: inv_g A(1) permutation_self_in_orbit)\n      } note inv_g_in_orb = this\n\n      from A(2) show ?thesis\n        by induct (simp_all add: inv_g_in_orb A permutation_self_in_orbit)\n    qed\n  } note orb_inv_ss = this\n\n  have \"inv (inv f) = f\"\n    by (simp add: assms inv_inv_eq permutation_bijective)\n  then show ?thesis\n    using orb_inv_ss[OF assms] orb_inv_ss[OF permutation_inverse[OF assms]] by auto\nqed\n\nlemma cyclic_on_alldef:\n  \"cyclic_on f S \\<longleftrightarrow> S \\<noteq> {} \\<and> (\\<forall>s\\<in>S. S = orbit f s)\"\n  unfolding cyclic_on_def by (auto intro: orbit.step orbit_swap orbit_trans)\n\n\nlemma cyclic_on_funpow_in:\n  assumes \"cyclic_on f S\" \"s \\<in> S\" shows \"(f^^n) s \\<in> S\"\n  using assms unfolding cyclic_on_def by (auto intro: funpow_in_orbit)\n\nlemma finite_cyclic_on:\n  assumes \"cyclic_on f S\" shows \"finite S\"\n  using assms by (auto simp: cyclic_on_def finite_orbit)\n\nlemma cyclic_on_singleI:\n  assumes \"s \\<in> S\" \"S = orbit f s\" shows \"cyclic_on f S\"\n  using assms unfolding cyclic_on_def by blast\n\nlemma inj_on_funpow_least:\n  assumes \"(f ^^ n) s = s\" \"\\<And>m. \\<lbrakk>m < n; 0 < m\\<rbrakk> \\<Longrightarrow> (f ^^ m) s \\<noteq> s\"\n  shows \"inj_on (\\<lambda>k. (f^^k) s) {0..<n}\"\nproof -\n  { fix k l assume A: \"k < n\" \"l < n\" \"k \\<noteq> l\" \"(f ^^ k) s = (f ^^ l) s\"\n    define k' l' where \"k' = min k l\" and \"l' = max k l\"\n    with A have A': \"k' < l'\" \"(f ^^ k') s = (f ^^ l') s\" \"l' < n\"\n      by (auto simp: min_def max_def)\n\n    have \"s = (f ^^ ((n - l') + l')) s\" using assms \\<open>l' < n\\<close> by simp\n    also have \"\\<dots> = (f ^^ (n - l')) ((f ^^ l') s)\" by (simp add: funpow_add)\n    also have \"(f ^^ l') s = (f ^^ k') s\" by (simp add: A')\n    also have \"(f ^^ (n - l')) \\<dots> = (f ^^ (n - l' + k')) s\" by (simp add: funpow_add)\n    finally have \"(f ^^ (n - l' + k')) s = s\" by simp\n    moreover have \"n - l' + k' < n\" \"0 < n - l' + k'\"using A' by linarith+\n    ultimately have False using assms(2) by auto\n  }\n  then show ?thesis by (intro inj_onI) auto\nqed\n\nlemma cyclic_on_inI:\n  assumes \"cyclic_on f S\" \"s \\<in> S\" shows \"f s \\<in> S\"\n  using assms by (auto simp: cyclic_on_def intro: orbit.intros)\n\nlemma bij_betw_funpow:\n  assumes \"bij_betw f S S\" shows \"bij_betw (f ^^ n) S S\"\nproof (induct n)\n  case 0 then show ?case by (auto simp: id_def[symmetric])\nnext\n  case (Suc n)\n  then show ?case unfolding funpow.simps using assms by (rule bij_betw_trans)\nqed\n\n(*XXX rename move*)\nlemma orbit_FOO:\n  assumes self:\"a \\<in> orbit g a\"\n    and eq: \"\\<And>x. x \\<in> orbit g a \\<Longrightarrow>  g' (f x) = f (g x)\"\n  shows \"f ` orbit g a = orbit g' (f a)\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix x assume \"x \\<in> ?L\"\n  then obtain x0 where \"x0 \\<in> orbit g a\" \"x = f x0\" by auto\n  then show \"x \\<in> ?R\"\n  proof (induct arbitrary: x)\n    case base then show ?case by (auto simp: self orbit.base eq[symmetric])\n  next\n    case step then show ?case by cases (auto simp: eq[symmetric] orbit.intros)\n  qed\nnext\n  fix x assume \"x \\<in> ?R\"\n  then show \"x \\<in> ?L\"\n  proof (induct arbitrary: )\n    case base then show ?case by (auto simp: self orbit.base eq)\n  next\n    case step then show ?case by cases (auto simp: eq orbit.intros)\n  qed\nqed\n\nlemma cyclic_on_FOO:\n  assumes \"cyclic_on f S\"\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> g (h x) = h (f x)\"\n  shows \"cyclic_on g (h ` S)\"\n  using assms by (auto simp: cyclic_on_def) (meson orbit_FOO)\n\nlemma cyclic_on_f_in:\n  assumes \"f permutes S\" \"cyclic_on f A\" \"f x \\<in> A\"\n  shows \"x \\<in> A\"\nproof -\n  from assms have fx_in_orb: \"f x \\<in> orbit f (f x)\" by (auto simp: cyclic_on_alldef)\n  from assms have \"A = orbit f (f x)\" by (auto simp: cyclic_on_alldef)\n  moreover\n  then have \"\\<dots> = orbit f x\" using \\<open>f x \\<in> A\\<close> by (auto intro: orbit_step orbit_subset)\n  ultimately\n    show ?thesis by (metis (no_types) orbit.simps permutes_inverses(2)[OF assms(1)])\nqed\n\nlemma permutes_not_in:\n  assumes \"f permutes S\" \"x \\<notin> S\" shows \"f x = x\"\n  using assms by (auto simp: permutes_def)\n\nlemma orbit_cong0:\n  assumes \"x \\<in> A\" \"f \\<in> A \\<rightarrow> A\" \"\\<And>y. y \\<in> A \\<Longrightarrow> f y = g y\" shows \"orbit f x = orbit g x\"\nproof -\n  { fix n have \"(f ^^ n) x = (g ^^ n) x \\<and> (f ^^ n) x \\<in> A\"\n      by (induct n rule: nat.induct) (insert assms, auto)\n  } then show ?thesis by (auto simp: orbit_altdef)\nqed\n\nlemma orbit_cong:\n  assumes self_in: \"t \\<in> orbit f t\" and eq: \"\\<And>s. s \\<in> orbit f t \\<Longrightarrow> g s = f s\"\n  shows \"orbit g t = orbit f t\"\n  using assms(1) _ assms(2) by (rule orbit_cong0) (auto simp: orbit.step eq)\n\nlemma cyclic_cong:\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> f s = g s\" shows \"cyclic_on f S = cyclic_on g S\"\nproof -\n  have \"(\\<exists>s\\<in>S. orbit f s = orbit g s) \\<Longrightarrow> cyclic_on f S = cyclic_on g S\"\n    by (metis cyclic_on_alldef cyclic_on_def)\n  then show ?thesis by (metis assms orbit_cong cyclic_on_def)\nqed\n\nlemma permutes_comp_preserves_cyclic1:\n  assumes \"g permutes B\" \"cyclic_on f C\"\n  assumes \"A \\<inter> B = {}\" \"C \\<subseteq> A\"\n  shows \"cyclic_on (f o g) C\"\nproof -\n  have *: \"\\<And>c. c \\<in> C \\<Longrightarrow> f (g c) = f c\"\n    using assms by (subst permutes_not_in[where f=g]) auto\n  with assms(2) show ?thesis by (simp cong: cyclic_cong)\nqed\n\nlemma permutes_comp_preserves_cyclic2:\n  assumes \"f permutes A\" \"cyclic_on g C\"\n  assumes \"A \\<inter> B = {}\" \"C \\<subseteq> B\"\n  shows \"cyclic_on (f o g) C\"\nproof -\n  obtain c where c: \"c \\<in> C\" \"C = orbit g c\" \"c \\<in> orbit g c\"\n    using \\<open>cyclic_on g C\\<close> by (auto simp: cyclic_on_def)\n  then have \"\\<And>c. c \\<in> C \\<Longrightarrow> f (g c) = g c\"\n    using assms c by (subst permutes_not_in[where f=f]) (auto intro: orbit.intros)\n  with assms(2) show ?thesis by (simp cong: cyclic_cong)\nqed\n\n\n(*XXX merge with previous section?*)\nsubsection \\<open>Orbits\\<close>\n\nlemma permutes_orbit_subset:\n  assumes \"f permutes S\" \"x \\<in> S\" shows \"orbit f x \\<subseteq> S\"\nproof\n  fix y assume \"y \\<in> orbit f x\"\n  then show \"y \\<in> S\" by induct (auto simp: permutes_in_image assms)\nqed\n\nlemma cyclic_on_orbit':\n  assumes \"permutation f\" shows \"cyclic_on f (orbit f x)\"\n  unfolding cyclic_on_alldef using orbit_nonempty[of f x]\n  by (auto intro: assms orbit_swap orbit_trans permutation_self_in_orbit)\n\n(* XXX remove? *)\nlemma cyclic_on_orbit:\n  assumes \"f permutes S\" \"finite S\" shows \"cyclic_on f (orbit f x)\"\n  using assms by (intro cyclic_on_orbit') (auto simp: permutation_permutes)\n\nlemma orbit_cyclic_eq3:\n  assumes \"cyclic_on f S\" \"y \\<in> S\" shows \"orbit f y = S\"\n  using assms unfolding cyclic_on_alldef by simp\n\n(*XXX move*)\nlemma orbit_eq_singleton_iff: \"orbit f x = {x} \\<longleftrightarrow> f x = x\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume A: ?R\n  { fix y assume \"y \\<in> orbit f x\" then have \"y = x\"\n      by induct (auto simp: A)\n  } then show ?L by (metis orbit_nonempty singletonI subsetI subset_singletonD)\nnext\n  assume A: ?L\n  then have \"\\<And>y. y \\<in> orbit f x \\<Longrightarrow> f x = y\"\n    by - (erule orbit.cases, simp_all)\n  then show ?R using A by blast\nqed\n\n(* XXX move *)\nlemma eq_on_cyclic_on_iff1:\n  assumes \"cyclic_on f S\" \"x \\<in> S\"\n  obtains \"f x \\<in> S\" \"f x = x \\<longleftrightarrow> card S = 1\"\nproof\n  from assms show \"f x \\<in> S\" by (auto simp: cyclic_on_def intro: orbit.intros)\n  from assms have \"S = orbit f x\" by (auto simp: cyclic_on_alldef)\n  then have \"f x = x \\<longleftrightarrow> S = {x}\" by (metis orbit_eq_singleton_iff)\n  then show \"f x = x \\<longleftrightarrow> card S = 1\" using \\<open>x \\<in> S\\<close> by (auto simp: card_Suc_eq)\nqed\n\n\n\n\n\n\n\nsubsection \\<open>Decomposition of Arbitrary Permutations\\<close>\n\ndefinition perm_restrict :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n  \"perm_restrict f S x \\<equiv> if x \\<in> S then f x else x\"\n\nlemma perm_restrict_comp:\n  assumes \"A \\<inter> B = {}\" \"cyclic_on f B\"\n  shows \"perm_restrict f A o perm_restrict f B = perm_restrict f (A \\<union> B)\"\nproof -\n  have \"\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<in> B\" using \\<open>cyclic_on f B\\<close> by (rule cyclic_on_inI)\n  with assms show ?thesis by (auto simp: perm_restrict_def fun_eq_iff)\nqed\n\nlemma perm_restrict_simps:\n  \"x \\<in> S \\<Longrightarrow> perm_restrict f S x = f x\"\n  \"x \\<notin> S \\<Longrightarrow> perm_restrict f S x = x\"\n  by (auto simp: perm_restrict_def)\n\nlemma perm_restrict_perm_restrict:\n  \"perm_restrict (perm_restrict f A) B = perm_restrict f (A \\<inter> B)\"\n  by (auto simp: perm_restrict_def)\n\nlemma perm_restrict_union:\n  assumes \"perm_restrict f A permutes A\" \"perm_restrict f B permutes B\" \"A \\<inter> B = {}\"\n  shows \"perm_restrict f A o perm_restrict f B = perm_restrict f (A \\<union> B)\"\n  using assms by (auto simp: fun_eq_iff perm_restrict_def permutes_def) (metis Diff_iff Diff_triv)\n\nlemma perm_restrict_id[simp]:\n  assumes \"f permutes S\" shows \"perm_restrict f S = f\"\n  using assms by (auto simp: permutes_def perm_restrict_def)\n\nlemma cyclic_on_perm_restrict:\n  \"cyclic_on (perm_restrict f S) S \\<longleftrightarrow> cyclic_on f S\"\n  by (simp add: perm_restrict_def cong: cyclic_cong)\n\nlemma perm_restrict_diff_cyclic:\n  assumes \"f permutes S\" \"cyclic_on f A\"\n  shows \"perm_restrict f (S - A) permutes (S - A)\"\nproof -\n  { fix y\n    have \"\\<exists>x. perm_restrict f (S - A) x = y\"\n    proof cases\n      assume A: \"y \\<in> S - A\"\n      with \\<open>f permutes S\\<close> obtain x where \"f x = y\" \"x \\<in> S\"\n        unfolding permutes_def by auto metis\n      moreover\n      with A have \"x \\<notin> A\" by (metis Diff_iff assms(2) cyclic_on_inI)\n      ultimately\n      have \"perm_restrict f (S - A) x = y\"  by (simp add: perm_restrict_simps)\n      then show ?thesis ..\n    next\n      assume \"y \\<notin> S - A\"\n      then have \"perm_restrict f (S - A) y = y\" by (simp add: perm_restrict_simps)\n      then show ?thesis ..\n    qed\n  } note X = this\n\n  { fix x y assume \"perm_restrict f (S - A) x = perm_restrict f (S - A) y\"\n    with assms have \"x = y\"\n      by (auto simp: perm_restrict_def permutes_def split: if_splits intro: cyclic_on_f_in)\n  } note Y = this\n\n  show ?thesis by (auto simp: permutes_def perm_restrict_simps X intro: Y)\nqed\n\nlemma orbit_eqI:\n  \"y = f x \\<Longrightarrow> y \\<in> orbit f x\"\n  \"z = f y \\<Longrightarrow>y \\<in> orbit f x \\<Longrightarrow>z \\<in> orbit f x\"\n  by (metis orbit.base) (metis orbit.step)\n\nlemma permutes_decompose:\n  assumes \"f permutes S\" \"finite S\"\n  shows \"\\<exists>C. (\\<forall>c \\<in> C. cyclic_on f c) \\<and> \\<Union>C = S \\<and> (\\<forall>c1 \\<in> C. \\<forall>c2 \\<in> C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {})\"\n  using assms(2,1)\nproof (induction arbitrary: f rule: finite_psubset_induct)\n  case (psubset S)\n\n  show ?case\n  proof (cases \"S = {}\")\n    case True then show ?thesis by (intro exI[where x=\"{}\"]) auto\n  next\n    case False\n    then obtain s where \"s \\<in> S\" by auto\n    with \\<open>f permutes S\\<close> have \"orbit f s \\<subseteq> S\"\n      by (rule permutes_orbit_subset)\n    have cyclic_orbit: \"cyclic_on f (orbit f s)\"\n      using \\<open>f permutes S\\<close> \\<open>finite S\\<close> by (rule cyclic_on_orbit)\n\n    let ?f' = \"perm_restrict f (S - orbit f s)\"\n\n    have \"f s \\<in> S\" using \\<open>f permutes S\\<close> \\<open>s \\<in> S\\<close> by (auto simp: permutes_in_image)\n    then have \"S - orbit f s \\<subset> S\" using orbit.base[of f s] \\<open>s \\<in> S\\<close> by blast\n    moreover\n    have \"?f' permutes (S - orbit f s)\"\n      using \\<open>f permutes S\\<close> cyclic_orbit by (rule perm_restrict_diff_cyclic)\n    ultimately\n    obtain C where C: \"\\<And>c. c \\<in> C \\<Longrightarrow> cyclic_on ?f' c\" \"\\<Union>C = S - orbit f s\"\n        \"\\<forall>c1 \\<in> C. \\<forall>c2 \\<in> C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {}\"\n      using psubset.IH by metis\n\n    { fix c assume \"c \\<in> C\"\n      then have *: \"\\<And>x. x \\<in> c \\<Longrightarrow> perm_restrict f (S - orbit f s) x = f x\"\n        using C(2) \\<open>f permutes S\\<close> by (auto simp add: perm_restrict_def)\n      then have \"cyclic_on f c\" using C(1)[OF \\<open>c \\<in> C\\<close>] by (simp cong: cyclic_cong add: *)\n    } note in_C_cyclic = this\n\n    have Un_ins: \"\\<Union>(insert (orbit f s) C) = S\"\n      using \\<open>\\<Union>C = _\\<close>  \\<open>orbit f s \\<subseteq> S\\<close> by blast\n\n    have Disj_ins: \"(\\<forall>c1 \\<in> insert (orbit f s) C. \\<forall>c2 \\<in> insert (orbit f s) C. c1 \\<noteq> c2 \\<longrightarrow> c1 \\<inter> c2 = {})\"\n      using C by auto\n\n    show ?thesis\n      by (intro conjI Un_ins Disj_ins exI[where x=\"insert (orbit f s) C\"])\n        (auto simp: cyclic_orbit in_C_cyclic)\n  qed\nqed\n\n\nsubsection \\<open>Funpow + Orbit\\<close>\n\nlemma funpow_dist_prop:\n  \"y \\<in> orbit f x \\<Longrightarrow> (f ^^ funpow_dist f x y) x = y\"\n  unfolding funpow_dist_def by (rule LeastI_ex) (auto simp: orbit_altdef)\n\nlemma funpow_dist_0_eq:\n  assumes \"y \\<in> orbit f x\" shows \"funpow_dist f x y = 0 \\<longleftrightarrow> x = y\"\n  using assms by (auto simp: funpow_dist_0 dest: funpow_dist_prop)\n\nlemma funpow_dist_step:\n  assumes \"x \\<noteq> y\" \"y \\<in> orbit f x\" shows \"funpow_dist f x y = Suc (funpow_dist f (f x) y)\"\nproof -\n  from \\<open>y \\<in> _\\<close> obtain n where \"(f ^^ n) x = y\" by (auto simp: orbit_altdef)\n  with \\<open>x \\<noteq> y\\<close> obtain n' where [simp]: \"n = Suc n'\" by (cases n) auto\n\n  show ?thesis\n    unfolding funpow_dist_def\n  proof (rule Least_Suc2)\n    show \"(f ^^ n) x = y\" by fact\n    then show \"(f ^^ n') (f x) = y\" by (simp add: funpow_swap1)\n    show \"(f ^^ 0) x \\<noteq> y\" using \\<open>x \\<noteq> y\\<close> by simp\n    show \"\\<forall>k. ((f ^^ Suc k) x = y) = ((f ^^ k) (f x) = y)\"\n      by (simp add: funpow_swap1)\n  qed\nqed\n\nlemma funpow_dist1_prop:\n  assumes \"y \\<in> orbit f x\" shows \"(f ^^ funpow_dist1 f x y) x = y\"\n  by (metis assms funpow.simps(1) funpow_dist_0 funpow_dist_prop funpow_simp_l funpow_swap1 id_apply orbit_step)\n\n(*XXX simplify? *)\nlemma funpow_neq_less_funpow_dist:\n  assumes \"y \\<in> orbit f x\" \"m \\<le> funpow_dist f x y\" \"n \\<le> funpow_dist f x y\" \"m \\<noteq> n\"\n  shows \"(f ^^ m) x \\<noteq> (f ^^ n) x\"\nproof (rule notI)\n  assume A: \"(f ^^ m) x = (f ^^ n) x\"\n\n  define m' n' where \"m' = min m n\" and \"n' = max m n\"\n  with A assms have A': \"m' < n'\" \"(f ^^ m') x = (f ^^ n') x\" \"n' \\<le> funpow_dist f x y\"\n    by (auto simp: min_def max_def)\n\n  have \"y = (f ^^ funpow_dist f x y) x\"\n    using \\<open>y \\<in> _\\<close> by (simp only: funpow_dist_prop)\n  also have \"\\<dots> = (f ^^ ((funpow_dist f x y - n') + n')) x\"\n    using \\<open>n' \\<le> _\\<close> by simp\n  also have \"\\<dots> = (f ^^ ((funpow_dist f x y - n') + m')) x\"\n    by (simp add: funpow_add \\<open>(f ^^ m') x = _\\<close>)\n  also have \"(f ^^ ((funpow_dist f x y - n') + m')) x \\<noteq> y\"\n    using A' by (intro funpow_dist_least) linarith\n  finally show \"False\" by simp\nqed\n\n(* XXX reduce to funpow_neq_less_funpow_dist? *)\nlemma funpow_neq_less_funpow_dist1:\n  assumes \"y \\<in> orbit f x\" \"m < funpow_dist1 f x y\" \"n < funpow_dist1 f x y\" \"m \\<noteq> n\"\n  shows \"(f ^^ m) x \\<noteq> (f ^^ n) x\"\nproof (rule notI)\n  assume A: \"(f ^^ m) x = (f ^^ n) x\"\n\n  define m' n' where \"m' = min m n\" and \"n' = max m n\"\n  with A assms have A': \"m' < n'\" \"(f ^^ m') x = (f ^^ n') x\" \"n' < funpow_dist1 f x y\"\n    by (auto simp: min_def max_def)\n\n  have \"y = (f ^^ funpow_dist1 f x y) x\"\n    using \\<open>y \\<in> _\\<close> by (simp only: funpow_dist1_prop)\n  also have \"\\<dots> = (f ^^ ((funpow_dist1 f x y - n') + n')) x\"\n    using \\<open>n' < _\\<close> by simp\n  also have \"\\<dots> = (f ^^ ((funpow_dist1 f x y - n') + m')) x\"\n    by (simp add: funpow_add \\<open>(f ^^ m') x = _\\<close>)\n  also have \"(f ^^ ((funpow_dist1 f x y - n') + m')) x \\<noteq> y\"\n    using A' by (intro funpow_dist1_least) linarith+\n  finally show \"False\" by simp\nqed\n\nlemma inj_on_funpow_dist:\n  assumes \"y \\<in> orbit f x\" shows \"inj_on (\\<lambda>n. (f ^^ n) x) {0..funpow_dist f x y}\"\n  using funpow_neq_less_funpow_dist[OF assms] by (intro inj_onI) auto\n\n\n\nlemma orbit_conv_funpow_dist1:\n  assumes \"x \\<in> orbit f x\"\n  shows \"orbit f x = (\\<lambda>n. (f ^^ n) x) ` {0..<funpow_dist1 f x x}\" (is \"?L = ?R\")\n  using funpow_dist1_prop[OF assms]\n  by (auto simp: orbit_altdef_bounded[where n=\"funpow_dist1 f x x\"])\n\nlemma funpow_dist1_prop1:\n  assumes \"(f ^^ n) x = y\" \"0 < n\" shows \"(f ^^ funpow_dist1 f x y) x = y\"\nproof -\n  from assms have \"y \\<in> orbit f x\" by (auto simp: orbit_altdef)\n  then show ?thesis by (rule funpow_dist1_prop)\nqed\n\nlemma funpow_dist1_dist:\n  assumes \"funpow_dist1 f x y < funpow_dist1 f x z\"\n  assumes \"{y,z} \\<subseteq> orbit f x\"\n  shows \"funpow_dist1 f x z = funpow_dist1 f x y + funpow_dist1 f y z\" (is \"?L = ?R\")\nproof -\n  have x_z: \"(f ^^ funpow_dist1 f x z) x = z\" using assms by (blast intro: funpow_dist1_prop)\n  have x_y: \"(f ^^ funpow_dist1 f x y) x = y\" using assms by (blast intro: funpow_dist1_prop)\n\n  have \"(f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) y\n      = (f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) ((f ^^ funpow_dist1 f x y) x)\"\n    using x_y by simp\n  also have \"\\<dots> = z\"\n    using assms x_z by (simp del: funpow.simps add: funpow_add_app)\n  finally have y_z_diff: \"(f ^^ (funpow_dist1 f x z - funpow_dist1 f x y)) y = z\" .\n  then have \"(f ^^ funpow_dist1 f y z) y = z\"\n    using assms by (intro funpow_dist1_prop1) auto\n  then have \"(f ^^ funpow_dist1 f y z) ((f ^^ funpow_dist1 f x y) x) = z\"\n    using x_y by simp\n  then have \"(f ^^ (funpow_dist1 f y z + funpow_dist1 f x y)) x = z\"\n    by (simp del: funpow.simps add: funpow_add_app)\n\n  show ?thesis\n  proof (rule antisym)\n    from y_z_diff have \"(f ^^ funpow_dist1 f y z) y = z\"\n      using assms by (intro funpow_dist1_prop1) auto\n    then have \"(f ^^ funpow_dist1 f y z) ((f ^^ funpow_dist1 f x y) x) = z\"\n      using x_y by simp\n    then have \"(f ^^ (funpow_dist1 f y z + funpow_dist1 f x y)) x = z\"\n      by (simp del: funpow.simps add: funpow_add_app)\n    then have \"funpow_dist1 f x z \\<le> funpow_dist1 f y z + funpow_dist1 f x y\"\n      using funpow_dist1_least not_less by fastforce\n    then show \"?L \\<le> ?R\" by presburger\n  next\n    have \"funpow_dist1 f y z \\<le> funpow_dist1 f x z - funpow_dist1 f x y\"\n      using y_z_diff assms(1) by (metis not_less zero_less_diff funpow_dist1_least)\n    then show \"?R \\<le> ?L\" by linarith\n  qed\nqed\n\nlemma funpow_dist1_le_self:\n  assumes \"(f ^^ m) x = x\" \"0 < m\" \"y \\<in> orbit f x\"\n  shows \"funpow_dist1 f x y \\<le> m\"\nproof (cases \"x = y\")\n  case True with assms show ?thesis by (auto dest!: funpow_dist1_least)\nnext\n  case False\n  have \"(f ^^ funpow_dist1 f x y) x = (f ^^ (funpow_dist1 f x y mod m)) x\"\n    using assms by (simp add: funpow_mod_eq)\n  with False \\<open>y \\<in> orbit f x\\<close> have \"funpow_dist1 f x y \\<le> funpow_dist1 f x y mod m\"\n    by auto (metis funpow_dist_least funpow_dist_prop funpow_dist_step funpow_simp_l not_less) \n  with \\<open>m > 0\\<close> show ?thesis\n    by (auto intro: order_trans)\nqed\n\n\nsubsection \\<open>Permutation Domains\\<close>\n\ndefinition has_dom :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"has_dom f S \\<equiv> \\<forall>s. s \\<notin> S \\<longrightarrow> f s = s\"\n\nlemma permutes_conv_has_dom:\n  \"f permutes S \\<longleftrightarrow> bij f \\<and> has_dom f S\"\n  by (auto simp: permutes_def has_dom_def bij_iff)\n\n\n\nsection \\<open>Segments\\<close>\n\ninductive_set segment :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a set\" for f a b where\n  base: \"f a \\<noteq> b \\<Longrightarrow> f a \\<in> segment f a b\" |\n  step: \"x \\<in> segment f a b \\<Longrightarrow> f x \\<noteq> b \\<Longrightarrow> f x \\<in> segment f a b\"\n\nlemma segment_step_2D:\n  assumes \"x \\<in> segment f a (f b)\" shows \"x \\<in> segment f a b \\<or> x = b\"\n  using assms by induct (auto intro: segment.intros)\n\nlemma not_in_segment2D:\n  assumes \"x \\<in> segment f a b\" shows \"x \\<noteq> b\"\n  using assms by induct auto\n\nlemma segment_altdef:\n  assumes \"b \\<in> orbit f a\"\n  shows \"segment f a b = (\\<lambda>n. (f ^^ n) a) ` {1..<funpow_dist1 f a b}\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix x assume \"x \\<in> ?L\"\n  have \"f a \\<noteq>b \\<Longrightarrow> b \\<in> orbit f (f a)\"\n    using assms  by (simp add: orbit_step)\n  then have *: \"f a \\<noteq> b \\<Longrightarrow> 0 < funpow_dist f (f a) b\"\n    using assms using gr0I funpow_dist_0_eq[OF \\<open>_ \\<Longrightarrow> b \\<in> orbit f (f a)\\<close>] by (simp add: orbit.intros)\n  from \\<open>x \\<in> ?L\\<close> show \"x \\<in> ?R\"\n  proof induct\n    case base then show ?case by (intro image_eqI[where x=1]) (auto simp: *)\n  next\n    case step then show ?case using assms funpow_dist1_prop less_antisym\n      by (fastforce intro!: image_eqI[where x=\"Suc n\" for n])\n  qed\nnext\n  fix x assume \"x \\<in> ?R\"\n  then obtain n where \"(f ^^ n ) a = x\" \"0 < n\" \"n < funpow_dist1 f a b\" by auto\n  then show \"x \\<in> ?L\"\n  proof (induct n arbitrary: x)\n    case 0 then show ?case by simp\n  next\n    case (Suc n)\n    have \"(f ^^ Suc n) a \\<noteq> b\" using Suc by (meson funpow_dist1_least)\n    with Suc show ?case by (cases \"n = 0\") (auto intro: segment.intros)\n  qed\nqed\n\n(*XXX move up*)\nlemma segmentD_orbit:\n  assumes \"x \\<in> segment f y z\" shows \"x \\<in> orbit f y\"\n  using assms by induct (auto intro: orbit.intros)\n\nlemma segment1_empty: \"segment f x (f x) = {}\"\n  by (auto simp: segment_altdef orbit.base funpow_dist_0)\n\nlemma segment_subset:\n  assumes \"y \\<in> segment f x z\"\n  assumes \"w \\<in> segment f x y\"\n  shows \"w \\<in> segment f x z\"\n  using assms by (induct arbitrary: w) (auto simp: segment1_empty intro: segment.intros dest: segment_step_2D elim: segment.cases)\n\n(* XXX move up*)\nlemma not_in_segment1:\n  assumes \"y \\<in> orbit f x\" shows \"x \\<notin> segment f x y\"\nproof\n  assume \"x \\<in> segment f x y\"\n  then obtain n where n: \"0 < n\" \"n < funpow_dist1 f x y\" \"(f ^^ n) x = x\"\n    using assms by (auto simp: segment_altdef Suc_le_eq)\n  then have neq_y: \"(f ^^ (funpow_dist1 f x y - n)) x \\<noteq> y\" by (simp add: funpow_dist1_least)\n\n  have \"(f ^^ (funpow_dist1 f x y - n)) x = (f ^^ (funpow_dist1 f x y - n)) ((f ^^ n) x)\"\n    using n by (simp add: funpow_add_app)\n  also have \"\\<dots> = (f ^^ funpow_dist1 f x y) x\"\n    using \\<open>n < _\\<close> by (simp add: funpow_add_app)\n  also have \"\\<dots> = y\" using assms by (rule funpow_dist1_prop)\n  finally show False using neq_y by contradiction\nqed\n\nlemma not_in_segment2: \"y \\<notin> segment f x y\"\n  using not_in_segment2D by metis\n\n(*XXX move*)\nlemma in_segmentE:\n  assumes \"y \\<in> segment f x z\" \"z \\<in> orbit f x\"\n  obtains \"(f ^^ funpow_dist1 f x y) x = y\" \"funpow_dist1 f x y < funpow_dist1 f x z\"\nproof\n  from assms show \"(f ^^ funpow_dist1 f x y) x = y\"\n    by (intro segmentD_orbit funpow_dist1_prop)\n  moreover\n  obtain n where \"(f ^^ n) x = y\" \"0 < n\" \"n < funpow_dist1 f x z\"\n    using assms by (auto simp: segment_altdef)\n  moreover then have \"funpow_dist1 f x y \\<le> n\" by (meson funpow_dist1_least not_less)\n  ultimately show \"funpow_dist1 f x y < funpow_dist1 f x z\" by linarith\nqed\n\n(*XXX move*)\nlemma cyclic_split_segment:\n  assumes S: \"cyclic_on f S\" \"a \\<in> S\" \"b \\<in> S\" and \"a \\<noteq> b\"\n  shows \"S = {a,b} \\<union> segment f a b \\<union> segment f b a\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix c assume \"c \\<in> ?L\"\n  with S have \"c \\<in> orbit f a\" unfolding cyclic_on_alldef by auto\n  then show \"c \\<in> ?R\" by induct (auto intro: segment.intros)\nnext\n  fix c assume \"c \\<in> ?R\"\n  moreover have \"segment f a b \\<subseteq> orbit f a\" \"segment f b a \\<subseteq> orbit f b\"\n    by (auto dest: segmentD_orbit)\n  ultimately show \"c \\<in> ?L\" using S by (auto simp: cyclic_on_alldef)\nqed\n\n(*XXX move*)\nlemma segment_split:\n  assumes y_in_seg: \"y \\<in> segment f x z\"\n  shows \"segment f x z = segment f x y \\<union> {y} \\<union> segment f y z\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix w assume \"w \\<in> ?L\" then show \"w \\<in> ?R\" by induct (auto intro: segment.intros)\nnext\n  fix w assume \"w \\<in> ?R\"\n  moreover\n  { assume \"w \\<in> segment f x y\" then have \"w \\<in> segment f x z\"\n    using segment_subset[OF y_in_seg] by auto }\n  moreover\n  { assume \"w \\<in> segment f y z\" then have \"w \\<in> segment f x z\"\n      using y_in_seg by induct (auto intro: segment.intros) }\n  ultimately\n  show \"w \\<in> ?L\" using y_in_seg by (auto intro: segment.intros)\nqed\n\nlemma in_segmentD_inv:\n  assumes \"x \\<in> segment f a b\" \"x \\<noteq> f a\"\n  assumes \"inj f\"\n  shows \"inv f x \\<in> segment f a b\"\n  using assms by (auto elim: segment.cases)\n\nlemma in_orbit_invI:\n  assumes \"b \\<in> orbit f a\"\n  assumes \"inj f\"\n  shows \"a \\<in> orbit (inv f) b\"\n  using assms(1)\n  apply induct\n   apply (simp add: assms(2) orbit_eqI(1))\n  by (metis assms(2) inv_f_f orbit.base orbit_trans)\n\nlemma segment_step_2:\n  assumes A: \"x \\<in> segment f a b\" \"b \\<noteq> a\" and \"inj f\"\n  shows \"x \\<in> segment f a (f b)\"\n  using A by induct (auto intro: segment.intros dest: not_in_segment2D injD[OF \\<open>inj f\\<close>])\n\nlemma inv_end_in_segment:\n  assumes \"b \\<in> orbit f a\" \"f a \\<noteq> b\" \"bij f\"\n  shows \"inv f b \\<in> segment f a b\"\n  using assms(1,2)\nproof induct\n  case base then show ?case by simp\nnext\n  case (step x)\n  moreover\n  from \\<open>bij f\\<close> have \"inj f\" by (rule bij_is_inj)\n  moreover\n  then have \"x \\<noteq> f x \\<Longrightarrow> f a = x \\<Longrightarrow> x \\<in> segment f a (f x)\" by (meson segment.simps)\n  moreover\n  have \"x \\<noteq> f x\"\n    using step \\<open>inj f\\<close> by (metis in_orbit_invI inv_f_eq not_in_segment1 segment.base)\n  then have \"inv f x \\<in> segment f a (f x) \\<Longrightarrow> x \\<in> segment f a (f x)\"\n    using \\<open>bij f\\<close> \\<open>inj f\\<close> by (auto dest: segment.step simp: surj_f_inv_f bij_is_surj)\n  then have \"inv f x \\<in> segment f a x \\<Longrightarrow> x \\<in> segment f a (f x)\"\n    using \\<open>f a \\<noteq> f x\\<close> \\<open>inj f\\<close> by (auto dest: segment_step_2 injD)\n  ultimately show ?case by (cases \"f a = x\") simp_all\nqed\n\nlemma segment_overlapping:\n  assumes \"x \\<in> orbit f a\" \"x \\<in> orbit f b\" \"bij f\"\n  shows \"segment f a x \\<subseteq> segment f b x \\<or> segment f b x \\<subseteq> segment f a x\"\n  using assms(1,2)\nproof induction\n  case base then show ?case by (simp add: segment1_empty)\nnext\n  case (step x)\n  from \\<open>bij f\\<close> have \"inj f\" by (simp add: bij_is_inj)\n  have *: \"\\<And>f x y. y \\<in> segment f x (f x) \\<Longrightarrow> False\" by (simp add: segment1_empty)\n  { fix y z\n    assume A: \"y \\<in> segment f b (f x)\" \"y \\<notin> segment f a (f x)\" \"z \\<in> segment f a (f x)\"\n    from \\<open>x \\<in> orbit f a\\<close> \\<open>f x \\<in> orbit f b\\<close> \\<open>y \\<in> segment f b (f x)\\<close>\n    have \"x \\<in> orbit f b\"\n      by (metis * inv_end_in_segment[OF _ _ \\<open>bij f\\<close>] inv_f_eq[OF \\<open>inj f\\<close>] segmentD_orbit)\n    moreover\n    with \\<open>x \\<in> orbit f a\\<close> step.IH\n    have \"segment f a (f x) \\<subseteq> segment f b (f x) \\<or> segment f b (f x) \\<subseteq> segment f a (f x)\"\n      apply auto\n       apply (metis * inv_end_in_segment[OF _ _ \\<open>bij f\\<close>] inv_f_eq[OF \\<open>inj f\\<close>] segment_step_2D segment_subset step.prems subsetCE)\n      by (metis (no_types, lifting) \\<open>inj f\\<close> * inv_end_in_segment[OF _ _ \\<open>bij f\\<close>] inv_f_eq orbit_eqI(2) segment_step_2D segment_subset subsetCE)\n    ultimately\n    have \"segment f a (f x) \\<subseteq> segment f b (f x)\" using A by auto\n  } note C = this\n  then show ?case by auto\nqed\n\nlemma segment_disj:\n  assumes \"a \\<noteq> b\" \"bij f\"\n  shows \"segment f a b \\<inter> segment f b a = {}\"\nproof (rule ccontr)\n  assume \"\\<not>?thesis\"\n  then obtain x where x: \"x \\<in> segment f a b\" \"x \\<in> segment f b a\" by blast\n  then have \"segment f a b = segment f a x \\<union> {x} \\<union> segment f x b\"\n      \"segment f b a = segment f b x \\<union> {x} \\<union> segment f x a\"\n    by (auto dest: segment_split)\n  then have o: \"x \\<in> orbit f a\" \"x \\<in> orbit f b\" by (auto dest: segmentD_orbit)\n\n  note * = segment_overlapping[OF o \\<open>bij f\\<close>]\n  have \"inj f\" using \\<open>bij f\\<close> by (simp add: bij_is_inj)\n\n  have \"segment f a x = segment f b x\"\n  proof (intro set_eqI iffI)\n    fix y assume A: \"y \\<in> segment f b x\"\n    then have \"y \\<in> segment f a x \\<or> f a \\<in> segment f b a\"\n      using * x(2) by (auto intro: segment.base segment_subset)\n    then show \"y \\<in> segment f a x\"\n      using \\<open>inj f\\<close> A by (metis (no_types) not_in_segment2 segment_step_2)\n  next\n    fix y assume A: \"y \\<in> segment f a x \"\n    then have \"y \\<in> segment f b x \\<or> f b \\<in> segment f a b\"\n      using * x(1) by (auto intro: segment.base segment_subset)\n    then show \"y \\<in> segment f b x\"\n      using \\<open>inj f\\<close> A by (metis (no_types) not_in_segment2 segment_step_2)\n  qed\n  moreover\n  have \"segment f a x \\<noteq> segment f b x\"\n    by (metis assms bij_is_inj not_in_segment2 segment.base segment_step_2 segment_subset x(1))\n  ultimately show False by contradiction\nqed\n\nlemma segment_x_x_eq:\n  assumes \"permutation f\"\n  shows \"segment f x x = orbit f x - {x}\" (is \"?L = ?R\")\nproof (intro set_eqI iffI)\n  fix y assume \"y \\<in> ?L\" then show \"y \\<in> ?R\" by (auto dest: segmentD_orbit simp: not_in_segment2)\nnext\n  fix y assume \"y \\<in> ?R\"\n  then have \"y \\<in> orbit f x\" \"y \\<noteq> x\" by auto\n  then show \"y \\<in> ?L\" by induct (auto intro: segment.intros)\nqed\n\n\n\nsection \\<open>Lists of Powers\\<close>\n\ndefinition iterate :: \"nat \\<Rightarrow> nat \\<Rightarrow> ('a \\<Rightarrow> 'a ) \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"iterate m n f x = map (\\<lambda>n. (f^^n) x) [m..<n]\"\n\nlemma set_iterate:\n  \"set (iterate m n f x) = (\\<lambda>k. (f ^^ k) x) ` {m..<n} \"\n  by (auto simp: iterate_def)\n\nlemma iterate_empty[simp]: \"iterate n m f x = [] \\<longleftrightarrow> m \\<le> n\"\n  by (auto simp: iterate_def)\n\n\n\nlemma iterate_nth[simp]:\n  assumes \"k < n - m\" shows \"iterate m n f x ! k = (f^^(m+k)) x\"\n  using assms\n  by (induct k arbitrary: m) (auto simp: iterate_def)\n\nlemma iterate_applied:\n  \"iterate n m f (f x) = iterate (Suc n) (Suc m) f x\"\n  by (induct m arbitrary: n) (auto simp: iterate_def funpow_swap1)\n\nend\n", "meta": {"author": "jepsen-io", "repo": "elle", "sha": "fc04f273786684bbd0dd85f09e01a79b483e9c98", "save_path": "github-repos/isabelle/jepsen-io-elle", "path": "github-repos/isabelle/jepsen-io-elle/elle-fc04f273786684bbd0dd85f09e01a79b483e9c98/proof/graphs/Funpow.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8688267881258485, "lm_q1q2_score": 0.7721774454086971}}
{"text": "(*\n  Boolean Expression Checkers Based on Binary Decision Trees\n  Author: Tobias Nipkow\n*)\n\ntheory Boolean_Expression_Checkers\n  imports Main \"HOL-Library.Mapping\" \"Eval_Base.Eval_Base\"\nbegin\n\nsection \\<open>Tautology (etc) Checking via Binary Decision Trees\\<close>\n\nsubsection \\<open>Binary Decision Trees\\<close>\n\ndatatype 'a ifex = Trueif | Falseif | IF 'a \"'a ifex\" \"'a ifex\"\n\nfun val_ifex :: \"'a ifex \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" \nwhere\n  \"val_ifex Trueif s = True\"\n| \"val_ifex Falseif s = False\"\n| \"val_ifex (IF n t1 t2) s = (if s n then val_ifex t1 s else val_ifex t2 s)\"\n\nsubsubsection \\<open>Environment\\<close>\n\ntext \\<open>Environments are substitutions of values for variables:\\<close>\n\ntype_synonym 'a env_bool = \"('a, bool) mapping\"\n\ndefinition agree :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a env_bool \\<Rightarrow> bool\"\nwhere\n  \"agree s env = (\\<forall>x b. Mapping.lookup env x = Some b \\<longrightarrow> s x = b)\"\n\nlemma agree_Nil: \n  \"agree s Mapping.empty\"\n  by (simp add: agree_def lookup_empty)\n\nlemma lookup_update_unfold: \n  \"Mapping.lookup (Mapping.update k v m) k' = (if k = k' then Some v else Mapping.lookup m k')\"\n  using lookup_update lookup_update_neq by metis\n\nlemma agree_Cons: \n  \"x \\<notin> Mapping.keys env \\<Longrightarrow> agree s (Mapping.update x b env) = ((if b then s x else \\<not> s x) \\<and> agree s env)\"\n  by (simp add: agree_def lookup_update_unfold; unfold keys_is_none_rep lookup_update_unfold Option.is_none_def; blast)\n\nlemma agreeDT:\n  \"agree s env \\<Longrightarrow> Mapping.lookup env x = Some True \\<Longrightarrow> s x\"\n  by (simp add: agree_def)\n\nlemma agreeDF:\n  \"agree s env \\<Longrightarrow> Mapping.lookup env x = Some False \\<Longrightarrow> \\<not>s x\"\n  by (auto simp add: agree_def)\n\nsubsection \\<open>Recursive Tautology Checker\\<close>\n\ntext \\<open>Provided for completeness. However, it is recommend to use the checkers based on reduced trees.\\<close>\n\nfun taut_test_rec :: \"'a ifex \\<Rightarrow> 'a env_bool \\<Rightarrow> bool\" \nwhere\n  \"taut_test_rec Trueif env = True\" \n| \"taut_test_rec Falseif env = False\" \n| \"taut_test_rec (IF x t1 t2) env = (case Mapping.lookup env x of\n  Some b \\<Rightarrow> taut_test_rec (if b then t1 else t2) env |\n  None \\<Rightarrow> taut_test_rec t1 (Mapping.update x True env) \\<and> taut_test_rec t2 (Mapping.update x False env))\"\n\nlemma taut_test_rec: \n  \"taut_test_rec t env = (\\<forall>s. agree s env \\<longrightarrow> val_ifex t s)\"\nproof2 (induction t arbitrary: env)\n  case Falseif\n    have \"agree (\\<lambda>x. the (Mapping.lookup env x)) env\" \n      by (auto simp: agree_def)\n    thus ?case \n      by auto\nnext\n  case (IF x t1 t2) \n    thus ?case\n    proof (cases \"Mapping.lookup env x\")\n      case None \n        with IF show ?thesis \n          by simp (metis is_none_simps(1) agree_Cons keys_is_none_rep)\n    qed (simp add: agree_def)\nqed simp\n\ndefinition taut_test_ifex :: \"'a ifex \\<Rightarrow> bool\" \nwhere\n  \"taut_test_ifex t = taut_test_rec t Mapping.empty\"\n\ncorollary taut_test_ifex: \n  \"taut_test_ifex t = (\\<forall>s. val_ifex t s)\"\n  by (auto simp: taut_test_ifex_def taut_test_rec agree_Nil)\n\nsubsection \\<open>Reduced Binary Decision Trees\\<close>\n\nsubsubsection \\<open>Normalisation\\<close>\n\ntext \\<open>A normalisation avoiding duplicate variables and collapsing @{term \"If x t t\"} to \\<open>t\\<close>.\\<close>\n\ndefinition mkIF :: \"'a \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\" \nwhere\n  \"mkIF x t1 t2 = (if t1=t2 then t1 else IF x t1 t2)\"\n\nfun reduce :: \"'a env_bool \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\"\nwhere\n  \"reduce env (IF x t1 t2) = (case Mapping.lookup env x of\n     None \\<Rightarrow> mkIF x (reduce (Mapping.update x True env) t1) (reduce (Mapping.update x False env) t2) |\n     Some b \\<Rightarrow> reduce env (if b then t1 else t2))\" \n| \"reduce _ t = t\"\n\nprimrec normif :: \"'a env_bool \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex \\<Rightarrow> 'a ifex\" \nwhere\n  \"normif env Trueif t1 t2 = reduce env t1\" \n| \"normif env Falseif t1 t2 = reduce env t2\" \n| \"normif env (IF x t1 t2) t3 t4 =\n    (case Mapping.lookup env x of\n       None \\<Rightarrow> mkIF x (normif (Mapping.update x True env) t1 t3 t4) (normif (Mapping.update x False env) t2 t3 t4) |\n       Some b \\<Rightarrow> if b then normif env t1 t3 t4 else normif env t2 t3 t4)\"\n\nsubsubsection \\<open>Functional Correctness Proof\\<close>\n\nlemma val_mkIF: \n  \"val_ifex (mkIF x t1 t2) s = val_ifex (IF x t1 t2) s\"\n  by (auto simp: mkIF_def Let_def)\n\ntheorem val_reduce: \n  \"agree s env \\<Longrightarrow> val_ifex (reduce env t) s = val_ifex t s\"\n  apply2 (induction t arbitrary: s env)\n  by(auto simp: map_of_eq_None_iff val_mkIF agree_Cons Let_def keys_is_none_rep\n           dest: agreeDT agreeDF split: option.splits) \n\nlemma val_normif: \n  \"agree s env \\<Longrightarrow> val_ifex (normif env t t1 t2) s = val_ifex (if val_ifex t s then t1 else t2) s\"\n  apply2 (induct t arbitrary: t1 t2 s env)\n  by(auto simp: val_reduce val_mkIF agree_Cons map_of_eq_None_iff keys_is_none_rep\n           dest: agreeDT agreeDF split: option.splits)   \n\nsubsubsection \\<open>Reduced If-Expressions\\<close>\n\ntext \\<open>An expression reduced iff no variable appears twice on any branch and there is no subexpression @{term \"IF x t t\"}.\\<close>\n\nfun reduced :: \"'a ifex \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"reduced (IF x t1 t2) X =\n  (x \\<notin> X \\<and> t1 \\<noteq> t2 \\<and> reduced t1 (insert x X) \\<and> reduced t2 (insert x X))\" |\n\"reduced _ _ = True\"\n\nlemma reduced_antimono: \n  \"X \\<subseteq> Y \\<Longrightarrow> reduced t Y \\<Longrightarrow> reduced t X\"\n  apply2 (induction t arbitrary: X Y)\n  by (auto, (metis insert_mono)+)\n\nlemma reduced_mkIF: \n  \"x \\<notin> X \\<Longrightarrow> reduced t1 (insert x X) \\<Longrightarrow> reduced t2 (insert x X) \\<Longrightarrow> reduced (mkIF x t1 t2) X\"\n  by (auto simp: mkIF_def intro:reduced_antimono)\n\nlemma reduced_reduce:\n  \"reduced (reduce env t) (Mapping.keys env)\"\nproof2(induction t arbitrary: env)\n  case (IF x t1 t2)\n    thus ?case \n      using IF.IH(1) IF.IH(2)\n      apply (auto simp: map_of_eq_None_iff image_iff reduced_mkIF split: option.split) \n      by (metis is_none_code(1) keys_is_none_rep keys_update reduced_mkIF)\nqed auto\n\nlemma reduced_normif:\n  \"reduced (normif env t t1 t2) (Mapping.keys env)\"\nproof2(induction t arbitrary: t1 t2 env)\n  case (IF x s1 s2)\n  thus ?case using IF.IH\n    apply (auto simp: reduced_mkIF map_of_eq_None_iff split: option.split) \n    by (metis is_none_code(1) keys_is_none_rep keys_update reduced_mkIF)\nqed (auto simp: reduced_reduce)\n\nsubsubsection \\<open>Checkers Based on Reduced Binary Decision Trees\\<close>\n\ntext \\<open>The checkers are parameterized over the translation function to binary decision trees. \n  They rely on the fact that @{term ifex_of} produces reduced trees\\<close>\n\ndefinition taut_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"taut_test ifex_of b = (ifex_of b = Trueif)\"\n\ndefinition sat_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"sat_test ifex_of b = (ifex_of b \\<noteq> Falseif)\"\n\ndefinition impl_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"impl_test ifex_of b1 b2 = (normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif = Trueif)\"\n\ndefinition equiv_test :: \"('a \\<Rightarrow> 'b ifex) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \nwhere\n  \"equiv_test ifex_of b1 b2 = (let t1 = ifex_of b1; t2 = ifex_of b2 \n    in Trueif = normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif))\"\n\nlocale reduced_bdt_checkers = \n  fixes\n    ifex_of :: \"'b \\<Rightarrow> 'a ifex\"\n  fixes\n    val :: \"'b \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  assumes\n    val_ifex: \"val_ifex (ifex_of b) s = val b s\"\n  assumes \n    reduced_ifex: \"reduced (ifex_of b) {}\"\nbegin\n\ntext \\<open>Proof that reduced if-expressions are @{const Trueif}, @{const Falseif}\nor can evaluate to both @{const True} and @{const False}.\\<close>\n\nlemma same_val_if_reduced:\n  \"reduced t X \\<Longrightarrow> \\<forall>x. x \\<notin> X \\<longrightarrow> s1 x = s2 x \\<Longrightarrow> val_ifex t s1 = val_ifex t s2\"\n  apply2 (induction t arbitrary: X) by auto\n\nlemma reduced_IF_depends: \n  \"\\<lbrakk> reduced t X; t \\<noteq> Trueif; t \\<noteq> Falseif \\<rbrakk> \\<Longrightarrow> \\<exists>s1 s2. val_ifex t s1 \\<noteq> val_ifex t s2\"\nproof2(induction t arbitrary: X)\n  case (IF x t1 t2)\n  let ?t = \"IF x t1 t2\"\n  have 1: \"reduced t1 (insert x X)\" using IF.prems(1) by simp\n  have 2: \"reduced t2 (insert x X)\" using IF.prems(1) by simp\n  show ?case\n  proof(cases t1)\n    case [simp]: Trueif\n    show ?thesis\n    proof (cases t2)\n      case Trueif thus ?thesis using IF.prems(1) by simp\n    next\n      case Falseif\n      hence \"val_ifex ?t (\\<lambda>_. True) \\<noteq> val_ifex ?t (\\<lambda>_. False)\" by simp\n      thus ?thesis by blast\n    next\n      case IF\n      then obtain s1 s2 where \"val_ifex t2 s1 \\<noteq> val_ifex t2 s2\"\n        using IF.IH(2)[OF 2] IF.prems(1) by auto\n      hence \"val_ifex ?t (s1(x:=False)) \\<noteq> val_ifex ?t (s2(x:=False))\"\n        using same_val_if_reduced[OF 2, of \"s1(x:=False)\" s1]\n          same_val_if_reduced[OF 2, of \"s2(x:=False)\" s2] by simp\n      thus ?thesis by blast\n    qed\n  next\n    case [simp]: Falseif\n    show ?thesis\n    proof (cases t2)\n      case Falseif thus ?thesis using IF.prems(1) by simp\n    next\n      case Trueif\n      hence \"val_ifex ?t (\\<lambda>_. True) \\<noteq> val_ifex ?t (\\<lambda>_. False)\" by simp\n      thus ?thesis by blast\n    next\n      case IF\n      then obtain s1 s2 where \"val_ifex t2 s1 \\<noteq> val_ifex t2 s2\"\n        using IF.IH(2)[OF 2] IF.prems(1) by auto\n      hence \"val_ifex ?t (s1(x:=False)) \\<noteq> val_ifex ?t (s2(x:=False))\"\n        using same_val_if_reduced[OF 2, of \"s1(x:=False)\" s1]\n          same_val_if_reduced[OF 2, of \"s2(x:=False)\" s2] by simp\n      thus ?thesis by blast\n    qed\n  next\n    case IF\n    then obtain s1 s2 where \"val_ifex t1 s1 \\<noteq> val_ifex t1 s2\"\n      using IF.IH(1)[OF 1] IF.prems(1) by auto\n    hence \"val_ifex ?t (s1(x:=True)) \\<noteq> val_ifex ?t (s2(x:=True))\"\n      using same_val_if_reduced[OF 1, of \"s1(x:=True)\" s1]\n          same_val_if_reduced[OF 1, of \"s2(x:=True)\" s2] by simp\n    thus ?thesis by blast\n  qed\nqed auto\n\ncorollary taut_test: \n  \"taut_test ifex_of b = (\\<forall>s. val b s)\"    \n  by (metis taut_test_def reduced_IF_depends[OF reduced_ifex] val_ifex val_ifex.simps(1,2))\n\ncorollary sat_test: \n  \"sat_test ifex_of b = (\\<exists>s. val b s)\"\n  by (metis sat_test_def reduced_IF_depends[OF reduced_ifex] val_ifex val_ifex.simps(1,2))\n\ncorollary impl_test: \n  \"impl_test ifex_of b1 b2 = (\\<forall>s. val b1 s \\<longrightarrow> val b2 s)\"\nproof -\n  have \"impl_test ifex_of b1 b2 = (\\<forall>s. val_ifex (normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif) s)\"\n    using reduced_IF_depends[OF reduced_normif] by (fastforce  simp: impl_test_def)\n  also\n  have \"(\\<forall>s. val_ifex (normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif) s) \\<longleftrightarrow> (\\<forall>s. val b1 s \\<longrightarrow> val b2 s)\"\n    using reduced_IF_depends[OF reduced_ifex] val_ifex unfolding val_normif[OF agree_Nil] by simp\n  finally\n  show ?thesis .\nqed\n\ncorollary equiv_test: \n  \"equiv_test ifex_of b1 b2 = (\\<forall>s. val b1 s = val b2 s)\"\nproof -\n  have \"equiv_test ifex_of b1 b2 = (\\<forall>s. val_ifex (let t1 = ifex_of b1; t2 = ifex_of b2 in normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif)) s)\"\n    by (simp add: equiv_test_def Let_def; insert reduced_IF_depends[OF reduced_normif]; force)\n  moreover\n  {\n    fix s\n    have \"val_ifex (let t1 = ifex_of b1; t2 = ifex_of b2 in normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif)) s\n      = (val b1 s = val b2 s)\"\n      using val_ifex by (simp add: Let_def val_normif[OF agree_Nil]) \n  }\n  ultimately\n  show ?thesis \n    by blast\nqed\n\nend\n\nsubsection \\<open>Boolean Expressions\\<close>\n\ntext \\<open>This is the simplified interface to the tautology checker. If you have your own type of Boolean \nexpressions you can either define your own translation to reduced binary decision trees or you can just \ntranslate into this type.\\<close>\n\ndatatype 'a bool_expr =\n  Const_bool_expr bool |\n  Atom_bool_expr 'a |\n  Neg_bool_expr \"'a bool_expr\" |\n  And_bool_expr \"'a bool_expr\" \"'a bool_expr\" |\n  Or_bool_expr \"'a bool_expr\" \"'a bool_expr\" |\n  Imp_bool_expr \"'a bool_expr\" \"'a bool_expr\" |\n  Iff_bool_expr \"'a bool_expr\" \"'a bool_expr\"\n\nprimrec val_bool_expr :: \"'a bool_expr \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"val_bool_expr (Const_bool_expr b) s = b\" |\n\"val_bool_expr (Atom_bool_expr x) s = s x\" |\n\"val_bool_expr (Neg_bool_expr b) s = (\\<not> val_bool_expr b s)\" |\n\"val_bool_expr (And_bool_expr b1 b2) s = (val_bool_expr b1 s \\<and> val_bool_expr b2 s)\" |\n\"val_bool_expr (Or_bool_expr b1 b2) s = (val_bool_expr b1 s \\<or> val_bool_expr b2 s)\" |\n\"val_bool_expr (Imp_bool_expr b1 b2) s = (val_bool_expr b1 s \\<longrightarrow> val_bool_expr b2 s)\" |\n\"val_bool_expr (Iff_bool_expr b1 b2) s = (val_bool_expr b1 s = val_bool_expr b2 s)\"\n\nfun ifex_of :: \"'a bool_expr \\<Rightarrow> 'a ifex\" where\n\"ifex_of (Const_bool_expr b) = (if b then Trueif else Falseif)\" |\n\"ifex_of (Atom_bool_expr x)   = IF x Trueif Falseif\" |\n\"ifex_of (Neg_bool_expr b)   = normif Mapping.empty (ifex_of b) Falseif Trueif\" |\n\"ifex_of (And_bool_expr b1 b2) = normif Mapping.empty (ifex_of b1) (ifex_of b2) Falseif\" |\n\"ifex_of (Or_bool_expr b1 b2) = normif Mapping.empty (ifex_of b1) Trueif (ifex_of b2)\" |\n\"ifex_of (Imp_bool_expr b1 b2) = normif Mapping.empty (ifex_of b1) (ifex_of b2) Trueif\" |\n\"ifex_of (Iff_bool_expr b1 b2) = (let t1 = ifex_of b1; t2 = ifex_of b2 in\n   normif Mapping.empty t1 t2 (normif Mapping.empty t2 Falseif Trueif))\"\n\ntheorem val_ifex:\n  \"val_ifex (ifex_of b) s = val_bool_expr b s\"\n  apply2(induct_tac b) by(auto simp: val_normif agree_Nil Let_def)\n\ntheorem reduced_ifex: \n  \"reduced (ifex_of b) {}\"\n  apply2(induction b) by(simp add: Let_def; metis keys_empty reduced_normif)+\n\ndefinition \"bool_taut_test \\<equiv> taut_test ifex_of\"\ndefinition \"bool_sat_test \\<equiv> sat_test ifex_of\"\ndefinition \"bool_impl_test \\<equiv> impl_test ifex_of\"\ndefinition \"bool_equiv_test \\<equiv> equiv_test ifex_of\"\n\nlemma bool_tests:\n  \"bool_taut_test b = (\\<forall>s. val_bool_expr b s)\" (is ?t1)\n  \"bool_sat_test b = (\\<exists>s. val_bool_expr b s)\" (is ?t2)\n  \"bool_impl_test b1 b2 = (\\<forall>s. val_bool_expr b1 s \\<longrightarrow> val_bool_expr b2 s)\" (is ?t3)\n  \"bool_equiv_test b1 b2 = (\\<forall>s. val_bool_expr b1 s \\<longleftrightarrow> val_bool_expr b2 s)\" (is ?t4)\nproof -\n  interpret reduced_bdt_checkers ifex_of val_bool_expr\n    by (unfold_locales; insert val_ifex reduced_ifex; blast)\n  show ?t1 ?t2 ?t3 ?t4\n    by (simp_all add: bool_taut_test_def bool_sat_test_def bool_impl_test_def bool_equiv_test_def taut_test sat_test impl_test equiv_test) \nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Boolean_Expression_Checkers/Boolean_Expression_Checkers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8688267762381844, "lm_q1q2_score": 0.7721774425233062}}
{"text": "(*  Title:      HOL/Analysis/L2_Norm.thy\n    Author:     Brian Huffman, Portland State University\n*)\n\nchapter \\<open>Linear Algebra\\<close>\n\ntheory L2_Norm\nimports Complex_Main\nbegin\n\nsection \\<open>L2 Norm\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> L2_set :: \"('a \\<Rightarrow> real) \\<Rightarrow> 'a set \\<Rightarrow> real\" where\n\"L2_set f A = sqrt (\\<Sum>i\\<in>A. (f i)\\<^sup>2)\"\n\nlemma L2_set_cong:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> L2_set f A = L2_set g B\"\n  unfolding L2_set_def by simp\n\nlemma L2_set_cong_simp:\n  \"\\<lbrakk>A = B; \\<And>x. x \\<in> B =simp=> f x = g x\\<rbrakk> \\<Longrightarrow> L2_set f A = L2_set g B\"\n  unfolding L2_set_def simp_implies_def by simp\n\nlemma L2_set_infinite [simp]: \"\\<not> finite A \\<Longrightarrow> L2_set f A = 0\"\n  unfolding L2_set_def by simp\n\nlemma L2_set_empty [simp]: \"L2_set f {} = 0\"\n  unfolding L2_set_def by simp\n\nlemma L2_set_insert [simp]:\n  \"\\<lbrakk>finite F; a \\<notin> F\\<rbrakk> \\<Longrightarrow>\n    L2_set f (insert a F) = sqrt ((f a)\\<^sup>2 + (L2_set f F)\\<^sup>2)\"\n  unfolding L2_set_def by (simp add: sum_nonneg)\n\nlemma L2_set_nonneg [simp]: \"0 \\<le> L2_set f A\"\n  unfolding L2_set_def by (simp add: sum_nonneg)\n\nlemma L2_set_0': \"\\<forall>a\\<in>A. f a = 0 \\<Longrightarrow> L2_set f A = 0\"\n  unfolding L2_set_def by simp\n\nlemma L2_set_constant: \"L2_set (\\<lambda>x. y) A = sqrt (of_nat (card A)) * \\<bar>y\\<bar>\"\n  unfolding L2_set_def by (simp add: real_sqrt_mult)\n\nlemma L2_set_mono:\n  assumes \"\\<And>i. i \\<in> K \\<Longrightarrow> f i \\<le> g i\"\n  assumes \"\\<And>i. i \\<in> K \\<Longrightarrow> 0 \\<le> f i\"\n  shows \"L2_set f K \\<le> L2_set g K\"\n  unfolding L2_set_def\n  by (simp add: sum_nonneg sum_mono power_mono assms)\n\nlemma L2_set_strict_mono:\n  assumes \"finite K\" and \"K \\<noteq> {}\"\n  assumes \"\\<And>i. i \\<in> K \\<Longrightarrow> f i < g i\"\n  assumes \"\\<And>i. i \\<in> K \\<Longrightarrow> 0 \\<le> f i\"\n  shows \"L2_set f K < L2_set g K\"\n  unfolding L2_set_def\n  by (simp add: sum_strict_mono power_strict_mono assms)\n\nlemma L2_set_right_distrib:\n  \"0 \\<le> r \\<Longrightarrow> r * L2_set f A = L2_set (\\<lambda>x. r * f x) A\"\n  unfolding L2_set_def\n  apply (simp add: power_mult_distrib)\n  apply (simp add: sum_distrib_left [symmetric])\n  apply (simp add: real_sqrt_mult sum_nonneg)\n  done\n\nlemma L2_set_left_distrib:\n  \"0 \\<le> r \\<Longrightarrow> L2_set f A * r = L2_set (\\<lambda>x. f x * r) A\"\n  unfolding L2_set_def\n  apply (simp add: power_mult_distrib)\n  apply (simp add: sum_distrib_right [symmetric])\n  apply (simp add: real_sqrt_mult sum_nonneg)\n  done\n\nlemma L2_set_eq_0_iff: \"finite A \\<Longrightarrow> L2_set f A = 0 \\<longleftrightarrow> (\\<forall>x\\<in>A. f x = 0)\"\n  unfolding L2_set_def\n  by (simp add: sum_nonneg sum_nonneg_eq_0_iff)\n\nproposition L2_set_triangle_ineq:\n  \"L2_set (\\<lambda>i. f i + g i) A \\<le> L2_set f A + L2_set g A\"\nproof (cases \"finite A\")\n  case False\n  thus ?thesis by simp\nnext\n  case True\n  thus ?thesis\n  proof (induct set: finite)\n    case empty\n    show ?case by simp\n  next\n    case (insert x F)\n    hence \"sqrt ((f x + g x)\\<^sup>2 + (L2_set (\\<lambda>i. f i + g i) F)\\<^sup>2) \\<le>\n           sqrt ((f x + g x)\\<^sup>2 + (L2_set f F + L2_set g F)\\<^sup>2)\"\n      by (intro real_sqrt_le_mono add_left_mono power_mono insert\n                L2_set_nonneg add_increasing zero_le_power2)\n    also have\n      \"\\<dots> \\<le> sqrt ((f x)\\<^sup>2 + (L2_set f F)\\<^sup>2) + sqrt ((g x)\\<^sup>2 + (L2_set g F)\\<^sup>2)\"\n      by (rule real_sqrt_sum_squares_triangle_ineq)\n    finally show ?case\n      using insert by simp\n  qed\nqed\n\nlemma L2_set_le_sum [rule_format]:\n  \"(\\<forall>i\\<in>A. 0 \\<le> f i) \\<longrightarrow> L2_set f A \\<le> sum f A\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply simp\n  apply clarsimp\n  apply (erule order_trans [OF sqrt_sum_squares_le_sum])\n  apply simp\n  apply simp\n  apply simp\n  done\n\nlemma L2_set_le_sum_abs: \"L2_set f A \\<le> (\\<Sum>i\\<in>A. \\<bar>f i\\<bar>)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply simp\n  apply simp\n  apply (rule order_trans [OF sqrt_sum_squares_le_sum_abs])\n  apply simp\n  apply simp\n  done\n\nlemma L2_set_mult_ineq: \"(\\<Sum>i\\<in>A. \\<bar>f i\\<bar> * \\<bar>g i\\<bar>) \\<le> L2_set f A * L2_set g A\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply simp\n  apply (rule power2_le_imp_le, simp)\n  apply (rule order_trans)\n  apply (rule power_mono)\n  apply (erule add_left_mono)\n  apply (simp add: sum_nonneg)\n  apply (simp add: power2_sum)\n  apply (simp add: power_mult_distrib)\n  apply (simp add: distrib_left distrib_right)\n  apply (rule ord_le_eq_trans)\n  apply (rule L2_set_mult_ineq_lemma)\n  apply simp_all\n  done\n\nlemma member_le_L2_set: \"\\<lbrakk>finite A; i \\<in> A\\<rbrakk> \\<Longrightarrow> f i \\<le> L2_set f A\"\n  unfolding L2_set_def\n  by (auto intro!: member_le_sum real_le_rsqrt)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/L2_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.8887587993853654, "lm_q1q2_score": 0.7721774425233062}}
{"text": "theory Tree0\nimports Main\nbegin\n\ndatatype tree0 = Leaf | Node tree0 tree0\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Leaf = 1\" |\n\"nodes (Node t1 t2) = 1 + nodes t1 + nodes t2\"\n\nlemma \"nodes (Node t t) = 2 * (nodes t) + 1\"\napply(auto)\ndone\n\nlemma \"nodes (explode (Suc n) t) = 2 * nodes (explode n t) + 1\"\napply(induction n arbitrary: t)\napply(auto)\ndone\n\nlemma \"nodes (explode n (Node t t)) = 2 * nodes (explode n t) + 1\"\napply(induction n arbitrary: t)\napply(auto)\ndone\n\nlemma \"n \\<ge> 2 \\<Longrightarrow> (n::nat) - 2 + 1 = n - 1\"\napply(auto)\ndone\n\nlemma \"nodes (explode n t) = ((nodes t) + 1) * 2 ^ n - 1\"\napply(induction n arbitrary: t)\napply(auto simp add:algebra_simps)\ndone\n\nend\n", "meta": {"author": "masateruk", "repo": "isabelle_concrete_semantics", "sha": "fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab", "save_path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics", "path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics/isabelle_concrete_semantics-fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab/chapter2/Tree0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7719313446215803}}
{"text": "(* Author: Alexander Bentkamp, Universität des Saarlandes\n*)\nsection \\<open>Tensor Scalar Multiplication\\<close>\n\ntheory Tensor_Scalar_Mult\nimports Tensor_Plus Tensor_Subtensor\nbegin\n\ndefinition vec_smult::\"'a::ring \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"vec_smult \\<alpha> \\<beta> = map ((*) \\<alpha>) \\<beta>\"\n\nlemma vec_smult0: \"vec_smult 0 as = vec0 (length as)\"\n  by (induction as; auto simp add:vec0_def vec_smult_def)\n\nlemma vec_smult_distr_right:\nshows \"vec_smult (\\<alpha> + \\<beta>) as = vec_plus (vec_smult \\<alpha> as) (vec_smult \\<beta> as)\"\n  unfolding vec_smult_def vec_plus_def\n  by (induction as; simp add: distrib_right)\n\nlemma vec_smult_Cons:\nshows \"vec_smult \\<alpha> (a # as) = (\\<alpha> * a) # vec_smult \\<alpha> as\" by (simp add: vec_smult_def)\n\nlemma vec_plus_Cons:\nshows \"vec_plus (a # as) (b # bs) = (a+b) # vec_plus as bs\" by (simp add: vec_plus_def)\n\nlemma vec_smult_distr_left:\nassumes \"length as = length bs\"\nshows \"vec_smult \\<alpha> (vec_plus as bs) = vec_plus (vec_smult \\<alpha> as) (vec_smult \\<alpha> bs)\"\nusing assms proof (induction as arbitrary:bs)\n  case Nil\n  then show ?case unfolding vec_smult_def vec_plus_def by simp\nnext\n  case (Cons a as')\n  then obtain b bs' where \"bs = b # bs'\" by (metis Suc_length_conv)\n  then have 0:\"vec_smult \\<alpha> (vec_plus (a # as') bs) = (\\<alpha>*(a+b)) # vec_smult \\<alpha> (vec_plus as' bs')\"\n    unfolding vec_smult_def vec_plus_def using Cons.IH[of bs'] by simp\n  have \"length bs' = length as'\" using Cons.prems \\<open>bs = b # bs'\\<close> by auto\n  then show ?case unfolding 0 unfolding  \\<open>bs = b # bs'\\<close> vec_smult_Cons vec_plus_Cons\n    by (simp add: Cons.IH distrib_left)\nqed\n\nlemma length_vec_smult: \"length (vec_smult \\<alpha> v) = length v\" unfolding vec_smult_def by simp\n\ndefinition smult::\"'a::ring \\<Rightarrow> 'a tensor \\<Rightarrow> 'a tensor\" (infixl \"\\<cdot>\" 70) where\n\"smult \\<alpha> A = (tensor_from_vec (dims A) (vec_smult \\<alpha> (vec A)))\"\n\n\nlemma tensor_smult0: fixes A::\"'a::ring tensor\"\nshows \"0 \\<cdot> A = tensor0 (dims A)\"\n  unfolding smult_def tensor0_def vec_smult_def using vec_smult0 length_vec\n  by (metis (no_types) vec_smult_def)\n\nlemma dims_smult[simp]:\"dims (\\<alpha> \\<cdot> A) = dims A\"\nand   vec_smult[simp]: \"vec  (\\<alpha> \\<cdot> A) = map ((*) \\<alpha>) (vec A)\"\n  unfolding smult_def vec_smult_def by (simp add: length_vec)+\n\nlemma tensor_smult_distr_right: \"(\\<alpha> + \\<beta>) \\<cdot> A = \\<alpha> \\<cdot> A  + \\<beta> \\<cdot> A\"\n  unfolding plus_def plus_base_def\n  by (auto; metis smult_def vec_smult_def vec_smult_distr_right)\n\nlemma tensor_smult_distr_left: \"dims A = dims B \\<Longrightarrow> \\<alpha> \\<cdot> (A + B) = \\<alpha> \\<cdot> A  + \\<alpha> \\<cdot> B\"\nproof -\n  assume a1: \"dims A = dims B\"\n  then have f2: \"length (vec_plus (vec A) (vec B)) = length (vec A)\"\n    by (simp add: length_vec vec_plus_def)\n  have f3: \"dims (tensor_from_vec (dims B) (vec_smult \\<alpha> (vec A))) = dims B\"\n    using a1 by (simp add: length_vec vec_smult_def)\n  have f4: \"vec (\\<alpha> \\<cdot> A) = vec_smult \\<alpha> (vec A)\"\n    by (simp add: vec_smult_def)\n  have \"length (vec_smult \\<alpha> (vec B)) = length (vec B)\"\n    by (simp add: vec_smult_def)\n  then show ?thesis\n    unfolding plus_def plus_base_def using f4 f3 f2 a1\n    by (simp add: length_vec smult_def vec_smult_distr_left)\nqed\n\nlemma smult_fixed_length_sublist:\nassumes \"length xs = l * c\" \"i<c\"\nshows \"fixed_length_sublist (vec_smult \\<alpha> xs) l i = vec_smult \\<alpha> (fixed_length_sublist xs l i)\"\nunfolding fixed_length_sublist_def vec_smult_def by (simp add: drop_map take_map)\n\nlemma smult_subtensor:\nassumes \"dims A \\<noteq> []\" \"i < hd (dims A)\"\nshows \"\\<alpha> \\<cdot> subtensor A i = subtensor (\\<alpha> \\<cdot> A) i\"\nproof (rule tensor_eqI)\n  show \"dims (\\<alpha> \\<cdot> subtensor A i) = dims (subtensor (\\<alpha> \\<cdot> A) i)\"\n    using dims_smult dims_subtensor assms(1) assms(2) by simp\n  show \"vec (\\<alpha> \\<cdot> subtensor A i) = vec (subtensor (\\<alpha> \\<cdot> A) i)\"\n    unfolding vec_smult\n    unfolding vec_subtensor[OF \\<open>dims A \\<noteq> []\\<close> \\<open>i < hd (dims A)\\<close>]\n    using vec_subtensor[of \"\\<alpha> \\<cdot> A\" i]\n    by (simp add: assms(1) assms(2) drop_map fixed_length_sublist_def take_map)\nqed\n\nlemma lookup_smult:\nassumes \"is \\<lhd> dims A\"\nshows \"lookup (\\<alpha> \\<cdot> A) is = \\<alpha> * lookup A is\"\nusing assms proof (induction A arbitrary:\"is\" rule:subtensor_induct)\n  case (order_0 A \"is\")\n  then have \"length (vec A) = 1\" by (simp add: length_vec)\n  then have \"hd (vec_smult \\<alpha> (vec A)) = \\<alpha> * hd (vec A)\" unfolding vec_smult_def by (metis list.map_sel(1) list.size(3) zero_neq_one)\n  moreover have \"is = []\" using order_0 by auto\n  ultimately show ?case unfolding smult_def by (auto simp add: \\<open>length (Tensor.vec A) = 1\\<close> lookup_def length_vec_smult order_0.hyps)\nnext\n  case (order_step A \"is\")\n  then obtain i is' where \"is = i # is'\" by blast\n  then have \"lookup (\\<alpha> \\<cdot> subtensor A i) is' = \\<alpha> * lookup (subtensor A i) is'\"\n    by (metis (no_types, lifting) dims_subtensor list.sel(1) list.sel(3) order_step.IH order_step.hyps order_step.prems valid_index_dimsE)\n  then show ?case using smult_subtensor \\<open>is = i # is'\\<close> dims_smult lookup_subtensor1\n    list.sel(1) order_step.hyps order_step.prems valid_index_dimsE\n    by metis\nqed\n\nlemma tensor_smult_assoc:\nfixes A::\"'a::ring tensor\"\nshows \"\\<alpha> \\<cdot> (\\<beta> \\<cdot> A) = (\\<alpha> * \\<beta>) \\<cdot> A\"\nby (rule tensor_lookup_eqI, simp, metis lookup_smult dims_smult mult.assoc)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Deep_Learning/Tensor_Scalar_Mult.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037241905732, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7719116722628017}}
{"text": "section \\<open>Contour integration\\<close>\ntheory Contour_Integration\n  imports \"HOL-Analysis.Analysis\"\nbegin\n\nlemma lhopital_complex_simple:\n  assumes \"(f has_field_derivative f') (at z)\"\n  assumes \"(g has_field_derivative g') (at z)\"\n  assumes \"f z = 0\" \"g z = 0\" \"g' \\<noteq> 0\" \"f' / g' = c\"\n  shows   \"((\\<lambda>w. f w / g w) \\<longlongrightarrow> c) (at z)\"\nproof -\n  have \"eventually (\\<lambda>w. w \\<noteq> z) (at z)\"\n    by (auto simp: eventually_at_filter)\n  hence \"eventually (\\<lambda>w. ((f w - f z) / (w - z)) / ((g w - g z) / (w - z)) = f w / g w) (at z)\"\n    by eventually_elim (simp add: assms field_split_simps)\n  moreover have \"((\\<lambda>w. ((f w - f z) / (w - z)) / ((g w - g z) / (w - z))) \\<longlongrightarrow> f' / g') (at z)\"\n    by (intro tendsto_divide has_field_derivativeD assms)\n  ultimately have \"((\\<lambda>w. f w / g w) \\<longlongrightarrow> f' / g') (at z)\"\n    by (blast intro: Lim_transform_eventually)\n  with assms show ?thesis by simp\nqed\n\nsubsection\\<open>Definition\\<close>\n\ntext\\<open>\n  This definition is for complex numbers only, and does not generalise to \n  line integrals in a vector field\n\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> has_contour_integral :: \"(complex \\<Rightarrow> complex) \\<Rightarrow> complex \\<Rightarrow> (real \\<Rightarrow> complex) \\<Rightarrow> bool\"\n           (infixr \"has'_contour'_integral\" 50)\n  where \"(f has_contour_integral i) g \\<equiv>\n           ((\\<lambda>x. f(g x) * vector_derivative g (at x within {0..1}))\n            has_integral i) {0..1}\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> contour_integrable_on\n           (infixr \"contour'_integrable'_on\" 50)\n  where \"f contour_integrable_on g \\<equiv> \\<exists>i. (f has_contour_integral i) g\"\n\ndefinition\\<^marker>\\<open>tag important\\<close> contour_integral\n  where \"contour_integral g f \\<equiv> SOME i. (f has_contour_integral i) g \\<or> \\<not> f contour_integrable_on g \\<and> i=0\"\n\nlemma not_integrable_contour_integral: \"\\<not> f contour_integrable_on g \\<Longrightarrow> contour_integral g f = 0\"\n  unfolding contour_integrable_on_def contour_integral_def by blast\n\nlemma contour_integral_unique: \"(f has_contour_integral i) g \\<Longrightarrow> contour_integral g f = i\"\n  apply (simp add: contour_integral_def has_contour_integral_def contour_integrable_on_def)\n  using has_integral_unique by blast\n\nlemma has_contour_integral_eqpath:\n     \"\\<lbrakk>(f has_contour_integral y) p; f contour_integrable_on \\<gamma>;\n       contour_integral p f = contour_integral \\<gamma> f\\<rbrakk>\n      \\<Longrightarrow> (f has_contour_integral y) \\<gamma>\"\nusing contour_integrable_on_def contour_integral_unique by auto\n\nlemma has_contour_integral_integral:\n    \"f contour_integrable_on i \\<Longrightarrow> (f has_contour_integral (contour_integral i f)) i\"\n  by (metis contour_integral_unique contour_integrable_on_def)\n\nlemma has_contour_integral_unique:\n    \"(f has_contour_integral i) g \\<Longrightarrow> (f has_contour_integral j) g \\<Longrightarrow> i = j\"\n  using has_integral_unique\n  by (auto simp: has_contour_integral_def)\n\nlemma has_contour_integral_integrable: \"(f has_contour_integral i) g \\<Longrightarrow> f contour_integrable_on g\"\n  using contour_integrable_on_def by blast\n\ntext\\<open>Show that we can forget about the localized derivative.\\<close>\n\nlemma has_integral_localized_vector_derivative:\n    \"((\\<lambda>x. f (g x) * vector_derivative p (at x within {a..b})) has_integral i) {a..b} \\<longleftrightarrow>\n     ((\\<lambda>x. f (g x) * vector_derivative p (at x)) has_integral i) {a..b}\"\nproof -\n  have *: \"{a..b} - {a,b} = interior {a..b}\"\n    by (simp add: atLeastAtMost_diff_ends)\n  show ?thesis\n    by (rule has_integral_spike_eq [of \"{a,b}\"]) (auto simp: at_within_interior [of _ \"{a..b}\"])\nqed\n\nlemma integrable_on_localized_vector_derivative:\n    \"(\\<lambda>x. f (g x) * vector_derivative p (at x within {a..b})) integrable_on {a..b} \\<longleftrightarrow>\n     (\\<lambda>x. f (g x) * vector_derivative p (at x)) integrable_on {a..b}\"\n  by (simp add: integrable_on_def has_integral_localized_vector_derivative)\n\nlemma has_contour_integral:\n     \"(f has_contour_integral i) g \\<longleftrightarrow>\n      ((\\<lambda>x. f (g x) * vector_derivative g (at x)) has_integral i) {0..1}\"\n  by (simp add: has_integral_localized_vector_derivative has_contour_integral_def)\n\nlemma contour_integrable_on:\n     \"f contour_integrable_on g \\<longleftrightarrow>\n      (\\<lambda>t. f(g t) * vector_derivative g (at t)) integrable_on {0..1}\"\n  by (simp add: has_contour_integral integrable_on_def contour_integrable_on_def)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Reversing a path\\<close>\n\n\n\nlemma has_contour_integral_reversepath:\n  assumes \"valid_path g\" and f: \"(f has_contour_integral i) g\"\n    shows \"(f has_contour_integral (-i)) (reversepath g)\"\nproof -\n  { fix S x\n    assume xs: \"g C1_differentiable_on ({0..1} - S)\" \"x \\<notin> (-) 1 ` S\" \"0 \\<le> x\" \"x \\<le> 1\"\n    have \"vector_derivative (\\<lambda>x. g (1 - x)) (at x within {0..1}) =\n            - vector_derivative g (at (1 - x) within {0..1})\"\n    proof -\n      obtain f' where f': \"(g has_vector_derivative f') (at (1 - x))\"\n        using xs\n        by (force simp: has_vector_derivative_def C1_differentiable_on_def)\n      have \"(g \\<circ> (\\<lambda>x. 1 - x) has_vector_derivative -1 *\\<^sub>R f') (at x)\"\n        by (intro vector_diff_chain_within has_vector_derivative_at_within [OF f'] derivative_eq_intros | simp)+\n      then have mf': \"((\\<lambda>x. g (1 - x)) has_vector_derivative -f') (at x)\"\n        by (simp add: o_def)\n      show ?thesis\n        using xs\n        by (auto simp: vector_derivative_at_within_ivl [OF mf'] vector_derivative_at_within_ivl [OF f'])\n    qed\n  } note * = this\n  obtain S where S: \"continuous_on {0..1} g\" \"finite S\" \"g C1_differentiable_on {0..1} - S\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def)\n  have \"((\\<lambda>x. - (f (g (1 - x)) * vector_derivative g (at (1 - x) within {0..1}))) has_integral -i)\n       {0..1}\"\n    using has_integral_affinity01 [where m= \"-1\" and c=1, OF f [unfolded has_contour_integral_def]]\n    by (simp add: has_integral_neg)\n  then show ?thesis\n    using S\n    unfolding reversepath_def has_contour_integral_def\n    by (rule_tac S = \"(\\<lambda>x. 1 - x) ` S\" in has_integral_spike_finite) (auto simp: *)\nqed\n\nlemma contour_integrable_reversepath:\n    \"valid_path g \\<Longrightarrow> f contour_integrable_on g \\<Longrightarrow> f contour_integrable_on (reversepath g)\"\n  using has_contour_integral_reversepath contour_integrable_on_def by blast\n\nlemma contour_integrable_reversepath_eq:\n    \"valid_path g \\<Longrightarrow> (f contour_integrable_on (reversepath g) \\<longleftrightarrow> f contour_integrable_on g)\"\n  using contour_integrable_reversepath valid_path_reversepath by fastforce\n\nlemma contour_integral_reversepath:\n  assumes \"valid_path g\"\n    shows \"contour_integral (reversepath g) f = - (contour_integral g f)\"\nproof (cases \"f contour_integrable_on g\")\n  case True then show ?thesis\n    by (simp add: assms contour_integral_unique has_contour_integral_integral has_contour_integral_reversepath)\nnext\n  case False then have \"\\<not> f contour_integrable_on (reversepath g)\"\n    by (simp add: assms contour_integrable_reversepath_eq)\n  with False show ?thesis by (simp add: not_integrable_contour_integral)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Joining two paths together\\<close>\n\nlemma has_contour_integral_join:\n  assumes \"(f has_contour_integral i1) g1\" \"(f has_contour_integral i2) g2\"\n          \"valid_path g1\" \"valid_path g2\"\n    shows \"(f has_contour_integral (i1 + i2)) (g1 +++ g2)\"\nproof -\n  obtain s1 s2\n    where s1: \"finite s1\" \"\\<forall>x\\<in>{0..1} - s1. g1 differentiable at x\"\n      and s2: \"finite s2\" \"\\<forall>x\\<in>{0..1} - s2. g2 differentiable at x\"\n    using assms\n    by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have 1: \"((\\<lambda>x. f (g1 x) * vector_derivative g1 (at x)) has_integral i1) {0..1}\"\n   and 2: \"((\\<lambda>x. f (g2 x) * vector_derivative g2 (at x)) has_integral i2) {0..1}\"\n    using assms\n    by (auto simp: has_contour_integral)\n  have i1: \"((\\<lambda>x. (2*f (g1 (2*x))) * vector_derivative g1 (at (2*x))) has_integral i1) {0..1/2}\"\n   and i2: \"((\\<lambda>x. (2*f (g2 (2*x - 1))) * vector_derivative g2 (at (2*x - 1))) has_integral i2) {1/2..1}\"\n    using has_integral_affinity01 [OF 1, where m= 2 and c=0, THEN has_integral_cmul [where c=2]]\n          has_integral_affinity01 [OF 2, where m= 2 and c=\"-1\", THEN has_integral_cmul [where c=2]]\n    by (simp_all only: image_affinity_atLeastAtMost_div_diff, simp_all add: scaleR_conv_of_real mult_ac)\n  have g1: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at z) =\n            2 *\\<^sub>R vector_derivative g1 (at (z*2))\" \n      if \"0 \\<le> z\" \"z*2 < 1\" \"z*2 \\<notin> s1\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>z - 1/2\\<bar>\"\n      using that by auto\n    have \"((*) 2 has_vector_derivative 2) (at z)\" \n      by (simp add: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    moreover have \"(g1 has_vector_derivative vector_derivative g1 (at (z * 2))) (at (2 * z))\"\n      using s1 that by (auto simp: algebra_simps vector_derivative_works)\n    ultimately\n    show \"((\\<lambda>x. g1 (2 * x)) has_vector_derivative 2 *\\<^sub>R vector_derivative g1 (at (z * 2))) (at z)\"\n      by (intro vector_diff_chain_at [simplified o_def])\n  qed (use that in \\<open>simp_all add: dist_real_def abs_if split: if_split_asm\\<close>)\n\n  have g2: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at z) =\n            2 *\\<^sub>R vector_derivative g2 (at (z*2 - 1))\" \n           if \"1 < z*2\" \"z \\<le> 1\" \"z*2 - 1 \\<notin> s2\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>z - 1/2\\<bar>\"\n      using that by auto\n    have \"((\\<lambda>x. 2 * x - 1) has_vector_derivative 2) (at z)\"\n      by (simp add: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    moreover have \"(g2 has_vector_derivative vector_derivative g2 (at (z * 2 - 1))) (at (2 * z - 1))\"\n      using s2 that by (auto simp: algebra_simps vector_derivative_works)\n    ultimately\n    show \"((\\<lambda>x. g2 (2 * x - 1)) has_vector_derivative 2 *\\<^sub>R vector_derivative g2 (at (z * 2 - 1))) (at z)\"\n      by (intro vector_diff_chain_at [simplified o_def])\n  qed (use that in \\<open>simp_all add: dist_real_def abs_if split: if_split_asm\\<close>)\n\n  have \"((\\<lambda>x. f ((g1 +++ g2) x) * vector_derivative (g1 +++ g2) (at x)) has_integral i1) {0..1/2}\"\n  proof (rule has_integral_spike_finite [OF _ _ i1])\n    show \"finite (insert (1/2) ((*) 2 -` s1))\"\n      using s1 by (force intro: finite_vimageI [where h = \"(*)2\"] inj_onI)\n  qed (auto simp add: joinpaths_def scaleR_conv_of_real mult_ac g1)\n  moreover have \"((\\<lambda>x. f ((g1 +++ g2) x) * vector_derivative (g1 +++ g2) (at x)) has_integral i2) {1/2..1}\"\n  proof (rule has_integral_spike_finite [OF _ _ i2])\n    show \"finite (insert (1/2) ((\\<lambda>x. 2 * x - 1) -` s2))\"\n      using s2 by (force intro: finite_vimageI [where h = \"\\<lambda>x. 2*x-1\"] inj_onI)\n  qed (auto simp add: joinpaths_def scaleR_conv_of_real mult_ac g2)\n  ultimately\n  show ?thesis\n    by (simp add: has_contour_integral has_integral_combine [where c = \"1/2\"])\nqed\n\nlemma contour_integrable_joinI:\n  assumes \"f contour_integrable_on g1\" \"f contour_integrable_on g2\"\n          \"valid_path g1\" \"valid_path g2\"\n    shows \"f contour_integrable_on (g1 +++ g2)\"\n  using assms\n  by (meson has_contour_integral_join contour_integrable_on_def)\n\nlemma contour_integrable_joinD1:\n  assumes \"f contour_integrable_on (g1 +++ g2)\" \"valid_path g1\"\n    shows \"f contour_integrable_on g1\"\nproof -\n  obtain s1\n    where s1: \"finite s1\" \"\\<forall>x\\<in>{0..1} - s1. g1 differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have \"(\\<lambda>x. f ((g1 +++ g2) (x/2)) * vector_derivative (g1 +++ g2) (at (x/2))) integrable_on {0..1}\"\n    using assms integrable_affinity [of _ 0 \"1/2\" \"1/2\" 0] integrable_on_subcbox [where a=0 and b=\"1/2\"]\n    by (fastforce simp: contour_integrable_on)\n  then have *: \"(\\<lambda>x. (f ((g1 +++ g2) (x/2))/2) * vector_derivative (g1 +++ g2) (at (x/2))) integrable_on {0..1}\"\n    by (auto dest: integrable_cmul [where c=\"1/2\"] simp: scaleR_conv_of_real)\n  have g1: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at (z/2)) =\n            2 *\\<^sub>R vector_derivative g1 (at z)\" \n    if \"0 < z\" \"z < 1\" \"z \\<notin> s1\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>(z - 1)/2\\<bar>\"\n      using that by auto\n    have \\<section>: \"((\\<lambda>x. x * 2) has_vector_derivative 2) (at (z/2))\"\n      using s1 by (auto simp: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    have \"(g1 has_vector_derivative vector_derivative g1 (at z)) (at z)\"\n      using s1 that by (auto simp: vector_derivative_works)\n    then show \"((\\<lambda>x. g1 (2 * x)) has_vector_derivative 2 *\\<^sub>R vector_derivative g1 (at z)) (at (z/2))\"\n      using vector_diff_chain_at [OF \\<section>] by (auto simp: field_simps o_def)\n  qed (use that in \\<open>simp_all add: field_simps dist_real_def abs_if split: if_split_asm\\<close>)\n  have fin01: \"finite ({0, 1} \\<union> s1)\"\n    by (simp add: s1)\n  show ?thesis\n    unfolding contour_integrable_on\n    by (intro integrable_spike_finite [OF fin01 _ *]) (auto simp: joinpaths_def scaleR_conv_of_real g1)\nqed\n\nlemma contour_integrable_joinD2:\n  assumes \"f contour_integrable_on (g1 +++ g2)\" \"valid_path g2\"\n    shows \"f contour_integrable_on g2\"\nproof -\n  obtain s2\n    where s2: \"finite s2\" \"\\<forall>x\\<in>{0..1} - s2. g2 differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have \"(\\<lambda>x. f ((g1 +++ g2) (x/2 + 1/2)) * vector_derivative (g1 +++ g2) (at (x/2 + 1/2))) integrable_on {0..1}\"\n    using assms integrable_affinity [of _ \"1/2::real\" 1 \"1/2\" \"1/2\"] \n                integrable_on_subcbox [where a=\"1/2\" and b=1]\n    by (fastforce simp: contour_integrable_on image_affinity_atLeastAtMost_diff)\n  then have *: \"(\\<lambda>x. (f ((g1 +++ g2) (x/2 + 1/2))/2) * vector_derivative (g1 +++ g2) (at (x/2 + 1/2)))\n                integrable_on {0..1}\"\n    by (auto dest: integrable_cmul [where c=\"1/2\"] simp: scaleR_conv_of_real)\n  have g2: \"vector_derivative (\\<lambda>x. if x*2 \\<le> 1 then g1 (2*x) else g2 (2*x - 1)) (at (z/2+1/2)) =\n            2 *\\<^sub>R vector_derivative g2 (at z)\" \n        if \"0 < z\" \"z < 1\" \"z \\<notin> s2\" for z\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    show \"0 < \\<bar>z/2\\<bar>\"\n      using that by auto\n    have \\<section>: \"((\\<lambda>x. x * 2 - 1) has_vector_derivative 2) (at ((1 + z)/2))\"\n      using s2 by (auto simp: has_vector_derivative_def has_derivative_def bounded_linear_mult_left)\n    have \"(g2 has_vector_derivative vector_derivative g2 (at z)) (at z)\"\n      using s2 that by (auto simp: vector_derivative_works)\n    then show \"((\\<lambda>x. g2 (2*x - 1)) has_vector_derivative 2 *\\<^sub>R vector_derivative g2 (at z)) (at (z/2 + 1/2))\"\n      using vector_diff_chain_at [OF \\<section>] by (auto simp: field_simps o_def)\n  qed (use that in \\<open>simp_all add: field_simps dist_real_def abs_if split: if_split_asm\\<close>)\n  have fin01: \"finite ({0, 1} \\<union> s2)\"\n    by (simp add: s2)\n  show ?thesis\n    unfolding contour_integrable_on\n    by (intro integrable_spike_finite [OF fin01 _ *]) (auto simp: joinpaths_def scaleR_conv_of_real g2)\nqed\n\nlemma contour_integrable_join [simp]:\n    \"\\<lbrakk>valid_path g1; valid_path g2\\<rbrakk>\n     \\<Longrightarrow> f contour_integrable_on (g1 +++ g2) \\<longleftrightarrow> f contour_integrable_on g1 \\<and> f contour_integrable_on g2\"\nusing contour_integrable_joinD1 contour_integrable_joinD2 contour_integrable_joinI by blast\n\nlemma contour_integral_join [simp]:\n    \"\\<lbrakk>f contour_integrable_on g1; f contour_integrable_on g2; valid_path g1; valid_path g2\\<rbrakk>\n        \\<Longrightarrow> contour_integral (g1 +++ g2) f = contour_integral g1 f + contour_integral g2 f\"\n  by (simp add: has_contour_integral_integral has_contour_integral_join contour_integral_unique)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Shifting the starting point of a (closed) path\\<close>\n\nlemma has_contour_integral_shiftpath:\n  assumes f: \"(f has_contour_integral i) g\" \"valid_path g\"\n      and a: \"a \\<in> {0..1}\"\n    shows \"(f has_contour_integral i) (shiftpath a g)\"\nproof -\n  obtain S\n    where S: \"finite S\" and g: \"\\<forall>x\\<in>{0..1} - S. g differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  have *: \"((\\<lambda>x. f (g x) * vector_derivative g (at x)) has_integral i) {0..1}\"\n    using assms by (auto simp: has_contour_integral)\n  then have i: \"i = integral {a..1} (\\<lambda>x. f (g x) * vector_derivative g (at x)) +\n                    integral {0..a} (\\<lambda>x. f (g x) * vector_derivative g (at x))\"\n    apply (rule has_integral_unique)\n    apply (subst add.commute)\n    apply (subst Henstock_Kurzweil_Integration.integral_combine)\n    using assms * integral_unique by auto\n\n  have vd1: \"vector_derivative (shiftpath a g) (at x) = vector_derivative g (at (x + a))\"\n    if \"0 \\<le> x\" \"x + a < 1\" \"x \\<notin> (\\<lambda>x. x - a) ` S\" for x\n    unfolding shiftpath_def\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    have \"((\\<lambda>x. g (x + a)) has_vector_derivative vector_derivative g (at (a + x))) (at x)\"\n    proof (rule vector_diff_chain_at [of _ 1, simplified o_def scaleR_one])\n      show \"((\\<lambda>x. x + a) has_vector_derivative 1) (at x)\"\n        by (rule derivative_eq_intros | simp)+\n      have \"g differentiable at (x + a)\"\n        using g a that by force\n      then show \"(g has_vector_derivative vector_derivative g (at (a + x))) (at (x + a))\"\n        by (metis add.commute vector_derivative_works)\n    qed\n    then\n    show \"((\\<lambda>x. g (a + x)) has_vector_derivative vector_derivative g (at (x + a))) (at x)\"\n      by (auto simp: field_simps)\n    show \"0 < dist (1 - a) x\"\n      using that by auto\n  qed (use that in \\<open>auto simp: dist_real_def\\<close>)\n\n  have vd2: \"vector_derivative (shiftpath a g) (at x) = vector_derivative g (at (x + a - 1))\"\n    if \"x \\<le> 1\" \"1 < x + a\" \"x \\<notin> (\\<lambda>x. x - a + 1) ` S\" for x\n    unfolding shiftpath_def\n  proof (rule vector_derivative_at [OF has_vector_derivative_transform_within])\n    have \"((\\<lambda>x. g (x + a - 1)) has_vector_derivative vector_derivative g (at (a+x-1))) (at x)\"\n    proof (rule vector_diff_chain_at [of _ 1, simplified o_def scaleR_one])\n      show \"((\\<lambda>x. x + a - 1) has_vector_derivative 1) (at x)\"\n        by (rule derivative_eq_intros | simp)+\n      have \"g differentiable at (x+a-1)\"\n        using g a that by force\n      then show \"(g has_vector_derivative vector_derivative g (at (a+x-1))) (at (x + a - 1))\"\n        by (metis add.commute vector_derivative_works)\n    qed\n    then show \"((\\<lambda>x. g (a + x - 1)) has_vector_derivative vector_derivative g (at (x + a - 1))) (at x)\"\n      by (auto simp: field_simps)\n    show \"0 < dist (1 - a) x\"\n      using that by auto\n  qed (use that in \\<open>auto simp: dist_real_def\\<close>)\n\n  have va1: \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on ({a..1})\"\n    using * a   by (fastforce intro: integrable_subinterval_real)\n  have v0a: \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on ({0..a})\"\n    using * a by (force intro: integrable_subinterval_real)\n  have \"finite ({1 - a} \\<union> (\\<lambda>x. x - a) ` S)\"\n    using S by blast\n  then have \"((\\<lambda>x. f (shiftpath a g x) * vector_derivative (shiftpath a g) (at x))\n        has_integral integral {a..1} (\\<lambda>x. f (g x) * vector_derivative g (at x)))  {0..1 - a}\"\n    apply (rule has_integral_spike_finite\n        [where f = \"\\<lambda>x. f(g(a+x)) * vector_derivative g (at(a+x))\"])\n    subgoal\n      using a by (simp add: vd1) (force simp: shiftpath_def add.commute)\n    subgoal\n      using has_integral_affinity [where m=1 and c=a] integrable_integral [OF va1]\n      by (force simp add: add.commute)\n    done\n  moreover\n  have \"finite ({1 - a} \\<union> (\\<lambda>x. x - a + 1) ` S)\"\n    using S by blast\n  then have \"((\\<lambda>x. f (shiftpath a g x) * vector_derivative (shiftpath a g) (at x))\n             has_integral  integral {0..a} (\\<lambda>x. f (g x) * vector_derivative g (at x)))  {1 - a..1}\"\n    apply (rule has_integral_spike_finite\n        [where f = \"\\<lambda>x. f(g(a+x-1)) * vector_derivative g (at(a+x-1))\"])\n    subgoal\n      using a by (simp add: vd2) (force simp: shiftpath_def add.commute)\n    subgoal\n      using has_integral_affinity [where m=1 and c=\"a-1\", simplified, OF integrable_integral [OF v0a]]\n      by (force simp add: algebra_simps)\n    done\n  ultimately show ?thesis\n    using a\n    by (auto simp: i has_contour_integral intro: has_integral_combine [where c = \"1-a\"])\nqed\n\nlemma has_contour_integral_shiftpath_D:\n  assumes \"(f has_contour_integral i) (shiftpath a g)\"\n          \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"(f has_contour_integral i) g\"\nproof -\n  obtain S\n    where S: \"finite S\" and g: \"\\<forall>x\\<in>{0..1} - S. g differentiable at x\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def C1_differentiable_on_eq)\n  { fix x\n    assume x: \"0 < x\" \"x < 1\" \"x \\<notin> S\"\n    then have gx: \"g differentiable at x\"\n      using g by auto\n    have \\<section>: \"shiftpath (1 - a) (shiftpath a g) differentiable at x\"\n      using assms x\n      by (intro differentiable_transform_within [OF gx, of \"min x (1-x)\"])\n         (auto simp: dist_real_def shiftpath_shiftpath abs_if split: if_split_asm)\n    have \"vector_derivative g (at x within {0..1}) =\n          vector_derivative (shiftpath (1 - a) (shiftpath a g)) (at x within {0..1})\"\n      apply (rule vector_derivative_at_within_ivl\n                  [OF has_vector_derivative_transform_within_open\n                      [where f = \"(shiftpath (1 - a) (shiftpath a g))\" and S = \"{0<..<1}-S\"]])\n      using S assms x \\<section>\n      apply (auto simp: finite_imp_closed open_Diff shiftpath_shiftpath\n                        at_within_interior [of _ \"{0..1}\"] vector_derivative_works [symmetric])\n      done\n  } note vd = this\n  have fi: \"(f has_contour_integral i) (shiftpath (1 - a) (shiftpath a g))\"\n    using assms  by (auto intro!: has_contour_integral_shiftpath)\n  show ?thesis\n    unfolding has_contour_integral_def\n  proof (rule has_integral_spike_finite [of \"{0,1} \\<union> S\", OF _ _  fi [unfolded has_contour_integral_def]])\n    show \"finite ({0, 1} \\<union> S)\"\n      by (simp add: S)\n  qed (use S assms vd in \\<open>auto simp: shiftpath_shiftpath\\<close>)\nqed\n\nlemma has_contour_integral_shiftpath_eq:\n  assumes \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"(f has_contour_integral i) (shiftpath a g) \\<longleftrightarrow> (f has_contour_integral i) g\"\n  using assms has_contour_integral_shiftpath has_contour_integral_shiftpath_D by blast\n\nlemma contour_integrable_on_shiftpath_eq:\n  assumes \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"f contour_integrable_on (shiftpath a g) \\<longleftrightarrow> f contour_integrable_on g\"\nusing assms contour_integrable_on_def has_contour_integral_shiftpath_eq by auto\n\nlemma contour_integral_shiftpath:\n  assumes \"valid_path g\" \"pathfinish g = pathstart g\" \"a \\<in> {0..1}\"\n    shows \"contour_integral (shiftpath a g) f = contour_integral g f\"\n   using assms\n   by (simp add: contour_integral_def contour_integrable_on_def has_contour_integral_shiftpath_eq)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>More about straight-line paths\\<close>\n\nlemma has_contour_integral_linepath:\n  shows \"(f has_contour_integral i) (linepath a b) \\<longleftrightarrow>\n         ((\\<lambda>x. f(linepath a b x) * (b - a)) has_integral i) {0..1}\"\n  by (simp add: has_contour_integral)\n\nlemma has_contour_integral_trivial [iff]: \"(f has_contour_integral 0) (linepath a a)\"\n  by (simp add: has_contour_integral_linepath)\n\nlemma has_contour_integral_trivial_iff [simp]: \"(f has_contour_integral i) (linepath a a) \\<longleftrightarrow> i=0\"\n  using has_contour_integral_unique by blast\n\nlemma contour_integral_trivial [simp]: \"contour_integral (linepath a a) f = 0\"\n  using has_contour_integral_trivial contour_integral_unique by blast\n\n\nsubsection\\<open>Relation to subpath construction\\<close>\n\nlemma has_contour_integral_subpath_refl [iff]: \"(f has_contour_integral 0) (subpath u u g)\"\n  by (simp add: has_contour_integral subpath_def)\n\nlemma contour_integrable_subpath_refl [iff]: \"f contour_integrable_on (subpath u u g)\"\n  using has_contour_integral_subpath_refl contour_integrable_on_def by blast\n\nlemma contour_integral_subpath_refl [simp]: \"contour_integral (subpath u u g) f = 0\"\n  by (simp add: contour_integral_unique)\n\nlemma has_contour_integral_subpath:\n  assumes f: \"f contour_integrable_on g\" and g: \"valid_path g\"\n      and uv: \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<le> v\"\n    shows \"(f has_contour_integral  integral {u..v} (\\<lambda>x. f(g x) * vector_derivative g (at x)))\n           (subpath u v g)\"\nproof (cases \"v=u\")\n  case True\n  then show ?thesis\n    using f   by (simp add: contour_integrable_on_def subpath_def has_contour_integral)\nnext\n  case False\n  obtain S where S: \"\\<And>x. x \\<in> {0..1} - S \\<Longrightarrow> g differentiable at x\" and fs: \"finite S\"\n    using g unfolding piecewise_C1_differentiable_on_def C1_differentiable_on_eq valid_path_def by blast\n  have \\<section>: \"(\\<lambda>t. f (g t) * vector_derivative g (at t)) integrable_on {u..v}\"\n    using contour_integrable_on f integrable_on_subinterval uv by fastforce\n  then have *: \"((\\<lambda>x. f (g ((v - u) * x + u)) * vector_derivative g (at ((v - u) * x + u)))\n            has_integral (1 / (v - u)) * integral {u..v} (\\<lambda>t. f (g t) * vector_derivative g (at t)))\n           {0..1}\"\n    using uv False unfolding has_integral_integral\n    apply simp\n    apply (drule has_integral_affinity [where m=\"v-u\" and c=u, simplified])\n    apply (simp_all add: image_affinity_atLeastAtMost_div_diff scaleR_conv_of_real)\n    apply (simp add: divide_simps)\n    done\n\n  have vd: \"vector_derivative (\\<lambda>x. g ((v-u) * x + u)) (at x) = (v-u) *\\<^sub>R vector_derivative g (at ((v-u) * x + u))\"\n    if \"x \\<in> {0..1}\"  \"x \\<notin> (\\<lambda>t. (v-u) *\\<^sub>R t + u) -` S\" for x\n  proof (rule vector_derivative_at [OF vector_diff_chain_at [simplified o_def]])\n    show \"((\\<lambda>x. (v - u) * x + u) has_vector_derivative v - u) (at x)\"\n      by (intro derivative_eq_intros | simp)+\n  qed (use S uv mult_left_le [of x \"v-u\"] that in \\<open>auto simp: vector_derivative_works\\<close>)\n\n  have fin: \"finite ((\\<lambda>t. (v - u) *\\<^sub>R t + u) -` S)\"\n    using fs by (auto simp: inj_on_def False finite_vimageI)\n  show ?thesis\n    unfolding subpath_def has_contour_integral\n    apply (rule has_integral_spike_finite [OF fin])\n    using has_integral_cmul [OF *, where c = \"v-u\"] fs assms\n    by (auto simp: False vd scaleR_conv_of_real)\nqed\n\nlemma contour_integrable_subpath:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\"\n    shows \"f contour_integrable_on (subpath u v g)\"\nproof (cases u v rule: linorder_class.le_cases)\n  case le\n  then show ?thesis\n    by (metis contour_integrable_on_def has_contour_integral_subpath [OF assms])\nnext\n  case ge\n  with assms show ?thesis\n    by (metis (no_types, lifting) contour_integrable_on_def contour_integrable_reversepath_eq has_contour_integral_subpath reversepath_subpath valid_path_subpath)\nqed\n\nlemma has_integral_contour_integral_subpath:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<le> v\"\n    shows \"(((\\<lambda>x. f(g x) * vector_derivative g (at x)))\n            has_integral  contour_integral (subpath u v g) f) {u..v}\"\n  using assms\nproof -\n  have \"(\\<lambda>r. f (g r) * vector_derivative g (at r)) integrable_on {u..v}\"\n    by (metis (full_types) assms(1) assms(3) assms(4) atLeastAtMost_iff atLeastatMost_subset_iff contour_integrable_on integrable_on_subinterval)\n  then have \"((\\<lambda>r. f (g r) * vector_derivative g (at r)) has_integral integral {u..v} (\\<lambda>r. f (g r) * vector_derivative g (at r))) {u..v}\"\n    by blast\n  then show ?thesis\n    by (metis (full_types) assms contour_integral_unique has_contour_integral_subpath)\nqed\n\nlemma contour_integral_subcontour_integral:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"u \\<le> v\"\n    shows \"contour_integral (subpath u v g) f =\n           integral {u..v} (\\<lambda>x. f(g x) * vector_derivative g (at x))\"\n  using assms has_contour_integral_subpath contour_integral_unique by blast\n\nlemma contour_integral_subpath_combine_less:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"w \\<in> {0..1}\"\n          \"u<v\" \"v<w\"\n    shows \"contour_integral (subpath u v g) f + contour_integral (subpath v w g) f =\n           contour_integral (subpath u w g) f\"\nproof -\n  have \"(\\<lambda>x. f (g x) * vector_derivative g (at x)) integrable_on {u..w}\"\n    using integrable_on_subcbox [where a=u and b=w and S = \"{0..1}\"] assms\n    by (auto simp: contour_integrable_on)\n  with assms show ?thesis\n    by (auto simp: contour_integral_subcontour_integral Henstock_Kurzweil_Integration.integral_combine)\nqed\n\nlemma contour_integral_subpath_combine:\n  assumes \"f contour_integrable_on g\" \"valid_path g\" \"u \\<in> {0..1}\" \"v \\<in> {0..1}\" \"w \\<in> {0..1}\"\n    shows \"contour_integral (subpath u v g) f + contour_integral (subpath v w g) f =\n           contour_integral (subpath u w g) f\"\nproof (cases \"u\\<noteq>v \\<and> v\\<noteq>w \\<and> u\\<noteq>w\")\n  case True\n    have *: \"subpath v u g = reversepath(subpath u v g) \\<and>\n             subpath w u g = reversepath(subpath u w g) \\<and>\n             subpath w v g = reversepath(subpath v w g)\"\n      by (auto simp: reversepath_subpath)\n    have \"u < v \\<and> v < w \\<or>\n          u < w \\<and> w < v \\<or>\n          v < u \\<and> u < w \\<or>\n          v < w \\<and> w < u \\<or>\n          w < u \\<and> u < v \\<or>\n          w < v \\<and> v < u\"\n      using True assms by linarith\n    with assms show ?thesis\n      using contour_integral_subpath_combine_less [of f g u v w]\n            contour_integral_subpath_combine_less [of f g u w v]\n            contour_integral_subpath_combine_less [of f g v u w]\n            contour_integral_subpath_combine_less [of f g v w u]\n            contour_integral_subpath_combine_less [of f g w u v]\n            contour_integral_subpath_combine_less [of f g w v u]\n      by (elim disjE) (auto simp: * contour_integral_reversepath contour_integrable_subpath\n                                    valid_path_subpath algebra_simps)\nnext\n  case False\n  with assms show ?thesis\n    by (metis add.right_neutral contour_integral_reversepath contour_integral_subpath_refl diff_0 eq_diff_eq add_0 reversepath_subpath valid_path_subpath)\nqed\n\nlemma contour_integral_integral:\n     \"contour_integral g f = integral {0..1} (\\<lambda>x. f (g x) * vector_derivative g (at x))\"\n  by (simp add: contour_integral_def integral_def has_contour_integral contour_integrable_on)\n\nlemma contour_integral_cong:\n  assumes \"g = g'\" \"\\<And>x. x \\<in> path_image g \\<Longrightarrow> f x = f' x\"\n  shows   \"contour_integral g f = contour_integral g' f'\"\n  unfolding contour_integral_integral using assms\n  by (intro integral_cong) (auto simp: path_image_def)\n\n\ntext \\<open>Contour integral along a segment on the real axis\\<close>\n\nlemma has_contour_integral_linepath_Reals_iff:\n  fixes a b :: complex and f :: \"complex \\<Rightarrow> complex\"\n  assumes \"a \\<in> Reals\" \"b \\<in> Reals\" \"Re a < Re b\"\n  shows   \"(f has_contour_integral I) (linepath a b) \\<longleftrightarrow>\n             ((\\<lambda>x. f (of_real x)) has_integral I) {Re a..Re b}\"\nproof -\n  from assms have [simp]: \"of_real (Re a) = a\" \"of_real (Re b) = b\"\n    by (simp_all add: complex_eq_iff)\n  from assms have \"a \\<noteq> b\" by auto\n  have \"((\\<lambda>x. f (of_real x)) has_integral I) (cbox (Re a) (Re b)) \\<longleftrightarrow>\n          ((\\<lambda>x. f (a + b * of_real x - a * of_real x)) has_integral I /\\<^sub>R (Re b - Re a)) {0..1}\"\n    by (subst has_integral_affinity_iff [of \"Re b - Re a\" _ \"Re a\", symmetric])\n       (insert assms, simp_all add: field_simps scaleR_conv_of_real)\n  also have \"(\\<lambda>x. f (a + b * of_real x - a * of_real x)) =\n               (\\<lambda>x. (f (a + b * of_real x - a * of_real x) * (b - a)) /\\<^sub>R (Re b - Re a))\"\n    using \\<open>a \\<noteq> b\\<close> by (auto simp: field_simps fun_eq_iff scaleR_conv_of_real)\n  also have \"(\\<dots> has_integral I /\\<^sub>R (Re b - Re a)) {0..1} \\<longleftrightarrow> \n               ((\\<lambda>x. f (linepath a b x) * (b - a)) has_integral I) {0..1}\" using assms\n    by (subst has_integral_cmul_iff) (auto simp: linepath_def scaleR_conv_of_real algebra_simps)\n  also have \"\\<dots> \\<longleftrightarrow> (f has_contour_integral I) (linepath a b)\" unfolding has_contour_integral_def\n    by (intro has_integral_cong) (simp add: vector_derivative_linepath_within)\n  finally show ?thesis by simp\nqed\n\n\n\nlemma contour_integral_linepath_Reals_eq:\n  fixes a b :: complex and f :: \"complex \\<Rightarrow> complex\"\n  assumes \"a \\<in> Reals\" \"b \\<in> Reals\" \"Re a < Re b\"\n  shows   \"contour_integral (linepath a b) f = integral {Re a..Re b} (\\<lambda>x. f (of_real x))\"\nproof (cases \"f contour_integrable_on linepath a b\")\n  case True\n  thus ?thesis using has_contour_integral_linepath_Reals_iff[OF assms, of f]\n    using has_contour_integral_integral has_contour_integral_unique by blast\nnext\n  case False\n  thus ?thesis using contour_integrable_linepath_Reals_iff[OF assms, of f]\n    by (simp add: not_integrable_contour_integral not_integrable_integral)\nqed\n\nsubsection \\<open>Cauchy's theorem where there's a primitive\\<close>\n\nlemma contour_integral_primitive_lemma:\n  fixes f :: \"complex \\<Rightarrow> complex\" and g :: \"real \\<Rightarrow> complex\"\n  assumes \"a \\<le> b\"\n      and \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and \"g piecewise_differentiable_on {a..b}\"  \"\\<And>x. x \\<in> {a..b} \\<Longrightarrow> g x \\<in> S\"\n    shows \"((\\<lambda>x. f'(g x) * vector_derivative g (at x within {a..b}))\n             has_integral (f(g b) - f(g a))) {a..b}\"\nproof -\n  obtain K where \"finite K\" and K: \"\\<forall>x\\<in>{a..b} - K. g differentiable (at x within {a..b})\" and cg: \"continuous_on {a..b} g\"\n    using assms by (auto simp: piecewise_differentiable_on_def)\n  have \"continuous_on (g ` {a..b}) f\"\n    using assms\n    by (metis field_differentiable_def field_differentiable_imp_continuous_at continuous_on_eq_continuous_within continuous_on_subset image_subset_iff)\n  then have cfg: \"continuous_on {a..b} (\\<lambda>x. f (g x))\"\n    by (rule continuous_on_compose [OF cg, unfolded o_def])\n  { fix x::real\n    assume a: \"a < x\" and b: \"x < b\" and xk: \"x \\<notin> K\"\n    then have \"g differentiable at x within {a..b}\"\n      using K by (simp add: differentiable_at_withinI)\n    then have \"(g has_vector_derivative vector_derivative g (at x within {a..b})) (at x within {a..b})\"\n      by (simp add: vector_derivative_works has_field_derivative_def scaleR_conv_of_real)\n    then have gdiff: \"(g has_derivative (\\<lambda>u. u * vector_derivative g (at x within {a..b}))) (at x within {a..b})\"\n      by (simp add: has_vector_derivative_def scaleR_conv_of_real)\n    have \"(f has_field_derivative (f' (g x))) (at (g x) within g ` {a..b})\"\n      using assms by (metis a atLeastAtMost_iff b DERIV_subset image_subset_iff less_eq_real_def)\n    then have fdiff: \"(f has_derivative (*) (f' (g x))) (at (g x) within g ` {a..b})\"\n      by (simp add: has_field_derivative_def)\n    have \"((\\<lambda>x. f (g x)) has_vector_derivative f' (g x) * vector_derivative g (at x within {a..b})) (at x within {a..b})\"\n      using diff_chain_within [OF gdiff fdiff]\n      by (simp add: has_vector_derivative_def scaleR_conv_of_real o_def mult_ac)\n  } note * = this\n  show ?thesis\n    using assms cfg *\n    by (force simp: at_within_Icc_at intro: fundamental_theorem_of_calculus_interior_strong [OF \\<open>finite K\\<close>])\nqed\n\nlemma contour_integral_primitive:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and \"valid_path g\" \"path_image g \\<subseteq> S\"\n    shows \"(f' has_contour_integral (f(pathfinish g) - f(pathstart g))) g\"\n  using assms\n  apply (simp add: valid_path_def path_image_def pathfinish_def pathstart_def has_contour_integral_def)\n  apply (auto intro!: piecewise_C1_imp_differentiable contour_integral_primitive_lemma [of 0 1 S])\n  done\n\ncorollary Cauchy_theorem_primitive:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> (f has_field_derivative f' x) (at x within S)\"\n      and \"valid_path g\"  \"path_image g \\<subseteq> S\" \"pathfinish g = pathstart g\"\n    shows \"(f' has_contour_integral 0) g\"\n  using assms by (metis diff_self contour_integral_primitive)\n\ntext\\<open>Existence of path integral for continuous function\\<close>\nlemma contour_integrable_continuous_linepath:\n  assumes \"continuous_on (closed_segment a b) f\"\n  shows \"f contour_integrable_on (linepath a b)\"\nproof -\n  have \"continuous_on (closed_segment a b) (\\<lambda>x. f x * (b - a))\"\n    by (rule continuous_intros | simp add: assms)+\n  then have \"continuous_on {0..1} (\\<lambda>x. f (linepath a b x) * (b - a))\"\n    by (metis (no_types, lifting) continuous_on_compose continuous_on_cong continuous_on_linepath linepath_image_01 o_apply)\n  then have \"(\\<lambda>x. f (linepath a b x) *\n         vector_derivative (linepath a b)\n          (at x within {0..1})) integrable_on\n    {0..1}\"\n    by (metis (no_types, lifting) continuous_on_cong integrable_continuous_real vector_derivative_linepath_within)\n  then show ?thesis\n    by (simp add: contour_integrable_on_def has_contour_integral_def integrable_on_def [symmetric])\nqed\n\nlemma has_field_der_id: \"((\\<lambda>x. x\\<^sup>2/2) has_field_derivative x) (at x)\"\n  by (rule has_derivative_imp_has_field_derivative)\n     (rule derivative_intros | simp)+\n\nlemma contour_integral_id [simp]: \"contour_integral (linepath a b) (\\<lambda>y. y) = (b^2 - a^2)/2\"\n  using contour_integral_primitive [of UNIV \"\\<lambda>x. x^2/2\" \"\\<lambda>x. x\" \"linepath a b\"] contour_integral_unique\n  by (simp add: has_field_der_id)\n\nlemma contour_integrable_on_const [iff]: \"(\\<lambda>x. c) contour_integrable_on (linepath a b)\"\n  by (simp add: contour_integrable_continuous_linepath)\n\nlemma contour_integrable_on_id [iff]: \"(\\<lambda>x. x) contour_integrable_on (linepath a b)\"\n  by (simp add: contour_integrable_continuous_linepath)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Arithmetical combining theorems\\<close>\n\nlemma has_contour_integral_neg:\n    \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. -(f x)) has_contour_integral (-i)) g\"\n  by (simp add: has_integral_neg has_contour_integral_def)\n\nlemma has_contour_integral_add:\n    \"\\<lbrakk>(f1 has_contour_integral i1) g; (f2 has_contour_integral i2) g\\<rbrakk>\n     \\<Longrightarrow> ((\\<lambda>x. f1 x + f2 x) has_contour_integral (i1 + i2)) g\"\n  by (simp add: has_integral_add has_contour_integral_def algebra_simps)\n\nlemma has_contour_integral_diff:\n  \"\\<lbrakk>(f1 has_contour_integral i1) g; (f2 has_contour_integral i2) g\\<rbrakk>\n         \\<Longrightarrow> ((\\<lambda>x. f1 x - f2 x) has_contour_integral (i1 - i2)) g\"\n  by (simp add: has_integral_diff has_contour_integral_def algebra_simps)\n\nlemma has_contour_integral_lmul:\n  \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. c * (f x)) has_contour_integral (c*i)) g\"\n  by (simp add: has_contour_integral_def algebra_simps has_integral_mult_right)\n\nlemma has_contour_integral_rmul:\n  \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. (f x) * c) has_contour_integral (i*c)) g\"\n  by (simp add: mult.commute has_contour_integral_lmul)\n\nlemma has_contour_integral_div:\n  \"(f has_contour_integral i) g \\<Longrightarrow> ((\\<lambda>x. f x/c) has_contour_integral (i/c)) g\"\n  by (simp add: field_class.field_divide_inverse) (metis has_contour_integral_rmul)\n\nlemma has_contour_integral_eq:\n    \"\\<lbrakk>(f has_contour_integral y) p; \\<And>x. x \\<in> path_image p \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> (g has_contour_integral y) p\"\n  by (metis (mono_tags, lifting) has_contour_integral_def has_integral_eq image_eqI path_image_def)\n\nlemma has_contour_integral_bound_linepath:\n  assumes \"(f has_contour_integral i) (linepath a b)\"\n          \"0 \\<le> B\" and B: \"\\<And>x. x \\<in> closed_segment a b \\<Longrightarrow> norm(f x) \\<le> B\"\n    shows \"norm i \\<le> B * norm(b - a)\"\nproof -\n  have \"norm i \\<le> (B * norm (b - a)) * content (cbox 0 (1::real))\"\n  proof (rule has_integral_bound\n       [of _ \"\\<lambda>x. f (linepath a b x) * vector_derivative (linepath a b) (at x within {0..1})\"])\n    show  \"cmod (f (linepath a b x) * vector_derivative (linepath a b) (at x within {0..1}))\n         \\<le> B * cmod (b - a)\"\n      if \"x \\<in> cbox 0 1\" for x::real\n      using that box_real(2) norm_mult\n      by (metis B linepath_in_path mult_right_mono norm_ge_zero vector_derivative_linepath_within)\n  qed (use assms has_contour_integral_def in auto)\n  then show ?thesis\n    by (auto simp: content_real)\nqed\n\nlemma has_contour_integral_const_linepath: \"((\\<lambda>x. c) has_contour_integral c*(b - a))(linepath a b)\"\n  unfolding has_contour_integral_linepath\n  by (metis content_real diff_0_right has_integral_const_real lambda_one of_real_1 scaleR_conv_of_real zero_le_one)\n\nlemma has_contour_integral_0: \"((\\<lambda>x. 0) has_contour_integral 0) g\"\n  by (simp add: has_contour_integral_def)\n\nlemma has_contour_integral_is_0:\n    \"(\\<And>z. z \\<in> path_image g \\<Longrightarrow> f z = 0) \\<Longrightarrow> (f has_contour_integral 0) g\"\n  by (rule has_contour_integral_eq [OF has_contour_integral_0]) auto\n\nlemma has_contour_integral_sum:\n    \"\\<lbrakk>finite s; \\<And>a. a \\<in> s \\<Longrightarrow> (f a has_contour_integral i a) p\\<rbrakk>\n     \\<Longrightarrow> ((\\<lambda>x. sum (\\<lambda>a. f a x) s) has_contour_integral sum i s) p\"\n  by (induction s rule: finite_induct) (auto simp: has_contour_integral_0 has_contour_integral_add)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Operations on path integrals\\<close>\n\nlemma contour_integral_const_linepath [simp]: \"contour_integral (linepath a b) (\\<lambda>x. c) = c*(b - a)\"\n  by (rule contour_integral_unique [OF has_contour_integral_const_linepath])\n\nlemma contour_integral_neg:\n    \"f contour_integrable_on g \\<Longrightarrow> contour_integral g (\\<lambda>x. -(f x)) = -(contour_integral g f)\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_neg)\n\nlemma contour_integral_add:\n    \"f1 contour_integrable_on g \\<Longrightarrow> f2 contour_integrable_on g \\<Longrightarrow> contour_integral g (\\<lambda>x. f1 x + f2 x) =\n                contour_integral g f1 + contour_integral g f2\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_add)\n\nlemma contour_integral_diff:\n    \"f1 contour_integrable_on g \\<Longrightarrow> f2 contour_integrable_on g \\<Longrightarrow> contour_integral g (\\<lambda>x. f1 x - f2 x) =\n                contour_integral g f1 - contour_integral g f2\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_diff)\n\nlemma contour_integral_lmul:\n  shows \"f contour_integrable_on g\n           \\<Longrightarrow> contour_integral g (\\<lambda>x. c * f x) = c*contour_integral g f\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_lmul)\n\nlemma contour_integral_rmul:\n  shows \"f contour_integrable_on g\n        \\<Longrightarrow> contour_integral g (\\<lambda>x. f x * c) = contour_integral g f * c\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_rmul)\n\nlemma contour_integral_div:\n  shows \"f contour_integrable_on g\n        \\<Longrightarrow> contour_integral g (\\<lambda>x. f x / c) = contour_integral g f / c\"\n  by (simp add: contour_integral_unique has_contour_integral_integral has_contour_integral_div)\n\nlemma contour_integral_eq:\n    \"(\\<And>x. x \\<in> path_image p \\<Longrightarrow> f x = g x) \\<Longrightarrow> contour_integral p f = contour_integral p g\"\n  using contour_integral_cong contour_integral_def by fastforce\n\nlemma contour_integral_eq_0:\n    \"(\\<And>z. z \\<in> path_image g \\<Longrightarrow> f z = 0) \\<Longrightarrow> contour_integral g f = 0\"\n  by (simp add: has_contour_integral_is_0 contour_integral_unique)\n\nlemma contour_integral_bound_linepath:\n  shows\n    \"\\<lbrakk>f contour_integrable_on (linepath a b);\n      0 \\<le> B; \\<And>x. x \\<in> closed_segment a b \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n     \\<Longrightarrow> norm(contour_integral (linepath a b) f) \\<le> B*norm(b - a)\"\n  using has_contour_integral_bound_linepath [of f]\n  by (auto simp: has_contour_integral_integral)\n\nlemma contour_integral_0 [simp]: \"contour_integral g (\\<lambda>x. 0) = 0\"\n  by (simp add: contour_integral_unique has_contour_integral_0)\n\nlemma contour_integral_sum:\n    \"\\<lbrakk>finite s; \\<And>a. a \\<in> s \\<Longrightarrow> (f a) contour_integrable_on p\\<rbrakk>\n     \\<Longrightarrow> contour_integral p (\\<lambda>x. sum (\\<lambda>a. f a x) s) = sum (\\<lambda>a. contour_integral p (f a)) s\"\n  by (auto simp: contour_integral_unique has_contour_integral_sum has_contour_integral_integral)\n\nlemma contour_integrable_eq:\n    \"\\<lbrakk>f contour_integrable_on p; \\<And>x. x \\<in> path_image p \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> g contour_integrable_on p\"\n  unfolding contour_integrable_on_def\n  by (metis has_contour_integral_eq)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Arithmetic theorems for path integrability\\<close>\n\nlemma contour_integrable_neg:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. -(f x)) contour_integrable_on g\"\n  using has_contour_integral_neg contour_integrable_on_def by blast\n\nlemma contour_integrable_add:\n    \"\\<lbrakk>f1 contour_integrable_on g; f2 contour_integrable_on g\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f1 x + f2 x) contour_integrable_on g\"\n  using has_contour_integral_add contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_diff:\n    \"\\<lbrakk>f1 contour_integrable_on g; f2 contour_integrable_on g\\<rbrakk> \\<Longrightarrow> (\\<lambda>x. f1 x - f2 x) contour_integrable_on g\"\n  using has_contour_integral_diff contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_lmul:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. c * f x) contour_integrable_on g\"\n  using has_contour_integral_lmul contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_rmul:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. f x * c) contour_integrable_on g\"\n  using has_contour_integral_rmul contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_div:\n    \"f contour_integrable_on g \\<Longrightarrow> (\\<lambda>x. f x / c) contour_integrable_on g\"\n  using has_contour_integral_div contour_integrable_on_def\n  by fastforce\n\nlemma contour_integrable_sum:\n    \"\\<lbrakk>finite s; \\<And>a. a \\<in> s \\<Longrightarrow> (f a) contour_integrable_on p\\<rbrakk>\n     \\<Longrightarrow> (\\<lambda>x. sum (\\<lambda>a. f a x) s) contour_integrable_on p\"\n   unfolding contour_integrable_on_def\n   by (metis has_contour_integral_sum)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Reversing a path integral\\<close>\n\nlemma has_contour_integral_reverse_linepath:\n    \"(f has_contour_integral i) (linepath a b)\n     \\<Longrightarrow> (f has_contour_integral (-i)) (linepath b a)\"\n  using has_contour_integral_reversepath valid_path_linepath by fastforce\n\nlemma contour_integral_reverse_linepath:\n    \"continuous_on (closed_segment a b) f\n     \\<Longrightarrow> contour_integral (linepath a b) f = - (contour_integral(linepath b a) f)\"\n  by (metis contour_integrable_continuous_linepath contour_integral_unique has_contour_integral_integral has_contour_integral_reverse_linepath)\n\n\ntext \\<open>Splitting a path integral in a flat way.*)\\<close>\n\nlemma has_contour_integral_split:\n  assumes f: \"(f has_contour_integral i) (linepath a c)\" \"(f has_contour_integral j) (linepath c b)\"\n      and k: \"0 \\<le> k\" \"k \\<le> 1\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"(f has_contour_integral (i + j)) (linepath a b)\"\nproof (cases \"k = 0 \\<or> k = 1\")\n  case True\n  then show ?thesis\n    using assms by auto\nnext\n  case False\n  then have k: \"0 < k\" \"k < 1\" \"complex_of_real k \\<noteq> 1\"\n    using assms by auto\n  have c': \"c = k *\\<^sub>R (b - a) + a\"\n    by (metis diff_add_cancel c)\n  have bc: \"(b - c) = (1 - k) *\\<^sub>R (b - a)\"\n    by (simp add: algebra_simps c')\n  { assume *: \"((\\<lambda>x. f ((1 - x) *\\<^sub>R a + x *\\<^sub>R c) * (c - a)) has_integral i) {0..1}\"\n    have \"\\<And>x. (x / k) *\\<^sub>R a + ((k - x) / k) *\\<^sub>R a = a\"\n      using False by (simp add: field_split_simps flip: real_vector.scale_left_distrib)\n    then have \"\\<And>x. ((k - x) / k) *\\<^sub>R a + (x / k) *\\<^sub>R c = (1 - x) *\\<^sub>R a + x *\\<^sub>R b\"\n      using False by (simp add: c' algebra_simps)\n    then have \"((\\<lambda>x. f ((1 - x) *\\<^sub>R a + x *\\<^sub>R b) * (b - a)) has_integral i) {0..k}\"\n      using k has_integral_affinity01 [OF *, of \"inverse k\" \"0\"] \n      by (force dest: has_integral_cmul [where c = \"inverse k\"] \n              simp add: divide_simps mult.commute [of _ \"k\"] image_affinity_atLeastAtMost c)\n  } note fi = this\n  { assume *: \"((\\<lambda>x. f ((1 - x) *\\<^sub>R c + x *\\<^sub>R b) * (b - c)) has_integral j) {0..1}\"\n    have **: \"\\<And>x. (((1 - x) / (1 - k)) *\\<^sub>R c + ((x - k) / (1 - k)) *\\<^sub>R b) = ((1 - x) *\\<^sub>R a + x *\\<^sub>R b)\"\n      using k unfolding c' scaleR_conv_of_real\n      apply (simp add: divide_simps)\n      apply (simp add: distrib_right distrib_left right_diff_distrib left_diff_distrib)\n      done\n    have \"((\\<lambda>x. f ((1 - x) *\\<^sub>R a + x *\\<^sub>R b) * (b - a)) has_integral j) {k..1}\"\n      using k has_integral_affinity01 [OF *, of \"inverse(1 - k)\" \"-(k/(1 - k))\"]\n      apply (simp add: divide_simps mult.commute [of _ \"1-k\"] image_affinity_atLeastAtMost ** bc)\n      apply (auto dest: has_integral_cmul [where k = \"(1 - k) *\\<^sub>R j\" and c = \"inverse (1 - k)\"])\n      done\n  } note fj = this\n  show ?thesis\n    using f k unfolding has_contour_integral_linepath\n    by (simp add: linepath_def has_integral_combine [OF _ _ fi fj])\nqed\n\nlemma continuous_on_closed_segment_transform:\n  assumes f: \"continuous_on (closed_segment a b) f\"\n      and k: \"0 \\<le> k\" \"k \\<le> 1\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"continuous_on (closed_segment a c) f\"\nproof -\n  have c': \"c = (1 - k) *\\<^sub>R a + k *\\<^sub>R b\"\n    using c by (simp add: algebra_simps)\n  have \"closed_segment a c \\<subseteq> closed_segment a b\"\n    by (metis c' ends_in_segment(1) in_segment(1) k subset_closed_segment)\n  then show \"continuous_on (closed_segment a c) f\"\n    by (rule continuous_on_subset [OF f])\nqed\n\nlemma contour_integral_split:\n  assumes f: \"continuous_on (closed_segment a b) f\"\n      and k: \"0 \\<le> k\" \"k \\<le> 1\"\n      and c: \"c - a = k *\\<^sub>R (b - a)\"\n    shows \"contour_integral(linepath a b) f = contour_integral(linepath a c) f + contour_integral(linepath c b) f\"\nproof -\n  have c': \"c = (1 - k) *\\<^sub>R a + k *\\<^sub>R b\"\n    using c by (simp add: algebra_simps)\n  have \"closed_segment a c \\<subseteq> closed_segment a b\"\n    by (metis c' ends_in_segment(1) in_segment(1) k subset_closed_segment)\n  moreover have \"closed_segment c b \\<subseteq> closed_segment a b\"\n    by (metis c' ends_in_segment(2) in_segment(1) k subset_closed_segment)\n  ultimately\n  have *: \"continuous_on (closed_segment a c) f\" \"continuous_on (closed_segment c b) f\"\n    by (auto intro: continuous_on_subset [OF f])\n  show ?thesis\n    by (rule contour_integral_unique) (meson \"*\" c contour_integrable_continuous_linepath has_contour_integral_integral has_contour_integral_split k)\nqed\n\nlemma contour_integral_split_linepath:\n  assumes f: \"continuous_on (closed_segment a b) f\"\n      and c: \"c \\<in> closed_segment a b\"\n    shows \"contour_integral(linepath a b) f = contour_integral(linepath a c) f + contour_integral(linepath c b) f\"\n  using c by (auto simp: closed_segment_def algebra_simps intro!: contour_integral_split [OF f])\n\n\nsubsection\\<open>Reversing the order in a double path integral\\<close>\n\ntext\\<open>The condition is stronger than needed but it's often true in typical situations\\<close>\n\nlemma fst_im_cbox [simp]: \"cbox c d \\<noteq> {} \\<Longrightarrow> (fst ` cbox (a,c) (b,d)) = cbox a b\"\n  by (auto simp: cbox_Pair_eq)\n\nlemma snd_im_cbox [simp]: \"cbox a b \\<noteq> {} \\<Longrightarrow> (snd ` cbox (a,c) (b,d)) = cbox c d\"\n  by (auto simp: cbox_Pair_eq)\n\nproposition contour_integral_swap:\n  assumes fcon:  \"continuous_on (path_image g \\<times> path_image h) (\\<lambda>(y1,y2). f y1 y2)\"\n      and vp:    \"valid_path g\" \"valid_path h\"\n      and gvcon: \"continuous_on {0..1} (\\<lambda>t. vector_derivative g (at t))\"\n      and hvcon: \"continuous_on {0..1} (\\<lambda>t. vector_derivative h (at t))\"\n  shows \"contour_integral g (\\<lambda>w. contour_integral h (f w)) =\n         contour_integral h (\\<lambda>z. contour_integral g (\\<lambda>w. f w z))\"\nproof -\n  have gcon: \"continuous_on {0..1} g\" and hcon: \"continuous_on {0..1} h\"\n    using assms by (auto simp: valid_path_def piecewise_C1_differentiable_on_def)\n  have fgh1: \"\\<And>x. (\\<lambda>t. f (g x) (h t)) = (\\<lambda>(y1,y2). f y1 y2) \\<circ> (\\<lambda>t. (g x, h t))\"\n    by (rule ext) simp\n  have fgh2: \"\\<And>x. (\\<lambda>t. f (g t) (h x)) = (\\<lambda>(y1,y2). f y1 y2) \\<circ> (\\<lambda>t. (g t, h x))\"\n    by (rule ext) simp\n  have fcon_im1: \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> continuous_on ((\\<lambda>t. (g x, h t)) ` {0..1}) (\\<lambda>(x, y). f x y)\"\n    by (rule continuous_on_subset [OF fcon]) (auto simp: path_image_def)\n  have fcon_im2: \"\\<And>x. 0 \\<le> x \\<Longrightarrow> x \\<le> 1 \\<Longrightarrow> continuous_on ((\\<lambda>t. (g t, h x)) ` {0..1}) (\\<lambda>(x, y). f x y)\"\n    by (rule continuous_on_subset [OF fcon]) (auto simp: path_image_def)\n  have \"continuous_on (cbox (0, 0) (1, 1::real)) ((\\<lambda>x. vector_derivative g (at x)) \\<circ> fst)\"\n       \"continuous_on (cbox (0, 0) (1::real, 1)) ((\\<lambda>x. vector_derivative h (at x)) \\<circ> snd)\"\n    by (rule continuous_intros | simp add: gvcon hvcon)+\n  then have gvcon': \"continuous_on (cbox (0, 0) (1, 1::real)) (\\<lambda>z. vector_derivative g (at (fst z)))\"\n       and  hvcon': \"continuous_on (cbox (0, 0) (1::real, 1)) (\\<lambda>x. vector_derivative h (at (snd x)))\"\n    by auto\n  have \"continuous_on (cbox (0, 0) (1, 1)) ((\\<lambda>(y1, y2). f y1 y2) \\<circ> (\\<lambda>w. ((g \\<circ> fst) w, (h \\<circ> snd) w)))\"\n    apply (intro gcon hcon continuous_intros | simp)+\n    apply (auto simp: path_image_def intro: continuous_on_subset [OF fcon])\n    done\n  then have fgh: \"continuous_on (cbox (0, 0) (1, 1)) (\\<lambda>x. f (g (fst x)) (h (snd x)))\"\n    by auto\n  have \"integral {0..1} (\\<lambda>x. contour_integral h (f (g x)) * vector_derivative g (at x)) =\n        integral {0..1} (\\<lambda>x. contour_integral h (\\<lambda>y. f (g x) y * vector_derivative g (at x)))\"\n  proof (rule integral_cong [OF contour_integral_rmul [symmetric]])\n    have \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow>\n         continuous_on {0..1} (\\<lambda>xa. f (g x) (h xa))\"\n    by (subst fgh1) (rule fcon_im1 hcon continuous_intros | simp)+\n    then show \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> f (g x) contour_integrable_on h\"\n      unfolding contour_integrable_on\n      using continuous_on_mult hvcon integrable_continuous_real by blast\n  qed\n  also have \"\\<dots> = integral {0..1}\n                     (\\<lambda>y. contour_integral g (\\<lambda>x. f x (h y) * vector_derivative h (at y)))\"\n    unfolding contour_integral_integral\n    apply (subst integral_swap_continuous [where 'a = real and 'b = real, of 0 0 1 1, simplified])\n    subgoal\n      by (rule fgh gvcon' hvcon' continuous_intros | simp add: split_def)+\n    subgoal\n      unfolding integral_mult_left [symmetric]\n      by (simp only: mult_ac)\n    done\n  also have \"\\<dots> = contour_integral h (\\<lambda>z. contour_integral g (\\<lambda>w. f w z))\"\n    unfolding contour_integral_integral integral_mult_left [symmetric]\n    by (simp add: algebra_simps)\n  finally show ?thesis\n    by (simp add: contour_integral_integral)\nqed\n\nlemma valid_path_negatepath: \"valid_path \\<gamma> \\<Longrightarrow> valid_path (uminus \\<circ> \\<gamma>)\"\n   unfolding o_def using piecewise_C1_differentiable_neg valid_path_def by blast\n\nlemma has_contour_integral_negatepath:\n  assumes \\<gamma>: \"valid_path \\<gamma>\" and cint: \"((\\<lambda>z. f (- z)) has_contour_integral - i) \\<gamma>\"\n  shows \"(f has_contour_integral i) (uminus \\<circ> \\<gamma>)\"\nproof -\n  obtain S where cont: \"continuous_on {0..1} \\<gamma>\" and \"finite S\" and diff: \"\\<gamma> C1_differentiable_on {0..1} - S\"\n    using \\<gamma> by (auto simp: valid_path_def piecewise_C1_differentiable_on_def)\n  have \"((\\<lambda>x. - (f (- \\<gamma> x) * vector_derivative \\<gamma> (at x within {0..1}))) has_integral i) {0..1}\"\n    using cint by (auto simp: has_contour_integral_def dest: has_integral_neg)\n  then\n  have \"((\\<lambda>x. f (- \\<gamma> x) * vector_derivative (uminus \\<circ> \\<gamma>) (at x within {0..1})) has_integral i) {0..1}\"\n  proof (rule rev_iffD1 [OF _ has_integral_spike_eq])\n    show \"negligible S\"\n      by (simp add: \\<open>finite S\\<close> negligible_finite)\n    show \"f (- \\<gamma> x) * vector_derivative (uminus \\<circ> \\<gamma>) (at x within {0..1}) =\n         - (f (- \\<gamma> x) * vector_derivative \\<gamma> (at x within {0..1}))\"\n      if \"x \\<in> {0..1} - S\" for x\n    proof -\n      have \"vector_derivative (uminus \\<circ> \\<gamma>) (at x within cbox 0 1) = - vector_derivative \\<gamma> (at x within cbox 0 1)\"\n      proof (rule vector_derivative_within_cbox)\n        show \"(uminus \\<circ> \\<gamma> has_vector_derivative - vector_derivative \\<gamma> (at x within cbox 0 1)) (at x within cbox 0 1)\"\n          using that unfolding o_def\n          by (metis C1_differentiable_on_eq UNIV_I diff differentiable_subset has_vector_derivative_minus subsetI that vector_derivative_works)\n      qed (use that in auto)\n      then show ?thesis\n        by simp\n    qed\n  qed\n  then show ?thesis by (simp add: has_contour_integral_def)\nqed\n\nlemma contour_integrable_negatepath:\n  assumes \\<gamma>: \"valid_path \\<gamma>\" and pi: \"(\\<lambda>z. f (- z)) contour_integrable_on \\<gamma>\"\n  shows \"f contour_integrable_on (uminus \\<circ> \\<gamma>)\"\n  by (metis \\<gamma> add.inverse_inverse contour_integrable_on_def has_contour_integral_negatepath pi)\n\nlemma C1_differentiable_polynomial_function:\n  fixes p :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"polynomial_function p \\<Longrightarrow> p C1_differentiable_on S\"\n  by (metis continuous_on_polymonial_function C1_differentiable_on_def  has_vector_derivative_polynomial_function)\n\nlemma valid_path_polynomial_function:\n  fixes p :: \"real \\<Rightarrow> 'a::euclidean_space\"\n  shows \"polynomial_function p \\<Longrightarrow> valid_path p\"\nby (force simp: valid_path_def piecewise_C1_differentiable_on_def continuous_on_polymonial_function C1_differentiable_polynomial_function)\n\nlemma valid_path_subpath_trivial [simp]:\n    fixes g :: \"real \\<Rightarrow> 'a::euclidean_space\"\n    shows \"z \\<noteq> g x \\<Longrightarrow> valid_path (subpath x x g)\"\n  by (simp add: subpath_def valid_path_polynomial_function)\n\nsubsection\\<open>Partial circle path\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> part_circlepath :: \"[complex, real, real, real, real] \\<Rightarrow> complex\"\n  where \"part_circlepath z r s t \\<equiv> \\<lambda>x. z + of_real r * exp (\\<i> * of_real (linepath s t x))\"\n\nlemma pathstart_part_circlepath [simp]:\n     \"pathstart(part_circlepath z r s t) = z + r*exp(\\<i> * s)\"\nby (metis part_circlepath_def pathstart_def pathstart_linepath)\n\nlemma pathfinish_part_circlepath [simp]:\n     \"pathfinish(part_circlepath z r s t) = z + r*exp(\\<i>*t)\"\nby (metis part_circlepath_def pathfinish_def pathfinish_linepath)\n\nlemma reversepath_part_circlepath[simp]:\n    \"reversepath (part_circlepath z r s t) = part_circlepath z r t s\"\n  unfolding part_circlepath_def reversepath_def linepath_def \n  by (auto simp:algebra_simps)\n    \nlemma has_vector_derivative_part_circlepath [derivative_intros]:\n    \"((part_circlepath z r s t) has_vector_derivative\n      (\\<i> * r * (of_real t - of_real s) * exp(\\<i> * linepath s t x)))\n     (at x within X)\"\n  unfolding part_circlepath_def linepath_def scaleR_conv_of_real\n  by (rule has_vector_derivative_real_field derivative_eq_intros | simp)+\n\nlemma differentiable_part_circlepath:\n  \"part_circlepath c r a b differentiable at x within A\"\n  using has_vector_derivative_part_circlepath[of c r a b x A] differentiableI_vector by blast\n\nlemma vector_derivative_part_circlepath:\n    \"vector_derivative (part_circlepath z r s t) (at x) =\n       \\<i> * r * (of_real t - of_real s) * exp(\\<i> * linepath s t x)\"\n  using has_vector_derivative_part_circlepath vector_derivative_at by blast\n\nlemma vector_derivative_part_circlepath01:\n    \"\\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk>\n     \\<Longrightarrow> vector_derivative (part_circlepath z r s t) (at x within {0..1}) =\n          \\<i> * r * (of_real t - of_real s) * exp(\\<i> * linepath s t x)\"\n  using has_vector_derivative_part_circlepath\n  by (auto simp: vector_derivative_at_within_ivl)\n\nlemma valid_path_part_circlepath [simp]: \"valid_path (part_circlepath z r s t)\"\n  unfolding valid_path_def\n  by (auto simp: C1_differentiable_on_eq vector_derivative_works vector_derivative_part_circlepath has_vector_derivative_part_circlepath\n              intro!: C1_differentiable_imp_piecewise continuous_intros)\n\nlemma path_part_circlepath [simp]: \"path (part_circlepath z r s t)\"\n  by (simp add: valid_path_imp_path)\n\nproposition path_image_part_circlepath:\n  assumes \"s \\<le> t\"\n    shows \"path_image (part_circlepath z r s t) = {z + r * exp(\\<i> * of_real x) | x. s \\<le> x \\<and> x \\<le> t}\"\nproof -\n  { fix z::real\n    assume \"0 \\<le> z\" \"z \\<le> 1\"\n    with \\<open>s \\<le> t\\<close> have \"\\<exists>x. (exp (\\<i> * linepath s t z) = exp (\\<i> * of_real x)) \\<and> s \\<le> x \\<and> x \\<le> t\"\n      apply (rule_tac x=\"(1 - z) * s + z * t\" in exI)\n      apply (simp add: linepath_def scaleR_conv_of_real algebra_simps)\n      by (metis (no_types) affine_ineq mult.commute mult_left_mono)\n  }\n  moreover\n  { fix z\n    assume \"s \\<le> z\" \"z \\<le> t\"\n    then have \"z + of_real r * exp (\\<i> * of_real z) \\<in> (\\<lambda>x. z + of_real r * exp (\\<i> * linepath s t x)) ` {0..1}\"\n      apply (rule_tac x=\"(z - s)/(t - s)\" in image_eqI)\n      apply (simp add: linepath_def scaleR_conv_of_real divide_simps exp_eq)\n      apply (auto simp: field_split_simps)\n      done\n  }\n  ultimately show ?thesis\n    by (fastforce simp add: path_image_def part_circlepath_def)\nqed\n\nlemma path_image_part_circlepath':\n  \"path_image (part_circlepath z r s t) = (\\<lambda>x. z + r * cis x) ` closed_segment s t\"\nproof -\n  have \"path_image (part_circlepath z r s t) = \n          (\\<lambda>x. z + r * exp(\\<i> * of_real x)) ` linepath s t ` {0..1}\"\n    by (simp add: image_image path_image_def part_circlepath_def)\n  also have \"linepath s t ` {0..1} = closed_segment s t\"\n    by (rule linepath_image_01)\n  finally show ?thesis by (simp add: cis_conv_exp)\nqed\n\nlemma path_image_part_circlepath_subset:\n    \"\\<lbrakk>s \\<le> t; 0 \\<le> r\\<rbrakk> \\<Longrightarrow> path_image(part_circlepath z r s t) \\<subseteq> sphere z r\"\nby (auto simp: path_image_part_circlepath sphere_def dist_norm algebra_simps norm_mult)\n\nlemma in_path_image_part_circlepath:\n  assumes \"w \\<in> path_image(part_circlepath z r s t)\" \"s \\<le> t\" \"0 \\<le> r\"\n    shows \"norm(w - z) = r\"\nproof -\n  have \"w \\<in> {c. dist z c = r}\"\n    by (metis (no_types) path_image_part_circlepath_subset sphere_def subset_eq assms)\n  thus ?thesis\n    by (simp add: dist_norm norm_minus_commute)\nqed\n\nlemma path_image_part_circlepath_subset':\n  assumes \"r \\<ge> 0\"\n  shows   \"path_image (part_circlepath z r s t) \\<subseteq> sphere z r\"\nproof (cases \"s \\<le> t\")\n  case True\n  thus ?thesis using path_image_part_circlepath_subset[of s t r z] assms by simp\nnext\n  case False\n  thus ?thesis using path_image_part_circlepath_subset[of t s r z] assms\n    by (subst reversepath_part_circlepath [symmetric], subst path_image_reversepath) simp_all\nqed\n\nlemma part_circlepath_cnj: \"cnj (part_circlepath c r a b x) = part_circlepath (cnj c) r (-a) (-b) x\"\n  by (simp add: part_circlepath_def exp_cnj linepath_def algebra_simps)\n\nlemma contour_integral_bound_part_circlepath:\n  assumes \"f contour_integrable_on part_circlepath c r a b\"\n  assumes \"B \\<ge> 0\" \"r \\<ge> 0\" \"\\<And>x. x \\<in> path_image (part_circlepath c r a b) \\<Longrightarrow> norm (f x) \\<le> B\"\n  shows   \"norm (contour_integral (part_circlepath c r a b) f) \\<le> B * r * \\<bar>b - a\\<bar>\"\nproof -\n  let ?I = \"integral {0..1} (\\<lambda>x. f (part_circlepath c r a b x) * \\<i> * of_real (r * (b - a)) *\n              exp (\\<i> * linepath a b x))\"\n  have \"norm ?I \\<le> integral {0..1} (\\<lambda>x::real. B * 1 * (r * \\<bar>b - a\\<bar>) * 1)\"\n  proof (rule integral_norm_bound_integral, goal_cases)\n    case 1\n    with assms(1) show ?case\n      by (simp add: contour_integrable_on vector_derivative_part_circlepath mult_ac)\n  next\n    case (3 x)\n    with assms(2-) show ?case unfolding norm_mult norm_of_real abs_mult\n      by (intro mult_mono) (auto simp: path_image_def)\n  qed auto\n  also have \"?I = contour_integral (part_circlepath c r a b) f\"\n    by (simp add: contour_integral_integral vector_derivative_part_circlepath mult_ac)\n  finally show ?thesis by simp\nqed\n\nlemma has_contour_integral_part_circlepath_iff:\n  assumes \"a < b\"\n  shows \"(f has_contour_integral I) (part_circlepath c r a b) \\<longleftrightarrow>\n           ((\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) has_integral I) {a..b}\"\nproof -\n  have \"(f has_contour_integral I) (part_circlepath c r a b) \\<longleftrightarrow>\n          ((\\<lambda>x. f (part_circlepath c r a b x) * vector_derivative (part_circlepath c r a b)\n           (at x within {0..1})) has_integral I) {0..1}\"\n    unfolding has_contour_integral_def ..\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. f (part_circlepath c r a b x) * r * (b - a) * \\<i> *\n                            cis (linepath a b x)) has_integral I) {0..1}\"\n    by (intro has_integral_cong, subst vector_derivative_part_circlepath01)\n       (simp_all add: cis_conv_exp)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. f (c + r * exp (\\<i> * linepath (of_real a) (of_real b) x)) *\n                       r * \\<i> * exp (\\<i> * linepath (of_real a) (of_real b) x) *\n                       vector_derivative (linepath (of_real a) (of_real b)) \n                         (at x within {0..1})) has_integral I) {0..1}\"\n    by (intro has_integral_cong, subst vector_derivative_linepath_within)\n       (auto simp: part_circlepath_def cis_conv_exp of_real_linepath [symmetric])\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>z. f (c + r * exp (\\<i> * z)) * r * \\<i> * exp (\\<i> * z)) has_contour_integral I)\n                      (linepath (of_real a) (of_real b))\"\n    by (simp add: has_contour_integral_def)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) has_integral I) {a..b}\" using assms\n    by (subst has_contour_integral_linepath_Reals_iff) (simp_all add: cis_conv_exp)\n  finally show ?thesis .\nqed\n\nlemma contour_integrable_part_circlepath_iff:\n  assumes \"a < b\"\n  shows \"f contour_integrable_on (part_circlepath c r a b) \\<longleftrightarrow>\n           (\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) integrable_on {a..b}\"\n  using assms by (auto simp: contour_integrable_on_def integrable_on_def \n                             has_contour_integral_part_circlepath_iff)\n\nlemma contour_integral_part_circlepath_eq:\n  assumes \"a < b\"\n  shows \"contour_integral (part_circlepath c r a b) f =\n           integral {a..b} (\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t)\"\nproof (cases \"f contour_integrable_on part_circlepath c r a b\")\n  case True\n  hence \"(\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) integrable_on {a..b}\" \n    using assms by (simp add: contour_integrable_part_circlepath_iff)\n  with True show ?thesis\n    using has_contour_integral_part_circlepath_iff[OF assms]\n          contour_integral_unique has_integral_integrable_integral by blast\nnext\n  case False\n  hence \"\\<not>(\\<lambda>t. f (c + r * cis t) * r * \\<i> * cis t) integrable_on {a..b}\" \n    using assms by (simp add: contour_integrable_part_circlepath_iff)\n  with False show ?thesis\n    by (simp add: not_integrable_contour_integral not_integrable_integral)\nqed\n\nlemma contour_integral_part_circlepath_reverse:\n  \"contour_integral (part_circlepath c r a b) f = -contour_integral (part_circlepath c r b a) f\"\n  by (subst reversepath_part_circlepath [symmetric], subst contour_integral_reversepath) simp_all\n\nlemma contour_integral_part_circlepath_reverse':\n  \"b < a \\<Longrightarrow> contour_integral (part_circlepath c r a b) f = \n               -contour_integral (part_circlepath c r b a) f\"\n  by (rule contour_integral_part_circlepath_reverse)\n\nlemma finite_bounded_log: \"finite {z::complex. norm z \\<le> b \\<and> exp z = w}\"\nproof (cases \"w = 0\")\n  case True then show ?thesis by auto\nnext\n  case False\n  have *: \"finite {x. cmod ((2 * real_of_int x * pi) * \\<i>) \\<le> b + cmod (Ln w)}\"\n  proof (simp add: norm_mult finite_int_iff_bounded_le)\n    show \"\\<exists>k. abs ` {x. 2 * \\<bar>of_int x\\<bar> * pi \\<le> b + cmod (Ln w)} \\<subseteq> {..k}\"\n    apply (rule_tac x=\"\\<lfloor>(b + cmod (Ln w)) / (2*pi)\\<rfloor>\" in exI)\n    apply (auto simp: field_split_simps le_floor_iff)\n      done\n  qed\n  have [simp]: \"\\<And>P f. {z. P z \\<and> (\\<exists>n. z = f n)} = f ` {n. P (f n)}\"\n    by blast\n  have \"finite {z. cmod z \\<le> b \\<and> exp z = exp (Ln w)}\"\n    using norm_add_leD by (fastforce intro: finite_subset [OF _ *] simp: exp_eq)\n  then show ?thesis\n    using False by auto\nqed\n\nlemma finite_bounded_log2:\n  fixes a::complex\n    assumes \"a \\<noteq> 0\"\n    shows \"finite {z. norm z \\<le> b \\<and> exp(a*z) = w}\"\nproof -\n  have *: \"finite ((\\<lambda>z. z / a) ` {z. cmod z \\<le> b * cmod a \\<and> exp z = w})\"\n    by (rule finite_imageI [OF finite_bounded_log])\n  show ?thesis\n    by (rule finite_subset [OF _ *]) (force simp: assms norm_mult)\nqed\n\nlemma has_contour_integral_bound_part_circlepath_strong:\n  assumes fi: \"(f has_contour_integral i) (part_circlepath z r s t)\"\n      and \"finite k\" and le: \"0 \\<le> B\" \"0 < r\" \"s \\<le> t\"\n      and B: \"\\<And>x. x \\<in> path_image(part_circlepath z r s t) - k \\<Longrightarrow> norm(f x) \\<le> B\"\n    shows \"cmod i \\<le> B * r * (t - s)\"\nproof -\n  consider \"s = t\" | \"s < t\" using \\<open>s \\<le> t\\<close> by linarith\n  then show ?thesis\n  proof cases\n    case 1 with fi [unfolded has_contour_integral]\n    have \"i = 0\"  by (simp add: vector_derivative_part_circlepath)\n    with assms show ?thesis by simp\n  next\n    case 2\n    have [simp]: \"\\<bar>r\\<bar> = r\" using \\<open>r > 0\\<close> by linarith\n    have [simp]: \"cmod (complex_of_real t - complex_of_real s) = t-s\"\n      by (metis \"2\" abs_of_pos diff_gt_0_iff_gt norm_of_real of_real_diff)\n    have \"finite (part_circlepath z r s t -` {y} \\<inter> {0..1})\" if \"y \\<in> k\" for y\n    proof -\n      let ?w = \"(y - z)/of_real r / exp(\\<i> * of_real s)\"\n      have fin: \"finite (of_real -` {z. cmod z \\<le> 1 \\<and> exp (\\<i> * complex_of_real (t - s) * z) = ?w})\"\n        using \\<open>s < t\\<close> \n        by (intro finite_vimageI [OF finite_bounded_log2]) (auto simp: inj_of_real)\n      show ?thesis\n        unfolding part_circlepath_def linepath_def vimage_def\n        using le\n        by (intro finite_subset [OF _ fin]) (auto simp: algebra_simps scaleR_conv_of_real exp_add exp_diff)\n    qed\n    then have fin01: \"finite ((part_circlepath z r s t) -` k \\<inter> {0..1})\"\n      by (rule finite_finite_vimage_IntI [OF \\<open>finite k\\<close>])\n    have **: \"((\\<lambda>x. if (part_circlepath z r s t x) \\<in> k then 0\n                    else f(part_circlepath z r s t x) *\n                       vector_derivative (part_circlepath z r s t) (at x)) has_integral i)  {0..1}\"\n      by (rule has_integral_spike [OF negligible_finite [OF fin01]])  (use fi has_contour_integral in auto)\n    have *: \"\\<And>x. \\<lbrakk>0 \\<le> x; x \\<le> 1; part_circlepath z r s t x \\<notin> k\\<rbrakk> \\<Longrightarrow> cmod (f (part_circlepath z r s t x)) \\<le> B\"\n      by (auto intro!: B [unfolded path_image_def image_def, simplified])\n    show ?thesis\n      apply (rule has_integral_bound [where 'a=real, simplified, OF _ **, simplified])\n      using assms le * \"2\" \\<open>r > 0\\<close> by (auto simp add: norm_mult vector_derivative_part_circlepath)\n  qed\nqed\n\nlemma has_contour_integral_bound_part_circlepath:\n      \"\\<lbrakk>(f has_contour_integral i) (part_circlepath z r s t);\n        0 \\<le> B; 0 < r; s \\<le> t;\n        \\<And>x. x \\<in> path_image(part_circlepath z r s t) \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n       \\<Longrightarrow> norm i \\<le> B*r*(t - s)\"\n  by (auto intro: has_contour_integral_bound_part_circlepath_strong)\n\nlemma contour_integrable_continuous_part_circlepath:\n     \"continuous_on (path_image (part_circlepath z r s t)) f\n      \\<Longrightarrow> f contour_integrable_on (part_circlepath z r s t)\"\n  unfolding contour_integrable_on has_contour_integral_def vector_derivative_part_circlepath path_image_def\n  apply (rule integrable_continuous_real)\n  apply (fast intro: path_part_circlepath [unfolded path_def] continuous_intros continuous_on_compose2 [where g=f, OF _ _ order_refl])\n  done\n\nlemma simple_path_part_circlepath:\n    \"simple_path(part_circlepath z r s t) \\<longleftrightarrow> (r \\<noteq> 0 \\<and> s \\<noteq> t \\<and> \\<bar>s - t\\<bar> \\<le> 2*pi)\"\nproof (cases \"r = 0 \\<or> s = t\")\n  case True\n  then show ?thesis\n    unfolding part_circlepath_def simple_path_def\n    by (rule disjE) (force intro: bexI [where x = \"1/4\"] bexI [where x = \"1/3\"])+\nnext\n  case False then have \"r \\<noteq> 0\" \"s \\<noteq> t\" by auto\n  have *: \"\\<And>x y z s t. \\<i>*((1 - x) * s + x * t) = \\<i>*(((1 - y) * s + y * t)) + z  \\<longleftrightarrow> \\<i>*(x - y) * (t - s) = z\"\n    by (simp add: algebra_simps)\n  have abs01: \"\\<And>x y::real. 0 \\<le> x \\<and> x \\<le> 1 \\<and> 0 \\<le> y \\<and> y \\<le> 1\n                      \\<Longrightarrow> (x = y \\<or> x = 0 \\<and> y = 1 \\<or> x = 1 \\<and> y = 0 \\<longleftrightarrow> \\<bar>x - y\\<bar> \\<in> {0,1})\"\n    by auto\n  have **: \"\\<And>x y. (\\<exists>n. (complex_of_real x - of_real y) * (of_real t - of_real s) = 2 * (of_int n * of_real pi)) \\<longleftrightarrow>\n                  (\\<exists>n. \\<bar>x - y\\<bar> * (t - s) = 2 * (of_int n * pi))\"\n    by (force simp: algebra_simps abs_if dest: arg_cong [where f=Re] arg_cong [where f=complex_of_real]\n                    intro: exI [where x = \"-n\" for n])\n  have 1: \"\\<bar>s - t\\<bar> \\<le> 2 * pi\"\n    if \"\\<And>x. 0 \\<le> x \\<and> x \\<le> 1 \\<Longrightarrow> (\\<exists>n. x * (t - s) = 2 * (real_of_int n * pi)) \\<longrightarrow> x = 0 \\<or> x = 1\"\n  proof (rule ccontr)\n    assume \"\\<not> \\<bar>s - t\\<bar> \\<le> 2 * pi\"\n    then have *: \"\\<And>n. t - s \\<noteq> of_int n * \\<bar>s - t\\<bar>\"\n      using False that [of \"2*pi / \\<bar>t - s\\<bar>\"]\n      by (simp add: abs_minus_commute divide_simps)\n    show False\n      using * [of 1] * [of \"-1\"] by auto\n  qed\n  have 2: \"\\<bar>s - t\\<bar> = \\<bar>2 * (real_of_int n * pi) / x\\<bar>\" if \"x \\<noteq> 0\" \"x * (t - s) = 2 * (real_of_int n * pi)\" for x n\n  proof -\n    have \"t-s = 2 * (real_of_int n * pi)/x\"\n      using that by (simp add: field_simps)\n    then show ?thesis by (metis abs_minus_commute)\n  qed\n  have abs_away: \"\\<And>P. (\\<forall>x\\<in>{0..1}. \\<forall>y\\<in>{0..1}. P \\<bar>x - y\\<bar>) \\<longleftrightarrow> (\\<forall>x::real. 0 \\<le> x \\<and> x \\<le> 1 \\<longrightarrow> P x)\"\n    by force\n  show ?thesis using False\n    apply (simp add: simple_path_def)\n    apply (simp add: part_circlepath_def linepath_def exp_eq  * ** abs01 del: Set.insert_iff)\n    apply (subst abs_away)\n    apply (auto simp: 1)\n    apply (rule ccontr)\n    apply (auto simp: 2 field_split_simps abs_mult dest: of_int_leD)\n    done\nqed\n\nlemma arc_part_circlepath:\n  assumes \"r \\<noteq> 0\" \"s \\<noteq> t\" \"\\<bar>s - t\\<bar> < 2*pi\"\n    shows \"arc (part_circlepath z r s t)\"\nproof -\n  have *: \"x = y\" if eq: \"\\<i> * (linepath s t x) = \\<i> * (linepath s t y) + 2 * of_int n * complex_of_real pi * \\<i>\"\n    and x: \"x \\<in> {0..1}\" and y: \"y \\<in> {0..1}\" for x y n\n  proof (rule ccontr)\n    assume \"x \\<noteq> y\"\n    have \"(linepath s t x) = (linepath s t y) + 2 * of_int n * complex_of_real pi\"\n      by (metis add_divide_eq_iff complex_i_not_zero mult.commute nonzero_mult_div_cancel_left eq)\n    then have \"s*y + t*x = s*x + (t*y + of_int n * (pi * 2))\"\n      by (force simp: algebra_simps linepath_def dest: arg_cong [where f=Re])\n    with \\<open>x \\<noteq> y\\<close> have st: \"s-t = (of_int n * (pi * 2) / (y-x))\"\n      by (force simp: field_simps)\n    have \"\\<bar>real_of_int n\\<bar> < \\<bar>y - x\\<bar>\"\n      using assms \\<open>x \\<noteq> y\\<close> by (simp add: st abs_mult field_simps)\n    then show False\n      using assms x y st by (auto dest: of_int_lessD)\n  qed\n  then have \"inj_on (part_circlepath z r s t) {0..1}\"\n    using assms by (force simp add: part_circlepath_def inj_on_def exp_eq)\n  then show ?thesis\n    by (simp add: arc_def)\nqed\n\nsubsection\\<open>Special case of one complete circle\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> circlepath :: \"[complex, real, real] \\<Rightarrow> complex\"\n  where \"circlepath z r \\<equiv> part_circlepath z r 0 (2*pi)\"\n\nlemma circlepath: \"circlepath z r = (\\<lambda>x. z + r * exp(2 * of_real pi * \\<i> * of_real x))\"\n  by (simp add: circlepath_def part_circlepath_def linepath_def algebra_simps)\n\nlemma pathstart_circlepath [simp]: \"pathstart (circlepath z r) = z + r\"\n  by (simp add: circlepath_def)\n\nlemma pathfinish_circlepath [simp]: \"pathfinish (circlepath z r) = z + r\"\n  by (simp add: circlepath_def) (metis exp_two_pi_i mult.commute)\n\nlemma circlepath_minus: \"circlepath z (-r) x = circlepath z r (x + 1/2)\"\nproof -\n  have \"z + of_real r * exp (2 * pi * \\<i> * (x + 1/2)) =\n        z + of_real r * exp (2 * pi * \\<i> * x + pi * \\<i>)\"\n    by (simp add: divide_simps) (simp add: algebra_simps)\n  also have \"\\<dots> = z - r * exp (2 * pi * \\<i> * x)\"\n    by (simp add: exp_add)\n  finally show ?thesis\n    by (simp add: circlepath path_image_def sphere_def dist_norm)\nqed\n\nlemma circlepath_add1: \"circlepath z r (x+1) = circlepath z r x\"\n  using circlepath_minus [of z r \"x+1/2\"] circlepath_minus [of z \"-r\" x]\n  by (simp add: add.commute)\n\nlemma circlepath_add_half: \"circlepath z r (x + 1/2) = circlepath z r (x - 1/2)\"\n  using circlepath_add1 [of z r \"x-1/2\"]\n  by (simp add: add.commute)\n\nlemma path_image_circlepath_minus_subset:\n     \"path_image (circlepath z (-r)) \\<subseteq> path_image (circlepath z r)\"\nproof -\n  have \"\\<exists>x\\<in>{0..1}. circlepath z r (y + 1/2) = circlepath z r x\"\n    if \"0 \\<le> y\" \"y \\<le> 1\" for y\n  proof (cases \"y \\<le> 1/2\")\n    case False\n    with that show ?thesis\n      by (force simp: circlepath_add_half)\n  qed (use that in force)\n  then show ?thesis\n    by (auto simp add: path_image_def image_def circlepath_minus)\nqed\n\nlemma path_image_circlepath_minus: \"path_image (circlepath z (-r)) = path_image (circlepath z r)\"\n  using path_image_circlepath_minus_subset by fastforce\n\nlemma has_vector_derivative_circlepath [derivative_intros]:\n \"((circlepath z r) has_vector_derivative (2 * pi * \\<i> * r * exp (2 * of_real pi * \\<i> * x)))\n   (at x within X)\"\n  unfolding circlepath_def scaleR_conv_of_real\n  by (rule derivative_eq_intros) (simp add: algebra_simps)\n\nlemma vector_derivative_circlepath:\n  \"vector_derivative (circlepath z r) (at x) =\n    2 * pi * \\<i> * r * exp(2 * of_real pi * \\<i> * x)\"\n  using has_vector_derivative_circlepath vector_derivative_at by blast\n\nlemma vector_derivative_circlepath01:\n    \"\\<lbrakk>0 \\<le> x; x \\<le> 1\\<rbrakk>\n     \\<Longrightarrow> vector_derivative (circlepath z r) (at x within {0..1}) =\n          2 * pi * \\<i> * r * exp(2 * of_real pi * \\<i> * x)\"\n  using has_vector_derivative_circlepath\n  by (auto simp: vector_derivative_at_within_ivl)\n\nlemma valid_path_circlepath [simp]: \"valid_path (circlepath z r)\"\n  by (simp add: circlepath_def)\n\nlemma path_circlepath [simp]: \"path (circlepath z r)\"\n  by (simp add: valid_path_imp_path)\n\nlemma path_image_circlepath_nonneg:\n  assumes \"0 \\<le> r\" shows \"path_image (circlepath z r) = sphere z r\"\nproof -\n  have *: \"x \\<in> (\\<lambda>u. z + (cmod (x - z)) * exp (\\<i> * (of_real u * (of_real pi * 2)))) ` {0..1}\" for x\n  proof (cases \"x = z\")\n    case True then show ?thesis by force\n  next\n    case False\n    define w where \"w = x - z\"\n    then have \"w \\<noteq> 0\" by (simp add: False)\n    have **: \"\\<And>t. \\<lbrakk>Re w = cos t * cmod w; Im w = sin t * cmod w\\<rbrakk> \\<Longrightarrow> w = of_real (cmod w) * exp (\\<i> * t)\"\n      using cis_conv_exp complex_eq_iff by auto\n    obtain t where \"0 \\<le> t\" \"t < 2*pi\" \"Re(w/norm w) = cos t\" \"Im(w/norm w) = sin t\"\n      apply (rule sincos_total_2pi [of \"Re(w/(norm w))\" \"Im(w/(norm w))\"])\n      by (auto simp add: divide_simps \\<open>w \\<noteq> 0\\<close> cmod_power2 [symmetric])\n    then\n    show ?thesis\n      using False ** w_def \\<open>w \\<noteq> 0\\<close>\n      by (rule_tac x=\"t / (2*pi)\" in image_eqI) (auto simp add: field_simps)\n  qed\n  show ?thesis\n    unfolding circlepath path_image_def sphere_def dist_norm\n    by (force simp: assms algebra_simps norm_mult norm_minus_commute intro: *)\nqed\n\nlemma path_image_circlepath [simp]:\n    \"path_image (circlepath z r) = sphere z \\<bar>r\\<bar>\"\n  using path_image_circlepath_minus\n  by (force simp: path_image_circlepath_nonneg abs_if)\n\nlemma has_contour_integral_bound_circlepath_strong:\n      \"\\<lbrakk>(f has_contour_integral i) (circlepath z r);\n        finite k; 0 \\<le> B; 0 < r;\n        \\<And>x. \\<lbrakk>norm(x - z) = r; x \\<notin> k\\<rbrakk> \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n        \\<Longrightarrow> norm i \\<le> B*(2*pi*r)\"\n  unfolding circlepath_def\n  by (auto simp: algebra_simps in_path_image_part_circlepath dest!: has_contour_integral_bound_part_circlepath_strong)\n\nlemma has_contour_integral_bound_circlepath:\n      \"\\<lbrakk>(f has_contour_integral i) (circlepath z r);\n        0 \\<le> B; 0 < r; \\<And>x. norm(x - z) = r \\<Longrightarrow> norm(f x) \\<le> B\\<rbrakk>\n        \\<Longrightarrow> norm i \\<le> B*(2*pi*r)\"\n  by (auto intro: has_contour_integral_bound_circlepath_strong)\n\nlemma contour_integrable_continuous_circlepath:\n    \"continuous_on (path_image (circlepath z r)) f\n     \\<Longrightarrow> f contour_integrable_on (circlepath z r)\"\n  by (simp add: circlepath_def contour_integrable_continuous_part_circlepath)\n\nlemma simple_path_circlepath: \"simple_path(circlepath z r) \\<longleftrightarrow> (r \\<noteq> 0)\"\n  by (simp add: circlepath_def simple_path_part_circlepath)\n\nlemma notin_path_image_circlepath [simp]: \"cmod (w - z) < r \\<Longrightarrow> w \\<notin> path_image (circlepath z r)\"\n  by (simp add: sphere_def dist_norm norm_minus_commute)\n\nlemma contour_integral_circlepath:\n  assumes \"r > 0\"\n  shows \"contour_integral (circlepath z r) (\\<lambda>w. 1 / (w - z)) = 2 * complex_of_real pi * \\<i>\"\nproof (rule contour_integral_unique)\n  show \"((\\<lambda>w. 1 / (w - z)) has_contour_integral 2 * complex_of_real pi * \\<i>) (circlepath z r)\"\n    unfolding has_contour_integral_def using assms has_integral_const_real [of _ 0 1]\n    apply (subst has_integral_cong)\n     apply (simp add: vector_derivative_circlepath01)\n    apply (force simp: circlepath)\n    done\nqed\n\nsubsection\\<open> Uniform convergence of path integral\\<close>\n\ntext\\<open>Uniform convergence when the derivative of the path is bounded, and in particular for the special case of a circle.\\<close>\n\nproposition contour_integral_uniform_limit:\n  assumes ev_fint: \"eventually (\\<lambda>n::'a. (f n) contour_integrable_on \\<gamma>) F\"\n      and ul_f: \"uniform_limit (path_image \\<gamma>) f l F\"\n      and noleB: \"\\<And>t. t \\<in> {0..1} \\<Longrightarrow> norm (vector_derivative \\<gamma> (at t)) \\<le> B\"\n      and \\<gamma>: \"valid_path \\<gamma>\"\n      and [simp]: \"\\<not> trivial_limit F\"\n  shows \"l contour_integrable_on \\<gamma>\" \"((\\<lambda>n. contour_integral \\<gamma> (f n)) \\<longlongrightarrow> contour_integral \\<gamma> l) F\"\nproof -\n  have \"0 \\<le> B\" by (meson noleB [of 0] atLeastAtMost_iff norm_ge_zero order_refl order_trans zero_le_one)\n  { fix e::real\n    assume \"0 < e\"\n    then have \"0 < e / (\\<bar>B\\<bar> + 1)\" by simp\n    then have \"\\<forall>\\<^sub>F n in F. \\<forall>x\\<in>path_image \\<gamma>. cmod (f n x - l x) < e / (\\<bar>B\\<bar> + 1)\"\n      using ul_f [unfolded uniform_limit_iff dist_norm] by auto\n    with ev_fint\n    obtain a where fga: \"\\<And>x. x \\<in> {0..1} \\<Longrightarrow> cmod (f a (\\<gamma> x) - l (\\<gamma> x)) < e / (\\<bar>B\\<bar> + 1)\"\n               and inta: \"(\\<lambda>t. f a (\\<gamma> t) * vector_derivative \\<gamma> (at t)) integrable_on {0..1}\"\n      using eventually_happens [OF eventually_conj]\n      by (fastforce simp: contour_integrable_on path_image_def)\n    have Ble: \"B * e / (\\<bar>B\\<bar> + 1) \\<le> e\"\n      using \\<open>0 \\<le> B\\<close>  \\<open>0 < e\\<close> by (simp add: field_split_simps)\n    have \"\\<exists>h. (\\<forall>x\\<in>{0..1}. cmod (l (\\<gamma> x) * vector_derivative \\<gamma> (at x) - h x) \\<le> e) \\<and> h integrable_on {0..1}\"\n    proof (intro exI conjI ballI)\n      show \"cmod (l (\\<gamma> x) * vector_derivative \\<gamma> (at x) - f a (\\<gamma> x) * vector_derivative \\<gamma> (at x)) \\<le> e\"\n        if \"x \\<in> {0..1}\" for x\n        apply (rule order_trans [OF _ Ble])\n        using noleB [OF that] fga [OF that] \\<open>0 \\<le> B\\<close> \\<open>0 < e\\<close>\n        apply (fastforce simp: mult_ac dest: mult_mono [OF less_imp_le] simp add: norm_mult left_diff_distrib [symmetric] norm_minus_commute divide_simps)\n        done\n    qed (rule inta)\n  }\n  then show lintg: \"l contour_integrable_on \\<gamma>\"\n    unfolding contour_integrable_on by (metis (mono_tags, lifting)integrable_uniform_limit_real)\n  { fix e::real\n    define B' where \"B' = B + 1\"\n    have B': \"B' > 0\" \"B' > B\" using  \\<open>0 \\<le> B\\<close> by (auto simp: B'_def)\n    assume \"0 < e\"\n    then have ev_no': \"\\<forall>\\<^sub>F n in F. \\<forall>x\\<in>path_image \\<gamma>. 2 * cmod (f n x - l x) < e / B'\"\n      using ul_f [unfolded uniform_limit_iff dist_norm, rule_format, of \"e / B'/2\"] B'\n        by (simp add: field_simps)\n    have ie: \"integral {0..1::real} (\\<lambda>x. e/2) < e\" using \\<open>0 < e\\<close> by simp\n    have *: \"cmod (f x (\\<gamma> t) * vector_derivative \\<gamma> (at t) - l (\\<gamma> t) * vector_derivative \\<gamma> (at t)) \\<le> e/2\"\n             if t: \"t\\<in>{0..1}\" and leB': \"2 * cmod (f x (\\<gamma> t) - l (\\<gamma> t)) < e / B'\" for x t\n    proof -\n      have \"2 * cmod (f x (\\<gamma> t) - l (\\<gamma> t)) * cmod (vector_derivative \\<gamma> (at t)) \\<le> e * (B/ B')\"\n        using mult_mono [OF less_imp_le [OF leB'] noleB] B' \\<open>0 < e\\<close> t by auto\n      also have \"\\<dots> < e\"\n        by (simp add: B' \\<open>0 < e\\<close> mult_imp_div_pos_less)\n      finally have \"2 * cmod (f x (\\<gamma> t) - l (\\<gamma> t)) * cmod (vector_derivative \\<gamma> (at t)) < e\" .\n      then show ?thesis\n        by (simp add: left_diff_distrib [symmetric] norm_mult)\n    qed\n    have le_e: \"\\<And>x. \\<lbrakk>\\<forall>xa\\<in>{0..1}. 2 * cmod (f x (\\<gamma> xa) - l (\\<gamma> xa)) < e / B'; f x contour_integrable_on \\<gamma>\\<rbrakk>\n         \\<Longrightarrow> cmod (integral {0..1}\n                    (\\<lambda>u. f x (\\<gamma> u) * vector_derivative \\<gamma> (at u) - l (\\<gamma> u) * vector_derivative \\<gamma> (at u))) < e\"\n      apply (rule le_less_trans [OF integral_norm_bound_integral ie])\n        apply (simp add: lintg integrable_diff contour_integrable_on [symmetric])\n       apply (blast intro: *)+\n      done\n    have \"\\<forall>\\<^sub>F x in F. dist (contour_integral \\<gamma> (f x)) (contour_integral \\<gamma> l) < e\"\n      apply (rule eventually_mono [OF eventually_conj [OF ev_no' ev_fint]])\n      apply (simp add: dist_norm contour_integrable_on path_image_def contour_integral_integral)\n      apply (simp add: lintg integral_diff [symmetric] contour_integrable_on [symmetric] le_e)\n      done\n  }\n  then show \"((\\<lambda>n. contour_integral \\<gamma> (f n)) \\<longlongrightarrow> contour_integral \\<gamma> l) F\"\n    by (rule tendstoI)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> contour_integral_uniform_limit_circlepath:\n  assumes \"\\<forall>\\<^sub>F n::'a in F. (f n) contour_integrable_on (circlepath z r)\"\n      and \"uniform_limit (sphere z r) f l F\"\n      and \"\\<not> trivial_limit F\" \"0 < r\"\n    shows \"l contour_integrable_on (circlepath z r)\"\n          \"((\\<lambda>n. contour_integral (circlepath z r) (f n)) \\<longlongrightarrow> contour_integral (circlepath z r) l) F\"\n  using assms by (auto simp: vector_derivative_circlepath norm_mult intro!: contour_integral_uniform_limit)\n\nend", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Complex_Analysis/Contour_Integration.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7719098370543841}}
{"text": "theory Chapter13_7\nimports \"~~/src/HOL/IMP/Abs_Int2\"\nbegin\n\ntext{*\n\\setcounter{exercise}{15}\n\\exercise\nGive a readable proof that if @{text \"\\<gamma> ::\"} \\noquotes{@{typ[source]\"'a::lattice \\<Rightarrow> 'b::lattice\"}}\nis a monotone function, then @{prop \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"}:\n*}\n\nlemma fixes \\<gamma> :: \"'a::lattice \\<Rightarrow> 'b :: lattice\"\nassumes mono: \"\\<And>x y. x \\<le> y \\<Longrightarrow> \\<gamma> x \\<le> \\<gamma> y\"\nshows \"\\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2) \\<le> \\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2\"\n(* your definition/proof here *)\n\ntext{*\nGive an example of two lattices and a monotone @{text \\<gamma>}\nwhere @{prop\"\\<gamma> a\\<^sub>1 \\<sqinter> \\<gamma> a\\<^sub>2 \\<le> \\<gamma> (a\\<^sub>1 \\<sqinter> a\\<^sub>2)\"} does not hold.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider a simple sign analysis based on this abstract domain:\n*}\n\ndatatype sign = None | Neg | Pos0 | Any\n\nfun \\<gamma> :: \"sign \\<Rightarrow> val set\" where\n\"\\<gamma> None = {}\" |\n\"\\<gamma> Neg = {i. i < 0}\" |\n\"\\<gamma> Pos0 = {i. i \\<ge> 0}\" |\n\"\\<gamma> Any = UNIV\"\n\ntext{*\nDefine inverse analyses for ``@{text\"+\"}'' and ``@{text\"<\"}''\nand prove the required correctness properties:\n*}\n\nfun inv_plus' :: \"sign \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n(* your definition/proof here *)\n\nlemma\n  \"\\<lbrakk> inv_plus' a a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; i1+i2 \\<in> \\<gamma> a \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2' \"\n(* your definition/proof here *)\n\nfun inv_less' :: \"bool \\<Rightarrow> sign \\<Rightarrow> sign \\<Rightarrow> sign * sign\" where\n(* your definition/proof here *)\n\nlemma\n  \"\\<lbrakk> inv_less' bv a1 a2 = (a1',a2');  i1 \\<in> \\<gamma> a1;  i2 \\<in> \\<gamma> a2; (i1<i2) = bv \\<rbrakk>\n  \\<Longrightarrow> i1 \\<in> \\<gamma> a1' \\<and> i2 \\<in> \\<gamma> a2'\"\n(* your definition/proof here *)\n\ntext{*\n\\indent\nFor the ambitious: turn the above fragment into a full-blown abstract interpreter\nby replacing the interval analysis in theory @{theory Abs_Int2}@{text\"_ivl\"}\nby a sign analysis.\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "EduPH", "repo": "concrete-semantics-Sols", "sha": "ab33a5ea3b3752c3cf62468cb5b97d9ad8669be2", "save_path": "github-repos/isabelle/EduPH-concrete-semantics-Sols", "path": "github-repos/isabelle/EduPH-concrete-semantics-Sols/concrete-semantics-Sols-ab33a5ea3b3752c3cf62468cb5b97d9ad8669be2/Chapter13_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7717161041165739}}
{"text": "(*  Title:      Free_Boolean_Algebra.thy\n    Author:     Brian Huffman, Portland State University\n*)\n\nsection \\<open>Free Boolean algebras\\<close>\n\ntheory Free_Boolean_Algebra\nimports Main\nbegin\n\n(*<*)\nnotation\n  bot (\"\\<bottom>\") and\n  top (\"\\<top>\") and\n  inf  (infixl \"\\<sqinter>\" 70) and\n  sup  (infixl \"\\<squnion>\" 65)\n\nlemma sup_conv_inf:\n  fixes x y :: \"'a::boolean_algebra\"\n  shows \"x \\<squnion> y = - (- x \\<sqinter> - y)\"\nby simp\n(*>*)\n\nsubsection \\<open>Free boolean algebra as a set\\<close>\n\ntext \\<open>\n  We start by defining the free boolean algebra over type @{typ 'a} as\n  an inductive set.  Here \\<open>i :: 'a\\<close> represents a variable;\n  \\<open>A :: 'a set\\<close> represents a valuation, assigning a truth\n  value to each variable; and \\<open>S :: 'a set set\\<close> represents a\n  formula, as the set of valuations that make the formula true.  The\n  set \\<open>fba\\<close> contains representatives of formulas built from\n  finite combinations of variables with negation and conjunction.\n\\<close>\n\ninductive_set\n  fba :: \"'a set set set\"\nwhere\n  var: \"{A. i \\<in> A} \\<in> fba\"\n| Compl: \"S \\<in> fba \\<Longrightarrow> - S \\<in> fba\"\n| inter: \"S \\<in> fba \\<Longrightarrow> T \\<in> fba \\<Longrightarrow> S \\<inter> T \\<in> fba\"\n\nlemma fba_Diff: \"S \\<in> fba \\<Longrightarrow> T \\<in> fba \\<Longrightarrow> S - T \\<in> fba\"\nunfolding Diff_eq by (intro fba.inter fba.Compl)\n\nlemma fba_union: \"S \\<in> fba \\<Longrightarrow> T \\<in> fba \\<Longrightarrow> S \\<union> T \\<in> fba\"\nproof -\n  assume \"S \\<in> fba\" and \"T \\<in> fba\"\n  hence \"- (- S \\<inter> - T) \\<in> fba\" by (intro fba.intros)\n  thus \"S \\<union> T \\<in> fba\" by simp\nqed\n\nlemma fba_empty: \"({} :: 'a set set) \\<in> fba\"\nproof -\n  obtain S :: \"'a set set\" where \"S \\<in> fba\"\n    by (fast intro: fba.var)\n  hence \"S \\<inter> - S \\<in> fba\"\n    by (intro fba.intros)\n  thus ?thesis by simp\nqed\n\nlemma fba_UNIV: \"(UNIV :: 'a set set) \\<in> fba\"\nproof -\n  have \"- {} \\<in> fba\" using fba_empty by (rule fba.Compl)\n  thus \"UNIV \\<in> fba\" by simp\nqed\n\n\nsubsection \\<open>Free boolean algebra as a type\\<close>\n\ntext \\<open>\n  The next step is to use \\<open>typedef\\<close> to define a type isomorphic\n  to the set @{const fba}.  We also define a constructor \\<open>var\\<close>\n  that corresponds with the similarly-named introduction rule for\n  @{const fba}.\n\\<close>\n\ntypedef 'a formula = \"fba :: 'a set set set\"\n  by (auto intro: fba_empty)\n\ndefinition var :: \"'a \\<Rightarrow> 'a formula\"\nwhere \"var i = Abs_formula {A. i \\<in> A}\"\n\nlemma Rep_formula_var: \"Rep_formula (var i) = {A. i \\<in> A}\"\nunfolding var_def using fba.var by (rule Abs_formula_inverse)\n\ntext \\<open>\n  \\medskip\n  Now we make type @{typ \"'a formula\"} into a Boolean algebra.  This\n  involves defining the various operations (ordering relations, binary\n  infimum and supremum, complement, difference, top and bottom\n  elements) and proving that they satisfy the appropriate laws.\n\\<close>\n\ninstantiation formula :: (type) boolean_algebra\nbegin\n\ndefinition\n  \"x \\<sqinter> y = Abs_formula (Rep_formula x \\<inter> Rep_formula y)\"\n\ndefinition\n  \"x \\<squnion> y = Abs_formula (Rep_formula x \\<union> Rep_formula y)\"\n\ndefinition\n  \"\\<top> = Abs_formula UNIV\"\n\ndefinition\n  \"\\<bottom> = Abs_formula {}\"\n\ndefinition\n  \"x \\<le> y \\<longleftrightarrow> Rep_formula x \\<subseteq> Rep_formula y\"\n\ndefinition\n  \"x < y \\<longleftrightarrow> Rep_formula x \\<subset> Rep_formula y\"\n\ndefinition\n  \"- x = Abs_formula (- Rep_formula x)\"\n\ndefinition\n  \"x - y = Abs_formula (Rep_formula x - Rep_formula y)\"\n\nlemma Rep_formula_inf:\n  \"Rep_formula (x \\<sqinter> y) = Rep_formula x \\<inter> Rep_formula y\"\nunfolding inf_formula_def\nby (intro Abs_formula_inverse fba.inter Rep_formula)\n\nlemma Rep_formula_sup:\n  \"Rep_formula (x \\<squnion> y) = Rep_formula x \\<union> Rep_formula y\"\nunfolding sup_formula_def\nby (intro Abs_formula_inverse fba_union Rep_formula)\n\n\n\nlemma Rep_formula_bot: \"Rep_formula \\<bottom> = {}\"\nunfolding bot_formula_def by (intro Abs_formula_inverse fba_empty)\n\nlemma Rep_formula_compl: \"Rep_formula (- x) = - Rep_formula x\"\nunfolding uminus_formula_def\nby (intro Abs_formula_inverse fba.Compl Rep_formula)\n\nlemma Rep_formula_diff:\n  \"Rep_formula (x - y) = Rep_formula x - Rep_formula y\"\nunfolding minus_formula_def\nby (intro Abs_formula_inverse fba_Diff Rep_formula)\n\nlemmas eq_formula_iff = Rep_formula_inject [symmetric]\n\nlemmas Rep_formula_simps =\n  less_eq_formula_def less_formula_def eq_formula_iff\n  Rep_formula_sup Rep_formula_inf Rep_formula_top Rep_formula_bot\n  Rep_formula_compl Rep_formula_diff Rep_formula_var\n\ninstance proof\nqed (unfold Rep_formula_simps, auto)\n\nend\n\ntext \\<open>\n  \\medskip\n  The laws of a Boolean algebra do not require the top and bottom\n  elements to be distinct, so the following rules must be proved\n  separately:\n\\<close>\n\nlemma bot_neq_top_formula [simp]: \"(\\<bottom> :: 'a formula) \\<noteq> \\<top>\"\nunfolding Rep_formula_simps by auto\n\nlemma top_neq_bot_formula [simp]: \"(\\<top> :: 'a formula) \\<noteq> \\<bottom>\"\nunfolding Rep_formula_simps by auto\n\ntext \\<open>\n  \\medskip\n  Here we prove an essential property of a free Boolean algebra:\n  all generators are independent.\n\\<close>\n\nlemma var_le_var_simps [simp]:\n  \"var i \\<le> var j \\<longleftrightarrow> i = j\"\n  \"\\<not> var i \\<le> - var j\"\n  \"\\<not> - var i \\<le> var j\"\nunfolding Rep_formula_simps by fast+\n\nlemma var_eq_var_simps [simp]:\n  \"var i = var j \\<longleftrightarrow> i = j\"\n  \"var i \\<noteq> - var j\"\n  \"- var i \\<noteq> var j\"\nunfolding Rep_formula_simps set_eq_subset by fast+\n\ntext \\<open>\n  \\medskip\n  We conclude this section by proving an induction principle for\n  formulas.  It mirrors the definition of the inductive set \\<open>fba\\<close>, with cases for variables, complements, and conjunction.\n\\<close>\n\nlemma formula_induct [case_names var compl inf, induct type: formula]:\n  fixes P :: \"'a formula \\<Rightarrow> bool\"\n  assumes 1: \"\\<And>i. P (var i)\"\n  assumes 2: \"\\<And>x. P x \\<Longrightarrow> P (- x)\"\n  assumes 3: \"\\<And>x y. P x \\<Longrightarrow> P y \\<Longrightarrow> P (x \\<sqinter> y)\"\n  shows \"P x\"\nproof (induct x rule: Abs_formula_induct)\n  fix y :: \"'a set set\"\n  assume \"y \\<in> fba\" thus \"P (Abs_formula y)\"\n  proof (induct rule: fba.induct)\n    case (var i)\n    have \"P (var i)\" by (rule 1)\n    thus ?case unfolding var_def .\n  next\n    case (Compl S)\n    from \\<open>P (Abs_formula S)\\<close> have \"P (- Abs_formula S)\" by (rule 2)\n    with \\<open>S \\<in> fba\\<close> show ?case\n      unfolding uminus_formula_def by (simp add: Abs_formula_inverse)\n  next\n    case (inter S T)\n    from \\<open>P (Abs_formula S)\\<close> and \\<open>P (Abs_formula T)\\<close>\n    have \"P (Abs_formula S \\<sqinter> Abs_formula T)\" by (rule 3)\n    with \\<open>S \\<in> fba\\<close> and \\<open>T \\<in> fba\\<close> show ?case\n      unfolding inf_formula_def by (simp add: Abs_formula_inverse)\n  qed\nqed\n\n\nsubsection \\<open>If-then-else for Boolean algebras\\<close>\n\ntext \\<open>\n  This is a generic if-then-else operator for arbitrary Boolean\n  algebras.\n\\<close>\n\ndefinition\n  ifte :: \"'a::boolean_algebra \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"ifte a x y = (a \\<sqinter> x) \\<squnion> (- a \\<sqinter> y)\"\n\nlemma ifte_top [simp]: \"ifte \\<top> x y = x\"\nunfolding ifte_def by simp\n\nlemma ifte_bot [simp]: \"ifte \\<bottom> x y = y\"\nunfolding ifte_def by simp\n\nlemma ifte_same: \"ifte a x x = x\"\nunfolding ifte_def\nby (simp add: inf_sup_distrib2 [symmetric] sup_compl_top)\n\nlemma compl_ifte: \"- ifte a x y = ifte a (- x) (- y)\"\nunfolding ifte_def\napply (rule order_antisym)\napply (simp add: inf_sup_distrib1 inf_sup_distrib2 compl_inf_bot)\napply (simp add: sup_inf_distrib1 sup_inf_distrib2 sup_compl_top)\napply (simp add: le_infI1 le_infI2 le_supI1 le_supI2)\napply (simp add: le_infI1 le_infI2 le_supI1 le_supI2)\ndone\n\nlemma inf_ifte_distrib:\n  \"ifte x a b \\<sqinter> ifte x c d = ifte x (a \\<sqinter> c) (b \\<sqinter> d)\"\nunfolding ifte_def\napply (simp add: inf_sup_distrib1 inf_sup_distrib2)\napply (simp add: inf_sup_aci inf_compl_bot)\ndone\n\nlemma ifte_ifte_distrib:\n  \"ifte x (ifte y a b) (ifte y c d) = ifte y (ifte x a c) (ifte x b d)\"\nunfolding ifte_def [of x] sup_conv_inf\nby (simp only: compl_ifte [symmetric] inf_ifte_distrib [symmetric] ifte_same)\n\n\nsubsection \\<open>Formulas over a set of generators\\<close>\n\ntext \\<open>\n  The set \\<open>formulas S\\<close> consists of those formulas that only\n  depend on variables in the set \\<open>S\\<close>.  It is analogous to the\n  @{const lists} operator for the list datatype.\n\\<close>\n\ndefinition\n  formulas :: \"'a set \\<Rightarrow> 'a formula set\"\nwhere\n  \"formulas S =\n    {x. \\<forall>A B. (\\<forall>i\\<in>S. i \\<in> A \\<longleftrightarrow> i \\<in> B) \\<longrightarrow>\n      A \\<in> Rep_formula x \\<longleftrightarrow> B \\<in> Rep_formula x}\"\n\nlemma formulasI:\n  assumes \"\\<And>A B. \\<forall>i\\<in>S. i \\<in> A \\<longleftrightarrow> i \\<in> B\n    \\<Longrightarrow> A \\<in> Rep_formula x \\<longleftrightarrow> B \\<in> Rep_formula x\"\n  shows \"x \\<in> formulas S\"\nusing assms unfolding formulas_def by simp\n\nlemma formulasD:\n  assumes \"x \\<in> formulas S\"\n  assumes \"\\<forall>i\\<in>S. i \\<in> A \\<longleftrightarrow> i \\<in> B\"\n  shows \"A \\<in> Rep_formula x \\<longleftrightarrow> B \\<in> Rep_formula x\"\nusing assms unfolding formulas_def by simp\n\nlemma formulas_mono: \"S \\<subseteq> T \\<Longrightarrow> formulas S \\<subseteq> formulas T\"\nby (fast intro!: formulasI elim!: formulasD)\n\nlemma formulas_insert: \"x \\<in> formulas S \\<Longrightarrow> x \\<in> formulas (insert a S)\"\nunfolding formulas_def by simp\n\nlemma formulas_var: \"i \\<in> S \\<Longrightarrow> var i \\<in> formulas S\"\nunfolding formulas_def by (simp add: Rep_formula_simps)\n\nlemma formulas_var_iff: \"var i \\<in> formulas S \\<longleftrightarrow> i \\<in> S\"\nunfolding formulas_def by (simp add: Rep_formula_simps, fast)\n\nlemma formulas_bot: \"\\<bottom> \\<in> formulas S\"\nunfolding formulas_def by (simp add: Rep_formula_simps)\n\n\n\nlemma formulas_compl: \"x \\<in> formulas S \\<Longrightarrow> - x \\<in> formulas S\"\nunfolding formulas_def by (simp add: Rep_formula_simps)\n\nlemma formulas_inf:\n  \"x \\<in> formulas S \\<Longrightarrow> y \\<in> formulas S \\<Longrightarrow> x \\<sqinter> y \\<in> formulas S\"\nunfolding formulas_def by (auto simp add: Rep_formula_simps)\n\nlemma formulas_sup:\n  \"x \\<in> formulas S \\<Longrightarrow> y \\<in> formulas S \\<Longrightarrow> x \\<squnion> y \\<in> formulas S\"\nunfolding formulas_def by (auto simp add: Rep_formula_simps)\n\nlemma formulas_diff:\n  \"x \\<in> formulas S \\<Longrightarrow> y \\<in> formulas S \\<Longrightarrow> x - y \\<in> formulas S\"\nunfolding formulas_def by (auto simp add: Rep_formula_simps)\n\nlemma formulas_ifte:\n  \"a \\<in> formulas S \\<Longrightarrow> x \\<in> formulas S \\<Longrightarrow> y \\<in> formulas S \\<Longrightarrow>\n    ifte a x y \\<in> formulas S\"\nunfolding ifte_def\nby (intro formulas_sup formulas_inf formulas_compl)\n\nlemmas formulas_intros =\n  formulas_var formulas_bot formulas_top formulas_compl\n  formulas_inf formulas_sup formulas_diff formulas_ifte\n\n\nsubsection \\<open>Injectivity of if-then-else\\<close>\n\ntext \\<open>\n  The if-then-else operator is injective in some limited\n  circumstances: when the scrutinee is a variable that is not\n  mentioned in either branch.\n\\<close>\n\nlemma ifte_inject:\n  assumes \"ifte (var i) x y = ifte (var i) x' y'\" \n  assumes \"i \\<notin> S\"\n  assumes \"x \\<in> formulas S\" and \"x' \\<in> formulas S\"\n  assumes \"y \\<in> formulas S\" and \"y' \\<in> formulas S\"\n  shows \"x = x' \\<and> y = y'\"\nproof\n  have 1: \"\\<And>A. i \\<in> A \\<Longrightarrow> A \\<in> Rep_formula x \\<longleftrightarrow> A \\<in> Rep_formula x'\"\n    using assms(1)\n    by (simp add: Rep_formula_simps ifte_def set_eq_iff, fast)\n  have 2: \"\\<And>A. i \\<notin> A \\<Longrightarrow> A \\<in> Rep_formula y \\<longleftrightarrow> A \\<in> Rep_formula y'\"\n    using assms(1)\n    by (simp add: Rep_formula_simps ifte_def set_eq_iff, fast)\n\n  show \"x = x'\"\n  unfolding Rep_formula_simps\n  proof (rule set_eqI)\n    fix A\n    have \"A \\<in> Rep_formula x \\<longleftrightarrow> insert i A \\<in> Rep_formula x\"\n      using \\<open>x \\<in> formulas S\\<close> by (rule formulasD, force simp add: \\<open>i \\<notin> S\\<close>)\n    also have \"\\<dots> \\<longleftrightarrow> insert i A \\<in> Rep_formula x'\"\n      by (rule 1, simp)\n    also have \"\\<dots> \\<longleftrightarrow> A \\<in> Rep_formula x'\"\n      using \\<open>x' \\<in> formulas S\\<close> by (rule formulasD, force simp add: \\<open>i \\<notin> S\\<close>)\n    finally show \"A \\<in> Rep_formula x \\<longleftrightarrow> A \\<in> Rep_formula x'\" .\n  qed\n  show  \"y = y'\"\n  unfolding Rep_formula_simps\n  proof (rule set_eqI)\n    fix A\n    have \"A \\<in> Rep_formula y \\<longleftrightarrow> A - {i} \\<in> Rep_formula y\"\n      using \\<open>y \\<in> formulas S\\<close> by (rule formulasD, force simp add: \\<open>i \\<notin> S\\<close>)\n    also have \"\\<dots> \\<longleftrightarrow> A - {i} \\<in> Rep_formula y'\"\n      by (rule 2, simp)\n    also have \"\\<dots> \\<longleftrightarrow> A \\<in> Rep_formula y'\"\n      using \\<open>y' \\<in> formulas S\\<close> by (rule formulasD, force simp add: \\<open>i \\<notin> S\\<close>)\n    finally show \"A \\<in> Rep_formula y \\<longleftrightarrow> A \\<in> Rep_formula y'\" .\n  qed\nqed\n\n\nsubsection \\<open>Specification of homomorphism operator\\<close>\n\ntext \\<open>\n  Our goal is to define a homomorphism operator \\<open>hom\\<close> such that\n  for any function \\<open>f\\<close>, \\<open>hom f\\<close> is the unique Boolean\n  algebra homomorphism satisfying \\<open>hom f (var i) = f i\\<close>\n  for all \\<open>i\\<close>.\n\n  Instead of defining \\<open>hom\\<close> directly, we will follow the\n  approach used to define Isabelle's \\<open>fold\\<close> operator for finite\n  sets.  First we define the graph of the \\<open>hom\\<close> function as a\n  relation; later we will define the \\<open>hom\\<close> function itself using\n  definite choice.\n\n  The \\<open>hom_graph\\<close> relation is defined inductively, with\n  introduction rules based on the if-then-else normal form of Boolean\n  formulas.  The relation is also indexed by an extra set parameter\n  \\<open>S\\<close>, to ensure that branches of each if-then-else do not use\n  the same variable again.\n\\<close>\n\ninductive\n  hom_graph ::\n    \"('a \\<Rightarrow> 'b::boolean_algebra) \\<Rightarrow> 'a set \\<Rightarrow> 'a formula \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  for f :: \"'a \\<Rightarrow> 'b::boolean_algebra\"\nwhere\n  bot: \"hom_graph f {} bot bot\"\n| top: \"hom_graph f {} top top\"\n| ifte: \"i \\<notin> S \\<Longrightarrow> hom_graph f S x a \\<Longrightarrow> hom_graph f S y b \\<Longrightarrow>\n  hom_graph f (insert i S) (ifte (var i) x y) (ifte (f i) a b)\"\n\ntext \\<open>\n  \\medskip\n  The next two lemmas establish a stronger elimination rule for\n  assumptions of the form @{term \"hom_graph f (insert i S) x a\"}.\n  Essentially, they say that we can arrange the top-level if-then-else\n  to use the variable of our choice.  The proof makes use of the\n  distributive properties of if-then-else.\n\\<close>\n\nlemma hom_graph_dest:\n  \"hom_graph f S x a \\<Longrightarrow> k \\<in> S \\<Longrightarrow> \\<exists>y z b c.\n    x = ifte (var k) y z \\<and> a = ifte (f k) b c \\<and>\n    hom_graph f (S - {k}) y b \\<and> hom_graph f (S - {k}) z c\"\nproof (induct set: hom_graph)\n  case (ifte i S x a y b) show ?case\n  proof (cases \"i = k\")\n    assume \"i = k\" with ifte(1,2,4) show ?case by auto\n  next\n    assume \"i \\<noteq> k\"\n    with \\<open>k \\<in> insert i S\\<close> have k: \"k \\<in> S\" by simp\n    have *: \"insert i S - {k} = insert i (S - {k})\"\n      using \\<open>i \\<noteq> k\\<close> by (simp add: insert_Diff_if)\n    have **: \"i \\<notin> S - {k}\" using \\<open>i \\<notin> S\\<close> by simp\n    from ifte(1) ifte(3) [OF k] ifte(5) [OF k]\n    show ?case\n      unfolding *\n      apply clarify\n      apply (simp only: ifte_ifte_distrib [of \"var i\"])\n      apply (simp only: ifte_ifte_distrib [of \"f i\"])\n      apply (fast intro: hom_graph.ifte [OF **])\n      done\n  qed\nqed simp_all\n\nlemma hom_graph_insert_elim:\n  assumes \"hom_graph f (insert i S) x a\" and \"i \\<notin> S\"\n  obtains y z b c\n  where \"x = ifte (var i) y z\"\n    and \"a = ifte (f i) b c\"\n    and \"hom_graph f S y b\"\n    and \"hom_graph f S z c\"\nusing hom_graph_dest [OF assms(1) insertI1]\nby (clarify, simp add: assms(2))\n\ntext \\<open>\n  \\medskip\n  Now we prove the first uniqueness property of the @{const hom_graph}\n  relation.  This version of uniqueness says that for any particular\n  value of \\<open>S\\<close>, the relation @{term \"hom_graph f S\"} maps each\n  \\<open>x\\<close> to at most one \\<open>a\\<close>.  The proof uses the\n  injectiveness of if-then-else, which we proved earlier.\n\\<close>\n\nlemma hom_graph_imp_formulas:\n  \"hom_graph f S x a \\<Longrightarrow> x \\<in> formulas S\"\nby (induct set: hom_graph, simp_all add: formulas_intros formulas_insert)\n\nlemma hom_graph_unique:\n  \"hom_graph f S x a \\<Longrightarrow> hom_graph f S x a' \\<Longrightarrow> a = a'\"\nproof (induct arbitrary: a' set: hom_graph)\n  case (ifte i S y b z c a')\n  from ifte(6,1) obtain y' z' b' c'\n    where 1: \"ifte (var i) y z = ifte (var i) y' z'\"\n      and 2: \"a' = ifte (f i) b' c'\"\n      and 3: \"hom_graph f S y' b'\"\n      and 4: \"hom_graph f S z' c'\"\n    by (rule hom_graph_insert_elim)\n  from 1 3 4 ifte(1,2,4) have \"y = y' \\<and> z = z'\"\n    by (intro ifte_inject hom_graph_imp_formulas)\n  with 2 3 4 ifte(3,5) show \"ifte (f i) b c = a'\"\n    by simp\nqed (erule hom_graph.cases, simp_all)+\n\ntext \\<open>\n  \\medskip\n  The next few lemmas will help to establish a stronger version of the\n  uniqueness property of @{const hom_graph}.  They show that the @{const\n  hom_graph} relation is preserved if we replace \\<open>S\\<close> with a\n  larger finite set.\n\\<close>\n\nlemma hom_graph_insert:\n  assumes \"hom_graph f S x a\"\n  shows \"hom_graph f (insert i S) x a\"\nproof (cases \"i \\<in> S\")\n  assume \"i \\<in> S\" with assms show ?thesis by (simp add: insert_absorb)\nnext\n  assume \"i \\<notin> S\"\n  hence \"hom_graph f (insert i S) (ifte (var i) x x) (ifte (f i) a a)\"\n    by (intro hom_graph.ifte assms)\n  thus \"hom_graph f (insert i S) x a\"\n    by (simp only: ifte_same)\nqed\n\nlemma hom_graph_finite_superset:\n  assumes \"hom_graph f S x a\" and \"finite T\" and \"S \\<subseteq> T\"\n  shows \"hom_graph f T x a\"\nproof -\n  from \\<open>finite T\\<close> have \"hom_graph f (S \\<union> T) x a\"\n    by (induct set: finite, simp add: assms, simp add: hom_graph_insert)\n  with \\<open>S \\<subseteq> T\\<close> show \"hom_graph f T x a\"\n    by (simp only: subset_Un_eq)\nqed\n\nlemma hom_graph_imp_finite:\n  \"hom_graph f S x a \\<Longrightarrow> finite S\"\nby (induct set: hom_graph) simp_all\n\ntext \\<open>\n  \\medskip\n  This stronger uniqueness property says that @{term \"hom_graph f\"}\n  maps each \\<open>x\\<close> to at most one \\<open>a\\<close>, even for\n  \\emph{different} values of the set parameter.\n\\<close>\n\nlemma hom_graph_unique':\n  assumes \"hom_graph f S x a\" and \"hom_graph f T x a'\"\n  shows \"a = a'\"\nproof (rule hom_graph_unique)\n  have fin: \"finite (S \\<union> T)\"\n    using assms by (intro finite_UnI hom_graph_imp_finite)\n  show \"hom_graph f (S \\<union> T) x a\"\n    using assms(1) fin Un_upper1 by (rule hom_graph_finite_superset)\n  show \"hom_graph f (S \\<union> T) x a'\"\n    using assms(2) fin Un_upper2 by (rule hom_graph_finite_superset)\nqed\n\ntext \\<open>\n  \\medskip\n  Finally, these last few lemmas establish that the @{term \"hom_graph\n  f\"} relation is total: every \\<open>x\\<close> is mapped to some \\<open>a\\<close>.\n\\<close>\n\nlemma hom_graph_var: \"hom_graph f {i} (var i) (f i)\"\nproof -\n  have \"hom_graph f {i} (ifte (var i) top bot) (ifte (f i) top bot)\"\n    by (simp add: hom_graph.intros)\n  thus \"hom_graph f {i} (var i) (f i)\"\n    unfolding ifte_def by simp\nqed\n\nlemma hom_graph_compl:\n  \"hom_graph f S x a \\<Longrightarrow> hom_graph f S (- x) (- a)\"\nby (induct set: hom_graph, simp_all add: hom_graph.intros compl_ifte)\n\nlemma hom_graph_inf:\n  \"hom_graph f S x a \\<Longrightarrow> hom_graph f S y b \\<Longrightarrow>\n   hom_graph f S (x \\<sqinter> y) (a \\<sqinter> b)\"\n apply (induct arbitrary: y b set: hom_graph)\n   apply (simp add: hom_graph.bot)\n  apply simp\n apply (erule (1) hom_graph_insert_elim)\n apply (auto simp add: inf_ifte_distrib hom_graph.ifte)\ndone\n\nlemma hom_graph_union_inf:\n  assumes \"hom_graph f S x a\" and \"hom_graph f T y b\"\n  shows \"hom_graph f (S \\<union> T) (x \\<sqinter> y) (a \\<sqinter> b)\"\nproof (rule hom_graph_inf)\n  have fin: \"finite (S \\<union> T)\"\n    using assms by (intro finite_UnI hom_graph_imp_finite)\n  show \"hom_graph f (S \\<union> T) x a\"\n    using assms(1) fin Un_upper1 by (rule hom_graph_finite_superset)\n  show \"hom_graph f (S \\<union> T) y b\"\n    using assms(2) fin Un_upper2 by (rule hom_graph_finite_superset)\nqed\n\nlemma hom_graph_exists: \"\\<exists>a S. hom_graph f S x a\"\nby (induct x)\n   (auto intro: hom_graph_var hom_graph_compl hom_graph_union_inf)\n\n\nsubsection \\<open>Homomorphisms into other boolean algebras\\<close>\n\ntext \\<open>\n  Now that we have proved the necessary existence and uniqueness\n  properties of @{const hom_graph}, we can define the function \\<open>hom\\<close> using definite choice.\n\\<close>\n\ndefinition\n  hom :: \"('a \\<Rightarrow> 'b::boolean_algebra) \\<Rightarrow> 'a formula \\<Rightarrow> 'b\"\nwhere\n  \"hom f x = (THE a. \\<exists>S. hom_graph f S x a)\"\n\nlemma hom_graph_hom: \"\\<exists>S. hom_graph f S x (hom f x)\"\nunfolding hom_def\napply (rule theI')\napply (rule ex_ex1I)\napply (rule hom_graph_exists)\napply (fast elim: hom_graph_unique')\ndone\n\nlemma hom_equality:\n  \"hom_graph f S x a \\<Longrightarrow> hom f x = a\"\nunfolding hom_def\napply (rule the_equality)\napply (erule exI)\napply (erule exE)\napply (erule (1) hom_graph_unique')\ndone\n\ntext \\<open>\n  \\medskip\n  The @{const hom} function correctly implements its specification:\n\\<close>\n\nlemma hom_var [simp]: \"hom f (var i) = f i\"\nby (rule hom_equality, rule hom_graph_var)\n\nlemma hom_bot [simp]: \"hom f \\<bottom> = \\<bottom>\"\nby (rule hom_equality, rule hom_graph.bot)\n\nlemma hom_top [simp]: \"hom f \\<top> = \\<top>\"\nby (rule hom_equality, rule hom_graph.top)\n\nlemma hom_compl [simp]: \"hom f (- x) = - hom f x\"\nproof -\n  obtain S where \"hom_graph f S x (hom f x)\"\n    using hom_graph_hom ..\n  hence \"hom_graph f S (- x) (- hom f x)\"\n    by (rule hom_graph_compl)\n  thus \"hom f (- x) = - hom f x\"\n    by (rule hom_equality)\nqed\n\nlemma hom_inf [simp]: \"hom f (x \\<sqinter> y) = hom f x \\<sqinter> hom f y\"\nproof -\n  obtain S where S: \"hom_graph f S x (hom f x)\"\n    using hom_graph_hom ..\n  obtain T where T: \"hom_graph f T y (hom f y)\"\n    using hom_graph_hom ..\n  have \"hom_graph f (S \\<union> T) (x \\<sqinter> y) (hom f x \\<sqinter> hom f y)\"\n    using S T by (rule hom_graph_union_inf)\n  thus ?thesis by (rule hom_equality)\nqed\n\nlemma hom_sup [simp]: \"hom f (x \\<squnion> y) = hom f x \\<squnion> hom f y\"\nunfolding sup_conv_inf by (simp only: hom_compl hom_inf)\n\nlemma hom_diff [simp]: \"hom f (x - y) = hom f x - hom f y\"\nunfolding diff_eq by (simp only: hom_compl hom_inf)\n\nlemma hom_ifte [simp]:\n  \"hom f (ifte x y z) = ifte (hom f x) (hom f y) (hom f z)\"\nunfolding ifte_def by (simp only: hom_compl hom_inf hom_sup)\n\nlemmas hom_simps =\n  hom_var hom_bot hom_top hom_compl\n  hom_inf hom_sup hom_diff hom_ifte\n\ntext \\<open>\n  \\medskip\n  The type @{typ \"'a formula\"} can be viewed as a monad, with @{const\n  var} as the unit, and @{const hom} as the bind operator.  We can\n  prove the standard monad laws with simple proofs by induction.\n\\<close>\n\nlemma hom_var_eq_id: \"hom var x = x\"\nby (induct x) simp_all\n\nlemma hom_hom: \"hom f (hom g x) = hom (\\<lambda>i. hom f (g i)) x\"\nby (induct x) simp_all\n\n\nsubsection \\<open>Map operation on Boolean formulas\\<close>\n\ntext \\<open>\n  We can define a map functional in terms of @{const hom} and @{const\n  var}.  The properties of \\<open>fmap\\<close> follow directly from the\n  lemmas we have already proved about @{const hom}.\n\\<close>\n\ndefinition\n  fmap :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a formula \\<Rightarrow> 'b formula\"\nwhere\n  \"fmap f = hom (\\<lambda>i. var (f i))\"\n\nlemma fmap_var [simp]: \"fmap f (var i) = var (f i)\"\nunfolding fmap_def by simp\n\nlemma fmap_bot [simp]: \"fmap f \\<bottom> = \\<bottom>\"\nunfolding fmap_def by simp\n\nlemma fmap_top [simp]: \"fmap f \\<top> = \\<top>\"\nunfolding fmap_def by simp\n\nlemma fmap_compl [simp]: \"fmap f (- x) = - fmap f x\"\nunfolding fmap_def by simp\n\nlemma fmap_inf [simp]: \"fmap f (x \\<sqinter> y) = fmap f x \\<sqinter> fmap f y\"\nunfolding fmap_def by simp\n\nlemma fmap_sup [simp]: \"fmap f (x \\<squnion> y) = fmap f x \\<squnion> fmap f y\"\nunfolding fmap_def by simp\n\nlemma fmap_diff [simp]: \"fmap f (x - y) = fmap f x - fmap f y\"\nunfolding fmap_def by simp\n\nlemma fmap_ifte [simp]:\n  \"fmap f (ifte x y z) = ifte (fmap f x) (fmap f y) (fmap f z)\"\nunfolding fmap_def by simp\n\nlemmas fmap_simps =\n  fmap_var fmap_bot fmap_top fmap_compl\n  fmap_inf fmap_sup fmap_diff fmap_ifte\n\ntext \\<open>\n  \\medskip\n  The map functional satisfies the functor laws: it preserves identity\n  and function composition.\n\\<close>\n\nlemma fmap_ident: \"fmap (\\<lambda>i. i) x = x\"\nby (induct x) simp_all\n\nlemma fmap_fmap: \"fmap f (fmap g x) = fmap (f \\<circ> g) x\"\nby (induct x) simp_all\n\n\nsubsection \\<open>Hiding lattice syntax\\<close>\n\ntext \\<open>\n  The following command hides the lattice syntax, to avoid potential\n  conflicts with other theories that import this one.  To re-enable\n  the syntax, users should import theory \\<open>Lattice_Syntax\\<close> from\n  the Isabelle library.\n\\<close>\n\nno_notation\n  top (\"\\<top>\") and\n  bot (\"\\<bottom>\") and\n  inf  (infixl \"\\<sqinter>\" 70) and\n  sup  (infixl \"\\<squnion>\" 65)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Free-Boolean-Algebra/Free_Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8596637469145054, "lm_q1q2_score": 0.7717160960476143}}
{"text": "theory Inductive_Demo\nimports Main\nbegin\n\nsubsection \"Inductive definition of the even numbers\"\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nthm ev0 evSS\nthm ev.intros\n\ntext \\<open>Using the introduction rules:\\<close>\n\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\n\ndone\n\nthm evSS[OF evSS[OF ev0]]\n\ntext \\<open>A recursive definition of evenness:\\<close>\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\ntext \\<open>A simple example of rule induction:\\<close>\n\nlemma \"ev n \\<Longrightarrow> evn n\"\napply(induction rule: ev.induct)\n\ndone\n\ntext \\<open>An induction on the computation of evn:\\<close>\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\n\ndone\n\ntext \\<open>No problem with termination because the premises are always smaller\nthan the conclusion:\\<close>\n\ndeclare ev.intros[simp,intro]\n\ntext \\<open>A shorter proof:\\<close>\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\napply(simp_all)\ndone\n\ntext \\<open>The power of arith:\\<close>\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\napply(induction rule: ev.induct)\n apply simp\napply arith\ndone\n\n\nsubsection \"Inductive definition of the reflexive transitive closure\"\n\ninductive\n  star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nfor r where\nrefl:  \"star r x x\" |\nstep:  \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans:\n  \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\napply(induction rule: star.induct)\napply(assumption)\napply(rename_tac u x y)\n\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Inductive_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657176, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7715717959557412}}
{"text": "(*  Title:      HOL/Complete_Lattices.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Markus Wenzel\n    Author:     Florian Haftmann\n    Author:     Viorel Preoteasa (Complete Distributive Lattices)     \n*)\n\nsection \\<open>Complete lattices\\<close>\n\ntheory Complete_Lattices\n  imports Fun\nbegin\n\nsubsection \\<open>Syntactic infimum and supremum operations\\<close>\n\nclass Inf =\n  fixes Inf :: \"'a set \\<Rightarrow> 'a\"  (\"\\<Sqinter>\")\n\nclass Sup =\n  fixes Sup :: \"'a set \\<Rightarrow> 'a\"  (\"\\<Squnion>\")\n\nsyntax\n  \"_INF1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3INF _./ _)\" [0, 10] 10)\n  \"_INF\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3INF _\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_SUP1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3SUP _./ _)\" [0, 10] 10)\n  \"_SUP\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3SUP _\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax\n  \"_INF1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3\\<Sqinter>_./ _)\" [0, 10] 10)\n  \"_INF\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3\\<Sqinter>_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_SUP1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3\\<Squnion>_./ _)\" [0, 10] 10)\n  \"_SUP\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3\\<Squnion>_\\<in>_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<Sqinter>x y. f\"   \\<rightleftharpoons> \"\\<Sqinter>x. \\<Sqinter>y. f\"\n  \"\\<Sqinter>x. f\"     \\<rightleftharpoons> \"\\<Sqinter>(CONST range (\\<lambda>x. f))\"\n  \"\\<Sqinter>x\\<in>A. f\"   \\<rightleftharpoons> \"CONST Inf ((\\<lambda>x. f) ` A)\"\n  \"\\<Squnion>x y. f\"   \\<rightleftharpoons> \"\\<Squnion>x. \\<Squnion>y. f\"\n  \"\\<Squnion>x. f\"     \\<rightleftharpoons> \"\\<Squnion>(CONST range (\\<lambda>x. f))\"\n  \"\\<Squnion>x\\<in>A. f\"   \\<rightleftharpoons> \"CONST Sup ((\\<lambda>x. f) `  A)\"\n\ncontext Inf\nbegin\n\nlemma INF_image: \"\\<Sqinter> (g ` f ` A) = \\<Sqinter> ((g \\<circ> f) ` A)\"\n  by (simp add: image_comp)\n\nlemma INF_identity_eq [simp]: \"(\\<Sqinter>x\\<in>A. x) = \\<Sqinter>A\"\n  by simp\n\nlemma INF_id_eq [simp]: \"\\<Sqinter>(id ` A) = \\<Sqinter>A\"\n  by simp\n\nlemma INF_cong: \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> C x = D x) \\<Longrightarrow> \\<Sqinter>(C ` A) = \\<Sqinter>(D ` B)\"\n  by (simp add: image_def)\n\nlemma INF_cong_simp:\n  \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B =simp=> C x = D x) \\<Longrightarrow> \\<Sqinter>(C ` A) = \\<Sqinter>(D ` B)\"\n  unfolding simp_implies_def by (fact INF_cong)\n\nend\n\ncontext Sup\nbegin\n\nlemma SUP_image: \"\\<Squnion> (g ` f ` A) = \\<Squnion> ((g \\<circ> f) ` A)\"\nby(fact Inf.INF_image)\n\nlemma SUP_identity_eq [simp]: \"(\\<Squnion>x\\<in>A. x) = \\<Squnion>A\"\nby(fact Inf.INF_identity_eq)\n\nlemma SUP_id_eq [simp]: \"\\<Squnion>(id ` A) = \\<Squnion>A\"\nby(fact Inf.INF_id_eq)\n\nlemma SUP_cong: \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> C x = D x) \\<Longrightarrow> \\<Squnion>(C ` A) = \\<Squnion>(D ` B)\"\nby (fact Inf.INF_cong)\n\nlemma SUP_cong_simp:\n  \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B =simp=> C x = D x) \\<Longrightarrow> \\<Squnion>(C ` A) = \\<Squnion>(D ` B)\"\nby (fact Inf.INF_cong_simp)\n\nend\n\n\nsubsection \\<open>Abstract complete lattices\\<close>\n\ntext \\<open>A complete lattice always has a bottom and a top,\nso we include them into the following type class,\nalong with assumptions that define bottom and top\nin terms of infimum and supremum.\\<close>\n\nclass complete_lattice = lattice + Inf + Sup + bot + top +\n  assumes Inf_lower: \"x \\<in> A \\<Longrightarrow> \\<Sqinter>A \\<le> x\"\n    and Inf_greatest: \"(\\<And>x. x \\<in> A \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> z \\<le> \\<Sqinter>A\"\n    and Sup_upper: \"x \\<in> A \\<Longrightarrow> x \\<le> \\<Squnion>A\"\n    and Sup_least: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> \\<Squnion>A \\<le> z\"\n    and Inf_empty [simp]: \"\\<Sqinter>{} = \\<top>\"\n    and Sup_empty [simp]: \"\\<Squnion>{} = \\<bottom>\"\nbegin\n\nsubclass bounded_lattice\nproof\n  fix a\n  show \"\\<bottom> \\<le> a\"\n    by (auto intro: Sup_least simp only: Sup_empty [symmetric])\n  show \"a \\<le> \\<top>\"\n    by (auto intro: Inf_greatest simp only: Inf_empty [symmetric])\nqed\n\nlemma dual_complete_lattice: \"class.complete_lattice Sup Inf sup (\\<ge>) (>) inf \\<top> \\<bottom>\"\n  by (auto intro!: class.complete_lattice.intro dual_lattice)\n    (unfold_locales, (fact Inf_empty Sup_empty Sup_upper Sup_least Inf_lower Inf_greatest)+)\n\nend\n\ncontext complete_lattice\nbegin\n\nlemma Sup_eqI:\n  \"(\\<And>y. y \\<in> A \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> (\\<And>y. (\\<And>z. z \\<in> A \\<Longrightarrow> z \\<le> y) \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> \\<Squnion>A = x\"\n  by (blast intro: antisym Sup_least Sup_upper)\n\nlemma Inf_eqI:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> x \\<le> i) \\<Longrightarrow> (\\<And>y. (\\<And>i. i \\<in> A \\<Longrightarrow> y \\<le> i) \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> \\<Sqinter>A = x\"\n  by (blast intro: antisym Inf_greatest Inf_lower)\n\nlemma SUP_eqI:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<le> x) \\<Longrightarrow> (\\<And>y. (\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<le> y) \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> (\\<Squnion>i\\<in>A. f i) = x\"\n  using Sup_eqI [of \"f ` A\" x] by auto\n\nlemma INF_eqI:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> x \\<le> f i) \\<Longrightarrow> (\\<And>y. (\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<ge> y) \\<Longrightarrow> x \\<ge> y) \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) = x\"\n  using Inf_eqI [of \"f ` A\" x] by auto\n\nlemma INF_lower: \"i \\<in> A \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) \\<le> f i\"\n  using Inf_lower [of _ \"f ` A\"] by simp\n\nlemma INF_greatest: \"(\\<And>i. i \\<in> A \\<Longrightarrow> u \\<le> f i) \\<Longrightarrow> u \\<le> (\\<Sqinter>i\\<in>A. f i)\"\n  using Inf_greatest [of \"f ` A\"] by auto\n\nlemma SUP_upper: \"i \\<in> A \\<Longrightarrow> f i \\<le> (\\<Squnion>i\\<in>A. f i)\"\n  using Sup_upper [of _ \"f ` A\"] by simp\n\nlemma SUP_least: \"(\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<le> u) \\<Longrightarrow> (\\<Squnion>i\\<in>A. f i) \\<le> u\"\n  using Sup_least [of \"f ` A\"] by auto\n\nlemma Inf_lower2: \"u \\<in> A \\<Longrightarrow> u \\<le> v \\<Longrightarrow> \\<Sqinter>A \\<le> v\"\n  using Inf_lower [of u A] by auto\n\nlemma INF_lower2: \"i \\<in> A \\<Longrightarrow> f i \\<le> u \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) \\<le> u\"\n  using INF_lower [of i A f] by auto\n\nlemma Sup_upper2: \"u \\<in> A \\<Longrightarrow> v \\<le> u \\<Longrightarrow> v \\<le> \\<Squnion>A\"\n  using Sup_upper [of u A] by auto\n\nlemma SUP_upper2: \"i \\<in> A \\<Longrightarrow> u \\<le> f i \\<Longrightarrow> u \\<le> (\\<Squnion>i\\<in>A. f i)\"\n  using SUP_upper [of i A f] by auto\n\nlemma le_Inf_iff: \"b \\<le> \\<Sqinter>A \\<longleftrightarrow> (\\<forall>a\\<in>A. b \\<le> a)\"\n  by (auto intro: Inf_greatest dest: Inf_lower)\n\nlemma le_INF_iff: \"u \\<le> (\\<Sqinter>i\\<in>A. f i) \\<longleftrightarrow> (\\<forall>i\\<in>A. u \\<le> f i)\"\n  using le_Inf_iff [of _ \"f ` A\"] by simp\n\nlemma Sup_le_iff: \"\\<Squnion>A \\<le> b \\<longleftrightarrow> (\\<forall>a\\<in>A. a \\<le> b)\"\n  by (auto intro: Sup_least dest: Sup_upper)\n\nlemma SUP_le_iff: \"(\\<Squnion>i\\<in>A. f i) \\<le> u \\<longleftrightarrow> (\\<forall>i\\<in>A. f i \\<le> u)\"\n  using Sup_le_iff [of \"f ` A\"] by simp\n\nlemma Inf_insert [simp]: \"\\<Sqinter>(insert a A) = a \\<sqinter> \\<Sqinter>A\"\n  by (auto intro: le_infI le_infI1 le_infI2 antisym Inf_greatest Inf_lower)\n\nlemma INF_insert: \"(\\<Sqinter>x\\<in>insert a A. f x) = f a \\<sqinter> \\<Sqinter>(f ` A)\"\n  by simp\n\nlemma Sup_insert [simp]: \"\\<Squnion>(insert a A) = a \\<squnion> \\<Squnion>A\"\n  by (auto intro: le_supI le_supI1 le_supI2 antisym Sup_least Sup_upper)\n\nlemma SUP_insert: \"(\\<Squnion>x\\<in>insert a A. f x) = f a \\<squnion> \\<Squnion>(f ` A)\"\n  by simp\n\nlemma INF_empty: \"(\\<Sqinter>x\\<in>{}. f x) = \\<top>\"\n  by simp\n\nlemma SUP_empty: \"(\\<Squnion>x\\<in>{}. f x) = \\<bottom>\"\n  by simp\n\nlemma Inf_UNIV [simp]: \"\\<Sqinter>UNIV = \\<bottom>\"\n  by (auto intro!: antisym Inf_lower)\n\nlemma Sup_UNIV [simp]: \"\\<Squnion>UNIV = \\<top>\"\n  by (auto intro!: antisym Sup_upper)\n\nlemma Inf_eq_Sup: \"\\<Sqinter>A = \\<Squnion>{b. \\<forall>a \\<in> A. b \\<le> a}\"\n  by (auto intro: antisym Inf_lower Inf_greatest Sup_upper Sup_least)\n\nlemma Sup_eq_Inf:  \"\\<Squnion>A = \\<Sqinter>{b. \\<forall>a \\<in> A. a \\<le> b}\"\n  by (auto intro: antisym Inf_lower Inf_greatest Sup_upper Sup_least)\n\nlemma Inf_superset_mono: \"B \\<subseteq> A \\<Longrightarrow> \\<Sqinter>A \\<le> \\<Sqinter>B\"\n  by (auto intro: Inf_greatest Inf_lower)\n\nlemma Sup_subset_mono: \"A \\<subseteq> B \\<Longrightarrow> \\<Squnion>A \\<le> \\<Squnion>B\"\n  by (auto intro: Sup_least Sup_upper)\n\nlemma Inf_mono:\n  assumes \"\\<And>b. b \\<in> B \\<Longrightarrow> \\<exists>a\\<in>A. a \\<le> b\"\n  shows \"\\<Sqinter>A \\<le> \\<Sqinter>B\"\nproof (rule Inf_greatest)\n  fix b assume \"b \\<in> B\"\n  with assms obtain a where \"a \\<in> A\" and \"a \\<le> b\" by blast\n  from \\<open>a \\<in> A\\<close> have \"\\<Sqinter>A \\<le> a\" by (rule Inf_lower)\n  with \\<open>a \\<le> b\\<close> show \"\\<Sqinter>A \\<le> b\" by auto\nqed\n\nlemma INF_mono: \"(\\<And>m. m \\<in> B \\<Longrightarrow> \\<exists>n\\<in>A. f n \\<le> g m) \\<Longrightarrow> (\\<Sqinter>n\\<in>A. f n) \\<le> (\\<Sqinter>n\\<in>B. g n)\"\n  using Inf_mono [of \"g ` B\" \"f ` A\"] by auto\n\nlemma INF_mono': \"(\\<And>x. f x \\<le> g x) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. f x) \\<le> (\\<Sqinter>x\\<in>A. g x)\"\n  by (rule INF_mono) auto\n\nlemma Sup_mono:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> \\<exists>b\\<in>B. a \\<le> b\"\n  shows \"\\<Squnion>A \\<le> \\<Squnion>B\"\nproof (rule Sup_least)\n  fix a assume \"a \\<in> A\"\n  with assms obtain b where \"b \\<in> B\" and \"a \\<le> b\" by blast\n  from \\<open>b \\<in> B\\<close> have \"b \\<le> \\<Squnion>B\" by (rule Sup_upper)\n  with \\<open>a \\<le> b\\<close> show \"a \\<le> \\<Squnion>B\" by auto\nqed\n\nlemma SUP_mono: \"(\\<And>n. n \\<in> A \\<Longrightarrow> \\<exists>m\\<in>B. f n \\<le> g m) \\<Longrightarrow> (\\<Squnion>n\\<in>A. f n) \\<le> (\\<Squnion>n\\<in>B. g n)\"\n  using Sup_mono [of \"f ` A\" \"g ` B\"] by auto\n\nlemma SUP_mono': \"(\\<And>x. f x \\<le> g x) \\<Longrightarrow> (\\<Squnion>x\\<in>A. f x) \\<le> (\\<Squnion>x\\<in>A. g x)\"\n  by (rule SUP_mono) auto\n\nlemma INF_superset_mono: \"B \\<subseteq> A \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. f x) \\<le> (\\<Sqinter>x\\<in>B. g x)\"\n  \\<comment> \\<open>The last inclusion is POSITIVE!\\<close>\n  by (blast intro: INF_mono dest: subsetD)\n\nlemma SUP_subset_mono: \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<le> g x) \\<Longrightarrow> (\\<Squnion>x\\<in>A. f x) \\<le> (\\<Squnion>x\\<in>B. g x)\"\n  by (blast intro: SUP_mono dest: subsetD)\n\nlemma Inf_less_eq:\n  assumes \"\\<And>v. v \\<in> A \\<Longrightarrow> v \\<le> u\"\n    and \"A \\<noteq> {}\"\n  shows \"\\<Sqinter>A \\<le> u\"\nproof -\n  from \\<open>A \\<noteq> {}\\<close> obtain v where \"v \\<in> A\" by blast\n  moreover from \\<open>v \\<in> A\\<close> assms(1) have \"v \\<le> u\" by blast\n  ultimately show ?thesis by (rule Inf_lower2)\nqed\n\nlemma less_eq_Sup:\n  assumes \"\\<And>v. v \\<in> A \\<Longrightarrow> u \\<le> v\"\n    and \"A \\<noteq> {}\"\n  shows \"u \\<le> \\<Squnion>A\"\nproof -\n  from \\<open>A \\<noteq> {}\\<close> obtain v where \"v \\<in> A\" by blast\n  moreover from \\<open>v \\<in> A\\<close> assms(1) have \"u \\<le> v\" by blast\n  ultimately show ?thesis by (rule Sup_upper2)\nqed\n\nlemma INF_eq:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> \\<exists>j\\<in>B. f i \\<ge> g j\"\n    and \"\\<And>j. j \\<in> B \\<Longrightarrow> \\<exists>i\\<in>A. g j \\<ge> f i\"\n  shows \"\\<Sqinter>(f ` A) = \\<Sqinter>(g ` B)\"\n  by (intro antisym INF_greatest) (blast intro: INF_lower2 dest: assms)+\n\nlemma SUP_eq:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> \\<exists>j\\<in>B. f i \\<le> g j\"\n    and \"\\<And>j. j \\<in> B \\<Longrightarrow> \\<exists>i\\<in>A. g j \\<le> f i\"\n  shows \"\\<Squnion>(f ` A) = \\<Squnion>(g ` B)\"\n  by (intro antisym SUP_least) (blast intro: SUP_upper2 dest: assms)+\n\nlemma less_eq_Inf_inter: \"\\<Sqinter>A \\<squnion> \\<Sqinter>B \\<le> \\<Sqinter>(A \\<inter> B)\"\n  by (auto intro: Inf_greatest Inf_lower)\n\nlemma Sup_inter_less_eq: \"\\<Squnion>(A \\<inter> B) \\<le> \\<Squnion>A \\<sqinter> \\<Squnion>B \"\n  by (auto intro: Sup_least Sup_upper)\n\nlemma Inf_union_distrib: \"\\<Sqinter>(A \\<union> B) = \\<Sqinter>A \\<sqinter> \\<Sqinter>B\"\n  by (rule antisym) (auto intro: Inf_greatest Inf_lower le_infI1 le_infI2)\n\nlemma INF_union: \"(\\<Sqinter>i \\<in> A \\<union> B. M i) = (\\<Sqinter>i \\<in> A. M i) \\<sqinter> (\\<Sqinter>i\\<in>B. M i)\"\n  by (auto intro!: antisym INF_mono intro: le_infI1 le_infI2 INF_greatest INF_lower)\n\nlemma Sup_union_distrib: \"\\<Squnion>(A \\<union> B) = \\<Squnion>A \\<squnion> \\<Squnion>B\"\n  by (rule antisym) (auto intro: Sup_least Sup_upper le_supI1 le_supI2)\n\nlemma SUP_union: \"(\\<Squnion>i \\<in> A \\<union> B. M i) = (\\<Squnion>i \\<in> A. M i) \\<squnion> (\\<Squnion>i\\<in>B. M i)\"\n  by (auto intro!: antisym SUP_mono intro: le_supI1 le_supI2 SUP_least SUP_upper)\n\nlemma INF_inf_distrib: \"(\\<Sqinter>a\\<in>A. f a) \\<sqinter> (\\<Sqinter>a\\<in>A. g a) = (\\<Sqinter>a\\<in>A. f a \\<sqinter> g a)\"\n  by (rule antisym) (rule INF_greatest, auto intro: le_infI1 le_infI2 INF_lower INF_mono)\n\nlemma SUP_sup_distrib: \"(\\<Squnion>a\\<in>A. f a) \\<squnion> (\\<Squnion>a\\<in>A. g a) = (\\<Squnion>a\\<in>A. f a \\<squnion> g a)\"\n  (is \"?L = ?R\")\nproof (rule antisym)\n  show \"?L \\<le> ?R\"\n    by (auto intro: le_supI1 le_supI2 SUP_upper SUP_mono)\n  show \"?R \\<le> ?L\"\n    by (rule SUP_least) (auto intro: le_supI1 le_supI2 SUP_upper)\nqed\n\nlemma Inf_top_conv [simp]:\n  \"\\<Sqinter>A = \\<top> \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\"\n  \"\\<top> = \\<Sqinter>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\"\nproof -\n  show \"\\<Sqinter>A = \\<top> \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\"\n  proof\n    assume \"\\<forall>x\\<in>A. x = \\<top>\"\n    then have \"A = {} \\<or> A = {\\<top>}\" by auto\n    then show \"\\<Sqinter>A = \\<top>\" by auto\n  next\n    assume \"\\<Sqinter>A = \\<top>\"\n    show \"\\<forall>x\\<in>A. x = \\<top>\"\n    proof (rule ccontr)\n      assume \"\\<not> (\\<forall>x\\<in>A. x = \\<top>)\"\n      then obtain x where \"x \\<in> A\" and \"x \\<noteq> \\<top>\" by blast\n      then obtain B where \"A = insert x B\" by blast\n      with \\<open>\\<Sqinter>A = \\<top>\\<close> \\<open>x \\<noteq> \\<top>\\<close> show False by simp\n    qed\n  qed\n  then show \"\\<top> = \\<Sqinter>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\" by auto\nqed\n\nlemma INF_top_conv [simp]:\n  \"(\\<Sqinter>x\\<in>A. B x) = \\<top> \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<top>)\"\n  \"\\<top> = (\\<Sqinter>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<top>)\"\n  using Inf_top_conv [of \"B ` A\"] by simp_all\n\nlemma Sup_bot_conv [simp]:\n  \"\\<Squnion>A = \\<bottom> \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<bottom>)\"\n  \"\\<bottom> = \\<Squnion>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<bottom>)\"\n  using dual_complete_lattice\n  by (rule complete_lattice.Inf_top_conv)+\n\nlemma SUP_bot_conv [simp]:\n  \"(\\<Squnion>x\\<in>A. B x) = \\<bottom> \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<bottom>)\"\n  \"\\<bottom> = (\\<Squnion>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<bottom>)\"\n  using Sup_bot_conv [of \"B ` A\"] by simp_all\n\nlemma INF_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f) = f\"\n  by (auto intro: antisym INF_lower INF_greatest)\n\nlemma SUP_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Squnion>i\\<in>A. f) = f\"\n  by (auto intro: antisym SUP_upper SUP_least)\n\nlemma INF_top [simp]: \"(\\<Sqinter>x\\<in>A. \\<top>) = \\<top>\"\n  by (cases \"A = {}\") simp_all\n\nlemma SUP_bot [simp]: \"(\\<Squnion>x\\<in>A. \\<bottom>) = \\<bottom>\"\n  by (cases \"A = {}\") simp_all\n\nlemma INF_commute: \"(\\<Sqinter>i\\<in>A. \\<Sqinter>j\\<in>B. f i j) = (\\<Sqinter>j\\<in>B. \\<Sqinter>i\\<in>A. f i j)\"\n  by (iprover intro: INF_lower INF_greatest order_trans antisym)\n\nlemma SUP_commute: \"(\\<Squnion>i\\<in>A. \\<Squnion>j\\<in>B. f i j) = (\\<Squnion>j\\<in>B. \\<Squnion>i\\<in>A. f i j)\"\n  by (iprover intro: SUP_upper SUP_least order_trans antisym)\n\nlemma INF_absorb:\n  assumes \"k \\<in> I\"\n  shows \"A k \\<sqinter> (\\<Sqinter>i\\<in>I. A i) = (\\<Sqinter>i\\<in>I. A i)\"\nproof -\n  from assms obtain J where \"I = insert k J\" by blast\n  then show ?thesis by simp\nqed\n\nlemma SUP_absorb:\n  assumes \"k \\<in> I\"\n  shows \"A k \\<squnion> (\\<Squnion>i\\<in>I. A i) = (\\<Squnion>i\\<in>I. A i)\"\nproof -\n  from assms obtain J where \"I = insert k J\" by blast\n  then show ?thesis by simp\nqed\n\nlemma INF_inf_const1: \"I \\<noteq> {} \\<Longrightarrow> (\\<Sqinter>i\\<in>I. inf x (f i)) = inf x (\\<Sqinter>i\\<in>I. f i)\"\n  by (intro antisym INF_greatest inf_mono order_refl INF_lower)\n     (auto intro: INF_lower2 le_infI2 intro!: INF_mono)\n\nlemma INF_inf_const2: \"I \\<noteq> {} \\<Longrightarrow> (\\<Sqinter>i\\<in>I. inf (f i) x) = inf (\\<Sqinter>i\\<in>I. f i) x\"\n  using INF_inf_const1[of I x f] by (simp add: inf_commute)\n\nlemma INF_constant: \"(\\<Sqinter>y\\<in>A. c) = (if A = {} then \\<top> else c)\"\n  by simp\n\nlemma SUP_constant: \"(\\<Squnion>y\\<in>A. c) = (if A = {} then \\<bottom> else c)\"\n  by simp\n\nlemma less_INF_D:\n  assumes \"y < (\\<Sqinter>i\\<in>A. f i)\" \"i \\<in> A\"\n  shows \"y < f i\"\nproof -\n  note \\<open>y < (\\<Sqinter>i\\<in>A. f i)\\<close>\n  also have \"(\\<Sqinter>i\\<in>A. f i) \\<le> f i\" using \\<open>i \\<in> A\\<close>\n    by (rule INF_lower)\n  finally show \"y < f i\" .\nqed\n\nlemma SUP_lessD:\n  assumes \"(\\<Squnion>i\\<in>A. f i) < y\" \"i \\<in> A\"\n  shows \"f i < y\"\nproof -\n  have \"f i \\<le> (\\<Squnion>i\\<in>A. f i)\"\n    using \\<open>i \\<in> A\\<close> by (rule SUP_upper)\n  also note \\<open>(\\<Squnion>i\\<in>A. f i) < y\\<close>\n  finally show \"f i < y\" .\nqed\n\nlemma INF_UNIV_bool_expand: \"(\\<Sqinter>b. A b) = A True \\<sqinter> A False\"\n  by (simp add: UNIV_bool inf_commute)\n\nlemma SUP_UNIV_bool_expand: \"(\\<Squnion>b. A b) = A True \\<squnion> A False\"\n  by (simp add: UNIV_bool sup_commute)\n\nlemma Inf_le_Sup: \"A \\<noteq> {} \\<Longrightarrow> Inf A \\<le> Sup A\"\n  by (blast intro: Sup_upper2 Inf_lower ex_in_conv)\n\nlemma INF_le_SUP: \"A \\<noteq> {} \\<Longrightarrow> \\<Sqinter>(f ` A) \\<le> \\<Squnion>(f ` A)\"\n  using Inf_le_Sup [of \"f ` A\"] by simp\n\nlemma INF_eq_const: \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i = x) \\<Longrightarrow> \\<Sqinter>(f ` I) = x\"\n  by (auto intro: INF_eqI)\n\nlemma SUP_eq_const: \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i = x) \\<Longrightarrow> \\<Squnion>(f ` I) = x\"\n  by (auto intro: SUP_eqI)\n\nlemma INF_eq_iff: \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<le> c) \\<Longrightarrow> \\<Sqinter>(f ` I) = c \\<longleftrightarrow> (\\<forall>i\\<in>I. f i = c)\"\n  by (auto intro: INF_eq_const INF_lower antisym)\n\nlemma SUP_eq_iff: \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> c \\<le> f i) \\<Longrightarrow> \\<Squnion>(f ` I) = c \\<longleftrightarrow> (\\<forall>i\\<in>I. f i = c)\"\n  by (auto intro: SUP_eq_const SUP_upper antisym)\n\nend\n\ncontext complete_lattice\nbegin\nlemma Sup_Inf_le: \"Sup (Inf ` {f ` A | f . (\\<forall> Y \\<in> A . f Y \\<in> Y)}) \\<le> Inf (Sup ` A)\"\n  by (rule SUP_least, clarify, rule INF_greatest, simp add: INF_lower2 Sup_upper)\nend \n\nclass complete_distrib_lattice = complete_lattice +\n  assumes Inf_Sup_le: \"Inf (Sup ` A) \\<le> Sup (Inf ` {f ` A | f . (\\<forall> Y \\<in> A . f Y \\<in> Y)})\"\nbegin\n  \nlemma Inf_Sup: \"Inf (Sup ` A) = Sup (Inf ` {f ` A | f . (\\<forall> Y \\<in> A . f Y \\<in> Y)})\"\n  by (rule antisym, rule Inf_Sup_le, rule Sup_Inf_le)\n\nsubclass distrib_lattice\nproof\n  fix a b c\n  show \"a \\<squnion> b \\<sqinter> c = (a \\<squnion> b) \\<sqinter> (a \\<squnion> c)\"\n  proof (rule antisym, simp_all, safe)\n    show \"b \\<sqinter> c \\<le> a \\<squnion> b\"\n      by (rule le_infI1, simp)\n    show \"b \\<sqinter> c \\<le> a \\<squnion> c\"\n      by (rule le_infI2, simp)\n    have [simp]: \"a \\<sqinter> c \\<le> a \\<squnion> b \\<sqinter> c\"\n      by (rule le_infI1, simp)\n    have [simp]: \"b \\<sqinter> a \\<le> a \\<squnion> b \\<sqinter> c\"\n      by (rule le_infI2, simp)\n    have \"\\<Sqinter>(Sup ` {{a, b}, {a, c}}) =\n      \\<Squnion>(Inf ` {f ` {{a, b}, {a, c}} | f. \\<forall>Y\\<in>{{a, b}, {a, c}}. f Y \\<in> Y})\"\n      by (rule Inf_Sup)\n    from this show \"(a \\<squnion> b) \\<sqinter> (a \\<squnion> c) \\<le> a \\<squnion> b \\<sqinter> c\"\n      apply simp\n      by (rule SUP_least, safe, simp_all)\n  qed\nqed\nend\n\ncontext complete_lattice\nbegin\ncontext\n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  assumes \"mono f\"\nbegin\n\nlemma mono_Inf: \"f (\\<Sqinter>A) \\<le> (\\<Sqinter>x\\<in>A. f x)\"\n  using \\<open>mono f\\<close> by (auto intro: complete_lattice_class.INF_greatest Inf_lower dest: monoD)\n\nlemma mono_Sup: \"(\\<Squnion>x\\<in>A. f x) \\<le> f (\\<Squnion>A)\"\n  using \\<open>mono f\\<close> by (auto intro: complete_lattice_class.SUP_least Sup_upper dest: monoD)\n\nlemma mono_INF: \"f (\\<Sqinter>i\\<in>I. A i) \\<le> (\\<Sqinter>x\\<in>I. f (A x))\"\n  by (intro complete_lattice_class.INF_greatest monoD[OF \\<open>mono f\\<close>] INF_lower)\n\nlemma mono_SUP: \"(\\<Squnion>x\\<in>I. f (A x)) \\<le> f (\\<Squnion>i\\<in>I. A i)\"\n  by (intro complete_lattice_class.SUP_least monoD[OF \\<open>mono f\\<close>] SUP_upper)\n\nend\n\nend\n\nclass complete_boolean_algebra = boolean_algebra + complete_distrib_lattice\nbegin\n\nlemma uminus_Inf: \"- (\\<Sqinter>A) = \\<Squnion>(uminus ` A)\"\nproof (rule antisym)\n  show \"- \\<Sqinter>A \\<le> \\<Squnion>(uminus ` A)\"\n    by (rule compl_le_swap2, rule Inf_greatest, rule compl_le_swap2, rule Sup_upper) simp\n  show \"\\<Squnion>(uminus ` A) \\<le> - \\<Sqinter>A\"\n    by (rule Sup_least, rule compl_le_swap1, rule Inf_lower) auto\nqed\n\nlemma uminus_INF: \"- (\\<Sqinter>x\\<in>A. B x) = (\\<Squnion>x\\<in>A. - B x)\"\n  by (simp add: uminus_Inf image_image)\n\nlemma uminus_Sup: \"- (\\<Squnion>A) = \\<Sqinter>(uminus ` A)\"\nproof -\n  have \"\\<Squnion>A = - \\<Sqinter>(uminus ` A)\"\n    by (simp add: image_image uminus_INF)\n  then show ?thesis by simp\nqed\n\nlemma uminus_SUP: \"- (\\<Squnion>x\\<in>A. B x) = (\\<Sqinter>x\\<in>A. - B x)\"\n  by (simp add: uminus_Sup image_image)\n\nend\n\nclass complete_linorder = linorder + complete_lattice\nbegin\n\nlemma dual_complete_linorder:\n  \"class.complete_linorder Sup Inf sup (\\<ge>) (>) inf \\<top> \\<bottom>\"\n  by (rule class.complete_linorder.intro, rule dual_complete_lattice, rule dual_linorder)\n\nlemma complete_linorder_inf_min: \"inf = min\"\n  by (auto intro: antisym simp add: min_def fun_eq_iff)\n\nlemma complete_linorder_sup_max: \"sup = max\"\n  by (auto intro: antisym simp add: max_def fun_eq_iff)\n\nlemma Inf_less_iff: \"\\<Sqinter>S < a \\<longleftrightarrow> (\\<exists>x\\<in>S. x < a)\"\n  by (simp add: not_le [symmetric] le_Inf_iff)\n\nlemma INF_less_iff: \"(\\<Sqinter>i\\<in>A. f i) < a \\<longleftrightarrow> (\\<exists>x\\<in>A. f x < a)\"\n  by (simp add: Inf_less_iff [of \"f ` A\"])\n\nlemma less_Sup_iff: \"a < \\<Squnion>S \\<longleftrightarrow> (\\<exists>x\\<in>S. a < x)\"\n  by (simp add: not_le [symmetric] Sup_le_iff)\n\nlemma less_SUP_iff: \"a < (\\<Squnion>i\\<in>A. f i) \\<longleftrightarrow> (\\<exists>x\\<in>A. a < f x)\"\n  by (simp add: less_Sup_iff [of _ \"f ` A\"])\n\nlemma Sup_eq_top_iff [simp]: \"\\<Squnion>A = \\<top> \\<longleftrightarrow> (\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < i)\"\nproof\n  assume *: \"\\<Squnion>A = \\<top>\"\n  show \"(\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < i)\"\n    unfolding * [symmetric]\n  proof (intro allI impI)\n    fix x\n    assume \"x < \\<Squnion>A\"\n    then show \"\\<exists>i\\<in>A. x < i\"\n      by (simp add: less_Sup_iff)\n  qed\nnext\n  assume *: \"\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < i\"\n  show \"\\<Squnion>A = \\<top>\"\n  proof (rule ccontr)\n    assume \"\\<Squnion>A \\<noteq> \\<top>\"\n    with top_greatest [of \"\\<Squnion>A\"] have \"\\<Squnion>A < \\<top>\"\n      unfolding le_less by auto\n    with * have \"\\<Squnion>A < \\<Squnion>A\"\n      unfolding less_Sup_iff by auto\n    then show False by auto\n  qed\nqed\n\nlemma SUP_eq_top_iff [simp]: \"(\\<Squnion>i\\<in>A. f i) = \\<top> \\<longleftrightarrow> (\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < f i)\"\n  using Sup_eq_top_iff [of \"f ` A\"] by simp\n\nlemma Inf_eq_bot_iff [simp]: \"\\<Sqinter>A = \\<bottom> \\<longleftrightarrow> (\\<forall>x>\\<bottom>. \\<exists>i\\<in>A. i < x)\"\n  using dual_complete_linorder\n  by (rule complete_linorder.Sup_eq_top_iff)\n\nlemma INF_eq_bot_iff [simp]: \"(\\<Sqinter>i\\<in>A. f i) = \\<bottom> \\<longleftrightarrow> (\\<forall>x>\\<bottom>. \\<exists>i\\<in>A. f i < x)\"\n  using Inf_eq_bot_iff [of \"f ` A\"] by simp\n\nlemma Inf_le_iff: \"\\<Sqinter>A \\<le> x \\<longleftrightarrow> (\\<forall>y>x. \\<exists>a\\<in>A. y > a)\"\nproof safe\n  fix y\n  assume \"x \\<ge> \\<Sqinter>A\" \"y > x\"\n  then have \"y > \\<Sqinter>A\" by auto\n  then show \"\\<exists>a\\<in>A. y > a\"\n    unfolding Inf_less_iff .\nqed (auto elim!: allE[of _ \"\\<Sqinter>A\"] simp add: not_le[symmetric] Inf_lower)\n\nlemma INF_le_iff: \"\\<Sqinter>(f ` A) \\<le> x \\<longleftrightarrow> (\\<forall>y>x. \\<exists>i\\<in>A. y > f i)\"\n  using Inf_le_iff [of \"f ` A\"] by simp\n\nlemma le_Sup_iff: \"x \\<le> \\<Squnion>A \\<longleftrightarrow> (\\<forall>y<x. \\<exists>a\\<in>A. y < a)\"\nproof safe\n  fix y\n  assume \"x \\<le> \\<Squnion>A\" \"y < x\"\n  then have \"y < \\<Squnion>A\" by auto\n  then show \"\\<exists>a\\<in>A. y < a\"\n    unfolding less_Sup_iff .\nqed (auto elim!: allE[of _ \"\\<Squnion>A\"] simp add: not_le[symmetric] Sup_upper)\n\nlemma le_SUP_iff: \"x \\<le> \\<Squnion>(f ` A) \\<longleftrightarrow> (\\<forall>y<x. \\<exists>i\\<in>A. y < f i)\"\n  using le_Sup_iff [of _ \"f ` A\"] by simp\n\nend\n\nsubsection \\<open>Complete lattice on \\<^typ>\\<open>bool\\<close>\\<close>\n\ninstantiation bool :: complete_lattice\nbegin\n\ndefinition [simp, code]: \"\\<Sqinter>A \\<longleftrightarrow> False \\<notin> A\"\n\ndefinition [simp, code]: \"\\<Squnion>A \\<longleftrightarrow> True \\<in> A\"\n\ninstance\n  by standard (auto intro: bool_induct)\n\nend\n\nlemma not_False_in_image_Ball [simp]: \"False \\<notin> P ` A \\<longleftrightarrow> Ball A P\"\n  by auto\n\nlemma True_in_image_Bex [simp]: \"True \\<in> P ` A \\<longleftrightarrow> Bex A P\"\n  by auto\n\nlemma INF_bool_eq [simp]: \"(\\<lambda>A f. \\<Sqinter>(f ` A)) = Ball\"\n  by (simp add: fun_eq_iff)\n\nlemma SUP_bool_eq [simp]: \"(\\<lambda>A f. \\<Squnion>(f ` A)) = Bex\"\n  by (simp add: fun_eq_iff)\n\ninstance bool :: complete_boolean_algebra\n  by (standard, fastforce)\n\nsubsection \\<open>Complete lattice on \\<^typ>\\<open>_ \\<Rightarrow> _\\<close>\\<close>\n\ninstantiation \"fun\" :: (type, Inf) Inf\nbegin\n\ndefinition \"\\<Sqinter>A = (\\<lambda>x. \\<Sqinter>f\\<in>A. f x)\"\n\nlemma Inf_apply [simp, code]: \"(\\<Sqinter>A) x = (\\<Sqinter>f\\<in>A. f x)\"\n  by (simp add: Inf_fun_def)\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, Sup) Sup\nbegin\n\ndefinition \"\\<Squnion>A = (\\<lambda>x. \\<Squnion>f\\<in>A. f x)\"\n\nlemma Sup_apply [simp, code]: \"(\\<Squnion>A) x = (\\<Squnion>f\\<in>A. f x)\"\n  by (simp add: Sup_fun_def)\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, complete_lattice) complete_lattice\nbegin\n\ninstance\n  by standard (auto simp add: le_fun_def intro: INF_lower INF_greatest SUP_upper SUP_least)\n\nend\n\nlemma INF_apply [simp]: \"(\\<Sqinter>y\\<in>A. f y) x = (\\<Sqinter>y\\<in>A. f y x)\"\n  by (simp add: image_comp)\n\nlemma SUP_apply [simp]: \"(\\<Squnion>y\\<in>A. f y) x = (\\<Squnion>y\\<in>A. f y x)\"\n  by (simp add: image_comp)\n\nsubsection \\<open>Complete lattice on unary and binary predicates\\<close>\n\nlemma Inf1_I: \"(\\<And>P. P \\<in> A \\<Longrightarrow> P a) \\<Longrightarrow> (\\<Sqinter>A) a\"\n  by auto\n\nlemma INF1_I: \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x b) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. B x) b\"\n  by simp\n\nlemma INF2_I: \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x b c) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. B x) b c\"\n  by simp\n\nlemma Inf2_I: \"(\\<And>r. r \\<in> A \\<Longrightarrow> r a b) \\<Longrightarrow> (\\<Sqinter>A) a b\"\n  by auto\n\nlemma Inf1_D: \"(\\<Sqinter>A) a \\<Longrightarrow> P \\<in> A \\<Longrightarrow> P a\"\n  by auto\n\nlemma INF1_D: \"(\\<Sqinter>x\\<in>A. B x) b \\<Longrightarrow> a \\<in> A \\<Longrightarrow> B a b\"\n  by simp\n\nlemma Inf2_D: \"(\\<Sqinter>A) a b \\<Longrightarrow> r \\<in> A \\<Longrightarrow> r a b\"\n  by auto\n\nlemma INF2_D: \"(\\<Sqinter>x\\<in>A. B x) b c \\<Longrightarrow> a \\<in> A \\<Longrightarrow> B a b c\"\n  by simp\n\nlemma Inf1_E:\n  assumes \"(\\<Sqinter>A) a\"\n  obtains \"P a\" | \"P \\<notin> A\"\n  using assms by auto\n\nlemma INF1_E:\n  assumes \"(\\<Sqinter>x\\<in>A. B x) b\"\n  obtains \"B a b\" | \"a \\<notin> A\"\n  using assms by auto\n\nlemma Inf2_E:\n  assumes \"(\\<Sqinter>A) a b\"\n  obtains \"r a b\" | \"r \\<notin> A\"\n  using assms by auto\n\nlemma INF2_E:\n  assumes \"(\\<Sqinter>x\\<in>A. B x) b c\"\n  obtains \"B a b c\" | \"a \\<notin> A\"\n  using assms by auto\n\nlemma Sup1_I: \"P \\<in> A \\<Longrightarrow> P a \\<Longrightarrow> (\\<Squnion>A) a\"\n  by auto\n\nlemma SUP1_I: \"a \\<in> A \\<Longrightarrow> B a b \\<Longrightarrow> (\\<Squnion>x\\<in>A. B x) b\"\n  by auto\n\nlemma Sup2_I: \"r \\<in> A \\<Longrightarrow> r a b \\<Longrightarrow> (\\<Squnion>A) a b\"\n  by auto\n\nlemma SUP2_I: \"a \\<in> A \\<Longrightarrow> B a b c \\<Longrightarrow> (\\<Squnion>x\\<in>A. B x) b c\"\n  by auto\n\nlemma Sup1_E:\n  assumes \"(\\<Squnion>A) a\"\n  obtains P where \"P \\<in> A\" and \"P a\"\n  using assms by auto\n\nlemma SUP1_E:\n  assumes \"(\\<Squnion>x\\<in>A. B x) b\"\n  obtains x where \"x \\<in> A\" and \"B x b\"\n  using assms by auto\n\nlemma Sup2_E:\n  assumes \"(\\<Squnion>A) a b\"\n  obtains r where \"r \\<in> A\" \"r a b\"\n  using assms by auto\n\nlemma SUP2_E:\n  assumes \"(\\<Squnion>x\\<in>A. B x) b c\"\n  obtains x where \"x \\<in> A\" \"B x b c\"\n  using assms by auto\n\n\nsubsection \\<open>Complete lattice on \\<^typ>\\<open>_ set\\<close>\\<close>\n\ninstantiation \"set\" :: (type) complete_lattice\nbegin\n\ndefinition \"\\<Sqinter>A = {x. \\<Sqinter>((\\<lambda>B. x \\<in> B) ` A)}\"\n\ndefinition \"\\<Squnion>A = {x. \\<Squnion>((\\<lambda>B. x \\<in> B) ` A)}\"\n\ninstance\n  by standard (auto simp add: less_eq_set_def Inf_set_def Sup_set_def le_fun_def)\n\nend\n\nsubsubsection \\<open>Inter\\<close>\n\nabbreviation Inter :: \"'a set set \\<Rightarrow> 'a set\"  (\"\\<Inter>\")\n  where \"\\<Inter>S \\<equiv> \\<Sqinter>S\"\n\nlemma Inter_eq: \"\\<Inter>A = {x. \\<forall>B \\<in> A. x \\<in> B}\"\nproof (rule set_eqI)\n  fix x\n  have \"(\\<forall>Q\\<in>{P. \\<exists>B\\<in>A. P \\<longleftrightarrow> x \\<in> B}. Q) \\<longleftrightarrow> (\\<forall>B\\<in>A. x \\<in> B)\"\n    by auto\n  then show \"x \\<in> \\<Inter>A \\<longleftrightarrow> x \\<in> {x. \\<forall>B \\<in> A. x \\<in> B}\"\n    by (simp add: Inf_set_def image_def)\nqed\n\nlemma Inter_iff [simp]: \"A \\<in> \\<Inter>C \\<longleftrightarrow> (\\<forall>X\\<in>C. A \\<in> X)\"\n  by (unfold Inter_eq) blast\n\nlemma InterI [intro!]: \"(\\<And>X. X \\<in> C \\<Longrightarrow> A \\<in> X) \\<Longrightarrow> A \\<in> \\<Inter>C\"\n  by (simp add: Inter_eq)\n\ntext \\<open>\n  \\<^medskip> A ``destruct'' rule -- every \\<^term>\\<open>X\\<close> in \\<^term>\\<open>C\\<close>\n  contains \\<^term>\\<open>A\\<close> as an element, but \\<^prop>\\<open>A \\<in> X\\<close> can hold when\n  \\<^prop>\\<open>X \\<in> C\\<close> does not!  This rule is analogous to \\<open>spec\\<close>.\n\\<close>\n\nlemma InterD [elim, Pure.elim]: \"A \\<in> \\<Inter>C \\<Longrightarrow> X \\<in> C \\<Longrightarrow> A \\<in> X\"\n  by auto\n\nlemma InterE [elim]: \"A \\<in> \\<Inter>C \\<Longrightarrow> (X \\<notin> C \\<Longrightarrow> R) \\<Longrightarrow> (A \\<in> X \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  \\<comment> \\<open>``Classical'' elimination rule -- does not require proving\n    \\<^prop>\\<open>X \\<in> C\\<close>.\\<close>\n  unfolding Inter_eq by blast\n\nlemma Inter_lower: \"B \\<in> A \\<Longrightarrow> \\<Inter>A \\<subseteq> B\"\n  by (fact Inf_lower)\n\nlemma Inter_subset: \"(\\<And>X. X \\<in> A \\<Longrightarrow> X \\<subseteq> B) \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \\<Inter>A \\<subseteq> B\"\n  by (fact Inf_less_eq)\n\nlemma Inter_greatest: \"(\\<And>X. X \\<in> A \\<Longrightarrow> C \\<subseteq> X) \\<Longrightarrow> C \\<subseteq> \\<Inter>A\"\n  by (fact Inf_greatest)\n\nlemma Inter_empty: \"\\<Inter>{} = UNIV\"\n  by (fact Inf_empty) (* already simp *)\n\nlemma Inter_UNIV: \"\\<Inter>UNIV = {}\"\n  by (fact Inf_UNIV) (* already simp *)\n\nlemma Inter_insert: \"\\<Inter>(insert a B) = a \\<inter> \\<Inter>B\"\n  by (fact Inf_insert) (* already simp *)\n\nlemma Inter_Un_subset: \"\\<Inter>A \\<union> \\<Inter>B \\<subseteq> \\<Inter>(A \\<inter> B)\"\n  by (fact less_eq_Inf_inter)\n\nlemma Inter_Un_distrib: \"\\<Inter>(A \\<union> B) = \\<Inter>A \\<inter> \\<Inter>B\"\n  by (fact Inf_union_distrib)\n\nlemma Inter_UNIV_conv [simp]:\n  \"\\<Inter>A = UNIV \\<longleftrightarrow> (\\<forall>x\\<in>A. x = UNIV)\"\n  \"UNIV = \\<Inter>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = UNIV)\"\n  by (fact Inf_top_conv)+\n\nlemma Inter_anti_mono: \"B \\<subseteq> A \\<Longrightarrow> \\<Inter>A \\<subseteq> \\<Inter>B\"\n  by (fact Inf_superset_mono)\n\n\nsubsubsection \\<open>Intersections of families\\<close>\n\nsyntax (ASCII)\n  \"_INTER1\"     :: \"pttrns \\<Rightarrow> 'b set \\<Rightarrow> 'b set\"           (\"(3INT _./ _)\" [0, 10] 10)\n  \"_INTER\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> 'b set\"  (\"(3INT _:_./ _)\" [0, 0, 10] 10)\n\nsyntax\n  \"_INTER1\"     :: \"pttrns \\<Rightarrow> 'b set \\<Rightarrow> 'b set\"           (\"(3\\<Inter>_./ _)\" [0, 10] 10)\n  \"_INTER\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> 'b set\"  (\"(3\\<Inter>_\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax (latex output)\n  \"_INTER1\"     :: \"pttrns \\<Rightarrow> 'b set \\<Rightarrow> 'b set\"           (\"(3\\<Inter>(\\<open>unbreakable\\<close>\\<^bsub>_\\<^esub>)/ _)\" [0, 10] 10)\n  \"_INTER\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> 'b set\"  (\"(3\\<Inter>(\\<open>unbreakable\\<close>\\<^bsub>_\\<in>_\\<^esub>)/ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<Inter>x y. f\"  \\<rightleftharpoons> \"\\<Inter>x. \\<Inter>y. f\"\n  \"\\<Inter>x. f\"    \\<rightleftharpoons> \"\\<Inter>(CONST range (\\<lambda>x. f))\"\n  \"\\<Inter>x\\<in>A. f\"  \\<rightleftharpoons> \"CONST Inter ((\\<lambda>x. f) ` A)\"\n\nlemma INTER_eq: \"(\\<Inter>x\\<in>A. B x) = {y. \\<forall>x\\<in>A. y \\<in> B x}\"\n  by (auto intro!: INF_eqI)\n\nlemma INT_iff [simp]: \"b \\<in> (\\<Inter>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. b \\<in> B x)\"\n  using Inter_iff [of _ \"B ` A\"] by simp\n\nlemma INT_I [intro!]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> b \\<in> B x) \\<Longrightarrow> b \\<in> (\\<Inter>x\\<in>A. B x)\"\n  by auto\n\nlemma INT_D [elim, Pure.elim]: \"b \\<in> (\\<Inter>x\\<in>A. B x) \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> B a\"\n  by auto\n\nlemma INT_E [elim]: \"b \\<in> (\\<Inter>x\\<in>A. B x) \\<Longrightarrow> (b \\<in> B a \\<Longrightarrow> R) \\<Longrightarrow> (a \\<notin> A \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  \\<comment> \\<open>\"Classical\" elimination -- by the Excluded Middle on \\<^prop>\\<open>a\\<in>A\\<close>.\\<close>\n  by auto\n\nlemma Collect_ball_eq: \"{x. \\<forall>y\\<in>A. P x y} = (\\<Inter>y\\<in>A. {x. P x y})\"\n  by blast\n\nlemma Collect_all_eq: \"{x. \\<forall>y. P x y} = (\\<Inter>y. {x. P x y})\"\n  by blast\n\nlemma INT_lower: \"a \\<in> A \\<Longrightarrow> (\\<Inter>x\\<in>A. B x) \\<subseteq> B a\"\n  by (fact INF_lower)\n\nlemma INT_greatest: \"(\\<And>x. x \\<in> A \\<Longrightarrow> C \\<subseteq> B x) \\<Longrightarrow> C \\<subseteq> (\\<Inter>x\\<in>A. B x)\"\n  by (fact INF_greatest)\n\nlemma INT_empty: \"(\\<Inter>x\\<in>{}. B x) = UNIV\"\n  by (fact INF_empty)\n\nlemma INT_absorb: \"k \\<in> I \\<Longrightarrow> A k \\<inter> (\\<Inter>i\\<in>I. A i) = (\\<Inter>i\\<in>I. A i)\"\n  by (fact INF_absorb)\n\nlemma INT_subset_iff: \"B \\<subseteq> (\\<Inter>i\\<in>I. A i) \\<longleftrightarrow> (\\<forall>i\\<in>I. B \\<subseteq> A i)\"\n  by (fact le_INF_iff)\n\nlemma INT_insert [simp]: \"(\\<Inter>x \\<in> insert a A. B x) = B a \\<inter> \\<Inter> (B ` A)\"\n  by (fact INF_insert)\n\nlemma INT_Un: \"(\\<Inter>i \\<in> A \\<union> B. M i) = (\\<Inter>i \\<in> A. M i) \\<inter> (\\<Inter>i\\<in>B. M i)\"\n  by (fact INF_union)\n\nlemma INT_insert_distrib: \"u \\<in> A \\<Longrightarrow> (\\<Inter>x\\<in>A. insert a (B x)) = insert a (\\<Inter>x\\<in>A. B x)\"\n  by blast\n\nlemma INT_constant [simp]: \"(\\<Inter>y\\<in>A. c) = (if A = {} then UNIV else c)\"\n  by (fact INF_constant)\n\nlemma INTER_UNIV_conv:\n  \"(UNIV = (\\<Inter>x\\<in>A. B x)) = (\\<forall>x\\<in>A. B x = UNIV)\"\n  \"((\\<Inter>x\\<in>A. B x) = UNIV) = (\\<forall>x\\<in>A. B x = UNIV)\"\n  by (fact INF_top_conv)+ (* already simp *)\n\nlemma INT_bool_eq: \"(\\<Inter>b. A b) = A True \\<inter> A False\"\n  by (fact INF_UNIV_bool_expand)\n\nlemma INT_anti_mono: \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<subseteq> g x) \\<Longrightarrow> (\\<Inter>x\\<in>B. f x) \\<subseteq> (\\<Inter>x\\<in>A. g x)\"\n  \\<comment> \\<open>The last inclusion is POSITIVE!\\<close>\n  by (fact INF_superset_mono)\n\nlemma Pow_INT_eq: \"Pow (\\<Inter>x\\<in>A. B x) = (\\<Inter>x\\<in>A. Pow (B x))\"\n  by blast\n\nlemma vimage_INT: \"f -` (\\<Inter>x\\<in>A. B x) = (\\<Inter>x\\<in>A. f -` B x)\"\n  by blast\n\n\nsubsubsection \\<open>Union\\<close>\n\nabbreviation Union :: \"'a set set \\<Rightarrow> 'a set\"  (\"\\<Union>\")\n  where \"\\<Union>S \\<equiv> \\<Squnion>S\"\n\nlemma Union_eq: \"\\<Union>A = {x. \\<exists>B \\<in> A. x \\<in> B}\"\nproof (rule set_eqI)\n  fix x\n  have \"(\\<exists>Q\\<in>{P. \\<exists>B\\<in>A. P \\<longleftrightarrow> x \\<in> B}. Q) \\<longleftrightarrow> (\\<exists>B\\<in>A. x \\<in> B)\"\n    by auto\n  then show \"x \\<in> \\<Union>A \\<longleftrightarrow> x \\<in> {x. \\<exists>B\\<in>A. x \\<in> B}\"\n    by (simp add: Sup_set_def image_def)\nqed\n\nlemma Union_iff [simp]: \"A \\<in> \\<Union>C \\<longleftrightarrow> (\\<exists>X\\<in>C. A\\<in>X)\"\n  by (unfold Union_eq) blast\n\nlemma UnionI [intro]: \"X \\<in> C \\<Longrightarrow> A \\<in> X \\<Longrightarrow> A \\<in> \\<Union>C\"\n  \\<comment> \\<open>The order of the premises presupposes that \\<^term>\\<open>C\\<close> is rigid;\n    \\<^term>\\<open>A\\<close> may be flexible.\\<close>\n  by auto\n\nlemma UnionE [elim!]: \"A \\<in> \\<Union>C \\<Longrightarrow> (\\<And>X. A \\<in> X \\<Longrightarrow> X \\<in> C \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by auto\n\nlemma Union_upper: \"B \\<in> A \\<Longrightarrow> B \\<subseteq> \\<Union>A\"\n  by (fact Sup_upper)\n\nlemma Union_least: \"(\\<And>X. X \\<in> A \\<Longrightarrow> X \\<subseteq> C) \\<Longrightarrow> \\<Union>A \\<subseteq> C\"\n  by (fact Sup_least)\n\nlemma Union_empty: \"\\<Union>{} = {}\"\n  by (fact Sup_empty) (* already simp *)\n\nlemma Union_UNIV: \"\\<Union>UNIV = UNIV\"\n  by (fact Sup_UNIV) (* already simp *)\n\nlemma Union_insert: \"\\<Union>(insert a B) = a \\<union> \\<Union>B\"\n  by (fact Sup_insert) (* already simp *)\n\nlemma Union_Un_distrib [simp]: \"\\<Union>(A \\<union> B) = \\<Union>A \\<union> \\<Union>B\"\n  by (fact Sup_union_distrib)\n\nlemma Union_Int_subset: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>A \\<inter> \\<Union>B\"\n  by (fact Sup_inter_less_eq)\n\nlemma Union_empty_conv: \"(\\<Union>A = {}) \\<longleftrightarrow> (\\<forall>x\\<in>A. x = {})\"\n  by (fact Sup_bot_conv) (* already simp *)\n\nlemma empty_Union_conv: \"({} = \\<Union>A) \\<longleftrightarrow> (\\<forall>x\\<in>A. x = {})\"\n  by (fact Sup_bot_conv) (* already simp *)\n\nlemma subset_Pow_Union: \"A \\<subseteq> Pow (\\<Union>A)\"\n  by blast\n\nlemma Union_Pow_eq [simp]: \"\\<Union>(Pow A) = A\"\n  by blast\n\nlemma Union_mono: \"A \\<subseteq> B \\<Longrightarrow> \\<Union>A \\<subseteq> \\<Union>B\"\n  by (fact Sup_subset_mono)\n\nlemma Union_subsetI: \"(\\<And>x. x \\<in> A \\<Longrightarrow> \\<exists>y. y \\<in> B \\<and> x \\<subseteq> y) \\<Longrightarrow> \\<Union>A \\<subseteq> \\<Union>B\"\n  by blast\n\nlemma disjnt_inj_on_iff:\n     \"\\<lbrakk>inj_on f (\\<Union>\\<A>); X \\<in> \\<A>; Y \\<in> \\<A>\\<rbrakk> \\<Longrightarrow> disjnt (f ` X) (f ` Y) \\<longleftrightarrow> disjnt X Y\"\n  apply (auto simp: disjnt_def)\n  using inj_on_eq_iff by fastforce\n\nlemma disjnt_Union1 [simp]: \"disjnt (\\<Union>\\<A>) B \\<longleftrightarrow> (\\<forall>A \\<in> \\<A>. disjnt A B)\"\n  by (auto simp: disjnt_def)\n\nlemma disjnt_Union2 [simp]: \"disjnt B (\\<Union>\\<A>) \\<longleftrightarrow> (\\<forall>A \\<in> \\<A>. disjnt B A)\"\n  by (auto simp: disjnt_def)\n\n\nsubsubsection \\<open>Unions of families\\<close>\n\nsyntax (ASCII)\n  \"_UNION1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3UN _./ _)\" [0, 10] 10)\n  \"_UNION\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3UN _:_./ _)\" [0, 0, 10] 10)\n\nsyntax\n  \"_UNION1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3\\<Union>_./ _)\" [0, 10] 10)\n  \"_UNION\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3\\<Union>_\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax (latex output)\n  \"_UNION1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3\\<Union>(\\<open>unbreakable\\<close>\\<^bsub>_\\<^esub>)/ _)\" [0, 10] 10)\n  \"_UNION\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3\\<Union>(\\<open>unbreakable\\<close>\\<^bsub>_\\<in>_\\<^esub>)/ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<Union>x y. f\"   \\<rightleftharpoons> \"\\<Union>x. \\<Union>y. f\"\n  \"\\<Union>x. f\"     \\<rightleftharpoons> \"\\<Union>(CONST range (\\<lambda>x. f))\"\n  \"\\<Union>x\\<in>A. f\"   \\<rightleftharpoons> \"CONST Union ((\\<lambda>x. f) ` A)\"\n\ntext \\<open>\n  Note the difference between ordinary syntax of indexed\n  unions and intersections (e.g.\\ \\<open>\\<Union>a\\<^sub>1\\<in>A\\<^sub>1. B\\<close>)\n  and their \\LaTeX\\ rendition: \\<^term>\\<open>\\<Union>a\\<^sub>1\\<in>A\\<^sub>1. B\\<close>.\n\\<close>\n\nlemma disjoint_UN_iff: \"disjnt A (\\<Union>i\\<in>I. B i) \\<longleftrightarrow> (\\<forall>i\\<in>I. disjnt A (B i))\"\n  by (auto simp: disjnt_def)\n\nlemma UNION_eq: \"(\\<Union>x\\<in>A. B x) = {y. \\<exists>x\\<in>A. y \\<in> B x}\"\n  by (auto intro!: SUP_eqI)\n\nlemma bind_UNION [code]: \"Set.bind A f = \\<Union>(f ` A)\"\n  by (simp add: bind_def UNION_eq)\n\nlemma member_bind [simp]: \"x \\<in> Set.bind A f \\<longleftrightarrow> x \\<in> \\<Union>(f ` A)\"\n  by (simp add: bind_UNION)\n\nlemma Union_SetCompr_eq: \"\\<Union>{f x| x. P x} = {a. \\<exists>x. P x \\<and> a \\<in> f x}\"\n  by blast\n\nlemma UN_iff [simp]: \"b \\<in> (\\<Union>x\\<in>A. B x) \\<longleftrightarrow> (\\<exists>x\\<in>A. b \\<in> B x)\"\n  using Union_iff [of _ \"B ` A\"] by simp\n\nlemma UN_I [intro]: \"a \\<in> A \\<Longrightarrow> b \\<in> B a \\<Longrightarrow> b \\<in> (\\<Union>x\\<in>A. B x)\"\n  \\<comment> \\<open>The order of the premises presupposes that \\<^term>\\<open>A\\<close> is rigid;\n    \\<^term>\\<open>b\\<close> may be flexible.\\<close>\n  by auto\n\nlemma UN_E [elim!]: \"b \\<in> (\\<Union>x\\<in>A. B x) \\<Longrightarrow> (\\<And>x. x\\<in>A \\<Longrightarrow> b \\<in> B x \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by auto\n\nlemma UN_upper: \"a \\<in> A \\<Longrightarrow> B a \\<subseteq> (\\<Union>x\\<in>A. B x)\"\n  by (fact SUP_upper)\n\nlemma UN_least: \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> C) \\<Longrightarrow> (\\<Union>x\\<in>A. B x) \\<subseteq> C\"\n  by (fact SUP_least)\n\nlemma Collect_bex_eq: \"{x. \\<exists>y\\<in>A. P x y} = (\\<Union>y\\<in>A. {x. P x y})\"\n  by blast\n\nlemma UN_insert_distrib: \"u \\<in> A \\<Longrightarrow> (\\<Union>x\\<in>A. insert a (B x)) = insert a (\\<Union>x\\<in>A. B x)\"\n  by blast\n\nlemma UN_empty: \"(\\<Union>x\\<in>{}. B x) = {}\"\n  by (fact SUP_empty)\n\nlemma UN_empty2: \"(\\<Union>x\\<in>A. {}) = {}\"\n  by (fact SUP_bot) (* already simp *)\n\nlemma UN_absorb: \"k \\<in> I \\<Longrightarrow> A k \\<union> (\\<Union>i\\<in>I. A i) = (\\<Union>i\\<in>I. A i)\"\n  by (fact SUP_absorb)\n\nlemma UN_insert [simp]: \"(\\<Union>x\\<in>insert a A. B x) = B a \\<union> \\<Union>(B ` A)\"\n  by (fact SUP_insert)\n\nlemma UN_Un [simp]: \"(\\<Union>i \\<in> A \\<union> B. M i) = (\\<Union>i\\<in>A. M i) \\<union> (\\<Union>i\\<in>B. M i)\"\n  by (fact SUP_union)\n\nlemma UN_UN_flatten: \"(\\<Union>x \\<in> (\\<Union>y\\<in>A. B y). C x) = (\\<Union>y\\<in>A. \\<Union>x\\<in>B y. C x)\"\n  by blast\n\nlemma UN_subset_iff: \"((\\<Union>i\\<in>I. A i) \\<subseteq> B) = (\\<forall>i\\<in>I. A i \\<subseteq> B)\"\n  by (fact SUP_le_iff)\n\nlemma UN_constant [simp]: \"(\\<Union>y\\<in>A. c) = (if A = {} then {} else c)\"\n  by (fact SUP_constant)\n\nlemma UNION_singleton_eq_range: \"(\\<Union>x\\<in>A. {f x}) = f ` A\"\n  by blast\n\nlemma image_Union: \"f ` \\<Union>S = (\\<Union>x\\<in>S. f ` x)\"\n  by blast\n\nlemma UNION_empty_conv:\n  \"{} = (\\<Union>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = {})\"\n  \"(\\<Union>x\\<in>A. B x) = {} \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = {})\"\n  by (fact SUP_bot_conv)+ (* already simp *)\n\nlemma Collect_ex_eq: \"{x. \\<exists>y. P x y} = (\\<Union>y. {x. P x y})\"\n  by blast\n\nlemma ball_UN: \"(\\<forall>z \\<in> \\<Union>(B ` A). P z) \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>z \\<in> B x. P z)\"\n  by blast\n\nlemma bex_UN: \"(\\<exists>z \\<in> \\<Union>(B ` A). P z) \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<exists>z\\<in>B x. P z)\"\n  by blast\n\nlemma Un_eq_UN: \"A \\<union> B = (\\<Union>b. if b then A else B)\"\n  by safe (auto simp add: if_split_mem2)\n\nlemma UN_bool_eq: \"(\\<Union>b. A b) = (A True \\<union> A False)\"\n  by (fact SUP_UNIV_bool_expand)\n\nlemma UN_Pow_subset: \"(\\<Union>x\\<in>A. Pow (B x)) \\<subseteq> Pow (\\<Union>x\\<in>A. B x)\"\n  by blast\n\nlemma UN_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<subseteq> g x) \\<Longrightarrow>\n    (\\<Union>x\\<in>A. f x) \\<subseteq> (\\<Union>x\\<in>B. g x)\"\n  by (fact SUP_subset_mono)\n\nlemma vimage_Union: \"f -` (\\<Union>A) = (\\<Union>X\\<in>A. f -` X)\"\n  by blast\n\nlemma vimage_UN: \"f -` (\\<Union>x\\<in>A. B x) = (\\<Union>x\\<in>A. f -` B x)\"\n  by blast\n\nlemma vimage_eq_UN: \"f -` B = (\\<Union>y\\<in>B. f -` {y})\"\n  \\<comment> \\<open>NOT suitable for rewriting\\<close>\n  by blast\n\nlemma image_UN: \"f ` \\<Union>(B ` A) = (\\<Union>x\\<in>A. f ` B x)\"\n  by blast\n\nlemma UN_singleton [simp]: \"(\\<Union>x\\<in>A. {x}) = A\"\n  by blast\n\nlemma inj_on_image: \"inj_on f (\\<Union>A) \\<Longrightarrow> inj_on ((`) f) A\"\n  unfolding inj_on_def by blast\n\n\nsubsubsection \\<open>Distributive laws\\<close>\n\nlemma Int_Union: \"A \\<inter> \\<Union>B = (\\<Union>C\\<in>B. A \\<inter> C)\"\n  by blast\n\nlemma Un_Inter: \"A \\<union> \\<Inter>B = (\\<Inter>C\\<in>B. A \\<union> C)\"\n  by blast\n\nlemma Int_Union2: \"\\<Union>B \\<inter> A = (\\<Union>C\\<in>B. C \\<inter> A)\"\n  by blast\n\nlemma INT_Int_distrib: \"(\\<Inter>i\\<in>I. A i \\<inter> B i) = (\\<Inter>i\\<in>I. A i) \\<inter> (\\<Inter>i\\<in>I. B i)\"\n  by (rule sym) (rule INF_inf_distrib)\n\nlemma UN_Un_distrib: \"(\\<Union>i\\<in>I. A i \\<union> B i) = (\\<Union>i\\<in>I. A i) \\<union> (\\<Union>i\\<in>I. B i)\"\n  by (rule sym) (rule SUP_sup_distrib)\n\nlemma Int_Inter_image: \"(\\<Inter>x\\<in>C. A x \\<inter> B x) = \\<Inter>(A ` C) \\<inter> \\<Inter>(B ` C)\"  (* FIXME drop *)\n  by (simp add: INT_Int_distrib)\n\nlemma Int_Inter_eq: \"A \\<inter> \\<Inter>\\<B> = (if \\<B>={} then A else (\\<Inter>B\\<in>\\<B>. A \\<inter> B))\"\n                    \"\\<Inter>\\<B> \\<inter> A = (if \\<B>={} then A else (\\<Inter>B\\<in>\\<B>. B \\<inter> A))\"\n  by auto\n\nlemma Un_Union_image: \"(\\<Union>x\\<in>C. A x \\<union> B x) = \\<Union>(A ` C) \\<union> \\<Union>(B ` C)\"  (* FIXME drop *)\n  \\<comment> \\<open>Devlin, Fundamentals of Contemporary Set Theory, page 12, exercise 5:\\<close>\n  \\<comment> \\<open>Union of a family of unions\\<close>\n  by (simp add: UN_Un_distrib)\n\nlemma Un_INT_distrib: \"B \\<union> (\\<Inter>i\\<in>I. A i) = (\\<Inter>i\\<in>I. B \\<union> A i)\"\n  by blast\n\nlemma Int_UN_distrib: \"B \\<inter> (\\<Union>i\\<in>I. A i) = (\\<Union>i\\<in>I. B \\<inter> A i)\"\n  \\<comment> \\<open>Halmos, Naive Set Theory, page 35.\\<close>\n  by blast\n\nlemma Int_UN_distrib2: \"(\\<Union>i\\<in>I. A i) \\<inter> (\\<Union>j\\<in>J. B j) = (\\<Union>i\\<in>I. \\<Union>j\\<in>J. A i \\<inter> B j)\"\n  by blast\n\nlemma Un_INT_distrib2: \"(\\<Inter>i\\<in>I. A i) \\<union> (\\<Inter>j\\<in>J. B j) = (\\<Inter>i\\<in>I. \\<Inter>j\\<in>J. A i \\<union> B j)\"\n  by blast\n\nlemma Union_disjoint: \"(\\<Union>C \\<inter> A = {}) \\<longleftrightarrow> (\\<forall>B\\<in>C. B \\<inter> A = {})\"\n  by blast\n\nlemma SUP_UNION: \"(\\<Squnion>x\\<in>(\\<Union>y\\<in>A. g y). f x) = (\\<Squnion>y\\<in>A. \\<Squnion>x\\<in>g y. f x :: _ :: complete_lattice)\"\n  by (rule order_antisym) (blast intro: SUP_least SUP_upper2)+\n\n\nsubsection \\<open>Injections and bijections\\<close>\n\nlemma inj_on_Inter: \"S \\<noteq> {} \\<Longrightarrow> (\\<And>A. A \\<in> S \\<Longrightarrow> inj_on f A) \\<Longrightarrow> inj_on f (\\<Inter>S)\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_INTER: \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> inj_on f (A i)) \\<Longrightarrow> inj_on f (\\<Inter>i \\<in> I. A i)\"\n  unfolding inj_on_def by safe simp\n\nlemma inj_on_UNION_chain:\n  assumes chain: \"\\<And>i j. i \\<in> I \\<Longrightarrow> j \\<in> I \\<Longrightarrow> A i \\<le> A j \\<or> A j \\<le> A i\"\n    and inj: \"\\<And>i. i \\<in> I \\<Longrightarrow> inj_on f (A i)\"\n  shows \"inj_on f (\\<Union>i \\<in> I. A i)\"\nproof -\n  have \"x = y\"\n    if *: \"i \\<in> I\" \"j \\<in> I\"\n    and **: \"x \\<in> A i\" \"y \\<in> A j\"\n    and ***: \"f x = f y\"\n    for i j x y\n    using chain [OF *]\n  proof\n    assume \"A i \\<le> A j\"\n    with ** have \"x \\<in> A j\" by auto\n    with inj * ** *** show ?thesis\n      by (auto simp add: inj_on_def)\n  next\n    assume \"A j \\<le> A i\"\n    with ** have \"y \\<in> A i\" by auto\n    with inj * ** *** show ?thesis\n      by (auto simp add: inj_on_def)\n  qed\n  then show ?thesis\n    by (unfold inj_on_def UNION_eq) auto\nqed\n\nlemma bij_betw_UNION_chain:\n  assumes chain: \"\\<And>i j. i \\<in> I \\<Longrightarrow> j \\<in> I \\<Longrightarrow> A i \\<le> A j \\<or> A j \\<le> A i\"\n    and bij: \"\\<And>i. i \\<in> I \\<Longrightarrow> bij_betw f (A i) (A' i)\"\n  shows \"bij_betw f (\\<Union>i \\<in> I. A i) (\\<Union>i \\<in> I. A' i)\"\n  unfolding bij_betw_def\nproof safe\n  have \"\\<And>i. i \\<in> I \\<Longrightarrow> inj_on f (A i)\"\n    using bij bij_betw_def[of f] by auto\n  then show \"inj_on f (\\<Union>(A ` I))\"\n    using chain inj_on_UNION_chain[of I A f] by auto\nnext\n  fix i x\n  assume *: \"i \\<in> I\" \"x \\<in> A i\"\n  with bij have \"f x \\<in> A' i\"\n    by (auto simp: bij_betw_def)\n  with * show \"f x \\<in> \\<Union>(A' ` I)\" by blast\nnext\n  fix i x'\n  assume *: \"i \\<in> I\" \"x' \\<in> A' i\"\n  with bij have \"\\<exists>x \\<in> A i. x' = f x\"\n    unfolding bij_betw_def by blast\n  with * have \"\\<exists>j \\<in> I. \\<exists>x \\<in> A j. x' = f x\"\n    by blast\n  then show \"x' \\<in> f ` \\<Union>(A ` I)\"\n    by blast\nqed\n\n(*injectivity's required.  Left-to-right inclusion holds even if A is empty*)\nlemma image_INT: \"inj_on f C \\<Longrightarrow> \\<forall>x\\<in>A. B x \\<subseteq> C \\<Longrightarrow> j \\<in> A \\<Longrightarrow> f ` (\\<Inter>(B ` A)) = (\\<Inter>x\\<in>A. f ` B x)\"\n  by (auto simp add: inj_on_def) blast\n\nlemma bij_image_INT: \"bij f \\<Longrightarrow> f ` (\\<Inter>(B ` A)) = (\\<Inter>x\\<in>A. f ` B x)\"\n  by (auto simp: bij_def inj_def surj_def) blast\n\nlemma UNION_fun_upd: \"\\<Union>(A(i := B) ` J) = \\<Union>(A ` (J - {i})) \\<union> (if i \\<in> J then B else {})\"\n  by (auto simp add: set_eq_iff)\n\nlemma bij_betw_Pow:\n  assumes \"bij_betw f A B\"\n  shows \"bij_betw (image f) (Pow A) (Pow B)\"\nproof -\n  from assms have \"inj_on f A\"\n    by (rule bij_betw_imp_inj_on)\n  then have \"inj_on f (\\<Union>(Pow A))\"\n    by simp\n  then have \"inj_on (image f) (Pow A)\"\n    by (rule inj_on_image)\n  then have \"bij_betw (image f) (Pow A) (image f ` Pow A)\"\n    by (rule inj_on_imp_bij_betw)\n  moreover from assms have \"f ` A = B\"\n    by (rule bij_betw_imp_surj_on)\n  then have \"image f ` Pow A = Pow B\"\n    by (rule image_Pow_surj)\n  ultimately show ?thesis by simp\nqed\n\n\nsubsubsection \\<open>Complement\\<close>\n\nlemma Compl_INT [simp]: \"- (\\<Inter>x\\<in>A. B x) = (\\<Union>x\\<in>A. -B x)\"\n  by blast\n\nlemma Compl_UN [simp]: \"- (\\<Union>x\\<in>A. B x) = (\\<Inter>x\\<in>A. -B x)\"\n  by blast\n\nsubsubsection \\<open>Miniscoping and maxiscoping\\<close>\n\ntext \\<open>\\<^medskip> Miniscoping: pushing in quantifiers and big Unions and Intersections.\\<close>\n\nlemma UN_simps [simp]:\n  \"\\<And>a B C. (\\<Union>x\\<in>C. insert a (B x)) = (if C={} then {} else insert a (\\<Union>x\\<in>C. B x))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x \\<union> B) = ((if C={} then {} else (\\<Union>x\\<in>C. A x) \\<union> B))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A \\<union> B x) = ((if C={} then {} else A \\<union> (\\<Union>x\\<in>C. B x)))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x \\<inter> B) = ((\\<Union>x\\<in>C. A x) \\<inter> B)\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A \\<inter> B x) = (A \\<inter>(\\<Union>x\\<in>C. B x))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x - B) = ((\\<Union>x\\<in>C. A x) - B)\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A - B x) = (A - (\\<Inter>x\\<in>C. B x))\"\n  \"\\<And>A B. (\\<Union>x\\<in>\\<Union>A. B x) = (\\<Union>y\\<in>A. \\<Union>x\\<in>y. B x)\"\n  \"\\<And>A B C. (\\<Union>z\\<in>(\\<Union>(B ` A)). C z) = (\\<Union>x\\<in>A. \\<Union>z\\<in>B x. C z)\"\n  \"\\<And>A B f. (\\<Union>x\\<in>f`A. B x) = (\\<Union>a\\<in>A. B (f a))\"\n  by auto\n\nlemma INT_simps [simp]:\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x \\<inter> B) = (if C={} then UNIV else (\\<Inter>x\\<in>C. A x) \\<inter> B)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A \\<inter> B x) = (if C={} then UNIV else A \\<inter>(\\<Inter>x\\<in>C. B x))\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x - B) = (if C={} then UNIV else (\\<Inter>x\\<in>C. A x) - B)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A - B x) = (if C={} then UNIV else A - (\\<Union>x\\<in>C. B x))\"\n  \"\\<And>a B C. (\\<Inter>x\\<in>C. insert a (B x)) = insert a (\\<Inter>x\\<in>C. B x)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x \\<union> B) = ((\\<Inter>x\\<in>C. A x) \\<union> B)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A \\<union> B x) = (A \\<union> (\\<Inter>x\\<in>C. B x))\"\n  \"\\<And>A B. (\\<Inter>x\\<in>\\<Union>A. B x) = (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B x)\"\n  \"\\<And>A B C. (\\<Inter>z\\<in>(\\<Union>(B ` A)). C z) = (\\<Inter>x\\<in>A. \\<Inter>z\\<in>B x. C z)\"\n  \"\\<And>A B f. (\\<Inter>x\\<in>f`A. B x) = (\\<Inter>a\\<in>A. B (f a))\"\n  by auto\n\nlemma UN_ball_bex_simps [simp]:\n  \"\\<And>A P. (\\<forall>x\\<in>\\<Union>A. P x) \\<longleftrightarrow> (\\<forall>y\\<in>A. \\<forall>x\\<in>y. P x)\"\n  \"\\<And>A B P. (\\<forall>x\\<in>(\\<Union>(B ` A)). P x) = (\\<forall>a\\<in>A. \\<forall>x\\<in> B a. P x)\"\n  \"\\<And>A P. (\\<exists>x\\<in>\\<Union>A. P x) \\<longleftrightarrow> (\\<exists>y\\<in>A. \\<exists>x\\<in>y. P x)\"\n  \"\\<And>A B P. (\\<exists>x\\<in>(\\<Union>(B ` A)). P x) \\<longleftrightarrow> (\\<exists>a\\<in>A. \\<exists>x\\<in>B a. P x)\"\n  by auto\n\n\ntext \\<open>\\<^medskip> Maxiscoping: pulling out big Unions and Intersections.\\<close>\n\nlemma UN_extend_simps:\n  \"\\<And>a B C. insert a (\\<Union>x\\<in>C. B x) = (if C={} then {a} else (\\<Union>x\\<in>C. insert a (B x)))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x) \\<union> B = (if C={} then B else (\\<Union>x\\<in>C. A x \\<union> B))\"\n  \"\\<And>A B C. A \\<union> (\\<Union>x\\<in>C. B x) = (if C={} then A else (\\<Union>x\\<in>C. A \\<union> B x))\"\n  \"\\<And>A B C. ((\\<Union>x\\<in>C. A x) \\<inter> B) = (\\<Union>x\\<in>C. A x \\<inter> B)\"\n  \"\\<And>A B C. (A \\<inter> (\\<Union>x\\<in>C. B x)) = (\\<Union>x\\<in>C. A \\<inter> B x)\"\n  \"\\<And>A B C. ((\\<Union>x\\<in>C. A x) - B) = (\\<Union>x\\<in>C. A x - B)\"\n  \"\\<And>A B C. (A - (\\<Inter>x\\<in>C. B x)) = (\\<Union>x\\<in>C. A - B x)\"\n  \"\\<And>A B. (\\<Union>y\\<in>A. \\<Union>x\\<in>y. B x) = (\\<Union>x\\<in>\\<Union>A. B x)\"\n  \"\\<And>A B C. (\\<Union>x\\<in>A. \\<Union>z\\<in>B x. C z) = (\\<Union>z\\<in>(\\<Union>(B ` A)). C z)\"\n  \"\\<And>A B f. (\\<Union>a\\<in>A. B (f a)) = (\\<Union>x\\<in>f`A. B x)\"\n  by auto\n\nlemma INT_extend_simps:\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x) \\<inter> B = (if C={} then B else (\\<Inter>x\\<in>C. A x \\<inter> B))\"\n  \"\\<And>A B C. A \\<inter> (\\<Inter>x\\<in>C. B x) = (if C={} then A else (\\<Inter>x\\<in>C. A \\<inter> B x))\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x) - B = (if C={} then UNIV - B else (\\<Inter>x\\<in>C. A x - B))\"\n  \"\\<And>A B C. A - (\\<Union>x\\<in>C. B x) = (if C={} then A else (\\<Inter>x\\<in>C. A - B x))\"\n  \"\\<And>a B C. insert a (\\<Inter>x\\<in>C. B x) = (\\<Inter>x\\<in>C. insert a (B x))\"\n  \"\\<And>A B C. ((\\<Inter>x\\<in>C. A x) \\<union> B) = (\\<Inter>x\\<in>C. A x \\<union> B)\"\n  \"\\<And>A B C. A \\<union> (\\<Inter>x\\<in>C. B x) = (\\<Inter>x\\<in>C. A \\<union> B x)\"\n  \"\\<And>A B. (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B x) = (\\<Inter>x\\<in>\\<Union>A. B x)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>A. \\<Inter>z\\<in>B x. C z) = (\\<Inter>z\\<in>(\\<Union>(B ` A)). C z)\"\n  \"\\<And>A B f. (\\<Inter>a\\<in>A. B (f a)) = (\\<Inter>x\\<in>f`A. B x)\"\n  by auto\n\ntext \\<open>Finally\\<close>\n\nlemmas mem_simps =\n  insert_iff empty_iff Un_iff Int_iff Compl_iff Diff_iff\n  mem_Collect_eq UN_iff Union_iff INT_iff Inter_iff\n  \\<comment> \\<open>Each of these has ALREADY been added \\<open>[simp]\\<close> above.\\<close>\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Complete_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.8774767858797979, "lm_q1q2_score": 0.7714308798708757}}
{"text": "(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Hermitean matrices\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Hermitean matrices over $\\mathbb{C}$ generalize symmetric matrices over $\\mathbb{R}$. Quadratic\nforms with Hermitean matrices represent circles and lines in the extended complex plane (when\napplied to homogenous coordinates).\\<close>\n\ntheory Hermitean_Matrices\nimports Unitary_Matrices\nbegin\n\ndefinition hermitean :: \"complex_mat \\<Rightarrow> bool\" where\n \"hermitean A \\<longleftrightarrow> mat_adj A = A\"\n\nlemma hermitean_transpose:\n  shows \"hermitean A \\<longleftrightarrow> mat_transpose A = mat_cnj A\"\n  unfolding hermitean_def\n  by (cases A) (auto simp add: mat_adj_def mat_cnj_def)\n\ntext \\<open>Characterization of 2x2 Hermitean matrices elements. \nAll 2x2 Hermitean matrices are of the form \n$$\n\\left(\n\\begin{array}{cc}\nA & B\\\\\n\\overline{B} & D\n\\end{array}\n\\right),\n$$\nfor real $A$ and $D$ and complex $B$.\n\\<close>\n\nlemma hermitean_mk_circline [simp]: \n  shows \"hermitean (cor A, B, cnj B, cor D)\"\n  unfolding hermitean_def mat_adj_def mat_cnj_def\n  by simp\n\n\n\nlemma hermitean_elems:\n  assumes \"hermitean (A, B, C, D)\"\n  shows \"is_real A\" and \"is_real D\" and \"B = cnj C\" and \"cnj B = C\"\n  using assms eq_cnj_iff_real[of A] eq_cnj_iff_real[of D]\n  by (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\n\ntext \\<open>Operations that preserve the Hermitean property\\<close>\n\nlemma hermitean_mat_cnj: \n  shows \"hermitean H \\<longleftrightarrow> hermitean (mat_cnj H)\"\n  by (cases H) (auto simp add:  hermitean_def mat_adj_def mat_cnj_def)\n\nlemma hermitean_mult_real:\n  assumes \"hermitean H\"\n  shows \"hermitean ((cor k) *\\<^sub>s\\<^sub>m H)\"\n  using assms\n  unfolding hermitean_def\n  by simp\n\nlemma hermitean_congruence:\n  assumes \"hermitean H\"\n  shows \"hermitean (congruence M H)\"\n  using assms\n  unfolding hermitean_def\n  by (auto simp add: mult_mm_assoc)\n\ntext \\<open>Identity matrix is Hermitean\\<close>\n\nlemma hermitean_eye [simp]:\n  shows \"hermitean eye\"\n  by (auto simp add:  hermitean_def mat_adj_def mat_cnj_def)\n\nlemma hermitean_eye' [simp]: \n  shows \"hermitean (1, 0, 0, 1)\"\n  by (auto simp add:  hermitean_def mat_adj_def mat_cnj_def)\n\ntext \\<open>Unit circle matrix is Hermitean\\<close>\n\nlemma hermitean_unit_circle [simp]:\n  shows \"hermitean (1, 0, 0, -1)\"\n  by (auto simp add:  hermitean_def mat_adj_def mat_cnj_def)\n\ntext \\<open>Hermitean matrices have real determinant\\<close>\nlemma mat_det_hermitean_real:\n  assumes \"hermitean A\"\n  shows \"is_real (mat_det A)\"\n  using assms\n  unfolding hermitean_def\n  by (metis eq_cnj_iff_real mat_det_adj)\n\ntext \\<open>Zero matrix is the only Hermitean matrix with both determinant and trace equal\nto zero\\<close>\nlemma hermitean_det_zero_trace_zero:\n  assumes \"mat_det A = 0\" and \"mat_trace A = (0::complex)\" and \"hermitean A\"\n  shows \"A = mat_zero\"\nusing assms\nproof-\n  {\n    fix a d c\n    assume \"a * d = cnj c * c\" \"a + d = 0\" \"cnj a = a\"\n    from \\<open>a + d = 0\\<close> have \"d = -a\"\n      by (metis add_eq_0_iff)\n    hence \"- (cor (Re a))\\<^sup>2  = (cor (cmod c))\\<^sup>2\"\n      using \\<open>cnj a = a\\<close> eq_cnj_iff_real[of a]\n      using \\<open>a*d = cnj c * c\\<close>\n      using complex_mult_cnj_cmod[of \"cnj c\"]\n      by (simp add: power2_eq_square)\n    hence \"- (Re a)\\<^sup>2 \\<ge> 0\"\n      using zero_le_power2[of \"cmod c\"]\n      by (metis Re_complex_of_real cor_squared of_real_minus)\n    hence \"a = 0\"\n      using zero_le_power2[of \"Re a\"]\n      using \\<open>cnj a = a\\<close>  eq_cnj_iff_real[of a]\n      by (simp add: complex_eq_if_Re_eq)\n  } note * = this\n  obtain a b c d where \"A = (a, b, c, d)\"\n    by (cases A) auto\n  thus ?thesis\n    using *[of a d c]  *[of d a c]\n    using assms \\<open>A = (a, b, c, d)\\<close>\n    by (auto simp add: hermitean_def mat_adj_def mat_cnj_def)\nqed\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Bilinear and quadratic forms with Hermitean matrices\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>A Hermitean matrix $(A, B, \\overline{B}, D)$, for real $A$ and $D$, gives rise to bilinear form\n$A\\cdot \\overline{v_{11}} \\cdot v_{21}+\\overline{B} \\cdot \\overline{v_{12}} \\cdot v_{21} +\nB \\cdot \\overline{v_{11}} \\cdot v_{22}+D\\cdot \\overline{v_{12}}\\cdot v_{22}$ (acting on vectors $(v_{11}, v_{12})$ and\n$(v_{21}, v_{22})$) and to the quadratic form $A \\cdot \\overline{v_1} \\cdot v_1+\\overline{B}\\cdot \\overline{v_2}\\cdot v_1 +\nB\\cdot \\overline{v_1}\\cdot v_2 + D\\cdot \\overline{v_2} \\cdot v_2$ (acting on the vector $(v_1, v_2)$).\\<close>\n\nlemma bilinear_form_hermitean_commute:\n  assumes \"hermitean H\"\n  shows \"bilinear_form v1 v2 H = cnj (bilinear_form v2 v1 H)\"\nproof-\n  have \"v2 *\\<^sub>v\\<^sub>m mat_cnj H *\\<^sub>v\\<^sub>v vec_cnj v1 = vec_cnj v1 *\\<^sub>v\\<^sub>v (mat_adj H *\\<^sub>m\\<^sub>v v2)\"\n    by (subst mult_vv_commute, subst mult_mv_mult_vm, simp add: mat_adj_def mat_transpose_mat_cnj)\n  also\n  have \"\\<dots> = bilinear_form v1 v2 H\"\n    using assms\n    by (simp add: mult_vv_mv hermitean_def)\n  finally\n  show ?thesis\n    by (simp add: cnj_mult_vv vec_cnj_mult_vm)\nqed\n\nlemma quad_form_hermitean_real:\n  assumes \"hermitean H\"\n  shows \"is_real (quad_form z H)\"\n  using assms\n  by (subst eq_cnj_iff_real[symmetric])  (simp del: quad_form_def add: hermitean_def)\n\nlemma quad_form_vec_cnj_mat_cnj:\n  assumes \"hermitean H\"\n  shows \"quad_form (vec_cnj z) (mat_cnj H) = quad_form z H\"\n  using assms\n  using cnj_mult_vv cnj_quad_form hermitean_def vec_cnj_mult_vm by auto\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Eigenvalues, eigenvectors and diagonalization of Hermitean matrices\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Hermitean matrices have real eigenvalues\\<close>\nlemma hermitean_eigenval_real:\n  assumes \"hermitean H\" and \"eigenval k H\"\n  shows \"is_real k\"\nproof-\n  from assms obtain v where \"v \\<noteq> vec_zero\" \"H *\\<^sub>m\\<^sub>v v = k *\\<^sub>s\\<^sub>v v\"\n    unfolding eigenval_def\n    by blast\n  have \"k * (v *\\<^sub>v\\<^sub>v vec_cnj v) = (k *\\<^sub>s\\<^sub>v v) *\\<^sub>v\\<^sub>v (vec_cnj v)\"\n    by (simp add: mult_vv_scale_sv1)\n  also have \"... = (H *\\<^sub>m\\<^sub>v v) *\\<^sub>v\\<^sub>v (vec_cnj v)\"\n    using \\<open>H *\\<^sub>m\\<^sub>v v = k *\\<^sub>s\\<^sub>v v\\<close>\n    by simp\n  also have \"... =  v *\\<^sub>v\\<^sub>v (mat_transpose H *\\<^sub>m\\<^sub>v (vec_cnj v))\"\n    by (simp add: mult_mv_vv)\n  also have \"... = v *\\<^sub>v\\<^sub>v (vec_cnj (mat_cnj (mat_transpose H) *\\<^sub>m\\<^sub>v v))\"\n    by (simp add: vec_cnj_mult_mv)\n  also have \"... = v *\\<^sub>v\\<^sub>v (vec_cnj (H *\\<^sub>m\\<^sub>v v))\"\n    using \\<open>hermitean H\\<close>\n    by (simp add: hermitean_def mat_adj_def)\n  also have \"... = v *\\<^sub>v\\<^sub>v (vec_cnj (k *\\<^sub>s\\<^sub>v v))\"\n    using \\<open>H *\\<^sub>m\\<^sub>v v = k *\\<^sub>s\\<^sub>v v\\<close>\n    by simp\n  finally have \"k * (v *\\<^sub>v\\<^sub>v vec_cnj v) = cnj k * (v *\\<^sub>v\\<^sub>v vec_cnj v)\"\n    by (simp add: mult_vv_scale_sv2)\n  hence \"k = cnj k\"\n    using \\<open>v \\<noteq> vec_zero\\<close>\n    using scalsquare_vv_zero[of v]\n    by (simp add: mult_vv_commute)\n  thus ?thesis\n    by (metis eq_cnj_iff_real)\nqed\n\ntext \\<open>Non-diagonal Hermitean matrices have distinct eigenvalues\\<close>\nlemma hermitean_distinct_eigenvals:\n  assumes \"hermitean H\"\n  shows \"(\\<exists> k\\<^sub>1 k\\<^sub>2. k\\<^sub>1 \\<noteq> k\\<^sub>2 \\<and> eigenval k\\<^sub>1 H \\<and> eigenval k\\<^sub>2 H) \\<or> mat_diagonal H\"\nproof-\n  obtain A B C D where HH: \"H = (A, B, C, D)\"\n    by (cases H) auto\n  show ?thesis\n  proof (cases \"B = 0\")\n    case True\n    thus ?thesis\n      using \\<open>hermitean H\\<close> hermitean_elems[of A B C D] HH\n      by auto\n  next\n    case False\n    have \"(mat_trace H)\\<^sup>2 \\<noteq> 4 * mat_det H\"\n    proof (rule ccontr)\n      have \"C = cnj B\" \"is_real A\" \"is_real D\"\n        using hermitean_elems HH \\<open>hermitean H\\<close>\n        by auto\n      assume \"\\<not> ?thesis\"\n      hence \"(A + D)\\<^sup>2 = 4*(A*D - B*C)\"\n        using HH\n        by auto\n      hence \"(A - D)\\<^sup>2 = - 4*B*cnj B\"\n        using \\<open>C = cnj B\\<close>\n        by (auto simp add: power2_eq_square field_simps)\n      hence \"(A - D)\\<^sup>2 / cor ((cmod B)\\<^sup>2) = -4\"\n        using \\<open>B \\<noteq> 0\\<close> complex_mult_cnj_cmod[of B]\n        by (auto simp add: field_simps)\n      hence \"(Re A - Re D)\\<^sup>2 / (cmod B)\\<^sup>2 = -4\"\n        using \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>B \\<noteq> 0\\<close>\n        using Re_divide_real[of \"cor ((cmod B)\\<^sup>2)\" \"(A - D)\\<^sup>2\"]\n        by (auto simp add: power2_eq_square)\n      thus False\n        by (metis abs_neg_numeral abs_power2 neg_numeral_neq_numeral power_divide)\n    qed\n    show ?thesis\n      apply (rule disjI1)\n      apply (subst eigen_equation)+\n      using complex_quadratic_equation_monic_distinct_roots[of \"-mat_trace H\" \"mat_det H\"] \\<open>(mat_trace H)\\<^sup>2 \\<noteq> 4 * mat_det H\\<close>\n      by auto\n  qed\nqed\n\ntext \\<open>Eigenvectors corresponding to different eigenvalues of Hermitean matrices are\northogonal\\<close>\nlemma hermitean_ortho_eigenvecs:\n  assumes \"hermitean H\"\n  assumes \"eigenpair k1 v1 H\" and \"eigenpair k2 v2 H\" and \"k1 \\<noteq> k2\"\n  shows \"vec_cnj v2 *\\<^sub>v\\<^sub>v v1 = 0\" and \"vec_cnj v1 *\\<^sub>v\\<^sub>v v2 = 0\"\nproof-\n  from assms\n  have \"v1 \\<noteq> vec_zero\" \"H *\\<^sub>m\\<^sub>v v1 = k1 *\\<^sub>s\\<^sub>v v1\"\n       \"v2 \\<noteq> vec_zero\" \"H *\\<^sub>m\\<^sub>v v2 = k2 *\\<^sub>s\\<^sub>v v2\"\n    unfolding eigenpair_def\n    by auto\n  have real_k: \"is_real k1\" \"is_real k2\"\n    using assms\n    using hermitean_eigenval_real[of H k1]\n    using hermitean_eigenval_real[of H k2]\n    unfolding eigenpair_def eigenval_def\n    by blast+\n\n  have \"vec_cnj (H *\\<^sub>m\\<^sub>v v2) = vec_cnj (k2 *\\<^sub>s\\<^sub>v v2)\"\n    using \\<open>H *\\<^sub>m\\<^sub>v v2 = k2 *\\<^sub>s\\<^sub>v v2\\<close>\n    by auto\n  hence \"vec_cnj v2 *\\<^sub>v\\<^sub>m H  = k2 *\\<^sub>s\\<^sub>v vec_cnj v2\"\n    using \\<open>hermitean H\\<close> real_k eq_cnj_iff_real[of k1] eq_cnj_iff_real[of k2]\n    unfolding hermitean_def\n    by (cases H, cases v2) (auto simp add: mat_adj_def mat_cnj_def vec_cnj_def)\n  have \"k2 * (vec_cnj v2 *\\<^sub>v\\<^sub>v v1) = k1 * (vec_cnj v2 *\\<^sub>v\\<^sub>v v1)\"\n    using \\<open>H *\\<^sub>m\\<^sub>v v1 = k1 *\\<^sub>s\\<^sub>v v1\\<close>\n    using \\<open>vec_cnj v2 *\\<^sub>v\\<^sub>m H  = k2 *\\<^sub>s\\<^sub>v vec_cnj v2\\<close>\n    by (cases v1, cases v2, cases H)\n       (metis mult_vv_mv mult_vv_scale_sv1 mult_vv_scale_sv2)\n  thus \"vec_cnj v2 *\\<^sub>v\\<^sub>v v1 = 0\"\n    using \\<open>k1 \\<noteq> k2\\<close>\n    by simp\n  hence \"cnj (vec_cnj v2 *\\<^sub>v\\<^sub>v v1) = 0\"\n    by simp\n  thus \"vec_cnj v1 *\\<^sub>v\\<^sub>v v2 = 0\"\n    by (simp add: cnj_mult_vv mult_vv_commute)\nqed\n\ntext \\<open>Hermitean matrices are diagonizable by unitary matrices. Diagonal entries are\nreal and the sign of the determinant is preserved.\\<close>\nlemma hermitean_diagonizable:\n  assumes \"hermitean H\"\n  shows \"\\<exists> k1 k2 M. mat_det M \\<noteq> 0 \\<and> unitary M \\<and> congruence M H = (k1, 0, 0, k2) \\<and>\n                    is_real k1 \\<and> is_real k2 \\<and> sgn (Re k1 * Re k2) = sgn (Re (mat_det H))\"\nproof-\n  from assms\n  have \"(\\<exists>k\\<^sub>1 k\\<^sub>2. k\\<^sub>1 \\<noteq> k\\<^sub>2 \\<and> eigenval k\\<^sub>1 H \\<and> eigenval k\\<^sub>2 H) \\<or> mat_diagonal H\"\n    using hermitean_distinct_eigenvals[of H]\n    by simp\n  thus ?thesis\n  proof\n    assume \"\\<exists>k\\<^sub>1 k\\<^sub>2. k\\<^sub>1 \\<noteq> k\\<^sub>2 \\<and> eigenval k\\<^sub>1 H \\<and> eigenval k\\<^sub>2 H\"\n    then  obtain k1 k2 where  \"k1 \\<noteq> k2\" \"eigenval k1 H\" \"eigenval k2 H\"\n      using hermitean_distinct_eigenvals\n      by blast\n    then obtain v1 v2 where \"eigenpair k1 v1 H\" \"eigenpair k2 v2 H\"\n      \"v1 \\<noteq> vec_zero\" \"v2 \\<noteq> vec_zero\"\n      unfolding eigenval_def eigenpair_def\n      by blast\n    hence *: \"vec_cnj v2 *\\<^sub>v\\<^sub>v v1 = 0\" \"vec_cnj v1 *\\<^sub>v\\<^sub>v v2 = 0\"\n      using \\<open>k1 \\<noteq> k2\\<close> hermitean_ortho_eigenvecs \\<open>hermitean H\\<close>\n      by auto\n    obtain v11 v12 v21 v22 where vv: \"v1 = (v11, v12)\" \"v2 = (v21, v22)\"\n      by  (cases v1, cases v2) auto\n    let ?nv1' = \"vec_cnj v1 *\\<^sub>v\\<^sub>v v1\" and ?nv2' = \"vec_cnj v2 *\\<^sub>v\\<^sub>v v2\"\n    let ?nv1 = \"cor (sqrt (Re ?nv1'))\"\n    let ?nv2 = \"cor (sqrt (Re ?nv2'))\"\n    have \"?nv1' \\<noteq> 0\"  \"?nv2' \\<noteq> 0\"\n      using \\<open>v1 \\<noteq> vec_zero\\<close> \\<open>v2 \\<noteq> vec_zero\\<close> vv\n      by (simp add: scalsquare_vv_zero)+\n    moreover\n    have \"is_real ?nv1'\" \"is_real ?nv2'\"\n      using vv\n      by (auto simp add: vec_cnj_def)\n    ultimately\n    have \"?nv1 \\<noteq> 0\"  \"?nv2 \\<noteq> 0\"\n      using complex_eq_if_Re_eq\n      by auto\n    have \"Re (?nv1') \\<ge> 0\"  \"Re (?nv2') \\<ge> 0\"\n      using vv\n      by (auto simp add: vec_cnj_def)\n    obtain nv1 nv2 where \"nv1 = ?nv1\" \"nv1 \\<noteq> 0\"  \"nv2 = ?nv2\" \"nv2 \\<noteq> 0\"\n      using \\<open>?nv1 \\<noteq> 0\\<close>  \\<open>?nv2 \\<noteq> 0\\<close>\n      by auto\n    let ?M = \"(1/nv1 * v11, 1/nv2 * v21, 1/nv1 * v12, 1/nv2 * v22)\"\n\n    have \"is_real k1\" \"is_real k2\"\n      using  \\<open>eigenval k1 H\\<close> \\<open>eigenval k2 H\\<close> \\<open>hermitean H\\<close>\n      by (auto simp add: hermitean_eigenval_real)\n    moreover\n    have \"mat_det ?M \\<noteq> 0\"\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      hence \"v11 * v22 = v12 * v21\"\n        using \\<open>nv1 \\<noteq> 0\\<close> \\<open>nv2 \\<noteq> 0\\<close>\n        by (auto simp add: field_simps)\n      hence \"\\<exists> k. k \\<noteq> 0 \\<and> v2 = k *\\<^sub>s\\<^sub>v v1\"\n        using vv \\<open>v1 \\<noteq> vec_zero\\<close> \\<open>v2 \\<noteq> vec_zero\\<close>\n        apply auto\n        apply (rule_tac x=\"v21/v11\" in exI, force simp add: field_simps)\n        apply (rule_tac x=\"v21/v11\" in exI, force simp add: field_simps)\n        apply (rule_tac x=\"v22/v12\" in exI, force simp add: field_simps)\n        apply (rule_tac x=\"v22/v12\" in exI, force simp add: field_simps)\n        done\n      thus False\n        using * \\<open>vec_cnj v1 *\\<^sub>v\\<^sub>v v2 = 0\\<close> \\<open>vec_cnj v2 *\\<^sub>v\\<^sub>v v2 \\<noteq> 0\\<close> vv \\<open>?nv1' \\<noteq> 0\\<close>\n        by (metis mult_vv_scale_sv2 mult_zero_right)\n    qed\n    moreover\n    have \"unitary ?M\"\n    proof-\n      have **: \"cnj nv1 * nv1 = ?nv1'\"  \"cnj nv2 * nv2 = ?nv2'\"\n        using \\<open>nv1 = ?nv1\\<close> \\<open>nv1 \\<noteq> 0\\<close>  \\<open>nv2 = ?nv2\\<close> \\<open>nv2 \\<noteq> 0\\<close> \\<open>is_real ?nv1'\\<close> \\<open>is_real ?nv2'\\<close>\n        using \\<open>Re (?nv1') \\<ge> 0\\<close>  \\<open>Re (?nv2') \\<ge> 0\\<close>\n        by auto\n      have ***: \"cnj nv1 * nv2 \\<noteq> 0\"  \"cnj nv2 * nv1 \\<noteq> 0\"\n        using vv \\<open>nv1 = ?nv1\\<close> \\<open>nv1 \\<noteq> 0\\<close>  \\<open>nv2 = ?nv2\\<close> \\<open>nv2 \\<noteq> 0\\<close> \\<open>is_real ?nv1'\\<close> \\<open>is_real ?nv2'\\<close>\n        by auto           \n\n      show ?thesis\n        unfolding unitary_def\n        using vv ** \\<open>?nv1' \\<noteq> 0\\<close> \\<open>?nv2' \\<noteq> 0\\<close> * ***\n        unfolding mat_adj_def mat_cnj_def vec_cnj_def\n        by simp (metis (no_types, lifting) add_divide_distrib divide_eq_0_iff divide_eq_1_iff)\n    qed\n    moreover\n    have \"congruence ?M H = (k1, 0, 0, k2)\"\n    proof-\n      have \"mat_inv ?M *\\<^sub>m\\<^sub>m H *\\<^sub>m\\<^sub>m ?M = (k1, 0, 0, k2)\"\n      proof-\n        have *: \"H *\\<^sub>m\\<^sub>m ?M = ?M *\\<^sub>m\\<^sub>m (k1, 0, 0, k2)\"\n          using \\<open>eigenpair k1 v1 H\\<close> \\<open>eigenpair k2 v2 H\\<close> vv \\<open>?nv1 \\<noteq> 0\\<close> \\<open>?nv2 \\<noteq> 0\\<close>\n          unfolding eigenpair_def vec_cnj_def\n          by (cases H) (smt mult_mm.simps vec_map.simps add.right_neutral add_cancel_left_left distrib_left fst_mult_sv mult.commute mult.left_commute mult_mv.simps mult_zero_right prod.sel(1) prod.sel(2) snd_mult_sv)\n        show ?thesis\n          using mult_mm_inv_l[of ?M \"(k1, 0, 0, k2)\" \"H *\\<^sub>m\\<^sub>m ?M\", OF \\<open>mat_det ?M \\<noteq> 0\\<close> *[symmetric], symmetric]\n          by (simp add: mult_mm_assoc)\n      qed\n      moreover\n      have \"mat_inv ?M = mat_adj ?M\"\n        using \\<open>mat_det ?M \\<noteq> 0\\<close> \\<open>unitary ?M\\<close> mult_mm_inv_r[of ?M \"mat_adj ?M\" eye]\n        by (simp add: unitary_def)\n      ultimately\n      show ?thesis\n        by simp\n    qed\n    moreover\n    have \"sgn (Re k1 * Re k2) = sgn (Re (mat_det H))\"\n      using \\<open>congruence ?M H = (k1, 0, 0, k2)\\<close> \\<open>is_real k1\\<close> \\<open>is_real k2\\<close>\n      using Re_det_sgn_congruence[of ?M H] \\<open>mat_det ?M \\<noteq> 0\\<close> \\<open>hermitean H\\<close>\n      by simp\n    ultimately\n    show ?thesis\n      by (rule_tac x=\"k1\" in exI, rule_tac x=\"k2\" in exI, rule_tac x=\"?M\" in exI) simp\n  next\n    assume \"mat_diagonal H\"\n    then obtain A D where \"H = (A, 0, 0, D)\"\n      by (cases H) auto\n    moreover\n    hence \"is_real A\" \"is_real D\"\n      using \\<open>hermitean H\\<close> hermitean_elems[of A 0 0 D]\n      by auto\n    ultimately\n    show ?thesis\n      by (rule_tac x=\"A\" in exI, rule_tac x=\"D\" in exI, rule_tac x=\"eye\" in exI) (simp add: unitary_def mat_adj_def mat_cnj_def)\n  qed\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/Hermitean_Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.7713906355638664}}
{"text": "(*  Title:      HOL/ex/Primrec.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n\nAckermann's Function and the\nPrimitive Recursive Functions.\n*)\n\nsection \\<open>Primitive Recursive Functions\\<close>\n\ntheory Primrec imports Main begin\n\ntext \\<open>\n  Proof adopted from\n\n  Nora Szasz, A Machine Checked Proof that Ackermann's Function is not\n  Primitive Recursive, In: Huet \\& Plotkin, eds., Logical Environments\n  (CUP, 1993), 317-338.\n\n  See also E. Mendelson, Introduction to Mathematical Logic.  (Van\n  Nostrand, 1964), page 250, exercise 11.\n  \\medskip\n\\<close>\n\n\nsubsection\\<open>Ackermann's Function\\<close>\n\nfun ack :: \"nat => nat => nat\" where\n\"ack 0 n =  Suc n\" |\n\"ack (Suc m) 0 = ack m 1\" |\n\"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\n\ntext \\<open>PROPERTY A 4\\<close>\n\nlemma less_ack2 [iff]: \"j < ack i j\"\nby (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc2 [iff]: \"ack i j < ack i (Suc j)\"\nby (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5, monotonicity for \\<open><\\<close>\\<close>\n\nlemma ack_less_mono2: \"j < k ==> ack i j < ack i k\"\nusing lift_Suc_mono_less[where f = \"ack i\"]\nby (metis ack_less_ack_Suc2)\n\n\ntext \\<open>PROPERTY A 5', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono2: \"j \\<le> k ==> ack i j \\<le> ack i k\"\napply (simp add: order_le_less)\napply (blast intro: ack_less_mono2)\ndone\n\n\ntext \\<open>PROPERTY A 6\\<close>\n\nlemma ack2_le_ack1 [iff]: \"ack i (Suc j) \\<le> ack (Suc i) j\"\nproof (induct j)\n  case 0 show ?case by simp\nnext\n  case (Suc j) show ?case \n    by (auto intro!: ack_le_mono2)\n      (metis Suc Suc_leI Suc_lessI less_ack2 linorder_not_less)\nqed\n\n\ntext \\<open>PROPERTY A 7-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc1 [iff]: \"ack i j < ack (Suc i) j\"\nby (blast intro: ack_less_mono2 less_le_trans)\n\n\ntext \\<open>PROPERTY A 4'? Extra lemma needed for @{term CONSTANT} case, constant functions\\<close>\n\nlemma less_ack1 [iff]: \"i < ack i j\"\napply (induct i)\n apply simp_all\napply (blast intro: Suc_leI le_less_trans)\ndone\n\n\ntext \\<open>PROPERTY A 8\\<close>\n\nlemma ack_1 [simp]: \"ack (Suc 0) j = j + 2\"\nby (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 9.  The unary \\<open>1\\<close> and \\<open>2\\<close> in @{term\n  ack} is essential for the rewriting.\\<close>\n\nlemma ack_2 [simp]: \"ack (Suc (Suc 0)) j = 2 * j + 3\"\nby (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 7, monotonicity for \\<open><\\<close> [not clear why\n  @{thm [source] ack_1} is now needed first!]\\<close>\n\nlemma ack_less_mono1_aux: \"ack i k < ack (Suc (i +i')) k\"\nproof (induct i k rule: ack.induct)\n  case (1 n) show ?case\n    by (simp, metis ack_less_ack_Suc1 less_ack2 less_trans_Suc) \nnext\n  case (2 m) thus ?case by simp\nnext\n  case (3 m n) thus ?case\n    by (simp, blast intro: less_trans ack_less_mono2)\nqed\n\nlemma ack_less_mono1: \"i < j ==> ack i k < ack j k\"\napply (drule less_imp_Suc_add)\napply (blast intro!: ack_less_mono1_aux)\ndone\n\n\ntext \\<open>PROPERTY A 7', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono1: \"i \\<le> j ==> ack i k \\<le> ack j k\"\napply (simp add: order_le_less)\napply (blast intro: ack_less_mono1)\ndone\n\n\ntext \\<open>PROPERTY A 10\\<close>\n\nlemma ack_nest_bound: \"ack i1 (ack i2 j) < ack (2 + (i1 + i2)) j\"\napply simp\napply (rule ack2_le_ack1 [THEN [2] less_le_trans])\napply simp\napply (rule le_add1 [THEN ack_le_mono1, THEN le_less_trans])\napply (rule ack_less_mono1 [THEN ack_less_mono2])\napply (simp add: le_imp_less_Suc le_add2)\ndone\n\n\ntext \\<open>PROPERTY A 11\\<close>\n\nlemma ack_add_bound: \"ack i1 j + ack i2 j < ack (4 + (i1 + i2)) j\"\napply (rule less_trans [of _ \"ack (Suc (Suc 0)) (ack (i1 + i2) j)\"])\n prefer 2\n apply (rule ack_nest_bound [THEN less_le_trans])\n apply (simp add: Suc3_eq_add_3)\napply simp\napply (cut_tac i = i1 and m1 = i2 and k = j in le_add1 [THEN ack_le_mono1])\napply (cut_tac i = \"i2\" and m1 = i1 and k = j in le_add2 [THEN ack_le_mono1])\napply auto\ndone\n\n\ntext \\<open>PROPERTY A 12.  Article uses existential quantifier but the ALF proof\n  used \\<open>k + 4\\<close>.  Quantified version must be nested \\<open>\\<exists>k'. \\<forall>i j. ...\\<close>\\<close>\n\nlemma ack_add_bound2: \"i < ack k j ==> i + j < ack (4 + k) j\"\napply (rule less_trans [of _ \"ack k j + ack 0 j\"])\n apply (blast intro: add_less_mono) \napply (rule ack_add_bound [THEN less_le_trans])\napply simp\ndone\n\n\nsubsection\\<open>Primitive Recursive Functions\\<close>\n\nprimrec hd0 :: \"nat list => nat\" where\n\"hd0 [] = 0\" |\n\"hd0 (m # ms) = m\"\n\n\ntext \\<open>Inductive definition of the set of primitive recursive functions of type @{typ \"nat list => nat\"}.\\<close>\n\ndefinition SC :: \"nat list => nat\" where\n\"SC l = Suc (hd0 l)\"\n\ndefinition CONSTANT :: \"nat => nat list => nat\" where\n\"CONSTANT k l = k\"\n\ndefinition PROJ :: \"nat => nat list => nat\" where\n\"PROJ i l = hd0 (drop i l)\"\n\ndefinition\nCOMP :: \"(nat list => nat) => (nat list => nat) list => nat list => nat\"\nwhere \"COMP g fs l = g (map (\\<lambda>f. f l) fs)\"\n\ndefinition PREC :: \"(nat list => nat) => (nat list => nat) => nat list => nat\"\nwhere\n  \"PREC f g l =\n    (case l of\n      [] => 0\n    | x # l' => rec_nat (f l') (\\<lambda>y r. g (r # y # l')) x)\"\n  \\<comment> \\<open>Note that @{term g} is applied first to @{term \"PREC f g y\"} and then to @{term y}!\\<close>\n\ninductive PRIMREC :: \"(nat list => nat) => bool\" where\nSC: \"PRIMREC SC\" |\nCONSTANT: \"PRIMREC (CONSTANT k)\" |\nPROJ: \"PRIMREC (PROJ i)\" |\nCOMP: \"PRIMREC g ==> \\<forall>f \\<in> set fs. PRIMREC f ==> PRIMREC (COMP g fs)\" |\nPREC: \"PRIMREC f ==> PRIMREC g ==> PRIMREC (PREC f g)\"\n\n\ntext \\<open>Useful special cases of evaluation\\<close>\n\nlemma SC [simp]: \"SC (x # l) = Suc x\"\nby (simp add: SC_def)\n\nlemma CONSTANT [simp]: \"CONSTANT k l = k\"\nby (simp add: CONSTANT_def)\n\nlemma PROJ_0 [simp]: \"PROJ 0 (x # l) = x\"\nby (simp add: PROJ_def)\n\nlemma COMP_1 [simp]: \"COMP g [f] l = g [f l]\"\nby (simp add: COMP_def)\n\nlemma PREC_0 [simp]: \"PREC f g (0 # l) = f l\"\nby (simp add: PREC_def)\n\nlemma PREC_Suc [simp]: \"PREC f g (Suc x # l) = g (PREC f g (x # l) # x # l)\"\nby (simp add: PREC_def)\n\n\ntext \\<open>MAIN RESULT\\<close>\n\nlemma SC_case: \"SC l < ack 1 (sum_list l)\"\napply (unfold SC_def)\napply (induct l)\napply (simp_all add: le_add1 le_imp_less_Suc)\ndone\n\nlemma CONSTANT_case: \"CONSTANT k l < ack k (sum_list l)\"\nby simp\n\nlemma PROJ_case: \"PROJ i l < ack 0 (sum_list l)\"\napply (simp add: PROJ_def)\napply (induct l arbitrary:i)\n apply (auto simp add: drop_Cons split: nat.split)\napply (blast intro: less_le_trans le_add2)\ndone\n\n\ntext \\<open>@{term COMP} case\\<close>\n\nlemma COMP_map_aux: \"\\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (sum_list l))\n  ==> \\<exists>k. \\<forall>l. sum_list (map (\\<lambda>f. f l) fs) < ack k (sum_list l)\"\napply (induct fs)\n apply (rule_tac x = 0 in exI)\n apply simp\napply simp\napply (blast intro: add_less_mono ack_add_bound less_trans)\ndone\n\nlemma COMP_case:\n  \"\\<forall>l. g l < ack kg (sum_list l) ==>\n  \\<forall>f \\<in> set fs. PRIMREC f \\<and> (\\<exists>kf. \\<forall>l. f l < ack kf (sum_list l))\n  ==> \\<exists>k. \\<forall>l. COMP g fs  l < ack k (sum_list l)\"\napply (unfold COMP_def)\napply (drule COMP_map_aux)\napply (meson ack_less_mono2 ack_nest_bound less_trans)\ndone\n\n\ntext \\<open>@{term PREC} case\\<close>\n\nlemma PREC_case_aux:\n  \"\\<forall>l. f l + sum_list l < ack kf (sum_list l) ==>\n    \\<forall>l. g l + sum_list l < ack kg (sum_list l) ==>\n    PREC f g l + sum_list l < ack (Suc (kf + kg)) (sum_list l)\"\napply (unfold PREC_def)\napply (case_tac l)\n apply simp_all\n apply (blast intro: less_trans)\napply (erule ssubst) \\<comment> \\<open>get rid of the needless assumption\\<close>\napply (induct_tac a)\n apply simp_all\n txt \\<open>base case\\<close>\n apply (blast intro: le_add1 [THEN le_imp_less_Suc, THEN ack_less_mono1] less_trans)\ntxt \\<open>induction step\\<close>\napply (rule Suc_leI [THEN le_less_trans])\n apply (rule le_refl [THEN add_le_mono, THEN le_less_trans])\n  prefer 2\n  apply (erule spec)\n apply (simp add: le_add2)\ntxt \\<open>final part of the simplification\\<close>\napply simp\napply (rule le_add2 [THEN ack_le_mono1, THEN le_less_trans])\napply (erule ack_less_mono2)\ndone\n\nlemma PREC_case:\n  \"\\<forall>l. f l < ack kf (sum_list l) ==>\n    \\<forall>l. g l < ack kg (sum_list l) ==>\n    \\<exists>k. \\<forall>l. PREC f g l < ack k (sum_list l)\"\nby (metis le_less_trans [OF le_add1 PREC_case_aux] ack_add_bound2)\n\nlemma ack_bounds_PRIMREC: \"PRIMREC f ==> \\<exists>k. \\<forall>l. f l < ack k (sum_list l)\"\napply (erule PRIMREC.induct)\n    apply (blast intro: SC_case CONSTANT_case PROJ_case COMP_case PREC_case)+\ndone\n\ntheorem ack_not_PRIMREC:\n  \"\\<not> PRIMREC (\\<lambda>l. case l of [] => 0 | x # l' => ack x x)\"\napply (rule notI)\napply (erule ack_bounds_PRIMREC [THEN exE])\napply (rule less_irrefl [THEN notE])\napply (drule_tac x = \"[x]\" in spec)\napply simp\ndone\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/ex/Primrec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8757869900269366, "lm_q1q2_score": 0.7713906107852356}}
{"text": "(*<*)\n(*\n   Title:  Theory arith_hints.thy \n   Author: Maria Spichkova <maria.spichkova at rmit.edu.au>, 2013\n*)\n(*>*)\nsection \\<open>Auxiliary arithmetic lemmas\\<close>\n\ntheory arith_hints\nimports Main\nbegin\n\nlemma arith_mod_neq:\n  assumes \"a mod n \\<noteq> b mod n\"\n  shows \"a \\<noteq> b\"\n  using assms by blast\n\nlemma arith_mod_nzero: \n  fixes i :: nat\n  assumes \"i < n\" and \"0 < i\"\n  shows \"0 < (n * t + i) mod n\"\n  using assms by simp\n\n\n\nlemma arith_mult_neq_nzero2:\n  fixes i::nat\n  assumes \"i < n\"\n         and \"0 < i\"\n  shows \"n * t + i \\<noteq> n * q\"\nusing assms\nby (metis arith_mult_neq_nzero1 add.commute) \n\nlemma arith_mult_neq_nzero3:\n  fixes i::nat\n  assumes \"i < n\"\n         and \"0 < i\"\n  shows \"n + n * t + i \\<noteq> n * qc\"\nproof -\n   from assms have sg1: \"n *(Suc t) + i  \\<noteq> n * qc\"\n     by (rule arith_mult_neq_nzero2)\n   have sg2: \"n + n * t + i = n *(Suc t) + i\" by simp\n   from sg1 and sg2  show ?thesis  by arith\nqed\n\nlemma arith_modZero1:\n  \"(t + n * t) mod Suc n = 0\"\nby (metis mod_mult_self1_is_0 mult_Suc)\n\nlemma arith_modZero2:\n  \"Suc (n + (t + n * t)) mod Suc n = 0\"\nby (metis add_Suc_right add_Suc_shift mod_mult_self1_is_0 mult_Suc mult.commute)\n\nlemma arith1:\n  assumes h1:\"Suc n * t = Suc n * q\"\n  shows \"t = q\"\nusing assms\nby (metis mult_cancel2 mult.commute neq0_conv zero_less_Suc)\n\nlemma arith2:\n  fixes t n q :: \"nat\"\n  assumes h1:\"t + n * t = q + n * q\"\n  shows \"t = q\"\nusing assms\nby (metis arith1 mult_Suc)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/FocusStreamsCaseStudies/arith_hints.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7713344288424305}}
{"text": "(*\n  File:    Descartes_Sign_Rule.thy\n  Author:  Manuel Eberl <manuel@pruvisto.org>\n\n  Descartes' Rule of Signs, which relates the number of positive real roots of a polynomial\n  with the number of sign changes in its coefficient list.\n*)\nsection \\<open>Sign changes and Descartes' Rule of Signs\\<close>\n\ntheory Descartes_Sign_Rule\nimports \n  Complex_Main\n  \"HOL-Computational_Algebra.Polynomial\"\nbegin\n\n\n\nlemma filter_dropWhile: \n  \"filter (\\<lambda>x. \\<not>P x) (dropWhile P xs) = filter (\\<lambda>x. \\<not>P x) xs\"\n  by (induction xs) simp_all\n\n\nsubsection \\<open>Polynomials\\<close> \n\ntext\\<open>\n  A real polynomial whose leading and constant coefficients have opposite\n  non-zero signs must have a positive root.\n\\<close>\nlemma pos_root_exI:\n  assumes \"poly p 0 * lead_coeff p < (0 :: real)\"\n  obtains x where \"x > 0\" \"poly p x = 0\"\nproof -\n  have P: \"\\<exists>x>0. poly p x = (0::real)\" if \"lead_coeff p > 0\" \"poly p 0 < 0\" for p\n  proof -\n    note that(1)\n    also from poly_pinfty_gt_lc[OF \\<open>lead_coeff p > 0\\<close>] obtain x0 \n      where \"\\<And>x. x \\<ge> x0 \\<Longrightarrow> poly p x \\<ge> lead_coeff p\" by auto\n    hence \"poly p (max x0 1) \\<ge> lead_coeff p\" by auto\n    finally have \"poly p (max x0 1) > 0\" .\n    with that have \"\\<exists>x. x > 0 \\<and> x < max x0 1 \\<and> poly p x = 0\"\n      by (intro poly_IVT mult_neg_pos) auto\n    thus \"\\<exists>x>0. poly p x = 0\"  by auto\n  qed\n\n  show ?thesis\n  proof (cases \"lead_coeff p > 0\")\n    case True\n    with assms have \"poly p 0 < 0\" \n      by (auto simp: mult_less_0_iff)\n    from P[OF True this] that show ?thesis \n      by blast\n  next\n    case False\n    from False assms have \"poly (-p) 0 < 0\" \n      by (auto simp: mult_less_0_iff)\n    moreover from assms have \"p \\<noteq> 0\"\n      by auto\n    with False have \"lead_coeff (-p) > 0\" \n      by (cases rule: linorder_cases[of \"lead_coeff p\" 0]) \n         (simp_all add:)\n    ultimately show ?thesis using that P[of \"-p\"] by auto\n  qed\nqed\n\ntext \\<open>\n  Substitute $X$ with $aX$ in a polynomial $p(X)$. This turns all the $X - a$ factors in $p$\n  into factors of the form $X - 1$.\n\\<close>\ndefinition reduce_root where\n  \"reduce_root a p = pcompose p [:0, a:]\"\n\nlemma reduce_root_pCons: \n  \"reduce_root a (pCons c p) = pCons c (smult a (reduce_root a p))\"\n  by (simp add: reduce_root_def pcompose_pCons)\n\nlemma reduce_root_nonzero [simp]: \n  \"a \\<noteq> 0 \\<Longrightarrow> p \\<noteq> 0 \\<Longrightarrow> reduce_root a p \\<noteq> (0 :: 'a :: idom poly)\"\n  unfolding reduce_root_def using pcompose_eq_0[of p \"[:0, a:]\"] \n  by auto\n\n\nsubsection \\<open>List of partial sums\\<close>\n\ntext \\<open>\n  We first define, for a given list, the list of accumulated partial sums from left to right: \n  the list @{term \"psums xs\"} has as its $i$-th entry $\\sum_{j=0}^i \\mathrm{xs}_i$.\n\\<close>\n\nfun psums where\n  \"psums [] = []\"\n| \"psums [x] = [x]\"\n| \"psums (x#y#xs) = x # psums ((x+y) # xs)\"\n\nlemma length_psums [simp]: \"length (psums xs) = length xs\"\n  by (induction xs rule: psums.induct) simp_all\n\nlemma psums_Cons: \n  \"psums (x#xs) = (x :: 'a :: semigroup_add) # map ((+) x) (psums xs)\"\n  by (induction xs rule: psums.induct) (simp_all add: algebra_simps)\n\nlemma last_psums: \n  \"(xs :: 'a :: monoid_add list) \\<noteq> [] \\<Longrightarrow> last (psums xs) = sum_list xs\"\n  by (induction xs rule: psums.induct) \n     (auto simp add: add.assoc [symmetric] psums_Cons o_def)\n\nlemma psums_0_Cons [simp]: \n  \"psums (0#xs :: 'a :: monoid_add list) = 0 # psums xs\"\n  by (induction xs rule: psums.induct) (simp_all add: algebra_simps)\n\nlemma map_uminus_psums: \n  fixes xs :: \"'a :: ab_group_add list\"\n  shows \"map uminus (psums xs) = psums (map uminus xs)\"\n  by (induction xs rule: psums.induct) (simp_all)\n\nlemma psums_replicate_0_append:\n  \"psums (replicate n (0 :: 'a :: monoid_add) @ xs) = \n     replicate n 0 @ psums xs\"\n  by (induction n) (simp_all add: psums_Cons op_plus_0)\n\nlemma psums_nth: \"n < length xs \\<Longrightarrow> psums xs ! n = (\\<Sum>i\\<le>n. xs ! i)\"\nproof (induction xs arbitrary: n rule: psums.induct[case_names Nil sng rec])\n  case (rec x y xs n)\n  show ?case\n  proof (cases n)\n    case (Suc m)\n    from Suc have \"psums (x # y # xs) ! n = psums ((x+y) # xs) ! m\" by simp\n    also from rec.prems Suc have \"\\<dots> = (\\<Sum>i\\<le>m. ((x+y) # xs) ! i)\" \n      by (intro rec.IH) simp_all\n    also have \"\\<dots> = x + y + (\\<Sum>i=1..m. (y#xs) ! i)\"\n      by (auto simp: atLeast0AtMost [symmetric] sum.atLeast_Suc_atMost[of 0])\n    also have \"(\\<Sum>i=1..m. (y#xs) ! i) = (\\<Sum>i=Suc 1..Suc m. (x#y#xs) ! i)\"\n      by (subst sum.shift_bounds_cl_Suc_ivl) simp\n    also from Suc have \"x + y + \\<dots> = (\\<Sum>i\\<le>n. (x#y#xs) ! i)\"\n      by (auto simp: atLeast0AtMost [symmetric] sum.atLeast_Suc_atMost add_ac)\n    finally show ?thesis .\n  qed simp\nqed simp_all\n\n\nsubsection \\<open>Sign changes in a list\\<close>\n\ntext \\<open>\n  Next, we define the number of sign changes in a sequence. Intuitively, this is the number \n  of times that, when passing through the list, a sign change between one element and the next \n  element occurs (while ignoring all zero entries).\n\n  We implement this by filtering all zeros from the list of signs, removing all adjacent equal \n  elements and taking the length of the resulting list minus one.\n\\<close>\ndefinition sign_changes :: \"('a :: {sgn,zero} list) \\<Rightarrow> nat\" where\n  \"sign_changes xs = length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map sgn xs))) - 1\"\n\nlemma sign_changes_Nil [simp]: \"sign_changes [] = 0\" \n  by (simp add: sign_changes_def)\n\nlemma sign_changes_singleton [simp]: \"sign_changes [x] = 0\" \n  by (simp add: sign_changes_def)\n\nlemma sign_changes_cong:\n  assumes \"map sgn xs = map sgn ys\"\n  shows   \"sign_changes xs = sign_changes ys\"\n  using assms unfolding sign_changes_def by simp\n\nlemma sign_changes_Cons_ge: \"sign_changes (x # xs) \\<ge> sign_changes xs\"\n  unfolding sign_changes_def by (simp add: remdups_adj_Cons split: list.split)\n\nlemma sign_changes_Cons_Cons_different: \n  fixes x y :: \"'a :: linordered_idom\"\n  assumes \"x * y < 0\"\n  shows \"sign_changes (x # y # xs) = 1 + sign_changes (y # xs)\"\nproof -\n  from assms have \"sgn x = -1 \\<and> sgn y = 1 \\<or> sgn x = 1 \\<and> sgn y = -1\"\n    by (auto simp: mult_less_0_iff)\n  thus ?thesis by (fastforce simp: sign_changes_def)\nqed\n\nlemma sign_changes_Cons_Cons_same: \n  fixes x y :: \"'a :: linordered_idom\"\n  shows \"x * y > 0 \\<Longrightarrow> sign_changes (x # y # xs) = sign_changes (y # xs)\"\n  by (subst (asm) zero_less_mult_iff) (fastforce simp: sign_changes_def)\n\nlemma sign_changes_0_Cons [simp]: \n  \"sign_changes (0 # xs :: 'a :: idom_abs_sgn list) = sign_changes xs\"\n  by (simp add: sign_changes_def)\n\nlemma sign_changes_two: \n  fixes x y :: \"'a :: linordered_idom\"\n  shows \"sign_changes [x,y] = \n           (if x > 0 \\<and> y < 0 \\<or> x < 0 \\<and> y > 0 then 1 else 0)\"\n  by (auto simp: sgn_if sign_changes_def mult_less_0_iff)\n\nlemma sign_changes_induct [case_names nil sing zero nonzero]:\n  assumes \"P []\" \"\\<And>x. P [x]\" \"\\<And>xs. P xs \\<Longrightarrow> P (0#xs)\"\n          \"\\<And>x y xs. x \\<noteq> 0 \\<Longrightarrow> P ((x + y) # xs) \\<Longrightarrow> P (x # y # xs)\"\n  shows   \"P xs\"\nproof (induction \"length xs\" arbitrary: xs rule: less_induct)\n  case (less xs)\n  show ?case\n  proof (cases xs rule: psums.cases)\n    fix x y xs' assume \"xs = x # y # xs'\"\n    with assms less show ?thesis by (cases \"x = 0\") auto\n  qed (insert less assms, auto)\nqed \n\nlemma sign_changes_filter: \n  fixes xs :: \"'a :: linordered_idom list\"\n  shows \"sign_changes (filter (\\<lambda>x. x \\<noteq> 0) xs) = sign_changes xs\"\n  by (simp add: sign_changes_def filter_map o_def sgn_0_0)\n\nlemma sign_changes_Cons_Cons_0: \n  fixes xs :: \"'a :: linordered_idom list\"\n  shows \"sign_changes (x # 0 # xs) = sign_changes (x # xs)\"\n  by (subst (1 2) sign_changes_filter [symmetric]) simp_all\n\nlemma sign_changes_uminus: \n  fixes xs :: \"'a :: linordered_idom list\"\n  shows   \"sign_changes (map uminus xs) = sign_changes xs\"\nproof -\n  have \"sign_changes (map uminus xs) = \n          length (remdups_adj [x\\<leftarrow>map sgn (map uminus xs) . x \\<noteq> 0]) - 1\" \n   unfolding sign_changes_def ..\n  also have \"map sgn (map uminus xs) = map uminus (map sgn xs)\" \n    by (auto simp: sgn_minus)\n  also have \"remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) \\<dots>) = \n                 map uminus (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map sgn xs)))\"\n    by (subst filter_map, subst remdups_adj_map_injective) \n       (simp_all add: o_def)\n  also have \"length \\<dots> - 1 = sign_changes xs\" by (simp add: sign_changes_def)\n  finally show ?thesis .\nqed\n\nlemma sign_changes_replicate: \"sign_changes (replicate n x) = 0\"\n  by (simp add: sign_changes_def remdups_adj_replicate filter_replicate)\n\nlemma sign_changes_decompose:\n  assumes \"x \\<noteq> (0 :: 'a :: linordered_idom)\"\n  shows   \"sign_changes (xs @ x # ys) = \n             sign_changes (xs @ [x]) + sign_changes (x # ys)\"\nproof -\n  have \"sign_changes (xs @ x # ys) = \n            length (remdups_adj ([x\\<leftarrow>map sgn xs . x \\<noteq> 0] @ \n                      sgn x # [x\\<leftarrow>map sgn ys . x \\<noteq> 0])) - 1\"\n    by (simp add: sgn_0_0 assms sign_changes_def)\n  also have \"\\<dots> = sign_changes (xs @ [x]) + sign_changes (x # ys)\"\n    by (subst remdups_adj_append) (simp add: sign_changes_def assms sgn_0_0)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  If the first and the last entry of a list are non-zero, its number of sign changes is even \n  if and only if the first and the last element have the same sign. This will be important \n  later to establish the base case of Descartes' Rule. (if there are no positive roots, \n  the number of sign changes is even)\n\\<close>\nlemma even_sign_changes_iff:\n  assumes \"xs \\<noteq> ([] :: 'a :: linordered_idom list)\" \"hd xs \\<noteq> 0\" \"last xs \\<noteq> 0\"\n  shows   \"even (sign_changes xs) \\<longleftrightarrow> sgn (hd xs) = sgn (last xs)\"\nusing assms\nproof (induction \"length xs\" arbitrary: xs rule: less_induct)\n  case (less xs)\n  show ?case\n  proof (cases xs)\n    case (Cons x xs')\n    note x = this\n    show ?thesis\n    proof (cases xs')\n      case (Cons y xs'')\n      note y = this\n      show ?thesis\n      proof (rule linorder_cases[of \"x*y\" 0])\n        assume xy: \"x*y = 0\"\n        with x y less(1,3,4) show ?thesis by (auto simp: sign_changes_Cons_Cons_0)\n      next\n        assume xy: \"x*y > 0\"\n        with less(1,4) show ?thesis\n          by (auto simp add: x y sign_changes_Cons_Cons_same zero_less_mult_iff)\n      next\n        assume xy: \"x*y < 0\"\n        moreover from xy have \"sgn x = - sgn y\" by (auto simp: mult_less_0_iff)\n        moreover have \"even (sign_changes (y # xs'')) \\<longleftrightarrow> \n                         sgn (hd (y # xs'')) = sgn (last (y # xs''))\"\n          using xy less.prems by (intro less) (auto simp: x y)\n        moreover from xy less.prems \n          have \"sgn y = sgn (last xs) \\<longleftrightarrow> -sgn y \\<noteq> sgn (last xs)\"\n          by (auto simp: sgn_if)\n        ultimately show ?thesis by (auto simp: sign_changes_Cons_Cons_different x y)\n      qed\n    qed (auto simp: x)\n  qed (insert less.prems, simp_all)\nqed\n\n\nsubsection \\<open>Arthan's lemma\\<close>\n\ncontext\nbegin\n\ntext \\<open>\n  We first prove an auxiliary lemma that allows us to assume w.l.o.g. that the first element of \n  the list is non-negative, similarly to what Arthan does in his proof.\n\\<close>\nprivate lemma arthan_wlog [consumes 3, case_names nonneg lift]:\n  fixes xs :: \"'a :: linordered_idom list\"\n  assumes \"xs \\<noteq> []\" \"last xs \\<noteq> 0\" \"x + y + sum_list xs = 0\"\n  assumes \"\\<And>x y xs. xs \\<noteq> [] \\<Longrightarrow> last xs \\<noteq> 0 \\<Longrightarrow> \n               x + y + sum_list xs = 0 \\<Longrightarrow> x \\<ge> 0 \\<Longrightarrow> P x y xs\"\n  assumes \"\\<And>x y xs. xs \\<noteq> [] \\<Longrightarrow> P x y xs \\<Longrightarrow> P (-x) (-y) (map uminus xs)\"\n  shows   \"P x y xs\"\nproof (cases \"x \\<ge> 0\")\n  assume x: \"\\<not>(x \\<ge> 0)\"\n  from assms have \"map uminus xs \\<noteq> []\" by simp\n  moreover from x assms(1,2,3) have\"P (-x) (-y) (map uminus xs)\"\n    using uminus_sum_list_map[of \"\\<lambda>x. x\" xs, symmetric]\n    by (intro assms) (auto simp: last_map algebra_simps o_def neg_eq_iff_add_eq_0)\n  ultimately have \"P (- (-x)) (- (-y)) (map uminus (map uminus xs))\" by (rule assms)\n  thus ?thesis by (simp add: o_def)\nqed (simp_all add: assms)\n\ntext \\<open>\n  We now show that the $\\alpha$ and $\\beta$ in Arthan's proof have the necessary properties:\n  their difference is non-negative and even.\n\\<close>\nprivate lemma arthan_aux1:\n  fixes xs :: \"'a :: {linordered_idom} list\"\n  assumes \"xs \\<noteq> []\" \"last xs \\<noteq> 0\" \"x + y + sum_list xs = 0\"\n  defines \"v \\<equiv> \\<lambda>xs. int (sign_changes xs)\"\n  shows \"v (x # y # xs) - v ((x + y) # xs) \\<ge> \n             v (psums (x # y # xs)) - v (psums ((x + y) # xs)) \\<and> \n         even (v (x # y # xs) - v ((x + y) # xs) - \n                  (v (psums (x # y # xs)) - v (psums ((x + y) # xs))))\"\nusing assms(1-3)\nproof (induction rule: arthan_wlog)\n  have uminus_v: \"v (map uminus xs) = v xs\" for xs by (simp add: v_def sign_changes_uminus)\n\n  case (lift x y xs)\n  note lift(2)\n  also have \"v (psums (x#y#xs)) - v (psums ((x+y)#xs)) =\n                 v (psums (- x # - y # map uminus xs)) - \n                 v (psums ((- x + - y) # map uminus xs))\"\n    by (subst (1 2) uminus_v [symmetric]) (simp add: map_uminus_psums)\n  also have \"v (x # y # xs) - v ((x + y) # xs) = \n                 v (-x # -y # map uminus xs) - v ((-x + -y) # map uminus xs)\"\n    by (subst (1 2) uminus_v [symmetric]) simp\n  finally show ?case .\nnext\n  case (nonneg x y xs)\n  define p where \"p = (LEAST n. xs ! n \\<noteq> 0)\"\n  define xs1 :: \"'a list\" where \"xs1 = replicate p 0\"\n  define xs2 where \"xs2 = drop (Suc p) xs\"\n  from nonneg have \"xs ! (length xs - 1) \\<noteq> 0\" by (simp add: last_conv_nth)\n  hence p_nz: \"xs ! p \\<noteq> 0\" unfolding p_def by (rule LeastI)\n  {\n    fix q assume \"q < p\" hence \"xs ! q = 0\"\n      using Least_le[of \"\\<lambda>n. xs ! n \\<noteq> 0\" q] unfolding p_def by force\n  } note less_p_zero = this\n  from Least_le[of \"\\<lambda>n. xs ! n \\<noteq> 0\" \"length xs - 1\"] nonneg \n    have \"p \\<le> length xs - 1\" unfolding p_def by (auto simp: last_conv_nth)\n  with nonneg have p_less_length: \"p < length xs\" by (cases xs) simp_all\n\n  from p_less_length less_p_zero have \"take p xs = replicate p 0\" \n    by (subst list_eq_iff_nth_eq) auto\n  with p_less_length have xs_decompose: \"xs = xs1 @ xs ! p # xs2\" \n    unfolding xs1_def xs2_def\n    by (subst append_take_drop_id [of p, symmetric], \n        subst Cons_nth_drop_Suc) simp_all\n\n  have v_decompose: \"v (xs' @ xs) = v (xs' @ [xs ! p]) + v (xs ! p # xs2)\" for xs'\n  proof -\n    have \"xs' @ xs = (xs' @ xs1) @ xs ! p # xs2\" by (subst xs_decompose) simp\n    also have \"v \\<dots> = v (xs' @ [xs ! p]) + v (xs ! p # xs2)\" unfolding v_def\n      by (subst sign_changes_decompose[OF p_nz], \n          subst (1 2 3 4) sign_changes_filter [symmetric]) (simp_all add: xs1_def)\n    finally show ?thesis .\n  qed\n\n  have psums_decompose: \"psums xs = replicate p 0 @ psums (xs!p # xs2)\" \n    by (subst xs_decompose) (simp add: xs1_def psums_replicate_0_append)\n  have v_psums_decompose: \"sign_changes (xs' @ psums xs) = sign_changes (xs' @ [xs!p]) + \n         sign_changes (xs!p # map ((+) (xs!p)) (psums xs2))\" for xs'\n  proof -\n    fix xs' :: \"'a list\"\n    have \"sign_changes (xs' @ psums xs) = \n            sign_changes (xs' @ xs ! p # map ((+) (xs!p)) (psums xs2))\"\n      by (subst psums_decompose, subst (1 2) sign_changes_filter [symmetric]) \n         (simp_all add: psums_Cons)\n    also have \"\\<dots> = sign_changes (xs' @ [xs!p]) + \n                      sign_changes (xs!p # map ((+) (xs!p)) (psums xs2))\"\n      by (subst sign_changes_decompose[OF p_nz]) simp_all\n    finally show \"sign_changes (xs' @ psums xs) = \\<dots>\" .\n  qed\n\n  show ?case\n  proof (cases \"x > 0\")\n    assume \"\\<not>(x > 0)\"\n    with nonneg show ?thesis by (auto simp: v_def)\n  next\n    assume x: \"x > 0\"\n    show ?thesis\n    proof (rule linorder_cases[of y 0])\n      assume y: \"y > 0\"\n      from x and this have xy: \"x + y > 0\" by (rule add_pos_pos)\n      with y have \"sign_changes ((x + y) # xs) = sign_changes (y # xs)\"\n        by (intro sign_changes_cong) auto\n      moreover have \"sign_changes (x # psums ((x + y) # xs)) = \n                       sign_changes (psums ((x+y) # xs))\"\n        using x xy by (subst (1 2) psums_Cons) (simp_all add: sign_changes_Cons_Cons_same)\n      ultimately show ?thesis using x y \n        by (simp add: v_def algebra_simps sign_changes_Cons_Cons_same)\n    next\n      assume y: \"y = 0\"\n      with x show ?thesis\n        by (simp add: v_def sign_changes_Cons_Cons_0 psums_Cons \n                      o_def sign_changes_Cons_Cons_same)\n    next\n      assume y: \"y < 0\"\n      with x have different: \"x * y < 0\" by (rule mult_pos_neg)\n      show ?thesis\n      proof (rule linorder_cases[of \"x + y\" 0])\n        assume xy: \"x + y < 0\"\n        with x have different': \"x * (x + y) < 0\" by (rule mult_pos_neg)\n        have \"(\\<lambda>t. t + (x + y)) = ((+) (x + y))\" by (rule ext) simp\n        moreover from y xy have \"sign_changes ((x+y) # xs) = sign_changes (y # xs)\" \n          by (intro sign_changes_cong) auto\n        ultimately show ?thesis using xy different different' y\n          by (simp add: v_def sign_changes_Cons_Cons_different psums_Cons o_def add_ac)\n      next\n        assume xy: \"x + y = 0\"\n        show ?case\n        proof (cases \"xs ! p > 0\")\n          assume p: \"xs ! p > 0\"\n          from p y have different': \"y * xs ! p < 0\" by (intro mult_neg_pos)\n          with v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] x xy p different different' \n               v_psums_decompose[of \"[x]\"] v_psums_decompose[of \"[]\"]\n          show ?thesis by (auto simp add: algebra_simps v_def sign_changes_Cons_Cons_0 \n                             sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        next\n          assume \"\\<not>(xs ! p > 0)\"\n          with p_nz have p: \"xs ! p < 0\" by simp\n          from p y have same: \"y * xs ! p > 0\" by (intro mult_neg_neg)\n          from p x have different': \"x * xs ! p < 0\" by (intro mult_pos_neg)\n          from v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] xy different different' same \n               v_psums_decompose[of \"[x]\"] v_psums_decompose[of \"[]\"]\n          show ?thesis by (auto simp add: algebra_simps v_def sign_changes_Cons_Cons_0 \n                             sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        qed\n      next\n        assume xy: \"x + y > 0\"\n        from x and this have same: \"x * (x + y) > 0\" by (rule mult_pos_pos)\n        show ?case\n        proof (cases \"xs ! p > 0\")\n          assume p: \"xs ! p > 0\"\n          from xy p have same': \"(x + y) * xs ! p > 0\" by (intro mult_pos_pos)\n          from p y have different': \"y * xs ! p < 0\" by (intro mult_neg_pos)\n          have \"(\\<lambda>t. t + (x + y)) = ((+) (x + y))\" by (rule ext) simp\n          with v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] different different' same same'\n          show ?thesis by (auto simp add: algebra_simps v_def psums_Cons o_def\n                             sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        next\n          assume \"\\<not>(xs ! p > 0)\"\n          with p_nz have p: \"xs ! p < 0\" by simp\n          from xy p have different': \"(x + y) * xs ! p < 0\" by (rule mult_pos_neg)\n          from y p have same': \"y * xs ! p > 0\" by (rule mult_neg_neg)\n          have \"(\\<lambda>t. t + (x + y)) = ((+) (x + y))\" by (rule ext) simp\n          with v_decompose[of \"[x, y]\"] v_decompose[of \"[x+y]\"] different different' same same'\n          show ?thesis by (auto simp add: algebra_simps v_def psums_Cons o_def\n                              sign_changes_Cons_Cons_different sign_changes_Cons_Cons_same)\n        qed\n      qed\n    qed\n  qed\nqed\n\n\ntext \\<open>\n  Now we can prove the main lemma of the proof by induction over the list with our specialised\n  induction rule for @{term \"sign_changes\"}. It states that for a non-empty list whose last element \n  is non-zero and whose sum is zero, the difference of the sign changes in the list and in the list \n  of its partial sums is odd and positive. \n\\<close>\nlemma arthan:\n  fixes xs :: \"'a :: linordered_idom list\"\n  assumes \"xs \\<noteq> []\" \"last xs \\<noteq> 0\" \"sum_list xs = 0\"\n  shows   \"sign_changes xs > sign_changes (psums xs) \\<and> \n           odd (sign_changes xs - sign_changes (psums xs))\"\nusing assms\nproof (induction xs rule: sign_changes_induct)\n  case (nonzero x y xs)\n  show ?case\n  proof (cases \"xs = []\")\n    case False\n    define \\<alpha> where \"\\<alpha> = int (sign_changes (x # y # xs)) - int (sign_changes ((x + y) # xs))\"\n    define \\<beta> where \"\\<beta> = int (sign_changes (psums (x # y # xs))) - int (sign_changes (psums ((x+y) # xs)))\"\n    from nonzero False have \"\\<alpha> \\<ge> \\<beta> \\<and> even (\\<alpha> - \\<beta>)\" unfolding \\<alpha>_def \\<beta>_def\n      by (intro arthan_aux1) auto\n    from False and nonzero.prems have\n       \"sign_changes (psums ((x + y) # xs)) < sign_changes ((x + y) # xs) \\<and>\n        odd (sign_changes ((x + y) # xs) - sign_changes (psums ((x + y) # xs)))\"\n      by (intro nonzero.IH) (auto simp: add.assoc)\n    with arthan_aux1[of xs x y] nonzero(4,5) False(1) show ?thesis by force\n  qed (insert nonzero.prems, auto split: if_split_asm simp: sign_changes_two add_eq_0_iff)\nqed (auto split: if_split_asm simp: add_eq_0_iff)\n\nend\n\n\nsubsection \\<open>Roots of a polynomial with a certain property\\<close>\n\ntext \\<open>\n  The set of roots of a polynomial @{term \"p\"} that fulfil a given property @{term \"P\"}:\n\\<close>\ndefinition \"roots_with P p = {x. P x \\<and> poly p x = 0}\"\n\ntext \\<open>\n  The number of roots of a polynomial @{term \"p\"} with a given property @{term \"P\"}, where \n  multiple roots are counted multiple times.\n \\<close>\ndefinition \"count_roots_with P p = (\\<Sum>x\\<in>roots_with P p. order x p)\"\n\nabbreviation \"pos_roots \\<equiv> roots_with (\\<lambda>x. x > 0)\"\nabbreviation \"count_pos_roots \\<equiv> count_roots_with (\\<lambda>x. x > 0)\"\n\n\nlemma finite_roots_with [simp]: \n  \"(p :: 'a :: linordered_idom poly) \\<noteq> 0 \\<Longrightarrow> finite (roots_with P p)\"\n  by (rule finite_subset[OF _ poly_roots_finite[of p]]) (auto simp: roots_with_def)\n\nlemma count_roots_with_times_root:\n  assumes \"p \\<noteq> 0\" \"P (a :: 'a :: linordered_idom)\"\n  shows   \"count_roots_with P ([:a, -1:] * p) = Suc (count_roots_with P p)\"\nproof -\n  define q where \"q = [:a, -1:] * p\"\n  from assms have a: \"a \\<in> roots_with P q\" by (simp_all add: roots_with_def q_def)\n  have q_nz: \"q \\<noteq> 0\" unfolding q_def by (rule no_zero_divisors) (simp_all add: assms)\n\n  have \"count_roots_with P q = (\\<Sum>x\\<in>roots_with P q. order x q)\" by (simp add: count_roots_with_def)\n  also from a q_nz have \"\\<dots> = order a q + (\\<Sum>x\\<in>roots_with P q - {a}. order x q)\"\n    by (subst sum.remove) simp_all\n  also have \"order a q = order a [:a, -1:] + order a p\" unfolding q_def\n    by (subst order_mult[OF no_zero_divisors]) (simp_all add: assms)\n  also have \"order a [:a, -1:] = 1\"\n    by (subst order_smult [of \"-1\", symmetric])\n       (insert order_power_n_n[of a 1], simp_all add: order_1)\n  also have \"(\\<Sum>x\\<in>roots_with P q - {a}. order x q) = (\\<Sum>x\\<in>roots_with P q - {a}. order x p)\"\n  proof (intro sum.cong refl)\n    fix x assume x: \"x \\<in> roots_with P q - {a}\"\n    from assms have \"order x q = order x [:a, -1:] + order x p\" unfolding q_def\n      by (subst order_mult[OF no_zero_divisors]) (simp_all add: assms)\n    also from x have \"order x [:a, -1:] = 0\" by (intro order_0I) simp_all\n    finally show \"order x q = order x p\" by simp\n  qed\n  also from a q_nz have \"1 + order a p + (\\<Sum>x\\<in>roots_with P q - {a}. order x p) = \n                           1 + (\\<Sum>x\\<in>roots_with P q. order x p)\"\n    by (subst add.assoc, subst sum.remove[symmetric]) simp_all\n  also from q_nz have \"(\\<Sum>x\\<in>roots_with P q. order x p) = (\\<Sum>x\\<in>roots_with P p. order x p)\"\n  proof (intro sum.mono_neutral_right)\n    show \"roots_with P p \\<subseteq> roots_with P q\" \n      by (auto simp: roots_with_def q_def simp del: mult_pCons_left)\n    show \"\\<forall>x\\<in>roots_with P q - roots_with P p. order x p = 0\"\n      by (auto simp: roots_with_def q_def order_root simp del: mult_pCons_left)\n  qed simp_all\n  finally show ?thesis by (simp add: q_def count_roots_with_def)\nqed\n\n\nsubsection \\<open>Coefficient sign changes of a polynomial\\<close>\n\nabbreviation (input) \"coeff_sign_changes f \\<equiv> sign_changes (coeffs f)\"\n\ntext \\<open>\n  We first show that when building a polynomial from a coefficient list, the coefficient sign\n  sign changes of the resulting polynomial are the same as the same sign changes in the list.\n\n  Note that constructing a polynomial from a list removes all trailing zeros.\n\\<close>\nlemma sign_changes_coeff_sign_changes:\n  assumes \"Poly xs = (p :: 'a :: linordered_idom poly)\"\n  shows   \"sign_changes xs = coeff_sign_changes p\"\nproof -\n  have \"coeffs p = coeffs (Poly xs)\" by (subst assms) (rule refl)\n  also have \"\\<dots> = strip_while ((=) 0) xs\" by simp\n  also have \"filter ((\\<noteq>) 0) \\<dots> = filter ((\\<noteq>) 0) xs\" unfolding strip_while_def o_def\n    by (subst rev_filter [symmetric], subst filter_dropWhile) (simp_all add: rev_filter)\n  also have \"sign_changes \\<dots> = sign_changes xs\" by (simp add: sign_changes_filter)\n  finally show ?thesis by (simp add: sign_changes_filter)\nqed\n\ntext \\<open>\n  By applying @{term \"reduce_root a\"}, we can assume w.l.o.g. that the root in\n  question is 1, since applying root reduction does not change the number of \n  sign changes.\n\\<close>\nlemma coeff_sign_changes_reduce_root: \n  assumes \"a > (0 :: 'a :: linordered_idom)\"\n  shows   \"coeff_sign_changes (reduce_root a p) = coeff_sign_changes p\"\nproof (intro sign_changes_cong, induction p)\n  case (pCons c p)\n  have \"map sgn (coeffs (reduce_root a (pCons c p))) = \n             cCons (sgn c) (map sgn (coeffs (reduce_root a p)))\"\n    using assms by (auto simp add: cCons_def sgn_0_0 sgn_mult reduce_root_pCons coeffs_smult)\n  also note pCons.IH\n  also have \"cCons (sgn c) (map sgn (coeffs p)) = map sgn (coeffs (pCons c p))\"\n    using assms by (auto simp add: cCons_def sgn_0_0)\n  finally show ?case .\nqed (simp_all add: reduce_root_def)\n\ntext \\<open>\n  Multiplying a polynomial with a positive constant also does not change the number \n  of sign changes. (in fact, any non-zero constant would also work, but the proof \n  is slightly more difficult and positive constants suffice in our use case)\n\\<close>\nlemma coeff_sign_changes_smult: \n  assumes \"a > (0 :: 'a :: linordered_idom)\"\n  shows   \"coeff_sign_changes (smult a p) = coeff_sign_changes p\"\n  using assms by (auto intro!: sign_changes_cong simp: sgn_mult coeffs_smult)\n\n\ncontext\nbegin\n\ntext \\<open>\n  We now show that a polynomial with an odd number of sign changes contains a \n  positive root. We first assume that the constant coefficient is non-zero. Then it is \n  clear that the polynomial's sign at 0 will be the sign of the constant coefficient, whereas \n  the polynomial's sign for sufficiently large inputs will be the sign of the leading coefficient.\n\n  Moreover, we have shown before that in a list with an odd number of sign changes and \n  non-zero initial and last coefficients, the initial coefficient and the last coefficient have \n  opposite and non-zero signs. Then, the polynomial obviously has a positive root.\n\\<close>\nprivate lemma odd_coeff_sign_changes_imp_pos_roots_aux:\n  assumes [simp]: \"p \\<noteq> (0 :: real poly)\" \"poly p 0 \\<noteq> 0\"\n  assumes \"odd (coeff_sign_changes p)\"\n  obtains x where \"x > 0\" \"poly p x = 0\"\nproof -\n  from \\<open>poly p 0 \\<noteq> 0\\<close>\n  have [simp]: \"hd (coeffs p) \\<noteq> 0\"\n    by (induct p) auto\n  from assms have  \"\\<not> even (coeff_sign_changes p)\"\n    by blast\n  also have \"even (coeff_sign_changes p) \\<longleftrightarrow> sgn (hd (coeffs p)) = sgn (lead_coeff p)\"\n    by (auto simp add: even_sign_changes_iff last_coeffs_eq_coeff_degree)\n  finally have \"sgn (hd (coeffs p)) * sgn (lead_coeff p) < 0\" \n    by (auto simp: sgn_if split: if_split_asm)\n  also from \\<open>p \\<noteq> 0\\<close> have \"hd (coeffs p) = poly p 0\" by (induction p) auto\n  finally have \"poly p 0 * lead_coeff p < 0\" by (auto simp: mult_less_0_iff)\n\n  from pos_root_exI[OF this] that show ?thesis by blast\nqed\n\ntext \\<open>\n  We can now show the statement without the restriction to a non-zero constant coefficient.\n  We can do this by simply factoring $p$ into the form $p \\cdot x^n$, where $n$ is chosen as\n  large as possible. This corresponds to stripping all initial zeros of the coefficient list,\n  which obviously changes neither the existence of positive roots nor the number of coefficient \n  sign changes.\n\\<close>\nlemma odd_coeff_sign_changes_imp_pos_roots:\n  assumes \"p \\<noteq> (0 :: real poly)\"\n  assumes \"odd (coeff_sign_changes p)\"\n  obtains x where \"x > 0\" \"poly p x = 0\"\nproof -\n  define s where \"s = sgn (lead_coeff p)\"\n  define n where \"n = order 0 p\"\n  define r where \"r = p div [:0, 1:] ^ n\"\n  have p: \"p = [:0, 1:] ^ n * r\" unfolding r_def n_def\n    using order_1[of 0 p] by (simp del: mult_pCons_left)\n  from assms p have r_nz: \"r \\<noteq> 0\" by auto\n\n  obtain x where \"x > 0\" \"poly r x = 0\"\n  proof (rule odd_coeff_sign_changes_imp_pos_roots_aux)\n    show \"r \\<noteq> 0\" by fact\n    have \"order 0 p = order 0 p + order 0 r\"\n      by (subst p, insert order_power_n_n[of \"0::real\" n] r_nz)\n         (simp del: mult_pCons_left add: order_mult n_def)\n    hence \"order 0 r = 0\" by simp\n    with r_nz show nz: \"poly r 0 \\<noteq> 0\" by (simp add: order_root)\n\n    note \\<open>odd (coeff_sign_changes p)\\<close> \n    also have \"p = [:0, 1:] ^ n * r\" by (simp add: p)\n    also have \"[:0, 1:] ^ n = monom 1 n\" \n      by (induction n) (simp_all add: monom_Suc monom_0)\n    also have \"coeffs (monom 1 n * r) = replicate n 0 @ coeffs r\"\n      by (induction n) (simp_all add: monom_Suc cCons_def r_nz monom_0)\n    also have \"sign_changes \\<dots> = coeff_sign_changes r\"\n      by (subst (1 2) sign_changes_filter [symmetric]) simp\n    finally show \"odd (coeff_sign_changes r)\" .\n  qed\n  thus ?thesis by (intro that[of x]) (simp_all add: p)\nqed\n\nend\n\n\nsubsection \\<open>Proof of Descartes' sign rule\\<close>\n\ntext \\<open>\n  For a polynomial $p(X) = a_0 + \\ldots + a_n X^n$, we have \n  $[X^i] (1-X)p(X) = (\\sum\\limits_{j=0}^i a_j)$.\n\\<close>\nlemma coeff_poly_times_one_minus_x:\n  fixes g :: \"'a :: linordered_idom poly\"\n  shows \"coeff g n = (\\<Sum>i\\<le>n. coeff (g * [:1, -1:]) i)\"\n  by (induction n) simp_all\n\ntext \\<open>\n  We apply the previous lemma to the coefficient list of a polynomial and show: \n  given a polynomial $p(X)$ and $q(X) = (1 - X)p(X)$, the coefficient list of $p(X)$ is the \n  list of partial sums of the coefficient list of $q(X)$.\n\\<close>\nlemma Poly_times_one_minus_x_eq_psums:\n  fixes xs :: \"'a :: linordered_idom list\"\n  assumes [simp]: \"length xs = length ys\"\n  assumes \"Poly xs = Poly ys * [:1, -1:]\"\n  shows   \"ys = psums xs\"\nproof (rule nth_equalityI; safe?)\n  fix i assume i: \"i < length ys\"\n  hence \"ys ! i = coeff (Poly ys) i\"\n    by (simp add: nth_default_def)\n  also from coeff_poly_times_one_minus_x[of \"Poly ys\" i] assms\n    have \"\\<dots> = (\\<Sum>j\\<le>i. coeff (Poly xs) j)\" by simp\n    also from i have \"\\<dots> = psums xs ! i\"\n      by (auto simp: nth_default_def psums_nth)\n  finally show \"ys ! i = psums xs ! i\" .\nqed simp_all\n\ntext \\<open>\n  We can now apply our main lemma on the sign changes in lists to the coefficient lists of \n  a nonzero polynomial $p(X)$ and $(1-X)p(X)$: the difference of the changes in the \n  coefficient lists is odd and positive.\n\\<close>\nlemma sign_changes_poly_times_one_minus_x:\n  fixes g :: \"'a :: linordered_idom poly\" and a :: 'a\n  assumes nz: \"g \\<noteq> 0\"\n  defines \"v \\<equiv> coeff_sign_changes\"\n  shows \"v ([:1, -1:] * g) - v g > 0 \\<and> odd (v ([:1, -1:] * g) - v g)\"\nproof -\n  define xs where \"xs = coeffs ([:1, -1:] * g)\"\n  define ys where \"ys = coeffs g @ [0]\"\n  have ys: \"ys = psums xs\"\n  proof (rule Poly_times_one_minus_x_eq_psums)\n    show \"length xs = length ys\" unfolding xs_def ys_def\n      by (simp add: length_coeffs nz degree_mult_eq no_zero_divisors del: mult_pCons_left)\n    show \"Poly xs = Poly ys * [:1, - 1:]\" unfolding xs_def ys_def\n      by (simp only: Poly_snoc Poly_coeffs) simp\n  qed\n  have \"sign_changes (psums xs) < sign_changes xs \\<and> \n        odd (sign_changes xs - sign_changes (psums xs))\"\n  proof (rule arthan)\n    show \"xs \\<noteq> []\"\n      by (auto simp: xs_def nz simp del: mult_pCons_left)\n    then show \"sum_list xs = 0\" by (simp add: last_psums [symmetric] ys [symmetric] ys_def)\n    show \"last xs \\<noteq> 0\"\n      by (auto simp: xs_def nz last_coeffs_eq_coeff_degree simp del: mult_pCons_left)\n  qed\n  with ys have \"sign_changes ys < sign_changes xs \\<and> \n                odd (sign_changes xs - sign_changes ys)\" by simp\n  also have \"sign_changes xs = v ([:1, -1:] * g)\" unfolding v_def\n    by (intro sign_changes_coeff_sign_changes) (simp_all add: xs_def)\n  also have \"sign_changes ys = v g\" unfolding v_def\n    by (intro sign_changes_coeff_sign_changes) (simp_all add: ys_def Poly_snoc)\n  finally show ?thesis by simp\nqed\n\ntext \\<open>\n  We can now lift the previous lemma to the case of $p(X)$ and $(a-X)p(X)$ by substituting $X$ \n  with $aX$, yielding the polynomials $p(aX)$ and $a \\cdot (1-X) \\cdot p(aX)$.\n\\<close>\nlemma sign_changes_poly_times_root_minus_x:\n  fixes g :: \"'a :: linordered_idom poly\" and a :: 'a\n  assumes nz: \"g \\<noteq> 0\" and pos: \"a > 0\"\n  defines \"v \\<equiv> coeff_sign_changes\"\n  shows \"v ([:a, -1:] * g) - v g > 0 \\<and> odd (v ([:a, -1:] * g) - v g)\"\nproof -\n  have \"0 < v ([:1, - 1:] * reduce_root a g) - v (reduce_root a g) \\<and>\n            odd (v ([:1, - 1:] * reduce_root a g) - v (reduce_root a g))\"\n    using nz pos unfolding v_def by (intro sign_changes_poly_times_one_minus_x) simp_all\n  also have \"v ([:1, -1:] * reduce_root a g) = v (smult a ([:1, -1:] * reduce_root a g))\"\n    unfolding v_def by (simp add: coeff_sign_changes_smult pos)\n  also have \"smult a ([:1, -1:] * reduce_root a g) = [:a:] * [:1, -1:] * reduce_root a g\" \n    by (subst mult.assoc) simp\n  also have \"[:a:] * [:1, -1:] = reduce_root a [:a, -1:]\" \n    by (simp add: reduce_root_def pcompose_pCons)\n  also have \"\\<dots> * reduce_root a g = reduce_root a ([:a, -1:] * g)\" \n    unfolding reduce_root_def by (simp only: pcompose_mult)\n  also have \"v \\<dots> = v ([:a, -1:] * g)\" by (simp add: v_def coeff_sign_changes_reduce_root pos)\n  also have \"v (reduce_root a g) = v g\" by (simp add: v_def coeff_sign_changes_reduce_root pos)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Finally, the difference of the number of coefficient sign changes and the number of\n  positive roots is non-negative and even. This follows straightforwardly by induction \n  over the roots.\n\\<close>\nlemma descartes_sign_rule_aux:\n  fixes p :: \"real poly\"\n  assumes \"p \\<noteq> 0\"\n  shows   \"coeff_sign_changes p \\<ge> count_pos_roots p \\<and> \n           even (coeff_sign_changes p - count_pos_roots p)\"\nusing assms\nproof (induction p rule: poly_root_induct[where P = \"\\<lambda>a. a > 0\"])\n  case (root a p)\n  define q where \"q = [:a, -1:] * p\"\n  from root.prems have p: \"p \\<noteq> 0\" by auto\n  with root p sign_changes_poly_times_root_minus_x[of p a] \n       count_roots_with_times_root[of p \"\\<lambda>x. x > 0\" a] show ?case by (fold q_def) fastforce\nnext\n  case (no_roots p)\n  from no_roots have \"pos_roots p = {}\" by (auto simp: roots_with_def)\n  hence [simp]: \"count_pos_roots p = 0\" by (simp add: count_roots_with_def)\n  thus ?case using no_roots \\<open>p \\<noteq> 0\\<close> odd_coeff_sign_changes_imp_pos_roots[of p]\n    by (auto simp: roots_with_def)\nqed simp_all\n\ntext \\<open>\n  The main theorem is then an obvious consequence\n\\<close>\ntheorem descartes_sign_rule:\n  fixes p :: \"real poly\"\n  assumes \"p \\<noteq> 0\"\n  shows \"\\<exists>d. even d \\<and> coeff_sign_changes p = count_pos_roots p + d\"\nproof\n  define d where \"d = coeff_sign_changes p - count_pos_roots p\"\n  show \"even d \\<and> coeff_sign_changes p = count_pos_roots p + d\"\n    unfolding d_def using descartes_sign_rule_aux[OF assms] by auto\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Descartes_Sign_Rule/Descartes_Sign_Rule.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8824278741843884, "lm_q1q2_score": 0.7713101164995019}}
{"text": "(*<*)\ntheory Tree imports Main begin\n(*>*)\n\ntext\\<open>\\noindent\nDefine the datatype of \\rmindex{binary trees}:\n\\<close>\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"(*<*)\n\nprimrec mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l x r) = Node (mirror r) x (mirror l)\"(*>*)\n\ntext\\<open>\\noindent\nDefine a function \\<^term>\\<open>mirror\\<close> that mirrors a binary tree\nby swapping subtrees recursively. Prove\n\\<close>\n\nlemma mirror_mirror: \"mirror(mirror t) = t\"\n(*<*)\napply(induct_tac t)\nby(auto)\n\nprimrec flatten :: \"'a tree => 'a list\" where\n\"flatten Tip = []\" |\n\"flatten (Node l x r) = flatten l @ [x] @ flatten r\"\n(*>*)\n\ntext\\<open>\\noindent\nDefine a function \\<^term>\\<open>flatten\\<close> that flattens a tree into a list\nby traversing it in infix order. Prove\n\\<close>\n\nlemma \"flatten(mirror t) = rev(flatten t)\"\n(*<*)\napply(induct_tac t)\nby(auto)\n\nend\n(*>*)\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/Misc/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094174159129, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7712758498273554}}
{"text": "(* Title:      Matrix Relation Algebras\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Matrix Relation Algebras\\<close>\n\ntext \\<open>\nThis theory gives matrix models of Stone relation algebras and more general structures.\nWe consider only square matrices.\nThe main result is that matrices over Stone relation algebras form a Stone relation algebra.\n\nWe use the monoid structure underlying semilattices to provide finite sums, which are necessary for defining the composition of two matrices.\nSee \\cite{ArmstrongFosterStruthWeber2016,ArmstrongGomesStruthWeber2016} for similar liftings to matrices for semirings and relation algebras.\nA technical difference is that those theories are mostly based on semirings whereas our hierarchy is mostly based on lattices (and our semirings directly inherit from semilattices).\n\nRelation algebras have both a semiring and a lattice structure such that semiring addition and lattice join coincide.\nIn particular, finite sums and finite suprema coincide.\nIsabelle/HOL has separate theories for semirings and lattices, based on separate addition and join operations and different operations for finite sums and finite suprema.\nReusing results from both theories is beneficial for relation algebras, but not always easy to realise.\n\\<close>\n\ntheory Matrix_Relation_Algebras\n\nimports Relation_Algebras\n\nbegin\n\nsubsection \\<open>Finite Suprema\\<close>\n\ntext \\<open>\nWe consider finite suprema in idempotent semirings and Stone relation algebras.\nWe mostly use the first of the following notations, which denotes the supremum of expressions \\<open>t(x)\\<close> over all \\<open>x\\<close> from the type of \\<open>x\\<close>.\nFor finite types, this is implemented in Isabelle/HOL as the repeated application of binary suprema.\n\\<close>\n\nsyntax\n  \"_sum_sup_monoid\" :: \"idt \\<Rightarrow> 'a::bounded_semilattice_sup_bot \\<Rightarrow> 'a\" (\"(\\<Squnion>\\<^sub>_ _)\" [0,10] 10)\n  \"_sum_sup_monoid_bounded\" :: \"idt \\<Rightarrow> 'b set \\<Rightarrow> 'a::bounded_semilattice_sup_bot \\<Rightarrow> 'a\" (\"(\\<Squnion>\\<^bsub>_\\<in>_\\<^esub> _)\" [0,51,10] 10)\ntranslations\n  \"\\<Squnion>\\<^sub>x t\" => \"XCONST sup_monoid.sum (\\<lambda>x . t) { x . CONST True }\"\n  \"\\<Squnion>\\<^bsub>x\\<in>X\\<^esub> t\" => \"XCONST sup_monoid.sum (\\<lambda>x . t) X\"\n\ncontext idempotent_semiring\nbegin\n\ntext \\<open>\nThe following induction principles are useful for comparing two suprema.\nThe first principle works because types are not empty.\n\\<close>\n\nlemma one_sup_induct [case_names one sup]:\n  fixes f g :: \"'b::finite \\<Rightarrow> 'a\"\n  assumes one: \"\\<And>i . P (f i) (g i)\"\n      and sup: \"\\<And>j I . j \\<notin> I \\<Longrightarrow> P (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> f i) (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> g i) \\<Longrightarrow> P (f j \\<squnion> (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> f i)) (g j \\<squnion> (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> g i))\"\n    shows \"P (\\<Squnion>\\<^sub>k f k) (\\<Squnion>\\<^sub>k g k)\"\nproof -\n  let ?X = \"{ k::'b . True }\"\n  have \"finite ?X\" and \"?X \\<noteq> {}\"\n    by auto\n  thus ?thesis\n  proof (induct rule: finite_ne_induct)\n    case (singleton i) thus ?case\n      using one by simp\n  next\n    case (insert j I) thus ?case\n      using sup by simp\n  qed\nqed\n\nlemma bot_sup_induct [case_names bot sup]:\n  fixes f g :: \"'b::finite \\<Rightarrow> 'a\"\n  assumes bot: \"P bot bot\"\n      and sup: \"\\<And>j I . j \\<notin> I \\<Longrightarrow> P (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> f i) (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> g i) \\<Longrightarrow> P (f j \\<squnion> (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> f i)) (g j \\<squnion> (\\<Squnion>\\<^bsub>i\\<in>I\\<^esub> g i))\"\n    shows \"P (\\<Squnion>\\<^sub>k f k) (\\<Squnion>\\<^sub>k g k)\"\n  apply (induct rule: one_sup_induct)\n  using bot sup apply fastforce\n  using sup by blast\n\ntext \\<open>\nNow many properties of finite suprema follow by simple applications of the above induction rules.\nIn particular, we show distributivity of composition, isotonicity and the upper-bound property.\n\\<close>\n\nlemma comp_right_dist_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<Squnion>\\<^sub>k f k * x) = (\\<Squnion>\\<^sub>k f k) * x\"\nproof (induct rule: one_sup_induct)\n  case one show ?case\n    by simp\nnext\n  case (sup j I) thus ?case\n    using mult_right_dist_sup by auto\nqed\n\nlemma comp_left_dist_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<Squnion>\\<^sub>k x * f k) = x * (\\<Squnion>\\<^sub>k f k)\"\nproof (induct rule: one_sup_induct)\n  case one show ?case\n    by simp\nnext\n  case (sup j I) thus ?case\n    by (simp add: mult_left_dist_sup)\nqed\n\nlemma leq_sum:\n  fixes f g :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<forall>k . f k \\<le> g k) \\<Longrightarrow> (\\<Squnion>\\<^sub>k f k) \\<le> (\\<Squnion>\\<^sub>k g k)\"\nproof (induct rule: one_sup_induct)\n  case one thus ?case\n    by simp\nnext\n  case (sup j I) thus ?case\n    using sup_mono by blast\nqed\n\nlemma ub_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"f i \\<le> (\\<Squnion>\\<^sub>k f k)\"\nproof -\n  have \"i \\<in> { k . True }\"\n    by simp\n  thus \"f i \\<le> (\\<Squnion>\\<^sub>k f (k::'b))\"\n    by (metis finite_code sup_monoid.sum.insert sup_ge1 mk_disjoint_insert)\nqed\n\nlemma lub_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  assumes \"\\<forall>k . f k \\<le> x\"\n    shows \"(\\<Squnion>\\<^sub>k f k) \\<le> x\"\nproof (induct rule: one_sup_induct)\n  case one show ?case\n    by (simp add: assms)\nnext\n  case (sup j I) thus ?case\n    using assms le_supI by blast\nqed\n\nlemma lub_sum_iff:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<forall>k . f k \\<le> x) \\<longleftrightarrow> (\\<Squnion>\\<^sub>k f k) \\<le> x\"\n  using order.trans ub_sum lub_sum by blast\n\nend\n\ncontext stone_relation_algebra\nbegin\n\ntext \\<open>\nIn Stone relation algebras, we can also show that converse,  double complement and meet distribute over finite suprema.\n\\<close>\n\nlemma conv_dist_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<Squnion>\\<^sub>k (f k)\\<^sup>T) = (\\<Squnion>\\<^sub>k f k)\\<^sup>T\"\nproof (induct rule: one_sup_induct)\n  case one show ?case\n    by simp\nnext\n  case (sup j I) thus ?case\n    by (simp add: conv_dist_sup)\nqed\n\nlemma pp_dist_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<Squnion>\\<^sub>k --f k) = --(\\<Squnion>\\<^sub>k f k)\"\nproof (induct rule: one_sup_induct)\n  case one show ?case\n    by simp\nnext\n  case (sup j I) thus ?case\n    by simp\nqed\n\nlemma inf_right_dist_sum:\n  fixes f :: \"'b::finite \\<Rightarrow> 'a\"\n  shows \"(\\<Squnion>\\<^sub>k f k \\<sqinter> x) = (\\<Squnion>\\<^sub>k f k) \\<sqinter> x\"\n  by (rule comp_inf.comp_right_dist_sum)\n\nend\n\nsubsection \\<open>Square Matrices\\<close>\n\ntext \\<open>\nBecause our semiring and relation algebra type classes only work for homogeneous relations, we only look at square matrices.\n\\<close>\n\ntype_synonym ('a,'b) square = \"'a \\<times> 'a \\<Rightarrow> 'b\"\n\ntext \\<open>\nWe use standard matrix operations.\nThe Stone algebra structure is lifted componentwise.\nComposition is matrix multiplication using given composition and supremum operations.\nIts unit lifts given zero and one elements into an identity matrix.\nConverse is matrix transpose with an additional componentwise transpose.\n\\<close>\n\ndefinition less_eq_matrix :: \"('a,'b::ord) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\"                                           (infix \"\\<preceq>\" 50)   where \"f \\<preceq> g = (\\<forall>e . f e \\<le> g e)\"\ndefinition less_matrix    :: \"('a,'b::ord) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\"                                           (infix \"\\<prec>\" 50)   where \"f \\<prec> g = (f \\<preceq> g \\<and> \\<not> g \\<preceq> f)\"\ndefinition sup_matrix     :: \"('a,'b::sup) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> ('a,'b) square\"                                 (infixl \"\\<oplus>\" 65)  where \"f \\<oplus> g = (\\<lambda>e . f e \\<squnion> g e)\"\ndefinition inf_matrix     :: \"('a,'b::inf) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> ('a,'b) square\"                                 (infixl \"\\<otimes>\" 67)  where \"f \\<otimes> g = (\\<lambda>e . f e \\<sqinter> g e)\"\ndefinition minus_matrix   :: \"('a,'b::{uminus,inf}) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> ('a,'b) square\"                        (infixl \"\\<ominus>\" 65)  where \"f \\<ominus> g = (\\<lambda>e . f e \\<sqinter> -g e)\"\ndefinition implies_matrix :: \"('a,'b::implies) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> ('a,'b) square\"                             (infixl \"\\<oslash>\" 65)  where \"f \\<oslash> g = (\\<lambda>e . f e \\<leadsto> g e)\"\ndefinition times_matrix   :: \"('a,'b::{times,bounded_semilattice_sup_bot}) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> ('a,'b) square\" (infixl \"\\<odot>\" 70)  where \"f \\<odot> g = (\\<lambda>(i,j) . \\<Squnion>\\<^sub>k f (i,k) * g (k,j))\"\ndefinition uminus_matrix  :: \"('a,'b::uminus) square \\<Rightarrow> ('a,'b) square\"                                                (\"\\<ominus> _\" [80] 80)  where \"\\<ominus>f    = (\\<lambda>e . -f e)\"\ndefinition conv_matrix    :: \"('a,'b::conv) square \\<Rightarrow> ('a,'b) square\"                                                  (\"_\\<^sup>t\" [100] 100) where \"f\\<^sup>t      = (\\<lambda>(i,j) . (f (j,i))\\<^sup>T)\"\ndefinition bot_matrix     :: \"('a,'b::bot) square\"                                                                     (\"mbot\")         where \"mbot   = (\\<lambda>e . bot)\"\ndefinition top_matrix     :: \"('a,'b::top) square\"                                                                     (\"mtop\")         where \"mtop   = (\\<lambda>e . top)\"\ndefinition one_matrix     :: \"('a,'b::{one,bot}) square\"                                                               (\"mone\")         where \"mone   = (\\<lambda>(i,j) . if i = j then 1 else bot)\"\n\nsubsection \\<open>Stone Algebras\\<close>\n\ntext \\<open>\nWe first lift the Stone algebra structure.\nBecause all operations are componentwise, this also works for infinite matrices.\n\\<close>\n\ninterpretation matrix_order: order where less_eq = less_eq_matrix and less = \"less_matrix :: ('a,'b::order) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\"\n  apply unfold_locales\n  apply (simp add: less_matrix_def)\n  apply (simp add: less_eq_matrix_def)\n  apply (meson less_eq_matrix_def order_trans)\n  by (meson less_eq_matrix_def antisym ext)\n\ninterpretation matrix_semilattice_sup: semilattice_sup where sup = sup_matrix and less_eq = less_eq_matrix and less = \"less_matrix :: ('a,'b::semilattice_sup) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\"\n  apply unfold_locales\n  apply (simp add: sup_matrix_def less_eq_matrix_def)\n  apply (simp add: sup_matrix_def less_eq_matrix_def)\n  by (simp add: sup_matrix_def less_eq_matrix_def)\n\ninterpretation matrix_semilattice_inf: semilattice_inf where inf = inf_matrix and less_eq = less_eq_matrix and less = \"less_matrix :: ('a,'b::semilattice_inf) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\"\n  apply unfold_locales\n  apply (simp add: inf_matrix_def less_eq_matrix_def)\n  apply (simp add: inf_matrix_def less_eq_matrix_def)\n  by (simp add: inf_matrix_def less_eq_matrix_def)\n\ninterpretation matrix_bounded_semilattice_sup_bot: bounded_semilattice_sup_bot where sup = sup_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::bounded_semilattice_sup_bot) square\"\n  apply unfold_locales\n  by (simp add: bot_matrix_def less_eq_matrix_def)\n\ninterpretation matrix_bounded_semilattice_inf_top: bounded_semilattice_inf_top where inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and top = \"top_matrix :: ('a,'b::bounded_semilattice_inf_top) square\"\n  apply unfold_locales\n  by (simp add: less_eq_matrix_def top_matrix_def)\n\ninterpretation matrix_lattice: lattice where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = \"less_matrix :: ('a,'b::lattice) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\" ..\n\ninterpretation matrix_distrib_lattice: distrib_lattice where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = \"less_matrix :: ('a,'b::distrib_lattice) square \\<Rightarrow> ('a,'b) square \\<Rightarrow> bool\"\n  apply unfold_locales\n  by (simp add: sup_inf_distrib1 sup_matrix_def inf_matrix_def)\n\ninterpretation matrix_bounded_lattice: bounded_lattice where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::bounded_lattice) square\" and top = top_matrix ..\n\ninterpretation matrix_bounded_distrib_lattice: bounded_distrib_lattice where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::bounded_distrib_lattice) square\" and top = top_matrix ..\n\ninterpretation matrix_p_algebra: p_algebra where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::p_algebra) square\" and top = top_matrix and uminus = uminus_matrix\n  apply unfold_locales\n  apply (unfold inf_matrix_def bot_matrix_def less_eq_matrix_def uminus_matrix_def)\n  by (meson pseudo_complement)\n\ninterpretation matrix_pd_algebra: pd_algebra where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::pd_algebra) square\" and top = top_matrix and uminus = uminus_matrix ..\n\ntext \\<open>\nIn particular, matrices over Stone algebras form a Stone algebra.\n\\<close>\n\ninterpretation matrix_stone_algebra: stone_algebra where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::stone_algebra) square\" and top = top_matrix and uminus = uminus_matrix\n  by unfold_locales (simp add: sup_matrix_def uminus_matrix_def top_matrix_def)\n\ninterpretation matrix_heyting_stone_algebra: heyting_stone_algebra where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::heyting_stone_algebra) square\" and top = top_matrix and uminus = uminus_matrix and implies = implies_matrix\n  apply unfold_locales\n  apply (unfold inf_matrix_def sup_matrix_def bot_matrix_def top_matrix_def less_eq_matrix_def uminus_matrix_def implies_matrix_def)\n  apply (simp add: implies_galois)\n  apply (simp add: uminus_eq)\n  by simp\n\ninterpretation matrix_boolean_algebra: boolean_algebra where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a,'b::boolean_algebra) square\" and top = top_matrix and uminus = uminus_matrix and minus = minus_matrix\n  apply unfold_locales\n  apply simp\n  apply (simp add: sup_matrix_def uminus_matrix_def top_matrix_def)\n  by (simp add: inf_matrix_def uminus_matrix_def minus_matrix_def)\n\nsubsection \\<open>Semirings\\<close>\n\ntext \\<open>\nNext, we lift the semiring structure.\nBecause of composition, this requires a restriction to finite matrices.\n\\<close>\n\ninterpretation matrix_monoid: monoid_mult where times = times_matrix and one = \"one_matrix :: ('a::finite,'b::idempotent_semiring) square\"\nproof\n  fix f g h :: \"('a,'b) square\"\n  show \"(f \\<odot> g) \\<odot> h = f \\<odot> (g \\<odot> h)\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"((f \\<odot> g) \\<odot> h) (i,j) = (\\<Squnion>\\<^sub>l (f \\<odot> g) (i,l) * h (l,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>l (\\<Squnion>\\<^sub>k f (i,k) * g (k,l)) * h (l,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>l \\<Squnion>\\<^sub>k (f (i,k) * g (k,l)) * h (l,j))\"\n      by (metis (no_types) comp_right_dist_sum)\n    also have \"... = (\\<Squnion>\\<^sub>l \\<Squnion>\\<^sub>k f (i,k) * (g (k,l) * h (l,j)))\"\n      by (simp add: mult.assoc)\n    also have \"... = (\\<Squnion>\\<^sub>k \\<Squnion>\\<^sub>l f (i,k) * (g (k,l) * h (l,j)))\"\n      using sup_monoid.sum.swap by auto\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (\\<Squnion>\\<^sub>l g (k,l) * h (l,j)))\"\n      by (metis (no_types) comp_left_dist_sum)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g \\<odot> h) (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (f \\<odot> (g \\<odot> h)) (i,j)\"\n      by (simp add: times_matrix_def)\n    finally show \"((f \\<odot> g) \\<odot> h) (i,j) = (f \\<odot> (g \\<odot> h)) (i,j)\"\n      .\n  qed\nnext\n  fix f :: \"('a,'b) square\"\n  show \"mone \\<odot> f = f\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(mone \\<odot> f) (i,j) = (\\<Squnion>\\<^sub>k mone (i,k) * f (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k (if i = k then 1 else bot) * f (k,j))\"\n      by (simp add: one_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k if i = k then 1 * f (k,j) else bot * f (k,j))\"\n      by (metis (full_types, hide_lams))\n    also have \"... = (\\<Squnion>\\<^sub>k if i = k then f (k,j) else bot)\"\n      by (meson mult_left_one mult_left_zero)\n    also have \"... = f (i,j)\"\n      by simp\n    finally show \"(mone \\<odot> f) (i,j) = f (i,j)\"\n      .\n  qed\nnext\n  fix f :: \"('a,'b) square\"\n  show \"f \\<odot> mone = f\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(f \\<odot> mone) (i,j) = (\\<Squnion>\\<^sub>k f (i,k) * mone (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (if k = j then 1 else bot))\"\n      by (simp add: one_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k if k = j then f (i,k) * 1 else f (i,k) * bot)\"\n      by (metis (full_types, hide_lams))\n    also have \"... = (\\<Squnion>\\<^sub>k if k = j then f (i,k) else bot)\"\n      by (meson mult.right_neutral semiring.mult_zero_right)\n    also have \"... = f (i,j)\"\n      by simp\n    finally show \"(f \\<odot> mone) (i,j) = f (i,j)\"\n      .\n  qed\nqed\n\ninterpretation matrix_idempotent_semiring: idempotent_semiring where sup = sup_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a::finite,'b::idempotent_semiring) square\" and one = one_matrix and times = times_matrix\nproof\n  fix f g h :: \"('a,'b) square\"\n  show \"f \\<odot> g \\<oplus> f \\<odot> h \\<preceq> f \\<odot> (g \\<oplus> h)\"\n  proof (unfold less_eq_matrix_def, rule allI, rule prod_cases)\n    fix i j\n    have \"(f \\<odot> g \\<oplus> f \\<odot> h) (i,j) = (f \\<odot> g) (i,j) \\<squnion> (f \\<odot> h) (i,j)\"\n      by (simp add: sup_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * g (k,j)) \\<squnion> (\\<Squnion>\\<^sub>k f (i,k) * h (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * g (k,j) \\<squnion> f (i,k) * h (k,j))\"\n      by (simp add: sup_monoid.sum.distrib)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g (k,j) \\<squnion> h (k,j)))\"\n      by (simp add: mult_left_dist_sup)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g \\<oplus> h) (k,j))\"\n      by (simp add: sup_matrix_def)\n    also have \"... = (f \\<odot> (g \\<oplus> h)) (i,j)\"\n      by (simp add: times_matrix_def)\n    finally show \"(f \\<odot> g \\<oplus> f \\<odot> h) (i,j) \\<le> (f \\<odot> (g \\<oplus> h)) (i,j)\"\n      by simp\n  qed\nnext\n  fix f g h :: \"('a,'b) square\"\n  show \"(f \\<oplus> g) \\<odot> h = f \\<odot> h \\<oplus> g \\<odot> h\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"((f \\<oplus> g) \\<odot> h) (i,j) = (\\<Squnion>\\<^sub>k (f \\<oplus> g) (i,k) * h (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k (f (i,k) \\<squnion> g (i,k)) * h (k,j))\"\n      by (simp add: sup_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * h (k,j) \\<squnion> g (i,k) * h (k,j))\"\n      by (meson mult_right_dist_sup)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * h (k,j)) \\<squnion> (\\<Squnion>\\<^sub>k g (i,k) * h (k,j))\"\n      by (simp add: sup_monoid.sum.distrib)\n    also have \"... = (f \\<odot> h) (i,j) \\<squnion> (g \\<odot> h) (i,j)\"\n      by (simp add: times_matrix_def)\n    also have \"... = (f \\<odot> h \\<oplus> g \\<odot> h) (i,j)\"\n      by (simp add: sup_matrix_def)\n    finally show \"((f \\<oplus> g) \\<odot> h) (i,j) = (f \\<odot> h \\<oplus> g \\<odot> h) (i,j)\"\n      .\n  qed\nnext\n  fix f :: \"('a,'b) square\"\n  show \"mbot \\<odot> f = mbot\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(mbot \\<odot> f) (i,j) = (\\<Squnion>\\<^sub>k mbot (i,k) * f (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k bot * f (k,j))\"\n      by (simp add: bot_matrix_def)\n    also have \"... = bot\"\n      by simp\n    also have \"... = mbot (i,j)\"\n      by (simp add: bot_matrix_def)\n    finally show \"(mbot \\<odot> f) (i,j) = mbot (i,j)\"\n      .\n  qed\nnext\n  fix f :: \"('a,'b) square\"\n  show \"mone \\<odot> f = f\"\n    by simp\nnext\n  fix f :: \"('a,'b) square\"\n  show \"f \\<preceq> f \\<odot> mone\"\n    by simp\nnext\n  fix f g h :: \"('a,'b) square\"\n  show \"f \\<odot> (g \\<oplus> h) = f \\<odot> g \\<oplus> f \\<odot> h\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(f \\<odot> (g \\<oplus> h)) (i,j) = (\\<Squnion>\\<^sub>k f (i,k) * (g \\<oplus> h) (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g (k,j) \\<squnion> h (k,j)))\"\n      by (simp add: sup_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * g (k,j) \\<squnion> f (i,k) * h (k,j))\"\n      by (meson mult_left_dist_sup)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * g (k,j)) \\<squnion> (\\<Squnion>\\<^sub>k f (i,k) * h (k,j))\"\n      by (simp add: sup_monoid.sum.distrib)\n    also have \"... = (f \\<odot> g) (i,j) \\<squnion> (f \\<odot> h) (i,j)\"\n      by (simp add: times_matrix_def)\n    also have \"... = (f \\<odot> g \\<oplus> f \\<odot> h) (i,j)\"\n      by (simp add: sup_matrix_def)\n    finally show \"(f \\<odot> (g \\<oplus> h)) (i,j) = (f \\<odot> g \\<oplus> f \\<odot> h) (i,j)\"\n      .\n  qed\nnext\n  fix f :: \"('a,'b) square\"\n  show \"f \\<odot> mbot = mbot\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(f \\<odot> mbot) (i,j) = (\\<Squnion>\\<^sub>k f (i,k) * mbot (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * bot)\"\n      by (simp add: bot_matrix_def)\n    also have \"... = bot\"\n      by simp\n    also have \"... = mbot (i,j)\"\n      by (simp add: bot_matrix_def)\n    finally show \"(f \\<odot> mbot) (i,j) = mbot (i,j)\"\n      .\n  qed\nqed\n\ninterpretation matrix_bounded_idempotent_semiring: bounded_idempotent_semiring where sup = sup_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a::finite,'b::bounded_idempotent_semiring) square\" and top = top_matrix and one = one_matrix and times = times_matrix\nproof\n  fix f :: \"('a,'b) square\"\n  show \"f \\<oplus> mtop = mtop\"\n  proof\n    fix e\n    have \"(f \\<oplus> mtop) e = f e \\<squnion> mtop e\"\n      by (simp add: sup_matrix_def)\n    also have \"... = f e \\<squnion> top\"\n      by (simp add: top_matrix_def)\n    also have \"... = top\"\n      by simp\n    also have \"... = mtop e\"\n      by (simp add: top_matrix_def)\n    finally show \"(f \\<oplus> mtop) e = mtop e\"\n      .\n  qed\nqed\n\nsubsection \\<open>Stone Relation Algebras\\<close>\n\ntext \\<open>\nFinally, we show that matrices over Stone relation algebras form a Stone relation algebra.\n\\<close>\n\ninterpretation matrix_stone_relation_algebra: stone_relation_algebra where sup = sup_matrix and inf = inf_matrix and less_eq = less_eq_matrix and less = less_matrix and bot = \"bot_matrix :: ('a::finite,'b::stone_relation_algebra) square\" and top = top_matrix and uminus = uminus_matrix and one = one_matrix and times = times_matrix and conv = conv_matrix\nproof\n  fix f g h :: \"('a,'b) square\"\n  show \"(f \\<odot> g) \\<odot> h = f \\<odot> (g \\<odot> h)\"\n    by (simp add: matrix_monoid.mult_assoc)\nnext\n  fix f g h :: \"('a,'b) square\"\n  show \"(f \\<oplus> g) \\<odot> h = f \\<odot> h \\<oplus> g \\<odot> h\"\n    by (simp add: matrix_idempotent_semiring.mult_right_dist_sup)\nnext\n  fix f :: \"('a,'b) square\"\n  show \"mbot \\<odot> f = mbot\"\n    by simp\nnext\n  fix f :: \"('a,'b) square\"\n  show \"mone \\<odot> f = f\"\n    by simp\nnext\n  fix f :: \"('a,'b) square\"\n  show \"f\\<^sup>t\\<^sup>t = f\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(f\\<^sup>t\\<^sup>t) (i,j) = ((f\\<^sup>t) (j,i))\\<^sup>T\"\n      by (simp add: conv_matrix_def)\n    also have \"... = f (i,j)\"\n      by (simp add: conv_matrix_def)\n    finally show \"(f\\<^sup>t\\<^sup>t) (i,j) = f (i,j)\"\n      .\n  qed\nnext\n  fix f g :: \"('a,'b) square\"\n  show \"(f \\<oplus> g)\\<^sup>t = f\\<^sup>t \\<oplus> g\\<^sup>t\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"((f \\<oplus> g)\\<^sup>t) (i,j) = ((f \\<oplus> g) (j,i))\\<^sup>T\"\n      by (simp add: conv_matrix_def)\n    also have \"... = (f (j,i) \\<squnion> g (j,i))\\<^sup>T\"\n      by (simp add: sup_matrix_def)\n    also have \"... = (f\\<^sup>t) (i,j) \\<squnion> (g\\<^sup>t) (i,j)\"\n      by (simp add: conv_matrix_def conv_dist_sup)\n    also have \"... = (f\\<^sup>t \\<oplus> g\\<^sup>t) (i,j)\"\n      by (simp add: sup_matrix_def)\n    finally show \"((f \\<oplus> g)\\<^sup>t) (i,j) = (f\\<^sup>t \\<oplus> g\\<^sup>t) (i,j)\"\n      .\n  qed\nnext\n  fix f g :: \"('a,'b) square\"\n  show \"(f \\<odot> g)\\<^sup>t = g\\<^sup>t \\<odot> f\\<^sup>t\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"((f \\<odot> g)\\<^sup>t) (i,j) = ((f \\<odot> g) (j,i))\\<^sup>T\"\n      by (simp add: conv_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (j,k) * g (k,i))\\<^sup>T\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k (f (j,k) * g (k,i))\\<^sup>T)\"\n      by (metis (no_types) conv_dist_sum)\n    also have \"... = (\\<Squnion>\\<^sub>k (g (k,i))\\<^sup>T * (f (j,k))\\<^sup>T)\"\n      by (simp add: conv_dist_comp)\n    also have \"... = (\\<Squnion>\\<^sub>k (g\\<^sup>t) (i,k) * (f\\<^sup>t) (k,j))\"\n      by (simp add: conv_matrix_def)\n    also have \"... = (g\\<^sup>t \\<odot> f\\<^sup>t) (i,j)\"\n      by (simp add: times_matrix_def)\n    finally show \"((f \\<odot> g)\\<^sup>t) (i,j) = (g\\<^sup>t \\<odot> f\\<^sup>t) (i,j)\"\n      .\n  qed\nnext\n  fix f g h :: \"('a,'b) square\"\n  show \"(f \\<odot> g) \\<otimes> h \\<preceq> f \\<odot> (g \\<otimes> (f\\<^sup>t \\<odot> h))\"\n  proof (unfold less_eq_matrix_def, rule allI, rule prod_cases)\n    fix i j\n    have \"((f \\<odot> g) \\<otimes> h) (i,j) = (f \\<odot> g) (i,j) \\<sqinter> h (i,j)\"\n      by (simp add: inf_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * g (k,j)) \\<sqinter> h (i,j)\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * g (k,j) \\<sqinter> h (i,j))\"\n      by (metis (no_types) inf_right_dist_sum)\n    also have \"... \\<le> (\\<Squnion>\\<^sub>k f (i,k) * (g (k,j) \\<sqinter> (f (i,k))\\<^sup>T * h (i,j)))\"\n      by (rule leq_sum, meson dedekind_1)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g (k,j) \\<sqinter> (f\\<^sup>t) (k,i) * h (i,j)))\"\n      by (simp add: conv_matrix_def)\n    also have \"... \\<le> (\\<Squnion>\\<^sub>k f (i,k) * (g (k,j) \\<sqinter> (\\<Squnion>\\<^sub>l (f\\<^sup>t) (k,l) * h (l,j))))\"\n      by (rule leq_sum, rule allI, rule comp_right_isotone, rule inf.sup_right_isotone, rule ub_sum)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g (k,j) \\<sqinter> (f\\<^sup>t \\<odot> h) (k,j)))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k f (i,k) * (g \\<otimes> (f\\<^sup>t \\<odot> h)) (k,j))\"\n      by (simp add: inf_matrix_def)\n    also have \"... = (f \\<odot> (g \\<otimes> (f\\<^sup>t \\<odot> h))) (i,j)\"\n      by (simp add: times_matrix_def)\n    finally show \"((f \\<odot> g) \\<otimes> h) (i,j) \\<le> (f \\<odot> (g \\<otimes> (f\\<^sup>t \\<odot> h))) (i,j)\"\n      .\n  qed\nnext\n  fix f g :: \"('a,'b) square\"\n  show \"\\<ominus>\\<ominus>(f \\<odot> g) = \\<ominus>\\<ominus>f \\<odot> \\<ominus>\\<ominus>g\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(\\<ominus>\\<ominus>(f \\<odot> g)) (i,j) = --((f \\<odot> g) (i,j))\"\n      by (simp add: uminus_matrix_def)\n    also have \"... = --(\\<Squnion>\\<^sub>k f (i,k) * g (k,j))\"\n      by (simp add: times_matrix_def)\n    also have \"... = (\\<Squnion>\\<^sub>k --(f (i,k) * g (k,j)))\"\n      by (metis (no_types) pp_dist_sum)\n    also have \"... = (\\<Squnion>\\<^sub>k --(f (i,k)) * --(g (k,j)))\"\n      by (meson pp_dist_comp)\n    also have \"... = (\\<Squnion>\\<^sub>k (\\<ominus>\\<ominus>f) (i,k) * (\\<ominus>\\<ominus>g) (k,j))\"\n      by (simp add: uminus_matrix_def)\n    also have \"... = (\\<ominus>\\<ominus>f \\<odot> \\<ominus>\\<ominus>g) (i,j)\"\n      by (simp add: times_matrix_def)\n    finally show \"(\\<ominus>\\<ominus>(f \\<odot> g)) (i,j) = (\\<ominus>\\<ominus>f \\<odot> \\<ominus>\\<ominus>g) (i,j)\"\n      .\n  qed\nnext\n  let ?o = \"mone :: ('a,'b) square\"\n  show \"\\<ominus>\\<ominus>?o = ?o\"\n  proof (rule ext, rule prod_cases)\n    fix i j\n    have \"(\\<ominus>\\<ominus>?o) (i,j) = --(?o (i,j))\"\n      by (simp add: uminus_matrix_def)\n    also have \"... = --(if i = j then 1 else bot)\"\n      by (simp add: one_matrix_def)\n    also have \"... = (if i = j then --1 else --bot)\"\n      by simp\n    also have \"... = (if i = j then 1 else bot)\"\n      by auto\n    also have \"... = ?o (i,j)\"\n      by (simp add: one_matrix_def)\n    finally show \"(\\<ominus>\\<ominus>?o) (i,j) = ?o (i,j)\"\n      .\n  qed\nqed\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Stone_Relation_Algebras/Matrix_Relation_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8577681068080748, "lm_q1q2_score": 0.7712376346155215}}
{"text": "(*  Title:      FOL/ex/Quantifiers_Cla.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n*)\n\nsection \\<open>First-Order Logic: quantifier examples (classical version)\\<close>\n\ntheory Quantifiers_Cla\nimports FOL\nbegin\n\nlemma \\<open>(\\<forall>x y. P(x,y)) \\<longrightarrow> (\\<forall>y x. P(x,y))\\<close>\n  by fast\n\nlemma \\<open>(\\<exists>x y. P(x,y)) \\<longrightarrow> (\\<exists>y x. P(x,y))\\<close>\n  by fast\n\n\ntext \\<open>Converse is false.\\<close>\nlemma \\<open>(\\<forall>x. P(x)) \\<or> (\\<forall>x. Q(x)) \\<longrightarrow> (\\<forall>x. P(x) \\<or> Q(x))\\<close>\n  by fast\n\nlemma \\<open>(\\<forall>x. P \\<longrightarrow> Q(x)) \\<longleftrightarrow> (P \\<longrightarrow> (\\<forall>x. Q(x)))\\<close>\n  by fast\n\n\nlemma \\<open>(\\<forall>x. P(x) \\<longrightarrow> Q) \\<longleftrightarrow> ((\\<exists>x. P(x)) \\<longrightarrow> Q)\\<close>\n  by fast\n\n\ntext \\<open>Some harder ones.\\<close>\n\nlemma \\<open>(\\<exists>x. P(x) \\<or> Q(x)) \\<longleftrightarrow> (\\<exists>x. P(x)) \\<or> (\\<exists>x. Q(x))\\<close>\n  by fast\n\n\\<comment> \\<open>Converse is false.\\<close>\nlemma \\<open>(\\<exists>x. P(x) \\<and> Q(x)) \\<longrightarrow> (\\<exists>x. P(x)) \\<and> (\\<exists>x. Q(x))\\<close>\n  by fast\n\n\ntext \\<open>Basic test of quantifier reasoning.\\<close>\n\n\\<comment> \\<open>TRUE\\<close>\nlemma \\<open>(\\<exists>y. \\<forall>x. Q(x,y)) \\<longrightarrow> (\\<forall>x. \\<exists>y. Q(x,y))\\<close>\n  by fast\n\nlemma \\<open>(\\<forall>x. Q(x)) \\<longrightarrow> (\\<exists>x. Q(x))\\<close>\n  by fast\n\n\ntext \\<open>The following should fail, as they are false!\\<close>\n\nlemma \\<open>(\\<forall>x. \\<exists>y. Q(x,y)) \\<longrightarrow> (\\<exists>y. \\<forall>x. Q(x,y))\\<close>\n  apply fast?\n  oops\n\nlemma \\<open>(\\<exists>x. Q(x)) \\<longrightarrow> (\\<forall>x. Q(x))\\<close>\n  apply fast?\n  oops\n\nschematic_goal \\<open>P(?a) \\<longrightarrow> (\\<forall>x. P(x))\\<close>\n  apply fast?\n  oops\n\nschematic_goal \\<open>(P(?a) \\<longrightarrow> (\\<forall>x. Q(x))) \\<longrightarrow> (\\<forall>x. P(x) \\<longrightarrow> Q(x))\\<close>\n  apply fast?\n  oops\n\n\ntext \\<open>Back to things that are provable \\dots\\<close>\n\nlemma \\<open>(\\<forall>x. P(x) \\<longrightarrow> Q(x)) \\<and> (\\<exists>x. P(x)) \\<longrightarrow> (\\<exists>x. Q(x))\\<close>\n  by fast\n\ntext \\<open>An example of why \\<open>exI\\<close> should be delayed as long as possible.\\<close>\nlemma \\<open>(P \\<longrightarrow> (\\<exists>x. Q(x))) \\<and> P \\<longrightarrow> (\\<exists>x. Q(x))\\<close>\n  by fast\n\nschematic_goal \\<open>(\\<forall>x. P(x) \\<longrightarrow> Q(f(x))) \\<and> (\\<forall>x. Q(x) \\<longrightarrow> R(g(x))) \\<and> P(d) \\<longrightarrow> R(?a)\\<close>\n  by fast\n\nlemma \\<open>(\\<forall>x. Q(x)) \\<longrightarrow> (\\<exists>x. Q(x))\\<close>\n  by fast\n\n\ntext \\<open>Some slow ones\\<close>\n\ntext \\<open>Principia Mathematica *11.53\\<close>\nlemma \\<open>(\\<forall>x y. P(x) \\<longrightarrow> Q(y)) \\<longleftrightarrow> ((\\<exists>x. P(x)) \\<longrightarrow> (\\<forall>y. Q(y)))\\<close>\n  by fast\n\n(*Principia Mathematica *11.55  *)\nlemma \\<open>(\\<exists>x y. P(x) \\<and> Q(x,y)) \\<longleftrightarrow> (\\<exists>x. P(x) \\<and> (\\<exists>y. Q(x,y)))\\<close>\n  by fast\n\n(*Principia Mathematica *11.61  *)\nlemma \\<open>(\\<exists>y. \\<forall>x. P(x) \\<longrightarrow> Q(x,y)) \\<longrightarrow> (\\<forall>x. P(x) \\<longrightarrow> (\\<exists>y. Q(x,y)))\\<close>\n  by fast\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/FOL/ex/Quantifiers_Cla.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096044278532, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7712045588831408}}
{"text": "theory hw2\nimports Main\nbegin\n\nfun add :: \"nat \\<Rightarrow> nat\" where\n  \"add x = x + 1\"\n\nvalue \"add 3\"\n\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n  \"count x [] = 0\"\n| \"count x (y # xs) = (if x = y then add (count x xs)  else count x xs) \" \n\nvalue \"length [1::nat,3,5,3]\"\nvalue \"count (3::nat) [1,3,5,3]\"\n\ntheorem[simp]: \"count a xs <= length xs\"\n  apply (induction xs)\n  by auto\n\n (*define tree*)\ndatatype 'a tree = Tip | Node \" 'a tree\" 'a \" 'a tree\" | leave 'a\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l a r ) = Node (mirror r ) a (mirror l)\"\n| \"mirror (leave a) = leave a\"\n\ndatatype 'a list = Nil | Cons 'a \" 'a list\"\n\nthm list.induct\n\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\n\nlemma app_nil [simp]: \"app xs Nil = xs\"\n  apply (induction xs)\n  by auto\n\nlemma app_assoc [simp]: \"app xs (app ys zs) = app (app xs ys) zs\"\n  apply (induction xs)\n  by auto\n\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\nvalue \"rev(Cons True (Cons False Nil))\"\nvalue \"app (Cons a (Cons b Nil)) (Cons a (Cons c Nil))\"\n\nfun preorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"preorder Tip = Nil\" \n| \"preorder (Node l a r) = (app (app (Cons a Nil) (preorder l)) (preorder r))\"\n| \"preorder (leave a)  = (Cons a Nil)\"\n\nvalue \"preorder (Node (Node Tip f Tip) a Tip)\"\n\nfun postorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"postorder Tip = Nil\" \n| \"postorder (Node l a r) = (app (app (postorder l) (postorder r)) (Cons a Nil))\"\n| \"postorder (leave a) = (Cons a Nil)\"\n\n\nvalue \"rev (postorder (Node (Node Tip f Tip) a (Node (Node Tip a_1 Tip) a_2 (leave a_3))))\"\nvalue \"preorder (mirror (Node (Node Tip f Tip) a (Node (Node Tip a_1 Tip) a_2 (leave a_3))))\"\n\ntheorem Tip_lema1:\n \"preorder (mirror Tip) = rev (postorder Tip)\"\n  apply (induction Tip)\n  by auto\n\ntheorem leave_lema[simp]: \n \"\\<And>x. preorder (mirror (leave x)) = hw2.rev (postorder (leave x))\"\n  apply (induction)\n  by auto\n\nlemma rev_append [simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"\n  apply (induction xs)\n  by auto\n\ntheorem final : \"preorder (mirror t) = rev (postorder t)\"\n  apply (induction t)\n  by auto\n\nend", "meta": {"author": "hong-code", "repo": "ucas_Pro_theory", "sha": "94c5e854987ba4bea5ce906ef166afe48b136eef", "save_path": "github-repos/isabelle/hong-code-ucas_Pro_theory", "path": "github-repos/isabelle/hong-code-ucas_Pro_theory/ucas_Pro_theory-94c5e854987ba4bea5ce906ef166afe48b136eef/hw2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7711893388168225}}
{"text": "(*\nTitle: MoreGraph.thy\nAuthor:Wenda Li\n*)\n\ntheory MoreGraph imports Complex_Main \"../Dijkstra_Shortest_Path/Graph\"\nbegin\nsection {*Undirected Multigraph and undirected trails*}\n\nlocale valid_unMultigraph=valid_graph G for G::\"('v,'w) graph\"+\n              assumes corres[simp]: \"(v,w,u') \\<in> edges G \\<longleftrightarrow> (u',w,v) \\<in> edges G\"\n                and   no_id[simp]:\"(v,w,v) \\<notin> edges G\"\n\nfun (in valid_unMultigraph) is_trail :: \"'v \\<Rightarrow> ('v,'w) path \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n      \"is_trail v [] v' \\<longleftrightarrow> v=v' \\<and> v'\\<in> V\" |\n      \"is_trail v ((v1,w,v2)#ps) v' \\<longleftrightarrow> v=v1 \\<and> (v1,w,v2)\\<in>E \\<and> \n                (v1,w,v2)\\<notin>set ps \\<and>(v2,w,v1)\\<notin>set ps \\<and> is_trail v2 ps v'\"\n\n(*This section mainly includes lemmas related to degrees of nodes, especially when edges and paths \nare removed from an undirected graph*)\nsection {* Degrees and related properties*}\n\ndefinition degree :: \"'v \\<Rightarrow> ('v,'w) graph \\<Rightarrow> nat\" where\n    \"degree v g\\<equiv> card({e. e\\<in>edges g \\<and> fst e=v})\"\n\ndefinition odd_nodes_set :: \"('v,'w) graph \\<Rightarrow> 'v set\" where\n    \"odd_nodes_set g \\<equiv> {v. v\\<in>nodes g \\<and> odd(degree v g)}\"\n\n  (*return the number of nodes with an odd degree in the current valid multigraph*)\ndefinition num_of_odd_nodes :: \"('v, 'w) graph \\<Rightarrow> nat\" where\n    \"num_of_odd_nodes g\\<equiv> card( odd_nodes_set g)\"\n\ndefinition num_of_even_nodes :: \"('v, 'w) graph \\<Rightarrow> nat\" where\n    \"num_of_even_nodes g\\<equiv> card( {v. v\\<in>nodes g \\<and> even(degree v g)})\"\n\ndefinition del_unEdge where \"del_unEdge v e v' g \\<equiv> \\<lparr>\n    nodes = nodes g, edges = edges g - {(v,e,v'),(v',e,v)} \\<rparr>\"\n\ndefinition rev_path :: \"('v,'w) path \\<Rightarrow> ('v,'w) path\" where\n    \"rev_path ps \\<equiv> map (\\<lambda>(a,b,c).(c,b,a)) (rev ps)\"\n\nfun rem_unPath:: \"('v,'w) path \\<Rightarrow> ('v,'w) graph \\<Rightarrow> ('v,'w) graph\" where\n    \"rem_unPath [] g= g\"|\n    \"rem_unPath ((v,w,v')#ps) g= \n        rem_unPath ps (del_unEdge v w v' g)\" \n    \nlemma del_undirected: \"del_unEdge v e v' g = delete_edge v' e v (delete_edge v e v' g)\"\n  unfolding del_unEdge_def delete_edge_def by auto\n\nlemma delete_edge_sym: \"del_unEdge v e v' g = del_unEdge v' e v g\" \n  unfolding del_unEdge_def by auto\n\nlemma del_unEdge_valid[simp]: assumes \"valid_unMultigraph g\" \n    shows \"valid_unMultigraph (del_unEdge v e v' g)\"\nproof -\n  interpret valid_unMultigraph g by fact\n  show ?thesis \n    unfolding del_unEdge_def\n    by unfold_locales (auto dest: E_validD) \nqed\n\n \nlemma set_compre_diff:\"{x \\<in> A - B. P x}={x \\<in> A. P x} - {x \\<in> B . P x}\" by blast\nlemma set_compre_subset: \"B \\<subseteq> A \\<Longrightarrow> {x \\<in> B. P x} \\<subseteq> {x \\<in> A. P x}\" by blast \n\nlemma del_edge_undirected_degree_plus: \"finite (edges g) \\<Longrightarrow> (v,e,v') \\<in> edges g \n    \\<Longrightarrow> (v',e,v) \\<in> edges g  \\<Longrightarrow> degree v (del_unEdge v e v' g) + 1=degree v g\" \nproof -\n  assume assms: \"finite (edges g)\" \"(v,e,v') \\<in> edges g\" \"(v',e,v) \\<in> edges g \"\n  have \"degree v (del_unEdge v e v' g) + 1\n          = card ({ea \\<in>  edges g - {(v, e, v'), (v', e, v)}. fst ea = v}) + 1\"  \n    unfolding del_unEdge_def degree_def by simp\n  also have \"...=card ({ea \\<in>  edges g. fst ea = v} - {ea \\<in> {(v, e, v'), (v', e, v)}. \n      fst ea = v})+1\" \n    by (metis set_compre_diff) \n  also have \"...=card ({ea \\<in>  edges g. fst ea = v}) - card({ea \\<in> {(v, e, v'), (v', e, v)}. \n      fst ea = v})+1\" \n    proof -\n      have \"{(v, e, v'), (v', e, v)} \\<subseteq> edges g\" using `(v,e,v') \\<in> edges g` `(v',e,v) \\<in> edges g` \n        by auto\n      hence \"{ea \\<in> {(v, e, v'), (v', e, v)}. fst ea = v} \\<subseteq> {ea \\<in>  edges g. fst ea = v}\" by auto\n      moreover have \"finite {ea \\<in> {(v, e, v'), (v', e, v)}. fst ea = v}\" by auto\n      ultimately have \"card ({ea \\<in> edges g. fst ea = v} - {ea \\<in> {(v, e, v'), (v', e, v)}. \n          fst ea = v})=card {ea \\<in> edges g. fst ea = v} - card {ea \\<in> {(v, e, v'), (v', e, v)}.\n          fst ea = v}\"\n        using card_Diff_subset by blast\n      thus ?thesis by auto \n    qed\n  also have \"...=card ({ea \\<in>  edges g. fst ea = v})\" \n    proof -\n      have \"{ea \\<in> {(v, e, v'), (v', e, v)}. fst ea = v}={(v,e,v')}\" by auto\n      hence \"card {ea \\<in> {(v, e, v'), (v', e, v)}. fst ea = v} = 1\" by auto\n      moreover have \"card {ea \\<in> edges g. fst ea = v}\\<noteq>0\" \n        by (metis (lifting, mono_tags) Collect_empty_eq assms(1) assms(2) \n          card_eq_0_iff fst_conv mem_Collect_eq rev_finite_subset subsetI)\n      ultimately show ?thesis by arith\n    qed\n  finally have \"degree v (del_unEdge v e v' g) + 1=card ({ea \\<in>  edges g. fst ea = v})\" .\n  thus ?thesis unfolding degree_def .\nqed\n\nlemma del_edge_undirected_degree_plus': \"finite (edges g) \\<Longrightarrow> (v,e,v') \\<in> edges g \n    \\<Longrightarrow> (v',e,v) \\<in> edges g \\<Longrightarrow> degree v' (del_unEdge v e v' g) + 1=degree v' g\"\n  by (metis del_edge_undirected_degree_plus delete_edge_sym) \n\nlemma del_edge_undirected_degree_minus[simp]: \"finite (edges g) \\<Longrightarrow> (v,e,v') \\<in> edges g \n    \\<Longrightarrow> (v',e,v) \\<in> edges g \\<Longrightarrow> degree v (del_unEdge v e v' g) =degree v g- (1::nat)\" \n  using del_edge_undirected_degree_plus by (metis add_diff_cancel_left' add.commute);\n\n\n\n\nlemma del_unEdge_com: \"del_unEdge v w v' (del_unEdge n e n' g)\n          = del_unEdge n e n' (del_unEdge v w v' g)\" \n  unfolding del_unEdge_def by auto\n\nlemma rem_unPath_com: \"rem_unPath ps (del_unEdge v w v' g) \n            = del_unEdge v w v' (rem_unPath ps g)\" \nproof (induct ps arbitrary: g)\n  case Nil\n  thus ?case by (metis rem_unPath.simps(1))\nnext\n  case (Cons a ps')\n  thus ?case using del_unEdge_com \n    by (metis prod_cases3 rem_unPath.simps(1) rem_unPath.simps(2))\nqed\n\nlemma rem_unPath_valid[intro]: \n  \"valid_unMultigraph g \\<Longrightarrow> valid_unMultigraph (rem_unPath ps g)\"\nproof (induct ps )\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons x xs)\n  thus ?case \n    proof -\n    have \"valid_unMultigraph (rem_unPath (x # xs) g) = valid_unMultigraph \n         (del_unEdge (fst x) (fst (snd x)) (snd (snd x)) (rem_unPath xs g))\"\n      using rem_unPath_com by (metis pair_collapse rem_unPath.simps(2))\n    also have \"...=valid_unMultigraph (rem_unPath xs g)\" \n      by (metis Cons.hyps Cons.prems del_unEdge_valid)\n    also have \"...=True\" \n      using Cons by auto\n    finally have \"?case=True\" .\n    thus ?case by simp\n    qed\nqed \n\n\nlemma (in valid_unMultigraph) degree_frame:\n    assumes \"finite (edges G)\"  \"x \\<notin> {v, v'}\" \n    shows \"degree x (del_unEdge v w v' G) = degree x G\" (is \"?L=?R\")\nproof (cases \"(v,w,v') \\<in> edges G\")\n  case True\n  have \"?L=card({e. e\\<in>edges G - {(v,w,v'),(v',w,v)} \\<and> fst e=x})\" \n    by (simp add:del_unEdge_def degree_def)\n  also have \"...=card({e. e\\<in>edges G \\<and> fst e=x}-{e. e\\<in>{(v,w,v'),(v',w,v)} \\<and> fst e=x})\"\n    by (metis  set_compre_diff)\n  also have \"...=card({e. e\\<in>edges G \\<and> fst e=x})\" using `x \\<notin> {v, v'}` \n    proof -\n      have \"x\\<noteq>v \\<and> x\\<noteq> v'\" using `x\\<notin>{v,v'}`by simp\n      hence \"{e. e\\<in>{(v,w,v'),(v',w,v)} \\<and> fst e=x}={}\" by auto\n      thus ?thesis by (metis Diff_empty)\n    qed\n  also have \"...=?R\" by (simp add:degree_def)\n  finally show ?thesis .\nnext\n  case False\n  moreover hence \"(v',w,v)\\<notin>E\" using corres by auto\n  ultimately have \"E- {(v,w,v'),(v',w,v)}=E\" by blast   \n  hence \"del_unEdge v w v' G=G\" by (auto simp add:del_unEdge_def)\n  thus ?thesis by auto\nqed\n\n\n\nlemma del_UnEdge_node[simp]: \"v\\<in>nodes (del_unEdge u e u' G) \\<longleftrightarrow> v\\<in>nodes G  \" \n    by (metis del_unEdge_def select_convs(1))\n\nlemma [intro!]: \"finite (edges G) \\<Longrightarrow> finite (edges (del_unEdge u e u' G))\"\n    by (metis del_unEdge_def finite_Diff select_convs(2))\n\nlemma [intro!]: \"finite (nodes G) \\<Longrightarrow> finite (nodes (del_unEdge u e u' G))\"\n    by (metis del_unEdge_def select_convs(1))\n \nlemma [intro!]: \"finite (edges G) \\<Longrightarrow> finite (edges (rem_unPath ps G))\"\nproof (induct ps arbitrary:G)\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons x xs)\n  hence \"finite (edges (rem_unPath (x # xs) G)) = finite (edges (del_unEdge \n          (fst x) (fst (snd x)) (snd (snd x)) (rem_unPath xs G)))\" \n    by (metis rem_unPath.simps(2) rem_unPath_com surjective_pairing)\n  also have \"...=finite (edges (rem_unPath xs G))\" \n    using del_unEdge_def  \n    by (metis  finite.emptyI finite_Diff2 finite_Diff_insert select_convs(2))\n  also have \"...=True\" using Cons by auto\n  finally have \"?case = True\" .\n  thus ?case by simp\nqed\n\nlemma del_UnEdge_frame[intro]: \n  \"x\\<in>edges g \\<Longrightarrow> x\\<noteq>(v,e,v') \\<Longrightarrow>x\\<noteq>(v',e,v) \\<Longrightarrow> x\\<in>edges (del_unEdge v e v' g)\"\n  unfolding del_unEdge_def by auto\n\nlemma [intro!]: \"finite (nodes G) \\<Longrightarrow> finite (odd_nodes_set G)\"\n    by (metis (lifting) mem_Collect_eq odd_nodes_set_def rev_finite_subset subsetI)\n\nlemma [simp]: \"nodes (del_unEdge u e u' G)=nodes G\" \n    by (metis del_unEdge_def select_convs(1))\n\nlemma [simp]: \"nodes (rem_unPath ps G) = nodes G\" \nproof (induct ps)\n  case Nil\n  show ?case by simp\nnext \n  case (Cons x xs)\n  have \"nodes (rem_unPath (x # xs) G)=nodes (del_unEdge \n        (fst x) (fst (snd x)) (snd (snd x)) (rem_unPath xs G))\" \n    by (metis rem_unPath.simps(2) rem_unPath_com surjective_pairing)\n  also have \"...=nodes (rem_unPath xs G)\" by auto\n  also have \"...=nodes G\" using Cons by auto\n  finally show ?case .\nqed\n\nlemma [intro!]: \"finite (nodes G) \\<Longrightarrow> finite (nodes (rem_unPath ps G))\" by auto\n\nlemma in_set_rev_path[simp]: \"(v',w,v )\\<in>set (rev_path ps) \\<longleftrightarrow> (v,w,v')\\<in>set ps \" \nproof (induct ps)\n  case Nil\n  thus ?case unfolding rev_path_def by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n  have \"set (rev_path (x # xs))=set ((rev_path xs)@[(x3,x2,x1)])\" \n    unfolding rev_path_def \n    using x by auto\n  also have \"...=set (rev_path xs) \\<union> {(x3,x2,x1)}\" by auto\n  finally have \"set (rev_path (x # xs)) =set (rev_path xs) \\<union> {(x3,x2,x1)}\" .\n  moreover have \"set (x#xs)= set xs \\<union> {(x1,x2,x3)}\" \n    by (metis List.set_simps(2) insert_is_Un sup_commute x)\n  ultimately show ?case using Cons by auto\nqed\n\nlemma rem_unPath_edges: \n    \"edges(rem_unPath ps G) = edges G - (set ps \\<union> set (rev_path ps))\" \nproof (induct ps)\n  case Nil\n  show ?case unfolding rev_path_def by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x: \"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence \"edges(rem_unPath (x#xs) G)= edges(del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n    by (metis rem_unPath.simps(2) rem_unPath_com)\n  also have \"...=edges(rem_unPath xs G)-{(x1,x2,x3),(x3,x2,x1)}\"\n    by (metis del_unEdge_def select_convs(2))\n  also have \"...= edges G - (set xs \\<union> set (rev_path xs))-{(x1,x2,x3),(x3,x2,x1)}\"\n    by (metis Cons.hyps)\n  also have \"...=edges G - (set (x#xs) \\<union> set (rev_path (x#xs)))\"  \n    proof -\n      have \"set (rev_path xs) \\<union> {(x3,x2,x1)}=set ((rev_path xs)@[(x3,x2,x1)])\" \n        by (metis List.set_simps(2) empty_set set_append)\n      also have \"...=set (rev_path (x#xs))\" unfolding rev_path_def using  x by auto\n      finally have \"set (rev_path xs) \\<union> {(x3,x2,x1)}=set (rev_path (x#xs))\" .\n      moreover have \"set xs \\<union> {(x1,x2,x3)}=set (x#xs)\" \n        by (metis List.set_simps(2) insert_is_Un sup_commute x)\n      moreover have \"edges G - (set xs \\<union> set (rev_path xs))-{(x1,x2,x3),(x3,x2,x1)} =\n                      edges G - ((set xs \\<union> {(x1,x2,x3)}) \\<union> (set (rev_path xs) \\<union> {(x3,x2,x1)}))\" \n        by auto \n      ultimately show ?thesis by auto\n    qed\n  finally show ?case .\nqed  \n\nlemma [simp]: \"rev_path (rev_path ps)= ps\" unfolding rev_path_def by (induct ps,auto)\n\nlemma rem_unPath_graph [simp]: \n    \"rem_unPath (rev_path ps) G=rem_unPath ps G\"\nproof -\n  have \"nodes(rem_unPath (rev_path ps) G)=nodes(rem_unPath ps G)\" \n    by auto\n  moreover have \"edges(rem_unPath (rev_path ps) G)=edges(rem_unPath ps G)\"  \n    proof -\n      have \"set (rev_path ps) \\<union> set (rev_path (rev_path ps)) = set ps \\<union>  set (rev_path ps) \" \n        by auto\n      thus ?thesis by (metis rem_unPath_edges)\n    qed\n  ultimately show ?thesis by auto\nqed \n\nlemma distinct_rev_path[simp]: \"distinct (rev_path ps) \\<longleftrightarrow>distinct ps\" \nproof (induct ps)\n  case Nil\n  show ?case by auto\nnext \n  case (Cons x xs)\n  obtain x1 x2 x3 where x: \"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence \"distinct (rev_path (x # xs))=distinct ((rev_path xs)@[(x3,x2,x1)])\" \n    unfolding rev_path_def by auto\n  also have \"...= (distinct (rev_path xs) \\<and> (x3,x2,x1)\\<notin>set (rev_path xs))\" \n    by (metis distinct.simps(2) distinct1_rotate rotate1.simps(2))\n  also have \"...=distinct (x#xs)\" \n    by (metis Cons.hyps distinct.simps(2) in_set_rev_path x)\n  finally have \"distinct (rev_path (x # xs))=distinct (x#xs)\" .\n  thus ?case .\nqed\n\n\nlemma (in valid_unMultigraph) is_path_rev: \"is_path v' (rev_path ps) v \\<longleftrightarrow> is_path v ps v'\" \nproof (induct ps arbitrary: v)\n  case Nil\n  show ?case by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x: \"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence \"is_path v' (rev_path (x # xs)) v=is_path v' ((rev_path xs) @[(x3,x2,x1)]) v\" \n    unfolding rev_path_def by auto\n  also have \"...=(is_path v' (rev_path xs) x3 \\<and> (x3,x2,x1)\\<in>E \\<and> is_path x1 [] v)\" by auto\n  also have \"...=(is_path x3 xs v' \\<and> (x3,x2,x1)\\<in>E \\<and> is_path x1 [] v)\" using Cons.hyps by auto\n  also have \"...=is_path v (x#xs) v'\" \n    by (metis corres is_path.simps(1) is_path.simps(2) is_path_memb x)\n  finally have \"is_path v' (rev_path (x # xs)) v=is_path v (x#xs) v'\" .\n  thus ?case .\nqed\n\n\nlemma (in valid_unMultigraph) singleton_distinct_path [intro]:\n   \"(v,w,v')\\<in>E \\<Longrightarrow> is_trail v [(v,w,v')] v'\" \n   by (metis E_validD(2) all_not_in_conv is_trail.simps set_empty) \n  \nlemma (in valid_unMultigraph) is_trail_path: \n  \"is_trail v ps v' \\<longleftrightarrow> is_path v ps v' \\<and> distinct ps \\<and> (set ps \\<inter> set (rev_path ps) = {})\"\nproof (induct ps arbitrary:v)\n  case Nil\n  show ?case by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x: \"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence \"is_trail v (x#xs) v'= (v=x1 \\<and> (x1,x2,x3)\\<in>E \\<and> \n                (x1,x2,x3)\\<notin>set xs \\<and>(x3,x2,x1)\\<notin>set xs \\<and> is_trail x3 xs v')\" \n    by (metis is_trail.simps(2))\n  also have \"...=(v=x1 \\<and> (x1,x2,x3)\\<in>E \\<and>  (x1,x2,x3)\\<notin>set xs \\<and>(x3,x2,x1)\\<notin>set xs \\<and> is_path x3 xs v' \n                  \\<and> distinct xs \\<and> (set xs \\<inter> set (rev_path xs)={}))\" \n    using Cons.hyps by auto\n  also have \"...=(is_path v (x#xs) v' \\<and> (x1,x2,x3) \\<noteq> (x3,x2,x1) \\<and> (x1,x2,x3)\\<notin>set xs \n                  \\<and>(x3,x2,x1)\\<notin>set xs \\<and> distinct xs \\<and> (set xs \\<inter> set (rev_path xs)={}))\"\n    by (metis append_Nil is_path.simps(1) is_path_simps(2) is_path_split' no_id x)\n  also have \"...=(is_path v (x#xs) v' \\<and> (x1,x2,x3) \\<noteq> (x3,x2,x1) \\<and>(x3,x2,x1)\\<notin>set xs \n                  \\<and> distinct (x#xs) \\<and> (set xs \\<inter> set (rev_path xs)={}))\"\n    by (metis (full_types) distinct.simps(2) x)\n  also have \"...=(is_path v (x#xs) v' \\<and> (x1,x2,x3) \\<noteq> (x3,x2,x1) \\<and> distinct (x#xs) \n                  \\<and> (x3,x2,x1)\\<notin>set xs \\<and> set xs \\<inter> set (rev_path (x#xs))={})\" \n    proof -\n      have \"set (rev_path (x#xs)) = set ((rev_path xs)@[(x3,x2,x1)])\" using x by auto\n      also have \"... = set (rev_path xs) \\<union> {(x3,x2,x1)}\" by auto\n      finally have \"set (rev_path (x#xs))=set (rev_path xs) \\<union> {(x3,x2,x1)}\" .\n      thus ?thesis by blast\n    qed\n  also have \"...=(is_path v (x#xs) v'\\<and> distinct (x#xs) \\<and> (set (x#xs) \\<inter> set (rev_path (x#xs))={}))\"\n    proof -\n      have \"(x3,x2,x1)\\<notin>set xs \\<longleftrightarrow> (x1,x2,x3)\\<notin> set (rev_path xs)\" using in_set_rev_path by auto\n      moreover have  \"set (rev_path (x#xs))=set (rev_path xs) \\<union> {(x3,x2,x1)}\" \n        unfolding rev_path_def using x by auto\n      ultimately have \" (x1,x2,x3) \\<noteq> (x3,x2,x1)\\<and> (x3,x2,x1)\\<notin>set xs \n                        \\<longleftrightarrow> (x1,x2,x3)\\<notin> set (rev_path (x#xs))\"  by blast \n      thus ?thesis \n        by (metis (mono_tags) Int_iff Int_insert_left_if0 List.set_simps(2) empty_iff insertI1 x)\n    qed\n  finally have \"is_trail v (x#xs) v'\\<longleftrightarrow>(is_path v (x#xs) v'\\<and> distinct (x#xs) \n                  \\<and> (set (x#xs) \\<inter> set (rev_path (x#xs))={}))\" .\n  thus ?case .\nqed      \n \nlemma  (in valid_unMultigraph) is_trail_rev: \n    \"is_trail v' (rev_path ps) v \\<longleftrightarrow> is_trail v ps v' \" \n    using rev_path_append is_trail_path  is_path_rev distinct_rev_path\n    by (metis Int_commute distinct_append)\n\nlemma (in valid_unMultigraph) is_trail_intro[intro]:\n  \"is_trail v' ps v \\<Longrightarrow> is_path v' ps v\" by (induct ps arbitrary:v',auto)   \n\nlemma (in valid_unMultigraph) is_trail_split:\n      \"is_trail v (p1@p2) v' \\<Longrightarrow> (\\<exists>u. is_trail v p1 u \\<and> is_trail u p2 v')\"\napply (induct p1 arbitrary: v,auto) \napply (metis is_trail_intro is_path_memb)\ndone\n\nlemma (in valid_unMultigraph) is_trail_split':\"is_trail v (p1@(u,w,u')#p2) v' \n    \\<Longrightarrow> is_trail v p1 u \\<and> (u,w,u')\\<in>E \\<and> is_trail u' p2 v'\"\n  by (metis is_trail.simps(2) is_trail_split)\n\nlemma (in valid_unMultigraph) distinct_elim[simp]:\n  assumes \"is_trail v ((v1,w,v2)#ps) v'\" \n  shows \"(v1,w,v2)\\<in>edges(rem_unPath ps G) \\<longleftrightarrow> (v1,w,v2)\\<in>E\" \nproof \n  assume \"(v1, w, v2) \\<in> edges (rem_unPath ps G)\"\n  thus \"(v1, w, v2) \\<in> E\" by (metis assms is_trail.simps(2))\nnext\n  assume \"(v1, w, v2) \\<in> E\"\n  have \"(v1,w,v2)\\<notin>set ps \\<and> (v2,w,v1)\\<notin>set ps\" by (metis assms is_trail.simps(2))\n  hence \"(v1,w,v2)\\<notin>set ps \\<and> (v1,w,v2)\\<notin>set (rev_path ps)\" by simp\n  hence \"(v1,w,v2)\\<notin>set ps \\<union> set (rev_path ps)\" by simp\n  hence \"(v1,w,v2)\\<in>edges G - (set ps \\<union> set (rev_path ps))\"\n    using `(v1, w, v2) \\<in> E` by auto\n  thus \"(v1,w,v2)\\<in>edges(rem_unPath ps G)\" \n    by (metis rem_unPath_edges)\nqed\n\nlemma distinct_path_subset:\n  assumes \"valid_unMultigraph G1\" \"valid_unMultigraph G2\" \"edges G1 \\<subseteq>edges G2\" \"nodes G1 \\<subseteq>nodes G2\"\n  assumes distinct_G1:\"valid_unMultigraph.is_trail G1 v ps v'\"\n  shows \"valid_unMultigraph.is_trail G2 v ps v'\" using distinct_G1\nproof (induct ps arbitrary:v)\n  case Nil\n  hence \"v=v'\\<and>v'\\<in>nodes G1\" \n    by (metis (full_types) assms(1) valid_unMultigraph.is_trail.simps(1))\n  hence \"v=v'\\<and>v'\\<in>nodes G2\" using `nodes G1 \\<subseteq> nodes G2` by auto\n  thus ?case by (metis assms(2) valid_unMultigraph.is_trail.simps(1))\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence \"valid_unMultigraph.is_trail G1 x3 xs v'\"\n    by (metis Cons.prems assms(1) valid_unMultigraph.is_trail.simps(2)) \n  hence \"valid_unMultigraph.is_trail G2 x3 xs v'\" using Cons by auto\n  moreover have \"x\\<in>edges G1\"\n    by (metis Cons.prems assms(1) valid_unMultigraph.is_trail.simps(2) x)\n  hence \"x\\<in>edges G2\" using `edges G1 \\<subseteq> edges G2` by auto\n  moreover have \"v=x1\\<and>(x1,x2,x3)\\<notin>set xs\\<and>(x3,x2,x1)\\<notin>set xs\"\n    by (metis Cons.prems assms(1) valid_unMultigraph.is_trail.simps(2) x)\n  hence \"v=x1\" \"(x1,x2,x3)\\<notin>set xs\" \"(x3,x2,x1)\\<notin>set xs\" by auto\n  ultimately show ?case by (metis assms(2) valid_unMultigraph.is_trail.simps(2) x)\nqed\n\nlemma (in valid_unMultigraph) distinct_path_intro':\n  assumes \"valid_unMultigraph.is_trail (rem_unPath p G) v ps v'\"\n  shows \"is_trail  v ps v'\" \nproof -\n  have valid:\"valid_unMultigraph (rem_unPath p G)\"\n    using rem_unPath_valid[OF valid_unMultigraph_axioms,of p] by auto\n  moreover have \"nodes (rem_unPath p G) \\<subseteq> V\" by auto\n  moreover have \"edges (rem_unPath p G) \\<subseteq> E\" \n    using rem_unPath_edges by auto\n  ultimately show ?thesis \n    using distinct_path_subset[of \"rem_unPath p G\" G] valid_unMultigraph_axioms assms \n    by auto\nqed\n\nlemma (in valid_unMultigraph) distinct_path_intro:\n  assumes \"valid_unMultigraph.is_trail (del_unEdge x1 x2 x3 G) v ps v'\"\n  shows \"is_trail  v ps v'\" \nby (metis (full_types) assms distinct_path_intro' rem_unPath.simps(1) \n    rem_unPath.simps(2))\n\n\n\nlemma (in valid_unMultigraph) del_UnEdge_even':\n  assumes \"(v,w,v') \\<in> E\" \"finite E\"\n  shows \"v'\\<in>odd_nodes_set(del_unEdge v w v' G) \\<longleftrightarrow> even (degree v' G)\" \nproof -\n  show ?thesis by (metis (full_types) assms corres del_UnEdge_even delete_edge_sym)          \nqed\n\nlemma del_UnEdge_even_even:\n    assumes \"valid_unMultigraph G\" \"finite(edges G)\" \"finite(nodes G)\" \"(v, w, v')\\<in>edges G\"\n    assumes parity_assms: \"even (degree v G)\" \"even (degree v' G)\"\n    shows \"num_of_odd_nodes(del_unEdge v w v' G)=num_of_odd_nodes G + 2\"\nproof -\n  interpret G:valid_unMultigraph by fact \n  have  \"v\\<in>odd_nodes_set(del_unEdge v w v' G)\"  \n    by (metis G.del_UnEdge_even assms(2) assms(4) parity_assms(1))\n  moreover have  \"v'\\<in>odd_nodes_set(del_unEdge v w v' G)\"  \n    by (metis G.del_UnEdge_even' assms(2) assms(4) parity_assms(2))\n  ultimately have extra_odd_nodes:\"{v,v'} \\<subseteq> odd_nodes_set(del_unEdge v w v' G)\"\n    unfolding odd_nodes_set_def by auto\n  moreover have \"v \\<notin>odd_nodes_set G\" and \"v'\\<notin>odd_nodes_set G\" \n    using parity_assms unfolding odd_nodes_set_def by auto \n  hence vv'_odd_disjoint: \"{v,v'} \\<inter> odd_nodes_set G = {}\" by auto\n  moreover have \"odd_nodes_set(del_unEdge v w v' G) -{v,v'}\\<subseteq>odd_nodes_set G \" \n    proof\n      fix x\n      assume x_odd_set: \"x \\<in> odd_nodes_set (del_unEdge v w v' G) - {v, v'}\"\n      hence \"degree x (del_unEdge v w v' G) = degree x G\" \n        by (metis Diff_iff G.degree_frame assms(2))\n      hence \"odd(degree x G)\" using x_odd_set\n        unfolding odd_nodes_set_def by auto\n      moreover have \"x \\<in> nodes G\" using x_odd_set unfolding odd_nodes_set_def by auto\n      ultimately show \"x \\<in> odd_nodes_set G\" unfolding odd_nodes_set_def by auto\n    qed\n  moreover have \"odd_nodes_set G \\<subseteq> odd_nodes_set(del_unEdge v w v' G)\" \n    proof \n      fix x\n      assume x_odd_set:  \"x \\<in> odd_nodes_set G\"\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> odd(degree x (del_unEdge v w v' G))\" \n        by (metis (lifting) G.degree_frame assms(2) mem_Collect_eq odd_nodes_set_def)\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> x\\<in>odd_nodes_set(del_unEdge v w v' G)\" \n        using x_odd_set del_UnEdge_node unfolding odd_nodes_set_def by auto \n      moreover have \"x\\<in>{v,v'} \\<Longrightarrow> x\\<in>odd_nodes_set(del_unEdge v w v' G)\" \n        using extra_odd_nodes by auto\n      ultimately show \"x \\<in> odd_nodes_set (del_unEdge v w v' G)\" by auto\n    qed\n  ultimately have \"odd_nodes_set(del_unEdge v w v' G)=odd_nodes_set G \\<union> {v,v'}\" by auto\n  thus \"num_of_odd_nodes(del_unEdge v w v' G) = num_of_odd_nodes G + 2\"\n    proof -\n      assume \"odd_nodes_set(del_unEdge v w v' G)=odd_nodes_set G \\<union> {v,v'}\"\n      moreover have \"v\\<noteq>v'\" using G.no_id `(v,w,v')\\<in>edges G` by auto\n      hence \"card{v,v'}=2\" by simp\n      moreover have \" odd_nodes_set G \\<inter> {v,v'} = {}\" \n        using vv'_odd_disjoint by auto\n      moreover have \"finite(odd_nodes_set G)\" \n        by (metis (lifting) assms(3) mem_Collect_eq odd_nodes_set_def rev_finite_subset subsetI)\n      moreover have \"finite {v,v'}\" by auto\n      ultimately show ?thesis unfolding num_of_odd_nodes_def using card_Un_disjoint by metis\n    qed\nqed\n  \nlemma del_UnEdge_even_odd:\n    assumes \"valid_unMultigraph G\" \"finite(edges G)\" \"finite(nodes G)\" \"(v, w, v')\\<in>edges G\"\n    assumes parity_assms: \"even (degree v G)\" \"odd (degree v' G)\"\n    shows \"num_of_odd_nodes(del_unEdge v w v' G)=num_of_odd_nodes G\"\nproof -\n  interpret G : valid_unMultigraph by fact\n  have odd_v:\"v\\<in>odd_nodes_set(del_unEdge v w v' G)\" \n    by (metis G.del_UnEdge_even assms(2) assms(4) parity_assms(1))\n  have  not_odd_v':\"v'\\<notin>odd_nodes_set(del_unEdge v w v' G)\"\n    by (metis G.del_UnEdge_even' assms(2) assms(4) parity_assms(2))\n  have \"odd_nodes_set(del_unEdge v w v' G) \\<union> {v'} \\<subseteq>odd_nodes_set G \\<union> {v}\"\n    proof \n      fix x \n      assume x_prems:\" x \\<in> odd_nodes_set (del_unEdge v w v' G) \\<union> {v'}\"\n      have \"x=v' \\<Longrightarrow>x\\<in>odd_nodes_set G \\<union> {v}\" \n        using parity_assms\n        by (metis (lifting) G.E_validD(2) Un_def assms(4) mem_Collect_eq odd_nodes_set_def )\n      moreover have \"x=v \\<Longrightarrow> x\\<in>odd_nodes_set G \\<union> {v}\"  \n        by (metis insertI1 insert_is_Un sup_commute)\n      moreover have \"x\\<notin>{v,v'} \\<Longrightarrow> x \\<in> odd_nodes_set (del_unEdge v w v' G)\" \n        using x_prems by auto\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> x \\<in> odd_nodes_set G\" unfolding odd_nodes_set_def\n        using G.degree_frame `finite (edges G)` by auto\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> x\\<in>odd_nodes_set G \\<union> {v}\" by simp \n      ultimately show \"x \\<in> odd_nodes_set G \\<union> {v}\" by auto\n    qed\n  moreover have \"odd_nodes_set G \\<union> {v} \\<subseteq> odd_nodes_set(del_unEdge v w v' G) \\<union> {v'}\" \n    proof\n      fix x\n      assume x_prems: \"x \\<in> odd_nodes_set G \\<union> {v}\"\n      have \"x=v \\<Longrightarrow> x \\<in> odd_nodes_set (del_unEdge v w v' G) \\<union> {v'}\" \n        by (metis UnI1 odd_v)\n      moreover have \"x=v' \\<Longrightarrow> x \\<in> odd_nodes_set (del_unEdge v w v' G) \\<union> {v'}\" \n        by auto\n      moreover have \"x\\<notin>{v,v'} \\<Longrightarrow> x \\<in> odd_nodes_set G \\<union> {v}\" using x_prems by auto\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow>  x\\<in>odd_nodes_set (del_unEdge v w v' G)\" unfolding odd_nodes_set_def\n        using G.degree_frame `finite (edges G)` by auto\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> x \\<in> odd_nodes_set (del_unEdge v w v' G) \\<union> {v'}\" by simp\n        ultimately show \"x \\<in> odd_nodes_set (del_unEdge v w v' G) \\<union> {v'}\" by auto\n    qed\n  ultimately have \"odd_nodes_set(del_unEdge v w v' G) \\<union> {v'} = odd_nodes_set G \\<union> {v}\"\n    by auto\n  moreover have \" odd_nodes_set G \\<inter> {v} = {}\" \n    using parity_assms unfolding odd_nodes_set_def by auto\n  moreover have \" odd_nodes_set(del_unEdge v w v' G) \\<inter> {v'}={}\" \n    by (metis Int_insert_left_if0 inf_bot_left inf_commute not_odd_v')\n  moreover have \"finite (odd_nodes_set(del_unEdge v w v' G))\" \n     using `finite (nodes G)` by auto\n  moreover have \"finite (odd_nodes_set G)\" using `finite (nodes G)` by auto\n  ultimately have \"card(odd_nodes_set G) + card {v} = \n                   card(odd_nodes_set(del_unEdge v w v' G)) + card {v'}\" \n    using card_Un_disjoint[of \"odd_nodes_set (del_unEdge v w v' G)\" \"{v'}\"] \n      card_Un_disjoint[of \"odd_nodes_set G\" \"{v}\"] \n    by auto \n  thus ?thesis unfolding num_of_odd_nodes_def by simp \nqed  \n  \nlemma del_UnEdge_odd_even:\n    assumes \"valid_unMultigraph G\" \"finite(edges G)\" \"finite(nodes G)\" \"(v, w, v')\\<in>edges G\"\n    assumes parity_assms: \"odd (degree v G)\" \"even (degree v' G)\"\n    shows \"num_of_odd_nodes(del_unEdge v w v' G)=num_of_odd_nodes G\"  \nby (metis assms del_UnEdge_even_odd delete_edge_sym parity_assms valid_unMultigraph.corres)\n \nlemma del_UnEdge_odd_odd:\n    assumes \"valid_unMultigraph G\" \"finite(edges G)\" \"finite(nodes G)\" \"(v, w, v')\\<in>edges G\"\n    assumes parity_assms: \"odd (degree v G)\" \"odd (degree v' G)\"\n    shows \"num_of_odd_nodes G=num_of_odd_nodes(del_unEdge v w v' G)+2\"\nproof -\n  interpret G:valid_unMultigraph by fact\n  have  \"v\\<notin>odd_nodes_set(del_unEdge v w v' G)\"  \n    by (metis G.del_UnEdge_even assms(2) assms(4) parity_assms(1))\n  moreover have  \"v'\\<notin>odd_nodes_set(del_unEdge v w v' G)\"  \n    by (metis G.del_UnEdge_even' assms(2) assms(4) parity_assms(2))\n  ultimately have vv'_disjoint: \"{v,v'} \\<inter> odd_nodes_set(del_unEdge v w v' G) = {}\" \n    by (metis (full_types) Int_insert_left_if0 inf_bot_left)\n  moreover have extra_odd_nodes:\"{v,v'} \\<subseteq> odd_nodes_set( G)\"\n    unfolding odd_nodes_set_def \n    using `(v,w,v')\\<in>edges G`\n    by (metis (lifting) G.E_validD empty_subsetI insert_subset mem_Collect_eq parity_assms)  \n  moreover have \"odd_nodes_set G -{v,v'}\\<subseteq>odd_nodes_set (del_unEdge v w v' G) \" \n    proof\n      fix x\n      assume x_odd_set: \"x \\<in> odd_nodes_set G - {v, v'}\"\n      hence \"degree x G = degree x (del_unEdge v w v' G)\" \n        by (metis Diff_iff G.degree_frame assms(2))\n      hence \"odd(degree x (del_unEdge v w v' G))\" using x_odd_set \n        unfolding odd_nodes_set_def by auto\n      moreover have \"x \\<in> nodes (del_unEdge v w v' G)\" \n        using x_odd_set unfolding odd_nodes_set_def by auto\n      ultimately show \"x \\<in> odd_nodes_set (del_unEdge v w v' G)\" \n        unfolding odd_nodes_set_def by auto\n    qed\n  moreover have \"odd_nodes_set (del_unEdge v w v' G) \\<subseteq> odd_nodes_set G\" \n    proof \n      fix x\n      assume x_odd_set:  \"x \\<in> odd_nodes_set (del_unEdge v w v' G)\"\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> odd(degree x G)\" \n        using assms G.degree_frame unfolding odd_nodes_set_def\n        by auto\n      hence \"x\\<notin>{v,v'} \\<Longrightarrow> x\\<in>odd_nodes_set G\" \n        using x_odd_set del_UnEdge_node unfolding odd_nodes_set_def  \n        by auto\n      moreover have \"x\\<in>{v,v'} \\<Longrightarrow> x\\<in>odd_nodes_set G\" \n        using extra_odd_nodes by auto\n      ultimately show \"x \\<in> odd_nodes_set G\" by auto\n    qed\n  ultimately have \"odd_nodes_set G=odd_nodes_set (del_unEdge v w v' G) \\<union> {v,v'}\" \n    by auto\n  thus ?thesis\n    proof -\n      assume \"odd_nodes_set G=odd_nodes_set (del_unEdge v w v' G) \\<union> {v,v'}\"\n      moreover have \" odd_nodes_set (del_unEdge v w v' G) \\<inter> {v,v'} = {}\" \n        using vv'_disjoint by auto\n      moreover have \"finite(odd_nodes_set (del_unEdge v w v' G))\" \n        using assms del_UnEdge_node finite_subset unfolding odd_nodes_set_def\n        by auto\n      moreover have \"finite {v,v'}\" by auto\n      ultimately have \"card(odd_nodes_set G)\n                       = card(odd_nodes_set  (del_unEdge v w v' G)) + card{v,v'}\"\n        unfolding num_of_odd_nodes_def \n        using card_Un_disjoint \n        by metis \n      moreover have \"v\\<noteq>v'\" using G.no_id `(v,w,v')\\<in>edges G` by auto\n      hence \"card{v,v'}=2\" by simp\n      ultimately show ?thesis unfolding num_of_odd_nodes_def by simp\n    qed\nqed \n\nlemma (in valid_unMultigraph) rem_UnPath_parity_v': \n  assumes \"finite E\"  \"is_trail v ps v'\" \n  shows \"v\\<noteq>v' \\<longleftrightarrow> (odd (degree v' (rem_unPath ps G)) = even(degree v' G))\" using assms \nproof (induct ps arbitrary:v)\n  case Nil\n  thus ?case by (metis is_trail.simps(1) rem_unPath.simps(1))\nnext\n  case (Cons x xs) print_cases\n  obtain x1 x2 x3 where x: \"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence rem_x:\"odd (degree v' (rem_unPath (x#xs) G)) = odd(degree v' (del_unEdge\n            x1 x2 x3 (rem_unPath xs G)))\" \n    by (metis  rem_unPath.simps(2) rem_unPath_com)\n  have \"x3=v' \\<Longrightarrow> ?case\" \n    proof (cases \"v=v'\")\n      case True \n      assume \"x3=v'\"\n      have \"x1=v'\" using x by (metis Cons.prems(2) True is_trail.simps(2))\n      thus ?thesis using `x3=v'` by (metis Cons.prems(2) is_trail.simps(2) no_id x)\n    next\n      case False\n      assume \"x3=v'\"\n      have \"odd (degree v' (rem_unPath (x # xs) G)) =odd(degree v' (\n            del_unEdge x1 x2 x3 (rem_unPath xs G)))\" using rem_x .\n      also have \"...=odd(degree v' (rem_unPath xs G) - 1)\" \n        proof -\n          have \"finite (edges (rem_unPath xs G))\" \n            by (metis (full_types) assms(1) finite_Diff rem_unPath_edges)\n          moreover have \"(x1,x2,x3) \\<in>edges( rem_unPath xs G)\" \n            by (metis Cons.prems(2) distinct_elim is_trail.simps(2) x)\n          moreover have \"(x3,x2,x1) \\<in>edges( rem_unPath xs G)\"\n            by (metis Cons.prems(2) corres distinct_elim_rev is_trail.simps(2) x)\n          ultimately show ?thesis \n            by (metis `x3 = v'` del_edge_undirected_degree_minus delete_edge_sym  x)\n        qed\n      also have \"...=even(degree v' (rem_unPath xs G))\"\n        proof -\n          have \"(x1,x2,x3)\\<in>E\" by (metis Cons.prems(2) is_trail.simps(2) x)\n          hence \"(x3,x2,x1)\\<in>edges (rem_unPath xs G)\" \n            by (metis Cons.prems(2) corres distinct_elim_rev x)\n          hence \"(x3,x2,x1)\\<in>{e \\<in> edges (rem_unPath xs G). fst e = v'}\" \n            using `x3=v'` by (metis (mono_tags) fst_conv mem_Collect_eq)\n          moreover have \"finite {e \\<in> edges (rem_unPath xs G). fst e = v'}\"\n            using `finite E` by auto\n          ultimately have \"degree v' (rem_unPath xs G)\\<noteq>0\" \n            unfolding degree_def by auto\n          thus ?thesis by auto\n        qed\n      also have \"...=even (degree v' G)\" \n        using `x3 = v'` assms\n        by (metis (mono_tags) Cons.hyps Cons.prems(2) is_trail.simps(2) x)\n      finally have \"odd (degree v' (rem_unPath (x # xs) G))=even (degree v' G)\" .\n      thus ?thesis by (metis False)\n    qed\n  moreover have \"x3\\<noteq>v'\\<Longrightarrow>?case\" \n    proof (cases \"v=v'\")\n      case True\n      assume \"x3\\<noteq>v'\"\n      have \"odd (degree v' (rem_unPath (x # xs) G)) =odd(degree v' (\n            del_unEdge x1 x2 x3 (rem_unPath xs G)))\" using rem_x .\n      also have \"...=odd(degree v' (rem_unPath xs G) - 1)\" \n        proof -\n          have \"finite (edges (rem_unPath xs G))\" \n            by (metis (full_types) assms(1) finite_Diff rem_unPath_edges)\n          moreover have \"(x1,x2,x3) \\<in>edges( rem_unPath xs G)\" \n            by (metis Cons.prems(2) distinct_elim is_trail.simps(2) x)\n          moreover have \"(x3,x2,x1) \\<in>edges( rem_unPath xs G)\"\n            by (metis Cons.prems(2) corres distinct_elim_rev is_trail.simps(2) x)\n          ultimately show ?thesis \n            using True x\n            by (metis Cons.prems(2) del_edge_undirected_degree_minus is_trail.simps(2))\n        qed\n      also have \"...=even(degree v' (rem_unPath xs G))\"\n        proof -\n          have \"(x1,x2,x3)\\<in>E\" by (metis Cons.prems(2) is_trail.simps(2) x)\n          hence \"(x1,x2,x3)\\<in>edges (rem_unPath xs G)\" \n            by (metis Cons.prems(2) distinct_elim x)\n          hence \"(x1,x2,x3)\\<in>{e \\<in> edges (rem_unPath xs G). fst e = v'}\" \n            using `v=v'` x  Cons\n            by (metis (lifting, mono_tags) fst_conv is_trail.simps(2) mem_Collect_eq) \n          moreover have \"finite {e \\<in> edges (rem_unPath xs G). fst e = v'}\"\n            using `finite E` by auto\n          ultimately have \"degree v' (rem_unPath xs G)\\<noteq>0\" \n            unfolding degree_def by auto\n          thus ?thesis by auto\n        qed\n      also have \"...\\<noteq>even (degree v' G)\" \n        using `x3 \\<noteq> v'` assms \n        by (metis Cons.hyps Cons.prems(2)is_trail.simps(2) x)\n      finally have \"odd (degree v' (rem_unPath (x # xs) G))\\<noteq>even (degree v' G)\" .\n      thus ?thesis by (metis True)\n    next \n      case False\n      assume \"x3\\<noteq>v'\"\n      have \"odd (degree v' (rem_unPath (x # xs) G)) =odd(degree v' (\n            del_unEdge x1 x2 x3 (rem_unPath xs G)))\" using rem_x .\n      also have \"...=odd(degree v' (rem_unPath xs G))\" \n        proof -\n          have \"v=x1\" by (metis Cons.prems(2) is_trail.simps(2) x)\n          hence \"v'\\<notin>{x1,x3}\" by (metis (mono_tags) False `x3 \\<noteq> v'` empty_iff insert_iff) \n          moreover have \"valid_unMultigraph (rem_unPath xs G)\" \n            using valid_unMultigraph_axioms by auto\n          moreover have \"finite (edges (rem_unPath xs G))\" \n            by (metis (full_types) assms(1) finite_Diff rem_unPath_edges)\n          ultimately have \"degree v' (del_unEdge x1 x2 x3 (rem_unPath xs G))\n                            =degree v' (rem_unPath xs G)\" using degree_frame \n            by (metis valid_unMultigraph.degree_frame)\n          thus ?thesis by simp\n        qed\n      also have \"...=even (degree v' G)\"\n        using assms x `x3 \\<noteq> v'`\n        by (metis Cons.hyps Cons.prems(2)  is_trail.simps(2))\n      finally have \"odd (degree v' (rem_unPath (x # xs) G))=even (degree v' G)\" .\n      thus ?thesis by (metis False)\n    qed\n  ultimately show ?case by auto\nqed\n\nlemma (in valid_unMultigraph) rem_UnPath_parity_v: \n  assumes \"finite E\"  \"is_trail v ps v'\" \n  shows \"v\\<noteq>v' \\<longleftrightarrow> (odd (degree v (rem_unPath ps G)) = even(degree v G))\" \nby (metis assms is_trail_rev rem_UnPath_parity_v' rem_unPath_graph)\n\nlemma (in valid_unMultigraph) rem_UnPath_parity_others:\n  assumes \"finite E\"  \"is_trail v ps v'\" \"n\\<notin>{v,v'}\"\n  shows \" even (degree n (rem_unPath ps G)) = even(degree n G)\" using assms\nproof (induct ps arbitrary: v)\n  case Nil\n  thus ?case by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3) \n  hence \"even (degree n (rem_unPath (x#xs) G))= even (degree n (\n          del_unEdge x1 x2 x3 (rem_unPath xs G)))\" \n    by (metis rem_unPath.simps(2) rem_unPath_com)\n  have \"n=x3 \\<Longrightarrow>?case\" \n    proof - \n      assume \"n=x3\"\n      have \"even (degree n (rem_unPath (x#xs) G))= even (degree n (\n          del_unEdge x1 x2 x3 (rem_unPath xs G)))\" \n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"...=even(degree n (rem_unPath xs G) - 1)\" \n        proof -\n          have \"finite (edges (rem_unPath xs G))\" \n            by (metis (full_types) assms(1) finite_Diff rem_unPath_edges)\n          moreover have \"(x1,x2,x3) \\<in>edges( rem_unPath xs G)\" \n            by (metis Cons.prems(2) distinct_elim is_trail.simps(2) x)\n          moreover have \"(x3,x2,x1) \\<in>edges( rem_unPath xs G)\"\n            by (metis Cons.prems(2) corres distinct_elim_rev is_trail.simps(2) x)\n          ultimately show ?thesis \n            using `n = x3` del_edge_undirected_degree_minus' \n            by auto\n        qed\n      also have \"...=odd(degree n (rem_unPath xs G))\"\n        proof -\n          have \"(x1,x2,x3)\\<in>E\" by (metis Cons.prems(2) is_trail.simps(2) x)\n          hence \"(x3,x2,x1)\\<in>edges (rem_unPath xs G)\" \n            by (metis Cons.prems(2) corres distinct_elim_rev x)\n          hence \"(x3,x2,x1)\\<in>{e \\<in> edges (rem_unPath xs G). fst e = n}\" \n            using `n=x3` by (metis (mono_tags) fst_conv mem_Collect_eq)\n          moreover have \"finite {e \\<in> edges (rem_unPath xs G). fst e = n}\"\n            using `finite E` by auto\n          ultimately have \"degree n (rem_unPath xs G)\\<noteq>0\" \n            unfolding degree_def by auto\n          thus ?thesis by auto\n        qed\n      also have \"...=even(degree n G)\" \n        proof -\n          have \"x3\\<noteq>v'\" by (metis `n = x3` assms(3) insert_iff)\n          hence \"odd (degree x3 (rem_unPath xs G)) = even(degree x3 G)\"\n            using Cons assms\n            by (metis is_trail.simps(2) rem_UnPath_parity_v x)\n          thus ?thesis using `n=x3` by auto\n        qed\n      finally have \"even (degree n (rem_unPath (x#xs) G))=even(degree n G)\" .\n      thus ?thesis .\n    qed\n  moreover have \"n\\<noteq>x3 \\<Longrightarrow>?case\" \n    proof -\n      assume \"n\\<noteq>x3\"\n       have \"even (degree n (rem_unPath (x#xs) G))= even (degree n (\n          del_unEdge x1 x2 x3 (rem_unPath xs G)))\" \n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"...=even(degree n (rem_unPath xs G))\" \n        proof -\n          have \"v=x1\" by (metis Cons.prems(2) is_trail.simps(2) x)\n          hence \"n\\<notin>{x1,x3}\" by (metis Cons.prems(3) `n \\<noteq> x3` insertE insertI1 singletonE)\n          moreover have \"valid_unMultigraph (rem_unPath xs G)\" \n            using valid_unMultigraph_axioms by auto\n          moreover have \"finite (edges (rem_unPath xs G))\" \n            by (metis (full_types) assms(1) finite_Diff rem_unPath_edges)\n          ultimately have \"degree n (del_unEdge x1 x2 x3 (rem_unPath xs G))\n                            =degree n (rem_unPath xs G)\" using degree_frame \n            by (metis valid_unMultigraph.degree_frame)\n          thus ?thesis by simp\n        qed\n      also have \"...=even(degree n G)\" \n        using Cons assms `n \\<noteq> x3` x by auto\n      finally have \"even (degree n (rem_unPath (x#xs) G))=even(degree n G)\" .\n      thus ?thesis .\n    qed\n  ultimately show ?case by auto\nqed\n    \nlemma (in valid_unMultigraph) rem_UnPath_even:\n  assumes \"finite E\" \"finite V\" \"is_trail v ps v'\" \n  assumes parity_assms:  \"even (degree v' G)\"\n  shows \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G \n          + (if even (degree v G)\\<and> v\\<noteq>v' then 2 else 0)\" using assms\nproof (induct ps arbitrary:v)\n  case Nil \n  thus ?case by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3) \n  have fin_nodes: \"finite (nodes (rem_unPath xs G))\" using Cons by auto\n  have fin_edges: \"finite (edges (rem_unPath xs G))\" using Cons by auto\n  have valid_rem_xs: \"valid_unMultigraph (rem_unPath xs G)\" using valid_unMultigraph_axioms \n    by auto\n  have x_in:\"(x1,x2,x3)\\<in>edges (rem_unPath xs G)\" \n    by (metis (full_types) Cons.prems(3) distinct_elim is_trail.simps(2) x)\n  have \"even (degree x1 (rem_unPath xs G)) \n        \\<Longrightarrow> even(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\" \n    proof -\n      assume parity_x1_x3: \"even (degree x1 (rem_unPath xs G))\" \n                           \"even(degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)+2\" \n        using  parity_x1_x3  fin_nodes fin_edges valid_rem_xs x_in del_UnEdge_even_even \n        by metis\n      also have \"...=num_of_odd_nodes G+(if even(degree x3 G) \\<and> x3\\<noteq>v' then 2 else 0 )+2\"\n        using Cons.hyps[OF `finite E` `finite V`, of x3] `is_trail v (x # xs) v'`\n          `even (degree v' G)` x \n        by auto\n      also have \"...=num_of_odd_nodes G+2\" \n        proof -\n          have \"even(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> odd (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          thus ?thesis using parity_x1_x3(2) by auto\n        qed\n      also have \"...=num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" \n        proof -\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover hence \"x1\\<noteq>v'\" \n            using Cons assms  \n            by (metis is_trail.simps(2)  parity_x1_x3(1) rem_UnPath_parity_v' x)\n          ultimately have \"x1\\<notin>{x3,v'}\" by auto\n          hence  \"even(degree x1 G)\" \n            using Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) \n            by (metis (full_types)  is_trail.simps(2) rem_UnPath_parity_others x)\n          hence \"even(degree x1 G) \\<and> x1\\<noteq>v'\" using `x1 \\<noteq> v'` by auto\n          hence \"even(degree v G) \\<and> v\\<noteq>v'\" by (metis Cons.prems(3) is_trail.simps(2) x)\n          thus ?thesis by auto\n        qed\n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" .\n      thus ?thesis .\n    qed       \n  moreover have \"even (degree x1 (rem_unPath xs G)) \\<Longrightarrow> \n                    odd(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\" \n    proof -\n      assume parity_x1_x3: \"even (degree x1 (rem_unPath xs G))\" \n                           \"odd (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)\" \n        using  parity_x1_x3  fin_nodes fin_edges valid_rem_xs x_in \n        by (metis del_UnEdge_even_odd)\n      also have \"...=num_of_odd_nodes G+(if even(degree x3 G) \\<and> x3\\<noteq>v' then 2 else 0 )\"\n        using  Cons.hyps Cons.prems(3) assms(1) assms(2)  parity_assms x\n        by auto\n      also have \"...=num_of_odd_nodes G+2\" \n         proof -\n          have \"even(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> odd (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          thus ?thesis using parity_x1_x3(2) by auto\n        qed\n      also have \"...=num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\"\n        proof -\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover hence \"x1\\<noteq>v'\" \n            using Cons assms  \n            by (metis is_trail.simps(2)  parity_x1_x3(1) rem_UnPath_parity_v' x)\n          ultimately have \"x1\\<notin>{x3,v'}\" by auto\n          hence  \"even(degree x1 G)\" \n            using Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) \n            by (metis (full_types)  is_trail.simps(2) rem_UnPath_parity_others x)\n          hence \"even(degree x1 G) \\<and> x1\\<noteq>v'\" using `x1 \\<noteq> v'` by auto\n          hence \"even(degree v G) \\<and> v\\<noteq>v'\" by (metis Cons.prems(3) is_trail.simps(2) x)\n          thus ?thesis by auto\n        qed\n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" .\n      thus ?thesis .\n    qed         \n  moreover have \"odd (degree x1 (rem_unPath xs G)) \\<Longrightarrow> \n                    even(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\"             \n    proof -\n      assume parity_x1_x3: \"odd (degree x1 (rem_unPath xs G))\" \n                           \"even (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)\" \n        using  parity_x1_x3  fin_nodes fin_edges valid_rem_xs x_in \n        by (metis del_UnEdge_odd_even)\n      also have \"...=num_of_odd_nodes G+(if even(degree x3 G) \\<and> x3\\<noteq>v' then 2 else 0 )\"\n        using  Cons.hyps Cons.prems(3) assms(1) assms(2) parity_assms x\n        by auto\n      also have \"...=num_of_odd_nodes G\" \n        proof -\n          have \"even(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> odd (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          thus ?thesis using parity_x1_x3(2) by auto\n        qed\n      also have \"...=num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" \n        proof (cases \"v\\<noteq>v'\")\n          case True\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover have \"is_trail x3 xs v' \" \n            by (metis Cons.prems(3) is_trail.simps(2) x)\n          ultimately have  \"odd (degree x1 (rem_unPath xs G)) \n                          \\<longleftrightarrow> odd(degree x1 G)\"  \n            using True parity_x1_x3(1) rem_UnPath_parity_others x Cons.prems(3) assms(1) assms(2)\n            by auto\n          hence \"odd(degree x1 G)\" by (metis parity_x1_x3(1))\n          thus ?thesis \n            by (metis (mono_tags) Cons.prems(3) Nat.add_0_right is_trail.simps(2) x)\n        next\n          case False\n          thus ?thesis by (metis (mono_tags) add_0_iff)\n        qed    \n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" .\n      thus ?thesis .\n    qed         \n  moreover have \"odd (degree x1 (rem_unPath xs G)) \\<Longrightarrow> \n                    odd(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\" \n    proof -\n      assume parity_x1_x3: \"odd (degree x1 (rem_unPath xs G))\" \n                           \"odd (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)-(2::nat)\" \n        using del_UnEdge_odd_odd\n        by (metis add_implies_diff  fin_edges fin_nodes parity_x1_x3 valid_rem_xs x_in)  \n      also have \"...=num_of_odd_nodes G+(if even(degree x3 G) \\<and> x3\\<noteq>v' then 2 else 0 )-(2::nat)\"\n        using Cons assms \n        by (metis is_trail.simps(2) x)\n      also have \"...=num_of_odd_nodes G\" \n        proof -\n          have \"even(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> odd (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          thus ?thesis using parity_x1_x3(2) by auto\n        qed\n      also have \"...=num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" \n         proof (cases \"v\\<noteq>v'\")\n          case True\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover have \"is_trail x3 xs v' \" \n            by (metis Cons.prems(3) is_trail.simps(2) x)\n          ultimately have  \"odd (degree x1 (rem_unPath xs G)) \n                          \\<longleftrightarrow> odd(degree x1 G)\"  \n            using True Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) rem_UnPath_parity_others x \n            by auto\n          hence \"odd(degree x1 G)\" by (metis parity_x1_x3(1))\n          thus ?thesis \n            by (metis (mono_tags) Cons.prems(3) Nat.add_0_right is_trail.simps(2) x)\n        next\n          case False\n          thus ?thesis by (metis (mono_tags) add_0_iff)\n        qed    \n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if even(degree v G) \\<and> v\\<noteq>v' then 2 else 0)\" .\n      thus ?thesis .\n    qed       \n  ultimately show ?case by metis\nqed \n\nlemma (in valid_unMultigraph) rem_UnPath_odd:\n  assumes \"finite E\" \"finite V\" \"is_trail v ps v'\" \n  assumes parity_assms:  \"odd (degree v' G)\"\n  shows \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G \n          + (if odd (degree v G)\\<and> v\\<noteq>v' then -2 else 0)\" using assms\nproof (induct ps arbitrary:v)\n  case Nil \n  thus ?case by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3) \n  have fin_nodes: \"finite (nodes (rem_unPath xs G))\" using Cons by auto\n  have fin_edges: \"finite (edges (rem_unPath xs G))\" using Cons by auto\n  have valid_rem_xs: \"valid_unMultigraph (rem_unPath xs G)\" using valid_unMultigraph_axioms \n    by auto\n  have x_in:\"(x1,x2,x3)\\<in>edges (rem_unPath xs G)\" \n    by (metis (full_types) Cons.prems(3) distinct_elim is_trail.simps(2) x)\n  have \"even (degree x1 (rem_unPath xs G)) \n        \\<Longrightarrow> even(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\" \n    proof -\n      assume parity_x1_x3: \"even (degree x1 (rem_unPath xs G))\" \n                           \"even (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)+2\" \n        using  parity_x1_x3  fin_nodes fin_edges valid_rem_xs x_in del_UnEdge_even_even \n        by metis\n      also have \"...=num_of_odd_nodes G+(if odd(degree x3 G) \\<and> x3\\<noteq>v' then - 2 else 0 )+2\"\n        using Cons.hyps[OF `finite E` `finite V`,of x3] `is_trail v (x # xs) v'`\n          `odd (degree v' G)` x\n        by auto\n      also have \"...=num_of_odd_nodes G\" \n        proof -\n          have \"odd (degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> even (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          thus ?thesis using parity_x1_x3(2) by auto\n        qed\n      also have \"...=num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" \n         proof (cases \"v\\<noteq>v'\")\n          case True\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover have \"is_trail x3 xs v' \" \n            by (metis Cons.prems(3) is_trail.simps(2) x)\n          ultimately have  \"even (degree x1 (rem_unPath xs G)) \n                          \\<longleftrightarrow> even (degree x1 G)\"  \n            using True Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) \n                rem_UnPath_parity_others x\n            by auto\n          hence \"even (degree x1 G)\" by (metis parity_x1_x3(1))\n          thus ?thesis \n            by (metis (hide_lams, mono_tags) Cons.prems(3)  is_trail.simps(2)  \n                monoid_add_class.add.right_neutral x)\n        next\n          case False\n          thus ?thesis by (metis (mono_tags) add_0_iff)\n        qed    \n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" .\n      thus ?thesis .\n    qed       \n  moreover have \"even (degree x1 (rem_unPath xs G)) \\<Longrightarrow> \n                    odd(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\" \n    proof -\n      assume parity_x1_x3: \"even (degree x1 (rem_unPath xs G))\" \n                           \"odd (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)\" \n        using  parity_x1_x3  fin_nodes fin_edges valid_rem_xs x_in \n        by (metis del_UnEdge_even_odd)\n      also have \"...=num_of_odd_nodes G+(if odd(degree x3 G) \\<and> x3\\<noteq>v' then - 2 else 0 )\"\n        using  Cons.hyps[OF `finite E` `finite V`, of x3] Cons.prems(3) assms(1) assms(2) \n          parity_assms x\n        by auto\n      also have \"...=num_of_odd_nodes G\" \n         proof -\n          have \"odd(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> even (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          thus ?thesis using parity_x1_x3(2) by auto\n        qed\n      also have \"...= num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\"\n         proof (cases \"v\\<noteq>v'\")\n          case True\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover have \"is_trail x3 xs v' \" \n            by (metis Cons.prems(3) is_trail.simps(2) x)\n          ultimately have  \"even (degree x1 (rem_unPath xs G)) \n                          \\<longleftrightarrow> even (degree x1 G)\"  \n            using True Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) \n                rem_UnPath_parity_others x\n            by auto\n          hence \"even (degree x1 G)\" by (metis parity_x1_x3(1))\n          thus ?thesis \n            by (metis (hide_lams, mono_tags) Cons.prems(3)  is_trail.simps(2)  \n                monoid_add_class.add.right_neutral x)\n        next\n          case False\n          thus ?thesis by (metis (mono_tags) add_0_iff)\n        qed   \n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" .\n      thus ?thesis .\n    qed         \n  moreover have \"odd (degree x1 (rem_unPath xs G)) \\<Longrightarrow> \n                    even(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\"             \n    proof -\n      assume parity_x1_x3: \"odd (degree x1 (rem_unPath xs G))\" \n                           \"even (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)\" \n        using  parity_x1_x3  fin_nodes fin_edges valid_rem_xs x_in \n        by (metis del_UnEdge_odd_even)\n      also have \"...=num_of_odd_nodes G+(if odd(degree x3 G) \\<and> x3\\<noteq>v' then -2 else 0 )\"\n        using  Cons.hyps Cons.prems(3) assms(1) assms(2) parity_assms x\n        by auto\n      also have \"...=num_of_odd_nodes G + (- 2)\" \n        proof -\n          have \"odd(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> even (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          hence \"odd(degree x3 G) \\<and> x3\\<noteq>v'\" by (metis parity_x1_x3(2))\n          thus ?thesis by auto\n        qed\n      also have \"...=num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" \n         proof -\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover hence \"x1\\<noteq>v'\" \n            using Cons assms  \n            by (metis is_trail.simps(2)  parity_x1_x3(1) rem_UnPath_parity_v' x)\n          ultimately have \"x1\\<notin>{x3,v'}\" by auto\n          hence  \"odd(degree x1 G)\" \n            using Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) \n            by (metis (full_types)  is_trail.simps(2) rem_UnPath_parity_others x)\n          hence \"odd(degree x1 G) \\<and> x1\\<noteq>v'\" using `x1 \\<noteq> v'` by auto\n          hence \"odd(degree v G) \\<and> v\\<noteq>v'\" by (metis Cons.prems(3) is_trail.simps(2) x)\n          thus ?thesis by auto\n        qed\n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" .\n      thus ?thesis .\n    qed         \n  moreover have \"odd (degree x1 (rem_unPath xs G)) \\<Longrightarrow> \n                    odd(degree x3 (rem_unPath xs G)) \\<Longrightarrow> ?case\" \n    proof -\n      assume parity_x1_x3: \"odd (degree x1 (rem_unPath xs G))\" \n                           \"odd (degree x3 (rem_unPath xs G))\"\n      have \"num_of_odd_nodes (rem_unPath (x#xs) G)= num_of_odd_nodes \n         (del_unEdge x1 x2 x3 (rem_unPath xs G))\"\n        by (metis rem_unPath.simps(2) rem_unPath_com x)\n      also have \"... =num_of_odd_nodes (rem_unPath xs G)-(2::nat)\" \n        using del_UnEdge_odd_odd\n        by (metis add_implies_diff  fin_edges fin_nodes parity_x1_x3 valid_rem_xs x_in)  \n      also have \"...=num_of_odd_nodes G -(2::nat)\"\n        proof -\n          have \"odd(degree x3 G) \\<and> x3\\<noteq>v' \\<longleftrightarrow> even (degree x3 (rem_unPath xs G))\" \n            using Cons.prems assms\n            by (metis  is_trail.simps(2) parity_x1_x3(2) rem_UnPath_parity_v x)\n          hence \"\\<not>(odd(degree x3 G) \\<and> x3\\<noteq>v')\" by (metis parity_x1_x3(2))  \n          have \"num_of_odd_nodes (rem_unPath xs G)= \n                  num_of_odd_nodes G+(if odd(degree x3 G) \\<and> x3\\<noteq>v' then -2 else 0)\" \n            by (metis Cons.hyps Cons.prems(3) assms(1) assms(2) \n                is_trail.simps(2) parity_assms x)\n          thus ?thesis \n            using `\\<not> (odd (degree x3 G) \\<and> x3 \\<noteq> v')` by auto \n        qed\n      also have \"...=num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" \n        proof -\n          have \"x1\\<noteq>x3\" by (metis valid_rem_xs valid_unMultigraph.no_id x_in)\n          moreover hence \"x1\\<noteq>v'\" \n            using Cons assms  \n            by (metis is_trail.simps(2)  parity_x1_x3(1) rem_UnPath_parity_v' x)\n          ultimately have \"x1\\<notin>{x3,v'}\" by auto\n          hence  \"odd(degree x1 G)\" \n            using Cons.prems(3) assms(1) assms(2) parity_x1_x3(1) \n            by (metis (full_types)  is_trail.simps(2) rem_UnPath_parity_others x)\n          hence \"odd(degree x1 G) \\<and> x1\\<noteq>v'\" using `x1 \\<noteq> v'` by auto\n          hence \"odd(degree v G) \\<and> v\\<noteq>v'\" by (metis Cons.prems(3) is_trail.simps(2) x)\n          hence \"v\\<in>odd_nodes_set G\" \n            using Cons.prems(3) E_validD(1)  x unfolding odd_nodes_set_def\n            by auto\n          moreover have \"v'\\<in>odd_nodes_set G\" \n            using  is_path_memb[OF is_trail_intro[OF assms(3)]]  parity_assms\n            unfolding odd_nodes_set_def \n            by auto\n          ultimately have \"{v,v'}\\<subseteq>odd_nodes_set G\" by auto\n          moreover have \"v\\<noteq>v'\" by (metis `odd (degree v G) \\<and> v \\<noteq> v'`)\n          hence \"card{v,v'}=2\" by auto \n          moreover have \"finite(odd_nodes_set G)\" \n            using `finite V` unfolding odd_nodes_set_def\n            by auto\n          ultimately have \"num_of_odd_nodes G\\<ge>2\" by (metis card_mono num_of_odd_nodes_def)  \n          thus ?thesis using `odd (degree v G) \\<and> v \\<noteq> v'` by auto\n        qed\n      finally have \"num_of_odd_nodes (rem_unPath (x#xs) G)=\n                        num_of_odd_nodes G+(if odd(degree v G) \\<and> v\\<noteq>v' then -2 else 0)\" .\n      thus ?thesis .\n    qed       \n  ultimately show ?case by metis\nqed \n\nlemma (in valid_unMultigraph) rem_UnPath_cycle:\n  assumes \"finite E\" \"finite V\" \"is_trail v ps v'\" \"v=v'\"\n  shows \"num_of_odd_nodes (rem_unPath ps G) = num_of_odd_nodes G\" (is \"?L=?R\")\nproof  (cases \"even(degree v' G)\")\n  case True\n  hence \"?L = num_of_odd_nodes G + (if even (degree v G)\\<and> v\\<noteq>v' then 2 else 0)\" \n    by (metis assms(1) assms(2) assms(3) rem_UnPath_even)\n  thus ?thesis by (metis (mono_tags) True assms(4) add.commute plus_nat.add_0)\nnext\n  case False\n  hence \"?L = num_of_odd_nodes G + (if odd (degree v G)\\<and> v\\<noteq>v' then -2 else 0)\" \n    by (metis assms(1) assms(2) assms(3) rem_UnPath_odd)\n  thus ?thesis using `v = v'` by auto   \nqed\n\n\n\nsection{*Connectivity*}\n\ndefinition (in valid_unMultigraph) connected::bool where\n  \"connected \\<equiv> \\<forall> v\\<in>V. \\<forall>v'\\<in>V. v\\<noteq>v' \\<longrightarrow> (\\<exists>ps. is_path v ps v')\"\n\nlemma (in valid_unMultigraph) \"connected \\<Longrightarrow> \\<forall>v\\<in>V. \\<forall>v'\\<in>V. v\\<noteq>v'\\<longrightarrow>(\\<exists>ps. is_trail v ps v')\"\nproof (rule,rule,rule)\n  fix v v'\n  assume \"v\\<in>V\" \"v'\\<in>V\" \"v\\<noteq>v'\"\n  assume connected\n  obtain ps where \"is_path v ps v'\" by (metis `connected` `v \\<in> V` `v' \\<in> V` `v\\<noteq>v'`  connected_def)\n  then obtain ps' where \"is_trail v ps' v'\"\n    proof (induct ps arbitrary:v )\n      case Nil\n      thus ?case by (metis is_trail.simps(1) is_path.simps(1))\n    next\n      case (Cons x xs)\n      obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n      have \"is_path x3 xs v'\" by (metis Cons.prems(2) is_path.simps(2) x)\n      moreover have \"\\<And>ps'. is_trail x3 ps' v' \\<Longrightarrow> thesis\" \n        proof -\n          fix ps'\n          assume \"is_trail x3 ps' v'\"\n          hence \"(x1,x2,x3)\\<notin>set ps' \\<and> (x3,x2,x1)\\<notin>set ps' \\<Longrightarrow>is_trail v (x#ps') v'\"\n            by (metis Cons.prems(2) is_trail.simps(2) is_path.simps(2) x)\n          moreover have \"(x1,x2,x3)\\<in>set ps' \\<Longrightarrow> \\<exists>ps1. is_trail v ps1 v'\" \n            proof -\n              assume \"(x1,x2,x3)\\<in>set ps'\"\n              then obtain ps1 ps2 where \"ps'=ps1@(x1,x2,x3)#ps2\" by (metis split_list)\n              hence \"is_trail v (x#ps2) v'\" \n                using `is_trail x3 ps' v'` x\n                by (metis Cons.prems(2) is_trail.simps(2) \n                    is_trail_split is_path.simps(2))\n              thus ?thesis by rule\n            qed\n          moreover have \"(x3,x2,x1)\\<in>set ps' \\<Longrightarrow>  \\<exists>ps1. is_trail v ps1 v'\" \n             proof -\n              assume \"(x3,x2,x1)\\<in>set ps'\"\n              then obtain ps1 ps2 where \"ps'=ps1@(x3,x2,x1)#ps2\" by (metis split_list)\n              hence \"is_trail v ps2 v'\" \n                using `is_trail x3 ps' v'` x\n                by (metis Cons.prems(2) is_trail.simps(2) \n                    is_trail_split is_path.simps(2))\n              thus ?thesis by rule \n            qed\n          ultimately show thesis using Cons by auto\n        qed\n      ultimately show ?case using Cons by auto\n    qed\n  thus \"\\<exists>ps. is_trail v ps v'\" by rule\nqed\n\nlemma (in valid_unMultigraph) no_rep_length: \"is_trail v ps v'\\<Longrightarrow>length ps=card(set ps)\" \n  by (induct ps arbitrary:v, auto)\n\nlemma (in valid_unMultigraph) path_in_edges:\"is_trail v ps v' \\<Longrightarrow> set ps \\<subseteq> E\" \nproof (induct ps arbitrary:v)\n  case Nil\n  show ?case by auto\nnext\n  case (Cons x xs)\n  obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n  hence \"is_trail x3 xs v'\" using Cons by auto\n  hence \" set xs \\<subseteq> E\" using Cons by auto\n  moreover have \"x\\<in>E\" using Cons by (metis is_trail_intro is_path.simps(2) x)\n  ultimately show ?case by auto\nqed\n\n\nlemma (in valid_unMultigraph) trail_bound: \n    assumes \"finite E\" \" is_trail v ps v'\"\n    shows \"length ps \\<le>card E\" \nby (metis (hide_lams, no_types) assms(1) assms(2) card_mono no_rep_length path_in_edges)\n\ndefinition (in valid_unMultigraph) exist_path_length:: \"'v \\<Rightarrow> nat \\<Rightarrow>bool\" where\n  \"exist_path_length v l\\<equiv>\\<exists>v' ps. is_trail v' ps v \\<and> length ps=l\"   \n\nlemma (in valid_unMultigraph) longest_path:\n  assumes \"finite E\" \"n \\<in> V\"\n  shows \"\\<exists>v. \\<exists>max_path. is_trail v max_path n \\<and> \n        (\\<forall>v'. \\<forall>e\\<in>E. \\<not>is_trail v' (e#max_path) n)\"\nproof (rule ccontr)\n  assume  contro:\"\\<not> (\\<exists>v max_path. is_trail v max_path n \n           \\<and> (\\<forall>v'. \\<forall>e\\<in>E. \\<not>is_trail v' (e#max_path) n))\"\n  hence  induct:\"(\\<forall>v max_path.  is_trail v max_path n \n           \\<longrightarrow> (\\<exists>v'. \\<exists>e\\<in>E. is_trail v' (e#max_path) n))\" by auto\n  have \"is_trail n [] n\" using `n \\<in> V` by auto \n  hence \"exist_path_length n 0\" unfolding exist_path_length_def by auto\n  moreover have \"\\<forall>y. exist_path_length n y \\<longrightarrow> y \\<le> card E\" \n    using trail_bound[OF `finite E`] unfolding exist_path_length_def \n    by auto\n  hence bound:\"\\<forall>y. exist_path_length n y \\<longrightarrow> y < card E + 1\" by auto\n  ultimately have \"exist_path_length n (GREATEST x. exist_path_length n x)\" using GreatestI by auto\n  then obtain v max_path where \n    max_path:\"is_trail v max_path n\" \"length max_path=(GREATEST x. exist_path_length n x)\"\n    by (metis exist_path_length_def)\n  hence \"\\<exists> v' e. is_trail v' (e#max_path) n\" using induct by metis\n  hence \"exist_path_length n (length max_path +1)\" \n    by (metis One_nat_def exist_path_length_def list.size(4))\n  hence \"length max_path + 1 \\<le> (GREATEST x. exist_path_length n x)\" by (metis Greatest_le bound)\n  hence \"length max_path + 1 \\<le> length max_path\" using max_path by auto\n  thus False by auto\nqed\n\n\nlemma even_card':\n  assumes \"even(card A)\" \"x\\<in>A\"\n  shows \"\\<exists>y\\<in>A. y\\<noteq>x\" \nproof (rule ccontr)\n  assume \"\\<not> (\\<exists>y\\<in>A. y \\<noteq> x)\"\n  hence \"\\<forall>y\\<in>A. y=x\" by auto\n  hence \"A={x}\" by (metis all_not_in_conv assms(2) insertI2 mk_disjoint_insert)\n  hence \"card(A)=1\" by auto\n  thus False using `even(card A)` by auto\nqed\n\nlemma odd_card: \n  assumes \"finite A\" \"odd(card A)\"\n  shows \"\\<exists>x. x\\<in>A\" \nby (metis all_not_in_conv assms(2) card_empty even_zero) \n\nlemma (in valid_unMultigraph) extend_distinct_path: \n  assumes \"finite E\"  \"is_trail v' ps v\" \n  assumes parity_assms:\"(even (degree v' G)\\<and>v'\\<noteq>v)\\<or>(odd (degree v' G)\\<and>v'=v)\"\n  shows \"\\<exists>e v1. is_trail v1 (e#ps) v\" \nproof -\n  have \"(even (degree v' G)\\<and>v'\\<noteq>v) \\<Longrightarrow> odd(degree v' (rem_unPath  ps G))\" \n    by (metis assms(1) assms(2) rem_UnPath_parity_v)\n  moreover have \"(odd (degree v' G)\\<and>v'=v) \\<Longrightarrow> odd(degree v' (rem_unPath  ps G))\" \n    by (metis assms(1) assms(2) rem_UnPath_parity_v')\n  ultimately have \"odd(degree v' (rem_unPath  ps G))\" using parity_assms by auto\n  hence \"odd (card {e. fst e=v' \\<and> e\\<in>edges G - (set ps \\<union> set (rev_path ps))})\" \n    using  rem_unPath_edges unfolding degree_def \n    by (metis (lifting, no_types) Collect_cong)\n  hence \"{e. fst e=v' \\<and> e\\<in>E - (set ps \\<union> set (rev_path ps))}\\<noteq>{}\" \n    by (metis empty_iff finite.emptyI odd_card)\n  then obtain v0 w where v0w:  \"(v',w,v0)\\<in>E\" \"(v',w,v0)\\<notin>set ps \\<union> set (rev_path ps)\" by auto\n  hence \"is_trail v0 ((v0,w,v')#ps) v\" \n    by (metis (hide_lams, mono_tags) Un_iff assms(2) corres in_set_rev_path is_trail.simps(2))  \n  thus ?thesis by metis\nqed\n\ntext{*replace an edge (or its reverse in a path) by another path (in an undirected graph)*}\nfun replace_by_UnPath:: \"('v,'w) path \\<Rightarrow> 'v \\<times>'w \\<times>'v \\<Rightarrow> ('v,'w) path \\<Rightarrow>  ('v,'w) path\" where\n  \"replace_by_UnPath [] _ _ = []\" |\n  \"replace_by_UnPath (x#xs) (v,e,v') ps = \n    (if x=(v,e,v') then ps@replace_by_UnPath xs (v,e,v') ps\n     else if x=(v',e,v) then (rev_path ps)@replace_by_UnPath xs (v,e,v') ps\n     else x#replace_by_UnPath xs (v,e,v') ps)\"\n\nlemma (in valid_unMultigraph) del_unEdge_connectivity:\n  assumes \"connected\" \"\\<exists>ps. valid_graph.is_path (del_unEdge v e v' G) v ps v'\"\n  shows \"valid_unMultigraph.connected (del_unEdge v e v' G)\"\nproof -\n  have valid_unMulti:\"valid_unMultigraph (del_unEdge v e v' G)\" \n    using valid_unMultigraph_axioms by simp\n  have valid_graph: \"valid_graph (del_unEdge v e v' G)\" \n    using valid_graph_axioms del_undirected by (metis delete_edge_valid)\n  obtain ex_path where ex_path:\"valid_graph.is_path (del_unEdge v e v' G) v ex_path v'\" \n    by (metis assms(2))\n  show ?thesis unfolding valid_unMultigraph.connected_def[OF valid_unMulti]\n  proof (rule,rule,rule)\n    fix n n' \n    assume  n : \"n \\<in>nodes (del_unEdge v e v' G)\" \n    assume  n': \"n'\\<in>nodes (del_unEdge v e v' G)\"\n    assume \"n\\<noteq>n'\"\n    obtain ps where ps:\"is_path n ps n'\" \n      by (metis `n\\<noteq>n'` n n' `connected` connected_def del_UnEdge_node)\n    hence \"valid_graph.is_path (del_unEdge v e v' G) \n           n (replace_by_UnPath ps (v,e,v') ex_path) n'\" \n      proof (induct ps arbitrary:n)\n        case Nil\n        thus ?case by (metis is_path.simps(1) n' replace_by_UnPath.simps(1) valid_graph \n          valid_graph.is_path_simps(1))\n      next\n        case (Cons x xs)\n        obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n        have \"x=(v,e,v') \\<Longrightarrow> ?case\" \n          proof -\n            assume \"x=(v,e,v')\"\n            hence \"valid_graph.is_path (del_unEdge v e v' G) \n                n (replace_by_UnPath (x#xs) (v,e,v') ex_path) n'\n                = valid_graph.is_path (del_unEdge v e v' G) \n                n (ex_path@(replace_by_UnPath xs (v,e,v') ex_path)) n'\" \n              by (metis replace_by_UnPath.simps(2))\n            also have \"...=True\" \n              by (metis Cons.hyps Cons.prems `x = (v, e, v')` ex_path is_path.simps(2) valid_graph \n                  valid_graph.is_path_split)\n            finally show ?thesis by simp\n          qed\n        moreover have \"x=(v',e,v) \\<Longrightarrow> ?case\" \n          proof -\n            assume \"x=(v',e,v)\"\n            hence \"valid_graph.is_path (del_unEdge v e v' G) \n                n (replace_by_UnPath (x#xs) (v,e,v') ex_path) n'\n                = valid_graph.is_path (del_unEdge v e v' G) \n                n ((rev_path ex_path)@(replace_by_UnPath xs (v,e,v') ex_path)) n'\" \n              by (metis Cons.prems is_path.simps(2) no_id replace_by_UnPath.simps(2))\n            also have \"...=True\" \n              by (metis Cons.hyps Cons.prems `x = (v', e, v)` is_path.simps(2) ex_path valid_graph \n                  valid_graph.is_path_split valid_unMulti valid_unMultigraph.is_path_rev)\n            finally show ?thesis by simp\n          qed\n        moreover have \"x\\<noteq>(v,e,v')\\<and>x\\<noteq>(v',e,v)\\<Longrightarrow>?case\" \n          by (metis Cons.hyps Cons.prems del_UnEdge_frame is_path.simps(2) replace_by_UnPath.simps(2) \n              valid_graph valid_graph.is_path.simps(2) x)\n        ultimately show ?case by auto\n      qed\n    thus \"\\<exists>ps. valid_graph.is_path (del_unEdge v e v' G) n ps n'\" by auto\n  qed\nqed\n\nlemma (in valid_unMultigraph) path_between_odds:\n  assumes \"odd(degree v G)\" \"odd(degree v' G)\" \"finite E\"  \"v\\<noteq>v'\" \"num_of_odd_nodes G=2\"\n  shows \"\\<exists>ps. is_trail v ps v'\"\nproof -\n   have \"v\\<in>V\" \n    proof (rule ccontr)\n      assume \"v\\<notin>V\"\n      hence \"\\<forall>e \\<in> E. fst e \\<noteq> v\" by (metis E_valid(1) imageI set_mp)\n      hence \"degree v G=0\" unfolding degree_def using `finite E` \n        by force\n      thus False using `odd(degree v G)` by auto\n    qed\n  have \"v'\\<in>V\" \n    proof (rule ccontr)\n      assume \"v'\\<notin>V\"\n      hence \"\\<forall>e \\<in> E. fst e \\<noteq> v'\" by (metis E_valid(1) imageI set_mp)\n      hence \"degree v' G=0\" unfolding degree_def using `finite E` \n        by force\n     thus False using `odd(degree v' G)` by auto\n    qed\n  then obtain max_path v0 where max_path:\n      \"is_trail  v0 max_path v'\" \n      \"(\\<forall>n. \\<forall>w\\<in>E. \\<not>is_trail n (w#max_path) v')\" \n    using longest_path[of v'] by (metis assms(3)) \n  have \"even(degree v0 G)\\<Longrightarrow>v0=v' \\<Longrightarrow> v0=v\" \n    by (metis assms(2))\n  moreover have \"even(degree v0 G)\\<Longrightarrow>v0\\<noteq>v' \\<Longrightarrow> v0=v\" \n    proof -\n      assume\"even(degree v0 G)\" \"v0\\<noteq>v'\"\n      hence \"\\<exists>w v1. is_trail \n            v1 (w#max_path) v'\" \n        by (metis assms(3) extend_distinct_path max_path(1))\n      thus ?thesis by (metis (full_types) is_trail.simps(2) max_path(2) prod.exhaust)\n    qed\n  moreover have \"odd(degree v0 G)\\<Longrightarrow>v0=v'\\<Longrightarrow>v0=v\" \n    proof -\n      assume\"odd(degree v0 G)\" \"v0=v'\"\n      hence \"\\<exists>w v1. is_trail v1 (w#max_path) v'\" \n        by (metis assms(3) extend_distinct_path max_path(1))\n      thus ?thesis by (metis (full_types) List.set_simps(2) insert_subset max_path(2) path_in_edges)\n    qed\n  moreover have \"odd(degree v0 G)\\<Longrightarrow>v0\\<noteq>v'\\<Longrightarrow>v0=v\"\n    proof (rule ccontr)\n      assume \"v0 \\<noteq> v\" \"odd(degree v0 G)\" \"v0\\<noteq>v'\"\n      moreover have \"v\\<in>odd_nodes_set G\" \n        using `v \\<in> V` ` odd (degree v G)` unfolding odd_nodes_set_def\n        by auto\n      moreover have \"v'\\<in>odd_nodes_set G\" \n        using `v' \\<in> V` `odd (degree v' G)`\n        unfolding odd_nodes_set_def\n        by auto\n      ultimately have \"{v,v',v0} \\<subseteq> odd_nodes_set G\" \n        using   is_path_memb[OF is_trail_intro[OF `is_trail v0 max_path v'`]] max_path(1)\n        unfolding odd_nodes_set_def\n        by auto\n      moreover have \"card {v,v',v0}=3\" using `v0\\<noteq>v` `v\\<noteq>v'` `v0\\<noteq>v'` by auto\n      moreover have \"finite (odd_nodes_set G)\" \n        using assms(5) card_eq_0_iff[of \"odd_nodes_set G\"] unfolding num_of_odd_nodes_def \n        by auto\n      ultimately have \"3\\<le>card(odd_nodes_set G)\" by (metis card_mono)\n      thus False using `num_of_odd_nodes G=2` unfolding num_of_odd_nodes_def by auto\n    qed\n  ultimately have \"v0=v\" by auto\n  thus ?thesis by (metis max_path(1))\nqed\n\nlemma (in valid_unMultigraph) del_unEdge_even_connectivity:\n  assumes \"finite E\" \"finite V\" \"connected\" \"\\<forall>n\\<in>V. even(degree n G)\" \"(v,e,v')\\<in>E\"\n  shows \"valid_unMultigraph.connected (del_unEdge v e v' G)\" \nproof -\n  have valid_unMulti:\"valid_unMultigraph (del_unEdge v e v' G)\" \n    using valid_unMultigraph_axioms by simp\n  have valid_graph: \"valid_graph (del_unEdge v e v' G)\" \n    using valid_graph_axioms del_undirected by (metis delete_edge_valid)\n  have fin_E': \"finite(edges (del_unEdge v e v' G))\" \n    by (metis (hide_lams, no_types) assms(1) del_undirected delete_edge_def \n        finite_Diff select_convs(2))\n  have fin_V': \"finite(nodes (del_unEdge v e v' G))\" \n    by (metis (mono_tags) assms(2) del_undirected delete_edge_def select_convs(1))\n  have all_even: \"\\<forall>n\\<in>nodes (del_unEdge v e v' G). n\\<notin>{v,v'}\n                  \\<longrightarrow>even(degree n (del_unEdge v e v' G))\"\n    by (metis (full_types) assms(1) assms(4) degree_frame del_UnEdge_node)\n  have \"even (degree v G)\" by (metis (full_types) E_validD(1) assms(4) assms(5))\n  moreover have \"even (degree v' G)\" by (metis (full_types) E_validD(2) assms(4) assms(5))\n  moreover have \"num_of_odd_nodes G = 0\" \n    using `\\<forall>n\\<in>V. even(degree n G)` `finite V`\n    unfolding num_of_odd_nodes_def odd_nodes_set_def by auto\n  ultimately have \"num_of_odd_nodes (del_unEdge v e v' G) = 2\" \n    using del_UnEdge_even_even[of G v e v',OF valid_unMultigraph_axioms] \n    by (metis assms(1) assms(2) assms(5) monoid_add_class.add.left_neutral)\n  moreover have \" odd (degree v (del_unEdge v e v' G))\" \n    using `even (degree v G)` del_UnEdge_even[OF `(v,e,v')\\<in>E` `finite E`] \n    unfolding odd_nodes_set_def \n    by auto\n  moreover have \"odd (degree v' (del_unEdge v e v' G))\" \n    using `even (degree v' G)` del_UnEdge_even'[OF `(v,e,v')\\<in>E` `finite E`] \n    unfolding odd_nodes_set_def \n    by auto  \n  moreover have \"finite (edges (del_unEdge v e v' G))\" \n    using `finite E` by auto\n  moreover have \"v\\<noteq>v'\" using no_id `(v,e,v')\\<in>E` by auto\n  ultimately have \"\\<exists>ps. valid_unMultigraph.is_trail (del_unEdge v e v' G) v ps v'\"\n    using valid_unMultigraph.path_between_odds[OF valid_unMulti,of v v']    \n    by auto\n  thus ?thesis \n    by (metis (full_types) assms(3) del_unEdge_connectivity valid_unMulti \n      valid_unMultigraph.is_trail_intro)\nqed\n\n\nlemma (in valid_graph) path_end:\"ps\\<noteq>[] \\<Longrightarrow> is_path v ps v' \\<Longrightarrow> v'=snd (snd(last ps))\" \n  by (induct ps arbitrary:v,auto)\n\nlemma (in valid_unMultigraph) connectivity_split:\n  assumes \"connected\" \"\\<not>valid_unMultigraph.connected (del_unEdge v w v' G)\" \n          \"(v,w,v')\\<in>E\"\n  obtains G1 G2 where\n         \"nodes G1={n. \\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v}\"\n         and \"edges G1={(n,e,n'). (n,e,n')\\<in>edges (del_unEdge v w v' G) \n            \\<and> n\\<in>nodes G1 \\<and> n'\\<in>nodes G1}\"\n         and \"nodes G2={n. \\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v'}\"\n         and \"edges G2={(n,e,n'). (n,e,n')\\<in>edges (del_unEdge v w v' G) \n            \\<and> n\\<in>nodes G2 \\<and> n'\\<in>nodes G2}\" \n         and \"edges G1 \\<union> edges G2 = edges (del_unEdge v w v' G)\" \n         and \"edges G1 \\<inter> edges G2={}\" \n         and \"nodes G1 \\<union> nodes G2=nodes (del_unEdge v w v' G)\"\n         and \"nodes G1 \\<inter> nodes G2={}\" \n         and \"valid_unMultigraph G1\" \n         and \"valid_unMultigraph G2\"\n         and \"valid_unMultigraph.connected G1\"  \n         and \"valid_unMultigraph.connected G2\"\nproof -\n  have valid0:\"valid_graph (del_unEdge v w v' G)\" using valid_graph_axioms \n    by (metis del_undirected delete_edge_valid)\n  have valid0':\"valid_unMultigraph (del_unEdge v w v' G)\" using valid_unMultigraph_axioms \n    by (metis del_unEdge_valid)\n  obtain G1_nodes where G1_nodes:\"G1_nodes= \n      {n. \\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v}\" \n    by metis\n  then obtain G1 where G1:\"G1=\n      \\<lparr>nodes=G1_nodes, edges={(n,e,n'). (n,e,n')\\<in>edges (del_unEdge v w v' G) \n      \\<and> n\\<in>G1_nodes \\<and> n'\\<in>G1_nodes}\\<rparr>\"\n    by metis\n  obtain G2_nodes where G2_nodes:\"G2_nodes= \n      {n. \\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v'}\" \n    by metis\n  then obtain G2 where G2:\"G2=\n      \\<lparr>nodes=G2_nodes, edges={(n,e,n'). (n,e,n')\\<in>edges (del_unEdge v w v' G) \n      \\<and> n\\<in>G2_nodes \\<and> n'\\<in>G2_nodes}\\<rparr>\"\n    by metis \n  have valid_G1:\"valid_unMultigraph G1\" \n    using G1 valid_unMultigraph.corres[OF valid0'] valid_unMultigraph.no_id[OF valid0']\n    by (unfold_locales,auto)\n  hence valid_G1':\"valid_graph G1\" using valid_unMultigraph_def by auto\n  have valid_G2:\"valid_unMultigraph G2\"  \n    using G2 valid_unMultigraph.corres[OF valid0'] valid_unMultigraph.no_id[OF valid0'] \n    by (unfold_locales,auto)\n  hence valid_G2': \"valid_graph G2\" using valid_unMultigraph_def by auto\n  have \"nodes G1={n. \\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v}\" \n    using G1_nodes G1 by auto\n  moreover have \"edges G1={(n,e,n'). (n,e,n')\\<in>edges (del_unEdge v w v' G) \n                 \\<and> n\\<in>nodes G1 \\<and> n'\\<in>nodes G1}\"\n    using G1_nodes G1 by auto\n  moreover have \"nodes G2={n. \\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v'}\"\n    using G2_nodes G2 by auto\n  moreover have \"edges G2={(n,e,n'). (n,e,n')\\<in>edges (del_unEdge v w v' G) \n                 \\<and> n\\<in>nodes G2 \\<and> n'\\<in>nodes G2}\"\n    using G2_nodes G2 by auto               \n  moreover have \"nodes G1 \\<union> nodes G2=nodes (del_unEdge v w v' G)\" \n    proof (rule ccontr)\n      assume \"nodes G1 \\<union> nodes G2 \\<noteq> nodes (del_unEdge v w v' G)\"\n      moreover have \"nodes G1 \\<subseteq> nodes (del_unEdge v w v' G)\"\n        using valid_graph.is_path_memb[OF valid0] G1 G1_nodes by auto\n      moreover have \"nodes G2 \\<subseteq> nodes (del_unEdge v w v' G)\"\n        using valid_graph.is_path_memb[OF valid0] G2 G2_nodes by auto\n      ultimately obtain n where n:\n          \"n\\<in>nodes (del_unEdge v w v' G)\" \"n\\<notin>nodes G1\" \"n\\<notin>nodes G2\"\n        by auto\n      hence n_neg_v : \"\\<not>(\\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v)\" and\n            n_neg_v': \"\\<not>(\\<exists>ps. valid_graph.is_path (del_unEdge v w v' G) n ps v')\"\n        using G1 G1_nodes G2 G2_nodes by auto\n      hence \"n\\<noteq>v\" by (metis n(1) valid0 valid_graph.is_path_simps(1))\n      then obtain nvs where nvs: \"is_path n nvs v\" using `connected` \n        by (metis E_validD(1) assms(3) connected_def del_UnEdge_node n(1))\n      then obtain nvs' where nvs': \"nvs'=takeWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs\" by auto\n      moreover have nvs_nvs':\"nvs=nvs'@dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs\" \n        using nvs' takeWhile_dropWhile_id by auto\n      ultimately obtain n' where is_path_nvs': \"is_path n nvs' n'\"\n          and \"is_path n' (dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs) v\"\n        using nvs is_path_split[of n nvs' \"dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs\"] by auto\n      have \"n'=v \\<or> n'=v'\" \n        proof (cases \"dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs\")\n          case Nil\n          hence \"nvs=nvs'\" using nvs_nvs' by (metis append_Nil2)\n          hence \"n'=v\" using  nvs is_path_nvs' path_end by (metis (mono_tags) is_path.simps(1))\n          thus ?thesis  by auto\n        next\n          case (Cons x xs)\n          hence \"dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs\\<noteq>[]\" by auto\n          hence \"hd (dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs)=(v,w,v')\n                 \\<or> hd (dropWhile (\\<lambda>x. x\\<noteq>(v,w,v')\\<and>x\\<noteq>(v',w,v)) nvs)=(v',w,v)\" \n            by (metis (lifting, full_types) hd_dropWhile)\n          hence \"x=(v,w,v')\\<or>x=(v',w,v)\" using Cons by auto\n          thus ?thesis\n            using `is_path n' (dropWhile (\\<lambda>x. x \\<noteq> (v, w, v') \\<and> x \\<noteq> (v', w, v)) nvs) v`\n            by (metis Cons  is_path.simps(2))\n        qed\n      moreover have \"valid_graph.is_path (del_unEdge v w v' G) n nvs' n'\" \n        using is_path_nvs' nvs'\n        proof (induct nvs' arbitrary:n nvs)\n          case Nil\n          thus ?case by (metis del_UnEdge_node is_path.simps(1) valid0 valid_graph.is_path_simps(1))\n        next\n          case (Cons x xs)\n          obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n          hence \"is_path x3 xs n'\" using Cons by auto\n          moreover have \"xs = takeWhile (\\<lambda>x. x \\<noteq> (v, w, v') \\<and> x \\<noteq> (v', w, v)) (tl nvs)\" \n            using `x # xs = takeWhile (\\<lambda>x. x \\<noteq> (v, w, v') \\<and> x \\<noteq> (v', w, v)) nvs` \n            by (metis (lifting, no_types) append_Cons list.distinct(1) takeWhile.simps(2) \n                takeWhile_dropWhile_id list.sel(3))\n          ultimately have \"valid_graph.is_path (del_unEdge v w v' G) x3 xs n'\" \n            using Cons by auto\n          moreover have \"x\\<noteq>(v,w,v') \\<and> x\\<noteq>(v',w,v)\" \n            using Cons(3) set_takeWhileD[of x \"(\\<lambda>x. x \\<noteq> (v, w, v') \\<and> x \\<noteq> (v', w, v))\" nvs] \n            by (metis List.set_simps(2) insertI1)\n          hence \"x\\<in>edges (del_unEdge v w v' G)\" \n            by (metis Cons.prems(1) del_UnEdge_frame is_path.simps(2) x)\n          ultimately show ?case using x \n            by (metis Cons.prems(1) is_path.simps(2) valid0 valid_graph.is_path.simps(2))\n        qed\n      ultimately show False using n_neg_v n_neg_v' by auto\n    qed\n  moreover have \"nodes G1 \\<inter> nodes G2={}\" \n    proof (rule ccontr)\n      assume \"nodes G1 \\<inter> nodes G2 \\<noteq> {}\"\n      then obtain n where n:\"n\\<in>nodes G1\" \"n\\<in>nodes G2\" by auto  \n      then obtain nvs nv's where \n          nvs  : \"valid_graph.is_path (del_unEdge v w v' G) n nvs v\" and\n          nv's : \"valid_graph.is_path (del_unEdge v w v' G) n nv's v'\"\n        using G1 G2 G1_nodes G2_nodes by auto\n      hence \"valid_graph.is_path (del_unEdge v w v' G) v ((rev_path nvs)@nv's) v'\"\n        using valid_unMultigraph.is_path_rev[OF valid0'] valid_graph.is_path_split[OF valid0] \n        by auto \n      hence \"valid_unMultigraph.connected (del_unEdge v w v' G)\" \n        by (metis assms(1) del_unEdge_connectivity)\n      thus False by (metis assms(2))  \n    qed\n  moreover have \"edges G1 \\<union> edges G2 = edges (del_unEdge v w v' G)\" \n    proof (rule ccontr)\n      assume \"edges G1 \\<union> edges G2 \\<noteq> edges (del_unEdge v w v' G)\"\n      moreover have \"edges G1 \\<subseteq> edges (del_unEdge v w v' G)\" using G1 by auto\n      moreover have \"edges G2 \\<subseteq> edges (del_unEdge v w v' G)\" using G2 by auto\n      ultimately obtain n e n' where \n          nen':\n          \"(n,e,n')\\<in>edges (del_unEdge v w v' G)\" \n          \"(n,e,n')\\<notin>edges G1\" \"(n,e,n')\\<notin>edges G2\" \n        by auto\n      moreover have \"n\\<in>nodes (del_unEdge v w v' G)\" \n        by (metis nen'(1) valid0 valid_graph.E_validD(1))\n      moreover have \"n'\\<in>nodes (del_unEdge v w v' G)\" \n        by (metis nen'(1) valid0 valid_graph.E_validD(2))\n      ultimately have \"(n\\<in>nodes G1 \\<and> n'\\<in>nodes G2)\\<or>(n\\<in>nodes G2\\<and>n'\\<in>nodes G1)\" \n        using G1 G2 `nodes G1 \\<union> nodes G2=nodes (del_unEdge v w v' G)` by auto\n      moreover have \"n\\<in>nodes G1 \\<Longrightarrow> n'\\<in>nodes G2 \\<Longrightarrow> False\" \n        proof -\n          assume \"n\\<in>nodes G1\" \"n'\\<in>nodes G2\"\n          then obtain nvs nv's where \n              nvs  : \"valid_graph.is_path (del_unEdge v w v' G) n nvs v\" and\n              nv's : \"valid_graph.is_path (del_unEdge v w v' G) n' nv's v'\"\n            using G1 G2 G1_nodes G2_nodes by auto\n          hence \"valid_graph.is_path (del_unEdge v w v' G) v \n                  ((rev_path nvs)@(n,e,n')#nv's) v'\"\n            using valid_unMultigraph.is_path_rev[OF valid0'] valid_graph.is_path_split'[OF valid0]\n                  `(n,e,n')\\<in>edges (del_unEdge v w v' G)`\n            by auto \n          hence \"valid_unMultigraph.connected (del_unEdge v w v' G)\" \n            by (metis assms(1) del_unEdge_connectivity)\n          thus False by (metis assms(2))\n        qed\n      moreover have \"n\\<in>nodes G2 \\<Longrightarrow> n'\\<in>nodes G1 \\<Longrightarrow> False\" \n        proof -\n          assume \"n'\\<in>nodes G1\" \"n\\<in>nodes G2\"\n          then obtain n'vs nvs where \n              n'vs  : \"valid_graph.is_path (del_unEdge v w v' G) n' n'vs v\" and\n              nvs : \"valid_graph.is_path (del_unEdge v w v' G) n nvs v'\"\n            using G1 G2 G1_nodes G2_nodes by auto\n          moreover have \"(n',e,n)\\<in>edges (del_unEdge v w v' G)\" \n            by (metis nen'(1) valid0' valid_unMultigraph.corres)\n          ultimately have \"valid_graph.is_path (del_unEdge v w v' G) v \n                  ((rev_path n'vs)@(n',e,n)#nvs) v'\"\n            using valid_unMultigraph.is_path_rev[OF valid0'] valid_graph.is_path_split'[OF valid0]\n            by auto \n          hence \"valid_unMultigraph.connected (del_unEdge v w v' G)\" \n            by (metis assms(1) del_unEdge_connectivity)\n          thus False by (metis assms(2))\n        qed\n      ultimately show False by auto\n    qed\n  moreover have \"edges G1 \\<inter> edges G2={}\" \n    proof (rule ccontr)\n      assume \"edges G1 \\<inter> edges G2 \\<noteq> {}\"\n      then obtain n e n' where \"(n,e,n')\\<in>edges G1\" \"(n,e,n')\\<in>edges G2\" by auto\n      hence \"n\\<in>nodes G1\" \"n\\<in>nodes G2\" using G1 G2 by auto\n      thus False using `nodes G1 \\<inter> nodes G2={}` by auto\n    qed\n  moreover have \"valid_unMultigraph.connected G1\" \n    unfolding valid_unMultigraph.connected_def[OF valid_G1]\n    proof (rule,rule,rule)\n      fix n n' \n      assume  n : \"n \\<in>nodes G1\" \n      assume  n': \"n'\\<in>nodes G1\"\n      assume \"n\\<noteq>n'\"\n      obtain ps where \"valid_graph.is_path (del_unEdge v w v' G) n ps v\" \n        using G1 G1_nodes n by auto\n      hence ps:\"valid_graph.is_path G1 n ps v\" \n        proof (induct ps arbitrary:n)\n          case Nil\n          moreover have \"v\\<in>nodes G1\" using G1 G1_nodes valid0 \n            by (metis (lifting, no_types) calculation mem_Collect_eq select_convs(1) \n                valid_graph.is_path.simps(1))\n          ultimately show ?case \n            by (metis valid0 valid_G1 valid_unMultigraph.is_trail.simps(1)\n                 valid_graph.is_path.simps(1)  valid_unMultigraph.is_trail_intro)\n        next\n          case (Cons x xs)\n          obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n          have \"x1\\<in>nodes G1\" using G1 G1_nodes Cons.prems x \n            by (metis (lifting) mem_Collect_eq select_convs(1) valid0 valid_graph.is_path.simps(2))\n          moreover have \"(x1,x2,x3)\\<in>edges (del_unEdge v w v' G)\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately have \"(x1,x2,x3)\\<in>edges G1\" \n            using G1 G2 `nodes G1 \\<inter> nodes G2={}` `edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)` \n            by (metis (full_types) IntI Un_iff  bex_empty   valid_G2' valid_graph.E_validD(1) )\n          moreover have \"valid_graph.is_path (del_unEdge v w v' G) x3 xs v\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          hence \"valid_graph.is_path G1 x3 xs v\" using Cons.hyps by auto\n          moreover have \"x1=n\" by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately show ?case using x valid_G1' by (metis valid_graph.is_path.simps(2))   \n        qed\n      obtain ps' where \"valid_graph.is_path (del_unEdge v w v' G) n' ps' v\" \n        using G1 G1_nodes n' by auto\n      hence ps':\"valid_graph.is_path G1 n' ps' v\" \n        proof (induct ps' arbitrary:n')\n          case Nil\n          moreover have \"v\\<in>nodes G1\" using G1 G1_nodes valid0 \n            by (metis (lifting, no_types) calculation mem_Collect_eq select_convs(1) \n                valid_graph.is_path.simps(1))\n          ultimately show ?case \n            by (metis valid0 valid_G1 valid_unMultigraph.is_trail.simps(1)\n                 valid_graph.is_path.simps(1)  valid_unMultigraph.is_trail_intro)\n        next\n          case (Cons x xs)\n          obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n          have \"x1\\<in>nodes G1\" using G1 G1_nodes Cons.prems x \n            by (metis (lifting) mem_Collect_eq select_convs(1) valid0 valid_graph.is_path.simps(2))\n          moreover have \"(x1,x2,x3)\\<in>edges (del_unEdge v w v' G)\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately have \"(x1,x2,x3)\\<in>edges G1\" \n            using G1 G2 `nodes G1 \\<inter> nodes G2={}` \n              `edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)`\n            by (metis (full_types) IntI Un_iff  bex_empty  valid_G2' valid_graph.E_validD(1))\n          moreover have \"valid_graph.is_path (del_unEdge v w v' G) x3 xs v\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          hence \"valid_graph.is_path G1 x3 xs v\" using Cons.hyps by auto\n          moreover have \"x1=n'\" by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately show ?case using x valid_G1' by (metis valid_graph.is_path.simps(2))   \n        qed\n      hence \"valid_graph.is_path G1 v (rev_path ps') n'\" \n        using valid_unMultigraph.is_path_rev[OF valid_G1]\n        by auto\n      hence \"valid_graph.is_path G1 n (ps@(rev_path ps')) n'\" \n        using ps valid_graph.is_path_split[OF valid_G1',of n ps \"rev_path ps'\" n']\n        by auto\n      thus \"\\<exists>ps. valid_graph.is_path G1 n ps n'\" by auto\n    qed\n  moreover have \"valid_unMultigraph.connected G2\" \n    unfolding valid_unMultigraph.connected_def[OF valid_G2]\n    proof (rule,rule,rule)\n      fix n n' \n      assume  n : \"n \\<in>nodes G2\" \n      assume  n': \"n'\\<in>nodes G2\"\n      assume \"n\\<noteq>n'\"\n      obtain ps where \"valid_graph.is_path (del_unEdge v w v' G) n ps v'\" \n        using G2 G2_nodes n by auto\n      hence ps:\"valid_graph.is_path G2 n ps v'\" \n        proof (induct ps arbitrary:n)\n          case Nil\n          moreover have \"v'\\<in>nodes G2\" using G2 G2_nodes valid0 \n            by (metis (lifting, no_types) calculation mem_Collect_eq select_convs(1) \n                valid_graph.is_path.simps(1))\n          ultimately show ?case \n            by (metis valid0 valid_G2 valid_unMultigraph.is_trail.simps(1)\n                 valid_graph.is_path.simps(1)  valid_unMultigraph.is_trail_intro)\n        next\n          case (Cons x xs)\n          obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n          have \"x1\\<in>nodes G2\" using G2 G2_nodes Cons.prems x \n            by (metis (lifting) mem_Collect_eq select_convs(1) valid0 valid_graph.is_path.simps(2))\n          moreover have \"(x1,x2,x3)\\<in>edges (del_unEdge v w v' G)\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately have \"(x1,x2,x3)\\<in>edges G2\" \n            using `nodes G1 \\<inter> nodes G2={}` `edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)`\n            by (metis IntI Un_iff assms(1) bex_empty connected_def del_UnEdge_node valid0 valid0'\n              valid_G1' valid_graph.E_validD(1) valid_graph.E_validD(2) valid_unMultigraph.no_id)\n          moreover have \"valid_graph.is_path (del_unEdge v w v' G) x3 xs v'\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          hence \"valid_graph.is_path G2 x3 xs v'\" using Cons.hyps by auto\n          moreover have \"x1=n\" by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately show ?case using x valid_G2' by (metis valid_graph.is_path.simps(2))   \n        qed\n      obtain ps' where \"valid_graph.is_path (del_unEdge v w v' G) n' ps' v'\" \n        using G2 G2_nodes n' by auto\n      hence ps':\"valid_graph.is_path G2 n' ps' v'\" \n        proof (induct ps' arbitrary:n')\n          case Nil\n          moreover have \"v'\\<in>nodes G2\" using G2 G2_nodes valid0 \n            by (metis (lifting, no_types) calculation mem_Collect_eq select_convs(1) \n                valid_graph.is_path.simps(1))\n          ultimately show ?case \n            by (metis valid0 valid_G2 valid_unMultigraph.is_trail.simps(1)\n                 valid_graph.is_path.simps(1)  valid_unMultigraph.is_trail_intro)\n        next\n          case (Cons x xs)\n          obtain x1 x2 x3 where x:\"x=(x1,x2,x3)\" by (metis prod_cases3)\n          have \"x1\\<in>nodes G2\" using G2 G2_nodes Cons.prems x \n            by (metis (lifting) mem_Collect_eq select_convs(1) valid0 valid_graph.is_path.simps(2))\n          moreover have \"(x1,x2,x3)\\<in>edges (del_unEdge v w v' G)\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately have \"(x1,x2,x3)\\<in>edges G2\" \n            using  `nodes G1 \\<inter> nodes G2={}` `edges G1 \\<union> edges G2=edges (del_unEdge v w v' G)`\n            by (metis IntI Un_iff assms(1) bex_empty connected_def del_UnEdge_node valid0 valid0' \n              valid_G1' valid_graph.E_validD(1) valid_graph.E_validD(2) valid_unMultigraph.no_id)\n          moreover have \"valid_graph.is_path (del_unEdge v w v' G) x3 xs v'\" \n            by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          hence \"valid_graph.is_path G2 x3 xs v'\" using Cons.hyps by auto\n          moreover have \"x1=n'\" by (metis Cons.prems valid0 valid_graph.is_path.simps(2) x)\n          ultimately show ?case using x valid_G2' by (metis valid_graph.is_path.simps(2))   \n        qed\n      hence \"valid_graph.is_path G2 v' (rev_path ps') n'\" \n        using valid_unMultigraph.is_path_rev[OF valid_G2]\n        by auto\n      hence \"valid_graph.is_path G2 n (ps@(rev_path ps')) n'\" \n        using ps valid_graph.is_path_split[OF valid_G2',of n ps \"rev_path ps'\" n']\n        by auto\n      thus \"\\<exists>ps. valid_graph.is_path G2 n ps n'\" by auto\n    qed\n  ultimately show ?thesis using valid_G1 valid_G2 that by auto\nqed\n\n\nlemma sub_graph_degree_frame:\n  assumes \"valid_graph G2\" \"edges G1 \\<union> edges G2 =edges G\" \"nodes G1 \\<inter> nodes G2={}\" \"n\\<in>nodes G1\"\n  shows \"degree n G=degree n G1\"\nproof -\n  have \"{e \\<in> edges G. fst e = n}\\<subseteq>{e \\<in> edges G1. fst e = n}\" \n    proof \n      fix e assume  \"e \\<in> {e \\<in> edges G. fst e = n}\"\n      hence \"e\\<in>edges G\" \"fst e=n\" by auto\n      moreover have \"n\\<notin>nodes G2\" \n        using `nodes G1 \\<inter> nodes G2={}` `n\\<in>nodes G1`\n        by auto\n      hence \"e\\<notin>edges G2\" using valid_graph.E_validD[OF `valid_graph G2`] `fst e=n` \n        by (metis PairE fst_conv)  \n      ultimately have \"e\\<in>edges G1\" using `edges G1 \\<union> edges G2 =edges G` by auto\n      thus \"e \\<in> {e \\<in> edges G1. fst e = n}\" using `fst e=n` by auto\n    qed\n  moreover have \"{e \\<in> edges G1. fst e = n}\\<subseteq>{e \\<in> edges G. fst e = n}\" \n    by (metis (lifting) Collect_mono Un_iff assms(2))\n  ultimately show ?thesis unfolding degree_def by auto\nqed\n      \nlemma odd_nodes_no_edge[simp]: \"finite (nodes g) \\<Longrightarrow> num_of_odd_nodes (g \\<lparr>edges:={} \\<rparr>) = 0\" \n  unfolding  num_of_odd_nodes_def odd_nodes_set_def degree_def by simp\n\nsection {*Adjacent nodes*}\n  \ndefinition (in valid_unMultigraph) adjacent:: \"'v \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n    \"adjacent v v' \\<equiv> \\<exists>w. (v,w,v')\\<in>E\"\n    \nlemma (in valid_unMultigraph) adjacent_sym: \"adjacent v v' \\<longleftrightarrow> adjacent v' v\" \n    unfolding adjacent_def by auto\n  \nlemma (in valid_unMultigraph) adjacent_no_loop[simp]: \"adjacent v v' \\<Longrightarrow> v \\<noteq>v'\"\n     unfolding adjacent_def by auto\n\nlemma (in valid_unMultigraph) adjacent_V[simp]: \n    assumes \"adjacent v v'\"\n    shows \"v\\<in>V\" \"v'\\<in>V\"\n  using assms E_validD unfolding adjacent_def by auto\n\n\nlemma (in valid_unMultigraph) adjacent_finite:\n  \"finite E \\<Longrightarrow> finite {n. adjacent v n}\"\nproof -\n  assume \"finite E\"\n  { fix S v \n    have \"finite S \\<Longrightarrow> finite {n. \\<exists>w. (v,w,n)\\<in>S}\" \n      proof (induct S rule: finite_induct)\n        case empty\n        thus ?case by auto\n      next\n        case (insert x F)\n        obtain x1 x2 x3 where x: \"x=(x1,x2,x3)\" by (metis prod_cases3)\n        have \"x1=v \\<Longrightarrow> ?case\"\n          proof -\n            assume \"x1=v\"\n            hence \"{n. \\<exists>w. (v, w, n) \\<in> insert x F}=insert x3 {n. \\<exists>w. (v, w, n) \\<in> F}\"\n              using x by auto\n            thus ?thesis using insert by auto\n          qed\n        moreover have \"x1\\<noteq>v \\<Longrightarrow> ?case\"\n          proof -\n            assume \"x1\\<noteq>v\"\n            hence \"{n. \\<exists>w. (v, w, n) \\<in> insert x F}={n. \\<exists>w. (v, w, n) \\<in> F}\" using x by auto\n            thus ?thesis using insert by auto\n          qed\n        ultimately show ?case by auto\n      qed }\n  note aux=this\n  show ?thesis using aux[OF `finite E`, of v]  unfolding adjacent_def by auto\nqed\n\nsection{* Undirected simple graph*}\n\nlocale valid_unSimpGraph=valid_unMultigraph G for G::\"('v,'w) graph\"+\n              assumes no_multi[simp]: \"(v,w,u) \\<in> edges G \\<Longrightarrow> (v,w',u) \\<in>edges G \\<Longrightarrow> w = w'\"\n\nlemma (in valid_unSimpGraph) finV_to_finE[simp]: \n  assumes \"finite V\" \n  shows \"finite E\"\nproof (cases \"{(v1,v2). adjacent v1 v2}={}\")\n  case True\n  hence \"E={}\" unfolding adjacent_def by auto\n  thus \"finite E\" by auto\nnext\n  case False\n  have \"{(v1,v2). adjacent v1 v2} \\<subseteq> V \\<times> V\" using adjacent_V by auto\n  moreover have \"finite (V \\<times> V)\" using `finite V` by auto\n  ultimately have \"finite {(v1,v2). adjacent v1 v2}\" using finite_subset by auto\n  hence \"card {(v1,v2). adjacent v1 v2}\\<noteq>0\" using False card_eq_0_iff by auto\n  moreover have \"card E=card {(v1,v2). adjacent v1 v2}\" \n    proof -\n      have \"(\\<lambda>(v1,w,v2). (v1,v2))`E = {(v1,v2). adjacent v1 v2}\" \n        proof -\n          have \"\\<And>x. x\\<in>(\\<lambda>(v1,w,v2). (v1,v2))`E \\<Longrightarrow> x\\<in> {(v1,v2). adjacent v1 v2}\" \n            unfolding adjacent_def by auto\n          moreover have \"\\<And>x. x\\<in>{(v1,v2). adjacent v1 v2} \\<Longrightarrow> x\\<in>(\\<lambda>(v1,w,v2). (v1,v2))`E\" \n            unfolding adjacent_def by force\n          ultimately show ?thesis by force\n        qed\n      moreover have \"inj_on (\\<lambda>(v1,w,v2). (v1,v2)) E\" unfolding inj_on_def by auto\n      ultimately show ?thesis by (metis card_image)\n    qed\n  ultimately show \"finite E\" by (metis card_infinite)\nqed\n\n\n\n\nlemma (in valid_unSimpGraph) del_UnEdge_non_adj: \n    \"(v,w,u)\\<in>E \\<Longrightarrow> \\<not>valid_unMultigraph.adjacent (del_unEdge v w u G) v u\"\nproof\n  assume \"(v, w, u) \\<in> E\" \n      and ccontr:\"valid_unMultigraph.adjacent (del_unEdge v w u G) v u\"\n  have valid:\"valid_unMultigraph (del_unEdge v w u G)\" \n    using valid_unMultigraph_axioms by auto\n  then obtain w' where vw'u:\"(v,w',u)\\<in>edges (del_unEdge v w u G)\"\n    using ccontr unfolding valid_unMultigraph.adjacent_def[OF valid] by auto\n  hence \"(v,w',u)\\<notin>{(v,w,u),(u,w,v)}\" unfolding del_unEdge_def by auto\n  hence \"w'\\<noteq>w\" by auto\n  moreover have \"(v,w',u)\\<in>E\" using vw'u unfolding del_unEdge_def by auto\n  ultimately show False using no_multi[of v w u w'] `(v, w, u) \\<in> E` by auto\nqed\n\nlemma (in valid_unSimpGraph) degree_adjacent: \"finite E \\<Longrightarrow> degree v G=card {n. adjacent v n}\"\n  using valid_unSimpGraph_axioms \nproof (induct \"degree v G\" arbitrary: G)\n  case 0\n  note valid3=`valid_unSimpGraph G`\n  hence valid2: \"valid_unMultigraph G\" using valid_unSimpGraph_def by auto\n  have \"{a. valid_unMultigraph.adjacent G v a}={}\" \n    proof (rule ccontr)\n      assume \"{a. valid_unMultigraph.adjacent G v a} \\<noteq> {}\"\n      then obtain w u where \"(v,w,u)\\<in>edges G\" \n        unfolding valid_unMultigraph.adjacent_def[OF valid2] by auto\n      hence \"degree v G\\<noteq>0\" using `finite (edges G)` unfolding degree_def by auto\n      thus False using `0 = degree v G` by auto\n    qed\n  thus ?case by (metis \"0.hyps\" card_empty)\nnext\n  case (Suc n)\n  hence \"{e \\<in> edges G. fst e = v}\\<noteq>{}\" using card_empty unfolding degree_def  by force\n  then obtain w u where \"(v,w,u)\\<in>edges G\" by auto\n  have valid:\"valid_unMultigraph G\" using `valid_unSimpGraph G` valid_unSimpGraph_def by auto\n  hence valid':\"valid_unMultigraph (del_unEdge v w u G)\" by auto\n  have \"valid_unSimpGraph (del_unEdge v w u G)\" \n    using del_unEdge_valid' `valid_unSimpGraph G` by auto\n  moreover have \"n = degree v (del_unEdge v w u G)\" \n    using `Suc n = degree v G``(v, w, u) \\<in> edges G`  del_edge_undirected_degree_plus[of G v w u]\n    by (metis Suc.prems(1) Suc_eq_plus1 diff_Suc_1 valid valid_unMultigraph.corres)\n  moreover have \"finite (edges (del_unEdge v w u G))\" \n    using `finite (edges G)` unfolding del_unEdge_def\n    by auto\n  ultimately have \"degree v (del_unEdge v w u G) \n      = card (Collect (valid_unMultigraph.adjacent (del_unEdge v w u G) v))\"\n    using Suc.hyps  by auto\n  moreover have \"Suc(card ({n. valid_unMultigraph.adjacent (del_unEdge v w u G)  \n      v n})) = card ({n. valid_unMultigraph.adjacent G v n})\" \n    using valid_unMultigraph.adjacent_def[OF valid'] \n    proof -\n      have \"{n. valid_unMultigraph.adjacent (del_unEdge v w u G) v n} \\<subseteq> \n          {n. valid_unMultigraph.adjacent G v n}\"\n        using del_unEdge_def[of v w u G]\n        unfolding valid_unMultigraph.adjacent_def[OF valid'] \n          valid_unMultigraph.adjacent_def[OF valid]\n        by auto\n      moreover have \"u\\<in>{n. valid_unMultigraph.adjacent G v n}\" \n        using `(v,w,u)\\<in>edges G` unfolding valid_unMultigraph.adjacent_def[OF valid] by auto\n      ultimately have \"{n. valid_unMultigraph.adjacent (del_unEdge v w u G) v n} \\<union> {u}\n          \\<subseteq> {n. valid_unMultigraph.adjacent G v n}\" by auto\n      moreover have \"{n. valid_unMultigraph.adjacent G v n} - {u}\n          \\<subseteq> {n. valid_unMultigraph.adjacent (del_unEdge v w u G) v n}\"\n        using del_unEdge_def[of v w u G]\n        unfolding valid_unMultigraph.adjacent_def[OF valid'] \n          valid_unMultigraph.adjacent_def[OF valid]\n        by auto\n      ultimately have \"{n. valid_unMultigraph.adjacent (del_unEdge v w u G) v n} \\<union> {u}\n          = {n. valid_unMultigraph.adjacent G v n}\" by auto\n      moreover have \"u\\<notin>{n. valid_unMultigraph.adjacent (del_unEdge v w u G) v n}\" \n        using valid_unSimpGraph.del_UnEdge_non_adj[OF `valid_unSimpGraph G` `(v,w,u)\\<in>edges G`]\n        by auto\n      moreover have \"finite {n. valid_unMultigraph.adjacent G v n}\" \n        using valid_unMultigraph.adjacent_finite[OF valid `finite (edges G)`] by simp \n      ultimately show ?thesis \n        by (metis Un_insert_right card_insert_disjoint finite_Un sup_bot_right)\n    qed\n  ultimately show ?case by (metis Suc.hyps(2) `n = degree v (del_unEdge v w u G)`)\nqed \n  \nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Koenigsberg_Friendship/MoreGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7711892449111248}}
{"text": "theory ex_2_2\n  imports Main\nbegin\nfun add::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 m = m\" | \n\"add (Suc n) m = Suc (add n m)\"\n\ntheorem add_assoc: \"add x (add y z) = add (add x y) z\"\n  apply (induction x)\n  by (auto)\n\nlemma add_suc_r[simp]: \"add n (Suc m) = Suc (add n m)\"\n  apply (induction n)\n  by (auto)\n\nlemma add_id_r[simp]: \"add y 0 = y\"\n  apply (induction y)\n  by (auto)\n\ntheorem add_comm: \"add x y = add y x\"\n  apply (induction x)\n  by (auto)\n\nfun double::\"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc n) = Suc(Suc(double n))\"\n\ntheorem double_add: \"double m = add m m\"\n  apply (induction m)\n  by (auto)\nend", "meta": {"author": "20051615", "repo": "Gale-Shapley-formalization", "sha": "d601131b66c039561f8a72cd4913fcf8c84f08fa", "save_path": "github-repos/isabelle/20051615-Gale-Shapley-formalization", "path": "github-repos/isabelle/20051615-Gale-Shapley-formalization/Gale-Shapley-formalization-d601131b66c039561f8a72cd4913fcf8c84f08fa/tutorials/prog-prove/ex_2_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465116437761, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.7711575807680334}}
{"text": "(*  Title:      HOL/Isar_Examples/Expr_Compiler.thy\n    Author:     Makarius\n\nCorrectness of a simple expression/stack-machine compiler.\n*)\n\nsection \\<open>Correctness of a simple expression compiler\\<close>\n\ntheory Expr_Compiler\n  imports Main\nbegin\n\ntext \\<open>\n  This is a (rather trivial) example of program verification. We model a\n  compiler for translating expressions to stack machine instructions, and\n  prove its correctness wrt.\\ some evaluation semantics.\n\\<close>\n\n\nsubsection \\<open>Binary operations\\<close>\n\ntext \\<open>\n  Binary operations are just functions over some type of values. This is both\n  for abstract syntax and semantics, i.e.\\ we use a ``shallow embedding''\n  here.\n\\<close>\n\ntype_synonym 'val binop = \"'val \\<Rightarrow> 'val \\<Rightarrow> 'val\"\n\n\nsubsection \\<open>Expressions\\<close>\n\ntext \\<open>\n  The language of expressions is defined as an inductive type, consisting of\n  variables, constants, and binary operations on expressions.\n\\<close>\n\ndatatype (dead 'adr, dead 'val) expr =\n    Variable 'adr\n  | Constant 'val\n  | Binop \"'val binop\" \"('adr, 'val) expr\" \"('adr, 'val) expr\"\n\ntext \\<open>\n  Evaluation (wrt.\\ some environment of variable assignments) is defined by\n  primitive recursion over the structure of expressions.\n\\<close>\n\nprimrec eval :: \"('adr, 'val) expr \\<Rightarrow> ('adr \\<Rightarrow> 'val) \\<Rightarrow> 'val\"\n  where\n    \"eval (Variable x) env = env x\"\n  | \"eval (Constant c) env = c\"\n  | \"eval (Binop f e1 e2) env = f (eval e1 env) (eval e2 env)\"\n\n\nsubsection \\<open>Machine\\<close>\n\ntext \\<open>\n  Next we model a simple stack machine, with three instructions.\n\\<close>\n\ndatatype (dead 'adr, dead 'val) instr =\n    Const 'val\n  | Load 'adr\n  | Apply \"'val binop\"\n\ntext \\<open>\n  Execution of a list of stack machine instructions is easily defined as\n  follows.\n\\<close>\n\nprimrec exec :: \"(('adr, 'val) instr) list \\<Rightarrow> 'val list \\<Rightarrow> ('adr \\<Rightarrow> 'val) \\<Rightarrow> 'val list\"\n  where\n    \"exec [] stack env = stack\"\n  | \"exec (instr # instrs) stack env =\n      (case instr of\n        Const c \\<Rightarrow> exec instrs (c # stack) env\n      | Load x \\<Rightarrow> exec instrs (env x # stack) env\n      | Apply f \\<Rightarrow> exec instrs (f (hd stack) (hd (tl stack)) # (tl (tl stack))) env)\"\n\ndefinition execute :: \"(('adr, 'val) instr) list \\<Rightarrow> ('adr \\<Rightarrow> 'val) \\<Rightarrow> 'val\"\n  where \"execute instrs env = hd (exec instrs [] env)\"\n\n\nsubsection \\<open>Compiler\\<close>\n\ntext \\<open>\n  We are ready to define the compilation function of expressions to lists of\n  stack machine instructions.\n\\<close>\n\nprimrec compile :: \"('adr, 'val) expr \\<Rightarrow> (('adr, 'val) instr) list\"\n  where\n    \"compile (Variable x) = [Load x]\"\n  | \"compile (Constant c) = [Const c]\"\n  | \"compile (Binop f e1 e2) = compile e2 @ compile e1 @ [Apply f]\"\n\n\ntext \\<open>\n  The main result of this development is the correctness theorem for\n  \\<open>compile\\<close>. We first establish a lemma about \\<open>exec\\<close> and list append.\n\\<close>\n\nlemma exec_append:\n  \"exec (xs @ ys) stack env =\n    exec ys (exec xs stack env) env\"\nproof (induct xs arbitrary: stack)\n  case Nil\n  show ?case by simp\nnext\n  case (Cons x xs)\n  show ?case\n  proof (induct x)\n    case Const\n    from Cons show ?case by simp\n  next\n    case Load\n    from Cons show ?case by simp\n  next\n    case Apply\n    from Cons show ?case by simp\n  qed\nqed\n\ntheorem correctness: \"execute (compile e) env = eval e env\"\nproof -\n  have \"\\<And>stack. exec (compile e) stack env = eval e env # stack\"\n  proof (induct e)\n    case Variable\n    show ?case by simp\n  next\n    case Constant\n    show ?case by simp\n  next\n    case Binop\n    then show ?case by (simp add: exec_append)\n  qed\n  then show ?thesis by (simp add: execute_def)\nqed\n\n\ntext \\<open>\n  \\<^bigskip>\n  In the proofs above, the \\<open>simp\\<close> method does quite a lot of work behind the\n  scenes (mostly ``functional program execution''). Subsequently, the same\n  reasoning is elaborated in detail --- at most one recursive function\n  definition is used at a time. Thus we get a better idea of what is actually\n  going on.\n\\<close>\n\nlemma exec_append':\n  \"exec (xs @ ys) stack env = exec ys (exec xs stack env) env\"\nproof (induct xs arbitrary: stack)\n  case (Nil s)\n  have \"exec ([] @ ys) s env = exec ys s env\"\n    by simp\n  also have \"\\<dots> = exec ys (exec [] s env) env\"\n    by simp\n  finally show ?case .\nnext\n  case (Cons x xs s)\n  show ?case\n  proof (induct x)\n    case (Const val)\n    have \"exec ((Const val # xs) @ ys) s env = exec (Const val # xs @ ys) s env\"\n      by simp\n    also have \"\\<dots> = exec (xs @ ys) (val # s) env\"\n      by simp\n    also from Cons have \"\\<dots> = exec ys (exec xs (val # s) env) env\" .\n    also have \"\\<dots> = exec ys (exec (Const val # xs) s env) env\"\n      by simp\n    finally show ?case .\n  next\n    case (Load adr)\n    from Cons show ?case\n      by simp \\<comment> \\<open>same as above\\<close>\n  next\n    case (Apply fn)\n    have \"exec ((Apply fn # xs) @ ys) s env =\n        exec (Apply fn # xs @ ys) s env\" by simp\n    also have \"\\<dots> =\n        exec (xs @ ys) (fn (hd s) (hd (tl s)) # (tl (tl s))) env\"\n      by simp\n    also from Cons have \"\\<dots> =\n        exec ys (exec xs (fn (hd s) (hd (tl s)) # tl (tl s)) env) env\" .\n    also have \"\\<dots> = exec ys (exec (Apply fn # xs) s env) env\"\n      by simp\n    finally show ?case .\n  qed\nqed\n\ntheorem correctness': \"execute (compile e) env = eval e env\"\nproof -\n  have exec_compile: \"\\<And>stack. exec (compile e) stack env = eval e env # stack\"\n  proof (induct e)\n    case (Variable adr s)\n    have \"exec (compile (Variable adr)) s env = exec [Load adr] s env\"\n      by simp\n    also have \"\\<dots> = env adr # s\"\n      by simp\n    also have \"env adr = eval (Variable adr) env\"\n      by simp\n    finally show ?case .\n  next\n    case (Constant val s)\n    show ?case by simp \\<comment> \\<open>same as above\\<close>\n  next\n    case (Binop fn e1 e2 s)\n    have \"exec (compile (Binop fn e1 e2)) s env =\n        exec (compile e2 @ compile e1 @ [Apply fn]) s env\"\n      by simp\n    also have \"\\<dots> = exec [Apply fn]\n        (exec (compile e1) (exec (compile e2) s env) env) env\"\n      by (simp only: exec_append)\n    also have \"exec (compile e2) s env = eval e2 env # s\"\n      by fact\n    also have \"exec (compile e1) \\<dots> env = eval e1 env # \\<dots>\"\n      by fact\n    also have \"exec [Apply fn] \\<dots> env =\n        fn (hd \\<dots>) (hd (tl \\<dots>)) # (tl (tl \\<dots>))\"\n      by simp\n    also have \"\\<dots> = fn (eval e1 env) (eval e2 env) # s\"\n      by simp\n    also have \"fn (eval e1 env) (eval e2 env) =\n        eval (Binop fn e1 e2) env\"\n      by simp\n    finally show ?case .\n  qed\n\n  have \"execute (compile e) env = hd (exec (compile e) [] env)\"\n    by (simp add: execute_def)\n  also from exec_compile have \"exec (compile e) [] env = [eval e env]\" .\n  also have \"hd \\<dots> = eval e env\"\n    by simp\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Isar_Examples/Expr_Compiler.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.9136765228260895, "lm_q1q2_score": 0.771047135757733}}
{"text": "section\\<open>Core data structures\\<close>\ntheory Data\nimports Main\nbegin\n\nsubsection \\<open>Data types\\<close>\n\nsubsubsection \\<open>Unique identifier\\<close>\n\ntext \\<open>Every node of a BDD is uniquely identified by its label and a level-identifer. The prior is\n      the input variable in \\<open>'l\\<close> that it represents, while the second is supposed to induce a total\n      ordering within a level.\\<close>\n\ndatatype 'l uid = U (label:\\<open>'l\\<close>) (id:\\<open>nat\\<close>)\n\ntext \\<open>All algorithms are based on a level-by-level processing of all nodes. This requires nodes to\n      be topologically ordered. Secondly, these algorithms need to know when they are going to see\n      a node within the level, so secondarily they are sorted on the identifier.\n\n      Hence, the uid is sorted lexicographically on the above tuple.\\<close>\n\ninstantiation uid :: (linorder) linorder\nbegin\ndefinition less_uid where\n   \\<open>less_uid \\<equiv> \\<lambda>(U i1 id1) \\<Rightarrow> \\<lambda>(U i2 id2) \\<Rightarrow> (i1 < i2 \\<or> (i1 = i2 \\<and> id1 < id2))\\<close>\n\ndefinition less_eq_uid where\n   \\<open>less_eq_uid \\<equiv> \\<lambda>(U i1 id1) \\<Rightarrow> \\<lambda>(U i2 id2) \\<Rightarrow> (i1 < i2 \\<or> (i1 = i2 \\<and> id1 \\<le> id2))\\<close>\n\ninstance\n  by standard (auto simp: less_uid_def less_eq_uid_def split: uid.splits)\n\nend\n\nlemma less_uid_simp[simp]:\n  \\<open>(U i1 id1) < (U i2 id2) = (i1 < i2 \\<or> (i1 = i2 \\<and> id1 < id2))\\<close>\n  unfolding less_uid_def by simp\n\nlemma less_eq_uid_simp[simp]:\n  \\<open>(U i1 id1) \\<le> (U i2 id2) = (i1 < i2 \\<or> (i1 = i2 \\<and> id1 \\<le> id2))\\<close>\n  unfolding less_eq_uid_def by simp\n\nsubsubsection \\<open>Pointer\\<close>\n\ntext \\<open>The above encapsulates identification of an internal node of a BDD. We also need nodes to be\n      able to reference leaves in the BDD, i.e. the True and the False Boolean values.\n\n      Hence, a pointer can either refer to a leaf or to an internal node. To this end, we lift the\n      ordering from both the ordering of Boolean values (\\<open>False < True\\<close>) and the ordering of uids up\n      to pointers.\\<close>\n\ndatatype 'l ptr = Leaf \\<open>bool\\<close> | Node \\<open>'l uid\\<close>\n\ninstantiation ptr :: (linorder) linorder\nbegin\ndefinition less_ptr where\n   \\<open>less_ptr \\<equiv> \\<lambda>ptr1 \\<Rightarrow> \\<lambda>ptr2 \\<Rightarrow> (case (ptr1, ptr2) of\n      (Node u1, Node u2) \\<Rightarrow> u1 < u2\n    | (Node _, Leaf _) \\<Rightarrow> True\n    | (Leaf _, Node _) \\<Rightarrow> False\n    | (Leaf b1, Leaf b2) \\<Rightarrow> b1 < b2)\\<close>\n\ndefinition less_eq_ptr where\n   \\<open>less_eq_ptr \\<equiv> \\<lambda>ptr1 \\<Rightarrow> \\<lambda>ptr2 \\<Rightarrow> (case (ptr1, ptr2) of\n      (Node u1, Node u2) \\<Rightarrow> u1 \\<le> u2\n    | (Node _, Leaf _) \\<Rightarrow> True\n    | (Leaf _, Node _) \\<Rightarrow> False\n    | (Leaf b1, Leaf b2) \\<Rightarrow> b1 \\<le> b2\n)\\<close>\n\ninstance\n  by standard (auto simp: less_ptr_def less_eq_ptr_def split: ptr.splits)\nend\n\ntext \\<open>And a simple rule to simplify case distinction on pointers within our proofs.\\<close>\n\nlemma ptr_cases:\n  fixes ptr :: \"'a ptr\"\n  obtains\n    (True)  \"ptr = Leaf True\"\n  | (False) \"ptr = Leaf False\"\n  | (Node)  u :: \"'a uid\" where \"ptr = Node u\"\n  by (cases ptr) auto\n\nsubsubsection \\<open>Node data type\\<close>\n\ntext \\<open>A node is a triple that consists of its unique identifier, i.e. its label and its\n      level-identifier, together with a pointer to its high child, i.e. where to go to in the 'then'\n      case on the input variable, and finally the pointer to its low child, i.e. where to go to when\n      the input variable evaluates to false.\\<close>\n\ndatatype 'l node = N (uid:\\<open>'l uid\\<close>) (high:\\<open>'l ptr\\<close>) (low:\\<open>'l ptr\\<close>)\n\ntext \\<open>Nodes are sorted lexicographically on the above triple. This makes nodes first and foremost\n      sorted by their unique identifiers, which makes them topologically ordered.\n\n      At this point, we are not (yet) going to use the ordering on children. See Reduce.thy for how\n      we actually can guarantee this ordering is fully satisfied.\\<close>\n\ninstantiation node :: (linorder) linorder\nbegin\ndefinition less_node where\n  \\<open>less_node \\<equiv> \\<lambda>(N i1 t1 e1) \\<Rightarrow> \\<lambda>(N i2 t2 e2) \\<Rightarrow>\n    (i1 < i2 \\<or> i1 = i2 \\<and> t1 < t2 \\<or> i1 = i2 \\<and> t1 = t2 \\<and> e1 < e2)\\<close>\n\ndefinition less_eq_node where\n  \\<open>less_eq_node \\<equiv> \\<lambda>(N i1 t1 e1) \\<Rightarrow> \\<lambda>(N i2 t2 e2) \\<Rightarrow>\n    (i1 < i2 \\<or> i1 = i2 \\<and> t1 < t2 \\<or> i1 = i2 \\<and> t1 = t2 \\<and> e1 \\<le> e2)\\<close>\n\ninstance\n  by standard (auto simp: less_node_def less_eq_node_def split: node.splits)\n\nend\n\nlemma less_node_simp[simp]:\n  \\<open>(N i1 t1 e1) < (N i2 t2 e2) =\n    (i1 < i2 \\<or> i1 = i2 \\<and> t1 < t2 \\<or> i1 = i2 \\<and> t1 = t2 \\<and> e1 < e2)\\<close>\n  unfolding less_node_def by simp\n\nlemma less_eq_node_simp[simp]:\n  \\<open>(N i1 t1 e1) \\<le> (N i2 t2 e2) \\<longleftrightarrow>\n    (i1 < i2 \\<or> i1 = i2 \\<and> t1 < t2 \\<or> i1 = i2 \\<and> t1 = t2 \\<and> e1 \\<le> e2)\\<close>\n  unfolding less_eq_node_def by simp\n\nsubsection \\<open>Binary Decision Diagram\\<close>\n\ntext \\<open>A BDD is then either immediately a leaf, thereby representing a constant function. Otherwise,\n      it a (non-empty) stream of nodes, where the first node is to be interpreted as the root.\\<close>\n\ndatatype 'l bdd = Constant \\<open>bool\\<close> | Nodes \\<open>'l node list\\<close>\n\ntext \\<open>All algorithms rely on the nodes in the Binary Decision Diagram are well-formed in some way.\n      Specifically, we need them to\n\n      (a) be 'closed', i.e. every node mentioned actually exists,\n      (b) be sorted\n      (c) the levels are always (strictly) increasing, i.e. a node may not mention any other node on\n          the same level or above.\n      (d) the node list is non-empty\n\n      TODO: (e) Every node mentioned is transitively reachable from the root?\\<close>\n\nfun closed :: \\<open>'l node list \\<Rightarrow> bool\\<close> where\n  \\<open>closed []             = True\\<close>\n| \\<open>closed (N i t e # ns) = (closed ns\n                          \\<and> (case t of Leaf b \\<Rightarrow> True | Node l_uid \\<Rightarrow> \\<exists>n \\<in> set ns . uid n = l_uid)\n                          \\<and> (case e of Leaf b \\<Rightarrow> True | Node h_uid \\<Rightarrow> \\<exists>n \\<in> set ns . uid n = h_uid))\\<close>\n\ndefinition\n  \"ptr_lb i \\<equiv> \\<lambda>Node n \\<Rightarrow> i < label n | _ \\<Rightarrow> True\"\n\nfun inc_labels :: \\<open>('l::linorder) node list \\<Rightarrow> bool\\<close> where\n  \\<open>inc_labels []             \\<longleftrightarrow> True\\<close>\n| \\<open>inc_labels (N i t e # ns) \\<longleftrightarrow> inc_labels ns \\<and> ptr_lb (label i) t \\<and> ptr_lb (label i) e\\<close>\n\ndefinition\n  \"well_formed_nl ns \\<equiv> closed ns \\<and> inc_labels ns \\<and> sorted ns\"\n\nlemma closed_if_well_formed_nl[intro,simp]:\n  \"closed ns\" if \"well_formed_nl ns\"\n  using that unfolding well_formed_nl_def ..\n\nlemma inc_labels_if_well_formed_nl[intro,simp]:\n  \"inc_labels ns\" if \"well_formed_nl ns\"\n  using that unfolding well_formed_nl_def by (elim conjE)\n\nlemma sorted_if_well_formed_nl[intro,simp]:\n  \"sorted ns\" if \"well_formed_nl ns\"\n  using that unfolding well_formed_nl_def by (elim conjE)\n\nfun well_formed :: \\<open>('l::linorder) bdd \\<Rightarrow> bool\\<close> where\n  \\<open>well_formed (Constant _) = True\\<close>\n| \\<open>well_formed (Nodes [])   = False\\<close>\n| \\<open>well_formed (Nodes ns)   = well_formed_nl ns\\<close>\n\nlemma well_formed_nl_ConsD[intro?]:\n  \\<open>well_formed_nl ns\\<close> if \\<open>well_formed_nl (n # ns)\\<close>\n  using that unfolding well_formed_nl_def by (cases n, simp)\n\nlemma high_lb:\n  \"ptr_lb (label (uid n)) (high n)\" if \"inc_labels (n # ns)\"\n  using that by (cases n; simp)\n\nlemma low_lb:\n  \"ptr_lb (label (uid n)) (low n)\" if \"inc_labels (n # ns)\"\n  using that by (cases n; simp)\n\nlemma ptr_lb_trans:\n  \"ptr_lb l n\" if \"ptr_lb k n\" \"(l :: 'a :: order) \\<le> k\"\n  using that unfolding ptr_lb_def by (auto split: ptr.splits)\n\ntext \\<open>Finally we have here a few ease-of-life lemmas for later proofs.\\<close>\n\nlemma nl_induct[case_names Nil Cons]:\n  fixes P :: \"'a node list \\<Rightarrow> bool\"\n    and ns :: \"'a node list\"\n  assumes \"P []\"\n    and \"\\<And>i t e ns. P ns \\<Longrightarrow> P (N i t e # ns)\"\n  shows \"P ns\"\n  using assms by (rule closed.induct)\n\nfun bdd_cases where\n  Const: \"bdd_cases (Constant b) = undefined\"\n| Empty: \"bdd_cases (Nodes [])   = undefined\"\n| Nodes: \"bdd_cases (Nodes (N i t e # ns)) = undefined\"\n\nlemma bdd_cases:\n  fixes bdd :: \"'c bdd\"\n  obtains \n      (Const) b :: \"bool\" where \"bdd = Constant b\"\n    | (Empty) \"bdd = Nodes []\"\n    | (Nodes) i :: \"'c uid\" and t :: \"'c ptr\" and e :: \"'c ptr\" and ns :: \"'c node list\"\n    where \"bdd = Nodes (N i t e # ns)\"\n  by (rule bdd_cases.cases)\n\nsubsection \\<open>Assignment\\<close>\n\ntext \\<open>For assignments we are going to reuse the definition from @{cite Michaelis2016} of a function\n      from the set of labels to the Boolean values they were assigned.\n\n      While this is not (yet) reflective of the definition in Adiar it is planned to implement it\n      exactly like this (cf. Issue #147 on 'github.com/SSoelvsten/adiar/').\\<close>\n\ntype_synonym 'l assignment = \\<open>'l \\<Rightarrow> bool\\<close>\n\nend", "meta": {"author": "SSoelvsten", "repo": "cadiar", "sha": "d4eaf2e5a88f9f49102a6b97a9c649bdd7e8fd87", "save_path": "github-repos/isabelle/SSoelvsten-cadiar", "path": "github-repos/isabelle/SSoelvsten-cadiar/cadiar-d4eaf2e5a88f9f49102a6b97a9c649bdd7e8fd87/cadiar/Data.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7710283386036499}}
{"text": "(*  Title:      HOL/HOLCF/Porder.thy\n    Author:     Franz Regensburger and Brian Huffman\n*)\n\nsection {* Partial orders *}\n\ntheory Porder\nimports Main\nbegin\n\nsubsection {* Type class for partial orders *}\n\nclass below =\n  fixes below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation\n  below (infix \"<<\" 50)\n\nnotation (xsymbols)\n  below (infix \"\\<sqsubseteq>\" 50)\n\nabbreviation\n  not_below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"~<<\" 50)\n  where \"not_below x y \\<equiv> \\<not> below x y\"\n\nnotation (xsymbols)\n  not_below (infix \"\\<notsqsubseteq>\" 50)\n\nlemma below_eq_trans: \"\\<lbrakk>a \\<sqsubseteq> b; b = c\\<rbrakk> \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule subst)\n\nlemma eq_below_trans: \"\\<lbrakk>a = b; b \\<sqsubseteq> c\\<rbrakk> \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule ssubst)\n\nend\n\nclass po = below +\n  assumes below_refl [iff]: \"x \\<sqsubseteq> x\"\n  assumes below_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  assumes below_antisym: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma eq_imp_below: \"x = y \\<Longrightarrow> x \\<sqsubseteq> y\"\n  by simp\n\nlemma box_below: \"a \\<sqsubseteq> b \\<Longrightarrow> c \\<sqsubseteq> a \\<Longrightarrow> b \\<sqsubseteq> d \\<Longrightarrow> c \\<sqsubseteq> d\"\n  by (rule below_trans [OF below_trans])\n\nlemma po_eq_conv: \"x = y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\n  by (fast intro!: below_antisym)\n\nlemma rev_below_trans: \"y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> y \\<Longrightarrow> x \\<sqsubseteq> z\"\n  by (rule below_trans)\n\nlemma not_below2not_eq: \"x \\<notsqsubseteq> y \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nend\n\nlemmas HOLCF_trans_rules [trans] =\n  below_trans\n  below_antisym\n  below_eq_trans\n  eq_below_trans\n\ncontext po\nbegin\n\nsubsection {* Upper bounds *}\n\ndefinition is_ub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<|\" 55) where\n  \"S <| x \\<longleftrightarrow> (\\<forall>y\\<in>S. y \\<sqsubseteq> x)\"\n\nlemma is_ubI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> x \\<sqsubseteq> u) \\<Longrightarrow> S <| u\"\n  by (simp add: is_ub_def)\n\nlemma is_ubD: \"\\<lbrakk>S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  by (simp add: is_ub_def)\n\nlemma ub_imageI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<sqsubseteq> u) \\<Longrightarrow> (\\<lambda>x. f x) ` S <| u\"\n  unfolding is_ub_def by fast\n\nlemma ub_imageD: \"\\<lbrakk>f ` S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq> u\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeI: \"(\\<And>i. S i \\<sqsubseteq> x) \\<Longrightarrow> range S <| x\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeD: \"range S <| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_empty [simp]: \"{} <| u\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_insert [simp]: \"(insert x A) <| y = (x \\<sqsubseteq> y \\<and> A <| y)\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_upward: \"\\<lbrakk>S <| x; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> S <| y\"\n  unfolding is_ub_def by (fast intro: below_trans)\n\nsubsection {* Least upper bounds *}\n\ndefinition is_lub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<<|\" 55) where\n  \"S <<| x \\<longleftrightarrow> S <| x \\<and> (\\<forall>u. S <| u \\<longrightarrow> x \\<sqsubseteq> u)\"\n\ndefinition lub :: \"'a set \\<Rightarrow> 'a\" where\n  \"lub S = (THE x. S <<| x)\"\n\nend\n\nsyntax\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3LUB _:_./ _)\" [0,0, 10] 10)\n\nsyntax (xsymbols)\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3\\<Squnion>_\\<in>_./ _)\" [0,0, 10] 10)\n\ntranslations\n  \"LUB x:A. t\" == \"CONST lub ((%x. t) ` A)\"\n\ncontext po\nbegin\n\nabbreviation\n  Lub  (binder \"LUB \" 10) where\n  \"LUB n. t n == lub (range t)\"\n\nnotation (xsymbols)\n  Lub  (binder \"\\<Squnion> \" 10)\n\ntext {* access to some definition as inference rule *}\n\nlemma is_lubD1: \"S <<| x \\<Longrightarrow> S <| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lubD2: \"\\<lbrakk>S <<| x; S <| u\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  unfolding is_lub_def by fast\n\nlemma is_lubI: \"\\<lbrakk>S <| x; \\<And>u. S <| u \\<Longrightarrow> x \\<sqsubseteq> u\\<rbrakk> \\<Longrightarrow> S <<| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lub_below_iff: \"S <<| x \\<Longrightarrow> x \\<sqsubseteq> u \\<longleftrightarrow> S <| u\"\n  unfolding is_lub_def is_ub_def by (metis below_trans)\n\ntext {* lubs are unique *}\n\nlemma is_lub_unique: \"\\<lbrakk>S <<| x; S <<| y\\<rbrakk> \\<Longrightarrow> x = y\"\n  unfolding is_lub_def is_ub_def by (blast intro: below_antisym)\n\ntext {* technical lemmas about @{term lub} and @{term is_lub} *}\n\nlemma is_lub_lub: \"M <<| x \\<Longrightarrow> M <<| lub M\"\n  unfolding lub_def by (rule theI [OF _ is_lub_unique])\n\nlemma lub_eqI: \"M <<| l \\<Longrightarrow> lub M = l\"\n  by (rule is_lub_unique [OF is_lub_lub])\n\nlemma is_lub_singleton: \"{x} <<| x\"\n  by (simp add: is_lub_def)\n\nlemma lub_singleton [simp]: \"lub {x} = x\"\n  by (rule is_lub_singleton [THEN lub_eqI])\n\nlemma is_lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> {x, y} <<| y\"\n  by (simp add: is_lub_def)\n\nlemma lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> lub {x, y} = y\"\n  by (rule is_lub_bin [THEN lub_eqI])\n\nlemma is_lub_maximal: \"\\<lbrakk>S <| x; x \\<in> S\\<rbrakk> \\<Longrightarrow> S <<| x\"\n  by (erule is_lubI, erule (1) is_ubD)\n\nlemma lub_maximal: \"\\<lbrakk>S <| x; x \\<in> S\\<rbrakk> \\<Longrightarrow> lub S = x\"\n  by (rule is_lub_maximal [THEN lub_eqI])\n\nsubsection {* Countable chains *}\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  -- {* Here we use countable chains and I prefer to code them as functions! *}\n  \"chain Y = (\\<forall>i. Y i \\<sqsubseteq> Y (Suc i))\"\n\nlemma chainI: \"(\\<And>i. Y i \\<sqsubseteq> Y (Suc i)) \\<Longrightarrow> chain Y\"\n  unfolding chain_def by fast\n\nlemma chainE: \"chain Y \\<Longrightarrow> Y i \\<sqsubseteq> Y (Suc i)\"\n  unfolding chain_def by fast\n\ntext {* chains are monotone functions *}\n\nlemma chain_mono_less: \"\\<lbrakk>chain Y; i < j\\<rbrakk> \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (erule less_Suc_induct, erule chainE, erule below_trans)\n\nlemma chain_mono: \"\\<lbrakk>chain Y; i \\<le> j\\<rbrakk> \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (cases \"i = j\", simp, simp add: chain_mono_less)\n\nlemma chain_shift: \"chain Y \\<Longrightarrow> chain (\\<lambda>i. Y (i + j))\"\n  by (rule chainI, simp, erule chainE)\n\ntext {* technical lemmas about (least) upper bounds of chains *}\n\nlemma is_lub_rangeD1: \"range S <<| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  by (rule is_lubD1 [THEN ub_rangeD])\n\nlemma is_ub_range_shift:\n  \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <| x = range S <| x\"\napply (rule iffI)\napply (rule ub_rangeI)\napply (rule_tac y=\"S (i + j)\" in below_trans)\napply (erule chain_mono)\napply (rule le_add1)\napply (erule ub_rangeD)\napply (rule ub_rangeI)\napply (erule ub_rangeD)\ndone\n\nlemma is_lub_range_shift:\n  \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <<| x = range S <<| x\"\n  by (simp add: is_lub_def is_ub_range_shift)\n\ntext {* the lub of a constant chain is the constant *}\n\nlemma chain_const [simp]: \"chain (\\<lambda>i. c)\"\n  by (simp add: chainI)\n\nlemma is_lub_const: \"range (\\<lambda>x. c) <<| c\"\nby (blast dest: ub_rangeD intro: is_lubI ub_rangeI)\n\nlemma lub_const [simp]: \"(\\<Squnion>i. c) = c\"\n  by (rule is_lub_const [THEN lub_eqI])\n\nsubsection {* Finite chains *}\n\ndefinition max_in_chain :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  -- {* finite chains, needed for monotony of continuous functions *}\n  \"max_in_chain i C \\<longleftrightarrow> (\\<forall>j. i \\<le> j \\<longrightarrow> C i = C j)\"\n\ndefinition finite_chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"finite_chain C = (chain C \\<and> (\\<exists>i. max_in_chain i C))\"\n\ntext {* results about finite chains *}\n\nlemma max_in_chainI: \"(\\<And>j. i \\<le> j \\<Longrightarrow> Y i = Y j) \\<Longrightarrow> max_in_chain i Y\"\n  unfolding max_in_chain_def by fast\n\nlemma max_in_chainD: \"\\<lbrakk>max_in_chain i Y; i \\<le> j\\<rbrakk> \\<Longrightarrow> Y i = Y j\"\n  unfolding max_in_chain_def by fast\n\nlemma finite_chainI:\n  \"\\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> finite_chain C\"\n  unfolding finite_chain_def by fast\n\nlemma finite_chainE:\n  \"\\<lbrakk>finite_chain C; \\<And>i. \\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  unfolding finite_chain_def by fast\n\nlemma lub_finch1: \"\\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> range C <<| C i\"\napply (rule is_lubI)\napply (rule ub_rangeI, rename_tac j)\napply (rule_tac x=i and y=j in linorder_le_cases)\napply (drule (1) max_in_chainD, simp)\napply (erule (1) chain_mono)\napply (erule ub_rangeD)\ndone\n\nlemma lub_finch2:\n  \"finite_chain C \\<Longrightarrow> range C <<| C (LEAST i. max_in_chain i C)\"\napply (erule finite_chainE)\napply (erule LeastI2 [where Q=\"\\<lambda>i. range C <<| C i\"])\napply (erule (1) lub_finch1)\ndone\n\nlemma finch_imp_finite_range: \"finite_chain Y \\<Longrightarrow> finite (range Y)\"\n apply (erule finite_chainE)\n apply (rule_tac B=\"Y ` {..i}\" in finite_subset)\n  apply (rule subsetI)\n  apply (erule rangeE, rename_tac j)\n  apply (rule_tac x=i and y=j in linorder_le_cases)\n   apply (subgoal_tac \"Y j = Y i\", simp)\n   apply (simp add: max_in_chain_def)\n  apply simp\n apply simp\ndone\n\nlemma finite_range_has_max:\n  fixes f :: \"nat \\<Rightarrow> 'a\" and r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes mono: \"\\<And>i j. i \\<le> j \\<Longrightarrow> r (f i) (f j)\"\n  assumes finite_range: \"finite (range f)\"\n  shows \"\\<exists>k. \\<forall>i. r (f i) (f k)\"\nproof (intro exI allI)\n  fix i :: nat\n  let ?j = \"LEAST k. f k = f i\"\n  let ?k = \"Max ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n  have \"?j \\<le> ?k\"\n  proof (rule Max_ge)\n    show \"finite ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n      using finite_range by (rule finite_imageI)\n    show \"?j \\<in> (\\<lambda>x. LEAST k. f k = x) ` range f\"\n      by (intro imageI rangeI)\n  qed\n  hence \"r (f ?j) (f ?k)\"\n    by (rule mono)\n  also have \"f ?j = f i\"\n    by (rule LeastI, rule refl)\n  finally show \"r (f i) (f ?k)\" .\nqed\n\nlemma finite_range_imp_finch:\n  \"\\<lbrakk>chain Y; finite (range Y)\\<rbrakk> \\<Longrightarrow> finite_chain Y\"\n apply (subgoal_tac \"\\<exists>k. \\<forall>i. Y i \\<sqsubseteq> Y k\")\n  apply (erule exE)\n  apply (rule finite_chainI, assumption)\n  apply (rule max_in_chainI)\n  apply (rule below_antisym)\n   apply (erule (1) chain_mono)\n  apply (erule spec)\n apply (rule finite_range_has_max)\n  apply (erule (1) chain_mono)\n apply assumption\ndone\n\nlemma bin_chain: \"x \\<sqsubseteq> y \\<Longrightarrow> chain (\\<lambda>i. if i=0 then x else y)\"\n  by (rule chainI, simp)\n\nlemma bin_chainmax:\n  \"x \\<sqsubseteq> y \\<Longrightarrow> max_in_chain (Suc 0) (\\<lambda>i. if i=0 then x else y)\"\n  unfolding max_in_chain_def by simp\n\nlemma is_lub_bin_chain:\n  \"x \\<sqsubseteq> y \\<Longrightarrow> range (\\<lambda>i::nat. if i=0 then x else y) <<| y\"\napply (frule bin_chain)\napply (drule bin_chainmax)\napply (drule (1) lub_finch1)\napply simp\ndone\n\ntext {* the maximal element in a chain is its lub *}\n\nlemma lub_chain_maxelem: \"\\<lbrakk>Y i = c; \\<forall>i. Y i \\<sqsubseteq> c\\<rbrakk> \\<Longrightarrow> lub (range Y) = c\"\n  by (blast dest: ub_rangeD intro: lub_eqI is_lubI ub_rangeI)\n\nend\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/HOLCF/Porder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314617436728, "lm_q2_score": 0.8705972600147106, "lm_q1q2_score": 0.7710283239768645}}
{"text": "theory BDD\n    imports\nMain begin\n\ntext \\<open>\nBoolean functions (in finitely many variables) can be represented by so-called\n{\\it binary decision diagrams} (BDDs), which are given by the following data\ntype:\n\\<close>\n\ndatatype bdd = Leaf bool | Branch bdd bdd\n\ntext \\<open>\nA constructor @{term \"Branch b1 b2\"} that is $i$ steps away from the root of\nthe tree corresponds to a case distinction based on the value of the variable\n$v_i$.  If the value of $v_i$ is @{term \"False\"}, the left subtree @{term \"b1\"}\nis evaluated, otherwise the right subtree @{term \"b2\"} is evaluated.  The\nfollowing figure shows a Boolean function and the corresponding BDD.\n\\begin{center}\n\\begin{minipage}{8cm}\n\\begin{tabular}{|c|c|c|c|} \\hline\n$v_0$ & $v_1$ & $v_2$ & $f(v_0,v_1,v_2)$ \\\\ \\hline\n@{term \"False\"} & @{term \"False\"} & *               & @{term \"True\"} \\\\\n@{term \"False\"} & @{term \"True\"}  & *               & @{term \"False\"} \\\\\n@{term \"True\"}  & @{term \"False\"} & *               & @{term \"False\"} \\\\\n@{term \"True\"}  & @{term \"True\"}  & @{term \"False\"} & @{term \"False\"} \\\\\n@{term \"True\"}  & @{term \"True\"}  & @{term \"True\"}  & @{term \"True\"} \\\\ \\hline\n\\end{tabular}\n\\end{minipage}\n\\begin{minipage}{7cm}\n\\begin{picture}(0,0)%\n\\includegraphics[scale=0.5]{bdd}%\n\\end{picture}%\n\\setlength{\\unitlength}{2072sp}%\n\\begin{picture}(6457,3165)(1329,-4471)\n\\put(1351,-3571){\\makebox(0,0)[b]{@{term \"True\"}}}%\n\\put(3151,-3571){\\makebox(0,0)[b]{@{term \"False\"}}}%\n\\put(4951,-3571){\\makebox(0,0)[b]{@{term \"False\"}}}%\n\\put(5851,-4471){\\makebox(0,0)[b]{@{term \"False\"}}}%\n\\put(7651,-4471){\\makebox(0,0)[b]{@{term \"True\"}}}%\n\\put(7786,-3301){\\makebox(0,0)[lb]{$v_2$}}%\n\\put(7786,-2401){\\makebox(0,0)[lb]{$v_1$}}%\n\\put(7786,-1501){\\makebox(0,0)[lb]{$v_0$}}%\n\\end{picture}\n\\end{minipage}\n\\end{center}\n\n{\\bf Exercise 1:} Define a function\n\\<close>\n\nprimrec eval :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> bdd \\<Rightarrow> bool\"\n  where\n\"eval _ _ (Leaf b) = b\" |\n\"eval val i (Branch b1 b2) = (if (val i)\n                             then (eval val (Suc i) b2)\n                             else (eval val (Suc i) b1))\"\n\ntext \\<open>\nthat evaluates a BDD under a given variable assignment, beginning at a variable\nwith a given index.\n\\<close>\n\n\ntext \\<open>\n{\\bf Exercise 2:} Define two functions\n\\<close>\n\n\nprimrec  bdd_unop :: \"(bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  where\n\"bdd_unop f (Leaf b) = Leaf (f b)\" |\n\"bdd_unop f (Branch b1 b2) = Branch (bdd_unop f b1) (bdd_unop f b2)\"\n\nlemma bdd_unop_correct:\"eval val i (bdd_unop f b) = f (eval val i b)\"\n  apply (induction b arbitrary: i) by auto\n\nprimrec bdd_binop :: \"(bool \\<Rightarrow> bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  where\n\"bdd_binop f (Leaf x) b = bdd_unop (f x) b\" |\n\"bdd_binop f (Branch b1\\<^sub>1 b2\\<^sub>1) b =\n   (case b of\n   Leaf x          \\<Rightarrow> Branch (bdd_binop f b1\\<^sub>1 b) (bdd_binop f b2\\<^sub>1 b) |\n   Branch b1\\<^sub>2 b2\\<^sub>2  \\<Rightarrow> Branch (bdd_binop f b1\\<^sub>1 b1\\<^sub>2) (bdd_binop f b2\\<^sub>1 b2\\<^sub>2))\"\n\nlemma bdd_binop_correct:\"eval val i (bdd_binop f b1 b2) = f (eval val i b1) (eval val i b2)\"\n  apply (induction b1 arbitrary: i b2)\n  by (auto simp add: bdd_unop_correct split: bdd.split)\n\ntext \\<open>\nfor the application of unary and binary operators to BDDs, and prove their\ncorrectness.\n\\<close>\n\n\ntext \\<open>\nNow use @{term \"bdd_unop\"} and @{term \"bdd_binop\"} to define\n\\<close>\n\ndefinition bdd_and :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  where\n\"bdd_and b1 b2 = bdd_binop (\\<and>) b1 b2\"\n\ndefinition bdd_or :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  where\n\"bdd_or b1 b2 = bdd_binop (\\<or>) b1 b2\"\n\ndefinition  bdd_not :: \"bdd \\<Rightarrow> bdd\"\n  where\n\"bdd_not b = bdd_unop (\\<lambda>x. \\<not>x) b\"\n\ndefinition xor:: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixl \"\\<oplus>\" 60)\n  where\n\"xor a b = ((a \\<and> \\<not>b) \\<or> (\\<not>a \\<and> b))\"\n\ndefinition bdd_xor :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\"\n  where\n\"bdd_xor b1 b2 = bdd_binop (\\<oplus>) b1 b2\"\n\nlemma bdd_and_correct:\"eval val i (bdd_and b1 b2) = ((eval val i b1) \\<and> (eval val i b2))\"\n  by (simp add: bdd_and_def bdd_binop_correct)\n\nlemma bdd_or_correct:\"eval val i (bdd_or b1 b2) = ((eval val i b1) \\<or> (eval val i b2))\"\n  by (simp add: bdd_or_def bdd_binop_correct)\n\nlemma bdd_not_correct:\"eval val i (bdd_not b) = (\\<not>(eval val i b))\"\n  by (simp add: bdd_not_def bdd_unop_correct)\n\nlemma bdd_xor_correct:\"eval val i (bdd_xor b1 b2) = (eval val i b1) \\<oplus> (eval val i b2)\"\n  by (simp add: bdd_xor_def bdd_binop_correct)\n\ntext \\<open>\nand show correctness.\n\\<close>\n\n\ntext \\<open>\nFinally, define a function\n\\<close>\n\nprimrec bdd_var :: \"nat \\<Rightarrow> bdd\"\n  where\n\"bdd_var 0 = (Branch (Leaf False) (Leaf True))\" |\n\"bdd_var (Suc n) = (Branch (bdd_var n) (bdd_var n))\"\n\ntext \\<open>\nto create a BDD that evaluates to @{term \"True\"} if and only if the variable\nwith the given index evaluates to @{term \"True\"}.  Again prove a suitable\ncorrectness theorem.\n\n{\\bf Hint:} If a lemma cannot be proven by induction because in the inductive\nstep a different value is used for a (non-induction) variable than in the\ninduction hypothesis, it may be necessary to strengthen the lemma by universal\nquantification over that variable (cf.\\ Section 3.2 in the Tutorial on\nIsabelle/HOL).\n\\<close>\n\nlemma bdd_var_correct:\"eval val j (bdd_var i) = val (i + j)\"\n  apply (induction i arbitrary: j) by auto\n\ntext_raw \\<open> \\begin{minipage}[t]{0.45\\textwidth} \\<close>\n \ntext\\<open>\n{\\bf Example:} instead of\n\\<close>\n\nlemma \"P (b::bdd) x\" \napply (induct b) (*<*) oops (*>*)\n\ntext_raw \\<open> \\end{minipage} \\<close>\ntext_raw \\<open> \\begin{minipage}[t]{0.45\\textwidth} \\<close>   \n\ntext \\<open> Strengthening: \\<close>\n\nlemma \"\\<forall>x. P (b::bdd) x\"\napply (induct b) (*<*) oops (*>*)  \n\ntext_raw \\<open> \\end{minipage} \\\\[0.5cm]\\<close> \n\n\ntext \\<open>\n{\\bf Exercise 3:} Recall the following data type of propositional formulae\n(cf.\\ the exercise on ``Representation of Propositional Formulae by\nPolynomials'')\n\\<close>\n\ndatatype form = T | Var nat | And form form | Xor form form\n\ntext \\<open>\ntogether with the evaluation function @{text \"evalf\"}:\n\\<close>\n\nprimrec evalf :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\" where\n  \"evalf e T = True\"\n| \"evalf e (Var i) = e i\"\n| \"evalf e (And f1 f2) = (evalf e f1 \\<and> evalf e f2)\"\n| \"evalf e (Xor f1 f2) = xor (evalf e f1) (evalf e f2)\"\n\ntext \\<open>\nDefine a function\n\\<close>\n\nprimrec mk_bdd :: \"form \\<Rightarrow> bdd\"\n  where\n\"mk_bdd T = (Leaf True)\" |\n\"mk_bdd (Var n) = bdd_var n\" |\n\"mk_bdd (And f1 f2) = bdd_and (mk_bdd f1) (mk_bdd f2)\" |\n\"mk_bdd (Xor f1 f2) = bdd_xor (mk_bdd f1) (mk_bdd f2)\"\n\ntext \\<open>\nthat transforms a propositional formula of type @{typ \"form\"} into a BDD.\nProve the correctness theorem\n\\<close>\n\ntheorem mk_bdd_correct: \"eval e 0 (mk_bdd f) = evalf e f\"\n  apply (induction f arbitrary: e)\n    by (auto simp add: bdd_var_correct bdd_and_correct bdd_xor_correct)\n\n\n(*<*) end (*>*)\n", "meta": {"author": "tomssem", "repo": "isabelle_exercises", "sha": "000b8edcb2050d4931e3177e9a339101d777dfe7", "save_path": "github-repos/isabelle/tomssem-isabelle_exercises", "path": "github-repos/isabelle/tomssem-isabelle_exercises/isabelle_exercises-000b8edcb2050d4931e3177e9a339101d777dfe7/tree/BDD.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7708953120265803}}
{"text": "theory Support \n  imports \"../Nominal\" \nbegin\n\ntext {* \n  An example showing that in general\n\n  x\\<sharp>(A \\<union> B) does not imply  x\\<sharp>A and  x\\<sharp>B\n\n  For this we set A to the set of even atoms and B to \n  the set of odd atoms. Then A \\<union> B, that is the set of \n  all atoms, has empty support. The sets A, respectively B, \n  however have the set of all atoms as their support. \n*}\n\natom_decl atom\n\ntext {* The set of even atoms. *}\nabbreviation\n  EVEN :: \"atom set\"\nwhere\n  \"EVEN \\<equiv> {atom n | n. \\<exists>i. n=2*i}\"\n\ntext {* The set of odd atoms: *}\nabbreviation  \n  ODD :: \"atom set\"\nwhere\n  \"ODD \\<equiv> {atom n | n. \\<exists>i. n=2*i+1}\"\n\ntext {* An atom is either even or odd. *}\nlemma even_or_odd:\n  fixes n :: nat\n  shows \"\\<exists>i. (n = 2*i) \\<or> (n=2*i+1)\"\n  by (induct n) (presburger)+\n\ntext {* \n  The union of even and odd atoms is the set of all atoms. \n  (Unfortunately I do not know a simpler proof of this fact.) *}\nlemma EVEN_union_ODD:\n  shows \"EVEN \\<union> ODD = UNIV\"\n  using even_or_odd\nproof -\n  have \"EVEN \\<union> ODD = (\\<lambda>n. atom n) ` {n. \\<exists>i. n = 2*i} \\<union> (\\<lambda>n. atom n) ` {n. \\<exists>i. n = 2*i+1}\" by auto\n  also have \"\\<dots> = (\\<lambda>n. atom n) ` ({n. \\<exists>i. n = 2*i} \\<union> {n. \\<exists>i. n = 2*i+1})\" by auto\n  also have \"\\<dots> = (\\<lambda>n. atom n) ` ({n. \\<exists>i. n = 2*i \\<or> n = 2*i+1})\" by auto\n  also have \"\\<dots> = (\\<lambda>n. atom n) ` (UNIV::nat set)\" using even_or_odd by auto\n  also have \"\\<dots> = (UNIV::atom set)\" using atom.exhaust\n    by (auto simp add: surj_def)\n  finally show \"EVEN \\<union> ODD = UNIV\" by simp\nqed\n\ntext {* The sets of even and odd atoms are disjunct. *}\nlemma EVEN_intersect_ODD:\n  shows \"EVEN \\<inter> ODD = {}\"\n  using even_or_odd\n  by (auto) (presburger)\n\ntext {* \n  The preceeding two lemmas help us to prove \n  the following two useful equalities: *}\n\nlemma UNIV_subtract:\n  shows \"UNIV - EVEN = ODD\"\n  and   \"UNIV - ODD  = EVEN\"\n  using EVEN_union_ODD EVEN_intersect_ODD\n  by (blast)+\n\ntext {* The sets EVEN and ODD are infinite. *}\nlemma EVEN_ODD_infinite:\n  shows \"infinite EVEN\"\n  and   \"infinite ODD\"\nunfolding infinite_iff_countable_subset\nproof -\n  let ?f = \"\\<lambda>n. atom (2*n)\"\n  have \"inj ?f \\<and> range ?f \\<subseteq> EVEN\" by (auto simp add: inj_on_def)\n  then show \"\\<exists>f::nat\\<Rightarrow>atom. inj f \\<and> range f \\<subseteq> EVEN\" by (rule_tac exI)\nnext\n  let ?f = \"\\<lambda>n. atom (2*n+1)\"\n  have \"inj ?f \\<and> range ?f \\<subseteq> ODD\" by (auto simp add: inj_on_def)\n  then show \"\\<exists>f::nat\\<Rightarrow>atom. inj f \\<and> range f \\<subseteq> ODD\" by (rule_tac exI)\nqed\n\ntext {* \n  A general fact about a set S of atoms that is both infinite and \n  coinfinite. Then S has all atoms as its support. Steve Zdancewic \n  helped with proving this fact. *}\n\nlemma supp_infinite_coinfinite:\n  fixes S::\"atom set\"\n  assumes asm1: \"infinite S\"\n  and     asm2: \"infinite (UNIV-S)\"\n  shows \"(supp S) = (UNIV::atom set)\"\nproof -\n  have \"\\<forall>(x::atom). x\\<in>(supp S)\"\n  proof\n    fix x::\"atom\"\n    show \"x\\<in>(supp S)\"\n    proof (cases \"x\\<in>S\")\n      case True\n      have \"x\\<in>S\" by fact\n      hence \"\\<forall>b\\<in>(UNIV-S). [(x,b)]\\<bullet>S\\<noteq>S\" by (auto simp add: perm_set_def calc_atm)\n      with asm2 have \"infinite {b\\<in>(UNIV-S). [(x,b)]\\<bullet>S\\<noteq>S}\" by (rule infinite_Collection)\n      hence \"infinite {b. [(x,b)]\\<bullet>S\\<noteq>S}\" by (rule_tac infinite_super, auto)\n      then show \"x\\<in>(supp S)\" by (simp add: supp_def)\n    next\n      case False\n      have \"x\\<notin>S\" by fact\n      hence \"\\<forall>b\\<in>S. [(x,b)]\\<bullet>S\\<noteq>S\" by (auto simp add: perm_set_def calc_atm)\n      with asm1 have \"infinite {b\\<in>S. [(x,b)]\\<bullet>S\\<noteq>S}\" by (rule infinite_Collection)\n      hence \"infinite {b. [(x,b)]\\<bullet>S\\<noteq>S}\" by (rule_tac infinite_super, auto)\n      then show \"x\\<in>(supp S)\" by (simp add: supp_def)\n    qed\n  qed\n  then show \"(supp S) = (UNIV::atom set)\" by auto\nqed\n\ntext {* As a corollary we get that EVEN and ODD have infinite support. *}\nlemma EVEN_ODD_supp:\n  shows \"supp EVEN = (UNIV::atom set)\"\n  and   \"supp ODD  = (UNIV::atom set)\"\n  using supp_infinite_coinfinite UNIV_subtract EVEN_ODD_infinite\n  by simp_all\n\ntext {* \n  The set of all atoms has empty support, since any swappings leaves \n  this set unchanged. *}\n\nlemma UNIV_supp:\n  shows \"supp (UNIV::atom set) = ({}::atom set)\"\nproof -\n  have \"\\<forall>(x::atom) (y::atom). [(x,y)]\\<bullet>UNIV = (UNIV::atom set)\"\n    by (auto simp add: perm_set_def calc_atm)\n  then show \"supp (UNIV::atom set) = ({}::atom set)\" by (simp add: supp_def)\nqed\n\ntext {* Putting everything together. *}\ntheorem EVEN_ODD_freshness:\n  fixes x::\"atom\"\n  shows \"x\\<sharp>(EVEN \\<union> ODD)\"\n  and   \"\\<not>x\\<sharp>EVEN\"\n  and   \"\\<not>x\\<sharp>ODD\"\n  by (auto simp only: fresh_def EVEN_union_ODD EVEN_ODD_supp UNIV_supp)\n\ntext {* Moral: support is a sublte notion. *}\n\nend", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Nominal/Examples/Support.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8688267711434708, "lm_q1q2_score": 0.7708270999117033}}
{"text": "\nsection \\<open>Various examples for transfer procedure\\<close>\n\ntheory Transfer_Ex\nimports Main Transfer_Int_Nat\nbegin\n\nlemma ex1: \"(x::nat) + y = y + x\"\n  by auto\n\nlemma \"0 \\<le> (y::int) \\<Longrightarrow> 0 \\<le> (x::int) \\<Longrightarrow> x + y = y + x\"\n  by (fact ex1 [transferred])\n\n(* Using new transfer package *)\nlemma \"0 \\<le> (x::int) \\<Longrightarrow> 0 \\<le> (y::int) \\<Longrightarrow> x + y = y + x\"\n  by (fact ex1 [untransferred])\n\nlemma ex2: \"(a::nat) div b * b + a mod b = a\"\n  by (rule div_mult_mod_eq)\n\nlemma \"0 \\<le> (b::int) \\<Longrightarrow> 0 \\<le> (a::int) \\<Longrightarrow> a div b * b + a mod b = a\"\n  by (fact ex2 [transferred])\n\n(* Using new transfer package *)\nlemma \"0 \\<le> (a::int) \\<Longrightarrow> 0 \\<le> (b::int) \\<Longrightarrow> a div b * b + a mod b = a\"\n  by (fact ex2 [untransferred])\n\nlemma ex3: \"ALL (x::nat). ALL y. EX z. z >= x + y\"\n  by auto\n\nlemma \"\\<forall>x\\<ge>0::int. \\<forall>y\\<ge>0. \\<exists>z\\<ge>0. x + y \\<le> z\"\n  by (fact ex3 [transferred nat_int])\n\n(* Using new transfer package *)\nlemma \"\\<forall>x::int\\<in>{0..}. \\<forall>y\\<in>{0..}. \\<exists>z\\<in>{0..}. x + y \\<le> z\"\n  by (fact ex3 [untransferred])\n\nlemma ex4: \"(x::nat) >= y \\<Longrightarrow> (x - y) + y = x\"\n  by auto\n\nlemma \"0 \\<le> (x::int) \\<Longrightarrow> 0 \\<le> (y::int) \\<Longrightarrow> y \\<le> x \\<Longrightarrow> tsub x y + y = x\"\n  by (fact ex4 [transferred])\n\n(* Using new transfer package *)\nlemma \"0 \\<le> (y::int) \\<Longrightarrow> 0 \\<le> (x::int) \\<Longrightarrow> y \\<le> x \\<Longrightarrow> tsub x y + y = x\"\n  by (fact ex4 [untransferred])\n\nlemma ex5: \"(2::nat) * \\<Sum>{..n} = n * (n + 1)\"\n  by (induct n rule: nat_induct, auto)\n\nlemma \"0 \\<le> (n::int) \\<Longrightarrow> 2 * \\<Sum>{0..n} = n * (n + 1)\"\n  by (fact ex5 [transferred])\n\n(* Using new transfer package *)\nlemma \"0 \\<le> (n::int) \\<Longrightarrow> 2 * \\<Sum>{0..n} = n * (n + 1)\"\n  by (fact ex5 [untransferred])\n\nlemma \"0 \\<le> (n::nat) \\<Longrightarrow> 2 * \\<Sum>{0..n} = n * (n + 1)\"\n  by (fact ex5 [transferred, transferred])\n\n(* Using new transfer package *)\nlemma \"0 \\<le> (n::nat) \\<Longrightarrow> 2 * \\<Sum>{..n} = n * (n + 1)\"\n  by (fact ex5 [untransferred, Transfer.transferred])\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/ex/Transfer_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760039, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7708055785923806}}
{"text": "theory Exercises2_09\n  imports Main\nbegin\n\n(*---------------- Exercise 2.9----------------*)\n(* add function *)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 y = y\" |\n\"add (Suc x) y = Suc(add x y)\"\n\n(* tail recursive add function *)\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 y = y\" |\n\"itadd (Suc x) y = itadd x (Suc y)\"\n\nlemma suc_add : \"add x (Suc y) = add (Suc x) y\"\n  apply(induction x)\n   apply(auto)\n  done\n\ntheorem itadd_add : \"itadd x y = add x y\"\n  apply(induction x arbitrary: y)\n  apply(auto)\n   apply(simp add: suc_add)\n  done\n\n\n\nend", "meta": {"author": "rohitdureja", "repo": "isabelle-practice", "sha": "1cb45450b155d1516c0cf3ce6787452ae33712c1", "save_path": "github-repos/isabelle/rohitdureja-isabelle-practice", "path": "github-repos/isabelle/rohitdureja-isabelle-practice/isabelle-practice-1cb45450b155d1516c0cf3ce6787452ae33712c1/Exercises2_09.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7707195564810697}}
{"text": "theory Chapter2\n  imports Main\nbegin\n\n\n(* Exercise 2.1  *)\n\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(* Exercise 2.2  *)\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where \"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\nlemma add_assoc [simp] : \"add (add p q) r  = add p (add q r)\"\n  apply(induction p)\n   apply(auto)\n  done\n\nlemma add_02 [simp] : \"add m 0 = m\" apply(induction m)\napply(auto)\ndone\n\nlemma add_plus1 [simp] : \"Suc (add q p) = add q (Suc p)\"\n  apply(induction q)\n   apply(auto)\n  done\n\nlemma add_comm [simp] : \"add p q = add q p\"\n  apply(induction p)\n   apply(auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\"\n| \"double (Suc n) = 2 + (double n)\"\n\nlemma double_correct [simp] : \"double n = add n n\"\n  apply(induction n)\n   apply(auto)\n  done\n\n(* Exercise 2.3 *)\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count x Nil = 0\"\n| \"count x (Cons t ts) = 1 + (count x ts)\"\n\nlemma leq_count_length : \"count x xs \\<le> length xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n(* Exercise 2.4 *)\n\nfun snoc :: \" 'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc Nil x = [x]\"\n|\"snoc (Cons t ts) x = Cons t (snoc ts x)\"\n\nfun reverse :: \" 'a list \\<Rightarrow> 'a list\" where\n\"reverse Nil = Nil\"\n|\"reverse (Cons t ts) = snoc (reverse ts) t\"\n\nlemma app_assoc [simp]: \"(xs @ ys) @ zs = xs @ (ys @ zs)\" \n  apply(induction xs)\n  apply(auto)\n  done\n\nlemma snoc_add1 [simp] : \"snoc xs x = xs @ [x]\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma rev_app_distr [simp] : \"reverse (xs @ ys) = (reverse ys) @ reverse(xs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma reverse_correct : \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n(* Exercise 2.5 *)\n\nfun sum_upto  :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\"\n| \"sum_upto (Suc n) = (n + (sum_upto n)) + 1\"\n\nlemma sum_upto_correct : \"sum_upto n = n * (n + 1) div 2\"\n  apply(induction n)\n  apply(auto)\n  done\n\n(* Exercise 2.6 *)\n\ndatatype 'a tree = Tip | Node \" 'a tree\" 'a \" 'a tree\"\n\nfun contents :: \" 'a tree \\<Rightarrow> 'a list \" where\n\" contents Tip = Nil \"\n| \" contents (Node l a r) =  a # ((contents l) @ (contents r))\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\" sum_tree Tip = 0 \"\n| \" sum_tree (Node l a r) = a + (sum_tree l) + (sum_tree r)\"\n\nlemma sum_tree_correct : \"sum_tree t = sum_list(contents t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n(* Exercise 2.7 *)\n\ndatatype 'a tree2 = Tip2 'a | Node \" 'a tree2\" 'a \" 'a tree2\"\n\nfun mirror2 :: \" 'a tree2 \\<Rightarrow> 'a tree2 \" where\n \"mirror2 (Tip2 a) = Tip2 a\"\n| \"mirror2 (Node l a r) = Node (mirror2 r) a (mirror2 l)\"\n\nfun pre_order :: \" 'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order (Tip2 a) = [a]\"\n| \"pre_order (Node l a r) = a # ((pre_order l) @ (pre_order r))\"\n\nfun post_order :: \" 'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Tip2 a) = [a]\"\n| \"post_order (Node l a r) = (post_order l) @ (post_order r) @ [a] \"\n\nlemma tree2_orders_correct : \"pre_order(mirror2 t) = rev(post_order t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n(* Exercise 2.8 *)\n\nfun intersperse :: \" 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse a Nil = [a]\"\n| \"intersperse a (Cons x Nil) = [x]\"\n| \"intersperse a (Cons x xs) = [x, a] @ (intersperse a xs)\"\n\nlemma intersperse_correct : \" map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction a xs rule: intersperse.induct)\n    apply(auto)\n  done\n\n(* Exercise 2.9 *)\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n \"itadd 0 m  = m\"\n| \"itadd (Suc 0) m = Suc m\"\n| \"itadd (Suc n) m = itadd (Suc 0) (itadd n m)\"\n\nlemma add_suc0 : \"Suc m = add m (Suc 0)\"\n  apply(induction m)\n   apply(auto)\n  done\n\nlemma itadd_correct : \"itadd n m = add n m\"\n  apply(induction n m rule: itadd.induct)\n    apply(auto)\n  apply (rule add_suc0)\n  done\n\n(* Exercise 2.10 *)\n\ndatatype tree0 = Tip0 | Node0 \"tree0\" \"tree0\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip0 = 1\"\n| \"nodes (Node0 l r) = nodes l + nodes r + 1\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where \n\"explode 0 t = t\" \n|\"explode (Suc n) t = explode n (Node0 t t)\"\n\nlemma exploded_tree_size: \"nodes(explode n t) = (2^n)*(nodes t) + (2^n) - 1\"\napply(induct n arbitrary: t)\napply(auto simp add: algebra_simps)\n  done\n\n(* Exercise 2.11 *)\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\"\n| \"eval (Const k) x = k\"\n| \"eval (Add u v) x = (eval u x) + (eval v x)\"\n| \"eval (Mult u v) x = (eval u x) * (eval v x)\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp Nil k = 0\"\n| \"evalp (Cons x xs) k = x + (k * (evalp xs k))\"\n\n\nfun coeffs_add :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"coeffs_add Nil ys = ys\"\n| \"coeffs_add xs Nil = xs\"\n| \"coeffs_add (Cons x xs) (Cons y ys) = (x + y) # (coeffs_add xs ys)\"\n\nvalue \"coeffs_add [0,1,4,5] [1,0,5]\"\n\nfun MultByC :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"MultByC c Nil = Nil\"\n| \"MultByC c (Cons x xs) = (c * x) # (MultByC c xs)\"\n\nfun coeffs_mult :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"coeffs_mult Nil ys = Nil\"\n| \"coeffs_mult (Cons x xs) ys = coeffs_add (MultByC x ys) (0 # (coeffs_mult xs ys))\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0,1]\"\n| \"coeffs (Const k) = [k]\"\n| \"coeffs (Add e1 e2) = coeffs_add (coeffs e1) (coeffs e2)\"\n| \"coeffs (Mult e1 e2) = coeffs_mult (coeffs e1) (coeffs e2)\"\n\nlemma coeffs_add_correct [simp] : \"evalp (coeffs_add xs ys) x = (evalp xs x) + (evalp ys x)\"\n  apply(induction xs ys arbitrary: x rule: coeffs_add.induct)\n    apply(auto simp add: algebra_simps)\n  done\n\nlemma factor_by_const_prop : \" evalp (MultByC a ys) x = a * evalp ys x\"\n  apply(induction ys)\n   apply(auto simp add: algebra_simps)\n  done\n\nlemma coeffs_mult_correct [simp] : \"evalp (coeffs_mult xs ys) x = (evalp xs x) * (evalp ys x)\"\n  apply(induction xs arbitrary: ys  x)\n   apply(auto simp add: algebra_simps)\n  apply(rule factor_by_const_prop)\n  done\n\n\nlemma coeffs_correct : \"evalp (coeffs e) x = eval e x\"\n  apply(induction e arbitrary: x)\n     apply(auto simp add: algebra_simps)\n  done\n\n\nend", "meta": {"author": "PHart3", "repo": "Isabelle-exercises", "sha": "f668ff1e75d20b8d53c7d747e53c28813b7c72b1", "save_path": "github-repos/isabelle/PHart3-Isabelle-exercises", "path": "github-repos/isabelle/PHart3-Isabelle-exercises/Isabelle-exercises-f668ff1e75d20b8d53c7d747e53c28813b7c72b1/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7707194611216898}}
{"text": "(*  Title:       Infinite Sequences\n    Author:      Christian Sternagel <c-sterna@jaist.ac.jp>\n                 René Thiemann       <rene.thiemann@uibk.ac.at>\n    Maintainer:  Christian Sternagel and René Thiemann\n    License:     LGPL\n*)\n\n(*\nCopyright 2012 Christian Sternagel, René Thiemann\n\nThis file is part of IsaFoR/CeTA.\n\nIsaFoR/CeTA is free software: you can redistribute it and/or modify it under the\nterms of the GNU Lesser General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\n\nIsaFoR/CeTA is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along\nwith IsaFoR/CeTA. If not, see <http://www.gnu.org/licenses/>.\n*)\nheader {* Infinite Sequences *}\ntheory Seq\nimports\n  Main\n  \"~~/src/HOL/Library/Infinite_Set\"\nbegin\n\ntext {*Infinite sequences are represented by functions of type @{typ \"nat \\<Rightarrow> 'a\"}.*}\ntype_synonym 'a seq = \"nat \\<Rightarrow> 'a\"\n\n\nsubsection {*Operations on Infinite Sequences*}\n\ntext {*An infinite sequence is \\emph{linked} by a binary predicate @{term P} if every two\nconsecutive elements satisfy it. Such a sequence is called a \\emph{@{term P}-chain}. *}\nabbreviation (input) chainp :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow>'a seq \\<Rightarrow> bool\" where\n  \"chainp P S \\<equiv> \\<forall>i. P (S i) (S (Suc i))\"\n\ntext {*Special version for relations.*}\nabbreviation (input) chain :: \"'a rel \\<Rightarrow> 'a seq \\<Rightarrow> bool\" where\n  \"chain r S \\<equiv> chainp (\\<lambda>x y. (x, y) \\<in> r) S\"\n\ntext {*Extending a chain at the front.*}\nlemma cons_chainp:\n  assumes \"P x (S 0)\" and \"chainp P S\"\n  shows \"chainp P (case_nat x S)\" (is \"chainp P ?S\")\nproof\n  fix i show \"P (?S i) (?S (Suc i))\" using assms by (cases i) simp_all\nqed\n\ntext {*Special version for relations.*}\nlemma cons_chain:\n  assumes \"(x, S 0) \\<in> r\" and \"chain r S\" shows \"chain r (case_nat x S)\"\n  using cons_chainp[of \"\\<lambda>x y. (x, y) \\<in> r\", OF assms] .\n\ntext {*A chain admits arbitrary transitive steps.*}\nlemma chainp_imp_relpowp:\n  assumes \"chainp P S\" shows \"(P^^j) (S i) (S (i + j))\"\nproof (induct \"i + j\" arbitrary: j)\n  case (Suc n) thus ?case using assms by (cases j) auto\nqed simp\n\nlemma chain_imp_relpow:\n  assumes \"chain r S\" shows \"(S i, S (i + j)) \\<in> r^^j\"\nproof (induct \"i + j\" arbitrary: j)\n  case (Suc n) thus ?case using assms by (cases j) auto\nqed simp\n\nlemma chainp_imp_tranclp:\n  assumes \"chainp P S\" and \"i < j\" shows \"P^++ (S i) (S j)\"\nproof -\n  from less_imp_Suc_add[OF assms(2)] obtain n where \"j = i + Suc n\" by auto\n  with chainp_imp_relpowp[of P S \"Suc n\" i, OF assms(1)]\n    show ?thesis\n      unfolding trancl_power[of \"(S i, S j)\", to_pred]\n      by force\nqed\n\nlemma chain_imp_trancl:\n  assumes \"chain r S\" and \"i < j\" shows \"(S i, S j) \\<in> r^+\"\nproof -\n  from less_imp_Suc_add[OF assms(2)] obtain n where \"j = i + Suc n\" by auto\n  with chain_imp_relpow[OF assms(1), of i \"Suc n\"]\n    show ?thesis unfolding trancl_power by force\nqed\n\ntext {*A chain admits arbitrary reflexive and transitive steps.*}\nlemma chainp_imp_rtranclp:\n  assumes \"chainp P S\" and \"i \\<le> j\" shows \"P^** (S i) (S j)\"\nproof -\n  from assms(2) obtain n where \"j = i + n\" by (induct \"j - i\" arbitrary: j) force+\n  with chainp_imp_relpowp[of P S, OF assms(1), of n i] show ?thesis\n    by (simp add: relpow_imp_rtrancl[of \"(S i, S (i + n))\", to_pred])\nqed\n\nlemma chain_imp_rtrancl:\n  assumes \"chain r S\" and \"i \\<le> j\" shows \"(S i, S j) \\<in> r^*\"\nproof -\n  from assms(2) obtain n where \"j = i + n\" by (induct \"j - i\" arbitrary: j) force+\n  with chain_imp_relpow[OF assms(1), of i n] show ?thesis by (simp add: relpow_imp_rtrancl)\nqed\n\ntext {*If for every @{term i} there is a later index @{term \"f i\"} such that the\ncorresponding elements satisfy the predicate @{term P}, then there is a @{term P}-chain.*}\nlemma stepfun_imp_chainp':\n  assumes \"\\<forall>i\\<ge>n::nat. f i \\<ge> i \\<and> P (S i) (S (f i))\"\n  shows \"chainp P (\\<lambda>i. S ((f ^^ i) n))\" (is \"chainp P ?T\")\nproof\n  fix i\n  from assms have \"(f ^^ i) n \\<ge> n\" by (induct i) auto\n  with assms[THEN spec[of _ \"(f ^^ i) n\"]]\n    show \"P (?T i) (?T (Suc i))\" by simp\nqed\n\nlemma stepfun_imp_chainp:\n  assumes \"\\<forall>i\\<ge>n::nat. f i > i \\<and> P (S i) (S (f i))\"\n  shows \"chainp P (\\<lambda>i. S ((f ^^ i) n))\" (is \"chainp P ?T\")\n  using stepfun_imp_chainp'[of n f P S] and assms by force\n\nlemma subchain:\n  assumes \"\\<forall>i::nat>n. \\<exists>j>i. P (f i) (f j)\"\n  shows \"\\<exists>\\<phi>. (\\<forall>i j. i < j \\<longrightarrow> \\<phi> i < \\<phi> j) \\<and> (\\<forall>i. P (f (\\<phi> i)) (f (\\<phi> (Suc i))))\"\nproof -\n  from assms have \"\\<forall>i\\<in>{i. i > n}. \\<exists>j>i. P (f i) (f j)\" by simp\n  from bchoice [OF this] obtain g\n    where *: \"\\<forall>i>n. g i > i\"\n    and **: \"\\<forall>i>n. P (f i) (f (g i))\" by auto\n  def [simp]: \\<phi> \\<equiv> \"\\<lambda>i. (g ^^ i) (Suc n)\"\n  from * have ***: \"\\<And>i. \\<phi> i > n\" by (induct_tac i) auto\n  then have \"\\<And>i. \\<phi> i < \\<phi> (Suc i)\" using * by (induct_tac i) auto\n  then have \"\\<And>i j. i < j \\<Longrightarrow> \\<phi> i < \\<phi> j\" by (rule lift_Suc_mono_less)\n  moreover have \"\\<And>i. P (f (\\<phi> i)) (f (\\<phi> (Suc i)))\" using ** and *** by simp\n  ultimately show ?thesis by blast\nqed\n\ntext {*If for every @{term i} there is a later index @{term j} such that the\ncorresponding elements satisfy the predicate @{term P}, then there is a @{term P}-chain.*}\nlemma steps_imp_chainp':\n  assumes \"\\<forall>i\\<ge>n::nat. \\<exists>j\\<ge>i. P (S i) (S j)\" shows \"\\<exists>T. chainp P T\"\nproof -\n  from assms have \"\\<forall>i\\<in>{i. i \\<ge> n}. \\<exists>j\\<ge>i. P (S i) (S j)\" by auto\n  from bchoice [OF this] (*choice could be replaced by an application of Least_Enum.infinitely_many2*)\n    obtain f where \"\\<forall>i\\<ge>n. f i \\<ge> i \\<and> P (S i) (S (f i))\" by auto\n  from stepfun_imp_chainp'[of n f P S, OF this] show ?thesis by fast\nqed\n\nlemma steps_imp_chainp:\n  assumes \"\\<forall>i\\<ge>n::nat. \\<exists>j>i. P (S i) (S j)\" shows \"\\<exists>T. chainp P T\"\n  using steps_imp_chainp' [of n P S] and assms by force\n\n\nsubsection {* Predicates on Natural Numbers *}\n\ntext {*If some property holds for infinitely many natural numbers, obtain\nan index function that points to these numbers in increasing order.*}\n\nlocale infinitely_many =\n  fixes p :: \"nat \\<Rightarrow> bool\"\n  assumes infinite: \"INFM j. p j\"\nbegin\n\nlemma inf: \"\\<exists>j\\<ge>i. p j\" using infinite[unfolded INFM_nat_le] by auto\n\nfun index :: \"nat seq\" where\n  \"index 0 = (LEAST n. p n)\"\n| \"index (Suc n) = (LEAST k. p k \\<and> k > index n)\"\n\nlemma index_p: \"p (index n)\"\nproof (induct n)\n  case 0\n  from inf obtain j where \"p j\" by auto\n  with LeastI[of p j] show ?case by auto\nnext\n  case (Suc n)\n  from inf obtain k where \"k \\<ge> Suc (index n) \\<and> p k\" by auto\n  with LeastI[of \"\\<lambda> k. p k \\<and> k > index n\" k] show ?case by auto\nqed\n\nlemma index_ordered: \"index n < index (Suc n)\"\nproof -\n  from inf obtain k where \"k \\<ge> Suc (index n) \\<and> p k\" by auto\n  with LeastI[of \"\\<lambda> k. p k \\<and> k > index n\" k] show ?thesis by auto\nqed\n\nlemma index_not_p_between:\n  assumes i1: \"index n < i\"\n    and i2: \"i < index (Suc n)\"\n  shows \"\\<not> p i\"\nproof -\n  from not_less_Least[OF i2[simplified]] i1 show ?thesis by auto\nqed\n\nlemma index_ordered_le:\n  assumes \"i \\<le> j\" shows \"index i \\<le> index j\"\nproof - \n  from assms have \"j = i + (j - i)\" by auto\n  then obtain k where j: \"j = i + k\" by auto\n  have \"index i \\<le> index (i + k)\"\n  proof (induct k)\n    case (Suc k)\n    with index_ordered[of \"i + k\"]\n    show ?case by auto\n  qed simp\n  thus ?thesis unfolding j .\nqed\n\nlemma index_surj:\n  assumes \"k \\<ge> index l\"\n  shows \"\\<exists>i j. k = index i + j \\<and> index i + j < index (Suc i)\"\nproof -\n  from assms have \"k = index l + (k - index l)\" by auto\n  then obtain u where k: \"k = index l + u\" by auto\n  show ?thesis unfolding k\n  proof (induct u)\n    case 0\n    show ?case\n      by (intro exI conjI, rule refl, insert index_ordered[of l], simp)\n  next\n    case (Suc u)\n    then obtain i j\n      where lu: \"index l + u = index i + j\" and lt: \"index i + j < index (Suc i)\" by auto\n    hence \"index l + u < index (Suc i)\" by auto\n    show ?case\n    proof (cases \"index l + (Suc u) = index (Suc i)\")\n      case False\n      show ?thesis\n        by (rule exI[of _ i], rule exI[of _ \"Suc j\"], insert lu lt False, auto)\n    next\n      case True\n      show ?thesis\n        by (rule exI[of _ \"Suc i\"], rule exI[of _ 0], insert True index_ordered[of \"Suc i\"], auto)\n    qed\n  qed\nqed\n\nlemma index_ordered_less:\n  assumes \"i < j\" shows \"index i < index j\"\nproof - \n  from assms have \"Suc i \\<le> j\" by auto\n  from index_ordered_le[OF this]\n  have \"index (Suc i) \\<le> index j\" .\n  with index_ordered[of i] show ?thesis by auto\nqed\n\nlemma index_not_p_start: assumes i: \"i < index 0\" shows \"\\<not> p i\"\nproof -\n  from i[simplified index.simps] have \"i < Least p\" .\n  from not_less_Least[OF this] show ?thesis .\nqed\n\nend\n\n\nsubsection {* Assembling Infinite Words from Finite Words *}\n\ntext {*Concatenate infinitely many non-empty words to an infinite word.*}\n\nfun inf_concat_simple :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat)\" where\n  \"inf_concat_simple f 0 = (0, 0)\"\n| \"inf_concat_simple f (Suc n) = (\n    let (i, j) = inf_concat_simple f n in \n    if Suc j < f i then (i, Suc j)\n    else (Suc i, 0))\"\n\nlemma inf_concat_simple_add:\n  assumes ck: \"inf_concat_simple f k = (i, j)\"\n    and jl: \"j + l < f i\"\n  shows \"inf_concat_simple f (k + l) = (i,j + l)\"\nusing jl\nproof (induct l)\n  case 0\n  thus ?case using ck by simp\nnext\n  case (Suc l)\n  hence c: \"inf_concat_simple f (k + l) = (i, j+ l)\" by auto\n  show ?case \n    by (simp add: c, insert Suc(2), auto)\nqed\n\nlemma inf_concat_simple_surj_zero: \"\\<exists> k. inf_concat_simple f k = (i,0)\"\nproof (induct i)\n  case 0\n  show ?case \n    by (rule exI[of _ 0], simp)\nnext\n  case (Suc i)\n  then obtain k where ck: \"inf_concat_simple f k = (i,0)\" by auto\n  show ?case\n  proof (cases \"f i\")\n    case 0\n    show ?thesis\n      by (rule exI[of _ \"Suc k\"], simp add: ck 0)\n  next\n    case (Suc n)\n    hence \"0 + n < f i\" by auto\n    from inf_concat_simple_add[OF ck, OF this] Suc\n    show ?thesis\n      by (intro exI[of _ \"k + Suc n\"], auto)\n  qed\nqed\n\n\n\nlemma inf_concat_simple_mono:\n  assumes \"k \\<le> k'\" shows \"fst (inf_concat_simple f k) \\<le> fst (inf_concat_simple f k')\"\nproof -\n  from assms have \"k' = k + (k' - k)\" by auto\n  then obtain l where k': \"k' = k + l\" by auto\n  show ?thesis  unfolding k'\n  proof (induct l)\n    case (Suc l)\n    obtain i j where ckl: \"inf_concat_simple f (k+l) = (i,j)\" by (cases \"inf_concat_simple f (k+l)\", auto)\n    with Suc have \"fst (inf_concat_simple f k) \\<le> i\" by auto\n    also have \"... \\<le> fst (inf_concat_simple f (k + Suc l))\"\n      by (simp add: ckl)\n    finally show ?case .\n  qed simp\nqed\n\n\n(* inf_concat assembles infinitely many (possibly empty) words to an infinite word *)\nfun inf_concat :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat \\<times> nat\" where\n  \"inf_concat n 0 = (LEAST j. n j > 0, 0)\"\n| \"inf_concat n (Suc k) = (let (i, j) = inf_concat n k in (if Suc j < n i then (i, Suc j) else (LEAST i'. i' > i \\<and> n i' > 0, 0)))\"\n\nlemma inf_concat_bounds:\n  assumes inf: \"INFM i. n i > 0\"\n    and res: \"inf_concat n k = (i,j)\"\n  shows \"j < n i\"\nproof (cases k)\n  case 0\n  with res have i: \"i = (LEAST i. n i > 0)\" and j: \"j = 0\" by auto\n  from inf[unfolded INFM_nat_le] obtain i' where i': \"0 < n i'\" by auto\n  have \"0 < n (LEAST i. n i > 0)\" \n    by (rule LeastI, rule i')\n  with i j show ?thesis by auto\nnext\n  case (Suc k')\n  obtain i' j' where res': \"inf_concat n k' = (i',j')\" by force\n  note res = res[unfolded Suc inf_concat.simps res' Let_def split]\n  show ?thesis \n  proof (cases \"Suc j' < n i'\")\n    case True\n    with res show ?thesis by auto\n  next\n    case False\n    with res have i: \"i = (LEAST f. i' < f \\<and> 0 < n f)\" and j: \"j = 0\" by auto\n    from inf[unfolded INFM_nat] obtain f where f: \"i' < f \\<and> 0 < n f\" by auto\n    have \"0 < n (LEAST f. i' < f \\<and> 0 < n f)\"\n      using LeastI[of \"\\<lambda> f. i' < f \\<and> 0 < n f\", OF f]\n      by auto\n    with i j show ?thesis by auto\n  qed\nqed\n\nlemma inf_concat_add:\n  assumes res: \"inf_concat n k = (i,j)\"\n    and j: \"j + m < n i\"\n  shows \"inf_concat n (k + m) = (i,j+m)\"\n  using j\nproof (induct m)\n  case 0 show ?case using res by auto\nnext\n  case (Suc m)\n  hence \"inf_concat n (k + m) = (i, j+m)\" by auto\n  with Suc(2)\n  show ?case by auto\nqed\n\nlemma inf_concat_step:\n  assumes res: \"inf_concat n k = (i,j)\"\n    and j: \"Suc (j + m) = n i\"\n  shows \"inf_concat n (k + Suc m) = (LEAST i'. i' > i \\<and> 0 < n i', 0)\"\nproof -\n  from j have \"j + m < n i\" by auto\n  note res = inf_concat_add[OF res, OF this]\n  show ?thesis by (simp add: res j)\nqed\n\nlemma inf_concat_surj_zero:\n  assumes \"0 < n i\"\n  shows \"\\<exists>k. inf_concat n k = (i, 0)\"\nproof -\n  {\n    fix l\n    have \"\\<forall> j. j < l \\<and> 0 < n j \\<longrightarrow> (\\<exists> k. inf_concat n k = (j,0))\"\n    proof (induct l)\n      case 0\n      thus ?case by auto\n    next\n      case (Suc l)\n      show ?case\n      proof (intro allI impI, elim conjE)\n        fix j\n        assume j: \"j < Suc l\" and nj: \"0 < n j\"\n        show \"\\<exists> k. inf_concat n k = (j, 0)\"\n        proof (cases \"j < l\")\n          case True\n          from Suc[THEN spec[of _ j]] True nj show ?thesis by auto\n        next\n          case False\n          with j have j: \"j = l\" by auto\n          show ?thesis\n          proof (cases \"\\<exists> j'. j' < l \\<and> 0 < n j'\")\n            case False\n            have l: \"(LEAST i. 0 < n i) = l\"\n            proof (rule Least_equality, rule nj[unfolded j])\n              fix l'\n              assume \"0 < n l'\"\n              with False have \"\\<not> l' < l\" by auto\n              thus \"l \\<le> l'\" by auto\n            qed\n            show ?thesis\n              by (rule exI[of _ 0], simp add: l j)\n          next\n            case True\n            then obtain lll where lll: \"lll < l\" and nlll: \"0 < n lll\" by auto \n            then obtain ll where l: \"l = Suc ll\" by (cases l, auto)   \n            from lll l have lll: \"lll = ll - (ll - lll)\" by auto\n            let ?l' = \"LEAST d. 0 < n (ll - d)\"\n            have nl': \"0 < n (ll - ?l')\"\n            proof (rule LeastI)\n              show \"0 < n (ll - (ll - lll))\" using lll nlll by auto\n            qed\n            with Suc[THEN spec[of _ \"ll - ?l'\"]] obtain k where k:\n              \"inf_concat n k = (ll - ?l',0)\" unfolding l by auto\n            from nl' obtain off where off: \"Suc (0 + off) = n (ll - ?l')\" by (cases \"n (ll - ?l')\", auto)\n            from inf_concat_step[OF k, OF off]\n            have id: \"inf_concat n (k + Suc off) = (LEAST i'. ll - ?l' < i' \\<and> 0 < n i',0)\" (is \"_ = (?l,0)\") .\n            have ll: \"?l = l\" unfolding l\n            proof (rule Least_equality)\n              show \"ll - ?l' < Suc ll \\<and> 0 < n (Suc ll)\" using nj[unfolded j l] by simp\n            next\n              fix l'\n              assume ass: \"ll - ?l' < l' \\<and> 0 < n l'\"\n              show \"Suc ll \\<le> l'\" \n              proof (rule ccontr)\n                assume not: \"\\<not> ?thesis\"\n                hence \"l' \\<le> ll\" by auto\n                hence \"ll = l' + (ll - l')\" by auto\n                then obtain k where ll: \"ll = l' + k\" by auto\n                from ass have \"l' + k - ?l' < l'\" unfolding ll by auto\n                hence kl': \"k < ?l'\" by auto\n                have \"0 < n (ll - k)\" using ass unfolding ll by simp\n                from Least_le[of \"\\<lambda> k. 0 < n (ll - k)\", OF this] kl'\n                show False by auto\n              qed\n            qed            \n            show ?thesis unfolding j\n              by (rule exI[of _ \"k + Suc off\"], unfold id ll, simp)\n          qed\n        qed\n      qed\n    qed\n  }\n  with assms show ?thesis by auto\nqed\n\nlemma inf_concat_surj:\n  assumes j: \"j < n i\"\n  shows \"\\<exists>k. inf_concat n k = (i, j)\"\nproof -\n  from j have \"0 < n i\" by auto\n  from inf_concat_surj_zero[of n, OF this]\n  obtain k where \"inf_concat n k = (i,0)\" by auto\n  from inf_concat_add[OF this, of j] j\n  show ?thesis by auto\nqed\n\nlemma inf_concat_mono:\n  assumes inf: \"INFM i. n i > 0\"\n    and resk: \"inf_concat n k = (i, j)\"\n    and reskp: \"inf_concat n k' = (i', j')\"\n    and lt: \"i < i'\"\n  shows \"k < k'\"\nproof -\n  note bounds = inf_concat_bounds[OF inf]\n  {\n    assume \"k' \\<le> k\"\n    hence \"k = k' + (k - k')\" by auto\n    then obtain l where k: \"k = k' + l\" by auto\n    have \"i' \\<le> fst (inf_concat n (k' + l))\" \n    proof (induct l)\n      case 0\n      with reskp show ?case by auto\n    next      \n      case (Suc l)\n      obtain i'' j'' where l: \"inf_concat n (k' + l) = (i'',j'')\" by force\n      with Suc have one: \"i' \\<le> i''\" by auto\n      from bounds[OF l] have j'': \"j'' < n i''\" by auto\n      show ?case \n      proof (cases \"Suc j'' < n i''\")\n        case True\n        show ?thesis by (simp add: l True one)\n      next\n        case False\n        let ?i = \"LEAST i'. i'' < i' \\<and> 0 < n i'\"\n        from inf[unfolded INFM_nat] obtain k where \"i'' < k \\<and> 0 < n k\" by auto\n        from LeastI[of \"\\<lambda> k. i'' < k \\<and> 0 < n k\", OF this]\n        have \"i'' < ?i\" by auto\n        with one show ?thesis by (simp add: l False)\n      qed\n    qed      \n    with resk k lt have False by auto\n  }\n  thus ?thesis by arith\nqed\n\nlemma inf_concat_Suc:\n  assumes inf: \"INFM i. n i > 0\"\n    and f: \"\\<And> i. f i (n i) = f (Suc i) 0\"\n    and resk: \"inf_concat n k = (i, j)\"\n    and ressk: \"inf_concat n (Suc k) = (i', j')\"\n  shows \"f i' j' = f i (Suc j)\"\nproof - \n  note bounds = inf_concat_bounds[OF inf]\n  from bounds[OF resk] have j: \"j < n i\" .\n  show ?thesis\n  proof (cases \"Suc j < n i\")\n    case True\n    with ressk resk\n    show ?thesis by simp\n  next\n    case False\n    let ?p = \"\\<lambda> i'. i < i' \\<and> 0 < n i'\"\n    let ?i' = \"LEAST i'. ?p i'\"\n    from False j have id: \"Suc (j + 0) = n i\" by auto\n    from inf_concat_step[OF resk, OF id] ressk\n    have i': \"i' = ?i'\" and j': \"j' = 0\" by auto\n    from id have j: \"Suc j = n i\" by simp\n    from inf[unfolded INFM_nat] obtain k where \"?p k\" by auto\n    from LeastI[of ?p, OF this] have \"?p ?i'\" .\n    hence \"?i' = Suc i + (?i' - Suc i)\" by simp\n    then obtain d where ii': \"?i' = Suc i + d\" by auto\n    from not_less_Least[of _ ?p, unfolded ii'] have d': \"\\<And> d'. d' < d \\<Longrightarrow> n (Suc i + d') = 0\" by auto\n    have \"f (Suc i) 0 = f ?i' 0\" unfolding ii' using d'\n    proof (induct d)\n      case 0\n      show ?case by simp\n    next\n      case (Suc d)\n      hence \"f (Suc i) 0 = f (Suc i + d) 0\" by auto\n      also have \"... = f (Suc (Suc i + d)) 0\"\n        unfolding f[symmetric]\n        using Suc(2)[of d] by simp\n      finally show ?case by simp\n    qed\n    thus ?thesis unfolding i' j' j f by simp\n  qed\nqed\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Abstract-Rewriting/Seq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.8558511451289037, "lm_q1q2_score": 0.7707194555259477}}
{"text": "(*  Title:      ZF/ex/Primes.thy\n    Author:     Christophe Tabacznyj and Lawrence C Paulson\n    Copyright   1996  University of Cambridge\n*)\n\nsection\\<open>The Divides Relation and Euclid's algorithm for the GCD\\<close>\n\ntheory Primes imports ZF begin\n\ndefinition\n  divides :: \"[i,i]=>o\"              (infixl \"dvd\" 50)  where\n    \"m dvd n == m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\n\ndefinition\n  is_gcd  :: \"[i,i,i]=>o\"     \\<comment>\\<open>definition of great common divisor\\<close>  where\n    \"is_gcd(p,m,n) == ((p dvd m) & (p dvd n))   &\n                       (\\<forall>d\\<in>nat. (d dvd m) & (d dvd n) \\<longrightarrow> d dvd p)\"\n\ndefinition\n  gcd     :: \"[i,i]=>i\"       \\<comment>\\<open>Euclid's algorithm for the gcd\\<close>  where\n    \"gcd(m,n) == transrec(natify(n),\n                        %n f. \\<lambda>m \\<in> nat.\n                                if n=0 then m else f`(m mod n)`n) ` natify(m)\"\n\ndefinition\n  coprime :: \"[i,i]=>o\"       \\<comment>\\<open>the coprime relation\\<close>  where\n    \"coprime(m,n) == gcd(m,n) = 1\"\n  \ndefinition\n  prime   :: i                \\<comment>\\<open>the set of prime numbers\\<close>  where\n   \"prime == {p \\<in> nat. 1<p & (\\<forall>m \\<in> nat. m dvd p \\<longrightarrow> m=1 | m=p)}\"\n\n\nsubsection\\<open>The Divides Relation\\<close>\n\nlemma dvdD: \"m dvd n ==> m \\<in> nat & n \\<in> nat & (\\<exists>k \\<in> nat. n = m#*k)\"\nby (unfold divides_def, assumption)\n\nlemma dvdE:\n     \"[|m dvd n;  !!k. [|m \\<in> nat; n \\<in> nat; k \\<in> nat; n = m#*k|] ==> P|] ==> P\"\nby (blast dest!: dvdD)\n\nlemmas dvd_imp_nat1 = dvdD [THEN conjunct1]\nlemmas dvd_imp_nat2 = dvdD [THEN conjunct2, THEN conjunct1]\n\n\nlemma dvd_0_right [simp]: \"m \\<in> nat ==> m dvd 0\"\napply (simp add: divides_def)\napply (fast intro: nat_0I mult_0_right [symmetric])\ndone\n\nlemma dvd_0_left: \"0 dvd m ==> m = 0\"\nby (simp add: divides_def)\n\nlemma dvd_refl [simp]: \"m \\<in> nat ==> m dvd m\"\napply (simp add: divides_def)\napply (fast intro: nat_1I mult_1_right [symmetric])\ndone\n\nlemma dvd_trans: \"[| m dvd n; n dvd p |] ==> m dvd p\"\nby (auto simp add: divides_def intro: mult_assoc mult_type)\n\nlemma dvd_anti_sym: \"[| m dvd n; n dvd m |] ==> m=n\"\napply (simp add: divides_def)\napply (force dest: mult_eq_self_implies_10\n             simp add: mult_assoc mult_eq_1_iff)\ndone\n\nlemma dvd_mult_left: \"[|(i#*j) dvd k; i \\<in> nat|] ==> i dvd k\"\nby (auto simp add: divides_def mult_assoc)\n\nlemma dvd_mult_right: \"[|(i#*j) dvd k; j \\<in> nat|] ==> j dvd k\"\napply (simp add: divides_def, clarify)\napply (rule_tac x = \"i#*ka\" in bexI)\napply (simp add: mult_ac)\napply (rule mult_type)\ndone\n\n\nsubsection\\<open>Euclid's Algorithm for the GCD\\<close>\n\nlemma gcd_0 [simp]: \"gcd(m,0) = natify(m)\"\napply (simp add: gcd_def)\napply (subst transrec, simp)\ndone\n\nlemma gcd_natify1 [simp]: \"gcd(natify(m),n) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_natify2 [simp]: \"gcd(m, natify(n)) = gcd(m,n)\"\nby (simp add: gcd_def)\n\nlemma gcd_non_0_raw: \n    \"[| 0<n;  n \\<in> nat |] ==> gcd(m,n) = gcd(n, m mod n)\"\napply (simp add: gcd_def)\napply (rule_tac P = \"%z. left (z) = right\" for left right in transrec [THEN ssubst])\napply (simp add: ltD [THEN mem_imp_not_eq, THEN not_sym] \n                 mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_non_0: \"0 < natify(n) ==> gcd(m,n) = gcd(n, m mod n)\"\napply (cut_tac m = m and n = \"natify (n) \" in gcd_non_0_raw)\napply auto\ndone\n\nlemma gcd_1 [simp]: \"gcd(m,1) = 1\"\nby (simp (no_asm_simp) add: gcd_non_0)\n\nlemma dvd_add: \"[| k dvd a; k dvd b |] ==> k dvd (a #+ b)\"\napply (simp add: divides_def)\napply (fast intro: add_mult_distrib_left [symmetric] add_type)\ndone\n\nlemma dvd_mult: \"k dvd n ==> k dvd (m #* n)\"\napply (simp add: divides_def)\napply (fast intro: mult_left_commute mult_type)\ndone\n\nlemma dvd_mult2: \"k dvd m ==> k dvd (m #* n)\"\napply (subst mult_commute)\napply (blast intro: dvd_mult)\ndone\n\n(* k dvd (m*k) *)\nlemmas dvdI1 [simp] = dvd_refl [THEN dvd_mult]\nlemmas dvdI2 [simp] = dvd_refl [THEN dvd_mult2]\n\nlemma dvd_mod_imp_dvd_raw:\n     \"[| a \\<in> nat; b \\<in> nat; k dvd b; k dvd (a mod b) |] ==> k dvd a\"\napply (case_tac \"b=0\") \n apply (simp add: DIVISION_BY_ZERO_MOD)\napply (blast intro: mod_div_equality [THEN subst]\n             elim: dvdE \n             intro!: dvd_add dvd_mult mult_type mod_type div_type)\ndone\n\nlemma dvd_mod_imp_dvd: \"[| k dvd (a mod b); k dvd b; a \\<in> nat |] ==> k dvd a\"\napply (cut_tac b = \"natify (b)\" in dvd_mod_imp_dvd_raw)\napply auto\napply (simp add: divides_def)\ndone\n\n(*Imitating TFL*)\nlemma gcd_induct_lemma [rule_format (no_asm)]: \"[| n \\<in> nat;  \n         \\<forall>m \\<in> nat. P(m,0);  \n         \\<forall>m \\<in> nat. \\<forall>n \\<in> nat. 0<n \\<longrightarrow> P(n, m mod n) \\<longrightarrow> P(m,n) |]  \n      ==> \\<forall>m \\<in> nat. P (m,n)\"\napply (erule_tac i = n in complete_induct)\napply (case_tac \"x=0\")\napply (simp (no_asm_simp))\napply clarify\napply (drule_tac x1 = m and x = x in bspec [THEN bspec])\napply (simp_all add: Ord_0_lt_iff)\napply (blast intro: mod_less_divisor [THEN ltD])\ndone\n\nlemma gcd_induct: \"!!P. [| m \\<in> nat; n \\<in> nat;  \n         !!m. m \\<in> nat ==> P(m,0);  \n         !!m n. [|m \\<in> nat; n \\<in> nat; 0<n; P(n, m mod n)|] ==> P(m,n) |]  \n      ==> P (m,n)\"\nby (blast intro: gcd_induct_lemma)\n\n\nsubsection\\<open>Basic Properties of @{term gcd}\\<close>\n\ntext\\<open>type of gcd\\<close>\nlemma gcd_type [simp,TC]: \"gcd(m, n) \\<in> nat\"\napply (subgoal_tac \"gcd (natify (m), natify (n)) \\<in> nat\")\napply simp\napply (rule_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_induct)\napply auto\napply (simp add: gcd_non_0)\ndone\n\n\ntext\\<open>Property 1: gcd(a,b) divides a and b\\<close>\n\nlemma gcd_dvd_both:\n     \"[| m \\<in> nat; n \\<in> nat |] ==> gcd (m, n) dvd m & gcd (m, n) dvd n\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0)\napply (blast intro: dvd_mod_imp_dvd_raw nat_into_Ord [THEN Ord_0_lt])\ndone\n\nlemma gcd_dvd1 [simp]: \"m \\<in> nat ==> gcd(m,n) dvd m\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\nlemma gcd_dvd2 [simp]: \"n \\<in> nat ==> gcd(m,n) dvd n\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_dvd_both)\napply auto\ndone\n\ntext\\<open>if f divides a and b then f divides gcd(a,b)\\<close>\n\nlemma dvd_mod: \"[| f dvd a; f dvd b |] ==> f dvd (a mod b)\"\napply (simp add: divides_def)\napply (case_tac \"b=0\")\n apply (simp add: DIVISION_BY_ZERO_MOD, auto)\napply (blast intro: mod_mult_distrib2 [symmetric])\ndone\n\ntext\\<open>Property 2: for all a,b,f naturals, \n               if f divides a and f divides b then f divides gcd(a,b)\\<close>\n\nlemma gcd_greatest_raw [rule_format]:\n     \"[| m \\<in> nat; n \\<in> nat; f \\<in> nat |]    \n      ==> (f dvd m) \\<longrightarrow> (f dvd n) \\<longrightarrow> f dvd gcd(m,n)\"\napply (rule_tac m = m and n = n in gcd_induct)\napply (simp_all add: gcd_non_0 dvd_mod)\ndone\n\nlemma gcd_greatest: \"[| f dvd m;  f dvd n;  f \\<in> nat |] ==> f dvd gcd(m,n)\"\napply (rule gcd_greatest_raw)\napply (auto simp add: divides_def)\ndone\n\nlemma gcd_greatest_iff [simp]: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> (k dvd gcd (m, n)) \\<longleftrightarrow> (k dvd m & k dvd n)\"\nby (blast intro!: gcd_greatest gcd_dvd1 gcd_dvd2 intro: dvd_trans)\n\n\nsubsection\\<open>The Greatest Common Divisor\\<close>\n\ntext\\<open>The GCD exists and function gcd computes it.\\<close>\n\nlemma is_gcd: \"[| m \\<in> nat; n \\<in> nat |] ==> is_gcd(gcd(m,n), m, n)\"\nby (simp add: is_gcd_def)\n\ntext\\<open>The GCD is unique\\<close>\n\nlemma is_gcd_unique: \"[|is_gcd(m,a,b); is_gcd(n,a,b); m\\<in>nat; n\\<in>nat|] ==> m=n\"\napply (simp add: is_gcd_def)\napply (blast intro: dvd_anti_sym)\ndone\n\nlemma is_gcd_commute: \"is_gcd(k,m,n) \\<longleftrightarrow> is_gcd(k,n,m)\"\nby (simp add: is_gcd_def, blast)\n\nlemma gcd_commute_raw: \"[| m \\<in> nat; n \\<in> nat |] ==> gcd(m,n) = gcd(n,m)\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (rule_tac [3] is_gcd_commute [THEN iffD1])\napply (rule_tac [3] is_gcd, auto)\ndone\n\nlemma gcd_commute: \"gcd(m,n) = gcd(n,m)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_commute_raw)\napply auto\ndone\n\nlemma gcd_assoc_raw: \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (rule is_gcd_unique)\napply (rule is_gcd)\napply (simp_all add: is_gcd_def)\napply (blast intro: gcd_dvd1 gcd_dvd2 gcd_type intro: dvd_trans)\ndone\n\nlemma gcd_assoc: \"gcd (gcd (k, m), n) = gcd (k, gcd (m, n))\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_assoc_raw)\napply auto\ndone\n\nlemma gcd_0_left [simp]: \"gcd (0, m) = natify(m)\"\nby (simp add: gcd_commute [of 0])\n\nlemma gcd_1_left [simp]: \"gcd (1, m) = 1\"\nby (simp add: gcd_commute [of 1])\n\n\nsubsection\\<open>Addition laws\\<close>\n\nlemma gcd_add1 [simp]: \"gcd (m #+ n, n) = gcd (m, n)\"\napply (subgoal_tac \"gcd (m #+ natify (n), natify (n)) = gcd (m, natify (n))\")\napply simp\napply (case_tac \"natify (n) = 0\")\napply (auto simp add: Ord_0_lt_iff gcd_non_0)\ndone\n\nlemma gcd_add2 [simp]: \"gcd (m, m #+ n) = gcd (m, n)\"\napply (rule gcd_commute [THEN trans])\napply (subst add_commute, simp)\napply (rule gcd_commute)\ndone\n\nlemma gcd_add2' [simp]: \"gcd (m, n #+ m) = gcd (m, n)\"\nby (subst add_commute, rule gcd_add2)\n\nlemma gcd_add_mult_raw: \"k \\<in> nat ==> gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (erule nat_induct)\napply (auto simp add: gcd_add2 add_assoc)\ndone\n\nlemma gcd_add_mult: \"gcd (m, k #* m #+ n) = gcd (m, n)\"\napply (cut_tac k = \"natify (k)\" in gcd_add_mult_raw)\napply auto\ndone\n\n\nsubsection\\<open>Multiplication Laws\\<close>\n\nlemma gcd_mult_distrib2_raw:\n     \"[| k \\<in> nat; m \\<in> nat; n \\<in> nat |]  \n      ==> k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (erule_tac m = m and n = n in gcd_induct, assumption)\napply simp\napply (case_tac \"k = 0\", simp)\napply (simp add: mod_geq gcd_non_0 mod_mult_distrib2 Ord_0_lt_iff)\ndone\n\nlemma gcd_mult_distrib2: \"k #* gcd (m, n) = gcd (k #* m, k #* n)\"\napply (cut_tac k = \"natify (k)\" and m = \"natify (m)\" and n = \"natify (n) \" \n       in gcd_mult_distrib2_raw)\napply auto\ndone\n\nlemma gcd_mult [simp]: \"gcd (k, k #* n) = natify(k)\"\nby (cut_tac k = k and m = 1 and n = n in gcd_mult_distrib2, auto)\n\nlemma gcd_self [simp]: \"gcd (k, k) = natify(k)\"\nby (cut_tac k = k and n = 1 in gcd_mult, auto)\n\nlemma relprime_dvd_mult:\n     \"[| gcd (k,n) = 1;  k dvd (m #* n);  m \\<in> nat |] ==> k dvd m\"\napply (cut_tac k = m and m = k and n = n in gcd_mult_distrib2, auto)\napply (erule_tac b = m in ssubst)\napply (simp add: dvd_imp_nat1)\ndone\n\nlemma relprime_dvd_mult_iff:\n     \"[| gcd (k,n) = 1;  m \\<in> nat |] ==> k dvd (m #* n) \\<longleftrightarrow> k dvd m\"\nby (blast intro: dvdI2 relprime_dvd_mult dvd_trans)\n\nlemma prime_imp_relprime: \n     \"[| p \\<in> prime;  ~ (p dvd n);  n \\<in> nat |] ==> gcd (p, n) = 1\"\napply (simp add: prime_def, clarify)\napply (drule_tac x = \"gcd (p,n)\" in bspec)\napply auto\napply (cut_tac m = p and n = n in gcd_dvd2, auto)\ndone\n\nlemma prime_into_nat: \"p \\<in> prime ==> p \\<in> nat\"\nby (simp add: prime_def)\n\nlemma prime_nonzero: \"p \\<in> prime \\<Longrightarrow> p\\<noteq>0\"\nby (auto simp add: prime_def)\n\n\ntext\\<open>This theorem leads immediately to a proof of the uniqueness of\n  factorization.  If @{term p} divides a product of primes then it is\n  one of those primes.\\<close>\n\nlemma prime_dvd_mult:\n     \"[|p dvd m #* n; p \\<in> prime; m \\<in> nat; n \\<in> nat |] ==> p dvd m \\<or> p dvd n\"\nby (blast intro: relprime_dvd_mult prime_imp_relprime prime_into_nat)\n\n\nlemma gcd_mult_cancel_raw:\n     \"[|gcd (k,n) = 1; m \\<in> nat; n \\<in> nat|] ==> gcd (k #* m, n) = gcd (m, n)\"\napply (rule dvd_anti_sym)\n apply (rule gcd_greatest)\n  apply (rule relprime_dvd_mult [of _ k])\napply (simp add: gcd_assoc)\napply (simp add: gcd_commute)\napply (simp_all add: mult_commute)\napply (blast intro: dvdI1 gcd_dvd1 dvd_trans)\ndone\n\nlemma gcd_mult_cancel: \"gcd (k,n) = 1 ==> gcd (k #* m, n) = gcd (m, n)\"\napply (cut_tac m = \"natify (m)\" and n = \"natify (n)\" in gcd_mult_cancel_raw)\napply auto\ndone\n\n\nsubsection\\<open>The Square Root of a Prime is Irrational: Key Lemma\\<close>\n\nlemma prime_dvd_other_side:\n     \"\\<lbrakk>n#*n = p#*(k#*k); p \\<in> prime; n \\<in> nat\\<rbrakk> \\<Longrightarrow> p dvd n\"\napply (subgoal_tac \"p dvd n#*n\")\n apply (blast dest: prime_dvd_mult)\napply (rule_tac j = \"k#*k\" in dvd_mult_left)\n apply (auto simp add: prime_def)\ndone\n\nlemma reduction:\n     \"\\<lbrakk>k#*k = p#*(j#*j); p \\<in> prime; 0 < k; j \\<in> nat; k \\<in> nat\\<rbrakk>  \n      \\<Longrightarrow> k < p#*j & 0 < j\"\napply (rule ccontr)\napply (simp add: not_lt_iff_le prime_into_nat)\napply (erule disjE)\n apply (frule mult_le_mono, assumption+)\napply (simp add: mult_ac)\napply (auto dest!: natify_eqE \n            simp add: not_lt_iff_le prime_into_nat mult_le_cancel_le1)\napply (simp add: prime_def)\napply (blast dest: lt_trans1)\ndone\n\nlemma rearrange: \"j #* (p#*j) = k#*k \\<Longrightarrow> k#*k = p#*(j#*j)\"\nby (simp add: mult_ac)\n\nlemma prime_not_square:\n     \"\\<lbrakk>m \\<in> nat; p \\<in> prime\\<rbrakk> \\<Longrightarrow> \\<forall>k \\<in> nat. 0<k \\<longrightarrow> m#*m \\<noteq> p#*(k#*k)\"\napply (erule complete_induct, clarify)\napply (frule prime_dvd_other_side, assumption)\napply assumption\napply (erule dvdE)\napply (simp add: mult_assoc mult_cancel1 prime_nonzero prime_into_nat)\napply (blast dest: rearrange reduction ltD)\ndone\n\nend\n", "meta": {"author": "alexkrauss", "repo": "isabelle-zf-experiments", "sha": "6477db2ffcd2bf71287168d8061c218b29436e5b", "save_path": "github-repos/isabelle/alexkrauss-isabelle-zf-experiments", "path": "github-repos/isabelle/alexkrauss-isabelle-zf-experiments/isabelle-zf-experiments-6477db2ffcd2bf71287168d8061c218b29436e5b/src/ex/Primes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483232, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.770719443075943}}
{"text": "(*  Title:      HOL/Library/Multiset_Permutations.thy\n    Author:     Manuel Eberl (TU München)\n\nDefines the set of permutations of a given multiset (or set), i.e. the set of all lists whose \nentries correspond to the multiset (resp. set).\n*)\n\nsection \\<open>Permutations of a Multiset\\<close>\n\ntheory Multiset_Permutations\nimports \n  Complex_Main \n  Multiset\n  Permutations\nbegin\n\n(* TODO Move *)\nlemma mset_tl: \"xs \\<noteq> [] \\<Longrightarrow> mset (tl xs) = mset xs - {#hd xs#}\"\n  by (cases xs) simp_all\n\nlemma mset_set_image_inj:\n  assumes \"inj_on f A\"\n  shows   \"mset_set (f ` A) = image_mset f (mset_set A)\"\nproof (cases \"finite A\")\n  case True\n  from this and assms show ?thesis by (induction A) auto\nqed (insert assms, simp add: finite_image_iff)\n\nlemma multiset_remove_induct [case_names empty remove]:\n  assumes \"P {#}\" \"\\<And>A. A \\<noteq> {#} \\<Longrightarrow> (\\<And>x. x \\<in># A \\<Longrightarrow> P (A - {#x#})) \\<Longrightarrow> P A\"\n  shows   \"P A\"\nproof (induction A rule: full_multiset_induct)\n  case (less A)\n  hence IH: \"P B\" if \"B \\<subset># A\" for B using that by blast\n  show ?case\n  proof (cases \"A = {#}\")\n    case True\n    thus ?thesis by (simp add: assms)\n  next\n    case False\n    hence \"P (A - {#x#})\" if \"x \\<in># A\" for x\n      using that by (intro IH) (simp add: mset_subset_diff_self)\n    from False and this show \"P A\" by (rule assms)\n  qed\nqed\n\nlemma map_list_bind: \"map g (List.bind xs f) = List.bind xs (map g \\<circ> f)\"\n  by (simp add: List.bind_def map_concat)\n\nlemma mset_eq_mset_set_imp_distinct:\n  \"finite A \\<Longrightarrow> mset_set A = mset xs \\<Longrightarrow> distinct xs\"\nproof (induction xs arbitrary: A)\n  case (Cons x xs A)\n  from Cons.prems(2) have \"x \\<in># mset_set A\" by simp\n  with Cons.prems(1) have [simp]: \"x \\<in> A\" by simp\n  from Cons.prems have \"x \\<notin># mset_set (A - {x})\" by simp\n  also from Cons.prems have \"mset_set (A - {x}) = mset_set A - {#x#}\"\n    by (subst mset_set_Diff) simp_all\n  also have \"mset_set A = mset (x#xs)\" by (simp add: Cons.prems)\n  also have \"\\<dots> - {#x#} = mset xs\" by simp\n  finally have [simp]: \"x \\<notin> set xs\" by (simp add: in_multiset_in_set)\n  from Cons.prems show ?case by (auto intro!: Cons.IH[of \"A - {x}\"] simp: mset_set_Diff)\nqed simp_all\n(* END TODO *)\n\n\nsubsection \\<open>Permutations of a multiset\\<close>\n\ndefinition permutations_of_multiset :: \"'a multiset \\<Rightarrow> 'a list set\" where\n  \"permutations_of_multiset A = {xs. mset xs = A}\"\n\nlemma permutations_of_multisetI: \"mset xs = A \\<Longrightarrow> xs \\<in> permutations_of_multiset A\"\n  by (simp add: permutations_of_multiset_def)\n\nlemma permutations_of_multisetD: \"xs \\<in> permutations_of_multiset A \\<Longrightarrow> mset xs = A\"\n  by (simp add: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_Cons_iff:\n  \"x # xs \\<in> permutations_of_multiset A \\<longleftrightarrow> x \\<in># A \\<and> xs \\<in> permutations_of_multiset (A - {#x#})\"\n  by (auto simp: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_empty [simp]: \"permutations_of_multiset {#} = {[]}\"\n  unfolding permutations_of_multiset_def by simp\n\nlemma permutations_of_multiset_nonempty: \n  assumes nonempty: \"A \\<noteq> {#}\"\n  shows   \"permutations_of_multiset A = \n             (\\<Union>x\\<in>set_mset A. ((#) x) ` permutations_of_multiset (A - {#x#}))\" (is \"_ = ?rhs\")\nproof safe\n  fix xs assume \"xs \\<in> permutations_of_multiset A\"\n  hence mset_xs: \"mset xs = A\" by (simp add: permutations_of_multiset_def)\n  hence \"xs \\<noteq> []\" by (auto simp: nonempty)\n  then obtain x xs' where xs: \"xs = x # xs'\" by (cases xs) simp_all\n  with mset_xs have \"x \\<in> set_mset A\" \"xs' \\<in> permutations_of_multiset (A - {#x#})\"\n    by (auto simp: permutations_of_multiset_def)\n  with xs show \"xs \\<in> ?rhs\" by auto\nqed (auto simp: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_singleton [simp]: \"permutations_of_multiset {#x#} = {[x]}\"\n  by (simp add: permutations_of_multiset_nonempty)\n\nlemma permutations_of_multiset_doubleton: \n  \"permutations_of_multiset {#x,y#} = {[x,y], [y,x]}\"\n  by (simp add: permutations_of_multiset_nonempty insert_commute)\n\nlemma rev_permutations_of_multiset [simp]:\n  \"rev ` permutations_of_multiset A = permutations_of_multiset A\"\nproof\n  have \"rev ` rev ` permutations_of_multiset A \\<subseteq> rev ` permutations_of_multiset A\"\n    unfolding permutations_of_multiset_def by auto\n  also have \"rev ` rev ` permutations_of_multiset A = permutations_of_multiset A\"\n    by (simp add: image_image)\n  finally show \"permutations_of_multiset A \\<subseteq> rev ` permutations_of_multiset A\" .\nnext\n  show \"rev ` permutations_of_multiset A \\<subseteq> permutations_of_multiset A\"\n    unfolding permutations_of_multiset_def by auto\nqed\n\nlemma length_finite_permutations_of_multiset:\n  \"xs \\<in> permutations_of_multiset A \\<Longrightarrow> length xs = size A\"\n  by (auto simp: permutations_of_multiset_def)\n\nlemma permutations_of_multiset_lists: \"permutations_of_multiset A \\<subseteq> lists (set_mset A)\"\n  by (auto simp: permutations_of_multiset_def)\n\nlemma finite_permutations_of_multiset [simp]: \"finite (permutations_of_multiset A)\"\nproof (rule finite_subset)\n  show \"permutations_of_multiset A \\<subseteq> {xs. set xs \\<subseteq> set_mset A \\<and> length xs = size A}\" \n    by (auto simp: permutations_of_multiset_def)\n  show \"finite {xs. set xs \\<subseteq> set_mset A \\<and> length xs = size A}\" \n    by (rule finite_lists_length_eq) simp_all\nqed\n\nlemma permutations_of_multiset_not_empty [simp]: \"permutations_of_multiset A \\<noteq> {}\"\nproof -\n  from ex_mset[of A] guess xs ..\n  thus ?thesis by (auto simp: permutations_of_multiset_def)\nqed\n\nlemma permutations_of_multiset_image:\n  \"permutations_of_multiset (image_mset f A) = map f ` permutations_of_multiset A\"\nproof safe\n  fix xs assume A: \"xs \\<in> permutations_of_multiset (image_mset f A)\"\n  from ex_mset[of A] obtain ys where ys: \"mset ys = A\" ..\n  with A have \"mset xs = mset (map f ys)\" \n    by (simp add: permutations_of_multiset_def)\n  from mset_eq_permutation[OF this] guess \\<sigma> . note \\<sigma> = this\n  with ys have \"xs = map f (permute_list \\<sigma> ys)\"\n    by (simp add: permute_list_map)\n  moreover from \\<sigma> ys have \"permute_list \\<sigma> ys \\<in> permutations_of_multiset A\"\n    by (simp add: permutations_of_multiset_def)\n  ultimately show \"xs \\<in> map f ` permutations_of_multiset A\" by blast\nqed (auto simp: permutations_of_multiset_def)\n\n\nsubsection \\<open>Cardinality of permutations\\<close>\n\ntext \\<open>\n  In this section, we prove some basic facts about the number of permutations of a multiset.\n\\<close>\n\ncontext\nbegin\n\nprivate lemma multiset_prod_fact_insert:\n  \"(\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count (A+{#x#}) y)) =\n     (count A x + 1) * (\\<Prod>y\\<in>set_mset A. fact (count A y))\"\nproof -\n  have \"(\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count (A+{#x#}) y)) =\n          (\\<Prod>y\\<in>set_mset (A+{#x#}). (if y = x then count A x + 1 else 1) * fact (count A y))\"\n    by (intro prod.cong) simp_all\n  also have \"\\<dots> = (count A x + 1) * (\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count A y))\"\n    by (simp add: prod.distrib)\n  also have \"(\\<Prod>y\\<in>set_mset (A+{#x#}). fact (count A y)) = (\\<Prod>y\\<in>set_mset A. fact (count A y))\"\n    by (intro prod.mono_neutral_right) (auto simp: not_in_iff)\n  finally show ?thesis .\nqed\n\nprivate lemma multiset_prod_fact_remove:\n  \"x \\<in># A \\<Longrightarrow> (\\<Prod>y\\<in>set_mset A. fact (count A y)) =\n                   count A x * (\\<Prod>y\\<in>set_mset (A-{#x#}). fact (count (A-{#x#}) y))\"\n  using multiset_prod_fact_insert[of \"A - {#x#}\" x] by simp\n\nlemma card_permutations_of_multiset_aux:\n  \"card (permutations_of_multiset A) * (\\<Prod>x\\<in>set_mset A. fact (count A x)) = fact (size A)\"\nproof (induction A rule: multiset_remove_induct)\n  case (remove A)\n  have \"card (permutations_of_multiset A) = \n          card (\\<Union>x\\<in>set_mset A. (#) x ` permutations_of_multiset (A - {#x#}))\"\n    by (simp add: permutations_of_multiset_nonempty remove.hyps)\n  also have \"\\<dots> = (\\<Sum>x\\<in>set_mset A. card (permutations_of_multiset (A - {#x#})))\"\n    by (subst card_UN_disjoint) (auto simp: card_image)\n  also have \"\\<dots> * (\\<Prod>x\\<in>set_mset A. fact (count A x)) = \n               (\\<Sum>x\\<in>set_mset A. card (permutations_of_multiset (A - {#x#})) * \n                 (\\<Prod>y\\<in>set_mset A. fact (count A y)))\"\n    by (subst sum_distrib_right) simp_all\n  also have \"\\<dots> = (\\<Sum>x\\<in>set_mset A. count A x * fact (size A - 1))\"\n  proof (intro sum.cong refl)\n    fix x assume x: \"x \\<in># A\"\n    have \"card (permutations_of_multiset (A - {#x#})) * (\\<Prod>y\\<in>set_mset A. fact (count A y)) = \n            count A x * (card (permutations_of_multiset (A - {#x#})) * \n              (\\<Prod>y\\<in>set_mset (A - {#x#}). fact (count (A - {#x#}) y)))\" (is \"?lhs = _\")\n      by (subst multiset_prod_fact_remove[OF x]) simp_all\n    also note remove.IH[OF x]\n    also from x have \"size (A - {#x#}) = size A - 1\" by (simp add: size_Diff_submset)\n    finally show \"?lhs = count A x * fact (size A - 1)\" .\n  qed\n  also have \"(\\<Sum>x\\<in>set_mset A. count A x * fact (size A - 1)) =\n                size A * fact (size A - 1)\"\n    by (simp add: sum_distrib_right size_multiset_overloaded_eq)\n  also from remove.hyps have \"\\<dots> = fact (size A)\"\n    by (cases \"size A\") auto\n  finally show ?case .\nqed simp_all\n\ntheorem card_permutations_of_multiset:\n  \"card (permutations_of_multiset A) = fact (size A) div (\\<Prod>x\\<in>set_mset A. fact (count A x))\"\n  \"(\\<Prod>x\\<in>set_mset A. fact (count A x) :: nat) dvd fact (size A)\"\n  by (simp_all flip: card_permutations_of_multiset_aux[of A])\n\nlemma card_permutations_of_multiset_insert_aux:\n  \"card (permutations_of_multiset (A + {#x#})) * (count A x + 1) = \n      (size A + 1) * card (permutations_of_multiset A)\"\nproof -\n  note card_permutations_of_multiset_aux[of \"A + {#x#}\"]\n  also have \"fact (size (A + {#x#})) = (size A + 1) * fact (size A)\" by simp\n  also note multiset_prod_fact_insert[of A x]\n  also note card_permutations_of_multiset_aux[of A, symmetric]\n  finally have \"card (permutations_of_multiset (A + {#x#})) * (count A x + 1) *\n                    (\\<Prod>y\\<in>set_mset A. fact (count A y)) =\n                (size A + 1) * card (permutations_of_multiset A) *\n                    (\\<Prod>x\\<in>set_mset A. fact (count A x))\" by (simp only: mult_ac)\n  thus ?thesis by (subst (asm) mult_right_cancel) simp_all\nqed\n\nlemma card_permutations_of_multiset_remove_aux:\n  assumes \"x \\<in># A\"\n  shows   \"card (permutations_of_multiset A) * count A x = \n             size A * card (permutations_of_multiset (A - {#x#}))\"\nproof -\n  from assms have A: \"A - {#x#} + {#x#} = A\" by simp\n  from assms have B: \"size A = size (A - {#x#}) + 1\" \n    by (subst A [symmetric], subst size_union) simp\n  show ?thesis\n    using card_permutations_of_multiset_insert_aux[of \"A - {#x#}\" x, unfolded A] assms\n    by (simp add: B)\nqed\n\nlemma real_card_permutations_of_multiset_remove:\n  assumes \"x \\<in># A\"\n  shows   \"real (card (permutations_of_multiset (A - {#x#}))) = \n             real (card (permutations_of_multiset A) * count A x) / real (size A)\"\n  using assms by (subst card_permutations_of_multiset_remove_aux[OF assms]) auto\n\nlemma real_card_permutations_of_multiset_remove':\n  assumes \"x \\<in># A\"\n  shows   \"real (card (permutations_of_multiset A)) = \n             real (size A * card (permutations_of_multiset (A - {#x#}))) / real (count A x)\"\n  using assms by (subst card_permutations_of_multiset_remove_aux[OF assms, symmetric]) simp\n\nend\n\n\n\nsubsection \\<open>Permutations of a set\\<close>\n\ndefinition permutations_of_set :: \"'a set \\<Rightarrow> 'a list set\" where\n  \"permutations_of_set A = {xs. set xs = A \\<and> distinct xs}\"\n\nlemma permutations_of_set_altdef:\n  \"finite A \\<Longrightarrow> permutations_of_set A = permutations_of_multiset (mset_set A)\"\n  by (auto simp add: permutations_of_set_def permutations_of_multiset_def mset_set_set \n        in_multiset_in_set [symmetric] mset_eq_mset_set_imp_distinct)\n\nlemma permutations_of_setI [intro]:\n  assumes \"set xs = A\" \"distinct xs\"\n  shows   \"xs \\<in> permutations_of_set A\"\n  using assms unfolding permutations_of_set_def by simp\n  \nlemma permutations_of_setD:\n  assumes \"xs \\<in> permutations_of_set A\"\n  shows   \"set xs = A\" \"distinct xs\"\n  using assms unfolding permutations_of_set_def by simp_all\n  \nlemma permutations_of_set_lists: \"permutations_of_set A \\<subseteq> lists A\"\n  unfolding permutations_of_set_def by auto\n\nlemma permutations_of_set_empty [simp]: \"permutations_of_set {} = {[]}\"\n  by (auto simp: permutations_of_set_def)\n  \nlemma UN_set_permutations_of_set [simp]:\n  \"finite A \\<Longrightarrow> (\\<Union>xs\\<in>permutations_of_set A. set xs) = A\"\n  using finite_distinct_list by (auto simp: permutations_of_set_def)\n\nlemma permutations_of_set_infinite:\n  \"\\<not>finite A \\<Longrightarrow> permutations_of_set A = {}\"\n  by (auto simp: permutations_of_set_def)\n\nlemma permutations_of_set_nonempty:\n  \"A \\<noteq> {} \\<Longrightarrow> permutations_of_set A = \n                  (\\<Union>x\\<in>A. (\\<lambda>xs. x # xs) ` permutations_of_set (A - {x}))\"\n  by (cases \"finite A\")\n     (simp_all add: permutations_of_multiset_nonempty mset_set_empty_iff mset_set_Diff \n                    permutations_of_set_altdef permutations_of_set_infinite)\n    \nlemma permutations_of_set_singleton [simp]: \"permutations_of_set {x} = {[x]}\"\n  by (subst permutations_of_set_nonempty) auto\n\nlemma permutations_of_set_doubleton: \n  \"x \\<noteq> y \\<Longrightarrow> permutations_of_set {x,y} = {[x,y], [y,x]}\"\n  by (subst permutations_of_set_nonempty) \n     (simp_all add: insert_Diff_if insert_commute)\n\nlemma rev_permutations_of_set [simp]:\n  \"rev ` permutations_of_set A = permutations_of_set A\"\n  by (cases \"finite A\") (simp_all add: permutations_of_set_altdef permutations_of_set_infinite)\n\nlemma length_finite_permutations_of_set:\n  \"xs \\<in> permutations_of_set A \\<Longrightarrow> length xs = card A\"\n  by (auto simp: permutations_of_set_def distinct_card)\n\nlemma finite_permutations_of_set [simp]: \"finite (permutations_of_set A)\"\n  by (cases \"finite A\") (simp_all add: permutations_of_set_infinite permutations_of_set_altdef)\n\nlemma permutations_of_set_empty_iff [simp]:\n  \"permutations_of_set A = {} \\<longleftrightarrow> \\<not>finite A\"\n  unfolding permutations_of_set_def using finite_distinct_list[of A] by auto\n\nlemma card_permutations_of_set [simp]:\n  \"finite A \\<Longrightarrow> card (permutations_of_set A) = fact (card A)\"\n  by (simp add: permutations_of_set_altdef card_permutations_of_multiset del: One_nat_def)\n\nlemma permutations_of_set_image_inj:\n  assumes inj: \"inj_on f A\"\n  shows   \"permutations_of_set (f ` A) = map f ` permutations_of_set A\"\n  by (cases \"finite A\")\n     (simp_all add: permutations_of_set_infinite permutations_of_set_altdef\n                    permutations_of_multiset_image mset_set_image_inj inj finite_image_iff)\n\nlemma permutations_of_set_image_permutes:\n  \"\\<sigma> permutes A \\<Longrightarrow> map \\<sigma> ` permutations_of_set A = permutations_of_set A\"\n  by (subst permutations_of_set_image_inj [symmetric])\n     (simp_all add: permutes_inj_on permutes_image)\n\n\nsubsection \\<open>Code generation\\<close>\n\ntext \\<open>\n  First, we give code an implementation for permutations of lists.\n\\<close>\n\ndeclare length_remove1 [termination_simp] \n\nfun permutations_of_list_impl where\n  \"permutations_of_list_impl xs = (if xs = [] then [[]] else\n     List.bind (remdups xs) (\\<lambda>x. map ((#) x) (permutations_of_list_impl (remove1 x xs))))\"\n\nfun permutations_of_list_impl_aux where\n  \"permutations_of_list_impl_aux acc xs = (if xs = [] then [acc] else\n     List.bind (remdups xs) (\\<lambda>x. permutations_of_list_impl_aux (x#acc) (remove1 x xs)))\"\n\ndeclare permutations_of_list_impl_aux.simps [simp del]    \ndeclare permutations_of_list_impl.simps [simp del]\n    \nlemma permutations_of_list_impl_Nil [simp]:\n  \"permutations_of_list_impl [] = [[]]\"\n  by (simp add: permutations_of_list_impl.simps)\n\nlemma permutations_of_list_impl_nonempty:\n  \"xs \\<noteq> [] \\<Longrightarrow> permutations_of_list_impl xs = \n     List.bind (remdups xs) (\\<lambda>x. map ((#) x) (permutations_of_list_impl (remove1 x xs)))\"\n  by (subst permutations_of_list_impl.simps) simp_all\n\nlemma set_permutations_of_list_impl:\n  \"set (permutations_of_list_impl xs) = permutations_of_multiset (mset xs)\"\n  by (induction xs rule: permutations_of_list_impl.induct)\n     (subst permutations_of_list_impl.simps, \n      simp_all add: permutations_of_multiset_nonempty set_list_bind)\n\nlemma distinct_permutations_of_list_impl:\n  \"distinct (permutations_of_list_impl xs)\"\n  by (induction xs rule: permutations_of_list_impl.induct, \n      subst permutations_of_list_impl.simps)\n     (auto intro!: distinct_list_bind simp: distinct_map o_def disjoint_family_on_def)\n\nlemma permutations_of_list_impl_aux_correct':\n  \"permutations_of_list_impl_aux acc xs = \n     map (\\<lambda>xs. rev xs @ acc) (permutations_of_list_impl xs)\"\n  by (induction acc xs rule: permutations_of_list_impl_aux.induct,\n      subst permutations_of_list_impl_aux.simps, subst permutations_of_list_impl.simps)\n     (auto simp: map_list_bind intro!: list_bind_cong)\n    \nlemma permutations_of_list_impl_aux_correct:\n  \"permutations_of_list_impl_aux [] xs = map rev (permutations_of_list_impl xs)\"\n  by (simp add: permutations_of_list_impl_aux_correct')\n\nlemma distinct_permutations_of_list_impl_aux:\n  \"distinct (permutations_of_list_impl_aux acc xs)\"\n  by (simp add: permutations_of_list_impl_aux_correct' distinct_map \n        distinct_permutations_of_list_impl inj_on_def)\n\nlemma set_permutations_of_list_impl_aux:\n  \"set (permutations_of_list_impl_aux [] xs) = permutations_of_multiset (mset xs)\"\n  by (simp add: permutations_of_list_impl_aux_correct set_permutations_of_list_impl)\n  \ndeclare set_permutations_of_list_impl_aux [symmetric, code]\n\nvalue [code] \"permutations_of_multiset {#1,2,3,4::int#}\"\n\n\n\ntext \\<open>\n  Now we turn to permutations of sets. We define an auxiliary version with an \n  accumulator to avoid having to map over the results.\n\\<close>\nfunction permutations_of_set_aux where\n  \"permutations_of_set_aux acc A = \n     (if \\<not>finite A then {} else if A = {} then {acc} else \n        (\\<Union>x\\<in>A. permutations_of_set_aux (x#acc) (A - {x})))\"\nby auto\ntermination by (relation \"Wellfounded.measure (card \\<circ> snd)\") (simp_all add: card_gt_0_iff)\n\nlemma permutations_of_set_aux_altdef:\n  \"permutations_of_set_aux acc A = (\\<lambda>xs. rev xs @ acc) ` permutations_of_set A\"\nproof (cases \"finite A\")\n  assume \"finite A\"\n  thus ?thesis\n  proof (induction A arbitrary: acc rule: finite_psubset_induct)\n    case (psubset A acc)\n    show ?case\n    proof (cases \"A = {}\")\n      case False\n      note [simp del] = permutations_of_set_aux.simps\n      from psubset.hyps False \n        have \"permutations_of_set_aux acc A = \n                (\\<Union>y\\<in>A. permutations_of_set_aux (y#acc) (A - {y}))\"\n        by (subst permutations_of_set_aux.simps) simp_all\n      also have \"\\<dots> = (\\<Union>y\\<in>A. (\\<lambda>xs. rev xs @ acc) ` (\\<lambda>xs. y # xs) ` permutations_of_set (A - {y}))\"\n        apply (rule arg_cong [of _ _ Union], rule image_cong)\n         apply (simp_all add: image_image)\n        apply (subst psubset)\n         apply auto\n        done\n      also from False have \"\\<dots> = (\\<lambda>xs. rev xs @ acc) ` permutations_of_set A\"\n        by (subst (2) permutations_of_set_nonempty) (simp_all add: image_UN)\n      finally show ?thesis .\n    qed simp_all\n  qed\nqed (simp_all add: permutations_of_set_infinite)\n\ndeclare permutations_of_set_aux.simps [simp del]\n\nlemma permutations_of_set_aux_correct:\n  \"permutations_of_set_aux [] A = permutations_of_set A\"\n  by (simp add: permutations_of_set_aux_altdef)\n\n\ntext \\<open>\n  In another refinement step, we define a version on lists.\n\\<close>\ndeclare length_remove1 [termination_simp]\n\nfun permutations_of_set_aux_list where\n  \"permutations_of_set_aux_list acc xs = \n     (if xs = [] then [acc] else \n        List.bind xs (\\<lambda>x. permutations_of_set_aux_list (x#acc) (List.remove1 x xs)))\"\n\ndefinition permutations_of_set_list where\n  \"permutations_of_set_list xs = permutations_of_set_aux_list [] xs\"\n\ndeclare permutations_of_set_aux_list.simps [simp del]\n\nlemma permutations_of_set_aux_list_refine:\n  assumes \"distinct xs\"\n  shows   \"set (permutations_of_set_aux_list acc xs) = permutations_of_set_aux acc (set xs)\"\n  using assms\n  by (induction acc xs rule: permutations_of_set_aux_list.induct)\n     (subst permutations_of_set_aux_list.simps,\n      subst permutations_of_set_aux.simps,\n      simp_all add: set_list_bind)\n\n\ntext \\<open>\n  The permutation lists contain no duplicates if the inputs contain no duplicates.\n  Therefore, these functions can easily be used when working with a representation of\n  sets by distinct lists.\n  The same approach should generalise to any kind of set implementation that supports\n  a monadic bind operation, and since the results are disjoint, merging should be cheap.\n\\<close>\nlemma distinct_permutations_of_set_aux_list:\n  \"distinct xs \\<Longrightarrow> distinct (permutations_of_set_aux_list acc xs)\"\n  by (induction acc xs rule: permutations_of_set_aux_list.induct)\n     (subst permutations_of_set_aux_list.simps,\n      auto intro!: distinct_list_bind simp: disjoint_family_on_def \n         permutations_of_set_aux_list_refine permutations_of_set_aux_altdef)\n\nlemma distinct_permutations_of_set_list:\n    \"distinct xs \\<Longrightarrow> distinct (permutations_of_set_list xs)\"\n  by (simp add: permutations_of_set_list_def distinct_permutations_of_set_aux_list)\n\nlemma permutations_of_list:\n    \"permutations_of_set (set xs) = set (permutations_of_set_list (remdups xs))\"\n  by (simp add: permutations_of_set_aux_correct [symmetric] \n        permutations_of_set_aux_list_refine permutations_of_set_list_def)\n\nlemma permutations_of_list_code [code]:\n  \"permutations_of_set (set xs) = set (permutations_of_set_list (remdups xs))\"\n  \"permutations_of_set (List.coset xs) = \n     Code.abort (STR ''Permutation of set complement not supported'') \n       (\\<lambda>_. permutations_of_set (List.coset xs))\"\n  by (simp_all add: permutations_of_list)\n\nvalue [code] \"permutations_of_set (set ''abcd'')\"\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Library/Multiset_Permutations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357632379241, "lm_q2_score": 0.8887587993853655, "lm_q1q2_score": 0.7705856639595114}}
{"text": "(*  Title:      HOL/Euclidean_Division.thy\n    Author:     Manuel Eberl, TU Muenchen\n    Author:     Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>Division in euclidean (semi)rings\\<close>\n\ntheory Euclidean_Division\n  imports Int Lattices_Big\nbegin\n\nsubsection \\<open>Euclidean (semi)rings with explicit division and remainder\\<close>\n\nclass euclidean_semiring = semidom_modulo +\n  fixes euclidean_size :: \"'a \\<Rightarrow> nat\"\n  assumes size_0 [simp]: \"euclidean_size 0 = 0\"\n  assumes mod_size_less:\n    \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size (a mod b) < euclidean_size b\"\n  assumes size_mult_mono:\n    \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size a \\<le> euclidean_size (a * b)\"\nbegin\n\nlemma euclidean_size_eq_0_iff [simp]:\n  \"euclidean_size b = 0 \\<longleftrightarrow> b = 0\"\nproof\n  assume \"b = 0\"\n  then show \"euclidean_size b = 0\"\n    by simp\nnext\n  assume \"euclidean_size b = 0\"\n  show \"b = 0\"\n  proof (rule ccontr)\n    assume \"b \\<noteq> 0\"\n    with mod_size_less have \"euclidean_size (b mod b) < euclidean_size b\" .\n    with \\<open>euclidean_size b = 0\\<close> show False\n      by simp\n  qed\nqed\n\nlemma euclidean_size_greater_0_iff [simp]:\n  \"euclidean_size b > 0 \\<longleftrightarrow> b \\<noteq> 0\"\n  using euclidean_size_eq_0_iff [symmetric, of b] by safe simp\n\nlemma size_mult_mono': \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size a \\<le> euclidean_size (b * a)\"\n  by (subst mult.commute) (rule size_mult_mono)\n\nlemma dvd_euclidean_size_eq_imp_dvd:\n  assumes \"a \\<noteq> 0\" and \"euclidean_size a = euclidean_size b\"\n    and \"b dvd a\"\n  shows \"a dvd b\"\nproof (rule ccontr)\n  assume \"\\<not> a dvd b\"\n  hence \"b mod a \\<noteq> 0\" using mod_0_imp_dvd [of b a] by blast\n  then have \"b mod a \\<noteq> 0\" by (simp add: mod_eq_0_iff_dvd)\n  from \\<open>b dvd a\\<close> have \"b dvd b mod a\" by (simp add: dvd_mod_iff)\n  then obtain c where \"b mod a = b * c\" unfolding dvd_def by blast\n    with \\<open>b mod a \\<noteq> 0\\<close> have \"c \\<noteq> 0\" by auto\n  with \\<open>b mod a = b * c\\<close> have \"euclidean_size (b mod a) \\<ge> euclidean_size b\"\n    using size_mult_mono by force\n  moreover from \\<open>\\<not> a dvd b\\<close> and \\<open>a \\<noteq> 0\\<close>\n  have \"euclidean_size (b mod a) < euclidean_size a\"\n    using mod_size_less by blast\n  ultimately show False using \\<open>euclidean_size a = euclidean_size b\\<close>\n    by simp\nqed\n\nlemma euclidean_size_times_unit:\n  assumes \"is_unit a\"\n  shows   \"euclidean_size (a * b) = euclidean_size b\"\nproof (rule antisym)\n  from assms have [simp]: \"a \\<noteq> 0\" by auto\n  thus \"euclidean_size (a * b) \\<ge> euclidean_size b\" by (rule size_mult_mono')\n  from assms have \"is_unit (1 div a)\" by simp\n  hence \"1 div a \\<noteq> 0\" by (intro notI) simp_all\n  hence \"euclidean_size (a * b) \\<le> euclidean_size ((1 div a) * (a * b))\"\n    by (rule size_mult_mono')\n  also from assms have \"(1 div a) * (a * b) = b\"\n    by (simp add: algebra_simps unit_div_mult_swap)\n  finally show \"euclidean_size (a * b) \\<le> euclidean_size b\" .\nqed\n\nlemma euclidean_size_unit:\n  \"is_unit a \\<Longrightarrow> euclidean_size a = euclidean_size 1\"\n  using euclidean_size_times_unit [of a 1] by simp\n\nlemma unit_iff_euclidean_size:\n  \"is_unit a \\<longleftrightarrow> euclidean_size a = euclidean_size 1 \\<and> a \\<noteq> 0\"\nproof safe\n  assume A: \"a \\<noteq> 0\" and B: \"euclidean_size a = euclidean_size 1\"\n  show \"is_unit a\"\n    by (rule dvd_euclidean_size_eq_imp_dvd [OF A B]) simp_all\nqed (auto intro: euclidean_size_unit)\n\nlemma euclidean_size_times_nonunit:\n  assumes \"a \\<noteq> 0\" \"b \\<noteq> 0\" \"\\<not> is_unit a\"\n  shows   \"euclidean_size b < euclidean_size (a * b)\"\nproof (rule ccontr)\n  assume \"\\<not>euclidean_size b < euclidean_size (a * b)\"\n  with size_mult_mono'[OF assms(1), of b]\n    have eq: \"euclidean_size (a * b) = euclidean_size b\" by simp\n  have \"a * b dvd b\"\n    by (rule dvd_euclidean_size_eq_imp_dvd [OF _ eq])\n       (use assms in simp_all)\n  hence \"a * b dvd 1 * b\" by simp\n  with \\<open>b \\<noteq> 0\\<close> have \"is_unit a\" by (subst (asm) dvd_times_right_cancel_iff)\n  with assms(3) show False by contradiction\nqed\n\nlemma dvd_imp_size_le:\n  assumes \"a dvd b\" \"b \\<noteq> 0\"\n  shows   \"euclidean_size a \\<le> euclidean_size b\"\n  using assms by (auto simp: size_mult_mono)\n\nlemma dvd_proper_imp_size_less:\n  assumes \"a dvd b\" \"\\<not> b dvd a\" \"b \\<noteq> 0\"\n  shows   \"euclidean_size a < euclidean_size b\"\nproof -\n  from assms(1) obtain c where \"b = a * c\" by (erule dvdE)\n  hence z: \"b = c * a\" by (simp add: mult.commute)\n  from z assms have \"\\<not>is_unit c\" by (auto simp: mult.commute mult_unit_dvd_iff)\n  with z assms show ?thesis\n    by (auto intro!: euclidean_size_times_nonunit)\nqed\n\nlemma unit_imp_mod_eq_0:\n  \"a mod b = 0\" if \"is_unit b\"\n  using that by (simp add: mod_eq_0_iff_dvd unit_imp_dvd)\n\nlemma mod_eq_self_iff_div_eq_0:\n  \"a mod b = a \\<longleftrightarrow> a div b = 0\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  with div_mult_mod_eq [of a b] show ?Q\n    by auto\nnext\n  assume ?Q\n  with div_mult_mod_eq [of a b] show ?P\n    by simp\nqed\n\nlemma coprime_mod_left_iff [simp]:\n  \"coprime (a mod b) b \\<longleftrightarrow> coprime a b\" if \"b \\<noteq> 0\"\n  by (rule iffI; rule coprimeI)\n    (use that in \\<open>auto dest!: dvd_mod_imp_dvd coprime_common_divisor simp add: dvd_mod_iff\\<close>)\n\nlemma coprime_mod_right_iff [simp]:\n  \"coprime a (b mod a) \\<longleftrightarrow> coprime a b\" if \"a \\<noteq> 0\"\n  using that coprime_mod_left_iff [of a b] by (simp add: ac_simps)\n\nend\n\nclass euclidean_ring = idom_modulo + euclidean_semiring\nbegin\n\nlemma dvd_diff_commute [ac_simps]:\n  \"a dvd c - b \\<longleftrightarrow> a dvd b - c\"\nproof -\n  have \"a dvd c - b \\<longleftrightarrow> a dvd (c - b) * - 1\"\n    by (subst dvd_mult_unit_iff) simp_all\n  then show ?thesis\n    by simp\nqed\n\nend\n\n\nsubsection \\<open>Euclidean (semi)rings with cancel rules\\<close>\n\nclass euclidean_semiring_cancel = euclidean_semiring +\n  assumes div_mult_self1 [simp]: \"b \\<noteq> 0 \\<Longrightarrow> (a + c * b) div b = c + a div b\"\n  and div_mult_mult1 [simp]: \"c \\<noteq> 0 \\<Longrightarrow> (c * a) div (c * b) = a div b\"\nbegin\n\nlemma div_mult_self2 [simp]:\n  assumes \"b \\<noteq> 0\"\n  shows \"(a + b * c) div b = c + a div b\"\n  using assms div_mult_self1 [of b a c] by (simp add: mult.commute)\n\nlemma div_mult_self3 [simp]:\n  assumes \"b \\<noteq> 0\"\n  shows \"(c * b + a) div b = c + a div b\"\n  using assms by (simp add: add.commute)\n\nlemma div_mult_self4 [simp]:\n  assumes \"b \\<noteq> 0\"\n  shows \"(b * c + a) div b = c + a div b\"\n  using assms by (simp add: add.commute)\n\nlemma mod_mult_self1 [simp]: \"(a + c * b) mod b = a mod b\"\nproof (cases \"b = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  have \"a + c * b = (a + c * b) div b * b + (a + c * b) mod b\"\n    by (simp add: div_mult_mod_eq)\n  also from False div_mult_self1 [of b a c] have\n    \"\\<dots> = (c + a div b) * b + (a + c * b) mod b\"\n      by (simp add: algebra_simps)\n  finally have \"a = a div b * b + (a + c * b) mod b\"\n    by (simp add: add.commute [of a] add.assoc distrib_right)\n  then have \"a div b * b + (a + c * b) mod b = a div b * b + a mod b\"\n    by (simp add: div_mult_mod_eq)\n  then show ?thesis by simp\nqed\n\nlemma mod_mult_self2 [simp]:\n  \"(a + b * c) mod b = a mod b\"\n  by (simp add: mult.commute [of b])\n\nlemma mod_mult_self3 [simp]:\n  \"(c * b + a) mod b = a mod b\"\n  by (simp add: add.commute)\n\nlemma mod_mult_self4 [simp]:\n  \"(b * c + a) mod b = a mod b\"\n  by (simp add: add.commute)\n\nlemma mod_mult_self1_is_0 [simp]:\n  \"b * a mod b = 0\"\n  using mod_mult_self2 [of 0 b a] by simp\n\nlemma mod_mult_self2_is_0 [simp]:\n  \"a * b mod b = 0\"\n  using mod_mult_self1 [of 0 a b] by simp\n\nlemma div_add_self1:\n  assumes \"b \\<noteq> 0\"\n  shows \"(b + a) div b = a div b + 1\"\n  using assms div_mult_self1 [of b a 1] by (simp add: add.commute)\n\nlemma div_add_self2:\n  assumes \"b \\<noteq> 0\"\n  shows \"(a + b) div b = a div b + 1\"\n  using assms div_add_self1 [of b a] by (simp add: add.commute)\n\nlemma mod_add_self1 [simp]:\n  \"(b + a) mod b = a mod b\"\n  using mod_mult_self1 [of a 1 b] by (simp add: add.commute)\n\nlemma mod_add_self2 [simp]:\n  \"(a + b) mod b = a mod b\"\n  using mod_mult_self1 [of a 1 b] by simp\n\nlemma mod_div_trivial [simp]:\n  \"a mod b div b = 0\"\nproof (cases \"b = 0\")\n  assume \"b = 0\"\n  thus ?thesis by simp\nnext\n  assume \"b \\<noteq> 0\"\n  hence \"a div b + a mod b div b = (a mod b + a div b * b) div b\"\n    by (rule div_mult_self1 [symmetric])\n  also have \"\\<dots> = a div b\"\n    by (simp only: mod_div_mult_eq)\n  also have \"\\<dots> = a div b + 0\"\n    by simp\n  finally show ?thesis\n    by (rule add_left_imp_eq)\nqed\n\nlemma mod_mod_trivial [simp]:\n  \"a mod b mod b = a mod b\"\nproof -\n  have \"a mod b mod b = (a mod b + a div b * b) mod b\"\n    by (simp only: mod_mult_self1)\n  also have \"\\<dots> = a mod b\"\n    by (simp only: mod_div_mult_eq)\n  finally show ?thesis .\nqed\n\nlemma mod_mod_cancel:\n  assumes \"c dvd b\"\n  shows \"a mod b mod c = a mod c\"\nproof -\n  from \\<open>c dvd b\\<close> obtain k where \"b = c * k\"\n    by (rule dvdE)\n  have \"a mod b mod c = a mod (c * k) mod c\"\n    by (simp only: \\<open>b = c * k\\<close>)\n  also have \"\\<dots> = (a mod (c * k) + a div (c * k) * k * c) mod c\"\n    by (simp only: mod_mult_self1)\n  also have \"\\<dots> = (a div (c * k) * (c * k) + a mod (c * k)) mod c\"\n    by (simp only: ac_simps)\n  also have \"\\<dots> = a mod c\"\n    by (simp only: div_mult_mod_eq)\n  finally show ?thesis .\nqed\n\nlemma div_mult_mult2 [simp]:\n  \"c \\<noteq> 0 \\<Longrightarrow> (a * c) div (b * c) = a div b\"\n  by (drule div_mult_mult1) (simp add: mult.commute)\n\nlemma div_mult_mult1_if [simp]:\n  \"(c * a) div (c * b) = (if c = 0 then 0 else a div b)\"\n  by simp_all\n\nlemma mod_mult_mult1:\n  \"(c * a) mod (c * b) = c * (a mod b)\"\nproof (cases \"c = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  from div_mult_mod_eq\n  have \"((c * a) div (c * b)) * (c * b) + (c * a) mod (c * b) = c * a\" .\n  with False have \"c * ((a div b) * b + a mod b) + (c * a) mod (c * b)\n    = c * a + c * (a mod b)\" by (simp add: algebra_simps)\n  with div_mult_mod_eq show ?thesis by simp\nqed\n\nlemma mod_mult_mult2:\n  \"(a * c) mod (b * c) = (a mod b) * c\"\n  using mod_mult_mult1 [of c a b] by (simp add: mult.commute)\n\nlemma mult_mod_left: \"(a mod b) * c = (a * c) mod (b * c)\"\n  by (fact mod_mult_mult2 [symmetric])\n\nlemma mult_mod_right: \"c * (a mod b) = (c * a) mod (c * b)\"\n  by (fact mod_mult_mult1 [symmetric])\n\nlemma dvd_mod: \"k dvd m \\<Longrightarrow> k dvd n \\<Longrightarrow> k dvd (m mod n)\"\n  unfolding dvd_def by (auto simp add: mod_mult_mult1)\n\nlemma div_plus_div_distrib_dvd_left:\n  \"c dvd a \\<Longrightarrow> (a + b) div c = a div c + b div c\"\n  by (cases \"c = 0\") auto\n\nlemma div_plus_div_distrib_dvd_right:\n  \"c dvd b \\<Longrightarrow> (a + b) div c = a div c + b div c\"\n  using div_plus_div_distrib_dvd_left [of c b a]\n  by (simp add: ac_simps)\n\nlemma sum_div_partition:\n  \\<open>(\\<Sum>a\\<in>A. f a) div b = (\\<Sum>a\\<in>A \\<inter> {a. b dvd f a}. f a div b) + (\\<Sum>a\\<in>A \\<inter> {a. \\<not> b dvd f a}. f a) div b\\<close>\n    if \\<open>finite A\\<close>\nproof -\n  have \\<open>A = A \\<inter> {a. b dvd f a} \\<union> A \\<inter> {a. \\<not> b dvd f a}\\<close>\n    by auto\n  then have \\<open>(\\<Sum>a\\<in>A. f a) = (\\<Sum>a\\<in>A \\<inter> {a. b dvd f a} \\<union> A \\<inter> {a. \\<not> b dvd f a}. f a)\\<close>\n    by simp\n  also have \\<open>\\<dots> = (\\<Sum>a\\<in>A \\<inter> {a. b dvd f a}. f a) + (\\<Sum>a\\<in>A \\<inter> {a. \\<not> b dvd f a}. f a)\\<close>\n    using \\<open>finite A\\<close> by (auto intro: sum.union_inter_neutral)\n  finally have *: \\<open>sum f A = sum f (A \\<inter> {a. b dvd f a}) + sum f (A \\<inter> {a. \\<not> b dvd f a})\\<close> .\n  define B where B: \\<open>B = A \\<inter> {a. b dvd f a}\\<close>\n  with \\<open>finite A\\<close> have \\<open>finite B\\<close> and \\<open>a \\<in> B \\<Longrightarrow> b dvd f a\\<close> for a\n    by simp_all\n  then have \\<open>(\\<Sum>a\\<in>B. f a) div b = (\\<Sum>a\\<in>B. f a div b)\\<close> and \\<open>b dvd (\\<Sum>a\\<in>B. f a)\\<close>\n    by induction (simp_all add: div_plus_div_distrib_dvd_left)\n  then show ?thesis using *\n    by (simp add: B div_plus_div_distrib_dvd_left)\nqed\n\nnamed_theorems mod_simps\n\ntext \\<open>Addition respects modular equivalence.\\<close>\n\nlemma mod_add_left_eq [mod_simps]:\n  \"(a mod c + b) mod c = (a + b) mod c\"\nproof -\n  have \"(a + b) mod c = (a div c * c + a mod c + b) mod c\"\n    by (simp only: div_mult_mod_eq)\n  also have \"\\<dots> = (a mod c + b + a div c * c) mod c\"\n    by (simp only: ac_simps)\n  also have \"\\<dots> = (a mod c + b) mod c\"\n    by (rule mod_mult_self1)\n  finally show ?thesis\n    by (rule sym)\nqed\n\nlemma mod_add_right_eq [mod_simps]:\n  \"(a + b mod c) mod c = (a + b) mod c\"\n  using mod_add_left_eq [of b c a] by (simp add: ac_simps)\n\nlemma mod_add_eq:\n  \"(a mod c + b mod c) mod c = (a + b) mod c\"\n  by (simp add: mod_add_left_eq mod_add_right_eq)\n\nlemma mod_sum_eq [mod_simps]:\n  \"(\\<Sum>i\\<in>A. f i mod a) mod a = sum f A mod a\"\nproof (induct A rule: infinite_finite_induct)\n  case (insert i A)\n  then have \"(\\<Sum>i\\<in>insert i A. f i mod a) mod a\n    = (f i mod a + (\\<Sum>i\\<in>A. f i mod a)) mod a\"\n    by simp\n  also have \"\\<dots> = (f i + (\\<Sum>i\\<in>A. f i mod a) mod a) mod a\"\n    by (simp add: mod_simps)\n  also have \"\\<dots> = (f i + (\\<Sum>i\\<in>A. f i) mod a) mod a\"\n    by (simp add: insert.hyps)\n  finally show ?case\n    by (simp add: insert.hyps mod_simps)\nqed simp_all\n\nlemma mod_add_cong:\n  assumes \"a mod c = a' mod c\"\n  assumes \"b mod c = b' mod c\"\n  shows \"(a + b) mod c = (a' + b') mod c\"\nproof -\n  have \"(a mod c + b mod c) mod c = (a' mod c + b' mod c) mod c\"\n    unfolding assms ..\n  then show ?thesis\n    by (simp add: mod_add_eq)\nqed\n\ntext \\<open>Multiplication respects modular equivalence.\\<close>\n\nlemma mod_mult_left_eq [mod_simps]:\n  \"((a mod c) * b) mod c = (a * b) mod c\"\nproof -\n  have \"(a * b) mod c = ((a div c * c + a mod c) * b) mod c\"\n    by (simp only: div_mult_mod_eq)\n  also have \"\\<dots> = (a mod c * b + a div c * b * c) mod c\"\n    by (simp only: algebra_simps)\n  also have \"\\<dots> = (a mod c * b) mod c\"\n    by (rule mod_mult_self1)\n  finally show ?thesis\n    by (rule sym)\nqed\n\nlemma mod_mult_right_eq [mod_simps]:\n  \"(a * (b mod c)) mod c = (a * b) mod c\"\n  using mod_mult_left_eq [of b c a] by (simp add: ac_simps)\n\nlemma mod_mult_eq:\n  \"((a mod c) * (b mod c)) mod c = (a * b) mod c\"\n  by (simp add: mod_mult_left_eq mod_mult_right_eq)\n\nlemma mod_prod_eq [mod_simps]:\n  \"(\\<Prod>i\\<in>A. f i mod a) mod a = prod f A mod a\"\nproof (induct A rule: infinite_finite_induct)\n  case (insert i A)\n  then have \"(\\<Prod>i\\<in>insert i A. f i mod a) mod a\n    = (f i mod a * (\\<Prod>i\\<in>A. f i mod a)) mod a\"\n    by simp\n  also have \"\\<dots> = (f i * ((\\<Prod>i\\<in>A. f i mod a) mod a)) mod a\"\n    by (simp add: mod_simps)\n  also have \"\\<dots> = (f i * ((\\<Prod>i\\<in>A. f i) mod a)) mod a\"\n    by (simp add: insert.hyps)\n  finally show ?case\n    by (simp add: insert.hyps mod_simps)\nqed simp_all\n\nlemma mod_mult_cong:\n  assumes \"a mod c = a' mod c\"\n  assumes \"b mod c = b' mod c\"\n  shows \"(a * b) mod c = (a' * b') mod c\"\nproof -\n  have \"(a mod c * (b mod c)) mod c = (a' mod c * (b' mod c)) mod c\"\n    unfolding assms ..\n  then show ?thesis\n    by (simp add: mod_mult_eq)\nqed\n\ntext \\<open>Exponentiation respects modular equivalence.\\<close>\n\nlemma power_mod [mod_simps]:\n  \"((a mod b) ^ n) mod b = (a ^ n) mod b\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(a mod b) ^ Suc n mod b = (a mod b) * ((a mod b) ^ n mod b) mod b\"\n    by (simp add: mod_mult_right_eq)\n  with Suc show ?case\n    by (simp add: mod_mult_left_eq mod_mult_right_eq)\nqed\n\nlemma power_diff_power_eq:\n  \\<open>a ^ m div a ^ n = (if n \\<le> m then a ^ (m - n) else 1 div a ^ (n - m))\\<close>\n    if \\<open>a \\<noteq> 0\\<close>\nproof (cases \\<open>n \\<le> m\\<close>)\n  case True\n  with that power_diff [symmetric, of a n m] show ?thesis by simp\nnext\n  case False\n  then obtain q where n: \\<open>n = m + Suc q\\<close>\n    by (auto simp add: not_le dest: less_imp_Suc_add)\n  then have \\<open>a ^ m div a ^ n = (a ^ m * 1) div (a ^ m * a ^ Suc q)\\<close>\n    by (simp add: power_add ac_simps)\n  moreover from that have \\<open>a ^ m \\<noteq> 0\\<close>\n    by simp\n  ultimately have \\<open>a ^ m div a ^ n = 1 div a ^ Suc q\\<close>\n    by (subst (asm) div_mult_mult1) simp\n  with False n show ?thesis\n    by simp\nqed\n\nend\n\n\nclass euclidean_ring_cancel = euclidean_ring + euclidean_semiring_cancel\nbegin\n\nsubclass idom_divide ..\n\nlemma div_minus_minus [simp]: \"(- a) div (- b) = a div b\"\n  using div_mult_mult1 [of \"- 1\" a b] by simp\n\nlemma mod_minus_minus [simp]: \"(- a) mod (- b) = - (a mod b)\"\n  using mod_mult_mult1 [of \"- 1\" a b] by simp\n\nlemma div_minus_right: \"a div (- b) = (- a) div b\"\n  using div_minus_minus [of \"- a\" b] by simp\n\nlemma mod_minus_right: \"a mod (- b) = - ((- a) mod b)\"\n  using mod_minus_minus [of \"- a\" b] by simp\n\nlemma div_minus1_right [simp]: \"a div (- 1) = - a\"\n  using div_minus_right [of a 1] by simp\n\nlemma mod_minus1_right [simp]: \"a mod (- 1) = 0\"\n  using mod_minus_right [of a 1] by simp\n\ntext \\<open>Negation respects modular equivalence.\\<close>\n\nlemma mod_minus_eq [mod_simps]:\n  \"(- (a mod b)) mod b = (- a) mod b\"\nproof -\n  have \"(- a) mod b = (- (a div b * b + a mod b)) mod b\"\n    by (simp only: div_mult_mod_eq)\n  also have \"\\<dots> = (- (a mod b) + - (a div b) * b) mod b\"\n    by (simp add: ac_simps)\n  also have \"\\<dots> = (- (a mod b)) mod b\"\n    by (rule mod_mult_self1)\n  finally show ?thesis\n    by (rule sym)\nqed\n\nlemma mod_minus_cong:\n  assumes \"a mod b = a' mod b\"\n  shows \"(- a) mod b = (- a') mod b\"\nproof -\n  have \"(- (a mod b)) mod b = (- (a' mod b)) mod b\"\n    unfolding assms ..\n  then show ?thesis\n    by (simp add: mod_minus_eq)\nqed\n\ntext \\<open>Subtraction respects modular equivalence.\\<close>\n\nlemma mod_diff_left_eq [mod_simps]:\n  \"(a mod c - b) mod c = (a - b) mod c\"\n  using mod_add_cong [of a c \"a mod c\" \"- b\" \"- b\"]\n  by simp\n\nlemma mod_diff_right_eq [mod_simps]:\n  \"(a - b mod c) mod c = (a - b) mod c\"\n  using mod_add_cong [of a c a \"- b\" \"- (b mod c)\"] mod_minus_cong [of \"b mod c\" c b]\n  by simp\n\nlemma mod_diff_eq:\n  \"(a mod c - b mod c) mod c = (a - b) mod c\"\n  using mod_add_cong [of a c \"a mod c\" \"- b\" \"- (b mod c)\"] mod_minus_cong [of \"b mod c\" c b]\n  by simp\n\nlemma mod_diff_cong:\n  assumes \"a mod c = a' mod c\"\n  assumes \"b mod c = b' mod c\"\n  shows \"(a - b) mod c = (a' - b') mod c\"\n  using assms mod_add_cong [of a c a' \"- b\" \"- b'\"] mod_minus_cong [of b c \"b'\"]\n  by simp\n\nlemma minus_mod_self2 [simp]:\n  \"(a - b) mod b = a mod b\"\n  using mod_diff_right_eq [of a b b]\n  by (simp add: mod_diff_right_eq)\n\nlemma minus_mod_self1 [simp]:\n  \"(b - a) mod b = - a mod b\"\n  using mod_add_self2 [of \"- a\" b] by simp\n\nlemma mod_eq_dvd_iff:\n  \"a mod c = b mod c \\<longleftrightarrow> c dvd a - b\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then have \"(a mod c - b mod c) mod c = 0\"\n    by simp\n  then show ?Q\n    by (simp add: dvd_eq_mod_eq_0 mod_simps)\nnext\n  assume ?Q\n  then obtain d where d: \"a - b = c * d\" ..\n  then have \"a = c * d + b\"\n    by (simp add: algebra_simps)\n  then show ?P by simp\nqed\n\nlemma mod_eqE:\n  assumes \"a mod c = b mod c\"\n  obtains d where \"b = a + c * d\"\nproof -\n  from assms have \"c dvd a - b\"\n    by (simp add: mod_eq_dvd_iff)\n  then obtain d where \"a - b = c * d\" ..\n  then have \"b = a + c * - d\"\n    by (simp add: algebra_simps)\n  with that show thesis .\nqed\n\nlemma invertible_coprime:\n  \"coprime a c\" if \"a * b mod c = 1\"\n  by (rule coprimeI) (use that dvd_mod_iff [of _ c \"a * b\"] in auto)\n\nend\n\n\nsubsection \\<open>Uniquely determined division\\<close>\n\nclass unique_euclidean_semiring = euclidean_semiring +\n  assumes euclidean_size_mult: \\<open>euclidean_size (a * b) = euclidean_size a * euclidean_size b\\<close>\n  fixes division_segment :: \\<open>'a \\<Rightarrow> 'a\\<close>\n  assumes is_unit_division_segment [simp]: \\<open>is_unit (division_segment a)\\<close>\n    and division_segment_mult:\n    \\<open>a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> division_segment (a * b) = division_segment a * division_segment b\\<close>\n    and division_segment_mod:\n    \\<open>b \\<noteq> 0 \\<Longrightarrow> \\<not> b dvd a \\<Longrightarrow> division_segment (a mod b) = division_segment b\\<close>\n  assumes div_bounded:\n    \\<open>b \\<noteq> 0 \\<Longrightarrow> division_segment r = division_segment b\n    \\<Longrightarrow> euclidean_size r < euclidean_size b\n    \\<Longrightarrow> (q * b + r) div b = q\\<close>\nbegin\n\nlemma division_segment_not_0 [simp]:\n  \\<open>division_segment a \\<noteq> 0\\<close>\n  using is_unit_division_segment [of a] is_unitE [of \\<open>division_segment a\\<close>] by blast\n\nlemma euclidean_relationI [case_names by0 divides euclidean_relation]:\n  \\<open>(a div b, a mod b) = (q, r)\\<close>\n    if by0: \\<open>b = 0 \\<Longrightarrow> q = 0 \\<and> r = a\\<close>\n    and divides: \\<open>b \\<noteq> 0 \\<Longrightarrow> b dvd a \\<Longrightarrow> r = 0 \\<and> a = q * b\\<close>\n    and euclidean_relation: \\<open>b \\<noteq> 0 \\<Longrightarrow> \\<not> b dvd a \\<Longrightarrow> division_segment r = division_segment b\n      \\<and> euclidean_size r < euclidean_size b \\<and> a = q * b + r\\<close>\nproof (cases \\<open>b = 0\\<close>)\n  case True\n  with by0 show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof (cases \\<open>b dvd a\\<close>)\n    case True\n    with \\<open>b \\<noteq> 0\\<close> divides\n    show ?thesis\n      by simp\n  next\n    case False\n    with \\<open>b \\<noteq> 0\\<close> euclidean_relation\n    have \\<open>division_segment r = division_segment b\\<close>\n      \\<open>euclidean_size r < euclidean_size b\\<close> \\<open>a = q * b + r\\<close>\n      by simp_all\n    from \\<open>b \\<noteq> 0\\<close> \\<open>division_segment r = division_segment b\\<close>\n      \\<open>euclidean_size r < euclidean_size b\\<close>\n    have \\<open>(q * b + r) div b = q\\<close>\n      by (rule div_bounded)\n    with \\<open>a = q * b + r\\<close>\n    have \\<open>q = a div b\\<close>\n      by simp\n    from \\<open>a = q * b + r\\<close>\n    have \\<open>a div b * b + a mod b = q * b + r\\<close>\n      by (simp add: div_mult_mod_eq)\n    with \\<open>q = a div b\\<close>\n    have \\<open>q * b + a mod b = q * b + r\\<close>\n      by simp\n    then have \\<open>r = a mod b\\<close>\n      by simp\n    with \\<open>q = a div b\\<close>\n    show ?thesis\n      by simp\n  qed\nqed\n\nsubclass euclidean_semiring_cancel\nproof\n  fix a b c\n  assume \\<open>b \\<noteq> 0\\<close>\n  have \\<open>((a + c * b) div b, (a + c * b) mod b) = (c + a div b, a mod b)\\<close>\n  proof (cases b \\<open>c + a div b\\<close> \\<open>a mod b\\<close> \\<open>a + c * b\\<close> rule: euclidean_relationI)\n    case by0\n    with \\<open>b \\<noteq> 0\\<close>\n    show ?case\n      by simp\n  next\n    case divides\n    then show ?case\n      by (simp add: algebra_simps dvd_add_left_iff)\n  next\n    case euclidean_relation\n    then have \\<open>\\<not> b dvd a\\<close>\n      by (simp add: dvd_add_left_iff)\n    have \\<open>a mod b + (b * c + b * (a div b)) = b * c + ((a div b) * b + a mod b)\\<close>\n      by (simp add: ac_simps)\n    with \\<open>b \\<noteq> 0\\<close> have *: \\<open>a mod b + (b * c + b * (a div b)) = b * c + a\\<close>\n      by (simp add: div_mult_mod_eq)\n    from \\<open>\\<not> b dvd a\\<close> euclidean_relation show ?case\n      by (simp_all add: algebra_simps division_segment_mod mod_size_less *)\n  qed\n  then show \\<open>(a + c * b) div b = c + a div b\\<close>\n    by simp\nnext\n  fix a b c\n  assume \\<open>c \\<noteq> 0\\<close>\n  have \\<open>((c * a) div (c * b), (c * a) mod (c * b)) = (a div b, c * (a mod b))\\<close>\n  proof (cases \\<open>c * b\\<close> \\<open>a div b\\<close> \\<open>c * (a mod b)\\<close> \\<open>c * a\\<close> rule: euclidean_relationI)\n    case by0\n    with \\<open>c \\<noteq> 0\\<close> show ?case\n      by simp\n  next\n    case divides\n    then show ?case\n      by (auto simp add: algebra_simps)\n  next\n    case euclidean_relation\n    then have \\<open>b \\<noteq> 0\\<close> \\<open>a mod b \\<noteq> 0\\<close>\n      by (simp_all add: mod_eq_0_iff_dvd)\n    have \\<open>c * (a mod b) + b * (c * (a div b)) = c * ((a div b) * b + a mod b)\\<close>\n      by (simp add: algebra_simps)\n    with \\<open>b \\<noteq> 0\\<close> have *: \\<open>c * (a mod b) + b * (c * (a div b)) = c * a\\<close>\n      by (simp add: div_mult_mod_eq)\n    from \\<open>b \\<noteq> 0\\<close> \\<open>c \\<noteq> 0\\<close> have \\<open>euclidean_size c * euclidean_size (a mod b)\n      < euclidean_size c * euclidean_size b\\<close>\n      using mod_size_less [of b a] by simp\n    with euclidean_relation \\<open>b \\<noteq> 0\\<close> \\<open>a mod b \\<noteq> 0\\<close> show ?case\n      by (simp add: algebra_simps division_segment_mult division_segment_mod euclidean_size_mult *)\n  qed\n  then show \\<open>(c * a) div (c * b) = a div b\\<close>\n    by simp\nqed\n\nlemma div_eq_0_iff:\n  \\<open>a div b = 0 \\<longleftrightarrow> euclidean_size a < euclidean_size b \\<or> b = 0\\<close> (is \"_ \\<longleftrightarrow> ?P\")\n  if \\<open>division_segment a = division_segment b\\<close>\nproof (cases \\<open>a = 0 \\<or> b = 0\\<close>)\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have \\<open>a \\<noteq> 0\\<close> \\<open>b \\<noteq> 0\\<close>\n    by simp_all\n  have \\<open>a div b = 0 \\<longleftrightarrow> euclidean_size a < euclidean_size b\\<close>\n  proof\n    assume \\<open>a div b = 0\\<close>\n    then have \\<open>a mod b = a\\<close>\n      using div_mult_mod_eq [of a b] by simp\n    with \\<open>b \\<noteq> 0\\<close> mod_size_less [of b a]\n    show \\<open>euclidean_size a < euclidean_size b\\<close>\n      by simp\n  next\n    assume \\<open>euclidean_size a < euclidean_size b\\<close>\n    have \\<open>(a div b, a mod b) = (0, a)\\<close>\n    proof (cases b 0 a a rule: euclidean_relationI)\n      case by0\n      show ?case\n        by simp\n    next\n      case divides\n      with \\<open>euclidean_size a < euclidean_size b\\<close> show ?case\n        using dvd_imp_size_le [of b a] \\<open>a \\<noteq> 0\\<close> by simp\n    next\n      case euclidean_relation\n      with \\<open>euclidean_size a < euclidean_size b\\<close> that\n      show ?case\n        by simp\n    qed\n    then show \\<open>a div b = 0\\<close>\n      by simp\n  qed\n  with \\<open>b \\<noteq> 0\\<close> show ?thesis\n    by simp\nqed\n\nlemma div_mult1_eq:\n  \\<open>(a * b) div c = a * (b div c) + a * (b mod c) div c\\<close>\nproof -\n  have *: \\<open>(a * b) mod c + (a * (c * (b div c)) + c * (a * (b mod c) div c)) = a * b\\<close> (is \\<open>?A + (?B + ?C) = _\\<close>)\n  proof -\n    have \\<open>?A = a * (b mod c) mod c\\<close>\n      by (simp add: mod_mult_right_eq)\n    then have \\<open>?C + ?A = a * (b mod c)\\<close>\n      by (simp add: mult_div_mod_eq)\n    then have \\<open>?B + (?C + ?A) = a * (c * (b div c) + (b mod c))\\<close>\n      by (simp add: algebra_simps)\n    also have \\<open>\\<dots> = a * b\\<close>\n      by (simp add: mult_div_mod_eq)\n    finally show ?thesis\n      by (simp add: algebra_simps)\n  qed\n  have \\<open>((a * b) div c, (a * b) mod c) = (a * (b div c) + a * (b mod c) div c, (a * b) mod c)\\<close>\n  proof (cases c \\<open>a * (b div c) + a * (b mod c) div c\\<close> \\<open>(a * b) mod c\\<close> \\<open>a * b\\<close> rule: euclidean_relationI)\n    case by0\n    then show ?case by simp\n  next\n    case divides\n    with * show ?case\n      by (simp add: algebra_simps)\n  next\n    case euclidean_relation\n    with * show ?case\n      by (simp add: division_segment_mod mod_size_less algebra_simps)\n  qed\n  then show ?thesis\n    by simp\nqed\n\nlemma div_add1_eq:\n  \\<open>(a + b) div c = a div c + b div c + (a mod c + b mod c) div c\\<close>\nproof -\n  have *: \\<open>(a + b) mod c + (c * (a div c) + (c * (b div c) + c * ((a mod c + b mod c) div c))) = a + b\\<close>\n    (is \\<open>?A + (?B + (?C + ?D)) = _\\<close>)\n  proof -\n    have \\<open>?A + (?B + (?C + ?D)) = ?A + ?D + (?B + ?C)\\<close>\n      by (simp add: ac_simps)\n    also have \\<open>?A + ?D = (a mod c + b mod c) mod c + ?D\\<close>\n      by (simp add: mod_add_eq)\n    also have \\<open>\\<dots> = a mod c + b mod c\\<close>\n      by (simp add: mod_mult_div_eq)\n    finally have \\<open>?A + (?B + (?C + ?D)) = (a mod c + ?B) + (b mod c + ?C)\\<close>\n      by (simp add: ac_simps)\n    then show ?thesis\n      by (simp add: mod_mult_div_eq)\n  qed\n  have \\<open>((a + b) div c, (a + b) mod c) = (a div c + b div c + (a mod c + b mod c) div c, (a + b) mod c)\\<close>\n  proof (cases c \\<open>a div c + b div c + (a mod c + b mod c) div c\\<close> \\<open>(a + b) mod c\\<close> \\<open>a + b\\<close> rule: euclidean_relationI)\n    case by0\n    then show ?case\n      by simp\n  next\n    case divides\n    with * show ?case\n      by (simp add: algebra_simps)\n  next\n    case euclidean_relation\n    with * show ?case\n      by (simp add: division_segment_mod mod_size_less algebra_simps)\n  qed\n  then show ?thesis\n    by simp\nqed\n\nend\n\nclass unique_euclidean_ring = euclidean_ring + unique_euclidean_semiring\nbegin\n\nsubclass euclidean_ring_cancel ..\n\nend\n\n\nsubsection \\<open>Euclidean division on \\<^typ>\\<open>nat\\<close>\\<close>\n\ninstantiation nat :: normalization_semidom\nbegin\n\ndefinition normalize_nat :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where [simp]: \\<open>normalize = (id :: nat \\<Rightarrow> nat)\\<close>\n\ndefinition unit_factor_nat :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where \\<open>unit_factor n = of_bool (n > 0)\\<close> for n :: nat\n\nlemma unit_factor_simps [simp]:\n  \\<open>unit_factor 0 = (0::nat)\\<close>\n  \\<open>unit_factor (Suc n) = 1\\<close>\n  by (simp_all add: unit_factor_nat_def)\n\ndefinition divide_nat :: \\<open>nat \\<Rightarrow> nat \\<Rightarrow> nat\\<close>\n  where \\<open>m div n = (if n = 0 then 0 else Max {k. k * n \\<le> m})\\<close> for m n :: nat\n\ninstance\n  by standard (auto simp add: divide_nat_def ac_simps unit_factor_nat_def intro: Max_eqI)\n\nend\n\nlemma coprime_Suc_0_left [simp]:\n  \"coprime (Suc 0) n\"\n  using coprime_1_left [of n] by simp\n\nlemma coprime_Suc_0_right [simp]:\n  \"coprime n (Suc 0)\"\n  using coprime_1_right [of n] by simp\n\nlemma coprime_common_divisor_nat: \"coprime a b \\<Longrightarrow> x dvd a \\<Longrightarrow> x dvd b \\<Longrightarrow> x = 1\"\n  for a b :: nat\n  by (drule coprime_common_divisor [of _ _ x]) simp_all\n\ninstantiation nat :: unique_euclidean_semiring\nbegin\n\ndefinition euclidean_size_nat :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where [simp]: \\<open>euclidean_size_nat = id\\<close>\n\ndefinition division_segment_nat :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where [simp]: \\<open>division_segment n = 1\\<close> for n :: nat\n\ndefinition modulo_nat :: \\<open>nat \\<Rightarrow> nat \\<Rightarrow> nat\\<close>\n  where \\<open>m mod n = m - (m div n * n)\\<close> for m n :: nat\n\ninstance proof\n  fix m n :: nat\n  have ex: \"\\<exists>k. k * n \\<le> l\" for l :: nat\n    by (rule exI [of _ 0]) simp\n  have fin: \"finite {k. k * n \\<le> l}\" if \"n > 0\" for l\n  proof -\n    from that have \"{k. k * n \\<le> l} \\<subseteq> {k. k \\<le> l}\"\n      by (cases n) auto\n    then show ?thesis\n      by (rule finite_subset) simp\n  qed\n  have mult_div_unfold: \"n * (m div n) = Max {l. l \\<le> m \\<and> n dvd l}\"\n  proof (cases \"n = 0\")\n    case True\n    moreover have \"{l. l = 0 \\<and> l \\<le> m} = {0::nat}\"\n      by auto\n    ultimately show ?thesis\n      by simp\n  next\n    case False\n    with ex [of m] fin have \"n * Max {k. k * n \\<le> m} = Max (times n ` {k. k * n \\<le> m})\"\n      by (auto simp add: nat_mult_max_right intro: hom_Max_commute)\n    also have \"times n ` {k. k * n \\<le> m} = {l. l \\<le> m \\<and> n dvd l}\"\n      by (auto simp add: ac_simps elim!: dvdE)\n    finally show ?thesis\n      using False by (simp add: divide_nat_def ac_simps)\n  qed\n  have less_eq: \"m div n * n \\<le> m\"\n    by (auto simp add: mult_div_unfold ac_simps intro: Max.boundedI)\n  then show \"m div n * n + m mod n = m\"\n    by (simp add: modulo_nat_def)\n  assume \"n \\<noteq> 0\"\n  show \"euclidean_size (m mod n) < euclidean_size n\"\n  proof -\n    have \"m < Suc (m div n) * n\"\n    proof (rule ccontr)\n      assume \"\\<not> m < Suc (m div n) * n\"\n      then have \"Suc (m div n) * n \\<le> m\"\n        by (simp add: not_less)\n      moreover from \\<open>n \\<noteq> 0\\<close> have \"Max {k. k * n \\<le> m} < Suc (m div n)\"\n        by (simp add: divide_nat_def)\n      with \\<open>n \\<noteq> 0\\<close> ex fin have \"\\<And>k. k * n \\<le> m \\<Longrightarrow> k < Suc (m div n)\"\n        by auto\n      ultimately have \"Suc (m div n) < Suc (m div n)\"\n        by blast\n      then show False\n        by simp\n    qed\n    with \\<open>n \\<noteq> 0\\<close> show ?thesis\n      by (simp add: modulo_nat_def)\n  qed\n  show \"euclidean_size m \\<le> euclidean_size (m * n)\"\n    using \\<open>n \\<noteq> 0\\<close> by (cases n) simp_all\n  fix q r :: nat\n  show \"(q * n + r) div n = q\" if \"euclidean_size r < euclidean_size n\"\n  proof -\n    from that have \"r < n\"\n      by simp\n    have \"k \\<le> q\" if \"k * n \\<le> q * n + r\" for k\n    proof (rule ccontr)\n      assume \"\\<not> k \\<le> q\"\n      then have \"q < k\"\n        by simp\n      then obtain l where \"k = Suc (q + l)\"\n        by (auto simp add: less_iff_Suc_add)\n      with \\<open>r < n\\<close> that show False\n        by (simp add: algebra_simps)\n    qed\n    with \\<open>n \\<noteq> 0\\<close> ex fin show ?thesis\n      by (auto simp add: divide_nat_def Max_eq_iff)\n  qed\nqed simp_all\n\nend\n\nlemma euclidean_relation_natI [case_names by0 divides euclidean_relation]:\n  \\<open>(m div n, m mod n) = (q, r)\\<close>\n    if by0: \\<open>n = 0 \\<Longrightarrow> q = 0 \\<and> r = m\\<close>\n    and divides: \\<open>n > 0 \\<Longrightarrow> n dvd m \\<Longrightarrow> r = 0 \\<and> m = q * n\\<close>\n    and euclidean_relation: \\<open>n > 0 \\<Longrightarrow> \\<not> n dvd m \\<Longrightarrow> r < n \\<and> m = q * n + r\\<close> for m n q r :: nat\n  by (rule euclidean_relationI) (use that in simp_all)\n\nlemma div_nat_eqI:\n  \\<open>m div n = q\\<close> if \\<open>n * q \\<le> m\\<close> and \\<open>m < n * Suc q\\<close> for m n q :: nat\nproof -\n  have \\<open>(m div n, m mod n) = (q, m - n * q)\\<close>\n  proof (cases n q \\<open>m - n * q\\<close>  m rule: euclidean_relation_natI)\n    case by0\n    with that show ?case\n      by simp\n  next\n    case divides\n    from \\<open>n dvd m\\<close> obtain s where \\<open>m = n * s\\<close> ..\n    with \\<open>n > 0\\<close> that have \\<open>s < Suc q\\<close>\n      by (simp only: mult_less_cancel1)\n    with \\<open>m = n * s\\<close> \\<open>n > 0\\<close> that have \\<open>q = s\\<close>\n      by simp\n    with \\<open>m = n * s\\<close> show ?case\n      by (simp add: ac_simps)\n  next\n    case euclidean_relation\n    with that show ?case\n      by (simp add: ac_simps)\n  qed\n  then show ?thesis\n    by simp\nqed\n\nlemma mod_nat_eqI:\n  \\<open>m mod n = r\\<close> if \\<open>r < n\\<close> and \\<open>r \\<le> m\\<close> and \\<open>n dvd m - r\\<close> for m n r :: nat\nproof -\n  have \\<open>(m div n, m mod n) = ((m - r) div n, r)\\<close>\n  proof (cases n \\<open>(m - r) div n\\<close> r  m rule: euclidean_relation_natI)\n    case by0\n    with that show ?case\n      by simp\n  next\n    case divides\n    from that dvd_minus_add [of r \\<open>m\\<close> 1 n]\n    have \\<open>n dvd m + (n - r)\\<close>\n      by simp\n    with divides have \\<open>n dvd n - r\\<close>\n      by (simp add: dvd_add_right_iff)\n    then have \\<open>n \\<le> n - r\\<close>\n      by (rule dvd_imp_le) (use \\<open>r < n\\<close> in simp)\n    with \\<open>n > 0\\<close> have \\<open>r = 0\\<close>\n      by simp\n    with \\<open>n > 0\\<close> that show ?case\n      by simp\n  next\n    case euclidean_relation\n    with that show ?case\n      by (simp add: ac_simps)\n  qed\n  then show ?thesis\n    by simp\nqed\n\ntext \\<open>Tool support\\<close>\n\nML \\<open>\nstructure Cancel_Div_Mod_Nat = Cancel_Div_Mod\n(\n  val div_name = \\<^const_name>\\<open>divide\\<close>;\n  val mod_name = \\<^const_name>\\<open>modulo\\<close>;\n  val mk_binop = HOLogic.mk_binop;\n  val dest_plus = HOLogic.dest_bin \\<^const_name>\\<open>Groups.plus\\<close> HOLogic.natT;\n  val mk_sum = Arith_Data.mk_sum;\n  fun dest_sum tm =\n    if HOLogic.is_zero tm then []\n    else\n      (case try HOLogic.dest_Suc tm of\n        SOME t => HOLogic.Suc_zero :: dest_sum t\n      | NONE =>\n          (case try dest_plus tm of\n            SOME (t, u) => dest_sum t @ dest_sum u\n          | NONE => [tm]));\n\n  val div_mod_eqs = map mk_meta_eq @{thms cancel_div_mod_rules};\n\n  val prove_eq_sums = Arith_Data.prove_conv2 all_tac\n    (Arith_Data.simp_all_tac @{thms add_0_left add_0_right ac_simps})\n)\n\\<close>\n\nsimproc_setup cancel_div_mod_nat (\"(m::nat) + n\") =\n  \\<open>K Cancel_Div_Mod_Nat.proc\\<close>\n\nlemma div_mult_self_is_m [simp]:\n  \"m * n div n = m\" if \"n > 0\" for m n :: nat\n  using that by simp\n\nlemma div_mult_self1_is_m [simp]:\n  \"n * m div n = m\" if \"n > 0\" for m n :: nat\n  using that by simp\n\nlemma mod_less_divisor [simp]:\n  \"m mod n < n\" if \"n > 0\" for m n :: nat\n  using mod_size_less [of n m] that by simp\n\nlemma mod_le_divisor [simp]:\n  \"m mod n \\<le> n\" if \"n > 0\" for m n :: nat\n  using that by (auto simp add: le_less)\n\nlemma div_times_less_eq_dividend [simp]:\n  \"m div n * n \\<le> m\" for m n :: nat\n  by (simp add: minus_mod_eq_div_mult [symmetric])\n\nlemma times_div_less_eq_dividend [simp]:\n  \"n * (m div n) \\<le> m\" for m n :: nat\n  using div_times_less_eq_dividend [of m n]\n  by (simp add: ac_simps)\n\nlemma dividend_less_div_times:\n  \"m < n + (m div n) * n\" if \"0 < n\" for m n :: nat\nproof -\n  from that have \"m mod n < n\"\n    by simp\n  then show ?thesis\n    by (simp add: minus_mod_eq_div_mult [symmetric])\nqed\n\nlemma dividend_less_times_div:\n  \"m < n + n * (m div n)\" if \"0 < n\" for m n :: nat\n  using dividend_less_div_times [of n m] that\n  by (simp add: ac_simps)\n\nlemma mod_Suc_le_divisor [simp]:\n  \"m mod Suc n \\<le> n\"\n  using mod_less_divisor [of \"Suc n\" m] by arith\n\nlemma mod_less_eq_dividend [simp]:\n  \"m mod n \\<le> m\" for m n :: nat\nproof (rule add_leD2)\n  from div_mult_mod_eq have \"m div n * n + m mod n = m\" .\n  then show \"m div n * n + m mod n \\<le> m\" by auto\nqed\n\nlemma\n  div_less [simp]: \"m div n = 0\"\n  and mod_less [simp]: \"m mod n = m\"\n  if \"m < n\" for m n :: nat\n  using that by (auto intro: div_nat_eqI mod_nat_eqI)\n\nlemma split_div:\n  \\<open>P (m div n) \\<longleftrightarrow>\n    (n = 0 \\<longrightarrow> P 0) \\<and>\n    (n \\<noteq> 0 \\<longrightarrow> (\\<forall>i j. j < n \\<and> m = n * i + j \\<longrightarrow> P i))\\<close> (is ?div)\n  and split_mod:\n  \\<open>Q (m mod n) \\<longleftrightarrow>\n    (n = 0 \\<longrightarrow> Q m) \\<and>\n    (n \\<noteq> 0 \\<longrightarrow> (\\<forall>i j. j < n \\<and> m = n * i + j \\<longrightarrow> Q j))\\<close> (is ?mod)\n  for m n :: nat\nproof -\n  have *: \\<open>R (m div n) (m mod n) \\<longleftrightarrow>\n    (n = 0 \\<longrightarrow> R 0 m) \\<and>\n    (n \\<noteq> 0 \\<longrightarrow> (\\<forall>i j. j < n \\<and> m = n * i + j \\<longrightarrow> R i j))\\<close> for R\n    by (cases \\<open>n = 0\\<close>) auto\n  from * [of \\<open>\\<lambda>q _. P q\\<close>] show ?div .\n  from * [of \\<open>\\<lambda>_ r. Q r\\<close>] show ?mod .\nqed\n\ndeclare split_div [of _ _ \\<open>numeral n\\<close>, linarith_split] for n\ndeclare split_mod [of _ _ \\<open>numeral n\\<close>, linarith_split] for n\n\nlemma split_div':\n  \"P (m div n) \\<longleftrightarrow> n = 0 \\<and> P 0 \\<or> (\\<exists>q. (n * q \\<le> m \\<and> m < n * Suc q) \\<and> P q)\"\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  then have \"n * q \\<le> m \\<and> m < n * Suc q \\<longleftrightarrow> m div n = q\" for q\n    by (auto intro: div_nat_eqI dividend_less_times_div)\n  then show ?thesis\n    by auto\nqed\n\nlemma le_div_geq:\n  \"m div n = Suc ((m - n) div n)\" if \"0 < n\" and \"n \\<le> m\" for m n :: nat\nproof -\n  from \\<open>n \\<le> m\\<close> obtain q where \"m = n + q\"\n    by (auto simp add: le_iff_add)\n  with \\<open>0 < n\\<close> show ?thesis\n    by (simp add: div_add_self1)\nqed\n\nlemma le_mod_geq:\n  \"m mod n = (m - n) mod n\" if \"n \\<le> m\" for m n :: nat\nproof -\n  from \\<open>n \\<le> m\\<close> obtain q where \"m = n + q\"\n    by (auto simp add: le_iff_add)\n  then show ?thesis\n    by simp\nqed\n\nlemma div_if:\n  \"m div n = (if m < n \\<or> n = 0 then 0 else Suc ((m - n) div n))\"\n  by (simp add: le_div_geq)\n\nlemma mod_if:\n  \"m mod n = (if m < n then m else (m - n) mod n)\" for m n :: nat\n  by (simp add: le_mod_geq)\n\nlemma div_eq_0_iff:\n  \"m div n = 0 \\<longleftrightarrow> m < n \\<or> n = 0\" for m n :: nat\n  by (simp add: div_eq_0_iff)\n\nlemma div_greater_zero_iff:\n  \"m div n > 0 \\<longleftrightarrow> n \\<le> m \\<and> n > 0\" for m n :: nat\n  using div_eq_0_iff [of m n] by auto\n\nlemma mod_greater_zero_iff_not_dvd:\n  \"m mod n > 0 \\<longleftrightarrow> \\<not> n dvd m\" for m n :: nat\n  by (simp add: dvd_eq_mod_eq_0)\n\nlemma div_by_Suc_0 [simp]:\n  \"m div Suc 0 = m\"\n  using div_by_1 [of m] by simp\n\nlemma mod_by_Suc_0 [simp]:\n  \"m mod Suc 0 = 0\"\n  using mod_by_1 [of m] by simp\n\nlemma div2_Suc_Suc [simp]:\n  \"Suc (Suc m) div 2 = Suc (m div 2)\"\n  by (simp add: numeral_2_eq_2 le_div_geq)\n\nlemma Suc_n_div_2_gt_zero [simp]:\n  \"0 < Suc n div 2\" if \"n > 0\" for n :: nat\n  using that by (cases n) simp_all\n\nlemma div_2_gt_zero [simp]:\n  \"0 < n div 2\" if \"Suc 0 < n\" for n :: nat\n  using that Suc_n_div_2_gt_zero [of \"n - 1\"] by simp\n\nlemma mod2_Suc_Suc [simp]:\n  \"Suc (Suc m) mod 2 = m mod 2\"\n  by (simp add: numeral_2_eq_2 le_mod_geq)\n\nlemma add_self_div_2 [simp]:\n  \"(m + m) div 2 = m\" for m :: nat\n  by (simp add: mult_2 [symmetric])\n\nlemma add_self_mod_2 [simp]:\n  \"(m + m) mod 2 = 0\" for m :: nat\n  by (simp add: mult_2 [symmetric])\n\nlemma mod2_gr_0 [simp]:\n  \"0 < m mod 2 \\<longleftrightarrow> m mod 2 = 1\" for m :: nat\nproof -\n  have \"m mod 2 < 2\"\n    by (rule mod_less_divisor) simp\n  then have \"m mod 2 = 0 \\<or> m mod 2 = 1\"\n    by arith\n  then show ?thesis\n    by auto\nqed\n\nlemma mod_Suc_eq [mod_simps]:\n  \"Suc (m mod n) mod n = Suc m mod n\"\nproof -\n  have \"(m mod n + 1) mod n = (m + 1) mod n\"\n    by (simp only: mod_simps)\n  then show ?thesis\n    by simp\nqed\n\nlemma mod_Suc_Suc_eq [mod_simps]:\n  \"Suc (Suc (m mod n)) mod n = Suc (Suc m) mod n\"\nproof -\n  have \"(m mod n + 2) mod n = (m + 2) mod n\"\n    by (simp only: mod_simps)\n  then show ?thesis\n    by simp\nqed\n\nlemma\n  Suc_mod_mult_self1 [simp]: \"Suc (m + k * n) mod n = Suc m mod n\"\n  and Suc_mod_mult_self2 [simp]: \"Suc (m + n * k) mod n = Suc m mod n\"\n  and Suc_mod_mult_self3 [simp]: \"Suc (k * n + m) mod n = Suc m mod n\"\n  and Suc_mod_mult_self4 [simp]: \"Suc (n * k + m) mod n = Suc m mod n\"\n  by (subst mod_Suc_eq [symmetric], simp add: mod_simps)+\n\nlemma Suc_0_mod_eq [simp]:\n  \"Suc 0 mod n = of_bool (n \\<noteq> Suc 0)\"\n  by (cases n) simp_all\n\nlemma div_mult2_eq:\n    \\<open>m div (n * q) = (m div n) div q\\<close> (is ?Q)\n  and mod_mult2_eq:\n    \\<open>m mod (n * q) = n * (m div n mod q) + m mod n\\<close> (is ?R)\n  for m n q :: nat\nproof -\n  have \\<open>(m div (n * q), m mod (n * q)) = ((m div n) div q, n * (m div n mod q) + m mod n)\\<close>\n  proof (cases \\<open>n * q\\<close> \\<open>(m div n) div q\\<close> \\<open>n * (m div n mod q) + m mod n\\<close> m rule: euclidean_relation_natI)\n    case by0\n    then show ?case\n      by auto\n  next\n    case divides\n    from \\<open>n * q dvd m\\<close> obtain t where \\<open>m = n * q * t\\<close> ..\n    with \\<open>n * q > 0\\<close> show ?case\n      by (simp add: algebra_simps)\n  next\n    case euclidean_relation\n    then have \\<open>n > 0\\<close> \\<open>q > 0\\<close>\n      by simp_all\n    from \\<open>n > 0\\<close> have \\<open>m mod n < n\\<close>\n      by (rule mod_less_divisor)\n    from \\<open>q > 0\\<close> have \\<open>m div n mod q < q\\<close>\n      by (rule mod_less_divisor)\n    then obtain s where \\<open>q = Suc (m div n mod q + s)\\<close>\n      by (blast dest: less_imp_Suc_add)\n    moreover have \\<open>m mod n + n * (m div n mod q) < n * Suc (m div n mod q + s)\\<close>\n      using \\<open>m mod n < n\\<close> by (simp add: add_mult_distrib2)\n    ultimately have \\<open>m mod n + n * (m div n mod q) < n * q\\<close>\n      by simp\n    then show ?case\n      by (simp add: algebra_simps flip: add_mult_distrib2)\n  qed\n  then show ?Q and ?R\n    by simp_all\nqed\n\nlemma div_le_mono:\n  \"m div k \\<le> n div k\" if \"m \\<le> n\" for m n k :: nat\nproof -\n  from that obtain q where \"n = m + q\"\n    by (auto simp add: le_iff_add)\n  then show ?thesis\n    by (simp add: div_add1_eq [of m q k])\nqed\n\ntext \\<open>Antimonotonicity of \\<^const>\\<open>divide\\<close> in second argument\\<close>\n\nlemma div_le_mono2:\n  \"k div n \\<le> k div m\" if \"0 < m\" and \"m \\<le> n\" for m n k :: nat\nusing that proof (induct k arbitrary: m rule: less_induct)\n  case (less k)\n  show ?case\n  proof (cases \"n \\<le> k\")\n    case False\n    then show ?thesis\n      by simp\n  next\n    case True\n    have \"(k - n) div n \\<le> (k - m) div n\"\n      using less.prems\n      by (blast intro: div_le_mono diff_le_mono2)\n    also have \"\\<dots> \\<le> (k - m) div m\"\n      using \\<open>n \\<le> k\\<close> less.prems less.hyps [of \"k - m\" m]\n      by simp\n    finally show ?thesis\n      using \\<open>n \\<le> k\\<close> less.prems\n      by (simp add: le_div_geq)\n  qed\nqed\n\nlemma div_le_dividend [simp]:\n  \"m div n \\<le> m\" for m n :: nat\n  using div_le_mono2 [of 1 n m] by (cases \"n = 0\") simp_all\n\nlemma div_less_dividend [simp]:\n  \"m div n < m\" if \"1 < n\" and \"0 < m\" for m n :: nat\nusing that proof (induct m rule: less_induct)\n  case (less m)\n  show ?case\n  proof (cases \"n < m\")\n    case False\n    with less show ?thesis\n      by (cases \"n = m\") simp_all\n  next\n    case True\n    then show ?thesis\n      using less.hyps [of \"m - n\"] less.prems\n      by (simp add: le_div_geq)\n  qed\nqed\n\nlemma div_eq_dividend_iff:\n  \"m div n = m \\<longleftrightarrow> n = 1\" if \"m > 0\" for m n :: nat\nproof\n  assume \"n = 1\"\n  then show \"m div n = m\"\n    by simp\nnext\n  assume P: \"m div n = m\"\n  show \"n = 1\"\n  proof (rule ccontr)\n    have \"n \\<noteq> 0\"\n      by (rule ccontr) (use that P in auto)\n    moreover assume \"n \\<noteq> 1\"\n    ultimately have \"n > 1\"\n      by simp\n    with that have \"m div n < m\"\n      by simp\n    with P show False\n      by simp\n  qed\nqed\n\nlemma less_mult_imp_div_less:\n  \"m div n < i\" if \"m < i * n\" for m n i :: nat\nproof -\n  from that have \"i * n > 0\"\n    by (cases \"i * n = 0\") simp_all\n  then have \"i > 0\" and \"n > 0\"\n    by simp_all\n  have \"m div n * n \\<le> m\"\n    by simp\n  then have \"m div n * n < i * n\"\n    using that by (rule le_less_trans)\n  with \\<open>n > 0\\<close> show ?thesis\n    by simp\nqed\n\nlemma div_less_iff_less_mult:\n  \\<open>m div q < n \\<longleftrightarrow> m < n * q\\<close> (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\n  if \\<open>q > 0\\<close> for m n q :: nat\nproof\n  assume ?Q then show ?P\n    by (rule less_mult_imp_div_less)\nnext\n  assume ?P\n  then obtain h where \\<open>n = Suc (m div q + h)\\<close>\n    using less_natE by blast\n  moreover have \\<open>m < m + (Suc h * q - m mod q)\\<close>\n    using that by (simp add: trans_less_add1)\n  ultimately show ?Q\n    by (simp add: algebra_simps flip: minus_mod_eq_mult_div)\nqed\n\nlemma less_eq_div_iff_mult_less_eq:\n  \\<open>m \\<le> n div q \\<longleftrightarrow> m * q \\<le> n\\<close> if \\<open>q > 0\\<close> for m n q :: nat\n  using div_less_iff_less_mult [of q n m] that by auto\n\nlemma div_Suc:\n  \\<open>Suc m div n = (if Suc m mod n = 0 then Suc (m div n) else m div n)\\<close>  (is \"_ = ?rhs\")\nproof (cases \\<open>n = 0 \\<or> n = 1\\<close>)\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have \\<open>n > 1\\<close>\n    by simp\n  then have *: \\<open>Suc 0 div n = 0\\<close>\n    by (simp add: div_eq_0_iff)\n  have \\<open>(m + 1) div n = ?rhs\\<close>\n  proof (cases \\<open>n dvd Suc m\\<close>)\n    case True\n    then obtain q where \\<open>Suc m = n * q\\<close> ..\n    then have m: \\<open>m = n * q - 1\\<close>\n      by simp\n    have \\<open>q > 0\\<close> by (rule ccontr)\n      (use \\<open>Suc m = n * q\\<close> in simp)\n    from m have \\<open>m mod n = (n * q - 1) mod n\\<close>\n      by simp\n    also have \\<open>\\<dots> = (n * q - 1 + n) mod n\\<close>\n      by simp\n    also have \\<open>n * q - 1 + n = n * q + (n - 1)\\<close>\n      using \\<open>n > 1\\<close> \\<open>q > 0\\<close> by (simp add: algebra_simps)\n    finally have \\<open>m mod n = (n - 1) mod n\\<close>\n      by simp\n    with \\<open>n > 1\\<close> have \\<open>m mod n = n - 1\\<close>\n      by simp\n    with True \\<open>n > 1\\<close> show ?thesis\n      by (subst div_add1_eq) auto\n  next\n    case False\n    have \\<open>Suc (m mod n) \\<noteq> n\\<close>\n    proof (rule ccontr)\n      assume \\<open>\\<not> Suc (m mod n) \\<noteq> n\\<close>\n      then have \\<open>m mod n = n - 1\\<close>\n        by simp\n      with \\<open>n > 1\\<close> have \\<open>(m + 1) mod n = 0\\<close>\n        by (subst mod_add_left_eq [symmetric]) simp\n      then have \\<open>n dvd Suc m\\<close>\n        by auto\n      with False show False ..\n    qed\n    moreover have \\<open>Suc (m mod n) \\<le> n\\<close>\n      using \\<open>n > 1\\<close> by (simp add: Suc_le_eq)\n    ultimately have \\<open>Suc (m mod n) < n\\<close>\n      by simp\n    with False \\<open>n > 1\\<close> show ?thesis\n      by (subst div_add1_eq) (auto simp add: div_eq_0_iff mod_greater_zero_iff_not_dvd)\n  qed\n  then show ?thesis\n    by simp\nqed\n\nlemma mod_Suc:\n  \\<open>Suc m mod n = (if Suc (m mod n) = n then 0 else Suc (m mod n))\\<close>  (is \"_ = ?rhs\")\nproof (cases \"n = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  have \"Suc m mod n = Suc (m mod n) mod n\"\n    by (simp add: mod_simps)\n  also have \"\\<dots> = ?rhs\"\n    using False by (auto intro!: mod_nat_eqI intro: neq_le_trans simp add: Suc_le_eq)\n  finally show ?thesis .\nqed\n\nlemma Suc_times_mod_eq:\n  \"Suc (m * n) mod m = 1\" if \"Suc 0 < m\"\n  using that by (simp add: mod_Suc)\n\nlemma Suc_times_numeral_mod_eq [simp]:\n  \"Suc (numeral k * n) mod numeral k = 1\" if \"numeral k \\<noteq> (1::nat)\"\n  by (rule Suc_times_mod_eq) (use that in simp)\n\nlemma Suc_div_le_mono [simp]:\n  \"m div n \\<le> Suc m div n\"\n  by (simp add: div_le_mono)\n\ntext \\<open>These lemmas collapse some needless occurrences of Suc:\n  at least three Sucs, since two and fewer are rewritten back to Suc again!\n  We already have some rules to simplify operands smaller than 3.\\<close>\n\nlemma div_Suc_eq_div_add3 [simp]:\n  \"m div Suc (Suc (Suc n)) = m div (3 + n)\"\n  by (simp add: Suc3_eq_add_3)\n\nlemma mod_Suc_eq_mod_add3 [simp]:\n  \"m mod Suc (Suc (Suc n)) = m mod (3 + n)\"\n  by (simp add: Suc3_eq_add_3)\n\nlemma Suc_div_eq_add3_div:\n  \"Suc (Suc (Suc m)) div n = (3 + m) div n\"\n  by (simp add: Suc3_eq_add_3)\n\nlemma Suc_mod_eq_add3_mod:\n  \"Suc (Suc (Suc m)) mod n = (3 + m) mod n\"\n  by (simp add: Suc3_eq_add_3)\n\nlemmas Suc_div_eq_add3_div_numeral [simp] =\n  Suc_div_eq_add3_div [of _ \"numeral v\"] for v\n\nlemmas Suc_mod_eq_add3_mod_numeral [simp] =\n  Suc_mod_eq_add3_mod [of _ \"numeral v\"] for v\n\nlemma (in field_char_0) of_nat_div:\n  \"of_nat (m div n) = ((of_nat m - of_nat (m mod n)) / of_nat n)\"\nproof -\n  have \"of_nat (m div n) = ((of_nat (m div n * n + m mod n) - of_nat (m mod n)) / of_nat n :: 'a)\"\n    unfolding of_nat_add by (cases \"n = 0\") simp_all\n  then show ?thesis\n    by simp\nqed\n\ntext \\<open>An ``induction'' law for modulus arithmetic.\\<close>\n\nlemma mod_induct [consumes 3, case_names step]:\n  \"P m\" if \"P n\" and \"n < p\" and \"m < p\"\n    and step: \"\\<And>n. n < p \\<Longrightarrow> P n \\<Longrightarrow> P (Suc n mod p)\"\nusing \\<open>m < p\\<close> proof (induct m)\n  case 0\n  show ?case\n  proof (rule ccontr)\n    assume \"\\<not> P 0\"\n    from \\<open>n < p\\<close> have \"0 < p\"\n      by simp\n    from \\<open>n < p\\<close> obtain m where \"0 < m\" and \"p = n + m\"\n      by (blast dest: less_imp_add_positive)\n    with \\<open>P n\\<close> have \"P (p - m)\"\n      by simp\n    moreover have \"\\<not> P (p - m)\"\n    using \\<open>0 < m\\<close> proof (induct m)\n      case 0\n      then show ?case\n        by simp\n    next\n      case (Suc m)\n      show ?case\n      proof\n        assume P: \"P (p - Suc m)\"\n        with \\<open>\\<not> P 0\\<close> have \"Suc m < p\"\n          by (auto intro: ccontr)\n        then have \"Suc (p - Suc m) = p - m\"\n          by arith\n        moreover from \\<open>0 < p\\<close> have \"p - Suc m < p\"\n          by arith\n        with P step have \"P ((Suc (p - Suc m)) mod p)\"\n          by blast\n        ultimately show False\n          using \\<open>\\<not> P 0\\<close> Suc.hyps by (cases \"m = 0\") simp_all\n      qed\n    qed\n    ultimately show False\n      by blast\n  qed\nnext\n  case (Suc m)\n  then have \"m < p\" and mod: \"Suc m mod p = Suc m\"\n    by simp_all\n  from \\<open>m < p\\<close> have \"P m\"\n    by (rule Suc.hyps)\n  with \\<open>m < p\\<close> have \"P (Suc m mod p)\"\n    by (rule step)\n  with mod show ?case\n    by simp\nqed\n\nlemma funpow_mod_eq: \\<^marker>\\<open>contributor \\<open>Lars Noschinski\\<close>\\<close>\n  \\<open>(f ^^ (m mod n)) x = (f ^^ m) x\\<close> if \\<open>(f ^^ n) x = x\\<close>\nproof -\n  have \\<open>(f ^^ m) x = (f ^^ (m mod n + m div n * n)) x\\<close>\n    by simp\n  also have \\<open>\\<dots> = (f ^^ (m mod n)) (((f ^^ n) ^^ (m div n)) x)\\<close>\n    by (simp only: funpow_add funpow_mult ac_simps) simp\n  also have \\<open>((f ^^ n) ^^ q) x = x\\<close> for q\n    by (induction q) (use \\<open>(f ^^ n) x = x\\<close> in simp_all)\n  finally show ?thesis\n    by simp\nqed\n\nlemma mod_eq_dvd_iff_nat:\n  \\<open>m mod q = n mod q \\<longleftrightarrow> q dvd m - n\\<close> (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\n    if \\<open>m \\<ge> n\\<close> for m n q :: nat\nproof\n  assume ?Q\n  then obtain s where \\<open>m - n = q * s\\<close> ..\n  with that have \\<open>m = q * s + n\\<close>\n    by simp\n  then show ?P\n    by simp\nnext\n  assume ?P\n  have \\<open>m - n = m div q * q + m mod q - (n div q * q + n mod q)\\<close>\n    by simp\n  also have \\<open>\\<dots> = q * (m div q - n div q)\\<close>\n    by (simp only: algebra_simps \\<open>?P\\<close>)\n  finally show ?Q ..\nqed\n\nlemma mod_eq_iff_dvd_symdiff_nat:\n  \\<open>m mod q = n mod q \\<longleftrightarrow> q dvd nat \\<bar>int m - int n\\<bar>\\<close>\n  by (auto simp add: abs_if mod_eq_dvd_iff_nat nat_diff_distrib dest: sym intro: sym)\n\nlemma mod_eq_nat1E:\n  fixes m n q :: nat\n  assumes \"m mod q = n mod q\" and \"m \\<ge> n\"\n  obtains s where \"m = n + q * s\"\nproof -\n  from assms have \"q dvd m - n\"\n    by (simp add: mod_eq_dvd_iff_nat)\n  then obtain s where \"m - n = q * s\" ..\n  with \\<open>m \\<ge> n\\<close> have \"m = n + q * s\"\n    by simp\n  with that show thesis .\nqed\n\nlemma mod_eq_nat2E:\n  fixes m n q :: nat\n  assumes \"m mod q = n mod q\" and \"n \\<ge> m\"\n  obtains s where \"n = m + q * s\"\n  using assms mod_eq_nat1E [of n q m] by (auto simp add: ac_simps)\n\nlemma nat_mod_eq_iff:\n  \"(x::nat) mod n = y mod n \\<longleftrightarrow> (\\<exists>q1 q2. x + n * q1 = y + n * q2)\"  (is \"?lhs = ?rhs\")\nproof\n  assume H: \"x mod n = y mod n\"\n  { assume xy: \"x \\<le> y\"\n    from H have th: \"y mod n = x mod n\" by simp\n    from mod_eq_nat1E [OF th xy] obtain q where \"y = x + n * q\" .\n    then have \"x + n * q = y + n * 0\"\n      by simp\n    then have \"\\<exists>q1 q2. x + n * q1 = y + n * q2\"\n      by blast\n  }\n  moreover\n  { assume xy: \"y \\<le> x\"\n    from mod_eq_nat1E [OF H xy] obtain q where \"x = y + n * q\" .\n    then have \"x + n * 0 = y + n * q\"\n      by simp\n    then have \"\\<exists>q1 q2. x + n * q1 = y + n * q2\"\n      by blast\n  }\n  ultimately show ?rhs using linear[of x y] by blast\nnext\n  assume ?rhs then obtain q1 q2 where q12: \"x + n * q1 = y + n * q2\" by blast\n  hence \"(x + n * q1) mod n = (y + n * q2) mod n\" by simp\n  thus  ?lhs by simp\nqed\n\n\n\nsubsection \\<open>Elementary euclidean division on \\<^typ>\\<open>int\\<close>\\<close>\n\nsubsubsection \\<open>Basic instantiation\\<close>\n\ninstantiation int :: \"{normalization_semidom, idom_modulo}\"\nbegin\n\ndefinition normalize_int :: \\<open>int \\<Rightarrow> int\\<close>\n  where [simp]: \\<open>normalize = (abs :: int \\<Rightarrow> int)\\<close>\n\ndefinition unit_factor_int :: \\<open>int \\<Rightarrow> int\\<close>\n  where [simp]: \\<open>unit_factor = (sgn :: int \\<Rightarrow> int)\\<close>\n\ndefinition divide_int :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>k div l = (sgn k * sgn l * int (nat \\<bar>k\\<bar> div nat \\<bar>l\\<bar>)\n    - of_bool (l \\<noteq> 0 \\<and> sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k))\\<close>\n\nlemma divide_int_unfold:\n  \\<open>(sgn k * int m) div (sgn l * int n) = (sgn k * sgn l * int (m div n)\n    - of_bool ((k = 0 \\<longleftrightarrow> m = 0) \\<and> l \\<noteq> 0 \\<and> n \\<noteq> 0 \\<and> sgn k \\<noteq> sgn l \\<and> \\<not> n dvd m))\\<close>\n  by (simp add: divide_int_def sgn_mult nat_mult_distrib abs_mult sgn_eq_0_iff ac_simps)\n\ndefinition modulo_int :: \\<open>int \\<Rightarrow> int \\<Rightarrow> int\\<close>\n  where \\<open>k mod l = sgn k * int (nat \\<bar>k\\<bar> mod nat \\<bar>l\\<bar>) + l * of_bool (sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k)\\<close>\n\nlemma modulo_int_unfold:\n  \\<open>(sgn k * int m) mod (sgn l * int n) =\n    sgn k * int (m mod (of_bool (l \\<noteq> 0) * n)) + (sgn l * int n) * of_bool ((k = 0 \\<longleftrightarrow> m = 0) \\<and> sgn k \\<noteq> sgn l \\<and> \\<not> n dvd m)\\<close>\n  by (auto simp add: modulo_int_def sgn_mult abs_mult)\n\ninstance proof\n  fix k :: int show \"k div 0 = 0\"\n  by (simp add: divide_int_def)\nnext\n  fix k l :: int\n  assume \"l \\<noteq> 0\"\n  obtain n m and s t where k: \"k = sgn s * int n\" and l: \"l = sgn t * int m\"\n    by (blast intro: int_sgnE elim: that)\n  then have \"k * l = sgn (s * t) * int (n * m)\"\n    by (simp add: ac_simps sgn_mult)\n  with k l \\<open>l \\<noteq> 0\\<close> show \"k * l div l = k\"\n    by (simp only: divide_int_unfold)\n      (auto simp add: algebra_simps sgn_mult sgn_1_pos sgn_0_0)\nnext\n  fix k l :: int\n  obtain n m and s t where \"k = sgn s * int n\" and \"l = sgn t * int m\"\n    by (blast intro: int_sgnE elim: that)\n  then show \"k div l * l + k mod l = k\"\n    by (simp add: divide_int_unfold modulo_int_unfold algebra_simps modulo_nat_def of_nat_diff)\nqed (auto simp add: sgn_mult mult_sgn_abs abs_eq_iff')\n\nend\n\n\nsubsubsection \\<open>Algebraic foundations\\<close>\n\nlemma coprime_int_iff [simp]:\n  \"coprime (int m) (int n) \\<longleftrightarrow> coprime m n\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  show ?Q\n  proof (rule coprimeI)\n    fix q\n    assume \"q dvd m\" \"q dvd n\"\n    then have \"int q dvd int m\" \"int q dvd int n\"\n      by simp_all\n    with \\<open>?P\\<close> have \"is_unit (int q)\"\n      by (rule coprime_common_divisor)\n    then show \"is_unit q\"\n      by simp\n  qed\nnext\n  assume ?Q\n  show ?P\n  proof (rule coprimeI)\n    fix k\n    assume \"k dvd int m\" \"k dvd int n\"\n    then have \"nat \\<bar>k\\<bar> dvd m\" \"nat \\<bar>k\\<bar> dvd n\"\n      by simp_all\n    with \\<open>?Q\\<close> have \"is_unit (nat \\<bar>k\\<bar>)\"\n      by (rule coprime_common_divisor)\n    then show \"is_unit k\"\n      by simp\n  qed\nqed\n\nlemma coprime_abs_left_iff [simp]:\n  \"coprime \\<bar>k\\<bar> l \\<longleftrightarrow> coprime k l\" for k l :: int\n  using coprime_normalize_left_iff [of k l] by simp\n\nlemma coprime_abs_right_iff [simp]:\n  \"coprime k \\<bar>l\\<bar> \\<longleftrightarrow> coprime k l\" for k l :: int\n  using coprime_abs_left_iff [of l k] by (simp add: ac_simps)\n\nlemma coprime_nat_abs_left_iff [simp]:\n  \"coprime (nat \\<bar>k\\<bar>) n \\<longleftrightarrow> coprime k (int n)\"\nproof -\n  define m where \"m = nat \\<bar>k\\<bar>\"\n  then have \"\\<bar>k\\<bar> = int m\"\n    by simp\n  moreover have \"coprime k (int n) \\<longleftrightarrow> coprime \\<bar>k\\<bar> (int n)\"\n    by simp\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma coprime_nat_abs_right_iff [simp]:\n  \"coprime n (nat \\<bar>k\\<bar>) \\<longleftrightarrow> coprime (int n) k\"\n  using coprime_nat_abs_left_iff [of k n] by (simp add: ac_simps)\n\nlemma coprime_common_divisor_int: \"coprime a b \\<Longrightarrow> x dvd a \\<Longrightarrow> x dvd b \\<Longrightarrow> \\<bar>x\\<bar> = 1\"\n  for a b :: int\n  by (drule coprime_common_divisor [of _ _ x]) simp_all\n\n\nsubsubsection \\<open>Basic conversions\\<close>\n\nlemma div_abs_eq_div_nat:\n  \"\\<bar>k\\<bar> div \\<bar>l\\<bar> = int (nat \\<bar>k\\<bar> div nat \\<bar>l\\<bar>)\"\n  by (auto simp add: divide_int_def)\n\nlemma div_eq_div_abs:\n  \\<open>k div l = sgn k * sgn l * (\\<bar>k\\<bar> div \\<bar>l\\<bar>)\n    - of_bool (l \\<noteq> 0 \\<and> sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k)\\<close>\n  for k l :: int\n  by (simp add: divide_int_def [of k l] div_abs_eq_div_nat)\n\nlemma div_abs_eq:\n  \\<open>\\<bar>k\\<bar> div \\<bar>l\\<bar> = sgn k * sgn l * (k div l + of_bool (sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k))\\<close>\n  for k l :: int\n  by (simp add: div_eq_div_abs [of k l] ac_simps)\n\nlemma mod_abs_eq_div_nat:\n  \"\\<bar>k\\<bar> mod \\<bar>l\\<bar> = int (nat \\<bar>k\\<bar> mod nat \\<bar>l\\<bar>)\"\n  by (simp add: modulo_int_def)\n\nlemma mod_eq_mod_abs:\n  \\<open>k mod l = sgn k * (\\<bar>k\\<bar> mod \\<bar>l\\<bar>) + l * of_bool (sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k)\\<close>\n  for k l :: int\n  by (simp add: modulo_int_def [of k l] mod_abs_eq_div_nat)\n\nlemma mod_abs_eq:\n  \\<open>\\<bar>k\\<bar> mod \\<bar>l\\<bar> = sgn k * (k mod l - l * of_bool (sgn k \\<noteq> sgn l \\<and> \\<not> l dvd k))\\<close>\n  for k l :: int\n  by (auto simp: mod_eq_mod_abs [of k l])\n\nlemma div_sgn_abs_cancel:\n  fixes k l v :: int\n  assumes \"v \\<noteq> 0\"\n  shows \"(sgn v * \\<bar>k\\<bar>) div (sgn v * \\<bar>l\\<bar>) = \\<bar>k\\<bar> div \\<bar>l\\<bar>\"\n  using assms by (simp add: sgn_mult abs_mult sgn_0_0\n    divide_int_def [of \"sgn v * \\<bar>k\\<bar>\" \"sgn v * \\<bar>l\\<bar>\"] flip: div_abs_eq_div_nat)\n\nlemma div_eq_sgn_abs:\n  fixes k l v :: int\n  assumes \"sgn k = sgn l\"\n  shows \"k div l = \\<bar>k\\<bar> div \\<bar>l\\<bar>\"\n  using assms by (auto simp add: div_abs_eq)\n\nlemma div_dvd_sgn_abs:\n  fixes k l :: int\n  assumes \"l dvd k\"\n  shows \"k div l = (sgn k * sgn l) * (\\<bar>k\\<bar> div \\<bar>l\\<bar>)\"\n  using assms by (auto simp add: div_abs_eq ac_simps)\n\nlemma div_noneq_sgn_abs:\n  fixes k l :: int\n  assumes \"l \\<noteq> 0\"\n  assumes \"sgn k \\<noteq> sgn l\"\n  shows \"k div l = - (\\<bar>k\\<bar> div \\<bar>l\\<bar>) - of_bool (\\<not> l dvd k)\"\n  using assms by (auto simp add: div_abs_eq ac_simps sgn_0_0 dest!: sgn_not_eq_imp)\n\n\nsubsubsection \\<open>Euclidean division\\<close>\n\ninstantiation int :: unique_euclidean_ring\nbegin\n\ndefinition euclidean_size_int :: \"int \\<Rightarrow> nat\"\n  where [simp]: \"euclidean_size_int = (nat \\<circ> abs :: int \\<Rightarrow> nat)\"\n\ndefinition division_segment_int :: \"int \\<Rightarrow> int\"\n  where \"division_segment_int k = (if k \\<ge> 0 then 1 else - 1)\"\n\nlemma division_segment_eq_sgn:\n  \"division_segment k = sgn k\" if \"k \\<noteq> 0\" for k :: int\n  using that by (simp add: division_segment_int_def)\n\nlemma abs_division_segment [simp]:\n  \"\\<bar>division_segment k\\<bar> = 1\" for k :: int\n  by (simp add: division_segment_int_def)\n\nlemma abs_mod_less:\n  \"\\<bar>k mod l\\<bar> < \\<bar>l\\<bar>\" if \"l \\<noteq> 0\" for k l :: int\nproof -\n  obtain n m and s t where \"k = sgn s * int n\" and \"l = sgn t * int m\"\n    by (blast intro: int_sgnE elim: that)\n  with that show ?thesis\n    by (auto simp add: modulo_int_unfold abs_mult mod_greater_zero_iff_not_dvd\n        simp flip: right_diff_distrib dest!: sgn_not_eq_imp)\n      (simp add: sgn_0_0)\nqed\n\nlemma sgn_mod:\n  \"sgn (k mod l) = sgn l\" if \"l \\<noteq> 0\" \"\\<not> l dvd k\" for k l :: int\nproof -\n  obtain n m and s t where \"k = sgn s * int n\" and \"l = sgn t * int m\"\n    by (blast intro: int_sgnE elim: that)\n  with that show ?thesis\n    by (auto simp add: modulo_int_unfold sgn_mult mod_greater_zero_iff_not_dvd\n      simp flip: right_diff_distrib dest!: sgn_not_eq_imp)\nqed\n\ninstance proof\n  fix k l :: int\n  show \"division_segment (k mod l) = division_segment l\" if\n    \"l \\<noteq> 0\" and \"\\<not> l dvd k\"\n    using that by (simp add: division_segment_eq_sgn dvd_eq_mod_eq_0 sgn_mod)\nnext\n  fix l q r :: int\n  obtain n m and s t\n     where l: \"l = sgn s * int n\" and q: \"q = sgn t * int m\"\n    by (blast intro: int_sgnE elim: that)\n  assume \\<open>l \\<noteq> 0\\<close>\n  with l have \"s \\<noteq> 0\" and \"n > 0\"\n    by (simp_all add: sgn_0_0)\n  assume \"division_segment r = division_segment l\"\n  moreover have \"r = sgn r * \\<bar>r\\<bar>\"\n    by (simp add: sgn_mult_abs)\n  moreover define u where \"u = nat \\<bar>r\\<bar>\"\n  ultimately have \"r = sgn l * int u\"\n    using division_segment_eq_sgn \\<open>l \\<noteq> 0\\<close> by (cases \"r = 0\") simp_all\n  with l \\<open>n > 0\\<close> have r: \"r = sgn s * int u\"\n    by (simp add: sgn_mult)\n  assume \"euclidean_size r < euclidean_size l\"\n  with l r \\<open>s \\<noteq> 0\\<close> have \"u < n\"\n    by (simp add: abs_mult)\n  show \"(q * l + r) div l = q\"\n  proof (cases \"q = 0 \\<or> r = 0\")\n    case True\n    then show ?thesis\n    proof\n      assume \"q = 0\"\n      then show ?thesis\n        using l r \\<open>u < n\\<close> by (simp add: divide_int_unfold)\n    next\n      assume \"r = 0\"\n      from \\<open>r = 0\\<close> have *: \"q * l + r = sgn (t * s) * int (n * m)\"\n        using q l by (simp add: ac_simps sgn_mult)\n      from \\<open>s \\<noteq> 0\\<close> \\<open>n > 0\\<close> show ?thesis\n        by (simp only: *, simp only: * q l divide_int_unfold)\n          (auto simp add: sgn_mult ac_simps)\n    qed\n  next\n    case False\n    with q r have \"t \\<noteq> 0\" and \"m > 0\" and \"s \\<noteq> 0\" and \"u > 0\"\n      by (simp_all add: sgn_0_0)\n    moreover from \\<open>0 < m\\<close> \\<open>u < n\\<close> have \"u \\<le> m * n\"\n      using mult_le_less_imp_less [of 1 m u n] by simp\n    ultimately have *: \"q * l + r = sgn (s * t)\n      * int (if t < 0 then m * n - u else m * n + u)\"\n      using l q r\n      by (simp add: sgn_mult algebra_simps of_nat_diff)\n    have \"(m * n - u) div n = m - 1\" if \"u > 0\"\n      using \\<open>0 < m\\<close> \\<open>u < n\\<close> that\n      by (auto intro: div_nat_eqI simp add: algebra_simps)\n    moreover have \"n dvd m * n - u \\<longleftrightarrow> n dvd u\"\n      using \\<open>u \\<le> m * n\\<close> dvd_diffD1 [of n \"m * n\" u]\n      by auto\n    ultimately show ?thesis\n      using \\<open>s \\<noteq> 0\\<close> \\<open>m > 0\\<close> \\<open>u > 0\\<close> \\<open>u < n\\<close> \\<open>u \\<le> m * n\\<close>\n      by (simp only: *, simp only: l q divide_int_unfold)\n        (auto simp add: sgn_mult sgn_0_0 sgn_1_pos algebra_simps dest: dvd_imp_le)\n  qed\nqed (use mult_le_mono2 [of 1] in \\<open>auto simp add: division_segment_int_def not_le zero_less_mult_iff mult_less_0_iff abs_mult sgn_mult abs_mod_less sgn_mod nat_mult_distrib\\<close>)\n\nend\n\nlemma euclidean_relation_intI [case_names by0 divides euclidean_relation]:\n  \\<open>(k div l, k mod l) = (q, r)\\<close>\n    if by0': \\<open>l = 0 \\<Longrightarrow> q = 0 \\<and> r = k\\<close>\n    and divides': \\<open>l \\<noteq> 0 \\<Longrightarrow> l dvd k \\<Longrightarrow> r = 0 \\<and> k = q * l\\<close>\n    and euclidean_relation': \\<open>l \\<noteq> 0 \\<Longrightarrow> \\<not> l dvd k \\<Longrightarrow> sgn r = sgn l\n      \\<and> \\<bar>r\\<bar> < \\<bar>l\\<bar> \\<and> k = q * l + r\\<close> for k l :: int\nproof (cases l q r k rule: euclidean_relationI)\n  case by0\n  then show ?case\n    by (rule by0')\nnext\n  case divides\n  then show ?case\n    by (rule divides')\nnext\n  case euclidean_relation\n  with euclidean_relation' have \\<open>sgn r = sgn l\\<close> \\<open>\\<bar>r\\<bar> < \\<bar>l\\<bar>\\<close> \\<open>k = q * l + r\\<close>\n    by simp_all\n  from \\<open>sgn r = sgn l\\<close> \\<open>l \\<noteq> 0\\<close> have \\<open>division_segment r = division_segment l\\<close>\n    by (simp add: division_segment_int_def sgn_if split: if_splits)\n  with \\<open>\\<bar>r\\<bar> < \\<bar>l\\<bar>\\<close> \\<open>k = q * l + r\\<close>\n  show ?case\n    by simp\nqed\n\n\nsubsection \\<open>Special case: euclidean rings containing the natural numbers\\<close>\n\nclass unique_euclidean_semiring_with_nat = semidom + semiring_char_0 + unique_euclidean_semiring +\n  assumes of_nat_div: \"of_nat (m div n) = of_nat m div of_nat n\"\n    and division_segment_of_nat [simp]: \"division_segment (of_nat n) = 1\"\n    and division_segment_euclidean_size [simp]: \"division_segment a * of_nat (euclidean_size a) = a\"\nbegin\n\nlemma division_segment_eq_iff:\n  \"a = b\" if \"division_segment a = division_segment b\"\n    and \"euclidean_size a = euclidean_size b\"\n  using that division_segment_euclidean_size [of a] by simp\n\nlemma euclidean_size_of_nat [simp]:\n  \"euclidean_size (of_nat n) = n\"\nproof -\n  have \"division_segment (of_nat n) * of_nat (euclidean_size (of_nat n)) = of_nat n\"\n    by (fact division_segment_euclidean_size)\n  then show ?thesis by simp\nqed\n\nlemma of_nat_euclidean_size:\n  \"of_nat (euclidean_size a) = a div division_segment a\"\nproof -\n  have \"of_nat (euclidean_size a) = division_segment a * of_nat (euclidean_size a) div division_segment a\"\n    by (subst nonzero_mult_div_cancel_left) simp_all\n  also have \"\\<dots> = a div division_segment a\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma division_segment_1 [simp]:\n  \"division_segment 1 = 1\"\n  using division_segment_of_nat [of 1] by simp\n\nlemma division_segment_numeral [simp]:\n  \"division_segment (numeral k) = 1\"\n  using division_segment_of_nat [of \"numeral k\"] by simp\n\nlemma euclidean_size_1 [simp]:\n  \"euclidean_size 1 = 1\"\n  using euclidean_size_of_nat [of 1] by simp\n\nlemma euclidean_size_numeral [simp]:\n  \"euclidean_size (numeral k) = numeral k\"\n  using euclidean_size_of_nat [of \"numeral k\"] by simp\n\nlemma of_nat_dvd_iff:\n  \"of_nat m dvd of_nat n \\<longleftrightarrow> m dvd n\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof (cases \"m = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?Q\n    then show ?P\n      by auto\n  next\n    assume ?P\n    with False have \"of_nat n = of_nat n div of_nat m * of_nat m\"\n      by simp\n    then have \"of_nat n = of_nat (n div m * m)\"\n      by (simp add: of_nat_div)\n    then have \"n = n div m * m\"\n      by (simp only: of_nat_eq_iff)\n    then have \"n = m * (n div m)\"\n      by (simp add: ac_simps)\n    then show ?Q ..\n  qed\nqed\n\nlemma of_nat_mod:\n  \"of_nat (m mod n) = of_nat m mod of_nat n\"\nproof -\n  have \"of_nat m div of_nat n * of_nat n + of_nat m mod of_nat n = of_nat m\"\n    by (simp add: div_mult_mod_eq)\n  also have \"of_nat m = of_nat (m div n * n + m mod n)\"\n    by simp\n  finally show ?thesis\n    by (simp only: of_nat_div of_nat_mult of_nat_add) simp\nqed\n\nlemma one_div_two_eq_zero [simp]:\n  \"1 div 2 = 0\"\nproof -\n  from of_nat_div [symmetric] have \"of_nat 1 div of_nat 2 = of_nat 0\"\n    by (simp only:) simp\n  then show ?thesis\n    by simp\nqed\n\nlemma one_mod_two_eq_one [simp]:\n  \"1 mod 2 = 1\"\nproof -\n  from of_nat_mod [symmetric] have \"of_nat 1 mod of_nat 2 = of_nat 1\"\n    by (simp only:) simp\n  then show ?thesis\n    by simp\nqed\n\nlemma one_mod_2_pow_eq [simp]:\n  \"1 mod (2 ^ n) = of_bool (n > 0)\"\nproof -\n  have \"1 mod (2 ^ n) = of_nat (1 mod (2 ^ n))\"\n    using of_nat_mod [of 1 \"2 ^ n\"] by simp\n  also have \"\\<dots> = of_bool (n > 0)\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma one_div_2_pow_eq [simp]:\n  \"1 div (2 ^ n) = of_bool (n = 0)\"\n  using div_mult_mod_eq [of 1 \"2 ^ n\"] by auto\n\nlemma div_mult2_eq':\n  \\<open>a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\\<close>\nproof (cases \\<open>m = 0 \\<or> n = 0\\<close>)\n  case True\n  then show ?thesis\n    by auto\nnext\n  case False\n  then have \\<open>m > 0\\<close> \\<open>n > 0\\<close>\n    by simp_all\n  show ?thesis\n  proof (cases \\<open>of_nat m * of_nat n dvd a\\<close>)\n    case True\n    then obtain b where \\<open>a = (of_nat m * of_nat n) * b\\<close> ..\n    then have \\<open>a = of_nat m * (of_nat n * b)\\<close>\n      by (simp add: ac_simps)\n    then show ?thesis\n      by simp\n  next\n    case False\n    define q where \\<open>q = a div (of_nat m * of_nat n)\\<close>\n    define r where \\<open>r = a mod (of_nat m * of_nat n)\\<close>\n    from \\<open>m > 0\\<close> \\<open>n > 0\\<close> \\<open>\\<not> of_nat m * of_nat n dvd a\\<close> r_def have \"division_segment r = 1\"\n      using division_segment_of_nat [of \"m * n\"] by (simp add: division_segment_mod)\n    with division_segment_euclidean_size [of r]\n    have \"of_nat (euclidean_size r) = r\"\n      by simp\n    have \"a mod (of_nat m * of_nat n) div (of_nat m * of_nat n) = 0\"\n      by simp\n    with \\<open>m > 0\\<close> \\<open>n > 0\\<close> r_def have \"r div (of_nat m * of_nat n) = 0\"\n      by simp\n    with \\<open>of_nat (euclidean_size r) = r\\<close>\n    have \"of_nat (euclidean_size r) div (of_nat m * of_nat n) = 0\"\n      by simp\n    then have \"of_nat (euclidean_size r div (m * n)) = 0\"\n      by (simp add: of_nat_div)\n    then have \"of_nat (euclidean_size r div m div n) = 0\"\n      by (simp add: div_mult2_eq)\n    with \\<open>of_nat (euclidean_size r) = r\\<close> have \"r div of_nat m div of_nat n = 0\"\n      by (simp add: of_nat_div)\n    with \\<open>m > 0\\<close> \\<open>n > 0\\<close> q_def\n    have \"q = (r div of_nat m + q * of_nat n * of_nat m div of_nat m) div of_nat n\"\n      by simp\n    moreover have \\<open>a = q * (of_nat m * of_nat n) + r\\<close>\n      by (simp add: q_def r_def div_mult_mod_eq)\n    ultimately show \\<open>a div (of_nat m * of_nat n) = a div of_nat m div of_nat n\\<close>\n      using q_def [symmetric] div_plus_div_distrib_dvd_right [of \\<open>of_nat m\\<close> \\<open>q * (of_nat m * of_nat n)\\<close> r]\n      by (simp add: ac_simps)\n  qed\nqed\n\nlemma mod_mult2_eq':\n  \"a mod (of_nat m * of_nat n) = of_nat m * (a div of_nat m mod of_nat n) + a mod of_nat m\"\nproof -\n  have \"a div (of_nat m * of_nat n) * (of_nat m * of_nat n) + a mod (of_nat m * of_nat n) = a div of_nat m div of_nat n * of_nat n * of_nat m + (a div of_nat m mod of_nat n * of_nat m + a mod of_nat m)\"\n    by (simp add: combine_common_factor div_mult_mod_eq)\n  moreover have \"a div of_nat m div of_nat n * of_nat n * of_nat m = of_nat n * of_nat m * (a div of_nat m div of_nat n)\"\n    by (simp add: ac_simps)\n  ultimately show ?thesis\n    by (simp add: div_mult2_eq' mult_commute)\nqed\n\nlemma div_mult2_numeral_eq:\n  \"a div numeral k div numeral l = a div numeral (k * l)\" (is \"?A = ?B\")\nproof -\n  have \"?A = a div of_nat (numeral k) div of_nat (numeral l)\"\n    by simp\n  also have \"\\<dots> = a div (of_nat (numeral k) * of_nat (numeral l))\"\n    by (fact div_mult2_eq' [symmetric])\n  also have \"\\<dots> = ?B\"\n    by simp\n  finally show ?thesis .\nqed\n\nlemma numeral_Bit0_div_2:\n  \"numeral (num.Bit0 n) div 2 = numeral n\"\nproof -\n  have \"numeral (num.Bit0 n) = numeral n + numeral n\"\n    by (simp only: numeral.simps)\n  also have \"\\<dots> = numeral n * 2\"\n    by (simp add: mult_2_right)\n  finally have \"numeral (num.Bit0 n) div 2 = numeral n * 2 div 2\"\n    by simp\n  also have \"\\<dots> = numeral n\"\n    by (rule nonzero_mult_div_cancel_right) simp\n  finally show ?thesis .\nqed\n\nlemma numeral_Bit1_div_2:\n  \"numeral (num.Bit1 n) div 2 = numeral n\"\nproof -\n  have \"numeral (num.Bit1 n) = numeral n + numeral n + 1\"\n    by (simp only: numeral.simps)\n  also have \"\\<dots> = numeral n * 2 + 1\"\n    by (simp add: mult_2_right)\n  finally have \"numeral (num.Bit1 n) div 2 = (numeral n * 2 + 1) div 2\"\n    by simp\n  also have \"\\<dots> = numeral n * 2 div 2 + 1 div 2\"\n    using dvd_triv_right by (rule div_plus_div_distrib_dvd_left)\n  also have \"\\<dots> = numeral n * 2 div 2\"\n    by simp\n  also have \"\\<dots> = numeral n\"\n    by (rule nonzero_mult_div_cancel_right) simp\n  finally show ?thesis .\nqed\n\nlemma exp_mod_exp:\n  \\<open>2 ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\\<close>\nproof -\n  have \\<open>(2::nat) ^ m mod 2 ^ n = of_bool (m < n) * 2 ^ m\\<close> (is \\<open>?lhs = ?rhs\\<close>)\n    by (auto simp add: not_less monoid_mult_class.power_add dest!: le_Suc_ex)\n  then have \\<open>of_nat ?lhs = of_nat ?rhs\\<close>\n    by simp\n  then show ?thesis\n    by (simp add: of_nat_mod)\nqed\n\nlemma mask_mod_exp:\n  \\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - 1\\<close>\nproof -\n  have \\<open>(2 ^ n - 1) mod 2 ^ m = 2 ^ min m n - (1::nat)\\<close> (is \\<open>?lhs = ?rhs\\<close>)\n  proof (cases \\<open>n \\<le> m\\<close>)\n    case True\n    then show ?thesis\n      by (simp add: Suc_le_lessD)\n  next\n    case False\n    then have \\<open>m < n\\<close>\n      by simp\n    then obtain q where n: \\<open>n = Suc q + m\\<close>\n      by (auto dest: less_imp_Suc_add)\n    then have \\<open>min m n = m\\<close>\n      by simp\n    moreover have \\<open>(2::nat) ^ m \\<le> 2 * 2 ^ q * 2 ^ m\\<close>\n      using mult_le_mono1 [of 1 \\<open>2 * 2 ^ q\\<close> \\<open>2 ^ m\\<close>] by simp\n    with n have \\<open>2 ^ n - 1 = (2 ^ Suc q - 1) * 2 ^ m + (2 ^ m - (1::nat))\\<close>\n      by (simp add: monoid_mult_class.power_add algebra_simps)\n    ultimately show ?thesis\n      by (simp only: euclidean_semiring_cancel_class.mod_mult_self3) simp\n  qed\n  then have \\<open>of_nat ?lhs = of_nat ?rhs\\<close>\n    by simp\n  then show ?thesis\n    by (simp add: of_nat_mod of_nat_diff)\nqed\n\nlemma of_bool_half_eq_0 [simp]:\n  \\<open>of_bool b div 2 = 0\\<close>\n  by simp\n\nend\n\nclass unique_euclidean_ring_with_nat = ring + unique_euclidean_semiring_with_nat\n\ninstance nat :: unique_euclidean_semiring_with_nat\n  by standard (simp_all add: dvd_eq_mod_eq_0)\n\ninstance int :: unique_euclidean_ring_with_nat\n  by standard (auto simp add: divide_int_def division_segment_int_def elim: contrapos_np)\n\n\nsubsection \\<open>More on euclidean division on \\<^typ>\\<open>int\\<close>\\<close>\n\nsubsubsection \\<open>Trivial reduction steps\\<close>\n\nlemma div_pos_pos_trivial [simp]:\n  \"k div l = 0\" if \"k \\<ge> 0\" and \"k < l\" for k l :: int\n  using that by (simp add: unique_euclidean_semiring_class.div_eq_0_iff division_segment_int_def)\n\nlemma mod_pos_pos_trivial [simp]:\n  \"k mod l = k\" if \"k \\<ge> 0\" and \"k < l\" for k l :: int\n  using that by (simp add: mod_eq_self_iff_div_eq_0)\n\nlemma div_neg_neg_trivial [simp]:\n  \"k div l = 0\" if \"k \\<le> 0\" and \"l < k\" for k l :: int\n  using that by (cases \"k = 0\") (simp, simp add: unique_euclidean_semiring_class.div_eq_0_iff division_segment_int_def)\n\nlemma mod_neg_neg_trivial [simp]:\n  \"k mod l = k\" if \"k \\<le> 0\" and \"l < k\" for k l :: int\n  using that by (simp add: mod_eq_self_iff_div_eq_0)\n\nlemma\n  div_pos_neg_trivial: \\<open>k div l = - 1\\<close>  (is ?Q)\n  and mod_pos_neg_trivial: \\<open>k mod l = k + l\\<close>  (is ?R)\n    if \\<open>0 < k\\<close> and \\<open>k + l \\<le> 0\\<close> for k l :: int\nproof -\n  from that have \\<open>l < 0\\<close>\n    by simp\n  have \\<open>(k div l, k mod l) = (- 1, k + l)\\<close>\n  proof (cases l \\<open>- 1 :: int\\<close> \\<open>k + l\\<close> k rule: euclidean_relation_intI)\n    case by0\n    with \\<open>l < 0\\<close> show ?case\n      by simp\n  next\n    case divides\n    from \\<open>l dvd k\\<close> obtain j where \\<open>k = l * j\\<close> ..\n    with \\<open>l < 0\\<close> \\<open>0 < k\\<close> have \\<open>j < 0\\<close>\n      by (simp add: zero_less_mult_iff)\n    moreover from \\<open>k + l \\<le> 0\\<close> \\<open>k = l * j\\<close> have \\<open>l * (j + 1) \\<le> 0\\<close>\n      by (simp add: algebra_simps)\n    with \\<open>l < 0\\<close> have \\<open>j + 1 \\<ge> 0\\<close>\n      by (simp add: mult_le_0_iff)\n    with \\<open>j < 0\\<close> have \\<open>j = - 1\\<close>\n      by simp\n    with \\<open>k = l * j\\<close> show ?case\n      by simp\n  next\n    case euclidean_relation\n    with \\<open>k + l \\<le> 0\\<close> have \\<open>k + l < 0\\<close>\n      by (auto simp add: less_le add_eq_0_iff)\n    with \\<open>0 < k\\<close> show ?case\n      by simp\n  qed\n  then show ?Q and ?R\n    by simp_all\nqed\n\ntext \\<open>There is neither \\<open>div_neg_pos_trivial\\<close> nor \\<open>mod_neg_pos_trivial\\<close>\n  because \\<^term>\\<open>0 div l = 0\\<close> would supersede it.\\<close>\n\n\nsubsubsection \\<open>More uniqueness rules\\<close>\n\nlemma\n  fixes a b q r :: int\n  assumes \\<open>a = b * q + r\\<close> \\<open>0 \\<le> r\\<close> \\<open>r < b\\<close>\n  shows int_div_pos_eq:\n      \\<open>a div b = q\\<close> (is ?Q)\n    and int_mod_pos_eq:\n      \\<open>a mod b = r\\<close> (is ?R)\nproof -\n  from assms have \\<open>(a div b, a mod b) = (q, r)\\<close>\n    by (cases b q r a rule: euclidean_relation_intI)\n      (auto simp add: ac_simps dvd_add_left_iff sgn_1_pos le_less dest: zdvd_imp_le)\n  then show ?Q and ?R\n    by simp_all\nqed\n\nlemma int_div_neg_eq:\n  \\<open>a div b = q\\<close> if \\<open>a = b * q + r\\<close> \\<open>r \\<le> 0\\<close> \\<open>b < r\\<close> for a b q r :: int\n  using that int_div_pos_eq [of a \\<open>- b\\<close> \\<open>- q\\<close> \\<open>- r\\<close>] by simp_all\n\nlemma int_mod_neg_eq:\n  \\<open>a mod b = r\\<close> if \\<open>a = b * q + r\\<close> \\<open>r \\<le> 0\\<close> \\<open>b < r\\<close> for a b q r :: int\n  using that int_div_neg_eq [of a b q r] by simp\n\n\nsubsubsection \\<open>Laws for unary minus\\<close>\n\nlemma zmod_zminus1_not_zero:\n  fixes k l :: int\n  shows \"- k mod l \\<noteq> 0 \\<Longrightarrow> k mod l \\<noteq> 0\"\n  by (simp add: mod_eq_0_iff_dvd)\n\nlemma zmod_zminus2_not_zero:\n  fixes k l :: int\n  shows \"k mod - l \\<noteq> 0 \\<Longrightarrow> k mod l \\<noteq> 0\"\n  by (simp add: mod_eq_0_iff_dvd)\n\nlemma zdiv_zminus1_eq_if:\n  \\<open>(- a) div b = (if a mod b = 0 then - (a div b) else - (a div b) - 1)\\<close>\n  if \\<open>b \\<noteq> 0\\<close> for a b :: int\n  using that sgn_not_eq_imp [of b \\<open>- a\\<close>]\n  by (cases \\<open>a = 0\\<close>) (auto simp add: div_eq_div_abs [of \\<open>- a\\<close> b] div_eq_div_abs [of a b] sgn_eq_0_iff)\n\nlemma zdiv_zminus2_eq_if:\n  \\<open>a div (- b) = (if a mod b = 0 then - (a div b) else - (a div b) - 1)\\<close>\n  if \\<open>b \\<noteq> 0\\<close> for a b :: int\n  using that by (auto simp add: zdiv_zminus1_eq_if div_minus_right)\n\nlemma zmod_zminus1_eq_if:\n  \\<open>(- a) mod b = (if a mod b = 0 then 0 else b - (a mod b))\\<close>\n  for a b :: int\n  by (cases \\<open>b = 0\\<close>)\n    (auto simp flip: minus_div_mult_eq_mod simp add: zdiv_zminus1_eq_if algebra_simps)\n\nlemma zmod_zminus2_eq_if:\n  \\<open>a mod (- b) = (if a mod b = 0 then 0 else (a mod b) - b)\\<close>\n  for a b :: int\n  by (auto simp add: zmod_zminus1_eq_if mod_minus_right)\n\n\nsubsubsection \\<open>Borders\\<close>\n\nlemma pos_mod_bound [simp]:\n  \"k mod l < l\" if \"l > 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain n where \"l = sgn 1 * int n\"\n    by (cases l) simp_all\n  moreover from this that have \"n > 0\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold)\n      (auto simp add: mod_greater_zero_iff_not_dvd sgn_1_pos)\nqed\n\nlemma neg_mod_bound [simp]:\n  \"l < k mod l\" if \"l < 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain q where \"l = sgn (- 1) * int (Suc q)\"\n    by (cases l) simp_all\n  moreover define n where \"n = Suc q\"\n  then have \"Suc q = n\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold)\n      (auto simp add: mod_greater_zero_iff_not_dvd sgn_1_neg)\nqed\n\nlemma pos_mod_sign [simp]:\n  \"0 \\<le> k mod l\" if \"l > 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain n where \"l = sgn 1 * int n\"\n    by (cases l) auto\n  moreover from this that have \"n > 0\"\n    by simp\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold) (auto simp add: sgn_1_pos)\nqed\n\nlemma neg_mod_sign [simp]:\n  \"k mod l \\<le> 0\" if \"l < 0\" for k l :: int\nproof -\n  obtain m and s where \"k = sgn s * int m\"\n    by (rule int_sgnE)\n  moreover from that obtain q where \"l = sgn (- 1) * int (Suc q)\"\n    by (cases l) simp_all\n  moreover define n where \"n = Suc q\"\n  then have \"Suc q = n\"\n    by simp\n  moreover have \\<open>int (m mod n) \\<le> int n\\<close>\n    using \\<open>Suc q = n\\<close> by simp\n  then have \\<open>sgn s * int (m mod n) \\<le> int n\\<close>\n    by (cases s \\<open>0::int\\<close> rule: linorder_cases) simp_all\n  ultimately show ?thesis\n    by (simp only: modulo_int_unfold) auto\nqed\n\n\nsubsubsection \\<open>Splitting Rules for div and mod\\<close>\n\nlemma split_zdiv:\n  \\<open>P (n div k) \\<longleftrightarrow>\n    (k = 0 \\<longrightarrow> P 0) \\<and>\n    (0 < k \\<longrightarrow> (\\<forall>i j. 0 \\<le> j \\<and> j < k \\<and> n = k * i + j \\<longrightarrow> P i)) \\<and>\n    (k < 0 \\<longrightarrow> (\\<forall>i j. k < j \\<and> j \\<le> 0 \\<and> n = k * i + j \\<longrightarrow> P i))\\<close> (is ?div)\n  and split_zmod:\n  \\<open>Q (n mod k) \\<longleftrightarrow>\n    (k = 0 \\<longrightarrow> Q n) \\<and>\n    (0 < k \\<longrightarrow> (\\<forall>i j. 0 \\<le> j \\<and> j < k \\<and> n = k * i + j \\<longrightarrow> Q j)) \\<and>\n    (k < 0 \\<longrightarrow> (\\<forall>i j. k < j \\<and> j \\<le> 0 \\<and> n = k * i + j \\<longrightarrow> Q j))\\<close> (is ?mod)\n  for n k :: int\nproof -\n  have *: \\<open>R (n div k) (n mod k) \\<longleftrightarrow>\n    (k = 0 \\<longrightarrow> R 0 n) \\<and>\n    (0 < k \\<longrightarrow> (\\<forall>i j. 0 \\<le> j \\<and> j < k \\<and> n = k * i + j \\<longrightarrow> R i j)) \\<and>\n    (k < 0 \\<longrightarrow> (\\<forall>i j. k < j \\<and> j \\<le> 0 \\<and> n = k * i + j \\<longrightarrow> R i j))\\<close> for R\n    by (cases \\<open>k = 0\\<close>)\n      (auto simp add: linorder_class.neq_iff)\n  from * [of \\<open>\\<lambda>q _. P q\\<close>] show ?div .\n  from * [of \\<open>\\<lambda>_ r. Q r\\<close>] show ?mod .\nqed\n\ntext \\<open>Enable (lin)arith to deal with \\<^const>\\<open>divide\\<close> and \\<^const>\\<open>modulo\\<close>\n  when these are applied to some constant that is of the form\n  \\<^term>\\<open>numeral k\\<close>:\\<close>\ndeclare split_zdiv [of _ _ \\<open>numeral n\\<close>, linarith_split] for n\ndeclare split_zdiv [of _ _ \\<open>- numeral n\\<close>, linarith_split] for n\ndeclare split_zmod [of _ _ \\<open>numeral n\\<close>, linarith_split] for n\ndeclare split_zmod [of _ _ \\<open>- numeral n\\<close>, linarith_split] for n\n\nlemma zdiv_eq_0_iff:\n  \"i div k = 0 \\<longleftrightarrow> k = 0 \\<or> 0 \\<le> i \\<and> i < k \\<or> i \\<le> 0 \\<and> k < i\" (is \"?L = ?R\")\n  for i k :: int\nproof\n  assume ?L\n  moreover have \"?L \\<longrightarrow> ?R\"\n    by (rule split_zdiv [THEN iffD2]) simp\n  ultimately show ?R\n    by blast\nnext\n  assume ?R then show ?L\n    by auto\nqed\n\nlemma zmod_trivial_iff:\n  fixes i k :: int\n  shows \"i mod k = i \\<longleftrightarrow> k = 0 \\<or> 0 \\<le> i \\<and> i < k \\<or> i \\<le> 0 \\<and> k < i\"\nproof -\n  have \"i mod k = i \\<longleftrightarrow> i div k = 0\"\n    using div_mult_mod_eq [of i k] by safe auto\n  with zdiv_eq_0_iff\n  show ?thesis\n    by simp\nqed\n\n\nsubsubsection \\<open>Algebraic rewrites\\<close>\n\nlemma zdiv_zmult2_eq:\n  \\<open>a div (b * c) = (a div b) div c\\<close> if \\<open>c \\<ge> 0\\<close> for a b c :: int\nproof (cases \\<open>b \\<ge> 0\\<close>)\n  case True\n  with that show ?thesis\n    using div_mult2_eq' [of a \\<open>nat b\\<close> \\<open>nat c\\<close>] by simp\nnext\n  case False\n  with that show ?thesis\n    using div_mult2_eq' [of \\<open>- a\\<close> \\<open>nat (- b)\\<close> \\<open>nat c\\<close>] by simp\nqed\n\nlemma zdiv_zmult2_eq':\n  \\<open>k div (l * j) = ((sgn j * k) div l) div \\<bar>j\\<bar>\\<close> for k l j :: int\nproof -\n  have \\<open>k div (l * j) = (sgn j * k) div (sgn j * (l * j))\\<close>\n    by (simp add: sgn_0_0)\n  also have \\<open>sgn j * (l * j) = l * \\<bar>j\\<bar>\\<close>\n    by (simp add: mult.left_commute [of _ l] abs_sgn) (simp add: ac_simps)\n  also have \\<open>(sgn j * k) div (l * \\<bar>j\\<bar>) = ((sgn j * k) div l) div \\<bar>j\\<bar>\\<close>\n    by (simp add: zdiv_zmult2_eq)\n  finally show ?thesis .\nqed\n\nlemma zmod_zmult2_eq:\n  \\<open>a mod (b * c) = b * (a div b mod c) + a mod b\\<close> if \\<open>c \\<ge> 0\\<close> for a b c :: int\nproof (cases \\<open>b \\<ge> 0\\<close>)\n  case True\n  with that show ?thesis\n    using mod_mult2_eq' [of a \\<open>nat b\\<close> \\<open>nat c\\<close>] by simp\nnext\n  case False\n  with that show ?thesis\n    using mod_mult2_eq' [of \\<open>- a\\<close> \\<open>nat (- b)\\<close> \\<open>nat c\\<close>] by simp\nqed\n\nlemma half_nonnegative_int_iff [simp]:\n  \\<open>k div 2 \\<ge> 0 \\<longleftrightarrow> k \\<ge> 0\\<close> for k :: int\n  by auto\n\nlemma half_negative_int_iff [simp]:\n  \\<open>k div 2 < 0 \\<longleftrightarrow> k < 0\\<close> for k :: int\n  by auto\n\n\nsubsubsection \\<open>Distributive laws for conversions.\\<close>\n\nlemma zdiv_int:\n  \"int (a div b) = int a div int b\"\n  by (fact of_nat_div)\n\nlemma zmod_int:\n  \"int (a mod b) = int a mod int b\"\n  by (fact of_nat_mod)\n\nlemma nat_div_distrib:\n  \\<open>nat (x div y) = nat x div nat y\\<close> if \\<open>0 \\<le> x\\<close>\n  using that by (simp add: divide_int_def sgn_if)\n\nlemma nat_div_distrib':\n  \\<open>nat (x div y) = nat x div nat y\\<close> if \\<open>0 \\<le> y\\<close>\n  using that by (simp add: divide_int_def sgn_if)\n\nlemma nat_mod_distrib: \\<comment> \\<open>Fails if y<0: the LHS collapses to (nat z) but the RHS doesn't\\<close>\n  \\<open>nat (x mod y) = nat x mod nat y\\<close> if \\<open>0 \\<le> x\\<close> \\<open>0 \\<le> y\\<close>\n  using that by (simp add: modulo_int_def sgn_if)\n\n\nsubsubsection \\<open>Monotonicity in the First Argument (Dividend)\\<close>\n\nlemma zdiv_mono1:\n  \\<open>a div b \\<le> a' div b\\<close>\n    if \\<open>a \\<le> a'\\<close> \\<open>0 < b\\<close>\n    for a b b' :: int\nproof -\n  from \\<open>a \\<le> a'\\<close> have \\<open>b * (a div b) + a mod b \\<le> b * (a' div b) + a' mod b\\<close>\n    by simp\n  then have \\<open>b * (a div b) \\<le> (a' mod b - a mod b) + b * (a' div b)\\<close>\n    by (simp add: algebra_simps)\n  moreover have \\<open>a' mod b < b + a mod b\\<close>\n    by (rule less_le_trans [of _ b]) (use \\<open>0 < b\\<close> in simp_all)\n  ultimately have \\<open>b * (a div b) < b * (1 + a' div b)\\<close>\n    by (simp add: distrib_left)\n  with \\<open>0 < b\\<close> have \\<open>a div b < 1 + a' div b\\<close>\n    by (simp add: mult_less_cancel_left)\n  then show ?thesis\n    by simp\nqed\n\nlemma zdiv_mono1_neg:\n  \\<open>a' div b \\<le> a div b\\<close>\n    if \\<open>a \\<le> a'\\<close> \\<open>b < 0\\<close>\n    for a a' b :: int\n  using that zdiv_mono1 [of \\<open>- a'\\<close> \\<open>- a\\<close> \\<open>- b\\<close>] by simp\n\n\nsubsubsection \\<open>Monotonicity in the Second Argument (Divisor)\\<close>\n\nlemma zdiv_mono2:\n  \\<open>a div b \\<le> a div b'\\<close> if \\<open>0 \\<le> a\\<close> \\<open>0 < b'\\<close> \\<open>b' \\<le> b\\<close> for a b b' :: int\nproof -\n  define q q' r r' where **: \\<open>q = a div b\\<close> \\<open>q' = a div b'\\<close> \\<open>r = a mod b\\<close> \\<open>r' = a mod b'\\<close>\n  then have *: \\<open>b * q + r = b' * q' + r'\\<close> \\<open>0 \\<le> b' * q' + r'\\<close>\n    \\<open>r' < b'\\<close> \\<open>0 \\<le> r\\<close> \\<open>0 < b'\\<close> \\<open>b' \\<le> b\\<close>\n    using that by simp_all\n  have \\<open>0 < b' * (q' + 1)\\<close>\n    using * by (simp add: distrib_left)\n  with * have \\<open>0 \\<le> q'\\<close>\n    by (simp add: zero_less_mult_iff)\n  moreover have \\<open>b * q = r' - r + b' * q'\\<close>\n    using * by linarith\n  ultimately have \\<open>b * q < b * (q' + 1)\\<close>\n    using mult_right_mono * unfolding distrib_left by fastforce\n  with * have \\<open>q \\<le> q'\\<close>\n    by (simp add: mult_less_cancel_left_pos)\n  with ** show ?thesis\n    by simp\nqed\n\nlemma zdiv_mono2_neg:\n  \\<open>a div b' \\<le> a div b\\<close> if \\<open>a < 0\\<close> \\<open>0 < b'\\<close> \\<open>b' \\<le> b\\<close> for a b b' :: int\nproof -\n  define q q' r r' where **: \\<open>q = a div b\\<close> \\<open>q' = a div b'\\<close> \\<open>r = a mod b\\<close> \\<open>r' = a mod b'\\<close>\n  then have *: \\<open>b * q + r = b' * q' + r'\\<close> \\<open>b' * q' + r' < 0\\<close>\n    \\<open>r < b\\<close> \\<open>0 \\<le> r'\\<close> \\<open>0 < b'\\<close> \\<open>b' \\<le> b\\<close>\n    using that by simp_all\n  have \\<open>b' * q' < 0\\<close>\n    using * by linarith\n  with * have \\<open>q' \\<le> 0\\<close>\n    by (simp add: mult_less_0_iff)\n  have \\<open>b * q' \\<le> b' * q'\\<close>\n    by (simp add: \\<open>q' \\<le> 0\\<close> * mult_right_mono_neg)\n  then have \"b * q' < b * (q + 1)\"\n    using * by (simp add: distrib_left)\n  then have \\<open>q' \\<le> q\\<close>\n    using * by (simp add: mult_less_cancel_left)\n  then show ?thesis\n    by (simp add: **)\nqed\n\n\nsubsubsection \\<open>Quotients of Signs\\<close>\n\nlemma div_eq_minus1:\n  \\<open>0 < b \\<Longrightarrow> - 1 div b = - 1\\<close> for b :: int\n  by (simp add: divide_int_def)\n\nlemma zmod_minus1:\n  \\<open>0 < b \\<Longrightarrow> - 1 mod b = b - 1\\<close> for b :: int\n  by (auto simp add: modulo_int_def)\n\nlemma minus_mod_int_eq:\n  \\<open>- k mod l = l - 1 - (k - 1) mod l\\<close> if \\<open>l \\<ge> 0\\<close> for k l :: int\nproof (cases \\<open>l = 0\\<close>)\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  with that have \\<open>l > 0\\<close>\n    by simp\n  then show ?thesis\n  proof (cases \\<open>l dvd k\\<close>)\n    case True\n    then obtain j where \\<open>k = l * j\\<close> ..\n    moreover have \\<open>(l * j mod l - 1) mod l = l - 1\\<close>\n      using \\<open>l > 0\\<close> by (simp add: zmod_minus1)\n    then have \\<open>(l * j - 1) mod l = l - 1\\<close>\n      by (simp only: mod_simps)\n    ultimately show ?thesis\n      by simp\n  next\n    case False\n    moreover have 1: \\<open>0 < k mod l\\<close>\n      using \\<open>0 < l\\<close> False le_less by fastforce\n    moreover have 2: \\<open>k mod l < 1 + l\\<close>\n      using \\<open>0 < l\\<close> pos_mod_bound[of l k] by linarith\n    from 1 2 \\<open>l > 0\\<close> have \\<open>(k mod l - 1) mod l = k mod l - 1\\<close>\n      by (simp add: zmod_trivial_iff)\n    ultimately show ?thesis\n      by (simp only: zmod_zminus1_eq_if)\n         (simp add: mod_eq_0_iff_dvd algebra_simps mod_simps)\n  qed\nqed\n\nlemma div_neg_pos_less0:\n  \\<open>a div b < 0\\<close> if \\<open>a < 0\\<close> \\<open>0 < b\\<close> for a b :: int\nproof -\n  have \"a div b \\<le> - 1 div b\"\n    using zdiv_mono1 that by auto\n  also have \"... \\<le> -1\"\n    by (simp add: that(2) div_eq_minus1)\n  finally show ?thesis\n    by force\nqed\n\nlemma div_nonneg_neg_le0:\n  \\<open>a div b \\<le> 0\\<close> if \\<open>0 \\<le> a\\<close> \\<open>b < 0\\<close> for a b :: int\n  using that by (auto dest: zdiv_mono1_neg)\n\nlemma div_nonpos_pos_le0:\n  \\<open>a div b \\<le> 0\\<close> if \\<open>a \\<le> 0\\<close> \\<open>0 < b\\<close> for a b :: int\n  using that by (auto dest: zdiv_mono1)\n\ntext\\<open>Now for some equivalences of the form \\<open>a div b >=< 0 \\<longleftrightarrow> \\<dots>\\<close>\nconditional upon the sign of \\<open>a\\<close> or \\<open>b\\<close>. There are many more.\nThey should all be simp rules unless that causes too much search.\\<close>\n\nlemma pos_imp_zdiv_nonneg_iff:\n  \\<open>0 \\<le> a div b \\<longleftrightarrow> 0 \\<le> a\\<close>\n  if \\<open>0 < b\\<close> for a b :: int\nproof\n  assume \\<open>0 \\<le> a div b\\<close>\n  show \\<open>0 \\<le> a\\<close>\n  proof (rule ccontr)\n    assume \\<open>\\<not> 0 \\<le> a\\<close>\n    then have \\<open>a < 0\\<close>\n      by simp\n    then have \\<open>a div b < 0\\<close>\n      using that by (rule div_neg_pos_less0)\n    with \\<open>0 \\<le> a div b\\<close> show False\n      by simp\n  qed\nnext\n  assume \"0 \\<le> a\"\n  then have \"0 div b \\<le> a div b\"\n    using zdiv_mono1 that by blast\n  then show \"0 \\<le> a div b\"\n    by auto\nqed\n\nlemma neg_imp_zdiv_nonneg_iff:\n  \\<open>0 \\<le> a div b \\<longleftrightarrow> a \\<le> 0\\<close> if \\<open>b < 0\\<close> for a b :: int\n  using that pos_imp_zdiv_nonneg_iff [of \\<open>- b\\<close> \\<open>- a\\<close>] by simp\n\nlemma pos_imp_zdiv_pos_iff:\n  \\<open>0 < (i::int) div k \\<longleftrightarrow> k \\<le> i\\<close> if \\<open>0 < k\\<close> for i k :: int\n  using that pos_imp_zdiv_nonneg_iff [of k i] zdiv_eq_0_iff [of i k] by arith\n\nlemma pos_imp_zdiv_neg_iff:\n  \\<open>a div b < 0 \\<longleftrightarrow> a < 0\\<close> if \\<open>0 < b\\<close> for a b :: int\n    \\<comment> \\<open>But not \\<^prop>\\<open>a div b \\<le> 0 \\<longleftrightarrow> a \\<le> 0\\<close>; consider \\<^prop>\\<open>a = 1\\<close>, \\<^prop>\\<open>b = 2\\<close> when \\<^prop>\\<open>a div b = 0\\<close>.\\<close>\n  using that by (simp add: pos_imp_zdiv_nonneg_iff flip: linorder_not_le)\n\nlemma neg_imp_zdiv_neg_iff:\n    \\<comment> \\<open>But not \\<^prop>\\<open>a div b \\<le> 0 \\<longleftrightarrow> 0 \\<le> a\\<close>; consider \\<^prop>\\<open>a = - 1\\<close>, \\<^prop>\\<open>b = - 2\\<close> when \\<^prop>\\<open>a div b = 0\\<close>.\\<close>\n  \\<open>a div b < 0 \\<longleftrightarrow> 0 < a\\<close> if \\<open>b < 0\\<close> for a b :: int\n  using that by (simp add: neg_imp_zdiv_nonneg_iff flip: linorder_not_le)\n\nlemma nonneg1_imp_zdiv_pos_iff:\n  \\<open>a div b > 0 \\<longleftrightarrow> a \\<ge> b \\<and> b > 0\\<close> if \\<open>0 \\<le> a\\<close> for a b :: int\nproof -\n  have \"0 < a div b \\<Longrightarrow> b \\<le> a\"\n    using div_pos_pos_trivial[of a b] that by arith\n  moreover have \"0 < a div b \\<Longrightarrow> b > 0\"\n    using that div_nonneg_neg_le0[of a b] by (cases \"b=0\"; force)\n  moreover have \"b \\<le> a \\<and> 0 < b \\<Longrightarrow> 0 < a div b\"\n    using int_one_le_iff_zero_less[of \"a div b\"] zdiv_mono1[of b a b] by simp\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma zmod_le_nonneg_dividend:\n  \\<open>m mod k \\<le> m\\<close> if \\<open>(m::int) \\<ge> 0\\<close> for m k :: int\nproof -\n  from that have \\<open>m > 0 \\<or> m = 0\\<close>\n    by auto\n  then show ?thesis proof\n    assume \\<open>m = 0\\<close> then show ?thesis\n      by simp\n  next\n    assume \\<open>m > 0\\<close> then show ?thesis\n    proof (cases k \\<open>0::int\\<close> rule: linorder_cases)\n      case less\n      moreover define l where \\<open>l = - k\\<close>\n      ultimately have \\<open>l > 0\\<close>\n        by simp\n      with \\<open>m > 0\\<close> have \\<open>int (nat m mod nat l) \\<le> m\\<close>\n        by (simp flip: le_nat_iff)\n      then have \\<open>int (nat m mod nat l) - l \\<le> m\\<close>\n        using \\<open>l > 0\\<close> by simp\n      with \\<open>m > 0\\<close> \\<open>l > 0\\<close> show ?thesis\n        by (simp add: modulo_int_def l_def flip: le_nat_iff)\n    qed (simp_all add: modulo_int_def flip: le_nat_iff)\n  qed\nqed\n\nlemma sgn_div_eq_sgn_mult:\n  \\<open>sgn (k div l) = of_bool (k div l \\<noteq> 0) * sgn (k * l)\\<close>\n  for k l :: int\nproof (cases \\<open>k div l = 0\\<close>)\n  case True\n  then show ?thesis\n    by simp\nnext\n  case False\n  have \\<open>0 \\<le> \\<bar>k\\<bar> div \\<bar>l\\<bar>\\<close>\n    by (cases \\<open>l = 0\\<close>) (simp_all add: pos_imp_zdiv_nonneg_iff)\n  then have \\<open>\\<bar>k\\<bar> div \\<bar>l\\<bar> \\<noteq> 0 \\<longleftrightarrow> 0 < \\<bar>k\\<bar> div \\<bar>l\\<bar>\\<close>\n    by (simp add: less_le)\n  also have \\<open>\\<dots> \\<longleftrightarrow> \\<bar>k\\<bar> \\<ge> \\<bar>l\\<bar>\\<close>\n    using False nonneg1_imp_zdiv_pos_iff by auto\n  finally have *: \\<open>\\<bar>k\\<bar> div \\<bar>l\\<bar> \\<noteq> 0 \\<longleftrightarrow> \\<bar>l\\<bar> \\<le> \\<bar>k\\<bar>\\<close> .\n  show ?thesis\n    using \\<open>0 \\<le> \\<bar>k\\<bar> div \\<bar>l\\<bar>\\<close> False\n  by (auto simp add: div_eq_div_abs [of k l] div_eq_sgn_abs [of k l]\n    sgn_mult sgn_1_pos sgn_1_neg sgn_eq_0_iff nonneg1_imp_zdiv_pos_iff * dest: sgn_not_eq_imp)\nqed\n\n\nsubsubsection \\<open>Further properties\\<close>\n\nlemma div_int_pos_iff:\n  \"k div l \\<ge> 0 \\<longleftrightarrow> k = 0 \\<or> l = 0 \\<or> k \\<ge> 0 \\<and> l \\<ge> 0\n    \\<or> k < 0 \\<and> l < 0\"\n  for k l :: int\nproof (cases \"k = 0 \\<or> l = 0\")\n  case False\n  then have *: \"k \\<noteq> 0\" \"l \\<noteq> 0\"\n    by auto\n  then have \"0 \\<le> k div l \\<Longrightarrow> \\<not> k < 0 \\<Longrightarrow> 0 \\<le> l\"\n    by (meson neg_imp_zdiv_neg_iff not_le not_less_iff_gr_or_eq)\n  then show ?thesis\n   using * by (auto simp add: pos_imp_zdiv_nonneg_iff neg_imp_zdiv_nonneg_iff)\nqed auto\n\nlemma mod_int_pos_iff:\n  \\<open>k mod l \\<ge> 0 \\<longleftrightarrow> l dvd k \\<or> l = 0 \\<and> k \\<ge> 0 \\<or> l > 0\\<close>\n  for k l :: int\nproof (cases \"l > 0\")\n  case False\n  then show ?thesis\n    by (simp add: dvd_eq_mod_eq_0) (use neg_mod_sign [of l k] in \\<open>auto simp add: le_less not_less\\<close>)\nqed auto\n\nlemma abs_div:\n  \\<open>\\<bar>x div y\\<bar> = \\<bar>x\\<bar> div \\<bar>y\\<bar>\\<close> if \\<open>y dvd x\\<close> for x y :: int\n  using that by (cases \\<open>y = 0\\<close>) (auto simp add: abs_mult)\n\nlemma int_power_div_base: \\<^marker>\\<open>contributor \\<open>Matthias Daum\\<close>\\<close>\n  \\<open>k ^ m div k = k ^ (m - Suc 0)\\<close> if \\<open>0 < m\\<close> \\<open>0 < k\\<close> for k :: int\n  using that by (cases m) simp_all\n\nlemma int_div_less_self: \\<^marker>\\<open>contributor \\<open>Matthias Daum\\<close>\\<close>\n  \\<open>x div k < x\\<close> if \\<open>0 < x\\<close> \\<open>1 < k\\<close> for x k :: int\nproof -\n  from that have \\<open>nat (x div k) = nat x div nat k\\<close>\n    by (simp add: nat_div_distrib)\n  also from that have \\<open>nat x div nat k < nat x\\<close>\n    by simp\n  finally show ?thesis\n    by simp\nqed\n\n\nsubsubsection \\<open>Computing \\<open>div\\<close> and \\<open>mod\\<close> by shifting\\<close>\n\nlemma div_pos_geq:\n  \\<open>k div l = (k - l) div l + 1\\<close> if \\<open>0 < l\\<close> \\<open>l \\<le> k\\<close> for k l :: int\nproof -\n  have \"k = (k - l) + l\" by simp\n  then obtain j where k: \"k = j + l\" ..\n  with that show ?thesis by (simp add: div_add_self2)\nqed\n\nlemma mod_pos_geq:\n  \\<open>k mod l = (k - l) mod l\\<close>  if \\<open>0 < l\\<close> \\<open>l \\<le> k\\<close> for k l :: int\nproof -\n  have \"k = (k - l) + l\" by simp\n  then obtain j where k: \"k = j + l\" ..\n  with that show ?thesis by simp\nqed\n\nlemma pos_zdiv_mult_2: \\<open>(1 + 2 * b) div (2 * a) = b div a\\<close> (is ?Q)\n  and pos_zmod_mult_2: \\<open>(1 + 2 * b) mod (2 * a) = 1 + 2 * (b mod a)\\<close> (is ?R)\n  if \\<open>0 \\<le> a\\<close> for a b :: int\nproof -\n  have \\<open>((1 + 2 * b) div (2 * a), (1 + 2 * b) mod (2 * a)) = (b div a, 1 + 2 * (b mod a))\\<close>\n  proof (cases \\<open>2 * a\\<close> \\<open>b div a\\<close> \\<open>1 + 2 * (b mod a)\\<close> \\<open>1 + 2 * b\\<close> rule: euclidean_relation_intI)\n    case by0\n    then show ?case\n      by simp\n  next\n    case divides\n    have \\<open>2 dvd (2 * a)\\<close>\n      by simp\n    then have \\<open>2 dvd (1 + 2 * b)\\<close>\n      using \\<open>2 * a dvd 1 + 2 * b\\<close> by (rule dvd_trans)\n    then have \\<open>2 dvd (1 + b * 2)\\<close>\n      by (simp add: ac_simps)\n    then have \\<open>is_unit (2 :: int)\\<close>\n      by simp\n    then show ?case\n      by simp\n  next\n    case euclidean_relation\n    with that have \\<open>a > 0\\<close>\n      by simp\n    moreover have \\<open>b mod a < a\\<close>\n      using \\<open>a > 0\\<close> by simp\n    then have \\<open>1 + 2 * (b mod a) < 2 * a\\<close>\n      by simp\n    moreover have \\<open>2 * (b mod a) + a * (2 * (b div a)) = 2 * (b div a * a + b mod a)\\<close>\n      by (simp only: algebra_simps)\n    moreover have \\<open>0 \\<le> 2 * (b mod a)\\<close>\n      using \\<open>a > 0\\<close> by simp\n    ultimately show ?case\n      by (simp add: algebra_simps)\n  qed\n  then show ?Q and ?R\n    by simp_all\nqed\n\nlemma neg_zdiv_mult_2: \\<open>(1 + 2 * b) div (2 * a) = (b + 1) div a\\<close> (is ?Q)\n  and neg_zmod_mult_2: \\<open>(1 + 2 * b) mod (2 * a) = 2 * ((b + 1) mod a) - 1\\<close> (is ?R)\n  if \\<open>a \\<le> 0\\<close> for a b :: int\nproof -\n  have \\<open>((1 + 2 * b) div (2 * a), (1 + 2 * b) mod (2 * a)) = ((b + 1) div a, 2 * ((b + 1) mod a) - 1)\\<close>\n  proof (cases \\<open>2 * a\\<close> \\<open>(b + 1) div a\\<close> \\<open>2 * ((b + 1) mod a) - 1\\<close> \\<open>1 + 2 * b\\<close> rule: euclidean_relation_intI)\n    case by0\n    then show ?case\n      by simp\n  next\n    case divides\n    have \\<open>2 dvd (2 * a)\\<close>\n      by simp\n    then have \\<open>2 dvd (1 + 2 * b)\\<close>\n      using \\<open>2 * a dvd 1 + 2 * b\\<close> by (rule dvd_trans)\n    then have \\<open>2 dvd (1 + b * 2)\\<close>\n      by (simp add: ac_simps)\n    then have \\<open>is_unit (2 :: int)\\<close>\n      by simp\n    then show ?case\n      by simp\n  next\n    case euclidean_relation\n    with that have \\<open>a < 0\\<close>\n      by simp\n    moreover have \\<open>(b + 1) mod a > a\\<close>\n      using \\<open>a < 0\\<close> by simp\n    then have \\<open>2 * ((b + 1) mod a) > 1 + 2 * a\\<close>\n      by simp\n    moreover have \\<open>((1 + b) mod a) \\<le> 0\\<close>\n      using \\<open>a < 0\\<close> by simp\n    then have \\<open>2 * ((1 + b) mod a) \\<le> 0\\<close>\n      by simp\n    moreover have \\<open>2 * ((1 + b) mod a) + a * (2 * ((1 + b) div a)) =\n      2 * ((1 + b) div a * a + (1 + b) mod a)\\<close>\n      by (simp only: algebra_simps)\n    ultimately show ?case\n      by (simp add: algebra_simps sgn_mult abs_mult)\n  qed\n  then show ?Q and ?R\n    by simp_all\nqed\n\nlemma zdiv_numeral_Bit0 [simp]:\n  \\<open>numeral (Num.Bit0 v) div numeral (Num.Bit0 w) =\n    numeral v div (numeral w :: int)\\<close>\n  unfolding numeral.simps unfolding mult_2 [symmetric]\n  by (rule div_mult_mult1) simp\n\nlemma zdiv_numeral_Bit1 [simp]:\n  \\<open>numeral (Num.Bit1 v) div numeral (Num.Bit0 w) =\n    (numeral v div (numeral w :: int))\\<close>\n  unfolding numeral.simps\n  unfolding mult_2 [symmetric] add.commute [of _ 1]\n  by (rule pos_zdiv_mult_2) simp\n\nlemma zmod_numeral_Bit0 [simp]:\n  \\<open>numeral (Num.Bit0 v) mod numeral (Num.Bit0 w) =\n    (2::int) * (numeral v mod numeral w)\\<close>\n  unfolding numeral_Bit0 [of v] numeral_Bit0 [of w]\n  unfolding mult_2 [symmetric] by (rule mod_mult_mult1)\n\nlemma zmod_numeral_Bit1 [simp]:\n  \\<open>numeral (Num.Bit1 v) mod numeral (Num.Bit0 w) =\n    2 * (numeral v mod numeral w) + (1::int)\\<close>\n  unfolding numeral_Bit1 [of v] numeral_Bit0 [of w]\n  unfolding mult_2 [symmetric] add.commute [of _ 1]\n  by (rule pos_zmod_mult_2) simp\n\n\nsubsection \\<open>Generic symbolic computations\\<close>\n\ntext \\<open>\n  The following type class contains everything necessary to formulate\n  a division algorithm in ring structures with numerals, restricted\n  to its positive segments.\n\\<close>\n\nclass unique_euclidean_semiring_with_nat_division = unique_euclidean_semiring_with_nat +\n  fixes divmod :: \\<open>num \\<Rightarrow> num \\<Rightarrow> 'a \\<times> 'a\\<close>\n    and divmod_step :: \\<open>'a \\<Rightarrow> 'a \\<times> 'a \\<Rightarrow> 'a \\<times> 'a\\<close> \\<comment> \\<open>\n      These are conceptually definitions but force generated code\n      to be monomorphic wrt. particular instances of this class which\n      yields a significant speedup.\\<close>\n  assumes divmod_def: \\<open>divmod m n = (numeral m div numeral n, numeral m mod numeral n)\\<close>\n    and divmod_step_def [simp]: \\<open>divmod_step l (q, r) =\n      (if euclidean_size l \\<le> euclidean_size r then (2 * q + 1, r - l)\n       else (2 * q, r))\\<close> \\<comment> \\<open>\n         This is a formulation of one step (referring to one digit position)\n         in school-method division: compare the dividend at the current\n         digit position with the remainder from previous division steps\n         and evaluate accordingly.\\<close>\nbegin\n\nlemma fst_divmod:\n  \\<open>fst (divmod m n) = numeral m div numeral n\\<close>\n  by (simp add: divmod_def)\n\nlemma snd_divmod:\n  \\<open>snd (divmod m n) = numeral m mod numeral n\\<close>\n  by (simp add: divmod_def)\n\ntext \\<open>\n  Following a formulation of school-method division.\n  If the divisor is smaller than the dividend, terminate.\n  If not, shift the dividend to the right until termination\n  occurs and then reiterate single division steps in the\n  opposite direction.\n\\<close>\n\nlemma divmod_divmod_step:\n  \\<open>divmod m n = (if m < n then (0, numeral m)\n    else divmod_step (numeral n) (divmod m (Num.Bit0 n)))\\<close>\nproof (cases \\<open>m < n\\<close>)\n  case True\n  then show ?thesis\n    by (simp add: prod_eq_iff fst_divmod snd_divmod flip: of_nat_numeral of_nat_div of_nat_mod)\nnext\n  case False\n  define r s t where \\<open>r = (numeral m :: nat)\\<close> \\<open>s = (numeral n :: nat)\\<close> \\<open>t = 2 * s\\<close>\n  then have *: \\<open>numeral m = of_nat r\\<close> \\<open>numeral n = of_nat s\\<close> \\<open>numeral (num.Bit0 n) = of_nat t\\<close>\n    and \\<open>\\<not> s \\<le> r mod s\\<close>\n    by (simp_all add: not_le)\n  have t: \\<open>2 * (r div t) = r div s - r div s mod 2\\<close>\n    \\<open>r mod t = s * (r div s mod 2) + r mod s\\<close>\n    by (simp add: Rings.minus_mod_eq_mult_div Groups.mult.commute [of 2] Euclidean_Division.div_mult2_eq \\<open>t = 2 * s\\<close>)\n      (use mod_mult2_eq [of r s 2] in \\<open>simp add: ac_simps \\<open>t = 2 * s\\<close>\\<close>)\n  have rs: \\<open>r div s mod 2 = 0 \\<or> r div s mod 2 = Suc 0\\<close>\n    by auto\n  from \\<open>\\<not> s \\<le> r mod s\\<close> have \\<open>s \\<le> r mod t \\<Longrightarrow>\n     r div s = Suc (2 * (r div t)) \\<and>\n     r mod s = r mod t - s\\<close>\n    using rs\n    by (auto simp add: t)\n  moreover have \\<open>r mod t < s \\<Longrightarrow>\n     r div s = 2 * (r div t) \\<and>\n     r mod s = r mod t\\<close>\n    using rs\n    by (auto simp add: t)\n  ultimately show ?thesis\n    by (simp add: divmod_def prod_eq_iff split_def Let_def\n        not_less mod_eq_0_iff_dvd Rings.mod_eq_0_iff_dvd False not_le *)\n    (simp add: flip: of_nat_numeral of_nat_mult add.commute [of 1] of_nat_div of_nat_mod of_nat_Suc of_nat_diff)\nqed\n\ntext \\<open>The division rewrite proper -- first, trivial results involving \\<open>1\\<close>\\<close>\n\nlemma divmod_trivial [simp]:\n  \"divmod m Num.One = (numeral m, 0)\"\n  \"divmod num.One (num.Bit0 n) = (0, Numeral1)\"\n  \"divmod num.One (num.Bit1 n) = (0, Numeral1)\"\n  using divmod_divmod_step [of \"Num.One\"] by (simp_all add: divmod_def)\n\ntext \\<open>Division by an even number is a right-shift\\<close>\n\nlemma divmod_cancel [simp]:\n  \\<open>divmod (Num.Bit0 m) (Num.Bit0 n) = (case divmod m n of (q, r) \\<Rightarrow> (q, 2 * r))\\<close> (is ?P)\n  \\<open>divmod (Num.Bit1 m) (Num.Bit0 n) = (case divmod m n of (q, r) \\<Rightarrow> (q, 2 * r + 1))\\<close> (is ?Q)\nproof -\n  define r s where \\<open>r = (numeral m :: nat)\\<close> \\<open>s = (numeral n :: nat)\\<close>\n  then have *: \\<open>numeral m = of_nat r\\<close> \\<open>numeral n = of_nat s\\<close>\n    \\<open>numeral (num.Bit0 m) = of_nat (2 * r)\\<close> \\<open>numeral (num.Bit0 n) = of_nat (2 * s)\\<close>\n    \\<open>numeral (num.Bit1 m) = of_nat (Suc (2 * r))\\<close>\n    by simp_all\n  have **: \\<open>Suc (2 * r) div 2 = r\\<close>\n    by simp\n  show ?P and ?Q\n    by (simp_all add: divmod_def *)\n      (simp_all flip: of_nat_numeral of_nat_div of_nat_mod of_nat_mult add.commute [of 1] of_nat_Suc\n       add: Euclidean_Division.mod_mult_mult1 div_mult2_eq [of _ 2] mod_mult2_eq [of _ 2] **)\nqed\n\ntext \\<open>The really hard work\\<close>\n\nlemma divmod_steps [simp]:\n  \"divmod (num.Bit0 m) (num.Bit1 n) =\n      (if m \\<le> n then (0, numeral (num.Bit0 m))\n       else divmod_step (numeral (num.Bit1 n))\n             (divmod (num.Bit0 m)\n               (num.Bit0 (num.Bit1 n))))\"\n  \"divmod (num.Bit1 m) (num.Bit1 n) =\n      (if m < n then (0, numeral (num.Bit1 m))\n       else divmod_step (numeral (num.Bit1 n))\n             (divmod (num.Bit1 m)\n               (num.Bit0 (num.Bit1 n))))\"\n  by (simp_all add: divmod_divmod_step)\n\nlemmas divmod_algorithm_code = divmod_trivial divmod_cancel divmod_steps\n\ntext \\<open>Special case: divisibility\\<close>\n\ndefinition divides_aux :: \"'a \\<times> 'a \\<Rightarrow> bool\"\nwhere\n  \"divides_aux qr \\<longleftrightarrow> snd qr = 0\"\n\nlemma divides_aux_eq [simp]:\n  \"divides_aux (q, r) \\<longleftrightarrow> r = 0\"\n  by (simp add: divides_aux_def)\n\nlemma dvd_numeral_simp [simp]:\n  \"numeral m dvd numeral n \\<longleftrightarrow> divides_aux (divmod n m)\"\n  by (simp add: divmod_def mod_eq_0_iff_dvd)\n\ntext \\<open>Generic computation of quotient and remainder\\<close>\n\nlemma numeral_div_numeral [simp]:\n  \"numeral k div numeral l = fst (divmod k l)\"\n  by (simp add: fst_divmod)\n\nlemma numeral_mod_numeral [simp]:\n  \"numeral k mod numeral l = snd (divmod k l)\"\n  by (simp add: snd_divmod)\n\nlemma one_div_numeral [simp]:\n  \"1 div numeral n = fst (divmod num.One n)\"\n  by (simp add: fst_divmod)\n\nlemma one_mod_numeral [simp]:\n  \"1 mod numeral n = snd (divmod num.One n)\"\n  by (simp add: snd_divmod)\n\nend\n\ninstantiation nat :: unique_euclidean_semiring_with_nat_division\nbegin\n\ndefinition divmod_nat :: \"num \\<Rightarrow> num \\<Rightarrow> nat \\<times> nat\"\nwhere\n  divmod'_nat_def: \"divmod_nat m n = (numeral m div numeral n, numeral m mod numeral n)\"\n\ndefinition divmod_step_nat :: \"nat \\<Rightarrow> nat \\<times> nat \\<Rightarrow> nat \\<times> nat\"\nwhere\n  \"divmod_step_nat l qr = (let (q, r) = qr\n    in if r \\<ge> l then (2 * q + 1, r - l)\n    else (2 * q, r))\"\n\ninstance\n  by standard (simp_all add: divmod'_nat_def divmod_step_nat_def)\n\nend\n\ndeclare divmod_algorithm_code [where ?'a = nat, code]\n\nlemma Suc_0_div_numeral [simp]:\n  \\<open>Suc 0 div numeral Num.One = 1\\<close>\n  \\<open>Suc 0 div numeral (Num.Bit0 n) = 0\\<close>\n  \\<open>Suc 0 div numeral (Num.Bit1 n) = 0\\<close>\n  by simp_all\n\nlemma Suc_0_mod_numeral [simp]:\n  \\<open>Suc 0 mod numeral Num.One = 0\\<close>\n  \\<open>Suc 0 mod numeral (Num.Bit0 n) = 1\\<close>\n  \\<open>Suc 0 mod numeral (Num.Bit1 n) = 1\\<close>\n  by simp_all\n\ninstantiation int :: unique_euclidean_semiring_with_nat_division\nbegin\n\ndefinition divmod_int :: \"num \\<Rightarrow> num \\<Rightarrow> int \\<times> int\"\nwhere\n  \"divmod_int m n = (numeral m div numeral n, numeral m mod numeral n)\"\n\ndefinition divmod_step_int :: \"int \\<Rightarrow> int \\<times> int \\<Rightarrow> int \\<times> int\"\nwhere\n  \"divmod_step_int l qr = (let (q, r) = qr\n    in if \\<bar>l\\<bar> \\<le> \\<bar>r\\<bar> then (2 * q + 1, r - l)\n    else (2 * q, r))\"\n\ninstance\n  by standard (auto simp add: divmod_int_def divmod_step_int_def)\n\nend\n\ndeclare divmod_algorithm_code [where ?'a = int, code]\n\ncontext\nbegin\n\nqualified definition adjust_div :: \"int \\<times> int \\<Rightarrow> int\"\nwhere\n  \"adjust_div qr = (let (q, r) = qr in q + of_bool (r \\<noteq> 0))\"\n\nqualified lemma adjust_div_eq [simp, code]:\n  \"adjust_div (q, r) = q + of_bool (r \\<noteq> 0)\"\n  by (simp add: adjust_div_def)\n\nqualified definition adjust_mod :: \"num \\<Rightarrow> int \\<Rightarrow> int\"\nwhere\n  [simp]: \"adjust_mod l r = (if r = 0 then 0 else numeral l - r)\"\n\nlemma minus_numeral_div_numeral [simp]:\n  \"- numeral m div numeral n = - (adjust_div (divmod m n) :: int)\"\nproof -\n  have \"int (fst (divmod m n)) = fst (divmod m n)\"\n    by (simp only: fst_divmod divide_int_def) auto\n  then show ?thesis\n    by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def)\nqed\n\nlemma minus_numeral_mod_numeral [simp]:\n  \"- numeral m mod numeral n = adjust_mod n (snd (divmod m n) :: int)\"\nproof (cases \"snd (divmod m n) = (0::int)\")\n  case True\n  then show ?thesis\n    by (simp add: mod_eq_0_iff_dvd divides_aux_def)\nnext\n  case False\n  then have \"int (snd (divmod m n)) = snd (divmod m n)\" if \"snd (divmod m n) \\<noteq> (0::int)\"\n    by (simp only: snd_divmod modulo_int_def) auto\n  then show ?thesis\n    by (simp add: divides_aux_def adjust_div_def)\n      (simp add: divides_aux_def modulo_int_def)\nqed\n\nlemma numeral_div_minus_numeral [simp]:\n  \"numeral m div - numeral n = - (adjust_div (divmod m n) :: int)\"\nproof -\n  have \"int (fst (divmod m n)) = fst (divmod m n)\"\n    by (simp only: fst_divmod divide_int_def) auto\n  then show ?thesis\n    by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def)\nqed\n\nlemma numeral_mod_minus_numeral [simp]:\n  \"numeral m mod - numeral n = - adjust_mod n (snd (divmod m n) :: int)\"\nproof (cases \"snd (divmod m n) = (0::int)\")\n  case True\n  then show ?thesis\n    by (simp add: mod_eq_0_iff_dvd divides_aux_def)\nnext\n  case False\n  then have \"int (snd (divmod m n)) = snd (divmod m n)\" if \"snd (divmod m n) \\<noteq> (0::int)\"\n    by (simp only: snd_divmod modulo_int_def) auto\n  then show ?thesis\n    by (simp add: divides_aux_def adjust_div_def)\n      (simp add: divides_aux_def modulo_int_def)\nqed\n\nlemma minus_one_div_numeral [simp]:\n  \"- 1 div numeral n = - (adjust_div (divmod Num.One n) :: int)\"\n  using minus_numeral_div_numeral [of Num.One n] by simp\n\nlemma minus_one_mod_numeral [simp]:\n  \"- 1 mod numeral n = adjust_mod n (snd (divmod Num.One n) :: int)\"\n  using minus_numeral_mod_numeral [of Num.One n] by simp\n\nlemma one_div_minus_numeral [simp]:\n  \"1 div - numeral n = - (adjust_div (divmod Num.One n) :: int)\"\n  using numeral_div_minus_numeral [of Num.One n] by simp\n\nlemma one_mod_minus_numeral [simp]:\n  \"1 mod - numeral n = - adjust_mod n (snd (divmod Num.One n) :: int)\"\n  using numeral_mod_minus_numeral [of Num.One n] by simp\n\n\n\nend\n\nlemma divmod_BitM_2_eq [simp]:\n  \\<open>divmod (Num.BitM m) (Num.Bit0 Num.One) = (numeral m - 1, (1 :: int))\\<close>\n  by (cases m) simp_all\n\n\nsubsubsection \\<open>Computation by simplification\\<close>\n\nlemma euclidean_size_nat_less_eq_iff:\n  \\<open>euclidean_size m \\<le> euclidean_size n \\<longleftrightarrow> m \\<le> n\\<close> for m n :: nat\n  by simp\n\nlemma euclidean_size_int_less_eq_iff:\n  \\<open>euclidean_size k \\<le> euclidean_size l \\<longleftrightarrow> \\<bar>k\\<bar> \\<le> \\<bar>l\\<bar>\\<close> for k l :: int\n  by auto\n\nsimproc_setup numeral_divmod\n  (\"0 div 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"0 mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"0 div 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"0 mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"0 div - 1 :: int\" | \"0 mod - 1 :: int\" |\n   \"0 div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"0 mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"0 div - numeral b :: int\" | \"0 mod - numeral b :: int\" |\n   \"1 div 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"1 mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"1 div 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"1 mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"1 div - 1 :: int\" | \"1 mod - 1 :: int\" |\n   \"1 div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"1 mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"1 div - numeral b :: int\" |\"1 mod - numeral b :: int\" |\n   \"- 1 div 0 :: int\" | \"- 1 mod 0 :: int\" | \"- 1 div 1 :: int\" | \"- 1 mod 1 :: int\" |\n   \"- 1 div - 1 :: int\" | \"- 1 mod - 1 :: int\" | \"- 1 div numeral b :: int\" | \"- 1 mod numeral b :: int\" |\n   \"- 1 div - numeral b :: int\" | \"- 1 mod - numeral b :: int\" |\n   \"numeral a div 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"numeral a mod 0 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"numeral a div 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"numeral a mod 1 :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"numeral a div - 1 :: int\" | \"numeral a mod - 1 :: int\" |\n   \"numeral a div numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" | \"numeral a mod numeral b :: 'a :: unique_euclidean_semiring_with_nat_division\" |\n   \"numeral a div - numeral b :: int\" | \"numeral a mod - numeral b :: int\" |\n   \"- numeral a div 0 :: int\" | \"- numeral a mod 0 :: int\" |\n   \"- numeral a div 1 :: int\" | \"- numeral a mod 1 :: int\" |\n   \"- numeral a div - 1 :: int\" | \"- numeral a mod - 1 :: int\" |\n   \"- numeral a div numeral b :: int\" | \"- numeral a mod numeral b :: int\" |\n   \"- numeral a div - numeral b :: int\" | \"- numeral a mod - numeral b :: int\") = \\<open>\n  let\n    val if_cong = the (Code.get_case_cong \\<^theory> \\<^const_name>\\<open>If\\<close>);\n    fun successful_rewrite ctxt ct =\n      let\n        val thm = Simplifier.rewrite ctxt ct\n      in if Thm.is_reflexive thm then NONE else SOME thm end;\n  in fn phi =>\n    let\n      val simps = Morphism.fact phi (@{thms div_0 mod_0 div_by_0 mod_by_0 div_by_1 mod_by_1\n        one_div_numeral one_mod_numeral minus_one_div_numeral minus_one_mod_numeral\n        one_div_minus_numeral one_mod_minus_numeral\n        numeral_div_numeral numeral_mod_numeral minus_numeral_div_numeral minus_numeral_mod_numeral\n        numeral_div_minus_numeral numeral_mod_minus_numeral\n        div_minus_minus mod_minus_minus Euclidean_Division.adjust_div_eq of_bool_eq one_neq_zero\n        numeral_neq_zero neg_equal_0_iff_equal arith_simps arith_special divmod_trivial\n        divmod_cancel divmod_steps divmod_step_def fst_conv snd_conv numeral_One\n        case_prod_beta rel_simps Euclidean_Division.adjust_mod_def div_minus1_right mod_minus1_right\n        minus_minus numeral_times_numeral mult_zero_right mult_1_right\n        euclidean_size_nat_less_eq_iff euclidean_size_int_less_eq_iff diff_nat_numeral nat_numeral}\n        @ [@{lemma \"0 = 0 \\<longleftrightarrow> True\" by simp}]);\n      fun prepare_simpset ctxt = HOL_ss |> Simplifier.simpset_map ctxt\n        (Simplifier.add_cong if_cong #> fold Simplifier.add_simp simps)\n    in fn ctxt => successful_rewrite (Simplifier.put_simpset (prepare_simpset ctxt) ctxt) end\n  end\n\\<close> \\<comment> \\<open>\n  There is space for improvement here: the calculation itself\n  could be carried out outside the logic, and a generic simproc\n  (simplifier setup) for generic calculation would be helpful.\n\\<close>\n\n\nsubsubsection \\<open>Code generation\\<close>\n\ncontext\nbegin\n\nqualified definition divmod_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<times> nat\"\n  where \"divmod_nat m n = (m div n, m mod n)\"\n\nqualified lemma divmod_nat_if [code]:\n  \"divmod_nat m n = (if n = 0 \\<or> m < n then (0, m) else\n    let (q, r) = divmod_nat (m - n) n in (Suc q, r))\"\n  by (simp add: divmod_nat_def prod_eq_iff case_prod_beta not_less le_div_geq le_mod_geq)\n\nqualified lemma [code]:\n  \"m div n = fst (divmod_nat m n)\"\n  \"m mod n = snd (divmod_nat m n)\"\n  by (simp_all add: divmod_nat_def)\n\nend\n\ncode_identifier\n  code_module Euclidean_Division \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nend\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Euclidean_Division.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.867035758084294, "lm_q1q2_score": 0.7705856517151336}}
{"text": "header \"Permutation Lemmas\"\n\ntheory PermutationLemmas\nimports \"~~/src/HOL/Library/Permutation\" \"~~/src/HOL/Library/Multiset\"\nbegin\n\n  -- \"following function is very close to that in multisets- now we can make the connection that x <~~> y iff the multiset of x is the same as that of y\"\n\nsubsection \"perm, count equivalence\"\n\nprimrec count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\nwhere\n  \"count x [] = 0\"\n| \"count x (y#ys) = (if x=y then 1 else 0) + count x ys\"\n\nlemma perm_count: \"A <~~> B \\<Longrightarrow> (\\<forall> x. count x A = count x B)\"\n  by(induct set: perm) auto\n\nlemma count_0: \"(\\<forall>x. count x B = 0) = (B = [])\"\n  by(induct B) auto\n\nlemma count_Suc: \"count a B = Suc m \\<Longrightarrow> a : set B\"\n  apply(induct B)\n   apply auto\n  apply(case_tac \"a = aa\")\n   apply auto\n  done\n\nlemma count_append: \"count a (xs@ys) = count a xs + count a ys\"\n  by(induct xs) auto\n\nlemma count_perm: \"!! B. (\\<forall> x. count x A = count x B) \\<Longrightarrow> A <~~> B\"\n  apply(induct A)\n  apply(simp add: count_0)\nproof -\n  fix a list B\n  assume a: \"\\<And>B. \\<forall>x. count x list = count x B \\<Longrightarrow> list <~~> B\"\n    and b: \"\\<forall>x. count x (a # list) = count x B\"\n  from b have \"a : set B\"\n    apply auto\n    apply (drule_tac x=a in spec, simp) apply(metis count_Suc) done\n  from split_list[OF this] obtain xs ys where B: \"B = xs@a#ys\" by blast\n  let ?B' = \"xs@ys\"\n  from b have \"\\<forall>x. count x list = count x ?B'\" by(simp add: count_append B)\n  from a[OF this] have c: \"list <~~> xs@ys\" .\n  hence \"a#list <~~> a#(xs@ys)\" by rule\n  also have \"a#(xs@ys) <~~> xs@a#ys\" by(rule perm_append_Cons)\n  also (perm.trans) note B[symmetric]\n  finally show \"a # list <~~> B\" .\nqed\n\nlemma perm_count_conv: \"A <~~> B = (\\<forall> x. count x A = count x B)\"\n  apply(blast intro!: perm_count count_perm) done \n\n\nsubsection \"Properties closed under Perm and Contr hold for x iff hold for remdups x\"\n\nlemma remdups_append: \"y : set ys --> remdups (ws@y#ys) = remdups (ws@ys)\"\n  apply (induct ws, simp)\n  apply (case_tac \"y = a\", simp, simp)\n  done\n\nlemma perm_contr': assumes perm[rule_format]: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and contr'[rule_format]: \"! x xs. P(x#x#xs) = P (x#xs)\" \n  shows \"! xs. length xs = n --> (P xs = P (remdups xs))\"\n  apply(induct n rule: nat_less_induct)\nproof (safe)\n  fix xs :: \"'a list\"\n  assume a[rule_format]: \"\\<forall>m<length xs. \\<forall>ys. length ys = m \\<longrightarrow> P ys = P (remdups ys)\"\n  show \"P xs = P (remdups xs)\"\n  proof (cases \"distinct xs\")\n    case True\n    thus ?thesis by(simp add:distinct_remdups_id)\n  next\n    case False\n    from not_distinct_decomp[OF this] obtain ws ys zs y where xs: \"xs = ws@[y]@ys@[y]@zs\" by force\n    have \"P xs = P (ws@[y]@ys@[y]@zs)\" by (simp add: xs)\n    also have \"... = P ([y,y]@ws@ys@zs)\" \n      apply(rule perm) apply(rule iffD2[OF perm_count_conv]) apply rule apply(simp add: count_append) done\n    also have \"... = P ([y]@ws@ys@zs)\" apply simp apply(rule contr') done\n    also have \"... = P (ws@ys@[y]@zs)\" \n      apply(rule perm) apply(rule iffD2[OF perm_count_conv]) apply rule apply(simp add: count_append) done\n    also have \"... = P (remdups (ws@ys@[y]@zs))\"\n      apply(rule a) by(auto simp: xs)\n    also have \"(remdups (ws@ys@[y]@zs)) = (remdups xs)\"\n      apply(simp add: xs remdups_append) done \n    finally show \"P xs = P (remdups xs)\" .\n  qed\nqed\n\nlemma perm_contr: assumes perm: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and contr': \"! x xs. P(x#x#xs) = P (x#xs)\" \n  shows \"(P xs = P (remdups xs))\"\n  apply(rule perm_contr'[OF perm contr', rule_format]) by force\n\n\nsubsection \"List properties closed under Perm, Weak and Contr are monotonic in the set of the list\"\n\ndefinition\n  rem :: \"'a => 'a list => 'a list\" where\n  \"rem x xs = filter (%y. y ~= x) xs\"\n\nlemma rem: \"x ~: set (rem x xs)\"\n  by(simp add: rem_def)\n\nlemma length_rem: \"length (rem x xs) <= length xs\"\n  by(simp add: rem_def)\n\nlemma rem_notin: \"x ~: set xs ==> rem x xs = xs\"\n  apply(simp add: rem_def)\n  apply(rule filter_True)\n  apply force\n  done\n\n\nlemma perm_weak_filter': assumes perm[rule_format]: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and weak[rule_format]: \"! x xs. P xs --> P (x#xs)\"\n  shows \"! ys. P (ys@filter Q xs) --> P (ys@xs)\"\n  apply (induct xs, simp, rule)\n  apply rule\n  apply simp\n  apply (case_tac \"Q a\", simp)\n   apply(drule_tac x=\"ys@[a]\" in spec) apply simp\n  apply simp\n  apply(drule_tac x=\"ys@[a]\" in spec) apply simp\n  apply(erule impE)\n   apply(subgoal_tac \"(ys @ a # filter Q xs) <~~> a#ys@filter Q xs\")\n    apply(simp add: perm)\n    apply(rule weak) apply simp\n   apply(rule perm_sym) apply(rule perm_append_Cons)\n  .\n\nlemma perm_weak_filter: assumes perm: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and weak: \"! x xs. P xs --> P (x#xs)\"\n  shows \"P (filter Q xs) ==> P xs\"\n  using perm_weak_filter'[OF perm weak, rule_format, of \"[]\", simplified]\n  by blast\n\n  -- \"right, now in a position to prove that in presence of perm, contr and weak, set x leq set y and x : ded implies y : ded\"\n\nlemma perm_weak_contr_mono: \n  assumes perm: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and contr: \"! x xs. P (x#x#xs) --> P (x#xs)\"\n  and weak: \"! x xs. P xs --> P (x#xs)\"\n  and xy: \"set x <= set y\"\n  and Px : \"P x\"\n  shows \"P y\"\nproof -\n  from contr weak have contr': \"! x xs. P(x#x#xs) = P (x#xs)\" by blast\n\n  def y' == \"filter (% z. z : set x) y\"\n  from xy have \"set x = set y'\" apply(simp add: y'_def) apply blast done\n  hence rxry': \"remdups x <~~> remdups y'\" by(simp add: perm_remdups_iff_eq_set)\n\n  from Px perm_contr[OF perm contr'] have Prx: \"P (remdups x)\" by simp\n  with rxry' have \"P (remdups y')\" by(simp add: perm)\n  \n  with perm_contr[OF perm contr'] have \"P y'\" by simp\n  thus \"P y\" \n    apply(simp add: y'_def)\n    apply(rule perm_weak_filter[OF perm weak]) .\nqed\n\n(* No, not used\nsubsection \"Following used in Soundness\"\n\nprimrec multiset_of_list :: \"'a list \\<Rightarrow> 'a multiset\"\nwhere\n  \"multiset_of_list [] = {#}\"\n| \"multiset_of_list (x#xs) = {#x#} + multiset_of_list xs\"\n\nlemma count_count[symmetric]: \"count x A = Multiset.count (multiset_of_list A) x\"\n  by (induct A) simp_all\n\nlemma perm_multiset: \"A <~~> B = (multiset_of_list A = multiset_of_list B)\"\n  apply(simp add: perm_count_conv)\n  apply(simp add: multiset_eq_iff)\n  apply(simp add: count_count)\n  done\n\nlemma set_of_multiset_of_list: \"set_of (multiset_of_list A) = set A\"\n  by (induct A) auto\n*)\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Completeness/PermutationLemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912913, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7704748136743678}}
{"text": "(* Authors: Tobias Nipkow and Thomas Sewell *)\n\nsection \"Sorting via Priority Queues Based on Braun Trees\"\n\ntheory Sorting_Braun\nimports Priority_Queue_Braun\nbegin\n\ntext \\<open>This theory is about sorting algorithms based on heaps.\nAlgorithm A can be found here\n\\<^url>\\<open>http://www.csse.canterbury.ac.nz/walter.guttmann/publications/0005.pdf\\<close> on p. 54.\n(published here \\<^url>\\<open>http://www.jucs.org/doi?doi=10.3217/jucs-009-02-0173\\<close>)\nNot really the classic heap sort but a mixture of heap sort and merge sort.\nThe algorithm (B) in Larry's book comes closer to the classic heap sort:\n\\<^url>\\<open>https://www.cl.cam.ac.uk/~lp15/MLbook/programs/sample7.sml\\<close>.\n\nBoth algorithms have two phases:\nbuild a heap from a list, then extract the elements of the heap into a sorted list.\n\\<close>\n\nabbreviation(input)\n  \"nlog2 n == nat(ceiling(log 2 n))\"\n\nsection \\<open>Phase 1: List to Tree\\<close>\n\ntext \\<open>Algorithm A does this naively, in $O(n lg n)$ fashion and generates a Braun tree:\\<close>\n\nfun heap_of_A :: \"('a::linorder) list \\<Rightarrow> 'a tree\" where\n\"heap_of_A [] = Leaf\" |\n\"heap_of_A (a#as) = insert a (heap_of_A as)\"\n\n(* just for testing\ndefinition\n  shuffle100 :: \"nat list\"\n  where\n  \"shuffle100 = [50 :: nat, 7, 77, 15, 42, 82, 87, 68, 69, 29, 43, 24, 84, 12, 35, 30, 95, 45, 14, 47, 54, 66, 96, 71, 98, 4, 22, 0, 92, 86, 34, 33, 57, 91, 20, 13, 64, 73, 70, 8, 85, 40, 16, 18, 81, 99, 63, 41, 56, 72, 79, 48, 78, 52, 25, 49, 65, 90, 26, 76, 3, 59, 74, 58, 46, 38, 61, 94, 75, 11, 88, 31, 53, 17, 44, 89, 39, 93, 62, 5, 1, 21, 6, 55, 83, 28, 37, 60, 19, 67, 23, 97, 51, 10, 27, 32, 2, 36, 9, 80]\"\n\nvalue \"heap_of_A shuffle100\"\n*)\n\nlemma heap_heap_of_A: \"heap (heap_of_A xs)\"\nby(induction xs)(simp_all add: heap_insert)\n\nlemma braun_heap_of_A: \"braun (heap_of_A xs)\"\nby(induction xs)(simp_all add: braun_insert)\n\nlemma mset_tree_heap_of_A: \"mset_tree (heap_of_A xs) = mset xs\"\nby(induction xs)(simp_all add: mset_insert)\n\ntext \\<open>Running time is n*log n, which we can approximate with height.\\<close>\n\nfun t_insert :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n\"t_insert a Leaf = 1\" |\n\"t_insert a (Node l x r) =\n (if a < x then 1 + t_insert x r else 1 + t_insert a r)\"\n\nfun t_heap_of_A :: \"('a::linorder) list \\<Rightarrow> nat\" where\n\"t_heap_of_A [] = 0\" |\n\"t_heap_of_A (a#as) = t_insert a (heap_of_A as) + t_heap_of_A as\"\n\nlemma t_insert_height:\n  \"t_insert x t \\<le> height t + 1\"\n  apply (induct t arbitrary: x; simp)\n  apply (simp only: max_Suc_Suc[symmetric] le_max_iff_disj, simp)\n  done\n\nlemma height_insert_ge:\n  \"height t \\<le> height (insert x t)\"\n  apply (induct t arbitrary: x; simp add: le_max_iff_disj)\n  apply (metis less_imp_le_nat less_le_trans not_le_imp_less)\n  done\n\nlemma t_heap_of_A_bound:\n  \"t_heap_of_A xs \\<le> length xs * (height (heap_of_A xs) + 1)\"\nproof (induct xs)\n  case (Cons x xs)\n\n  let ?lhs = \"t_insert x (heap_of_A xs) + t_heap_of_A xs\"\n\n  have \"?lhs \\<le> ?lhs\"\n    by simp\n  also note Cons\n  also note height_insert_ge[of \"heap_of_A xs\" x]\n  also note t_insert_height[of x \"heap_of_A xs\"]\n\n  finally show ?case\n    apply simp\n    apply (erule order_trans)\n    apply (simp add: height_insert_ge)\n    done\nqed simp_all\n\nlemma size_heap_of_A:\n  \"size (heap_of_A xs) = length xs\"\n  using arg_cong[OF mset_tree_heap_of_A, of size xs]\n  by simp\n\nlemma t_heap_of_A_log_bound:\n  \"t_heap_of_A xs \\<le> length xs * (nlog2 (length xs + 1) + 1)\"\n  using t_heap_of_A_bound[of xs]\n    balanced_if_braun[OF braun_heap_of_A, of xs]\n  by (simp add: height_balanced size1_size size_heap_of_A)\n\ntext \\<open>Algorithm B mimics heap sort more closely by building heaps bottom up in a balanced way:\\<close>\n\nfun heapify :: \"nat \\<Rightarrow> ('a::linorder) list \\<Rightarrow> 'a tree * 'a list\" where\n\"heapify 0 xs = (Leaf, xs)\" |\n\"heapify (Suc n) (x#xs) =\n\t (let (l, ys) = heapify (Suc n div 2) xs;\n\t\t    (r, zs) = heapify (n div 2) ys\n\t  in (sift_down l x r, zs))\"\n\ntext \\<open>The result should be a Braun tree:\\<close>\n\nlemma heapify_snd:\n  \"n \\<le> length xs \\<Longrightarrow> snd (heapify n xs) = drop n xs\"\n  apply (induct xs arbitrary: n rule: measure_induct[where f=length])\n  apply (case_tac n; simp)\n  apply (clarsimp simp: Suc_le_length_iff case_prod_beta)\n  apply (rule arg_cong[where f=\"\\<lambda>n. drop n xs\" for xs])\n  apply simp\n  done\n\nlemma heapify_snd_tup:\n  \"heapify n xs = (t, ys) \\<Longrightarrow> n \\<le> length xs \\<Longrightarrow> ys = drop n xs\"\n  by (drule heapify_snd, simp)\n\nlemma heapify_correct:\n  \"n \\<le> length xs \\<Longrightarrow> heapify n xs = (t, ys) \\<Longrightarrow>\n    size t = n \\<and> heap t \\<and> braun t \\<and> mset_tree t = mset (take n xs)\"\nproof (induct n xs arbitrary: t ys rule: heapify.induct)\n  case (2 n x xs)\n\n  note len = \"2.prems\"(1)\n\n  obtain t1 ys1 where h1: \"heapify (Suc n div 2) xs = (t1, ys1)\"\n    by (simp add: prod_eq_iff)\n  obtain t2 ys2 where h2: \"heapify (n div 2) ys1 = (t2, ys2)\"\n    by (simp add: prod_eq_iff)\n\n  from len have le1: \"Suc n div 2 \\<le> length xs\"\n    by simp\n  note ys1 = heapify_snd_tup[OF h1 le1]\n  from len have le2: \"n div 2 \\<le> length ys1\"\n    by (simp add: ys1)\n\n  note app_hyps = \"2.hyps\"(1)[OF le1 h1]\n    \"2.hyps\"(2)[OF refl h1[symmetric], simplified, OF le2 h2]\n\n  hence braun: \"braun (Node t1 x t2)\"\n    by (simp, linarith)\n\n  have eq:\n    \"n div 2 + Suc n div 2 = n\"\n    by simp\n\n  have msets:\n    \"mset (take (Suc n div 2) xs) + mset (take (n div 2) ys1) = mset (take n xs)\"\n    apply (subst append_take_drop_id[symmetric, where n=\"Suc n div 2\" and t=\"take n xs\"],\n        subst mset_append)\n    apply (simp add: take_drop min_absorb1 le1 eq ys1)\n    done\n\n  from \"2.prems\" app_hyps msets show ?case\n    apply (clarsimp simp: h1 h2 le2)\n    apply (clarsimp simp: size_sift_down[OF braun]\n                       braun_sift_down[OF braun]\n                       mset_sift_down[OF braun])\n    apply (simp add: heap_sift_down[OF braun])\n    done\nqed simp_all\n\nlemma braun_heapify:\n  \"n \\<le> length xs \\<Longrightarrow> braun (fst (heapify n xs))\"\n  by (cases \"heapify n xs\", drule(1) heapify_correct, simp)\n\nlemma heap_heapify:\n  \"n \\<le> length xs \\<Longrightarrow> heap (fst (heapify n xs))\"\n  by (cases \"heapify n xs\", drule(1) heapify_correct, simp)\n\nlemma mset_heapify:\n  \"n \\<le> length xs \\<Longrightarrow> mset_tree (fst (heapify n xs)) = mset (take n xs)\"\n  by (cases \"heapify n xs\", drule(1) heapify_correct, simp)\n\ntext \\<open>The running time of heapify is linear.\n  (similar to \\<^url>\\<open>https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap\\<close>)\n\nThis is an interesting result, so we embark on this exercise\nto prove it the hard way.\n\\<close>\n\ncontext includes pattern_aliases\nbegin\n\nfunction (sequential) t_sift_down :: \"'a::linorder tree \\<Rightarrow> 'a \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n\"t_sift_down Leaf a Leaf = 1\" |\n\"t_sift_down (Node Leaf x Leaf) a Leaf = 2\" |\n\"t_sift_down (Node l1 x1 r1 =: t1) a (Node l2 x2 r2 =: t2) =\n  (if a \\<le> x1 \\<and> a \\<le> x2\n   then 1\n   else if x1 \\<le> x2 then 1 + t_sift_down l1 a r1\n        else 1 + t_sift_down l2 a r2)\"\nby pat_completeness auto\n\ntermination\nby (relation \"measure (%(l,a,r). size l + size r)\") auto\n\nend\n\nfun t_heapify :: \"nat \\<Rightarrow> ('a::linorder) list \\<Rightarrow> nat\" where\n\"t_heapify 0 xs = 1\" |\n\"t_heapify (Suc n) (x#xs) =\n\t (let (l, ys) = heapify (Suc n div 2) xs;\n        t1 = t_heapify (Suc n div 2) xs;\n        (r, zs) = heapify (n div 2) ys;\n\t\t    t2 = t_heapify (n div 2) ys\n\t  in 1 + t1 + t2 + t_sift_down l x r)\"\n\nlemma t_sift_down_height:\n  \"braun (Node l x r) \\<Longrightarrow> t_sift_down l x r \\<le> height (Node l x r)\"\n  by (induct l x r rule: t_sift_down.induct; auto)\n\nlemma sift_down_height:\n  \"braun (Node l x r) \\<Longrightarrow> height (sift_down l x r) \\<le> height (Node l x r)\"\n  by (induct l x r rule: sift_down.induct; auto simp: Let_def)\n\nlemma braun_height_r_le:\n  \"braun (Node l x r) \\<Longrightarrow> height r \\<le> height l\"\n  by (rule balanced_optimal, auto intro: balanced_if_braun)\n\nlemma braun_height_l_le:\n  assumes b: \"braun (Node l x r)\"\n  shows \"height l \\<le> Suc (height r)\"\n  using b balanced_if_braun[OF b] min_height_le_height[of r]\n  by (simp add: balanced_def)\n\nlemma braun_height_node_eq:\n  assumes b: \"braun (Node l x r)\"\n  shows \"height (Node l x r) = Suc (height l)\"\n  using b braun_height_r_le[OF b]\n  by (auto simp add: max_def)\n\nlemma t_heapify_induct:\n  \"i \\<le> length xs \\<Longrightarrow> t_heapify i xs + height (fst (heapify i xs)) \\<le> 5 * i + 1\"\nproof (induct i xs rule: t_heapify.induct)\n  case (1 vs)\n  thus ?case\n    by simp\nnext\n  case (2 i x xs)\n\n  obtain l ys where h1: \"heapify (Suc i div 2) xs = (l, ys)\"\n    by (simp add: prod_eq_iff)\n  note hyps1 = \"2.hyps\"[OF h1[symmetric] refl, simplified]\n  obtain r zs where h2: \"heapify (i div 2) ys = (r, zs)\"\n    by (simp add: prod_eq_iff)\n\n  from \"2.prems\" heapify_snd_tup[OF h1]\n  have le1: \"Suc i div 2 \\<le> length xs\"\n    and le2: \"i div 2 \\<le> length xs\"\n    and le4: \"i div 2 \\<le> length ys\"\n    by simp_all\n\n  note hyps2 = hyps1(1)[OF le1] hyps1(2)[OF refl h2[symmetric] refl le4]\n\n  note prem = add_le_mono[OF add_le_mono[OF hyps2] order_refl[where x=3]]\n\n  from heapify_correct[OF le1 h1] heapify_correct[OF le4 h2]\n  have braun: \"braun \\<langle>l, x, r\\<rangle>\"\n    by auto\n\n  have t_sift_l:\n    \"t_sift_down l x r \\<le> height l + 1\"\n    using t_sift_down_height[OF braun] braun_height_r_le[OF braun]\n    by simp\n\n  from t_sift_down_height[OF braun]\n  have height_sift_r:\n    \"height (sift_down l x r) \\<le> height r + 2\"\n    using sift_down_height[OF braun] braun_height_l_le[OF braun]\n    by simp\n\n  from h1 h2 t_sift_l height_sift_r \"2.prems\"\n  show ?case\n    apply simp\n    apply (rule order_trans, rule order_trans[rotated], rule prem)\n     apply simp_all\n    apply (simp only: mult_le_cancel1 add_mult_distrib2[symmetric])\n    apply simp\n    done\n\nqed simp_all\n\nlemma t_heapify_bound:\n  \"i \\<le> length xs \\<Longrightarrow> t_heapify i xs \\<le> 5 * i + 1\"\n  using t_heapify_induct[of i xs]\n  by simp\n\nsection \\<open>Phase 2: Heap to List\\<close>\n\ntext\\<open>Algorithm A extracts (\\<open>list_of_A\\<close>) the list by removing the root and merging the children:\\<close>\n\n\n(* For termination of \\<open>merge\\<close> only: *)\nlemma size_prod_measure[measure_function]:\n  \"is_measure f \\<Longrightarrow> is_measure g \\<Longrightarrow> is_measure (size_prod f g)\"\nby (rule is_measure_trivial)\n\nfun merge :: \"('a::linorder) tree \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"merge Leaf t2 = t2\" |\n\"merge t1 Leaf = t1\" |\n\"merge (Node l1 a1 r1) (Node l2 a2 r2) =\n   (if a1 \\<le> a2 then Node (merge l1 r1) a1 (Node l2 a2 r2)\n    else Node (Node l1 a1 r1) a2 (merge l2 r2))\"\n\n(* Merging does not preserve braun: *)\nvalue \"merge \\<langle>\\<langle>\\<rangle>, 0::int, \\<langle>\\<rangle>\\<rangle> \\<langle>\\<langle>\\<rangle>, 0, \\<langle>\\<rangle>\\<rangle> = \\<langle>\\<langle>\\<rangle>, 0, \\<langle>\\<langle>\\<rangle>, 0, \\<langle>\\<rangle>\\<rangle>\\<rangle>\"\n\nlemma merge_size[termination_simp]:\n  \"size (merge l r) = size l + size r\"\n  by (induct rule: merge.induct; simp)\n\nfun list_of_A :: \"('a::linorder) tree \\<Rightarrow> 'a list\" where\n\"list_of_A Leaf = []\" |\n\"list_of_A (Node l a r) = a # list_of_A (merge l r)\"\n\nvalue \"list_of_A (heap_of_A shuffle100)\"\n\nlemma set_tree_merge[simp]:\n  \"set_tree (merge l r) = set_tree l \\<union> set_tree r\"\n  by (induct l r rule: merge.induct; simp)\n\nlemma mset_tree_merge[simp]:\n  \"mset_tree (merge l r) = mset_tree l + mset_tree r\"\n  by (induct l r rule: merge.induct; simp)\n\nlemma merge_heap:\n  \"heap l \\<Longrightarrow> heap r \\<Longrightarrow> heap (merge l r)\"\n  by (induct l r rule: merge.induct; auto simp: ball_Un)\n\nlemma set_list_of_A[simp]:\n  \"set (list_of_A t) = set_tree t\"\n  by (induct t rule: list_of_A.induct; simp)\n\nlemma mset_list_of_A[simp]:\n  \"mset (list_of_A t) = mset_tree t\"\n  by (induct t rule: list_of_A.induct; simp)\n\nlemma sorted_list_of_A:\n  \"heap t \\<Longrightarrow> sorted (list_of_A t)\"\n  by (induct t rule: list_of_A.induct; simp add: merge_heap)\n\nlemma sortedA: \"sorted (list_of_A (heap_of_A xs))\"\nby (simp add: heap_heap_of_A sorted_list_of_A)\n\nlemma msetA: \"mset (list_of_A (heap_of_A xs)) = mset xs\"\n  by (simp add: mset_tree_heap_of_A)\n\ntext\\<open>Does \\<open>list_of_A\\<close> take time $O(n lg n)$? Although \\<open>merge\\<close> does not preserve \\<open>braun\\<close>,\nit cannot increase the height of the heap.\\<close>\n\nlemma merge_height:\n  \"height (merge l r) \\<le>  Suc (max (height l) (height r))\"\n  by (induct rule: merge.induct, auto)\n\ncorollary merge_height_display:\n  \"height (merge l r) \\<le> height (Node l x r)\"\n  using merge_height by simp\n\nfun t_merge :: \"('a::linorder) tree \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n\"t_merge Leaf t2 = 0\" |\n\"t_merge t1 Leaf = 0\" |\n\"t_merge (Node l1 a1 r1) (Node l2 a2 r2) =\n   (if a1 \\<le> a2 then 1 + t_merge l1 r1\n    else 1 + t_merge l2 r2)\"\n\nfun t_list_of_A :: \"('a::linorder) tree \\<Rightarrow> nat\" where\n\"t_list_of_A Leaf = 0\" |\n\"t_list_of_A (Node l a r) = 1 + t_merge l r + t_list_of_A (merge l r)\"\n\nlemma t_merge_height:\n  \"t_merge l r \\<le> max (height l) (height r)\"\n  by (induct rule: t_merge.induct, auto)\n\nlemma t_list_of_A_induct:\n  \"height t \\<le> n \\<Longrightarrow> t_list_of_A t \\<le> 2 * n * size t\"\n  apply (induct rule: t_list_of_A.induct)\n   apply simp\n  apply simp\n  apply (drule meta_mp)\n   apply (rule order_trans, rule merge_height)\n   apply simp\n  apply (simp add: merge_size)\n  apply (cut_tac l=l and r=r in t_merge_height)\n  apply linarith\n  done\n\nlemma t_list_of_A_bound:\n  \"t_list_of_A t \\<le> 2 * height t * size t\"\n  by (rule t_list_of_A_induct, simp)\n\nlemma t_list_of_A_log_bound:\n  \"braun t \\<Longrightarrow> t_list_of_A t \\<le> 2 * nlog2 (size t + 1) * size t\"\n  using t_list_of_A_bound[of t]\n  by (simp add: height_balanced balanced_if_braun size1_size)\n\nvalue \"t_list_of_A (heap_of_A shuffle100)\"\n\ntheorem t_sortA:\n  \"t_heap_of_A xs + t_list_of_A (heap_of_A xs) \\<le> 3 * length xs * (nlog2 (length xs + 1) + 1)\"\n  (is \"?lhs \\<le> _\")\nproof -\n  have \"?lhs \\<le> ?lhs\" by simp\n  also note t_heap_of_A_log_bound[of xs]\n  also note t_list_of_A_log_bound[of \"heap_of_A xs\", OF braun_heap_of_A]\n  finally show ?thesis\n    by (simp add: size_heap_of_A)\nqed\n\ntext \\<open>Running time of algorithm B:\\<close>\n\n(* Unfortunately this can only be proven to terminate conditionally.\n   To make it unconditional would require a total specification of\n   sift_down, which would be complex and differ substantially from\n   Paulson's presentation.  *)\nfunction list_of_B :: \"('a::linorder) tree \\<Rightarrow> 'a list\" where\n\"list_of_B Leaf = []\" |\n\"list_of_B (Node l a r) = a # list_of_B (del_min (Node l a r))\"\n  by pat_completeness auto\n\nlemma list_of_B_braun_ptermination:\n  \"braun t \\<Longrightarrow> list_of_B_dom t\"\n  apply (induct t rule: measure_induct[where f=size])\n  apply (rule accpI, erule list_of_B_rel.cases)\n  apply (clarsimp simp: size_del_min braun_del_min)\n  done\n\nlemmas list_of_B_braun_simps\n    = list_of_B.psimps[OF list_of_B_braun_ptermination]\n\nlemma mset_list_of_B:\n  \"braun t \\<Longrightarrow> mset (list_of_B t) = mset_tree t\"\n  apply (induct t rule: measure_induct[where f=size])\n  apply (case_tac x; simp add: list_of_B_braun_simps)\n  apply (simp add: size_del_min braun_del_min mset_del_min)\n  done\n\nlemma set_list_of_B:\n  \"braun t \\<Longrightarrow> set (list_of_B t) = set_tree t\"\n  by (simp only: set_mset_mset[symmetric] mset_list_of_B, simp)\n\nlemma sorted_list_of_B:\n  \"braun t \\<Longrightarrow> heap t \\<Longrightarrow> sorted (list_of_B t)\"\n  apply (induct t rule: measure_induct[where f=size])\n  apply (case_tac x; simp add: list_of_B_braun_simps)\n  apply (clarsimp simp: set_list_of_B braun_del_min size_del_min heap_del_min)\n  apply (simp add: set_mset_tree[symmetric] mset_del_min del: set_mset_tree)\n  done\n\ndefinition\n  \"heap_of_B xs = fst (heapify (length xs) xs)\"\n\nlemma sortedB: \"sorted (list_of_B (heap_of_B xs))\"\nby (simp add: heap_of_B_def braun_heapify heap_heapify sorted_list_of_B)\n\nlemma msetB: \"mset (list_of_B (heap_of_B xs)) = mset xs\"\nby (simp add: heap_of_B_def braun_heapify mset_heapify mset_list_of_B)\n\nfun t_del_left :: \"'a tree \\<Rightarrow> nat\" where\n\"t_del_left (Node Leaf x r) = 1\" |\n\"t_del_left (Node l x r) = (let (y,l') = del_left l in 2 + t_del_left l)\"\n\nfun t_del_min :: \"'a::linorder tree \\<Rightarrow> nat\" where\n\"t_del_min Leaf = 0\" |\n\"t_del_min (Node Leaf x r) = 0\" |\n\"t_del_min (Node l x r) = (let (y,l') = del_left l in t_del_left l + t_sift_down r y l')\"\n\nfunction t_list_of_B :: \"('a::linorder) tree \\<Rightarrow> nat\" where\n\"t_list_of_B Leaf = 0\" |\n\"t_list_of_B (Node l a r) = 1 + t_del_min (Node l a r) + t_list_of_B (del_min (Node l a r))\"\n  by pat_completeness auto\n\nlemma t_del_left_bound:\n  \"t \\<noteq> Leaf \\<Longrightarrow> t_del_left t \\<le> 2 * height t\"\n  apply (induct rule: t_del_left.induct; clarsimp)\n  apply (atomize(full); clarsimp simp: prod_eq_iff)\n  apply (simp add: nat_mult_max_right le_max_iff_disj)\n  done\n\nlemma del_left_height:\n  \"del_left t = (v, t') \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> height t' \\<le> height t\"\n  apply (induct t arbitrary: v t' rule: del_left.induct; simp)\n  apply (atomize(full), clarsimp split: prod.splits)\n  apply simp\n  done\n\nlemma t_del_min_bound:\n  \"braun t \\<Longrightarrow> t_del_min t \\<le> 3 * height t\"\n  apply (cases t rule: t_del_min.cases; simp)\n  apply (clarsimp split: prod.split)\n  apply (frule del_left_braun, simp+)\n  apply (frule del_left_size, simp+)\n  apply (frule del_left_height, simp)\n  apply (rule order_trans)\n   apply ((rule add_le_mono t_del_left_bound t_sift_down_height | simp)+)[1]\n   apply auto[1]\n  apply (simp add: max_def)\n  done\n\nlemma t_list_of_B_braun_ptermination:\n  \"braun t \\<Longrightarrow> t_list_of_B_dom t\"\n  apply (induct t rule: measure_induct[where f=size])\n  apply (rule accpI, erule t_list_of_B_rel.cases)\n  apply (clarsimp simp: size_del_min braun_del_min)\n  done\n\nlemmas t_list_of_B_braun_simps\n    = t_list_of_B.psimps[OF t_list_of_B_braun_ptermination]\n\nlemma del_min_height:\n  \"braun t \\<Longrightarrow> height (del_min t) \\<le> height t\"\n  apply (cases t rule: del_min.cases; simp)\n  apply (clarsimp split: prod.split)\n  apply (frule del_left_braun, simp+)\n  apply (frule del_left_size, simp+)\n  apply (drule del_left_height)\n   apply simp\n  apply (rule order_trans, rule sift_down_height, auto)\n  done\n\nlemma t_list_of_B_induct:\n  \"braun t \\<Longrightarrow> height t \\<le> n \\<Longrightarrow> t_list_of_B t \\<le> 3 * (n + 1) * size t\"\n  apply (induct t rule: measure_induct[where f=size])\n  apply (drule_tac x=\"del_min x\" in spec)\n  apply (frule del_min_height)\n  apply (case_tac x; simp add: t_list_of_B_braun_simps)\n  apply (rename_tac l x' r)\n  apply (clarsimp simp: braun_del_min size_del_min)\n  apply (rule order_trans)\n   apply ((rule add_le_mono t_del_min_bound | assumption | simp)+)[1]\n  apply simp\n  done\n\nlemma t_list_of_B_bound:\n  \"braun t \\<Longrightarrow> t_list_of_B t \\<le> 3 * (height t + 1) * size t\"\n  by (erule t_list_of_B_induct, simp)\n\n\n\ndefinition\n  \"t_heap_of_B xs = length xs + t_heapify (length xs) xs\"\n\nlemma t_heap_of_B_bound:\n  \"t_heap_of_B xs \\<le> 6 * length xs + 1\"\n  by (simp add: t_heap_of_B_def order_trans[OF t_heapify_bound])\n\nlemmas size_heapify = arg_cong[OF mset_heapify, where f=size, simplified]\n\ntheorem t_sortB:\n  \"t_heap_of_B xs + t_list_of_B (heap_of_B xs)\n    \\<le> 3 * length xs * (nlog2 (length xs + 1) + 3) + 1\"\n  (is \"?lhs \\<le> _\")\nproof -\n  have \"?lhs \\<le> ?lhs\" by simp\n  also note t_heap_of_B_bound[of xs]\n  also note t_list_of_B_log_bound[of \"heap_of_B xs\"]\n  finally show ?thesis\n    apply (simp add: size_heapify braun_heapify heap_of_B_def)\n    apply (simp add: field_simps)\n    done\nqed\n\n(* One suspects that algorithm A is actually faster, despite being\nalgorithmically slower on the construction of the heap. The operation\nmerge needs to allocate one constructor per level of the heap,\nas opposed to del_min, which needs three, so the extraction is probably\nmuch faster. Not sure how to validate that.\n\nvalue \"t_list_of_B (heap_of\n  [50 :: nat, 7, 77, 15, 42, 82, 87, 68, 69, 29, 43, 24, 84, 12, 35, 30, 95, 45, 14, 47, 54, 66, 96, 71, 98, 4, 22, 0, 92, 86, 34, 33, 57, 91, 20, 13, 64, 73, 70, 8, 85, 40, 16, 18, 81, 99, 63, 41, 56, 72, 79, 48, 78, 52, 25, 49, 65, 90, 26, 76, 3, 59, 74, 58, 46, 38, 61, 94, 75, 11, 88, 31, 53, 17, 44, 89, 39, 93, 62, 5, 1, 21, 6, 55, 83, 28, 37, 60, 19, 67, 23, 97, 51, 10, 27, 32, 2, 36, 9, 80]\n)\"\n *)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Priority_Queue_Braun/Sorting_Braun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637469145054, "lm_q2_score": 0.8962513682840824, "lm_q1q2_score": 0.7704748094363466}}
{"text": "section {* Types of Cardinality 2 or Greater *}\n\ntheory Two\nimports HOL.Real\nbegin\n\ntext {* The two class states that a type's carrier is either infinite, or else it has a finite \n  cardinality of at least 2. It is needed when we depend on having at least two distinguishable\n  elements. *}\n  \nclass two =\n  assumes card_two: \"infinite (UNIV :: 'a set) \\<or> card (UNIV :: 'a set) \\<ge> 2\"\nbegin\nlemma two_diff: \"\\<exists> x y :: 'a. x \\<noteq> y\"\nproof -\n  obtain A where \"finite A\" \"card A = 2\" \"A \\<subseteq> (UNIV :: 'a set)\"\n  proof (cases \"infinite (UNIV :: 'a set)\")\n    case True\n    with infinite_arbitrarily_large[of \"UNIV :: 'a set\" 2] that\n    show ?thesis by auto\n  next\n    case False\n    with card_two that\n    show ?thesis\n      by (metis UNIV_bool card_UNIV_bool card_image card_le_inj finite.intros(1) finite_insert finite_subset)\n  qed\n  thus ?thesis\n    by (metis (full_types) One_nat_def Suc_1 UNIV_eq_I card.empty card.insert finite.intros(1) insertCI nat.inject nat.simps(3))\nqed\nend\n\ninstance bool :: two\n  by (intro_classes, auto)\n\ninstance nat :: two\n  by (intro_classes, auto)\n\ninstance int :: two\n  by (intro_classes, auto simp add: infinite_UNIV_int)\n\ninstance rat :: two\n  by (intro_classes, auto simp add: infinite_UNIV_char_0)\n\ninstance real :: two\n  by (intro_classes, auto simp add: infinite_UNIV_char_0)\n\ninstance list :: (type) two\n  by (intro_classes, auto simp add: infinite_UNIV_listI)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Optics/Two.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.7703040243761569}}
{"text": "(*  Title:      HOL/Examples/Ackermann.thy\n    Author:     Larry Paulson\n*)\n\nsection \\<open>A Tail-Recursive, Stack-Based Ackermann's Function\\<close>\n\ntheory Ackermann imports Main\n\nbegin\n\ntext\\<open>This theory investigates a stack-based implementation of Ackermann's function.\nLet's recall the traditional definition,\nas modified by R{\\'o}zsa P\\'eter and Raphael Robinson.\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n             = Suc n\"\n| \"ack (Suc m) 0       = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\ntext\\<open>Here is the stack-based version, which uses lists.\\<close>\n\nfunction (domintros) ackloop :: \"nat list \\<Rightarrow> nat\" where\n  \"ackloop (n # 0 # l)         = ackloop (Suc n # l)\"\n| \"ackloop (0 # Suc m # l)     = ackloop (1 # m # l)\"\n| \"ackloop (Suc n # Suc m # l) = ackloop (n # Suc m # m # l)\"\n| \"ackloop [m] = m\"\n| \"ackloop [] =  0\"\n  by pat_completeness auto\n\ntext\\<open>\nThe key task is to prove termination. In the first recursive call, the head of the list gets bigger\nwhile the list gets shorter, suggesting that the length of the list should be the primary\ntermination criterion. But in the third recursive call, the list gets longer. The idea of trying\na multiset-based termination argument is frustrated by the second recursive call when m = 0:\nthe list elements are simply permuted.\n\nFortunately, the function definition package allows us to define a function and only later identify its domain of termination.\nInstead, it makes all the recursion equations conditional on satisfying\nthe function's domain predicate. Here we shall eventually be able\nto show that the predicate is always satisfied.\\<close>\n\ntext\\<open>@{thm [display] ackloop.domintros[no_vars]}\\<close>\ndeclare ackloop.domintros [simp]\n\ntext \\<open>Termination is trivial if the length of the list is less then two.\nThe following lemma is the key to proving termination for longer lists.\\<close>\nlemma \"\\<And>n l. ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\nproof (induction m)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (Suc m)\n  note IH = Suc\n  have \"\\<And>l. ackloop_dom (ack (Suc m) n # l) \\<Longrightarrow> ackloop_dom (n # Suc m # l)\"\n  proof (induction n)\n    case 0\n    then show ?case\n      by (simp add: IH)\n  next\n    case (Suc n)\n    then show ?case\n      by (auto simp: IH)\n  qed\n  then show ?case\n    using Suc.prems by blast\nqed\n\ntext \\<open>The proof above (which actually is unused) can be expressed concisely as follows.\\<close>\nlemma ackloop_dom_longer:\n  \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\nlemma \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\ntext\\<open>This function codifies what @{term ackloop} is designed to do.\nProving the two functions equivalent also shows that @{term ackloop} can be used\nto compute Ackermann's function.\\<close>\nfun acklist :: \"nat list \\<Rightarrow> nat\" where\n  \"acklist (n#m#l) = acklist (ack m n # l)\"\n| \"acklist [m] = m\"\n| \"acklist [] =  0\"\n\ntext\\<open>The induction rule for @{term acklist} is @{thm [display] acklist.induct[no_vars]}.\\<close>\n\nlemma ackloop_dom: \"ackloop_dom l\"\n  by (induction l rule: acklist.induct) (auto simp: ackloop_dom_longer)\n\ntermination ackloop\n  by (simp add: ackloop_dom)\n\ntext\\<open>This result is trivial even by inspection of the function definitions\n(which faithfully follow the definition of Ackermann's function).\nAll that we needed was termination.\\<close>\nlemma ackloop_acklist: \"ackloop l = acklist l\"\n  by (induction l rule: ackloop.induct) auto\n\ntheorem ack: \"ack m n = ackloop [n,m]\"\n  by (simp add: ackloop_acklist)\n\nend\n", "meta": {"author": "object-logics", "repo": "isabelle_para", "sha": "fd37dea4fd86b40bde51d9ca7adeba3e009d87c4", "save_path": "github-repos/isabelle/object-logics-isabelle_para", "path": "github-repos/isabelle/object-logics-isabelle_para/isabelle_para-fd37dea4fd86b40bde51d9ca7adeba3e009d87c4/src/HOL/Examples/Ackermann.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220291, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7703040143021619}}
{"text": "section \\<open>Powerset\\<close>\ntheory Powerset\n  imports\n    Main\n    n_Sequences\n    Common_Lemmas\n    Filter_Bool_List\nbegin\n\nsubsection\"Definition\"\n\ntext \"Pow A\"\ntext \"Cardinality: \\<open>2 ^ card A\\<close>\"\ntext \"Example: \\<open>Pow {0,1} = {{}, {1}, {0}, {0, 1}}\\<close>\"\n\nsubsection\"Algorithm\"\n\nfun all_bool_lists :: \"nat \\<Rightarrow> bool list list\" where\n  \"all_bool_lists 0 = [[]]\"\n| \"all_bool_lists (Suc x) = concat [[False#xs, True#xs] . xs \\<leftarrow> all_bool_lists x]\"\n\nfun powerset_enum where\n  \"powerset_enum xs = [(filter_bool_list x xs) . x \\<leftarrow> all_bool_lists (length xs)]\"\n\nsubsection\"Verification\"\n\ntext \"First we show the relevant theorems for \\<open>all_bool_lists\\<close>, then we'll transfer the\nresults to the enumeration algorithm for powersets.\"\n\nlemma distinct_concat_aux: \"distinct xs \\<Longrightarrow> distinct (concat (map (\\<lambda>xs. [False # xs, True # xs]) xs))\"\n  by (induct xs) auto\n\nlemma distinct_all_bool_lists : \"distinct (all_bool_lists x)\"\n  by (induct x) (auto simp add: distinct_concat_aux)\n\nlemma all_bool_lists_correct: \"set (all_bool_lists x) = {xs. length xs = x}\"\nproof(standard)\n  show \"set (all_bool_lists x) \\<subseteq> {xs. length xs = x}\"\n    by (induct x) auto\nnext\n  show \"{xs. length xs = x} \\<subseteq> set (all_bool_lists x)\"\n  proof(induct x)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc x)\n    have \"length ys = Suc x \\<Longrightarrow> \\<exists>xs. ys = False # xs \\<or> ys = True # xs\" for ys\n      by (metis (full_types) Suc_length_conv)\n    then show ?case using Suc\n      by fastforce\n  qed\nqed\n\nsubsubsection\"Correctness\"\n\ntheorem powerset_enum_correct: \"set (map set (powerset_enum xs)) = Pow (set xs)\"\nproof(standard)\n  show \"set (map set (powerset_enum xs)) \\<subseteq> Pow (set xs)\"\n    using filter_bool_list_not_elem by fastforce\nnext\n  have \"\\<And>x. x \\<subseteq> set xs \\<Longrightarrow> x \\<in> (\\<lambda>x. set (filter_bool_list x xs)) ` {zs. length zs = length xs}\"\n    unfolding image_def using filter_bool_list_exist_length image_def by auto\n  then show \"Pow (set xs) \\<subseteq> set (map set (powerset_enum xs))\"\n    using all_bool_lists_correct by auto\nqed\n  \nsubsubsection\"Distinctness\"\n\ntheorem powerset_enum_distinct_elem: \"distinct xs \\<Longrightarrow> ys \\<in> set (powerset_enum xs) \\<Longrightarrow> distinct ys\"\n  using filter_bool_list_distinct by auto \n\ntheorem powerset_enum_distinct: \"distinct xs \\<Longrightarrow> distinct (powerset_enum xs)\"\nproof -\n  assume dis: \"distinct xs\"\n  then have \" distinct (map (\\<lambda>x. filter_bool_list x xs) (all_bool_lists (length xs)))\"\n    using distinct_map filter_bool_list_inj distinct_all_bool_lists\n    by (metis all_bool_lists_correct)\n  then show ?thesis\n    using dis by simp\nqed\n\nsubsubsection\"Cardinality\"\n\ntext \"Cardinality for powersets is already shown in @{thm [source] card_Pow}.\"\n\nsubsection\"Alternative algorithm with \\<open>n_sequence_enum\\<close>\"\n\nfun all_bool_lists2 :: \"nat \\<Rightarrow> bool list list\" where\n  \"all_bool_lists2 n = n_sequence_enum [True, False] n\"\n\nlemma all_bool_lists2_distinct: \"distinct (all_bool_lists2 n)\"\n  by (auto simp add: n_sequence_enum_distinct)\n\nlemma all_bool_lists2_correct: \"set (all_bool_lists n) = set (all_bool_lists2 n)\"\n  by (auto simp: all_bool_lists_correct n_sequence_enum_correct n_sequences_def)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Combinatorial_Enumeration_Algorithms/Powerset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.8902942348544447, "lm_q1q2_score": 0.7703040063875068}}
{"text": "theory MyList\nimports Main\nbegin\n\nfun itrev :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"itrev [] ys = ys\" |\n\"itrev (x#xs) ys = itrev xs (x#ys)\"\n\n\n\nlemma \"itrev xs [] = rev xs\"\napply(induction xs)\napply(auto)\ndone\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc (add m n)\"\n\n\nfun iadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"iadd 0 n = n\" |\n\"iadd (Suc m) n = iadd m (Suc n)\"\n\nvalue \"iadd 3 2\"\nvalue \"iadd 2 0\"\nvalue \"iadd 0 0\"\n\nlemma [simp] : \"add m (Suc n) = Suc (add m n)\"\napply(induction m)\napply(auto)\ndone\n\nlemma \"iadd m n = add m n\"\napply(induction m arbitrary: n)\napply(auto)\ndone\n\nend", "meta": {"author": "masateruk", "repo": "isabelle_concrete_semantics", "sha": "fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab", "save_path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics", "path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics/isabelle_concrete_semantics-fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab/chapter2/MyList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7701870904233599}}
{"text": "theory tangle_relation\nimports Datatype Main\nbegin\n\n\n\nlemma symmetry1: assumes \"symp R\" \nshows \"\\<forall>x y. (x, y) \\<in> {(x, y). R x y}\\<^sup>* \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\\<^sup>*\" \nproof-\nhave  \"R x y \\<longrightarrow>  R y x\" by (metis assms sympD)\nthen have \" (x, y) \\<in> {(x, y). R x y} \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\" by auto\nthen have 2:\"\\<forall> x y. (x, y) \\<in> {(x, y). R x y} \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\"\n by (metis (full_types) assms mem_Collect_eq split_conv sympE)\nthen have \"sym {(x, y). R x y}\" unfolding sym_def by auto\nthen have 3: \"sym (rtrancl {(x, y). R x y})\" using sym_rtrancl by auto\nthen show ?thesis by (metis symE)\nqed\n\nlemma symmetry2: assumes \"\\<forall>x y. (x, y) \\<in> {(x, y). R x y}\\<^sup>* \\<longrightarrow> (y, x) \\<in> {(x, y). R x y}\\<^sup>* \"\nshows \"symp R^**\" \nunfolding symp_def Enum.rtranclp_rtrancl_eq assms by (metis assms)\n\nlemma symmetry3: assumes \"symp R\" shows \"symp R^**\" using assms symmetry1 symmetry2 by metis\n\nlemma symm_trans: assumes \"symp R\" shows \"symp R^++\" by (metis assms rtranclpD symmetry3 symp_def tranclp_into_rtranclp)\n\nend\n", "meta": {"author": "prathamesh-t", "repo": "Tangle-Isabelle", "sha": "372f6b5ea473340405f0bb3f5e5502725b04e505", "save_path": "github-repos/isabelle/prathamesh-t-Tangle-Isabelle", "path": "github-repos/isabelle/prathamesh-t-Tangle-Isabelle/Tangle-Isabelle-372f6b5ea473340405f0bb3f5e5502725b04e505/tangle_relation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7701870789794887}}
{"text": "section \\<open>Peano's axioms for Natural Numbers\\<close>\n\ntheory Peano_Axioms\n  imports MainRLT\nbegin\n\nlocale peano =  \\<comment> \\<open>or: \\<^theory_text>\\<open>class\\<close>\\<close>\n  fixes zero :: 'a\n  fixes succ :: \"'a \\<Rightarrow> 'a\"\n  assumes succ_neq_zero [simp]: \"succ m \\<noteq> zero\"\n  assumes succ_inject [simp]: \"succ m = succ n \\<longleftrightarrow> m = n\"\n  assumes induct [case_names zero succ, induct type: 'a]:\n    \"P zero \\<Longrightarrow> (\\<And>n. P n \\<Longrightarrow> P (succ n)) \\<Longrightarrow> P n\"\nbegin\n\nlemma zero_neq_succ [simp]: \"zero \\<noteq> succ m\"\n  by (rule succ_neq_zero [symmetric])\n\n\ntext \\<open>\\<^medskip> Primitive recursion as a (functional) relation -- polymorphic!\\<close>\n\ninductive Rec :: \"'b \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  for e :: 'b and r :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b\"\nwhere\n  Rec_zero: \"Rec e r zero e\"\n| Rec_succ: \"Rec e r m n \\<Longrightarrow> Rec e r (succ m) (r m n)\"\n\nlemma Rec_functional: \"\\<exists>!y::'b. Rec e r x y\" for x :: 'a\nproof -\n  let ?R = \"Rec e r\"\n  show ?thesis\n  proof (induct x)\n    case zero\n    show \"\\<exists>!y. ?R zero y\"\n    proof\n      show \"?R zero e\" ..\n      show \"y = e\" if \"?R zero y\" for y\n        using that by cases simp_all\n    qed\n  next\n    case (succ m)\n    from \\<open>\\<exists>!y. ?R m y\\<close>\n    obtain y where y: \"?R m y\" and yy': \"\\<And>y'. ?R m y' \\<Longrightarrow> y = y'\"\n      by blast\n    show \"\\<exists>!z. ?R (succ m) z\"\n    proof\n      from y show \"?R (succ m) (r m y)\" ..\n    next\n      fix z\n      assume \"?R (succ m) z\"\n      then obtain u where \"z = r m u\" and \"?R m u\"\n        by cases simp_all\n      with yy' show \"z = r m y\"\n        by (simp only:)\n    qed\n  qed\nqed\n\n\ntext \\<open>\\<^medskip> The recursion operator -- polymorphic!\\<close>\n\ndefinition rec :: \"'b \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where \"rec e r x = (THE y. Rec e r x y)\"\n\nlemma rec_eval:\n  assumes Rec: \"Rec e r x y\"\n  shows \"rec e r x = y\"\n  unfolding rec_def\n  using Rec_functional and Rec by (rule the1_equality)\n\nlemma rec_zero [simp]: \"rec e r zero = e\"\nproof (rule rec_eval)\n  show \"Rec e r zero e\" ..\nqed\n\nlemma rec_succ [simp]: \"rec e r (succ m) = r m (rec e r m)\"\nproof (rule rec_eval)\n  let ?R = \"Rec e r\"\n  have \"?R m (rec e r m)\"\n    unfolding rec_def using Rec_functional by (rule theI')\n  then show \"?R (succ m) (r m (rec e r m))\" ..\nqed\n\n\ntext \\<open>\\<^medskip> Example: addition (monomorphic)\\<close>\n\ndefinition add :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"add m n = rec n (\\<lambda>_ k. succ k) m\"\n\nlemma add_zero [simp]: \"add zero n = n\"\n  and add_succ [simp]: \"add (succ m) n = succ (add m n)\"\n  unfolding add_def by simp_all\n\n\n\nlemma add_zero_right: \"add m zero = m\"\n  by (induct m) simp_all\n\nlemma add_succ_right: \"add m (succ n) = succ (add m n)\"\n  by (induct m) simp_all\n\nlemma \"add (succ (succ (succ zero))) (succ (succ zero)) =\n    succ (succ (succ (succ (succ zero))))\"\n  by simp\n\n\ntext \\<open>\\<^medskip> Example: replication (polymorphic)\\<close>\n\ndefinition repl :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'b list\"\n  where \"repl n x = rec [] (\\<lambda>_ xs. x # xs) n\"\n\nlemma repl_zero [simp]: \"repl zero x = []\"\n  and repl_succ [simp]: \"repl (succ n) x = x # repl n x\"\n  unfolding repl_def by simp_all\n\nlemma \"repl (succ (succ (succ zero))) True = [True, True, True]\"\n  by simp\n\nend\n\n\ntext \\<open>\\<^medskip> Just see that our abstract specification makes sense \\dots\\<close>\n\ninterpretation peano 0 Suc\nproof\n  fix m n\n  show \"Suc m \\<noteq> 0\" by simp\n  show \"Suc m = Suc n \\<longleftrightarrow> m = n\" by simp\n  show \"P n\"\n    if zero: \"P 0\"\n    and succ: \"\\<And>n. P n \\<Longrightarrow> P (Suc n)\"\n    for P\n  proof (induct n)\n    case 0\n    show ?case by (rule zero)\n  next\n    case Suc\n    then show ?case by (rule succ)\n  qed\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/ex/Peano_Axioms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7701615745929302}}
{"text": "(*  Title:      HOL/ex/Pythagoras.thy\n    Author:     Amine Chaieb\n*)\n\nsection \"The Pythagorean Theorem\"\n\ntheory Pythagoras\nimports Complex_Main\nbegin\n\ntext \\<open>Expressed in real numbers:\\<close>\n\nlemma pythagoras_verbose:\n  \"((A1::real) - B1) * (C1 - B1) + (A2 - B2) * (C2 - B2) = 0 \\<Longrightarrow> \n  (C1 - A1) * (C1 - A1) + (C2 - A2) * (C2 - A2) =\n  ((B1 - A1) * (B1 - A1) + (B2 - A2) * (B2 - A2)) + (C1 - B1) * (C1 - B1) + (C2 - B2) * (C2 - B2)\"\n  by algebra\n\n\ntext \\<open>Expressed in vectors:\\<close>\n\ntype_synonym point = \"real \\<times> real\"\n\nlemma pythagoras: \n  defines ort:\"orthogonal \\<equiv> (\\<lambda>(A::point) B. fst A * fst B + snd A * snd B = 0)\"\n       and vc:\"vector \\<equiv> (\\<lambda>(A::point) B. (fst A  - fst B, snd A - snd B))\"\n      and vcn:\"vecsqnorm \\<equiv> (\\<lambda>A::point. fst A ^ 2 + snd A ^2)\"\n assumes o: \"orthogonal (vector A B) (vector C B)\"\n shows \"vecsqnorm(vector C A) = vecsqnorm(vector B  A) + vecsqnorm(vector C B)\"\n   using o unfolding ort vc vcn by (algebra add: fst_conv snd_conv)\n \n end\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/Pythagoras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8333245932423309, "lm_q1q2_score": 0.7701101131961298}}
{"text": "theory Assertion imports\n\"State\"\n\nbegin\n\n(*evalF defines the semantics of assertions written in first-order logic*)\nprimrec evalF :: \"state => fform => bool\" where\n\"evalF (f,WTrue) = (True)\" |\n\"evalF (f,WFalse) = (False)\" |\n\"evalF (f,e1 [=] e2) = (case (evalE (f,e1), evalE (f,e2)) of\n                            (RR (r1),RR (r2)) => ((r1::real) = r2) |\n                            (SS (r1),SS (r2)) => ((r1::string) = r2) | \n                            (BB (r1),BB (r2)) => ((r1::bool) = r2) | \n                            (_,_) => False)\" |\n\"evalF (f,e1 [<] e2) = (case (evalE (f,e1), evalE (f,e2)) of\n                            (RR (r1),RR (r2)) => ((r1::real) < r2) | \n                            (_,_) => False)\" |\n\"evalF (f,e1 [>] e2) = (case (evalE (f,e1), evalE (f,e2)) of\n                            (RR (r1),RR (r2)) => (r1::real) > r2 | \n                            (_,_) => False)\" |\n\"evalF (f,[~] form1) = (~ (evalF (f,form1)))\" |\n\"evalF (f,form1 [&] form2) = ((evalF (f,form1)) & (evalF (f,form2)))\" |\n\"evalF (f,form1 [|] form2) = ((evalF (f,form1)) | (evalF (f,form2)))\" |\n\"evalF (f,form1 [-->] form2) = ((evalF (f,form1)) --> (evalF (f,form2)))\" |\n\"evalF (f,form1 [<->] form2) = ((evalF (f,form1)) <-> (evalF (f,form2)))\" |\n\"evalF (f,WALL x form1)= (ALL (v::real). (evalF((%a. %i. (if (a=x) then (RR (v)) else (f(a, i)))), form1)))\" |\n\"evalF (f,WEX x form1)= (EX (v::real). evalF((%a. %i. (if (a=x) then (RR (v)) else f(a, i))), form1))\"\n\n\ndefinition evalFP :: \"cstate => fform => now => bool\" where\n\"evalFP(f,P,c) == ALL s. inList(s,f(c)) --> evalF(s,P)\"\n\n(*ievalF defines the semantics of assertions written in interval logic and duration calculus*)\nconsts ievalF :: \"cstate => fform => now => now => bool\"\naxiomatization where\nchop_eval: \"ievalF (f, P[^]Q, c, d) =  (EX k s1 s2. s1@s2=f(k) & ievalF (%t. if t=k then s1 else f(t), P, c, k)\n                                                  & ievalF (%t. if t=k then s2 else f(t), Q, k, d))\" and\nchop_sep: \"ievalF (f, P, c, d) = (ALL k s1 s2. s1@s2=f(k) --> ievalF (%t. if t=k then s1 else f(t), P, c, k)\n                                                  & ievalF (%t. if t=k then s2 else f(t), P, k, d))\" and\npf_eval: \"ievalF (f, pf (P), c, d) = (c=d & (EX s. inList(s, f(c))) & evalF (s, P))\" and\nhigh_eval: \"ievalF (f, high P, c, d) = ((ALL (k::real). (c<k & k<d) --> evalFP (f, P, k)))\" and\nchop_interval: \"(ALL t. (c=d --> f(c)=g(c)) & (c<=t & t<=d --> f(t)=g(t))) ==> ievalF(f,P,c,d)=ievalF(g,P,c,d)\"\n\nlemma chop_eval1: \"(EX k. ievalF (f, P, c, k) & ievalF (f, Q, k, d)) ==> ievalF (f, P[^]Q, c, d)\"\napply (simp add: chop_eval,auto)\napply (cut_tac x=k in exI,auto)\napply (cut_tac x=\"f(k)\" in exI,auto)\napply (subgoal_tac \"f = (%t. if t = k then f(k) else f(t))\",auto)\napply (subgoal_tac \"(ALL ka s1 s2. s1@s2=f(ka) --> ievalF (%t. if t=ka then s1 else f(t), Q, k, ka)\n                                                  & ievalF (%t. if t=ka then s2 else f(t), Q, ka, d))\")\napply (subgoal_tac \"ievalF(%t. if t = k then f(k) else f(t), Q, k, k) &\n               ievalF(%t. if t = k then [] else f(t), Q, k, d)\")\napply blast\napply (erule allE)+\napply blast\napply (cut_tac f=f and P=Q and c=k and d=d in chop_sep,auto)\ndone\n\n(*The following axioms define the evaluation of formulas of part of first-order interval logic.*)\naxiomatization where\nTrue_eval : \"ievalF (f,WTrue, c, d) = (True)\"  and\nFalse_eval : \"ievalF (f,WFalse,c,d) = (False)\" and\nL_eval : \"ievalF (f, (l [=] Real L), c, d) = (d-c = L)\" and \n(*Equal_eval : \"ievalF (f,e1 [=] e2,c,d) = evalFP(f,e1 [=] e2,c)\" and\nLess_eval : \"ievalF (f,e1 [<] e2,c,d) = evalFP(f,e1 [<] e2,c)\" and\nGreat_eval: \"ievalF (f,e1 [>] e2,c,d) = evalFP(f,e1 [>] e2,c)\" and*)\nNot_eval: \"ievalF (f,[~] form1,c,d) = (~ (ievalF (f,form1,c,d)))\" and\nAnd_eval: \"ievalF (f,form1 [&] form2,c,d) = ((ievalF (f,form1,c,d)) & (ievalF (f,form2,c,d)))\" and\nOr_eval: \"ievalF (f,F [|] G,c,d) = ((ievalF (f,F,c,d)) | (ievalF (f,G,c,d)))\" and\nImply_eval: \"ievalF (f,form1 [-->] form2,c,d) = ((ievalF (f,form1,c,d)) --> (ievalF (f,form2,c,d)))\" and\nEquiv_eval: \"ievalF (f,form1 [<->] form2,c,d) = ((ievalF (f,form1,c,d)) <-> (ievalF (f,form2,c,d)))\" and\nALL_eval: \"ievalF (f,WALL x form1,c,d)= (ALL (v::real). ievalF((%t. List.map(%s. %y i. if y=x & i=R then RR(v) else s(y,i),f(t))), form1, c, d))\" and\nEX_eval: \"ievalF (f,WEX x form1,c,d)= (EX (v::real). ievalF((%t. List.map(%s. %y i. if y=x & i=R then RR(v) else s(y,i),f(t))), form1, c, d))\"\n\n(*The following axioms define the semantic meanings of closure of formulas.*)\naxiomatization where\nclose_fact1: \"ALL t. (t>=b & t<c --> evalF (f, p)) --> (evalF (f, close(p)))\" and\nclose_fact2: \"ALL t. (t>=b & t<c --> evalF (f, p)) --> (evalF (f, close([~]p)))\" and\nclose_fact3: \"evalF (s,p) ==> evalF (s,close(p))\"\n\nend\n", "meta": {"author": "wangslyl", "repo": "hhlprover", "sha": "500e7ae1f93f0decb67b55ec2e0b4f756ae9ede0", "save_path": "github-repos/isabelle/wangslyl-hhlprover", "path": "github-repos/isabelle/wangslyl-hhlprover/hhlprover-500e7ae1f93f0decb67b55ec2e0b4f756ae9ede0/HHLProver/Assertion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.8267117876664789, "lm_q1q2_score": 0.7700510342798235}}
{"text": "section \\<open> Enumeration Extras \\<close>\n\ntheory Enum_extra\n  imports \"HOL-Library.Cardinality\"\nbegin\n\nsubsection \\<open> First Index Function \\<close>\n\ntext \\<open> The following function extracts the index of the first occurrence of an element in a list, \n  assuming it is indeed an element. \\<close>\n\nfun first_ind :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"first_ind [] y i = undefined\" |\n\"first_ind (x # xs) y i = (if (x = y) then i else first_ind xs y (Suc i))\"\n\nlemma first_ind_length:\n  \"x \\<in> set(xs) \\<Longrightarrow> first_ind xs x i < length(xs) + i\"\n  by (induct xs arbitrary: i, auto, metis add_Suc_right)\n\nlemma nth_first_ind:\n  \"\\<lbrakk> distinct xs; x \\<in> set(xs) \\<rbrakk> \\<Longrightarrow> xs ! (first_ind xs x i - i) = x\"\n  apply (induct xs arbitrary: i)\n   apply (auto)\n  apply (metis One_nat_def add.right_neutral add_Suc_right add_diff_cancel_left' diff_diff_left empty_iff first_ind.simps(2) list.set(1) nat.simps(3) neq_Nil_conv nth_Cons' zero_diff)\n  done\n\nlemma first_ind_nth:\n  \"\\<lbrakk> distinct xs; i < length xs \\<rbrakk> \\<Longrightarrow> first_ind xs (xs ! i) j = i + j\"\n  apply (induct xs arbitrary: i j)\n   apply (auto)\n   apply (metis less_Suc_eq_le nth_equal_first_eq)\n  using less_Suc_eq_0_disj apply auto\n  done\n\nsubsection \\<open> Enumeration Indices \\<close>\n\nsyntax\n  \"_ENUM\" :: \"type \\<Rightarrow> logic\" (\"ENUM'(_')\")\n\ntranslations\n  \"ENUM('a)\" => \"CONST Enum.enum :: ('a::enum) list\"\n\ntext \\<open> Extract a unique natural number associated with an enumerated value by using its index\n  in the characteristic list \\<^term>\\<open>ENUM('a)\\<close>. \\<close>\n\ndefinition enum_ind :: \"'a::enum \\<Rightarrow> nat\" where\n\"enum_ind (x :: 'a::enum) = first_ind ENUM('a) x 0\"\n\nlemma length_enum_CARD: \"length ENUM('a) = CARD('a)\"\n  by (simp add: UNIV_enum distinct_card enum_distinct)\n\nlemma CARD_length_enum: \"CARD('a) = length ENUM('a)\"\n  by (simp add: length_enum_CARD)\n\nlemma enum_ind_less_CARD [simp]: \"enum_ind (x :: 'a::enum) < CARD('a)\"\n  using first_ind_length[of x, OF in_enum, of 0] by (simp add: enum_ind_def CARD_length_enum)\n  \nlemma enum_nth_ind [simp]: \"Enum.enum ! (enum_ind x) = x\"\n  using nth_first_ind[of Enum.enum x 0, OF enum_distinct in_enum] by (simp add: enum_ind_def)\n\nlemma enum_distinct_conv_nth:\n  assumes \"i < CARD('a)\" \"j < CARD('a)\" \"ENUM('a) ! i = ENUM('a) ! j\"\n  shows \"i = j\"\nproof -\n  have \"(\\<forall>i<length ENUM('a). \\<forall>j<length ENUM('a). i \\<noteq> j \\<longrightarrow> ENUM('a) ! i \\<noteq> ENUM('a) ! j)\"\n    using distinct_conv_nth[of \"ENUM('a)\", THEN sym] by (simp add: enum_distinct)\n  with assms show ?thesis\n    by (auto simp add: CARD_length_enum)\nqed\n\nlemma enum_ind_nth [simp]:\n  assumes \"i < CARD('a::enum)\"\n  shows \"enum_ind (ENUM('a) ! i) = i\"\n  using assms first_ind_nth[of \"ENUM('a)\" i 0, OF enum_distinct]\n  by (simp add: enum_ind_def CARD_length_enum)\n\nlemma enum_ind_spec:\n  \"enum_ind (x :: 'a::enum) = (THE i. i < CARD('a) \\<and> Enum.enum ! i = x)\"\nproof (rule sym, rule the_equality, safe)\n  show \"enum_ind x < CARD('a)\"\n    by (simp add: enum_ind_less_CARD[of x])\n  show \"enum_class.enum ! enum_ind x = x\"\n    by simp\n  show \"\\<And>i. i < CARD('a) \\<Longrightarrow> x = ENUM('a) ! i \\<Longrightarrow> i = enum_ind (ENUM('a) ! i)\"\n    by (simp add: enum_ind_nth)\nqed\n\nlemma enum_ind_inj: \"inj (enum_ind :: 'a::enum \\<Rightarrow> nat)\"\n  by (rule inj_on_inverseI[of _ \"\\<lambda> i. ENUM('a) ! i\"], simp)\n\nlemma enum_ind_neq [simp]: \"x \\<noteq> y \\<Longrightarrow> enum_ind x \\<noteq> enum_ind y\"\n  by (simp add: enum_ind_inj inj_eq)\n\nend", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Physical_Quantities/Enum_extra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7700143834425818}}
{"text": "header \"Derivatives of regular expressions\"\n\n(* Author: Christian Urban *)\n\ntheory Derivatives\nimports Regular_Exp\nbegin\n\ntext{* This theory is based on work by Brozowski \\cite{Brzozowski64} and Antimirov \\cite{Antimirov95}. *}\n\nsubsection {* Brzozowski's derivatives of regular expressions *}\n\nprimrec\n  deriv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"deriv c (Zero) = Zero\"\n| \"deriv c (One) = Zero\"\n| \"deriv c (Atom c') = (if c = c' then One else Zero)\"\n| \"deriv c (Plus r1 r2) = Plus (deriv c r1) (deriv c r2)\"\n| \"deriv c (Times r1 r2) = \n    (if nullable r1 then Plus (Times (deriv c r1) r2) (deriv c r2) else Times (deriv c r1) r2)\"\n| \"deriv c (Star r) = Times (deriv c r) (Star r)\"\n\nprimrec \n  derivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"derivs [] r = r\"\n| \"derivs (c # s) r = derivs s (deriv c r)\"\n\n\nlemma atoms_deriv_subset: \"atoms (deriv x r) \\<subseteq> atoms r\"\nby (induction r) (auto)\n\nlemma atoms_derivs_subset: \"atoms (derivs w r) \\<subseteq> atoms r\"\nby (induction w arbitrary: r) (auto dest: atoms_deriv_subset[THEN subsetD])\n\nlemma lang_deriv: \"lang (deriv c r) = Deriv c (lang r)\"\nby (induct r) (simp_all add: nullable_iff)\n\nlemma lang_derivs: \"lang (derivs s r) = Derivs s (lang r)\"\nby (induct s arbitrary: r) (simp_all add: lang_deriv)\n\ntext {* A regular expression matcher: *}\n\ndefinition matcher :: \"'a rexp \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"matcher r s = nullable (derivs s r)\"\n\nlemma matcher_correctness: \"matcher r s \\<longleftrightarrow> s \\<in> lang r\"\nby (induct s arbitrary: r)\n   (simp_all add: nullable_iff lang_deriv matcher_def Deriv_def)\n\n\nsubsection {* Antimirov's partial derivatives *}\n\nabbreviation\n  \"Timess rs r \\<equiv> (\\<Union>r' \\<in> rs. {Times r' r})\"\n\nprimrec\n  pderiv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderiv c Zero = {}\"\n| \"pderiv c One = {}\"\n| \"pderiv c (Atom c') = (if c = c' then {One} else {})\"\n| \"pderiv c (Plus r1 r2) = (pderiv c r1) \\<union> (pderiv c r2)\"\n| \"pderiv c (Times r1 r2) = \n    (if nullable r1 then Timess (pderiv c r1) r2 \\<union> pderiv c r2 else Timess (pderiv c r1) r2)\"\n| \"pderiv c (Star r) = Timess (pderiv c r) (Star r)\"\n\nprimrec\n  pderivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> ('a rexp) set\"\nwhere\n  \"pderivs [] r = {r}\"\n| \"pderivs (c # s) r = \\<Union> (pderivs s ` pderiv c r)\"\n\nabbreviation\n pderiv_set :: \"'a \\<Rightarrow> 'a rexp set \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderiv_set c rs \\<equiv> \\<Union> (pderiv c ` rs)\"\n\nabbreviation\n  pderivs_set :: \"'a list \\<Rightarrow> 'a rexp set \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderivs_set s rs \\<equiv> \\<Union> (pderivs s ` rs)\"\n\nlemma pderivs_append:\n  \"pderivs (s1 @ s2) r = \\<Union> (pderivs s2 ` pderivs s1 r)\"\nby (induct s1 arbitrary: r) (simp_all)\n\nlemma pderivs_snoc:\n  shows \"pderivs (s @ [c]) r = pderiv_set c (pderivs s r)\"\nby (simp add: pderivs_append)\n\nlemma pderivs_simps [simp]:\n  shows \"pderivs s Zero = (if s = [] then {Zero} else {})\"\n  and   \"pderivs s One = (if s = [] then {One} else {})\"\n  and   \"pderivs s (Plus r1 r2) = (if s = [] then {Plus r1 r2} else (pderivs s r1) \\<union> (pderivs s r2))\"\nby (induct s) (simp_all)\n\nlemma pderivs_Atom:\n  shows \"pderivs s (Atom c) \\<subseteq> {Atom c, One}\"\nby (induct s) (simp_all)\n\nsubsection {* Relating left-quotients and partial derivatives *}\n\nlemma Deriv_pderiv:\n  shows \"Deriv c (lang r) = \\<Union> (lang ` pderiv c r)\"\nby (induct r) (auto simp add: nullable_iff conc_UNION_distrib)\n\nlemma Derivs_pderivs:\n  shows \"Derivs s (lang r) = \\<Union> (lang ` pderivs s r)\"\nproof (induct s arbitrary: r)\n  case (Cons c s)\n  have ih: \"\\<And>r. Derivs s (lang r) = \\<Union> (lang ` pderivs s r)\" by fact\n  have \"Derivs (c # s) (lang r) = Derivs s (Deriv c (lang r))\" by simp\n  also have \"\\<dots> = Derivs s (\\<Union> (lang ` pderiv c r))\" by (simp add: Deriv_pderiv)\n  also have \"\\<dots> = Derivss s (lang ` (pderiv c r))\"\n    by (auto simp add:  Derivs_def)\n  also have \"\\<dots> = \\<Union> (lang ` (pderivs_set s (pderiv c r)))\"\n    using ih by auto\n  also have \"\\<dots> = \\<Union> (lang ` (pderivs (c # s) r))\" by simp\n  finally show \"Derivs (c # s) (lang r) = \\<Union> (lang ` pderivs (c # s) r)\" .\nqed (simp add: Derivs_def)\n\nsubsection {* Relating derivatives and partial derivatives *}\n\nlemma deriv_pderiv:\n  shows \"\\<Union> (lang ` (pderiv c r)) = lang (deriv c r)\"\nunfolding lang_deriv Deriv_pderiv by simp\n\nlemma derivs_pderivs:\n  shows \"\\<Union> (lang ` (pderivs s r)) = lang (derivs s r)\"\nunfolding lang_derivs Derivs_pderivs by simp\n\n\nsubsection {* Finiteness property of partial derivatives *}\n\ndefinition\n  pderivs_lang :: \"'a lang \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderivs_lang A r \\<equiv> \\<Union>x \\<in> A. pderivs x r\"\n\nlemma pderivs_lang_subsetI:\n  assumes \"\\<And>s. s \\<in> A \\<Longrightarrow> pderivs s r \\<subseteq> C\"\n  shows \"pderivs_lang A r \\<subseteq> C\"\nusing assms unfolding pderivs_lang_def by (rule UN_least)\n\nlemma pderivs_lang_union:\n  shows \"pderivs_lang (A \\<union> B) r = (pderivs_lang A r \\<union> pderivs_lang B r)\"\nby (simp add: pderivs_lang_def)\n\nlemma pderivs_lang_subset:\n  shows \"A \\<subseteq> B \\<Longrightarrow> pderivs_lang A r \\<subseteq> pderivs_lang B r\"\nby (auto simp add: pderivs_lang_def)\n\ndefinition\n  \"UNIV1 \\<equiv> UNIV - {[]}\"\n\nlemma pderivs_lang_Zero [simp]:\n  shows \"pderivs_lang UNIV1 Zero = {}\"\nunfolding UNIV1_def pderivs_lang_def by auto\n\nlemma pderivs_lang_One [simp]:\n  shows \"pderivs_lang UNIV1 One = {}\"\nunfolding UNIV1_def pderivs_lang_def by (auto split: if_splits)\n\nlemma pderivs_lang_Atom [simp]:\n  shows \"pderivs_lang UNIV1 (Atom c) = {One}\"\nunfolding UNIV1_def pderivs_lang_def \napply(auto)\napply(frule rev_subsetD)\napply(rule pderivs_Atom)\napply(simp)\napply(case_tac xa)\napply(auto split: if_splits)\ndone\n\nlemma pderivs_lang_Plus [simp]:\n  shows \"pderivs_lang UNIV1 (Plus r1 r2) = pderivs_lang UNIV1 r1 \\<union> pderivs_lang UNIV1 r2\"\nunfolding UNIV1_def pderivs_lang_def by auto\n\n\ntext {* Non-empty suffixes of a string (needed for the cases of @{const Times} and @{const Star} below) *}\n\ndefinition\n  \"PSuf s \\<equiv> {v. v \\<noteq> [] \\<and> (\\<exists>u. u @ v = s)}\"\n\nlemma PSuf_snoc:\n  shows \"PSuf (s @ [c]) = (PSuf s) @@ {[c]} \\<union> {[c]}\"\nunfolding PSuf_def conc_def\nby (auto simp add: append_eq_append_conv2 append_eq_Cons_conv)\n\nlemma PSuf_Union:\n  shows \"(\\<Union>v \\<in> PSuf s @@ {[c]}. f v) = (\\<Union>v \\<in> PSuf s. f (v @ [c]))\"\nby (auto simp add: conc_def)\n\nlemma pderivs_lang_snoc:\n  shows \"pderivs_lang (PSuf s @@ {[c]}) r = (pderiv_set c (pderivs_lang (PSuf s) r))\"\nunfolding pderivs_lang_def\nby (simp add: PSuf_Union pderivs_snoc)\n\nlemma pderivs_Times:\n  shows \"pderivs s (Times r1 r2) \\<subseteq> Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2)\"\nproof (induct s rule: rev_induct)\n  case (snoc c s)\n  have ih: \"pderivs s (Times r1 r2) \\<subseteq> Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2)\" \n    by fact\n  have \"pderivs (s @ [c]) (Times r1 r2) = pderiv_set c (pderivs s (Times r1 r2))\" \n    by (simp add: pderivs_snoc)\n  also have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2))\"\n    using ih by fast\n  also have \"\\<dots> = pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderiv_set c (pderivs_lang (PSuf s) r2)\"\n    by (simp)\n  also have \"\\<dots> = pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (simp add: pderivs_lang_snoc)\n  also \n  have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by auto\n  also \n  have \"\\<dots> \\<subseteq> Timess (pderiv_set c (pderivs s r1)) r2 \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (auto simp add: if_splits)\n  also have \"\\<dots> = Timess (pderivs (s @ [c]) r1) r2 \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (simp add: pderivs_snoc)\n  also have \"\\<dots> \\<subseteq> Timess (pderivs (s @ [c]) r1) r2 \\<union> pderivs_lang (PSuf (s @ [c])) r2\"\n    unfolding pderivs_lang_def by (auto simp add: PSuf_snoc)  \n  finally show ?case .\nqed (simp) \n\nlemma pderivs_lang_Times_aux1:\n  assumes a: \"s \\<in> UNIV1\"\n  shows \"pderivs_lang (PSuf s) r \\<subseteq> pderivs_lang UNIV1 r\"\nusing a unfolding UNIV1_def PSuf_def pderivs_lang_def by auto\n\n\n\nlemma pderivs_lang_Times:\n  shows \"pderivs_lang UNIV1 (Times r1 r2) \\<subseteq> Timess (pderivs_lang UNIV1 r1) r2 \\<union> pderivs_lang UNIV1 r2\"\napply(rule pderivs_lang_subsetI)\napply(rule subset_trans)\napply(rule pderivs_Times)\nusing pderivs_lang_Times_aux1 pderivs_lang_Times_aux2\napply(blast)\ndone\n\nlemma pderivs_Star:\n  assumes a: \"s \\<noteq> []\"\n  shows \"pderivs s (Star r) \\<subseteq> Timess (pderivs_lang (PSuf s) r) (Star r)\"\nusing a\nproof (induct s rule: rev_induct)\n  case (snoc c s)\n  have ih: \"s \\<noteq> [] \\<Longrightarrow> pderivs s (Star r) \\<subseteq> Timess (pderivs_lang (PSuf s) r) (Star r)\" by fact\n  { assume asm: \"s \\<noteq> []\"\n    have \"pderivs (s @ [c]) (Star r) = pderiv_set c (pderivs s (Star r))\" by (simp add: pderivs_snoc)\n    also have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs_lang (PSuf s) r) (Star r))\"\n      using ih[OF asm] by fast\n    also have \"\\<dots> \\<subseteq> Timess (pderiv_set c (pderivs_lang (PSuf s) r)) (Star r) \\<union> pderiv c (Star r)\"\n      by (auto split: if_splits)\n    also have \"\\<dots> \\<subseteq> Timess (pderivs_lang (PSuf (s @ [c])) r) (Star r) \\<union> (Timess (pderiv c r) (Star r))\"\n      by (simp only: PSuf_snoc pderivs_lang_snoc pderivs_lang_union)\n         (auto simp add: pderivs_lang_def)\n    also have \"\\<dots> = Timess (pderivs_lang (PSuf (s @ [c])) r) (Star r)\"\n      by (auto simp add: PSuf_snoc PSuf_Union pderivs_snoc pderivs_lang_def)\n    finally have ?case .\n  }\n  moreover\n  { assume asm: \"s = []\"\n    then have ?case by (auto simp add: pderivs_lang_def pderivs_snoc PSuf_def)\n  }\n  ultimately show ?case by blast\nqed (simp)\n\nlemma pderivs_lang_Star:\n  shows \"pderivs_lang UNIV1 (Star r) \\<subseteq> Timess (pderivs_lang UNIV1 r) (Star r)\"\napply(rule pderivs_lang_subsetI)\napply(rule subset_trans)\napply(rule pderivs_Star)\napply(simp add: UNIV1_def)\napply(simp add: UNIV1_def PSuf_def)\napply(auto simp add: pderivs_lang_def)\ndone\n\nlemma finite_Timess [simp]:\n  assumes a: \"finite A\"\n  shows \"finite (Timess A r)\"\nusing a by auto\n\nlemma finite_pderivs_lang_UNIV1:\n  shows \"finite (pderivs_lang UNIV1 r)\"\napply(induct r)\napply(simp_all add: \n  finite_subset[OF pderivs_lang_Times]\n  finite_subset[OF pderivs_lang_Star])\ndone\n    \nlemma pderivs_lang_UNIV:\n  shows \"pderivs_lang UNIV r = pderivs [] r \\<union> pderivs_lang UNIV1 r\"\nunfolding UNIV1_def pderivs_lang_def\nby blast\n\nlemma finite_pderivs_lang_UNIV:\n  shows \"finite (pderivs_lang UNIV r)\"\nunfolding pderivs_lang_UNIV\nby (simp add: finite_pderivs_lang_UNIV1)\n\nlemma finite_pderivs_lang:\n  shows \"finite (pderivs_lang A r)\"\nby (metis finite_pderivs_lang_UNIV pderivs_lang_subset rev_finite_subset subset_UNIV)\n\nend", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Regular-Sets/Derivatives.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110454379297, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7699821758804485}}
{"text": "theory Chap5 imports Main\nbegin\n\nlemma \"\\<not> surj ( f :: 'a \\<Rightarrow> 'a set )\"\nproof\n  assume 0 : \"surj f\"\n  from this have \"\\<forall> A . \\<exists> a . A = f a\" by ( simp add: surj_def)\n  from this have \"\\<exists> a . { x . x \\<notin> f x } = f a\" by blast\n  from this have \"\\<exists> a . x \\<in> f a = ( x \\<notin> f a )\" by blast\n  from this show \"False\" by blast\nqed\n\nlemma\n  assumes T : \"\\<forall> x y . T x y \\<or> T y x\"\n      and A : \"\\<forall> x y . A x y \\<and> A y x \\<longrightarrow> x = y\"\n      and TA: \"\\<forall> x y . T x y \\<longrightarrow> A x y\"\n      and \"A x y\"\n    shows \"T x y\"\nproof cases\n  assume \"T x y\"\n  thus \"T x y\" by simp\nnext\n  assume \"\\<not> T x y\"\n  hence \"T y x\" using T by blast\n  hence \"A y x\" using TA by blast\n  hence \"x = y\" using assms by blast\n  thus \"T x y\" using T by blast\nqed\n\n\nlemma \"( \\<exists> ys zs . xs = ys @ zs \\<and> length ys = length zs )\n     \\<or> ( \\<exists> ys zs . xs = ys @ zs \\<and> length ys = length zs + 1 )\"\nproof cases\n  assume \"even ( length xs )\"\n    hence \"\\<exists> n . length xs = 2*n\" by ( auto simp add: dvd_def )\n    then obtain n where \"length xs = 2*n\" by blast\n    let ?ys = \"take n xs\"\n    let ?zs = \"drop n xs\"\n    have \"length ?ys = length ?zs\" by (simp add: `length xs = 2 * n`)\n    hence \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs\" by simp\n    hence \"\\<exists> ys zs . xs = ys @ zs \\<and> length ys = length zs\" by blast\n  thus ?thesis by blast\nnext\n  assume \"odd ( length xs )\"\n    hence \"\\<exists> n . length xs = (2 * n) + 1\" by presburger\n    from this obtain n where \"length xs = (2 * n) + 1\" by blast\n    let ?ys = \"take ( n + 1 ) xs\"\n    let ?zs = \"drop ( n + 1 ) xs\"\n    have \"length ?ys = length ?zs + 1\" by ( simp add: `length xs = (2 * n) + 1`)\n    hence \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" by auto\n    hence \"\\<exists> ys zs . xs = ys @ zs \\<and> length ys = length zs + 1\" by blast\n  thus ?thesis by blast\nqed\n\n\nlemma \"length(tl xs) = length xs - 1\"\nproof ( cases xs )\n  assume \"xs = []\"\n  thus ?thesis by simp\nnext\n  fix y ys assume \"xs = y # ys\"\n  thus ?thesis by simp\nqed\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS : \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nlemma \"ev n \\<Longrightarrow> ev ( n - 2 )\"\nproof -\n  assume \"ev n\"\n  from this have \"ev ( n - 2 )\"\n  proof ( cases )\n    case ev0 thus \"ev ( n - 2 )\" by ( simp add: ev.ev0 )\n  next\n    case (evSS k) thus \"ev ( n - 2 )\" by simp\n  qed\n  thus ?thesis by blast\nqed\n\nlemma \"ev ( Suc m ) \\<Longrightarrow> \\<not> ev m\"\nproof ( induction \"Suc m\" arbitrary: m rule: ev.induct )\n  fix n assume IH: \"\\<And> m . n = Suc m \\<Longrightarrow> \\<not> ev m\"\n  show \"\\<not> ev ( Suc n )\"\n  proof -- contradiction\n    assume \"ev ( Suc n )\"\n    thus False\n    proof ( cases \"Suc n\" -- rule  )\n      fix k assume \"n = Suc k\" \"ev k\"\n      thus False using IH by auto\n    qed\n  qed\nqed\n\n\nlemma \n  assumes \"ev n\"\n  shows \"ev ( n - 2 )\"\nproof -\n  show \"ev ( n - 2 )\" using `ev n`\n  proof cases\n    case ev0 thus \"ev ( n - 2 )\" by ( simp add: ev.ev0)\n  next\n    case evSS thus \"ev ( n - 2 )\" by simp\n  qed\nqed\n\nlemma\n  assumes a: \"ev ( Suc ( Suc n ) )\"\n  shows \"ev n\"\nproof -\n  from a show \"ev n\" by cases\nqed\n\nlemma \"\\<not> ev ( Suc ( Suc ( Suc 0 ) ) )\"\nproof\n  assume \"ev ( Suc ( Suc ( Suc 0 ) ) )\"\n  thus False\n  proof cases\n    assume \"ev ( Suc 0 )\" hence False by cases\n    thus False by blast\n  qed\nqed\n\ninductive star :: \"( 'a \\<Rightarrow> 'a \\<Rightarrow> bool ) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl  : \"star r x x\" |\n  step  : \"r x y  \\<Longrightarrow>  star r y z  \\<Longrightarrow>  star r x z\"\n\ninductive iter :: \"( 'a \\<Rightarrow> 'a \\<Rightarrow> bool ) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl_i : \"iter r 0 x x\" |\n  step_i : \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r ( n + 1 ) x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof ( induction rule: iter.induct )\n  fix x show \"star r x x\" by ( simp add: refl )\n  fix x y n z assume \"r x y\" \"star r y z\"\n  thus \"star r x z\" by ( metis step )\nqed\n  \n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n  \"elems [] = {}\" |\n  \"elems ( a # as ) = { a } \\<union> elems as\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof ( induction xs rule: elems.induct )\n  assume \"x \\<in> elems []\"\n  thus \"\\<exists> ys zs . [] = ys @ x # zs \\<and> x \\<notin> elems ys\"  by simp\n\n  next\n  fix a as assume IH : \"(x \\<in> elems as \\<Longrightarrow> \\<exists>ys zs. as = ys @ x # zs \\<and> x \\<notin> elems ys)\"\n               and H : \"x \\<in> elems (a # as)\"\n  thus \"\\<exists>ys zs. a # as = ys @ x # zs \\<and> x \\<notin> elems ys\"\n\n  proof ( cases \"x = a\" )\n    assume \"x \\<noteq> a\"\n    hence \"x \\<in> elems as\" using H by auto\n    hence \"\\<exists> ys zs . as = ys @ x # zs \\<and> x \\<notin> elems ys\" using IH  by auto\n    then obtain ys zs where \"as = ys @ x # zs \\<and> x \\<notin> elems ys\" by blast\n      hence \"a # as = (a # ys) @ x # zs \\<and> x \\<notin> elems ( a # ys )\" using `x \\<noteq> a` by auto\n    thus \"\\<exists>ys zs. a # as = ys @ x # zs \\<and> x \\<notin> elems ys\" by blast\n\n  next\n    assume \"x = a\"\n    hence \"a # as = [] @ x # as \\<and> x \\<notin> elems []\" by auto\n    thus ?thesis by blast\n\n  qed\nqed\n\n\n\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\n  emptyS  : \"S []\" |\n  middl   : \"S w \\<Longrightarrow> S ( a # w @ [b] )\" |\n  doubl   : \"S w \\<Longrightarrow> S v \\<Longrightarrow> S ( w @ v )\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\n  emptyT  : \"T []\" |\n  alter   : \"T w \\<Longrightarrow> T v \\<Longrightarrow> T ( w @ a # v @ [b] )\"\n\n\nlemma TImpS : \"T w \\<Longrightarrow> S w\"\n  apply ( induction rule: T.induct )\n  apply ( rule emptyS )\n  apply ( rule doubl )\n  apply ( assumption )\n  apply ( rule middl )\n  apply ( assumption )\ndone\n\nlemma app_emp : \"T ([] @ a # w @ [b]) \\<Longrightarrow> T ( a # w @ [b])\"\n  apply ( auto )\ndone\n\nlemma assoc_arb : \"X ((w @ a # v @ b # wa) @ a # va @ [b]) \\<Longrightarrow> X (w @ a # v @ b # wa @ a # va @ [b])\"\n  apply ( auto )\ndone\n\n\nlemma append_T : \"T ts \\<Longrightarrow> T v \\<Longrightarrow> T w \\<Longrightarrow> T (w @ a # v @ b # ts)\"\n  apply ( induction rule: T.induct )\n  apply ( metis alter )\n  apply ( rule assoc_arb )\n  apply ( metis alter )\ndone\n\nlemma doublT : \"T w \\<Longrightarrow> T v \\<Longrightarrow> T ( w @ v)\"\n  apply ( induction rule: T.induct )\n  apply ( auto )\n  apply ( metis append_T )\ndone\n\nlemma SImpT : \"S w \\<Longrightarrow> T w\"\n  apply ( induction rule: S.induct )\n  apply ( rule emptyT )\n  apply ( rule app_emp )\n  apply ( rule alter )\n  apply ( rule emptyT )\n  apply ( assumption )\n  apply ( metis doublT )\ndone\n\nthm append_eq_append_conv_if leD\n\nlemma \"S w = T w\" by ( metis SImpT TImpS )\n\nlemma ab_inter : \"S ( v @ w ) \\<Longrightarrow> S ( v @ a # b # w )\"\nproof ( induction \"v @ w\" arbitrary: v w rule: S.induct )\n\n  fix v :: \"alpha list\" and w assume\n    E : \"[] = v @ w\"\n    show \"S ( v @ a # b # w )\"\n  proof -\n    have \"S ( a # [] @ [b] )\" by ( metis middl emptyS )\n    hence \"S ( a # [b] )\" by simp\n    moreover have \"v=[]\" using E by simp\n    moreover have \"w=[]\" using E by simp\n    ultimately show \"S ( v @ a # b # w )\" by simp\n  qed\n\n  next\n  fix w v w' assume\n    H : \"S w\" and\n    IH : \"\\<And>v w' . w = v @ w' \\<Longrightarrow> S ( v @ a # b # w' )\" and\n    EH : \"a # w @ [b] = v @ w'\"\n    show \"S ( v @ a # b # w' )\"\n  proof ( cases \"v = []\" )\n    assume \"v = []\" show \"S ( v @ a # b # w' )\"\n    proof -\n      have \"w' = a # w @ [b]\" using `v = []` EH by simp\n      moreover hence \"S ( w' )\" using H by ( metis middl )\n      moreover hence \"S ( v @ a # [ b ] )\" using `v = []` by ( metis append_Nil emptyS middl )\n      ultimately have \"S ( ( v @ a # [ b ] ) @ w' )\" by ( metis doubl )\n      thus \"S ( v @ a # b # w' )\" by simp\n    qed\n\n    next\n    assume \"v \\<noteq> []\" show \"S ( v @ a # b # w' )\"\n    proof ( cases \"w' = []\" )\n      assume \"w' = []\" show \"S ( v @ a # b # w' )\"\n      proof -\n        have \"v = a # w @ [b]\" using `w' = []` EH by simp\n        moreover hence \"S ( v )\" using H by ( metis middl )\n        moreover hence \"S ( v @ a # [ b ] )\" by ( metis emptyS middl doubl append_Nil )\n        ultimately have \"S ( v @ a # [ b ] @ w' )\" using `w' = []` by simp\n        thus \"S ( v @ a # b # w' )\" by simp\n      qed\n\n      next\n      assume \"w' \\<noteq> []\" show \"S ( v @ a # b # w' )\"\n      proof -\n        have \"v @ w' = ( hd v ) # ( tl v ) @ w'\" using `v \\<noteq> []` by simp\n        hence V: \"w @ [ b ] = tl v @ w' \\<and> hd v = a\" using `v \\<noteq> []` EH by ( metis list.inject )\n        hence \"w @ [ b ] = ( tl v @ butlast w' ) @ [ last w' ]\" using `w' \\<noteq> []` by simp\n        hence W': \"w = tl v @ butlast w' \\<and> last w' = b\" by ( metis append1_eq_conv )\n        hence \"S ( tl v @ butlast w' )\" using H by metis\n        hence \"S ( tl v @ a # b # butlast w' )\" using IH W' by metis\n        hence \"S ( a # (tl v @ a # b # butlast w' ) @ [ b ] )\" by ( metis middl )\n        hence \"S ( ( a # tl v ) @ [a,b] @ ( butlast w' @ [ b ] ) )\" by simp\n        moreover have \"a # tl v = v\" using V list.collapse `v \\<noteq> []` by force\n        moreover have \"butlast w' @ [ b ] = w'\" using W' append_butlast_last_id `w' \\<noteq> []` by force\n        ultimately show \"S (  v @ a # b # w' )\" by simp\n      qed\n    qed\n  qed\n\n  next\n  fix w v p s assume\n    W : \"S w\"\n    \"\\<And>p s. w = p @ s \\<Longrightarrow> S ( p @ a # b # s )\" and\n    V : \"S v\"\n    \"\\<And>p s. v = p @ s \\<Longrightarrow> S ( p @ a # b # s )\" and\n    EH : \"w @ v = p @ s\"\n    show \"S ( p @ a # b # s )\"\n  proof ( cases \"length p = length w\" )\n    assume LH : \"length p = length w\" show \"S ( p @ a # b # s )\"\n    proof -\n      have \"S ( a # [ b ] )\" by ( metis emptyS middl append_Nil)\n      moreover have \"w = p \\<and> v = s\" using EH LH by simp\n      ultimately have \"S ( p @ [ a , b ] @ s )\" using W V by ( metis doubl )\n      thus ?thesis by simp\n    qed\n\n    next\n    assume LD : \"length p \\<noteq> length w\" show \"S ( p @ a # b # s )\"\n    proof ( cases \"length p < length w\" )\n      assume LPLTLW : \"length p < length w\" show \"S ( p @ a # b # s )\" \n      proof -\n        have \"w = take ( length p ) w @ drop ( length p ) w\" using LPLTLW by simp\n        moreover have PS : \"p = take ( length p ) w \\<and>\n                              s = drop ( length p ) w @ v\"\n                                using EH LPLTLW by (metis append_eq_append_conv_if leD)\n        ultimately have \"w = p @ drop ( length p ) w\" by simp\n        hence \"S ( p @ a # b # drop ( length p ) w )\" using W  by metis\n        hence \"S ( ( p @ a # b # drop ( length p ) w ) @ v )\" using V by ( metis doubl )\n        thus \"S ( p @ a # b # s )\" using PS by simp\n      qed\n\n      next\n      assume LNL : \"\\<not> length p < length w\" show \"S ( p @ a # b # s )\"\n      proof -\n        have \"length p > length w\" using LD LNL by ( metis linorder_class.less_linear )\n        moreover hence \"length w = length ( take ( length w ) p )\" by simp\n        moreover have \"w @ v = take ( length w ) p @ drop ( length w ) p @ s\" using EH by simp\n        ultimately have \n          \"w = take ( length w ) p \\<and>\n            v = drop ( length w ) p @ s\" by ( metis append_eq_append_conv )\n        moreover hence \"S ( drop ( length w ) p @ a # b # s )\" using V by metis\n        ultimately have \"S ( take ( length w ) p @ drop ( length w ) p @ a # b # s )\"\n          using W by ( metis doubl )\n        thus ?thesis by ( metis append_take_drop_id  append_assoc )\n      qed\n    qed\n  qed\nqed\n\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n  \"balanced 0 [] = True\" |\n  \"balanced _ [] = False\" |\n  \"balanced 0 ( b # _ ) = False\" |\n  \"balanced n ( a # w ) = balanced ( Suc n ) w\" |\n  \"balanced ( Suc n ) ( b # w ) = balanced n w\"\n\nvalue \"balanced 1 [b]\"\n\nlemma \"balanced n w \\<Longrightarrow> S ( replicate n a @ w )\"\n  proof ( induction n w rule: balanced.induct )\n  assume \"balanced 0 []\" thus \"S ( replicate 0 a @ [] )\" using emptyS replicate_0 by auto\n\n  next\n  fix v assume\n    H : \"balanced ( Suc v ) []\"\n    show \"S ( replicate ( Suc v ) a @ [] )\"\n  proof -\n    have False using H by simp\n    thus ?thesis by metis\n  qed\n\n  next\n  fix as assume\n    H : \"balanced 0 ( b # as )\"\n    show \"S ( replicate 0 a @ b # as )\"\n  proof -\n    have False using H by simp\n    thus ?thesis by metis\n  qed\n\n  next\n  fix n w assume\n    IH : \"balanced ( Suc n ) w \\<Longrightarrow> S ( replicate ( Suc n ) a @ w )\" and\n    H  : \"balanced n ( a # w )\"\n    show \"S ( replicate n a @ a # w )\"\n  proof -\n    have \"balanced ( Suc n ) w\" using H by simp\n    hence \"S ( replicate ( Suc n ) a @ w )\" using IH by metis\n    hence \"S ( a # replicate n a @ w )\" by simp\n    thus ?thesis using replicate_app_Cons_same by metis\n  qed\n\n  next\n  fix n w assume\n    IH : \"balanced n w \\<Longrightarrow> S ( replicate n a @ w )\" and\n    H  : \"balanced ( Suc n ) ( b # w )\"\n    show \"S ( replicate ( Suc n ) a @ b # w )\"\n  proof -\n    have \"balanced n w\" using H by simp\n    hence \"S ( replicate n a @ w )\" using IH by metis\n    hence \"S ( replicate n a @ a # b # w )\" using ab_inter by metis\n    hence \"S ( ( replicate n a @ [ a ] ) @ b # w )\" by simp\n    hence \"S ( ( a # replicate n a ) @ b # w )\" by ( metis replicate_append_same )\n    thus ?thesis by simp\n  qed\nqed\n\nend", "meta": {"author": "tarc", "repo": "concrete-semantics-book", "sha": "68031292649bf4101455b655a34d6bcebeda2a27", "save_path": "github-repos/isabelle/tarc-concrete-semantics-book", "path": "github-repos/isabelle/tarc-concrete-semantics-book/concrete-semantics-book-68031292649bf4101455b655a34d6bcebeda2a27/Chap5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916064586998, "lm_q2_score": 0.8918110411247541, "lm_q1q2_score": 0.769982167454307}}
{"text": "theory AExp imports Main begin\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw{*\\snip{AExpaexpdef}{2}{1}{% *}\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw{*}%endsnip*}\n\ntext_raw{*\\snip{AExpavaldef}{1}{2}{% *}\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\ntext_raw{*}%endsnip*}\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext {* The same state more concisely: *}\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext {* A little syntax magic to write larger states compactly: *}\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\n*}\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext {* In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n*}\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext{* Note that this @{text\"<\\<dots>>\"} syntax works for any function space\n@{text\"\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\"} where @{text \"\\<tau>\\<^sub>2\"} has a @{text 0}. *}\n\n\nsubsection \"Constant Folding\"\n\ntext{* Evaluate constant subsexpressions: *}\n\ntext_raw{*\\snip{AExpasimpconstdef}{0}{2}{% *}\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext{* Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors: *}\n\ntext_raw{*\\snip{AExpplusdef}{0}{2}{% *}\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw{*\\snip{AExpasimpdef}{2}{0}{% *}\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntext{* Note that in @{const asimp_const} the optimized constructor was\ninlined. Making it a separate function @{const plus} improves modularity of\nthe code and the proofs. *}\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend", "meta": {"author": "user7", "repo": "concrete-semantics", "sha": "5ddbd752550b3037d0d461d67a39d4f61c4548e5", "save_path": "github-repos/isabelle/user7-concrete-semantics", "path": "github-repos/isabelle/user7-concrete-semantics/concrete-semantics-5ddbd752550b3037d0d461d67a39d4f61c4548e5/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8791467548438124, "lm_q1q2_score": 0.7699452859412946}}
{"text": "(* License: LGPL *)\n(*\nAuthor: Julian Parsert <julian.parsert@gmail.com>\nAuthor: Cezary Kaliszyk\n*)\n\n\nsection \\<open> Utility Functions \\<close>\n\ntext \\<open> Utility functions and results involving them. \\<close>\n\ntheory Utility_Functions\n  imports\n    Preferences\nbegin\n\n\nsubsection \"Ordinal utility functions\"\n\ntext \\<open> Ordinal utility function locale \\<close>\n\nlocale ordinal_utility =\n  fixes carrier :: \"'a set\"\n  fixes relation :: \"'a relation\"\n  fixes u :: \"'a \\<Rightarrow> real\"\n  assumes util_def[iff]: \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> x \\<succeq>[relation] y \\<longleftrightarrow> u x \\<ge> u y\"\n  assumes not_outside: \"x \\<succeq>[relation] y \\<Longrightarrow> x \\<in> carrier\"\n    and \"x \\<succeq>[relation] y \\<Longrightarrow> y \\<in> carrier\"\nbegin\n\nlemma util_def_conf: \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> u x \\<ge> u y \\<longleftrightarrow> x \\<succeq>[relation] y\"\n  using util_def by blast\n\nlemma relation_subset_crossp:\n  \"relation \\<subseteq> carrier \\<times> carrier\"\nproof\n  fix x\n  assume \"x \\<in> relation\"\n  have \"\\<forall>(a,b) \\<in> relation. a \\<in> carrier \\<and> b \\<in> carrier\"\n    by (metis (no_types, lifting) case_prod_conv ordinal_utility_axioms ordinal_utility_def surj_pair)\n  then show \"x \\<in> carrier \\<times> carrier\"\n    using \\<open>x \\<in> relation\\<close> by auto\nqed\n\ntext \\<open> Utility function implies totality of relation \\<close>\nlemma util_imp_total: \"total_on carrier relation\"\nproof\n  fix x and y\n  assume x_inc: \"x \\<in> carrier\" and y_inc : \"y \\<in> carrier\"\n  have fst : \"u x \\<ge> u y \\<or> u y \\<ge> u x\"\n    using util_def by auto\n  then show  \"x \\<succeq>[relation] y \\<or> y \\<succeq>[relation] x\"\n    by (simp add: x_inc y_inc)\nqed\n\nlemma x_y_in_carrier: \"x \\<succeq>[relation] y \\<Longrightarrow> x \\<in> carrier \\<and> y \\<in> carrier\"\n  by (meson ordinal_utility_axioms ordinal_utility_def)\n\ntext \\<open> Utility function implies transitivity of relation. \\<close>\n\nlemma util_imp_trans: \"trans relation\"\nproof (rule transI)\n  fix x and y and z\n  assume x_y: \"x \\<succeq>[relation] y\"\n  assume y_z: \"y \\<succeq>[relation] z\"\n  have x_ge_y: \"x \\<succeq>[relation] y\"\n    using x_y by auto\n  then have x_y: \"u x \\<ge> u y\"\n    by (meson x_y_in_carrier ordinal_utility_axioms util_def x_y)\n  have \"u y \\<ge> u z\"\n    by (meson y_z ordinal_utility_axioms ordinal_utility_def)\n  have \"x \\<in> carrier\"\n    using x_y_in_carrier[of x y] x_ge_y  by simp\n  then have \"u x \\<ge> u z\"\n    using \\<open>u z \\<le> u y\\<close> order_trans x_y by blast\n  hence \"x \\<succeq>[relation] z\"\n    by (meson \\<open>x \\<in> carrier\\<close> ordinal_utility_axioms ordinal_utility_def y_z)\n  then show \"x \\<succeq>[relation] z\" .\nqed\n\nlemma util_imp_refl: \"refl_on carrier relation\"\n  by (simp add: refl_on_def relation_subset_crossp)\n\nlemma affine_trans_is_u:\n  shows \"\\<forall>\\<alpha>>0. (\\<forall>\\<beta>. ordinal_utility  carrier relation (\\<lambda>x. u(x)*\\<alpha> + \\<beta>))\"\nproof (rule allI, rule impI, rule allI)\n  fix \\<alpha>::real and \\<beta>\n  assume *:\"\\<alpha> > 0\"\n  show \"ordinal_utility carrier relation (\\<lambda>x. u x * \\<alpha> + \\<beta>)\"\n  proof (subst ordinal_utility_def, rule conjI, goal_cases)\n    case 1\n    then show ?case\n      by (metis * add.commute add_le_cancel_left not_le real_mult_less_iff1 util_def_conf)\n  next\n    case 2\n    then show ?case \n      by (meson refl_on_domain util_imp_refl)\n  qed\nqed\n\ntext \\<open> This utility function definition is ordinal.\n        Hence they are only unique up to a monotone transformation. \\<close>\n\nlemma ordinality_of_utility_function :\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes monot: \"monotone (>) (>) f\"\n  shows \"(f \\<circ> u) x > (f \\<circ> u) y \\<longleftrightarrow> u x > u y\"\nproof -\n  let ?func = \"(\\<lambda>x. f(u x))\"\n  have \"\\<forall>m n . u m \\<ge> u n \\<longleftrightarrow> ?func m \\<ge> ?func n\"\n    by (metis le_less monot monotone_def not_less)\n  hence \"u x > u y \\<longleftrightarrow> ?func x > ?func y\"\n    using not_le by blast\n  thus ?thesis  by auto\nqed\n\ncorollary utility_prefs_corresp :\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes monotonicity : \"monotone (>) (>) f\"\n  shows \"\\<forall>x\\<in>carrier. \\<forall>y\\<in>carrier. (x,y) \\<in> relation \\<longleftrightarrow> (f \\<circ> u) x \\<ge> (f \\<circ> u) y\"\n  by (meson monotonicity not_less ordinality_of_utility_function util_def_conf)\n\ncorollary monotone_comp_is_utility:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes monot: \"monotone (>) (>) f\"\n  shows \"ordinal_utility carrier relation (f \\<circ> u)\"\nproof (rule ordinal_utility.intro, goal_cases)\ncase (1 x y)\n  then show ?case\n    using monot utility_prefs_corresp by blast\nnext\n  case (2 x y)\n  then show ?case\n    using not_outside by blast\nnext\n  case (3 x y)\n  then show ?case\n    using x_y_in_carrier by blast\nqed\n\nlemma ordinal_utility_left:\n  assumes \"x \\<succeq>[relation] y\"\n  shows \"u x \\<ge> u y\"\n  using assms x_y_in_carrier by blast\n\nlemma add_right:\n  assumes \"\\<And>x y. x \\<succeq>[relation] y \\<Longrightarrow> f x \\<ge> f y\"\n  shows   \"ordinal_utility carrier relation (\\<lambda>x. u x + f x)\"\nproof (rule ordinal_utility.intro, goal_cases)\n  case (1 x y)\n  assume xy: \"x \\<in> carrier\" \"y \\<in> carrier\"\n  then show ?case\n  proof -\n    have \"u x \\<le> u y \\<longrightarrow> (\\<exists>r. ((x, y) \\<notin> relation \\<and> \\<not> r \\<le> u x + f x) \\<and> r \\<le> u y + f y) \\<or> u y \\<le> u x\"\n      by (metis (no_types) add_le_cancel_left add_le_cancel_right assms util_def xy(1) xy(2))\n    moreover show ?thesis\n      by (meson add_mono assms calculation le_cases order_trans util_def xy(1) xy(2))\n  qed\nnext\n  case (2 x y)\n  then show ?case\n    using not_outside by blast\nnext\n  case (3 x y)\n  then show ?case\n    using x_y_in_carrier by blast\nqed\n\nlemma add_left:\n  assumes \"\\<And>x y. x \\<succeq>[relation] y \\<Longrightarrow> f x \\<ge> f y\"\n  shows \"ordinal_utility carrier relation (\\<lambda>x. f x + u x)\"\nproof -\n  have \"ordinal_utility carrier relation (\\<lambda>x. u x + f x)\"\n    by (simp add: add_right assms)\n  thus ?thesis using Groups.ab_semigroup_add_class.add.commute\n    by (simp add: add.commute)\nqed\n\n\nlemma ordinal_utility_scale_transl:\n  assumes \"(c::real) > 0\"\n  shows \"ordinal_utility carrier relation (\\<lambda>x. c * (u x) + d)\"\nproof -\n  have \"monotone (>) (>) (\\<lambda>x. c * x + d)\" (is \"monotone (>) (>) ?fn\" )\n    by (simp add: assms monotone_def)\n  with monotone_comp_is_utility have \"ordinal_utility carrier relation (?fn \\<circ> u)\"\n    by blast\n  moreover have \"?fn \\<circ> u =  (\\<lambda>x. c * (u x) + d)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma strict_prefernce_iff_strict_utility:\n  assumes \"x \\<in> carrier\"\n  assumes \"y \\<in> carrier\"\n  shows \"x \\<succ>[relation] y \\<longleftrightarrow> u x > u y\"\n  by (meson assms(1) assms(2) less_eq_real_def not_less util_def)\n\nend\n\ntext \\<open> A utility function implies a rational preference relation.\n      Hence a utility function contains exactly the same amount of information as a RPR \\<close>\n\nsublocale ordinal_utility \\<subseteq> rational_preference carrier relation\nproof\n  fix x and y\n  assume xy: \"x \\<succeq>[relation] y\"\n  then show \"x \\<in> carrier\"\n    and \"y \\<in> carrier\"\n    using not_outside by (simp)\n      (meson xy refl_onD2 util_imp_refl)\nnext\n  show \"preorder_on carrier relation\"\n  proof-\n    have \"trans relation\" using util_imp_trans by auto\n    then have \"preorder_on carrier relation\"\n      by (simp add: preorder_on_def util_imp_refl)\n    then show ?thesis .\n  qed\nnext\n  show \"total_on carrier relation\"\n    by (simp add: util_imp_total)\nqed\n\n\ntext \\<open> Given a finite carrier set. We can guarantee that given a rational preference\n       relation, there must also exist a utility function representing this relation.\n       Construction of witness roughly follows from.\\<close>\n\ntheorem fnt_carrier_exists_util_fun:\n  assumes \"finite carrier\"\n  assumes \"rational_preference carrier relation\"\n  shows \"\\<exists>u. ordinal_utility carrier relation u\"\nproof-\n  define f where\n    f: \"f = (\\<lambda>x. card (no_better_than x carrier relation))\"\n  have \"ordinal_utility carrier relation f\"\n  proof\n    fix x y\n    assume x_c: \"x \\<in> carrier\"\n    assume y_c: \"y \\<in> carrier\"\n    show \"x \\<succeq>[relation] y \\<longleftrightarrow> (real (f y) \\<le> real (f x))\"\n    proof\n      assume asm: \"x \\<succeq>[relation] y\"\n      define yn where\n        yn: \"yn = no_better_than y carrier relation\"\n      define xn where\n        xn: \"xn = no_better_than x carrier relation\"\n      then have \"yn \\<subseteq> xn\"\n        by (simp add: asm yn assms(2) rational_preference.no_better_subset_pref)\n      then have \"card yn \\<le> card xn\"\n        by (simp add: x_c y_c asm assms(1) assms(2) rational_preference.card_leq_pref xn yn)\n      then show \"(real (f y) \\<le> real (f x))\"\n        using  f xn yn by simp\n    next\n      assume \"real (f y) \\<le> real (f x)\"\n      then show \"x \\<succeq>[relation] y\"\n        using assms(1) assms(2) f rational_preference.card_leq_pref x_c y_c by fastforce\n    qed\n  next\n    fix x y\n    assume asm: \"x \\<succeq>[relation] y\"\n    show \"x \\<in> carrier\"\n      by (meson asm assms(2) preference.not_outside rational_preference.axioms(1))\n    show \"y \\<in> carrier\"\n      by (meson asm assms(2) preference_def rational_preference_def)\n  qed\n  then show ?thesis\n    by blast\nqed\n\ncorollary obt_u_fnt_carrier:\n  assumes \"finite carrier\"\n  assumes \"rational_preference carrier relation\"\n  obtains u where \"ordinal_utility carrier relation u\"\n  using assms(1) assms(2) fnt_carrier_exists_util_fun by blast\n\ntheorem ordinal_util_imp_rat_prefs:\n  assumes \"ordinal_utility carrier relation u\"\n  shows \"rational_preference carrier relation\"\n  by (metis (full_types) assms order_on_defs(1) ordinal_utility.util_imp_refl \n      ordinal_utility.util_imp_total ordinal_utility.util_imp_trans ordinal_utility_def \n      preference.intro rational_preference.intro rational_preference_axioms_def)\n\nsubsection \\<open> Utility function on  Euclidean Space \\<close>\n\nlocale eucl_ordinal_utility = ordinal_utility carrier relation u\n  for carrier :: \"('a::euclidean_space) set\"\n  and relation :: \"'a relation\"\n  and u :: \"'a \\<Rightarrow> real\"\n\nsublocale eucl_ordinal_utility \\<subseteq> rational_preference carrier relation\n  using rational_preference_axioms by blast\n\n\nlemma ord_eucl_utility_imp_rpr: \"eucl_ordinal_utility s rel u \\<longrightarrow> real_vector_rpr s rel\"\n  using eucl_ordinal_utility.axioms ordinal_util_imp_rat_prefs real_vector_rpr.intro by blast\n\ncontext eucl_ordinal_utility\nbegin\n\ntext \\<open> Local non-satiation on utility functions \\<close>\n\nlemma lns_pref_lns_util [iff]:\n  \"local_nonsatiation carrier relation \\<longleftrightarrow>\n  (\\<forall>x\\<in>carrier. \\<forall>e > 0. \\<exists>y\\<in>carrier.\n  norm (y - x) \\<le> e \\<and> u y > u x)\" (is \"_ \\<longleftrightarrow> ?alt\")\nproof\n  assume lns: \"local_nonsatiation carrier relation\"\n  have \"\\<forall>a b. a \\<succ> b \\<longrightarrow> u a > u b\"\n    by (metis less_eq_real_def util_def x_y_in_carrier)\n  then show \"?alt\"\n    by (meson lns local_nonsatiation_def)\nnext\n  assume lns: \"?alt\"\n  show \"local_nonsatiation carrier relation\"\n  proof(rule lns_normI)\n    fix x and e::real\n    assume x_in: \"x \\<in> carrier\"\n    assume e: \"e > 0\"\n    have \"\\<forall>x \\<in> carrier. \\<forall>e>0. \\<exists>y\\<in>carrier. norm (y - x) \\<le> e \\<and> y \\<succ> x\"\n      by (meson less_eq_real_def linorder_not_less lns util_def)\n    have \"\\<exists>y\\<in>carrier. norm (y - x) \\<le> e \\<and> u y > u x\"\n      using e x_in lns by blast\n    then show \"\\<exists>y\\<in>carrier. norm (y - x) \\<le> e \\<and> y \\<succ> x\"\n      by (meson compl not_less util_def x_in)\n  qed\nqed\n\nend\n\nlemma finite_carrier_rpr_iff_u:\n  assumes \"finite carrier\"\n    and \"(relation::'a relation) \\<subseteq> carrier \\<times> carrier\"\n  shows \"rational_preference carrier relation \\<longleftrightarrow> (\\<exists>u. ordinal_utility carrier relation u)\"\nproof\n  assume \"rational_preference carrier relation\" \n  then show \"\\<exists>u. ordinal_utility carrier relation u\"\n    by (simp add: assms(1) fnt_carrier_exists_util_fun)\nnext\n  assume \"\\<exists>u. ordinal_utility carrier relation u\"\n  then show \"rational_preference carrier relation\" \n    by (metis (full_types) order_on_defs(1) ordinal_utility.util_imp_refl \n        ordinal_utility.util_imp_total ordinal_utility.util_imp_trans ordinal_utility_def \n        preference.intro rational_preference_axioms_def rational_preference_def)\nqed\n\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/First_Welfare_Theorem/Utility_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7698846801302692}}
{"text": "(*\n\nFormalization of Many-Valued Logics - Isabelle Partiality.thy\n\nAnders Schlichtkrull & Jørgen Villadsen, DTU Compute, Denmark\n\n*)\n\ntheory Partiality imports Main begin\n\nsection \\<open>Syntax and Semantics\\<close>\n\ntext \\<open>Syntax of propositional logic with strings as identifiers in atomic formulas\\<close>\n\ntype_synonym id = string\n\ndatatype fm = Pro id | Truth | Neg' fm | Con fm fm | Eql fm fm | Eql' fm fm\n\ntext \\<open>Semantics of propositional logic with determinate and indeterminate truth values\\<close>\n\ndatatype tv = Det bool | is_indet: Indet (get_indet: nat)\n\nabbreviation (input)\n  \"eval_neg p \\<equiv>\n    (\n      case p of\n        Det False \\<Rightarrow> Det True |\n        Det True \\<Rightarrow> Det False |\n        Indet n \\<Rightarrow> Indet n\n    )\"\n\nfun\n  eval :: \"(id \\<Rightarrow> tv) \\<Rightarrow> fm \\<Rightarrow> tv\"\nwhere\n  \"eval i (Pro s) = i s\" |\n  \"eval i Truth = Det True\" |\n  \"eval i (Neg' p) = eval_neg (eval i p)\" |\n  \"eval i (Con p q) =\n    (\n      if eval i p = eval i q then eval i p else\n      if eval i p = Det True then eval i q else\n      if eval i q = Det True then eval i p else Det False\n    )\" |\n  \"eval i (Eql p q) =\n    (\n      if eval i p = eval i q then Det True else Det False\n    )\" |\n  \"eval i (Eql' p q) =\n    (\n      if eval i p = eval i q then Det True else\n        (\n          case (eval i p, eval i q) of\n            (Det True, _) \\<Rightarrow> eval i q |\n            (_, Det True) \\<Rightarrow> eval i p |\n            (Det False, _) \\<Rightarrow> eval_neg (eval i q) |\n            (_, Det False) \\<Rightarrow> eval_neg (eval i p) |\n            _ \\<Rightarrow> Det False\n        )\n    )\"\n\ntext \\<open>Proofs of key properties\\<close>\n\nproposition \"eval i (Eql p q) = Det (eval i p = eval i q)\"\n  by simp\n\ntheorem eval_negation:\n  \"eval i (Neg' p) =\n    (\n      if eval i p = Det False then Det True else\n      if eval i p = Det True then Det False else\n      eval i p\n    )\"\n  by (cases \"eval i p\") simp_all\n\ntheorem eval_equality:\n  \"eval i (Eql' p q) =\n    (\n      if eval i p = eval i q then Det True else\n      if eval i p = Det True then eval i q else\n      if eval i q = Det True then eval i p else\n      if eval i p = Det False then eval i (Neg' q) else\n      if eval i q = Det False then eval i (Neg' p) else\n      Det False\n    )\"\n  by (cases \"eval i p\"; cases \"eval i q\") simp_all\n\ntext \\<open>Additional operators\\<close>\n\nabbreviation \"Falsity \\<equiv> Neg' Truth\"\n\nabbreviation \"Dis p q \\<equiv> Neg' (Con (Neg' p) (Neg' q))\"\n\nabbreviation \"Imp p q \\<equiv> Eql p (Con p q)\"\n\nabbreviation \"Imp' p q \\<equiv> Eql' p (Con p q)\"\n\nabbreviation \"Box p \\<equiv> (Eql p Truth)\"\n\nabbreviation \"Neg p \\<equiv> Neg' (Box p)\"\n\ntext \\<open>Validity\\<close>\n\ndefinition\n  valid :: \"fm \\<Rightarrow> bool\"\nwhere\n  \"valid p \\<equiv> \\<forall>i. eval i p = Det True\"\n\ntext \\<open>Key equalities\\<close>\n\nproposition \"valid (Eql p (Neg' (Neg' p)))\"\n  unfolding valid_def\n  using eval_negation\n  by simp\n\nproposition \"valid (Eql Truth (Neg' Falsity))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql Falsity (Neg' Truth))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql p (Con p p))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql p (Con Truth p))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql p (Con p Truth))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql Truth (Eql' p p))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql p (Eql' Truth p))\"\n  unfolding valid_def\n  by simp\n\nproposition \"valid (Eql p (Eql' p Truth))\"\n  unfolding valid_def\nproof\n  fix i\n  show \"eval i (Eql p (Eql' p Truth)) = Det True\"\n    by (cases \"eval i p\") simp_all\nqed\n\nproposition \"valid (Eql (Neg' p) (Eql' Falsity p))\"\n  unfolding valid_def\nproof\n  fix i\n  show \"eval i (Eql (Neg' p) (Eql' (Neg' Truth) p)) = Det True\"\n    by (cases \"eval i p\") simp_all\nqed\n\nproposition \"valid (Eql (Neg' p) (Eql' p Falsity))\"\n  unfolding valid_def\n  using eval.simps eval_equality eval_negation\n  by metis\n\ntext \\<open>Selected theorems\\<close>\n\ntheorem double_negation: \"valid (Neg' (Neg' p)) \\<longleftrightarrow> valid p\"\n  unfolding valid_def\n  using eval_negation\n  by auto\n\ntheorem conjunction: \"valid (Con p q) \\<longleftrightarrow> valid p \\<and> valid q\"\n  unfolding valid_def\n  by auto\n\ncorollary \"valid (Con p q) \\<Longrightarrow> valid p\"\n  using conjunction\n  by simp\n\ncorollary \"valid (Con p q) \\<Longrightarrow> valid q\"\n  using conjunction\n  by simp\n\nproposition \"valid p \\<Longrightarrow> valid (Imp p q) \\<Longrightarrow> valid q\"\n  unfolding valid_def\n  using eval.simps tv.inject\n  by (metis (full_types))\n\nproposition \"valid p \\<Longrightarrow> valid (Imp' p q) \\<Longrightarrow> valid q\"\n  unfolding valid_def\n  using eval.simps eval_equality\n  by (metis (full_types))\n\nsection \\<open>Truth Tables\\<close>\n\ndefinition\n  tv_pair_row :: \"tv list \\<Rightarrow> tv \\<Rightarrow> (tv * tv) list\"\nwhere\n  \"tv_pair_row tvs tv = map (\\<lambda>x. (tv, x)) tvs\"\n\ndefinition\n  tv_pair_table :: \"tv list \\<Rightarrow> (tv * tv) list list\"\nwhere\n  \"tv_pair_table tvs \\<equiv> map (tv_pair_row tvs) tvs\"\n\ndefinition\n  map_row :: \"(tv \\<Rightarrow> tv \\<Rightarrow> tv) \\<Rightarrow> (tv * tv) list \\<Rightarrow> tv list\"\nwhere\n  \"map_row f tvtvs = map (\\<lambda>(x,y). f x y) tvtvs\"\n\ndefinition\n  map_table :: \"(tv \\<Rightarrow> tv \\<Rightarrow> tv) \\<Rightarrow> (tv * tv) list list \\<Rightarrow> tv list list\"\nwhere\n  \"map_table f tvtvss = map (map_row f) tvtvss\"\n\ndefinition\n  unary_truth_table :: \"fm \\<Rightarrow> tv list \\<Rightarrow> tv list\"\nwhere\n  \"unary_truth_table p tvs =\n      map (\\<lambda>x. eval ((\\<lambda>x. Det undefined)(''p'' := x)) p) tvs\"\n\ndefinition\n  binary_truth_table :: \"fm \\<Rightarrow> tv list \\<Rightarrow> tv list list\"\nwhere\n  \"binary_truth_table p tvs =\n      map_table (\\<lambda>x y. eval ((\\<lambda>x. Det undefined)(''p'' := x, ''q'' := y)) p)\n          (tv_pair_table tvs)\"\n\nfun\n  string_of_nat :: \"nat \\<Rightarrow> string\"\nwhere\n  \"string_of_nat n = (if n < 10 then [char_of_nat (48 + n)] else\n      string_of_nat (n div 10) @ [char_of_nat (48 + (n mod 10))])\"\n\nfun\n  string_tv :: \"tv \\<Rightarrow> string\"\nwhere\n  \"string_tv (Det True) = ''*'' \" |\n  \"string_tv (Det False) = ''o'' \" |\n  \"string_tv (Indet n) = string_of_nat n\"\n\ndefinition\n  appends :: \"string list \\<Rightarrow> string\"\nwhere\n  \"appends strs = foldr append strs []\"\n\ndefinition\n  appends_nl :: \"string list \\<Rightarrow> string\"\nwhere\n  \"appends_nl strs = ''\\<newline>  '' @\n      foldr (\\<lambda>x y. x @ ''\\<newline>  '' @ y) (butlast strs) (last strs) @ ''\\<newline>''\"\n\ndefinition\n  string_table :: \"tv list list \\<Rightarrow> string list list\"\nwhere\n  \"string_table tvss = map (map string_tv) tvss\"\n\ndefinition\n  string_table_string :: \"string list list \\<Rightarrow> string\"\nwhere\n  \"string_table_string strss = appends_nl (map appends strss)\"\n\ndefinition\n  unary :: \"fm \\<Rightarrow> tv list \\<Rightarrow> string\"\nwhere\n  \"unary p tvs = appends_nl (map string_tv (unary_truth_table p tvs))\"\n\ndefinition\n  binary :: \"fm \\<Rightarrow> tv list \\<Rightarrow> string\"\nwhere\n  \"binary p tvs = string_table_string (string_table (binary_truth_table p tvs))\"\n\nproposition\n  \"binary (Con (Pro ''p'') (Pro ''q''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  *o12\n  oooo\n  1o1o\n  2oo2\n'' \"\n  by code_simp\n\nproposition\n  \"binary (Dis (Pro ''p'') (Pro ''q''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  ****\n  *o12\n  *11*\n  *2*2\n'' \"\n  by code_simp\n\nproposition\n  \"unary (Neg' (Pro ''p''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  o\n  *\n  1\n  2\n'' \"\n  by code_simp\n\nproposition\n  \"binary (Eql (Pro ''p'') (Pro ''q''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  *ooo\n  o*oo\n  oo*o\n  ooo*\n'' \"\n  by code_simp\n\nproposition\n  \"binary (Imp (Pro ''p'') (Pro ''q''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  *ooo\n  ****\n  *o*o\n  *oo*\n'' \"\n  by code_simp\n\nproposition\n  \"unary (Box (Pro ''p''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  *\n  o\n  o\n  o\n'' \"\n  by code_simp\n\nproposition\n  \"binary (Eql' (Pro ''p'') (Pro ''q''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  *o12\n  o*12\n  11*o\n  22o*\n'' \"\n  by code_simp\n\nproposition\n  \"binary (Imp' (Pro ''p'') (Pro ''q''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  *o12\n  ****\n  *1*1\n  *22*\n'' \"\n  by code_simp\n\nproposition\n  \"unary (Neg (Pro ''p''))\n      [Det True, Det False, Indet 1, Indet 2] = ''\n  o\n  *\n  *\n  *\n'' \"\n  by code_simp\n\nsection \\<open>Smaller Domains and Paraconsistency\\<close>\n\ndefinition\n  domain :: \"nat set \\<Rightarrow> tv set\"\nwhere\n  \"domain U \\<equiv> {Det True, Det False} \\<union> Indet ` U\"\n\ntheorem universal_domain: \"domain {n. True} = {x. True}\"\nproof -\n  have \"\\<forall>x. x = Det True \\<or> x = Det False \\<or> x \\<in> range Indet\"\n    using range_eqI tv.collapse tv.inject\n    by metis\n  then show ?thesis\n    unfolding domain_def\n    by blast\nqed\n\ndefinition\n  valid_in :: \"nat set \\<Rightarrow> fm \\<Rightarrow> bool\"\nwhere\n  \"valid_in U p \\<equiv> \\<forall>i. range i \\<subseteq> domain U \\<longrightarrow> eval i p = Det True\"\n\nproposition \"valid p \\<longleftrightarrow> valid_in {n. True} p\"\n  unfolding valid_def valid_in_def\n  using universal_domain\n  by simp\n\ntheorem double_negation_in: \"valid_in U (Neg' (Neg' p)) \\<longleftrightarrow> valid_in U p\"\n  unfolding valid_in_def\n  using eval_negation\n  by auto\n\ntheorem conjunction_in: \"valid_in U (Con p q) \\<longleftrightarrow> valid_in U p \\<and> valid_in U q\"\n  unfolding valid_in_def\n  by auto\n\ncorollary \"valid_in U (Con p q) \\<Longrightarrow> valid_in U p\"\n  using conjunction_in\n  by simp\n\ncorollary \"valid_in U (Con p q) \\<Longrightarrow> valid_in U q\"\n  using conjunction_in\n  by simp\n\nproposition \"valid_in U p \\<Longrightarrow> valid_in U (Imp p q) \\<Longrightarrow> valid_in U q\"\n  unfolding valid_in_def\n  using eval.simps tv.inject\n  by (metis (full_types))\n\nproposition \"valid_in U p \\<Longrightarrow> valid_in U (Imp' p q) \\<Longrightarrow> valid_in U q\"\n  unfolding valid_in_def\n  using eval.simps eval_equality\n  by (metis (full_types))\n\nlemma paraconsistency:\n  \"\\<not> valid_in {1} (Imp' (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q''))\"\nproof -\n  let ?i = \"(\\<lambda>s. Det False)(''P'' := Indet 1, ''Q'' := Det False)\"\n  have \"range ?i \\<subseteq> domain {1}\"\n    unfolding domain_def\n    by auto\n  moreover have \"eval ?i (Imp' (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q'')) = Indet 1\"\n    by simp\n  moreover have \"Indet 1 \\<noteq> Det True\"\n    by simp\n  ultimately show ?thesis\n    unfolding valid_in_def\n    by metis\nqed\n\ntheorem transfer: \"\\<not> valid_in U p \\<Longrightarrow> \\<not> valid p\"\n  unfolding valid_in_def valid_def\n  by metis\n\nproposition \"\\<not> valid (Imp' (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q''))\"\n  using paraconsistency transfer\n  by simp\n\nproposition \"\\<not> valid (Imp (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q''))\"\n  using paraconsistency transfer eval.simps tv.simps\n  unfolding valid_in_def\n  (* by smt OK *)\nproof -\n  assume *: \"\\<not> (\\<forall>i. range i \\<subseteq> domain U \\<longrightarrow> eval i p = Det True) \\<Longrightarrow> \\<not> valid p\" for U p\n  assume \"\\<not> (\\<forall>i. range i \\<subseteq> domain {1} \\<longrightarrow>\n      eval i (Imp' (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q'')) = Det True)\"\n  then obtain i where\n    **: \"range i \\<subseteq> domain {1} \\<and>\n        eval i (Imp' (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q'')) \\<noteq> Det True\"\n    by blast\n  then have \"eval i (Con (Pro ''P'') (Neg' (Pro ''P''))) \\<noteq>\n      eval i (Con (Con (Pro ''P'') (Neg' (Pro ''P''))) (Pro ''Q''))\"\n    by force\n  then show ?thesis\n    using * **\n    by force\nqed\n\nsection \\<open>Example: Contraposition\\<close>\n\nabbreviation (input)\n  \"contrapos P Q \\<equiv> Eql' (Imp' P Q) (Imp' (Neg' Q) (Neg' P))\"\n\nproposition \"valid_in {} (contrapos (Pro ''P'') (Pro ''Q''))\"\n  unfolding valid_in_def\nproof (rule; rule)\n  fix i :: \"id \\<Rightarrow> tv\"\n  assume \"range i \\<subseteq> domain {}\"\n  then have\n      \"i ''P'' \\<in> {Det True, Det False}\"\n      \"i ''Q'' \\<in> {Det True, Det False}\"\n    unfolding domain_def\n    by auto\n  then show \"eval i (contrapos (Pro ''P'') (Pro ''Q'')) = Det True\"\n    by (cases \"i ''P''\"; cases \"i ''Q''\") auto\nqed\n\nproposition \"valid_in {1} (contrapos (Pro ''P'') (Pro ''Q''))\"\n  unfolding valid_in_def\nproof (rule; rule)\n  fix i :: \"id \\<Rightarrow> tv\"\n  assume \"range i \\<subseteq> domain {1}\"\n  then have\n      \"i ''P'' \\<in> {Det True, Det False, Indet 1}\"\n      \"i ''Q'' \\<in> {Det True, Det False, Indet 1}\"\n    unfolding domain_def\n    by auto\n  then show \"eval i (contrapos (Pro ''P'') (Pro ''Q'')) = Det True\"\n    by (cases \"i ''P''\"; cases \"i ''Q''\") auto\nqed\n\nproposition \"\\<not> valid_in {1,2} (contrapos (Pro ''P'') (Pro ''Q''))\"\nproof -\n  let ?i = \"(\\<lambda>s. Det False)(''P'' := Indet 1, ''Q'' := Indet 2)\"\n  have \"range ?i \\<subseteq> domain {1, 2}\"\n    unfolding domain_def\n    by auto\n  moreover have \"eval ?i (contrapos (Pro ''P'') (Pro ''Q'')) = Det False\"\n    by simp\n  moreover have \"Det False \\<noteq> Det True\"\n    by simp\n  ultimately show ?thesis\n    unfolding valid_in_def\n    by metis\nqed\n\nsection \\<open>Four Truth Values Are Not Enough\\<close>\n\nabbreviation (input)\n  \"ternary P Q R \\<equiv>\n      Imp' (Neg' (Imp' Q P))\n          (Imp' (Neg' (Dis (Neg' R) (Imp' R Q))) (Imp' P Q))\"\n\nproposition \"valid_in {} (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R''))\"\n  unfolding valid_in_def\nproof (rule; rule)\n  fix i :: \"id \\<Rightarrow> tv\"\n  assume \"range i \\<subseteq> domain {}\"\n  then have\n      \"i ''P'' \\<in> {Det True, Det False}\"\n      \"i ''Q'' \\<in> {Det True, Det False}\"\n      \"i ''R'' \\<in> {Det True, Det False}\"\n    unfolding domain_def\n    by auto\n  then show \"eval i (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R'')) = Det True\"\n    by (cases \"i ''P''\"; cases \"i ''Q''\"; cases \"i ''R''\") auto\nqed\n\nproposition \"valid_in {1} (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R''))\"\n  unfolding valid_in_def\nproof (rule; rule)\n  fix i :: \"id \\<Rightarrow> tv\"\n  assume \"range i \\<subseteq> domain {1}\"\n  then have\n      \"i ''P'' \\<in> {Det True, Det False, Indet 1}\"\n      \"i ''Q'' \\<in> {Det True, Det False, Indet 1}\"\n      \"i ''R'' \\<in> {Det True, Det False, Indet 1}\"\n    unfolding domain_def\n    by auto\n  then show \"eval i (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R'')) = Det True\"\n    by (cases \"i ''P''\"; cases \"i ''Q''\"; cases \"i ''R''\") auto\nqed\n\nproposition \"valid_in {1,2} (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R''))\"\n  unfolding valid_in_def\nproof (rule; rule)\n  fix i :: \"id \\<Rightarrow> tv\"\n  assume \"range i \\<subseteq> domain {1,2}\"\n  then have\n      \"i ''P'' \\<in> {Det True, Det False, Indet 1, Indet 2}\"\n      \"i ''Q'' \\<in> {Det True, Det False, Indet 1, Indet 2}\"\n      \"i ''R'' \\<in> {Det True, Det False, Indet 1, Indet 2}\"\n    unfolding domain_def\n    by auto\n  then show \"eval i (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R'')) = Det True\"\n    by (cases \"i ''P''\"; cases \"i ''Q''\"; cases \"i ''R''\") auto\nqed\n\nproposition \"\\<not> valid_in {1,2,3} (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R''))\"\nproof -\n  let ?i = \"(\\<lambda>s. Det False)(''P'' := Indet 2, ''Q'' := Indet 1, ''R'' := Indet 3)\"\n  have \"range ?i \\<subseteq> domain {1, 2, 3}\"\n    unfolding domain_def\n    by auto\n  moreover have \"eval ?i (ternary (Pro ''P'') (Pro ''Q'') (Pro ''R'')) = Indet 1\"\n    by simp\n  moreover have \"Indet 1 \\<noteq> Det True\"\n    by simp\n  ultimately show ?thesis\n    unfolding valid_in_def\n    by metis\nqed\n\nsection \\<open>Meta-Theorems\\<close>\n\ntheorem valid_valid_in:\n  assumes \"valid p\"\n  shows \"valid_in U p\"\n  using assms transfer\n  by blast\n\nfun\n  props :: \"fm \\<Rightarrow> id set\"\nwhere\n  \"props Truth = {}\" |\n  \"props (Pro s) = {s}\" |\n  \"props (Neg' p) = props p\" |\n  \"props (Con p q) = props p \\<union> props q\" |\n  \"props (Eql p q) = props p \\<union> props q\" |\n  \"props (Eql' p q) = props p \\<union> props q\"\n\nlemma relevant_props:\n  assumes \"\\<forall>s \\<in> props p. i1 s = i2 s\"\n  shows \"eval i1 p = eval i2 p\"\n  using assms\n  by (induct p) (simp_all, metis)\n\nfun\n  change_tv :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> tv \\<Rightarrow> tv\"\nwhere\n  \"change_tv f (Det b) = Det b\" |\n  \"change_tv f (Indet n) = Indet (f n)\"\n\nlemma change_tv_injection:\n  assumes \"inj f\"\n  shows \"inj (change_tv f)\"\nproof -\n  {\n    fix tv1 tv2\n    have \"inj f \\<Longrightarrow> change_tv f tv1 = change_tv f tv2 \\<Longrightarrow> tv1 = tv2\"\n      by (cases tv1; cases tv2) (simp_all add: inj_eq)\n  }\n  then show ?thesis\n    using assms\n    by (simp add: injI)\nqed\n\ndefinition\n  change_int :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (id \\<Rightarrow> tv) \\<Rightarrow> (id \\<Rightarrow> tv)\"\nwhere\n  \"change_int f i \\<equiv> \\<lambda>s. change_tv f (i s)\"\n\nlemma eval_change_int_change_tv:\n  assumes \"inj f\"\n  shows \"eval (change_int f i) p = change_tv f (eval i p)\"\nproof (induct p)\n  fix p\n  assume a: \"eval (change_int f i) p = change_tv f (eval i p)\"\n  have \"eval_neg (eval (change_int f i) p) = eval_neg (change_tv f (eval i p))\"\n    using assms a\n    by auto\n  then have \"eval_neg (eval (change_int f i) p) = change_tv f (eval_neg (eval i p))\"\n    by (cases \"eval i p\") (auto simp add: case_bool_if)\n  then show \"eval (change_int f i) (Neg' p) = change_tv f (eval i (Neg' p))\"\n    by auto\nnext\n  fix p1 p2\n  assume ih1: \"eval (change_int f i) p1 = change_tv f (eval i p1)\"\n  assume ih2: \"eval (change_int f i) p2 = change_tv f (eval i p2)\"\n  show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n  proof (cases \"eval i p1 = eval i p2\")\n    assume a: \"eval i p1 = eval i p2\"\n    then have yes: \"eval i (Con p1 p2) = eval i p1\"\n      by auto\n    from a have \"change_tv f (eval i p1) = change_tv f (eval i p2)\"\n      by auto\n    then have \"eval (change_int f i) p1 = eval (change_int f i) p2\"\n      using ih1 ih2\n      by auto\n    then have \"eval (change_int f i) (Con p1 p2) = eval (change_int f i) p1\"\n      by auto\n    then show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n      using yes ih1\n      by auto\n  next\n    assume a': \"eval i p1 \\<noteq> eval i p2\"\n    from a' have b': \"eval (change_int f i) p1 \\<noteq> eval (change_int f i) p2\"\n      using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f\n      by metis\n    show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n    proof (cases \"eval i p1 = Det True\")\n      assume a: \"eval i p1 = Det True\"\n      from a a' have \"eval i (Con p1 p2) = eval i p2\"\n        by auto\n      then have c: \"change_tv f (eval i (Con p1 p2)) = change_tv f (eval i p2)\"\n        by auto\n      from a have b: \"eval (change_int f i) p1 = Det True\"\n        using ih1\n        by auto\n      from b b' have \"eval (change_int f i) (Con p1 p2) = eval (change_int f i) p2\"\n        by auto\n      then show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n        using c ih2\n        by auto\n    next\n      assume a'': \"eval i p1 \\<noteq> Det True\"\n      from a'' have b'': \"eval (change_int f i) p1 \\<noteq> Det True\"\n        using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n        by metis\n      show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n      proof (cases \"eval i p2 = Det True\")\n        assume a: \"eval i p2 = Det True\"\n        from a a' a'' have \"eval i (Con p1 p2) = eval i p1\"\n          by auto\n        then have c: \"change_tv f (eval i (Con p1 p2)) = change_tv f (eval i p1)\"\n          by auto\n        from a have b: \"eval (change_int f i) p2 = Det True\"\n          using ih2\n          by auto\n        from b b' b'' have \"eval (change_int f i) (Con p1 p2) = eval (change_int f i) p1\"\n          by auto\n        then show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n          using c ih1\n          by auto\n      next\n        assume a''': \"eval i p2 \\<noteq> Det True\"\n        from a' a'' a''' have \"eval i (Con p1 p2) = Det False\"\n          by auto\n        then have c: \"change_tv f (eval i (Con p1 p2)) = Det False\"\n          by auto\n        from a''' have b''': \"eval (change_int f i) p2 \\<noteq> Det True\"\n          using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n          by metis\n        from b' b'' b''' have \"eval (change_int f i) (Con p1 p2) = Det False\"\n          by auto\n        then show \"eval (change_int f i) (Con p1 p2) = change_tv f (eval i (Con p1 p2))\"\n          using c\n          by auto\n      qed\n    qed\n  qed\nnext\n  fix p1 p2\n  assume ih1: \"eval (change_int f i) p1 = change_tv f (eval i p1)\"\n  assume ih2: \"eval (change_int f i) p2 = change_tv f (eval i p2)\"\n  have \"Det (eval (change_int f i) p1 = eval (change_int f i) p2) =\n      Det (change_tv f (eval i p1) = change_tv f (eval i p2))\"\n    using ih1 ih2\n    by auto\n  also have \"... = Det ((eval i p1) = (eval i p2))\"\n    using assms change_tv_injection\n    by (simp add: inj_eq)\n  also have \"... = change_tv f (Det (eval i p1 = eval i p2))\"\n    by auto\n  finally\n  show \"eval (change_int f i) (Eql p1 p2) = change_tv f (eval i (Eql p1 p2))\"\n    using eval_equality\n    by auto\nnext\n  fix p1 p2\n  assume ih1: \"eval (change_int f i) p1 = change_tv f (eval i p1)\"\n  assume ih2: \"eval (change_int f i) p2 = change_tv f (eval i p2)\"\n  show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n  proof (cases \"eval i p1 = eval i p2\")\n    assume a: \"eval i p1 = eval i p2\"\n    then have yes: \"eval i (Eql' p1 p2) = Det True\"\n      by auto\n    from a have \"change_tv f (eval i p1) = change_tv f (eval i p2)\"\n      by auto\n    then have \"eval (change_int f i) p1 = eval (change_int f i) p2\"\n      using ih1 ih2\n      by auto\n    then have \"eval (change_int f i) (Eql' p1 p2) = Det True\"\n      by auto\n    then show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n      using yes ih1\n      by auto\n  next\n    assume a': \"eval i p1 \\<noteq> eval i p2\"\n    show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n    proof (cases \"eval i p1 = Det True\")\n      assume a: \"eval i p1 = Det True\"\n      from a a' have yes: \"eval i (Eql' p1 p2) = eval i p2\"\n        by auto\n      from a have \"change_tv f (eval i p1) = Det True\"\n        by auto\n      then have b: \"eval (change_int f i) p1 = Det True\"\n        using ih1\n        by auto\n      from a' have b': \"eval (change_int f i) p1 \\<noteq> eval (change_int f i) p2\"\n        using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n        by metis\n      from b b' have \"eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) p2\"\n        by auto\n      then show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n        using ih2 yes\n        by auto\n    next\n      assume a'': \"eval i p1 \\<noteq> Det True\"\n      show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n      proof (cases \"eval i p2 = Det True\")\n        assume a: \"eval i p2 = Det True\"\n        from a a' a'' have yes: \"eval i (Eql' p1 p2) = eval i p1\"\n          using eval_equality[of i p1 p2]\n          by auto\n        from a have \"change_tv f (eval i p2) = Det True\"\n          by auto\n        then have b: \"eval (change_int f i) p2 = Det True\"\n          using ih2\n          by auto\n        from a' have b': \"eval (change_int f i) p1 \\<noteq> eval (change_int f i) p2\"\n          using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n          by metis\n        from a'' have b'': \"eval (change_int f i) p1 \\<noteq> Det True\"\n          using b b'\n          by auto\n        from b b' b'' have \"eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) p1\"\n          using eval_equality[of \"change_int f i\" p1 p2]\n          by auto\n        then show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n          using ih1 yes\n          by auto\n      next\n        assume a''': \"eval i p2 \\<noteq> Det True\"\n        show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n        proof (cases \"eval i p1 = Det False\")\n          assume a: \"eval i p1 = Det False\"\n          from a a' a'' a''' have yes: \"eval i (Eql' p1 p2) = eval i (Neg' p2)\"\n            using eval_equality[of i p1 p2]\n            by auto\n          from a have \"change_tv f (eval i p1) = Det False\"\n            by auto\n          then have b: \"eval (change_int f i) p1 = Det False\"\n            using ih1\n             by auto\n          from a' have b': \"eval (change_int f i) p1 \\<noteq> eval (change_int f i) p2\"\n            using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n            by metis\n          from a'' have b'': \"eval (change_int f i) p1 \\<noteq> Det True\"\n            using b b'\n            by auto\n          from a''' have b''': \"eval (change_int f i) p2 \\<noteq> Det True\"\n            using b b' b''\n            by (metis assms change_tv.simps(1) change_tv_injection inj_eq ih2)\n          from b b' b'' b'''\n          have \"eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) (Neg' p2)\"\n            using eval_equality[of \"change_int f i\" p1 p2]\n            by auto\n          then show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n            using ih2 yes a a' a''' b b' b''' eval_negation\n            by metis\n        next\n          assume a'''': \"eval i p1 \\<noteq> Det False\"\n          show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n          proof (cases \"eval i p2 = Det False\")\n            assume a: \"eval i p2 = Det False\"\n            from a a' a'' a''' a'''' have yes: \"eval i (Eql' p1 p2) = eval i (Neg' p1)\"\n              using eval_equality[of i p1 p2]\n              by auto\n            from a have \"change_tv f (eval i p2) = Det False\"\n              by auto\n            then have b: \"eval (change_int f i) p2 = Det False\"\n              using ih2\n              by auto\n            from a' have b': \"eval (change_int f i) p1 \\<noteq> eval (change_int f i) p2\"\n              using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n              by metis\n            from a'' have b'': \"eval (change_int f i) p1 \\<noteq> Det True\"\n              using change_tv.elims ih1 tv.simps(4)\n              by auto\n            from a''' have b''': \"eval (change_int f i) p2 \\<noteq> Det True\"\n              using b b' b''\n              by (metis assms change_tv.simps(1) change_tv_injection inj_eq ih2)\n            from a'''' have b'''': \"eval (change_int f i) p1 \\<noteq> Det False\"\n              using b b'\n              by auto\n            from b b' b'' b''' b''''\n            have \"eval (change_int f i) (Eql' p1 p2) = eval (change_int f i) (Neg' p1)\"\n              using eval_equality[of \"change_int f i\" p1 p2]\n              by auto\n            then show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n              using ih1 yes a a' a''' a'''' b b' b''' b'''' eval_negation a'' b''\n              by metis\n          next\n            assume a''''': \"eval i p2 \\<noteq> Det False\"\n            from a' a'' a''' a'''' a''''' have yes: \"eval i (Eql' p1 p2) = Det False\"\n              using eval_equality[of i p1 p2]\n              by auto\n            from a''''' have \"change_tv f (eval i p2) \\<noteq> Det False\"\n              using change_tv_injection inj_eq \\<open>inj f\\<close> change_tv.simps\n              by metis\n            then have b: \"eval (change_int f i) p2 \\<noteq> Det False\"\n              using ih2\n              by auto\n            from a' have b': \"eval (change_int f i) p1 \\<noteq> eval (change_int f i) p2\"\n              using \\<open>inj f\\<close> ih1 ih2 change_tv_injection the_inv_f_f change_tv.simps\n              by metis\n            from a'' have b'': \"eval (change_int f i) p1 \\<noteq> Det True\"\n              using change_tv.elims ih1 tv.simps(4)\n              by auto\n            from a''' have b''': \"eval (change_int f i) p2 \\<noteq> Det True\"\n              using b b' b''\n              by (metis assms change_tv.simps(1) change_tv_injection the_inv_f_f ih2)\n            from a'''' have b'''': \"eval (change_int f i) p1 \\<noteq> Det False\"\n              by (metis a'' change_tv.simps(2) ih1 string_tv.cases tv.distinct(1))\n            from b b' b'' b''' b'''' have \"eval (change_int f i) (Eql' p1 p2) = Det False\"\n              using eval_equality[of \"change_int f i\" p1 p2]\n              by auto\n            then show \"eval (change_int f i) (Eql' p1 p2) = change_tv f (eval i (Eql' p1 p2))\"\n              using ih1 yes a' a''' a'''' b b' b''' b'''' eval_negation a'' b''\n              by auto\n          qed\n        qed\n      qed\n    qed\n  qed\nqed (simp_all add: change_int_def)\n\ntheorem valid_in_valid:\n  assumes \"card U \\<ge> card (props p)\"\n  assumes \"valid_in U p\"\n  shows \"valid p\"\nproof -\n  have \"finite U \\<Longrightarrow> card (props p) \\<le> card U \\<Longrightarrow> valid_in U p \\<Longrightarrow> valid p\" for U p\n  proof -\n    assume assms: \"finite U\" \"card (props p) \\<le> card U\" \"valid_in U p\"\n    show \"valid p\"\n      unfolding valid_def\n    proof\n      fix i\n      obtain f where f_p: \"(change_int f i) ` (props p) \\<subseteq> (domain U) \\<and> inj f\"\n      proof -\n        have \"finite U \\<Longrightarrow> card (props p) \\<le> card U \\<Longrightarrow>\n            \\<exists>f. change_int f i ` props p \\<subseteq> domain U \\<and> inj f\" for U p\n        proof -\n          assume assms: \"finite U\" \"card (props p) \\<le> card U\"\n          show ?thesis\n          proof -\n            let ?X = \"(get_indet ` ((i ` props p) \\<inter> {tv. is_indet tv}))\"\n            have d: \"finite (props p)\"\n              by (induct p) auto\n            then have f: \"finite ?X\"\n              by auto\n            have cx: \"card ?X \\<le> card U\"\n              using assms\n              by (metis Int_lower1 d card_image_le card_mono finite_Int finite_imageI le_trans)\n            obtain f where f_p: \"(\\<forall>n \\<in> ?X. f n \\<in> U) \\<and> (inj f)\"\n            proof -\n              have \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> card X \\<le> card Y \\<Longrightarrow> \\<exists>f. (\\<forall>n\\<in>X. f n \\<in> Y) \\<and> inj f\"\n                  for X Y :: \"nat set\"\n              proof -\n                assume assms: \"finite X\" \"finite Y\" \"card X \\<le> card Y\"\n                show ?thesis\n                proof -\n                  from assms obtain Z where \"Z \\<subseteq> Y \\<and> card Z = card X\"\n                    by (metis card_image card_le_inj)\n                  then obtain f where \"bij_betw f X Z\"\n                    by (metis assms(1) assms(2) finite_same_card_bij infinite_super)\n                  then have f_p: \"(\\<forall>n \\<in> X. f n \\<in> Y) \\<and> inj_on f X\"\n                    using \\<open>Z \\<subseteq> Y \\<and> card Z = card X\\<close> bij_betwE bij_betw_imp_inj_on\n                    by blast\n                  obtain f' where f': \"f' = (\\<lambda>n. if n \\<in> X then f n else n + Suc (Max Y + n))\"\n                    by simp\n                  have \"inj f'\"\n                    unfolding f' inj_on_def\n                    using assms(2) f_p le_add2 trans_le_add2 not_less_eq_eq\n                    by (simp, metis Max_ge add.commute inj_on_eq_iff)\n                  moreover have \"(\\<forall>n \\<in> X. f' n \\<in> Y)\"\n                    unfolding f'\n                    using f_p\n                    by auto\n                  ultimately show ?thesis\n                    by metis\n                qed\n              qed\n              then show \"(\\<And>f. (\\<forall>n \\<in> get_indet ` (i ` props p \\<inter> {tv. is_indet tv}). f n \\<in> U)\n                  \\<and> inj f \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n                using assms cx f\n                unfolding inj_on_def\n                by metis\n            qed\n            have \"(change_int f i) ` (props p) \\<subseteq> (domain U)\"\n            proof\n              fix x\n              assume \"x \\<in> change_int f i ` props p\"\n              then obtain s where s_p: \"s \\<in> props p \\<and> change_int f i s = x\"\n                by auto\n              then have \"change_int f i s \\<in> {Det True, Det False} \\<union> Indet ` U\"\n              proof (cases \"change_int f i s \\<in> {Det True, Det False}\")\n                case True\n                then show ?thesis\n                  by auto\n              next\n                case False\n                then obtain n' where \"change_int f i s = Indet n'\"\n                  by (cases \"change_int f i s\") auto\n                then have p: \"change_tv f (i s) = Indet n'\"\n                  by (simp add: change_int_def)\n                moreover\n                {\n                  obtain n'' where \"f n'' = n'\"\n                    using calculation change_tv.elims\n                    by blast\n                  moreover have \"s \\<in> props p \\<and> i s = (Indet n'')\"\n                    using p calculation change_tv.simps change_tv_injection the_inv_f_f f_p s_p\n                    by metis\n                  then have \"(Indet n'') \\<in> i ` props p\"\n                    using image_iff\n                    by metis\n                  then have \"(Indet n'') \\<in> i ` props p \\<and> is_indet (Indet n'') \\<and>\n                      get_indet (Indet n'') = n''\"\n                    by auto\n                  then have \"n'' \\<in> ?X\"\n                    using Int_Collect image_iff\n                    by metis\n                  ultimately have \"n' \\<in> U\"\n                    using f_p\n                    by auto\n                }\n                ultimately have \"change_tv f (i s) \\<in> Indet ` U\"\n                  by auto\n                then have \"change_int f i s \\<in> Indet ` U\"\n                  unfolding change_int_def\n                  by auto\n                then show ?thesis\n                  by auto\n              qed\n              then show \"x \\<in> domain U\"\n                unfolding domain_def\n                using s_p\n                by simp\n            qed\n            then have \"(change_int f i) ` (props p) \\<subseteq> (domain U) \\<and> (inj f)\"\n              unfolding domain_def\n              using f_p\n              by simp\n            then show ?thesis\n              using f_p\n              by metis\n          qed\n        qed\n        then show \"(\\<And>f. change_int f i ` props p \\<subseteq> domain U \\<and> inj f \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n          using assms\n          by metis\n      qed\n      obtain i2 where i2: \"i2 = (\\<lambda>s. if s \\<in> props p then (change_int f i) s else Det True)\"\n        by simp\n      then have i2_p: \"\\<forall>s \\<in> props p. i2 s = (change_int f i) s\"\n            \"\\<forall>s \\<in> - props p. i2 s = Det True\"\n        by auto\n      then have \"range i2 \\<subseteq> (domain U)\"\n        using i2 f_p\n        unfolding domain_def\n        by auto\n      then have \"eval i2 p = Det True\"\n        using assms\n        unfolding valid_in_def\n        by auto\n      then have \"eval (change_int f i) p = Det True\"\n        using relevant_props[of p i2 \"change_int f i\"] i2_p\n        by auto\n      then have \"change_tv f (eval i p) = Det True\"\n        using eval_change_int_change_tv f_p\n        by auto\n      then show \"eval i p = Det True\"\n        by (cases \"eval i p\") auto\n    qed\n  qed\n  then show ?thesis\n    using assms subsetI sup_bot.comm_neutral image_is_empty subsetCE UnCI valid_in_def\n        Un_insert_left card.empty card.infinite finite.intros(1)\n    unfolding domain_def\n    by metis\nqed\n\nproposition \"valid p \\<longleftrightarrow> valid_in {1..card (props p)} p\"\n  using valid_in_valid transfer\n  by force\n\nend\n", "meta": {"author": "logic-tools", "repo": "mvl", "sha": "3947414b9e2e7b46533c4df33b7c848926146f67", "save_path": "github-repos/isabelle/logic-tools-mvl", "path": "github-repos/isabelle/logic-tools-mvl/mvl-3947414b9e2e7b46533c4df33b7c848926146f67/Partiality.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8807970795424088, "lm_q1q2_score": 0.76988466736007}}
{"text": "theory Example_A\n  imports \"../Classifying_Markov_Chain_States\"\nbegin\n\nsection \\<open>Example A\\<close> text_raw \\<open>\\label{ex:A}\\<close>\n\ntext \\<open>\n\nWe formalize the following Markov chain:\n\n\\begin{center}\n\\begin{tikzpicture}[thick]\n\n  \\path [fill, color = gray!30] (0, 0) circle(0.6) ;\n\n  \\path [fill, color = gray!30] (1, 1) circle(0.6) ;\n\n  \\path [fill, color = gray!30] (4.5, 0.66) ellipse(2 and 1.9) ;\n\n  \\node (bot)  at (-1, 0) {} ;\n\n  \\node[draw,circle] (A)  at (0, 0) {$A$} ;\n\n  \\node[draw,circle] (B)  at (1, 1) {$B$} ;\n\n  \\node[draw,circle] (C1) at (3, 0) {$C_1$} ;\n\n  \\node[draw,circle] (C2) at (6, 0) {$C_2$} ;\n\n  \\node[draw,circle] (C3) at (4.5, 2) {$C_3$} ;\n\n  \\path[->, >=latex]\n    (bot) edge (A)\n    (A)   edge                node [above] {$\\frac{1}{2}$} (B)\n          edge                node [below] {$\\frac{1}{2}$} (C1)\n    (B)   edge [loop above]   node [left]  {$\\frac{1}{2}$} (B)\n          edge [out = 0]      node [above] {$\\frac{1}{2}$} (C1)\n    (C1)  edge [loop above]   node [above] {$\\frac{1}{3}$} (C1)\n          edge [bend left=15] node [above] {$\\frac{1}{3}$} (C2)\n          edge [bend left=15] node [above] {$\\frac{1}{3}$} (C3)\n    (C2)  edge [loop right]   node [above] {$\\frac{1}{3}$} (C2)\n          edge [bend left=15] node [above] {$\\frac{1}{3}$} (C1)\n          edge [bend left=15] node [above] {$\\frac{1}{3}$} (C3)\n    (C3)  edge [loop right]   node [above] {$\\frac{1}{2}$} (C3)\n          edge [bend left=15] node [above] {$\\frac{1}{4}$} (C1)\n          edge [bend left=15] node [above] {$\\frac{1}{4}$} (C2) ;\n\n\\end{tikzpicture}\n\\end{center}\n\nFirst we define the state space as its own type:\n\n\\<close>\n\ndatatype state = A | B | C1 | C2 | C3\n\ntext \\<open>Now the state space is \\<open>UNIV :: state set\\<close>\\<close>\n\nlemma UNIV_state: \"UNIV = {A, B, C1, C2, C3}\"\n  using state.nchotomy by auto\n\ninstance state :: finite\n  by standard (simp add: UNIV_state)\n\ntext \\<open>The transition function \\<open>tau\\<close> is easily defined using the case statement, this allows\nus to give a sparse specification as all \\<open>0\\<close> cases are collected at the end.\\<close>\n\ndefinition tau :: \"state \\<Rightarrow> state \\<Rightarrow> real\" where\n  \"tau s t = (case (s, t) of\n      (A,  B)  \\<Rightarrow> 1 / 2 | (A,  C1) \\<Rightarrow> 1 / 2\n    | (B,  B)  \\<Rightarrow> 1 / 2 | (B,  C1) \\<Rightarrow> 1 / 2\n    | (C1, C1) \\<Rightarrow> 1 / 3 | (C1, C2) \\<Rightarrow> 1 / 3 | (C1, C3) \\<Rightarrow> 1 / 3\n    | (C2, C1) \\<Rightarrow> 1 / 3 | (C2, C2) \\<Rightarrow> 1 / 3 | (C2, C3) \\<Rightarrow> 1 / 3\n    | (C3, C1) \\<Rightarrow> 1 / 4 | (C3, C2) \\<Rightarrow> 1 / 4 | (C3, C3) \\<Rightarrow> 1 / 2\n    | _ \\<Rightarrow> 0)\"\n\nlift_definition K :: \"state \\<Rightarrow> state pmf\" is tau\n  by (auto simp: tau_def nn_integral_count_space_finite UNIV_state split: state.split simp del: ennreal_plus)\n\ntext \\<open>We use the \\<open>finite_pmf\\<close>-locale which introduces the point measure \\<open>tau.M\\<close>, and\n  provides us with the necessary simplifier setup.\\<close>\n\ninterpretation A: MC_syntax K .\n\nsubsection \\<open>The essential classs @{term \"{C1, C2, C3}\"}\\<close>\n\ncontext\nbegin\n\ninterpretation pmf_as_function .\n\nlemma A_E_eq:\n  \"set_pmf (K x) = (case x of A \\<Rightarrow> {B, C1} | B \\<Rightarrow> {B, C1} | _ \\<Rightarrow> {C1, C2, C3})\"\n  using state.nchotomy by transfer (auto simp: tau_def split: prod.split state.split)\n\nlemma A_essential: \"A.essential_class {C1, C2, C3}\"\n  by (rule A.essential_classI2) (auto simp: A_E_eq)\n\nlemma A_aperiodic: \"A.aperiodic {C1, C2, C3}\"\n  unfolding A.aperiodic_def\nproof safe\n  have eq: \"\\<And>x'. (if x' = C1 then 1 else 0) = indicator {C1} x'\" by auto\n\n  show \"{C1, C2, C3} \\<in> UNIV // A.communicating\"\n    using A_essential by (simp add: A.essential_class_def)\n  then have \"A.period {C1, C2, C3} = Gcd (A.period_set C1)\"\n    by (rule A.period_eq) simp\n  also have \"\\<dots> = 1\"\n    by (rule Gcd_nat_eq_one) (simp add: A_E_eq A.period_set_def A.p_Suc' A.p_0 eq measure_pmf_single pmf_positive)\n  finally show \"A.period {C1, C2, C3} = 1\" .\nqed\n\nsubsection \\<open>The stationary distribution \\<open>n\\<close>\\<close>\n\ntext \\<open>Similar to \\<open>tau\\<close> we introduce \\<open>n\\<close> using the \\<open>finite_pmf\\<close>-locale.\\<close>\n\nlift_definition n :: \"state pmf\" is \"\\<lambda>C1 \\<Rightarrow> 0.3 | C2 \\<Rightarrow> 0.3 | C3 \\<Rightarrow> 0.4 | _ \\<Rightarrow> 0\"\n  by (auto simp: UNIV_state nn_integral_count_space_finite split: state.split)\n\nlemma stationary_distribution_N: \"A.stationary_distribution n\"\n  unfolding A.stationary_distribution_def\n  apply (auto intro!: pmf_eqI simp: pmf_bind integral_measure_pmf[of UNIV])\n  apply transfer\n  apply (auto simp: UNIV_state tau_def split: state.split)\n  done\n\nlemma exclusive_N[simp]: \"set_pmf n = {C1, C2, C3}\"\n  using state.nchotomy by transfer (auto split: state.splits)\n\nend\n\nlemma n_is_limit:\n  assumes x: \"x \\<in> {C1, C2, C3}\" and y: \"y \\<in> {C1, C2, C3}\"\n  shows \"(A.p x y) \\<longlonglongrightarrow> pmf n y\"\n  using A.stationary_distribution_imp_p_limit[OF A_aperiodic A_essential _ stationary_distribution_N _ x y]\n  by simp\n\nlemma C_is_pos_recurrent: \"x \\<in> {C1, C2, C3} \\<Longrightarrow> A.pos_recurrent x\"\n  using A.stationary_distributionD(1)[OF A_essential _ stationary_distribution_N] by auto\n\nlemma C_recurrence_time:\n  assumes x: \"x \\<in> {C1, C2, C3}\"\n  shows \"A.U' x x = 1 / pmf n x\"\nproof -\n  from A.stationary_distributionD(2)[OF A_essential _ stationary_distribution_N _]\n  have \"A.stat {C1, C2, C3} = n\" by simp\n  with x have \"1 / pmf n x = 1 / emeasure (A.stat {C1, C2, C3}) {x}\"\n    by (simp add: emeasure_pmf_single pmf_positive divide_ennreal ennreal_1[symmetric] del: ennreal_1)\n  also have \"\\<dots> = A.U' x x\"\n    unfolding A.stat_def using x\n    by (subst emeasure_point_measure_finite) (simp_all add:  A.U'_def)\n  finally show ?thesis ..\nqed\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Markov_Models/ex/Example_A.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.7698846606766679}}
{"text": "theory transitive_closure_star\nimports Main\nbegin\n(* \nRelation = if x \\in X, y \\in Y when we have R x y \\<longleftrightarrow> (x,y) \\<in> X \\<times> Y.\nReflexive = self loops  in the graph. e.g. \\<forall>x \\<in> X, (x,x) \\in X \\<times> X\nTransitive = if there is a path from x to y and from y to z then there is one from\nx to z. if R x y, R y z \\<Longrightarrow> R x z.\nReflexive closure = smallest relation that is reflexive and contains R. \n  r(R) := R \\<union> Diagonal.\nTransitive closure t(r) := R \\<and> Transitive \\<and> Smallest\n\nTransitive closure := \ntr(r) := R \\<and> Reflexive \\<and> Transitive \\<and> Smallest\n\ntransitive closure\ntransitive closure relation means it must be reflexive and transitive. \nSo if we have R then tr(R) = R* is a new relation that is reflexive and transitive.\nNote the * operator maps relations to it’s transitive closure \ni.e. *(R) = R* for short hand.\n\n*)\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  for r where \nrefl: \"star r x x\"|\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n \n(* By definition star r is reflexive. *)\n\nlemma star_reflexive: \"star r x x\" by (rule refl)\n\n(* It is also transitive, but we need rule induction to prove that: *)\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  apply(induction rule: star.induct)\n   apply assumption\n  by (simp add: star.step)\n\nlemma \n  shows \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\nproof (induction rule: star.induct)\ncase (refl x)\n  then show ?case by assumption\nnext\n  case (step x y z)\n  then show ?case by (simp add: star.step)\nqed\n\nend", "meta": {"author": "brando90", "repo": "isabelle-gym", "sha": "f4d231cb9f625422e873aa2c9c2c6f22b7da4b27", "save_path": "github-repos/isabelle/brando90-isabelle-gym", "path": "github-repos/isabelle/brando90-isabelle-gym/isabelle-gym-f4d231cb9f625422e873aa2c9c2c6f22b7da4b27/isar_brandos_resources/transitive_closure_star.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.8459424353665381, "lm_q1q2_score": 0.7697289445114873}}
{"text": "(*  Title:      FOL/ex/Classical.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection \\<open>Classical Predicate Calculus Problems\\<close>\n\ntheory Classical\nimports FOL\nbegin\n\nlemma \\<open>(P \\<longrightarrow> Q \\<or> R) \\<longrightarrow> (P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R)\\<close>\n  by blast\n\n\nsubsubsection \\<open>If and only if\\<close>\n\nlemma \\<open>(P \\<longleftrightarrow> Q) \\<longleftrightarrow> (Q \\<longleftrightarrow> P)\\<close>\n  by blast\n\nlemma \\<open>\\<not> (P \\<longleftrightarrow> \\<not> P)\\<close>\n  by blast\n\n\nsubsection \\<open>Pelletier's examples\\<close>\n\ntext \\<open>\n  Sample problems from\n\n    \\<^item> F. J. Pelletier,\n    Seventy-Five Problems for Testing Automatic Theorem Provers,\n    J. Automated Reasoning 2 (1986), 191-216.\n    Errata, JAR 4 (1988), 236-236.\n\n  The hardest problems -- judging by experience with several theorem\n  provers, including matrix ones -- are 34 and 43.\n\\<close>\n\ntext\\<open>1\\<close>\nlemma \\<open>(P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\\<close>\n  by blast\n\ntext\\<open>2\\<close>\nlemma \\<open>\\<not> \\<not> P \\<longleftrightarrow> P\\<close>\n  by blast\n\ntext\\<open>3\\<close>\nlemma \\<open>\\<not> (P \\<longrightarrow> Q) \\<longrightarrow> (Q \\<longrightarrow> P)\\<close>\n  by blast\n\ntext\\<open>4\\<close>\nlemma \\<open>(\\<not> P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> P)\\<close>\n  by blast\n\ntext\\<open>5\\<close>\nlemma \\<open>((P \\<or> Q) \\<longrightarrow> (P \\<or> R)) \\<longrightarrow> (P \\<or> (Q \\<longrightarrow> R))\\<close>\n  by blast\n\ntext\\<open>6\\<close>\nlemma \\<open>P \\<or> \\<not> P\\<close>\n  by blast\n\ntext\\<open>7\\<close>\nlemma \\<open>P \\<or> \\<not> \\<not> \\<not> P\\<close>\n  by blast\n\ntext\\<open>8. Peirce's law\\<close>\nlemma \\<open>((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P\\<close>\n  by blast\n\ntext\\<open>9\\<close>\nlemma \\<open>((P \\<or> Q) \\<and> (\\<not> P \\<or> Q) \\<and> (P \\<or> \\<not> Q)) \\<longrightarrow> \\<not> (\\<not> P \\<or> \\<not> Q)\\<close>\n  by blast\n\ntext\\<open>10\\<close>\nlemma \\<open>(Q \\<longrightarrow> R) \\<and> (R \\<longrightarrow> P \\<and> Q) \\<and> (P \\<longrightarrow> Q \\<or> R) \\<longrightarrow> (P \\<longleftrightarrow> Q)\\<close>\n  by blast\n\ntext\\<open>11. Proved in each direction (incorrectly, says Pelletier!!)\\<close>\nlemma \\<open>P \\<longleftrightarrow> P\\<close>\n  by blast\n\ntext\\<open>12. \"Dijkstra's law\"\\<close>\nlemma \\<open>((P \\<longleftrightarrow> Q) \\<longleftrightarrow> R) \\<longleftrightarrow> (P \\<longleftrightarrow> (Q \\<longleftrightarrow> R))\\<close>\n  by blast\n\ntext\\<open>13. Distributive law\\<close>\nlemma \\<open>P \\<or> (Q \\<and> R) \\<longleftrightarrow> (P \\<or> Q) \\<and> (P \\<or> R)\\<close>\n  by blast\n\ntext\\<open>14\\<close>\nlemma \\<open>(P \\<longleftrightarrow> Q) \\<longleftrightarrow> ((Q \\<or> \\<not> P) \\<and> (\\<not> Q \\<or> P))\\<close>\n  by blast\n\ntext\\<open>15\\<close>\nlemma \\<open>(P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> P \\<or> Q)\\<close>\n  by blast\n\ntext\\<open>16\\<close>\nlemma \\<open>(P \\<longrightarrow> Q) \\<or> (Q \\<longrightarrow> P)\\<close>\n  by blast\n\ntext\\<open>17\\<close>\nlemma \\<open>((P \\<and> (Q \\<longrightarrow> R)) \\<longrightarrow> S) \\<longleftrightarrow> ((\\<not> P \\<or> Q \\<or> S) \\<and> (\\<not> P \\<or> \\<not> R \\<or> S))\\<close>\n  by blast\n\n\nsubsection \\<open>Classical Logic: examples with quantifiers\\<close>\n\nlemma \\<open>(\\<forall>x. P(x) \\<and> Q(x)) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<and> (\\<forall>x. Q(x))\\<close>\n  by blast\n\nlemma \\<open>(\\<exists>x. P \\<longrightarrow> Q(x)) \\<longleftrightarrow> (P \\<longrightarrow> (\\<exists>x. Q(x)))\\<close>\n  by blast\n\nlemma \\<open>(\\<exists>x. P(x) \\<longrightarrow> Q) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<longrightarrow> Q\\<close>\n  by blast\n\nlemma \\<open>(\\<forall>x. P(x)) \\<or> Q \\<longleftrightarrow> (\\<forall>x. P(x) \\<or> Q)\\<close>\n  by blast\n\ntext\\<open>Discussed in Avron, Gentzen-Type Systems, Resolution and Tableaux,\n  JAR 10 (265-281), 1993.  Proof is trivial!\\<close>\nlemma \\<open>\\<not> ((\\<exists>x. \\<not> P(x)) \\<and> ((\\<exists>x. P(x)) \\<or> (\\<exists>x. P(x) \\<and> Q(x))) \\<and> \\<not> (\\<exists>x. P(x)))\\<close>\n  by blast\n\n\nsubsection \\<open>Problems requiring quantifier duplication\\<close>\n\ntext\\<open>Theorem B of Peter Andrews, Theorem Proving via General Matings,\n  JACM 28 (1981).\\<close>\nlemma \\<open>(\\<exists>x. \\<forall>y. P(x) \\<longleftrightarrow> P(y)) \\<longrightarrow> ((\\<exists>x. P(x)) \\<longleftrightarrow> (\\<forall>y. P(y)))\\<close>\n  by blast\n\ntext\\<open>Needs multiple instantiation of ALL.\\<close>\nlemma \\<open>(\\<forall>x. P(x) \\<longrightarrow> P(f(x))) \\<and> P(d) \\<longrightarrow> P(f(f(f(d))))\\<close>\n  by blast\n\ntext\\<open>Needs double instantiation of the quantifier\\<close>\nlemma \\<open>\\<exists>x. P(x) \\<longrightarrow> P(a) \\<and> P(b)\\<close>\n  by blast\n\nlemma \\<open>\\<exists>z. P(z) \\<longrightarrow> (\\<forall>x. P(x))\\<close>\n  by blast\n\nlemma \\<open>\\<exists>x. (\\<exists>y. P(y)) \\<longrightarrow> P(x)\\<close>\n  by blast\n\ntext\\<open>V. Lifschitz, What Is the Inverse Method?, JAR 5 (1989), 1--23. NOT PROVED.\\<close>\nlemma\n  \\<open>\\<exists>x x'. \\<forall>y. \\<exists>z z'.\n    (\\<not> P(y,y) \\<or> P(x,x) \\<or> \\<not> S(z,x)) \\<and>\n    (S(x,y) \\<or> \\<not> S(y,z) \\<or> Q(z',z')) \\<and>\n    (Q(x',y) \\<or> \\<not> Q(y,z') \\<or> S(x',x'))\\<close>\n  oops\n\n\nsubsection \\<open>Hard examples with quantifiers\\<close>\n\ntext\\<open>18\\<close>\nlemma \\<open>\\<exists>y. \\<forall>x. P(y) \\<longrightarrow> P(x)\\<close>\n  by blast\n\ntext\\<open>19\\<close>\nlemma \\<open>\\<exists>x. \\<forall>y z. (P(y) \\<longrightarrow> Q(z)) \\<longrightarrow> (P(x) \\<longrightarrow> Q(x))\\<close>\n  by blast\n\ntext\\<open>20\\<close>\nlemma \\<open>(\\<forall>x y. \\<exists>z. \\<forall>w. (P(x) \\<and> Q(y) \\<longrightarrow> R(z) \\<and> S(w)))\n  \\<longrightarrow> (\\<exists>x y. P(x) \\<and> Q(y)) \\<longrightarrow> (\\<exists>z. R(z))\\<close>\n  by blast\n\ntext\\<open>21\\<close>\nlemma \\<open>(\\<exists>x. P \\<longrightarrow> Q(x)) \\<and> (\\<exists>x. Q(x) \\<longrightarrow> P) \\<longrightarrow> (\\<exists>x. P \\<longleftrightarrow> Q(x))\\<close>\n  by blast\n\ntext\\<open>22\\<close>\nlemma \\<open>(\\<forall>x. P \\<longleftrightarrow> Q(x)) \\<longrightarrow> (P \\<longleftrightarrow> (\\<forall>x. Q(x)))\\<close>\n  by blast\n\ntext\\<open>23\\<close>\nlemma \\<open>(\\<forall>x. P \\<or> Q(x)) \\<longleftrightarrow> (P \\<or> (\\<forall>x. Q(x)))\\<close>\n  by blast\n\ntext\\<open>24\\<close>\nlemma\n  \\<open>\\<not> (\\<exists>x. S(x) \\<and> Q(x)) \\<and> (\\<forall>x. P(x) \\<longrightarrow> Q(x) \\<or> R(x)) \\<and>\n    (\\<not> (\\<exists>x. P(x)) \\<longrightarrow> (\\<exists>x. Q(x))) \\<and> (\\<forall>x. Q(x) \\<or> R(x) \\<longrightarrow> S(x))\n    \\<longrightarrow> (\\<exists>x. P(x) \\<and> R(x))\\<close>\n  by blast\n\ntext\\<open>25\\<close>\nlemma\n  \\<open>(\\<exists>x. P(x)) \\<and>\n    (\\<forall>x. L(x) \\<longrightarrow> \\<not> (M(x) \\<and> R(x))) \\<and>\n    (\\<forall>x. P(x) \\<longrightarrow> (M(x) \\<and> L(x))) \\<and>\n    ((\\<forall>x. P(x) \\<longrightarrow> Q(x)) \\<or> (\\<exists>x. P(x) \\<and> R(x)))\n    \\<longrightarrow> (\\<exists>x. Q(x) \\<and> P(x))\\<close>\n  by blast\n\ntext\\<open>26\\<close>\nlemma\n  \\<open>((\\<exists>x. p(x)) \\<longleftrightarrow> (\\<exists>x. q(x))) \\<and>\n    (\\<forall>x. \\<forall>y. p(x) \\<and> q(y) \\<longrightarrow> (r(x) \\<longleftrightarrow> s(y)))\n  \\<longrightarrow> ((\\<forall>x. p(x) \\<longrightarrow> r(x)) \\<longleftrightarrow> (\\<forall>x. q(x) \\<longrightarrow> s(x)))\\<close>\n  by blast\n\ntext\\<open>27\\<close>\nlemma\n  \\<open>(\\<exists>x. P(x) \\<and> \\<not> Q(x)) \\<and>\n    (\\<forall>x. P(x) \\<longrightarrow> R(x)) \\<and>\n    (\\<forall>x. M(x) \\<and> L(x) \\<longrightarrow> P(x)) \\<and>\n    ((\\<exists>x. R(x) \\<and> \\<not> Q(x)) \\<longrightarrow> (\\<forall>x. L(x) \\<longrightarrow> \\<not> R(x)))\n  \\<longrightarrow> (\\<forall>x. M(x) \\<longrightarrow> \\<not> L(x))\\<close>\n  by blast\n\ntext\\<open>28. AMENDED\\<close>\nlemma\n  \\<open>(\\<forall>x. P(x) \\<longrightarrow> (\\<forall>x. Q(x))) \\<and>\n    ((\\<forall>x. Q(x) \\<or> R(x)) \\<longrightarrow> (\\<exists>x. Q(x) \\<and> S(x))) \\<and>\n    ((\\<exists>x. S(x)) \\<longrightarrow> (\\<forall>x. L(x) \\<longrightarrow> M(x)))\n  \\<longrightarrow> (\\<forall>x. P(x) \\<and> L(x) \\<longrightarrow> M(x))\\<close>\n  by blast\n\ntext\\<open>29. Essentially the same as Principia Mathematica *11.71\\<close>\nlemma\n  \\<open>(\\<exists>x. P(x)) \\<and> (\\<exists>y. Q(y))\n    \\<longrightarrow> ((\\<forall>x. P(x) \\<longrightarrow> R(x)) \\<and> (\\<forall>y. Q(y) \\<longrightarrow> S(y)) \\<longleftrightarrow>\n      (\\<forall>x y. P(x) \\<and> Q(y) \\<longrightarrow> R(x) \\<and> S(y)))\\<close>\n  by blast\n\ntext\\<open>30\\<close>\nlemma\n  \\<open>(\\<forall>x. P(x) \\<or> Q(x) \\<longrightarrow> \\<not> R(x)) \\<and>\n    (\\<forall>x. (Q(x) \\<longrightarrow> \\<not> S(x)) \\<longrightarrow> P(x) \\<and> R(x))\n    \\<longrightarrow> (\\<forall>x. S(x))\\<close>\n  by blast\n\ntext\\<open>31\\<close>\nlemma\n  \\<open>\\<not> (\\<exists>x. P(x) \\<and> (Q(x) \\<or> R(x))) \\<and>\n    (\\<exists>x. L(x) \\<and> P(x)) \\<and>\n    (\\<forall>x. \\<not> R(x) \\<longrightarrow> M(x))\n  \\<longrightarrow> (\\<exists>x. L(x) \\<and> M(x))\\<close>\n  by blast\n\ntext\\<open>32\\<close>\nlemma\n  \\<open>(\\<forall>x. P(x) \\<and> (Q(x) \\<or> R(x)) \\<longrightarrow> S(x)) \\<and>\n    (\\<forall>x. S(x) \\<and> R(x) \\<longrightarrow> L(x)) \\<and>\n    (\\<forall>x. M(x) \\<longrightarrow> R(x))\n  \\<longrightarrow> (\\<forall>x. P(x) \\<and> M(x) \\<longrightarrow> L(x))\\<close>\n  by blast\n\ntext\\<open>33\\<close>\nlemma\n  \\<open>(\\<forall>x. P(a) \\<and> (P(x) \\<longrightarrow> P(b)) \\<longrightarrow> P(c)) \\<longleftrightarrow>\n    (\\<forall>x. (\\<not> P(a) \\<or> P(x) \\<or> P(c)) \\<and> (\\<not> P(a) \\<or> \\<not> P(b) \\<or> P(c)))\\<close>\n  by blast\n\ntext\\<open>34. AMENDED (TWICE!!). Andrews's challenge.\\<close>\nlemma\n  \\<open>((\\<exists>x. \\<forall>y. p(x) \\<longleftrightarrow> p(y)) \\<longleftrightarrow> ((\\<exists>x. q(x)) \\<longleftrightarrow> (\\<forall>y. p(y)))) \\<longleftrightarrow>\n    ((\\<exists>x. \\<forall>y. q(x) \\<longleftrightarrow> q(y)) \\<longleftrightarrow> ((\\<exists>x. p(x)) \\<longleftrightarrow> (\\<forall>y. q(y))))\\<close>\n  by blast\n\ntext\\<open>35\\<close>\nlemma \\<open>\\<exists>x y. P(x,y) \\<longrightarrow> (\\<forall>u v. P(u,v))\\<close>\n  by blast\n\ntext\\<open>36\\<close>\nlemma\n  \\<open>(\\<forall>x. \\<exists>y. J(x,y)) \\<and>\n    (\\<forall>x. \\<exists>y. G(x,y)) \\<and>\n    (\\<forall>x y. J(x,y) \\<or> G(x,y) \\<longrightarrow> (\\<forall>z. J(y,z) \\<or> G(y,z) \\<longrightarrow> H(x,z)))\n  \\<longrightarrow> (\\<forall>x. \\<exists>y. H(x,y))\\<close>\n  by blast\n\ntext\\<open>37\\<close>\nlemma\n  \\<open>(\\<forall>z. \\<exists>w. \\<forall>x. \\<exists>y.\n    (P(x,z) \\<longrightarrow> P(y,w)) \\<and> P(y,z) \\<and> (P(y,w) \\<longrightarrow> (\\<exists>u. Q(u,w)))) \\<and>\n    (\\<forall>x z. \\<not> P(x,z) \\<longrightarrow> (\\<exists>y. Q(y,z))) \\<and>\n    ((\\<exists>x y. Q(x,y)) \\<longrightarrow> (\\<forall>x. R(x,x)))\n  \\<longrightarrow> (\\<forall>x. \\<exists>y. R(x,y))\\<close>\n  by blast\n\ntext\\<open>38\\<close>\nlemma\n  \\<open>(\\<forall>x. p(a) \\<and> (p(x) \\<longrightarrow> (\\<exists>y. p(y) \\<and> r(x,y))) \\<longrightarrow>\n    (\\<exists>z. \\<exists>w. p(z) \\<and> r(x,w) \\<and> r(w,z)))  \\<longleftrightarrow>\n    (\\<forall>x. (\\<not> p(a) \\<or> p(x) \\<or> (\\<exists>z. \\<exists>w. p(z) \\<and> r(x,w) \\<and> r(w,z))) \\<and>\n      (\\<not> p(a) \\<or> \\<not> (\\<exists>y. p(y) \\<and> r(x,y)) \\<or>\n      (\\<exists>z. \\<exists>w. p(z) \\<and> r(x,w) \\<and> r(w,z))))\\<close>\n  by blast\n\ntext\\<open>39\\<close>\nlemma \\<open>\\<not> (\\<exists>x. \\<forall>y. F(y,x) \\<longleftrightarrow> \\<not> F(y,y))\\<close>\n  by blast\n\ntext\\<open>40. AMENDED\\<close>\nlemma\n  \\<open>(\\<exists>y. \\<forall>x. F(x,y) \\<longleftrightarrow> F(x,x)) \\<longrightarrow>\n    \\<not> (\\<forall>x. \\<exists>y. \\<forall>z. F(z,y) \\<longleftrightarrow> \\<not> F(z,x))\\<close>\n  by blast\n\ntext\\<open>41\\<close>\nlemma\n  \\<open>(\\<forall>z. \\<exists>y. \\<forall>x. f(x,y) \\<longleftrightarrow> f(x,z) \\<and> \\<not> f(x,x))\n    \\<longrightarrow> \\<not> (\\<exists>z. \\<forall>x. f(x,z))\\<close>\n  by blast\n\ntext\\<open>42\\<close>\nlemma \\<open>\\<not> (\\<exists>y. \\<forall>x. p(x,y) \\<longleftrightarrow> \\<not> (\\<exists>z. p(x,z) \\<and> p(z,x)))\\<close>\n  by blast\n\ntext\\<open>43\\<close>\nlemma\n  \\<open>(\\<forall>x. \\<forall>y. q(x,y) \\<longleftrightarrow> (\\<forall>z. p(z,x) \\<longleftrightarrow> p(z,y)))\n    \\<longrightarrow> (\\<forall>x. \\<forall>y. q(x,y) \\<longleftrightarrow> q(y,x))\\<close>\n  by blast\n\ntext \\<open>\n  Other proofs: Can use \\<open>auto\\<close>, which cheats by using rewriting!\n  \\<open>Deepen_tac\\<close> alone requires 253 secs.  Or\n  \\<open>by (mini_tac 1 THEN Deepen_tac 5 1)\\<close>.\n\\<close>\n\ntext\\<open>44\\<close>\nlemma\n  \\<open>(\\<forall>x. f(x) \\<longrightarrow> (\\<exists>y. g(y) \\<and> h(x,y) \\<and> (\\<exists>y. g(y) \\<and> \\<not> h(x,y)))) \\<and>\n    (\\<exists>x. j(x) \\<and> (\\<forall>y. g(y) \\<longrightarrow> h(x,y)))\n  \\<longrightarrow> (\\<exists>x. j(x) \\<and> \\<not> f(x))\\<close>\n  by blast\n\ntext\\<open>45\\<close>\nlemma\n  \\<open>(\\<forall>x. f(x) \\<and> (\\<forall>y. g(y) \\<and> h(x,y) \\<longrightarrow> j(x,y))\n      \\<longrightarrow> (\\<forall>y. g(y) \\<and> h(x,y) \\<longrightarrow> k(y))) \\<and>\n      \\<not> (\\<exists>y. l(y) \\<and> k(y)) \\<and>\n      (\\<exists>x. f(x) \\<and> (\\<forall>y. h(x,y) \\<longrightarrow> l(y)) \\<and> (\\<forall>y. g(y) \\<and> h(x,y) \\<longrightarrow> j(x,y)))\n      \\<longrightarrow> (\\<exists>x. f(x) \\<and> \\<not> (\\<exists>y. g(y) \\<and> h(x,y)))\\<close>\n  by blast\n\n\ntext\\<open>46\\<close>\nlemma\n  \\<open>(\\<forall>x. f(x) \\<and> (\\<forall>y. f(y) \\<and> h(y,x) \\<longrightarrow> g(y)) \\<longrightarrow> g(x)) \\<and>\n      ((\\<exists>x. f(x) \\<and> \\<not> g(x)) \\<longrightarrow>\n       (\\<exists>x. f(x) \\<and> \\<not> g(x) \\<and> (\\<forall>y. f(y) \\<and> \\<not> g(y) \\<longrightarrow> j(x,y)))) \\<and>\n      (\\<forall>x y. f(x) \\<and> f(y) \\<and> h(x,y) \\<longrightarrow> \\<not> j(y,x))\n      \\<longrightarrow> (\\<forall>x. f(x) \\<longrightarrow> g(x))\\<close>\n  by blast\n\n\nsubsection \\<open>Problems (mainly) involving equality or functions\\<close>\n\ntext\\<open>48\\<close>\nlemma \\<open>(a = b \\<or> c = d) \\<and> (a = c \\<or> b = d) \\<longrightarrow> a = d \\<or> b = c\\<close>\n  by blast\n\ntext\\<open>49. NOT PROVED AUTOMATICALLY. Hard because it involves substitution for\n  Vars; the type constraint ensures that x,y,z have the same type as a,b,u.\\<close>\nlemma\n  \\<open>(\\<exists>x y::'a. \\<forall>z. z = x \\<or> z = y) \\<and> P(a) \\<and> P(b) \\<and> a \\<noteq> b \\<longrightarrow> (\\<forall>u::'a. P(u))\\<close>\n  apply safe\n  apply (rule_tac x = \\<open>a\\<close> in allE, assumption)\n  apply (rule_tac x = \\<open>b\\<close> in allE, assumption)\n  apply fast  \\<comment> \\<open>blast's treatment of equality can't do it\\<close>\n  done\n\ntext\\<open>50. (What has this to do with equality?)\\<close>\nlemma \\<open>(\\<forall>x. P(a,x) \\<or> (\\<forall>y. P(x,y))) \\<longrightarrow> (\\<exists>x. \\<forall>y. P(x,y))\\<close>\n  by blast\n\ntext\\<open>51\\<close>\nlemma\n  \\<open>(\\<exists>z w. \\<forall>x y. P(x,y) \\<longleftrightarrow> (x = z \\<and> y = w)) \\<longrightarrow>\n    (\\<exists>z. \\<forall>x. \\<exists>w. (\\<forall>y. P(x,y) \\<longleftrightarrow> y=w) \\<longleftrightarrow> x = z)\\<close>\n  by blast\n\ntext\\<open>52\\<close>\ntext\\<open>Almost the same as 51.\\<close>\nlemma\n  \\<open>(\\<exists>z w. \\<forall>x y. P(x,y) \\<longleftrightarrow> (x = z \\<and> y = w)) \\<longrightarrow>\n    (\\<exists>w. \\<forall>y. \\<exists>z. (\\<forall>x. P(x,y) \\<longleftrightarrow> x = z) \\<longleftrightarrow> y = w)\\<close>\n  by blast\n\ntext\\<open>55\\<close>\ntext\\<open>Non-equational version, from Manthey and Bry, CADE-9 (Springer, 1988).\n  fast DISCOVERS who killed Agatha.\\<close>\nschematic_goal\n  \\<open>lives(agatha) \\<and> lives(butler) \\<and> lives(charles) \\<and>\n   (killed(agatha,agatha) \\<or> killed(butler,agatha) \\<or> killed(charles,agatha)) \\<and>\n   (\\<forall>x y. killed(x,y) \\<longrightarrow> hates(x,y) \\<and> \\<not> richer(x,y)) \\<and>\n   (\\<forall>x. hates(agatha,x) \\<longrightarrow> \\<not> hates(charles,x)) \\<and>\n   (hates(agatha,agatha) \\<and> hates(agatha,charles)) \\<and>\n   (\\<forall>x. lives(x) \\<and> \\<not> richer(x,agatha) \\<longrightarrow> hates(butler,x)) \\<and>\n   (\\<forall>x. hates(agatha,x) \\<longrightarrow> hates(butler,x)) \\<and>\n   (\\<forall>x. \\<not> hates(x,agatha) \\<or> \\<not> hates(x,butler) \\<or> \\<not> hates(x,charles)) \\<longrightarrow>\n    killed(?who,agatha)\\<close>\n  by fast  \\<comment> \\<open>MUCH faster than blast\\<close>\n\n\ntext\\<open>56\\<close>\nlemma \\<open>(\\<forall>x. (\\<exists>y. P(y) \\<and> x = f(y)) \\<longrightarrow> P(x)) \\<longleftrightarrow> (\\<forall>x. P(x) \\<longrightarrow> P(f(x)))\\<close>\n  by blast\n\ntext\\<open>57\\<close>\nlemma\n  \\<open>P(f(a,b), f(b,c)) \\<and> P(f(b,c), f(a,c)) \\<and>\n    (\\<forall>x y z. P(x,y) \\<and> P(y,z) \\<longrightarrow> P(x,z)) \\<longrightarrow> P(f(a,b), f(a,c))\\<close>\n  by blast\n\ntext\\<open>58  NOT PROVED AUTOMATICALLY\\<close>\nlemma \\<open>(\\<forall>x y. f(x) = g(y)) \\<longrightarrow> (\\<forall>x y. f(f(x)) = f(g(y)))\\<close>\n  by (slow elim: subst_context)\n\n\ntext\\<open>59\\<close>\nlemma \\<open>(\\<forall>x. P(x) \\<longleftrightarrow> \\<not> P(f(x))) \\<longrightarrow> (\\<exists>x. P(x) \\<and> \\<not> P(f(x)))\\<close>\n  by blast\n\ntext\\<open>60\\<close>\nlemma \\<open>\\<forall>x. P(x,f(x)) \\<longleftrightarrow> (\\<exists>y. (\\<forall>z. P(z,y) \\<longrightarrow> P(z,f(x))) \\<and> P(x,y))\\<close>\n  by blast\n\ntext\\<open>62 as corrected in JAR 18 (1997), page 135\\<close>\nlemma\n  \\<open>(\\<forall>x. p(a) \\<and> (p(x) \\<longrightarrow> p(f(x))) \\<longrightarrow> p(f(f(x)))) \\<longleftrightarrow>\n    (\\<forall>x. (\\<not> p(a) \\<or> p(x) \\<or> p(f(f(x)))) \\<and>\n      (\\<not> p(a) \\<or> \\<not> p(f(x)) \\<or> p(f(f(x)))))\\<close>\n  by blast\n\ntext \\<open>From Davis, Obvious Logical Inferences, IJCAI-81, 530-531\n  fast indeed copes!\\<close>\nlemma\n  \\<open>(\\<forall>x. F(x) \\<and> \\<not> G(x) \\<longrightarrow> (\\<exists>y. H(x,y) \\<and> J(y))) \\<and>\n    (\\<exists>x. K(x) \\<and> F(x) \\<and> (\\<forall>y. H(x,y) \\<longrightarrow> K(y))) \\<and>\n    (\\<forall>x. K(x) \\<longrightarrow> \\<not> G(x)) \\<longrightarrow> (\\<exists>x. K(x) \\<and> J(x))\\<close>\n  by fast\n\ntext \\<open>From Rudnicki, Obvious Inferences, JAR 3 (1987), 383-393.\n  It does seem obvious!\\<close>\nlemma\n  \\<open>(\\<forall>x. F(x) \\<and> \\<not> G(x) \\<longrightarrow> (\\<exists>y. H(x,y) \\<and> J(y))) \\<and>\n    (\\<exists>x. K(x) \\<and> F(x) \\<and> (\\<forall>y. H(x,y) \\<longrightarrow> K(y))) \\<and>\n    (\\<forall>x. K(x) \\<longrightarrow> \\<not> G(x)) \\<longrightarrow> (\\<exists>x. K(x) \\<longrightarrow> \\<not> G(x))\\<close>\n  by fast\n\ntext \\<open>Halting problem: Formulation of Li Dafa (AAR Newsletter 27, Oct 1994.)\n  author U. Egly.\\<close>\nlemma\n  \\<open>((\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z)))) \\<longrightarrow>\n     (\\<exists>w. C(w) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(w,y,z)))))\n    \\<and>\n    (\\<forall>w. C(w) \\<and> (\\<forall>u. C(u) \\<longrightarrow> (\\<forall>v. D(w,u,v))) \\<longrightarrow>\n          (\\<forall>y z.\n              (C(y) \\<and> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,g)) \\<and>\n              (C(y) \\<and> \\<not> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,b))))\n    \\<and>\n    (\\<forall>w. C(w) \\<and>\n      (\\<forall>y z.\n          (C(y) \\<and> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,g)) \\<and>\n          (C(y) \\<and> \\<not> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,b))) \\<longrightarrow>\n      (\\<exists>v. C(v) \\<and>\n            (\\<forall>y. ((C(y) \\<and> Q(w,y,y)) \\<and> OO(w,g) \\<longrightarrow> \\<not> P(v,y)) \\<and>\n                    ((C(y) \\<and> Q(w,y,y)) \\<and> OO(w,b) \\<longrightarrow> P(v,y) \\<and> OO(v,b)))))\n     \\<longrightarrow> \\<not> (\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z))))\\<close>\n  by (blast 12)\n    \\<comment> \\<open>Needed because the search for depths below 12 is very slow.\\<close>\n\n\ntext \\<open>\n  Halting problem II: credited to M. Bruschi by Li Dafa in JAR 18(1),\n  p. 105.\n\\<close>\nlemma\n  \\<open>((\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z)))) \\<longrightarrow>\n     (\\<exists>w. C(w) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(w,y,z)))))\n    \\<and>\n    (\\<forall>w. C(w) \\<and> (\\<forall>u. C(u) \\<longrightarrow> (\\<forall>v. D(w,u,v))) \\<longrightarrow>\n          (\\<forall>y z.\n              (C(y) \\<and> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,g)) \\<and>\n              (C(y) \\<and> \\<not> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,b))))\n    \\<and>\n    ((\\<exists>w. C(w) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> Q(w,y,y) \\<and> OO(w,g)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> Q(w,y,y) \\<and> OO(w,b))))\n     \\<longrightarrow>\n     (\\<exists>v. C(v) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,g)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,b)))))\n    \\<longrightarrow>\n    ((\\<exists>v. C(v) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,g)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,b))))\n     \\<longrightarrow>\n     (\\<exists>u. C(u) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> \\<not> P(u,y)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> P(u,y) \\<and> OO(u,b)))))\n     \\<longrightarrow> \\<not> (\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z))))\\<close>\n  by blast\n\ntext \\<open>Challenge found on info-hol.\\<close>\nlemma \\<open>\\<forall>x. \\<exists>v w. \\<forall>y z. P(x) \\<and> Q(y) \\<longrightarrow> (P(v) \\<or> R(w)) \\<and> (R(z) \\<longrightarrow> Q(v))\\<close>\n  by blast\n\ntext \\<open>\n  Attributed to Lewis Carroll by S. G. Pulman. The first or last assumption\n  can be deleted.\\<close>\nlemma\n  \\<open>(\\<forall>x. honest(x) \\<and> industrious(x) \\<longrightarrow> healthy(x)) \\<and>\n    \\<not> (\\<exists>x. grocer(x) \\<and> healthy(x)) \\<and>\n    (\\<forall>x. industrious(x) \\<and> grocer(x) \\<longrightarrow> honest(x)) \\<and>\n    (\\<forall>x. cyclist(x) \\<longrightarrow> industrious(x)) \\<and>\n    (\\<forall>x. \\<not> healthy(x) \\<and> cyclist(x) \\<longrightarrow> \\<not> honest(x))\n    \\<longrightarrow> (\\<forall>x. grocer(x) \\<longrightarrow> \\<not> cyclist(x))\\<close>\n  by blast\n\n\n(*Runtimes for old versions of this file:\nThu Jul 23 1992: loaded in 467s using iffE [on SPARC2]\nMon Nov 14 1994: loaded in 144s [on SPARC10, with deepen_tac]\nWed Nov 16 1994: loaded in 138s [after addition of norm_term_skip]\nMon Nov 21 1994: loaded in 131s [DEPTH_FIRST suppressing repetitions]\n\nFurther runtimes on a Sun-4\nTue Mar  4 1997: loaded in 93s (version 94-7)\nTue Mar  4 1997: loaded in 89s\nThu Apr  3 1997: loaded in 44s--using mostly Blast_tac\nThu Apr  3 1997: loaded in 96s--addition of two Halting Probs\nThu Apr  3 1997: loaded in 98s--using lim-1 for all haz rules\nTue Dec  2 1997: loaded in 107s--added 46; new equalSubst\nFri Dec 12 1997: loaded in 91s--faster proof reconstruction\nThu Dec 18 1997: loaded in 94s--two new \"obvious theorems\" (??)\n*)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/FOL/ex/Classical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7696421779175326}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_rotate_structural_mod\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"'a list => 'a list => 'a list\" where\n\"x (nil2) z = z\"\n| \"x (cons2 z2 xs) z = cons2 z2 (x xs z)\"\n\nfun rotate :: \"Nat => 'a list => 'a list\" where\n\"rotate (Z) z = z\"\n| \"rotate (S z2) (nil2) = nil2\"\n| \"rotate (S z2) (cons2 z22 xs1) =\n     rotate z2 (x xs1 (cons2 z22 (nil2)))\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) z = z\"\n| \"plus (S z2) z = S (plus z2 z)\"\n\nfun minus :: \"Nat => Nat => Nat\" where\n\"minus (Z) z = Z\"\n| \"minus (S z2) (S y2) = minus z2 y2\"\n\nfun length :: \"'a list => Nat\" where\n\"length (nil2) = Z\"\n| \"length (cons2 z l) = plus (S Z) (length l)\"\n\nfun le :: \"Nat => Nat => bool\" where\n\"le (Z) z = True\"\n| \"le (S z2) (Z) = False\"\n| \"le (S z2) (S x2) = le z2 x2\"\n\nfun take :: \"Nat => 'a list => 'a list\" where\n\"take y z =\n   (if le y Z then nil2 else\n      (case z of\n         nil2 => nil2\n         | cons2 z2 xs => (case y of S x2 => cons2 z2 (take x2 xs))))\"\n\nfun go :: \"Nat => Nat => Nat => Nat\" where\n\"go y z (Z) = Z\"\n| \"go (Z) (Z) (S x2) = Z\"\n| \"go (Z) (S x5) (S x2) = minus (S x2) (S x5)\"\n| \"go (S x3) (Z) (S x2) = go x3 x2 (S x2)\"\n| \"go (S x3) (S x4) (S x2) = go x3 x4 (S x2)\"\n\nfun modstructural :: \"Nat => Nat => Nat\" where\n\"modstructural y z = go y Z z\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n\"drop y z =\n   (if le y Z then z else\n      (case z of\n         nil2 => nil2\n         | cons2 z2 xs1 => (case y of S x2 => drop x2 xs1)))\"\n\ntheorem property0 :\n  \"((rotate n xs) =\n      (x (drop (modstructural n (length xs)) xs)\n         (take (modstructural n (length xs)) xs)))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_rotate_structural_mod.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8244619242200081, "lm_q1q2_score": 0.7695781656411804}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Skew Heap Analysis\"\n\ntheory Skew_Heap_Analysis\nimports\n  Complex_Main\n  Skew_Heap.Skew_Heap\n  Amortized_Framework\n  Priority_Queue_ops_merge\nbegin\n\ntext\\<open>The following proof is a simplified version of the one by Kaldewaij and\nSchoenmakers~\\cite{KaldewaijS-IPL91}.\\<close>\n\ntext \\<open>right-heavy:\\<close>\ndefinition rh :: \"'a tree => 'a tree => nat\" where\n\"rh l r = (if size l < size r then 1 else 0)\"\n\ntext \\<open>Function \\<open>\\<Gamma>\\<close> in \\cite{KaldewaijS-IPL91}: number of right-heavy nodes on left spine.\\<close>\nfun lrh :: \"'a tree \\<Rightarrow> nat\" where\n\"lrh Leaf = 0\" |\n\"lrh (Node l _ r) = rh l r + lrh l\"\n\ntext \\<open>Function \\<open>\\<Delta>\\<close> in \\cite{KaldewaijS-IPL91}: number of not-right-heavy nodes on right spine.\\<close>\nfun rlh :: \"'a tree \\<Rightarrow> nat\" where\n\"rlh Leaf = 0\" |\n\"rlh (Node l _ r) = (1 - rh l r) + rlh r\"\n\nlemma Gexp: \"2 ^ lrh t \\<le> size t + 1\"\nby (induction t) (auto simp: rh_def)\n\ncorollary Glog: \"lrh t \\<le> log 2 (size1 t)\"\nby (metis Gexp le_log2_of_power size1_size)\n\nlemma Dexp: \"2 ^ rlh t \\<le> size t + 1\"\nby (induction t) (auto simp: rh_def)\n\ncorollary Dlog: \"rlh t \\<le> log 2 (size1 t)\"\nby (metis Dexp le_log2_of_power size1_size)\n\nfunction T_merge :: \"'a::linorder tree \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n\"T_merge Leaf t = 1\" |\n\"T_merge t Leaf = 1\" |\n\"T_merge (Node l1 a1 r1) (Node l2 a2 r2) =\n   (if a1 \\<le> a2 then T_merge (Node l2 a2 r2) r1 else T_merge (Node l1 a1 r1) r2) + 1\"\nby pat_completeness auto\ntermination\nby (relation \"measure (\\<lambda>(x, y). size x + size y)\") auto\n\nfun \\<Phi> :: \"'a tree \\<Rightarrow> int\" where\n\"\\<Phi> Leaf = 0\" |\n\"\\<Phi> (Node l _ r) = \\<Phi> l + \\<Phi> r + rh l r\"\n\nlemma \\<Phi>_nneg: \"\\<Phi> t \\<ge> 0\"\nby (induction t) auto\n\nlemma plus_log_le_2log_plus: \"\\<lbrakk> x > 0; y > 0; b > 1 \\<rbrakk>\n  \\<Longrightarrow> log b x + log b y \\<le> 2 * log b (x + y)\"\nby(subst mult_2; rule add_mono; auto)\n\nlemma rh1: \"rh l r \\<le> 1\"\nby(simp add: rh_def)\n\nlemma amor_le_long:\n  \"T_merge t1 t2 + \\<Phi> (merge t1 t2) - \\<Phi> t1 - \\<Phi> t2 \\<le>\n   lrh(merge t1 t2) + rlh t1 + rlh t2 + 1\"\nproof (induction t1 t2 rule: merge.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 l1 a1 r1 l2 a2 r2)\n  show ?case\n  proof (cases \"a1 \\<le> a2\")\n    case True\n    let ?t1 = \"Node l1 a1 r1\" let ?t2 = \"Node l2 a2 r2\" let ?m = \"merge ?t2 r1\"\n    have \"T_merge ?t1 ?t2 + \\<Phi> (merge ?t1 ?t2) - \\<Phi> ?t1 - \\<Phi> ?t2\n          = T_merge ?t2 r1 + 1 + \\<Phi> ?m + \\<Phi> l1 + rh ?m l1 - \\<Phi> ?t1 - \\<Phi> ?t2\"\n      using True by (simp)\n    also have \"\\<dots> = T_merge ?t2 r1 + 1 + \\<Phi> ?m + rh ?m l1 - \\<Phi> r1 - rh l1 r1 - \\<Phi> ?t2\"\n      by simp\n    also have \"\\<dots> \\<le> lrh ?m + rlh ?t2 + rlh r1 + rh ?m l1 + 2 - rh l1 r1\"\n      using \"3.IH\"(1)[OF True] by linarith\n    also have \"\\<dots> = lrh ?m + rlh ?t2 + rlh r1 + rh ?m l1 + 1 + (1 - rh l1 r1)\"\n      using rh1[of l1 r1] by (simp)\n    also have \"\\<dots> = lrh ?m + rlh ?t2 + rlh ?t1 + rh ?m l1 + 1\"\n      by (simp)\n    also have \"\\<dots> = lrh (merge ?t1 ?t2) + rlh ?t1 + rlh ?t2 + 1\"\n      using True by(simp)\n    finally show ?thesis .\n  next\n    case False with 3 show ?thesis by auto\n  qed\nqed\n\nlemma amor_le:\n  \"T_merge t1 t2 + \\<Phi> (merge t1 t2) - \\<Phi> t1 - \\<Phi> t2 \\<le>\n   lrh(merge t1 t2) + rlh t1 + rlh t2 + 1\"\nby(induction t1 t2 rule: merge.induct)(auto)\n\nlemma a_merge:\n  \"T_merge t1 t2 + \\<Phi>(merge t1 t2) - \\<Phi> t1 - \\<Phi> t2 \\<le>\n   3 * log 2 (size1 t1 + size1 t2) + 1\" (is \"?l \\<le> _\")\nproof -\n  have \"?l \\<le> lrh(merge t1 t2) + rlh t1 + rlh t2 + 1\" using amor_le[of t1 t2] by arith\n  also have \"\\<dots> = real(lrh(merge t1 t2)) + rlh t1 + rlh t2 + 1\" by simp\n  also have \"\\<dots> = real(lrh(merge t1 t2)) + (real(rlh t1) + rlh t2) + 1\" by simp\n  also have \"rlh t1 \\<le> log 2 (size1 t1)\" by(rule Dlog)\n  also have \"rlh t2 \\<le> log 2 (size1 t2)\" by(rule Dlog)\n  also have \"lrh (merge t1 t2) \\<le> log 2 (size1(merge t1 t2))\" by(rule Glog)\n  also have \"size1(merge t1 t2) = size1 t1 + size1 t2 - 1\" by(simp add: size1_size size_merge)\n  also have \"log 2 (size1 t1 + size1 t2 - 1) \\<le> log 2 (size1 t1 + size1 t2)\" by(simp add: size1_size)\n  also have \"log 2 (size1 t1) + log 2 (size1 t2) \\<le> 2 * log 2 (real(size1 t1) + (size1 t2))\"\n    by(rule plus_log_le_2log_plus) (auto simp: size1_size)\n  finally show ?thesis by(simp)\nqed\n\ndefinition T_insert :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> int\" where\n\"T_insert a t = T_merge (Node Leaf a Leaf) t + 1\"\n\nlemma a_insert: \"T_insert a t + \\<Phi>(skew_heap.insert a t) - \\<Phi> t \\<le> 3 * log 2 (size1 t + 2) + 2\"\nusing a_merge[of \"Node Leaf a Leaf\" \"t\"]\nby (simp add: numeral_eq_Suc T_insert_def rh_def)\n\ndefinition T_del_min :: \"('a::linorder) tree \\<Rightarrow> int\" where\n\"T_del_min t = (case t of Leaf \\<Rightarrow> 1 | Node t1 a t2 \\<Rightarrow> T_merge t1 t2 + 1)\"\n\nlemma a_del_min: \"T_del_min t + \\<Phi>(skew_heap.del_min t) - \\<Phi> t \\<le> 3 * log 2 (size1 t + 2) + 2\"\nproof (cases t)\n  case Leaf thus ?thesis by (simp add: T_del_min_def)\nnext\n  case (Node t1 _ t2)\n  have [arith]: \"log 2 (2 + (real (size t1) + real (size t2))) \\<le>\n                log 2 (4 + (real (size t1) + real (size t2)))\" by simp\n  from Node show ?thesis using a_merge[of t1 t2]\n    by (simp add: size1_size T_del_min_def rh_def)\nqed\n\n\nsubsubsection \"Instantiation of Amortized Framework\"\n\nlemma T_merge_nneg: \"T_merge t1 t2 \\<ge> 0\"\nby(induction t1 t2 rule: T_merge.induct) auto\n\nfun exec :: \"'a::linorder op \\<Rightarrow> 'a tree list \\<Rightarrow> 'a tree\" where\n\"exec Empty [] = Leaf\" |\n\"exec (Insert a) [t] = skew_heap.insert a t\" |\n\"exec Del_min [t] = skew_heap.del_min t\" |\n\"exec Merge [t1,t2] = merge t1 t2\"\n\nfun cost :: \"'a::linorder op \\<Rightarrow> 'a tree list \\<Rightarrow> nat\" where\n\"cost Empty [] = 1\" |\n\"cost (Insert a) [t] = T_merge (Node Leaf a Leaf) t + 1\" |\n\"cost Del_min [t] = (case t of Leaf \\<Rightarrow> 1 | Node t1 a t2 \\<Rightarrow> T_merge t1 t2 + 1)\" |\n\"cost Merge [t1,t2] = T_merge t1 t2\"\n\nfun U where\n\"U Empty [] = 1\" |\n\"U (Insert _) [t] = 3 * log 2 (size1 t + 2) + 2\" |\n\"U Del_min [t] = 3 * log 2 (size1 t + 2) + 2\" |\n\"U Merge [t1,t2] = 3 * log 2 (size1 t1 + size1 t2) + 1\"\n\ninterpretation Amortized\nwhere arity = arity and exec = exec and inv = \"\\<lambda>_. True\"\nand cost = cost and \\<Phi> = \\<Phi> and U = U\nproof (standard, goal_cases)\n  case 1 show ?case by simp\nnext\n  case (2 t) show ?case using \\<Phi>_nneg[of t] by linarith\nnext\n  case (3 ss f)\n  show ?case\n  proof (cases f)\n    case Empty thus ?thesis using 3(2) by (auto)\n  next\n    case [simp]: (Insert a)\n    obtain t where [simp]: \"ss = [t]\" using 3(2) by (auto)\n    thus ?thesis using a_merge[of \"Node Leaf a Leaf\" \"t\"]\n      by (simp add: numeral_eq_Suc insert_def rh_def T_merge_nneg)\n  next\n    case [simp]: Del_min\n    obtain t where [simp]: \"ss = [t]\" using 3(2) by (auto)\n    thus ?thesis\n    proof (cases t)\n      case Leaf with Del_min show ?thesis by simp\n    next\n      case (Node t1 _ t2)\n      have [arith]: \"log 2 (2 + (real (size t1) + real (size t2))) \\<le>\n               log 2 (4 + (real (size t1) + real (size t2)))\" by simp\n      from Del_min Node show ?thesis using a_merge[of t1 t2]\n        by (simp add: size1_size T_merge_nneg)\n    qed\n  next\n    case [simp]: Merge\n    obtain t1 t2 where \"ss = [t1,t2]\" using 3(2) by (auto simp: numeral_eq_Suc)\n    thus ?thesis using a_merge[of t1 t2] by (simp add: T_merge_nneg)\n  qed\nqed\n\nend\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Amortized_Complexity/Skew_Heap_Analysis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308147331957, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7695781656411804}}
{"text": "theory ex_3_1\n  imports Main\nbegin\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\nfun set::\"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\" |\n\"set (Node l a r) = {a} \\<union> (set l) \\<union> (set r)\"\n\n(* true \\<longrightarrow> isLeft *)\nfun isOrdered::\"int \\<Rightarrow> bool \\<Rightarrow> int tree \\<Rightarrow> bool\" where\n\"isOrdered _ _ Tip = True\" |\n\"isOrdered parent True (Node _ child _) = (child \\<le> parent)\" |\n\"isOrdered parent False (Node _ child _) = (parent \\<le> child)\"\n\nfun ord::\"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node l a r) = (isOrdered a True l \n                   \\<and> isOrdered a False r \n                   \\<and> ord l \\<and> ord r)\"\n\nfun ins::\"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins x Tip = Node Tip x Tip\" |\n\"ins x (Node l a r) = (if x = a then (Node l a r) \n                 else (if x < a then (Node (ins x l) a r)\n                                else (Node l a (ins x r))))\"\n\ntheorem inserted:\"set (ins x t) = {x} \\<union> set t\"\n  apply (induction t)\n  by (auto)\n\nlemma isOrdered_ins_l:\"\\<lbrakk>i < a; isOrdered a True t\\<rbrakk> \\<Longrightarrow> isOrdered a True (ins i t)\"\n  apply (induction t)\n  by (auto)\n\nlemma isOrdered_ins_r:\"\\<lbrakk>i > a; isOrdered a False t\\<rbrakk> \\<Longrightarrow> isOrdered a False (ins i t)\"\n  apply (induction t)\n  by (auto)\n\ntheorem still_ordered:\"ord t \\<Longrightarrow> ord(ins i t)\"\n  apply (induction t)\n  apply (auto)\n  apply (rule isOrdered_ins_l)\n  apply (auto)\n  apply (rule isOrdered_ins_r)\n  by (auto)\nend", "meta": {"author": "20051615", "repo": "Gale-Shapley-formalization", "sha": "d601131b66c039561f8a72cd4913fcf8c84f08fa", "save_path": "github-repos/isabelle/20051615-Gale-Shapley-formalization", "path": "github-repos/isabelle/20051615-Gale-Shapley-formalization/Gale-Shapley-formalization-d601131b66c039561f8a72cd4913fcf8c84f08fa/tutorials/prog-prove/ex_3_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7694574988288447}}
{"text": "theory Chapter2\n  imports Main\nbegin\n\n(* Exercise 2.1 *)\n\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(* Exercise 2.2 *)\n\ndatatype mynat = Z | S mynat\n\nfun add :: \"mynat \\<Rightarrow> mynat \\<Rightarrow> mynat\" where\n\"add Z m = m\" |\n\"add (S n) m = S (add n m)\"\n\ntheorem add_assoc [simp]: \"add (add x y) z = add x (add y z)\"\n  apply(induction x)\n  apply(auto)\ndone\n\nlemma add_Zright [simp]: \"add x Z = x\"\n  apply(induction x)\n  apply(auto)\ndone\n\nlemma add_Sright [simp]: \"add x (S y) = S (add x y)\"\n  apply(induction x)\n  apply(auto)\ndone\n\ntheorem add_comm [simp]: \"add x y = add y x\"\n  apply(induction x)\n  apply(auto)\ndone\n\nfun double :: \"mynat \\<Rightarrow> mynat\" where\n\"double Z = Z\" |\n\"double (S n) = S ( S ( double n))\"\n\ntheorem double_m_eq_add_m_m: \"double m = add m m\"\n  apply(induction m)\n  apply(auto)\ndone\n\n(* Exercise 2.3 *)\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count n [] = 0\" |\n\"count n (x#xs) = (if n = x then 1 else 0) + (count n xs)\"\n\ntheorem count_lte_length: \"count x xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\ndone\n\n(* Exercise 2.4 *)\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] e = [e]\" |\n\"snoc (x#xs) e = x#(snoc xs e)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\" |\n\"reverse (x#xs) = snoc (reverse xs) x\"\n\nlemma reverse_snoc [simp]: \"reverse (snoc xs x) = x#(reverse xs)\"\n  apply(induction xs)\n  apply(auto)\ndone\n\ntheorem reverse_reverse [simp]: \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n  apply(auto)\ndone\n\n(* Exercise 2.5 *)\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\" |\n\"sum_upto (Suc n) = (Suc n) + (sum_upto n)\"\n\ntheorem sum_upto_n [simp]: \"sum_upto n = n * (n + 1) div 2\"\n  apply(induction n)\n  apply(auto)\ndone\n\n(* Exercise 2.6 *)\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l a r) = (contents l)@[a]@(contents r)\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l a r) = (sum_tree l) + a + (sum_tree r)\"\n\ntheorem sum_tree_eq_sum_list_contents : \"sum_tree t = sum_list (contents t)\"\n  apply(induction t)\n  apply(auto)\ndone\n\n(* Exercise 2.7 *)\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l a r) = Node (mirror r) a (mirror l)\"\n\nfun pre_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"pre_order Tip = []\" |\n\"pre_order (Node l a r) = a#(pre_order l)@(pre_order r)\"\n\nfun post_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"post_order Tip = []\" |\n\"post_order (Node l a r) = (post_order l)@(post_order r)@[a]\"\n\ntheorem pre_order_mirror_eq_rev_post_order : \"pre_order (mirror t) = rev (post_order t)\"\n  apply(induction t)\n  apply(auto)\ndone\n\n(* Exercise 2.8 *)\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse _ [] = []\" |\n\"intersperse _ [x] = [x]\" |\n\"intersperse a (x#xs) = a#x#xs\"\n\ntheorem map_f_intersperse_eq_intersperse_map_f : \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction xs rule: intersperse.induct)\n  apply(auto)\ndone\n\n(* Exercise 2.9 *)\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 n = n\" |\n\"itadd (Suc m) n = itadd m (Suc n)\"\n\ntheorem itadd_eq_add : \"itadd m n = m + n\"\n  apply(induction m arbitrary: n)\n  apply(auto)\ndone\n\n(* Exercise 2.10 *)\n\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n  \"explode 0 t = t\" |\n  \"explode (Suc n) t = explode n (Node t t)\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Tip = 1\" |\n  \"nodes (Node l r) = 1 + (nodes l) + (nodes r)\"\n\ntheorem nodes_explode : \"nodes (explode n t) = 2^n * (1 + nodes t) - 1\"\n  apply(induction n arbitrary: t)\n  apply(auto simp add: algebra_simps)\ndone\n\n(* Exercise 2.11 *)\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\" |\n\"eval (Const n) _ = n\" |\n\"eval (Add e1 e2) x = (eval e1 x) + (eval e2 x)\" |\n\"eval (Mult e1 e2) x = (eval e1 x) + (eval e2 x)\"\n\nfun evalp' :: \"int list \\<Rightarrow> int \\<Rightarrow> nat \\<Rightarrow> int\" where\n\"evalp' [] value order  = 0\" |\n\"evalp' (p#ps) value order = p * (value ^ order) + evalp' ps value (order + 1)\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp polynomial value  = evalp' polynomial value 0\"\n\nend", "meta": {"author": "abhishekc-sharma", "repo": "ConcreteSemantics", "sha": "16bbc7905c27c936898916b94608b6e77044f86e", "save_path": "github-repos/isabelle/abhishekc-sharma-ConcreteSemantics", "path": "github-repos/isabelle/abhishekc-sharma-ConcreteSemantics/ConcreteSemantics-16bbc7905c27c936898916b94608b6e77044f86e/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802462567087, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7693373846073104}}
{"text": "theory AExp imports Main begin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw\\<open>\\snip{AExpaexpdef}{2}{1}{%\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\ntext_raw\\<open>\\snip{AExpavaldef}{1}{2}{%\\<close>\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>\\noindent\n  We can now write a series of updates to the function \\<open>\\<lambda>x. 0\\<close> compactly:\n\\<close>\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext\\<open>Note that this \\<open><\\<dots>>\\<close> syntax works for any function space\n\\<open>\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\\<close> where \\<open>\\<tau>\\<^sub>2\\<close> has a \\<open>0\\<close>.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Evaluate constant subsexpressions:\\<close>\n\ntext_raw\\<open>\\snip{AExpasimpconstdef}{0}{2}{%\\<close>\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext\\<open>Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors:\\<close>\n\ntext_raw\\<open>\\snip{AExpplusdef}{0}{2}{%\\<close>\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw\\<open>\\snip{AExpasimpdef}{2}{0}{%\\<close>\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntext\\<open>Note that in \\<^const>\\<open>asimp_const\\<close> the optimized constructor was\ninlined. Making it a separate function \\<^const>\\<open>plus\\<close> improves modularity of\nthe code and the proofs.\\<close>\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend", "meta": {"author": "RinGotou", "repo": "Isabelle-Practice", "sha": "41fb1aff3b7a08e010055bd5c887480d09cbfa05", "save_path": "github-repos/isabelle/RinGotou-Isabelle-Practice", "path": "github-repos/isabelle/RinGotou-Isabelle-Practice/Isabelle-Practice-41fb1aff3b7a08e010055bd5c887480d09cbfa05/from_csem_book/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8670357494949105, "lm_q1q2_score": 0.7692381076263707}}
{"text": "theory Matrix_Util\n  imports \"HOL-Analysis.Analysis\"\nbegin\n\nsection \\<open>Matrices\\<close>\n\nproposition scalar_matrix_assoc':\n  fixes C :: \"('b::real_algebra_1)^'m^'n\"\n  shows \"k *\\<^sub>R (C ** D) = C ** (k *\\<^sub>R D)\"\n  by (simp add: matrix_matrix_mult_def sum_distrib_left mult_ac vec_eq_iff scaleR_sum_right)\n\nsubsection \\<open>Nonnegative Matrices\\<close>\n\nlemma nonneg_matrix_nonneg [dest]: \"0 \\<le> m \\<Longrightarrow> 0 \\<le> m $ i $ j\"\n  by (simp add: Finite_Cartesian_Product.less_eq_vec_def)\n\nlemma matrix_mult_mono: \n  assumes \"0 \\<le> E\" \"0 \\<le> C\" \"(E :: real^'c^'c) \\<le> B\" \"C \\<le> D\"\n  shows \"E ** C \\<le> B ** D\"\n  using order.trans[OF assms(1) assms(3)] assms\n  unfolding Finite_Cartesian_Product.less_eq_vec_def\n  by (auto intro!: sum_mono mult_mono simp: matrix_matrix_mult_def)\n\nlemma nonneg_matrix_mult: \"0 \\<le> (C :: ('b::{field, ordered_ring})^_^_) \\<Longrightarrow> 0 \\<le> D \\<Longrightarrow> 0 \\<le> C ** D\"\n  unfolding Finite_Cartesian_Product.less_eq_vec_def\n  by (auto simp: matrix_matrix_mult_def intro!: sum_nonneg)\n\nlemma zero_le_mat_iff [simp]: \"0 \\<le> mat (x :: 'c :: {zero, order}) \\<longleftrightarrow> 0 \\<le> x\"\n  by (auto simp: Finite_Cartesian_Product.less_eq_vec_def mat_def)\n\nlemma nonneg_mat_ge_zero: \"0 \\<le> Q \\<Longrightarrow> 0 \\<le> v \\<Longrightarrow> 0 \\<le> Q *v (v :: real^'c)\"\n  unfolding Finite_Cartesian_Product.less_eq_vec_def\n  by (auto intro!: sum_nonneg simp: matrix_vector_mult_def)\n\nlemma nonneg_mat_mono: \"0 \\<le> Q \\<Longrightarrow> u \\<le> v \\<Longrightarrow> Q *v u \\<le> Q *v (v :: real^'c)\"\n  using nonneg_mat_ge_zero[of Q \"v - u\"]\n  by (simp add: vec.diff)\n\nlemma nonneg_mult_imp_nonneg_mat:\n  assumes \"\\<And>v. v \\<ge> 0 \\<Longrightarrow> X *v v \\<ge> 0\"\n  shows \"X \\<ge> (0 :: real ^ _ ^_)\"\nproof -\n  { assume \"\\<not> (0 \\<le> X)\"\n    then obtain i j where neg: \"X $ i $ j < 0\" \n      by (metis less_eq_vec_def not_le zero_index)\n    let ?v = \"\\<chi> k. if j = k then 1::real else 0\"\n    have \"(X *v ?v) $ i < 0\"\n      using neg\n      by (auto simp: matrix_vector_mult_def if_distrib cong: if_cong)\n    hence \"?v \\<ge> 0 \\<and> \\<not> ((X *v ?v) \\<ge> 0)\"\n      by (auto simp: less_eq_vec_def not_le)\n    hence \"\\<exists>v. v \\<ge> 0 \\<and> \\<not> X *v v \\<ge> 0\"\n      by blast\n  }\n  thus ?thesis\n    using assms by auto\nqed\n\nlemma nonneg_mat_iff:\n  \"(X \\<ge> (0 :: real ^ _ ^_)) \\<longleftrightarrow> (\\<forall>v. v \\<ge> 0 \\<longrightarrow> X *v v \\<ge> 0)\"\n  using nonneg_mat_ge_zero nonneg_mult_imp_nonneg_mat by auto\n\nlemma mat_le_iff: \"(X \\<le> Y) \\<longleftrightarrow> (\\<forall>x\\<ge>0. (X::real^_^_) *v x \\<le> Y *v x)\"\n  by (metis diff_ge_0_iff_ge matrix_vector_mult_diff_rdistrib nonneg_mat_iff)\n\nsubsection \\<open>Matrix Powers\\<close>\n\n(* copied from Perron-Frobenius *)\nprimrec matpow :: \"'a::semiring_1^'n^'n \\<Rightarrow> nat \\<Rightarrow> 'a^'n^'n\" where\n  matpow_0:   \"matpow A 0 = mat 1\" |\n  matpow_Suc: \"matpow A (Suc n) = (matpow A n) ** A\"\n\nlemma nonneg_matpow: \"0 \\<le> X \\<Longrightarrow> 0 \\<le> matpow (X :: real ^ _ ^ _) i\"\n  by (induction i) (auto simp: nonneg_matrix_mult)\n\nlemma matpow_mono: \"0 \\<le> C \\<Longrightarrow> C \\<le> D \\<Longrightarrow> matpow (C :: real^_^_) n \\<le> matpow D n\"\n  by (induction n) (auto intro!: matrix_mult_mono nonneg_matpow)\n\nlemma matpow_scaleR: \"matpow (c *\\<^sub>R (X :: 'b :: real_algebra_1^_^_)) n = (c^n) *\\<^sub>R (matpow X) n\"\nproof (induction n arbitrary: X c)\n  case (Suc n)\n  have \"matpow (c *\\<^sub>R X) (Suc n) = (c^n)*\\<^sub>R (matpow X) n ** c *\\<^sub>R X\"\n    using Suc by auto\n  also have \"\\<dots> = c *\\<^sub>R ((c^n) *\\<^sub>R (matpow X) n ** X)\"\n    using scalar_matrix_assoc' \n    by (auto simp: scalar_matrix_assoc')\n  finally show ?case\n    by (simp add: scalar_matrix_assoc)\nqed auto\n\nlemma matrix_vector_mult_code': \"(X *v x) $ i = (\\<Sum>j\\<in>UNIV. X $ i $ j * x $ j)\"\n  by (simp add: matrix_vector_mult_def)\n\nlemma matrix_vector_mult_mono: \"(0::real^_^_) \\<le> X \\<Longrightarrow> 0 \\<le> v \\<Longrightarrow> X \\<le> Y \\<Longrightarrow> X *v v \\<le> Y *v v\"\n  by (metis diff_ge_0_iff_ge matrix_vector_mult_diff_rdistrib nonneg_mat_iff)\n\nsubsection \\<open>Triangular Matrices\\<close>\n\ndefinition \"lower_triangular_mat X \\<longleftrightarrow> (\\<forall>i j. (i :: 'b::{finite, linorder}) < j \\<longrightarrow> X $ i $ j = 0)\"\n\ndefinition \"strict_lower_triangular_mat X \\<longleftrightarrow> (\\<forall>i j. (i :: 'b::{finite, linorder}) \\<le> j \\<longrightarrow> X $ i $ j = 0)\"\n\ndefinition \"upper_triangular_mat X \\<longleftrightarrow> (\\<forall>i j. j < i \\<longrightarrow> X $ i $ j = 0)\"\n\nlemma stlI: \"strict_lower_triangular_mat X \\<Longrightarrow> lower_triangular_mat X\"\n  unfolding strict_lower_triangular_mat_def lower_triangular_mat_def\n  by auto\n\nlemma lower_triangular_mat_mat: \"lower_triangular_mat (mat x)\"\n  unfolding lower_triangular_mat_def mat_def\n  by auto\n\nlemma lower_triangular_mult:\n  assumes \"lower_triangular_mat X\" \"lower_triangular_mat Y\"\n  shows \"lower_triangular_mat (X ** Y)\"\n  using assms \n  unfolding matrix_matrix_mult_def lower_triangular_mat_def\n  by (auto intro!: sum.neutral) (metis mult_not_zero neqE less_trans)\n\nlemma lower_triangular_pow:\n  assumes \"lower_triangular_mat X\"\n  shows \"lower_triangular_mat (matpow X i)\"\n  using assms lower_triangular_mult lower_triangular_mat_mat\n  by (induction i) auto\n\nlemma lower_triangular_suminf:\n  assumes \"\\<And>i. lower_triangular_mat (f i)\" \"summable (f :: nat \\<Rightarrow> 'b::real_normed_vector^_^_)\" \n  shows \"lower_triangular_mat (\\<Sum>i. f i)\"\n  using assms\n  unfolding lower_triangular_mat_def\n  by (subst bounded_linear.suminf) (auto intro: bounded_linear_compose)\n\nlemma lower_triangular_pow_eq:\n  assumes \"lower_triangular_mat X\" \"lower_triangular_mat Y\" \"\\<And>s'. s' \\<le> s \\<Longrightarrow> row s' X = row s' Y\" \"s' \\<le> s\"\n  shows \"row s' (matpow X i) = row s' (matpow Y i)\"\n  using assms\nproof (induction i)\n  case (Suc i)\n  thus ?case\n  proof -\n    have ltX: \"lower_triangular_mat (matpow X i)\"\n      by (simp add: Suc(2) lower_triangular_pow)\n    have ltY: \"lower_triangular_mat (matpow Y i)\"\n      by (simp add: Suc(3) lower_triangular_pow)\n    have \" (\\<Sum>k\\<in>UNIV. matpow X i $ s' $ k * X $ k $ j) = (\\<Sum>k\\<in>UNIV. matpow Y i $ s' $ k * Y $ k $ j)\" for j\n    proof -\n      have \"(\\<Sum>k\\<in>UNIV. matpow X i $ s' $ k * X $ k $ j) = (\\<Sum>k\\<in>UNIV. if s' < k then 0 else matpow Y i $ s' $ k * X $ k $ j)\"\n        using Suc ltY\n        by (auto simp: row_def lower_triangular_mat_def intro!: sum.cong)\n      also have \"\\<dots> = (\\<Sum>k \\<in> UNIV . matpow Y i $ s' $ k * Y $ k $ j)\"\n        using Suc ltY\n        by (auto simp: row_def lower_triangular_mat_def cong: if_cong intro!: sum.cong)\n      finally show ?thesis.\n    qed\n    thus ?thesis\n      by (auto simp: row_def matrix_matrix_mult_def)\n  qed\nqed simp\n\nlemma lower_triangular_mat_mult:\n  assumes \"lower_triangular_mat M\" \"\\<And>i. i \\<le> j \\<Longrightarrow> v $ i = v' $ i\"\n  shows \"(M *v v) $ j = (M *v v') $ j\"\nproof -\n  have \"(M *v v) $ j = (\\<Sum>i\\<in>UNIV. (if j < i then 0 else  M $ j $ i * v $ i))\"\n    using assms unfolding lower_triangular_mat_def\n    by (auto simp: matrix_vector_mult_def intro!: sum.cong)\n  also have \"\\<dots> = (\\<Sum>i\\<in>UNIV. (if j < i then 0 else  M $ j $ i * v' $ i))\"\n    using assms\n    by (auto intro!: sum.cong)\n  also have \"\\<dots> = (M *v v') $ j\"\n    using assms unfolding lower_triangular_mat_def\n    by (auto simp: matrix_vector_mult_def intro!: sum.cong)\n  finally show ?thesis.\nqed\n\nsubsection \\<open>Inverses\\<close>\n\n(* from AFP/Rank_Nullity_Theorem *)\nlemma matrix_inv:\n  assumes \"invertible M\"\n  shows matrix_inv_left: \"matrix_inv M ** M = mat 1\"\n    and matrix_inv_right: \"M ** matrix_inv M = mat 1\"\n  using \\<open>invertible M\\<close> and someI_ex [of \"\\<lambda> N. M ** N = mat 1 \\<and> N ** M = mat 1\"]\n  unfolding invertible_def and matrix_inv_def\n  by simp_all\n\n(* from AFP/Rank_Nullity_Theorem *)\nlemma matrix_inv_unique:\n  fixes A::\"'a::{semiring_1}^'n^'n\"\n  assumes AB: \"A ** B = mat 1\" and BA: \"B ** A = mat 1\"\n  shows \"matrix_inv A = B\"\n  by (metis AB BA invertible_def matrix_inv_right matrix_mul_assoc matrix_mul_lid) \n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/MDP-Algorithms/Matrix_Util.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8596637559030338, "lm_q1q2_score": 0.7692180731721819}}
{"text": "theory Chap2_3\nimports Main\nbegin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\"\n| \"contents (Node l a r) = a # contents l @ contents r\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\"\n| \"sum_tree (Node l a r) = a + sum_tree l + sum_tree r\"\n\nlemma \"sum_tree t = sum_list (contents t)\"\n  apply (induction t)\n  by auto\n\ndefinition pre_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"pre_order t = contents t\"\n\nfun post_order :: \"'a tree \\<Rightarrow> 'a list\" where\n\"post_order Tip = []\"\n| \"post_order (Node l a r) = post_order l @ post_order r @ [a]\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\"\n| \"mirror (Node l a r) = Node (mirror r) a (mirror l)\"\n\nlemma \"pre_order (mirror t) = rev (post_order t)\"\n  apply (induction t)\n  by (auto simp add: pre_order_def)\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse a [] = []\"\n| \"intersperse a [x] = [x]\"\n| \"intersperse a (x#y#xs) = x#a#y#(intersperse a xs)\"\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply (induction xs rule: intersperse.induct)\n  by simp+\n\nend", "meta": {"author": "1000teslas", "repo": "concrete_semantics", "sha": "690bb968718a3162b1c4ada4ef40370a4ff99c9c", "save_path": "github-repos/isabelle/1000teslas-concrete_semantics", "path": "github-repos/isabelle/1000teslas-concrete_semantics/concrete_semantics-690bb968718a3162b1c4ada4ef40370a4ff99c9c/Chap2_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7692180578936493}}
{"text": "theory t2\nimports Main\nbegin\n\n(*Problema 1*)\nprimrec soma::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\nsoma1: \"soma x 0 = x\"|\nsoma2: \"soma x (Suc y) = Suc (soma x y)\"\n\nvalue \"soma 0 0\" (* OK *)\n\n(* soma(x,y) = x + y *)\ntheorem t1 \"soma x y = x + y\"\nproof (induct y)\n  show \" soma x 0 = x + 0\"\n  proof -\n    have \"soma x 0 = x\" by (simp only:soma1)\n    also have \"... = x + 0\" by (simp)\n    finally show \"soma x 0 = x + 0\" by (simp)\n  qed\nnext\n  fix y::nat\n  assume HI: \"soma x y = x + y\"\n  show \"soma x (Suc y) = x + Suc y\"\n  proof -\n    have \"soma x (Suc y) = Suc (soma x y)\" by (simp only: soma2)\n    also have \"... = Suc x + y\" by (simp only: HI)\n    also have \"... = x + Suc y\" by (simp)\n    finally show \"soma x (Suc y) = x + Suc y\" by (simp)\n  qed\nqed (*erro*)\n\n\n\n(* soma(x,y) = soma(y,x) *)\ntheorem t2 \" soma x y = soma y x\"\nproof (induct y)\n  show \"\\<forall>x. soma x 0 = soma 0 x\"\n  proof-\n    have \"soma x 0 = x by (soma1)\n    also have \"... = 0 + x by (simp)\n  \n\n\n\n(* soma (x,0) = 0 *)\n\n(* soma (0,x) = x *)\n\n(* soma(x,soma(y,z)) = soma(soma (x,y),z) *)\n\n\n\n\n\n(*Problema 2*)\nprimrec mult::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mult x 0 = 0\"|\n\"mult x (Suc y) = soma x (mult x y)\"\n\nvalue \" mult 8 3 \" (* OK *)\n\n\n(* mult(x,y) = x * y *)\n\n(* mult(x,y) = mult(y,x) *)\n\n(* mult (x,1) = 1 *)\n\n(* mult (1,x) = x *)\n\n(* mult(x,mult(y,z)) = mult(mult (x,y),z) *)\nend", "meta": {"author": "thiagomedinacc", "repo": "t2metformais", "sha": "5ef16d561701be096c33acc12e0f1ddcae23ad29", "save_path": "github-repos/isabelle/thiagomedinacc-t2metformais", "path": "github-repos/isabelle/thiagomedinacc-t2metformais/t2metformais-5ef16d561701be096c33acc12e0f1ddcae23ad29/t2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391706552538, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7691912509850639}}
{"text": "theory Concrete_Semantics_2_2_ex5\nimports Main\nbegin\n\nfun sum_upto :: \"nat => nat\" where\n\"sum_upto 0 = 0\" |\n\"sum_upto n = n + sum_upto (n - 1)\"\n\nlemma \"sum_upto n = n * (n + 1) div 2\"\napply(induction n)\napply(auto)\ndone\n\nend", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/ConcreteSemanticsChapter2/ex2_2/Concrete_Semantics_2_2_ex5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.8198933403143929, "lm_q1q2_score": 0.7691616345309318}}
{"text": "theory Boolos imports Main\nbegin\n\ntypedecl i\nconsts \n e :: \"i\"  (*one*) \n s :: \"i \\<Rightarrow> i\"  (*successor*)\n F :: \"i \\<Rightarrow> i \\<Rightarrow> i\" (*binary function; will be axiomatised as Ackermann function*)\n D :: \"i \\<Rightarrow> bool\" (*arbitrary unary predicate*)\n\naxiomatization where \n  A1: \"\\<forall>n. F n e = s e\" and \n  A2: \"\\<forall>y. F e (s y) = s (s (F e y))\" and \n  A3: \"\\<forall>x y. F (s x) (s y) = F x (F (s x) y)\" and \n  A4: \"D e\" and \n  A5: \"\\<forall>x. D x \\<longrightarrow> D (s x)\"\n\ndefinition induct where \"induct X \\<equiv> (X e) \\<and> (\\<forall>x. X x \\<longrightarrow> X (s x))\"  (*X inductively def. Pred.*)\ndefinition N where \"N x \\<equiv> (\\<forall>X::i\\<Rightarrow>bool. induct X \\<longrightarrow> X x)\"    (*Higher-order quantifier*)\ndefinition P1 where \"P1 x y \\<equiv> N (F x y)\"\ndefinition P2 where \"P2 x \\<equiv> (\\<forall>z. N z \\<longrightarrow> P1 x z)\"\n\ntheorem Boolos: \"D (F (s (s (s (s e)))) (s (s (s (s e)))))\"\nproof- \n  have L1: \"\\<forall>X::i\\<Rightarrow>bool. induct X \\<longrightarrow> (\\<forall>z. N z \\<longrightarrow> X z)\" using N_def by fastforce \n  have L2: \"induct N\" by (metis N_def induct_def)\n  have L3: \"induct D\" by (simp add: A4 A5 induct_def)\n  have L4: \"N (s (s (s (s e))))\" by (metis L2 induct_def)\n  have L5: \"P1 e e\" by (metis A1 L2 P1_def induct_def)\n  have L6: \"\\<forall>x. P1 e x \\<longrightarrow> P1 e (s x)\" by (metis A2 P1_def induct_def L2)\n  have L7: \"induct (P1 e)\" using induct_def L5 L6 by auto\n  have L8: \"\\<forall>x. P1 (s x) e\" by (metis A1 P1_def induct_def L2)\n  have L9: \"P2 e\" by (metis L1 L7 P2_def)\n  have L10: \"\\<forall>x. P2 x \\<longrightarrow> (\\<forall>y. P1 (s x) y \\<longrightarrow> P1 (s x) (s y))\" by (metis A3 P1_def P2_def)\n  have L11: \"\\<forall>x. P2 x \\<longrightarrow> P2 (s x)\" by (metis L1 L10 L8 P2_def induct_def)\n  have L12: \"induct P2\" by (simp add: L11 L9 induct_def)\n  thus ?thesis using L3 L4 N_def P1_def P2_def by blast \nqed\n\nend", "meta": {"author": "cbenzmueller", "repo": "LogiKEy", "sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf", "save_path": "github-repos/isabelle/cbenzmueller-LogiKEy", "path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/CoursesAndTutorials/2022-Bamberg/Boolos.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172630429475, "lm_q2_score": 0.810478913248044, "lm_q1q2_score": 0.7690774321133564}}
{"text": "theory sample4\n  imports Main begin\n\n(* inductive one of evenness *)\ninductive ev  :: \"nat \\<Rightarrow> bool\" where\n  ev0: \"ev 0\" |\n(*evSS: \"ev n \\<Longrightarrow> ev (n + 2)*)\n  evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc(n)))\"\n\n(*\n  How do we prove that some number is even,\n  e.g., ev 4? Simply by combining the \n  defining rules for ev:\n  ev 0 =\\<Rightarrow> ev (0 + 2) =\\<Rightarrow> ev((0 + 2) + 2) = ev 4\n*)\n\n(* recursive one of evenness *)\nfun evn :: \"nat \\<Rightarrow> bool\" where\n  \"evn 0 = True\" |\n  \"evn (Suc 0) = False\" |\n  \"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev(Suc(Suc(Suc(Suc 0::nat))))\"\n  apply(rule evSS)\n  apply(rule evSS)\n  apply(rule ev0)\n  done\n\nlemma agree_ev_evn [simp]: \"ev m \\<Longrightarrow> evn m\"\n  apply(induction rule: ev.induct)\n(*\n  apply(simp)\n  apply(simp)\n*)\n  apply(simp_all)\n  done\n\n(*declare ev.intros[simp, intro]*)\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply(induction n rule: evn.induct)\n    apply(simp_all add: ev0 evSS)\n  done\n  \n\n  \n  ", "meta": {"author": "RinGotou", "repo": "Isabelle-Practice", "sha": "41fb1aff3b7a08e010055bd5c887480d09cbfa05", "save_path": "github-repos/isabelle/RinGotou-Isabelle-Practice", "path": "github-repos/isabelle/RinGotou-Isabelle-Practice/Isabelle-Practice-41fb1aff3b7a08e010055bd5c887480d09cbfa05/sample4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460243, "lm_q2_score": 0.8221891305219505, "lm_q1q2_score": 0.7690317366269246}}
{"text": "(*  Title:      HOL/Library/Stirling.thy\n    Author:     Amine Chaieb\n    Author:     Florian Haftmann\n    Author:     Lukas Bulwahn\n    Author:     Manuel Eberl\n*)\n\nsection \\<open>Stirling numbers of first and second kind\\<close>\n\ntheory Stirling\nimports Main\nbegin\n\nsubsection \\<open>Stirling numbers of the second kind\\<close>\n\nfun Stirling :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Stirling 0 0 = 1\"\n  | \"Stirling 0 (Suc k) = 0\"\n  | \"Stirling (Suc n) 0 = 0\"\n  | \"Stirling (Suc n) (Suc k) = Suc k * Stirling n (Suc k) + Stirling n k\"\n\nlemma Stirling_1 [simp]: \"Stirling (Suc n) (Suc 0) = 1\"\n  by (induct n) simp_all\n\nlemma Stirling_less [simp]: \"n < k \\<Longrightarrow> Stirling n k = 0\"\n  by (induct n k rule: Stirling.induct) simp_all\n\nlemma Stirling_same [simp]: \"Stirling n n = 1\"\n  by (induct n) simp_all\n\nlemma Stirling_2_2: \"Stirling (Suc (Suc n)) (Suc (Suc 0)) = 2 ^ Suc n - 1\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"Stirling (Suc (Suc (Suc n))) (Suc (Suc 0)) =\n      2 * Stirling (Suc (Suc n)) (Suc (Suc 0)) + Stirling (Suc (Suc n)) (Suc 0)\"\n    by simp\n  also have \"\\<dots> = 2 * (2 ^ Suc n - 1) + 1\"\n    by (simp only: Suc Stirling_1)\n  also have \"\\<dots> = 2 ^ Suc (Suc n) - 1\"\n  proof -\n    have \"(2::nat) ^ Suc n - 1 > 0\"\n      by (induct n) simp_all\n    then have \"2 * ((2::nat) ^ Suc n - 1) > 0\"\n      by simp\n    then have \"2 \\<le> 2 * ((2::nat) ^ Suc n)\"\n      by simp\n    with add_diff_assoc2 [of 2 \"2 * 2 ^ Suc n\" 1]\n    have \"2 * 2 ^ Suc n - 2 + (1::nat) = 2 * 2 ^ Suc n + 1 - 2\" .\n    then show ?thesis\n      by (simp add: nat_distrib)\n  qed\n  finally show ?case by simp\nqed\n\nlemma Stirling_2: \"Stirling (Suc n) (Suc (Suc 0)) = 2 ^ n - 1\"\n  using Stirling_2_2 by (cases n) simp_all\n\n\nsubsection \\<open>Stirling numbers of the first kind\\<close>\n\nfun stirling :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"stirling 0 0 = 1\"\n  | \"stirling 0 (Suc k) = 0\"\n  | \"stirling (Suc n) 0 = 0\"\n  | \"stirling (Suc n) (Suc k) = n * stirling n (Suc k) + stirling n k\"\n\nlemma stirling_0 [simp]: \"n > 0 \\<Longrightarrow> stirling n 0 = 0\"\n  by (cases n) simp_all\n\nlemma stirling_less [simp]: \"n < k \\<Longrightarrow> stirling n k = 0\"\n  by (induct n k rule: stirling.induct) simp_all\n\nlemma stirling_same [simp]: \"stirling n n = 1\"\n  by (induct n) simp_all\n\nlemma stirling_Suc_n_1: \"stirling (Suc n) (Suc 0) = fact n\"\n  by (induct n) auto\n\nlemma stirling_Suc_n_n: \"stirling (Suc n) n = Suc n choose 2\"\n  by (induct n) (auto simp add: numerals(2))\n\nlemma stirling_Suc_n_2:\n  assumes \"n \\<ge> Suc 0\"\n  shows \"stirling (Suc n) 2 = (\\<Sum>k=1..n. fact n div k)\"\n  using assms\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by (simp add: numerals(2))\n  next\n    case Suc\n    then have geq1: \"Suc 0 \\<le> n\"\n      by simp\n    have \"stirling (Suc (Suc n)) 2 = Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0)\"\n      by (simp only: stirling.simps(4)[of \"Suc n\"] numerals(2))\n    also have \"\\<dots> = Suc n * (\\<Sum>k=1..n. fact n div k) + fact n\"\n      using Suc.hyps[OF geq1]\n      by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)\n    also have \"\\<dots> = Suc n * (\\<Sum>k=1..n. fact n div k) + Suc n * fact n div Suc n\"\n      by (metis nat.distinct(1) nonzero_mult_div_cancel_left)\n    also have \"\\<dots> = (\\<Sum>k=1..n. fact (Suc n) div k) + fact (Suc n) div Suc n\"\n      by (simp add: sum_distrib_left div_mult_swap dvd_fact)\n    also have \"\\<dots> = (\\<Sum>k=1..Suc n. fact (Suc n) div k)\"\n      by simp\n    finally show ?thesis .\n  qed\nqed\n\nlemma of_nat_stirling_Suc_n_2:\n  assumes \"n \\<ge> Suc 0\"\n  shows \"(of_nat (stirling (Suc n) 2)::'a::field_char_0) = fact n * (\\<Sum>k=1..n. (1 / of_nat k))\"\n  using assms\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by (auto simp add: numerals(2))\n  next\n    case Suc\n    then have geq1: \"Suc 0 \\<le> n\"\n      by simp\n    have \"(of_nat (stirling (Suc (Suc n)) 2)::'a) =\n        of_nat (Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0))\"\n      by (simp only: stirling.simps(4)[of \"Suc n\"] numerals(2))\n    also have \"\\<dots> = of_nat (Suc n) * (fact n * (\\<Sum>k = 1..n. 1 / of_nat k)) + fact n\"\n      using Suc.hyps[OF geq1]\n      by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)\n    also have \"\\<dots> = fact (Suc n) * (\\<Sum>k = 1..n. 1 / of_nat k) + fact (Suc n) * (1 / of_nat (Suc n))\"\n      using of_nat_neq_0 by auto\n    also have \"\\<dots> = fact (Suc n) * (\\<Sum>k = 1..Suc n. 1 / of_nat k)\"\n      by (simp add: distrib_left)\n    finally show ?thesis .\n  qed\nqed\n\nlemma sum_stirling: \"(\\<Sum>k\\<le>n. stirling n k) = fact n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>k\\<le>Suc n. stirling (Suc n) k) = stirling (Suc n) 0 + (\\<Sum>k\\<le>n. stirling (Suc n) (Suc k))\"\n    by (simp only: sum.atMost_Suc_shift)\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. stirling (Suc n) (Suc k))\"\n    by simp\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. n * stirling n (Suc k) + stirling n k)\"\n    by simp\n  also have \"\\<dots> = n * (\\<Sum>k\\<le>n. stirling n (Suc k)) + (\\<Sum>k\\<le>n. stirling n k)\"\n    by (simp add: sum.distrib sum_distrib_left)\n  also have \"\\<dots> = n * fact n + fact n\"\n  proof -\n    have \"n * (\\<Sum>k\\<le>n. stirling n (Suc k)) = n * ((\\<Sum>k\\<le>Suc n. stirling n k) - stirling n 0)\"\n      by (metis add_diff_cancel_left' sum.atMost_Suc_shift)\n    also have \"\\<dots> = n * (\\<Sum>k\\<le>n. stirling n k)\"\n      by (cases n) simp_all\n    also have \"\\<dots> = n * fact n\"\n      using Suc.hyps by simp\n    finally have \"n * (\\<Sum>k\\<le>n. stirling n (Suc k)) = n * fact n\" .\n    moreover have \"(\\<Sum>k\\<le>n. stirling n k) = fact n\"\n      using Suc.hyps .\n    ultimately show ?thesis by simp\n  qed\n  also have \"\\<dots> = fact (Suc n)\" by simp\n  finally show ?case .\nqed\n\nlemma stirling_pochhammer:\n  \"(\\<Sum>k\\<le>n. of_nat (stirling n k) * x ^ k) = (pochhammer x n :: 'a::comm_semiring_1)\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"of_nat (n * stirling n 0) = (0 :: 'a)\" by (cases n) simp_all\n  then have \"(\\<Sum>k\\<le>Suc n. of_nat (stirling (Suc n) k) * x ^ k) =\n      (of_nat (n * stirling n 0) * x ^ 0 +\n      (\\<Sum>i\\<le>n. of_nat (n * stirling n (Suc i)) * (x ^ Suc i))) +\n      (\\<Sum>i\\<le>n. of_nat (stirling n i) * (x ^ Suc i))\"\n    by (subst sum.atMost_Suc_shift) (simp add: sum.distrib ring_distribs)\n  also have \"\\<dots> = pochhammer x (Suc n)\"\n    by (subst sum.atMost_Suc_shift [symmetric])\n      (simp add: algebra_simps sum.distrib sum_distrib_left pochhammer_Suc flip: Suc)\n  finally show ?case .\nqed\n\n\ntext \\<open>A row of the Stirling number triangle\\<close>\n\ndefinition stirling_row :: \"nat \\<Rightarrow> nat list\"\n  where \"stirling_row n = [stirling n k. k \\<leftarrow> [0..<Suc n]]\"\n\nlemma nth_stirling_row: \"k \\<le> n \\<Longrightarrow> stirling_row n ! k = stirling n k\"\n  by (simp add: stirling_row_def del: upt_Suc)\n\nlemma length_stirling_row [simp]: \"length (stirling_row n) = Suc n\"\n  by (simp add: stirling_row_def)\n\nlemma stirling_row_nonempty [simp]: \"stirling_row n \\<noteq> []\"\n  using length_stirling_row[of n] by (auto simp del: length_stirling_row)\n\n\nsubsubsection \\<open>Efficient code\\<close>\n\ntext \\<open>\n  Naively using the defining equations of the Stirling numbers of the first\n  kind to compute them leads to exponential run time due to repeated\n  computations. We can use memoisation to compute them row by row without\n  repeating computations, at the cost of computing a few unneeded values.\n\n  As a bonus, this is very efficient for applications where an entire row of\n  Stirling numbers is needed.\n\\<close>\n\ndefinition zip_with_prev :: \"('a \\<Rightarrow> 'a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'b list\"\n  where \"zip_with_prev f x xs = map2 f (x # xs) xs\"\n\nlemma zip_with_prev_altdef:\n  \"zip_with_prev f x xs =\n    (if xs = [] then [] else f x (hd xs) # [f (xs!i) (xs!(i+1)). i \\<leftarrow> [0..<length xs - 1]])\"\nproof (cases xs)\n  case Nil\n  then show ?thesis\n    by (simp add: zip_with_prev_def)\nnext\n  case (Cons y ys)\n  then have \"zip_with_prev f x xs = f x (hd xs) # zip_with_prev f y ys\"\n    by (simp add: zip_with_prev_def)\n  also have \"zip_with_prev f y ys = map (\\<lambda>i. f (xs ! i) (xs ! (i + 1))) [0..<length xs - 1]\"\n    unfolding Cons\n    by (induct ys arbitrary: y)\n      (simp_all add: zip_with_prev_def upt_conv_Cons flip: map_Suc_upt del: upt_Suc)\n  finally show ?thesis\n    using Cons by simp\nqed\n\n\nprimrec stirling_row_aux\n  where\n    \"stirling_row_aux n y [] = [1]\"\n  | \"stirling_row_aux n y (x#xs) = (y + n * x) # stirling_row_aux n x xs\"\n\nlemma stirling_row_aux_correct:\n  \"stirling_row_aux n y xs = zip_with_prev (\\<lambda>a b. a + n * b) y xs @ [1]\"\n  by (induct xs arbitrary: y) (simp_all add: zip_with_prev_def)\n\nlemma stirling_row_code [code]:\n  \"stirling_row 0 = [1]\"\n  \"stirling_row (Suc n) = stirling_row_aux n 0 (stirling_row n)\"\nproof goal_cases\n  case 1\n  show ?case by (simp add: stirling_row_def)\nnext\n  case 2\n  have \"stirling_row (Suc n) =\n    0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \\<leftarrow> [0..<n]] @ [1]\"\n  proof (rule nth_equalityI, goal_cases length nth)\n    case (nth i)\n    from nth have \"i \\<le> Suc n\"\n      by simp\n    then consider \"i = 0 \\<or> i = Suc n\" | \"i > 0\" \"i \\<le> n\"\n      by linarith\n    then show ?case\n    proof cases\n      case 1\n      then show ?thesis\n        by (auto simp: nth_stirling_row nth_append)\n    next\n      case 2\n      then show ?thesis\n        by (cases i) (simp_all add: nth_append nth_stirling_row)\n    qed\n  next\n    case length\n    then show ?case by simp\n  qed\n  also have \"0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \\<leftarrow> [0..<n]] @ [1] =\n      zip_with_prev (\\<lambda>a b. a + n * b) 0 (stirling_row n) @ [1]\"\n    by (cases n) (auto simp add: zip_with_prev_altdef stirling_row_def hd_map simp del: upt_Suc)\n  also have \"\\<dots> = stirling_row_aux n 0 (stirling_row n)\"\n    by (simp add: stirling_row_aux_correct)\n  finally show ?case .\nqed\n\nlemma stirling_code [code]:\n  \"stirling n k =\n    (if k = 0 then (if n = 0 then 1 else 0)\n     else if k > n then 0\n     else if k = n then 1\n     else stirling_row n ! k)\"\n  by (simp add: nth_stirling_row)\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Library/Stirling.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7689755117317908}}
{"text": "theory Induccion\nimports Main\nbegin\n\nsection {* Definiciones de la función inversa *}\n\ntext {* (inversa xs) es la inversa de xs. Por ejemplo,\n     inversa [a,b,c] = [c,b,a]\n*}\nfun inversa :: \"'a list \\<Rightarrow> 'a list\" where\n  \"inversa []     = []\"\n| \"inversa (x#xs) = inversa xs @ [x]\"\n\nvalue \"inversa [a,b,c]\"\nlemma \"inversa [a,b,c] = [c,b,a]\" by simp\n\ntext {* (inversaIaux xs) es la inversa de xs calculada de manera\n  iterativa. Por ejemplo, \n     inversaIaux [a,b,c] = [c,b,a]\n*}\nfun inversaIaux :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"inversaIaux [] ys     = ys\" \n| \"inversaIaux (x#xs) ys = inversaIaux xs (x#ys)\"\n\ndefinition inversaI :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  \"inversaI xs = inversaIaux xs []\"\n\nvalue \"inversaI [a,b,c]\"\nlemma \"inversaI [a,b,c] = [c,b,a]\" by (simp add: inversaI_def)\n\nsection {* Equivalencia de las definiciones de inversa *}\n\ntext {* El objetivo de esta sección es demostrar la equivalencia de las\n  dos definiciones; es decir,\n     equiv_inversa: \"inversaI xs = inversa xs\"\n  \n  A la vista de la definición de inversaI, se observa que la propiedad\n  anterior es un corolario de \n     equiv_inversa_aux: \"inversaIaux xs [] = inversa xs\"\n\n  Vamos a demostrar equiv_inversa_aux usando heurísticas de inducción.  \n*}  \n\ntext {* 1\\<ordmasculine> intento de prueba de equiv_inversa_aux *}\nlemma equiv_inversa_aux_1:\n  \"inversaIaux xs [] = inversa xs\"\napply (induction xs)  \napply auto\noops\n\ntext {* Se observa que se queda sin demostrar el objetivo \n     inversaIaux xs [] = inversa xs \\<Longrightarrow> \n     inversaIaux xs [a] = inversa xs @ [a]\n  \n  La causa es que el enunciado era demasiado específico al tener como\n  segundo argumento la lista vacía. Lo generalizamos a\n     equiv_inversa_aux_2: inversaIaux xs ys = inversa xs @ ys\n*}\n\ntext {* 2\\<ordmasculine> intento de prueba de equiv_inversa_aux *}\nlemma equiv_inversa_aux_2:\n  \"inversaIaux xs ys = inversa xs @ ys\"\napply (induction xs)  \napply auto\noops\n\ntext {* Se observa que se queda sin demostrar el objetivo \n     inversaIaux xs ys = inversa xs @ ys \\<Longrightarrow> \n     inversaIaux xs (a # ys) = inversa xs @ a # ys\n  \n  La causa es que aunque el segundo argumento es la variable ys, no se\n  ha tenido en cuenta que su valor varía. Por tanto, hay que declararla\n  como arbitraria.\n*}\n\ntext {* Prueba de equiv_inversa_aux *}\nlemma equiv_inversa_aux:\n  \"inversaIaux xs ys = inversa xs @ ys\"\napply (induction xs arbitrary: ys)  \napply auto\ndone\n\ntext {* Prueba de equiv_inversa *}\ncorollary equiv_inversa: \n  \"inversaI xs = inversa xs\"\napply (simp add: inversaI_def equiv_inversa_aux)\ndone\n\nend\n", "meta": {"author": "jaalonso", "repo": "SLP", "sha": "799e829200ea0a4fbb526f47356135d98a190864", "save_path": "github-repos/isabelle/jaalonso-SLP", "path": "github-repos/isabelle/jaalonso-SLP/SLP-799e829200ea0a4fbb526f47356135d98a190864/Temas/Ejemplos/Induccion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.8652240791017536, "lm_q1q2_score": 0.7689755111924398}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP Toolkit                                              *)\n(* File: FSet_Extra.thy                                                       *)\n(* Authors: Frank Zeyda and Simon Foster (University of York, UK)             *)\n(* Emails: frank.zeyda@york.ac.uk and simon.foster@york.ac.uk                 *)\n(******************************************************************************)\n\nsection {* Finite Sets: extra functions and properties *}\n\ntheory FSet_Extra\nimports\n  \"HOL-Library.FSet\"\n  \"HOL-Library.Countable_Set_Type\"\nbegin\n\nsetup_lifting type_definition_fset\n\nnotation fempty (\"\\<lbrace>\\<rbrace>\")\nnotation fset (\"\\<langle>_\\<rangle>\\<^sub>f\")\nnotation fminus (infixl \"-\\<^sub>f\" 65)\n\nsyntax\n  \"_FinFset\" :: \"args => 'a fset\"    (\"\\<lbrace>(_)\\<rbrace>\")\n\ntranslations\n  \"\\<lbrace>x, xs\\<rbrace>\" == \"CONST finsert x \\<lbrace>xs\\<rbrace>\"\n  \"\\<lbrace>x\\<rbrace>\" == \"CONST finsert x \\<lbrace>\\<rbrace>\"\n\nterm \"fBall\"\n\nsyntax\n  \"_fBall\" :: \"pttrn => 'a fset => bool => bool\" (\"(3\\<forall> _|\\<in>|_./ _)\" [0, 0, 10] 10)\n  \"_fBex\"  :: \"pttrn => 'a fset => bool => bool\" (\"(3\\<exists> _|\\<in>|_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall> x|\\<in>|A. P\" == \"CONST fBall A (%x. P)\"\n  \"\\<exists> x|\\<in>|A. P\" == \"CONST fBex A (%x. P)\"\n\ndefinition FUnion :: \"'a fset fset \\<Rightarrow> 'a fset\" (\"\\<Union>\\<^sub>f_\" [90] 90) where\n\"FUnion xs = Abs_fset (\\<Union>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n\ndefinition FInter :: \"'a fset fset \\<Rightarrow> 'a fset\" (\"\\<Inter>\\<^sub>f_\" [90] 90) where\n\"FInter xs = Abs_fset (\\<Inter>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n\ntext \\<open> Finite power set \\<close>\n\ndefinition FinPow :: \"'a fset \\<Rightarrow> 'a fset fset\" where\n\"FinPow xs = Abs_fset (Abs_fset ` Pow \\<langle>xs\\<rangle>\\<^sub>f)\"\n\ntext \\<open> Set of all finite subsets of a set \\<close>\n\ndefinition Fow :: \"'a set \\<Rightarrow> 'a fset set\" where\n\"Fow A = {x. \\<langle>x\\<rangle>\\<^sub>f \\<subseteq> A}\"\n\ndeclare Abs_fset_inverse [simp]\n\nlemma fset_intro:\n  \"fset x = fset y \\<Longrightarrow> x = y\"\n  by (simp add:fset_inject)\n\nlemma fset_elim:\n  \"\\<lbrakk> x = y; fset x = fset y \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (auto)\n\nlemma fmember_intro:\n  \"\\<lbrakk> x \\<in> fset(xs) \\<rbrakk> \\<Longrightarrow> x |\\<in>| xs\"\n  by (metis fmember.rep_eq)\n\nlemma fmember_elim:\n  \"\\<lbrakk> x |\\<in>| xs; x \\<in> fset(xs) \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (metis fmember.rep_eq)\n\nlemma fnmember_intro [intro]:\n  \"\\<lbrakk> x \\<notin> fset(xs) \\<rbrakk> \\<Longrightarrow> x |\\<notin>| xs\"\n  by (metis fmember.rep_eq)\n\nlemma fnmember_elim [elim]:\n  \"\\<lbrakk> x |\\<notin>| xs; x \\<notin> fset(xs) \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (metis fmember.rep_eq)\n\nlemma fsubset_intro [intro]:\n  \"\\<langle>xs\\<rangle>\\<^sub>f \\<subseteq> \\<langle>ys\\<rangle>\\<^sub>f \\<Longrightarrow> xs |\\<subseteq>| ys\"\n  by (metis less_eq_fset.rep_eq)\n\nlemma fsubset_elim [elim]:\n  \"\\<lbrakk> xs |\\<subseteq>| ys; \\<langle>xs\\<rangle>\\<^sub>f \\<subseteq> \\<langle>ys\\<rangle>\\<^sub>f \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (metis less_eq_fset.rep_eq)\n\nlemma fBall_intro [intro]:\n  \"Ball \\<langle>A\\<rangle>\\<^sub>f P \\<Longrightarrow> fBall A P\"\n  by (metis (poly_guards_query) fBallI fmember.rep_eq)\n\nlemma fBall_elim [elim]:\n  \"\\<lbrakk> fBall A P; Ball \\<langle>A\\<rangle>\\<^sub>f P \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> Q\"\n  by (metis fBallE fmember.rep_eq)\n\nlift_definition finset :: \"'a list \\<Rightarrow> 'a fset\" is set ..\n\ncontext linorder\nbegin\n\nlemma sorted_list_of_set_inj:\n  \"\\<lbrakk> finite xs; finite ys; sorted_list_of_set xs = sorted_list_of_set ys \\<rbrakk>\n   \\<Longrightarrow> xs = ys\"\n  apply (simp add:sorted_list_of_set_def)\n  apply (induct xs rule:finite_induct)\n   apply (induct ys rule:finite_induct)\n    apply (simp_all)\n   apply (metis finite.insertI insert_not_empty sorted_list_of_set_def sorted_list_of_set_empty sorted_list_of_set_eq_Nil_iff)\n  apply (metis finite.insertI finite_list set_remdups set_sort sorted_list_of_set_def sorted_list_of_set_sort_remdups)\n  done\n\ndefinition flist :: \"'a fset \\<Rightarrow> 'a list\" where\n\"flist xs = sorted_list_of_set (fset xs)\"\n\nlemma flist_inj: \"inj flist\"\n  apply (simp add:flist_def inj_on_def)\n  apply (clarify)\n  apply (rename_tac x y)\n  apply (subgoal_tac \"fset x = fset y\")\n   apply (simp add:fset_inject)\n  apply (rule sorted_list_of_set_inj, simp_all)\n  done\n\nlemma flist_props [simp]:\n  \"sorted (flist xs)\"\n  \"distinct (flist xs)\"\n  by (simp_all add:flist_def)\n\nlemma flist_empty [simp]:\n  \"flist \\<lbrace>\\<rbrace> = []\"\n  by (simp add:flist_def)\n\nlemma flist_inv [simp]: \"finset (flist xs) = xs\"\n  by (simp add:finset_def flist_def fset_inverse)\n\nlemma flist_set [simp]: \"set (flist xs) = fset xs\"\n  by (simp add:finset_def flist_def fset_inverse)\n\nlemma fset_inv [simp]: \"\\<lbrakk> sorted xs; distinct xs \\<rbrakk> \\<Longrightarrow> flist (finset xs) = xs\"\n  apply (simp add:finset_def flist_def fset_inverse)\n  apply (metis local.sorted_list_of_set_sort_remdups local.sorted_sort_id remdups_id_iff_distinct)\n  done\n\nlemma fcard_flist:\n  \"fcard xs = length (flist xs)\"\n  apply (simp add:fcard_def)\n  apply (fold flist_set)\n  apply (unfold distinct_card[OF flist_props(2)])\n  apply (rule refl)\n  done\n\nlemma flist_nth:\n  \"i < fcard vs \\<Longrightarrow> flist vs ! i |\\<in>| vs\"\n  apply (simp add: fmember_def flist_def fcard_def)\n  apply (metis fcard.rep_eq fcard_flist finset.rep_eq flist_def flist_inv nth_mem)\n  done\n\ndefinition fmax :: \"'a fset \\<Rightarrow> 'a\" where\n\"fmax xs = (if (xs = \\<lbrace>\\<rbrace>) then undefined else last (flist xs))\"\n\nend\n\ndefinition flists :: \"'a fset \\<Rightarrow> 'a list set\" where\n\"flists A = {xs. distinct xs \\<and> finset xs = A}\"\n\nlemma flists_nonempty: \"\\<exists> xs. xs \\<in> flists A\"\n  apply (simp add: flists_def)\n  apply (metis Abs_fset_cases Abs_fset_inverse finite_distinct_list finite_fset finset.rep_eq)\n  done\n\nlemma flists_elem_uniq: \"\\<lbrakk> x \\<in> flists A; x \\<in> flists B \\<rbrakk> \\<Longrightarrow> A = B\"\n  by (simp add: flists_def)\n\ndefinition flist_arb :: \"'a fset \\<Rightarrow> 'a list\" where\n\"flist_arb A = (SOME xs. xs \\<in> flists A)\"\n\nlemma flist_arb_distinct [simp]: \"distinct (flist_arb A)\"\n  by (metis (mono_tags) flist_arb_def flists_def flists_nonempty mem_Collect_eq someI_ex)\n\nlemma flist_arb_inv [simp]: \"finset (flist_arb A) = A\"\n  by (metis (mono_tags) flist_arb_def flists_def flists_nonempty mem_Collect_eq someI_ex)\n\nlemma flist_arb_inj:\n  \"inj flist_arb\"\n  by (metis flist_arb_inv injI)\n\nlemma flist_arb_lists: \"flist_arb ` Fow A \\<subseteq> lists A\"\n  apply (auto)\n  using Fow_def finset.rep_eq apply fastforce\n  done\n\nlemma countable_Fow:\n  fixes A :: \"'a set\"\n  assumes \"countable A\"\n  shows \"countable (Fow A)\"\nproof -\n  from assms obtain to_nat_list :: \"'a list \\<Rightarrow> nat\" where \"inj_on to_nat_list (lists A)\"\n    by blast\n  thus ?thesis\n    apply (simp add: countable_def)\n    apply (rule_tac x=\"to_nat_list \\<circ> flist_arb\" in exI)\n    apply (rule comp_inj_on)\n     apply (metis flist_arb_inv inj_on_def)\n    apply (simp add: flist_arb_lists subset_inj_on)\n    done\nqed\n\ndefinition flub :: \"'a fset set \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" where\n\"flub A t = (if (\\<forall> a\\<in>A. a |\\<subseteq>| t) then Abs_fset (\\<Union>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f) else t)\"\n\nlemma finite_Union_subsets:\n  \"\\<lbrakk> \\<forall> a \\<in> A. a \\<subseteq> b; finite b \\<rbrakk> \\<Longrightarrow> finite (\\<Union>A)\"\n  by (metis Sup_le_iff finite_subset)\n\nlemma finite_UN_subsets:\n  \"\\<lbrakk> \\<forall> a \\<in> A. B a \\<subseteq> b; finite b \\<rbrakk> \\<Longrightarrow> finite (\\<Union>a\\<in>A. B a)\"\n  by (metis UN_subset_iff finite_subset)\n\nlemma flub_rep_eq:\n  \"\\<langle>flub A t\\<rangle>\\<^sub>f = (if (\\<forall> a\\<in>A. a |\\<subseteq>| t) then (\\<Union>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f) else \\<langle>t\\<rangle>\\<^sub>f)\"\n  apply (subgoal_tac \"(if (\\<forall> a\\<in>A. a |\\<subseteq>| t) then (\\<Union>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f) else \\<langle>t\\<rangle>\\<^sub>f) \\<in> {x. finite x}\")\n   apply (auto simp add:flub_def)\n  apply (rule finite_UN_subsets[of _ _ \"\\<langle>t\\<rangle>\\<^sub>f\"])\n   apply (auto)\n  done\n\ndefinition fglb :: \"'a fset set \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" where\n\"fglb A t = (if (A = {}) then t else Abs_fset (\\<Inter>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f))\"\n\nlemma fglb_rep_eq:\n  \"\\<langle>fglb A t\\<rangle>\\<^sub>f = (if (A = {}) then \\<langle>t\\<rangle>\\<^sub>f else (\\<Inter>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f))\"\n  apply (subgoal_tac \"(if (A = {}) then \\<langle>t\\<rangle>\\<^sub>f else (\\<Inter>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f)) \\<in> {x. finite x}\")\n   apply (metis Abs_fset_inverse fglb_def)\n  apply (auto)\n  apply (metis finite_INT finite_fset)\n  done\n\nlemma FinPow_rep_eq [simp]:\n  \"fset (FinPow xs) = {ys. ys |\\<subseteq>| xs}\"\n  apply (subgoal_tac \"finite (Abs_fset ` Pow \\<langle>xs\\<rangle>\\<^sub>f)\")\n   apply (auto simp add: fmember_def FinPow_def)\n   apply (rename_tac x' y')\n   apply (subgoal_tac \"finite x'\")\n    apply (auto)\n   apply (metis finite_fset finite_subset)\n  apply (metis (full_types) Pow_iff fset_inverse imageI less_eq_fset.rep_eq)\n  done\n\nlemma FUnion_rep_eq [simp]:\n  \"\\<langle>\\<Union>\\<^sub>f xs\\<rangle>\\<^sub>f = (\\<Union>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n  by (simp add:FUnion_def)\n\nlemma FInter_rep_eq [simp]:\n  \"xs \\<noteq> \\<lbrace>\\<rbrace> \\<Longrightarrow> \\<langle>\\<Inter>\\<^sub>f xs\\<rangle>\\<^sub>f = (\\<Inter>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n  apply (simp add:FInter_def)\n  apply (subgoal_tac \"finite (\\<Inter>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\")\n   apply (simp)\n  apply (metis (poly_guards_query) bot_fset.rep_eq fglb_rep_eq finite_fset fset_inverse)\n  done\n\nlemma FUnion_empty [simp]:\n  \"\\<Union>\\<^sub>f \\<lbrace>\\<rbrace> = \\<lbrace>\\<rbrace>\"\n  by (auto simp add:FUnion_def fmember_def)\n\nlemma FinPow_member [simp]:\n  \"xs |\\<in>| FinPow xs\"\n  by (auto simp add:fmember_def)\n\nlemma FUnion_FinPow [simp]:\n  \"\\<Union>\\<^sub>f (FinPow x) = x\"\n  by (auto simp add:fmember_def less_eq_fset_def)\n\nlemma Fow_mem [iff]: \"x \\<in> Fow A \\<longleftrightarrow> \\<langle>x\\<rangle>\\<^sub>f \\<subseteq> A\"\n  by (auto simp add:Fow_def)\n\nlemma Fow_UNIV [simp]: \"Fow UNIV = UNIV\"\n  by (simp add:Fow_def)\n\nlift_definition FMax :: \"('a::linorder) fset \\<Rightarrow> 'a\" is \"Max\" .\n\nend", "meta": {"author": "isabelle-utp", "repo": "Z_Toolkit", "sha": "87271e3ac0e8fe9092603a2ec2e8df5484903f50", "save_path": "github-repos/isabelle/isabelle-utp-Z_Toolkit", "path": "github-repos/isabelle/isabelle-utp-Z_Toolkit/Z_Toolkit-87271e3ac0e8fe9092603a2ec2e8df5484903f50/FSet_Extra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7689755108004998}}
{"text": "theory boolean_algebra_functional\n  imports boolean_algebra\nbegin\n\nsubsection \\<open>Algebraic connectives on set-valued functions\\<close>\n\n(**Functions with sets in their codomain will be called here 'set-valued functions'.\n  We conveniently define some (2nd-order) Boolean operations on them.*)\n\n(**The 'meet' and 'join' of two set-valued functions: *)\ndefinition svfun_meet::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>)\" (infixr \"\\<^bold>\\<sqinter>\" 62) \n  where \"\\<phi> \\<^bold>\\<sqinter> \\<psi> \\<equiv> \\<lambda>x. (\\<phi> x) \\<^bold>\\<and> (\\<psi> x)\"\ndefinition svfun_join::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>)\" (infixr \"\\<^bold>\\<squnion>\" 61) \n  where \"\\<phi> \\<^bold>\\<squnion> \\<psi> \\<equiv> \\<lambda>x. (\\<phi> x) \\<^bold>\\<or> (\\<psi> x)\"\n(**analogously, we can define an 'implication' and a 'complement'*)\ndefinition svfun_impl::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>)\" (infixr \"\\<^bold>\\<sqsupset>\" 61) \n  where \"\\<psi> \\<^bold>\\<sqsupset> \\<phi> \\<equiv> \\<lambda>x. (\\<psi> x) \\<^bold>\\<rightarrow> (\\<phi> x)\"\ndefinition svfun_compl::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>)\" (\"(_\\<^sup>c)\") \n  where \"\\<phi>\\<^sup>c \\<equiv> \\<lambda>x. \\<^bold>\\<midarrow>(\\<phi> x)\"\n(**There are two natural 0-ary connectives (aka. constants) *)\ndefinition svfun_top::\"'i \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<top>''\") \n  where \"\\<^bold>\\<top>' \\<equiv> \\<lambda>x. \\<^bold>\\<top>\"\ndefinition svfun_bot::\"'i \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>\\<bottom>''\") \n  where \"\\<^bold>\\<bottom>' \\<equiv> \\<lambda>x. \\<^bold>\\<bottom>\"\n\nnamed_theorems conn2 (*to group together definitions for 2nd-order algebraic connectives*)\ndeclare svfun_meet_def[conn2] svfun_join_def[conn2] svfun_impl_def[conn2]\n        svfun_compl_def[conn2] svfun_top_def[conn2] svfun_bot_def[conn2]\n\n(**And, of course, set-valued functions are naturally ordered in the expected way*)\ndefinition svfun_sub::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (infixr \"\\<sqsubseteq>\" 55) \n  where \"\\<psi> \\<sqsubseteq> \\<phi> \\<equiv> \\<forall>x. (\\<psi> x) \\<preceq> (\\<phi> x)\"\ndefinition svfun_equ::\"('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('i \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (infixr \"\\<cong>\" 55) \n  where \"\\<psi> \\<cong> \\<phi> \\<equiv> \\<forall>x. (\\<psi> x) \\<approx> (\\<phi> x)\"\n\nnamed_theorems order2 (*to group together definitions for 2nd-order algebraic connectives*)\ndeclare svfun_sub_def[order2] svfun_equ_def[order2]\n\nlemma svfun_sub_char: \"(\\<psi> \\<sqsubseteq> \\<phi>) = (\\<psi> \\<^bold>\\<sqsupset> \\<phi> \\<cong> \\<^bold>\\<top>')\" by (simp add: BA_impl svfun_equ_def svfun_impl_def svfun_sub_def svfun_top_def)\nlemma svfun_equ_char: \"(\\<psi> \\<cong> \\<phi>) = (\\<psi> \\<sqsubseteq> \\<phi> \\<and> \\<phi> \\<sqsubseteq> \\<psi>)\" unfolding order2 setequ_char by blast\nlemma svfun_equ_ext: \"(\\<psi> \\<cong> \\<phi>) = (\\<psi> = \\<phi>)\" by (meson ext setequ_ext svfun_equ_def)\n\n(**Clearly, set-valued functions form a Boolean algebra. We can prove some interesting relationships*)\nlemma svfun_compl_char: \"\\<phi>\\<^sup>c = (\\<phi> \\<^bold>\\<sqsupset> \\<^bold>\\<bottom>')\" unfolding conn conn2 by simp\nlemma svfun_impl_char1: \"(\\<psi> \\<^bold>\\<sqsupset> \\<phi>) = (\\<psi>\\<^sup>c \\<^bold>\\<squnion> \\<phi>)\" unfolding conn conn2 by simp\nlemma svfun_impl_char2: \"(\\<psi> \\<^bold>\\<sqsupset> \\<phi>) = (\\<psi> \\<^bold>\\<sqinter> (\\<phi>\\<^sup>c))\\<^sup>c\" unfolding conn conn2 by simp\nlemma svfun_deMorgan1: \"(\\<psi> \\<^bold>\\<sqinter> \\<phi>)\\<^sup>c = (\\<psi>\\<^sup>c) \\<^bold>\\<squnion> (\\<phi>\\<^sup>c)\" unfolding conn conn2 by simp\nlemma svfun_deMorgan2: \"(\\<psi> \\<^bold>\\<squnion> \\<phi>)\\<^sup>c = (\\<psi>\\<^sup>c) \\<^bold>\\<sqinter> (\\<phi>\\<^sup>c)\" unfolding conn conn2 by simp\n\n\nsubsection \\<open>Further algebraic connectives on operators\\<close>\n\n(**Dual to set-valued functions we can have set-domain functions. For them we can define the 'dual-complement'*)\ndefinition sdfun_dcompl::\"('w \\<sigma> \\<Rightarrow> 'i) \\<Rightarrow> ('w \\<sigma> \\<Rightarrow> 'i)\" (\"(_\\<^sup>-)\") \n  where \"\\<phi>\\<^sup>- \\<equiv> \\<lambda>X. \\<phi>(\\<^bold>\\<midarrow>X)\"\nlemma sdfun_dcompl_char: \"\\<phi>\\<^sup>- = (\\<lambda>X. \\<exists>Y. (\\<phi> Y) \\<and> (X = \\<^bold>\\<midarrow>Y))\" by (metis BA_dn setequ_ext sdfun_dcompl_def)\n\n(**Operators are a particularly important kind of functions. They are both set-valued and set-domain.\nThus our algebra of operators inherits the connectives defined above plus some idiosyncratic ones. *)\n\n(**We conveniently define the 'dual' of an operator*)\ndefinition op_dual::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('w \\<sigma> \\<Rightarrow> 'w \\<sigma>)\" (\"(_\\<^sup>d)\") \n  where \"\\<phi>\\<^sup>d \\<equiv> \\<lambda>X. \\<^bold>\\<midarrow>(\\<phi>(\\<^bold>\\<midarrow>X))\"\n\n(**The following two 0-ary connectives (i.e operator 'constants') exist already (but somehow implicitly).\n  We just make them explicit by introducing some convenient notation.*)\ndefinition id_op::\"'w \\<sigma> \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>e\") \n  where \"\\<^bold>e \\<equiv> \\<lambda>X. X\" (*introduces notation to refer to 'identity' operator*)\ndefinition compl_op::\"'w \\<sigma> \\<Rightarrow> 'w \\<sigma>\" (\"\\<^bold>n\") \n  where \"\\<^bold>n \\<equiv> \\<lambda>X. \\<^bold>\\<midarrow>X\" (*to refer to 'complement' operator*)\n\ndeclare sdfun_dcompl_def[conn2] op_dual_def[conn2] id_op_def[conn2] compl_op_def[conn2]\n\n(**We now prove some lemmas (some of them might help provers in their hard work).*)\nlemma dual_compl_char1: \"\\<phi>\\<^sup>- = (\\<phi>\\<^sup>d)\\<^sup>c\" unfolding conn2 conn order by simp\nlemma dual_compl_char2: \"\\<phi>\\<^sup>- = (\\<phi>\\<^sup>c)\\<^sup>d\" unfolding conn2 conn order by simp\nlemma sfun_compl_invol: \"\\<phi>\\<^sup>c\\<^sup>c = \\<phi>\" unfolding conn2 conn order by simp\nlemma dual_invol: \"\\<phi>\\<^sup>d\\<^sup>d = \\<phi>\" unfolding conn2 conn order by simp\nlemma dualcompl_invol: \"(\\<phi>\\<^sup>-)\\<^sup>- = \\<phi>\" unfolding conn2 conn order by simp\n\nlemma op_prop1: \"\\<^bold>e\\<^sup>d = \\<^bold>e\" unfolding conn2 conn by simp\nlemma op_prop2: \"\\<^bold>n\\<^sup>d = \\<^bold>n\" unfolding conn2 conn by simp\nlemma op_prop3: \"\\<^bold>e\\<^sup>c = \\<^bold>n\" unfolding conn2 conn by simp\nlemma op_prop4: \"(\\<phi> \\<^bold>\\<squnion> \\<psi>)\\<^sup>d = (\\<phi>\\<^sup>d) \\<^bold>\\<sqinter> (\\<psi>\\<^sup>d)\" unfolding conn2 conn by simp\nlemma op_prop5: \"(\\<phi> \\<^bold>\\<squnion> \\<psi>)\\<^sup>c = (\\<phi>\\<^sup>c) \\<^bold>\\<sqinter> (\\<psi>\\<^sup>c)\" unfolding conn2 conn by simp\nlemma op_prop6: \"(\\<phi> \\<^bold>\\<sqinter> \\<psi>)\\<^sup>d = (\\<phi>\\<^sup>d) \\<^bold>\\<squnion> (\\<psi>\\<^sup>d)\" unfolding conn2 conn by simp\nlemma op_prop7: \"(\\<phi> \\<^bold>\\<sqinter> \\<psi>)\\<^sup>c = (\\<phi>\\<^sup>c) \\<^bold>\\<squnion> (\\<psi>\\<^sup>c)\" unfolding conn2 conn by simp\nlemma op_prop8: \"\\<^bold>\\<top>' = \\<^bold>n \\<^bold>\\<squnion> \\<^bold>e\" unfolding conn2 conn by simp\nlemma op_prop9: \"\\<^bold>\\<bottom>' = \\<^bold>n \\<^bold>\\<sqinter> \\<^bold>e\" unfolding conn2 conn by simp\n\n(**The notion of a fixed-point is fundamental. We speak of sets being fixed-points of operators.\nWe define a function that given an operator returns the set of all its fixed-points.*)\ndefinition fixpoints::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('w \\<sigma>)\\<sigma>\" (\"fp\") \n  where \"fp \\<phi> \\<equiv> \\<lambda>X. (\\<phi> X) \\<approx> X\"\n(**We can in fact 'operationalize' the function above thus obtaining a (2nd-order) 'fixed-point' connective*)\ndefinition op_fixpoint::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('w \\<sigma> \\<Rightarrow> 'w \\<sigma>)\" (\"(_\\<^sup>f\\<^sup>p)\")\n(* definition op_fixpoint (\"(_\\<^sup>f\\<^sup>p)\")  *)\n  where \"\\<phi>\\<^sup>f\\<^sup>p \\<equiv> \\<lambda>X. (\\<phi> X) \\<^bold>\\<leftrightarrow> X\"\n\ndeclare fixpoints_def[conn2] op_fixpoint_def[conn2]\n\n(**Interestingly, the fixed-point connective is definable in terms of the others*)\nlemma op_fixpoint_char: \"\\<phi>\\<^sup>f\\<^sup>p = (\\<phi> \\<^bold>\\<sqinter> \\<^bold>e) \\<^bold>\\<squnion> (\\<phi>\\<^sup>c \\<^bold>\\<sqinter> \\<^bold>n)\" unfolding conn2 order conn by blast\n\n(**Given an operator \\<phi>: the fixed-points of \\<phi>'s dual is the set of complements of \\<phi>' fixed-points*)\nlemma fp_dual: \"fp \\<phi>\\<^sup>d = (fp \\<phi>)\\<^sup>-\" unfolding order conn conn2 by blast\n(**the fixed-points of \\<phi>'s complement is the set of complements of the fixed-points of \\<phi>'s dual-complement*)\nlemma fp_compl: \"fp \\<phi>\\<^sup>c = (fp (\\<phi>\\<^sup>-))\\<^sup>-\" by (simp add: dual_compl_char2 dualcompl_invol fp_dual)\n(**the fixed-points of \\<phi>'s dual-complement is the set of complements of the fixed-points of \\<phi>'s complement*)\nlemma fp_dcompl: \"fp (\\<phi>\\<^sup>-) = (fp \\<phi>\\<^sup>c)\\<^sup>-\" by (simp add: dualcompl_invol fp_compl)\n\n(**The fixed-points function and the fixed-point connective are essentially related.*)\nlemma fp_rel: \"fp \\<phi> A \\<longleftrightarrow> (\\<phi>\\<^sup>f\\<^sup>p A) \\<approx> \\<^bold>\\<top>\" unfolding conn2 order conn by simp\nlemma fp_d_rel:  \"fp \\<phi>\\<^sup>d A \\<longleftrightarrow> \\<phi>\\<^sup>f\\<^sup>p(\\<^bold>\\<midarrow>A) \\<approx> \\<^bold>\\<top>\" unfolding conn2 order conn by blast\nlemma fp_c_rel: \"fp \\<phi>\\<^sup>c A \\<longleftrightarrow> \\<phi>\\<^sup>f\\<^sup>p A \\<approx> \\<^bold>\\<bottom>\" unfolding conn2 order conn by blast\nlemma fp_dc_rel: \"fp (\\<phi>\\<^sup>-) A \\<longleftrightarrow> \\<phi>\\<^sup>f\\<^sup>p(\\<^bold>\\<midarrow>A) \\<approx> \\<^bold>\\<bottom>\" unfolding conn2 order conn by simp\n\n(**The fixed-point operation is involutive*)\nlemma ofp_invol: \"(\\<phi>\\<^sup>f\\<^sup>p)\\<^sup>f\\<^sup>p = \\<phi>\" unfolding conn2 order conn by blast\n(**and commutes the dual with the dual-complement operations*)\nlemma ofp_comm_dc1: \"(\\<phi>\\<^sup>d)\\<^sup>f\\<^sup>p = (\\<phi>\\<^sup>f\\<^sup>p)\\<^sup>-\" unfolding conn2 order conn by blast\nlemma ofp_comm_dc2:\"(\\<phi>\\<^sup>-)\\<^sup>f\\<^sup>p = (\\<phi>\\<^sup>f\\<^sup>p)\\<^sup>d\" unfolding conn2 order conn by simp\n\n(**The fixed-point operation commutes with the complement*)\nlemma ofp_comm_compl: \"(\\<phi>\\<^sup>c)\\<^sup>f\\<^sup>p = (\\<phi>\\<^sup>f\\<^sup>p)\\<^sup>c\" unfolding conn2 order conn by blast\n(**The above motivates the following alternative definition for a 'complemented-fixed-point' operation*)\nlemma ofp_fixpoint_compl_def: \"\\<phi>\\<^sup>f\\<^sup>p\\<^sup>c = (\\<lambda>X. (\\<phi> X) \\<^bold>\\<triangle> X)\" unfolding conn2 conn by simp\n(**Analogously, the complemented fixed-point connective is also definable in terms of the others*)\nlemma op_fixpoint_compl_char: \"\\<phi>\\<^sup>f\\<^sup>p\\<^sup>c = (\\<phi> \\<^bold>\\<squnion> \\<^bold>e) \\<^bold>\\<sqinter> (\\<phi>\\<^sup>c \\<^bold>\\<squnion> \\<^bold>n)\" unfolding conn2 conn by blast\n\n(**In fact, function composition can be seen as an additional binary connective for operators.\n  We show below some interesting relationships that hold: *)\nlemma op_prop10: \"\\<phi> = (\\<^bold>e \\<circ> \\<phi>)\" unfolding conn2 fun_comp_def by simp\nlemma op_prop11: \"\\<phi> = (\\<phi> \\<circ> \\<^bold>e)\" unfolding conn2 fun_comp_def by simp\nlemma op_prop12: \"\\<^bold>e = (\\<^bold>n \\<circ> \\<^bold>n)\" unfolding conn2 conn fun_comp_def by simp\nlemma op_prop13: \"\\<phi>\\<^sup>c = (\\<^bold>n \\<circ> \\<phi>)\" unfolding conn2 fun_comp_def by simp\nlemma op_prop14: \"\\<phi>\\<^sup>- = (\\<phi> \\<circ> \\<^bold>n)\" unfolding conn2 fun_comp_def by simp\nlemma op_prop15: \"\\<phi>\\<^sup>d = (\\<^bold>n \\<circ> \\<phi> \\<circ> \\<^bold>n)\" unfolding conn2 fun_comp_def by simp\n\n(**There are also some useful properties regarding the images of operators*)\nlemma im_prop1: \"\\<lbrakk>\\<phi> D\\<rbrakk>\\<^sup>-  = \\<lbrakk>\\<phi>\\<^sup>d D\\<^sup>-\\<rbrakk>\" unfolding image_def op_dual_def sdfun_dcompl_def by (metis BA_dn setequ_ext)\nlemma im_prop2: \"\\<lbrakk>\\<phi>\\<^sup>c D\\<rbrakk>\\<^sup>- = \\<lbrakk>\\<phi> D\\<rbrakk>\" unfolding image_def svfun_compl_def sdfun_dcompl_def by (metis BA_dn setequ_ext)\nlemma im_prop3: \"\\<lbrakk>\\<phi>\\<^sup>d D\\<rbrakk>\\<^sup>- = \\<lbrakk>\\<phi> D\\<^sup>-\\<rbrakk>\" unfolding image_def op_dual_def sdfun_dcompl_def by (metis BA_dn setequ_ext)\nlemma im_prop4: \"\\<lbrakk>\\<phi>\\<^sup>- D\\<rbrakk>\\<^sup>- = \\<lbrakk>\\<phi>\\<^sup>d D\\<rbrakk>\" unfolding image_def op_dual_def sdfun_dcompl_def by (metis BA_dn setequ_ext)\nlemma im_prop5: \"\\<lbrakk>\\<phi>\\<^sup>c D\\<^sup>-\\<rbrakk>  = \\<lbrakk>\\<phi>\\<^sup>- D\\<rbrakk>\\<^sup>-\" unfolding image_def svfun_compl_def sdfun_dcompl_def by (metis (no_types, opaque_lifting) BA_dn setequ_ext)\nlemma im_prop6: \"\\<lbrakk>\\<phi>\\<^sup>- D\\<^sup>-\\<rbrakk>  = \\<lbrakk>\\<phi> D\\<rbrakk>\" unfolding image_def sdfun_dcompl_def by (metis BA_dn setequ_ext)\n\n\n(**Observe that all results obtained by assuming fixed-point predicates extend to their associated operators.*)\nlemma \"\\<phi>\\<^sup>f\\<^sup>p(A) \\<^bold>\\<and> \\<Gamma>(A) \\<preceq> \\<Delta>(A) \\<longrightarrow> (fp \\<phi>)(A) \\<longrightarrow> \\<Gamma>(A) \\<preceq> \\<Delta>(A)\"\n  by (simp add: fp_rel meet_def setequ_ext subset_def top_def)\nlemma \"\\<phi>\\<^sup>f\\<^sup>p(A) \\<^bold>\\<and> \\<phi>\\<^sup>f\\<^sup>p(B) \\<^bold>\\<and> (\\<Gamma> A B) \\<preceq> (\\<Delta> A B) \\<longrightarrow> (fp \\<phi>)(A) \\<and> (fp \\<phi>)(B) \\<longrightarrow> (\\<Gamma> A B) \\<preceq> (\\<Delta> A B)\"\n  by (simp add: fp_rel meet_def setequ_ext subset_def top_def)\n\nend", "meta": {"author": "davfuenmayor", "repo": "topological-semantics", "sha": "770a84ffa2cf8498bd5f60853d11be4d77fc8cd3", "save_path": "github-repos/isabelle/davfuenmayor-topological-semantics", "path": "github-repos/isabelle/davfuenmayor-topological-semantics/topological-semantics-770a84ffa2cf8498bd5f60853d11be4d77fc8cd3/boolean_algebra/boolean_algebra_functional.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8652240808393984, "lm_q1q2_score": 0.7689755050887572}}
{"text": "(*\n  File: Dijkstra.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Dijkstra's algorithm for shortest paths\\<close>\n\ntheory Dijkstra\n  imports Mapping_Str Arrays_Ex\nbegin\n\ntext \\<open>\n  Verification of Dijkstra's algorithm: function part.\n\n  The algorithm is also verified by Nordhoff and Lammich in\n  \\<^cite>\\<open>\"Dijkstra_Shortest_Path-AFP\"\\<close>.\n\\<close>\n\nsubsection \\<open>Graphs\\<close>\n\ndatatype graph = Graph \"nat list list\"\n\nfun size :: \"graph \\<Rightarrow> nat\" where\n  \"size (Graph G) = length G\"\n\nfun weight :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"weight (Graph G) m n = (G ! m) ! n\"\n\nfun valid_graph :: \"graph \\<Rightarrow> bool\" where\n  \"valid_graph (Graph G) \\<longleftrightarrow> (\\<forall>i<length G. length (G ! i) = length G)\"\nsetup \\<open>add_rewrite_rule @{thm valid_graph.simps}\\<close>\n\nsubsection \\<open>Paths on graphs\\<close>\n\ntext \\<open>The set of vertices less than n.\\<close>\ndefinition verts :: \"graph \\<Rightarrow> nat set\" where\n  \"verts G = {i. i < size G}\"\n\nlemma verts_mem [rewrite]: \"i \\<in> verts G \\<longleftrightarrow> i < size G\" by (simp add: verts_def)\nlemma card_verts [rewrite]: \"card (verts G) = size G\" using verts_def by auto\nlemma finite_verts [forward]: \"finite (verts G)\" using verts_def by auto\n\ndefinition is_path :: \"graph \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"is_path G p \\<longleftrightarrow> p \\<noteq> [] \\<and> set p \\<subseteq> verts G\"\n\nlemma is_path_to_in_verts [forward]: \"is_path G p \\<Longrightarrow> hd p \\<in> verts G \\<and> last p \\<in> verts G\"\n@proof @have \"last p \\<in> set p\" @qed\n\ndefinition joinable :: \"graph \\<Rightarrow> nat list \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"joinable G p q \\<longleftrightarrow> (is_path G p \\<and> is_path G q \\<and> last p = hd q)\"\n\ndefinition path_join :: \"graph \\<Rightarrow> nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where [rewrite]:\n  \"path_join G p q = p @ tl q\"\nsetup \\<open>register_wellform_data (\"path_join G p q\", [\"joinable G p q\"])\\<close>\nsetup \\<open>add_prfstep_check_req (\"path_join G p q\", \"joinable G p q\")\\<close>\n\nlemma path_join_is_path:\n  \"joinable G p q \\<Longrightarrow> is_path G (path_join G p q)\"\n@proof @have \"q = hd q # tl q\" @qed\nsetup \\<open>add_forward_prfstep_cond @{thm path_join_is_path} [with_term \"path_join ?G ?p ?q\"]\\<close>\n\nfun path_weight :: \"graph \\<Rightarrow> nat list \\<Rightarrow> nat\" where\n  \"path_weight G [] = 0\"\n| \"path_weight G (x # xs) = (if xs = [] then 0 else weight G x (hd xs) + path_weight G xs)\"\nsetup \\<open>fold add_rewrite_rule @{thms path_weight.simps}\\<close>\n\nlemma path_weight_singleton [rewrite]: \"path_weight G [x] = 0\" by auto2\nlemma path_weight_doubleton [rewrite]: \"path_weight G [m, n] = weight G m n\" by auto2\n\nlemma path_weight_sum [rewrite]:\n  \"joinable G p q \\<Longrightarrow> path_weight G (path_join G p q) = path_weight G p + path_weight G q\"\n@proof @induct p @qed\n\nfun path_set :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list set\" where\n  \"path_set G m n = {p. is_path G p \\<and> hd p = m \\<and> last p = n}\"\n\nlemma path_set_mem [rewrite]:\n  \"p \\<in> path_set G m n \\<longleftrightarrow> is_path G p \\<and> hd p = m \\<and> last p = n\" by simp\n\nlemma path_join_set: \"joinable G p q \\<Longrightarrow> path_join G p q \\<in> path_set G (hd p) (last q)\"\n@proof @have \"q = hd q # tl q\" @case \"tl q = []\" @qed\nsetup \\<open>add_forward_prfstep_cond @{thm path_join_set} [with_term \"path_join ?G ?p ?q\"]\\<close>\n\nsubsection \\<open>Shortest paths\\<close>\n\ndefinition is_shortest_path :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where [rewrite]:\n  \"is_shortest_path G m n p \\<longleftrightarrow>\n     (p \\<in> path_set G m n \\<and> (\\<forall>p'\\<in>path_set G m n. path_weight G p' \\<ge> path_weight G p))\"\n\nlemma is_shortest_pathD1 [forward]:\n  \"is_shortest_path G m n p \\<Longrightarrow> p \\<in> path_set G m n\" by auto2\n\nlemma is_shortest_pathD2 [forward]:\n  \"is_shortest_path G m n p \\<Longrightarrow> p' \\<in> path_set G m n \\<Longrightarrow> path_weight G p' \\<ge> path_weight G p\" by auto2\nsetup \\<open>del_prfstep_thm_eqforward @{thm is_shortest_path_def}\\<close>\n\ndefinition has_dist :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where [rewrite]:\n  \"has_dist G m n \\<longleftrightarrow> (\\<exists>p. is_shortest_path G m n p)\"\n\nlemma has_distI [forward]: \"is_shortest_path G m n p \\<Longrightarrow> has_dist G m n\" by auto2\nlemma has_distD [resolve]: \"has_dist G m n \\<Longrightarrow> \\<exists>p. is_shortest_path G m n p\" by auto2\nlemma has_dist_to_in_verts [forward]: \"has_dist G u v \\<Longrightarrow> u \\<in> verts G \\<and> v \\<in> verts G\" by auto2\nsetup \\<open>del_prfstep_thm @{thm has_dist_def}\\<close>\n\ndefinition dist :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where [rewrite]:\n  \"dist G m n = path_weight G (SOME p. is_shortest_path G m n p)\"\nsetup \\<open>register_wellform_data (\"dist G m n\", [\"has_dist G m n\"])\\<close>\n\nlemma dist_eq [rewrite]:\n  \"is_shortest_path G m n p \\<Longrightarrow> dist G m n = path_weight G p\" by auto2\n\nlemma distD [forward]:\n  \"has_dist G m n \\<Longrightarrow> p \\<in> path_set G m n \\<Longrightarrow> path_weight G p \\<ge> dist G m n\" by auto2\nsetup \\<open>del_prfstep_thm @{thm dist_def}\\<close>\n\nlemma shortest_init [resolve]: \"n \\<in> verts G \\<Longrightarrow> is_shortest_path G n n [n]\" by auto2\n\nsubsection \\<open>Interior points\\<close>\n\ntext \\<open>List of interior points\\<close>\ndefinition int_pts :: \"nat list \\<Rightarrow> nat set\" where [rewrite]:\n  \"int_pts p = set (butlast p)\"\n\nlemma int_pts_singleton [rewrite]: \"int_pts [x] = {}\" by auto2\nlemma int_pts_doubleton [rewrite]: \"int_pts [x, y] = {x}\" by auto2\n\ndefinition path_set_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> nat list set\" where\n  \"path_set_on G m n V = {p. p \\<in> path_set G m n \\<and> int_pts p \\<subseteq> V}\"\n\nlemma path_set_on_mem [rewrite]:\n  \"p \\<in> path_set_on G m n V \\<longleftrightarrow> p \\<in> path_set G m n \\<and> int_pts p \\<subseteq> V\" by (simp add: path_set_on_def)\n\ntext \\<open>Version of shortest path on a set of points\\<close>\ndefinition is_shortest_path_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat list \\<Rightarrow> nat set \\<Rightarrow> bool\" where [rewrite]:\n  \"is_shortest_path_on G m n p V \\<longleftrightarrow>\n    (p \\<in> path_set_on G m n V \\<and> (\\<forall>p'\\<in>path_set_on G m n V. path_weight G p' \\<ge> path_weight G p))\"\n\nlemma is_shortest_path_onD1 [forward]:\n  \"is_shortest_path_on G m n p V \\<Longrightarrow> p \\<in> path_set_on G m n V\" by auto2\n\nlemma is_shortest_path_onD2 [forward]:\n  \"is_shortest_path_on G m n p V \\<Longrightarrow> p' \\<in> path_set_on G m n V \\<Longrightarrow> path_weight G p' \\<ge> path_weight G p\" by auto2\nsetup \\<open>del_prfstep_thm_eqforward @{thm is_shortest_path_on_def}\\<close>\n\ndefinition has_dist_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> bool\" where [rewrite]:\n  \"has_dist_on G m n V \\<longleftrightarrow> (\\<exists>p. is_shortest_path_on G m n p V)\"\n\nlemma has_dist_onI [forward]: \"is_shortest_path_on G m n p V \\<Longrightarrow> has_dist_on G m n V\" by auto2\nlemma has_dist_onD [resolve]: \"has_dist_on G m n V \\<Longrightarrow> \\<exists>p. is_shortest_path_on G m n p V\" by auto2\nsetup \\<open>del_prfstep_thm @{thm has_dist_on_def}\\<close>\n\ndefinition dist_on :: \"graph \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<Rightarrow> nat\" where [rewrite]:\n  \"dist_on G m n V = path_weight G (SOME p. is_shortest_path_on G m n p V)\"\nsetup \\<open>register_wellform_data (\"dist_on G m n V\", [\"has_dist_on G m n V\"])\\<close>\n\nlemma dist_on_eq [rewrite]:\n  \"is_shortest_path_on G m n p V \\<Longrightarrow> dist_on G m n V = path_weight G p\" by auto2\n\nlemma dist_onD [forward]:\n  \"has_dist_on G m n V \\<Longrightarrow> p \\<in> path_set_on G m n V \\<Longrightarrow> path_weight G p \\<ge> dist_on G m n V\" by auto2\nsetup \\<open>del_prfstep_thm @{thm dist_on_def}\\<close>\n\nsubsection \\<open>Two splitting lemmas\\<close>\n\nlemma path_split1 [backward]: \"is_path G p \\<Longrightarrow> hd p \\<in> V \\<Longrightarrow> last p \\<notin> V \\<Longrightarrow>\n  \\<exists>p1 p2. joinable G p1 p2 \\<and> p = path_join G p1 p2 \\<and> int_pts p1 \\<subseteq> V \\<and> hd p2 \\<notin> V\"\n@proof @induct p @with\n  @subgoal \"p = a # p'\"\n    @let \"p = a # p'\"\n    @case \"p' = []\"\n    @case \"hd p' \\<notin> V\" @with @have \"p = path_join G [a, hd p'] p'\" @end\n    @obtain p1 p2 where \"joinable G p1 p2\" \"p' = path_join G p1 p2\" \"int_pts p1 \\<subseteq> V\" \"hd p2 \\<notin> V\"\n    @have \"p = path_join G (a # p1) p2\"\n  @endgoal @end\n@qed\n\nlemma path_split2 [backward]: \"is_path G p \\<Longrightarrow> hd p \\<noteq> last p \\<Longrightarrow>\n  \\<exists>q n. joinable G q [n, last p] \\<and> p = path_join G q [n, last p]\"\n@proof\n  @have \"p = butlast p @ [last p]\"\n  @have \"butlast p \\<noteq> []\"\n  @let \"n = last (butlast p)\"\n  @have \"p = path_join G (butlast p) [n, last p]\"\n@qed\n\nsubsection \\<open>Deriving has\\_dist and has\\_dist\\_on\\<close>\n\ndefinition known_dists :: \"graph \\<Rightarrow> nat set \\<Rightarrow> bool\" where [rewrite]:\n  \"known_dists G V \\<longleftrightarrow> (V \\<subseteq> verts G \\<and> 0 \\<in> V \\<and>\n      (\\<forall>i\\<in>verts G. has_dist_on G 0 i V) \\<and>\n      (\\<forall>i\\<in>V. has_dist G 0 i \\<and> dist G 0 i = dist_on G 0 i V))\"\n\nlemma derive_dist [backward2]:\n  \"known_dists G V \\<Longrightarrow>\n   m \\<in> verts G - V \\<Longrightarrow>\n   \\<forall>i\\<in>verts G - V. dist_on G 0 i V \\<ge> dist_on G 0 m V \\<Longrightarrow>\n   has_dist G 0 m \\<and> dist G 0 m = dist_on G 0 m V\"\n@proof\n  @obtain p where \"is_shortest_path_on G 0 m p V\"\n  @have \"is_shortest_path G 0 m p\" @with\n    @have \"p \\<in> path_set G 0 m\"\n    @have \"\\<forall>p'\\<in>path_set G 0 m. path_weight G p' \\<ge> path_weight G p\" @with\n      @obtain p1 p2 where \"joinable G p1 p2\" \"p' = path_join G p1 p2\"\n                          \"int_pts p1 \\<subseteq> V\" \"hd p2 \\<notin> V\"\n      @let \"x = last p1\"\n      @have \"dist_on G 0 x V \\<ge> dist_on G 0 m V\"\n      @have \"p1 \\<in> path_set_on G 0 x V\"\n      @have \"path_weight G p1 \\<ge> dist_on G 0 x V\"\n      @have \"path_weight G p' \\<ge> dist_on G 0 m V + path_weight G p2\"\n    @end\n  @end\n@qed\n\nlemma join_def' [resolve]: \"joinable G p q \\<Longrightarrow> path_join G p q = butlast p @ q\"\n@proof\n  @have \"p = butlast p @ [last p]\"\n  @have \"path_join G p q = butlast p @ [last p] @ tl q\"\n@qed\n\nlemma int_pts_join [rewrite]:\n  \"joinable G p q \\<Longrightarrow> int_pts (path_join G p q) = int_pts p \\<union> int_pts q\"\n@proof @have \"path_join G p q = butlast p @ q\" @qed\n\nlemma dist_on_triangle_ineq [backward]:\n  \"has_dist_on G k m V \\<Longrightarrow> has_dist_on G k n V \\<Longrightarrow> V \\<subseteq> verts G \\<Longrightarrow> n \\<in> verts G \\<Longrightarrow> m \\<in> V \\<Longrightarrow>\n   dist_on G k m V + weight G m n \\<ge> dist_on G k n V\"\n@proof\n  @obtain p where \"is_shortest_path_on G k m p V\"\n  @let \"pq = path_join G p [m, n]\"\n  @have \"V \\<union> {m} = V\"\n  @have \"pq \\<in> path_set_on G k n V\"\n@qed\n\nlemma derive_dist_on [backward2]:\n  \"known_dists G V \\<Longrightarrow>\n   m \\<in> verts G - V \\<Longrightarrow>\n   \\<forall>i\\<in>verts G - V. dist_on G 0 i V \\<ge> dist_on G 0 m V \\<Longrightarrow>\n   V' = V \\<union> {m} \\<Longrightarrow>\n   n \\<in> verts G - V' \\<Longrightarrow>\n   has_dist_on G 0 n V' \\<and> dist_on G 0 n V' = min (dist_on G 0 n V) (dist_on G 0 m V + weight G m n)\"\n@proof\n  @have \"has_dist G 0 m \\<and> dist G 0 m = dist_on G 0 m V\"\n  @let \"M = min (dist_on G 0 n V) (dist_on G 0 m V + weight G m n)\"\n  @have \"\\<forall>p\\<in>path_set_on G 0 n V'. path_weight G p \\<ge> M\" @with\n    @obtain q n' where \"joinable G q [n', n]\" \"p = path_join G q [n', n]\"\n    @have \"q \\<in> path_set G 0 n'\"\n    @have \"n' \\<in> V'\"\n    @case \"n' \\<in> V\" @with\n      @have \"dist_on G 0 n' V = dist G 0 n'\"\n      @have \"path_weight G q \\<ge> dist_on G 0 n' V\"\n      @have \"path_weight G p \\<ge> dist_on G 0 n' V + weight G n' n\"\n      @have \"dist_on G 0 n' V + weight G n' n \\<ge> dist_on G 0 n V\"\n    @end\n    @have \"n' = m\"\n    @have \"path_weight G q \\<ge> dist G 0 m\"\n    @have \"path_weight G p \\<ge> dist G 0 m + weight G m n\"\n  @end\n  @case \"dist_on G 0 m V + weight G m n \\<ge> dist_on G 0 n V\" @with\n    @obtain p where \"is_shortest_path_on G 0 n p V\"\n    @have \"is_shortest_path_on G 0 n p V'\" @with\n      @have \"p \\<in> path_set_on G 0 n V'\" @with @have \"V \\<subseteq> V'\" @end\n    @end\n  @end\n  @have \"M = dist_on G 0 m V + weight G m n\"\n  @obtain pm where \"is_shortest_path_on G 0 m pm V\"\n  @have \"path_weight G pm = dist G 0 m\"\n  @let \"p = path_join G pm [m, n]\"\n  @have \"joinable G pm [m, n]\"\n  @have \"path_weight G p = path_weight G pm + weight G m n\"\n  @have \"is_shortest_path_on G 0 n p V'\"\n@qed\n\nsubsection \\<open>Invariant for the Dijkstra's algorithm\\<close>\n\ntext \\<open>The state consists of an array maintaining the best estimates,\n  and a heap containing estimates for the unknown vertices.\\<close>\ndatatype state = State (est: \"nat list\") (heap: \"(nat, nat) map\")\nsetup \\<open>add_simple_datatype \"state\"\\<close>\n\ndefinition unknown_set :: \"state \\<Rightarrow> nat set\" where [rewrite]:\n  \"unknown_set S = keys_of (heap S)\"\n\ndefinition known_set :: \"state \\<Rightarrow> nat set\" where [rewrite]:\n  \"known_set S = {..<length (est S)} - unknown_set S\"\n\ntext \\<open>Invariant: for every vertex, the estimate is at least the shortest distance.\n  Furthermore, for the known vertices the estimate is exact.\\<close>\ndefinition inv :: \"graph \\<Rightarrow> state \\<Rightarrow> bool\" where [rewrite]:\n  \"inv G S \\<longleftrightarrow> (let V = known_set S; W = unknown_set S; M = heap S in\n      (length (est S) = size G \\<and> known_dists G V \\<and>\n      keys_of M \\<subseteq> verts G \\<and>\n      (\\<forall>i\\<in>W. M\\<langle>i\\<rangle> = Some (est S ! i)) \\<and>\n      (\\<forall>i\\<in>V. est S ! i = dist G 0 i) \\<and>\n      (\\<forall>i\\<in>verts G. est S ! i = dist_on G 0 i V)))\"\n\nlemma invE1 [forward]: \"inv G S \\<Longrightarrow> length (est S) = size G \\<and> known_dists G (known_set S) \\<and> unknown_set S \\<subseteq> verts G\" by auto2\nlemma invE2 [forward]: \"inv G S \\<Longrightarrow> i \\<in> known_set S \\<Longrightarrow> est S ! i = dist G 0 i\" by auto2\nlemma invE3 [forward]: \"inv G S \\<Longrightarrow> i \\<in> verts G \\<Longrightarrow> est S ! i = dist_on G 0 i (known_set S)\" by auto2\nlemma invE4 [rewrite]: \"inv G S \\<Longrightarrow> i \\<in> unknown_set S \\<Longrightarrow> (heap S)\\<langle>i\\<rangle> = Some (est S ! i)\" by auto2\nsetup \\<open>del_prfstep_thm_str \"@eqforward\" @{thm inv_def}\\<close>\n\nlemma inv_unknown_set [rewrite]:\n  \"inv G S \\<Longrightarrow> unknown_set S = verts G - known_set S\" by auto2\n\nlemma dijkstra_end_inv [forward]:\n  \"inv G S \\<Longrightarrow> unknown_set S = {} \\<Longrightarrow> \\<forall>i\\<in>verts G. has_dist G 0 i \\<and> est S ! i = dist G 0 i\" by auto2\n\nsubsection \\<open>Starting state\\<close>\n\ndefinition dijkstra_start_state :: \"graph \\<Rightarrow> state\" where [rewrite]:\n  \"dijkstra_start_state G =\n     State (list (\\<lambda>i. if i = 0 then 0 else weight G 0 i) (size G))\n           (map_constr (\\<lambda>i. i > 0) (\\<lambda>i. weight G 0 i) (size G))\"\nsetup \\<open>register_wellform_data (\"dijkstra_start_state G\", [\"size G > 0\"])\\<close>\n\nlemma dijkstra_start_known_set [rewrite]:\n  \"size G > 0 \\<Longrightarrow> known_set (dijkstra_start_state G) = {0}\" by auto2\n    \nlemma dijkstra_start_unknown_set [rewrite]:\n  \"size G > 0 \\<Longrightarrow> unknown_set (dijkstra_start_state G) = verts G - {0}\" by auto2\n\nlemma card_start_state [rewrite]:\n  \"size G > 0 \\<Longrightarrow> card (unknown_set (dijkstra_start_state G)) = size G - 1\"\n@proof @have \"0 \\<in> verts G\" @qed\n\ntext \\<open>Starting start of Dijkstra's algorithm satisfies the invariant.\\<close>\ntheorem dijkstra_start_inv [backward]:\n  \"size G > 0 \\<Longrightarrow> inv G (dijkstra_start_state G)\"\n@proof\n  @let \"V = {0::nat}\"\n  @have \"has_dist G 0 0 \\<and> dist G 0 0 = 0\" @with\n    @have \"is_shortest_path G 0 0 [0]\" @end\n  @have \"has_dist_on G 0 0 V \\<and> dist_on G 0 0 V = 0\" @with\n    @have \"is_shortest_path_on G 0 0 [0] V\" @end\n  @have \"V \\<subseteq> verts G \\<and> 0 \\<in> V\"\n  @have (@rule) \"\\<forall>i\\<in>verts G. i \\<noteq> 0 \\<longrightarrow> has_dist_on G 0 i V \\<and> dist_on G 0 i V = weight G 0 i\" @with\n    @let \"p = [0, i]\"\n    @have \"is_shortest_path_on G 0 i p V\" @with\n      @have \"p \\<in> path_set_on G 0 i V\"\n      @have \"\\<forall>p'\\<in>path_set_on G 0 i V. path_weight G p' \\<ge> weight G 0 i\" @with\n        @obtain q n where \"joinable G q [n, last p']\" \"p' = path_join G q [n, last p']\"\n        @have \"n \\<in> V\" @have \"n = 0\"\n        @have \"path_weight G p' = path_weight G q + weight G 0 i\"\n      @end\n    @end\n  @end\n@qed\n\nsubsection \\<open>Step of Dijkstra's algorithm\\<close>\n\nfun dijkstra_step :: \"graph \\<Rightarrow> nat \\<Rightarrow> state \\<Rightarrow> state\" where\n  \"dijkstra_step G m (State e M) =\n    (let M' = delete_map m M;\n         e' = list_update_set (\\<lambda>i. i \\<in> keys_of M') (\\<lambda>i. min (e ! m + weight G m i) (e ! i)) e;\n         M'' = map_update_all (\\<lambda>i. e' ! i) M'\n     in State e' M'')\"\nsetup \\<open>add_rewrite_rule @{thm dijkstra_step.simps}\\<close>\nsetup \\<open>register_wellform_data (\"dijkstra_step G m S\", [\"inv G S\", \"m \\<in> unknown_set S\"])\\<close>\n\nlemma has_dist_on_larger [backward1]:\n  \"has_dist G m n \\<Longrightarrow> has_dist_on G m n V \\<Longrightarrow> dist_on G m n V = dist G m n \\<Longrightarrow>\n   has_dist_on G m n (V \\<union> {x}) \\<and> dist_on G m n (V \\<union> {x}) = dist G m n\"\n@proof\n  @obtain p where \"is_shortest_path_on G m n p V\"\n  @let \"V' = V \\<union> {x}\"\n  @have \"p \\<in> path_set_on G m n V'\" @with @have \"V \\<subseteq> V'\" @end\n  @have \"is_shortest_path_on G m n p V'\"\n@qed\n\nlemma dijkstra_step_unknown_set [rewrite]:\n  \"inv G S \\<Longrightarrow> m \\<in> unknown_set S \\<Longrightarrow> unknown_set (dijkstra_step G m S) = unknown_set S - {m}\" by auto2\n\nlemma dijkstra_step_known_set [rewrite]:\n  \"inv G S \\<Longrightarrow> m \\<in> unknown_set S \\<Longrightarrow> known_set (dijkstra_step G m S) = known_set S \\<union> {m}\" by auto2\n\ntext \\<open>One step of Dijkstra's algorithm preserves the invariant.\\<close>\ntheorem dijkstra_step_preserves_inv [backward]:\n  \"inv G S \\<Longrightarrow> is_heap_min m (heap S) \\<Longrightarrow> inv G (dijkstra_step G m S)\"\n@proof\n  @let \"V = known_set S\" \"V' = V \\<union> {m}\"\n  @have (@rule) \"\\<forall>i\\<in>V. has_dist G 0 i \\<and> has_dist_on G 0 i V' \\<and> dist_on G 0 i V' = dist G 0 i\"\n  @have \"has_dist G 0 m \\<and> dist G 0 m = dist_on G 0 m V\"\n  @have \"has_dist_on G 0 m V' \\<and> dist_on G 0 m V' = dist G 0 m\"\n  @have (@rule) \"\\<forall>i\\<in>verts G - V'. has_dist_on G 0 i V' \\<and> dist_on G 0 i V' = min (dist_on G 0 i V) (dist_on G 0 m V + weight G m i)\"\n  @let \"S' = dijkstra_step G m S\"\n  @have \"known_dists G V'\"\n  @have \"\\<forall>i\\<in>V'. est S' ! i = dist G 0 i\"\n  @have \"\\<forall>i\\<in>verts G. est S' ! i = dist_on G 0 i V'\" @with @case \"i \\<in> V'\" @end\n@qed\n\ndefinition is_dijkstra_step :: \"graph \\<Rightarrow> state \\<Rightarrow> state \\<Rightarrow> bool\" where [rewrite]:\n  \"is_dijkstra_step G S S' \\<longleftrightarrow> (\\<exists>m. is_heap_min m (heap S) \\<and> S' = dijkstra_step G m S)\"\n\nlemma is_dijkstra_stepI [backward2]:\n  \"is_heap_min m (heap S) \\<Longrightarrow> dijkstra_step G m S = S' \\<Longrightarrow> is_dijkstra_step G S S'\" by auto2\n\nlemma is_dijkstra_stepD1 [forward]:\n  \"inv G S \\<Longrightarrow> is_dijkstra_step G S S' \\<Longrightarrow> inv G S'\" by auto2\n\nlemma is_dijkstra_stepD2 [forward]:\n  \"inv G S \\<Longrightarrow> is_dijkstra_step G S S' \\<Longrightarrow> card (unknown_set S') = card (unknown_set S) - 1\" by auto2\nsetup \\<open>del_prfstep_thm @{thm is_dijkstra_step_def}\\<close>\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Auto2_Imperative_HOL/Functional/Dijkstra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.863391617003942, "lm_q1q2_score": 0.768672581553431}}
{"text": "section \"Stack Machine and Compilation\"\n\ntheory ASM\nimports AExp\nbegin\n\nsubsection \"Stack Machine\"\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk  =  n # stk\" |\n\"exec1 (LOAD x) s stk  =  s(x) # stk\" |\n\"exec1  ADD _ (j#i#stk)  =  (i + j) # stk\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i#is) s stk = exec is s (exec1 i s stk)\"\n\nvalue \"exec [LOADI 5, LOAD ''y'', ADD] <''x'' := 42, ''y'' := 43> [50]\"\n\nlemma exec_append[simp]:\n  \"exec (is1 @ is2) s stk = exec is2 s (exec is1 s stk)\"\napply(induction is1 arbitrary: stk)\napply (auto)\ndone\n\nsubsection \"Compilation\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e\\<^sub>1 e\\<^sub>2) = comp e\\<^sub>1 @ comp e\\<^sub>2 @ [ADD]\"\n\nvalue \"comp (Plus (Plus (V ''x'') (N 1)) (V ''z''))\"\n\ntheorem exec_comp: \"exec (comp a) s stk = aval a s # stk\"\napply(induction a arbitrary: stk)\napply (auto)\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Complete/ASM.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.8633916082162403, "lm_q1q2_score": 0.7686725636771319}}
{"text": "(*\n  File: Lists_Ex.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Lists\\<close>\n\ntheory Lists_Ex\n  imports Mapping_Str\nbegin\n\ntext \\<open>\n  Examples on lists. The itrev example comes from\n  \\cite[Section 2.4]{prog-prove}.\n\n  The development here of insertion and deletion on lists is\n  essential for verifying functional binary search trees and\n  red-black trees. The idea, following Nipkow~\\cite{nipkow16},\n  is that showing sorted-ness and preservation of multisets for trees\n  should be done on the in-order traversal of the tree.\n\\<close>\n\nsubsection \\<open>Linear time version of rev\\<close>\n\nfun itrev :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"itrev []       ys = ys\"\n| \"itrev (x # xs) ys = itrev xs (x # ys)\"\nsetup \\<open>fold add_rewrite_rule @{thms itrev.simps}\\<close>\n\nlemma itrev_eq_rev: \"itrev x [] = rev x\"\n@proof\n  @induct x for \"\\<forall>y. itrev x y = rev x @ y\" arbitrary y\n@qed\n\nsubsection \\<open>Strict sorted\\<close>\n\nfun strict_sorted :: \"'a::linorder list \\<Rightarrow> bool\" where\n  \"strict_sorted [] = True\"\n| \"strict_sorted (x # ys) = ((\\<forall>y\\<in>set ys. x < y) \\<and> strict_sorted ys)\"\nsetup \\<open>fold add_rewrite_rule @{thms strict_sorted.simps}\\<close>\n\nlemma strict_sorted_appendI [backward]:\n  \"strict_sorted xs \\<and> strict_sorted ys \\<and> (\\<forall>x\\<in>set xs. \\<forall>y\\<in>set ys. x < y) \\<Longrightarrow> strict_sorted (xs @ ys)\"\n@proof @induct xs @qed\n\nlemma strict_sorted_appendE1 [forward]:\n  \"strict_sorted (xs @ ys) \\<Longrightarrow> strict_sorted xs \\<and> strict_sorted ys\"\n@proof @induct xs @qed\n\nlemma strict_sorted_appendE2 [forward]:\n  \"strict_sorted (xs @ ys) \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> \\<forall>y\\<in>set ys. x < y\"\n@proof @induct xs @qed\n\nlemma strict_sorted_distinct [forward]: \"strict_sorted l \\<Longrightarrow> distinct l\"\n@proof @induct l @qed\n\nsubsection \\<open>Ordered insert\\<close>\n\nfun ordered_insert :: \"'a::ord \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"ordered_insert x [] = [x]\"\n| \"ordered_insert x (y # ys) = (\n    if x = y then (y # ys)\n    else if x < y then x # (y # ys)\n    else y # ordered_insert x ys)\"\nsetup \\<open>fold add_rewrite_rule @{thms ordered_insert.simps}\\<close>\n\nlemma ordered_insert_set [rewrite]:\n  \"set (ordered_insert x ys) = {x} \\<union> set ys\"\n@proof @induct ys @qed\n\nlemma ordered_insert_sorted [forward]:\n  \"strict_sorted ys \\<Longrightarrow> strict_sorted (ordered_insert x ys)\"\n@proof @induct ys @qed\n\nlemma ordered_insert_binary [rewrite]:\n  \"strict_sorted (xs @ a # ys) \\<Longrightarrow> ordered_insert x (xs @ a # ys) =\n    (if x < a then ordered_insert x xs @ a # ys\n     else if x > a then xs @ a # ordered_insert x ys\n     else xs @ a # ys)\"\n@proof @induct xs @qed\n\nsubsection \\<open>Deleting an element\\<close>\n\nfun remove_elt_list :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"remove_elt_list x [] = []\"\n| \"remove_elt_list x (y # ys) = (if y = x then remove_elt_list x ys else y # remove_elt_list x ys)\"\nsetup \\<open>fold add_rewrite_rule @{thms remove_elt_list.simps}\\<close>\n\nlemma remove_elt_list_set [rewrite]:\n  \"set (remove_elt_list x ys) = set ys - {x}\"\n@proof @induct ys @qed\n\nlemma remove_elt_list_sorted [forward]:\n  \"strict_sorted ys \\<Longrightarrow> strict_sorted (remove_elt_list x ys)\"\n@proof @induct ys @qed\n\nlemma remove_elt_idem [rewrite]:\n  \"x \\<notin> set ys \\<Longrightarrow> remove_elt_list x ys = ys\"\n@proof @induct ys @qed\n\nlemma remove_elt_list_binary [rewrite]:\n  \"strict_sorted (xs @ a # ys) \\<Longrightarrow> remove_elt_list x (xs @ a # ys) =\n    (if x < a then remove_elt_list x xs @ a # ys\n     else if x > a then xs @ a # remove_elt_list x ys else xs @ ys)\"\n@proof @induct xs @with\n  @subgoal \"xs = []\"\n    @case \"x < a\" @with @have \"x \\<notin> set ys\" @end\n  @endgoal @end\n@qed\n\nsubsection \\<open>Ordered insertion into list of pairs\\<close>\n\nfun ordered_insert_pairs :: \"'a::ord \\<Rightarrow> 'b \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow> ('a \\<times> 'b) list\" where\n  \"ordered_insert_pairs x v [] = [(x, v)]\"\n| \"ordered_insert_pairs x v (y # ys) = (\n    if x = fst y then ((x, v) # ys)\n    else if x < fst y then (x, v) # (y # ys)\n    else y # ordered_insert_pairs x v ys)\"\nsetup \\<open>fold add_rewrite_rule @{thms ordered_insert_pairs.simps}\\<close>\n\nlemma ordered_insert_pairs_map [rewrite]:\n  \"map_of_alist (ordered_insert_pairs x v ys) = update_map (map_of_alist ys) x v\"\n@proof @induct ys @qed\n\nlemma ordered_insert_pairs_set [rewrite]:\n  \"set (map fst (ordered_insert_pairs x v ys)) = {x} \\<union> set (map fst ys)\"\n@proof @induct ys @qed\n\nlemma ordered_insert_pairs_sorted [backward]:\n  \"strict_sorted (map fst ys) \\<Longrightarrow> strict_sorted (map fst (ordered_insert_pairs x v ys))\"\n@proof @induct ys @qed\n\nlemma ordered_insert_pairs_binary [rewrite]:\n  \"strict_sorted (map fst (xs @ a # ys)) \\<Longrightarrow> ordered_insert_pairs x v (xs @ a # ys) =\n    (if x < fst a then ordered_insert_pairs x v xs @ a # ys\n     else if x > fst a then xs @ a # ordered_insert_pairs x v ys\n     else xs @ (x, v) # ys)\"\n@proof @induct xs @qed\n\nsubsection \\<open>Deleting from a list of pairs\\<close>\n\nfun remove_elt_pairs :: \"'a \\<Rightarrow> ('a \\<times> 'b) list \\<Rightarrow> ('a \\<times> 'b) list\" where\n  \"remove_elt_pairs x [] = []\"\n| \"remove_elt_pairs x (y # ys) = (if fst y = x then ys else y # remove_elt_pairs x ys)\"\nsetup \\<open>fold add_rewrite_rule @{thms remove_elt_pairs.simps}\\<close>\n\nlemma remove_elt_pairs_map [rewrite]:\n  \"strict_sorted (map fst ys) \\<Longrightarrow> map_of_alist (remove_elt_pairs x ys) = delete_map x (map_of_alist ys)\"\n@proof @induct ys @with\n  @subgoal \"ys = y # ys'\"\n    @case \"fst y = x\" @with @have \"x \\<notin> set (map fst ys')\" @end\n  @endgoal @end\n@qed\n\nlemma remove_elt_pairs_on_set [rewrite]:\n  \"strict_sorted (map fst ys) \\<Longrightarrow> set (map fst (remove_elt_pairs x ys)) = set (map fst ys) - {x}\"\n@proof @induct ys @qed\n\nlemma remove_elt_pairs_sorted [backward]:\n  \"strict_sorted (map fst ys) \\<Longrightarrow> strict_sorted (map fst (remove_elt_pairs x ys))\"\n@proof @induct ys @qed\n\nlemma remove_elt_pairs_idem [rewrite]:\n  \"x \\<notin> set (map fst ys) \\<Longrightarrow> remove_elt_pairs x ys = ys\"\n@proof @induct ys @qed\n\nlemma remove_elt_pairs_binary [rewrite]:\n  \"strict_sorted (map fst (xs @ a # ys)) \\<Longrightarrow> remove_elt_pairs x (xs @ a # ys) =\n    (if x < fst a then remove_elt_pairs x xs @ a # ys\n     else if x > fst a then xs @ a # remove_elt_pairs x ys else xs @ ys)\"\n@proof @induct xs @with\n  @subgoal \"xs = []\"\n    @case \"x < fst a\" @with @have \"x \\<notin> set (map fst ys)\" @end\n  @endgoal @end\n@qed\n\nsubsection \\<open>Search in a list of pairs\\<close>\n\nlemma map_of_alist_binary [rewrite]:\n  \"strict_sorted (map fst (xs @ a # ys)) \\<Longrightarrow> (map_of_alist (xs @ a # ys))\\<langle>x\\<rangle> =\n   (if x < fst a then (map_of_alist xs)\\<langle>x\\<rangle>\n    else if x > fst a then (map_of_alist ys)\\<langle>x\\<rangle> else Some (snd a))\"\n@proof @induct xs @with\n  @subgoal \"xs = []\"\n    @case \"x \\<notin> set (map fst ys)\"\n  @endgoal @end\n@qed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Auto2_Imperative_HOL/Functional/Lists_Ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8902942188450159, "lm_q1q2_score": 0.7686725589589477}}
{"text": "(*\n  File:     Error_Function_Asymptotics.thy\n  Author:   Manuel Eberl, TU München\n\n  The asymptotics of the real error function\n*)\nsubsection \\<open>Asymptotics\\<close>\ntheory Error_Function_Asymptotics\n  imports Error_Function Landau_Symbols.Landau_More\nbegin\n\nlemma real_powr_eq_powerI:\n  \"x > 0 \\<Longrightarrow> y = real y' \\<Longrightarrow> x powr y = x ^ y'\"\n  by (simp add: powr_realpow)\n\ndefinition erf_remainder_integral where\n  \"erf_remainder_integral n x =\n     lim (\\<lambda>m. integral {x..x + real m} (\\<lambda>t. exp (-(t^2)) / t ^ (2*n)))\"\n\ntext \\<open>\n  The following is the remainder term in the asymptotic expansion of @{term erfc}.\n\\<close>\ndefinition erf_remainder where\n  \"erf_remainder n x =\n     ((-1)^n * 2 * fact (2*n)) / (sqrt pi * 4 ^ n * fact n) *\n     erf_remainder_integral n x\"\n  \n\nlemma erf_remainder_integral_aux_nonneg:\n  \"x > 0 \\<Longrightarrow> integral {x..x + real m} (\\<lambda>t. exp (-(t^2)) / t ^ (2*n)) \\<ge> 0\"\n  by (intro integral_nonneg integrable_continuous_real) (auto intro!: continuous_intros)\n\nlemma erf_remainder_integral_aux_bound:\n  assumes \"x > 0\"\n  shows   \"norm (integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n))) \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\"\n    and   \"integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n)) \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\"\nproof -\n  have \"norm (integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n))) \\<le>\n          integral {x..x + real m} (\\<lambda>t. exp (-x*t) / x ^ (2*n))\"\n  proof (intro integral_norm_bound_integral ballI)\n    fix t assume t: \"t \\<in> {x..x + real m}\"\n    from t have \"norm (exp (-t\\<^sup>2) / t ^ (2*n)) = exp (-t\\<^sup>2) / t ^ (2*n)\" by simp\n    also have \"\\<dots> \\<le> exp (-x*t) / x ^ (2*n)\" using t assms\n      by (intro frac_le) (simp_all add: self_le_power power2_eq_square power_mono)\n    finally show \"norm (exp (-t\\<^sup>2) / t ^ (2*n)) \\<le> \\<dots>\" by simp\n  qed (insert assms, auto intro!: continuous_intros integrable_continuous_real)\n  also have \"\\<dots> = -exp (-x*(x + real m)) / x ^ (2*n+1) - (-exp (-x*x) / x ^ (2*n+1))\"\n    using assms\n    by (intro integral_unique fundamental_theorem_of_calculus)\n       (auto simp: has_field_derivative_iff_has_vector_derivative [symmetric]\n             intro!: derivative_eq_intros)\n  also have \"\\<dots> \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\" using assms by (simp add: power2_eq_square)\n  finally show *: \"norm (integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n))) \\<le>\n                      exp (-x\\<^sup>2) / x ^ (2*n+1)\" .\n  have \"integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n)) \\<le>\n          norm (integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n)))\" by simp\n  also note *\n  finally show \"integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n)) \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\" .\nqed\n\nlemma convergent_erf_remainder_integral:\n  assumes \"x > 0\"\n  shows   \"convergent (\\<lambda>m. integral {x..x + real m} (\\<lambda>t. exp (-(t^2)) / t ^ (2*n)))\"\nproof (intro Bseq_mono_convergent BseqI'; clarify?)\n  fix m :: nat\n  show \"norm (integral {x..x + real m} (\\<lambda>t. exp (-t\\<^sup>2) / t ^ (2*n))) \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\"\n    using assms by (rule erf_remainder_integral_aux_bound)\nqed (insert assms, auto intro!: integral_subset_le integrable_continuous_real continuous_intros)\n\nlemma LIMSEQ_erf_remainder_integral:\n  \"x > 0 \\<Longrightarrow> (\\<lambda>m. integral {x..x + real m} (\\<lambda>t. exp (-(t^2)) / t ^ (2*n))) \\<longlonglongrightarrow>\n                 erf_remainder_integral n x\"\n  using convergent_erf_remainder_integral[of x]\n  by (simp add: convergent_LIMSEQ_iff erf_remainder_integral_def)\n\n\ntext \\<open>\n  We show some bounds on the remainder term.\n\\<close>\nlemma\n  assumes \"x > 0\"\n  shows   erf_remainder_integral_nonneg: \"erf_remainder_integral n x \\<ge> 0\"\n    and   erf_remainder_integral_bound:  \"erf_remainder_integral n x \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\"\nproof -\n  note * = LIMSEQ_erf_remainder_integral[OF assms]\n  show \"erf_remainder_integral n x \\<ge> 0\"\n    by (intro tendsto_le[OF _ * tendsto_const] always_eventually\n          erf_remainder_integral_aux_nonneg allI assms sequentially_bot)\n  show \"erf_remainder_integral n x \\<le> exp (-x\\<^sup>2) / x ^ (2*n+1)\"\n    by (intro tendsto_le[OF _ tendsto_const *] always_eventually\n          erf_remainder_integral_aux_bound allI assms sequentially_bot)\nqed\n\nlemma erf_remainder_integral_bigo: \n  \"erf_remainder_integral n \\<in> O(\\<lambda>x. exp (-x\\<^sup>2) / x ^ (2*n+1))\"\n  using erf_remainder_integral_nonneg erf_remainder_integral_bound\n  by (auto intro!: bigoI[of _ 1] eventually_mono [OF eventually_gt_at_top[of \"0::real\"]])\n  \ntheorem erf_remainder_bigo: \"erf_remainder n \\<in> O(\\<lambda>x. exp (-x\\<^sup>2) / x ^ (2*n+1))\"\n  using erf_remainder_integral_bigo[of n] by (simp add: erf_remainder_def [abs_def])\n\n\ntext \\<open>\n  Next, we unroll the remainder term to develop the asymptotic expansion.\n\\<close>\nlemma erf_remainder_integral_0_conv_erfc:\n  assumes \"(x::real) > 0\"\n  shows   \"erf_remainder_integral 0 x = sqrt pi / 2 * erfc x\"\nproof -\n  have \"(\\<lambda>m. sqrt pi / 2 * (erf (x + real m) - erf x)) \\<longlonglongrightarrow> sqrt pi / 2 * erfc x\"\n    (is \"filterlim ?f _ _\") unfolding erfc_def\n    by (intro tendsto_intros filterlim_tendsto_add_at_top[OF \n          tendsto_const filterlim_real_sequentially])\n  also have \"?f = (\\<lambda>m. integral {x..x+real m} (\\<lambda>t. exp (-t\\<^sup>2)))\"\n    by (auto simp: fun_eq_iff integral_unique[OF integral_exp_minus_squared_real])\n  finally have \"(\\<lambda>m. integral {x..x + real m} (\\<lambda>t. exp (- t\\<^sup>2))) \\<longlonglongrightarrow> sqrt pi / 2 * erfc x\" .\n  moreover have \"(\\<lambda>m. integral {x..x + real m} (\\<lambda>t. exp (- t\\<^sup>2))) \\<longlonglongrightarrow> erf_remainder_integral 0 x\"\n    using LIMSEQ_erf_remainder_integral[of x 0] assms by simp\n  ultimately show \"erf_remainder_integral 0 x = sqrt pi / 2 * erfc x\"\n    by (intro LIMSEQ_unique)\nqed\n\ntext \\<open>\n  The first remainder is the @{term erfc} function itself.\n\\<close>\nlemma erf_remainder_0_conv_erfc: \"x > 0 \\<Longrightarrow> erf_remainder 0 x = erfc x\"\n  by (simp add: erf_remainder_def erf_remainder_integral_0_conv_erfc)    \n\ntext \\<open>\n  Also, the following recurrence allows us to get the next term of the asymptotic expansion.\n\\<close>\nlemma erf_remainder_integral_conv_Suc:\n  assumes \"x > 0\"\n  shows   \"erf_remainder_integral n x = exp (-x\\<^sup>2) / (2*x^(2*n+1)) -\n             real (2*n+1) / 2 * erf_remainder_integral (Suc n) x\"\nproof -\n  let ?A = \"\\<lambda>m. {x..x + real m}\"\n  let ?J = \"\\<lambda>m n. integral {x..x+real m} (\\<lambda>t. exp(-t\\<^sup>2) / t ^ (2*n))\"\n  define I where\n    \"I = (\\<lambda>m. exp (- (x + real m)\\<^sup>2) / (- 2 * (x + real m) ^ (2 * n + 1)) -\n              exp (- x\\<^sup>2) * inverse (- 2 * x ^ (2 * n + 1)) - real (2*n+1)/2 * ?J m (Suc n))\"\n\n  have I_eq: \"I = (\\<lambda>m. integral (?A m) (\\<lambda>t. exp (- t\\<^sup>2) / t ^ (2 * n)))\"\n  proof\n    fix m :: nat\n    have \"((\\<lambda>t. (-2*t*exp (-(t^2))) * inverse (-2*t^(2*n+1))) has_integral I m) (?A m)\"\n    proof (rule integration_by_parts[OF bounded_bilinear_mult])\n      fix t assume t: \"t \\<in> ?A m\"\n      with assms show \"((\\<lambda>t. exp (-(t^2))) has_vector_derivative -2*t*exp (-(t^2))) (at t)\"\n        by (auto simp: has_field_derivative_iff_has_vector_derivative [symmetric]\n                       field_simps intro!: derivative_eq_intros)\n      from assms t have \"((\\<lambda>t. -(1/2) * t powr (-2*n-1)) has_field_derivative\n                           (2*n+1)/2 * t powr (-2*n-2)) (at t)\"\n        by (auto intro!: derivative_eq_intros simp: field_simps powr_numeral power2_eq_square\n                         powr_minus powr_divide [symmetric] powr_add)\n      also have \"?this \\<longleftrightarrow> ((\\<lambda>t. inverse (-2*t^(2*n+1))) has_field_derivative\n                              (2*n+1)/2 / t ^ (2*Suc n)) (at t)\" using t\n        using eventually_nhds_in_open[of \"{0<..}\" t] assms\n        by (intro DERIV_cong_ev refl)\n           (auto elim!: eventually_mono simp: powr_minus field_simps powr_diff\n                        powr_realpow power2_eq_square intro!: real_powr_eq_powerI)\n      finally show \"((\\<lambda>t. inverse (-2*t^(2*n+1))) has_vector_derivative\n                              (2*n+1)/2 / t ^ (2*Suc n)) (at t)\"\n        by (simp add: has_field_derivative_iff_has_vector_derivative)\n    next\n      have \"((\\<lambda>t. real (2*n+1)/2 * (exp (- t\\<^sup>2) / t ^ (2 * Suc n))) has_integral\n             real (2*n+1)/2 * ?J m (Suc n)) (?A m)\" (is \"(?f has_integral ?a) _\")\n        using assms\n        by (intro has_integral_mult_right integrable_integral integrable_continuous_real)\n           (auto intro!: continuous_intros)\n      also have \"?f = (\\<lambda>t. exp (- t\\<^sup>2) * (real (2 * n + 1) / 2 / t ^ (2 * Suc n)))\"\n        by (simp add: fun_eq_iff field_simps)\n      also have \"?a = exp (- (x + real m)\\<^sup>2) * inverse (- 2 * (x + real m) ^ (2 * n + 1)) -\n                          exp (- x\\<^sup>2) * inverse (- 2 * x ^ (2 * n + 1)) - I m\" using assms\n        by (simp add: I_def algebra_simps inverse_eq_divide)\n      finally show \"((\\<lambda>t. exp (- t\\<^sup>2) * (real (2 * n + 1) / 2 / t ^ (2 * Suc n))) has_integral \\<dots>)\n                      {x..x + real m}\" .\n    qed (insert assms, auto intro!: continuous_intros)\n    hence \"I m = integral {x..x + real m} (\\<lambda>t. - 2*t*exp (- t\\<^sup>2) * inverse (-2*t^(2 * n + 1)))\"\n      by (simp add: has_integral_iff)\n    also have \"\\<dots> = integral {x..x + real m} (\\<lambda>t. exp (- t\\<^sup>2) / t ^ (2*n))\"\n      using assms by (intro integral_cong) (simp_all add: field_simps)\n    finally show \"I m = \\<dots>\" .\n  qed\n\n  have \"filterlim (\\<lambda>m. (-exp (- (x + real m)\\<^sup>2)) / (2 * (x + real m) ^ (2 * n + 1)))\n          (nhds 0) at_top\"\n    by (rule real_tendsto_divide_at_top filterlim_real_sequentially tendsto_minus\n             filterlim_compose[OF exp_at_bot] filterlim_compose[OF filterlim_uminus_at_bot_at_top]\n             filterlim_pow_at_top filterlim_tendsto_add_at_top tendsto_const filterlim_ident\n             filterlim_tendsto_pos_mult_at_top | simp)+\n  hence *: \"filterlim (\\<lambda>m. (exp (- (x + real m)\\<^sup>2)) / (-2 * (x + real m) ^ (2 * n + 1)))\n              (nhds 0) at_top\" by (simp add: add_ac)\n  have \"I \\<longlonglongrightarrow> 0 - exp (- x\\<^sup>2) * inverse (- 2 * x ^ (2 * n + 1)) -\n                  real (2 * n + 1) / 2 * erf_remainder_integral (Suc n) x\"\n    unfolding I_def\n    by (intro tendsto_diff * tendsto_const tendsto_mult LIMSEQ_erf_remainder_integral assms)\n  moreover from LIMSEQ_erf_remainder_integral[OF assms, of n] I_eq\n    have \"I \\<longlonglongrightarrow> erf_remainder_integral n x\"  by simp\n  ultimately have \"0 - exp (- x\\<^sup>2) * inverse (- 2 * x ^ (2 * n + 1)) - real (2 * n + 1) / 2 *\n                     erf_remainder_integral (Suc n) x = erf_remainder_integral n x\"\n    by (rule LIMSEQ_unique)\n  thus ?thesis by (simp add: field_simps)\nqed\n\nlemma erf_remainder_conv_Suc:\n  assumes \"x > 0\"\n  shows   \"erf_remainder n x = (- 1) ^ n * fact (2 * n) / (sqrt pi * 4 ^ n * fact n) *\n                    exp (- x\\<^sup>2) / (x ^ (2 * n + 1)) + erf_remainder (Suc n) x\"\nproof -\n  have \"erf_remainder n x =\n          (- 1) ^ n * 2 * fact (2 * n) / (sqrt pi * 4 ^ n * fact n) *\n             exp (- x\\<^sup>2) / (2 * x ^ (2 * n + 1)) + -(\n          (- 1) ^ n * 2 * fact (2 * n) / (sqrt pi * 4 ^ n * fact n) *\n            real (2 * n + 1) / 2 * erf_remainder_integral (Suc n) x)\" (is \"_ = ?A + ?B\")\n    unfolding erf_remainder_def using assms\n    by (subst erf_remainder_integral_conv_Suc)\n       (auto simp: assms algebra_simps simp del: power_Suc)\n  also have \"?B = erf_remainder (Suc n) x\"\n    by (simp add: divide_simps erf_remainder_def)\n  also have \"?A = (- 1) ^ n * fact (2 * n) / (sqrt pi * 4 ^ n * fact n) *\n                    exp (- x\\<^sup>2) / (x ^ (2 * n + 1))\"\n    by (simp add: divide_simps)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Finally, this gives us the full asymptotic expansion for @{term erfc}:\n\\<close>\ntheorem erfc_unroll:\n  assumes \"x > 0\"\n  shows   \"erfc x = exp (-x\\<^sup>2) / sqrt pi * \n             (\\<Sum>i<n. (-1)^i * fact (2*i) / (4^i*fact i) / x^(2*i+1)) + erf_remainder n x\"\nproof (induction n)\n  case (Suc n)\n  note Suc.IH\n  also note erf_remainder_conv_Suc[OF assms, of n]\n  also have \"exp (- x\\<^sup>2) / sqrt pi *\n               (\\<Sum>i<n. (- 1) ^ i * fact (2 * i) / (4 ^ i * fact i) / x ^ (2*i+1)) +\n                 ((- 1) ^ n * fact (2*n) / (sqrt pi * 4 ^ n * fact n) * exp (- x\\<^sup>2) / x^(2*n+1) +\n                 erf_remainder (Suc n) x) =\n               exp (- x\\<^sup>2) / sqrt pi *\n                 (\\<Sum>i<Suc n. (- 1) ^ i * fact (2 * i) / (4 ^ i * fact i) / x ^ (2 * i + 1)) +\n                 erf_remainder (Suc n) x\"\n    by (subst sum.lessThan_Suc) (simp add: algebra_simps)\n  finally show ?case .\nqed (auto simp: assms erf_remainder_0_conv_erfc)\n  \n\n\ntext \\<open>\n  For convenience, we define another auxiliary function that is more suitable for use in an \n  automated expansion framework, since it has a simple asymptotic expansion in powers of $x$.\n\\<close>\ndefinition erfc_aux where \"erfc_aux x = exp (x\\<^sup>2) * sqrt pi * erfc x\"\ndefinition erf_remainder' where \"erf_remainder' n x = exp (x\\<^sup>2) * sqrt pi * erf_remainder n x\"\n\nlemma erfc_aux_unroll: \n  \"x > 0 \\<Longrightarrow> \n     erfc_aux x = (\\<Sum>i<n. (-1)^i * fact (2*i) / (4^i*fact i) / x^(2*i+1)) + erf_remainder' n x\"\n  using erfc_unroll[of x n] \n  by (simp add: erfc_aux_def erf_remainder'_def exp_minus field_simps del: of_nat_Suc)\n\nlemma erf_remainder'_bigo: \"erf_remainder' n \\<in> O(\\<lambda>x. 1 / x ^ (2*n+1))\"\nproof -\n  have \"(\\<lambda>x. exp (x\\<^sup>2) * erf_remainder n x) \\<in> O(\\<lambda>x. exp (x\\<^sup>2) * (exp (-x\\<^sup>2) / x ^ (2*n+1)))\"\n    by (intro landau_o.big.mult erf_remainder_bigo) simp_all\n  thus ?thesis by (simp add: exp_minus erf_remainder'_def [abs_def])\nqed\n\nlemma has_field_derivative_erfc_aux: \n    \"(erfc_aux has_field_derivative (2 * x * erfc_aux x - 2)) (at x)\"\n  by (auto simp: erfc_aux_def [abs_def] exp_minus field_simps intro!: derivative_eq_intros)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Error_Function/Error_Function_Asymptotics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8633916064586998, "lm_q1q2_score": 0.7686725570860741}}
{"text": "section \"Vertex Cover\"\n\ntheory Approx_VC_Hoare\nimports \"HOL-Hoare.Hoare_Logic\"\nbegin\n\ntext \\<open>The algorithm is classical, the proof is based on and augments the one\nby Berghammer and M\\\"uller-Olm \\<^cite>\\<open>\"BerghammerM03\"\\<close>.\\<close>\n\nsubsection \"Graph\"\n\ntext \\<open>A graph is simply a set of edges, where an edge is a 2-element set.\\<close>\n\ndefinition vertex_cover :: \"'a set set \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n\"vertex_cover E C = (\\<forall>e \\<in> E. e \\<inter> C \\<noteq> {})\"\n\nabbreviation matching :: \"'a set set \\<Rightarrow> bool\" where\n\"matching M \\<equiv> pairwise disjnt M\"\n\nlemma card_matching_vertex_cover:\n  \"\\<lbrakk> finite C;  matching M;  M \\<subseteq> E;  vertex_cover E C \\<rbrakk> \\<Longrightarrow> card M \\<le> card C\"\napply(erule card_le_if_inj_on_rel[where r = \"\\<lambda>e v. v \\<in> e\"])\n apply (meson disjnt_def disjnt_iff vertex_cover_def subsetCE)\nby (meson disjnt_iff pairwise_def)\n\n\nsubsection \"The Approximation Algorithm\"\n\ntext \\<open>Formulated using a simple(!) predefined Hoare-logic.\nThis leads to a streamlined proof based on standard invariant reasoning.\n\nThe nondeterministic selection of an element from a set \\<open>F\\<close> is simulated by @{term \"SOME x. x \\<in> F\"}.\nThe \\<open>SOME\\<close> operator is built into HOL: @{term \"SOME x. P x\"} denotes some \\<open>x\\<close> that satisfies \\<open>P\\<close>\nif such an \\<open>x\\<close> exists; otherwise it denotes an arbitrary element. Note that there is no\nactual nondeterminism involved: @{term \"SOME x. P x\"} is some fixed element\nbut in general we don't know which one. Proofs about \\<open>SOME\\<close> are notoriously tedious.\nTypically it involves showing first that @{prop \"\\<exists>x. P x\"}. Then @{thm someI_ex} implies\n@{prop\"P (SOME x. P x)\"}. There are a number of (more) useful related theorems:\njust click on @{thm someI_ex} to be taken there.\\<close>\n\ntext \\<open>Convenient notation for choosing an arbitrary element from a set:\\<close>\nabbreviation \"some A \\<equiv> SOME x. x \\<in> A\"\n\nlocale Edges =\n  fixes E :: \"'a set set\"\n  assumes finE: \"finite E\"\n  assumes edges2: \"e \\<in> E \\<Longrightarrow> card e = 2\"\nbegin\n\ntext \\<open>The invariant:\\<close>\n\ndefinition \"inv_matching C F M =\n  (matching M \\<and> M \\<subseteq> E \\<and> card C \\<le> 2 * card M \\<and> (\\<forall>e \\<in> M. \\<forall>f \\<in> F. e \\<inter> f = {}))\"\n\ndefinition invar :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\" where\n\"invar C F = (F \\<subseteq> E \\<and> vertex_cover (E-F) C \\<and> finite C \\<and> (\\<exists>M. inv_matching C F M))\"\n\ntext \\<open>Preservation of the invariant by the loop body:\\<close>\n\n\n\n\nlemma approx_vertex_cover:\n\"VARS C F\n  {True}\n  C := {};\n  F := E;\n  WHILE F \\<noteq> {}\n  INV {invar C F}\n  DO C := C \\<union> some F;\n     F := F - {e' \\<in> F. some F \\<inter> e' \\<noteq> {}}\n  OD\n  {vertex_cover E C \\<and> (\\<forall>C'. finite C' \\<and> vertex_cover E C' \\<longrightarrow> card C \\<le> 2 * card C')}\"\nproof (vcg, goal_cases)\n  case (1 C F)\n  have \"inv_matching {} E {}\" by (auto simp add: inv_matching_def)\n  with 1 show ?case by (auto simp add: invar_def vertex_cover_def)\nnext\n  case (2 C F)\n  thus ?case using invar_step[of F C] by(auto simp: Let_def)\nnext\n  case (3 C F)\n  then obtain M :: \"'a set set\" where\n    post: \"vertex_cover E C\" \"matching M\" \"M \\<subseteq> E\" \"card C \\<le> 2 * card M\"\n    by(auto simp: invar_def inv_matching_def)\n\n  have opt: \"card C \\<le> 2 * card C'\" if C': \"finite C'\" \"vertex_cover E C'\" for C'\n  proof -\n    note post(4)\n    also have \"2 * card M \\<le> 2 * card C'\"\n    using card_matching_vertex_cover[OF C'(1) post(2,3) C'(2)] by simp\n    finally show \"card C \\<le> 2 * card C'\" .\n  qed\n\n  show ?case using post(1) opt by auto\nqed\n\nend (* locale Graph *)\n\nsubsection \"Version for Hypergraphs\"\n\ntext \\<open>Almost the same. We assume that the degree of every edge is bounded.\\<close>\n\nlocale Bounded_Hypergraph =\n  fixes E :: \"'a set set\"\n  fixes k :: nat\n  assumes finE: \"finite E\"\n  assumes edge_bnd: \"e \\<in> E \\<Longrightarrow> finite e \\<and> card e \\<le> k\"\n  assumes E1: \"{} \\<notin> E\"\nbegin\n\ndefinition \"inv_matching C F M =\n  (matching M \\<and> M \\<subseteq> E \\<and> card C \\<le> k * card M \\<and> (\\<forall>e \\<in> M. \\<forall>f \\<in> F. e \\<inter> f = {}))\"\n\ndefinition invar :: \"'a set \\<Rightarrow> 'a set set \\<Rightarrow> bool\" where\n\"invar C F = (F \\<subseteq> E \\<and> vertex_cover (E-F) C \\<and> finite C \\<and> (\\<exists>M. inv_matching C F M))\"\n\nlemma invar_step:\n  assumes \"F \\<noteq> {}\" \"invar C F\"\n  shows \"invar (C \\<union> some F) (F - {e' \\<in> F. some F \\<inter> e' \\<noteq> {}})\"\nproof -\n  from assms(2) obtain M where \"F \\<subseteq> E\" and vc: \"vertex_cover (E-F) C\" and fC: \"finite C\"\n    and m: \"matching M\" \"M \\<subseteq> E\" and card: \"card C \\<le> k * card M\"\n    and disj: \"\\<forall>e \\<in> M. \\<forall>f \\<in> F. e \\<inter> f = {}\"\n  by (auto simp: invar_def inv_matching_def)\n  let ?e = \"SOME e. e \\<in> F\"\n  have \"?e \\<in> F\" using \\<open>F \\<noteq> {}\\<close> by (simp add: some_in_eq)\n  hence fe': \"finite ?e\" using \\<open>F \\<subseteq> E\\<close> assms(2) edge_bnd by blast\n  have \"?e \\<notin> M\" using E1 \\<open>?e \\<in> F\\<close> disj \\<open>F \\<subseteq> E\\<close> by fastforce\n  have card': \"card (C \\<union> ?e) \\<le> k * card (insert ?e M)\"\n    using \\<open>?e \\<in> F\\<close> \\<open>?e \\<notin> M\\<close> card_Un_le[of C ?e] \\<open>F \\<subseteq> E\\<close> edge_bnd card finite_subset[OF m(2) finE]\n    by fastforce\n  let ?M = \"M \\<union> {?e}\"\n  have vc': \"vertex_cover (E - (F - {e' \\<in> F. ?e \\<inter> e' \\<noteq> {}})) (C \\<union> ?e)\"\n    using vc by(auto simp: vertex_cover_def)\n  have m': \"inv_matching (C \\<union> ?e) (F - {e' \\<in> F. ?e \\<inter> e' \\<noteq> {}}) ?M\"\n    using m card' \\<open>F \\<subseteq> E\\<close> \\<open>?e \\<in> F\\<close> disj\n    by(auto simp: inv_matching_def Int_commute disjnt_def pairwise_insert)\n  show ?thesis using \\<open>F \\<subseteq> E\\<close> vc' fC fe' m' by(auto simp add: invar_def Let_def)\nqed\n\n\nlemma approx_vertex_cover_bnd:\n\"VARS C F\n  {True}\n  C := {};\n  F := E;\n  WHILE F \\<noteq> {}\n  INV {invar C F}\n  DO C := C \\<union> some F;\n     F := F - {e' \\<in> F. some F \\<inter> e' \\<noteq> {}}\n  OD\n  {vertex_cover E C \\<and> (\\<forall>C'. finite C' \\<and> vertex_cover E C' \\<longrightarrow> card C \\<le> k * card C')}\"\nproof (vcg, goal_cases)\n  case (1 C F)\n  have \"inv_matching {} E {}\" by (auto simp add: inv_matching_def)\n  with 1 show ?case by (auto simp add: invar_def vertex_cover_def)\nnext\n  case (2 C F)\n  thus ?case using invar_step[of F C] by(auto simp: Let_def)\nnext\n  case (3 C F)\n  then obtain M :: \"'a set set\" where\n    post: \"vertex_cover E C\" \"matching M\" \"M \\<subseteq> E\" \"card C \\<le> k * card M\"\n    by(auto simp: invar_def inv_matching_def)\n\n  have opt: \"card C \\<le> k * card C'\" if C': \"finite C'\" \"vertex_cover E C'\" for C'\n  proof -\n    note post(4)\n    also have \"k * card M \\<le> k * card C'\"\n    using card_matching_vertex_cover[OF C'(1) post(2,3) C'(2)] by simp\n    finally show \"card C \\<le> k * card C'\" .\n  qed\n\n  show ?case using post(1) opt by auto\nqed\n\nend (* locale Bounded_Hypergraph *)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Approximation_Algorithms/Approx_VC_Hoare.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467770088163, "lm_q2_score": 0.8740772482857833, "lm_q1q2_score": 0.7684421956871812}}
{"text": "(*header {* Section 3 --- All, Some, No *}*)\n\ntheory Section3\nimports Main \"~~/src/HOL/Library/Order_Relation\"\n\nbegin\n\nsubsection {* Basic definitions *}\n\ntext {* \\begin{tcolor} The set of atomic propositions is formalized as a\n  type. \\end{tcolor} *}\ntypedecl atProp\n\ntext {* The inductively defined set of formulas is formalised as a datatype *}\ndatatype formula = \n    All atProp atProp (\"All _ are _ \") \n  | Some atProp atProp (\"Some _ are _\") \n  | No atProp atProp (\"No _ are _\")\n\ntext {* The carrier of a model can be any type, written as alpha or \n  @{typ 'a}.\n  A model then is a function that assigns to each atomic proposition \n  a subset of @{typ 'a} (its extension, ie, the subset where it is true).*}\ntype_synonym 'a model = \"(atProp \\<Rightarrow>'a set)\"\n\ntext {* \\begin{tcolor}The satisfiability relation is formalized as a Boolean valued\n  function. The notation (@{text \"_ \\<Turnstile> _\"}) allows us to use the usual\n  mathematical notation \\begin{qcolor}$M\\models\\phi$\\end{qcolor} in Isabelle.\\end{tcolor}*}\nfun M_satisfies :: \"'a model \\<Rightarrow> formula \\<Rightarrow> bool\" (\"_ \\<Turnstile> _\")\nwhere\n   \"M_satisfies MM (All x are y) = (MM x \\<subseteq> MM y)\"\n | \"M_satisfies MM (Some x are y) = (\\<exists>e. e \\<in> MM x \\<inter> MM y)\"\n | \"M_satisfies MM (No x are y) = (MM x \\<inter> MM y = {})\"\n\nthm M_satisfies.simps\n\n(* model satisfies theory *)\ndefinition M_satisfies_G :: \"'a model \\<Rightarrow> formula set \\<Rightarrow> bool\" (\"_ \\<Turnstile>M _\")\nwhere\n  \"M_satisfies_G M G  \\<equiv> \\<forall>f. f \\<in> G \\<longrightarrow> (M \\<Turnstile> f)\"\n\n(* some useful rewrites for simplification, thanks to Thomas Tuerk *)\nlemma M_satisfies_G_I [intro!]:\n \"(\\<And>f. f \\<in> G \\<Longrightarrow> M \\<Turnstile> f) \\<Longrightarrow> (M \\<Turnstile>M G)\"\nunfolding M_satisfies_G_def by auto\n\nlemma M_satisfies_G_rewrites [simp] :\n  \"(M \\<Turnstile>M {})\" (is ?g1) (* ak *)\n  \"(M \\<Turnstile>M (insert g G)) \\<longleftrightarrow> ((M \\<Turnstile> g) \\<and> (M \\<Turnstile>M G))\" (is ?g2)\n  \"(M \\<Turnstile>M (G1 \\<union> G2)) \\<longleftrightarrow> ((M \\<Turnstile>M G1) \\<and> (M \\<Turnstile>M G2))\" (is ?g3)\nproof -\n  show ?g1 by auto (* thanks to intro-rule above *)\nnext\n  show ?g2 unfolding M_satisfies_G_def by auto\nnext\n  show ?g3 unfolding M_satisfies_G_def by auto\nqed\n\nlemma M_satisfies_G_mono :\nassumes \"G' \\<subseteq> G\"\n    and \"M \\<Turnstile>M G\"\n  shows \"M \\<Turnstile>M G'\"\nusing assms\n  by (metis M_satisfies_G_def in_mono)\n\n(* semantic consequence *)\ndefinition G_satisfies :: \"formula set \\<Rightarrow> formula \\<Rightarrow> 'a itself \\<Rightarrow> bool\" (\"_ \\<Turnstile>G _ _\")\n(* TT: use itself types, passing types around (and nothing else) is what they are for) *)\nwhere\n  \"G_satisfies G f (ty :: 'a itself) \\<equiv> \\<forall> (M::'a model). (M \\<Turnstile>M G) \\<longrightarrow> (M \\<Turnstile> f)\"\n\nlemma G_satisfies_I [intro]:\n \"(\\<And>(M::'a model). M \\<Turnstile>M G \\<Longrightarrow> M \\<Turnstile> f) \\<Longrightarrow> (G \\<Turnstile>G f (ty :: 'a itself))\"\nunfolding G_satisfies_def by auto\n\n(* Example 9 *)\nlemma example_9: \"{(All p are q), (Some p are r)} \\<Turnstile>G (Some q are r) (TYPE (atProp))\"\napply (rule G_satisfies_I)\napply (auto)\ndone\n\n(* Example 10 *)\nlemma example_10: \"{(All p are v), (All q are w), (No v are w)} \\<Turnstile>G (No p are q) (TYPE(atProp))\"\napply (rule G_satisfies_I)\napply (auto)\ndone\n\n\n(* Figure 3. The logical system for S *)\ninductive der :: \"formula \\<Rightarrow> bool\" (\"\\<turnstile>X _\")\n  where\n    initA: \"\\<turnstile>X All X are X\"\n  | initS2: \"\\<turnstile>X Some X are Y \\<Longrightarrow> \\<turnstile>X Some X are X\"\n  | initN: \"\\<turnstile>X No X are X \\<Longrightarrow> \\<turnstile>X No X are Y\"\n  | initN2: \"\\<turnstile>X No X are X \\<Longrightarrow> \\<turnstile>X All X are Y\"\n  | transA: \"\\<lbrakk>\\<turnstile>X All X are Y; \\<turnstile>X All Y are Z\\<rbrakk> \\<Longrightarrow> \\<turnstile>X All X are Z\"\n  | transS: \"\\<lbrakk>\\<turnstile>X All Y are Z; \\<turnstile>X Some X are Y\\<rbrakk> \\<Longrightarrow> \\<turnstile>X Some X are Z\"\n  | transN: \"\\<lbrakk>\\<turnstile>X All X are Y; \\<turnstile>X No Y are Z\\<rbrakk> \\<Longrightarrow> \\<turnstile>X No X are Z\"\n  | reflS: \"\\<turnstile>X Some X are Y \\<Longrightarrow> \\<turnstile>X Some Y are X\"\n  | reflN: \"\\<turnstile>X No X are Y \\<Longrightarrow> \\<turnstile>X No Y are X\"\n  | any: \"\\<lbrakk>\\<turnstile>X Some X are Y; \\<turnstile>X No X are Y\\<rbrakk>  \\<Longrightarrow> \\<turnstile>X _\"\n\ninductive derarg :: \"formula set \\<Rightarrow> formula \\<Rightarrow> bool\" (\" _ \\<turnstile> _\")\n  for hs\n  where\n    initA: \"hs \\<turnstile> All X are X\"\n  | initS2: \"hs \\<turnstile> Some X are Y \\<Longrightarrow> hs \\<turnstile> Some X are X\"\n  | initN: \"hs \\<turnstile> No X are X \\<Longrightarrow> hs \\<turnstile> No X are Y\"\n  | initN2: \"hs \\<turnstile> No X are X \\<Longrightarrow> hs \\<turnstile> All X are Y\"\n  | transA: \"\\<lbrakk>hs \\<turnstile> All X are Y; hs \\<turnstile> All Y are Z\\<rbrakk> \\<Longrightarrow> hs \\<turnstile> All X are Z\"\n  | transS: \"\\<lbrakk>hs \\<turnstile> All Y are Z; hs \\<turnstile> Some X are Y\\<rbrakk> \\<Longrightarrow> hs \\<turnstile> Some X are Z\"\n  | transN: \"\\<lbrakk>hs \\<turnstile> All X are Y; hs \\<turnstile> No Y are Z\\<rbrakk> \\<Longrightarrow> hs \\<turnstile> No X are Z\"\n  | reflS: \"hs \\<turnstile> Some X are Y \\<Longrightarrow> hs \\<turnstile> Some Y are X\"\n  | reflN: \"hs \\<turnstile> No X are Y \\<Longrightarrow> hs \\<turnstile> No Y are X\"\n  | any: \"\\<lbrakk>hs \\<turnstile> Some X are Y; hs \\<turnstile> No X are Y\\<rbrakk>  \\<Longrightarrow> hs \\<turnstile> _\"\n  | ass: \"f \\<in> hs \\<Longrightarrow>  hs \\<turnstile> f\"\n\n(* ak: how to prove this for a generic G? *)\nlemma G_derives_mono :\nassumes \"hs \\<turnstile> f\"\n    and \"hs \\<subseteq> hs'\"\nshows \"hs' \\<turnstile> f\"\n(* apply (rule derarg.induct)\napply (rule assms)\napply (rule initA)\napply (rule initS2)\nak *)\nusing assms\nproof (induct rule: derarg.induct)\n  case (initA X)\n  show ?case\n  by (rule derarg.initA)\nnext\n  case (initS2 X Y)\n  from derarg.initS2[OF initS2(2)] initS2(3)\n  show ?case .\nnext\n  case (initN X Y)\n  from derarg.initN[OF initN(2)] initN(3)\n  show ?case .\nnext\n  case (initN2 X Y)\n  from derarg.initN2[OF initN2(2)] initN2(3)\n  show ?case .\nnext\n  case (transA X Y Z)\n  from derarg.transA[OF transA(2) transA(4)] transA(5)\n  show ?case by simp\nnext\n  case(transS X Y Z)\n  from derarg.transS[OF transS(2) transS(4)] transS(5)\n  show ?case by simp\nnext\n  case(transN X Y Z)\n  from derarg.transN[OF transN(2) transN(4)] transN(5)\n  show ?case by simp\nnext\n  case(reflS X Y)\n  from derarg.reflS[OF reflS(2)] reflS(3)\n  show ?case .\nnext\n  case(reflN X Y)\n  from derarg.reflN[OF reflN(2)] reflN(3)\n  show ?case .\nnext\n  case(any X Y)\n  from derarg.any[OF any(2) any(4)] any(5)\n  show ?case by simp\nnext\n  case(ass f)\n  hence \"f \\<in> hs'\" by auto\n  from derarg.ass[OF this]\n  show ?case .\nprint_cases\nthm derarg.induct\nqed\n\n(* Example 14 *)\nlemma example_14 : \"{All p are v, All q are w, No v are w} \\<turnstile> No p are q\" (is \"?hs \\<turnstile> _\")\nproof -\n  have p1: \"?hs \\<turnstile> All p are v\" by (rule ass, simp)\n  have p2: \"?hs \\<turnstile> All q are w\" by (rule ass, simp)\n  have p3: \"?hs \\<turnstile> No v are w\" by (rule ass, simp)\n\n  have p4: \"?hs \\<turnstile> No p are w\" using transN [OF p1 p3] .\n  have p5: \"?hs \\<turnstile> No w are p\" using reflN [OF p4] .\n  have p6: \"?hs \\<turnstile> No q are p\" using transN [OF p2 p5] .\n  show ?thesis using reflN [OF p6] .\nqed\n\n\n(* Section 3.3 *)\n\n(* !!! from section 2 !!! *)\n\n(* order induced on atomic propositions by a theory *)\ndefinition less_equal_prop:: \n  \"atProp \\<Rightarrow> formula set \\<Rightarrow> atProp \\<Rightarrow> bool\" (\"_ \\<lesssim> _ _\")  where\n  \"less_equal_prop x G y \\<equiv> G \\<turnstile> All x are y\"\n\n(* TT: export the theorems for trans and refl, since they are useful in the following *)\nlemma less_equal_prop_refl [simp]:\n  \"\\<And>G x. x \\<lesssim>G x\"\nunfolding less_equal_prop_def \n  by (simp add: derarg.initA)\n\nlemma less_equal_prop_trans:\n  \"\\<And>G x y z. x \\<lesssim>G y \\<Longrightarrow> y \\<lesssim>G z \\<Longrightarrow> x \\<lesssim>G z\"\nunfolding less_equal_prop_def \nby (metis derarg.transA)\n\nlemma less_equal_prop_ass [simp] :\n  \"(All u are v) \\<in> G \\<Longrightarrow> less_equal_prop u G v\"\nunfolding less_equal_prop_def by (rule ass) (* ak what does ass refer to ? *)\n\n(* Proposition 2.1 *)\nlemma prop_2_1:\n  fixes G \n  defines R_def: \"R \\<equiv> { (x,y). less_equal_prop x G y }\"\n  shows \"preorder_on UNIV R\" (* ak explain preorder_on UNIV *)\nproof -\n  have \"refl R\"\n    by (simp add: refl_on_def R_def)\n  have \"trans R\"\n    by (metis assms less_equal_prop_trans mem_Collect_eq old.prod.case trans_def)\n  with `refl R` show ?thesis by (simp add: preorder_on_def)\nqed\n\n(* TT: use top-level pattern matching, since it gives nicer rewrites ak *)\n\n(* the set of all All formulas *)\nfun form_all :: \"formula \\<Rightarrow> bool\" where\n    \"form_all (All _ are _) = True\"\n  | \"form_all _ = False\"\n\nlemma form_all_alt_def :\n  \"form_all f \\<longleftrightarrow> (\\<exists>p q. (f = All p are q))\"\nby (cases f) auto\n\n(* the set of all Some formulas *)\nfun form_some :: \"formula \\<Rightarrow> bool\" where\n    \"form_some (Some _ are _) = True\"\n  | \"form_some _ = False\"\n\nlemma form_some_alt_def :\n  \"form_some f \\<longleftrightarrow> (\\<exists>p q. (f = Some p are q))\"\nby (cases f) auto\n\n(* the set of all No formulas *)\nfun form_no :: \"formula \\<Rightarrow> bool\" where\n    \"form_no (No _ are _) = True\"\n  | \"form_no _ = False\"\n\nlemma form_no_alt_def :\n  \"form_no f \\<longleftrightarrow> (\\<exists>p q. (f = No p are q))\"\nby (cases f) auto\n\nlemma forms_complete :\n  \"form_all f \\<or> form_some f \\<or> form_no f\"\nby (cases f) simp_all\n\nlemma forms_distinct :\n  \"\\<not>(form_all f) \\<or> \\<not>(form_some f)\"\n  \"\\<not>(form_all f) \\<or> \\<not>(form_no f)\"\n  \"\\<not>(form_some f) \\<or> \\<not>(form_no f)\"\nby (cases f, simp_all)+\n\n\ndefinition \"all_formulas = {x. x \\<in> (UNIV::formula set) \\<and> (form_all x) }\"\ndefinition \"some_formulas = {x. x \\<in> (UNIV::formula set) \\<and> (form_some x) }\"\n\n(* TT: add useful rewrite early to simplifier *)\nlemma in_all_formulas [simp] :\n  \"f \\<in> all_formulas \\<longleftrightarrow> form_all f\" \nunfolding all_formulas_def by simp\n\nlemma in_some_formulas [simp] :\n  \"f \\<in> some_formulas \\<longleftrightarrow> form_some f\" \nunfolding some_formulas_def by simp\n\n(* TT: now this is trivial *)\n\nlemma \"(All x are y) \\<in> all_formulas\" by simp\nlemma \"(No x are y) \\<notin> some_formulas\" by simp\n\ndefinition \"all_gamma G = G \\<inter> all_formulas\"\ndefinition \"some_gamma G = G \\<inter> some_formulas\"\n\ndefinition \"all_some_formulas = {x. x \\<in> (UNIV::formula set) \\<and> (form_all x \\<or> form_some x) }\"\ndefinition \"all_some_gamma G = G \\<inter> all_some_formulas\"\n\n(* TT: often it is useful to establish connections to existing constructs *)\nlemma all_some_formulas_alt_def :\n  \"all_some_formulas = all_formulas \\<union> some_formulas\"\nunfolding all_some_formulas_def all_formulas_def some_formulas_def by auto\n\nlemma in_all_some_formulas [simp] :\n  \"f \\<in> all_some_formulas \\<longleftrightarrow> \\<not>(form_no f)\"\nunfolding all_some_formulas_alt_def\nby (cases f) simp_all\n\nlemma all_some_gamma_alt_def :\n  \"all_some_gamma G = all_gamma G \\<union> some_gamma G\"\nunfolding all_some_gamma_def all_some_formulas_alt_def all_gamma_def some_gamma_def\nby auto\n\n(* TT: I prefer this definition, since it introduces less cases and looks clearer.\n       Due to less cases better for automation *)\n\ndefinition char_model_ex6 :: \"formula set \\<Rightarrow> formula model\" (\"_ \\<lbrakk>_\\<rbrakk>\") where\n  \"char_model_ex6 G u = {Some x are y | x y. ((Some x are y) \\<in> G) \\<and> \n     (less_equal_prop x G u \\<or> less_equal_prop y G u)}\"\nthm char_model_ex6_def\n\nlemma exercise_6_1: \n  fixes G \n  defines \"M \\<equiv> char_model_ex6 G\"\n  assumes G_sub: \"G \\<subseteq> all_some_formulas\"\n  shows \"M \\<Turnstile>M G\"\nproof (rule M_satisfies_G_I)\n  fix g\n  assume \"g \\<in> G\"\n  show \"M \\<Turnstile> g\"\n  proof (cases g)\n    case (No x y)\n    with `g \\<in> G` G_sub have False by auto\n    thus ?thesis ..\n  next\n    case (All x y)\n    note g_is_All = All\n    \n    from `g \\<in> G` g_is_All\n    have \"less_equal_prop x G y\" \n      by auto\n \n    thus ?thesis\n      unfolding g_is_All M_def\n      by (auto simp add: char_model_ex6_def)\n         (metis less_equal_prop_trans)+\n  next\n    case (Some x y)\n    note g_is_Some = Some\n\n    have \"g \\<in> char_model_ex6 G x\" \"g \\<in> char_model_ex6 G y\"\n      using `g \\<in> G`\n      unfolding g_is_Some char_model_ex6_def\n      by simp_all\n    thus ?thesis\n      unfolding M_def g_is_Some\n      by simp blast\n  qed\nqed\n\n\nlemma exercise_6_2: \n  fixes G\n  defines \"M \\<equiv> char_model_ex6 G\"\n  assumes G_sub: \"G \\<subseteq> all_some_formulas\"\n  assumes M_sat: \"M \\<Turnstile> Some p are q\"\n  shows \"G \\<turnstile> Some p are q\"\nproof -\n  have \"\\<exists>x y. (Some x are y) \\<in> (M p \\<inter> M q)\"\n  proof -\n    from M_sat have \"M p \\<inter> M q \\<noteq> {}\" by auto\n    then obtain e where \"e \\<in> M p\" and \"e \\<in> M q\" by auto\n\n    from `e \\<in> M p` have \"form_some e\"\n      unfolding M_def by (auto simp add: char_model_ex6_def)\n\n    from `form_some e` `e \\<in> M p` `e \\<in> M q`\n    show ?thesis unfolding form_some_alt_def by auto\n  qed\n  then obtain x y where in_Mp: \"(Some x are y) \\<in> M p\" \n                    and in_Mq: \"(Some x are y) \\<in> M q\" by auto\n\n  from in_Mp have in_G: \"(Some x are y) \\<in> G\"\n    unfolding M_def char_model_ex6_def by simp\n\n  from in_Mp in_Mq have some_x_y_p_q : \"((x \\<lesssim>G p) \\<or> (y \\<lesssim>G p))\" \"((x \\<lesssim>G q) \\<or> (y \\<lesssim>G q))\"\n    unfolding M_def char_model_ex6_def by simp_all\n  thus ?thesis\n    by (metis ass derarg.initS2 derarg.reflS derarg.transS in_G less_equal_prop_def)\nqed\n\n(*declare [[show_types]]*)\n\nlemma exercise_7_1: \n  fixes G\n  defines \"G' \\<equiv> G \\<inter> all_some_formulas\"  \n  defines \"M \\<equiv> char_model_ex6 G'\"\n  assumes G_sat: \"G \\<Turnstile>G Some p are q (TYPE(formula))\"\n  assumes M_sat_G: \"M \\<Turnstile>M G\"\n  shows \"G \\<turnstile> Some p are q\"\nproof -\n\n  have 1: \"G' \\<subseteq> all_some_formulas\" \n    by (metis G'_def Int_lower2)\n (* have 2: \"M \\<Turnstile>M G'\" \n    by (metis G'_def M_sat_G M_satisfies_G_rewrites(3) sup_inf_absorb)\n  *)\n  have 2: \"M \\<Turnstile> Some p are q\"\n    using G_sat M_sat_G\n    unfolding G_satisfies_def\n    by simp\n \n  from 1 2 have \"G' \\<turnstile> Some p are q\"\n    using exercise_6_2[of G'] \n    unfolding M_def\n    by metis\n  thus ?thesis\n    by (metis G'_def G_derives_mono Int_lower1)\nqed\n\nlemma exercise_7_2: \n  fixes G\n  defines \"G' \\<equiv> G \\<inter> all_some_formulas\"  \n  defines \"M \\<equiv> char_model_ex6 G'\"\n  assumes G_sat: \"G \\<Turnstile>G Some p are q (TYPE(formula))\"\n  assumes not_M_sat_G: \"\\<not>(M \\<Turnstile>M G)\"\n  shows \"G \\<turnstile> Some p are q\"\nproof -\n  from not_M_sat_G have 1: \"\\<exists> f \\<in> G. \\<not>(M \\<Turnstile> f)\"\n    by (metis M_satisfies_G_def)\n\n  then obtain x y where \"(No x are y) \\<in> G\" and  \"\\<not>(M \\<Turnstile> No x are y)\"\n    by (metis G'_def IntI Int_lower2 M_def M_satisfies_G_def exercise_6_1 form_no.elims(2) in_all_some_formulas)\n  \n  then have \"M x \\<inter> M y \\<noteq> {}\" by simp\n  then have \"G' \\<turnstile> Some x are y\"\n    using exercise_6_2[of G'] \n    by (metis G'_def IntE M_def M_satisfies.simps(2) ex_in_conv subsetI)\n  \n  then have \"G \\<turnstile> Some x are y\"\n    by (metis G'_def G_derives_mono Int_lower1)\n  \n  from `(No x are y) \\<in> G` have \"G \\<turnstile> No x are y\" by (rule derarg.ass)\n  thus ?thesis\n    using `G \\<turnstile> Some x are y`\n    by (metis derarg.any)\nqed\n\n\ndefinition \"no_formulas = {x. x \\<in> (UNIV::formula set) \\<and> (form_no x) }\"\n\ndefinition \"no_gamma G = G \\<inter> no_formulas\"\n\ndefinition \"all_no_formulas = {x. x \\<in> (UNIV::formula set) \\<and> (form_all x \\<or> form_no x) }\"\ndefinition \"all_no_gamma G = G \\<inter> all_no_formulas\"\n\ndefinition \"all_some_no_formulas = {x. x \\<in> (UNIV::formula set) \\<and> (form_all x \\<or> form_some x \\<or> form_no x) }\"\n\n(* TT: often it is useful to establish connections to existing constructs *)\nlemma all_no_formulas_alt_def :\n  \"all_no_formulas = all_formulas \\<union> no_formulas\"\nunfolding all_no_formulas_def all_formulas_def no_formulas_def by auto\n\nlemma in_all_no_formulas [simp] :\n  \"f \\<in> all_no_formulas \\<longleftrightarrow> \\<not>(form_some f)\"\nunfolding all_no_formulas_alt_def\nby (metis (lifting) UNIV_I all_no_formulas_alt_def all_no_formulas_def all_some_formulas_def forms_distinct(1) in_all_some_formulas mem_Collect_eq) \n\nlemma all_no_gamma_alt_def :\n  \"all_no_gamma G = all_gamma G \\<union> no_gamma G\"\nunfolding all_no_gamma_def all_no_formulas_alt_def all_gamma_def no_gamma_def\nby auto\n\n\n\n\ndefinition up_closed :: \"atProp set \\<Rightarrow> formula set \\<Rightarrow> bool\" where\n  \"up_closed A G \\<equiv> \\<forall>v \\<in> A. \\<forall>w. (v \\<lesssim>G w) \\<longrightarrow> w \\<in> A\"\n\ndefinition does_not_derive :: \"atProp set \\<Rightarrow> formula set \\<Rightarrow> bool\" where\n  \"does_not_derive A G \\<equiv> \\<forall>v \\<in> A. \\<forall>w \\<in> A. \\<not>(G \\<turnstile> No v are w)\"\n\ndefinition \"M_ex7 G \\<equiv> {A. A \\<subseteq> (UNIV::atProp set) \\<and> (up_closed A G) \\<and> (does_not_derive A G) }\"\n\ndefinition char_model_ex8 :: \"formula set \\<Rightarrow> (atProp set) model\" where\n  \"char_model_ex8 G v = { A. A \\<in> (M_ex7 G) \\<and> v \\<in> A }\"\n\n\n\nlemma exercise_8_1: \n  fixes G \n  defines \"M \\<equiv> char_model_ex8 G\"\n  assumes G_sub: \"G \\<subseteq> all_no_formulas\"\n  shows \"M \\<Turnstile>M G\"\nproof (rule M_satisfies_G_I)\n  fix g\n  assume \"g \\<in> G\"\n\n  show \"M \\<Turnstile> g\"\n  proof (cases g)\n    case (Some x y)\n    with `g \\<in> G` G_sub have False by auto\n    thus ?thesis ..\n  next\n    case (All x y)\n    then have \"x \\<lesssim>G y\"\n      using `g \\<in> G`\n      by (metis less_equal_prop_ass)\n    then have \"M x \\<subseteq> M y\"\n      unfolding M_def char_model_ex8_def M_ex7_def\n      by simp (metis (lifting, no_types) Collect_mono up_closed_def)\n    thus ?thesis\n      by (metis M_satisfies.simps(1) All)\n  next  \n    case (No x y)\n    then have g_derives_n : \"G \\<turnstile> No x are y\" \n      using `g \\<in> G`\n      by (metis ass)\n    {\n      fix X \n      assume \"X \\<in> M x\"\n      have \"X \\<notin> M y\"\n        proof (rule notI)\n          assume \"X \\<in> M y\"\n          have 1: \"x \\<in> X\"\n            by (metis (lifting) M_def `X \\<in> M x` char_model_ex8_def mem_Collect_eq)\n          have 2: \"y \\<in> X\"\n            by (metis (lifting) M_def `X \\<in> M y` char_model_ex8_def mem_Collect_eq)\n          from 1 2 `X \\<in> M x` have \"\\<not>(G \\<turnstile> No x are y)\"\n            unfolding M_def char_model_ex8_def M_ex7_def does_not_derive_def\n            by auto\n          then have \"X \\<notin> M x\"\n            by (metis g_derives_n)\n          with `X \\<in> M x` show False by metis\n        qed\n    }\n    hence \"M x \\<inter> M y = {}\" by auto\n    thus ?thesis\n      by (metis M_satisfies.simps(3) No)\n  qed\nqed\n\nlemma exercise_8_2: \n  fixes G \n  defines \"M \\<equiv> char_model_ex8 G\"\n  assumes G_sub: \"G \\<subseteq> all_no_formulas\"\n  assumes g_in_all_no : \"g \\<in> all_no_formulas\"\n  and \"M \\<Turnstile> g\"\n  shows \"G \\<turnstile> g\"\nproof - \n  show ?thesis\n  proof (cases g)\n    case(Some x y)\n    with g_in_all_no have False by simp\n    thus ?thesis ..\n  next\n    case(All x y)\n    {\n      define Ax where \"Ax = { z. x \\<lesssim>G z }\"\n\n      have ?thesis\n      proof (cases \"Ax \\<in> M_ex7 G\")\n        case (True)\n        have x_in_Ax : \"x \\<in> Ax\"\n          by (metis Ax_def less_equal_prop_refl mem_Collect_eq)\n        have \"M \\<Turnstile> All x are y\"\n          using exercise_8_1[of G]\n          by (metis All `M \\<Turnstile> g`)\n        then have \"M x \\<subseteq> M y\" by simp\n        from x_in_Ax `Ax \\<in> M_ex7 G` have Ax_in_Mx : \"Ax \\<in> M x\"\n          by (metis (lifting) M_def char_model_ex8_def mem_Collect_eq)\n        from `M x \\<subseteq> M y` Ax_in_Mx have Ax_in_My : \"Ax \\<in> M y\"\n          by (metis subsetD)\n        from Ax_in_My Ax_def have y_in_Ax : \"y \\<in> Ax\"\n          by (metis (lifting) M_def char_model_ex8_def mem_Collect_eq)\n        from x_in_Ax y_in_Ax Ax_def have \"x \\<lesssim>G y\"\n          by (metis mem_Collect_eq)\n        then have A_in_M: \"G \\<turnstile> All x are y\"\n          by (metis less_equal_prop_def)\n        thus ?thesis by (metis All)\n      next\n        case (False)\n        then have \"\\<not>(does_not_derive Ax G)\"\n          by (metis (lifting, no_types) M_ex7_def less_equal_prop_trans mem_Collect_eq Ax_def top_greatest up_closed_def)\n        then have \"\\<exists>v \\<in> Ax. \\<exists>w \\<in> Ax. (G \\<turnstile> No v are w)\" \n          unfolding M_ex7_def does_not_derive_def\n          by simp\n        then obtain v w where no_v_w : \"(G \\<turnstile> No v are w)\" by metis\n        then have cases_x :\"(x \\<lesssim>G v)\" \"(x \\<lesssim>G w)\"\n          by (metis (mono_tags) `\\<exists>v\\<in>Ax. \\<exists>w\\<in>Ax. (G \\<turnstile> No v are w)` derarg.initN2 derarg.reflN derarg.transN less_equal_prop_def mem_Collect_eq order_refl Ax_def set_rev_mp)+ \n   \n        from cases_x(1) have all_x_v : \"G \\<turnstile> All x are v\" by (metis less_equal_prop_def)\n        from all_x_v no_v_w have no_x_w : \"G \\<turnstile> No x are w\" by (metis all_x_v derarg.transN)\n        from no_x_w cases_x(2) have \"G \\<turnstile> No x are x\" by (metis derarg.reflN derarg.transN less_equal_prop_def)\n        then have \"G \\<turnstile> All x are y\" by (rule derarg.initN2)\n        thus ?thesis by (metis All)\n      qed\n    }\n    thus ?thesis\n      by metis\n  next\n    case (No x y)\n    {\n      define Axy where \"Axy = { z. (x \\<lesssim>G z) \\<or> (y \\<lesssim>G z) }\"\n    \n      have \"Axy \\<notin> M_ex7 G\"\n      proof (rule notI)\n        assume \"Axy \\<in> M_ex7 G\"\n        from `M \\<Turnstile> g` No have \"M x \\<inter> M y = {}\" by simp\n        have 1 : \"Axy \\<in> M x\"\n          by (metis (lifting, no_types) Axy_def M_def `Axy \\<in> M_ex7 G` char_model_ex8_def less_equal_prop_refl mem_Collect_eq)\n        have 2 : \"Axy \\<in> M y\"\n          by (metis (lifting, no_types) Axy_def M_def `Axy \\<in> M_ex7 G` char_model_ex8_def less_equal_prop_refl mem_Collect_eq)\n        from 1 2 have \"M x \\<inter> M y \\<noteq> {}\" by auto\n        with `M x \\<inter> M y = {}` show False by simp\n      qed\n      then have \"\\<not>(does_not_derive Axy G)\"\n        by (metis (lifting) Axy_def M_ex7_def less_equal_prop_trans mem_Collect_eq subset_UNIV up_closed_def)\n      then have \"\\<exists>v \\<in> Axy. \\<exists>w \\<in> Axy. (G \\<turnstile> No v are w)\"\n        unfolding M_ex7_def does_not_derive_def\n        by simp\n      then obtain v w where \"G \\<turnstile> No v are w\" \"v \\<in> Axy\" \"w \\<in> Axy\" by auto\n      then have cases : \"(x \\<lesssim>G v) \\<or> (y \\<lesssim>G v)\" \"(x \\<lesssim>G w) \\<or> (y \\<lesssim>G w)\"\n        by (metis mem_Collect_eq Axy_def)+\n    \n      note case1_e = disjE[OF cases(1)]\n      note case2_e = disjE[OF cases(2)]\n      note cases_elim = case1_e[case_product case2_e, case_names 1 2 3 4]\n      have ?thesis\n      proof (cases rule: cases_elim)\n        case 1\n        then have \"G \\<turnstile> All x are v\" \"G \\<turnstile> All x are w\" by (metis less_equal_prop_def)+\n        with `G \\<turnstile> No v are w` have \"G \\<turnstile> No x are w\" by (metis derarg.transN)\n        then have \"G \\<turnstile> No w are x\" by (rule derarg.reflN)\n        with `G \\<turnstile> All x are w` have \"G \\<turnstile> No x are x\" by (rule derarg.transN)\n        then have \"G \\<turnstile> No x are y\" by (rule derarg.initN)\n        thus ?thesis by (metis No)\n      next\n        case 2\n        then have \"G \\<turnstile> All x are v\" \"G \\<turnstile> All y are w\" by (metis less_equal_prop_def)+\n        with `G \\<turnstile> No v are w` have \"G \\<turnstile> No x are w\" by (metis derarg.transN)\n        then have \"G \\<turnstile> No w are x\" by (rule derarg.reflN)\n        with `G \\<turnstile> All y are w` have \"G \\<turnstile> No x are y\" by (metis derarg.reflN derarg.transN)\n        thus ?thesis by (metis No)\n      next\n        case 3\n        then have \"G \\<turnstile> All y are v\" \"G \\<turnstile> All x are w\" by (metis less_equal_prop_def)+\n        with `G \\<turnstile> No v are w` have \"G \\<turnstile> No y are w\" by (metis derarg.transN)\n        then have \"G \\<turnstile> No w are y\" by (rule derarg.reflN)\n        with `G \\<turnstile> All x are w` have \"G \\<turnstile> No x are y\" by (metis derarg.transN)\n        thus ?thesis by (metis No)\n      next\n        case 4\n        then have \"G \\<turnstile> All y are v\" \"G \\<turnstile> All y are w\" by (metis less_equal_prop_def)+\n        with `G \\<turnstile> No v are w` have \"G \\<turnstile> No y are w\" by (metis derarg.transN)\n        then have \"G \\<turnstile> No w are y\" by (rule derarg.reflN)\n        with `G \\<turnstile> All y are w` have \"G \\<turnstile> No y are y\" by (rule derarg.transN)\n        then have \"G \\<turnstile> No x are y\" by (metis derarg.initN derarg.reflN)\n        thus ?thesis by (metis No)\n      qed\n    }\n    thus ?thesis by metis\n  qed\nqed\n\n\nlemma a :\"(A::formula set) \\<inter> all_some_no_formulas \\<equiv> A\"\nproof -\n  have \"\\<forall>a \\<in> A. a \\<in> all_some_no_formulas\"\n    by (metis (lifting) UNIV_I all_some_no_formulas_def forms_complete mem_Collect_eq)\n  then have \"A \\<subseteq> {x \\<in> UNIV. form_all x \\<or> form_some x \\<or> form_no x}\"\n    by (metis all_some_no_formulas_def subsetI)\n  then have \"A = A \\<inter> {x \\<in> UNIV. form_all x \\<or> form_some x \\<or> form_no x}\"\n    by (metis eq_iff inf.bounded_iff inf.cobounded1 subset_refl)\n  then show \"(A::formula set) \\<inter> all_some_no_formulas \\<equiv> A\"\n    unfolding all_some_no_formulas_def by auto\nqed\n\nlemma intersect:\n  fixes G\n  defines \"Gall_no \\<equiv> G \\<inter> all_no_formulas\"\n    and \"Gsome \\<equiv> G \\<inter> some_formulas\"\n    shows \"G = Gall_no \\<union> Gsome\"\nproof (simp add:Gall_no_def all_no_formulas_def Gsome_def some_formulas_def)\n  have 1: \"G \\<inter> ({x. form_all x \\<or> form_no x} \\<union> {x. form_some x}) = G \\<inter> {x. form_all x \\<or> form_no x} \\<union> G \\<inter> {x. form_some x}\"\n    by auto \n  have 2: \"({x. form_all x \\<or> form_no x} \\<union> {x. form_some x}) = all_some_no_formulas\"\n  proof -\n    have \"Collect form_all \\<union> (Collect form_some \\<union> Collect form_no) = all_some_no_formulas\"\n      using all_some_no_formulas_def by auto\n    thus \"{x. form_all x \\<or> form_no x} \\<union> {x. form_some x} = all_some_no_formulas\"\n      by (metis Collect_disj_eq sup_commute sup_left_commute)\n  qed\n  have \"G \\<inter> all_some_no_formulas = G \\<inter> {x. form_all x \\<or> form_no x} \\<union> G \\<inter> {x. form_some x}\"\n    by (metis \"1\" \"2\" Collect_disj_eq a)\n  then have \"G = G \\<inter> {x. form_all x \\<or> form_no x} \\<union> G \\<inter> {x. form_some x}\"\n    by (metis a)\n  then show \"G = G \\<inter> {x. form_all x \\<or> form_no x} \\<union> G \\<inter> {x. form_some x}\" by fast\nqed\n\ntheorem exercise_9: \n  fixes G\n  assumes G_sat1 : \"G \\<Turnstile>G g TYPE(formula)\"\n      and G_sat2 : \"G \\<Turnstile>G g TYPE((atProp set))\"\n  shows \"G \\<turnstile> g\"\nproof -\n  have all_no_form_der_g : \"g \\<in> all_no_formulas \\<Longrightarrow> G \\<turnstile> g\"\n  proof -\n    assume \"g \\<in> all_no_formulas\"\n    define G' where \"G' = G \\<inter> all_no_formulas\"\n    define M where \"M = char_model_ex8 G'\"\n    define Gsome where \"Gsome = G \\<inter> some_formulas\"\n\n    show ?thesis\n    proof (cases \"M \\<Turnstile>M Gsome\")\n      case(True)\n      have \"G' \\<subseteq> all_no_formulas\"\n        by (metis G'_def Int_lower2)\n      have M_sat_G': \"M \\<Turnstile>M G'\" \n        by (metis G'_def M_def exercise_8_1 inf.cobounded1 inf_commute)\n      have \"G' \\<union> Gsome = G\" \n        by (metis G'_def Gsome_def intersect)\n      with M_sat_G' have M_sat_G : \"M \\<Turnstile>M G\"\n        by (metis M_satisfies_G_rewrites(3) True)\n      then have \"M \\<Turnstile> g\"\n        by (metis G_satisfies_def G_sat2)   \n      then have \"G' \\<turnstile> g\"\n        using exercise_8_2[of G' g]\n        by (metis M_def `g \\<in> all_no_formulas` `G' \\<subseteq> all_no_formulas`)\n      then show ?thesis\n        by (metis G'_def G_derives_mono inf.cobounded2 inf_commute)\n    next\n      case (False)\n      then have \"\\<not>(M \\<Turnstile>M G)\"\n        by (metis Gsome_def M_satisfies_G_rewrites(3) sup_inf_absorb)\n      have \"G' \\<subseteq> all_no_formulas\"\n        by (metis G'_def Int_lower2)\n      from False have 1: \"\\<exists>f \\<in> Gsome. \\<not>(M \\<Turnstile> f)\" by fast\n      obtain f where dNd : \"f \\<in> Gsome\" \"\\<not>(M \\<Turnstile> f)\"\n        by (metis \"1\")\n      obtain x y where Sxy : \"f = Some x are y\"\n        by (metis Gsome_def Int_iff dNd(1) form_some.elims(2) in_some_formulas)\n      from dNd have dNdSxy: \"\\<not>(M \\<Turnstile> Some x are y)\"\n        by (metis Sxy)\n      from dNdSxy have \"M x \\<inter> M y = {}\" by auto\n      then obtain f' where derNxy : \"M \\<Turnstile> f'\" \"f' = No x are y\" by (metis M_satisfies.simps(3))\n      have \"f' \\<in> all_no_formulas\"\n        by (metis derNxy(2) form_some.simps(3) in_all_no_formulas)\n      then have \"G' \\<turnstile> f'\"\n        using exercise_8_2[of G' f']\n        by (metis M_def `G' \\<subseteq> all_no_formulas` derNxy(1))\n      then have \"G \\<turnstile> No x are y\" by (metis G'_def G_derives_mono Int_lower1 derNxy(2))\n      have \"G \\<turnstile> Some x are y\" by (metis Gsome_def IntE Sxy ass dNd(1))\n      with `G \\<turnstile> No x are y` show ?thesis by (metis derarg.any)\n    qed\n  qed\n\n  show ?thesis\n  proof (cases g)\n    case (Some x y)\n    show ?thesis\n     by (metis G_sat1 Some exercise_7_1 exercise_7_2)\n  next\n    case (All x y)\n    have \"g \\<in> all_no_formulas\"\n     by (metis All form_some.simps(2) in_all_no_formulas)\n    with all_no_form_der_g show ?thesis by auto\n  next\n    case (No x y)\n    have \"g \\<in> all_no_formulas\"\n     by (metis No form_some.simps(3) in_all_no_formulas)\n    with all_no_form_der_g show ?thesis by auto\n  qed\nqed\n\nend\n", "meta": {"author": "goodlyrottenapple", "repo": "isabelle-syllogisms", "sha": "3ca41c0ad9716e15a8fe42221dc2fb299e7a0a8d", "save_path": "github-repos/isabelle/goodlyrottenapple-isabelle-syllogisms", "path": "github-repos/isabelle/goodlyrottenapple-isabelle-syllogisms/isabelle-syllogisms-3ca41c0ad9716e15a8fe42221dc2fb299e7a0a8d/Section3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7683938373942001}}
{"text": "  \n(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Comparing growth of functions on natural numbers by a preorder relation\\<close>\n\ntheory Function_Growth\nimports Main Preorder Discrete\nbegin\n\n(* FIXME move *)\n\ncontext linorder\nbegin\n\nlemma mono_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x < y\"\nproof\n  show \"x < y\"\n  proof (rule ccontr)\n    assume \"\\<not> x < y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nend\n\nlemma (in semidom_divide) power_diff:\n  fixes a :: 'a\n  assumes \"a \\<noteq> 0\"\n  assumes \"m \\<ge> n\"\n  shows \"a ^ (m - n) = (a ^ m) div (a ^ n)\"\nproof -\n  define q where \"q = m - n\"\n  with assms have \"m = q + n\" by (simp add: q_def)\n  with q_def show ?thesis using \\<open>a \\<noteq> 0\\<close> by (simp add: power_add)\nqed\n\n\nsubsection \\<open>Motivation\\<close>\n\ntext \\<open>\n  When comparing growth of functions in computer science, it is common to adhere\n  on Landau Symbols (``O-Notation'').  However these come at the cost of notational\n  oddities, particularly writing \\<open>f = O(g)\\<close> for \\<open>f \\<in> O(g)\\<close> etc.\n  \n  Here we suggest a different way, following Hardy (G.~H.~Hardy and J.~E.~Littlewood,\n  Some problems of Diophantine approximation, Acta Mathematica 37 (1914), p.~225).\n  We establish a quasi order relation \\<open>\\<lesssim>\\<close> on functions such that\n  \\<open>f \\<lesssim> g \\<longleftrightarrow> f \\<in> O(g)\\<close>.  From a didactic point of view, this does not only\n  avoid the notational oddities mentioned above but also emphasizes the key insight\n  of a growth hierarchy of functions:\n  \\<open>(\\<lambda>n. 0) \\<lesssim> (\\<lambda>n. k) \\<lesssim> Discrete.log \\<lesssim> Discrete.sqrt \\<lesssim> id \\<lesssim> \\<dots>\\<close>.\n\\<close>\n\nsubsection \\<open>Model\\<close>\n\ntext \\<open>\n  Our growth functions are of type \\<open>\\<nat> \\<Rightarrow> \\<nat>\\<close>.  This is different\n  to the usual conventions for Landau symbols for which \\<open>\\<real> \\<Rightarrow> \\<real>\\<close>\n  would be appropriate, but we argue that \\<open>\\<real> \\<Rightarrow> \\<real>\\<close> is more\n  appropriate for analysis, whereas our setting is discrete.\n\n  Note that we also restrict the additional coefficients to \\<open>\\<nat>\\<close>, something\n  we discuss at the particular definitions.\n\\<close>\n\nsubsection \\<open>The \\<open>\\<lesssim>\\<close> relation\\<close>\n\ndefinition less_eq_fun :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" (infix \"\\<lesssim>\" 50)\nwhere\n  \"f \\<lesssim> g \\<longleftrightarrow> (\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m)\"\n\ntext \\<open>\n  This yields \\<open>f \\<lesssim> g \\<longleftrightarrow> f \\<in> O(g)\\<close>.  Note that \\<open>c\\<close> is restricted to\n  \\<open>\\<nat>\\<close>.  This does not pose any problems since if \\<open>f \\<in> O(g)\\<close> holds for\n  a \\<open>c \\<in> \\<real>\\<close>, it also holds for \\<open>\\<lceil>c\\<rceil> \\<in> \\<nat>\\<close> by transitivity.\n\\<close>\n\nlemma less_eq_funI [intro?]:\n  assumes \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\"\n  shows \"f \\<lesssim> g\"\n  unfolding less_eq_fun_def by (rule assms)\n\nlemma not_less_eq_funI:\n  assumes \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * g m < f m\"\n  shows \"\\<not> f \\<lesssim> g\"\n  using assms unfolding less_eq_fun_def linorder_not_le [symmetric] by blast\n\nlemma less_eq_funE [elim?]:\n  assumes \"f \\<lesssim> g\"\n  obtains n c where \"c > 0\" and \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c * g m\"\n  using assms unfolding less_eq_fun_def by blast\n\nlemma not_less_eq_funE:\n  assumes \"\\<not> f \\<lesssim> g\" and \"c > 0\"\n  obtains m where \"m > n\" and \"c * g m < f m\"\n  using assms unfolding less_eq_fun_def linorder_not_le [symmetric] by blast\n\n\nsubsection \\<open>The \\<open>\\<approx>\\<close> relation, the equivalence relation induced by \\<open>\\<lesssim>\\<close>\\<close>\n\ndefinition equiv_fun :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" (infix \"\\<cong>\" 50)\nwhere\n  \"f \\<cong> g \\<longleftrightarrow>\n    (\\<exists>c\\<^sub>1>0. \\<exists>c\\<^sub>2>0. \\<exists>n. \\<forall>m>n. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m)\"\n\ntext \\<open>\n  This yields \\<open>f \\<cong> g \\<longleftrightarrow> f \\<in> \\<Theta>(g)\\<close>.  Concerning \\<open>c\\<^sub>1\\<close> and \\<open>c\\<^sub>2\\<close>\n  restricted to @{typ nat}, see note above on \\<open>(\\<lesssim>)\\<close>.\n\\<close>\n\nlemma equiv_funI:\n  assumes \"\\<exists>c\\<^sub>1>0. \\<exists>c\\<^sub>2>0. \\<exists>n. \\<forall>m>n. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n  shows \"f \\<cong> g\"\n  unfolding equiv_fun_def by (rule assms)\n\nlemma not_equiv_funI:\n  assumes \"\\<And>c\\<^sub>1 c\\<^sub>2 n. c\\<^sub>1 > 0 \\<Longrightarrow> c\\<^sub>2 > 0 \\<Longrightarrow>\n    \\<exists>m>n. c\\<^sub>1 * f m < g m \\<or> c\\<^sub>2 * g m < f m\"\n  shows \"\\<not> f \\<cong> g\"\n  using assms unfolding equiv_fun_def linorder_not_le [symmetric] by blast\n\nlemma equiv_funE:\n  assumes \"f \\<cong> g\"\n  obtains n c\\<^sub>1 c\\<^sub>2 where \"c\\<^sub>1 > 0\" and \"c\\<^sub>2 > 0\"\n    and \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n  using assms unfolding equiv_fun_def by blast\n\nlemma not_equiv_funE:\n  fixes n c\\<^sub>1 c\\<^sub>2\n  assumes \"\\<not> f \\<cong> g\" and \"c\\<^sub>1 > 0\" and \"c\\<^sub>2 > 0\"\n  obtains m where \"m > n\"\n    and \"c\\<^sub>1 * f m < g m \\<or> c\\<^sub>2 * g m < f m\"\n  using assms unfolding equiv_fun_def linorder_not_le [symmetric] by blast\n\n\nsubsection \\<open>The \\<open>\\<prec>\\<close> relation, the strict part of \\<open>\\<lesssim>\\<close>\\<close>\n\ndefinition less_fun :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> bool\" (infix \"\\<prec>\" 50)\nwhere\n  \"f \\<prec> g \\<longleftrightarrow> f \\<lesssim> g \\<and> \\<not> g \\<lesssim> f\"\n\nlemma less_funI:\n  assumes \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\"\n    and \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * f m < g m\"\n  shows \"f \\<prec> g\"\n  using assms unfolding less_fun_def less_eq_fun_def linorder_not_less [symmetric] by blast\n\nlemma not_less_funI:\n  assumes \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * g m < f m\"\n    and \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. g m \\<le> c * f m\"\n  shows \"\\<not> f \\<prec> g\"\n  using assms unfolding less_fun_def less_eq_fun_def linorder_not_less [symmetric] by blast\n\nlemma less_funE [elim?]:\n  assumes \"f \\<prec> g\"\n  obtains n c where \"c > 0\" and \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c * g m\"\n    and \"\\<And>c n. c > 0 \\<Longrightarrow> \\<exists>m>n. c * f m < g m\"\nproof -\n  from assms have \"f \\<lesssim> g\" and \"\\<not> g \\<lesssim> f\" by (simp_all add: less_fun_def)\n  from \\<open>f \\<lesssim> g\\<close> obtain n c where *:\"c > 0\" \"m > n \\<Longrightarrow> f m \\<le> c * g m\" for m\n    by (rule less_eq_funE) blast\n  { fix c n :: nat\n    assume \"c > 0\"\n    with \\<open>\\<not> g \\<lesssim> f\\<close> obtain m where \"m > n\" \"c * f m < g m\"\n      by (rule not_less_eq_funE) blast\n    then have **: \"\\<exists>m>n. c * f m < g m\" by blast\n  } note ** = this\n  from * ** show thesis by (rule that)\nqed\n\nlemma not_less_funE:\n  assumes \"\\<not> f \\<prec> g\" and \"c > 0\"\n  obtains m where \"m > n\" and \"c * g m < f m\"\n    | d q where \"\\<And>m. d > 0 \\<Longrightarrow> m > q \\<Longrightarrow> g q \\<le> d * f q\"\n  using assms unfolding less_fun_def linorder_not_less [symmetric] by blast\n\ntext \\<open>\n  I did not find a proof for \\<open>f \\<prec> g \\<longleftrightarrow> f \\<in> o(g)\\<close>.  Maybe this only\n  holds if \\<open>f\\<close> and/or \\<open>g\\<close> are of a certain class of functions.\n  However \\<open>f \\<in> o(g) \\<longrightarrow> f \\<prec> g\\<close> is provable, and this yields a\n  handy introduction rule.\n\n  Note that D. Knuth ignores \\<open>o\\<close> altogether.  So what \\dots\n\n  Something still has to be said about the coefficient \\<open>c\\<close> in\n  the definition of \\<open>(\\<prec>)\\<close>.  In the typical definition of \\<open>o\\<close>,\n  it occurs on the \\emph{right} hand side of the \\<open>(>)\\<close>.  The reason\n  is that the situation is dual to the definition of \\<open>O\\<close>: the definition\n  works since \\<open>c\\<close> may become arbitrary small.  Since this is not possible\n  within @{term \\<nat>}, we push the coefficient to the left hand side instead such\n  that it may become arbitrary big instead.\n\\<close>\n\nlemma less_fun_strongI:\n  assumes \"\\<And>c. c > 0 \\<Longrightarrow> \\<exists>n. \\<forall>m>n. c * f m < g m\"\n  shows \"f \\<prec> g\"\nproof (rule less_funI)\n  have \"1 > (0::nat)\" by simp\n  with assms [OF this] obtain n where *: \"m > n \\<Longrightarrow> 1 * f m < g m\" for m\n    by blast\n  have \"\\<forall>m>n. f m \\<le> 1 * g m\"\n  proof (rule allI, rule impI)\n    fix m\n    assume \"m > n\"\n    with * have \"1 * f m < g m\" by simp\n    then show \"f m \\<le> 1 * g m\" by simp\n  qed\n  with \\<open>1 > 0\\<close> show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\" by blast\n  fix c n :: nat\n  assume \"c > 0\"\n  with assms obtain q where \"m > q \\<Longrightarrow> c * f m < g m\" for m by blast\n  then have \"c * f (Suc (q + n)) < g (Suc (q + n))\" by simp\n  moreover have \"Suc (q + n) > n\" by simp\n  ultimately show \"\\<exists>m>n. c * f m < g m\" by blast\nqed\n\n\nsubsection \\<open>\\<open>\\<lesssim>\\<close> is a preorder\\<close>\n\ntext \\<open>This yields all lemmas relating \\<open>\\<lesssim>\\<close>, \\<open>\\<prec>\\<close> and \\<open>\\<cong>\\<close>.\\<close>\n\ninterpretation fun_order: preorder_equiv less_eq_fun less_fun\n  rewrites \"fun_order.equiv = equiv_fun\"\nproof -\n  interpret preorder: preorder_equiv less_eq_fun less_fun\n  proof\n    fix f g h\n    show \"f \\<lesssim> f\"\n    proof\n      have \"\\<exists>n. \\<forall>m>n. f m \\<le> 1 * f m\" by auto\n      then show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * f m\" by blast\n    qed\n    show \"f \\<prec> g \\<longleftrightarrow> f \\<lesssim> g \\<and> \\<not> g \\<lesssim> f\"\n      by (fact less_fun_def)\n    assume \"f \\<lesssim> g\" and \"g \\<lesssim> h\"\n    show \"f \\<lesssim> h\"\n    proof\n      from \\<open>f \\<lesssim> g\\<close> obtain n\\<^sub>1 c\\<^sub>1\n        where \"c\\<^sub>1 > 0\" and P\\<^sub>1: \"\\<And>m. m > n\\<^sub>1 \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m\"\n        by rule blast\n      from \\<open>g \\<lesssim> h\\<close> obtain n\\<^sub>2 c\\<^sub>2\n        where \"c\\<^sub>2 > 0\" and P\\<^sub>2: \"\\<And>m. m > n\\<^sub>2 \\<Longrightarrow> g m \\<le> c\\<^sub>2 * h m\"\n        by rule blast\n      have \"\\<forall>m>max n\\<^sub>1 n\\<^sub>2. f m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume Q: \"m > max n\\<^sub>1 n\\<^sub>2\"\n        from P\\<^sub>1 Q have *: \"f m \\<le> c\\<^sub>1 * g m\" by simp\n        from P\\<^sub>2 Q have \"g m \\<le> c\\<^sub>2 * h m\" by simp\n        with \\<open>c\\<^sub>1 > 0\\<close> have \"c\\<^sub>1 * g m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\" by simp\n        with * show \"f m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\" by (rule order_trans)\n      qed\n      then have \"\\<exists>n. \\<forall>m>n. f m \\<le> (c\\<^sub>1 * c\\<^sub>2) * h m\" by rule\n      moreover from \\<open>c\\<^sub>1 > 0\\<close> \\<open>c\\<^sub>2 > 0\\<close> have \"c\\<^sub>1 * c\\<^sub>2 > 0\" by simp\n      ultimately show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * h m\" by blast\n    qed\n  qed\n  from preorder.preorder_equiv_axioms show \"class.preorder_equiv less_eq_fun less_fun\" .\n  show \"preorder_equiv.equiv less_eq_fun = equiv_fun\"\n  proof (rule ext, rule ext, unfold preorder.equiv_def)\n    fix f g\n    show \"f \\<lesssim> g \\<and> g \\<lesssim> f \\<longleftrightarrow> f \\<cong> g\"\n    proof\n      assume \"f \\<cong> g\"\n      then obtain n c\\<^sub>1 c\\<^sub>2 where \"c\\<^sub>1 > 0\" and \"c\\<^sub>2 > 0\"\n        and *: \"\\<And>m. m > n \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n        by (rule equiv_funE) blast\n      have \"\\<forall>m>n. f m \\<le> c\\<^sub>1 * g m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume \"m > n\"\n        with * show \"f m \\<le> c\\<^sub>1 * g m\" by simp\n      qed\n      with \\<open>c\\<^sub>1 > 0\\<close> have \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * g m\" by blast\n      then have \"f \\<lesssim> g\" ..\n      have \"\\<forall>m>n. g m \\<le> c\\<^sub>2 * f m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume \"m > n\"\n        with * show \"g m \\<le> c\\<^sub>2 * f m\" by simp\n      qed\n      with \\<open>c\\<^sub>2 > 0\\<close> have \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. g m \\<le> c * f m\" by blast\n      then have \"g \\<lesssim> f\" ..\n      from \\<open>f \\<lesssim> g\\<close> and \\<open>g \\<lesssim> f\\<close> show \"f \\<lesssim> g \\<and> g \\<lesssim> f\" ..\n    next\n      assume \"f \\<lesssim> g \\<and> g \\<lesssim> f\"\n      then have \"f \\<lesssim> g\" and \"g \\<lesssim> f\" by auto\n      from \\<open>f \\<lesssim> g\\<close> obtain n\\<^sub>1 c\\<^sub>1 where \"c\\<^sub>1 > 0\"\n        and P\\<^sub>1: \"\\<And>m. m > n\\<^sub>1 \\<Longrightarrow> f m \\<le> c\\<^sub>1 * g m\" by rule blast\n      from \\<open>g \\<lesssim> f\\<close> obtain n\\<^sub>2 c\\<^sub>2 where \"c\\<^sub>2 > 0\"\n        and P\\<^sub>2: \"\\<And>m. m > n\\<^sub>2 \\<Longrightarrow> g m \\<le> c\\<^sub>2 * f m\" by rule blast\n      have \"\\<forall>m>max n\\<^sub>1 n\\<^sub>2. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume Q: \"m > max n\\<^sub>1 n\\<^sub>2\"\n        from P\\<^sub>1 Q have \"f m \\<le> c\\<^sub>1 * g m\" by simp\n        moreover from P\\<^sub>2 Q have \"g m \\<le> c\\<^sub>2 * f m\" by simp\n        ultimately show \"f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\" ..\n      qed\n      with \\<open>c\\<^sub>1 > 0\\<close> \\<open>c\\<^sub>2 > 0\\<close> have \"\\<exists>c\\<^sub>1>0. \\<exists>c\\<^sub>2>0. \\<exists>n.\n        \\<forall>m>n. f m \\<le> c\\<^sub>1 * g m \\<and> g m \\<le> c\\<^sub>2 * f m\" by blast\n      then show \"f \\<cong> g\" by (rule equiv_funI)\n    qed\n  qed\nqed\n\ndeclare fun_order.antisym [intro?]\n\n\nsubsection \\<open>Simple examples\\<close>\n\ntext \\<open>\n  Most of these are left as constructive exercises for the reader.  Note that additional\n  preconditions to the functions may be necessary.  The list here is by no means to be\n  intended as complete construction set for typical functions, here surely something\n  has to be added yet.\n\\<close>\n\ntext \\<open>@{prop \"(\\<lambda>n. f n + k) \\<cong> f\"}\\<close>\n\nlemma equiv_fun_mono_const:\n  assumes \"mono f\" and \"\\<exists>n. f n > 0\"\n  shows \"(\\<lambda>n. f n + k) \\<cong> f\"\nproof (cases \"k = 0\")\n  case True then show ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof\n    show \"(\\<lambda>n. f n + k) \\<lesssim> f\"\n    proof\n      from \\<open>\\<exists>n. f n > 0\\<close> obtain n where \"f n > 0\" ..\n      have \"\\<forall>m>n. f m + k \\<le> Suc k * f m\"\n      proof (rule allI, rule impI)\n        fix m\n        assume \"n < m\"\n        with \\<open>mono f\\<close> have \"f n \\<le> f m\"\n          using less_imp_le_nat monoE by blast\n        with  \\<open>0 < f n\\<close> have \"0 < f m\" by auto\n        then obtain l where \"f m = Suc l\" by (cases \"f m\") simp_all\n        then show \"f m + k \\<le> Suc k * f m\" by simp\n      qed\n      then show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m + k \\<le> c * f m\" by blast\n    qed\n    show \"f \\<lesssim> (\\<lambda>n. f n + k)\"\n    proof\n      have \"f m \\<le> 1 * (f m + k)\" for m by simp\n      then show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * (f m + k)\" by blast\n    qed\n  qed\nqed\n\nlemma\n  assumes \"strict_mono f\"\n  shows \"(\\<lambda>n. f n + k) \\<cong> f\"\nproof (rule equiv_fun_mono_const)\n  from assms show \"mono f\" by (rule strict_mono_mono)\n  show \"\\<exists>n. 0 < f n\"\n  proof (rule ccontr)\n    assume \"\\<not> (\\<exists>n. 0 < f n)\"\n    then have \"\\<And>n. f n = 0\" by simp\n    then have \"f 0 = f 1\" by simp\n    moreover from \\<open>strict_mono f\\<close> have \"f 0 < f 1\"\n      by (simp add: strict_mono_def) \n    ultimately show False by simp\n  qed\nqed\n  \nlemma\n  \"(\\<lambda>n. Suc k * f n) \\<cong> f\"\nproof\n  show \"(\\<lambda>n. Suc k * f n) \\<lesssim> f\"\n  proof\n    have \"Suc k * f m \\<le> Suc k * f m\" for m by simp\n    then show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. Suc k * f m \\<le> c * f m\" by blast\n  qed\n  show \"f \\<lesssim> (\\<lambda>n. Suc k * f n)\"\n  proof\n    have \"f m \\<le> 1 * (Suc k * f m)\" for m by simp\n    then show \"\\<exists>c>0. \\<exists>n. \\<forall>m>n. f m \\<le> c * (Suc k * f m)\" by blast\n  qed\nqed\n\nlemma\n  \"f \\<lesssim> (\\<lambda>n. f n + g n)\"\n  by rule auto\n\nlemma\n  \"(\\<lambda>_. 0) \\<prec> (\\<lambda>n. Suc k)\"\n  by (rule less_fun_strongI) auto\n\nlemma\n  \"(\\<lambda>_. k) \\<prec> Discrete.log\"\nproof (rule less_fun_strongI)\n  fix c :: nat\n  have \"\\<forall>m>2 ^ (Suc (c * k)). c * k < Discrete.log m\"\n  proof (rule allI, rule impI)\n    fix m :: nat\n    assume \"2 ^ Suc (c * k) < m\"\n    then have \"2 ^ Suc (c * k) \\<le> m\" by simp\n    with log_mono have \"Discrete.log (2 ^ (Suc (c * k))) \\<le> Discrete.log m\"\n      by (blast dest: monoD)\n    moreover have \"c * k < Discrete.log (2 ^ (Suc (c * k)))\" by simp\n    ultimately show \"c * k < Discrete.log m\" by auto\n  qed\n  then show \"\\<exists>n. \\<forall>m>n. c * k < Discrete.log m\" ..\nqed\n\n(*lemma\n  \"Discrete.log \\<prec> Discrete.sqrt\"\nproof (rule less_fun_strongI)*)\ntext \\<open>@{prop \"Discrete.log \\<prec> Discrete.sqrt\"}\\<close>\n\nlemma\n  \"Discrete.sqrt \\<prec> id\"\nproof (rule less_fun_strongI)\n  fix c :: nat\n  assume \"0 < c\"\n  have \"\\<forall>m>(Suc c)\\<^sup>2. c * Discrete.sqrt m < id m\"\n  proof (rule allI, rule impI)\n    fix m\n    assume \"(Suc c)\\<^sup>2 < m\"\n    then have \"(Suc c)\\<^sup>2 \\<le> m\" by simp\n    with mono_sqrt have \"Discrete.sqrt ((Suc c)\\<^sup>2) \\<le> Discrete.sqrt m\" by (rule monoE)\n    then have \"Suc c \\<le> Discrete.sqrt m\" by simp\n    then have \"c < Discrete.sqrt m\" by simp\n    moreover from \\<open>(Suc c)\\<^sup>2 < m\\<close> have \"Discrete.sqrt m > 0\" by simp\n    ultimately have \"c * Discrete.sqrt m < Discrete.sqrt m * Discrete.sqrt m\" by simp\n    also have \"\\<dots> \\<le> m\" by (simp add: power2_eq_square [symmetric])\n    finally show \"c * Discrete.sqrt m < id m\" by simp\n  qed\n  then show \"\\<exists>n. \\<forall>m>n. c * Discrete.sqrt m < id m\" ..\nqed\n\nlemma\n  \"id \\<prec> (\\<lambda>n. n\\<^sup>2)\"\n  by (rule less_fun_strongI) (auto simp add: power2_eq_square)\n\nlemma\n  \"(\\<lambda>n. n ^ k) \\<prec> (\\<lambda>n. n ^ Suc k)\"\n  by (rule less_fun_strongI) auto\n\n(*lemma \n  \"(\\<lambda>n. n ^ k) \\<prec> (\\<lambda>n. 2 ^ n)\"\nproof (rule less_fun_strongI)*)\ntext \\<open>@{prop \"(\\<lambda>n. n ^ k) \\<prec> (\\<lambda>n. 2 ^ n)\"}\\<close>\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/Function_Growth.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8723473713594991, "lm_q1q2_score": 0.7683610156751335}}
{"text": "theory Scratch\nimports Porder\nbegin\n\ndatatype 'a myList = \n  myNil |\n  myCons 'a \"'a myList\"\n\nfun myBelow :: \"'a::below myList \\<Rightarrow> 'a myList \\<Rightarrow> bool\"  where\n  \"myBelow myNil y = True\" |\n  \"myBelow (myCons b xs) myNil = False\" |\n  \"myBelow (myCons b xs) (myCons c ys) = ((below b c) \\<and> (myBelow xs ys))\"\n\ninstantiation myList :: (below) below\nbegin\n  definition below_myList_def [simp]:\n    \"(op \\<sqsubseteq>) \\<equiv> (\\<lambda>x y. myBelow x y)\"\n  instance ..\nend\n\nlemma refl_less_myList: \"(x::('a::po) myList) \\<sqsubseteq> x\"\n  apply (induction x)\n  apply simp\n  apply auto\n  done\n\n\n\nlemma antisym_help: \"myBelow (myCons a x) (y::('a::po) myList) \\<Longrightarrow> myBelow y (myCons a x) \\<Longrightarrow> myCons a x = y\"\n  apply (induction y rule:myBelow.induct)\n  apply auto\n  apply (metis myBelow.simps(2) myList.exhaust)\n  by (metis below_antisym)\n\nlemma antisym_less_myList: \"(x::('a::po) myList) \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\n  apply (induction x)\n  apply auto\n  apply (metis myBelow.simps(2) myList.exhaust)\n  by (metis antisym_help)\n\nlemma trans_help: \"(\\<And>y. myBelow ys y \\<Longrightarrow> myBelow y xs \\<Longrightarrow> myBelow ys xs) \\<Longrightarrow>\n       myBelow (myCons c ys) (z::('a::po) myList)  \\<Longrightarrow> myBelow z (myCons b xs) \\<Longrightarrow> myBelow ys xs\"\n  by (metis myBelow.elims(2) myBelow.simps(3) myList.distinct(1) myList.exhaust)\n\nlemma trans_less_myList: \"(x::('a::po) myList) \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  apply (induction x arbitrary: y rule:myBelow.induct)\n  apply auto\n  apply (metis myBelow.elims(2) myBelow.simps(3) myList.distinct(1) myList.exhaust rev_below_trans)\n  by (metis trans_help)\n  \ninstantiation myList :: (po)po \nbegin\n  instance \n  apply intro_classes\n  apply (metis refl_less_myList)\n  apply (metis trans_less_myList)\n  apply (metis antisym_less_myList)\n  done\nend\n", "meta": {"author": "tyler-barker", "repo": "Random-Variable-Monad-in-Isabelle", "sha": "fa91ca592e82d16fb4d7e1b84a77e86b8b2b04a5", "save_path": "github-repos/isabelle/tyler-barker-Random-Variable-Monad-in-Isabelle", "path": "github-repos/isabelle/tyler-barker-Random-Variable-Monad-in-Isabelle/Random-Variable-Monad-in-Isabelle-fa91ca592e82d16fb4d7e1b84a77e86b8b2b04a5/Scratch.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026641072386, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.768351025734175}}
{"text": "theory ex2_06 imports Main begin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l v r) = v # contents l @ contents r\"\n\nfun treesum :: \"nat tree \\<Rightarrow> nat\" where\n\"treesum Tip = 0\" |\n\"treesum (Node l v r) = v + treesum l + treesum r\"\n\nvalue \"contents (Node (Node Tip x Tip) y (Node Tip z Tip))\"\nvalue \"treesum (Node (Node Tip 1 Tip) 2 (Node Tip 4 Tip))\"\n\ntheorem \"treesum t = listsum (contents t)\"\napply(induction t)\napply auto\ndone\n\nend", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter2/ex2_06.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7683461912260978}}
{"text": "(*  Title:      HOL/Computational_Algebra/Fraction_Field.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection\\<open>A formalization of the fraction field of any integral domain;\n         generalization of theory Rat from int to any integral domain\\<close>\n\ntheory Fraction_Field\nimports MainRLT\nbegin\n\nsubsection \\<open>General fractions construction\\<close>\n\nsubsubsection \\<open>Construction of the type of fractions\\<close>\n\ncontext idom begin\n\ndefinition fractrel :: \"'a \\<times> 'a \\<Rightarrow> 'a * 'a \\<Rightarrow> bool\" where\n  \"fractrel = (\\<lambda>x y. snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0 \\<and> fst x * snd y = fst y * snd x)\"\n\nlemma fractrel_iff [simp]:\n  \"fractrel x y \\<longleftrightarrow> snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0 \\<and> fst x * snd y = fst y * snd x\"\n  by (simp add: fractrel_def)\n\nlemma symp_fractrel: \"symp fractrel\"\n  by (simp add: symp_def)\n\nlemma transp_fractrel: \"transp fractrel\"\nproof (rule transpI, unfold split_paired_all)\n  fix a b a' b' a'' b'' :: 'a\n  assume A: \"fractrel (a, b) (a', b')\"\n  assume B: \"fractrel (a', b') (a'', b'')\"\n  have \"b' * (a * b'') = b'' * (a * b')\" by (simp add: ac_simps)\n  also from A have \"a * b' = a' * b\" by auto\n  also have \"b'' * (a' * b) = b * (a' * b'')\" by (simp add: ac_simps)\n  also from B have \"a' * b'' = a'' * b'\" by auto\n  also have \"b * (a'' * b') = b' * (a'' * b)\" by (simp add: ac_simps)\n  finally have \"b' * (a * b'') = b' * (a'' * b)\" .\n  moreover from B have \"b' \\<noteq> 0\" by auto\n  ultimately have \"a * b'' = a'' * b\" by simp\n  with A B show \"fractrel (a, b) (a'', b'')\" by auto\nqed\n\nlemma part_equivp_fractrel: \"part_equivp fractrel\"\nusing _ symp_fractrel transp_fractrel\nby(rule part_equivpI)(rule exI[where x=\"(0, 1)\"]; simp)\n\nend\n\nquotient_type (overloaded) 'a fract = \"'a :: idom \\<times> 'a\" / partial: \"fractrel\"\nby(rule part_equivp_fractrel)\n\nsubsubsection \\<open>Representation and basic operations\\<close>\n\nlift_definition Fract :: \"'a :: idom \\<Rightarrow> 'a \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>a b. if b = 0 then (0, 1) else (a, b)\"\n  by simp\n\nlemma Fract_cases [cases type: fract]:\n  obtains (Fract) a b where \"q = Fract a b\" \"b \\<noteq> 0\"\nby transfer simp\n\nlemma Fract_induct [case_names Fract, induct type: fract]:\n  \"(\\<And>a b. b \\<noteq> 0 \\<Longrightarrow> P (Fract a b)) \\<Longrightarrow> P q\"\n  by (cases q) simp\n\nlemma eq_fract:\n  shows \"\\<And>a b c d. b \\<noteq> 0 \\<Longrightarrow> d \\<noteq> 0 \\<Longrightarrow> Fract a b = Fract c d \\<longleftrightarrow> a * d = c * b\"\n    and \"\\<And>a. Fract a 0 = Fract 0 1\"\n    and \"\\<And>a c. Fract 0 a = Fract 0 c\"\nby(transfer; simp)+\n\ninstantiation fract :: (idom) comm_ring_1\nbegin\n\nlift_definition zero_fract :: \"'a fract\" is \"(0, 1)\" by simp\n\nlemma Zero_fract_def: \"0 = Fract 0 1\"\nby transfer simp\n\nlift_definition one_fract :: \"'a fract\" is \"(1, 1)\" by simp\n\nlemma One_fract_def: \"1 = Fract 1 1\"\nby transfer simp\n\nlift_definition plus_fract :: \"'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>q r. (fst q * snd r + fst r * snd q, snd q * snd r)\"\nby(auto simp add: algebra_simps)\n\nlemma add_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b + Fract c d = Fract (a * d + c * b) (b * d)\"\nby transfer simp\n\nlift_definition uminus_fract :: \"'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>x. (- fst x, snd x)\"\nby simp\n\nlemma minus_fract [simp]:\n  fixes a b :: \"'a::idom\"\n  shows \"- Fract a b = Fract (- a) b\"\nby transfer simp\n\nlemma minus_fract_cancel [simp]: \"Fract (- a) (- b) = Fract a b\"\n  by (cases \"b = 0\") (simp_all add: eq_fract)\n\ndefinition diff_fract_def: \"q - r = q + - (r::'a fract)\"\n\nlemma diff_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b - Fract c d = Fract (a * d - c * b) (b * d)\"\n  by (simp add: diff_fract_def)\n\nlift_definition times_fract :: \"'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>q r. (fst q * fst r, snd q * snd r)\"\nby(simp add: algebra_simps)\n\nlemma mult_fract [simp]: \"Fract (a::'a::idom) b * Fract c d = Fract (a * c) (b * d)\"\nby transfer simp\n\nlemma mult_fract_cancel:\n  \"c \\<noteq> 0 \\<Longrightarrow> Fract (c * a) (c * b) = Fract a b\"\nby transfer simp\n\ninstance\nproof\n  fix q r s :: \"'a fract\"\n  show \"(q * r) * s = q * (r * s)\"\n    by (cases q, cases r, cases s) (simp add: eq_fract algebra_simps)\n  show \"q * r = r * q\"\n    by (cases q, cases r) (simp add: eq_fract algebra_simps)\n  show \"1 * q = q\"\n    by (cases q) (simp add: One_fract_def eq_fract)\n  show \"(q + r) + s = q + (r + s)\"\n    by (cases q, cases r, cases s) (simp add: eq_fract algebra_simps)\n  show \"q + r = r + q\"\n    by (cases q, cases r) (simp add: eq_fract algebra_simps)\n  show \"0 + q = q\"\n    by (cases q) (simp add: Zero_fract_def eq_fract)\n  show \"- q + q = 0\"\n    by (cases q) (simp add: Zero_fract_def eq_fract)\n  show \"q - r = q + - r\"\n    by (cases q, cases r) (simp add: eq_fract)\n  show \"(q + r) * s = q * s + r * s\"\n    by (cases q, cases r, cases s) (simp add: eq_fract algebra_simps)\n  show \"(0::'a fract) \\<noteq> 1\"\n    by (simp add: Zero_fract_def One_fract_def eq_fract)\nqed\n\nend\n\nlemma of_nat_fract: \"of_nat k = Fract (of_nat k) 1\"\n  by (induct k) (simp_all add: Zero_fract_def One_fract_def)\n\nlemma Fract_of_nat_eq: \"Fract (of_nat k) 1 = of_nat k\"\n  by (rule of_nat_fract [symmetric])\n\nlemma fract_collapse:\n  \"Fract 0 k = 0\"\n  \"Fract 1 1 = 1\"\n  \"Fract k 0 = 0\"\nby(transfer; simp)+\n\nlemma fract_expand:\n  \"0 = Fract 0 1\"\n  \"1 = Fract 1 1\"\n  by (simp_all add: fract_collapse)\n\nlemma Fract_cases_nonzero:\n  obtains (Fract) a b where \"q = Fract a b\" and \"b \\<noteq> 0\" and \"a \\<noteq> 0\"\n    | (0) \"q = 0\"\nproof (cases \"q = 0\")\n  case True\n  then show thesis using 0 by auto\nnext\n  case False\n  then obtain a b where \"q = Fract a b\" and \"b \\<noteq> 0\" by (cases q) auto\n  with False have \"0 \\<noteq> Fract a b\" by simp\n  with \\<open>b \\<noteq> 0\\<close> have \"a \\<noteq> 0\" by (simp add: Zero_fract_def eq_fract)\n  with Fract \\<open>q = Fract a b\\<close> \\<open>b \\<noteq> 0\\<close> show thesis by auto\nqed\n\n\nsubsubsection \\<open>The field of rational numbers\\<close>\n\ncontext idom\nbegin\n\nsubclass ring_no_zero_divisors ..\n\nend\n\ninstantiation fract :: (idom) field\nbegin\n\nlift_definition inverse_fract :: \"'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>x. if fst x = 0 then (0, 1) else (snd x, fst x)\"\nby(auto simp add: algebra_simps)\n\nlemma inverse_fract [simp]: \"inverse (Fract a b) = Fract (b::'a::idom) a\"\nby transfer simp\n\ndefinition divide_fract_def: \"q div r = q * inverse (r:: 'a fract)\"\n\nlemma divide_fract [simp]: \"Fract a b div Fract c d = Fract (a * d) (b * c)\"\n  by (simp add: divide_fract_def)\n\ninstance\nproof\n  fix q :: \"'a fract\"\n  assume \"q \\<noteq> 0\"\n  then show \"inverse q * q = 1\"\n    by (cases q rule: Fract_cases_nonzero)\n      (simp_all add: fract_expand eq_fract mult.commute)\nnext\n  fix q r :: \"'a fract\"\n  show \"q div r = q * inverse r\" by (simp add: divide_fract_def)\nnext\n  show \"inverse 0 = (0:: 'a fract)\"\n    by (simp add: fract_expand) (simp add: fract_collapse)\nqed\n\nend\n\n\nsubsubsection \\<open>The ordered field of fractions over an ordered idom\\<close>\n\ninstantiation fract :: (linordered_idom) linorder\nbegin\n\nlemma less_eq_fract_respect:\n  fixes a b a' b' c d c' d' :: 'a\n  assumes neq: \"b \\<noteq> 0\"  \"b' \\<noteq> 0\"  \"d \\<noteq> 0\"  \"d' \\<noteq> 0\"\n  assumes eq1: \"a * b' = a' * b\"\n  assumes eq2: \"c * d' = c' * d\"\n  shows \"((a * d) * (b * d) \\<le> (c * b) * (b * d)) \\<longleftrightarrow> ((a' * d') * (b' * d') \\<le> (c' * b') * (b' * d'))\"\nproof -\n  let ?le = \"\\<lambda>a b c d. ((a * d) * (b * d) \\<le> (c * b) * (b * d))\"\n  {\n    fix a b c d x :: 'a\n    assume x: \"x \\<noteq> 0\"\n    have \"?le a b c d = ?le (a * x) (b * x) c d\"\n    proof -\n      from x have \"0 < x * x\"\n        by (auto simp add: zero_less_mult_iff)\n      then have \"?le a b c d =\n          ((a * d) * (b * d) * (x * x) \\<le> (c * b) * (b * d) * (x * x))\"\n        by (simp add: mult_le_cancel_right)\n      also have \"... = ?le (a * x) (b * x) c d\"\n        by (simp add: ac_simps)\n      finally show ?thesis .\n    qed\n  } note le_factor = this\n\n  let ?D = \"b * d\" and ?D' = \"b' * d'\"\n  from neq have D: \"?D \\<noteq> 0\" by simp\n  from neq have \"?D' \\<noteq> 0\" by simp\n  then have \"?le a b c d = ?le (a * ?D') (b * ?D') c d\"\n    by (rule le_factor)\n  also have \"... = ((a * b') * ?D * ?D' * d * d' \\<le> (c * d') * ?D * ?D' * b * b')\"\n    by (simp add: ac_simps)\n  also have \"... = ((a' * b) * ?D * ?D' * d * d' \\<le> (c' * d) * ?D * ?D' * b * b')\"\n    by (simp only: eq1 eq2)\n  also have \"... = ?le (a' * ?D) (b' * ?D) c' d'\"\n    by (simp add: ac_simps)\n  also from D have \"... = ?le a' b' c' d'\"\n    by (rule le_factor [symmetric])\n  finally show \"?le a b c d = ?le a' b' c' d'\" .\nqed\n\nlift_definition less_eq_fract :: \"'a fract \\<Rightarrow> 'a fract \\<Rightarrow> bool\"\n  is \"\\<lambda>q r. (fst q * snd r) * (snd q * snd r) \\<le> (fst r * snd q) * (snd q * snd r)\"\nby (clarsimp simp add: less_eq_fract_respect)\n\ndefinition less_fract_def: \"z < (w::'a fract) \\<longleftrightarrow> z \\<le> w \\<and> \\<not> w \\<le> z\"\n\nlemma le_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b \\<le> Fract c d \\<longleftrightarrow> (a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n  by transfer simp\n\nlemma less_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b < Fract c d \\<longleftrightarrow> (a * d) * (b * d) < (c * b) * (b * d)\"\n  by (simp add: less_fract_def less_le_not_le ac_simps)\n\ninstance\nproof\n  fix q r s :: \"'a fract\"\n  assume \"q \\<le> r\" and \"r \\<le> s\"\n  then show \"q \\<le> s\"\n  proof (induct q, induct r, induct s)\n    fix a b c d e f :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\" \"f \\<noteq> 0\"\n    assume 1: \"Fract a b \\<le> Fract c d\"\n    assume 2: \"Fract c d \\<le> Fract e f\"\n    show \"Fract a b \\<le> Fract e f\"\n    proof -\n      from neq obtain bb: \"0 < b * b\" and dd: \"0 < d * d\" and ff: \"0 < f * f\"\n        by (auto simp add: zero_less_mult_iff linorder_neq_iff)\n      have \"(a * d) * (b * d) * (f * f) \\<le> (c * b) * (b * d) * (f * f)\"\n      proof -\n        from neq 1 have \"(a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n          by simp\n        with ff show ?thesis by (simp add: mult_le_cancel_right)\n      qed\n      also have \"... = (c * f) * (d * f) * (b * b)\"\n        by (simp only: ac_simps)\n      also have \"... \\<le> (e * d) * (d * f) * (b * b)\"\n      proof -\n        from neq 2 have \"(c * f) * (d * f) \\<le> (e * d) * (d * f)\"\n          by simp\n        with bb show ?thesis by (simp add: mult_le_cancel_right)\n      qed\n      finally have \"(a * f) * (b * f) * (d * d) \\<le> e * b * (b * f) * (d * d)\"\n        by (simp only: ac_simps)\n      with dd have \"(a * f) * (b * f) \\<le> (e * b) * (b * f)\"\n        by (simp add: mult_le_cancel_right)\n      with neq show ?thesis by simp\n    qed\n  qed\nnext\n  fix q r :: \"'a fract\"\n  assume \"q \\<le> r\" and \"r \\<le> q\"\n  then show \"q = r\"\n  proof (induct q, induct r)\n    fix a b c d :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\"\n    assume 1: \"Fract a b \\<le> Fract c d\"\n    assume 2: \"Fract c d \\<le> Fract a b\"\n    show \"Fract a b = Fract c d\"\n    proof -\n      from neq 1 have \"(a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n        by simp\n      also have \"... \\<le> (a * d) * (b * d)\"\n      proof -\n        from neq 2 have \"(c * b) * (d * b) \\<le> (a * d) * (d * b)\"\n          by simp\n        then show ?thesis by (simp only: ac_simps)\n      qed\n      finally have \"(a * d) * (b * d) = (c * b) * (b * d)\" .\n      moreover from neq have \"b * d \\<noteq> 0\" by simp\n      ultimately have \"a * d = c * b\" by simp\n      with neq show ?thesis by (simp add: eq_fract)\n    qed\n  qed\nnext\n  fix q r :: \"'a fract\"\n  show \"q \\<le> q\"\n    by (induct q) simp\n  show \"(q < r) = (q \\<le> r \\<and> \\<not> r \\<le> q)\"\n    by (simp only: less_fract_def)\n  show \"q \\<le> r \\<or> r \\<le> q\"\n    by (induct q, induct r)\n       (simp add: mult.commute, rule linorder_linear)\nqed\n\nend\n\ninstantiation fract :: (linordered_idom) linordered_field\nbegin\n\ndefinition abs_fract_def2:\n  \"\\<bar>q\\<bar> = (if q < 0 then -q else (q::'a fract))\"\n\ndefinition sgn_fract_def:\n  \"sgn (q::'a fract) = (if q = 0 then 0 else if 0 < q then 1 else - 1)\"\n\ntheorem abs_fract [simp]: \"\\<bar>Fract a b\\<bar> = Fract \\<bar>a\\<bar> \\<bar>b\\<bar>\"\n  unfolding abs_fract_def2 not_le [symmetric]\n  by transfer (auto simp add: zero_less_mult_iff le_less)\n\ninstance proof\n  fix q r s :: \"'a fract\"\n  assume \"q \\<le> r\"\n  then show \"s + q \\<le> s + r\"\n  proof (induct q, induct r, induct s)\n    fix a b c d e f :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\" \"f \\<noteq> 0\"\n    assume le: \"Fract a b \\<le> Fract c d\"\n    show \"Fract e f + Fract a b \\<le> Fract e f + Fract c d\"\n    proof -\n      let ?F = \"f * f\" from neq have F: \"0 < ?F\"\n        by (auto simp add: zero_less_mult_iff)\n      from neq le have \"(a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n        by simp\n      with F have \"(a * d) * (b * d) * ?F * ?F \\<le> (c * b) * (b * d) * ?F * ?F\"\n        by (simp add: mult_le_cancel_right)\n      with neq show ?thesis by (simp add: field_simps)\n    qed\n  qed\nnext\n  fix q r s :: \"'a fract\"\n  assume \"q < r\" and \"0 < s\"\n  then show \"s * q < s * r\"\n  proof (induct q, induct r, induct s)\n    fix a b c d e f :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\" \"f \\<noteq> 0\"\n    assume le: \"Fract a b < Fract c d\"\n    assume gt: \"0 < Fract e f\"\n    show \"Fract e f * Fract a b < Fract e f * Fract c d\"\n    proof -\n      let ?E = \"e * f\" and ?F = \"f * f\"\n      from neq gt have \"0 < ?E\"\n        by (auto simp add: Zero_fract_def order_less_le eq_fract)\n      moreover from neq have \"0 < ?F\"\n        by (auto simp add: zero_less_mult_iff)\n      moreover from neq le have \"(a * d) * (b * d) < (c * b) * (b * d)\"\n        by simp\n      ultimately have \"(a * d) * (b * d) * ?E * ?F < (c * b) * (b * d) * ?E * ?F\"\n        by (simp add: mult_less_cancel_right)\n      with neq show ?thesis\n        by (simp add: ac_simps)\n    qed\n  qed\nqed (fact sgn_fract_def abs_fract_def2)+\n\nend\n\ninstantiation fract :: (linordered_idom) distrib_lattice\nbegin\n\ndefinition inf_fract_def:\n  \"(inf :: 'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract) = min\"\n\ndefinition sup_fract_def:\n  \"(sup :: 'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract) = max\"\n\ninstance\n  by standard (simp_all add: inf_fract_def sup_fract_def max_min_distrib2)\n  \nend\n\nlemma fract_induct_pos [case_names Fract]:\n  fixes P :: \"'a::linordered_idom fract \\<Rightarrow> bool\"\n  assumes step: \"\\<And>a b. 0 < b \\<Longrightarrow> P (Fract a b)\"\n  shows \"P q\"\nproof (cases q)\n  case (Fract a b)\n  {\n    fix a b :: 'a\n    assume b: \"b < 0\"\n    have \"P (Fract a b)\"\n    proof -\n      from b have \"0 < - b\" by simp\n      then have \"P (Fract (- a) (- b))\"\n        by (rule step)\n      then show \"P (Fract a b)\"\n        by (simp add: order_less_imp_not_eq [OF b])\n    qed\n  }\n  with Fract show \"P q\"\n    by (auto simp add: linorder_neq_iff step)\nqed\n\nlemma zero_less_Fract_iff: \"0 < b \\<Longrightarrow> 0 < Fract a b \\<longleftrightarrow> 0 < a\"\n  by (auto simp add: Zero_fract_def zero_less_mult_iff)\n\nlemma Fract_less_zero_iff: \"0 < b \\<Longrightarrow> Fract a b < 0 \\<longleftrightarrow> a < 0\"\n  by (auto simp add: Zero_fract_def mult_less_0_iff)\n\nlemma zero_le_Fract_iff: \"0 < b \\<Longrightarrow> 0 \\<le> Fract a b \\<longleftrightarrow> 0 \\<le> a\"\n  by (auto simp add: Zero_fract_def zero_le_mult_iff)\n\nlemma Fract_le_zero_iff: \"0 < b \\<Longrightarrow> Fract a b \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (auto simp add: Zero_fract_def mult_le_0_iff)\n\nlemma one_less_Fract_iff: \"0 < b \\<Longrightarrow> 1 < Fract a b \\<longleftrightarrow> b < a\"\n  by (auto simp add: One_fract_def mult_less_cancel_right_disj)\n\nlemma Fract_less_one_iff: \"0 < b \\<Longrightarrow> Fract a b < 1 \\<longleftrightarrow> a < b\"\n  by (auto simp add: One_fract_def mult_less_cancel_right_disj)\n\nlemma one_le_Fract_iff: \"0 < b \\<Longrightarrow> 1 \\<le> Fract a b \\<longleftrightarrow> b \\<le> a\"\n  by (auto simp add: One_fract_def mult_le_cancel_right)\n\nlemma Fract_le_one_iff: \"0 < b \\<Longrightarrow> Fract a b \\<le> 1 \\<longleftrightarrow> a \\<le> b\"\n  by (auto simp add: One_fract_def mult_le_cancel_right)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Computational_Algebra/Fraction_Field.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7683292961920345}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Sorting\"\n\ntheory Sorting\nimports\n  Complex_Main\n  \"HOL-Library.Multiset\"\nbegin\n\nhide_const List.insort\n\ndeclare Let_def [simp]\n\n\nsubsection \"Insertion Sort\"\n\nfun insort :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"insort x [] = [x]\" |\n\"insort x (y#ys) =\n  (if x \\<le> y then x#y#ys else y#(insort x ys))\"\n\nfun isort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"isort [] = []\" |\n\"isort (x#xs) = insort x (isort xs)\"\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_insort: \"mset (insort x xs) = add_mset x (mset xs)\"\napply(induction xs)\napply auto\ndone\n\nlemma mset_isort: \"mset (isort xs) = mset xs\"\napply(induction xs)\napply simp\napply (simp add: mset_insort)\ndone\n\nlemma set_insort: \"set (insort x xs) = insert x (set xs)\"\nby (metis mset_insort set_mset_add_mset_insert set_mset_mset)\n\nlemma sorted_insort: \"sorted (insort a xs) = sorted xs\"\napply(induction xs)\napply(auto simp add: set_insort)\ndone\n\nlemma sorted_isort: \"sorted (isort xs)\"\napply(induction xs)\napply(auto simp: sorted_insort)\ndone\n\n\nsubsubsection \"Time Complexity\"\n\ntext \\<open>We count the number of function calls.\\<close>\n\ntext\\<open>\n\\<open>insort x [] = [x]\\<close>\n\\<open>insort x (y#ys) =\n  (if x \\<le> y then x#y#ys else y#(insort x ys))\\<close>\n\\<close>\nfun t_insort :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"t_insort x [] = 1\" |\n\"t_insort x (y#ys) =\n  (if x \\<le> y then 0 else t_insort x ys) + 1\"\n\ntext\\<open>\n\\<open>isort [] = []\\<close>\n\\<open>isort (x#xs) = insort x (isort xs)\\<close>\n\\<close>\nfun t_isort :: \"'a::linorder list \\<Rightarrow> nat\" where\n\"t_isort [] = 1\" |\n\"t_isort (x#xs) = t_isort xs + t_insort x (isort xs) + 1\"\n\n\nlemma t_insort_length: \"t_insort x xs \\<le> length xs + 1\"\napply(induction xs)\napply auto\ndone\n\nlemma length_insort: \"length (insort x xs) = length xs + 1\"\napply(induction xs)\napply auto\ndone\n\nlemma length_isort: \"length (isort xs) = length xs\"\napply(induction xs)\napply (auto simp: length_insort)\ndone\n\nlemma t_isort_length: \"t_isort xs \\<le> (length xs + 1) ^ 2\"\nproof(induction xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  have \"t_isort (x#xs) = t_isort xs + t_insort x (isort xs) + 1\" by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + t_insort x (isort xs) + 1\"\n    using Cons.IH by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + length xs + 1 + 1\"\n    using t_insort_length[of x \"isort xs\"] by (simp add: length_isort)\n  also have \"\\<dots> \\<le> (length(x#xs) + 1) ^ 2\"\n    by (simp add: power2_eq_square)\n  finally show ?case .\nqed\n\n\nsubsection \"Merge Sort\"\n\nfun merge :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"merge [] ys = ys\" |\n\"merge xs [] = xs\" |\n\"merge (x#xs) (y#ys) = (if x \\<le> y then x # merge xs (y#ys) else y # merge (x#xs) ys)\"\n\nfun msort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"msort xs = (let n = length xs in\n  if n \\<le> 1 then xs\n  else merge (msort (take (n div 2) xs)) (msort (drop (n div 2) xs)))\"\n\ndeclare msort.simps [simp del]\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_merge: \"mset(merge xs ys) = mset xs + mset ys\"\nby(induction xs ys rule: merge.induct) auto\n\nlemma mset_msort: \"mset (msort xs) = mset xs\"\nproof(induction xs rule: msort.induct)\n  case (1 xs)\n  let ?n = \"length xs\"\n  let ?ys = \"take (?n div 2) xs\"\n  let ?zs = \"drop (?n div 2) xs\"\n  show ?case\n  proof cases\n    assume \"?n \\<le> 1\"\n    thus ?thesis by(simp add: msort.simps[of xs])\n  next\n    assume \"\\<not> ?n \\<le> 1\"\n    hence \"mset (msort xs) = mset (msort ?ys) + mset (msort ?zs)\"\n      by(simp add: msort.simps[of xs] mset_merge)\n    also have \"\\<dots> = mset ?ys + mset ?zs\"\n      using \\<open>\\<not> ?n \\<le> 1\\<close> by(simp add: \"1.IH\")\n    also have \"\\<dots> = mset (?ys @ ?zs)\" by (simp del: append_take_drop_id)\n    also have \"\\<dots> = mset xs\" by simp\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>Via the previous lemma or directly:\\<close>\n\nlemma set_merge: \"set(merge xs ys) = set xs \\<union> set ys\"\nby (metis mset_merge set_mset_mset set_mset_union)\n\nlemma \"set(merge xs ys) = set xs \\<union> set ys\"\nby(induction xs ys rule: merge.induct) (auto)\n\nlemma sorted_merge: \"sorted (merge xs ys) \\<longleftrightarrow> (sorted xs \\<and> sorted ys)\"\nby(induction xs ys rule: merge.induct) (auto simp: set_merge)\n\nlemma sorted_msort: \"sorted (msort xs)\"\nproof(induction xs rule: msort.induct)\n  case (1 xs)\n  let ?n = \"length xs\"\n  show ?case\n  proof cases\n    assume \"?n \\<le> 1\"\n    thus ?thesis by(simp add: msort.simps[of xs] sorted01)\n  next\n    assume \"\\<not> ?n \\<le> 1\"\n    thus ?thesis using \"1.IH\"\n      by(simp add: sorted_merge msort.simps[of xs])\n  qed\nqed\n\n\nsubsubsection \"Time Complexity\"\n\ntext \\<open>We only count the number of comparisons between list elements.\\<close>\n\nfun c_merge :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"c_merge [] ys = 0\" |\n\"c_merge xs [] = 0\" |\n\"c_merge (x#xs) (y#ys) = 1 + (if x \\<le> y then c_merge xs (y#ys) else c_merge (x#xs) ys)\"\n\nlemma c_merge_ub: \"c_merge xs ys \\<le> length xs + length ys\"\nby (induction xs ys rule: c_merge.induct) auto\n\nfun c_msort :: \"'a::linorder list \\<Rightarrow> nat\" where\n\"c_msort xs =\n  (let n = length xs;\n       ys = take (n div 2) xs;\n       zs = drop (n div 2) xs\n   in if n \\<le> 1 then 0\n      else c_msort ys + c_msort zs + c_merge (msort ys) (msort zs))\"\n\ndeclare c_msort.simps [simp del]\n\nlemma length_merge: \"length(merge xs ys) = length xs + length ys\"\napply (induction xs ys rule: merge.induct)\napply auto\ndone\n\nlemma length_msort: \"length(msort xs) = length xs\"\nproof (induction xs rule: msort.induct)\n  case (1 xs)\n  thus ?case by (auto simp: msort.simps[of xs] length_merge)\nqed\ntext \\<open>Why structured proof?\n   To have the name \"xs\" to specialize msort.simps with xs\n   to ensure that msort.simps cannot be used recursively.\nAlso works without this precaution, but that is just luck.\\<close>\n\nlemma c_msort_le: \"length xs = 2^k \\<Longrightarrow> c_msort xs \\<le> k * 2^k\"\nproof(induction k arbitrary: xs)\n  case 0 thus ?case by (simp add: c_msort.simps)\nnext\n  case (Suc k)\n  let ?n = \"length xs\"\n  let ?ys = \"take (?n div 2) xs\"\n  let ?zs = \"drop (?n div 2) xs\"\n  show ?case\n  proof (cases \"?n \\<le> 1\")\n    case True\n    thus ?thesis by(simp add: c_msort.simps)\n  next\n    case False\n    have \"c_msort(xs) =\n      c_msort ?ys + c_msort ?zs + c_merge (msort ?ys) (msort ?zs)\"\n      by (simp add: c_msort.simps msort.simps)\n    also have \"\\<dots> \\<le> c_msort ?ys + c_msort ?zs + length ?ys + length ?zs\"\n      using c_merge_ub[of \"msort ?ys\" \"msort ?zs\"] length_msort[of ?ys] length_msort[of ?zs]\n      by arith\n    also have \"\\<dots> \\<le> k * 2^k + c_msort ?zs + length ?ys + length ?zs\"\n      using Suc.IH[of ?ys] Suc.prems by simp\n    also have \"\\<dots> \\<le> k * 2^k + k * 2^k + length ?ys + length ?zs\"\n      using Suc.IH[of ?zs] Suc.prems by simp\n    also have \"\\<dots> = 2 * k * 2^k + 2 * 2 ^ k\"\n      using Suc.prems by simp\n    finally show ?thesis by simp\n  qed\nqed\n\n(* Beware of implicit conversions: *)\nlemma c_msort_log: \"length xs = 2^k \\<Longrightarrow> c_msort xs \\<le> length xs * log 2 (length xs)\"\nusing c_msort_le[of xs k] apply (simp add: log_nat_power algebra_simps)\nby (metis (mono_tags) numeral_power_eq_of_nat_cancel_iff of_nat_le_iff of_nat_mult)\n\n\nsubsection \"Bottom-Up Merge Sort\"\n\nfun merge_adj :: \"('a::linorder) list list \\<Rightarrow> 'a list list\" where\n\"merge_adj [] = []\" |\n\"merge_adj [xs] = [xs]\" |\n\"merge_adj (xs # ys # zss) = merge xs ys # merge_adj zss\"\n\ntext \\<open>For the termination proof of \\<open>merge_all\\<close> below.\\<close>\nlemma length_merge_adjacent[simp]: \"length (merge_adj xs) = (length xs + 1) div 2\"\nby (induction xs rule: merge_adj.induct) auto\n\nfun merge_all :: \"('a::linorder) list list \\<Rightarrow> 'a list\" where\n\"merge_all [] = []\" |\n\"merge_all [xs] = xs\" |\n\"merge_all xss = merge_all (merge_adj xss)\"\n\ndefinition msort_bu :: \"('a::linorder) list \\<Rightarrow> 'a list\" where\n\"msort_bu xs = merge_all (map (\\<lambda>x. [x]) xs)\"\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_merge_adj:\n  \"\\<Union># (image_mset mset (mset (merge_adj xss))) = \\<Union># (image_mset mset (mset xss))\"\nby(induction xss rule: merge_adj.induct) (auto simp: mset_merge)\n\nlemma mset_merge_all:\n  \"mset (merge_all xss) = (\\<Union># (mset (map mset xss)))\"\nby(induction xss rule: merge_all.induct) (auto simp: mset_merge mset_merge_adj)\n\nlemma mset_msort_bu: \"mset (msort_bu xs) = mset xs\"\nby(simp add: msort_bu_def mset_merge_all comp_def)\n\nlemma sorted_merge_adj:\n  \"\\<forall>xs \\<in> set xss. sorted xs \\<Longrightarrow> \\<forall>xs \\<in> set (merge_adj xss). sorted xs\"\nby(induction xss rule: merge_adj.induct) (auto simp: sorted_merge)\n\nlemma sorted_merge_all:\n  \"\\<forall>xs \\<in> set xss. sorted xs \\<Longrightarrow> sorted (merge_all xss)\"\napply(induction xss rule: merge_all.induct)\nusing [[simp_depth_limit=3]] by (auto simp add: sorted_merge_adj)\n\nlemma sorted_msort_bu: \"sorted (msort_bu xs)\"\nby(simp add: msort_bu_def sorted_merge_all)\n\n\nsubsubsection \"Time Complexity\"\n\nfun c_merge_adj :: \"('a::linorder) list list \\<Rightarrow> nat\" where\n\"c_merge_adj [] = 0\" |\n\"c_merge_adj [xs] = 0\" |\n\"c_merge_adj (xs # ys # zss) = c_merge xs ys + c_merge_adj zss\"\n\nfun c_merge_all :: \"('a::linorder) list list \\<Rightarrow> nat\" where\n\"c_merge_all [] = 0\" |\n\"c_merge_all [xs] = 0\" |\n\"c_merge_all xss = c_merge_adj xss + c_merge_all (merge_adj xss)\"\n\ndefinition c_msort_bu :: \"('a::linorder) list \\<Rightarrow> nat\" where\n\"c_msort_bu xs = c_merge_all (map (\\<lambda>x. [x]) xs)\"\n\nlemma length_merge_adj:\n  \"\\<lbrakk> even(length xss); \\<forall>xs \\<in> set xss. length xs = m \\<rbrakk>\n  \\<Longrightarrow> \\<forall>xs \\<in> set (merge_adj xss). length xs = 2*m\"\nby(induction xss rule: merge_adj.induct) (auto simp: length_merge)\n\nlemma c_merge_adj: \"\\<forall>xs \\<in> set xss. length xs = m \\<Longrightarrow> c_merge_adj xss \\<le> m * length xss\"\nproof(induction xss rule: c_merge_adj.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 x y) thus ?case using c_merge_ub[of x y] by (simp add: algebra_simps)\nqed\n\nlemma c_merge_all: \"\\<lbrakk> \\<forall>xs \\<in> set xss. length xs = m; length xss = 2^k \\<rbrakk>\n  \\<Longrightarrow> c_merge_all xss \\<le> m * k * 2^k\"\nproof (induction xss arbitrary: k m rule: c_merge_all.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 xs ys xss)\n  let ?xss = \"xs # ys # xss\"\n  let ?xss2 = \"merge_adj ?xss\"\n  obtain k' where k': \"k = Suc k'\" using \"3.prems\"(2)\n    by (metis length_Cons nat.inject nat_power_eq_Suc_0_iff nat.exhaust)\n  have \"even (length ?xss)\" using \"3.prems\"(2) k' by auto\n  from length_merge_adj[OF this \"3.prems\"(1)]\n  have *: \"\\<forall>x \\<in> set(merge_adj ?xss). length x = 2*m\" .\n  have **: \"length ?xss2 = 2 ^ k'\" using \"3.prems\"(2) k' by auto\n  have \"c_merge_all ?xss = c_merge_adj ?xss + c_merge_all ?xss2\" by simp\n  also have \"\\<dots> \\<le> m * 2^k + c_merge_all ?xss2\"\n    using \"3.prems\"(2) c_merge_adj[OF \"3.prems\"(1)] by (auto simp: algebra_simps)\n  also have \"\\<dots> \\<le> m * 2^k + (2*m) * k' * 2^k'\"\n    using \"3.IH\"[OF * **] by simp\n  also have \"\\<dots> = m * k * 2^k\"\n    using k' by (simp add: algebra_simps)\n  finally show ?case .\nqed\n\ncorollary c_msort_bu: \"length xs = 2 ^ k \\<Longrightarrow> c_msort_bu xs \\<le> k * 2 ^ k\"\nusing c_merge_all[of \"map (\\<lambda>x. [x]) xs\" 1] by (simp add: c_msort_bu_def)\n\n\nsubsection \"Quicksort\"\n\nfun quicksort :: \"('a::linorder) list \\<Rightarrow> 'a list\" where\n\"quicksort []     = []\" |\n\"quicksort (x#xs) = quicksort (filter (\\<lambda>y. y < x) xs) @ [x] @ quicksort (filter (\\<lambda>y. x \\<le> y) xs)\"\n\nlemma mset_quicksort: \"mset (quicksort xs) = mset xs\"\napply (induction xs rule: quicksort.induct)\napply (auto simp: not_le)\ndone\n\nlemma set_quicksort: \"set (quicksort xs) = set xs\"\nby(rule mset_eq_setD[OF mset_quicksort])\n\nlemma sorted_quicksort: \"sorted (quicksort xs)\"\napply (induction xs rule: quicksort.induct)\napply (auto simp add: sorted_append set_quicksort)\ndone\n\n\nsubsection \"Insertion Sort w.r.t. Keys and Stability\"\n\ntext \\<open>Note that \\<^const>\\<open>insort_key\\<close> is already defined in theory \\<^theory>\\<open>HOL.List\\<close>.\nThus some of the lemmas are already present as well.\\<close>\n\nfun isort_key :: \"('a \\<Rightarrow> 'k::linorder) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"isort_key f [] = []\" |\n\"isort_key f (x # xs) = insort_key f x (isort_key f xs)\"\n\n\nsubsubsection \"Standard functional correctness\"\n\nlemma mset_insort_key: \"mset (insort_key f x xs) = add_mset x (mset xs)\"\nby(induction xs) simp_all\n\nlemma mset_isort_key: \"mset (isort_key f xs) = mset xs\"\nby(induction xs) (simp_all add: mset_insort_key)\n\nlemma set_isort_key: \"set (isort_key f xs) = set xs\"\nby (rule mset_eq_setD[OF mset_isort_key])\n\nlemma sorted_insort_key: \"sorted (map f (insort_key f a xs)) = sorted (map f xs)\"\nby(induction xs)(auto simp: set_insort_key)\n\nlemma sorted_isort_key: \"sorted (map f (isort_key f xs))\"\nby(induction xs)(simp_all add: sorted_insort_key)\n\n\nsubsubsection \"Stability\"\n\nlemma insort_is_Cons: \"\\<forall>x\\<in>set xs. f a \\<le> f x \\<Longrightarrow> insort_key f a xs = a # xs\"\nby (cases xs) auto\n\nlemma filter_insort_key_neg:\n  \"\\<not> P x \\<Longrightarrow> filter P (insort_key f x xs) = filter P xs\"\nby (induction xs) simp_all\n\nlemma filter_insort_key_pos:\n  \"sorted (map f xs) \\<Longrightarrow> P x \\<Longrightarrow> filter P (insort_key f x xs) = insort_key f x (filter P xs)\"\nby (induction xs) (auto, subst insort_is_Cons, auto)\n\nlemma sort_key_stable: \"filter (\\<lambda>y. f y = k) (isort_key f xs) = filter (\\<lambda>y. f y = k) xs\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\n  thus ?case\n  proof (cases \"f a = k\")\n    case False thus ?thesis  by (simp add: Cons.IH filter_insort_key_neg)\n  next\n    case True\n    have \"filter (\\<lambda>y. f y = k) (isort_key f (a # xs))\n      = filter (\\<lambda>y. f y = k) (insort_key f a (isort_key f xs))\"  by simp\n    also have \"\\<dots> = insort_key f a (filter (\\<lambda>y. f y = k) (isort_key f xs))\"\n      by (simp add: True filter_insort_key_pos sorted_isort_key)\n    also have \"\\<dots> = insort_key f a (filter (\\<lambda>y. f y = k) xs)\"  by (simp add: Cons.IH)\n    also have \"\\<dots> = a # (filter (\\<lambda>y. f y = k) xs)\"  by(simp add: True insort_is_Cons)\n    also have \"\\<dots> = filter (\\<lambda>y. f y = k) (a # xs)\" by (simp add: True)\n    finally show ?thesis .\n  qed\nqed\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Data_Structures/Sorting.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8918110396870288, "lm_q1q2_score": 0.7683292957942858}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Sorting\"\n\ntheory Sorting\nimports\n  Complex_Main\n  \"HOL-Library.Multiset\"\nbegin\n\nhide_const List.insort\n\ndeclare Let_def [simp]\n\n\nsubsection \"Insertion Sort\"\n\nfun insort :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"insort x [] = [x]\" |\n\"insort x (y#ys) =\n  (if x \\<le> y then x#y#ys else y#(insort x ys))\"\n\nfun isort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"isort [] = []\" |\n\"isort (x#xs) = insort x (isort xs)\"\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_insort: \"mset (insort x xs) = {#x#} + mset xs\"\napply(induction xs)\napply auto\ndone\n\nlemma mset_isort: \"mset (isort xs) = mset xs\"\napply(induction xs)\napply simp\napply (simp add: mset_insort)\ndone\n\nlemma set_insort: \"set (insort x xs) = {x} \\<union> set xs\"\nby(simp add: mset_insort flip: set_mset_mset)\n\nlemma sorted_insort: \"sorted (insort a xs) = sorted xs\"\napply(induction xs)\napply(auto simp add: set_insort)\ndone\n\nlemma sorted_isort: \"sorted (isort xs)\"\napply(induction xs)\napply(auto simp: sorted_insort)\ndone\n\n\nsubsubsection \"Time Complexity\"\n\ntext \\<open>We count the number of function calls.\\<close>\n\ntext\\<open>\n\\<open>insort x [] = [x]\\<close>\n\\<open>insort x (y#ys) =\n  (if x \\<le> y then x#y#ys else y#(insort x ys))\\<close>\n\\<close>\nfun T_insort :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"T_insort x [] = 1\" |\n\"T_insort x (y#ys) =\n  (if x \\<le> y then 0 else T_insort x ys) + 1\"\n\ntext\\<open>\n\\<open>isort [] = []\\<close>\n\\<open>isort (x#xs) = insort x (isort xs)\\<close>\n\\<close>\nfun T_isort :: \"'a::linorder list \\<Rightarrow> nat\" where\n\"T_isort [] = 1\" |\n\"T_isort (x#xs) = T_isort xs + T_insort x (isort xs) + 1\"\n\n\nlemma T_insort_length: \"T_insort x xs \\<le> length xs + 1\"\napply(induction xs)\napply auto\ndone\n\nlemma length_insort: \"length (insort x xs) = length xs + 1\"\napply(induction xs)\napply auto\ndone\n\nlemma length_isort: \"length (isort xs) = length xs\"\napply(induction xs)\napply (auto simp: length_insort)\ndone\n\nlemma T_isort_length: \"T_isort xs \\<le> (length xs + 1) ^ 2\"\nproof(induction xs)\n  case Nil show ?case by simp\nnext\n  case (Cons x xs)\n  have \"T_isort (x#xs) = T_isort xs + T_insort x (isort xs) + 1\" by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + T_insort x (isort xs) + 1\"\n    using Cons.IH by simp\n  also have \"\\<dots> \\<le> (length xs + 1) ^ 2 + length xs + 1 + 1\"\n    using T_insort_length[of x \"isort xs\"] by (simp add: length_isort)\n  also have \"\\<dots> \\<le> (length(x#xs) + 1) ^ 2\"\n    by (simp add: power2_eq_square)\n  finally show ?case .\nqed\n\n\nsubsection \"Merge Sort\"\n\nfun merge :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"merge [] ys = ys\" |\n\"merge xs [] = xs\" |\n\"merge (x#xs) (y#ys) = (if x \\<le> y then x # merge xs (y#ys) else y # merge (x#xs) ys)\"\n\nfun msort :: \"'a::linorder list \\<Rightarrow> 'a list\" where\n\"msort xs = (let n = length xs in\n  if n \\<le> 1 then xs\n  else merge (msort (take (n div 2) xs)) (msort (drop (n div 2) xs)))\"\n\ndeclare msort.simps [simp del]\n\n\nsubsubsection \"Functional Correctness\"\n\nlemma mset_merge: \"mset(merge xs ys) = mset xs + mset ys\"\nby(induction xs ys rule: merge.induct) auto\n\nlemma mset_msort: \"mset (msort xs) = mset xs\"\nproof(induction xs rule: msort.induct)\n  case (1 xs)\n  let ?n = \"length xs\"\n  let ?ys = \"take (?n div 2) xs\"\n  let ?zs = \"drop (?n div 2) xs\"\n  show ?case\n  proof cases\n    assume \"?n \\<le> 1\"\n    thus ?thesis by(simp add: msort.simps[of xs])\n  next\n    assume \"\\<not> ?n \\<le> 1\"\n    hence \"mset (msort xs) = mset (msort ?ys) + mset (msort ?zs)\"\n      by(simp add: msort.simps[of xs] mset_merge)\n    also have \"\\<dots> = mset ?ys + mset ?zs\"\n      using \\<open>\\<not> ?n \\<le> 1\\<close> by(simp add: \"1.IH\")\n    also have \"\\<dots> = mset (?ys @ ?zs)\" by (simp del: append_take_drop_id)\n    also have \"\\<dots> = mset xs\" by simp\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>Via the previous lemma or directly:\\<close>\n\nlemma set_merge: \"set(merge xs ys) = set xs \\<union> set ys\"\nby (metis mset_merge set_mset_mset set_mset_union)\n\nlemma \"set(merge xs ys) = set xs \\<union> set ys\"\nby(induction xs ys rule: merge.induct) (auto)\n\nlemma sorted_merge: \"sorted (merge xs ys) \\<longleftrightarrow> (sorted xs \\<and> sorted ys)\"\nby(induction xs ys rule: merge.induct) (auto simp: set_merge)\n\nlemma sorted_msort: \"sorted (msort xs)\"\nproof(induction xs rule: msort.induct)\n  case (1 xs)\n  let ?n = \"length xs\"\n  show ?case\n  proof cases\n    assume \"?n \\<le> 1\"\n    thus ?thesis by(simp add: msort.simps[of xs] sorted01)\n  next\n    assume \"\\<not> ?n \\<le> 1\"\n    thus ?thesis using \"1.IH\"\n      by(simp add: sorted_merge msort.simps[of xs])\n  qed\nqed\n\n\nsubsubsection \"Time Complexity\"\n\ntext \\<open>We only count the number of comparisons between list elements.\\<close>\n\nfun C_merge :: \"'a::linorder list \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"C_merge [] ys = 0\" |\n\"C_merge xs [] = 0\" |\n\"C_merge (x#xs) (y#ys) = 1 + (if x \\<le> y then C_merge xs (y#ys) else C_merge (x#xs) ys)\"\n\nlemma C_merge_ub: \"C_merge xs ys \\<le> length xs + length ys\"\nby (induction xs ys rule: C_merge.induct) auto\n\nfun C_msort :: \"'a::linorder list \\<Rightarrow> nat\" where\n\"C_msort xs =\n  (let n = length xs;\n       ys = take (n div 2) xs;\n       zs = drop (n div 2) xs\n   in if n \\<le> 1 then 0\n      else C_msort ys + C_msort zs + C_merge (msort ys) (msort zs))\"\n\ndeclare C_msort.simps [simp del]\n\nlemma length_merge: \"length(merge xs ys) = length xs + length ys\"\napply (induction xs ys rule: merge.induct)\napply auto\ndone\n\nlemma length_msort: \"length(msort xs) = length xs\"\nproof (induction xs rule: msort.induct)\n  case (1 xs)\n  show ?case\n    by (auto simp: msort.simps [of xs] 1 length_merge)\nqed\ntext \\<open>Why structured proof?\n   To have the name \"xs\" to specialize msort.simps with xs\n   to ensure that msort.simps cannot be used recursively.\nAlso works without this precaution, but that is just luck.\\<close>\n\nlemma C_msort_le: \"length xs = 2^k \\<Longrightarrow> C_msort xs \\<le> k * 2^k\"\nproof(induction k arbitrary: xs)\n  case 0 thus ?case by (simp add: C_msort.simps)\nnext\n  case (Suc k)\n  let ?n = \"length xs\"\n  let ?ys = \"take (?n div 2) xs\"\n  let ?zs = \"drop (?n div 2) xs\"\n  show ?case\n  proof (cases \"?n \\<le> 1\")\n    case True\n    thus ?thesis by(simp add: C_msort.simps)\n  next\n    case False\n    have \"C_msort(xs) =\n      C_msort ?ys + C_msort ?zs + C_merge (msort ?ys) (msort ?zs)\"\n      by (simp add: C_msort.simps msort.simps)\n    also have \"\\<dots> \\<le> C_msort ?ys + C_msort ?zs + length ?ys + length ?zs\"\n      using C_merge_ub[of \"msort ?ys\" \"msort ?zs\"] length_msort[of ?ys] length_msort[of ?zs]\n      by arith\n    also have \"\\<dots> \\<le> k * 2^k + C_msort ?zs + length ?ys + length ?zs\"\n      using Suc.IH[of ?ys] Suc.prems by simp\n    also have \"\\<dots> \\<le> k * 2^k + k * 2^k + length ?ys + length ?zs\"\n      using Suc.IH[of ?zs] Suc.prems by simp\n    also have \"\\<dots> = 2 * k * 2^k + 2 * 2 ^ k\"\n      using Suc.prems by simp\n    finally show ?thesis by simp\n  qed\nqed\n\n(* Beware of implicit conversions: *)\nlemma C_msort_log: \"length xs = 2^k \\<Longrightarrow> C_msort xs \\<le> length xs * log 2 (length xs)\"\nusing C_msort_le[of xs k] apply (simp add: log_nat_power algebra_simps)\nby (metis (mono_tags) numeral_power_eq_of_nat_cancel_iff of_nat_le_iff of_nat_mult)\n\n\nsubsection \"Bottom-Up Merge Sort\"\n\nfun merge_adj :: \"('a::linorder) list list \\<Rightarrow> 'a list list\" where\n\"merge_adj [] = []\" |\n\"merge_adj [xs] = [xs]\" |\n\"merge_adj (xs # ys # zss) = merge xs ys # merge_adj zss\"\n\ntext \\<open>For the termination proof of \\<open>merge_all\\<close> below.\\<close>\nlemma length_merge_adjacent[simp]: \"length (merge_adj xs) = (length xs + 1) div 2\"\nby (induction xs rule: merge_adj.induct) auto\n\nfun merge_all :: \"('a::linorder) list list \\<Rightarrow> 'a list\" where\n\"merge_all [] = []\" |\n\"merge_all [xs] = xs\" |\n\"merge_all xss = merge_all (merge_adj xss)\"\n\ndefinition msort_bu :: \"('a::linorder) list \\<Rightarrow> 'a list\" where\n\"msort_bu xs = merge_all (map (\\<lambda>x. [x]) xs)\"\n\n\nsubsubsection \"Functional Correctness\"\n\nabbreviation mset_mset :: \"'a list list \\<Rightarrow> 'a multiset\" where\n\"mset_mset xss \\<equiv> \\<Sum>\\<^sub># (image_mset mset (mset xss))\"\n\nlemma mset_merge_adj:\n  \"mset_mset (merge_adj xss) = mset_mset xss\"\nby(induction xss rule: merge_adj.induct) (auto simp: mset_merge)\n\nlemma mset_merge_all:\n  \"mset (merge_all xss) = mset_mset xss\"\nby(induction xss rule: merge_all.induct) (auto simp: mset_merge mset_merge_adj)\n\nlemma mset_msort_bu: \"mset (msort_bu xs) = mset xs\"\nby(simp add: msort_bu_def mset_merge_all multiset.map_comp comp_def)\n\nlemma sorted_merge_adj:\n  \"\\<forall>xs \\<in> set xss. sorted xs \\<Longrightarrow> \\<forall>xs \\<in> set (merge_adj xss). sorted xs\"\nby(induction xss rule: merge_adj.induct) (auto simp: sorted_merge)\n\nlemma sorted_merge_all:\n  \"\\<forall>xs \\<in> set xss. sorted xs \\<Longrightarrow> sorted (merge_all xss)\"\napply(induction xss rule: merge_all.induct)\nusing [[simp_depth_limit=3]] by (auto simp add: sorted_merge_adj)\n\nlemma sorted_msort_bu: \"sorted (msort_bu xs)\"\nby(simp add: msort_bu_def sorted_merge_all)\n\n\nsubsubsection \"Time Complexity\"\n\nfun C_merge_adj :: \"('a::linorder) list list \\<Rightarrow> nat\" where\n\"C_merge_adj [] = 0\" |\n\"C_merge_adj [xs] = 0\" |\n\"C_merge_adj (xs # ys # zss) = C_merge xs ys + C_merge_adj zss\"\n\nfun C_merge_all :: \"('a::linorder) list list \\<Rightarrow> nat\" where\n\"C_merge_all [] = 0\" |\n\"C_merge_all [xs] = 0\" |\n\"C_merge_all xss = C_merge_adj xss + C_merge_all (merge_adj xss)\"\n\ndefinition C_msort_bu :: \"('a::linorder) list \\<Rightarrow> nat\" where\n\"C_msort_bu xs = C_merge_all (map (\\<lambda>x. [x]) xs)\"\n\nlemma length_merge_adj:\n  \"\\<lbrakk> even(length xss); \\<forall>xs \\<in> set xss. length xs = m \\<rbrakk>\n  \\<Longrightarrow> \\<forall>xs \\<in> set (merge_adj xss). length xs = 2*m\"\nby(induction xss rule: merge_adj.induct) (auto simp: length_merge)\n\nlemma C_merge_adj: \"\\<forall>xs \\<in> set xss. length xs = m \\<Longrightarrow> C_merge_adj xss \\<le> m * length xss\"\nproof(induction xss rule: C_merge_adj.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 x y) thus ?case using C_merge_ub[of x y] by (simp add: algebra_simps)\nqed\n\nlemma C_merge_all: \"\\<lbrakk> \\<forall>xs \\<in> set xss. length xs = m; length xss = 2^k \\<rbrakk>\n  \\<Longrightarrow> C_merge_all xss \\<le> m * k * 2^k\"\nproof (induction xss arbitrary: k m rule: C_merge_all.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 xs ys xss)\n  let ?xss = \"xs # ys # xss\"\n  let ?xss2 = \"merge_adj ?xss\"\n  obtain k' where k': \"k = Suc k'\" using \"3.prems\"(2)\n    by (metis length_Cons nat.inject nat_power_eq_Suc_0_iff nat.exhaust)\n  have \"even (length ?xss)\" using \"3.prems\"(2) k' by auto\n  from length_merge_adj[OF this \"3.prems\"(1)]\n  have *: \"\\<forall>x \\<in> set(merge_adj ?xss). length x = 2*m\" .\n  have **: \"length ?xss2 = 2 ^ k'\" using \"3.prems\"(2) k' by auto\n  have \"C_merge_all ?xss = C_merge_adj ?xss + C_merge_all ?xss2\" by simp\n  also have \"\\<dots> \\<le> m * 2^k + C_merge_all ?xss2\"\n    using \"3.prems\"(2) C_merge_adj[OF \"3.prems\"(1)] by (auto simp: algebra_simps)\n  also have \"\\<dots> \\<le> m * 2^k + (2*m) * k' * 2^k'\"\n    using \"3.IH\"[OF * **] by simp\n  also have \"\\<dots> = m * k * 2^k\"\n    using k' by (simp add: algebra_simps)\n  finally show ?case .\nqed\n\ncorollary C_msort_bu: \"length xs = 2 ^ k \\<Longrightarrow> C_msort_bu xs \\<le> k * 2 ^ k\"\nusing C_merge_all[of \"map (\\<lambda>x. [x]) xs\" 1] by (simp add: C_msort_bu_def)\n\n\nsubsection \"Quicksort\"\n\nfun quicksort :: \"('a::linorder) list \\<Rightarrow> 'a list\" where\n\"quicksort []     = []\" |\n\"quicksort (x#xs) = quicksort (filter (\\<lambda>y. y < x) xs) @ [x] @ quicksort (filter (\\<lambda>y. x \\<le> y) xs)\"\n\nlemma mset_quicksort: \"mset (quicksort xs) = mset xs\"\napply (induction xs rule: quicksort.induct)\napply (auto simp: not_le)\ndone\n\nlemma set_quicksort: \"set (quicksort xs) = set xs\"\nby(rule mset_eq_setD[OF mset_quicksort])\n\nlemma sorted_quicksort: \"sorted (quicksort xs)\"\napply (induction xs rule: quicksort.induct)\napply (auto simp add: sorted_append set_quicksort)\ndone\n\n\nsubsection \"Insertion Sort w.r.t. Keys and Stability\"\n\ntext \\<open>Note that \\<^const>\\<open>insort_key\\<close> is already defined in theory \\<^theory>\\<open>HOL.List\\<close>.\nThus some of the lemmas are already present as well.\\<close>\n\nfun isort_key :: \"('a \\<Rightarrow> 'k::linorder) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"isort_key f [] = []\" |\n\"isort_key f (x # xs) = insort_key f x (isort_key f xs)\"\n\n\nsubsubsection \"Standard functional correctness\"\n\nlemma mset_insort_key: \"mset (insort_key f x xs) = {#x#} + mset xs\"\nby(induction xs) simp_all\n\nlemma mset_isort_key: \"mset (isort_key f xs) = mset xs\"\nby(induction xs) (simp_all add: mset_insort_key)\n\nlemma set_isort_key: \"set (isort_key f xs) = set xs\"\nby (rule mset_eq_setD[OF mset_isort_key])\n\nlemma sorted_insort_key: \"sorted (map f (insort_key f a xs)) = sorted (map f xs)\"\nby(induction xs)(auto simp: set_insort_key)\n\nlemma sorted_isort_key: \"sorted (map f (isort_key f xs))\"\nby(induction xs)(simp_all add: sorted_insort_key)\n\n\nsubsubsection \"Stability\"\n\nlemma insort_is_Cons: \"\\<forall>x\\<in>set xs. f a \\<le> f x \\<Longrightarrow> insort_key f a xs = a # xs\"\nby (cases xs) auto\n\nlemma filter_insort_key_neg:\n  \"\\<not> P x \\<Longrightarrow> filter P (insort_key f x xs) = filter P xs\"\nby (induction xs) simp_all\n\nlemma filter_insort_key_pos:\n  \"sorted (map f xs) \\<Longrightarrow> P x \\<Longrightarrow> filter P (insort_key f x xs) = insort_key f x (filter P xs)\"\nby (induction xs) (auto, subst insort_is_Cons, auto)\n\nlemma sort_key_stable: \"filter (\\<lambda>y. f y = k) (isort_key f xs) = filter (\\<lambda>y. f y = k) xs\"\nproof (induction xs)\n  case Nil thus ?case by simp\nnext\n  case (Cons a xs)\n  thus ?case\n  proof (cases \"f a = k\")\n    case False thus ?thesis  by (simp add: Cons.IH filter_insort_key_neg)\n  next\n    case True\n    have \"filter (\\<lambda>y. f y = k) (isort_key f (a # xs))\n      = filter (\\<lambda>y. f y = k) (insort_key f a (isort_key f xs))\"  by simp\n    also have \"\\<dots> = insort_key f a (filter (\\<lambda>y. f y = k) (isort_key f xs))\"\n      by (simp add: True filter_insort_key_pos sorted_isort_key)\n    also have \"\\<dots> = insort_key f a (filter (\\<lambda>y. f y = k) xs)\"  by (simp add: Cons.IH)\n    also have \"\\<dots> = a # (filter (\\<lambda>y. f y = k) xs)\"  by(simp add: True insort_is_Cons)\n    also have \"\\<dots> = filter (\\<lambda>y. f y = k) (a # xs)\" by (simp add: True)\n    finally show ?thesis .\n  qed\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Data_Structures/Sorting.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382058759129, "lm_q2_score": 0.8918110511888303, "lm_q1q2_score": 0.7683292930215367}}
{"text": "theory Vedic\n    imports Main\nbegin\n\ntext\\<open>\nA book about Vedic mathematics describes three methods to make the calculation of squares of natural numbers easier:\n\n\\begin{itemize}\n\\item {\\em MM1}: Numbers whose predecessors have squares that are known or can easily be calculated. For example:\n\\\\ Needed: $61^2$  \n\\\\ Given: $60^2 = 3600$\n\\\\ Observe: $61^2 = 3600 + 60 + 61 = 3721$\n\n\\item {\\em MM2}: Numbers greater than, but near 100. For example:\n\\\\ Needed: $102^2$\n\\\\ Let $h = 102 - 100 = 2$ , $h^2 = 4$\n\\\\ Observe: $102^2 = (102+h)$ shifted two places to the left $ + h^2 = 10404$\n \n\\item {\\em MM3}: Numbers ending in $5$. For example:\n\\\\ Needed: $85^2$\n\\\\ Observe: $85^2 = (8 * 9)$ appended to $ 25 = 7225$\n\\\\ Needed: $995^2$\n\\\\ Observe: $995^2 = (99 * 100)$ appended to $ 25 = 990025 $\n\\end{itemize}\n\nIn this exercise we will show that these methods are not so magical after all!\n\n\\begin{itemize}\n\\item Based on {\\em MM1} define a function @{term \"sq\"} that calculates the square of a natural number.\n\\item Prove the correctness of @{term \"sq\"} (i.e.\\ @{term \"sq n = n * n\"}).\n\\item Formulate and prove the correctness of {\\em MM2}.\\\\ Hints:\n  \\begin{itemize}\n  \\item Generalise {\\em MM2} for an arbitrary constant (instead of $100$).\n  \\item Universally quantify all variables other than the induction variable.\n  \\end{itemize}\n\\item Formulate and prove the correctness of {\\em MM3}.\\\\ Hints:\n  \\begin{itemize}\n  \\item Try to formulate the property `numbers ending in $5$' such that it is easy to get to the rest of the number.\n  \\item Proving the binomial formula for $(a+b)^2$ can be of some help.\n  \\end{itemize}\n\\end{itemize}\n\\<close>\n\n\nprimrec sq :: \"nat \\<Rightarrow> nat\"\n  where\n\"sq 0 = 0\" |\n\"sq (Suc n) = (if (10 dvd (Suc n))\n               then (Suc n) * (Suc n)\n               else (Suc n) + n + (sq n))\"\n\nlemma MM1[simp]:\"sq n = n * n\"\n  apply (induction n) by auto\n\ndefinition sq1 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n\"sq1 n c = (let h = (n - c) in (n + h) * c + (sq h))\"\n\nlemma sq1_zero[simp]:\"sq1 0 c = 0\"\n  by (simp add: sq1_def)\n\nlemma MM2:\"\\<forall>c. c \\<le> n \\<Longrightarrow> (sq1 n c) = n*n\"\n  apply (simp add: Let_def sq1_def)\n  apply (induction n , auto)\n  by presburger\n\nvalue \"75 div 10::nat\"\n\nlemma bin_theorem_squared[simp]:\"((a::nat) + b)^2 = a^2 + 2 * a * b + b^2\"\n  by algebra\n\ndefinition sq2 :: \"nat \\<Rightarrow> nat\"\n  where\n\"sq2 n = (let c = n div 10 in ((Suc c) * c) * 100 + 25)\"\n\nvalue \"sq2 35 = sq 35\"\nvalue \"remaninder\"\n\ndefinition div_rem :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"div_rem a b q r = (b = a * q + r)\"\n\nlemma MM3:\"div_rem 10 n c 5 \\<Longrightarrow> ((Suc c) * c) * 100 + 25 = sq n\"\n  apply (simp add: Let_def sq2_def div_rem_def)\n  apply (induction n, auto)\n  by algebra\n\n(*<*) end (*>*)\n", "meta": {"author": "tomssem", "repo": "isabelle_exercises", "sha": "000b8edcb2050d4931e3177e9a339101d777dfe7", "save_path": "github-repos/isabelle/tomssem-isabelle_exercises", "path": "github-repos/isabelle/tomssem-isabelle_exercises/isabelle_exercises-000b8edcb2050d4931e3177e9a339101d777dfe7/arithmetic/Vedic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.8558511414521923, "lm_q1q2_score": 0.7682935404263321}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_rotate_structural_mod\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"'a list => 'a list => 'a list\" where\n\"x (nil2) z = z\"\n| \"x (cons2 z2 xs) z = cons2 z2 (x xs z)\"\n\nfun rotate :: \"Nat => 'a list => 'a list\" where\n\"rotate (Z) z = z\"\n| \"rotate (S z2) (nil2) = nil2\"\n| \"rotate (S z2) (cons2 z22 xs1) =\n     rotate z2 (x xs1 (cons2 z22 (nil2)))\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) z = z\"\n| \"plus (S z2) z = S (plus z2 z)\"\n\nfun minus :: \"Nat => Nat => Nat\" where\n\"minus (Z) z = Z\"\n| \"minus (S z2) (S y2) = minus z2 y2\"\n\nfun length :: \"'a list => Nat\" where\n\"length (nil2) = Z\"\n| \"length (cons2 z l) = plus (S Z) (length l)\"\n\nfun le :: \"Nat => Nat => bool\" where\n\"le (Z) z = True\"\n| \"le (S z2) (Z) = False\"\n| \"le (S z2) (S x2) = le z2 x2\"\n\nfun take :: \"Nat => 'a list => 'a list\" where\n\"take y z =\n   (if le y Z then nil2 else\n      (case z of\n         nil2 => nil2\n         | cons2 z2 xs => (case y of S x2 => cons2 z2 (take x2 xs))))\"\n\nfun go :: \"Nat => Nat => Nat => Nat\" where\n\"go y z (Z) = Z\"\n| \"go (Z) (Z) (S x2) = Z\"\n| \"go (Z) (S x5) (S x2) = minus (S x2) (S x5)\"\n| \"go (S x3) (Z) (S x2) = go x3 x2 (S x2)\"\n| \"go (S x3) (S x4) (S x2) = go x3 x4 (S x2)\"\n\nfun modstructural :: \"Nat => Nat => Nat\" where\n\"modstructural y z = go y Z z\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n\"drop y z =\n   (if le y Z then z else\n      (case z of\n         nil2 => nil2\n         | cons2 z2 xs1 => (case y of S x2 => drop x2 xs1)))\"\n\ntheorem property0 :\n  \"((rotate n xs) =\n      (x (drop (modstructural n (length xs)) xs)\n         (take (modstructural n (length xs)) xs)))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_rotate_structural_mod.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7682495512931163}}
{"text": "theory Tarjan\nimports Main\nbegin\n\ntext \\<open>\n  Tarjan's algorithm computes the strongly connected components of\n  a finite graph using depth-first search. We formalize a functional\n  version of the algorithm in Isabelle/HOL, following a development\n  of Lévy et al. in Why3 that is available at\n  \\url{http://pauillac.inria.fr/~levy/why3/graph/abs/scct/1-68bis/scc.html}.\n\\<close>\n\ntext \\<open>Make the simplifier expand let-constructions automatically\\<close>\ndeclare Let_def[simp]\n\ntext \\<open>\n  Definition of an auxiliary data structure holding local variables\n  during the execution of Tarjan's algorithm.\n\\<close>\nrecord 'v env =\n  black :: \"'v set\"\n  gray  :: \"'v set\"\n  stack :: \"'v list\"\n  sccs  :: \"'v set set\"\n  sn    :: nat\n  num   :: \"'v \\<Rightarrow> int\"\n\ndefinition colored where\n  \"colored e \\<equiv> black e \\<union> gray e\"\n\nlocale graph =\n  fixes vertices :: \"'v set\"\n    and successors :: \"'v \\<Rightarrow> 'v set\"\n  assumes vfin: \"finite vertices\"\n    and sclosed: \"\\<forall>x \\<in> vertices. successors x \\<subseteq> vertices\"\n\ncontext graph\nbegin\n\nsection {* Reachability in graphs *}\n\nabbreviation edge where\n  \"edge x y \\<equiv> y \\<in> successors x\"\n\ndefinition xedge_to where\n  \\<comment> \\<open>@{text ys} is a suffix of @{text xs}, @{text y} appears in @{text ys},\n      and there is an edge from some node in the prefix of @{text xs} to @{text y}\\<close>\n  \"xedge_to xs ys y \\<equiv>\n    y \\<in> set ys\n  \\<and> (\\<exists>zs. xs = zs @ ys \\<and> (\\<exists>z \\<in> set zs. edge z y))\"\n\ninductive reachable where\n  reachable_refl[iff]: \"reachable x x\"\n| reachable_succ[elim]: \"\\<lbrakk>edge x y; reachable y z\\<rbrakk> \\<Longrightarrow> reachable x z\"\n\nlemma reachable_edge: \"edge x y \\<Longrightarrow> reachable x y\"\n  by auto\n\nlemma succ_reachable:\n  assumes \"reachable x y\" and \"edge y z\"\n  shows \"reachable x z\"\n  using assms by induct auto\n\nlemma reachable_trans:\n  assumes y: \"reachable x y\" and z: \"reachable y z\"\n  shows \"reachable x z\"\n  using assms by induct auto\n\ntext {*\n  Given some set @{text S} and two vertices @{text x} and @{text y}\n  such that @{text y} is reachable from @{text x}, and @{text x} is\n  an element of @{text S} but @{text y} is not, then there exists\n  some vertices @{text x'} and @{text y'} linked by an edge such that\n  @{text x'} is an element of @{text S}, @{text y'} is not,\n  @{text x'} is reachable from @{text x}, and @{text y} is reachable  \n  from @{text y'}.\n*}\nlemma reachable_crossing_set:\n  assumes 1: \"reachable x y\" and 2: \"x \\<in> S\" and 3: \"y \\<notin> S\"\n  obtains x' y' where\n    \"x' \\<in> S\" \"y' \\<notin> S\" \"edge x' y'\" \"reachable x x'\" \"reachable y' y\"\nproof -\n  from assms\n  have \"\\<exists>x' y'. x' \\<in> S \\<and> y' \\<notin> S \\<and> edge x' y' \\<and> reachable x x' \\<and> reachable y' y\"\n    by induct (blast intro: reachable_edge reachable_trans)+\n  with that show ?thesis by blast\nqed\n\nsection {* Strongly connected components *}\n\ndefinition is_subscc where\n  \"is_subscc S \\<equiv> \\<forall>x \\<in> S. \\<forall>y \\<in> S. reachable x y\"\n\ndefinition is_scc where\n  \"is_scc S \\<equiv> S \\<noteq> {} \\<and> is_subscc S \\<and> (\\<forall>S'. S \\<subseteq> S' \\<and> is_subscc S' \\<longrightarrow> S' = S)\"\n\nlemma subscc_add:\n  assumes \"is_subscc S\" and \"x \\<in> S\"\n      and \"reachable x y\" and \"reachable y x\"\n  shows \"is_subscc (insert y S)\"\nusing assms unfolding is_subscc_def by (metis insert_iff reachable_trans)\n\nlemma sccE:\n  \\<comment> \\<open>Two vertices that are reachable from each other are in the same SCC.\\<close>\n  assumes \"is_scc S\" and \"x \\<in> S\"\n      and \"reachable x y\" and \"reachable y x\"\n  shows \"y \\<in> S\"\nusing assms unfolding is_scc_def by (metis insertI1 subscc_add subset_insertI)\n\nlemma scc_partition:\n  \\<comment> \\<open>Two SCCs that contain a common element are identical.\\<close>\n  assumes \"is_scc S\" and \"is_scc S'\" and \"x \\<in> S \\<inter> S'\"\n  shows \"S = S'\"\n  using assms unfolding is_scc_def is_subscc_def\n  by (metis IntE assms(2) sccE subsetI)\n\n\nsection {* Auxiliary functions *}\n\nabbreviation infty (\"\\<infinity>\") where\n  \\<comment> \\<open>integer exceeding any one used as a vertex number during the algorithm\\<close>\n  \"\\<infinity> \\<equiv> int (card vertices)\"\n\ndefinition set_infty where\n  \\<comment> \\<open>set @{text \"f x\"} to @{text \\<infinity>} for all x in xs\\<close>\n  \"set_infty xs f = fold (\\<lambda>x g. g (x := \\<infinity>)) xs f\"\n\nlemma set_infty:\n  \"(set_infty xs f) x = (if x \\<in> set xs then \\<infinity> else f x)\"\n  unfolding set_infty_def by (induct xs arbitrary: f) auto\n\ntext {*\n  Split a list at the first occurrence of a given element.\n  Returns the two sublists of elements before (and including)\n  the element and those strictly after the element. \n  If the element does not occur in the list, returns a pair \n  formed by the entire list and the empty list.\n*}\nfun split_list where\n  \"split_list x []  = ([], [])\"\n| \"split_list x (y # xs) =\n    (if x = y then ([x], xs) else \n       (let (l, r) = split_list x xs in\n         (y # l, r)))\" \n\nlemma split_list_concat:\n  \\<comment> \\<open>Concatenating the two sublists produced by @{text \"split_list\"}\n      yields back the original list.\\<close>\n  assumes \"x \\<in> set xs\"\n  shows \"(fst (split_list x xs)) @ (snd (split_list x xs)) = xs\"\n  using assms by (induct xs) (auto simp: split_def)\n\nlemma fst_split_list:\n  assumes \"x \\<in> set xs\"\n  shows \"\\<exists>ys. fst (split_list x xs) = ys @ [x] \\<and> x \\<notin> set ys\"\n  using assms by (induct xs) (auto simp: split_def)\n\ntext \\<open>\n  Push a vertex on the stack and increment the sequence number.\n  The pushed vertex is associated with the (old) sequence number.\n  It is also added to the set of gray nodes.\n\\<close>\ndefinition add_stack_incr where\n  \"add_stack_incr x e =\n      e \\<lparr> gray := insert x (gray e),\n          stack := x # (stack e),\n          sn := sn e +1,\n          num := (num e) (x := int (sn e)) \\<rparr>\"\n\ntext \\<open>\n  Add vertex @{text x} to the set of black vertices in @{text e}\n  and remove it from the set of gray vertices.\n\\<close>\ndefinition add_black where\n  \"add_black x e = e \\<lparr> black := insert x (black e),\n                       gray := (gray e) - {x} \\<rparr>\"\n\n\nsection \\<open>Main functions used for Tarjan's algorithms\\<close>\n\nsubsection \\<open>Function definitions\\<close>\n\ntext {*\n  We define two mutually recursive functions that contain the essence\n  of Tarjan's algorithm. Their arguments are respectively a single\n  vertex and a set of vertices, as well as an environment that contains\n  the local variables of the algorithm, and an auxiliary parameter\n  representing the set of ``gray'' vertices, which is used only for\n  the proof. The main function is then obtained by specializing the\n  function operating on a set of vertices.\n*}\n\nfunction (domintros) dfs1 and dfs where\n  \"dfs1 x e  =\n    (let (n1, e1) = dfs (successors x) (add_stack_incr x e) in\n      if n1 < int (sn e) then (n1, add_black x e1)\n      else\n       (let (l,r) = split_list x (stack e1) in\n         (\\<infinity>, \n           \\<lparr> black = insert x (black e1),\n             gray = gray e,\n             stack = r,\n             sccs = insert (set l) (sccs e1),\n             sn = sn e1,\n             num = set_infty l (num e1) \\<rparr> )))\"\n| \"dfs roots e =\n    (if roots = {} then (\\<infinity>, e)\n    else\n      (let x = SOME x. x \\<in> roots;\n           res1 = (if num e x \\<noteq> -1 then (num e x, e) else dfs1 x e);\n           res2 = dfs (roots - {x}) (snd res1)\n      in (min (fst res1) (fst res2), snd res2) ))\"\n  by pat_completeness auto\n\ndefinition init_env where\n  \"init_env \\<equiv> \\<lparr> black = {},            gray = {},\n                stack = [],            sccs = {},\n                sn = 0,                num = \\<lambda>_. -1 \\<rparr>\"\n\ndefinition tarjan where\n  \"tarjan \\<equiv> sccs (snd (dfs vertices init_env))\"\n\n\nsubsection \\<open>Well-definedness of the functions\\<close>\n\ntext \\<open>\n  We did not prove termination when we defined the two mutually \n  recursive functions @{text dfs1} and @{text dfs} defined above,\n  and indeed it is easy to see that they do not terminate for\n  arbitrary arguments. Isabelle allows us to define ``partial''\n  recursive functions, for which it introduces an auxiliary\n  domain predicate that characterizes their domain of definition.\n  We now make this more concrete and prove that the two functions\n  terminate when called for nodes of the graph, also assuming an\n  elementary well-definedness condition for environments. These\n  conditions are met in the cases of interest, and in particular\n  in the call to @{text dfs} in the main function @{text tarjan}.\n  Intuitively, the reason is that every (possibly indirect)\n  recursive call to @{text dfs} either decreases the set of roots\n  or increases the set of nodes colored black or gray.\n\\<close>\n\ntext \\<open>\n  The set of nodes colored black never decreases in the course\n  of the computation.\n\\<close>\nlemma black_increasing:\n  \"dfs1_dfs_dom (Inl (x,e)) \\<Longrightarrow> black e \\<subseteq> black (snd (dfs1 x e))\"\n  \"dfs1_dfs_dom (Inr (roots,e)) \\<Longrightarrow> black e \\<subseteq> black (snd (dfs roots e))\"\n  by (induct rule: dfs1_dfs.pinduct,\n      (fastforce simp: dfs1.psimps dfs.psimps case_prod_beta \n                   add_black_def add_stack_incr_def)+)\n\ntext \\<open>\n  Similarly, the set of nodes colored black or gray \n  never decreases in the course of the computation.\n\\<close>\nlemma colored_increasing:\n  \"dfs1_dfs_dom (Inl (x,e)) \\<Longrightarrow>\n    colored e \\<subseteq> colored (snd (dfs1 x e)) \\<and>\n    colored (add_stack_incr x e)\n    \\<subseteq> colored (snd (dfs (successors x) (add_stack_incr x e)))\"\n  \"dfs1_dfs_dom (Inr (roots,e)) \\<Longrightarrow>\n    colored e \\<subseteq> colored (snd (dfs roots e))\"\nproof (induct rule: dfs1_dfs.pinduct)\n  case (1 x e)\n  from `dfs1_dfs_dom (Inl (x,e))`\n  have \"black e \\<subseteq> black (snd (dfs1 x e))\"\n    by (rule black_increasing)\n  with 1 show ?case\n    by (auto simp: dfs1.psimps case_prod_beta add_stack_incr_def\n                   add_black_def colored_def)\nnext\n  case (2 roots e) then show ?case\n    by (fastforce simp: dfs.psimps case_prod_beta)\nqed\n\ntext \\<open>\n  The functions @{text dfs1} and @{text dfs} never assign the\n  number of a vertex to -1.\n\\<close>\nlemma dfs_num_defined:\n  \"\\<lbrakk>dfs1_dfs_dom (Inl (x,e)); num (snd (dfs1 x e)) v = -1\\<rbrakk> \\<Longrightarrow>\n    num e v = -1\"\n  \"\\<lbrakk>dfs1_dfs_dom (Inr (roots,e)); num (snd (dfs roots e)) v = -1\\<rbrakk> \\<Longrightarrow>\n    num e v = -1\"\n  by (induct rule: dfs1_dfs.pinduct,\n      (auto simp: dfs1.psimps dfs.psimps case_prod_beta add_stack_incr_def \n                  add_black_def set_infty\n            split: if_split_asm))\n\ntext \\<open>\n  We are only interested in environments that assign positive\n  numbers to colored nodes, and we show that calls to @{text dfs1}\n  and @{text dfs} preserve this property.\n\\<close>\ndefinition colored_num where\n  \"colored_num e \\<equiv> \\<forall>v \\<in> colored e. v \\<in> vertices \\<and> num e v \\<noteq> -1\"\n\nlemma colored_num:\n  \"\\<lbrakk>dfs1_dfs_dom (Inl (x,e)); x \\<in> vertices; colored_num e\\<rbrakk> \\<Longrightarrow>\n    colored_num (snd (dfs1 x e))\"\n  \"\\<lbrakk>dfs1_dfs_dom (Inr (roots,e)); roots \\<subseteq> vertices; colored_num e\\<rbrakk> \\<Longrightarrow>\n    colored_num (snd (dfs roots e))\"\nproof (induct rule: dfs1_dfs.pinduct)\n  case (1 x e) \n  let ?rec = \"dfs (successors x) (add_stack_incr x e)\"\n  from sclosed `x \\<in> vertices`\n  have \"successors x \\<subseteq> vertices\" ..\n  moreover\n  from `colored_num e` `x \\<in> vertices`\n  have \"colored_num (add_stack_incr x e)\" \n    by (auto simp: colored_num_def add_stack_incr_def colored_def)\n  ultimately \n  have rec: \"colored_num (snd ?rec)\"\n    using 1 by blast\n  have x: \"x \\<in> colored (add_stack_incr x e)\"\n    by (simp add: add_stack_incr_def colored_def)\n  from `dfs1_dfs_dom (Inl (x,e))` colored_increasing\n  have colrec: \"colored (add_stack_incr x e) \\<subseteq> colored (snd ?rec)\"\n    by blast\n  show ?case\n  proof (cases \"fst ?rec < int (sn e)\")\n    case True\n    with rec x colrec `dfs1_dfs_dom (Inl (x,e))` show ?thesis\n      by (auto simp: dfs1.psimps case_prod_beta \n                     colored_num_def add_black_def colored_def)\n  next\n    case False\n    let ?e' = \"snd (dfs1 x e)\"\n    have \"colored e \\<subseteq> colored (add_stack_incr x e)\"\n      by (auto simp: colored_def add_stack_incr_def)\n    with False x colrec `dfs1_dfs_dom (Inl (x,e))`\n    have \"colored ?e' \\<subseteq> colored (snd ?rec)\" \n         \"\\<exists>xs. num ?e' = set_infty xs (num (snd ?rec))\"\n      by (auto simp: dfs1.psimps case_prod_beta colored_def)\n    with rec show ?thesis\n      by (auto simp: colored_num_def set_infty split: if_split_asm)\n  qed\nnext\n  case (2 roots e)\n  show ?case\n  proof (cases \"roots = {}\")\n    case True\n    with `dfs1_dfs_dom (Inr (roots,e))` `colored_num e`\n    show ?thesis by (auto simp: dfs.psimps)\n  next\n    case False\n    let ?x = \"SOME x. x \\<in> roots\"\n    from False obtain r where \"r \\<in> roots\" by blast\n    hence \"?x \\<in> roots\" by (rule someI)\n    with `roots \\<subseteq> vertices` have x: \"?x \\<in> vertices\" ..\n    let ?res1 = \"if num e ?x \\<noteq> -1 then (num e ?x, e) else dfs1 ?x e\"\n    let ?res2 = \"dfs (roots - {?x}) (snd ?res1)\"\n    from 2 False `roots \\<subseteq> vertices` x\n    have \"colored_num (snd ?res1)\" by auto\n    with 2 False `roots \\<subseteq> vertices`\n    have \"colored_num (snd ?res2)\"\n      by blast\n    moreover\n    from False `dfs1_dfs_dom (Inr (roots,e))`\n    have \"dfs roots e = (min (fst ?res1) (fst ?res2), snd ?res2)\"\n      by (auto simp: dfs.psimps)\n    ultimately show ?thesis by simp\n  qed\nqed\n\ntext \\<open>\n  The following relation underlies the termination argument used\n  for proving well-definedness of the functions @{text dfs1} and\n  @{text dfs}. It is defined on the disjoint sum of the types of\n  arguments of the two functions and relates the arguments of\n  (mutually) recursive calls.\n\\<close>\ndefinition dfs1_dfs_term where\n  \"dfs1_dfs_term \\<equiv>\n    { (Inl(x, e::'v env), Inr(roots,e)) | \n      x e roots .\n      roots \\<subseteq> vertices \\<and> x \\<in> roots \\<and> colored e \\<subseteq> vertices }\n  \\<union> { (Inr(roots, add_stack_incr x e), Inl(x, e)) |\n      x e roots .\n      colored e \\<subseteq> vertices \\<and> x \\<in> vertices - colored e }\n  \\<union> { (Inr(roots, e::'v env), Inr(roots', e')) | \n      roots roots' e e' .\n      roots' \\<subseteq> vertices \\<and> roots \\<subset> roots' \\<and> \n      colored e' \\<subseteq> colored e \\<and> colored e \\<subseteq> vertices }\"\n\ntext \\<open>\n  In order to prove that the above relation is well-founded, we\n  use the following function that embeds it into triples whose first\n  component is the complement of the colored nodes, whose second\n  component is the set of root nodes, and whose third component\n  is 1 or 2 depending on the function being called. The third\n  component corresponds to the first case in the definition of\n  @{text dfs1_dfs_term}.\n\\<close>\nfun dfs1_dfs_to_tuple where\n  \"dfs1_dfs_to_tuple (Inl(x::'v, e::'v env)) = (vertices - colored e, {x}, 1::nat)\"\n| \"dfs1_dfs_to_tuple (Inr(roots, e::'v env)) = (vertices - colored e, roots, 2)\"\n\nlemma wf_term: \"wf dfs1_dfs_term\"\nproof -\n  let ?r = \"(finite_psubset :: ('v set \\<times> 'v set) set)\n            <*lex*> (finite_psubset :: ('v set \\<times> 'v set) set)\n            <*lex*> pred_nat\"\n  have \"wf ?r\"\n    using wf_finite_psubset wf_pred_nat by blast\n  moreover\n  have \"dfs1_dfs_term \\<subseteq> inv_image ?r dfs1_dfs_to_tuple\"\n    unfolding dfs1_dfs_term_def pred_nat_def using vfin \n    by (auto dest: finite_subset simp: add_stack_incr_def colored_def)\n  ultimately show ?thesis\n    using wf_inv_image wf_subset by blast\nqed\n\ntext \\<open>\n  The following theorem establishes sufficient conditions under\n  which the two functions @{text dfs1} and @{text dfs} terminate.\n  The proof proceeds by well-founded induction using the relation\n  @{text dfs1_dfs_term} and makes use of the theorem\n  @{text dfs1_dfs.domintros} that was generated by Isabelle from\n  the mutually recursive definitions in order to characterize the\n  domain conditions for these functions.\n\\<close>\ntheorem dfs1_dfs_termination:\n  \"\\<lbrakk>x \\<in> vertices - colored e; colored_num e\\<rbrakk> \\<Longrightarrow> dfs1_dfs_dom (Inl(x, e))\"\n  \"\\<lbrakk>roots \\<subseteq> vertices; colored_num e\\<rbrakk> \\<Longrightarrow> dfs1_dfs_dom (Inr(roots, e))\"\nproof -\n  { fix args\n    have \"(case args\n          of Inl(x,e) \\<Rightarrow> \n             x \\<in> vertices - colored e \\<and> colored_num e\n          |  Inr(roots,e) \\<Rightarrow> \n             roots \\<subseteq> vertices \\<and> colored_num e)\n        \\<longrightarrow> dfs1_dfs_dom args\" (is \"?P args \\<longrightarrow> ?Q args\")\n    proof (rule wf_induct[OF wf_term])\n      fix arg :: \"('v \\<times> 'v env) + ('v set \\<times> 'v env)\"\n      assume ih: \"\\<forall>arg'. (arg',arg) \\<in> dfs1_dfs_term\n                      \\<longrightarrow> (?P arg' \\<longrightarrow> ?Q arg')\"\n      show \"?P arg \\<longrightarrow> ?Q arg\"\n      proof\n        assume P: \"?P arg\"\n        show \"?Q arg\"\n        proof (cases arg)\n          case (Inl a)\n          then obtain x e where a: \"arg = Inl(x,e)\"\n            using dfs1.cases by metis\n          have \"?Q (Inl(x,e))\"\n          proof (rule dfs1_dfs.domintros)\n            let ?recarg = \"Inr (successors x, add_stack_incr x e)\"\n            from a P have \"(?recarg, arg) \\<in> dfs1_dfs_term\"\n              by (auto simp: add_stack_incr_def colored_num_def dfs1_dfs_term_def)\n            moreover\n            from a P sclosed have \"?P ?recarg\"\n              by (auto simp: add_stack_incr_def colored_num_def colored_def)\n            ultimately show \"?Q ?recarg\"\n              using ih by auto\n          qed\n          with a show ?thesis by simp\n        next\n          case (Inr b)\n          then obtain roots e where b: \"arg = Inr(roots,e)\"\n            using dfs.cases by metis\n          let ?sx = \"SOME x. x \\<in> roots\"\n          let ?rec1arg = \"Inl (?sx, e)\"\n          let ?rec2arg = \"Inr (roots - {?sx}, e)\"\n          let ?rec3arg = \"Inr (roots - {?sx}, snd (dfs1 ?sx e))\"\n          have \"?Q (Inr(roots,e))\"\n          proof (rule dfs1_dfs.domintros)\n            fix x\n            assume 1: \"x \\<in> roots\"\n               and 2: \"num e ?sx = -1\"\n               and 3: \"\\<not> dfs1_dfs_dom ?rec1arg\"\n            from 1 have sx: \"?sx \\<in> roots\" by (rule someI)\n            with P b have \"(?rec1arg, arg) \\<in> dfs1_dfs_term\"\n              by (auto simp: dfs1_dfs_term_def colored_num_def)\n            moreover\n            from sx 2 P b have \"?P ?rec1arg\"\n              by (auto simp: colored_num_def)\n            ultimately show False\n              using ih 3 by auto\n          next\n            fix x\n            assume \"x \\<in> roots\"\n            hence sx: \"?sx \\<in> roots\" by (rule someI)\n            from sx b P have \"(?rec2arg, arg) \\<in> dfs1_dfs_term\"\n              by (auto simp: dfs1_dfs_term_def colored_num_def)\n            moreover\n            from P b have \"?P ?rec2arg\" by auto\n            ultimately show \"dfs1_dfs_dom ?rec2arg\"\n              using ih by auto\n          next\n            fix x\n            assume 1: \"x \\<in> roots\" and 2: \"num e ?sx = -1\"\n            from 1 have sx: \"?sx \\<in> roots\" by (rule someI)\n            have \"dfs1_dfs_dom ?rec1arg\"\n            proof -\n              from sx P b have \"(?rec1arg, arg) \\<in> dfs1_dfs_term\"\n                by (auto simp: dfs1_dfs_term_def colored_num_def)\n              moreover\n              from sx 2 P b have \"?P ?rec1arg\"\n                by (auto simp: colored_num_def)\n              ultimately show ?thesis\n                using ih by auto\n            qed\n            with P b sx have \"colored_num (snd (dfs1 ?sx e))\"\n              by (auto elim: colored_num)\n            moreover\n            from this sx b P `dfs1_dfs_dom ?rec1arg`\n            have \"(?rec3arg, arg) \\<in> dfs1_dfs_term\"\n              by (auto simp: dfs1_dfs_term_def colored_num_def \n                       dest: colored_increasing)\n            moreover\n            from this P b `colored_num (snd (dfs1 ?sx e))`\n            have \"?P ?rec3arg\" by auto\n            ultimately show \"dfs1_dfs_dom ?rec3arg\"\n              using ih by auto\n          qed\n          with b show ?thesis by simp\n        qed\n      qed\n    qed\n  }\n  note dom = this\n  from dom \n  show \"\\<lbrakk>x \\<in> vertices - colored e; colored_num e\\<rbrakk> \\<Longrightarrow> dfs1_dfs_dom (Inl(x,e))\"\n    by auto\n  from dom\n  show \"\\<lbrakk>roots \\<subseteq> vertices; colored_num e\\<rbrakk> \\<Longrightarrow> dfs1_dfs_dom (Inr(roots,e))\"\n    by auto\nqed\n\n\nsection {* Auxiliary notions for the proof of partial correctness *}\n\ntext \\<open>\n  The proof of partial correctness is more challenging and requires\n  some further concepts that we now define.\n\n  We need to reason about the relative order of elements in a list\n  (specifically, the stack used in the algorithm).\n\\<close>\ndefinition precedes (\"_ \\<preceq> _ in _\" [100,100,100] 39) where\n  \\<comment> \\<open>@{text x} has an occurrence in @{text xs} that\n      precedes an occurrence of @{text y}.\\<close>\n  \"x \\<preceq> y in xs \\<equiv> \\<exists>l r. xs = l @ (x # r) \\<and> y \\<in> set (x # r)\"\n\nlemma precedes_mem:\n  assumes \"x \\<preceq> y in xs\"\n  shows \"x \\<in> set xs\" \"y \\<in> set xs\"\n  using assms unfolding precedes_def by auto\n\nlemma head_precedes:\n  assumes \"y \\<in> set (x # xs)\"\n  shows \"x \\<preceq> y in (x # xs)\"\n  using assms unfolding precedes_def by force\n\nlemma precedes_in_tail:\n  assumes \"x \\<noteq> z\"\n  shows \"x \\<preceq> y in (z # zs) \\<longleftrightarrow> x \\<preceq> y in zs\"\n  using assms unfolding precedes_def by (auto simp: Cons_eq_append_conv)\n\nlemma tail_not_precedes:\n  assumes \"y \\<preceq> x in (x # xs)\" \"x \\<notin> set xs\"\n  shows \"x = y\"\n  using assms unfolding precedes_def\n  by (metis Cons_eq_append_conv Un_iff list.inject set_append)\n\nlemma split_list_precedes:\n  assumes \"y \\<in> set (ys @ [x])\"\n  shows \"y \\<preceq> x in (ys @ x # xs)\"\n  using assms unfolding precedes_def\n  by (metis append_Cons append_assoc in_set_conv_decomp\n            rotate1.simps(2) set_ConsD set_rotate1)\n\nlemma precedes_refl [simp]: \"(x \\<preceq> x in xs) = (x \\<in> set xs)\"\nproof\n  assume \"x \\<preceq> x in xs\" thus \"x \\<in> set xs\"\n    by (simp add: precedes_mem)\nnext\n  assume \"x \\<in> set xs\"\n  from this[THEN split_list] show \"x \\<preceq> x in xs\"\n    unfolding precedes_def by auto\nqed\n\nlemma precedes_append_left:\n  assumes \"x \\<preceq> y in xs\"\n  shows \"x \\<preceq> y in (ys @ xs)\"\n  using assms unfolding precedes_def by (metis append.assoc)\n\nlemma precedes_append_left_iff:\n  assumes \"x \\<notin> set ys\"\n  shows \"x \\<preceq> y in (ys @ xs) \\<longleftrightarrow> x \\<preceq> y in xs\" (is \"?lhs = ?rhs\")\nproof\n  assume \"?lhs\"\n  then obtain l r where lr: \"ys @ xs = l @ (x # r)\" \"y \\<in> set (x # r)\"\n    unfolding precedes_def by blast\n  then obtain us where\n    \"(ys = l @ us \\<and> us @ xs = x # r) \\<or> (ys @ us = l \\<and> xs = us @ (x # r))\"\n    by (auto simp: append_eq_append_conv2)\n  thus ?rhs\n  proof\n    assume us: \"ys = l @ us \\<and> us @ xs = x # r\"\n    with assms have \"us = []\"\n      by (metis Cons_eq_append_conv in_set_conv_decomp)\n    with us lr show ?rhs\n      unfolding precedes_def by auto\n  next\n    assume us: \"ys @ us = l \\<and> xs = us @ (x # r)\"\n    with \\<open>y \\<in> set (x # r)\\<close> show ?rhs\n      unfolding precedes_def by blast\n  qed\nnext\n  assume \"?rhs\" thus \"?lhs\" by (rule precedes_append_left)\nqed\n\nlemma precedes_append_right:\n  assumes \"x \\<preceq> y in xs\"\n  shows \"x \\<preceq> y in (xs @ ys)\"\n  using assms unfolding precedes_def by force\n\nlemma precedes_append_right_iff:\n  assumes \"y \\<notin> set ys\"\n  shows \"x \\<preceq> y in (xs @ ys) \\<longleftrightarrow> x \\<preceq> y in xs\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain l r where lr: \"xs @ ys = l @ (x # r)\" \"y \\<in> set (x # r)\"\n    unfolding precedes_def by blast\n  then obtain us where\n    \"(xs = l @ us \\<and> us @ ys = x # r) \\<or> (xs @ us = l \\<and> ys = us @ (x # r))\"\n    by (auto simp: append_eq_append_conv2)\n  thus ?rhs\n  proof\n    assume us: \"xs = l @ us \\<and> us @ ys = x # r\"\n    with \\<open>y \\<in> set (x # r)\\<close> assms show ?rhs\n      unfolding precedes_def by (metis Cons_eq_append_conv Un_iff set_append)\n  next\n    assume us: \"xs @ us = l \\<and> ys = us @ (x # r)\"\n    with \\<open>y \\<in> set (x # r)\\<close> assms \n    show ?rhs by auto \\<comment> \\<open>contradiction\\<close>\n  qed\nnext\n  assume ?rhs thus ?lhs by (rule precedes_append_right)\nqed\n\ntext \\<open>\n  Precedence determines an order on the elements of a list,\n  provided elements have unique occurrences. However, consider\n  a list such as @{term \"[2,3,1,2]\"}: then $1$ precedes $2$ and\n  $2$ precedes $3$, but $1$ does not precede $3$.\n\\<close>\nlemma precedes_trans:\n  assumes \"x \\<preceq> y in xs\" and \"y \\<preceq> z in xs\" and \"distinct xs\"\n  shows \"x \\<preceq> z in xs\"\n  using assms unfolding precedes_def\n  by (smt Un_iff append.assoc append_Cons_eq_iff distinct_append \n          not_distinct_conv_prefix set_append split_list_last)\n\nlemma precedes_antisym:\n  assumes \"x \\<preceq> y in xs\" and \"y \\<preceq> x in xs\" and \"distinct xs\"\n  shows \"x = y\"\nproof -\n  from \\<open>x \\<preceq> y in xs\\<close> \\<open>distinct xs\\<close> obtain as bs where\n    1: \"xs = as @ (x # bs)\" \"y \\<in> set (x # bs)\" \"y \\<notin> set as\"\n    unfolding precedes_def by force\n  from \\<open>y \\<preceq> x in xs\\<close> \\<open>distinct xs\\<close> obtain cs ds where\n    2: \"xs = cs @ (y # ds)\" \"x \\<in> set (y # ds)\" \"x \\<notin> set cs\"\n    unfolding precedes_def by force\n  from 1 2 have \"as @ (x # bs) = cs @ (y # ds)\"\n    by simp\n  then obtain zs where\n    \"(as = cs @ zs \\<and> zs @ (x # bs) = y # ds) \n     \\<or> (as @ zs = cs \\<and> x # bs = zs @ (y # ds))\"  (is \"?P \\<or> ?Q\")\n    by (auto simp: append_eq_append_conv2)\n  then show ?thesis\n  proof\n    assume \"?P\" with \\<open>y \\<notin> set as\\<close> show ?thesis \n      by (cases \"zs\") auto\n  next\n    assume \"?Q\" with \\<open>x \\<notin> set cs\\<close> show ?thesis\n      by (cases \"zs\") auto\n  qed\nqed\n\n\nsection {* Predicates and lemmas about environments *}\n\ndefinition subenv where\n  \"subenv e e' \\<equiv>\n    (\\<exists>s. stack e' = s @ (stack e) \\<and> set s \\<subseteq> black e')\n  \\<and> black e \\<subseteq> black e' \\<and> gray e = gray e'\n  \\<and> sccs e \\<subseteq> sccs e'\n  \\<and> (\\<forall>x \\<in> set (stack e). num e x = num e' x)\"\n\nlemma subenv_refl [simp]: \"subenv e e\"\n  by (auto simp: subenv_def)\n\nlemma subenv_trans:\n  assumes \"subenv e e'\" and \"subenv e' e''\"\n  shows \"subenv e e''\"\n  using assms unfolding subenv_def by force\n\ndefinition wf_color where\n  \\<comment> \\<open>conditions about colors, part of the invariant of the algorithm\\<close>\n  \"wf_color e \\<equiv>\n    colored e \\<subseteq> vertices\n  \\<and> black e \\<inter> gray e = {}\n  \\<and> (\\<Union> (sccs e)) \\<subseteq> black e\n  \\<and> set (stack e) = gray e \\<union> (black e - \\<Union> (sccs e))\"\n\ndefinition wf_num where\n  \\<comment> \\<open>conditions about vertex numbers\\<close>\n  \"wf_num e \\<equiv>\n    int (sn e) \\<le> \\<infinity>\n  \\<and> (\\<forall>x. -1 \\<le> num e x \\<and> (num e x = \\<infinity> \\<or> num e x < int (sn e)))\n  \\<and> sn e = card (colored e)\n  \\<and> (\\<forall>x. num e x = \\<infinity> \\<longleftrightarrow> x \\<in> \\<Union> (sccs e))\n  \\<and> (\\<forall>x. num e x = -1 \\<longleftrightarrow> x \\<notin> colored e)\n  \\<and> (\\<forall>x \\<in> set (stack e). \\<forall>y \\<in> set (stack e).\n        (num e x \\<le> num e y \\<longleftrightarrow> y \\<preceq> x in (stack e)))\"\n\nlemma subenv_num:\n  \\<comment> \\<open>If @{text e} and @{text e'} are two well-formed environments,\n      and @{text e} is a sub-environment of @{text e'} then the number\n      assigned by @{text e'} to any vertex is at least that assigned\n      by @{text e}.\\<close>\n  assumes sub: \"subenv e e'\"\n      and e: \"wf_color e\" \"wf_num e\"\n      and e': \"wf_color e'\" \"wf_num e'\"\n  shows \"num e x \\<le> num e' x\"\n(*\n  using assms unfolding wf_color_def wf_num_def subenv_def colored_def\n  by (smt DiffI UnCI UnE mem_simps(9) subsetCE)\n*)\nproof (cases \"x \\<in> colored e\")\n  case True then show ?thesis unfolding colored_def\n  proof\n    assume \"x \\<in> gray e\"\n    with e sub show ?thesis \n      by (auto simp: wf_color_def subenv_def)\n  next\n    assume \"x \\<in> black e\"\n    show ?thesis\n    proof (cases \"x \\<in> \\<Union> (sccs e)\")\n      case True\n      with sub e e' have \"num e x = \\<infinity>\" \"num e' x = \\<infinity>\"\n        by (auto simp: subenv_def wf_num_def)\n      thus ?thesis by simp\n    next\n      case False\n      with \\<open>x \\<in> black e\\<close> e sub show ?thesis\n        by (auto simp: wf_color_def subenv_def)\n    qed\n  qed\nnext\n  case False with e e' show ?thesis\n    unfolding wf_num_def by metis\nqed\n\ndefinition no_black_to_white where\n  \\<comment> \\<open>successors of black vertices cannot be white\\<close>\n  \"no_black_to_white e \\<equiv> \\<forall>x y. edge x y \\<and> x \\<in> black e \\<longrightarrow> y \\<in> colored e\"\n\ndefinition wf_env where\n  \"wf_env e \\<equiv>\n    wf_color e \\<and> wf_num e\n  \\<and> no_black_to_white e \\<and> distinct (stack e)\n  \\<and> (\\<forall>x y. y \\<preceq> x in (stack e) \\<longrightarrow> reachable x y)\n  \\<and> (\\<forall>y \\<in> set (stack e). \\<exists>g \\<in> gray e. y \\<preceq> g in (stack e) \\<and> reachable y g)\n  \\<and> sccs e = { C . C \\<subseteq> black e \\<and> is_scc C }\"\n\nlemma num_in_stack:\n  assumes \"wf_env e\" and \"x \\<in> set (stack e)\"\n  shows \"num e x \\<noteq> -1\"\n        \"num e x < int (sn e)\"\nproof -\n  from assms \n  show \"num e x \\<noteq> -1\"\n    by (auto simp: wf_env_def wf_color_def wf_num_def colored_def)\n  from `wf_env e`\n  have \"num e x < int (sn e) \\<or> x \\<in> \\<Union> (sccs e)\"\n    unfolding wf_env_def wf_num_def by metis\n  with assms show \"num e x < int (sn e)\"\n    unfolding wf_env_def wf_color_def by blast\nqed\n\ntext \\<open>\n  Numbers assigned to different stack elements are distinct.\n\\<close>\nlemma num_inj:\n  assumes \"wf_env e\" and \"x \\<in> set (stack e)\" \n      and \"y \\<in> set (stack e)\" and \"num e x = num e y\"\n    shows \"x = y\"\n  using assms unfolding wf_env_def wf_num_def\n  by (metis precedes_refl precedes_antisym) \n\ntext \\<open>\n  The set of black elements at the top of the stack together\n  with the first gray element always form a sub-SCC. This lemma\n  is useful for the ``else'' branch of @{text dfs1}.\n\\<close>\nlemma first_gray_yields_subscc:\n  assumes e: \"wf_env e\"\n    and x: \"stack e = ys @ (x # zs)\"\n    and g: \"x \\<in> gray e\"\n    and ys: \"set ys \\<subseteq> black e\"\n  shows \"is_subscc (insert x (set ys))\"\nproof -\n  from e x have \"\\<forall>y \\<in> set ys. \\<exists>g \\<in> gray e. reachable y g\"\n    unfolding wf_env_def by force\n  moreover\n  have \"\\<forall>g \\<in> gray e. reachable g x\"\n  proof\n    fix g\n    assume \"g \\<in> gray e\"\n    with e x ys have \"g \\<in> set (x # zs)\"\n      unfolding wf_env_def wf_color_def by auto\n    with e x show \"reachable g x\"\n      unfolding wf_env_def precedes_def by blast\n  qed\n  moreover\n  from e x g have \"\\<forall>y \\<in> set ys. reachable x y\"\n    unfolding wf_env_def by (simp add: split_list_precedes)\n  ultimately show ?thesis\n    unfolding is_subscc_def \n    by (metis reachable_trans reachable_refl insertE)\nqed\n\nsection \\<open>Partial correctness of the main functions\\<close>\n\ntext \\<open>\n  We now define the pre- and post-conditions for proving that\n  the functions @{text dfs1} and @{text dfs} are partially correct.\n  The parameters of the preconditions, as well as the first parameters\n  of the postconditions, coincide with the parameters of the\n  functions @{text dfs1} and @{text dfs}. The final parameter of\n  the postconditions represents the result computed by the function.\n\\<close>\n\ndefinition dfs1_pre where\n  \"dfs1_pre x e \\<equiv>\n    x \\<in> vertices\n  \\<and> x \\<notin> colored e\n  \\<and> (\\<forall>g \\<in> gray e. reachable g x)\n  \\<and> wf_env e\"\n\ndefinition dfs1_post where\n  \"dfs1_post x e res \\<equiv>\n    let n = fst res; e' = snd res\n    in  wf_env e'\n      \\<and> subenv e e'\n      \\<and> x \\<in> black e'\n      \\<and> n \\<le> num e' x\n      \\<and> (n = \\<infinity> \\<or> (\\<exists>y \\<in> set (stack e'). num e' y = n \\<and> reachable x y))\n      \\<and> (\\<forall>y. xedge_to (stack e') (stack e) y \\<longrightarrow> n \\<le> num e' y)\"\n\ndefinition dfs_pre where\n  \"dfs_pre roots e \\<equiv>\n    roots \\<subseteq> vertices\n  \\<and> (\\<forall>x \\<in> roots. \\<forall>g \\<in> gray e. reachable g x)\n  \\<and> wf_env e\"\n\ndefinition dfs_post where\n  \"dfs_post roots e res \\<equiv>\n    let n = fst res; e' = snd res\n    in  wf_env e'\n      \\<and> subenv e e'\n      \\<and> roots \\<subseteq> colored e'\n      \\<and> (\\<forall>x \\<in> roots. n \\<le> num e' x)\n      \\<and> (n = \\<infinity> \\<or> (\\<exists>x \\<in> roots. \\<exists>y \\<in> set (stack e'). num e' y = n \\<and> reachable x y))\n      \\<and> (\\<forall>y. xedge_to (stack e') (stack e) y \\<longrightarrow> n \\<le> num e' y)\"\n\ntext \\<open>\n  The following lemmas express some useful consequences of the\n  pre- and post-conditions. In particular, the preconditions\n  ensure that the function calls terminate.\n\\<close>\n\nlemma dfs1_pre_domain:\n  assumes \"dfs1_pre x e\"\n  shows \"colored e \\<subseteq> vertices\" \n        \"x \\<in> vertices - colored e\"\n        \"x \\<notin> set (stack e)\"\n        \"int (sn e) < \\<infinity>\"\n  using assms vfin\n  unfolding dfs1_pre_def wf_env_def wf_color_def wf_num_def colored_def\n  by (auto intro: psubset_card_mono)\n\nlemma dfs1_pre_dfs1_dom:\n  \"dfs1_pre x e \\<Longrightarrow> dfs1_dfs_dom (Inl(x,e))\"\n  unfolding dfs1_pre_def wf_env_def wf_color_def wf_num_def\n  by (auto simp: colored_num_def intro!: dfs1_dfs_termination)\n\nlemma dfs_pre_dfs_dom:\n  \"dfs_pre roots e \\<Longrightarrow> dfs1_dfs_dom (Inr(roots,e))\"\n  unfolding dfs_pre_def wf_env_def wf_color_def wf_num_def\n  by (auto simp: colored_num_def intro!: dfs1_dfs_termination)\n\n(** not needed, but potentially useful\nlemma dfs1_post_num:\n  \"dfs1_post x e res \\<Longrightarrow> fst res \\<le> \\<infinity>\"\n  unfolding dfs1_post_def wf_env_def wf_num_def\n  by smt\n\nlemma dfs_post_num:\n  \"dfs_post roots e res \\<Longrightarrow> fst res \\<le> \\<infinity>\"\n  unfolding dfs_post_def wf_env_def wf_num_def\n  by smt\n**)\n\nlemma dfs_post_stack:\n  assumes \"dfs_post roots e res\"\n  obtains s where \n    \"stack (snd res) = s @ stack e\" \n    \"set s \\<subseteq> black (snd res)\"\n    \"\\<forall>x \\<in> set (stack e). num (snd res) x = num e x\"\n  using assms unfolding dfs_post_def subenv_def by auto\n\nlemma dfs_post_split:\n  fixes x e res\n  defines \"n' \\<equiv> fst res\"\n  defines \"e' \\<equiv> snd res\"\n  defines \"l \\<equiv> fst (split_list x (stack e'))\"\n  defines \"r \\<equiv> snd (split_list x (stack e'))\"\n  assumes post: \"dfs_post (successors x) (add_stack_incr x e) res\"\n             (is \"dfs_post ?roots ?e res\")\n  obtains ys where\n    \"l = ys @ [x]\"\n    \"x \\<notin> set ys\"\n    \"set ys \\<subseteq> black e'\"\n    \"stack e' = l @ r\"\n    \"is_subscc (set l)\"\n    \"r = stack e\"\nproof -\n  from post have dist: \"distinct (stack e')\"\n    unfolding dfs_post_def wf_env_def e'_def by auto\n  from post obtain s where\n    s: \"stack e' = s @ (x # stack e)\" \"set s \\<subseteq> black e'\"\n    unfolding add_stack_incr_def e'_def\n    by (auto intro: dfs_post_stack)\n  then obtain ys where ys: \"l = ys @ [x]\" \"x \\<notin> set ys\" \"stack e' = l @ r\"\n    unfolding add_stack_incr_def l_def r_def\n    by (metis in_set_conv_decomp split_list_concat fst_split_list)\n  with s have l: \"l = (s @ [x]) \\<and> r = stack e\"\n    by (metis dist append.assoc append.simps(1) append.simps(2) \n              append_Cons_eq_iff distinct.simps(2) distinct_append)\n  from post have \"wf_env e'\" \"x \\<in> gray e'\"\n    by (auto simp: dfs_post_def subenv_def add_stack_incr_def e'_def)\n  with s l have \"is_subscc (set l)\"\n    by (auto simp: add_stack_incr_def intro: first_gray_yields_subscc)\n  with s ys l that show ?thesis by auto\nqed\n\ntext {*\n  A crucial lemma establishing a condition after the ``then'' branch\n  following the recursive call in function @{text dfs1}.\n*}\nlemma dfs_post_reach_gray:\n  fixes x e res\n  defines \"n' \\<equiv> fst res\"\n  defines \"e' \\<equiv> snd res\"\n  assumes e: \"wf_env e\"\n      and post: \"dfs_post (successors x) (add_stack_incr x e) res\"\n             (is \"dfs_post ?roots ?e res\")\n      and n': \"n' < int (sn e)\"\n  obtains g where\n    \"g \\<noteq> x\" \"g \\<in> gray e'\" \"x \\<preceq> g in (stack e')\" \n    \"reachable x g\" \"reachable g x\"\nproof -\n  from post have e': \"wf_env e'\" \"subenv ?e e'\"\n    by (auto simp: dfs_post_def e'_def)\n  hence x_e': \"x \\<in> set (stack e')\" \"x \\<in> vertices\" \"num e' x = int(sn e)\"\n    by (auto simp: add_stack_incr_def subenv_def wf_env_def wf_color_def colored_def)\n  from e n' have \"n' \\<noteq> \\<infinity>\"\n    unfolding wf_env_def wf_num_def by simp\n  with post e' obtain sx y g where\n    g: \"sx \\<in> ?roots\" \"y \\<in> set (stack e')\" \"num e' y = n'\" \"reachable sx y\"\n       \"g \\<in> gray e'\" \"g \\<in> set (stack e')\" \"y \\<preceq> g in (stack e')\" \"reachable y g\"\n    unfolding dfs_post_def e'_def n'_def wf_env_def\n    by (fastforce intro: precedes_mem )\n  with e' have \"num e' g \\<le> num e' y\"\n    unfolding wf_env_def wf_num_def by metis\n  with n' x_e' \\<open>num e' y = n'\\<close> \n  have \"num e' g \\<le> num e' x\" \"g \\<noteq> x\" by auto\n  with \\<open>g \\<in> set (stack e')\\<close> \\<open>x \\<in> set (stack e')\\<close> e'\n  have \"g \\<noteq> x \\<and> x \\<preceq> g in (stack e') \\<and> reachable g x\"\n    unfolding wf_env_def wf_num_def by auto\n  moreover \n  from g have \"reachable x g\"\n    by (metis reachable_succ reachable_trans)\n  moreover\n  note \\<open>g \\<in> gray e'\\<close> that\n  ultimately show ?thesis by auto\nqed\n\ntext {*\n  The following lemmas represent steps in the proof of partial correctness.\n*}\n\nlemma dfs1_pre_dfs_pre:\n  \\<comment> \\<open>The precondition of @{text dfs1} establishes that of the recursive\n      call to @{text dfs}.\\<close>\n  assumes \"dfs1_pre x e\"\n  shows \"dfs_pre (successors x) (add_stack_incr x e)\"\n        (is \"dfs_pre ?roots' ?e'\")\nproof -\n  from assms sclosed have \"?roots' \\<subseteq> vertices\"\n    unfolding dfs1_pre_def by blast\n  moreover\n  from assms have \"\\<forall>y \\<in> ?roots'. \\<forall>g \\<in> gray ?e'. reachable g y\"\n    unfolding dfs1_pre_def add_stack_incr_def\n    by (auto dest: succ_reachable reachable_trans)\n  moreover\n  {\n    from assms have wf_col': \"wf_color ?e'\"\n      by (auto simp: dfs1_pre_def wf_env_def wf_color_def \n                     add_stack_incr_def colored_def)\n    note 1 = dfs1_pre_domain[OF assms]\n    from assms 1 have dist': \"distinct (stack ?e')\"\n      unfolding dfs1_pre_def wf_env_def add_stack_incr_def by auto\n    from assms have 3: \"sn e = card (colored e)\"\n      unfolding dfs1_pre_def wf_env_def wf_num_def by simp\n    from 1 have 4: \"int (sn ?e') \\<le> \\<infinity>\"\n      unfolding add_stack_incr_def by simp\n    with assms have 5: \"\\<forall>x. -1 \\<le> num ?e' x \\<and> (num ?e' x = \\<infinity> \\<or> num ?e' x < int (sn ?e'))\"\n      unfolding dfs1_pre_def wf_env_def wf_num_def add_stack_incr_def by auto\n    from 1 vfin have \"finite (colored e)\" using finite_subset by blast\n    with 1 3 have 6: \"sn ?e' = card (colored ?e')\"\n      unfolding add_stack_incr_def colored_def by auto\n    from assms 1 3 have 7: \"\\<forall>y. num ?e' y = \\<infinity> \\<longleftrightarrow> y \\<in> \\<Union> (sccs ?e')\"\n      by (auto simp: dfs1_pre_def wf_env_def wf_num_def\n                     add_stack_incr_def colored_def)\n    from assms 3 have 8: \"\\<forall>y. num ?e' y = -1 \\<longleftrightarrow> y \\<notin> colored ?e'\"\n      by (auto simp: dfs1_pre_def wf_env_def wf_num_def add_stack_incr_def colored_def)\n    from assms 1 have \"\\<forall>y \\<in> set (stack e). num ?e' y < num ?e' x\"\n      unfolding dfs1_pre_def add_stack_incr_def\n      by (auto dest: num_in_stack)\n    moreover\n    have \"\\<forall>y \\<in> set (stack e). x \\<preceq> y in (stack ?e')\"\n      unfolding add_stack_incr_def by (auto intro: head_precedes)\n    moreover\n    from 1 have \"\\<forall>y \\<in> set (stack e). \\<not>(y \\<preceq> x in (stack ?e'))\"\n      unfolding add_stack_incr_def by (auto dest: tail_not_precedes)\n    moreover\n    {\n      fix y z\n      assume \"y \\<in> set (stack e)\" \"z \\<in> set (stack e)\"\n      with 1 have \"x \\<noteq> y\" by auto\n      hence \"y \\<preceq> z in (stack ?e') \\<longleftrightarrow> y \\<preceq> z in (stack e)\"\n        by (simp add: add_stack_incr_def precedes_in_tail)\n    }\n    ultimately\n    have 9: \"\\<forall>y \\<in> set (stack ?e'). \\<forall>z \\<in> set (stack ?e').\n                num ?e' y \\<le> num ?e' z \\<longleftrightarrow> z \\<preceq> y in (stack ?e')\"\n      using assms\n      unfolding dfs1_pre_def wf_env_def wf_num_def add_stack_incr_def\n      by auto\n    from 4 5 6 7 8 9 have wf_num': \"wf_num ?e'\"\n      unfolding wf_num_def by blast\n    from assms have nbtw': \"no_black_to_white ?e'\"\n      by (auto simp: dfs1_pre_def wf_env_def no_black_to_white_def \n                     add_stack_incr_def colored_def)\n\n    have stg': \"\\<forall>y \\<in> set (stack ?e'). \\<exists>g \\<in> gray ?e'.\n                   y \\<preceq> g in (stack ?e') \\<and> reachable y g\"\n    proof\n      fix y\n      assume y: \"y \\<in> set (stack ?e')\"\n      show \"\\<exists>g \\<in> gray ?e'. y \\<preceq> g in (stack ?e') \\<and> reachable y g\"\n      proof (cases \"y = x\")\n        case True\n        then show ?thesis\n          unfolding add_stack_incr_def by auto\n      next\n        case False\n        with y have \"y \\<in> set (stack e)\"\n          by (simp add: add_stack_incr_def)\n        with assms obtain g where \n          \"g \\<in> gray e \\<and> y \\<preceq> g in (stack e) \\<and> reachable y g\"\n          unfolding dfs1_pre_def wf_env_def by blast\n        thus ?thesis\n          unfolding add_stack_incr_def\n          by (auto dest: precedes_append_left[where ys=\"[x]\"])\n      qed\n    qed\n\n    have str': \"\\<forall>y z. y \\<preceq> z in (stack ?e') \\<longrightarrow> reachable z y\"\n    proof (clarify)\n      fix y z\n      assume yz: \"y \\<preceq> z in stack ?e'\"\n      show \"reachable z y\"\n      proof (cases \"y = x\")\n        case True\n        from yz[THEN precedes_mem(2)] stg'\n        obtain g where \"g \\<in> gray ?e'\" \"reachable z g\" by blast\n        with True assms show ?thesis\n          unfolding dfs1_pre_def add_stack_incr_def\n          by (auto elim: reachable_trans)\n      next\n        case False\n        with yz have yze: \"y \\<preceq> z in stack e\"\n          by (simp add: add_stack_incr_def precedes_in_tail)\n        with assms show ?thesis\n          unfolding dfs1_pre_def wf_env_def by blast\n      qed\n    qed\n    from assms have \"sccs (add_stack_incr x e) = \n           {C . C \\<subseteq> black (add_stack_incr x e) \\<and> is_scc C}\"\n      by (auto simp: dfs1_pre_def wf_env_def add_stack_incr_def)\n    with wf_col' wf_num' nbtw' dist' str' stg'\n    have \"wf_env ?e'\"\n      unfolding wf_env_def by blast\n  }\n  ultimately show ?thesis\n    unfolding dfs_pre_def by blast\nqed\n\nlemma dfs_pre_dfs1_pre:\n  \\<comment> \\<open>The precondition of @{text dfs} establishes that of the recursive\n      call to @{text dfs1}, for any @{text \"x \\<in> roots\"} such that\n      @{text \"num e x = -1\"}.\\<close>\n  assumes \"dfs_pre roots e\" and \"x \\<in> roots\" and \"num e x = -1\"\n  shows \"dfs1_pre x e\"\n  using assms unfolding dfs_pre_def dfs1_pre_def wf_env_def wf_num_def by auto\n\ntext \\<open>\n  Prove the post-condition of @{text dfs1} for the ``then'' branch\n  in the definition of @{text dfs1}, assuming that the recursive call\n  to @{text dfs} establishes its post-condition.\n\\<close>\nlemma dfs_post_dfs1_post_case1:\n  fixes x e\n  defines \"res1 \\<equiv> dfs (successors x) (add_stack_incr x e)\"\n  defines \"n1 \\<equiv> fst res1\"\n  defines \"e1 \\<equiv> snd res1\"\n  defines \"res \\<equiv> dfs1 x e\"\n  assumes pre: \"dfs1_pre x e\"\n      and post: \"dfs_post (successors x) (add_stack_incr x e) res1\"\n      and lt: \"fst res1 < int (sn e)\"\n  shows \"dfs1_post x e res\"\nproof -\n  let ?e' = \"add_black x e1\"\n  from pre have dom: \"dfs1_dfs_dom (Inl (x, e))\"\n    by (rule dfs1_pre_dfs1_dom)\n  from lt dom have dfs1: \"res = (n1, ?e')\"\n    by (simp add: res1_def n1_def e1_def res_def case_prod_beta dfs1.psimps)\n  from post have wf_env1: \"wf_env e1\"\n    unfolding dfs_post_def e1_def by auto\n  from post obtain s where s: \"stack e1 = s @ stack (add_stack_incr x e)\"\n    unfolding e1_def by (blast intro: dfs_post_stack)\n  from post have x_e1: \"x \\<in> set (stack e1)\"\n    by (auto intro: dfs_post_stack simp: e1_def add_stack_incr_def)\n  from post have se1: \"subenv (add_stack_incr x e) e1\"\n    unfolding dfs_post_def by (simp add: e1_def split_def)\n  from pre lt post obtain g where\n    g: \"g \\<noteq> x\" \"g \\<in> gray e1\" \"x \\<preceq> g in (stack e1)\" \n       \"reachable x g\" \"reachable g x\"\n    unfolding e1_def using dfs_post_reach_gray dfs1_pre_def by blast\n\n  have wf_env': \"wf_env ?e'\"\n  proof -\n    from wf_env1 dfs1_pre_domain[OF pre] x_e1 have \"wf_color ?e'\"\n      by (auto simp: dfs_pre_def wf_env_def wf_color_def add_black_def colored_def)\n    moreover\n    from se1\n    have \"x \\<in> gray e1\" \"colored ?e' = colored e1\"\n      by (auto simp: subenv_def add_stack_incr_def add_black_def colored_def)\n    with wf_env1 have \"wf_num ?e'\"\n      unfolding dfs_pre_def wf_env_def wf_num_def add_black_def by auto\n    moreover\n    from post wf_env1 have \"no_black_to_white ?e'\"\n      unfolding dfs_post_def wf_env_def no_black_to_white_def \n                add_black_def e1_def subenv_def colored_def\n      by auto\n    moreover\n    {\n      fix y\n      assume \"y \\<in> set (stack ?e')\"\n      hence y: \"y \\<in> set (stack e1)\" by (simp add: add_black_def)\n      with wf_env1 obtain z where \n        z: \"z \\<in> gray e1\"\n           \"y \\<preceq> z in stack e1\"\n           \"reachable y z\"\n        unfolding wf_env_def by blast\n      have \"\\<exists>g \\<in> gray ?e'.\n             y \\<preceq> g in (stack ?e') \\<and> reachable y g\"\n      proof (cases \"z \\<in> gray ?e'\")\n        case True with z show ?thesis by (auto simp: add_black_def)\n      next\n        case False\n        with z have \"z = x\" by (simp add: add_black_def)\n        with g z wf_env1 show ?thesis\n          unfolding wf_env_def add_black_def\n          by (auto elim: reachable_trans precedes_trans)\n      qed\n    }\n    moreover\n    have \"sccs ?e' = {C . C \\<subseteq> black ?e' \\<and> is_scc C}\"\n    proof -\n      {\n        fix C\n        assume \"C \\<in> sccs ?e'\"\n        with post have \"is_scc C \\<and> C \\<subseteq> black ?e'\"\n          unfolding dfs_post_def wf_env_def add_black_def e1_def by auto\n      }\n      moreover\n      {\n        fix C\n        assume C: \"is_scc C\" \"C \\<subseteq> black ?e'\"\n        have \"x \\<notin> C\"\n        proof\n          assume xC: \"x \\<in> C\"\n          with \\<open>is_scc C\\<close> g have \"g \\<in> C\"\n            unfolding is_scc_def by (auto dest: subscc_add)\n          with wf_env1 g \\<open>C \\<subseteq> black ?e'\\<close>  show \"False\"\n            unfolding wf_env_def wf_color_def add_black_def by auto\n        qed\n        with post C have \"C \\<in> sccs ?e'\"\n          unfolding dfs_post_def wf_env_def add_black_def e1_def by auto\n      }\n      ultimately show ?thesis by blast\n    qed\n\n    ultimately show ?thesis  \\<comment> \\<open>the remaining conjuncts carry over trivially\\<close>\n      using wf_env1 unfolding wf_env_def add_black_def by auto\n  qed\n\n  from pre have \"x \\<notin> set (stack e)\" \"x \\<notin> gray e\"\n    unfolding dfs1_pre_def wf_env_def wf_color_def colored_def by auto\n  with se1 have subenv': \"subenv e ?e'\"\n    unfolding subenv_def add_stack_incr_def add_black_def\n    by (auto split: if_split_asm)\n\n  have xblack': \"x \\<in> black ?e'\"\n    unfolding add_black_def by simp\n\n  from lt have \"n1 < num (add_stack_incr x e) x\"\n    unfolding add_stack_incr_def n1_def by simp\n  also have \"\\<dots> = num e1 x\"\n    using se1 unfolding subenv_def add_stack_incr_def by auto\n  finally have xnum': \"n1 \\<le> num ?e' x\"\n    unfolding add_black_def by simp\n\n  from lt pre have \"n1 \\<noteq> \\<infinity>\"\n    unfolding dfs1_pre_def wf_env_def wf_num_def n1_def by simp\n  with post obtain sx y where\n    \"sx \\<in> successors x\" \"y \\<in> set (stack ?e')\" \"num ?e' y = n1\" \"reachable sx y\"\n    unfolding dfs_post_def add_black_def n1_def e1_def by auto\n  with dfs1_pre_domain[OF pre] \n  have n1': \"\\<exists>y \\<in> set (stack ?e'). num ?e' y = n1 \\<and> reachable x y\"\n    by (auto intro: reachable_trans)\n\n  {\n    fix y\n    assume \"xedge_to (stack ?e') (stack e) y\"\n    then obtain zs z where\n      y: \"stack ?e' = zs @ (stack e)\" \"z \\<in> set zs\" \"y \\<in> set (stack e)\" \"edge z y\"\n      unfolding xedge_to_def by auto\n    have \"n1 \\<le> num ?e' y\"\n    proof (cases \"z=x\")\n      case True\n      with \\<open>edge z y\\<close> post show ?thesis\n        unfolding dfs_post_def add_black_def n1_def e1_def by auto\n    next\n      case False\n      with s y have \"xedge_to (stack e1) (stack (add_stack_incr x e)) y\"\n        unfolding xedge_to_def add_black_def add_stack_incr_def by auto\n      with post show ?thesis\n        unfolding dfs_post_def add_black_def n1_def e1_def by auto\n    qed\n  }\n\n  with dfs1 wf_env' subenv' xblack' xnum' n1'\n  show ?thesis unfolding dfs1_post_def by simp\nqed\n\ntext \\<open>\n  Prove the post-condition of @{text dfs1} for the ``else'' branch\n  in the definition of @{text dfs1}, assuming that the recursive call\n  to @{text dfs} establishes its post-condition.\n\\<close>\nlemma dfs_post_dfs1_post_case2:\n  fixes x e\n  defines \"res1 \\<equiv> dfs (successors x) (add_stack_incr x e)\"\n  defines \"n1 \\<equiv> fst res1\"\n  defines \"e1 \\<equiv> snd res1\"\n  defines \"res \\<equiv> dfs1 x e\"\n  assumes pre: \"dfs1_pre x e\"\n      and post: \"dfs_post (successors x) (add_stack_incr x e) res1\"\n      and nlt: \"\\<not>(n1 < int (sn e))\"\n  shows \"dfs1_post x e res\"\nproof -\n  let ?split = \"split_list x (stack e1)\"\n  let ?e' = \"\\<lparr> black = insert x (black e1),\n               gray = gray e,\n               stack = snd ?split,\n               sccs = insert (set (fst ?split)) (sccs e1),\n               sn = sn e1,\n               num = set_infty (fst ?split) (num e1) \\<rparr>\"\n  from pre have dom: \"dfs1_dfs_dom (Inl (x, e))\"\n    by (rule dfs1_pre_dfs1_dom)\n  from dom nlt have res: \"res = (\\<infinity>, ?e')\"\n    by (simp add: res1_def n1_def e1_def res_def case_prod_beta dfs1.psimps)\n  from post have wf_e1: \"wf_env e1\" \"subenv (add_stack_incr x e) e1\" \n                        \"successors x \\<subseteq> colored e1\"\n    by (auto simp: dfs_post_def e1_def)\n  hence gray': \"gray e1 = insert x (gray e)\"\n    by (auto simp: subenv_def add_stack_incr_def)\n  from post obtain l where\n    l: \"fst ?split = l @ [x]\"\n       \"x \\<notin> set l\"\n       \"set l \\<subseteq> black e1\"\n       \"stack e1 = fst ?split @ snd ?split\"\n       \"is_subscc (set (fst ?split))\"\n       \"snd ?split = stack e\"\n    unfolding e1_def by (blast intro: dfs_post_split)\n  hence x: \"x \\<in> set (stack e1)\" by auto\n  from l have stack: \"set (stack e) \\<subseteq> set (stack e1)\" by auto\n  from wf_e1 l \n  have dist: \"x \\<notin> set l\"    \"x \\<notin> set (stack e)\" \n             \"set l \\<inter> set (stack e) = {}\"   \n             \"set (fst ?split) \\<inter> set (stack e) = {}\"\n    unfolding wf_env_def by auto\n  with \\<open>stack e1 = fst ?split @ snd ?split\\<close> \\<open>snd ?split = stack e\\<close>\n  have prec: \"\\<forall>y \\<in> set (stack e). \\<forall>z. y \\<preceq> z in (stack e1) \\<longleftrightarrow> y \\<preceq> z in (stack e)\"\n    by (metis precedes_append_left_iff Int_iff empty_iff) \n  from post have numx: \"num e1 x = int (sn e)\"\n    unfolding dfs_post_def subenv_def add_stack_incr_def e1_def by auto\n\n  text \\<open>\n    All nodes contained in the same SCC as @{text x} are elements of \n    @{text \"fst ?split\"}. Therefore, @{text \"set (fst ?split)\"} constitutes an SCC.\\<close>\n  {\n    fix y\n    assume xy: \"reachable x y\" and yx: \"reachable y x\"\n       and y: \"y \\<notin> set (fst ?split)\"\n    from l(1) have \"x \\<in> set (fst ?split)\" by simp\n    with xy y obtain x' y' where\n      y': \"reachable x x'\" \"edge x' y'\" \"reachable y' y\"\n          \"x' \\<in> set (fst ?split)\" \"y' \\<notin> set (fst ?split)\"\n      using reachable_crossing_set by metis\n    with wf_e1 l have \"y' \\<in> colored e1\"\n      unfolding wf_env_def no_black_to_white_def by auto\n    from \\<open>reachable x x'\\<close> \\<open>edge x' y'\\<close> have \"reachable x y'\"\n      using reachable_succ reachable_trans by blast\n    moreover\n    from \\<open>reachable y' y\\<close> \\<open>reachable y x\\<close> have \"reachable y' x\"\n      by (rule reachable_trans)\n    ultimately have \"y' \\<notin> \\<Union> (sccs e1)\"\n      using wf_e1 gray'\n      by (auto simp: wf_env_def wf_color_def dest: sccE) \n    with wf_e1 \\<open>y' \\<in> colored e1\\<close> have y'e1: \"y' \\<in> set (stack e1)\"\n      unfolding wf_env_def wf_color_def e1_def colored_def by auto\n    with y' l have y'e: \"y' \\<in> set (stack e)\" by auto\n    with y' post l have numy': \"n1 \\<le> num e1 y'\"\n      unfolding dfs_post_def e1_def n1_def xedge_to_def add_stack_incr_def\n      by force\n    with numx nlt have \"num e1 x \\<le> num e1 y'\" by auto\n    with y'e1 x wf_e1 have \"y' \\<preceq> x in stack e1\"\n      unfolding wf_env_def wf_num_def e1_def n1_def by auto\n    with y'e have \"y' \\<preceq> x in stack e\" by (auto simp: prec)\n    with dist have \"False\" by (simp add: precedes_mem)\n  }\n  hence \"\\<forall>y. reachable x y \\<and> reachable y x \\<longrightarrow> y \\<in> set (fst ?split)\"\n    by blast\n  with l have scc: \"is_scc (set (fst ?split))\"\n    by (simp add: is_scc_def is_subscc_def subset_antisym subsetI)\n\n  have wf_e': \"wf_env ?e'\"\n  proof -\n    have wfc: \"wf_color ?e'\"\n    proof -\n      from post dfs1_pre_domain[OF pre] l\n      have \"gray ?e' \\<subseteq> vertices \\<and> black ?e' \\<subseteq> vertices \n           \\<and> gray ?e' \\<inter> black ?e' = {}\n           \\<and> (\\<Union> (sccs ?e')) \\<subseteq> black ?e'\"\n        by (auto simp: dfs_post_def wf_env_def wf_color_def e1_def subenv_def\n                       add_stack_incr_def colored_def)\n      moreover\n      have \"set (stack ?e') = gray ?e' \\<union> (black ?e' - \\<Union> (sccs ?e'))\" (is \"?lhs = ?rhs\")\n      proof\n        from wf_e1 dist l show \"?lhs \\<subseteq> ?rhs\"\n          by (auto simp: wf_env_def wf_color_def e1_def subenv_def \n                         add_stack_incr_def colored_def)\n      next\n        from l have \"stack ?e' = stack e\" \"gray ?e' = gray e\" by simp+\n        moreover\n        from pre have \"gray e \\<subseteq> set (stack e)\"\n          unfolding dfs1_pre_def wf_env_def wf_color_def by auto\n        moreover\n        {\n          fix v\n          assume \"v \\<in> black ?e' - \\<Union> (sccs ?e')\"\n          with l wf_e1\n          have \"v \\<in> black e1\" \"v \\<notin> \\<Union> (sccs e1)\" \"v \\<notin> insert x (set l)\" \n               \"v \\<in> set (stack e1)\"\n            unfolding wf_env_def wf_color_def by auto\n          with l have \"v \\<in> set (stack e)\" by auto\n        }\n        ultimately show \"?rhs \\<subseteq> ?lhs\" by auto\n      qed\n      ultimately show ?thesis\n        unfolding wf_color_def colored_def by blast\n    qed\n    moreover\n    from wf_e1 l dist prec gray' have \"wf_num ?e'\"\n      unfolding wf_env_def wf_num_def colored_def\n      by (auto simp: set_infty)\n    moreover \n    from wf_e1 gray' have \"no_black_to_white ?e'\"\n      by (auto simp: wf_env_def no_black_to_white_def colored_def)\n    moreover \n    from wf_e1 l have \"distinct (stack ?e')\"\n      unfolding wf_env_def by auto\n    moreover \n    from wf_e1 prec\n    have \"\\<forall>y z. y \\<preceq> z in (stack e) \\<longrightarrow> reachable z y\"\n      unfolding wf_env_def by (metis precedes_mem(1))\n    moreover\n    from wf_e1 prec stack dfs1_pre_domain[OF pre] gray'\n    have \"\\<forall>y \\<in> set (stack e). \\<exists>g \\<in> gray e. y \\<preceq> g in (stack e) \\<and> reachable y g\"\n      unfolding wf_env_def by (metis insert_iff subsetCE precedes_mem(2))\n    moreover\n    from wf_e1 l scc have \"sccs ?e' = {C . C \\<subseteq> black ?e' \\<and> is_scc C}\"\n      by (auto simp: wf_env_def dest: scc_partition)\n    ultimately show ?thesis\n      using l unfolding wf_env_def by simp\n  qed\n\n  from post l dist have sub: \"subenv e ?e'\"\n    unfolding dfs_post_def subenv_def e1_def add_stack_incr_def\n    by (auto simp: set_infty)\n\n  from l have num: \"\\<infinity> \\<le> num ?e' x\"\n    by (auto simp: set_infty)\n\n  from l have \"\\<forall>y. xedge_to (stack ?e') (stack e) y \\<longrightarrow> \\<infinity> \\<le> num ?e' y\"\n    unfolding xedge_to_def by auto\n\n  with res wf_e' sub num show ?thesis\n    unfolding dfs1_post_def res_def by simp\nqed\n\ntext \\<open>\n  The following main lemma establishes the partial correctness\n  of the two mutually recursive functions. The domain conditions\n  appear explicitly as hypotheses, although we already know that\n  they are subsumed by the preconditions. They are needed for the\n  application of the ``partial induction'' rule generated by\n  Isabelle for recursive functions whose termination was not proved.\n  We will remove them in the next step.\n\\<close>\n\nlemma dfs_partial_correct:\n  fixes x roots e\n  shows\n  \"\\<lbrakk>dfs1_dfs_dom (Inl(x,e)); dfs1_pre x e\\<rbrakk> \\<Longrightarrow> dfs1_post x e (dfs1 x e)\"\n  \"\\<lbrakk>dfs1_dfs_dom (Inr(roots,e)); dfs_pre roots e\\<rbrakk> \\<Longrightarrow> dfs_post roots e (dfs roots e)\"\nproof (induct rule: dfs1_dfs.pinduct)\n  fix x e\n  let ?res1 = \"dfs1 x e\"\n  let ?res' = \"dfs (successors x) (add_stack_incr x e)\"\n  assume ind: \"dfs_pre (successors x) (add_stack_incr x e)\n           \\<Longrightarrow> dfs_post (successors x) (add_stack_incr x e) ?res'\"\n     and pre: \"dfs1_pre x e\"\n  have post: \"dfs_post (successors x) (add_stack_incr x e) ?res'\"\n    by (rule ind) (rule dfs1_pre_dfs_pre[OF pre])\n  show \"dfs1_post x e ?res1\"\n  proof (cases \"fst ?res' < int (sn e)\")\n    case True with pre post show ?thesis by (rule dfs_post_dfs1_post_case1)\n  next\n    case False\n    with pre post show ?thesis by (rule dfs_post_dfs1_post_case2)\n  qed\nnext\n  fix roots e\n  let ?res' = \"dfs roots e\"\n  let ?dfs1 = \"\\<lambda>x. dfs1 x e\"\n  let ?dfs = \"\\<lambda>x e'. dfs (roots - {x}) e'\"\n  assume ind1: \"\\<And>x. \\<lbrakk> roots \\<noteq> {}; x = (SOME x. x \\<in> roots);\n                          \\<not> num e x \\<noteq> - 1; dfs1_pre x e \\<rbrakk>\n                \\<Longrightarrow> dfs1_post x e (?dfs1 x)\"\n     and ind': \"\\<And>x res1.\n                  \\<lbrakk> roots \\<noteq> {}; x = (SOME x. x \\<in> roots);\n                    res1 = (if num e x \\<noteq> - 1 then (num e x, e) else ?dfs1 x);\n                    dfs_pre (roots - {x}) (snd res1) \\<rbrakk>\n               \\<Longrightarrow> dfs_post (roots - {x}) (snd res1) (?dfs x (snd res1))\"\n     and pre: \"dfs_pre roots e\"\n  from pre have dom: \"dfs1_dfs_dom (Inr (roots, e))\"\n    by (rule dfs_pre_dfs_dom)\n  show \"dfs_post roots e ?res'\"\n  proof (cases \"roots = {}\")\n    case True\n    with pre dom show ?thesis\n      unfolding dfs_pre_def dfs_post_def subenv_def xedge_to_def\n      by (auto simp: dfs.psimps)\n  next\n    case nempty: False\n    define x where \"x = (SOME x. x \\<in> roots)\"\n    with nempty have x: \"x \\<in> roots\" by (auto intro: someI)\n    define res1 where\n      \"res1 = (if num e x \\<noteq> - 1 then (num e x, e) else ?dfs1 x)\"\n    define res2 where\n      \"res2 = ?dfs x (snd res1)\"\n    have post1: \"num e x = -1 \\<longrightarrow> dfs1_post x e (?dfs1 x)\"\n    proof\n      assume num: \"num e x = -1\"\n      with pre x have \"dfs1_pre x e\"\n        by (rule dfs_pre_dfs1_pre)\n      with nempty num x_def show \"dfs1_post x e (?dfs1 x)\"\n        by (simp add: ind1)\n    qed\n    have sub1: \"subenv e (snd res1)\"\n    proof (cases \"num e x = -1\")\n      case True\n      with post1 res1_def show ?thesis\n        by (auto simp: dfs1_post_def)\n    next\n      case False\n      with res1_def show ?thesis by simp\n    qed\n    have wf1: \"wf_env (snd res1)\"\n    proof (cases \"num e x = -1\")\n      case True\n      with res1_def post1 show ?thesis\n        by (auto simp: dfs1_post_def)\n    next\n      case False\n      with res1_def pre show ?thesis\n        by (auto simp: dfs_pre_def)\n    qed\n    from post1 pre res1_def\n    have res1: \"dfs_pre (roots - {x}) (snd res1)\"\n      unfolding dfs_pre_def dfs1_post_def subenv_def by auto\n    with nempty x_def res1_def ind'\n    have post: \"dfs_post (roots - {x}) (snd res1) (?dfs x (snd res1))\"\n      by blast\n    with res2_def have sub2: \"subenv (snd res1) (snd res2)\"\n      by (auto simp: dfs_post_def)\n    from post res2_def have wf2: \"wf_env (snd res2)\"\n      by (auto simp: dfs_post_def)\n    from dom nempty x_def res1_def res2_def\n    have res: \"dfs roots e = (min (fst res1) (fst res2), snd res2)\"\n      by (auto simp add: dfs.psimps)\n    show ?thesis\n    proof -\n      let ?n2 = \"min (fst res1) (fst res2)\"\n      let ?e2 = \"snd res2\"\n\n      from post res2_def \n      have \"wf_env ?e2\"\n        unfolding dfs_post_def by auto\n\n      moreover\n      from sub1 sub2 have sub: \"subenv e ?e2\"\n        by (rule subenv_trans)\n\n      moreover\n      have \"x \\<in> colored ?e2\"\n      proof (cases \"num e x = -1\")\n        case True\n        with post1 res1_def sub2 show ?thesis\n          by (auto simp: dfs1_post_def subenv_def colored_def)\n      next\n        case False\n        with pre sub show ?thesis\n          by (auto simp: dfs_pre_def wf_env_def wf_num_def subenv_def colored_def)\n      qed\n      with post res2_def have \"roots \\<subseteq> colored ?e2\"\n        unfolding dfs_post_def by auto\n\n      moreover\n      have \"\\<forall>y \\<in> roots. ?n2 \\<le> num ?e2 y\"\n      proof\n        fix y\n        assume y: \"y \\<in> roots\"\n        show \"?n2 \\<le> num ?e2 y\"\n        proof (cases \"y = x\")\n          case True\n          show ?thesis\n          proof (cases \"num e x = -1\")\n            case True\n            with post1 res1_def have \"fst res1 \\<le> num (snd res1) x\"\n              unfolding dfs1_post_def by auto\n            moreover\n            from wf1 wf2 sub2 have \"num (snd res1) x \\<le> num (snd res2) x\"\n              unfolding wf_env_def by (auto elim: subenv_num)\n            ultimately show ?thesis\n              using \\<open>y=x\\<close> by simp\n          next\n            case False\n            with res1_def wf1 wf2 sub2 have \"fst res1 \\<le> num (snd res2) x\"\n              unfolding wf_env_def by (auto elim: subenv_num)\n            with \\<open>y=x\\<close> show ?thesis by simp\n          qed\n        next\n          case False\n          with y post res2_def have \"fst res2 \\<le> num ?e2 y\"\n            unfolding dfs_post_def by auto\n          thus ?thesis by simp\n        qed\n      qed\n\n      moreover\n      {\n        assume n2: \"?n2 \\<noteq> \\<infinity>\"\n        hence \"(fst res1 \\<noteq> \\<infinity> \\<and> ?n2 = fst res1)\n             \\<or> (fst res2 \\<noteq> \\<infinity> \\<and> ?n2 = fst res2)\" by auto\n        hence \"\\<exists>r \\<in> roots. \\<exists>y \\<in> set (stack ?e2). num ?e2 y = ?n2 \\<and> reachable r y\"\n        proof\n          assume n2: \"fst res1 \\<noteq> \\<infinity> \\<and> ?n2 = fst res1\"\n          have \"\\<exists>y \\<in> set (stack (snd res1)). \n                     num (snd res1) y = (fst res1) \\<and> reachable x y\"\n          proof (cases \"num e x = -1\")\n            case True\n            with post1 res1_def n2 show ?thesis\n              unfolding dfs1_post_def by auto\n          next\n            case False\n            with wf1 res1_def n2 have \"x \\<in> set (stack (snd res1))\"\n              unfolding wf_env_def wf_color_def wf_num_def colored_def by auto\n            with False res1_def show ?thesis\n              by auto\n          qed\n          with sub2 x n2 show ?thesis\n            unfolding subenv_def by fastforce\n        next\n          assume \"fst res2 \\<noteq> \\<infinity> \\<and> ?n2 = fst res2\"\n          with post res2_def show ?thesis\n            unfolding dfs_post_def by auto\n        qed\n      }\n      hence \"?n2 = \\<infinity> \\<or> (\\<exists>r \\<in> roots. \\<exists>y \\<in> set (stack ?e2). num ?e2 y = ?n2 \\<and> reachable r y)\"\n        by blast\n\n      moreover\n      have \"\\<forall>y. xedge_to (stack ?e2) (stack e) y \\<longrightarrow> ?n2 \\<le> num ?e2 y\"\n      proof (clarify)\n        fix y\n        assume y: \"xedge_to (stack ?e2) (stack e) y\"\n        show \"?n2 \\<le> num ?e2 y\"\n        proof (cases \"num e x = -1\")\n          case True\n          from sub1 obtain s1 where\n            s1: \"stack (snd res1) = s1 @ stack e\"\n            by (auto simp: subenv_def)\n          from sub2 obtain s2 where\n            s2: \"stack ?e2 = s2 @ stack (snd res1)\"\n            by (auto simp: subenv_def)\n          from y obtain zs z where\n            z: \"stack ?e2 = zs @ stack e\" \"z \\<in> set zs\" \n               \"y \\<in> set (stack e)\" \"edge z y\"\n            by (auto simp: xedge_to_def)\n          with s1 s2 have \"z \\<in> (set s1) \\<union> (set s2)\" by auto\n          thus ?thesis\n          proof\n            assume \"z \\<in> set s1\"\n            with s1 z have \"xedge_to (stack (snd res1)) (stack e) y\"\n              by (auto simp: xedge_to_def)\n            with post1 res1_def \\<open>num e x = -1\\<close>\n            have \"fst res1 \\<le> num (snd res1) y\"\n              by (auto simp: dfs1_post_def)\n            moreover\n            with wf1 wf2 sub2 have \"num (snd res1) y \\<le> num ?e2 y\"\n              unfolding wf_env_def by (auto elim: subenv_num)\n            ultimately show ?thesis by simp\n          next\n            assume \"z \\<in> set s2\"\n            with s1 s2 z have \"xedge_to (stack ?e2) (stack (snd res1)) y\"\n              by (auto simp: xedge_to_def)\n            with post res2_def show ?thesis\n              by (auto simp: dfs_post_def)\n          qed\n        next\n          case False\n          with y post res1_def res2_def show ?thesis\n            unfolding dfs_post_def by auto\n        qed\n      qed\n\n      ultimately show ?thesis\n        using res unfolding dfs_post_def by simp\n    qed\n  qed\nqed\n\nsection \\<open>Theorems establishing total correctness\\<close>\n\ntext \\<open>\n  Combining the previous theorems, we show total correctness for\n  both the auxiliary functions and the main function @{text tarjan}.\n\\<close>\n\ntheorem dfs_correct:\n  \"dfs1_pre x e \\<Longrightarrow> dfs1_post x e (dfs1 x e)\"\n  \"dfs_pre roots e \\<Longrightarrow> dfs_post roots e (dfs roots e)\"\n  using dfs_partial_correct dfs1_pre_dfs1_dom dfs_pre_dfs_dom by (blast+)\n\ntheorem tarjan_correct: \"tarjan = { C . is_scc C \\<and> C \\<subseteq> vertices }\"\nproof -\n  have \"dfs_pre vertices init_env\"\n    by (auto simp: dfs_pre_def init_env_def wf_env_def wf_color_def colored_def\n                   wf_num_def no_black_to_white_def is_scc_def precedes_def)\n  hence res: \"dfs_post vertices init_env (dfs vertices init_env)\"\n    by (rule dfs_correct)\n  thus ?thesis\n    by (auto simp: tarjan_def init_env_def dfs_post_def wf_env_def wf_color_def \n                   colored_def subenv_def)\nqed\n\nend \\<comment> \\<open>context graph\\<close>\nend \\<comment> \\<open>theory Tarjan\\<close>\n", "meta": {"author": "VTrelat", "repo": "Tarjan", "sha": "33564d34be43189a76b2e6e4ffbcd6fe540c4ed2", "save_path": "github-repos/isabelle/VTrelat-Tarjan", "path": "github-repos/isabelle/VTrelat-Tarjan/Tarjan-33564d34be43189a76b2e6e4ffbcd6fe540c4ed2/Isabelle/Tarjan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7681121631796631}}
{"text": "theory Height\n  imports \"HOL-Nominal.Nominal\"\nbegin\n\ntext \\<open>\n  A small problem suggested by D. Wang. It shows how\n  the height of a lambda-terms behaves under substitution.\n\\<close>\n\natom_decl name\n\nnominal_datatype lam = \n    Var \"name\"\n  | App \"lam\" \"lam\"\n  | Lam \"\\<guillemotleft>name\\<guillemotright>lam\" (\"Lam [_]._\" [100,100] 100)\n\ntext \\<open>Definition of the height-function on lambda-terms.\\<close> \n\nnominal_primrec\n  height :: \"lam \\<Rightarrow> int\"\nwhere\n  \"height (Var x) = 1\"\n| \"height (App t1 t2) = (max (height t1) (height t2)) + 1\"\n| \"height (Lam [a].t) = (height t) + 1\"\n  apply(finite_guess add: perm_int_def)+\n  apply(rule TrueI)+\n  apply(simp add: fresh_int)\n  apply(fresh_guess add: perm_int_def)+\n  done\n\ntext \\<open>Definition of capture-avoiding substitution.\\<close>\n\nnominal_primrec\n  subst :: \"lam \\<Rightarrow> name \\<Rightarrow> lam \\<Rightarrow> lam\"  (\"_[_::=_]\" [100,100,100] 100)\nwhere\n  \"(Var x)[y::=t'] = (if x=y then t' else (Var x))\"\n| \"(App t1 t2)[y::=t'] = App (t1[y::=t']) (t2[y::=t'])\"\n| \"\\<lbrakk>x\\<sharp>y; x\\<sharp>t'\\<rbrakk> \\<Longrightarrow> (Lam [x].t)[y::=t'] = Lam [x].(t[y::=t'])\"\napply(finite_guess)+\napply(rule TrueI)+\napply(simp add: abs_fresh)\napply(fresh_guess)+\ndone\n\ntext\\<open>The next lemma is needed in the Var-case of the theorem below.\\<close>\n\nlemma height_ge_one: \n  shows \"1 \\<le> (height e)\"\nby (nominal_induct e rule: lam.strong_induct) (simp_all)\n\ntext \\<open>\n  Unlike the proplem suggested by Wang, however, the \n  theorem is here formulated entirely by using functions. \n\\<close>\n\ntheorem height_subst:\n  shows \"height (e[x::=e']) \\<le> ((height e) - 1) + (height e')\"\nproof (nominal_induct e avoiding: x e' rule: lam.strong_induct)\n  case (Var y)\n  have \"1 \\<le> height e'\" by (rule height_ge_one)\n  then show \"height (Var y[x::=e']) \\<le> height (Var y) - 1 + height e'\" by simp\nnext\n  case (Lam y e1)\n  hence ih: \"height (e1[x::=e']) \\<le> ((height e1) - 1) + (height e')\" by simp\n  moreover\n  have vc: \"y\\<sharp>x\" \"y\\<sharp>e'\" by fact+ (* usual variable convention *)\n  ultimately show \"height ((Lam [y].e1)[x::=e']) \\<le> height (Lam [y].e1) - 1 + height e'\" by simp\nnext    \n  case (App e1 e2)\n  hence ih1: \"height (e1[x::=e']) \\<le> ((height e1) - 1) + (height e')\" \n    and ih2: \"height (e2[x::=e']) \\<le> ((height e2) - 1) + (height e')\" by simp_all\n  then show \"height ((App e1 e2)[x::=e']) \\<le> height (App e1 e2) - 1 + height e'\"  by simp \nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Nominal/Examples/Height.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7680940577890008}}
{"text": "theory ExF012\n  imports Main \nbegin \n  \n  \nlemma \"(\\<forall>x. (P x \\<longrightarrow> Q x)) \\<longrightarrow> (\\<forall>x. (Q x \\<longrightarrow> R x)) \\<longrightarrow> (\\<forall>x .(P x \\<longrightarrow> R x))\"  \nproof - \n  {\n    assume a:\"\\<forall>x. (P x \\<longrightarrow> Q x)\"\n    {\n      assume b:\"\\<forall>x. (Q x \\<longrightarrow> R x)\"\n      {\n        fix aa \n        {\n          assume c:\"P aa\"\n          from b have e:\"Q aa \\<longrightarrow> R aa\" by (rule allE)\n          from a have d:\"P aa \\<longrightarrow> Q aa\" by (rule allE)\n          from this and c have \"Q aa\" by (rule mp)\n          with e have \"R aa\" by (rule mp)\n        }\n        hence \"P aa \\<longrightarrow> R aa\" by (rule impI)\n      }\n      hence \"\\<forall>x. (P x \\<longrightarrow> R x)\" by (rule allI)\n    }\n    hence \"(\\<forall>x. (Q x \\<longrightarrow> R x)) \\<longrightarrow>(\\<forall>x. (P x \\<longrightarrow> R x))\" by (rule impI)\n  }\n  thus ?thesis by (rule impI)\nqed\n  \n  \n              ", "meta": {"author": "SvenWille", "repo": "LogicForwardProofs", "sha": "b03c110b073eb7c34a561fce94b860b14cde75f7", "save_path": "github-repos/isabelle/SvenWille-LogicForwardProofs", "path": "github-repos/isabelle/SvenWille-LogicForwardProofs/LogicForwardProofs-b03c110b073eb7c34a561fce94b860b14cde75f7/src/FOL/ExF012.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9532750453562491, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.7679890681645545}}
{"text": "(******************************************************************************)\n(* Project: Isabelle/UTP Toolkit                                              *)\n(* File: FSet_Extra.thy                                                       *)\n(* Authors: Frank Zeyda and Simon Foster (University of York, UK)             *)\n(* Emails: frank.zeyda@york.ac.uk and simon.foster@york.ac.uk                 *)\n(******************************************************************************)\n\nsection \\<open>Finite Sets: extra functions and properties\\<close>\n\ntheory FSet_Extra\nimports\n  \"HOL-Library.FSet\"\n  \"HOL-Library.Countable_Set_Type\"\nbegin\n\nsetup_lifting type_definition_fset\n\nnotation fempty (\"\\<lbrace>\\<rbrace>\")\nnotation fset (\"\\<langle>_\\<rangle>\\<^sub>f\")\nnotation fminus (infixl \"-\\<^sub>f\" 65)\n\nsyntax\n  \"_FinFset\" :: \"args => 'a fset\"    (\"\\<lbrace>(_)\\<rbrace>\")\n\ntranslations\n  \"\\<lbrace>x, xs\\<rbrace>\" == \"CONST finsert x \\<lbrace>xs\\<rbrace>\"\n  \"\\<lbrace>x\\<rbrace>\" == \"CONST finsert x \\<lbrace>\\<rbrace>\"\n\nterm \"fBall\"\n\nsyntax\n  \"_fBall\" :: \"pttrn => 'a fset => bool => bool\" (\"(3\\<forall> _|\\<in>|_./ _)\" [0, 0, 10] 10)\n  \"_fBex\"  :: \"pttrn => 'a fset => bool => bool\" (\"(3\\<exists> _|\\<in>|_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall> x|\\<in>|A. P\" == \"CONST fBall A (%x. P)\"\n  \"\\<exists> x|\\<in>|A. P\" == \"CONST fBex A (%x. P)\"\n\ndefinition FUnion :: \"'a fset fset \\<Rightarrow> 'a fset\" (\"\\<Union>\\<^sub>f_\" [90] 90) where\n\"FUnion xs = Abs_fset (\\<Union>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n\ndefinition FInter :: \"'a fset fset \\<Rightarrow> 'a fset\" (\"\\<Inter>\\<^sub>f_\" [90] 90) where\n\"FInter xs = Abs_fset (\\<Inter>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n\ntext \\<open>Finite power set\\<close>\n\ndefinition FinPow :: \"'a fset \\<Rightarrow> 'a fset fset\" where\n\"FinPow xs = Abs_fset (Abs_fset ` Pow \\<langle>xs\\<rangle>\\<^sub>f)\"\n\ntext \\<open>Set of all finite subsets of a set\\<close>\n\ndefinition Fow :: \"'a set \\<Rightarrow> 'a fset set\" where\n\"Fow A = {x. \\<langle>x\\<rangle>\\<^sub>f \\<subseteq> A}\"\n\ndeclare Abs_fset_inverse [simp]\n\nlemma fset_intro:\n  \"fset x = fset y \\<Longrightarrow> x = y\"\n  by (simp add:fset_inject)\n\nlemma fset_elim:\n  \"\\<lbrakk> x = y; fset x = fset y \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (auto)\n\nlemma fmember_intro:\n  \"\\<lbrakk> x \\<in> fset(xs) \\<rbrakk> \\<Longrightarrow> x |\\<in>| xs\"\n  by (metis fmember.rep_eq)\n\nlemma fmember_elim:\n  \"\\<lbrakk> x |\\<in>| xs; x \\<in> fset(xs) \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (metis fmember.rep_eq)\n\nlemma fnmember_intro [intro]:\n  \"\\<lbrakk> x \\<notin> fset(xs) \\<rbrakk> \\<Longrightarrow> x |\\<notin>| xs\"\n  by (metis fmember.rep_eq)\n\nlemma fnmember_elim [elim]:\n  \"\\<lbrakk> x |\\<notin>| xs; x \\<notin> fset(xs) \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (metis fmember.rep_eq)\n\nlemma fsubset_intro [intro]:\n  \"\\<langle>xs\\<rangle>\\<^sub>f \\<subseteq> \\<langle>ys\\<rangle>\\<^sub>f \\<Longrightarrow> xs |\\<subseteq>| ys\"\n  by (metis less_eq_fset.rep_eq)\n\nlemma fsubset_elim [elim]:\n  \"\\<lbrakk> xs |\\<subseteq>| ys; \\<langle>xs\\<rangle>\\<^sub>f \\<subseteq> \\<langle>ys\\<rangle>\\<^sub>f \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (metis less_eq_fset.rep_eq)\n\nlemma fBall_intro [intro]:\n  \"Ball \\<langle>A\\<rangle>\\<^sub>f P \\<Longrightarrow> fBall A P\"\n  by (metis (poly_guards_query) fBallI fmember.rep_eq)\n\nlemma fBall_elim [elim]:\n  \"\\<lbrakk> fBall A P; Ball \\<langle>A\\<rangle>\\<^sub>f P \\<Longrightarrow> Q \\<rbrakk> \\<Longrightarrow> Q\"\n  by (metis fBallE fmember.rep_eq)\n\nlift_definition finset :: \"'a list \\<Rightarrow> 'a fset\" is set ..\n\ncontext linorder\nbegin\n\nlemma sorted_list_of_set_inj:\n  \"\\<lbrakk> finite xs; finite ys; sorted_list_of_set xs = sorted_list_of_set ys \\<rbrakk>\n   \\<Longrightarrow> xs = ys\"\n  apply (simp add:sorted_list_of_set_def)\n  apply (induct xs rule:finite_induct)\n   apply (induct ys rule:finite_induct)\n    apply (simp_all)\n   apply (metis finite.insertI insert_not_empty sorted_list_of_set_def sorted_list_of_set_empty sorted_list_of_set_eq_Nil_iff)\n  apply (metis finite.insertI finite_list set_remdups set_sort sorted_list_of_set_def sorted_list_of_set_sort_remdups)\n  done\n\ndefinition flist :: \"'a fset \\<Rightarrow> 'a list\" where\n\"flist xs = sorted_list_of_set (fset xs)\"\n\nlemma flist_inj: \"inj flist\"\n  apply (simp add:flist_def inj_on_def)\n  apply (clarify)\n  apply (rename_tac x y)\n  apply (subgoal_tac \"fset x = fset y\")\n   apply (simp add:fset_inject)\n  apply (rule sorted_list_of_set_inj, simp_all)\n  done\n\nlemma flist_props [simp]:\n  \"sorted (flist xs)\"\n  \"distinct (flist xs)\"\n  by (simp_all add:flist_def)\n\nlemma flist_empty [simp]:\n  \"flist \\<lbrace>\\<rbrace> = []\"\n  by (simp add:flist_def)\n\nlemma flist_inv [simp]: \"finset (flist xs) = xs\"\n  by (simp add:finset_def flist_def fset_inverse)\n\nlemma flist_set [simp]: \"set (flist xs) = fset xs\"\n  by (simp add:finset_def flist_def fset_inverse)\n\nlemma fset_inv [simp]: \"\\<lbrakk> sorted xs; distinct xs \\<rbrakk> \\<Longrightarrow> flist (finset xs) = xs\"\n  apply (simp add:finset_def flist_def fset_inverse)\n  apply (metis local.sorted_list_of_set_sort_remdups local.sorted_sort_id remdups_id_iff_distinct)\n  done\n\nlemma fcard_flist:\n  \"fcard xs = length (flist xs)\"\n  apply (simp add:fcard_def)\n  apply (fold flist_set)\n  apply (unfold distinct_card[OF flist_props(2)])\n  apply (rule refl)\n  done\n\nlemma flist_nth:\n  \"i < fcard vs \\<Longrightarrow> flist vs ! i |\\<in>| vs\"\n  apply (simp add: fmember_def flist_def fcard_def)\n  apply (metis fcard.rep_eq fcard_flist finset.rep_eq flist_def flist_inv nth_mem)\n  done\n\ndefinition fmax :: \"'a fset \\<Rightarrow> 'a\" where\n\"fmax xs = (if (xs = \\<lbrace>\\<rbrace>) then undefined else last (flist xs))\"\n\nend\n\ndefinition flists :: \"'a fset \\<Rightarrow> 'a list set\" where\n\"flists A = {xs. distinct xs \\<and> finset xs = A}\"\n\nlemma flists_nonempty: \"\\<exists> xs. xs \\<in> flists A\"\n  apply (simp add: flists_def)\n  apply (metis Abs_fset_cases Abs_fset_inverse finite_distinct_list finite_fset finset.rep_eq)\n  done\n\nlemma flists_elem_uniq: \"\\<lbrakk> x \\<in> flists A; x \\<in> flists B \\<rbrakk> \\<Longrightarrow> A = B\"\n  by (simp add: flists_def)\n\ndefinition flist_arb :: \"'a fset \\<Rightarrow> 'a list\" where\n\"flist_arb A = (SOME xs. xs \\<in> flists A)\"\n\nlemma flist_arb_distinct [simp]: \"distinct (flist_arb A)\"\n  by (metis (mono_tags) flist_arb_def flists_def flists_nonempty mem_Collect_eq someI_ex)\n\nlemma flist_arb_inv [simp]: \"finset (flist_arb A) = A\"\n  by (metis (mono_tags) flist_arb_def flists_def flists_nonempty mem_Collect_eq someI_ex)\n\nlemma flist_arb_inj:\n  \"inj flist_arb\"\n  by (metis flist_arb_inv injI)\n\nlemma flist_arb_lists: \"flist_arb ` Fow A \\<subseteq> lists A\"\n  apply (auto)\n  using Fow_def finset.rep_eq apply fastforce\n  done\n\nlemma countable_Fow:\n  fixes A :: \"'a set\"\n  assumes \"countable A\"\n  shows \"countable (Fow A)\"\nproof -\n  from assms obtain to_nat_list :: \"'a list \\<Rightarrow> nat\" where \"inj_on to_nat_list (lists A)\"\n    by blast\n  thus ?thesis\n    apply (simp add: countable_def)\n    apply (rule_tac x=\"to_nat_list \\<circ> flist_arb\" in exI)\n    apply (rule comp_inj_on)\n     apply (metis flist_arb_inv inj_on_def)\n    apply (simp add: flist_arb_lists subset_inj_on)\n    done\nqed\n\ndefinition flub :: \"'a fset set \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" where\n\"flub A t = (if (\\<forall> a\\<in>A. a |\\<subseteq>| t) then Abs_fset (\\<Union>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f) else t)\"\n\nlemma finite_Union_subsets:\n  \"\\<lbrakk> \\<forall> a \\<in> A. a \\<subseteq> b; finite b \\<rbrakk> \\<Longrightarrow> finite (\\<Union>A)\"\n  by (metis Sup_le_iff finite_subset)\n\nlemma finite_UN_subsets:\n  \"\\<lbrakk> \\<forall> a \\<in> A. B a \\<subseteq> b; finite b \\<rbrakk> \\<Longrightarrow> finite (\\<Union>a\\<in>A. B a)\"\n  by (metis UN_subset_iff finite_subset)\n\nlemma flub_rep_eq:\n  \"\\<langle>flub A t\\<rangle>\\<^sub>f = (if (\\<forall> a\\<in>A. a |\\<subseteq>| t) then (\\<Union>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f) else \\<langle>t\\<rangle>\\<^sub>f)\"\n  apply (subgoal_tac \"(if (\\<forall> a\\<in>A. a |\\<subseteq>| t) then (\\<Union>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f) else \\<langle>t\\<rangle>\\<^sub>f) \\<in> {x. finite x}\")\n   apply (auto simp add:flub_def)\n  apply (rule finite_UN_subsets[of _ _ \"\\<langle>t\\<rangle>\\<^sub>f\"])\n   apply (auto)\n  done\n\ndefinition fglb :: \"'a fset set \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\" where\n\"fglb A t = (if (A = {}) then t else Abs_fset (\\<Inter>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f))\"\n\nlemma fglb_rep_eq:\n  \"\\<langle>fglb A t\\<rangle>\\<^sub>f = (if (A = {}) then \\<langle>t\\<rangle>\\<^sub>f else (\\<Inter>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f))\"\n  apply (subgoal_tac \"(if (A = {}) then \\<langle>t\\<rangle>\\<^sub>f else (\\<Inter>x\\<in>A. \\<langle>x\\<rangle>\\<^sub>f)) \\<in> {x. finite x}\")\n   apply (metis Abs_fset_inverse fglb_def)\n  apply (auto)\n  apply (metis finite_INT finite_fset)\n  done\n\nlemma FinPow_rep_eq [simp]:\n  \"fset (FinPow xs) = {ys. ys |\\<subseteq>| xs}\"\n  apply (subgoal_tac \"finite (Abs_fset ` Pow \\<langle>xs\\<rangle>\\<^sub>f)\")\n   apply (auto simp add: fmember_def FinPow_def)\n   apply (rename_tac x' y')\n   apply (subgoal_tac \"finite x'\")\n    apply (auto)\n   apply (metis finite_fset finite_subset)\n  apply (metis (full_types) Pow_iff fset_inverse imageI less_eq_fset.rep_eq)\n  done\n\nlemma FUnion_rep_eq [simp]:\n  \"\\<langle>\\<Union>\\<^sub>f xs\\<rangle>\\<^sub>f = (\\<Union>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n  by (simp add:FUnion_def)\n\nlemma FInter_rep_eq [simp]:\n  \"xs \\<noteq> \\<lbrace>\\<rbrace> \\<Longrightarrow> \\<langle>\\<Inter>\\<^sub>f xs\\<rangle>\\<^sub>f = (\\<Inter>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\"\n  apply (simp add:FInter_def)\n  apply (subgoal_tac \"finite (\\<Inter>x\\<in>\\<langle>xs\\<rangle>\\<^sub>f. \\<langle>x\\<rangle>\\<^sub>f)\")\n   apply (simp)\n  apply (metis (poly_guards_query) bot_fset.rep_eq fglb_rep_eq finite_fset fset_inverse)\n  done\n\nlemma FUnion_empty [simp]:\n  \"\\<Union>\\<^sub>f \\<lbrace>\\<rbrace> = \\<lbrace>\\<rbrace>\"\n  by (auto simp add:FUnion_def fmember_def)\n\nlemma FinPow_member [simp]:\n  \"xs |\\<in>| FinPow xs\"\n  by (auto simp add:fmember_def)\n\nlemma FUnion_FinPow [simp]:\n  \"\\<Union>\\<^sub>f (FinPow x) = x\"\n  by (auto simp add:fmember_def less_eq_fset_def)\n\nlemma Fow_mem [iff]: \"x \\<in> Fow A \\<longleftrightarrow> \\<langle>x\\<rangle>\\<^sub>f \\<subseteq> A\"\n  by (auto simp add:Fow_def)\n\nlemma Fow_UNIV [simp]: \"Fow UNIV = UNIV\"\n  by (simp add:Fow_def)\n\nlift_definition FMax :: \"('a::linorder) fset \\<Rightarrow> 'a\" is \"Max\" .\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/UTP/toolkit/FSet_Extra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8596637523076224, "lm_q1q2_score": 0.7679457086550309}}
{"text": "chapter \\<open>Examples for IMP++\\<close>\ntheory Examples\nimports IPP_Lib \"~~/src/HOL/Library/Multiset\"\nbegin\n\nlocale Imp_Array_Examples begin\n  unbundle IMP_Syntax          -- \\<open>Syntactic Sugar for IMP Programs. Unbundling this may take some time.\\<close>\n  sublocale Vcg_Aux_Lemmas .   -- \\<open>Library of auxiliary lemmas commonly needed for verification\\<close>\nend  \n  \ncontext Imp_Array_Examples begin\n\nsection \\<open>Common Loop Patterns\\<close>\nsubsection \\<open>Approximate from Below\\<close>\ntext \\<open>Used to invert a monotonic function. \n  We count up, until we overshoot the desired result, \n  then we subtract one. \n\\<close>  \n\ndefinition \"sqrt_prog \\<equiv> \n  CLR r;; \n  r ::= N 1;;\n  WHILE ($r * $r <= $n) DO (\n    r ::= Plus ($r) (N 1)\n  );;\n  r ::= Minus ($r) (N 1)\n  \"\n\ntext \\<open>The invariant states that the \\<open>r-1\\<close> is not too big.\n  When the loop terminates, \\<open>r-1\\<close> is not too big, but \\<open>r\\<close> is already too big,\n  so \\<open>r-1\\<close> is the desired value (rounding down).\n\\<close>\ndefinition Isqrt :: \"int \\<Rightarrow> int \\<Rightarrow> bool\" \n  where \"Isqrt n\\<^sub>0 r \\<equiv> 0\\<le>r \\<and> (r-1)\\<^sup>2 \\<le> n\\<^sub>0\"  \n  \ntext \\<open>Note: Be careful to not accidentally define the invariant \n  over some generic type \\<open>'a\\<close>! \\<close>  \n  \nlemma Isqrt_aux:\n  \"0 \\<le> n\\<^sub>0 \\<Longrightarrow> Isqrt n\\<^sub>0 1\"\n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; r * r \\<le> n\\<^sub>0; Isqrt n\\<^sub>0 r\\<rbrakk> \\<Longrightarrow> Isqrt n\\<^sub>0 (r + 1)\"\n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; \\<not> r * r \\<le> n\\<^sub>0; Isqrt n\\<^sub>0 r\\<rbrakk> \\<Longrightarrow> (r - 1)\\<^sup>2 \\<le> n\\<^sub>0 \\<and> n\\<^sub>0 < r\\<^sup>2\"\n  \"Isqrt n\\<^sub>0 r \\<Longrightarrow> r * r \\<le> n\\<^sub>0 \\<Longrightarrow> r\\<le>n\\<^sub>0\"\n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; \\<not> r * r \\<le> n\\<^sub>0; Isqrt n\\<^sub>0 r\\<rbrakk> \\<Longrightarrow> 0 < r\"\n  apply (auto simp: Isqrt_def power2_eq_square algebra_simps)\n  by (smt combine_common_factor mult_right_mono semiring_normalization_rules(3))\n  \nfind_theorems \"(_(_:=_)) _\"\n\nlemma \"                    \n  \\<Turnstile>\\<^sub>t {\\<lambda>n\\<^sub>0. vars n in n=n\\<^sub>0 \\<and> 0\\<le>n\\<^sub>0}           \n      sqrt_prog \n    {\\<lambda>n\\<^sub>0. vars r n in n=n\\<^sub>0 \\<and> 0\\<le>r \\<and> r\\<^sup>2 \\<le> n\\<^sub>0 \\<and> n\\<^sub>0 < (r+1)\\<^sup>2} mod {''r''}\"\n  unfolding sqrt_prog_def\n  \n  apply (rewrite annot_tinvar[where \n    R=\"measure (\\<lambda>s. nat (s ''n'' 0 + 1 - s ''r'' 0))\" and\n    I=\"\\<lambda>n\\<^sub>0. vars r n in n=n\\<^sub>0 \\<and> 0\\<le>n\\<^sub>0 \\<and> Isqrt n\\<^sub>0 r\n    \"]) \n  supply Isqrt_aux [simp]\n  by vcg\n  \nsubsection \\<open>Count Up\\<close>  \n\ntext \\<open>\n  Counter \\<open>c\\<close> counts from \\<open>0\\<close> to \\<open>n\\<close>, such that loop is executed \\<open>n\\<close> times.\n\\<close>\n\nsubsubsection \\<open>Exponential\\<close>\ndefinition \"exp_prog \\<equiv> \n  CLR c;; CLR r;;  \n  c ::= N 0;;\n  r ::= N 1;;\n  WHILE $c < $n DO (\n    r ::= $r * $b;;\n    c ::= $c + (N 1)\n  )\"\n\ntext \\<open>The invariant states that we have computed the function for the counter value \\<open>c\\<close>:\\<close>  \n  \nabbreviation \"Iexp n\\<^sub>0 b\\<^sub>0 r c \\<equiv> 0\\<le>c \\<and> c\\<le>n\\<^sub>0 \\<and> r = b\\<^sub>0 ^ nat c\"\n  \nlemma \"                                \n  \\<Turnstile>\\<^sub>t {\\<lambda>(n\\<^sub>0,b\\<^sub>0). vars n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0 \\<and> 0\\<le>n\\<^sub>0}  \n       exp_prog \n     {\\<lambda>(n\\<^sub>0,b\\<^sub>0). vars r n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0 \\<and> r = b\\<^sub>0 ^ nat n\\<^sub>0} mod {''c'',''r''}\"\n  unfolding exp_prog_def   \n  apply (rewrite annot_tinvar[where \n    R=\"measure (\\<lambda>s. nat (s ''n'' 0 - s ''c'' 0))\" and \n    I=\"\\<lambda>(n\\<^sub>0,b\\<^sub>0). vars r c n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0 \\<and> Iexp n\\<^sub>0 b\\<^sub>0 r c\"])\n  apply vcg \n  done\n\nsubsubsection \\<open>Factorial\\<close>\n\ndefinition ifact :: \"int \\<Rightarrow> int\" where \"ifact n = (\\<Prod>i=1..n. i)\"\n\n\n\nlemma ifact_simps[simp]:\n  \"i\\<ge>0 \\<Longrightarrow> ifact (i+1) = (i+1)*ifact i\"\n  \"i\\<ge>0 \\<Longrightarrow> ifact (1+i) = (1+i)*ifact i\"\n  \"i\\<le>0 \\<Longrightarrow> ifact i = 1\"\n  unfolding ifact_def\n  by (auto simp: algebra_simps)\n\nlemma ifact_nonzero[simp]: \"ifact n\\<^sub>0 \\<noteq> 0\" unfolding ifact_def by auto\n  \nabbreviation \"fact_prog \\<equiv> \n  CLR r;; CLR c;;\n  r ::= N 1;;\n  c ::= N 0;;\n  WHILE ($c < $n) DO (\n    c ::= $c + N 1;;\n    r ::= $r * $c    \n  )\"\n  \ndefinition \"fact_invar n r c \\<equiv> 0\\<le>c \\<and> c\\<le>n \\<and> r=ifact c\"  \n\nlemma fact_prog_correct: \" \n  \\<Turnstile>\\<^sub>t {\\<lambda>n\\<^sub>0. vars n in n=n\\<^sub>0 \\<and> 0\\<le>n } \n       fact_prog \n    {\\<lambda>n\\<^sub>0. vars n r in n=n\\<^sub>0 \\<and> r = (ifact n\\<^sub>0) } mod {''r'',''c''}\"\n  apply (rewrite annot_tinvar[where \n    I=\"\\<lambda>n\\<^sub>0. vars n r c in n=n\\<^sub>0 \\<and> fact_invar n\\<^sub>0 r c\"\n  and R=\"measure_exp ($n - $c)\"  \n    ])\n  unfolding fact_invar_def\n  by vcg\n  \n  \nsubsubsection \\<open>Square by Sum\\<close>\n\ntext \\<open>We exploit the fact that \\<open>n\\<^sup>2\\<close> is the sum of the first \\<open>n\\<close> odd numbers.\n  We compute the next odd number in the loop, in auxiliary variable \\<open>b\\<close>.\n\\<close>\n\ndefinition \"sqr_prog \\<equiv> \n  CLR a;; CLR b;; CLR c;;\n  b ::= \\<acute>1;;\n  a ::= \\<acute>0;;\n  c ::= \\<acute>0;;\n  WHILE ($c < $n) DO (\n    a ::= $a + $b;;\n    b ::= $b + \\<acute>2;;\n    c ::= $c + \\<acute>1\n  )\"\n\nlemma sqr_prog_correct: \n  \"\\<Turnstile>\\<^sub>t {\\<lambda>_. vars n in n\\<ge>0} sqr_prog {\\<lambda>_. vars n a in a=n\\<^sup>2} mod {''a'', ''b'', ''c''}\"\n  unfolding sqr_prog_def\n  apply (rewrite annot_tinvar[where R=\"measure_exp ($n-$c)\" \n        and I=\"\\<lambda>_. vars a b c n in a=c\\<^sup>2 \\<and> b = 2*c+1 \\<and> c\\<le>n\"])\n  apply vcg_all\n  apply (auto simp: power2_eq_square algebra_simps)\n  done\n\n\n  \n  \n  \nsubsubsection \\<open>Fibonacci Numbers\\<close>  \nfun fib :: \"nat \\<Rightarrow> nat\" where \n  \"fib 0 = 1\"\n| \"fib (Suc 0) = 1\"  \n| \"fib (Suc (Suc n)) = fib n + fib (Suc n)\"  \n      \n    \nabbreviation \"fib_prog \\<equiv> \n  CLR j;; CLR k;; CLR c;;\n  j::=N 1;;\n  k::=N 1;;\n  c::=N 1;;\n  \n  WHILE $c < $n DO (\n    CLR t;;\n    t::=$k;; k::=$k+$j;; j::=$t;;\n    c::=$c + N 1\n  )\n\"\n\nlemma fib_aux: \"0 < c \\<Longrightarrow> fib (nat c) + fib (nat (c - 1)) = fib (Suc (nat c))\"\n  by (smt Suc_nat_eq_nat_zadd1 add.commute fib.simps(3))\n\nlemma fib_correct: \"\n  \\<Turnstile> {\\<lambda>_. vars n in 0\\<le>n } \n      fib_prog \n    {\\<lambda>_. vars n k in k = int (fib (nat n))} mod {''c'', ''j'', ''k'', ''t''}\"\n  apply (rewrite annot_invar[where I=\"\\<lambda>_. vars j k c n in \n       0<c \\<and> 0\\<le>n\n    \\<and> (0<n \\<longrightarrow> c\\<le>n \\<and> j=int (fib (nat (c-1))) \\<and> k = int (fib (nat c)))\n    \\<and> (n=0 \\<longrightarrow> k=1)\n  \"])\n  supply fib_aux[simp]\n  by vcg\n  \n  \nsubsection \\<open>Count down\\<close>  \n  \nsubsubsection \\<open>Exponential\\<close>\ntext \\<open>Essentially the same as count up, but we use the input variable as counter\\<close>\n\ndefinition \"exp_prog' \\<equiv> \n  CLR r;;  (* Aux variables are cleared before use. *)\n  r ::= N 1;;\n  WHILE N 0 < $n DO (\n    r ::= $r * $b;;\n    n ::= $n - N 1\n  )\"\n\n  \nlemma [simp]: \"lhs_vars exp_prog' = {''n'',''r''}\"\n  by (simp add: exp_prog'_def)\n\n  \ntext \\<open>The invariant is the same as for count-up. \n  Only that we have to compute the actual number \n  of loop iterations by \\<open>n\\<^sub>0 - n\\<close>\n\\<close>  \ndefinition exp_invar' :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> bool\"\n  where \"exp_invar' n\\<^sub>0 b\\<^sub>0 n r \\<equiv> (\n      let c=n\\<^sub>0-n in\n        0\\<le>c \\<and> c\\<le>n\\<^sub>0 \\<and> r = b\\<^sub>0 ^ nat c\n    )\"\n\ntext \\<open>If the invariants become more complex or hard to prove automatically,\n  it can be advantageous to define the (logical part of) the invariant as\n  a predicate, and prove the required VCs as separate lemmas.\n\\<close>  \n    \n      \nlemma exp_prog'_vcs:  \n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; 0 < n; exp_invar' n\\<^sub>0 b\\<^sub>0 n r\\<rbrakk> \\<Longrightarrow> exp_invar' n\\<^sub>0 b\\<^sub>0 (n - 1) (r * b\\<^sub>0)\"\n  \"\\<lbrakk>0 \\<le> n\\<^sub>0; \\<not> 0 < n; exp_invar' n\\<^sub>0 b\\<^sub>0 n r\\<rbrakk> \\<Longrightarrow> r = b\\<^sub>0 ^ nat n\\<^sub>0\"\n  \"0 \\<le> n\\<^sub>0 \\<Longrightarrow> exp_invar' n\\<^sub>0 b\\<^sub>0 n\\<^sub>0 1\"\n  by (auto simp: exp_invar'_def) \n\nlemma exp_prog'_correct: \" \n  \\<Turnstile>\\<^sub>t {\\<lambda>(n\\<^sub>0,b\\<^sub>0). vars n b in n=n\\<^sub>0 \\<and> b=b\\<^sub>0 \\<and> 0\\<le>n\\<^sub>0} \n       exp_prog' \n    {\\<lambda>(n\\<^sub>0,b\\<^sub>0). vars r b in b=b\\<^sub>0 \\<and> r = (b\\<^sub>0 ^ nat n\\<^sub>0)} mod {''r'',''n''}\"\nproof -\n  note [simp] = exp_prog'_vcs\n  show ?thesis\n    unfolding exp_prog'_def   \n    apply (rewrite annot_tinvar[where \n      I=\"\\<lambda>(n\\<^sub>0,b\\<^sub>0). vars r n b in b=b\\<^sub>0 \\<and> exp_invar' n\\<^sub>0 b\\<^sub>0 n r \\<and> 0\\<le>n\\<^sub>0\" and\n      R=\"measure (\\<lambda>s. nat (s ''n'' 0))\"\n      ])\n    by vcg \nqed    \n\n\nsubsubsection \\<open>Square by Sum\\<close>\ndefinition \"sqr_prog' \\<equiv> \n  CLR a;; CLR b;; \n  b ::= \\<acute>1;;\n  a ::= \\<acute>0;;\n  WHILE (\\<acute>0 < $n) DO (\n    a ::= $a + $b;;\n    b ::= $b + \\<acute>2;;\n    n ::= $n - \\<acute>1\n  )\"\n\nlemma sqr_prog'_correct: \n  \"\\<Turnstile>\\<^sub>t {\\<lambda>n\\<^sub>0. vars n in n=n\\<^sub>0 \\<and> 0\\<le>n\\<^sub>0} sqr_prog' {\\<lambda>n\\<^sub>0. vars a in a=n\\<^sub>0\\<^sup>2} mod {''a'',''b'',''n''}\"\n  unfolding sqr_prog'_def\n  apply (rewrite annot_tinvar[where R=\"measure_exp ($n)\" \n        and I=\"\\<lambda>n\\<^sub>0. vars a b n in 0\\<le>n \\<and> n\\<le>n\\<^sub>0 \\<and> (let i=n\\<^sub>0-n in b=2*i+1 \\<and> a=i\\<^sup>2)\"])\n  apply vcg_all\n  apply (auto simp: power2_eq_square algebra_simps)\n  done\n\n\nsubsubsection \\<open>Factorial\\<close>\ndefinition \"fact_prog' \\<equiv> \n  CLR r;;\n  r ::= N 1;;\n  WHILE ($n > N 0) DO (\n    r ::= $r * $n;;\n    n ::= $n - N 1\n  )\"\n\ndefinition fact'_invar :: \"int \\<Rightarrow> _\" \n  where \"fact'_invar n\\<^sub>0 n r \\<equiv> r = ifact n\\<^sub>0 div ifact n \\<and> 0\\<le>n \\<and> n\\<le>n\\<^sub>0\"\n  \n\nlemma ifact_div_one_less:\n  assumes \"0 < n\" \"n \\<le> n\\<^sub>0\"\n  shows \"ifact n\\<^sub>0 div ifact (n - 1) = ifact n\\<^sub>0 div ifact n * n\"\nproof -\n  have [simp]: \"finite B \\<Longrightarrow> 0\\<notin>A \\<Longrightarrow> A\\<subseteq>B \\<Longrightarrow> \\<Prod>B div \\<Prod>A = \\<Prod>(B-A)\" for A B :: \"int set\"\n    by (simp add: prod.subset_diff rev_finite_subset)\n  have [simp]: \"0<n \\<Longrightarrow> n\\<le>n\\<^sub>0 \\<Longrightarrow> ({1..n\\<^sub>0} - {1..n - 1}) = insert n ({1..n\\<^sub>0} - {1..n})\"\n    by auto\n\n  from assms show ?thesis\n    unfolding ifact_def by auto\nqed      \n  \nlemma fact'_vcs:  \n  \"0 \\<le> n\\<^sub>0 \\<Longrightarrow> fact'_invar n\\<^sub>0 n\\<^sub>0 1\"\n  \"\\<lbrakk>0 < n; fact'_invar n\\<^sub>0 n r\\<rbrakk> \\<Longrightarrow> fact'_invar n\\<^sub>0 (n - 1) (r * n)\"\n  \"\\<lbrakk>\\<not> 0 < n; fact'_invar n\\<^sub>0 n r\\<rbrakk> \\<Longrightarrow> r = ifact n\\<^sub>0\"\n  by (auto simp: fact'_invar_def ifact_div_one_less) \n\nlemma fact'_correct: \" \n  \\<Turnstile>\\<^sub>t {\\<lambda>n\\<^sub>0. vars n in n=n\\<^sub>0 \\<and> 0\\<le>n}\n       fact_prog' \n    {\\<lambda>n\\<^sub>0. vars r in r = (ifact n\\<^sub>0) } mod {''n'',''r''}\"\n  unfolding fact_prog'_def  \n  apply (rewrite annot_tinvar[where \n      R=\"measure_exp ($n)\"\n    and I=\"\\<lambda>n\\<^sub>0. vars r n in fact'_invar n\\<^sub>0 n r\n  \"])\n  supply [simp] = fact'_vcs\n  by vcg\n\n\nsection \\<open>Reusing Programs in Context\\<close>\n\ndeclare exp_prog'_correct[vcg_rules]\n\nfun (in -) tower2 :: \"nat \\<Rightarrow> nat\" where \n  \"tower2 0 = 1\"\n| \"tower2 (Suc n) = 2^tower2 n\"\n\ndefinition \"tower2_prog \\<equiv> \n  CLR b;; CLR c;; CLR a;; \n  b ::= \\<acute>2;;\n  c ::= \\<acute>0;;\n  a ::= \\<acute>1;;\n  WHILE $c < $x DO (\n    CLR n;;\n    n::=$a;;\n    exp_prog';;\n    a::=$r;;\n    c::=$c+\\<acute>1\n  )\" \n  \nlemma tower2_prog_correct: \"\\<Turnstile>\\<^sub>t \n  {\\<lambda>x\\<^sub>0. vars x in x=x\\<^sub>0 \\<and> 0\\<le>x} \n    tower2_prog \n  {\\<lambda>x\\<^sub>0. vars x a in x=x\\<^sub>0 \\<and> a=int (tower2 (nat x))} mod {''b'',''c'',''a'',''n'',''r''}\"\n  unfolding tower2_prog_def\n  apply (rewrite annot_tinvar[where\n    R = \"measure_exp ($x-$c)\" and\n    I = \"\\<lambda>x\\<^sub>0. vars b c a x in x=x\\<^sub>0 \\<and> 0\\<le>c \\<and> c\\<le>x \\<and> b=2 \\<and> a = int (tower2 (nat c))\"\n  ])\n  by vcg\n\n\n  \n  \nsection \\<open>Working with Arrays\\<close>  \n  \nsubsection \\<open>Summation over Array\\<close>\n\ndefinition \"array_sum \\<equiv> \n  CLR r;;             \n  r ::= N 0;;         \n  WHILE $l < $h DO (\n    r ::= $r + a\\<^bold>[$l\\<^bold>];;\n    l ::= $l + (\\<acute>1)\n  )\"\n\n\nlemma array_sum_aux:\n  fixes f :: \"int \\<Rightarrow> int\"\n  shows \"l\\<^sub>0\\<le>l \\<Longrightarrow> (\\<Sum>i=l\\<^sub>0..<l+1. f i) = (\\<Sum>i=l\\<^sub>0..<l. f i) + f l\" \n  by (auto simp: intvs_incdec)\n  \nlemma \"\\<Turnstile> \n  {\\<lambda>l\\<^sub>0. vars l h (a:imap) in l\\<le>h \\<and> l=l\\<^sub>0 } \n    Imp_Array_Examples.array_sum \n  {\\<lambda>l\\<^sub>0. vars l h (a:imap) r in r = (\\<Sum>i=l\\<^sub>0..<h. a i) } mod {''l'',''r''}\n  \"\n  unfolding array_sum_def\n  apply (rewrite annot_invar[where \n    I=\"\\<lambda>l\\<^sub>0. vars l h (a:imap) r in\n      l\\<^sub>0\\<le>l \\<and> l\\<le>h\n      \\<and> r = (\\<Sum>i=l\\<^sub>0..<l. a i)\"])\n  supply array_sum_aux[simp]    \n  by vcg\n\ntext \\<open>Getting rid of the \\<open>l\\<le>h\\<close> precondition\\<close>\n\nlemma array_sum_correct: \"\\<Turnstile> \n  {\\<lambda>l\\<^sub>0. vars l h (a:imap) in l=l\\<^sub>0 } \n    array_sum \n  {\\<lambda>l\\<^sub>0. vars l h (a:imap) r in r = (\\<Sum>i=l\\<^sub>0..<h. a i) } mod {''l'',''r''}\"\n  unfolding array_sum_def\n  apply (rewrite annot_invar[where \n    I=\"\\<lambda>l\\<^sub>0. vars l h (a:imap) r in (\n        if l\\<^sub>0 \\<le> h then  \n            l\\<^sub>0 \\<le>l\n          \\<and> l \\<le> h \n          \\<and> r = (\\<Sum>i\\<in>{l\\<^sub>0..<l}. a i)\n        else\n            r = 0 \n          \\<and> l = l\\<^sub>0\n        )\n        \"])\n  supply array_sum_aux[simp]    \n  supply if_splits[split]        \n  by vcg\n\ntext \\<open>Summing up only elements greater 5\\<close>  \n  \ndefinition \"array_sum_gt5 \\<equiv> \n  CLR r;;\n  r ::= N 0;;\n  WHILE $l < $h DO (\n    IF N 5 < a\\<^bold>[$l\\<^bold>] THEN\n      r ::= $r + a\\<^bold>[$l\\<^bold>]\n    ELSE SKIP;;  \n    l ::= $l + N 1\n  )\"\n    \nabbreviation \"gt5 i \\<equiv> if i>5 then i else 0\"  \n  \nlemma array_sum_gt5_correct: \"\\<Turnstile> \n  {\\<lambda>l\\<^sub>0. vars l h (a:imap) in l=l\\<^sub>0}\n    array_sum_gt5 \n  {\\<lambda>l\\<^sub>0. vars h (a:imap) r in r = (\\<Sum>i\\<in>{l\\<^sub>0..<h}. gt5 (a i)) } mod {''r'',''l''}\" \n  unfolding array_sum_gt5_def\n  apply (rewrite annot_invar[where \n    I=\"\\<lambda>l\\<^sub>0. vars (a:imap) h l r in\n      (\n        if l\\<^sub>0 \\<le> h then \n          l\\<^sub>0\\<le>l\n          \\<and> l\\<le>h\n          \\<and> r = (\\<Sum>i\\<in>{l\\<^sub>0..<l}. gt5 (a i))\n        else\n            r = 0 \n          \\<and> l = l\\<^sub>0\n      )\n        \"])\n  supply array_sum_aux[simp]    \n  supply if_splits[split]        \n  by vcg\n\n\nsubsection \\<open>Range of an Array as List\\<close>  \nfunction (sequential) lran :: \"(int \\<Rightarrow> val) \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> val list\" where\n  \"lran a l h = (if l<h then a l # lran a (l+1) h else [])\"\n  by pat_completeness auto\ntermination \n  by (relation \"measure (\\<lambda>(_,l,h). nat (h-l))\") auto\n  \ndeclare lran.simps[simp del]  \n  \ntext \\<open>\n  \\<open>lran a l h\\<close> is the list \\<open>[a\\<^sub>l,a\\<^sub>l\\<^sub>+\\<^sub>1,...,a\\<^sub>h\\<^sub>-\\<^sub>1]\\<close>\n\\<close>\n\nsubsubsection \\<open>Auxiliary Lemmas\\<close>\n\nlemma lran_empty[simp]: \n  \"lran a l l = []\"\n  \"lran a l h = [] \\<longleftrightarrow> h\\<le>l\"\n  by (rewrite lran.simps; auto)+\n\nlemma lran_bwd_simp: \"lran a l h = (if l<h then lran a l (h-1)@[a (h-1)] else [])\"\n  apply (induction a l h rule: lran.induct)\n  apply (rewrite in \"\\<hole> = _\" lran.simps)\n  apply (rewrite in \"_ = \\<hole>\" lran.simps)\n  by (auto simp: less_le)\n    \n    \nlemma lran_append1[simp]: \"l\\<le>h \\<Longrightarrow> lran a l (h + 1) = lran a l h @ [a h]\"\n  by (rewrite in \"\\<hole> = _\" lran_bwd_simp) auto\n\nlemma lran_prepend1[simp]: \"l\\<le>h \\<Longrightarrow> lran a (l-1) h = a(l-1) # lran a l h\"\n  by (rewrite in \"\\<hole> = _\" lran.simps) auto\n    \nlemma lran_tail[simp]: \"lran a (l+1) h = tl (lran a l h)\"\n  apply (rewrite in \"_ = \\<hole>\" lran.simps)\n  apply auto\n  done\n    \nlemma lran_butlast[simp]: \"lran a l (h-1) = butlast (lran a l h)\"\n  apply (rewrite in \"_ = \\<hole>\" lran_bwd_simp)\n  apply auto\n  done\n  \n\nlemma lran_upd_outside[simp]:\n  \"i<l \\<Longrightarrow> lran (a(i:=x)) l h = lran a l h\"\n  \"h\\<le>i \\<Longrightarrow> lran (a(i:=x)) l h = lran a l h\"\n  subgoal\n    apply (induction a l h rule: lran.induct)\n    apply (rewrite in \"\\<hole> = _\" lran.simps)\n    apply (rewrite in \"_ = \\<hole>\" lran.simps)\n    by (auto)\n  subgoal\n    apply (induction a l h rule: lran.induct)\n    apply (rewrite in \"\\<hole> = _\" lran.simps)\n    apply (rewrite in \"_ = \\<hole>\" lran.simps)\n    by (auto)\n  done  \n\nlemma lran_eq_iff: \"lran a l h = lran a' l h \\<longleftrightarrow> (\\<forall>i. l\\<le>i \\<and> i<h \\<longrightarrow> a i = a' i)\"  \n  apply (induction a l h rule: lran.induct)\n  apply (rewrite in \"\\<hole> = _\" lran.simps)\n  apply (rewrite in \"_ = \\<hole>\" lran.simps)\n  apply auto\n  by (metis antisym_conv not_less zless_imp_add1_zle)\n  \nlemma set_lran[simp]: \"set (lran a l h) = a`{l..<h}\"  \n  apply (induction a l h rule: lran.induct)\n  apply (rewrite in \"\\<hole> = _\" lran.simps)\n  apply auto\n  by (metis atLeastLessThan_iff image_iff not_less not_less_iff_gr_or_eq zless_imp_add1_zle)\n  \nlemma mset_lran[simp]: \"mset (lran a l h) = image_mset a (mset_set {l..<h})\"\n  apply (induction a l h rule: lran.induct)\n  apply (rewrite in \"\\<hole> = _\" lran.simps)\n  by (auto simp: intvs_lower_incr)\n\nsubsection \\<open>Filtering\\<close>\ndefinition \"filter_prog \\<equiv>\n  CLR r;; CLR w;;\n  r::=$l;; w::=$l;;\n  WHILE $r<$h DO (\n    IF a\\<^bold>[$r\\<^bold>] > \\<acute>5 THEN\n      a\\<^bold>[$w\\<^bold>] ::= a\\<^bold>[$r\\<^bold>];;\n      w::=$w+\\<acute>1\n    ELSE SKIP;;\n    r::=$r+\\<acute>1\n  );;\n  h::=$w\n  \"  \n\nlemma filter_prog_correct: \" \n  \\<Turnstile>\\<^sub>t {\\<lambda>(h\\<^sub>0,a\\<^sub>0). vars l h (a:imap) in a=a\\<^sub>0 \\<and> h=h\\<^sub>0 \\<and> l\\<le>h} \n       filter_prog \n     {\\<lambda>(h\\<^sub>0,a\\<^sub>0). vars l h (a:imap) in h\\<le>h\\<^sub>0 \\<and> lran a l h = filter (\\<lambda>x. 5<x) (lran a\\<^sub>0 l h\\<^sub>0)}\n     mod {''h'', ''r'', ''w'', ''a''}\n     \"\n  unfolding filter_prog_def   \n  apply (rewrite annot_tinvar[where \n    I=\"\\<lambda>(h\\<^sub>0,a\\<^sub>0). vars l h (a:imap) r w in \n      h=h\\<^sub>0 \\<and> l\\<le>w \\<and> w\\<le>r \\<and> r\\<le>h \\<and>\n      lran a l w = filter (\\<lambda>x. 5<x) (lran a\\<^sub>0 l r) \\<and>\n      lran a r h = lran a\\<^sub>0 r h\n      \"\n    and\n    R=\"measure_exp ($h - $r)\"\n    ])\n  supply lran_eq_iff[simp]\n  by vcg\n\nsubsection \\<open>Find First Element in Range\\<close>  \n  definition \"find_in_range_prog \\<equiv> \n    WHILE $l<$h && a\\<^bold>[$l\\<^bold>] != $x DO l::=$l+\\<acute>1\n  \"    \n  \n  abbreviation \"iran_spec l h a x \\<equiv> (\n    let\n      iran = \\<lambda>i. i\\<in>{l..<h} \\<and> a i = x  (* i is in range and points to x *)\n    in\n      (if \\<exists>i. iran i then \n        (LEAST i. iran i)    (* Return least index *)\n       else h                (* Or upper bound to indicate that no element has been found *)\n      )\n    )\"\n  \n  lemma find_in_range_prog_correct: \"\n    \\<Turnstile> {\\<lambda>l\\<^sub>0. vars l h x (a : imap) in l=l\\<^sub>0 \\<and> l\\<le>h}\n      find_in_range_prog\n    {\\<lambda>l\\<^sub>0. vars l h x (a : imap) in l = iran_spec l\\<^sub>0 l a x } mod {''l''}\"\n    unfolding find_in_range_prog_def\n    apply (rewrite annot_invar[where I=\"\\<lambda>l\\<^sub>0.\n      vars l h x (a : imap) in  \n        l\\<^sub>0\\<le>l \\<and> l\\<le>h \\<and> (\\<forall>i\\<in>{l\\<^sub>0..<l}. a i \\<noteq> x)\"])\n    apply vcg_all\n    apply (auto simp: Let_def)\n    done\n  \nsubsection \\<open>Minimum Sort\\<close>  \n  \nsubsubsection \\<open>Find Minimum\\<close>\n  \ntext \\<open>Find index of minimum element in \\<open>a i, ..., a (h-1)\\<close>, return in \\<open>j\\<close>\\<close>\ndefinition \"find_min \\<equiv> \n  CLR j;; CLR k;; CLR m;;\n  j::=$i;; k::=$i+\\<acute>1;; m::=a\\<^bold>[$j\\<^bold>];;\n  WHILE $k<$h DO (\n    (* m stores current minimum element, j stores its index *)\n    IF a\\<^bold>[$k\\<^bold>] < $m THEN\n      m ::= a\\<^bold>[$k\\<^bold>];;\n      j::=$k\n    ELSE SKIP;;\n    k::=$k+\\<acute>1\n  )\"\n  \n  \nlemma [simp]: \"lhs_vars find_min \n  = {''k'', ''j'', ''m''}\"  \n  unfolding find_min_def by auto\n  \n(* Augment the type signature as long as no type variables ('a,'b,...) occur \n  in the output of the definition command! *)  \ndefinition find_min_invar :: \"int \\<Rightarrow> int \\<Rightarrow> (int \\<Rightarrow> int) \\<Rightarrow> _\"\n  where\n  \"find_min_invar i h a j k m \\<equiv> \n      i\\<le>j \\<and> j<h \\<and> i<k \\<and> k\\<le>h            (* Everything in range *)\n    \\<and> m = a j \\<and> a j = Min (a`{i..<k})\"  (* m stores minimum element, j its index *) \n\nlemma fmi_vcs_aux1: \"i\\<^sub>0 < k \\<Longrightarrow> \\<forall>x\\<in>{i\\<^sub>0..<k}. a\\<^sub>0 k < (a\\<^sub>0::int\\<Rightarrow>int) x \\<Longrightarrow> a\\<^sub>0 k = Min (a\\<^sub>0 ` {i\\<^sub>0..<k + 1})\"  \n  apply (rule Min_eqI[symmetric])\n  apply (auto simp: Ball_def) \n  using eq_iff by fastforce\n  \nlemma fmi_vcs:\n  \"\\<lbrakk>k < h; find_min_invar i h a j k m; a k < m\\<rbrakk> \\<Longrightarrow> find_min_invar i h a k (k + 1) (a k)\"\n  \"\\<lbrakk>k < h; find_min_invar i h a j k m; \\<not> a k < m\\<rbrakk> \\<Longrightarrow> find_min_invar i h a j (k + 1) m\"\n  \"\\<lbrakk>\\<not> k < h; find_min_invar i h a j k m\\<rbrakk> \\<Longrightarrow> i \\<le> j \\<and> j < h \\<and> a j = Min (a ` {i..<h})\"\n  \"i < h \\<Longrightarrow> find_min_invar i h a i (i + 1) (a i)\"\n  unfolding find_min_invar_def\n  apply (simp_all add: fmi_vcs_aux1)\n  subgoal \n    apply (clarsimp simp add: intvs_incdec min_def not_less)\n    apply (rule Min_eqI)\n    apply auto \n    by (metis atLeastLessThan_iff eq_iff image_eqI)\n  done  \n\n\nlemma find_min_correct[vcg_rules]: \"\\<Turnstile>\\<^sub>t\n  {\\<lambda>_. vars i h (a:imap) in i<h} \n    find_min \n  {\\<lambda>_. vars i h (a:imap) j in i\\<le>j \\<and> j<h \\<and> (a j = Min (a`{i..<h}))} \n  mod {''j'',''k'',''m''}\"\n  unfolding find_min_def\n  apply (rewrite annot_tinvar[where \n    R=\"measure_exp ($h - $k)\" and\n    I=\"\\<lambda>_. vars i h (a:imap) j k m in find_min_invar i h a j k m\"\n  ])\n  apply vcg_all\n\n  (* If the VCs make the simplifier loop, some more 'creative' techniques may help.\n  \n    using fmi_vcs by metis+\n  \n    Or, apply them one by one!\n  *)\n  using fmi_vcs(1) apply metis\n  using fmi_vcs(2) apply metis\n  using fmi_vcs(3) apply metis\n  using fmi_vcs(3) apply metis\n  using fmi_vcs(3) apply metis\n  using fmi_vcs(4) apply metis\n  done\n  \n  \nsubsubsection \\<open>Minsort Algorithm\\<close>  \ntext \\<open>Sort the array \\<open>a\\<close> in between indices \\<open>l\\<close> and \\<open>h\\<close>.\n  Idea: Find minimum element in remaining part array,\n    swap to end of already sorted part.\n    \n    \\<open>i\\<close> points to first element of unsorted part.\n\\<close>  \ndefinition \"minsort \\<equiv> \n  CLR i;;\n  i::=$l;;\n  WHILE $i<$h DO (\n    find_min;;\n  \n    CLR t;;\n    t ::= a\\<^bold>[$i\\<^bold>];;\n    a\\<^bold>[$i\\<^bold>] ::= a\\<^bold>[$j\\<^bold>];;\n    a\\<^bold>[$j\\<^bold>] ::= $t;;\n    \n    i::=$i+\\<acute>1\n  )\"\n  \n  \ndefinition \"sorted_spec l l' \\<equiv> mset l' = mset l \\<and> sorted l'\"\n  \n(* verify that all types are inferred as int, and no polymorphic ('a) types remain! *)\ndefinition \"I_minsort a\\<^sub>0 l\\<^sub>0 h\\<^sub>0 a i \\<equiv> \n    l\\<^sub>0\\<le>i \\<and> i\\<le>h\\<^sub>0 \n  \\<and> mset (lran a\\<^sub>0 l\\<^sub>0 h\\<^sub>0) = mset (lran a l\\<^sub>0 h\\<^sub>0)   (* Array contains original elements *)\n  \\<and> sorted (lran a l\\<^sub>0 i)                        (* Sorted part is sorted *)\n  \\<and> (\\<forall>k1\\<in>{l\\<^sub>0..<i}. \\<forall>k2\\<in>{i..<h\\<^sub>0}. a k1 \\<le> a k2)  (* Every element of unsorted part \\<ge> sorted part *)\n  \"\n\n\nlemma [simp]: \"lhs_vars minsort = {''i'', ''a'', ''t'', ''k'', ''j'', ''m''}\"\n  unfolding minsort_def by auto\n\n\n\nlemma image_mset_subst_in_range:\n  assumes \"i\\<in>{l::int..<h}\"  \n  shows \"image_mset (f(i:=x)) (mset_set {l..<h}) = image_mset f (mset_set {l..<h}) - {#f i#} + {#x#}\"\nproof -  \n  from assms have \"l<h\" \"l\\<le>i\" \"i<h\" by auto\n  then show ?thesis\n    apply (induction rule: int_less_induct)\n    apply (auto simp: intvs_decr_l image_mset_subst_outside)\n    apply (simp add: antisym_conv)\n    done\nqed    \n  \n  \n  \nlemma minsort_vcs:  \n  \"\\<lbrakk>I_minsort z l ha aa ia; ia \\<le> j; j < ha; aa j = Min (aa ` {ia..<ha})\\<rbrakk>\n       \\<Longrightarrow> I_minsort z l ha (aa(ia := Min (aa ` {ia..<ha}), j := aa ia)) (ia + 1)\"\n  \"\\<lbrakk>\\<not> i < h; I_minsort z l h a i\\<rbrakk> \\<Longrightarrow> sorted_spec (lran z l h) (lran a l h)\"\n  \"l \\<le> h \\<Longrightarrow> I_minsort z l h z l\"  \n  subgoal\n    unfolding I_minsort_def\n    apply (auto simp: sorted_append)\n    apply (metis fun_upd_triv)\n    apply (auto simp: image_mset_subst_in_range)\n    done\n  subgoal\n    unfolding I_minsort_def sorted_spec_def\n    by (auto)\n\n  subgoal\n    unfolding I_minsort_def\n    by (auto)\n  \n  done\n  \n  \nlemma minsort_correct: \"\\<Turnstile>\\<^sub>t\n  {\\<lambda>a\\<^sub>0. vars l h (a:imap) in l\\<le>h \\<and> a=a\\<^sub>0}\n    minsort\n  {\\<lambda>a\\<^sub>0. vars l h (a:imap) in sorted_spec (lran a\\<^sub>0 l h) (lran a l h) } \n    mod {''i'',''t'',''j'',''k'',''m'',''a''}\"\n  \n  unfolding minsort_def\n  apply (rewrite annot_tinvar[where \n    R = \"measure_exp ($h - $i)\" and\n    I = \"\\<lambda>a\\<^sub>0. vars l h (a:imap) i in I_minsort a\\<^sub>0 l h a i\"\n    ])\n  supply minsort_vcs[simp]  \n  by vcg\n  \n  \n  \nsection \\<open>Debugging\\<close>  \ntext \\<open>Automatic Derivation of Big-Step Execution\\<close>\n  fun vlist' :: \"int \\<Rightarrow> val list \\<Rightarrow> (int \\<Rightarrow> val)\" where\n    \"vlist' l [] = (\\<lambda>_. 0)\"\n  | \"vlist' l (x#xs) = (vlist' (l+1) xs)(l:=x)\"\n  \n  abbreviation \"vlist \\<equiv> vlist' 0\"\n  \n  schematic_goal \"(array_sum,<''l'':=var 1, ''h'':=var 5, ''a'':=vlist [100,1,2,3,4,200,300]>) \\<Rightarrow> ?s\"\n    unfolding array_sum_def\n    by BigSteps\n\n  schematic_goal \"(fact_prog',<''n'' := var 5>) \\<Rightarrow> ?s\"  \n    unfolding fact_prog'_def\n    by BigSteps\n  \n  \n    \n    \nend\n  \n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Project/Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.885631484383387, "lm_q1q2_score": 0.7678741669670742}}
{"text": "theory Homework5_2\nimports Main\nbegin\n\n  (*\n    ISSUED: Wednesday, October 18\n    DUE: Wednesday, October 25, 11:59pm\n    POINTS: 5\n  *)\n\n\n  (*\n    In a directed graph, a path from node q to node v is the list of nodes \n    visited on the way from q to v, including the first node, and excluding \n    the last node.\n    \n    Inductively, we can characterize paths as follows:\n  *)\n  inductive path :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n    \"path E q [] q\"\n  | \"\\<lbrakk> E p q; path E q w r \\<rbrakk> \\<Longrightarrow> path E p (p#w) r\"\n\n  (*\n    Functionally, we have the following characterization:\n  *)\n  lemma path_Nil_conv: \"path E p [] q \\<longleftrightarrow> q=p\"\n    by (auto elim: path.cases intro: path.intros)\n\n  lemma path_Cons_conv: \"path E p (x#xs) q \\<longleftrightarrow> (x=p \\<and> (\\<exists>r. E p r \\<and> path E r xs q))\"\n    by (auto elim: path.cases intro: path.intros)\n    \n  (* Prove the equivalence rule for appending two paths.\n    Hint: Induction on w1, use the path_Nil_conv and path_Cons_conv \n      lemmas as simp-rules. Proof should be straightforward, probably no Isar required.\n  *)  \n  lemma path_append_conv: \"path E p (w1@w2) q \\<longleftrightarrow> (\\<exists>r. path E p w1 r \\<and> path E r w2 q)\"\n    sorry\n  \n  (*\n    A path is called simple, if it visits each node at most once \n    (except for circular path, that, of course, visit their common \n      start and end node twice)\n  \n    For our path definition, a path is simple if and only if it contains \n    no node twice (Isabelle constant: distinct). Recall, the end node is excluded.\n    \n    Show: If there is a path from p to q, then there is also a \n      simple path from p to q.\n\n    Proof sketch (informal):\n      Induction on the length of the path (rule: length_induct)\n        Assume we have a path xs from p to q.\n        IH: For all shorter path, we can find a simple path\n        To show: There is a simple path from p to q\n      \n        If xs is already distinct, we are done.\n        Otherwise, xs must have the form xs = xs1@[x]@xs2@[x]@xs3 (thm not_distinct_decomp)\n        hence, we obtain nodes p1 p2 such that\n          p -xs1\\<rightarrow> x   x\\<rightarrow>p1   p1 -xs2\\<rightarrow> x   x\\<rightarrow>p2   p2 -xs3\\<rightarrow> q\n        \n        Here, p -xs\\<rightarrow> q denotes a path, and p\\<rightarrow>q a single edge.\n          \n        by \"dropping\" the loop, we obtain a path  p -xs1@[x]@xs3\\<rightarrow> q\n        this path is shorter than the original path, so by IH, we have a simple path from p to q. \n        QED.\n        \n    Prove the lemma formally. Most probably, you will need Isar!\n  *)\n  lemma \n    assumes \"path E p xs q\"\n    shows \"\\<exists>ys. distinct ys \\<and> path E p ys q\"\n    using assms\n  proof (induction xs rule: length_induct)\n    case (1 xs)\n    \n    (* These two lines just assign more readable names to the premises and the IH *)\n    note PREMS=\"1.prems\"\n    note IH=\"1.IH\"\n    \n    (* Now we use these names *)\n    thm PREMS (* We may assume that we have a path*)\n    thm IH    (* For shorter path, there exists distinct paths *)\n    term ?case (* We have to show that there exists a distinct path *)\n    \n    show ?case sorry (* Fill in your proof here! *)\n  qed\n  \n  \nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Homeworks/Homework5_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623015, "lm_q2_score": 0.8670357666736772, "lm_q1q2_score": 0.7678741560405138}}
{"text": "(*  Title:      HOL/Library/Lub_Glb.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge\n    Author:     Amine Chaieb, University of Cambridge *)\n\nsection \\<open>Definitions of Least Upper Bounds and Greatest Lower Bounds\\<close>\n\ntheory Lub_Glb\nimports Complex_Main\nbegin\n\ntext \\<open>Thanks to suggestions by James Margetson\\<close>\n\ndefinition setle :: \"'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"  (infixl \"*<=\" 70)\n  where \"S *<= x = (ALL y: S. y \\<le> x)\"\n\ndefinition setge :: \"'a::ord \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infixl \"<=*\" 70)\n  where \"x <=* S = (ALL y: S. x \\<le> y)\"\n\n\nsubsection \\<open>Rules for the Relations \\<open>*<=\\<close> and \\<open><=*\\<close>\\<close>\n\nlemma setleI: \"ALL y: S. y \\<le> x \\<Longrightarrow> S *<= x\"\n  by (simp add: setle_def)\n\nlemma setleD: \"S *<= x \\<Longrightarrow> y: S \\<Longrightarrow> y \\<le> x\"\n  by (simp add: setle_def)\n\nlemma setgeI: \"ALL y: S. x \\<le> y \\<Longrightarrow> x <=* S\"\n  by (simp add: setge_def)\n\nlemma setgeD: \"x <=* S \\<Longrightarrow> y: S \\<Longrightarrow> x \\<le> y\"\n  by (simp add: setge_def)\n\n\ndefinition leastP :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"leastP P x = (P x \\<and> x <=* Collect P)\"\n\ndefinition isUb :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isUb R S x = (S *<= x \\<and> x: R)\"\n\ndefinition isLub :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isLub R S x = leastP (isUb R S) x\"\n\ndefinition ubs :: \"'a set \\<Rightarrow> 'a::ord set \\<Rightarrow> 'a set\"\n  where \"ubs R S = Collect (isUb R S)\"\n\n\nsubsection \\<open>Rules about the Operators @{term leastP}, @{term ub} and @{term lub}\\<close>\n\nlemma leastPD1: \"leastP P x \\<Longrightarrow> P x\"\n  by (simp add: leastP_def)\n\nlemma leastPD2: \"leastP P x \\<Longrightarrow> x <=* Collect P\"\n  by (simp add: leastP_def)\n\nlemma leastPD3: \"leastP P x \\<Longrightarrow> y: Collect P \\<Longrightarrow> x \\<le> y\"\n  by (blast dest!: leastPD2 setgeD)\n\nlemma isLubD1: \"isLub R S x \\<Longrightarrow> S *<= x\"\n  by (simp add: isLub_def isUb_def leastP_def)\n\nlemma isLubD1a: \"isLub R S x \\<Longrightarrow> x: R\"\n  by (simp add: isLub_def isUb_def leastP_def)\n\nlemma isLub_isUb: \"isLub R S x \\<Longrightarrow> isUb R S x\"\n  unfolding isUb_def by (blast dest: isLubD1 isLubD1a)\n\nlemma isLubD2: \"isLub R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<le> x\"\n  by (blast dest!: isLubD1 setleD)\n\nlemma isLubD3: \"isLub R S x \\<Longrightarrow> leastP (isUb R S) x\"\n  by (simp add: isLub_def)\n\nlemma isLubI1: \"leastP(isUb R S) x \\<Longrightarrow> isLub R S x\"\n  by (simp add: isLub_def)\n\nlemma isLubI2: \"isUb R S x \\<Longrightarrow> x <=* Collect (isUb R S) \\<Longrightarrow> isLub R S x\"\n  by (simp add: isLub_def leastP_def)\n\nlemma isUbD: \"isUb R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<le> x\"\n  by (simp add: isUb_def setle_def)\n\nlemma isUbD2: \"isUb R S x \\<Longrightarrow> S *<= x\"\n  by (simp add: isUb_def)\n\nlemma isUbD2a: \"isUb R S x \\<Longrightarrow> x: R\"\n  by (simp add: isUb_def)\n\nlemma isUbI: \"S *<= x \\<Longrightarrow> x: R \\<Longrightarrow> isUb R S x\"\n  by (simp add: isUb_def)\n\nlemma isLub_le_isUb: \"isLub R S x \\<Longrightarrow> isUb R S y \\<Longrightarrow> x \\<le> y\"\n  unfolding isLub_def by (blast intro!: leastPD3)\n\nlemma isLub_ubs: \"isLub R S x \\<Longrightarrow> x <=* ubs R S\"\n  unfolding ubs_def isLub_def by (rule leastPD2)\n\nlemma isLub_unique: \"[| isLub R S x; isLub R S y |] ==> x = (y::'a::linorder)\"\n  apply (frule isLub_isUb)\n  apply (frule_tac x = y in isLub_isUb)\n  apply (blast intro!: order_antisym dest!: isLub_le_isUb)\n  done\n\nlemma isUb_UNIV_I: \"(\\<And>y. y \\<in> S \\<Longrightarrow> y \\<le> u) \\<Longrightarrow> isUb UNIV S u\"\n  by (simp add: isUbI setleI)\n\n\ndefinition greatestP :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"greatestP P x = (P x \\<and> Collect P *<=  x)\"\n\ndefinition isLb :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isLb R S x = (x <=* S \\<and> x: R)\"\n\ndefinition isGlb :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> 'a::ord \\<Rightarrow> bool\"\n  where \"isGlb R S x = greatestP (isLb R S) x\"\n\ndefinition lbs :: \"'a set \\<Rightarrow> 'a::ord set \\<Rightarrow> 'a set\"\n  where \"lbs R S = Collect (isLb R S)\"\n\n\nsubsection \\<open>Rules about the Operators @{term greatestP}, @{term isLb} and @{term isGlb}\\<close>\n\nlemma greatestPD1: \"greatestP P x \\<Longrightarrow> P x\"\n  by (simp add: greatestP_def)\n\nlemma greatestPD2: \"greatestP P x \\<Longrightarrow> Collect P *<= x\"\n  by (simp add: greatestP_def)\n\nlemma greatestPD3: \"greatestP P x \\<Longrightarrow> y: Collect P \\<Longrightarrow> x \\<ge> y\"\n  by (blast dest!: greatestPD2 setleD)\n\nlemma isGlbD1: \"isGlb R S x \\<Longrightarrow> x <=* S\"\n  by (simp add: isGlb_def isLb_def greatestP_def)\n\nlemma isGlbD1a: \"isGlb R S x \\<Longrightarrow> x: R\"\n  by (simp add: isGlb_def isLb_def greatestP_def)\n\nlemma isGlb_isLb: \"isGlb R S x \\<Longrightarrow> isLb R S x\"\n  unfolding isLb_def by (blast dest: isGlbD1 isGlbD1a)\n\nlemma isGlbD2: \"isGlb R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<ge> x\"\n  by (blast dest!: isGlbD1 setgeD)\n\nlemma isGlbD3: \"isGlb R S x \\<Longrightarrow> greatestP (isLb R S) x\"\n  by (simp add: isGlb_def)\n\nlemma isGlbI1: \"greatestP (isLb R S) x \\<Longrightarrow> isGlb R S x\"\n  by (simp add: isGlb_def)\n\nlemma isGlbI2: \"isLb R S x \\<Longrightarrow> Collect (isLb R S) *<= x \\<Longrightarrow> isGlb R S x\"\n  by (simp add: isGlb_def greatestP_def)\n\nlemma isLbD: \"isLb R S x \\<Longrightarrow> y : S \\<Longrightarrow> y \\<ge> x\"\n  by (simp add: isLb_def setge_def)\n\nlemma isLbD2: \"isLb R S x \\<Longrightarrow> x <=* S \"\n  by (simp add: isLb_def)\n\nlemma isLbD2a: \"isLb R S x \\<Longrightarrow> x: R\"\n  by (simp add: isLb_def)\n\nlemma isLbI: \"x <=* S \\<Longrightarrow> x: R \\<Longrightarrow> isLb R S x\"\n  by (simp add: isLb_def)\n\nlemma isGlb_le_isLb: \"isGlb R S x \\<Longrightarrow> isLb R S y \\<Longrightarrow> x \\<ge> y\"\n  unfolding isGlb_def by (blast intro!: greatestPD3)\n\nlemma isGlb_ubs: \"isGlb R S x \\<Longrightarrow> lbs R S *<= x\"\n  unfolding lbs_def isGlb_def by (rule greatestPD2)\n\nlemma isGlb_unique: \"[| isGlb R S x; isGlb R S y |] ==> x = (y::'a::linorder)\"\n  apply (frule isGlb_isLb)\n  apply (frule_tac x = y in isGlb_isLb)\n  apply (blast intro!: order_antisym dest!: isGlb_le_isLb)\n  done\n\nlemma bdd_above_setle: \"bdd_above A \\<longleftrightarrow> (\\<exists>a. A *<= a)\"\n  by (auto simp: bdd_above_def setle_def)\n\nlemma bdd_below_setge: \"bdd_below A \\<longleftrightarrow> (\\<exists>a. a <=* A)\"\n  by (auto simp: bdd_below_def setge_def)\n\nlemma isLub_cSup: \n  \"(S::'a :: conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> (\\<exists>b. S *<= b) \\<Longrightarrow> isLub UNIV S (Sup S)\"\n  by  (auto simp add: isLub_def setle_def leastP_def isUb_def\n            intro!: setgeI cSup_upper cSup_least)\n\nlemma isGlb_cInf: \n  \"(S::'a :: conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> (\\<exists>b. b <=* S) \\<Longrightarrow> isGlb UNIV S (Inf S)\"\n  by  (auto simp add: isGlb_def setge_def greatestP_def isLb_def\n            intro!: setleI cInf_lower cInf_greatest)\n\nlemma cSup_le: \"(S::'a::conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> S *<= b \\<Longrightarrow> Sup S \\<le> b\"\n  by (metis cSup_least setle_def)\n\nlemma cInf_ge: \"(S::'a :: conditionally_complete_lattice set) \\<noteq> {} \\<Longrightarrow> b <=* S \\<Longrightarrow> Inf S \\<ge> b\"\n  by (metis cInf_greatest setge_def)\n\nlemma cSup_bounds:\n  fixes S :: \"'a :: conditionally_complete_lattice set\"\n  shows \"S \\<noteq> {} \\<Longrightarrow> a <=* S \\<Longrightarrow> S *<= b \\<Longrightarrow> a \\<le> Sup S \\<and> Sup S \\<le> b\"\n  using cSup_least[of S b] cSup_upper2[of _ S a]\n  by (auto simp: bdd_above_setle setge_def setle_def)\n\nlemma cSup_unique: \"(S::'a :: {conditionally_complete_linorder, no_bot} set) *<= b \\<Longrightarrow> (\\<forall>b'<b. \\<exists>x\\<in>S. b' < x) \\<Longrightarrow> Sup S = b\"\n  by (rule cSup_eq) (auto simp: not_le[symmetric] setle_def)\n\nlemma cInf_unique: \"b <=* (S::'a :: {conditionally_complete_linorder, no_top} set) \\<Longrightarrow> (\\<forall>b'>b. \\<exists>x\\<in>S. b' > x) \\<Longrightarrow> Inf S = b\"\n  by (rule cInf_eq) (auto simp: not_le[symmetric] setge_def)\n\ntext\\<open>Use completeness of reals (supremum property) to show that any bounded sequence has a least upper bound\\<close>\n\nlemma reals_complete: \"\\<exists>X. X \\<in> S \\<Longrightarrow> \\<exists>Y. isUb (UNIV::real set) S Y \\<Longrightarrow> \\<exists>t. isLub (UNIV :: real set) S t\"\n  by (intro exI[of _ \"Sup S\"] isLub_cSup) (auto simp: setle_def isUb_def intro!: cSup_upper)\n\nlemma Bseq_isUb: \"\\<And>X :: nat \\<Rightarrow> real. Bseq X \\<Longrightarrow> \\<exists>U. isUb (UNIV::real set) {x. \\<exists>n. X n = x} U\"\n  by (auto intro: isUbI setleI simp add: Bseq_def abs_le_iff)\n\nlemma Bseq_isLub: \"\\<And>X :: nat \\<Rightarrow> real. Bseq X \\<Longrightarrow> \\<exists>U. isLub (UNIV::real set) {x. \\<exists>n. X n = x} U\"\n  by (blast intro: reals_complete Bseq_isUb)\n\nlemma isLub_mono_imp_LIMSEQ:\n  fixes X :: \"nat \\<Rightarrow> real\"\n  assumes u: \"isLub UNIV {x. \\<exists>n. X n = x} u\" (* FIXME: use 'range X' *)\n  assumes X: \"\\<forall>m n. m \\<le> n \\<longrightarrow> X m \\<le> X n\"\n  shows \"X \\<longlonglongrightarrow> u\"\nproof -\n  have \"X \\<longlonglongrightarrow> (SUP i. X i)\"\n    using u[THEN isLubD1] X\n    by (intro LIMSEQ_incseq_SUP) (auto simp: incseq_def image_def eq_commute bdd_above_setle)\n  also have \"(SUP i. X i) = u\"\n    using isLub_cSup[of \"range X\"] u[THEN isLubD1]\n    by (intro isLub_unique[OF _ u]) (auto simp add: image_def eq_commute)\n  finally show ?thesis .\nqed\n\nlemmas real_isGlb_unique = isGlb_unique[where 'a=real]\n\nlemma real_le_inf_subset: \"t \\<noteq> {} \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> \\<exists>b. b <=* s \\<Longrightarrow> Inf s \\<le> Inf (t::real set)\"\n  by (rule cInf_superset_mono) (auto simp: bdd_below_setge)\n\nlemma real_ge_sup_subset: \"t \\<noteq> {} \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> \\<exists>b. s *<= b \\<Longrightarrow> Sup s \\<ge> Sup (t::real set)\"\n  by (rule cSup_subset_mono) (auto simp: bdd_above_setle)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/Lub_Glb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.9099070133672955, "lm_q1q2_score": 0.7678660616436875}}
{"text": "theory Part_1 imports Main\n\nbegin\n\n(* 4.1 *)\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\" |\n\"set (Node left a right) = (set left) \\<union> (set right) \\<union> {a}\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node left a right) = ((\\<forall>x\\<in>set left. x \\<le> a) \\<and> (\\<forall>y\\<in>set right. y > a) \\<and> ord left \\<and> ord right)\"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins n Tip = Node Tip n Tip\" |\n\"ins n (Node left a right) = \n  (if n = a \n    then Node left a right \n  else if n \\<le> a \n    then Node (ins n left) a right\n  else\n    Node left a (ins n right))\"\n\nlemma set_ins [simp] : \"set (ins x t) = {x} \\<union> set t\"\n  apply(induction t)\n   apply(auto)\n  done\n\nlemma ord_ins : \"ord t \\<Longrightarrow> ord (ins i t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\nend", "meta": {"author": "joshua-morris", "repo": "concrete-semantics", "sha": "a6621e2d7b55b7a6965ed17a21befc93cd9dd298", "save_path": "github-repos/isabelle/joshua-morris-concrete-semantics", "path": "github-repos/isabelle/joshua-morris-concrete-semantics/concrete-semantics-a6621e2d7b55b7a6965ed17a21befc93cd9dd298/chapter-4/Part_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.8289388062084421, "lm_q1q2_score": 0.7678491117491795}}
{"text": "theory Chapter3\nimports Main Chapter2\nbegin\n\n\n(* Exercise 3.1 *)\n\ndatatype 'a tree = Tip | Node \" 'a tree\" 'a \" 'a tree\"\n\nfun set :: \" 'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\"\n| \"set (Node l a r) = {a} \\<union> (set l) \\<union> (set r)\"\n\nfun leq_tree :: \"int tree \\<Rightarrow> int \\<Rightarrow> bool\" where\n\"leq_tree Tip x = True\"\n| \"leq_tree (Node l a r) x = ((a \\<le> x) & (leq_tree l x) & (leq_tree r x))\"\n\nfun sg_tree :: \"int tree \\<Rightarrow> int \\<Rightarrow> bool\" where\n\"sg_tree Tip x = True\"\n| \"sg_tree (Node l a r) x = ((x < a) & (sg_tree l x) & (sg_tree r x))\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\"\n| \"ord (Node l a r) = ( (ord l) & (ord r) & (leq_tree l a) & (sg_tree r a)  ) \"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins x Tip = Node Tip x Tip\"\n| \"ins x (Node l a r) = ( \n    if x = a then Node l a r\n    else (if x < a then Node (ins x l) a r  else Node l a (ins x r)) \n)\"\n\nlemma ins_spec : \"set (ins x t) = {x} \\<union> set t\"\n  apply(induction t arbitrary: x)\n   apply(auto)\n  done\n\nlemma tree_ord_prop1 [simp] : \"leq_tree t1 x2  \\<Longrightarrow> x < x2 \\<Longrightarrow> leq_tree (ins x t1) x2\"\n  apply(induction t1 arbitrary: x2 x)\n   apply(auto)\n  done\n\nlemma trich_int_prop : \"\\<not> x < x2 \\<Longrightarrow> x \\<noteq> x2 \\<Longrightarrow> x2 < (x::int)\"\n  apply(auto)\n  done\n\nlemma tree_ord_prop2 [simp]  : \" sg_tree t2 x2 \\<Longrightarrow> x2 < x \\<Longrightarrow> sg_tree (ins x t2) x2\"\n  apply(induction t2 arbitrary: x2 x)\n   apply(auto)\n  done\n\nlemma ord_spec : \"ord t \\<Longrightarrow>  ord (ins x t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n(* Exercise 3.2 *)\n\ninductive palindrome :: \" 'a list \\<Rightarrow> bool \" where\nempty : \" palindrome Nil\"\n| singleton : \"palindrome [a]\"\n| palin_append : \" palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma palindrome_correct : \" palindrome xs \\<Longrightarrow> rev xs = xs \"\n  apply(induction xs rule: palindrome.induct)\n    apply(auto)\n  done\n\n(* Exercise 3.3 *)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where \nrefl : \"star r x x\" |\nstep : \" r x y  \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where \nrefl' : \"star' r x x\" |\nstep' : \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma star_step_symm [intro] : \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  apply(induction rule: star.induct)\n   apply(rule step)\n    apply(auto)\n   apply(rule refl)\n  apply(rule step)\n   apply(auto)\n  done\n\nlemma star'_step'_symm [intro] : \"  star' r y z \\<Longrightarrow> r x y  \\<Longrightarrow>  star' r x z\"\n apply(induction rule: star'.induct)\n   apply(rule step')\n    apply(auto)\n   apply(rule refl')\n  apply(rule step')\n   apply(auto)\n  done\n\nlemma star_star'_equiv : \"star' r x y = star r x y\"\n  apply(rule)\n   apply(induction rule: star'.induct)\n    apply(simp add: refl)\n   apply(auto)\n  apply(induction rule: star.induct)\n   apply(rule refl')\n  apply(auto)\n  done\n\n(* Exercise 3.4 *)\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n iter0: \"iter r 0 x x\"\n| iter1: \"r x y \\<Longrightarrow>  iter r (Suc 0) x y\"\n| iter_step: \"iter r n x y \\<Longrightarrow> iter r m y z \\<Longrightarrow> iter r (n + m) x z\"\n\nlemma trivial [simp] : \"  iter r n y z \\<Longrightarrow> \\<exists> m.  iter r m y z\"\n  by auto\n\nlemma iter_spec : \" star r x y \\<Longrightarrow> EX n.  iter r n x y\"\n  apply(induction rule: star.induct)\n   apply(rule)\n   apply(rule iter0)\n  apply(auto)\n  apply(rule)\n  apply(rule iter_step)\n   apply(rule iter1)\n   apply(assumption)\n  apply(rule)\n   apply(auto)\n  apply(rule iter0)\n  done\n  \n(* Exercise 3.5 *)\n\ndatatype alpha = a | b | c\n\ntype_synonym word = \"alpha list\"\n\ninductive S :: \"word  \\<Rightarrow> bool\" where\nSempty : \"S Nil\"\n| Sconj : \" S w \\<Longrightarrow> S ( a # w @ [b]) \"\n| Sdouble : \" S w \\<Longrightarrow> S u  \\<Longrightarrow> S (w @ u)\"\n\ninductive T :: \"word  \\<Rightarrow> bool\" where\nTempty : \"T Nil\"\n| Talt : \" T w \\<Longrightarrow> T u \\<Longrightarrow> T ( w @ [a] @ u @ [b]) \"\n\nlemma T_append [simp] : \" T u \\<Longrightarrow> T w \\<Longrightarrow> T(w @ u) \"\n  apply(induction rule: T.induct)\n   apply(simp)\n  apply(metis T.simps app_assoc) (* by Sledgehammer *)\n  done\n  \n\nlemma S_T_equiv : \" S w = T w \"\n  apply(rule)\n   apply(induction rule: S.induct)\n     apply(rule Tempty)\n    apply(auto)\n   apply (metis T.simps Tempty append.simps(1) append.simps(2)) (* by Sledgehammer *)\n  apply(induction rule: T.induct)\n   apply(rule)\n  apply(auto)\n  apply(simp add: Sconj Sdouble)\n  done\n  \n  \nend", "meta": {"author": "PHart3", "repo": "Isabelle-exercises", "sha": "f668ff1e75d20b8d53c7d747e53c28813b7c72b1", "save_path": "github-repos/isabelle/PHart3-Isabelle-exercises", "path": "github-repos/isabelle/PHart3-Isabelle-exercises/Isabelle-exercises-f668ff1e75d20b8d53c7d747e53c28813b7c72b1/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7677740336874566}}
{"text": "theory Fib\n  imports Main\nbegin\n\nsection {* Fibonacci *}\n\nfun fib :: \"nat \\<Rightarrow> nat\" where\n  \"fib 0 = 1\"\n  | \"fib (Suc 0) = 1\"\n  | \"fib (Suc (Suc n')) = fib (Suc n') + fib n'\"\n\nvalue \"fib 0\"\nvalue \"fib 1\"\nvalue \"fib (Suc (Suc 0))\"\n\nlemma fib_test1: \"fib 1 = 1\" by simp\nlemma fib_test2: \"fib (Suc 1) = 2\" by simp\nlemma fib_test3: \"fib (Suc (Suc 1)) = 3\" by simp\n\ntheorem fib_thy: \"fib n \\<ge> 1\"\n  apply(induction n rule:fib.induct)\n  apply(auto)\n  done\n\nend", "meta": {"author": "kubo39", "repo": "isabelle-training", "sha": "8305ce734249bc4cc29a6e7091c10deebfedb07b", "save_path": "github-repos/isabelle/kubo39-isabelle-training", "path": "github-repos/isabelle/kubo39-isabelle-training/isabelle-training-8305ce734249bc4cc29a6e7091c10deebfedb07b/Fib.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7677712077965324}}
{"text": "(*\nAuction Theory Toolbox (http://formare.github.io/auctions/)\n\nAuthors:\n* Marco B. Caminati http://caminati.co.nr\n* Manfred Kerber <mnfrd.krbr@gmail.com>\n* Christoph Lange <math.semantic.web@gmail.com>\n* Colin Rowat <c.rowat@bham.ac.uk>\n\nDually licenced under\n* Creative Commons Attribution (CC-BY) 3.0\n* ISC License (1-clause BSD License)\nSee LICENSE file for details\n(Rationale for this dual licence: http://arxiv.org/abs/1107.3212)\n*)\n\nsection \\<open>Additional properties of relations, and operators on relations,\n  as they have been defined by Relations.thy\\<close>\n\ntheory RelationProperties\nimports\n  RelationOperators\n\nbegin\n\nsubsection \\<open>Right-Uniqueness\\<close>\n\n(* flip is applied to pairs so that (flip (x, y)) = (y, x) *)\nlemma injflip: \"inj_on flip A\" \n  by (metis flip_flip inj_on_def)\n\nlemma lm01: \"card P = card (P^-1)\" \n  using card_image flip_conv injflip by metis\n\nlemma cardinalityOneTheElemIdentity: \"(card X = 1) = (X={the_elem X})\" \n  by (metis One_nat_def card_Suc_eq card_empty empty_iff the_elem_eq)\n\nlemma lm02: \"trivial X = (X={} \\<or> card X=1)\" \n  using cardinalityOneTheElemIdentity order_refl subset_singletonD trivial_def trivial_empty by (metis(no_types))\n\nlemma lm03: \"trivial P = trivial (P^-1)\" \n  using trivial_def subset_singletonD  subset_refl subset_insertI cardinalityOneTheElemIdentity converse_inject\n        converse_empty lm01 \n  by metis\n\n(* The range of P restricted to X is equal to the image of X through P *)\nlemma restrictedRange: \"Range (P||X) = P``X\" \n  unfolding restrict_def by blast\n\nlemma doubleRestriction:  \"((P || X) || Y) = (P || (X \\<inter> Y))\" \n  unfolding restrict_def by fast\n\nlemma restrictedDomain: \"Domain (R||X) = Domain R \\<inter> X\" \n  using restrict_def by fastforce\n\ntext \\<open>A subrelation of a right-unique relation is right-unique.\\<close>\n\nlemma subrel_runiq: \n  assumes \"runiq Q\" \"P \\<subseteq> Q\" \n  shows \"runiq P\" \n  using assms runiq_def by (metis Image_mono subsetI trivial_subset)\n\nlemma rightUniqueInjectiveOnFirstImplication: \n  assumes \"runiq P\" \n  shows \"inj_on fst P\" \n  unfolding inj_on_def \n  using assms runiq_def trivial_def trivial_imp_no_distinct \n        the_elem_eq surjective_pairing subsetI Image_singleton_iff \n  by (metis(no_types))\n\ntext \\<open>alternative characterization of right-uniqueness: the image of a singleton set is\n   @{const trivial}, i.e.\\ an empty or a singleton set.\\<close>\nlemma runiq_alt: \"runiq R \\<longleftrightarrow> (\\<forall> x . trivial (R `` {x}))\" \n  unfolding runiq_def by (metis Image_empty2 trivial_empty_or_singleton trivial_singleton) \n \ntext \\<open>an alternative definition of right-uniqueness in terms of @{const eval_rel}\\<close>\n(* Note that R `` {x} is the image of {x} under R and R ,, x gives you an element y such that R x y. Because of right-uniqueness in this case the element is determined, otherwise it may be undetermined *)\nlemma runiq_wrt_eval_rel: \"runiq R = (\\<forall>x . R `` {x} \\<subseteq> {R ,, x})\" \n  by (metis eval_rel.simps runiq_alt trivial_def)\n\nlemma rightUniquePair: \n  assumes \"runiq f\" \n  assumes \"(x,y)\\<in>f\" \n  shows \"y=f,,x\" \n  using assms runiq_wrt_eval_rel subset_singletonD Image_singleton_iff equals0D singletonE \n  by fast\n\nlemma runiq_basic: \"runiq R \\<longleftrightarrow> (\\<forall> x y y' . (x, y) \\<in> R \\<and> (x, y') \\<in> R \\<longrightarrow> y = y')\" \n  unfolding runiq_alt trivial_same by blast\n\nlemma rightUniqueFunctionAfterInverse: \n  assumes \"runiq f\" \n  shows \"f``(f^-1``Y) \\<subseteq> Y\" \n  using assms runiq_basic ImageE converse_iff subsetI by (metis(no_types))\n\nlemma lm04: \n  assumes \"runiq f\" \"y1 \\<in> Range f\" \n  shows \"(f^-1 `` {y1} \\<inter> f^-1 `` {y2} \\<noteq> {}) = (f^-1``{y1}=f^-1``{y2})\"\n  using assms rightUniqueFunctionAfterInverse by fast\n\nlemma converse_Image: \n  assumes runiq: \"runiq R\"\n      and runiq_conv: \"runiq (R^-1)\"\n  shows \"(R^-1) `` R `` X \\<subseteq> X\" \n  using assms by (metis converse_converse rightUniqueFunctionAfterInverse)\n\nlemma lm05: \n  assumes \"inj_on fst P\" \n  shows \"runiq P\" \n  unfolding runiq_basic \n  using assms fst_conv inj_on_def old.prod.inject \n  by (metis(no_types))\n\n(* Another characterization of runiq, relating the set theoretical expression P to the injectivity of the function fst applied to P *)\nlemma rightUniqueInjectiveOnFirst: \"(runiq P) = (inj_on fst P)\" \n  using rightUniqueInjectiveOnFirstImplication lm05 by blast\n\nlemma disj_Un_runiq: \n  assumes \"runiq P\" \"runiq Q\" \"(Domain P) \\<inter> (Domain Q) = {}\" \n  shows \"runiq (P \\<union> Q)\" \n  using assms rightUniqueInjectiveOnFirst fst_eq_Domain injection_union by metis\n\nlemma runiq_paste1: \n  assumes \"runiq Q\" \"runiq (P outside Domain Q)\" \n  shows \"runiq (P +* Q)\"\n  unfolding paste_def \n  using assms disj_Un_runiq Diff_disjoint Un_commute outside_reduces_domain\n  by (metis (poly_guards_query))\n\ncorollary runiq_paste2: \n  assumes \"runiq Q\" \"runiq P\" \n  shows \"runiq (P +* Q)\"\n  using assms runiq_paste1 subrel_runiq Diff_subset Outside_def \n  by (metis)\n\n(* Let f be a function, then its graph {(x, f x)} and all its restrictions such that P x for arbitrary P are right-unique. *)\nlemma rightUniqueRestrictedGraph: \"runiq {(x,f x)| x. P x}\" \n  unfolding runiq_basic by fast\n\nlemma rightUniqueSetCardinality: \n  assumes \"x \\<in> Domain R\" \"runiq R\" \n  shows \"card (R``{x})=1\"\n  using assms  lm02 DomainE Image_singleton_iff empty_iff\n  by (metis runiq_alt)\n\n\ntext \\<open>The image of a singleton set under a right-unique relation is a singleton set.\\<close>\nlemma Image_runiq_eq_eval: \n  assumes \"x \\<in> Domain R\" \"runiq R\" \n  shows \"R `` {x} = {R ,, x}\" \n  using assms rightUniqueSetCardinality\n  by (metis eval_rel.simps cardinalityOneTheElemIdentity)\n\nlemma lm06: \n  assumes \"trivial f\" \n  shows \"runiq f\" \n  using assms trivial_subset_non_empty runiq_basic snd_conv\n  by fastforce\n\ntext \\<open>A singleton relation is right-unique.\\<close>\ncorollary runiq_singleton_rel: \"runiq {(x, y)}\" \n  using trivial_singleton lm06 by fast\n\ntext \\<open>The empty relation is right-unique\\<close>\nlemma runiq_emptyrel: \"runiq {}\" \n  using trivial_empty lm06 by blast\n\n(* characterization of right-uniqueness with  \\<exists>! *)\nlemma runiq_wrt_ex1:\n  \"runiq R \\<longleftrightarrow> (\\<forall> a \\<in> Domain R . \\<exists>! b . (a, b) \\<in> R)\"\n  using runiq_basic by (metis Domain.DomainI Domain.cases)\n\ntext \\<open>alternative characterization of the fact that, if a relation @{term R} is right-unique,\n  its evaluation @{term \"R,,x\"} on some argument @{term x} in its domain, occurs in @{term R}'s\n  range. Note that we need runiq R in order to get a definite value for @{term \"R,,x\"}\\<close>\nlemma eval_runiq_rel:\n  assumes domain: \"x \\<in> Domain R\"\n      and runiq: \"runiq R\" \n  shows \"(x, R,,x) \\<in> R\"\n  using assms by (metis rightUniquePair runiq_wrt_ex1)\n\ntext \\<open>Evaluating a right-unique relation as a function on the relation's domain yields an\n  element from its range.\\<close>\nlemma eval_runiq_in_Range:\n  assumes \"runiq R\"\n      and \"a \\<in> Domain R\"\n  shows \"R ,, a \\<in> Range R\"\n  using assms by (metis Range_iff eval_runiq_rel)\n\n\n\n\n\nsubsection \\<open>Converse\\<close>\n\ntext \\<open>The inverse image of the image of a singleton set under some relation is the same\n  singleton set, if both the relation and its converse are right-unique and the singleton set\n  is in the relation's domain.\\<close>\nlemma converse_Image_singleton_Domain:\n  assumes runiq: \"runiq R\"\n      and runiq_conv: \"runiq (R\\<inverse>)\"\n      and domain: \"x \\<in> Domain R\"\n  shows \"R\\<inverse> `` R `` {x} = {x}\"\nproof -\n  have sup: \"{x} \\<subseteq> R\\<inverse> `` R `` {x}\" using domain by fast\n  have \"trivial (R `` {x})\" using runiq domain by (metis runiq_def trivial_singleton)\n  then have \"trivial (R\\<inverse> `` R `` {x})\"\n    using assms runiq_def by blast\n  then show ?thesis\n    using sup by (metis singleton_sub_trivial_uniq subset_antisym trivial_def)\nqed\n\ntext \\<open>The images of two disjoint sets under an injective function are disjoint.\\<close>\n\nlemma disj_Domain_imp_disj_Image: \n  assumes \"Domain R \\<inter> X \\<inter> Y = {}\" \n  assumes \"runiq R\"\n      and \"runiq (R\\<inverse>)\"\n  shows \"(R `` X) \\<inter> (R `` Y) = {}\" \n  using assms unfolding runiq_basic by blast\n\nlemma runiq_converse_paste_singleton: \n  assumes \"runiq (P^-1)\" \"y\\<notin>(Range P)\" \n  shows \"runiq ((P +* {(x,y)})\\<inverse>)\" \n  (is \"?u (?P^-1)\")\nproof -\n  have \"(?P) \\<subseteq> P \\<union> {(x,y)}\" using assms by (metis paste_sub_Un)\n  then have \"?P^-1 \\<subseteq> P^-1 \\<union> ({(x,y)}^-1)\" by blast\n  moreover have \"... = P^-1 \\<union> {(y,x)}\" by fast\n  moreover have \"Domain (P^-1) \\<inter> Domain {(y,x)} = {}\" using assms(2) by auto\n  ultimately moreover have \"?u (P^-1 \\<union> {(y,x)})\" using assms(1) by (metis disj_Un_runiq runiq_singleton_rel)\n  ultimately show ?thesis by (metis subrel_runiq)\nqed\n\n\n\n\n\n\n\n\n\n\nsubsection \\<open>Injectivity\\<close>\n\ntext \\<open>The following is a classical definition of the set of all injective functions from @{term X} to @{term Y}.\\<close>\ndefinition injections :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<times> 'b) set set\"\n  where \"injections X Y = {R . Domain R = X \\<and> Range R \\<subseteq> Y \\<and> runiq R \\<and> runiq (R\\<inverse>)}\"\n\ntext \\<open>The following definition is a constructive (computational) characterization of the set of all injections X Y, represented by a list. That is, we define the list of all injective functions (represented as relations) from one set (represented as a list) to another set. We formally prove the equivalence of the constructive and the classical definition in Universes.thy.\\<close>\nfun injections_alg (* :: \"'a list \\<Rightarrow> 'b::linorder set \\<Rightarrow> ('a \\<times> 'b) set list\" *)\n  where \"injections_alg [] Y = [{}]\" |\n        \"injections_alg (x # xs) Y = concat [ [ R +* {(x,y)} . y \\<leftarrow> sorted_list_of_set (Y - Range R) ]\n       . R \\<leftarrow> injections_alg xs Y ]\"\n(* We need this as a list in order to be able to iterate over it.  It would be easy to provide \n   an alternative of type ('a \\<times> 'b) set set, by using \\<Union> and set comprehension. *)\n\nlemma Image_within_domain': \n  fixes x R \n  shows \"(x \\<in> Domain R) = (R `` {x} \\<noteq> {})\" \n  by blast\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Vickrey_Clarke_Groves/RelationProperties.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.845942439250491, "lm_q1q2_score": 0.767533915819755}}
{"text": "theory P24 imports Main begin\n\nprimrec insort :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n\"insort x Nil = [x]\" |\n\"insort x (y # ys) = (if (x < y) then ([x, y] @ ys) else (y # (insort x ys)))\"\n\nprimrec sort :: \"nat list \\<Rightarrow> nat list\" where\n\"sort Nil = Nil\" |\n\"sort (x # xs) = (insort x (sort xs))\"\n\nprimrec le :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n\"le n Nil = True\" |\n\"le n (x # xs) = ((n \\<le> x) \\<and> (le n xs))\"\n\nprimrec sorted :: \"nat list \\<Rightarrow> bool\" where\n\"sorted Nil = True\" |\n\"sorted (x # xs) = (if xs = Nil then True else ((x \\<le> hd xs) \\<and> sorted xs))\"\n\n\n\nlemma [simp]: \"P24.sorted xs \\<Longrightarrow> P24.sorted (P24.insort a xs)\"\nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case \n  proof (cases xs)\n    case Nil\n  then show ?thesis by simp\n  next\n    case (Cons y ys)\n    then show ?thesis\n      using Cons.hyps Cons.prems by auto\n  qed\nqed\n\ntheorem \"sorted (sort xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nfun count :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"count xs n = length (filter (\\<lambda>x. x=n) xs)\"\n\nlemma [simp]: \"count (a # xs) x = (count xs x) + (if (x=a) then 1 else 0)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma insort_length[simp]: \"count (insort a xs) x = (count xs x) + (if (x=a) then 1 else 0)\"\n  apply (induct xs arbitrary: a x)\n   apply auto\n  done\n\ntheorem \"count (sort xs) x = count xs x\"\nproof (induct xs arbitrary: x)\ncase Nil\nthen show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case\n  proof (cases \"x=a\")\n    case True\n    print_facts\n    have \"count (sort (a # xs)) x = (count (sort xs) x + 1)\"\n      using True insort_length by auto\n    also have \"\\<dots> = (count xs x + 1)\" using Cons.hyps by auto\n    finally have 1: \"count (P24.sort (a # xs)) x =(count xs x + 1)\" by blast\n    have \"count (a # xs) x = (count xs x + 1)\" using True by simp\n    then show ?thesis using 1 by auto\n  next\n    case False\n    have \"count (sort (a # xs)) x = count (insort a (sort xs)) x\" by simp\n    also have \"\\<dots> = count (sort xs) x\" using False insort_length by auto\n    also have \"\\<dots> = count xs x\" using Cons.hyps by simp\n    finally have 1: \"count (sort (a # xs)) x = count xs x\" by blast\n    have \"count (a # xs) x = count xs x\" using False by simp\n    then show ?thesis using 1 by auto\n  qed\nqed\n\n\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P24.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7675339154615665}}
{"text": "theory Ex029 \n  imports Main \nbegin \n  \n(*since implication has right associativity this is the same as (A \\<longrightarrow> B) \\<longrightarrow> (C \\<longrightarrow> \\<not>B) \\<longrightarrow> A \\<longrightarrow> \\<not>C*)\nlemma \"(A \\<longrightarrow> B) \\<longrightarrow> (C \\<longrightarrow> \\<not>B) \\<longrightarrow> (A \\<longrightarrow> \\<not>C)\"\nproof -\n  {\n    assume a:\"A \\<longrightarrow> B\"\n    {\n      assume b:\"C \\<longrightarrow> \\<not>B\"\n      {\n        assume A\n        with a have c:B by (rule mp)\n        {\n          assume C \n          with b have \"\\<not>B\" by (rule mp)\n          with c have False by contradiction\n        }\n        hence \"\\<not>C\" by (rule notI)\n      }\n      hence \"A \\<longrightarrow> \\<not>C\" by (rule impI)\n    }\n    hence \"(C \\<longrightarrow> \\<not>B) \\<longrightarrow> A \\<longrightarrow> \\<not>C\" by (rule impI)\n  }\n  thus ?thesis by (rule impI)\nqed\n  \n      \n          \n        ", "meta": {"author": "SvenWille", "repo": "LogicForwardProofs", "sha": "b03c110b073eb7c34a561fce94b860b14cde75f7", "save_path": "github-repos/isabelle/SvenWille-LogicForwardProofs", "path": "github-repos/isabelle/SvenWille-LogicForwardProofs/LogicForwardProofs-b03c110b073eb7c34a561fce94b860b14cde75f7/src/propLogic/Ex029.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.8267118004748677, "lm_q1q2_score": 0.7675265061711594}}
{"text": "theory Indices\nimports Main\nbegin\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Basic Lemmas for Manipulating Indices and Lists\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\nfun index_list where\n\"index_list 0 = []\"|\n\"index_list (Suc n) = index_list n @ [n]\"\n\nlemma index_list_length:\n\"length (index_list n) = n\"\n  by(induction n, simp, auto ) \n\nlemma index_list_indices:\n\"k < n \\<Longrightarrow> (index_list n)!k = k\"\n  apply(induction n)\n  apply (simp; fail)\n  by (simp add: index_list_length nth_append)\n\nlemma index_list_set:\n\"set (index_list n) = {..<n}\"\n  apply(induction n)\n  apply force\n  by (metis Zero_not_Suc atLeastLessThan_empty atLeastLessThan_singleton atLeastLessThan_upt \n      diff_Suc_1 index_list.elims ivl_disj_un_singleton(2) lessI lessThan_Suc_atMost less_Suc_eq_le \n      set_append sorted_list_of_set_empty sorted_list_of_set_range upt_rec)\n\nfun flat_map :: \"('a => 'b list) => 'a list => 'b list\" where\n  \"flat_map f [] = []\"\n |\"flat_map f (h#t) = (f h)@(flat_map f t)\"\n\nabbreviation(input) project_at_indices (\"\\<pi>\\<^bsub>_\\<^esub>\") where\n\"project_at_indices S as \\<equiv> nths as S\"\n\nfun insert_at_index :: \" 'a list \\<Rightarrow>'a \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n\"insert_at_index as a n= (take n as) @ (a#(drop n as))\"\n\nlemma insert_at_index_length:\n  shows \"length (insert_at_index as a n) = length as + 1\"\n  by(induction n, auto) \n\nlemma insert_at_index_eq[simp]:\n  assumes \"n \\<le> length as\"\n  shows \"(insert_at_index as a n)!n = a\"\n  by (metis assms insert_at_index.elims length_take min.absorb2 nth_append_length)\n\nlemma insert_at_index_eq'[simp]:\n  assumes \"n \\<le> length as\"\n  assumes \"k < n\"\n  shows \"(insert_at_index as a n)!k = as ! k\"\n  using assms \n  by (simp add: nth_append)\n\nlemma insert_at_index_eq''[simp]:\n  assumes \"n < length as\"\n  assumes \"k \\<le> n\"\n  shows \"(insert_at_index as a k)!(Suc n) = as ! n\"  \n  using assms insert_at_index.simps[of as a k] \n  by (smt Suc_diff_Suc append_take_drop_id diff_Suc_Suc dual_order.order_iff_strict \n      le_imp_less_Suc length_take less_trans min.absorb2 not_le nth_Cons_Suc nth_append)\n\ntext\\<open>Correctness of project\\_at\\_indices\\<close>\n\ndefinition indices_of :: \"'a list \\<Rightarrow> nat set\" where\n\"indices_of as = {..<(length as)}\"\n\nlemma proj_at_index_list_length[simp]:\n  assumes \"S \\<subseteq> indices_of as\"\n  shows \"length (project_at_indices S as) = card S\"\nproof-\n  have \"S = {i. i < length as \\<and> i \\<in> S}\"\n    using assms unfolding indices_of_def \n    by blast\n  thus ?thesis \n  using length_nths[of as S] by auto   \nqed\n\ntext\\<open>A function which enumerates finite sets\\<close>\n\nabbreviation(input) set_to_list :: \"nat set \\<Rightarrow>  nat list\" where\n\"set_to_list S \\<equiv> sorted_list_of_set S\"\n\nlemma set_to_list_set:\n  assumes \"finite S\"\n  shows \"set (set_to_list S) = S\"\n  by (simp add: assms)\n\nlemma set_to_list_length:\n  assumes \"finite S\"\n  shows \"length (set_to_list S) = card S\"\n  by (metis assms length_remdups_card_conv length_sort set_sorted_list_of_set sorted_list_of_set_sort_remdups)\n\nlemma set_to_list_empty:\n  assumes \"card S = 0\"\n  shows \"set_to_list S = []\"\n  by (metis assms length_0_conv length_sorted_list_of_set)\n\nlemma set_to_list_first:\n  assumes \"card S > 0\"\n  shows \"Min S = set_to_list S ! 0 \"\nproof-\n  have 0: \"set (set_to_list S) = S\"\n    using assms card_ge_0_finite set_sorted_list_of_set by blast\n  have 1: \"sorted (set_to_list S)\"\n    by simp\n  show ?thesis apply(rule Min_eqI)\n    using assms card_ge_0_finite apply blast\n     apply (metis \"0\" \"1\" in_set_conv_nth less_Suc0 less_or_eq_imp_le not_less_eq sorted_iff_nth_mono_less)\n      by (metis \"0\" Max_in assms card_0_eq card_ge_0_finite gr_zeroI in_set_conv_nth not_less0)\nqed\n  \nlemma set_to_list_last:\n  assumes \"card S > 0\"\n  shows \"Max S = last (set_to_list S)\"\nproof-\n  have 0: \"set (set_to_list S) = S\"\n    using assms card_ge_0_finite set_sorted_list_of_set by blast\n  have 1: \"sorted (set_to_list S)\"\n    by simp\n  show ?thesis apply(rule Max_eqI)\n    using assms card_ge_0_finite apply blast\n     apply (smt \"0\" \"1\" Suc_diff_1 in_set_conv_nth last_conv_nth le_simps(2) length_greater_0_conv \n        less_or_eq_imp_le nat_neq_iff neq0_conv not_less_eq sorted_iff_nth_mono_less)\n      by (metis \"0\" assms card.empty empty_set last_in_set less_numeral_extra(3))\nqed\n\nlemma set_to_list_insert_Max:\n  assumes \"finite S\"\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> a > s\"\n  shows \"set_to_list (insert a S) = set_to_list S @[a]\"\n  by (metis assms(1) assms(2) card_0_eq card_insert_if finite.insertI infinite_growing \n      insert_not_empty less_imp_le_nat sorted_insort_is_snoc sorted_list_of_set(1) sorted_list_of_set(2) \n      sorted_list_of_set_insert)\n\nlemma set_to_list_insert_Min:\n  assumes \"finite S\"\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> a < s\"\n  shows \"set_to_list (insert a S) = a#set_to_list S\"\n  by (metis assms(1) assms(2) insort_is_Cons nat_less_le sorted_list_of_set(1) sorted_list_of_set_insert)\n\nfun nth_elem where\n\"nth_elem S n = set_to_list S ! n\"\n\nlemma nth_elem_closed:\n  assumes \"i < card S\"\n  shows \"nth_elem S i \\<in> S\"\n  by (metis assms card.infinite not_less0 nth_elem.elims nth_mem set_to_list_length sorted_list_of_set(1))\n\nlemma nth_elem_Min:\n  assumes \"card S > 0\"\n  shows \"nth_elem S 0 = Min S\"\n  by (simp add: assms  set_to_list_first)\n\nlemma nth_elem_Max:\n  assumes \"card S > 0\"\n  shows \"nth_elem S (card S - 1) = Max S\"\nproof-\n  have \"last (set_to_list S) = set_to_list S ! (card S - 1)\"\n    by (metis assms card_0_eq card_ge_0_finite last_conv_nth neq0_conv set_to_list_length sorted_list_of_set_eq_Nil_iff)\n  thus ?thesis \n    using assms set_to_list_last set_to_list_length \n    by simp\nqed\n\nlemma nth_elem_Suc:\n  assumes \"card S > Suc n\"\n  shows \"nth_elem S (Suc n) > nth_elem S n\"\n  using assms sorted_sorted_list_of_set[of S] set_to_list_length[of S]\n  by (metis Suc_lessD card.infinite distinct_sorted_list_of_set lessI nat_less_le not_less0 nth_elem.elims nth_eq_iff_index_eq sorted_iff_nth_mono_less)\n\nlemma nth_elem_insert_Min:\n  assumes \"card S > 0\"\n  assumes \"a < Min S\"\n  shows \"nth_elem (insert a S) (Suc i) = nth_elem S i\"\n  using assms  \n  by (metis Min_gr_iff card_0_eq card_ge_0_finite neq0_conv nth_Cons_Suc nth_elem.elims set_to_list_insert_Min)\n  \nlemma set_to_list_Suc_map:\n  assumes \"finite S\"\n  shows \"set_to_list (Suc ` S) = map Suc (set_to_list S)\"\nproof-\n  obtain n where n_def: \"n = card S\"\n    by blast \n  have \"\\<And>S. card S = n \\<Longrightarrow> set_to_list (Suc ` S) = map Suc (set_to_list S)\"\n  proof(induction n)\n    case 0\n    then show ?case \n      by (metis card_eq_0_iff finite_imageD image_is_empty inj_Suc list.simps(8) set_to_list_empty)\n  next\n    case (Suc n)\n    have 0: \"S = insert (Min S) (S - {Min S})\"\n      by (metis Min_in Suc.prems card_gt_0_iff insert_Diff zero_less_Suc)\n    have 1: \"sorted_list_of_set (Suc ` (S - {Min S})) = map Suc (sorted_list_of_set (S - {Min S}))\"\n      by (metis \"0\" Suc.IH Suc.prems card_Diff_singleton card.infinite diff_Suc_1 insertI1 nat.simps(3))\n    have 2: \"set_to_list S = (Min S)#(set_to_list (S - {Min S}))\"\n      by (metis \"0\" DiffD1 Min_le Suc.prems card_Diff_singleton card.infinite card_insert_if  \n          diff_Suc_1 finite_Diff n_not_Suc_n nat.simps(3) nat_less_le set_to_list_insert_Min)\n    have 3: \"sorted_list_of_set (Suc ` S) = (Min (Suc ` S))#(set_to_list ((Suc ` S) - {Min (Suc ` S)}))\"\n      by (metis DiffD1 Diff_idemp Min_in Min_le Suc.prems card_Diff1_less card_eq_0_iff finite_Diff \n          finite_imageI image_is_empty insert_Diff nat.simps(3) nat_less_le set_to_list_insert_Min)\n    have 4: \"(Min (Suc ` S)) = Suc (Min S)\"\n      by (metis Min.hom_commute Suc.prems Suc_le_mono card_eq_0_iff min_def nat.simps(3))\n    have 5: \"sorted_list_of_set (Suc ` S) = Suc (Min S)#(set_to_list ((Suc ` S) - {Suc (Min S)}))\"\n      using 3 4 by auto \n    have 6: \"sorted_list_of_set (Suc ` S) = Suc (Min S)#(set_to_list (Suc ` (S - {Min S})))\"\n      by (metis (no_types, lifting) \"0\" \"5\" Diff_insert_absorb image_insert inj_Suc inj_on_insert)\n    show ?case \n      using 6 \n      by (simp add: \"1\" \"2\")\n  qed  \n  thus ?thesis \n    using n_def by blast\nqed\n\nlemma nth_elem_Suc_im:\n  assumes \"i < card S\"\n  shows \"nth_elem (Suc ` S) i = Suc (nth_elem S i) \"\n  using set_to_list_Suc_map \n  by (metis assms card_ge_0_finite dual_order.strict_trans not_gr0 nth_elem.elims nth_map set_to_list_length)\n\nlemma set_to_list_upto:\n\"set_to_list {..<n} = [0..<n]\"\n  by (simp add: lessThan_atLeast0)\n\nlemma nth_elem_upto:\n  assumes \"i < n\"\n  shows \"nth_elem {..<n} i = i\"\n  using set_to_list_upto \n  by (simp add: assms)\n\ntext\\<open>Characterizing the entries of project\\_at\\_indices \\<close>\n\nlemma project_at_indices_append:\n\"project_at_indices S (as@bs) = project_at_indices S as @ project_at_indices {j. j + length as \\<in> S} bs\"\n  using nths_append[of as bs S] by auto \n\nlemma project_at_indices_nth:\n  assumes \"S \\<subseteq> indices_of as\"\n  assumes \"card S > i\"\n  shows \"project_at_indices S as ! i = as ! (nth_elem S i)\"\nproof-\n  have \"\\<And> S i. S \\<subseteq> indices_of as \\<and> card S > i \\<Longrightarrow> project_at_indices S as ! i = as ! (nth_elem S i)\"\n  proof(induction as)\n    case Nil\n    then show ?case \n      by (metis list.size(3) not_less0 nths_nil proj_at_index_list_length)   \n  next\n    case (Cons a as)\n    assume A: \"S \\<subseteq> indices_of (a # as) \\<and> i < card S\"\n    have 0: \"nths (a # as) S = (if 0 \\<in> S then [a] else []) @ nths as {j. Suc j \\<in> S}\"\n      using nths_Cons[of a as S] by simp \n    show \"nths (a # as) S ! i = (a # as) ! nth_elem S i\"\n    proof(cases \"0 \\<in> S\")\n      case True\n      show ?thesis \n      proof(cases \"S = {0}\")\n        case True\n        then show ?thesis \n          using \"0\" Cons.prems  by auto        \n      next\n        case False\n        have T0: \"nths (a # as) S = a#nths as {j. Suc j \\<in> S}\"\n          using 0 \n          by (simp add: True)\n        have T1: \"{j. Suc j \\<in> S} \\<subseteq> indices_of as\"\n        proof fix x assume A: \"x \\<in> {j. Suc j \\<in> S}\"\n          then have \"Suc x < length (a#as)\" \n          using Cons.prems indices_of_def by blast\n         then show \"x \\<in> indices_of as\"\n          by (simp add: indices_of_def)\n        qed\n        have T2: \"\\<And>i.  i < card {j. Suc j \\<in> S} \\<Longrightarrow> nths as {j. Suc j \\<in> S} ! i = as ! nth_elem {j. Suc j \\<in> S} i\"\n          using Cons.IH T1 by blast\n        have T3: \"\\<And>i.  i < card {j. Suc j \\<in> S} \\<Longrightarrow> nth_elem {j. j > 0 \\<and> j\\<in> S} i = nth_elem S (Suc i)\"\n        proof-\n          have 0: \" 0 < card {j. Suc j \\<in> S}\" \n            by (smt Cons.prems Diff_iff Diff_subset False T0 T1 True add_diff_cancel_left' \n                card.insert card_0_eq card.infinite finite_subset gr_zeroI insert_Diff \n                length_Cons n_not_Suc_n plus_1_eq_Suc proj_at_index_list_length singletonI)\n          have 1: \"(insert 0 {j. 0 < j \\<and> j \\<in> S}) = S\"\n            apply(rule set_eqI) using True  gr0I by blast\n          have 2: \"0 < Min {j. 0 < j \\<and> j \\<in> S}\" using False \n            by (metis (mono_tags, lifting) \"1\" Cons.prems Min_in finite_insert finite_lessThan\n                finite_subset indices_of_def less_Suc_eq less_Suc_eq_0_disj mem_Collect_eq singleton_conv)    \n          show \"\\<And>i. i < card {j. Suc j \\<in> S} \\<Longrightarrow> nth_elem {j. 0 < j \\<and> j \\<in> S} i = nth_elem S (Suc i)\"\n            using 0 1 2 nth_elem_insert_Min[of \"{j. 0 < j \\<and> j \\<in> S}\" 0] True False \n            by (metis (no_types, lifting) Cons.prems T0 T1 card_gt_0_iff finite_insert length_Cons less_SucI proj_at_index_list_length)\n        qed      \n        show \"nths (a # as) S ! i = (a # as) ! nth_elem S i\"\n          apply(cases \"i = 0\")\n           apply (metis Cons.prems Min_le T0 True card_ge_0_finite le_zero_eq nth_Cons' nth_elem_Min)           \n        proof-\n          assume \"i \\<noteq> 0\"\n          then have \"i = Suc (i - 1)\"\n            using Suc_pred' by blast\n          hence \"nths (a # as) S ! i = nths as {j. Suc j \\<in> S} ! (i-1)\"\n            using A by (simp add: T0)\n          thus \"nths (a # as) S ! i = (a # as) ! nth_elem S i\"\n          proof-\n            have \"i - 1 < card {j. Suc j \\<in> S}\"\n              by (metis Cons.prems Suc_less_SucD T0 T1 \\<open>i = Suc (i - 1)\\<close> length_Cons proj_at_index_list_length)\n            hence 0: \"nth_elem {j. 0 < j \\<and> j \\<in> S} (i - 1) = nth_elem S i\" \n              using T3[of \"i-1\"] \\<open>i = Suc (i - 1)\\<close> by auto   \n\n            have 1: \"nths as {j. Suc j \\<in> S} ! (i-1) = as ! nth_elem {j. Suc j \\<in> S} (i-1)\"\n              using T2 \\<open>i - 1 < card {j. Suc j \\<in> S}\\<close> by blast\n            have 2: \"(a # as) ! nth_elem S i = as! ((nth_elem S i) - 1)\"\n              by (metis Cons.prems \\<open>i = Suc (i - 1)\\<close> not_less0 nth_Cons' nth_elem_Suc)\n            have 3: \"(nth_elem S i) - 1 = nth_elem {j. Suc j \\<in> S} (i-1)\"\n            proof-\n              have \"Suc ` {j. Suc j \\<in> S} = {j. 0 < j \\<and> j \\<in> S}\"\n              proof\n                show \"Suc ` {j. Suc j \\<in> S} \\<subseteq> {j. 0 < j \\<and> j \\<in> S}\"\n                  by blast\n                show \"{j. 0 < j \\<and> j \\<in> S} \\<subseteq> Suc ` {j. Suc j \\<in> S}\"\n                  using Suc_pred gr0_conv_Suc by auto\n              qed\n              thus ?thesis \n                using \"0\" \\<open>i - 1 < card {j. Suc j \\<in> S}\\<close> nth_elem_Suc_im by fastforce\n            qed\n            show \"nths (a # as) S ! i = (a # as) ! nth_elem S i\"\n              using \"1\" \"2\" \"3\" \\<open>nths (a # as) S ! i = nths as {j. Suc j \\<in> S} ! (i - 1)\\<close> by auto\n          qed\n        qed\n      qed\n    next\n      case False\n      have F0: \"nths (a # as) S = nths as {j. Suc j \\<in> S}\"\n        by (simp add: \"0\" False)\n      have F1: \"Suc `{j. Suc j \\<in> S} = S\"\n      proof show \"Suc ` {j. Suc j \\<in> S} \\<subseteq> S\" by auto \n            show \"S \\<subseteq> Suc ` {j. Suc j \\<in> S}\"  using False Suc_pred  \n                by (smt image_iff mem_Collect_eq neq0_conv subsetI)\n      qed\n      have F2: \"{j. Suc j \\<in> S} \\<subseteq> indices_of as \\<and> i < card {j. Suc j \\<in> S}\"\n        using F1 \n        by (metis (mono_tags, lifting) A F0 Suc_less_SucD indices_of_def length_Cons lessThan_iff\n            mem_Collect_eq proj_at_index_list_length subset_iff)        \n      have F3: \"project_at_indices {j. Suc j \\<in> S} as ! i = as ! (nth_elem {j. Suc j \\<in> S} i)\"\n        using F2 Cons(1)[of \"{j. Suc j \\<in> S}\"] Cons(2)\n        by blast\n      then show ?thesis \n        using F0 F1 F2 nth_elem_Suc_im by fastforce\n    qed\n  qed\n  then show ?thesis \n    using assms(1) assms(2) by blast\nqed\n\ntext\\<open>An inverse for nth\\_elem\\<close>\n\ndefinition set_rank where\n\"set_rank S x = (THE i. i < card S \\<and> x = nth_elem S i)\"\n\nlemma set_rank_exist:\n  assumes \"finite S\"\n  assumes \"x \\<in> S\"\n  shows \"\\<exists>i. i < card S \\<and> x = nth_elem S i\"\n  using assms nth_elem.simps[of S]\n  by (metis in_set_conv_nth set_to_list_length sorted_list_of_set(1))  \n\nlemma set_rank_unique:\n  assumes \"finite S\"\n  assumes \"x \\<in> S\"\n  assumes \"i < card S \\<and> x = nth_elem S i\"\n  assumes \"j < card S \\<and> x = nth_elem S j\"\n  shows \"i = j\"\n  using assms nth_elem.simps[of S]\n  by (simp add: \\<open>i < card S \\<and> x = nth_elem S i\\<close> \\<open>j < card S \\<and> x = nth_elem S j\\<close>\n      nth_eq_iff_index_eq set_to_list_length)\n\nlemma nth_elem_set_rank_inv:\n  assumes \"finite S\"\n  assumes \"x \\<in> S\"\n  shows \"nth_elem S (set_rank S x) = x\"\n  using the_equality  set_rank_unique set_rank_exist assms \n  unfolding set_rank_def \n  by smt\n\nlemma set_rank_nth_elem_inv:\n  assumes \"finite S\"\n  assumes \"i < card S\"\n  shows \"set_rank S (nth_elem S i) = i\"\n  using the_equality  set_rank_unique set_rank_exist assms \n  unfolding set_rank_def \nproof -\n  show \"(THE n. n < card S \\<and> nth_elem S i = nth_elem S n) = i\"\n    using assms(1) assms(2) nth_elem_closed set_rank_unique by blast\nqed\n \nlemma set_rank_range:\n  assumes \"finite S\"\n  assumes \"x \\<in> S\"\n  shows \"set_rank S x < card S\"\n  using assms(1) assms(2) set_rank_exist set_rank_nth_elem_inv by fastforce\n\nlemma project_at_indices_nth':\n  assumes \"S \\<subseteq> indices_of as\"\n  assumes \"i \\<in> S\"\n  shows \"as ! i = project_at_indices S as ! (set_rank S i) \"\n  by (metis assms(1) assms(2) finite_lessThan finite_subset indices_of_def nth_elem_set_rank_inv \n      project_at_indices_nth set_rank_range)\n\nfun proj_away_from_index :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" (\"\\<pi>\\<^bsub>\\<noteq>_\\<^esub>\")where\n\"proj_away_from_index n as = (take n as)@(drop (Suc n) as)\"\n\ntext\\<open>proj\\_away\\_from\\_index is an inverse to insert\\_at\\_index\\<close>\n\nlemma insert_at_index_project_away[simp]:\n  assumes \"k < length as\"\n  assumes \"bs = (insert_at_index as a k)\"\n  shows \"\\<pi>\\<^bsub>\\<noteq> k\\<^esub> bs = as\"\n  using assms insert_at_index.simps[of as a k] proj_away_from_index.simps[of k bs]\n  by (simp add: \\<open>k < length as\\<close> less_imp_le_nat min.absorb2)\n\ndefinition fibred_cell :: \"'a list set \\<Rightarrow> ('a list \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list set\" where \n\"fibred_cell C P = {as . \\<exists>x t. as = (t#x) \\<and> x \\<in> C \\<and> (P x t)}\"\n\ndefinition fibred_cell_at_ind :: \"nat \\<Rightarrow> 'a list set \\<Rightarrow> ('a list \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list set\" where\n\"fibred_cell_at_ind n C P = {as . \\<exists>x t. as = (insert_at_index x t n) \\<and> x \\<in> C \\<and> (P x t)}\"\n\nlemma fibred_cell_lengths:\n  assumes \"\\<And>k. k \\<in> C \\<Longrightarrow> length k = n\"\n  shows \"k \\<in> (fibred_cell C P) \\<Longrightarrow> length k = Suc n\"\nproof-\n  assume \"k \\<in> (fibred_cell C P)\"\n  obtain x t where \"k = (t#x) \\<and> x \\<in> C \\<and> P x t\"\n  proof -\n    assume a1: \"\\<And>t x. k = t # x \\<and> x \\<in> C \\<and> P x t \\<Longrightarrow> thesis\"\n    have \"\\<exists>as a. k = a # as \\<and> as \\<in> C \\<and> P as a\"\n      using \\<open>k \\<in> fibred_cell C P\\<close> fibred_cell_def by blast\n    then show ?thesis\n      using a1 by blast\n  qed\n  then show ?thesis \n    by (simp add: assms)\nqed\n\nlemma fibred_cell_at_ind_lengths:\n  assumes \"\\<And>k. k \\<in> C \\<Longrightarrow> length k = n\"\n  assumes \"k \\<le> n\"\n  shows \"c \\<in> (fibred_cell_at_ind k C P) \\<Longrightarrow> length c = Suc n\"\nproof-\n  assume \"c \\<in> (fibred_cell_at_ind k C P)\"\n  then obtain x t where \"c = (insert_at_index x t k) \\<and> x \\<in> C \\<and> (P x t)\"\n    using assms\n    unfolding fibred_cell_at_ind_def \n    by blast\n  then show ?thesis \n    by (simp add: assms(1))   \nqed\n\nlemma project_fibred_cell:\n  assumes \"\\<And>k. k \\<in> C \\<Longrightarrow> length k = n\"\n  assumes \"k < n\"\n  assumes \"\\<forall>x \\<in> C. \\<exists>t. P x t\"\n  shows \"\\<pi>\\<^bsub>\\<noteq> k\\<^esub> ` (fibred_cell_at_ind k C P) = C\"\nproof\n  show \"\\<pi>\\<^bsub>\\<noteq>k\\<^esub> ` fibred_cell_at_ind k C P \\<subseteq> C\"\n  proof\n    fix x\n    assume x_def: \"x \\<in> \\<pi>\\<^bsub>\\<noteq>k\\<^esub> ` fibred_cell_at_ind k C P\"\n    then obtain c where c_def: \"x = \\<pi>\\<^bsub>\\<noteq>k\\<^esub> c \\<and> c \\<in>  fibred_cell_at_ind k C P\"\n      by blast\n    then obtain y t where yt_def: \"c = (insert_at_index y t k) \\<and> y \\<in> C \\<and> (P y t)\"\n      using assms\n      unfolding fibred_cell_at_ind_def \n      by blast\n    have 0: \"x =\\<pi>\\<^bsub>\\<noteq>k\\<^esub> c\"\n      by (simp add: c_def)\n    have 1: \"y =\\<pi>\\<^bsub>\\<noteq>k\\<^esub> c\"\n      using yt_def  assms(1) assms(2)\n      by (metis insert_at_index_project_away)      \n    have 2: \"x = y\" using 0 1 by auto \n    then show \"x \\<in> C\"\n      by (simp add: yt_def)\n  qed\n  show \"C \\<subseteq> \\<pi>\\<^bsub>\\<noteq>k\\<^esub> ` fibred_cell_at_ind k C P\"\n  proof fix x\n    assume A: \"x \\<in> C\"\n    obtain t where t_def: \"P x t\"\n      using assms A by auto \n    then show \"x \\<in> \\<pi>\\<^bsub>\\<noteq>k\\<^esub> ` fibred_cell_at_ind k C P\"\n    proof -\n      have f1: \"\\<forall>a n A as. take n as @ (a::'a) # drop n as \\<notin> A \\<or> as \\<in> \\<pi>\\<^bsub>\\<noteq>n\\<^esub> ` A \\<or> \\<not> n < length as\"\n        by (metis insert_at_index.simps insert_at_index_project_away rev_image_eqI)        \n      have \"\\<forall>n. \\<exists>as a. take n x @ t # drop n x = insert_at_index as a n \\<and> as \\<in> C \\<and> P as a\"\n        using A t_def by auto \n      then have \"\\<forall>n. take n x @ t # drop n x \\<in> {insert_at_index as a n |as a. as \\<in> C \\<and> P as a}\"\n        by blast\n      then have \"x \\<in> \\<pi>\\<^bsub>\\<noteq>k\\<^esub> ` {insert_at_index as a k |as a. as \\<in> C \\<and> P as a}\"\n        using f1 by (metis (lifting) A assms(1) assms(2))\n      then show ?thesis\n        by (simp add: fibred_cell_at_ind_def)\n    qed\n  qed\nqed\n\ndefinition list_segment where\n\"list_segment i j as = map (nth as)  [i..<j]\"\n\nlemma list_segment_length:\n  assumes \"i \\<le> j\"\n  assumes \"j \\<le>  length as\"\n  shows \"length (list_segment i j as) = j - i\"\n  using  assms \n  unfolding list_segment_def   \n  by (metis length_map length_upt)\n\nlemma list_segment_drop:\n  assumes \"i < length as\"\n  shows \"(list_segment i (length as) as) = drop i  as\"\n  by (metis One_nat_def Suc_diff_Suc add_diff_inverse_nat drop0  drop_map drop_upt\n      less_Suc_eq list_segment_def map_nth neq0_conv not_less0 plus_1_eq_Suc)\n  \nlemma list_segment_concat:\n  assumes \"j \\<le> k\"\n  assumes \"i \\<le> j\"\n  shows \"(list_segment i j as) @ (list_segment j k as) = (list_segment i k as)\"\n  using assms   unfolding list_segment_def \n  using le_Suc_ex upt_add_eq_append \n  by fastforce\n\nlemma list_segment_subset:\n  assumes \"j \\<le> k\"\n  shows \"set (list_segment i j as) \\<subseteq> set (list_segment i k as)\"\n  apply(cases \"i > j\")\n  unfolding list_segment_def \n  apply (metis in_set_conv_nth length_map list.size(3) order.asym subsetI upt_rec zero_order(3))\nproof-\n  assume \"\\<not> j < i\"\n  then have \"i \\<le>j\"\n    using not_le \n    by blast\n  then have \"list_segment i j as @ list_segment j k as = list_segment i k as\"\n    using assms list_segment_concat[of j k i as] by auto \n  then show \"set (map ((!) as) [i..<j]) \\<subseteq> set (map ((!) as) [i..<k])\" \n    using set_append  unfolding list_segment_def \n    by (metis Un_upper1)\nqed\n\nlemma list_segment_subset_list_set:\n  assumes \"j \\<le> length as\"\n  shows \"set (list_segment i j as) \\<subseteq> set as\"\n  apply(cases \"i \\<ge> j\")\n  apply (simp add: list_segment_def)\nproof-\n  assume A: \"\\<not> j \\<le> i\"\n  then have B: \"i < j\"\n    by auto \n  have 0: \"list_segment i (length as) as = drop i as\"\n    using B assms list_segment_drop[of i as] less_le_trans \n    by blast\n  have 1: \"set (list_segment i j as) \\<subseteq> set (list_segment i (length as) as)\"\n    using B assms list_segment_subset[of j \"length as\" i as] \n    by blast\n  then show ?thesis \n  using assms 0 dual_order.trans  set_drop_subset[of i as]\n    by metis\nqed\n\ndefinition fun_inv where \n\"fun_inv = inv\"\n\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Padic_Field/Indices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7675218760238477}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_bin_nat_plus\nimports \"../../Test_Base\"\nbegin\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Bin = One | ZeroAnd \"Bin\" | OneAnd \"Bin\"\n\nfun s :: \"Bin => Bin\" where\n\"s (One) = ZeroAnd One\"\n| \"s (ZeroAnd xs) = OneAnd xs\"\n| \"s (OneAnd ys) = ZeroAnd (s ys)\"\n\nfun plus2 :: \"Bin => Bin => Bin\" where\n\"plus2 (One) y = s y\"\n| \"plus2 (ZeroAnd z) (One) = s (ZeroAnd z)\"\n| \"plus2 (ZeroAnd z) (ZeroAnd ys) = ZeroAnd (plus2 z ys)\"\n| \"plus2 (ZeroAnd z) (OneAnd xs) = OneAnd (plus2 z xs)\"\n| \"plus2 (OneAnd x2) (One) = s (OneAnd x2)\"\n| \"plus2 (OneAnd x2) (ZeroAnd zs) = OneAnd (plus2 x2 zs)\"\n| \"plus2 (OneAnd x2) (OneAnd ys2) = ZeroAnd (s (plus2 x2 ys2))\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n\"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun toNat :: \"Bin => Nat\" where\n\"toNat (One) = S Z\"\n| \"toNat (ZeroAnd xs) = plus (toNat xs) (toNat xs)\"\n| \"toNat (OneAnd ys) = plus (plus (S Z) (toNat ys)) (toNat ys)\"\n\ntheorem property0 :\n  \"((toNat (plus2 x y)) = (plus (toNat x) (toNat y)))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_bin_nat_plus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7673516989638115}}
{"text": "(*  Title:      HOL/Num.thy\n    Author:     Florian Haftmann\n    Author:     Brian Huffman\n*)\n\nsection {* Binary Numerals *}\n\ntheory Num\nimports BNF_Least_Fixpoint\nbegin\n\nsubsection {* The @{text num} type *}\n\ndatatype num = One | Bit0 num | Bit1 num\n\ntext {* Increment function for type @{typ num} *}\n\nprimrec inc :: \"num \\<Rightarrow> num\" where\n  \"inc One = Bit0 One\" |\n  \"inc (Bit0 x) = Bit1 x\" |\n  \"inc (Bit1 x) = Bit0 (inc x)\"\n\ntext {* Converting between type @{typ num} and type @{typ nat} *}\n\nprimrec nat_of_num :: \"num \\<Rightarrow> nat\" where\n  \"nat_of_num One = Suc 0\" |\n  \"nat_of_num (Bit0 x) = nat_of_num x + nat_of_num x\" |\n  \"nat_of_num (Bit1 x) = Suc (nat_of_num x + nat_of_num x)\"\n\nprimrec num_of_nat :: \"nat \\<Rightarrow> num\" where\n  \"num_of_nat 0 = One\" |\n  \"num_of_nat (Suc n) = (if 0 < n then inc (num_of_nat n) else One)\"\n\nlemma nat_of_num_pos: \"0 < nat_of_num x\"\n  by (induct x) simp_all\n\nlemma nat_of_num_neq_0: \" nat_of_num x \\<noteq> 0\"\n  by (induct x) simp_all\n\nlemma nat_of_num_inc: \"nat_of_num (inc x) = Suc (nat_of_num x)\"\n  by (induct x) simp_all\n\nlemma num_of_nat_double:\n  \"0 < n \\<Longrightarrow> num_of_nat (n + n) = Bit0 (num_of_nat n)\"\n  by (induct n) simp_all\n\ntext {*\n  Type @{typ num} is isomorphic to the strictly positive\n  natural numbers.\n*}\n\nlemma nat_of_num_inverse: \"num_of_nat (nat_of_num x) = x\"\n  by (induct x) (simp_all add: num_of_nat_double nat_of_num_pos)\n\nlemma num_of_nat_inverse: \"0 < n \\<Longrightarrow> nat_of_num (num_of_nat n) = n\"\n  by (induct n) (simp_all add: nat_of_num_inc)\n\nlemma num_eq_iff: \"x = y \\<longleftrightarrow> nat_of_num x = nat_of_num y\"\n  apply safe\n  apply (drule arg_cong [where f=num_of_nat])\n  apply (simp add: nat_of_num_inverse)\n  done\n\nlemma num_induct [case_names One inc]:\n  fixes P :: \"num \\<Rightarrow> bool\"\n  assumes One: \"P One\"\n    and inc: \"\\<And>x. P x \\<Longrightarrow> P (inc x)\"\n  shows \"P x\"\nproof -\n  obtain n where n: \"Suc n = nat_of_num x\"\n    by (cases \"nat_of_num x\", simp_all add: nat_of_num_neq_0)\n  have \"P (num_of_nat (Suc n))\"\n  proof (induct n)\n    case 0 show ?case using One by simp\n  next\n    case (Suc n)\n    then have \"P (inc (num_of_nat (Suc n)))\" by (rule inc)\n    then show \"P (num_of_nat (Suc (Suc n)))\" by simp\n  qed\n  with n show \"P x\"\n    by (simp add: nat_of_num_inverse)\nqed\n\ntext {*\n  From now on, there are two possible models for @{typ num}:\n  as positive naturals (rule @{text \"num_induct\"})\n  and as digit representation (rules @{text \"num.induct\"}, @{text \"num.cases\"}).\n*}\n\n\nsubsection {* Numeral operations *}\n\ninstantiation num :: \"{plus,times,linorder}\"\nbegin\n\ndefinition [code del]:\n  \"m + n = num_of_nat (nat_of_num m + nat_of_num n)\"\n\ndefinition [code del]:\n  \"m * n = num_of_nat (nat_of_num m * nat_of_num n)\"\n\ndefinition [code del]:\n  \"m \\<le> n \\<longleftrightarrow> nat_of_num m \\<le> nat_of_num n\"\n\ndefinition [code del]:\n  \"m < n \\<longleftrightarrow> nat_of_num m < nat_of_num n\"\n\ninstance\n  by (default, auto simp add: less_num_def less_eq_num_def num_eq_iff)\n\nend\n\nlemma nat_of_num_add: \"nat_of_num (x + y) = nat_of_num x + nat_of_num y\"\n  unfolding plus_num_def\n  by (intro num_of_nat_inverse add_pos_pos nat_of_num_pos)\n\nlemma nat_of_num_mult: \"nat_of_num (x * y) = nat_of_num x * nat_of_num y\"\n  unfolding times_num_def\n  by (intro num_of_nat_inverse mult_pos_pos nat_of_num_pos)\n\nlemma add_num_simps [simp, code]:\n  \"One + One = Bit0 One\"\n  \"One + Bit0 n = Bit1 n\"\n  \"One + Bit1 n = Bit0 (n + One)\"\n  \"Bit0 m + One = Bit1 m\"\n  \"Bit0 m + Bit0 n = Bit0 (m + n)\"\n  \"Bit0 m + Bit1 n = Bit1 (m + n)\"\n  \"Bit1 m + One = Bit0 (m + One)\"\n  \"Bit1 m + Bit0 n = Bit1 (m + n)\"\n  \"Bit1 m + Bit1 n = Bit0 (m + n + One)\"\n  by (simp_all add: num_eq_iff nat_of_num_add)\n\nlemma mult_num_simps [simp, code]:\n  \"m * One = m\"\n  \"One * n = n\"\n  \"Bit0 m * Bit0 n = Bit0 (Bit0 (m * n))\"\n  \"Bit0 m * Bit1 n = Bit0 (m * Bit1 n)\"\n  \"Bit1 m * Bit0 n = Bit0 (Bit1 m * n)\"\n  \"Bit1 m * Bit1 n = Bit1 (m + n + Bit0 (m * n))\"\n  by (simp_all add: num_eq_iff nat_of_num_add\n    nat_of_num_mult distrib_right distrib_left)\n\nlemma eq_num_simps:\n  \"One = One \\<longleftrightarrow> True\"\n  \"One = Bit0 n \\<longleftrightarrow> False\"\n  \"One = Bit1 n \\<longleftrightarrow> False\"\n  \"Bit0 m = One \\<longleftrightarrow> False\"\n  \"Bit1 m = One \\<longleftrightarrow> False\"\n  \"Bit0 m = Bit0 n \\<longleftrightarrow> m = n\"\n  \"Bit0 m = Bit1 n \\<longleftrightarrow> False\"\n  \"Bit1 m = Bit0 n \\<longleftrightarrow> False\"\n  \"Bit1 m = Bit1 n \\<longleftrightarrow> m = n\"\n  by simp_all\n\nlemma le_num_simps [simp, code]:\n  \"One \\<le> n \\<longleftrightarrow> True\"\n  \"Bit0 m \\<le> One \\<longleftrightarrow> False\"\n  \"Bit1 m \\<le> One \\<longleftrightarrow> False\"\n  \"Bit0 m \\<le> Bit0 n \\<longleftrightarrow> m \\<le> n\"\n  \"Bit0 m \\<le> Bit1 n \\<longleftrightarrow> m \\<le> n\"\n  \"Bit1 m \\<le> Bit1 n \\<longleftrightarrow> m \\<le> n\"\n  \"Bit1 m \\<le> Bit0 n \\<longleftrightarrow> m < n\"\n  using nat_of_num_pos [of n] nat_of_num_pos [of m]\n  by (auto simp add: less_eq_num_def less_num_def)\n\nlemma less_num_simps [simp, code]:\n  \"m < One \\<longleftrightarrow> False\"\n  \"One < Bit0 n \\<longleftrightarrow> True\"\n  \"One < Bit1 n \\<longleftrightarrow> True\"\n  \"Bit0 m < Bit0 n \\<longleftrightarrow> m < n\"\n  \"Bit0 m < Bit1 n \\<longleftrightarrow> m \\<le> n\"\n  \"Bit1 m < Bit1 n \\<longleftrightarrow> m < n\"\n  \"Bit1 m < Bit0 n \\<longleftrightarrow> m < n\"\n  using nat_of_num_pos [of n] nat_of_num_pos [of m]\n  by (auto simp add: less_eq_num_def less_num_def)\n\ntext {* Rules using @{text One} and @{text inc} as constructors *}\n\nlemma add_One: \"x + One = inc x\"\n  by (simp add: num_eq_iff nat_of_num_add nat_of_num_inc)\n\nlemma add_One_commute: \"One + n = n + One\"\n  by (induct n) simp_all\n\nlemma add_inc: \"x + inc y = inc (x + y)\"\n  by (simp add: num_eq_iff nat_of_num_add nat_of_num_inc)\n\nlemma mult_inc: \"x * inc y = x * y + x\"\n  by (simp add: num_eq_iff nat_of_num_mult nat_of_num_add nat_of_num_inc)\n\ntext {* The @{const num_of_nat} conversion *}\n\nlemma num_of_nat_One:\n  \"n \\<le> 1 \\<Longrightarrow> num_of_nat n = One\"\n  by (cases n) simp_all\n\nlemma num_of_nat_plus_distrib:\n  \"0 < m \\<Longrightarrow> 0 < n \\<Longrightarrow> num_of_nat (m + n) = num_of_nat m + num_of_nat n\"\n  by (induct n) (auto simp add: add_One add_One_commute add_inc)\n\ntext {* A double-and-decrement function *}\n\nprimrec BitM :: \"num \\<Rightarrow> num\" where\n  \"BitM One = One\" |\n  \"BitM (Bit0 n) = Bit1 (BitM n)\" |\n  \"BitM (Bit1 n) = Bit1 (Bit0 n)\"\n\nlemma BitM_plus_one: \"BitM n + One = Bit0 n\"\n  by (induct n) simp_all\n\nlemma one_plus_BitM: \"One + BitM n = Bit0 n\"\n  unfolding add_One_commute BitM_plus_one ..\n\ntext {* Squaring and exponentiation *}\n\nprimrec sqr :: \"num \\<Rightarrow> num\" where\n  \"sqr One = One\" |\n  \"sqr (Bit0 n) = Bit0 (Bit0 (sqr n))\" |\n  \"sqr (Bit1 n) = Bit1 (Bit0 (sqr n + n))\"\n\nprimrec pow :: \"num \\<Rightarrow> num \\<Rightarrow> num\" where\n  \"pow x One = x\" |\n  \"pow x (Bit0 y) = sqr (pow x y)\" |\n  \"pow x (Bit1 y) = sqr (pow x y) * x\"\n\nlemma nat_of_num_sqr: \"nat_of_num (sqr x) = nat_of_num x * nat_of_num x\"\n  by (induct x, simp_all add: algebra_simps nat_of_num_add)\n\nlemma sqr_conv_mult: \"sqr x = x * x\"\n  by (simp add: num_eq_iff nat_of_num_sqr nat_of_num_mult)\n\n\nsubsection {* Binary numerals *}\n\ntext {*\n  We embed binary representations into a generic algebraic\n  structure using @{text numeral}.\n*}\n\nclass numeral = one + semigroup_add\nbegin\n\nprimrec numeral :: \"num \\<Rightarrow> 'a\" where\n  numeral_One: \"numeral One = 1\" |\n  numeral_Bit0: \"numeral (Bit0 n) = numeral n + numeral n\" |\n  numeral_Bit1: \"numeral (Bit1 n) = numeral n + numeral n + 1\"\n\nlemma numeral_code [code]:\n  \"numeral One = 1\"\n  \"numeral (Bit0 n) = (let m = numeral n in m + m)\"\n  \"numeral (Bit1 n) = (let m = numeral n in m + m + 1)\"\n  by (simp_all add: Let_def)\n  \nlemma one_plus_numeral_commute: \"1 + numeral x = numeral x + 1\"\n  apply (induct x)\n  apply simp\n  apply (simp add: add.assoc [symmetric], simp add: add.assoc)\n  apply (simp add: add.assoc [symmetric], simp add: add.assoc)\n  done\n\nlemma numeral_inc: \"numeral (inc x) = numeral x + 1\"\nproof (induct x)\n  case (Bit1 x)\n  have \"numeral x + (1 + numeral x) + 1 = numeral x + (numeral x + 1) + 1\"\n    by (simp only: one_plus_numeral_commute)\n  with Bit1 show ?case\n    by (simp add: add.assoc)\nqed simp_all\n\ndeclare numeral.simps [simp del]\n\nabbreviation \"Numeral1 \\<equiv> numeral One\"\n\ndeclare numeral_One [code_post]\n\nend\n\ntext {* Numeral syntax. *}\n\nsyntax\n  \"_Numeral\" :: \"num_const \\<Rightarrow> 'a\"    (\"_\")\n\nML_file \"Tools/numeral.ML\"\n\nparse_translation {*\n  let\n    fun numeral_tr [(c as Const (@{syntax_const \"_constrain\"}, _)) $ t $ u] =\n          c $ numeral_tr [t] $ u\n      | numeral_tr [Const (num, _)] =\n          (Numeral.mk_number_syntax o #value o Lexicon.read_num) num\n      | numeral_tr ts = raise TERM (\"numeral_tr\", ts);\n  in [(@{syntax_const \"_Numeral\"}, K numeral_tr)] end\n*}\n\ntyped_print_translation {*\n  let\n    fun dest_num (Const (@{const_syntax Bit0}, _) $ n) = 2 * dest_num n\n      | dest_num (Const (@{const_syntax Bit1}, _) $ n) = 2 * dest_num n + 1\n      | dest_num (Const (@{const_syntax One}, _)) = 1;\n    fun num_tr' ctxt T [n] =\n      let\n        val k = dest_num n;\n        val t' =\n          Syntax.const @{syntax_const \"_Numeral\"} $\n            Syntax.free (string_of_int k);\n      in\n        (case T of\n          Type (@{type_name fun}, [_, T']) =>\n            if Printer.type_emphasis ctxt T' then\n              Syntax.const @{syntax_const \"_constrain\"} $ t' $\n                Syntax_Phases.term_of_typ ctxt T'\n            else t'\n        | _ => if T = dummyT then t' else raise Match)\n      end;\n  in\n   [(@{const_syntax numeral}, num_tr')]\n  end\n*}\n\n\nsubsection {* Class-specific numeral rules *}\n\ntext {*\n  @{const numeral} is a morphism.\n*}\n\nsubsubsection {* Structures with addition: class @{text numeral} *}\n\ncontext numeral\nbegin\n\nlemma numeral_add: \"numeral (m + n) = numeral m + numeral n\"\n  by (induct n rule: num_induct)\n     (simp_all only: numeral_One add_One add_inc numeral_inc add.assoc)\n\nlemma numeral_plus_numeral: \"numeral m + numeral n = numeral (m + n)\"\n  by (rule numeral_add [symmetric])\n\nlemma numeral_plus_one: \"numeral n + 1 = numeral (n + One)\"\n  using numeral_add [of n One] by (simp add: numeral_One)\n\nlemma one_plus_numeral: \"1 + numeral n = numeral (One + n)\"\n  using numeral_add [of One n] by (simp add: numeral_One)\n\nlemma one_add_one: \"1 + 1 = 2\"\n  using numeral_add [of One One] by (simp add: numeral_One)\n\nlemmas add_numeral_special =\n  numeral_plus_one one_plus_numeral one_add_one\n\nend\n\nsubsubsection {*\n  Structures with negation: class @{text neg_numeral}\n*}\n\nclass neg_numeral = numeral + group_add\nbegin\n\nlemma uminus_numeral_One:\n  \"- Numeral1 = - 1\"\n  by (simp add: numeral_One)\n\ntext {* Numerals form an abelian subgroup. *}\n\ninductive is_num :: \"'a \\<Rightarrow> bool\" where\n  \"is_num 1\" |\n  \"is_num x \\<Longrightarrow> is_num (- x)\" |\n  \"\\<lbrakk>is_num x; is_num y\\<rbrakk> \\<Longrightarrow> is_num (x + y)\"\n\nlemma is_num_numeral: \"is_num (numeral k)\"\n  by (induct k, simp_all add: numeral.simps is_num.intros)\n\nlemma is_num_add_commute:\n  \"\\<lbrakk>is_num x; is_num y\\<rbrakk> \\<Longrightarrow> x + y = y + x\"\n  apply (induct x rule: is_num.induct)\n  apply (induct y rule: is_num.induct)\n  apply simp\n  apply (rule_tac a=x in add_left_imp_eq)\n  apply (rule_tac a=x in add_right_imp_eq)\n  apply (simp add: add.assoc)\n  apply (simp add: add.assoc [symmetric], simp add: add.assoc)\n  apply (rule_tac a=x in add_left_imp_eq)\n  apply (rule_tac a=x in add_right_imp_eq)\n  apply (simp add: add.assoc)\n  apply (simp add: add.assoc, simp add: add.assoc [symmetric])\n  done\n\nlemma is_num_add_left_commute:\n  \"\\<lbrakk>is_num x; is_num y\\<rbrakk> \\<Longrightarrow> x + (y + z) = y + (x + z)\"\n  by (simp only: add.assoc [symmetric] is_num_add_commute)\n\nlemmas is_num_normalize =\n  add.assoc is_num_add_commute is_num_add_left_commute\n  is_num.intros is_num_numeral\n  minus_add\n\ndefinition dbl :: \"'a \\<Rightarrow> 'a\" where \"dbl x = x + x\"\ndefinition dbl_inc :: \"'a \\<Rightarrow> 'a\" where \"dbl_inc x = x + x + 1\"\ndefinition dbl_dec :: \"'a \\<Rightarrow> 'a\" where \"dbl_dec x = x + x - 1\"\n\ndefinition sub :: \"num \\<Rightarrow> num \\<Rightarrow> 'a\" where\n  \"sub k l = numeral k - numeral l\"\n\nlemma numeral_BitM: \"numeral (BitM n) = numeral (Bit0 n) - 1\"\n  by (simp only: BitM_plus_one [symmetric] numeral_add numeral_One eq_diff_eq)\n\nlemma dbl_simps [simp]:\n  \"dbl (- numeral k) = - dbl (numeral k)\"\n  \"dbl 0 = 0\"\n  \"dbl 1 = 2\"\n  \"dbl (- 1) = - 2\"\n  \"dbl (numeral k) = numeral (Bit0 k)\"\n  by (simp_all add: dbl_def numeral.simps minus_add)\n\nlemma dbl_inc_simps [simp]:\n  \"dbl_inc (- numeral k) = - dbl_dec (numeral k)\"\n  \"dbl_inc 0 = 1\"\n  \"dbl_inc 1 = 3\"\n  \"dbl_inc (- 1) = - 1\"\n  \"dbl_inc (numeral k) = numeral (Bit1 k)\"\n  by (simp_all add: dbl_inc_def dbl_dec_def numeral.simps numeral_BitM is_num_normalize algebra_simps del: add_uminus_conv_diff)\n\nlemma dbl_dec_simps [simp]:\n  \"dbl_dec (- numeral k) = - dbl_inc (numeral k)\"\n  \"dbl_dec 0 = - 1\"\n  \"dbl_dec 1 = 1\"\n  \"dbl_dec (- 1) = - 3\"\n  \"dbl_dec (numeral k) = numeral (BitM k)\"\n  by (simp_all add: dbl_dec_def dbl_inc_def numeral.simps numeral_BitM is_num_normalize)\n\nlemma sub_num_simps [simp]:\n  \"sub One One = 0\"\n  \"sub One (Bit0 l) = - numeral (BitM l)\"\n  \"sub One (Bit1 l) = - numeral (Bit0 l)\"\n  \"sub (Bit0 k) One = numeral (BitM k)\"\n  \"sub (Bit1 k) One = numeral (Bit0 k)\"\n  \"sub (Bit0 k) (Bit0 l) = dbl (sub k l)\"\n  \"sub (Bit0 k) (Bit1 l) = dbl_dec (sub k l)\"\n  \"sub (Bit1 k) (Bit0 l) = dbl_inc (sub k l)\"\n  \"sub (Bit1 k) (Bit1 l) = dbl (sub k l)\"\n  by (simp_all add: dbl_def dbl_dec_def dbl_inc_def sub_def numeral.simps\n    numeral_BitM is_num_normalize del: add_uminus_conv_diff add: diff_conv_add_uminus)\n\nlemma add_neg_numeral_simps:\n  \"numeral m + - numeral n = sub m n\"\n  \"- numeral m + numeral n = sub n m\"\n  \"- numeral m + - numeral n = - (numeral m + numeral n)\"\n  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize\n    del: add_uminus_conv_diff add: diff_conv_add_uminus)\n\nlemma add_neg_numeral_special:\n  \"1 + - numeral m = sub One m\"\n  \"- numeral m + 1 = sub One m\"\n  \"numeral m + - 1 = sub m One\"\n  \"- 1 + numeral n = sub n One\"\n  \"- 1 + - numeral n = - numeral (inc n)\"\n  \"- numeral m + - 1 = - numeral (inc m)\"\n  \"1 + - 1 = 0\"\n  \"- 1 + 1 = 0\"\n  \"- 1 + - 1 = - 2\"\n  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize right_minus numeral_inc\n    del: add_uminus_conv_diff add: diff_conv_add_uminus)\n\nlemma diff_numeral_simps:\n  \"numeral m - numeral n = sub m n\"\n  \"numeral m - - numeral n = numeral (m + n)\"\n  \"- numeral m - numeral n = - numeral (m + n)\"\n  \"- numeral m - - numeral n = sub n m\"\n  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize\n    del: add_uminus_conv_diff add: diff_conv_add_uminus)\n\nlemma diff_numeral_special:\n  \"1 - numeral n = sub One n\"\n  \"numeral m - 1 = sub m One\"\n  \"1 - - numeral n = numeral (One + n)\"\n  \"- numeral m - 1 = - numeral (m + One)\"\n  \"- 1 - numeral n = - numeral (inc n)\"\n  \"numeral m - - 1 = numeral (inc m)\"\n  \"- 1 - - numeral n = sub n One\"\n  \"- numeral m - - 1 = sub One m\"\n  \"1 - 1 = 0\"\n  \"- 1 - 1 = - 2\"\n  \"1 - - 1 = 2\"\n  \"- 1 - - 1 = 0\"\n  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize numeral_inc\n    del: add_uminus_conv_diff add: diff_conv_add_uminus)\n\nend\n\nsubsubsection {*\n  Structures with multiplication: class @{text semiring_numeral}\n*}\n\nclass semiring_numeral = semiring + monoid_mult\nbegin\n\nsubclass numeral ..\n\nlemma numeral_mult: \"numeral (m * n) = numeral m * numeral n\"\n  apply (induct n rule: num_induct)\n  apply (simp add: numeral_One)\n  apply (simp add: mult_inc numeral_inc numeral_add distrib_left)\n  done\n\nlemma numeral_times_numeral: \"numeral m * numeral n = numeral (m * n)\"\n  by (rule numeral_mult [symmetric])\n\nlemma mult_2: \"2 * z = z + z\"\n  unfolding one_add_one [symmetric] distrib_right by simp\n\nlemma mult_2_right: \"z * 2 = z + z\"\n  unfolding one_add_one [symmetric] distrib_left by simp\n\nend\n\nsubsubsection {*\n  Structures with a zero: class @{text semiring_1}\n*}\n\ncontext semiring_1\nbegin\n\nsubclass semiring_numeral ..\n\nlemma of_nat_numeral [simp]: \"of_nat (numeral n) = numeral n\"\n  by (induct n,\n    simp_all only: numeral.simps numeral_class.numeral.simps of_nat_add of_nat_1)\n\nend\n\nlemma nat_of_num_numeral [code_abbrev]:\n  \"nat_of_num = numeral\"\nproof\n  fix n\n  have \"numeral n = nat_of_num n\"\n    by (induct n) (simp_all add: numeral.simps)\n  then show \"nat_of_num n = numeral n\" by simp\nqed\n\nlemma nat_of_num_code [code]:\n  \"nat_of_num One = 1\"\n  \"nat_of_num (Bit0 n) = (let m = nat_of_num n in m + m)\"\n  \"nat_of_num (Bit1 n) = (let m = nat_of_num n in Suc (m + m))\"\n  by (simp_all add: Let_def)\n\nsubsubsection {*\n  Equality: class @{text semiring_char_0}\n*}\n\ncontext semiring_char_0\nbegin\n\nlemma numeral_eq_iff: \"numeral m = numeral n \\<longleftrightarrow> m = n\"\n  unfolding of_nat_numeral [symmetric] nat_of_num_numeral [symmetric]\n    of_nat_eq_iff num_eq_iff ..\n\nlemma numeral_eq_one_iff: \"numeral n = 1 \\<longleftrightarrow> n = One\"\n  by (rule numeral_eq_iff [of n One, unfolded numeral_One])\n\nlemma one_eq_numeral_iff: \"1 = numeral n \\<longleftrightarrow> One = n\"\n  by (rule numeral_eq_iff [of One n, unfolded numeral_One])\n\nlemma numeral_neq_zero: \"numeral n \\<noteq> 0\"\n  unfolding of_nat_numeral [symmetric] nat_of_num_numeral [symmetric]\n  by (simp add: nat_of_num_pos)\n\nlemma zero_neq_numeral: \"0 \\<noteq> numeral n\"\n  unfolding eq_commute [of 0] by (rule numeral_neq_zero)\n\nlemmas eq_numeral_simps [simp] =\n  numeral_eq_iff\n  numeral_eq_one_iff\n  one_eq_numeral_iff\n  numeral_neq_zero\n  zero_neq_numeral\n\nend\n\nsubsubsection {*\n  Comparisons: class @{text linordered_semidom}\n*}\n\ntext {*  Could be perhaps more general than here. *}\n\ncontext linordered_semidom\nbegin\n\nlemma numeral_le_iff: \"numeral m \\<le> numeral n \\<longleftrightarrow> m \\<le> n\"\nproof -\n  have \"of_nat (numeral m) \\<le> of_nat (numeral n) \\<longleftrightarrow> m \\<le> n\"\n    unfolding less_eq_num_def nat_of_num_numeral of_nat_le_iff ..\n  then show ?thesis by simp\nqed\n\nlemma one_le_numeral: \"1 \\<le> numeral n\"\nusing numeral_le_iff [of One n] by (simp add: numeral_One)\n\nlemma numeral_le_one_iff: \"numeral n \\<le> 1 \\<longleftrightarrow> n \\<le> One\"\nusing numeral_le_iff [of n One] by (simp add: numeral_One)\n\nlemma numeral_less_iff: \"numeral m < numeral n \\<longleftrightarrow> m < n\"\nproof -\n  have \"of_nat (numeral m) < of_nat (numeral n) \\<longleftrightarrow> m < n\"\n    unfolding less_num_def nat_of_num_numeral of_nat_less_iff ..\n  then show ?thesis by simp\nqed\n\nlemma not_numeral_less_one: \"\\<not> numeral n < 1\"\n  using numeral_less_iff [of n One] by (simp add: numeral_One)\n\nlemma one_less_numeral_iff: \"1 < numeral n \\<longleftrightarrow> One < n\"\n  using numeral_less_iff [of One n] by (simp add: numeral_One)\n\nlemma zero_le_numeral: \"0 \\<le> numeral n\"\n  by (induct n) (simp_all add: numeral.simps)\n\nlemma zero_less_numeral: \"0 < numeral n\"\n  by (induct n) (simp_all add: numeral.simps add_pos_pos)\n\nlemma not_numeral_le_zero: \"\\<not> numeral n \\<le> 0\"\n  by (simp add: not_le zero_less_numeral)\n\nlemma not_numeral_less_zero: \"\\<not> numeral n < 0\"\n  by (simp add: not_less zero_le_numeral)\n\nlemmas le_numeral_extra =\n  zero_le_one not_one_le_zero\n  order_refl [of 0] order_refl [of 1]\n\nlemmas less_numeral_extra =\n  zero_less_one not_one_less_zero\n  less_irrefl [of 0] less_irrefl [of 1]\n\nlemmas le_numeral_simps [simp] =\n  numeral_le_iff\n  one_le_numeral\n  numeral_le_one_iff\n  zero_le_numeral\n  not_numeral_le_zero\n\nlemmas less_numeral_simps [simp] =\n  numeral_less_iff\n  one_less_numeral_iff\n  not_numeral_less_one\n  zero_less_numeral\n  not_numeral_less_zero\n\nend\n\nsubsubsection {*\n  Multiplication and negation: class @{text ring_1}\n*}\n\ncontext ring_1\nbegin\n\nsubclass neg_numeral ..\n\nlemma mult_neg_numeral_simps:\n  \"- numeral m * - numeral n = numeral (m * n)\"\n  \"- numeral m * numeral n = - numeral (m * n)\"\n  \"numeral m * - numeral n = - numeral (m * n)\"\n  unfolding mult_minus_left mult_minus_right\n  by (simp_all only: minus_minus numeral_mult)\n\nlemma mult_minus1 [simp]: \"- 1 * z = - z\"\n  unfolding numeral.simps mult_minus_left by simp\n\nlemma mult_minus1_right [simp]: \"z * - 1 = - z\"\n  unfolding numeral.simps mult_minus_right by simp\n\nend\n\nsubsubsection {*\n  Equality using @{text iszero} for rings with non-zero characteristic\n*}\n\ncontext ring_1\nbegin\n\ndefinition iszero :: \"'a \\<Rightarrow> bool\"\n  where \"iszero z \\<longleftrightarrow> z = 0\"\n\nlemma iszero_0 [simp]: \"iszero 0\"\n  by (simp add: iszero_def)\n\nlemma not_iszero_1 [simp]: \"\\<not> iszero 1\"\n  by (simp add: iszero_def)\n\nlemma not_iszero_Numeral1: \"\\<not> iszero Numeral1\"\n  by (simp add: numeral_One)\n\nlemma not_iszero_neg_1 [simp]: \"\\<not> iszero (- 1)\"\n  by (simp add: iszero_def)\n\nlemma not_iszero_neg_Numeral1: \"\\<not> iszero (- Numeral1)\"\n  by (simp add: numeral_One)\n\nlemma iszero_neg_numeral [simp]:\n  \"iszero (- numeral w) \\<longleftrightarrow> iszero (numeral w)\"\n  unfolding iszero_def\n  by (rule neg_equal_0_iff_equal)\n\nlemma eq_iff_iszero_diff: \"x = y \\<longleftrightarrow> iszero (x - y)\"\n  unfolding iszero_def by (rule eq_iff_diff_eq_0)\n\ntext {* The @{text \"eq_numeral_iff_iszero\"} lemmas are not declared\n@{text \"[simp]\"} by default, because for rings of characteristic zero,\nbetter simp rules are possible. For a type like integers mod @{text\n\"n\"}, type-instantiated versions of these rules should be added to the\nsimplifier, along with a type-specific rule for deciding propositions\nof the form @{text \"iszero (numeral w)\"}.\n\nbh: Maybe it would not be so bad to just declare these as simp\nrules anyway? I should test whether these rules take precedence over\nthe @{text \"ring_char_0\"} rules in the simplifier.\n*}\n\nlemma eq_numeral_iff_iszero:\n  \"numeral x = numeral y \\<longleftrightarrow> iszero (sub x y)\"\n  \"numeral x = - numeral y \\<longleftrightarrow> iszero (numeral (x + y))\"\n  \"- numeral x = numeral y \\<longleftrightarrow> iszero (numeral (x + y))\"\n  \"- numeral x = - numeral y \\<longleftrightarrow> iszero (sub y x)\"\n  \"numeral x = 1 \\<longleftrightarrow> iszero (sub x One)\"\n  \"1 = numeral y \\<longleftrightarrow> iszero (sub One y)\"\n  \"- numeral x = 1 \\<longleftrightarrow> iszero (numeral (x + One))\"\n  \"1 = - numeral y \\<longleftrightarrow> iszero (numeral (One + y))\"\n  \"numeral x = 0 \\<longleftrightarrow> iszero (numeral x)\"\n  \"0 = numeral y \\<longleftrightarrow> iszero (numeral y)\"\n  \"- numeral x = 0 \\<longleftrightarrow> iszero (numeral x)\"\n  \"0 = - numeral y \\<longleftrightarrow> iszero (numeral y)\"\n  unfolding eq_iff_iszero_diff diff_numeral_simps diff_numeral_special\n  by simp_all\n\nend\n\nsubsubsection {*\n  Equality and negation: class @{text ring_char_0}\n*}\n\nclass ring_char_0 = ring_1 + semiring_char_0\nbegin\n\nlemma not_iszero_numeral [simp]: \"\\<not> iszero (numeral w)\"\n  by (simp add: iszero_def)\n\nlemma neg_numeral_eq_iff: \"- numeral m = - numeral n \\<longleftrightarrow> m = n\"\n  by simp\n\nlemma numeral_neq_neg_numeral: \"numeral m \\<noteq> - numeral n\"\n  unfolding eq_neg_iff_add_eq_0\n  by (simp add: numeral_plus_numeral)\n\nlemma neg_numeral_neq_numeral: \"- numeral m \\<noteq> numeral n\"\n  by (rule numeral_neq_neg_numeral [symmetric])\n\nlemma zero_neq_neg_numeral: \"0 \\<noteq> - numeral n\"\n  unfolding neg_0_equal_iff_equal by simp\n\nlemma neg_numeral_neq_zero: \"- numeral n \\<noteq> 0\"\n  unfolding neg_equal_0_iff_equal by simp\n\nlemma one_neq_neg_numeral: \"1 \\<noteq> - numeral n\"\n  using numeral_neq_neg_numeral [of One n] by (simp add: numeral_One)\n\nlemma neg_numeral_neq_one: \"- numeral n \\<noteq> 1\"\n  using neg_numeral_neq_numeral [of n One] by (simp add: numeral_One)\n\nlemma neg_one_neq_numeral:\n  \"- 1 \\<noteq> numeral n\"\n  using neg_numeral_neq_numeral [of One n] by (simp add: numeral_One)\n\nlemma numeral_neq_neg_one:\n  \"numeral n \\<noteq> - 1\"\n  using numeral_neq_neg_numeral [of n One] by (simp add: numeral_One)\n\nlemma neg_one_eq_numeral_iff:\n  \"- 1 = - numeral n \\<longleftrightarrow> n = One\"\n  using neg_numeral_eq_iff [of One n] by (auto simp add: numeral_One)\n\nlemma numeral_eq_neg_one_iff:\n  \"- numeral n = - 1 \\<longleftrightarrow> n = One\"\n  using neg_numeral_eq_iff [of n One] by (auto simp add: numeral_One)\n\nlemma neg_one_neq_zero:\n  \"- 1 \\<noteq> 0\"\n  by simp\n\nlemma zero_neq_neg_one:\n  \"0 \\<noteq> - 1\"\n  by simp\n\nlemma neg_one_neq_one:\n  \"- 1 \\<noteq> 1\"\n  using neg_numeral_neq_numeral [of One One] by (simp only: numeral_One not_False_eq_True)\n\nlemma one_neq_neg_one:\n  \"1 \\<noteq> - 1\"\n  using numeral_neq_neg_numeral [of One One] by (simp only: numeral_One not_False_eq_True)\n\nlemmas eq_neg_numeral_simps [simp] =\n  neg_numeral_eq_iff\n  numeral_neq_neg_numeral neg_numeral_neq_numeral\n  one_neq_neg_numeral neg_numeral_neq_one\n  zero_neq_neg_numeral neg_numeral_neq_zero\n  neg_one_neq_numeral numeral_neq_neg_one\n  neg_one_eq_numeral_iff numeral_eq_neg_one_iff\n  neg_one_neq_zero zero_neq_neg_one\n  neg_one_neq_one one_neq_neg_one\n\nend\n\nsubsubsection {*\n  Structures with negation and order: class @{text linordered_idom}\n*}\n\ncontext linordered_idom\nbegin\n\nsubclass ring_char_0 ..\n\nlemma neg_numeral_le_iff: \"- numeral m \\<le> - numeral n \\<longleftrightarrow> n \\<le> m\"\n  by (simp only: neg_le_iff_le numeral_le_iff)\n\nlemma neg_numeral_less_iff: \"- numeral m < - numeral n \\<longleftrightarrow> n < m\"\n  by (simp only: neg_less_iff_less numeral_less_iff)\n\nlemma neg_numeral_less_zero: \"- numeral n < 0\"\n  by (simp only: neg_less_0_iff_less zero_less_numeral)\n\nlemma neg_numeral_le_zero: \"- numeral n \\<le> 0\"\n  by (simp only: neg_le_0_iff_le zero_le_numeral)\n\nlemma not_zero_less_neg_numeral: \"\\<not> 0 < - numeral n\"\n  by (simp only: not_less neg_numeral_le_zero)\n\nlemma not_zero_le_neg_numeral: \"\\<not> 0 \\<le> - numeral n\"\n  by (simp only: not_le neg_numeral_less_zero)\n\nlemma neg_numeral_less_numeral: \"- numeral m < numeral n\"\n  using neg_numeral_less_zero zero_less_numeral by (rule less_trans)\n\nlemma neg_numeral_le_numeral: \"- numeral m \\<le> numeral n\"\n  by (simp only: less_imp_le neg_numeral_less_numeral)\n\nlemma not_numeral_less_neg_numeral: \"\\<not> numeral m < - numeral n\"\n  by (simp only: not_less neg_numeral_le_numeral)\n\nlemma not_numeral_le_neg_numeral: \"\\<not> numeral m \\<le> - numeral n\"\n  by (simp only: not_le neg_numeral_less_numeral)\n  \nlemma neg_numeral_less_one: \"- numeral m < 1\"\n  by (rule neg_numeral_less_numeral [of m One, unfolded numeral_One])\n\nlemma neg_numeral_le_one: \"- numeral m \\<le> 1\"\n  by (rule neg_numeral_le_numeral [of m One, unfolded numeral_One])\n\nlemma not_one_less_neg_numeral: \"\\<not> 1 < - numeral m\"\n  by (simp only: not_less neg_numeral_le_one)\n\nlemma not_one_le_neg_numeral: \"\\<not> 1 \\<le> - numeral m\"\n  by (simp only: not_le neg_numeral_less_one)\n\nlemma not_numeral_less_neg_one: \"\\<not> numeral m < - 1\"\n  using not_numeral_less_neg_numeral [of m One] by (simp add: numeral_One)\n\nlemma not_numeral_le_neg_one: \"\\<not> numeral m \\<le> - 1\"\n  using not_numeral_le_neg_numeral [of m One] by (simp add: numeral_One)\n\nlemma neg_one_less_numeral: \"- 1 < numeral m\"\n  using neg_numeral_less_numeral [of One m] by (simp add: numeral_One)\n\nlemma neg_one_le_numeral: \"- 1 \\<le> numeral m\"\n  using neg_numeral_le_numeral [of One m] by (simp add: numeral_One)\n\nlemma neg_numeral_less_neg_one_iff: \"- numeral m < - 1 \\<longleftrightarrow> m \\<noteq> One\"\n  by (cases m) simp_all\n\nlemma neg_numeral_le_neg_one: \"- numeral m \\<le> - 1\"\n  by simp\n\nlemma not_neg_one_less_neg_numeral: \"\\<not> - 1 < - numeral m\"\n  by simp\n\nlemma not_neg_one_le_neg_numeral_iff: \"\\<not> - 1 \\<le> - numeral m \\<longleftrightarrow> m \\<noteq> One\"\n  by (cases m) simp_all\n\nlemma sub_non_negative:\n  \"sub n m \\<ge> 0 \\<longleftrightarrow> n \\<ge> m\"\n  by (simp only: sub_def le_diff_eq) simp\n\nlemma sub_positive:\n  \"sub n m > 0 \\<longleftrightarrow> n > m\"\n  by (simp only: sub_def less_diff_eq) simp\n\nlemma sub_non_positive:\n  \"sub n m \\<le> 0 \\<longleftrightarrow> n \\<le> m\"\n  by (simp only: sub_def diff_le_eq) simp\n\nlemma sub_negative:\n  \"sub n m < 0 \\<longleftrightarrow> n < m\"\n  by (simp only: sub_def diff_less_eq) simp\n\nlemmas le_neg_numeral_simps [simp] =\n  neg_numeral_le_iff\n  neg_numeral_le_numeral not_numeral_le_neg_numeral\n  neg_numeral_le_zero not_zero_le_neg_numeral\n  neg_numeral_le_one not_one_le_neg_numeral\n  neg_one_le_numeral not_numeral_le_neg_one\n  neg_numeral_le_neg_one not_neg_one_le_neg_numeral_iff\n\nlemma le_minus_one_simps [simp]:\n  \"- 1 \\<le> 0\"\n  \"- 1 \\<le> 1\"\n  \"\\<not> 0 \\<le> - 1\"\n  \"\\<not> 1 \\<le> - 1\"\n  by simp_all\n\nlemmas less_neg_numeral_simps [simp] =\n  neg_numeral_less_iff\n  neg_numeral_less_numeral not_numeral_less_neg_numeral\n  neg_numeral_less_zero not_zero_less_neg_numeral\n  neg_numeral_less_one not_one_less_neg_numeral\n  neg_one_less_numeral not_numeral_less_neg_one\n  neg_numeral_less_neg_one_iff not_neg_one_less_neg_numeral\n\nlemma less_minus_one_simps [simp]:\n  \"- 1 < 0\"\n  \"- 1 < 1\"\n  \"\\<not> 0 < - 1\"\n  \"\\<not> 1 < - 1\"\n  by (simp_all add: less_le)\n\nlemma abs_numeral [simp]: \"abs (numeral n) = numeral n\"\n  by simp\n\nlemma abs_neg_numeral [simp]: \"abs (- numeral n) = numeral n\"\n  by (simp only: abs_minus_cancel abs_numeral)\n\nlemma abs_neg_one [simp]:\n  \"abs (- 1) = 1\"\n  by simp\n\nend\n\nsubsubsection {*\n  Natural numbers\n*}\n\nlemma Suc_1 [simp]: \"Suc 1 = 2\"\n  unfolding Suc_eq_plus1 by (rule one_add_one)\n\nlemma Suc_numeral [simp]: \"Suc (numeral n) = numeral (n + One)\"\n  unfolding Suc_eq_plus1 by (rule numeral_plus_one)\n\ndefinition pred_numeral :: \"num \\<Rightarrow> nat\"\n  where [code del]: \"pred_numeral k = numeral k - 1\"\n\nlemma numeral_eq_Suc: \"numeral k = Suc (pred_numeral k)\"\n  unfolding pred_numeral_def by simp\n\nlemma eval_nat_numeral:\n  \"numeral One = Suc 0\"\n  \"numeral (Bit0 n) = Suc (numeral (BitM n))\"\n  \"numeral (Bit1 n) = Suc (numeral (Bit0 n))\"\n  by (simp_all add: numeral.simps BitM_plus_one)\n\nlemma pred_numeral_simps [simp]:\n  \"pred_numeral One = 0\"\n  \"pred_numeral (Bit0 k) = numeral (BitM k)\"\n  \"pred_numeral (Bit1 k) = numeral (Bit0 k)\"\n  unfolding pred_numeral_def eval_nat_numeral\n  by (simp_all only: diff_Suc_Suc diff_0)\n\nlemma numeral_2_eq_2: \"2 = Suc (Suc 0)\"\n  by (simp add: eval_nat_numeral)\n\nlemma numeral_3_eq_3: \"3 = Suc (Suc (Suc 0))\"\n  by (simp add: eval_nat_numeral)\n\nlemma numeral_1_eq_Suc_0: \"Numeral1 = Suc 0\"\n  by (simp only: numeral_One One_nat_def)\n\nlemma Suc_nat_number_of_add:\n  \"Suc (numeral v + n) = numeral (v + One) + n\"\n  by simp\n\n(*Maps #n to n for n = 1, 2*)\nlemmas numerals = numeral_One [where 'a=nat] numeral_2_eq_2\n\ntext {* Comparisons involving @{term Suc}. *}\n\nlemma eq_numeral_Suc [simp]: \"numeral k = Suc n \\<longleftrightarrow> pred_numeral k = n\"\n  by (simp add: numeral_eq_Suc)\n\nlemma Suc_eq_numeral [simp]: \"Suc n = numeral k \\<longleftrightarrow> n = pred_numeral k\"\n  by (simp add: numeral_eq_Suc)\n\nlemma less_numeral_Suc [simp]: \"numeral k < Suc n \\<longleftrightarrow> pred_numeral k < n\"\n  by (simp add: numeral_eq_Suc)\n\nlemma less_Suc_numeral [simp]: \"Suc n < numeral k \\<longleftrightarrow> n < pred_numeral k\"\n  by (simp add: numeral_eq_Suc)\n\nlemma le_numeral_Suc [simp]: \"numeral k \\<le> Suc n \\<longleftrightarrow> pred_numeral k \\<le> n\"\n  by (simp add: numeral_eq_Suc)\n\nlemma le_Suc_numeral [simp]: \"Suc n \\<le> numeral k \\<longleftrightarrow> n \\<le> pred_numeral k\"\n  by (simp add: numeral_eq_Suc)\n\nlemma diff_Suc_numeral [simp]: \"Suc n - numeral k = n - pred_numeral k\"\n  by (simp add: numeral_eq_Suc)\n\nlemma diff_numeral_Suc [simp]: \"numeral k - Suc n = pred_numeral k - n\"\n  by (simp add: numeral_eq_Suc)\n\nlemma max_Suc_numeral [simp]:\n  \"max (Suc n) (numeral k) = Suc (max n (pred_numeral k))\"\n  by (simp add: numeral_eq_Suc)\n\nlemma max_numeral_Suc [simp]:\n  \"max (numeral k) (Suc n) = Suc (max (pred_numeral k) n)\"\n  by (simp add: numeral_eq_Suc)\n\nlemma min_Suc_numeral [simp]:\n  \"min (Suc n) (numeral k) = Suc (min n (pred_numeral k))\"\n  by (simp add: numeral_eq_Suc)\n\nlemma min_numeral_Suc [simp]:\n  \"min (numeral k) (Suc n) = Suc (min (pred_numeral k) n)\"\n  by (simp add: numeral_eq_Suc)\n\ntext {* For @{term case_nat} and @{term rec_nat}. *}\n\nlemma case_nat_numeral [simp]:\n  \"case_nat a f (numeral v) = (let pv = pred_numeral v in f pv)\"\n  by (simp add: numeral_eq_Suc)\n\nlemma case_nat_add_eq_if [simp]:\n  \"case_nat a f ((numeral v) + n) = (let pv = pred_numeral v in f (pv + n))\"\n  by (simp add: numeral_eq_Suc)\n\nlemma rec_nat_numeral [simp]:\n  \"rec_nat a f (numeral v) =\n    (let pv = pred_numeral v in f pv (rec_nat a f pv))\"\n  by (simp add: numeral_eq_Suc Let_def)\n\nlemma rec_nat_add_eq_if [simp]:\n  \"rec_nat a f (numeral v + n) =\n    (let pv = pred_numeral v in f (pv + n) (rec_nat a f (pv + n)))\"\n  by (simp add: numeral_eq_Suc Let_def)\n\ntext {* Case analysis on @{term \"n < 2\"} *}\n\nlemma less_2_cases: \"n < 2 \\<Longrightarrow> n = 0 \\<or> n = Suc 0\"\n  by (auto simp add: numeral_2_eq_2)\n\ntext {* Removal of Small Numerals: 0, 1 and (in additive positions) 2 *}\ntext {* bh: Are these rules really a good idea? *}\n\nlemma add_2_eq_Suc [simp]: \"2 + n = Suc (Suc n)\"\n  by simp\n\nlemma add_2_eq_Suc' [simp]: \"n + 2 = Suc (Suc n)\"\n  by simp\n\ntext {* Can be used to eliminate long strings of Sucs, but not by default. *}\n\nlemma Suc3_eq_add_3: \"Suc (Suc (Suc n)) = 3 + n\"\n  by simp\n\nlemmas nat_1_add_1 = one_add_one [where 'a=nat] (* legacy *)\n\n\nsubsection {* Particular lemmas concerning @{term 2} *}\n\ncontext linordered_field_inverse_zero\nbegin\n\nlemma half_gt_zero_iff:\n  \"0 < a / 2 \\<longleftrightarrow> 0 < a\" (is \"?P \\<longleftrightarrow> ?Q\")\n  by (auto simp add: field_simps)\n\nlemma half_gt_zero [simp]:\n  \"0 < a \\<Longrightarrow> 0 < a / 2\"\n  by (simp add: half_gt_zero_iff)\n\nend\n\n\nsubsection {* Numeral equations as default simplification rules *}\n\ndeclare (in numeral) numeral_One [simp]\ndeclare (in numeral) numeral_plus_numeral [simp]\ndeclare (in numeral) add_numeral_special [simp]\ndeclare (in neg_numeral) add_neg_numeral_simps [simp]\ndeclare (in neg_numeral) add_neg_numeral_special [simp]\ndeclare (in neg_numeral) diff_numeral_simps [simp]\ndeclare (in neg_numeral) diff_numeral_special [simp]\ndeclare (in semiring_numeral) numeral_times_numeral [simp]\ndeclare (in ring_1) mult_neg_numeral_simps [simp]\n\nsubsection {* Setting up simprocs *}\n\nlemma mult_numeral_1: \"Numeral1 * a = (a::'a::semiring_numeral)\"\n  by simp\n\nlemma mult_numeral_1_right: \"a * Numeral1 = (a::'a::semiring_numeral)\"\n  by simp\n\nlemma divide_numeral_1: \"a / Numeral1 = (a::'a::field)\"\n  by simp\n\nlemma inverse_numeral_1:\n  \"inverse Numeral1 = (Numeral1::'a::division_ring)\"\n  by simp\n\ntext{*Theorem lists for the cancellation simprocs. The use of a binary\nnumeral for 1 reduces the number of special cases.*}\n\nlemma mult_1s:\n  fixes a :: \"'a::semiring_numeral\"\n    and b :: \"'b::ring_1\"\n  shows \"Numeral1 * a = a\"\n    \"a * Numeral1 = a\"\n    \"- Numeral1 * b = - b\"\n    \"b * - Numeral1 = - b\"\n  by simp_all\n\nsetup {*\n  Reorient_Proc.add\n    (fn Const (@{const_name numeral}, _) $ _ => true\n    | Const (@{const_name uminus}, _) $ (Const (@{const_name numeral}, _) $ _) => true\n    | _ => false)\n*}\n\nsimproc_setup reorient_numeral\n  (\"numeral w = x\" | \"- numeral w = y\") = Reorient_Proc.proc\n\n\nsubsubsection {* Simplification of arithmetic operations on integer constants. *}\n\nlemmas arith_special = (* already declared simp above *)\n  add_numeral_special add_neg_numeral_special\n  diff_numeral_special\n\n(* rules already in simpset *)\nlemmas arith_extra_simps =\n  numeral_plus_numeral add_neg_numeral_simps add_0_left add_0_right\n  minus_zero\n  diff_numeral_simps diff_0 diff_0_right\n  numeral_times_numeral mult_neg_numeral_simps\n  mult_zero_left mult_zero_right\n  abs_numeral abs_neg_numeral\n\ntext {*\n  For making a minimal simpset, one must include these default simprules.\n  Also include @{text simp_thms}.\n*}\n\nlemmas arith_simps =\n  add_num_simps mult_num_simps sub_num_simps\n  BitM.simps dbl_simps dbl_inc_simps dbl_dec_simps\n  abs_zero abs_one arith_extra_simps\n\nlemmas more_arith_simps =\n  neg_le_iff_le\n  minus_zero left_minus right_minus\n  mult_1_left mult_1_right\n  mult_minus_left mult_minus_right\n  minus_add_distrib minus_minus mult.assoc\n\nlemmas of_nat_simps =\n  of_nat_0 of_nat_1 of_nat_Suc of_nat_add of_nat_mult\n\ntext {* Simplification of relational operations *}\n\nlemmas eq_numeral_extra =\n  zero_neq_one one_neq_zero\n\nlemmas rel_simps =\n  le_num_simps less_num_simps eq_num_simps\n  le_numeral_simps le_neg_numeral_simps le_minus_one_simps le_numeral_extra\n  less_numeral_simps less_neg_numeral_simps less_minus_one_simps less_numeral_extra\n  eq_numeral_simps eq_neg_numeral_simps eq_numeral_extra\n\nlemma Let_numeral [simp]: \"Let (numeral v) f = f (numeral v)\"\n  -- {* Unfold all @{text let}s involving constants *}\n  unfolding Let_def ..\n\nlemma Let_neg_numeral [simp]: \"Let (- numeral v) f = f (- numeral v)\"\n  -- {* Unfold all @{text let}s involving constants *}\n  unfolding Let_def ..\n\ndeclaration {*\nlet \n  fun number_of thy T n =\n    if not (Sign.of_sort thy (T, @{sort numeral}))\n    then raise CTERM (\"number_of\", [])\n    else Numeral.mk_cnumber (Thm.ctyp_of thy T) n;\nin\n  K (\n    Lin_Arith.add_simps (@{thms arith_simps} @ @{thms more_arith_simps}\n      @ @{thms rel_simps}\n      @ @{thms pred_numeral_simps}\n      @ @{thms arith_special numeral_One}\n      @ @{thms of_nat_simps})\n    #> Lin_Arith.add_simps [@{thm Suc_numeral},\n      @{thm Let_numeral}, @{thm Let_neg_numeral}, @{thm Let_0}, @{thm Let_1},\n      @{thm le_Suc_numeral}, @{thm le_numeral_Suc},\n      @{thm less_Suc_numeral}, @{thm less_numeral_Suc},\n      @{thm Suc_eq_numeral}, @{thm eq_numeral_Suc},\n      @{thm mult_Suc}, @{thm mult_Suc_right},\n      @{thm of_nat_numeral}]\n    #> Lin_Arith.set_number_of number_of)\nend\n*}\n\n\nsubsubsection {* Simplification of arithmetic when nested to the right. *}\n\nlemma add_numeral_left [simp]:\n  \"numeral v + (numeral w + z) = (numeral(v + w) + z)\"\n  by (simp_all add: add.assoc [symmetric])\n\nlemma add_neg_numeral_left [simp]:\n  \"numeral v + (- numeral w + y) = (sub v w + y)\"\n  \"- numeral v + (numeral w + y) = (sub w v + y)\"\n  \"- numeral v + (- numeral w + y) = (- numeral(v + w) + y)\"\n  by (simp_all add: add.assoc [symmetric])\n\nlemma mult_numeral_left [simp]:\n  \"numeral v * (numeral w * z) = (numeral(v * w) * z :: 'a::semiring_numeral)\"\n  \"- numeral v * (numeral w * y) = (- numeral(v * w) * y :: 'b::ring_1)\"\n  \"numeral v * (- numeral w * y) = (- numeral(v * w) * y :: 'b::ring_1)\"\n  \"- numeral v * (- numeral w * y) = (numeral(v * w) * y :: 'b::ring_1)\"\n  by (simp_all add: mult.assoc [symmetric])\n\nhide_const (open) One Bit0 Bit1 BitM inc pow sqr sub dbl dbl_inc dbl_dec\n\n\nsubsection {* code module namespace *}\n\ncode_identifier\n  code_module Num \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Num.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096181702032, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7673516973541054}}
{"text": "theory Huntington\n  imports Main\nbegin\n\n(*\n  A proof that a Huntington Algebra is a Boolean Algebra, and vice versa\n\n  Following\n    http://math.colgate.edu/~amann/MA/robbins_complete.pdf\n*)\n\nno_notation disj (infixr \"\\<or>\" 30)\nno_notation conj (infixr \"\\<and>\" 35)\n\n(*  Definition of a boolean algebra *)\nlocale boolean_algebra =\n  fixes disj :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\" (infixl \"\\<or>\" 70)\n    and conj :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\" (infixl \"\\<and>\" 70)\n    and neg :: \"'b \\<Rightarrow> 'b\"\n    and tt :: \"'b\"\n    and ff :: \"'b\"\n  assumes assoc_disj [simp]: \"a \\<or> (b \\<or> c) = a \\<or> b \\<or> c\"\n      and comm_disj: \"a \\<or> b = b \\<or> a\"\n      and assoc_conj [simp]: \"a \\<and> (b \\<and> c) = a \\<and> b \\<and> c\"\n      and comm_conj: \"a \\<and> b = b \\<and> a\"\n      and absorb1 [simp]: \"a \\<or> (a \\<and> b) = a\"\n      and absorb2 [simp]: \"a \\<and> (a \\<or> b) = a\"\n      and distrib_disj_over_conj: \"a \\<or> (b \\<and> c) = (a \\<or> b) \\<and> (a \\<or> c)\"\n      and distrib_conj_over_disj: \"a \\<and> (b \\<or> c) = (a \\<and> b) \\<or> (a \\<and> c)\"\n      and lem: \"a \\<or> neg a = tt\"\n      and noncontra: \"a \\<and> neg a = ff\"\nbegin\n\nlemma ac_rule_disj: \"z \\<or> y \\<or> x = z \\<or> x \\<or> y\"\n  by (metis assoc_disj comm_disj)\n\nlemma ac_rule_conj: \"z \\<and> y \\<and> x = z \\<and> x \\<and> y\"\n  by (metis assoc_conj comm_conj)\n    \nlemma idempotence_disj[simp]: \"x \\<or> x = x\"\nproof -\n  have \"x \\<or> x = x \\<or> (x \\<and> (x \\<or> x))\"\n    by (subst absorb2, rule refl)\n  also have \"... = x\"\n    by (subst absorb1[where a=\"x\" and b=\"x \\<or> x\"], rule refl)\n  finally show ?thesis .\nqed\n\nlemma idempotence_conj[simp]: \"x \\<and> x = x\"\n  by (metis absorb1 absorb2)\n\nlemma y_disj_absorb_iff_x_conj_absorb: \"x \\<or> y = y \\<longleftrightarrow> x \\<and> y = x\"\n  by (metis absorb1 absorb2 comm_conj comm_disj)\n    \nlemma neutral_disj_ff[simp]: \"x \\<or> ff = x\"\n  using absorb1 noncontra by fastforce\n\nlemma neutral_conj_tt[simp]: \"x \\<and> tt = x\"\n  using absorb2 lem by fastforce\n    \nlemma absorbing_disj_tt[simp]: \"x \\<or> tt = tt\"\n  by (metis absorb2 comm_conj comm_disj neutral_conj_tt)\n\nlemma absorbing_conj_ff[simp]: \"x \\<and> ff = ff\"\n  by (metis absorb2 comm_conj comm_disj neutral_disj_ff)\n    \ndefinition is_complement where\n  \"is_complement a b \\<equiv> HOL.conj (a \\<and> b = ff) (a \\<or> b = tt)\"\n    \nlemma complement_unique: \"\\<lbrakk> is_complement x y; is_complement x z \\<rbrakk> \\<Longrightarrow> y = z\"\n  unfolding is_complement_def\n  by (metis (full_types) distrib_disj_over_conj comm_conj comm_disj idempotence_disj neutral_conj_tt)\n\nlemma complement_neg: \"is_complement x (neg x)\"\n  unfolding is_complement_def\n  by (simp add: lem noncontra)\n    \nlemma double_negation_elim[simp]: \"neg (neg x) = x\"\n  by (metis complement_unique is_complement_def comm_conj comm_disj lem noncontra)\n    \nlemma neg_injective: \"neg x = neg y \\<Longrightarrow> x = y\"\n  by (metis double_negation_elim)\n\nlemma neg_ff_is_tt[simp]: \"neg ff = tt\"\n  by (metis lem noncontra y_disj_absorb_iff_x_conj_absorb)\n\nlemma neg_tt_is_ff[simp]: \"neg tt = ff\"\n  using double_negation_elim neg_ff_is_tt by blast\n\n(* The De Morgan rules *)\nlemma demorgan_over_disj[simp]: \"neg (x \\<or> y) = neg x \\<and> neg y\"\nproof -\n  have \"(x \\<or> y) \\<and> (neg x \\<and> neg y) = (x \\<and> neg x \\<and> neg y) \\<or> (y \\<and> neg x \\<and> neg y)\"\n    by (metis absorbing_conj_ff assoc_conj comm_conj distrib_conj_over_disj noncontra)\n  also have \"... = (ff \\<and> neg y) \\<or> (ff \\<and> neg x)\"\n    using ac_rule_conj noncontra by force\n  also have \"... = ff\"\n    by (metis absorb1 absorbing_conj_ff comm_conj)\n  finally have A: \"(x \\<or> y) \\<and> (neg x \\<and> neg y) = ff\" .\n \n  have \"(x \\<or> y) \\<or> (neg x \\<and> neg y) = (x \\<or> y \\<or> neg x) \\<and> (x \\<or> y \\<or> neg y)\"\n    by (metis distrib_disj_over_conj)\n  also have \"... = (y \\<or> tt) \\<and> (x \\<or> tt)\"\n    by (metis ac_rule_disj assoc_disj lem)\n  also have \"... = tt\"\n    by simp\n  finally have B: \"(x \\<or> y) \\<or> (neg x \\<and> neg y) = tt\" .\n      \n  have \"is_complement (x \\<or> y) (neg x \\<and> neg y)\"\n    using A B is_complement_def by blast\n  thus ?thesis\n    using is_complement_def complement_neg complement_unique by blast\nqed\n\nlemma demorgan_over_conj[simp]: \"neg (x \\<and> y) = neg x \\<or> neg y\"\n  by (metis demorgan_over_disj double_negation_elim)\n\n(* The Huntington Equation *)\nlemma huntington: \"neg (neg x \\<or> neg y) \\<or> neg (neg x \\<or> y) = x\"\n  by (metis double_negation_elim demorgan_over_disj distrib_conj_over_disj lem neutral_disj_ff)\n\nlemma disj_dual_conj: \"a \\<or> b = neg (neg a \\<and> neg b)\"\n  by simp\n\nlemma conj_dual_disj: \"a \\<and> b = neg (neg a \\<or> neg b)\"\n  by simp\n    \nend\n\n  \n(* Definition of a Huntington Algebra *)\nlocale huntington_algebra =\n  fixes disj :: \"'b \\<Rightarrow> 'b \\<Rightarrow> 'b\" (infixl \"\\<or>\" 70)\n    and neg :: \"'b \\<Rightarrow> 'b\"\n  assumes assoc[simp]: \"a \\<or> (b \\<or> c) = a \\<or> b \\<or> c\"\n      and comm: \"a \\<or> b = b \\<or> a\"\n      and huntington[simp]: \"neg (neg x \\<or> neg y) \\<or> neg (neg x \\<or> y) = x\"\nbegin\n\nlemma ac_rule: \"z \\<or> y \\<or> x = z \\<or> x \\<or> y\"\n  by (metis assoc comm)\n    \nlemma xnx_eq_nxnnx[simp]: \"neg x \\<or> neg (neg x) = x \\<or> neg x\"\nproof -\n  have \"neg x \\<or> neg (neg x) = neg (neg (neg (neg x)) \\<or> neg x) \\<or> neg (neg (neg (neg x)) \\<or> neg (neg x)) \\<or> neg (neg (neg x) \\<or> neg x) \\<or> neg (neg (neg x) \\<or> neg (neg x))\"\n    by (metis huntington[where y=\"neg x\"] assoc comm)\n  also have \"... = neg (neg x \\<or> neg (neg (neg x))) \\<or> neg (neg x \\<or> neg (neg x)) \\<or> neg (neg (neg x) \\<or> neg (neg (neg x))) \\<or> neg (neg (neg x) \\<or> neg (neg x))\"\n    proof (rule arg_cong[where f=\"\\<lambda>z. z \\<or> neg (neg (neg x) \\<or> neg (neg x))\"])\n      show \"neg (neg (neg (neg x)) \\<or> neg x) \\<or> neg (neg (neg (neg x)) \\<or> neg (neg x)) \\<or> neg (neg (neg x) \\<or> neg x) =\n           neg (neg x \\<or> neg (neg (neg x))) \\<or> neg (neg x \\<or> neg (neg x)) \\<or> neg (neg (neg x) \\<or> neg (neg (neg x)))\"\n        by (metis ac_rule comm)\n    qed\n  also have \"... = x \\<or> neg x\"\n    by (metis huntington[where y=\"neg (neg x)\"] assoc comm)\n  finally show ?thesis .\nqed\n\nlemma double_negation_elim[simp]: \"neg (neg x) = x\"\nproof -\n  have \"neg (neg x) = neg (neg (neg (neg x)) \\<or> neg (neg x)) \\<or> neg (neg (neg (neg x)) \\<or> neg x)\"\n    by (simp only: huntington[symmetric, where y=\"neg x\"])\n  also have \"... = neg (neg x \\<or> neg (neg (neg x))) \\<or> neg (neg x \\<or> neg (neg x))\"\n    by (simp only: xnx_eq_nxnnx comm)\n  also have \"... = x\"\n    by (simp only: huntington[where y=\"neg (neg x)\"])\n  finally show ?thesis .\nqed\n\nlemma neg_injective: \"neg x = neg y \\<Longrightarrow> x = y\"\n  by (metis double_negation_elim)\n\n(* Define conj as the dual operation of disj *)\ndefinition conj (infixl \"\\<and>\" 70) where\n  \"a \\<and> b = neg (neg a \\<or> neg b)\"\n  \nlemma assoc_conj[simp]: \"a \\<and> (b \\<and> c) = a \\<and> b \\<and> c\"\n  unfolding conj_def\n  by simp\n\nlemma comm_conj: \"a \\<and> b = b \\<and> a\"\n  unfolding conj_def\n  by (simp add: comm)\n\nlemma ac_rule_conj: \"z \\<and> y \\<and> x = z \\<and> x \\<and> y\"\n  by (metis assoc_conj comm_conj)\n\nlemma demorgan_over_disj: \"neg (x \\<or> y) = neg x \\<and> neg y\"\n  unfolding conj_def\n  by simp\n\nlemma demorgan_over_conj[simp]: \"neg (x \\<and> y) = neg x \\<or> neg y\"\n  unfolding conj_def\n  using double_negation_elim by blast\n\nlemma huntington2[simp]: \"(x \\<and> y) \\<or> (x \\<and> neg y) = x\"\n  unfolding conj_def\n  using huntington by force\n\nlemma tt_unique: \"x \\<or> neg x = y \\<or> neg y\"\nproof -\n  have \"x \\<or> neg x = (x \\<and> neg y) \\<or> (x \\<and> neg (neg y)) \\<or> (neg x \\<and> neg y) \\<or> (neg x \\<and> neg (neg y))\"\n    by (metis assoc huntington2[where y=\"neg y\"])\n  also have \"... = (neg y \\<and> x) \\<or> (neg y \\<and> neg x) \\<or> (y \\<and> x) \\<or> (y \\<and> neg x)\"\n    by (simp only: double_negation_elim comm_conj assoc ac_rule)\n  also have \"... = y \\<or> neg y\"\n    by (metis assoc comm huntington2)\n  finally show ?thesis .\nqed\n\nlemma ff_unique: \"x \\<and> neg x = y \\<and> neg y\"\n  unfolding conj_def\n  by (metis tt_unique)\n\n(* define tt as excluded middle *)    \ndefinition tt where\n  \"tt \\<equiv> (THE y. \\<forall>x. x \\<or> neg x = y)\"\n\ndefinition ff where\n  \"ff \\<equiv> neg tt\"\n\n(* show non-contradiction is false *)  \nlemma noncontra[simp]: \"x \\<and> neg x = ff\"\nproof -\n  have \"\\<exists>!y. (\\<forall>x. x \\<or> neg x = y)\"\n    by (metis tt_unique)\n  hence \"\\<forall>x. x \\<or> neg x = (THE x. \\<forall>xa. xa \\<or> neg xa = x)\"\n    by (rule theI')\n  hence \"neg x \\<or> x = (THE y. \\<forall>x. x \\<or> neg x = y)\"\n    by (metis comm)\n  thus \"x \\<and> neg x = ff\"\n    unfolding ff_def tt_def\n    by (simp add: conj_def)\nqed\n  \n(* Show law of excluded middle *)\nlemma lem[simp]: \"x \\<or> neg x = tt\"\n  by (metis demorgan_over_disj ff_def neg_injective noncontra)\n\nlemma tt_dup[simp]: \"tt \\<or> tt = tt\"\n  by (metis assoc huntington demorgan_over_conj double_negation_elim noncontra xnx_eq_nxnnx)\n  \nlemma ff_dup[simp]: \"ff \\<or> ff = ff\"\nproof -\n  have \"ff \\<or> ff = neg (tt \\<or> tt) \\<or> neg tt\"\n    using ff_def tt_dup by simp\n  also have \"... = neg tt\"\n    by (metis ff_def huntington2 demorgan_over_disj noncontra)\n  also have \"... = ff\"\n    by (simp only: ff_def)\n  finally show \"ff \\<or> ff = ff\" .\nqed\n    \nlemma neutral_disj_ff[simp]: \"x \\<or> ff = x\"\n  by (metis assoc ff_dup huntington2 noncontra)\n\nlemma neutral_conj_tt[simp]: \"x \\<and> tt = x\"\n  using ff_def neg_injective neutral_disj_ff by simp\n\nlemma idempotence_disj[simp]: \"x \\<or> x = x\"\n  by (metis demorgan_over_disj huntington2 neg_injective neutral_disj_ff noncontra)\n\nlemma idempotence_conj[simp]: \"x \\<and> x = x\"\n  by (metis huntington2 neutral_disj_ff noncontra)\n\nlemma absorbing_disj_tt[simp]: \"x \\<or> tt = tt\"\n  by (metis assoc idempotence_disj lem)\n\nlemma absorbing_conj_ff[simp]: \"x \\<and> ff = ff\"\n  by (metis ac_rule_conj comm_conj idempotence_conj noncontra)\n    \nlemma absorb1 [simp]: \"a \\<or> (a \\<and> b) = a\"\n  by (metis comm huntington2 assoc idempotence_disj)\n  \nlemma absorb2 [simp]: \"a \\<and> (a \\<or> b) = a\"\n  by (simp add: demorgan_over_disj neg_injective)\n\n(* Show the distributive laws *)\nlemma distrib_conj_over_disj: \"x \\<and> (y \\<or> z) = (x \\<and> y) \\<or> (x \\<and> z)\"\nproof -\n  have \"x \\<and> (y \\<or> z) = (x \\<and> (y \\<or> z) \\<and> y) \\<or> (x \\<and> (y \\<or> z) \\<and> neg y)\"\n    by simp      \n  also have \"... = (x \\<and> y) \\<or> (x \\<and> (y \\<or> z) \\<and> neg y)\"\n    by (metis absorb2 ac_rule_conj comm_conj)\n  also have \"... = (x \\<and> y \\<and> z) \\<or> (x \\<and> y \\<and> neg z) \\<or> (x \\<and> neg y \\<and> z \\<and> (y \\<or> z)) \\<or> (x \\<and> (y \\<or> z) \\<and> neg y \\<and> neg z)\"\n      by (metis ac_rule_conj assoc huntington2)\n  also have \"... = (x \\<and> y \\<and> z) \\<or> (x \\<and> y \\<and> neg z) \\<or> (x \\<and> neg y \\<and> z) \\<or> (x \\<and> (y \\<or> z) \\<and> neg (y \\<or> z))\"\n    proof -\n      have \"x \\<and> neg y \\<and> z = x \\<and> neg y \\<and> z \\<and> (y \\<or> z)\"\n        by (metis absorb2 assoc_conj comm)\n      then show ?thesis\n        using demorgan_over_disj by force\n    qed\n  also have \"... = (x \\<and> y \\<and> z) \\<or> (x \\<and> y \\<and> neg z) \\<or> (x \\<and> neg y \\<and> z)\"\n    by (metis absorbing_conj_ff assoc_conj neutral_disj_ff noncontra)\n  also have \"... = (x \\<and> y \\<and> z) \\<or> (x \\<and> y \\<and> neg z) \\<or> (((x \\<and> z) \\<and> y) \\<or> ((x \\<and> z) \\<and> neg y))\"\n    by (simp add: ac_rule_conj)\n  also have \"... = (x \\<and> y) \\<or> (x \\<and> z)\"\n    by (simp only: huntington2)\n  finally show ?thesis .\nqed\n\nlemma distrib_disj_over_conj: \"a \\<or> (b \\<and> c) = (a \\<or> b) \\<and> (a \\<or> c)\"\n  by (metis conj_def demorgan_over_disj distrib_conj_over_disj double_negation_elim)\nend\n\n(* \n  The main theorems\n\n  Given a boolean algebra, we have a huntington algebra\n*)\ntheorem B_imp_H: \"boolean_algebra disj' conj' neg' tt ff \\<Longrightarrow> huntington_algebra disj' neg'\"\nproof -\n  assume B: \"boolean_algebra disj' conj' neg' tt ff\"\n  show ?thesis\n  proof unfold_locales\n    show \"\\<And>a b c. disj' a (disj' b c) = disj' (disj' a b) c\"\n      using B boolean_algebra.assoc_disj by metis\n  next\n    show \"\\<And>a b. disj' a b = disj' b a\"\n      using B boolean_algebra.comm_disj by metis\n  next\n    show \"\\<And>x y. disj' (neg' (disj' (neg' x) (neg' y))) (neg' (disj' (neg' x) y)) = x\"\n      using B boolean_algebra.huntington by metis\n  qed\nqed\n\n(* \n  The main theorems\n\n  Given a huntington algebra, we can construct a boolean algebra\n*)\ntheorem H_imp_B: \"\\<lbrakk> huntington_algebra disj' neg'; conj' = huntington_algebra.conj disj' neg';\n                    tt = huntington_algebra.tt disj' neg'; ff = huntington_algebra.ff disj' neg' \\<rbrakk> \\<Longrightarrow>\n                  boolean_algebra disj' conj' neg' tt ff\"\nproof -\n  assume H: \"huntington_algebra disj' neg'\"\n     and A: \"conj' = huntington_algebra.conj disj' neg'\"\n     and T: \"tt = huntington_algebra.tt disj' neg'\"\n     and F: \"ff = huntington_algebra.ff disj' neg'\"\n\n  show ?thesis\n  proof unfold_locales\n    show \"\\<And>a b c. disj' a (disj' b c) = disj' (disj' a b) c\"\n      by (meson H huntington_algebra.assoc)\n  next\n    show \"\\<And>a b. disj' a b = disj' b a\"\n      by (meson H huntington_algebra.comm)\n  next  \n    show \"\\<And>a b c. conj' a (conj' b c) = conj' (conj' a b) c\"\n      by (simp only: H A huntington_algebra.assoc_conj)\n  next\n    show \"\\<And>a b. conj' a b = conj' b a\"\n      by (simp only: A H huntington_algebra.comm_conj)\n  next\n    show  \"\\<And>a b. disj' a (conj' a b) = a\"\n      by (simp only: H A huntington_algebra.absorb1)\n  next\n    show  \"\\<And>a b. conj' a (disj' a b) = a\"\n      by (simp only: H A huntington_algebra.absorb2)\n  next\n    show \"\\<And>a b c. disj' a (conj' b c) = conj' (disj' a b) (disj' a c)\"\n      by (simp only: H A huntington_algebra.distrib_disj_over_conj)\n  next\n    show  \"\\<And>a b c. conj' a (disj' b c) = disj' (conj' a b) (conj' a c)\"\n      by (simp only: H A huntington_algebra.distrib_conj_over_disj)\n  next\n    show \"\\<And>a. disj' a (neg' a) = tt\"\n      by (simp only: H T huntington_algebra.lem)\n  next\n    show \"\\<And>a. conj' a (neg' a) = ff\"\n      by (simp only: H A F huntington_algebra.noncontra)\n  qed\nqed\n\nend", "meta": {"author": "vjackson725", "repo": "huntington-algebras", "sha": "3e2cc876b72255991933ebf72e13defef371042f", "save_path": "github-repos/isabelle/vjackson725-huntington-algebras", "path": "github-repos/isabelle/vjackson725-huntington-algebras/huntington-algebras-3e2cc876b72255991933ebf72e13defef371042f/Huntington.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587905460026, "lm_q2_score": 0.8633916047011595, "lm_q1q2_score": 0.7673468783617748}}
{"text": "section\\<open>Perfect Number Theorem\\<close>\n\ntheory Perfect\nimports Sigma\nbegin\n\ndefinition  perfect :: \"nat => bool\" where\n  \"perfect m \\<equiv> m>0 \\<and> 2*m = sigma m\"\n\ntheorem perfect_number_theorem:\n  assumes even: \"even m\" and perfect: \"perfect m\"\n  shows \"\\<exists> n . m = 2^n*(2^(n+1) - 1) \\<and> prime ((2::nat)^(n+1) - 1)\"\nproof                                         \n  from perfect have m0: \"m>0\" by (auto simp add: perfect_def)\n\n  let ?n = \"multiplicity 2 m\" \n  let ?A = \"m div 2^?n\"\n  let ?np = \"(2::nat)^(?n+1) - 1\"\n\n  from even m0 have n1: \"?n >= 1 \" by (simp add: multiplicity_geI)\n\n  have  \"2^?n dvd m\" by (rule multiplicity_dvd)\n  hence \"m = 2^?n*?A\" by (simp only: dvd_mult_div_cancel) \n  with m0 have mdef: \"m=2^?n*?A \\<and> coprime 2 ?A\"\n    using multiplicity_decompose [of m 2] by simp\n  moreover with m0 have a0: \"?A>0\" by (metis nat_0_less_mult_iff)\n  moreover\n  { from perfect have \"2*m=sigma(m)\" by (simp add: perfect_def)\n    with mdef have \"2^(?n+1)*?A=sigma(2^?n*?A)\" by auto\n  } ultimately have \"2^(?n+1)*?A=sigma(2^?n)*sigma(?A)\"\n    by (simp add: sigma_semimultiplicative)\n  hence formula: \"2^(?n+1)*?A=(?np)*sigma(?A)\"\n    by (simp only: sigma_prime_power_two)\n\n  from n1 have \"(2::nat)^(?n+1) >= 2^2\" by (simp only: power_increasing)\n  hence nplarger: \"?np>= 3\" by auto\n\n  let ?B = \"?A div ?np\"\n\n  from formula have \"?np dvd ?A * 2^(?n+1)\"\n    by (auto simp add: ac_simps)\n  then have \"?np dvd ?A\"\n    using coprime_diff_one_left_nat [of \"2 ^ (multiplicity 2 m + 1)\"]\n    by (auto simp add: coprime_dvd_mult_left_iff)\n  then have bdef: \"?np*?B = ?A\"\n    by simp\n  with a0 have  b0: \"?B>0\" by (metis gr0I mult_is_0)\n\n  from nplarger a0 have bsmallera: \"?B < ?A\" by auto\n\n  have \"?B = 1\"\n  proof (rule ccontr)\n    assume \"?B \\<noteq> 1\"\n    with b0 bsmallera have \"1<?B\" \"?B<?A\" by auto\n    moreover from bdef have \"?B : divisors ?A\"\n      by (metis divisors_eq_dvd dvd_triv_right)\n    ultimately have \"1+?B+?A \\<le> sigma ?A\"\n      using sigma_third_divisor by blast\n    with nplarger have \"?np*(1+?A+?B) \\<le> ?np*(sigma ?A)\"\n      by (auto simp only: nat_mult_le_cancel1)\n    with bdef have \"?np+?A*?np + ?A*1 \\<le> ?np*(sigma ?A)\"\n      by (simp add: mult.commute distrib_left)\n    hence \"?np+?A*(?np + 1) \\<le> ?np*(sigma ?A)\" by (simp only:add_mult_distrib2)\n    with nplarger have \"2^(?n+1)*?A < ?np*(sigma ?A)\" by(simp add:mult.commute)\n    with formula show \"False\" by auto\n  qed\n\n  with bdef have adef: \"?A=?np\" by auto\n  with formula have \"?np*2^(?n+1) = ?np * sigma(?A)\" by auto\n  with nplarger adef have \"?A + 1=sigma(?A)\" by auto\n  with a0 have \"prime ?A\"\n    by (simp add: prime_iff_sigma)\n  with mdef adef show \"m = 2^?n * ?np \\<and> prime ?np\" by simp\nqed\n\ntheorem Euclid_book9_prop36:\n  assumes p: \"prime (2^(n+1) - (1::nat))\"\n  shows \"perfect (2 ^ n * (2 ^ (n + 1) - 1))\"\n  unfolding perfect_def\nproof (intro conjI; simp)\n  from assms show \"2 * 2^n > Suc 0\" by (auto simp add: prime_nat_iff)\nnext\n  have \"2 \\<noteq> ((2::nat)^(n+1) - 1)\" by simp arith\n  then have \"coprime (2::nat) (2^(n+1) - 1)\"\n    by (metis p primes_coprime_nat two_is_prime_nat) \n  moreover with p have \"2^(n+1) - 1 > (0::nat)\"\n    by (auto simp add: prime_nat_iff)\n  ultimately have  \"sigma (2^n*(2^(n+1) - 1)) = (sigma(2^n))*(sigma(2^(n+1) - 1))\"\n    by (metis sigma_semimultiplicative two_is_prime_nat)\n  also from assms have \"... = (sigma(2^(n)))*(2^(n+1))\"\n    by (auto simp add: prime_imp_sigma)\n  also have \"... = (2^(n+1) - 1)*(2^(n+1))\" by(simp add: sigma_prime_power_two)\n  finally show \"2*(2^n * (2*2^n - Suc 0)) = sigma(2^n*(2*2^n - Suc 0))\" by auto\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Perfect-Number-Thm/Perfect.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.8333246035907933, "lm_q1q2_score": 0.7673166916523424}}
{"text": "\\<^marker>\\<open>creator Florian Kessler\\<close>\n\ntheory Memory\n  imports Big_Step_Small_Step_Equivalence \"HOL-Library.Discrete\" Max_Constant\nbegin\n\ntext \\<open> We give a definition for the amount of memory that an IMP- program uses during its \n       execution, and show that there is a bound that is linear in the number of steps the\n       execution takes. \\<close>\n\ndefinition bit_length where \"bit_length x \\<equiv>  Discrete.log x + 1\"\n\nlemma bit_length_monotonic: \"x \\<le> y \\<Longrightarrow> bit_length x \\<le> bit_length y\" \n  by(auto simp: bit_length_def log_le_iff)\n\nlemma bit_length_of_power_of_two: \"y > 0 \\<Longrightarrow> bit_length (2 ^ x * y) = x + bit_length y\"\n  apply(induction x)\n  by(auto simp: bit_length_def mult.assoc)\n\ntext \\<open> The amount of memory a single state uses. Note that we only consider registers that \n       can be accessed by the program, hence the additional parameter 'c' in this definition. \\<close>\n\ndefinition state_memory :: \"com \\<Rightarrow> state \\<Rightarrow> nat\" where\n\"state_memory c s = fold (+) (map (\\<lambda> r. bit_length (s r)) (remdups (all_variables c))) 0\"\n\ntext \\<open> We define something to be a memory bound for a program and an initial state, if it\n       bounds every state that is reachable. \\<close>\n\ndefinition is_memory_bound :: \"com \\<Rightarrow> state \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"is_memory_bound c s n \\<equiv> (\\<forall> t c' s'. (c, s) \\<rightarrow>\\<^bsup>t\\<^esup> (c', s') \\<longrightarrow> state_memory c' s' \\<le> n)\"\n\nlemma x_leq_fold_max_l_x: \"(x :: nat) \\<le> fold max l x\" \nproof(induction l arbitrary: x)\n  case (Cons a l)\n  then show ?case by (auto intro: le_trans[where ?j = \"max a x\"])\nqed auto\n\nlemma fold_max_l_x_le_l_y: \"(x :: nat) \\<le> y \\<Longrightarrow> fold max l x \\<le> fold max l y\" \n  by (induction l arbitrary: x y) auto\n\nlemma sum_of_list_leq_length_times_max: \"length l * fold max l (0 :: nat) \\<le> k \\<Longrightarrow> fold (+) l 0 \\<le> k\"\nproof(induction l arbitrary: k)\n  case (Cons a l)\n  let ?k = \"length l * fold max l (0 :: nat)\"\n  have \"fold (+) (a # l) 0 = a + fold (+) l 0\" by (simp add: fold_plus_sum_list_rev)\n  also have \"... \\<le> a + ?k\" using Cons.IH[where ?k=\"?k\"] by simp\n  also have \"... \\<le> fold max l a + ?k\" \n    using x_leq_fold_max_l_x by simp\n  also have \"... \\<le> fold max l a + length l * fold max l a\" \n    using fold_max_l_x_le_l_y by simp\n  finally show ?case using Cons by auto\nqed auto\n\nlemma max_bit_length_bit_length: \"max (bit_length x) (bit_length y) = bit_length (max x y)\"\n  by (simp add: bit_length_def log_mono max_of_mono)\n\nlemma fold_max_map_bit_length: \"l \\<noteq> [] \n  \\<Longrightarrow> fold max (map (\\<lambda>x. bit_length (f x)) l) (bit_length a) = bit_length (fold max (map f l) a)\"\nproof(induction l arbitrary: a)\n  case (Cons a l)\n  then show ?case by (cases l) (auto simp: max_bit_length_bit_length)\nqed auto\n\nlemma fold_max_map_bit_length': \n  assumes \"l \\<noteq> []\"\n  shows \"fold max (map (\\<lambda>x. bit_length (f x)) l) 0 = bit_length (fold max (map f l) 0)\"\n  using assms proof(induction l)\n  case (Cons a l)\n  then show ?case \n    apply(auto simp: max_bit_length_bit_length)\n    apply(cases l)\n     apply simp\n    apply(rule fold_max_map_bit_length )\n    by simp\nqed auto\n\nlemma remdups_non_empty_iff[simp]: \"remdups l \\<noteq> [] \\<longleftrightarrow> l \\<noteq> []\"\n  by (induction l) auto\n\nlemma fold_max_map_le_Max_range: \n  \"finite (range (f :: _ \\<Rightarrow> nat)) \\<Longrightarrow> fold max (map f l) x \\<le> max x (Max (range f))\"\n  apply(induction l arbitrary: x)\n   apply auto\n  by (smt Max.in_idem max.assoc max.commute rangeI)\n\nlemma fold_max_map_le_Max_range': \n  \"finite (range (f :: _ \\<Rightarrow> nat)) \\<Longrightarrow> fold max (map f l) 0 \\<le> Max (range f)\"\n  using fold_max_map_le_Max_range\n  by (metis max_0L)\n\nlemma Max_register_bounds_state_memory: \"finite (range s) \n  \\<Longrightarrow> state_memory c s \\<le> num_variables c * bit_length (Max (range s))\"\n  by(auto simp: num_variables_def fold_max_map_bit_length' state_memory_def\n          intro!: bit_length_monotonic fold_max_map_le_Max_range' sum_of_list_leq_length_times_max)\n\nlemma finite_range_stays_finite_step: \"(c1, s1) \\<rightarrow> (c2, s2) \\<Longrightarrow> finite (range s1)\n  \\<Longrightarrow> finite (range s2)\"\nproof(induction c1 s1 c2 s2 rule: small_step_induct)\n  case (Assign x a s)\n  then show ?case \n    by (auto intro: finite_subset[where ?B = \"range s\"])\nqed auto\n\nlemma finite_range_stays_finite: \"(c1, s1) \\<rightarrow>\\<^bsup>t\\<^esup> (c2, s2) \\<Longrightarrow> finite (range s1)\n  \\<Longrightarrow> finite (range s2)\"\n  apply(induction t arbitrary: c1 s1)\n   using finite_range_stays_finite_step by auto\n\nlemma Max_insert_le_when: \"finite (range (s :: vname \\<Rightarrow> nat)) \\<Longrightarrow> y \\<le> r \\<Longrightarrow>  Max (range s) \\<le> r \n  \\<Longrightarrow> Max (range (s(x := y))) \\<le> r\"\n  apply auto\n  apply(subst Max_insert)\n    apply(metis Un_infinite image_Un sup_top_right)\n   apply(auto)\n  apply(subst Max_le_iff)\n    apply(metis Un_infinite image_Un sup_top_right)\n  by auto\n\nlemma le_then_sub_le: \"(a :: nat) \\<le> b \\<Longrightarrow> a - c \\<le> b\" by simp\n\nlemma one_step_Max_increase: \"(c1, s1) \\<rightarrow> (c2, s2) \\<Longrightarrow> finite (range s1)\n  \\<Longrightarrow> Max (range s2) \\<le> 2 * (max (Max (range s1)) (max_constant c1))\"\nproof (induction c1 s1 c2 s2 rule: small_step_induct)\n  case (Assign x a s)\n  then show ?case\n  proof (cases a)\n    case (A x1)\n    then show ?thesis\n      using \\<open>finite (range s)\\<close>\n      by (cases x1; fastforce simp: numeral_2_eq_2 trans_le_add1 intro: Max_insert_le_when)\n  next\n    case (Plus x1 x2)\n    then show ?thesis\n      using \\<open>finite (range s)\\<close>\n      apply(cases x1; cases x2; auto simp only: intro!: Max_insert_le_when)\n      by(auto simp add: numeral_2_eq_2 max.coboundedI1 intro!: add_le_mono)\n  next\n    case (Sub x1 x2)\n    then show ?thesis\n      using \\<open>finite (range s)\\<close>\n      apply(cases x1; cases x2; auto simp only: intro!: Max_insert_le_when)\n      by(auto simp: numeral_2_eq_2 max.coboundedI1 \n              intro!: le_then_sub_le trans_le_add1)\n  next\n    case (Parity x1)\n    then show ?thesis\n    proof (cases x1)\n      case (N x1)\n      then show ?thesis \n        using \\<open>finite (range s)\\<close> Parity\n        apply (auto simp only: intro!: Max_insert_le_when)\n        by auto\n    next\n      case (V x2)\n      then show ?thesis\n        using \\<open>finite (range s)\\<close> Parity\n        apply(auto simp only: intro!: Max_insert_le_when)\n        apply auto\n        apply(rule le_trans[where ?j=\"s x2\"])\n        by(auto simp add: numeral_2_eq_2 intro!: trans_le_add1)\n    qed\n  next\n    case (RightShift x1)\n    then show ?thesis\n    proof (cases x1)\n      case (N x1)\n      then show ?thesis \n        using \\<open>finite (range s)\\<close> RightShift\n        apply (auto simp only: intro!: Max_insert_le_when)\n        by auto\n    next\n      case (V x2)\n      then show ?thesis\n        using \\<open>finite (range s)\\<close> RightShift\n        apply(auto simp only: intro!: Max_insert_le_when)\n        apply auto\n        apply(rule le_trans[where ?j=\"s x2\"])\n        by(auto simp add: numeral_2_eq_2 intro!: trans_le_add1)\n    qed\n  qed\nnext\n  case (Seq2 c\\<^sub>1 s c\\<^sub>1' s' c\\<^sub>2)\n  then show ?case by simp\nqed (linarith)+\n\nlemma Max_increase: \"(c1, s1) \\<rightarrow>\\<^bsup>t\\<^esup> (c2, s2) \\<Longrightarrow> finite (range s1) \n  \\<Longrightarrow> Max (range s2) \\<le> (2 ^ t) * (max (Max (range s1)) (max_constant c1))\"\nproof (induction t arbitrary: c1 s1)\n  case (Suc t)\n  obtain c1' s1' where \"(c1, s1) \\<rightarrow> (c1', s1')\" \"(c1', s1') \\<rightarrow>\\<^bsup>t\\<^esup> (c2, s2)\"\n    using \\<open>(c1, s1) \\<rightarrow>\\<^bsup>Suc t\\<^esup> (c2, s2)\\<close>\n    by auto\n  have \"Max (range s2) \\<le> (2 ^ t) * (max (Max (range s1')) (max_constant c1'))\"\n    using Suc.IH \\<open>finite (range s1)\\<close>\n      \\<open>(c1', s1') \\<rightarrow>\\<^bsup>t\\<^esup> (c2, s2)\\<close> \\<open>(c1, s1) \\<rightarrow> (c1', s1')\\<close> \n      finite_range_stays_finite_step \n    by presburger\n  also have \"... \\<le> (2 ^ t) * \n    (max (2 * (max (Max (range s1)) (max_constant c1))) (max_constant c1'))\"\n    using one_step_Max_increase[OF \\<open>(c1, s1) \\<rightarrow> (c1', s1')\\<close> \\<open>finite (range s1)\\<close>]\n    by simp\n  also have \"... \\<le> (2 ^ Suc t) *\n      (max (max (Max (range s1)) (max_constant c1))) (max_constant c1')\"\n    by simp\n  also have \"... \\<le> (2 ^ Suc t) * max (Max (range s1)) (max_constant c1)\"\n    using max_constant_not_increasing_step[OF \\<open>(c1, s1) \\<rightarrow> (c1', s1')\\<close>]\n    by simp\n  finally show ?case by simp\nqed auto\n\ntext \\<open> We show that there always is a linear bound for the memory consumption. \\<close>\n\nlemma linear_bound: \"(c1, s1) \\<Rightarrow>\\<^bsup>t\\<^esup> s2 \\<Longrightarrow> finite (range s1)\n  \\<Longrightarrow> is_memory_bound c1 s1 ((num_variables c1) \n      * (t + bit_length (max 1 (max (Max (range s1)) (max_constant c1)))))\"\n  apply (simp only: is_memory_bound_def)\nproof\n  let ?b = \"(num_variables c1) \n      * (t + bit_length (max 1 (max (Max (range s1)) (max_constant c1))))\"\n\n  assume \"(c1, s1) \\<Rightarrow>\\<^bsup>t\\<^esup> s2\" \"finite (range s1)\"\n  fix t'\n  show \"\\<forall>c' s'.\n             (c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s') \\<longrightarrow>\n             state_memory c' s' \\<le> ?b\"\n  proof\n    fix c'\n    show \"\\<forall>s'. (c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s') \\<longrightarrow>\n               state_memory c' s' \\<le> ?b\"\n    proof \n      fix s'\n      show \"(c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s') \\<longrightarrow>\n               state_memory c' s' \\<le> ?b\"\n      proof\n        assume \"(c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s')\"\n\n        hence \"finite (range s')\"\n          using \\<open>finite (range s1)\\<close> finite_range_stays_finite\n          by auto\n\n        have \"Max (range s') \\<le> (2 ^ t') * (max (Max (range s1)) (max_constant c1))\"\n          using Max_increase \\<open>(c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s')\\<close> \\<open>finite (range s1)\\<close> \n          by auto\n        also have \"... \\<le> (2 ^ t) * (max (Max (range s1)) (max_constant c1))\"\n          using small_step_cant_run_longer_than_big_step\n            \\<open>(c1, s1) \\<Rightarrow>\\<^bsup>t\\<^esup> s2\\<close> \\<open>(c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s')\\<close>\n          by simp\n\n        finally have \"state_memory c' s' \\<le> num_variables c' \n          * bit_length ((2 ^ t) * (max (Max (range s1)) (max_constant c1)))\" \n          using Max_register_bounds_state_memory[OF \\<open>finite (range s')\\<close>]\n          by (meson bit_length_monotonic dual_order.trans mult_le_cancel1)\n        also have \"... \\<le>  num_variables c' \n          * bit_length ((2 ^ t) * (max 1 (max (Max (range s1)) (max_constant c1))))\"\n          using bit_length_monotonic\n          by simp          \n\n        finally show \"state_memory c' s' \\<le> ?b\"\n          using num_variables_not_increasing[OF \\<open>(c1, s1) \\<rightarrow>\\<^bsup>t'\\<^esup> (c', s')\\<close>] order_trans\n          by(fastforce simp: bit_length_of_power_of_two)\n      qed\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "wimmers", "repo": "poly-reductions", "sha": "b2d7c584bcda9913dd5c3785817a5d63b14d1455", "save_path": "github-repos/isabelle/wimmers-poly-reductions", "path": "github-repos/isabelle/wimmers-poly-reductions/poly-reductions-b2d7c584bcda9913dd5c3785817a5d63b14d1455/IMP-/Memory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676518712608, "lm_q2_score": 0.8397339636614178, "lm_q1q2_score": 0.7672452045629039}}
{"text": "theory Skip\n    imports \"Extras\"\nbegin\n\ntext \\<open>Suppressing an element from a function\\<close>                               \n\ndefinition skip :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a)\" where\n\"skip z f \\<equiv> \\<lambda> x. (if x = z then z else (if f x = z then f z else f x))\"\n\nlemma skip_id [simp]: \"skip z f z = z\"\n  unfolding skip_def by simp\n\nlemma skip_z_eq_fz: \"f z = z \\<Longrightarrow> x \\<noteq> z \\<Longrightarrow> (skip z f) x = f x\"\n  unfolding skip_def by simp\n\nlemma skip_fz [simp]: \"f x = z \\<Longrightarrow> skip z f x = f z\"\n  by (metis skip_def)\n\nlemma skip_invariant: \"x \\<noteq> z \\<Longrightarrow> f x \\<noteq> z \\<Longrightarrow> skip z f x = f x\"\n  unfolding skip_def by simp\n\nlemma inj_skip: \"inj f \\<Longrightarrow> inj (skip z f)\"\n  unfolding skip_def by (smt (verit, ccfv_SIG) injD inj_on_def)\n\nlemma bij_skip: \"bij f \\<Longrightarrow> bij (skip z f)\"\n  by (metis bij_def inj_skip skip_def surj_def) \n\nlemma skip_permutes:\n  assumes \"f permutes S\"\n  shows \"skip z f permutes S - {z}\"\nproof (simp add: permutes_def; rule conjI)\n  show \"\\<forall>x. (x \\<in> S \\<longrightarrow> x = z) \\<longrightarrow> skip z f x = x\"\n    by (metis assms permutes_def skip_def)\n  have \"bij (skip z f)\"\n    by (meson assms bij_skip permutes_bij)\n  then show \"\\<forall>y. \\<exists>!x. skip z f x = y\"\n    by (simp add: bij_iff)\nqed\n\nsection \\<open>Suppressing an element from a permutation\\<close>\n\ndefinition skip_perm :: \"'a \\<Rightarrow> 'a perm \\<Rightarrow> 'a perm\" where\n\"skip_perm \\<equiv> (\\<lambda>z (p ::'a perm). Perm (skip z p))\"\n\nlemma apply_skip_perm: \"(\\<langle>$\\<rangle>) (skip_perm z p) = skip z p\"\nunfolding skip_perm_def\nproof\n  obtain A where \"A = set_perm p\" by simp\n  fix x show \"(Perm (skip z p)) \\<langle>$\\<rangle> x = skip z p x\"\n  proof (rule apply_perm_Perm)\n    show \"finite A\" by (simp add: \\<open>A = set_perm p\\<close>)\n    show \"inj_on (skip z ((\\<langle>$\\<rangle>) p)) A\"\n      by (meson inj_skip inj_on_apply_perm inj_on_subset subset_UNIV)\n    show \"\\<And>x. x \\<in> A \\<Longrightarrow> skip z p x \\<in> A\"\n      by (metis \\<open>A = set_perm p\\<close> apply_set_perm skip_def)\n    show \"\\<And>x. x \\<notin> A \\<Longrightarrow> skip z p x = x\"\n      by (metis \\<open>A = set_perm p\\<close> in_set_permI skip_def)\n   qed\n qed\n\nlemma skip_perm_invariant: \"x \\<noteq> z \\<Longrightarrow> p \\<langle>$\\<rangle> x \\<noteq> z \\<Longrightarrow> skip_perm z p x = p \\<langle>$\\<rangle> x\"\n  by (simp add: skip_invariant apply_skip_perm)\n\nlemma skip_perm_notin: \"z \\<notin> set_perm p \\<Longrightarrow> skip_perm z p = p\"\nproof -\n  assume \"z \\<notin> set_perm p\"\n  then have \"p \\<langle>$\\<rangle> z = z\"\n    by blast\n  then have \"skip z p = p\"\n    by (metis perm_eq_iff skip_id skip_z_eq_fz apply_skip_perm)\n  then show ?thesis\n    by (simp add: perm.apply_perm_inverse skip_perm_def)\nqed\n\nlemma skip_perm_permutes: \"(p :: 'a perm) permutes S \\<Longrightarrow> skip_perm z p permutes S - {z}\"\n  by (simp add: apply_skip_perm skip_permutes)\n\nlemma set_perm_skip_id_cycle: \"p \\<langle>$\\<rangle> z = z \\<Longrightarrow> set_perm p = set_perm (skip_perm z p)\"\n  by (simp add: in_set_perm skip_perm_notin)\n\nlemma set_perm_skip_2_cycle: \n  fixes p :: \"'a perm\"\n  assumes \"p z \\<noteq> z\" \"p (p z) = z\"\n  shows \"set_perm p = set_perm (skip_perm z p) \\<union> {z, p z}\"\nproof (rule subset_antisym; rule subsetI)\n  fix x assume \"x \\<in> set_perm p\"\n  then have \"x \\<noteq> z \\<and> x \\<noteq> p z \\<Longrightarrow> x \\<in> set_perm (skip_perm z p)\"\n    by (metis apply_perm_neq_idI apply_skip_perm in_set_permI skip_def)\n  then show \"x \\<in> set_perm (skip_perm z p) \\<union> {z, p z}\"\n    by auto\nnext\n  show \"x \\<in> set_perm p\" if \"x \\<in> set_perm (skip_perm z p) \\<union> {z, p z}\" for x\n    by (metis that Un_insert_right apply_perm_eq_same_iff(2) apply_skip_perm\n        assms boolean_algebra_cancel.sup0 insert_iff skip_invariant)\nqed\n\nlemma set_perm_skip_n_cycle:\n  fixes p :: \"'a perm\"\n  assumes \"p z \\<noteq> z\" \"p (p z) \\<noteq> z\"\n  shows \"set_perm p = set_perm (skip_perm z p) \\<union> {z}\"\nproof (rule subset_antisym; rule subsetI)\n  fix x assume \"x \\<in> set_perm p\"\n  then show \"x \\<in> set_perm (skip_perm z p) \\<union> {z}\"\n    by (metis apply_perm_eq_same_iff(2) apply_skip_perm assms(2) inf_sup_aci(5)\n        insert_iff insert_is_Un skip_fz skip_invariant)\nnext\n  fix x assume \"x \\<in> set_perm (skip_perm z p) \\<union> {z}\"\n  then show \"x \\<in> set_perm p\"\n    by (metis UnE apply_perm_neq_idI apply_skip_perm assms(1) empty_iff in_set_permI\n        insert_iff skip_invariant)\nqed\n\nlemma cycles_imp_cycles_skip:\n  assumes \"c \\<in> cycles_of_perm p\" (is \"c \\<in> ?C\")\n      and \"c \\<notin> cycles_of_perm (skip_perm z p)\" (is \"c \\<notin> ?C'\")\n  shows \"\\<And> x. x \\<noteq> c \\<Longrightarrow> x \\<in> cycles_of_perm p \\<Longrightarrow> x \\<in> cycles_of_perm (skip_perm z p)\"\nproof -\n  have \"z \\<in> set_cycle c\"\n    by (smt (verit, ccfv_threshold) assms apply_cycle_in_set_iff apply_perm_cycle apply_skip_perm \n        cycles_of_perm_altdef mem_Collect_eq skip_invariant)\n  then have \"c = perm_orbit p z\"\n    using assms(1) perm_orbit_eqI by fastforce\n  have disj: \"disjoint_cycles ?C\" by auto\n  fix x assume \"x \\<noteq> c\"\n  then show \"x \\<in> ?C \\<Longrightarrow> x \\<in> ?C'\"\n    by (smt (verit, ccfv_threshold) \\<open>c \\<in> ?C\\<close> disj(1) IntI \\<open>z \\<in> set_cycle c\\<close> apply_cycle_cycles_of_perm\n        apply_perm_cycle apply_set_perm apply_skip_perm cycle_perm_same_iff cycles_of_perm_altdef\n        cycles_of_perm_of_cycles disjoint_cycles_insert empty_iff insertE mem_Collect_eq\n        mk_disjoint_insert perm_of_cycles_not_in set_perm_cycle skip_invariant)\nqed\n\nlemma skip_perm_cycle_invariant:\n  assumes \"x \\<notin> set_cycle (perm_orbit p z)\" \"x \\<in> set_perm p\"\n  shows \"perm_orbit (skip_perm z p) x = perm_orbit p x\"\n  by (smt (verit) apply_cycle_cycles_of_perm apply_perm_cycle apply_perm_neq_idI assms\n      cycles_imp_cycles_skip apply_skip_perm perm_orbit_eqI\n      perm_orbit_in_cycles_of_perm skip_id skip_perm_notin start_in_perm_orbit_iff)\n\nlemma perm_orbit_notin_skip_perm: \"perm_orbit p z \\<notin> cycles_of_perm (skip_perm z p)\"\n  by (metis apply_cycle_cycles_of_perm apply_cycle_perm_orbit' apply_skip_perm\n      id_cycle_eq_perm_orbit_iff id_cycle_not_in_cycles_of_perm skip_id start_in_perm_orbit_iff)\n\ntheorem remove1_cycle_orbit: \"delete_cycle z (perm_orbit p z) = perm_orbit (skip_perm z p) (p z)\"\nproof (rule cycle_eqI; rule; auto simp: conjI apply_cycle_delete)\n  show \"p \\<langle>$\\<rangle> z = z \\<Longrightarrow> z = (skip_perm z p) \\<langle>$\\<rangle> z\"\n    by (simp add: apply_skip_perm)\n  fix x\n  show \"apply_cycle (perm_orbit p z) x = z \\<Longrightarrow> x \\<noteq> z \\<Longrightarrow>\n         p \\<langle>$\\<rangle> z = apply_cycle (perm_orbit (skip_perm z p) (p \\<langle>$\\<rangle> z)) x\"\n    by (metis apply_cycle_perm_orbit apply_cycle_same_iff apply_perm_in_perm_orbit_iff \n      apply_skip_perm skip_def start_in_perm_orbit_iff)\n  show \"p \\<langle>$\\<rangle> z \\<noteq> z \\<Longrightarrow> z = apply_cycle (perm_orbit (skip_perm z p) (p \\<langle>$\\<rangle> z)) z\"\n    by (metis apply_cycle_not_in_set apply_cycle_perm_orbit apply_skip_perm skip_id)\n  \n  assume *: \"apply_cycle (perm_orbit p z) x \\<noteq> z\"  \"x \\<noteq> z\"\n  then consider \"p z = x\" \n    | \"x \\<notin> set_cycle (perm_orbit p z)\"\n    | \"p z \\<noteq> x \\<and> x \\<in> set_cycle (perm_orbit p z)\" \n    by blast \n  then show \"apply_cycle (perm_orbit p z) x = apply_cycle (perm_orbit (skip_perm z p) (p \\<langle>$\\<rangle> z)) x\"\n  proof cases\n    case 1\n    then show ?thesis\n      by (metis *(1) apply_cycle_perm_orbit apply_cycle_perm_orbit'\n          apply_perm_in_perm_orbit_iff skip_perm_invariant start_in_perm_orbit)\n  next\n    case 2\n    then have \"apply_cycle (perm_orbit p z) x = x\"\n      by (transfer; simp)\n    also have \"apply_cycle (perm_orbit (skip_perm z p) (p \\<langle>$\\<rangle> z)) x = x\"\n      by (smt (z3) 2 apply_cycle_not_in_set apply_cycle_perm_orbit apply_perm_in_perm_orbit_iff \n          apply_skip_perm perm_orbit_eqI perm_orbit_eq_id_cycle_iff skip_def start_in_perm_orbit_iff)\n    ultimately show ?thesis by simp\nnext\n  case 3\n  then have \"apply_cycle (perm_orbit p z) x = p x\"\n      by (meson apply_cycle_perm_orbit)\n    also {\n      have \"skip_perm z p x = p x\"\n        by (metis \\<open>apply_cycle (perm_orbit p z) x \\<noteq> z\\<close> \\<open>x \\<noteq> z\\<close> skip_invariant \n            apply_skip_perm calculation)\n      define n where \"n = (LEAST n. (p ^ Suc n) x = p z)\"\n      then have \"((\\<langle>$\\<rangle>) (skip_perm z p) ^^ n) x = p z\"\n      proof (simp add: apply_skip_perm)\n        assume n_def: \"n = (LEAST n. (p * p ^ n) \\<langle>$\\<rangle> x = p \\<langle>$\\<rangle> z)\"\n        have \"\\<exists>m. (p * p ^ m) x = p z\"\n          by (metis 3 apply_perm_power apply_perm_sequence cycles_funpow)\n        then have \"(p * p ^ n) x = p z\"\n          using LeastI n_def by fast\n        then have \"(p ^ n) x = z\"\n          by (metis apply_inj_eq_iff apply_perm_sequence)\n        then have \"n > 0\"\n          using \\<open>x \\<noteq> z\\<close> gr_zeroI by fastforce\n        { fix l assume \"l < n\"\n          then have \"(p ^ l) x \\<noteq> p z \\<and> (p ^ l) x \\<noteq> z\"\n            apply (safe)\n            using 3 \\<open>(p ^ n) \\<langle>$\\<rangle> x = z\\<close> apply_inj_eq_iff apply_perm_sequence\n                dual_order.strict_trans n_def not0_implies_Suc not_less_Least not_less_eq power_Suc\n                power_Suc0_right by (smt (verit, del_insts) \\<open>l < n\\<close>)+\n          from \\<open>l < n\\<close> have p_eq: \"(p ^ l) x = ((skip z p) ^^ l) x\"\n          proof (induct l)\n            case 0\n            then show ?case by simp\n          next\n            case (Suc l)\n            then show ?case\n              by (smt (z3) Suc_lessD n_def\n                   apply_perm_sequence apply_skip_perm funpow_simp_l not_less_Least power_Suc \n                   skip_perm_invariant)\n          qed\n        }\n        then have \"(p ^ (n-1)) x = ((skip z p) ^^ (n-1)) x\"\n          by (simp add: \\<open>0 < n\\<close>)\n        then show \"(skip z ((\\<langle>$\\<rangle>) p) ^^ (LEAST n. (p * p ^ n) \\<langle>$\\<rangle> x = p \\<langle>$\\<rangle> z)) x = p \\<langle>$\\<rangle> z\"\n          by (smt (z3) One_nat_def Suc_pred \\<open>(p ^ n) \\<langle>$\\<rangle> x = z\\<close> \\<open>0 < n\\<close>\n              n_def apply_perm_power funpow_simp_l skip_fz)\n      qed\n      then have \"apply_cycle (perm_orbit (skip_perm z p) (p \\<langle>$\\<rangle> z)) x = p x\"\n        by (metis 3 \\<open>(skip_perm z p) \\<langle>$\\<rangle> x = p \\<langle>$\\<rangle> x\\<close> apply_cycle_perm_orbit funpow_cycles)\n    }\n    ultimately show ?thesis by simp\n  next\n  qed\nqed\n\nlemma cycles_skip_diff:\n  assumes \"x \\<noteq> delete_cycle z (perm_orbit p z)\" \n      and \"x \\<in> cycles_of_perm (skip_perm z p)\" (is \"x \\<in> ?C'\")\n    shows \"x \\<in> cycles_of_perm p\"\nproof -\n  from assms(1) have \"\\<forall>y \\<in> set_cycle x. y \\<notin> set_cycle (perm_orbit (skip_perm z p) z)\"\n    by (simp add: apply_skip_perm)\n  moreover have \"x \\<in> cycles_of_perm p \\<Longrightarrow> \\<forall>y \\<in> set_cycle x. perm_orbit p y \\<in> cycles_of_perm p\"\n    by (meson perm_orbit_in_cycles_of_perm set_cycle_of_perm_subset subset_iff)\n  consider  (empty) \"set_cycle (perm_orbit p z) = {}\" | \n            (size_two) \"size (perm_orbit p z) = 2\" |\n            (union) \"size (perm_orbit p z) > 2\"\n    by (metis One_nat_def gr_implies_not_zero less_2_cases_iff neqE perm_orbit_fixpoint\n        set_cycle_empty_iff set_cycle_ex_funpow size_cycle_not_1' start_in_perm_orbit_iff)\n  then show ?thesis\n  proof cases\n    case empty\n    then show ?thesis\n      by (metis assms(2) id_cycle_not_in_cycles_of_perm perm_orbit_in_cycles_of_perm\n          set_cycle_empty_iff skip_perm_notin)\n  next\n    case size_two\n    then have \"{z, p z} = set_cycle (perm_orbit p z)\"\n      by (smt (z3) apply_cycle_in_set_iff apply_cycle_perm_orbit' card_2_iff card_set_cycle\n      doubleton_eq_iff insert_absorb insert_iff perm_orbit_eq_id_cycle_iff set_cycle_empty_iff\n      start_in_perm_orbit)\n    also have \"perm_orbit (skip_perm z p) (p z) = id_cycle\"\n      by (smt (verit, ccfv_threshold) calculation apply_cycle_in_set_iff apply_cycle_perm_orbit\n apply_skip_perm insertCI insertE is_singletonI is_singleton_conv_Ex1 perm_orbit_fixpoint skip_def)\n    ultimately show ?thesis\n      by (smt (z3) DiffD2 Diff_insert_absorb apply_perm_neq_idI apply_skip_perm assms(2)\n          cycles_of_perm_def image_iff in_set_permI insertE perm_orbit_eq_id_cycle_iff skip_id \n          skip_invariant skip_perm_cycle_invariant)\n  next\n    case union\n    then have \"size (perm_orbit p z) \\<ge> 3\" by simp\n    define poz where \"poz = perm_orbit p z\"\n    then have \"delete_cycle z poz \\<noteq> id_cycle\"\n      using \\<open>size (perm_orbit p z) \\<ge> 3\\<close> apply transfer\n      by (smt (z3) List.finite_set One_nat_def card.empty card.insert_remove cycle_relE\n          cycle_rel_imp_same_set distinct_card empty_set filter_cong insert_absorb leD lessI \n          list.size(3) not_numeral_le_zero numeral_3_eq_3 perm_orbit_impl set_minus_filter_out)\n    also have remove1_poz: \"delete_cycle z poz = perm_orbit (skip_perm z p) (p z)\"\n      by (simp add: poz_def remove1_cycle_orbit union)\n    moreover have \"perm_orbit p z = perm_orbit p (p z)\"\n      by (smt (verit, ccfv_threshold) apply_perm_in_perm_orbit_iff apply_set_perm apply_skip_perm \ncycles_imp_cycles_skip disjoint_cycles_cycles_of_perms in_set_permI perm_of_cycles_in\n perm_of_cycles_of_perm perm_orbit_fixpoint perm_orbit_in_cycles_of_perm perm_orbit_notin_skip_perm\n skip_id start_in_perm_orbit)\n    ultimately have \"set_cycle (perm_orbit (skip_perm z p) (p z)) \\<union> {z} = set_cycle (perm_orbit p z)\"\n      by (metis Un_insert_right poz_def boolean_algebra_cancel.sup0\n          gr_implies_not_zero insert_Diff not_less_iff_gr_or_eq perm_orbit_eq_id_cycle_iff\n          set_cycle_delete size_cycle_eq_0_iff' start_in_perm_orbit union)\n    then show ?thesis\n      by (smt (verit, ccfv_SIG) poz_def remove1_poz apply_cycle_cycles_of_perm\n          apply_cycle_same_iff apply_set_perm apply_skip_perm assms cycles_of_perm_altdef\n          mem_Collect_eq perm_orbit_eqI set_perm_cycle skip_def)\n  qed\nqed\n\nlemma cycles_skip:\n  assumes \"z \\<in> set_perm p\"\n  shows \"cycles_of_perm p = cycles_of_perm (skip_perm z p) \\<union>\n       {perm_orbit p z} - {delete_cycle z (perm_orbit p z)}\" (is \"?C = ?C' \\<union> {?poz} - {?poz'}\")\nproof (rule subset_antisym; rule subsetI)\n  have disj: \"disjoint_cycles ?C\" \"disjoint_cycles ?C'\" by auto\n  have poz_subset: \"set_cycle ?poz' \\<subseteq> set_cycle ?poz\"\n    by (metis DiffD1 apply_perm_neq_idI assms cycle_delete_swap equals0D set_cycle_delete\n        set_cycle_empty_iff start_in_perm_orbit subsetI)\n  have poz_in_C: \"?poz \\<in> ?C\" using assms by (rule perm_orbit_in_cycles_of_perm)\n  {\n    fix x assume \"x \\<in> ?C\"\n    then have \"z \\<notin> set_cycle x \\<Longrightarrow> x \\<in> ?C'\"\n      by (metis apply_cycle_cycles_of_perm apply_perm_neq_idI apply_skip_perm assms\n          cycles_imp_cycles_skip poz_in_C skip_def start_in_perm_orbit_iff)\n      also have x_orbit: \"z \\<in> set_cycle x \\<Longrightarrow> x = perm_orbit p z\"\n        using \\<open>x \\<in> ?C\\<close> perm_orbit_eqI by fastforce\n      have \"?poz \\<noteq> ?poz'\" \n        by (metis apply_cycle_delete apply_cycle_perm_orbit' apply_perm_neq_idI assms)\n      hence \"x \\<noteq> ?poz'\"\n          by (smt (verit, ccfv_SIG) poz_subset \\<open>x \\<in> ?C\\<close> x_orbit apply_perm_neq_idI cycles_funpow cycles_of_perm_def\n              funpow_apply_perm_in_perm_orbit_iff imageE in_mono start_in_perm_orbit calculation disj)\n      then show \"x \\<in> ?C' \\<union> {?poz} - {?poz'}\"\n        using x_orbit calculation by blast\n    }\n  fix x assume x_in: \"x \\<in> ?C' \\<union> {?poz} - {?poz'}\"    \n  also have \"?poz \\<in> ?C\"\n    using assms by (rule perm_orbit_in_cycles_of_perm)\n  moreover have \"x \\<noteq> ?poz' \\<Longrightarrow> x \\<in> ?C' \\<Longrightarrow> x \\<in> ?C\"\n    using cycles_skip_diff by fast\n  ultimately show \"x \\<in> ?C\" by fast\nqed\n\nsection \\<open>Permutation domain lemmas\\<close>\ncontext perm_on\nbegin\nlemma cycle_count_skip:\n  assumes \"finite S\" \"z \\<in> S\"\n  shows \"count_cycles_on S p = count_cycles_on (S - {z}) (skip_perm z p) + (if p z = z then 1 else 0)\"\nproof -\n  consider \"p z = z\" | \"p z \\<noteq> z \\<and> p (p z) = z\" | \"p (p z) \\<noteq> z\" by blast\nthen show ?thesis\nproof cases\n  case 1\n  have \"set_perm p = set_perm (skip_perm z p)\"\n    by (metis apply_perm_neq_idI 1 skip_perm_notin)\n  moreover have \"card (S - set_perm p) = Suc (card (S - {z} - set_perm (skip_perm z p)))\"\n    by (smt (z3) 1 Diff_eq_empty_iff Diff_insert2 One_nat_def Suc_pred add_Suc_right \n        add_diff_cancel_right' apply_perm_neq_idI assms calculation card_Diff_insert card_gt_0_iff \n        finite_Diff subsetD zero_less_Suc)\n  ultimately show ?thesis\n    by (smt (z3) \"1\" Nat.add_0_right add_Suc_right apply_perm_neq_idI count_cycles_on_def \n        perm_type_on_def size_replicate_mset One_nat_def size_union skip_perm_notin)\nnext\n  case 2\n  then have pz_id: \"skip_perm z p (p z) = p z\"\n    by (simp add: apply_skip_perm)\n  then have skip_z: \"delete_cycle z (perm_orbit p z) = id_cycle\"\n    by (simp add: remove1_cycle_orbit)\n  { have \"cycles_of_perm p = cycles_of_perm (skip_perm z p) \\<union> {perm_orbit p z}\n                              - {delete_cycle z (perm_orbit p z)}\"\n      by (meson \"2\" apply_perm_eq_idI cycles_skip)\n    then have \"cycles_of_perm p = cycles_of_perm (skip_perm z p) \\<union> {perm_orbit p z}\"\n        by (simp add: skip_z 2)\n    moreover have \"perm_orbit p z \\<notin> cycles_of_perm (skip_perm z p)\"\n        by (simp add: perm_orbit_notin_skip_perm)\n    ultimately have \"card (cycles_of_perm p) = card (cycles_of_perm (skip_perm z p)) + 1\"\n      by (simp add: finite_cycles_of_perm)\n  }\n  moreover {\n    have \"set_perm p = set_perm (skip_perm z p) \\<union> {z, p z}\"\n      by (meson 2 assms(1) set_perm_skip_2_cycle)\n    also have \"z \\<notin> set_perm (skip_perm z p)\"\n      by (simp add: apply_skip_perm in_set_perm)\n    moreover have \"p z \\<notin> set_perm (skip_perm z p)\"\n      using 2 \\<open>(skip_perm z p) (p z) = p z\\<close> by blast\n    ultimately have \"card (S - set_perm p) = card (S - {z} - set_perm (skip_perm z p)) - 1\"\n      by (smt (z3) Diff_iff Diff_insert2 Diff_insert_absorb Permutations.permutes_not_in \n          Un_insert_right apply_perm_eq_same_iff(1) apply_set_perm assms\n          boolean_algebra_cancel.sup0 card_Diff_insert permutes_p singletonD)\n    }\n  ultimately show ?thesis\n    apply (simp add: perm_on.count_cycles_on_eq_card perm_on.intro skip_perm_permutes permutes_p)\n    by (smt (verit, ccfv_threshold) \"2\" Diff_eq_empty_iff Diff_insert_absorb Suc_pred \n        apply_perm_in_iff apply_perm_neq_idI assms card_gt_0_iff finite_Diff\n        in_mono insertE mk_disjoint_insert pz_id set_perm_subset)\nnext\n  case 3\n  { then have \"set_perm p = set_perm (skip_perm z p) \\<union> {z}\"\n      by (metis set_perm_skip_n_cycle)\n    also have \"z \\<notin> set_perm (skip_perm z p)\"\n      by (simp add: apply_skip_perm in_set_perm)\n    ultimately have \"S - set_perm p = S - {z} - set_perm (skip_perm z p)\"\n      by (metis Diff_insert2 Un_insert_right boolean_algebra_cancel.sup0)\n  }\n  also have \"card (cycles_of_perm p) = card (cycles_of_perm (skip_perm z p))\"\n    by (smt (verit, ccfv_threshold) Diff_insert_absorb 3 Un_insert_right apply_set_perm \n        boolean_algebra_cancel.sup0 card.infinite card_0_eq card_Diff_insert card_insert_le \n        cycles_skip finite_cycles_of_perm insert_absorb insert_iff le_zero_eq\n        perm_orbit_in_cycles_of_perm perm_orbit_notin_skip_perm remove1_cycle_orbit\n        set_perm_skip_n_cycle)\n  ultimately show ?thesis\n    by (smt (z3) 3 add.right_neutral perm_on.count_cycles_on_eq_card \n        perm_on.intro permutes_p skip_perm_permutes)\nqed\nqed\n\nend\nend\n", "meta": {"author": "cplaursen", "repo": "isabelle-hypermap", "sha": "79606dedb7099c929994e12d72a9ee16aa578725", "save_path": "github-repos/isabelle/cplaursen-isabelle-hypermap", "path": "github-repos/isabelle/cplaursen-isabelle-hypermap/isabelle-hypermap-79606dedb7099c929994e12d72a9ee16aa578725/Skip.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8519528019683105, "lm_q1q2_score": 0.7672088745390622}}
{"text": "theory Ex2_4 \n  imports Main \nbegin \n  \ndatatype bdd = Leaf bool | Branch bdd bdd \n  \nprimrec eval :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> bdd \\<Rightarrow> bool\" where \n  \"eval _ _ (Leaf b) = b\"|\n  \"eval P n (Branch l r) = (if P n  then eval P (Suc n) l else eval P (Suc n) r)\"\n  \nprimrec bdd_unop :: \"(bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n  \"bdd_unop  f (Leaf b)=  (Leaf (f b))\"|\n  \"bdd_unop f (Branch l r) = Branch (bdd_unop f l) (bdd_unop f r)\"\n  \nfun bdd_binop :: \"(bool \\<Rightarrow> bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\" where \n  \"bdd_binop f (Leaf b) (Leaf b2) = (Leaf (f b b2))\"|\n  \"bdd_binop f (Leaf b) (Branch l r) =  Branch (bdd_binop f (Leaf b) l) (bdd_binop f (Leaf b) r)\"|\n  \"bdd_binop f (Branch l r) (Leaf b) = Branch (bdd_binop f l (Leaf b)) (bdd_binop f r (Leaf b))\"|\n  \"bdd_binop f (Branch l1 r1) (Branch l2 r2) = Branch (bdd_binop f l1 l2) (bdd_binop f r1 r2)\"\n  \ntheorem \"size (bdd_unop f bdd) = size bdd\" by (induction bdd, simp_all)\n    \ntheorem \"bdd_unop id bdd = bdd\" by (induction bdd, simp_all)\n\ntheorem main1 : \"\\<forall>i . eval f i (bdd_unop f2 bdd) = f2 (eval f i bdd)\" by (induction bdd ; simp)\n    \ntheorem main2: \"\\<forall> i . eval f i (bdd_binop f2 bdd1 bdd2) = f2 (eval f i bdd1) (eval f i bdd2)\"\nproof (rule allI)\n  fix i\n  show  \"eval f i (bdd_binop f2 bdd1 bdd2) = f2 (eval f i bdd1) (eval f i bdd2)\"\n  proof (induction bdd1 arbitrary  : i bdd2)\n    case (Leaf x)\n    then show ?case \n    proof (induction bdd2 arbitrary : i)\n      case (Leaf xx)\n      then show ?case by simp\n    next\n      case (Branch bdd21 bdd22)\n      then show ?case by simp\n    qed\n  next\n    case (Branch bdd11 bdd12)\n    assume hyp1:\"\\<And>i bdd2 . eval f i (bdd_binop f2 bdd11 bdd2) = f2 (eval f i bdd11) (eval f i bdd2)\"\n      and hyp2:\"\\<And> i bdd2 . eval f i (bdd_binop f2 bdd12 bdd2) = f2 (eval f i bdd12) (eval f i bdd2)\"\n    show ?case \n    proof (cases \"f i\")\n      case True\n        assume c1:\"f i\"\n      then show ?thesis \n      proof (cases bdd2)\n        case (Leaf x1)\n        assume c2:\"bdd2 = Leaf x1\"\n        have \"eval f i (bdd_binop f2 (Branch bdd11 bdd12) bdd2) = eval f (Suc i) (bdd_binop f2 bdd11 bdd2)\" using c1 c2 by simp\n        also have \"\\<dots> = f2 (eval f (Suc i) bdd11) (eval f (Suc i) bdd2)\" using hyp1 by simp\n        also have \"\\<dots> = f2 (eval f i (Branch bdd11 bdd12)) (eval f i bdd2)\" using c1 c2 by simp\n        finally show ?thesis by assumption\n      next\n        case (Branch x21 x22)\n        then show ?thesis using hyp1 c1 by simp\n      qed\n    next\n      case False\n      then show ?thesis using hyp1 hyp2 by (cases bdd2 , simp_all)\n    qed\n  qed\nqed\n  \ndefinition bdd_and :: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\" where \n  \"bdd_and bdd1 bdd2 = bdd_binop (op \\<and>) bdd1 bdd2\"\n  \ndefinition \"bdd_or =  bdd_binop op \\<or>\"\n \ndefinition \"bdd_not = bdd_unop (\\<lambda>x \\<Rightarrow> \\<not>x)\"\n  \ndefinition \"bdd_xor = bdd_binop  (\\<lambda> x y . (x \\<and> \\<not>y) \\<or> (\\<not>x \\<and> y))\"\n  \ntheorem lem1 : \"eval f i (bdd_and t1 t2) = (eval f i t1 \\<and> eval f i t2)\"\nproof - \n  have \"\\<forall> i . eval f i (bdd_binop op \\<and> t1 t2) = op \\<and> (eval f i t1) (eval f i t2)\" by (rule main2)\n  hence \"eval f i (bdd_binop op \\<and> t1 t2) = op \\<and> (eval f i t1) (eval f i t2)\" by (rule allE)\n  thus ?thesis using bdd_and_def by simp    \nqed\n  \ntheorem \"\\<forall>i .eval f i (bdd_or t1 t2) = (eval f i t1 \\<or> eval f i t2)\" using main2 by (simp add : bdd_or_def)\n\ndefinition bxor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"bxor a b = ((a \\<and> \\<not>b) \\<or> (\\<not>a \\<and> b))\" \n    \nnotation \n  bxor (infixl \"<*>\" 50)\n  \ntheorem lem2 : \"\\<forall>i .eval f i (bdd_xor t1 t2) = (eval f i t1 <*> eval f i t2)\" using main2 by (simp add : bdd_xor_def bxor_def)\n    \ntheorem \"\\<forall>i .eval f i (bdd_not t1) = (\\<not>(eval f i t1))\" using  main1 by (simp add : bdd_not_def)\n\nprimrec bdd_var :: \"nat \\<Rightarrow> bdd\" where\n  \"bdd_var 0 = Branch (Leaf True) (Leaf False)\"|\n  \"bdd_var (Suc n) = Branch (bdd_var n) (bdd_var n)\"\n\ntheorem \"\\<forall>i . eval f i (bdd_var n) = f (i + n)\" by (induction n; simp)\n\n    \ndatatype form = T | Var nat | And form form | Xor form form\n  \ndefinition \"xor = bxor\"\n  \nprimrec evalf :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\" where \n  \"evalf e T = True\"|\n  \"evalf e (Var i) = e i\"|\n  \"evalf e (And f1 f2) = (evalf e f1 \\<and> evalf e f2)\"|\n  \"evalf e (Xor f1 f2) =  ((evalf e f1) <*> (evalf e f2))\"\n  \nprimrec mk_bdd :: \"form \\<Rightarrow> bdd\" where \n  \"mk_bdd T = Leaf True\"|\n  \"mk_bdd (Var i) = bdd_var i\"|\n  \"mk_bdd (And f1 f2) =  bdd_and (mk_bdd f1) (mk_bdd f2)\"|\n  \"mk_bdd (Xor f1 f2) = bdd_xor (mk_bdd f1) (mk_bdd f2)\"\n  \nlemma helper1 : \"f x = evalf f (Var x)\" by (induction x, simp_all)\n    \nlemma helper2 : \"f (x + n) = eval f n (bdd_var x)\" \nproof (induction x arbitrary : n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc x)\n    assume hyp:\"\\<And>n . f (x + n) = eval f n (bdd_var x)\"\n    then show ?case using hyp[of \"Suc n\"] by (cases \"f (x + n)\"; cases \"f n\" ; simp)\nqed\n  \n\n  \ntheorem mk_bdd_correct : \"eval e 0 (mk_bdd f) = evalf e f\" \nproof (induction f)\n  case T\n  then show ?case by simp\nnext\n  case (Var x)\n  then show ?case \n  proof (induction x)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc x)\n    assume hyp:\"eval e 0 (mk_bdd (Var x)) = evalf e (Var x)\"\n    then show ?case using helper1 helper2 by simp\n  qed\nnext\n  case (And f1 f2)\n  assume hyp1:\"eval e 0 (mk_bdd f1) = evalf e f1\"\n    and hyp2:\"eval e 0 (mk_bdd f2) = evalf e f2\"\n  have \"eval e 0 (mk_bdd (And f1 f2))  = eval e 0 (bdd_and (mk_bdd f1) (mk_bdd f2))\" by simp\n  also have \"\\<dots> = (eval e 0 (mk_bdd f1) \\<and> eval e 0 (mk_bdd f2))\" using lem1 by simp\n  finally show ?case using hyp1 hyp2 by simp\nnext\n  case (Xor f1 f2)\n  then show ?case using lem2 by simp\nqed\n  ", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/2. Trees and other inductive data types/Ex2_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.8519527963298947, "lm_q1q2_score": 0.7672088694615009}}
{"text": "theory Part_2 imports Main\n\nbegin\n\n(* 4.2 *)\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\npempty: \"palindrome []\" |\npsingle: \"palindrome [x]\" |\nplist: \"palindrome xs \\<Longrightarrow> palindrome (a # (xs @ [a]))\"\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply(induction rule: palindrome.induct)\n    apply(auto)\n  done\n\n(* 4.3 *)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n  \nlemma [simp] : \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply(induction rule: star'.induct)\n   apply(auto intro: refl' step')\n  done\n\ntheorem star_star' : \"star r x y \\<Longrightarrow> star' r x y\"\n  apply(induction rule: star.induct)\n   apply(auto simp add: refl')\n  done\n\n(* 4.4 *)\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nit0: \"iter r 0 x x\" |\nitSS: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma star_imp_iter : \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\n  apply(induction rule: star.induct)\n   apply(auto intro: it0 itSS)\n  done\n\n(* 4.5 *)\n\ndatatype alpha = a | b (* a == '(', b == ')' *)\n\n(* \nGrammar for balanced parentheses S\n  S \\<rightarrow> \\<epsilon> | aSb | SS\n*)\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS0: \"S []\" |\nS1: \"S w \\<Longrightarrow> S (a # w @ [b])\" (*S [a,b,a,b] \\<rightarrow> S [a,b] \\<rightarrow> S [] \\<rightarrow> true *) |\nS2: \"S w \\<Longrightarrow> S x \\<Longrightarrow> S (w @ x)\" (* S [a,b,a,b] \\<rightarrow> S [a,b] \\<and> S [a,b] \\<rightarrow> true *)\n\n(* \nSecond grammar for balanced parentheses T\n  T \\<rightarrow> \\<epsilon> | TaTb \n*)\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nT0: \"T []\" |\nT1: \"T w \\<Longrightarrow> T x \\<Longrightarrow> T (w @ [a] @ x @ [b])\"\n\nlemma TS : \"T w \\<Longrightarrow> S w\"\n  apply(induction rule: T.induct)\n   apply(auto intro: S0 S1 S2)\n  done\n\nlemma ST : \"S w \\<Longrightarrow> T w\"\nproof (induction rule: S.induct)\n  case S0\n  thus ?case by (simp add: T0)\nnext\n  case S1\n  thus ?case using T1 by blast\nnext\n  case S2\n  thus ?case using T1 by blast\nqed\n\ncorollary SeqT: \"S w \\<longleftrightarrow> T w\"\n  apply(auto intro: ST TS)\n  done\n\n(* 4.6 *)\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N c) s = c\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus c d) s = aval c s + aval d s\"\n\ninductive rel_aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nConstN: \"rel_aval (N c) s c\" |\nValV: \"rel_aval (V x) s (s x)\" |\nPlusX: \"rel_aval p s x \\<Longrightarrow> rel_aval q s y \\<Longrightarrow> rel_aval (Plus p q) s (x + y)\"\n\nlemma aval_rel_aval: \"rel_aval c s v \\<Longrightarrow> aval c s = v\"\n  apply(induction rule: rel_aval.induct)\n    apply(auto)\n  done\n  \n\nlemma aval_aval_rel: \"aval c s = v \\<Longrightarrow> rel_aval c s v\"\n  apply(induction c arbitrary: v)\n    apply(auto intro: ConstN ValV PlusX)\n  done\n\ncorollary \"rel_aval c s v \\<longleftrightarrow> aval c s = v\"\n  apply(auto intro: aval_rel_aval aval_aval_rel)\n  done\n\n(* 4.7 *)\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec1 (LOADI n) _ stk = Some (n # stk)\" |\n\"exec1 ADD _ [] = None\" |\n\"exec1 ADD _ [c] = None\" |\n\"exec1 (LOAD x) s stk = Some (s(x) # stk)\" |\n\"exec1 ADD _ (j # i # stk) = Some ((i + j) # stk)\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec [] _ stk = Some stk\" |\n\"exec (i#is) s stk = (case (exec1 i s stk) of\n                      Some c \\<Rightarrow> exec is s c |\n                      None \\<Rightarrow> None)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x ) = [LOAD x ]\" |\n\"comp (Plus e\\<^sub>1 e\\<^sub>2) = comp e\\<^sub>1 @ comp e\\<^sub>2 @ [ADD]\"\n\nlemma [simp] : \"exec is\\<^sub>1 s stk = Some c \\<Longrightarrow> exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s c\"\n  apply(induction is\\<^sub>1 arbitrary: stk)\n   apply(auto simp add: option.split)\n  apply (metis option.case_eq_if option.simps(3))\n  done\n\nlemma \"exec (comp c) s stk = Some (aval c s # stk)\"\n  apply(induction c arbitrary: stk)\n    apply(auto)\n  done\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\nokBase : \"ok n [] n\" |\nok1 : \"ok n is n' \\<Longrightarrow> ok n (is @ [LOADI k]) (Suc n')\" |\nok2 : \"ok n is n' \\<Longrightarrow> ok n (is @ [LOAD x]) (Suc n')\" |\nok3 : \"ok n is (Suc (Suc n')) \\<Longrightarrow> ok n (is @ [ADD]) (Suc n')\"\n\nlemma \"ok 0 [LOAD k] (Suc 0)\"\n  apply (induction k)\n   apply (metis append_self_conv2 ok.simps)\n  apply (metis append_eq_Cons_conv ok.simps ok2)\n  done\n\nlemma \"ok 0 [LOAD x, LOADI v, ADD] (Suc 0)\"\n  apply(induction x)\n  apply(induction v)\n    apply (metis append.left_neutral append_Cons ok1 ok2 ok3 okBase)\n   apply (metis append.left_neutral append_Cons ok.simps okBase)\n  apply (metis append.left_neutral append_Cons ok1 ok2 ok3 okBase)\n  done\n\nlemma \"ok (Suc (Suc 0)) [LOAD x, ADD, ADD, LOAD y] (Suc (Suc 0))\"\n  using ok.cases by force\n\nlemma \"\\<lbrakk> ok n is n'; length stk = n; exec is s stk = Some c \\<rbrakk> \\<Longrightarrow> length c = n'\"\n  using ok.cases by force", "meta": {"author": "joshua-morris", "repo": "concrete-semantics", "sha": "a6621e2d7b55b7a6965ed17a21befc93cd9dd298", "save_path": "github-repos/isabelle/joshua-morris-concrete-semantics", "path": "github-repos/isabelle/joshua-morris-concrete-semantics/concrete-semantics-a6621e2d7b55b7a6965ed17a21befc93cd9dd298/chapter-4/Part_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225518, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7671274073275842}}
{"text": "chapter \\<open>Addition, Sequences and their Concatenation\\<close>\n\ntheory OrdArith imports Rank\nbegin\n\nsection \\<open>Generalised Addition --- Also for Ordinals\\<close>\ntext \\<open>Source: Laurence Kirby, Addition and multiplication of sets\n      Math. Log. Quart. 53, No. 1, 52-65 (2007) / DOI 10.1002/malq.200610026\n      @{url \"http://faculty.baruch.cuny.edu/lkirby/mlqarticlejan2007.pdf\"}\\<close>\n\ndefinition\n  hadd      :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"           (infixl \"@+\" 65)  where\n    \"hadd x \\<equiv> hmemrec (\\<lambda>f z. x \\<squnion> RepFun z f)\"\n\nlemma hadd: \"x @+ y = x \\<squnion> RepFun y (\\<lambda>z. x @+ z)\"\n  by (metis def_hmemrec RepFun_ecut hadd_def order_refl)\n\nlemma hmem_hadd_E:\n  assumes l: \"l \\<^bold>\\<in> x @+ y\"\n  obtains \"l \\<^bold>\\<in> x\" | z where \"z \\<^bold>\\<in> y\" \"l = x @+ z\"\n  using l\n  by (auto simp: hadd [of x y])\n\nlemma hadd_0_right [simp]: \"x @+ 0 = x\"\n  by (subst hadd) simp\n\nlemma hadd_hinsert_right: \"x @+ hinsert y z = hinsert (x @+ y) (x @+ z)\"\n  by (metis hadd hunion_hinsert_right RepFun_hinsert)\n\nlemma hadd_succ_right [simp]: \"x @+ succ y = succ (x @+ y)\"\n  by (metis hadd_hinsert_right succ_def)\n\nlemma not_add_less_right: \"\\<not> (x @+ y < x)\"\n  apply (induct y, auto)\n  apply (metis less_supI1 hadd order_less_le)\n  done\n\nlemma not_add_mem_right: \"\\<not> (x @+ y \\<^bold>\\<in> x)\"\n  by (metis hadd hmem_not_refl hunion_iff)\n\nlemma hadd_0_left [simp]: \"0 @+ x = x\"\n  by (induct x) (auto simp: hadd_hinsert_right)\n\nlemma hadd_succ_left [simp]: \"Ord y \\<Longrightarrow> succ x @+ y = succ (x @+ y)\"\n  by (induct y rule: Ord_induct2) auto\n\nlemma hadd_assoc: \"(x @+ y) @+ z = x @+ (y @+ z)\"\n  by (induct z) (auto simp: hadd_hinsert_right)\n\nlemma RepFun_hadd_disjoint: \"x \\<sqinter> RepFun y ((@+) x) = 0\"\n  by (metis hf_equalityI RepFun_iff hinter_iff not_add_mem_right hmem_hempty)\n\n\nsubsection \\<open>Cancellation laws for addition\\<close>\n\nlemma Rep_le_Cancel: \"x \\<squnion> RepFun y ((@+) x) \\<le> x \\<squnion> RepFun z ((@+) x)\n                      \\<Longrightarrow> RepFun y ((@+) x) \\<le> RepFun z ((@+) x)\"\n  by (auto simp add: not_add_mem_right)\n\nlemma hadd_cancel_right [simp]: \"x @+ y = x @+ z \\<longleftrightarrow> y=z\"\nproof (induct y arbitrary: z rule: hmem_induct)\n  case (step y z) show ?case\n  proof auto\n    assume eq: \"x @+ y = x @+ z\"\n    hence  \"RepFun y ((@+) x) = RepFun z ((@+) x)\"\n      by (metis hadd Rep_le_Cancel order_antisym order_refl)\n    thus  \"y = z\"\n      by (metis hf_equalityI RepFun_iff step)\n  qed\nqed\n\nlemma RepFun_hadd_cancel: \"RepFun y (\\<lambda>z. x @+ z) = RepFun z (\\<lambda>z. x @+ z) \\<longleftrightarrow> y=z\"\n  by (metis hadd hadd_cancel_right)\n\nlemma hadd_hmem_cancel [simp]: \"x @+ y \\<^bold>\\<in> x @+ z \\<longleftrightarrow> y \\<^bold>\\<in> z\"\n  apply (auto simp: hadd [of _ y] hadd [of _ z] not_add_mem_right)\n  apply (metis hmem_not_refl hunion_iff)\n  apply (metis hadd hadd_cancel_right)\n  done\n\nlemma ord_of_add: \"ord_of (i+j) = ord_of i @+ ord_of j\"\n  by (induct j) auto\n\nlemma Ord_hadd: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> Ord (x @+ y)\"\n  by (induct x rule: Ord_induct2) auto\n\nlemma hmem_self_hadd [simp]: \"k1 \\<^bold>\\<in> k1 @+ k2 \\<longleftrightarrow> 0 \\<^bold>\\<in> k2\"\n  by (metis hadd_0_right hadd_hmem_cancel)\n\nlemma hadd_commute: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> x @+ y = y @+ x\"\n  by (induct x rule: Ord_induct2) auto\n\nlemma hadd_cancel_left [simp]: \"Ord x \\<Longrightarrow> y @+ x = z @+ x \\<longleftrightarrow> y=z\"\n  by (induct x rule: Ord_induct2) auto\n\n\nsubsection \\<open>The predecessor function\\<close>\n\ndefinition pred :: \"hf \\<Rightarrow> hf\"\n  where \"pred x \\<equiv> (THE y. succ y = x \\<or> x=0 \\<and> y=0)\"\n\nlemma pred_succ [simp]: \"pred (succ x) = x\"\n  by (simp add: pred_def)\n\nlemma pred_0 [simp]: \"pred 0 = 0\"\n  by (simp add: pred_def)\n\nlemma succ_pred [simp]: \"Ord x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> succ (pred x) = x\"\n  by (metis Ord_cases pred_succ)\n\nlemma pred_mem [simp]: \"Ord x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> pred x \\<^bold>\\<in> x\"\n  by (metis succ_iff succ_pred)\n\nlemma Ord_pred [simp]: \"Ord x \\<Longrightarrow> Ord (pred x)\"\n  by (metis Ord_in_Ord pred_0 pred_mem)\n\nlemma hadd_pred_right: \"Ord y \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> x @+ pred y = pred (x @+ y)\"\n  by (metis hadd_succ_right pred_succ succ_pred)\n\nlemma Ord_pred_HUnion: \"Ord(k) \\<Longrightarrow> pred k = \\<Squnion>k\"\n  by (metis HUnion_hempty Ordinal.Ord_pred pred_0 pred_succ)\n\n\nsection \\<open>A Concatentation Operation for Sequences\\<close>\n\ndefinition shift :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"shift f delta = \\<lbrace>v . u \\<^bold>\\<in> f, \\<exists>n y. u = \\<langle>n, y\\<rangle> \\<and> v = \\<langle>delta @+ n, y\\<rangle>\\<rbrace>\"\n\nlemma shiftD: \"x \\<^bold>\\<in> shift f delta \\<Longrightarrow> \\<exists>u. u \\<^bold>\\<in> f \\<and> x = \\<langle>delta @+ hfst u, hsnd u\\<rangle>\"\n  by (auto simp: shift_def hsplit_def)\n\nlemma hmem_shift_iff: \"\\<langle>m, y\\<rangle> \\<^bold>\\<in> shift f delta \\<longleftrightarrow> (\\<exists>n. m = delta @+ n \\<and> \\<langle>n, y\\<rangle> \\<^bold>\\<in> f)\"\n  by (auto simp: shift_def hrelation_def is_hpair_def)\n\nlemma hmem_shift_add_iff [simp]: \"\\<langle>delta @+ n, y\\<rangle> \\<^bold>\\<in> shift f delta \\<longleftrightarrow> \\<langle>n, y\\<rangle> \\<^bold>\\<in> f\"\n  by (metis hadd_cancel_right hmem_shift_iff)\n\nlemma hrelation_shift [simp]: \"hrelation (shift f delta)\"\n  by (auto simp: shift_def hrelation_def hsplit_def)\n\nlemma app_shift [simp]: \"app (shift f k) (k @+ j) = app f j\"\n  by (simp add: app_def)\n\nlemma hfunction_shift_iff [simp]: \"hfunction (shift f delta) = hfunction f\"\n  by (auto simp: hfunction_def hmem_shift_iff)\n\nlemma hdomain_shift_add: \"hdomain (shift f delta) = \\<lbrace>delta @+ n . n \\<^bold>\\<in> hdomain f\\<rbrace>\"\n  by  (rule hf_equalityI) (force simp add: hdomain_def hmem_shift_iff)\n\n\n\ndefinition seq_append :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"seq_append k f g \\<equiv> hrestrict f k \\<squnion> shift g k\"\n\nlemma hrelation_seq_append [simp]: \"hrelation (seq_append k f g)\"\n  by (simp add: seq_append_def)\n\nlemma Seq_append: \"Seq s1 k1 \\<Longrightarrow> Seq s2 k2 \\<Longrightarrow> Seq (seq_append k1 s1 s2) (k1 @+ k2)\"\n  apply (auto simp: Seq_def seq_append_def)\n  apply (metis hdomain_restr hdomain_shift_disjoint hfunction_hunion hfunction_restr hfunction_shift_iff inf_absorb2 seq_append_def)\n  apply (simp add: hdomain_shift_add)\n  apply (metis hmem_hadd_E rev_hsubsetD)\n  apply (erule hmem_hadd_E, assumption, auto)\n  apply (metis Seq_def Seq_iff_app hdomainI hmem_shift_add_iff)\n  done\n\nlemma app_hunion1: \"x \\<^bold>\\<notin> hdomain g \\<Longrightarrow> app (f \\<squnion> g) x = app f x\"\n  by (auto simp: app_def) (metis hdomainI)\n\nlemma app_hunion2: \"x \\<^bold>\\<notin> hdomain f \\<Longrightarrow> app (f \\<squnion> g) x = app g x\"\n  by (auto simp: app_def) (metis hdomainI)\n\nlemma Seq_append_app1: \"Seq s k \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> app (seq_append k s s') l = app s l\"\n  apply (auto simp: Seq_def seq_append_def)\n  apply (metis app_hunion1 hdomain_shift_disjoint hemptyE hinter_iff app_hrestrict)\n  done\n\nlemma Seq_append_app2: \"Seq s1 k1 \\<Longrightarrow> Seq s2 k2 \\<Longrightarrow> l = k1 @+ j \\<Longrightarrow> app (seq_append k1 s1 s2) l = app s2 j\"\n  by (metis seq_append_def app_hunion2 app_shift hdomain_restr hinter_iff not_add_mem_right)\n\n\nsection \\<open>Nonempty sequences indexed by ordinals\\<close>\n\ndefinition OrdDom where\n \"OrdDom r \\<equiv> \\<forall>x y. \\<langle>x,y\\<rangle> \\<^bold>\\<in> r \\<longrightarrow> Ord x\"\n\nlemma OrdDom_insf: \"\\<lbrakk>OrdDom s; Ord k\\<rbrakk> \\<Longrightarrow> OrdDom (insf s (succ k) y)\"\n  by (auto simp: insf_def OrdDom_def)\n\nlemma OrdDom_hunion [simp]: \"OrdDom (s1 \\<squnion> s2) \\<longleftrightarrow> OrdDom s1 \\<and> OrdDom s2\"\n  by (auto simp: OrdDom_def)\n\nlemma OrdDom_hrestrict: \"OrdDom s \\<Longrightarrow> OrdDom (hrestrict s A)\"\n  by (auto simp: OrdDom_def)\n\nlemma OrdDom_shift: \"\\<lbrakk>OrdDom s; Ord k\\<rbrakk> \\<Longrightarrow> OrdDom (shift s k)\"\n  by (auto simp: OrdDom_def shift_def Ord_hadd)\n\n\ntext \\<open>A sequence of positive length ending with @{term y}\\<close>\ndefinition LstSeq :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"LstSeq s k y \\<equiv> Seq s (succ k) \\<and> Ord k \\<and> \\<langle>k,y\\<rangle> \\<^bold>\\<in> s \\<and> OrdDom s\"\n\n\n\nlemma LstSeq_imp_Seq_same: \"LstSeq s k y \\<Longrightarrow> Seq s k\"\n  by (metis LstSeq_imp_Seq_succ Seq_succ_D)\n\nlemma LstSeq_imp_Ord: \"LstSeq s k y \\<Longrightarrow> Ord k\"\n  by (metis LstSeq_def)\n\nlemma LstSeq_trunc: \"LstSeq s k y \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> LstSeq s l (app s l)\"\n  apply (auto simp: LstSeq_def Seq_iff_app)\n  apply (metis Ord_succ Seq_Ord_D mem_succ_iff)\n  apply (metis Ord_in_Ord)\n  done\n\nlemma LstSeq_insf: \"LstSeq s k z \\<Longrightarrow> LstSeq (insf s (succ k) y) (succ k) y\"\n  by (metis OrdDom_insf LstSeq_def Ord_succ_iff Seq_imp_eq_app Seq_insf Seq_succ_iff app_insf_Seq)\n\nlemma app_insf_LstSeq: \"LstSeq s k z \\<Longrightarrow> app (insf s (succ k) y) (succ k) = y\"\n  by (metis LstSeq_imp_Seq_succ app_insf_Seq)\n\nlemma app_insf2_LstSeq: \"LstSeq s k z \\<Longrightarrow> k' \\<noteq> succ k \\<Longrightarrow> app (insf s (succ k) y) k' = app s k'\"\n  by (metis LstSeq_imp_Seq_succ app_insf2_Seq)\n\nlemma app_insf_LstSeq_if: \"LstSeq s k z \\<Longrightarrow> app (insf s (succ k) y) k' = (if k' = succ k then y else app s k')\"\n  by (metis app_insf2_LstSeq app_insf_LstSeq)\n\nlemma LstSeq_append_app1:\n  \"LstSeq s k y \\<Longrightarrow> l \\<^bold>\\<in> succ k \\<Longrightarrow> app (seq_append (succ k) s s') l = app s l\"\n  by (metis LstSeq_imp_Seq_succ Seq_append_app1)\n\nlemma LstSeq_append_app2:\n  \"\\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2; l = succ k1 @+ j\\<rbrakk>\n   \\<Longrightarrow> app (seq_append (succ k1) s1 s2) l = app s2 j\"\n   by (metis LstSeq_imp_Seq_succ Seq_append_app2)\n\nlemma Seq_append_pair:\n  \"\\<lbrakk>Seq s1 k1; Seq s2 (succ n);  \\<langle>n, y\\<rangle> \\<^bold>\\<in> s2; Ord n\\<rbrakk> \\<Longrightarrow> \\<langle>k1 @+ n, y\\<rangle> \\<^bold>\\<in> (seq_append k1 s1 s2)\"\n  by (metis hmem_shift_add_iff hunion_iff seq_append_def)\n\nlemma Seq_append_OrdDom: \"\\<lbrakk>Ord k; OrdDom s1; OrdDom s2\\<rbrakk> \\<Longrightarrow> OrdDom (seq_append k s1 s2)\"\n  by (auto simp: seq_append_def OrdDom_hrestrict OrdDom_shift)\n\nlemma LstSeq_append:\n  \"\\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2\\<rbrakk> \\<Longrightarrow> LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n  apply (auto simp: LstSeq_def Seq_append Ord_hadd Seq_append_pair)\n  apply (metis Seq_append hadd_succ_left hadd_succ_right)\n  apply (metis Seq_append_pair hadd_succ_left)\n  apply (metis Ord_succ Seq_append_OrdDom)\n  done\n\nlemma LstSeq_app [simp]: \"LstSeq s k y \\<Longrightarrow> app s k = y\"\n  by (metis LstSeq_def Seq_imp_eq_app)\n\n\nsubsection \\<open>Sequence-building operators\\<close>\n\ndefinition Builds :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"Builds B C s l \\<equiv> B (app s l) \\<or> (\\<exists>m \\<^bold>\\<in> l. \\<exists>n \\<^bold>\\<in> l. C (app s l) (app s m) (app s n))\"\n\ndefinition BuildSeq :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"BuildSeq B C s k y \\<equiv> LstSeq s k y \\<and> (\\<forall>l \\<^bold>\\<in> succ k. Builds B C s l)\"\n\nlemma BuildSeqI: \"LstSeq s k y \\<Longrightarrow> (\\<And>l. l \\<^bold>\\<in> succ k \\<Longrightarrow> Builds B C s l) \\<Longrightarrow> BuildSeq B C s k y\"\n  by (simp add: BuildSeq_def)\n\nlemma BuildSeq_imp_LstSeq: \"BuildSeq B C s k y \\<Longrightarrow> LstSeq s k y\"\n  by (metis BuildSeq_def)\n\nlemma BuildSeq_imp_Seq: \"BuildSeq B C s k y \\<Longrightarrow> Seq s (succ k)\"\n  by (metis LstSeq_imp_Seq_succ BuildSeq_imp_LstSeq)\n\nlemma BuildSeq_conj_distrib:\n \"BuildSeq (\\<lambda>x. B x \\<and> P x) (\\<lambda>x y z. C x y z \\<and> P x) s k y \\<longleftrightarrow>\n  BuildSeq B C s k y \\<and> (\\<forall>l \\<^bold>\\<in> succ k. P (app s l))\"\n  by (auto simp: BuildSeq_def Builds_def)\n\nlemma BuildSeq_mono:\n  assumes y: \"BuildSeq B C s k y\"\n      and B: \"\\<And>x. B x \\<Longrightarrow> B' x\" and C: \"\\<And>x y z. C x y z \\<Longrightarrow> C' x y z\"\n  shows \"BuildSeq B' C' s k y\"\nusing y\n  by (auto simp: BuildSeq_def Builds_def intro!: B C)\n\nlemma BuildSeq_trunc:\n  assumes b: \"BuildSeq B C s k y\"\n      and l: \"l \\<^bold>\\<in> k\"\n  shows \"BuildSeq B C s l (app s l)\"\nproof -\n  { fix j\n    assume j: \"j \\<^bold>\\<in> succ l\"\n    have k: \"Ord k\"\n      by (metis BuildSeq_imp_LstSeq LstSeq_def b)\n    hence \"Builds B C s j\"\n      by (metis BuildSeq_def OrdmemD b hballE hsubsetD j l succ_iff)\n }\n thus ?thesis using b l\n  by (auto simp: BuildSeq_def LstSeq_trunc)\nqed\n\n\nsubsection \\<open>Showing that Sequences can be Constructed\\<close>\n\nlemma Builds_insf: \"Builds B C s l \\<Longrightarrow> LstSeq s k z \\<Longrightarrow> l \\<^bold>\\<in> succ k \\<Longrightarrow> Builds B C (insf s (succ k) y) l\"\nby (auto simp: HBall_def hmem_not_refl Builds_def app_insf_LstSeq_if simp del: succ_iff)\n   (metis hmem_not_sym)\n\nlemma BuildSeq_insf:\n  assumes b: \"BuildSeq B C s k z\"\n      and m: \"m \\<^bold>\\<in> succ k\"\n      and n: \"n \\<^bold>\\<in> succ k\"\n      and y: \"B y \\<or> C y (app s m) (app s n)\"\nshows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\nproof (rule BuildSeqI)\n  show \"LstSeq (insf s (succ k) y) (succ k) y\"\n  by (metis BuildSeq_imp_LstSeq LstSeq_insf b)\nnext\n  fix l\n  assume l: \"l \\<^bold>\\<in> succ (succ k)\"\n  thus \"Builds B C (insf s (succ k) y) l\"\n  proof\n    assume l: \"l = succ k\"\n    have \"B (app (insf s l y) l) \\<or> C (app (insf s l y) l) (app (insf s l y) m) (app (insf s l y) n)\"\n      by (metis BuildSeq_imp_Seq app_insf_Seq_if b hmem_not_refl l m n y)\n    thus \"Builds B C (insf s (succ k) y) l\" using m n\n      by (auto simp: Builds_def l)\n  next\n    assume l: \"l \\<^bold>\\<in> succ k\"\n    have  \"LstSeq s k z\"\n      by (metis BuildSeq_imp_LstSeq b)\n    thus \"Builds B C (insf s (succ k) y) l\" using b l\n      by (metis hballE Builds_insf BuildSeq_def)\n  qed\nqed\n\nlemma BuildSeq_insf1:\n  assumes b: \"BuildSeq B C s k z\"\n      and y: \"B y\"\n  shows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\nby (metis BuildSeq_insf b succ_iff y)\n\nlemma BuildSeq_insf2:\n  assumes b: \"BuildSeq B C s k z\"\n      and m: \"m \\<^bold>\\<in> k\"\n      and n: \"n \\<^bold>\\<in> k\"\n      and y: \"C y (app s m) (app s n)\"\n  shows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\n  by (metis BuildSeq_insf b m n succ_iff y)\n\nlemma BuildSeq_append:\n  assumes s1: \"BuildSeq B C s1 k1 y1\" and s2: \"BuildSeq B C s2 k2 y2\"\n  shows \"BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\nproof (rule BuildSeqI)\n  show \"LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n    using assms\n    by (metis BuildSeq_imp_LstSeq LstSeq_append)\nnext\n  fix l\n  have s1L: \"LstSeq s1 k1 y1\"\n   and s1BC: \"\\<And>l. l \\<^bold>\\<in> succ k1 \\<Longrightarrow> Builds B C s1 l\"\n   and s2L: \"LstSeq s2 k2 y2\"\n   and s2BC: \"\\<And>l. l \\<^bold>\\<in> succ k2 \\<Longrightarrow> Builds B C s2 l\"\n    using s1 s2 by (auto simp: BuildSeq_def)\n  assume l: \"l \\<^bold>\\<in> succ (succ (k1 @+ k2))\"\n  hence  \"l \\<^bold>\\<in> succ k1 @+ succ k2\"\n    by (metis LstSeq_imp_Ord hadd_succ_left hadd_succ_right s2L)\n  thus \"Builds B C (seq_append (succ k1) s1 s2) l\"\n  proof (rule hmem_hadd_E)\n    assume l1: \"l \\<^bold>\\<in> succ k1\"\n    hence \"B (app s1 l) \\<or> (\\<exists>m\\<^bold>\\<in>l. \\<exists>n\\<^bold>\\<in>l. C (app s1 l) (app s1 m) (app s1 n))\" using s1BC\n      by (simp add: Builds_def)\n    thus ?thesis\n    proof\n      assume \"B (app s1 l)\"\n      thus ?thesis\n        by (metis Builds_def LstSeq_append_app1 l1 s1L)\n    next\n      assume \"\\<exists>m\\<^bold>\\<in>l. \\<exists>n\\<^bold>\\<in>l. C (app s1 l) (app s1 m) (app s1 n)\"\n      then obtain m n where mn: \"m \\<^bold>\\<in> l\" \"n \\<^bold>\\<in> l\" and C: \"C (app s1 l) (app s1 m) (app s1 n)\"\n        by blast\n      also have \"m \\<^bold>\\<in> succ k1\" \"n \\<^bold>\\<in> succ k1\"\n        by (metis LstSeq_def Ord_trans l1 mn s1L succ_iff)+\n      ultimately have \"C (app (seq_append (succ k1) s1 s2) l)\n                         (app (seq_append (succ k1) s1 s2) m)\n                         (app (seq_append (succ k1) s1 s2) n)\"\n        using s1L l1\n        by (simp add: LstSeq_append_app1)\n      thus \"Builds B C (seq_append (succ k1) s1 s2) l\" using mn\n        by (auto simp: Builds_def)\n    qed\n  next\n    fix z\n    assume z: \"z \\<^bold>\\<in> succ k2\" and l2: \"l = succ k1 @+ z\"\n    hence \"B (app s2 z) \\<or> (\\<exists>m\\<^bold>\\<in>z. \\<exists>n\\<^bold>\\<in>z. C (app s2 z) (app s2 m) (app s2 n))\" using s2BC\n      by (simp add: Builds_def)\n    thus ?thesis\n    proof\n      assume \"B (app s2 z)\"\n      thus ?thesis\n        by (metis Builds_def LstSeq_append_app2 l2 s1L s2L)\n    next\n      assume \"\\<exists>m\\<^bold>\\<in>z. \\<exists>n\\<^bold>\\<in>z. C (app s2 z) (app s2 m) (app s2 n)\"\n      then obtain m n where mn: \"m \\<^bold>\\<in> z\" \"n \\<^bold>\\<in> z\" and C: \"C (app s2 z) (app s2 m) (app s2 n)\"\n        by blast\n      also have \"m \\<^bold>\\<in> succ k2\" \"n \\<^bold>\\<in> succ k2\" using mn\n        by (metis LstSeq_def Ord_trans z s2L succ_iff)+\n      ultimately have \"C (app (seq_append (succ k1) s1 s2) l)\n                         (app (seq_append (succ k1) s1 s2) (succ k1 @+ m))\n                         (app (seq_append (succ k1) s1 s2) (succ k1 @+ n))\"\n        using s1L s2L l2 z\n        by (simp add: LstSeq_append_app2)\n      thus \"Builds B C (seq_append (succ k1) s1 s2) l\" using mn l2\n        by (auto simp: Builds_def HBall_def)\n    qed\n  qed\nqed\n\nlemma BuildSeq_combine:\n  assumes b1: \"BuildSeq B C s1 k1 y1\" and b2: \"BuildSeq B C s2 k2 y2\"\n      and y: \"C y y1 y2\"\n  shows \"BuildSeq B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) y) (succ (succ (k1 @+ k2))) y\"\nproof -\n  have k2: \"Ord k2\"  using b2\n    by (auto simp: BuildSeq_def LstSeq_def)\n  show ?thesis\n  proof (rule BuildSeq_insf [where m=k1 and n=\"succ(k1@+k2)\"])\n    show \"BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n      by (rule BuildSeq_append [OF b1 b2])\n  next\n    show \"k1 \\<^bold>\\<in> succ (succ (k1 @+ k2))\" using k2\n      by (metis hadd_0_right hmem_0_Ord hmem_self_hadd succ_iff)\n  next\n    show \"succ (k1 @+ k2) \\<^bold>\\<in> succ (succ (k1 @+ k2))\"\n      by (metis succ_iff)\n  next\n    have [simp]: \"app (seq_append (succ k1) s1 s2) k1 = y1\"\n      by (metis b1 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app1 succ_iff)\n    have [simp]: \"app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) = y2\"\n      by (metis b1 b2 k2 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app2 hadd_succ_left)\n    show \"B y \\<or>\n          C y (app (seq_append (succ k1) s1 s2) k1)\n              (app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)))\"\n      using y by simp\n  qed\nqed\n\nlemma LstSeq_1: \"LstSeq \\<lbrace>\\<langle>0, y\\<rangle>\\<rbrace> 0 y\"\n by (auto simp: LstSeq_def One_hf_eq_succ Seq_ins OrdDom_def)\n\nlemma BuildSeq_1: \"B y \\<Longrightarrow> BuildSeq B C \\<lbrace>\\<langle>0, y\\<rangle>\\<rbrace> 0 y\"\n  by (auto simp: BuildSeq_def Builds_def LstSeq_1)\n\nlemma BuildSeq_exI: \"B t \\<Longrightarrow> \\<exists>s k. BuildSeq B C s k t\"\n  by (metis BuildSeq_1)\n\n\nsubsection \\<open>Proving Properties of Given Sequences\\<close>\n\n\n\nlemma BuildSeq_induct [consumes 1, case_names B C]:\n  assumes major: \"BuildSeq B C s k a\"\n      and B: \"\\<And>x. B x \\<Longrightarrow> P x\"\n      and C: \"\\<And>x y z. C x y z \\<Longrightarrow> P y \\<Longrightarrow> P z \\<Longrightarrow> P x\"\n  shows \"P a\"\nproof -\n  have \"Ord k\" using assms\n    by (auto simp: BuildSeq_def LstSeq_def)\n  hence \"\\<And>a s. BuildSeq B C s k a \\<Longrightarrow> P a\"\n    by (induction k rule: Ord_induct) (metis BuildSeq_trunc BuildSeq_succ_E B C)\n  thus ?thesis\n    by (metis major)\nqed\n\ndefinition BuildSeq2 :: \"[[hf,hf] \\<Rightarrow> bool, [hf,hf,hf,hf,hf,hf] \\<Rightarrow> bool, hf, hf, hf, hf] \\<Rightarrow> bool\"\n  where \"BuildSeq2 B C s k y y' \\<equiv>\n         BuildSeq (\\<lambda>p. \\<exists>x x'. p = \\<langle>x,x'\\<rangle> \\<and> B x x')\n                  (\\<lambda>p q r. \\<exists>x x' y y' z z'. p = \\<langle>x,x'\\<rangle> \\<and> q = \\<langle>y,y'\\<rangle> \\<and> r = \\<langle>z,z'\\<rangle> \\<and> C x x' y y' z z')\n                  s k \\<langle>y,y'\\<rangle>\"\n\nlemma BuildSeq2_combine:\n  assumes b1: \"BuildSeq2 B C s1 k1 y1 y1'\" and b2: \"BuildSeq2 B C s2 k2 y2 y2'\"\n      and y: \"C y y' y1 y1' y2 y2'\"\n  shows \"BuildSeq2 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \\<langle>y, y'\\<rangle>)\n                       (succ (succ (k1 @+ k2))) y y'\"\n  using assms\n  apply (unfold BuildSeq2_def)\n  apply (blast intro: BuildSeq_combine)\n  done\n\nlemma BuildSeq2_1: \"B y y' \\<Longrightarrow> BuildSeq2 B C \\<lbrace>\\<langle>0, y, y'\\<rangle>\\<rbrace> 0 y y'\"\n  by (auto simp: BuildSeq2_def BuildSeq_1)\n\n\n\nlemma BuildSeq2_induct [consumes 1, case_names B C]:\n  assumes \"BuildSeq2 B C s k a a'\"\n      and B: \"\\<And>x x'. B x x' \\<Longrightarrow> P x x'\"\n      and C: \"\\<And>x x' y y' z z'. C x x' y y' z z' \\<Longrightarrow> P y y' \\<Longrightarrow> P z z' \\<Longrightarrow> P x x'\"\n  shows \"P a a'\"\nusing assms\napply (simp add: BuildSeq2_def)\napply (drule BuildSeq_induct [where P = \"\\<lambda>\\<langle>x,x'\\<rangle>. P x x'\"])\napply (auto intro: B C)\ndone\n\ndefinition BuildSeq3\n   :: \"[[hf,hf,hf] \\<Rightarrow> bool, [hf,hf,hf,hf,hf,hf,hf,hf,hf] \\<Rightarrow> bool, hf, hf, hf, hf, hf] \\<Rightarrow> bool\"\n  where \"BuildSeq3 B C s k y y' y'' \\<equiv>\n         BuildSeq (\\<lambda>p. \\<exists>x x' x''. p = \\<langle>x,x',x''\\<rangle> \\<and> B x x' x'')\n                  (\\<lambda>p q r. \\<exists>x x' x'' y y' y'' z z' z''.\n                           p = \\<langle>x,x',x''\\<rangle> \\<and> q = \\<langle>y,y',y''\\<rangle> \\<and> r = \\<langle>z,z',z''\\<rangle> \\<and>\n                           C x x' x'' y y' y'' z z' z'')\n                  s k \\<langle>y,y',y''\\<rangle>\"\n\nlemma BuildSeq3_combine:\n  assumes b1: \"BuildSeq3 B C s1 k1 y1 y1' y1''\" and b2: \"BuildSeq3 B C s2 k2 y2 y2' y2''\"\n      and y: \"C y y' y'' y1 y1' y1'' y2 y2' y2''\"\n  shows \"BuildSeq3 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \\<langle>y, y', y''\\<rangle>)\n                       (succ (succ (k1 @+ k2))) y y' y''\"\n  using assms\n  apply (unfold BuildSeq3_def)\n  apply (blast intro: BuildSeq_combine)\n  done\n\nlemma BuildSeq3_1: \"B y y' y'' \\<Longrightarrow> BuildSeq3 B C \\<lbrace>\\<langle>0, y, y', y''\\<rangle>\\<rbrace> 0 y y' y''\"\n  by (auto simp: BuildSeq3_def BuildSeq_1)\n\nlemma BuildSeq3_exI: \"B t t' t'' \\<Longrightarrow> \\<exists>s k. BuildSeq3 B C s k t t' t''\"\n  by (metis BuildSeq3_1)\n\nlemma BuildSeq3_induct [consumes 1, case_names B C]:\n  assumes \"BuildSeq3 B C s k a a' a''\"\n      and B: \"\\<And>x x' x''. B x x' x'' \\<Longrightarrow> P x x' x''\"\n      and C: \"\\<And>x x' x'' y y' y'' z z' z''. C x x' x'' y y' y'' z z' z'' \\<Longrightarrow> P y y' y'' \\<Longrightarrow> P z z' z'' \\<Longrightarrow> P x x' x''\"\n  shows \"P a a' a''\"\nusing assms\napply (simp add: BuildSeq3_def)\napply (drule BuildSeq_induct [where P = \"\\<lambda>\\<langle>x,x',x''\\<rangle>. P x x' x''\"])\napply (auto intro: B C)\ndone\n\n\nsection \\<open>A Unique Predecessor for every non-empty set\\<close>\n\nlemma Rep_hf_0 [simp]: \"Rep_hf 0 = 0\"\n  by (metis Abs_hf_inverse HF.HF_def UNIV_I Zero_hf_def image_empty set_encode_empty)\n\nlemma hmem_imp_less: \"x \\<^bold>\\<in> y \\<Longrightarrow> Rep_hf x < Rep_hf y\"\napply (auto simp: hmem_def hfset_def set_decode_def Abs_hf_inverse)\napply (metis div_less even_zero le_less_trans less_two_power not_less)\ndone\n\nlemma hsubset_imp_le: \"x \\<le> y \\<Longrightarrow> Rep_hf x \\<le> Rep_hf y\"\n  apply (auto simp: less_eq_hf_def hmem_def hfset_def Abs_hf_inverse)\n  apply (cases x rule: Abs_hf_cases)\n  apply (cases y rule: Abs_hf_cases, auto)\n  apply (rule subset_decode_imp_le)\n  apply (auto simp: Abs_hf_inverse [OF UNIV_I])\n  apply (metis Abs_hf_inverse UNIV_I imageE imageI)\n  done\n\nlemma diff_hmem_imp_less: assumes \"x \\<^bold>\\<in> y\" shows \"Rep_hf (y - \\<lbrace>x\\<rbrace>) < Rep_hf y\"\nproof -\n  have  \"Rep_hf (y - \\<lbrace>x\\<rbrace>) \\<le> Rep_hf y\"\n    by (metis hdiff_iff hsubsetI hsubset_imp_le)\n  moreover\n  have \"Rep_hf (y - \\<lbrace>x\\<rbrace>) \\<noteq> Rep_hf y\" using assms\n    by (metis Rep_hf_inject hdiff_iff hinsert_iff)\n  ultimately show ?thesis\n    by (metis le_neq_implies_less)\nqed\n\ndefinition least :: \"hf \\<Rightarrow> hf\"\n  where \"least a \\<equiv> (THE x. x \\<^bold>\\<in> a \\<and> (\\<forall>y. y \\<^bold>\\<in> a \\<longrightarrow> Rep_hf x \\<le> Rep_hf y))\"\n\nlemma least_equality:\n  assumes \"x \\<^bold>\\<in> a\" and \"\\<And>y. y \\<^bold>\\<in> a \\<Longrightarrow> Rep_hf x \\<le> Rep_hf y\"\n  shows \"least a = x\"\nunfolding least_def\napply (rule the_equality)\napply (metis assms)\napply (metis Rep_hf_inverse assms eq_iff)\ndone\n\n\n\nlemma nonempty_imp_ex_least: \"a \\<noteq> 0 \\<Longrightarrow> \\<exists>x. x \\<^bold>\\<in> a \\<and> (\\<forall>y. y \\<^bold>\\<in> a \\<longrightarrow> Rep_hf x \\<le> Rep_hf y)\"\nproof (induction a rule: hf_induct)\n  case 0 thus ?case by simp\nnext\n  case (hinsert u v)\n  show ?case\n    proof (cases \"v=0\")\n     case True thus ?thesis\n       by (rule_tac x=u in exI, simp)\n    next\n      case False\n      thus ?thesis\n        by (metis dual_order.trans eq_iff hinsert.IH(2) hmem_hinsert\n                  less_eq_insert1_iff linear)\n    qed\nqed\n\nlemma least_hmem: \"a \\<noteq> 0 \\<Longrightarrow> least a \\<^bold>\\<in> a\"\napply (frule nonempty_imp_ex_least, clarify)\napply (rule leastI2_order, auto)\ndone\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/HereditarilyFinite/OrdArith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.8479677545357569, "lm_q1q2_score": 0.7671144828890731}}
{"text": "(*\n  File: Group_Sort.thy\n  Author: Manuel Eberl <manuel@pruvisto.org>\n\n  A sorting algorithm that sorts values according to a key function and groups equivalent \n  elements using a commutative and associative binary operation.\n*)\nsection \\<open>Sorting and grouping factors\\<close>\n\ntheory Group_Sort\nimports Main \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>\n  For the reification of products of powers of primitive functions such as\n  @{term \"\\<lambda>x. x * ln x ^2\"} into a canonical form, we need to be able to sort the factors \n  according to the growth of the primitive function it contains and merge terms with the same \n  function by adding their exponents. The following locale defines such an operation in a \n  general setting; we can then instantiate it for our setting.\n\n  The locale takes as parameters a key function @{term \"f\"} that sends list elements into a \n  linear ordering that determines the sorting order, a @{term \"merge\"} function to merge to \n  equivalent (w.r.t. @{term \"f\"}) elements into one, and a list reduction function @{term \"g\"} \n  that reduces a list to a single value. This function must be invariant w.r.t. the order of \n  list elements and be compatible with merging of equivalent elements. In our case, this list \n  reduction function will be the product of all list elements.\n\\<close>\n\nlocale groupsort = \n  fixes f :: \"'a \\<Rightarrow> ('b::linorder)\"\n  fixes merge :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  fixes g :: \"'a list \\<Rightarrow> 'c\"\n  assumes f_merge: \"f x = f y \\<Longrightarrow> f (merge x y) = f x\"\n  assumes g_cong: \"mset xs = mset ys \\<Longrightarrow> g xs = g ys\"\n  assumes g_merge: \"f x = f y \\<Longrightarrow> g [x,y] = g [merge x y]\"\n  assumes g_append_cong: \"g xs1 = g xs2 \\<Longrightarrow> g ys1 = g ys2 \\<Longrightarrow> g (xs1 @ ys1) = g (xs2 @ ys2)\"\nbegin\n\ncontext\nbegin\n\nprivate function part_aux :: \n  \"'b \\<Rightarrow> 'a list \\<Rightarrow> ('a list) \\<times> ('a list) \\<times> ('a list) \\<Rightarrow> ('a list) \\<times> ('a list) \\<times> ('a list)\" \nwhere\n  \"part_aux p [] (ls, eq, gs) = (ls, eq, gs)\"\n| \"f x < p \\<Longrightarrow> part_aux p (x#xs) (ls, eq, gs) = part_aux p xs (x#ls, eq, gs)\"\n| \"f x > p \\<Longrightarrow> part_aux p (x#xs) (ls, eq, gs) = part_aux p xs (ls, eq, x#gs)\"\n| \"f x = p \\<Longrightarrow> part_aux p (x#xs) (ls, eq, gs) = part_aux p xs (ls, eq@[x], gs)\"\nproof (clarify, goal_cases)\n  case prems: (1 P p xs ls eq gs)\n  show ?case\n  proof (cases xs)\n    fix x xs' assume \"xs = x # xs'\"\n    thus ?thesis using prems by (cases \"f x\" p rule: linorder_cases) auto\n  qed (auto intro: prems(1))\nqed simp_all\ntermination by (relation \"Wellfounded.measure (size \\<circ> fst \\<circ> snd)\") simp_all\n\nprivate lemma groupsort_locale: \"groupsort f merge g\" by unfold_locales\n\nprivate lemmas part_aux_induct = part_aux.induct[split_format (complete), OF groupsort_locale]\n\nprivate definition part where \"part p xs = part_aux (f p) xs ([], [p], [])\"\n\nprivate lemma part: \n  \"part p xs = (rev (filter (\\<lambda>x. f x < f p) xs), \n     p # filter (\\<lambda>x. f x = f p) xs, rev (filter (\\<lambda>x. f x > f p) xs))\"\nproof-\n  {\n    fix p xs ls eq gs\n    have \"fst (part_aux p xs (ls, eq, gs)) = rev (filter (\\<lambda>x. f x < p) xs) @ ls\"\n      by (induction p xs ls eq gs rule: part_aux_induct) simp_all\n  } note A = this\n  {\n    fix p xs ls eq gs\n    have \"snd (snd (part_aux p xs (ls, eq, gs))) = rev (filter (\\<lambda>x. f x > p) xs) @ gs\"\n      by (induction p xs ls eq gs rule: part_aux_induct) simp_all\n  } note B = this\n  {\n    fix p xs ls eq gs\n    have \"fst (snd (part_aux p xs (ls, eq, gs))) = eq @ filter (\\<lambda>x. f x = p) xs\"\n      by (induction p xs ls eq gs rule: part_aux_induct) auto\n  } note C = this\n  note ABC = A B C\n  from ABC[of \"f p\" xs \"[]\" \"[p]\" \"[]\"] show ?thesis unfolding part_def\n    by (intro prod_eqI) simp_all\nqed\n\nprivate function sort :: \"'a list \\<Rightarrow> 'a list\" where\n  \"sort [] = []\"\n| \"sort (x#xs) = (case part x xs of (ls, eq, gs) \\<Rightarrow> sort ls @ eq @ sort gs)\"\nby pat_completeness simp_all\ntermination by (relation \"Wellfounded.measure length\") (simp_all add: part less_Suc_eq_le)\n\nprivate lemma filter_mset_union:\n  assumes \"\\<And>x. x \\<in># A \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> False\"\n  shows \"filter_mset P A + filter_mset Q A = filter_mset (\\<lambda>x. P x \\<or> Q x) A\" (is \"?lhs = ?rhs\")\n  using assms by (auto simp add: count_eq_zero_iff intro!: multiset_eqI) blast\n\nprivate lemma multiset_of_sort: \"mset (sort xs) = mset xs\"\nproof (induction xs rule: sort.induct)\n  case (2 x xs)\n  let ?M = \"\\<lambda>oper. {#y:# mset xs. oper (f y) (f x)#}\"\n  from 2 have \"mset (sort (x#xs)) = ?M (<) + ?M (=) + ?M (>) + {#x#}\"\n    by (simp add: part Multiset.union_assoc mset_filter)\n  also have \"?M (<) + ?M (=) + ?M (>) = mset xs\"\n    by ((subst filter_mset_union, force)+, subst multiset_eq_iff, force)\n  finally show ?case by simp\nqed simp\n\nprivate lemma g_sort: \"g (sort xs) = g xs\"\n  by (intro g_cong multiset_of_sort)\n\nprivate lemma set_sort: \"set (sort xs) = set xs\"\n  using arg_cong[OF multiset_of_sort[of xs], of \"set_mset\"] by (simp only: set_mset_mset)\n\nprivate \n\nprivate lemma sorted_sort: \"sorted (map f (sort xs))\"\napply (induction xs rule: sort.induct)\napply simp\napply (simp only: sorted_append sort.simps part map_append split)\napply (intro conjI TrueI)\nusing sorted_map_same by (auto simp: set_sort)\n\n\n\nprivate fun group where\n  \"group [] = []\"\n| \"group (x#xs) = (case partition (\\<lambda>y. f y = f x) xs of (xs', xs'') \\<Rightarrow> \n                     fold merge xs' x # group xs'')\"\n\nprivate lemma f_fold_merge: \"(\\<And>y. y \\<in> set xs \\<Longrightarrow> f y = f x) \\<Longrightarrow> f (fold merge xs x) = f x\"\n  by (induction xs rule: rev_induct) (auto simp: f_merge)\n\nprivate lemma f_group: \"x \\<in> set (group xs) \\<Longrightarrow> \\<exists>x'\\<in>set xs. f x = f x'\"\nproof (induction xs rule: group.induct)\n  case (2 x' xs)\n  hence \"x = fold merge [y\\<leftarrow>xs . f y = f x'] x' \\<or> x \\<in> set (group [xa\\<leftarrow>xs . f xa \\<noteq> f x'])\"\n    by (auto simp: o_def)\n  thus ?case\n  proof\n    assume \"x = fold merge [y\\<leftarrow>xs . f y = f x'] x'\"\n    also have \"f ... = f x'\" by (rule f_fold_merge) simp\n    finally show ?thesis by simp\n  next\n    assume \"x \\<in> set (group [xa\\<leftarrow>xs . f xa \\<noteq> f x'])\"\n    from 2(1)[OF _ this] have \"\\<exists>x'\\<in>set [xa\\<leftarrow>xs . f xa \\<noteq> f x']. f x = f x'\" by (simp add: o_def)\n    thus ?thesis by force\n  qed\nqed simp\n\nprivate lemma sorted_group: \"sorted (map f xs) \\<Longrightarrow> sorted (map f (group xs))\"\nproof (induction xs rule: group.induct)\n  case (2 x xs)\n  {\n    fix x' assume x': \"x' \\<in> set (group [y\\<leftarrow>xs . f y \\<noteq> f x])\"\n    with f_group obtain x'' where x'': \"x'' \\<in> set xs\" \"f x' = f x''\" by force\n    have \"f (fold merge [y\\<leftarrow>xs . f y = f x] x) = f x\"\n      by (subst f_fold_merge) simp_all\n    also from 2(2) x'' have \"... \\<le> f x'\" by (auto) \n    finally have \"f (fold merge [y\\<leftarrow>xs . f y = f x] x) \\<le> f x'\" .\n  }\n  moreover from 2(2) have \"sorted (map f (group [xa\\<leftarrow>xs . f xa \\<noteq> f x]))\"\n    by (intro 2 sorted_filter) (simp_all add: o_def)\n  ultimately show ?case by (simp add: o_def)\nqed simp_all\n\nprivate lemma distinct_group: \"distinct (map f (group xs))\"\nproof (induction xs rule: group.induct)\n  case (2 x xs)\n  have \"distinct (map f (group [xa\\<leftarrow>xs . f xa \\<noteq> f x]))\" by (intro 2) (simp_all add: o_def)\n  moreover have \"f (fold merge [y\\<leftarrow>xs . f y = f x] x) \\<notin> set (map f (group [xa\\<leftarrow>xs . f xa \\<noteq> f x]))\"\n    by (rule notI, subst (asm) f_fold_merge) (auto dest: f_group)\n  ultimately show ?case by (simp add: o_def)\nqed simp\n\nprivate lemma g_fold_same:\n  assumes \"\\<And>z. z \\<in> set xs \\<Longrightarrow> f z = f x\"\n  shows   \"g (fold merge xs x # ys) = g (x#xs@ys)\"\nusing assms\nproof (induction xs arbitrary: x)\n  case (Cons y xs)\n  have \"g (x # y # xs @ ys) = g (y # x # xs @ ys)\" by (intro g_cong) (auto simp: add_ac)\n  also have \"y # x # xs @ ys = [y,x] @ xs @ ys\" by simp\n  also from Cons.prems have \"g ... = g ([merge y x] @ xs @ ys)\" \n    by (intro g_append_cong g_merge) auto\n  also have \"[merge y x] @ xs @ ys = merge y x # xs @ ys\" by simp\n  also from Cons.prems have \"g ... = g (fold merge xs (merge y x) # ys)\"\n    by (intro Cons.IH[symmetric]) (auto simp: f_merge)\n  also have \"... = g (fold merge (y # xs) x # ys)\" by simp\n  finally show ?case by simp\nqed simp\n\nprivate lemma g_group: \"g (group xs) = g xs\"\nproof (induction xs rule: group.induct)\n  case (2 x xs)\n  have \"g (group (x#xs)) = g (fold merge [y\\<leftarrow>xs . f y = f x] x # group [xa\\<leftarrow>xs . f xa \\<noteq> f x])\"\n    by (simp add: o_def)\n  also have \"... = g (x # [y\\<leftarrow>xs . f y = f x] @ group [y\\<leftarrow>xs . f y \\<noteq> f x])\"\n    by (intro g_fold_same) simp_all\n  also have \"... = g ((x # [y\\<leftarrow>xs . f y = f x]) @ group [y\\<leftarrow>xs . f y \\<noteq> f x])\" (is \"_ = ?A\") by simp\n  also from 2 have \"g (group [y\\<leftarrow>xs . f y \\<noteq> f x]) = g [y\\<leftarrow>xs . f y \\<noteq> f x]\" by (simp add: o_def)\n  hence \"?A = g ((x # [y\\<leftarrow>xs . f y = f x]) @ [y\\<leftarrow>xs . f y \\<noteq> f x])\"\n    by (intro g_append_cong) simp_all\n  also have \"... = g (x#xs)\" by (intro g_cong) (simp_all)\n  finally show ?case .\nqed simp\n\n\nfunction group_part_aux :: \n  \"'b \\<Rightarrow> 'a list \\<Rightarrow> ('a list) \\<times> 'a \\<times> ('a list) \\<Rightarrow> ('a list) \\<times> 'a \\<times> ('a list)\" \nwhere\n  \"group_part_aux p [] (ls, eq, gs) = (ls, eq, gs)\"\n| \"f x < p \\<Longrightarrow> group_part_aux p (x#xs) (ls, eq, gs) = group_part_aux p xs (x#ls, eq, gs)\"\n| \"f x > p \\<Longrightarrow> group_part_aux p (x#xs) (ls, eq, gs) = group_part_aux p xs (ls, eq, x#gs)\"\n| \"f x = p \\<Longrightarrow> group_part_aux p (x#xs) (ls, eq, gs) = group_part_aux p xs (ls, merge x eq, gs)\"\nproof (clarify, goal_cases)\n  case prems: (1 P p xs ls eq gs)\n  show ?case\n  proof (cases xs)\n    fix x xs' assume \"xs = x # xs'\"\n    thus ?thesis using prems by (cases \"f x\" p rule: linorder_cases) auto\n  qed (auto intro: prems(1))\nqed simp_all\ntermination by (relation \"Wellfounded.measure (size \\<circ> fst \\<circ> snd)\") simp_all\n\nprivate lemmas group_part_aux_induct = \n  group_part_aux.induct[split_format (complete), OF groupsort_locale]\n\ndefinition group_part where \"group_part p xs = group_part_aux (f p) xs ([], p, [])\"\n\nprivate lemma group_part: \n  \"group_part p xs = (rev (filter (\\<lambda>x. f x < f p) xs), \n     fold merge (filter (\\<lambda>x. f x = f p) xs) p, rev (filter (\\<lambda>x. f x > f p) xs))\"\nproof-\n  {\n    fix p xs ls eq gs\n    have \"fst (group_part_aux p xs (ls, eq, gs)) = rev (filter (\\<lambda>x. f x < p) xs) @ ls\"\n      by (induction p xs ls eq gs rule: group_part_aux_induct) simp_all\n  } note A = this\n  {\n    fix p xs ls eq gs\n    have \"snd (snd (group_part_aux p xs (ls, eq, gs))) = rev (filter (\\<lambda>x. f x > p) xs) @ gs\"\n      by (induction p xs ls eq gs rule: group_part_aux_induct) simp_all\n  } note B = this\n  {\n    fix p xs ls eq gs\n    have \"fst (snd (group_part_aux p xs (ls, eq, gs))) = \n            fold merge (filter (\\<lambda>x. f x = p) xs) eq\"\n      by (induction p xs ls eq gs rule: group_part_aux_induct) auto\n  } note C = this\n  note ABC = A B C\n  from ABC[of \"f p\" xs \"[]\" \"p\" \"[]\"] show ?thesis unfolding group_part_def\n    by (intro prod_eqI) simp_all\nqed\n\n\nfunction group_sort :: \"'a list \\<Rightarrow> 'a list\" where\n  \"group_sort [] = []\"\n| \"group_sort (x#xs) = (case group_part x xs of (ls, eq, gs) \\<Rightarrow> group_sort ls @ eq # group_sort gs)\"\nby pat_completeness simp_all\ntermination by (relation \"Wellfounded.measure length\") (simp_all add: group_part less_Suc_eq_le)\n\nprivate lemma group_append:\n  assumes \"\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> f x \\<noteq> f y\"\n  shows   \"group (xs @ ys) = group xs @ group ys\"\nusing assms\nproof (induction xs arbitrary: ys rule: length_induct)\n  case (1 xs')\n  hence IH: \"\\<And>x xs ys. length xs < length xs' \\<Longrightarrow> (\\<And>x y. x \\<in> set xs \\<Longrightarrow> y \\<in> set ys \\<Longrightarrow> f x \\<noteq> f y)\n                \\<Longrightarrow> group (xs @ ys) = group xs @ group ys\" by blast\n  show ?case\n  proof (cases xs')\n    case (Cons x xs)\n    note [simp] = this\n    have \"group (xs' @ ys) = fold merge [y\\<leftarrow>xs@ys . f y = f x] x #\n            group ([xa\\<leftarrow>xs . f xa \\<noteq> f x] @ [xa\\<leftarrow>ys . f xa \\<noteq> f x])\" by (simp add: o_def)\n    also from 1(2) have \"[y\\<leftarrow>xs@ys . f y = f x] = [y\\<leftarrow>xs . f y = f x]\"\n      by (force simp: filter_empty_conv)\n    also from 1(2) have \"[xa\\<leftarrow>ys . f xa \\<noteq> f x] = ys\" by (force simp: filter_id_conv)\n    also have \"group ([xa\\<leftarrow>xs . f xa \\<noteq> f x] @ ys) =\n               group [xa\\<leftarrow>xs . f xa \\<noteq> f x] @ group ys\" using 1(2)\n      by (intro IH) (simp_all add: less_Suc_eq_le)\n    finally show ?thesis by (simp add: o_def)\n  qed simp\nqed\n\nprivate lemma group_empty_iff [simp]: \"group xs = [] \\<longleftrightarrow> xs = []\"\n  by (induction xs rule: group.induct) auto\n\nlemma group_sort_correct: \"group_sort xs = group (sort xs)\"\nproof (induction xs rule: group_sort.induct)\n  case (2 x xs)\n  have \"group_sort (x#xs) = \n          group_sort (rev [xa\\<leftarrow>xs . f xa < f x]) @ group (x#[xa\\<leftarrow>xs . f xa = f x]) @\n          group_sort (rev [xa\\<leftarrow>xs . f x < f xa])\" by (simp add: group_part)\n  also have \"group_sort (rev [xa\\<leftarrow>xs . f xa < f x]) = group (sort (rev [xa\\<leftarrow>xs . f xa < f x]))\"\n    by (rule 2) (simp_all add: group_part)\n  also have \"group_sort (rev [xa\\<leftarrow>xs . f xa > f x]) = group (sort (rev [xa\\<leftarrow>xs . f xa > f x]))\"\n    by (rule 2) (simp_all add: group_part)\n  also have \"group (x#[xa\\<leftarrow>xs . f xa = f x]) @ group (sort (rev [xa\\<leftarrow>xs . f xa > f x])) =\n             group ((x#[xa\\<leftarrow>xs . f xa = f x]) @ sort (rev [xa\\<leftarrow>xs . f xa > f x]))\"\n    by (intro group_append[symmetric]) (auto simp: set_sort)\n  also have \"group (sort (rev [xa\\<leftarrow>xs . f xa < f x])) @ ... = \n             group (sort (rev [xa\\<leftarrow>xs . f xa < f x]) @ (x#[xa\\<leftarrow>xs . f xa = f x]) @\n                 sort (rev [xa\\<leftarrow>xs . f xa > f x]))\"\n    by (intro group_append[symmetric]) (auto simp: set_sort)\n  also have \"sort (rev [xa\\<leftarrow>xs . f xa < f x]) @ (x#[xa\\<leftarrow>xs . f xa = f x]) @\n                 sort (rev [xa\\<leftarrow>xs . f xa > f x]) = sort (x # xs)\" by (simp add: part)\n  finally show ?case .\nqed simp\n\n\nlemma sorted_group_sort: \"sorted (map f (group_sort xs))\"\n  by (auto simp: group_sort_correct intro!: sorted_group sorted_sort)\n\n\n\nlemma g_group_sort: \"g (group_sort xs) = g xs\"\n  by (simp add: group_sort_correct g_group g_sort)\n\nlemmas [simp del] = group_sort.simps group_part_aux.simps\n\nend\nend\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Landau_Symbols/Group_Sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.8962513620489619, "lm_q1q2_score": 0.7670577495900572}}
{"text": "theory Chapter09_2_Typechecking\nimports Chapter09_1_Language\nbegin\n\ninductive typecheck :: \"type env => expr => type => bool\"\nwhere tc_var [simp]: \"lookup gam x = Some t ==> typecheck gam (Var x) t\"\n    | tc_zero [simp]: \"typecheck gam Zero Nat\"\n    | tc_suc [simp]: \"typecheck gam e Nat ==> typecheck gam (Suc e) Nat\"\n    | tc_rec [simp]: \"typecheck gam et Nat ==> typecheck gam e0 t ==> \n                typecheck (extend (extend gam t) Nat) es t ==> typecheck gam (Rec et e0 es) t\"\n    | tc_lam [simp]: \"typecheck (extend gam t1) e t2 ==> typecheck gam (Lam t1 e) (Arrow t1 t2)\"\n    | tc_appl [simp]: \"typecheck gam e1 (Arrow t2 t) ==> typecheck gam e2 t2 ==> \n                typecheck gam (Appl e1 e2) t\"\n\ninductive_cases [elim!]: \"typecheck gam (Var x) t\"\ninductive_cases [elim!]: \"typecheck gam Zero t\"\ninductive_cases [elim!]: \"typecheck gam (Suc e) t\"\ninductive_cases [elim!]: \"typecheck gam (Rec et e0 es) t\"\ninductive_cases [elim!]: \"typecheck gam (Lam t1 e) t\"\ninductive_cases [elim!]: \"typecheck gam (Appl e1 e2) t\"\n\n\n\nlemma [simp]: \"typecheck (extend_at n gam t') e t ==> n in gam ==> typecheck gam e' t' ==> \n                          typecheck gam (subst e' n e) t\"\nby (induction \"extend_at n gam t'\" e t arbitrary: n gam t' e' rule: typecheck.induct, fastforce+)\n\nend\n", "meta": {"author": "xtreme-james-cooper", "repo": "Harper", "sha": "ec2c52a05a5695cdaeb42bbcaa885aa55eac994f", "save_path": "github-repos/isabelle/xtreme-james-cooper-Harper", "path": "github-repos/isabelle/xtreme-james-cooper-Harper/Harper-ec2c52a05a5695cdaeb42bbcaa885aa55eac994f/isabelle/Chapter09_2_Typechecking.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7670544462227689}}
{"text": "theory HoareLogicTutorial\nimports Main \"~~/src/HOL/Hoare/Hoare_Logic\"\nbegin\n\n(* The minimum of two integers x and y: *)\nlemma Min: \"VARS (z :: int)\n {True}\n IF x \\<le> y THEN z := x ELSE z := y FI\n { z = min x y }\"\n  apply vcg\n  apply (simp add: min_def)\n  done\n\n\n\n\n(* Iteratively copy an integer variable x to y: *)\nlemma Copy: \"VARS (a :: int) y\n {0 \\<le> x}\n a := x; y := 0;\n WHILE a \\<noteq> 0\n INV { x=y+a } \n DO y := y + 1 ; a := a - 1 OD\n {x = y}\"\napply vcg_simp\ndone\n\n(* Multiplication *) \nlemma Multipl: \"VARS (z :: int) i\n{0 \\<le> y}\ni := y;\nz := 0;\nWHILE i \\<noteq> 0 \nINV { z = (y - i) * x }\nDO\n  z := z + x;\n  i := i - 1\nOD\n{z = x * y}\"\n  apply vcg\n  apply (auto simp add: algebra_simps)\n  done\n\n\n(* Iterative multiplication through addition: *)\nlemma Multi: \"VARS (a :: int) z\n {0 \\<le> y}\n a := 0; z := 0;\n WHILE a \\<noteq> y\n INV {z = x * a}\n DO \n   z := z + x ; \n   a := a + 1 \n OD\n {z = x * y}\"\n(* \"Replace Inv with your invariant.\" *)\n  apply vcg_simp\n  apply (erule conjE)\n  apply (simp add: distrib_left) \n  done\n\n\n\n(* A factorial algorithm: *)\nlemma DownFact: \"VARS (z :: nat) (y::nat)\n {True}\n z := x; y := 1;\n WHILE z > 0\n INV { Inv }\n DO \n   y := y * z; \n   z := z - 1 \n OD\n {y = fact x}\"\n(* \"Replace Inv with your invariant.\" *)\noops\n\n\n(* Integer division of x by y: *)\nlemma Div: \"VARS (r :: int) d \n {y \\<noteq> 0}\n r := x; d := 0;\n WHILE y \\<le> r\n INV { Inv }\n DO \n  r := r - y;\n  d := d + 1\n OD\n { Postcondition }\"\n(* \"Replace Inv with your invariant.\" *)\n(* \"Replace Postcondition with your postcondition.\" *)\noops\n\n\nend", "meta": {"author": "athiyadeviyani", "repo": "AR-Labs-and-Tutorials", "sha": "2870fcdb268ce650bc99315ce52923ab752c410f", "save_path": "github-repos/isabelle/athiyadeviyani-AR-Labs-and-Tutorials", "path": "github-repos/isabelle/athiyadeviyani-AR-Labs-and-Tutorials/AR-Labs-and-Tutorials-2870fcdb268ce650bc99315ce52923ab752c410f/HoareLogicTutorial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.7670224959477326}}
{"text": "theory Ex2_1\n  imports Main \nbegin \n  \n  \ndatatype 'a tree = Leaf (nval  :'a) | Node (nval : 'a) (lft : \"'a tree\") (rgt : \"'a tree\")\n  \nprimrec preOrder :: \"'a tree \\<Rightarrow> 'a list \" where \n  \"preOrder (Leaf val) = [val]\"|\n  \"preOrder (Node val lt rt) =  val # preOrder lt @ preOrder rt\"\n  \nprimrec postOrder :: \"'a tree \\<Rightarrow> 'a list\" where \n  \"postOrder (Leaf val) = [val]\"|\n  \"postOrder (Node val lt rt) = postOrder lt @ postOrder rt @ [val]\"\n  \nprimrec inOrder :: \"'a tree  \\<Rightarrow> 'a list\" where \n  \"inOrder (Leaf val) = [val]\"|\n  \"inOrder (Node val lt rt) = inOrder lt @ val # inOrder rt\"\n  \nprimrec mirror :: \"'a tree \\<Rightarrow> 'a tree\" where \n  \"mirror (Leaf val) = (Leaf val)\"|\n  \"mirror (Node val lt rt) = Node val (mirror rt) (mirror lt)\"\n  \n(*lemma \"preOrder (mirror xt) = rev (preOrder xt)\"  quickcheck *)\n  \nlemma \"let xt = Node (1::int) (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)  in preOrder (mirror xt) = rev (preOrder xt) \\<Longrightarrow> False\" by simp\n    \nlemma \"preOrder (mirror xt) = rev (postOrder xt)\"  \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Node x1a xt1 xt2)\n  assume hyp1:\" preOrder (mirror xt1) = rev (postOrder xt1)\"\n     and hyp2:\"preOrder (mirror xt2) = rev (postOrder xt2)\"\n  then show ?case by simp\nqed\n    \nlemma \"postOrder (mirror xt) = rev (preOrder xt)\" \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Node x1a xt1 xt2)\n  then show ?case by simp\nqed\n      \nlemma \"let xt =  Node (1::int) (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)   in preOrder (mirror xt) = rev (inOrder xt) \\<Longrightarrow> False\" by simp\n    \nlemma \"let xt =  Node (1::int) (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)   in inOrder (mirror xt) = rev (preOrder xt) \\<Longrightarrow> False\" by simp\n    \nlemma \"let xt =  Node (1::int) (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)   in postOrder (mirror xt) = rev (postOrder xt) \\<Longrightarrow> False\" by simp\n    \nlemma \"let xt =  Node (1::int) (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)   in postOrder (mirror xt) = rev (inOrder xt) \\<Longrightarrow> False\" by simp\n    \nlemma \"let xt =  Node (1::int) (Node 2 (Leaf 3) (Leaf 4)) (Leaf 5)   in inOrder (mirror xt) = rev (postOrder xt) \\<Longrightarrow> False\" by simp\n    \nlemma \"inOrder (mirror xt) = rev (inOrder xt)\" \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Node x1a xt1 xt2)\n  then show ?case by simp\nqed\n  \ndefinition root :: \"'a tree \\<Rightarrow> 'a\" where \n  \"root xt = nval xt\"\n  \nprimrec leftmost :: \"'a tree \\<Rightarrow> 'a\" where \n  \"leftmost (Leaf val) = val\"|\n  \"leftmost (Node _ lt _) = leftmost lt\"\n  \nprimrec rightmost :: \"'a tree \\<Rightarrow> 'a\" where \n  \"rightmost (Leaf val) = val\"|\n  \"rightmost (Node _ _ rt) = rightmost rt\"\n  \nlemma helper1 : \"length (inOrder xt) > 0\" \nproof (cases xt)\n  case (Leaf x1)\n  then show ?thesis  by simp\nnext\n  case (Node x21 x22 x23)\n  then show ?thesis by simp\nqed\n  \n  \n    \ntheorem \"last (inOrder xt) = rightmost xt\" \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Node x1a xt1 xt2)\n  assume hyp:\"last (inOrder xt2) = rightmost xt2\"\n  have \"last (inOrder (Node x1a xt1 xt2)) = last (inOrder xt1 @ x1a  #  inOrder xt2)\" by simp\n  also have \"\\<dots> = last (inOrder xt2)\" using helper1 by auto     \n  finally show ?case using hyp by auto\nqed\n  \nlemma helper2 : \"length xs > 0 \\<Longrightarrow> hd (xs @ ys) = hd xs\" by (induct xs, auto)  \n  \ntheorem \"hd (inOrder xt) = leftmost xt\" \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Node x1a xt1 xt2)\n  assume hyp:\"hd (inOrder xt1) = leftmost xt1\"\n  have \" hd (inOrder (Node x1a xt1 xt2)) = hd (inOrder xt1 @ x1a # inOrder xt2)\" by simp\n  also have \"\\<dots> = hd (inOrder xt1)\" using helper1 helper2 by auto\n  then show ?case using hyp by auto\nqed\n  \ntheorem \"hd (preOrder xt) = last (postOrder xt)\" \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by simp\nnext\n  case (Node x1a xt1 xt2)\n  then show ?case by simp\nqed\n  \ntheorem \"hd (preOrder xt)  = root xt\" \nproof (induct xt)\n  case (Leaf x)\n  then show ?case by (auto simp add : root_def)\nnext\n  case (Node x1a xt1 xt2)\n  then show ?case by (auto simp add: root_def) \nqed\n  \nlemma \"let xt = Node (1 :: int) (Leaf 2) (Leaf 3) in (hd (inOrder xt) = root xt) \\<Longrightarrow> False\" by (simp add : root_def)\n    \ntheorem \"last (postOrder xt) = root xt\" by (induct xt, auto simp add : root_def)\n  ", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/2. Trees and other inductive data types/Ex2_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8615382076534742, "lm_q1q2_score": 0.76702248684187}}
{"text": "(* Title:      Domain Semirings\n   Author:     Victor B. F. Gomes, Walter Guttmann, Peter Höfner, Georg Struth, Tjark Weber\n   Maintainer: Walter Guttmann <walter.guttman at canterbury.ac.nz>\n               Georg Struth <g.struth at sheffield.ac.uk>\n               Tjark Weber <tjark.weber at it.uu.se>\n*)\n\nsection \\<open>Domain Semirings\\<close>\n\ntheory Domain_Semiring\nimports Kleene_Algebra.Kleene_Algebra\n\nbegin\n\nsubsection \\<open>Domain Semigroups and Domain Monoids\\<close>\n\nclass domain_op =\n  fixes domain_op :: \"'a \\<Rightarrow> 'a\" (\"d\")\n\ntext \\<open>First we define the class of domain semigroups. Axioms are taken from~\\<^cite>\\<open>\"DesharnaisJipsenStruth\"\\<close>.\\<close>\n\nclass domain_semigroup = semigroup_mult + domain_op +\n  assumes dsg1 [simp]: \"d x \\<cdot> x = x\"\n  and dsg2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dsg3 [simp]: \"d (d x \\<cdot> y) = d x \\<cdot> d y\"\n  and dsg4: \"d x \\<cdot> d y = d y \\<cdot> d x\"\n\nbegin\n\nlemma domain_invol [simp]: \"d (d x) = d x\"\nproof -\n  have \"d (d x) = d (d (d x \\<cdot> x))\"\n    by simp\n  also have \"... = d (d x \\<cdot> d x)\"\n    using dsg3 by presburger\n  also have \"... = d (d x \\<cdot> x)\"\n    by simp\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>The next lemmas show that domain elements form semilattices.\\<close>\n\nlemma dom_el_idem [simp]: \"d x \\<cdot> d x = d x\"\nproof -\n  have \"d x \\<cdot> d x = d (d x \\<cdot> x)\"\n    using dsg3 by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma dom_mult_closed [simp]: \"d (d x \\<cdot> d y) = d x \\<cdot> d y\"\n  by simp\n\nlemma dom_lc3 [simp]: \"d x \\<cdot> d (x \\<cdot> y) = d (x \\<cdot> y)\"\nproof -\n  have \"d x \\<cdot> d (x \\<cdot> y) = d (d x \\<cdot> x \\<cdot> y)\"\n    using dsg3 mult_assoc by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma d_fixpoint: \"(\\<exists>y. x = d y) \\<longleftrightarrow> x = d x\"\n  by auto\n\nlemma d_type: \"\\<forall>P. (\\<forall>x. x = d x \\<longrightarrow> P x) \\<longleftrightarrow> (\\<forall>x. P (d x))\"\n  by (metis domain_invol)\n\ntext \\<open>We define the semilattice ordering on domain semigroups and explore the semilattice of domain elements from the order point of view.\\<close>\n\ndefinition ds_ord :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<sqsubseteq>\" 50) where\n  \"x \\<sqsubseteq> y \\<longleftrightarrow> x = d x \\<cdot> y\"\n\nlemma ds_ord_refl: \"x \\<sqsubseteq> x\"\n  by (simp add: ds_ord_def)\n\nlemma ds_ord_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\nproof -\n  assume \"x \\<sqsubseteq> y\" and a: \"y \\<sqsubseteq> z\"\n  hence b: \"x = d x \\<cdot> y\"\n    using ds_ord_def by blast\n  hence \"x = d x \\<cdot> d y \\<cdot> z\"\n    using a ds_ord_def mult_assoc by force\n  also have \"... = d (d x \\<cdot> y) \\<cdot> z\"\n    by simp\n  also have \"... = d x \\<cdot> z\"\n    using b by auto\n  finally show ?thesis\n    using ds_ord_def by blast\nqed\n\nlemma ds_ord_antisym: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nproof -\n  assume a: \"x \\<sqsubseteq> y\" and \"y \\<sqsubseteq> x\"\n  hence b: \"y = d y \\<cdot> x\"\n    using ds_ord_def by auto\n  have \"x = d x \\<cdot> d y \\<cdot> x\"\n    using a b ds_ord_def mult_assoc by force\n  also have \"... = d y \\<cdot> x\"\n    by (metis (full_types) b dsg3 dsg4)\n  thus ?thesis\n    using b calculation by presburger\nqed\n\ntext \\<open>This relation is indeed an order.\\<close>\n\nsublocale ds: ordering \\<open>(\\<sqsubseteq>)\\<close> \\<open>\\<lambda>x y. x \\<sqsubseteq> y \\<and> x \\<noteq> y\\<close>\nproof\n  show \\<open>x \\<sqsubseteq> y \\<and> x \\<noteq> y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> x \\<noteq> y\\<close> for x y\n    by (rule refl)\n  show \"x \\<sqsubseteq> x\" for x\n    by (rule ds_ord_refl)\n  show \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\" for x y z\n    by (rule ds_ord_trans)\n  show \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\" for x y\n    by (rule ds_ord_antisym)\nqed\n\ndeclare ds.refl [simp]\n\nlemma ds_ord_eq: \"x \\<sqsubseteq> d x \\<longleftrightarrow> x = d x\"\n  by (simp add: ds_ord_def)\n\nlemma \"x \\<sqsubseteq> y \\<Longrightarrow> z \\<cdot> x \\<sqsubseteq> z \\<cdot> y\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma ds_ord_iso_right: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<cdot> z \\<sqsubseteq> y \\<cdot> z\"\nproof -\n  assume \"x \\<sqsubseteq> y\"\n  hence a: \"x = d x \\<cdot> y\"\n    by (simp add: ds_ord_def)\n  hence \"x \\<cdot> z = d x \\<cdot> y \\<cdot> z\"\n    by auto\n  also have \"... = d (d x \\<cdot> y \\<cdot> z) \\<cdot> d x \\<cdot> y \\<cdot> z\"\n    using dsg1 mult_assoc by presburger\n  also have \"... = d (x \\<cdot> z) \\<cdot> d x \\<cdot> y \\<cdot> z\"\n    using a by presburger\n  finally show ?thesis\n    using ds_ord_def dsg4 mult_assoc by auto\nqed\n\ntext \\<open>The order on domain elements could as well be defined based on multiplication/meet.\\<close>\n\nlemma ds_ord_sl_ord: \"d x \\<sqsubseteq> d y \\<longleftrightarrow> d x \\<cdot> d y = d x\"\n  using ds_ord_def by auto\n\nlemma ds_ord_1: \"d (x \\<cdot> y) \\<sqsubseteq> d x\"\n  by (simp add: ds_ord_sl_ord dsg4)\n\nlemma ds_subid_aux: \"d x \\<cdot> y \\<sqsubseteq> y\"\n  by (simp add: ds_ord_def mult_assoc)\n\nlemma \"y \\<cdot> d x \\<sqsubseteq> y\"\n(*nitpick [expect=genuine]*)\noops\n\nlemma ds_dom_iso: \"x \\<sqsubseteq> y \\<Longrightarrow> d x \\<sqsubseteq> d y\"\nproof -\n  assume \"x \\<sqsubseteq> y\"\n  hence \"x = d x \\<cdot> y\"\n    by (simp add: ds_ord_def)\n  hence \"d x = d (d x \\<cdot> y)\"\n    by presburger\n  also have \"... = d x \\<cdot> d y\"\n    by simp\n  finally show ?thesis\n    using ds_ord_sl_ord by auto\nqed\n\nlemma ds_dom_llp: \"x \\<sqsubseteq> d y \\<cdot> x \\<longleftrightarrow> d x \\<sqsubseteq> d y\"\nproof\n  assume \"x \\<sqsubseteq> d y \\<cdot> x\"\n  hence \"x = d y \\<cdot> x\"\n    by (simp add: ds_subid_aux ds.antisym)\n  hence \"d x = d (d y \\<cdot> x)\"\n    by presburger\n  thus \"d x \\<sqsubseteq> d y\"\n    using ds_ord_sl_ord dsg4 by force\nnext\n  assume \"d x \\<sqsubseteq> d y\"\n  thus \"x \\<sqsubseteq> d y \\<cdot> x\"\n    by (metis (no_types) ds_ord_iso_right dsg1)\nqed\n\nlemma ds_dom_llp_strong: \"x = d y \\<cdot> x \\<longleftrightarrow> d x \\<sqsubseteq> d y\"\n  using ds.eq_iff\n  by (simp add: ds_dom_llp ds.eq_iff ds_subid_aux)\n\ndefinition refines :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"refines x y \\<equiv> d y \\<sqsubseteq> d x \\<and> (d y) \\<cdot> x \\<sqsubseteq> y\"\n\nlemma refines_refl: \"refines x x\"\n  using refines_def by simp\n\nlemma refines_trans: \"refines x y \\<Longrightarrow> refines y z \\<Longrightarrow> refines x z\"\n  unfolding refines_def\n  by (metis domain_invol ds.trans dsg1 dsg3 ds_ord_def)\n\nlemma refines_antisym: \"refines x y \\<Longrightarrow> refines y x \\<Longrightarrow> x = y\"\n  apply (rule ds.antisym)\n   apply (simp_all add: refines_def)\n   apply (metis ds_dom_llp_strong)\n  apply (metis ds_dom_llp_strong)\n  done\n\nsublocale ref: ordering \"refines\" \"\\<lambda>x y. (refines x y \\<and> x \\<noteq> y)\"\nproof\n  show \"\\<And>x y. refines x y \\<and> x \\<noteq> y \\<longleftrightarrow> refines x y \\<and> x \\<noteq> y\"\n    ..\n  show \"\\<And>x. refines x x\"\n    by (rule refines_refl)\n  show \"\\<And>x y z. refines x y \\<Longrightarrow> refines y z \\<Longrightarrow> refines x z\"\n    by (rule refines_trans)\n  show \"\\<And>x y. refines x y \\<Longrightarrow> refines y x \\<Longrightarrow> x = y\"\n    by (rule refines_antisym)\nqed\n\nend\n\ntext \\<open>We expand domain semigroups to domain monoids.\\<close>\n\nclass domain_monoid = monoid_mult + domain_semigroup\nbegin\n\nlemma dom_one [simp]: \"d 1 = 1\"\nproof -\n  have \"1 = d 1 \\<cdot> 1\"\n    using dsg1 by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma ds_subid_eq: \"x \\<sqsubseteq> 1 \\<longleftrightarrow> x = d x\"\n  by (simp add: ds_ord_def)\n\nend\n\nsubsection \\<open>Domain Near-Semirings\\<close>\n\ntext \\<open>The axioms for domain near-semirings are taken from~\\<^cite>\\<open>\"DesharnaisStruthAMAST\"\\<close>.\\<close>\n\nclass domain_near_semiring = ab_near_semiring + plus_ord + domain_op +\n  assumes dns1 [simp]: \"d x \\<cdot> x = x\"\n  and dns2 [simp]: \"d (x \\<cdot> d y) = d(x \\<cdot> y)\"\n  and dns3 [simp]: \"d (x + y) = d x + d y\"\n  and dns4: \"d x \\<cdot> d y = d y \\<cdot> d x\"\n  and dns5 [simp]: \"d x \\<cdot> (d x + d y) = d x\"\n\nbegin\n\ntext \\<open>Domain near-semirings are automatically dioids; addition is idempotent.\\<close>\n\nsubclass near_dioid\nproof\n  show \"\\<And>x. x + x = x\"\n  proof -\n    fix x\n    have a: \"d x = d x \\<cdot> d (x + x)\"\n      using dns3 dns5 by presburger\n    have \"d (x + x) = d (x + x + (x + x)) \\<cdot> d (x + x)\"\n      by (metis (no_types) dns3  dns4 dns5)\n    hence \"d (x + x) = d (x + x) + d (x + x)\"\n      by simp\n    thus \"x + x = x\"\n      by (metis a dns1 dns4 distrib_right')\n  qed\nqed\n\ntext \\<open>Next we prepare to show that domain near-semirings are domain semigroups.\\<close>\n\n\n\nlemma dom_add_closed [simp]: \"d (d x + d y) = d x + d y\"\nproof -\n  have \"d (d x + d y) = d (d x) + d (d y)\"\n    by simp\n  thus ?thesis\n    by (metis dns1 dns2 dns3 dns4)\nqed\n\nlemma dom_absorp_2 [simp]: \"d x + d x \\<cdot> d y = d x\"\nproof -\n  have \"d x + d x \\<cdot> d y = d x \\<cdot> d x + d x \\<cdot> d y\"\n    by (metis add_idem' dns5)\n  also have \"... = (d x + d y) \\<cdot> d x\"\n    by (simp add: dns4)\n  also have \"... = d x \\<cdot> (d x + d y)\"\n    by (metis dom_add_closed dns4)\n  finally show ?thesis\n    by simp\nqed\n\nlemma dom_1: \"d (x \\<cdot> y) \\<le> d x\"\nproof -\n  have \"d (x \\<cdot> y) = d (d x \\<cdot> d (x \\<cdot> y))\"\n    by (metis dns1 dns2 mult_assoc)\n  also have \"... \\<le> d (d x) + d (d x \\<cdot> d (x \\<cdot> y))\"\n    by simp\n  also have \"... = d (d x + d x \\<cdot> d (x \\<cdot> y))\"\n    using dns3  by presburger\n  also have \"... = d (d x)\"\n    by simp\n  finally show ?thesis\n    by (metis dom_add_closed add_idem')\nqed\n\nlemma dom_subid_aux2: \"d x \\<cdot> y \\<le> y\"\nproof -\n  have \"d x \\<cdot> y \\<le> d (x + d y) \\<cdot> y\"\n    by (simp add: mult_isor)\n  also have \"... = (d x + d (d y)) \\<cdot> d y \\<cdot> y\"\n    using dns1 dns3 mult_assoc by presburger\n  also have \"... = (d y + d y \\<cdot> d x) \\<cdot> y\"\n    by (simp add: dns4 add_commute)\n  finally show ?thesis\n    by simp\nqed\n\nlemma dom_glb: \"d x \\<le> d y \\<Longrightarrow> d x \\<le> d z \\<Longrightarrow> d x \\<le> d y \\<cdot> d z\"\n  by (metis dns5 less_eq_def mult_isor)\n\nlemma dom_glb_eq: \"d x \\<le> d y \\<cdot> d z \\<longleftrightarrow> d x \\<le> d y \\<and> d x \\<le> d z\"\nproof -\n  have \"d x \\<le> d z \\<longrightarrow> d x \\<le> d z\"\n    by meson\n  then show ?thesis\n    by (metis (no_types) dom_absorp_2 dom_glb dom_subid_aux2 local.dual_order.trans local.join.sup.coboundedI2)\nqed\n\nlemma dom_ord: \"d x \\<le> d y \\<longleftrightarrow> d x \\<cdot> d y = d x\"\nproof\n  assume \"d x \\<le> d y\"\n  hence \"d x + d y = d y\"\n    by (simp add: less_eq_def)\n  thus \"d x \\<cdot> d y = d x\"\n    by (metis dns5)\nnext\n  assume \"d x \\<cdot> d y = d x\"\n  thus \"d x \\<le> d y\"\n    by (metis dom_subid_aux2)\nqed\n\nlemma dom_export [simp]: \"d (d x \\<cdot> y) = d x \\<cdot> d y\"\nproof (rule order.antisym)\n  have \"d (d x \\<cdot> y) = d (d (d x \\<cdot> y)) \\<cdot> d (d x \\<cdot> y)\"\n    using dns1 by presburger\n  also have \"... = d (d x \\<cdot> d y) \\<cdot> d (d x \\<cdot> y)\"\n    by (metis dns1 dns2 mult_assoc)\n  finally show a: \"d (d x \\<cdot> y) \\<le> d x \\<cdot> d y\"\n    by (metis (no_types) dom_add_closed dom_glb dom_1 add_idem' dns2 dns4)\n  have \"d (d x \\<cdot> y) = d (d x \\<cdot> y) \\<cdot> d x\"\n    using a dom_glb_eq dom_ord by force\n  hence \"d x \\<cdot> d y = d (d x \\<cdot> y) \\<cdot> d y\"\n    by (metis dns1 dns2 mult_assoc)\n  thus \"d x \\<cdot> d y \\<le> d (d x \\<cdot> y)\"\n    using a dom_glb_eq dom_ord by auto\nqed\n\nsubclass domain_semigroup\n by (unfold_locales, auto simp: dns4)\n\ntext \\<open>We compare the domain semigroup ordering with that of the dioid.\\<close>\n\n\n\nlemma two_orders: \"x \\<sqsubseteq> y \\<Longrightarrow> x \\<le> y\"\n  by (metis dom_subid_aux2 ds_ord_def)\n\nlemma \"x \\<le> y \\<Longrightarrow> x \\<sqsubseteq> y\"\n(*nitpick [expect=genuine]*)\noops\n\ntext \\<open>Next we prove additional properties.\\<close>\n\nlemma dom_subdist: \"d x \\<le> d (x + y)\"\n  by simp\n\nlemma dom_distrib: \"d x + d y \\<cdot> d z = (d x + d y) \\<cdot> (d x + d z)\"\nproof -\n  have \"(d x + d y) \\<cdot> (d x + d z) = d x \\<cdot> (d x + d z) + d y \\<cdot> (d x + d z)\"\n    using distrib_right' by blast\n  also have \"... = d x + (d x + d z) \\<cdot> d y\"\n    by (metis (no_types) dns3 dns5 dsg4)\n  also have \"... = d x + d x \\<cdot> d y + d z \\<cdot> d y\"\n    using add_assoc' distrib_right' by presburger\n  finally show ?thesis\n    by (simp add: dsg4)\nqed\n\nlemma dom_llp1: \"x \\<le> d y \\<cdot> x \\<Longrightarrow> d x \\<le> d y\"\nproof -\n  assume \"x \\<le> d y \\<cdot> x\"\n  hence \"d x \\<le> d (d y \\<cdot> x)\"\n    using dom_iso by blast\n  also have \"... = d y \\<cdot> d x\"\n    by simp\n  finally show \"d x \\<le> d y\"\n    by (simp add: dom_glb_eq)\nqed\n\nlemma dom_llp2: \"d x \\<le> d y \\<Longrightarrow> x \\<le> d y \\<cdot> x\"\n  using d_two_orders local.ds_dom_llp two_orders by blast\n\nlemma dom_llp: \"x \\<le> d y \\<cdot> x \\<longleftrightarrow> d x \\<le> d y\"\n  using dom_llp1 dom_llp2 by blast\n\nend\n\ntext \\<open>We expand domain near-semirings by an additive unit, using slightly different axioms.\\<close>\n\nclass domain_near_semiring_one = ab_near_semiring_one + plus_ord + domain_op +\n  assumes dnso1 [simp]: \"x + d x \\<cdot> x = d x \\<cdot> x\"\n  and dnso2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dnso3 [simp]: \"d x + 1 = 1\"\n  and dnso4 [simp]: \"d (x + y) = d x + d y\"\n  and dnso5: \"d x \\<cdot> d y = d y \\<cdot> d x\"\n\nbegin\n\ntext \\<open>The previous axioms are derivable.\\<close>\n\nsubclass domain_near_semiring\nproof\n  show a: \"\\<And>x. d x \\<cdot> x = x\"\n    by (metis add_commute local.dnso3 local.distrib_right' local.dnso1 local.mult_onel)\n  show \"\\<And>x y. d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n    by simp\n  show \"\\<And>x y. d (x + y) = d x + d y\"\n    by simp\n  show \"\\<And>x y. d x \\<cdot> d y = d y \\<cdot> d x\"\n    by (simp add: dnso5)\n  show \"\\<And>x y. d x \\<cdot> (d x + d y) = d x\"\n  proof -\n    fix x y\n    have \"\\<And>x. 1 + d x = 1\"\n      using add_commute dnso3 by presburger\n    thus \"d x \\<cdot> (d x + d y) = d x\"\n      by (metis (no_types) a dnso2 dnso4 dnso5 distrib_right' mult_onel)\n  qed\nqed\n\nsubclass domain_monoid ..\n\nlemma dom_subid: \"d x \\<le> 1\"\n  by (simp add: less_eq_def)\n\nend\n\ntext \\<open>We add a left unit of multiplication.\\<close>\n\nclass domain_near_semiring_one_zerol = ab_near_semiring_one_zerol + domain_near_semiring_one +\n  assumes dnso6 [simp]: \"d 0 = 0\"\n\nbegin\n\nlemma domain_very_strict: \"d x = 0 \\<longleftrightarrow> x = 0\"\n  by (metis annil dns1 dnso6)\n\nlemma dom_weakly_local: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> d y = 0\"\nproof -\n  have \"x \\<cdot> y = 0 \\<longleftrightarrow> d (x \\<cdot> y) = 0\"\n    by (simp add: domain_very_strict)\n  also have \"... \\<longleftrightarrow> d (x \\<cdot> d y) = 0\"\n    by simp\n  finally show ?thesis\n    using domain_very_strict by blast\nqed\n\nend\n\nsubsection \\<open>Domain Pre-Dioids\\<close>\n\ntext \\<open>\n  Pre-semirings with one and a left zero are automatically dioids.\n  Hence there is no point defining domain pre-semirings separately from domain dioids. The axioms\nare once again from~\\<^cite>\\<open>\"DesharnaisStruthAMAST\"\\<close>.\n\\<close>\n\nclass domain_pre_dioid_one = pre_dioid_one + domain_op +\n  assumes dpd1 : \"x \\<le> d x \\<cdot> x\"\n  and dpd2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dpd3 [simp]: \"d x \\<le> 1\"\n  and dpd4 [simp]: \"d (x + y) = d x + d y\"\n\nbegin\n\ntext \\<open>We prepare to show that every domain pre-dioid with one is a domain near-dioid with one.\\<close>\n\nlemma dns1'' [simp]: \"d x \\<cdot> x = x\"\nproof (rule order.antisym)\n  show \"d x \\<cdot> x \\<le> x\"\n    using dpd3  mult_isor by fastforce\n  show \"x \\<le> d x \\<cdot> x \"\n    by (simp add: dpd1)\nqed\n\nlemma d_iso: \"x \\<le> y \\<Longrightarrow> d x \\<le> d y\"\n  by (metis dpd4 less_eq_def)\n\nlemma domain_1'': \"d (x \\<cdot> y) \\<le> d x\"\nproof -\n  have \"d (x \\<cdot> y) = d (x \\<cdot> d y)\"\n    by simp\n  also have \"... \\<le> d (x \\<cdot> 1)\"\n    by (meson d_iso dpd3 mult_isol)\n  finally show ?thesis\n    by simp\nqed\n\nlemma domain_export'' [simp]: \"d (d x \\<cdot> y) = d x \\<cdot> d y\"\nproof (rule order.antisym)\n  have one: \"d (d x \\<cdot> y) \\<le> d x\"\n    by (metis dpd2 domain_1'' mult_onel)\n  have two: \"d (d x \\<cdot> y) \\<le> d y\"\n    using d_iso dpd3 mult_isor by fastforce\n  have \"d (d x \\<cdot> y) = d (d (d x \\<cdot> y)) \\<cdot> d (d x \\<cdot> y)\"\n    by simp\n  also have \"... = d (d x \\<cdot> y) \\<cdot> d (d x \\<cdot> y)\"\n    by (metis dns1'' dpd2 mult_assoc)\n  thus \"d (d x \\<cdot> y) \\<le> d x \\<cdot> d y\"\n    using mult_isol_var one two by force\nnext\n  have \"d x \\<cdot> d y \\<le> 1\"\n    by (metis dpd3  mult_1_right mult_isol order.trans)\n  thus \"d x \\<cdot> d y \\<le> d (d x \\<cdot> y)\"\n    by (metis dns1'' dpd2 mult_isol mult_oner)\nqed\n\nlemma dom_subid_aux1'': \"d x \\<cdot> y \\<le> y\"\nproof -\n  have \"d x \\<cdot> y \\<le> 1 \\<cdot> y\"\n    using dpd3 mult_isor by blast\n  thus ?thesis\n    by simp\nqed\n\nlemma dom_subid_aux2'': \"x \\<cdot> d y \\<le> x\"\n  using dpd3 mult_isol by fastforce\n\nlemma d_comm: \"d x \\<cdot> d y = d y \\<cdot> d x\"\nproof (rule order.antisym)\n  have \"d x \\<cdot> d y = (d x \\<cdot> d y) \\<cdot> (d x \\<cdot> d y)\"\n    by (metis dns1'' domain_export'')\n  thus \"d x \\<cdot> d y \\<le> d y \\<cdot> d x\"\n    by (metis dom_subid_aux1'' dom_subid_aux2'' mult_isol_var)\nnext\n  have \"d y \\<cdot> d x = (d y \\<cdot> d x) \\<cdot> (d y \\<cdot> d x)\"\n    by (metis dns1'' domain_export'')\n  thus \"d y \\<cdot> d x \\<le> d x \\<cdot> d y\"\n    by (metis dom_subid_aux1'' dom_subid_aux2'' mult_isol_var)\nqed\n\nsubclass domain_near_semiring_one\n  by (unfold_locales, auto simp: d_comm local.join.sup.absorb2)\n\nlemma domain_subid: \"x \\<le> 1 \\<Longrightarrow> x \\<le> d x\"\n  by (metis dns1 mult_isol mult_oner)\n\nlemma d_preserves_equation: \"d y \\<cdot> x \\<le> x \\<cdot> d z \\<longleftrightarrow> d y \\<cdot> x = d y \\<cdot> x \\<cdot> d z\"\n  by (metis dom_subid_aux2'' order.antisym local.dom_el_idem local.dom_subid_aux2 local.order_prop local.subdistl mult_assoc)\n\nlemma d_restrict_iff: \"(x \\<le> y) \\<longleftrightarrow> (x \\<le> d x \\<cdot> y)\"\n  by (metis dom_subid_aux2 dsg1 less_eq_def order_trans subdistl)\n\nlemma d_restrict_iff_1: \"(d x \\<cdot> y \\<le> z) \\<longleftrightarrow> (d x \\<cdot> y \\<le> d x \\<cdot> z)\"\n  by (metis dom_subid_aux2 domain_1'' domain_invol dsg1 mult_isol_var order_trans)\n\nend\n\ntext \\<open>We add once more a left unit of multiplication.\\<close>\n\nclass domain_pre_dioid_one_zerol = domain_pre_dioid_one + pre_dioid_one_zerol +\n  assumes dpd5 [simp]: \"d 0 = 0\"\n\nbegin\n\nsubclass domain_near_semiring_one_zerol\n  by (unfold_locales, simp)\n\nend\n\nsubsection \\<open>Domain Semirings\\<close>\n\ntext \\<open>We do not consider domain semirings without units separately at the moment. The axioms are taken from from~\\<^cite>\\<open>\"DesharnaisStruthSCP\"\\<close>\\<close>\n\nclass domain_semiringl = semiring_one_zerol + plus_ord + domain_op +\n  assumes dsr1 [simp]: \"x + d x \\<cdot> x = d x \\<cdot> x\"\n  and dsr2 [simp]: \"d (x \\<cdot> d y) = d (x \\<cdot> y)\"\n  and dsr3 [simp]: \"d x + 1 = 1\"\n  and dsr4 [simp]: \"d 0 = 0\"\n  and dsr5 [simp]: \"d (x + y) = d x + d y\"\n\nbegin\n\ntext \\<open>Every domain semiring is automatically a domain pre-dioid with one and left zero.\\<close>\n\nsubclass dioid_one_zerol\n  by (standard, metis add_commute dsr1 dsr3 distrib_left mult_oner)\n\nsubclass domain_pre_dioid_one_zerol\n  by (standard, auto simp: less_eq_def)\n\nend\n\nclass domain_semiring = domain_semiringl + semiring_one_zero\n\nsubsection \\<open>The Algebra of Domain Elements\\<close>\n\ntext \\<open>We show that the domain elements of a domain semiring form a distributive lattice. Unfortunately we cannot prove this within the type class of domain semirings.\\<close>\n\ntypedef (overloaded)  'a d_element = \"{x :: 'a :: domain_semiring. x = d x}\"\n  by (rule_tac x = 1 in exI, simp add: domain_subid ds.eq_iff)\n\nsetup_lifting type_definition_d_element\n\ninstantiation d_element :: (domain_semiring) bounded_lattice\n\nbegin\n\nlift_definition less_eq_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> bool\" is \"(\\<le>)\" .\n\nlift_definition less_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> bool\" is \"(<)\" .\n\nlift_definition bot_d_element :: \"'a d_element\" is 0\n  by simp\n\nlift_definition top_d_element :: \"'a d_element\" is 1\n  by simp\n\nlift_definition inf_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> 'a d_element\" is \"(\\<cdot>)\"\n  by (metis dsg3)\n\nlift_definition sup_d_element :: \"'a d_element \\<Rightarrow> 'a d_element \\<Rightarrow> 'a d_element\" is \"(+)\"\n  by simp\n\ninstance\n  apply (standard; transfer)\n  apply (simp add: less_le_not_le)+\n  apply (metis dom_subid_aux2'')\n  apply (metis dom_subid_aux2)\n  apply (metis dom_glb)\n  apply simp+\n  by (metis dom_subid)\n\nend\n\ninstance d_element :: (domain_semiring) distrib_lattice\n  by (standard, transfer, metis dom_distrib)\n\nsubsection \\<open>Domain Semirings with a Greatest Element\\<close>\n\ntext \\<open>If there is a greatest element in the semiring, then we have another equality.\\<close>\n\nclass domain_semiring_top = domain_semiring + order_top\n\nbegin\n\nnotation top (\"\\<top>\")\n\n\n\nend\n\nsubsection \\<open>Forward Diamond Operators\\<close>\n\ncontext domain_semiringl\n\nbegin\n\ntext \\<open>We define a forward diamond operator over a domain semiring. A more modular consideration is not given at the moment.\\<close>\n\ndefinition fd :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (\"( |_\\<rangle> _)\" [61,81] 82) where\n  \"|x\\<rangle> y = d (x \\<cdot> y)\"\n\nlemma fdia_d_simp [simp]: \"|x\\<rangle> d y = |x\\<rangle> y\"\n  by (simp add: fd_def)\n\nlemma fdia_dom [simp]: \"|x\\<rangle> 1 = d x\"\n  by (simp add: fd_def)\n\nlemma fdia_add1: \"|x\\<rangle> (y + z) = |x\\<rangle> y + |x\\<rangle> z\"\n  by (simp add: fd_def distrib_left)\n\nlemma fdia_add2: \"|x + y\\<rangle> z = |x\\<rangle> z + |y\\<rangle> z\"\n  by (simp add: fd_def distrib_right)\n\nlemma fdia_mult: \"|x \\<cdot> y\\<rangle> z = |x\\<rangle> |y\\<rangle> z\"\n  by (simp add: fd_def mult_assoc)\n\nlemma fdia_one [simp]: \"|1\\<rangle> x = d x\"\n  by (simp add: fd_def)\n\nlemma fdemodalisation1: \"d z \\<cdot> |x\\<rangle> y = 0 \\<longleftrightarrow> d z \\<cdot> x \\<cdot> d y = 0\"\nproof -\n  have \"d z \\<cdot> |x\\<rangle> y = 0 \\<longleftrightarrow> d z \\<cdot> d (x \\<cdot> y) = 0\"\n    by (simp add: fd_def)\n  also have \"... \\<longleftrightarrow> d z \\<cdot> x \\<cdot> y = 0\"\n    by (metis annil dnso6 dsg1 dsg3 mult_assoc)\n  finally show ?thesis\n    using dom_weakly_local by auto\nqed\n\nlemma fdemodalisation2: \"|x\\<rangle> y \\<le> d z \\<longleftrightarrow> x \\<cdot> d y \\<le> d z \\<cdot> x\"\nproof\n  assume \"|x\\<rangle> y \\<le> d z\"\n  hence a: \"d (x \\<cdot> d y) \\<le> d z\"\n    by (simp add: fd_def)\n  have \"x \\<cdot> d y = d (x \\<cdot> d y) \\<cdot> x \\<cdot> d y\"\n    using dsg1 mult_assoc by presburger\n  also have \"... \\<le> d z \\<cdot> x \\<cdot> d y\"\n    using a calculation dom_llp2 mult_assoc by auto\n  finally show \"x \\<cdot> d y \\<le> d z \\<cdot> x\"\n    using dom_subid_aux2'' order_trans by blast\nnext\n  assume \"x \\<cdot> d y \\<le> d z \\<cdot> x\"\n  hence \"d (x \\<cdot> d y) \\<le> d (d z \\<cdot> d x)\"\n    using dom_iso by fastforce\n  also have \"... \\<le> d (d z)\"\n    using domain_1'' by blast\n  finally show \"|x\\<rangle> y \\<le> d z\"\n    by (simp add: fd_def)\nqed\n\nlemma fd_iso1: \"d x \\<le> d y \\<Longrightarrow> |z\\<rangle> x \\<le> |z\\<rangle> y\"\n  using fd_def local.dom_iso local.mult_isol by fastforce\n\nlemma fd_iso2: \"x \\<le> y \\<Longrightarrow> |x\\<rangle> z \\<le> |y\\<rangle> z\"\n  by (simp add: fd_def dom_iso mult_isor)\n\nlemma fd_zero_var [simp]: \"|0\\<rangle> x = 0\"\n  by (simp add: fd_def)\n\nlemma fd_subdist_1: \"|x\\<rangle> y \\<le> |x\\<rangle> (y + z)\"\n  by (simp add: fd_iso1)\n\nlemma fd_subdist_2: \"|x\\<rangle> (d y \\<cdot> d z) \\<le> |x\\<rangle> y\"\n  by (simp add: fd_iso1 dom_subid_aux2'')\n\nlemma fd_subdist: \"|x\\<rangle> (d y \\<cdot> d z) \\<le> |x\\<rangle> y \\<cdot> |x\\<rangle> z\"\n  using fd_def fd_iso1 fd_subdist_2 dom_glb dom_subid_aux2 by auto\n\nlemma fdia_export_1: \"d y \\<cdot> |x\\<rangle> z = |d y \\<cdot> x\\<rangle> z\"\n  by (simp add: fd_def mult_assoc)\n\nend\n\ncontext domain_semiring\n\nbegin\n\n\n\nend\n\nsubsection \\<open>Domain Kleene Algebras\\<close>\n\ntext \\<open>We add the Kleene star to our considerations. Special domain axioms are not needed.\\<close>\n\nclass domain_left_kleene_algebra = left_kleene_algebra_zerol + domain_semiringl\n\nbegin\n\nlemma dom_star [simp]: \"d (x\\<^sup>\\<star>) = 1\"\nproof -\n  have \"d (x\\<^sup>\\<star>) = d (1 + x \\<cdot> x\\<^sup>\\<star>)\"\n    by simp\n  also have \"... = d 1 + d (x \\<cdot> x\\<^sup>\\<star>)\"\n    using dns3 by blast\n  finally show ?thesis\n    using add_commute local.dsr3 by auto\nqed\n\nlemma fdia_star_unfold [simp]: \"|1\\<rangle> y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"|1\\<rangle> y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |1 + x \\<cdot> x\\<^sup>\\<star>\\<rangle> y\"\n    using local.fdia_add2 local.fdia_mult by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma fdia_star_unfoldr [simp]: \"|1\\<rangle> y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"|1\\<rangle> y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |1 + x\\<^sup>\\<star> \\<cdot> x\\<rangle> y\"\n    using fdia_add2 fdia_mult by presburger\n  thus ?thesis\n    by simp\nqed\n\nlemma fdia_star_unfold_var [simp]: \"d y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"d y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y = |1\\<rangle> y + |x\\<rangle> |x\\<^sup>\\<star>\\<rangle> y\"\n    by simp\n  also have \"... = |1 + x \\<cdot> x\\<^sup>\\<star>\\<rangle> y\"\n    using fdia_add2 fdia_mult by presburger\n  finally show ?thesis\n    by simp\nqed\n\nlemma fdia_star_unfoldr_var [simp]: \"d y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |x\\<^sup>\\<star>\\<rangle> y\"\nproof -\n  have \"d y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y = |1\\<rangle> y + |x\\<^sup>\\<star>\\<rangle> |x\\<rangle> y\"\n    by simp\n  also have \"... = |1 + x\\<^sup>\\<star> \\<cdot> x\\<rangle> y\"\n    using fdia_add2 fdia_mult by presburger\n  finally show ?thesis\n    by simp\nqed\n\nlemma fdia_star_induct_var: \"|x\\<rangle> y \\<le> d y \\<Longrightarrow> |x\\<^sup>\\<star>\\<rangle> y \\<le> d y\"\nproof -\n  assume a1: \"|x\\<rangle> y \\<le> d y\"\n  hence \"x \\<cdot> d y \\<le> d y \\<cdot> x\"\n    by (simp add: fdemodalisation2)\n  hence \"x\\<^sup>\\<star> \\<cdot> d y \\<le> d y \\<cdot> x\\<^sup>\\<star>\"\n    by (simp add: star_sim1)\n  thus ?thesis\n    by (simp add: fdemodalisation2)\nqed\n\nlemma fdia_star_induct: \"d z + |x\\<rangle> y \\<le> d y \\<Longrightarrow> |x\\<^sup>\\<star>\\<rangle> z \\<le> d y\"\nproof -\n  assume a: \"d z + |x\\<rangle> y \\<le> d y\"\n  hence b: \"d z \\<le> d y\" and c: \"|x\\<rangle> y \\<le> d y\"\n    apply (simp add: local.join.le_supE)\n    using a by auto\n  hence d: \"|x\\<^sup>\\<star>\\<rangle> z \\<le> |x\\<^sup>\\<star>\\<rangle> y\"\n    using fd_def fd_iso1 by auto\n  have \"|x\\<^sup>\\<star>\\<rangle> y \\<le> d y\"\n    using c fdia_star_induct_var by blast\n  thus ?thesis\n    using d by fastforce\nqed\n\nlemma fdia_star_induct_eq: \"d z + |x\\<rangle> y = d y \\<Longrightarrow> |x\\<^sup>\\<star>\\<rangle> z \\<le> d y\"\n  by (simp add: fdia_star_induct)\n\nend\n\nclass domain_kleene_algebra = kleene_algebra + domain_semiring\n\nbegin\n\nsubclass domain_left_kleene_algebra ..\n\nend\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/KAD/Domain_Semiring.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.8615382094310355, "lm_q1q2_score": 0.7670224834088823}}
{"text": "(*  Title:      HOL/ex/ThreeDivides.thy\n    Author:     Benjamin Porter, 2005\n*)\n\nsection \\<open>Three Divides Theorem\\<close>\n\ntheory ThreeDivides\nimports Main \"~~/src/HOL/Library/LaTeXsugar\"\nbegin\n\nsubsection \\<open>Abstract\\<close>\n\ntext \\<open>\nThe following document presents a proof of the Three Divides N theorem\nformalised in the Isabelle/Isar theorem proving system.\n\n{\\em Theorem}: $3$ divides $n$ if and only if $3$ divides the sum of all\ndigits in $n$.\n\n{\\em Informal Proof}:\nTake $n = \\sum{n_j * 10^j}$ where $n_j$ is the $j$'th least\nsignificant digit of the decimal denotation of the number n and the\nsum ranges over all digits. Then $$ (n - \\sum{n_j}) = \\sum{n_j * (10^j\n- 1)} $$ We know $\\forall j\\; 3|(10^j - 1) $ and hence $3|LHS$,\ntherefore $$\\forall n\\; 3|n \\Longleftrightarrow 3|\\sum{n_j}$$\n\\<open>\\<box>\\<close>\n\\<close>\n\n\nsubsection \\<open>Formal proof\\<close>\n\nsubsubsection \\<open>Miscellaneous summation lemmas\\<close>\n\ntext \\<open>If $a$ divides \\<open>A x\\<close> for all x then $a$ divides any\nsum over terms of the form \\<open>(A x)*(P x)\\<close> for arbitrary $P$.\\<close>\n\nlemma div_sum:\n  fixes a::nat and n::nat\n  shows \"\\<forall>x. a dvd A x \\<Longrightarrow> a dvd (\\<Sum>x<n. A x * D x)\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  from Suc\n  have \"a dvd (A n * D n)\" by (simp add: dvd_mult2)\n  with Suc\n  have \"a dvd ((\\<Sum>x<n. A x * D x) + (A n * D n))\" by (simp add: dvd_add)\n  thus ?case by simp\nqed\n\n\nsubsubsection \\<open>Generalised Three Divides\\<close>\n\ntext \\<open>This section solves a generalised form of the three divides\nproblem. Here we show that for any sequence of numbers the theorem\nholds. In the next section we specialise this theorem to apply\ndirectly to the decimal expansion of the natural numbers.\\<close>\n\ntext \\<open>Here we show that the first statement in the informal proof is\ntrue for all natural numbers. Note we are using @{term \"D i\"} to\ndenote the $i$'th element in a sequence of numbers.\\<close>\n\nlemma digit_diff_split:\n  fixes n::nat and nd::nat and x::nat\n  shows \"n = (\\<Sum>x\\<in>{..<nd}. (D x)*((10::nat)^x)) \\<Longrightarrow>\n             (n - (\\<Sum>x<nd. (D x))) = (\\<Sum>x<nd. (D x)*(10^x - 1))\"\nby (simp add: sum_diff_distrib diff_mult_distrib2)\n\ntext \\<open>Now we prove that 3 always divides numbers of the form $10^x - 1$.\\<close>\nlemma three_divs_0:\n  shows \"(3::nat) dvd (10^x - 1)\"\nproof (induct x)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  let ?thr = \"(3::nat)\"\n  have \"?thr dvd 9\" by simp\n  moreover\n  have \"?thr dvd (10*(10^n - 1))\" by (rule dvd_mult) (rule Suc)\n  hence \"?thr dvd (10^(n+1) - 10)\" by (simp add: nat_distrib)\n  ultimately\n  have\"?thr dvd ((10^(n+1) - 10) + 9)\"\n    by (simp only: ac_simps) (rule dvd_add)\n  thus ?case by simp\nqed\n\ntext \\<open>Expanding on the previous lemma and lemma \\<open>div_sum\\<close>.\\<close>\nlemma three_divs_1:\n  fixes D :: \"nat \\<Rightarrow> nat\"\n  shows \"3 dvd (\\<Sum>x<nd. D x * (10^x - 1))\"\n  by (subst mult.commute, rule div_sum) (simp add: three_divs_0 [simplified])\n\ntext \\<open>Using lemmas \\<open>digit_diff_split\\<close> and \n\\<open>three_divs_1\\<close> we now prove the following lemma. \n\\<close>\nlemma three_divs_2:\n  fixes nd::nat and D::\"nat\\<Rightarrow>nat\"\n  shows \"3 dvd ((\\<Sum>x<nd. (D x)*(10^x)) - (\\<Sum>x<nd. (D x)))\"\nproof -\n  from three_divs_1 have \"3 dvd (\\<Sum>x<nd. D x * (10 ^ x - 1))\" .\n  thus ?thesis by (simp only: digit_diff_split)\nqed\n\ntext \\<open>\nWe now present the final theorem of this section. For any\nsequence of numbers (defined by a function @{term \"D :: (nat\\<Rightarrow>nat)\"}),\nwe show that 3 divides the expansive sum $\\sum{(D\\;x)*10^x}$ over $x$\nif and only if 3 divides the sum of the individual numbers\n$\\sum{D\\;x}$. \n\\<close>\nlemma three_div_general:\n  fixes D :: \"nat \\<Rightarrow> nat\"\n  shows \"(3 dvd (\\<Sum>x<nd. D x * 10^x)) = (3 dvd (\\<Sum>x<nd. D x))\"\nproof\n  have mono: \"(\\<Sum>x<nd. D x) \\<le> (\\<Sum>x<nd. D x * 10^x)\"\n    by (rule sum_mono) simp\n  txt \\<open>This lets us form the term\n         @{term \"(\\<Sum>x<nd. D x * 10^x) - (\\<Sum>x<nd. D x)\"}\\<close>\n\n  {\n    assume \"3 dvd (\\<Sum>x<nd. D x)\"\n    with three_divs_2 mono\n    show \"3 dvd (\\<Sum>x<nd. D x * 10^x)\" \n      by (blast intro: dvd_diffD)\n  }\n  {\n    assume \"3 dvd (\\<Sum>x<nd. D x * 10^x)\"\n    with three_divs_2 mono\n    show \"3 dvd (\\<Sum>x<nd. D x)\"\n      by (blast intro: dvd_diffD1)\n  }\nqed\n\n\nsubsubsection \\<open>Three Divides Natural\\<close>\n\ntext \\<open>This section shows that for all natural numbers we can\ngenerate a sequence of digits less than ten that represent the decimal\nexpansion of the number. We then use the lemma \\<open>three_div_general\\<close> to prove our final theorem.\\<close>\n\n\ntext \\<open>\\medskip Definitions of length and digit sum.\\<close>\n\ntext \\<open>This section introduces some functions to calculate the\nrequired properties of natural numbers. We then proceed to prove some\nproperties of these functions.\n\nThe function \\<open>nlen\\<close> returns the number of digits in a natural\nnumber n.\\<close>\n\nfun nlen :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"nlen 0 = 0\"\n| \"nlen x = 1 + nlen (x div 10)\"\n\ntext \\<open>The function \\<open>sumdig\\<close> returns the sum of all digits in\nsome number n.\\<close>\n\ndefinition\n  sumdig :: \"nat \\<Rightarrow> nat\" where\n  \"sumdig n = (\\<Sum>x < nlen n. n div 10^x mod 10)\"\n\ntext \\<open>Some properties of these functions follow.\\<close>\n\nlemma nlen_zero:\n  \"0 = nlen x \\<Longrightarrow> x = 0\"\n  by (induct x rule: nlen.induct) auto\n\nlemma nlen_suc:\n  \"Suc m = nlen n \\<Longrightarrow> m = nlen (n div 10)\"\n  by (induct n rule: nlen.induct) simp_all\n\n\ntext \\<open>The following lemma is the principle lemma required to prove\nour theorem. It states that an expansion of some natural number $n$\ninto a sequence of its individual digits is always possible.\\<close>\n\nlemma exp_exists:\n  \"m = (\\<Sum>x<nlen m. (m div (10::nat)^x mod 10) * 10^x)\"\nproof (induct \"nlen m\" arbitrary: m)\n  case 0 thus ?case by (simp add: nlen_zero)\nnext\n  case (Suc nd)\n  obtain c where mexp: \"m = 10*(m div 10) + c \\<and> c < 10\"\n    and cdef: \"c = m mod 10\" by simp\n  show \"m = (\\<Sum>x<nlen m. m div 10^x mod 10 * 10^x)\"\n  proof -\n    from \\<open>Suc nd = nlen m\\<close>\n    have \"nd = nlen (m div 10)\" by (rule nlen_suc)\n    with Suc have\n      \"m div 10 = (\\<Sum>x<nd. m div 10 div 10^x mod 10 * 10^x)\" by simp\n    with mexp have\n      \"m = 10*(\\<Sum>x<nd. m div 10 div 10^x mod 10 * 10^x) + c\" by simp\n    also have\n      \"\\<dots> = (\\<Sum>x<nd. m div 10 div 10^x mod 10 * 10^(x+1)) + c\"\n      by (subst sum_distrib_left) (simp add: ac_simps)\n    also have\n      \"\\<dots> = (\\<Sum>x<nd. m div 10^(Suc x) mod 10 * 10^(Suc x)) + c\"\n      by (simp add: div_mult2_eq[symmetric])\n    also have\n      \"\\<dots> = (\\<Sum>x\\<in>{Suc 0..<Suc nd}. m div 10^x  mod 10 * 10^x) + c\"\n      by (simp only: sum_shift_bounds_Suc_ivl)\n         (simp add: atLeast0LessThan)\n    also have\n      \"\\<dots> = (\\<Sum>x<Suc nd. m div 10^x mod 10 * 10^x)\"\n      by (simp add: atLeast0LessThan[symmetric] sum_head_upt_Suc cdef)\n    also note \\<open>Suc nd = nlen m\\<close>\n    finally\n    show \"m = (\\<Sum>x<nlen m. m div 10^x mod 10 * 10^x)\" .\n  qed\nqed\n\n\ntext \\<open>\\medskip Final theorem.\\<close>\n\ntext \\<open>We now combine the general theorem \\<open>three_div_general\\<close>\nand existence result of \\<open>exp_exists\\<close> to prove our final\ntheorem.\\<close>\n\ntheorem three_divides_nat:\n  shows \"(3 dvd n) = (3 dvd sumdig n)\"\nproof (unfold sumdig_def)\n  have \"n = (\\<Sum>x<nlen n. (n div (10::nat)^x mod 10) * 10^x)\"\n    by (rule exp_exists)\n  moreover\n  have \"3 dvd (\\<Sum>x<nlen n. (n div (10::nat)^x mod 10) * 10^x) =\n        (3 dvd (\\<Sum>x<nlen n. n div 10^x mod 10))\"\n    by (rule three_div_general)\n  ultimately \n  show \"3 dvd n = (3 dvd (\\<Sum>x<nlen n. n div 10^x mod 10))\" by simp\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/ex/ThreeDivides.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.8757869867849167, "lm_q1q2_score": 0.7670028448021443}}
{"text": "(*  Title:      HOL/ex/PER.thy\n    Author:     Oscar Slotosch and Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Partial equivalence relations\\<close>\n\ntheory PER\nimports Main\nbegin\n\ntext \\<open>\n  Higher-order quotients are defined over partial equivalence\n  relations (PERs) instead of total ones.  We provide axiomatic type\n  classes \\<open>equiv < partial_equiv\\<close> and a type constructor\n  \\<open>'a quot\\<close> with basic operations.  This development is based\n  on:\n\n  Oscar Slotosch: \\emph{Higher Order Quotients and their\n  Implementation in Isabelle HOL.}  Elsa L. Gunter and Amy Felty,\n  editors, Theorem Proving in Higher Order Logics: TPHOLs '97,\n  Springer LNCS 1275, 1997.\n\\<close>\n\n\nsubsection \\<open>Partial equivalence\\<close>\n\ntext \\<open>\n  Type class \\<open>partial_equiv\\<close> models partial equivalence\n  relations (PERs) using the polymorphic \\<open>\\<sim> :: 'a \\<Rightarrow> 'a \\<Rightarrow>\n  bool\\<close> relation, which is required to be symmetric and transitive,\n  but not necessarily reflexive.\n\\<close>\n\nclass partial_equiv =\n  fixes eqv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"    (infixl \"\\<sim>\" 50)\n  assumes partial_equiv_sym [elim?]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\"\n  assumes partial_equiv_trans [trans]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> x \\<sim> z\"\n\ntext \\<open>\n  \\medskip The domain of a partial equivalence relation is the set of\n  reflexive elements.  Due to symmetry and transitivity this\n  characterizes exactly those elements that are connected with\n  \\emph{any} other one.\n\\<close>\n\ndefinition\n  \"domain\" :: \"'a::partial_equiv set\" where\n  \"domain = {x. x \\<sim> x}\"\n\nlemma domainI [intro]: \"x \\<sim> x \\<Longrightarrow> x \\<in> domain\"\n  unfolding domain_def by blast\n\nlemma domainD [dest]: \"x \\<in> domain \\<Longrightarrow> x \\<sim> x\"\n  unfolding domain_def by blast\n\ntheorem domainI' [elim?]: \"x \\<sim> y \\<Longrightarrow> x \\<in> domain\"\nproof\n  assume xy: \"x \\<sim> y\"\n  also from xy have \"y \\<sim> x\" ..\n  finally show \"x \\<sim> x\" .\nqed\n\n\nsubsection \\<open>Equivalence on function spaces\\<close>\n\ntext \\<open>\n  The \\<open>\\<sim>\\<close> relation is lifted to function spaces.  It is\n  important to note that this is \\emph{not} the direct product, but a\n  structural one corresponding to the congruence property.\n\\<close>\n\ninstantiation \"fun\" :: (partial_equiv, partial_equiv) partial_equiv\nbegin\n\ndefinition \"f \\<sim> g \\<longleftrightarrow> (\\<forall>x \\<in> domain. \\<forall>y \\<in> domain. x \\<sim> y \\<longrightarrow> f x \\<sim> g y)\"\n\nlemma partial_equiv_funI [intro?]:\n    \"(\\<And>x y. x \\<in> domain \\<Longrightarrow> y \\<in> domain \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> f x \\<sim> g y) \\<Longrightarrow> f \\<sim> g\"\n  unfolding eqv_fun_def by blast\n\nlemma partial_equiv_funD [dest?]:\n    \"f \\<sim> g \\<Longrightarrow> x \\<in> domain \\<Longrightarrow> y \\<in> domain \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> f x \\<sim> g y\"\n  unfolding eqv_fun_def by blast\n\ntext \\<open>\n  The class of partial equivalence relations is closed under function\n  spaces (in \\emph{both} argument positions).\n\\<close>\n\ninstance proof\n  fix f g h :: \"'a::partial_equiv \\<Rightarrow> 'b::partial_equiv\"\n  assume fg: \"f \\<sim> g\"\n  show \"g \\<sim> f\"\n  proof\n    fix x y :: 'a\n    assume x: \"x \\<in> domain\" and y: \"y \\<in> domain\"\n    assume \"x \\<sim> y\" then have \"y \\<sim> x\" ..\n    with fg y x have \"f y \\<sim> g x\" ..\n    then show \"g x \\<sim> f y\" ..\n  qed\n  assume gh: \"g \\<sim> h\"\n  show \"f \\<sim> h\"\n  proof\n    fix x y :: 'a\n    assume x: \"x \\<in> domain\" and y: \"y \\<in> domain\" and \"x \\<sim> y\"\n    with fg have \"f x \\<sim> g y\" ..\n    also from y have \"y \\<sim> y\" ..\n    with gh y y have \"g y \\<sim> h y\" ..\n    finally show \"f x \\<sim> h y\" .\n  qed\nqed\n\nend\n\n\nsubsection \\<open>Total equivalence\\<close>\n\ntext \\<open>\n  The class of total equivalence relations on top of PERs.  It\n  coincides with the standard notion of equivalence, i.e.\\ \\<open>\\<sim>\n  :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> is required to be reflexive, transitive and\n  symmetric.\n\\<close>\n\nclass equiv =\n  assumes eqv_refl [intro]: \"x \\<sim> x\"\n\ntext \\<open>\n  On total equivalences all elements are reflexive, and congruence\n  holds unconditionally.\n\\<close>\n\ntheorem equiv_domain [intro]: \"(x::'a::equiv) \\<in> domain\"\nproof\n  show \"x \\<sim> x\" ..\nqed\n\ntheorem equiv_cong [dest?]: \"f \\<sim> g \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> f x \\<sim> g (y::'a::equiv)\"\nproof -\n  assume \"f \\<sim> g\"\n  moreover have \"x \\<in> domain\" ..\n  moreover have \"y \\<in> domain\" ..\n  moreover assume \"x \\<sim> y\"\n  ultimately show ?thesis ..\nqed\n\n\nsubsection \\<open>Quotient types\\<close>\n\ntext \\<open>\n  The quotient type \\<open>'a quot\\<close> consists of all\n  \\emph{equivalence classes} over elements of the base type \\<^typ>\\<open>'a\\<close>.\n\\<close>\n\ndefinition \"quot = {{x. a \\<sim> x}| a::'a::partial_equiv. True}\"\n\ntypedef (overloaded) 'a quot = \"quot :: 'a::partial_equiv set set\"\n  unfolding quot_def by blast\n\nlemma quotI [intro]: \"{x. a \\<sim> x} \\<in> quot\"\n  unfolding quot_def by blast\n\nlemma quotE [elim]: \"R \\<in> quot \\<Longrightarrow> (\\<And>a. R = {x. a \\<sim> x} \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  unfolding quot_def by blast\n\ntext \\<open>\n  \\medskip Abstracted equivalence classes are the canonical\n  representation of elements of a quotient type.\n\\<close>\n\ndefinition eqv_class :: \"('a::partial_equiv) \\<Rightarrow> 'a quot\"  (\"\\<lfloor>_\\<rfloor>\")\n  where \"\\<lfloor>a\\<rfloor> = Abs_quot {x. a \\<sim> x}\"\n\ntheorem quot_rep: \"\\<exists>a. A = \\<lfloor>a\\<rfloor>\"\nproof (cases A)\n  fix R assume R: \"A = Abs_quot R\"\n  assume \"R \\<in> quot\" then have \"\\<exists>a. R = {x. a \\<sim> x}\" by blast\n  with R have \"\\<exists>a. A = Abs_quot {x. a \\<sim> x}\" by blast\n  then show ?thesis by (unfold eqv_class_def)\nqed\n\nlemma quot_cases [cases type: quot]:\n  obtains (rep) a where \"A = \\<lfloor>a\\<rfloor>\"\n  using quot_rep by blast\n\n\nsubsection \\<open>Equality on quotients\\<close>\n\ntext \\<open>\n  Equality of canonical quotient elements corresponds to the original\n  relation as follows.\n\\<close>\n\ntheorem eqv_class_eqI [intro]: \"a \\<sim> b \\<Longrightarrow> \\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor>\"\nproof -\n  assume ab: \"a \\<sim> b\"\n  have \"{x. a \\<sim> x} = {x. b \\<sim> x}\"\n  proof (rule Collect_cong)\n    fix x show \"a \\<sim> x \\<longleftrightarrow> b \\<sim> x\"\n    proof\n      from ab have \"b \\<sim> a\" ..\n      also assume \"a \\<sim> x\"\n      finally show \"b \\<sim> x\" .\n    next\n      note ab\n      also assume \"b \\<sim> x\"\n      finally show \"a \\<sim> x\" .\n    qed\n  qed\n  then show ?thesis by (simp only: eqv_class_def)\nqed\n\ntheorem eqv_class_eqD' [dest?]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<Longrightarrow> a \\<in> domain \\<Longrightarrow> a \\<sim> b\"\nproof (unfold eqv_class_def)\n  assume \"Abs_quot {x. a \\<sim> x} = Abs_quot {x. b \\<sim> x}\"\n  then have \"{x. a \\<sim> x} = {x. b \\<sim> x}\" by (simp only: Abs_quot_inject quotI)\n  moreover assume \"a \\<in> domain\" then have \"a \\<sim> a\" ..\n  ultimately have \"a \\<in> {x. b \\<sim> x}\" by blast\n  then have \"b \\<sim> a\" by blast\n  then show \"a \\<sim> b\" ..\nqed\n\ntheorem eqv_class_eqD [dest?]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<Longrightarrow> a \\<sim> (b::'a::equiv)\"\nproof (rule eqv_class_eqD')\n  show \"a \\<in> domain\" ..\nqed\n\nlemma eqv_class_eq' [simp]: \"a \\<in> domain \\<Longrightarrow> \\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<longleftrightarrow> a \\<sim> b\"\n  using eqv_class_eqI eqv_class_eqD' by (blast del: eqv_refl)\n\nlemma eqv_class_eq [simp]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<longleftrightarrow> a \\<sim> (b::'a::equiv)\"\n  using eqv_class_eqI eqv_class_eqD by blast\n\n\nsubsection \\<open>Picking representing elements\\<close>\n\ndefinition pick :: \"'a::partial_equiv quot \\<Rightarrow> 'a\"\n  where \"pick A = (SOME a. A = \\<lfloor>a\\<rfloor>)\"\n\ntheorem pick_eqv' [intro?, simp]: \"a \\<in> domain \\<Longrightarrow> pick \\<lfloor>a\\<rfloor> \\<sim> a\"\nproof (unfold pick_def)\n  assume a: \"a \\<in> domain\"\n  show \"(SOME x. \\<lfloor>a\\<rfloor> = \\<lfloor>x\\<rfloor>) \\<sim> a\"\n  proof (rule someI2)\n    show \"\\<lfloor>a\\<rfloor> = \\<lfloor>a\\<rfloor>\" ..\n    fix x assume \"\\<lfloor>a\\<rfloor> = \\<lfloor>x\\<rfloor>\"\n    from this and a have \"a \\<sim> x\" ..\n    then show \"x \\<sim> a\" ..\n  qed\nqed\n\ntheorem pick_eqv [intro, simp]: \"pick \\<lfloor>a\\<rfloor> \\<sim> (a::'a::equiv)\"\nproof (rule pick_eqv')\n  show \"a \\<in> domain\" ..\nqed\n\ntheorem pick_inverse: \"\\<lfloor>pick A\\<rfloor> = (A::'a::equiv quot)\"\nproof (cases A)\n  fix a assume a: \"A = \\<lfloor>a\\<rfloor>\"\n  then have \"pick A \\<sim> a\" by simp\n  then have \"\\<lfloor>pick A\\<rfloor> = \\<lfloor>a\\<rfloor>\" by simp\n  with a show ?thesis by simp\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/PER.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.8740772400852111, "lm_q1q2_score": 0.7669824858403463}}
{"text": "theory Basel_Sum_Approx\n  imports \"HOL.Transcendental\" \"HOL-Analysis.Interval_Integral\"\nbegin\n\ntext \\<open>Inspired by Integral_Test.sum_integral_diff_series_nonneg.\\<close>\nlemma riemann_approx:\n  fixes f :: \"real \\<Rightarrow> real\"\n  assumes \"\\<And>x y. x \\<ge> a \\<Longrightarrow> y \\<le> b \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  assumes \"continuous_on {a..b} f\"\n  assumes \"a \\<le> b\"\n  shows \"(\\<Sum>k=a+1..b. f (of_int k)) \\<le> integral {a..b} f\" (is \"?L \\<le> ?R\")\nproof -\n  note int = integrable_continuous_real[OF continuous_on_subset[OF assms(2)]]\n  obtain j :: nat where m_def: \"b = a + int j\" \n    using zle_iff_zadd assms(3) by blast\n\n  have \"integral {a..a+int j} f = (\\<Sum>k=a+1..a+int j. integral {k-1..k} f)\" if \"a + int j \\<le> b\" for j\n    using that\n  proof (induction j)\n    case 0\n    then show ?case by simp\n  next\n    case (Suc j)\n    have \"integral {a..a+int (Suc j)} f = integral {a..a+int j} f + integral {a+int j..a+int (Suc j)} f\"\n      using Suc(2) by (intro integral_combine[symmetric] int) auto \n    also have \"... = (\\<Sum>k=a+1..a+ int j. integral {k-1..k} f) + integral {a+int j..a+int (Suc j)} f\"\n      using Suc(2) by (intro arg_cong2[where f=\"(+)\"] Suc(1)) auto\n    also have \"... = (\\<Sum>k \\<in> insert (a+int (Suc j)) {a+1..a+ int j}. integral {k-1..k} f)\"\n      by simp\n    also have \"... = (\\<Sum>k \\<in> {a+1..a+ int (Suc j)}. integral {k-1..k} f)\"\n      by (intro sum.cong) auto\n    finally show ?case by simp\n  qed\n  hence a:\"integral {a..b} f = (\\<Sum>k=a+1..b. integral {k-1..k} f)\"\n    using m_def by simp\n\n  have \"?L = (\\<Sum>k=a+1..b. integral {k-1..k} (\\<lambda>_. f (of_int k)))\"\n    by simp\n  also have \"... \\<le> (\\<Sum>k=a+1..b. integral {k-1..k} f)\"\n    using assms by (intro sum_mono integral_le int) auto\n  also have \"... = ?R\"\n    using a by simp\n  finally show ?thesis by simp\nqed\n\nlemma basel_sum: \n  assumes \"k > 0\"\n  shows \"(\\<Sum>y\\<in>{k+1..m}. 1 / real y^2) \\<le> 1/real k\" (is \"?L \\<le> ?R\")\nproof (cases \"m \\<ge> k\")\n  case True\n  have \"?L = (\\<Sum>y\\<in>int ` {k+1..m}. 1 / real_of_int y^2)\"\n    by (subst sum.reindex) auto\n  also have \"... = (\\<Sum>y\\<in>{int k+1..int m}. 1 / real_of_int y^2)\"\n    using image_int_atLeastAtMost by (intro sum.cong refl)  auto\n  also have \"... \\<le> integral {int k..int m} (\\<lambda>y. 1 / y^2)\"\n    using assms True by (intro riemann_approx frac_le power_mono continuous_intros) auto\n  also have \"... \\<le> integral {real k..real m} (\\<lambda>y. 1 / y^2)\"\n    by simp\n  also have \"... = (-(1/m))-(-(1/k))\"\n    using assms True has_real_derivative_iff_has_vector_derivative[symmetric]\n    by (intro integral_unique[OF fundamental_theorem_of_calculus] of_nat_mono True)\n     (auto intro!:derivative_eq_intros simp add:power2_eq_square)\n  also have \"... \\<le> 1/k\"\n    by simp\n  finally show ?thesis by simp\nnext\n  case False\n  thus ?thesis by simp\nqed\n\nend", "meta": {"author": "ekarayel", "repo": "distributed-distinct-elements-formalization", "sha": "0fe0146cfb86bcfa79957e46d243426e6c5cea4e", "save_path": "github-repos/isabelle/ekarayel-distributed-distinct-elements-formalization", "path": "github-repos/isabelle/ekarayel-distributed-distinct-elements-formalization/distributed-distinct-elements-formalization-0fe0146cfb86bcfa79957e46d243426e6c5cea4e/Distributed_Distinct_Elements/unused/Basel_Sum_Approx.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.766959015608251}}
{"text": "theory Fib\nimports Main\nbegin\n\nsubsection \"Basic Functions\"\n\ntext \\<open>This set of basic functions assumes that the function to be tabulated (\\<open>f\\<close>)\nhas type \\<open>nat \\<Rightarrow> nat\\<close>. This needs to be adjusted for other types.\nIn the worst case one may have to redefine these basic functions on the fly\nto suit particular \\<open>f\\<close>'s.\\<close>\n\ntype_synonym tab = \"nat \\<Rightarrow> nat option\"\n\ntext \\<open>Defined to avoid \\<open>\\<noteq> None\\<close> because that gets modified by the standard\nsimplifier and rule setup.\\<close>\ndefinition is_None :: \"'a option \\<Rightarrow> bool\" where\n\"is_None x = (x = None)\"\n\ntext \\<open>Partial correctness of table wrt function:\\<close>\ndefinition pcorrect :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> tab \\<Rightarrow> bool\" where\n\"pcorrect f t = (\\<forall>i. \\<not> is_None (t i) \\<longrightarrow> the(t i) = f i)\"\n\nlemma pcorrect_upd:\n  \"pcorrect f t \\<Longrightarrow> m = f n \\<Longrightarrow> pcorrect f (t(n := Some m))\"\nby (simp add: pcorrect_def)\n\nlemma pcorrect_not_None:\n  \"pcorrect f t \\<Longrightarrow> m = f n \\<Longrightarrow> \\<not> is_None (t n) \\<Longrightarrow> (t n = Some m) = True\"\nby(auto simp add: pcorrect_def is_None_def)\n\nlemma map_le_updR: \"t \\<subseteq>\\<^sub>m t' \\<Longrightarrow> is_None (t n) \\<Longrightarrow> t \\<subseteq>\\<^sub>m t'(n \\<mapsto> m)\"\nby (metis is_None_def fun_upd_triv map_le_imp_upd_le)\n\nlemma map_le_id_upR: \"pcorrect f t \\<Longrightarrow> f n = m \\<Longrightarrow> t \\<subseteq>\\<^sub>m t(n \\<mapsto> m)\"\napply(simp add: pcorrect_def)\nby (metis fun_upd_triv map_le_imp_upd_le map_le_refl map_le_updR option.exhaust_sel)\n\nsubsection \"Application fib\"\n\nfun fib :: \"nat \\<Rightarrow> nat\" where\n\"fib 0 = 0\" |\n\"fib (Suc 0) = 1\" |\n\"fib (Suc(Suc n)) = fib(Suc n) + fib n\"\n\nfun fib' :: \"nat \\<Rightarrow> tab \\<Rightarrow> tab\" where\n\"fib' 0 t = (if is_None (t 0) then t(0 := Some 0) else t)\" |\n\"fib' (Suc 0) t = (if is_None (t 1) then t(1 := Some 1) else t)\" |\n\"fib' (Suc(Suc n)) t = (if is_None(t (Suc(Suc n))) then\n   let t1 = fib' (Suc n) t; t2 = fib' n t1\n   in t2((Suc(Suc n)) := Some(the(t1(Suc n)) + the(t2 n))) else t)\"\n\ntext \\<open>A first proof where the proposition consists of 3 conjuncts:\\<close>\n\nlemma fib'_correct_aux: \"pcorrect fib t \\<Longrightarrow>\n  t \\<subseteq>\\<^sub>m fib' n t \\<and> pcorrect fib (fib' n t) \\<and> fib' n t n = Some(fib n)\"\nproof(induction n arbitrary: t rule: fib.induct)\n  case 1\n  show ?case (is \"?A \\<and> ?B \\<and> ?C\")\n  proof (intro conjI)\n    show ?A using 1 by (simp add: map_le_id_upR del: fun_upd_apply)\n    show ?B using 1 by(simp add: pcorrect_upd del: fun_upd_apply)\n    show ?C using 1 using [[simp_depth_limit=3]] by (simp add: pcorrect_not_None)\n  qed\nnext\n  case 2\n  show ?case (is \"?A \\<and> ?B \\<and> ?C\")\n  proof (intro conjI)\n    show ?A using 2 by (simp add: map_le_id_upR del: fun_upd_apply)\n    show ?B using 2 by(simp add: pcorrect_upd del: fun_upd_apply)\n    show ?C using 2 using [[simp_depth_limit=3]] by (simp add: pcorrect_not_None)\n  qed\nnext\n  case (3 n)\n  note IH1 = \"3.IH\"(1)[OF \"3.prems\"]\n  note IH2 = \"3.IH\"(2)[OF conjunct1[OF conjunct2[OF IH1]]]\n  note map_le = map_le_trans[OF conjunct1[OF IH1] conjunct1[OF IH2]]\n  note pcorr = conjunct1 [OF conjunct2[OF IH2]]\n  note result1 = conjunct2 [OF conjunct2[OF IH1]]\n  note result2 = conjunct2 [OF conjunct2[OF IH2]]\n  show ?case (is \"?A \\<and> ?B \\<and> ?C\")\n  proof (intro conjI)\n    show ?A apply (auto simp: Let_def)\n      by(erule map_le_updR[OF map_le])\n    show ?B using \"3.prems\"\n      apply(auto simp: result1 result2 Let_def)\n      apply(rule pcorrect_upd[OF pcorr])\n      apply simp\n      done\n    show ?C using \"3.prems\"\n      by (simp add: result1 result2 Let_def pcorrect_not_None)\n  qed\nqed\n\ncorollary fib'_correct: \"fib' n empty n = Some(fib n)\"\nusing fib'_correct_aux[of empty n]\nby(simp add: pcorrect_def is_None_def)\n\ntext \\<open>Second proof where parts of the main proposition are hidden in a definition:\\<close>\n\ndefinition correct_tab :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> tab \\<Rightarrow> tab \\<Rightarrow> bool\" where\n\"correct_tab f t t' = (t \\<subseteq>\\<^sub>m t' \\<and> pcorrect f t')\"\n\nlemma pcorrect_if_correct_tab: \"correct_tab f t t' \\<Longrightarrow> pcorrect f t'\"\nby(simp add: correct_tab_def)\n\nlemma correct_tab_id:\n  \"pcorrect f t \\<Longrightarrow> correct_tab f t t\"\nby(auto simp: correct_tab_def)\n\nlemma correct_tab_upd1:\n  \"pcorrect f t \\<Longrightarrow> f n = m \\<Longrightarrow> correct_tab f t (t(n \\<mapsto> m))\"\nby(auto simp: correct_tab_def map_le_id_upR pcorrect_upd)\n\nlemma correct_tab_upd2:\n  \"\\<lbrakk> pcorrect f t; correct_tab f t t'; f n = m \\<rbrakk>\n  \\<Longrightarrow> correct_tab f t (t'(n \\<mapsto> m))\"\nby (meson correct_tab_def map_le_id_upR map_le_trans pcorrect_upd)\n\nlemma correct_tab_trans:\n  \"correct_tab f t t' \\<Longrightarrow> correct_tab f t' t'' \\<Longrightarrow> correct_tab f t t''\"\nby(auto simp: correct_tab_def intro: map_le_trans)\n\nlemma fib'_correct_aux2: \"pcorrect fib t \\<Longrightarrow>\n  correct_tab fib t (fib' n t) \\<and> fib' n t n = Some(fib n)\"\nproof(induction n arbitrary: t rule: fib.induct)\n  case 1\n  show ?case\n    using 1 by (simp add: correct_tab_id correct_tab_upd1 pcorrect_not_None)\nnext\n  case 2\n  show ?case\n    using 2 by (simp add: correct_tab_id correct_tab_upd1 pcorrect_not_None)\nnext\n  case 3\n  note IH1 = \"3.IH\"(1)[OF \"3.prems\"]\n  note corrtab1 = conjunct1[OF IH1]\n  note IH2 = \"3.IH\"(2)[OF pcorrect_if_correct_tab[OF corrtab1]]\n  note corrtab2 = conjunct1[OF IH2]\n  note corrtab12 = correct_tab_trans[OF corrtab1 corrtab2]\n  note results = conjunct2[OF IH1] conjunct2[OF IH2]\n  show ?case\n    apply(auto simp: correct_tab_id[OF \"3.prems\"] pcorrect_not_None[OF \"3.prems\"] results Let_def)\n    apply(rule correct_tab_upd2[OF \"3.prems\" corrtab12])\n    by (simp add: results)\nqed\n\ncorollary fib'_correct2: \"fib' n empty n = Some(fib n)\"\nusing fib'_correct_aux2[of empty n]\nby(simp add: pcorrect_def is_None_def)\n\nend", "meta": {"author": "exprosic", "repo": "praktikum-dp", "sha": "eea935077c34f238dd60436a0ba772f309f83a21", "save_path": "github-repos/isabelle/exprosic-praktikum-dp", "path": "github-repos/isabelle/exprosic-praktikum-dp/praktikum-dp-eea935077c34f238dd60436a0ba772f309f83a21/Fib.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7669213647705733}}
{"text": "(*<*)\ntheory hw08bonustmpl\n  imports\n    Main\n    \"HOL-Data_Structures.Tree23_Set\"\nbegin\n(*>*)\n\nfun join :: \"'a tree23 \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a up\\<^sub>i\"\nwhere\n  \"join Leaf Leaf = T\\<^sub>i Leaf\"\n| \"join (Node2 t1 a t2) (Node2 t3 b t4) = (\n    case (join t2 t3) of\n      T\\<^sub>i t23 \\<Rightarrow> T\\<^sub>i (Node3 t1 a t23 b t4)\n    | Up\\<^sub>i t2' x t3' \\<Rightarrow> Up\\<^sub>i (Node2 t1 a t2') x (Node2 t3' b t4)\n  )\"\n| \"join (Node2 t1 a t2) (Node3 t3 b t4 c t5) = (\n    case (join t2 t3) of\n      T\\<^sub>i t23 \\<Rightarrow> Up\\<^sub>i (Node2 t1 a t23) b (Node2 t4 c t5)\n    | Up\\<^sub>i t2' x t3' \\<Rightarrow> Up\\<^sub>i (Node2 t1 a t2') x (Node3 t3' b t4 c t5)\n)\"\n| \"join (Node3 t1 a t2 b t3) (Node2 t4 c t5) = (\n    case (join t3 t4) of\n      T\\<^sub>i t34 \\<Rightarrow> Up\\<^sub>i (Node2 t1 a t2) b (Node2 t34 c t5)\n    | Up\\<^sub>i t3' x t4' \\<Rightarrow> Up\\<^sub>i (Node2 t1 a t2) b (Node3 t3' x t4' c t5)\n)\"\n| \"join (Node3 t1 a t2 b t3) (Node3 t4 c t5 d t6) = (\n    case (join t3 t4) of\n      T\\<^sub>i t34 \\<Rightarrow> Up\\<^sub>i (Node2 t1 a t2) b (Node3 t34 c t5 d t6)\n    | Up\\<^sub>i t3' x t4' \\<Rightarrow> Up\\<^sub>i (Node3 t1 a t2 b t3') x (Node3 t4' c t5 d t6)\n)\"\n| \"join _ _ = T\\<^sub>i Leaf\"\n\n\nfun del' :: \"'a::linorder \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a up\\<^sub>d\" where\n  \"del' x Leaf = T\\<^sub>d Leaf\"\n| \"del' x (Node2 Leaf a Leaf) = (if (x = a) then (Up\\<^sub>d Leaf) else T\\<^sub>d(Node2 Leaf a Leaf))\"\n| \"del' x (Node3 Leaf a Leaf b Leaf) = T\\<^sub>d(if x = a then Node2 Leaf b Leaf else\n     if x = b then Node2 Leaf a Leaf\n     else Node3 Leaf a Leaf b Leaf)\"\n| \"del' x (Node2 l a r) =  (case cmp x a of\n     LT \\<Rightarrow> node21 (del' x l) a r |\n     GT \\<Rightarrow> node22 l a (del' x r) |\n     EQ \\<Rightarrow>  T\\<^sub>d(tree\\<^sub>i(join l r)))\"\n|\"del' x (Node3 l a m b r) =\n  (case cmp x a of\n     LT \\<Rightarrow> node31 (del' x l) a m b r |\n     EQ \\<Rightarrow>  T\\<^sub>d(Node2 tree\\<^sub>i((join (l m)::'a tree23) d r)) |\n     GT \\<Rightarrow>\n       (case cmp x b of\n          LT \\<Rightarrow> node32 l a (del x m) b r |\n          EQ \\<Rightarrow> let (b',r') = del_min r in node33 l a m b' r' |\n          GT \\<Rightarrow> node33 l a m b (del x r)))\"\n\n\nfun del :: \"'a::linorder \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a up\\<^sub>d\" where\n\"del x Leaf = T\\<^sub>d Leaf\" |\n\"del x (Node2 Leaf a Leaf) =\n  (if x = a then Up\\<^sub>d Leaf else T\\<^sub>d(Node2 Leaf a Leaf))\" |\n\"del x (Node3 Leaf a Leaf b Leaf) =\n  T\\<^sub>d(if x = a then Node2 Leaf b Leaf else\n     if x = b then Node2 Leaf a Leaf\n     else Node3 Leaf a Leaf b Leaf)\" |\n\"del x (Node2 l a r) =\n  (case cmp x a of\n     LT \\<Rightarrow> node21 (del x l) a r |\n     GT \\<Rightarrow> node22 l a (del x r) |\n     EQ \\<Rightarrow> let (a',t) = del_min r in node22 l a' t)\" |\n\"del x (Node3 l a m b r) =\n  (case cmp x a of\n     LT \\<Rightarrow> node31 (del x l) a m b r |\n     EQ \\<Rightarrow> let (a',m') = del_min m in node32 l a' m' b r |\n     GT \\<Rightarrow>\n       (case cmp x b of\n          LT \\<Rightarrow> node32 l a (del x m) b r |\n          EQ \\<Rightarrow> let (b',r') = del_min r in node33 l a m b' r' |\n          GT \\<Rightarrow> node33 l a m b (del x r)))\"\n\n(* These are the two essential lemmas needed to instantiate the\n  set_by_ordered infrastructure with the new del function:\n\n  (You're not required to repeat the instantiation proof, just these two lemmas are enough. )\n*)\nlemma inorder_del': \"\\<lbrakk> bal t ; sorted(inorder t) \\<rbrakk> \\<Longrightarrow>\n  inorder(tree\\<^sub>d (del' x t)) = del_list x (inorder t)\"\n  sorry\n\nlemma bal_tree\\<^sub>d_del: \"bal t \\<Longrightarrow> bal(tree\\<^sub>d(del' x t))\"\n  sorry\n\ntext \\<open>A few hints:\n  \\<^item> Prove auxiliary lemmas on \\<open>join\\<close> that are suitable to discharge your proof obligations, and\n    disable simplification of join for your main proof (\\<open>declare join.simps[simp del]\\<close>).\n    This will make proof obligations more readable.\n  \\<^item> Case splitting by \\<open>simp\\<close> or \\<open>auto\\<close> may take quite a long time.\n    Use \\<open>split!:\\<close> instead of \\<open>split:\\<close> to make it a bit faster.\n\n\\<close>\n\n\n(* In case you are interested how to instantiate the infrastructure with\n  the new delete function: *)\n\ndefinition delete' :: \"'a::linorder \\<Rightarrow> 'a tree23 \\<Rightarrow> 'a tree23\" where\n  \"delete' x t = tree\\<^sub>d(del' x t)\"\n\n\ninterpretation Set_by_Ordered\nwhere empty = Leaf and isin = isin and insert = insert and delete = delete'\nand inorder = inorder and inv = bal\nproof (standard, goal_cases)\n  case 2 thus ?case by(simp add: isin_set)\nnext\n  case 3 thus ?case by(simp add: inorder_insert)\nnext\n  case 4 thus ?case by(simp add: delete'_def inorder_del')\nnext\n  case 6 thus ?case by(simp add: bal_insert)\nnext\n  case 7 thus ?case by(simp add: delete'_def bal_tree\\<^sub>d_del)\nqed simp+\n\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "amartyads", "repo": "functional-data-structures-HW", "sha": "df9edfd02bda931a0633f0e66bf8e32d7347902b", "save_path": "github-repos/isabelle/amartyads-functional-data-structures-HW", "path": "github-repos/isabelle/amartyads-functional-data-structures-HW/functional-data-structures-HW-df9edfd02bda931a0633f0e66bf8e32d7347902b/08/hw08bonustmpl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.870597265050901, "lm_q2_score": 0.880797081106935, "lm_q1q2_score": 0.7668195298765142}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Weight-Balanced Trees Have Logarithmic Height\\<close>\n\ntext \\<open>This theory is based on the original definition of weight-balanced trees\n\\cite{NievergeltR72,NievergeltR73}\nwhere the size of the child of a node must be a minimum and a maximum fraction\nof the size of the node.\\<close>\n\ntheory Weight_Balanced_Trees_log\nimports\n  Complex_Main\n  \"HOL-Library.Tree\"\nbegin\n\n(* FIXME mod field_simps *)\nlemmas neq0_if = less_imp_neq dual_order.strict_implies_not_eq\n\nlocale WBT0 =\nfixes \\<alpha> :: real\nassumes alpha_pos: \"0 < \\<alpha>\" and alpha_ub: \"\\<alpha> \\<le> 1/2\"\nbegin\n\nfun wbt :: \"'a tree \\<Rightarrow> bool\" where\n\"wbt Leaf = True\" |\n\"wbt (Node l _ r) = (wbt l \\<and> wbt r \\<and> (let ratio = size1 l / (size1 l + size1 r)\n  in \\<alpha> \\<le> ratio \\<and> ratio \\<le> 1 - \\<alpha>))\"\n\nlemma height_size1_exp:\n  \"wbt t \\<Longrightarrow> t \\<noteq> Leaf \\<Longrightarrow> 2 \\<le> (1-\\<alpha>) ^ (height t - 1) * size1 t\"\nproof(induction  t)\n  case Leaf thus ?case by simp\nnext\n  case (Node l a r)\n  have 0: \"0 \\<le> (1 - \\<alpha>) ^ k\" for k using alpha_ub by simp\n  let ?t = \"Node l a r\" let ?s = \"size1 ?t\"\n  from Node.prems(1) have 1: \"size1 l \\<le> (1-\\<alpha>) * ?s\" and 2: \"size1 r \\<le> (1-\\<alpha>) * ?s\"\n    by (auto simp: Let_def field_simps add_pos_pos neq0_if)\n  show ?case\n  proof (cases \"l = Leaf \\<and> r = Leaf\")\n    case True thus ?thesis by simp\n  next\n    case not_Leafs: False\n    show ?thesis\n    proof (cases \"height l \\<le> height r\")\n      case hlr: True\n      hence r: \"r \\<noteq> Leaf\" and hr: \"height r \\<noteq> 0\" using not_Leafs by (auto)\n      have \"2 \\<le> (1-\\<alpha>) ^ (height r - 1) * size1 r\"\n        using Node.IH(2)[OF _ r] Node.prems by simp\n      also have \"\\<dots> \\<le> (1-\\<alpha>) ^ (height r - 1) * ((1-\\<alpha>) * ?s)\"\n        by(rule mult_left_mono[OF 2 0])\n      also have \"\\<dots> = (1-\\<alpha>) ^ (height r - 1 + 1) * ?s\" by simp\n      also have \"\\<dots> = (1-\\<alpha>) ^ (height r) * ?s\"\n        using hr by (auto simp del: eq_height_0)\n      finally show ?thesis using hlr by (simp)\n    next\n      case hlr: False\n      hence l: \"l \\<noteq> Leaf\" and hl: \"height l \\<noteq> 0\" using not_Leafs by (auto)\n      have \"2 \\<le> (1-\\<alpha>) ^ (height l - 1) * size1 l\"\n        using Node.IH(1)[OF _ l] Node.prems by simp\n      also have \"\\<dots> \\<le> (1-\\<alpha>) ^ (height l - 1) * ((1-\\<alpha>) * ?s)\"\n        by(rule mult_left_mono[OF 1 0])\n      also have \"\\<dots> = (1-\\<alpha>) ^ (height l - 1 + 1) * ?s\" by simp\n      also have \"\\<dots> = (1-\\<alpha>) ^ (height l) * ?s\"\n        using hl by (auto simp del: eq_height_0)\n      finally show ?thesis using hlr by (simp)\n    qed\n  qed\nqed\n\nlemma height_size1_log: assumes \"wbt t\" \"t \\<noteq> Leaf\"\nshows \"height t \\<le> (log 2 (size1 t) - 1) / log 2 (1/(1-\\<alpha>)) + 1\"\nproof -\n  have \"1 \\<le> log 2 ((1-\\<alpha>) ^ (height t - 1) * size1 t)\"\n    using height_size1_exp[OF assms] by simp\n  hence \"1 \\<le> log 2 ((1-\\<alpha>) ^ (height t - 1)) + log 2 (size1 t)\"\n    using alpha_ub by(simp add: log_mult)\n  hence \"1 \\<le> (height t - 1) * log 2 (1-\\<alpha>) + log 2 (size1 t)\"\n    using alpha_ub by(simp add: log_nat_power)\n  hence \"- (height t - 1) * log 2 (1-\\<alpha>) \\<le> log 2 (size1 t) - 1\"\n    by(simp add: algebra_simps)\n  hence \"(height t - 1) * log 2 (1/(1-\\<alpha>)) \\<le> log 2 (size1 t) - 1\"\n    using alpha_ub by(simp add: log_divide)\n  hence \"height t - 1 \\<le> (log 2 (size1 t) - 1) / log 2 (1/(1-\\<alpha>))\"\n    using alpha_pos alpha_ub by(simp add: field_simps log_divide)\n  thus ?thesis by(simp)\nqed\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Weight_Balanced_Trees/Weight_Balanced_Trees_log.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7667781912267794}}
{"text": "(*\nAuction Theory Toolbox (http://formare.github.io/auctions/)\n\nAuthors:\n* Marco B. Caminati http://caminati.co.nr\n* Manfred Kerber <mnfrd.krbr@gmail.com>\n* Christoph Lange <math.semantic.web@gmail.com>\n* Colin Rowat <c.rowat@bham.ac.uk>\n\n\nDually licenced under\n* Creative Commons Attribution (CC-BY) 3.0\n* ISC License (1-clause BSD License)\nSee LICENSE file for details\n(Rationale for this dual licence: http://arxiv.org/abs/1107.3212)\n*)\n\nsection \\<open>Locus where a function or a list (of linord type) attains its maximum value\\<close>\n\ntheory Argmax\nimports Main\n\nbegin\n\ntext \\<open>Structural induction is used in proofs on lists.\\<close>\nlemma structInduct: assumes \"P []\" and \"\\<forall>x xs. P (xs) \\<longrightarrow> P (x#xs)\" \n                    shows \"P l\" \n      using assms list_nonempty_induct by (metis)\n\ntext \\<open>the subset of elements of a set where a function reaches its maximum\\<close>\nfun argmax :: \"('a \\<Rightarrow> 'b::linorder) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n    where \"argmax f A = { x \\<in> A . f x = Max (f ` A) }\"\n\n(* For reasons we do not understand we have to duplicate the definition as a lemma \n   in order to prove lm16 in CombinatorialAuctions.thy. *)\nlemma argmaxLemma: \"argmax f A = { x \\<in> A . f x = Max (f ` A) }\" \n  by simp\n\nlemma maxLemma: \n  assumes \"x \\<in> X\" \"finite X\" \n  shows \"Max (f`X) >= f x\" \n  (is \"?L >= ?R\") using assms \n  by (metis (opaque_lifting, no_types) Max.coboundedI finite_imageI image_eqI)\n\nlemma lm01: \n  \"argmax f A = A \\<inter> f -` {Max (f ` A)}\" \n  by force\n\nlemma lm02: \n  assumes \"y \\<in> f`A\" \n  shows \"A \\<inter> f -` {y} \\<noteq> {}\" \n  using assms by blast\n\nlemma argmaxEquivalence: \n  assumes \"\\<forall>x\\<in>X. f x = g x\" \n  shows \"argmax f X = argmax g X\" \n  using assms argmaxLemma Collect_cong image_cong \n  by (metis(no_types,lifting))\n\ntext \\<open>The arg max of a function over a non-empty set is non-empty.\\<close>\ncorollary argmax_non_empty_iff: assumes \"finite X\" \"X \\<noteq> {}\" \n                                shows \"argmax f X \\<noteq>{}\"\n                                using assms Max_in finite_imageI image_is_empty lm01 lm02 \n                                by (metis(no_types))\n\ntext \\<open>The previous definition of argmax operates on sets. In the following we define a corresponding notion on lists. To this end, we start with defining a filter predicate and are looking for the elements of a list satisfying a given predicate;\nbut, rather than returning them directly, we return the (sorted) list of their indices. \nThis is done, in different ways, by @{term filterpositions} and @{term filterpositions2}.\\<close>\n\n(* Given a list l, filterpositions yields the indices of its elements which satisfy a given pred P*)\ndefinition filterpositions :: \"('a => bool) => 'a list => nat list\"\n           where \"filterpositions P l = map snd (filter (P o fst) (zip l (upt 0 (size l))))\"\n(* That is, you take the list [a0, a1, ..., an] pair with the indices [0, 1, ..., n], i.e., you get\n   [(a0,0), (a1,1), ..., (an,n)] look where the predicate (P o fst) holds and return the list of the\n   corresponding snd elements. *)\n\n\n(* Alternative definition, making use of list comprehension. In the next line the type info is\n   commented out, since the type inference can be left to Isabelle. *)\ndefinition filterpositions2 (*  :: \"('a => bool) => 'a list => nat list\" *)\n           where \"filterpositions2 P l = [n. n \\<leftarrow> [0..<size l], P (l!n)]\"\n\ndefinition maxpositions (*:: \"'a::linorder list => nat list\"*) \n           where \"maxpositions l = filterpositions2 (%x . x \\<ge> Max (set l)) l\"\n\nlemma lm03: \"maxpositions l = [n. n\\<leftarrow>[0..<size l], l!n \\<ge> Max(set l)]\" \n      unfolding maxpositions_def filterpositions2_def by fastforce\n\n(* argmaxList takes a function and a list as arguments and looks for the positions of the elements at which the function applied to the list element is maximal, e.g., \nfor the list [9, 3, 5, 9, 13] and the function `modulo 8', the function applied to the list would give the list [1, 3, 5, 1, 5], that is, argmaxList will return [2, 4]. *)\ndefinition argmaxList (*:: \"('a => ('b::linorder)) => 'a list => 'a list\"*)\n           where \"argmaxList f l = map (nth l) (maxpositions (map f l))\"\n\n(* The following lemmas state some relationships between different representation such as map and list comprehension *)\nlemma lm04: \"[n . n <- l, P n] = [n . n <- l, n \\<in> set l, P n]\" \nproof - \n(*sledgehammer-generated proof. \n  Commented out the first three lines (they look quite useless), making it more readable. \n  assume \"\\<forall>v0. SMT2.fun_app uu__ v0 = (if P v0 then [v0] else [])\"\n  assume \"\\<forall>v0. SMT2.fun_app uua__ v0 = (if v0 \\<in> set l then if P v0 then [v0] else [] else [])\" \n  obtain v3_0 :: \"('a \\<Rightarrow> 'a list) \\<Rightarrow> 'a list \\<Rightarrow> ('a \\<Rightarrow> 'a list) \\<Rightarrow> 'a\" where *) \n  have \"map (\\<lambda>uu. if P uu then [uu] else []) l = \n    map (\\<lambda>uu. if uu \\<in> set l then if P uu then [uu] else [] else []) l\" by simp\n  thus \"concat (map (\\<lambda>n. if P n then [n] else []) l) = \n    concat (map (\\<lambda>n. if n \\<in> set l then if P n then [n] else [] else []) l)\" by presburger\nqed\n\nlemma lm05: \"[n . n <- [0..<m], P n] = [n . n <- [0..<m], n \\<in> set [0..<m], P n]\" \n      using lm04 by fast\n (* sledgehammer suggested:  concat_map_singleton map_ident  map_ext by smt*)\n\nlemma lm06: fixes f m P \n            shows \"(map f [n . n <- [0..<m], P n]) = [ f n . n <- [0..<m], P n]\" \n      by (induct m) auto\n\n(* Base case stating the property for the empty list *)\nlemma map_commutes_a: \"[f n . n <- [], Q (f n)] = [x <- (map f []). Q x]\" \n      by simp\n\n(* Step case where the element x is added to the list xs *)\nlemma map_commutes_b: \"\\<forall> x xs. ([f n . n <- xs,     Q (f n)] = [x <- (map f xs).     Q x] \\<longrightarrow> \n                                [f n . n <- (x#xs), Q (f n)] = [x <- (map f (x#xs)). Q x])\" \n      by simp\n\n(* General case comprising the two previous cases. *)\nlemma map_commutes: fixes f::\"'a => 'b\" fixes Q::\"'b => bool\" fixes xs::\"'a list\" \n                    shows \"[f n . n <- xs, Q (f n)] = [x <- (map f xs). Q x]\"\n      using map_commutes_a map_commutes_b structInduct by fast\n\nlemma lm07: fixes f l \n            shows \"maxpositions (map f l) = \n                   [n . n <- [0..<size l], f (l!n) \\<ge> Max (f`(set l))]\" \n            (is \"maxpositions (?fl) = _\") (* Pattern matching abbreviation ?fl corresponds to (map f l). Used in the proof, not part of lemma itself *)\nproof -\n  have \"maxpositions ?fl = \n  [n. n <- [0..<size ?fl], n\\<in> set[0..<size ?fl], ?fl!n \\<ge> Max (set ?fl)]\"\n  using lm04 unfolding filterpositions2_def maxpositions_def .\n  also have \"... = \n  [n . n <- [0..<size l], (n<size l), (?fl!n  \\<ge> Max (set ?fl))]\" by simp\n  also have \"... = \n  [n . n <- [0..<size l], (n<size l) \\<and> (f (l!n)  \\<ge> Max (set ?fl))]\" \n  using nth_map by (metis (poly_guards_query, opaque_lifting)) also have \"... = \n  [n . n <- [0..<size l], (n\\<in> set [0..<size l]),(f (l!n)  \\<ge> Max (set ?fl))]\" \n  using atLeastLessThan_iff le0 set_upt by (metis(no_types))\n  also have \"... =  \n  [n . n <- [0..<size l], f (l!n) \\<ge> Max (set ?fl)]\" using lm05 by presburger \n  finally show ?thesis by auto\nqed\n\nlemma lm08: fixes f l \n            shows \"argmaxList f l = \n                   [ l!n . n <- [0..<size l], f (l!n) \\<ge> Max (f`(set l))]\"\n      unfolding lm07 argmaxList_def by (metis lm06)\n\ntext\\<open>The theorem expresses that argmaxList is the list of arguments greater equal the Max of the list.\\<close>\n\ntheorem argmaxadequacy: fixes f::\"'a => ('b::linorder)\" fixes l::\"'a list\" \n                        shows \"argmaxList f l = [ x <- l. f x \\<ge> Max (f`(set l))]\"\n                        (is \"?lh=_\") (* pattern match ?lh abbreviates \"argmaxList f l\" *)\nproof -\n  let ?P=\"% y::('b::linorder) . y \\<ge> Max (f`(set l))\"\n  let ?mh=\"[nth l n . n <- [0..<size l], ?P (f (nth l n))]\"\n  let ?rh=\"[ x <- (map (nth l) [0..<size l]). ?P (f x)]\"\n  have \"?lh = ?mh\" using lm08 by fast\n  also have \"... = ?rh\" using map_commutes by fast\n  also have \"...= [x <- l. ?P (f x)]\" using map_nth by metis\n  finally show ?thesis by force\nqed\n\nend\n\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Vickrey_Clarke_Groves/Argmax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278757303677, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7666769635363798}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)\n\nsection \\<open>Lexical order on functions\\<close>\n\ntheory Fun_Lexorder\nimports Main\nbegin\n\ndefinition less_fun :: \"('a::linorder \\<Rightarrow> 'b::linorder) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\nwhere\n  \"less_fun f g \\<longleftrightarrow> (\\<exists>k. f k < g k \\<and> (\\<forall>k' < k. f k' = g k'))\"\n\nlemma less_funI:\n  assumes \"\\<exists>k. f k < g k \\<and> (\\<forall>k' < k. f k' = g k')\"\n  shows \"less_fun f g\"\n  using assms by (simp add: less_fun_def)\n\nlemma less_funE:\n  assumes \"less_fun f g\"\n  obtains k where \"f k < g k\" and \"\\<And>k'. k' < k \\<Longrightarrow> f k' = g k'\"\n  using assms unfolding less_fun_def by blast\n\nlemma less_fun_asym:\n  assumes \"less_fun f g\"\n  shows \"\\<not> less_fun g f\"\nproof\n  from assms obtain k1 where k1: \"f k1 < g k1\" \"\\<And>k'. k' < k1 \\<Longrightarrow> f k' = g k'\"\n    by (blast elim!: less_funE) \n  assume \"less_fun g f\" then obtain k2 where k2: \"g k2 < f k2\" \"\\<And>k'. k' < k2 \\<Longrightarrow> g k' = f k'\"\n    by (blast elim!: less_funE) \n  show False proof (cases k1 k2 rule: linorder_cases)\n    case equal with k1 k2 show False by simp\n  next\n    case less with k2 have \"g k1 = f k1\" by simp\n    with k1 show False by simp\n  next\n    case greater with k1 have \"f k2 = g k2\" by simp\n    with k2 show False by simp\n  qed\nqed\n\nlemma less_fun_irrefl:\n  \"\\<not> less_fun f f\"\nproof\n  assume \"less_fun f f\"\n  then obtain k where k: \"f k < f k\"\n    by (blast elim!: less_funE)\n  then show False by simp\nqed\n\nlemma less_fun_trans:\n  assumes \"less_fun f g\" and \"less_fun g h\"\n  shows \"less_fun f h\"\nproof (rule less_funI)\n  from `less_fun f g` obtain k1 where k1: \"f k1 < g k1\" \"\\<And>k'. k' < k1 \\<Longrightarrow> f k' = g k'\"\n    by (blast elim!: less_funE) \n  from `less_fun g h` obtain k2 where k2: \"g k2 < h k2\" \"\\<And>k'. k' < k2 \\<Longrightarrow> g k' = h k'\"\n    by (blast elim!: less_funE) \n  show \"\\<exists>k. f k < h k \\<and> (\\<forall>k'<k. f k' = h k')\"\n  proof (cases k1 k2 rule: linorder_cases)\n    case equal with k1 k2 show ?thesis by (auto simp add: exI [of _ k2])\n  next\n    case less with k2 have \"g k1 = h k1\" \"\\<And>k'. k' < k1 \\<Longrightarrow> g k' = h k'\" by simp_all\n    with k1 show ?thesis by (auto intro: exI [of _ k1])\n  next\n    case greater with k1 have \"f k2 = g k2\" \"\\<And>k'. k' < k2 \\<Longrightarrow> f k' = g k'\" by simp_all\n    with k2 show ?thesis by (auto intro: exI [of _ k2])\n  qed\nqed\n\nlemma order_less_fun:\n  \"class.order (\\<lambda>f g. less_fun f g \\<or> f = g) less_fun\"\n  by (rule order_strictI) (auto intro: less_fun_trans intro!: less_fun_irrefl less_fun_asym)\n\nlemma less_fun_trichotomy:\n  assumes \"finite {k. f k \\<noteq> g k}\"\n  shows \"less_fun f g \\<or> f = g \\<or> less_fun g f\"\nproof -\n  { def K \\<equiv> \"{k. f k \\<noteq> g k}\"\n    assume \"f \\<noteq> g\"\n    then obtain k' where \"f k' \\<noteq> g k'\" by auto\n    then have [simp]: \"K \\<noteq> {}\" by (auto simp add: K_def)\n    with assms have [simp]: \"finite K\" by (simp add: K_def)\n    def q \\<equiv> \"Min K\"\n    then have \"q \\<in> K\" and \"\\<And>k. k \\<in> K \\<Longrightarrow> k \\<ge> q\" by auto\n    then have \"\\<And>k. \\<not> k \\<ge> q \\<Longrightarrow> k \\<notin> K\" by blast\n    then have *: \"\\<And>k. k < q \\<Longrightarrow> f k = g k\" by (simp add: K_def)\n    from `q \\<in> K` have \"f q \\<noteq> g q\" by (simp add: K_def)\n    then have \"f q < g q \\<or> f q > g q\" by auto\n    with * have \"less_fun f g \\<or> less_fun g f\"\n      by (auto intro!: less_funI)\n  } then show ?thesis by blast\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Fun_Lexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.8688267796346599, "lm_q1q2_score": 0.7666769560987857}}
{"text": "(* Author: Chelsea Edmonds\nTheory: Incidence_Matrices.thy \n*)\n\nsection \\<open> Incidence Vectors and Matrices \\<close>\ntext \\<open>Incidence Matrices are an important representation for any incidence set system. The majority\nof basic definitions and properties proved in this theory are based on Stinson \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>\nand Colbourn \\<^cite>\\<open>\"colbournHandbookCombinatorialDesigns2007\"\\<close>.\\<close>\n\ntheory Incidence_Matrices imports \"Design_Extras\" Matrix_Vector_Extras \"List-Index.List_Index\"\n \"Design_Theory.Design_Isomorphisms\"\nbegin\n\nsubsection \\<open>Incidence Vectors \\<close>\ntext \\<open>A function which takes an ordered list of points, and a block, \nreturning a 0-1 vector $v$ where there is a 1 in the ith position if point i is in that block \\<close>\n\ndefinition inc_vec_of :: \"'a list \\<Rightarrow> 'a set \\<Rightarrow> ('b :: {ring_1}) vec\" where\n\"inc_vec_of Vs bl \\<equiv> vec (length Vs) (\\<lambda> i . if (Vs ! i) \\<in> bl then 1 else 0)\"\n\nlemma inc_vec_one_zero_elems: \"set\\<^sub>v (inc_vec_of Vs bl) \\<subseteq> {0, 1}\"\n  by (auto simp add: vec_set_def inc_vec_of_def)\n\nlemma finite_inc_vec_elems: \"finite (set\\<^sub>v (inc_vec_of Vs bl))\"\n  using finite_subset inc_vec_one_zero_elems by blast\n\nlemma inc_vec_elems_max_two: \"card (set\\<^sub>v (inc_vec_of Vs bl)) \\<le> 2\"\n  using card_mono inc_vec_one_zero_elems finite.insertI card_0_eq card_2_iff\n  by (smt (verit)  insert_absorb2 linorder_le_cases linordered_nonzero_semiring_class.zero_le_one \n      obtain_subset_with_card_n one_add_one subset_singletonD trans_le_add1) \n\nlemma inc_vec_dim: \"dim_vec (inc_vec_of Vs bl) = length Vs\"\n  by (simp add: inc_vec_of_def)\n\nlemma inc_vec_index: \"i < length Vs \\<Longrightarrow> inc_vec_of Vs bl $ i = (if (Vs ! i) \\<in> bl then 1 else 0)\"\n  by (simp add: inc_vec_of_def)\n\nlemma inc_vec_index_one_iff:  \"i < length Vs \\<Longrightarrow> inc_vec_of Vs bl $ i = 1 \\<longleftrightarrow> Vs ! i \\<in> bl\"\n  by (auto simp add: inc_vec_of_def ) \n\nlemma inc_vec_index_zero_iff: \"i < length Vs \\<Longrightarrow> inc_vec_of Vs bl $ i = 0 \\<longleftrightarrow> Vs ! i \\<notin> bl\"\n  by (auto simp add: inc_vec_of_def)\n\nlemma inc_vec_of_bij_betw: \n  assumes \"inj_on f (set Vs)\"\n  assumes \"bl \\<subseteq> (set Vs)\"\n  shows \"inc_vec_of Vs bl = inc_vec_of (map f Vs) (f ` bl)\"\nproof (intro eq_vecI, simp_all add: inc_vec_dim)\n  fix i assume \"i < length Vs\"\n  then have \"Vs ! i \\<in> bl \\<longleftrightarrow> (map f Vs) ! i \\<in> (f ` bl)\"\n    by (metis assms(1) assms(2) inj_on_image_mem_iff nth_map nth_mem)\n  then show \"inc_vec_of Vs bl $ i = inc_vec_of (map f Vs) (f ` bl) $ i\"\n    using inc_vec_index by (metis \\<open>i < length Vs\\<close> length_map) \nqed\n\nsubsection \\<open> Incidence Matrices \\<close>\n\ntext \\<open> A function which takes a list of points, and list of sets of points, and returns \na $v \\times b$ 0-1 matrix $M$, where $v$ is the number of points, and $b$ the number of sets, such \nthat there is a 1 in the i, j position if and only if point i is in block j. The matrix has \ntype @{typ \"('b :: ring_1) mat\"} to allow for operations commonly used on matrices \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>\\<close>\n\ndefinition inc_mat_of :: \"'a list \\<Rightarrow> 'a set list \\<Rightarrow> ('b :: {ring_1}) mat\" where\n\"inc_mat_of Vs Bs \\<equiv> mat (length Vs) (length Bs) (\\<lambda> (i,j) . if (Vs ! i) \\<in> (Bs ! j) then 1 else 0)\"\n\ntext \\<open> Basic lemmas on the @{term \"inc_mat_of\"} matrix result (elements/dimensions/indexing)\\<close>\n\nlemma inc_mat_one_zero_elems: \"elements_mat (inc_mat_of Vs Bs) \\<subseteq> {0, 1}\"\n  by (auto simp add: inc_mat_of_def elements_mat_def)\n\nlemma fin_incidence_mat_elems: \"finite (elements_mat (inc_mat_of Vs Bs))\"\n  using finite_subset inc_mat_one_zero_elems by auto \n\nlemma inc_matrix_elems_max_two: \"card (elements_mat (inc_mat_of Vs Bs)) \\<le> 2\"\n  using inc_mat_one_zero_elems order_trans card_2_iff\n  by (smt (verit, del_insts) antisym bot.extremum card.empty insert_commute insert_subsetI \n      is_singletonI is_singleton_altdef linorder_le_cases not_one_le_zero one_le_numeral  subset_insert) \n\nlemma inc_mat_of_index [simp]: \"i < dim_row (inc_mat_of Vs Bs) \\<Longrightarrow> j < dim_col (inc_mat_of Vs Bs) \\<Longrightarrow> \n  inc_mat_of Vs Bs $$ (i, j) = (if (Vs ! i) \\<in> (Bs ! j) then 1 else 0)\"\n  by (simp add: inc_mat_of_def)\n\nlemma inc_mat_dim_row: \"dim_row (inc_mat_of Vs Bs) = length Vs\"\n  by (simp add: inc_mat_of_def)\n\nlemma inc_mat_dim_vec_row: \"dim_vec (row (inc_mat_of Vs Bs) i) = length Bs\"\n  by (simp add:  inc_mat_of_def)\n\nlemma inc_mat_dim_col: \"dim_col (inc_mat_of Vs Bs) = length Bs\"\n  by (simp add:  inc_mat_of_def)\n\nlemma inc_mat_dim_vec_col: \"dim_vec (col (inc_mat_of Vs Bs) i) = length Vs\"\n  by (simp add:  inc_mat_of_def)\n\nlemma inc_matrix_point_in_block_one: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> Vs ! i \\<in> Bs ! j\n    \\<Longrightarrow> (inc_mat_of Vs Bs) $$ (i, j) = 1\"\n  by (simp add: inc_mat_of_def)   \n\nlemma inc_matrix_point_not_in_block_zero: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> Vs ! i \\<notin> Bs ! j \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0\"\n  by(simp add: inc_mat_of_def)\n\nlemma inc_matrix_point_in_block: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> (inc_mat_of Vs Bs) $$ (i, j) = 1 \n    \\<Longrightarrow> Vs ! i \\<in> Bs ! j\"\n  using inc_matrix_point_not_in_block_zero by (metis zero_neq_one) \n\nlemma inc_matrix_point_not_in_block:  \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0 \\<Longrightarrow> Vs ! i \\<notin> Bs ! j\"\n  using inc_matrix_point_in_block_one by (metis zero_neq_one)\n\nlemma inc_matrix_point_not_in_block_iff:  \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0 \\<longleftrightarrow> Vs ! i \\<notin> Bs ! j\"\n  using inc_matrix_point_not_in_block inc_matrix_point_not_in_block_zero by blast\n\nlemma inc_matrix_point_in_block_iff:  \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow>\n    (inc_mat_of Vs Bs) $$ (i, j) = 1 \\<longleftrightarrow> Vs ! i \\<in> Bs ! j\"\n  using inc_matrix_point_in_block inc_matrix_point_in_block_one by blast\n\nlemma inc_matrix_subset_implies_one: \n  assumes \"I \\<subseteq> {..< length Vs}\"\n  assumes \"j < length Bs\"\n  assumes \"(!) Vs ` I \\<subseteq> Bs ! j\"\n  assumes \"i \\<in> I\"\n  shows \"(inc_mat_of Vs Bs) $$ (i, j) = 1\"\nproof - \n  have iin: \"Vs ! i \\<in> Bs ! j\" using assms(3) assms(4) by auto\n  have \"i < length Vs\" using assms(1) assms(4) by auto\n  thus ?thesis using iin inc_matrix_point_in_block_iff assms(2) by blast  \nqed\n\nlemma inc_matrix_one_implies_membership: \"I \\<subseteq> {..< length Vs} \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (\\<And> i. i\\<in>I \\<Longrightarrow> (inc_mat_of Vs Bs) $$ (i, j) = 1) \\<Longrightarrow> i \\<in> I \\<Longrightarrow> Vs ! i \\<in> Bs ! j\"\n  using inc_matrix_point_in_block subset_iff by blast \n\nlemma inc_matrix_elems_one_zero: \"i < length Vs \\<Longrightarrow> j < length Bs \\<Longrightarrow> \n    (inc_mat_of Vs Bs) $$ (i, j) = 0 \\<or> (inc_mat_of Vs Bs) $$ (i, j) = 1\"\n  using inc_matrix_point_in_block_one inc_matrix_point_not_in_block_zero by blast\n\ntext \\<open>Reasoning on Rows/Columns of the incidence matrix \\<close>\n\nlemma inc_mat_col_def:  \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    (col (inc_mat_of Vs Bs) j) $ i = (if (Vs ! i \\<in> Bs ! j) then 1 else 0)\"\n  by (simp add: inc_mat_of_def) \n\nlemma inc_mat_col_list_map_elem: \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    col (inc_mat_of Vs Bs) j $ i = map_vec (\\<lambda> x . if (x \\<in> (Bs ! j)) then 1 else 0) (vec_of_list Vs) $ i\"\n  by (simp add: inc_mat_of_def index_vec_of_list)\n\nlemma inc_mat_col_list_map:  \"j < length Bs \\<Longrightarrow> \n    col (inc_mat_of Vs Bs) j = map_vec (\\<lambda> x . if (x \\<in> (Bs ! j)) then 1 else 0) (vec_of_list Vs)\"\n  by (intro eq_vecI) \n    (simp_all add: inc_mat_dim_row inc_mat_dim_col inc_mat_col_list_map_elem index_vec_of_list)\n\nlemma inc_mat_row_def: \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    (row (inc_mat_of Vs Bs) i) $ j = (if (Vs ! i \\<in> Bs ! j) then 1 else 0)\"\n  by (simp add: inc_mat_of_def)\n\nlemma inc_mat_row_list_map_elem: \"j < length Bs \\<Longrightarrow> i < length Vs \\<Longrightarrow> \n    row (inc_mat_of Vs Bs) i $ j = map_vec (\\<lambda> bl . if ((Vs ! i) \\<in> bl) then 1 else 0) (vec_of_list Bs) $ j\"\n  by (simp add: inc_mat_of_def vec_of_list_index)\n\nlemma inc_mat_row_list_map: \"i < length Vs \\<Longrightarrow> \n    row (inc_mat_of Vs Bs) i = map_vec (\\<lambda> bl . if ((Vs ! i) \\<in> bl) then 1 else 0) (vec_of_list Bs)\"\n  by (intro eq_vecI) \n    (simp_all add: inc_mat_dim_row inc_mat_dim_col inc_mat_row_list_map_elem index_vec_of_list)\n\ntext \\<open> Connecting @{term \"inc_vec_of\"} and @{term \"inc_mat_of\"} \\<close>\n\nlemma inc_mat_col_inc_vec: \"j < length Bs \\<Longrightarrow> col (inc_mat_of Vs Bs) j = inc_vec_of Vs (Bs ! j)\"\n  by (auto simp add: inc_mat_of_def inc_vec_of_def)\n\nlemma inc_mat_of_cols_inc_vecs: \"cols (inc_mat_of Vs Bs) = map (\\<lambda> j . inc_vec_of Vs j) Bs\"\nproof (intro nth_equalityI)\n  have l1: \"length (cols (inc_mat_of Vs Bs)) = length Bs\"\n    using inc_mat_dim_col by simp\n  have l2: \"length (map (\\<lambda> j . inc_vec_of Vs j) Bs) = length Bs\"\n    using length_map by simp\n  then show \"length (cols (inc_mat_of Vs Bs)) = length (map (inc_vec_of Vs) Bs)\" \n    using l1 l2 by simp\n  show \"\\<And> i. i < length (cols (inc_mat_of Vs Bs)) \\<Longrightarrow> \n    (cols (inc_mat_of Vs Bs) ! i) = (map (\\<lambda> j . inc_vec_of Vs j) Bs) ! i\"\n    using inc_mat_col_inc_vec l1 by (metis cols_nth inc_mat_dim_col nth_map) \nqed\n\nlemma inc_mat_of_bij_betw: \n  assumes \"inj_on f (set Vs)\"\n  assumes \"\\<And> bl . bl \\<in> (set Bs) \\<Longrightarrow> bl \\<subseteq> (set Vs)\"\n  shows \"inc_mat_of Vs Bs = inc_mat_of (map f Vs) (map ((`) f) Bs)\"\nproof (intro eq_matI, simp_all add: inc_mat_dim_row inc_mat_dim_col, intro impI)\n  fix i j assume ilt: \"i < length Vs\" and jlt: \" j < length Bs\" and \"Vs ! i \\<notin> Bs ! j\"\n  then show \"f (Vs ! i) \\<notin> f ` Bs ! j\"\n    by (meson assms(1) assms(2) ilt inj_on_image_mem_iff jlt nth_mem) \nqed\n\ntext \\<open>Definitions for the incidence matrix representation of common incidence system properties \\<close>\n\ndefinition non_empty_col :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"non_empty_col M j \\<equiv> \\<exists> k. k \\<noteq> 0 \\<and> k \\<in>$ col M j\"\n\ndefinition proper_inc_mat :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> bool\" where\n\"proper_inc_mat M \\<equiv> (dim_row M > 0 \\<and> dim_col M > 0)\"\n\ntext \\<open>Matrix version of the representation number property @{term \"point_replication_number\"}\\<close>\ndefinition mat_rep_num :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mat_rep_num M i \\<equiv> count_vec (row M i) 1\"\n\ntext \\<open>Matrix version of the points index property @{term \"points_index\"}\\<close>\ndefinition mat_point_index :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat set \\<Rightarrow> nat\" where\n\"mat_point_index M I \\<equiv> card {j . j < dim_col M \\<and> (\\<forall> i \\<in> I. M $$ (i, j) = 1)}\"\n\ndefinition mat_inter_num :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mat_inter_num M j1 j2 \\<equiv> card {i . i < dim_row M \\<and> M $$ (i, j1) = 1 \\<and>  M $$ (i, j2) = 1}\"\n\ntext \\<open>Matrix version of the block size property\\<close>\ndefinition mat_block_size :: \"('a :: {zero_neq_one}) mat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"mat_block_size M j \\<equiv> count_vec (col M j) 1\"\n\nlemma non_empty_col_obtains: \n  assumes \"non_empty_col M j\"\n  obtains i where \"i < dim_row M\" and \"(col M j) $ i \\<noteq> 0\"\nproof -\n  have d: \"dim_vec (col M j) = dim_row M\" by simp\n  from assms obtain k where \"k \\<noteq> 0\" and \"k \\<in>$ col M j\" \n    by (auto simp add: non_empty_col_def)\n  thus ?thesis using vec_contains_obtains_index d\n    by (metis that) \nqed\n\nlemma non_empty_col_alt_def: \n  assumes \"j < dim_col M\" \n  shows \"non_empty_col M j \\<longleftrightarrow> (\\<exists> i. i < dim_row M \\<and> M $$ (i, j) \\<noteq> 0)\"\nproof (intro iffI)\n  show \"non_empty_col M j \\<Longrightarrow> \\<exists>i<dim_row M. M $$ (i, j) \\<noteq> 0\"\n    by(metis assms index_col non_empty_col_obtains)\nnext \n  assume \"\\<exists>i<dim_row M. M $$ (i, j) \\<noteq> 0\"\n  then obtain i where ilt: \" i < dim_row M\" and ne: \"M $$ (i, j) \\<noteq> 0\" by blast\n  then have ilt2: \" i < dim_vec (col M j)\" by simp\n  then have \"(col M j) $ i \\<noteq> 0\" using ne by (simp add: assms) \n  then obtain k where \"(col M j) $ i = k\" and \"k \\<noteq> 0\"\n    by simp\n  then show \"non_empty_col M j \" using non_empty_col_def\n    by (metis ilt2 vec_setI) \nqed\n\nlemma proper_inc_mat_map: \"proper_inc_mat M \\<Longrightarrow> proper_inc_mat (map_mat f M)\"\n  by (simp add: proper_inc_mat_def)\n\nlemma mat_point_index_alt: \"mat_point_index M I = card {j \\<in> {0..<dim_col M} . (\\<forall> i \\<in> I . M $$(i, j) = 1)}\"\n  by (simp add: mat_point_index_def)\n\nlemma mat_block_size_sum_alt: \n  fixes M :: \"'a :: {ring_1} mat\"\n  shows \"elements_mat M \\<subseteq> {0, 1} \\<Longrightarrow> j < dim_col M \\<Longrightarrow> of_nat (mat_block_size M j) = sum_vec (col M j)\"\n  unfolding mat_block_size_def using count_vec_sum_ones_alt col_elems_subset_mat subset_trans\n  by metis  \n\nlemma mat_rep_num_sum_alt: \n  fixes M :: \"'a :: {ring_1} mat\"\n  shows \"elements_mat M \\<subseteq> {0, 1} \\<Longrightarrow> i < dim_row M \\<Longrightarrow> of_nat (mat_rep_num M i) = sum_vec (row M i)\"\n  using count_vec_sum_ones_alt\n  by (metis mat_rep_num_def row_elems_subset_mat subset_trans) \n\nlemma mat_point_index_two_alt: \n  assumes \"i1 < dim_row M\"\n  assumes \"i2 < dim_row M\"\n  shows \"mat_point_index M {i1, i2} = card {j . j < dim_col M \\<and> M $$(i1, j) = 1 \\<and> M $$ (i2, j) = 1}\"\nproof -\n  let ?I = \"{i1, i2}\"\n  have ss: \"{i1, i2} \\<subseteq> {..<dim_row M}\" using assms by blast\n  have filter: \"\\<And> j . j < dim_col M \\<Longrightarrow> (\\<forall> i \\<in> ?I . M $$(i, j) = 1) \\<longleftrightarrow> M $$(i1, j) = 1 \\<and> M $$ (i2, j) = 1\"\n    by auto\n  have \"?I \\<subseteq> {..< dim_row M}\" using assms(1) assms(2) by fastforce\n  thus ?thesis using filter ss unfolding mat_point_index_def\n    by meson \nqed\n\ntext \\<open> Transpose symmetries \\<close>\n\nlemma trans_mat_rep_block_size_sym: \"j < dim_col M \\<Longrightarrow> mat_block_size M j = mat_rep_num M\\<^sup>T j\"\n  \"i < dim_row M \\<Longrightarrow> mat_rep_num M i = mat_block_size M\\<^sup>T i\"\n  unfolding mat_block_size_def mat_rep_num_def by simp_all\n\nlemma trans_mat_point_index_inter_sym: \n  \"i1 < dim_row M \\<Longrightarrow> i2 < dim_row M \\<Longrightarrow> mat_point_index M {i1, i2} = mat_inter_num M\\<^sup>T i1 i2\"\n  \"j1 < dim_col M \\<Longrightarrow> j2 < dim_col M \\<Longrightarrow> mat_inter_num M j1 j2 = mat_point_index M\\<^sup>T {j1, j2}\"\n   apply (simp_all add: mat_inter_num_def mat_point_index_two_alt)\n   apply (metis (no_types, lifting) index_transpose_mat(1))\n  by (metis (no_types, lifting) index_transpose_mat(1))\n\nsubsection \\<open>0-1 Matrices \\<close>\ntext \\<open>Incidence matrices contain only two elements: 0 and 1. We define a locale which provides\na context to work in for matrices satisfying this condition for any @{typ \"'b :: zero_neq_one\"} type.\\<close>\nlocale zero_one_matrix = \n  fixes matrix :: \"'b :: {zero_neq_one} mat\" (\"M\")\n  assumes elems01: \"elements_mat M \\<subseteq> {0, 1}\"\nbegin\n\ntext \\<open> Row and Column Properties of the Matrix \\<close>\n\nlemma row_elems_ss01:\"i < dim_row M \\<Longrightarrow> vec_set (row M i) \\<subseteq> {0, 1}\"\n  using row_elems_subset_mat elems01 by blast\n\nlemma col_elems_ss01: \n  assumes \"j < dim_col M\"\n  shows \"vec_set (col M j) \\<subseteq> {0, 1}\"\nproof -\n  have \"vec_set (col M j) \\<subseteq> elements_mat M\" using assms \n    by (simp add: col_elems_subset_mat assms) \n  thus ?thesis using elems01 by blast\nqed\n\nlemma col_nth_0_or_1_iff: \n  assumes \"j < dim_col M\"\n  assumes \"i < dim_row M\"\n  shows \"col M j $ i = 0 \\<longleftrightarrow> col M j $ i \\<noteq> 1\"\nproof (intro iffI)\n  have dv: \"i < dim_vec (col M j)\" using assms by simp\n  have sv: \"set\\<^sub>v (col M j) \\<subseteq> {0, 1}\" using col_elems_ss01 assms by simp\n  then show \"col M j $ i = 0 \\<Longrightarrow> col M j $ i \\<noteq> 1\" using dv by simp\n  show \"col M j $ i \\<noteq> 1 \\<Longrightarrow> col M j $ i = 0\" using dv sv\n    by (meson insertE singletonD subset_eq vec_setI) \nqed\n\nlemma row_nth_0_or_1_iff: \n  assumes \"j < dim_col M\"\n  assumes \"i < dim_row M\"\n  shows \"row M i $ j = 0 \\<longleftrightarrow> row M i $ j \\<noteq> 1\"\nproof (intro iffI)\n  have dv: \"j < dim_vec (row M i)\" using assms by simp\n  have sv: \"set\\<^sub>v (row M i) \\<subseteq> {0, 1}\" using row_elems_ss01 assms by simp\n  then show \"row M i $ j = 0 \\<Longrightarrow> row M i $ j \\<noteq> 1\" by simp\n  show \"row M i $ j \\<noteq> 1 \\<Longrightarrow> row M i $ j = 0\" using dv sv\n    by (meson insertE singletonD subset_eq vec_setI) \nqed\n\nlemma transpose_entries: \"elements_mat (M\\<^sup>T) \\<subseteq> {0, 1}\"\n  using elems01 transpose_mat_elems by metis \n\nlemma M_not_zero_simp: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> M $$ (i, j) \\<noteq> 0 \\<Longrightarrow> M $$ (i, j) = 1\"\n  using elems01 by auto\n\nlemma M_not_one_simp: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> M $$ (i, j) \\<noteq> 1 \\<Longrightarrow> M $$ (i, j) = 0\"\n  using elems01 by auto\n\ntext \\<open>Definition for mapping a column to a block \\<close>\ndefinition map_col_to_block :: \"'a :: {zero_neq_one} vec  \\<Rightarrow> nat set\" where\n\"map_col_to_block c \\<equiv> { i \\<in> {..<dim_vec c} . c $ i = 1}\"\n\nlemma map_col_to_block_alt: \"map_col_to_block c = {i . i < dim_vec c \\<and> c$ i = 1}\"\n  by (simp add: map_col_to_block_def)\n\nlemma map_col_to_block_elem: \"i < dim_vec c \\<Longrightarrow> i \\<in> map_col_to_block c \\<longleftrightarrow>  c $ i = 1\"\n  by (simp add: map_col_to_block_alt)\n\nlemma in_map_col_valid_index: \"i \\<in> map_col_to_block c \\<Longrightarrow> i < dim_vec c\"\n  by (simp add: map_col_to_block_alt)\n\nlemma map_col_to_block_size: \"j < dim_col M \\<Longrightarrow> card (map_col_to_block (col M j)) = mat_block_size M j\"\n  unfolding mat_block_size_def map_col_to_block_alt using count_vec_alt[of \"col M j\" \"1\"] Collect_cong\n  by (metis (no_types, lifting))\n\nlemma in_map_col_valid_index_M: \"j < dim_col M \\<Longrightarrow> i \\<in> map_col_to_block (col M j) \\<Longrightarrow> i < dim_row M\"\n  using in_map_col_valid_index by (metis dim_col) \n\nlemma map_col_to_block_elem_not: \"c \\<in> set (cols M) \\<Longrightarrow> i < dim_vec c \\<Longrightarrow> i \\<notin> map_col_to_block c \\<longleftrightarrow> c $ i = 0\"\n  apply (auto simp add: map_col_to_block_alt)\n  using elems01 by (metis col_nth_0_or_1_iff dim_col obtain_col_index) \n\nlemma obtain_block_index_map_block_set: \n  assumes \"bl \\<in># {# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  obtains j where \"j < dim_col M\" and \"bl = map_col_to_block (col M j)\"\nproof -\n  obtain c where bleq: \"bl = map_col_to_block c\" and \"c \\<in># mset (cols M)\"\n    using assms by blast\n  then have \"c \\<in> set (cols M)\" by simp\n  thus ?thesis using bleq obtain_col_index\n    by (metis that)\nqed\n\nlemma mat_ord_inc_sys_point[simp]: \"x < dim_row M \\<Longrightarrow> [0..<(dim_row M)] ! x = x\"\n  by simp\n\nlemma mat_ord_inc_sys_block[simp]: \"j < dim_col M \\<Longrightarrow> \n  (map (map_col_to_block) (cols M)) ! j = map_col_to_block (col M j)\"\n  by auto\n\nlemma ordered_to_mset_col_blocks:\n  \"{# map_col_to_block c . c \\<in># mset (cols M)#} = mset (map (map_col_to_block) (cols M))\"\n  by simp\n\ntext \\<open> Lemmas on incidence matrix properties \\<close>\nlemma non_empty_col_01: \n  assumes \"j < dim_col M\"\n  shows \"non_empty_col M j \\<longleftrightarrow> 1 \\<in>$ col M j\"\nproof (intro iffI)\n  assume \"non_empty_col M j\"\n  then obtain k where kn0: \"k \\<noteq> 0\" and kin: \"k \\<in>$ col M j\" using non_empty_col_def\n    by blast\n  then have \"k \\<in> elements_mat M\" using vec_contains_col_elements_mat assms\n    by metis \n  then have \"k = 1\" using kn0\n    using elems01 by blast \n  thus \"1 \\<in>$ col M j\" using kin by simp\nnext\n  assume \"1 \\<in>$ col M j\"\n  then show \"non_empty_col M j\" using non_empty_col_def\n    by (metis zero_neq_one)\nqed\n\nlemma mat_rep_num_alt: \n  assumes \"i < dim_row M\"\n  shows \"mat_rep_num M i = card {j . j < dim_col M \\<and> M $$ (i, j) = 1}\"\nproof (simp add: mat_rep_num_def)\n  have eq: \"\\<And> j. (j < dim_col M \\<and> M $$ (i, j) = 1) = (row M i $ j = 1 \\<and> j < dim_vec (row M i))\" \n    using assms by auto\n  have \"count_vec (row M i) 1 = card {j. (row M i) $ j = 1 \\<and>  j < dim_vec (row M i)}\"\n    using count_vec_alt[of \"row M i\" \"1\"] by simp\n  thus \"count_vec (row M i) 1 = card {j. j < dim_col M \\<and> M $$ (i, j) = 1}\"\n    using eq Collect_cong by simp\nqed\n\nlemma mat_rep_num_alt_col: \"i < dim_row M \\<Longrightarrow> mat_rep_num M i = size {#c \\<in># (mset (cols M)) . c $ i = 1#}\"\n  using mat_rep_num_alt index_to_col_card_size_prop[of i M] by auto\n\ntext \\<open> A zero one matrix is an incidence system \\<close>\n\nlemma map_col_to_block_wf: \"\\<And>c. c \\<in> set (cols M) \\<Longrightarrow> map_col_to_block c \\<subseteq> {0..<dim_row M}\"\n  by (auto simp add: map_col_to_block_def)(metis dim_col obtain_col_index)\n\nlemma one_implies_block_nempty: \"j < dim_col M \\<Longrightarrow> 1 \\<in>$ (col M j) \\<Longrightarrow> map_col_to_block (col M j) \\<noteq> {}\"\n  unfolding map_col_to_block_def using vec_setE by force \n\ninterpretation incidence_sys: incidence_system \"{0..<dim_row M}\" \n    \"{# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  using map_col_to_block_wf by (unfold_locales) auto \n\ninterpretation fin_incidence_sys: finite_incidence_system \"{0..<dim_row M}\" \n    \"{# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  by (unfold_locales) (simp)\n\nlemma block_nempty_implies_all_zeros: \"j < dim_col M \\<Longrightarrow> map_col_to_block (col M j) = {} \\<Longrightarrow> \n    i < dim_row M \\<Longrightarrow> col M j $ i = 0\"\n  by (metis col_nth_0_or_1_iff dim_col one_implies_block_nempty vec_setI)\n\nlemma block_nempty_implies_no_one: \"j < dim_col M \\<Longrightarrow> map_col_to_block (col M j) = {} \\<Longrightarrow> \\<not> (1 \\<in>$ (col M j))\"\n  using one_implies_block_nempty by blast\n\nlemma mat_is_design:\n  assumes \"\\<And>j. j < dim_col M\\<Longrightarrow> 1 \\<in>$ (col M j)\"\n  shows \"design {0..<dim_row M} {# map_col_to_block c . c \\<in># mset (cols M)#}\"\nproof (unfold_locales)\n  fix bl \n  assume \"bl \\<in># {# map_col_to_block c . c \\<in># mset (cols M)#}\"\n  then obtain j where \"j < dim_col M\" and map: \"bl = map_col_to_block (col M j)\"\n    using obtain_block_index_map_block_set by auto\n  thus \"bl \\<noteq> {}\" using assms one_implies_block_nempty\n    by simp \nqed\n\nlemma mat_is_proper_design: \n  assumes \"\\<And>j. j < dim_col M \\<Longrightarrow> 1 \\<in>$ (col M j)\"\n  assumes \"dim_col M > 0\"\n  shows \"proper_design {0..<dim_row M} {# map_col_to_block c . c \\<in># mset (cols M)#}\"\nproof -\n  interpret des: design \"{0..<dim_row M}\" \"{# map_col_to_block c . c \\<in># mset (cols M)#}\"\n    using mat_is_design assms by simp\n  show ?thesis proof (unfold_locales)\n    have \"length (cols M) \\<noteq> 0\" using assms(2) by auto\n    then have \"size {# map_col_to_block c . c \\<in># mset (cols M)#} \\<noteq> 0\" by auto\n    then show \"incidence_sys.\\<b> \\<noteq> 0\" by simp\n  qed\nqed\n\ntext \\<open> Show the 01 injective function preserves system properties \\<close>\n\nlemma inj_on_01_hom_index:\n  assumes \"inj_on_01_hom f\"\n  assumes \"i < dim_row M\" \"j < dim_col M\"\n  shows \"M $$ (i, j) = 1  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 1\"\n    and \"M $$ (i, j) = 0  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 0\"\nproof -\n  interpret hom: inj_on_01_hom f using assms by simp\n  show \"M $$ (i, j) = 1  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 1\" \n    using assms col_nth_0_or_1_iff\n    by (simp add: hom.inj_1_iff) \n  show \"M $$ (i, j) = 0  \\<longleftrightarrow> (map_mat f M) $$ (i, j) = 0\"\n    using assms col_nth_0_or_1_iff\n    by (simp add: hom.inj_0_iff) \nqed\n\nlemma preserve_non_empty: \n  assumes \"inj_on_01_hom f\" \n  assumes \"j < dim_col M\"\n  shows \"non_empty_col M j \\<longleftrightarrow> non_empty_col (map_mat f M) j\"\nproof(simp add: non_empty_col_def, intro iffI) \n  interpret hom: inj_on_01_hom f using assms(1) by simp\n  assume \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col M j\"\n  then obtain k where kneq: \"k \\<noteq> 0\" and kin: \"k \\<in>$ col M j\" by blast\n  then have \"f k \\<in>$ col (map_mat f M) j\" using vec_contains_img\n    by (metis assms(2) col_map_mat) \n  then have \"f k \\<noteq> 0\" using assms(1) kneq kin assms(2) col_elems_ss01 hom.inj_0_iff by blast\n  thus \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col (map_mat f M) j\"\n    using \\<open>f k \\<in>$ col (map_mat f M) j\\<close> by blast\nnext\n  interpret hom: inj_on_01_hom f using assms(1) by simp\n  assume \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col (map_mat f M) j\"\n  then obtain k where kneq: \"k \\<noteq> 0\" and kin: \"k \\<in>$ col (map_mat f M) j\" by blast\n  then have \"k \\<in>$ map_vec f (col M j)\" using assms(2) col_map_mat by simp\n  then have \"k \\<in> f ` set\\<^sub>v (col M j)\"\n    by (smt (verit) image_eqI index_map_vec(1) index_map_vec(2) vec_setE vec_setI) \n  then obtain k' where keq: \"k = f k'\" and kin2: \"k' \\<in> set\\<^sub>v (col M j)\"\n    by blast \n  then have \"k' \\<noteq> 0\" using assms(1) kneq hom.inj_0_iff by blast \n  thus  \"\\<exists>k. k \\<noteq> 0 \\<and> k \\<in>$ col M j\" using kin2 by auto\nqed\n\nlemma preserve_mat_rep_num:\n  assumes \"inj_on_01_hom f\"\n  assumes \"i < dim_row M\"\n  shows \"mat_rep_num M i = mat_rep_num (map_mat f M) i\"\n  unfolding mat_rep_num_def using injective_lim.lim_inj_hom_count_vec inj_on_01_hom_def row_map_mat\n  by (metis assms(1) assms(2) inj_on_01_hom.inj_1_iff insert_iff row_elems_ss01)\n\nlemma preserve_mat_block_size: \n  assumes \"inj_on_01_hom f\"\n  assumes \"j < dim_col M\"\n  shows \"mat_block_size M j = mat_block_size (map_mat f M) j\"\n  unfolding mat_block_size_def using injective_lim.lim_inj_hom_count_vec inj_on_01_hom_def col_map_mat\n  by (metis assms(1) assms(2) inj_on_01_hom.inj_1_iff insert_iff col_elems_ss01)\n\n\nlemma preserve_mat_point_index: \n  assumes \"inj_on_01_hom f\"\n  assumes \"\\<And> i. i \\<in> I \\<Longrightarrow> i < dim_row M\"\n  shows \"mat_point_index M I = mat_point_index (map_mat f M) I\"\nproof -\n  have \"\\<And> i j. i \\<in> I \\<Longrightarrow> j < dim_col M \\<and> M $$ (i, j) = 1 \\<longleftrightarrow> \n      j < dim_col (map_mat f M) \\<and> (map_mat f M) $$ (i, j) = 1\"\n    using assms(2) inj_on_01_hom_index(1) assms(1) by (metis index_map_mat(3)) \n  thus ?thesis unfolding mat_point_index_def\n    by (metis (no_types, opaque_lifting) index_map_mat(3)) \nqed\n\nlemma preserve_mat_inter_num: \n  assumes \"inj_on_01_hom f\"\n  assumes \"j1 < dim_col M\" \"j2 < dim_col M\"\n  shows \"mat_inter_num M j1 j2 = mat_inter_num (map_mat f M) j1 j2\"\n  unfolding mat_inter_num_def using assms\n  by (metis (no_types, opaque_lifting) index_map_mat(2) inj_on_01_hom_index(1)) \n\nlemma lift_mat_01_index_iff: \n  \"i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> (lift_01_mat M) $$ (i, j) = 0 \\<longleftrightarrow> M $$ (i, j) = 0\"\n  \"i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> (lift_01_mat M) $$ (i, j) = 1 \\<longleftrightarrow> M $$ (i, j) = 1\"\n  by (simp) (metis col_nth_0_or_1_iff index_col lift_01_mat_simp(3) of_zero_neq_one_def zero_neq_one) \n\nlemma lift_mat_elems: \"elements_mat (lift_01_mat M) \\<subseteq> {0, 1}\"\nproof -\n  have \"elements_mat (lift_01_mat M) = of_zero_neq_one ` (elements_mat M)\"\n    by (simp add: lift_01_mat_def map_mat_elements)\n  then have \"elements_mat (lift_01_mat M) \\<subseteq> of_zero_neq_one ` {0, 1}\" using elems01\n    by fastforce \n  thus ?thesis\n    by simp \nqed\n\nlemma lift_mat_is_0_1: \"zero_one_matrix (lift_01_mat M)\"\n  using lift_mat_elems by (unfold_locales)\n\nlemma lift_01_mat_distinct_cols: \"distinct (cols M) \\<Longrightarrow> distinct (cols (lift_01_mat M))\"\n  using of_injective_lim.mat_cols_hom_lim_distinct_iff lift_01_mat_def\n  by (metis elems01 map_vec_mat_cols) \n\nend\n\ntext \\<open>Some properties must be further restricted to matrices having a @{typ \"'a :: ring_1\"} type \\<close>\nlocale zero_one_matrix_ring_1 = zero_one_matrix M for M :: \"'b :: {ring_1} mat\"\nbegin\n\nlemma map_col_block_eq: \n  assumes \"c \\<in> set(cols M)\"\n  shows \"inc_vec_of [0..<dim_vec c] (map_col_to_block c) = c\"\nproof (intro eq_vecI, simp add: map_col_to_block_def inc_vec_of_def, intro impI)\n  show \"\\<And>i. i < dim_vec c \\<Longrightarrow> c $ i \\<noteq> 1 \\<Longrightarrow> c $ i = 0\"\n    using assms map_col_to_block_elem map_col_to_block_elem_not by auto \n  show \"dim_vec (inc_vec_of [0..<dim_vec c] (map_col_to_block c)) = dim_vec c\"\n    unfolding inc_vec_of_def by simp \nqed\n\nlemma inc_mat_of_map_rev: \"inc_mat_of [0..<dim_row M] (map map_col_to_block (cols M)) = M\"\nproof (intro eq_matI, simp_all add: inc_mat_of_def, intro conjI impI)\n  show \"\\<And>i j. i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> i \\<in> map_col_to_block (col M j) \\<Longrightarrow> M $$ (i, j) = 1\"\n    by (simp add: map_col_to_block_elem)\n  show \"\\<And>i j. i < dim_row M \\<Longrightarrow> j < dim_col M \\<Longrightarrow> i \\<notin> map_col_to_block (col M j) \\<Longrightarrow> M $$ (i, j) = 0\"\n    by (metis col_nth_0_or_1_iff dim_col index_col map_col_to_block_elem)\nqed\n\nlemma M_index_square_itself: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> (M $$ (i, j))^2 = M $$ (i, j)\"\n  using M_not_zero_simp by (cases \"M $$ (i, j) = 0\")(simp_all, metis power_one) \n\nlemma M_col_index_square_itself: \"j < dim_col M \\<Longrightarrow> i < dim_row M \\<Longrightarrow> ((col M j) $ i)^2 = (col M j) $ i\"\n  using index_col M_index_square_itself by auto \n\n\ntext \\<open> Scalar Prod Alternative definitions for matrix properties \\<close>\n\nlemma scalar_prod_inc_vec_block_size_mat:\n  assumes \"j < dim_col M\"\n  shows \"(col M j) \\<bullet> (col M j) = of_nat (mat_block_size M j)\"\nproof -\n  have \"(col M j) \\<bullet> (col M j) = (\\<Sum> i \\<in> {0..<dim_row M} . (col M j) $ i * (col M j) $ i)\" \n     using assms  scalar_prod_def sum.cong by (smt (verit, ccfv_threshold) dim_col) \n  also have \"... = (\\<Sum> i \\<in> {0..<dim_row M} . ((col M j) $ i)^2)\"\n    by (simp add: power2_eq_square ) \n  also have \"... = (\\<Sum> i \\<in> {0..<dim_row M} . ((col M j) $ i))\"\n    using M_col_index_square_itself assms by auto\n  finally show ?thesis using sum_vec_def mat_block_size_sum_alt\n    by (metis assms dim_col elems01) \nqed\n\nlemma scalar_prod_inc_vec_mat_inter_num: \n  assumes \"j1 < dim_col M\" \"j2 < dim_col M\"\n  shows \"(col M j1) \\<bullet> (col M j2) = of_nat (mat_inter_num M j1 j2)\"\nproof -\n  have split: \"{0..<dim_row M} = {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } \\<union> \n    {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0}\" using assms M_not_zero_simp by auto\n  have inter: \"{i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } \\<inter> \n    {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0} = {}\" by auto\n  have \"(col M j1) \\<bullet> (col M j2) = (\\<Sum> i \\<in> {0..<dim_row M} . (col M j1) $ i * (col M j2) $ i)\" \n    using assms scalar_prod_def by (metis (full_types) dim_col) \n  also have \"... = (\\<Sum> i \\<in> {0..<dim_row M} . M $$ (i, j1) * M $$ (i, j2))\" \n    using assms by simp\n  also have \"... = (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } . M $$ (i, j1) * M $$ (i, j2)) \n      + (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0} . M $$ (i, j1) * M $$ (i, j2))\" \n    using split inter sum.union_disjoint[of \" {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1)}\" \n      \"{i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0}\" \"\\<lambda> i . M $$ (i, j1) * M $$ (i, j2)\"]\n    by (metis (no_types, lifting) finite_Un finite_atLeastLessThan) \n  also have \"... = (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1) } . 1) \n      + (\\<Sum> i \\<in> {i \\<in> {0..<dim_row M} . M $$ (i, j1) = 0 \\<or> M $$ (i, j2) = 0} . 0)\" \n    using sum.cong mem_Collect_eq by (smt (z3) mult.right_neutral mult_not_zero) \n  finally have \"(col M j1) \\<bullet> (col M j2) = \n      of_nat (card {i . i < dim_row M \\<and> (M $$ (i, j1) = 1) \\<and> (M $$ (i, j2) = 1)})\"\n    by simp \n  then show ?thesis using mat_inter_num_def[of M j1 j2] by simp\nqed\n\nend\n\ntext \\<open> Any matrix generated by @{term \"inc_mat_of\"} is a 0-1 matrix.\\<close>\nlemma inc_mat_of_01_mat: \"zero_one_matrix_ring_1 (inc_mat_of Vs Bs)\"\n  by (unfold_locales) (simp add: inc_mat_one_zero_elems) \n\nsubsection \\<open>Ordered Incidence Systems \\<close>\ntext \\<open>We impose an arbitrary ordering on the point set and block collection to enable\nmatrix reasoning. Note that this is also common in computer algebra representations of designs \\<close>\n\nlocale ordered_incidence_system =\n  fixes \\<V>s :: \"'a list\" and \\<B>s :: \"'a set list\"\n  assumes wf_list: \"b \\<in># (mset \\<B>s) \\<Longrightarrow> b \\<subseteq> set \\<V>s\"\n  assumes distinct: \"distinct \\<V>s\"\n\ntext \\<open>An ordered incidence system, as it is defined on lists, can only represent finite incidence systems \\<close>\nsublocale ordered_incidence_system \\<subseteq> finite_incidence_system \"set \\<V>s\" \"mset \\<B>s\"\n  by(unfold_locales) (auto simp add: wf_list)\n\nlemma ordered_incidence_sysI: \n  assumes \"finite_incidence_system \\<V> \\<B>\" \n  assumes \"\\<V>s \\<in> permutations_of_set \\<V>\" and \"\\<B>s \\<in> permutations_of_multiset \\<B>\"\n  shows \"ordered_incidence_system \\<V>s \\<B>s\"\nproof -\n  have veq: \"\\<V> = set \\<V>s\" using assms permutations_of_setD(1) by auto \n  have beq: \"\\<B> = mset \\<B>s\" using assms permutations_of_multisetD by auto\n  interpret fisys: finite_incidence_system \"set \\<V>s\" \"mset \\<B>s\" using assms(1) veq beq by simp\n  show ?thesis proof (unfold_locales)\n    show \"\\<And>b. b \\<in># mset \\<B>s \\<Longrightarrow> b \\<subseteq> set \\<V>s\" using fisys.wellformed\n      by simp \n    show \"distinct \\<V>s\" using assms permutations_of_setD(2) by auto\n  qed\nqed\n\nlemma ordered_incidence_sysII: \n  assumes \"finite_incidence_system \\<V> \\<B>\" and \"set \\<V>s = \\<V>\" and \"distinct \\<V>s\" and \"mset \\<B>s = \\<B>\"\n  shows \"ordered_incidence_system \\<V>s \\<B>s\"\nproof -\n  interpret fisys: finite_incidence_system \"set \\<V>s\" \"mset \\<B>s\" using assms by simp\n  show ?thesis using fisys.wellformed assms by (unfold_locales) (simp_all)\nqed\n\ncontext ordered_incidence_system \nbegin\ntext \\<open>For ease of notation, establish the same notation as for incidence systems \\<close>\n\nabbreviation \"\\<V> \\<equiv> set \\<V>s\"\nabbreviation \"\\<B> \\<equiv> mset \\<B>s\"\n\ntext \\<open>Basic properties on ordered lists \\<close>\nlemma points_indexing: \"\\<V>s \\<in> permutations_of_set \\<V>\"\n  by (simp add: permutations_of_set_def distinct)\n\nlemma blocks_indexing: \"\\<B>s \\<in> permutations_of_multiset \\<B>\"\n  by (simp add: permutations_of_multiset_def)\n\nlemma points_list_empty_iff: \"\\<V>s = [] \\<longleftrightarrow> \\<V> = {}\"\n  using finite_sets points_indexing\n  by (simp add: elem_permutation_of_set_empty_iff) \n\nlemma points_indexing_inj: \"\\<forall> i \\<in> I . i < length \\<V>s \\<Longrightarrow> inj_on ((!) \\<V>s) I\"\n  by (simp add: distinct inj_on_nth)\n\nlemma blocks_list_empty_iff: \"\\<B>s = [] \\<longleftrightarrow> \\<B> = {#}\"\n  using blocks_indexing by (simp) \n\nlemma blocks_list_nempty: \"proper_design \\<V> \\<B> \\<Longrightarrow> \\<B>s \\<noteq> []\"\n  using mset.simps(1) proper_design.design_blocks_nempty by blast\n\nlemma points_list_nempty: \"proper_design \\<V> \\<B> \\<Longrightarrow> \\<V>s \\<noteq> []\"\n  using proper_design.design_points_nempty points_list_empty_iff by blast\n\nlemma points_list_length: \"length \\<V>s = \\<v>\"\n  using points_indexing\n  by (simp add: length_finite_permutations_of_set) \n\nlemma blocks_list_length: \"length \\<B>s = \\<b>\"\n  using blocks_indexing length_finite_permutations_of_multiset by blast\n\nlemma valid_points_index: \"i < \\<v> \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>\"\n  using points_list_length by simp \n\nlemma valid_points_index_cons: \"x \\<in> \\<V> \\<Longrightarrow> \\<exists> i. \\<V>s ! i = x \\<and> i < \\<v>\"\n  using points_list_length by (auto simp add: in_set_conv_nth)\n\nlemma valid_points_index_obtains: \n  assumes \"x \\<in> \\<V>\"\n  obtains i where \"\\<V>s ! i = x \\<and> i < \\<v>\"\n  using valid_points_index_cons assms by auto\n\nlemma valid_blocks_index: \"j < \\<b> \\<Longrightarrow> \\<B>s ! j \\<in># \\<B>\"\n  using blocks_list_length by (metis nth_mem_mset)\n\nlemma valid_blocks_index_cons: \"bl \\<in># \\<B> \\<Longrightarrow> \\<exists> j . \\<B>s ! j = bl \\<and> j < \\<b>\"\n  by (auto simp add: in_set_conv_nth)\n\nlemma valid_blocks_index_obtains: \n  assumes \"bl \\<in># \\<B>\"\n  obtains j where  \"\\<B>s ! j = bl \\<and> j < \\<b>\"\n  using assms valid_blocks_index_cons by auto\n\nlemma block_points_valid_point_index: \n  assumes \"bl \\<in># \\<B>\" \"x \\<in> bl\"\n  obtains i where \"i < length \\<V>s \\<and> \\<V>s ! i = x\"\n  using wellformed valid_points_index_obtains assms\n  by (metis points_list_length wf_invalid_point) \n\nlemma points_set_index_img: \"\\<V> = image(\\<lambda> i . (\\<V>s ! i)) ({..<\\<v>})\"\n  using valid_points_index_cons valid_points_index by auto\n\nlemma blocks_mset_image: \"\\<B> = image_mset (\\<lambda> i . (\\<B>s ! i)) (mset_set {..<\\<b>})\"\n  by (simp add: mset_list_by_index)\n\nlemma incidence_cond_indexed[simp]: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> incident (\\<V>s ! i) (\\<B>s ! j) \\<longleftrightarrow> (\\<V>s ! i) \\<in> (\\<B>s ! j)\"\n  using incidence_alt_def valid_points_index valid_blocks_index by simp\n\nlemma bij_betw_points_index: \"bij_betw (\\<lambda> i. \\<V>s ! i) {0..<\\<v>} \\<V>\"\nproof (simp add: bij_betw_def, intro conjI)\n  show \"inj_on ((!) \\<V>s) {0..<\\<v>}\"\n    by (simp add: points_indexing_inj points_list_length) \n  show \"(!) \\<V>s ` {0..<\\<v>} = \\<V>\" \n  proof (intro subset_antisym subsetI)\n    fix x assume \"x \\<in> (!) \\<V>s ` {0..<\\<v>}\" \n    then obtain i where \"x = \\<V>s ! i\" and \"i < \\<v>\" by auto\n    then show \"x \\<in> \\<V>\"\n      by (simp add: valid_points_index) \n  next \n    fix x assume \"x \\<in> \\<V>\"\n    then obtain i where \"\\<V>s ! i = x\" and \"i <\\<v>\"\n      using valid_points_index_cons by auto \n    then show \"x \\<in> (!) \\<V>s ` {0..<\\<v>}\" by auto\n  qed\nqed\n\ntext \\<open>Some lemmas on cardinality due to different set descriptor filters \\<close>\nlemma card_filter_point_indices: \"card {i \\<in> {0..<\\<v>}. P (\\<V>s ! i)} = card {v \\<in> \\<V> . P v }\"\nproof -\n  have \"{v \\<in> \\<V> . P v }= (\\<lambda> i. \\<V>s ! i) ` {i \\<in> {0..<\\<v>}. P (\\<V>s ! i)}\"\n    by (metis Compr_image_eq lessThan_atLeast0 points_set_index_img)\n  thus ?thesis using inj_on_nth points_list_length\n    by (metis (no_types, lifting) card_image distinct lessThan_atLeast0 lessThan_iff mem_Collect_eq)\nqed\n\nlemma card_block_points_filter: \n  assumes \"j < \\<b>\"\n  shows \"card (\\<B>s ! j) = card {i \\<in> {0..<\\<v>} . (\\<V>s ! i) \\<in> (\\<B>s ! j)}\"\nproof -\n  obtain bl where \"bl \\<in># \\<B>\" and blis: \"bl = \\<B>s ! j\"\n    using assms by auto\n  then have cbl: \"card bl = card {v \\<in> \\<V> . v \\<in> bl}\" using block_size_alt by simp\n  have \"\\<V> = (\\<lambda> i. \\<V>s ! i) ` {0..<\\<v>}\" using bij_betw_points_index\n    using lessThan_atLeast0 points_set_index_img by presburger\n  then have \"Set.filter (\\<lambda> v . v \\<in> bl) \\<V> = Set.filter (\\<lambda> v . v \\<in> bl) ((\\<lambda> i. \\<V>s ! i) ` {0..<\\<v>})\"\n    by presburger \n  have \"card {i \\<in> {0..<\\<v>} . (\\<V>s ! i) \\<in> bl} = card {v \\<in> \\<V> . v \\<in> bl}\" \n    using card_filter_point_indices by simp\n  thus ?thesis using cbl blis by simp\nqed\n\nlemma obtains_two_diff_block_indexes: \n  assumes \"j1 < \\<b>\"\n  assumes \"j2 < \\<b>\"\n  assumes \"j1 \\<noteq> j2\"\n  assumes \"\\<b> \\<ge> 2\"\n  obtains bl1 bl2 where \"bl1 \\<in># \\<B>\" and \"\\<B>s ! j1 = bl1\" and \"bl2 \\<in># \\<B> - {#bl1#}\" and \"\\<B>s ! j2 = bl2\"\nproof -\n  have j1lt: \"min j1 (length \\<B>s) = j1\" using assms by auto\n  obtain bl1 where bl1in: \"bl1 \\<in># \\<B>\" and bl1eq: \"\\<B>s ! j1 = bl1\"\n    using assms(1) valid_blocks_index by blast\n  then have split: \"\\<B>s = take j1 \\<B>s @ \\<B>s!j1 # drop (Suc j1) \\<B>s\" \n    using assms id_take_nth_drop by auto\n  then have lj1: \"length (take j1 \\<B>s) = j1\" using j1lt by (simp add: length_take[of j1 \\<B>s]) \n  have \"\\<B> = mset (take j1 \\<B>s @ \\<B>s!j1 # drop (Suc j1) \\<B>s)\" using split assms(1) by presburger \n  then have bsplit: \"\\<B> = mset (take j1 \\<B>s) + {#bl1#} + mset (drop (Suc j1) \\<B>s)\" by (simp add: bl1eq)\n  then have btake: \"\\<B> - {#bl1#} = mset (take j1 \\<B>s) + mset (drop (Suc j1) \\<B>s)\" by simp\n  thus ?thesis proof (cases \"j2 < j1\")\n    case True\n    then have \"j2 < length (take j1 \\<B>s)\" using lj1 by simp\n    then obtain bl2 where bl2eq: \"bl2 = (take j1 \\<B>s) ! j2\" by auto\n    then have bl2eq2: \"bl2 = \\<B>s ! j2\"\n      by (simp add: True) \n    then have \"bl2 \\<in># \\<B> - {#bl1#}\" using btake\n      by (metis bl2eq \\<open>j2 < length (take j1 \\<B>s)\\<close> nth_mem_mset union_iff) \n    then show ?thesis using bl2eq2 bl1in bl1eq that by auto\n  next\n    case False\n    then have j2gt: \"j2 \\<ge> Suc j1\" using assms by simp\n    then obtain i where ieq: \"i = j2 - Suc j1\"\n      by simp \n    then have j2eq: \"j2 = (Suc j1) + i\" using j2gt by presburger\n    have \"length (drop (Suc j1) \\<B>s) = \\<b> - (Suc j1)\" using blocks_list_length by auto\n    then have \"i < length (drop (Suc j1) \\<B>s)\" using ieq assms blocks_list_length\n      using diff_less_mono j2gt by presburger \n    then obtain bl2 where bl2eq: \"bl2 = (drop (Suc j1) \\<B>s) ! i\" by auto\n    then have bl2in: \"bl2 \\<in># \\<B> - {#bl1#}\" using btake nth_mem_mset union_iff\n      by (metis \\<open>i < length (drop (Suc j1) \\<B>s)\\<close>) \n    then have \"bl2 = \\<B>s ! j2\" using bl2eq nth_drop blocks_list_length assms j2eq\n      by (metis Suc_leI)\n    then show ?thesis using bl1in bl1eq bl2in that by auto\n  qed\nqed\n\nlemma filter_size_blocks_eq_card_indexes: \"size {# b \\<in># \\<B> . P b #} = card {j \\<in> {..<(\\<b>)}. P (\\<B>s ! j)}\"\nproof -\n  have \"\\<B> = image_mset (\\<lambda> j . \\<B>s ! j) (mset_set {..<(\\<b>)})\" \n    using blocks_mset_image by simp\n  then have helper: \"{# b \\<in># \\<B> . P b #} = image_mset (\\<lambda> j . \\<B>s ! j) {# j \\<in># (mset_set {..< \\<b>}). P (\\<B>s ! j) #} \"\n    by (simp add: filter_mset_image_mset)\n  have \"card {j \\<in> {..<\\<b>}. P (\\<B>s ! j)} = size {# j \\<in># (mset_set {..< \\<b>}). P (\\<B>s ! j) #}\"\n    using card_size_filter_eq [of \"{..<\\<b>}\"] by simp\n  thus ?thesis using helper by simp\nqed\n\nlemma blocks_index_ne_belong: \n  assumes \"i1 < length \\<B>s\"\n  assumes \"i2 < length \\<B>s\"\n  assumes \"i1 \\<noteq> i2\"\n  shows \"\\<B>s ! i2 \\<in># \\<B> - {#(\\<B>s ! i1)#}\"\nproof (cases \"\\<B>s ! i1 = \\<B>s ! i2\")\n  case True\n  then have \"count (mset \\<B>s) (\\<B>s ! i1) \\<ge> 2\" using count_min_2_indices assms by fastforce\n  then have \"count ((mset \\<B>s) - {#(\\<B>s ! i1)#}) (\\<B>s ! i1) \\<ge> 1\"\n    by (metis Nat.le_diff_conv2 add_leD2 count_diff count_single nat_1_add_1) \n  then show ?thesis\n    by (metis True count_inI not_one_le_zero)\nnext\n  case False\n  have \"\\<B>s ! i2 \\<in># \\<B>\" using assms\n    by simp \n  then show ?thesis using False\n    by (metis in_remove1_mset_neq)\nqed\n\nlemma inter_num_points_filter_def: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\" \"j1 \\<noteq> j2\"\n  shows \"card {x \\<in> {0..<\\<v>} . ((\\<V>s ! x) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! x) \\<in> (\\<B>s ! j2)) } = (\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2)\"\nproof - \n  have inter: \"\\<And> v. v \\<in> \\<V> \\<Longrightarrow> v \\<in> (\\<B>s ! j1) \\<and> v \\<in> (\\<B>s ! j2) \\<longleftrightarrow> v \\<in> (\\<B>s ! j1) \\<inter> (\\<B>s ! j2)\"\n    by simp \n  obtain bl1 bl2 where bl1in: \"bl1 \\<in># \\<B>\" and bl1eq: \"\\<B>s ! j1 = bl1\" and bl2in: \"bl2 \\<in># \\<B> - {#bl1#}\" \n    and bl2eq: \"\\<B>s ! j2 = bl2\" \n    using assms obtains_two_diff_block_indexes\n    by (metis blocks_index_ne_belong size_mset valid_blocks_index) \n  have \"card {x \\<in> {0..<\\<v>} . (\\<V>s ! x) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! x) \\<in> (\\<B>s ! j2) } = \n      card {v \\<in> \\<V> . v \\<in> (\\<B>s ! j1) \\<and> v \\<in> (\\<B>s ! j2) }\" \n    using card_filter_point_indices by simp\n  also have \"... = card {v \\<in> \\<V> . v \\<in> bl1 \\<and> v \\<in> bl2 }\" using bl1eq bl2eq by simp\n  finally show ?thesis using points_inter_num_rep bl1in bl2in\n    by (simp add: bl1eq bl2eq) \nqed\n\ntext \\<open>Define an incidence matrix for this ordering of an incidence system \\<close>\n\nabbreviation N :: \"int mat\" where\n\"N \\<equiv> inc_mat_of \\<V>s \\<B>s\"\n\nsublocale zero_one_matrix_ring_1 \"N\"\n  using inc_mat_of_01_mat .\n\nlemma N_alt_def_dim: \"N = mat \\<v> \\<b> (\\<lambda> (i,j) . if (incident (\\<V>s ! i) (\\<B>s ! j)) then 1 else 0) \" \n  using incidence_cond_indexed inc_mat_of_def \n  by (intro eq_matI) (simp_all add: inc_mat_dim_row inc_mat_dim_col inc_matrix_point_in_block_one \n      inc_matrix_point_not_in_block_zero points_list_length)\n\ntext \\<open>Matrix Dimension related lemmas \\<close>\n \nlemma N_carrier_mat: \"N \\<in> carrier_mat \\<v> \\<b>\" \n  by (simp add: N_alt_def_dim)\n\nlemma dim_row_is_v[simp]: \"dim_row N = \\<v>\"\n  by (simp add: N_alt_def_dim)\n\nlemma dim_col_is_b[simp]: \"dim_col N = \\<b>\"\n  by (simp add:  N_alt_def_dim)\n\nlemma dim_vec_row_N: \"dim_vec (row N i) = \\<b>\"\n  by (simp add:  N_alt_def_dim)\n\nlemma dim_vec_col_N: \"dim_vec (col N i) = \\<v>\" by simp \n\nlemma dim_vec_N_col: \n  assumes \"j < \\<b>\"\n  shows \"dim_vec (cols N ! j) = \\<v>\"\nproof -\n  have \"cols N ! j = col N j\" using assms dim_col_is_b by simp\n  then have \"dim_vec (cols N ! j) = dim_vec (col N j)\" by simp\n  thus ?thesis using dim_col assms by (simp) \nqed\n\nlemma N_carrier_mat_01_lift: \"lift_01_mat N \\<in> carrier_mat \\<v> \\<b>\"\n  by auto\n\ntext \\<open>Transpose properties \\<close>\n\nlemma transpose_N_mult_dim: \"dim_row (N * N\\<^sup>T) = \\<v>\" \"dim_col (N * N\\<^sup>T) = \\<v>\"\n  by (simp_all)\n\nlemma N_trans_index_val: \"i < dim_col N \\<Longrightarrow> j < dim_row N \\<Longrightarrow> \n    N\\<^sup>T $$ (i, j) = (if (\\<V>s ! j) \\<in> (\\<B>s ! i) then 1 else 0)\"\n  by (simp add: inc_mat_of_def)\n\ntext \\<open>Matrix element and index related lemmas \\<close>\nlemma mat_row_elems: \"i < \\<v> \\<Longrightarrow> vec_set (row N i) \\<subseteq> {0, 1}\"\n  using points_list_length\n  by (simp add: row_elems_ss01) \n\nlemma mat_col_elems: \"j < \\<b> \\<Longrightarrow> vec_set (col N j) \\<subseteq> {0, 1}\"\n  using blocks_list_length by (metis col_elems_ss01 dim_col_is_b)\n\nlemma matrix_elems_one_zero: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 0 \\<or> N $$ (i, j) = 1\"\n  by (metis blocks_list_length inc_matrix_elems_one_zero points_list_length)\n\nlemma matrix_point_in_block_one: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> (\\<V>s ! i)\\<in> (\\<B>s ! j) \\<Longrightarrow>N $$ (i, j) = 1\"\n  by (metis inc_matrix_point_in_block_one points_list_length blocks_list_length )   \n\nlemma matrix_point_not_in_block_zero: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j \\<Longrightarrow> N $$ (i, j) = 0\"\n  by(metis inc_matrix_point_not_in_block_zero points_list_length blocks_list_length)\n\nlemma matrix_point_in_block: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 1 \\<Longrightarrow> \\<V>s ! i \\<in> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length  inc_matrix_point_in_block)\n\nlemma matrix_point_not_in_block: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 0 \\<Longrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length inc_matrix_point_not_in_block)\n\nlemma matrix_point_not_in_block_iff: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 0 \\<longleftrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length inc_matrix_point_not_in_block_iff)\n\nlemma matrix_point_in_block_iff: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> N $$ (i, j) = 1 \\<longleftrightarrow> \\<V>s ! i \\<in> \\<B>s ! j\"\n  by (metis blocks_list_length points_list_length inc_matrix_point_in_block_iff)\n\nlemma matrix_subset_implies_one: \"I \\<subseteq> {..< \\<v>} \\<Longrightarrow> j < \\<b> \\<Longrightarrow> (!) \\<V>s ` I \\<subseteq> \\<B>s ! j \\<Longrightarrow> i \\<in> I \\<Longrightarrow> \n  N $$ (i, j) = 1\"\n  by (metis blocks_list_length points_list_length inc_matrix_subset_implies_one)\n\nlemma matrix_one_implies_membership: \n\"I \\<subseteq> {..< \\<v>} \\<Longrightarrow> j < size \\<B> \\<Longrightarrow> \\<forall>i\\<in>I. N $$ (i, j) = 1 \\<Longrightarrow> i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<B>s ! j\"\n  by (simp add: matrix_point_in_block_iff subset_iff)\n\ntext \\<open>Incidence Vector's of Incidence Matrix columns \\<close>\n\nlemma col_inc_vec_of: \"j < length \\<B>s \\<Longrightarrow> inc_vec_of \\<V>s (\\<B>s ! j) = col N j\"\n  by (simp add: inc_mat_col_inc_vec) \n\nlemma inc_vec_eq_iff_blocks: \n  assumes \"bl \\<in># \\<B>\"\n  assumes \"bl' \\<in># \\<B>\"\n  shows \"inc_vec_of \\<V>s bl = inc_vec_of \\<V>s bl' \\<longleftrightarrow> bl = bl'\"\nproof (intro iffI eq_vecI, simp_all add: inc_vec_dim assms)\n  define v1 :: \"'c :: {ring_1} vec\" where \"v1 = inc_vec_of \\<V>s bl\"\n  define v2 :: \"'c :: {ring_1} vec\" where \"v2 = inc_vec_of \\<V>s bl'\"\n  assume a: \"v1 = v2\"\n  then have \"dim_vec v1 = dim_vec v2\"\n    by (simp add: inc_vec_dim) \n  then have \"\\<And> i. i < dim_vec v1 \\<Longrightarrow> v1 $ i = v2 $ i\" using a by simp\n  then have \"\\<And> i. i < length \\<V>s \\<Longrightarrow> v1 $ i = v2 $ i\" by (simp add: v1_def inc_vec_dim)\n  then have \"\\<And> i. i < length \\<V>s \\<Longrightarrow> (\\<V>s ! i)  \\<in> bl \\<longleftrightarrow> (\\<V>s ! i)  \\<in> bl'\"\n    using  inc_vec_index_one_iff v1_def v2_def by metis \n  then have \"\\<And> x. x \\<in> \\<V> \\<Longrightarrow> x \\<in> bl \\<longleftrightarrow> x \\<in> bl'\"\n    using points_list_length valid_points_index_cons by auto \n  then show \"bl = bl'\" using wellformed assms\n    by (meson subset_antisym subset_eq)\nqed\n\ntext \\<open>Incidence matrix column properties\\<close>\n\nlemma N_col_def: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> (col N j) $ i = (if (\\<V>s ! i \\<in> \\<B>s ! j) then 1 else 0)\"\n  by (metis inc_mat_col_def points_list_length blocks_list_length) \n\nlemma N_col_def_indiv: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \\<V>s ! i \\<in> \\<B>s ! j \\<Longrightarrow> (col N j) $ i = 1\"\n     \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \\<V>s ! i \\<notin> \\<B>s ! j \\<Longrightarrow> (col N j) $ i = 0\"\n  by(simp_all add: inc_matrix_point_in_block_one inc_matrix_point_not_in_block_zero points_list_length)\n\nlemma N_col_list_map_elem: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \n    col N j $ i = map_vec (\\<lambda> x . if (x \\<in> (\\<B>s ! j)) then 1 else 0) (vec_of_list \\<V>s) $ i\"\n  by (metis inc_mat_col_list_map_elem points_list_length blocks_list_length) \n\nlemma N_col_list_map: \"j < \\<b> \\<Longrightarrow> col N j = map_vec (\\<lambda> x . if (x \\<in> (\\<B>s ! j)) then 1 else 0) (vec_of_list \\<V>s)\"\n  by (metis inc_mat_col_list_map blocks_list_length) \n\nlemma N_col_mset_point_set_img: \"j < \\<b> \\<Longrightarrow> \n    vec_mset (col N j) = image_mset (\\<lambda> x. if (x \\<in> (\\<B>s ! j)) then 1 else 0) (mset_set \\<V>)\"\n  using vec_mset_img_map N_col_list_map points_indexing\n  by (metis (no_types, lifting) finite_sets permutations_of_multisetD permutations_of_set_altdef) \n\nlemma matrix_col_to_block: \n  assumes \"j < \\<b>\"\n  shows \"\\<B>s ! j = (\\<lambda> k . \\<V>s ! k) ` {i \\<in> {..< \\<v>} . (col N j) $ i = 1}\"\nproof (intro subset_antisym subsetI)\n  fix x assume assm1: \"x \\<in> \\<B>s ! j\"\n  then have \"x \\<in> \\<V>\" using wellformed assms valid_blocks_index by blast \n  then obtain i where vs: \"\\<V>s ! i = x\" and \"i < \\<v>\"\n    using valid_points_index_cons by auto \n  then have inset: \"i \\<in> {..< \\<v>}\"\n    by fastforce\n  then have \"col N j $ i = 1\" using assm1 N_col_def assms vs\n    using \\<open>i < \\<v>\\<close> by presburger \n  then have \"i \\<in> {i. i \\<in> {..< \\<v>} \\<and> col N j $ i = 1}\"\n    using inset by blast\n  then show \"x \\<in> (!) \\<V>s ` {i.  i \\<in> {..<\\<v>} \\<and> col N j $ i = 1}\" using vs by blast\nnext\n  fix x assume assm2: \"x \\<in> ((\\<lambda> k . \\<V>s ! k) ` {i \\<in> {..< \\<v>} . col N j $ i = 1})\"\n  then obtain k where \"x = \\<V>s !k\" and inner: \"k \\<in>{i \\<in> {..< \\<v>} . col N j $ i = 1}\"\n    by blast \n  then have ilt: \"k < \\<v>\" by auto\n  then have \"N $$ (k, j) = 1\" using inner\n    by (metis (mono_tags) N_col_def assms matrix_point_in_block_iff matrix_point_not_in_block_zero mem_Collect_eq) \n  then show \"x \\<in> \\<B>s ! j\" using ilt\n    using \\<open>x = \\<V>s ! k\\<close> assms matrix_point_in_block_iff by blast\nqed\n\nlemma matrix_col_to_block_v2: \"j < \\<b> \\<Longrightarrow> \\<B>s ! j = (\\<lambda> k . \\<V>s ! k) ` map_col_to_block (col N j)\"\n  using matrix_col_to_block map_col_to_block_def by fastforce\n\nlemma matrix_col_in_blocks: \"j < \\<b> \\<Longrightarrow> (!) \\<V>s ` map_col_to_block (col N j) \\<in># \\<B>\"\n  using matrix_col_to_block_v2 by (metis (no_types, lifting) valid_blocks_index) \n\nlemma inc_matrix_col_block: \n  assumes \"c \\<in> set (cols N)\"\n  shows \"(\\<lambda> x. \\<V>s ! x) ` (map_col_to_block c) \\<in># \\<B>\"\nproof -\n  obtain j where \"c = col N j\" and \"j < \\<b>\" using assms cols_length cols_nth in_mset_conv_nth \n    ordered_incidence_system_axioms set_mset_mset by (metis dim_col_is_b)  \n  thus ?thesis\n    using matrix_col_in_blocks by blast \nqed\n\ntext \\<open> Incidence Matrix Row Definitions \\<close>\nlemma N_row_def: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> (row N i) $ j = (if (\\<V>s ! i \\<in> \\<B>s ! j) then 1 else 0)\"\n  by (metis inc_mat_row_def points_list_length blocks_list_length) \n\nlemma N_row_list_map_elem: \"j < \\<b> \\<Longrightarrow> i < \\<v> \\<Longrightarrow> \n    row N i $ j = map_vec (\\<lambda> bl . if ((\\<V>s ! i) \\<in> bl) then 1 else 0) (vec_of_list \\<B>s) $ j\"\n  by (metis inc_mat_row_list_map_elem points_list_length blocks_list_length) \n\nlemma N_row_list_map: \"i < \\<v> \\<Longrightarrow> \n    row N i = map_vec (\\<lambda> bl . if ((\\<V>s ! i) \\<in> bl) then 1 else 0) (vec_of_list \\<B>s)\"\n  by (simp add: inc_mat_row_list_map points_list_length blocks_list_length) \n\nlemma N_row_mset_blocks_img: \"i < \\<v> \\<Longrightarrow> \n    vec_mset (row N i) = image_mset (\\<lambda> x . if ((\\<V>s ! i) \\<in> x) then 1 else 0) \\<B>\"\n  using vec_mset_img_map N_row_list_map by metis\n\ntext \\<open>Alternate Block representations \\<close>\n\nlemma block_mat_cond_rep:\n  assumes \"j < length \\<B>s\"\n  shows \"(\\<B>s ! j) = {\\<V>s ! i | i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\nproof -\n  have cond: \"\\<And> i. i < length \\<V>s \\<and> N $$ (i, j) = 1 \\<longleftrightarrow>i \\<in> {..< \\<v>} \\<and> (col N j) $ i = 1\"\n    using assms points_list_length by auto\n  have \"(\\<B>s ! j) = (\\<lambda> k . \\<V>s ! k) ` {i \\<in> {..< \\<v>} . (col N j) $ i = 1}\" \n    using matrix_col_to_block assms by simp\n  also have \"... = {\\<V>s ! i | i. i \\<in> {..< \\<v>} \\<and> (col N j) $ i = 1}\" by auto\n  finally show \"(\\<B>s ! j) = {\\<V>s ! i | i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\n    using Collect_cong cond by auto\nqed\n\nlemma block_mat_cond_rep': \"j < length \\<B>s \\<Longrightarrow> (\\<B>s ! j) = ((!) \\<V>s) ` {i . i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\n  by (simp add: block_mat_cond_rep setcompr_eq_image)\n\nlemma block_mat_cond_rev: \n  assumes \"j < length \\<B>s\"\n  shows \"{i . i < length \\<V>s \\<and> N $$ (i, j) = 1} = ((List_Index.index) \\<V>s) ` (\\<B>s ! j)\"\nproof (intro Set.set_eqI iffI)\n  fix i assume a1: \"i \\<in> {i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\"\n  then have ilt1: \"i < length \\<V>s\" and Ni1: \"N $$ (i, j) = 1\" by auto\n  then obtain x where \"\\<V>s ! i = x\" and \"x \\<in> (\\<B>s ! j)\"\n    using assms inc_matrix_point_in_block by blast  \n  then have \"List_Index.index \\<V>s x = i\" using distinct  index_nth_id ilt1 by auto\n  then show \"i \\<in> List_Index.index \\<V>s ` \\<B>s ! j\" by (metis \\<open>x \\<in> \\<B>s ! j\\<close> imageI) \nnext\n  fix i assume a2: \"i \\<in> List_Index.index \\<V>s ` \\<B>s ! j\"\n  then obtain x where ieq: \"i = List_Index.index \\<V>s x\" and xin: \"x \\<in> \\<B>s !j\"\n    by blast \n  then have ilt: \"i < length \\<V>s\"\n    by (smt (z3) assms index_first index_le_size nat_less_le nth_mem_mset points_list_length \n        valid_points_index_cons wf_invalid_point)\n  then have \"N $$ (i, j) = 1\" using xin inc_matrix_point_in_block_one\n    by (metis ieq assms index_conv_size_if_notin less_irrefl_nat nth_index)\n  then show \"i \\<in> {i. i < length \\<V>s \\<and> N $$ (i, j) = 1}\" using ilt by simp\nqed\n\ntext \\<open>Incidence Matrix incidence system properties \\<close>\nlemma incomplete_block_col:\n  assumes \"j < \\<b>\"\n  assumes \"incomplete_block (\\<B>s ! j)\"\n  shows \"0 \\<in>$ (col N j)\" \nproof -\n  obtain x where \"x \\<in> \\<V>\" and \"x \\<notin> (\\<B>s ! j)\"\n    by (metis Diff_iff assms(2) incomplete_block_proper_subset psubset_imp_ex_mem)\n  then obtain i where \"\\<V>s ! i = x\" and \"i< \\<v>\" \n    using valid_points_index_cons by blast \n  then have \"N $$ (i, j) = 0\"\n    using \\<open>x \\<notin> \\<B>s ! j\\<close> assms(1) matrix_point_not_in_block_zero by blast \n  then have \"col N j $ i = 0\"\n    using N_col_def \\<open>\\<V>s ! i = x\\<close> \\<open>i < \\<v>\\<close> \\<open>x \\<notin> \\<B>s ! j\\<close> assms(1) by fastforce \n  thus ?thesis using vec_setI\n    by (smt (z3) \\<open>i < \\<v>\\<close> dim_col dim_row_is_v)\nqed\n\nlemma mat_rep_num_N_row: \n  assumes \"i < \\<v>\"\n  shows \"mat_rep_num N i = \\<B> rep (\\<V>s ! i)\"\nproof -\n  have \"count (image_mset (\\<lambda> x . if ((\\<V>s ! i) \\<in> x) then 1 else (0 :: int )) \\<B>) 1 = \n    size (filter_mset (\\<lambda> x . (\\<V>s ! i) \\<in> x) \\<B>)\"\n    using count_mset_split_image_filter[of \"\\<B>\" \"1\" \"\\<lambda> x . (0 :: int)\" \"\\<lambda> x . (\\<V>s ! i) \\<in> x\"] by simp\n  then have \"count (image_mset (\\<lambda> x . if ((\\<V>s ! i) \\<in> x) then 1 else (0 :: int )) \\<B>) 1\n    = \\<B> rep (\\<V>s ! i)\" by (simp add: point_rep_number_alt_def)\n  thus ?thesis using N_row_mset_blocks_img assms\n    by (simp add: mat_rep_num_def) \nqed\n\nlemma point_rep_mat_row_sum:  \"i < \\<v> \\<Longrightarrow> sum_vec (row N i) = \\<B> rep (\\<V>s ! i)\"\n  using count_vec_sum_ones_alt mat_rep_num_N_row mat_row_elems mat_rep_num_def by metis \n\nlemma mat_block_size_N_col: \n  assumes \"j < \\<b>\"\n  shows \"mat_block_size N j = card (\\<B>s ! j)\"\nproof -\n  have val_b: \"\\<B>s ! j \\<in># \\<B>\" using assms valid_blocks_index by auto \n  have \"\\<And> x. x \\<in># mset_set \\<V> \\<Longrightarrow> (\\<lambda>x . (0 :: int)) x \\<noteq> 1\" using zero_neq_one by simp\n  then have \"count (image_mset (\\<lambda> x. if (x \\<in> (\\<B>s ! j)) then 1 else (0 :: int)) (mset_set \\<V>)) 1 = \n    size (filter_mset (\\<lambda> x . x \\<in> (\\<B>s ! j)) (mset_set \\<V>))\"\n    using count_mset_split_image_filter [of \"mset_set \\<V>\" \"1\" \"(\\<lambda> x . (0 :: int))\" \"\\<lambda> x . x \\<in> \\<B>s ! j\"] \n    by simp\n  then have \"count (image_mset (\\<lambda> x. if (x \\<in> (\\<B>s ! j)) then 1 else (0 :: int)) (mset_set \\<V>)) 1 = card (\\<B>s ! j)\"\n    using val_b block_size_alt by (simp add: finite_sets)\n  thus ?thesis using N_col_mset_point_set_img assms mat_block_size_def by metis \nqed\n\nlemma block_size_mat_rep_sum: \"j < \\<b> \\<Longrightarrow> sum_vec (col N j) = mat_block_size N j\"\n  using count_vec_sum_ones_alt mat_block_size_N_col mat_block_size_def by (metis mat_col_elems) \n\nlemma mat_point_index_rep:\n  assumes \"I \\<subseteq> {..<\\<v>}\"\n  shows \"mat_point_index N I = \\<B> index ((\\<lambda> i. \\<V>s ! i) ` I)\"\nproof - \n  have \"\\<And> i . i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>\" using assms valid_points_index by auto \n  then have eqP: \"\\<And> j. j < dim_col N \\<Longrightarrow> ((\\<lambda> i. \\<V>s ! i) ` I) \\<subseteq> (\\<B>s ! j) \\<longleftrightarrow> (\\<forall> i \\<in> I . N $$ (i, j) = 1)\"\n  proof (intro iffI subsetI, simp_all)\n    show \"\\<And>j i. j < length \\<B>s \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>) \\<Longrightarrow> (!) \\<V>s ` I \\<subseteq> \\<B>s ! j \\<Longrightarrow> \n        \\<forall>i\\<in>I. N $$ (i, j) = 1\"\n      using matrix_subset_implies_one assms by simp\n    have \"\\<And>x.  x\\<in> (!) \\<V>s ` I \\<Longrightarrow> \\<exists> i \\<in> I. \\<V>s ! i = x\"\n      by auto \n    then show \"\\<And>j x. j < length \\<B>s \\<Longrightarrow> \\<forall>i\\<in>I. N $$ (i, j) = 1 \\<Longrightarrow> x \\<in> (!) \\<V>s ` I \n        \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> \\<V>s ! i \\<in> \\<V>) \\<Longrightarrow> x \\<in> \\<B>s ! j\"\n      using assms matrix_one_implies_membership by (metis blocks_list_length) \n  qed\n  have \"card {j . j < dim_col N \\<and> (\\<forall> i \\<in> I . N $$(i, j) = 1)} = \n      card {j . j < dim_col N \\<and> ((\\<lambda> i . \\<V>s ! i) ` I) \\<subseteq> \\<B>s ! j}\"\n    using eqP by (metis (mono_tags, lifting))\n  also have \"... = size {# b \\<in># \\<B> . ((\\<lambda> i . \\<V>s ! i) ` I) \\<subseteq> b #}\"\n    using filter_size_blocks_eq_card_indexes by auto\n  also have \"... = points_index \\<B> ((\\<lambda> i . \\<V>s ! i) ` I)\"\n    by (simp add: points_index_def)\n  finally have \"card {j . j < dim_col N \\<and> (\\<forall> i \\<in> I . N $$(i, j) = 1)} = \\<B> index ((\\<lambda> i . \\<V>s ! i) ` I)\"\n    by blast\n  thus ?thesis unfolding mat_point_index_def by simp\nqed\n\nlemma incidence_mat_two_index: \"i1 < \\<v> \\<Longrightarrow> i2 < \\<v> \\<Longrightarrow> \n    mat_point_index N {i1, i2} = \\<B> index {\\<V>s ! i1, \\<V>s ! i2}\"\n  using mat_point_index_two_alt[of  i1 N i2 ] mat_point_index_rep[of \"{i1, i2}\"] dim_row_is_v\n  by (metis (no_types, lifting) empty_subsetI image_empty image_insert insert_subset lessThan_iff) \n\nlemma ones_incidence_mat_block_size: \n  assumes \"j < \\<b>\"\n  shows \"((u\\<^sub>v \\<v>) \\<^sub>v* N) $ j = mat_block_size N j\"\nproof - \n  have \"dim_vec ((u\\<^sub>v \\<v>) \\<^sub>v* N) = \\<b>\" by (simp) \n  then have \"((u\\<^sub>v \\<v>) \\<^sub>v* N) $ j = (u\\<^sub>v \\<v>) \\<bullet> col N j\" using assms by simp \n  also have \"... = (\\<Sum> i \\<in> {0 ..< \\<v>}. (u\\<^sub>v \\<v>) $ i * (col N j) $ i)\" \n    by (simp add: scalar_prod_def)\n  also have \"... = sum_vec (col N j)\" using dim_row_is_v by (simp add: sum_vec_def)\n  finally show ?thesis  using block_size_mat_rep_sum assms by simp\nqed\n\nlemma mat_block_size_conv:  \"j < dim_col N \\<Longrightarrow> card (\\<B>s ! j) = mat_block_size N j\"\n  by (simp add: mat_block_size_N_col)\n\nlemma mat_inter_num_conv: \n  assumes \"j1 < dim_col N\" \"j2 < dim_col N\"\n  shows \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = mat_inter_num N j1 j2\"\nproof -\n  have eq_sets: \"\\<And> P. (\\<lambda> i . \\<V>s ! i) ` {i \\<in> {0..<\\<v>}. P (\\<V>s ! i)} = {x \\<in> \\<V> . P x}\"\n    by (metis Compr_image_eq lessThan_atLeast0 points_set_index_img)\n  have bin: \"\\<B>s ! j1 \\<in># \\<B>\" \"\\<B>s ! j2 \\<in># \\<B>\" using assms dim_col_is_b by simp_all\n  have \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = card ((\\<B>s ! j1) \\<inter> (\\<B>s ! j2))\" \n    by (simp add: intersection_number_def)\n  also have \"... = card {x . x \\<in> (\\<B>s ! j1) \\<and> x \\<in> (\\<B>s ! j2)}\"\n    by (simp add: Int_def) \n  also have \"... = card {x \\<in> \\<V>. x \\<in> (\\<B>s ! j1) \\<and> x \\<in> (\\<B>s ! j2)}\" using wellformed bin\n    by (meson wf_invalid_point) \n  also have \"... = card ((\\<lambda> i . \\<V>s ! i) ` {i \\<in> {0..<\\<v>}. (\\<V>s ! i) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j2)})\" \n    using eq_sets[of \"\\<lambda> x. x \\<in> (\\<B>s ! j1) \\<and> x \\<in> (\\<B>s ! j2)\"] by simp\n  also have \"... = card ({i \\<in> {0..<\\<v>}. (\\<V>s ! i) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j2)})\"\n    using points_indexing_inj card_image\n    by (metis (no_types, lifting) lessThan_atLeast0 lessThan_iff mem_Collect_eq points_list_length) \n  also have \"... = card ({i . i < \\<v> \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j1) \\<and> (\\<V>s ! i) \\<in> (\\<B>s ! j2)})\" by auto\n  also have \"... = card ({i . i < \\<v> \\<and> N $$ (i, j1) = 1 \\<and> N $$ (i, j2) = 1})\" using assms\n    by (metis (no_types, opaque_lifting) inc_mat_dim_col inc_matrix_point_in_block_iff points_list_length) \n  finally have \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = card {i . i < dim_row N \\<and> N $$ (i, j1) = 1 \\<and> N $$ (i, j2) = 1}\"\n    using dim_row_is_v by presburger\n  thus ?thesis using assms by (simp add: mat_inter_num_def)\nqed\n\nlemma non_empty_col_map_conv: \n  assumes \"j < dim_col N\"\n  shows \"non_empty_col N j \\<longleftrightarrow> \\<B>s ! j \\<noteq> {}\"\nproof (intro iffI)\n  assume \"non_empty_col N j\"\n  then obtain i where ilt: \"i < dim_row N\" and \"(col N j) $ i \\<noteq> 0\"\n    using non_empty_col_obtains assms by blast\n  then have \"(col N j) $ i = 1\"\n    using assms\n    by (metis N_col_def_indiv(1) N_col_def_indiv(2) dim_col_is_b dim_row_is_v) \n  then have \"\\<V>s ! i \\<in> \\<B>s ! j\"\n    by (smt (verit, best) assms ilt inc_mat_col_def dim_col_is_b inc_mat_dim_col inc_mat_dim_row) \n  thus \"\\<B>s ! j \\<noteq> {}\" by blast\nnext\n  assume a: \"\\<B>s ! j \\<noteq> {}\"\n  have \"\\<B>s ! j \\<in># \\<B>\" using assms dim_col_is_b by simp\n  then obtain x where \"x \\<in> \\<B>s ! j\" and \"x \\<in> \\<V>\" using wellformed a by auto\n  then obtain i where \"\\<V>s ! i \\<in> \\<B>s ! j\" and \"i < dim_row N\" using dim_row_is_v\n    using valid_points_index_cons by auto \n  then have \"N $$ (i, j) = 1\"\n    using assms by (meson inc_mat_of_index)  \n  then show \"non_empty_col N j\" using non_empty_col_alt_def\n    using \\<open>i < dim_row N\\<close> assms by fastforce \nqed\n\nlemma scalar_prod_inc_vec_inter_num: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\"\n  shows \"(col N j1) \\<bullet> (col N j2) = (\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2)\"\n  using scalar_prod_inc_vec_mat_inter_num assms N_carrier_mat\n  by (simp add: mat_inter_num_conv)\n\nlemma scalar_prod_block_size_lift_01: \n  assumes \"i < \\<b>\"\n  shows \"((col (lift_01_mat N) i) \\<bullet> (col (lift_01_mat N) i)) = (of_nat (card (\\<B>s ! i)) :: ('b :: {ring_1}))\"\nproof -\n  interpret z1: zero_one_matrix_ring_1 \"(lift_01_mat N)\"\n    by (intro_locales) (simp add: lift_mat_is_0_1)\n  show ?thesis using assms z1.scalar_prod_inc_vec_block_size_mat preserve_mat_block_size \n      mat_block_size_N_col lift_01_mat_def\n    by (metis inc_mat_dim_col lift_01_mat_simp(2) of_inj_on_01_hom.inj_on_01_hom_axioms size_mset)\nqed\n\nlemma scalar_prod_inter_num_lift_01: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\"\n  shows \"((col (lift_01_mat N) j1) \\<bullet> (col (lift_01_mat N) j2)) = (of_nat ((\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2)) :: ('b :: {ring_1}))\"\nproof -\n  interpret z1: zero_one_matrix_ring_1 \"(lift_01_mat N)\"\n    by (intro_locales) (simp add: lift_mat_is_0_1)\n  show ?thesis using assms z1.scalar_prod_inc_vec_mat_inter_num preserve_mat_inter_num \n    mat_inter_num_conv lift_01_mat_def blocks_list_length inc_mat_dim_col\n    by (metis  lift_01_mat_simp(2) of_inj_on_01_hom.inj_on_01_hom_axioms)\nqed\n\ntext \\<open> The System complement's incidence matrix flips 0's and 1's \\<close>\n\nlemma map_block_complement_entry: \"j < \\<b> \\<Longrightarrow> (map block_complement \\<B>s) ! j = block_complement (\\<B>s ! j)\"\n  using blocks_list_length by (metis nth_map) \n\nlemma complement_mat_entries: \n  assumes \"i < \\<v>\" and \"j < \\<b>\"\n  shows \"(\\<V>s ! i \\<notin> \\<B>s ! j) \\<longleftrightarrow> (\\<V>s ! i \\<in> (map block_complement \\<B>s) ! j)\"\n  using assms block_complement_def map_block_complement_entry valid_points_index by simp\n\nlemma length_blocks_complement: \"length (map block_complement \\<B>s) = \\<b>\"\n  by auto \n\nlemma ordered_complement: \"ordered_incidence_system \\<V>s (map block_complement \\<B>s)\"\nproof -\n  interpret inc: finite_incidence_system \\<V> \"complement_blocks\"\n    by (simp add: complement_finite)\n  have \"map inc.block_complement \\<B>s \\<in> permutations_of_multiset complement_blocks\"\n    using complement_image by (simp add: permutations_of_multiset_def)\n  then show ?thesis using ordered_incidence_sysI[of \"\\<V>\" \"complement_blocks\" \"\\<V>s\" \"(map block_complement \\<B>s)\"]\n    by (simp add: inc.finite_incidence_system_axioms points_indexing) \nqed\n\ninterpretation ordered_comp: ordered_incidence_system \"\\<V>s\" \"(map block_complement \\<B>s)\"\n  using ordered_complement by simp\n\nlemma complement_mat_entries_val: \n  assumes \"i < \\<v>\" and \"j < \\<b>\"\n  shows \"ordered_comp.N $$ (i, j) = (if \\<V>s ! i \\<in> \\<B>s ! j then 0 else 1)\"\nproof -\n  have cond: \"(\\<V>s ! i \\<notin> \\<B>s ! j) \\<longleftrightarrow> (\\<V>s ! i \\<in> (map block_complement \\<B>s) ! j)\"\n    using complement_mat_entries assms by simp\n  then have \"ordered_comp.N $$ (i, j) = (if (\\<V>s ! i \\<in> (map block_complement \\<B>s) ! j) then 1 else 0)\"\n    using assms ordered_comp.matrix_point_in_block_one ordered_comp.matrix_point_not_in_block_iff \n    by force \n  then show ?thesis using cond by simp\nqed\n\nlemma ordered_complement_mat: \"ordered_comp.N = mat \\<v> \\<b> (\\<lambda> (i,j) . if (\\<V>s ! i) \\<in> (\\<B>s ! j) then 0 else 1)\"\n  using complement_mat_entries_val by (intro eq_matI, simp_all)\n\nlemma ordered_complement_mat_map: \"ordered_comp.N = map_mat (\\<lambda>x. if x = 1 then 0 else 1) N\"\n  apply (intro eq_matI, simp_all)\n  using ordered_incidence_system.matrix_point_in_block_iff ordered_incidence_system_axioms \n    complement_mat_entries_val by (metis blocks_list_length) \n\n\nend\n\ntext \\<open>Establishing connection between incidence system and ordered incidence system locale \\<close>\n\nlemma (in incidence_system) alt_ordering_sysI: \"Vs \\<in> permutations_of_set \\<V> \\<Longrightarrow> Bs \\<in> permutations_of_multiset \\<B> \\<Longrightarrow> \n    ordered_incidence_system Vs Bs\"\n  by (unfold_locales) (simp_all add: permutations_of_multisetD permutations_of_setD wellformed)\n\nlemma (in finite_incidence_system) exists_ordering_sysI: \"\\<exists> Vs Bs . Vs \\<in> permutations_of_set \\<V> \\<and> \n  Bs \\<in> permutations_of_multiset \\<B> \\<and> ordered_incidence_system Vs Bs\"\nproof -\n  obtain Vs where \"Vs \\<in> permutations_of_set \\<V>\"\n    by (meson all_not_in_conv finite_sets permutations_of_set_empty_iff) \n  obtain Bs where \"Bs \\<in> permutations_of_multiset \\<B>\"\n    by (meson all_not_in_conv permutations_of_multiset_not_empty) \n  then show ?thesis using alt_ordering_sysI \\<open>Vs \\<in> permutations_of_set \\<V>\\<close> by blast \nqed\n\nlemma inc_sys_orderedI: \n  assumes \"incidence_system V B\" and \"distinct Vs\" and \"set Vs = V\" and \"mset Bs = B\" \n  shows \"ordered_incidence_system Vs Bs\"\nproof -\n  interpret inc: incidence_system V B using assms by simp\n  show ?thesis proof (unfold_locales)\n    show \"\\<And>b. b \\<in># mset Bs \\<Longrightarrow> b \\<subseteq> set Vs\" using inc.wellformed assms by simp\n    show \"distinct Vs\" using assms(2)permutations_of_setD(2) by auto \n  qed\nqed\n\ntext \\<open>Generalise the idea of an incidence matrix to an unordered context \\<close>\n\ndefinition is_incidence_matrix :: \"'c :: {ring_1} mat \\<Rightarrow> 'a set \\<Rightarrow> 'a set multiset \\<Rightarrow> bool\" where\n\"is_incidence_matrix N V B \\<longleftrightarrow> \n  (\\<exists> Vs Bs . (Vs \\<in> permutations_of_set V \\<and> Bs \\<in> permutations_of_multiset B \\<and> N = (inc_mat_of Vs Bs)))\"\n\nlemma (in incidence_system) is_incidence_mat_alt: \"is_incidence_matrix N \\<V> \\<B> \\<longleftrightarrow> \n  (\\<exists> Vs Bs. (set Vs = \\<V> \\<and> mset Bs = \\<B> \\<and> ordered_incidence_system Vs Bs \\<and> N = (inc_mat_of Vs Bs)))\"\nproof (intro iffI, simp add: is_incidence_matrix_def)\n  assume \"\\<exists>Vs. Vs \\<in> permutations_of_set \\<V> \\<and> (\\<exists>Bs. Bs \\<in> permutations_of_multiset \\<B> \\<and> N = inc_mat_of Vs Bs)\"\n  then obtain Vs Bs where \"Vs \\<in> permutations_of_set \\<V> \\<and> Bs \\<in> permutations_of_multiset \\<B> \\<and> N = inc_mat_of Vs Bs\"\n    by auto\n  then show \"\\<exists>Vs. set Vs = \\<V> \\<and> (\\<exists>Bs. mset Bs = \\<B> \\<and> ordered_incidence_system Vs Bs \\<and> N = inc_mat_of Vs Bs)\"\n    using incidence_system.alt_ordering_sysI incidence_system_axioms permutations_of_multisetD permutations_of_setD(1) \n    by blast \nnext\n  assume \"\\<exists>Vs Bs. set Vs = \\<V> \\<and> mset Bs = \\<B> \\<and> ordered_incidence_system Vs Bs \\<and> N = inc_mat_of Vs Bs\"\n  then obtain Vs Bs where s: \"set Vs = \\<V>\" and ms: \"mset Bs = \\<B>\" and \"ordered_incidence_system Vs Bs\" \n    and n: \"N = inc_mat_of Vs Bs\" by auto \n  then interpret ois: ordered_incidence_system Vs Bs by simp \n  have vs: \"Vs \\<in> permutations_of_set \\<V>\"\n    using ois.points_indexing s by blast \n  have \"Bs \\<in> permutations_of_multiset \\<B>\" using ois.blocks_indexing ms by blast\n  then show \"is_incidence_matrix N \\<V> \\<B> \" using n vs\n    using is_incidence_matrix_def by blast \nqed\n\nlemma (in ordered_incidence_system) is_incidence_mat_true: \"is_incidence_matrix N \\<V> \\<B> = True\"\n  using blocks_indexing is_incidence_matrix_def points_indexing by blast\n\nsubsection\\<open>Incidence Matrices on Design Subtypes \\<close>\n\nlocale ordered_design = ordered_incidence_system \\<V>s \\<B>s + design \"set \\<V>s\" \"mset \\<B>s\" \n  for \\<V>s and \\<B>s\nbegin\n\nlemma incidence_mat_non_empty_blocks: \n  assumes \"j < \\<b>\"\n  shows \"1 \\<in>$ (col N j)\" \nproof -\n  obtain bl where isbl: \"\\<B>s ! j = bl\" by simp\n  then have \"bl \\<in># \\<B>\"\n    using assms valid_blocks_index by auto \n  then obtain x where inbl: \"x \\<in> bl\"\n    using blocks_nempty by blast\n  then obtain i where isx: \"\\<V>s ! i = x\" and vali: \"i < \\<v>\"\n    using \\<open>bl \\<in># \\<B>\\<close> valid_points_index_cons wf_invalid_point by blast\n  then have \"N $$ (i, j) = 1\"\n    using \\<open>\\<B>s ! j = bl\\<close> \\<open>x \\<in> bl\\<close> assms matrix_point_in_block_one by blast\n  thus ?thesis using vec_setI\n    by (smt (verit, ccfv_SIG) N_col_def isx vali isbl inbl assms dim_vec_col_N of_nat_less_imp_less) \nqed\n\nlemma all_cols_non_empty: \"j < dim_col N \\<Longrightarrow> non_empty_col N j\"\n  using blocks_nempty non_empty_col_map_conv dim_col_is_b by simp \nend\n\nlocale ordered_simple_design = ordered_design \\<V>s \\<B>s + simple_design \"(set \\<V>s)\" \"mset \\<B>s\" for \\<V>s \\<B>s\nbegin\n\nlemma block_list_distinct: \"distinct \\<B>s\"\n  using block_mset_distinct by auto\n  \nlemma distinct_cols_N: \"distinct (cols N)\"\nproof -\n  have \"inj_on (\\<lambda> bl . inc_vec_of \\<V>s bl) (set \\<B>s)\" using inc_vec_eq_iff_blocks \n    by (simp add: inc_vec_eq_iff_blocks inj_on_def) \n  then show ?thesis using distinct_map inc_mat_of_cols_inc_vecs block_list_distinct\n    by (simp add: distinct_map inc_mat_of_cols_inc_vecs ) \nqed\n\nlemma simp_blocks_length_card: \"length \\<B>s = card (set \\<B>s)\"\n  using design_support_def simple_block_size_eq_card by fastforce\n\nlemma blocks_index_inj_on: \"inj_on (\\<lambda> i . \\<B>s ! i) {0..<length \\<B>s}\"\n  by (auto simp add: inj_on_def) (metis simp_blocks_length_card card_distinct nth_eq_iff_index_eq)\n\nlemma x_in_block_set_img: assumes \"x \\<in> set \\<B>s\" shows \"x \\<in> (!) \\<B>s ` {0..<length \\<B>s}\"\nproof -\n  obtain i where \"\\<B>s ! i = x\" and \"i < length \\<B>s\" using assms\n    by (meson in_set_conv_nth) \n  thus ?thesis by auto\nqed\n\nlemma blocks_index_simp_bij_betw: \"bij_betw (\\<lambda> i . \\<B>s ! i) {0..<length \\<B>s} (set \\<B>s)\"\n  using blocks_index_inj_on x_in_block_set_img by (auto simp add: bij_betw_def) \n\nlemma blocks_index_simp_unique:  \"i1 < length \\<B>s \\<Longrightarrow> i2 < length \\<B>s \\<Longrightarrow> i1 \\<noteq> i2 \\<Longrightarrow> \\<B>s ! i1 \\<noteq> \\<B>s ! i2\"\n  using block_list_distinct nth_eq_iff_index_eq by blast \n\nlemma lift_01_distinct_cols_N: \"distinct (cols (lift_01_mat N))\"\n  using  lift_01_mat_distinct_cols distinct_cols_N by simp\n\nend\n\nlocale ordered_proper_design = ordered_design \\<V>s \\<B>s + proper_design \"set \\<V>s\" \"mset \\<B>s\" \n  for \\<V>s and \\<B>s\nbegin\n\nlemma mat_is_proper: \"proper_inc_mat N\"\n  using design_blocks_nempty v_non_zero \n  by (auto simp add: proper_inc_mat_def)\n\nend\n\nlocale ordered_constant_rep = ordered_proper_design \\<V>s \\<B>s + constant_rep_design \"set \\<V>s\" \"mset \\<B>s\" \\<r> \n  for \\<V>s and \\<B>s and \\<r>\n\nbegin\n\nlemma incidence_mat_rep_num: \"i < \\<v> \\<Longrightarrow> mat_rep_num N i = \\<r>\"\n  using mat_rep_num_N_row rep_number valid_points_index by simp \n\nlemma incidence_mat_rep_num_sum: \"i < \\<v> \\<Longrightarrow> sum_vec (row N i) = \\<r>\"\n  using incidence_mat_rep_num  mat_rep_num_N_row\n  by (simp add: point_rep_mat_row_sum)  \n\nlemma transpose_N_mult_diag: \n  assumes \"i = j\" and \"i < \\<v>\" and \"j < \\<v>\" \n  shows \"(N * N\\<^sup>T) $$ (i, j) = \\<r>\"\nproof -\n  have unsq: \"\\<And> k . k < \\<b> \\<Longrightarrow> (N $$ (i, k))^2 = N $$ (i, k)\"\n    using assms(2) matrix_elems_one_zero by fastforce\n  then have \"(N * N\\<^sup>T) $$ (i, j) = (\\<Sum>k \\<in>{0..<\\<b>} . N $$ (i, k) * N $$ (j, k))\"\n    using assms(2) assms(3) transpose_mat_mult_entries[of \"i\" \"N\" \"j\"] by (simp) \n  also have \"... = (\\<Sum>k \\<in>{0..<\\<b>} . (N $$ (i, k))^2)\" using assms(1)\n    by (simp add: power2_eq_square)\n  also have \"... = (\\<Sum>k \\<in>{0..<\\<b>} . N $$ (i, k))\"\n    by (meson atLeastLessThan_iff sum.cong unsq) \n  also have \"... = (\\<Sum>k \\<in>{0..<\\<b>} . (row N i) $ k)\"\n    using assms(2) dim_col_is_b dim_row_is_v by auto \n  finally have \"(N * N\\<^sup>T) $$ (i, j) = sum_vec (row N i)\"\n    by (simp add: sum_vec_def)\n  thus ?thesis using incidence_mat_rep_num_sum\n    using assms(2) by presburger \nqed\n\nend\n\nlocale ordered_block_design = ordered_proper_design \\<V>s \\<B>s + block_design \"set \\<V>s\" \"mset \\<B>s\" \\<k>\n  for \\<V>s and \\<B>s and \\<k>\n\nbegin \n\n(* Every col has k ones *)\nlemma incidence_mat_block_size: \"j < \\<b> \\<Longrightarrow> mat_block_size N j = \\<k>\"\n  using mat_block_size_N_col uniform valid_blocks_index by fastforce\n\nlemma incidence_mat_block_size_sum: \"j < \\<b> \\<Longrightarrow> sum_vec (col N j) = \\<k>\"\n  using incidence_mat_block_size block_size_mat_rep_sum by presburger \n\nlemma ones_mult_incidence_mat_k_index: \"j < \\<b> \\<Longrightarrow> ((u\\<^sub>v \\<v>) \\<^sub>v* N) $ j = \\<k>\"\n  using ones_incidence_mat_block_size uniform incidence_mat_block_size by blast \n\nlemma ones_mult_incidence_mat_k: \"((u\\<^sub>v \\<v>) \\<^sub>v* N) = \\<k> \\<cdot>\\<^sub>v (u\\<^sub>v \\<b>)\"\n  using ones_mult_incidence_mat_k_index dim_col_is_b by (intro eq_vecI) (simp_all)\n\nend\n\nlocale ordered_incomplete_design = ordered_block_design \\<V>s \\<B>s \\<k> + incomplete_design \\<V> \\<B> \\<k>\n  for \\<V>s and \\<B>s and \\<k>\n\nbegin \n\nlemma incidence_mat_incomplete:  \"j < \\<b> \\<Longrightarrow> 0 \\<in>$ (col N j)\"\n  using valid_blocks_index incomplete_block_col incomplete_imp_incomp_block by blast \n\nend\n\nlocale ordered_t_wise_balance = ordered_proper_design \\<V>s \\<B>s + t_wise_balance \"set \\<V>s\" \"mset \\<B>s\" \\<t> \\<Lambda>\\<^sub>t\n  for \\<V>s and \\<B>s and \\<t> and \\<Lambda>\\<^sub>t\n\nbegin\n\nlemma incidence_mat_des_index: \n  assumes \"I \\<subseteq> {0..<\\<v>}\"\n  assumes \"card I = \\<t>\"\n  shows \"mat_point_index N I = \\<Lambda>\\<^sub>t\"\nproof -\n  have card: \"card ((!) \\<V>s ` I) = \\<t>\" using assms points_indexing_inj\n    by (metis (mono_tags, lifting) card_image ex_nat_less_eq not_le points_list_length subset_iff) \n  have \"((!) \\<V>s ` I) \\<subseteq> \\<V>\" using assms\n    by (metis atLeastLessThan_iff image_subset_iff subsetD valid_points_index)\n  then have \"\\<B> index ((!) \\<V>s ` I) = \\<Lambda>\\<^sub>t\" using balanced assms(2) card by simp\n  thus ?thesis using mat_point_index_rep assms(1) lessThan_atLeast0 by presburger \nqed\n\nend\n\nlocale ordered_pairwise_balance = ordered_t_wise_balance \\<V>s \\<B>s 2 \\<Lambda> + pairwise_balance \"set \\<V>s\" \"mset \\<B>s\" \\<Lambda>\n  for \\<V>s and \\<B>s and \\<Lambda>\nbegin\n\nlemma incidence_mat_des_two_index: \n  assumes \"i1 < \\<v>\"\n  assumes \"i2 < \\<v>\"\n  assumes \"i1 \\<noteq> i2\"\n  shows \"mat_point_index N {i1, i2} = \\<Lambda>\"\n  using incidence_mat_des_index incidence_mat_two_index \nproof -\n  have \"\\<V>s ! i1 \\<noteq> \\<V>s ! i2\" using assms(3)\n    by (simp add: assms(1) assms(2) distinct nth_eq_iff_index_eq points_list_length) \n  then have pair: \"card {\\<V>s ! i1, \\<V>s ! i2} = 2\" using card_2_iff by blast\n  have \"{\\<V>s ! i1, \\<V>s ! i2} \\<subseteq> \\<V>\" using assms\n    by (simp add: valid_points_index) \n  then have \"\\<B> index {\\<V>s ! i1, \\<V>s ! i2} = \\<Lambda>\" using pair\n    using balanced by blast \n  thus ?thesis using incidence_mat_two_index assms by simp\nqed\n\nlemma transpose_N_mult_off_diag: \n  assumes \"i \\<noteq> j\" and \"i < \\<v>\" and \"j < \\<v>\"\n  shows \"(N * N\\<^sup>T) $$ (i, j) = \\<Lambda>\"\nproof -\n  have rev: \"\\<And> k. k \\<in> {0..<\\<b>} \\<Longrightarrow> \\<not> (N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1) \\<longleftrightarrow> N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0\"\n    using assms matrix_elems_one_zero by auto\n  then have split: \"{0..<\\<b>} = {k \\<in> {0..<\\<b>}. N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1} \\<union> \n      {k \\<in> {0..<\\<b>}. N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0}\"\n    by blast\n  have zero: \"\\<And> k . k \\<in> {0..<\\<b>} \\<Longrightarrow> N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0 \\<Longrightarrow> N $$ (i, k) * N$$ (j, k) = 0\"\n    by simp \n  have djnt: \"{k \\<in> {0..<\\<b>}. N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1} \\<inter> \n    {k \\<in> {0..<\\<b>}. N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0} = {}\" using rev by auto\n  have fin1: \"finite {k \\<in> {0..<\\<b>}. N $$ (i, k) = 1 \\<and> N $$ (j, k) = 1}\" by simp\n  have fin2: \"finite {k \\<in> {0..<\\<b>}. N $$ (i, k) = 0 \\<or> N $$ (j, k) = 0}\" by simp\n  have \"(N * N\\<^sup>T) $$ (i, j) = (\\<Sum>k \\<in>{0..<\\<b>} . N $$ (i, k) * N $$ (j, k))\"\n    using assms(2) assms(3) transpose_mat_mult_entries[of \"i\" \"N\" \"j\"] by (simp)\n  also have \"... = (\\<Sum>k \\<in>({k' \\<in> {0..<\\<b>}. N $$ (i, k') = 1 \\<and> N $$ (j, k') = 1} \\<union> \n    {k' \\<in> {0..<\\<b>}. N $$ (i, k') = 0 \\<or> N $$ (j, k') = 0}) . N $$ (i, k) * N $$ (j, k))\"\n    using split by metis\n  also have \"... = (\\<Sum>k \\<in>{k' \\<in> {0..<\\<b>}. N $$ (i, k') = 1 \\<and> N $$ (j, k') = 1} . N $$ (i, k) * N $$ (j, k)) + \n    (\\<Sum>k \\<in>{k' \\<in> {0..<\\<b>}. N $$ (i, k') = 0 \\<or> N $$ (j, k') = 0} . N $$ (i, k) * N $$ (j, k))\"\n    using fin1 fin2 djnt sum.union_disjoint by blast \n  also have \"... = card {k' \\<in> {0..<\\<b>}. N $$ (i, k') = 1 \\<and> N $$ (j, k') = 1}\" \n    by (simp add: zero)\n  also have \"... = mat_point_index N {i, j}\" \n    using assms mat_point_index_two_alt[of i N j] by simp\n  finally show ?thesis using incidence_mat_des_two_index assms by simp\nqed\n\nend\n\ncontext pairwise_balance\nbegin\n\nlemma ordered_pbdI: \n  assumes \"\\<B> = mset \\<B>s\" and \"\\<V> = set \\<V>s\" and \"distinct \\<V>s\"\n  shows \"ordered_pairwise_balance \\<V>s \\<B>s \\<Lambda>\"\nproof -\n  interpret ois: ordered_incidence_system \\<V>s \\<B>s \n    using ordered_incidence_sysII assms finite_incidence_system_axioms by blast \n  show ?thesis using b_non_zero blocks_nempty assms t_lt_order balanced \n    by (unfold_locales)(simp_all)\nqed\nend\n\nlocale ordered_regular_pairwise_balance = ordered_pairwise_balance \"\\<V>s\" \"\\<B>s\" \\<Lambda> + \n  regular_pairwise_balance \"set \\<V>s\" \"mset \\<B>s\" \\<Lambda> \\<r> for \\<V>s and \\<B>s and \\<Lambda> and \\<r>\n\nsublocale ordered_regular_pairwise_balance \\<subseteq> ordered_constant_rep\n  by unfold_locales\n\ncontext ordered_regular_pairwise_balance\nbegin\n\ntext \\<open> Stinson's Theorem 1.15. Stinson \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close> \ngives an iff condition for incidence matrices of regular pairwise \nbalanced designs. The other direction is proven in the @{term \"zero_one_matrix\"} context \\<close>\nlemma rpbd_incidence_matrix_cond: \"N * (N\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m \\<v>) + (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m \\<v>)\"\nproof (intro eq_matI)\n  fix i j\n  assume ilt: \"i < dim_row (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\" \n    and jlt: \"j < dim_col (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\"\n  then have \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \n    (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v>) $$(i, j) + (int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j)\" \n    by simp\n  then have split: \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \n    (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v>) $$(i, j) + (\\<r> - \\<Lambda>) * ((1\\<^sub>m \\<v>) $$ (i, j))\"\n    using ilt jlt by simp\n  have lhs: \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v>) $$(i, j) = \\<Lambda>\" using ilt jlt by simp\n  show \"(N * N\\<^sup>T) $$ (i, j) = (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j)\"\n  proof (cases \"i = j\")\n    case True\n    then have rhs: \"(int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = (\\<r> - \\<Lambda>)\" using ilt by fastforce \n    have \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \\<Lambda> + (\\<r> - \\<Lambda>)\"\n      using True jlt by auto\n    then have \"(int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>) $$ (i, j) = \\<r>\" \n      using reg_index_lt_rep by (simp add: nat_diff_split)\n    then show ?thesis using lhs split rhs True transpose_N_mult_diag ilt jlt by simp\n  next\n    case False\n    then have \"(1\\<^sub>m \\<v>) $$ (i, j) = 0\" using ilt jlt by simp\n    then have \"(\\<r> - \\<Lambda>) * ((1\\<^sub>m \\<v>) $$ (i, j)) = 0\" using ilt jlt\n      by (simp add: \\<open>1\\<^sub>m \\<v> $$ (i, j) = 0\\<close>) \n    then show ?thesis using lhs transpose_N_mult_off_diag ilt jlt False by simp\n  qed\nnext\n  show \"dim_row (N * N\\<^sup>T) = dim_row (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\"\n    using transpose_N_mult_dim(1) by auto\nnext\n  show \"dim_col (N * N\\<^sup>T) = dim_col (int \\<Lambda> \\<cdot>\\<^sub>m J\\<^sub>m \\<v> + int (\\<r> - \\<Lambda>) \\<cdot>\\<^sub>m 1\\<^sub>m \\<v>)\"\n    using transpose_N_mult_dim(1) by auto\nqed\nend\n\nlocale ordered_bibd = ordered_proper_design \\<V>s \\<B>s + bibd \"set \\<V>s\" \"mset \\<B>s\" \\<k> \\<Lambda> \n  for \\<V>s and \\<B>s and \\<k> and \\<Lambda>\n\nsublocale ordered_bibd \\<subseteq> ordered_incomplete_design\n  by unfold_locales\n\nsublocale ordered_bibd \\<subseteq> ordered_constant_rep \\<V>s \\<B>s \\<r>\n  by unfold_locales\n\nsublocale ordered_bibd \\<subseteq> ordered_pairwise_balance\n  by unfold_locales\n\nlocale ordered_sym_bibd = ordered_bibd \\<V>s \\<B>s \\<k> \\<Lambda> + symmetric_bibd \"set \\<V>s\" \"mset \\<B>s\" \\<k> \\<Lambda> \n  for \\<V>s and \\<B>s and \\<k> and \\<Lambda>\n\n\nsublocale ordered_sym_bibd \\<subseteq> ordered_simple_design\n  by (unfold_locales)\n\nlocale ordered_const_intersect_design = ordered_proper_design \\<V>s \\<B>s + const_intersect_design \"set \\<V>s\" \"mset \\<B>s\" \\<m>\n  for \\<V>s \\<B>s \\<m>\n\n\nlocale simp_ordered_const_intersect_design = ordered_const_intersect_design + ordered_simple_design\nbegin \n\nlemma max_one_block_size_inter: \n  assumes \"\\<b> \\<ge> 2\"\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"card bl = \\<m>\"\n  assumes \"bl2 \\<in># \\<B> - {#bl#}\"\n  shows \"\\<m> < card bl2\"\nproof -\n  have sd: \"simple_design \\<V> \\<B>\"\n    by (simp add: simple_design_axioms) \n  have bl2in: \"bl2 \\<in># \\<B>\" using assms(4)\n    by (meson in_diffD)\n  have blin: \"bl \\<in># {#b \\<in># \\<B> . card b = \\<m>#}\" using assms(3) assms(2) by simp\n  then have slt: \"size {#b \\<in># \\<B> . card b = \\<m>#} = 1\" using simple_const_inter_iff sd assms(1)\n    by (metis count_empty count_eq_zero_iff less_one nat_less_le size_eq_0_iff_empty) \n  then have \"size {#b \\<in># (\\<B> - {#bl#}) . card b = \\<m>#} = 0\" using blin\n    by (smt (verit) add_mset_eq_singleton_iff count_eq_zero_iff count_filter_mset \n        filter_mset_add_mset insert_DiffM size_1_singleton_mset size_eq_0_iff_empty) \n  then have ne: \"card bl2 \\<noteq> \\<m>\" using assms(4)\n    by (metis (mono_tags, lifting) filter_mset_empty_conv size_eq_0_iff_empty) \n  thus ?thesis using inter_num_le_block_size assms bl2in nat_less_le by presburger \nqed\n\nlemma block_size_inter_num_cases:\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"\\<b> \\<ge> 2\"\n  shows \"\\<m> < card bl \\<or> (card bl = \\<m> \\<and> (\\<forall> bl' \\<in># (\\<B> - {#bl#}) . \\<m> < card bl'))\"\nproof (cases \"card bl = \\<m>\")\n  case True\n  have \"(\\<And> bl'. bl' \\<in># (\\<B> - {#bl#}) \\<Longrightarrow> \\<m> < card bl')\"\n    using max_one_block_size_inter True assms by simp\n  then show ?thesis using True by simp\nnext\n  case False\n  then have \"\\<m> < card bl\" using assms inter_num_le_block_size nat_less_le by presburger\n  then show ?thesis by simp\nqed\n\nlemma indexed_const_intersect: \n  assumes \"j1 < \\<b>\"\n  assumes \"j2 < \\<b>\"\n  assumes \"j1 \\<noteq> j2\"\n  shows \"(\\<B>s ! j1) |\\<inter>| (\\<B>s ! j2) = \\<m>\"\nproof -\n  obtain bl1 bl2 where \"bl1 \\<in># \\<B>\" and \"\\<B>s ! j1 = bl1\" and \"bl2 \\<in># \\<B> - {#bl1#}\" and \"\\<B>s ! j2 = bl2\" \n    using obtains_two_diff_block_indexes assms by fastforce \n  thus ?thesis by (simp add: const_intersect)\nqed\n\nlemma const_intersect_block_size_diff: \n  assumes \"j' < \\<b>\" and \"j < \\<b>\" and \"j \\<noteq> j'\" and \"card (\\<B>s ! j') = \\<m>\" and \"\\<b> \\<ge> 2\"\n  shows \"card (\\<B>s ! j) - \\<m> > 0\"\nproof -\n  obtain bl1 bl2 where \"bl1 \\<in># \\<B>\" and \"\\<B>s ! j' = bl1\" and \"bl2 \\<in># \\<B> - {#bl1#}\" and \"\\<B>s ! j = bl2\"\n    using assms(1) assms(2) assms(3) obtains_two_diff_block_indexes by fastforce \n  then have \"\\<m> < card (bl2)\" \n    using max_one_block_size_inter assms(4) assms(5) by blast  \n  thus ?thesis\n    by (simp add: \\<open>\\<B>s ! j = bl2\\<close>) \nqed\n\nlemma scalar_prod_inc_vec_const_inter: \n  assumes \"j1 < \\<b>\" \"j2 < \\<b>\" \"j1 \\<noteq> j2\"\n  shows \"(col N j1) \\<bullet> (col N j2) = \\<m>\"\n  using scalar_prod_inc_vec_inter_num indexed_const_intersect assms by simp\n\nend\n\nsubsection \\<open> Zero One Matrix Incidence System Existence \\<close>\ntext \\<open>We prove 0-1 matrices with certain properties imply the existence of an incidence system\nwith particular properties. This leads to Stinson's theorem in the other direction \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close> \\<close>\n\ncontext zero_one_matrix\nbegin\n\nlemma mat_is_ordered_incidence_sys: \"ordered_incidence_system [0..<(dim_row M)] (map (map_col_to_block) (cols M))\"\n  apply (unfold_locales, simp_all)\n  using map_col_to_block_wf atLeastLessThan_upt by blast\n\ninterpretation mat_ord_inc_sys: ordered_incidence_system \"[0..<(dim_row M)]\" \"(map (map_col_to_block) (cols M))\"\n  by (simp add: mat_is_ordered_incidence_sys)\n\nlemma mat_ord_inc_sys_N: \"mat_ord_inc_sys.N = lift_01_mat M\" \n  by (intro eq_matI, simp_all add: inc_mat_of_def map_col_to_block_elem) \n    (metis lift_01_mat_simp(3) lift_mat_01_index_iff(2) of_zero_neq_one_def)\n\nlemma map_col_to_block_mat_rep_num:\n  assumes \"x <dim_row M\"\n  shows \"({# map_col_to_block c . c \\<in># mset (cols M)#} rep x) = mat_rep_num M x\"\nproof -\n  have \"mat_rep_num M x = mat_rep_num (lift_01_mat M) x\" \n    using preserve_mat_rep_num mat_ord_inc_sys_N\n    by (metis assms lift_01_mat_def of_inj_on_01_hom.inj_on_01_hom_axioms)\n  then have \"mat_rep_num M x = (mat_rep_num mat_ord_inc_sys.N x)\" using mat_ord_inc_sys_N by (simp) \n  then have \"mat_rep_num M x = mset (map (map_col_to_block) (cols M)) rep x\"\n    using assms atLeastLessThan_upt card_atLeastLessThan mat_ord_inc_sys.mat_rep_num_N_row \n      mat_ord_inc_sys_point minus_nat.diff_0 by presburger\n  thus ?thesis using ordered_to_mset_col_blocks\n    by presburger \nqed\n\nend \n\ncontext zero_one_matrix_ring_1\nbegin\n\nlemma transpose_cond_index_vals: \n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"i < dim_row (M * (M\\<^sup>T))\"\n  assumes \"j < dim_col (M * (M\\<^sup>T))\"\n  shows \"i = j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = r\" \"i \\<noteq> j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = \\<Lambda>\"\n  using assms by auto\n\nend\n\nlocale zero_one_matrix_int = zero_one_matrix_ring_1 M for M :: \"int mat\"\nbegin\n\ntext \\<open>Some useful conditions on the transpose product for matrix system properties \\<close>\nlemma transpose_cond_diag_r:\n  assumes \"i < dim_row (M * (M\\<^sup>T))\"\n  assumes \"\\<And> j. i = j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = r\"\n  shows \"mat_rep_num M i = r\"\nproof -\n  have eqr: \"(M * M\\<^sup>T) $$ (i, i) = r\" using assms(2)\n    by simp\n  have unsq: \"\\<And> k . k < dim_col M \\<Longrightarrow> (M $$ (i, k))^2 = M $$ (i, k)\"\n    using assms elems01 by fastforce\n  have \"sum_vec (row M i) = (\\<Sum>k \\<in>{0..<(dim_col M)} . (row M i) $ k)\"\n    using assms by (simp add: sum_vec_def)\n  also have \"... = (\\<Sum>k \\<in>{0..<(dim_col M)} . M $$ (i, k))\"\n    using assms by auto\n  also have \"... = (\\<Sum>k \\<in>{0..<(dim_col M)} . M $$ (i, k)^2)\"\n    using atLeastLessThan_iff sum.cong unsq by simp\n  also have \"... = (\\<Sum>k \\<in>{0..<(dim_col M)} . M $$ (i, k) * M $$ (i, k))\"\n    using assms by (simp add: power2_eq_square)\n  also have \"... = (M * M\\<^sup>T) $$ (i, i)\" \n    using assms transpose_mat_mult_entries[of \"i\" \"M\" \"i\"] by simp\n  finally have \"sum_vec (row M i) = r\" using eqr by simp\n  thus ?thesis using mat_rep_num_sum_alt\n    by (metis assms(1) elems01 index_mult_mat(2) of_nat_eq_iff) \nqed\n\n\nlemma transpose_cond_non_diag:\n  assumes \"i1 < dim_row (M * (M\\<^sup>T))\"\n  assumes \"i2 < dim_row (M * (M\\<^sup>T))\"\n  assumes \"i1 \\<noteq> i2\"\n  assumes \"\\<And> j i. j \\<noteq> i \\<Longrightarrow> i < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> j < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = \\<Lambda>\"\n  shows \"\\<Lambda> = mat_point_index M {i1, i2}\"\nproof -\n  have ilt: \"i1 < dim_row M\" \"i2 < dim_row M\"\n    using assms(1) assms (2) by auto\n  have rev: \"\\<And> k. k \\<in> {0..<dim_col M} \\<Longrightarrow> \n      \\<not> (M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1) \\<longleftrightarrow> M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0\"\n    using assms elems01 by fastforce \n  then have split: \"{0..<dim_col M} = {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1} \\<union> \n      {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0}\"\n    by blast\n  have zero: \"\\<And> k . k \\<in> {0..<dim_col M} \\<Longrightarrow> M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0 \\<Longrightarrow> M $$ (i1, k) * M$$ (i2, k) = 0\"\n    by simp \n  have djnt: \"{k \\<in> {0..<dim_col M}. M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1} \\<inter> \n      {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0} = {}\" \n    using rev by auto\n  have fin1: \"finite {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 1 \\<and> M $$ (i2, k) = 1}\" by simp\n  have fin2: \"finite {k \\<in> {0..<dim_col M}. M $$ (i1, k) = 0 \\<or> M $$ (i2, k) = 0}\" by simp\n  have \"mat_point_index M {i1, i2} = card {k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 1 \\<and>M $$ (i2, k') = 1}\"\n    using mat_point_index_two_alt ilt assms(3) by auto\n  then have \"mat_point_index M {i1, i2} = \n    (\\<Sum>k \\<in>{k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 1 \\<and> M $$ (i2, k') = 1} . M $$ (i1, k) * M $$ (i2, k)) + \n    (\\<Sum>k \\<in>{k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 0 \\<or> M $$ (i2, k') = 0} . M $$ (i1, k) * M $$ (i2, k))\"\n    by (simp add: zero) (* Odd behaviour if I use also have here *)\n  also have \"... = (\\<Sum>k \\<in>({k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 1 \\<and> M $$ (i2, k') = 1} \\<union> \n    {k' \\<in> {0..<dim_col M}. M $$ (i1, k') = 0 \\<or> M $$ (i2, k') = 0}) . M $$ (i1, k) * M $$ (i2, k))\"\n    using fin1 fin2 djnt sum.union_disjoint by (metis (no_types, lifting)) \n  also have \"... =  (\\<Sum>k \\<in>{0..<dim_col M} . M $$ (i1, k) * M $$ (i2, k))\"\n    using split by metis\n  finally have \"mat_point_index M {i1, i2} = (M * (M\\<^sup>T)) $$ (i1, i2)\"\n    using assms(1) assms(2) transpose_mat_mult_entries[of \"i1\" \"M\" \"i2\"] by simp\n  thus ?thesis using assms by presburger \nqed\n\nlemma trans_cond_implies_map_rep_num:\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"x < dim_row M\"\n  shows \"(image_mset map_col_to_block (mset (cols M))) rep x = r\"\nproof -\n  interpret ois: ordered_incidence_system \"[0..<dim_row M]\" \"map map_col_to_block (cols M)\"\n    using mat_is_ordered_incidence_sys by simp\n  have eq: \"ois.\\<B> rep x = sum_vec (row M x)\" using ois.point_rep_mat_row_sum\n    by (simp add: assms(2) inc_mat_of_map_rev) \n  then have \"\\<And> j. x = j \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (x, j) = r\" using assms(1) transpose_cond_index_vals\n    by (metis assms(2) index_mult_mat(2) index_mult_mat(3) index_transpose_mat(3)) \n  thus ?thesis using eq transpose_cond_diag_r assms(2) index_mult_mat(2)\n    by (metis map_col_to_block_mat_rep_num) \nqed\n\nlemma trans_cond_implies_map_index:\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"ps \\<subseteq> {0..<dim_row M}\"\n  assumes \"card ps = 2\"\n  shows \"(image_mset map_col_to_block (mset (cols M))) index ps = \\<Lambda>\"\nproof - \n  interpret ois: ordered_incidence_system \"[0..<dim_row M]\" \"map map_col_to_block (cols M)\"\n    using mat_is_ordered_incidence_sys by simp\n  obtain i1 i2 where i1in: \"i1 <dim_row M\" and i2in: \"i2 <dim_row M\" and psis: \"ps = {i1, i2}\" and neqi: \"i1 \\<noteq> i2\"\n    using assms(2) assms(3) card_2_iff insert_subset by (metis atLeastLessThan_iff) \n  have cond: \"\\<And> j i. j \\<noteq> i \\<Longrightarrow> i < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> j < dim_row (M * (M\\<^sup>T)) \\<Longrightarrow> (M * (M\\<^sup>T)) $$ (i, j) = \\<Lambda>\"\n    using assms(1) by simp\n  then have \"(image_mset map_col_to_block (mset (cols M))) index ps = mat_point_index M ps\"\n     using ois.incidence_mat_two_index psis i1in i2in by (simp add: neqi inc_mat_of_map_rev)\n  thus ?thesis using cond transpose_cond_non_diag[of i1 i2 \\<Lambda>] i1in i2in index_mult_mat(2)[of \"M\" \"M\\<^sup>T\"] \n       neqi of_nat_eq_iff psis by simp\nqed\n\ntext \\<open> Stinson Theorem 1.15 existence direction \\<close>\nlemma rpbd_exists: \n  assumes \"dim_row M \\<ge> 2\" \\<comment> \\<open>Min two points\\<close>\n  assumes \"dim_col M \\<ge> 1\" \\<comment> \\<open>Min one block\\<close>\n  assumes \"\\<And> j. j < dim_col M \\<Longrightarrow> 1 \\<in>$ col M j\" \\<comment> \\<open>no empty blocks \\<close>\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  shows \"ordered_regular_pairwise_balance [0..<dim_row M] (map map_col_to_block (cols M)) \\<Lambda> r\"\nproof -\n  interpret ois: ordered_incidence_system \"[0..<dim_row M]\" \"(map map_col_to_block (cols M))\"\n    using mat_is_ordered_incidence_sys by simp\n  interpret pdes: ordered_design \"[0..<dim_row M]\" \"(map map_col_to_block (cols M))\"\n    using assms(2) mat_is_design assms(3)\n    by (simp add: ordered_design_def ois.ordered_incidence_system_axioms)  \n  show ?thesis using assms trans_cond_implies_map_index trans_cond_implies_map_rep_num \n    by (unfold_locales) (simp_all)\nqed\n\nlemma vec_k_uniform_mat_block_size: \n  assumes \"((u\\<^sub>v (dim_row M)) \\<^sub>v* M) = k \\<cdot>\\<^sub>v (u\\<^sub>v (dim_col M))\"\n  assumes \"j < dim_col M\"\n  shows \"mat_block_size M j = k\"\nproof -\n  have \"mat_block_size M j = sum_vec (col M j)\" using assms(2)\n    by (simp add: elems01 mat_block_size_sum_alt) \n  also have \"... = ((u\\<^sub>v (dim_row M)) \\<^sub>v* M) $ j\" using assms(2) \n    by (simp add: sum_vec_def scalar_prod_def)\n  finally show ?thesis using  assms(1) assms(2) by (simp)\nqed\n\nlemma vec_k_impl_uniform_block_size: \n  assumes \"((u\\<^sub>v (dim_row M)) \\<^sub>v* M) = k \\<cdot>\\<^sub>v (u\\<^sub>v (dim_col M))\"\n  assumes \"bl \\<in># (image_mset map_col_to_block (mset (cols M)))\"\n  shows \"card bl = k\"\nproof -\n  obtain j where jlt: \"j < dim_col M\" and bleq: \"bl = map_col_to_block (col M j)\"\n    using assms(2) obtain_block_index_map_block_set by blast \n  then have \"card (map_col_to_block (col M j)) = mat_block_size M j\"\n    by (simp add: map_col_to_block_size) \n  thus ?thesis using vec_k_uniform_mat_block_size assms(1) bleq jlt by blast \nqed\n\nlemma bibd_exists: \n  assumes \"dim_col M \\<ge> 1\" \\<comment> \\<open>Min one block\\<close>\n  assumes \"\\<And> j. j < dim_col M \\<Longrightarrow> 1 \\<in>$ col M j\" \\<comment> \\<open>no empty blocks \\<close>\n  assumes \"M * (M\\<^sup>T) = \\<Lambda> \\<cdot>\\<^sub>m (J\\<^sub>m (dim_row M)) + (r - \\<Lambda>) \\<cdot>\\<^sub>m (1\\<^sub>m (dim_row M))\"\n  assumes \"((u\\<^sub>v (dim_row M)) \\<^sub>v* M) = k \\<cdot>\\<^sub>v (u\\<^sub>v (dim_col M))\"\n  assumes \"(r ::nat) \\<ge> 0\"\n  assumes \"k \\<ge> 2\" \"k < dim_row M\"\n  shows \"ordered_bibd [0..<dim_row M] (map map_col_to_block (cols M)) k \\<Lambda>\"\nproof -\n  interpret ipbd: ordered_regular_pairwise_balance \"[0..<dim_row M]\" \"(map map_col_to_block (cols M))\" \\<Lambda> r\n    using rpbd_exists assms by simp\n  show ?thesis using vec_k_impl_uniform_block_size by (unfold_locales, simp_all add: assms)\nqed\n\nend\n\nsubsection \\<open>Isomorphisms and Incidence Matrices \\<close>\ntext \\<open>If two incidence systems have the same incidence matrix, they are isomorphic. Similarly\nif two incidence systems are isomorphic there exists an ordering such that they have the same\nincidence matrix \\<close>\nlocale two_ordered_sys = D1: ordered_incidence_system \\<V>s \\<B>s + D2: ordered_incidence_system \\<V>s' \\<B>s'\n  for \"\\<V>s\" and \"\\<B>s\" and \"\\<V>s'\" and \"\\<B>s'\" \n\nbegin\n\nlemma equal_inc_mat_isomorphism: \n  assumes \"D1.N = D2.N\"\n  shows \"incidence_system_isomorphism D1.\\<V> D1.\\<B> D2.\\<V> D2.\\<B> (\\<lambda> x . \\<V>s' ! (List_Index.index \\<V>s x))\"\nproof (unfold_locales)\n  show \"bij_betw (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x) D1.\\<V> D2.\\<V>\" \n  proof -\n    have comp: \"(\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x) = (\\<lambda> i. \\<V>s' ! i) \\<circ> (\\<lambda> y . List_Index.index \\<V>s y)\"\n      by (simp add: comp_def)\n    have leq: \"length \\<V>s = length \\<V>s'\" \n      using assms D1.dim_row_is_v D1.points_list_length D2.dim_row_is_v D2.points_list_length by force \n    have bij1: \"bij_betw (\\<lambda> i. \\<V>s' !i) {..<length \\<V>s} (set \\<V>s') \" using leq\n      by (simp add: bij_betw_nth D2.distinct) \n    have \"bij_betw (List_Index.index \\<V>s) (set \\<V>s) {..<length \\<V>s}\" using D1.distinct\n      by (simp add: bij_betw_index lessThan_atLeast0) \n    thus ?thesis using bij_betw_trans comp bij1 by simp\n  qed\nnext\n  have len:  \"length (map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) = length \\<B>s'\"\n    using length_map assms D1.dim_col_is_b by force \n  have mat_eq: \"\\<And> i j . D1.N $$ (i, j) = D2.N $$ (i, j)\" using assms\n    by simp \n  have vslen: \"length \\<V>s = length \\<V>s'\" using assms\n      using D1.dim_row_is_v D1.points_list_length D2.dim_row_is_v D2.points_list_length by force \n  have \"\\<And> j. j < length \\<B>s' \\<Longrightarrow> (map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = \\<B>s' ! j\"\n  proof -\n    fix j assume a: \"j < length \\<B>s'\" \n    then have \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x) ` (\\<B>s ! j)\"\n      by (metis D1.blocks_list_length D1.dim_col_is_b D2.blocks_list_length D2.dim_col_is_b assms nth_map) \n    also have \"... = (\\<lambda> i . \\<V>s' ! i) ` ((\\<lambda> x. List_Index.index \\<V>s x) ` (\\<B>s ! j))\" \n      by blast\n    also have \"... = ((\\<lambda> i . \\<V>s' ! i) ` {i . i < length \\<V>s \\<and> D1.N $$ (i, j) = 1})\" \n      using D1.block_mat_cond_rev a assms\n      by (metis (no_types, lifting) D1.blocks_list_length D1.dim_col_is_b D2.blocks_list_length D2.dim_col_is_b) \n    also have \"... = ((\\<lambda> i . \\<V>s' ! i) ` {i . i < length \\<V>s' \\<and> D2.N $$ (i, j) = 1})\" \n      using vslen mat_eq by simp\n    finally have \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = (\\<B>s' ! j)\" \n      using D2.block_mat_cond_rep' a by presburger\n    then show \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s) ! j = (\\<B>s' ! j)\" by simp\n  qed\n  then have \"map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s = \\<B>s'\" \n    using len nth_equalityI[of \"(map ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) \\<B>s)\" \"\\<B>s'\"] by simp\n  then show \"image_mset ((`) (\\<lambda>x. \\<V>s' ! List_Index.index \\<V>s x)) D1.\\<B> = D2.\\<B>\"\n    using mset_map by auto\nqed\n\nlemma equal_inc_mat_isomorphism_ex: \"D1.N = D2.N \\<Longrightarrow> \\<exists> \\<pi> . incidence_system_isomorphism D1.\\<V> D1.\\<B> D2.\\<V> D2.\\<B> \\<pi>\"\n  using equal_inc_mat_isomorphism by auto \n\nlemma equal_inc_mat_isomorphism_obtain: \n  assumes \"D1.N = D2.N\"\n  obtains \\<pi> where \"incidence_system_isomorphism D1.\\<V> D1.\\<B> D2.\\<V> D2.\\<B> \\<pi>\"\n  using equal_inc_mat_isomorphism assms by auto \n\nend\n\ncontext incidence_system_isomorphism\nbegin\n\nlemma exists_eq_inc_mats:\n  assumes \"finite \\<V>\" \"finite \\<V>'\"\n  obtains N where \"is_incidence_matrix N \\<V> \\<B>\" and \"is_incidence_matrix N \\<V>' \\<B>'\"\nproof -\n  obtain Vs where vsis: \"Vs \\<in> permutations_of_set \\<V>\" using assms\n    by (meson all_not_in_conv permutations_of_set_empty_iff) \n  obtain Bs where bsis: \"Bs \\<in> permutations_of_multiset \\<B>\"\n    by (meson all_not_in_conv permutations_of_multiset_not_empty) \n  have inj: \"inj_on \\<pi> \\<V>\" using bij\n    by (simp add: bij_betw_imp_inj_on) \n  then have mapvs: \"map \\<pi> Vs \\<in> permutations_of_set \\<V>'\" using permutations_of_set_image_inj\n    using \\<open>Vs \\<in> permutations_of_set \\<V>\\<close> iso_points_map by blast \n  have \"permutations_of_multiset (image_mset ((`)\\<pi>) \\<B>) = map ((`) \\<pi>) ` permutations_of_multiset \\<B>\"\n    using block_img permutations_of_multiset_image by blast \n  then have mapbs: \"map ((`) \\<pi>) Bs \\<in> permutations_of_multiset \\<B>'\" using bsis block_img by blast \n  define N :: \"'c :: {ring_1} mat\" where \"N \\<equiv> inc_mat_of Vs Bs\" \n  have \"is_incidence_matrix N \\<V> \\<B>\"\n    using N_def bsis is_incidence_matrix_def vsis by blast\n  have \"\\<And> bl . bl \\<in> (set Bs) \\<Longrightarrow> bl \\<subseteq> (set Vs)\"\n    by (meson bsis in_multiset_in_set ordered_incidence_system.wf_list source.alt_ordering_sysI vsis) \n  then have \"N = inc_mat_of (map \\<pi> Vs) (map ((`) \\<pi>) Bs)\" \n    using inc_mat_of_bij_betw inj\n    by (metis N_def permutations_of_setD(1) vsis) \n  then have \"is_incidence_matrix N \\<V>' \\<B>'\"\n    using mapbs mapvs is_incidence_matrix_def by blast \n  thus ?thesis\n    using \\<open>is_incidence_matrix N \\<V> \\<B>\\<close> that by auto \nqed\n\nend\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Fishers_Inequality/Incidence_Matrices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8918110396870287, "lm_q1q2_score": 0.7666576263299268}}
{"text": "(*  Title:      HOL/Wellfounded.thy\n    Author:     Tobias Nipkow\n    Author:     Lawrence C Paulson\n    Author:     Konrad Slind\n    Author:     Alexander Krauss\n    Author:     Andrei Popescu, TU Muenchen\n*)\n\nsection \\<open>Well-founded Recursion\\<close>\n\ntheory Wellfounded\n  imports Transitive_Closure\nbegin\n\nsubsection \\<open>Basic Definitions\\<close>\n\ndefinition wf :: \"('a \\<times> 'a) set \\<Rightarrow> bool\"\n  where \"wf r \\<longleftrightarrow> (\\<forall>P. (\\<forall>x. (\\<forall>y. (y, x) \\<in> r \\<longrightarrow> P y) \\<longrightarrow> P x) \\<longrightarrow> (\\<forall>x. P x))\"\n\ndefinition wfP :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where \"wfP r \\<longleftrightarrow> wf {(x, y). r x y}\"\n\nlemma wfP_wf_eq [pred_set_conv]: \"wfP (\\<lambda>x y. (x, y) \\<in> r) = wf r\"\n  by (simp add: wfP_def)\n\nlemma wfUNIVI: \"(\\<And>P x. (\\<forall>x. (\\<forall>y. (y, x) \\<in> r \\<longrightarrow> P y) \\<longrightarrow> P x) \\<Longrightarrow> P x) \\<Longrightarrow> wf r\"\n  unfolding wf_def by blast\n\nlemmas wfPUNIVI = wfUNIVI [to_pred]\n\ntext \\<open>Restriction to domain \\<open>A\\<close> and range \\<open>B\\<close>.\n  If \\<open>r\\<close> is well-founded over their intersection, then \\<open>wf r\\<close>.\\<close>\nlemma wfI:\n  assumes \"r \\<subseteq> A \\<times> B\"\n    and \"\\<And>x P. \\<lbrakk>\\<forall>x. (\\<forall>y. (y, x) \\<in> r \\<longrightarrow> P y) \\<longrightarrow> P x;  x \\<in> A; x \\<in> B\\<rbrakk> \\<Longrightarrow> P x\"\n  shows \"wf r\"\n  using assms unfolding wf_def by blast\n\nlemma wf_induct:\n  assumes \"wf r\"\n    and \"\\<And>x. \\<forall>y. (y, x) \\<in> r \\<longrightarrow> P y \\<Longrightarrow> P x\"\n  shows \"P a\"\n  using assms unfolding wf_def by blast\n\nlemmas wfP_induct = wf_induct [to_pred]\n\nlemmas wf_induct_rule = wf_induct [rule_format, consumes 1, case_names less, induct set: wf]\n\nlemmas wfP_induct_rule = wf_induct_rule [to_pred, induct set: wfP]\n\nlemma wf_not_sym: \"wf r \\<Longrightarrow> (a, x) \\<in> r \\<Longrightarrow> (x, a) \\<notin> r\"\n  by (induct a arbitrary: x set: wf) blast\n\nlemma wf_asym:\n  assumes \"wf r\" \"(a, x) \\<in> r\"\n  obtains \"(x, a) \\<notin> r\"\n  by (drule wf_not_sym[OF assms])\n\nlemma wf_imp_asym: \"wf r \\<Longrightarrow> asym r\"\n  by (auto intro: asymI elim: wf_asym)\n\nlemma wfP_imp_asymp: \"wfP r \\<Longrightarrow> asymp r\"\n  by (rule wf_imp_asym[to_pred])\n\nlemma wf_not_refl [simp]: \"wf r \\<Longrightarrow> (a, a) \\<notin> r\"\n  by (blast elim: wf_asym)\n\nlemma wf_irrefl:\n  assumes \"wf r\"\n  obtains \"(a, a) \\<notin> r\"\n  by (drule wf_not_refl[OF assms])\n\nlemma wf_imp_irrefl:\n  assumes \"wf r\" shows \"irrefl r\" \n  using wf_irrefl [OF assms] by (auto simp add: irrefl_def)\n\nlemma wfP_imp_irreflp: \"wfP r \\<Longrightarrow> irreflp r\"\n  by (rule wf_imp_irrefl[to_pred])\n\nlemma wf_wellorderI:\n  assumes wf: \"wf {(x::'a::ord, y). x < y}\"\n    and lin: \"OFCLASS('a::ord, linorder_class)\"\n  shows \"OFCLASS('a::ord, wellorder_class)\"\n  apply (rule wellorder_class.intro [OF lin])\n  apply (simp add: wellorder_class.intro class.wellorder_axioms.intro wf_induct_rule [OF wf])\n  done\n\nlemma (in wellorder) wf: \"wf {(x, y). x < y}\"\n  unfolding wf_def by (blast intro: less_induct)\n\nlemma (in wellorder) wfP_less[simp]: \"wfP (<)\"\n  by (simp add: wf wfP_def)\n\n\nsubsection \\<open>Basic Results\\<close>\n\ntext \\<open>Point-free characterization of well-foundedness\\<close>\n\nlemma wfE_pf:\n  assumes wf: \"wf R\"\n    and a: \"A \\<subseteq> R `` A\"\n  shows \"A = {}\"\nproof -\n  from wf have \"x \\<notin> A\" for x\n  proof induct\n    fix x assume \"\\<And>y. (y, x) \\<in> R \\<Longrightarrow> y \\<notin> A\"\n    then have \"x \\<notin> R `` A\" by blast\n    with a show \"x \\<notin> A\" by blast\n  qed\n  then show ?thesis by auto\nqed\n\nlemma wfI_pf:\n  assumes a: \"\\<And>A. A \\<subseteq> R `` A \\<Longrightarrow> A = {}\"\n  shows \"wf R\"\nproof (rule wfUNIVI)\n  fix P :: \"'a \\<Rightarrow> bool\" and x\n  let ?A = \"{x. \\<not> P x}\"\n  assume \"\\<forall>x. (\\<forall>y. (y, x) \\<in> R \\<longrightarrow> P y) \\<longrightarrow> P x\"\n  then have \"?A \\<subseteq> R `` ?A\" by blast\n  with a show \"P x\" by blast\nqed\n\n\nsubsubsection \\<open>Minimal-element characterization of well-foundedness\\<close>\n\nlemma wfE_min:\n  assumes wf: \"wf R\" and Q: \"x \\<in> Q\"\n  obtains z where \"z \\<in> Q\" \"\\<And>y. (y, z) \\<in> R \\<Longrightarrow> y \\<notin> Q\"\n  using Q wfE_pf[OF wf, of Q] by blast\n\nlemma wfE_min':\n  \"wf R \\<Longrightarrow> Q \\<noteq> {} \\<Longrightarrow> (\\<And>z. z \\<in> Q \\<Longrightarrow> (\\<And>y. (y, z) \\<in> R \\<Longrightarrow> y \\<notin> Q) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  using wfE_min[of R _ Q] by blast\n\nlemma wfI_min:\n  assumes a: \"\\<And>x Q. x \\<in> Q \\<Longrightarrow> \\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> R \\<longrightarrow> y \\<notin> Q\"\n  shows \"wf R\"\nproof (rule wfI_pf)\n  fix A\n  assume b: \"A \\<subseteq> R `` A\"\n  have False if \"x \\<in> A\" for x\n    using a[OF that] b by blast\n  then show \"A = {}\" by blast\nqed\n\nlemma wf_eq_minimal: \"wf r \\<longleftrightarrow> (\\<forall>Q x. x \\<in> Q \\<longrightarrow> (\\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> r \\<longrightarrow> y \\<notin> Q))\"\n  apply (rule iffI)\n   apply (blast intro:  elim!: wfE_min)\n  by (rule wfI_min) auto\n\nlemmas wfP_eq_minimal = wf_eq_minimal [to_pred]\n\n\nsubsubsection \\<open>Well-foundedness of transitive closure\\<close>\n\nlemma wf_trancl:\n  assumes \"wf r\"\n  shows \"wf (r\\<^sup>+)\"\nproof -\n  have \"P x\" if induct_step: \"\\<And>x. (\\<And>y. (y, x) \\<in> r\\<^sup>+ \\<Longrightarrow> P y) \\<Longrightarrow> P x\" for P x\n  proof (rule induct_step)\n    show \"P y\" if \"(y, x) \\<in> r\\<^sup>+\" for y\n      using \\<open>wf r\\<close> and that\n    proof (induct x arbitrary: y)\n      case (less x)\n      note hyp = \\<open>\\<And>x' y'. (x', x) \\<in> r \\<Longrightarrow> (y', x') \\<in> r\\<^sup>+ \\<Longrightarrow> P y'\\<close>\n      from \\<open>(y, x) \\<in> r\\<^sup>+\\<close> show \"P y\"\n      proof cases\n        case base\n        show \"P y\"\n        proof (rule induct_step)\n          fix y'\n          assume \"(y', y) \\<in> r\\<^sup>+\"\n          with \\<open>(y, x) \\<in> r\\<close> show \"P y'\"\n            by (rule hyp [of y y'])\n        qed\n      next\n        case step\n        then obtain x' where \"(x', x) \\<in> r\" and \"(y, x') \\<in> r\\<^sup>+\"\n          by simp\n        then show \"P y\" by (rule hyp [of x' y])\n      qed\n    qed\n  qed\n  then show ?thesis unfolding wf_def by blast\nqed\n\nlemmas wfP_trancl = wf_trancl [to_pred]\n\nlemma wf_converse_trancl: \"wf (r\\<inverse>) \\<Longrightarrow> wf ((r\\<^sup>+)\\<inverse>)\"\n  apply (subst trancl_converse [symmetric])\n  apply (erule wf_trancl)\n  done\n\ntext \\<open>Well-foundedness of subsets\\<close>\n\nlemma wf_subset: \"wf r \\<Longrightarrow> p \\<subseteq> r \\<Longrightarrow> wf p\"\n  by (simp add: wf_eq_minimal) fast\n\nlemmas wfP_subset = wf_subset [to_pred]\n\ntext \\<open>Well-foundedness of the empty relation\\<close>\n\nlemma wf_empty [iff]: \"wf {}\"\n  by (simp add: wf_def)\n\nlemma wfP_empty [iff]: \"wfP (\\<lambda>x y. False)\"\nproof -\n  have \"wfP bot\"\n    by (fact wf_empty[to_pred bot_empty_eq2])\n  then show ?thesis\n    by (simp add: bot_fun_def)\nqed\n\nlemma wf_Int1: \"wf r \\<Longrightarrow> wf (r \\<inter> r')\"\n  by (erule wf_subset) (rule Int_lower1)\n\nlemma wf_Int2: \"wf r \\<Longrightarrow> wf (r' \\<inter> r)\"\n  by (erule wf_subset) (rule Int_lower2)\n\ntext \\<open>Exponentiation.\\<close>\nlemma wf_exp:\n  assumes \"wf (R ^^ n)\"\n  shows \"wf R\"\nproof (rule wfI_pf)\n  fix A assume \"A \\<subseteq> R `` A\"\n  then have \"A \\<subseteq> (R ^^ n) `` A\"\n    by (induct n) force+\n  with \\<open>wf (R ^^ n)\\<close> show \"A = {}\"\n    by (rule wfE_pf)\nqed\n\ntext \\<open>Well-foundedness of \\<open>insert\\<close>.\\<close>\nlemma wf_insert [iff]: \"wf (insert (y,x) r) \\<longleftrightarrow> wf r \\<and> (x,y) \\<notin> r\\<^sup>*\" (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    by (blast elim: wf_trancl [THEN wf_irrefl]\n        intro: rtrancl_into_trancl1 wf_subset rtrancl_mono [THEN subsetD])\nnext\n  assume R: ?rhs\n  then have R': \"Q \\<noteq> {} \\<Longrightarrow> (\\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> r \\<longrightarrow> y \\<notin> Q)\" for Q\n    by (auto simp: wf_eq_minimal)\n  show ?lhs\n    unfolding wf_eq_minimal\n  proof clarify\n    fix Q :: \"'a set\" and q\n    assume \"q \\<in> Q\"\n    then obtain a where \"a \\<in> Q\" and a: \"\\<And>y. (y, a) \\<in> r \\<Longrightarrow> y \\<notin> Q\"\n      using R by (auto simp: wf_eq_minimal)\n    show \"\\<exists>z\\<in>Q. \\<forall>y'. (y', z) \\<in> insert (y, x) r \\<longrightarrow> y' \\<notin> Q\"\n    proof (cases \"a=x\")\n      case True\n      show ?thesis\n      proof (cases \"y \\<in> Q\")\n        case True\n        then obtain z where \"z \\<in> Q\" \"(z, y) \\<in> r\\<^sup>*\"\n                            \"\\<And>z'. (z', z) \\<in> r \\<longrightarrow> z' \\<in> Q \\<longrightarrow> (z', y) \\<notin> r\\<^sup>*\"\n          using R' [of \"{z \\<in> Q. (z,y) \\<in> r\\<^sup>*}\"] by auto\n        then have \"\\<forall>y'. (y', z) \\<in> insert (y, x) r \\<longrightarrow> y' \\<notin> Q\"\n          using R by(blast intro: rtrancl_trans)+\n        then show ?thesis\n          by (rule bexI) fact\n      next\n        case False\n        then show ?thesis\n          using a \\<open>a \\<in> Q\\<close> by blast\n      qed\n    next\n      case False\n      with a \\<open>a \\<in> Q\\<close> show ?thesis\n        by blast\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>Well-foundedness of image\\<close>\n\nlemma wf_map_prod_image_Dom_Ran:\n  fixes r:: \"('a \\<times> 'a) set\"\n    and f:: \"'a \\<Rightarrow> 'b\"\n  assumes wf_r: \"wf r\"\n    and inj: \"\\<And> a a'. a \\<in> Domain r \\<Longrightarrow> a' \\<in> Range r \\<Longrightarrow> f a = f a' \\<Longrightarrow> a = a'\"\n  shows \"wf (map_prod f f ` r)\"\nproof (unfold wf_eq_minimal, clarify)\n  fix B :: \"'b set\" and b::\"'b\"\n  assume \"b \\<in> B\"\n  define A where \"A = f -` B \\<inter> Domain r\"\n  show \"\\<exists>z\\<in>B. \\<forall>y. (y, z) \\<in> map_prod f f ` r \\<longrightarrow> y \\<notin> B\"\n  proof (cases \"A = {}\")\n    case False\n    then obtain a0 where \"a0 \\<in> A\" and \"\\<forall>a. (a, a0) \\<in> r \\<longrightarrow> a \\<notin> A\"\n      using wfE_min[OF wf_r] by auto\n    thus ?thesis\n      using inj unfolding A_def\n      by (intro bexI[of _ \"f a0\"]) auto\n  qed (use \\<open>b \\<in> B\\<close> in  \\<open>unfold A_def, auto\\<close>)\nqed\n\nlemma wf_map_prod_image: \"wf r \\<Longrightarrow> inj f \\<Longrightarrow> wf (map_prod f f ` r)\"\nby(rule wf_map_prod_image_Dom_Ran) (auto dest: inj_onD)\n\n\nsubsection \\<open>Well-Foundedness Results for Unions\\<close>\n\nlemma wf_union_compatible:\n  assumes \"wf R\" \"wf S\"\n  assumes \"R O S \\<subseteq> R\"\n  shows \"wf (R \\<union> S)\"\nproof (rule wfI_min)\n  fix x :: 'a and Q\n  let ?Q' = \"{x \\<in> Q. \\<forall>y. (y, x) \\<in> R \\<longrightarrow> y \\<notin> Q}\"\n  assume \"x \\<in> Q\"\n  obtain a where \"a \\<in> ?Q'\"\n    by (rule wfE_min [OF \\<open>wf R\\<close> \\<open>x \\<in> Q\\<close>]) blast\n  with \\<open>wf S\\<close> obtain z where \"z \\<in> ?Q'\" and zmin: \"\\<And>y. (y, z) \\<in> S \\<Longrightarrow> y \\<notin> ?Q'\"\n    by (erule wfE_min)\n  have \"y \\<notin> Q\" if \"(y, z) \\<in> S\" for y\n  proof\n    from that have \"y \\<notin> ?Q'\" by (rule zmin)\n    assume \"y \\<in> Q\"\n    with \\<open>y \\<notin> ?Q'\\<close> obtain w where \"(w, y) \\<in> R\" and \"w \\<in> Q\" by auto\n    from \\<open>(w, y) \\<in> R\\<close> \\<open>(y, z) \\<in> S\\<close> have \"(w, z) \\<in> R O S\" by (rule relcompI)\n    with \\<open>R O S \\<subseteq> R\\<close> have \"(w, z) \\<in> R\" ..\n    with \\<open>z \\<in> ?Q'\\<close> have \"w \\<notin> Q\" by blast\n    with \\<open>w \\<in> Q\\<close> show False by contradiction\n  qed\n  with \\<open>z \\<in> ?Q'\\<close> show \"\\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> R \\<union> S \\<longrightarrow> y \\<notin> Q\" by blast\nqed\n\n\ntext \\<open>Well-foundedness of indexed union with disjoint domains and ranges.\\<close>\n\nlemma wf_UN:\n  assumes r: \"\\<And>i. i \\<in> I \\<Longrightarrow> wf (r i)\"\n    and disj: \"\\<And>i j. \\<lbrakk>i \\<in> I; j \\<in> I; r i \\<noteq> r j\\<rbrakk> \\<Longrightarrow> Domain (r i) \\<inter> Range (r j) = {}\"\n  shows \"wf (\\<Union>i\\<in>I. r i)\"\n  unfolding wf_eq_minimal\nproof clarify\n  fix A and a :: \"'b\"\n  assume \"a \\<in> A\"\n  show \"\\<exists>z\\<in>A. \\<forall>y. (y, z) \\<in> \\<Union>(r ` I) \\<longrightarrow> y \\<notin> A\"\n  proof (cases \"\\<exists>i\\<in>I. \\<exists>a\\<in>A. \\<exists>b\\<in>A. (b, a) \\<in> r i\")\n    case True\n    then obtain i b c where ibc: \"i \\<in> I\" \"b \\<in> A\" \"c \\<in> A\" \"(c,b) \\<in> r i\"\n      by blast\n    have ri: \"\\<And>Q. Q \\<noteq> {} \\<Longrightarrow> \\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> r i \\<longrightarrow> y \\<notin> Q\"\n      using r [OF \\<open>i \\<in> I\\<close>] unfolding wf_eq_minimal by auto\n    show ?thesis\n      using ri [of \"{a. a \\<in> A \\<and> (\\<exists>b\\<in>A. (b, a) \\<in> r i) }\"] ibc disj\n      by blast\n  next\n    case False\n    with \\<open>a \\<in> A\\<close> show ?thesis\n      by blast\n  qed\nqed\n\nlemma wfP_SUP:\n  \"\\<forall>i. wfP (r i) \\<Longrightarrow> \\<forall>i j. r i \\<noteq> r j \\<longrightarrow> inf (Domainp (r i)) (Rangep (r j)) = bot \\<Longrightarrow>\n    wfP (\\<Squnion>(range r))\"\n  by (rule wf_UN[to_pred]) simp_all\n\nlemma wf_Union:\n  assumes \"\\<forall>r\\<in>R. wf r\"\n    and \"\\<forall>r\\<in>R. \\<forall>s\\<in>R. r \\<noteq> s \\<longrightarrow> Domain r \\<inter> Range s = {}\"\n  shows \"wf (\\<Union>R)\"\n  using assms wf_UN[of R \"\\<lambda>i. i\"] by simp\n\ntext \\<open>\n  Intuition: We find an \\<open>R \\<union> S\\<close>-min element of a nonempty subset \\<open>A\\<close> by case distinction.\n  \\<^enum> There is a step \\<open>a \\<midarrow>R\\<rightarrow> b\\<close> with \\<open>a, b \\<in> A\\<close>.\n    Pick an \\<open>R\\<close>-min element \\<open>z\\<close> of the (nonempty) set \\<open>{a\\<in>A | \\<exists>b\\<in>A. a \\<midarrow>R\\<rightarrow> b}\\<close>.\n    By definition, there is \\<open>z' \\<in> A\\<close> s.t. \\<open>z \\<midarrow>R\\<rightarrow> z'\\<close>. Because \\<open>z\\<close> is \\<open>R\\<close>-min in the\n    subset, \\<open>z'\\<close> must be \\<open>R\\<close>-min in \\<open>A\\<close>. Because \\<open>z'\\<close> has an \\<open>R\\<close>-predecessor, it cannot\n    have an \\<open>S\\<close>-successor and is thus \\<open>S\\<close>-min in \\<open>A\\<close> as well.\n  \\<^enum> There is no such step.\n    Pick an \\<open>S\\<close>-min element of \\<open>A\\<close>. In this case it must be an \\<open>R\\<close>-min\n    element of \\<open>A\\<close> as well.\n\\<close>\nlemma wf_Un: \"wf r \\<Longrightarrow> wf s \\<Longrightarrow> Domain r \\<inter> Range s = {} \\<Longrightarrow> wf (r \\<union> s)\"\n  using wf_union_compatible[of s r]\n  by (auto simp: Un_ac)\n\nlemma wf_union_merge: \"wf (R \\<union> S) = wf (R O R \\<union> S O R \\<union> S)\"\n  (is \"wf ?A = wf ?B\")\nproof\n  assume \"wf ?A\"\n  with wf_trancl have wfT: \"wf (?A\\<^sup>+)\" .\n  moreover have \"?B \\<subseteq> ?A\\<^sup>+\"\n    by (subst trancl_unfold, subst trancl_unfold) blast\n  ultimately show \"wf ?B\" by (rule wf_subset)\nnext\n  assume \"wf ?B\"\n  show \"wf ?A\"\n  proof (rule wfI_min)\n    fix Q :: \"'a set\" and x\n    assume \"x \\<in> Q\"\n    with \\<open>wf ?B\\<close> obtain z where \"z \\<in> Q\" and \"\\<And>y. (y, z) \\<in> ?B \\<Longrightarrow> y \\<notin> Q\"\n      by (erule wfE_min)\n    then have 1: \"\\<And>y. (y, z) \\<in> R O R \\<Longrightarrow> y \\<notin> Q\"\n      and 2: \"\\<And>y. (y, z) \\<in> S O R \\<Longrightarrow> y \\<notin> Q\"\n      and 3: \"\\<And>y. (y, z) \\<in> S \\<Longrightarrow> y \\<notin> Q\"\n      by auto\n    show \"\\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> ?A \\<longrightarrow> y \\<notin> Q\"\n    proof (cases \"\\<forall>y. (y, z) \\<in> R \\<longrightarrow> y \\<notin> Q\")\n      case True\n      with \\<open>z \\<in> Q\\<close> 3 show ?thesis by blast\n    next\n      case False\n      then obtain z' where \"z'\\<in>Q\" \"(z', z) \\<in> R\" by blast\n      have \"\\<forall>y. (y, z') \\<in> ?A \\<longrightarrow> y \\<notin> Q\"\n      proof (intro allI impI)\n        fix y assume \"(y, z') \\<in> ?A\"\n        then show \"y \\<notin> Q\"\n        proof\n          assume \"(y, z') \\<in> R\"\n          then have \"(y, z) \\<in> R O R\" using \\<open>(z', z) \\<in> R\\<close> ..\n          with 1 show \"y \\<notin> Q\" .\n        next\n          assume \"(y, z') \\<in> S\"\n          then have \"(y, z) \\<in> S O R\" using  \\<open>(z', z) \\<in> R\\<close> ..\n          with 2 show \"y \\<notin> Q\" .\n        qed\n      qed\n      with \\<open>z' \\<in> Q\\<close> show ?thesis ..\n    qed\n  qed\nqed\n\nlemma wf_comp_self: \"wf R \\<longleftrightarrow> wf (R O R)\"  \\<comment> \\<open>special case\\<close>\n  by (rule wf_union_merge [where S = \"{}\", simplified])\n\n\nsubsection \\<open>Well-Foundedness of Composition\\<close>\n\ntext \\<open>Bachmair and Dershowitz 1986, Lemma 2. [Provided by Tjark Weber]\\<close>\n\nlemma qc_wf_relto_iff:\n  assumes \"R O S \\<subseteq> (R \\<union> S)\\<^sup>* O R\" \\<comment> \\<open>R quasi-commutes over S\\<close>\n  shows \"wf (S\\<^sup>* O R O S\\<^sup>*) \\<longleftrightarrow> wf R\"\n    (is \"wf ?S \\<longleftrightarrow> _\")\nproof\n  show \"wf R\" if \"wf ?S\"\n  proof -\n    have \"R \\<subseteq> ?S\" by auto\n    with wf_subset [of ?S] that show \"wf R\"\n      by auto\n  qed\nnext\n  show \"wf ?S\" if \"wf R\"\n  proof (rule wfI_pf)\n    fix A\n    assume A: \"A \\<subseteq> ?S `` A\"\n    let ?X = \"(R \\<union> S)\\<^sup>* `` A\"\n    have *: \"R O (R \\<union> S)\\<^sup>* \\<subseteq> (R \\<union> S)\\<^sup>* O R\"\n    proof -\n      have \"(x, z) \\<in> (R \\<union> S)\\<^sup>* O R\" if \"(y, z) \\<in> (R \\<union> S)\\<^sup>*\" and \"(x, y) \\<in> R\" for x y z\n        using that\n      proof (induct y z)\n        case rtrancl_refl\n        then show ?case by auto\n      next\n        case (rtrancl_into_rtrancl a b c)\n        then have \"(x, c) \\<in> ((R \\<union> S)\\<^sup>* O (R \\<union> S)\\<^sup>*) O R\"\n          using assms by blast\n        then show ?case by simp\n      qed\n      then show ?thesis by auto\n    qed\n    then have \"R O S\\<^sup>* \\<subseteq> (R \\<union> S)\\<^sup>* O R\"\n      using rtrancl_Un_subset by blast\n    then have \"?S \\<subseteq> (R \\<union> S)\\<^sup>* O (R \\<union> S)\\<^sup>* O R\"\n      by (simp add: relcomp_mono rtrancl_mono)\n    also have \"\\<dots> = (R \\<union> S)\\<^sup>* O R\"\n      by (simp add: O_assoc[symmetric])\n    finally have \"?S O (R \\<union> S)\\<^sup>* \\<subseteq> (R \\<union> S)\\<^sup>* O R O (R \\<union> S)\\<^sup>*\"\n      by (simp add: O_assoc[symmetric] relcomp_mono)\n    also have \"\\<dots> \\<subseteq> (R \\<union> S)\\<^sup>* O (R \\<union> S)\\<^sup>* O R\"\n      using * by (simp add: relcomp_mono)\n    finally have \"?S O (R \\<union> S)\\<^sup>* \\<subseteq> (R \\<union> S)\\<^sup>* O R\"\n      by (simp add: O_assoc[symmetric])\n    then have \"(?S O (R \\<union> S)\\<^sup>*) `` A \\<subseteq> ((R \\<union> S)\\<^sup>* O R) `` A\"\n      by (simp add: Image_mono)\n    moreover have \"?X \\<subseteq> (?S O (R \\<union> S)\\<^sup>*) `` A\"\n      using A by (auto simp: relcomp_Image)\n    ultimately have \"?X \\<subseteq> R `` ?X\"\n      by (auto simp: relcomp_Image)\n    then have \"?X = {}\"\n      using \\<open>wf R\\<close> by (simp add: wfE_pf)\n    moreover have \"A \\<subseteq> ?X\" by auto\n    ultimately show \"A = {}\" by simp\n  qed\nqed\n\ncorollary wf_relcomp_compatible:\n  assumes \"wf R\" and \"R O S \\<subseteq> S O R\"\n  shows \"wf (S O R)\"\nproof -\n  have \"R O S \\<subseteq> (R \\<union> S)\\<^sup>* O R\"\n    using assms by blast\n  then have \"wf (S\\<^sup>* O R O S\\<^sup>*)\"\n    by (simp add: assms qc_wf_relto_iff)\n  then show ?thesis\n    by (rule Wellfounded.wf_subset) blast\nqed\n\n\nsubsection \\<open>Acyclic relations\\<close>\n\nlemma wf_acyclic: \"wf r \\<Longrightarrow> acyclic r\"\n  by (simp add: acyclic_def) (blast elim: wf_trancl [THEN wf_irrefl])\n\nlemmas wfP_acyclicP = wf_acyclic [to_pred]\n\n\nsubsubsection \\<open>Wellfoundedness of finite acyclic relations\\<close>\n\nlemma finite_acyclic_wf:\n  assumes \"finite r\" \"acyclic r\" shows \"wf r\"\n  using assms\nproof (induction r rule: finite_induct)\n  case (insert x r)\n  then show ?case\n    by (cases x) simp\nqed simp\n\nlemma finite_acyclic_wf_converse: \"finite r \\<Longrightarrow> acyclic r \\<Longrightarrow> wf (r\\<inverse>)\"\n  apply (erule finite_converse [THEN iffD2, THEN finite_acyclic_wf])\n  apply (erule acyclic_converse [THEN iffD2])\n  done\n\ntext \\<open>\n  Observe that the converse of an irreflexive, transitive,\n  and finite relation is again well-founded. Thus, we may\n  employ it for well-founded induction.\n\\<close>\nlemma wf_converse:\n  assumes \"irrefl r\" and \"trans r\" and \"finite r\"\n  shows \"wf (r\\<inverse>)\"\nproof -\n  have \"acyclic r\"\n    using \\<open>irrefl r\\<close> and \\<open>trans r\\<close>\n    by (simp add: irrefl_def acyclic_irrefl)\n  with \\<open>finite r\\<close> show ?thesis\n    by (rule finite_acyclic_wf_converse)\nqed\n\nlemma wf_iff_acyclic_if_finite: \"finite r \\<Longrightarrow> wf r = acyclic r\"\n  by (blast intro: finite_acyclic_wf wf_acyclic)\n\n\nsubsection \\<open>\\<^typ>\\<open>nat\\<close> is well-founded\\<close>\n\nlemma less_nat_rel: \"(<) = (\\<lambda>m n. n = Suc m)\\<^sup>+\\<^sup>+\"\nproof (rule ext, rule ext, rule iffI)\n  fix n m :: nat\n  show \"(\\<lambda>m n. n = Suc m)\\<^sup>+\\<^sup>+ m n\" if \"m < n\"\n    using that\n  proof (induct n)\n    case 0\n    then show ?case by auto\n  next\n    case (Suc n)\n    then show ?case\n      by (auto simp add: less_Suc_eq_le le_less intro: tranclp.trancl_into_trancl)\n  qed\n  show \"m < n\" if \"(\\<lambda>m n. n = Suc m)\\<^sup>+\\<^sup>+ m n\"\n    using that by (induct n) (simp_all add: less_Suc_eq_le reflexive le_less)\nqed\n\ndefinition pred_nat :: \"(nat \\<times> nat) set\"\n  where \"pred_nat = {(m, n). n = Suc m}\"\n\ndefinition less_than :: \"(nat \\<times> nat) set\"\n  where \"less_than = pred_nat\\<^sup>+\"\n\nlemma less_eq: \"(m, n) \\<in> pred_nat\\<^sup>+ \\<longleftrightarrow> m < n\"\n  unfolding less_nat_rel pred_nat_def trancl_def by simp\n\nlemma pred_nat_trancl_eq_le: \"(m, n) \\<in> pred_nat\\<^sup>* \\<longleftrightarrow> m \\<le> n\"\n  unfolding less_eq rtrancl_eq_or_trancl by auto\n\nlemma wf_pred_nat: \"wf pred_nat\"\n  unfolding wf_def\nproof clarify\n  fix P x\n  assume \"\\<forall>x'. (\\<forall>y. (y, x') \\<in> pred_nat \\<longrightarrow> P y) \\<longrightarrow> P x'\"\n  then show \"P x\"\n    unfolding pred_nat_def by (induction x) blast+\nqed\n\nlemma wf_less_than [iff]: \"wf less_than\"\n  by (simp add: less_than_def wf_pred_nat [THEN wf_trancl])\n\nlemma trans_less_than [iff]: \"trans less_than\"\n  by (simp add: less_than_def)\n\nlemma less_than_iff [iff]: \"((x,y) \\<in> less_than) = (x<y)\"\n  by (simp add: less_than_def less_eq)\n\nlemma irrefl_less_than: \"irrefl less_than\"\n  using irrefl_def by blast\n\nlemma asym_less_than: \"asym less_than\"\n  by (rule asymI) simp\n\nlemma total_less_than: \"total less_than\" and total_on_less_than [simp]: \"total_on A less_than\"\n  using total_on_def by force+\n\nlemma wf_less: \"wf {(x, y::nat). x < y}\"\n  by (rule Wellfounded.wellorder_class.wf)\n\n\nsubsection \\<open>Accessible Part\\<close>\n\ntext \\<open>\n  Inductive definition of the accessible part \\<open>acc r\\<close> of a\n  relation; see also \\<^cite>\\<open>\"paulin-tlca\"\\<close>.\n\\<close>\n\ninductive_set acc :: \"('a \\<times> 'a) set \\<Rightarrow> 'a set\" for r :: \"('a \\<times> 'a) set\"\n  where accI: \"(\\<And>y. (y, x) \\<in> r \\<Longrightarrow> y \\<in> acc r) \\<Longrightarrow> x \\<in> acc r\"\n\nabbreviation termip :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"termip r \\<equiv> accp (r\\<inverse>\\<inverse>)\"\n\nabbreviation termi :: \"('a \\<times> 'a) set \\<Rightarrow> 'a set\"\n  where \"termi r \\<equiv> acc (r\\<inverse>)\"\n\nlemmas accpI = accp.accI\n\nlemma accp_eq_acc [code]: \"accp r = (\\<lambda>x. x \\<in> Wellfounded.acc {(x, y). r x y})\"\n  by (simp add: acc_def)\n\n\ntext \\<open>Induction rules\\<close>\n\ntheorem accp_induct:\n  assumes major: \"accp r a\"\n  assumes hyp: \"\\<And>x. accp r x \\<Longrightarrow> \\<forall>y. r y x \\<longrightarrow> P y \\<Longrightarrow> P x\"\n  shows \"P a\"\n  apply (rule major [THEN accp.induct])\n  apply (rule hyp)\n   apply (rule accp.accI)\n   apply auto\n  done\n\nlemmas accp_induct_rule = accp_induct [rule_format, induct set: accp]\n\ntheorem accp_downward: \"accp r b \\<Longrightarrow> r a b \\<Longrightarrow> accp r a\"\n  by (cases rule: accp.cases)\n\nlemma not_accp_down:\n  assumes na: \"\\<not> accp R x\"\n  obtains z where \"R z x\" and \"\\<not> accp R z\"\nproof -\n  assume a: \"\\<And>z. R z x \\<Longrightarrow> \\<not> accp R z \\<Longrightarrow> thesis\"\n  show thesis\n  proof (cases \"\\<forall>z. R z x \\<longrightarrow> accp R z\")\n    case True\n    then have \"\\<And>z. R z x \\<Longrightarrow> accp R z\" by auto\n    then have \"accp R x\" by (rule accp.accI)\n    with na show thesis ..\n  next\n    case False then obtain z where \"R z x\" and \"\\<not> accp R z\"\n      by auto\n    with a show thesis .\n  qed\nqed\n\nlemma accp_downwards_aux: \"r\\<^sup>*\\<^sup>* b a \\<Longrightarrow> accp r a \\<longrightarrow> accp r b\"\n  by (erule rtranclp_induct) (blast dest: accp_downward)+\n\ntheorem accp_downwards: \"accp r a \\<Longrightarrow> r\\<^sup>*\\<^sup>* b a \\<Longrightarrow> accp r b\"\n  by (blast dest: accp_downwards_aux)\n\ntheorem accp_wfPI: \"\\<forall>x. accp r x \\<Longrightarrow> wfP r\"\nproof (rule wfPUNIVI)\n  fix P x\n  assume \"\\<forall>x. accp r x\" \"\\<forall>x. (\\<forall>y. r y x \\<longrightarrow> P y) \\<longrightarrow> P x\"\n  then show \"P x\"\n    using accp_induct[where P = P] by blast\nqed\n\ntheorem accp_wfPD: \"wfP r \\<Longrightarrow> accp r x\"\n  apply (erule wfP_induct_rule)\n  apply (rule accp.accI)\n  apply blast\n  done\n\ntheorem wfP_accp_iff: \"wfP r = (\\<forall>x. accp r x)\"\n  by (blast intro: accp_wfPI dest: accp_wfPD)\n\n\ntext \\<open>Smaller relations have bigger accessible parts:\\<close>\n\nlemma accp_subset:\n  assumes \"R1 \\<le> R2\"\n  shows \"accp R2 \\<le> accp R1\"\nproof (rule predicate1I)\n  fix x\n  assume \"accp R2 x\"\n  then show \"accp R1 x\"\n  proof (induct x)\n    fix x\n    assume \"\\<And>y. R2 y x \\<Longrightarrow> accp R1 y\"\n    with assms show \"accp R1 x\"\n      by (blast intro: accp.accI)\n  qed\nqed\n\n\ntext \\<open>This is a generalized induction theorem that works on\n  subsets of the accessible part.\\<close>\n\nlemma accp_subset_induct:\n  assumes subset: \"D \\<le> accp R\"\n    and dcl: \"\\<And>x z. D x \\<Longrightarrow> R z x \\<Longrightarrow> D z\"\n    and \"D x\"\n    and istep: \"\\<And>x. D x \\<Longrightarrow> (\\<And>z. R z x \\<Longrightarrow> P z) \\<Longrightarrow> P x\"\n  shows \"P x\"\nproof -\n  from subset and \\<open>D x\\<close>\n  have \"accp R x\" ..\n  then show \"P x\" using \\<open>D x\\<close>\n  proof (induct x)\n    fix x\n    assume \"D x\" and \"\\<And>y. R y x \\<Longrightarrow> D y \\<Longrightarrow> P y\"\n    with dcl and istep show \"P x\" by blast\n  qed\nqed\n\n\ntext \\<open>Set versions of the above theorems\\<close>\n\nlemmas acc_induct = accp_induct [to_set]\nlemmas acc_induct_rule = acc_induct [rule_format, induct set: acc]\nlemmas acc_downward = accp_downward [to_set]\nlemmas not_acc_down = not_accp_down [to_set]\nlemmas acc_downwards_aux = accp_downwards_aux [to_set]\nlemmas acc_downwards = accp_downwards [to_set]\nlemmas acc_wfI = accp_wfPI [to_set]\nlemmas acc_wfD = accp_wfPD [to_set]\nlemmas wf_acc_iff = wfP_accp_iff [to_set]\nlemmas acc_subset = accp_subset [to_set]\nlemmas acc_subset_induct = accp_subset_induct [to_set]\n\n\nsubsection \\<open>Tools for building wellfounded relations\\<close>\n\ntext \\<open>Inverse Image\\<close>\n\nlemma wf_inv_image [simp,intro!]: \n  fixes f :: \"'a \\<Rightarrow> 'b\"\n  assumes \"wf r\"\n  shows \"wf (inv_image r f)\"\nproof -\n  have \"\\<And>x P. x \\<in> P \\<Longrightarrow> \\<exists>z\\<in>P. \\<forall>y. (f y, f z) \\<in> r \\<longrightarrow> y \\<notin> P\"\n  proof -\n    fix P and x::'a\n    assume \"x \\<in> P\"\n    then obtain w where w: \"w \\<in> {w. \\<exists>x::'a. x \\<in> P \\<and> f x = w}\"\n      by auto\n    have *: \"\\<And>Q u. u \\<in> Q \\<Longrightarrow> \\<exists>z\\<in>Q. \\<forall>y. (y, z) \\<in> r \\<longrightarrow> y \\<notin> Q\"\n      using assms by (auto simp add: wf_eq_minimal)\n    show \"\\<exists>z\\<in>P. \\<forall>y. (f y, f z) \\<in> r \\<longrightarrow> y \\<notin> P\"\n      using * [OF w] by auto\n  qed\n  then show ?thesis\n    by (clarsimp simp: inv_image_def wf_eq_minimal)\nqed\n\n\nsubsubsection \\<open>Conversion to a known well-founded relation\\<close>\n\nlemma wf_if_convertible_to_wf:\n  fixes r :: \"'a rel\" and s :: \"'b rel\" and f :: \"'a \\<Rightarrow> 'b\"\n  assumes \"wf s\" and convertible: \"\\<And>x y. (x, y) \\<in> r \\<Longrightarrow> (f x, f y) \\<in> s\"\n  shows \"wf r\"\nproof (rule wfI_min[of r])\n  fix x :: 'a and Q :: \"'a set\"\n  assume \"x \\<in> Q\"\n  then obtain y where \"y \\<in> Q\" and \"\\<And>z. (f z, f y) \\<in> s \\<Longrightarrow> z \\<notin> Q\"\n    by (auto elim: wfE_min[OF wf_inv_image[of s f, OF \\<open>wf s\\<close>], unfolded in_inv_image])\n  thus \"\\<exists>z \\<in> Q. \\<forall>y. (y, z) \\<in> r \\<longrightarrow> y \\<notin> Q\"\n    by (auto intro: convertible)\nqed\n\nlemma wfP_if_convertible_to_wfP: \"wfP S \\<Longrightarrow> (\\<And>x y. R x y \\<Longrightarrow> S (f x) (f y)) \\<Longrightarrow> wfP R\"\n  using wf_if_convertible_to_wf[to_pred, of S R f] by simp\n\ntext \\<open>Converting to @{typ nat} is a very common special case that might be found more easily by\n  Sledgehammer.\\<close>\n\nlemma wfP_if_convertible_to_nat:\n  fixes f :: \"_ \\<Rightarrow> nat\"\n  shows \"(\\<And>x y. R x y \\<Longrightarrow> f x < f y) \\<Longrightarrow> wfP R\"\n  by (rule wfP_if_convertible_to_wfP[of \"(<) :: nat \\<Rightarrow> nat \\<Rightarrow> bool\", simplified])\n\n\nsubsubsection \\<open>Measure functions into \\<^typ>\\<open>nat\\<close>\\<close>\n\ndefinition measure :: \"('a \\<Rightarrow> nat) \\<Rightarrow> ('a \\<times> 'a) set\"\n  where \"measure = inv_image less_than\"\n\nlemma in_measure[simp, code_unfold]: \"(x, y) \\<in> measure f \\<longleftrightarrow> f x < f y\"\n  by (simp add:measure_def)\n\nlemma wf_measure [iff]: \"wf (measure f)\"\n  unfolding measure_def by (rule wf_less_than [THEN wf_inv_image])\n\nlemma wf_if_measure: \"(\\<And>x. P x \\<Longrightarrow> f(g x) < f x) \\<Longrightarrow> wf {(y,x). P x \\<and> y = g x}\"\n  for f :: \"'a \\<Rightarrow> nat\"\n  using wf_measure[of f] unfolding measure_def inv_image_def less_than_def less_eq\n  by (rule wf_subset) auto\n\n\nsubsubsection \\<open>Lexicographic combinations\\<close>\n\ndefinition lex_prod :: \"('a \\<times>'a) set \\<Rightarrow> ('b \\<times> 'b) set \\<Rightarrow> (('a \\<times> 'b) \\<times> ('a \\<times> 'b)) set\"\n    (infixr \"<*lex*>\" 80)\n    where \"ra <*lex*> rb = {((a, b), (a', b')). (a, a') \\<in> ra \\<or> a = a' \\<and> (b, b') \\<in> rb}\"\n\nlemma in_lex_prod[simp]: \"((a, b), (a', b')) \\<in> r <*lex*> s \\<longleftrightarrow> (a, a') \\<in> r \\<or> a = a' \\<and> (b, b') \\<in> s\"\n  by (auto simp:lex_prod_def)\n\nlemma wf_lex_prod [intro!]:\n  assumes \"wf ra\" \"wf rb\"\n  shows \"wf (ra <*lex*> rb)\"\nproof (rule wfI)\n  fix z :: \"'a \\<times> 'b\" and P\n  assume * [rule_format]: \"\\<forall>u. (\\<forall>v. (v, u) \\<in> ra <*lex*> rb \\<longrightarrow> P v) \\<longrightarrow> P u\"\n  obtain x y where zeq: \"z = (x,y)\"\n    by fastforce\n  have \"P(x,y)\" using \\<open>wf ra\\<close>\n  proof (induction x arbitrary: y rule: wf_induct_rule)\n    case (less x)\n    note lessx = less\n    show ?case using \\<open>wf rb\\<close> less\n    proof (induction y rule: wf_induct_rule)\n      case (less y)\n      show ?case\n        by (force intro: * less.IH lessx)\n    qed\n  qed\n  then show \"P z\"\n    by (simp add: zeq)\nqed auto\n\nlemma refl_lex_prod[simp]: \"refl r\\<^sub>B \\<Longrightarrow> refl (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (auto intro!: reflI dest: refl_onD)\n\nlemma irrefl_on_lex_prod[simp]:\n  \"irrefl_on A r\\<^sub>A \\<Longrightarrow> irrefl_on B r\\<^sub>B \\<Longrightarrow> irrefl_on (A \\<times> B) (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (auto intro!: irrefl_onI dest: irrefl_onD)\n\nlemma irrefl_lex_prod[simp]: \"irrefl r\\<^sub>A \\<Longrightarrow> irrefl r\\<^sub>B \\<Longrightarrow> irrefl (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (rule irrefl_on_lex_prod[of UNIV _ UNIV, unfolded UNIV_Times_UNIV])\n\nlemma sym_on_lex_prod[simp]:\n  \"sym_on A r\\<^sub>A \\<Longrightarrow> sym_on B r\\<^sub>B \\<Longrightarrow> sym_on (A \\<times> B) (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (auto intro!: sym_onI dest: sym_onD)\n\nlemma sym_lex_prod[simp]:\n  \"sym r\\<^sub>A \\<Longrightarrow> sym r\\<^sub>B \\<Longrightarrow> sym (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (rule sym_on_lex_prod[of UNIV _ UNIV, unfolded UNIV_Times_UNIV])\n\nlemma asym_on_lex_prod[simp]:\n  \"asym_on A r\\<^sub>A \\<Longrightarrow> asym_on B r\\<^sub>B \\<Longrightarrow> asym_on (A \\<times> B) (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (auto intro!: asym_onI dest: asym_onD)\n\nlemma asym_lex_prod[simp]:\n  \"asym r\\<^sub>A \\<Longrightarrow> asym r\\<^sub>B \\<Longrightarrow> asym (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (rule asym_on_lex_prod[of UNIV _ UNIV, unfolded UNIV_Times_UNIV])\n\nlemma trans_on_lex_prod[simp]:\n  assumes \"trans_on A r\\<^sub>A\" and \"trans_on B r\\<^sub>B\"\n  shows \"trans_on (A \\<times> B) (r\\<^sub>A <*lex*> r\\<^sub>B)\"\nproof (rule trans_onI)\n  fix x y z\n  show \"x \\<in> A \\<times> B \\<Longrightarrow> y \\<in> A \\<times> B \\<Longrightarrow> z \\<in> A \\<times> B \\<Longrightarrow>\n       (x, y) \\<in> r\\<^sub>A <*lex*> r\\<^sub>B \\<Longrightarrow> (y, z) \\<in> r\\<^sub>A <*lex*> r\\<^sub>B \\<Longrightarrow> (x, z) \\<in> r\\<^sub>A <*lex*> r\\<^sub>B\"\n  using trans_onD[OF \\<open>trans_on A r\\<^sub>A\\<close>, of \"fst x\" \"fst y\" \"fst z\"]\n  using trans_onD[OF \\<open>trans_on B r\\<^sub>B\\<close>, of \"snd x\" \"snd y\" \"snd z\"]\n  by auto\nqed\n\nlemma trans_lex_prod [simp,intro!]: \"trans r\\<^sub>A \\<Longrightarrow> trans r\\<^sub>B \\<Longrightarrow> trans (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (rule trans_on_lex_prod[of UNIV _ UNIV, unfolded UNIV_Times_UNIV])\n\nlemma total_on_lex_prod[simp]:\n  \"total_on A r\\<^sub>A \\<Longrightarrow> total_on B r\\<^sub>B \\<Longrightarrow> total_on (A \\<times> B) (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (auto simp: total_on_def)\n\nlemma total_lex_prod[simp]: \"total r\\<^sub>A \\<Longrightarrow> total r\\<^sub>B \\<Longrightarrow> total (r\\<^sub>A <*lex*> r\\<^sub>B)\"\n  by (rule total_on_lex_prod[of UNIV _ UNIV, unfolded UNIV_Times_UNIV])\n\ntext \\<open>lexicographic combinations with measure functions\\<close>\n\ndefinition mlex_prod :: \"('a \\<Rightarrow> nat) \\<Rightarrow> ('a \\<times> 'a) set \\<Rightarrow> ('a \\<times> 'a) set\" (infixr \"<*mlex*>\" 80)\n  where \"f <*mlex*> R = inv_image (less_than <*lex*> R) (\\<lambda>x. (f x, x))\"\n\nlemma\n  wf_mlex: \"wf R \\<Longrightarrow> wf (f <*mlex*> R)\" and\n  mlex_less: \"f x < f y \\<Longrightarrow> (x, y) \\<in> f <*mlex*> R\" and\n  mlex_leq: \"f x \\<le> f y \\<Longrightarrow> (x, y) \\<in> R \\<Longrightarrow> (x, y) \\<in> f <*mlex*> R\" and\n  mlex_iff: \"(x, y) \\<in> f <*mlex*> R \\<longleftrightarrow> f x < f y \\<or> f x = f y \\<and> (x, y) \\<in> R\"\n  by (auto simp: mlex_prod_def)\n\ntext \\<open>Proper subset relation on finite sets.\\<close>\ndefinition finite_psubset :: \"('a set \\<times> 'a set) set\"\n  where \"finite_psubset = {(A, B). A \\<subset> B \\<and> finite B}\"\n\nlemma wf_finite_psubset[simp]: \"wf finite_psubset\"\n  apply (unfold finite_psubset_def)\n  apply (rule wf_measure [THEN wf_subset])\n  apply (simp add: measure_def inv_image_def less_than_def less_eq)\n  apply (fast elim!: psubset_card_mono)\n  done\n\nlemma trans_finite_psubset: \"trans finite_psubset\"\n  by (auto simp: finite_psubset_def less_le trans_def)\n\nlemma in_finite_psubset[simp]: \"(A, B) \\<in> finite_psubset \\<longleftrightarrow> A \\<subset> B \\<and> finite B\"\n  unfolding finite_psubset_def by auto\n\ntext \\<open>max- and min-extension of order to finite sets\\<close>\n\ninductive_set max_ext :: \"('a \\<times> 'a) set \\<Rightarrow> ('a set \\<times> 'a set) set\"\n  for R :: \"('a \\<times> 'a) set\"\n  where max_extI[intro]:\n    \"finite X \\<Longrightarrow> finite Y \\<Longrightarrow> Y \\<noteq> {} \\<Longrightarrow> (\\<And>x. x \\<in> X \\<Longrightarrow> \\<exists>y\\<in>Y. (x, y) \\<in> R) \\<Longrightarrow> (X, Y) \\<in> max_ext R\"\n\nlemma max_ext_wf:\n  assumes wf: \"wf r\"\n  shows \"wf (max_ext r)\"\nproof (rule acc_wfI, intro allI)\n  show \"M \\<in> acc (max_ext r)\" (is \"_ \\<in> ?W\") for M\n  proof (induct M rule: infinite_finite_induct)\n    case empty\n    show ?case\n      by (rule accI) (auto elim: max_ext.cases)\n  next\n    case (insert a M)\n    from wf \\<open>M \\<in> ?W\\<close> \\<open>finite M\\<close> show \"insert a M \\<in> ?W\"\n    proof (induct arbitrary: M)\n      fix M a\n      assume \"M \\<in> ?W\"\n      assume [intro]: \"finite M\"\n      assume hyp: \"\\<And>b M. (b, a) \\<in> r \\<Longrightarrow> M \\<in> ?W \\<Longrightarrow> finite M \\<Longrightarrow> insert b M \\<in> ?W\"\n      have add_less: \"M \\<in> ?W \\<Longrightarrow> (\\<And>y. y \\<in> N \\<Longrightarrow> (y, a) \\<in> r) \\<Longrightarrow> N \\<union> M \\<in> ?W\"\n        if \"finite N\" \"finite M\" for N M :: \"'a set\"\n        using that by (induct N arbitrary: M) (auto simp: hyp)\n      show \"insert a M \\<in> ?W\"\n      proof (rule accI)\n        fix N\n        assume Nless: \"(N, insert a M) \\<in> max_ext r\"\n        then have *: \"\\<And>x. x \\<in> N \\<Longrightarrow> (x, a) \\<in> r \\<or> (\\<exists>y \\<in> M. (x, y) \\<in> r)\"\n          by (auto elim!: max_ext.cases)\n\n        let ?N1 = \"{n \\<in> N. (n, a) \\<in> r}\"\n        let ?N2 = \"{n \\<in> N. (n, a) \\<notin> r}\"\n        have N: \"?N1 \\<union> ?N2 = N\" by (rule set_eqI) auto\n        from Nless have \"finite N\" by (auto elim: max_ext.cases)\n        then have finites: \"finite ?N1\" \"finite ?N2\" by auto\n\n        have \"?N2 \\<in> ?W\"\n        proof (cases \"M = {}\")\n          case [simp]: True\n          have Mw: \"{} \\<in> ?W\" by (rule accI) (auto elim: max_ext.cases)\n          from * have \"?N2 = {}\" by auto\n          with Mw show \"?N2 \\<in> ?W\" by (simp only:)\n        next\n          case False\n          from * finites have N2: \"(?N2, M) \\<in> max_ext r\"\n            using max_extI[OF _ _ \\<open>M \\<noteq> {}\\<close>, where ?X = ?N2] by auto\n          with \\<open>M \\<in> ?W\\<close> show \"?N2 \\<in> ?W\" by (rule acc_downward)\n        qed\n        with finites have \"?N1 \\<union> ?N2 \\<in> ?W\"\n          by (rule add_less) simp\n        then show \"N \\<in> ?W\" by (simp only: N)\n      qed\n    qed\n  next\n    case infinite\n    show ?case\n      by (rule accI) (auto elim: max_ext.cases simp: infinite)\n  qed\nqed\n\nlemma max_ext_additive: \"(A, B) \\<in> max_ext R \\<Longrightarrow> (C, D) \\<in> max_ext R \\<Longrightarrow> (A \\<union> C, B \\<union> D) \\<in> max_ext R\"\n  by (force elim!: max_ext.cases)\n\ndefinition min_ext :: \"('a \\<times> 'a) set \\<Rightarrow> ('a set \\<times> 'a set) set\"\n  where \"min_ext r = {(X, Y) | X Y. X \\<noteq> {} \\<and> (\\<forall>y \\<in> Y. (\\<exists>x \\<in> X. (x, y) \\<in> r))}\"\n\nlemma min_ext_wf:\n  assumes \"wf r\"\n  shows \"wf (min_ext r)\"\nproof (rule wfI_min)\n  show \"\\<exists>m \\<in> Q. (\\<forall>n. (n, m) \\<in> min_ext r \\<longrightarrow> n \\<notin> Q)\" if nonempty: \"x \\<in> Q\"\n    for Q :: \"'a set set\" and x\n  proof (cases \"Q = {{}}\")\n    case True\n    then show ?thesis by (simp add: min_ext_def)\n  next\n    case False\n    with nonempty obtain e x where \"x \\<in> Q\" \"e \\<in> x\" by force\n    then have eU: \"e \\<in> \\<Union>Q\" by auto\n    with \\<open>wf r\\<close>\n    obtain z where z: \"z \\<in> \\<Union>Q\" \"\\<And>y. (y, z) \\<in> r \\<Longrightarrow> y \\<notin> \\<Union>Q\"\n      by (erule wfE_min)\n    from z obtain m where \"m \\<in> Q\" \"z \\<in> m\" by auto\n    from \\<open>m \\<in> Q\\<close> show ?thesis\n    proof (intro rev_bexI allI impI)\n      fix n\n      assume smaller: \"(n, m) \\<in> min_ext r\"\n      with \\<open>z \\<in> m\\<close> obtain y where \"y \\<in> n\" \"(y, z) \\<in> r\"\n        by (auto simp: min_ext_def)\n      with z(2) show \"n \\<notin> Q\" by auto\n    qed\n  qed\nqed\n\n\nsubsubsection \\<open>Bounded increase must terminate\\<close>\n\nlemma wf_bounded_measure:\n  fixes ub :: \"'a \\<Rightarrow> nat\"\n    and f :: \"'a \\<Rightarrow> nat\"\n  assumes \"\\<And>a b. (b, a) \\<in> r \\<Longrightarrow> ub b \\<le> ub a \\<and> ub a \\<ge> f b \\<and> f b > f a\"\n  shows \"wf r\"\n  by (rule wf_subset[OF wf_measure[of \"\\<lambda>a. ub a - f a\"]]) (auto dest: assms)\n\nlemma wf_bounded_set:\n  fixes ub :: \"'a \\<Rightarrow> 'b set\"\n    and f :: \"'a \\<Rightarrow> 'b set\"\n  assumes \"\\<And>a b. (b,a) \\<in> r \\<Longrightarrow> finite (ub a) \\<and> ub b \\<subseteq> ub a \\<and> ub a \\<supseteq> f b \\<and> f b \\<supset> f a\"\n  shows \"wf r\"\n  apply (rule wf_bounded_measure[of r \"\\<lambda>a. card (ub a)\" \"\\<lambda>a. card (f a)\"])\n  apply (drule assms)\n  apply (blast intro: card_mono finite_subset psubset_card_mono dest: psubset_eq[THEN iffD2])\n  done\n\nlemma finite_subset_wf:\n  assumes \"finite A\"\n  shows \"wf {(X, Y). X \\<subset> Y \\<and> Y \\<subseteq> A}\"\n  by (rule wf_subset[OF wf_finite_psubset[unfolded finite_psubset_def]])\n    (auto intro: finite_subset[OF _ assms])\n\nhide_const (open) acc accp\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Wellfounded.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637541053281, "lm_q2_score": 0.8918110353738529, "lm_q1q2_score": 0.766657622622046}}
{"text": "(*\n  File:    Primes_Omega.thy\n  Author:  Manuel Eberl, TU München\n\n  The primes \\<omega> function (i.e. the number of distinct prime factors)\n*)\nsection \\<open>The Prime \\<open>\\<omega>\\<close> function\\<close>\ntheory Primes_Omega\n  imports Dirichlet_Series.Dirichlet_Series Dirichlet_Series.Divisor_Count\nbegin\n\ntext \\<open>\n  The prime \\<open>\\<omega>\\<close> function $\\omega(n)$ counts the number of distinct prime factors of \\<open>n\\<close>.\n\\<close>\n\ndefinition primes_omega :: \"nat \\<Rightarrow> nat\" where\n  \"primes_omega n = card (prime_factors n)\"\n\nlemma primes_omega_prime [simp]: \"prime p \\<Longrightarrow> primes_omega p = 1\"\n  by (simp add: primes_omega_def prime_factorization_prime)\n\nlemma primes_omega_0 [simp]: \"primes_omega 0 = 0\"\n  by (simp add: primes_omega_def)\n\nlemma primes_omega_1 [simp]: \"primes_omega 1 = 0\"\n  by (simp add: primes_omega_def)\n\nlemma primes_omega_Suc_0 [simp]: \"primes_omega (Suc 0) = 0\"\n  by (simp add: primes_omega_def)\n\nlemma primes_omega_power [simp]: \"n > 0 \\<Longrightarrow> primes_omega (x ^ n) = primes_omega x\"\n  by (simp add: primes_omega_def prime_factors_power)\n\nlemma primes_omega_primepow [simp]: \"primepow n \\<Longrightarrow> primes_omega n = 1\"\n  by (auto simp: primepow_def)\n\nlemma primes_omega_eq_0_iff: \"primes_omega n = 0 \\<longleftrightarrow> n = 0 \\<or> n = 1\"\n  by (auto simp: primes_omega_def prime_factorization_empty_iff)\n\nlemma primes_omega_pos [simp, intro]: \"n > 1 \\<Longrightarrow> primes_omega n > 0\"\n  by (cases \"primes_omega n > 0\") (auto simp: primes_omega_eq_0_iff)\n\nlemma primes_omega_mult_coprime:\n  assumes \"coprime x y\" \"x > 0 \\<or> y > 0\"\n  shows   \"primes_omega (x * y) = primes_omega x + primes_omega y\"\nproof (cases \"x = 0 \\<or> y = 0\")\n  case False\n  hence \"prime_factors (x * y) = prime_factors x \\<union> prime_factors y\"\n    by (subst prime_factorization_mult) auto\n  also {\n    have \"prime_factors x \\<inter> prime_factors y = set_mset (prime_factorization (gcd x y))\"\n      using False by (subst prime_factorization_gcd) auto\n    also have \"gcd x y = 1\" using \\<open>coprime x y\\<close> by auto\n    finally have \"card (prime_factors x \\<union> prime_factors y) = primes_omega x + primes_omega y\"\n      unfolding primes_omega_def by (intro card_Un_disjoint) (use False in auto)\n  }\n  finally show ?thesis by (simp add: primes_omega_def)\nqed (use assms in auto)\n\nlemma divisor_count_squarefree:\n  assumes \"squarefree n\" \"n > 0\"\n  shows   \"divisor_count n = 2 ^ primes_omega n\"\nproof -\n  have \"divisor_count n = (\\<Prod>p\\<in>prime_factors n. Suc (multiplicity p n))\"\n    using assms by (subst divisor_count.prod_prime_factors') auto\n  also have \"\\<dots> = (\\<Prod>p\\<in>prime_factors n. 2)\"\n    using assms assms by (intro prod.cong) (auto simp: squarefree_factorial_semiring')\n  finally show ?thesis by (simp add: primes_omega_def)\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Prime_Distribution_Elementary/Primes_Omega.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206738932333, "lm_q2_score": 0.8499711794579722, "lm_q1q2_score": 0.7666065789665606}}
{"text": "(*  Title:      HOL/Isar_Examples/First_Order_Logic.thy\n    Author:     Makarius\n*)\n\nsection \\<open>A simple formulation of First-Order Logic\\<close>\n\ntext \\<open>\n  The subsequent theory development illustrates single-sorted intuitionistic\n  first-order logic with equality, formulated within the Pure framework.\n\\<close>\n\ntheory First_Order_Logic\n  imports Pure\nbegin\n\nsubsection \\<open>Abstract syntax\\<close>\n\ntypedecl i\ntypedecl o\n\njudgment Trueprop :: \"o \\<Rightarrow> prop\"  (\"_\" 5)\n\n\nsubsection \\<open>Propositional logic\\<close>\n\naxiomatization false :: o  (\"\\<bottom>\")\n  where falseE [elim]: \"\\<bottom> \\<Longrightarrow> A\"\n\n\naxiomatization imp :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longrightarrow>\" 25)\n  where impI [intro]: \"(A \\<Longrightarrow> B) \\<Longrightarrow> A \\<longrightarrow> B\"\n    and mp [dest]: \"A \\<longrightarrow> B \\<Longrightarrow> A \\<Longrightarrow> B\"\n\n\naxiomatization conj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<and>\" 35)\n  where conjI [intro]: \"A \\<Longrightarrow> B \\<Longrightarrow> A \\<and> B\"\n    and conjD1: \"A \\<and> B \\<Longrightarrow> A\"\n    and conjD2: \"A \\<and> B \\<Longrightarrow> B\"\n\ntheorem conjE [elim]:\n  assumes \"A \\<and> B\"\n  obtains A and B\nproof\n  from \\<open>A \\<and> B\\<close> show A\n    by (rule conjD1)\n  from \\<open>A \\<and> B\\<close> show B\n    by (rule conjD2)\nqed\n\n\naxiomatization disj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<or>\" 30)\n  where disjE [elim]: \"A \\<or> B \\<Longrightarrow> (A \\<Longrightarrow> C) \\<Longrightarrow> (B \\<Longrightarrow> C) \\<Longrightarrow> C\"\n    and disjI1 [intro]: \"A \\<Longrightarrow> A \\<or> B\"\n    and disjI2 [intro]: \"B \\<Longrightarrow> A \\<or> B\"\n\n\ndefinition true :: o  (\"\\<top>\")\n  where \"\\<top> \\<equiv> \\<bottom> \\<longrightarrow> \\<bottom>\"\n\ntheorem trueI [intro]: \\<top>\n  unfolding true_def ..\n\n\ndefinition not :: \"o \\<Rightarrow> o\"  (\"\\<not> _\" [40] 40)\n  where \"\\<not> A \\<equiv> A \\<longrightarrow> \\<bottom>\"\n\ntheorem notI [intro]: \"(A \\<Longrightarrow> \\<bottom>) \\<Longrightarrow> \\<not> A\"\n  unfolding not_def ..\n\ntheorem notE [elim]: \"\\<not> A \\<Longrightarrow> A \\<Longrightarrow> B\"\n  unfolding not_def\nproof -\n  assume \"A \\<longrightarrow> \\<bottom>\" and A\n  then have \\<bottom> ..\n  then show B ..\nqed\n\n\ndefinition iff :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longleftrightarrow>\" 25)\n  where \"A \\<longleftrightarrow> B \\<equiv> (A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n\ntheorem iffI [intro]:\n  assumes \"A \\<Longrightarrow> B\"\n    and \"B \\<Longrightarrow> A\"\n  shows \"A \\<longleftrightarrow> B\"\n  unfolding iff_def\nproof\n  from \\<open>A \\<Longrightarrow> B\\<close> show \"A \\<longrightarrow> B\" ..\n  from \\<open>B \\<Longrightarrow> A\\<close> show \"B \\<longrightarrow> A\" ..\nqed\n\ntheorem iff1 [elim]:\n  assumes \"A \\<longleftrightarrow> B\" and A\n  shows B\nproof -\n  from \\<open>A \\<longleftrightarrow> B\\<close> have \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n    unfolding iff_def .\n  then have \"A \\<longrightarrow> B\" ..\n  from this and \\<open>A\\<close> show B ..\nqed\n\ntheorem iff2 [elim]:\n  assumes \"A \\<longleftrightarrow> B\" and B\n  shows A\nproof -\n  from \\<open>A \\<longleftrightarrow> B\\<close> have \"(A \\<longrightarrow> B) \\<and> (B \\<longrightarrow> A)\"\n    unfolding iff_def .\n  then have \"B \\<longrightarrow> A\" ..\n  from this and \\<open>B\\<close> show A ..\nqed\n\n\nsubsection \\<open>Equality\\<close>\n\naxiomatization equal :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infixl \"=\" 50)\n  where refl [intro]: \"x = x\"\n    and subst: \"x = y \\<Longrightarrow> P x \\<Longrightarrow> P y\"\n\ntheorem trans [trans]: \"x = y \\<Longrightarrow> y = z \\<Longrightarrow> x = z\"\n  by (rule subst)\n\ntheorem sym [sym]: \"x = y \\<Longrightarrow> y = x\"\nproof -\n  assume \"x = y\"\n  from this and refl show \"y = x\"\n    by (rule subst)\nqed\n\n\nsubsection \\<open>Quantifiers\\<close>\n\naxiomatization All :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<forall>\" 10)\n  where allI [intro]: \"(\\<And>x. P x) \\<Longrightarrow> \\<forall>x. P x\"\n    and allD [dest]: \"\\<forall>x. P x \\<Longrightarrow> P a\"\n\naxiomatization Ex :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<exists>\" 10)\n  where exI [intro]: \"P a \\<Longrightarrow> \\<exists>x. P x\"\n    and exE [elim]: \"\\<exists>x. P x \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\n\nlemma \"(\\<exists>x. P (f x)) \\<longrightarrow> (\\<exists>y. P y)\"\nproof\n  assume \"\\<exists>x. P (f x)\"\n  then obtain x where \"P (f x)\" ..\n  then show \"\\<exists>y. P y\" ..\nqed\n\nlemma \"(\\<exists>x. \\<forall>y. R x y) \\<longrightarrow> (\\<forall>y. \\<exists>x. R x y)\"\nproof\n  assume \"\\<exists>x. \\<forall>y. R x y\"\n  then obtain x where \"\\<forall>y. R x y\" ..\n  show \"\\<forall>y. \\<exists>x. R x y\"\n  proof\n    fix y\n    from \\<open>\\<forall>y. R x y\\<close> have \"R x y\" ..\n    then show \"\\<exists>x. R x y\" ..\n  qed\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Isar_Examples/First_Order_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7666065750119476}}
{"text": "(*\n  File:    Efficient_Discrete_Sqrt.thy\n  Author:  Markus Großer, Manuel Eberl\n\n  A reasonably efficient algorithm to compute the square root of a natural number (rounded down)\n  and to test if a natural number is a perfect square.\n*)\ntheory Efficient_Discrete_Sqrt\nimports\n  Complex_Main\n  \"HOL-Computational_Algebra.Computational_Algebra\"\n  \"HOL-Library.Discrete\"\n  \"HOL-Library.Tree\"\n  \"HOL-Library.IArray\"\nbegin\nsection \\<open>Efficient Algorithms for the Square Root on \\<open>\\<nat>\\<close>\\<close>\n\n(*\n  TODO: This could perhaps be moved somewhere else. Thre is also probably some overlap\n  with Sqrt_Babylonian\n*)\n\nsubsection \\<open>A Discrete Variant of Heron's Algorithm\\<close>\n\ntext \\<open>\n  An algorithm for calculating the discrete square root, taken from \n  Cohen~\\<^cite>\\<open>\"cohen2010algebraic\"\\<close>. This algorithm is essentially a discretised variant of\n  Heron's method or Newton's method specialised to the square root function.\n\\<close>\n\nlemma sqrt_eq_floor_sqrt: \"Discrete.sqrt n = nat \\<lfloor>sqrt n\\<rfloor>\"\nproof -\n  have \"real ((nat \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2) = (real (nat \\<lfloor>sqrt n\\<rfloor>))\\<^sup>2\"\n    by simp\n  also have \"\\<dots> \\<le> sqrt (real n) ^ 2\"\n    by (intro power_mono) auto\n  also have \"\\<dots> = real n\" by simp\n  finally have \"(nat \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2 \\<le> n\"\n    by (simp only: of_nat_le_iff)\n  moreover have \"n < (Suc (nat \\<lfloor>sqrt n\\<rfloor>))\\<^sup>2\" proof -\n    have \"(1 + \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2 > n\"\n      using floor_correct[of \"sqrt n\"] real_le_rsqrt[of \"1 + \\<lfloor>sqrt n\\<rfloor>\" n]\n        of_int_less_iff[of n \"(1 + \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2\"] not_le\n      by fastforce\n    then show ?thesis\n      using le_nat_floor[of \"Suc (nat \\<lfloor>sqrt n\\<rfloor>)\" \"sqrt n\"]\n        of_nat_le_iff[of \"(Suc (nat \\<lfloor>sqrt n\\<rfloor>))\\<^sup>2\" n] real_le_rsqrt[of _ n] not_le\n      by fastforce\n  qed\n  ultimately show ?thesis using sqrt_unique by fast\nqed\n\nfun newton_sqrt_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"newton_sqrt_aux x n =\n     (let y = (x + n div x) div 2\n      in if y < x then newton_sqrt_aux y n else x)\"\n\ndeclare newton_sqrt_aux.simps [simp del]\n\nlemma newton_sqrt_aux_simps:\n  \"(x + n div x) div 2 < x \\<Longrightarrow> newton_sqrt_aux x n = newton_sqrt_aux ((x + n div x) div 2) n\"\n  \"(x + n div x) div 2 \\<ge> x \\<Longrightarrow> newton_sqrt_aux x n = x\"\n  by (subst newton_sqrt_aux.simps; simp add: Let_def)+\n\nlemma heron_step_real: \"\\<lbrakk>t > 0; n \\<ge> 0\\<rbrakk> \\<Longrightarrow> (t + n/t) / 2 \\<ge> sqrt n\"\n  using arith_geo_mean_sqrt[of t \"n/t\"] by simp\n\nlemma heron_step_div_eq_floored:\n  \"(t::nat) > 0 \\<Longrightarrow> (t + (n::nat) div t) div 2 = nat \\<lfloor>(t + n/t) / 2\\<rfloor>\"\nproof -\n  assume \"t > 0\"\n  then have \"\\<lfloor>(t + n/t) / 2\\<rfloor> = \\<lfloor>(t*t + n) / (2*t)\\<rfloor>\"\n    by (simp add: mult_divide_mult_cancel_right[of t \"t + n/t\" 2, symmetric]\n        algebra_simps)\n  also have \"\\<dots> = (t*t + n) div (2*t)\"\n    using floor_divide_of_nat_eq by blast\n  also have \"\\<dots> = (t*t + n) div t div 2\"\n    by (simp add: Divides.div_mult2_eq mult.commute)\n  also have \"\\<dots> = (t + n div t) div 2\"\n    by (simp add: \\<open>0 < t\\<close> power2_eq_square)\n  finally show ?thesis by simp\nqed\n\nlemma heron_step: \"t > 0 \\<Longrightarrow> (t + n div t) div 2 \\<ge> Discrete.sqrt n\"\nproof -\n  assume \"t > 0\"\n  have \"Discrete.sqrt n = nat \\<lfloor>sqrt n\\<rfloor>\" by (rule sqrt_eq_floor_sqrt)\n  also have \"\\<dots> \\<le> nat \\<lfloor>(t + n/t) / 2\\<rfloor>\"\n    using heron_step_real[of t n] \\<open>t > 0\\<close> by linarith\n  also have \"\\<dots> = (t + n div t) div 2\"\n    using heron_step_div_eq_floored[OF \\<open>t > 0\\<close>] by simp\n  finally show ?thesis .\nqed\n\nlemma newton_sqrt_aux_correct:\n  assumes \"x \\<ge> Discrete.sqrt n\"\n  shows   \"newton_sqrt_aux x n = Discrete.sqrt n\"\n  using assms\nproof (induction x n rule: newton_sqrt_aux.induct)\n  case (1 x n)\n  show ?case\n  proof (cases \"x = Discrete.sqrt n\")\n    case True\n    then have \"(x ^ 2) div x \\<le> n div x\" by (intro div_le_mono) simp_all\n    also have \"(x ^ 2) div x = x\" by (simp add: power2_eq_square)\n    finally have \"(x + n div x) div 2 \\<ge> x\" by linarith\n    with True show ?thesis by (auto simp: newton_sqrt_aux_simps)\n  next\n    case False\n    with \"1.prems\" have x_gt_sqrt: \"x > Discrete.sqrt n\" by auto\n    with Discrete.le_sqrt_iff[of x n] have \"n < x ^ 2\" by simp\n    have \"x * (n div x) \\<le> n\" using mult_div_mod_eq[of x n] by linarith\n    also have \"\\<dots> < x ^ 2\" using Discrete.le_sqrt_iff[of x n] and x_gt_sqrt by simp\n    also have \"\\<dots> = x * x\" by (simp add: power2_eq_square)\n    finally have \"n div x < x\" by (subst (asm) mult_less_cancel1) auto\n    then have step_decreasing: \"(x + n div x) div 2 < x\" by linarith\n    with x_gt_sqrt have step_ge_sqrt: \"(x + n div x) div 2 \\<ge> Discrete.sqrt n\"\n      by (simp add: heron_step)\n    from step_decreasing have \"newton_sqrt_aux x n = newton_sqrt_aux ((x + n div x) div 2) n\"\n      by (simp add: newton_sqrt_aux_simps)\n    also have \"\\<dots> = Discrete.sqrt n\"\n      by (intro \"1.IH\" step_decreasing step_ge_sqrt) simp_all\n    finally show ?thesis .\n  qed\nqed\n\ndefinition newton_sqrt :: \"nat \\<Rightarrow> nat\" where\n  \"newton_sqrt n = newton_sqrt_aux n n\"\n\ndeclare Discrete.sqrt_code [code del]\n\ntheorem Discrete_sqrt_eq_newton_sqrt [code]: \"Discrete.sqrt n = newton_sqrt n\"\n  unfolding newton_sqrt_def by (simp add: newton_sqrt_aux_correct Discrete.sqrt_le)\n\n\nsubsection \\<open>Square Testing\\<close>\n\ntext \\<open>\n  Next, we implement an algorithm to determine whether a given natural number is a perfect square,\n  as described by Cohen~\\<^cite>\\<open>\"cohen2010algebraic\"\\<close>. Essentially, the number first determines whether\n  the number is a square. Essentially\n\\<close>\n\ndefinition q11 :: \"nat set\"\n  where \"q11 = {0, 1, 3, 4, 5, 9}\"\ndefinition q63 :: \"nat set\"\n  where \"q63 = {0, 1, 4, 7, 9, 16, 28, 18, 22, 25, 36, 58, 46, 49, 37, 43}\"\ndefinition q64 :: \"nat set\"\n  where \"q64 = {0, 1, 4, 9, 16, 17, 25, 36, 33, 49, 41, 57}\"\ndefinition q65 :: \"nat set\"\n  where \"q65 = {0, 1, 4, 10, 14, 9, 16, 26, 30, 25, 29, 40, 56, 36, 49, 61, 35, 51, 39, 55, 64}\"\n\n\ndefinition q11_array where\n  \"q11_array = IArray [True,True,False,True,True,True,False,False,False,True,False]\"\n\ndefinition q63_array where\n  \"q63_array = IArray [True,True,False,False,True,False,False,True,False,True,False,False,\n     False,False,False,False,True,False,True,False,False,False,True,False,False,True,False,\n     False,True,False,False,False,False,False,False,False,True,True,False,False,False,False,\n     False,True,False,False,True,False,False,True,False,False,False,False,False,False,False,\n     False,True,False,False,False,False,False]\"\n\ndefinition q64_array where\n  \"q64_array = IArray [True,True,False,False,True,False,False,False,False,True,False,False,\n     False,False,False,False,True,True,False,False,False,False,False,False,False,True,False,\n     False,False,False,False,False,False,True,False,False,True,False,False,False,False,True,\n     False,False,False,False,False,False,False,True,False,False,False,False,False,False,\n     False,True,False,False,False,False,False,False, False]\"\n\ndefinition q65_array where\n  \"q65_array = IArray [True,True,False,False,True,False,False,False,False,True,True,False,\n     False,False,True,False,True,False,False,False,False,False,False,False,False,True,True,\n     False,False,True,True,False,False,False,False,True,True,False,False,True,True,False,\n     False,False,False,False,False,False,False,True,False,True,False,False,False,True,True\n     ,False,False,False,False,True,False,False,True,False]\"\n\nlemma sub_q11_array: \"i \\<in> {..<11} \\<Longrightarrow> IArray.sub q11_array i \\<longleftrightarrow> i \\<in> q11\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q11_def q11_array_def, elim disjE; simp)\n\nlemma sub_q63_array: \"i \\<in> {..<63} \\<Longrightarrow> IArray.sub q63_array i \\<longleftrightarrow> i \\<in> q63\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q63_def q63_array_def, elim disjE; simp)\n\nlemma sub_q64_array: \"i \\<in> {..<64} \\<Longrightarrow> IArray.sub q64_array i \\<longleftrightarrow> i \\<in> q64\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q64_def q64_array_def, elim disjE; simp)\n\nlemma sub_q65_array: \"i \\<in> {..<65} \\<Longrightarrow> IArray.sub q65_array i \\<longleftrightarrow> i \\<in> q65\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q65_def q65_array_def, elim disjE; simp)\n\n\nlemma in_q11_code: \"x mod 11 \\<in> q11 \\<longleftrightarrow> IArray.sub q11_array (x mod 11)\"\n  by (subst sub_q11_array) auto\n\nlemma in_q63_code: \"x mod 63 \\<in> q63 \\<longleftrightarrow> IArray.sub q63_array (x mod 63)\"\n  by (subst sub_q63_array) auto\n\nlemma in_q64_code: \"x mod 64 \\<in> q64 \\<longleftrightarrow> IArray.sub q64_array (x mod 64)\"\n  by (subst sub_q64_array) auto\n\nlemma in_q65_code: \"x mod 65 \\<in> q65 \\<longleftrightarrow> IArray.sub q65_array (x mod 65)\"\n  by (subst sub_q65_array) auto\n\n\ndefinition square_test :: \"nat \\<Rightarrow> bool\" where\n  \"square_test n =\n    (n mod 64 \\<in> q64 \\<and> (let r = n mod 45045 in\n      r mod 63 \\<in> q63 \\<and> r mod 65 \\<in> q65 \\<and> r mod 11 \\<in> q11 \\<and> n = (Discrete.sqrt n)\\<^sup>2))\"\n\nlemma square_test_code [code]:\n  \"square_test n =\n    (IArray.sub q64_array (n mod 64) \\<and> (let r = n mod 45045 in\n           IArray.sub q63_array (r mod 63) \\<and> \n           IArray.sub q65_array (r mod 65) \\<and>\n           IArray.sub q11_array (r mod 11) \\<and> n = (Discrete.sqrt n)\\<^sup>2))\"\n    using in_q11_code [symmetric] in_q63_code [symmetric] \n          in_q64_code [symmetric] in_q65_code [symmetric]\n  by (simp add: Let_def square_test_def)\n\nlemma square_mod_lower: \"m > 0 \\<Longrightarrow> (q\\<^sup>2 :: nat) mod m = a \\<Longrightarrow> \\<exists>q' < m. q'\\<^sup>2 mod m = a\"\n  using mod_less_divisor mod_mod_trivial power_mod by blast\n\nlemma q11_upto_def: \"q11 = (\\<lambda>k. k\\<^sup>2 mod 11) ` {..<11}\"\n  by (simp add: q11_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q11_infinite_def: \"q11 = (\\<lambda>k. k\\<^sup>2 mod 11) ` {0..}\"\n  unfolding q11_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 11 xa \"xa\\<^sup>2 mod 11\"]\n      ex_nat_less_eq[of 11 \"\\<lambda>x. xa\\<^sup>2 mod 11 = x\\<^sup>2 mod 11\"]\n    by auto\nqed\n\nlemma q63_upto_def: \"q63 = (\\<lambda>k. k\\<^sup>2 mod 63) ` {..<63}\"\n  by (simp add: q63_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q63_infinite_def: \"q63 = (\\<lambda>k. k\\<^sup>2 mod 63) ` {0..}\"\n  unfolding q63_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 63 xa \"xa\\<^sup>2 mod 63\"]\n      ex_nat_less_eq[of 63 \"\\<lambda>x. xa\\<^sup>2 mod 63 = x\\<^sup>2 mod 63\"]\n    by auto\nqed\n\nlemma q64_upto_def: \"q64 = (\\<lambda>k. k\\<^sup>2 mod 64) ` {..<64}\"\n  by (simp add: q64_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q64_infinite_def: \"q64 = (\\<lambda>k. k\\<^sup>2 mod 64) ` {0..}\"\n  unfolding q64_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 64 xa \"xa\\<^sup>2 mod 64\"]\n      ex_nat_less_eq[of 64 \"\\<lambda>x. xa\\<^sup>2 mod 64 = x\\<^sup>2 mod 64\"]\n    by auto\nqed\n\nlemma q65_upto_def: \"q65 = (\\<lambda>k. k\\<^sup>2 mod 65) ` {..<65}\"\n  by (simp add: q65_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q65_infinite_def: \"q65 = (\\<lambda>k. k\\<^sup>2 mod 65) ` {0..}\"\n  unfolding q65_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 65 xa \"xa\\<^sup>2 mod 65\"]\n      ex_nat_less_eq[of 65 \"\\<lambda>x. xa\\<^sup>2 mod 65 = x\\<^sup>2 mod 65\"]\n    by auto\nqed\n\nlemma square_mod_existence:\n  fixes n k :: nat\n  assumes \"\\<exists>q. q\\<^sup>2 = n\"\n  shows \"\\<exists>q. n mod k = q\\<^sup>2 mod k\"\n  using assms by auto\n\ntheorem square_test_correct: \"square_test n \\<longleftrightarrow> is_square n\"\nproof cases\n  assume \"is_square n\"\n  hence  rhs: \"\\<exists>q. q\\<^sup>2 = n\" by (auto elim: is_nth_powerE)\n  note sq_mod = square_mod_existence[OF this]\n  have q64_member: \"n mod 64 \\<in> q64\" using sq_mod[of 64]\n    unfolding q64_infinite_def image_def by simp\n  let ?r = \"n mod 45045\"\n  have \"11 dvd (45045::nat)\" \"63 dvd (45045::nat)\" \"65 dvd (45045::nat)\" by force+\n  then have mod_45045: \"?r mod 11 = n mod 11\" \"?r mod 63 = n mod 63\" \"?r mod 65 = n mod 65\"\n    using mod_mod_cancel[of _ 45045 n] by presburger+\n  then have \"?r mod 11 \\<in> q11\" \"?r mod 63 \\<in> q63\" \"?r mod 65 \\<in> q65\"\n    using sq_mod[of 11] sq_mod[of 63] sq_mod[of 65]\n    unfolding q11_infinite_def q63_infinite_def q65_infinite_def image_def mod_45045\n    by fast+\n  then show ?thesis unfolding square_test_def Let_def using q64_member rhs by auto\nnext\n  assume not_rhs: \"\\<not>is_square n\"\n  hence \"\\<nexists>q. q\\<^sup>2 = n\" by auto\n  then have \"(Discrete.sqrt n)\\<^sup>2 \\<noteq> n\" by simp\n  then show ?thesis unfolding square_test_def by (auto simp: is_nth_power_def)\nqed\n\n\ndefinition get_nat_sqrt :: \"nat \\<Rightarrow> nat option\" \n  where \"get_nat_sqrt n = (if is_square n then Some (Discrete.sqrt n) else None)\"\n\nlemma get_nat_sqrt_code [code]:\n  \"get_nat_sqrt n = \n    (if IArray.sub q64_array (n mod 64) \\<and> (let r = n mod 45045 in\n           IArray.sub q63_array (r mod 63) \\<and> \n           IArray.sub q65_array (r mod 65) \\<and>\n           IArray.sub q11_array (r mod 11)) then\n       (let x = Discrete.sqrt n in if x\\<^sup>2 = n then Some x else None) else None)\"\n  unfolding get_nat_sqrt_def square_test_correct [symmetric] square_test_def\n  using in_q11_code [symmetric] in_q63_code [symmetric] \n        in_q64_code [symmetric] in_q65_code [symmetric]\n  by (auto split: if_splits simp: Let_def )\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Pell/Efficient_Discrete_Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.8539127510928476, "lm_q1q2_score": 0.7665534541893235}}
{"text": "(*\n  File:   Master_Theorem.thy\n  Author: Manuel Eberl <eberlm@in.tum.de>\n\n  The Master theorem in a generalised form as derived from the Akra-Bazzi theorem.\n*)\nsection \\<open>The Master theorem\\<close>\ntheory Master_Theorem\nimports\n  \"HOL-Analysis.Equivalence_Lebesgue_Henstock_Integration\"\n  Akra_Bazzi_Library\n  Akra_Bazzi\nbegin\n\nlemma fundamental_theorem_of_calculus_real:\n  \"a \\<le> b \\<Longrightarrow> \\<forall>x\\<in>{a..b}. (f has_real_derivative f' x) (at x within {a..b}) \\<Longrightarrow>\n      (f' has_integral (f b - f a)) {a..b}\"\n  by (intro fundamental_theorem_of_calculus ballI)\n     (simp_all add: has_field_derivative_iff_has_vector_derivative[symmetric])\n\nlemma integral_powr:\n  \"y \\<noteq> -1 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a > 0 \\<Longrightarrow> integral {a..b} (\\<lambda>x. x powr y :: real) =\n     inverse (y + 1) * (b powr (y + 1) - a powr (y + 1))\"\n  by (subst right_diff_distrib, intro integral_unique fundamental_theorem_of_calculus_real)\n     (auto intro!: derivative_eq_intros)\n\nlemma integral_ln_powr_over_x:\n  \"y \\<noteq> -1 \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a > 1 \\<Longrightarrow> integral {a..b} (\\<lambda>x. ln x powr y / x :: real) =\n     inverse (y + 1) * (ln b powr (y + 1) - ln a powr (y + 1))\"\n  by (subst right_diff_distrib, intro integral_unique fundamental_theorem_of_calculus_real)\n     (auto intro!: derivative_eq_intros)\n\nlemma integral_one_over_x_ln_x:\n  \"a \\<le> b \\<Longrightarrow> a > 1 \\<Longrightarrow> integral {a..b} (\\<lambda>x. inverse (x * ln x) :: real) = ln (ln b) - ln (ln a)\"\n  by (intro integral_unique fundamental_theorem_of_calculus_real)\n     (auto intro!: derivative_eq_intros simp: field_simps)\n\nlemma akra_bazzi_integral_kurzweil_henstock:\n  \"akra_bazzi_integral (\\<lambda>f a b. f integrable_on {a..b}) (\\<lambda>f a b. integral {a..b} f)\"\napply unfold_locales\napply (rule integrable_const_ivl)\napply simp\napply (erule integrable_subinterval_real, simp)\napply (blast intro!: integral_le)\napply (rule integral_combine, simp_all) []\ndone\n\n\nlocale master_theorem_function = akra_bazzi_recursion +\n  fixes g :: \"nat \\<Rightarrow> real\"\n  assumes f_nonneg_base: \"x \\<ge> x\\<^sub>0 \\<Longrightarrow> x < x\\<^sub>1 \\<Longrightarrow> f x \\<ge> 0\"\n  and     f_rec:         \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> f x = g x + (\\<Sum>i<k. as!i * f ((ts!i) x))\"\n  and     g_nonneg:      \"x \\<ge> x\\<^sub>1 \\<Longrightarrow> g x \\<ge> 0\"\n  and     ex_pos_a:      \"\\<exists>a\\<in>set as. a > 0\"\nbegin\n\ninterpretation akra_bazzi_integral \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\"\n  by (rule akra_bazzi_integral_kurzweil_henstock)\n\nsublocale akra_bazzi_function x\\<^sub>0 x\\<^sub>1 k as bs ts f \"\\<lambda>f a b. f integrable_on {a..b}\"\n            \"\\<lambda>f a b. integral {a..b} f\" g\n  using f_nonneg_base f_rec g_nonneg ex_pos_a by unfold_locales\n\ncontext\nbegin\n\nprivate lemma g_nonneg': \"eventually (\\<lambda>x. g x \\<ge> 0) at_top\"\n  using g_nonneg by (force simp: eventually_at_top_linorder)\n\nprivate lemma g_pos:\n  assumes \"g \\<in> \\<Omega>(h)\"\n  assumes \"eventually (\\<lambda>x. h x > 0) at_top\"\n  shows   \"eventually (\\<lambda>x. g x > 0) at_top\"\nproof-\n  from landau_omega.bigE_nonneg_real[OF assms(1) g_nonneg'] guess c . note c = this\n  from assms(2) c(2) show ?thesis\n    by eventually_elim (rule less_le_trans[OF mult_pos_pos[OF c(1)]], simp_all)\nqed\n\nprivate lemma f_pos:\n  assumes \"g \\<in> \\<Omega>(h)\"\n  assumes \"eventually (\\<lambda>x. h x > 0) at_top\"\n  shows   \"eventually (\\<lambda>x. f x > 0) at_top\"\n  using g_pos[OF assms(1,2)] eventually_ge_at_top[of x\\<^sub>1]\n  by (eventually_elim) (subst f_rec, insert step_ge_x0,\n         auto intro!: add_pos_nonneg sum_nonneg mult_nonneg_nonneg[OF a_ge_0] f_nonneg)\n\nlemma bs_lower_bound: \"\\<exists>C>0. \\<forall>b\\<in>set bs. C < b\"\nproof (intro exI conjI ballI)\n  from b_pos show A: \"Min (set bs) / 2 > 0\" by auto\n  fix b assume b: \"b \\<in> set bs\"\n  from A have \"Min (set bs) / 2 < Min (set bs)\" by simp\n  also from b have \"... \\<le> b\" by simp\n  finally show \"Min (set bs) / 2 < b\" .\nqed\n\nprivate lemma powr_growth2:\n  \"\\<exists>C c2. 0 < c2 \\<and> C < Min (set bs) \\<and>\n      eventually (\\<lambda>x. \\<forall>u\\<in>{C * x..x}. c2 * x powr p' \\<ge> u powr p') at_top\"\nproof (intro exI conjI allI ballI)\n  define C where \"C = Min (set bs) / 2\"\n  from b_bounds bs_nonempty have C_pos: \"C > 0\" unfolding C_def by auto\n  thus \"C < Min (set bs)\" unfolding C_def by simp\n  show \"max (C powr p') 1 > 0\" by simp\n  show \"eventually (\\<lambda>x. \\<forall>u\\<in>{C * x..x}.\n    max ((Min (set bs)/2) powr p') 1 * x powr p' \\<ge> u powr p') at_top\"\n    using eventually_gt_at_top[of \"0::real\"] apply eventually_elim\n  proof clarify\n    fix x u assume x: \"x > 0\" and \"u \\<in> {C*x..x}\"\n    hence u: \"u \\<ge> C*x\" \"u \\<le> x\" unfolding C_def by  simp_all\n    from u have \"u powr p' \\<le> max ((C*x) powr p') (x powr p')\" using C_pos x\n      by (intro powr_upper_bound mult_pos_pos) simp_all\n    also from u x C_pos have \"max ((C*x) powr p') (x powr p') = x powr p' * max (C powr p') 1\"\n      by (subst max_mult_left) (simp_all add: powr_mult algebra_simps)\n    finally show \"u powr p' \\<le> max ((Min (set bs)/2) powr p') 1 * x powr p'\"\n      by (simp add: C_def algebra_simps)\n  qed\nqed\n\nprivate lemma powr_growth1:\n  \"\\<exists>C c1. 0 < c1 \\<and> C < Min (set bs) \\<and>\n      eventually (\\<lambda>x. \\<forall>u\\<in>{C * x..x}. c1 * x powr p' \\<le> u powr p') at_top\"\nproof (intro exI conjI allI ballI)\n  define C where \"C = Min (set bs) / 2\"\n  from b_bounds bs_nonempty have C_pos: \"C > 0\" unfolding C_def by auto\n  thus \"C < Min (set bs)\" unfolding C_def by simp\n  from C_pos show \"min (C powr p') 1 > 0\" by simp\n  show \"eventually (\\<lambda>x. \\<forall>u\\<in>{C * x..x}.\n          min ((Min (set bs)/2) powr p') 1 * x powr p' \\<le> u powr p') at_top\"\n    using eventually_gt_at_top[of \"0::real\"] apply eventually_elim\n  proof clarify\n    fix x u assume x: \"x > 0\" and \"u \\<in> {C*x..x}\"\n    hence u: \"u \\<ge> C*x\" \"u \\<le> x\" unfolding C_def by  simp_all\n    from u x C_pos have \"x powr p' * min (C powr p') 1 = min ((C*x) powr p') (x powr p')\"\n      by (subst min_mult_left) (simp_all add: powr_mult algebra_simps)\n    also from u have \"u powr p' \\<ge> min ((C*x) powr p') (x powr p')\" using C_pos x\n      by (intro powr_lower_bound mult_pos_pos) simp_all\n    finally show \"u powr p' \\<ge> min ((Min (set bs)/2) powr p') 1 * x powr p'\"\n      by (simp add: C_def algebra_simps)\n  qed\nqed\n\nprivate lemma powr_ln_powr_lower_bound:\n  \"a > 1 \\<Longrightarrow> a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow>\n     min (a powr p) (b powr p) * min (ln a powr p') (ln b powr p') \\<le> x powr p * ln x powr p'\"\n  by (intro mult_mono powr_lower_bound) (auto intro: min.coboundedI1)\n\nprivate lemma powr_ln_powr_upper_bound:\n  \"a > 1 \\<Longrightarrow> a \\<le> x \\<Longrightarrow> x \\<le> b \\<Longrightarrow>\n     max (a powr p) (b powr p) * max (ln a powr p') (ln b powr p') \\<ge> x powr p * ln x powr p'\"\n  by (intro mult_mono powr_upper_bound) (auto intro: max.coboundedI1)\n\nprivate lemma powr_ln_powr_upper_bound':\n  \"eventually (\\<lambda>a. \\<forall>b>a. \\<exists>c. \\<forall>x\\<in>{a..b}. x powr p * ln x powr p' \\<le> c) at_top\"\n  by (subst eventually_at_top_dense) (force intro: powr_ln_powr_upper_bound)\n\nprivate lemma powr_upper_bound':\n  \"eventually (\\<lambda>a::real. \\<forall>b>a. \\<exists>c. \\<forall>x\\<in>{a..b}. x powr p' \\<le> c) at_top\"\n  by (subst eventually_at_top_dense) (force intro: powr_upper_bound)\n\nlemmas bounds =\n  powr_ln_powr_lower_bound powr_ln_powr_upper_bound powr_ln_powr_upper_bound' powr_upper_bound'\n\n\nprivate lemma eventually_ln_const:\n  assumes \"(C::real) > 0\"\n  shows   \"eventually (\\<lambda>x. ln (C*x) / ln x > 1/2) at_top\"\nproof-\n  from tendstoD[OF tendsto_ln_over_ln[of C 1], of \"1/2\"] assms\n    have \"eventually (\\<lambda>x. \\<bar>ln (C*x) / ln x - 1\\<bar> < 1/2) at_top\" by (simp add: dist_real_def)\n  thus ?thesis by eventually_elim linarith\nqed\n\nprivate lemma powr_ln_powr_growth1: \"\\<exists>C c1. 0 < c1 \\<and> C < Min (set bs) \\<and>\n  eventually (\\<lambda>x. \\<forall>u\\<in>{C * x..x}. c1 * (x powr r * ln x powr r') \\<le> u powr r * ln u powr r') at_top\"\nproof (intro exI conjI)\n  let ?C = \"Min (set bs) / 2\" and ?f = \"\\<lambda>x. x powr r * ln x powr r'\"\n  define C where \"C = ?C\"\n  from b_bounds have C_pos: \"C > 0\" unfolding C_def by simp\n  let ?T = \"min (C powr r) (1 powr r) * min ((1/2) powr r') (1 powr r')\"\n  from C_pos show \"?T > 0\" unfolding min_def by (auto split: if_split)\n  from bs_nonempty b_bounds have C_pos: \"C > 0\" unfolding C_def by simp\n  thus \"C < Min (set bs)\" by (simp add: C_def)\n\n  show \"eventually (\\<lambda>x. \\<forall>u\\<in>{C*x..x}. ?T * ?f x \\<le> ?f u) at_top\"\n    using eventually_gt_at_top[of \"max 1 (inverse C)\"] eventually_ln_const[OF C_pos]\n    apply eventually_elim\n  proof clarify\n    fix x u assume x: \"x > max 1 (inverse C)\" and u: \"u \\<in> {C*x..x}\"\n    hence x': \"x > 1\" by (simp add: field_simps)\n    with C_pos have x_pos: \"x > 0\" by (simp add: field_simps)\n    from x u C_pos have u': \"u > 1\" by (simp add: field_simps)\n    assume A: \"ln (C*x) / ln x > 1/2\"\n    have \"min (C powr r) (1 powr r) \\<le> (u/x) powr r\"\n      using x u u' C_pos by (intro powr_lower_bound) (simp_all add: field_simps)\n    moreover {\n      note A\n      also from C_pos x' u u' have \"ln (C*x) \\<le> ln u\" by (subst ln_le_cancel_iff) simp_all\n      with x' have \"ln (C*x) / ln x \\<le> ln u / ln x\" by (simp add: field_simps)\n      finally have \"min ((1/2) powr r') (1 powr r') \\<le> (ln u / ln x) powr r'\"\n        using x u u' C_pos A by (intro powr_lower_bound) simp_all\n    }\n    ultimately have \"?T \\<le> (u/x) powr r * (ln u / ln x) powr r'\"\n      using x_pos by (intro mult_mono) simp_all\n    also from x u u' have \"... = ?f u / ?f x\" by (simp add: powr_divide)\n    finally show \"?T * ?f x \\<le> ?f u\" using x' by (simp add: field_simps)\n  qed\nqed\n\nprivate lemma powr_ln_powr_growth2: \"\\<exists>C c1. 0 < c1 \\<and> C < Min (set bs) \\<and>\n  eventually (\\<lambda>x. \\<forall>u\\<in>{C * x..x}. c1 * (x powr r * ln x powr r') \\<ge> u powr r * ln u powr r') at_top\"\nproof (intro exI conjI)\n  let ?C = \"Min (set bs) / 2\" and ?f = \"\\<lambda>x. x powr r * ln x powr r'\"\n  define C where \"C = ?C\"\n  let ?T = \"max (C powr r) (1 powr r) * max ((1/2) powr r') (1 powr r')\"\n  show \"?T > 0\" by simp\n  from b_bounds bs_nonempty have C_pos: \"C > 0\" unfolding C_def by simp\n  thus \"C < Min (set bs)\" by (simp add: C_def)\n\n  show \"eventually (\\<lambda>x. \\<forall>u\\<in>{C*x..x}. ?T * ?f x \\<ge> ?f u) at_top\"\n    using eventually_gt_at_top[of \"max 1 (inverse C)\"] eventually_ln_const[OF C_pos]\n    apply eventually_elim\n  proof clarify\n    fix x u assume x: \"x > max 1 (inverse C)\" and u: \"u \\<in> {C*x..x}\"\n    hence x': \"x > 1\" by (simp add: field_simps)\n    with C_pos have x_pos: \"x > 0\" by (simp add: field_simps)\n    from x u C_pos have u': \"u > 1\" by (simp add: field_simps)\n    assume A: \"ln (C*x) / ln x > 1/2\"\n    from x u u' have \"?f u / ?f x = (u/x) powr r * (ln u/ln x) powr r'\" by (simp add: powr_divide)\n    also {\n      have \"(u/x) powr r \\<le> max (C powr r) (1 powr r)\"\n        using x u u' C_pos by (intro powr_upper_bound) (simp_all add: field_simps)\n      moreover {\n        note A\n        also from C_pos x' u u' have \"ln (C*x) \\<le> ln u\" by (subst ln_le_cancel_iff) simp_all\n        with x' have \"ln (C*x) / ln x \\<le> ln u / ln x\" by (simp add: field_simps)\n        finally have \"(ln u / ln x) powr r' \\<le> max ((1/2) powr r') (1 powr r')\"\n          using x u u' C_pos A by (intro powr_upper_bound) simp_all\n      } ultimately have \"(u/x) powr r * (ln u / ln x) powr r' \\<le> ?T\"\n        using x_pos by (intro mult_mono) simp_all\n    }\n    finally show \"?T * ?f x \\<ge> ?f u\" using x' by (simp add: field_simps)\n  qed\nqed\n\nlemmas growths = powr_growth1 powr_growth2 powr_ln_powr_growth1 powr_ln_powr_growth2\n\n\nprivate lemma master_integrable:\n  \"\\<exists>a::real. \\<forall>b\\<ge>a. (\\<lambda>u. u powr r * ln u powr s / u powr t) integrable_on {a..b}\"\n  \"\\<exists>a::real. \\<forall>b\\<ge>a. (\\<lambda>u. u powr r / u powr s) integrable_on {a..b}\"\n  by (rule exI[of _ 2], force intro!: integrable_continuous_real continuous_intros)+\n\nprivate lemma master_integral:\n  fixes a p p' :: real\n  assumes p: \"p \\<noteq> p'\" and a: \"a > 0\"\n  obtains c d where \"c \\<noteq> 0\" \"p > p' \\<longrightarrow> d \\<noteq> 0\"\n    \"(\\<lambda>x::nat. x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p' / u powr (p+1)))) \\<in>\n             \\<Theta>(\\<lambda>x::nat. d * x powr p + c * x powr p')\"\nproof-\n  define e where \"e = a powr (p' - p)\"\n  from assms have e: \"e \\<ge> 0\" by (simp add: e_def)\n  define c where \"c = inverse (p' - p)\"\n  define d where \"d = 1 - inverse (p' - p) * e\"\n  have \"c \\<noteq> 0\" and \"p > p' \\<longrightarrow> d \\<noteq> 0\"\n    using e p a unfolding c_def d_def by (auto simp: field_simps)\n  thus ?thesis\n    apply (rule that) apply (rule bigtheta_real_nat_transfer, rule bigthetaI_cong)\n    using eventually_ge_at_top[of a]\n  proof eventually_elim\n    fix x assume x: \"x \\<ge> a\"\n    hence \"integral {a..x} (\\<lambda>u. u powr p' / u powr (p+1)) =\n               integral {a..x} (\\<lambda>u. u powr (p' - (p + 1)))\"\n      by (intro Henstock_Kurzweil_Integration.integral_cong) (simp_all add: powr_diff [symmetric] )\n    also have \"... = inverse (p' - p) * (x powr (p' - p) - a powr (p' - p))\"\n      using p x0_less_x1 a x by (simp add: integral_powr)\n    also have \"x powr p * (1 + ...) = d * x powr p + c * x powr p'\"\n      using p unfolding c_def d_def by (simp add: algebra_simps powr_diff e_def)\n    finally show \"x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p' / u powr (p+1))) =\n                      d * x powr p + c * x powr p'\" .\n  qed\nqed\n\nprivate lemma master_integral':\n  fixes a p p' :: real\n  assumes p': \"p' \\<noteq> 0\" and a: \"a > 1\"\n  obtains c d :: real where \"p' < 0 \\<longrightarrow> c \\<noteq> 0\" \"d \\<noteq> 0\"\n    \"(\\<lambda>x::nat. x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p * ln u powr (p'-1) / u powr (p+1)))) \\<in>\n       \\<Theta>(\\<lambda>x::nat. c * x powr p + d * x powr p * ln x powr p')\"\nproof-\n  define e where \"e = ln a powr p'\"\n  from assms have e: \"e > 0\" by (simp add: e_def)\n  define c where \"c = 1 - inverse p' * e\"\n  define d where \"d = inverse p'\"\n  from assms e have \"p' < 0 \\<longrightarrow> c \\<noteq> 0\" \"d \\<noteq> 0\" unfolding c_def d_def by (auto simp: field_simps)\n  thus ?thesis\n    apply (rule that) apply (rule landau_real_nat_transfer, rule bigthetaI_cong)\n    using eventually_ge_at_top[of a]\n  proof eventually_elim\n    fix x :: real assume x: \"x \\<ge> a\"\n    have \"integral {a..x} (\\<lambda>u. u powr p * ln u powr (p' - 1) / u powr (p + 1)) =\n          integral {a..x} (\\<lambda>u. ln u powr (p' - 1) / u)\" using x a x0_less_x1\n      by (intro Henstock_Kurzweil_Integration.integral_cong) (simp_all add: powr_add)\n    also have \"... = inverse p' * (ln x powr p' - ln a powr p')\"\n      using p' x0_less_x1 a(1) x by (simp add: integral_ln_powr_over_x)\n    also have \"x powr p * (1 + ...) = c * x powr p + d * x powr p * ln x powr p'\"\n      using p' by (simp add: algebra_simps c_def d_def e_def)\n    finally show \"x powr p * (1+integral {a..x} (\\<lambda>u. u powr p * ln u powr (p'-1) / u powr (p+1))) =\n                  c * x powr p + d * x powr p * ln x powr p'\" .\n  qed\nqed\n\nprivate lemma master_integral'':\n  fixes a p p' :: real\n  assumes a: \"a > 1\"\n  shows \"(\\<lambda>x::nat. x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p * ln u powr - 1/u powr (p+1)))) \\<in>\n           \\<Theta>(\\<lambda>x::nat. x powr p * ln (ln x))\"\nproof (rule landau_real_nat_transfer)\n  have \"(\\<lambda>x::real. x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p * ln u powr - 1/u powr (p+1)))) \\<in>\n          \\<Theta>(\\<lambda>x::real. (1 - ln (ln a)) * x powr p + x powr p * ln (ln x))\" (is \"?f \\<in> _\")\n    apply (rule bigthetaI_cong) using eventually_ge_at_top[of a]\n  proof eventually_elim\n    fix x assume x: \"x \\<ge> a\"\n    have \"integral {a..x} (\\<lambda>u. u powr p * ln u powr -1 / u powr (p + 1)) =\n          integral {a..x} (\\<lambda>u. inverse (u * ln u))\" using x a x0_less_x1\n      by (intro Henstock_Kurzweil_Integration.integral_cong) (simp_all add: powr_add powr_minus field_simps)\n    also have \"... = ln (ln x) - ln (ln a)\"\n      using x0_less_x1 a(1) x by (subst integral_one_over_x_ln_x) simp_all\n    also have \"x powr p * (1 + ...) = (1 - ln (ln a)) * x powr p + x powr p * ln (ln x)\"\n      by (simp add: algebra_simps)\n    finally show \"x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p * ln u powr - 1 / u powr (p+1))) =\n                    (1 - ln (ln a)) * x powr p + x powr p * ln (ln x)\" .\n  qed\n  also have \"(\\<lambda>x. (1 - ln (ln a)) * x powr p + x powr p * ln (ln x)) \\<in>\n                \\<Theta>(\\<lambda>x. x powr p * ln (ln x))\" by simp\n  finally show \"?f \\<in> \\<Theta>(\\<lambda>a. a powr p * ln (ln a))\" .\nqed\n\n\n\nlemma master1_bigo:\n  assumes g_bigo: \"g \\<in> O(\\<lambda>x. real x powr p')\"\n  assumes less_p': \"(\\<Sum>i<k. as!i * bs!i powr p') > 1\"\n  shows \"f \\<in> O(\\<lambda>x. real x powr p)\"\nproof-\n  interpret akra_bazzi_upper x\\<^sub>0 x\\<^sub>1 k as bs ts f\n    \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\" g \"\\<lambda>x. x powr p'\"\n    using assms growths g_bigo master_integrable by unfold_locales (assumption | simp)+\n  from less_p' have less_p: \"p' < p\" by (rule p_greaterI)\n  from bigo_f[of \"0\"] guess a . note a = this\n  note a(2)\n  also from a(1) less_p x0_less_x1 have \"p \\<noteq> p'\" by simp_all\n  from master_integral[OF this a(1)] guess c d . note cd = this\n  note cd(3)\n  also from cd(1,2) less_p\n    have \"(\\<lambda>x::nat. d * real x powr p + c * real x powr p') \\<in> \\<Theta>(\\<lambda>x. real x powr p)\" by force\n  finally show \"f \\<in> O(\\<lambda>x::nat. x powr p)\" .\nqed\n\n\nlemma master1:\n  assumes g_bigo: \"g \\<in> O(\\<lambda>x. real x powr p')\"\n  assumes less_p': \"(\\<Sum>i<k. as!i * bs!i powr p') > 1\"\n  assumes f_pos:  \"eventually (\\<lambda>x. f x > 0) at_top\"\n  shows \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p)\"\nproof (rule bigthetaI)\n  interpret akra_bazzi_lower x\\<^sub>0 x\\<^sub>1 k as bs ts f\n    \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\" g \"\\<lambda>_. 0\"\n    using assms(1,3) bs_lower_bound by unfold_locales (auto intro: always_eventually)\n  from bigomega_f show \"f \\<in> \\<Omega>(\\<lambda>x. real x powr p)\" by force\nqed (fact master1_bigo[OF g_bigo less_p'])\n\nlemma master2_3:\n  assumes g_bigtheta: \"g \\<in> \\<Theta>(\\<lambda>x. real x powr p * ln (real x) powr (p' - 1))\"\n  assumes p': \"p' > 0\"\n  shows \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p * ln (real x) powr p')\"\nproof-\n  have \"eventually (\\<lambda>x::real. x powr p * ln x powr (p' - 1) > 0) at_top\"\n    using eventually_gt_at_top[of \"1::real\"] by eventually_elim simp\n  hence \"eventually (\\<lambda>x. f x > 0) at_top\"\n    by (rule f_pos[OF bigthetaD2[OF g_bigtheta] eventually_nat_real])\n  then interpret akra_bazzi x\\<^sub>0 x\\<^sub>1 k as bs ts f\n    \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\" g \"\\<lambda>x. x powr p * ln x powr (p' - 1)\"\n    using assms growths bounds master_integrable by unfold_locales (assumption | simp)+\n  from bigtheta_f[of \"1\"] guess a . note a = this\n  note a(2)\n  also from a(1) p' have \"p' \\<noteq> 0\" by simp_all\n  from master_integral'[OF this a(1), of p] guess c d . note cd = this\n  note cd(3)\n  also have \"(\\<lambda>x::nat. c * real x powr p + d * real x powr p * ln (real x) powr p') \\<in>\n                 \\<Theta>(\\<lambda>x::nat. x powr p * ln x powr p')\" using cd(1,2) p' by force\n  finally show \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p * ln (real x) powr p')\" .\nqed\n\nlemma master2_1:\n  assumes g_bigtheta: \"g \\<in> \\<Theta>(\\<lambda>x. real x powr p * ln (real x) powr p')\"\n  assumes p': \"p' < -1\"\n  shows \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p)\"\nproof-\n  have \"eventually (\\<lambda>x::real. x powr p * ln x powr p' > 0) at_top\"\n    using eventually_gt_at_top[of \"1::real\"] by eventually_elim simp\n  hence \"eventually (\\<lambda>x. f x > 0) at_top\"\n    by (rule f_pos[OF bigthetaD2[OF g_bigtheta] eventually_nat_real])\n  then interpret akra_bazzi x\\<^sub>0 x\\<^sub>1 k as bs ts f\n    \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\" g \"\\<lambda>x. x powr p * ln x powr p'\"\n    using assms growths bounds master_integrable by unfold_locales (assumption | simp)+\n  from bigtheta_f[of \"1\"] guess a . note a = this\n  note a(2)\n  also from a(1) p' have A: \"p' + 1 \\<noteq> 0\" by simp_all\n  obtain c d :: real where cd: \"c \\<noteq> 0\" \"d \\<noteq> 0\" and\n    \"(\\<lambda>x::nat. x powr p * (1 + integral {a..x} (\\<lambda>u. u powr p * ln u powr p'/ u powr (p+1)))) \\<in>\n       \\<Theta>(\\<lambda>x::nat. c * x powr p + d * x powr p * ln x powr (p' + 1))\"\n    by (rule master_integral'[OF A a(1), of p]) (insert p', simp)\n  note this(3)\n  also have \"(\\<lambda>x::nat. c * real x powr p + d * real x powr p * ln (real x) powr (p' + 1)) \\<in>\n                 \\<Theta>(\\<lambda>x::nat. x powr p)\" using cd(1,2) p' by force\n  finally show \"f \\<in> \\<Theta>(\\<lambda>x::nat. x powr p)\" .\nqed\n\nlemma master2_2:\n  assumes g_bigtheta: \"g \\<in> \\<Theta>(\\<lambda>x. real x powr p / ln (real x))\"\n  shows \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p * ln (ln (real x)))\"\nproof-\n  have \"eventually (\\<lambda>x::real. x powr p / ln x > 0) at_top\"\n    using eventually_gt_at_top[of \"1::real\"] by eventually_elim simp\n  hence \"eventually (\\<lambda>x. f x > 0) at_top\"\n    by (rule f_pos[OF bigthetaD2[OF g_bigtheta] eventually_nat_real])\n  moreover from g_bigtheta have g_bigtheta': \"g \\<in> \\<Theta>(\\<lambda>x. real x powr p * ln (real x) powr -1)\"\n    by (rule landau_theta.trans, intro landau_real_nat_transfer) simp\n  ultimately interpret akra_bazzi x\\<^sub>0 x\\<^sub>1 k as bs ts f\n    \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\" g \"\\<lambda>x. x powr p * ln x powr -1\"\n    using assms growths bounds master_integrable by unfold_locales (assumption | simp)+\n  from bigtheta_f[of 1] guess a . note a = this\n  note a(2)\n  also note master_integral''[OF a(1)]\n  finally show \"f \\<in> \\<Theta>(\\<lambda>x::nat. x powr p * ln (ln x))\" .\nqed\n\nlemma master3:\n  assumes g_bigtheta: \"g \\<in> \\<Theta>(\\<lambda>x. real x powr p')\"\n  assumes p'_greater': \"(\\<Sum>i<k. as!i * bs!i powr p') < 1\"\n  shows \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p')\"\nproof-\n  have \"eventually (\\<lambda>x::real. x powr p' > 0) at_top\"\n    using eventually_gt_at_top[of \"1::real\"] by eventually_elim simp\n  hence \"eventually (\\<lambda>x. f x > 0) at_top\"\n    by (rule f_pos[OF bigthetaD2[OF g_bigtheta] eventually_nat_real])\n  then interpret akra_bazzi x\\<^sub>0 x\\<^sub>1 k as bs ts f\n    \"\\<lambda>f a b. f integrable_on {a..b}\" \"\\<lambda>f a b. integral {a..b} f\" g \"\\<lambda>x. x powr p'\"\n    using assms growths bounds master_integrable by unfold_locales (assumption | simp)+\n  from p'_greater' have p'_greater: \"p' > p\" by (rule p_lessI)\n  from bigtheta_f[of 0] guess a . note a = this\n  note a(2)\n  also from p'_greater have \"p \\<noteq> p'\" by simp\n  from master_integral[OF this a(1)] guess c d . note cd = this\n  note cd(3)\n  also have \"(\\<lambda>x::nat. d * x powr p + c * x powr p') \\<in> \\<Theta>(\\<lambda>x::real. x powr p')\"\n    using p'_greater cd(1,2) by force\n  finally show \"f \\<in> \\<Theta>(\\<lambda>x. real x powr p')\" .\nqed\n\nend\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Akra_Bazzi/Master_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.867035771827307, "lm_q1q2_score": 0.7664936756764809}}
{"text": "theory berIneq\n  imports Complex_Main\nbegin \n\ntheorem BernoulliInequality:\n  fixes x :: real\n  fixes n:: nat\n  assumes \"x \\<ge> -1\"\n  shows \"(1 + x) ^ n\\<ge> 1 + n*x\" (is \"?P n\")\nproof (induction n)\n  show \"?P 0\" by auto\nnext\n  fix n :: nat\n  assume IH : \"?P n\"\n  show \"?P (Suc n)\"\n  proof -\n    from assms have \"1+x \\<ge> 0\" by auto\n    then have start :\"(1+x)*(1+x) ^ n \\<ge> (1+x)*(1+n*x)\" \n      proof cases\n        assume \"1+x = 0\"\n        thus ?thesis using IH  by auto\n      next\n        assume \"\\<not>(1+x=0)\"\n        thus ?thesis using IH assms by auto\n      qed\n      have \"(1+x)*(1+n*x) = (1+n*x + x + n*(x ^ 2))\" by algebra\n      then have helper: \"(1+x) ^ (1+n) \\<ge> (1+n*x + x + n*(x ^ 2))\" using start by auto\n      have \"n*(x ^ 2) \\<ge> 0\" by auto\n      then have helper2 : \"(1+n*x + x + n*(x ^ 2)) \\<ge> (1+n*x + x)\" by auto\n      then have \"(1+x) ^ (1+n) \\<ge> (1+n*x + x)\" using helper by linarith\n      thus ?thesis\n        by (smt \\<open>(1 + x) * (1 + real n * x) = 1 + real n * x + x + real n * x\\<^sup>2\\<close> \\<open>0 \\<le> real n * x\\<^sup>2\\<close> of_nat_Suc power_Suc semiring_normalization_rules(2) start)\n    qed\n  qed\nend\n      \n    \n  ", "meta": {"author": "s-nandi", "repo": "automated-proofs", "sha": "719103028f53ded647e34fa88fff0383b09865e9", "save_path": "github-repos/isabelle/s-nandi-automated-proofs", "path": "github-repos/isabelle/s-nandi-automated-proofs/automated-proofs-719103028f53ded647e34fa88fff0383b09865e9/berIneq.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8333245891029456, "lm_q1q2_score": 0.7663607307447056}}
{"text": "subsection \"Boolean Expressions\"\n\ntheory BExp imports AExp begin\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ntext_raw\\<open>\\snip{BExpbvaldef}{1}{2}{%\\<close>\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\ntext_raw\\<open>}%endsnip\\<close>\n\nvalue \"bval (Less (V ''x'') (Plus (N 3) (V ''y'')))\n            <''x'' := 3, ''y'' := 1>\"\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Optimizing constructors:\\<close>\n\ntext_raw\\<open>\\snip{BExplessdef}{0}{2}{%\\<close>\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\" |\n\"less a\\<^sub>1 a\\<^sub>2 = Less a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\n\ntext_raw\\<open>\\snip{BExpanddef}{2}{2}{%\\<close>\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply simp_all\ndone\n\ntext_raw\\<open>\\snip{BExpnotdef}{2}{2}{%\\<close>\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction b rule: not.induct)\napply simp_all\ndone\n\ntext\\<open>Now the overall optimizer:\\<close>\n\ntext_raw\\<open>\\snip{BExpbsimpdef}{0}{2}{%\\<close>\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\nvalue \"bsimp (And (Less (N 0) (N 1)) b)\"\n\nvalue \"bsimp (And (Less (N 1) (N 0)) (Bc True))\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply simp_all\ndone\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/IMP/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726544, "lm_q2_score": 0.8376199653600371, "lm_q1q2_score": 0.7663393042855338}}
{"text": "theory Calculus\n  imports Main\nbegin\n\n(* locale  exos*)\nlocale partial_order = \n  fixes \n    le :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubseteq>\" 50) \n  assumes\n    refl [intro, simp] : \"\\<And>x. x \\<sqsubseteq> x\" and \n    anti_sym [intro] : \"\\<And>x y. \\<lbrakk> x \\<sqsubseteq> y; y \\<sqsubseteq> x \\<rbrakk> \\<Longrightarrow> x = y\" and\n    trans [trans] : \"\\<And>x y z. \\<lbrakk> x \\<sqsubseteq> y; y \\<sqsubseteq> z \\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> z\"\n\n  (*print_locales: lists the names of all locales of the currnet theory *)\nprint_locales\n  (*print_locale n : prints the parameters and assumptions of locale n *)\nprint_locale partial_order\n  (*print_locale! n : additionally outputs the conclusions that are stored in the locale *)\nprint_locale! partial_order\n  (* partial_order_def : predicate introduicd by the locale declaration *)\nthm partial_order_def\n  (* each conclusion has a foundational theorem as counterpart in the theory*)\nthm partial_order.trans\n  (**)\n\ndefinition (in partial_order) less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"\\<sqsubset>\" 50) where\n  \"(x \\<sqsubset> y) = (x \\<sqsubseteq> y \\<and> x \\<noteq> y)\"\n\nprint_locale partial_order\nprint_locale! partial_order\nthm partial_order_def\nthm partial_order.less_def\n\nlemma (in partial_order) less_le_trans [trans]: \"\\<lbrakk> x \\<sqsubset> y; y \\<sqsubseteq> z \\<rbrakk> \\<Longrightarrow> x \\<sqsubset> z\"\n  unfolding less_def by (blast intro : trans)\n\ncontext partial_order\nbegin\n  \ndefinition is_inf where\n  \"is_inf x y i = ( i \\<sqsubseteq> x \\<and> i \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> i ))\"\n  \ndefinition is_sup where\n  \"is_sup x y s = (   x \\<sqsubseteq> s \\<and> y \\<sqsubseteq> s \\<and> (\\<forall>z. x \\<sqsubseteq> z \\<and> y \\<sqsubseteq> z \\<longrightarrow> s \\<sqsubseteq> z ))\"\n\ntheorem is_inf_uniq : \" \\<lbrakk> is_inf x y a; is_inf x y b \\<rbrakk> \\<Longrightarrow> a = b \"\nproof-\n  assume \"is_inf x y a\" \"is_inf x y b\"\n  show \"a = b\"\n  proof-\n    from `is_inf x y a` have H1 : \"a \\<sqsubseteq> x \\<and> a \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> a)\"\n      by (simp add : is_inf_def)\n    from `is_inf x y b` have H2 : \"b \\<sqsubseteq> x \\<and> b \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> b)\"\n      by (simp add : is_inf_def)\n    from H1 H2 have \"b \\<sqsubseteq> a\" by simp\n    from H1 H2 have \"a \\<sqsubseteq> b\" by simp\n    from `a \\<sqsubseteq> b` `b \\<sqsubseteq> a` show \"a = b\" by (rule anti_sym)\n  qed\nqed\n\ntheorem is_sup_uniq : \" \\<lbrakk> is_sup x y a; is_sup x y b \\<rbrakk> \\<Longrightarrow> a = b \"\n  by (simp add : is_sup_def anti_sym)\nend\n\n(* Section 3 *)\n\nlocale lattice = partial_order +\n  assumes \n    ex_inf : \"\\<exists>inf. is_inf x y inf\" and\n    ex_sup : \"\\<exists>sup. is_sup x y sup\"\nbegin\n  definition meet (infixl \"\\<sqinter>\" 70) where \"x \\<sqinter> y = (THE z. is_inf x y z)\"\ndefinition join (infixl \"\\<squnion>\" 70) where \"x \\<squnion> y = (THE z. is_sup x y z)\"\n\n\n(**************************************\n***************************************\n  ***************************************)\n  \nlemma meet_left_1 : \"x \\<sqinter> y \\<sqsubseteq> x\"\n  (* sledgehammer *)\n  by (metis ex_inf is_inf_uniq meet_def partial_order.is_inf_def partial_order_axioms the_equality)\n\nfind_theorems name: the_equality\n\nlemma meet_left_2: \"x \\<sqinter> y \\<sqsubseteq> x \"\n  unfolding meet_def is_inf_def\nproof -\n  fix x y\n  obtain i where ix: \"i \\<sqsubseteq> x \\<and> i \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> i)\"\n    using ex_inf unfolding is_inf_def by blast\n  then have \"\\<And>z. ((z \\<sqsubseteq> x) \\<and> (z \\<sqsubseteq> y) \\<and> (\\<forall>w. (w \\<sqsubseteq> x) \\<and> (w \\<sqsubseteq> y) \\<longrightarrow> w \\<sqsubseteq> z)) \\<Longrightarrow> z = i\"\n    using is_inf_uniq unfolding is_inf_def by blast \n  then have \"i = (THE i. i \\<sqsubseteq> x \\<and> i \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> i))\"\n    using the_equality[of _ i] is_inf_uniq ix unfolding is_inf_def by (smt (verit,best)) \n  then show \\<open>(THE i. i \\<sqsubseteq> x \\<and> i \\<sqsubseteq> y \\<and> (\\<forall>z. z \\<sqsubseteq> x \\<and> z \\<sqsubseteq> y \\<longrightarrow> z \\<sqsubseteq> i)) \\<sqsubseteq> x\\<close>\n    using ix by blast \nqed\n\n\n\n(**************************************\n***************************************\n***************************************)\n\nend\n\nlocale total_order = partial_order + \n  assumes total : \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n\nlemma (in total_order) less_total : \"x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x\"\nproof(rule ccontr)\n  assume H0 : \"\\<not>(x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x)\"\n  from H0 have H1 : \"\\<not>(x \\<sqsubset> y) \\<and> x \\<noteq> y \\<and> \\<not>(y \\<sqsubset> x)\" by blast\n  from H1 have \"x \\<noteq> y\" by simp\n  from H1 have H2 : \"\\<not>(x \\<sqsubset> y) \\<and> \\<not>(y \\<sqsubset> x)\" by simp\n  from H2 have H3 : \"\\<not>(x \\<sqsubseteq> y \\<and> x \\<noteq> y) \\<and> \\<not>(y \\<sqsubseteq> x \\<and> y \\<noteq> x)\" by (simp add : less_def)\n  from H3 have H4 : \"(\\<not>(x \\<sqsubseteq> y) \\<and> \\<not>(y \\<sqsubseteq> x)) \\<or> \\<not>(x \\<noteq> y)\" by blast\n  from H4 show False \n  proof (rule disjE)\n    assume \"\\<not> x \\<noteq> y\"\n    from `\\<not>(x\\<noteq>y)` have \"x = y\" by simp\n    from `x \\<noteq> y` `x = y` show False by (rule notE)\n  next\n    assume H : \"\\<not> x \\<sqsubseteq> y \\<and> \\<not> y \\<sqsubseteq> x\" \n    from total have H' : \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\" by simp\n    from H H' show False by blast\n  qed\nqed\n\nlemma \"x \\<or> \\<not>x\"\nproof (rule ccontr)\n  assume \"\\<not>(x \\<or> \\<not>x)\"\n  then have \"\\<not>x \\<and> x\" by simp\n  then have \"x\" by (rule conjE)\n  then have \"x \\<or> \\<not>x\" by (rule disjI1)\n  from `\\<not>(x \\<or> \\<not>x)` this show False by (rule notE)\nqed\n\nlemma \"x \\<or> \\<not>x\"\nproof-\n  have \"\\<not>(x \\<or> \\<not>x) \\<Longrightarrow> False\"\n  proof-\n    assume \"\\<not>(x \\<or> \\<not>x)\"\n    then have \"\\<not>x \\<and> x\" by simp\n    then have \"x\" by (rule conjE)\n    then have \"x \\<or> \\<not>x\" by (rule disjI1)\n    from `\\<not>(x \\<or> \\<not>x)` this show False by (rule notE)\n  qed\n  from this show \"x \\<or> \\<not>x\" by (rule ccontr)\nqed\n\nlemma (in total_order) \"x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x\"\nproof-\n  have \"\\<not>(x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x) \\<Longrightarrow> False\" \n  proof-\n    assume H0 : \"\\<not>(x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x)\"\n    from H0 have H1 : \"\\<not>(x \\<sqsubset> y) \\<and> x \\<noteq> y \\<and> \\<not>(y \\<sqsubset> x)\" by blast\n    from H1 have \"x \\<noteq> y\" by simp\n    from H1 have H2 : \"\\<not>(x \\<sqsubset> y) \\<and> \\<not>(y \\<sqsubset> x)\" by simp\n    from H2 have H3 : \"\\<not>(x \\<sqsubseteq> y \\<and> x \\<noteq> y) \\<and> \\<not>(y \\<sqsubseteq> x \\<and> y \\<noteq> x)\" by (simp add : less_def)\n    from H3 have H4 : \"(\\<not>(x \\<sqsubseteq> y) \\<and> \\<not>(y \\<sqsubseteq> x)) \\<or> \\<not>(x \\<noteq> y)\" by blast\n    from H4 show False \n    proof (rule disjE)\n      assume \"\\<not> x \\<noteq> y\"\n      from `\\<not>(x\\<noteq>y)` have \"x = y\" by simp\n      from `x \\<noteq> y` `x = y` show False by (rule notE)\n    next\n      assume H : \"\\<not> x \\<sqsubseteq> y \\<and> \\<not> y \\<sqsubseteq> x\" \n      from total have H' : \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\" by simp\n      from H H' show False by blast\n    qed\n  qed\n  from `\\<not> (x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x) \\<Longrightarrow> False`\n  show \"x \\<sqsubset> y \\<or> x = y \\<or> y \\<sqsubset> x\" by (rule ccontr)\nqed\n\nlocale distrib_lattice = lattice + \n  assumes\n    meet_distr : \"x \\<sqinter> (y \\<sqinter> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n\n  \nlemma (in distrib_lattice) join_distr:\n  \"x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n  sorry\n\nsublocale total_order \\<subseteq> lattice\nproof unfold_locales\n  fix x y\n  from total have \"is_inf x y (if x \\<sqsubseteq> y then x else y)\" by (auto simp add : is_inf_def)\n  then show \"\\<exists>inf. is_inf x y inf\" by (rule exI)\nnext\n  fix x y \n  from total have \"is_sup x y (if x \\<sqsubseteq> y then y else x)\" by (auto simp add : is_sup_def)\n  then show \"\\<exists>sup. is_sup x y sup\" by (rule exI)\nqed\n\nsublocale total_order \\<subseteq> distrib_lattice\n  sorry\n\nlemma \"\\<And>x::nat. x \\<le> x\"\n  by (metis Orderings.order_class.order.refl)\n\nlemma \"\\<And>x::nat. x \\<le> x\"\n  apply (auto simp add : Orderings.order_class.order.refl)\n  sorry\n\nlemma \"(x::nat) \\<le> x\"\nproof-\n  from le_refl[of x] show \"x \\<le> x\" by simp\nqed\n\n(* question pourquoi cette preuve ne marche pas*)\nlemma \"\\<And>x::nat. x \\<le> x\"\nproof-\n  fix x\n  from le_refl[of x] have \"x \\<le> x\" by auto\n(*\nFailed to apply initial proof method\\<^here>:\nusing this:\n  x \\<le> x\ngoal (1 subgoal):\n 1. x \\<le> x\n*)\n  then show ?thesis by auto\n  oops\n\n  print_locale partial_order\n\n\n(* section 5.1 *)\ninterpretation int : partial_order \"(\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool\"\n  by unfold_locales auto\n\n(* section 5.2 *)\ninterpretation int : partial_order \"(\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool\"\n  rewrites \"int.less x y = (x < y)\"\nproof -\n  show \"partial_order ((\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool)\"\n    by unfold_locales auto\n  show \"partial_order.less ((\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool) x y = (x < y)\"\n    unfolding partial_order.less_def [OF \\<open>partial_order (\\<le>)\\<close>]\n    by auto\nqed\n\n(* section 5.3 *)\ninterpretation int : partial_order \"(\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool\"\n  rewrites \"int.less x y = (x < y)\"\nproof -\n  show \"partial_order ((\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool)\"\n    by unfold_locales auto\n  then interpret int : partial_order \"(\\<le>) :: [int, int] \\<Rightarrow> bool\" by assumption\n  show \"int.less x y = (x < y)\"\n    unfolding int.less_def\n    by auto\nqed\n\n(* section 5.4 *)\ninterpretation int : lattice \"(\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool\"\n  rewrites int_min_eq : \"int.meet x y = min x y\"\n  and int_max_eq : \"int.join x y = max x y\"\nproof - \n  show \"lattice ((\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool)\"\n    apply unfold_locales\n     apply (unfold int.is_inf_def int.is_sup_def)\n    by arith+\n  then interpret int : lattice \"(\\<le>) :: int \\<Rightarrow> int \\<Rightarrow> bool\" by assumption\n  show \"int.meet x y =  min x y\"\n    by (bestsimp simp : int.meet_def int.is_inf_def)\n  show \"int.join x y =  max x y\"\n    by (bestsimp simp : int.join_def int.is_sup_def)\nqed\n\n\nlocale order_preserving = \n  po_le : partial_order le  + po_le' : partial_order le'\n  for le (infixl \"\\<sqsubseteq>\" 50) and le' (infixl \"\\<lesssim>\" 50) +\n  fixes \\<phi>\n  assumes hom_le : \"x \\<sqsubseteq> y \\<Longrightarrow> \\<phi> x \\<lesssim> \\<phi> y\"\n\n\n\nprint_locale order_preserving\nprint_locale! order_preserving\n\nnotation (in order_preserving) po_le'.less (infixl \"<\" 50)\nprint_locale! order_preserving\n\n\n(* section 6.1  default instantiations *)\n\n(* section 6.2 implicit  parameters *)\n(* in a locale declarationm the expression partial_order is short for\n    partial_order le for le (infixl \"\\<sqsubseteq>\" 50)   *)\n\nlocale lattice_hom = \n  le : lattice + le' : lattice le' for le' (infixl \"\\<lesssim>\" 50) +\nfixes \\<phi>\nassumes \n  hom_meet : \"\\<phi> (x \\<sqinter> y) = le'.meet (\\<phi> x) (\\<phi> y)\"\n  and\n  hom_join : \"\\<phi> (x \\<squnion> y) = le'.join (\\<phi> x) (\\<phi> y)\"\n\ncontext lattice_hom\nbegin\n  notation le'.meet (infixl \"\\<sqinter>''\" 50)\n  notation le'.join (infixl \"\\<squnion>''\" 50)\nend\n\nlocale lattice_hom_2 = \n  le : lattice le + le' : lattice le' \n  for le (infixl \"\\<sqsubseteq>\" 50) and le' (infixl \"\\<lesssim>\" 50) +\nfixes \\<phi>\nassumes \n  hom_meet : \"\\<phi> (x \\<sqinter> y) = le'.meet (\\<phi> x) (\\<phi> y)\"\n  and\n  hom_join : \"\\<phi> (x \\<squnion> y) = le'.join (\\<phi> x) (\\<phi> y)\"\n\n(* section 7 Conditional interpretation*)\n\nlocale non_negative =\n  fixes n :: int\n  assumes non_neg : \"0 \\<le> n\"\n\nsublocale non_negative \\<subseteq> order_preserving \"(\\<le>)\" \"(\\<le>)\" \"\\<lambda>i. n * i\"\n\n\nend", "meta": {"author": "Qdake", "repo": "M2-LMFI_MPRI_programming_exo", "sha": "22c51738c66a79d5ce91be923edd76e7e0c68ca1", "save_path": "github-repos/isabelle/Qdake-M2-LMFI_MPRI_programming_exo", "path": "github-repos/isabelle/Qdake-M2-LMFI_MPRI_programming_exo/M2-LMFI_MPRI_programming_exo-22c51738c66a79d5ce91be923edd76e7e0c68ca1/isabelle/brouillon/locale_ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8652240947405564, "lm_q1q2_score": 0.7662696980434563}}
{"text": "(*<*)theory Advanced imports Even begin(*>*)\n\ntext \\<open>\nThe premises of introduction rules may contain universal quantifiers and\nmonotone functions.  A universal quantifier lets the rule \nrefer to any number of instances of \nthe inductively defined set.  A monotone function lets the rule refer\nto existing constructions (such as ``list of'') over the inductively defined\nset.  The examples below show how to use the additional expressiveness\nand how to reason from the resulting definitions.\n\\<close>\n\nsubsection\\<open>Universal Quantifiers in Introduction Rules \\label{sec:gterm-datatype}\\<close>\n\ntext \\<open>\n\\index{ground terms example|(}%\n\\index{quantifiers!and inductive definitions|(}%\nAs a running example, this section develops the theory of \\textbf{ground\nterms}: terms constructed from constant and function \nsymbols but not variables. To simplify matters further, we regard a\nconstant as a function applied to the null argument  list.  Let us declare a\ndatatype \\<open>gterm\\<close> for the type of ground  terms. It is a type constructor\nwhose argument is a type of  function symbols. \n\\<close>\n\ndatatype 'f gterm = Apply 'f \"'f gterm list\"\n\ntext \\<open>\nTo try it out, we declare a datatype of some integer operations: \ninteger constants, the unary minus operator and the addition \noperator.\n\\<close>\n\ndatatype integer_op = Number int | UnaryMinus | Plus\n\ntext \\<open>\nNow the type \\<^typ>\\<open>integer_op gterm\\<close> denotes the ground \nterms built over those symbols.\n\nThe type constructor \\<open>gterm\\<close> can be generalized to a function \nover sets.  It returns \nthe set of ground terms that can be formed over a set \\<open>F\\<close> of function symbols. For\nexample,  we could consider the set of ground terms formed from the finite \nset \\<open>{Number 2, UnaryMinus, Plus}\\<close>.\n\nThis concept is inductive. If we have a list \\<open>args\\<close> of ground terms \nover~\\<open>F\\<close> and a function symbol \\<open>f\\<close> in \\<open>F\\<close>, then we \ncan apply \\<open>f\\<close> to \\<open>args\\<close> to obtain another ground term. \nThe only difficulty is that the argument list may be of any length. Hitherto, \neach rule in an inductive definition referred to the inductively \ndefined set a fixed number of times, typically once or twice. \nA universal quantifier in the premise of the introduction rule \nexpresses that every element of \\<open>args\\<close> belongs\nto our inductively defined set: is a ground term \nover~\\<open>F\\<close>.  The function \\<^term>\\<open>set\\<close> denotes the set of elements in a given \nlist. \n\\<close>\n\ninductive_set\n  gterms :: \"'f set \\<Rightarrow> 'f gterm set\"\n  for F :: \"'f set\"\nwhere\nstep[intro!]: \"\\<lbrakk>\\<forall>t \\<in> set args. t \\<in> gterms F;  f \\<in> F\\<rbrakk>\n               \\<Longrightarrow> (Apply f args) \\<in> gterms F\"\n\ntext \\<open>\nTo demonstrate a proof from this definition, let us \nshow that the function \\<^term>\\<open>gterms\\<close>\nis \\textbf{monotone}.  We shall need this concept shortly.\n\\<close>\n\nlemma gterms_mono: \"F\\<subseteq>G \\<Longrightarrow> gterms F \\<subseteq> gterms G\"\napply clarify\napply (erule gterms.induct)\napply blast\ndone\n(*<*)\nlemma gterms_mono: \"F\\<subseteq>G \\<Longrightarrow> gterms F \\<subseteq> gterms G\"\napply clarify\napply (erule gterms.induct)\n(*>*)\ntxt\\<open>\nIntuitively, this theorem says that\nenlarging the set of function symbols enlarges the set of ground \nterms. The proof is a trivial rule induction.\nFirst we use the \\<open>clarify\\<close> method to assume the existence of an element of\n\\<^term>\\<open>gterms F\\<close>.  (We could have used \\<open>intro subsetI\\<close>.)  We then\napply rule induction. Here is the resulting subgoal:\n@{subgoals[display,indent=0]}\nThe assumptions state that \\<open>f\\<close> belongs \nto~\\<open>F\\<close>, which is included in~\\<open>G\\<close>, and that every element of the list \\<open>args\\<close> is\na ground term over~\\<open>G\\<close>.  The \\<open>blast\\<close> method finds this chain of reasoning easily.  \n\\<close>\n(*<*)oops(*>*)\ntext \\<open>\n\\begin{warn}\nWhy do we call this function \\<open>gterms\\<close> instead \nof \\<open>gterm\\<close>?  A constant may have the same name as a type.  However,\nname  clashes could arise in the theorems that Isabelle generates. \nOur choice of names keeps \\<open>gterms.induct\\<close> separate from \n\\<open>gterm.induct\\<close>.\n\\end{warn}\n\nCall a term \\textbf{well-formed} if each symbol occurring in it is applied\nto the correct number of arguments.  (This number is called the symbol's\n\\textbf{arity}.)  We can express well-formedness by\ngeneralizing the inductive definition of\n\\isa{gterms}.\nSuppose we are given a function called \\<open>arity\\<close>, specifying the arities\nof all symbols.  In the inductive step, we have a list \\<open>args\\<close> of such\nterms and a function  symbol~\\<open>f\\<close>. If the length of the list matches the\nfunction's arity  then applying \\<open>f\\<close> to \\<open>args\\<close> yields a well-formed\nterm.\n\\<close>\n\ninductive_set\n  well_formed_gterm :: \"('f \\<Rightarrow> nat) \\<Rightarrow> 'f gterm set\"\n  for arity :: \"'f \\<Rightarrow> nat\"\nwhere\nstep[intro!]: \"\\<lbrakk>\\<forall>t \\<in> set args. t \\<in> well_formed_gterm arity;  \n                length args = arity f\\<rbrakk>\n               \\<Longrightarrow> (Apply f args) \\<in> well_formed_gterm arity\"\n\ntext \\<open>\nThe inductive definition neatly captures the reasoning above.\nThe universal quantification over the\n\\<open>set\\<close> of arguments expresses that all of them are well-formed.%\n\\index{quantifiers!and inductive definitions|)}\n\\<close>\n\nsubsection\\<open>Alternative Definition Using a Monotone Function\\<close>\n\ntext \\<open>\n\\index{monotone functions!and inductive definitions|(}% \nAn inductive definition may refer to the\ninductively defined  set through an arbitrary monotone function.  To\ndemonstrate this powerful feature, let us\nchange the  inductive definition above, replacing the\nquantifier by a use of the function \\<^term>\\<open>lists\\<close>. This\nfunction, from the Isabelle theory of lists, is analogous to the\nfunction \\<^term>\\<open>gterms\\<close> declared above: if \\<open>A\\<close> is a set then\n\\<^term>\\<open>lists A\\<close> is the set of lists whose elements belong to\n\\<^term>\\<open>A\\<close>.  \n\nIn the inductive definition of well-formed terms, examine the one\nintroduction rule.  The first premise states that \\<open>args\\<close> belongs to\nthe \\<open>lists\\<close> of well-formed terms.  This formulation is more\ndirect, if more obscure, than using a universal quantifier.\n\\<close>\n\ninductive_set\n  well_formed_gterm' :: \"('f \\<Rightarrow> nat) \\<Rightarrow> 'f gterm set\"\n  for arity :: \"'f \\<Rightarrow> nat\"\nwhere\nstep[intro!]: \"\\<lbrakk>args \\<in> lists (well_formed_gterm' arity);  \n                length args = arity f\\<rbrakk>\n               \\<Longrightarrow> (Apply f args) \\<in> well_formed_gterm' arity\"\nmonos lists_mono\n\ntext \\<open>\nWe cite the theorem \\<open>lists_mono\\<close> to justify \nusing the function \\<^term>\\<open>lists\\<close>.%\n\\footnote{This particular theorem is installed by default already, but we\ninclude the \\isakeyword{monos} declaration in order to illustrate its syntax.}\n@{named_thms [display,indent=0] lists_mono [no_vars] (lists_mono)}\nWhy must the function be monotone?  An inductive definition describes\nan iterative construction: each element of the set is constructed by a\nfinite number of introduction rule applications.  For example, the\nelements of \\isa{even} are constructed by finitely many applications of\nthe rules\n@{thm [display,indent=0] even.intros [no_vars]}\nAll references to a set in its\ninductive definition must be positive.  Applications of an\nintroduction rule cannot invalidate previous applications, allowing the\nconstruction process to converge.\nThe following pair of rules do not constitute an inductive definition:\n\\begin{trivlist}\n\\item \\<^term>\\<open>0 \\<in> even\\<close>\n\\item \\<^term>\\<open>n \\<notin> even \\<Longrightarrow> (Suc n) \\<in> even\\<close>\n\\end{trivlist}\nShowing that 4 is even using these rules requires showing that 3 is not\neven.  It is far from trivial to show that this set of rules\ncharacterizes the even numbers.  \n\nEven with its use of the function \\isa{lists}, the premise of our\nintroduction rule is positive:\n@{thm [display,indent=0] (prem 1) step [no_vars]}\nTo apply the rule we construct a list \\<^term>\\<open>args\\<close> of previously\nconstructed well-formed terms.  We obtain a\nnew term, \\<^term>\\<open>Apply f args\\<close>.  Because \\<^term>\\<open>lists\\<close> is monotone,\napplications of the rule remain valid as new terms are constructed.\nFurther lists of well-formed\nterms become available and none are taken away.%\n\\index{monotone functions!and inductive definitions|)} \n\\<close>\n\nsubsection\\<open>A Proof of Equivalence\\<close>\n\ntext \\<open>\nWe naturally hope that these two inductive definitions of ``well-formed'' \ncoincide.  The equality can be proved by separate inclusions in \neach direction.  Each is a trivial rule induction. \n\\<close>\n\nlemma \"well_formed_gterm arity \\<subseteq> well_formed_gterm' arity\"\napply clarify\napply (erule well_formed_gterm.induct)\napply auto\ndone\n(*<*)\nlemma \"well_formed_gterm arity \\<subseteq> well_formed_gterm' arity\"\napply clarify\napply (erule well_formed_gterm.induct)\n(*>*)\ntxt \\<open>\nThe \\<open>clarify\\<close> method gives\nus an element of \\<^term>\\<open>well_formed_gterm arity\\<close> on which to perform \ninduction.  The resulting subgoal can be proved automatically:\n@{subgoals[display,indent=0]}\nThis proof resembles the one given in\n{\\S}\\ref{sec:gterm-datatype} above, especially in the form of the\ninduction hypothesis.  Next, we consider the opposite inclusion:\n\\<close>\n(*<*)oops(*>*)\nlemma \"well_formed_gterm' arity \\<subseteq> well_formed_gterm arity\"\napply clarify\napply (erule well_formed_gterm'.induct)\napply auto\ndone\n(*<*)\nlemma \"well_formed_gterm' arity \\<subseteq> well_formed_gterm arity\"\napply clarify\napply (erule well_formed_gterm'.induct)\n(*>*)\ntxt \\<open>\nThe proof script is virtually identical,\nbut the subgoal after applying induction may be surprising:\n@{subgoals[display,indent=0,margin=65]}\nThe induction hypothesis contains an application of \\<^term>\\<open>lists\\<close>.  Using a\nmonotone function in the inductive definition always has this effect.  The\nsubgoal may look uninviting, but fortunately \n\\<^term>\\<open>lists\\<close> distributes over intersection:\n@{named_thms [display,indent=0] lists_Int_eq [no_vars] (lists_Int_eq)}\nThanks to this default simplification rule, the induction hypothesis \nis quickly replaced by its two parts:\n\\begin{trivlist}\n\\item \\<^term>\\<open>args \\<in> lists (well_formed_gterm' arity)\\<close>\n\\item \\<^term>\\<open>args \\<in> lists (well_formed_gterm arity)\\<close>\n\\end{trivlist}\nInvoking the rule \\<open>well_formed_gterm.step\\<close> completes the proof.  The\ncall to \\<open>auto\\<close> does all this work.\n\nThis example is typical of how monotone functions\n\\index{monotone functions} can be used.  In particular, many of them\ndistribute over intersection.  Monotonicity implies one direction of\nthis set equality; we have this theorem:\n@{named_thms [display,indent=0] mono_Int [no_vars] (mono_Int)}\n\\<close>\n(*<*)oops(*>*)\n\n\nsubsection\\<open>Another Example of Rule Inversion\\<close>\n\ntext \\<open>\n\\index{rule inversion|(}%\nDoes \\<^term>\\<open>gterms\\<close> distribute over intersection?  We have proved that this\nfunction is monotone, so \\<open>mono_Int\\<close> gives one of the inclusions.  The\nopposite inclusion asserts that if \\<^term>\\<open>t\\<close> is a ground term over both of the\nsets\n\\<^term>\\<open>F\\<close> and~\\<^term>\\<open>G\\<close> then it is also a ground term over their intersection,\n\\<^term>\\<open>F \\<inter> G\\<close>.\n\\<close>\n\nlemma gterms_IntI:\n     \"t \\<in> gterms F \\<Longrightarrow> t \\<in> gterms G \\<longrightarrow> t \\<in> gterms (F\\<inter>G)\"\n(*<*)oops(*>*)\ntext \\<open>\nAttempting this proof, we get the assumption \n\\<^term>\\<open>Apply f args \\<in> gterms G\\<close>, which cannot be broken down. \nIt looks like a job for rule inversion:\\cmmdx{inductive\\protect\\_cases}\n\\<close>\n\ninductive_cases gterm_Apply_elim [elim!]: \"Apply f args \\<in> gterms F\"\n\ntext \\<open>\nHere is the result.\n@{named_thms [display,indent=0,margin=50] gterm_Apply_elim [no_vars] (gterm_Apply_elim)}\nThis rule replaces an assumption about \\<^term>\\<open>Apply f args\\<close> by \nassumptions about \\<^term>\\<open>f\\<close> and~\\<^term>\\<open>args\\<close>.  \nNo cases are discarded (there was only one to begin\nwith) but the rule applies specifically to the pattern \\<^term>\\<open>Apply f args\\<close>.\nIt can be applied repeatedly as an elimination rule without looping, so we\nhave given the \\<open>elim!\\<close> attribute. \n\nNow we can prove the other half of that distributive law.\n\\<close>\n\nlemma gterms_IntI [rule_format, intro!]:\n     \"t \\<in> gterms F \\<Longrightarrow> t \\<in> gterms G \\<longrightarrow> t \\<in> gterms (F\\<inter>G)\"\napply (erule gterms.induct)\napply blast\ndone\n(*<*)\nlemma \"t \\<in> gterms F \\<Longrightarrow> t \\<in> gterms G \\<longrightarrow> t \\<in> gterms (F\\<inter>G)\"\napply (erule gterms.induct)\n(*>*)\ntxt \\<open>\nThe proof begins with rule induction over the definition of\n\\<^term>\\<open>gterms\\<close>, which leaves a single subgoal:  \n@{subgoals[display,indent=0,margin=65]}\nTo prove this, we assume \\<^term>\\<open>Apply f args \\<in> gterms G\\<close>.  Rule inversion,\nin the form of \\<open>gterm_Apply_elim\\<close>, infers\nthat every element of \\<^term>\\<open>args\\<close> belongs to \n\\<^term>\\<open>gterms G\\<close>; hence (by the induction hypothesis) it belongs\nto \\<^term>\\<open>gterms (F \\<inter> G)\\<close>.  Rule inversion also yields\n\\<^term>\\<open>f \\<in> G\\<close> and hence \\<^term>\\<open>f \\<in> F \\<inter> G\\<close>. \nAll of this reasoning is done by \\<open>blast\\<close>.\n\n\\smallskip\nOur distributive law is a trivial consequence of previously-proved results:\n\\<close>\n(*<*)oops(*>*)\nlemma gterms_Int_eq [simp]:\n     \"gterms (F \\<inter> G) = gterms F \\<inter> gterms G\"\nby (blast intro!: mono_Int monoI gterms_mono)\n\ntext_raw \\<open>\n\\index{rule inversion|)}%\n\\index{ground terms example|)}\n\n\n\\begin{isamarkuptext}\n\\begin{exercise}\nA function mapping function symbols to their \ntypes is called a \\textbf{signature}.  Given a type \nranging over type symbols, we can represent a function's type by a\nlist of argument types paired with the result type. \nComplete this inductive definition:\n\\begin{isabelle}\n\\<close>\n\ninductive_set\n  well_typed_gterm :: \"('f \\<Rightarrow> 't list * 't) \\<Rightarrow> ('f gterm * 't)set\"\n  for sig :: \"'f \\<Rightarrow> 't list * 't\"\n(*<*)\nwhere\nstep[intro!]: \n    \"\\<lbrakk>\\<forall>pair \\<in> set args. pair \\<in> well_typed_gterm sig; \n      sig f = (map snd args, rtype)\\<rbrakk>\n     \\<Longrightarrow> (Apply f (map fst args), rtype) \n         \\<in> well_typed_gterm sig\"\n(*>*)\ntext_raw \\<open>\n\\end{isabelle}\n\\end{exercise}\n\\end{isamarkuptext}\n\\<close>\n\n(*<*)\n\ntext\\<open>the following declaration isn't actually used\\<close>\nprimrec\n  integer_arity :: \"integer_op \\<Rightarrow> nat\"\nwhere\n  \"integer_arity (Number n)        = 0\"\n| \"integer_arity UnaryMinus        = 1\"\n| \"integer_arity Plus              = 2\"\n\ntext\\<open>the rest isn't used: too complicated.  OK for an exercise though.\\<close>\n\ninductive_set\n  integer_signature :: \"(integer_op * (unit list * unit)) set\"\nwhere\n  Number:     \"(Number n,   ([], ())) \\<in> integer_signature\"\n| UnaryMinus: \"(UnaryMinus, ([()], ())) \\<in> integer_signature\"\n| Plus:       \"(Plus,       ([(),()], ())) \\<in> integer_signature\"\n\ninductive_set\n  well_typed_gterm' :: \"('f \\<Rightarrow> 't list * 't) \\<Rightarrow> ('f gterm * 't)set\"\n  for sig :: \"'f \\<Rightarrow> 't list * 't\"\nwhere\nstep[intro!]: \n    \"\\<lbrakk>args \\<in> lists(well_typed_gterm' sig); \n      sig f = (map snd args, rtype)\\<rbrakk>\n     \\<Longrightarrow> (Apply f (map fst args), rtype) \n         \\<in> well_typed_gterm' sig\"\nmonos lists_mono\n\n\nlemma \"well_typed_gterm sig \\<subseteq> well_typed_gterm' sig\"\napply clarify\napply (erule well_typed_gterm.induct)\napply auto\ndone\n\nlemma \"well_typed_gterm' sig \\<subseteq> well_typed_gterm sig\"\napply clarify\napply (erule well_typed_gterm'.induct)\napply auto\ndone\n\n\nend\n(*>*)\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/Inductive/Advanced.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.8933094103149354, "lm_q1q2_score": 0.7662523330477549}}
{"text": "section \\<open>Sum of Vector Sets\\<close>\n\ntext \\<open>We use Isabelle's Set-Algebra theory to be able to write V + W for sets of vectors V and W,\n and prove some obvious properties about them.\\<close>\ntheory Sum_Vec_Set\n  imports\n    Missing_Matrix\n    \"HOL-Library.Set_Algebras\"\nbegin\n\n\nlemma add_0_right_vecset:\n  assumes \"(A :: 'a :: monoid_add vec set) \\<subseteq> carrier_vec n\"\n  shows \"A + {0\\<^sub>v n} = A\"\n  unfolding set_plus_def using assms by force\n\nlemma add_0_left_vecset:\n  assumes \"(A :: 'a :: monoid_add vec set) \\<subseteq> carrier_vec n\"\n  shows \"{0\\<^sub>v n} + A = A\"\n  unfolding set_plus_def using assms by force\n\nlemma assoc_add_vecset:\n  assumes \"(A :: 'a :: semigroup_add vec set) \\<subseteq> carrier_vec n\"\n    and \"B \\<subseteq> carrier_vec n\"\n    and \"C \\<subseteq> carrier_vec n\"\n  shows \"A + (B + C) = (A + B) + C\"\nproof -\n  {\n    fix x\n    assume \"x \\<in> A + (B + C)\"\n    then obtain a b c where \"x = a + (b + c)\" and *: \"a \\<in> A\" \"b \\<in> B\" \"c \\<in> C\"\n      unfolding set_plus_def by auto\n    with assms have \"x = (a + b) + c\" using assoc_add_vec[of a n b c] by force\n    with * have \"x \\<in> (A + B) + C\" by auto\n  }\n  moreover\n  {\n    fix x\n    assume \"x \\<in> (A + B) + C\"\n    then obtain a b c where \"x = (a + b) + c\" and *: \"a \\<in> A\" \"b \\<in> B\" \"c \\<in> C\"\n      unfolding set_plus_def by auto\n    with assms have \"x = a + (b + c)\" using assoc_add_vec[of a n b c] by force\n    with * have \"x \\<in> A + (B + C)\" by auto\n  }\n  ultimately show ?thesis by blast\nqed\n\n\n\nlemma comm_add_vecset:\n  assumes \"(A :: 'a :: ab_semigroup_add vec set) \\<subseteq> carrier_vec n\"\n    and \"B \\<subseteq> carrier_vec n\"\n  shows \"A + B = B + A\"\n  unfolding set_plus_def using comm_add_vec assms by blast\n\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Linear_Inequalities/Sum_Vec_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8577681122619885, "lm_q1q2_score": 0.7662523302063075}}
{"text": "theory hw04\n  imports Main  \"~~/src/HOL/Library/Tree\"\nbegin\n\ndeclare Let_def [simp]\n\ndatatype 'a rtree = Leaf | Node \"'a rtree\" nat 'a \"'a rtree\"\n\nfun num_nodes:: \"'a rtree \\<Rightarrow> nat\" where\n  \"num_nodes Leaf = 0\"\n| \"num_nodes (Node l n b r) = 1 + num_nodes l + num_nodes r\"\n\nfun rbst:: \"'a::linorder rtree \\<Rightarrow> bool\" where\n  \"rbst Leaf = True\"\n| \"rbst (Node l a b r) = (rbst l \\<and> (\\<forall>x\\<in>set_rtree l. (b > x)) \\<and> (\\<forall>x\\<in>set_rtree r. (b < x)) \\<and> (a = num_nodes l) \\<and> rbst r)\"\n\n\nvalue \"rbst (Node (Node Leaf (0::nat) (1::nat) Leaf) (1::nat) 2 (Node Leaf (0::nat) 3 Leaf))\"\n\nfun rins:: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> 'a rtree\" where\n  \"rins x Leaf = (Node Leaf 0 x Leaf)\"\n| \"rins x (Node l n b r) =\n  (if (x < b) then (Node (rins x l) (Suc n) b r) else (Node l n b (rins x r)))\"\n\nvalue \"rins (4::nat) (Node (Node Leaf (0::nat) (1::nat) Leaf) (1::nat) 2 (Node Leaf (0::nat) 3 Leaf))\"\n\nlemma rins_set[simp]: \"set_rtree (rins x t) = insert x (set_rtree t)\"\n  apply(induction t arbitrary:x)\n   apply(auto)\n  done\n\n\nlemma aux1[simp]: \"(x\\<notin>set_rtree t) \\<Longrightarrow> num_nodes (rins x t) = Suc(num_nodes t)\"\n  apply(induction t arbitrary: x)\n   apply(auto)\n  done\n\nlemma aux2[simp]: \"rbst(Node l a b r) \\<Longrightarrow> (num_nodes l = a) \"\n   apply(auto)\n  done\n\nvalue \"rbst  (rtree.Node rtree.Leaf 0 (1::nat) (rtree.Node rtree.Leaf 0 (1::nat) rtree.Leaf))\"\n\n\n\nlemma \"x\\<notin>set_rtree t \\<Longrightarrow> rbst t \\<Longrightarrow> rbst (rins x t)\"\n  apply(induction t arbitrary: x rule:rbst.induct)\n   apply(auto)\n  done\n\nfun risin :: \"'a::linorder \\<Rightarrow> 'a rtree \\<Rightarrow> bool\" where\n  \"risin x Leaf = False\"\n| \"risin x (Node l a b r) = \n  (\n    if (b < x) then\n      (risin x r)\n    else if (b > x) then\n      (risin x l)\n    else\n      True\n  )\"\n\nvalue \"risin (3::nat) (Node (Node Leaf (0::nat) (1::nat) Leaf) (1::nat) 2 (Node Leaf (0::nat) 3 Leaf))\"\n\nlemma \"rbst t \\<Longrightarrow> risin x t \\<longleftrightarrow> x\\<in>set_rtree t\"\n  apply(induction t)\n   apply(auto)\n  done\n\nfun inorder:: \"'a rtree \\<Rightarrow> 'a list\" where\n  \"inorder Leaf = []\"\n| \"inorder (Node l a b r) = inorder l @ [b] @ inorder r\"\n\nfun rank::\"'a::linorder \\<Rightarrow> _\" where\n  \"rank x Leaf = undefined\"\n| \"rank x (Node l a b r) = (if (x = b) then a else if (x < b) then (rank x l) else (a + 1 + rank x r))\"\n\ndefinition \"at_index i l x \\<equiv> i<length l \\<and> l!i=x\"\n\nlemma aux3[simp]:\"rbst t \\<Longrightarrow> num_nodes t = length (inorder t)\"\n  apply(induction t)\n   apply(auto)\n  done\n\n\nlemma \"rbst t \\<Longrightarrow> x\\<in>set_rtree t \\<Longrightarrow> at_index (rank x t) (inorder t) x\"\n  unfolding at_index_def\n  apply(induction t rule:inorder.induct)\n   apply(auto)\n  sorry\n\nfun select :: \"nat \\<Rightarrow> 'a::linorder rtree \\<Rightarrow> 'a\" where\n  \"select n Leaf = undefined\"\n| \"select n (Node l a b r) = (if (n = a) then b else if n < a then select n l else select (n-a-1) r)\"\n\nlemma select_correct: \"rbst t \\<Longrightarrow> i<length (inorder t) \\<Longrightarrow> select i t = inorder t ! i\"\n  apply(induction i t rule:select.induct)\n   apply(auto)\n  sorry\n\nend", "meta": {"author": "amartyads", "repo": "functional-data-structures-HW", "sha": "df9edfd02bda931a0633f0e66bf8e32d7347902b", "save_path": "github-repos/isabelle/amartyads-functional-data-structures-HW", "path": "github-repos/isabelle/amartyads-functional-data-structures-HW/functional-data-structures-HW-df9edfd02bda931a0633f0e66bf8e32d7347902b/04/hw04.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218284193595, "lm_q2_score": 0.8311430499496096, "lm_q1q2_score": 0.7662489202875872}}
{"text": "theory Ch5\n  imports Main\nbegin\n\n(*\nthen = from this\nthus = then show\nhence = then have\n*)\n\n(*\n\nsee of and OF 4.4.4\n\nf.simps refers to the whole list of recursion equations defining\nf. Individual facts can be selected by writing f.simps(2), whole sublists by\nwriting f.simps(2−4).\n\n*)\n\n(*\nshow \"P (n)\"\nproof (induction n)\n  case 0            // let ?case = \"P (0)\"\n  ..\n  show ?case <proof>\nnext\n  case (Suc n)      // fix n assume Suc: \"P(n)\"\n                    // let ?case = \"P (Suc n)\"\n  ..\n  show ?case <proof>\nqed\n\nThat is, if in the above proof we replace show \"P (n)\" by\nshow \"A(n) \\<Longrightarrow> P (n)\" then case 0 stands for\n\n  assume 0: \"A(0)\"\n  let ?case = \"P (0)\"\n\nand case (Suc n) stands for\n\n  fix n\n  assume Suc: \"A(n) \\<Longrightarrow> P (n)\"\n              \"A(Suc n)\"\n  let ?case = \"P (Suc n)\"\n\npage 64 induction trickery\n\n*)\n\nlemma \"\\<not> surj (f :: 'a \\<Rightarrow> 'a set )\"\nproof\nassume 0: \"surj f\"\nfrom 0 have 1: \"\\<forall> A. \\<exists> a. A = f a\" by(simp add: surj_def)\nfrom 1 have 2: \"\\<exists> a. {x . x \\<notin> f x } = f a\" by blast\nfrom 2 show \"False\" by blast\nqed\n\nlemma \"\\<not> surj (f :: 'a \\<Rightarrow> 'a set )\"\nproof\nassume \"surj f\"\n  hence \"\\<exists> a. {x . x \\<notin> f x } = f a\" by(auto simp: surj_def)\n  thus \"False\" by blast\nqed\n\n(* 5.1 *)\n\nlemma\n  assumes TT: \"\\<forall> x y. T x y \\<or> T y x\"\n    and A:    \"\\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n    and TA:   \"\\<forall> x y. T x y \\<longrightarrow> A x y\"\n    and A2:   \"A x y\"\n  shows       \"T x y\"\nproof (rule ccontr)\n  assume Z: \"\\<not> T x y\"\n  from TT and this have \"T y x\" by auto\n  from TA and this have \"A y x\" by auto\n  from this and A2 have \"A x y \\<and> A y x\" by auto\n  from this and A have \"x = y\" by auto\n  from this and TT and Z show \"False\" by auto\nqed\n\n(* 5.2 *)\n\nlemma \"\\<exists> ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof -\n  obtain n where nd: \"n = (length xs) div 2\" by auto\n  obtain m where md: \"m = (length xs) - n\" by auto\n  from md have mmin: \"m \\<le> length xs\" by auto\n  from nd and md have mneq: \"m = n \\<or> m = n + 1\" by auto\n  obtain ys where yd: \"ys = take m xs\" by auto\n  obtain zs where zd: \"zs = drop m xs\" by auto\n  from nd and yd and mmin have L1: \"length ys = m\" by auto\n  from nd and md and zd have L2: \"length zs = n\" by auto\n  from L1 and L2 and mneq have Lconj: \"length ys = length zs \\<or> length ys = length zs + 1\" by auto\n  from yd and zd have Conc: \"xs = ys @ zs\" by auto\n  from Conc and Lconj show ?thesis by auto\nqed\n\n(* 5.3 *)\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev n \\<Longrightarrow> ev (n - 2)\"\nproof -\n  assume \"ev n\"\n  from this have \"ev (n - 2)\"\n  proof cases\n    case ev0 thus \"ev(n - 2)\" by (simp add: ev.ev0)\n  next\n    case (evSS k) thus \"ev (n - 2)\" by (simp add: ev.evSS)\n  qed\n  thus ?thesis by auto\nqed\n\nlemma assumes a: \"ev (Suc (Suc n))\" shows \"ev n\"\nproof -\n  show ?thesis using a\n  proof cases\n    case evSS thus ?thesis by auto\n  qed\nqed\n\nlemma assumes a: \"ev (Suc (Suc n))\" shows \"ev n\"\n  using a ev.cases by blast\n\n(* 5.4 *)\n\nlemma \"\\<not> ev (Suc 0)\"\nproof\n  assume \"ev (Suc 0)\" then show False by cases\nqed\n\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\"\n  hence \"ev (Suc 0)\" by cases\n  thus False by cases\nqed\n\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\n  using ev.cases by auto\n\n(*\nExercise 5.5. Recall predicate star from Section 4.5.2 and iter from Exer-\ncise 4.4. Prove iter r n x y =\\<Rightarrow> star r x y in a structured style; do not just\nsledgehammer each case of the required induction.\n*)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter0: \"iter r 0 x x\" |\nitern: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case iter0\n  show ?case by (auto intro: refl)\nnext\n  case itern\n  thus ?case by (auto intro: step)\nqed\n\n(* 5.6 *)\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (x#xs) = {x} \\<union> elems xs\"\n\nvalue \"elems ([1, 2, 5, 6]::nat list)\"\nvalue \"elems ([]::nat list)\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\n  case Nil thus ?case by auto\nnext\n  case (Cons h xs0) show ?case\n  proof cases\n    assume hx: \"h = x\" then\n    obtain ys where yd: \"ys = ([]::'a list)\" by auto\n    hence \"h \\<notin> elems ys\" by auto\n    thus ?thesis using yd hx by blast\n  next\n    assume hnx: \"h \\<noteq> x\"\n    from hnx Cons.prems have inxs: \"x \\<in> elems xs0\" by auto\n    obtain ys0 zs where iyzs: \"xs0 = ys0 @ x # zs \\<and> x \\<notin> elems ys0\" using Cons.IH inxs by blast\n    obtain ys where yd: \"ys = h # ys0\" by auto\n    obtain xs where xd: \"xs = h # xs0\" by auto\n    from hnx xd yd iyzs have wtf: \"xs = ys @ x # zs \\<and> x \\<notin> elems ys\" by auto\n    from wtf xd show ?thesis by auto\n  qed\nqed\n\n(* 5.7 *)\n\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS0:  \"S Nil\" |\naSb: \"S s \\<Longrightarrow> S (a # s @ [b])\" |\nSS:  \"S x \\<Longrightarrow> S y \\<Longrightarrow> S (x @ y)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nT0:   \"T Nil\" |\nTaTb: \"T x \\<Longrightarrow> T y \\<Longrightarrow> T (x @ a # y @ [b])\"\n\nlemma TS: \"T w \\<Longrightarrow> S w\"\n  apply(induction rule: T.induct)\n  apply(rule S0)\n  apply(rule SS)\n  apply(simp)\n  apply(rule aSb)\n  apply(simp)\n  (* apply(auto intro: S0 aSb SS) *)\n  done\n\nlemma aTb: \"T x \\<Longrightarrow> T (a # x @ [b])\"\n  (* try found it *)\n  by (metis Cons_eq_appendI T.simps self_append_conv2)\n\nlemma TT: \"T y \\<Longrightarrow> T x \\<Longrightarrow> T (x @ y)\"\n  apply(induction rule: T.induct)\n  apply(auto intro: TaTb T0)\n  by (metis T.simps append_eq_appendI)\n\nlemma ST: \"S w \\<Longrightarrow> T w\"\n  apply(induction rule: S.induct)\n  apply(rule T0)\n  apply(rule aTb)\n  apply(simp)\n  apply(rule TT)\n  apply(simp)\n  apply(simp)\n  done\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n\"balanced n Nil = (n = 0)\" |\n\"balanced n (a#xs) = balanced (n + 1) xs\" |\n\"balanced 0 (b#xs) = False\" |\n\"balanced n (b#xs) = balanced (n - 1) xs\"\n\nvalue \"balanced 0 [a, a, b, a, b, b, a, b]\"\n\nlemma \"balanced n w = S (replicate n a @ w)\"\n  sorry\n\nend", "meta": {"author": "user7", "repo": "concrete-semantics", "sha": "5ddbd752550b3037d0d461d67a39d4f61c4548e5", "save_path": "github-repos/isabelle/user7-concrete-semantics", "path": "github-repos/isabelle/user7-concrete-semantics/concrete-semantics-5ddbd752550b3037d0d461d67a39d4f61c4548e5/Ch5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.9124361628580401, "lm_q1q2_score": 0.7662036539228885}}
{"text": "section \\<open>Specification\\<close>\n\ntheory Goodstein_Lambda\n  imports Main\nbegin\n\nsubsection \\<open>Hereditary base representation\\<close>\n\ntext \\<open>We define a data type of trees and an evaluation function that sums siblings and\n  exponentiates with respect to the given base on nesting.\\<close>\n\ndatatype C = C (unC: \"C list\")\n\nfun evalC where\n  \"evalC b (C []) = 0\"\n| \"evalC b (C (x # xs)) = b^evalC b x + evalC b (C xs)\"\n\nvalue \"evalC 2 (C [])\" \\<comment> \\<open>$0$\\<close>\nvalue \"evalC 2 (C [C []])\" \\<comment> \\<open>$2^0 = 1$\\<close>\nvalue \"evalC 2 (C [C [C []]])\" \\<comment> \\<open>$2^1 = 2$\\<close>\nvalue \"evalC 2 (C [C [], C []])\" \\<comment> \\<open>$2^0 + 2^0 = 2^0 \\cdot 2 = 2$; not in hereditary base $2$\\<close>\n\ntext \\<open>The hereditary base representation is characterized as trees (i.e., nested lists) whose\n  lists have monotonically increasing evaluations, with fewer than @{term \"b\"} repetitions for\n  each value. We will show later that this representation is unique.\\<close>\n\ninductive_set hbase for b where\n  \"C [] \\<in> hbase b\"\n| \"i \\<noteq> 0 \\<Longrightarrow> i < b \\<Longrightarrow> n \\<in> hbase b \\<Longrightarrow>\n   C ms \\<in> hbase b \\<Longrightarrow> (\\<And>m'. m' \\<in> set ms \\<Longrightarrow> evalC b n < evalC b m') \\<Longrightarrow>\n   C (replicate i n @ ms) \\<in> hbase b\"\n\ntext \\<open>We can convert to and from natural numbers as follows.\\<close>\n\ndefinition H2N where\n  \"H2N b n = evalC b n\"\n\ntext \\<open>As we will show later, @{term \"H2N b\"} restricted to @{term \"hbase n\"} is bijective\n  if @{prop \"b \\<ge> (2 :: nat)\"}, so we can convert from natural numbers by taking the inverse.\\<close>\n\ndefinition N2H where\n  \"N2H b n = inv_into (hbase b) (H2N b) n\"\n\nsubsection \\<open>The Goodstein function\\<close>\n\ntext \\<open>We define a function that computes the length of the Goodstein sequence whose $c$-th element\n  is $g_c = n$. Termination will be shown later, thereby establishing Goodstein's theorem.\\<close>\n\nfunction (sequential) goodstein :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"goodstein 0 n = 0\"\n  \\<comment> \\<open>we start counting at 1; also note that the initial base is @{term \"c+1 :: nat\"} and\\<close>\n  \\<comment> \\<open>hereditary base 1 makes no sense, so we have to avoid this case\\<close>\n| \"goodstein c 0 = c\"\n| \"goodstein c n = goodstein (c+1) (H2N (c+2) (N2H (c+1) n) - 1)\"\n  by pat_completeness auto\n\nabbreviation \\<G> where\n  \"\\<G> n \\<equiv> goodstein (Suc 0) n\"\n\nsection \\<open>Ordinals\\<close>\n\ntext \\<open>The following type contains countable ordinals, by the usual case distinction into 0,\n  successor ordinal, or limit ordinal; limit ordinals are given by their fundamental sequence.\n  Hereditary base @{term \"b\"} representations carry over to such ordinals by replacing each\n  occurrence of the base by @{term \"\\<omega>\"}.\\<close>\n\ndatatype Ord = Z | S Ord | L \"nat \\<Rightarrow> Ord\"\n\ntext \\<open>Note that the following arithmetic operations are not correct for all ordinals. However, they\n  will only be used in cases where they actually correspond to the ordinal arithmetic operations.\\<close>\n\nprimrec addO where\n  \"addO n Z = n\"\n| \"addO n (S m) = S (addO n m)\"\n| \"addO n (L f) = L (\\<lambda>i. addO n (f i))\"\n\nprimrec mulO where\n  \"mulO n Z = Z\"\n| \"mulO n (S m) = addO (mulO n m) n\"\n| \"mulO n (L f) = L (\\<lambda>i. mulO n (f i))\"\n\ndefinition \\<omega> where\n  \"\\<omega> = L (\\<lambda>n. (S ^^ n) Z)\"\n\nprimrec exp\\<omega> where\n  \"exp\\<omega> Z = S Z\"\n| \"exp\\<omega> (S n) = mulO (exp\\<omega> n) \\<omega>\"\n| \"exp\\<omega> (L f) = L (\\<lambda>i. exp\\<omega> (f i))\"\n\nsubsection \\<open>Evaluation\\<close>\n\ntext \\<open>Evaluating an ordinal number at base $b$ is accomplished by taking the $b$-th element of\n  all fundamental sequences and interpreting zero and successor over the natural numbers.\\<close>\n\nprimrec evalO where\n  \"evalO b Z = 0\"\n| \"evalO b (S n) = Suc (evalO b n)\"\n| \"evalO b (L f) = evalO b (f b)\"\n\nsubsection \\<open>Goodstein function and sequence\\<close>\n\ntext \\<open>We can define the Goodstein function very easily, but proving correctness will take a while.\\<close>\n\nprimrec goodsteinO where\n  \"goodsteinO c Z = c\"\n| \"goodsteinO c (S n) = goodsteinO (c+1) n\"\n| \"goodsteinO c (L f) = goodsteinO c (f (c+2))\"\n\nprimrec stepO where\n  \"stepO c Z = Z\"\n| \"stepO c (S n) = n\"\n| \"stepO c (L f) = stepO c (f (c+2))\"\n\ntext \\<open>We can compute a few values of the Goodstein sequence starting at $4$.\\<close>\n\ndefinition g4O where\n  \"g4O n = fold stepO [1..<Suc n] ((exp\\<omega> ^^ 3) Z)\"\n\nvalue \"map (\\<lambda>n. evalO (n+2) (g4O n)) [0..<10]\"\n\\<comment> \\<open>@{value \"[4, 26, 41, 60, 83, 109, 139, 173, 211, 253] :: nat list\"}\\<close>\n\nsubsection \\<open>Properties of evaluation\\<close>\n\nlemma evalO_addO [simp]:\n  \"evalO b (addO n m) = evalO b n + evalO b m\"\n  by (induct m) auto\n\nlemma evalO_mulO [simp]:\n  \"evalO b (mulO n m) = evalO b n * evalO b m\"\n  by (induct m) auto\n\nlemma evalO_n [simp]:\n  \"evalO b ((S ^^ n) Z) = n\"\n  by (induct n) auto\n\nlemma evalO_\\<omega> [simp]:\n  \"evalO b \\<omega> = b\"\n  by (auto simp: \\<omega>_def)\n\nlemma evalO_exp\\<omega> [simp]:\n  \"evalO b (exp\\<omega> n) = b^(evalO b n)\"\n  by (induct n) auto\n\ntext \\<open>Note that evaluation is useful for proving that @{type \"Ord\"} values are distinct:\\<close>\nnotepad begin\n  have \"addO n (exp\\<omega> m) \\<noteq> n\" for n m by (auto dest: arg_cong[of _ _ \"evalO 1\"])\nend\n\nsubsection \\<open>Arithmetic properties\\<close>\n\nlemma addO_Z [simp]:\n  \"addO Z n = n\"\n  by (induct n) auto\n\nlemma addO_assoc [simp]:\n  \"addO n (addO m p) = addO (addO n m) p\"\n  by (induct p) auto\n\nlemma mul0_distrib [simp]:\n  \"mulO n (addO p q) = addO (mulO n p) (mulO n q)\"\n  by (induct q) auto\n\nlemma mulO_assoc [simp]:\n  \"mulO n (mulO m p) = mulO (mulO n m) p\"\n  by (induct p) auto\n\n\n\n\nsection \\<open>Cantor normal form\\<close>\n\ntext \\<open>The previously introduced tree type @{type C} can be used to represent Cantor normal forms;\n  they are trees (evaluated at base @{term \\<omega>}) such that siblings are in non-decreasing order.\n  One can think of this as hereditary base @{term \\<omega>}. The plan is to mirror selected operations on\n  ordinals in Cantor normal forms.\\<close>\n\nsubsection \\<open>Conversion to and from the ordinal type @{type Ord}\\<close>\n\nfun C2O where\n  \"C2O (C []) = Z\"\n| \"C2O (C (n # ns)) = addO (C2O (C ns)) (exp\\<omega> (C2O n))\"\n\ndefinition O2C where\n  \"O2C = inv C2O\"\n\ntext \\<open>We show that @{term C2O} is injective, meaning the inverse is unique.\\<close>\n\nlemma addO_exp\\<omega>_inj:\n  assumes \"addO n (exp\\<omega> m) = addO n' (exp\\<omega> m')\"\n  shows \"n = n'\" and \"m = m'\"\nproof -\n  have \"addO n (exp\\<omega> m) = addO n' (exp\\<omega> m') \\<Longrightarrow> n = n'\"\n    by (induct m arbitrary: m'; case_tac m';\n      force simp: \\<omega>_def dest!: fun_cong[of _ _ 1])\n  moreover have \"addO n (exp\\<omega> m) = addO n (exp\\<omega> m') \\<Longrightarrow> m = m'\"\n    apply (induct m arbitrary: n m'; case_tac m')\n    apply (auto 0 3 simp: \\<omega>_def intro: rangeI\n      dest: arg_cong[of _ _ \"evalO 1\"] fun_cong[of _ _ 0] fun_cong[of _ _ 1])[8] (* 1 left *)\n    by simp (meson ext rangeI)\n  ultimately show \"n = n'\" and \"m = m'\" using assms by simp_all\nqed\n\nlemma C2O_inj:\n  \"C2O n = C2O m \\<Longrightarrow> n = m\"\n  by (induct n arbitrary: m rule: C2O.induct; case_tac m rule: C2O.cases)\n    (auto dest: addO_exp\\<omega>_inj arg_cong[of _ _ \"evalO 1\"])\n\nlemma O2C_C2O [simp]:\n  \"O2C (C2O n) = n\"\n  by (auto intro!: inv_f_f simp: O2C_def inj_def C2O_inj)\n\nlemma O2C_Z [simp]:\n  \"O2C Z = C []\"\n  using O2C_C2O[of \"C []\", unfolded C2O.simps] .\n\nlemma C2O_replicate:\n  \"C2O (C (replicate i n)) = mulO (exp\\<omega> (C2O n)) ((S ^^ i) Z)\"\n  by (induct i) auto\n\nlemma C2O_app:\n  \"C2O (C (xs @ ys)) = addO (C2O (C ys)) (C2O (C xs))\"\n  by (induct xs arbitrary: ys) auto\n\nsubsection \\<open>Evaluation\\<close>\n\nlemma evalC_def':\n  \"evalC b n = evalO b (C2O n)\"\n  by (induct n rule: C2O.induct) auto\n\nlemma evalC_app [simp]:\n  \"evalC b (C (ns @ ms)) = evalC b (C ns) + evalC b (C ms)\"\n  by (induct ns) auto\n\nlemma evalC_replicate [simp]:\n  \"evalC b (C (replicate c n)) = c * evalC b (C [n])\"\n  by (induct c) auto\n\nsubsection \\<open>Transfer of the @{type Ord} induction principle to @{type C}\\<close>\n\nfun funC where \\<comment> \\<open>@{term funC} computes the fundamental sequence on @{type C}\\<close>\n  \"funC (C []) = (\\<lambda>i. [C []])\"\n| \"funC (C (C [] # ns)) = (\\<lambda>i. replicate i (C ns))\"\n| \"funC (C (n # ns)) = (\\<lambda>i. [C (funC n i @ ns)])\"\n\nlemma C2O_cons:\n  \"C2O (C (n # ns)) =\n    (if n = C [] then S (C2O (C ns)) else L (\\<lambda>i. C2O (C (funC n i @ ns))))\"\n  by (induct n arbitrary: ns rule: funC.induct)\n    (simp_all add: \\<omega>_def C2O_replicate C2O_app flip: exp\\<omega>_addO)\n\nlemma C_Ord_induct:\n  assumes \"P (C [])\"\n  and \"\\<And>ns. P (C ns) \\<Longrightarrow> P (C (C [] # ns))\"\n  and \"\\<And>n ns ms. (\\<And>i. P (C (funC (C (n # ns)) i @ ms))) \\<Longrightarrow>\n    P (C (C (n # ns) # ms))\"\n  shows \"P n\"\nproof -\n  have \"\\<forall>n. C2O n = m \\<longrightarrow> P n\" for m\n    by (induct m; intro allI; case_tac n rule: funC.cases)\n      (auto simp: C2O_cons simp del: C2O.simps(2) intro: assms)\n  then show ?thesis by simp\nqed\n\nsubsection \\<open>Goodstein function and sequence on @{type C}\\<close>\n\nfunction (domintros) goodsteinC where\n  \"goodsteinC c (C []) = c\"\n| \"goodsteinC c (C (C [] # ns)) = goodsteinC (c+1) (C ns)\"\n| \"goodsteinC c (C (C (n # ns) # ms)) =\n    goodsteinC c (C (funC (C (n # ns)) (c+2) @ ms))\"\n  by pat_completeness auto\n\ntermination\nproof -\n  have \"goodsteinC_dom (c, n)\" for c n\n    by (induct n arbitrary: c rule: C_Ord_induct) (auto intro: goodsteinC.domintros)\n  then show ?thesis by simp\nqed\n\nlemma goodsteinC_def':\n  \"goodsteinC c n = goodsteinO c (C2O n)\"\n  by (induct c n rule: goodsteinC.induct) (simp_all add: C2O_cons del: C2O.simps(2))\n\nfunction (domintros) stepC where\n  \"stepC c (C []) = C []\"\n| \"stepC c (C (C [] # ns)) = C ns\"\n| \"stepC c (C (C (n # ns) # ms)) =\n    stepC c (C (funC (C (n # ns)) (Suc (Suc c)) @ ms))\"\n  by pat_completeness auto\n\ntermination\nproof -\n  have \"stepC_dom (c, n)\" for c n\n    by (induct n arbitrary: c rule: C_Ord_induct) (auto intro: stepC.domintros)\n  then show ?thesis by simp\nqed\n\ndefinition g4C where\n  \"g4C n = fold stepC [1..<Suc n] (C [C [C [C []]]])\"\n\nvalue \"map (\\<lambda>n. evalC (n+2) (g4C n)) [0..<10]\"\n\\<comment> \\<open>@{value \"[4, 26, 41, 60, 83, 109, 139, 173, 211, 253] :: nat list\"}\\<close>\n\nsubsection \\<open>Properties\\<close>\n\nlemma stepC_def':\n  \"stepC c n = O2C (stepO c (C2O n))\"\n  by (induct c n rule: stepC.induct) (simp_all add: C2O_cons del: C2O.simps(2))\n\nlemma funC_ne [simp]:\n  \"funC m (Suc n) \\<noteq> []\"\n  by (cases m rule: funC.cases) simp_all\n\nlemma evalC_funC [simp]:\n  \"evalC b (C (funC n b)) = evalC b (C [n])\"\n  by (induct n rule: funC.induct) simp_all\n\nlemma stepC_app [simp]:\n  \"n \\<noteq> C [] \\<Longrightarrow> stepC c (C (unC n @ ns)) = C (unC (stepC c n) @ ns)\"\n  by (induct n arbitrary: ns rule: stepC.induct) simp_all\n\nlemma stepC_cons [simp]:\n  \"ns \\<noteq> [] \\<Longrightarrow> stepC c (C (n # ns)) = C (unC (stepC c (C [n])) @ ns)\"\n  using stepC_app[of \"C[n]\" c ns] by simp\n\nlemma stepC_dec:\n  \"n \\<noteq> C [] \\<Longrightarrow> Suc (evalC (Suc (Suc c)) (stepC c n)) = evalC (Suc (Suc c)) n\"\n  by (induct c n rule: stepC.induct) simp_all\n\nlemma stepC_dec':\n  \"n \\<noteq> C [] \\<Longrightarrow> evalC (c+3) (stepC c n) < evalC (c+3) n\"\nproof (induct c n rule: stepC.induct)\n  case (3 c n ns ms)\n  have \"evalC (c+3) (C (funC (C (n # ns)) (Suc (Suc c)))) \\<le>\n      (c+3) ^ ((c+3) ^ evalC (c+3) n + evalC (c+3) (C ns))\"\n    by (induct n rule: funC.induct) (simp_all add: distrib_right)\n  then show ?case using 3 by simp\nqed simp_all\n\n\nsection \\<open>Hereditary base @{term b} representation\\<close>\n\ntext \\<open>We now turn to properties of the @{term \"hbase b\"} subset of trees.\\<close>\n\nsubsection \\<open>Uniqueness\\<close>\n\ntext \\<open>We show uniqueness of the hereditary base representation by showing that @{term \"evalC b\"}\n  restricted to @{term \"hbase b\"} is injective.\\<close>\n\nlemma hbaseI2:\n  \"i < b \\<Longrightarrow> n \\<in> hbase b \\<Longrightarrow> C m \\<in> hbase b \\<Longrightarrow>\n    (\\<And>m'. m' \\<in> set m \\<Longrightarrow> evalC b n < evalC b m') \\<Longrightarrow>\n    C (replicate i n @ m) \\<in> hbase b\"\n  by (cases i) (auto intro: hbase.intros simp del: replicate.simps(2))\n\nlemmas hbase_singletonI =\n  hbase.intros(2)[of 1 \"Suc (Suc b)\" for b, OF _ _ _ hbase.intros(1), simplified]\n\nlemma hbase_hd:\n  \"C ns \\<in> hbase b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> hd ns \\<in> hbase b\"\n  by (cases rule: hbase.cases) auto\n\nlemmas hbase_hd' [dest] = hbase_hd[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_tl:\n  \"C ns \\<in> hbase b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> C (tl ns) \\<in> hbase b\"\n  by (cases \"C ns\" b rule: hbase.cases) (auto intro: hbaseI2)\n\nlemmas hbase_tl' [dest] = hbase_tl[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_elt [dest]:\n  \"C ns \\<in> hbase b \\<Longrightarrow> n \\<in> set ns \\<Longrightarrow> n \\<in> hbase b\"\n  by (induct ns) auto\n\nlemma evalC_sum_list:\n  \"evalC b (C ns) = sum_list (map (\\<lambda>n. b^evalC b n) ns)\"\n  by (induct ns) auto\n\nlemma sum_list_replicate:\n  \"sum_list (replicate n x) = n * x\"\n  by (induct n) auto\n\nlemma base_red:\n  fixes b :: nat\n  assumes n: \"\\<And>n'. n' \\<in> set ns \\<Longrightarrow> n < n'\" \"i < b\" \"i \\<noteq> 0\"\n  and m: \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> m < m'\" \"j < b\" \"j \\<noteq> 0\"\n  and s: \"i * b^n + sum_list (map (\\<lambda>n. b^n) ns) = j * b^m + sum_list (map (\\<lambda>n. b^n) ms)\"\n  shows \"i = j \\<and> n = m\"\n  using n(1) m(1) s\nproof (induct n arbitrary: m ns ms)\n  { fix ns ms :: \"nat list\" and i j m :: nat\n    assume n': \"\\<And>n'. n' \\<in> set ns \\<Longrightarrow> 0 < n'\" \"i < b\" \"i \\<noteq> 0\"\n    assume m': \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> m < m'\" \"j < b\" \"j \\<noteq> 0\"\n    assume s': \"i * b^0 + sum_list (map (\\<lambda>n. b^n) ns) = j * b^m + sum_list (map (\\<lambda>n. b^n) ms)\"\n    obtain x where [simp]: \"sum_list (map ((^) b) ns) = x*b\"\n      using n'(1)\n      by (intro that[of \"sum_list (map (\\<lambda>n. b^(n-1)) ns)\"])\n        (simp add: ac_simps flip: sum_list_const_mult power_Suc cong: map_cong)\n    obtain y where [simp]: \"sum_list (map ((^) b) ms) = y*b\"\n      using order.strict_trans1[OF le0 m'(1)]\n      by (intro that[of \"sum_list (map (\\<lambda>n. b^(n-1)) ms)\"])\n        (simp add: ac_simps flip: sum_list_const_mult power_Suc cong: map_cong)\n    have [simp]: \"m = 0\"\n      using s' n'(2,3)\n      by (cases m, simp_all)\n        (metis Groups.mult_ac(2) Groups.mult_ac(3) Suc_pred div_less mod_div_mult_eq\n          mod_mult_self2 mod_mult_self2_is_0 mult_zero_right nat.simps(3))\n    have \"i = j \\<and> 0 = m\" using s' n'(2,3) m'(2,3)\n      by simp (metis div_less mod_div_mult_eq mod_mult_self1)\n  } note BASE = this\n  {\n    case 0 show ?case by (rule BASE; fact)\n  next\n    case (Suc n m')\n    have \"j = i \\<and> 0 = Suc n\" if \"m' = 0\" using Suc(2-4)\n      by (intro BASE[of ms j ns \"Suc n\" i]) (simp_all add: ac_simps that n(2,3) m(2,3))\n    then obtain m where m' [simp]: \"m' = Suc m\"\n      by (cases m') auto\n    obtain ns' where [simp]: \"ns = map Suc ns'\" \"\\<And>n'. n' \\<in> set ns' \\<Longrightarrow> n < n'\"\n      using Suc(2) less_trans[OF zero_less_Suc Suc(2)]\n      by (intro that[of \"map (\\<lambda>n. n-1) ns\"]; force cong: map_cong)\n    obtain ms' where [simp]: \"ms = map Suc ms'\" \"\\<And>m'. m' \\<in> set ms' \\<Longrightarrow> m < m'\"\n      using Suc(3)[unfolded m'] less_trans[OF zero_less_Suc Suc(3)[unfolded m']]\n      by (intro that[of \"map (\\<lambda>n. n-1) ms\"]; force cong: map_cong)\n    have *: \"b * x = b * y \\<Longrightarrow> x = y\" for x y using n(2) by simp\n    have \"i = j \\<and> n = m\"\n    proof (rule Suc(1)[of \"map (\\<lambda>n. n-1) ns\" \"map (\\<lambda>n. n-1) ms\" m, OF _ _ *], goal_cases)\n      case 3 show ?case using Suc(4) unfolding add_mult_distrib2\n        by (simp add: comp_def ac_simps flip: sum_list_const_mult)\n    qed simp_all\n    then show ?case by simp\n  }\nqed\n\nlemma evalC_inj_on_hbase:\n  \"n \\<in> hbase b \\<Longrightarrow> m \\<in> hbase b \\<Longrightarrow> evalC b n = evalC b m \\<Longrightarrow> n = m\"\nproof (induct n arbitrary: m rule: hbase.induct)\n  case 1\n  then show ?case by (cases m rule: hbase.cases) simp_all\nnext\n  case (2 i n ns m')\n  obtain j m ms where [simp]: \"m' = C (replicate j m @ ms)\" and\n    m: \"j \\<noteq> 0\" \"j < b\" \"m \\<in> hbase b\" \"C ms \\<in> hbase b\" \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> evalC b m < evalC b m'\"\n    using 2(8,1,2,9) by (cases m' rule: hbase.cases) simp_all\n  have \"i = j \\<and> evalC b n = evalC b m\" using 2(1,2,7,9) m(1,2,5)\n    by (intro base_red[of \"map (evalC b) ns\" _ _ b \"map (evalC b) ms\"])\n      (auto simp: comp_def evalC_sum_list sum_list_replicate)\n  then show ?case\n    using 2(4)[OF m(3)] 2(6)[OF m(4)] 2(9) by simp\nqed\n\nsubsection \\<open>Correctness of @{const stepC}\\<close>\n\ntext \\<open>We show that @{term \"stepC c\"} preserves hereditary base @{term \"c + 2 :: nat\"}\n  representations. In order to cover intermediate results produced by @{const stepC}, we extend\n  the hereditary base representation to allow the least significant digit to be equal to @{term b},\n  which essentially means that we may have an extra sibling in front on every level.\\<close>\n\ninductive_set hbase_ext for b where\n  \"n \\<in> hbase b \\<Longrightarrow> n \\<in> hbase_ext b\"\n| \"n \\<in> hbase_ext b \\<Longrightarrow>\n   C m \\<in> hbase b \\<Longrightarrow> (\\<And>m'. m' \\<in> set m \\<Longrightarrow> evalC b n \\<le> evalC b m') \\<Longrightarrow>\n   C (n # m) \\<in> hbase_ext b\"\n\nlemma hbase_ext_hd' [dest]:\n  \"C (n # ns) \\<in> hbase_ext b \\<Longrightarrow> n \\<in> hbase_ext b\"\n  by (cases rule: hbase_ext.cases) (auto intro: hbase_ext.intros(1))\n\nlemma hbase_ext_tl:\n  \"C ns \\<in> hbase_ext b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> C (tl ns) \\<in> hbase b\"\n  by (cases \"C ns\" b rule: hbase_ext.cases; cases ns) (simp_all add: hbase_tl')\n\nlemmas hbase_ext_tl' [dest] = hbase_ext_tl[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_funC:\n  \"c \\<noteq> 0 \\<Longrightarrow> C (n # ns) \\<in> hbase_ext (Suc c) \\<Longrightarrow>\n    C (funC n (Suc c) @ ns) \\<in> hbase_ext (Suc c)\"\nproof (induct n arbitrary: ns rule: funC.induct)\n  case (2 ms)\n  have [simp]: \"evalC (Suc c) (C ms) < evalC (Suc c) m'\" if \"m' \\<in> set ns\" for m'\n    using 2(2)\n  proof (cases rule: hbase_ext.cases)\n    case 1 then show ?thesis using that\n      by (cases rule: hbase.cases, case_tac i) (auto intro: Suc_lessD)\n  qed (auto simp: Suc_le_eq that)\n  show ?case using 2\n    by (auto 0 4 intro: hbase_ext.intros hbase.intros(2) order.strict_implies_order)\nnext\n  case (3 m ms ms')\n  show ?case\n    unfolding funC.simps append_Cons append_Nil\n  proof (rule hbase_ext.intros(2), goal_cases 31 32 33)\n    case (33 m')\n    show ?case using 3(3)\n    proof (cases rule: hbase_ext.cases)\n      case 1 show ?thesis using 1 3(1,2) 33\n        by (cases rule: hbase.cases, case_tac i) (auto intro: less_or_eq_imp_le)\n    qed (insert 33, simp)\n  qed (insert 3, blast+)\nqed auto\n\nlemma stepC_sound:\n  \"n \\<in> hbase_ext (Suc (Suc c)) \\<Longrightarrow> stepC c n \\<in> hbase (Suc (Suc c))\"\nproof (induct c n rule: stepC.induct)\n  case (3 c n ns ms)\n  show ?case using 3(2,1)\n    by (cases rule: hbase_ext.cases; unfold stepC.simps) (auto intro: hbase_funC)\nqed (auto intro: hbase.intros)\n\nsubsection \\<open>Surjectivity of @{const evalC}\\<close>\n\ntext \\<open>Note that the base must be at least @{term \"2 :: nat\"}.\\<close>\n\nlemma evalC_surjective:\n  \"\\<exists>n' \\<in> hbase (Suc (Suc b)). evalC (Suc (Suc b)) n' = n\"\nproof (induct n)\n  case 0 then show ?case by (auto intro: bexI[of _ \"C []\"] hbase.intros)\nnext\n  have [simp]: \"Suc x \\<le> Suc (Suc b)^x\" for x by (induct x) auto\n  case (Suc n)\n  then obtain n' where \"n' \\<in> hbase (Suc (Suc b))\" \"evalC (Suc (Suc b)) n' = n\" by blast\n  then obtain n' j where n': \"Suc n \\<le> j\" \"j = evalC (Suc (Suc b)) n'\" \"n' \\<in> hbase (Suc (Suc b))\"\n    by (intro that[of _ \"C [n']\"])\n      (auto intro!: intro: hbase.intros(1) dest!: hbaseI2[of 1 \"b+2\" n' \"[]\", simplified])\n  then show ?case\n  proof (induct rule: inc_induct)\n    case (step m)\n    obtain n' where \"n' \\<in> hbase (Suc (Suc b))\" \"evalC (Suc (Suc b)) n' = Suc m\"\n      using step(3)[OF step(4,5)] by blast\n    then show ?case using stepC_dec[of n' \"b\"]\n      by (cases n' rule: C2O.cases) (auto intro: stepC_sound hbase_ext.intros(1))\n  qed blast\nqed\n\nsubsection \\<open>Monotonicity of @{const hbase}\\<close>\n\ntext \\<open>Here we show that every hereditary base @{term \"b :: nat\"} number is also a valid hereditary\n  base @{term \"b+1 :: nat\"} number. This is not immediate because we have to show that monotonicity\n  of siblings is preserved.\\<close>\n\nlemma hbase_evalC_mono:\n  assumes \"n \\<in> hbase b\" \"m \\<in> hbase b\" \"evalC b n < evalC b m\"\n  shows \"evalC (Suc b) n < evalC (Suc b) m\"\nproof (cases \"b < 2\")\n  case True show ?thesis using assms(2,3) True by (cases rule: hbase.cases) simp_all\nnext\n  case False\n  then obtain b' where [simp]: \"b = Suc (Suc b')\"\n    by (auto simp: numeral_2_eq_2 not_less_eq dest: less_imp_Suc_add)\n  show ?thesis using assms(3,1,2)\n  proof (induct \"evalC b n\" \"evalC b m\" arbitrary: n m rule: less_Suc_induct)\n    case 1 then show ?case using stepC_sound[of m b', OF hbase_ext.intros(1)]\n      stepC_dec[of m b'] stepC_dec'[of m b'] evalC_inj_on_hbase\n      by (cases m rule: C2O.cases) (fastforce simp: eval_nat_numeral)+\n  next\n    case (2 j) then show ?case\n      using evalC_surjective[of b' j] less_trans by fastforce\n  qed\nqed\n\nlemma hbase_mono:\n  \"n \\<in> hbase b \\<Longrightarrow> n \\<in> hbase (Suc b)\"\n  by (induct n rule: hbase.induct) (auto 0 3 intro: hbase.intros hbase_evalC_mono)\n\nsubsection \\<open>Conversion to and from @{type nat}\\<close>\n\ntext \\<open>We have previously defined @{term \"H2N b = evalC b\"} and @{term \"N2H b\"} as its inverse.\n  So we can use the injectivity and surjectivity of @{term \"evalC b\"} for simplification.\\<close>\n\nlemma N2H_inv:\n  \"n \\<in> hbase b \\<Longrightarrow> N2H b (H2N b n) = n\"\n  using evalC_inj_on_hbase\n  by (auto simp: N2H_def H2N_def[abs_def] inj_on_def intro!: inv_into_f_f)\n\n\n\nlemma N2H_eqI:\n  \"n \\<in> hbase (Suc (Suc b)) \\<Longrightarrow>\n   H2N (Suc (Suc b)) n = m \\<Longrightarrow> N2H (Suc (Suc b)) m = n\"\n  using N2H_inv by blast\n\nlemma N2H_neI:\n  \"n \\<in> hbase (Suc (Suc b)) \\<Longrightarrow>\n   H2N (Suc (Suc b)) n \\<noteq> m \\<Longrightarrow> N2H (Suc (Suc b)) m \\<noteq> n\"\n  using H2N_inv by blast\n\nlemma N2H_0 [simp]:\n  \"N2H (Suc (Suc c)) 0 = C []\"\n  using H2N_def N2H_inv hbase.intros(1) by fastforce\n\nlemma N2H_nz [simp]:\n  \"0 < n \\<Longrightarrow> N2H (Suc (Suc c)) n \\<noteq> C []\"\n  by (metis N2H_0 H2N_inv neq0_conv)\n\n\nsection \\<open>The Goodstein function revisited\\<close>\n\ntext \\<open>We are now ready to prove termination of the Goodstein function @{const goodstein} as well\n  as its relation to @{const goodsteinC} and @{const goodsteinO}.\\<close>\n\nlemma goodstein_aux:\n  \"goodsteinC (Suc c) (N2H (Suc (Suc c)) (Suc n)) =\n    goodsteinC (c+2) (N2H (c+3) (H2N (c+3) (N2H (c+2) (n+1)) - 1))\"\nproof -\n  have [simp]: \"n \\<noteq> C [] \\<Longrightarrow> goodsteinC c n = goodsteinC (c+1) (stepC c n)\" for c n\n    by (induct c n rule: stepC.induct) simp_all\n  have [simp]: \"stepC (Suc c) (N2H (Suc (Suc c)) (Suc n)) \\<in> hbase (Suc (Suc (Suc c)))\"\n    by (metis H2N_def N2H_inv evalC_surjective hbase_ext.intros(1) hbase_mono stepC_sound)\n  show ?thesis\n    using arg_cong[OF stepC_dec[of \"N2H (c+2) (n+1)\" \"c+1\", folded H2N_def], of \"\\<lambda>n. N2H (c+3) (n-1)\"]\n    by (simp add: eval_nat_numeral N2H_inv)\nqed\n\ntermination goodstein\nproof (relation \"measure (\\<lambda>(c, n). goodsteinC c (N2H (c+1) n) - c)\", goal_cases _ 1)\n  case (1 c n)\n  have *: \"goodsteinC c n \\<ge> c\" for c n\n    by (induct c n rule: goodsteinC.induct) simp_all\n  show ?case by (simp add: goodstein_aux eval_nat_numeral) (meson Suc_le_eq diff_less_mono2 lessI *)\nqed simp\n\nlemma goodstein_def':\n  \"c \\<noteq> 0 \\<Longrightarrow> goodstein c n = goodsteinC c (N2H (c+1) n)\"\n  by (induct c n rule: goodstein.induct) (simp_all add: goodstein_aux eval_nat_numeral)\n\nlemma goodstein_impl:\n  \"c \\<noteq> 0 \\<Longrightarrow> goodstein c n = goodsteinO c (C2O (N2H (c+1) n))\"\n  \\<comment> \\<open>but note that @{term N2H} is not executable as currently defined\\<close>\n  using goodstein_def'[unfolded goodsteinC_def'] .\n\nlemma goodstein_16:\n  \"\\<G> 16 = goodsteinO 1 (exp\\<omega> (exp\\<omega> (exp\\<omega> (exp\\<omega> Z))))\"\nproof -\n  have \"N2H (Suc (Suc 0)) 16 = C [C [C [C [C []]]]]\"\n    by (auto simp: H2N_def intro!: N2H_eqI hbase_singletonI hbase.intros(1))\n  then show ?thesis by (simp add: goodstein_impl)\nqed\n\n\nsection \\<open>Translation to $\\lambda$-calculus\\<close>\n\ntext \\<open>We define Church encodings for @{type nat} and @{type Ord}. Note that we are basically in a\n  Hindley-Milner type system, so we cannot use a proper polymorphic type. We can still express\n  Church encodings as folds over values of the original type.\\<close>\n\nabbreviation Z\\<^sub>N where \"Z\\<^sub>N \\<equiv> (\\<lambda>s z. z)\"\nabbreviation S\\<^sub>N where \"S\\<^sub>N \\<equiv> (\\<lambda>n s z. s (n s z))\"\n\nprimrec fold_nat (\"\\<langle>_\\<rangle>\\<^sub>N\") where\n  \"\\<langle>0\\<rangle>\\<^sub>N = Z\\<^sub>N\"\n| \"\\<langle>Suc n\\<rangle>\\<^sub>N = S\\<^sub>N \\<langle>n\\<rangle>\\<^sub>N\"\n\nlemma one\\<^sub>N:\n  \"\\<langle>1\\<rangle>\\<^sub>N = (\\<lambda>x. x)\"\n  by simp\n\nabbreviation Z\\<^sub>O where \"Z\\<^sub>O \\<equiv> (\\<lambda>z s l. z)\"\nabbreviation S\\<^sub>O where \"S\\<^sub>O \\<equiv> (\\<lambda>n z s l. s (n z s l))\"\nabbreviation L\\<^sub>O where \"L\\<^sub>O \\<equiv> (\\<lambda>f z s l. l (\\<lambda>i. f i z s l))\"\n\nprimrec fold_Ord (\"\\<langle>_\\<rangle>\\<^sub>O\") where\n  \"\\<langle>Z\\<rangle>\\<^sub>O = Z\\<^sub>O\"\n| \"\\<langle>S n\\<rangle>\\<^sub>O = S\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\n| \"\\<langle>L f\\<rangle>\\<^sub>O = L\\<^sub>O (\\<lambda>i. \\<langle>f i\\<rangle>\\<^sub>O)\"\n\ntext \\<open>The following abbreviations and lemmas show how to implement the arithmetic functions and\n  the Goodstein function on a Church-encoded @{type Ord} in lambda calculus.\\<close>\n\nabbreviation (input) add\\<^sub>O where\n  \"add\\<^sub>O n m \\<equiv> (\\<lambda>z s l. m (n z s l) s l)\"\n\nlemma add\\<^sub>O:\n  \"\\<langle>addO n m\\<rangle>\\<^sub>O = add\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\n  by (induct m) simp_all\n\nabbreviation (input) mul\\<^sub>O where\n  \"mul\\<^sub>O n m \\<equiv> (\\<lambda>z s l. m z (\\<lambda>m. n m s l) l)\"\n\nlemma mul\\<^sub>O:\n  \"\\<langle>mulO n m\\<rangle>\\<^sub>O = mul\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\n  by (induct m) (simp_all add: add\\<^sub>O)\n\nabbreviation (input) \\<omega>\\<^sub>O where\n  \"\\<omega>\\<^sub>O \\<equiv> (\\<lambda>z s l. l (\\<lambda>n. \\<langle>n\\<rangle>\\<^sub>N s z))\"\n\nlemma \\<omega>\\<^sub>O:\n  \"\\<langle>\\<omega>\\<rangle>\\<^sub>O = \\<omega>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>(S ^^ i) Z\\<rangle>\\<^sub>O z s l = \\<langle>i\\<rangle>\\<^sub>N s z\" for i z s l by (induct i) simp_all\n  show ?thesis by (simp add: \\<omega>_def)\nqed\n\nabbreviation (input) exp\\<omega>\\<^sub>O where\n  \"exp\\<omega>\\<^sub>O n \\<equiv> (\\<lambda>z s l. n s (\\<lambda>x z. l (\\<lambda>n. \\<langle>n\\<rangle>\\<^sub>N x z)) (\\<lambda>f z. l (\\<lambda>n. f n z)) z)\"\n\nlemma exp\\<omega>\\<^sub>O:\n  \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = exp\\<omega>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\n  by (induct n) (simp_all add: mul\\<^sub>O \\<omega>\\<^sub>O)\n\nabbreviation (input) goodstein\\<^sub>O where\n  \"goodstein\\<^sub>O \\<equiv> (\\<lambda>c n. n (\\<lambda>x. x) (\\<lambda>n m. n (m + 1)) (\\<lambda>f m. f (m + 2) m) c)\"\n\nlemma goodstein\\<^sub>O:\n  \"goodsteinO c n = goodstein\\<^sub>O c \\<langle>n\\<rangle>\\<^sub>O\"\n  by (induct n arbitrary: c) simp_all\n\ntext \\<open>Note that modeling Church encodings with folds is still limited. For example, the meaningful\n  expression @{text \"\\<langle>n\\<rangle>\\<^sub>N exp\\<omega>\\<^sub>O Z\\<^sub>O\"} cannot be typed in Isabelle/HOL, as that would require rank-2\n  polymorphism.\\<close>\n\nsubsection \\<open>Alternative: free theorems\\<close>\n\ntext \\<open>The following is essentially the free theorem for Church-encoded @{type Ord} values.\\<close>\n\nlemma freeOrd:\n  assumes \"\\<And>n. h (s n) = s' (h n)\" and \"\\<And>f. h (l f) = l' (\\<lambda>i. h (f i))\"\n  shows \"h (\\<langle>n\\<rangle>\\<^sub>O z s l) = \\<langle>n\\<rangle>\\<^sub>O (h z) s' l'\"\n  by (induct n) (simp_all add: assms)\n\ntext \\<open>Each of the following proofs first states a naive definition of the corresponding function\n  (which is proved correct by induction), from which we then derive the optimized version using\n  the free theorem, by (conditional) rewriting (without induction).\\<close>\n\nlemma add\\<^sub>O':\n  \"\\<langle>addO n m\\<rangle>\\<^sub>O = add\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>addO n m\\<rangle>\\<^sub>O = \\<langle>m\\<rangle>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O S\\<^sub>O L\\<^sub>O\"\n    by (induct m) simp_all\n  show ?thesis\n    by (intro ext) (simp add: freeOrd[where h = \"\\<lambda>n. n _ _ _\"])\nqed\n\nlemma mul\\<^sub>O':\n  \"\\<langle>mulO n m\\<rangle>\\<^sub>O = mul\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>mulO n m\\<rangle>\\<^sub>O = \\<langle>m\\<rangle>\\<^sub>O Z\\<^sub>O (\\<lambda>m. add\\<^sub>O m \\<langle>n\\<rangle>\\<^sub>O) L\\<^sub>O\"\n    by (induct m) (simp_all add: add\\<^sub>O)\n  show ?thesis\n    by (intro ext) (simp add: freeOrd[where h = \"\\<lambda>n. n _ _ _\"])\nqed\n\nlemma exp\\<omega>\\<^sub>O':\n  \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = exp\\<omega>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = \\<langle>n\\<rangle>\\<^sub>O (S\\<^sub>O Z\\<^sub>O) (\\<lambda>m. mul\\<^sub>O m \\<omega>\\<^sub>O) L\\<^sub>O\"\n    by (induct n) (simp_all add: mul\\<^sub>O \\<omega>\\<^sub>O)\n  show ?thesis\n    by (intro ext) (simp add: fun_cong[OF freeOrd[where h = \"\\<lambda>n z. n z _ _\"]])\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Goodstein_Lambda/Goodstein_Lambda.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213718636754, "lm_q2_score": 0.8519528000888386, "lm_q1q2_score": 0.7660089703789761}}
{"text": "(*  Title:      HOL/Analysis/Euclidean_Space.thy\n    Author:     Johannes Hölzl, TU München\n    Author:     Brian Huffman, Portland State University\n*)\n\nsection \\<open>Finite-Dimensional Inner Product Spaces\\<close>\n\ntheory Euclidean_Space\nimports\n  L2_Norm Product_Vector\nbegin\n\nsubsection \\<open>Type class of Euclidean spaces\\<close>\n\nclass euclidean_space = real_inner +\n  fixes Basis :: \"'a set\"\n  assumes nonempty_Basis [simp]: \"Basis \\<noteq> {}\"\n  assumes finite_Basis [simp]: \"finite Basis\"\n  assumes inner_Basis:\n    \"\\<lbrakk>u \\<in> Basis; v \\<in> Basis\\<rbrakk> \\<Longrightarrow> inner u v = (if u = v then 1 else 0)\"\n  assumes euclidean_all_zero_iff:\n    \"(\\<forall>u\\<in>Basis. inner x u = 0) \\<longleftrightarrow> (x = 0)\"\n\nsyntax \"_type_dimension\" :: \"type \\<Rightarrow> nat\"  (\"(1DIM/(1'(_')))\")\ntranslations \"DIM('a)\" \\<rightharpoonup> \"CONST card (CONST Basis :: 'a set)\"\ntyped_print_translation \\<open>\n  [(@{const_syntax card},\n    fn ctxt => fn _ => fn [Const (@{const_syntax Basis}, Type (@{type_name set}, [T]))] =>\n      Syntax.const @{syntax_const \"_type_dimension\"} $ Syntax_Phases.term_of_typ ctxt T)]\n\\<close>\n\nlemma (in euclidean_space) norm_Basis[simp]: \"u \\<in> Basis \\<Longrightarrow> norm u = 1\"\n  unfolding norm_eq_sqrt_inner by (simp add: inner_Basis)\n\nlemma (in euclidean_space) inner_same_Basis[simp]: \"u \\<in> Basis \\<Longrightarrow> inner u u = 1\"\n  by (simp add: inner_Basis)\n\nlemma (in euclidean_space) inner_not_same_Basis: \"u \\<in> Basis \\<Longrightarrow> v \\<in> Basis \\<Longrightarrow> u \\<noteq> v \\<Longrightarrow> inner u v = 0\"\n  by (simp add: inner_Basis)\n\nlemma (in euclidean_space) sgn_Basis: \"u \\<in> Basis \\<Longrightarrow> sgn u = u\"\n  unfolding sgn_div_norm by (simp add: scaleR_one)\n\nlemma (in euclidean_space) Basis_zero [simp]: \"0 \\<notin> Basis\"\nproof\n  assume \"0 \\<in> Basis\" thus \"False\"\n    using inner_Basis [of 0 0] by simp\nqed\n\nlemma (in euclidean_space) nonzero_Basis: \"u \\<in> Basis \\<Longrightarrow> u \\<noteq> 0\"\n  by clarsimp\n\nlemma (in euclidean_space) SOME_Basis: \"(SOME i. i \\<in> Basis) \\<in> Basis\"\n  by (metis ex_in_conv nonempty_Basis someI_ex)\n\nlemma (in euclidean_space) inner_sum_left_Basis[simp]:\n    \"b \\<in> Basis \\<Longrightarrow> inner (\\<Sum>i\\<in>Basis. f i *\\<^sub>R i) b = f b\"\n  by (simp add: inner_sum_left inner_Basis if_distrib comm_monoid_add_class.sum.If_cases)\n\nlemma (in euclidean_space) euclidean_eqI:\n  assumes b: \"\\<And>b. b \\<in> Basis \\<Longrightarrow> inner x b = inner y b\" shows \"x = y\"\nproof -\n  from b have \"\\<forall>b\\<in>Basis. inner (x - y) b = 0\"\n    by (simp add: inner_diff_left)\n  then show \"x = y\"\n    by (simp add: euclidean_all_zero_iff)\nqed\n\nlemma (in euclidean_space) euclidean_eq_iff:\n  \"x = y \\<longleftrightarrow> (\\<forall>b\\<in>Basis. inner x b = inner y b)\"\n  by (auto intro: euclidean_eqI)\n\nlemma (in euclidean_space) euclidean_representation_sum:\n  \"(\\<Sum>i\\<in>Basis. f i *\\<^sub>R i) = b \\<longleftrightarrow> (\\<forall>i\\<in>Basis. f i = inner b i)\"\n  by (subst euclidean_eq_iff) simp\n\nlemma (in euclidean_space) euclidean_representation_sum':\n  \"b = (\\<Sum>i\\<in>Basis. f i *\\<^sub>R i) \\<longleftrightarrow> (\\<forall>i\\<in>Basis. f i = inner b i)\"\n  by (auto simp add: euclidean_representation_sum[symmetric])\n\nlemma (in euclidean_space) euclidean_representation: \"(\\<Sum>b\\<in>Basis. inner x b *\\<^sub>R b) = x\"\n  unfolding euclidean_representation_sum by simp\n\nlemma (in euclidean_space) choice_Basis_iff:\n  fixes P :: \"'a \\<Rightarrow> real \\<Rightarrow> bool\"\n  shows \"(\\<forall>i\\<in>Basis. \\<exists>x. P i x) \\<longleftrightarrow> (\\<exists>x. \\<forall>i\\<in>Basis. P i (inner x i))\"\n  unfolding bchoice_iff\nproof safe\n  fix f assume \"\\<forall>i\\<in>Basis. P i (f i)\"\n  then show \"\\<exists>x. \\<forall>i\\<in>Basis. P i (inner x i)\"\n    by (auto intro!: exI[of _ \"\\<Sum>i\\<in>Basis. f i *\\<^sub>R i\"])\nqed auto\n\nlemma (in euclidean_space) bchoice_Basis_iff:\n  fixes P :: \"'a \\<Rightarrow> real \\<Rightarrow> bool\"\n  shows \"(\\<forall>i\\<in>Basis. \\<exists>x\\<in>A. P i x) \\<longleftrightarrow> (\\<exists>x. \\<forall>i\\<in>Basis. inner x i \\<in> A \\<and> P i (inner x i))\"\nby (simp add: choice_Basis_iff Bex_def)\n\nlemma (in euclidean_space) euclidean_representation_sum_fun:\n    \"(\\<lambda>x. \\<Sum>b\\<in>Basis. inner (f x) b *\\<^sub>R b) = f\"\n  by (rule ext) (simp add: euclidean_representation_sum)\n\nlemma euclidean_isCont:\n  assumes \"\\<And>b. b \\<in> Basis \\<Longrightarrow> isCont (\\<lambda>x. (inner (f x) b) *\\<^sub>R b) x\"\n    shows \"isCont f x\"\n  apply (subst euclidean_representation_sum_fun [symmetric])\n  apply (rule isCont_sum)\n  apply (blast intro: assms)\n  done\n\nlemma DIM_positive [simp]: \"0 < DIM('a::euclidean_space)\"\n  by (simp add: card_gt_0_iff)\n\nlemma DIM_ge_Suc0 [simp]: \"Suc 0 \\<le> card Basis\"\n  by (meson DIM_positive Suc_leI)\n\n\nlemma sum_inner_Basis_scaleR [simp]:\n  fixes f :: \"'a::euclidean_space \\<Rightarrow> 'b::real_vector\"\n  assumes \"b \\<in> Basis\" shows \"(\\<Sum>i\\<in>Basis. (inner i b) *\\<^sub>R f i) = f b\"\n  by (simp add: comm_monoid_add_class.sum.remove [OF finite_Basis assms]\n         assms inner_not_same_Basis comm_monoid_add_class.sum.neutral)\n\nlemma sum_inner_Basis_eq [simp]:\n  assumes \"b \\<in> Basis\" shows \"(\\<Sum>i\\<in>Basis. (inner i b) * f i) = f b\"\n  by (simp add: comm_monoid_add_class.sum.remove [OF finite_Basis assms]\n         assms inner_not_same_Basis comm_monoid_add_class.sum.neutral)\n\nsubsection \\<open>Subclass relationships\\<close>\n\ninstance euclidean_space \\<subseteq> perfect_space\nproof\n  fix x :: 'a show \"\\<not> open {x}\"\n  proof\n    assume \"open {x}\"\n    then obtain e where \"0 < e\" and e: \"\\<forall>y. dist y x < e \\<longrightarrow> y = x\"\n      unfolding open_dist by fast\n    define y where \"y = x + scaleR (e/2) (SOME b. b \\<in> Basis)\"\n    have [simp]: \"(SOME b. b \\<in> Basis) \\<in> Basis\"\n      by (rule someI_ex) (auto simp: ex_in_conv)\n    from \\<open>0 < e\\<close> have \"y \\<noteq> x\"\n      unfolding y_def by (auto intro!: nonzero_Basis)\n    from \\<open>0 < e\\<close> have \"dist y x < e\"\n      unfolding y_def by (simp add: dist_norm)\n    from \\<open>y \\<noteq> x\\<close> and \\<open>dist y x < e\\<close> show \"False\"\n      using e by simp\n  qed\nqed\n\nsubsection \\<open>Class instances\\<close>\n\nsubsubsection \\<open>Type @{typ real}\\<close>\n\ninstantiation real :: euclidean_space\nbegin\n\ndefinition\n  [simp]: \"Basis = {1::real}\"\n\ninstance\n  by standard auto\n\nend\n\nlemma DIM_real[simp]: \"DIM(real) = 1\"\n  by simp\n\nsubsubsection \\<open>Type @{typ complex}\\<close>\n\ninstantiation complex :: euclidean_space\nbegin\n\ndefinition Basis_complex_def: \"Basis = {1, \\<i>}\"\n\ninstance\n  by standard (auto simp add: Basis_complex_def intro: complex_eqI split: if_split_asm)\n\nend\n\nlemma DIM_complex[simp]: \"DIM(complex) = 2\"\n  unfolding Basis_complex_def by simp\n\nsubsubsection \\<open>Type @{typ \"'a \\<times> 'b\"}\\<close>\n\ninstantiation prod :: (euclidean_space, euclidean_space) euclidean_space\nbegin\n\ndefinition\n  \"Basis = (\\<lambda>u. (u, 0)) ` Basis \\<union> (\\<lambda>v. (0, v)) ` Basis\"\n\nlemma sum_Basis_prod_eq:\n  fixes f::\"('a*'b)\\<Rightarrow>('a*'b)\"\n  shows \"sum f Basis = sum (\\<lambda>i. f (i, 0)) Basis + sum (\\<lambda>i. f (0, i)) Basis\"\nproof -\n  have \"inj_on (\\<lambda>u. (u::'a, 0::'b)) Basis\" \"inj_on (\\<lambda>u. (0::'a, u::'b)) Basis\"\n    by (auto intro!: inj_onI Pair_inject)\n  thus ?thesis\n    unfolding Basis_prod_def\n    by (subst sum.union_disjoint) (auto simp: Basis_prod_def sum.reindex)\nqed\n\ninstance proof\n  show \"(Basis :: ('a \\<times> 'b) set) \\<noteq> {}\"\n    unfolding Basis_prod_def by simp\nnext\n  show \"finite (Basis :: ('a \\<times> 'b) set)\"\n    unfolding Basis_prod_def by simp\nnext\n  fix u v :: \"'a \\<times> 'b\"\n  assume \"u \\<in> Basis\" and \"v \\<in> Basis\"\n  thus \"inner u v = (if u = v then 1 else 0)\"\n    unfolding Basis_prod_def inner_prod_def\n    by (auto simp add: inner_Basis split: if_split_asm)\nnext\n  fix x :: \"'a \\<times> 'b\"\n  show \"(\\<forall>u\\<in>Basis. inner x u = 0) \\<longleftrightarrow> x = 0\"\n    unfolding Basis_prod_def ball_Un ball_simps\n    by (simp add: inner_prod_def prod_eq_iff euclidean_all_zero_iff)\nqed\n\nlemma DIM_prod[simp]: \"DIM('a \\<times> 'b) = DIM('a) + DIM('b)\"\n  unfolding Basis_prod_def\n  by (subst card_Un_disjoint) (auto intro!: card_image arg_cong2[where f=\"op +\"] inj_onI)\n\nend\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Analysis/Euclidean_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8872045996818986, "lm_q1q2_score": 0.7660050170512851}}
{"text": "header \"Binomial Heaps\"\n\ntheory BinomialHeap\nimports Main \"~~/src/HOL/Library/Multiset\"\nbegin\n\nlocale BinomialHeapStruc_loc\nbegin\n\nsubsection {* Datatype Definition *}\n\ntext {* Binomial heaps are lists of binomial trees. *}\ndatatype ('e, 'a) BinomialTree = \n  Node (val: 'e) (prio: \"'a::linorder\") (rank: nat) (children: \"('e , 'a) BinomialTree list\")\ntype_synonym ('e, 'a) BinomialQueue_inv = \"('e, 'a::linorder) BinomialTree list\"\n\ntext {* Combine two binomial trees (of rank $r$) to one (of rank $r+1$). *}\nfun  link :: \"('e, 'a::linorder) BinomialTree \\<Rightarrow> ('e, 'a) BinomialTree \\<Rightarrow> \n  ('e, 'a) BinomialTree\" where\n  \"link (Node e1 a1 r1 ts1) (Node e2 a2 r2 ts2) = \n   (if  a1\\<le>a2 \n     then (Node e1 a1 (Suc r1) ((Node e2 a2 r2 ts2)#ts1))\n     else (Node e2 a2 (Suc r2) ((Node e1 a1 r1 ts1)#ts2)))\"\n\n\nsubsubsection \"Abstraction to Multiset\"\ntext {* Return a multiset with all (element, priority) pairs from a queue. *}\nfun tree_to_multiset \n  :: \"('e, 'a::linorder) BinomialTree \\<Rightarrow> ('e \\<times> 'a) multiset\" \nand queue_to_multiset \n  :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> ('e \\<times> 'a) multiset\" where\n  \"tree_to_multiset (Node e a r ts) = {#(e,a)#} + queue_to_multiset ts\" |\n  \"queue_to_multiset [] = {#}\" |\n  \"queue_to_multiset (t#q) = tree_to_multiset t + queue_to_multiset q\" \n\n\nlemma qtmset_append_union[simp]: \"queue_to_multiset (q @ q') = \n  queue_to_multiset q + queue_to_multiset q'\"\n  apply(induct q)\n  apply(simp)\n  apply(simp add: union_ac)\ndone\n\nlemma qtmset_rev[simp]: \"queue_to_multiset (rev q) = queue_to_multiset q\"\n  apply(induct q)\n  apply(simp)\n  apply(simp add: union_ac)\ndone\n\nsubsubsection \"Invariant\"\n\ntext {* We first formulate the invariant for single binomial trees,\n  and then extend the invariant to binomial heaps (lists of binomial trees).\n  The invariant for trees claims that a tree labeled rank $0$ has no children,\n  and a tree labeled rank $r+1$ is the result of a link operation of\n  two rank $r$ trees.\n*}\nfunction tree_invar :: \"('e, 'a::linorder) BinomialTree \\<Rightarrow> bool\" where\n  \"tree_invar (Node e a 0 ts) = (ts = [])\" |\n  \"tree_invar (Node e a (Suc r) ts) = \n  (\\<exists> e1 a1 ts1 e2 a2 ts2. \n    tree_invar (Node e1 a1 r ts1) \\<and> \n    tree_invar (Node e2 a2 r ts2) \\<and> \n    (Node e a (Suc r) ts) = link (Node e1 a1 r ts1) (Node e2 a2 r ts2))\"\nby pat_completeness auto\ntermination\n  apply(relation \"measure (\\<lambda>t. rank t)\")\n  apply auto\ndone\n\ntext {* A queue satisfies the invariant, iff all trees inside the queue satisfy \n  the invariant, and the queue contains only trees of distinct rank and \n  is ordered by rank *}\n\ntext {* First part: All trees of the queue satisfy the tree invariant: *}\ndefinition queue_invar :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> bool\" where\n  \"queue_invar q \\<equiv> (\\<forall>t \\<in> set q. tree_invar t)\"\n\ntext {* Second part: Trees have distinct rank, and are ordered by \n  ascending rank: *}\nfun rank_invar :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> bool\" where\n  \"rank_invar [] = True\" |\n  \"rank_invar [t] = True\" |\n  \"rank_invar (t # t' # bq) = (rank t < rank t' \\<and> rank_invar (t' # bq))\"\n\nlemma queue_invar_simps[simp]:\n  \"queue_invar []\"\n  \"queue_invar (t#q) \\<longleftrightarrow> tree_invar t \\<and> queue_invar q\"\n  \"queue_invar (q@q') \\<longleftrightarrow> queue_invar q \\<and> queue_invar q'\"\n  unfolding queue_invar_def by auto\n\ntext {* Invariant for binomial queues: *}\ndefinition \"invar q == queue_invar q \\<and> rank_invar q\"\n\nlemma mset_link[simp]: \"(tree_to_multiset (link t1 t2)) \n  = (tree_to_multiset t1) + (tree_to_multiset t2)\"\n  by(cases t1, cases t2, auto simp add: union_ac)\n\nlemma link_tree_invar: \n  \"\\<lbrakk>tree_invar t1; tree_invar t2; rank t1 = rank t2\\<rbrakk> \\<Longrightarrow> tree_invar (link t1 t2)\"\n  by (cases t1, cases t2, simp, blast)\n\nlemma invar_children: \n  assumes \"tree_invar ((Node e a r ts)::(('e, 'a::linorder) BinomialTree))\" \n  shows \"queue_invar ts\" using assms\n  unfolding queue_invar_def\nproof(induct r arbitrary: e a ts, simp)\n  case goal1\n  from goal1(2) obtain e1 a1 ts1 e2 a2 ts2 where \n    O: \"tree_invar (Node e1 a1 r ts1)\"  \"tree_invar (Node e2 a2 r ts2)\" \n    \"(Node e a (Suc r) ts) = link (Node e1 a1 r ts1) (Node e2 a2 r ts2)\" \n    by (simp only: tree_invar.simps) blast\n  from goal1(1)[OF O(1)] O(2)\n  have case1: \"queue_invar ((Node e2 a2 r ts2) # ts1)\" \n    unfolding queue_invar_def by simp\n  from goal1(1)[OF O(2)] O(1)\n  have case2: \"queue_invar ((Node e1 a1 r ts1) # ts2)\" \n    unfolding queue_invar_def by simp\n  from O(3) have \"ts = (if a1\\<le>a2 \n    then (Node e2 a2 r ts2) # ts1 \n    else (Node e1 a1 r ts1) # ts2)\" by auto\n  with case1 case2 show ?case unfolding queue_invar_def by simp\nqed\n\nlemma invar_children': \"tree_invar t \\<Longrightarrow> queue_invar (children t)\"\n  by (cases t) (auto simp add: invar_children)\n\n\nlemma rank_link: \"rank t = rank t' \\<Longrightarrow> rank (link t t') = rank t + 1\"\napply (cases t)\napply (cases t')\napply(auto)\ndone\n\nlemma rank_invar_not_empty_hd: \"\\<lbrakk>rank_invar (t # bq); bq \\<noteq> []\\<rbrakk> \\<Longrightarrow> \n  rank t < rank (hd bq)\"\napply(induct bq arbitrary: t)\napply(auto)\ndone\n\nlemma rank_invar_to_set: \"rank_invar (t # bq) \\<Longrightarrow> \n  \\<forall> t' \\<in> set bq. rank t < rank t'\"\napply(induct bq arbitrary: t)\napply(simp)\napply (metis nat_less_le rank_invar.simps(3) set_ConsD xt1(7))\ndone\n\nlemma set_to_rank_invar: \"\\<lbrakk>\\<forall> t' \\<in> set bq. rank t < rank t'; rank_invar bq\\<rbrakk> \n  \\<Longrightarrow>  rank_invar (t # bq)\"\napply(induct bq arbitrary: t)\napply(simp)\nby (metis list.sel(1) hd_in_set list.distinct(1) rank_invar.simps(3))\n\nlemma rank_invar_hd_cons: \n  \"\\<lbrakk>rank_invar bq; rank t < rank (hd bq)\\<rbrakk> \\<Longrightarrow> rank_invar (t # bq)\"\napply(cases bq)\napply(auto)\ndone\n\nlemma rank_invar_cons: \"rank_invar (t # bq) \\<Longrightarrow> rank_invar bq\"\napply(cases bq)\napply(auto)\ndone\n\n\nlemma invar_cons_up: \n  \"\\<lbrakk>invar (t # bq); rank t' < rank t; tree_invar t'\\<rbrakk> \\<Longrightarrow> invar (t' # t # bq)\" \n  unfolding invar_def\n  by (cases bq) simp_all \n\nlemma invar_cons_down: \"invar (t # bq) \\<Longrightarrow> invar bq\" \n  unfolding invar_def\n  by (cases bq) simp_all\n\nlemma invar_app_single: \n  \"\\<lbrakk>invar bq; \\<forall>t \\<in> set bq. rank t < rank t'; tree_invar t'\\<rbrakk> \n   \\<Longrightarrow> invar (bq @ [t'])\" \nproof (induct bq, simp add: invar_def)\n  case goal1\n  from `invar (a # bq)` have \"invar bq\" by (rule invar_cons_down)\n  with goal1 have \"invar (bq @ [t'])\" by simp\n  with goal1 show ?case \n    apply (cases bq) \n    apply (simp_all add: invar_def)\n    done\nqed\n\nsubsubsection \"Heap Ordering\"\nfun heap_ordered :: \"('e, 'a::linorder) BinomialTree \\<Rightarrow> bool\" where\n  \"heap_ordered (Node e a r ts) = (\\<forall>x \\<in> set_of(queue_to_multiset ts). a \\<le> snd x)\"\n\ntext {* The invariant for trees implies heap order. *}\nlemma tree_invar_heap_ordered: \"tree_invar t \\<Longrightarrow> heap_ordered t\"\nproof (cases t)\n  case (goal1 e a nat list) thus ?case\n  proof (induct nat arbitrary: t e a list, simp)\n    case goal1\n    from goal1 obtain t1 e1 a1 ts1 t2 e2 a2 ts2 where \n      O: \"tree_invar t1\"  \"tree_invar t2\" \"t = link t1 t2\" \n      and t1[simp]: \"t1 = (Node e1 a1 nat ts1)\" \n      and t2[simp]: \"t2 = (Node e2 a2 nat ts2)\" \n      by (simp only: tree_invar.simps) blast\n    from O(3) have \"t = (if  a1\\<le>a2 \n      then (Node e1 a1 (Suc nat) (t2 # ts1))\n      else (Node e2 a2 (Suc nat) (t1 # ts2)))\" by simp\n    with goal1(1)[OF O(1) t1] goal1(1)[OF O(2) t2]\n    show ?case by (cases \"a1 \\<le> a2\", auto)\n  qed\nqed\n\nsubsubsection \"Height and Length\"\ntext {*\n  Although complexity of HOL-functions cannot be expressed within \n  HOL, we can express the height and length of a binomial heap.\n  By showing that both, height and length, are logarithmic in the number \n  of contained elements, we give strong evidence that our functions have\n  logarithmic complexity in the number of elements.\n*}\n\ntext {* Height of a tree and queue *}\nfun height_tree :: \"('e, ('a::linorder)) BinomialTree \\<Rightarrow> nat\" and\n    height_queue :: \"('e, ('a::linorder)) BinomialQueue_inv \\<Rightarrow> nat\" \n  where\n  \"height_tree (Node e a r ts) = height_queue ts\" |\n  \"height_queue [] = 0\" |\n  \"height_queue (t # ts) = max (Suc (height_tree t)) (height_queue ts)\"\n\nlemma link_length: \"size (tree_to_multiset (link t1 t2)) = \n  size (tree_to_multiset t1) + size (tree_to_multiset t2)\"\n  apply(cases t1)\n  apply(cases t2)\n  apply simp\ndone\n\nlemma tree_rank_estimate:\n  \"tree_invar (Node e a r ts) \\<Longrightarrow> \n  size (tree_to_multiset (Node e a r ts)) = (2::nat)^r\"\napply(induct r arbitrary: e a ts, simp)\nproof -\n  case goal1\n  from goal1(2) obtain e1 a1 ts1 e2 a2 ts2 where link:\n    \"(Node e a (Suc r) ts) = link (Node e1 a1 r ts1) (Node e2 a2 r ts2)\"\n    and inv1: \"tree_invar (Node e1 a1 r ts1) \"\n    and inv2: \"tree_invar (Node e2 a2 r ts2)\" by simp blast\n  from link_length[of \"(Node e1 a1 r ts1)\" \"(Node e2 a2 r ts2)\"]\n    goal1(1)[OF inv1] goal1(1)[OF inv2] link\n  show ?case by simp\nqed\n\nlemma tree_rank_height:\n  \"tree_invar (Node e a r ts) \\<Longrightarrow> height_tree (Node e a r ts) = r\"\n  apply(induct r arbitrary: e a ts, simp)\n  proof -\n    case goal1\n  from goal1(2) obtain e1 a1 ts1 e2 a2 ts2 where link:\n    \"(Node e a (Suc r) ts) = link (Node e1 a1 r ts1) (Node e2 a2 r ts2)\"\n    and inv1: \"tree_invar (Node e1 a1 r ts1) \"\n    and inv2: \"tree_invar (Node e2 a2 r ts2)\" by simp blast\n  with link goal1(1)[OF inv1] goal1(1)[OF inv2] goal1(2) show ?case\n    by (cases \"a1 \\<le> a2\") (simp_all)\nqed\n\ntext {* A binomial tree of height $h$ contains exactly $2^{h}$ elements *}\ntheorem tree_height_estimate:\n  \"tree_invar t \\<Longrightarrow> size (tree_to_multiset t) = (2::nat)^(height_tree t)\"\n  apply (cases t, simp only:)\n  apply (frule tree_rank_estimate)\n  apply (frule tree_rank_height)\n  apply (simp only: )\n  done\n\n(*lemma size_mset_tree_Node: \"tree_invar (Node e a r ts) \\<Longrightarrow> \n  size (tree_to_multiset (Node e a r ts)) = (2::nat)^r\"\n  apply(induct r arbitrary: e a ts, simp)\nproof -\n  case goal1\n  from goal1(2) obtain e1 a1 ts1 e2 a2 ts2 where link:\n    \"(Node e a (Suc r) ts) = link (Node e1 a1 r ts1) (Node e2 a2 r ts2)\"\n    and inv1: \"tree_invar (Node e1 a1 r ts1) \"\n    and inv2: \"tree_invar (Node e2 a2 r ts2)\" by simp blast\n  from link_length[of \"(Node e1 a1 r ts1)\" \"(Node e2 a2 r ts2)\"]\n    goal1(1)[OF inv1] goal1(1)[OF inv2] link\n  show ?case by simp\nqed*)\n\nlemma size_mset_tree: \"tree_invar t \\<Longrightarrow> \n  size (tree_to_multiset t) = (2::nat)^(rank t)\"\n  apply (cases t)\n  by (simp only: tree_rank_estimate BinomialTree.sel(3)) \n\n\nlemma invar_butlast: \"invar (bq @ [t]) \\<Longrightarrow> invar bq\"\n  unfolding invar_def\n  apply (induct bq) apply simp apply (case_tac bq) \n  by (simp_all)\n\nlemma invar_last_max: \"invar (bq @ [m]) \\<Longrightarrow> \\<forall> t \\<in> set bq. rank t < rank m\"\n  unfolding invar_def\n  apply (induct bq) apply simp apply (case_tac bq) apply simp by simp\n\nlemma invar_length: \"invar bq \\<Longrightarrow> length bq \\<le> Suc (rank (last bq))\"\nproof (induct bq rule: rev_induct)\n  case Nil thus ?case by simp\nnext\n  case (snoc x xs)\n  show ?case proof (cases xs)\n    case Nil thus ?thesis by simp\n  next\n    case (Cons xxs xx)[simp]\n    from snoc.hyps[OF invar_butlast[OF snoc.prems]] have\n      IH: \"length xs \\<le> Suc (rank (last xs))\" .\n    also from invar_last_max[OF snoc.prems] last_in_set[of xs] have\n      \"Suc (rank (last xs)) \\<le> rank (last (xs @ [x]))\"\n      by auto\n    finally show ?thesis by simp\n  qed\nqed\n\nlemma size_queue_listsum: \n  \"size (queue_to_multiset bq) = listsum (map (size \\<circ> tree_to_multiset) bq)\"\n  by (induct bq) simp_all\n\ntext {*\n  A binomial heap of length $l$ contains at least $2^l - 1$ elements. \n*}\ntheorem queue_length_estimate_lower: \n  \"invar bq \\<Longrightarrow> (size (queue_to_multiset bq)) \\<ge> 2^(length bq) - 1\"\nproof (induct bq rule: rev_induct)\n  case Nil thus ?case by simp\nnext\n  case (snoc x xs)\n  from snoc.hyps[OF invar_butlast[OF snoc.prems]]\n  have IH: \"2 ^ length xs \\<le> Suc (size (queue_to_multiset xs))\" by simp\n  have size_q: \n    \"size (queue_to_multiset (xs @ [x])) = \n    size (queue_to_multiset xs) + size (tree_to_multiset x)\" \n    by (simp add: size_queue_listsum)\n  also \n  from snoc.prems have inv_x: \"tree_invar x\" by (simp add: invar_def)\n  hence \"size (tree_to_multiset x) = 2 ^ rank x\" by (simp add: size_mset_tree)\n  finally have \n    eq: \"size (queue_to_multiset (xs @ [x])) = \n         size (queue_to_multiset xs) + (2\\<Colon>nat)^(rank x)\" .\n  from invar_length[OF snoc.prems] have \"length xs \\<le> rank x\" by simp\n  hence snd: \"(2::nat) ^ length xs \\<le> (2::nat) ^ rank x\" by simp\n  have\n    \"(2\\<Colon>nat) ^ length (xs @ [x]) = (2\\<Colon>nat) ^ (length xs) + (2\\<Colon>nat) ^ (length xs)\"\n    by simp\n  with IH have \n    \"2 ^ length (xs @ [x]) \\<le> Suc (size (queue_to_multiset xs)) + 2 ^ length xs\" \n    by simp\n  with snd have \"2 ^ length (xs @ [x]) \\<le> \n    Suc (size (queue_to_multiset xs)) + 2 ^ rank x\" \n    by arith\n  with eq show ?case by simp\nqed\n\nsubsection {* Operations *}\n\nsubsubsection \"Empty\"\nlemma empty_correct[simp]: \n  \"invar Nil\"\n  \"queue_to_multiset Nil = {#}\"\n  by (simp_all add: invar_def)\n  \ntext {* The empty multiset is represented by exactly the empty queue *}\nlemma empty_iff: \"t=Nil \\<longleftrightarrow> queue_to_multiset t = {#}\"\n  apply (cases t)\n  apply auto\n  apply (case_tac a)\n  apply auto\n  done\n\nsubsubsection \"Insert\"\ntext {* Inserts a binomial tree into a binomial queue, such that the queue \n  does not contain two trees of same rank. *}\nfun  ins :: \"('e, 'a::linorder) BinomialTree \\<Rightarrow> ('e, 'a) BinomialQueue_inv \\<Rightarrow> \n  ('e, 'a) BinomialQueue_inv\" where\n  \"ins t [] = [t]\" |\n  \"ins t' (t # bq) = (if (rank t') < (rank t) \n    then t' # t # bq \n    else (if (rank t) < (rank t') \n            then t # (ins t' bq)       \n            else ins (link t' t) bq))\" \n  \ntext {* Inserts an element with priority into the queue. *}\ndefinition insert :: \"'e \\<Rightarrow> 'a::linorder \\<Rightarrow> ('e, 'a) BinomialQueue_inv \\<Rightarrow> \n  ('e, 'a) BinomialQueue_inv\" where\n  \"insert e a bq = ins (Node e a 0 []) bq\"\n\n\n\nlemma insert_mset: \n  assumes \"queue_invar q\" \n  shows \"queue_to_multiset (insert e a q) = \n  queue_to_multiset q + {# (e,a) #}\" using assms\nproof -\n  have inv: \"tree_invar (Node e a 0 [])\" by simp\n  from ins_mset[OF inv assms] show ?thesis by (simp add: union_ac insert_def)\nqed\n\nlemma ins_queue_invar: \"\\<lbrakk>tree_invar t; queue_invar q\\<rbrakk> \\<Longrightarrow> queue_invar (ins t q)\"\nproof (induct q arbitrary: t)\n  case (Cons a q)\n  note iv = Cons.hyps\n  show ?case\n  proof (cases \"rank t = rank a\")\n    case True[simp]\n    from Cons.prems have \n      inv_a: \"tree_invar a\" and inv_q: \"queue_invar q\" \n      by (simp_all)\n    note inv_link = link_tree_invar[OF `tree_invar t` inv_a True]\n    from iv[OF inv_link inv_q] show ?thesis by simp\n  next\n    case False\n    with Cons show ?thesis by auto\n  qed\nqed simp\n\nlemma insert_queue_invar: \n  assumes \"queue_invar q\" \n  shows \"queue_invar (insert e a q)\"\nproof -\n  have inv: \"tree_invar (Node e a 0 [])\" by simp\n  from ins_queue_invar[OF inv assms] show ?thesis by (simp add: insert_def)\nqed\n\nlemma  rank_ins: \"(rank_invar (t # bq) \\<Longrightarrow> \n  (rank (hd (ins t' (t # bq))) \\<ge> rank t) \\<or> \n  (rank (hd (ins t' (t # bq))) \\<ge> rank t'))\"\napply(auto)\napply(induct bq arbitrary: t t')\napply(simp add: rank_link)\nproof -\n  case goal1\n  thus ?case\n    apply(cases \"rank (link t' t) = rank a\")\n    apply(auto simp add: rank_link)\n  proof -\n    case goal1\n    from goal1 and `\\<And> t' t. \\<lbrakk>rank_invar (t # bq); rank t' = rank t\\<rbrakk>\n      \\<Longrightarrow> rank t \\<le> rank (hd (ins (link t' t) bq))`[of a \"(link t' t)\"] \n    show ?case\n      apply(cases \"rank (hd (ins (link (link t' t) a) bq)) = rank a\")\n    proof -\n      case goal1\n      thus ?case by simp\n    next\n      case goal2\n      hence \"rank a \\<le> rank (hd (ins (link (link t' t) a) bq))\" \n        by (simp add: rank_link)\n      with goal2 show ?case by simp\n    qed\n  qed\nqed\n\nlemma rank_ins2: \"rank_invar bq \\<Longrightarrow> \n  rank t \\<le> rank (hd (ins t bq)) \\<or> \n  (rank (hd (ins t bq)) = rank (hd bq) \\<and> bq \\<noteq> [])\"\napply(induct bq arbitrary: t)\napply(auto)\nproof -\n  case goal1\n  hence r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n\n  from goal1 r and goal1(1)[of \"(link t a)\"] show ?case\n    apply(cases bq)\n    apply(auto)\n    done\nqed\n\nlemma rank_invar_ins: \"rank_invar bq \\<Longrightarrow> rank_invar (ins t bq)\"\napply(induct bq arbitrary: t)\napply(simp)\napply(auto)\nproof -\n  case goal1\n  hence inv: \"rank_invar (ins t bq)\" by (cases bq, simp_all)\n  from goal1 have hd: \"bq \\<noteq> [] \\<Longrightarrow> rank a < rank (hd bq)\"  \n    by (cases bq, auto)\n  from goal1 have \"rank t \\<le> rank (hd (ins t bq)) \\<or> \n    (rank (hd (ins t bq)) = rank (hd bq) \\<and> bq \\<noteq> [])\"\n    by (simp add: rank_ins2 rank_invar_cons)\n  with goal1 have \"rank a < rank (hd (ins t bq)) \\<or> \n    (rank (hd (ins t bq)) = rank (hd bq) \\<and> bq \\<noteq> [])\" by auto\n  with goal1 and inv and hd show ?case\n    apply(auto simp add: rank_invar_hd_cons)\n    done\nnext\n  case goal2\n  hence inv: \"rank_invar bq\" by (cases bq, simp_all)\n  with goal2 and goal2(1)[of \"(link t a)\"] show ?case by simp\nqed\n\nlemma rank_invar_insert: \"rank_invar bq \\<Longrightarrow> rank_invar (insert e a bq)\"\n  by (simp add: rank_invar_ins insert_def)\n\nlemma insert_correct: \n  assumes I: \"invar q\"\n  shows \n  \"invar (insert e a q)\"\n  \"queue_to_multiset (insert e a q) = queue_to_multiset q + {# (e,a) #}\"\n  using insert_queue_invar[of q] rank_invar_insert[of q] insert_mset[of q] I\n  unfolding invar_def by auto\n\nsubsubsection \"Meld\"\ntext {* Melds two queues. *}\nfun meld :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> ('e, 'a) BinomialQueue_inv\n  \\<Rightarrow> ('e, 'a) BinomialQueue_inv\" \n  where\n  \"meld [] bq = bq\" |\n  \"meld bq [] = bq\" |\n  \"meld (t1#bq1) (t2#bq2) =\n   (if (rank t1) < (rank t2) \n       then t1 # (meld bq1 (t2 # bq2))\n       else (\n         if (rank t2 < rank t1)\n            then t2 # (meld (t1 # bq1) bq2)\n            else ins (link t1 t2) (meld bq1 bq2)\n       )\n    )\"\n\nlemma meld_queue_invar: \n  \"\\<lbrakk>queue_invar q; queue_invar q'\\<rbrakk> \\<Longrightarrow> queue_invar (meld q q')\"\nproof (induct q q' rule: meld.induct, simp, simp)\n  case goal1 \n  from goal1 show ?case\n  proof (cases \"rank t1 < rank t2\")\n    case goal1\n    from goal1(4) have inv_bq1: \"queue_invar bq1\" by simp\n    from goal1(4) have inv_t1: \"tree_invar t1\" by simp\n    from goal1(1)[OF goal1(6) inv_bq1 goal1(5)] inv_t1 goal1(6)\n    show ?case by simp\n  next\n    case goal2 thus ?case\n    proof(cases \"rank t2 < rank t1\")\n      case goal1\n      from goal1(5) have inv_bq2: \"queue_invar bq2\" by simp\n      from goal1(5) have inv_t2: \"tree_invar t2\" by simp\n      from goal1(2)[OF goal1(6) goal1(7) goal1(4) inv_bq2] inv_t2 goal1(6,7)\n      show ?case by simp\n    next\n      case goal2\n      from goal2(6,7) have eq: \"rank t1 = rank t2\" by simp\n      from goal2(4) have inv_bq1: \"queue_invar bq1\" by simp\n      from goal2(4) have inv_t1: \"tree_invar t1\" by simp\n      from goal2(5) have inv_bq2: \"queue_invar bq2\" by simp\n      from goal2(5) have inv_t2: \"tree_invar t2\" by simp\n      note inv_link = link_tree_invar[OF inv_t1 inv_t2 eq]\n      note inv_meld = goal2(3)[OF goal2(6,7) inv_bq1 inv_bq2]\n      from ins_queue_invar[OF inv_link inv_meld] goal2(6,7)\n      show ?case by simp\n    qed\n  qed\nqed\n\nlemma rank_ins_min: \"rank_invar bq \\<Longrightarrow> \n  rank (hd (ins t bq)) \\<ge> min (rank t) (rank (hd bq))\"\napply(induct bq arbitrary: t)\napply(auto)\nproof -\n  case goal1\n  hence inv: \"rank_invar bq\" by (cases bq, simp_all)\n  from goal1 have r: \"rank (link t a) = rank a + 1\" by (simp add: rank_link)\n  with goal1 and inv and goal1(1)[of \"(link t a)\"] show ?case\n    apply(cases bq)\n    apply(auto)\n    done\nqed\n\nlemma rank_invar_meld_strong: \n  \"\\<lbrakk>rank_invar bq1; rank_invar bq2\\<rbrakk> \\<Longrightarrow> rank_invar (meld bq1 bq2) \\<and> \n  rank (hd (meld bq1 bq2)) \\<ge> min (rank (hd bq1)) (rank (hd bq2))\"\n  apply(induct bq1 bq2 rule: meld.induct)\n  apply(simp, simp)\nproof -\n  case goal1\n  from goal1 have inv1: \"rank_invar bq1\" by (cases bq1, simp_all)\n  from goal1 have inv2: \"rank_invar bq2\" by (cases bq2, simp_all)\n  \n  from inv1 and inv2 and goal1 show ?case\n    apply(auto)\n  proof -\n    let ?t = \"t2\"\n    let ?bq = \"bq2\"\n    let ?meld = \"rank t2 < rank (hd (meld (t1 # bq1) bq2))\"\n    case goal1\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with goal1 have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from goal1 have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with goal1 show ?case by (simp add: rank_invar_hd_cons)\n  next -- analog\n    let ?t = \"t1\"\n    let ?bq = \"bq1\"\n    let ?meld = \"rank t1 < rank (hd (meld bq1 (t2 # bq2)))\"\n    case goal2\n    hence \"?bq \\<noteq> [] \\<Longrightarrow> rank ?t < rank (hd ?bq)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with goal2 have ne: \"?bq \\<noteq> [] \\<Longrightarrow> ?meld\" by simp\n    from goal2 have \"?bq = [] \\<Longrightarrow> ?meld\" by simp\n    with ne have \"?meld\" by (cases \"?bq = []\")\n    with goal2 show ?case by (simp add: rank_invar_hd_cons)\n  next\n    case goal3\n    thus ?case by (simp add: rank_invar_ins)\n  next\n    case goal4 (* Ab hier wirds hässlich *)\n    from goal4 have r: \"rank (link t1 t2) = rank t2 + 1\" \n      by (simp add: rank_link)\n    have m: \"meld bq1 [] = bq1\" by (cases bq1, auto)\n    \n    from inv1 and inv2 and goal4 \n    have mm: \"min (rank (hd bq1)) (rank (hd bq2)) \\<le> rank (hd (meld bq1 bq2))\"\n      by simp\n    from `rank_invar (t1 # bq1)` have \"bq1 \\<noteq> [] \\<Longrightarrow> rank t1 < rank (hd bq1)\" \n      by (simp add: rank_invar_not_empty_hd)\n    with goal4 have r1: \"bq1 \\<noteq> [] \\<Longrightarrow> rank t2 < rank (hd bq1)\" by simp\n    from `rank_invar (t2 # bq2)` \n    have r2: \"bq2 \\<noteq> [] \\<Longrightarrow> rank t2 < rank (hd bq2)\" \n      by (simp add: rank_invar_not_empty_hd)\n    \n    from inv1 r r1 rank_ins_min[of bq1 \"(link t1 t2)\"] \n    have abc1: \"bq1 \\<noteq> [] \\<Longrightarrow> rank t2 \\<le> rank (hd (ins (link t1 t2) bq1))\" \n      by simp\n    from inv2 r r2 rank_ins_min[of bq2 \"(link t1 t2)\"] \n    have abc2: \"bq2 \\<noteq> [] \\<Longrightarrow> rank t2 \\<le> rank (hd (ins (link t1 t2) bq2))\" \n      by simp\n    from r1 r2 mm have \n      \"\\<lbrakk>bq1 \\<noteq> []; bq2 \\<noteq> []\\<rbrakk> \\<Longrightarrow> rank t2 < rank (hd (meld bq1 bq2))\" by simp\n    with `rank_invar (meld bq1 bq2)` \n      r rank_ins_min[of \"meld bq1 bq2\" \"link t1 t2\"] \n    have \"\\<lbrakk>bq1 \\<noteq> []; bq2 \\<noteq> []\\<rbrakk> \\<Longrightarrow> \n      rank t2 < rank (hd (ins (link t1 t2) (meld bq1 bq2)))\" by simp\n    thm rank_ins_min[of \"meld bq1 bq2\" \"link t1 t2\"]\n    with inv1 and inv2 and r m r1 show ?case\n      apply(cases \"bq2 = []\")\n      apply(cases \"bq1 = []\")\n      apply(simp)\n      apply(auto simp add: abc1)\n      apply(cases \"bq1 = []\")\n      apply(simp)\n      apply(auto simp add: abc2)\n      done\n  qed\nqed\n\nlemma rank_invar_meld: \n  \"\\<lbrakk>rank_invar bq1; rank_invar bq2\\<rbrakk> \\<Longrightarrow> rank_invar (meld bq1 bq2)\" \n  by (simp only: rank_invar_meld_strong)\n\nlemma meld_mset: \"\\<lbrakk>queue_invar q; queue_invar q'\\<rbrakk> \\<Longrightarrow> \n  queue_to_multiset (meld q q') = \n  queue_to_multiset q + queue_to_multiset q'\"\nproof(induct q q' rule: meld.induct)\n  case (3 t1 bq1 t2 bq2)\n  note iv=\"3.hyps\"\n  note prems=\"3.prems\"\n  show ?case (* \"rank t1 < rank t2\" *)\n  proof (cases rule: nat_less_cases[of \"rank t1\" \"rank t2\", \n            case_names less eq greater])\n    case less\n    from prems have inv_bq1: \"queue_invar bq1\" by simp\n    from iv(1)[OF less inv_bq1 prems(2)] less\n    show ?thesis by (simp add: union_ac)\n  next\n    case greater with prems iv show ?thesis\n      by (auto simp add: union_ac)\n  next\n    case eq[simp]\n    from prems have \n      inv_bq1: \"queue_invar bq1\" and\n      inv_t1: \"tree_invar t1\" and\n      inv_bq2: \"queue_invar bq2\" and\n      inv_t2: \"tree_invar t2\" by simp_all\n    note inv_link = link_tree_invar[OF inv_t1 inv_t2 eq]\n    note inv_meld = meld_queue_invar[OF inv_bq1 inv_bq2]\n    note mset_meld = iv(3)[OF _ _ inv_bq1 inv_bq2, simplified]\n    note mset_link = mset_link[of t1 t2]\n    from ins_mset[OF inv_link inv_meld] mset_meld mset_link\n    show ?thesis by (simp add: union_ac)\n  qed\nqed simp_all\n\nlemma meld_correct:\n  assumes \"invar q\" \"invar q'\" \n  shows \n  \"invar (meld q q')\"\n  \"queue_to_multiset (meld q q') = queue_to_multiset q + queue_to_multiset q'\"\n  using assms\n  unfolding invar_def\n  by (simp_all add: meld_queue_invar rank_invar_meld meld_mset)\n\nsubsubsection \"Find Minimal Element\"\ntext {* Finds the tree containing the minimal element. *}\nfun getMinTree :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> \n  ('e, 'a) BinomialTree\" where\n  \"getMinTree [t] = t\" |\n  \"getMinTree (t#bq) = (if prio t \\<le> prio (getMinTree bq) \n     then t else (getMinTree bq))\" \n\nlemma mintree_exists: \"(bq \\<noteq> []) = (getMinTree bq \\<in> set bq)\"\nproof (induct bq, simp)\n   case goal1 thus ?case by (cases bq) simp_all\nqed\n\nlemma treehead_in_multiset: \n  \"t \\<in> set bq \\<Longrightarrow> (val t, prio t) \\<in># queue_to_multiset bq\"\n  by (induct bq, simp, cases t, auto) \n\nlemma heap_ordered_single: \n\"heap_ordered t = (\\<forall>x \\<in> set_of (tree_to_multiset t). prio t \\<le> snd x)\"\n  by (cases t) auto\n\nlemma getMinTree_cons: \n  \"prio (getMinTree (y # x # xs)) \\<le> prio (getMinTree (x # xs))\" \n  by (induct xs rule: getMinTree.induct) simp_all \n\nlemma getMinTree_min_tree:\n  \"t \\<in> set bq  \\<Longrightarrow> prio (getMinTree bq) \\<le> prio t\"\n  apply(induct bq arbitrary: t rule: getMinTree.induct) \n  apply simp   \n  defer\n  apply simp\nproof -\n  case goal1 thus ?case\n    apply (cases \"ta = t\")\n    apply auto[1] \n    apply (metis getMinTree_cons goal1(1) goal1(3) set_ConsD xt1(6))\n    done\nqed\n\nlemma getMinTree_min_prio:\n  \"\\<lbrakk>queue_invar bq; y \\<in> set_of (queue_to_multiset bq)\\<rbrakk>\n  \\<Longrightarrow> prio (getMinTree bq) \\<le> snd y\"\nproof -\n  case goal1\n  hence \"bq \\<noteq> []\" by (cases bq) simp_all\n  with goal1 have \"\\<exists> t \\<in> set bq. (y \\<in> set_of ((tree_to_multiset t)))\"\n    apply(induct bq)\n    apply simp\n  proof -\n    case goal1 thus ?case\n      apply(cases \"y \\<in> set_of (tree_to_multiset a)\") \n      apply simp\n      apply(cases bq)\n      apply simp_all\n      done\n  qed\n  from this obtain t where O: \n    \"t \\<in> set bq\"\n    \"y \\<in> set_of (tree_to_multiset t)\" by blast\n  obtain e a r ts where [simp]: \"t = (Node e a r ts)\" by (cases t) blast\n  from O goal1(1) have inv: \"tree_invar t\" by (simp add: queue_invar_def)\n  from tree_invar_heap_ordered[OF inv] heap_ordered.simps[of e a r ts] O\n  have \"prio t \\<le> snd y\" by auto\n  with getMinTree_min_tree[OF O(1)] show ?case by simp\nqed\n\ntext {* Finds the minimal Element in the queue. *}\ndefinition findMin :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> ('e \\<times> 'a)\" where\n  \"findMin bq = (let min = getMinTree bq in (val min, prio min))\"\n\nlemma findMin_correct:\n  assumes I: \"invar q\"\n  assumes NE: \"q \\<noteq> Nil\"\n  shows \n  \"findMin q \\<in># queue_to_multiset q\"\n  \"\\<forall>y\\<in>set_of (queue_to_multiset q). snd (findMin q) \\<le> snd y\"\nproof -\n  from NE have \"getMinTree q \\<in> set q\" by (simp only: mintree_exists)\n  thus \"findMin q \\<in># queue_to_multiset q\" \n    by (simp add: treehead_in_multiset Let_def findMin_def)\n  show \"\\<forall>y\\<in>set_of (queue_to_multiset q). snd (findMin q) \\<le> snd y\"\n    using I[unfolded invar_def]\n    by (auto simp add: getMinTree_min_prio Let_def findMin_def)\nqed  \n\nsubsubsection \"Delete Minimal Element\"\n\ntext {* Removes the first tree, which has the priority $a$ within his root. *}\nfun remove1Prio :: \"'a \\<Rightarrow> ('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow>\n  ('e, 'a) BinomialQueue_inv\" where\n  \"remove1Prio a [] = []\" |\n  \"remove1Prio a (t#bq) = \n  (if (prio t) = a then bq else t # (remove1Prio a bq))\"\n\ntext {* Returns the queue without the minimal element. *}\ndefinition deleteMin :: \"('e, 'a::linorder) BinomialQueue_inv \\<Rightarrow> \n  ('e, 'a) BinomialQueue_inv\" where\n  \"deleteMin bq \\<equiv> (let min = getMinTree bq in \n                    meld (rev (children min)) \n                         (remove1Prio (prio min) bq))\"\n\nlemma queue_invar_rev: \"queue_invar q \\<Longrightarrow> queue_invar (rev q)\"\n  by (simp add: queue_invar_def)\n\nlemma queue_invar_remove1: \"queue_invar q \\<Longrightarrow> queue_invar (remove1 t q)\" \n  by (auto simp add: queue_invar_def)\n\nlemma qtm_in_set_subset: \"t \\<in> set q \\<Longrightarrow> \n  tree_to_multiset t \\<le> queue_to_multiset q\"\nproof(induct q, simp)\n  case goal1 thus ?case\n  proof(cases \"t = a\", simp)\n    case goal1\n    hence t_in_q: \"t \\<in> set q\" by simp\n    have \"queue_to_multiset q \\<le> queue_to_multiset (a # q)\"\n      by simp\n    from order_trans[OF goal1(1)[OF t_in_q] this] show ?case .\n  qed\nqed\n  \n\n\nlemma remove1Prio_remove1[simp]: \n  \"remove1Prio (prio (getMinTree bq)) bq = remove1 (getMinTree bq) bq\"\nproof (induct bq)\n  case Nil thus ?case by simp\nnext\n  case (Cons t bq) \n  note iv = Cons\n  thus ?case\n  proof (cases \"t = getMinTree (t # bq)\")\n    case True\n    with iv show ?thesis by simp\n  next\n    case False\n    hence ne: \"bq \\<noteq> []\" by auto\n    with False have down: \"getMinTree (t # bq) = getMinTree bq\" \n      by (induct bq rule: getMinTree.induct) auto\n    from ne False have \"prio t \\<noteq> prio (getMinTree bq)\" \n      by (induct bq rule: getMinTree.induct) auto\n    with down iv False ne show ?thesis by simp \n  qed\nqed\n    \nlemma deleteMin_queue_invar: \n  assumes INV: \"queue_invar q\" \n  assumes NE: \"q \\<noteq> Nil\"\n  shows \"queue_invar (deleteMin q)\"\n  using assms\nproof (cases q, simp)\n  case goal1\n  from goal1(3) have q_ne: \"q \\<noteq> []\" by simp\n  with mintree_exists[of q] goal1(1) \n  have inv_min: \"tree_invar (getMinTree q)\" by (simp add: queue_invar_def)\n  note inv_children = invar_children'[OF inv_min]\n  note inv_rev = queue_invar_rev[OF inv_children]\n  note inv_rem = queue_invar_remove1[OF goal1(1), of \"getMinTree q\"]\n  from meld_queue_invar[OF inv_rev inv_rem] show ?case \n    by (simp add: deleteMin_def Let_def)\nqed\n\nlemma children_rank_less: \n  \"tree_invar t \\<Longrightarrow> \\<forall>t' \\<in> set (children t). rank t' < rank t\"\nproof (cases t)\n  case (goal1 e a nat list) thus ?case\n  proof (induct nat arbitrary: t e a list, simp) \n    case goal1\n    from goal1 obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1) \\<and> tree_invar (Node e2 a2 nat ts2)\n      \\<and> t = link (Node e1 a1 nat ts1) (Node e2 a2 nat ts2)\" \n      by (simp only: tree_invar.simps) blast\n    hence ch_id: \"children t = \n      (if a1 \\<le> a2 then (Node e2 a2 nat ts2)#ts1 \n       else (Node e1 a1 nat ts1)#ts2)\" by simp \n    from O goal1(1)[of \"Node e1 a1 nat ts1\" \"e1\" \"a1\" \"ts1\"] \n    have  p1: \"\\<forall>t'\\<in>set ((Node e2 a2 nat ts2) # ts1). rank t' < Suc nat\" by auto\n    from O goal1(1)[of \"Node e2 a2 nat ts2\" \"e2\" \"a2\" \"ts2\"] \n    have p2: \"\\<forall>t'\\<in>set ((Node e1 a1 nat ts1) # ts2). rank t' < Suc nat\" by auto\n    from goal1(3) p1 p2 ch_id show ?case by simp\n  qed\nqed\n\nlemma strong_rev_children: \"tree_invar t \\<Longrightarrow> invar (rev (children t))\"\n  unfolding invar_def\nproof (cases t)\n  case (goal1 e a nat list) thus ?case\n  proof (induct \"nat\" arbitrary: t e a list, simp)\n    case goal1\n    from goal1 obtain e1 a1 ts1 e2 a2 ts2 where \n      O: \"tree_invar (Node e1 a1 nat ts1) \\<and> tree_invar (Node e2 a2 nat ts2)\n      \\<and> t = link (Node e1 a1 nat ts1) (Node e2 a2 nat ts2)\" \n      by (simp only: tree_invar.simps) blast\n    hence ch_id: \"children t = \n      (if a1 \\<le> a2 then (Node e2 a2 nat ts2)#ts1 \n       else (Node e1 a1 nat ts1)#ts2)\" by simp \n    from O goal1(1)[of \"Node e1 a1 nat ts1\" \"e1\" \"a1\" \"ts1\"] have \n      rev_ts1: \"invar (rev ts1)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e1 a1 nat ts1\"] have  \n      \"\\<forall>t\\<in>set (rev ts1). rank t < rank (Node e2 a2 nat ts2)\" by simp\n    with O rev_ts1 invar_app_single[of \"rev ts1\" \"Node e2 a2 nat ts2\"] \n    have p1: \"invar (rev ((Node e2 a2 nat ts2) # ts1))\" by simp \n    from O goal1(1)[of \"Node e2 a2 nat ts2\" \"e2\" \"a2\" \"ts2\"] have \n      rev_ts2: \"invar (rev ts2)\" by (simp add: invar_def)\n    from O children_rank_less[of \"Node e2 a2 nat ts2\"] have  \n      \"\\<forall>t\\<in>set (rev ts2). rank t < rank (Node e1 a1 nat ts1)\" by simp\n    with O rev_ts2 invar_app_single[of \"rev ts2\" \"Node e1 a1 nat ts1\"] \n    have p2: \"invar (rev ((Node e1 a1 nat ts1) # ts2))\" by simp \n    from p1 p2 ch_id show ?case by (simp add: invar_def)\n  qed\nqed\n\nlemma first_less: \"rank_invar (t # bq) \\<Longrightarrow> \\<forall>t' \\<in> set bq. rank t < rank t'\" \n  apply(induct bq arbitrary: t) \n  apply (simp)\n  apply (metis order_le_less rank_invar.simps(3) set_ConsD xt1(7)) \n  done\n\nlemma strong_remove1: \"invar bq \\<Longrightarrow> invar (remove1 t bq)\" \nproof (induct bq arbitrary: t, simp) \n  case goal1 \n  thus ?case \n    apply(cases \"t=a\")\n  proof -\n    case goal1\n    from goal1(2) have \"invar bq\" by (rule invar_cons_down)\n    with goal1(3) show ?case by simp\n  next\n    case goal2\n    from goal2(2) have \"invar bq\" by (rule invar_cons_down)\n    with goal2(1)[of \"t\"] have si1: \"invar (remove1 t bq)\" .\n    from goal2(3) have \n      \"invar (remove1 t (a # bq)) = invar (a # (remove1 t bq))\" \n      by simp\n    with si1 goal2(2) show ?case\n    proof (cases \"remove1 t bq\", simp add: invar_def) \n      fix aa list\n      assume ass: \"invar (remove1 t bq)\" \"invar (a # bq)\"\n        \"invar (remove1 t (a # bq)) = invar (a # remove1 t bq)\" \n        \"remove1 t bq = aa # list\"\n      from ass(2) have \"tree_invar a\" by (simp add: invar_def)\n      from ass(2) first_less[of \"a\" \"bq\"] have \n        \"\\<forall>t \\<in> set (remove1 t bq). rank a < rank t\"\n        by (metis notin_set_remove1 invar_def) \n      with ass(4) have \"rank a < rank aa\" by simp\n      with ass invar_cons_up[of \"aa\" \"list\" \"a\"] show ?case \n        by (simp add: invar_def)\n    qed\n  qed\nqed  \n\ntheorem deleteMin_invar: \n  \"\\<lbrakk>invar bq; bq \\<noteq> []\\<rbrakk> \\<Longrightarrow> invar (deleteMin bq)\" \nproof -\n  case goal1\n  have eq: \"invar (deleteMin bq) = \n    invar (meld (rev (children (getMinTree bq))) (remove1 (getMinTree bq) bq))\"\n    by (simp add: deleteMin_def Let_def)\n  from goal1 mintree_exists[of \"bq\"] have ti: \"tree_invar (getMinTree bq)\" \n    by (simp add: invar_def Let_def queue_invar_def)\n  with strong_rev_children[of \"getMinTree bq\"] have \n    m1: \"invar (rev (children (getMinTree bq)))\" .\n  from strong_remove1[of \"bq\" \"getMinTree bq\"] goal1(1) have \n    m2: \"invar (remove1 (getMinTree bq) bq)\" .\n  from meld_correct(1)[of \"rev (children (getMinTree bq))\" \n    \"remove1 (getMinTree bq) bq\"] m1 m2\n  have \n    \"invar (meld (rev (children (getMinTree bq))) (remove1 (getMinTree bq) bq))\" .\n  with eq show ?case ..\nqed\n\nlemma children_mset: \"queue_to_multiset (children t) = \n  tree_to_multiset t - {# (val t, prio t) #}\"\nproof (cases t)\n  case (goal1 e a nat list)\n  thus ?case by (induct list, simp_all)\nqed\n\nlemma deleteMin_mset: \"\\<lbrakk>queue_invar q; q \\<noteq> Nil\\<rbrakk> \\<Longrightarrow> \n  queue_to_multiset (deleteMin q) = \n  queue_to_multiset q - {# (findMin q) #}\"\nproof -\n  case goal1\n  with mintree_exists[of \"q\"] have min_in_q: \"getMinTree q \\<in> set q\" by auto\n  with goal1(1) have inv_min: \"tree_invar (getMinTree q)\" \n    by (simp add: queue_invar_def)\n  from goal1(2) have q_ne: \"q \\<noteq> []\" .\n  note inv_children = invar_children'[OF inv_min]\n  note inv_rev = queue_invar_rev[OF inv_children]\n  note inv_rem = queue_invar_remove1[OF goal1(1), of \"getMinTree q\"]\n  note m_meld = meld_mset[OF inv_rev inv_rem]\n  note m_rem = remove1_mset[OF min_in_q]\n  note m_rev = qtmset_rev[of \"children (getMinTree q)\"]\n  note m_children = children_mset[of \"getMinTree q\"]\n  note min_subset_q = qtm_in_set_subset[OF min_in_q]\n  let ?Q = \"queue_to_multiset q\"\n  let ?MT = \"tree_to_multiset (getMinTree q)\"\n  from q_ne have head_subset_min: \n    \"{# (val (getMinTree q), prio (getMinTree q)) #} \\<le> ?MT\"\n    by(cases \"getMinTree q\") simp\n  let ?Q = \"queue_to_multiset q\"\n  let ?MT = \"tree_to_multiset (getMinTree q)\"\n  from m_meld m_rem m_rev m_children \n    multiset_diff_union_assoc[OF head_subset_min, of \"?Q - ?MT\"]\n    mset_le_multiset_union_diff_commute[OF min_subset_q, of \"?MT\"]\n  show ?case by (simp add: deleteMin_def union_ac Let_def findMin_def)\nqed\n\nlemma deleteMin_correct:\n  assumes INV: \"invar q\" \n  assumes NE: \"q \\<noteq> Nil\"\n  shows \n  \"invar (deleteMin q)\"\n  \"queue_to_multiset (deleteMin q) = queue_to_multiset q - {# (findMin q) #}\"\n  using deleteMin_invar deleteMin_mset INV NE\n  unfolding invar_def\n  by auto\n\nend\n\ninterpretation BinomialHeapStruc: BinomialHeapStruc_loc .\n\n\nsubsection \"Hiding the Invariant\"\nsubsubsection \"Datatype\"\ntypedef ('e, 'a) BinomialHeap =\n  \"{q :: ('e,'a::linorder) BinomialHeapStruc.BinomialQueue_inv. BinomialHeapStruc.invar q }\"\n  apply (rule_tac x=\"Nil\" in exI)\n  apply auto\n  done\n\nlemma Rep_BinomialHeap_invar[simp]: \n  \"BinomialHeapStruc.invar (Rep_BinomialHeap x)\"\n  using Rep_BinomialHeap\n  by (auto)\n\n\n\nlemma [simp, code abstype]: \"Abs_BinomialHeap (Rep_BinomialHeap q) = q\"\n  by (rule Rep_BinomialHeap_inverse)\n\nlocale BinomialHeap_loc\nbegin\n  subsubsection \"Operations\"\n\n  definition [code]: \n    \"to_mset t == BinomialHeapStruc.queue_to_multiset (Rep_BinomialHeap t)\"\n\n  definition empty where \"empty == Abs_BinomialHeap Nil\" \n  lemma [code abstract, simp]: \"Rep_BinomialHeap empty = []\"\n    by (unfold empty_def) simp\n\n\n  definition [code]: \"isEmpty q == Rep_BinomialHeap q = Nil\"\n  lemma empty_rep: \"q=empty \\<longleftrightarrow> Rep_BinomialHeap q = Nil\"\n    apply (auto simp add: empty_def)\n    apply (metis Rep_BinomialHeap_inverse)\n    done\n\n  lemma isEmpty_correct: \"isEmpty q \\<longleftrightarrow> q=empty\"\n    by (simp add: empty_rep isEmpty_def)\n  \n  definition \n    insert \n    :: \"'e  \\<Rightarrow> ('a::linorder) \\<Rightarrow> ('e,'a) BinomialHeap \\<Rightarrow> ('e,'a) BinomialHeap\"\n    where \"insert e a q == \n            Abs_BinomialHeap (BinomialHeapStruc.insert e a (Rep_BinomialHeap q))\"\n  lemma [code abstract]: \n    \"Rep_BinomialHeap (insert e a q) \n    = BinomialHeapStruc.insert e a (Rep_BinomialHeap q)\"\n    by (simp add: insert_def BinomialHeapStruc.insert_correct)\n\n  definition [code]: \"findMin q == BinomialHeapStruc.findMin (Rep_BinomialHeap q)\"\n  \n  definition \"deleteMin q == \n    if q=empty then empty \n    else Abs_BinomialHeap (BinomialHeapStruc.deleteMin (Rep_BinomialHeap q))\"\n\n  text {*\n    In this lemma, we do not use equality, but case-distinction for checking \n    non-emptyness. That prevents the code generator from introducing\n    an equality-class parameter for the entry type @{text 'a}.\n    *}\n  lemma [code abstract]: \"Rep_BinomialHeap (deleteMin q) =\n    (case (Rep_BinomialHeap q) of [] \\<Rightarrow> [] |\n     _ \\<Rightarrow> BinomialHeapStruc.deleteMin (Rep_BinomialHeap q))\"\n  proof (cases \"Rep_BinomialHeap q\")\n    case Nil \n    show ?thesis\n      apply (simp add: Nil)\n      apply (auto simp add: deleteMin_def BinomialHeapStruc.deleteMin_correct \n      BinomialHeapStruc.empty_iff empty_rep Nil)\n      done\n  next\n    case (Cons a b)\n    hence NE: \"Rep_BinomialHeap q \\<noteq> []\" by auto\n    show ?thesis\n      apply (simp add: Cons)\n      apply (fold Cons)\n      using NE\n      by (auto simp add: deleteMin_def BinomialHeapStruc.deleteMin_correct \n        BinomialHeapStruc.empty_iff empty_rep)\n  qed\n\n  (*\n  lemma [code abstract]: \"Rep_BinomialHeap (deleteMin q) =\n    (if (Rep_BinomialHeap q = []) then [] \n     else BinomialHeapStruc.deleteMin (Rep_BinomialHeap q))\"\n    by (auto simp add: deleteMin_def BinomialHeapStruc.deleteMin_correct \n      BinomialHeapStruc.empty_iff empty_rep)\n      *)\n\n  definition \"meld q1 q2 == \n    Abs_BinomialHeap (BinomialHeapStruc.meld (Rep_BinomialHeap q1) \n                                             (Rep_BinomialHeap q2))\"\n  lemma [code abstract]:\n    \"Rep_BinomialHeap (meld q1 q2) \n    = BinomialHeapStruc.meld (Rep_BinomialHeap q1) (Rep_BinomialHeap q2)\"\n    by (simp add: meld_def BinomialHeapStruc.meld_correct)\n\n\n  subsubsection \"Correctness\"\n\n  lemma empty_correct: \"to_mset q = {#} \\<longleftrightarrow> q=empty\"\n    by (simp add: to_mset_def BinomialHeapStruc.empty_iff empty_rep)\n\n  lemma to_mset_of_empty[simp]: \"to_mset empty = {#}\"\n    by (simp add: empty_correct)\n\n  lemma insert_correct: \"to_mset (insert e a q) = to_mset q + {#(e,a)#}\"\n    apply (unfold insert_def to_mset_def)\n    apply (simp add: BinomialHeapStruc.insert_correct)\n    done\n\n  lemma findMin_correct: \n    assumes \"q\\<noteq>empty\"\n    shows \n    \"findMin q \\<in># to_mset q\"\n    \"\\<forall>y\\<in>set_of (to_mset q). snd (findMin q) \\<le> snd y\"\n    using assms\n    apply (unfold findMin_def to_mset_def)\n    apply (simp_all add: empty_rep BinomialHeapStruc.findMin_correct)\n    done\n\n  lemma deleteMin_correct:\n    assumes \"q\\<noteq>empty\"\n    shows \"to_mset (deleteMin q) = to_mset q - {# findMin q #}\"\n    using assms\n    apply (unfold findMin_def deleteMin_def to_mset_def)\n    apply (simp_all add: empty_rep BinomialHeapStruc.deleteMin_correct)\n    done\n\n  lemma meld_correct:\n    shows \"to_mset (meld q q') = to_mset q + to_mset q'\"\n    apply (unfold to_mset_def meld_def)\n    apply (simp_all add: BinomialHeapStruc.meld_correct)\n    done\n\n  text {* Correctness lemmas to be used with simplifier *}\n  lemmas correct = empty_correct deleteMin_correct meld_correct\n\n  end\n  interpretation BinomialHeap: BinomialHeap_loc .\n  \n\n  \nsubsection \"Documentation\"\n\n(*#DOC\n  fun [no_spec] BinomialHeap.to_mset\n    Abstraction to multiset.\n\n  fun BinomialHeap.empty\n    The empty heap. ($O(1)$)\n\n  fun BinomialHeap.isEmpty\n    Checks whether heap is empty. Mainly used to work around \n    code-generation issues. ($O(1)$)\n\n  fun BinomialHeap.insert\n    Inserts element ($O(\\log(n))$)\n\n  fun BinomialHeap.findMin\n    Returns a minimal element ($O(\\log(n))$)\n\n  fun BinomialHeap.deleteMin\n    Deletes {\\em the} element that is returned by {\\em find\\_min}\n\n  fun [long_type] BinomialHeap.meld\n    Melds two heaps ($O(\\log(n+m))$)\n\n*)\n\n\ntext {*\n    \\underline{@{term_type \"BinomialHeap.to_mset\"}}\\\\\n        Abstraction to multiset.\\\\\n\n\n    \\underline{@{term_type \"BinomialHeap.empty\"}}\\\\\n        The empty heap. ($O(1)$)\\\\\n    {\\bf Spec} @{text \"BinomialHeap.empty_correct\"}:\n    @{thm [display] BinomialHeap.empty_correct[no_vars]}\n\n\n    \\underline{@{term_type \"BinomialHeap.isEmpty\"}}\\\\\n        Checks whether heap is empty. Mainly used to work around\n    code-generation issues. ($O(1)$)\\\\\n    {\\bf Spec} @{text \"BinomialHeap.isEmpty_correct\"}:\n    @{thm [display] BinomialHeap.isEmpty_correct[no_vars]}\n\n\n    \\underline{@{term_type \"BinomialHeap.insert\"}}\\\\\n        Inserts element ($O(\\log(n))$)\\\\\n    {\\bf Spec} @{text \"BinomialHeap.insert_correct\"}:\n    @{thm [display] BinomialHeap.insert_correct[no_vars]}\n\n\n    \\underline{@{term_type \"BinomialHeap.findMin\"}}\\\\\n        Returns a minimal element ($O(\\log(n))$)\\\\\n    {\\bf Spec} @{text \"BinomialHeap.findMin_correct\"}:\n    @{thm [display] BinomialHeap.findMin_correct[no_vars]}\n\n\n    \\underline{@{term_type \"BinomialHeap.deleteMin\"}}\\\\\n        Deletes {\\em the} element that is returned by {\\em find\\_min}\\\\\n    {\\bf Spec} @{text \"BinomialHeap.deleteMin_correct\"}:\n    @{thm [display] BinomialHeap.deleteMin_correct[no_vars]}\n\n\n    \\underline{@{term \"BinomialHeap.meld\"}}\n    @{term_type [display] \"BinomialHeap.meld\"}\n        Melds two heaps ($O(\\log(n+m))$)\\\\\n    {\\bf Spec} @{text \"BinomialHeap.meld_correct\"}:\n    @{thm [display] BinomialHeap.meld_correct[no_vars]}\n\n*}\n\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Binomial-Heaps/BinomialHeap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070133672954, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.765983055050441}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\nsubsection \"Arithmetic Expressions\"\n\ntheory AExp imports Main begin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw\\<open>\\snip{AExpaexpdef}{2}{1}{%\\<close>\ndatatype aexp = N int | V vname | Plus aexp aexp | Times aexp aexp\ntext_raw\\<open>}%endsnip\\<close>\n\ntext_raw\\<open>\\snip{AExpavaldef}{1}{2}{%\\<close>\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\" |\n\"aval (Times a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s * aval a\\<^sub>2 s\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>\\noindent\n  We can now write a series of updates to the function \\<open>\\<lambda>x. 0\\<close> compactly:\n\\<close>\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext\\<open>Note that this \\<open><\\<dots>>\\<close> syntax works for any function space\n\\<open>\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\\<close> where \\<open>\\<tau>\\<^sub>2\\<close> has a \\<open>0\\<close>.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Evaluate constant subsexpressions:\\<close>\n\ntext_raw\\<open>\\snip{AExpasimpconstdef}{0}{2}{%\\<close>\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\" |\n\"asimp_const (Times a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1*n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Times b\\<^sub>1 b\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext\\<open>Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors:\\<close>\n\ntext_raw\\<open>\\snip{AExpplusdef}{0}{2}{%\\<close>\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw\\<open>\\snip{AExptimesdef}{0}{2}{%\\<close>\nfun times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"times (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1*i\\<^sub>2)\" |\n\"times (N i) a = (if i=0 then (N 0) else (if i=1 then a else Times (N i) a))\" |\n\"times a (N i) = (if i=0 then (N 0) else (if i=1 then a else Times a (N i)))\" |\n\"times a\\<^sub>1 a\\<^sub>2 = Times a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma aval_times[simp]:\n  \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\napply(induction a1 a2 rule: times.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw\\<open>\\snip{AExpasimpdef}{2}{0}{%\\<close>\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\" |\n\"asimp (Times a\\<^sub>1 a\\<^sub>2) = times (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\ntext\\<open>Note that in \\<^const>\\<open>asimp_const\\<close> the optimized constructor was\ninlined. Making it a separate function \\<^const>\\<open>plus\\<close> improves modularity of\nthe code and the proofs.\\<close>\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend\n", "meta": {"author": "lemmarathon", "repo": "isabelle-exercises", "sha": "6a4a5c030b23a0152c1245424d25232958d9c2f8", "save_path": "github-repos/isabelle/lemmarathon-isabelle-exercises", "path": "github-repos/isabelle/lemmarathon-isabelle-exercises/isabelle-exercises-6a4a5c030b23a0152c1245424d25232958d9c2f8/concrete-semantics/Ch3_AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.765964353048892}}
{"text": "theory Auto_Proof_Demo\nimports Main\nbegin\n\nterm \"{x::int. x>0}\"  \n  \nterm \"{x+y | x y. x>0 \\<and> y>0}\"\n  \n  \nlemma \"{x+y :: int | x y. x>0 \\<and> y>0} = {x. x>1}\"  \n  apply auto\n  by presburger \n    \n  \nsection{* Logic and sets *}\n\nlemma \"\\<forall>x. \\<exists>y. x=y\"\n  by auto\n    \nterm \"()\"    \n    \nlemma \"\\<exists>x::unit. \\<forall>y. x=y\" by simp\n  \nlemma \"\\<exists>x. True\" by blast\n    \n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\nby auto\n\ntext{* Note the bounded quantification notation: *}\n\nlemma \"\\<lbrakk> \\<forall>xs \\<in> A. \\<exists>ys. xs = ys @ ys;  us \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists>n. length us = n+n\"\nby fastforce\n\nlemma \"\\<lbrakk> \\<forall>xs \\<in> A. \\<exists>ys. xs = ys @ ys;  us \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists>n. length us = n+n\"\n  try0\n  by fastforce\n\n  \n  \ntext{*\n Most simple proofs in FOL and set theory are automatic.\n Example: if T is total, A is antisymmetric\n and T is a subset of A, then A is a subset of T.\n*}\n\nlemma AT:\n  \"\\<lbrakk> \\<forall>x y. T x y \\<or> T y x;\n     \\<forall>x y. A x y \\<and> A y x \\<longrightarrow> x = y;\n     \\<forall>x y. T x y \\<longrightarrow> A x y \\<rbrakk>\n   \\<Longrightarrow> \\<forall>x y. A x y \\<longrightarrow> T x y\"\nby blast\n\n\nsection{* Sledgehammer *}\n\nlemma \"R^* \\<subseteq> (R \\<union> S)^*\"\n  by (simp add: rtrancl_mono)\n\n(* Find a suitable P and try sledgehammer: *)\n\nlemma lemma1: \"a # xs = ys @ [a] \\<Longrightarrow> xs=[] \\<and> ys=[] \\<or> (\\<exists>zs. xs=zs@[a] \\<and> ys=a#zs)\"\n  by (metis Cons_eq_append_conv list.inject)\n    \n(* Can you also show equivalence ? *)    \nlemma \"a # xs = ys @ [a] \\<longleftrightarrow> (xs=[] \\<and> ys=[] \\<or> (\\<exists>zs. xs=zs@[a] \\<and> ys=a#zs))\"\n  by (meson Cons_eq_append_conv lemma1)\n    \nlemma \"{x::int. x>0} \\<subseteq> {x. x>-3}\" \n  apply safe\n  by auto  \n    \nthm lemma1    \n    \n\nsection{* Arithmetic *}\n\nlemma \"\\<lbrakk> (a::int) \\<le> f x + b; 2 * f x < c \\<rbrakk> \\<Longrightarrow> 2*a + 1 \\<le> 2*b + c\"\nby arith\n\nlemma \"\\<forall> (k::nat) \\<ge> 8. \\<exists> i j. k = 3*i + 5*j\"\nby arith\n\nlemma \"(n::int) mod 2 = 1 \\<Longrightarrow> (n+n) mod 2 = 0\"\nby arith\n\nlemma \"(i + j) * (i - j) \\<le> i*i + j*(j::int)\"\nby (simp add: algebra_simps)\n\nlemma \"(5::int) ^ 2 = 20+5\"\nby simp\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Demos/Auto_Proof_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7658066029965078}}
{"text": "header{*Tensor product of matrices*}\ntheory Matrix_Tensor\nimports\n  Utility Matrix_Arith\nbegin\n\n\ntext{*we define a multiplicative locale here - mult, \nwhere the multiplication satisfies commutativity, \nassociativity and contains a left and right identity*}\n\nlocale mult = \n fixes id::\"'a\"\n fixes f::\" 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \" (infixl \"*\" 60)\n assumes comm:\" f a  b = f b  a \"\n assumes assoc:\" (f (f a b) c) = (f a (f b c))\"\n assumes left_id:\" f id x = x\"\n assumes right_id:\"f x id = x\"\n\ncontext mult\nbegin   \n\n\ntext{*times a v , gives us the product of the vector v with \nmultiplied pointwise with a *}\n\nprimrec times:: \"'a \\<Rightarrow> 'a vec \\<Rightarrow> 'a vec\"\nwhere\n\"times n [] = []\"|\n\"times n (y#ys) = (f n y)#(times n ys)\"\n\nlemma times_scalar_id: \"times id v = v\"\napply(induct_tac v)\napply(auto)\napply(simp add:left_id)\ndone\n\n\nlemma times_vector_id: \"times v [id] = [v]\"\napply(simp add:right_id)\ndone\n\nlemma preserving_length: \"length (times n y) = (length y)\"\napply(induct_tac y)\napply(auto)\ndone\n\ntext{* vec$\\_$vec$\\_$Tensor is the tensor product of two vectors. It is \nillustrated by the following relation\n \nvec$\\_$vec$\\_$Tensor (v$\\_$1,v$\\_$2,...v$\\_$n) (w$\\_$1,w$\\_$2,...w$\\_$m) \n                 = (v$\\_$1 \\<cdot> w$\\_$1,...,v$\\_$1 \\<cdot> w$\\_$m,...\n                          , v$\\_$n\\<cdot> w$\\_$1 , ..., v$\\_$n \\<cdot> w_$\\_$m) *}\n\nprimrec vec_vec_Tensor:: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a vec\"\nwhere\n\"vec_vec_Tensor [] ys = []\"|\n\"vec_vec_Tensor (x#xs) ys = (times x ys)@(vec_vec_Tensor xs ys)\"\n\n\nlemma vec_vec_Tensor_left_id: \"vec_vec_Tensor [id] v = v\"\napply(induct_tac v)\napply(auto)\napply(simp add:left_id)\ndone\n\n\nlemma vec_vec_Tensor_right_id: \"vec_vec_Tensor v [id]  = v\"\napply(induct_tac v)\napply(auto)\napply(simp add:right_id)\ndone\n\ntheorem vec_vec_Tensor_length : \n \"(length(vec_vec_Tensor x y)) = (length x)*(length y)\"\napply(induct_tac x)\napply(auto)\napply(simp add: preserving_length)\ndone\n\ntheorem vec_length: assumes \"vec m x\" and \"vec n y\"\nshows \"vec (m*n) (vec_vec_Tensor x y)\"\napply(simp add:vec_def)\napply(simp add:vec_vec_Tensor_length)\napply (metis assms(1) assms(2) vec_def)\ndone\n\n\ntext{* vec$\\_$mat$\\_$Tensor is the tensor product of two vectors. It is \nillusstrated by the following relation\n \nvec_mat_Tensor (v$\\_$1,v$\\_$2,...v$\\_$n) (C$\\_$1,C$\\_$2,...C$\\_$m) \n                 = (v$\\_$1\\<cdot>C$\\_$1,...,v$\\_$n \\<cdot>C$\\_$1,\n                               ...,v$\\_$1\\<cdot> C$\\_$m , ..., v$\\_$n \\<cdot> C$\\_$m) *}\n\n\nprimrec vec_mat_Tensor::\"'a vec \\<Rightarrow> 'a mat \\<Rightarrow>'a mat\"\nwhere\n\"vec_mat_Tensor xs []  = []\"|\n\"vec_mat_Tensor xs (ys#yss) = (vec_vec_Tensor xs ys)#(vec_mat_Tensor xs yss)\"\n\n\nlemma vec_mat_Tensor_vector_id: \"vec_mat_Tensor [id] v = v\"\n apply(induct_tac v)\n apply(auto)\n apply(simp add: times_scalar_id)\n done\n\nlemma vec_mat_Tensor_matrix_id: \"vec_mat_Tensor  v [[id]] = [v]\"\napply(induct_tac v)\napply(auto)\napply(simp add: right_id)\ndone\n\n\ntheorem vec_mat_Tensor_length : \n \"(length(vec_mat_Tensor xs ys)) = (length ys)\"\napply(induct_tac ys)\napply(auto)\ndone\n\ntheorem length_matrix: assumes \"mat nr nc (y#ys)\" and \"length v = k\"\nand \"(vec_mat_Tensor v (y#ys) = x#xs)\" \n shows \"(vec (nr*k) x)\" \nproof-\nhave \"vec_mat_Tensor v (y#ys) = (vec_vec_Tensor v y)#(vec_mat_Tensor v ys)\"  using vec_mat_Tensor_def assms by auto\nalso have \"(vec_vec_Tensor v y) = x\" using assms by auto\nalso have \"length y = nr\" using assms mat_def by (metis in_set_member member_rec(1) vec_def)\nfrom this\n have \"length (vec_vec_Tensor v y) = nr*k\" using assms vec_vec_Tensor_length nat_mult_commute by auto\nfrom this have \"length x = nr*k\" by (simp add: `vec_vec_Tensor v y = x`)\nfrom this have \"vec (nr*k) x\" using vec_def by auto\nfrom this show ?thesis by auto\nqed\n\nlemma matrix_set_list: assumes \"mat nr nc M\" and \"length v = k\"\nand \" x \\<in> set M\" \n shows \"\\<exists>ys.\\<exists>zs.(ys@x#zs = M)\" using assms set_def in_set_conv_decomp by metis\n\nprimrec reduct :: \"'a mat \\<Rightarrow> 'a mat\"\nwhere\n\"reduct [] = []\"\n|\"reduct (x#xs) = xs\"\n\nlemma length_reduct: assumes \"m \\<noteq> []\"\nshows \"length (reduct m) +1  = (length m)\"\napply(auto)\nby (metis One_nat_def Suc_eq_plus1 assms list.size(4) neq_Nil_conv reduct.simps(2))\n\nlemma mat_empty_column_length: assumes \"mat nr nc M\" and \"M = []\"\nshows \"nc = 0\" \nproof-\nhave \"(length M = nc)\" using mat_def assms by metis\nfrom this have \"nc = 0\" using assms by auto\nfrom this show ?thesis by simp\nqed\n\nlemma vec_uniqueness: assumes \"vec m v\" and \"vec n v\" shows \n\"m = n\"\nusing vec_def assms(1) assms(2)  by metis\n\nlemma mat_uniqueness: assumes \"mat nr1 nc M\" and \"mat nr2 nc M\" and \"z = hd M\" and \"M \\<noteq> []\"\nshows \"(\\<forall>x\\<in>(set M).(nr1 = nr2))\" \nproof-\n have A:\"z \\<in> set M\" using assms(1) assms(3) assms(4) set_def mat_def by (metis hd_in_set)\n have \"Ball (set M) (vec nr1)\" using mat_def assms(1) by auto \n  from this have step1: \"((x \\<in> (set M)) \\<longrightarrow> (vec nr1 x))\" using Ball_def assms by auto\n  have \"Ball (set M) (vec nr2)\" using mat_def assms(2) by auto\n  from this have step2: \"((x \\<in> (set M)) \\<longrightarrow> (vec nr2 x))\" using Ball_def assms by auto\n  from step1 and step2 have step3:\"\\<forall>x.((x \\<in> (set M))\\<longrightarrow> ((vec nr1 x)\\<and> (vec nr2 x)))\"\n  by (metis `Ball (set M) (vec nr1)` `Ball (set M) (vec nr2)`)\n  have \"((vec nr1 x)\\<and> (vec nr2 x)) \\<longrightarrow> (nr1 = nr2)\" using vec_uniqueness by auto\n  from this and step3  have \"(\\<forall>x.((x \\<in> (set M)) \\<longrightarrow>((nr1 = nr2))))\" by \n (metis vec_uniqueness) \n from this have \"(\\<forall>x\\<in>(set M).(nr1 = nr2))\" by auto \n from this show ?thesis by auto\nqed\n\n \nlemma mat_empty_row_length: assumes \"mat nr nc M\" and \"M = []\"\nshows \"mat 0 nc M\" \nproof-\nhave \"set M = {}\" using mat_def assms  empty_set  by auto\nfrom this have \"Ball (set M) (vec 0)\" using Ball_def by auto\nfrom this have \"mat 0 nc M\" using mat_def assms(1) assms(2) gen_length_code(1) length_code\n by (metis (full_types) )\nfrom this show ?thesis by auto\nqed\n\nabbreviation null_matrix::\"'a list list\"\nwhere\n\"null_matrix \\<equiv> [Nil] \"\n\nlemma null_mat:\"null_matrix = [[]]\"\n      by auto\n\nlemma zero_matrix:\" mat 0 0 []\" using mat_def in_set_insert insert_Nil list.size(3) not_Cons_self2\n by (metis (full_types))\n\ntext{*row_length gives the length of the first row of a matrix. For a `valid'\nmatrix, it is equal to the number of rows *}\n\ndefinition row_length:: \"'a mat \\<Rightarrow> nat\"\nwhere\n\"row_length xs \\<equiv> if (xs = []) then 0 else (length (hd xs))\"\n\nlemma row_length_Nil: \"row_length [] =0\" using row_length_def by (metis )\n\nlemma row_length_Null: \"row_length [[]] =0\" using row_length_def by (metis hd.simps list.size(3))\n\nlemma row_length_vect_mat: \n \"row_length (vec_mat_Tensor v m)  = length v*(row_length m)\"\n proof(induct m)\n  case Nil\n   have \"row_length [] = 0\" \n                     using row_length_Nil by simp\n   moreover have \"vec_mat_Tensor v [] = []\" \n                     using vec_mat_Tensor.simps(1) by auto \n   ultimately have \n           \"row_length (vec_mat_Tensor v [])  = length v*(row_length [])\" \n            using mult_0_right by (metis )\n   from this show ?case by metis\n  next  \n   fix a m\n   assume A:\"row_length (vec_mat_Tensor v m) = length v * row_length m\"\n   let ?case = \n         \"row_length (vec_mat_Tensor v (a#m)) = (length v)*(row_length (a#m))\" \n   have A:\"row_length (a # m) = length a\" \n                   using row_length_def  hd.simps list.distinct(1)\n                   by auto\n   have \"(vec_mat_Tensor v  (a#m)) = (vec_vec_Tensor v a)#(vec_mat_Tensor v m)\" \n                   using vec_mat_Tensor_def vec_mat_Tensor.simps(2)\n                   by auto\n   from this have \n       \"row_length (vec_mat_Tensor v (a#m)) = length (vec_vec_Tensor v a)\" \n                   using row_length_def  hd.simps list.distinct(1) \n                   vec_mat_Tensor.simps(2)\n                   by auto\n   from this and vec_vec_Tensor_length have \n          \"row_length (vec_mat_Tensor v (a#m)) = (length v)*(length a)\" \n          by auto\n   from this and A  have \n         \"row_length (vec_mat_Tensor v (a#m)) = (length v)*(row_length (a#m))\"\n         by auto\n   from this show ?case by auto\nqed\n\ntext{*Tensor is the tensor product of matrices*}\n\nprimrec Tensor::\" 'a mat \\<Rightarrow> 'a mat \\<Rightarrow>'a mat\" (infixl \"\\<otimes>\" 63)\nwhere\n\"Tensor [] xs = []\"|\n\"Tensor (x#xs) ys = (vec_mat_Tensor x ys)@(Tensor xs ys)\"\n\nlemma Tensor_null: \"xs \\<otimes>[] = []\" \n  apply(induct_tac xs)\n  apply(auto)\n  done\n\n\ntext{*Tensor commutes with left and right identity*}\nlemma Tensor_left_id: \"  [[id]] \\<otimes> xs = xs\"\n  apply(induct_tac xs)\n  apply(auto)\n  apply(simp add:times_scalar_id)\n  done\n\n\nlemma Tensor_right_id: \"  xs \\<otimes> [[id]] = xs\"\n  apply(induct_tac xs)\n  apply(auto)\n  apply(simp add: vec_vec_Tensor_right_id)\n  done\n\nlemma hd_append:  \n       assumes \"xs \\<noteq> []\" \n       shows \"hd (xs@ys) = hd xs\" \n         using hd_def hd_append2 append_def \n         apply(induct_tac ys)\n         apply(auto)\n         by (metis assms hd_append2)\n\ntext{*row$\\_$length of tensor product of matrice is the product of \ntheir respective row lengths*}\nlemma row_length_mat: \n    \"(row_length (m1\\<otimes>m2)) = (row_length m1)*(row_length m2)\"\n proof(induct m1)\n  case Nil\n    have \"row_length ([]\\<otimes>m2) = 0\" \n     using Tensor.simps(1) row_length_def \n     by metis\n   from this \n    have \"row_length ([]\\<otimes>m2) = (row_length [])*(row_length m2)\"  \n     using comm_semiring_1_class.normalizing_semiring_rules(9) row_length_Nil   \n     by (metis)\n   then show ?case by metis\n  next\n  fix a m1 \n  assume \"row_length (m1 \\<otimes> m2) = row_length m1 * row_length m2\"\n  let ?case = \n    \"row_length ((a # m1) \\<otimes> m2) = row_length (a # m1) * row_length m2\"\n   have B: \"row_length (a#m1) = length a\" \n      using row_length_def  hd.simps list.distinct(1)\n      by auto\n   have \"row_length ((a # m1) \\<otimes> m2) = row_length (a # m1) * row_length m2\"\n    proof(induct m2)\n    case Nil\n       show ?case using Tensor_null row_length_def  mult_0_right by (metis)\n    next\n    fix aa m2\n    assume \"row_length (a # m1 \\<otimes> m2) = row_length (a # m1) * row_length m2\"\n    let ?case= \n      \"row_length (a # m1 \\<otimes> aa # m2) \n                  = row_length (a # m1) * row_length (aa # m2)\"\n      have \"aa#m2 \\<noteq> []\" \n               by auto\n      from this have non_zero:\"(vec_mat_Tensor a (aa#m2)) \\<noteq> []\" \n               using vec_mat_Tensor_def by auto\n      from this have \n            \"hd ((vec_mat_Tensor a (aa#m2))@(m1\\<otimes>m2))\n                  = hd (vec_mat_Tensor a (aa#m2))\" \n               by auto\n       from this have \n            \"hd ((a#m1)\\<otimes>(aa#m2)) = hd (vec_mat_Tensor a (aa#m2))\" \n             using Tensor.simps(2) by auto\n       from this have s1: \"row_length ((a#m1)\\<otimes>(aa#m2)) \n                       = row_length (vec_mat_Tensor a (aa#m2))\" \n             using row_length_def  Nil_is_append_conv non_zero Tensor.simps(2)\n             by auto\n       have \"row_length (vec_mat_Tensor a (aa#m2)) \n                    = (length a)*row_length(aa#m2)\" \n             using row_length_vect_mat by metis   \n       from this and s1  \n       have \"row_length (vec_mat_Tensor a (aa#m2)) \n                             = (length a)*row_length(aa#m2)\"\n             by auto\n       from this and B \n             have \"row_length (vec_mat_Tensor a (aa#m2)) \n                           = (row_length (a#m1))*row_length(aa#m2)\"    \n             by auto\n       from this  and s1 show ?case  by auto\n    qed\n    from this show ?case by auto\n qed\n\n\n\n\ntext{*for every valid matrix can also be written in the following form*}\ntheorem matrix_row_length: assumes \"mat nr nc M\" \nshows \"mat (row_length M) (length M) M\"\nproof(cases M)\n case Nil\n  have \"row_length M= 0 \" \n       using row_length_def by (metis Nil)\n  moreover have \"length M = 0\" \n       by (metis Nil list.size(3))\n  moreover  have \"mat 0 0 M\" \n       using zero_matrix Nil by auto \n  ultimately show ?thesis  \n       using mat_empty_row_length row_length_def mat_def  by metis\n next\n case (Cons a N) \n  have 1: \"mat nr nc (a#N)\" \n       using assms Cons by auto\n from this have \"(x \\<in> set (a #N)) \\<longrightarrow> (x = a) \\<or> (x \\<in> (set N))\" \n       using hd_set by auto\n from this and 1 have 2:\"vec nr a\" \n       using mat_def by (metis Ball_set_list_all list_all_simps(1))\n have \"row_length (a#N) = length a\" \n       using row_length_def Cons hd.simps list.distinct(1) by metis\n from this have \" vec (row_length (a#N)) a\" \n        using vec_def by auto\n from this and 2 have 3:\"(row_length M)  = nr\" \n        using vec_uniqueness Cons by auto\n have \" nc = (length M)\" \n        using 1 and mat_def and assms by metis\n with 3 \n        have \"mat (row_length M) (length M) M\" \n        using assms by auto \n from this show ?thesis by auto\nqed\n\n\nlemma reduct_matrix: \n assumes \"mat (row_length (a#M)) (length (a#M)) (a#M)\"\n shows \"mat (row_length M) (length M) M\"\nproof(cases M)\n case Nil\n   show ?thesis \n         using row_length_def zero_matrix Nil  list.size(3)  by (metis)\n next   \n case (Cons b N)\n  fix x\n  have 1: \"b \\<in> (set M)\" \n         using set_def  Cons ListMem_iff elem  by auto\n  have \"mat (row_length (a#M)) (length (a#M)) (a#M)\" \n         using assms by auto\n  then have \"(x \\<in> (set (a#M))) \\<longrightarrow> ((x = a) \\<or> (x \\<in> set M))\" \n         by auto\n  then have \" (x \\<in> (set (a#M))) \\<longrightarrow> (vec (row_length (a#M)) x)\" \n         using mat_def Ball_def assms \n         by metis\n  then have \"(x \\<in> (set (a#M))) \\<longrightarrow> (vec (length a) x)\" \n         using row_length_def hd.simps list.distinct(1) \n         by (metis )\n  then have 2:\"x \\<in> (set M) \\<longrightarrow> (vec (length a) x)\" \n         by auto\n  with 1 have 3:\"(vec (length a) b)\"\n         using assms in_set_member mat_def member_rec(1) vec_def\n         by (metis) \n  have 5: \"(vec (length b) b)\" \n         using vec_def by auto\n  with 3 have \"(length a) = (length b)\" \n         using vec_uniqueness by auto\n  with 2 have 4: \"x \\<in> (set M) \\<longrightarrow> (vec (length b) x)\" \n         by auto\n  have 6: \"row_length M = (length b)\" \n         using row_length_def hd.simps  Cons list.distinct(1)\n         by auto\n  with 4 have \"x \\<in> (set M) \\<longrightarrow> (vec (row_length M) x)\" \n         by auto\n  then have \"(\\<forall>x. (x \\<in> (set M) \\<longrightarrow> (vec (row_length M) x)))\" \n         using Cons 5 6 assms in_set_member mat_def member_rec(1) \n         vec_uniqueness\n         by metis\n  then have \"Ball (set M) (vec (row_length M))\" \n         using Ball_def by auto\n  then have \"(mat (row_length M) (length M) M)\" \n         using mat_def by auto\n  then show ?thesis by auto\n qed \n\n\ntheorem well_defined_vec_mat_Tensor:\n\"(mat (row_length M) (length M) M) \\<Longrightarrow>\n                  (mat \n                    ((row_length M)*(length v)) \n                    (length M) \n                           (vec_mat_Tensor v M))\"\n proof(induct M) \n case Nil\n  have \"(vec_mat_Tensor v []) = []\" \n      using vec_mat_Tensor.simps(1) Nil  \n      by simp\n  moreover have \"(row_length [] = 0)\"  \n      using row_length_def Nil \n      by metis\n  moreover have \"(length []) = 0\" \n      using Nil by simp\n  ultimately have \n       \"mat ((row_length [])*(length v)) (length []) (vec_mat_Tensor v [])\" \n      using zero_matrix by (metis mult_zero_left)\n  then show ?case by simp\n next\n fix a M\n assume hyp :\n   \"(mat (row_length M) (length M) M \n           \\<Longrightarrow> mat (row_length M * length v) (length M) (vec_mat_Tensor v M))\"\n   \"mat (row_length (a#M)) (length (a#M)) (a#M)\"                      \n  let ?case = \n   \"mat (row_length (a#M) * length v) (length (a#M)) (vec_mat_Tensor v (a#M))\"\n   have step1: \"mat (row_length M) (length M) M\" \n          using hyp(2) reduct_matrix by auto\n   then have step2:\n    \"mat (row_length M * length v) (length M) (vec_mat_Tensor v M)\" \n          using hyp(1) by auto \n  have \n   \"mat \n        (row_length (a#M) * length v) \n        (length (a#M)) \n             (vec_mat_Tensor v (a#M))\" \n    proof (cases M)\n    case Nil \n     fix x\n     have 1:\"(vec_mat_Tensor v (a#M)) = [vec_vec_Tensor v a]\" \n           using vec_mat_Tensor.simps Nil by auto\n     have   \"(x \\<in> (set [vec_vec_Tensor v a])) \\<longrightarrow>  x = (vec_vec_Tensor v a)\" \n           using set_def by auto\n     from this have 2:\n        \"(x \\<in> (set [vec_vec_Tensor v a])) \n                    \\<longrightarrow> (vec (length (vec_vec_Tensor v a)) x)\" \n           using vec_def by metis \n     have 3:\"length (vec_vec_Tensor v a) = (length v)*(length a)\" \n           using vec_vec_Tensor_length by auto \n     then have 4:\n        \"length (vec_vec_Tensor v a) = (length v)*(row_length (a#M))\" \n           using row_length_def hd.simps list.distinct(1) \n           by auto\n     with 2 have \n        \"(x \\<in> (set [vec_vec_Tensor v a])) \n                \\<longrightarrow> (vec ((length v)*(row_length (a#M))) x)\" \n           by auto\n     with 1 have 5:\n         \"(x \\<in> set (vec_mat_Tensor v (a#M))) \n               \\<longrightarrow> vec ((length v)*(row_length (a#M))) x\" \n           by auto\n     have 6: \"length (vec_mat_Tensor v (a#M)) = (length (a#M))\" \n           using vec_mat_Tensor_length by auto\n     from this have \n        \"mat \n              (row_length (a#M) * length v) \n              (length (vec_mat_Tensor v (a#M))) \n              (vec_mat_Tensor v (a#M))\"\n         using mat_def Ball_def 1 3 4  hd_set in_set_insert insert_Nil \n         length_code nat_mult_commute  not_Cons_self2 vec_vec_Tensor_length \n         vec_def\n          by (metis (hide_lams, no_types))\n     then show ?thesis using 6 by auto\n    next \n    case (Cons b L)\n    fix x\n     have 1:\"x \\<in> (set (a#M)) \\<longrightarrow> ((x=a) \\<or> (x \\<in> (set M)))\" \n                 using hd_set by auto\n     have \"mat (row_length (a#M)) (length (a#M)) (a#M)\" \n                 using hyp by auto\n     then have \"x\\<in> (set (a#M)) \\<longrightarrow> (vec (row_length (a#M)) x)\" \n                  using mat_def Ball_def by metis\n     then have \"x\\<in> (set (a#M))\\<longrightarrow> (vec (length a) x)\" \n                  using row_length_def hd.simps list.distinct(1)\n                  by auto\n     with 1 have \"x\\<in> (set M)\\<longrightarrow> (vec (length a) x)\" \n                  by auto\n     moreover have \" b \\<in> (set M)\" \n                  using Cons by auto\n     ultimately have \"vec (length a) b\"\n                  using  hyp(2) in_set_member mat_def member_rec(1) vec_def \n                  by (metis) \n     then have \"(length b) = (length a)\" \n                  using vec_def vec_uniqueness by auto\n     then have 2:\"row_length M = (length a)\" \n                   using row_length_def hd.simps  Cons list.distinct(1)\n                   by auto     \n     have \"mat (row_length M * length v) (length M) (vec_mat_Tensor v M)\" \n                   using step2 by auto \n     then have 3:\n          \"Ball (set (vec_mat_Tensor v M)) (vec ((row_length M)*(length v)))\" \n                   using mat_def by auto\n     then have \"(x \\<in> set (vec_mat_Tensor v M)) \n                        \\<longrightarrow> (vec ((row_length M)*(length v)) x)\" \n                   using mat_def Ball_def\n                   by auto\n     then have 4:\"(x \\<in> set (vec_mat_Tensor v M)) \n                          \\<longrightarrow> (vec ((length a)*(length v)) x)\" \n                   using 2 \n                   by auto  \n     have 5:\"length (vec_vec_Tensor v a) = (length a)*(length v)\" \n                   using  nat_mult_commute vec_vec_Tensor_length\n                   by auto  \n     then have 6:\" vec ((length a)*(length v)) (vec_vec_Tensor v a)\" \n                   using vec_vec_Tensor_length vec_def \n                   by (metis (full_types))\n      have 7:\"(length a) = (row_length (a#M))\" \n                   using row_length_def hd.simps  list.distinct(1)  \n                   by (metis) \n      have \"vec_mat_Tensor v (a#M) \n                   = (vec_vec_Tensor v a)#(vec_mat_Tensor v M)\" \n                   using vec_mat_Tensor.simps(2) by auto\n      then have \"(x \\<in> set (vec_mat_Tensor v (a#M)))\n                      \\<longrightarrow> ((x = (vec_vec_Tensor v a)) \n                           \\<or> (x \\<in> (set (vec_mat_Tensor v M))))\"\n                   using hd.simps hd_set by auto\n      with 4 6 have \"(x \\<in> set (vec_mat_Tensor v (a#M)))\n                             \\<longrightarrow>  vec ((length a)*(length v)) x\" \n                   by auto\n      with 7 have \"(x \\<in> set (vec_mat_Tensor v (a#M)))\n                                \\<longrightarrow>  vec ((row_length (a#M))*(length v)) x\" \n                   by auto\n      then have \"\\<forall>x.((x \\<in> set (vec_mat_Tensor v (a#M)))\n                                \\<longrightarrow>  vec ((row_length (a#M))*(length v)) x)\"\n                   using \"2\" \"3\" \"6\" \"7\" hd_set vec_mat_Tensor.simps(2)\n                   by auto\n      then have 7: \n      \"Ball \n            (set (vec_mat_Tensor v (a#M))) \n            (vec ((row_length (a#M))*(length v)))\" \n            using Ball_def \n            by auto\n      have 8: \"length (vec_mat_Tensor v (a#M)) = length (a#M)\" \n            using vec_mat_Tensor_length \n            by auto   \n      with 6  7 have \n               \"mat \n                 ((row_length (a#M))*(length v)) \n                 (length (a#M)) \n                           (vec_mat_Tensor v (a#M))\"\n            using mat_def  \"5\" length_code\n            by (metis (hide_lams, no_types))\n     from this show ?thesis by auto\n     qed\n    from hyp this show ?case by auto  \n qed\n\ntext{* The following theorem  gives length of tensor product of two matrices*}\nlemma length_Tensor:\" (length (M1\\<otimes>M2)) = (length M1)*(length M2)\"\nproof(induct M1)\n case Nil\n  show ?case by auto\n next\n case (Cons a M1)\n  have \"((a # M1) \\<otimes> M2) = (vec_mat_Tensor a M2)@(M1 \\<otimes> M2)\" \n       using Tensor.simps(2) by auto\n  then have 1:\n          \"length ((a # M1) \\<otimes> M2) = length ((vec_mat_Tensor a M2)@(M1 \\<otimes> M2))\" \n               by auto\n have 2:\"length ((vec_mat_Tensor a M2)@(M1 \\<otimes> M2)) \n              = length (vec_mat_Tensor a M2)+ length (M1 \\<otimes> M2)\" \n               using append_def\n               by auto\n have 3:\"(length (vec_mat_Tensor a M2)) = length M2\" \n               using vec_mat_Tensor_length by (auto)\n have 4:\"length (M1 \\<otimes> M2) = (length M1)*(length M2)\" \n               using  Cons.hyps by auto\n with 2 3 have \"length ((vec_mat_Tensor a M2)@(M1 \\<otimes> M2)) \n                              = (length M2) + (length M1)*(length M2)\"\n               by auto\n then have 5:\n    \"length ((vec_mat_Tensor a M2)@(M1 \\<otimes> M2)) = (1 + (length M1))*(length M2)\" \n               by auto\n with 1  have \"length ((a # M1) \\<otimes> M2) = ((length (a # M1)) * (length M2))\" \n          by auto\n then show ?case by auto\nqed\n\n\n\nlemma append_reduct_matrix: \n\"(mat (row_length (M1@M2)) (length (M1@M2)) (M1@M2))\n\\<Longrightarrow>(mat (row_length M2) (length M2) M2)\"\nproof(induct M1)\ncase Nil\n show ?thesis using Nil append.simps(1) by auto\nnext\ncase (Cons a M1)\n have \"mat (row_length (M1 @ M2)) (length (M1 @ M2)) (M1 @ M2)\" \n   using reduct_matrix Cons.prems append_Cons by metis\n from this have \"(mat (row_length M2) (length M2) M2)\" \n   using Cons.hyps by auto\n from this show?thesis by simp\nqed\n\ntext{*The following theorem proves that tensor product of two valid matrices\nis a valid matrix*}\n\ntheorem well_defined_Tensor:\n \"(mat (row_length M1) (length M1) M1) \n\\<and> (mat (row_length M2) (length M2) M2)\n\\<Longrightarrow>(mat ((row_length M1)*(row_length M2)) ((length M1)*(length M2)) (M1\\<otimes>M2))\"\nproof(induct M1)\n case Nil\n   have \"(row_length []) * (row_length M2) = 0\" \n            using row_length_def  mult_zero_left  by (metis)\n   moreover have \"(length []) * (length M2) = 0\" \n            using  mult_zero_left list.size(3) by auto \n   moreover have \"[] \\<otimes> M2 = []\" \n            using Tensor.simps(1) by auto\n   ultimately have \n       \"mat (row_length []*row_length M2) (length []*length M2) ([] \\<otimes> M2)\"\n            using zero_matrix by metis\n   then show ?case by simp\n next\n case (Cons a M1)\n   have step1: \"mat (row_length (a # M1)) (length (a # M1)) (a # M1)\" \n              using Cons.prems by auto\n then have \"mat (row_length (M1)) (length (M1)) (M1)\" \n              using reduct_matrix by auto\n moreover have \"mat (row_length (M2)) (length (M2)) (M2)\" \n              using Cons.prems by auto\n ultimately have step2:\n      \"mat (row_length M1 * row_length M2) (length M1 * length M2) (M1 \\<otimes> M2)\"\n              using Cons.hyps by auto\n have 0:\"row_length (a#M1) = length a\" \n              using row_length_def hd.simps list.distinct(1)  \n      by metis\n have \"mat \n           (row_length (a # M1)*row_length M2) \n           (length (a # M1)*length M2) \n                           (a # M1 \\<otimes> M2)\"\n  proof(cases M1)\n   case Nil \n    have \"(mat ((row_length M2)*(length a)) (length M2) (vec_mat_Tensor a M2))\" \n          using Cons.prems well_defined_vec_mat_Tensor by auto\n    moreover have \"(length (a # M1)) * (length M2) = length M2\" \n          using Nil by auto\n    moreover have \"(a#M1)\\<otimes>M2 = (vec_mat_Tensor a M2)\" \n          using Nil Tensor.simps append.simps(1) by auto\n    ultimately have \n        \"(mat \n            ((row_length M2)*(row_length (a#M1))) \n            ((length (a # M1)) * (length M2))\n               ((a#M1)\\<otimes>M2))\" \n             using 0\n             by auto\n     then show ?thesis using nat_mult_commute by metis\n  next\n  case (Cons b N1)\n     fix x\n     have 1:\"x \\<in> (set (a#M1)) \\<longrightarrow> ((x=a) \\<or> (x \\<in> (set M1)))\" \n               using hd_set by auto\n     have \"mat (row_length (a#M1)) (length (a#M1)) (a#M1)\" \n               using Cons.prems by auto\n     then have \"x\\<in> (set (a#M1)) \\<longrightarrow> (vec (row_length (a#M1)) x)\" \n               using mat_def Ball_def by metis\n     then have \"x\\<in> (set (a#M1))\\<longrightarrow> (vec (length a) x)\" \n               using row_length_def hd.simps list.distinct(1)\n               by auto \n      with 1 have \"x\\<in> (set M1)\\<longrightarrow> (vec (length a) x)\" \n               by auto\n      moreover have \" b \\<in> (set M1)\" \n               using Cons by auto\n      ultimately have \"vec (length a) b\" \n               using  Cons.prems in_set_member mat_def member_rec(1) vec_def\n               by metis\n      then have \"(length b) = (length a)\" \n               using vec_def vec_uniqueness by auto\n      then have 2:\"row_length M1 = (length a)\" \n               using row_length_def hd.simps by (metis Cons list.distinct(1)) \n      then have \"mat \n                    ((length a) * row_length M2) \n                    (length M1 * length M2) \n                                    (M1 \\<otimes> M2)\" \n                 using step2 by auto\n      then have \"Ball (set (M1\\<otimes>M2)) (vec ((length a)*(row_length M2))) \" \n                  using mat_def by auto     \n      from this have 3:\n         \"\\<forall>x. x \\<in> (set (M1 \\<otimes> M2)) \\<longrightarrow> (vec ((length a)*(row_length M2)) x)\" \n                  using Ball_def by auto    \n      have \"mat \n              ((row_length M2)*(length a)) \n              (length M2) \n                 (vec_mat_Tensor a M2)\" \n                   using well_defined_vec_mat_Tensor Cons.prems \n                   by auto\n      then have \"Ball \n                    (set (vec_mat_Tensor a M2)) \n                    (vec ((row_length M2)*(length a)))\" \n                    using mat_def\n                    by auto\n      then have 4:\n              \"\\<forall>x. x \\<in> (set (vec_mat_Tensor a M2)) \n                        \\<longrightarrow> (vec ((length a)*(row_length M2)) x)\"\n                     using nat_mult_commute by metis\n\n      with 3 have 5: \"\\<forall>x. (x \\<in> (set (vec_mat_Tensor a M2)))\n                          \\<or>(x \\<in> (set (M1 \\<otimes> M2))) \n                                 \\<longrightarrow> (vec ((length a)*(row_length M2)) x)\"  \n                      by auto  \n      have 6:\"(a # M1 \\<otimes> M2) = (vec_mat_Tensor a M2)@(M1 \\<otimes>M2)\" \n                      using Tensor.simps(2) by auto \n      then have \"x \\<in> (set (a # M1 \\<otimes> M2)) \n                 \\<longrightarrow> (x \\<in> (set (vec_mat_Tensor a M2)))\\<or>(x \\<in> (set (M1 \\<otimes> M2)))\"\n                       using set_def append_def by auto\n      with 5 have 7:\"\\<forall>x. (x \\<in>  (set (a # M1 \\<otimes> M2)))\n                         \\<longrightarrow> (vec ((length a)*(row_length M2)) x)\" \n                        by auto\n       then have 8:\n        \"Ball (set (a # M1 \\<otimes> M2)) (vec ((row_length (a#M1))*(row_length M2)))\" \n                         using Ball_def 0 by auto   \n       have \"(length ((a#M1)\\<otimes>M2)) = (length (a#M1))*(length M2)\" \n                         using length_Tensor by metis\n       with 7 8\n           have \"mat \n                     (row_length (a # M1) * row_length M2) \n                       (length (a # M1) * length M2) \n                                (a # M1 \\<otimes> M2)\"\n             using mat_def by (metis \"0\"  length_Tensor)\n        then show ?thesis by auto\n       qed\n     then show ?case by auto\n   qed\n\ntheorem effective_well_defined_Tensor:\n assumes \"(mat (row_length M1) (length M1) M1)\" \n     and \"(mat (row_length M2) (length M2) M2)\"\n shows \"mat \n            ((row_length M1)*(row_length M2)) \n            ((length M1)*(length M2)) \n                               (M1\\<otimes>M2)\"\n using well_defined_Tensor assms by auto\n\n\ndefinition natmod::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\" (infixl \"nmod\" 50)\nwhere\n \"natmod x y = nat ((int x) mod (int y))\"\n\ntheorem times_elements:\n \"\\<forall>i.((i<(length v)) \\<longrightarrow> (times a v)!i = f a (v!i))\"\n   apply(rule allI)\n   proof(induct v)\n   case Nil\n    have \"(length [] = 0)\" \n          by auto\n    then have \"i <(length []) \\<Longrightarrow> False\" \n          by auto\n    moreover have \"(times a []) = []\" \n          using times.simps(1) by auto \n    ultimately have \"(i<(length [])) \\<longrightarrow> (times a [])!i = f a ([]!i)\" \n          by auto\n    then have \"\\<forall>i. ((i<(length [])) \\<longrightarrow> (times a [])!i = f a ([]!i))\" \n          by auto\n    then show ?case  by auto\n   next\n   case (Cons x xs)\n    have \"\\<forall>i.((x#xs)!(i+1) = (xs)!i)\" \n      by auto\n    have 0:\"((i<length (x#xs))\\<longrightarrow> ((i<(length xs)) \\<or> (i = (length xs))))\" \n      by auto\n    have 1:\" ((i<length xs) \\<longrightarrow>((times a xs)!i = f a (xs!i)))\" \n      by (metis Cons.hyps)\n    have \"\\<forall>i.((x#xs)!(i+1) = (xs)!i)\" by auto\n    have \"((i <length (x#xs)) \\<longrightarrow>(times a (x#xs))!i = f a ((x#xs)!i))\"  \n    proof(cases i)\n      case 0\n       have \"((times a (x#xs))!i) = f a x\" \n          using 0 times.simps(2) by auto\n       then have \"(times a (x#xs))!i = f a ((x#xs)!i)\" \n         using 0 by auto\n       then show ?thesis by auto\n      next\n      case (Suc j)\n       have 1:\"(times a (x#xs))!i = ((f a x)#(times a xs))!i\" \n         using times.simps(2) by auto \n       have 2:\"((f a x)#(times a xs))!i = (times a xs)!j\" \n         using Suc by auto\n       have 3:\"(i <length (x#xs)) \\<longrightarrow> (j<length xs)\" \n         using One_nat_def Suc Suc_eq_plus1 list.size(4) not_less_eq \n         by metis\n       have 4:\"(j<length xs) \\<longrightarrow> ((times a xs)!j = (f a (xs!j)))\" \n         using 1 by (metis Cons.hyps)\n       have 5:\"(x#xs)!i = (xs!j)\" \n         using Suc by (metis nth_Cons_Suc)\n       with 1 2 4  have \"(j<length xs) \n                            \\<longrightarrow> ((times a (x#xs))!i = (f a ((x#xs)!i)))\" \n         by auto\n       with 3 have \"(i <length (x#xs)) \n                            \\<longrightarrow> ((times a (x#xs))!i = (f a ((x#xs)!i)))\" \n         by auto\n       then show ?thesis  by auto\n      qed\n     then show ?case by auto\n     qed\n\nlemma simpl_times_elements:\n assumes \"(i<length xs)\" \n shows \"((i<(length v)) \\<longrightarrow> (times a v)!i = f a (v!i))\"\n    using times_elements by auto\n\n(*some lemmas which are used to prove theorems*)\nlemma append_simpl: \"i<(length xs) \\<longrightarrow> (xs@ys)!i = (xs!i)\" \nusing nth_append  by metis\n\nlemma append_simpl2: \"i \\<ge>(length xs) \\<longrightarrow> (xs@ys)!i = (ys!(i- (length xs)))\" \nusing nth_append less_asym  leD  by metis\n\nlemma append_simpl3: \nassumes \"i > (length y)\"\nshows \" (i <((length (z#zs))*(length y))) \n                  \\<longrightarrow> (i - (length y))< (length zs)*(length y)\"\n proof-\n have \"length (z#zs) = (length zs)+1\" \n    by auto\n then have \"i <((length (z#zs))*(length y)) \n                   \\<longrightarrow> i <((length zs)+1)*(length y)\"\n    by auto\n then have 1: \"i <((length (z#zs))*(length y)) \n                  \\<longrightarrow> (i <((length zs)*(length y)+ (length y)))\" \n    by auto\n have \"i <((length zs)*(length y)+ (length y)) \n                   = ((i - (length y)) <((length zs)*(length y)))\"\n    using assms by auto\n then have \"(i <((length (z#zs))*(length y))) \n                  \\<longrightarrow> ((i - (length y)) <((length zs)*(length y)))\"\n     by auto\n then show ?thesis by auto\nqed\n\nlemma append_simpl4: \n\"(i > (length y))\n         \\<longrightarrow> ((i <((length (z#zs))*(length y)))) \n                \\<longrightarrow> ((i - (length y))< (length zs)*(length y))\"\n  using append_simpl3 by auto\n\nlemma vec_vec_Tensor_simpl: \n   \"i<(length y) \\<longrightarrow> (vec_vec_Tensor (z#zs) y)!i = (times z y)!i\" \n proof-\n have a: \"vec_vec_Tensor (z#zs) y = (times z y)@(vec_vec_Tensor zs y)\" \n      by auto\n have b: \"length (times z y) = (length y)\" using preserving_length by auto\n have \"i<(length (times z y)) \n          \\<longrightarrow> ((times z y)@(vec_vec_Tensor zs y))!i = (times z y)!i\" \n      using append_simpl by metis\n with b have \"i<(length y) \n          \\<longrightarrow> ((times z y)@(vec_vec_Tensor zs y))!i = (times z y)!i\" \n      by auto\n with  a have \"i<(length y) \n          \\<longrightarrow> (vec_vec_Tensor (z#zs) y)!i = (times z y)!i\" \n      by auto\n then show ?thesis by auto\nqed\n\n\nlemma vec_vec_Tensor_simpl2: \n  \"(i \\<ge> (length y)) \n  \\<longrightarrow> ((vec_vec_Tensor (z#zs) y)!i = (vec_vec_Tensor zs y)!(i- (length y)))\" \n    using vec_vec_Tensor.simps(2) append_simpl2  preserving_length \n    by metis\n\nlemma division_product: \n assumes \"(b::int)>0\"\n and \"a \\<ge>b\"\n shows \" (a div b) = ((a - b) div b) + 1\"\n proof-\n  fix c\n  have \"a -b \\<ge>0\" \n     using assms(2) by auto\n  have 1: \"a - b = a + (-1)*b\" \n     by auto\n  have \"(b \\<noteq> 0) \\<longrightarrow> ((a + b * (-1)) div b = (-1) + a div b)\" \n      using div_mult_self2 by metis\n  with 1 assms(1) have \"((a - b) div b) = (-1) + a div b\" \n       using comm_semiring_1_class.normalizing_semiring_rules(7) \n       less_int_code(1) by metis\n  then  have \"(a div b) = ((a - b) div b) + 1\" \n       by auto\n  then show ?thesis \n       by auto\n qed\n\nlemma int_nat_div: \n   \"(int a) div (int b) = int ((a::nat) div b)\"\n     by (metis zdiv_int)\n\nlemma int_nat_eq: \n assumes \"int (a::nat) = int b\"\n    shows \"a = b\" \n using  assms of_nat_eq_iff by auto\n\nlemma nat_div: \n assumes \"(b::nat) > 0\" \n     and \"a > b\"\n   shows \"(a div b) = ((a - b) div b) + 1\"\n proof-\n fix x\n have 1:\"(int b)>0\" \n      using assms(1) division_product by auto\n moreover have \"(int a)>(int b)\" \n      using assms(2) by auto\n with 1 have 2: \"((int a) div (int b)) \n                   = (((int a) - (int b)) div (int b)) + 1\" \n      using division_product by auto\n from int_nat_div have 3: \"((int a) div (int b)) = int ( a div b)\" \n      by auto\n from int_nat_div assms(2) have 4: \n        \"(((int a) - (int b)) div (int b)) = int ((a - b) div b)\" \n      by (metis (full_types) less_asym not_less of_nat_diff)\n have \"(int x) + 1 = int (x +1)\" \n      by auto\n with 2 3 4 have \"int (a div b) = int (((a - b) div b) + 1)\" \n      by auto\n with int_nat_eq have \"(a div b) = ((a - b) div b) + 1\" \n      by auto \n then show ?thesis by auto\n qed\n\nlemma mod_eq:\n \"(m::int) mod n = (m + (-1)*n) mod n\"\n   using mod_mult_self1 by metis\n\nlemma nat_mod_eq: \"(int (m::nat)) mod (int n) = int ( m mod n)\"\n   using Divides.transfer_int_nat_functions(2) by auto \n\nlemma nat_mod: \n assumes  \"(m::nat) > n\"\n    shows \"(m::nat) mod n = (m -n) mod n\"\n    using assms mod_if not_less_iff_gr_or_eq by auto \n\nlemma logic: \n assumes \"A \\<longrightarrow> B\" \n     and \"\\<not>A \\<longrightarrow> B\" \n   shows \"B\" \n   using assms(1) assms(2) by auto\n\ntheorem vec_vec_Tensor_elements:\nassumes \" (y \\<noteq> [])\"\nshows \n\"\\<forall>i.((i<((length x)*(length y)))\n\\<longrightarrow> ((vec_vec_Tensor x y)!i) \n             = f (x!(i div (length y))) (y!(i mod (length y))))\"\n apply(rule allI)\n proof(induct x)\n case Nil\n   have \"(length [] = 0)\" \n      by auto\n   also have \"length (vec_vec_Tensor [] y) = 0\" \n      using vec_vec_Tensor.simps(1) by auto\n   then have \"i <(length (vec_vec_Tensor [] y)) \\<Longrightarrow> False\" \n      by auto\n   moreover have \"(vec_vec_Tensor [] y) = []\" \n      by auto \n   moreover have \n   \"(i<(length (vec_vec_Tensor [] y))) \\<longrightarrow> \n   ((vec_vec_Tensor x y)!i) = f (x!(i div (length y))) (y!(i mod (length y)))\"  \n      by auto\n   then show ?case  \n      by auto\n next\n case (Cons z zs)\n   have 1:\"vec_vec_Tensor (z#zs) y = (times z y)@(vec_vec_Tensor zs y)\" \n      by auto\n   have 2:\"i<(length y)\\<longrightarrow>((times z y)!i = f z (y!i))\" \n      using times_elements by auto\n   moreover have 3:\n        \"i<(length y) \n           \\<longrightarrow> (vec_vec_Tensor (z#zs) y)!i = (times z y)!i\" \n      using vec_vec_Tensor_simpl by auto\n   moreover  have 35:\n           \"i<(length y) \\<longrightarrow> (vec_vec_Tensor (z#zs) y)!i = f z (y!i)\" \n      using calculation(1) calculation(2) by metis \n   have 4:\"(y \\<noteq> []) \\<longrightarrow> (length y) >0 \" \n      by auto \n   have \"(i <(length y)) \\<longrightarrow>  ((i div (length y)) = 0)\" \n      by auto\n   then have  6:\"(i <(length y)) \\<longrightarrow> (z#zs)!(i div (length y)) = z\" \n      using nth_Cons_0 by auto\n   then have 7:\"(i <(length y)) \\<longrightarrow> (i mod (length y)) = i\" \n      by auto\n   with 2 6  \n     have \"(i < (length y)) \n        \\<longrightarrow> (times z y)!i \n                 = f  ((z#zs)!(i div (length y))) (y! (i mod (length y)))\" \n      by auto \n    with 3 have step1:\n      \"((i < (length y)) \n          \\<longrightarrow> ((i<((length x)*(length y)) \n          \\<longrightarrow> ((vec_vec_Tensor (z#zs) y)!i \n                      =  f  \n                             ((z#zs)!(i div (length y))) \n                              (y! (i mod (length y)))))))\"\n       by auto\n    have \"((length y) \\<le> i) \\<longrightarrow> (i - (length y)) \\<ge> 0\" \n       by auto\n    have step2: \n        \"((length y) < i) \n           \\<longrightarrow> ((i < (length (z#zs)*(length y)))\n           \\<longrightarrow>((vec_vec_Tensor (z#zs) y)!i) \n                          = f \n                              ((z#zs)!(i div (length y))) \n                              (y!(i mod (length y))))\"\n         proof-\n         have \"(length y)>0\" \n           using assms by auto\n         then have 1: \n           \"(i > (length y))\n               \\<longrightarrow>(i div (length y)) = ((i-(length y)) div (length y)) + 1\" \n           using nat_div by auto\n         have \"zs!j = (z#zs)!(j+1)\" \n           by auto\n         then have \n            \"(zs!((i - (length y)) div (length y))) \n                     = (z#zs)!(((i - (length y)) div (length y))+1)\"\n           by auto\n         with 1 have 2: \n           \"(i > (length y))\n              \\<longrightarrow> (zs!((i - (length y)) div (length y)) \n                                = (z#zs)!(i div (length y)))\"\n           by auto\n         have \"(i > (length y))\n               \\<longrightarrow>((i mod (length y)) \n                                 = ((i - (length y)) mod (length y)))\" \n           using nat_mod by auto\n         then have 3:\n                \"(i > (length y))\n                    \\<longrightarrow>((y! (i mod (length y))) \n                                = (y! ((i - (length y)) mod (length y))))\" \n           by auto\n         have 4:\"(i > (length y))\n                       \\<longrightarrow>(vec_vec_Tensor (z#zs) y)!i \n                                = (vec_vec_Tensor zs y)!(i- (length y))\" \n           using vec_vec_Tensor_simpl2  by auto\n         have 5: \"(i > (length y)) \n                       \\<longrightarrow>((i <((length (z#zs))*(length y)))) \n                                = (i - (length y)< (length zs)*(length y))\"\n           by auto\n         then have 6:\n             \"\\<forall>i.((i<((length zs)*(length y)))\n                       \\<longrightarrow> ((vec_vec_Tensor zs y)!i) \n                                 = f \n                                    (zs!(i div (length y))) \n                                    (y!(i mod (length y))))\" \n           using Cons.hyps by auto\n         with 5 have \"(i > (length y))\n                       \\<longrightarrow> ((i<((length (z#zs))*(length y)))\n                       \\<longrightarrow> ((vec_vec_Tensor zs y)!(i -(length y))) \n                               = f \n                                  (zs!((i -(length y)) div (length y))) \n                                  (y!((i -(length y)) mod (length y))))\n                                   = ((i<((length zs)*(length y)))\n                                      \\<longrightarrow> ((vec_vec_Tensor zs y)!i) \n                                                = f \n                                                    (zs!(i div (length y))) \n                                                    (y!(i mod (length y))))\"\n                   by auto\n         with 6 have \n           \"(i > (length y))\n                \\<longrightarrow>((i<((length (z#zs))*(length y)))\n                \\<longrightarrow> ((vec_vec_Tensor zs y)!(i -(length y))) \n                            = f \n                               (zs!((i -(length y)) div (length y))) \n                               (y!((i -(length y))  mod (length y))))\" \n                    by auto\n         with 2 3 4 have  \n            \"(i > (length y))\n                \\<longrightarrow>((i<((length (z#zs))*(length y)))\n                \\<longrightarrow>((vec_vec_Tensor (z#zs) y)!i) \n                         =  f \n                               ((z#zs)!(i div (length y))) \n                               (y!(i mod (length y))))\"\n                    by auto\n         then show ?thesis  by auto\n         qed\n    have \"((length y) = i) \n                     \\<longrightarrow> ((i < (length (z#zs)*(length y)))\n                     \\<longrightarrow> ((vec_vec_Tensor (z#zs) y)!i) \n                                          = f \n                                              ((z#zs)!(i div (length y))) \n                                              (y!(i mod (length y))))\"\n         proof-\n         have 1:\"(i = (length y)) \n                  \\<longrightarrow> ((vec_vec_Tensor (z#zs) y)!i) \n                                        = (vec_vec_Tensor zs y)!0\" \n                  using vec_vec_Tensor_simpl2   by auto\n         have 2:\"(i = length y) \\<longrightarrow> (i mod (length y)) = 0\" \n                  by auto\n         have 3:\"(i = length y) \\<longrightarrow> (i div (length y)) = 1\" \n                  using 4 assms div_self less_numeral_extra(3)\n                  by auto\n         have 4: \"(i = length y) \n                  \\<longrightarrow> ((i < (length (z#zs))*(length y)) \n                               = (0 < (length zs)*(length y)))\" \n                  by auto\n         have \"(z#zs)!1 = (zs!0)\" \n                  by auto\n         with 3 have 5:\" (i = length y) \n                              \\<longrightarrow> ((z#zs)!(i div (length y))) = (zs!0)\" \n                  by auto \n         have \" \\<forall>i.((i < (length zs)*(length y))\n                               \\<longrightarrow>((vec_vec_Tensor (zs) y)!i) \n                                             = f \n                                                 ((zs)!(i div (length y))) \n                                                 (y!(i mod (length y))))\" \n                  using Cons.hyps by auto  \n         with 4 have 6:\"(i = length y) \n                           \\<longrightarrow> ((0 < ((length zs)*(length y)))\n                              \\<longrightarrow> (((vec_vec_Tensor (zs) y)!0) \n                                       = f ((zs)!0) (y!0))) \n                                         = ((i < ((length zs)*(length y)))\n                                               \\<longrightarrow>(((vec_vec_Tensor zs y)!i) \n                                                = f \n                                                    ((zs)!(i div (length y)))\n                                                    (y!(i mod (length y)))))\" \n                  by auto\n         have 7: \"(0 div (length y)) = 0\" \n                  by auto\n         have 8: \" (0 mod (length y)) = 0\" \n                  by auto\n         have 9: \"(0 < ((length zs)*(length y))) \n                       \\<longrightarrow> ((vec_vec_Tensor zs y)!0) \n                                           = f (zs!0) (y!0)\" \n                  using 7 8 Cons.hyps by auto\n         with  4 5 8 have \"(i = length y) \n                            \\<longrightarrow> ((i < (length (z#zs))*(length y)) \n                                     \\<longrightarrow> (((vec_vec_Tensor (zs) y)!0) \n                                             = f ((zs)!0) (y!0)))\" \n                  by auto\n         with 1 2 5 have \"(i = length y) \n                             \\<longrightarrow> ((i < (length (z#zs))*(length y)) \n                                 \\<longrightarrow> (((vec_vec_Tensor ((z#zs)) y)!i) \n                                            = f \n                                                 ((z#zs)!(i div (length y))) \n                                                 (y!(i mod (length y)))))\" \n                  by auto\n         then show ?thesis by auto\n         qed\n   with step2 have step4: \n            \"(i \\<ge> (length y)) \n                      \\<longrightarrow>  ((i < (length (z#zs))*(length y)) \n                       \\<longrightarrow> (((vec_vec_Tensor ((z#zs)) y)!i) \n                                    = f \n                                         ((z#zs)!(i div (length y))) \n                                         (y!(i mod (length y)))))\" \n         by auto\n   have \"(i < (length y)) \\<or> (i \\<ge> (length y))\" \n         by auto\n   with step1 step4 have \n            \"((i < (length (z#zs))*(length y)) \n                       \\<longrightarrow> (((vec_vec_Tensor ((z#zs)) y)!i) \n                                = f \n                                    ((z#zs)!(i div (length y))) \n                                     (y!(i mod (length y)))))\" \n         using logic by (metis \"6\" \"7\" 35) \n   then show ?case by auto\n  qed\n\ntext{*a few more results that will be used later on*}\n\nlemma nat_int:  \"nat (int x + int y) = x + y\"\nusing nat_int of_nat_add by auto\n\nlemma int_nat_equiv: \"(x > 0) \\<longrightarrow> (nat ((int x) + -1)+1) = x\"\nproof-\n have \"1 = nat (int 1)\" \n   by auto\n have \"-1 = -int 1\" \n   by auto\n  then have 1:\"(nat ((int x) + -1)+1) \n                      = (nat ((int x) + -1) + (nat (int 1)))\" \n   by auto\n  then have 2:\"(x > 0) \n                 \\<longrightarrow> nat ((int x) + -1 ) + (nat (int 1)) \n                                 =  (nat (((int x)  + -1) + (int 1)))\" \n   using of_nat_add nat_int by auto\n  have \"(nat (((int x)  + -1) + (int 1))) = (nat ((int x) + -1 + (int 1)))\" \n   by auto\n  then have \"(nat (((int x)  + -1) + (int 1))) = (nat ((int x)))\" \n   by auto\n  then have \"(nat (((int x)  + -1) + (int 1))) = x\" \n   by auto\n  with 1 2 have \" (x > 0) \\<longrightarrow> nat ((int x) + -1 ) + 1 = x\" \n   by auto\n  then show ?thesis by auto\nqed \n\nlemma list_int_nat: \"(k>0) \\<longrightarrow> ((x#xs)!k = xs!(nat ((int k)+-1)))\"  \n  proof-\n  fix  j\n  have \" ((x#xs)!(k+1) = xs!k)\" \n      by auto\n  have \"j = (k+1) \\<longrightarrow> (nat ((int j)+-1)) = k\" \n      by auto\n  moreover have \"(nat ((int j)+-1)) = k \n                  \\<longrightarrow> ((nat ((int j)+-1)) + 1) = (k +1)\" \n      by auto\n  moreover have \"(j>0)\\<longrightarrow>(((nat ((int j)+-1)) + 1) = j)\" \n      using  int_nat_equiv by (auto)\n  moreover have \"(k>0) \\<longrightarrow> ((x#xs)!k = xs!(nat ((int k)+-1)))\" \n      using Suc_eq_plus1 int_nat_equiv nth_Cons_Suc by (metis)\n  from this show ?thesis by auto\n  qed\n\n\n\nlemma row_length_eq:\"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \\<longrightarrow> \n    (row_length (a#b#N) = (row_length (b#N)))\" \n     proof-\n     have \"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n                        \\<longrightarrow> (b \\<in> set (a#b#M))\" \n           by auto\n     moreover have \n         \"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n                 \\<longrightarrow> (Ball (set (a#b#N)) (vec (row_length (a#b#N))))\"\n           using mat_def by metis\n     moreover have \"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n                       \\<longrightarrow> (b \\<in> (set (a#b#N)))\n                              \\<longrightarrow> (vec (row_length (a#b#N)) b)\"  \n           by (metis calculation(2))\n     then have \"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n                         \\<longrightarrow> (length b) = (row_length (a#b#N))\" \n                    using vec_def by auto\n     then have \"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n                          \\<longrightarrow> (row_length (b#N)) \n                                       = (row_length (a#b#N))\" \n                    using row_length_def by auto\n     then show ?thesis by auto\nqed\n\ntext{* The following theorem tells us the relationship between entries of \nvect_mat_Tensor v M and entries of v and M respectivety*}\n\ntheorem vec_mat_Tensor_elements: \n\"\\<forall>i.\\<forall>j.(((i<((length v)*(row_length M)))\\<and>(j < (length M)))\\<and>(mat (row_length M) (length M) M)\n\\<longrightarrow> ((vec_mat_Tensor v M)!j!i) = f (v!(i div (row_length M))) (M!j!(i mod (row_length M))))\"\n apply(rule allI)\n apply(rule allI)\n proof(induct M)\n case Nil\n  have \"row_length [] = 0\" \n       using row_length_def by auto\n  from this \n      have \"(length v)*(row_length []) = 0\" \n       by auto\n from this \n      have \"((i<((length v)*(row_length [])))\\<and>(j < (length []))) \\<longrightarrow> False\" \n       by auto\n moreover have \"vec_mat_Tensor v [] = []\" \n       by auto \n moreover have \"(((i<((length v)*(row_length [])))\\<and>(j < (length [])))\n                  \\<longrightarrow> ((vec_mat_Tensor v [])!j!i) \n                                = f (v!(i div (row_length []))) ([]!j!(i mod (row_length []))))\"\n       by auto\n from this \n       show ?case by auto\n next\n case (Cons a M)\n have \"(((i<((length v)*(row_length (a#M))))\n       \\<and>(j < (length (a#M))))\n       \\<and>(mat (row_length (a#M)) (length (a#M)) (a#M))\n           \\<longrightarrow> ((vec_mat_Tensor v (a#M))!j!i) \n                  = f \n                      (v!(i div (row_length (a#M)))) \n                      ((a#M)!j!(i mod (row_length (a#M)))))\"\n  proof(cases a)\n   case Nil\n     have \"row_length ([]#M) = 0\" \n          using row_length_def by auto\n     then have 1:\"(length v)*(row_length ([]#M)) = 0\" \n          by auto\n     then have \"((i<((length v)*(row_length ([]#M))))\n                \\<and>(j < (length ([]#M)))) \\<longrightarrow> False\" \n          by auto\n     moreover have \n                 \"(((i<((length v)*(row_length ([]#M))))\n                  \\<and>(j < (length ([]#M))))\n                     \\<longrightarrow> ((vec_mat_Tensor v ([]#M))!j!i) = \n                                   f \n                                        (v!(i div (row_length ([]#M)))) \n                                        ([]!j!(i mod (row_length ([]#M)))))\"\n          using calculation by auto \n     then  show ?thesis using Nil 1 less_nat_zero_code by (metis )\n  next\n  case (Cons x xs)\n     have 1:\"(a#M)!(j+1) = M!j\" by auto\n     have \"(((i<((length v)*(row_length M)))\n           \\<and>(j < (length M)))\n           \\<and>(mat (row_length M) (length M) M)\n             \\<longrightarrow> ((vec_mat_Tensor v M)!j!i) = f \n                                               (v!(i div (row_length M))) \n                                               (M!j!(i mod (row_length M))))\" \n          using Cons.hyps by auto\n     have 2: \"(row_length (a#M)) = (length a)\" \n          using row_length_def by auto\n     then have 3:\"(i< (row_length (a#M))*(length v)) \n                              = (i < (length a)*(length v))\" \n          by auto\n     have \"a \\<noteq> []\" \n          using Cons by auto\n     then have 4:\n         \"\\<forall>i.((i < (length a)*(length v)) \n              \\<longrightarrow>  ((vec_vec_Tensor v a)!i) = f \n                                               (v!(i div (length a))) \n                                               (a!(i mod (length a))))\" \n          using vec_vec_Tensor_elements Cons.hyps nat_mult_commute by auto\n  have \"(vec_mat_Tensor v (a#M))!0 = (vec_vec_Tensor v a)\" \n          using vec_mat_Tensor.simps(2) by auto\n  with 2 4 have 5: \n       \"\\<forall>i.((i < (row_length (a#M))*(length v)) \n          \\<longrightarrow>  ((vec_mat_Tensor v (a#M))!0!i) \n                                   = f \n                                       (v!(i div (row_length (a#M)))) \n                                       ((a#M)!0!(i mod (row_length (a#M)))))\" \n          by auto \n  have \"length (a#M)>0\" \n          by auto\n  with 5 have 6: \n       \"(j = 0)\\<longrightarrow>\n                    ((((i < (row_length (a#M))*(length v)) \n                    \\<and>(j < (length (a#M))))\n                    \\<and>(mat (row_length (a#M)) (length (a#M)) (a#M))  \n                         \\<longrightarrow>  ((vec_mat_Tensor v (a#M))!j!i) \n                               = f \n                                    (v!(i div (row_length (a#M)))) \n                                    ((a#M)!j!(i mod (row_length (a#M))))))\" \n          by auto \n   have \"(((i < (row_length (a#M))*(length v))\n         \\<and>(j < (length (a#M))))\n         \\<and>(mat (row_length (a#M)) (length (a#M)) (a#M)) \n          \\<longrightarrow>  \n           ((vec_mat_Tensor v (a#M))!j!i) = \n                                f \n                                         (v!(i div (row_length (a#M)))) \n                                         ((a#M)!j!(i mod (row_length (a#M)))))\" \n   proof(cases M)\n   case Nil\n    have \"(length (a#[])) = 1\" \n              by auto\n    then have \"(j<(length (a#[]))) = (j = 0)\" \n              by auto\n    then have \"((((i < (row_length (a#[]))*(length v)) \n               \\<and>(j < (length (a#[]))))\n               \\<and> (mat (row_length (a#[])) (length (a#[])) (a#[]))   \n                  \\<longrightarrow>  ((vec_mat_Tensor v (a#[]))!j!i) \n                                 = f \n                                    (v!(i div (row_length (a#[])))) \n                                     ((a#[])!j!(i mod (row_length (a#[]))))))\" \n              using 6 Nil by auto\n    then show ?thesis using Nil by auto \n   next\n   case (Cons b N)\n    have 7:\"(mat  (row_length (a#b#N))  (length (a#b#N)) (a#b#N)) \n               \\<longrightarrow> row_length (a#b#N) = (row_length (b#N))\" \n       using row_length_eq by metis\n    have 8: \"(j>0) \n            \\<longrightarrow> ((vec_mat_Tensor v (b#N))!(nat ((int j)+-1))) \n                                  = (vec_mat_Tensor v (a#b#N))!j\"\n       using vec_mat_Tensor.simps(2) using list_int_nat by metis\n    have 9: \"(j>0) \n                 \\<longrightarrow> (((i < (row_length (b#N))*(length v))\n                    \\<and>((nat ((int j)+-1)) < (length (b#N))))\n                    \\<and>(mat (row_length (b#N)) (length (b#N)) (b#N)) \n                      \\<longrightarrow>  \n             ((vec_mat_Tensor v (b#N))!(nat ((int j)+-1))!i) \n                    = f \n                      (v!(i div (row_length (b#N)))) \n                      ((b#N)!(nat ((int j)+-1))!(i mod (row_length (b#N)))))\"\n       using Cons.hyps Cons nat_mult_commute by metis\n   have \"(j>0) \\<longrightarrow> ((nat ((int j) + -1)) < (length (b#N))) \\<longrightarrow> ((nat ((int j) + -1) + 1) < length (a#b#N))\"\n       by auto\n   then have \n      \"(j>0) \n         \\<longrightarrow> ((nat ((int j) + -1)) < (length (b#N))) = (j < length (a#b#N))\"\n       by auto\n   then have  \n         \"(j>0) \n          \\<longrightarrow> (((i < (row_length (b#N))*(length v)) \\<and> (j < length (a#b#N)))\n              \\<and>(mat (row_length (b#N)) (length (b#N)) (b#N))   \\<longrightarrow>  \n                    ((vec_mat_Tensor v (b#N))!(nat ((int j)+-1))!i) \n       = f \n            (v!(i div (row_length (b#N)))) \n            ((b#N)!(nat ((int j)+-1))!(i mod (row_length (b#N)))))\"\n       using Cons.hyps Cons nat_mult_commute by metis\n   with 8 have \"(j>0) \n                 \\<longrightarrow> (((i < (row_length (b#N))*(length v)) \n                     \\<and> (j < length (a#b#N)))\n                     \\<and> (mat (row_length (b#N)) (length (b#N)) (b#N))   \n                      \\<longrightarrow>  \n         ((vec_mat_Tensor v (a#b#N))!j!i) \n                = f \n                    (v!(i div (row_length (b#N)))) \n                    ((b#N)!(nat ((int j)+-1))!(i mod (row_length (b#N)))))\"\n       by auto\n   also have \"(j>0) \\<longrightarrow> (b#N)!(nat ((int j)+-1)) = (a#b#N)!j\" \n       using list_int_nat by metis\n   moreover have \" (j>0) \\<longrightarrow> \n                    (((i < (row_length (b#N))*(length v)) \n                   \\<and> (j < length (a#b#N)))\n                   \\<and> (mat (row_length (b#N)) (length (b#N)) (b#N))   \n                     \\<longrightarrow>  \n                         ((vec_mat_Tensor v (a#b#N))!j!i) \n                                  = f \n                                      (v!(i div (row_length (b#N)))) \n                                      ((a#b#N)!j!(i mod (row_length (b#N)))))\"\n       by (metis calculation(1) calculation(2))\n   then have  \n           \"(j>0) \n             \\<longrightarrow> (((i < (row_length (b#N))*(length v)) \n                 \\<and> (j < length (a#b#N)))\n                 \\<and> (mat (row_length (a#b#N)) (length (a#b#N)) (a#b#N))   \n                 \\<longrightarrow>  \n                        ((vec_mat_Tensor v (a#b#N))!j!i) \n                              = f \n                                    (v!(i div (row_length (b#N)))) \n                                    ((a#b#N)!j!(i mod (row_length (b#N)))))\"\n      using reduct_matrix by (metis)\n   moreover  have \"(mat (row_length (a#b#N)) (length (a#b#N)) (a#b#N))\n   \\<longrightarrow>(row_length (b#N)) = (row_length (a#b#N))\" \n      by (metis \"7\" Cons)\n   moreover have 10:\"(j>0) \n                     \\<longrightarrow> (((i < (row_length (a#b#N))*(length v)) \n                        \\<and>(j < length (a#b#N)))\n                        \\<and>(mat (row_length (a#b#N)) (length (a#b#N)) (a#b#N))   \\<longrightarrow>  \n                         ((vec_mat_Tensor v (a#b#N))!j!i) \n                                = f (v!(i div (row_length (a#b#N)))) \n                                    ((a#b#N)!j!(i mod (row_length (a#b#N)))))\"\n     by (metis calculation(3) calculation(4))\n   have \"(j = 0) \\<or> (j > 0)\" \n     by auto\n   with 6 10 logic have \n     \"(((i < (row_length (a#b#N))*(length v)) \n       \\<and> (j < length (a#b#N)))\n       \\<and> (mat (row_length (a#b#N)) (length (a#b#N)) (a#b#N))   \\<longrightarrow>  \n                ((vec_mat_Tensor v (a#b#N))!j!i) \n                      = f \n                          (v!(i div (row_length (a#b#N)))) \n                          ((a#b#N)!j!(i mod (row_length (a#b#N)))))\"\n     using  Cons by metis\n     from this show ?thesis by (metis Cons)\n   qed\n  from this show ?thesis by (metis nat_mult_commute)\n  qed\n  from this show ?case by auto\n  qed\n\ntext{* The following theorem tells us about the relationship between\nentries of tensor products of two matrices and the entries of matrices*}\n\ntheorem matrix_Tensor_elements: \n fixes M1 M2\nshows\n \"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)))\n       \\<and>(j < (length M1)*(length M2)))\n       \\<and>(mat (row_length M1) (length M1) M1)\n       \\<and>(mat (row_length M2) (length M2) M2)\n            \\<longrightarrow> ((M1 \\<otimes> M2)!j!i) = \n                     f  \n                        (M1!(j div (length M2))!(i div (row_length M2))) \n                        (M2!(j mod length M2)!(i mod (row_length M2))))\"\n apply(rule allI)\n apply(rule allI)\n proof(induct M1)\n case Nil\n  have \"(row_length []) = 0\" \n          using row_length_def by auto\n  then have \"(i< ((row_length [])*(row_length M2))) \\<longrightarrow> False\" \n          by auto\n  from this have \"((i<((row_length [])*(row_length M2)))\n                 \\<and>(j < (length [])*(length M2)))\n                 \\<and>(mat (row_length []) (length []) [])\n                 \\<and>(mat (row_length M2) (length M2) M2) \n                                                 \\<longrightarrow> False\" \n          by auto\n  moreover have \"([] \\<otimes> M2) = []\" \n          by auto\n  moreover have \n          \"((i<((row_length [])*(row_length M2)))\n           \\<and>(j < (length [])*(length M2)))\n           \\<and>(mat (row_length []) (length []) [])\n           \\<and>(mat (row_length M2) (length M2) M2) \n               \\<longrightarrow> (([] \\<otimes> M2)!j!i) = \n                           f  \n                             ([]!(j div (length []))!(i div (row_length M2))) \n                              (M2!(j mod length [])!(i mod (row_length M2)))\" \n          by auto\n  then show ?case by auto\n next\n case (Cons v M)\n  fix a\n  have 0:\"(v#M) \\<otimes> M2 = (vec_mat_Tensor v M2)@(Tensor M M2)\" \n          by auto\n  then have 1:\n        \"(j<(length M2)) \\<longrightarrow> ( ((v#M) \\<otimes> M2)!j = (vec_mat_Tensor v M2)!j)\" \n          using append_simpl vec_mat_Tensor_length by metis\n  have \" (((i<((length a)*(row_length M2)))\n      \\<and>(j < (length M2)))\\<and>(mat (row_length M2) (length M2) M2)\n  \\<longrightarrow> ((vec_mat_Tensor a M2)!j!i) = f (a!(i div (row_length M2))) (M2!j!(i mod (row_length M2))))\"\n          using vec_mat_Tensor_elements by auto\n  have \"(j < (length M2)) \\<longrightarrow> (j div (length M2)) = 0\" \n          by auto\n  then have 2:\"(j < (length M2)) \\<longrightarrow> (v#M)!(j div (length M2)) = v\" \n          by auto\n  have \"(j < (length M2)) \\<longrightarrow> (j mod (length M2)) = j\" \n          by auto\n  moreover have \"(j < (length M2)) \\<longrightarrow> (v#M)!(j mod (length M2)) = (v#M)!j\" \n          by auto\n  have step0:\n    \"(j < (length M2)) \\<longrightarrow> \n               (((i<((length v)*(row_length M2)))\n              \\<and>(j < (length M2) * (length (v#M))))\n              \\<and>(mat (row_length M2) (length M2) M2)\n                  \\<longrightarrow> ((Tensor (v#M) M2)!j!i)  \n                     = f \n                         ((v#M)!(j div (length M2))!(i div (row_length M2))) \n                         (M2!(j mod (length M2))!(i mod (row_length M2))))\" \n          using 2 1  calculation(1) vec_mat_Tensor_elements by auto\n  have step1: \n     \"(j < (length M2)) \n        \\<longrightarrow> (((i<((row_length (v#M))*(row_length M2)))\n            \\<and>(j <  (length (v#M))*(length M2)))\n            \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n            \\<and>(mat (row_length M2) (length M2) M2)\n                 \\<longrightarrow> ((Tensor (v#M) M2)!j!i) =\n                   f \n                     ((v#M)!(j div (length M2))!(i div (row_length M2))) \n                     (M2!(j mod (length M2))!(i mod (row_length M2))))\" \n          using row_length_def  step0 by auto\n  from 0 have 3: \n        \"(j \\<ge> (length M2)) \\<longrightarrow> ((v#M) \\<otimes> M2)!j = (M \\<otimes> M2)!(j - (length M2))\" \n          using vec_mat_Tensor_length nat_add_commute append_simpl2 by metis\n  have 4:\n      \"(j \\<ge> (length M2)) \\<longrightarrow>\n                 (((i<((row_length M)*(row_length M2)))\n                 \\<and>((j-(length M2)) < (length M)*(length M2)))\n                 \\<and>(mat (row_length M) (length M) M)\n                 \\<and>(mat (row_length M2) (length M2) M2)\n               \\<longrightarrow> ((M \\<otimes> M2)!(j-(length M2))!i) \n              = f \n                 (M!((j-(length M2)) div (length M2))!(i div (row_length M2))) \n                 (M2!((j-(length M2)) mod length M2)!(i mod (row_length M2))))\" \n          using Cons.hyps by auto\n  moreover have \"(mat (row_length (v#M)) (length (v#M)) (v#M))\n                              \\<longrightarrow>(mat (row_length M) (length M) M)\"\n          using reduct_matrix by auto\n  moreover have 5:\n      \"(j \\<ge> (length M2)) \n        \\<longrightarrow> (((i<((row_length M)*(row_length M2)))\n         \\<and>((j-(length M2)) < (length M)*(length M2)))\n         \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n         \\<and>(mat (row_length M2) (length M2) M2)\n         \\<longrightarrow> ((M \\<otimes> M2)!(j-(length M2))!i) \n              = f \n                (M!((j-(length M2)) div (length M2))!(i div (row_length M2))) \n                (M2!((j-(length M2)) mod length M2)!(i mod (row_length M2))))\"\n          using 4 calculation(3) by metis\n  have \"(((j-(length M2)) < (length M)*(length M2))) \n                        \\<longrightarrow> (j < ((length M)+1)*(length M2))\" \n          by auto\n  then have 6:\n        \"(((j-(length M2)) < (length M)*(length M2))) \n              \\<longrightarrow> \n               (j < ((length (v#M))*(length M2)))\" \n          by auto\n  have 7: \n      \"(j \\<ge> (length M2)) \n        \\<longrightarrow> \n          ((j-(length M2)) div (length M2)) = ((j div (length M2)) - 1)\"\n          using  add_diff_cancel_left' div_add_self1 div_by_0 \n          le_imp_diff_is_add nat_add_commute zero_diff\n          by metis\n  then have 8:\n      \"(j \\<ge> (length M2)) \n         \\<longrightarrow> \n          M!((j-(length M2)) div (length M2)) \n                      = M!((j div (length M2)) - 1)\" \n          by auto\n  have step2:\n   \"(j \\<ge> (length M2)) \n      \\<longrightarrow>\n       (((i<((row_length (v#M))*(row_length M2)))\n       \\<and>(j < (length (v#M))*(length M2)))\n       \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n       \\<and>(mat (row_length M2) (length M2) M2))\n      \\<longrightarrow>(((v#M) \\<otimes> M2)!j!i) = \n                          f \n                         ((v#M)!(j div (length M2))!(i div (row_length M2))) \n                         (M2!(j mod length M2)!(i mod (row_length M2)))\"\n  proof(cases M2)\n  case Nil\n   have \"(0 = ((row_length (v#M))*(row_length M2)))\" \n          using row_length_def Nil mult_0_right by auto\n   then have \"(i < ((row_length (v#M))*(row_length M2))) \\<longrightarrow> False\" \n          by auto\n   then have \" (j \\<ge> (length M2)) \n                 \\<longrightarrow>(((i<((row_length (v#M))*(row_length M2)))\n                    \\<and>(j < (length (v#M))*(length M2)))\n                    \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n                    \\<and>(mat (row_length M2) (length M2) M2)) \n                            \\<longrightarrow> False\"\n          by auto\n   then show ?thesis by auto\n  next\n  case (Cons w N)\n   fix k\n   have \"(k < (length M))\\<and> (k \\<ge> 1) \\<longrightarrow> M!(k - 1)  = (v#M)!k\" \n        using   not_one_le_zero nth_Cons' by auto\n   have \"(j \\<ge> (length (w#N))) \\<longrightarrow> (j div (length (w#N))) \\<ge> 1\"\n        using  div_le_mono div_self length_0_conv neq_Nil_conv  by metis\n   moreover have \"(j \\<ge> (length (w#N))) \\<longrightarrow> (j div (length (w#N)))- 1  \\<ge> 0\" \n        by auto\n   moreover have \"(j \\<ge> (length (w#N))) \n                          \\<longrightarrow> M!((j div (length (w#N)))- 1 ) \n                                 = (v#M)!(j div (length (w#N)))\" \n        using calculation(1) not_one_le_zero nth_Cons' by auto\n   from this 7 have 9:\" (j \\<ge> (length (w#N))) \n                         \\<longrightarrow>  M!((j-(length (w#N))) div (length (w#N))) \n                                   = (v#M)!(j div (length (w#N)))\" \n        using Cons by auto\n   have 10: \"(j \\<ge> (length (w#N))) \n                     \\<longrightarrow>  ((j-(length (w#N))) mod (length (w#N))) \n                                   = (j mod(length (w#N)))\" \n        using mod_if not_less by auto \n   with 5 9  have \n   \"(j \\<ge> (length (w#N))) \\<longrightarrow>\n    ((i<((row_length M)*(row_length (w#N))))\n    \\<and>((j-(length (w#N))) < (length M)*(length (w#N)))\n    \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M)) \n    \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N)))\n    \\<longrightarrow> (((M \\<otimes> (w#N))!(j-(length (w#N)))!i) \n          = f \n              ((v#M)!(j div (length (w#N)))!(i div (row_length (w#N))))\n              ((w#N)!(j mod length (w#N))!(i mod (row_length (w#N)))))\" \n        using Cons by auto \n   then have \n     \"(j \\<ge> (length (w#N))) \\<longrightarrow>\n                ((i<((row_length M)*(row_length (w#N))))\n                \\<and>(j <(length (v#M))*(length (w#N)))\n                \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M)) \n                \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N)))\n                \\<longrightarrow> (((M \\<otimes> (w#N))!(j-(length (w#N)))!i) \n                 = f \n                    ((v#M)!(j div (length (w#N)))!(i div (row_length (w#N))))\n                    ((w#N)!(j mod length (w#N))!(i mod (row_length (w#N)))))\" \n        using 6 by auto\n   then have 11: \n    \"(j \\<ge> (length (w#N))) \\<longrightarrow>\n            ((i<((row_length M)*(row_length (w#N))))\n            \\<and>(j <(length (v#M))*(length (w#N)))\n            \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n            \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N)))\n            \\<longrightarrow> (((v#M) \\<otimes> (w#N))!j!i) = \n                    f \n                    ((v#M)!(j div (length (w#N)))!(i div (row_length (w#N))))\n                    ((w#N)!(j mod length (w#N))!(i mod (row_length (w#N))))\" \n        using 3 Cons by auto\n    have \n     \"(j \\<ge> (length (w#N))) \\<longrightarrow>\n              ((i<((row_length (v#M))*(row_length (w#N))))\n              \\<and>(j <(length (v#M))*(length (w#N)))\n              \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n              \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N)))\n                     \\<longrightarrow> (((v#M) \\<otimes> (w#N))!j!i) \n                = f \n                    ((v#M)!(j div (length (w#N)))!(i div (row_length (w#N))))\n                    ((w#N)!(j mod length (w#N))!(i mod (row_length (w#N))))\"\n    proof(cases M)\n    case Nil \n       have Nil0:\"(length (v#[])) = 1\" \n                    by auto\n       then have Nil1:\n             \"(j <(length (v#[]))*(length (w#N))) = (j< (length (w#N)))\" \n                      by (metis Nil nat_mult_1) \n       have \n              \"row_length (v#[]) = (length v)\" \n                      using row_length_def by auto\n       then have Nil2:\n              \"(i<((row_length (v#M))*(row_length (w#N)))) \n                                 = (i<((length v)*(row_length (w#N))))\"\n                      using Nil by auto\n       then have \"(j< (length (w#N))) \\<longrightarrow> (j div (length (w#N))) = 0\" \n                      by auto\n       from this have Nil3:\n                 \"(j< (length (w#N))) \\<longrightarrow> (v#M)!(j div (length (w#N))) = v\" \n                      using Nil by auto\n       then have Nil4:\n                 \"(j< (length (w#N))) \\<longrightarrow> (j mod (length (w#N))) = j\" \n                      by auto\n       then have Nil5:\"(v#M) \\<otimes> (w#N) = vec_mat_Tensor v (w#N)\" \n                      using Nil Tensor.simps(2) Tensor.simps(1)\n                      by auto\n       from vec_mat_Tensor_elements have \n                      \"(((i<((length v)*(row_length (w#N))))\n                       \\<and>(j < (length (w#N))))\n                       \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N))\n                          \\<longrightarrow> ((vec_mat_Tensor v (w#N))!j!i) \n                                    = f \n                                       (v!(i div (row_length (w#N)))) \n                                       ((w#N)!j!(i mod (row_length (w#N)))))\" \n                      by metis\n       then have \n            \"((i<((row_length (v#M))*(row_length (w#N))))\n             \\<and>(j < ((length (v#M))*(length (w#N))))\n             \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N))\n         \\<longrightarrow> ((vec_mat_Tensor v (w#N))!j!i) \n                    = f (v!(i div (row_length (w#N)))) \n                        ((w#N)!j!(i mod (row_length (w#N)))))\"\n                  using Nil1 Nil2 Nil by auto\n       then have  \n            \"((i<((row_length (v#M))*(row_length (w#N))))\n             \\<and>(j < ((length (v#M))*(length (w#N))))\n             \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N))\n          \\<longrightarrow> (((v#M)\\<otimes>(w#N))!j!i) \n                     = f \n                        ((v#M)!(j div (length (w#N)))!(i div (row_length (w#N)))) \n                        ((w#N)!(j mod (length (w#N)))!(i mod (row_length (w#N)))))\"\n                   using Nil3 Nil4  Nil5 Nil by auto\n        then have \n             \"((i<((row_length (v#M))*(row_length (w#N))))\n             \\<and>(j < ((length (v#M))*(length (w#N))))\n             \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n             \\<and>(mat (row_length (w#N)) (length (w#N)) (w#N))\n                  \\<longrightarrow> (((v#M)\\<otimes>(w#N))!j!i) \n                       = f \n                         ((v#M)!(j div (length (w#N)))!(i div (row_length (w#N)))) \n                         ((w#N)!(j mod (length (w#N)))!(i mod (row_length (w#N)))))\" by auto\n       from this show ?thesis by auto\n       next\n    case (Cons u P)\n       have \"(mat (row_length (v#M)) (length (v#M)) (v#M)) \\<longrightarrow> (row_length (v#M)) = (row_length M)\"\n          using Cons row_length_eq by metis\n       from this 11 show ?thesis by auto\n    qed\n   from this show ?thesis using Cons by auto \n   qed \n  have \"(j<(length M2)) \\<or> (j \\<ge> (length M2))\" by auto\n  from this step1 step2 logic have  \n     \"(((i<((row_length (v#M))*(row_length M2)))\n      \\<and>(j < (length M2) * (length (v#M))))\n      \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n      \\<and>(mat (row_length M2) (length M2) M2)        \n      \\<longrightarrow> ( ((v#M) \\<otimes> M2)!j!i) \n                 = f \n                     ((v#M)!(j div (length M2))!(i div (row_length M2))) \n                     (M2!(j mod (length M2))!(i mod (row_length M2))))\" \n          using  nat_mult_commute by metis\n  from this show ?case by (metis nat_mult_commute)\n  qed\n   \n\ntext{* we restate the theorem in two different forms for convenience \nof reuse*}\n\n\n\ntheorem effective_matrix_tensor_elements2:\n assumes  \" i<(row_length M1)*(row_length M2)\"\n and \"j < (length M1)*(length M2)\"\n and \"mat (row_length M1) (length M1) M1\"\n and \"mat (row_length M2) (length M2) M2\"\n shows \"(M1 \\<otimes> M2)!j!i = \n             (M1!(j div (length M2))!(i div (row_length M2)))\n              * (M2!(j mod length M2)!(i mod (row_length M2)))\"\n using assms matrix_Tensor_elements by auto\n\ntext{* the following lemmas are useful in proving associativity of tensor\nproducts*}\n\nlemma div_left_ineq:\n      assumes \"(x::nat) < y*z\" \n      shows \" (x div z) < y\"\n     proof(rule ccontr)\n     assume 0: \" \\<not>((x div z) < y)\"\n     then have 1:\" x div z \\<ge> y\"\n                 by auto\n     then have 2:\"(x div z)*z \\<ge> y*z\"\n            by auto\n     then have 3:\"(x div z)*z + (x mod z) = z\"\n          using mod_div_equality  by (metis add_leD1 assms div_mod_equality' le_diff_conv2 mod_less_eq_dividend not_less)\n     then have 4:\"(x div z)*z \\<le> z\"\n                by auto\n     then have 5:\"z \\<ge> y*z\"\n                using 2 by auto\n     then have 6:\"z div z \\<ge> (y*z) div z\"\n                by auto\n     then have \"(y*z) div z \\<le> 1\"\n                 by auto                \n      with 6 have \"1 \\<ge> y\"\n                using 1 3 assms \n                      comm_semiring_1_class.normalizing_semiring_rules(24) \n                      div_self less_nat_zero_code mult_zero_left \n                      nat_mult_commute semiring_div_class.mod_div_equality'\n                by metis\n     then have 7:\"(y = 0) \\<or> (y = 1)\"\n                by auto\n     have \"(y = 0 ) \\<Longrightarrow> x<0\"\n                using assms by auto\n     moreover have \"x \\<ge> 0\"\n                by auto\n     then have 8:\"(y = 0) \\<Longrightarrow> False\"\n                using calculation  less_nat_zero_code by auto\n     moreover have \"(y = 1) \\<Longrightarrow> ( x < z)\"\n                using assms by auto\n     then have \"(y = 1) \\<Longrightarrow> (x div z) = 0\"\n               by (metis div_less) \n     then have \"(y = 1) \\<Longrightarrow>(x div z) < y\"\n                 by auto\n      then have \"(y = 1) \\<Longrightarrow> False\"\n                   using 0 by auto\n      then show False using 7 8 by auto\nqed\n\nlemma div_right_ineq:\n      assumes \"(x::nat) < y*z\" \n      shows \" (x div y) < z\"\n           using assms div_left_ineq nat_mult_commute  \n               by (metis)\n\ntext{* In the following theorem, we obtain columns of vec$\\_$mat$\\_$Tensor of \na vector v and a matrix M in terms of the vector v and columns of the \nmatrix M*}\n\nlemma col_vec_mat_Tensor_prelim:\" \\<forall>j.(j < (length M) \\<longrightarrow>\ncol (vec_mat_Tensor v M) j = vec_vec_Tensor v (col M j))\"\n   unfolding col_def \n   apply(rule allI)\nproof(induct M)\n case Nil\n    show ?case using Nil by auto\n next\n case (Cons w N)\n    have Cons_1:\"vec_mat_Tensor v (w#N) \n                        = (vec_vec_Tensor v w)#(vec_mat_Tensor v N)\"\n              using vec_mat_Tensor.simps Cons by auto\n    then show ?case\n     proof(cases j)\n     case 0\n       have \"vec_mat_Tensor v (w#N)!0 =  (vec_vec_Tensor v w)\"\n           by auto\n       then show ?thesis using 0 by auto\n    next\n    case (Suc k) \n      have \" vec_mat_Tensor v (w#N)!j = (vec_mat_Tensor v N)!(k)\"  \n                 using Cons_1 Suc by auto\n      moreover have \"j < length (w#N) \\<Longrightarrow> k < length N\"\n         using Suc  by (metis length_Suc_conv not_less_eq)\n      moreover then have \"k < length (N) \n                  \\<Longrightarrow> (vec_mat_Tensor v N)!k =   vec_vec_Tensor v (N!k)\"\n               using Cons.hyps  by auto\n      ultimately show ?thesis using Suc by auto\n     qed\nqed\n\nlemma col_vec_mat_Tensor:fixes j M v\n assumes \"j < (length M)\" \n shows \"col (vec_mat_Tensor v M) j = vec_vec_Tensor v (col M j)\"\n  using col_vec_mat_Tensor_prelim assms by auto\n\nlemma  col_formula:\n fixes M1 and M2\nshows \"\\<forall>j.((j < (length M1)*(length M2)) \n         \\<and> (mat (row_length M1) (length M1) M1)\n         \\<and> (mat (row_length M2) (length M2) M2)\n         \\<longrightarrow> col (M1 \\<otimes> M2) j \n                =  vec_vec_Tensor \n                        (col M1 (j div length M2)) \n                        (col M2 (j mod length M2)))\"\n apply (rule allI)\n proof(induct M1)\n case Nil\n    show ?case using Nil by auto\n next\n case (Cons v M)\n  have \"j < (length (v#M))*(length M2) \n       \\<and> mat (row_length (v # M)) (length (v # M)) (v # M) \n       \\<and> mat (row_length M2) (length M2) M2 \\<Longrightarrow>\n       (col (v # M \\<otimes> M2) j \n                 = vec_vec_Tensor \n                            (col (v # M) (j div length M2)) \n                            (col M2 (j mod length M2)))\"\n     proof-\n      fix k\n      assume 0:\"j < (length (v#M))*(length M2) \n              \\<and> mat (row_length (v # M)) (length (v # M)) (v # M) \n              \\<and> mat (row_length M2) (length M2) M2\"\n      then have 1:\"mat (row_length M) (length M) M\"\n             by (metis reduct_matrix)\n      have \"j < (1+ length M)*(length M2)\"\n             using 0 by auto\n      then have \"j < (length M2)+  (length M)*(length M2)\"\n             by auto   \n      then have 2:\"j \\<ge> (length M2) \n                          \\<Longrightarrow> j- (length M2) < (length M)*(length M2)\"\n             using add_0_iff add_diff_inverse diff_is_0_eq \n                   less_diff_conv less_imp_le linorder_cases nat_add_commute \n                   neq0_conv\n             by (metis (hide_lams, no_types))\n      have 3:\"(v#M)\\<otimes>M2 = (vec_mat_Tensor v M2)@(M \\<otimes> M2)\"\n             using Tensor.simps by auto\n      have \"(col ((v#M)\\<otimes>M2) j) = (col ((vec_mat_Tensor v M2)@(M \\<otimes> M2)) j)\"\n             using col_def by auto\n      then have \"j < length (vec_mat_Tensor v M2) \n                   \\<Longrightarrow> (col ((v#M)\\<otimes>M2) j) = (col (vec_mat_Tensor v M2) j)\"\n             unfolding col_def using append_simpl by auto \n      then have 4:\"j < length M2 \\<Longrightarrow>\n                        (col ((v#M)\\<otimes>M2) j) = (col (vec_mat_Tensor v M2) j)\"\n             using vec_mat_Tensor_length by simp \n       then have \"j < length M2 \\<Longrightarrow>  \n                   (col (vec_mat_Tensor v M2) j) \n                                      =  vec_vec_Tensor v (col M2 j)\"\n             using col_vec_mat_Tensor by auto\n       then have \n           \"j< length M2 \\<Longrightarrow> \n                 (col (vec_mat_Tensor v M2) j) \n                            =  vec_vec_Tensor \n                                            ((v#M)!(j div length M2)) \n                                            (col M2 (j mod (length M2)))\"\n             by auto\n        then have step_1:\"j< length M2 \\<Longrightarrow> \n                 (col ((v#M)\\<otimes> M2) j) \n                             =  vec_vec_Tensor \n                                             ((v#M)!(j div length M2)) \n                                             (col M2 (j mod (length M2)))\"\n             using 4 by auto\n        have 4:\"j \\<ge> length M2 \n                  \\<Longrightarrow> (col ((v#M)\\<otimes>M2) j)= (M \\<otimes> M2)!(j- (length M2))\"\n             unfolding col_def  using 3 append_simpl2 vec_mat_Tensor_length \n             by metis\n        then have 5:\n         \"j \\<ge> length M2 \\<Longrightarrow> \n              col (M \\<otimes> M2) (j-length M2) \n                     = vec_vec_Tensor \n                                (col M ((j-length M2) div length M2)) \n                                (col M2 ((j- length M2) mod length M2))\"\n             using 1 0 2 Cons by auto\n        then have 6:\n         \"j \\<ge> length M2 \\<Longrightarrow> \n                 (j - length M2) div (length M2) + 1 = j div (length M2)\"\n             using 2 comm_monoid_diff_class.diff_cancel div_0 div_self \n                   le_neq_implies_less less_nat_zero_code \n                   monoid_add_class.add.right_neutral mult_0 mult_cancel2 \n                   nat_add_commute nat_div neq0_conv      \n             by metis\n        then have \n           \"j \\<ge> length M2 \\<Longrightarrow> \n                    ((j- length M2) mod length M2) = j mod (length M2)\"\n              using le_mod_geq by metis \n        with 6  have 7:\n         \"j \\<ge> length M2 \\<Longrightarrow> \n              col (M \\<otimes> M2) (j-length M2) \n                     = vec_vec_Tensor (col M ((j-length M2) div length M2)) \n                                (col M2 (j mod length M2))\"\n              using 5 by auto\n        moreover have \"k<(length M) \\<Longrightarrow> (col M k) = (col (v#M) (k+1))\"\n                            unfolding col_def by auto\n        ultimately have \"j \\<ge> length M2 \\<Longrightarrow> \n              col (M \\<otimes> M2) (j-length M2) \n                     = vec_vec_Tensor (col (v#M) (j div length M2)) \n                                (col M2 (j mod length M2))\"\n                   proof-\n                    assume temp:\"j \\<ge> length M2 \"\n                    have \" j- (length M2) < (length M)*(length M2)\"    \n                          using 2 temp by auto\n                    then have \"(j- (length M2)) div (length M2) < (length M)\"\n                            using div_right_ineq nat_mult_commute by auto\n                    moreover have \n                    \"((j- (length M2)) div (length M2)<(length M) \n                     \\<longrightarrow> (col M ((j- (length M2)) div (length M2))) \n                          = (col (v#M) ((j- (length M2)) div (length M2)+1)))\"\n                            unfolding col_def by auto\n                    ultimately have temp1:\n                      \"(col (v#M) (((j-length M2) div length M2)+1)) \n                                  = (col M (((j-length M2) div length M2)))\"\n                                  by auto\n                    then have \"(col (v#M) (((j-length M2) div length M2)+1)) \n                                   = (col (v#M) (j div length M2))\"\n                                   using 6 temp by auto\n                   then show ?thesis using temp1 7 by (metis temp) \n                  qed\n           then have \"j \\<ge> length M2 \\<Longrightarrow> \n              col ((v#M) \\<otimes> M2) j \n                     = vec_vec_Tensor (col (v#M) (j div length M2)) \n                                (col M2 (j mod length M2))\"\n                   using col_def 4 by metis\n          then show ?thesis \n                     using step_1  col_def le_refl nat_less_le nat_neq_iff\n                     by (metis)\n        qed\n then show ?case by auto\nqed\n\nlemma row_Cons:\"row (v#M) i = (v!i)#(row M i)\"\n          unfolding row_def map_def by auto\n\nlemma row_append:\"row (A@B)i = (row A i)@(row B i)\"\n  unfolding row_def map_append by auto \n\nlemma row_empty:\"row [] i = []\"\n       unfolding row_def by auto\n\nlemma vec_vec_Tensor_right_empty:\"vec_vec_Tensor x [] = []\"\n        using vec_vec_Tensor.simps times.simps \n        length_0_conv mult_0_right vec_vec_Tensor_length  \n        by (metis)\n\nlemma \"vec_mat_Tensor v ([]#[]) = [[]] \"\n   using vec_mat_Tensor.simps by (metis vec_vec_Tensor_right_empty)\n\nlemma \"i<0 \\<longrightarrow> [[]!i] = []\"\n         by auto\n\nlemma row_vec_mat_Tensor_prelim:\n \"\\<forall>i.\n     ((i < (length v)*(row_length M))\\<and>(mat nr (length M) M) \n      \\<longrightarrow> row (vec_mat_Tensor v M) i \n            = times (v!(i div row_length M)) (row M (i mod row_length M)))\"\n apply(rule allI)\n proof(induct M)\n case Nil\n    show ?case using Nil by (metis less_nat_zero_code mult_0_right row_length_Nil)\n next\n case (Cons w N) \n   have \"row (vec_mat_Tensor v (w#N)) i \n                      =  row ((vec_vec_Tensor v w)#(vec_mat_Tensor v N)) i\"\n           using vec_mat_Tensor.simps by auto\n   then have 1:\"...   = ((vec_vec_Tensor v w)!i)#(row (vec_mat_Tensor v N) i)\"\n           using row_Cons by auto\n   have 2:\"row_length (w#N) = length w\"\n              using row_length_def by auto\n   then have 3:\"(mat nr (length (w#N)) (w#N)) \\<Longrightarrow> nr = length w\"\n              using  hd_in_set list.distinct(1) \n              mat_uniqueness matrix_row_length by metis\n   then have   \"((i < (length v)*(row_length (w#N))) \n               \\<and> (mat nr (length (w#N)) (w#N)) \n                 \\<Longrightarrow> row (vec_mat_Tensor v (w#N)) i \n                           = times \n                                 (v!(i div row_length (w#N))) \n                                 (row (w#N) (i mod row_length (w#N))))\" \n       proof-\n       assume assms: \"i < (length v)*(row_length (w#N)) \n                     \\<and> (mat nr (length (w#N)) (w#N))\"   \n       show ?thesis    \n       proof(cases N)\n       case Nil\n         have \"row (vec_mat_Tensor v (w#N)) i = [(vec_vec_Tensor v w)!i]\"\n                   using 1 vec_mat_Tensor.simps  Nil row_empty by auto  \n         then show ?thesis\n           proof(cases w)\n           case Nil\n              have \"(vec_vec_Tensor v w) = []\"\n                   using Nil vec_vec_Tensor_right_empty by auto\n              moreover have \" (length v)*(row_length (w#N)) = 0\"\n                        using Nil row_length_def  by auto\n              then have \" [(vec_vec_Tensor v [])!i] = []\"\n                using assms less_nat_zero_code by metis\n              ultimately show ?thesis \n                   using vec_vec_Tensor.simps row_empty Nil assms \n                   list.distinct(1) by (metis)\n           next\n           case (Cons a w1)\n               have 1:\"w \\<noteq> []\"\n                    using Cons by auto\n               then have \"i < (length v)*(length w)\"\n                             using assms row_length_def by auto\n               then have \"(vec_vec_Tensor v w)!i  \n                                       = f \n                                           (v!(i div (length w))) \n                                           (w!(i mod (length w)))\"\n                        using vec_vec_Tensor_elements 1 allI by auto\n                then have \"(row (vec_mat_Tensor v (w#N)) i)\n                                = times \n                                      (v!(i div row_length (w#N))) \n                                      (row (w#N) (i mod (length w)))\"\n                        using Cons vec_mat_Tensor.simps row_def \n                        row_length_def 2 Nil row_Cons row_empty times.simps(1) \n                        times.simps(2)  by metis\n              then show ?thesis using row_def 2 by metis\n            qed\n         next\n         case (Cons w1 N1)\n          have Cons_0:\"row_length N = length w1\"\n                    using Cons row_length_def by auto\n          have \"mat nr (length (w#w1#N1)) (w#w1#N1)\"\n                      using assms Cons by auto\n          then have Cons_1:\n                     \"mat (row_length (w#w1#N1)) (length (w#w1#N1)) (w#w1#N1)\" \n                        by (metis matrix_row_length)\n          then have Cons_2:\n                     \"mat (row_length (w1#N1)) (length (w1#N1)) (w1#N1)\" \n                       by (metis reduct_matrix)\n          then have Cons_3:\"(length w1 = length w)\"\n                       using Cons_1 \n                       unfolding mat_def row_length_def Ball_def vec_def \n                       by (metis Cons_1 hd.simps list.distinct(1) \n                       row_length_def row_length_eq)\n          then have Cons_4:\"mat nr (length (w1#N1)) (w1#N1)\"                \n                        using 3 Cons_2 assms hd_conv_nth list.distinct(1) \n                        nth_Cons_0 row_length_def\n                        by metis  \n          moreover have \"i < (length v)*(row_length (w1#N1))\"\n                          using assms Cons_3 row_length_def by auto\n          ultimately have Cons_5:\"row (vec_mat_Tensor v N) i \n                                  = times \n                                      (v ! (i div row_length N)) \n                                      (row N (i mod row_length N))\"\n                            using Cons  Cons.hyps by auto \n          then show ?thesis\n            proof(cases w)\n            case Nil\n              have \"(vec_vec_Tensor v w) = []\"\n                   using Nil vec_vec_Tensor_right_empty by auto\n              moreover have \" (length v)*(row_length (w#N)) = 0\"\n                        using Nil row_length_def  by auto\n              then have \" [(vec_vec_Tensor v [])!i] = []\"\n                using assms   by (metis less_nat_zero_code)\n              ultimately show ?thesis \n                            using vec_vec_Tensor.simps row_empty Nil assms\n                            by (metis list.distinct(1))               \n             next\n             case (Cons a w2)\n                  have 1:\"w \\<noteq> []\"\n                    using Cons by auto\n               then have \"i < (length v)*(length w)\"\n                             using assms row_length_def by auto\n               then have ConsCons_2:\n                     \"(vec_vec_Tensor v w)!i = f \n                                                 (v!(i div (length w))) \n                                                 (w!(i mod (length w)))\"\n                        using vec_vec_Tensor_elements 1 allI by auto\n               moreover have \n                      \"times \n                              (v!(i div row_length (w#N))) \n                              (row (w#N) (i mod row_length (w#N))) \n                             = (f \n                                 (v!(i div (length w))) \n                                 (w!(i mod (length w))))\n                                  #(times (v ! (i div row_length N)) \n                                          (row N (i mod row_length N)))\"\n                  proof-\n                  have temp:\"row_length (w#N) = (row_length N)\"\n                            using row_length_def 2 Cons_3 Cons_0 by auto\n                  have \"(row (w#N) (i mod row_length (w#N))) \n                              = (w!(i mod (row_length (w#N))))\n                                       #(row N (i mod row_length (w#N)))\"\n                           unfolding row_def  by auto                     \n                  then have \"...\n                              = (w!(i mod (length w)))\n                                        #(row N (i mod row_length N))\"\n                           using Cons_3 3 assms 2 neq_Nil_conv row_Cons row_empty \n                           row_length_eq by (metis (hide_lams, no_types))\n                  then have \"times \n                               (v!(i div row_length (w#N)))  \n                               ((w!(i mod (length w)))\n                                           #(row N (i mod row_length N)))\n                               = (f  \n                                     (v!(i div row_length (w#N))) \n                                     (w!(i mod (length w))))\n                                         #(times  (v!(i div row_length (w#N)))\n                                                      (row N (i mod row_length N)))\"\n                           by auto\n                   then have \"... =  (f  \n                                       (v!(i div length w)) \n                                       (w!(i mod (length w))))\n                                         #(times  (v!(i div row_length N))\n                                                  (row N (i mod row_length N)))\"         \n                              using 3 Cons_3 assms temp row_length_def by auto \n                   then show ?thesis using times.simps 2 row_Cons temp by metis\n                 qed\n             then show ?thesis using Cons_5 ConsCons_2 1 \n                                row_Cons vec_mat_Tensor.simps(2) by (metis)\n             qed\n           qed\n          qed             \n       then show ?case by auto\n qed\n\ntext{*The following lemma gives us a formula for the row of a tensor of \ntwo matrices*}\n\nlemma  row_formula:\n fixes M1 and M2\n shows \"\\<forall>i.((i < (row_length M1)*(row_length M2))\n          \\<and>(mat (row_length M1) (length M1) M1)\n          \\<and>(mat (row_length M2) (length M2) M2)\n             \\<longrightarrow> row (M1 \\<otimes> M2) i \n                        =  vec_vec_Tensor \n                                 (row M1 (i div row_length M2)) \n                                 (row M2 (i mod row_length M2)))\"\n apply(rule allI)\n proof(induct M1)\n case Nil\n      show ?case using Nil by (metis less_nat_zero_code mult_0 row_length_Nil)\n next\n case (Cons v M)\n  have \n    \"((i < (row_length (v#M))*(row_length M2))  \n    \\<and> (mat (row_length (v#M)) (length (v#M)) (v#M))\n    \\<and> (mat (row_length M2) (length M2) M2)\n     \\<Longrightarrow> row ((v#M) \\<otimes> M2) i =  vec_vec_Tensor \n                                    (row (v#M) (i div row_length M2)) \n                                    (row M2 (i mod row_length M2)))\"\n   proof-\n    assume assms:\n                 \"(i < (row_length (v#M))*(row_length M2)) \n                 \\<and>(mat (row_length (v#M)) (length (v#M)) (v#M))\n                 \\<and>(mat (row_length M2) (length M2) M2)\"\n    have 0:\"i < (length v)*(row_length M2)\"\n             using assms row_length_def by auto  \n    have 1:\"mat (row_length M) (length M) M\"\n            using assms  reduct_matrix by (metis)\n    have \"row ((v#M)\\<otimes>M2) i = row ((vec_mat_Tensor v M2)@(M \\<otimes> M2)) i\"\n                 by auto\n    then have 2:\"... = (row (vec_mat_Tensor v M2) i)@(row (M \\<otimes> M2) i)\"\n                 using row_append by auto \n    then show ?thesis\n       proof(cases M)\n       case Nil\n         have \"row ((v#M)\\<otimes>M2) i = (row (vec_mat_Tensor v M2) i)\"\n                   using Nil 2 by auto\n         moreover have \"row (vec_mat_Tensor v M2) i =  times \n                                                (v!(i div row_length M2)) \n                                                (row M2 (i mod row_length M2))\"\n                    using row_vec_mat_Tensor_prelim assms 0 by auto\n         ultimately show ?thesis using vec_vec_Tensor_def \n             Nil append_Nil2 vec_vec_Tensor.simps(1) \n             vec_vec_Tensor.simps(2) row_Cons row_empty  by (metis)\n       next\n       case (Cons w N)\n        have Cons_Cons_1:\" mat (row_length M) (length M) M\"\n                     using assms reduct_matrix by auto\n        then have \"row_length (w#N) = row_length (v#M)\"\n                        using assms Cons unfolding mat_def Ball_def vec_def  \n                        using append_Cons hd.simps hd_in_set list.distinct(1) \n                        rotate1.simps(2) set_rotate1\n                        by metis\n        then have Cons_Cons_2:\"i < (row_length M)*(row_length M2)\"\n                        using assms Cons by auto\n        then have Cons_Cons_3:\"(row (M \\<otimes> M2) i) =  vec_vec_Tensor \n                                          (row M (i div row_length M2)) \n                                           (row M2 (i mod row_length M2))\"\n                       using Cons.hyps Cons_Cons_1 assms by auto\n         moreover have \"row (vec_mat_Tensor v M2) i   \n                                            =  times \n                                               (v!(i div row_length M2)) \n                                               (row M2 (i mod row_length M2))\"\n                        using row_vec_mat_Tensor_prelim assms 0 by auto\n        then have \"row ((v#M)\\<otimes>M2) i = \n                           (times \n                                   (v!(i div row_length M2)) \n                                    (row M2 (i mod row_length M2)))\n                                      @(vec_vec_Tensor \n                                          (row M (i div row_length M2)) \n                                           (row M2 (i mod row_length M2)))\"   \n                            using 2 Cons_Cons_3 by auto\n        moreover have \"... = (vec_vec_Tensor \n                                        ((v!(i div row_length M2))\n                                             #(row M (i div row_length M2)))\n                                        (row M2 (i mod row_length M2)))\"\n                             using vec_vec_Tensor.simps(2) by auto\n        moreover have \"... = (vec_vec_Tensor (row (v#M) (i div row_length M2))\n                                           (row M2 (i mod row_length M2)))\" \n                       using row_Cons by metis\n        ultimately show ?thesis by metis\n       qed\n     qed\n   then show ?case by auto\nqed  \n\nlemma  effective_row_formula:\n fixes M1 and M2\nassumes \"i < (row_length M1)*(row_length M2)\" \nand \"(mat (row_length M1) (length M1) M1)\"\nand \"(mat (row_length M2) (length M2) M2)\"\nshows \"row (M1 \\<otimes> M2) i =  vec_vec_Tensor (row M1 (i div row_length M2)) (row M2 (i mod row_length M2))\"\n           using assms row_formula by auto\n\nlemma alt_effective_matrix_tensor_elements:\n \" (((i<((row_length M2)*(row_length M3)))\\<and>(j < (length M2)*(length M3)))\n\\<and>(mat (row_length M2) (length M2) M2)\\<and>(mat (row_length M3) (length M3) M3)\n\\<Longrightarrow> ((M2 \\<otimes> M3)!j!i) = f (M2!(j div (length M3))!(i div (row_length M3))) \n(M3!(j mod length M3)!(i mod (row_length M3))))\"\n  using matrix_Tensor_elements by auto\n            \n\nlemma trans_impl:\"(\\<forall> i j.(P i j \\<longrightarrow> Q i j))\\<and>(\\<forall> i j. (Q i j \\<longrightarrow> R i j)) \\<Longrightarrow> (\\<forall> i j. (P i j \\<longrightarrow> R i j))\"\n          by auto\n\nlemma \"((x::nat) div y) div z = (x div (y*z))\"\n      using div_mult2_eq by auto\n\nlemma \"(\\<not>((a::nat) < b)) \\<Longrightarrow> (a \\<ge> b)\"\n        by auto\n\nlemma not_null: \"xs \\<noteq> [] \\<Longrightarrow> \\<exists>y ys. xs = y#ys\"\n      by (metis neq_Nil_conv)\n\nlemma \"(y::nat) \\<noteq> 0 \\<Longrightarrow> (x mod y) < y\"\n    using mod_less_divisor by auto\n\n\nlemma mod_prop1:\"((a::nat) mod (b*c)) mod c = (a mod c)\"\n proof(cases \"c = 0\")\n case True\n  have \"b*c = 0\"\n       by (metis True mult_0_right)\n  then have \"(a::nat) mod (b*c) = a\"\n         by auto\n  then have \"((a::nat) mod (b*c)) mod c = a mod c\"\n         by auto\n  then show ?thesis by auto\n next\n case False\n  let ?x = \"(a::nat) mod (b*c)\"\n  let ?z = \"?x mod c\"\n  have \"\\<exists>m. a = m*(b*c) + ?x\"\n        by (metis mod_eqD nat_add_commute)  \n  then obtain m1 where \"a = m1*(b*c) + ?x\"\n          by auto\n  then have \"?x = (a - m1*(b*c))\"\n             by auto\n  then have \"\\<exists>m.( ?x = m*c + ?z)\"\n           using mod_eqD nat_add_commute by metis\n  then obtain m where \"( ?x = m*c + ?z)\"\n                by auto\n  then have \"(a - m1*(b*c)) = m*c + ?z\"\n         using  `a mod (b * c) = a - m1 * (b * c)`   by (metis)\n  then have \"a = m1*b*c + m*c + ?z\"\n        using `a = m1 * (b * c) + a mod (b * c)` `a mod (b * c) \n        = m * c + a mod (b * c) mod c`\n        by (metis  ab_semigroup_add_class.add_ac(1) \n        ab_semigroup_mult_class.mult_ac(1))\n  then have 1:\"a = (m1*b + m)*c + ?z\"\n              by (metis add_mult_distrib2 nat_mult_commute) \n  let ?y = \"(a mod c)\"\n  have \"\\<exists>n. a = n*(c) + ?y\"\n           by (metis mod_eqD nat_add_commute)  \n  then obtain n where \"a = n*(c) + ?y\"\n           by auto\n  with 1 have \"(m1*b + m)*c + ?z = n*c + ?y\"\n         by auto\n  then have \"(m1*b + m)*c - (n*c) = ?y - ?z\"\n         by auto\n  then have \"(m1*b + m - n)*c = (?y - ?z)\"\n          by (metis diff_mult_distrib2 nat_mult_commute)     \n  then have \"c dvd (?y - ?z)\"\n           by (metis dvd_triv_right)\n  moreover have \"?y < c\"\n          using mod_less_divisor False by auto  \n  moreover have \"?z < c\"\n          using mod_less_divisor False by auto  \n  moreover have \"?y - ?z < c\"\n           by (metis \"1\" False comm_monoid_diff_class.diff_cancel less_nat_zero_code mod_add_right_eq mod_mult_self3 nat_neq_iff)   \n  ultimately have \"?y - ?z = 0\"\n             by (metis dvd_imp_mod_0 mod_less)\n  then show ?thesis using False by (metis \"1\" mod_add_right_eq mod_mult_self2 nat_add_commute nat_mult_commute)\nqed\n\nlemma mod_div_relation:\"((a::nat) mod (b*c)) div c = (a div c) mod b\"\n   proof(cases \"b*c = 0\")\n      case True\n          have T_1:\"(b = 0)\\<or>(c = 0)\"\n                      using True by auto\n          show ?thesis\n            proof(cases \"(b = 0)\")\n            case True\n              have \"a mod (b*c) = a\"\n                   using True by auto\n              then show ?thesis using True by auto\n             next\n             case False\n               have \"c = 0\"\n                   using T_1 False by auto\n               then show ?thesis by auto\n             qed\n      next\n      case False\n         have F_1:\"(b > 0)\\<and> (c > 0)\"\n               using False by auto\n         have \"\\<exists>x. a = x*(b*c) + (a mod (b*c))\"\n               by (metis mod_eqD nat_add_commute)\n         then obtain x where \"a = x*(b*c) + (a mod (b*c))\"\n               by auto\n         then have \"a div c = ((x*(b*c)) div c) + ((a mod (b*c)) div c)\"\n               by (metis div_add1_eq mod_add_self1 mod_add_self2 mod_by_0 mod_div_trivial mod_prop1 mod_self)\n         then have \"a div c = (((x*b)*c) div c) + ((a mod (b*c)) div c)\"\n               by auto\n         then have F_2:\"a div c = (x*b) + ((a mod (b*c)) div c)\"    \n               by (metis F_1 div_mult_self1_is_id nat_mult_commute neq0_conv)\n\n          have \"\\<exists>y. a div c = (y*b) + ((a div c) mod b)\"\n                     by (metis nat_add_commute semiring_div_class.mod_div_equality')\n          then obtain y where \"a div c = (y*b) + ((a div c) mod b)\"\n                      by auto\n          with F_2 have F_3:\" (x*b) + ((a mod (b*c)) div c) = (y*b) + ((a div c) mod b)\"\n                      by auto\n          then have \"(x*b) - (y * b) = ((a div c) mod b) - ((a mod (b*c)) div c) \"\n                          by auto\n          then have \"(x - y) * b = ((a div c) mod b) - ((a mod (b*c)) div c)\"\n                           by (metis diff_mult_distrib2 nat_mult_commute)\n          then have F_4:\"b dvd (((a div c) mod b) - ((a mod (b*c)) div c))\"\n                       by (metis dvd_eq_mod_eq_0 mod_mult_self1_is_0 nat_mult_commute)\n          have F_5:\"b >  ((a div c) mod b)\"\n                        by (metis F_1 mod_less_divisor)\n          have \"b*c > (a mod (b*c))\"\n                          by (metis False mod_less_divisor neq0_conv)\n          moreover then have \"(b*c) div c > (a mod (b*c)) div c\"\n                            by (metis F_1 div_left_ineq \n                                       div_mult_self2_is_id neq0_conv)\n          then have \"b > (a mod (b*c)) div c\"\n                                by (metis calculation \n                                       div_right_ineq nat_mult_commute)\n          with F_4 F_5 have F_6:\"((a div c) mod b)-((a mod (b*c)) div c) = 0\"\n                              by (metis less_imp_diff_less less_nat_zero_code \n                                        nat_dvd_not_less nat_less_cases)      \n          from F_3 have \"(y * b) - (x*b) \n                               = ((a mod (b*c)) div c) - ((a div c) mod b) \"\n                          by auto\n          then have \"(y - x) * b = ((a mod (b*c)) div c) - ((a div c) mod b)\"\n                           by (metis diff_mult_distrib2 nat_mult_commute)\n          then have F_7:\"b dvd (((a mod (b*c)) div c) - ((a div c) mod b))\"\n                       by (metis dvd_eq_mod_eq_0 mod_mult_self1_is_0 \n                                 nat_mult_commute)\n          have F_8:\"b >  ((a div c) mod b)\"\n                        by (metis F_1 mod_less_divisor)\n          have \"b*c > (a mod (b*c))\"\n                          by (metis False mod_less_divisor neq0_conv)\n          moreover then have \"(b*c) div c > (a mod (b*c)) div c\"\n                            by (metis F_1 div_left_ineq \n                                     div_mult_self2_is_id neq0_conv)\n          then have \"b > (a mod (b*c)) div c\"\n                                by (metis calculation div_right_ineq \n                                     nat_mult_commute)\n          with F_7 F_8 have \"((a mod (b*c)) div c) - ((a div c) mod b) = 0\"\n                              by (metis less_imp_diff_less less_nat_zero_code \n                                  nat_dvd_not_less nat_less_cases)      \n          with F_6 have \"((a mod (b*c)) div c) = ((a div c) mod b)\"\n                             by auto         \n          then show ?thesis using False by auto \nqed\n\ntext{*The following lemma proves that the tensor product of matrices\nis associative*}\nlemma associativity:fixes M1 M2 M3\nshows\n\"(mat (row_length M1) (length M1) M1) \\<and> (mat (row_length M2) (length M2) M2)\n\\<and> (mat (row_length M3) (length M3) M3)\n \\<Longrightarrow>\n           M1 \\<otimes> (M2 \\<otimes> M3) = (M1 \\<otimes> M2) \\<otimes> M3\" (is \"?x \\<Longrightarrow>?l = ?r\")\n proof-\n fix j\n assume 0:\"  (mat (row_length M1) (length M1) M1) \n           \\<and> (mat (row_length M2) (length M2) M2)\n           \\<and> (mat (row_length M3) (length M3) M3)\" \n have 1:\"length ((M1 \\<otimes> M2) \\<otimes> M3) \n                    = (length M1)*(length M2)* (length M3)\"\n       proof- \n           have \"length (M2 \\<otimes> M3) = (length M2)* (length M3)\"\n              by (metis length_Tensor)\n           then have \"length (M1 \\<otimes> (M2 \\<otimes> M3)) \n                   = (length M1)*(length M2)* (length M3)\"\n                        by (metis length_Tensor nat_mult_assoc)\n           moreover have \" length (M1 \\<otimes> M2) = (length M1)* (length M2)\"\n                        by (metis length_Tensor)\n           ultimately  show ?thesis by (metis length_Tensor nat_mult_assoc)\n           qed\n have 2:\"row_length ((M1 \\<otimes> M2) \\<otimes> M3) \n                    = (row_length M1)*(row_length M2)* (row_length M3)\"\n          proof-\n            have \"row_length (M2 \\<otimes> M3) = (row_length M2)* (row_length M3)\"\n              using row_length_mat assoc by auto\n            then have \"row_length (M1 \\<otimes> (M2 \\<otimes> M3)) \n                   = (row_length M1)*(row_length M2)* (row_length M3)\"\n              using row_length_mat assoc by auto\n            moreover have \" row_length (M1 \\<otimes> M2) \n                                   = (row_length M1)* (row_length M2)\"\n               using row_length_mat  by auto\n            ultimately show ?thesis  using row_length_mat assoc by auto\n          qed\n  have 3:\n      \"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            (((M1 \\<otimes> M2) \\<otimes> M3)!j!i) \n                = f \n                   ((M1 \\<otimes> M2)!(j div (length M3))!(i div (row_length M3))) \n                   (M3!(j mod length M3)!(i mod (row_length M3))))\"\n       using 0 matrix_Tensor_elements 1 2 effective_well_defined_Tensor \n             length_Tensor row_length_mat\n       by auto\n  moreover have \n       \"\\<forall>j.(j < (length M1)*(length M2)*(length M3))  \n                          \\<longrightarrow> (j div (length M3)) < (length M1)*(length M2)\"\n              apply(rule allI)\n              apply(simp add:div_left_ineq)\n              done\n moreover have \"\\<forall>i.(i < (row_length M1)*(row_length M2)*(row_length M3)) \n                       \\<longrightarrow> (i div (row_length M3)) \n                                         < (row_length M1)*(row_length M2)\"\n               apply(rule allI)\n               apply(simp add:div_left_ineq)\n               done\n ultimately have 4:\"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n          \\<longrightarrow> \n                ((i div (row_length M3)) < (row_length M1)*(row_length M2))\n                \\<and> ((j div (length M3)) < (length M1)*(length M2)))\"\n         using allI 0  by auto\n have \" (mat (row_length M1) (length M1) M1) \n           \\<and> (mat (row_length M2) (length M2) M2)\"\n             using 0 by auto\n then have \"\\<forall>i.\\<forall>j.(((i div (row_length M3)) < (row_length M1)*(row_length M2))\n         \\<and> ((j div (length M3)) < (length M1)*(length M2))\n          \\<longrightarrow>\n       (((M1 \\<otimes> M2))!(j div (length M3))!(i div row_length M3)) \n                = f \n          ((M1)!((j div (length M3)) div (length M2))\n               !((i div (row_length M3)) div (row_length M2))) \n          (M2!((j div (length M3)) mod (length M2))\n             !((i div (row_length M3)) mod (row_length M2))))\"\n            using  effective_matrix_tensor_elements by auto            \n with 4 have 5:\"\\<forall>i j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n          \\<longrightarrow>  (((M1 \\<otimes> M2))!(j div (length M3))!(i div row_length M3)) \n                = f \n       ((M1)!((j div (length M3)) div (length M2))\n            !((i div (row_length M3)) div (row_length M2))) \n        (M2!((j div (length M3)) mod (length M2))\n            !((i div (row_length M3)) mod (row_length M2))))\"\n                by auto\n with 3 have 6:\n      \"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            (((M1 \\<otimes> M2) \\<otimes> M3)!j!i) \n                = f \n                   (f \n                     ((M1)!((j div (length M3)) div (length M2))\n                             !((i div (row_length M3)) div (row_length M2))) \n                     (M2!((j div (length M3)) mod (length M2))\n                           !((i div (row_length M3)) mod (row_length M2)))) \n                   (M3!(j mod length M3)!(i mod (row_length M3))))\"\n                       by auto\n\n   \n have \"(j div (length M3))div (length M2) = (j div ((length M3)*(length M2)))\"\n                      using div_mult2_eq by auto  \n moreover have \"((i div (row_length M3)) div (row_length M2)) = (i div ((row_length M3)*(row_length M2)))\"\n                        using div_mult2_eq by auto\n ultimately have step1:\"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            (((M1 \\<otimes> M2) \\<otimes> M3)!j!i) \n                = f \n                   (f \n       ((M1)!(j div ((length M3)*(length M2)))! (i div ((row_length M3)*(row_length M2)))) \n          (M2!((j div (length M3)) mod (length M2))!((i div (row_length M3)) mod (row_length M2)))) \n                   (M3!(j mod length M3)!(i mod (row_length M3))))\"\n            using 6  by (metis \"3\" \"5\" div_mult2_eq)\n then have step1:\"\\<forall>i j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            (((M1 \\<otimes> M2) \\<otimes> M3)!j!i) \n                = f \n                   (f \n       ((M1)!(j div ((length M2)*(length M3)))! (i div ((row_length M2)*(row_length M3)))) \n          (M2!((j div (length M3)) mod (length M2))!((i div (row_length M3)) mod (row_length M2)))) \n                   (M3!(j mod length M3)!(i mod (row_length M3))))\"\n              by (metis nat_mult_commute)\n have 7:\n      \"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            ((M1 \\<otimes> (M2 \\<otimes> M3))!j!i) \n                = f \n                   ((M1)!(j div (length (M2 \\<otimes>  M3)))!(i div (row_length (M2 \\<otimes> M3)))) \n                   ((M2 \\<otimes> M3)!(j mod length (M2 \\<otimes>M3))!(i mod (row_length (M2 \\<otimes> M3)))))\"\n       using 0 matrix_Tensor_elements 1 2 effective_well_defined_Tensor \n             length_Tensor row_length_mat\n       by auto\n  then have \n      \"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            ((M1 \\<otimes> (M2 \\<otimes> M3))!j!i) \n                = f \n                   ((M1)!(j div ((length M2)*(length M3)))!(i div ((row_length M2)*(row_length M3)))) \n                   ((M2 \\<otimes> M3)!(j mod length (M2 \\<otimes>M3))!(i mod (row_length (M2 \\<otimes> M3)))))\"\n           using length_Tensor row_length_mat by auto\n   then have \n      \"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            ((M1 \\<otimes> (M2 \\<otimes> M3))!j!i) \n                = f \n                   ((M1)!(j div ((length M3)*(length M2)))\n                        !(i div ((row_length M3)*(row_length M2)))) \n                   ((M2 \\<otimes> M3)!(j mod length (M2 \\<otimes>M3))\n                             !(i mod (row_length (M2 \\<otimes> M3)))))\"\n            using nat_mult_commute by (metis)\n   have 8:\n       \"\\<forall>j.((j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> (j mod (length (M2 \\<otimes> M3))) < (length (M2 \\<otimes> M3))\"\n           proof(cases \"length (M2 \\<otimes> M3) = 0\")\n           case True\n             have \"(length M2)*(length M3) = 0\"\n                      using length_Tensor True by auto\n              then have \"(length M1)*(length M2)*(length M3) = 0\"\n                          by auto\n              then show ?thesis  by (metis  less_nat_zero_code)\n            next\n            case False\n                have \"length (M2 \\<otimes> M3)  > 0\"\n                      using False by auto\n                then show ?thesis using mod_less_divisor by auto\n            qed\n   then have 9:\n        \"\\<forall>i.((i < (row_length M1)*(row_length M2)*(row_length M3)))\n                \\<longrightarrow> (i mod (row_length (M2 \\<otimes> M3))) < (row_length (M2 \\<otimes> M3))\"\n           proof(cases \"row_length (M2 \\<otimes> M3) = 0\")\n           case True\n             have \"(row_length M2)*(row_length M3) = 0\"\n                      using  True by (metis row_length_mat)\n              then have \"(row_length M1)*(row_length M2)*(row_length M3) = 0\"\n                          by auto\n               then show ?thesis by (metis less_nat_zero_code)\n            next\n            case False\n                have \"row_length (M2 \\<otimes> M3)  > 0\"\n                      using False by auto\n                then show ?thesis using mod_less_divisor by auto\n            qed\n  \n with 8 have 10:\"\\<forall>i.\\<forall>j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n             \\<longrightarrow> \n                (i mod (row_length (M2 \\<otimes> M3))) < (row_length (M2 \\<otimes> M3))\n              \\<and> (j mod (length (M2 \\<otimes> M3))) < (length (M2 \\<otimes> M3)))\"\n          by auto\n then have 11:\"\\<forall> i j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n             \\<longrightarrow> \n                (i mod (row_length (M2 \\<otimes> M3))) \n                              < (row_length M2)*(row_length M3)\n                \\<and>(j mod (length (M2 \\<otimes> M3))) < (length M2)*(length  M3))\"\n           using length_Tensor row_length_mat by auto\n have \"(mat (row_length M2) (length M2) M2) \n           \\<and> (mat (row_length M3) (length M3) M3)\"\n           using 0 by auto\n then have \"\\<forall> i j.(((i mod (row_length (M2 \\<otimes> M3))) \n                                 < (row_length M2)*(row_length M3))\n                  \\<and>((j mod (length (M2\\<otimes>M3))) < (length M2)*(length M3))\n       \\<longrightarrow>\n       (((M2 \\<otimes> M3))!(j mod (length (M2 \\<otimes> M3)))!(i mod row_length (M2 \\<otimes> M3))) \n                = f \n                  ((M2)!((j mod (length (M2 \\<otimes> M3))) div (length M3))\n                        !((i mod (row_length (M2 \\<otimes> M3))) div (row_length M3))) \n                  (M3!((j mod (length (M2 \\<otimes> M3))) mod (length M3))\n                     !((i mod (row_length (M2 \\<otimes> M3))) mod (row_length M3))))\"\n           using matrix_Tensor_elements by auto \n then have \"\\<forall> i j.\n         ((i < (row_length M1)*(row_length M2)*(row_length M3))\n       \\<and>(j < (length M1)*(length M2)*(length M3) )\n             \\<longrightarrow> \n           (((M2 \\<otimes> M3))!(j mod (length (M2 \\<otimes> M3)))\n                       !(i mod row_length (M2 \\<otimes> M3))) \n                = \n       f \n       ((M2)!((j mod (length (M2 \\<otimes> M3))) div (length M3))\n            !((i mod (row_length (M2 \\<otimes> M3))) div (row_length M3))) \n        (M3!((j mod (length (M2 \\<otimes> M3))) mod (length M3))\n           !((i mod (row_length (M2 \\<otimes> M3))) mod (row_length M3))))\"   \n                     using 11 by auto \n moreover then have \"\\<forall>j.(j mod (length (M2 \\<otimes> M3))) mod (length M3)\n                         = j mod (length M3)\"\n                proof                  \n                 have \"\\<forall>j.((j mod (length (M2 \\<otimes> M3))) \n                         = (j mod ((length M2) *(length M3))))\"\n                                      using length_Tensor by auto\n                 moreover have \n                       \"\\<forall>j.\n                        ((j mod ((length M2) *(length M3))) mod (length M3)\n                                 = (j mod (length M3)))\"   \n                       using mod_prop1 by auto \n                 ultimately show ?thesis by auto\n                qed\n moreover then have \"\\<forall>i.(i mod (row_length (M2 \\<otimes> M3))) mod (row_length M3)\n                         = i mod (row_length M3)\"\n                proof                  \n                 have \"\\<forall>i.((i mod (row_length (M2 \\<otimes> M3))) \n                         = (i mod ((row_length M2) *(row_length M3))))\"\n                                      using row_length_mat by auto\n                 moreover have \n                               \"\\<forall>i.((i mod ((row_length M2)*(row_length M3))) \n                                       mod (row_length M3)\n                                 = (i mod (row_length M3)))\"   \n                       using mod_prop1 by auto \n                 ultimately show ?thesis by auto\n                qed\n ultimately have 12:\"\\<forall> i j.((i < (row_length M1)\n                            *(row_length M2)\n                            *(row_length M3))\n                            \\<and>(j < (length M1)*(length M2)*(length M3) )\n                       \\<longrightarrow> \n                          (((M2 \\<otimes> M3))!(j mod (length (M2 \\<otimes> M3)))\n                                       !(i mod row_length (M2 \\<otimes> M3))) \n                = f \n                   ((M2)!((j mod (length (M2 \\<otimes> M3))) div (length M3))\n                        !((i mod (row_length (M2 \\<otimes> M3))) div (row_length M3))) \n                   (M3!(j mod  (length M3))!(i mod (row_length M3))))\"   \n                     by auto \n moreover have \"\\<forall>j.(j mod (length (M2 \\<otimes> M3))) div (length M3)\n                    = (j div (length M3)) mod (length M2)\"\n           proof-\n            have \"\\<forall>j.((j mod (length (M2 \\<otimes> M3))) \n                    = (j mod ((length M2)*(length M3))))\"\n                    using length_Tensor by auto\n            then show ?thesis using mod_div_relation by auto\n           qed\n moreover have \"\\<forall>i.(i mod (row_length (M2 \\<otimes> M3))) div (row_length M3)\n                    = (i div (row_length M3)) mod (row_length M2)\"\n           proof-\n            have \"\\<forall>i.((i mod (row_length (M2 \\<otimes> M3))) \n                    = (i mod ((row_length M2)*(row_length M3))))\"\n                    using row_length_mat by auto\n            then show ?thesis using mod_div_relation by auto\n           qed\n ultimately have \"\\<forall> i j.\n                      ((i < (row_length M1)*(row_length M2)*(row_length M3))\n                      \\<and>(j < (length M1)*(length M2)*(length M3) )\n             \\<longrightarrow> \n                 (((M2 \\<otimes> M3))!(j mod (length (M2 \\<otimes> M3)))\n                             !(i mod row_length (M2 \\<otimes> M3))) \n                       = f \n                          ((M2)!((j div (length M3)) mod (length M2))\n                               !((i div (row_length M3)) mod (row_length M2)))\n                           (M3!(j mod  (length M3))!(i mod (row_length M3))))\"   \n                     by auto \n with 7 have 13:\"\\<forall>i j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            ((M1 \\<otimes> (M2 \\<otimes> M3))!j!i) \n                = f \n                   ((M1)!(j div ((length M2)*(length  M3)))\n                        !(i div ((row_length M2)*(row_length M3)))) \n                  (f \n       ((M2)!((j div (length M3)) mod (length M2))!((i div (row_length M3)) mod (row_length M2)))\n       (M3!(j mod  (length M3))\n           !(i mod (row_length M3)))))\"  \n             using length_Tensor row_length_mat  by auto\n moreover have \"\\<forall> i j.( f \n                    ((M1)!(j div ((length M2)*(length  M3)))\n                        !(i div ((row_length M2)*(row_length M3)))) \n                  (f \n                   ((M2)!((j div (length M3)) mod (length M2))!((i div (row_length M3)) mod (row_length M2)))\n       (M3!(j mod  (length M3))\n           !(i mod (row_length M3)))))\n           = f (f \n                    ((M1)!(j div ((length M2)*(length  M3)))\n                        !(i div ((row_length M2)*(row_length M3))))                  \n                    ((M2)!((j div (length M3)) mod (length M2))\n                         !((i div (row_length M3)) mod (row_length M2))))\n                (M3!(j mod  (length M3))\n                   !(i mod (row_length M3)))\"\n                using assoc by auto\n  with 13 have \"\\<forall>i j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            ((M1 \\<otimes> (M2 \\<otimes> M3))!j!i) \n                = f (f \n                    ((M1)!(j div ((length M2)*(length  M3)))\n                        !(i div ((row_length M2)*(row_length M3))))                  \n                    ((M2)!((j div (length M3)) mod (length M2))\n                         !((i div (row_length M3)) mod (row_length M2))))\n                (M3!(j mod  (length M3))\n                   !(i mod (row_length M3))))\"\n           by auto\n with step1 have step2: \"\\<forall>i j.(((i<((row_length M1)*(row_length M2)*(row_length M3)))\n       \\<and>(j < (length M1)*(length M2)*(length M3)))\n                \\<longrightarrow> \n            ((M1 \\<otimes> (M2 \\<otimes> M3))!j!i) = (((M1 \\<otimes> M2) \\<otimes> M3)!j!i))\"\n                    by auto\n moreover have \"mat ((row_length M1)*(row_length M2)*(row_length M3))\n           ((length M1)*(length M2)*(length M3))\n               (M1 \\<otimes> (M2 \\<otimes> M3))\"\n          proof-\n           have \"mat ((row_length M2)*(row_length M3)) ((length M2)*(length M3)) (M2 \\<otimes> M3)\"\n              using 0 effective_well_defined_Tensor  row_length_mat length_Tensor by auto\n           moreover have  \"mat ((row_length M1)*((row_length (M2 \\<otimes> M3))))\n           ((length M1)*((length (M2 \\<otimes> M3))))\n               (M1 \\<otimes> (M2 \\<otimes> M3))\"\n                  using  0 effective_well_defined_Tensor  row_length_mat length_Tensor \n                  by metis\n           ultimately show ?thesis using row_length_mat length_Tensor by (metis nat_mult_assoc)\n         qed\n  moreover have \"mat ((row_length M1)*(row_length M2)*(row_length M3))\n           ((length M1)*(length M2)*(length M3))\n               ((M1 \\<otimes> M2) \\<otimes> M3)\"\n          proof-\n           have \"mat ((row_length M1)*(row_length M2)) ((length M1)*(length M2)) (M1 \\<otimes> M2)\"\n              using 0 effective_well_defined_Tensor  row_length_mat length_Tensor by auto\n           moreover have  \"mat ((row_length (M1 \\<otimes> M2))*(row_length M3))\n           ((length (M1 \\<otimes> M2))*(length M3))\n               ((M1 \\<otimes> M2 )\\<otimes> M3)\"\n                  using  0 effective_well_defined_Tensor  row_length_mat length_Tensor \n                  by metis \n           ultimately show ?thesis using row_length_mat length_Tensor by (metis nat_mult_assoc)\n         qed\n ultimately show ?thesis using mat_eq_index  by metis\nqed     \nend  \n\nlemma \" \\<And>(a::nat) b.(times  a  b) =(times  b  a)\"\n by auto\n\nlocale plus_mult = \n mult+\n fixes zer::\"'a\"\n fixes g::\" 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \" (infixl \"+\" 60)\n fixes inv::\"'a \\<Rightarrow>  'a\"\n assumes plus_comm:\" g a  b = g b a \"\n assumes plus_assoc:\" (g (g a b) c) = (g a (g b c))\"\n assumes plus_left_id:\" g zer x = x\"\n assumes plus_right_id:\"g x zer = x\"\n assumes plus_left_distributivity: \"f a (g b c) = g (f a b) (f a c)\"\n assumes plus_right_distributivity: \"f (g a b) c = g (f a c) (f b c)\"\n assumes plus_left_inverse:\"(g x  (inv x)) = zer\"\n assumes plus_right_inverse:\"(g (inv x) x) = zer\"\n \n\ncontext plus_mult\nbegin\n(*\nlemma \"((a::'a)+b)*(c+d) = a*c + a*d + b*c + b*d\"\n proof-\n have \" ((a::'a)+b)*(c+d) = ((a::'a)+b)*c + ((a::'a)+b)*d\" \n     using plus_left_distributivity sledgehammer\n  *) \n\nlemma fixes M1 M2 M3\nshows\n \"(mat (row_length M1) (length M1) M1) \n \\<and>(mat (row_length M2) (length M2) M2)\n \\<and>(mat (row_length M3) (length M3) M3)\n   \\<Longrightarrow> (M1 \\<otimes> (M2 \\<otimes> M3)) = ((M1 \\<otimes> M2) \\<otimes> M3)\"\n       using associativity by auto\n\n\ntext{*matrix$\\_$mult refers to multiplication of matrices in the locale \nplus_mult *}\n\nabbreviation matrix_mult::\"'a mat \\<Rightarrow> 'a mat \\<Rightarrow> 'a mat\" (infixl \"\\<circ>\" 65)\n where\n\"matrix_mult M1 M2 \\<equiv> (mat_multI zer g f (row_length M1) M1 M2)\"\n\ndefinition scalar_product :: \"'a vec \\<Rightarrow> 'a vec \\<Rightarrow> 'a\" where\n \"scalar_product v w = scalar_prodI zer g f v w\"\n\nlemma ma :\n  assumes wf1: \"mat nr n m1\"\n  and wf2: \"mat n nc m2\"\n  and i: \"i < nr\"\n  and j: \"j < nc\"\n  shows \"mat_multI zer g f nr m1 m2 ! j ! i \n                  = scalar_prodI zer g f (row m1 i) (col m2 j)\"\n          using mat_mult_index i j wf1 wf2 by metis\n\nlemma matrix_index:\n  assumes wf1: \"mat (row_length m1) n m1\"\n  and wf2: \"mat n nc m2\"\n  and i: \"i < (row_length m1)\"\n  and j: \"j < nc\"\n  shows  \"matrix_mult  m1 m2 ! j ! i \n                 = scalar_product  (row m1 i) (col m2 j)\"\n         using wf1 wf2 i j ma scalar_product_def by auto\n\n\nlemma unique_row_col:\nassumes \"mat nr1 nc1 M\" and \"mat nr2 nc2 M\" and \"M \\<noteq> []\"\n shows \"nr1 = nr2\" and \"nc1 = nc2\"\nproof(cases M)\ncase Nil\n  show \"nr1 = nr2\" using assms(3) Nil by auto\nnext\ncase (Cons v M)\n have 1:\"v \\<in> set (v#M)\"\n        using Cons by auto\n then have \"length v = nr1\"\n        using assms(1) mat_def Ball_def vec_def  Cons by metis \n moreover then have \"length v = nr2\"\n        using 1 assms(2) mat_def Ball_def vec_def  Cons by metis\n ultimately show \"nr1 = nr2\"\n         by auto\nnext\n have \"length M = nc1\"\n        using mat_def assms(1) by auto\n moreover have \"length M = nc2\"\n         using mat_def assms(2) by auto\n ultimately show \"nc1 = nc2\"\n          by auto\nqed\n\nlemma matrix_mult_index: assumes \"m1 \\<noteq> []\"\nand  wf1: \"mat nr n m1\"\n  and wf2: \"mat n nc m2\"\n  and i: \"i < nr\"\n  and j: \"j < nc\"\n  shows  \"matrix_mult  m1 m2 ! j ! i = scalar_product  (row m1 i) (col m2 j)\"\n         using matrix_index unique_row_col assms by (metis matrix_row_length)\n\ntext{* the following definition checks if the given four matrices\n are such that the compositions in the distributive relation which\n will be proved, hold true. It further checks that the matrices are \n non empty and valid*}\ndefinition matrix_match::\"'a mat \\<Rightarrow> 'a mat \\<Rightarrow>'a mat \\<Rightarrow> 'a mat  \\<Rightarrow> bool\"\nwhere \n\"matrix_match A1 A2 B1 B2 \\<equiv> \n    (mat (row_length A1) (length A1) A1)\n   \\<and>(mat (row_length A2) (length A2) A2)\n   \\<and>(mat (row_length B1) (length B1) B1)\n   \\<and>(mat (row_length B2) (length B2) B2)\n   \\<and> (length A1 = row_length A2)\n   \\<and> (length B1 = row_length B2)\n   \\<and>(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> [])\"\n\n\nlemma non_empty_mat_mult:assumes wf1:\"mat nr n A\"\n and wf2:\"mat n nc B\"\n and \"A \\<noteq> []\" and \" B \\<noteq> []\"\n shows  \"A \\<circ> B \\<noteq> []\"\n proof-\n have \"mat nr nc (A \\<circ> B)\"\n         using assms(1) assms(2) mat_mult  assms(3) matrix_row_length unique_row_col(1) by (metis)\n then have \"length (A \\<circ> B) = nc\"\n           using mat_def by auto\n moreover have \"nc > 0\"\n              proof-\n              have \"length B = nc\"\n                    using assms(2) mat_def by auto\n              then show ?thesis\n                     using assms(4) by auto\n              qed\n moreover then have \"length (A \\<circ> B) > 0\"\n          by (metis calculation(1))  \n then show ?thesis by auto\nqed\n\nlemma tensor_compose_distribution1:\nassumes wf1:\"mat (row_length A1) (length A1) A1\"\n and wf2:\"mat (row_length A2) (length A2) A2\"\n and wf3:\"mat (row_length B1) (length B1) B1\"\n and wf4:\"mat (row_length B2) (length B2) B2\"\n and matchAA:\"length A1 = row_length A2\" \n and matchBB:\"length B1 = row_length B2\"\n and non_Nil:\"(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> [])\" \n shows \"mat ((row_length A1)*(row_length B1)) \n            ((length A2)*(length B2)) \n                    ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))\"\nproof-\n have 0:\"mat (row_length A1) (length A2) (matrix_mult A1 A2)\"\n          using wf1 wf2  mat_mult matchAA  by auto\n then have 1:\"mat (row_length (A1 \\<circ> A2)) (length (A1 \\<circ> A2)) (matrix_mult A1 A2)\"\n        by (metis matrix_row_length)\n then have 2: \"(row_length (A1 \\<circ> A2)) = (row_length A1)\" and \"length (A1 \\<circ> A2) = length A2\"\n             using non_empty_mat_mult unique_row_col 0  \n             apply (metis length_0_conv mat_empty_column_length non_Nil)\n             by (metis \"0\" \"1\" mat_empty_column_length unique_row_col(2))\n moreover have 3:\"mat (row_length B1) (length B2) (matrix_mult B1 B2)\"\n           using wf3 wf4 matchBB mat_mult by auto \n then have 4:\"mat (row_length (B1 \\<circ> B2)) (length (B1 \\<circ> B2)) (matrix_mult B1 B2)\"\n        by (metis matrix_row_length) \n then have 5: \"(row_length (B1 \\<circ> B2)) = (row_length B1)\" and \"length (B1 \\<circ> B2) = length B2\"\n             using non_empty_mat_mult unique_row_col 3\n             apply (metis length_0_conv mat_empty_column_length non_Nil) \n             by (metis \"3\" \"4\" mat_empty_column_length unique_row_col(2))\n then show ?thesis  using 1 4 5 well_defined_Tensor \n              by (metis \"2\" calculation(2))\nqed     \n\nlemma effective_tensor_compose_distribution1:\n \"matrix_match A1 A2 B1 B2 \\<Longrightarrow> mat ((row_length A1)*(row_length B1)) \n            ((length A2)*(length B2)) \n                    ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))\"\n  using tensor_compose_distribution1 unfolding matrix_match_def by auto\n\n\nlemma tensor_compose_distribution2:\nassumes wf1:\"mat (row_length A1) (length A1) A1\"\n and wf2:\"mat (row_length A2) (length A2) A2\"\n and wf3:\"mat (row_length B1) (length B1) B1\"\n and wf4:\"mat (row_length B2) (length B2) B2\"\n and matchAA:\"length A1 = row_length A2\"\n and matchBB:\"length B1 = row_length B2\"\n and non_Nil:\"(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> [])\" \n shows \"mat ((row_length A1)*(row_length B1)) \n            ((length A2)*(length B2)) \n                    ((A1 \\<otimes> B1) \\<circ>(A2 \\<otimes>B2))\"\n proof-\n have \"mat \n           ((row_length A1)*(row_length B1))  \n           ((length A1)*(length B1)) \n             (A1 \\<otimes> B1)\"\n          using wf1 wf3 well_defined_Tensor by auto\n moreover have \"mat \n                   ((row_length A2)*(row_length B2))  \n                   ((length A2)*(length B2)) \n                      (A2\\<otimes> B2)\"\n          using wf2 wf4 well_defined_Tensor by auto\n moreover have \"((length A1)*(length B1)) \n                        = ((row_length A2)*(row_length B2))\"\n                 using matchAA matchBB by auto\n ultimately show ?thesis using mat_mult row_length_mat by simp\nqed    \n\ntheorem tensor_non_empty: assumes \"A \\<noteq> []\" and \"B \\<noteq> []\"\n shows \"A \\<otimes> B \\<noteq> []\"\n using  assms(1) assms(2) length_0_conv length_Tensor mult_is_0 by metis\n\ntheorem non_empty_distribution:\n assumes \"mat nr1 n1 A1\" \n     and \"mat n1 nc1 A2\" \n     and \"mat nr2 n2 B1\" \n     and \"mat n2 nc2 B2\" \n     and \"A1 \\<noteq> []\" and \"B1 \\<noteq> []\" and \"A2 \\<noteq> []\" and \"B2 \\<noteq> []\" \n shows \"((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2)) \\<noteq> []\"\nproof-\n have \"A1 \\<circ> A2 \\<noteq> []\"\n       using assms  non_empty_mat_mult by auto\n moreover have \"B1 \\<circ> B2 \\<noteq> []\"\n        using assms  non_empty_mat_mult by auto\n ultimately show ?thesis using tensor_non_empty by auto \nqed\n\nlemma effective_tensor_compose_distribution2:\"matrix_match A1 A2 B1 B2 \\<Longrightarrow> \n   mat ((row_length A1)*(row_length B1)) \n            ((length A2)*(length B2)) \n                    ((A1 \\<otimes> B1) \\<circ>(A2 \\<otimes>B2))\"\n      using tensor_compose_distribution2 unfolding matrix_match_def by auto\n\ntheorem effective_matrix_Tensor_elements: \n fixes M1 M2 i j \n assumes \"i<((row_length M1)*(row_length M2))\"\n and \"j < (length M1)*(length M2)\"\n and \"mat (row_length M1) (length M1) M1\"\n and \"mat (row_length M2) (length M2) M2\"\nshows\n\"((M1 \\<otimes> M2)!j!i) = f (M1!(j div (length M2))!(i div (row_length M2))) \n(M2!(j mod length M2)!(i mod (row_length M2)))\"\n using matrix_Tensor_elements assms by auto\n\ntheorem effective_matrix_Tensor_elements2: \n fixes M1 M2 \n assumes \"mat (row_length M1) (length M1) M1\"\n and \"mat (row_length M2) (length M2) M2\"\nshows\n\"(\\<forall>i <((row_length M1)*(row_length M2)).\n \\<forall>j < ((length M1)*(length M2)).((M1 \\<otimes> M2)!j!i) = f (M1!(j div (length M2))!(i div (row_length M2))) \n(M2!(j mod length M2)!(i mod (row_length M2))))\"\n using matrix_Tensor_elements assms by auto\n\ndefinition matrix_compose_cond::\"'a mat \\<Rightarrow> 'a mat \\<Rightarrow>'a mat \\<Rightarrow> 'a mat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\nwhere \n\"matrix_compose_cond A1 A2 B1 B2 i j \\<equiv> \n     (mat (row_length A1) (length A1) A1)\n      \\<and>(mat (row_length A2) (length A2) A2)\n   \\<and>(mat (row_length B1) (length B1) B1)\n    \\<and>(mat (row_length B2) (length B2) B2)\n\n   \\<and> (length A1 = row_length A2)\n   \\<and> (length B1 = row_length B2)\n   \\<and>(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> []) \n\\<and>(i<(row_length A1)*(row_length B1))\\<and>(j< (length A2)*(length B2))\"\n\n (*  \\<and> (length A1 = row_length B1)\n   \\<and> (length A2 = row_length B2) *)\n\ntheorem elements_matrix_distribution_1:\nassumes wf1:\"mat (row_length A1) (length A1) A1\"\n and wf2:\"mat (row_length A2) (length A2) A2\"\n and wf3:\"mat (row_length B1) (length B1) B1\"\n and wf4:\"mat (row_length B2) (length B2) B2\"\n   and matchAA:\"length A1 = row_length A2\"\n   and matchBB:\"length B1 = row_length B2\"\n   and non_Nil:\"(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> [])\" \nand \"i<(row_length A1)*(row_length B1)\" and \"j< (length A2)*(length B2)\"\nshows\n\"((matrix_mult A1  A2)\\<otimes>(matrix_mult B1  B2))!j!i\n  =  f (scalar_product (row A1 (i div (row_length B1))) \n                        (col A2  (j div (length B2))))\n       (scalar_product (row B1 (i mod (row_length B1))) \n                       (col B2 (j mod (length B2))))\"\nproof-\n have 0:\"((matrix_mult A1  A2)\\<otimes>(matrix_mult B1  B2)) \\<noteq> []\"\n       using non_empty_distribution assms by auto\n then have 1:\"mat ((row_length A1)*(row_length B1)) \n            ((length A2)*(length B2)) \n                    ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))\"\n         using tensor_compose_distribution1 assms by auto\n then have 2:\"mat (row_length  ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))) \n            (length  ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))) \n                    ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))\"\n               by (metis matrix_row_length)\n then have 3:\"((row_length A1)*(row_length B1)) \n                         = (row_length  ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))) \"\n        and \"((length A2)*(length B2)) = (length  ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2)))\"\n      using 0 1 unique_row_col \n            apply metis\n            using 0 1 2 unique_row_col by metis  \n then have i:\"(i < ((row_length A1)*(row_length B1))) \n                             = (i < (row_length  ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))))\"\n                by auto\n moreover have j:\"(j < ((length A2)*(length B2))) \n                         = (j < (length  ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))))\"\n           using 3 `length A2 * length B2 = length (A1 \\<circ> A2 \\<otimes> B1 \\<circ> B2)` \n           by (metis)\n have 4:\"mat (row_length A1) (length A2) (A1 \\<circ> A2)\"\n                using assms mat_mult by auto\n then have 5:\"mat (row_length (A1 \\<circ> A2)) (length (A1 \\<circ> A2)) (A1 \\<circ> A2)\"\n              using  matrix_row_length  by (metis)\n with 4 have 6:\"row_length A1 = row_length (A1 \\<circ> A2)\"\n      by (metis \"0\" Tensor.simps(1) unique_row_col(1))\n with 4 5 have 7:\"length A2 = length (A1 \\<circ> A2)\"  \n                by (metis  mat_empty_column_length unique_row_col(2))           \n then have 8:\"mat (row_length B1) (length B2) (B1 \\<circ> B2)\"\n                using assms mat_mult by auto\n then have 9:\"mat (row_length (B1 \\<circ> B2)) (length (B1 \\<circ> B2)) (B1 \\<circ> B2)\"\n              using  matrix_row_length  by (metis)\n with 7 8 have 10:\"row_length B1 = row_length (B1 \\<circ> B2)\"\n               by (metis \"3\" \"6\" assms(8) less_nat_zero_code mult_cancel2 mult_is_0 nat_mult_commute row_length_mat)\n with 7 8 9  have 11:\"length B2 = length (B1 \\<circ> B2)\"  \n                by (metis  mat_empty_column_length unique_row_col(2))                    \n from 6 10 have 12:\n               \"(i < ((row_length A1)*(row_length B1))) \n                         = (i < (row_length  (A1\\<circ>A2))*(row_length (B1\\<circ>B2)))\"\n                 by auto   \n then have 13:\" (i < (row_length  (A1\\<circ>A2))*(row_length (B1\\<circ>B2)))\"\n                    using assms by auto\n from 7 11 have 14:   \n            \"(j < ((length A2)*(length B2))) \n                         = (j < (length  (A1\\<circ>A2))*(length (B1\\<circ>B2)))\"\n                by auto\n then have 15:\"(j < (length  (A1\\<circ>A2))*(length (B1\\<circ>B2)))\"\n              using assms by auto\n then have step_1:\"((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))!j!i\n            =  f ((A1\\<circ>A2)!(j div (length (B1\\<circ>B2)))\n                         !(i div (row_length (B1\\<circ>B2)))) \n                 ((B1\\<circ>B2)!(j mod length (B1\\<circ>B2))\n                         !(i mod (row_length (B1\\<circ>B2))))\"\n                using 5 9 13 15 effective_matrix_Tensor_elements by auto \n then have \"((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))!j!i\n            =  f ((A1\\<circ>A2)!(j div (length B2))!(i div (row_length B1))) \n                 ((B1\\<circ>B2)!(j mod length B2)!(i mod (row_length B1)))\"\n            using 10 11 by auto\n moreover have \" ((A1\\<circ>A2)!(j div (length B2))!(i div (row_length B1))) \n               = (scalar_product (row A1 (i div (row_length B1)) ) (col A2 (j div (length B2)) ))\"\n           proof-\n           have \"j div (length B2) < (length A2)\"\n                     using div_left_ineq assms by auto\n           moreover have \"i div (row_length B1) < (row_length A1)\"\n                     using assms div_left_ineq by auto   \n           moreover have \"mat (length A1) (length A2) A2\"\n                             using wf2 matchAA by auto   \n           ultimately show ?thesis   using wf1  non_Nil matrix_mult_index  by auto\n          qed\n moreover have \" ((B1\\<circ>B2)!(j mod (length B2))!(i mod (row_length B1))) \n               = (scalar_product \n                                 (row B1 (i mod (row_length B1)) ) \n                                 (col B2 (j mod (length B2))))\"\n           proof-\n           have \"j <(length A2)*(length B2)\"\n                    using assms by auto\n           then have \"j mod (length B2) < (length B2)\"\n                        by (metis calculation less_nat_zero_code \n                                  mod_less_divisor mult_is_0 neq0_conv)\n           moreover have \"i mod (row_length B1) < (row_length B1)\"\n                       by (metis assms(8) less_nat_zero_code mod_less_divisor \n                                 mult_is_0 neq0_conv)\n           moreover have \"mat (length B1) (length B2) B2\"\n                   using wf4 matchBB by auto\n           ultimately show ?thesis  \n                    using wf3 non_Nil matrix_mult_index by auto\n         qed\n ultimately show ?thesis by auto\nqed\n\nlemma effective_elements_matrix_distribution1:\n \"matrix_compose_cond A1 A2 B1 B2 i j \\<Longrightarrow>\n ((matrix_mult A1  A2)\\<otimes>(matrix_mult B1  B2))!j!i\n  =  f (scalar_product (row A1 (i div (row_length B1))) (col A2  (j div (length B2))))\n       (scalar_product (row B1 (i mod (row_length B1))) (col B2 (j mod (length B2))))\"\n      using  elements_matrix_distribution_1 matrix_compose_cond_def by auto      \n\nlemma matrix_match_condn_1:\n\"matrix_match A1 A2 B1 B2 \n      \\<and>((i<(row_length A1)*(row_length B1))\n      \\<and>(j<(length A2)*(length B2)))\n       \\<Longrightarrow>  ((matrix_mult A1  A2)\\<otimes>(matrix_mult B1  B2))!j!i\n  =  f\n       (scalar_product \n                 (row A1 (i div (row_length B1))) \n                 (col A2  (j div (length B2))))\n       (scalar_product \n                 (row B1 (i mod (row_length B1))) \n                 (col B2 (j mod (length B2))))\"\n   using elements_matrix_distribution_1 unfolding matrix_match_def by auto\n\nlemma effective_matrix_match_condn_1: \n assumes \"(matrix_match A1 A2 B1 B2) \"\n shows \"\\<forall>i j.((i<(row_length A1)*(row_length B1))\n             \\<and>(j<(length A2)*(length B2))\n              \\<longrightarrow>   ((A1 \\<circ>  A2)\\<otimes>(B1 \\<circ> B2))!j!i\n                        =  f \n                            (scalar_product \n                                  (row A1 (i div (row_length B1))) \n                                  (col A2  (j div (length B2))))\n                            (scalar_product \n                                  (row B1 (i mod (row_length B1))) \n                                  (col B2 (j mod (length B2)))))\"\n   using assms matrix_match_condn_1 unfolding matrix_match_def \n       by auto \n\ntheorem elements_matrix_distribution2:\nfixes A1 A2 B1 B2 i j\nassumes wf1:\"mat (row_length A1) (length A1) A1\"\n and wf2:\"mat (row_length A2) (length A2) A2\"\n and wf3:\"mat (row_length B1) (length B1) B1\"\n and wf4:\"mat (row_length B2) (length B2) B2\"\n   and matchAA:\"length A1 = row_length A2\"\n   and matchBB:\"length B1 = row_length B2\"\n   and non_Nil:\"(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> [])\"    \nand i:\"i<(row_length A1)*(row_length B1)\" and j:\"j< (length A2)*(length B2)\" \nshows\n\"((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i\n  =  scalar_product \n          (vec_vec_Tensor \n                    (row A1 (i div row_length B1)) \n                    (row B1 (i mod row_length B1))) \n          (vec_vec_Tensor \n                    (col A2 (j div length B2)) \n                    (col B2 (j mod length B2)))\" \nproof-\n have 1:\"mat \n              ((row_length A1)*(row_length B1)) \n              ((length A1)*(length B1)) \n                                   (A1 \\<otimes> B1)\"\n              using wf1 wf3 well_defined_Tensor by auto\n moreover have 2:\"mat \n                   ((row_length A2)*(row_length B2)) \n                   ((length A2)*(length B2)) \n                                   (A2 \\<otimes> B2)\"\n              using wf2 wf4 well_defined_Tensor by auto\n moreover have 3:\"((length A1)*(length B1)) \n                           = ((row_length A2)*(row_length B2))\"\n              using matchAA matchBB by auto\n ultimately have 4:\"((A1\\<otimes>B1)\\<circ>(A2\\<otimes>B2))!j!i \n                        = scalar_product (row (A1 \\<otimes> B1) i) (col (A2 \\<otimes> B2) j)\"\n              using i j matrix_mult_index non_Nil mat_mult_index \n                    row_length_mat scalar_product_def\n              by auto\n moreover have \"(row (A1 \\<otimes> B1) i)\n                  =  vec_vec_Tensor \n                           (row A1 (i div row_length B1)) \n                           (row B1 (i mod row_length B1))\"\n              using  wf1 wf3 i effective_row_formula by auto\n moreover have \" col (A2 \\<otimes> B2) j =  vec_vec_Tensor (col A2 (j div length B2)) (col B2 (j mod length B2))\"\n              using wf2 wf4 j col_formula by auto\n ultimately show ?thesis by auto\n qed\n\n\n\n\nlemma effective_matrix_match_condn_2: \n assumes \"(matrix_match A1 A2 B1 B2) \"\n   shows \"\\<forall>i j.((i<(row_length A1)*(row_length B1))\n         \\<and>(j<(length A2)*(length B2))\n            \\<longrightarrow> ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i\n           =  scalar_product \n                  (vec_vec_Tensor \n                           (row A1 (i div row_length B1)) \n                           (row B1 (i mod row_length B1))) \n                  (vec_vec_Tensor \n                           (col A2 (j div length B2)) \n                           (col B2 (j mod length B2))))\" \n   using assms matrix_match_condn_2 unfolding matrix_match_def \n       by auto\n\n\nlemma zip_Nil:\"zip [] [] = []\"\n       using zip_def by auto\n\nlemma zer_left_mult:\"f zer x = zer\"\n  proof-\n  have \"g zer zer = zer\"\n     using plus_left_id by auto\n  then have \"f zer x = f (g zer zer) x\"\n             by auto\n  then have \"f zer x = (f zer x) + (f zer x)\"\n          using  plus_right_distributivity by auto\n  then have \"(f zer x) + (inv (f zer x)) = (f zer x) + (f zer x) + (inv (f zer x))\"\n                by auto\n  then have \"zer = (f zer x) + zer\"\n           using plus_left_inverse  plus_assoc by (metis)\n  then show ?thesis\n            using plus_right_id by simp\nqed\n\nlemma zip_Cons:\"(length v = length w) \\<Longrightarrow> zip (a#v) (b#w) = (a,b)#(zip v w)\"\n      unfolding zip_def by auto \n\nlemma scalar_product_times:\n \"\\<forall>w1 w2.(length w1 = length w2) \\<and>(length w1 = n) \\<longrightarrow> \n           (f (x*y) (scalar_product w1 w2)) \n                      = (scalar_product \n                               (times x w1) \n                               (times y w2))\"\n apply(rule allI)\n apply (rule allI)\n proof(induct n)\n case 0\n  have \"(length w1 = length w2) \\<and>(length w1 = 0)  \\<Longrightarrow> ?case\"\n   proof-\n   assume assms:\"(length w1 = length w2) \\<and>(length w1 = 0)\"\n   have 1:\" w1 = []\"\n          using assms by auto\n   moreover have 2:\"(length w1 = length w2) \\<and>(length w1 = 0) \\<longrightarrow> w2 = []\"\n     by auto\n   ultimately have \"(length w1 = length w2) \\<and>(length w1 = 0) \n                                   \\<longrightarrow> scalar_product w1 w2 = zer\"\n     unfolding scalar_product_def scalar_prodI_def by auto\n   then have 3:\"(length w1 = length w2) \\<and>(length w1 = 0) \n                                   \\<longrightarrow> (f (x*y) (scalar_product w1 w2)) = zer\"\n                  using comm zer_left_mult  by metis\n   then have \"times x w1 = []\"\n               using 1 by auto\n   moreover have \"times y w2 = []\"\n               using 2 assms by auto\n   ultimately have \"(scalar_product (times x w1) ( times y w2)) = zer\"\n               unfolding scalar_product_def scalar_prodI_def by auto\n   with 3 show ?thesis by auto\n   qed\n  then show ?case by auto\n next\n case (Suc k)\n  have \"(length w1 = length w2) \\<and>(length w1 = (Suc k))  \\<Longrightarrow> ?case\"\n    proof-\n     assume assms:\"(length w1 = length w2) \\<and>(length w1 = (Suc k))\"\n     have \"\\<exists>a1 u1.(w1 = a1#u1)\\<and>(length u1 = k)\"\n            using assms by (metis length_Suc_conv)\n     then obtain a1 u1 where \"(w1 = a1#u1)\\<and>(length u1 = k)\"\n             by auto\n     then have Cons_1:\"(w1 = a1#u1)\\<and>(length u1 = k)\"\n             by auto\n      have \"length w2 = (Suc k)\"\n             using assms by auto\n      then have \"\\<exists>a2 u2.(w2 = a2#u2)\\<and>(length u2 = k)\"\n            using assms by (metis length_Suc_conv)\n     then obtain a2 u2 where \"(w2 = a2#u2)\\<and>(length u2 = k)\"\n             by auto\n     then have Cons_2:\"(w2 = a2#u2)\\<and>(length u2 = k)\"\n             by auto \n     then have \"(length u1 = length u2)\\<and>(length u1 = k)\"\n             using Cons_1 by auto\n     then have Cons_3:\"x * y * scalar_product u1 u2 \n                        = scalar_product (times x u1) (times y u2)\"\n             using Suc assms by auto\n     have \"scalar_product (a1#u1) (a2#u2) = (a1*a2) + (scalar_product u1 u2)\"\n                 unfolding scalar_product_def scalar_prodI_def zip_def by auto\n     then have \"scalar_product w1 w2 = (a1*a2) + (scalar_product u1 u2)\"\n                              using Cons_1 Cons_2 by auto\n     then have \"(x*y)*(scalar_product w1 w2) \n                       = ((x*y)*(a1*a2)) + ((x*y)*(scalar_product u1 u2))\" \n                         using plus_right_distributivity by (metis plus_left_distributivity)\n     then have Cons_4:\"(x*y)*(scalar_product w1 w2) \n                       = (x*a1*y*a2)+ ((x*y)*(scalar_product u1 u2))\"  \n                         using comm assoc by metis\n     have \"(times x w1) = (x*a1)#(times x u1)\"\n               using times.simps Cons_1 by auto\n     moreover have \"(times y w2) = (y*a2)#(times y u2)\"\n               using times.simps Cons_2 by auto\n     ultimately have Cons_5:\"scalar_product (times x w1) (times y w2) \n                            = scalar_product \n                                  ((x*a1)#(times x u1)) \n                                  ((y*a2)#(times y u2))\"\n                       by auto  \n     then have \"... = ((x*a1)*(y*a2)) \n                             + scalar_product (times x u1) (times y u2)\"\n                       unfolding scalar_product_def scalar_prodI_def zip_def \n                       by auto\n     with Cons_3 Cons_4 Cons_5 show ?thesis using assoc by auto\n    qed\n  then show ?case by auto\nqed\n\n\nlemma effective_scalar_product_times:\n assumes \"(length w1 = length w2)\"  \n shows \"(f (x*y) (scalar_product w1 w2)) \n                       = (scalar_product (times x w1) ( times y w2))\"\n      using scalar_product_times assms by auto \n\n\nlemma zip_append:\"(length zs = length ws)\\<and>(length xs = length ys) \n                       \\<Longrightarrow> (zip (xs@zs) (ys@ws)) = (zip xs ys)@(zip zs ws)\"\n                      using zip_append1 zip_append2 by auto \n\nfind_theorems foldr\nvalue \"foldr (\\<lambda>z. op + z) [(1::nat),2,3,4] 0\"\n\n\n\nlemma effective_scalar_product_append:\nassumes \"length zs = length ws\" and  \"(length xs = length ys)\"   \n shows \"(scalar_product (xs@zs) (ys@ws)) = (scalar_product xs ys)+(scalar_product zs ws)\"\n    using scalar_product_append assms by auto\n\nlemma scalar_product_distributivity:\n\"\\<forall>v1 v2 w1 w2.((length v1 = length v2)\\<and>(length v1 = n)\\<and> (length w1 = length w2)\n           \\<longrightarrow>  (scalar_product v1 v2)*(scalar_product w1 w2)\n      = scalar_product (vec_vec_Tensor v1 w1) (vec_vec_Tensor v2 w2)) \"\n apply (rule allI)\n apply (rule allI)\n apply (rule allI)\n apply (rule allI)\n proof(induct \"n\")\n case 0 \n    have \"((length v1 = length v2)\\<and>(length v1 = 0)\\<and> (length w1 = length w2))\n           \\<longrightarrow>length v1 = 0\"\n            using 0 by auto\n    then have 1:\"((length v1 = length v2)\n                 \\<and>(length v1 = 0)\n                 \\<and>(length w1 = length w2))\n                        \\<longrightarrow>v1 = []\"\n               by auto\n    moreover have \"((length v1 = length v2)\n                   \\<and>(length v1 = 0)\n                   \\<and>(length w1 = length w2))\n           \\<longrightarrow>length v2 = 0\"\n             using 0 by auto\n    moreover then have 2:\"((length v1 = length v2)\n                          \\<and>(length v1 = 0)\n                          \\<and>(length w1 = length w2))\n                                    \\<longrightarrow>v2 = []\"\n             by auto  \n    ultimately have 3:\n         \"((length v1 = length v2)\\<and>(length v1 = 0)\\<and> (length w1 = length w2))\n           \\<longrightarrow>scalar_product v1 v2 = zer\"\n                 unfolding scalar_product_def scalar_prodI_def \n                 using zip_Nil by auto \n    then have 4:\"f zer (scalar_product w1 w2) = zer\"\n              using zer_left_mult by auto\n    have \"((length v1 = length v2)\\<and>(length v1 = 0)\\<and> (length w1 = length w2))\n           \\<longrightarrow>vec_vec_Tensor v1 w1 = []\"\n            using 1 by auto\n    moreover have \"((length v1 = length v2)\n                   \\<and>(length v1 = 0)\n                   \\<and>(length w1 = length w2))\n                    \\<longrightarrow>vec_vec_Tensor v2 w2 = []\"\n            using 2 by auto\n    ultimately have \"((length v1 = length v2)\n                      \\<and>(length v1 = 0)\n                      \\<and>(length w1 = length w2))\n                         \\<longrightarrow> scalar_product \n                                 (vec_vec_Tensor v1 w1) \n                                 (vec_vec_Tensor v2 w2)  = zer\"\n                unfolding scalar_product_def scalar_prodI_def \n                using zip_Nil by auto\n    with 3 4 show ?case by auto   \n next\n case (Suc k)\n  have \"((length v1 = length v2)\\<and>(length v1 = Suc k)\n                    \\<and> (length w1 = length w2))\n           \\<Longrightarrow>  f (scalar_product v1 v2) (scalar_product w1 w2)\n      = scalar_product (vec_vec_Tensor v1 w1) (vec_vec_Tensor v2 w2)\"\n     proof-\n     assume assms:\"((length v1 = length v2)\\<and>(length v1 = Suc k)\n                    \\<and> (length w1 = length w2))\"\n      have \"length v1 = Suc k\"\n              using Suc assms by auto\n  then have \"(\\<exists>a1 u1.(v1 = a1#u1)\\<and>(length u1 = k))\"\n           using assms Suc_length_conv by metis\n  then obtain a1 u1 where \"(v1 = a1#u1)\\<and>(length u1 = k)\"\n           using assms    by auto\n  then have Cons_1:\"(v1 = a1#u1)\\<and>(length u1 = k)\"\n            by auto\n  moreover have \"length v2 = Suc k\"\n              using assms Suc by auto\n  then have \"(\\<exists>a2 u2.(v2 = a2#u2)\\<and>(length u2 = k))\"\n           using  Suc_length_conv by metis\n   then obtain a2 u2 where \"(v2 = a2#u2)\\<and>(length u2 = k)\"\n               by auto\n   then have Cons_2: \"(v2 = a2#u2)\\<and>(length u2 = k)\"\n               by simp\n   then have \"length u1 = length u2\"\n             using Cons_1 by auto\n   then have Cons_3:\"(scalar_product u1 u2) * scalar_product w1 w2 =\n         scalar_product (vec_vec_Tensor u1 w1) (vec_vec_Tensor u2 w2)\"\n                     using Suc Cons_1 Cons_2 assms by auto\n   then have \"zip v1 v2 = (a1,a2)#(zip u1 u2)\"\n                using  zip_Cons Cons_1 Cons_2 by auto \n   then have Cons_4:\"scalar_product v1 v2 =  (a1*a2)+ (scalar_product u1 u2)\"  \n                  unfolding scalar_product_def scalar_prodI_def by auto\n   then have \"f (scalar_product v1 v2) (scalar_product w1 w2)\n                      = ((a1*a2)+ (scalar_product u1 u2))*(scalar_product w1 w2)\"\n                      by auto\n   then have \"... = ((a1*a2)*(scalar_product w1 w2)) \n                                     + ((scalar_product u1 u2)*(scalar_product w1 w2))\"\n                 using plus_right_distributivity \n                 by auto\n   then have Cons_5:\"... = ((a1*a2)*(scalar_product w1 w2))\n                       + scalar_product (vec_vec_Tensor u1 w1) (vec_vec_Tensor u2 w2)\"\n                 using Cons_3 by auto\n   then have Cons_6:\"... = (scalar_product (times a1 w1) (times a2 w2))\n                    +  scalar_product (vec_vec_Tensor u1 w1) (vec_vec_Tensor u2 w2)\"\n                 using assms effective_scalar_product_times by auto  \n   then have \"scalar_product (vec_vec_Tensor v1 w1) (vec_vec_Tensor v2 w2)\n                        = scalar_product (vec_vec_Tensor (a1#u1) w1) (vec_vec_Tensor (a2#u2) w2)\"\n                   using Cons_1 Cons_2 by auto\n   moreover have \"(vec_vec_Tensor (a1#u1) w1) = (times a1 w1)@(vec_vec_Tensor u1 w1)\"\n                     using vec_vec_Tensor.simps by auto\n   moreover have \"(vec_vec_Tensor (a2#u2) w2) = (times a2 w2)@(vec_vec_Tensor u2 w2)\"\n                     using vec_vec_Tensor.simps by auto\n   ultimately have Cons_7:\"scalar_product (vec_vec_Tensor v1 w1) (vec_vec_Tensor v2 w2)\n                      = scalar_product ((times a1 w1)@(vec_vec_Tensor u1 w1)) \n                                ((times a2 w2)@(vec_vec_Tensor u2 w2))\"\n                         by auto \n   moreover have \"length (vec_vec_Tensor u2 w2) = length (vec_vec_Tensor u1 w1)\"\n                   using assms by (metis Cons_1 Cons_2 vec_vec_Tensor_length)\n   moreover have \"length (times a1 w1) = (length (times a2 w2))\"\n                   using assms by (metis preserving_length)  \n   ultimately have \"scalar_product ((times a1 w1)@(vec_vec_Tensor u1 w1)) \n                                ((times a2 w2)@(vec_vec_Tensor u2 w2)) = \n                    (scalar_product (times a1 w1) (times a2 w2))\n                    +  scalar_product (vec_vec_Tensor u1 w1) (vec_vec_Tensor u2 w2)\"\n                 using effective_scalar_product_append by auto\n \nthen show ?thesis using Cons_6 Cons_7 \n     `a1 * a2 + scalar_product u1 u2 * scalar_product w1 w2 \n  = a1 * a2 * scalar_product w1 w2 \n + (scalar_product u1 u2 * scalar_product w1 w2)` \nby (metis Cons_3 Cons_4 )\n qed\n then show ?case by auto\nqed\n\nlemma effective_scalar_product_distributivity:\n assumes \"length v1 = length v2\" and \"length w1 = length w2\"\n shows \"(scalar_product v1 v2)*(scalar_product w1 w2)\n      = scalar_product (vec_vec_Tensor v1 w1) (vec_vec_Tensor v2 w2) \"\n     using assms scalar_product_distributivity by auto\n\n\nlemma row_length_constant:assumes \"mat nr nc A\" and \"j < length A\" \n         shows \"length (A!j) = (row_length A)\"\n proof(cases A)\n  case Nil\n    have \"length (A!j) = 0\"\n          using assms(2) Nil by auto\n    then show ?thesis using assms(2) Nil row_length_Nil  by (metis)\n next\n case (Cons v B)\n     have 1:\"\\<forall>x. ((x \\<in> set A) \\<longrightarrow> length x = nr)\"\n         using assms unfolding mat_def Ball_def vec_def by auto\n     moreover have \"(A!j) \\<in> set A\"\n        using assms(2) by auto\n     ultimately have 2:\"length (A!j) = nr\"\n           by auto\n     have \"hd A \\<in> set A\"     \n             using hd_def Cons by auto\n     then have \"row_length A = nr\"\n              using row_length_def 1 by auto\n     then show ?thesis using 2 by auto\nqed\n\n\n\ntheorem row_col_match:\nfixes A1 A2 B1 B2 i j\nassumes wf1:\"mat (row_length A1) (length A1) A1\"\n and wf2:\"mat (row_length A2) (length A2) A2\"\n and wf3:\"mat (row_length B1) (length B1) B1\"\n and wf4:\"mat (row_length B2) (length B2) B2\"\n   and matchAA:\"length A1 = row_length A2\"\n   and matchBB:\"length B1 = row_length B2\"\n   and non_Nil:\"(A1 \\<noteq> [])\\<and>(A2 \\<noteq> [])\\<and>(B1 \\<noteq> [])\\<and>(B2 \\<noteq> [])\"\nand i:\"i<(row_length A1)*(row_length B1)\" and j:\"j< (length A2)*(length B2)\"\nshows \"length (row A1 (i div (row_length B1))) \n                 = length (col A2  (j div (length B2)))\"\n and \"length (row B1 (i mod (row_length B1))) \n                 = length (col B2 (j mod (length B2)))\"\nproof-\n have \"i div (row_length B1) < row_length  A1\" \n            using i by (metis div_left_ineq)\n then have 1:\"length (row A1 (i div (row_length B1))) = length A1\"\n                 unfolding row_def by auto\n have \"j div (length B2)< length A2\"\n           using j by (metis div_left_ineq)\n then have 2:\"length (col A2  (j div (length B2))) = row_length A2\"\n               using row_length_constant wf2  unfolding col_def by auto\n with 1 matchAA show \"length (row A1 (i div (row_length B1)))=length (col A2  (j div (length B2)))\"\n             by auto\n  have \"i mod (row_length B1) < row_length B1\"\n             using i by (metis less_nat_zero_code mod_less_divisor mult_is_0 neq0_conv)\n  then have 2:\"length (row B1 (i mod (row_length B1))) = length B1\"\n             unfolding row_def by auto\n  have \"j mod (length B2) < length B2\"\n             using j by (metis less_nat_zero_code mod_less_divisor mult_is_0 neq0_conv)\n  then have \"length (col B2 (j mod (length B2))) = row_length B2\"\n        using row_length_constant wf4  unfolding col_def by auto\n  with 2 matchBB show \"length (row B1 (i mod (row_length B1))) = length (col B2 (j mod (length B2)))\"\n        by auto\nqed\n\n\nlemma effective_row_col_match: assumes \"matrix_match A1 A2 B1 B2\"\n shows \"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \n\\<longrightarrow>length (row A1 (i div (row_length B1))) = length (col A2  (j div (length B2)))\"\n  \"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \\<longrightarrow>length (row B1 (i mod (row_length B1))) = length (col B2 (j mod (length B2)))\"\n using assms row_col_match unfolding matrix_match_def by auto \n       \n\ntheorem prelim_element_match:\n \"matrix_match A1 A2 B1 B2 \\<Longrightarrow> (\\<forall>i j.((i<(row_length A1)*(row_length B1))\n                              \\<and>(j<(length A2)*(length B2))) \n         \\<longrightarrow>\n(((A1 \\<circ> A2)\\<otimes>(B1 \\<circ>  B2))!j!i\n                  = ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i))\" \n proof- \n assume assms:\"matrix_match A1 A2 B1 B2 \"\n  have 1:\"matrix_match A1 A2 B1 B2\"\n             using assms matrix_compose_cond_def by auto\n then have 2:\"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \\<longrightarrow>\n(((A1 \\<circ> A2)\\<otimes>(B1 \\<circ>  B2))!j!i \n                = (scalar_product (row A1 (i div (row_length B1))) (col A2  (j div (length B2))))\n                   *(scalar_product (row B1 (i mod (row_length B1))) (col B2 (j mod (length B2)))))\"\n           using effective_matrix_match_condn_1 assms  by metis\n moreover from 1 have 3:\"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \\<longrightarrow>\n           ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i = \n                 scalar_product \n          (vec_vec_Tensor (row A1 (i div row_length B1)) (row B1 (i mod row_length B1))) \n          (vec_vec_Tensor (col A2 (j div length B2)) (col B2 (j mod length B2)))\" \n         using effective_matrix_match_condn_2 by auto \n have  \"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \n         \\<longrightarrow>length (row A1 (i div (row_length B1))) = length (col A2  (j div (length B2)))\"\n and \"\\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \n         \\<longrightarrow>length (row B1 (i mod (row_length B1))) = length (col B2 (j mod (length B2)))\"\n           using assms effective_row_col_match by auto  \n then have \" \\<forall>i j. ((i<(row_length A1)*(row_length B1))\\<and>(j<(length A2)*(length B2))) \n         \\<longrightarrow>\n(scalar_product (row A1 (i div (row_length B1))) (col A2  (j div (length B2))))\n                   *(scalar_product (row B1 (i mod (row_length B1))) (col B2 (j mod (length B2))))\n             =  scalar_product \n          (vec_vec_Tensor (row A1 (i div row_length B1)) (row B1 (i mod row_length B1))) \n          (vec_vec_Tensor (col A2 (j div length B2)) (col B2 (j mod length B2)))\" \n       using effective_scalar_product_distributivity by auto\n then show ?thesis using 2 3  by auto\nqed\n\ntheorem element_match:\n \"matrix_match A1 A2 B1 B2 \\<Longrightarrow>(\\<forall>i<((row_length A1)*(row_length B1)).\n                              \\<forall>j<((length A2)*(length B2)). \n(((A1 \\<circ> A2)\\<otimes>(B1 \\<circ>  B2))!j!i\n                  = ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i))\"\n       using prelim_element_match by auto\n\nlemma application: fixes m1 m2 \nshows \"\\<forall>m1 m2.(mat nr nc m1)\n              \\<and>(mat nr nc m2)\n              \\<and>(\\<forall> j < nc. \\<forall> i < nr. m1 ! j ! i = m2 ! j ! i)\n                  \\<longrightarrow> (m1 = m2)\"\n      using mat_eq_index assms by auto\n\n\ntheorem tensor_compose_condn: \nassumes wf1:\"mat nr nc ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))\"\n and wf2:\"mat nr nc ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))\"\n and wf3:\"\\<forall>j<nc.\\<forall>i<nr.(((A1 \\<circ> A2)\\<otimes>(B1 \\<circ>B2))!j!i  \n                              = ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i)\" \n shows \"((A1 \\<circ> A2) \\<otimes> (B1 \\<circ> B2))  \n                              = ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))\" \n apply(simp add:mat_eq_index[OF wf1, OF wf2])\n apply(simp add:wf3)\n done\n\ntext{*The following theorem gives us the distributivity relation of tensor\nproduct with matrix multiplication *}\n\ntheorem distributivity: \nassumes  \"matrix_match A1 A2 B1 B2\"\nshows \"((A1 \\<circ> A2)\\<otimes>(B1\\<circ>B2)) = ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))\" \nproof-\n let ?nr = \" ((row_length A1)*(row_length B1))\"\n let ?nc = \"((length A2)*(length B2))\"\n have \"mat ?nr ?nc ((A1\\<circ>A2)\\<otimes>(B1\\<circ>B2))\"\n          by (metis assms effective_tensor_compose_distribution1)\n moreover have \"mat ?nr ?nc ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))\"\n            using assms by (metis effective_tensor_compose_distribution2)\n moreover have \"\\<forall>j<?nc.\\<forall>i<?nr.\n                   (((A1 \\<circ> A2)\\<otimes>(B1 \\<circ>B2))!j!i \n                                = ((A1 \\<otimes> B1)\\<circ>(A2 \\<otimes> B2))!j!i)\" \n         using element_match assms by auto\n ultimately show ?thesis using tensor_compose_condn by auto\nqed   \n\nend\n\nend\n", "meta": {"author": "prathamesh-t", "repo": "Tangle-Isabelle", "sha": "372f6b5ea473340405f0bb3f5e5502725b04e505", "save_path": "github-repos/isabelle/prathamesh-t-Tangle-Isabelle", "path": "github-repos/isabelle/prathamesh-t-Tangle-Isabelle/Tangle-Isabelle-372f6b5ea473340405f0bb3f5e5502725b04e505/Matrix_Tensor.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7658065787196567}}
{"text": "(*  Title:      HOL/Orderings.thy\n    Author:     Tobias Nipkow, Markus Wenzel, and Larry Paulson\n*)\n\nsection \\<open>Abstract orderings\\<close>\n\ntheory Orderings\nimports HOL\nkeywords \"print_orders\" :: diag\nbegin\n\nML_file \"~~/src/Provers/order.ML\"\nML_file \"~~/src/Provers/quasi.ML\"  (* FIXME unused? *)\n\nsubsection \\<open>Abstract ordering\\<close>\n\nlocale ordering =\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<^bold>\\<le>\" 50)\n   and less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<^bold><\" 50)\n  assumes strict_iff_order: \"a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> a \\<noteq> b\"\n  assumes refl: \"a \\<^bold>\\<le> a\" \\<comment> \\<open>not \\<open>iff\\<close>: makes problems due to multiple (dual) interpretations\\<close>\n    and antisym: \"a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>\\<le> a \\<Longrightarrow> a = b\"\n    and trans: \"a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>\\<le> c \\<Longrightarrow> a \\<^bold>\\<le> c\"\nbegin\n\nlemma strict_implies_order:\n  \"a \\<^bold>< b \\<Longrightarrow> a \\<^bold>\\<le> b\"\n  by (simp add: strict_iff_order)\n\nlemma strict_implies_not_eq:\n  \"a \\<^bold>< b \\<Longrightarrow> a \\<noteq> b\"\n  by (simp add: strict_iff_order)\n\nlemma not_eq_order_implies_strict:\n  \"a \\<noteq> b \\<Longrightarrow> a \\<^bold>\\<le> b \\<Longrightarrow> a \\<^bold>< b\"\n  by (simp add: strict_iff_order)\n\nlemma order_iff_strict:\n  \"a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\"\n  by (auto simp add: strict_iff_order refl)\n\nlemma irrefl: \\<comment> \\<open>not \\<open>iff\\<close>: makes problems due to multiple (dual) interpretations\\<close>\n  \"\\<not> a \\<^bold>< a\"\n  by (simp add: strict_iff_order)\n\nlemma asym:\n  \"a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< a \\<Longrightarrow> False\"\n  by (auto simp add: strict_iff_order intro: antisym)\n\nlemma strict_trans1:\n  \"a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  by (auto simp add: strict_iff_order intro: trans antisym)\n\nlemma strict_trans2:\n  \"a \\<^bold>< b \\<Longrightarrow> b \\<^bold>\\<le> c \\<Longrightarrow> a \\<^bold>< c\"\n  by (auto simp add: strict_iff_order intro: trans antisym)\n\nlemma strict_trans:\n  \"a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  by (auto intro: strict_trans1 strict_implies_order)\n\nend\n\ntext \\<open>Alternative introduction rule with bias towards strict order\\<close>\n\nlemma ordering_strictI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes less_eq_less: \"\\<And>a b. a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\"\n    assumes asym: \"\\<And>a b. a \\<^bold>< b \\<Longrightarrow> \\<not> b \\<^bold>< a\"\n  assumes irrefl: \"\\<And>a. \\<not> a \\<^bold>< a\"\n  assumes trans: \"\\<And>a b c. a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  shows \"ordering less_eq less\"\nproof\n  fix a b\n  show \"a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> a \\<noteq> b\"\n    by (auto simp add: less_eq_less asym irrefl)\nnext\n  fix a\n  show \"a \\<^bold>\\<le> a\"\n    by (auto simp add: less_eq_less)\nnext\n  fix a b c\n  assume \"a \\<^bold>\\<le> b\" and \"b \\<^bold>\\<le> c\" then show \"a \\<^bold>\\<le> c\"\n    by (auto simp add: less_eq_less intro: trans)\nnext\n  fix a b\n  assume \"a \\<^bold>\\<le> b\" and \"b \\<^bold>\\<le> a\" then show \"a = b\"\n    by (auto simp add: less_eq_less asym)\nqed\n\nlemma ordering_dualI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"ordering (\\<lambda>a b. b \\<^bold>\\<le> a) (\\<lambda>a b. b \\<^bold>< a)\"\n  shows \"ordering less_eq less\"\nproof -\n  from assms interpret ordering \"\\<lambda>a b. b \\<^bold>\\<le> a\" \"\\<lambda>a b. b \\<^bold>< a\" .\n  show ?thesis\n    by standard (auto simp: strict_iff_order refl intro: antisym trans)\nqed\n\nlocale ordering_top = ordering +\n  fixes top :: \"'a\"  (\"\\<^bold>\\<top>\")\n  assumes extremum [simp]: \"a \\<^bold>\\<le> \\<^bold>\\<top>\"\nbegin\n\nlemma extremum_uniqueI:\n  \"\\<^bold>\\<top> \\<^bold>\\<le> a \\<Longrightarrow> a = \\<^bold>\\<top>\"\n  by (rule antisym) auto\n\nlemma extremum_unique:\n  \"\\<^bold>\\<top> \\<^bold>\\<le> a \\<longleftrightarrow> a = \\<^bold>\\<top>\"\n  by (auto intro: antisym)\n\nlemma extremum_strict [simp]:\n  \"\\<not> (\\<^bold>\\<top> \\<^bold>< a)\"\n  using extremum [of a] by (auto simp add: order_iff_strict intro: asym irrefl)\n\nlemma not_eq_extremum:\n  \"a \\<noteq> \\<^bold>\\<top> \\<longleftrightarrow> a \\<^bold>< \\<^bold>\\<top>\"\n  by (auto simp add: order_iff_strict intro: not_eq_order_implies_strict extremum)\n\nend\n\n\nsubsection \\<open>Syntactic orders\\<close>\n\nclass ord =\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    and less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation\n  less_eq  (\"op \\<le>\") and\n  less_eq  (\"(_/ \\<le> _)\"  [51, 51] 50) and\n  less  (\"op <\") and\n  less  (\"(_/ < _)\"  [51, 51] 50)\n\nabbreviation (input)\n  greater_eq  (infix \"\\<ge>\" 50)\n  where \"x \\<ge> y \\<equiv> y \\<le> x\"\n\nabbreviation (input)\n  greater  (infix \">\" 50)\n  where \"x > y \\<equiv> y < x\"\n\nnotation (ASCII)\n  less_eq  (\"op <=\") and\n  less_eq  (\"(_/ <= _)\" [51, 51] 50)\n\nnotation (input)\n  greater_eq  (infix \">=\" 50)\n\nend\n\n\nsubsection \\<open>Quasi orders\\<close>\n\nclass preorder = ord +\n  assumes less_le_not_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> (y \\<le> x)\"\n  and order_refl [iff]: \"x \\<le> x\"\n  and order_trans: \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\nbegin\n\ntext \\<open>Reflexivity.\\<close>\n\nlemma eq_refl: \"x = y \\<Longrightarrow> x \\<le> y\"\n    \\<comment> \\<open>This form is useful with the classical reasoner.\\<close>\nby (erule ssubst) (rule order_refl)\n\nlemma less_irrefl [iff]: \"\\<not> x < x\"\nby (simp add: less_le_not_le)\n\nlemma less_imp_le: \"x < y \\<Longrightarrow> x \\<le> y\"\nby (simp add: less_le_not_le)\n\n\ntext \\<open>Asymmetry.\\<close>\n\nlemma less_not_sym: \"x < y \\<Longrightarrow> \\<not> (y < x)\"\nby (simp add: less_le_not_le)\n\nlemma less_asym: \"x < y \\<Longrightarrow> (\\<not> P \\<Longrightarrow> y < x) \\<Longrightarrow> P\"\nby (drule less_not_sym, erule contrapos_np) simp\n\n\ntext \\<open>Transitivity.\\<close>\n\nlemma less_trans: \"x < y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\nlemma le_less_trans: \"x \\<le> y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\nlemma less_le_trans: \"x < y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\n\ntext \\<open>Useful for simplification, but too risky to include by default.\\<close>\n\nlemma less_imp_not_less: \"x < y \\<Longrightarrow> (\\<not> y < x) \\<longleftrightarrow> True\"\nby (blast elim: less_asym)\n\nlemma less_imp_triv: \"x < y \\<Longrightarrow> (y < x \\<longrightarrow> P) \\<longleftrightarrow> True\"\nby (blast elim: less_asym)\n\n\ntext \\<open>Transitivity rules for calculational reasoning\\<close>\n\nlemma less_asym': \"a < b \\<Longrightarrow> b < a \\<Longrightarrow> P\"\nby (rule less_asym)\n\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_preorder:\n  \"class.preorder (op \\<ge>) (op >)\"\n  by standard (auto simp add: less_le_not_le intro: order_trans)\n\nend\n\n\nsubsection \\<open>Partial orders\\<close>\n\nclass order = preorder +\n  assumes antisym: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma less_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> x \\<noteq> y\"\n  by (auto simp add: less_le_not_le intro: antisym)\n\nsublocale order: ordering less_eq less + dual_order: ordering greater_eq greater\nproof -\n  interpret ordering less_eq less\n    by standard (auto intro: antisym order_trans simp add: less_le)\n  show \"ordering less_eq less\"\n    by (fact ordering_axioms)\n  then show \"ordering greater_eq greater\"\n    by (rule ordering_dualI)\nqed\n\ntext \\<open>Reflexivity.\\<close>\n\nlemma le_less: \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x = y\"\n    \\<comment> \\<open>NOT suitable for iff, since it can cause PROOF FAILED.\\<close>\nby (fact order.order_iff_strict)\n\nlemma le_imp_less_or_eq: \"x \\<le> y \\<Longrightarrow> x < y \\<or> x = y\"\nby (simp add: less_le)\n\n\ntext \\<open>Useful for simplification, but too risky to include by default.\\<close>\n\nlemma less_imp_not_eq: \"x < y \\<Longrightarrow> (x = y) \\<longleftrightarrow> False\"\nby auto\n\nlemma less_imp_not_eq2: \"x < y \\<Longrightarrow> (y = x) \\<longleftrightarrow> False\"\nby auto\n\n\ntext \\<open>Transitivity rules for calculational reasoning\\<close>\n\nlemma neq_le_trans: \"a \\<noteq> b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a < b\"\nby (fact order.not_eq_order_implies_strict)\n\nlemma le_neq_trans: \"a \\<le> b \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a < b\"\nby (rule order.not_eq_order_implies_strict)\n\n\ntext \\<open>Asymmetry.\\<close>\n\nlemma eq_iff: \"x = y \\<longleftrightarrow> x \\<le> y \\<and> y \\<le> x\"\nby (blast intro: antisym)\n\nlemma antisym_conv: \"y \\<le> x \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x = y\"\nby (blast intro: antisym)\n\nlemma less_imp_neq: \"x < y \\<Longrightarrow> x \\<noteq> y\"\nby (fact order.strict_implies_not_eq)\n\n\ntext \\<open>Least value operator\\<close>\n\ndefinition (in ord)\n  Least :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \"LEAST \" 10) where\n  \"Least P = (THE x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<le> y))\"\n\nlemma Least_equality:\n  assumes \"P x\"\n    and \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n  shows \"Least P = x\"\nunfolding Least_def by (rule the_equality)\n  (blast intro: assms antisym)+\n\nlemma LeastI2_order:\n  assumes \"P x\"\n    and \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n    and \"\\<And>x. P x \\<Longrightarrow> \\<forall>y. P y \\<longrightarrow> x \\<le> y \\<Longrightarrow> Q x\"\n  shows \"Q (Least P)\"\nunfolding Least_def by (rule theI2)\n  (blast intro: assms antisym)+\n\nend\n\nlemma ordering_orderI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"ordering less_eq less\"\n  shows \"class.order less_eq less\"\nproof -\n  from assms interpret ordering less_eq less .\n  show ?thesis\n    by standard (auto intro: antisym trans simp add: refl strict_iff_order)\nqed\n\nlemma order_strictI:\n  fixes less (infix \"\\<sqsubset>\" 50)\n    and less_eq (infix \"\\<sqsubseteq>\" 50)\n  assumes \"\\<And>a b. a \\<sqsubseteq> b \\<longleftrightarrow> a \\<sqsubset> b \\<or> a = b\"\n    assumes \"\\<And>a b. a \\<sqsubset> b \\<Longrightarrow> \\<not> b \\<sqsubset> a\"\n  assumes \"\\<And>a. \\<not> a \\<sqsubset> a\"\n  assumes \"\\<And>a b c. a \\<sqsubset> b \\<Longrightarrow> b \\<sqsubset> c \\<Longrightarrow> a \\<sqsubset> c\"\n  shows \"class.order less_eq less\"\n  by (rule ordering_orderI) (rule ordering_strictI, (fact assms)+)\n\ncontext order\nbegin\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_order:\n  \"class.order (op \\<ge>) (op >)\"\n  using dual_order.ordering_axioms by (rule ordering_orderI)\n\nend\n\n\nsubsection \\<open>Linear (total) orders\\<close>\n\nclass linorder = order +\n  assumes linear: \"x \\<le> y \\<or> y \\<le> x\"\nbegin\n\nlemma less_linear: \"x < y \\<or> x = y \\<or> y < x\"\nunfolding less_le using less_le linear by blast\n\nlemma le_less_linear: \"x \\<le> y \\<or> y < x\"\nby (simp add: le_less less_linear)\n\nlemma le_cases [case_names le ge]:\n  \"(x \\<le> y \\<Longrightarrow> P) \\<Longrightarrow> (y \\<le> x \\<Longrightarrow> P) \\<Longrightarrow> P\"\nusing linear by blast\n\nlemma (in linorder) le_cases3:\n  \"\\<lbrakk>\\<lbrakk>x \\<le> y; y \\<le> z\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>y \\<le> x; x \\<le> z\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>x \\<le> z; z \\<le> y\\<rbrakk> \\<Longrightarrow> P;\n    \\<lbrakk>z \\<le> y; y \\<le> x\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>y \\<le> z; z \\<le> x\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>z \\<le> x; x \\<le> y\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (blast intro: le_cases)\n\nlemma linorder_cases [case_names less equal greater]:\n  \"(x < y \\<Longrightarrow> P) \\<Longrightarrow> (x = y \\<Longrightarrow> P) \\<Longrightarrow> (y < x \\<Longrightarrow> P) \\<Longrightarrow> P\"\nusing less_linear by blast\n\nlemma linorder_wlog[case_names le sym]:\n  \"(\\<And>a b. a \\<le> b \\<Longrightarrow> P a b) \\<Longrightarrow> (\\<And>a b. P b a \\<Longrightarrow> P a b) \\<Longrightarrow> P a b\"\n  by (cases rule: le_cases[of a b]) blast+\n\nlemma not_less: \"\\<not> x < y \\<longleftrightarrow> y \\<le> x\"\napply (simp add: less_le)\nusing linear apply (blast intro: antisym)\ndone\n\nlemma not_less_iff_gr_or_eq:\n \"\\<not>(x < y) \\<longleftrightarrow> (x > y | x = y)\"\napply(simp add:not_less le_less)\napply blast\ndone\n\nlemma not_le: \"\\<not> x \\<le> y \\<longleftrightarrow> y < x\"\napply (simp add: less_le)\nusing linear apply (blast intro: antisym)\ndone\n\nlemma neq_iff: \"x \\<noteq> y \\<longleftrightarrow> x < y \\<or> y < x\"\nby (cut_tac x = x and y = y in less_linear, auto)\n\nlemma neqE: \"x \\<noteq> y \\<Longrightarrow> (x < y \\<Longrightarrow> R) \\<Longrightarrow> (y < x \\<Longrightarrow> R) \\<Longrightarrow> R\"\nby (simp add: neq_iff) blast\n\nlemma antisym_conv1: \"\\<not> x < y \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x = y\"\nby (blast intro: antisym dest: not_less [THEN iffD1])\n\nlemma antisym_conv2: \"x \\<le> y \\<Longrightarrow> \\<not> x < y \\<longleftrightarrow> x = y\"\nby (blast intro: antisym dest: not_less [THEN iffD1])\n\nlemma antisym_conv3: \"\\<not> y < x \\<Longrightarrow> \\<not> x < y \\<longleftrightarrow> x = y\"\nby (blast intro: antisym dest: not_less [THEN iffD1])\n\nlemma leI: \"\\<not> x < y \\<Longrightarrow> y \\<le> x\"\nunfolding not_less .\n\nlemma leD: \"y \\<le> x \\<Longrightarrow> \\<not> x < y\"\nunfolding not_less .\n\nlemma not_le_imp_less: \"\\<not> y \\<le> x \\<Longrightarrow> x < y\"\nunfolding not_le .\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_linorder:\n  \"class.linorder (op \\<ge>) (op >)\"\nby (rule class.linorder.intro, rule dual_order) (unfold_locales, rule linear)\n\nend\n\n\ntext \\<open>Alternative introduction rule with bias towards strict order\\<close>\n\nlemma linorder_strictI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"class.order less_eq less\"\n  assumes trichotomy: \"\\<And>a b. a \\<^bold>< b \\<or> a = b \\<or> b \\<^bold>< a\"\n  shows \"class.linorder less_eq less\"\nproof -\n  interpret order less_eq less\n    by (fact \\<open>class.order less_eq less\\<close>)\n  show ?thesis\n  proof\n    fix a b\n    show \"a \\<^bold>\\<le> b \\<or> b \\<^bold>\\<le> a\"\n      using trichotomy by (auto simp add: le_less)\n  qed\nqed\n\n\nsubsection \\<open>Reasoning tools setup\\<close>\n\nML \\<open>\nsignature ORDERS =\nsig\n  val print_structures: Proof.context -> unit\n  val order_tac: Proof.context -> thm list -> int -> tactic\n  val add_struct: string * term list -> string -> attribute\n  val del_struct: string * term list -> attribute\nend;\n\nstructure Orders: ORDERS =\nstruct\n\n(* context data *)\n\nfun struct_eq ((s1: string, ts1), (s2, ts2)) =\n  s1 = s2 andalso eq_list (op aconv) (ts1, ts2);\n\nstructure Data = Generic_Data\n(\n  type T = ((string * term list) * Order_Tac.less_arith) list;\n    (* Order structures:\n       identifier of the structure, list of operations and record of theorems\n       needed to set up the transitivity reasoner,\n       identifier and operations identify the structure uniquely. *)\n  val empty = [];\n  val extend = I;\n  fun merge data = AList.join struct_eq (K fst) data;\n);\n\nfun print_structures ctxt =\n  let\n    val structs = Data.get (Context.Proof ctxt);\n    fun pretty_term t = Pretty.block\n      [Pretty.quote (Syntax.pretty_term ctxt t), Pretty.brk 1,\n        Pretty.str \"::\", Pretty.brk 1,\n        Pretty.quote (Syntax.pretty_typ ctxt (type_of t))];\n    fun pretty_struct ((s, ts), _) = Pretty.block\n      [Pretty.str s, Pretty.str \":\", Pretty.brk 1,\n       Pretty.enclose \"(\" \")\" (Pretty.breaks (map pretty_term ts))];\n  in\n    Pretty.writeln (Pretty.big_list \"order structures:\" (map pretty_struct structs))\n  end;\n\nval _ =\n  Outer_Syntax.command @{command_keyword print_orders}\n    \"print order structures available to transitivity reasoner\"\n    (Scan.succeed (Toplevel.keep (print_structures o Toplevel.context_of)));\n\n\n(* tactics *)\n\nfun struct_tac ((s, ops), thms) ctxt facts =\n  let\n    val [eq, le, less] = ops;\n    fun decomp thy (@{const Trueprop} $ t) =\n          let\n            fun excluded t =\n              (* exclude numeric types: linear arithmetic subsumes transitivity *)\n              let val T = type_of t\n              in\n                T = HOLogic.natT orelse T = HOLogic.intT orelse T = HOLogic.realT\n              end;\n            fun rel (bin_op $ t1 $ t2) =\n                  if excluded t1 then NONE\n                  else if Pattern.matches thy (eq, bin_op) then SOME (t1, \"=\", t2)\n                  else if Pattern.matches thy (le, bin_op) then SOME (t1, \"<=\", t2)\n                  else if Pattern.matches thy (less, bin_op) then SOME (t1, \"<\", t2)\n                  else NONE\n              | rel _ = NONE;\n            fun dec (Const (@{const_name Not}, _) $ t) =\n                  (case rel t of NONE =>\n                    NONE\n                  | SOME (t1, rel, t2) => SOME (t1, \"~\" ^ rel, t2))\n              | dec x = rel x;\n          in dec t end\n      | decomp _ _ = NONE;\n  in\n    (case s of\n      \"order\" => Order_Tac.partial_tac decomp thms ctxt facts\n    | \"linorder\" => Order_Tac.linear_tac decomp thms ctxt facts\n    | _ => error (\"Unknown order kind \" ^ quote s ^ \" encountered in transitivity reasoner\"))\n  end\n\nfun order_tac ctxt facts =\n  FIRST' (map (fn s => CHANGED o struct_tac s ctxt facts) (Data.get (Context.Proof ctxt)));\n\n\n(* attributes *)\n\nfun add_struct s tag =\n  Thm.declaration_attribute\n    (fn thm => Data.map (AList.map_default struct_eq (s, Order_Tac.empty TrueI) (Order_Tac.update tag thm)));\nfun del_struct s =\n  Thm.declaration_attribute\n    (fn _ => Data.map (AList.delete struct_eq s));\n\nend;\n\\<close>\n\nattribute_setup order = \\<open>\n  Scan.lift ((Args.add -- Args.name >> (fn (_, s) => SOME s) || Args.del >> K NONE) --|\n    Args.colon (* FIXME || Scan.succeed true *) ) -- Scan.lift Args.name --\n    Scan.repeat Args.term\n    >> (fn ((SOME tag, n), ts) => Orders.add_struct (n, ts) tag\n         | ((NONE, n), ts) => Orders.del_struct (n, ts))\n\\<close> \"theorems controlling transitivity reasoner\"\n\nmethod_setup order = \\<open>\n  Scan.succeed (fn ctxt => SIMPLE_METHOD' (Orders.order_tac ctxt []))\n\\<close> \"transitivity reasoner\"\n\n\ntext \\<open>Declarations to set up transitivity reasoner of partial and linear orders.\\<close>\n\ncontext order\nbegin\n\n(* The type constraint on @{term op =} below is necessary since the operation\n   is not a parameter of the locale. *)\n\ndeclare less_irrefl [THEN notE, order add less_reflE: order \"op = :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \"op <=\" \"op <\"]\n\ndeclare order_refl  [order add le_refl: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_imp_le [order add less_imp_le: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare antisym [order add eqI: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare eq_refl [order add eqD1: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare sym [THEN eq_refl, order add eqD2: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_trans [order add less_trans: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_le_trans [order add less_le_trans: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare le_less_trans [order add le_less_trans: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare order_trans [order add le_trans: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare le_neq_trans [order add le_neq_trans: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare neq_le_trans [order add neq_le_trans: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_imp_neq [order add less_imp_neq: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare eq_neq_eq_imp_neq [order add eq_neq_eq_imp_neq: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare not_sym [order add not_sym: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\nend\n\ncontext linorder\nbegin\n\ndeclare [[order del: order \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]]\n\ndeclare less_irrefl [THEN notE, order add less_reflE: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare order_refl [order add le_refl: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_imp_le [order add less_imp_le: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare not_less [THEN iffD2, order add not_lessI: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare not_le [THEN iffD2, order add not_leI: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare not_less [THEN iffD1, order add not_lessD: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare not_le [THEN iffD1, order add not_leD: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare antisym [order add eqI: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare eq_refl [order add eqD1: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare sym [THEN eq_refl, order add eqD2: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_trans [order add less_trans: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_le_trans [order add less_le_trans: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare le_less_trans [order add le_less_trans: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare order_trans [order add le_trans: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare le_neq_trans [order add le_neq_trans: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare neq_le_trans [order add neq_le_trans: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare less_imp_neq [order add less_imp_neq: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare eq_neq_eq_imp_neq [order add eq_neq_eq_imp_neq: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\ndeclare not_sym [order add not_sym: linorder \"op = :: 'a => 'a => bool\" \"op <=\" \"op <\"]\n\nend\n\nsetup \\<open>\n  map_theory_simpset (fn ctxt0 => ctxt0 addSolver\n    mk_solver \"Transitivity\" (fn ctxt => Orders.order_tac ctxt (Simplifier.prems_of ctxt)))\n  (*Adding the transitivity reasoners also as safe solvers showed a slight\n    speed up, but the reasoning strength appears to be not higher (at least\n    no breaking of additional proofs in the entire HOL distribution, as\n    of 5 March 2004, was observed).*)\n\\<close>\n\nML \\<open>\nlocal\n  fun prp t thm = Thm.prop_of thm = t;  (* FIXME proper aconv!? *)\nin\n\nfun antisym_le_simproc ctxt ct =\n  (case Thm.term_of ct of\n    (le as Const (_, T)) $ r $ s =>\n     (let\n        val prems = Simplifier.prems_of ctxt;\n        val less = Const (@{const_name less}, T);\n        val t = HOLogic.mk_Trueprop(le $ s $ r);\n      in\n        (case find_first (prp t) prems of\n          NONE =>\n            let val t = HOLogic.mk_Trueprop(HOLogic.Not $ (less $ r $ s)) in\n              (case find_first (prp t) prems of\n                NONE => NONE\n              | SOME thm => SOME(mk_meta_eq(thm RS @{thm linorder_class.antisym_conv1})))\n             end\n         | SOME thm => SOME (mk_meta_eq (thm RS @{thm order_class.antisym_conv})))\n      end handle THM _ => NONE)\n  | _ => NONE);\n\nfun antisym_less_simproc ctxt ct =\n  (case Thm.term_of ct of\n    NotC $ ((less as Const(_,T)) $ r $ s) =>\n     (let\n       val prems = Simplifier.prems_of ctxt;\n       val le = Const (@{const_name less_eq}, T);\n       val t = HOLogic.mk_Trueprop(le $ r $ s);\n      in\n        (case find_first (prp t) prems of\n          NONE =>\n            let val t = HOLogic.mk_Trueprop (NotC $ (less $ s $ r)) in\n              (case find_first (prp t) prems of\n                NONE => NONE\n              | SOME thm => SOME (mk_meta_eq(thm RS @{thm linorder_class.antisym_conv3})))\n            end\n        | SOME thm => SOME (mk_meta_eq (thm RS @{thm linorder_class.antisym_conv2})))\n      end handle THM _ => NONE)\n  | _ => NONE);\n\nend;\n\\<close>\n\nsimproc_setup antisym_le (\"(x::'a::order) \\<le> y\") = \"K antisym_le_simproc\"\nsimproc_setup antisym_less (\"\\<not> (x::'a::linorder) < y\") = \"K antisym_less_simproc\"\n\n\nsubsection \\<open>Bounded quantifiers\\<close>\n\nsyntax (ASCII)\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _<=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _<=_./ _)\" [0, 0, 10] 10)\n\n  \"_All_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _>_./ _)\"  [0, 0, 10] 10)\n  \"_All_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _>=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _>=_./ _)\" [0, 0, 10] 10)\n\nsyntax\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<le>_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<le>_./ _)\" [0, 0, 10] 10)\n\n  \"_All_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_>_./ _)\"  [0, 0, 10] 10)\n  \"_All_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<ge>_./ _)\" [0, 0, 10] 10)\n  \"_Ex_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<ge>_./ _)\" [0, 0, 10] 10)\n\nsyntax (input)\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _<=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _<=_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"ALL x<y. P\"   =>  \"ALL x. x < y \\<longrightarrow> P\"\n  \"EX x<y. P\"    =>  \"EX x. x < y \\<and> P\"\n  \"ALL x<=y. P\"  =>  \"ALL x. x <= y \\<longrightarrow> P\"\n  \"EX x<=y. P\"   =>  \"EX x. x <= y \\<and> P\"\n  \"ALL x>y. P\"   =>  \"ALL x. x > y \\<longrightarrow> P\"\n  \"EX x>y. P\"    =>  \"EX x. x > y \\<and> P\"\n  \"ALL x>=y. P\"  =>  \"ALL x. x >= y \\<longrightarrow> P\"\n  \"EX x>=y. P\"   =>  \"EX x. x >= y \\<and> P\"\n\nprint_translation \\<open>\nlet\n  val All_binder = Mixfix.binder_name @{const_syntax All};\n  val Ex_binder = Mixfix.binder_name @{const_syntax Ex};\n  val impl = @{const_syntax HOL.implies};\n  val conj = @{const_syntax HOL.conj};\n  val less = @{const_syntax less};\n  val less_eq = @{const_syntax less_eq};\n\n  val trans =\n   [((All_binder, impl, less),\n    (@{syntax_const \"_All_less\"}, @{syntax_const \"_All_greater\"})),\n    ((All_binder, impl, less_eq),\n    (@{syntax_const \"_All_less_eq\"}, @{syntax_const \"_All_greater_eq\"})),\n    ((Ex_binder, conj, less),\n    (@{syntax_const \"_Ex_less\"}, @{syntax_const \"_Ex_greater\"})),\n    ((Ex_binder, conj, less_eq),\n    (@{syntax_const \"_Ex_less_eq\"}, @{syntax_const \"_Ex_greater_eq\"}))];\n\n  fun matches_bound v t =\n    (case t of\n      Const (@{syntax_const \"_bound\"}, _) $ Free (v', _) => v = v'\n    | _ => false);\n  fun contains_var v = Term.exists_subterm (fn Free (x, _) => x = v | _ => false);\n  fun mk x c n P = Syntax.const c $ Syntax_Trans.mark_bound_body x $ n $ P;\n\n  fun tr' q = (q, fn _ =>\n    (fn [Const (@{syntax_const \"_bound\"}, _) $ Free (v, T),\n        Const (c, _) $ (Const (d, _) $ t $ u) $ P] =>\n        (case AList.lookup (op =) trans (q, c, d) of\n          NONE => raise Match\n        | SOME (l, g) =>\n            if matches_bound v t andalso not (contains_var v u) then mk (v, T) l u P\n            else if matches_bound v u andalso not (contains_var v t) then mk (v, T) g t P\n            else raise Match)\n      | _ => raise Match));\nin [tr' All_binder, tr' Ex_binder] end\n\\<close>\n\n\nsubsection \\<open>Transitivity reasoning\\<close>\n\ncontext ord\nbegin\n\nlemma ord_le_eq_trans: \"a \\<le> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<le> c\"\n  by (rule subst)\n\nlemma ord_eq_le_trans: \"a = b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n  by (rule ssubst)\n\nlemma ord_less_eq_trans: \"a < b \\<Longrightarrow> b = c \\<Longrightarrow> a < c\"\n  by (rule subst)\n\nlemma ord_eq_less_trans: \"a = b \\<Longrightarrow> b < c \\<Longrightarrow> a < c\"\n  by (rule ssubst)\n\nend\n\nlemma order_less_subst2: \"(a::'a::order) < b ==> f b < (c::'c::order) ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b < c\"\n  finally (less_trans) show ?thesis .\nqed\n\nlemma order_less_subst1: \"(a::'a::order) < f b ==> (b::'b::order) < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (less_trans) show ?thesis .\nqed\n\nlemma order_le_less_subst2: \"(a::'a::order) <= b ==> f b < (c::'c::order) ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b < c\"\n  finally (le_less_trans) show ?thesis .\nqed\n\nlemma order_le_less_subst1: \"(a::'a::order) <= f b ==> (b::'b::order) < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a <= f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (le_less_trans) show ?thesis .\nqed\n\nlemma order_less_le_subst2: \"(a::'a::order) < b ==> f b <= (c::'c::order) ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b <= c\"\n  finally (less_le_trans) show ?thesis .\nqed\n\nlemma order_less_le_subst1: \"(a::'a::order) < f b ==> (b::'b::order) <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a < f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (less_le_trans) show ?thesis .\nqed\n\nlemma order_subst1: \"(a::'a::order) <= f b ==> (b::'b::order) <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a <= f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (order_trans) show ?thesis .\nqed\n\nlemma order_subst2: \"(a::'a::order) <= b ==> f b <= (c::'c::order) ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a <= c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b <= c\"\n  finally (order_trans) show ?thesis .\nqed\n\nlemma ord_le_eq_subst: \"a <= b ==> f b = c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a <= c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b = c\"\n  finally (ord_le_eq_trans) show ?thesis .\nqed\n\nlemma ord_eq_le_subst: \"a = f b ==> b <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a <= f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a = f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (ord_eq_le_trans) show ?thesis .\nqed\n\nlemma ord_less_eq_subst: \"a < b ==> f b = c ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b = c\"\n  finally (ord_less_eq_trans) show ?thesis .\nqed\n\nlemma ord_eq_less_subst: \"a = f b ==> b < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a = f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (ord_eq_less_trans) show ?thesis .\nqed\n\ntext \\<open>\n  Note that this list of rules is in reverse order of priorities.\n\\<close>\n\nlemmas [trans] =\n  order_less_subst2\n  order_less_subst1\n  order_le_less_subst2\n  order_le_less_subst1\n  order_less_le_subst2\n  order_less_le_subst1\n  order_subst2\n  order_subst1\n  ord_le_eq_subst\n  ord_eq_le_subst\n  ord_less_eq_subst\n  ord_eq_less_subst\n  forw_subst\n  back_subst\n  rev_mp\n  mp\n\nlemmas (in order) [trans] =\n  neq_le_trans\n  le_neq_trans\n\nlemmas (in preorder) [trans] =\n  less_trans\n  less_asym'\n  le_less_trans\n  less_le_trans\n  order_trans\n\nlemmas (in order) [trans] =\n  antisym\n\nlemmas (in ord) [trans] =\n  ord_le_eq_trans\n  ord_eq_le_trans\n  ord_less_eq_trans\n  ord_eq_less_trans\n\nlemmas [trans] =\n  trans\n\nlemmas order_trans_rules =\n  order_less_subst2\n  order_less_subst1\n  order_le_less_subst2\n  order_le_less_subst1\n  order_less_le_subst2\n  order_less_le_subst1\n  order_subst2\n  order_subst1\n  ord_le_eq_subst\n  ord_eq_le_subst\n  ord_less_eq_subst\n  ord_eq_less_subst\n  forw_subst\n  back_subst\n  rev_mp\n  mp\n  neq_le_trans\n  le_neq_trans\n  less_trans\n  less_asym'\n  le_less_trans\n  less_le_trans\n  order_trans\n  antisym\n  ord_le_eq_trans\n  ord_eq_le_trans\n  ord_less_eq_trans\n  ord_eq_less_trans\n  trans\n\ntext \\<open>These support proving chains of decreasing inequalities\n    a >= b >= c ... in Isar proofs.\\<close>\n\nlemma xt1 [no_atp]:\n  \"a = b ==> b > c ==> a > c\"\n  \"a > b ==> b = c ==> a > c\"\n  \"a = b ==> b >= c ==> a >= c\"\n  \"a >= b ==> b = c ==> a >= c\"\n  \"(x::'a::order) >= y ==> y >= x ==> x = y\"\n  \"(x::'a::order) >= y ==> y >= z ==> x >= z\"\n  \"(x::'a::order) > y ==> y >= z ==> x > z\"\n  \"(x::'a::order) >= y ==> y > z ==> x > z\"\n  \"(a::'a::order) > b ==> b > a ==> P\"\n  \"(x::'a::order) > y ==> y > z ==> x > z\"\n  \"(a::'a::order) >= b ==> a ~= b ==> a > b\"\n  \"(a::'a::order) ~= b ==> a >= b ==> a > b\"\n  \"a = f b ==> b > c ==> (!!x y. x > y ==> f x > f y) ==> a > f c\"\n  \"a > b ==> f b = c ==> (!!x y. x > y ==> f x > f y) ==> f a > c\"\n  \"a = f b ==> b >= c ==> (!!x y. x >= y ==> f x >= f y) ==> a >= f c\"\n  \"a >= b ==> f b = c ==> (!! x y. x >= y ==> f x >= f y) ==> f a >= c\"\n  by auto\n\nlemma xt2 [no_atp]:\n  \"(a::'a::order) >= f b ==> b >= c ==> (!!x y. x >= y ==> f x >= f y) ==> a >= f c\"\nby (subgoal_tac \"f b >= f c\", force, force)\n\nlemma xt3 [no_atp]: \"(a::'a::order) >= b ==> (f b::'b::order) >= c ==>\n    (!!x y. x >= y ==> f x >= f y) ==> f a >= c\"\nby (subgoal_tac \"f a >= f b\", force, force)\n\nlemma xt4 [no_atp]: \"(a::'a::order) > f b ==> (b::'b::order) >= c ==>\n  (!!x y. x >= y ==> f x >= f y) ==> a > f c\"\nby (subgoal_tac \"f b >= f c\", force, force)\n\nlemma xt5 [no_atp]: \"(a::'a::order) > b ==> (f b::'b::order) >= c==>\n    (!!x y. x > y ==> f x > f y) ==> f a > c\"\nby (subgoal_tac \"f a > f b\", force, force)\n\nlemma xt6 [no_atp]: \"(a::'a::order) >= f b ==> b > c ==>\n    (!!x y. x > y ==> f x > f y) ==> a > f c\"\nby (subgoal_tac \"f b > f c\", force, force)\n\nlemma xt7 [no_atp]: \"(a::'a::order) >= b ==> (f b::'b::order) > c ==>\n    (!!x y. x >= y ==> f x >= f y) ==> f a > c\"\nby (subgoal_tac \"f a >= f b\", force, force)\n\nlemma xt8 [no_atp]: \"(a::'a::order) > f b ==> (b::'b::order) > c ==>\n    (!!x y. x > y ==> f x > f y) ==> a > f c\"\nby (subgoal_tac \"f b > f c\", force, force)\n\nlemma xt9 [no_atp]: \"(a::'a::order) > b ==> (f b::'b::order) > c ==>\n    (!!x y. x > y ==> f x > f y) ==> f a > c\"\nby (subgoal_tac \"f a > f b\", force, force)\n\nlemmas xtrans = xt1 xt2 xt3 xt4 xt5 xt6 xt7 xt8 xt9\n\n(*\n  Since \"a >= b\" abbreviates \"b <= a\", the abbreviation \"...\" stands\n  for the wrong thing in an Isar proof.\n\n  The extra transitivity rules can be used as follows:\n\nlemma \"(a::'a::order) > z\"\nproof -\n  have \"a >= b\" (is \"_ >= ?rhs\")\n    sorry\n  also have \"?rhs >= c\" (is \"_ >= ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs = d\" (is \"_ = ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs >= e\" (is \"_ >= ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs > f\" (is \"_ > ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs > z\"\n    sorry\n  finally (xtrans) show ?thesis .\nqed\n\n  Alternatively, one can use \"declare xtrans [trans]\" and then\n  leave out the \"(xtrans)\" above.\n*)\n\n\nsubsection \\<open>Monotonicity\\<close>\n\ncontext order\nbegin\n\ndefinition mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"mono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nlemma monoI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> mono f\"\n  unfolding mono_def by iprover\n\nlemma monoD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"mono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  unfolding mono_def by iprover\n\nlemma monoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<le> f y\"\nproof\n  from assms show \"f x \\<le> f y\" by (simp add: mono_def)\nqed\n\ndefinition antimono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"antimono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<ge> f y)\"\n\nlemma antimonoI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> antimono f\"\n  unfolding antimono_def by iprover\n\nlemma antimonoD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"antimono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  unfolding antimono_def by iprover\n\nlemma antimonoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"antimono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<ge> f y\"\nproof\n  from assms show \"f x \\<ge> f y\" by (simp add: antimono_def)\nqed\n\ndefinition strict_mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"strict_mono f \\<longleftrightarrow> (\\<forall>x y. x < y \\<longrightarrow> f x < f y)\"\n\nlemma strict_monoI [intro?]:\n  assumes \"\\<And>x y. x < y \\<Longrightarrow> f x < f y\"\n  shows \"strict_mono f\"\n  using assms unfolding strict_mono_def by auto\n\nlemma strict_monoD [dest?]:\n  \"strict_mono f \\<Longrightarrow> x < y \\<Longrightarrow> f x < f y\"\n  unfolding strict_mono_def by auto\n\nlemma strict_mono_mono [dest?]:\n  assumes \"strict_mono f\"\n  shows \"mono f\"\nproof (rule monoI)\n  fix x y\n  assume \"x \\<le> y\"\n  show \"f x \\<le> f y\"\n  proof (cases \"x = y\")\n    case True then show ?thesis by simp\n  next\n    case False with \\<open>x \\<le> y\\<close> have \"x < y\" by simp\n    with assms strict_monoD have \"f x < f y\" by auto\n    then show ?thesis by simp\n  qed\nqed\n\nend\n\ncontext linorder\nbegin\n\nlemma mono_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x \\<le> y\"\nproof\n  show \"x \\<le> y\"\n  proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_eq:\n  assumes \"strict_mono f\"\n  shows \"f x = f y \\<longleftrightarrow> x = y\"\nproof\n  assume \"f x = f y\"\n  show \"x = y\" proof (cases x y rule: linorder_cases)\n    case less with assms strict_monoD have \"f x < f y\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  next\n    case equal then show ?thesis .\n  next\n    case greater with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  qed\nqed simp\n\nlemma strict_mono_less_eq:\n  assumes \"strict_mono f\"\n  shows \"f x \\<le> f y \\<longleftrightarrow> x \\<le> y\"\nproof\n  assume \"x \\<le> y\"\n  with assms strict_mono_mono monoD show \"f x \\<le> f y\" by auto\nnext\n  assume \"f x \\<le> f y\"\n  show \"x \\<le> y\" proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\" then have \"y < x\" by simp\n    with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x \\<le> f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_less:\n  assumes \"strict_mono f\"\n  shows \"f x < f y \\<longleftrightarrow> x < y\"\n  using assms\n    by (auto simp add: less_le Orderings.less_le strict_mono_eq strict_mono_less_eq)\n\nend\n\n\nsubsection \\<open>min and max -- fundamental\\<close>\n\ndefinition (in ord) min :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"min a b = (if a \\<le> b then a else b)\"\n\ndefinition (in ord) max :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"max a b = (if a \\<le> b then b else a)\"\n\nlemma min_absorb1: \"x \\<le> y \\<Longrightarrow> min x y = x\"\n  by (simp add: min_def)\n\nlemma max_absorb2: \"x \\<le> y \\<Longrightarrow> max x y = y\"\n  by (simp add: max_def)\n\nlemma min_absorb2: \"(y::'a::order) \\<le> x \\<Longrightarrow> min x y = y\"\n  by (simp add:min_def)\n\nlemma max_absorb1: \"(y::'a::order) \\<le> x \\<Longrightarrow> max x y = x\"\n  by (simp add: max_def)\n\nlemma max_min_same [simp]:\n  fixes x y :: \"'a :: linorder\"\n  shows \"max x (min x y) = x\" \"max (min x y) x = x\" \"max (min x y) y = y\" \"max y (min x y) = y\"\nby(auto simp add: max_def min_def)\n\nsubsection \\<open>(Unique) top and bottom elements\\<close>\n\nclass bot =\n  fixes bot :: 'a (\"\\<bottom>\")\n\nclass order_bot = order + bot +\n  assumes bot_least: \"\\<bottom> \\<le> a\"\nbegin\n\nsublocale bot: ordering_top greater_eq greater bot\n  by standard (fact bot_least)\n\nlemma le_bot:\n  \"a \\<le> \\<bottom> \\<Longrightarrow> a = \\<bottom>\"\n  by (fact bot.extremum_uniqueI)\n\nlemma bot_unique:\n  \"a \\<le> \\<bottom> \\<longleftrightarrow> a = \\<bottom>\"\n  by (fact bot.extremum_unique)\n\nlemma not_less_bot:\n  \"\\<not> a < \\<bottom>\"\n  by (fact bot.extremum_strict)\n\nlemma bot_less:\n  \"a \\<noteq> \\<bottom> \\<longleftrightarrow> \\<bottom> < a\"\n  by (fact bot.not_eq_extremum)\n\nend\n\nclass top =\n  fixes top :: 'a (\"\\<top>\")\n\nclass order_top = order + top +\n  assumes top_greatest: \"a \\<le> \\<top>\"\nbegin\n\nsublocale top: ordering_top less_eq less top\n  by standard (fact top_greatest)\n\nlemma top_le:\n  \"\\<top> \\<le> a \\<Longrightarrow> a = \\<top>\"\n  by (fact top.extremum_uniqueI)\n\nlemma top_unique:\n  \"\\<top> \\<le> a \\<longleftrightarrow> a = \\<top>\"\n  by (fact top.extremum_unique)\n\nlemma not_top_less:\n  \"\\<not> \\<top> < a\"\n  by (fact top.extremum_strict)\n\nlemma less_top:\n  \"a \\<noteq> \\<top> \\<longleftrightarrow> a < \\<top>\"\n  by (fact top.not_eq_extremum)\n\nend\n\n\nsubsection \\<open>Dense orders\\<close>\n\nclass dense_order = order +\n  assumes dense: \"x < y \\<Longrightarrow> (\\<exists>z. x < z \\<and> z < y)\"\n\nclass dense_linorder = linorder + dense_order\nbegin\n\nlemma dense_le:\n  fixes y z :: 'a\n  assumes \"\\<And>x. x < y \\<Longrightarrow> x \\<le> z\"\n  shows \"y \\<le> z\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"z < y\" by simp\n  from dense[OF this]\n  obtain x where \"x < y\" and \"z < x\" by safe\n  moreover have \"x \\<le> z\" using assms[OF \\<open>x < y\\<close>] .\n  ultimately show False by auto\nqed\n\nlemma dense_le_bounded:\n  fixes x y z :: 'a\n  assumes \"x < y\"\n  assumes *: \"\\<And>w. \\<lbrakk> x < w ; w < y \\<rbrakk> \\<Longrightarrow> w \\<le> z\"\n  shows \"y \\<le> z\"\nproof (rule dense_le)\n  fix w assume \"w < y\"\n  from dense[OF \\<open>x < y\\<close>] obtain u where \"x < u\" \"u < y\" by safe\n  from linear[of u w]\n  show \"w \\<le> z\"\n  proof (rule disjE)\n    assume \"u \\<le> w\"\n    from less_le_trans[OF \\<open>x < u\\<close> \\<open>u \\<le> w\\<close>] \\<open>w < y\\<close>\n    show \"w \\<le> z\" by (rule *)\n  next\n    assume \"w \\<le> u\"\n    from \\<open>w \\<le> u\\<close> *[OF \\<open>x < u\\<close> \\<open>u < y\\<close>]\n    show \"w \\<le> z\" by (rule order_trans)\n  qed\nqed\n\nlemma dense_ge:\n  fixes y z :: 'a\n  assumes \"\\<And>x. z < x \\<Longrightarrow> y \\<le> x\"\n  shows \"y \\<le> z\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"z < y\" by simp\n  from dense[OF this]\n  obtain x where \"x < y\" and \"z < x\" by safe\n  moreover have \"y \\<le> x\" using assms[OF \\<open>z < x\\<close>] .\n  ultimately show False by auto\nqed\n\nlemma dense_ge_bounded:\n  fixes x y z :: 'a\n  assumes \"z < x\"\n  assumes *: \"\\<And>w. \\<lbrakk> z < w ; w < x \\<rbrakk> \\<Longrightarrow> y \\<le> w\"\n  shows \"y \\<le> z\"\nproof (rule dense_ge)\n  fix w assume \"z < w\"\n  from dense[OF \\<open>z < x\\<close>] obtain u where \"z < u\" \"u < x\" by safe\n  from linear[of u w]\n  show \"y \\<le> w\"\n  proof (rule disjE)\n    assume \"w \\<le> u\"\n    from \\<open>z < w\\<close> le_less_trans[OF \\<open>w \\<le> u\\<close> \\<open>u < x\\<close>]\n    show \"y \\<le> w\" by (rule *)\n  next\n    assume \"u \\<le> w\"\n    from *[OF \\<open>z < u\\<close> \\<open>u < x\\<close>] \\<open>u \\<le> w\\<close>\n    show \"y \\<le> w\" by (rule order_trans)\n  qed\nqed\n\nend\n\nclass no_top = order +\n  assumes gt_ex: \"\\<exists>y. x < y\"\n\nclass no_bot = order +\n  assumes lt_ex: \"\\<exists>y. y < x\"\n\nclass unbounded_dense_linorder = dense_linorder + no_top + no_bot\n\n\nsubsection \\<open>Wellorders\\<close>\n\nclass wellorder = linorder +\n  assumes less_induct [case_names less]: \"(\\<And>x. (\\<And>y. y < x \\<Longrightarrow> P y) \\<Longrightarrow> P x) \\<Longrightarrow> P a\"\nbegin\n\nlemma wellorder_Least_lemma:\n  fixes k :: 'a\n  assumes \"P k\"\n  shows LeastI: \"P (LEAST x. P x)\" and Least_le: \"(LEAST x. P x) \\<le> k\"\nproof -\n  have \"P (LEAST x. P x) \\<and> (LEAST x. P x) \\<le> k\"\n  using assms proof (induct k rule: less_induct)\n    case (less x) then have \"P x\" by simp\n    show ?case proof (rule classical)\n      assume assm: \"\\<not> (P (LEAST a. P a) \\<and> (LEAST a. P a) \\<le> x)\"\n      have \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n      proof (rule classical)\n        fix y\n        assume \"P y\" and \"\\<not> x \\<le> y\"\n        with less have \"P (LEAST a. P a)\" and \"(LEAST a. P a) \\<le> y\"\n          by (auto simp add: not_le)\n        with assm have \"x < (LEAST a. P a)\" and \"(LEAST a. P a) \\<le> y\"\n          by auto\n        then show \"x \\<le> y\" by auto\n      qed\n      with \\<open>P x\\<close> have Least: \"(LEAST a. P a) = x\"\n        by (rule Least_equality)\n      with \\<open>P x\\<close> show ?thesis by simp\n    qed\n  qed\n  then show \"P (LEAST x. P x)\" and \"(LEAST x. P x) \\<le> k\" by auto\nqed\n\n\\<comment> \"The following 3 lemmas are due to Brian Huffman\"\nlemma LeastI_ex: \"\\<exists>x. P x \\<Longrightarrow> P (Least P)\"\n  by (erule exE) (erule LeastI)\n\nlemma LeastI2:\n  \"P a \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> Q (Least P)\"\n  by (blast intro: LeastI)\n\nlemma LeastI2_ex:\n  \"\\<exists>a. P a \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> Q (Least P)\"\n  by (blast intro: LeastI_ex)\n\nlemma LeastI2_wellorder:\n  assumes \"P a\"\n  and \"\\<And>a. \\<lbrakk> P a; \\<forall>b. P b \\<longrightarrow> a \\<le> b \\<rbrakk> \\<Longrightarrow> Q a\"\n  shows \"Q (Least P)\"\nproof (rule LeastI2_order)\n  show \"P (Least P)\" using \\<open>P a\\<close> by (rule LeastI)\nnext\n  fix y assume \"P y\" thus \"Least P \\<le> y\" by (rule Least_le)\nnext\n  fix x assume \"P x\" \"\\<forall>y. P y \\<longrightarrow> x \\<le> y\" thus \"Q x\" by (rule assms(2))\nqed\n\nlemma LeastI2_wellorder_ex:\n  assumes \"\\<exists>x. P x\"\n  and \"\\<And>a. \\<lbrakk> P a; \\<forall>b. P b \\<longrightarrow> a \\<le> b \\<rbrakk> \\<Longrightarrow> Q a\"\n  shows \"Q (Least P)\"\nusing assms by clarify (blast intro!: LeastI2_wellorder)\n\nlemma not_less_Least: \"k < (LEAST x. P x) \\<Longrightarrow> \\<not> P k\"\napply (simp add: not_le [symmetric])\napply (erule contrapos_nn)\napply (erule Least_le)\ndone\n\nlemma exists_least_iff: \"(\\<exists>n. P n) \\<longleftrightarrow> (\\<exists>n. P n \\<and> (\\<forall>m < n. \\<not> P m))\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs thus ?lhs by blast\nnext\n  assume H: ?lhs then obtain n where n: \"P n\" by blast\n  let ?x = \"Least P\"\n  { fix m assume m: \"m < ?x\"\n    from not_less_Least[OF m] have \"\\<not> P m\" . }\n  with LeastI_ex[OF H] show ?rhs by blast\nqed\n\nend\n\n\nsubsection \\<open>Order on @{typ bool}\\<close>\n\ninstantiation bool :: \"{order_bot, order_top, linorder}\"\nbegin\n\ndefinition\n  le_bool_def [simp]: \"P \\<le> Q \\<longleftrightarrow> P \\<longrightarrow> Q\"\n\ndefinition\n  [simp]: \"(P::bool) < Q \\<longleftrightarrow> \\<not> P \\<and> Q\"\n\ndefinition\n  [simp]: \"\\<bottom> \\<longleftrightarrow> False\"\n\ndefinition\n  [simp]: \"\\<top> \\<longleftrightarrow> True\"\n\ninstance proof\nqed auto\n\nend\n\nlemma le_boolI: \"(P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<le> Q\"\n  by simp\n\nlemma le_boolI': \"P \\<longrightarrow> Q \\<Longrightarrow> P \\<le> Q\"\n  by simp\n\nlemma le_boolE: \"P \\<le> Q \\<Longrightarrow> P \\<Longrightarrow> (Q \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by simp\n\nlemma le_boolD: \"P \\<le> Q \\<Longrightarrow> P \\<longrightarrow> Q\"\n  by simp\n\nlemma bot_boolE: \"\\<bottom> \\<Longrightarrow> P\"\n  by simp\n\nlemma top_boolI: \\<top>\n  by simp\n\n\n\n\nsubsection \\<open>Order on @{typ \"_ \\<Rightarrow> _\"}\\<close>\n\ninstantiation \"fun\" :: (type, ord) ord\nbegin\n\ndefinition\n  le_fun_def: \"f \\<le> g \\<longleftrightarrow> (\\<forall>x. f x \\<le> g x)\"\n\ndefinition\n  \"(f::'a \\<Rightarrow> 'b) < g \\<longleftrightarrow> f \\<le> g \\<and> \\<not> (g \\<le> f)\"\n\ninstance ..\n\nend\n\ninstance \"fun\" :: (type, preorder) preorder proof\nqed (auto simp add: le_fun_def less_fun_def\n  intro: order_trans antisym)\n\ninstance \"fun\" :: (type, order) order proof\nqed (auto simp add: le_fun_def intro: antisym)\n\ninstantiation \"fun\" :: (type, bot) bot\nbegin\n\ndefinition\n  \"\\<bottom> = (\\<lambda>x. \\<bottom>)\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, order_bot) order_bot\nbegin\n\nlemma bot_apply [simp, code]:\n  \"\\<bottom> x = \\<bottom>\"\n  by (simp add: bot_fun_def)\n\ninstance proof\nqed (simp add: le_fun_def)\n\nend\n\ninstantiation \"fun\" :: (type, top) top\nbegin\n\ndefinition\n  [no_atp]: \"\\<top> = (\\<lambda>x. \\<top>)\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, order_top) order_top\nbegin\n\nlemma top_apply [simp, code]:\n  \"\\<top> x = \\<top>\"\n  by (simp add: top_fun_def)\n\ninstance proof\nqed (simp add: le_fun_def)\n\nend\n\nlemma le_funI: \"(\\<And>x. f x \\<le> g x) \\<Longrightarrow> f \\<le> g\"\n  unfolding le_fun_def by simp\n\nlemma le_funE: \"f \\<le> g \\<Longrightarrow> (f x \\<le> g x \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding le_fun_def by simp\n\nlemma le_funD: \"f \\<le> g \\<Longrightarrow> f x \\<le> g x\"\n  by (rule le_funE)\n\nlemma mono_compose: \"mono Q \\<Longrightarrow> mono (\\<lambda>i x. Q i (f x))\"\n  unfolding mono_def le_fun_def by auto\n\n\nsubsection \\<open>Order on unary and binary predicates\\<close>\n\nlemma predicate1I:\n  assumes PQ: \"\\<And>x. P x \\<Longrightarrow> Q x\"\n  shows \"P \\<le> Q\"\n  apply (rule le_funI)\n  apply (rule le_boolI)\n  apply (rule PQ)\n  apply assumption\n  done\n\nlemma predicate1D:\n  \"P \\<le> Q \\<Longrightarrow> P x \\<Longrightarrow> Q x\"\n  apply (erule le_funE)\n  apply (erule le_boolE)\n  apply assumption+\n  done\n\nlemma rev_predicate1D:\n  \"P x \\<Longrightarrow> P \\<le> Q \\<Longrightarrow> Q x\"\n  by (rule predicate1D)\n\nlemma predicate2I:\n  assumes PQ: \"\\<And>x y. P x y \\<Longrightarrow> Q x y\"\n  shows \"P \\<le> Q\"\n  apply (rule le_funI)+\n  apply (rule le_boolI)\n  apply (rule PQ)\n  apply assumption\n  done\n\nlemma predicate2D:\n  \"P \\<le> Q \\<Longrightarrow> P x y \\<Longrightarrow> Q x y\"\n  apply (erule le_funE)+\n  apply (erule le_boolE)\n  apply assumption+\n  done\n\nlemma rev_predicate2D:\n  \"P x y \\<Longrightarrow> P \\<le> Q \\<Longrightarrow> Q x y\"\n  by (rule predicate2D)\n\nlemma bot1E [no_atp]: \"\\<bottom> x \\<Longrightarrow> P\"\n  by (simp add: bot_fun_def)\n\nlemma bot2E: \"\\<bottom> x y \\<Longrightarrow> P\"\n  by (simp add: bot_fun_def)\n\nlemma top1I: \"\\<top> x\"\n  by (simp add: top_fun_def)\n\nlemma top2I: \"\\<top> x y\"\n  by (simp add: top_fun_def)\n\n\nsubsection \\<open>Name duplicates\\<close>\n\nlemmas order_eq_refl = preorder_class.eq_refl\nlemmas order_less_irrefl = preorder_class.less_irrefl\nlemmas order_less_imp_le = preorder_class.less_imp_le\nlemmas order_less_not_sym = preorder_class.less_not_sym\nlemmas order_less_asym = preorder_class.less_asym\nlemmas order_less_trans = preorder_class.less_trans\nlemmas order_le_less_trans = preorder_class.le_less_trans\nlemmas order_less_le_trans = preorder_class.less_le_trans\nlemmas order_less_imp_not_less = preorder_class.less_imp_not_less\nlemmas order_less_imp_triv = preorder_class.less_imp_triv\nlemmas order_less_asym' = preorder_class.less_asym'\n\nlemmas order_less_le = order_class.less_le\nlemmas order_le_less = order_class.le_less\nlemmas order_le_imp_less_or_eq = order_class.le_imp_less_or_eq\nlemmas order_less_imp_not_eq = order_class.less_imp_not_eq\nlemmas order_less_imp_not_eq2 = order_class.less_imp_not_eq2\nlemmas order_neq_le_trans = order_class.neq_le_trans\nlemmas order_le_neq_trans = order_class.le_neq_trans\nlemmas order_antisym = order_class.antisym\nlemmas order_eq_iff = order_class.eq_iff\nlemmas order_antisym_conv = order_class.antisym_conv\n\nlemmas linorder_linear = linorder_class.linear\nlemmas linorder_less_linear = linorder_class.less_linear\nlemmas linorder_le_less_linear = linorder_class.le_less_linear\nlemmas linorder_le_cases = linorder_class.le_cases\nlemmas linorder_not_less = linorder_class.not_less\nlemmas linorder_not_le = linorder_class.not_le\nlemmas linorder_neq_iff = linorder_class.neq_iff\nlemmas linorder_neqE = linorder_class.neqE\nlemmas linorder_antisym_conv1 = linorder_class.antisym_conv1\nlemmas linorder_antisym_conv2 = linorder_class.antisym_conv2\nlemmas linorder_antisym_conv3 = linorder_class.antisym_conv3\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Orderings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479467, "lm_q2_score": 0.8740772466456689, "lm_q1q2_score": 0.7655054823077306}}
{"text": "section \\<open>Ackermann's Function and the PR Functions\\<close>\n\ntext \\<open>\n  This proof has been adopted from a development by Nora Szasz \\<^cite>\\<open>\"szasz93\"\\<close>.\n  \\medskip\n\\<close>\n\n\ntheory Primrec imports Main begin\n\n\nsubsection\\<open>Ackermann's Function\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n =  Suc n\"\n| \"ack (Suc m) 0 = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\n\ntext \\<open>PROPERTY A 4\\<close>\n\nlemma less_ack2 [iff]: \"j < ack i j\"\n  by (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5-, the single-step lemma\\<close>\n\nlemma ack_less_ack_Suc2 [iff]: \"ack i j < ack i (Suc j)\"\n  by (induct i j rule: ack.induct) simp_all\n\n\ntext \\<open>PROPERTY A 5, monotonicity for \\<open><\\<close>\\<close>\n\nlemma ack_less_mono2: \"j < k \\<Longrightarrow> ack i j < ack i k\"\n  by (simp add: lift_Suc_mono_less)\n\n\ntext \\<open>PROPERTY A 5', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono2: \"j \\<le> k \\<Longrightarrow> ack i j \\<le> ack i k\"\n  by (simp add: ack_less_mono2 less_mono_imp_le_mono)\n\n\ntext \\<open>PROPERTY A 6\\<close>\n\nlemma ack2_le_ack1 [iff]: \"ack i (Suc j) \\<le> ack (Suc i) j\"\nproof (induct j)\n  case 0 show ?case by simp\nnext\n  case (Suc j) show ?case\n    by (metis Suc ack.simps(3) ack_le_mono2 le_trans less_ack2 less_eq_Suc_le)\nqed\n\n\ntext \\<open>PROPERTY A 4'? Extra lemma needed for \\<^term>\\<open>CONSTANT\\<close> case, constant functions\\<close>\n\nlemma ack_less_ack_Suc1 [iff]: \"ack i j < ack (Suc i) j\"\n  by (blast intro: ack_less_mono2 less_le_trans)\n\nlemma less_ack1 [iff]: \"i < ack i j\"\n  by (induct i) (auto intro: less_trans_Suc)\n\n\ntext \\<open>PROPERTY A 8\\<close>\n\nlemma ack_1 [simp]: \"ack (Suc 0) j = j + 2\"\n  by (induct j) simp_all\n\n\ntext \\<open>PROPERTY A 9.  The unary \\<open>1\\<close> and \\<open>2\\<close> in \\<^term>\\<open>ack\\<close> is essential for the rewriting.\\<close>\n\nlemma ack_2 [simp]: \"ack (Suc (Suc 0)) j = 2 * j + 3\"\n  by (induct j) simp_all\n\ntext \\<open>Added in 2022 just for fun\\<close>\nlemma ack_3: \"ack (Suc (Suc (Suc 0))) j = 2 ^ (j+3) - 3\"\nproof (induct j)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc j)\n  with less_le_trans show ?case\n    by (fastforce simp add: power_add algebra_simps)\nqed\n\ntext \\<open>PROPERTY A 7, monotonicity for \\<open><\\<close> [not clear why\n  @{thm [source] ack_1} is now needed first!]\\<close>\n\nlemma ack_less_mono1_aux: \"ack i k < ack (Suc (i+j)) k\"\nproof (induct i k rule: ack.induct)\n  case (1 n) show ?case\n    using less_le_trans by auto\nnext\n  case (2 m) thus ?case by simp\nnext\n  case (3 m n) thus ?case\n    using ack_less_mono2 less_trans by fastforce\nqed\n\nlemma ack_less_mono1: \"i < j \\<Longrightarrow> ack i k < ack j k\"\n  using ack_less_mono1_aux less_iff_Suc_add by auto\n\n\ntext \\<open>PROPERTY A 7', monotonicity for \\<open>\\<le>\\<close>\\<close>\n\nlemma ack_le_mono1: \"i \\<le> j \\<Longrightarrow> ack i k \\<le> ack j k\"\n  using ack_less_mono1 le_eq_less_or_eq by auto\n\n\ntext \\<open>PROPERTY A 10\\<close>\n\nlemma ack_nest_bound: \"ack i1 (ack i2 j) < ack (2 + (i1 + i2)) j\"\nproof -\n  have \"ack i1 (ack i2 j) < ack (i1 + i2) (ack (Suc (i1 + i2)) j)\"\n    by (meson ack_le_mono1 ack_less_mono1 ack_less_mono2 le_add1 le_trans less_add_Suc2 not_less)\n  also have \"\\<dots> = ack (Suc (i1 + i2)) (Suc j)\"\n    by simp\n  also have \"\\<dots> \\<le> ack (2 + (i1 + i2)) j\"\n    using ack2_le_ack1 add_2_eq_Suc by presburger\n  finally show ?thesis .\nqed\n\n\n\ntext \\<open>PROPERTY A 11\\<close>\n\nlemma ack_add_bound: \"ack i1 j + ack i2 j < ack (4 + (i1 + i2)) j\"\nproof -\n  have \"ack i1 j \\<le> ack (i1 + i2) j\" \"ack i2 j \\<le> ack (i1 + i2) j\"\n    by (simp_all add: ack_le_mono1)\n  then have \"ack i1 j + ack i2 j < ack (Suc (Suc 0)) (ack (i1 + i2) j)\"\n    by simp\n  also have \"\\<dots> < ack (4 + (i1 + i2)) j\"\n    by (metis ack_nest_bound add.assoc numeral_2_eq_2 numeral_Bit0)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>PROPERTY A 12.  Article uses existential quantifier but the ALF proof\n  used \\<open>k + 4\\<close>.  Quantified version must be nested \\<open>\\<exists>k'. \\<forall>i j. \\<dots>\\<close>\\<close>\n\nlemma ack_add_bound2:\n  assumes \"i < ack k j\" shows \"i + j < ack (4 + k) j\"\nproof -\n  have \"i + j < ack k j + ack 0 j\"\n    using assms by auto\n  also have \"\\<dots> < ack (4 + k) j\"\n    by (metis ack_add_bound add.right_neutral)\n  finally show ?thesis .\nqed\n\n\nsubsection\\<open>Primitive Recursive Functions\\<close>\n\nprimrec hd0 :: \"nat list \\<Rightarrow> nat\" where\n  \"hd0 [] = 0\"\n| \"hd0 (m # ms) = m\"\n\n\ntext \\<open>Inductive definition of the set of primitive recursive functions of type \\<^typ>\\<open>nat list \\<Rightarrow> nat\\<close>.\\<close>\n\ndefinition SC :: \"nat list \\<Rightarrow> nat\"\n  where \"SC l = Suc (hd0 l)\"\n\ndefinition CONSTANT :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where \"CONSTANT n l = n\"\n\ndefinition PROJ :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where \"PROJ i l = hd0 (drop i l)\"\n\ndefinition COMP :: \"[nat list \\<Rightarrow> nat, (nat list \\<Rightarrow> nat) list, nat list] \\<Rightarrow> nat\"\n  where \"COMP g fs l = g (map (\\<lambda>f. f l) fs)\"\n\nfun PREC :: \"[nat list \\<Rightarrow> nat, nat list \\<Rightarrow> nat, nat list] \\<Rightarrow> nat\"\n  where\n    \"PREC f g [] = 0\"\n  | \"PREC f g (x # l) = rec_nat (f l) (\\<lambda>y r. g (r # y # l)) x\"\n    \\<comment> \\<open>Note that \\<^term>\\<open>g\\<close> is applied first to \\<^term>\\<open>PREC f g y\\<close> and then to \\<^term>\\<open>y\\<close>!\\<close>\n\ninductive PRIMREC :: \"(nat list \\<Rightarrow> nat) \\<Rightarrow> bool\" where\n  SC: \"PRIMREC SC\"\n| CONSTANT: \"PRIMREC (CONSTANT k)\"\n| PROJ: \"PRIMREC (PROJ i)\"\n| COMP: \"PRIMREC g \\<Longrightarrow> listsp PRIMREC fs \\<Longrightarrow> PRIMREC (COMP g fs)\"\n| PREC: \"PRIMREC f \\<Longrightarrow> PRIMREC g \\<Longrightarrow> PRIMREC (PREC f g)\"\n  monos listsp_mono\n\n\nsubsection \\<open>Main Result: Ackermann's Function is not Primitive Recursive\\<close>\n\nlemma SC_case: \"SC l < ack 1 (sum_list l)\"\n  unfolding SC_def\n  by (induct l) (simp_all add: le_add1 le_imp_less_Suc)\n\nlemma CONSTANT_case: \"CONSTANT n l < ack n (sum_list l)\"\n  by (simp add: CONSTANT_def)\n\nlemma PROJ_case: \"PROJ i l < ack 0 (sum_list l)\"\nproof -\n  have \"hd0 (drop i l) \\<le> sum_list l\"\n    by (induct l arbitrary: i) (auto simp: drop_Cons' trans_le_add2)\n  then show ?thesis\n    by (simp add: PROJ_def)\nqed\n\ntext \\<open>\\<^term>\\<open>COMP\\<close> case\\<close>\n\nlemma COMP_map_aux: \"\\<forall>f \\<in> set fs. \\<exists>kf. \\<forall>l. f l < ack kf (sum_list l)\n        \\<Longrightarrow> \\<exists>k. \\<forall>l. sum_list (map (\\<lambda>f. f l) fs) < ack k (sum_list l)\"\nproof (induct fs)\n  case Nil\n  then show ?case\n    by auto\nnext\n  case (Cons a fs)\n  then show ?case\n    by simp (blast intro: add_less_mono ack_add_bound less_trans)\nqed\n\nlemma COMP_case:\n  assumes 1: \"\\<forall>l. g l < ack kg (sum_list l)\"\n      and 2: \"\\<forall>f \\<in> set fs. \\<exists>kf. \\<forall>l. f l < ack kf (sum_list l)\"\n  shows \"\\<exists>k. \\<forall>l. COMP g fs  l < ack k (sum_list l)\"\n  unfolding COMP_def\n  using 1 COMP_map_aux [OF 2] by (meson ack_less_mono2 ack_nest_bound less_trans)\n\ntext \\<open>\\<^term>\\<open>PREC\\<close> case\\<close>\n\nlemma PREC_case_aux:\n  assumes f: \"\\<And>l. f l + sum_list l < ack kf (sum_list l)\"\n    and g: \"\\<And>l. g l + sum_list l < ack kg (sum_list l)\"\n  shows \"PREC f g (m#l) + sum_list (m#l) < ack (Suc (kf + kg)) (sum_list (m#l))\"\nproof (induct m)\n  case 0\n  then show ?case\n    using ack_less_mono1_aux f less_trans by fastforce\nnext\n  case (Suc m)\n  let ?r = \"PREC f g (m#l)\"\n  have \"\\<not> g (?r # m # l) + sum_list (?r # m # l) < g (?r # m # l) + (m + sum_list l)\"\n    by force\n  then have \"g (?r # m # l) + (m + sum_list l) < ack kg (sum_list (?r # m # l))\"\n    by (meson g leI less_le_trans)\n  moreover\n    have \"\\<dots> < ack (kf + kg) (ack (Suc (kf + kg)) (m + sum_list l))\"\n    using Suc.hyps by simp (meson ack_le_mono1 ack_less_mono2 le_add2 le_less_trans)\n  ultimately show ?case\n    by auto\nqed\n\nlemma PREC_case_aux':\n  assumes f: \"\\<And>l. f l + sum_list l < ack kf (sum_list l)\"\n    and g: \"\\<And>l. g l + sum_list l < ack kg (sum_list l)\"\n  shows \"PREC f g l + sum_list l < ack (Suc (kf + kg)) (sum_list l)\"\n  by (smt (verit, best) PREC.elims PREC_case_aux add.commute add.right_neutral f g less_ack2)\n\nproposition PREC_case:\n  \"\\<lbrakk>\\<And>l. f l < ack kf (sum_list l); \\<And>l. g l < ack kg (sum_list l)\\<rbrakk>\n  \\<Longrightarrow> \\<exists>k. \\<forall>l. PREC f g l < ack k (sum_list l)\"\n  by (metis le_less_trans [OF le_add1 PREC_case_aux'] ack_add_bound2)\n\nlemma ack_bounds_PRIMREC: \"PRIMREC f \\<Longrightarrow> \\<exists>k. \\<forall>l. f l < ack k (sum_list l)\"\n  by (erule PRIMREC.induct) (blast intro: SC_case CONSTANT_case PROJ_case COMP_case PREC_case)+\n\ntheorem ack_not_PRIMREC:\n  \"\\<not> PRIMREC (\\<lambda>l. ack (hd0 l) (hd0 l))\"\nproof\n  assume *: \"PRIMREC (\\<lambda>l. ack (hd0 l) (hd0 l))\"\n  then obtain m where m: \"\\<And>l. ack (hd0 l) (hd0 l) < ack m (sum_list l)\"\n    using ack_bounds_PRIMREC by blast\n  show False\n    using m [of \"[m]\"] by simp\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Ackermanns_not_PR/Primrec.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772384450967, "lm_q2_score": 0.8757869932689566, "lm_q1q2_score": 0.765505476542664}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_nat_MSortBU2Sorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(Nat list) list => (Nat list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(Nat list) list => Nat list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun ordered :: \"Nat list => bool\" where\n  \"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun risers :: \"Nat list => (Nat list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if le y y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun msortbu2 :: \"Nat list => Nat list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\ntheorem property0 :\n  \"ordered (msortbu2 xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_nat_MSortBU2Sorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.8499711699569787, "lm_q1q2_score": 0.7654243490805616}}
{"text": "theory Submission\n  imports Defs\nbegin\n\ntext \\<open>\n  Annoying auxiliary lemma: a maximum over a dependent sum is the same as a\n  maximum over the maximum.\n\\<close>\nlemma Max_Sigma:\n  fixes g :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c :: linorder\"\n  assumes \"finite A\" \"A \\<noteq> {}\" \"\\<And>x. x \\<in> A \\<Longrightarrow> finite (B x)\" \"\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<noteq> {}\"\n  shows   \"Max ((\\<lambda>(x,y). g x y) ` Sigma A B) = (MAX x\\<in>A. MAX y\\<in>B x. g x y)\"\nproof (intro antisym)\n  show \"Max ((\\<lambda>(x,y). g x y) ` Sigma A B) \\<le> (MAX x\\<in>A. MAX y\\<in>B x. g x y)\"\n    using assms by (intro Max.boundedI) (auto simp: Max_ge_iff)\nnext\n  show \"Max ((\\<lambda>(x,y). g x y) ` Sigma A B) \\<ge> (MAX x\\<in>A. MAX y\\<in>B x. g x y)\"\n  proof (intro Max.boundedI; (safe)?)\n    fix a assume a: \"a \\<in> A\"\n    thus \"Max (g a ` B a) \\<le> (MAX (x, y)\\<in>Sigma A B. g x y)\"\n    proof (intro Max.boundedI; (safe)?)\n      fix b assume b: \"b \\<in> B a\"\n      show \"g a b \\<le> (MAX (x, y)\\<in>Sigma A B. g x y)\"\n        using a b assms by (subst Max_ge_iff) auto\n    qed (use assms in auto)\n  qed (use assms in auto)\nqed\n\ncontext \n  fixes a :: \"nat \\<Rightarrow> int\" \\<comment> \\<open>The input array\\<close>\n  fixes n :: nat \\<comment> \\<open>The length of @{term a}\\<close>\n  assumes n_gt_0: \"n > 0\"\nbegin\n\ndefinition max_sum_subseq where\n  \"max_sum_subseq = Max {\\<Sum>k=i..j. a k | i j. i \\<le> j \\<and> j < n}\"\n\nfunction f where\n  \"f i s m = (\n    if i \\<ge> n then m\n    else\n    let s' = (if s > 0 then s + a i else a i) in\n    f (i + 1) s' (max s' m)\n  )\n  \"\n  by auto\ntermination\n  by (relation \"measure (\\<lambda>(i, _, _). n - i)\"; simp)\n\nlemmas [simp del] = f.simps\n\n\ndefinition t where \"t i j = (\\<Sum>k=i..j. a k)\"\ndefinition s where \"s j = Max ((\\<lambda>i. t i j) ` {..j})\"\n\nlemma s_0 [simp]: \"s 0 = a 0\"\n  by (simp add: s_def t_def)\n\nlemma t_Suc_right: \"i \\<le> Suc j \\<Longrightarrow> t i (Suc j) = t i j + a (Suc j)\"\n  by (simp add: t_def)\n\nlemma t_gt [simp]: \"i > j \\<Longrightarrow> t i j = 0\"\n  by (simp add: t_def)\n\nlemma s_Suc: \"s (Suc j) = max 0 (s j) + a (Suc j)\"\nproof -\n  have \"s (Suc j) = (MAX i\\<in>{..Suc j}. t i (Suc j))\"\n    by (simp add: s_def)\n  also have \"\\<dots> = (MAX i\\<in>{..Suc j}. t i j + a (Suc j))\"\n    by (simp add: t_Suc_right)\n  also have \"\\<dots> = (MAX i\\<in>{..Suc j}. t i j) + a (Suc j)\"\n    by (metis Max_add_commute atMost_Suc_eq_insert_0 empty_not_insert finite_atMost)\n  also have \"{..Suc j} = insert (Suc j) {..j}\"\n    by auto\n  also have \"(MAX i\\<in>\\<dots>. t i j) = max 0 (s j)\"\n    by (simp add: s_def)\n  finally show ?thesis .\nqed\n\nlemma f_correct:\n  assumes \"M = Max (s ` {..<i})\"\n  assumes \"S = s (i - 1)\"\n  assumes \"i > 0\" \"i \\<le> n\"\n  shows   \"f i S M = Max (s ` {..<n})\"\n  using assms\nproof (induction i S M rule: f.induct)\n  case (1 i S M)\n  show ?case\n  proof (cases \"i \\<ge> n\")\n    case True\n    thus ?thesis using \"1.prems\"\n      by (subst f.simps) auto\n  next\n    case False\n    define S' where \"S' = max 0 S + a i\"\n    obtain i' where i': \"i = Suc i'\"\n      by (metis \"1.prems\"(3) Suc_pred)\n    have S': \"S' = s i\"\n      using \"1.prems\" False by (auto simp: S'_def s_Suc i')\n\n    have \"f i S M = f (i + 1) S' (max S' M)\"\n      using False by (subst f.simps) (auto simp: S'_def Let_def max_def)\n    also have \"\\<dots> = Max (local.s ` {..<n})\"\n    proof (rule \"1.IH\")\n      have \"{..<i + 1} = insert i {..<i}\"\n        using \\<open>i > 0\\<close> by auto\n      hence \"Max (s ` {..<i + 1}) = Max (insert (s i) (s ` {..<i}))\"\n        by simp\n      also have \"\\<dots> = max (s i) (Max (s ` {..<i}))\"\n        using \\<open>i > 0\\<close> by (subst Max.insert) auto\n      also have \"Max (s ` {..<i}) = M\"\n        using \"1.prems\" by simp\n      finally show \"max S' M = Max (s ` {..<i + 1})\"\n        by (simp add: S')\n    qed (use \"1.prems\" False S' in \\<open>auto simp: S'_def\\<close>)\n    finally show ?thesis .\n  qed\nqed\n\ntheorem max_sum_subseq_compute':\n  \"max_sum_subseq = f 1 (a 0) (a 0)\"\nproof -\n  have \"{sum a {i..j} |i j. i \\<le> j \\<and> j < n} = {t i j |i j. i \\<le> j \\<and> j < n}\"\n    by (auto simp: t_def)\n  also have \"\\<dots> = (\\<lambda>(j,i). t i j) ` (SIGMA j:{..<n}. {..j})\"\n    by (force simp: Sigma_def case_prod_unfold image_iff)\n  also have \"Max \\<dots> = (MAX j\\<in>{..<n}. MAX i\\<in>{..j}. t i j)\"\n    using \\<open>n > 0\\<close> by (intro Max_Sigma) auto\n  finally show ?thesis\n    unfolding max_sum_subseq_def using n_gt_0\n    by (subst f_correct) (auto simp: lessThan_Suc s_def t_def)\nqed\n\nlemma f_eq:\n  \"Defs.f a n i x y = Submission.f a n i x y\" if \"n > 0\"\n  by (induction i x y rule: f.induct) (simp add: f.simps that)\n\nend\n\ntheorem max_sum_subseq_compute:\n  \"n > 0 \\<Longrightarrow> Defs.max_sum_subseq a n = Defs.f a n 1 (a 0) (a 0)\"\n  using max_sum_subseq_compute' by (simp only: Defs.max_sum_subseq_def max_sum_subseq_def f_eq)\n\nend", "meta": {"author": "wimmers", "repo": "proofground2021-solutions", "sha": "212b4983c257cda2b3df15f40060ab4c455d504c", "save_path": "github-repos/isabelle/wimmers-proofground2021-solutions", "path": "github-repos/isabelle/wimmers-proofground2021-solutions/proofground2021-solutions-212b4983c257cda2b3df15f40060ab4c455d504c/maximum-sum-subsequence/isabelle/eberlm/Submission.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.765392172034477}}
{"text": "theory chap_2\n  imports Main\nbegin\n(* 2.1 *)\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(* 2.2 *)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"add 0 n = n\" |\n  \"add (Suc m) n = Suc(add m n)\"\nlemma add_02: \"add m 0 = m\"\n  apply(induction m)\n  apply(auto)\n  done\nthm add_02\n\nlemma add_associative: \"add(add n m) z = add n (add m z)\"\n  apply(induction n)\n  apply(auto)\n  done\nthm add_associative      \n\nlemma add_0[simp]: \"add m 0 = m\"\n  by (induct m) simp_all\n  \nlemma add_gen[simp]: \"add m (Suc n) = Suc (add m n)\"\n  by (induct m) simp_all\n  \nlemma add_commutative: \"add k m = add m k\"\n  apply(induction k)\n  apply(auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n  \"double m = add m m\"\n\nlemma \"double m = add m m\"\n  apply(induction m)\n  apply(auto)\n  done\n  \n(* 2.3 *)\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count [] x = 0\" |\n  \"count (x # xs) y = (if x = y then Suc (count xs y) else (count xs y))\"\n\nlemma count: \"count xs x \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n  \n(* 2.4 *)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] x = [x]\" |\n\"snoc (y # ys) x = y # (snoc ys x)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\" |\n  \"reverse (y # ys) = snoc (reverse ys) y\"\n  \nlemma reverse_snoc[simp]: \"reverse (snoc xs y) = y # reverse xs\"\n  apply(induction xs)\n   apply auto\n  done\n  \n    \nlemma reverse_proof: \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n  apply(auto)  \ndone\n    \nfind_theorems \"rev (rev _) = _\"\n\nthm rev_rev_ident\n\n(* 2.5 *)\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n  \"sum_upto 0 = 0\" |\n  \"sum_upto (Suc n)  = Suc n + sum_upto n\"\n\nvalue \"sum_upto 4 = 10\"\n  \nlemma discrete_add: \"sum_upto n = (n * (n + 1)) div 2\"\n  apply(induction n)\n  apply(auto)\n  done   \n\n(* 2.6 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n  \nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"contents Tip = []\" |\n  \"contents (Node l v r) = v # ((contents l) @ (contents r))\"\n  \nfun treesum :: \"nat tree \\<Rightarrow> nat \" where\n  \"treesum Tip = 0\" |\n  \"treesum (Node l v r) = v + (treesum l) + (treesum r)\"\n  \n  \nlemma \"listsum(contents t) = treesum t\"\n  apply(induction t)\n  apply(auto)\n  done\nsorry\n\n(* 2.7 *)\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2\" 'a \"'a tree2\"\n  \nfun mirror :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n  \"mirror (Tip v) = Tip v\" |\n  \"mirror (Node l v r) = Node (mirror r) v (mirror l)\"\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"pre_order (Tip v) = [v]\" |\n  \"pre_order (Node l v r) = v # ((pre_order l) @ (pre_order r))\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"post_order (Tip v) = [v]\" |\n  \"post_order (Node l v r) = (post_order l) @ (post_order r) @ [v]\"\n  \nlemma \"pre_order (mirror t) = rev(post_order t)\"\n  apply(induction t)\n  apply auto\n  done \n\n(* 2.8 *)\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intersperse c [] = []\" |\n  \"intersperse c [v] = [v]\" |\n  \"intersperse c (v#t) = v # c # (intersperse c t)\"\n  \n(*value \"intersperse(2,[]) = []\"*)\n\n(*value \"intersperse(2,[4]) = [4]\"*)\n\nvalue \"intersperse(2, [4,1,5,8])\"\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction xs rule:intersperse.induct)\n    apply(auto)\n  done  \n    \n    \n(* 2.9 *)\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"itadd 0 n = n\" |\n  \"itadd (Suc m) n = itadd m (Suc n)\"\n  \nlemma \"itadd m n = add m n\"\n  apply(induction m arbitrary:n)\n  apply auto\ndone\n  \n(* 2.10 *)\ndatatype tree0 = Tip | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n\"nodes Tip = 1\" |\n\"nodes (Node l r) = 1 + nodes l + nodes r\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\ntheorem explode_exponential: \"nodes (explode n t) = 2^n * nodes t + 2^n - 1\"\napply (induction n arbitrary:t)\napply (auto simp add:algebra_simps)\ndone\n  \n(* 2.11 *)\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\" |\n\"eval (Const k) x = k\" |\n\"eval (Add p q) x = eval p x + eval q x\" |\n\"eval (Mult p q) x = eval p x * eval q x\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] y = 0\" |\n\"evalp (x # xs) y = x + y * evalp xs y\"\n\nfun vsum :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"vsum [] xs = xs\" |\n\"vsum xs [] = xs\" |\n\"vsum (x # xs) (y # ys) = (x + y) # vsum xs ys\"\n\nfun scalar_mult :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"scalar_mult k [] = []\" |\n\"scalar_mult k (x # xs) = k * x # scalar_mult k xs\"\n\nfun vmult :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n\"vmult [] xs = []\" |\n\"vmult (x # xs) ys = vsum (scalar_mult x ys) (0 # vmult xs ys)\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0, 1]\" |\n\"coeffs (Const k) = [k]\" |\n\"coeffs (Add p q) = vsum (coeffs p) (coeffs q)\" |\n\"coeffs (Mult p q) = vmult (coeffs p) (coeffs q)\"\n\nlemma evalp_additive[simp]: \"evalp (vsum xs ys) a = evalp xs a + evalp ys a\"\napply (induction rule:vsum.induct)\napply (auto simp add:Int.int_distrib)\ndone\n\nlemma eval_preserves_mult[simp]: \"evalp (scalar_mult x ys) a = x * evalp ys a\"\napply (induction ys)\napply (auto simp add:Int.int_distrib)\ndone \n\nlemma evalp_multiplicative[simp]: \"evalp (vmult xs ys) a = evalp xs a * evalp ys a\"\napply (induction xs)\napply (auto simp add:Int.int_distrib)\ndone \n\ntheorem evalp_eval: \"evalp (coeffs e) x = eval e x\"\napply (induction e)\napply (auto)\ndone\n  \nend", "meta": {"author": "nud3l", "repo": "concrete-semantics", "sha": "03d6c0a1be7f0d2e145204fe9b122a791fd19051", "save_path": "github-repos/isabelle/nud3l-concrete-semantics", "path": "github-repos/isabelle/nud3l-concrete-semantics/concrete-semantics-03d6c0a1be7f0d2e145204fe9b122a791fd19051/excercise/chap_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7653827764954733}}
{"text": "(* Property from Productive Use of Failure in Inductive Proof, \n   Andrew Ireland and Alan Bundy, JAR 1996. \n   This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n   Some proofs were added by Yutaka Nagashima.*)\ntheory TIP_prop_05\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"'a list => 'a list => 'a list\" where\n  \"x (nil2) z = z\"\n| \"x (cons2 z2 xs) z = cons2 z2 (x xs z)\"\n\nfun rev :: \"'a list => 'a list\" where\n  \"rev (nil2) = nil2\"\n| \"rev (cons2 z xs) = x (rev xs) (cons2 z (nil2))\"\n\nfun length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 z xs) = S (length xs)\"\n\ntheorem property0 :\n  \"((length (rev y)) = (length y))\"\n  apply(induct rule:length.induct)(*rev.induct works as well. They are the same and return the same result.*)\n   apply auto[1](*\\<And>z does not appear in the goal. \\<rightarrow> clarsimp*)\n  apply clarsimp\n  apply(subgoal_tac \"\\<And>za lenxs revxs. \n             TIP_prop_05.length revxs = lenxs \\<Longrightarrow>\n             TIP_prop_05.length (x revxs (cons2 za nil2)) = S lenxs\")(*common sub-terms: revxs and lenxs*)\n   apply fastforce\n  apply(thin_tac \"TIP_prop_05.length (TIP_prop_05.rev xs) = TIP_prop_05.length xs\")\n  apply(subgoal_tac \"TIP_prop_05.length revxs = lenxs \\<longrightarrow> TIP_prop_05.length (x revxs (cons2 za nil2)) = S lenxs\")\n   apply fastforce\n  apply(thin_tac \"TIP_prop_05.length revxs = lenxs\")\n  apply(rule meta_allI)(*because we cannot use the arbitrary keyword with induct_tac*)\n  back nitpick quickcheck\n  back nitpick quickcheck\n  back\n  apply (induct_tac revxs) (*equivalent to (induct revxs arbitrary: lenxs) due to meta_allI*)\n   apply auto[1]\n  apply auto[1]\n  done\n\ntheorem alternative_proof: \"((length (rev y)) = (length y))\"\n  apply(induct y)\n   apply fastforce\n  apply clarsimp\n    (*common sub-term*)\n  apply(subgoal_tac \"\\<And>x1 y rev_y length_y. length rev_y = length_y \\<Longrightarrow> length (x rev_y (cons2 x1 nil2)) = S length_y\")\n   apply fastforce\n  apply(thin_tac \"TIP_prop_05.length (TIP_prop_05.rev y) = TIP_prop_05.length y\")\n  apply(subgoal_tac \"TIP_prop_05.length rev_y = length_y \\<longrightarrow> TIP_prop_05.length (x rev_y (cons2 x1a nil2)) = S length_y\")\n   apply fastforce\n  apply(thin_tac \"TIP_prop_05.length rev_y = length_y\")\n  apply(rule meta_allI)\n  back quickcheck (*Nitpick cannot handle goals with schematic type variables*)\n  back quickcheck (*Nitpick cannot handle goals with schematic type variables*)\n  back quickcheck (*Nitpick cannot handle goals with schematic type variables*)\n  apply (induct_tac rev_y)\n   apply auto\n  done\n\nlemma aux_0:\n  shows \"length rev_y = length_y \\<Longrightarrow> length (x rev_y (cons2 x1 nil2)) = S length_y\"\n  apply(induct rev_y arbitrary: length_y)\n  by auto\n\ntheorem property:\n  \"((length (rev y)) = (length y))\"\n  apply(induct y)\n   apply fastforce\n  apply clarsimp\n  using aux_0 apply fastforce (*common sub-term generalisation of (length y) and (rev y)*)\n  done\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/Prod/Prod/TIP_prop_05.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.8791467564270271, "lm_q1q2_score": 0.7653827764822403}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Binary Tries and Patricia Tries\"\n\ntheory Tries_Binary\nimports Set_Specs\nbegin\n\nhide_const (open) insert\n\ndeclare Let_def[simp]\n\nfun sel2 :: \"bool \\<Rightarrow> 'a * 'a \\<Rightarrow> 'a\" where\n\"sel2 b (a1,a2) = (if b then a2 else a1)\"\n\nfun mod2 :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> bool \\<Rightarrow> 'a * 'a \\<Rightarrow> 'a * 'a\" where\n\"mod2 f b (a1,a2) = (if b then (a1,f a2) else (f a1,a2))\"\n\n\nsubsection \"Trie\"\n\ndatatype trie = Lf | Nd bool \"trie * trie\"\n\ndefinition empty :: trie where\n[simp]: \"empty = Lf\"\n\nfun isin :: \"trie \\<Rightarrow> bool list \\<Rightarrow> bool\" where\n\"isin Lf ks = False\" |\n\"isin (Nd b lr) ks =\n   (case ks of\n      [] \\<Rightarrow> b |\n      k#ks \\<Rightarrow> isin (sel2 k lr) ks)\"\n\nfun insert :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"insert [] Lf = Nd True (Lf,Lf)\" |\n\"insert [] (Nd b lr) = Nd True lr\" |\n\"insert (k#ks) Lf = Nd False (mod2 (insert ks) k (Lf,Lf))\" |\n\"insert (k#ks) (Nd b lr) = Nd b (mod2 (insert ks) k lr)\"\n\nlemma isin_insert: \"isin (insert xs t) ys = (xs = ys \\<or> isin t ys)\"\napply(induction xs t arbitrary: ys rule: insert.induct)\napply (auto split: list.splits if_splits)\ndone\n\ntext \\<open>A simple implementation of delete; does not shrink the trie!\\<close>\n\nfun delete0 :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"delete0 ks Lf = Lf\" |\n\"delete0 ks (Nd b lr) =\n   (case ks of\n      [] \\<Rightarrow> Nd False lr |\n      k#ks' \\<Rightarrow> Nd b (mod2 (delete0 ks') k lr))\"\n\nlemma isin_delete0: \"isin (delete0 as t) bs = (as \\<noteq> bs \\<and> isin t bs)\"\napply(induction as t arbitrary: bs rule: delete0.induct)\napply (auto split: list.splits if_splits)\ndone\n\ntext \\<open>Now deletion with shrinking:\\<close>\n\nfun node :: \"bool \\<Rightarrow> trie * trie \\<Rightarrow> trie\" where\n\"node b lr = (if \\<not> b \\<and> lr = (Lf,Lf) then Lf else Nd b lr)\"\n\nfun delete :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"delete ks Lf = Lf\" |\n\"delete ks (Nd b lr) =\n   (case ks of\n      [] \\<Rightarrow> node False lr |\n      k#ks' \\<Rightarrow> node b (mod2 (delete ks') k lr))\"\n\nlemma isin_delete: \"isin (delete xs t) ys = (xs \\<noteq> ys \\<and> isin t ys)\"\napply(induction xs t arbitrary: ys rule: delete.induct)\n apply simp\napply (auto split: list.splits if_splits)\n  apply (metis isin.simps(1))\n apply (metis isin.simps(1))\n  done\n\ndefinition set_trie :: \"trie \\<Rightarrow> bool list set\" where\n\"set_trie t = {xs. isin t xs}\"\n\nlemma set_trie_empty: \"set_trie empty = {}\"\nby(simp add: set_trie_def)\n\nlemma set_trie_isin: \"isin t xs = (xs \\<in> set_trie t)\"\nby(simp add: set_trie_def)\n\nlemma set_trie_insert: \"set_trie(insert xs t) = set_trie t \\<union> {xs}\"\nby(auto simp add: isin_insert set_trie_def)\n\nlemma set_trie_delete: \"set_trie(delete xs t) = set_trie t - {xs}\"\nby(auto simp add: isin_delete set_trie_def)\n\ninterpretation S: Set\nwhere empty = empty and isin = isin and insert = insert and delete = delete\nand set = set_trie and invar = \"\\<lambda>t. True\"\nproof (standard, goal_cases)\n  case 1 show ?case by (rule set_trie_empty)\nnext\n  case 2 show ?case by(rule set_trie_isin)\nnext\n  case 3 thus ?case by(auto simp: set_trie_insert)\nnext\n  case 4 show ?case by(rule set_trie_delete)\nqed (rule TrueI)+\n\n\nsubsection \"Patricia Trie\"\n\ndatatype trieP = LfP | NdP \"bool list\" bool \"trieP * trieP\"\n\nfun isinP :: \"trieP \\<Rightarrow> bool list \\<Rightarrow> bool\" where\n\"isinP LfP ks = False\" |\n\"isinP (NdP ps b lr) ks =\n  (let n = length ps in\n   if ps = take n ks\n   then case drop n ks of [] \\<Rightarrow> b | k#ks' \\<Rightarrow> isinP (sel2 k lr) ks'\n   else False)\"\n\ndefinition emptyP :: trieP where\n[simp]: \"emptyP = LfP\"\n\nfun split where\n\"split [] ys = ([],[],ys)\" |\n\"split xs [] = ([],xs,[])\" |\n\"split (x#xs) (y#ys) =\n  (if x\\<noteq>y then ([],x#xs,y#ys)\n   else let (ps,xs',ys') = split xs ys in (x#ps,xs',ys'))\"\n\n\nlemma mod2_cong[fundef_cong]:\n  \"\\<lbrakk> lr = lr'; k = k'; \\<And>a b. lr'=(a,b) \\<Longrightarrow> f (a) = f' (a) ; \\<And>a b. lr'=(a,b) \\<Longrightarrow> f (b) = f' (b) \\<rbrakk>\n  \\<Longrightarrow> mod2 f k lr= mod2 f' k' lr'\"\nby(cases lr, cases lr', auto)\n\n\nfun insertP :: \"bool list \\<Rightarrow> trieP \\<Rightarrow> trieP\" where\n\"insertP ks LfP  = NdP ks True (LfP,LfP)\" |\n\"insertP ks (NdP ps b lr) =\n  (case split ks ps of\n     (qs,k#ks',p#ps') \\<Rightarrow>\n       let tp = NdP ps' b lr; tk = NdP ks' True (LfP,LfP) in\n       NdP qs False (if k then (tp,tk) else (tk,tp)) |\n     (qs,k#ks',[]) \\<Rightarrow>\n       NdP ps b (mod2 (insertP ks') k lr) |\n     (qs,[],p#ps') \\<Rightarrow>\n       let t = NdP ps' b lr in\n       NdP qs True (if p then (LfP,t) else (t,LfP)) |\n     (qs,[],[]) \\<Rightarrow> NdP ps True lr)\"\n\n\nfun nodeP :: \"bool list \\<Rightarrow> bool \\<Rightarrow> trieP * trieP \\<Rightarrow> trieP\" where\n\"nodeP ps b lr = (if \\<not> b \\<and> lr = (LfP,LfP) then LfP else NdP ps b lr)\"\n\nfun deleteP :: \"bool list \\<Rightarrow> trieP \\<Rightarrow> trieP\" where\n\"deleteP ks LfP  = LfP\" |\n\"deleteP ks (NdP ps b lr) =\n  (case split ks ps of\n     (qs,ks',p#ps') \\<Rightarrow> NdP ps b lr |\n     (qs,k#ks',[]) \\<Rightarrow> nodeP ps b (mod2 (deleteP ks') k lr) |\n     (qs,[],[]) \\<Rightarrow> nodeP ps False lr)\"\n\n\nsubsubsection \\<open>Functional Correctness\\<close>\n\ntext \\<open>First step: @{typ trieP} implements @{typ trie} via the abstraction function \\<open>abs_trieP\\<close>:\\<close>\n\nfun prefix_trie :: \"bool list \\<Rightarrow> trie \\<Rightarrow> trie\" where\n\"prefix_trie [] t = t\" |\n\"prefix_trie (k#ks) t =\n  (let t' = prefix_trie ks t in Nd False (if k then (Lf,t') else (t',Lf)))\"\n\nfun abs_trieP :: \"trieP \\<Rightarrow> trie\" where\n\"abs_trieP LfP = Lf\" |\n\"abs_trieP (NdP ps b (l,r)) = prefix_trie ps (Nd b (abs_trieP l, abs_trieP r))\"\n\n\ntext \\<open>Correctness of @{const isinP}:\\<close>\n\nlemma isin_prefix_trie:\n  \"isin (prefix_trie ps t) ks\n   = (ps = take (length ps) ks \\<and> isin t (drop (length ps) ks))\"\napply(induction ps arbitrary: ks)\napply(auto split: list.split)\ndone\n\nlemma abs_trieP_isinP:\n  \"isinP t ks = isin (abs_trieP t) ks\"\napply(induction t arbitrary: ks rule: abs_trieP.induct)\n apply(auto simp: isin_prefix_trie split: list.split)\ndone\n\n\ntext \\<open>Correctness of @{const insertP}:\\<close>\n\nlemma prefix_trie_Lfs: \"prefix_trie ks (Nd True (Lf,Lf)) = insert ks Lf\"\napply(induction ks)\napply auto\ndone\n\nlemma insert_prefix_trie_same:\n  \"insert ps (prefix_trie ps (Nd b lr)) = prefix_trie ps (Nd True lr)\"\napply(induction ps)\napply auto\ndone\n\nlemma insert_append: \"insert (ks @ ks') (prefix_trie ks t) = prefix_trie ks (insert ks' t)\"\napply(induction ks)\napply auto\ndone\n\nlemma prefix_trie_append: \"prefix_trie (ps @ qs) t = prefix_trie ps (prefix_trie qs t)\"\napply(induction ps)\napply auto\ndone\n\nlemma split_if: \"split ks ps = (qs, ks', ps') \\<Longrightarrow>\n  ks = qs @ ks' \\<and> ps = qs @ ps' \\<and> (ks' \\<noteq> [] \\<and> ps' \\<noteq> [] \\<longrightarrow> hd ks' \\<noteq> hd ps')\"\napply(induction ks ps arbitrary: qs ks' ps' rule: split.induct)\napply(auto split: prod.splits if_splits)\ndone\n\nlemma abs_trieP_insertP:\n  \"abs_trieP (insertP ks t) = insert ks (abs_trieP t)\"\napply(induction t arbitrary: ks)\napply(auto simp: prefix_trie_Lfs insert_prefix_trie_same insert_append prefix_trie_append\n           dest!: split_if split: list.split prod.split if_splits)\ndone\n\n\ntext \\<open>Correctness of @{const deleteP}:\\<close>\n\nlemma prefix_trie_Lf: \"prefix_trie xs t = Lf \\<longleftrightarrow> xs = [] \\<and> t = Lf\"\nby(cases xs)(auto)\n\nlemma abs_trieP_Lf: \"abs_trieP t = Lf \\<longleftrightarrow> t = LfP\"\nby(cases t) (auto simp: prefix_trie_Lf)\n\nlemma delete_prefix_trie:\n  \"delete xs (prefix_trie xs (Nd b (l,r)))\n   = (if (l,r) = (Lf,Lf) then Lf else prefix_trie xs (Nd False (l,r)))\"\nby(induction xs)(auto simp: prefix_trie_Lf)\n\nlemma delete_append_prefix_trie:\n  \"delete (xs @ ys) (prefix_trie xs t)\n   = (if delete ys t = Lf then Lf else prefix_trie xs (delete ys t))\"\nby(induction xs)(auto simp: prefix_trie_Lf)\n\nlemma delete_abs_trieP:\n  \"delete ks (abs_trieP t) = abs_trieP (deleteP ks t)\"\napply(induction t arbitrary: ks)\napply(auto simp: delete_prefix_trie delete_append_prefix_trie\n        prefix_trie_append prefix_trie_Lf abs_trieP_Lf\n        dest!: split_if split: if_splits list.split prod.split)\ndone\n\n\ntext \\<open>The overall correctness proof. Simply composes correctness lemmas.\\<close>\n\ndefinition set_trieP :: \"trieP \\<Rightarrow> bool list set\" where\n\"set_trieP = set_trie o abs_trieP\"\n\nlemma isinP_set_trieP: \"isinP t xs = (xs \\<in> set_trieP t)\"\nby(simp add: abs_trieP_isinP set_trie_isin set_trieP_def)\n\nlemma set_trieP_insertP: \"set_trieP (insertP xs t) = set_trieP t \\<union> {xs}\"\nby(simp add: abs_trieP_insertP set_trie_insert set_trieP_def)\n\nlemma set_trieP_deleteP: \"set_trieP (deleteP xs t) = set_trieP t - {xs}\"\nby(auto simp: set_trie_delete set_trieP_def simp flip: delete_abs_trieP)\n\ninterpretation SP: Set\nwhere empty = emptyP and isin = isinP and insert = insertP and delete = deleteP\nand set = set_trieP and invar = \"\\<lambda>t. True\"\nproof (standard, goal_cases)\n  case 1 show ?case by (simp add: set_trieP_def set_trie_def)\nnext\n  case 2 show ?case by(rule isinP_set_trieP)\nnext\n  case 3 thus ?case by (auto simp: set_trieP_insertP)\nnext\n  case 4 thus ?case by(auto simp: set_trieP_deleteP)\nqed (rule TrueI)+\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/Tries_Binary.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.8791467595934565, "lm_q1q2_score": 0.7653827585770245}}
{"text": "theory DemoITPFull\nimports \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\n(* Normal list datatype *)\ndatatype 'a Lst = \n   Nil\n  | Cons \"'a\" \"'a Lst\" (infix \";\" 65)\n\n(* The append function. Syntactic sugar: we use +++ instead of Haskell's ++ *)\nfun app :: \"'a Lst \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\" (infix \"+++\" 60)\nwhere \n  \"Nil +++ xs = xs\"\n| \"(x;xs) +++ ys = x;(xs +++ ys)\"\n\n(* The reverse function *)\nfun rev :: \"'a Lst \\<Rightarrow> 'a Lst\"\nwhere \n  \"rev Nil = Nil\"\n| \"rev (x;xs) = (rev xs) +++ (x;Nil)\"\n\n(* Datatype for binary trees from your exercises *)\ndatatype 'a Tree = \n  Empty  \n  | Node \"'a\" \"'a Tree\" \"'a Tree\"\n\n(* The swap function: swaps the left and right subtree. *)\nfun swap :: \"'a Tree => 'a Tree\"\nwhere\n  \"swap Empty = Empty\"\n| \"swap (Node data l r) = Node data (swap r) (swap l)\"\n\n(* The flatten function: turn a tree into a list *)\nfun flatten :: \"'a Tree \\<Rightarrow> 'a Lst\"\nwhere\n  \"flatten Empty = Nil\"\n| \"flatten (Node data l r) =  ((flatten l) +++ (data;Nil)) +++ (flatten r)\"\n\nhipster app rev\nlemma lemma_a [thy_expl]: \"y +++ Lst.Nil = y\"\n  apply (induct y)\n  apply simp\n  apply simp\n  done\n    \nlemma lemma_aa [thy_expl]: \"(y +++ z) +++ x2 = y +++ (z +++ x2)\"\n  apply (induct y arbitrary: x2 z)\n  apply simp\n  apply simp\n  done\n\nlemma lemma_ab [thy_expl]: \"DemoITPFull.rev z +++ DemoITPFull.rev y = DemoITPFull.rev (y +++ z)\"\n  apply (induct y arbitrary: z)\n  apply simp\n  apply (simp add: DemoITPFull.lemma_a)\n  apply simp\n  apply (metis lemma_aa)\n  done\n  \nlemma lemma_ac [thy_expl]: \"DemoITPFull.rev (DemoITPFull.rev y) = y\"\n  apply (induct y)\n  apply simp\n  apply simp\n  apply (metis DemoITPFull.lemma_ab DemoITPFull.rev.simps(1) DemoITPFull.rev.simps(2) Lst.distinct(1) app.elims app.simps(2))\n  done\n\nhipster swap flatten\nlemma lemma_ad [thy_expl]: \"swap (swap y) = y\"\n  apply (induct y)\n  apply simp\n  apply simp\n  done\n\n\n\n(* Last week's exercise 10 *)\ntheorem exercise10: \"flatten (swap p) = rev (flatten p)\"\n  apply (induct p)\n  apply simp\n  apply simp\n  apply (metis DemoITPFull.rev.simps(1) DemoITPFull.rev.simps(2) lemma_a lemma_aa lemma_ab)\n  done\n \n    \n(* Hard exercise (optional) *)\nfun qrev :: \"'a Lst \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\"\nwhere \n  \"qrev Nil acc  = acc\"\n| \"qrev (x;xs) acc = qrev xs (x;acc)\"\n\nhipster qrev rev\nlemma lemma_ae [thy_expl]: \"qrev (qrev z y) Lst.Nil = qrev y z\"\n  apply (induct z arbitrary: y)\n  apply simp\n  apply simp\n  done\n    \nlemma lemma_af [thy_expl]: \"DemoITPFull.rev y +++ z = qrev y z\"\n  apply (induct y arbitrary: z)\n  apply simp\n  apply simp\n  apply (metis DemoITPFull.rev.simps(2) app.simps(1) lemma_aa lemma_ab lemma_ac)\n  done\n\ntheorem hardExercise: \"rev xs = qrev xs Nil\"\nsledgehammer\n  by (metis lemma_a lemma_af)\n\n\n\n\n(* The spine function: turns a list into a tree. *)\n(* fun spine :: \"'a Lst \\<Rightarrow> 'a Tree\"\nwhere\n  \"spine Nil = Empty\"\n| \"spine (x;xs) = Node x Empty (spine xs)\"\n\nhipster spine flatten\nlemma lemma_af [thy_expl]: \"flatten (spine y) = y\"\n  apply (induct y)\n  by simp_all\n*)\n\n\nend", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/Examples/ITP2017/DemoITPFull.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7653536841933026}}
{"text": "section \\<open>Tensor products (finite dimensional)\\<close>\n\ntheory Finite_Tensor_Product\n  imports Complex_Bounded_Operators.Complex_L2 Misc\nbegin\n\ndeclare cblinfun.scaleC_right[simp]\n\nunbundle cblinfun_notation\nno_notation m_inv (\"inv\\<index> _\" [81] 80)\n\nlift_definition tensor_ell2 :: \\<open>'a::finite ell2 \\<Rightarrow> 'b::finite ell2 \\<Rightarrow> ('a\\<times>'b) ell2\\<close> (infixr \"\\<otimes>\\<^sub>s\" 70) is\n  \\<open>\\<lambda>\\<psi> \\<phi> (i,j). \\<psi> i * \\<phi> j\\<close>\n  by simp\n\nlemma tensor_ell2_add2: \\<open>tensor_ell2 a (b + c) = tensor_ell2 a b + tensor_ell2 a c\\<close>\n  apply transfer apply (rule ext) apply (auto simp: case_prod_beta)\n  by (meson algebra_simps)\n\nlemma tensor_ell2_add1: \\<open>tensor_ell2 (a + b) c = tensor_ell2 a c + tensor_ell2 b c\\<close>\n  apply transfer apply (rule ext) apply (auto simp: case_prod_beta)\n  by (simp add: vector_space_over_itself.scale_left_distrib)\n\nlemma tensor_ell2_scaleC2: \\<open>tensor_ell2 a (c *\\<^sub>C b) = c *\\<^sub>C tensor_ell2 a b\\<close>\n  apply transfer apply (rule ext) by (auto simp: case_prod_beta)\n\nlemma tensor_ell2_scaleC1: \\<open>tensor_ell2 (c *\\<^sub>C a) b = c *\\<^sub>C tensor_ell2 a b\\<close>\n  apply transfer apply (rule ext) by (auto simp: case_prod_beta)\n\nlemma tensor_ell2_inner_prod[simp]: \\<open>tensor_ell2 a b \\<bullet>\\<^sub>C tensor_ell2 c d = (a \\<bullet>\\<^sub>C c) * (b \\<bullet>\\<^sub>C d)\\<close>\n  apply transfer\n  by (auto simp: case_prod_beta sum_product sum.cartesian_product mult.assoc mult.left_commute)\n\nlemma clinear_tensor_ell21: \"clinear (\\<lambda>b. tensor_ell2 a b)\"\n  apply (rule clinearI; transfer)\n   apply (auto simp: case_prod_beta)\n  by (simp add: cond_case_prod_eta algebra_simps)\n\nlemma clinear_tensor_ell22: \"clinear (\\<lambda>a. tensor_ell2 a b)\"\n  apply (rule clinearI; transfer)\n   apply (auto simp: case_prod_beta)\n  by (simp add: case_prod_beta' algebra_simps)\n\nlemma tensor_ell2_ket[simp]: \"tensor_ell2 (ket i) (ket j) = ket (i,j)\"\n  apply transfer by auto\n\n\ndefinition tensor_op :: \\<open>('a ell2, 'b::finite ell2) cblinfun \\<Rightarrow> ('c ell2, 'd::finite ell2) cblinfun\n      \\<Rightarrow> (('a\\<times>'c) ell2, ('b\\<times>'d) ell2) cblinfun\\<close> (infixr \"\\<otimes>\\<^sub>o\" 70) where\n  \\<open>tensor_op M N = (SOME P. \\<forall>a c. P *\\<^sub>V (ket (a,c))\n      = tensor_ell2 (M *\\<^sub>V ket a) (N *\\<^sub>V ket c))\\<close>\n\nlemma tensor_op_ket: \n  fixes a :: \\<open>'a::finite\\<close> and b :: \\<open>'b\\<close> and c :: \\<open>'c::finite\\<close> and d :: \\<open>'d\\<close>\n  shows \\<open>tensor_op M N *\\<^sub>V (ket (a,c)) = tensor_ell2 (M *\\<^sub>V ket a) (N *\\<^sub>V ket c)\\<close>\nproof -\n  define S :: \\<open>('a\\<times>'c) ell2 set\\<close> where \"S = ket ` UNIV\"\n  define \\<phi> where \\<open>\\<phi> = (\\<lambda>(a,c). tensor_ell2 (M *\\<^sub>V ket a) (N *\\<^sub>V ket c))\\<close>\n  define \\<phi>' where \\<open>\\<phi>' = \\<phi> \\<circ> inv ket\\<close>\n\n  have def: \\<open>tensor_op M N = (SOME P. \\<forall>a c. P *\\<^sub>V (ket (a,c)) = \\<phi> (a,c))\\<close>\n    unfolding tensor_op_def \\<phi>_def by auto\n\n  have \\<open>cindependent S\\<close>\n    using S_def cindependent_ket by blast\n  moreover have \\<open>cspan S = UNIV\\<close>\n    using S_def cspan_range_ket_finite by blast\n  ultimately have \"cblinfun_extension_exists S \\<phi>'\"\n    by (rule cblinfun_extension_exists_finite_dim)\n  then have \"\\<exists>P. \\<forall>x\\<in>S. P *\\<^sub>V x = \\<phi>' x\"\n    unfolding cblinfun_extension_exists_def by auto\n  then have ex: \\<open>\\<exists>P. \\<forall>a c. P *\\<^sub>V ket (a,c) = \\<phi> (a,c)\\<close>\n    by (metis S_def \\<phi>'_def comp_eq_dest_lhs inj_ket inv_f_f rangeI)\n\n\n  then have \\<open>tensor_op M N *\\<^sub>V (ket (a,c)) = \\<phi> (a,c)\\<close>\n    unfolding def apply (rule someI2_ex[where P=\\<open>\\<lambda>P. \\<forall>a c. P *\\<^sub>V (ket (a,c)) = \\<phi> (a,c)\\<close>])\n    by auto\n  then show ?thesis\n    unfolding \\<phi>_def by auto\nqed\n\n\nlemma tensor_op_ell2: \"tensor_op A B *\\<^sub>V tensor_ell2 \\<psi> \\<phi> = tensor_ell2 (A *\\<^sub>V \\<psi>) (B *\\<^sub>V \\<phi>)\"\nproof -\n  have 1: \\<open>clinear (\\<lambda>a. tensor_op A B *\\<^sub>V tensor_ell2 a (ket b))\\<close> for b\n    by (auto intro!: clinearI simp: tensor_ell2_add1 tensor_ell2_scaleC1 cblinfun.add_right)\n  have 2: \\<open>clinear (\\<lambda>a. tensor_ell2 (A *\\<^sub>V a) (B *\\<^sub>V ket b))\\<close> for b\n    by (auto intro!: clinearI simp: tensor_ell2_add1 tensor_ell2_scaleC1 cblinfun.add_right)\n  have 3: \\<open>clinear (\\<lambda>a. tensor_op A B *\\<^sub>V tensor_ell2 \\<psi> a)\\<close>\n    by (auto intro!: clinearI simp: tensor_ell2_add2 tensor_ell2_scaleC2 cblinfun.add_right)\n  have 4: \\<open>clinear (\\<lambda>a. tensor_ell2 (A *\\<^sub>V \\<psi>) (B *\\<^sub>V a))\\<close>\n    by (auto intro!: clinearI simp: tensor_ell2_add2 tensor_ell2_scaleC2 cblinfun.add_right)\n\n  have eq_ket_ket: \\<open>tensor_op A B *\\<^sub>V tensor_ell2 (ket a) (ket b) = tensor_ell2 (A *\\<^sub>V ket a) (B *\\<^sub>V ket b)\\<close> for a b\n    by (simp add: tensor_op_ket)\n  have eq_ket: \\<open>tensor_op A B *\\<^sub>V tensor_ell2 \\<psi> (ket b) = tensor_ell2 (A *\\<^sub>V \\<psi>) (B *\\<^sub>V ket b)\\<close> for b\n    apply (rule fun_cong[where x=\\<psi>])\n    using 1 2 eq_ket_ket by (rule clinear_equal_ket)\n  show ?thesis \n    apply (rule fun_cong[where x=\\<phi>])\n    using 3 4 eq_ket by (rule clinear_equal_ket)\nqed\n\nlemma comp_tensor_op: \"(tensor_op a b) o\\<^sub>C\\<^sub>L (tensor_op c d) = tensor_op (a o\\<^sub>C\\<^sub>L c) (b o\\<^sub>C\\<^sub>L d)\"\n  for a :: \"'e::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2\" and b :: \"'f::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\" and\n      c :: \"'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'e ell2\" and d :: \"'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'f ell2\"\n  apply (rule equal_ket)\n  apply (rename_tac ij, case_tac ij, rename_tac i j, hypsubst_thin)\n  by (simp flip: tensor_ell2_ket add: tensor_op_ell2 cblinfun_apply_cblinfun_compose)\n\n\nlemma tensor_op_cbilinear: \\<open>cbilinear (tensor_op :: 'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::finite ell2\n                                                 \\<Rightarrow> 'c::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2 \\<Rightarrow> _)\\<close>\nproof -\n  have \\<open>clinear (\\<lambda>b::'c ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd ell2. tensor_op a b)\\<close> for a :: \\<open>'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b ell2\\<close>\n    apply (rule clinearI)\n     apply (rule equal_ket, rename_tac ij, case_tac ij, rename_tac i j, hypsubst_thin)\n     apply (simp flip: tensor_ell2_ket add: tensor_op_ell2 cblinfun.add_left tensor_ell2_add2)\n    apply (rule equal_ket, rename_tac ij, case_tac ij, rename_tac i j, hypsubst_thin)\n    by (simp add: scaleC_cblinfun.rep_eq tensor_ell2_scaleC2 tensor_op_ket)\n\n  moreover have \\<open>clinear (\\<lambda>a::'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::finite ell2. tensor_op a b)\\<close> for b :: \\<open>'c ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd ell2\\<close>\n    apply (rule clinearI)\n     apply (rule equal_ket, rename_tac ij, case_tac ij, rename_tac i j, hypsubst_thin)\n     apply (simp flip: tensor_ell2_ket add: tensor_op_ell2 cblinfun.add_left tensor_ell2_add1)\n    apply (rule equal_ket, rename_tac ij, case_tac ij, rename_tac i j, hypsubst_thin)\n    by (simp add: scaleC_cblinfun.rep_eq tensor_ell2_scaleC1 tensor_op_ket)\n\n  ultimately show ?thesis\n    unfolding cbilinear_def by auto\nqed\n\n\nlemma tensor_butter: \\<open>tensor_op (butterket i j) (butterket k l) = butterket (i,k) (j,l)\\<close>\n  for i :: \"_\" and j :: \"_::finite\" and k :: \"_\" and l :: \"_::finite\"\n  apply (rule equal_ket, rename_tac x, case_tac x)\n  apply (auto simp flip: tensor_ell2_ket simp: cblinfun_apply_cblinfun_compose tensor_op_ell2 butterfly_def)\n  by (auto simp: tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n\nlemma cspan_tensor_op: \\<open>cspan {tensor_op (butterket i j) (butterket k l)| i (j::_::finite) k (l::_::finite). True} = UNIV\\<close>\n  unfolding tensor_butter\n  apply (subst cspan_butterfly_ket[symmetric])\n  by (metis surj_pair)\n\nlemma cindependent_tensor_op: \\<open>cindependent {tensor_op (butterket i j) (butterket k l)| i (j::_::finite) k (l::_::finite). True}\\<close>\n  unfolding tensor_butter\n  using cindependent_butterfly_ket\n  by (smt (z3) Collect_mono_iff complex_vector.independent_mono)\n\n\nlemma tensor_extensionality:\n  fixes F G :: \\<open>((('a::finite \\<times> 'b::finite) ell2) \\<Rightarrow>\\<^sub>C\\<^sub>L (('c::finite \\<times> 'd::finite) ell2)) \\<Rightarrow> 'e::complex_vector\\<close>\n  assumes [simp]: \"clinear F\" \"clinear G\"\n  assumes tensor_eq: \"(\\<And>a b. F (tensor_op a b) = G (tensor_op a b))\"\n  shows \"F = G\"\nproof (rule ext, rule complex_vector.linear_eq_on_span[where f=F and g=G])\n  show \\<open>clinear F\\<close> and \\<open>clinear G\\<close>\n    using assms by (simp_all add: cbilinear_def)\n  show \\<open>x \\<in> cspan  {tensor_op (butterket i j) (butterket k l)| i j k l. True}\\<close> \n    for x :: \\<open>('a \\<times> 'b) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('c \\<times> 'd) ell2\\<close>\n    using cspan_tensor_op by auto\n  show \\<open>F x = G x\\<close> if \\<open>x \\<in> {tensor_op (butterket i j) (butterket k l) |i j k l. True}\\<close> for x\n    using that by (auto simp: tensor_eq)\nqed\n\nlemma tensor_id[simp]: \\<open>tensor_op id_cblinfun id_cblinfun = id_cblinfun\\<close>\n  apply (rule equal_ket, rename_tac x, case_tac x)\n  by (simp flip: tensor_ell2_ket add: tensor_op_ell2)\n\nlemma tensor_op_adjoint: \\<open>(tensor_op a b)* = tensor_op (a*) (b*)\\<close>\n  apply (rule cinner_ket_adjointI[symmetric])\n  apply (auto simp flip: tensor_ell2_ket simp: tensor_op_ell2)\n  by (simp add: cinner_adj_left)\n\nlemma tensor_butterfly[simp]: \"tensor_op (butterfly \\<psi> \\<psi>') (butterfly \\<phi> \\<phi>') = butterfly (tensor_ell2 \\<psi> \\<phi>) (tensor_ell2 \\<psi>' \\<phi>')\"\n  apply (rule equal_ket, rename_tac x, case_tac x)\n  by (simp flip: tensor_ell2_ket add: tensor_op_ell2 butterfly_def\n      cblinfun_apply_cblinfun_compose tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n\ndefinition tensor_lift :: \\<open>(('a1::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'a2::finite ell2) \\<Rightarrow> ('b1::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b2::finite ell2) \\<Rightarrow> 'c)\n                        \\<Rightarrow> ((('a1\\<times>'b1) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('a2\\<times>'b2) ell2) \\<Rightarrow> 'c::complex_vector)\\<close> where\n  \"tensor_lift F2 = (SOME G. clinear G \\<and> (\\<forall>a b. G (tensor_op a b) = F2 a b))\"\n\nlemma \n  fixes F2 :: \"'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::finite ell2\n            \\<Rightarrow> 'c::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\n            \\<Rightarrow> 'e::complex_normed_vector\"\n  assumes \"cbilinear F2\"\n  shows tensor_lift_clinear: \"clinear (tensor_lift F2)\"\n    and tensor_lift_correct:  \\<open>(\\<lambda>a b. tensor_lift F2 (tensor_op a b)) = F2\\<close>\nproof -\n  define F2' t4 \\<phi> where\n    \\<open>F2' = tensor_lift F2\\<close> and\n    \\<open>t4 = (\\<lambda>(i,j,k,l). tensor_op (butterket i j) (butterket k l))\\<close> and\n    \\<open>\\<phi> m = (let (i,j,k,l) = inv t4 m in F2 (butterket i j) (butterket k l))\\<close> for m\n  have t4inj: \"x = y\" if \"t4 x = t4 y\" for x y\n  proof (rule ccontr)\n    obtain i  j  k  l  where x: \"x = (i,j,k,l)\" by (meson prod_cases4) \n    obtain i' j' k' l' where y: \"y = (i',j',k',l')\" by (meson prod_cases4) \n    have 1: \"bra (i,k) *\\<^sub>V t4 x *\\<^sub>V ket (j,l) = 1\"\n      by (auto simp: t4_def x tensor_op_ell2 butterfly_def cinner_ket simp flip: tensor_ell2_ket)\n    assume \\<open>x \\<noteq> y\\<close>\n    then have 2: \"bra (i,k) *\\<^sub>V t4 y *\\<^sub>V ket (j,l) = 0\"\n      by (auto simp: t4_def x y tensor_op_ell2 butterfly_def cblinfun_apply_cblinfun_compose cinner_ket\n               simp flip: tensor_ell2_ket)\n    from 1 2 that\n    show False\n      by auto\n  qed\n  have \\<open>\\<phi> (tensor_op (butterket i j) (butterket k l)) = F2 (butterket i j) (butterket k l)\\<close> for i j k l\n    apply (subst asm_rl[of \\<open>tensor_op (butterket i j) (butterket k l) = t4 (i,j,k,l)\\<close>])\n     apply (simp add: t4_def)\n    by (auto simp add: injI t4inj inv_f_f \\<phi>_def)\n\n  have *: \\<open>range t4 = {tensor_op (butterket i j) (butterket k l) |i j k l. True}\\<close>\n    apply (auto simp: case_prod_beta t4_def)\n    using image_iff by fastforce\n\n  have \"cblinfun_extension_exists (range t4) \\<phi>\"\n    thm cblinfun_extension_exists_finite_dim[where \\<phi>=\\<phi>]\n    apply (rule cblinfun_extension_exists_finite_dim)\n     apply auto unfolding * \n    using cindependent_tensor_op\n    using cspan_tensor_op\n    by auto\n\n  then obtain G where G: \\<open>G *\\<^sub>V (t4 (i,j,k,l)) = F2 (butterket i j) (butterket k l)\\<close> for i j k l\n    apply atomize_elim\n    unfolding cblinfun_extension_exists_def\n    apply auto\n    by (metis (no_types, lifting) t4inj \\<phi>_def f_inv_into_f rangeI split_conv)\n\n  have *: \\<open>G *\\<^sub>V tensor_op (butterket i j) (butterket k l) = F2 (butterket i j) (butterket k l)\\<close> for i j k l\n    using G by (auto simp: t4_def)\n  have *: \\<open>G *\\<^sub>V tensor_op a (butterket k l) = F2 a (butterket k l)\\<close> for a k l\n    apply (rule complex_vector.linear_eq_on_span[where g=\\<open>\\<lambda>a. F2 a _\\<close> and B=\\<open>{butterket k l|k l. True}\\<close>])\n    unfolding cspan_butterfly_ket\n    using * apply (auto intro!: clinear_compose[unfolded o_def, where f=\\<open>\\<lambda>a. tensor_op a _\\<close> and g=\\<open>(*\\<^sub>V) G\\<close>])\n     apply (metis cbilinear_def tensor_op_cbilinear)\n    using assms unfolding cbilinear_def by blast\n  have G_F2: \\<open>G *\\<^sub>V tensor_op a b = F2 a b\\<close> for a b\n    apply (rule complex_vector.linear_eq_on_span[where g=\\<open>F2 a\\<close> and B=\\<open>{butterket k l|k l. True}\\<close>])\n    unfolding cspan_butterfly_ket\n    using * apply (auto simp: cblinfun.add_right clinearI\n                        intro!: clinear_compose[unfolded o_def, where f=\\<open>tensor_op a\\<close> and g=\\<open>(*\\<^sub>V) G\\<close>])\n    apply (meson cbilinear_def tensor_op_cbilinear)\n    using assms unfolding cbilinear_def by blast\n\n  have \\<open>clinear F2' \\<and> (\\<forall>a b. F2' (tensor_op a b) = F2 a b)\\<close>\n    unfolding F2'_def tensor_lift_def \n    apply (rule someI[where x=\\<open>(*\\<^sub>V) G\\<close> and P=\\<open>\\<lambda>G. clinear G \\<and> (\\<forall>a b. G (tensor_op a b) = F2 a b)\\<close>])\n    using G_F2 by (simp add: cblinfun.add_right clinearI)\n\n  then show \\<open>clinear F2'\\<close> and \\<open>(\\<lambda>a b. tensor_lift F2 (tensor_op a b)) = F2\\<close>\n    unfolding F2'_def by auto\nqed\n\nlift_definition assoc_ell20 :: \\<open>(('a::finite\\<times>'b::finite)\\<times>'c::finite) ell2 \\<Rightarrow> ('a\\<times>('b\\<times>'c)) ell2\\<close> is\n  \\<open>\\<lambda>f (a,(b,c)). f ((a,b),c)\\<close>\n  by auto\n\nlift_definition assoc_ell20' :: \\<open>('a::finite\\<times>('b::finite\\<times>'c::finite)) ell2 \\<Rightarrow> (('a\\<times>'b)\\<times>'c) ell2\\<close> is\n  \\<open>\\<lambda>f ((a,b),c). f (a,(b,c))\\<close>\n  by auto\n\nlift_definition assoc_ell2 :: \\<open>(('a::finite\\<times>'b::finite)\\<times>'c::finite) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('a\\<times>('b\\<times>'c)) ell2\\<close>\n  is assoc_ell20\n  apply (subst bounded_clinear_finite_dim)\n   apply (rule clinearI; transfer)\n  by auto\n\nlift_definition assoc_ell2' :: \\<open>('a::finite\\<times>('b::finite\\<times>'c::finite)) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L (('a\\<times>'b)\\<times>'c) ell2\\<close> is\n  assoc_ell20'\n  apply (subst bounded_clinear_finite_dim)\n   apply (rule clinearI; transfer)\n  by auto\n\nlemma assoc_ell2_tensor: \\<open>assoc_ell2 *\\<^sub>V tensor_ell2 (tensor_ell2 a b) c = tensor_ell2 a (tensor_ell2 b c)\\<close>\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=a])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add1 tensor_ell2_scaleC1)\n   apply (simp add: clinear_tensor_ell22)\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=b])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add1 tensor_ell2_add2 tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n   apply (simp add: clinearI tensor_ell2_add1 tensor_ell2_add2 tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=c])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add2 tensor_ell2_scaleC2)\n   apply (simp add: clinearI tensor_ell2_add2 tensor_ell2_scaleC2)\n  unfolding assoc_ell2.rep_eq\n  apply transfer\n  by auto\n\nlemma assoc_ell2'_tensor: \\<open>assoc_ell2' *\\<^sub>V tensor_ell2 a (tensor_ell2 b c) = tensor_ell2 (tensor_ell2 a b) c\\<close>\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=a])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add1 tensor_ell2_scaleC1)\n   apply (simp add: clinearI tensor_ell2_add1 tensor_ell2_scaleC1)\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=b])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add1 tensor_ell2_add2 tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n   apply (simp add: clinearI tensor_ell2_add1 tensor_ell2_add2 tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=c])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add2 tensor_ell2_scaleC2)\n   apply (simp add: clinearI tensor_ell2_add2 tensor_ell2_scaleC2)\n  unfolding assoc_ell2'.rep_eq\n  apply transfer\n  by auto\n\nlemma adjoint_assoc_ell2[simp]: \\<open>assoc_ell2* = assoc_ell2'\\<close>\nproof (rule adjoint_eqI[symmetric])\n  have [simp]: \\<open>clinear (cinner (assoc_ell2' *\\<^sub>V x))\\<close> for x :: \\<open>('a \\<times> 'b \\<times> 'c) ell2\\<close>\n    by (metis (no_types, lifting) cblinfun.add_right cinner_scaleC_right clinearI complex_scaleC_def mult.comm_neutral of_complex_def vector_to_cblinfun_adj_apply)\n  have [simp]: \\<open>clinear (\\<lambda>a. x \\<bullet>\\<^sub>C (assoc_ell2 *\\<^sub>V a))\\<close> for x :: \\<open>('a \\<times> 'b \\<times> 'c) ell2\\<close>\n    by (simp add: cblinfun.add_right cinner_add_right clinearI)\n  have [simp]: \\<open>antilinear (\\<lambda>a. a \\<bullet>\\<^sub>C y)\\<close> for y :: \\<open>('a \\<times> 'b \\<times> 'c) ell2\\<close>\n    using bounded_antilinear_cinner_left bounded_antilinear_def by blast\n  have [simp]: \\<open>antilinear (\\<lambda>a. (assoc_ell2' *\\<^sub>V a) \\<bullet>\\<^sub>C y)\\<close> for y :: \\<open>(('a \\<times> 'b) \\<times> 'c) ell2\\<close>\n    by (simp add: cblinfun.add_right cinner_add_left antilinearI)\n  have \\<open>(assoc_ell2' *\\<^sub>V ket x) \\<bullet>\\<^sub>C ket y = ket x \\<bullet>\\<^sub>C (assoc_ell2 *\\<^sub>V ket y)\\<close> for x :: \\<open>'a \\<times> 'b \\<times> 'c\\<close> and y\n    apply (cases x, cases y)\n    by (simp flip: tensor_ell2_ket add: assoc_ell2'_tensor assoc_ell2_tensor)\n  then have \\<open>(assoc_ell2' *\\<^sub>V ket x) \\<bullet>\\<^sub>C y = ket x \\<bullet>\\<^sub>C (assoc_ell2 *\\<^sub>V y)\\<close> for x :: \\<open>'a \\<times> 'b \\<times> 'c\\<close> and y\n    by (rule clinear_equal_ket[THEN fun_cong, rotated 2], simp_all)\n  then show \\<open>(assoc_ell2' *\\<^sub>V x) \\<bullet>\\<^sub>C y = x \\<bullet>\\<^sub>C (assoc_ell2 *\\<^sub>V y)\\<close> for x :: \\<open>('a \\<times> 'b \\<times> 'c) ell2\\<close> and y\n    by (rule antilinear_equal_ket[THEN fun_cong, rotated 2], simp_all)\nqed\n\nlemma adjoint_assoc_ell2'[simp]: \\<open>assoc_ell2'* = assoc_ell2\\<close>\n  by (simp flip: adjoint_assoc_ell2)\n\n\nlift_definition swap_ell20 :: \\<open>('a::finite\\<times>'b::finite) ell2 \\<Rightarrow> ('b\\<times>'a) ell2\\<close> is\n  \\<open>\\<lambda>f (a,b). f (b,a)\\<close>\n  by auto\n\nlift_definition swap_ell2 :: \\<open>('a::finite\\<times>'b::finite) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('b\\<times>'a) ell2\\<close>\n  is swap_ell20\n  apply (subst bounded_clinear_finite_dim)\n   apply (rule clinearI; transfer)\n  by auto\n\nlemma swap_ell2_tensor[simp]: \\<open>swap_ell2 *\\<^sub>V tensor_ell2 a b = tensor_ell2 b a\\<close>\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=a])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add1 tensor_ell2_scaleC1)\n   apply (simp add: clinear_tensor_ell21)\n  apply (rule clinear_equal_ket[THEN fun_cong, where x=b])\n    apply (simp add: cblinfun.add_right clinearI tensor_ell2_add1 tensor_ell2_add2 tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n   apply (simp add: clinearI tensor_ell2_add1 tensor_ell2_add2 tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n  unfolding swap_ell2.rep_eq\n  apply transfer\n  by auto\n\nlemma adjoint_swap_ell2[simp]: \\<open>swap_ell2* = swap_ell2\\<close>\nproof (rule adjoint_eqI[symmetric])\n  have [simp]: \\<open>clinear (cinner (swap_ell2 *\\<^sub>V x))\\<close> for x :: \\<open>('a \\<times> 'b) ell2\\<close>\n    by (metis (no_types, lifting) cblinfun.add_right cinner_scaleC_right clinearI complex_scaleC_def mult.comm_neutral of_complex_def vector_to_cblinfun_adj_apply)\n  have [simp]: \\<open>clinear (\\<lambda>a. x \\<bullet>\\<^sub>C (swap_ell2 *\\<^sub>V a))\\<close> for x :: \\<open>('a \\<times> 'b) ell2\\<close>\n    by (simp add: cblinfun.add_right cinner_add_right clinearI)\n  have [simp]: \\<open>antilinear (\\<lambda>a. a \\<bullet>\\<^sub>C y)\\<close> for y :: \\<open>('a \\<times> 'b) ell2\\<close>\n    using bounded_antilinear_cinner_left bounded_antilinear_def by blast\n  have [simp]: \\<open>antilinear (\\<lambda>a. (swap_ell2 *\\<^sub>V a) \\<bullet>\\<^sub>C y)\\<close> for y :: \\<open>('b \\<times> 'a) ell2\\<close>\n    by (simp add: cblinfun.add_right cinner_add_left antilinearI)\n  have \\<open>(swap_ell2 *\\<^sub>V ket x) \\<bullet>\\<^sub>C ket y = ket x \\<bullet>\\<^sub>C (swap_ell2 *\\<^sub>V ket y)\\<close> for x :: \\<open>'a \\<times> 'b\\<close> and y\n    apply (cases x, cases y)\n    by (simp flip: tensor_ell2_ket add: swap_ell2_tensor)\n  then have \\<open>(swap_ell2 *\\<^sub>V ket x) \\<bullet>\\<^sub>C y = ket x \\<bullet>\\<^sub>C (swap_ell2 *\\<^sub>V y)\\<close> for x :: \\<open>'a \\<times> 'b\\<close> and y\n    by (rule clinear_equal_ket[THEN fun_cong, rotated 2], simp_all)\n  then show \\<open>(swap_ell2 *\\<^sub>V x) \\<bullet>\\<^sub>C y = x \\<bullet>\\<^sub>C (swap_ell2 *\\<^sub>V y)\\<close> for x :: \\<open>('a \\<times> 'b) ell2\\<close> and y\n    apply (rule antilinear_equal_ket[THEN fun_cong, rotated 2])\n    by simp_all\nqed\n\n\nlemma tensor_ell2_extensionality:\n  assumes \"(\\<And>s t. a *\\<^sub>V (s \\<otimes>\\<^sub>s t) = b *\\<^sub>V (s \\<otimes>\\<^sub>s t))\"\n  shows \"a = b\"\n  apply (rule equal_ket, case_tac x, hypsubst_thin)\n  by (simp add: assms flip: tensor_ell2_ket)\n\nlemma assoc_ell2'_assoc_ell2[simp]: \\<open>assoc_ell2' o\\<^sub>C\\<^sub>L assoc_ell2 = id_cblinfun\\<close>\n  by (auto intro!: equal_ket simp: cblinfun_apply_cblinfun_compose assoc_ell2'_tensor assoc_ell2_tensor simp flip: tensor_ell2_ket)\n\nlemma assoc_ell2_assoc_ell2'[simp]: \\<open>assoc_ell2 o\\<^sub>C\\<^sub>L assoc_ell2' = id_cblinfun\\<close>\n  by (auto intro!: equal_ket simp: cblinfun_apply_cblinfun_compose assoc_ell2'_tensor assoc_ell2_tensor simp flip: tensor_ell2_ket)\n\nlemma unitary_assoc_ell2[simp]: \"unitary assoc_ell2\"\n  unfolding unitary_def by auto\n\nlemma unitary_assoc_ell2'[simp]: \"unitary assoc_ell2'\"\n  unfolding unitary_def by auto\n\nlemma tensor_op_left_add: \\<open>(x + y) \\<otimes>\\<^sub>o b = x \\<otimes>\\<^sub>o b + y \\<otimes>\\<^sub>o b\\<close>\n  for x y :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2\\<close> and b :: \\<open>'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\n  apply (auto intro!: equal_ket simp: tensor_op_ket)\n  by (simp add: plus_cblinfun.rep_eq tensor_ell2_add1 tensor_op_ket)\n\nlemma tensor_op_right_add: \\<open>b \\<otimes>\\<^sub>o (x + y) = b \\<otimes>\\<^sub>o x + b \\<otimes>\\<^sub>o y\\<close>\n  for x y :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2\\<close> and b :: \\<open>'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\n  apply (auto intro!: equal_ket simp: tensor_op_ket)\n  by (simp add: plus_cblinfun.rep_eq tensor_ell2_add2 tensor_op_ket)\n\nlemma tensor_op_scaleC_left: \\<open>(c *\\<^sub>C x) \\<otimes>\\<^sub>o b = c *\\<^sub>C (x \\<otimes>\\<^sub>o b)\\<close>\n  for x :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2\\<close> and b :: \\<open>'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\n  apply (auto intro!: equal_ket simp: tensor_op_ket)\n  by (metis scaleC_cblinfun.rep_eq tensor_ell2_ket tensor_ell2_scaleC1 tensor_op_ell2)\n\nlemma tensor_op_scaleC_right: \\<open>b \\<otimes>\\<^sub>o (c *\\<^sub>C x) = c *\\<^sub>C (b \\<otimes>\\<^sub>o x)\\<close>\n  for x :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2\\<close> and b :: \\<open>'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\n  apply (auto intro!: equal_ket simp: tensor_op_ket)\n  by (metis scaleC_cblinfun.rep_eq tensor_ell2_ket tensor_ell2_scaleC2 tensor_op_ell2)\n\nlemma clinear_tensor_left[simp]: \\<open>clinear (\\<lambda>a. a \\<otimes>\\<^sub>o b :: _::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _::finite ell2)\\<close>\n  apply (rule clinearI)\n   apply (rule tensor_op_left_add)\n  by (rule tensor_op_scaleC_left)\n\nlemma clinear_tensor_right[simp]: \\<open>clinear (\\<lambda>b. a \\<otimes>\\<^sub>o b :: _::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L _::finite ell2)\\<close>\n  apply (rule clinearI)\n   apply (rule tensor_op_right_add)\n  by (rule tensor_op_scaleC_right)\n\nlemma tensor_ell2_nonzero: \\<open>a \\<otimes>\\<^sub>s b \\<noteq> 0\\<close> if \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close>\n  apply (use that in transfer)\n  apply auto\n  by (metis mult_eq_0_iff old.prod.case)\n\nlemma tensor_op_nonzero:\n  fixes a :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2\\<close> and b :: \\<open>'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\n  assumes \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close>\n  shows \\<open>a \\<otimes>\\<^sub>o b \\<noteq> 0\\<close>\nproof -\n  from \\<open>a \\<noteq> 0\\<close> obtain i where i: \\<open>a *\\<^sub>V ket i \\<noteq> 0\\<close>\n    by (metis cblinfun.zero_left equal_ket)\n  from \\<open>b \\<noteq> 0\\<close> obtain j where j: \\<open>b *\\<^sub>V ket j \\<noteq> 0\\<close>\n    by (metis cblinfun.zero_left equal_ket)\n  from i j have ijneq0: \\<open>(a *\\<^sub>V ket i) \\<otimes>\\<^sub>s (b *\\<^sub>V ket j) \\<noteq> 0\\<close>\n    by (simp add: tensor_ell2_nonzero)\n  have \\<open>(a *\\<^sub>V ket i) \\<otimes>\\<^sub>s (b *\\<^sub>V ket j) = (a \\<otimes>\\<^sub>o b) *\\<^sub>V ket (i,j)\\<close>\n    by (simp add: tensor_op_ket)\n  with ijneq0 show \\<open>a \\<otimes>\\<^sub>o b \\<noteq> 0\\<close>\n    by force\nqed\n\nlemma inj_tensor_ell2_left: \\<open>inj (\\<lambda>a::'a::finite ell2. a \\<otimes>\\<^sub>s b)\\<close> if \\<open>b \\<noteq> 0\\<close> for b :: \\<open>'b::finite ell2\\<close>\nproof (rule injI, rule ccontr)\n  fix x y :: \\<open>'a ell2\\<close>\n  assume eq: \\<open>x \\<otimes>\\<^sub>s b = y \\<otimes>\\<^sub>s b\\<close>\n  assume neq: \\<open>x \\<noteq> y\\<close>\n  define a where \\<open>a = x - y\\<close>\n  from neq a_def have neq0: \\<open>a \\<noteq> 0\\<close>\n    by auto\n  with \\<open>b \\<noteq> 0\\<close> have \\<open>a \\<otimes>\\<^sub>s b \\<noteq> 0\\<close>\n    by (simp add: tensor_ell2_nonzero)\n  then have \\<open>x \\<otimes>\\<^sub>s b \\<noteq> y \\<otimes>\\<^sub>s b\\<close>\n    unfolding a_def\n    by (metis add_cancel_left_left diff_add_cancel tensor_ell2_add1)\n  with eq show False\n    by auto\nqed\n\nlemma inj_tensor_ell2_right: \\<open>inj (\\<lambda>b::'b::finite ell2. a \\<otimes>\\<^sub>s b)\\<close> if \\<open>a \\<noteq> 0\\<close> for a :: \\<open>'a::finite ell2\\<close>\nproof (rule injI, rule ccontr)\n  fix x y :: \\<open>'b ell2\\<close>\n  assume eq: \\<open>a \\<otimes>\\<^sub>s x = a \\<otimes>\\<^sub>s y\\<close>\n  assume neq: \\<open>x \\<noteq> y\\<close>\n  define b where \\<open>b = x - y\\<close>\n  from neq b_def have neq0: \\<open>b \\<noteq> 0\\<close>\n    by auto\n  with \\<open>a \\<noteq> 0\\<close> have \\<open>a \\<otimes>\\<^sub>s b \\<noteq> 0\\<close>\n    by (simp add: tensor_ell2_nonzero)\n  then have \\<open>a \\<otimes>\\<^sub>s x \\<noteq> a \\<otimes>\\<^sub>s y\\<close>\n    unfolding b_def\n    by (metis add_cancel_left_left diff_add_cancel tensor_ell2_add2)\n  with eq show False\n    by auto\nqed\n\n\n\nlemma inj_tensor_left: \\<open>inj (\\<lambda>a::'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2. a \\<otimes>\\<^sub>o b)\\<close> if \\<open>b \\<noteq> 0\\<close> for b :: \\<open>'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\nproof (rule injI, rule ccontr)\n  fix x y :: \\<open>'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c ell2\\<close>\n  assume eq: \\<open>x \\<otimes>\\<^sub>o b = y \\<otimes>\\<^sub>o b\\<close>\n  assume neq: \\<open>x \\<noteq> y\\<close>\n  define a where \\<open>a = x - y\\<close>\n  from neq a_def have neq0: \\<open>a \\<noteq> 0\\<close>\n    by auto\n  with \\<open>b \\<noteq> 0\\<close> have \\<open>a \\<otimes>\\<^sub>o b \\<noteq> 0\\<close>\n    by (simp add: tensor_op_nonzero)\n  then have \\<open>x \\<otimes>\\<^sub>o b \\<noteq> y \\<otimes>\\<^sub>o b\\<close>\n    unfolding a_def\n    by (metis add_cancel_left_left diff_add_cancel tensor_op_left_add) \n  with eq show False\n    by auto\nqed\n\nlemma inj_tensor_right: \\<open>inj (\\<lambda>b::'b::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c::finite ell2. a \\<otimes>\\<^sub>o b)\\<close> if \\<open>a \\<noteq> 0\\<close> for a :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\nproof (rule injI, rule ccontr)\n  fix x y :: \\<open>'b ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'c ell2\\<close>\n  assume eq: \\<open>a \\<otimes>\\<^sub>o x = a \\<otimes>\\<^sub>o y\\<close>\n  assume neq: \\<open>x \\<noteq> y\\<close>\n  define b where \\<open>b = x - y\\<close>\n  from neq b_def have neq0: \\<open>b \\<noteq> 0\\<close>\n    by auto\n  with \\<open>a \\<noteq> 0\\<close> have \\<open>a \\<otimes>\\<^sub>o b \\<noteq> 0\\<close>\n    by (simp add: tensor_op_nonzero)\n  then have \\<open>a \\<otimes>\\<^sub>o x \\<noteq> a \\<otimes>\\<^sub>o y\\<close>\n    unfolding b_def\n    by (metis add_cancel_left_left diff_add_cancel tensor_op_right_add) \n  with eq show False\n    by auto\nqed\n\nlemma tensor_ell2_almost_injective:\n  assumes \\<open>tensor_ell2 a b = tensor_ell2 c d\\<close>\n  assumes \\<open>a \\<noteq> 0\\<close>\n  shows \\<open>\\<exists>\\<gamma>. b = \\<gamma> *\\<^sub>C d\\<close>\nproof -\n  from \\<open>a \\<noteq> 0\\<close> obtain i where i: \\<open>cinner (ket i) a \\<noteq> 0\\<close>\n    by (metis cinner_eq_zero_iff cinner_ket_left ell2_pointwise_ortho)\n  have \\<open>cinner (ket i \\<otimes>\\<^sub>s ket j) (a \\<otimes>\\<^sub>s b) = cinner (ket i \\<otimes>\\<^sub>s ket j) (c \\<otimes>\\<^sub>s d)\\<close> for j\n    using assms by simp\n  then have eq2: \\<open>(cinner (ket i) a) * (cinner (ket j) b) = (cinner (ket i) c) * (cinner (ket j) d)\\<close> for j\n    by (metis tensor_ell2_inner_prod)\n  then obtain \\<gamma> where \\<open>cinner (ket i) c = \\<gamma> * cinner (ket i) a\\<close>\n    by (metis i eq_divide_eq)\n  with eq2 have \\<open>(cinner (ket i) a) * (cinner (ket j) b) = (cinner (ket i) a) * (\\<gamma> * cinner (ket j) d)\\<close> for j\n    by simp\n  then have \\<open>cinner (ket j) b = cinner (ket j) (\\<gamma> *\\<^sub>C d)\\<close> for j\n    using i by force\n  then have \\<open>b = \\<gamma> *\\<^sub>C d\\<close>\n    by (simp add: cinner_ket_eqI)\n  then show ?thesis\n    by auto\nqed\n\n\nlemma tensor_op_almost_injective:\n  fixes a c :: \\<open>'a::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::finite ell2\\<close>\n    and b d :: \\<open>'c::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2\\<close>\n  assumes \\<open>tensor_op a b = tensor_op c d\\<close>\n  assumes \\<open>a \\<noteq> 0\\<close>\n  shows \\<open>\\<exists>\\<gamma>. b = \\<gamma> *\\<^sub>C d\\<close>\nproof (cases \\<open>d = 0\\<close>)\n  case False\n  from \\<open>a \\<noteq> 0\\<close> obtain \\<psi> where \\<psi>: \\<open>a *\\<^sub>V \\<psi> \\<noteq> 0\\<close>\n    by (metis cblinfun.zero_left cblinfun_eqI)\n  have \\<open>(a \\<otimes>\\<^sub>o b) (\\<psi> \\<otimes>\\<^sub>s \\<phi>) = (c \\<otimes>\\<^sub>o d) (\\<psi> \\<otimes>\\<^sub>s \\<phi>)\\<close> for \\<phi>\n    using assms by simp\n  then have eq2: \\<open>(a \\<psi>) \\<otimes>\\<^sub>s (b \\<phi>) = (c \\<psi>) \\<otimes>\\<^sub>s (d \\<phi>)\\<close> for \\<phi>\n    by (simp add: tensor_op_ell2)\n  then have eq2': \\<open>(d \\<phi>) \\<otimes>\\<^sub>s (c \\<psi>) = (b \\<phi>) \\<otimes>\\<^sub>s (a \\<psi>)\\<close> for \\<phi>\n    by (metis swap_ell2_tensor)\n  from False obtain \\<phi>0 where \\<phi>0: \\<open>d \\<phi>0 \\<noteq> 0\\<close>\n    by (metis cblinfun.zero_left cblinfun_eqI)\n  obtain \\<gamma> where \\<open>c \\<psi> = \\<gamma> *\\<^sub>C a \\<psi>\\<close>\n    apply atomize_elim\n    using eq2' \\<phi>0 by (rule tensor_ell2_almost_injective)\n  with eq2 have \\<open>(a \\<psi>) \\<otimes>\\<^sub>s (b \\<phi>) = (a \\<psi>) \\<otimes>\\<^sub>s (\\<gamma> *\\<^sub>C d \\<phi>)\\<close> for \\<phi>\n    by (simp add: tensor_ell2_scaleC1 tensor_ell2_scaleC2)\n  then have \\<open>b \\<phi> = \\<gamma> *\\<^sub>C d \\<phi>\\<close> for \\<phi>\n    by (smt (verit, best) \\<psi> complex_vector.scale_cancel_right tensor_ell2_almost_injective tensor_ell2_nonzero tensor_ell2_scaleC2)\n  then have \\<open>b = \\<gamma> *\\<^sub>C d\\<close>\n    by (simp add: cblinfun_eqI)\n  then show ?thesis\n    by auto\nnext\n  case True\n  then have \\<open>c \\<otimes>\\<^sub>o d = 0\\<close>\n    by (metis add_cancel_right_left tensor_op_right_add)\n  then have \\<open>a \\<otimes>\\<^sub>o b = 0\\<close>\n    using assms(1) by presburger\n  with \\<open>a \\<noteq> 0\\<close> have \\<open>b = 0\\<close>\n    by (meson tensor_op_nonzero)\n  then show ?thesis\n    by auto\nqed\n\n\nlemma tensor_ell2_0_left[simp]: \\<open>tensor_ell2 0 x = 0\\<close>\n  apply transfer by auto\n\nlemma tensor_ell2_0_right[simp]: \\<open>tensor_ell2 x 0 = 0\\<close>\n  apply transfer by auto\n\nlemma tensor_op_0_left[simp]: \\<open>tensor_op 0 x = (0 :: ('a::finite*'b::finite) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('c::finite*'d::finite) ell2)\\<close>\n  apply (rule equal_ket)\n  by (auto simp flip: tensor_ell2_ket simp: tensor_op_ell2)\n\nlemma tensor_op_0_right[simp]: \\<open>tensor_op x 0 = (0 :: ('a::finite*'b::finite) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('c::finite*'d::finite) ell2)\\<close>\n  apply (rule equal_ket)\n  by (auto simp flip: tensor_ell2_ket simp: tensor_op_ell2)\n\nlemma bij_tensor_ell2_one_dim_left:\n  assumes \\<open>\\<psi> \\<noteq> 0\\<close>\n  shows \\<open>bij (\\<lambda>x::'b::finite ell2. (\\<psi> :: 'a::CARD_1 ell2) \\<otimes>\\<^sub>s x)\\<close>\nproof (rule bijI)\n  show \\<open>inj (\\<lambda>x::'b::finite ell2. (\\<psi> :: 'a::CARD_1 ell2) \\<otimes>\\<^sub>s x)\\<close>\n    using assms by (rule inj_tensor_ell2_right)\n  have \\<open>\\<exists>x. \\<psi> \\<otimes>\\<^sub>s x = \\<phi>\\<close> for \\<phi> :: \\<open>('a*'b) ell2\\<close>\n  proof (use assms in transfer)\n    fix \\<psi> :: \\<open>'a \\<Rightarrow> complex\\<close> and \\<phi> :: \\<open>'a*'b \\<Rightarrow> complex\\<close>\n    assume \\<open>has_ell2_norm \\<phi>\\<close> and \\<open>\\<psi> \\<noteq> (\\<lambda>_. 0)\\<close>\n    define c where \\<open>c = \\<psi> undefined\\<close>\n    then have \\<open>\\<psi> a = c\\<close> for a \n      apply (subst everything_the_same[of _ undefined])\n      by simp\n    with \\<open>\\<psi> \\<noteq> (\\<lambda>_. 0)\\<close> have \\<open>c \\<noteq> 0\\<close>\n      by auto\n\n    define x where \\<open>x j = \\<phi> (undefined, j) / c\\<close> for j\n    have \\<open>(\\<lambda>(i, j). \\<psi> i * x j) = \\<phi>\\<close>\n      apply (auto intro!: ext simp: x_def \\<open>\\<psi> _ = c\\<close> \\<open>c \\<noteq> 0\\<close>)\n      apply (subst (2) everything_the_same[of _ undefined])\n      by simp\n    then show \\<open>\\<exists>x\\<in>Collect has_ell2_norm. (\\<lambda>(i, j). \\<psi> i * x j) = \\<phi>\\<close>\n      apply (rule bexI[where x=x])\n      by simp\n  qed\n\n  then show \\<open>surj (\\<lambda>x::'b::finite ell2. (\\<psi> :: 'a::CARD_1 ell2) \\<otimes>\\<^sub>s x)\\<close>\n    by (metis surj_def)\nqed\n\nlemma bij_tensor_op_one_dim_left:\n  assumes \\<open>a \\<noteq> 0\\<close>\n  shows \\<open>bij (\\<lambda>x::'c::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2. (a :: 'a::{CARD_1,enum} ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::{CARD_1,enum} ell2) \\<otimes>\\<^sub>o x)\\<close>\nproof (rule bijI)\n  define t where \\<open>t = (\\<lambda>x::'c ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd ell2. (a :: 'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b ell2) \\<otimes>\\<^sub>o x)\\<close>\n  define i where\n    \\<open>i = tensor_lift (\\<lambda>(x::'a ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b ell2) (y::'c ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd ell2). (one_dim_iso x / one_dim_iso a) *\\<^sub>C y)\\<close>\n\n  have [simp]: \\<open>clinear i\\<close>\n    by (auto intro!: tensor_lift_clinear simp: i_def cbilinear_def clinearI scaleC_add_left add_divide_distrib)\n  have [simp]: \\<open>clinear t\\<close>\n    by (simp add: t_def)\n  have \\<open>i (x \\<otimes>\\<^sub>o y) = (one_dim_iso x / one_dim_iso a) *\\<^sub>C y\\<close> for x y\n    by (auto intro!: clinearI tensor_lift_correct[THEN fun_cong, THEN fun_cong] simp: t_def i_def cbilinear_def  scaleC_add_left add_divide_distrib)\n  then have \\<open>t (i (x \\<otimes>\\<^sub>o y)) = x \\<otimes>\\<^sub>o y\\<close> for x y\n    apply (simp add: t_def)\n    by (smt (z3) assms complex_vector.scale_eq_0_iff nonzero_mult_div_cancel_right one_dim_scaleC_1 scaleC_scaleC tensor_op_scaleC_left tensor_op_scaleC_right times_divide_eq_left)\n  then have \\<open>t (i x) = x\\<close> for x\n    apply (rule_tac fun_cong[where x=x])\n    apply (rule tensor_extensionality)\n    by (auto intro: clinear_compose complex_vector.module_hom_ident simp flip: o_def[of t i])\n  then show \\<open>surj t\\<close> \n    by (rule surjI)\n\n  show \\<open>inj t\\<close>\n    unfolding t_def using assms by (rule inj_tensor_right)\nqed\n\nlemma swap_ell2_selfinv[simp]: \\<open>swap_ell2 o\\<^sub>C\\<^sub>L swap_ell2 = id_cblinfun\\<close>\n  apply (rule tensor_ell2_extensionality)\n  by auto\n\nlemma bij_tensor_op_one_dim_right:\n  assumes \\<open>b \\<noteq> 0\\<close>\n  shows \\<open>bij (\\<lambda>x::'c::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2. x \\<otimes>\\<^sub>o (b :: 'a::{CARD_1,enum} ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::{CARD_1,enum} ell2))\\<close>\n    (is \\<open>bij ?f\\<close>)\nproof -\n  let ?sf = \\<open>(\\<lambda>x. swap_ell2 o\\<^sub>C\\<^sub>L (?f x) o\\<^sub>C\\<^sub>L swap_ell2)\\<close>\n  let ?s = \\<open>(\\<lambda>x. swap_ell2 o\\<^sub>C\\<^sub>L x o\\<^sub>C\\<^sub>L swap_ell2)\\<close>\n  let ?g = \\<open>(\\<lambda>x::'c::finite ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'd::finite ell2. (b :: 'a::{CARD_1,enum} ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b::{CARD_1,enum} ell2) \\<otimes>\\<^sub>o x)\\<close>\n  have \\<open>?sf = ?g\\<close>\n    by (auto intro!: ext tensor_ell2_extensionality simp add: swap_ell2_tensor tensor_op_ell2)\n  have \\<open>bij ?g\\<close>\n    using assms by (rule bij_tensor_op_one_dim_left)\n  have \\<open>?s o ?sf = ?f\\<close>\n    apply (auto intro!: ext simp: cblinfun_assoc_left)\n    by (auto simp: cblinfun_assoc_right)\n  also have \\<open>bij ?s\\<close>\n    apply (rule o_bij[where g=\\<open>(\\<lambda>x. swap_ell2 o\\<^sub>C\\<^sub>L x o\\<^sub>C\\<^sub>L swap_ell2)\\<close>])\n     apply (auto intro!: ext simp: cblinfun_assoc_left)\n    by (auto simp: cblinfun_assoc_right)\n  show \\<open>bij ?f\\<close>\n    apply (subst \\<open>?s o ?sf = ?f\\<close>[symmetric], subst \\<open>?sf = ?g\\<close>)\n    using \\<open>bij ?g\\<close> \\<open>bij ?s\\<close> by (rule bij_comp)\nqed\n\nlemma overlapping_tensor:\n  fixes a23 :: \\<open>('a2::finite*'a3::finite) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('b2::finite*'b3::finite) ell2\\<close>\n    and b12 :: \\<open>('a1::finite*'a2) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L ('b1::finite*'b2) ell2\\<close>\n  assumes eq: \\<open>butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o a23 = assoc_ell2 o\\<^sub>C\\<^sub>L (b12 \\<otimes>\\<^sub>o butterfly \\<phi> \\<phi>') o\\<^sub>C\\<^sub>L assoc_ell2'\\<close>\n  assumes \\<open>\\<psi> \\<noteq> 0\\<close> \\<open>\\<psi>' \\<noteq> 0\\<close> \\<open>\\<phi> \\<noteq> 0\\<close> \\<open>\\<phi>' \\<noteq> 0\\<close>\n  shows \\<open>\\<exists>c. butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o a23 = butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o c \\<otimes>\\<^sub>o butterfly \\<phi> \\<phi>'\\<close>\nproof -\n  note [[show_types]]\n  let ?id1 = \\<open>id_cblinfun :: unit ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L unit ell2\\<close>\n  note id_cblinfun_eq_1[simp del]\n  define d where \\<open>d = butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o a23\\<close>\n\n  define \\<psi>\\<^sub>n \\<psi>\\<^sub>n' a23\\<^sub>n where \\<open>\\<psi>\\<^sub>n = \\<psi> /\\<^sub>C norm \\<psi>\\<close> and \\<open>\\<psi>\\<^sub>n' = \\<psi>' /\\<^sub>C norm \\<psi>'\\<close> and \\<open>a23\\<^sub>n = norm \\<psi> *\\<^sub>C norm \\<psi>' *\\<^sub>C a23\\<close>\n  have [simp]: \\<open>norm \\<psi>\\<^sub>n = 1\\<close> \\<open>norm \\<psi>\\<^sub>n' = 1\\<close>\n    using \\<open>\\<psi> \\<noteq> 0\\<close> \\<open>\\<psi>' \\<noteq> 0\\<close> by (auto simp: \\<psi>\\<^sub>n_def \\<psi>\\<^sub>n'_def norm_inverse)\n  have n1: \\<open>butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o a23\\<^sub>n = butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o a23\\<close>\n    apply (auto simp: \\<psi>\\<^sub>n_def \\<psi>\\<^sub>n'_def a23\\<^sub>n_def tensor_op_scaleC_left tensor_op_scaleC_right)\n    by (metis (no_types, lifting) assms(2) assms(3) inverse_mult_distrib mult.commute no_zero_divisors norm_eq_zero of_real_eq_0_iff right_inverse scaleC_one)\n\n  define \\<phi>\\<^sub>n \\<phi>\\<^sub>n' b12\\<^sub>n where \\<open>\\<phi>\\<^sub>n = \\<phi> /\\<^sub>C norm \\<phi>\\<close> and \\<open>\\<phi>\\<^sub>n' = \\<phi>' /\\<^sub>C norm \\<phi>'\\<close> and \\<open>b12\\<^sub>n = norm \\<phi> *\\<^sub>C norm \\<phi>' *\\<^sub>C b12\\<close>\n  have [simp]: \\<open>norm \\<phi>\\<^sub>n = 1\\<close> \\<open>norm \\<phi>\\<^sub>n' = 1\\<close>\n    using \\<open>\\<phi> \\<noteq> 0\\<close> \\<open>\\<phi>' \\<noteq> 0\\<close> by (auto simp: \\<phi>\\<^sub>n_def \\<phi>\\<^sub>n'_def norm_inverse)\n  have n2: \\<open>b12\\<^sub>n \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n' = b12 \\<otimes>\\<^sub>o butterfly \\<phi> \\<phi>'\\<close>\n    apply (auto simp: \\<phi>\\<^sub>n_def \\<phi>\\<^sub>n'_def b12\\<^sub>n_def tensor_op_scaleC_left tensor_op_scaleC_right)\n    by (metis (no_types, lifting) assms(4) assms(5) field_class.field_inverse inverse_mult_distrib mult.commute no_zero_divisors norm_eq_zero of_real_hom.hom_0 scaleC_one)\n\n  define c' :: \\<open>(unit*'a2*unit) ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L (unit*'b2*unit) ell2\\<close> \n    where \\<open>c' = (vector_to_cblinfun \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun \\<otimes>\\<^sub>o vector_to_cblinfun \\<phi>\\<^sub>n)* o\\<^sub>C\\<^sub>L d\n            o\\<^sub>C\\<^sub>L (vector_to_cblinfun \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun \\<otimes>\\<^sub>o vector_to_cblinfun \\<phi>\\<^sub>n')\\<close>\n\n  define c'' :: \\<open>'a2 ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b2 ell2\\<close>\n    where \\<open>c'' = inv (\\<lambda>c''. id_cblinfun \\<otimes>\\<^sub>o c'' \\<otimes>\\<^sub>o id_cblinfun) c'\\<close>\n\n  have *: \\<open>bij (\\<lambda>c''::'a2 ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b2 ell2. ?id1 \\<otimes>\\<^sub>o c'' \\<otimes>\\<^sub>o ?id1)\\<close>\n    apply (subst asm_rl[of \\<open>_ = (\\<lambda>x. id_cblinfun \\<otimes>\\<^sub>o x) o (\\<lambda>c''. c'' \\<otimes>\\<^sub>o id_cblinfun)\\<close>])\n    using [[show_consts]]\n    by (auto intro!: bij_comp bij_tensor_op_one_dim_left bij_tensor_op_one_dim_right)\n\n  have c'_c'': \\<open>c' = ?id1 \\<otimes>\\<^sub>o c'' \\<otimes>\\<^sub>o ?id1\\<close>\n    unfolding c''_def \n    apply (rule surj_f_inv_f[where y=c', symmetric])\n    using * by (rule bij_is_surj)\n\n  define c :: \\<open>'a2 ell2 \\<Rightarrow>\\<^sub>C\\<^sub>L 'b2 ell2\\<close>\n    where \\<open>c = c'' /\\<^sub>C norm \\<psi> /\\<^sub>C norm \\<psi>' /\\<^sub>C norm \\<phi> /\\<^sub>C norm \\<phi>'\\<close>\n\n  have aux: \\<open>assoc_ell2' o\\<^sub>C\\<^sub>L (assoc_ell2 o\\<^sub>C\\<^sub>L x o\\<^sub>C\\<^sub>L assoc_ell2') o\\<^sub>C\\<^sub>L assoc_ell2 = x\\<close> for x\n    apply (simp add: cblinfun_assoc_left)\n    by (simp add: cblinfun_assoc_right)\n  have aux2: \\<open>(assoc_ell2 o\\<^sub>C\\<^sub>L ((x \\<otimes>\\<^sub>o y) \\<otimes>\\<^sub>o z) o\\<^sub>C\\<^sub>L assoc_ell2') = x \\<otimes>\\<^sub>o (y \\<otimes>\\<^sub>o z)\\<close> for x y z\n    apply (rule equal_ket, rename_tac xyz)\n    apply (case_tac xyz, hypsubst_thin)\n    by (simp flip: tensor_ell2_ket add: assoc_ell2'_tensor assoc_ell2_tensor tensor_op_ell2)\n\n  have \\<open>d = (butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun) o\\<^sub>C\\<^sub>L d o\\<^sub>C\\<^sub>L (butterfly \\<psi>\\<^sub>n' \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun)\\<close>\n    by (auto simp: d_def n1[symmetric] comp_tensor_op cnorm_eq_1[THEN iffD1])\n  also have \\<open>\\<dots> = (butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun) o\\<^sub>C\\<^sub>L assoc_ell2 o\\<^sub>C\\<^sub>L (b12\\<^sub>n \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n')\n                  o\\<^sub>C\\<^sub>L assoc_ell2' o\\<^sub>C\\<^sub>L (butterfly \\<psi>\\<^sub>n' \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun)\\<close>\n    by (auto simp: d_def eq n2 cblinfun_assoc_left)\n  also have \\<open>\\<dots> = (butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun) o\\<^sub>C\\<^sub>L assoc_ell2 o\\<^sub>C\\<^sub>L \n               ((id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n) o\\<^sub>C\\<^sub>L (b12\\<^sub>n \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n') o\\<^sub>C\\<^sub>L (id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n' \\<phi>\\<^sub>n'))\n               o\\<^sub>C\\<^sub>L assoc_ell2' o\\<^sub>C\\<^sub>L (butterfly \\<psi>\\<^sub>n' \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun)\\<close>\n    by (auto simp: comp_tensor_op cnorm_eq_1[THEN iffD1])\n  also have \\<open>\\<dots> = (butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun) o\\<^sub>C\\<^sub>L assoc_ell2 o\\<^sub>C\\<^sub>L \n               ((id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n) o\\<^sub>C\\<^sub>L (assoc_ell2' o\\<^sub>C\\<^sub>L d o\\<^sub>C\\<^sub>L assoc_ell2) o\\<^sub>C\\<^sub>L (id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n' \\<phi>\\<^sub>n'))\n               o\\<^sub>C\\<^sub>L assoc_ell2' o\\<^sub>C\\<^sub>L (butterfly \\<psi>\\<^sub>n' \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun)\\<close>\n    by (auto simp: d_def n2 eq aux)\n  also have \\<open>\\<dots> = ((butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun) o\\<^sub>C\\<^sub>L (assoc_ell2 o\\<^sub>C\\<^sub>L (id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n) o\\<^sub>C\\<^sub>L assoc_ell2'))\n               o\\<^sub>C\\<^sub>L d o\\<^sub>C\\<^sub>L ((assoc_ell2 o\\<^sub>C\\<^sub>L (id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n' \\<phi>\\<^sub>n') o\\<^sub>C\\<^sub>L assoc_ell2') o\\<^sub>C\\<^sub>L (butterfly \\<psi>\\<^sub>n' \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun))\\<close>\n    by (auto simp: sandwich_def cblinfun_assoc_left)\n  also have \\<open>\\<dots> = (butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n)\n               o\\<^sub>C\\<^sub>L d o\\<^sub>C\\<^sub>L (butterfly \\<psi>\\<^sub>n' \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n' \\<phi>\\<^sub>n')\\<close>\n    apply (simp only: tensor_id[symmetric] comp_tensor_op aux2)\n    by (simp add: cnorm_eq_1[THEN iffD1])\n  also have \\<open>\\<dots> = (vector_to_cblinfun \\<psi>\\<^sub>n \\<otimes>\\<^sub>o id_cblinfun \\<otimes>\\<^sub>o vector_to_cblinfun \\<phi>\\<^sub>n)\n               o\\<^sub>C\\<^sub>L c' o\\<^sub>C\\<^sub>L (vector_to_cblinfun \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o id_cblinfun \\<otimes>\\<^sub>o vector_to_cblinfun \\<phi>\\<^sub>n')*\\<close>\n    apply (simp add: c'_def butterfly_def_one_dim[where 'c=\"unit ell2\"] cblinfun_assoc_left comp_tensor_op\n                      tensor_op_adjoint cnorm_eq_1[THEN iffD1])\n    by (simp add: cblinfun_assoc_right comp_tensor_op)\n  also have \\<open>\\<dots> = butterfly \\<psi>\\<^sub>n \\<psi>\\<^sub>n' \\<otimes>\\<^sub>o c'' \\<otimes>\\<^sub>o butterfly \\<phi>\\<^sub>n \\<phi>\\<^sub>n'\\<close>\n    by (simp add: c'_c'' comp_tensor_op tensor_op_adjoint butterfly_def_one_dim[symmetric])\n  also have \\<open>\\<dots> = butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o c \\<otimes>\\<^sub>o butterfly \\<phi> \\<phi>'\\<close>\n    by (simp add: \\<psi>\\<^sub>n_def \\<psi>\\<^sub>n'_def \\<phi>\\<^sub>n_def \\<phi>\\<^sub>n'_def c_def tensor_op_scaleC_left tensor_op_scaleC_right)\n  finally have d_c: \\<open>d = butterfly \\<psi> \\<psi>' \\<otimes>\\<^sub>o c \\<otimes>\\<^sub>o butterfly \\<phi> \\<phi>'\\<close>\n    by -\n  then show ?thesis\n    by (auto simp: d_def)\nqed\n\nlemma norm_tensor_ell2: \\<open>norm (a \\<otimes>\\<^sub>s b) = norm a * norm b\\<close>\n  apply transfer\n  by (simp add: ell2_norm_finite sum_product sum.cartesian_product case_prod_beta\n      norm_mult power_mult_distrib flip: real_sqrt_mult)\n\nlemma bounded_cbilinear_tensor_ell2[bounded_cbilinear]: \\<open>bounded_cbilinear (\\<otimes>\\<^sub>s)\\<close>\nproof standard\n  fix a a' :: \"'a ell2\" and b b' :: \"'b ell2\" and r :: complex\n  show \\<open>tensor_ell2 (a + a') b = tensor_ell2 a b + tensor_ell2 a' b\\<close>\n    by (meson tensor_ell2_add1)\n  show \\<open>tensor_ell2 a (b + b') = tensor_ell2 a b + tensor_ell2 a b'\\<close>\n    by (simp add: tensor_ell2_add2)  \n  show \\<open>tensor_ell2 (r *\\<^sub>C a) b = r *\\<^sub>C tensor_ell2 a b\\<close>\n    by (simp add: tensor_ell2_scaleC1)\n  show \\<open>tensor_ell2 a (r *\\<^sub>C b) = r *\\<^sub>C tensor_ell2 a b\\<close>\n    by (simp add: tensor_ell2_scaleC2)\n  show \\<open>\\<exists>K. \\<forall>a b. norm (tensor_ell2 a b) \\<le> norm a * norm b * K \\<close>\n    apply (rule exI[of _ 1])\n    by (simp add: norm_tensor_ell2)\nqed\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Registers/Finite_Tensor_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.765353664377959}}
{"text": "theory Listas\nimports Main\nbegin\n\nsection \"El tipo de las listas\"\n\ntext {* ('a list) es el tipo de las listas con elementos de tipo 'a *}\ndatatype 'a lista = Nil | Cons \"'a\" \"'a lista\"\n\ntext {* Ejemplos de inferencia de tipo. *}\nterm \"Nil\"        \n  (* da \"lista.Nil\" :: \"'a lista\" *)\nterm \"Cons 1 Nil\" \n  (* da \"lista.Cons 1 lista.Nil\" :: \"'a lista\" *)\n\ntext {* Declaración para acortar los nombres. *}\ndeclare [[names_short]]\n\ntext {* Ejemplos de inferencia de tipo con nombres acortados. *}\nterm \"Nil\"        \n  (* da \"Nil\" :: \"'a lista\" *)\nterm \"Cons 1 Nil\" \n  (* da \"Cons 1 lista.Nil\" :: \"'a lista\" *)\n\nsection \"Funciones sobre listas: conc e inversa\"\n\ntext {* (conc xs ys) es la concatenación de las listas xs e ys. Por\n  ejemplo,   \n     conc (Cons a (Cons b Nil)) (Cons c (Cons d Nil))\n     = Cons a (Cons b (Cons c (Cons d Nil)))\n*}\nfun conc :: \"'a lista \\<Rightarrow> 'a lista \\<Rightarrow> 'a lista\" \nwhere\n  \"conc Nil ys         = ys\" \n| \"conc (Cons x xs) ys = Cons x (conc xs ys)\"\n\nvalue \"conc (Cons a (Cons b Nil)) (Cons c (Cons d Nil))\"\nlemma \"conc (Cons a (Cons b Nil)) (Cons c (Cons d Nil))\n       = Cons a (Cons b (Cons c (Cons d Nil)))\" by simp\n       \ntext {* (inversa xs) es la inversa de la lista xs. Por ejemplo,  \n*}\nfun inversa :: \"'a lista \\<Rightarrow> 'a lista\" \nwhere\n  \"inversa Nil         = Nil\" \n| \"inversa (Cons x xs) = conc (inversa xs) (Cons x Nil)\"\n\nvalue \"inversa (Cons a (Cons b (Cons c Nil)))\"\nlemma \"inversa (Cons a (Cons b (Cons c Nil)))\n       = Cons c (Cons b (Cons a Nil))\" by simp\n\nexport_code inversa in Haskell\n(* El resultado es\n  module Listas (Lista, inversa) where {\n\n  import Prelude ((==), ...\n  import qualified Prelude;\n\n  data Lista a = Nil | Cons a (Lista a);\n\n  conc :: forall a. Lista a -> Lista a -> Lista a;\n  conc Nil ys = ys;\n  conc (Cons x xs) ys = Cons x (conc xs ys);\n\n  inversa :: forall a. Lista a -> Lista a;\n  inversa Nil = Nil;\n  inversa (Cons x xs) = conc (inversa xs) (Cons x Nil);\n}\n*)\n       \nsection \"Ejemplo de búsqueda descendente de la demostración\"\n\ntext {* El objetivo de esta sección es mostrar cómo se conjeturan lemas\n  auxiliares para la demostración de la idempotencia de la función\n  inversa.\n  \n  Se mostrarán cómo los errores de las pruebas ayudan a conjeturar los\n  lemas.\n*}\n       \ntext {* Primer intento de prueba de inversa_inversa. *}\ntheorem inversa_inversa_1: \n  \"inversa (inversa xs) = xs\"\napply (induction xs)\napply auto\noops\n\ntext {* Queda sin demostrar el siguiente objetivo:\n     inversa (inversa xs) = xs \\<Longrightarrow> \n     inversa (conc (inversa xs) (Cons x1 Nil)) = Cons x1 xs\n            \n  Se observa que contiene la expresión \n     inversa (conc (inversa xs) (Cons x1 Nil))\n  que se puede simplificar a \n     conc (Cons x1 Nil) (inversa (inversa xs)) \n  con el siguiente lema:\n     inversa (conc xs ys) = conc (inversa ys) (inversa xs)\n*}\n\ntext {* Primer intento de prueba de inversa_conc. *}\nlemma inversa_conc_1: \n  \"inversa (conc xs ys) = conc (inversa ys) (inversa xs)\"\napply (induction xs)\napply auto\noops\n\ntext {* Queda sin demostrar el objetivo\n     inversa ys = conc (inversa ys) Nil\n  Se puede demostrar con el siguiente lema\n     conc xs Nil = xs\n*}\n\ntext {* Prueba de conc_Nil2. *}\nlemma conc_Nil2: \n  \"conc xs Nil = xs\"\napply (induction xs)\napply auto\ndone\n\ntext {* Segundo intento de prueba de inversa_conc usando conc_Nil2. *}\nlemma inversa_conc_2: \n  \"inversa (conc xs ys) = conc (inversa ys) (inversa xs)\"\napply (induction xs)\napply (auto simp add: conc_Nil2)\noops\n\ntext {* Queda sin probar el objetivo\n     inversa (conc xs ys) = conc (inversa ys) (inversa xs) \\<Longrightarrow>\n       conc (conc (inversa ys) (inversa xs)) (Cons x1 Nil) =\n       conc (inversa ys) (conc (inversa xs) (Cons x1 Nil))\n  que se puede simplificar usando la propiedad asociativa de conc.       \n*}\n\ntext {* Prueba de asociatividad de conc. *}\nlemma conc_asoc: \n  \"conc (conc xs ys) zs = conc xs (conc ys zs)\"\napply (induction xs)\napply auto\ndone\n\ntext {* Prueba de inversa_conc usando conc_Nil2 y conc_asoc. *}\nlemma inversa_conc: \n  \"inversa (conc xs ys) = conc (inversa ys) (inversa xs)\"\napply (induction xs)\napply (auto simp add: conc_Nil2 conc_asoc)\ndone\n\ntext {* Prueba de inversa_inversa usando inversa_conc. *}\ntheorem inversa_inversa: \n  \"inversa (inversa xs) = xs\"\napply (induction xs)\napply (auto simp add: inversa_conc)\ndone\n\ntext {* Una vez encontrada la demostración, se puede modificar la\n  presentación declarando los lemas como reglas de simplificación, como\n  se muestra a continuación. *} \n\nlemma conc_Nil2' [simp]: \n  \"conc xs Nil = xs\"\nby (induction xs) auto\n\nlemma conc_asoc' [simp]: \n  \"conc (conc xs ys) zs = conc xs (conc ys zs)\"\nby (induction xs) auto\n\nlemma inversa_conc' [simp]: \n  \"inversa (conc xs ys) = conc (inversa ys) (inversa xs)\"\nby (induction xs) auto\n\ntheorem inversa_inversa': \n  \"inversa (inversa xs) = xs\"\nby (induction xs) auto\n\nsection \"Ejemplo de cálculo con listas\"\n\nvalue \"a # [b,c]\"\n  (* da \"[a, b, c]\" *)  \nvalue \"hd [a,b,c]\"\n  (* da \"a\" *)\nvalue \"tl [a,b,c]\"\n  (* da \"[b, c]\" *)\nvalue \"set [b,a,c]\"\n  (* da \"{b, a, c}\" :: \"'a set\" *)\nvalue \"set [b,a,c] = set [c,a,b,a,c]\"\n  (* da \"True\" *)\nvalue \"map f [a,b,c]\"\n  (* da \"[f a, f b, f c]\" *)\nvalue \"last [a,b,c]\"\n  (* da \"c\" *)\nvalue \"butlast [a,b,c]\"\n  (* da  \"[a, b]\" *)\nvalue \"[a,b] @ [c,a,d]\"\n  (* da \"[a, b, c, a, d]\" *)\nvalue \"rev [a,b,c,d]\"\n  (* da \"[d, c, b, a]\" *)\nvalue \"filter (op > (Suc (Suc 0))) [0,Suc 0, Suc (Suc (Suc 0)), 0]\"\n  (* da \"[0, Suc 0, 0]\" *)\nvalue \"filter (\\<lambda>n::nat. n<2) [0,2,1] = [0,1]\"\n  (* da \"True\" *)\nvalue \"fold f [a,b,c] x\" \n  (* da \"f c (f b (f a x))\" *)\nvalue \"fold (op +) [Suc 0, Suc (Suc 0), Suc 0] 0\"\n  (* da \"Suc (Suc (Suc (Suc 0)))\" *)  \nvalue \"foldr f [a,b,c] x\"\n  (* da \"f a (f b (f c x))\" *)\nvalue \"foldr (op -) [Suc (Suc (Suc 0)), Suc 0, Suc 0] 0\"\n  (* da \"\"Suc (Suc (Suc 0))\" *)  \nvalue \"foldl f x [a,b,c]\"\n  (* da \"f (f (f x a) b) c\" *)\nvalue \"foldl (op -) 0 [Suc (Suc (Suc 0)), Suc 0, Suc 0]\"\n  (* da \"0\" *)  \nvalue \"concat [[a,b],[c],[d,a,c]]\"\n  (* da \"[a, b, c, d, a, c]\" *)\nvalue \"drop 2 [a,b,c,d]\"\n  (* da \"[c, d]\" *)\nvalue \"drop 6 [a,b,c,d]\"\n  (* da \"[]\" *)\nvalue \"take 2 [a,b,c,d]\"\n  (* da \"[a, b]\" *)\nvalue \"take 6 [a,b,c,d]\"\n  (* da \"[a, b, c, d]\" *)\nvalue \"nth [a,b,c,d] (Suc (Suc 0))\"\n  (* da \"c\" *)\nvalue \"list_update [a,b,c,d] (Suc (Suc 0)) g\"\n  (* da \"[a, b, g, d]\" *)\nvalue \"[a,b,c,d][Suc (Suc 0) := g]\"\n  (* da \"[a, b, g, d]\" *)\nvalue \"takeWhile (op > (Suc (Suc 0))) [0,Suc 0, Suc (Suc (Suc 0)), 0]\"\n  (* da \"[0, Suc 0]\" *)\nvalue \"dropWhile (op > (Suc (Suc 0))) [0,Suc 0, Suc (Suc (Suc 0)), 0]\"\n  (* da \"[Suc (Suc (Suc 0)), 0]\" *)\nvalue \"zip [a,b,c] [d,e,f,g]\"\n  (* da \"[(a, d), (b, e), (c, f)]\" *)\nvalue \"List.product [a,b] [c,d]\" \n  (* da \"[(a, c), (a, d), (b, c), (b, d)]\" *)\nvalue \"product_lists [[a,b], [c], [d,e]]\"\n  (* da \"[[a, c, d], [a, c, e], [b, c, d], [b, c, e]]\" *)\nvalue \"List.insert (Suc 0) [0,Suc (Suc 0)]\"\n  (* da \"[Suc 0, 0, Suc (Suc 0)]\" *)\nvalue \"List.insert (Suc (Suc 0)) [0,Suc (Suc 0)]\"\n  (* da \"[0, Suc (Suc 0)]\" *)\nvalue \"List.union [0,Suc 0] [0,Suc (Suc 0)]\"\n  (* da \"[Suc 0, 0, Suc (Suc 0)]\" *)\nvalue \"find (op = (Suc 0)) [0,Suc 0, Suc (Suc (Suc 0)), 0]\"\n  (* da \"Some (Suc 0)\" *)\nvalue \"find (op = (Suc (Suc 0))) [0,Suc 0, Suc (Suc (Suc 0)), 0]\"\n  (* da \"None\" *)\nvalue \"count_list [0,Suc 0,0, Suc (Suc 0), 0] 0\"\n  (* da \"Suc (Suc (Suc 0))\" *)\nvalue \"remove1 0 [Suc 0, 0, Suc (Suc 0), 0]\"\n  (* da \"[Suc 0, Suc (Suc 0), 0]\" *)\nvalue \"removeAll 0 [Suc 0, 0, Suc (Suc 0), 0]\"\n  (* da \"[Suc 0, Suc (Suc 0)]\" *)\nvalue \"distinct [1::nat,2,3]\"\n  (* da \"True\" *)\nvalue \"distinct [1::nat,2,1]\"\n  (* da \"False\" *)\nvalue \"remdups [1::nat,2,1]\"\n  (* da \"[Suc (Suc 0), Suc 0]\" *)\nvalue \"replicate 3 a\"\n  (* da \"[a, a, a]\" *)\nvalue \"length [a,b,c]\"\n  (* da \"Suc (Suc (Suc 0))\" :: nat*)\nvalue \"int (length [a,b,c])\"\n  (* da \"3\" :: int *)\nvalue \"int (size [a,b,c])\"\n  (* da \"3\" :: int *)\nvalue \"enumerate 0 [b,a,c]\"\n  (* da \"[(0, b), (Suc 0, a), (Suc (Suc 0), c)]\" *)\nvalue \"enumerate 1 [b,a,c]\"\n  (* da \"[(Suc 0, b), (Suc (Suc 0), a), (Suc (Suc (Suc 0)), c)]\" *)\nvalue \"[1..<4]\"\n  (* da  \"[Suc 0, Suc (Suc 0), Suc (Suc (Suc 0))]\" *)\nvalue \"rotate1 [a,b,c]\"\n  (* da \"[b, c, a]\" *)\nvalue \"rotate1 [b,c,a]\"\n  (* da \"[c, a, b]\" *)\nvalue \"(rotate1 ^^ 2) [a,b,c]\"\n  (* da \"[c, a, b]\" *)\nvalue \"rotate 2 [a,b,c]\"\n  (* da \"[c, a, b]\" *)\nvalue \"sublists [a,b,c]\"\n  (* da \"[[a, b, c], [a, b], [a, c], [a], [b, c], [b], [c], []]\" *)\nvalue \"splice [a,b,c] [x,y,z]\"\n  (* da \"[a, x, b, y, c, z]\" *)\nvalue \"splice [a,b,c,d] [x,y]\"\n  (* da \"[a, x, b, y, c, d]\" *)\nvalue \"List.n_lists 2 [a,b,c]\"\n  (* da [[a,a], [b,a], [c,a], [a,b], [b,b], [c,b], [a,c], [b,c], [c,c]]\" *)\nvalue \"sort [Suc 0, 0, Suc (Suc 0)]\"\n  (* da \"[0, Suc 0, Suc (Suc 0)]\" *)\n  \nend\n", "meta": {"author": "jaalonso", "repo": "SLP", "sha": "799e829200ea0a4fbb526f47356135d98a190864", "save_path": "github-repos/isabelle/jaalonso-SLP", "path": "github-repos/isabelle/jaalonso-SLP/SLP-799e829200ea0a4fbb526f47356135d98a190864/Temas/Ejemplos/Listas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.8902942159342104, "lm_q1q2_score": 0.7653536583253411}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_HSortIsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Heap = Node \"Heap\" \"Nat\" \"Heap\" | Nil\n\nfun toHeap :: \"Nat list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun insert :: \"Nat => Nat list => Nat list\" where\n  \"insert x (nil2) = cons2 x (nil2)\"\n| \"insert x (cons2 z xs) =\n     (if le x z then cons2 x (cons2 z xs) else cons2 z (insert x xs))\"\n\nfun isort :: \"Nat list => Nat list\" where\n  \"isort (nil2) = nil2\"\n| \"isort (cons2 y xs) = insert y (isort xs)\"\n\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if le x2 x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else\n      Node (hmerge (Node z x2 x3) x6) x5 x4)\"\n| \"hmerge (Node z x2 x3) (Nil) = Node z x2 x3\"\n| \"hmerge (Nil) y = y\"\n\nfun hpairwise :: \"Heap list => Heap list\" where\n  \"hpairwise (nil2) = nil2\"\n| \"hpairwise (cons2 q (nil2)) = cons2 q (nil2)\"\n| \"hpairwise (cons2 q (cons2 r qs)) =\n     cons2 (hmerge q r) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 q (nil2)) = q\"\n| \"hmerging (cons2 q (cons2 z x2)) =\n     hmerging (hpairwise (cons2 q (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"Nat list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => Nat list\" where\n  \"toList (Node q y r) = cons2 y (toList (hmerge q r))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"Nat list => Nat list\" where\n  \"hsort x = toList (toHeap2 x)\"\n\ntheorem property0 :\n  \"((hsort xs) = (isort xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_HSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7653136963915487}}
{"text": "\ntext \\<open>Stuff about triangle numbers, in particular triangular root \\<close>\n\ntheory Triangle_Extensions\n  imports \"Poly_Reductions_Lib.Landau_Auxiliaries\"\nbegin\n\nlemma triangle_Sum: \"triangle n = (\\<Sum>x\\<in>{1..n}. x)\"\n  by (induction n) (auto simp add: triangle_def)\n\n(* Proofs in here are ugly, look at again, I also do quite a lot by just doing it on reals and transfering back *)\n\n(* Stuff for moving to the reals *)\nlemma sqrt_power2_iff_eq: \"x \\<ge> 0 \\<Longrightarrow> y\\<ge>0\\<Longrightarrow> sqrt x = y \\<longleftrightarrow> x = y^2\" by auto\n\nlemma triangle_invert_real: \"n\\<ge>0 \\<Longrightarrow> (sqrt (8*(n*(n+1) / 2)+1) - 1) / 2 = n\"\nproof-\n  have s: \"(8*(n*(n+1) / 2)+1) = (2 * n + 1)^2\" if \"n\\<ge>0\"\n    using that by (auto simp add: power2_eq_square distrib_left mult.commute)\n  have \"sqrt (8*(n*(n+1) / 2)+1) = 2*n + 1\" if \"n\\<ge>0\"\n    using that by (simp add: s sqrt_power2_iff_eq) algebra\n  then show ?thesis if \"n\\<ge>0\"\n    using that by auto \nqed\n\nlemma sqrt_Discrete_sqrt: \"nat (floor (sqrt n)) = Discrete.sqrt n\"\n  apply (rule antisym)\n  apply (rule le_sqrtI)\n  apply (smt (verit, ccfv_threshold) of_int_floor_le of_nat_0_le_iff of_nat_le_of_nat_power_cancel_iff\n      of_nat_nat real_less_lsqrt real_sqrt_ge_0_iff zero_le_floor)\n  apply (rule sqrt_leI)\n  by (simp add: le_nat_floor real_le_rsqrt)\n\nlemma divide2_div2: \"nat (floor (n/2)) = n div 2\"\n  by linarith\nlemma divide2_div2': \"nat (floor (n/2)) = nat (floor (n::real)) div 2\"\n  by linarith\n\nlemma triangular_part_real: \"nat (floor (((sqrt (8*n + 1)) -1) /2)) = (Discrete.sqrt (8*n + 1) -1) div 2\"\n  apply (simp add: divide2_div2' nat_diff_distrib')\n  by (metis add.commute of_nat_Suc of_nat_mult of_nat_numeral sqrt_Discrete_sqrt)\n\nlemma triangle_invert_real_typ: \"(sqrt (8*(n*(n+1) / 2)+1) - 1) / 2 = (n::nat)\"\n  using triangle_invert_real by simp\n\nlemma triangle_invert_real_typ': \"nat (floor ((sqrt (8*(n*(n+1) / 2)+1) - 1) / 2)) = (n::nat)\"\n  using triangle_invert_real by simp\n\ntext \\<open>Triangular root\\<close>\n\ndefinition \"tsqrt n \\<equiv> (Discrete.sqrt (8*n + 1) - 1) div 2\"\n\nlemma tsqrt_0[simp]: \"tsqrt 0 = 0\"\n  by code_simp\nlemma tsqrt_1[simp]: \"tsqrt 1 = 1\"\n  by code_simp\nlemma tsqrt_2[simp]: \"tsqrt 2 = 1\"\n  by code_simp\n\nlemma tsqrt_correct[simp]: \"tsqrt (triangle n) = n\"\nproof(unfold triangle_def tsqrt_def)\n  have s: \"real (n * Suc n div 2) = real n * (real n + 1) / 2\"\n    by (smt (verit, del_insts) Multiseries_Expansion.intyness_1 add.commute double_gauss_sum gauss_sum \n        id_apply nat_1_add_1 nonzero_mult_div_cancel_left of_nat_Suc of_nat_eq_id of_nat_mult plus_1_eq_Suc)\n  show \"(Discrete.sqrt (8 * (n * Suc n div 2) + 1) - 1) div 2 = n\"\n    apply (subst triangular_part_real[symmetric]) apply (subst s)\n    using triangle_invert_real_typ' by simp\nqed\n\nlemma mono_tsqrt: \"mono tsqrt\"\n  unfolding tsqrt_def\n  apply (rule monoI) \n  unfolding tsqrt_def \n  by simp (meson Suc_le_mono diff_le_mono div_le_mono le_less mono_sqrt' mult_le_mono)\n\nlemma mono_tsqrt': \"x\\<le>y \\<Longrightarrow> tsqrt x \\<le> tsqrt y\"\n  using mono_tsqrt by (drule monoD)\n\ntext \\<open>Alternative triangular root definition, based on how \\<^const>\\<open>Discrete.sqrt\\<close> is defined\n  Copied lemmas/proofs as well and modified them for some free properties. \n\n  General way of this construction might be a student project?\n\\<close>\n\ndefinition \"tsqrt_alt n \\<equiv> Max {m. triangle m \\<le> n}\"\n\nlemma tsqrt_alt_aux:\n  fixes n :: nat\n  shows \"finite {m. triangle m \\<le> n}\" and \"{m. triangle m \\<le> n} \\<noteq> {}\"\nproof -\n  { fix m\n    assume \"triangle m \\<le> n\"\n    then have \"m \\<le> n\"\n      by (cases m) (simp_all)\n  } note ** = this\n  then have \"{m. triangle m \\<le> n} \\<subseteq> {m. m \\<le> n}\" by auto\n  then show \"finite {m. triangle m \\<le> n}\" by (rule finite_subset) rule\n  have \"triangle 0 \\<le> n\" by simp\n  then show *: \"{m. triangle m \\<le> n} \\<noteq> {}\" by blast\nqed\n\nlemma tsqrt_alt_unique:\n  assumes \"triangle m \\<le> n\" \"n < triangle (Suc m)\"\n  shows   \"tsqrt_alt n = m\"\nproof -\n  have \"m' \\<le> m\" if \"triangle m' \\<le> n\" for m'\n  proof -\n    note that\n    also note assms(2)\n    finally have \"m' < Suc m\" (* Apparently I already have some connection to tsqrt here *)\n      by (metis le_neq_implies_less less_or_eq_imp_le mono_tsqrt' nat_neq_iff tsqrt_correct)\n    thus \"m' \\<le> m\" by simp\n  qed\n  with \\<open>triangle m \\<le> n\\<close> tsqrt_alt_aux[of n] show ?thesis unfolding tsqrt_alt_def\n    by (intro antisym Max.boundedI Max.coboundedI) simp_all\nqed\n\n\nlemma triangle_nat_le_imp_le:\n  fixes m n :: nat\n  assumes \"triangle m \\<le> n\"\n  shows \"m \\<le> n\"\nproof (cases m)\n  case 0\n  then show ?thesis \n    by simp\nnext\n  case (Suc nat)\n  then show ?thesis \n    using assms by auto\nqed\n\n(* Real proof *)\nlemma triangle_nat_le_eq_le: \"triangle m \\<le> triangle n \\<longleftrightarrow> m \\<le> n\"\n  for m n :: nat\n  by (metis linorder_le_cases mono_tsqrt' tsqrt_correct verit_la_disequality)\n\n(* basically linear search, delete this code equation once you have a better one *)\nlemma tsqrt_alt_code_1 [code]: \"tsqrt_alt n = Max (Set.filter (\\<lambda>m. triangle m \\<le> n) {0..n})\"\nproof -\n  from triangle_nat_le_imp_le [of _ n] have \"{m. m \\<le> n \\<and> triangle m \\<le> n} = {m. triangle m \\<le> n}\" by auto\n  then show ?thesis by (simp add: tsqrt_alt_def Set.filter_def)\nqed\n\nlemma tsqrt_alt_inverse_triangle [simp]: \"tsqrt_alt (triangle n) = n\"\nproof -\n  have \"{m. m \\<le> n} \\<noteq> {}\" by auto\n  then have \"Max {m. m \\<le> n} \\<le> n\" by auto\n  then show ?thesis\n    by (auto simp add: tsqrt_alt_def triangle_nat_le_eq_le intro: antisym)\nqed\n\nlemma tsqrt_alt_zero [simp]: \"tsqrt_alt 0 = 0\"\n  using tsqrt_alt_inverse_triangle [of 0] by simp\n\nlemma tsqrt_alt_one [simp]: \"tsqrt_alt 1 = 1\"\n  using tsqrt_alt_inverse_triangle [of 1] by simp\n\nlemma mono_tsqrt_alt: \"mono tsqrt_alt\"\nproof\n  fix m n :: nat\n  have *: \"0 * 0 \\<le> m\" by simp\n  assume \"m \\<le> n\"\n  then show \"tsqrt_alt m \\<le> tsqrt_alt n\"\n    apply (auto intro!: Max_mono \\<open>0 * 0 \\<le> m\\<close> finite_less_ub simp add: tsqrt_alt_def triangle_nat_le_imp_le)\n    apply (metis triangle_0 zero_le)\n    done\nqed\n\nlemma mono_tsqrt_alt_': \"m \\<le> n \\<Longrightarrow> tsqrt_alt m \\<le> tsqrt_alt n\"\n  using mono_tsqrt_alt unfolding mono_def by auto\n\nlemma tsqrt_alt_greater_zero_iff [simp]: \"tsqrt_alt n > 0 \\<longleftrightarrow> n > 0\"\nproof -\n  have *: \"0 < Max {m. triangle m \\<le> n} \\<longleftrightarrow> (\\<exists>a\\<in>{m. triangle m \\<le> n}. 0 < a)\"\n    by (rule Max_gr_iff) (fact tsqrt_alt_aux)+\n  show ?thesis\n  proof\n    assume \"0 < tsqrt_alt n\"\n    then have \"0 < Max {m. triangle m \\<le> n}\" by (simp add: tsqrt_alt_def)\n    with * show \"0 < n\" by (auto dest: triangle_nat_le_imp_le)\n  next\n    assume \"0 < n\"\n    then have \"triangle 1 \\<le> n \\<and> 0 < (1::nat)\" by simp\n    then have \"\\<exists>q. triangle q \\<le> n \\<and> 0 < q\" ..\n    with * have \"0 < Max {m. triangle m \\<le> n}\" by blast\n    then show \"0 < tsqrt_alt n\" by (simp add: tsqrt_alt_def)\n  qed\nqed\n\n(* No idea what this proof does, find out sometime :) *)\nlemma tsqrt_alt_triangle_le [simp]: \"triangle (tsqrt_alt n) \\<le> n\" (* FIXME tune proof *)\nproof (cases \"n > 0\")\n  case False then show ?thesis by simp\nnext\n  case True then have \"tsqrt_alt n > 0\" by simp\n  then have \"mono (times (Max {m. triangle m \\<le> n}))\" by (auto intro: mono_times_nat simp add: tsqrt_alt_def)\n  then have *: \"Max {m. triangle m \\<le> n} * Max {m. triangle m \\<le> n} = Max (times (Max {m. triangle m \\<le> n}) ` {m. triangle m \\<le> n})\"\n    using tsqrt_alt_aux [of n] by (rule mono_Max_commute)\n  have \"\\<And>a. a * a \\<le> n \\<Longrightarrow> Max {m. m * m \\<le> n} * a \\<le> n\"\n  proof -\n    fix q\n    assume \"q * q \\<le> n\"\n    show \"Max {m. m * m \\<le> n} * q \\<le> n\"\n    proof (cases \"q > 0\")\n      case False then show ?thesis by simp\n    next\n      case True then have \"mono (times q)\" by (rule mono_times_nat)\n      then have \"q * Max {m. m * m \\<le> n} = Max (times q ` {m. m * m \\<le> n})\"\n        using sqrt_aux [of n] by (auto simp add: power2_eq_square intro: mono_Max_commute)\n      then have \"Max {m. m * m \\<le> n} * q = Max (times q ` {m. m * m \\<le> n})\" by (simp add: ac_simps)\n      moreover have \"finite ((*) q ` {m. m * m \\<le> n})\"\n        by (metis (mono_tags) finite_imageI finite_less_ub le_square)\n      moreover have \"\\<exists>x. x * x \\<le> n\"\n        by (metis \\<open>q * q \\<le> n\\<close>)\n      ultimately show ?thesis\n        by simp (metis \\<open>q * q \\<le> n\\<close> le_cases mult_le_mono1 mult_le_mono2 order_trans)\n    qed\n  qed\n  then have \"Max ((*) (Max {m. m * m \\<le> n}) ` {m. m * m \\<le> n}) \\<le> n\"\n    apply (subst Max_le_iff)\n      apply (metis (mono_tags) finite_imageI finite_less_ub le_square)\n     apply auto\n    apply (metis le0 mult_0_right)\n    done\n  with * show ?thesis \n    using tsqrt_alt_aux Max_in by (auto simp add: tsqrt_alt_def)\nqed\n\nlemma tsqrt_alt_le: \"tsqrt_alt n \\<le> n\"\n  using tsqrt_alt_aux [of n] by (auto simp add: tsqrt_alt_def intro: triangle_nat_le_imp_le)\n\nlemma Suc_tsqrt_alt_triangle_gt: \"n < triangle (Suc (tsqrt_alt n))\"\n  using Max_ge[OF tsqrt_alt_aux(1), of \"tsqrt_alt n + 1\" n]\n  by (cases \"n < triangle (Suc (tsqrt_alt n))\") (simp_all add: tsqrt_alt_def)\n\nlemma le_tsqrt_alt_iff: \"x \\<le> tsqrt_alt y \\<longleftrightarrow> triangle x \\<le> y\"\nproof -\n  have \"x \\<le> tsqrt_alt y \\<longleftrightarrow> (\\<exists>z. triangle z \\<le> y \\<and> x \\<le> z)\"    \n    using Max_ge_iff[OF tsqrt_alt_aux, of x y] by (simp add: tsqrt_alt_def)\n  also have \"\\<dots> \\<longleftrightarrow> triangle x \\<le> y\"\n  proof safe\n    fix z assume \"x \\<le> z\" \"triangle z \\<le> y\"\n    thus \"triangle x \\<le> y\" by (intro le_trans[of \"triangle x\" \"triangle z\" y]) (simp_all add: triangle_nat_le_eq_le)\n  qed auto\n  finally show ?thesis .\nqed\n  \nlemma le_tsqrt_altI: \"triangle x \\<le> y \\<Longrightarrow> x \\<le> tsqrt_alt y\"\n  by (simp add: le_tsqrt_alt_iff)\n\nlemma tsqrt_alt_le_iff: \"tsqrt_alt y \\<le> x \\<longleftrightarrow> (\\<forall>z. triangle z \\<le> y \\<longrightarrow> z \\<le> x)\"\n  using Max.bounded_iff[OF tsqrt_alt_aux] by (simp add: tsqrt_alt_def)\n\nlemma sqrt_leI:\n  \"(\\<And>z. triangle z \\<le> y \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> tsqrt_alt y \\<le> x\"\n  by simp\n    \nlemma triangle_less_imp_less: \"triangle x < triangle y \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x < y\"\n  by (simp add: less_le_not_le triangle_nat_le_eq_le)\nlemma tsqrt_alt_Suc:\n  \"tsqrt_alt (Suc n) = (if \\<exists>m. Suc n = triangle m then Suc (tsqrt_alt n) else tsqrt_alt n)\"\nproof cases\n  assume \"\\<exists> m. Suc n = triangle m\"\n  then obtain m where m_def: \"Suc n = triangle m\" by blast\n  then have lhs: \"tsqrt_alt (Suc n) = m\" by simp\n  from m_def tsqrt_alt_triangle_le[of n] \n    have \"triangle (tsqrt_alt n) < triangle m\" by linarith\n  with triangle_less_imp_less have lt_m: \"tsqrt_alt n < m\" by blast\n  from m_def Suc_tsqrt_alt_triangle_gt[of \"n\"]\n    have \"triangle m \\<le> triangle (Suc(tsqrt_alt n))\"\n      by linarith\n  with triangle_nat_le_eq_le have \"m \\<le> Suc (tsqrt_alt n)\" by blast\n  with lt_m have \"m = Suc (tsqrt_alt n)\" by simp\n  with lhs m_def show ?thesis by metis\nnext\n  assume asm: \"\\<not> (\\<exists> m. Suc n = triangle m)\"\n  hence \"Suc n \\<noteq> triangle (tsqrt_alt (Suc n))\" by simp\n  with tsqrt_alt_triangle_le[of \"Suc n\"] \n    have \"tsqrt_alt (Suc n) \\<le> tsqrt_alt n\" by (intro le_tsqrt_altI) linarith\n  moreover have \"tsqrt_alt (Suc n) \\<ge> tsqrt_alt n\"\n    by (intro monoD[OF mono_tsqrt_alt]) simp_all\n  ultimately show ?thesis using asm by simp\nqed\n\n(* Continue with direct definition, once again by moving to reals*)\n\nlemma triangle_tsqrt_le_real: \n  \"nat (floor (((sqrt (8 * n + 1) - 1) / 2) * ((1 + ((sqrt (8 * n + 1) - 1) / 2)) / 2))) \\<le> n\"\n  by (auto simp add: triangle_def field_simps)\n\nlemma tsqrt_real: \"tsqrt n = nat (floor (((sqrt (8 * n + 1) - 1) / 2)))\"\n  apply (simp add: tsqrt_def field_simps)\n  by (metis One_nat_def add.commute divide2_div2' mult.commute plus_1_eq_Suc triangular_part_real)\n\nlemma triangle_tsqrt_real_pre:\n  \"triangle (tsqrt n) = nat (floor ((nat (floor (((sqrt (8 * n + 1) - 1) / 2))) * nat (floor (1 + ((sqrt (8 * n + 1) - 1) / 2)))) / 2))\"\n  unfolding triangle_def tsqrt_real divide2_div2\n  apply (simp add: field_simps)\n  by (smt (verit, best) Suc_eq_plus1 add_mult_distrib2 floor_diff_of_int int_nat_eq\n      nat_int_comparison(1) nat_mult_1_right of_int_1 of_nat_1 of_nat_add plus_1_eq_Suc real_average_minus_first)\n\nlemma triangle_tsqrt_le_real_bound: \"nat (floor ((nat (floor (((sqrt (8 * n + 1) - 1) / 2))) * nat (floor (1 + ((sqrt (8 * n + 1) - 1) / 2)))) / 2))\n  \\<le> nat (floor (((sqrt (8 * n + 1) - 1) / 2) * ((1 + ((sqrt (8 * n + 1) - 1) / 2)) / 2)))\"\n  by (metis div_le_mono divide2_div2' le_mult_nat_floor times_divide_eq_right triangle_invert_real_typ triangle_invert_real_typ')\n\nlemma triangle_tsqrt_le: \"triangle (tsqrt n) \\<le> n\"\n  unfolding triangle_tsqrt_real_pre\n  using triangle_tsqrt_le_real triangle_tsqrt_le_real_bound\n  by (meson le_trans)\n  \nlemma tsqrt_unique:\n  assumes \"triangle m \\<le> n\" \"n < triangle (Suc m)\"\n  shows \"tsqrt n = m\"\n  using assms triangle_tsqrt_le tsqrt_correct\n  by (metis le_SucE le_antisym mono_tsqrt' nat_less_le)\n\nlemma tsqrt_tsqrt: \"tsqrt_alt n = tsqrt n\"\n  by (metis Suc_tsqrt_alt_triangle_gt tsqrt_unique tsqrt_alt_triangle_le)\n\nlemma tsqrt_Suc:\n  \"tsqrt (Suc n) = (if \\<exists>m. Suc n = triangle m then Suc (tsqrt n) else tsqrt n)\"\n  using tsqrt_alt_Suc tsqrt_tsqrt by force\n\nend", "meta": {"author": "AlexiosFan", "repo": "BA_NP_Reduction", "sha": "0e37ddc58cb822b0a09b2ce7c15e7b88652e154c", "save_path": "github-repos/isabelle/AlexiosFan-BA_NP_Reduction", "path": "github-repos/isabelle/AlexiosFan-BA_NP_Reduction/BA_NP_Reduction-0e37ddc58cb822b0a09b2ce7c15e7b88652e154c/poly-reductions/Lib/Triangle_Extensions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970811069351, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.7652600974729581}}
{"text": "(*  Title:      Sigma_Algebra.thy\n\n    Author:     Stefan Richter, Markus Wenzel, TU Muenchen\n    License:    LGPL\n\nChanges for Accordance to Joe Hurd's conventions\nand additions by Stefan Richter 2002\n*)\n\nsubsection \\<open>Sigma algebras \\label{sec:sigma}\\<close>\n\ntheory Sigma_Algebra imports Main begin\n\ntext \\<open>The $\\isacommand {theory}$ command commences a formal document and enumerates the\n  theories it depends on. With the \\<open>Main\\<close> theory, a standard\n  selection of useful HOL theories excluding the real\n  numbers is loaded. This theory includes and builds upon a tiny theory of the\n  same name by Markus Wenzel. This theory as well as \\<open>Measure\\<close>\n  in \\ref{sec:measure-spaces} is heavily\n  influenced by Joe Hurd's thesis \\<^cite>\\<open>\"hurd2002\"\\<close> and has been designed to keep the terminology as\n  consistent as possible with that work.\n\n  Sigma algebras are an elementary concept in measure\n  theory. To measure --- that is to integrate --- functions, we first have\n  to measure sets. Unfortunately, when dealing with a large universe,\n  it is often not possible to consistently assign a measure to every\n  subset. Therefore it is necessary to define the set of measurable\n  subsets of the universe. A sigma algebra is such a set that has\n  three very natural and desirable properties.\\<close>\n\ndefinition\n  sigma_algebra:: \"'a set set \\<Rightarrow> bool\" where\n  \"sigma_algebra A \\<longleftrightarrow>\n  {} \\<in> A \\<and> (\\<forall>a. a \\<in> A \\<longrightarrow> -a \\<in> A) \\<and>\n  (\\<forall>a. (\\<forall> i::nat. a i \\<in> A) \\<longrightarrow> (\\<Union>i. a i) \\<in> A)\"\n\ntext \\<open>\n  The $\\isacommand {definition}$ command defines new constants, which\n  are just named functions in HOL. Mind that the third condition\n  expresses the fact that the union of countably many sets in $A$ is\n  again a set in $A$ without explicitly defining the notion of\n  countability.\n\n  Sigma algebras can naturally be created as the closure of any set of\n  sets with regard to the properties just postulated. Markus Wenzel\n  wrote the following\n  inductive definition of the $\\isa {sigma}$ operator.\\<close>\n\n\ninductive_set\n  sigma :: \"'a set set \\<Rightarrow> 'a set set\"\n  for A :: \"'a set set\"\n  where\n    basic: \"a \\<in> A \\<Longrightarrow> a \\<in> sigma A\"\n  | empty: \"{} \\<in> sigma A\"\n  | complement: \"a \\<in> sigma A \\<Longrightarrow> -a \\<in> sigma A\"\n  | Union: \"(\\<And>i::nat. a i \\<in> sigma A) \\<Longrightarrow> (\\<Union>i. a i) \\<in> sigma A\"\n\n\ntext \\<open>He also proved the following basic facts. The easy proofs are omitted.\n\\<close>\n\ntheorem sigma_UNIV: \"UNIV \\<in> sigma A\"\n(*<*)proof -\n  have \"{} \\<in> sigma A\" by (rule sigma.empty)\n  hence \"-{} \\<in> sigma A\" by (rule sigma.complement)\n  also have \"-{} = UNIV\" by simp\n  finally show ?thesis .\nqed(*>*)\n\n\ntheorem sigma_Inter:\n  \"(\\<And>i::nat. a i \\<in> sigma A) \\<Longrightarrow> (\\<Inter>i. a i) \\<in> sigma A\"\n(*<*) proof -\n  assume \"\\<And>i::nat. a i \\<in> sigma A\"\n  hence \"\\<And>i::nat. -(a i) \\<in> sigma A\" by (rule sigma.complement)\n  hence \"(\\<Union>i. -(a i)) \\<in> sigma A\" by (rule sigma.Union)\n  hence \"-(\\<Union>i. -(a i)) \\<in> sigma A\" by (rule sigma.complement)\n  also have \"-(\\<Union>i. -(a i)) = (\\<Inter>i. a i)\" by simp\n  finally show ?thesis .\nqed(*>*)\n\ntext \\<open>It is trivial to show the connection between our first\n  definitions. We use the opportunity to introduce the proof syntax.\\<close>\n\n\ntheorem assumes sa: \"sigma_algebra A\"\n  \\<comment> \\<open>Named premises are introduced like this.\\<close>\n\n  shows sigma_sigma_algebra: \"sigma A = A\"\nproof\n\n  txt \\<open>The $\\isacommand {proof}$ command alone invokes a single standard rule to\n    simplify the goal. Here the following two subgoals emerge.\\<close>\n\n  show \"A \\<subseteq> sigma A\"\n    \\<comment> \\<open>The $\\isacommand {show}$ command starts the proof of a subgoal.\\<close>\n\n    by (auto simp add: sigma.basic)\n\n  txt \\<open>This is easy enough to be solved by an automatic step,\n    indicated by the keyword $\\isacommand {by}$. The method $\\isacommand {auto}$ is stated in parentheses, with attributes to it following.  In\n    this case, the first introduction rule for the $\\isacommand {sigma}$\n    operator is given as an extra simplification rule.\\<close>\n\n  show \"sigma A \\<subseteq> A\"\n  proof\n\n    txt \\<open>Because this goal is not quite as trivial, another proof is\n      invoked, delimiting a block as in a programming language.\\<close>\n\n    fix x\n    \\<comment> \\<open>A new named variable is introduced.\\<close>\n\n    assume \"x \\<in> sigma A\"\n\n    txt \\<open>An assumption is made that must be justified by the current proof\n      context. In this case the corresponding fact had been generated\n      by a rule automatically invoked by the inner $\\isacommand {proof}$\n      command.\\<close>\n\n    from this sa show \"x \\<in> A\"\n\n      txt \\<open>Named facts can explicitly be given to the proof methods using\n        $\\isacommand {from}$. A special name is \\<open>this\\<close>, which denotes\n        current facts generated by the last command. Usually $\\isacommand\n        {from}$ \\<open>this sa\\<close> --- remember that \\<open>sa\\<close> is an assumption from above\n        --- is abbreviated to $\\isacommand {with}$ \\<open>sa\\<close>, but in this case the order of\n        facts is relevant for the following method and $\\isacommand\n        {with}$\n        would have put the current facts last.\\<close>\n\n      by (induct rule: sigma.induct) (auto simp add: sigma_algebra_def)\n\n    txt \\<open>Two methods may be carried out at $\\isacommand {by}$. The first\n      one applies induction here via the canonical rule generated by the\n      inductive definition above, while the latter solves the\n      resulting subgoals by an automatic step involving\n      simplification.\\<close>\n\n  qed\nqed\n\ntext \"These two steps finish their respective proofs, checking\n  that all subgoals have been proven.\"\n\ntext \\<open>To end this theory we prove a special case of the \\<open>sigma_Inter\\<close> theorem above. It seems trivial that\n  the fact holds for two sets as well as for countably many.\n  We get a first taste of the cost of formal reasoning here, however. The\n  idea must be made precise by exhibiting a concrete sequence of\n  sets.\\<close>\n\nprimrec trivial_series:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> (nat \\<Rightarrow> 'a set)\"\nwhere\n  \"trivial_series a b 0 = a\"\n| \"trivial_series a b (Suc n) = b\"\n\ntext \\<open>Using $\\isacommand {primrec}$, primitive recursive functions over\n  inductively defined data types --- the natural numbers in this case ---\n  may be constructed.\\<close>\n\n\ntheorem assumes s: \"sigma_algebra A\" and a: \"a \\<in> A\" and b: \"b \\<in> A\"\n  shows sigma_algebra_inter: \"a \\<inter> b \\<in> A\"\nproof -\n    \\<comment> \\<open>This form of $\\isacommand {proof}$ foregoes the application of a rule.\\<close>\n\n  have \"a \\<inter> b = (\\<Inter>i::nat. trivial_series a b i)\"\n\n    txt \\<open>Intermediate facts that do not solve any subgoals yet are established this way.\\<close>\n\n  proof (rule set_eqI)\n\n    txt \\<open>The  $\\isacommand {proof}$ command may also take one explicit method\n      as an argument like the single rule application in this instance.\\<close>\n\n    fix x\n\n    {\n      fix i\n      assume \"x \\<in> a \\<inter> b\"\n      hence \"x \\<in> trivial_series a b i\" by (cases i) auto\n        \\<comment> \\<open>This is just an abbreviation for $\\isacommand {\"from this have\"}$.\\<close>\n    }\n\n    txt \\<open>Curly braces can be used to explicitly delimit\n      blocks. In conjunction with $\\isacommand {fix}$, universal\n      quantification over the fixed variable $i$ is achieved\n      for the last statement in the block, which is exported to the\n      enclosing block.\\<close>\n\n    hence \"x \\<in> a \\<inter> b \\<Longrightarrow> \\<forall>i. x \\<in> trivial_series a b i\"\n      by fast\n    also\n\n    txt \\<open>The statement $\\isacommand {also}$ introduces calculational\n      reasoning. This basically amounts to collecting facts. With\n      $\\isacommand {also}$, the current fact is added to a special list of\n      theorems called the calculation and\n      an automatically selected transitivity rule\n      is additionally applied from the second collected fact on.\\<close>\n\n    { assume \"\\<And>i. x \\<in> trivial_series a b i\"\n      hence \"x \\<in> trivial_series a b 0\" and \"x \\<in> trivial_series a b 1\"\n        by this+\n      hence \"x \\<in> a \\<inter> b\"\n        by simp\n    }\n    hence \"\\<forall>i. x \\<in> trivial_series a b i \\<Longrightarrow> x \\<in> a \\<inter> b\"\n      by blast\n\n    ultimately have \"x \\<in> a \\<inter> b = (\\<forall>i::nat. x \\<in> trivial_series a b i)\" ..\n\n    txt \\<open>The accumulated calculational facts including the current one\n      are exposed to the next statement by  $\\isacommand {ultimately}$ and\n      the calculation list is then erased. The two dots after the\n      statement here indicate proof by a single automatically\n      selected rule.\\<close>\n\n    also have \"\\<dots> =  (x \\<in> (\\<Inter>i::nat. trivial_series a b i))\"\n      by simp\n    finally show \"x \\<in> a \\<inter> b = (x \\<in> (\\<Inter>i::nat. trivial_series a b i))\" .\n\n    txt \\<open>The $\\isacommand {finally}$ directive behaves like $\\isacommand {ultimately}$\n      with the addition of a further transitivity rule application. A\n      single dot stands for proof by assumption.\\<close>\n\n  qed\n\n  moreover have \"(\\<Inter>i::nat. trivial_series a b i) \\<in> A\"\n  proof -\n    { fix i\n      from a b have \"trivial_series a b i \\<in> A\"\n        by (cases i) auto\n    }\n    hence \"\\<And>i. trivial_series a b i \\<in> sigma A\"\n      by (simp only: sigma.basic)\n    hence \"(\\<Inter>i::nat. trivial_series a b i) \\<in> sigma A\"\n      by (simp only: sigma_Inter)\n    with s show ?thesis\n      by (simp only: sigma_sigma_algebra)\n  qed\n\n  ultimately show ?thesis by simp\nqed\n\ntext \\<open>Of course, a like theorem holds for union instead of\n  intersection.  But as we will not need it in what follows, the\n  theory is finished with the following easy properties instead.\n  Note that the former is a kind of generalization of the last result and\n  could be used to  shorten its proof. Unfortunately, this one was needed ---\n  and therefore found --- only late in the development.\n\\<close>\n\ntheorem sigma_INTER:\n  assumes a:\"(\\<And>i::nat. i \\<in> S \\<Longrightarrow> a i \\<in> sigma A)\"\n  shows \"(\\<Inter>i\\<in>S. a i) \\<in> sigma A\"(*<*)\nproof -\n  from a have \"\\<And>i. (if i\\<in>S then {} else UNIV) \\<union> a i \\<in> sigma A\"\n    by (simp add: sigma.intros sigma_UNIV)\n  hence \"(\\<Inter>i. (if i\\<in>S then {} else UNIV) \\<union> a i) \\<in> sigma A\"\n    by (rule sigma_Inter)\n  also have \"(\\<Inter>i. (if i\\<in>S then {} else UNIV) \\<union> a i) = (\\<Inter>i\\<in>S. a i)\"\n    by force\n  finally show ?thesis .\nqed(*>*)\n\n\nlemma assumes s: \"sigma_algebra a\" shows sigma_algebra_UNIV: \"UNIV \\<in> a\"(*<*)\nproof -\n  from s have \"{}\\<in>a\" by (unfold sigma_algebra_def) blast\n  with s show ?thesis by (unfold sigma_algebra_def) auto\nqed(*>*)\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Integration/Sigma_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.8807970889295663, "lm_q1q2_score": 0.7652600833282287}}
{"text": "section {*foundations\\_on\\_functions*}\ntheory\n  foundations_on_functions\n\nimports\n  partial_functions\n\nbegin\n\ndefinition left_total_on :: \"\n  ('A \\<Rightarrow> 'B \\<Rightarrow> bool)\n  \\<Rightarrow> 'A set\n  \\<Rightarrow> 'B set\n  \\<Rightarrow> bool\"\n  where\n    \"left_total_on R A B \\<equiv>\n  \\<forall>a \\<in> A. \\<exists>b \\<in> B. R a b\"\n\ndefinition right_total_on :: \"\n  ('A \\<Rightarrow> 'B \\<Rightarrow> bool)\n  \\<Rightarrow> 'A set\n  \\<Rightarrow> 'B set\n  \\<Rightarrow> bool\"\n  where\n    \"right_total_on R A B \\<equiv>\n  \\<forall>b \\<in> B. \\<exists>a \\<in> A. R a b\"\n\ndefinition bijection_on :: \"\n  ('a \\<Rightarrow> 'b \\<Rightarrow> bool)\n  \\<Rightarrow> 'a set\n  \\<Rightarrow> 'b set\n  \\<Rightarrow> bool\"\n  where\n    \"bijection_on F A B \\<equiv>\n  (\\<forall>a \\<in> A. \\<exists>!b \\<in> B. F a b)\n  \\<and> (\\<forall>b \\<in> B. \\<exists>!a \\<in> A. F a b)\"\n\nlemma bijection_on_RT: \"\n  bijection_on F A B\n  \\<Longrightarrow> a \\<in> A\n  \\<Longrightarrow> \\<exists>b\\<in> B. F a b\"\n  apply(simp add: bijection_on_def)\n  apply(force)\n  done\n\nlemma bijection_on_LT: \"\n  bijection_on F A B\n  \\<Longrightarrow> b \\<in> B\n  \\<Longrightarrow> \\<exists>a\\<in> A. F a b\"\n  apply(simp add: bijection_on_def)\n  apply(force)\n  done\n\nlemma bijection_on_RU: \"\n  bijection_on F A B\n  \\<Longrightarrow> a \\<in> A\n  \\<Longrightarrow> b1 \\<in> B\n  \\<Longrightarrow> b2 \\<in> B\n  \\<Longrightarrow> F a b1\n  \\<Longrightarrow> F a b2\n  \\<Longrightarrow> b1 = b2\"\n  apply(simp add: bijection_on_def)\n  apply(force)\n  done\n\nlemma bijection_on_LU: \"\n  bijection_on F A B\n  \\<Longrightarrow> b \\<in> B\n  \\<Longrightarrow> a1 \\<in> A\n  \\<Longrightarrow> a2 \\<in> A\n  \\<Longrightarrow> F a1 b\n  \\<Longrightarrow> F a2 b\n  \\<Longrightarrow> a1=a2\"\n  apply(simp add: bijection_on_def)\n  apply(force)\n  done\n\nlemma bijection_on_intro: \"\n  (\\<forall>a\\<in> A. \\<exists>b\\<in> B. F a b)\n  \\<Longrightarrow> (\\<forall>b\\<in> B. \\<exists>a\\<in> A. F a b)\n  \\<Longrightarrow> (\\<forall>a\\<in> A. \\<forall>b1\\<in> B. \\<forall>b2\\<in> B. F a b1 \\<longrightarrow> F a b2 \\<longrightarrow> b1 = b2)\n  \\<Longrightarrow> (\\<forall>b\\<in> B. \\<forall>a1\\<in> A. \\<forall>a2\\<in> A. F a1 b \\<longrightarrow> F a2 b \\<longrightarrow> a1 = a2)\n  \\<Longrightarrow> bijection_on F A B\"\n  apply(simp add: bijection_on_def)\n  apply(rule conjI)\n   apply(clarsimp)\n   apply(erule_tac\n      x=\"a\"\n      in ballE)\n    prefer 2\n    apply(force)\n   apply(erule_tac\n      x=\"a\"\n      in ballE)\n    prefer 2\n    apply(force)\n   apply(clarsimp)\n   apply(rule_tac\n      a=\"b\"\n      in ex1I)\n    apply(force)\n   apply(force)\n  apply(clarsimp)\n  apply(erule_tac\n      x=\"b\"\n      in ballE)\n   prefer 2\n   apply(force)\n  apply(erule_tac\n      x=\"b\"\n      in ballE)\n   prefer 2\n   apply(force)\n  apply(clarsimp)\n  apply(rule_tac\n      a=\"a\"\n      in ex1I)\n   apply(force)\n  apply(force)\n  done\n\ndefinition LT_ON :: \"('\\<Sigma> \\<times> 'b)set \\<Rightarrow> '\\<Sigma> set \\<Rightarrow> 'b set \\<Rightarrow> bool\" where\n  \"LT_ON R A B = (\\<forall>x \\<in> A. \\<exists>y \\<in> B. (x,y) \\<in> R)\"\n\n\nend\n\n", "meta": {"author": "ControllerSynthesis", "repo": "Isabelle", "sha": "fc776edec292363e49785e5d3a752d9f9cfcf1c9", "save_path": "github-repos/isabelle/ControllerSynthesis-Isabelle", "path": "github-repos/isabelle/ControllerSynthesis-Isabelle/Isabelle-fc776edec292363e49785e5d3a752d9f9cfcf1c9/PRJ_01_02/foundations_on_functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7652600827879305}}
{"text": "(*  \n    Title:      Examples_Gauss_Jordan_IArrays.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nsection\\<open>Examples of computations over matrices represented as nested IArrays\\<close>\n\ntheory Examples_Gauss_Jordan_IArrays\nimports\n  System_Of_Equations_IArrays\n  Determinants_IArrays\n  Inverse_IArrays\n  Code_Z2\n  \"HOL-Library.Code_Target_Numeral\"\n(*\"HOL-Library.Code_Real_Approx_By_Float\"*)\nbegin\n\nsubsection\\<open>Transformations between nested lists nested IArrays\\<close>\ndefinition iarray_of_iarray_to_list_of_list :: \"'a iarray iarray => 'a list list\"\n  where \"iarray_of_iarray_to_list_of_list A = map IArray.list_of (map ((!!) A) [0..<IArray.length A])\"\n\ntext\\<open>The following definitions are also in the file \\<open>Examples_on_Gauss_Jordan_Abstract\\<close>.\\<close>\n\ntext\\<open>Definitions to transform a matrix to a list of list and vice versa\\<close>\ndefinition vec_to_list :: \"'a^'n::{finite, enum} => 'a list\"\n  where \"vec_to_list A = map (($) A) (enum_class.enum::'n list)\"\n\ndefinition matrix_to_list_of_list :: \"'a^'n::{finite, enum}^'m::{finite, enum} => 'a list list\"\n  where \"matrix_to_list_of_list A = map (vec_to_list) (map (($) A) (enum_class.enum::'m list))\"\n\ntext\\<open>This definition should be equivalent to \\<open>vector_def\\<close> (in suitable types)\\<close>\ndefinition list_to_vec :: \"'a list => 'a^'n::{enum, mod_type}\"\n  where \"list_to_vec xs = vec_lambda (% i. xs ! (to_nat i))\"\n\nlemma [code abstract]: \"vec_nth (list_to_vec xs) = (%i. xs ! (to_nat i))\"\n  unfolding list_to_vec_def by fastforce\n\ndefinition list_of_list_to_matrix :: \"'a list list => 'a^'n::{enum, mod_type}^'m::{enum, mod_type}\"\n  where \"list_of_list_to_matrix xs = vec_lambda (%i. list_to_vec (xs ! (to_nat i)))\"\n\nlemma [code abstract]: \"vec_nth (list_of_list_to_matrix xs) = (%i. list_to_vec (xs ! (to_nat i)))\"\n  unfolding list_of_list_to_matrix_def by auto\n\nsubsection\\<open>Examples\\<close>\n\ntext\\<open>The following three lemmas are presented in both this file and in the \n\\<open>Examples_Gauss_Jordan_Abstract\\<close> one. They allow a more convenient printing of rational and\nreal numbers after evaluation. They have already been added to the repository version of Isabelle, \nso after Isabelle2014 they should be removed from here.\\<close>\n\nlemma [code_post]:\n  \"int_of_integer (- 1) = - 1\"\n by simp\n\nlemma [code_abbrev]:\n \"(of_rat (- 1) :: real) = - 1\"\n  by simp\n\nlemma [code_post]:\n \"(of_rat (- (1 / numeral k)) :: real) = - 1 / numeral k\"\n \"(of_rat (- (numeral k / numeral l)) :: real) = - numeral k / numeral l\"\n by (simp_all add: of_rat_divide of_rat_minus)\n\ntext\\<open>From here on, we do the computations in two ways. The first one consists of executing the abstract functions (which internally will execute the ones over iarrays).\nThe second one runs directly the functions over iarrays.\\<close>\n\nsubsubsection\\<open>Ranks, dimensions and Gauss Jordan algorithm\\<close>\ntext\\<open>In the following examples, the theorem \\<open>matrix_to_iarray_rank\\<close> (which is the file \\<open>Gauss_Jordan_IArrays\\<close> \n  and it is a code unfold theorem) assures that the computation will be carried out using the iarrays representation.\\<close>\nvalue \"vec.dim (col_space (list_of_list_to_matrix [[1,0,0,7,5],[1,0,4,8,-1],[1,0,0,9,8],[1,2,3,6,5]]::real^5^4))\"\nvalue \"rank (list_of_list_to_matrix [[1,0,0,7,5],[1,0,4,8,-1],[1,0,0,9,8],[1,2,3,6,5]]::real^5^4)\" \nvalue \"vec.dim (null_space (list_of_list_to_matrix [[1,0,0,7,5],[1,0,4,8,-1],[1,0,0,9,8],[1,2,3,6,5]]::rat^5^4))\"\n\nvalue \"rank_iarray (IArray[IArray[1::rat,0,0,7,5],IArray[1,0,4,8,-1],IArray[1,0,0,9,8],IArray[1,2,3,6,5]])\" \n(*Identical matrices with coefficients in Z2 and R could have different rank in each field:*)\nvalue \"rank_iarray (IArray[IArray[1::real,0,1],IArray[1,1,0],IArray[0,1,1]])\"\nvalue \"rank_iarray (IArray[IArray[1::bit,0,1],IArray[1,1,0],IArray[0,1,1]])\"\n\ntext\\<open>Examples on computing the Gauss Jordan algorithm.\\<close>\nvalue \"iarray_of_iarray_to_list_of_list (matrix_to_iarray (Gauss_Jordan (list_of_list_to_matrix [[Complex 1 1,Complex 1 (- 1), Complex 0 0],[Complex 2 (- 1),Complex 1 3, Complex 7 3]]::complex^3^2)))\"\nvalue \"iarray_of_iarray_to_list_of_list (Gauss_Jordan_iarrays(IArray[IArray[Complex 1 1,Complex 1 (- 1),Complex 0 0],IArray[Complex 2 (- 1),Complex 1 3,Complex 7 3]]))\"\n\nsubsubsection\\<open>Inverse of a matrix\\<close>\ntext\\<open>Examples on inverting matrices\\<close>\n\ndefinition \"print_result_some_iarrays A = (if A = None then None else Some (iarray_of_iarray_to_list_of_list (the A)))\" \n\nvalue \"let A=(list_of_list_to_matrix [[1,1,2,4,5,9,8],[3,0,8,4,5,0,8],[3,2,0,4,5,9,8],[3,2,8,0,5,9,8],[3,2,8,4,0,9,8],[3,2,8,4,5,0,8],[3,2,8,4,5,9,0]]::real^7^7)\n                    in print_result_some_iarrays (matrix_to_iarray_option (inverse_matrix A))\"\nvalue \"let A=(IArray[IArray[1::real,1,2,4,5,9,8],IArray[3,0,8,4,5,0,8],IArray[3,2,0,4,5,9,8],IArray[3,2,8,0,5,9,8],IArray[3,2,8,4,0,9,8],IArray[3,2,8,4,5,0,8],IArray[3,2,8,4,5,9,0]])\n                    in print_result_some_iarrays (inverse_matrix_iarray A)\"\n\nsubsubsection\\<open>Determinant of a matrix\\<close>\ntext\\<open>Examples on computing determinants of matrices\\<close>\n\nvalue \"det (list_of_list_to_matrix ([[1,8,9,1,47],[7,2,2,5,9],[3,2,7,7,4],[9,8,7,5,1],[1,2,6,4,5]])::rat^5^5)\"\nvalue \"det (list_of_list_to_matrix [[1,2,7,8,9],[3,4,12,10,7],[-5,4,8,7,4],[0,1,2,4,8],[9,8,7,13,11]]::rat^5^5)\"\n\nvalue \"det_iarrays (IArray[IArray[1::real,2,7,8,9],IArray[3,4,12,10,7],IArray[-5,4,8,7,4],IArray[0,1,2,4,8],IArray[9,8,7,13,11]])\"\nvalue \"det_iarrays (IArray[IArray[286,662,263,246,642,656,351,454,339,848],\nIArray[307,489,667,908,103,47,120,133,85,834],\nIArray[69,732,285,147,527,655,732,661,846,202],\nIArray[463,855,78,338,786,954,593,550,913,378],\nIArray[90,926,201,362,985,341,540,912,494,427],\nIArray[384,511,12,627,131,620,987,996,445,216],\nIArray[385,538,362,643,567,804,499,914,332,512],\nIArray[879,159,312,187,827,503,823,893,139,546],\nIArray[800,376,331,363,840,737,911,886,456,848],\nIArray[900,737,280,370,121,195,958,862,957,754::real]])\"\n\n\nsubsubsection\\<open>Bases of the fundamental subspaces\\<close>\ntext\\<open>Examples on computing basis for null space, row space, column space and left null space.\\<close>\n(*Null_space basis:*)\nvalue \"let A = (list_of_list_to_matrix ([[1,3,-2,0,2,0],[2,6,-5,-2,4,-3],[0,0,5,10,0,15],[2,6,0,8,4,18]])::real^6^4) \n  in vec_to_list` (basis_null_space A)\"\nvalue \"let A = (list_of_list_to_matrix ([[3,4,0,7],[1,-5,2,-2],[-1,4,0,3],[1,-1,2,2]])::real^4^4) \n  in vec_to_list` (basis_null_space A)\"\n\nvalue \"let A = (IArray[IArray[1::real,3,-2,0,2,0],IArray[2,6,-5,-2,4,-3],IArray[0,0,5,10,0,15],IArray[2,6,0,8,4,18]]) \n  in IArray.list_of` (basis_null_space_iarrays A)\"\nvalue \"let A = (IArray[IArray[3::real,4,0,7],IArray[1,-5,2,-2],IArray[-1,4,0,3],IArray[1,-1,2,2]])\n  in IArray.list_of` (basis_null_space_iarrays A)\"\n\n(*Row_space basis*)\nvalue \"let A = (list_of_list_to_matrix ([[1,3,-2,0,2,0],[2,6,-5,-2,4,-3],[0,0,5,10,0,15],[2,6,0,8,4,18]])::real^6^4) \n    in vec_to_list` (basis_row_space A)\"\nvalue \"let A = (list_of_list_to_matrix ([[3,4,0,7],[1,-5,2,-2],[-1,4,0,3],[1,-1,2,2]])::real^4^4) \n  in vec_to_list` (basis_row_space A)\"\n\nvalue \"let A = (IArray[IArray[1::real,3,-2,0,2,0],IArray[2,6,-5,-2,4,-3],IArray[0,0,5,10,0,15],IArray[2,6,0,8,4,18]]) \n  in IArray.list_of` (basis_row_space_iarrays A)\"\nvalue \"let A = (IArray[IArray[3::real,4,0,7],IArray[1,-5,2,-2],IArray[-1,4,0,3],IArray[1,-1,2,2]])\n  in IArray.list_of` (basis_row_space_iarrays A)\"\n\n(*Col_space basis*)\nvalue \"let A = (list_of_list_to_matrix ([[1,3,-2,0,2,0],[2,6,-5,-2,4,-3],[0,0,5,10,0,15],[2,6,0,8,4,18]])::real^6^4) \n    in vec_to_list` (basis_col_space A)\"\nvalue \"let A = (list_of_list_to_matrix ([[3,4,0,7],[1,-5,2,-2],[-1,4,0,3],[1,-1,2,2]])::real^4^4) \n  in vec_to_list` (basis_col_space A)\"\n\nvalue \"let A = (IArray[IArray[1::real,3,-2,0,2,0],IArray[2,6,-5,-2,4,-3],IArray[0,0,5,10,0,15],IArray[2,6,0,8,4,18]]) \n  in IArray.list_of` (basis_col_space_iarrays A)\"\nvalue \"let A = (IArray[IArray[3::real,4,0,7],IArray[1,-5,2,-2],IArray[-1,4,0,3],IArray[1,-1,2,2]])\n  in IArray.list_of` (basis_col_space_iarrays A)\"\n\n(*Left_null_space basis*)\nvalue \"let A = (list_of_list_to_matrix ([[1,3,-2,0,2,0],[2,6,-5,-2,4,-3],[0,0,5,10,0,15],[2,6,0,8,4,18]])::real^6^4) \n    in vec_to_list` (basis_left_null_space A)\"\nvalue \"let A = (list_of_list_to_matrix ([[3,4,0,7],[1,-5,2,-2],[-1,4,0,3],[1,-1,2,2]])::real^4^4) \n  in vec_to_list` (basis_left_null_space A)\"\n\nvalue \"let A = (IArray[IArray[1::real,3,-2,0,2,0],IArray[2,6,-5,-2,4,-3],IArray[0,0,5,10,0,15],IArray[2,6,0,8,4,18]]) \n  in IArray.list_of` (basis_left_null_space_iarrays A)\"\nvalue \"let A = (IArray[IArray[3::real,4,0,7],IArray[1,-5,2,-2],IArray[-1,4,0,3],IArray[1,-1,2,2]])\n  in IArray.list_of` (basis_left_null_space_iarrays A)\"\n\n\nsubsubsection\\<open>Consistency and inconsistency\\<close>\n\ntext\\<open>Examples on checking the consistency/inconsistency of a system of equations. The theorems \\<open>matrix_to_iarray_independent_and_consistent\\<close> and \n\\<open>matrix_to_iarray_dependent_and_consistent\\<close> which are code theorems and they are in the file \\<open>System_Of_Equations_IArrays\\<close>\nassure the execution using the iarrays representation.\\<close>\n\nvalue \"independent_and_consistent (list_of_list_to_matrix ([[1,0,0],[0,1,0],[0,0,1],[0,0,0],[0,0,0]])::real^3^5) (list_to_vec([2,3,4,0,0])::real^5)\"\nvalue \"consistent (list_of_list_to_matrix ([[1,0,0],[0,1,0],[0,0,1],[0,0,0],[0,0,0]])::real^3^5) (list_to_vec([2,3,4,0,0])::real^5)\"\nvalue \"inconsistent (list_of_list_to_matrix ([[1,0,0],[0,1,0],[3,0,1],[0,7,0],[0,0,9]])::real^3^5) (list_to_vec([2,0,4,0,0])::real^5)\"\nvalue \"dependent_and_consistent (list_of_list_to_matrix ([[1,0,0],[0,1,0]])::real^3^2) (list_to_vec([3,4])::real^2)\"\nvalue \"independent_and_consistent (mat 1::real^3^3) (list_to_vec([3,4,5])::real^3)\"\n\n\nsubsubsection\\<open>Solving systems of linear equations\\<close>\ntext\\<open>Examples on solving linear systems.\\<close>\ndefinition \"print_result_system_iarrays A = (if A = None then None else Some (IArray.list_of (fst (the A)), IArray.list_of` (snd (the A))))\" \n\nvalue \"let A = (list_of_list_to_matrix [[0,0,0],[0,0,0],[0,0,1]]::real^3^3); b=(list_to_vec [4,5,0]::real^3);\n                  result = pair_vec_vecset (solve A b)\n                  in print_result_system_iarrays (result)\"\nvalue \"let A = (list_of_list_to_matrix [[3,2,5,2,7],[6,4,7,4,5],[3,2,-1,2,-11],[6,4,1,4,-13]]::real^5^4); b=(list_to_vec [0,0,0,0]::real^4);\n                  result = pair_vec_vecset (solve A b)\n                  in print_result_system_iarrays (result)\"\nvalue \"let A = (list_of_list_to_matrix [[4,5,8],[9,8,7],[4,6,1]]::real^3^3); b=(list_to_vec [4,5,8]::real^3);\n                  result = pair_vec_vecset (solve A b)\n                  in print_result_system_iarrays (result)\"\n\nvalue \"let A = (IArray[IArray[0::real,0,0],IArray[0,0,0],IArray[0,0,1]]); b=(IArray[4,5,0]);\n                  result = (solve_iarrays A b)\n                  in print_result_system_iarrays (result)\"\nvalue \"let A = (IArray[IArray[3::real,2,5,2,7],IArray[6,4,7,4,5],IArray[3,2,-1,2,-11],IArray[6,4,1,4,-13]]); b=(IArray[0,0,0,0]);\n                  result = (solve_iarrays A b)\n                  in print_result_system_iarrays (result)\"\nvalue \"let A = (IArray[IArray[4,5,8],IArray[9::real,8,7],IArray[4,6::real,1]]); b=(IArray[4,5,8]);\n                  result = (solve_iarrays A b)\n                  in print_result_system_iarrays (result)\"\n\nexport_code\n  rank_iarray\n  inverse_matrix_iarray\n  det_iarrays\n  consistent_iarrays\n  inconsistent_iarrays\n  independent_and_consistent_iarrays\n  dependent_and_consistent_iarrays\n  basis_left_null_space_iarrays\n  basis_null_space_iarrays\n  basis_col_space_iarrays\n  basis_row_space_iarrays\n  solve_iarrays\n  in SML\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gauss_Jordan/Examples_Gauss_Jordan_IArrays.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.8688267779364222, "lm_q1q2_score": 0.7652600764009196}}
{"text": "(*  Title:      FOL/ex/Classical.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1994  University of Cambridge\n*)\n\nsection \\<open>Classical Predicate Calculus Problems\\<close>\n\ntheory Classical\nimports FOL\nbegin\n\nlemma \"(P \\<longrightarrow> Q \\<or> R) \\<longrightarrow> (P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R)\"\n  by blast\n\n\nsubsubsection \\<open>If and only if\\<close>\n\nlemma \"(P \\<longleftrightarrow> Q) \\<longleftrightarrow> (Q \\<longleftrightarrow> P)\"\n  by blast\n\nlemma \"\\<not> (P \\<longleftrightarrow> \\<not> P)\"\n  by blast\n\n\nsubsection \\<open>Pelletier's examples\\<close>\n\ntext \\<open>\n  Sample problems from\n\n    \\<^item> F. J. Pelletier,\n    Seventy-Five Problems for Testing Automatic Theorem Provers,\n    J. Automated Reasoning 2 (1986), 191-216.\n    Errata, JAR 4 (1988), 236-236.\n\n  The hardest problems -- judging by experience with several theorem\n  provers, including matrix ones -- are 34 and 43.\n\\<close>\n\ntext\\<open>1\\<close>\nlemma \"(P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\"\n  by blast\n\ntext\\<open>2\\<close>\nlemma \"\\<not> \\<not> P \\<longleftrightarrow> P\"\n  by blast\n\ntext\\<open>3\\<close>\nlemma \"\\<not> (P \\<longrightarrow> Q) \\<longrightarrow> (Q \\<longrightarrow> P)\"\n  by blast\n\ntext\\<open>4\\<close>\nlemma \"(\\<not> P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> P)\"\n  by blast\n\ntext\\<open>5\\<close>\nlemma \"((P \\<or> Q) \\<longrightarrow> (P \\<or> R)) \\<longrightarrow> (P \\<or> (Q \\<longrightarrow> R))\"\n  by blast\n\ntext\\<open>6\\<close>\nlemma \"P \\<or> \\<not> P\"\n  by blast\n\ntext\\<open>7\\<close>\nlemma \"P \\<or> \\<not> \\<not> \\<not> P\"\n  by blast\n\ntext\\<open>8. Peirce's law\\<close>\nlemma \"((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P\"\n  by blast\n\ntext\\<open>9\\<close>\nlemma \"((P \\<or> Q) \\<and> (\\<not> P \\<or> Q) \\<and> (P \\<or> \\<not> Q)) \\<longrightarrow> \\<not> (\\<not> P \\<or> \\<not> Q)\"\n  by blast\n\ntext\\<open>10\\<close>\nlemma \"(Q \\<longrightarrow> R) \\<and> (R \\<longrightarrow> P \\<and> Q) \\<and> (P \\<longrightarrow> Q \\<or> R) \\<longrightarrow> (P \\<longleftrightarrow> Q)\"\n  by blast\n\ntext\\<open>11. Proved in each direction (incorrectly, says Pelletier!!)\\<close>\nlemma \"P \\<longleftrightarrow> P\"\n  by blast\n\ntext\\<open>12. \"Dijkstra's law\"\\<close>\nlemma \"((P \\<longleftrightarrow> Q) \\<longleftrightarrow> R) \\<longleftrightarrow> (P \\<longleftrightarrow> (Q \\<longleftrightarrow> R))\"\n  by blast\n\ntext\\<open>13. Distributive law\\<close>\nlemma \"P \\<or> (Q \\<and> R) \\<longleftrightarrow> (P \\<or> Q) \\<and> (P \\<or> R)\"\n  by blast\n\ntext\\<open>14\\<close>\nlemma \"(P \\<longleftrightarrow> Q) \\<longleftrightarrow> ((Q \\<or> \\<not> P) \\<and> (\\<not> Q \\<or> P))\"\n  by blast\n\ntext\\<open>15\\<close>\nlemma \"(P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> P \\<or> Q)\"\n  by blast\n\ntext\\<open>16\\<close>\nlemma \"(P \\<longrightarrow> Q) \\<or> (Q \\<longrightarrow> P)\"\n  by blast\n\ntext\\<open>17\\<close>\nlemma \"((P \\<and> (Q \\<longrightarrow> R)) \\<longrightarrow> S) \\<longleftrightarrow> ((\\<not> P \\<or> Q \\<or> S) \\<and> (\\<not> P \\<or> \\<not> R \\<or> S))\"\n  by blast\n\n\nsubsection \\<open>Classical Logic: examples with quantifiers\\<close>\n\nlemma \"(\\<forall>x. P(x) \\<and> Q(x)) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<and> (\\<forall>x. Q(x))\"\n  by blast\n\nlemma \"(\\<exists>x. P \\<longrightarrow> Q(x)) \\<longleftrightarrow> (P \\<longrightarrow> (\\<exists>x. Q(x)))\"\n  by blast\n\nlemma \"(\\<exists>x. P(x) \\<longrightarrow> Q) \\<longleftrightarrow> (\\<forall>x. P(x)) \\<longrightarrow> Q\"\n  by blast\n\nlemma \"(\\<forall>x. P(x)) \\<or> Q \\<longleftrightarrow> (\\<forall>x. P(x) \\<or> Q)\"\n  by blast\n\ntext\\<open>Discussed in Avron, Gentzen-Type Systems, Resolution and Tableaux,\n  JAR 10 (265-281), 1993.  Proof is trivial!\\<close>\nlemma \"\\<not> ((\\<exists>x. \\<not> P(x)) \\<and> ((\\<exists>x. P(x)) \\<or> (\\<exists>x. P(x) \\<and> Q(x))) \\<and> \\<not> (\\<exists>x. P(x)))\"\n  by blast\n\n\nsubsection \\<open>Problems requiring quantifier duplication\\<close>\n\ntext\\<open>Theorem B of Peter Andrews, Theorem Proving via General Matings,\n  JACM 28 (1981).\\<close>\nlemma \"(\\<exists>x. \\<forall>y. P(x) \\<longleftrightarrow> P(y)) \\<longrightarrow> ((\\<exists>x. P(x)) \\<longleftrightarrow> (\\<forall>y. P(y)))\"\n  by blast\n\ntext\\<open>Needs multiple instantiation of ALL.\\<close>\nlemma \"(\\<forall>x. P(x) \\<longrightarrow> P(f(x))) \\<and> P(d) \\<longrightarrow> P(f(f(f(d))))\"\n  by blast\n\ntext\\<open>Needs double instantiation of the quantifier\\<close>\nlemma \"\\<exists>x. P(x) \\<longrightarrow> P(a) \\<and> P(b)\"\n  by blast\n\nlemma \"\\<exists>z. P(z) \\<longrightarrow> (\\<forall>x. P(x))\"\n  by blast\n\nlemma \"\\<exists>x. (\\<exists>y. P(y)) \\<longrightarrow> P(x)\"\n  by blast\n\ntext\\<open>V. Lifschitz, What Is the Inverse Method?, JAR 5 (1989), 1--23. NOT PROVED.\\<close>\nlemma\n  \"\\<exists>x x'. \\<forall>y. \\<exists>z z'.\n    (\\<not> P(y,y) \\<or> P(x,x) \\<or> \\<not> S(z,x)) \\<and>\n    (S(x,y) \\<or> \\<not> S(y,z) \\<or> Q(z',z')) \\<and>\n    (Q(x',y) \\<or> \\<not> Q(y,z') \\<or> S(x',x'))\"\n  oops\n\n\nsubsection \\<open>Hard examples with quantifiers\\<close>\n\ntext\\<open>18\\<close>\nlemma \"\\<exists>y. \\<forall>x. P(y) \\<longrightarrow> P(x)\"\n  by blast\n\ntext\\<open>19\\<close>\nlemma \"\\<exists>x. \\<forall>y z. (P(y) \\<longrightarrow> Q(z)) \\<longrightarrow> (P(x) \\<longrightarrow> Q(x))\"\n  by blast\n\ntext\\<open>20\\<close>\nlemma \"(\\<forall>x y. \\<exists>z. \\<forall>w. (P(x) \\<and> Q(y) \\<longrightarrow> R(z) \\<and> S(w)))\n  \\<longrightarrow> (\\<exists>x y. P(x) \\<and> Q(y)) \\<longrightarrow> (\\<exists>z. R(z))\"\n  by blast\n\ntext\\<open>21\\<close>\nlemma \"(\\<exists>x. P \\<longrightarrow> Q(x)) \\<and> (\\<exists>x. Q(x) \\<longrightarrow> P) \\<longrightarrow> (\\<exists>x. P \\<longleftrightarrow> Q(x))\"\n  by blast\n\ntext\\<open>22\\<close>\nlemma \"(\\<forall>x. P \\<longleftrightarrow> Q(x)) \\<longrightarrow> (P \\<longleftrightarrow> (\\<forall>x. Q(x)))\"\n  by blast\n\ntext\\<open>23\\<close>\nlemma \"(\\<forall>x. P \\<or> Q(x)) \\<longleftrightarrow> (P \\<or> (\\<forall>x. Q(x)))\"\n  by blast\n\ntext\\<open>24\\<close>\nlemma\n  \"\\<not> (\\<exists>x. S(x) \\<and> Q(x)) \\<and> (\\<forall>x. P(x) \\<longrightarrow> Q(x) \\<or> R(x)) \\<and>\n    (\\<not> (\\<exists>x. P(x)) \\<longrightarrow> (\\<exists>x. Q(x))) \\<and> (\\<forall>x. Q(x) \\<or> R(x) \\<longrightarrow> S(x))\n    \\<longrightarrow> (\\<exists>x. P(x) \\<and> R(x))\"\n  by blast\n\ntext\\<open>25\\<close>\nlemma\n  \"(\\<exists>x. P(x)) \\<and>\n    (\\<forall>x. L(x) \\<longrightarrow> \\<not> (M(x) \\<and> R(x))) \\<and>\n    (\\<forall>x. P(x) \\<longrightarrow> (M(x) \\<and> L(x))) \\<and>\n    ((\\<forall>x. P(x) \\<longrightarrow> Q(x)) \\<or> (\\<exists>x. P(x) \\<and> R(x)))\n    \\<longrightarrow> (\\<exists>x. Q(x) \\<and> P(x))\"\n  by blast\n\ntext\\<open>26\\<close>\nlemma\n  \"((\\<exists>x. p(x)) \\<longleftrightarrow> (\\<exists>x. q(x))) \\<and>\n    (\\<forall>x. \\<forall>y. p(x) \\<and> q(y) \\<longrightarrow> (r(x) \\<longleftrightarrow> s(y)))\n  \\<longrightarrow> ((\\<forall>x. p(x) \\<longrightarrow> r(x)) \\<longleftrightarrow> (\\<forall>x. q(x) \\<longrightarrow> s(x)))\"\n  by blast\n\ntext\\<open>27\\<close>\nlemma\n  \"(\\<exists>x. P(x) \\<and> \\<not> Q(x)) \\<and>\n    (\\<forall>x. P(x) \\<longrightarrow> R(x)) \\<and>\n    (\\<forall>x. M(x) \\<and> L(x) \\<longrightarrow> P(x)) \\<and>\n    ((\\<exists>x. R(x) \\<and> \\<not> Q(x)) \\<longrightarrow> (\\<forall>x. L(x) \\<longrightarrow> \\<not> R(x)))\n  \\<longrightarrow> (\\<forall>x. M(x) \\<longrightarrow> \\<not> L(x))\"\n  by blast\n\ntext\\<open>28. AMENDED\\<close>\nlemma\n  \"(\\<forall>x. P(x) \\<longrightarrow> (\\<forall>x. Q(x))) \\<and>\n    ((\\<forall>x. Q(x) \\<or> R(x)) \\<longrightarrow> (\\<exists>x. Q(x) \\<and> S(x))) \\<and>\n    ((\\<exists>x. S(x)) \\<longrightarrow> (\\<forall>x. L(x) \\<longrightarrow> M(x)))\n  \\<longrightarrow> (\\<forall>x. P(x) \\<and> L(x) \\<longrightarrow> M(x))\"\n  by blast\n\ntext\\<open>29. Essentially the same as Principia Mathematica *11.71\\<close>\nlemma\n  \"(\\<exists>x. P(x)) \\<and> (\\<exists>y. Q(y))\n    \\<longrightarrow> ((\\<forall>x. P(x) \\<longrightarrow> R(x)) \\<and> (\\<forall>y. Q(y) \\<longrightarrow> S(y)) \\<longleftrightarrow>\n      (\\<forall>x y. P(x) \\<and> Q(y) \\<longrightarrow> R(x) \\<and> S(y)))\"\n  by blast\n\ntext\\<open>30\\<close>\nlemma\n  \"(\\<forall>x. P(x) \\<or> Q(x) \\<longrightarrow> \\<not> R(x)) \\<and>\n    (\\<forall>x. (Q(x) \\<longrightarrow> \\<not> S(x)) \\<longrightarrow> P(x) \\<and> R(x))\n    \\<longrightarrow> (\\<forall>x. S(x))\"\n  by blast\n\ntext\\<open>31\\<close>\nlemma\n  \"\\<not> (\\<exists>x. P(x) \\<and> (Q(x) \\<or> R(x))) \\<and>\n    (\\<exists>x. L(x) \\<and> P(x)) \\<and>\n    (\\<forall>x. \\<not> R(x) \\<longrightarrow> M(x))\n  \\<longrightarrow> (\\<exists>x. L(x) \\<and> M(x))\"\n  by blast\n\ntext\\<open>32\\<close>\nlemma\n  \"(\\<forall>x. P(x) \\<and> (Q(x) \\<or> R(x)) \\<longrightarrow> S(x)) \\<and>\n    (\\<forall>x. S(x) \\<and> R(x) \\<longrightarrow> L(x)) \\<and>\n    (\\<forall>x. M(x) \\<longrightarrow> R(x))\n  \\<longrightarrow> (\\<forall>x. P(x) \\<and> M(x) \\<longrightarrow> L(x))\"\n  by blast\n\ntext\\<open>33\\<close>\nlemma\n  \"(\\<forall>x. P(a) \\<and> (P(x) \\<longrightarrow> P(b)) \\<longrightarrow> P(c)) \\<longleftrightarrow>\n    (\\<forall>x. (\\<not> P(a) \\<or> P(x) \\<or> P(c)) \\<and> (\\<not> P(a) \\<or> \\<not> P(b) \\<or> P(c)))\"\n  by blast\n\ntext\\<open>34. AMENDED (TWICE!!). Andrews's challenge.\\<close>\nlemma\n  \"((\\<exists>x. \\<forall>y. p(x) \\<longleftrightarrow> p(y)) \\<longleftrightarrow> ((\\<exists>x. q(x)) \\<longleftrightarrow> (\\<forall>y. p(y)))) \\<longleftrightarrow>\n    ((\\<exists>x. \\<forall>y. q(x) \\<longleftrightarrow> q(y)) \\<longleftrightarrow> ((\\<exists>x. p(x)) \\<longleftrightarrow> (\\<forall>y. q(y))))\"\n  by blast\n\ntext\\<open>35\\<close>\nlemma \"\\<exists>x y. P(x,y) \\<longrightarrow> (\\<forall>u v. P(u,v))\"\n  by blast\n\ntext\\<open>36\\<close>\nlemma\n  \"(\\<forall>x. \\<exists>y. J(x,y)) \\<and>\n    (\\<forall>x. \\<exists>y. G(x,y)) \\<and>\n    (\\<forall>x y. J(x,y) \\<or> G(x,y) \\<longrightarrow> (\\<forall>z. J(y,z) \\<or> G(y,z) \\<longrightarrow> H(x,z)))\n  \\<longrightarrow> (\\<forall>x. \\<exists>y. H(x,y))\"\n  by blast\n\ntext\\<open>37\\<close>\nlemma\n  \"(\\<forall>z. \\<exists>w. \\<forall>x. \\<exists>y.\n    (P(x,z) \\<longrightarrow> P(y,w)) \\<and> P(y,z) \\<and> (P(y,w) \\<longrightarrow> (\\<exists>u. Q(u,w)))) \\<and>\n    (\\<forall>x z. \\<not> P(x,z) \\<longrightarrow> (\\<exists>y. Q(y,z))) \\<and>\n    ((\\<exists>x y. Q(x,y)) \\<longrightarrow> (\\<forall>x. R(x,x)))\n  \\<longrightarrow> (\\<forall>x. \\<exists>y. R(x,y))\"\n  by blast\n\ntext\\<open>38\\<close>\nlemma\n  \"(\\<forall>x. p(a) \\<and> (p(x) \\<longrightarrow> (\\<exists>y. p(y) \\<and> r(x,y))) \\<longrightarrow>\n    (\\<exists>z. \\<exists>w. p(z) \\<and> r(x,w) \\<and> r(w,z)))  \\<longleftrightarrow>\n    (\\<forall>x. (\\<not> p(a) \\<or> p(x) \\<or> (\\<exists>z. \\<exists>w. p(z) \\<and> r(x,w) \\<and> r(w,z))) \\<and>\n      (\\<not> p(a) \\<or> \\<not> (\\<exists>y. p(y) \\<and> r(x,y)) \\<or>\n      (\\<exists>z. \\<exists>w. p(z) \\<and> r(x,w) \\<and> r(w,z))))\"\n  by blast\n\ntext\\<open>39\\<close>\nlemma \"\\<not> (\\<exists>x. \\<forall>y. F(y,x) \\<longleftrightarrow> \\<not> F(y,y))\"\n  by blast\n\ntext\\<open>40. AMENDED\\<close>\nlemma\n  \"(\\<exists>y. \\<forall>x. F(x,y) \\<longleftrightarrow> F(x,x)) \\<longrightarrow>\n    \\<not> (\\<forall>x. \\<exists>y. \\<forall>z. F(z,y) \\<longleftrightarrow> \\<not> F(z,x))\"\n  by blast\n\ntext\\<open>41\\<close>\nlemma\n  \"(\\<forall>z. \\<exists>y. \\<forall>x. f(x,y) \\<longleftrightarrow> f(x,z) \\<and> \\<not> f(x,x))\n    \\<longrightarrow> \\<not> (\\<exists>z. \\<forall>x. f(x,z))\"\n  by blast\n\ntext\\<open>42\\<close>\nlemma \"\\<not> (\\<exists>y. \\<forall>x. p(x,y) \\<longleftrightarrow> \\<not> (\\<exists>z. p(x,z) \\<and> p(z,x)))\"\n  by blast\n\ntext\\<open>43\\<close>\nlemma\n  \"(\\<forall>x. \\<forall>y. q(x,y) \\<longleftrightarrow> (\\<forall>z. p(z,x) \\<longleftrightarrow> p(z,y)))\n    \\<longrightarrow> (\\<forall>x. \\<forall>y. q(x,y) \\<longleftrightarrow> q(y,x))\"\n  by blast\n\ntext \\<open>\n  Other proofs: Can use \\<open>auto\\<close>, which cheats by using rewriting!\n  \\<open>Deepen_tac\\<close> alone requires 253 secs.  Or\n  \\<open>by (mini_tac 1 THEN Deepen_tac 5 1)\\<close>.\n\\<close>\n\ntext\\<open>44\\<close>\nlemma\n  \"(\\<forall>x. f(x) \\<longrightarrow> (\\<exists>y. g(y) \\<and> h(x,y) \\<and> (\\<exists>y. g(y) \\<and> \\<not> h(x,y)))) \\<and>\n    (\\<exists>x. j(x) \\<and> (\\<forall>y. g(y) \\<longrightarrow> h(x,y)))\n  \\<longrightarrow> (\\<exists>x. j(x) \\<and> \\<not> f(x))\"\n  by blast\n\ntext\\<open>45\\<close>\nlemma\n  \"(\\<forall>x. f(x) \\<and> (\\<forall>y. g(y) \\<and> h(x,y) \\<longrightarrow> j(x,y))\n      \\<longrightarrow> (\\<forall>y. g(y) \\<and> h(x,y) \\<longrightarrow> k(y))) \\<and>\n      \\<not> (\\<exists>y. l(y) \\<and> k(y)) \\<and>\n      (\\<exists>x. f(x) \\<and> (\\<forall>y. h(x,y) \\<longrightarrow> l(y)) \\<and> (\\<forall>y. g(y) \\<and> h(x,y) \\<longrightarrow> j(x,y)))\n      \\<longrightarrow> (\\<exists>x. f(x) \\<and> \\<not> (\\<exists>y. g(y) \\<and> h(x,y)))\"\n  by blast\n\n\ntext\\<open>46\\<close>\nlemma\n  \"(\\<forall>x. f(x) \\<and> (\\<forall>y. f(y) \\<and> h(y,x) \\<longrightarrow> g(y)) \\<longrightarrow> g(x)) \\<and>\n      ((\\<exists>x. f(x) \\<and> \\<not> g(x)) \\<longrightarrow>\n       (\\<exists>x. f(x) \\<and> \\<not> g(x) \\<and> (\\<forall>y. f(y) \\<and> \\<not> g(y) \\<longrightarrow> j(x,y)))) \\<and>\n      (\\<forall>x y. f(x) \\<and> f(y) \\<and> h(x,y) \\<longrightarrow> \\<not> j(y,x))\n      \\<longrightarrow> (\\<forall>x. f(x) \\<longrightarrow> g(x))\"\n  by blast\n\n\nsubsection \\<open>Problems (mainly) involving equality or functions\\<close>\n\ntext\\<open>48\\<close>\nlemma \"(a = b \\<or> c = d) \\<and> (a = c \\<or> b = d) \\<longrightarrow> a = d \\<or> b = c\"\n  by blast\n\ntext\\<open>49. NOT PROVED AUTOMATICALLY. Hard because it involves substitution for\n  Vars; the type constraint ensures that x,y,z have the same type as a,b,u.\\<close>\nlemma\n  \"(\\<exists>x y::'a. \\<forall>z. z = x \\<or> z = y) \\<and> P(a) \\<and> P(b) \\<and> a \\<noteq> b \\<longrightarrow> (\\<forall>u::'a. P(u))\"\n  apply safe\n  apply (rule_tac x = a in allE, assumption)\n  apply (rule_tac x = b in allE, assumption)\n  apply fast  \\<comment> \\<open>blast's treatment of equality can't do it\\<close>\n  done\n\ntext\\<open>50. (What has this to do with equality?)\\<close>\nlemma \"(\\<forall>x. P(a,x) \\<or> (\\<forall>y. P(x,y))) \\<longrightarrow> (\\<exists>x. \\<forall>y. P(x,y))\"\n  by blast\n\ntext\\<open>51\\<close>\nlemma\n  \"(\\<exists>z w. \\<forall>x y. P(x,y) \\<longleftrightarrow> (x = z \\<and> y = w)) \\<longrightarrow>\n    (\\<exists>z. \\<forall>x. \\<exists>w. (\\<forall>y. P(x,y) \\<longleftrightarrow> y=w) \\<longleftrightarrow> x = z)\"\n  by blast\n\ntext\\<open>52\\<close>\ntext\\<open>Almost the same as 51.\\<close>\nlemma\n  \"(\\<exists>z w. \\<forall>x y. P(x,y) \\<longleftrightarrow> (x = z \\<and> y = w)) \\<longrightarrow>\n    (\\<exists>w. \\<forall>y. \\<exists>z. (\\<forall>x. P(x,y) \\<longleftrightarrow> x = z) \\<longleftrightarrow> y = w)\"\n  by blast\n\ntext\\<open>55\\<close>\ntext\\<open>Non-equational version, from Manthey and Bry, CADE-9 (Springer, 1988).\n  fast DISCOVERS who killed Agatha.\\<close>\nschematic_goal\n  \"lives(agatha) \\<and> lives(butler) \\<and> lives(charles) \\<and>\n   (killed(agatha,agatha) \\<or> killed(butler,agatha) \\<or> killed(charles,agatha)) \\<and>\n   (\\<forall>x y. killed(x,y) \\<longrightarrow> hates(x,y) \\<and> \\<not> richer(x,y)) \\<and>\n   (\\<forall>x. hates(agatha,x) \\<longrightarrow> \\<not> hates(charles,x)) \\<and>\n   (hates(agatha,agatha) \\<and> hates(agatha,charles)) \\<and>\n   (\\<forall>x. lives(x) \\<and> \\<not> richer(x,agatha) \\<longrightarrow> hates(butler,x)) \\<and>\n   (\\<forall>x. hates(agatha,x) \\<longrightarrow> hates(butler,x)) \\<and>\n   (\\<forall>x. \\<not> hates(x,agatha) \\<or> \\<not> hates(x,butler) \\<or> \\<not> hates(x,charles)) \\<longrightarrow>\n    killed(?who,agatha)\"\n  by fast  \\<comment> \\<open>MUCH faster than blast\\<close>\n\n\ntext\\<open>56\\<close>\nlemma \"(\\<forall>x. (\\<exists>y. P(y) \\<and> x = f(y)) \\<longrightarrow> P(x)) \\<longleftrightarrow> (\\<forall>x. P(x) \\<longrightarrow> P(f(x)))\"\n  by blast\n\ntext\\<open>57\\<close>\nlemma\n  \"P(f(a,b), f(b,c)) \\<and> P(f(b,c), f(a,c)) \\<and>\n    (\\<forall>x y z. P(x,y) \\<and> P(y,z) \\<longrightarrow> P(x,z)) \\<longrightarrow> P(f(a,b), f(a,c))\"\n  by blast\n\ntext\\<open>58  NOT PROVED AUTOMATICALLY\\<close>\nlemma \"(\\<forall>x y. f(x) = g(y)) \\<longrightarrow> (\\<forall>x y. f(f(x)) = f(g(y)))\"\n  by (slow elim: subst_context)\n\n\ntext\\<open>59\\<close>\nlemma \"(\\<forall>x. P(x) \\<longleftrightarrow> \\<not> P(f(x))) \\<longrightarrow> (\\<exists>x. P(x) \\<and> \\<not> P(f(x)))\"\n  by blast\n\ntext\\<open>60\\<close>\nlemma \"\\<forall>x. P(x,f(x)) \\<longleftrightarrow> (\\<exists>y. (\\<forall>z. P(z,y) \\<longrightarrow> P(z,f(x))) \\<and> P(x,y))\"\n  by blast\n\ntext\\<open>62 as corrected in JAR 18 (1997), page 135\\<close>\nlemma\n  \"(\\<forall>x. p(a) \\<and> (p(x) \\<longrightarrow> p(f(x))) \\<longrightarrow> p(f(f(x)))) \\<longleftrightarrow>\n    (\\<forall>x. (\\<not> p(a) \\<or> p(x) \\<or> p(f(f(x)))) \\<and>\n      (\\<not> p(a) \\<or> \\<not> p(f(x)) \\<or> p(f(f(x)))))\"\n  by blast\n\ntext \\<open>From Davis, Obvious Logical Inferences, IJCAI-81, 530-531\n  fast indeed copes!\\<close>\nlemma\n  \"(\\<forall>x. F(x) \\<and> \\<not> G(x) \\<longrightarrow> (\\<exists>y. H(x,y) \\<and> J(y))) \\<and>\n    (\\<exists>x. K(x) \\<and> F(x) \\<and> (\\<forall>y. H(x,y) \\<longrightarrow> K(y))) \\<and>\n    (\\<forall>x. K(x) \\<longrightarrow> \\<not> G(x)) \\<longrightarrow> (\\<exists>x. K(x) \\<and> J(x))\"\n  by fast\n\ntext \\<open>From Rudnicki, Obvious Inferences, JAR 3 (1987), 383-393.\n  It does seem obvious!\\<close>\nlemma\n  \"(\\<forall>x. F(x) \\<and> \\<not> G(x) \\<longrightarrow> (\\<exists>y. H(x,y) \\<and> J(y))) \\<and>\n    (\\<exists>x. K(x) \\<and> F(x) \\<and> (\\<forall>y. H(x,y) \\<longrightarrow> K(y))) \\<and>\n    (\\<forall>x. K(x) \\<longrightarrow> \\<not> G(x)) \\<longrightarrow> (\\<exists>x. K(x) \\<longrightarrow> \\<not> G(x))\"\n  by fast\n\ntext \\<open>Halting problem: Formulation of Li Dafa (AAR Newsletter 27, Oct 1994.)\n  author U. Egly.\\<close>\nlemma\n  \"((\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z)))) \\<longrightarrow>\n     (\\<exists>w. C(w) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(w,y,z)))))\n    \\<and>\n    (\\<forall>w. C(w) \\<and> (\\<forall>u. C(u) \\<longrightarrow> (\\<forall>v. D(w,u,v))) \\<longrightarrow>\n          (\\<forall>y z.\n              (C(y) \\<and> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,g)) \\<and>\n              (C(y) \\<and> \\<not> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,b))))\n    \\<and>\n    (\\<forall>w. C(w) \\<and>\n      (\\<forall>y z.\n          (C(y) \\<and> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,g)) \\<and>\n          (C(y) \\<and> \\<not> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,b))) \\<longrightarrow>\n      (\\<exists>v. C(v) \\<and>\n            (\\<forall>y. ((C(y) \\<and> Q(w,y,y)) \\<and> OO(w,g) \\<longrightarrow> \\<not> P(v,y)) \\<and>\n                    ((C(y) \\<and> Q(w,y,y)) \\<and> OO(w,b) \\<longrightarrow> P(v,y) \\<and> OO(v,b)))))\n     \\<longrightarrow> \\<not> (\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z))))\"\n  by (blast 12)\n    \\<comment> \\<open>Needed because the search for depths below 12 is very slow.\\<close>\n\n\ntext \\<open>\n  Halting problem II: credited to M. Bruschi by Li Dafa in JAR 18(1),\n  p. 105.\n\\<close>\nlemma\n  \"((\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z)))) \\<longrightarrow>\n     (\\<exists>w. C(w) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(w,y,z)))))\n    \\<and>\n    (\\<forall>w. C(w) \\<and> (\\<forall>u. C(u) \\<longrightarrow> (\\<forall>v. D(w,u,v))) \\<longrightarrow>\n          (\\<forall>y z.\n              (C(y) \\<and> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,g)) \\<and>\n              (C(y) \\<and> \\<not> P(y,z) \\<longrightarrow> Q(w,y,z) \\<and> OO(w,b))))\n    \\<and>\n    ((\\<exists>w. C(w) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> Q(w,y,y) \\<and> OO(w,g)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> Q(w,y,y) \\<and> OO(w,b))))\n     \\<longrightarrow>\n     (\\<exists>v. C(v) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,g)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,b)))))\n    \\<longrightarrow>\n    ((\\<exists>v. C(v) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,g)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> P(v,y) \\<and> OO(v,b))))\n     \\<longrightarrow>\n     (\\<exists>u. C(u) \\<and> (\\<forall>y. (C(y) \\<and> P(y,y) \\<longrightarrow> \\<not> P(u,y)) \\<and>\n                           (C(y) \\<and> \\<not> P(y,y) \\<longrightarrow> P(u,y) \\<and> OO(u,b)))))\n     \\<longrightarrow> \\<not> (\\<exists>x. A(x) \\<and> (\\<forall>y. C(y) \\<longrightarrow> (\\<forall>z. D(x,y,z))))\"\n  by blast\n\ntext \\<open>Challenge found on info-hol.\\<close>\nlemma \"\\<forall>x. \\<exists>v w. \\<forall>y z. P(x) \\<and> Q(y) \\<longrightarrow> (P(v) \\<or> R(w)) \\<and> (R(z) \\<longrightarrow> Q(v))\"\n  by blast\n\ntext \\<open>\n  Attributed to Lewis Carroll by S. G. Pulman. The first or last assumption\n  can be deleted.\\<close>\nlemma\n  \"(\\<forall>x. honest(x) \\<and> industrious(x) \\<longrightarrow> healthy(x)) \\<and>\n    \\<not> (\\<exists>x. grocer(x) \\<and> healthy(x)) \\<and>\n    (\\<forall>x. industrious(x) \\<and> grocer(x) \\<longrightarrow> honest(x)) \\<and>\n    (\\<forall>x. cyclist(x) \\<longrightarrow> industrious(x)) \\<and>\n    (\\<forall>x. \\<not> healthy(x) \\<and> cyclist(x) \\<longrightarrow> \\<not> honest(x))\n    \\<longrightarrow> (\\<forall>x. grocer(x) \\<longrightarrow> \\<not> cyclist(x))\"\n  by blast\n\n\n(*Runtimes for old versions of this file:\nThu Jul 23 1992: loaded in 467s using iffE [on SPARC2]\nMon Nov 14 1994: loaded in 144s [on SPARC10, with deepen_tac]\nWed Nov 16 1994: loaded in 138s [after addition of norm_term_skip]\nMon Nov 21 1994: loaded in 131s [DEPTH_FIRST suppressing repetitions]\n\nFurther runtimes on a Sun-4\nTue Mar  4 1997: loaded in 93s (version 94-7)\nTue Mar  4 1997: loaded in 89s\nThu Apr  3 1997: loaded in 44s--using mostly Blast_tac\nThu Apr  3 1997: loaded in 96s--addition of two Halting Probs\nThu Apr  3 1997: loaded in 98s--using lim-1 for all haz rules\nTue Dec  2 1997: loaded in 107s--added 46; new equalSubst\nFri Dec 12 1997: loaded in 91s--faster proof reconstruction\nThu Dec 18 1997: loaded in 94s--two new \"obvious theorems\" (??)\n*)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/FOL/ex/Classical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.8824278726384089, "lm_q1q2_score": 0.7650965119282422}}
{"text": "(*  Title:      HOL/Algebra/Bij.thy\n    Author:     Florian Kammueller, with new proofs by L C Paulson\n*)\n\ntheory Bij\nimports Group\nbegin\n\nsection \\<open>Bijections of a Set, Permutation and Automorphism Groups\\<close>\n\ndefinition\n  Bij :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n    \\<comment> \\<open>Only extensional functions, since otherwise we get too many.\\<close>\n   where \"Bij S = extensional S \\<inter> {f. bij_betw f S S}\"\n\ndefinition\n  BijGroup :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"BijGroup S =\n    \\<lparr>carrier = Bij S,\n     mult = \\<lambda>g \\<in> Bij S. \\<lambda>f \\<in> Bij S. compose S g f,\n     one = \\<lambda>x \\<in> S. x\\<rparr>\"\n\n\ndeclare Id_compose [simp] compose_Id [simp]\n\nlemma Bij_imp_extensional: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> extensional S\"\n  by (simp add: Bij_def)\n\nlemma Bij_imp_funcset: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> S \\<rightarrow> S\"\n  by (auto simp add: Bij_def bij_betw_imp_funcset)\n\n\nsubsection \\<open>Bijections Form a Group\\<close>\n\nlemma restrict_inv_into_Bij: \"f \\<in> Bij S \\<Longrightarrow> (\\<lambda>x \\<in> S. (inv_into S f) x) \\<in> Bij S\"\n  by (simp add: Bij_def bij_betw_inv_into)\n\nlemma id_Bij: \"(\\<lambda>x\\<in>S. x) \\<in> Bij S \"\n  by (auto simp add: Bij_def bij_betw_def inj_on_def)\n\nlemma compose_Bij: \"\\<lbrakk>x \\<in> Bij S; y \\<in> Bij S\\<rbrakk> \\<Longrightarrow> compose S x y \\<in> Bij S\"\n  by (auto simp add: Bij_def bij_betw_compose) \n\nlemma Bij_compose_restrict_eq:\n     \"f \\<in> Bij S \\<Longrightarrow> compose S (restrict (inv_into S f) S) f = (\\<lambda>x\\<in>S. x)\"\n  by (simp add: Bij_def compose_inv_into_id)\n\ntheorem group_BijGroup: \"group (BijGroup S)\"\napply (simp add: BijGroup_def)\napply (rule groupI)\n    apply (simp add: compose_Bij)\n   apply (simp add: id_Bij)\n  apply (simp add: compose_Bij)\n  apply (blast intro: compose_assoc [symmetric] dest: Bij_imp_funcset)\n apply (simp add: id_Bij Bij_imp_funcset Bij_imp_extensional, simp)\napply (blast intro: Bij_compose_restrict_eq restrict_inv_into_Bij)\ndone\n\n\nsubsection\\<open>Automorphisms Form a Group\\<close>\n\nlemma Bij_inv_into_mem: \"\\<lbrakk> f \\<in> Bij S;  x \\<in> S\\<rbrakk> \\<Longrightarrow> inv_into S f x \\<in> S\"\nby (simp add: Bij_def bij_betw_def inv_into_into)\n\nlemma Bij_inv_into_lemma:\n assumes eq: \"\\<And>x y. \\<lbrakk>x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> h(g x y) = g (h x) (h y)\"\n shows \"\\<lbrakk>h \\<in> Bij S;  g \\<in> S \\<rightarrow> S \\<rightarrow> S;  x \\<in> S;  y \\<in> S\\<rbrakk>\n        \\<Longrightarrow> inv_into S h (g x y) = g (inv_into S h x) (inv_into S h y)\"\napply (simp add: Bij_def bij_betw_def)\napply (subgoal_tac \"\\<exists>x'\\<in>S. \\<exists>y'\\<in>S. x = h x' \\<and> y = h y'\", clarify)\n apply (simp add: eq [symmetric] inv_f_f funcset_mem [THEN funcset_mem], blast)\ndone\n\n\ndefinition\n  auto :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n  where \"auto G = hom G G \\<inter> Bij (carrier G)\"\n\ndefinition\n  AutoGroup :: \"('a, 'c) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"AutoGroup G = BijGroup (carrier G) \\<lparr>carrier := auto G\\<rparr>\"\n\nlemma (in group) id_in_auto: \"(\\<lambda>x \\<in> carrier G. x) \\<in> auto G\"\n  by (simp add: auto_def hom_def restrictI group.axioms id_Bij)\n\nlemma (in group) mult_funcset: \"mult G \\<in> carrier G \\<rightarrow> carrier G \\<rightarrow> carrier G\"\n  by (simp add:  Pi_I group.axioms)\n\nlemma (in group) restrict_inv_into_hom:\n      \"\\<lbrakk>h \\<in> hom G G; h \\<in> Bij (carrier G)\\<rbrakk>\n       \\<Longrightarrow> restrict (inv_into (carrier G) h) (carrier G) \\<in> hom G G\"\n  by (simp add: hom_def Bij_inv_into_mem restrictI mult_funcset\n                group.axioms Bij_inv_into_lemma)\n\nlemma inv_BijGroup:\n     \"f \\<in> Bij S \\<Longrightarrow> m_inv (BijGroup S) f = (\\<lambda>x \\<in> S. (inv_into S f) x)\"\napply (rule group.inv_equality)\napply (rule group_BijGroup)\napply (simp_all add:BijGroup_def restrict_inv_into_Bij Bij_compose_restrict_eq)\ndone\n\nlemma (in group) subgroup_auto:\n      \"subgroup (auto G) (BijGroup (carrier G))\"\nproof (rule subgroup.intro)\n  show \"auto G \\<subseteq> carrier (BijGroup (carrier G))\"\n    by (force simp add: auto_def BijGroup_def)\nnext\n  fix x y\n  assume \"x \\<in> auto G\" \"y \\<in> auto G\" \n  thus \"x \\<otimes>\\<^bsub>BijGroup (carrier G)\\<^esub> y \\<in> auto G\"\n    by (force simp add: BijGroup_def is_group auto_def Bij_imp_funcset \n                        group.hom_compose compose_Bij)\nnext\n  show \"\\<one>\\<^bsub>BijGroup (carrier G)\\<^esub> \\<in> auto G\" by (simp add:  BijGroup_def id_in_auto)\nnext\n  fix x \n  assume \"x \\<in> auto G\" \n  thus \"inv\\<^bsub>BijGroup (carrier G)\\<^esub> x \\<in> auto G\"\n    by (simp del: restrict_apply\n        add: inv_BijGroup auto_def restrict_inv_into_Bij restrict_inv_into_hom)\nqed\n\ntheorem (in group) AutoGroup: \"group (AutoGroup G)\"\nby (simp add: AutoGroup_def subgroup.subgroup_is_group subgroup_auto \n              group_BijGroup)\n\nend\n", "meta": {"author": "DeVilhena-Paulo", "repo": "GaloisCVC4", "sha": "7d7e0ea67f44a3655ad145650c4fd24b3c159fa8", "save_path": "github-repos/isabelle/DeVilhena-Paulo-GaloisCVC4", "path": "github-repos/isabelle/DeVilhena-Paulo-GaloisCVC4/GaloisCVC4-7d7e0ea67f44a3655ad145650c4fd24b3c159fa8/Bij.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7649670810965183}}
{"text": "theory BExp imports AExp begin\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\n\nvalue \"bval (Less (V ''x'') (Plus (N 3) (V ''y'')))\n            <''x'' := 3, ''y'' := 1>\"\n\n\ntext{* To improve automation: *}\n\nlemma bval_And_if[simp]:\n  \"bval (And b1 b2) s = (if bval b1 s then bval b2 s else False)\"\nby(simp)\n\ndeclare bval.simps(3)[simp del]  --\"remove the original eqn\"\n\n\nsubsection \"Constant Folding\"\n\ntext{* Optimizing constructors: *}\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\" |\n\"less a\\<^sub>1 a\\<^sub>2 = Less a\\<^sub>1 a\\<^sub>2\"\n\n\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply simp_all\ndone\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction b rule: not.induct)\napply simp_all\ndone\n\ntext{* Now the overall optimizer: *}\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\nvalue \"bsimp (And (Less (N 0) (N 1)) b)\"\n\nvalue \"bsimp (And (Less (N 1) (N 0)) (Bc True))\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply simp_all\ndone\n\nend\n", "meta": {"author": "HrNilsson", "repo": "concrete-semantics", "sha": "e8d4cb6a0be5dc004eae15a08b29d8fc4dba7184", "save_path": "github-repos/isabelle/HrNilsson-concrete-semantics", "path": "github-repos/isabelle/HrNilsson-concrete-semantics/concrete-semantics-e8d4cb6a0be5dc004eae15a08b29d8fc4dba7184/Demos/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8577680995361899, "lm_q1q2_score": 0.7649670606577362}}
{"text": "theory OrdQuants \n  imports Ordinal\nbegin\n\nsection \\<open>Restricted quantification on the ordinal part of the < relation\\<close>\n\nsyntax\n  \"_oall\" :: \"[pttrn, 'a, bool] \\<Rightarrow> bool\"  (\\<open>(3\\<forall>_<_./ _)\\<close> 10)\n  \"_oex\"  :: \"[pttrn, 'a, bool] \\<Rightarrow> bool\"  (\\<open>(3\\<exists>_<_./ _)\\<close> 10)\ntranslations\n  \"\\<forall>i<j. P\" \\<rightharpoonup> \"\\<forall>i:(CONST Ord). i < j \\<longrightarrow> P\"\n  \"\\<exists>i<j. P\" \\<rightharpoonup> \"\\<exists>i:(CONST Ord). i < j \\<and> P\"\n\n\ncontext Ordinal begin\n\nlemma oallI [intro!] : \n  \"(\\<And>i. i : Ord \\<Longrightarrow> i < j \\<Longrightarrow> Q i) \\<Longrightarrow> \\<forall>i < j. Q i\"\n   by auto\n\nlemma tallE [elim!]: \n  assumes \"\\<forall>i < j. Q i\"\n  obtains \"\\<And>i. (i : Ord \\<Longrightarrow> i < j \\<Longrightarrow> Q i)\"\n  using assms by auto\n\nlemma oallD [elim]: \n  \"\\<lbrakk> \\<forall>i < j. Q i ; i : Ord; i < j \\<rbrakk> \\<Longrightarrow> Q i\"\n  by auto\n\nlemma oexI [intro] : \n  \"\\<lbrakk> i : Ord ; i < j ; Q i \\<rbrakk> \\<Longrightarrow> \\<exists>i < j. Q i\"\n  by auto\n\nlemma oexE [elim!] : \n  assumes \"\\<exists>i < j. Q i\" \n  obtains i where \"i : Ord\" \"i < j\" \"Q i\"\n  using assms by auto\nend\nend", "meta": {"author": "ultra-group", "repo": "isabelle-gst", "sha": "e0ccdde0105eac05f3f4bbccdd58a9860e642eca", "save_path": "github-repos/isabelle/ultra-group-isabelle-gst", "path": "github-repos/isabelle/ultra-group-isabelle-gst/isabelle-gst-e0ccdde0105eac05f3f4bbccdd58a9860e642eca/src/Ordinal/OrdQuants.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8418256472515683, "lm_q1q2_score": 0.764897840857349}}
{"text": "(*  Title:      HOL/NSA/Filter.thy\n    Author:     Jacques D. Fleuriot, University of Cambridge\n    Author:     Lawrence C Paulson\n    Author:     Brian Huffman\n*) \n\nsection {* Filters and Ultrafilters *}\n\ntheory Filter\nimports \"~~/src/HOL/Library/Infinite_Set\"\nbegin\n\nsubsection {* Definitions and basic properties *}\n\nsubsubsection {* Filters *}\n\nlocale filter =\n  fixes F :: \"'a set set\"\n  assumes UNIV [iff]:  \"UNIV \\<in> F\"\n  assumes empty [iff]: \"{} \\<notin> F\"\n  assumes Int:         \"\\<lbrakk>u \\<in> F; v \\<in> F\\<rbrakk> \\<Longrightarrow> u \\<inter> v \\<in> F\"\n  assumes subset:      \"\\<lbrakk>u \\<in> F; u \\<subseteq> v\\<rbrakk> \\<Longrightarrow> v \\<in> F\"\nbegin\n\nlemma memD: \"A \\<in> F \\<Longrightarrow> - A \\<notin> F\"\nproof\n  assume \"A \\<in> F\" and \"- A \\<in> F\"\n  hence \"A \\<inter> (- A) \\<in> F\" by (rule Int)\n  thus \"False\" by simp\nqed\n\nlemma not_memI: \"- A \\<in> F \\<Longrightarrow> A \\<notin> F\"\nby (drule memD, simp)\n\nlemma Int_iff: \"(x \\<inter> y \\<in> F) = (x \\<in> F \\<and> y \\<in> F)\"\nby (auto elim: subset intro: Int)\n\nend\n\nsubsubsection {* Ultrafilters *}\n\nlocale ultrafilter = filter +\n  assumes ultra: \"A \\<in> F \\<or> - A \\<in> F\"\nbegin\n\nlemma memI: \"- A \\<notin> F \\<Longrightarrow> A \\<in> F\"\nusing ultra [of A] by simp\n\nlemma not_memD: \"A \\<notin> F \\<Longrightarrow> - A \\<in> F\"\nby (rule memI, simp)\n\nlemma not_mem_iff: \"(A \\<notin> F) = (- A \\<in> F)\"\nby (rule iffI [OF not_memD not_memI])\n\nlemma Compl_iff: \"(- A \\<in> F) = (A \\<notin> F)\"\nby (rule iffI [OF not_memI not_memD])\n\nlemma Un_iff: \"(x \\<union> y \\<in> F) = (x \\<in> F \\<or> y \\<in> F)\"\n apply (rule iffI)\n  apply (erule contrapos_pp)\n  apply (simp add: Int_iff not_mem_iff)\n apply (auto elim: subset)\ndone\n\nend\n\nsubsubsection {* Free Ultrafilters *}\n\nlocale freeultrafilter = ultrafilter +\n  assumes infinite: \"A \\<in> F \\<Longrightarrow> infinite A\"\nbegin\n\nlemma finite: \"finite A \\<Longrightarrow> A \\<notin> F\"\nby (erule contrapos_pn, erule infinite)\n\nlemma singleton: \"{x} \\<notin> F\"\nby (rule finite, simp)\n\nlemma insert_iff [simp]: \"(insert x A \\<in> F) = (A \\<in> F)\"\napply (subst insert_is_Un)\napply (subst Un_iff)\napply (simp add: singleton)\ndone\n\nlemma filter: \"filter F\" ..\n\nlemma ultrafilter: \"ultrafilter F\" ..\n\nend\n\nsubsection {* Collect properties *}\n\nlemma (in filter) Collect_ex:\n  \"({n. \\<exists>x. P n x} \\<in> F) = (\\<exists>X. {n. P n (X n)} \\<in> F)\"\nproof\n  assume \"{n. \\<exists>x. P n x} \\<in> F\"\n  hence \"{n. P n (SOME x. P n x)} \\<in> F\"\n    by (auto elim: someI subset)\n  thus \"\\<exists>X. {n. P n (X n)} \\<in> F\" by fast\nnext\n  show \"\\<exists>X. {n. P n (X n)} \\<in> F \\<Longrightarrow> {n. \\<exists>x. P n x} \\<in> F\"\n    by (auto elim: subset)\nqed\n\nlemma (in filter) Collect_conj:\n  \"({n. P n \\<and> Q n} \\<in> F) = ({n. P n} \\<in> F \\<and> {n. Q n} \\<in> F)\"\nby (subst Collect_conj_eq, rule Int_iff)\n\nlemma (in ultrafilter) Collect_not:\n  \"({n. \\<not> P n} \\<in> F) = ({n. P n} \\<notin> F)\"\nby (subst Collect_neg_eq, rule Compl_iff)\n\nlemma (in ultrafilter) Collect_disj:\n  \"({n. P n \\<or> Q n} \\<in> F) = ({n. P n} \\<in> F \\<or> {n. Q n} \\<in> F)\"\nby (subst Collect_disj_eq, rule Un_iff)\n\nlemma (in ultrafilter) Collect_all:\n  \"({n. \\<forall>x. P n x} \\<in> F) = (\\<forall>X. {n. P n (X n)} \\<in> F)\"\napply (rule Not_eq_iff [THEN iffD1])\napply (simp add: Collect_not [symmetric])\napply (rule Collect_ex)\ndone\n\nsubsection {* Maximal filter = Ultrafilter *}\n\ntext {*\n   A filter F is an ultrafilter iff it is a maximal filter,\n   i.e. whenever G is a filter and @{term \"F \\<subseteq> G\"} then @{term \"F = G\"}\n*}\ntext {*\n  Lemmas that shows existence of an extension to what was assumed to\n  be a maximal filter. Will be used to derive contradiction in proof of\n  property of ultrafilter.\n*}\n\nlemma extend_lemma1: \"UNIV \\<in> F \\<Longrightarrow> A \\<in> {X. \\<exists>f\\<in>F. A \\<inter> f \\<subseteq> X}\"\nby blast\n\nlemma extend_lemma2: \"F \\<subseteq> {X. \\<exists>f\\<in>F. A \\<inter> f \\<subseteq> X}\"\nby blast\n\nlemma (in filter) extend_filter:\nassumes A: \"- A \\<notin> F\"\nshows \"filter {X. \\<exists>f\\<in>F. A \\<inter> f \\<subseteq> X}\" (is \"filter ?X\")\nproof (rule filter.intro)\n  show \"UNIV \\<in> ?X\" by blast\nnext\n  show \"{} \\<notin> ?X\"\n  proof (clarify)\n    fix f assume f: \"f \\<in> F\" and Af: \"A \\<inter> f \\<subseteq> {}\"\n    from Af have fA: \"f \\<subseteq> - A\" by blast\n    from f fA have \"- A \\<in> F\" by (rule subset)\n    with A show \"False\" by simp\n  qed\nnext\n  fix u and v\n  assume u: \"u \\<in> ?X\" and v: \"v \\<in> ?X\"\n  from u obtain f where f: \"f \\<in> F\" and Af: \"A \\<inter> f \\<subseteq> u\" by blast\n  from v obtain g where g: \"g \\<in> F\" and Ag: \"A \\<inter> g \\<subseteq> v\" by blast\n  from f g have fg: \"f \\<inter> g \\<in> F\" by (rule Int)\n  from Af Ag have Afg: \"A \\<inter> (f \\<inter> g) \\<subseteq> u \\<inter> v\" by blast\n  from fg Afg show \"u \\<inter> v \\<in> ?X\" by blast\nnext\n  fix u and v\n  assume uv: \"u \\<subseteq> v\" and u: \"u \\<in> ?X\"\n  from u obtain f where f: \"f \\<in> F\" and Afu: \"A \\<inter> f \\<subseteq> u\" by blast\n  from Afu uv have Afv: \"A \\<inter> f \\<subseteq> v\" by blast\n  from f Afv have \"\\<exists>f\\<in>F. A \\<inter> f \\<subseteq> v\" by blast\n  thus \"v \\<in> ?X\" by simp\nqed\n\nlemma (in filter) max_filter_ultrafilter:\nassumes max: \"\\<And>G. \\<lbrakk>filter G; F \\<subseteq> G\\<rbrakk> \\<Longrightarrow> F = G\"\nshows \"ultrafilter_axioms F\"\nproof (rule ultrafilter_axioms.intro)\n  fix A show \"A \\<in> F \\<or> - A \\<in> F\"\n  proof (rule disjCI)\n    let ?X = \"{X. \\<exists>f\\<in>F. A \\<inter> f \\<subseteq> X}\"\n    assume AF: \"- A \\<notin> F\"\n    from AF have X: \"filter ?X\" by (rule extend_filter)\n    from UNIV have AX: \"A \\<in> ?X\" by (rule extend_lemma1)\n    have FX: \"F \\<subseteq> ?X\" by (rule extend_lemma2)\n    from X FX have \"F = ?X\" by (rule max)\n    with AX show \"A \\<in> F\" by simp\n  qed\nqed\n\nlemma (in ultrafilter) max_filter:\nassumes G: \"filter G\" and sub: \"F \\<subseteq> G\" shows \"F = G\"\nproof\n  show \"F \\<subseteq> G\" using sub .\n  show \"G \\<subseteq> F\"\n  proof\n    fix A assume A: \"A \\<in> G\"\n    from G A have \"- A \\<notin> G\" by (rule filter.memD)\n    with sub have B: \"- A \\<notin> F\" by blast\n    thus \"A \\<in> F\" by (rule memI)\n  qed\nqed\n\nsubsection {* Ultrafilter Theorem *}\n\ntext \"A local context makes proof of ultrafilter Theorem more modular\"\ncontext\n  fixes   frechet :: \"'a set set\"\n  and     superfrechet :: \"'a set set set\"\n\n  assumes infinite_UNIV: \"infinite (UNIV :: 'a set)\"\n\n  defines frechet_def: \"frechet \\<equiv> {A. finite (- A)}\"\n  and     superfrechet_def: \"superfrechet \\<equiv> {G. filter G \\<and> frechet \\<subseteq> G}\"\nbegin\n\nlemma superfrechetI:\n  \"\\<lbrakk>filter G; frechet \\<subseteq> G\\<rbrakk> \\<Longrightarrow> G \\<in> superfrechet\"\nby (simp add: superfrechet_def)\n\nlemma superfrechetD1:\n  \"G \\<in> superfrechet \\<Longrightarrow> filter G\"\nby (simp add: superfrechet_def)\n\nlemma superfrechetD2:\n  \"G \\<in> superfrechet \\<Longrightarrow> frechet \\<subseteq> G\"\nby (simp add: superfrechet_def)\n\ntext {* A few properties of free filters *}\n\nlemma filter_cofinite:\nassumes inf: \"infinite (UNIV :: 'a set)\"\nshows \"filter {A:: 'a set. finite (- A)}\" (is \"filter ?F\")\nproof (rule filter.intro)\n  show \"UNIV \\<in> ?F\" by simp\nnext\n  show \"{} \\<notin> ?F\" using inf by simp\nnext\n  fix u v assume \"u \\<in> ?F\" and \"v \\<in> ?F\"\n  thus \"u \\<inter> v \\<in> ?F\" by simp\nnext\n  fix u v assume uv: \"u \\<subseteq> v\" and u: \"u \\<in> ?F\"\n  from uv have vu: \"- v \\<subseteq> - u\" by simp\n  from u show \"v \\<in> ?F\"\n    by (simp add: finite_subset [OF vu])\nqed\n\ntext {*\n   We prove: 1. Existence of maximal filter i.e. ultrafilter;\n             2. Freeness property i.e ultrafilter is free.\n             Use a locale to prove various lemmas and then \n             export main result: The ultrafilter Theorem\n*}\n\nlemma filter_frechet: \"filter frechet\"\nby (unfold frechet_def, rule filter_cofinite [OF infinite_UNIV])\n\nlemma frechet_in_superfrechet: \"frechet \\<in> superfrechet\"\nby (rule superfrechetI [OF filter_frechet subset_refl])\n\nlemma lemma_mem_chain_filter:\n  \"\\<lbrakk>c \\<in> chains superfrechet; x \\<in> c\\<rbrakk> \\<Longrightarrow> filter x\"\nby (unfold chains_def superfrechet_def, blast)\n\n\nsubsubsection {* Unions of chains of superfrechets *}\n\ntext \"In this section we prove that superfrechet is closed\nwith respect to unions of non-empty chains. We must show\n  1) Union of a chain is a filter,\n  2) Union of a chain contains frechet.\n\nNumber 2 is trivial, but 1 requires us to prove all the filter rules.\"\n\nlemma Union_chain_UNIV:\n  \"\\<lbrakk>c \\<in> chains superfrechet; c \\<noteq> {}\\<rbrakk> \\<Longrightarrow> UNIV \\<in> \\<Union>c\"\nproof -\n  assume 1: \"c \\<in> chains superfrechet\" and 2: \"c \\<noteq> {}\"\n  from 2 obtain x where 3: \"x \\<in> c\" by blast\n  from 1 3 have \"filter x\" by (rule lemma_mem_chain_filter)\n  hence \"UNIV \\<in> x\" by (rule filter.UNIV)\n  with 3 show \"UNIV \\<in> \\<Union>c\" by blast\nqed\n\nlemma Union_chain_empty:\n  \"c \\<in> chains superfrechet \\<Longrightarrow> {} \\<notin> \\<Union>c\"\nproof\n  assume 1: \"c \\<in> chains superfrechet\" and 2: \"{} \\<in> \\<Union>c\"\n  from 2 obtain x where 3: \"x \\<in> c\" and 4: \"{} \\<in> x\" ..\n  from 1 3 have \"filter x\" by (rule lemma_mem_chain_filter)\n  hence \"{} \\<notin> x\" by (rule filter.empty)\n  with 4 show \"False\" by simp\nqed\n\nlemma Union_chain_Int:\n  \"\\<lbrakk>c \\<in> chains superfrechet; u \\<in> \\<Union>c; v \\<in> \\<Union>c\\<rbrakk> \\<Longrightarrow> u \\<inter> v \\<in> \\<Union>c\"\nproof -\n  assume c: \"c \\<in> chains superfrechet\"\n  assume \"u \\<in> \\<Union>c\"\n    then obtain x where ux: \"u \\<in> x\" and xc: \"x \\<in> c\" ..\n  assume \"v \\<in> \\<Union>c\"\n    then obtain y where vy: \"v \\<in> y\" and yc: \"y \\<in> c\" ..\n  from c xc yc have \"x \\<subseteq> y \\<or> y \\<subseteq> x\" using c unfolding chains_def chain_subset_def by auto\n  with xc yc have xyc: \"x \\<union> y \\<in> c\"\n    by (auto simp add: Un_absorb1 Un_absorb2)\n  with c have fxy: \"filter (x \\<union> y)\" by (rule lemma_mem_chain_filter)\n  from ux have uxy: \"u \\<in> x \\<union> y\" by simp\n  from vy have vxy: \"v \\<in> x \\<union> y\" by simp\n  from fxy uxy vxy have \"u \\<inter> v \\<in> x \\<union> y\" by (rule filter.Int)\n  with xyc show \"u \\<inter> v \\<in> \\<Union>c\" ..\nqed\n\nlemma Union_chain_subset:\n  \"\\<lbrakk>c \\<in> chains superfrechet; u \\<in> \\<Union>c; u \\<subseteq> v\\<rbrakk> \\<Longrightarrow> v \\<in> \\<Union>c\"\nproof -\n  assume c: \"c \\<in> chains superfrechet\"\n     and u: \"u \\<in> \\<Union>c\" and uv: \"u \\<subseteq> v\"\n  from u obtain x where ux: \"u \\<in> x\" and xc: \"x \\<in> c\" ..\n  from c xc have fx: \"filter x\" by (rule lemma_mem_chain_filter)\n  from fx ux uv have vx: \"v \\<in> x\" by (rule filter.subset)\n  with xc show \"v \\<in> \\<Union>c\" ..\nqed\n\nlemma Union_chain_filter:\nassumes chain: \"c \\<in> chains superfrechet\" and nonempty: \"c \\<noteq> {}\"\nshows \"filter (\\<Union>c)\" \nproof (rule filter.intro)\n  show \"UNIV \\<in> \\<Union>c\" using chain nonempty by (rule Union_chain_UNIV)\nnext\n  show \"{} \\<notin> \\<Union>c\" using chain by (rule Union_chain_empty)\nnext\n  fix u v assume \"u \\<in> \\<Union>c\" and \"v \\<in> \\<Union>c\"\n  with chain show \"u \\<inter> v \\<in> \\<Union>c\" by (rule Union_chain_Int)\nnext\n  fix u v assume \"u \\<in> \\<Union>c\" and \"u \\<subseteq> v\"\n  with chain show \"v \\<in> \\<Union>c\" by (rule Union_chain_subset)\nqed\n\nlemma lemma_mem_chain_frechet_subset:\n  \"\\<lbrakk>c \\<in> chains superfrechet; x \\<in> c\\<rbrakk> \\<Longrightarrow> frechet \\<subseteq> x\"\nby (unfold superfrechet_def chains_def, blast)\n\nlemma Union_chain_superfrechet:\n  \"\\<lbrakk>c \\<noteq> {}; c \\<in> chains superfrechet\\<rbrakk> \\<Longrightarrow> \\<Union>c \\<in> superfrechet\"\nproof (rule superfrechetI)\n  assume 1: \"c \\<in> chains superfrechet\" and 2: \"c \\<noteq> {}\"\n  thus \"filter (\\<Union>c)\" by (rule Union_chain_filter)\n  from 2 obtain x where 3: \"x \\<in> c\" by blast\n  from 1 3 have \"frechet \\<subseteq> x\" by (rule lemma_mem_chain_frechet_subset)\n  also from 3 have \"x \\<subseteq> \\<Union>c\" by blast\n  finally show \"frechet \\<subseteq> \\<Union>c\" .\nqed\n\nsubsubsection {* Existence of free ultrafilter *}\n\nlemma max_cofinite_filter_Ex:\n  \"\\<exists>U\\<in>superfrechet. \\<forall>G\\<in>superfrechet. U \\<subseteq> G \\<longrightarrow> G = U\" \nproof (rule Zorn_Lemma2, safe)\n  fix c assume c: \"c \\<in> chains superfrechet\"\n  show \"\\<exists>U\\<in>superfrechet. \\<forall>G\\<in>c. G \\<subseteq> U\" (is \"?U\")\n  proof (cases)\n    assume \"c = {}\"\n    with frechet_in_superfrechet show \"?U\" by blast\n  next\n    assume A: \"c \\<noteq> {}\"\n    from A c have \"\\<Union>c \\<in> superfrechet\"\n      by (rule Union_chain_superfrechet)\n    thus \"?U\" by blast\n  qed\nqed\n\nlemma mem_superfrechet_all_infinite:\n  \"\\<lbrakk>U \\<in> superfrechet; A \\<in> U\\<rbrakk> \\<Longrightarrow> infinite A\"\nproof\n  assume U: \"U \\<in> superfrechet\" and A: \"A \\<in> U\" and fin: \"finite A\"\n  from U have fil: \"filter U\" and fre: \"frechet \\<subseteq> U\"\n    by (simp_all add: superfrechet_def)\n  from fin have \"- A \\<in> frechet\" by (simp add: frechet_def)\n  with fre have cA: \"- A \\<in> U\" by (rule subsetD)\n  from fil A cA have \"A \\<inter> - A \\<in> U\" by (rule filter.Int)\n  with fil show \"False\" by (simp add: filter.empty)\nqed\n\ntext {* There exists a free ultrafilter on any infinite set *}\n\nlemma freeultrafilter_Ex:\n  \"\\<exists>U::'a set set. freeultrafilter U\"\nproof -\n  from max_cofinite_filter_Ex obtain U\n    where U: \"U \\<in> superfrechet\"\n      and max [rule_format]: \"\\<forall>G\\<in>superfrechet. U \\<subseteq> G \\<longrightarrow> G = U\" ..\n  from U have fil: \"filter U\" by (rule superfrechetD1)\n  from U have fre: \"frechet \\<subseteq> U\" by (rule superfrechetD2)\n  have ultra: \"ultrafilter_axioms U\"\n  proof (rule filter.max_filter_ultrafilter [OF fil])\n    fix G assume G: \"filter G\" and UG: \"U \\<subseteq> G\"\n    from fre UG have \"frechet \\<subseteq> G\" by simp\n    with G have \"G \\<in> superfrechet\" by (rule superfrechetI)\n    from this UG show \"U = G\" by (rule max[symmetric])\n  qed\n  have free: \"freeultrafilter_axioms U\"\n  proof (rule freeultrafilter_axioms.intro)\n    fix A assume \"A \\<in> U\"\n    with U show \"infinite A\" by (rule mem_superfrechet_all_infinite)\n  qed\n  from fil ultra free have \"freeultrafilter U\"\n    by (rule freeultrafilter.intro [OF ultrafilter.intro])\n    (* FIXME: unfold_locales should use chained facts *)\n  then show ?thesis ..\nqed\n\nend\n\nhide_const (open) filter\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/NSA/Filter.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7648920864059976}}
{"text": "(*  Title:      HOL/HOLCF/Porder.thy\n    Author:     Franz Regensburger and Brian Huffman\n*)\n\nsection \\<open>Partial orders\\<close>\n\ntheory Porder\n  imports MainRLT\nbegin\n\ndeclare [[typedef_overloaded]]\n\n\nsubsection \\<open>Type class for partial orders\\<close>\n\nclass below =\n  fixes below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation (ASCII)\n  below (infix \"<<\" 50)\n\nnotation\n  below (infix \"\\<sqsubseteq>\" 50)\n\nabbreviation not_below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infix \"\\<notsqsubseteq>\" 50)\n  where \"not_below x y \\<equiv> \\<not> below x y\"\n\nnotation (ASCII)\n  not_below  (infix \"~<<\" 50)\n\nlemma below_eq_trans: \"a \\<sqsubseteq> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule subst)\n\nlemma eq_below_trans: \"a = b \\<Longrightarrow> b \\<sqsubseteq> c \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule ssubst)\n\nend\n\nclass po = below +\n  assumes below_refl [iff]: \"x \\<sqsubseteq> x\"\n  assumes below_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  assumes below_antisym: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma eq_imp_below: \"x = y \\<Longrightarrow> x \\<sqsubseteq> y\"\n  by simp\n\nlemma box_below: \"a \\<sqsubseteq> b \\<Longrightarrow> c \\<sqsubseteq> a \\<Longrightarrow> b \\<sqsubseteq> d \\<Longrightarrow> c \\<sqsubseteq> d\"\n  by (rule below_trans [OF below_trans])\n\nlemma po_eq_conv: \"x = y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\n  by (fast intro!: below_antisym)\n\nlemma rev_below_trans: \"y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> y \\<Longrightarrow> x \\<sqsubseteq> z\"\n  by (rule below_trans)\n\nlemma not_below2not_eq: \"x \\<notsqsubseteq> y \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nend\n\nlemmas HOLCF_trans_rules [trans] =\n  below_trans\n  below_antisym\n  below_eq_trans\n  eq_below_trans\n\ncontext po\nbegin\n\nsubsection \\<open>Upper bounds\\<close>\n\ndefinition is_ub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<|\" 55)\n  where \"S <| x \\<longleftrightarrow> (\\<forall>y\\<in>S. y \\<sqsubseteq> x)\"\n\nlemma is_ubI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> x \\<sqsubseteq> u) \\<Longrightarrow> S <| u\"\n  by (simp add: is_ub_def)\n\nlemma is_ubD: \"\\<lbrakk>S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  by (simp add: is_ub_def)\n\nlemma ub_imageI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<sqsubseteq> u) \\<Longrightarrow> (\\<lambda>x. f x) ` S <| u\"\n  unfolding is_ub_def by fast\n\nlemma ub_imageD: \"\\<lbrakk>f ` S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq> u\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeI: \"(\\<And>i. S i \\<sqsubseteq> x) \\<Longrightarrow> range S <| x\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeD: \"range S <| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_empty [simp]: \"{} <| u\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_insert [simp]: \"(insert x A) <| y = (x \\<sqsubseteq> y \\<and> A <| y)\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_upward: \"\\<lbrakk>S <| x; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> S <| y\"\n  unfolding is_ub_def by (fast intro: below_trans)\n\n\nsubsection \\<open>Least upper bounds\\<close>\n\ndefinition is_lub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<<|\" 55)\n  where \"S <<| x \\<longleftrightarrow> S <| x \\<and> (\\<forall>u. S <| u \\<longrightarrow> x \\<sqsubseteq> u)\"\n\ndefinition lub :: \"'a set \\<Rightarrow> 'a\"\n  where \"lub S = (THE x. S <<| x)\"\n\nend\n\nsyntax (ASCII)\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3LUB _:_./ _)\" [0,0, 10] 10)\n\nsyntax\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3\\<Squnion>_\\<in>_./ _)\" [0,0, 10] 10)\n\ntranslations\n  \"LUB x:A. t\" \\<rightleftharpoons> \"CONST lub ((\\<lambda>x. t) ` A)\"\n\ncontext po\nbegin\n\nabbreviation Lub  (binder \"\\<Squnion>\" 10)\n  where \"\\<Squnion>n. t n \\<equiv> lub (range t)\"\n\nnotation (ASCII)\n  Lub  (binder \"LUB \" 10)\n\ntext \\<open>access to some definition as inference rule\\<close>\n\nlemma is_lubD1: \"S <<| x \\<Longrightarrow> S <| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lubD2: \"\\<lbrakk>S <<| x; S <| u\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  unfolding is_lub_def by fast\n\nlemma is_lubI: \"\\<lbrakk>S <| x; \\<And>u. S <| u \\<Longrightarrow> x \\<sqsubseteq> u\\<rbrakk> \\<Longrightarrow> S <<| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lub_below_iff: \"S <<| x \\<Longrightarrow> x \\<sqsubseteq> u \\<longleftrightarrow> S <| u\"\n  unfolding is_lub_def is_ub_def by (metis below_trans)\n\ntext \\<open>lubs are unique\\<close>\n\nlemma is_lub_unique: \"S <<| x \\<Longrightarrow> S <<| y \\<Longrightarrow> x = y\"\n  unfolding is_lub_def is_ub_def by (blast intro: below_antisym)\n\ntext \\<open>technical lemmas about \\<^term>\\<open>lub\\<close> and \\<^term>\\<open>is_lub\\<close>\\<close>\n\nlemma is_lub_lub: \"M <<| x \\<Longrightarrow> M <<| lub M\"\n  unfolding lub_def by (rule theI [OF _ is_lub_unique])\n\nlemma lub_eqI: \"M <<| l \\<Longrightarrow> lub M = l\"\n  by (rule is_lub_unique [OF is_lub_lub])\n\nlemma is_lub_singleton [simp]: \"{x} <<| x\"\n  by (simp add: is_lub_def)\n\nlemma lub_singleton [simp]: \"lub {x} = x\"\n  by (rule is_lub_singleton [THEN lub_eqI])\n\nlemma is_lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> {x, y} <<| y\"\n  by (simp add: is_lub_def)\n\nlemma lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> lub {x, y} = y\"\n  by (rule is_lub_bin [THEN lub_eqI])\n\nlemma is_lub_maximal: \"S <| x \\<Longrightarrow> x \\<in> S \\<Longrightarrow> S <<| x\"\n  by (erule is_lubI, erule (1) is_ubD)\n\nlemma lub_maximal: \"S <| x \\<Longrightarrow> x \\<in> S \\<Longrightarrow> lub S = x\"\n  by (rule is_lub_maximal [THEN lub_eqI])\n\n\nsubsection \\<open>Countable chains\\<close>\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \\<comment> \\<open>Here we use countable chains and I prefer to code them as functions!\\<close>\n  \"chain Y = (\\<forall>i. Y i \\<sqsubseteq> Y (Suc i))\"\n\nlemma chainI: \"(\\<And>i. Y i \\<sqsubseteq> Y (Suc i)) \\<Longrightarrow> chain Y\"\n  unfolding chain_def by fast\n\nlemma chainE: \"chain Y \\<Longrightarrow> Y i \\<sqsubseteq> Y (Suc i)\"\n  unfolding chain_def by fast\n\ntext \\<open>chains are monotone functions\\<close>\n\nlemma chain_mono_less: \"chain Y \\<Longrightarrow> i < j \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (erule less_Suc_induct, erule chainE, erule below_trans)\n\nlemma chain_mono: \"chain Y \\<Longrightarrow> i \\<le> j \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (cases \"i = j\") (simp_all add: chain_mono_less)\n\nlemma chain_shift: \"chain Y \\<Longrightarrow> chain (\\<lambda>i. Y (i + j))\"\n  by (rule chainI, simp, erule chainE)\n\ntext \\<open>technical lemmas about (least) upper bounds of chains\\<close>\n\nlemma is_lub_rangeD1: \"range S <<| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  by (rule is_lubD1 [THEN ub_rangeD])\n\nlemma is_ub_range_shift: \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <| x = range S <| x\"\n  apply (rule iffI)\n   apply (rule ub_rangeI)\n   apply (rule_tac y=\"S (i + j)\" in below_trans)\n    apply (erule chain_mono)\n    apply (rule le_add1)\n   apply (erule ub_rangeD)\n  apply (rule ub_rangeI)\n  apply (erule ub_rangeD)\n  done\n\nlemma is_lub_range_shift: \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <<| x = range S <<| x\"\n  by (simp add: is_lub_def is_ub_range_shift)\n\ntext \\<open>the lub of a constant chain is the constant\\<close>\n\nlemma chain_const [simp]: \"chain (\\<lambda>i. c)\"\n  by (simp add: chainI)\n\nlemma is_lub_const: \"range (\\<lambda>x. c) <<| c\"\nby (blast dest: ub_rangeD intro: is_lubI ub_rangeI)\n\nlemma lub_const [simp]: \"(\\<Squnion>i. c) = c\"\n  by (rule is_lub_const [THEN lub_eqI])\n\n\nsubsection \\<open>Finite chains\\<close>\n\ndefinition max_in_chain :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \\<comment> \\<open>finite chains, needed for monotony of continuous functions\\<close>\n  \"max_in_chain i C \\<longleftrightarrow> (\\<forall>j. i \\<le> j \\<longrightarrow> C i = C j)\"\n\ndefinition finite_chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"finite_chain C = (chain C \\<and> (\\<exists>i. max_in_chain i C))\"\n\ntext \\<open>results about finite chains\\<close>\n\nlemma max_in_chainI: \"(\\<And>j. i \\<le> j \\<Longrightarrow> Y i = Y j) \\<Longrightarrow> max_in_chain i Y\"\n  unfolding max_in_chain_def by fast\n\nlemma max_in_chainD: \"max_in_chain i Y \\<Longrightarrow> i \\<le> j \\<Longrightarrow> Y i = Y j\"\n  unfolding max_in_chain_def by fast\n\nlemma finite_chainI: \"chain C \\<Longrightarrow> max_in_chain i C \\<Longrightarrow> finite_chain C\"\n  unfolding finite_chain_def by fast\n\nlemma finite_chainE: \"\\<lbrakk>finite_chain C; \\<And>i. \\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  unfolding finite_chain_def by fast\n\nlemma lub_finch1: \"chain C \\<Longrightarrow> max_in_chain i C \\<Longrightarrow> range C <<| C i\"\n  apply (rule is_lubI)\n   apply (rule ub_rangeI, rename_tac j)\n   apply (rule_tac x=i and y=j in linorder_le_cases)\n    apply (drule (1) max_in_chainD, simp)\n   apply (erule (1) chain_mono)\n  apply (erule ub_rangeD)\n  done\n\nlemma lub_finch2: \"finite_chain C \\<Longrightarrow> range C <<| C (LEAST i. max_in_chain i C)\"\n  apply (erule finite_chainE)\n  apply (erule LeastI2 [where Q=\"\\<lambda>i. range C <<| C i\"])\n  apply (erule (1) lub_finch1)\n  done\n\nlemma finch_imp_finite_range: \"finite_chain Y \\<Longrightarrow> finite (range Y)\"\n  apply (erule finite_chainE)\n  apply (rule_tac B=\"Y ` {..i}\" in finite_subset)\n   apply (rule subsetI)\n   apply (erule rangeE, rename_tac j)\n   apply (rule_tac x=i and y=j in linorder_le_cases)\n    apply (subgoal_tac \"Y j = Y i\", simp)\n    apply (simp add: max_in_chain_def)\n   apply simp\n  apply simp\n  done\n\nlemma finite_range_has_max:\n  fixes f :: \"nat \\<Rightarrow> 'a\"\n    and r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes mono: \"\\<And>i j. i \\<le> j \\<Longrightarrow> r (f i) (f j)\"\n  assumes finite_range: \"finite (range f)\"\n  shows \"\\<exists>k. \\<forall>i. r (f i) (f k)\"\nproof (intro exI allI)\n  fix i :: nat\n  let ?j = \"LEAST k. f k = f i\"\n  let ?k = \"Max ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n  have \"?j \\<le> ?k\"\n  proof (rule Max_ge)\n    show \"finite ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n      using finite_range by (rule finite_imageI)\n    show \"?j \\<in> (\\<lambda>x. LEAST k. f k = x) ` range f\"\n      by (intro imageI rangeI)\n  qed\n  hence \"r (f ?j) (f ?k)\"\n    by (rule mono)\n  also have \"f ?j = f i\"\n    by (rule LeastI, rule refl)\n  finally show \"r (f i) (f ?k)\" .\nqed\n\nlemma finite_range_imp_finch: \"chain Y \\<Longrightarrow> finite (range Y) \\<Longrightarrow> finite_chain Y\"\n  apply (subgoal_tac \"\\<exists>k. \\<forall>i. Y i \\<sqsubseteq> Y k\")\n   apply (erule exE)\n   apply (rule finite_chainI, assumption)\n   apply (rule max_in_chainI)\n   apply (rule below_antisym)\n    apply (erule (1) chain_mono)\n   apply (erule spec)\n  apply (rule finite_range_has_max)\n   apply (erule (1) chain_mono)\n  apply assumption\n  done\n\nlemma bin_chain: \"x \\<sqsubseteq> y \\<Longrightarrow> chain (\\<lambda>i. if i=0 then x else y)\"\n  by (rule chainI) simp\n\nlemma bin_chainmax: \"x \\<sqsubseteq> y \\<Longrightarrow> max_in_chain (Suc 0) (\\<lambda>i. if i=0 then x else y)\"\n  by (simp add: max_in_chain_def)\n\nlemma is_lub_bin_chain: \"x \\<sqsubseteq> y \\<Longrightarrow> range (\\<lambda>i::nat. if i=0 then x else y) <<| y\"\n  apply (frule bin_chain)\n  apply (drule bin_chainmax)\n  apply (drule (1) lub_finch1)\n  apply simp\n  done\n\ntext \\<open>the maximal element in a chain is its lub\\<close>\n\nlemma lub_chain_maxelem: \"Y i = c \\<Longrightarrow> \\<forall>i. Y i \\<sqsubseteq> c \\<Longrightarrow> lub (range Y) = c\"\n  by (blast dest: ub_rangeD intro: lub_eqI is_lubI ub_rangeI)\n\nend\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/HOLRLTCF/Porder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240756264639, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.764892067722805}}
{"text": "section \\<open>Basic facts about rings and modules\\<close>\n\ntheory RingModuleFacts\nimports Main\n  \"HOL-Algebra.Module\"\n  \"HOL-Algebra.Coset\"\n  (*MonoidSums*)\nbegin\n\nsubsection \\<open>Basic facts\\<close>\ntext \\<open>In a field, every nonzero element has an inverse.\\<close> (* Add to Ring.*)\nlemma (in field) inverse_exists [simp, intro]: \n  assumes h1: \"a\\<in>carrier R\"  and h2: \"a\\<noteq>\\<zero>\\<^bsub>R\\<^esub>\"\n  shows \"inv\\<^bsub>R\\<^esub> a\\<in> carrier R\"\nproof - \n  have 1: \"Units R = carrier R - {\\<zero>\\<^bsub>R\\<^esub>} \" by (rule field_Units)\n  from h1 h2 1 show ?thesis by auto\nqed\n\ntext \\<open>Multiplication by 0 in $R$ gives 0. (Note that this fact encompasses smult-l-null \nas this is for module while that is for algebra, so smult-l-null is redundant.)\\<close>\n(*Add to Module. *)\nlemma (in module) lmult_0 [simp]:\n  assumes 1: \"m\\<in>carrier M\"\n  shows \"\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m=\\<zero>\\<^bsub>M\\<^esub>\"\nproof - \n  from 1 have 0: \"\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m\\<in>carrier M\" by simp\n  from 1 have 2: \"\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m = (\\<zero>\\<^bsub>R\\<^esub> \\<oplus>\\<^bsub>R\\<^esub> \\<zero>\\<^bsub>R\\<^esub>) \\<odot>\\<^bsub>M\\<^esub> m\" by simp\n  from 1 have 3: \"(\\<zero>\\<^bsub>R\\<^esub> \\<oplus>\\<^bsub>R\\<^esub> \\<zero>\\<^bsub>R\\<^esub>) \\<odot>\\<^bsub>M\\<^esub> m=(\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m) \\<oplus>\\<^bsub>M\\<^esub> (\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m)\"  using [[simp_trace, simp_trace_depth_limit=3]]\n    by (simp add: smult_l_distr del: R.add.r_one R.add.l_one)\n  from 2 3 have 4: \"\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m =(\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m) \\<oplus>\\<^bsub>M\\<^esub> (\\<zero>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> m)\" by auto\n  from 0 4 show ?thesis\n    using M.l_neg M.r_neg1 by fastforce\nqed\n\ntext \\<open>Multiplication by 0 in $M$ gives 0.\\<close> (*Add to Module.*)\nlemma (in module) rmult_0 [simp]:\n  assumes 0: \"r\\<in>carrier R\"\n  shows \"r\\<odot>\\<^bsub>M\\<^esub> \\<zero>\\<^bsub>M\\<^esub>=\\<zero>\\<^bsub>M\\<^esub>\"\nby (metis M.zero_closed R.zero_closed assms lmult_0 r_null smult_assoc1)\n\ntext \\<open>Multiplication by $-1$ is the same as negation. May be useful as a simp rule.\\<close>\n(*Add to module.*)\nlemma (in module) smult_minus_1:\n  fixes v\n  assumes 0:\"v\\<in>carrier M\"\n  shows \"(\\<ominus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub>) \\<odot>\\<^bsub>M\\<^esub> v= (\\<ominus>\\<^bsub>M\\<^esub>  v)\"\n(*(simp add: M.l_neg)*)\nproof -\n  from 0 have a0: \"\\<one>\\<^bsub>R\\<^esub> \\<odot>\\<^bsub>M\\<^esub> v = v\" by simp\n  from 0 have 1: \"((\\<ominus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub>)\\<oplus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub>) \\<odot>\\<^bsub>M\\<^esub> v=\\<zero>\\<^bsub>M\\<^esub>\" \n    by (simp add:R.l_neg)\n  from 0 have 2: \"((\\<ominus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub>)\\<oplus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub>) \\<odot>\\<^bsub>M\\<^esub> v=(\\<ominus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub>) \\<odot>\\<^bsub>M\\<^esub> v \\<oplus>\\<^bsub>M\\<^esub> \\<one>\\<^bsub>R\\<^esub>\\<odot>\\<^bsub>M\\<^esub> v\"\n    by (simp add: smult_l_distr)\n  from 1 2 show ?thesis by (metis M.minus_equality R.add.inv_closed \n    a0 assms one_closed smult_closed) \nqed\n\ntext \\<open>The version with equality reversed.\\<close>\nlemmas (in module)  smult_minus_1_back = smult_minus_1[THEN sym]\n\ntext\\<open>-1 is not 0\\<close>\nlemma (in field) neg_1_not_0 [simp]: \"\\<ominus>\\<^bsub>R\\<^esub> \\<one>\\<^bsub>R\\<^esub> \\<noteq> \\<zero>\\<^bsub>R\\<^esub>\"\nby (metis minus_minus minus_zero one_closed zero_not_one) \n\ntext \\<open>Note smult-assoc1 is the wrong way around for simplification.\nThis is the reverse of smult-assoc1.\\<close>(*Add to Module. *)\nlemma (in module) smult_assoc_simp:\n\"[| a \\<in> carrier R; b \\<in> carrier R; x \\<in> carrier M |] ==>\n      a \\<odot>\\<^bsub>M\\<^esub> (b \\<odot>\\<^bsub>M\\<^esub> x) = (a \\<otimes> b) \\<odot>\\<^bsub>M\\<^esub> x \"\nby (auto simp add: smult_assoc1)\n  \n(* Add to Ring? *)\nlemmas (in abelian_group) show_r_zero= add.l_cancel_one\nlemmas (in abelian_group) show_l_zero= add.r_cancel_one\n\ntext \\<open>A nontrivial ring has $0\\neq 1$.\\<close>(*Add to Ring.*)\nlemma (in ring) nontrivial_ring [simp]:\n  assumes \"carrier R\\<noteq>{\\<zero>\\<^bsub>R\\<^esub>}\"\n  shows \"\\<zero>\\<^bsub>R\\<^esub>\\<noteq>\\<one>\\<^bsub>R\\<^esub>\"\nproof (rule ccontr)\n  assume 1: \"\\<not>(\\<zero>\\<^bsub>R\\<^esub>\\<noteq>\\<one>\\<^bsub>R\\<^esub>)\"\n  {\n    fix r\n    assume 2: \"r\\<in>carrier R\"\n    from 1 2 have 3: \"\\<one>\\<^bsub>R\\<^esub>\\<otimes>\\<^bsub>R\\<^esub> r = \\<zero>\\<^bsub>R\\<^esub>\\<otimes>\\<^bsub>R\\<^esub> r\" by auto\n    from 2 3 have \"r = \\<zero>\\<^bsub>R\\<^esub>\" by auto\n  }\n  from this assms show False by auto\nqed\n\ntext \\<open>Use as simp rule. To show $a-b=0$, it suffices to show $a=b$.\\<close>(*Add to Ring.*)\nlemma (in abelian_group) minus_other_side [simp]:\n  \"\\<lbrakk>a\\<in>carrier G; b\\<in>carrier G\\<rbrakk> \\<Longrightarrow> (a\\<ominus>\\<^bsub>G\\<^esub>b = \\<zero>\\<^bsub>G\\<^esub>) = (a=b)\"\n  by (metis a_minus_def add.inv_closed add.m_comm r_neg r_neg2)\n\nsubsection \\<open>Units group\\<close>\ntext \\<open>Define the units group $R^{\\times}$ and show it is actually a group.\\<close>(* Add to Ring.*)\ndefinition units_group::\"('a,'b) ring_scheme \\<Rightarrow> 'a monoid\"\n  where \"units_group R = \\<lparr>carrier = Units R, mult = (\\<lambda>x y. x\\<otimes>\\<^bsub>R\\<^esub> y), one = \\<one>\\<^bsub>R\\<^esub>\\<rparr>\"\n\ntext \\<open>The units form a group.\\<close>(*Add to Ring.*)\nlemma (in ring) units_form_group: \"group (units_group R)\"\n  apply (intro groupI)\n  apply (unfold units_group_def, auto)\n  apply (intro m_assoc) \n  apply auto\n  apply (unfold Units_def) \n  apply auto\n  done\n\ntext \\<open>The units of a \\<open>cring\\<close> form a commutative group.\\<close>(* Add to Ring.*)\nlemma (in cring) units_form_cgroup: \"comm_group (units_group R)\"\n  apply (intro comm_groupI)\n  apply (unfold units_group_def) apply auto\n  apply (intro m_assoc) apply auto\n  apply (unfold Units_def) apply auto\n  apply (rule m_comm) apply auto\n  done\n\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/VectorSpace/RingModuleFacts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.8840392695254319, "lm_q1q2_score": 0.7648920536480507}}
{"text": "theory PigeonholeWorking\n  imports Complex_Main HOL.Finite_Set\n\nbegin\n\nlemma distinct2:\n  fixes A :: \"'a set\"\n  assumes assms:\n          \"finite A\"\n          \"card A \\<ge> 2\"\n  obtains x y where \"x \\<in> A \\<and> y \\<in> A \\<and> x \\<noteq> y\"\nproof-\n  obtain x A' where \"x \\<in> A \\<and> x \\<notin> A' \\<and> card A' = card A - 1 \\<and> A' \\<subseteq> A\"\n      using assms(2) card_eq_SucD [of \"A\" \"card A - 1\"] by auto\n  hence x: \"x \\<in> A\" \"x \\<notin> A'\" \"card A' = card A - 1\" \"A' \\<subseteq> A\" by auto\n  hence A'_card: \"card A' = card A - 1\" by auto\n  also have \"... \\<ge> 1\" using assms(2) by auto\n  finally have \"card A' \\<ge> 1\" by auto\n  then obtain y where y: \"y \\<in> A'\" using card_eq_SucD [of \"A'\" \"card A' - 1\"] by auto\n  from that show ?thesis using x y by auto\nqed\n\ntheorem pigeonhole:\n  fixes f :: \"'a \\<Rightarrow> 'b\"\n  shows \"\\<And>A B. \\<forall>a \\<in> A. \\<exists>b \\<in> B. f a = b\n         \\<Longrightarrow> m = card B - 1\n         \\<Longrightarrow> finite A\n         \\<Longrightarrow> finite B\n         \\<Longrightarrow> card B < card A\n         \\<Longrightarrow> card B > 0\n         \\<Longrightarrow> (\\<exists>x y. x \\<noteq> y \\<and> f x = f y)\"\nproof(induction m rule: nat.induct)\n  case zero\n  then have B_card: \"card B = 1\" using zero.prems by auto\n  then have A_card: \"card A \\<ge> 2\" using zero.prems by auto\n\n  obtain b where \"B = {b}\" using B_card card_1_singletonE by auto\n  then have \"\\<forall>x \\<in> A. f x = b\" using zero.prems by auto\n  moreover obtain x y where \"x \\<in> A \\<and> y \\<in> A \\<and> x \\<noteq> y\" using A_card zero.prems distinct2[of \"A\"] by auto\n  moreover have \"f x = b\" using calculation by auto\n  moreover have \"f y = b\" using calculation by auto\n  ultimately have \"x \\<noteq> y \\<and> f x = f y\" by auto\n  hence \"\\<exists>y. x \\<noteq> y \\<and> f x = f y\" by (rule exI)\n  thus ?case by (rule exI)\nnext\n  case (Suc m)\n  have \"card A > 0\" using Suc.prems by auto\n  from this obtain a where a: \"a \\<in> A\" using card_eq_SucD[of \"A\" \"card A - 1\"] by auto\n  then have fa_in_B: \"f a \\<in> B\" using Suc.prems by auto\n  show ?case\n  proof(cases \"\\<exists>y. a \\<noteq> y \\<and> f a = f y\")\n    case True\n    thus ?thesis by (rule exI)\n  next\n    case False\n    then have fa_unique: \"\\<forall>y. a \\<noteq> y \\<longrightarrow> f a \\<noteq> f y\" by auto\n\n    define A' where \"A' = A - {a}\"\n    define B' where \"B' = B - {f a}\"\n    have A'_card: \"card A' = card A - 1\" using a A'_def card_Diff_singleton[of \"a\" \"A'\"] by auto\n    have B'_card: \"card B' = card B - 1\" using fa_in_B B'_def card_Diff_singleton[of \"f a\" \"B'\"] by auto\n\n    have \"A' \\<subseteq> A\" using A'_def by auto\n    moreover from this have \"\\<forall>x \\<in> A'. f x \\<in> B\" using Suc.prems by auto\n    moreover have \"\\<forall>x \\<in> A'. f x \\<noteq> f a\" using fa_unique A'_def by auto\n    moreover from this have \"\\<forall>x \\<in> A'. f x \\<notin> {f a}\" using A'_def B'_def fa_unique by auto\n    ultimately have \"\\<forall>x \\<in> A'. f x \\<in> B \\<and> f x \\<notin> {f a}\" by auto\n    \n    then have \"\\<forall>x \\<in> A'. f x \\<in> B'\" using B'_def by auto\n    then have \"\\<forall>x \\<in> A'. \\<exists>b \\<in> B'. f x = b\" by auto\n    moreover have \"finite A'\" using Suc.prems A'_def by auto\n    moreover have \"finite B'\" using Suc.prems B'_def by auto\n    moreover have \"card B' > 0\" using Suc.prems B'_card by auto\n    moreover from this have \"card B' < card A'\" using Suc.prems by (auto simp: A'_card B'_card)\n    moreover have \"card B' - 1 = m\" using Suc.prems B'_card by auto\n    ultimately show ?thesis using Suc.IH[of \"A'\" \"B'\"] by auto\n  qed\nqed\n\n(*Better formatted and stuff*)\ntheorem pigeonhole2:\n  fixes f :: \"'a \\<Rightarrow> 'b\"\n  fixes m :: \"nat\"\n  assumes \"\\<forall>a \\<in> A. \\<exists>b \\<in> B. f a = b\"\n  assumes \"finite A\"\n  assumes \"finite B\"\n  assumes \"card B < card A\"\n  assumes \"card B > 0\"\n  shows \"\\<exists>x y. x \\<noteq> y \\<and> f x = f y\"\n  using assms\nproof(induction \"card B - 1\" arbitrary: \"A\" \"B\" rule: nat.induct)\n  case zero\n  then have B_card: \"card B = 1\" using zero.prems by auto\n  then have A_card: \"card A \\<ge> 2\" using zero.prems by auto\n\n  obtain b where \"B = {b}\" using B_card card_1_singletonE by auto\n  then have \"\\<forall>x \\<in> A. f x = b\" using zero.prems by auto\n  moreover obtain x y where \"x \\<in> A \\<and> y \\<in> A \\<and> x \\<noteq> y\" using A_card zero.prems distinct2[of \"A\"] by auto\n  moreover have \"f x = b\" using calculation by auto\n  moreover have \"f y = b\" using calculation by auto\n  ultimately have \"x \\<noteq> y \\<and> f x = f y\" by auto\n  hence \"\\<exists>y. x \\<noteq> y \\<and> f x = f y\" by (rule exI)\n  thus ?case by (rule exI)\nnext\n  case (Suc m)\n  have \"card A > 0\" using Suc.prems by auto\n  from this obtain a where a: \"a \\<in> A\" using card_eq_SucD[of \"A\" \"card A - 1\"] by auto\n  then have fa_in_B: \"f a \\<in> B\" using Suc.prems by auto\n  show ?case\n  proof(cases \"\\<exists>y. a \\<noteq> y \\<and> f a = f y\")\n    case True\n    thus ?thesis by (rule exI)\n  next\n    case False\n    then have fa_unique: \"\\<forall>y. a \\<noteq> y \\<longrightarrow> f a \\<noteq> f y\" by auto\n\n    let ?A' = \"A - {a}\"\n    let ?B' = \"B - {f a}\"\n    have A'_card: \"card ?A' = card A - 1\" using a card_Diff_singleton[of \"a\" \"?A'\"] by auto\n    have B'_card: \"card ?B' = card B - 1\" using fa_in_B card_Diff_singleton[of \"f a\" \"?B'\"] by auto\n\n    have \"?A' \\<subseteq> A\" by auto\n    moreover from this have \"\\<forall>x \\<in> ?A'. f x \\<in> B\" using Suc.prems by auto\n    moreover have \"\\<forall>x \\<in> ?A'. f x \\<noteq> f a\" using fa_unique by auto\n    moreover from this have \"\\<forall>x \\<in> ?A'. f x \\<notin> {f a}\" using fa_unique by auto\n    ultimately have \"\\<forall>x \\<in> ?A'. f x \\<in> B \\<and> f x \\<notin> {f a}\" by auto\n    \n    then have \"\\<forall>x \\<in> ?A'. f x \\<in> ?B'\" by auto\n    then have \"\\<forall>x \\<in> ?A'. \\<exists>b \\<in> ?B'. f x = b\" by auto\n    moreover have \"finite ?A'\" using Suc.prems by auto\n    moreover have \"finite ?B'\" using Suc.prems by auto\n    moreover have \"card ?B' > 0\" using B'_card Suc.hyps(2) by linarith \n    moreover from this have \"card ?B' < card ?A'\"\n      by (simp add: A'_card B'_card Suc.prems(4) diff_less_mono) \n    moreover have \"card ?B' - 1 = m\"\n      by (metis B'_card Suc.hyps(2) diff_Suc_1) \n    ultimately show ?thesis using Suc.hyps(1)[of \"?B'\" \"?A'\"] by auto\n  qed\nqed\n\n\ntheorem pigeonhole_obtain:\n  fixes f :: \"'a \\<Rightarrow> 'b\" and\n        A :: \"'a set\" and\n        B :: \"'b set\"\n  assumes \"finite A\" and\n          \"finite B\" and\n          \"card A > card B\" and\n          \"\\<forall>x \\<in> A. f x \\<in> B\"\n  obtains x y where \"f x = f y\" using pigeonhole by auto\n\ntheorem pigeonhole_app:\n  fixes f :: \"nat \\<Rightarrow> nat\" and\n        A :: \"nat set\" and\n        B :: \"nat set\"\n  assumes \"finite A\" and\n          \"finite B\" and\n          \"card A > card B\" and\n          \"\\<forall>x \\<in> A. f x \\<in> B\"\n  shows \"\\<exists>x y. f x = f y\" using assms pigeonhole by auto\nend", "meta": {"author": "SageBinder", "repo": "Isabelle-Practice", "sha": "master", "save_path": "github-repos/isabelle/SageBinder-Isabelle-Practice", "path": "github-repos/isabelle/SageBinder-Isabelle-Practice/Isabelle-Practice-master/PigeonholeWorking.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528094861981, "lm_q2_score": 0.8976952832120991, "lm_q1q2_score": 0.7647940185950561}}
{"text": "(*  Title:      HOL/ex/Fundefs.thy\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection {* Examples of function definitions *}\n\ntheory Fundefs \nimports Main \"~~/src/HOL/Library/Monad_Syntax\"\nbegin\n\nsubsection {* Very basic *}\n\nfun fib :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"fib 0 = 1\"\n| \"fib (Suc 0) = 1\"\n| \"fib (Suc (Suc n)) = fib n + fib (Suc n)\"\n\ntext {* partial simp and induction rules: *}\nthm fib.psimps\nthm fib.pinduct\n\ntext {* There is also a cases rule to distinguish cases along the definition *}\nthm fib.cases\n\n\ntext {* total simp and induction rules: *}\nthm fib.simps\nthm fib.induct\n\ntext {* elimination rules *}\nthm fib.elims\n\nsubsection {* Currying *}\n\nfun add\nwhere\n  \"add 0 y = y\"\n| \"add (Suc x) y = Suc (add x y)\"\n\nthm add.simps\nthm add.induct -- {* Note the curried induction predicate *}\n\n\nsubsection {* Nested recursion *}\n\nfunction nz \nwhere\n  \"nz 0 = 0\"\n| \"nz (Suc x) = nz (nz x)\"\nby pat_completeness auto\n\nlemma nz_is_zero: -- {* A lemma we need to prove termination *}\n  assumes trm: \"nz_dom x\"\n  shows \"nz x = 0\"\nusing trm\nby induct (auto simp: nz.psimps)\n\ntermination nz\n  by (relation \"less_than\") (auto simp:nz_is_zero)\n\nthm nz.simps\nthm nz.induct\n\ntext {* Here comes McCarthy's 91-function *}\n\n\nfunction f91 :: \"nat => nat\"\nwhere\n  \"f91 n = (if 100 < n then n - 10 else f91 (f91 (n + 11)))\"\nby pat_completeness auto\n\n(* Prove a lemma before attempting a termination proof *)\nlemma f91_estimate: \n  assumes trm: \"f91_dom n\"\n  shows \"n < f91 n + 11\"\nusing trm by induct (auto simp: f91.psimps)\n\ntermination\nproof\n  let ?R = \"measure (%x. 101 - x)\"\n  show \"wf ?R\" ..\n\n  fix n::nat assume \"~ 100 < n\" (* Inner call *)\n  thus \"(n + 11, n) : ?R\" by simp\n\n  assume inner_trm: \"f91_dom (n + 11)\" (* Outer call *)\n  with f91_estimate have \"n + 11 < f91 (n + 11) + 11\" .\n  with `~ 100 < n` show \"(f91 (n + 11), n) : ?R\" by simp \nqed\n\ntext{* Now trivial (even though it does not belong here): *}\nlemma \"f91 n = (if 100 < n then n - 10 else 91)\"\nby (induct n rule:f91.induct) auto\n\n\nsubsection {* More general patterns *}\n\nsubsubsection {* Overlapping patterns *}\n\ntext {* Currently, patterns must always be compatible with each other, since\nno automatic splitting takes place. But the following definition of\ngcd is ok, although patterns overlap: *}\n\nfun gcd2 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd2 x 0 = x\"\n| \"gcd2 0 y = y\"\n| \"gcd2 (Suc x) (Suc y) = (if x < y then gcd2 (Suc x) (y - x)\n                                    else gcd2 (x - y) (Suc y))\"\n\nthm gcd2.simps\nthm gcd2.induct\n\nsubsubsection {* Guards *}\n\ntext {* We can reformulate the above example using guarded patterns *}\n\nfunction gcd3 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"gcd3 x 0 = x\"\n| \"gcd3 0 y = y\"\n| \"x < y \\<Longrightarrow> gcd3 (Suc x) (Suc y) = gcd3 (Suc x) (y - x)\"\n| \"\\<not> x < y \\<Longrightarrow> gcd3 (Suc x) (Suc y) = gcd3 (x - y) (Suc y)\"\n  apply (case_tac x, case_tac a, auto)\n  apply (case_tac ba, auto)\n  done\ntermination by lexicographic_order\n\nthm gcd3.simps\nthm gcd3.induct\n\n\ntext {* General patterns allow even strange definitions: *}\n\nfunction ev :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"ev (2 * n) = True\"\n| \"ev (2 * n + 1) = False\"\nproof -  -- {* completeness is more difficult here \\dots *}\n  fix P :: bool\n    and x :: nat\n  assume c1: \"\\<And>n. x = 2 * n \\<Longrightarrow> P\"\n    and c2: \"\\<And>n. x = 2 * n + 1 \\<Longrightarrow> P\"\n  have divmod: \"x = 2 * (x div 2) + (x mod 2)\" by auto\n  show \"P\"\n  proof cases\n    assume \"x mod 2 = 0\"\n    with divmod have \"x = 2 * (x div 2)\" by simp\n    with c1 show \"P\" .\n  next\n    assume \"x mod 2 \\<noteq> 0\"\n    hence \"x mod 2 = 1\" by simp\n    with divmod have \"x = 2 * (x div 2) + 1\" by simp\n    with c2 show \"P\" .\n  qed\nqed presburger+ -- {* solve compatibility with presburger *} \ntermination by lexicographic_order\n\nthm ev.simps\nthm ev.induct\nthm ev.cases\n\n\nsubsection {* Mutual Recursion *}\n\nfun evn od :: \"nat \\<Rightarrow> bool\"\nwhere\n  \"evn 0 = True\"\n| \"od 0 = False\"\n| \"evn (Suc n) = od n\"\n| \"od (Suc n) = evn n\"\n\nthm evn.simps\nthm od.simps\n\nthm evn_od.induct\nthm evn_od.termination\n\nthm evn.elims\nthm od.elims\n\nsubsection {* Definitions in local contexts *}\n\nlocale my_monoid = \nfixes opr :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  and un :: \"'a\"\nassumes assoc: \"opr (opr x y) z = opr x (opr y z)\"\n  and lunit: \"opr un x = x\"\n  and runit: \"opr x un = x\"\nbegin\n\nfun foldR :: \"'a list \\<Rightarrow> 'a\"\nwhere\n  \"foldR [] = un\"\n| \"foldR (x#xs) = opr x (foldR xs)\"\n\nfun foldL :: \"'a list \\<Rightarrow> 'a\"\nwhere\n  \"foldL [] = un\"\n| \"foldL [x] = x\"\n| \"foldL (x#y#ys) = foldL (opr x y # ys)\" \n\nthm foldL.simps\n\nlemma foldR_foldL: \"foldR xs = foldL xs\"\nby (induct xs rule: foldL.induct) (auto simp:lunit runit assoc)\n\nthm foldR_foldL\n\nend\n\nthm my_monoid.foldL.simps\nthm my_monoid.foldR_foldL\n\nsubsection {* @{text fun_cases} *}\n\nsubsubsection {* Predecessor *}\n\nfun pred :: \"nat \\<Rightarrow> nat\" where\n\"pred 0 = 0\" |\n\"pred (Suc n) = n\"\n\nthm pred.elims\n\nlemma assumes \"pred x = y\"\nobtains \"x = 0\" \"y = 0\" | \"n\" where \"x = Suc n\" \"y = n\"\nby (fact pred.elims[OF assms])\n\ntext {* If the predecessor of a number is 0, that number must be 0 or 1. *}\n\nfun_cases pred0E[elim]: \"pred n = 0\"\n\nlemma \"pred n = 0 \\<Longrightarrow> n = 0 \\<or> n = Suc 0\"\nby (erule pred0E) metis+\n\n\ntext {* Other expressions on the right-hand side also work, but whether the\n        generated rule is useful depends on how well the simplifier can\n        simplify it. This example works well: *}\n\nfun_cases pred42E[elim]: \"pred n = 42\"\n\nlemma \"pred n = 42 \\<Longrightarrow> n = 43\"\nby (erule pred42E)\n\nsubsubsection {* List to option *}\n\nfun list_to_option :: \"'a list \\<Rightarrow> 'a option\" where\n\"list_to_option [x] = Some x\" |\n\"list_to_option _ = None\"\n\nfun_cases list_to_option_NoneE: \"list_to_option xs = None\"\n      and list_to_option_SomeE: \"list_to_option xs = Some x\"\n\nlemma \"list_to_option xs = Some y \\<Longrightarrow> xs = [y]\"\nby (erule list_to_option_SomeE)\n\nsubsubsection {* Boolean Functions *}\n\nfun xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"xor False False = False\" |\n\"xor True True = False\" |\n\"xor _ _ = True\"\n\nthm xor.elims\n\ntext {* @{text fun_cases} does not only recognise function equations, but also works with\n   functions that return a boolean, e.g.: *}\n\nfun_cases xor_TrueE: \"xor a b\" and xor_FalseE: \"\\<not>xor a b\"\nprint_theorems\n\nsubsubsection {* Many parameters *}\n\nfun sum4 :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"sum4 a b c d = a + b + c + d\"\n\nfun_cases sum40E: \"sum4 a b c d = 0\"\n\nlemma \"sum4 a b c d = 0 \\<Longrightarrow> a = 0\"\nby (erule sum40E)\n\n\nsubsection {* Partial Function Definitions *}\n\ntext {* Partial functions in the option monad: *}\n\npartial_function (option)\n  collatz :: \"nat \\<Rightarrow> nat list option\"\nwhere\n  \"collatz n =\n  (if n \\<le> 1 then Some [n]\n   else if even n \n     then do { ns \\<leftarrow> collatz (n div 2); Some (n # ns) }\n     else do { ns \\<leftarrow> collatz (3 * n + 1);  Some (n # ns)})\"\n\ndeclare collatz.simps[code]\nvalue \"collatz 23\"\n\n\ntext {* Tail-recursive functions: *}\n\npartial_function (tailrec) fixpoint :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a \\<Rightarrow> 'a\"\nwhere\n  \"fixpoint f x = (if f x = x then x else fixpoint f (f x))\"\n\n\nsubsection {* Regression tests *}\n\ntext {* The following examples mainly serve as tests for the \n  function package *}\n\nfun listlen :: \"'a list \\<Rightarrow> nat\"\nwhere\n  \"listlen [] = 0\"\n| \"listlen (x#xs) = Suc (listlen xs)\"\n\n(* Context recursion *)\n\nfun f :: \"nat \\<Rightarrow> nat\" \nwhere\n  zero: \"f 0 = 0\"\n| succ: \"f (Suc n) = (if f n = 0 then 0 else f n)\"\n\n\n(* A combination of context and nested recursion *)\nfunction h :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"h 0 = 0\"\n| \"h (Suc n) = (if h n = 0 then h (h n) else h n)\"\n  by pat_completeness auto\n\n\n(* Context, but no recursive call: *)\nfun i :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"i 0 = 0\"\n| \"i (Suc n) = (if n = 0 then 0 else i n)\"\n\n\n(* Tupled nested recursion *)\nfun fa :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"fa 0 y = 0\"\n| \"fa (Suc n) y = (if fa n y = 0 then 0 else fa n y)\"\n\n(* Let *)\nfun j :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"j 0 = 0\"\n| \"j (Suc n) = (let u = n  in Suc (j u))\"\n\n\n(* There were some problems with fresh names\\<dots> *)\nfunction  k :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"k x = (let a = x; b = x in k x)\"\n  by pat_completeness auto\n\n\nfunction f2 :: \"(nat \\<times> nat) \\<Rightarrow> (nat \\<times> nat)\"\nwhere\n  \"f2 p = (let (x,y) = p in f2 (y,x))\"\n  by pat_completeness auto\n\n\n(* abbreviations *)\nfun f3 :: \"'a set \\<Rightarrow> bool\"\nwhere\n  \"f3 x = finite x\"\n\n\n(* Simple Higher-Order Recursion *)\ndatatype 'a tree = \n  Leaf 'a \n  | Branch \"'a tree list\"\n\nfun treemap :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\"\nwhere\n  \"treemap fn (Leaf n) = (Leaf (fn n))\"\n| \"treemap fn (Branch l) = (Branch (map (treemap fn) l))\"\n\nfun tinc :: \"nat tree \\<Rightarrow> nat tree\"\nwhere\n  \"tinc (Leaf n) = Leaf (Suc n)\"\n| \"tinc (Branch l) = Branch (map tinc l)\"\n\nfun testcase :: \"'a tree \\<Rightarrow> 'a list\"\nwhere\n  \"testcase (Leaf a) = [a]\"\n| \"testcase (Branch x) =\n    (let xs = concat (map testcase x);\n         ys = concat (map testcase x) in\n     xs @ ys)\"\n\n\n(* Pattern matching on records *)\nrecord point =\n  Xcoord :: int\n  Ycoord :: int\n\nfunction swp :: \"point \\<Rightarrow> point\"\nwhere\n  \"swp \\<lparr> Xcoord = x, Ycoord = y \\<rparr> = \\<lparr> Xcoord = y, Ycoord = x \\<rparr>\"\nproof -\n  fix P x\n  assume \"\\<And>xa y. x = \\<lparr>Xcoord = xa, Ycoord = y\\<rparr> \\<Longrightarrow> P\"\n  thus \"P\"\n    by (cases x)\nqed auto\ntermination by rule auto\n\n\n(* The diagonal function *)\nfun diag :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool \\<Rightarrow> nat\"\nwhere\n  \"diag x True False = 1\"\n| \"diag False y True = 2\"\n| \"diag True False z = 3\"\n| \"diag True True True = 4\"\n| \"diag False False False = 5\"\n\n\n(* Many equations (quadratic blowup) *)\ndatatype DT = \n  A | B | C | D | E | F | G | H | I | J | K | L | M | N | P\n| Q | R | S | T | U | V\n\nfun big :: \"DT \\<Rightarrow> nat\"\nwhere\n  \"big A = 0\" \n| \"big B = 0\" \n| \"big C = 0\" \n| \"big D = 0\" \n| \"big E = 0\" \n| \"big F = 0\" \n| \"big G = 0\" \n| \"big H = 0\" \n| \"big I = 0\" \n| \"big J = 0\" \n| \"big K = 0\" \n| \"big L = 0\" \n| \"big M = 0\" \n| \"big N = 0\" \n| \"big P = 0\" \n| \"big Q = 0\" \n| \"big R = 0\" \n| \"big S = 0\" \n| \"big T = 0\" \n| \"big U = 0\" \n| \"big V = 0\"\n\n\n(* automatic pattern splitting *)\nfun\n  f4 :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" \nwhere\n  \"f4 0 0 = True\"\n| \"f4 _ _ = False\"\n\n\n(* polymorphic partial_function *)\npartial_function (option) f5 :: \"'a list \\<Rightarrow> 'a option\"\nwhere\n  \"f5 x = f5 x\"\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/ex/Fundefs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.863391611731321, "lm_q1q2_score": 0.7646467907923872}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>Creating Balanced Trees\\<close>\n\ntheory Balance\nimports\n  \"HOL-Library.Tree_Real\"\nbegin\n\nfun bal :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a tree * 'a list\" where\n\"bal n xs = (if n=0 then (Leaf,xs) else\n (let m = n div 2;\n      (l, ys) = bal m xs;\n      (r, zs) = bal (n-1-m) (tl ys)\n  in (Node l (hd ys) r, zs)))\"\n\ndeclare bal.simps[simp del]\ndeclare Let_def[simp]\n\ndefinition bal_list :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a tree\" where\n\"bal_list n xs = fst (bal n xs)\"\n\ndefinition balance_list :: \"'a list \\<Rightarrow> 'a tree\" where\n\"balance_list xs = bal_list (length xs) xs\"\n\ndefinition bal_tree :: \"nat \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"bal_tree n t = bal_list n (inorder t)\"\n\ndefinition balance_tree :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"balance_tree t = bal_tree (size t) t\"\n\nlemma bal_simps:\n  \"bal 0 xs = (Leaf, xs)\"\n  \"n > 0 \\<Longrightarrow>\n   bal n xs =\n  (let m = n div 2;\n      (l, ys) = bal m xs;\n      (r, zs) = bal (n-1-m) (tl ys)\n  in (Node l (hd ys) r, zs))\"\nby(simp_all add: bal.simps)\n\nlemma bal_inorder:\n  \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,zs) \\<rbrakk>\n  \\<Longrightarrow> xs = inorder t @ zs \\<and> size t = n\"\nproof(induction n arbitrary: xs t zs rule: less_induct)\n  case (less n) show ?case\n  proof cases\n    assume \"n = 0\" thus ?thesis using less.prems by (simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    let ?m = \"n div 2\" let ?m' = \"n - 1 - ?m\"\n    from less.prems(2) obtain l r ys where\n      b1: \"bal ?m xs = (l,ys)\" and\n      b2: \"bal ?m' (tl ys) = (r,zs)\" and\n      t: \"t = \\<langle>l, hd ys, r\\<rangle>\"\n      by(auto simp: bal_simps split: prod.splits)\n    have IH1: \"xs = inorder l @ ys \\<and> size l = ?m\"\n      using b1 less.prems(1) by(intro less.IH) auto\n    have IH2: \"tl ys = inorder r @ zs \\<and> size r = ?m'\"\n      using  b2 IH1 less.prems(1) by(intro less.IH) auto\n    show ?thesis using t IH1 IH2 less.prems(1) hd_Cons_tl[of ys] by fastforce\n  qed\nqed\n\ncorollary inorder_bal_list[simp]:\n  \"n \\<le> length xs \\<Longrightarrow> inorder(bal_list n xs) = take n xs\"\nunfolding bal_list_def\nby (metis (mono_tags) prod.collapse[of \"bal n xs\"] append_eq_conv_conj bal_inorder length_inorder)\n\ncorollary inorder_balance_list[simp]: \"inorder(balance_list xs) = xs\"\nby(simp add: balance_list_def)\n\ncorollary inorder_bal_tree:\n  \"n \\<le> size t \\<Longrightarrow> inorder(bal_tree n t) = take n (inorder t)\"\nby(simp add: bal_tree_def)\n\ncorollary inorder_balance_tree[simp]: \"inorder(balance_tree t) = inorder t\"\nby(simp add: balance_tree_def inorder_bal_tree)\n\n\ntext\\<open>The length/size lemmas below do not require the precondition @{prop\"n \\<le> length xs\"}\n(or  @{prop\"n \\<le> size t\"}) that they come with. They could take advantage of the fact\nthat @{term \"bal xs n\"} yields a result even if @{prop \"n > length xs\"}.\nIn that case the result will contain one or more occurrences of @{term \"hd []\"}.\nHowever, this is counter-intuitive and does not reflect the execution\nin an eager functional language.\\<close>\n\nlemma bal_length: \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,zs) \\<rbrakk> \\<Longrightarrow> length zs = length xs - n\"\nusing bal_inorder by fastforce\n\ncorollary size_bal_list[simp]: \"n \\<le> length xs \\<Longrightarrow> size(bal_list n xs) = n\"\nunfolding bal_list_def using bal_inorder prod.exhaust_sel by blast\n\ncorollary size_balance_list[simp]: \"size(balance_list xs) = length xs\"\nby (simp add: balance_list_def)\n\ncorollary size_bal_tree[simp]: \"n \\<le> size t \\<Longrightarrow> size(bal_tree n t) = n\"\nby(simp add: bal_tree_def)\n\ncorollary size_balance_tree[simp]: \"size(balance_tree t) = size t\"\nby(simp add: balance_tree_def)\n\nlemma min_height_bal:\n  \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,zs) \\<rbrakk> \\<Longrightarrow> min_height t = nat(\\<lfloor>log 2 (n + 1)\\<rfloor>)\"\nproof(induction n arbitrary: xs t zs rule: less_induct)\n  case (less n)\n  show ?case\n  proof cases\n    assume \"n = 0\" thus ?thesis using less.prems(2) by (simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    let ?m = \"n div 2\" let ?m' = \"n - 1 - ?m\"\n    from less.prems obtain l r ys where\n      b1: \"bal ?m xs = (l,ys)\" and\n      b2: \"bal ?m' (tl ys) = (r,zs)\" and\n      t: \"t = \\<langle>l, hd ys, r\\<rangle>\"\n      by(auto simp: bal_simps split: prod.splits)\n    let ?hl = \"nat (floor(log 2 (?m + 1)))\"\n    let ?hr = \"nat (floor(log 2 (?m' + 1)))\"\n    have IH1: \"min_height l = ?hl\" using less.IH[OF _ _ b1] less.prems(1) by simp\n    have IH2: \"min_height r = ?hr\"\n      using less.prems(1) bal_length[OF _ b1] b2 by(intro less.IH) auto\n    have \"(n+1) div 2 \\<ge> 1\" by arith\n    hence 0: \"log 2 ((n+1) div 2) \\<ge> 0\" by simp\n    have \"?m' \\<le> ?m\" by arith\n    hence le: \"?hr \\<le> ?hl\" by(simp add: nat_mono floor_mono)\n    have \"min_height t = min ?hl ?hr + 1\" by (simp add: t IH1 IH2)\n    also have \"\\<dots> = ?hr + 1\" using le by (simp add: min_absorb2)\n    also have \"?m' + 1 = (n+1) div 2\" by linarith\n    also have \"nat (floor(log 2 ((n+1) div 2))) + 1\n       = nat (floor(log 2 ((n+1) div 2) + 1))\"\n      using 0 by linarith\n    also have \"\\<dots> = nat (floor(log 2 (n + 1)))\"\n      using floor_log2_div2[of \"n+1\"] by (simp add: log_mult)\n    finally show ?thesis .\n  qed\nqed\n\nlemma height_bal:\n  \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,zs) \\<rbrakk> \\<Longrightarrow> height t = nat \\<lceil>log 2 (n + 1)\\<rceil>\"\nproof(induction n arbitrary: xs t zs rule: less_induct)\n  case (less n) show ?case\n  proof cases\n    assume \"n = 0\" thus ?thesis\n      using less.prems by (simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    let ?m = \"n div 2\" let ?m' = \"n - 1 - ?m\"\n    from less.prems obtain l r ys where\n      b1: \"bal ?m xs = (l,ys)\" and\n      b2: \"bal ?m' (tl ys) = (r,zs)\" and\n      t: \"t = \\<langle>l, hd ys, r\\<rangle>\"\n      by(auto simp: bal_simps split: prod.splits)\n    let ?hl = \"nat \\<lceil>log 2 (?m + 1)\\<rceil>\"\n    let ?hr = \"nat \\<lceil>log 2 (?m' + 1)\\<rceil>\"\n    have IH1: \"height l = ?hl\" using less.IH[OF _ _ b1] less.prems(1) by simp\n    have IH2: \"height r = ?hr\"\n      using b2 bal_length[OF _ b1] less.prems(1) by(intro less.IH) auto\n    have 0: \"log 2 (?m + 1) \\<ge> 0\" by simp\n    have \"?m' \\<le> ?m\" by arith\n    hence le: \"?hr \\<le> ?hl\"\n      by(simp add: nat_mono ceiling_mono del: nat_ceiling_le_eq)\n    have \"height t = max ?hl ?hr + 1\" by (simp add: t IH1 IH2)\n    also have \"\\<dots> = ?hl + 1\" using le by (simp add: max_absorb1)\n    also have \"\\<dots> = nat \\<lceil>log 2 (?m + 1) + 1\\<rceil>\" using 0 by linarith\n    also have \"\\<dots> = nat \\<lceil>log 2 (n + 1)\\<rceil>\"\n      using ceiling_log2_div2[of \"n+1\"] by (simp)\n    finally show ?thesis .\n  qed\nqed\n\nlemma balanced_bal:\n  assumes \"n \\<le> length xs\" \"bal n xs = (t,ys)\" shows \"balanced t\"\nunfolding balanced_def\nusing height_bal[OF assms] min_height_bal[OF assms]\nby linarith\n\nlemma height_bal_list:\n  \"n \\<le> length xs \\<Longrightarrow> height (bal_list n xs) = nat \\<lceil>log 2 (n + 1)\\<rceil>\"\nunfolding bal_list_def by (metis height_bal prod.collapse)\n\nlemma height_balance_list:\n  \"height (balance_list xs) = nat \\<lceil>log 2 (length xs + 1)\\<rceil>\"\nby (simp add: balance_list_def height_bal_list)\n\ncorollary height_bal_tree:\n  \"n \\<le> size t \\<Longrightarrow> height (bal_tree n t) = nat\\<lceil>log 2 (n + 1)\\<rceil>\"\nunfolding bal_list_def bal_tree_def\nby (metis bal_list_def height_bal_list length_inorder)\n\ncorollary height_balance_tree:\n  \"height (balance_tree t) = nat\\<lceil>log 2 (size t + 1)\\<rceil>\"\nby (simp add: bal_tree_def balance_tree_def height_bal_list)\n\ncorollary balanced_bal_list[simp]: \"n \\<le> length xs \\<Longrightarrow> balanced (bal_list n xs)\"\nunfolding bal_list_def by (metis  balanced_bal prod.collapse)\n\ncorollary balanced_balance_list[simp]: \"balanced (balance_list xs)\"\nby (simp add: balance_list_def)\n\ncorollary balanced_bal_tree[simp]: \"n \\<le> size t \\<Longrightarrow> balanced (bal_tree n t)\"\nby (simp add: bal_tree_def)\n\ncorollary balanced_balance_tree[simp]: \"balanced (balance_tree t)\"\nby (simp add: balance_tree_def)\n\nlemma wbalanced_bal: \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,ys) \\<rbrakk> \\<Longrightarrow> wbalanced t\"\nproof(induction n arbitrary: xs t ys rule: less_induct)\n  case (less n)\n  show ?case\n  proof cases\n    assume \"n = 0\"\n    thus ?thesis using less.prems(2) by(simp add: bal_simps)\n  next\n    assume [arith]: \"n \\<noteq> 0\"\n    with less.prems obtain l ys r zs where\n      rec1: \"bal (n div 2) xs = (l, ys)\" and\n      rec2: \"bal (n - 1 - n div 2) (tl ys) = (r, zs)\" and\n      t: \"t = \\<langle>l, hd ys, r\\<rangle>\"\n      by(auto simp add: bal_simps split: prod.splits)\n    have l: \"wbalanced l\" using less.IH[OF _ _ rec1] less.prems(1) by linarith\n    have \"wbalanced r\"\n      using rec1 rec2 bal_length[OF _ rec1] less.prems(1) by(intro less.IH) auto\n    with l t bal_length[OF _ rec1] less.prems(1) bal_inorder[OF _ rec1] bal_inorder[OF _ rec2]\n    show ?thesis by auto\n  qed\nqed\n\ntext\\<open>An alternative proof via @{thm balanced_if_wbalanced}:\\<close>\nlemma \"\\<lbrakk> n \\<le> length xs; bal n xs = (t,ys) \\<rbrakk> \\<Longrightarrow> balanced t\"\nby(rule balanced_if_wbalanced[OF wbalanced_bal])\n\nlemma wbalanced_bal_list[simp]: \"n \\<le> length xs \\<Longrightarrow> wbalanced (bal_list n xs)\"\nby(simp add: bal_list_def) (metis prod.collapse wbalanced_bal)\n\nlemma wbalanced_balance_list[simp]: \"wbalanced (balance_list xs)\"\nby(simp add: balance_list_def)\n\nlemma wbalanced_bal_tree[simp]: \"n \\<le> size t \\<Longrightarrow> wbalanced (bal_tree n t)\"\nby(simp add: bal_tree_def)\n\nlemma wbalanced_balance_tree: \"wbalanced (balance_tree t)\"\nby (simp add: balance_tree_def)\n\nhide_const (open) bal\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Data_Structures/Balance.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.8633916187614823, "lm_q1q2_score": 0.7646467839872262}}
{"text": "(*\nConcrete Semantics with Isabelle/HOL\n3. Case Study: IMP Expressions\n\nProof is based on \"Proof of validity of compilation result of IMP\".\nhttps://qiita.com/masateruk/items/06a6e4ffbb18307403c2\n*)\n\ntheory \"imp_register_compiler\" imports Main begin\n\n(*********************************************)\nsubsection \"Arithmetic Expressions\"\n(*********************************************)\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n  \"aval (N n) s = n\" |\n  \"aval (V x) s = s x\" |\n  \"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\" (* 12 *)\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\" (* 12 *)\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\" (* 12 *)\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\" (* 5 *)\n\n(*********************************************)\nsubsection \"Constant Folding\"\n(*********************************************)\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n  \"asimp_const (N n) = N n\" |\n  \"asimp_const (V x) = V x\" |\n  \"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\n\nlemma aval_asimp_const : \"aval (asimp_const a) s = aval a s\"\n  apply (induction a)\n    apply (auto split: aexp.split)\ndone\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n  \"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n  \"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n  \"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n\nlemma aval_plus [simp] : \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction a1 a2 rule: plus.induct)\n              apply simp_all (* just for a change from auto *)\n  done\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n  \"asimp (N n) = N n\" |\n  \"asimp (V x) = V x\" |\n  \"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\" (* \"V ''x''\" *)\n\nlemma aval_asimp [simp] : \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n    apply simp_all\n  done\n\n(*********************************************)\nsubsection \"Register Machine\"\n(*********************************************)\n\ntype_synonym reg = nat\ntype_synonym rstate = \"reg \\<Rightarrow> val\"\n\ndatatype instr = LDI val reg | LD vname reg | ADD reg reg\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> reg \\<Rightarrow> val\" where\n  \"exec1 (LDI n R) s rs r = (if R = r then n else rs(r))\" |\n  \"exec1 (LD  x R) s rs r = (if R = r then s(x) else rs(r))\" |\n  \"exec1 (ADD R S) s rs r = (if R = r then rs(R) + rs(S) else rs(r))\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> reg \\<Rightarrow> val\" where\n  \"exec [] s rs r = rs(r)\" |\n  \"exec (i # is) s rs r = exec is s (exec1 i s rs) r\"\n\nvalue \"exec [LDI 5 0, LD ''y'' 1, ADD 0 1] <''x'' := 42, ''y'' := 43> \n<0 := 0, 1 := 0, 2 := 50> 0\" (* 48 *)\n\n(*********************************************)\nsubsection \"Compilation\"\n(*********************************************)\n\nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n  \"comp (N n) r = [LDI n r]\" |\n  \"comp (V v) r = [LD v r]\" |\n  \"comp (Plus a1 a2) r = (comp a1 r) @ (comp a2 (r + 1)) @ [ADD r (r + 1)]\"\n \nvalue \"comp (Plus (Plus (V ''x'') (N 1)) (V ''z'')) 0\"\n (* \"[LD ''x'' 0, LDI 1 1, ADD 0 1, LD ''z'' 1, ADD 0 1]\" *)\n\nfun execn :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n  \"execn [] s rs = rs\" |\n  \"execn (i # is) s rs = execn is s (exec1 i s rs)\"\n\nlemma exec_execn : \"exec is1 s rs r = (execn is1 s rs) r\"\n  apply (induction is1 arbitrary: rs)\n   apply auto  \n  done\n\nlemma execn_dist_append : \"(execn (is1 @ is2) s rs) = (execn is2 s (execn is1 s rs))\"  \n  apply (induction is1 arbitrary: rs)\n   apply auto\n  done\n\nlemma execn_comp_append : \"(execn ((comp a r) @ is2) s rs) = (execn is2 s (execn (comp a r) s rs))\"\n  apply (auto simp add: execn_dist_append)\n  done\n\nlemma comp_left_rs_not_changed : \"r1 > r \\<Longrightarrow> execn (comp a r1) s rs r = rs(r)\"\n  apply (induction a arbitrary: r r1 rs)\n    apply (auto simp add: execn_dist_append)\n  done\n\ntheorem \"exec (comp a r) s rs r = aval a s\"\n  apply (induction a arbitrary: r rs)\n    apply (auto simp add: exec_execn execn_comp_append comp_left_rs_not_changed)\n  done\n\nend", "meta": {"author": "suharahiromichi", "repo": "isabelle", "sha": "9c4969e67b9cbbf87edfc926d609c446c8d71824", "save_path": "github-repos/isabelle/suharahiromichi-isabelle", "path": "github-repos/isabelle/suharahiromichi-isabelle/isabelle-9c4969e67b9cbbf87edfc926d609c446c8d71824/cs/imp_register_compiler.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.8633915976709976, "lm_q1q2_score": 0.7646467705213467}}
{"text": "theory BinarySearch\n  imports \"../Refine_Imperative_HOL/IICF/IICF\" \n     \"NREST.RefineMonadicVCG\" \"Imperative_HOL_Time.Asymptotics_1D\"\nbegin\nsection \"Binary Search\"                           \n\ndefinition avg :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"avg l r = (l + r) div 2\"\n\ndefinition \"listlookup_time = 1\"\n\nfunction binarysearch_time :: \"nat \\<Rightarrow> nat\" where\n  \"n < 2 \\<Longrightarrow> binarysearch_time n = 2 + listlookup_time\"\n| \"n \\<ge> 2 \\<Longrightarrow> binarysearch_time n = 2 + listlookup_time + binarysearch_time (n div 2)\"\nby force simp_all\ntermination by (relation \"Wellfounded.measure (\\<lambda>n. n)\") auto\n\ndefinition binarysearch_time' :: \"nat \\<Rightarrow> real\" where\n  \"binarysearch_time' n = real (binarysearch_time n)\"\n\nlemma div_2_to_rounding:\n  \"n - n div 2 = nat \\<lceil>n / 2\\<rceil>\" \"n div 2 = nat \\<lfloor>n / 2\\<rfloor>\" by linarith+\n\nlemma binarysearch_time'_Theta: \"(\\<lambda>n. binarysearch_time' n) \\<in> \\<Theta>(\\<lambda>n. ln (real n))\"\n  apply (master_theorem2 2.3 recursion: binarysearch_time.simps(2) rew: binarysearch_time'_def div_2_to_rounding)\n  unfolding listlookup_time_def\n  prefer 2 apply auto2\n  by (auto simp: binarysearch_time'_def)\n\nlemma binarysearch_mono:\n  \"m \\<le> n \\<Longrightarrow> binarysearch_time m \\<le> binarysearch_time n\" \nproof (induction n arbitrary: m rule: less_induct)\n  case (less n)\n  show ?case\n  proof (cases \"m<2\")\n    case True\n    then show ?thesis apply (cases \"n<2\") by auto\n  next\n    case False\n    then show ?thesis using less(2) by (auto intro: less(1))\n  qed\nqed\n\ndefinition binarysearch_SPEC :: \"nat \\<Rightarrow> nat \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> bool nrest\" where\n  \"binarysearch_SPEC l r xs x\n   = SPECT (emb (\\<lambda>s. s \\<longleftrightarrow> (\\<exists>i. l \\<le> i \\<and> i < r \\<and> xs ! i = x)) (binarysearch_time (r-l)) )\"\n\ndefinition \"binarysearch l r x xs \\<equiv>\n    RECT (\\<lambda>fw (l,r).\n      if l \\<ge> r then RETURNT False\n    else if l + 1 \\<ge> r then do {\n              ASSERT (l < length xs);\n             xsi \\<leftarrow> mop_lookup_list (\\<lambda>_. listlookup_time) xs l;\n                                RETURNT (xsi = x) }\n    else do {\n        m \\<leftarrow> RETURNT (avg l r);\n        ASSERT (m < length xs);\n        xm \\<leftarrow> mop_lookup_list (\\<lambda>_. listlookup_time) xs m;\n      (if xm = x then RETURNT True\n      else if xm < x then fw (m + 1, r)\n      else fw (l, m))\n      }\n  ) (l,r)\"\n\nprepare_code_thms binarysearch_def\nprint_theorems\nthm binarysearch.code(1,2) \n\n \nlemma avg_diff1: \"(l::nat) \\<le> r \\<Longrightarrow> r - (avg l r + 1) \\<le> (r - l) div 2\" by (simp add: avg_def)\nlemma avg_diff2: \"(l::nat) \\<le> r \\<Longrightarrow> avg l r - l \\<le> (r - l) div 2\" by  (simp add: avg_def)\n\nlemma avg_between [backward] :\n  \"l + 1 < r \\<Longrightarrow> r > avg l r\"\n  \"l + 1 < r \\<Longrightarrow> avg l r > l\" by (auto simp: avg_def)\n\nlemma binarysearch_correct: \"sorted xs \\<Longrightarrow> l \\<le> r \\<Longrightarrow> r \\<le> length xs \\<Longrightarrow>\n   binarysearch l r x xs \\<le> binarysearch_SPEC l r xs x\"\n  unfolding binarysearch_SPEC_def \n  apply(rule T_specifies_I)\n    apply(subst binarysearch.code(1))\nproof(induct \"r-l\" arbitrary: l r rule: less_induct)\n  case less\n  from less(2-4) show ?case apply(subst binarysearch.code(2))  unfolding mop_lookup_list_def\n     apply (vcg'\\<open>simp\\<close> rules: less(1)[THEN T_conseq4] )   \n    unfolding Some_le_emb'_conv Some_eq_emb'_conv\n    subgoal by auto \n    subgoal using le_less_Suc_eq by fastforce\n    subgoal apply (simp) by auto2 \n    subgoal by(simp add: avg_def)  \n    subgoal by(simp add: avg_def)  \n    subgoal \n      apply (rule allI conjI) apply auto2\n        using binarysearch_mono[OF avg_diff1] \n        by (simp add: le_SucI)\n    subgoal by(simp add: avg_def)    \n    subgoal by(simp add: avg_def) \n    subgoal \n      apply (rule allI conjI) apply auto2  \n        using binarysearch_mono[OF avg_diff2] \n        by (simp add: le_SucI) \n    subgoal by auto2\n    done\n  \nqed\n \nsepref_definition binarysearch_impl is \n  \"uncurry3 binarysearch\" :: \"nat_assn\\<^sup>k *\\<^sub>a nat_assn\\<^sup>k *\\<^sub>a id_assn\\<^sup>k *\\<^sub>a array_assn\\<^sup>k \\<rightarrow>\\<^sub>a bool_assn\"\n  unfolding binarysearch_def avg_def  listlookup_time_def\n  using [[goals_limit = 3]] \n  by sepref\n\nthm binarysearch_impl.refine[to_hnr]\nthm hnr_refine[OF binarysearch_correct ] binarysearch_impl.refine[to_hnr, unfolded autoref_tag_defs]\nthm  hnr_refine[OF binarysearch_correct, OF _ _ _ binarysearch_impl.refine[to_hnr, unfolded autoref_tag_defs], no_vars] \n\nlemma binary_search_impl_correct: \n  assumes \"sorted xs\" \"l \\<le> r\" \"r \\<le> length xs\"\n  shows \"hn_refine (hn_ctxt array_assn xs bi * hn_val Id x bia * hn_val nat_rel r bib * hn_val nat_rel l ai)\n            (binarysearch_impl ai bib bia bi)\n            (hn_ctxt array_assn xs bi * hn_val Id x bia * hn_val nat_rel r bib * hn_val nat_rel l ai) \n            bool_assn (binarysearch_SPEC l r xs x)\"\n  using assms hnr_refine[OF binarysearch_correct, OF _ _ _ binarysearch_impl.refine[to_hnr, unfolded autoref_tag_defs]] by metis\n\nthm extract_cost_ub'[OF binary_search_impl_correct[unfolded  binarysearch_SPEC_def], where Cost_ub=\"binarysearch_time (r - l)\" ]\nlemma binary_search_correct': \"sorted xs \\<Longrightarrow> r \\<le> length xs \\<Longrightarrow> l \\<le> r \\<Longrightarrow> \n     <hn_ctxt array_assn xs p * hn_val Id x bia * hn_val nat_rel r bib * hn_val nat_rel l ai * timeCredit_assn (binarysearch_time (r - l))> \n        binarysearch_impl ai bib bia p\n       <\\<lambda>ra. hn_ctxt array_assn xs p * \\<up> (ra \\<longleftrightarrow> (\\<exists>i\\<ge>l. i < r \\<and> xs ! i = x))>\\<^sub>t\"\n  apply(rule extract_cost_ub'[OF binary_search_impl_correct[unfolded  binarysearch_SPEC_def], where Cost_ub=\"binarysearch_time (r - l)\" ])\n       apply auto\n     apply(subst in_ran_emb_special_case) apply (simp_all add: pure_def) apply auto\n   by (metis (no_types, lifting) ent_true_drop(1) entails_ex entt_refl') \n\n\nsubsection \\<open>Final Hoare triple and run-time claim.\\<close>\n\nlemma binary_search_correct: \"sorted xs \\<Longrightarrow> r \\<le> length xs \\<Longrightarrow> l \\<le> r \\<Longrightarrow> \n     <array_assn xs p * timeCredit_assn (binarysearch_time (r - l))> \n        binarysearch_impl l r x p\n       <\\<lambda>ra.   array_assn xs p * \\<up> (ra \\<longleftrightarrow> (\\<exists>i\\<ge>l. i < r \\<and> xs ! i = x))>\\<^sub>t\"\n  apply(rule ht_cons_rule[OF _ _ binary_search_correct'[ unfolded hn_ctxt_def pure_def ]])\n  by (sep_auto )+\n\nlemma binary_search_time_ln: \"binarysearch_time \\<in> \\<Theta>(\\<lambda>n. ln (real n))\"\n  using binarysearch_time'_Theta unfolding binarysearch_time'_def by auto\n\nend", "meta": {"author": "maxhaslbeck", "repo": "Sepreftime", "sha": "c1c987b45ec886d289ba215768182ac87b82f20d", "save_path": "github-repos/isabelle/maxhaslbeck-Sepreftime", "path": "github-repos/isabelle/maxhaslbeck-Sepreftime/Sepreftime-c1c987b45ec886d289ba215768182ac87b82f20d/Examples/BinarySearch.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7645603752551448}}
{"text": "theory Chapter9_2\nimports \"~~/src/HOL/IMP/Sec_Typing\"\nbegin\n\ntext{*\n\\exercise\nReformulate the inductive predicate @{const sec_type}\nas a recursive function and prove the equivalence of the two formulations:\n*}\n\nfun ok :: \"level \\<Rightarrow> com \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntheorem \"(l \\<turnstile> c) = ok l c\"\n(* your definition/proof here *)\n\ntext{*\nTry to reformulate the bottom-up system @{prop \"\\<turnstile> c : l\"}\nas a function that computes @{text l} from @{text c}. What difficulty do you face?\n\\endexercise\n\n\\exercise\nDefine a bottom-up termination insensitive security type system\n@{text\"\\<turnstile>' c : l\"} with subsumption rule:\n*}\n\ninductive sec_type2' :: \"com \\<Rightarrow> level \\<Rightarrow> bool\" (\"(\\<turnstile>' _ : _)\" [0,0] 50) where\n(* your definition/proof here *)\n\ntext{*\nProve equivalence with the bottom-up system @{prop \"\\<turnstile> c : l\"}\nwithout subsumption rule:\n*}\n\nlemma \"\\<turnstile> c : l \\<Longrightarrow> \\<turnstile>' c : l\"\n(* your definition/proof here *)\n\nlemma \"\\<turnstile>' c : l \\<Longrightarrow> \\<exists>l' \\<ge> l. \\<turnstile> c : l'\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a function that erases those parts of a command that\ncontain variables above some security level: *}\n\nfun erase :: \"level \\<Rightarrow> com \\<Rightarrow> com\" where\n(* your definition/proof here *)\n\ntext{*\nFunction @{term \"erase l\"} should replace all assignments to variables with\nsecurity level @{text\"\\<ge> l\"} by @{const SKIP}.\nIt should also erase certain @{text IF}s and @{text WHILE}s,\ndepending on the security level of the boolean condition. Now show\nthat @{text c} and @{term \"erase l c\"} behave the same on the variables up\nto level @{text l}: *}\n\ntheorem \"\\<lbrakk> (c,s) \\<Rightarrow> s';  (erase l c,t) \\<Rightarrow> t';  0 \\<turnstile> c;  s = t (< l) \\<rbrakk>\n   \\<Longrightarrow> s' = t' (< l)\"\n(* your definition/proof here *)\n\ntext{* This theorem looks remarkably like the noninterference lemma from\ntheory \\mbox{@{theory Sec_Typing}} (although @{text\"\\<le>\"} has been replaced by @{text\"<\"}).\nYou may want to start with that proof and modify it.\nThe structure should remain the same. You may also need one or\ntwo simple additional lemmas.\n\nIn the theorem above we assume that both @{term\"(c,s)\"}\nand @{term \"(erase l c,t)\"} terminate. How about the following two properties: *}\n\nlemma \"\\<lbrakk> (c,s) \\<Rightarrow> s';  0 \\<turnstile> c;  s = t (< l) \\<rbrakk>\n  \\<Longrightarrow> \\<exists>t'. (erase l c, t) \\<Rightarrow> t' \\<and> s' = t' (< l)\"\n(* your definition/proof here *)\n\n\nlemma \"\\<lbrakk> (erase l c,s) \\<Rightarrow> s';  0 \\<turnstile> c;  s = t (< l) \\<rbrakk>\n  \\<Longrightarrow> \\<exists>t'. (c,t) \\<Rightarrow> t' \\<and> s' = t' (< l)\"\n(* your definition/proof here *)\n\ntext{* Give proofs or counterexamples.\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "EduPH", "repo": "concrete-semantics-Sols", "sha": "ab33a5ea3b3752c3cf62468cb5b97d9ad8669be2", "save_path": "github-repos/isabelle/EduPH-concrete-semantics-Sols", "path": "github-repos/isabelle/EduPH-concrete-semantics-Sols/concrete-semantics-Sols-ab33a5ea3b3752c3cf62468cb5b97d9ad8669be2/Chapter9_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7645603745279297}}
{"text": "(*  Author: Tobias Nipkow, Alex Krauss, Dmitriy Traytel  *)\n\nsection \"Regular Sets\"\n\n(*<*)\ntheory Pi_Regular_Set\nimports Main\nbegin\n(*>*)\n\ntype_synonym 'a lang = \"'a list set\"\n\ndefinition conc :: \"'a lang \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\" (infixr \"@@\" 75) where\n\"A @@ B = {xs@ys | xs ys. xs:A & ys:B}\"\n\n\n\noverloading word_pow == \"compow :: nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nbegin\n  primrec word_pow :: \"nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"word_pow 0 w = []\" |\n  \"word_pow (Suc n) w = w @ word_pow n w\"\nend\n\noverloading lang_pow == \"compow :: nat \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nbegin\n  primrec lang_pow :: \"nat \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\" where\n  \"lang_pow 0 A = {[]}\" |\n  \"lang_pow (Suc n) A = A @@ (lang_pow n A)\"\nend\n\nlemma word_pow_alt: \"compow n w = concat (replicate n w)\"\n  by (induct n) auto\n\ndefinition star :: \"'a lang \\<Rightarrow> 'a lang\" where\n\"star A = (\\<Union>n. A ^^ n)\"\n\n\nsubsection\\<open>Concatenation of Languages\\<close>\n\nlemma concI[simp,intro]: \"u : A \\<Longrightarrow> v : B \\<Longrightarrow> u@v : A @@ B\"\n  by (auto simp add: conc_def)\n\nlemma concE[elim]: \nassumes \"w \\<in> A @@ B\"\nobtains u v where \"u \\<in> A\" \"v \\<in> B\" \"w = u@v\"\n  using assms by (auto simp: conc_def)\n\nlemma conc_mono: \"A \\<subseteq> C \\<Longrightarrow> B \\<subseteq> D \\<Longrightarrow> A @@ B \\<subseteq> C @@ D\"\n  by (auto simp: conc_def) \n\nlemma conc_empty[simp]: shows \"{} @@ A = {}\" and \"A @@ {} = {}\"\n  by auto\n\nlemma conc_epsilon[simp]: shows \"{[]} @@ A = A\" and \"A @@ {[]} = A\"\n  by (simp_all add:conc_def)\n\nlemma conc_assoc: \"(A @@ B) @@ C = A @@ (B @@ C)\"\n  by (auto elim!: concE) (simp only: append_assoc[symmetric] concI)\n\nlemma conc_Un_distrib:\nshows \"A @@ (B \\<union> C) = A @@ B \\<union> A @@ C\"\nand   \"(A \\<union> B) @@ C = A @@ C \\<union> B @@ C\"\n  by auto\n\nlemma conc_UNION_distrib:\nshows \"A @@ \\<Union>(M ` I) = \\<Union>((%i. A @@ M i) ` I)\"\nand   \"\\<Union>(M ` I) @@ A = \\<Union>((%i. M i @@ A) ` I)\"\n  by auto\n\nlemma hom_image_conc: \"\\<lbrakk>\\<And>xs ys. f (xs @ ys) = f xs @ f ys\\<rbrakk> \\<Longrightarrow> f ` (A @@ B) = f ` A @@ f ` B\"\n  unfolding conc_def by (auto simp: image_iff) metis\n\nlemma map_image_conc[simp]: \"map f ` (A @@ B) = map f ` A @@ map f ` B\"\n  by (simp add: hom_image_conc)\n\nlemma conc_subset_lists: \"A \\<subseteq> lists S \\<Longrightarrow> B \\<subseteq> lists S \\<Longrightarrow> A @@ B \\<subseteq> lists S\"\n  by(fastforce simp: conc_def in_lists_conv_set)\n\n\nsubsection\\<open>Iteration of Languages\\<close>\n\nlemma lang_pow_add: \"A ^^ (n + m) = A ^^ n @@ A ^^ m\"\n  by (induct n) (auto simp: conc_assoc)\n\nlemma lang_pow_simps: \"(A ^^ Suc n) = (A ^^ n @@ A)\"\n  using lang_pow_add[of n \"Suc 0\" A] by auto\n\nlemma lang_pow_empty: \"{} ^^ n = (if n = 0 then {[]} else {})\"\n  by (induct n) auto\n\nlemma lang_pow_empty_Suc[simp]: \"({}::'a lang) ^^ Suc n = {}\"\n  by (simp add: lang_pow_empty)\n\n\n\nlemma length_lang_pow_ub:\n  \"ALL w : A. length w \\<le> k \\<Longrightarrow> w : A^^n \\<Longrightarrow> length w \\<le> k*n\"\n  by(induct n arbitrary: w) (fastforce simp: conc_def)+\n\nlemma length_lang_pow_lb:\n  \"ALL w : A. length w \\<ge> k \\<Longrightarrow> w : A^^n \\<Longrightarrow> length w \\<ge> k*n\"\n  by(induct n arbitrary: w) (fastforce simp: conc_def)+\n\nlemma lang_pow_subset_lists: \"A \\<subseteq> lists S \\<Longrightarrow> A ^^ n \\<subseteq> lists S\"\n  by (induct n) (auto simp: conc_subset_lists)\n\nlemma star_subset_lists: \"A \\<subseteq> lists S \\<Longrightarrow> star A \\<subseteq> lists S\"\n  unfolding star_def by(blast dest: lang_pow_subset_lists)\n\nlemma star_if_lang_pow[simp]: \"w : A ^^ n \\<Longrightarrow> w : star A\"\n  by (auto simp: star_def)\n\nlemma Nil_in_star[iff]: \"[] : star A\"\nproof (rule star_if_lang_pow)\n  show \"[] : A ^^ 0\" by simp\nqed\n\nlemma star_if_lang[simp]: assumes \"w : A\" shows \"w : star A\"\nproof (rule star_if_lang_pow)\n  show \"w : A ^^ 1\" using \\<open>w : A\\<close> by simp\nqed\n\nlemma append_in_starI[simp]:\nassumes \"u : star A\" and \"v : star A\" shows \"u@v : star A\"\nproof -\n  from \\<open>u : star A\\<close> obtain m where \"u : A ^^ m\" by (auto simp: star_def)\n  moreover\n  from \\<open>v : star A\\<close> obtain n where \"v : A ^^ n\" by (auto simp: star_def)\n  ultimately have \"u@v : A ^^ (m+n)\" by (simp add: lang_pow_add)\n  thus ?thesis by simp\nqed\n\nlemma conc_star_star: \"star A @@ star A = star A\"\n  by (auto simp: conc_def)\n\nlemma conc_star_comm:\n  shows \"A @@ star A = star A @@ A\"\n  unfolding star_def conc_pow_comm conc_UNION_distrib\n  by simp\n\nlemma star_induct[consumes 1, case_names Nil append, induct set: star]:\nassumes \"w : star A\"\n  and \"P []\"\n  and step: \"!!u v. u : A \\<Longrightarrow> v : star A \\<Longrightarrow> P v \\<Longrightarrow> P (u@v)\"\nshows \"P w\"\nproof -\n  { fix n have \"w : A ^^ n \\<Longrightarrow> P w\"\n    by (induct n arbitrary: w) (auto intro: \\<open>P []\\<close> step star_if_lang_pow) }\n  with \\<open>w : star A\\<close> show \"P w\" by (auto simp: star_def)\nqed\n\nlemma star_empty[simp]: \"star {} = {[]}\"\n  by (auto elim: star_induct)\n\nlemma star_epsilon[simp]: \"star {[]} = {[]}\"\n  by (auto elim: star_induct)\n\nlemma star_idemp[simp]: \"star (star A) = star A\"\n  by (auto elim: star_induct)\n\nlemma star_unfold_left: \"star A = A @@ star A \\<union> {[]}\" (is \"?L = ?R\")\nproof\n  show \"?L \\<subseteq> ?R\" by (rule, erule star_induct) auto\nqed auto\n\nlemma concat_in_star: \"set ws \\<subseteq> A \\<Longrightarrow> concat ws : star A\"\n  by (induct ws) simp_all\n\nlemma in_star_iff_concat:\n  \"w : star A = (EX ws. set ws \\<subseteq> A & w = concat ws & [] \\<notin> set ws)\"\n  (is \"_ = (EX ws. ?R w ws)\")\nproof\n  assume \"w : star A\" thus \"EX ws. ?R w ws\"\n  proof induct\n    case Nil have \"?R [] []\" by simp\n    thus ?case ..\n  next\n    case (append u v)\n    moreover\n    then obtain ws where \"set ws \\<subseteq> A \\<and> v = concat ws \\<and> [] \\<notin> set ws\" by blast\n    ultimately have \"?R (u@v) (if u = [] then ws else u#ws)\" by auto\n    thus ?case ..\n  qed\nnext\n  assume \"EX us. ?R w us\" thus \"w : star A\"\n  by (auto simp: concat_in_star)\nqed\n\nlemma star_conv_concat: \"star A = {concat ws|ws. set ws \\<subseteq> A & [] \\<notin> set ws}\"\n  by (fastforce simp: in_star_iff_concat)\n\nlemma star_insert_eps[simp]: \"star (insert [] A) = star(A)\"\nproof-\n  { fix us\n    have \"set us \\<subseteq> insert [] A \\<Longrightarrow> EX vs. concat us = concat vs \\<and> set vs \\<subseteq> A\"\n      (is \"?P \\<Longrightarrow> EX vs. ?Q vs\")\n    proof\n      let ?vs = \"filter (%u. u \\<noteq> []) us\"\n      show \"?P \\<Longrightarrow> ?Q ?vs\" by (induct us) auto\n    qed\n  } thus ?thesis by (auto simp: star_conv_concat)\nqed\n\nlemma star_decom: \n  assumes a: \"x \\<in> star A\" \"x \\<noteq> []\"\n  shows \"\\<exists>a b. x = a @ b \\<and> a \\<noteq> [] \\<and> a \\<in> A \\<and> b \\<in> star A\"\n  using a by (induct rule: star_induct) (blast)+\n\nlemma Ball_starI: \"\\<forall>a \\<in> set as. [a] \\<in> A \\<Longrightarrow> as \\<in> star A\"\n  by (induct as rule: rev_induct) auto\n\nlemma map_image_star[simp]: \"map f ` star A = star (map f ` A)\"\n  by (auto elim: star_induct) (auto elim: star_induct simp del: map_append simp: map_append[symmetric] intro!: imageI)\n\nsubsection \\<open>Left-Quotients of Languages\\<close>\n\ndefinition lQuot :: \"'a \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nwhere \"lQuot x A = { xs. x#xs \\<in> A }\"\n\ndefinition lQuots :: \"'a list \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nwhere \"lQuots xs A = { ys. xs @ ys \\<in> A }\"\n\nabbreviation \n  lQuotss :: \"'a list \\<Rightarrow> 'a lang set \\<Rightarrow> 'a lang\"\nwhere\n  \"lQuotss s As \\<equiv> \\<Union> (lQuots s ` As)\"\n\n\nlemma lQuot_empty[simp]:   \"lQuot a {} = {}\"\n  and lQuot_epsilon[simp]: \"lQuot a {[]} = {}\"\n  and lQuot_char[simp]:    \"lQuot a {[b]} = (if a = b then {[]} else {})\"\n  and lQuot_chars[simp]:   \"lQuot a {[b] | b. P b} = (if P a then {[]} else {})\"\n  and lQuot_union[simp]:   \"lQuot a (A \\<union> B) = lQuot a A \\<union> lQuot a B\"\n  and lQuot_inter[simp]:   \"lQuot a (A \\<inter> B) = lQuot a A \\<inter> lQuot a B\"\n  and lQuot_compl[simp]:   \"lQuot a (-A) = - lQuot a A\"\n  by (auto simp: lQuot_def)\n\nlemma lQuot_conc_subset: \"lQuot a A @@ B \\<subseteq> lQuot a (A @@ B)\" (is \"?L \\<subseteq> ?R\")\nproof \n  fix w assume \"w \\<in> ?L\"\n  then obtain u v where \"w = u @ v\" \"a # u \\<in> A\" \"v \\<in> B\"\n    by (auto simp: lQuot_def)\n  then have \"a # w \\<in> A @@ B\"\n    by (auto intro: concI[of \"a # u\", simplified])\n  thus \"w \\<in> ?R\" by (auto simp: lQuot_def)\nqed\n\nlemma lQuot_conc [simp]: \"lQuot c (A @@ B) = (lQuot c A) @@ B \\<union> (if [] \\<in> A then lQuot c B else {})\"\n  unfolding lQuot_def conc_def\n  by (auto simp add: Cons_eq_append_conv)\n\nlemma lQuot_star [simp]: \"lQuot c (star A) = (lQuot c A) @@ star A\"\nproof -\n  have incl: \"[] \\<in> A \\<Longrightarrow> lQuot c (star A) \\<subseteq> (lQuot c A) @@ star A\"\n    unfolding lQuot_def conc_def \n    apply(auto simp add: Cons_eq_append_conv)\n    apply(drule star_decom)\n    apply(auto simp add: Cons_eq_append_conv)\n    done\n\n  have \"lQuot c (star A) = lQuot c (A @@ star A \\<union> {[]})\"\n    by (simp only: star_unfold_left[symmetric])\n  also have \"... = lQuot c (A @@ star A)\"\n    by (simp only: lQuot_union) (simp)\n  also have \"... =  (lQuot c A) @@ (star A) \\<union> (if [] \\<in> A then lQuot c (star A) else {})\"\n    by simp\n   also have \"... =  (lQuot c A) @@ star A\"\n    using incl by auto\n  finally show \"lQuot c (star A) = (lQuot c A) @@ star A\" . \nqed\n\nlemma lQuot_diff[simp]: \"lQuot c (A - B) = lQuot c A - lQuot c B\"\n  by(auto simp add: lQuot_def)\n\nlemma lQuot_lists[simp]: \"c : S \\<Longrightarrow> lQuot c (lists S) = lists S\"\n  by(auto simp add: lQuot_def)\n\nlemma lQuots_simps [simp]:\n  shows \"lQuots [] A = A\"\n  and   \"lQuots (c # s) A = lQuots s (lQuot c A)\"\n  and   \"lQuots (s1 @ s2) A = lQuots s2 (lQuots s1 A)\"\n  unfolding lQuots_def lQuot_def by auto\n\nlemma lQuots_append[iff]: \"v \\<in> lQuots w A \\<longleftrightarrow> w @ v \\<in> A\"\n  by (induct w arbitrary: v A) (auto simp add: lQuot_def)\n\nsubsection \\<open>Right-Quotients of Languages\\<close>\n\ndefinition rQuot :: \"'a \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nwhere \"rQuot x A = { xs. xs @ [x] \\<in> A }\"\n\ndefinition rQuots :: \"'a list \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nwhere \"rQuots xs A = { ys. ys @ rev xs \\<in> A }\"\n\nabbreviation \n  rQuotss :: \"'a list \\<Rightarrow> 'a lang set \\<Rightarrow> 'a lang\"\nwhere\n  \"rQuotss s As \\<equiv> \\<Union> (rQuots s ` As)\"\n\nlemma rQuot_rev_lQuot: \"rQuot x A = rev ` lQuot x (rev ` A)\"\n  unfolding rQuot_def lQuot_def by (auto simp: rev_swap[symmetric])\n\nlemma rQuots_rev_lQuots: \"rQuots x A = rev ` lQuots x (rev ` A)\"\n  unfolding rQuots_def lQuots_def by (auto simp: rev_swap[symmetric])\n\nlemma rQuot_empty[simp]:   \"rQuot a {} = {}\"\n  and rQuot_epsilon[simp]: \"rQuot a {[]} = {}\"\n  and rQuot_char[simp]:    \"rQuot a {[b]} = (if a = b then {[]} else {})\"\n  and rQuot_union[simp]:   \"rQuot a (A \\<union> B) = rQuot a A \\<union> rQuot a B\"\n  and rQuot_inter[simp]:   \"rQuot a (A \\<inter> B) = rQuot a A \\<inter> rQuot a B\"\n  and rQuot_compl[simp]:   \"rQuot a (-A) = - rQuot a A\"\n  by (auto simp: rQuot_def)\n\nlemma lQuot_rQuot: \"lQuot a (rQuot b A) = rQuot b (lQuot a A)\"\n  unfolding lQuot_def rQuot_def by auto\n\nlemma rQuot_lQuot: \"rQuot a (lQuot b A) = lQuot b (rQuot a A)\"\n  unfolding lQuot_def rQuot_def by auto\n\nlemma rev_simp_invert: \"(xs @ [x] = rev zs) = (zs = x # rev xs)\"\n  by (induct zs) auto\n\nlemma rev_append_invert: \"(xs @ ys = rev zs) = (zs = rev ys @ rev xs)\"\n  by (induct xs arbitrary: ys rule: rev_induct) auto\n\nlemma image_rev_lists[simp]: \"rev ` lists S = lists S\"\nproof (intro set_eqI)\n  fix xs\n  show \"xs \\<in> rev ` lists S \\<longleftrightarrow> xs \\<in> lists S\"\n  proof (induct xs rule: rev_induct)\n    case (snoc x xs)\n    thus ?case by (auto intro!: image_eqI[of _ rev] simp: rev_simp_invert)\n  qed simp\nqed\n\nlemma image_rev_conc[simp]: \"rev ` (A @@ B) = rev ` B @@ rev ` A\"\n  by auto (auto simp: rev_append[symmetric] simp del: rev_append)\n\nlemma image_rev_star[simp]: \"rev ` star A = star (rev ` A)\"\n  by (auto elim: star_induct) (auto elim: star_induct simp: rev_append[symmetric] simp del: rev_append)\n\nlemma rQuot_conc [simp]: \"rQuot c (A @@ B) = A @@ (rQuot c B) \\<union> (if [] \\<in> B then rQuot c A else {})\"\n  unfolding rQuot_rev_lQuot by (auto simp: image_image image_Un)\n\nlemma rQuot_star [simp]: \"rQuot c (star A) = star A @@ (rQuot c A)\"\n  unfolding rQuot_rev_lQuot by (auto simp: image_image)\n\nlemma rQuot_diff[simp]: \"rQuot c (A - B) = rQuot c A - rQuot c B\"\n  by(auto simp add: rQuot_def)\n\nlemma rQuot_lists[simp]: \"c : S \\<Longrightarrow> rQuot c (lists S) = lists S\"\n  by(auto simp add: rQuot_def)\n\nlemma rQuots_simps [simp]:\n  shows \"rQuots [] A = A\"\n  and   \"rQuots (c # s) A = rQuots s (rQuot c A)\"\n  and   \"rQuots (s1 @ s2) A = rQuots s2 (rQuots s1 A)\"\n  unfolding rQuots_def rQuot_def by auto\n\nlemma rQuots_append[iff]: \"v \\<in> rQuots w A \\<longleftrightarrow> v @ rev w \\<in> A\"\n  by (induct w arbitrary: v A) (auto simp add: rQuot_def)\n\nsubsection \\<open>Two-Sided-Quotients of Languages\\<close>\n\ndefinition biQuot :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nwhere \"biQuot x y A = { xs. x # xs @ [y] \\<in> A }\"\n\ndefinition biQuots :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a lang \\<Rightarrow> 'a lang\"\nwhere \"biQuots xs ys A = { zs. xs @ zs @ rev ys \\<in> A }\"\n\nabbreviation \n  biQuotss :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a lang set \\<Rightarrow> 'a lang\"\nwhere\n  \"biQuotss xs ys As \\<equiv> \\<Union> (biQuots xs ys ` As)\"\n\nlemma biQuot_rQuot_lQuot: \"biQuot x y A = rQuot y (lQuot x A)\"\n  unfolding biQuot_def rQuot_def lQuot_def by auto\n\nlemma biQuot_lQuot_rQuot: \"biQuot x y A = lQuot x (rQuot y A)\"\n  unfolding biQuot_def rQuot_def lQuot_def by auto\n\nlemma biQuots_rQuots_lQuots: \"biQuots x y A = rQuots y (lQuots x A)\"\n  unfolding biQuots_def rQuots_def lQuots_def by auto\n\nlemma biQuots_lQuots_rQuots: \"biQuots x y A = lQuots x (rQuots y A)\"\n  unfolding biQuots_def rQuots_def lQuots_def by auto\n\nlemma biQuot_empty[simp]:   \"biQuot a b {} = {}\"\n  and biQuot_epsilon[simp]: \"biQuot a b {[]} = {}\"\n  and biQuot_char[simp]:    \"biQuot a b {[c]} = {}\"\n  and biQuot_union[simp]:   \"biQuot a b (A \\<union> B) = biQuot a b A \\<union> biQuot a b B\"\n  and biQuot_inter[simp]:   \"biQuot a b (A \\<inter> B) = biQuot a b A \\<inter> biQuot a b B\"\n  and biQuot_compl[simp]:   \"biQuot a b (-A) = - biQuot a b A\"\n  by (auto simp: biQuot_def)\n\nlemma biQuot_conc [simp]: \"biQuot a b (A @@ B) =\n  lQuot a A @@ rQuot b B \\<union>\n  (if [] \\<in> A \\<and> [] \\<in> B then biQuot a b A \\<union> biQuot a b B\n  else if [] \\<in> A then biQuot a b B\n  else if [] \\<in> B then biQuot a b A\n  else {})\"\n  unfolding biQuot_rQuot_lQuot by auto\n\nlemma biQuot_star [simp]: \"biQuot a b (star A) = biQuot a b A \\<union> lQuot a A @@ star A @@ rQuot b A\"\n  unfolding biQuot_rQuot_lQuot by auto\n\nlemma biQuot_diff[simp]: \"biQuot a b (A - B) = biQuot a b A - biQuot a b B\"\n  by(auto simp add: biQuot_def)\n\nlemma biQuot_lists[simp]: \"a : S \\<Longrightarrow> b : S \\<Longrightarrow> biQuot a b (lists S) = lists S\"\n  by(auto simp add: biQuot_def)\n\nlemma biQuots_simps [simp]:\n  shows \"biQuots [] [] A = A\"\n  and   \"biQuots (a#as) (b#bs) A = biQuots as bs (biQuot a b A)\"\n  and   \"\\<lbrakk>length s1 = length t1; length s2 = length t2\\<rbrakk> \\<Longrightarrow>\n    biQuots (s1 @ s2) (t1 @ t2) A = biQuots s2 t2 (biQuots s1 t1 A)\"\n  unfolding biQuots_def biQuot_def by auto\n\nlemma biQuots_append[iff]: \"v \\<in> biQuots u w A \\<longleftrightarrow> u @ v @ rev w \\<in> A\"\n  unfolding biQuots_def by auto\n\nsubsection \\<open>Arden's Lemma\\<close>\n\nlemma arden_helper:\n  assumes eq: \"X = A @@ X \\<union> B\"\n  shows \"X = (A ^^ Suc n) @@ X \\<union> (\\<Union>m\\<le>n. (A ^^ m) @@ B)\"\nproof (induct n)\n  case 0 \n  show \"X = (A ^^ Suc 0) @@ X \\<union> (\\<Union>m\\<le>0. (A ^^ m) @@ B)\"\n    using eq by simp\nnext\n  case (Suc n)\n  have ih: \"X = (A ^^ Suc n) @@ X \\<union> (\\<Union>m\\<le>n. (A ^^ m) @@ B)\" by fact\n  also have \"\\<dots> = (A ^^ Suc n) @@ (A @@ X \\<union> B) \\<union> (\\<Union>m\\<le>n. (A ^^ m) @@ B)\" using eq by simp\n  also have \"\\<dots> = (A ^^ Suc (Suc n)) @@ X \\<union> ((A ^^ Suc n) @@ B) \\<union> (\\<Union>m\\<le>n. (A ^^ m) @@ B)\"\n    by (simp add: conc_Un_distrib conc_assoc[symmetric] conc_pow_comm)\n  also have \"\\<dots> = (A ^^ Suc (Suc n)) @@ X \\<union> (\\<Union>m\\<le>Suc n. (A ^^ m) @@ B)\"\n    by (auto simp add: atMost_Suc)\n  finally show \"X = (A ^^ Suc (Suc n)) @@ X \\<union> (\\<Union>m\\<le>Suc n. (A ^^ m) @@ B)\" .\nqed\n\nlemma Arden:\n  assumes \"[] \\<notin> A\" \n  shows \"X = A @@ X \\<union> B \\<longleftrightarrow> X = star A @@ B\"\nproof\n  assume eq: \"X = A @@ X \\<union> B\"\n  { fix w assume \"w : X\"\n    let ?n = \"size w\"\n    from \\<open>[] \\<notin> A\\<close> have \"ALL u : A. length u \\<ge> 1\"\n      by (metis Suc_eq_plus1 add_leD2 le_0_eq length_0_conv not_less_eq_eq)\n    hence \"ALL u : A^^(?n+1). length u \\<ge> ?n+1\"\n      by (metis length_lang_pow_lb nat_mult_1)\n    hence \"ALL u : A^^(?n+1)@@X. length u \\<ge> ?n+1\"\n      by(auto simp only: conc_def length_append)\n    hence \"w \\<notin> A^^(?n+1)@@X\" by auto\n    hence \"w : star A @@ B\" using \\<open>w : X\\<close> using arden_helper[OF eq, where n=\"?n\"]\n      by (auto simp add: star_def conc_UNION_distrib)\n  } moreover\n  { fix w assume \"w : star A @@ B\"\n    hence \"EX n. w : A^^n @@ B\" by(auto simp: conc_def star_def)\n    hence \"w : X\" using arden_helper[OF eq] by blast\n  } ultimately show \"X = star A @@ B\" by blast \nnext\n  assume eq: \"X = star A @@ B\"\n  have \"star A = A @@ star A \\<union> {[]}\"\n    by (rule star_unfold_left)\n  then have \"star A @@ B = (A @@ star A \\<union> {[]}) @@ B\"\n    by metis\n  also have \"\\<dots> = (A @@ star A) @@ B \\<union> B\"\n    unfolding conc_Un_distrib by simp\n  also have \"\\<dots> = A @@ (star A @@ B) \\<union> B\" \n    by (simp only: conc_assoc)\n  finally show \"X = A @@ X \\<union> B\" \n    using eq by blast \nqed\n\n\nlemma reversed_arden_helper:\n  assumes eq: \"X = X @@ A \\<union> B\"\n  shows \"X = X @@ (A ^^ Suc n) \\<union> (\\<Union>m\\<le>n. B @@ (A ^^ m))\"\nproof (induct n)\n  case 0 \n  show \"X = X @@ (A ^^ Suc 0) \\<union> (\\<Union>m\\<le>0. B @@ (A ^^ m))\"\n    using eq by simp\nnext\n  case (Suc n)\n  have ih: \"X = X @@ (A ^^ Suc n) \\<union> (\\<Union>m\\<le>n. B @@ (A ^^ m))\" by fact\n  also have \"\\<dots> = (X @@ A \\<union> B) @@ (A ^^ Suc n) \\<union> (\\<Union>m\\<le>n. B @@ (A ^^ m))\" using eq by simp\n  also have \"\\<dots> = X @@ (A ^^ Suc (Suc n)) \\<union> (B @@ (A ^^ Suc n)) \\<union> (\\<Union>m\\<le>n. B @@ (A ^^ m))\"\n    by (simp add: conc_Un_distrib conc_assoc)\n  also have \"\\<dots> = X @@ (A ^^ Suc (Suc n)) \\<union> (\\<Union>m\\<le>Suc n. B @@ (A ^^ m))\"\n    by (auto simp add: atMost_Suc)\n  finally show \"X = X @@ (A ^^ Suc (Suc n)) \\<union> (\\<Union>m\\<le>Suc n. B @@ (A ^^ m))\" .\nqed\n\ntheorem reversed_Arden:\n  assumes nemp: \"[] \\<notin> A\"\n  shows \"X = X @@ A \\<union> B \\<longleftrightarrow> X = B @@ star A\"\nproof\n assume eq: \"X = X @@ A \\<union> B\"\n  { fix w assume \"w : X\"\n    let ?n = \"size w\"\n    from \\<open>[] \\<notin> A\\<close> have \"ALL u : A. length u \\<ge> 1\"\n      by (metis Suc_eq_plus1 add_leD2 le_0_eq length_0_conv not_less_eq_eq)\n    hence \"ALL u : A^^(?n+1). length u \\<ge> ?n+1\"\n      by (metis length_lang_pow_lb nat_mult_1)\n    hence \"ALL u : X @@ A^^(?n+1). length u \\<ge> ?n+1\"\n      by(auto simp only: conc_def length_append)\n    hence \"w \\<notin> X @@ A^^(?n+1)\" by auto\n    hence \"w : B @@ star A\" using \\<open>w : X\\<close> using reversed_arden_helper[OF eq, where n=\"?n\"]\n      by (auto simp add: star_def conc_UNION_distrib)\n  } moreover\n  { fix w assume \"w : B @@ star A\"\n    hence \"EX n. w : B @@ A^^n\" by (auto simp: conc_def star_def)\n    hence \"w : X\" using reversed_arden_helper[OF eq] by blast\n  } ultimately show \"X = B @@ star A\" by blast \nnext \n  assume eq: \"X = B @@ star A\"\n  have \"star A = {[]} \\<union> star A @@ A\" \n    unfolding conc_star_comm[symmetric]\n    by(metis Un_commute star_unfold_left)\n  then have \"B @@ star A = B @@ ({[]} \\<union> star A @@ A)\"\n    by metis\n  also have \"\\<dots> = B \\<union> B @@ (star A @@ A)\"\n    unfolding conc_Un_distrib by simp\n  also have \"\\<dots> = B \\<union> (B @@ star A) @@ A\" \n    by (simp only: conc_assoc)\n  finally show \"X = X @@ A \\<union> B\" \n    using eq by blast \nqed\n\nsubsection \\<open>Lists of Fixed Length\\<close>\n\nabbreviation listsN where \"listsN n S \\<equiv> {xs. xs \\<in> lists S \\<and> length xs = n}\"\n\nlemma tl_listsN: \"A \\<subseteq> listsN (n + 1) S \\<Longrightarrow> tl ` A \\<subseteq> listsN n S\"\nproof (intro image_subsetI)\n  fix xs assume \"A \\<subseteq> listsN (n + 1) S\" \"xs \\<in> A\"\n  thus \"tl xs \\<in> listsN n S\" by (induct xs) auto\nqed\n\nlemma map_tl_listsN: \"A \\<subseteq> lists (listsN (n + 1) S) \\<Longrightarrow> map tl ` A \\<subseteq> lists (listsN n S)\"\nproof (intro image_subsetI)\n  fix xss assume \"A \\<subseteq> lists (listsN (n + 1) S)\" \"xss \\<in> A\"\n  hence \"set xss \\<subseteq> listsN (n + 1) S\" by auto\n  hence \"\\<forall>xs \\<in> set xss. tl xs \\<in> listsN n S\" using tl_listsN[of \"set xss\" S n] by auto\n  thus \"map tl xss \\<in> lists (listsN n S)\" by (induct xss) auto\nqed\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/MSO_Regex_Equivalence/Pi_Regular_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7645603681016735}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_HSortCount\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Heap = Node \"Heap\" \"Nat\" \"Heap\" | Nil\n\nfun toHeap :: \"Nat list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if le x2 x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else\n      Node (hmerge (Node z x2 x3) x6) x5 x4)\"\n| \"hmerge (Node z x2 x3) (Nil) = Node z x2 x3\"\n| \"hmerge (Nil) y = y\"\n\nfun hpairwise :: \"Heap list => Heap list\" where\n  \"hpairwise (nil2) = nil2\"\n| \"hpairwise (cons2 q (nil2)) = cons2 q (nil2)\"\n| \"hpairwise (cons2 q (cons2 r qs)) =\n     cons2 (hmerge q r) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 q (nil2)) = q\"\n| \"hmerging (cons2 q (cons2 z x2)) =\n     hmerging (hpairwise (cons2 q (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"Nat list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => Nat list\" where\n  \"toList (Node q y r) = cons2 y (toList (hmerge q r))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"Nat list => Nat list\" where\n  \"hsort x = toList (toHeap2 x)\"\n\nfun count :: \"'a => 'a list => Nat\" where\n  \"count x (nil2) = Z\"\n| \"count x (cons2 z ys) =\n     (if (x = z) then plus (S Z) (count x ys) else count x ys)\"\n\ntheorem property0 :\n  \"((count x (hsort xs)) = (count x xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_HSortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.7644108638391968}}
{"text": "theory BExp \nimports AExp \nbegin\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ntext_raw{*\\snip{BExpbvaldef}{1}{2}{% *}\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\ntext_raw{*}%endsnip*}\n\nvalue \"bval (Less (V ''x'') (Plus (N 3) (V ''y'')))\n            <''x'' := 3, ''y'' := 1>\"\n\n\nsubsection \"Constant Folding\"\n\ntext{* Optimizing constructors: *}\n\ntext_raw{*\\snip{BExplessdef}{0}{2}{% *}\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\" |\n\"less a\\<^sub>1 a\\<^sub>2 = Less a\\<^sub>1 a\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\n\n\ntext_raw{*\\snip{BExpanddef}{2}{2}{% *}\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply simp_all\ndone\n\ntext_raw{*\\snip{BExpnotdef}{2}{2}{% *}\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\ntext_raw{*}%endsnip*}\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction b rule: not.induct)\napply simp_all\ndone\n\ntext{* Now the overall optimizer: *}\n\ntext_raw{*\\snip{BExpbsimpdef}{0}{2}{% *}\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\nvalue \"bsimp (And (Less (N 0) (N 1)) b)\"\n\nvalue \"bsimp (And (Less (N 1) (N 0)) (Bc True))\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply simp_all\ndone\n\nend", "meta": {"author": "sseefried", "repo": "concrete-semantics-solutions", "sha": "ca562994bc36b2d9c9e6047bf481056e0be7bbcd", "save_path": "github-repos/isabelle/sseefried-concrete-semantics-solutions", "path": "github-repos/isabelle/sseefried-concrete-semantics-solutions/concrete-semantics-solutions-ca562994bc36b2d9c9e6047bf481056e0be7bbcd/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900950352329, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7643846802257811}}
{"text": "theory Utility_Functions\nimports\n  Complex_Main\n  \"~~/src/HOL/Probability/Probability\"\n  Missing_PMF\n  Preference_Profiles\nbegin\n\nsubsection \\<open>Definition of von Neumann--Morgenstern utility functions\\<close>\n\nlocale vnm_utility = finite_total_preorder_on +\n  fixes u :: \"'a \\<Rightarrow> real\"\n  assumes utility_le_iff: \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> u x \\<le> u y \\<longleftrightarrow> x \\<preceq>[le] y\"\nbegin\n\nlemma utility_le: \"x \\<preceq>[le] y \\<Longrightarrow> u x \\<le> u y\"\n  using not_outside[of x y] utility_le_iff by simp\n\nlemma utility_less_iff:\n  \"x \\<in> carrier \\<Longrightarrow> y \\<in> carrier \\<Longrightarrow> u x < u y \\<longleftrightarrow> x \\<prec>[le] y\"\n  using utility_le_iff[of x y] utility_le_iff[of y x] \n  by (auto simp: strongly_preferred_def)\n\nlemma utility_less: \"x \\<prec>[le] y \\<Longrightarrow> u x < u y\"\n  using not_outside[of x y] utility_less_iff by (simp add: strongly_preferred_def)\n\ntext \\<open>\n  The following lemma allows us to compute the expected utility by summing \n  over all indifference classes, using the fact that alternatives in the same\n  indifference class must have the same utility.\n\\<close>\nlemma expected_utility_weak_ranking:\n  assumes \"p \\<in> lotteries_on carrier\"\n  shows   \"measure_pmf.expectation p u =\n             (\\<Sum>A\\<leftarrow>weak_ranking le. u (SOME x. x \\<in> A) * measure_pmf.prob p A)\"\nproof -\n  from assms have \"measure_pmf.expectation p u = (\\<Sum>a\\<in>carrier. u a * pmf p a)\"\n    by (subst integral_measure_pmf[OF finite_carrier])\n       (auto simp: lotteries_on_def)\n  also have carrier: \"carrier = \\<Union>set (weak_ranking le)\" by (simp add: weak_ranking_Union)\n  also from this have finite: \"finite A\" if \"A \\<in> set (weak_ranking le)\" for A\n    using that by (blast intro!: finite_subset[OF _ finite_carrier, of A])\n  hence \"(\\<Sum>a\\<in>\\<Union>set (weak_ranking le). u a * pmf p a) = \n           (\\<Sum>A\\<leftarrow>weak_ranking le. \\<Sum>a\\<in>A. u a * pmf p a)\" (is \"_ = listsum ?xs\")\n    using weak_ranking_total_preorder\n    by (subst setsum.Union_disjoint)\n       (auto simp: is_weak_ranking_iff disjoint_def setsum.distinct_set_conv_list)\n  also have \"?xs  = map (\\<lambda>A. \\<Sum>a\\<in>A. u (SOME a. a\\<in>A) * pmf p a) (weak_ranking le)\"\n  proof (intro map_cong HOL.refl setsum.cong)\n    fix x A assume x: \"x \\<in> A\" and A: \"A \\<in> set (weak_ranking le)\"\n    have \"(SOME x. x \\<in> A) \\<in> A\" by (rule someI_ex) (insert x, blast)\n    from weak_ranking_eqclass1[OF A x this] weak_ranking_eqclass1[OF A this x] x this A\n      have \"u x = u (SOME x. x \\<in> A)\"\n      by (intro antisym; subst utility_le_iff) (auto simp: carrier)\n    thus \"u x * pmf p x = u (SOME x. x \\<in> A) * pmf p x\" by simp\n  qed\n  also have \"\\<dots> = map (\\<lambda>A. u (SOME a. a \\<in> A) * measure_pmf.prob p A) (weak_ranking le)\"\n    using finite by (intro map_cong HOL.refl)\n                    (auto simp: setsum_right_distrib measure_measure_pmf_finite)\n  finally show ?thesis .\nqed\n\nlemma scaled: \"c > 0 \\<Longrightarrow> vnm_utility carrier le (\\<lambda>x. c * u x)\"\n  by unfold_locales (insert utility_le_iff, auto)\n\nlemma add_right: \n  assumes \"\\<And>x y. le x y \\<Longrightarrow> f x \\<le> f y\"\n  shows   \"vnm_utility carrier le (\\<lambda>x. u x + f x)\"\nproof\n  fix x y assume xy: \"x \\<in> carrier\" \"y \\<in> carrier\"\n  from assms[of x y] utility_le_iff[OF xy] assms[of y x] utility_le_iff[OF xy(2,1)] \n    show \"(u x + f x \\<le> u y + f y) = le x y\" by auto\nqed\n\nlemma add_left: \n  \"(\\<And>x y. le x y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> vnm_utility carrier le (\\<lambda>x. f x + u x)\"\n  by (subst add.commute) (rule add_right)\n\ntext \\<open>\n  Given a consistent utility function, any function that assigns equal values to \n  equivalent alternatives can be added to it (scaled with a sufficiently small @{term \"\\<epsilon>\"}), \n  again yielding a consistent utility function.\n\\<close>\nlemma add_epsilon:\n  assumes A: \"\\<And>x y. le x y \\<Longrightarrow> le y x \\<Longrightarrow> f x = f y\"\n  shows \"\\<exists>\\<epsilon>>0. vnm_utility carrier le (\\<lambda>x. u x + \\<epsilon> * f x)\"\nproof -\n  let ?A = \"{(u y - u x) / (f x - f y) |x y. x \\<prec>[le] y \\<and> f x > f y}\"\n  have \"?A = (\\<lambda>(x,y). (u y - u x) / (f x - f y)) ` {(x,y) |x y. x \\<prec>[le] y \\<and> f x > f y}\" by auto\n  also have \"finite {(x,y) |x y. x \\<prec>[le] y \\<and> f x > f y}\"\n    by (rule finite_subset[of _ \"carrier \\<times> carrier\"]) \n       (insert not_outside, auto simp: strongly_preferred_def)\n  hence \"finite ((\\<lambda>(x,y). (u y - u x) / (f x - f y)) ` {(x,y) |x y. x \\<prec>[le] y \\<and> f x > f y})\"\n    by simp\n  finally have finite: \"finite ?A\" .\n\n  def \\<epsilon> \\<equiv> \"Min (insert 1 ?A) / 2\"\n  from finite have \"Min (insert 1 ?A) > 0\"\n    by (intro Min_grI) (auto intro!: divide_pos_pos simp: utility_less)\n  hence \\<epsilon>: \"\\<epsilon> > 0\" unfolding \\<epsilon>_def by simp\n\n  have mono: \"u x + \\<epsilon> * f x < u y + \\<epsilon> * f y\" if xy: \"x \\<prec>[le] y\" for x y\n  proof (cases \"f x > f y\")\n    assume less: \"f x > f y\"\n    from \\<epsilon> have \"\\<epsilon> < Min (insert 1 ?A)\" unfolding \\<epsilon>_def by linarith\n    also from less xy finite have \"Min (insert 1 ?A) \\<le> (u y - u x) / (f x - f y)\" unfolding \\<epsilon>_def\n      by (intro Min_le) auto\n    finally show ?thesis using less by (simp add: field_simps)\n  next\n    assume \"\\<not>f x > f y\"\n    with utility_less[OF xy] \\<epsilon> show ?thesis \n      by (simp add: algebra_simps not_less add_less_le_mono)\n  qed\n  have eq: \"u x + \\<epsilon> * f x = u y + \\<epsilon> * f y\" if xy: \"x \\<preceq>[le] y\" \"y \\<preceq>[le] x\" for x y\n    using xy[THEN utility_le] A[OF xy] by simp\n  have \"vnm_utility carrier le (\\<lambda>x. u x + \\<epsilon> * f x)\"\n  proof\n    fix x y assume xy: \"x \\<in> carrier\" \"y \\<in> carrier\"\n    show \"(u x + \\<epsilon> * f x \\<le> u y + \\<epsilon> * f y) \\<longleftrightarrow> le x y\"\n      using total[OF xy] mono[of x y] mono[of y x] eq[of x y]\n      by (cases \"le x y\"; cases \"le y x\") (auto simp: strongly_preferred_def)\n  qed\n  from \\<epsilon> this show ?thesis by blast\nqed\n\nlemma diff_epsilon:\n  assumes \"\\<And>x y. le x y \\<Longrightarrow> le y x \\<Longrightarrow> f x = f y\"\n  shows \"\\<exists>\\<epsilon>>0. vnm_utility carrier le (\\<lambda>x. u x - \\<epsilon> * f x)\"\nproof -\n  from assms have \"\\<exists>\\<epsilon>>0. vnm_utility carrier le (\\<lambda>x. u x + \\<epsilon> * -f x)\"\n    by (intro add_epsilon) (subst neg_equal_iff_equal)\n  thus ?thesis by simp\nqed\n\nend\n\nend", "meta": {"author": "pruvisto", "repo": "SDS", "sha": "e0b280bff615c917314285b374d77416c51ed39c", "save_path": "github-repos/isabelle/pruvisto-SDS", "path": "github-repos/isabelle/pruvisto-SDS/SDS-e0b280bff615c917314285b374d77416c51ed39c/thys/Randomised_Social_Choice/Utility_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730775, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7642272615201056}}
{"text": "(*  Title:      HOL/Algebra/Ideal_Product.thy\n    Author:     Paulo Emílio de Vilhena\n*)\n\ntheory Ideal_Product\n  imports Ideal\nbegin\n\nsection \\<open>Product of Ideals\\<close>\n\ntext \\<open>In this section, we study the structure of the set of ideals of a given ring.\\<close>\n\ninductive_set\n  ideal_prod :: \"[ ('a, 'b) ring_scheme, 'a set, 'a set ] \\<Rightarrow> 'a set\" (infixl \"\\<cdot>\\<index>\" 80)\n  for R and I and J (* both I and J are supposed ideals *) where\n    prod: \"\\<lbrakk> i \\<in> I; j \\<in> J \\<rbrakk> \\<Longrightarrow> i \\<otimes>\\<^bsub>R\\<^esub> j \\<in> ideal_prod R I J\"\n  |  sum: \"\\<lbrakk> s1 \\<in> ideal_prod R I J; s2 \\<in> ideal_prod R I J \\<rbrakk> \\<Longrightarrow> s1 \\<oplus>\\<^bsub>R\\<^esub> s2 \\<in> ideal_prod R I J\"\n\ndefinition ideals_set :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a set) ring\"\n  where \"ideals_set R = \\<lparr> carrier = { I. ideal I R },\n                             mult = ideal_prod R,\n                              one = carrier R,\n                             zero = { \\<zero>\\<^bsub>R\\<^esub> },\n                              add = set_add R \\<rparr>\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma (in ring) ideal_prod_in_carrier:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J \\<subseteq> carrier R\"\nproof\n  fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> carrier R\"\n    by (induct s rule: ideal_prod.induct) (auto, meson assms ideal.I_l_closed ideal.Icarr) \nqed\n\nlemma (in ring) ideal_prod_inter:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J \\<subseteq> I \\<inter> J\"\nproof\n  fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> I \\<inter> J\"\n    apply (induct s rule: ideal_prod.induct)\n    apply (auto, (meson assms ideal.I_r_closed ideal.I_l_closed ideal.Icarr)+)\n    apply (simp_all add: additive_subgroup.a_closed assms ideal.axioms(1))\n    done\nqed\n\nlemma (in ring) ideal_prod_is_ideal:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"ideal (I \\<cdot> J) R\"\nproof (rule idealI)\n  show \"ring R\" using ring_axioms .\nnext\n  show \"subgroup (I \\<cdot> J) (add_monoid R)\"\n    unfolding subgroup_def\n  proof (auto)\n    show \"\\<zero> \\<in> I \\<cdot> J\" using ideal_prod.prod[of \\<zero> I \\<zero> J R]\n      by (simp add: additive_subgroup.zero_closed assms ideal.axioms(1))\n  next\n    fix s1 s2 assume s1: \"s1 \\<in> I \\<cdot> J\" and s2: \"s2 \\<in> I \\<cdot> J\"\n    have IJcarr: \"\\<And>a. a \\<in> I \\<cdot> J \\<Longrightarrow> a \\<in> carrier R\"\n      by (meson assms subsetD ideal_prod_in_carrier)\n    show \"s1 \\<in> carrier R\" using ideal_prod_in_carrier[OF assms] s1 by blast\n    show \"s1 \\<oplus> s2 \\<in> I \\<cdot> J\" by (simp add: ideal_prod.sum[OF s1 s2])\n    show \"inv\\<^bsub>add_monoid R\\<^esub> s1 \\<in> I \\<cdot> J\" using s1\n    proof (induct s1 rule: ideal_prod.induct)\n      case (prod i j)\n      hence \"inv\\<^bsub>add_monoid R\\<^esub> (i \\<otimes> j) = (inv\\<^bsub>add_monoid R\\<^esub> i) \\<otimes> j\"\n        by (metis a_inv_def assms(1) assms(2) ideal.Icarr l_minus)\n      thus ?case using ideal_prod.prod[of \"inv\\<^bsub>add_monoid R\\<^esub> i\" I j J R] assms\n        by (simp add: additive_subgroup.a_subgroup ideal.axioms(1) prod.hyps subgroup.m_inv_closed)\n    next\n      case (sum s1 s2) thus ?case\n        by (metis (no_types) IJcarr a_inv_def add.inv_mult_group ideal_prod.sum sum.hyps)\n    qed\n  qed\nnext\n  fix s x assume s: \"s \\<in> I \\<cdot> J\" and x: \"x \\<in> carrier R\"\n  show \"x \\<otimes> s \\<in> I \\<cdot> J\" using s\n  proof (induct s rule: ideal_prod.induct)\n    case (prod i j) thus ?case using ideal_prod.prod[of \"x \\<otimes> i\" I j J R] assms\n      by (simp add: x ideal.I_l_closed ideal.Icarr m_assoc)\n  next\n    case (sum s1 s2) thus ?case\n    proof -\n      have IJ: \"I \\<cdot> J \\<subseteq> carrier R\"\n        by (metis (no_types) assms(1) assms(2) ideal.axioms(2) ring.ideal_prod_in_carrier)\n      then have \"s2 \\<in> carrier R\"\n        using sum.hyps(3) by blast\n      moreover have \"s1 \\<in> carrier R\"\n        using IJ sum.hyps(1) by blast\n      ultimately show ?thesis\n        by (simp add: ideal_prod.sum r_distr sum.hyps x)\n    qed\n  qed\n  show \"s \\<otimes> x \\<in> I \\<cdot> J\" using s\n  proof (induct s rule: ideal_prod.induct)\n    case (prod i j) thus ?case using ideal_prod.prod[of i I \"j \\<otimes> x\" J R] assms x\n      by (simp add: x ideal.I_r_closed ideal.Icarr m_assoc)\n  next\n    case (sum s1 s2) thus ?case \n    proof -\n      have \"s1 \\<in> carrier R\" \"s2 \\<in> carrier R\"\n        by (meson assms subsetD ideal_prod_in_carrier sum.hyps)+\n      then show ?thesis\n        by (metis ideal_prod.sum l_distr sum.hyps(2) sum.hyps(4) x)\n    qed\n  qed\nqed\n\nlemma (in ring) ideal_prod_eq_genideal:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J = Idl (I <#> J)\"\nproof\n  have \"I <#> J \\<subseteq> I \\<cdot> J\"\n  proof\n    fix s assume \"s \\<in> I <#> J\"\n    then obtain i j where \"i \\<in> I\" \"j \\<in> J\" \"s = i \\<otimes> j\"\n      unfolding set_mult_def by blast\n    thus \"s \\<in> I \\<cdot> J\" using ideal_prod.prod by simp\n  qed\n  thus \"Idl (I <#> J) \\<subseteq> I \\<cdot> J\"\n    unfolding genideal_def using ideal_prod_is_ideal[OF assms] by blast\nnext\n  show \"I \\<cdot> J \\<subseteq> Idl (I <#> J)\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> Idl (I <#> J)\"\n    proof (induct s rule: ideal_prod.induct)\n      case (prod i j) hence \"i \\<otimes> j \\<in> I <#> J\" unfolding set_mult_def by blast\n      thus ?case unfolding genideal_def by blast \n    next\n      case (sum s1 s2) thus ?case\n        by (simp add: additive_subgroup.a_closed additive_subgroup.a_subset\n            assms genideal_ideal ideal.axioms(1) set_mult_closed)\n    qed\n  qed\nqed\n\n\nlemma (in ring) ideal_prod_simp:\n  assumes \"ideal I R\" \"ideal J R\" (* the second assumption could be suppressed *)\n  shows \"I = I <+> (I \\<cdot> J)\"\nproof\n  show \"I \\<subseteq> I <+> I \\<cdot> J\"\n  proof\n    fix i assume \"i \\<in> I\" hence \"i \\<oplus> \\<zero> \\<in> I <+> I \\<cdot> J\"\n      using set_add_def'[of R I \"I \\<cdot> J\"] ideal_prod_is_ideal[OF assms]\n            additive_subgroup.zero_closed[OF ideal.axioms(1), of \"I \\<cdot> J\" R] by auto\n    thus \"i \\<in> I <+> I \\<cdot> J\"\n      using \\<open>i \\<in> I\\<close> assms(1) ideal.Icarr by fastforce \n  qed\nnext\n  show \"I <+> I \\<cdot> J \\<subseteq> I\"\n  proof\n    fix s assume \"s \\<in> I <+> I \\<cdot> J\"\n    then obtain i ij where \"i \\<in> I\" \"ij \\<in> I \\<cdot> J\" \"s = i \\<oplus> ij\"\n      using set_add_def'[of R I \"I \\<cdot> J\"] by auto\n    thus \"s \\<in> I\"\n      using ideal_prod_inter[OF assms]\n      by (meson additive_subgroup.a_closed assms(1) ideal.axioms(1) inf_sup_ord(1) subsetCE) \n  qed\nqed\n\nlemma (in ring) ideal_prod_one:\n  assumes \"ideal I R\"\n  shows \"I \\<cdot> (carrier R) = I\"\nproof\n  show \"I \\<cdot> (carrier R) \\<subseteq> I\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> (carrier R)\" thus \"s \\<in> I\"\n      by (induct s rule: ideal_prod.induct)\n         (simp_all add: assms ideal.I_r_closed additive_subgroup.a_closed ideal.axioms(1))\n  qed\nnext\n  show \"I \\<subseteq> I \\<cdot> (carrier R)\"\n  proof\n    fix i assume \"i \\<in> I\" thus \"i \\<in>  I \\<cdot> (carrier R)\"\n      by (metis assms ideal.Icarr ideal_prod.simps one_closed r_one)\n  qed\nqed\n\nlemma (in ring) ideal_prod_zero:\n  assumes \"ideal I R\"\n  shows \"I \\<cdot> { \\<zero> } = { \\<zero> }\"\nproof\n  show \"I \\<cdot> { \\<zero> } \\<subseteq> { \\<zero> }\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> {\\<zero>}\" thus \"s \\<in> { \\<zero> }\"\n      using assms ideal.Icarr by (induct s rule: ideal_prod.induct) (fastforce, simp)\n  qed\nnext\n  show \"{ \\<zero> } \\<subseteq> I \\<cdot> { \\<zero> }\"\n    by (simp add: additive_subgroup.zero_closed assms\n                  ideal.axioms(1) ideal_prod_is_ideal zeroideal)\nqed\n\nlemma (in ring) ideal_prod_assoc:\n  assumes \"ideal I R\" \"ideal J R\" \"ideal K R\"\n  shows \"(I \\<cdot> J) \\<cdot> K = I \\<cdot> (J \\<cdot> K)\"\nproof\n  show \"(I \\<cdot> J) \\<cdot> K \\<subseteq> I \\<cdot> (J \\<cdot> K)\"\n  proof\n    fix s assume \"s \\<in> (I \\<cdot> J) \\<cdot> K\" thus \"s \\<in> I \\<cdot> (J \\<cdot> K)\"\n    proof (induct s rule: ideal_prod.induct)\n      case (sum s1 s2) thus ?case\n        by (simp add: ideal_prod.sum)\n    next\n      case (prod i k) thus ?case\n      proof (induct i rule: ideal_prod.induct)\n        case (prod i j) thus ?case\n          using ideal_prod.prod[OF prod(1) ideal_prod.prod[OF prod(2-3),of R], of R]\n          by (metis assms ideal.Icarr m_assoc) \n      next\n        case (sum s1 s2) thus ?case\n        proof -\n          have \"s1 \\<in> carrier R\" \"s2 \\<in> carrier R\"\n            by (meson assms subsetD ideal.axioms(2) ring.ideal_prod_in_carrier sum.hyps)+\n          moreover have \"k \\<in> carrier R\"\n            by (meson additive_subgroup.a_Hcarr assms(3) ideal.axioms(1) sum.prems)\n          ultimately show ?thesis\n            by (metis ideal_prod.sum l_distr sum.hyps(2) sum.hyps(4) sum.prems)\n        qed\n      qed\n    qed\n  qed\nnext\n  show \"I \\<cdot> (J \\<cdot> K) \\<subseteq> (I \\<cdot> J) \\<cdot> K\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> (J \\<cdot> K)\" thus \"s \\<in> (I \\<cdot> J) \\<cdot> K\"\n    proof (induct s rule: ideal_prod.induct)\n      case (sum s1 s2) thus ?case by (simp add: ideal_prod.sum)\n    next\n      case (prod i j) show ?case using prod(2) prod(1)\n      proof (induct j rule: ideal_prod.induct)\n        case (prod j k) thus ?case\n          using ideal_prod.prod[OF ideal_prod.prod[OF prod(3) prod(1), of R] prod (2), of R]\n          by (metis assms ideal.Icarr m_assoc)\n      next\n        case (sum s1 s2) thus ?case\n        proof -\n          have \"\\<And>a A B. \\<lbrakk>a \\<in> B \\<cdot> A; ideal A R; ideal B R\\<rbrakk> \\<Longrightarrow> a \\<in> carrier R\"\n            by (meson subsetD ideal_prod_in_carrier)\n          moreover have \"i \\<in> carrier R\"\n            by (meson additive_subgroup.a_Hcarr assms(1) ideal.axioms(1) sum.prems)\n          ultimately show ?thesis\n            by (metis (no_types) assms(2) assms(3) ideal_prod.sum r_distr sum)\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma (in ring) ideal_prod_r_distr:\n  assumes \"ideal I R\" \"ideal J R\" \"ideal K R\"\n  shows \"I \\<cdot> (J <+> K) = (I \\<cdot> J) <+>  (I \\<cdot> K)\"\nproof\n  show \"I \\<cdot> (J <+> K) \\<subseteq> I \\<cdot> J <+> I \\<cdot> K\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> (J <+> K)\" thus \"s \\<in> I \\<cdot> J <+> I \\<cdot> K\"\n    proof(induct s rule: ideal_prod.induct)\n      case (prod i jk)\n      then obtain j k where j: \"j \\<in> J\" and k: \"k \\<in> K\" and jk: \"jk = j \\<oplus> k\"\n        using set_add_def'[of R J K] by auto\n      hence \"i \\<otimes> j \\<oplus> i \\<otimes> k \\<in> I \\<cdot> J <+> I \\<cdot> K\"\n        using ideal_prod.prod[OF prod(1) j,of R]\n              ideal_prod.prod[OF prod(1) k,of R]\n              set_add_def'[of R \"I \\<cdot> J\" \"I \\<cdot> K\"] by auto\n      thus ?case\n        using assms ideal.Icarr r_distr jk j k prod(1) by metis \n    next\n      case (sum s1 s2) thus ?case\n        by (simp add: add_ideals additive_subgroup.a_closed assms ideal.axioms(1)\n                      local.ring_axioms ring.ideal_prod_is_ideal) \n    qed\n  qed\nnext\n  { fix s J K assume A: \"ideal J R\" \"ideal K R\" \"s \\<in> I \\<cdot> J\"\n    have \"s \\<in> I \\<cdot> (J <+> K) \\<and> s \\<in> I \\<cdot> (K <+> J)\"\n    proof -\n      from \\<open>s \\<in> I \\<cdot> J\\<close> have \"s \\<in> I \\<cdot> (J <+> K)\"\n      proof (induct s rule: ideal_prod.induct)\n        case (prod i j)\n        hence \"(j \\<oplus> \\<zero>) \\<in> J <+> K\"\n          using set_add_def'[of R J K]\n                additive_subgroup.zero_closed[OF ideal.axioms(1), of K R] A(2) by auto\n        thus ?case\n          by (metis A(1) additive_subgroup.a_Hcarr ideal.axioms(1) ideal_prod.prod prod r_zero)  \n      next\n        case (sum s1 s2) thus ?case\n          by (simp add: ideal_prod.sum) \n      qed\n      thus ?thesis\n        by (metis A(1) A(2) ideal_def ring.union_genideal sup_commute) \n    qed } note aux_lemma = this\n\n  show \"I \\<cdot> J <+> I \\<cdot> K \\<subseteq> I \\<cdot> (J <+> K)\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> J <+> I \\<cdot> K\"\n    then obtain s1 s2 where s1: \"s1 \\<in> I \\<cdot> J\" and s2: \"s2 \\<in> I \\<cdot> K\" and  s: \"s = s1 \\<oplus> s2\"\n      using set_add_def'[of R \"I \\<cdot> J\" \"I \\<cdot> K\"] by auto\n    thus \"s \\<in> I \\<cdot> (J <+> K)\"\n      using aux_lemma[OF assms(2) assms(3) s1]\n            aux_lemma[OF assms(3) assms(2) s2] by (simp add: ideal_prod.sum)\n  qed\nqed\n\nlemma (in cring) ideal_prod_commute:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J = J \\<cdot> I\"\nproof -\n  { fix I J assume A: \"ideal I R\" \"ideal J R\"\n    have \"I \\<cdot> J \\<subseteq> J \\<cdot> I\"\n    proof\n      fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> J \\<cdot> I\"\n      proof (induct s rule: ideal_prod.induct)\n        case (prod i j) thus ?case\n          using m_comm[OF ideal.Icarr[OF A(1) prod(1)] ideal.Icarr[OF A(2) prod(2)]]\n          by (simp add: ideal_prod.prod)\n      next\n        case (sum s1 s2) thus ?case by (simp add: ideal_prod.sum) \n      qed\n    qed }\n  thus ?thesis using assms by blast \nqed\n\ntext \\<open>The following result would also be true for locale ring\\<close>\nlemma (in cring) ideal_prod_distr:\n  assumes \"ideal I R\" \"ideal J R\" \"ideal K R\"\n  shows \"I \\<cdot> (J <+> K) = (I \\<cdot> J) <+>  (I \\<cdot> K)\"\n    and \"(J <+> K) \\<cdot> I = (J \\<cdot> I) <+>  (K \\<cdot> I)\"\n  by (simp_all add: assms ideal_prod_commute local.ring_axioms\n                    ring.add_ideals ring.ideal_prod_r_distr)\n\nlemma (in cring) ideal_prod_eq_inter:\n  assumes \"ideal I R\" \"ideal J R\"\n    and \"I <+> J = carrier R\"\n  shows \"I \\<cdot> J = I \\<inter> J\"\nproof\n  show \"I \\<cdot> J \\<subseteq> I \\<inter> J\"\n    using assms ideal_prod_inter by auto\nnext\n  show \"I \\<inter> J \\<subseteq> I \\<cdot> J\"\n  proof\n    have \"\\<one> \\<in> I <+> J\" using assms(3) one_closed by simp \n    then obtain i j where ij: \"i \\<in> I\" \"j \\<in> J\" \"\\<one> = i \\<oplus> j\"\n      using set_add_def'[of R I J] by auto\n\n    fix s assume s: \"s \\<in> I \\<inter> J\"\n    hence \"(i \\<otimes> s \\<in> I \\<cdot> J) \\<and> (s \\<otimes> j \\<in> I \\<cdot> J)\"\n      using ij(1-2) by (simp add: ideal_prod.prod)\n    moreover have \"s = (i \\<otimes> s) \\<oplus> (s \\<otimes> j)\"\n      using ideal.Icarr[OF assms(1) ij(1)]\n            ideal.Icarr[OF assms(2) ij(2)]\n            ideal.Icarr[OF assms(1), of s]\n      by (metis ij(3) s m_comm[of s i] Int_iff r_distr r_one)\n    ultimately show \"s \\<in>  I \\<cdot> J\"\n      using ideal_prod.sum by fastforce\n  qed\nqed\n\n\nsubsection \\<open>Structure of the Set of Ideals\\<close>\n\ntext \\<open>We focus on commutative rings for convenience.\\<close>\n\nlemma (in cring) ideals_set_is_semiring: \"semiring (ideals_set R)\"\nproof -\n  have \"abelian_monoid (ideals_set R)\"\n    apply (rule abelian_monoidI) unfolding ideals_set_def\n    apply (simp_all add: add_ideals zeroideal)\n    apply (simp add: add.set_mult_assoc additive_subgroup.a_subset ideal.axioms(1) set_add_defs(1))\n    apply (metis Un_absorb1 additive_subgroup.a_subset additive_subgroup.zero_closed\n        cgenideal_minimal cgenideal_self empty_iff genideal_minimal ideal.axioms(1)\n        local.ring_axioms order_refl ring.genideal_self subset_antisym subset_singletonD\n        union_genideal zero_closed zeroideal)\n    by (metis sup_commute union_genideal)\n\n  moreover have \"monoid (ideals_set R)\"\n    apply (rule monoidI) unfolding ideals_set_def\n    apply (simp_all add: ideal_prod_is_ideal oneideal\n                         ideal_prod_commute ideal_prod_one)\n    by (metis ideal_prod_assoc ideal_prod_commute)\n\n  ultimately show ?thesis\n    unfolding semiring_def semiring_axioms_def ideals_set_def\n    by (simp_all add: ideal_prod_distr ideal_prod_commute ideal_prod_zero zeroideal) \nqed\n\nlemma (in cring) ideals_set_is_comm_monoid: \"comm_monoid (ideals_set R)\"\nproof -\n  have \"monoid (ideals_set R)\"\n    apply (rule monoidI) unfolding ideals_set_def\n    apply (simp_all add: ideal_prod_is_ideal oneideal\n                         ideal_prod_commute ideal_prod_one)\n    by (metis ideal_prod_assoc ideal_prod_commute)\n  thus ?thesis\n    unfolding comm_monoid_def comm_monoid_axioms_def\n    by (simp add: ideal_prod_commute ideals_set_def)\nqed\n\nlemma (in cring) ideal_prod_eq_Inter_aux:\n  assumes \"I: {..(Suc n)} \\<rightarrow> { J. ideal J R }\" \n    and \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n \\<rbrakk> \\<Longrightarrow>\n                 i \\<noteq> j \\<Longrightarrow> (I i) <+> (I j) = carrier R\"\n  shows \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. I k) <+> (I (Suc n)) = carrier R\" using assms\nproof (induct n arbitrary: I)\n  case 0\n  hence \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..0}. I k) <+> I (Suc 0) = (I 0) <+> (I (Suc 0))\"\n    using comm_monoid.finprod_0[OF ideals_set_is_comm_monoid, of I]\n    by (simp add: atMost_Suc ideals_set_def)\n  also have \" ... = carrier R\"\n    using 0(2)[of 0 \"Suc 0\"] by simp\n  finally show ?case .\nnext\n  interpret ISet: comm_monoid \"ideals_set R\"\n    by (simp add: ideals_set_is_comm_monoid)\n\n  case (Suc n)\n  let ?I' = \"\\<lambda>i. I (Suc i)\"\n  have \"?I': {..(Suc n)} \\<rightarrow> { J. ideal J R }\"\n    using Suc.prems(1) by auto\n  moreover have \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n \\<rbrakk> \\<Longrightarrow>\n                         i \\<noteq> j \\<Longrightarrow> (?I' i) <+> (?I' j) = carrier R\"\n    by (simp add: Suc.prems(2))\n  ultimately have \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. ?I' k) <+> (?I' (Suc n)) = carrier R\"\n    using Suc.hyps by metis\n\n  moreover have I_carr: \"I: {..Suc (Suc n)} \\<rightarrow> carrier (ideals_set R)\"\n    unfolding ideals_set_def using Suc by simp\n  hence I'_carr: \"I \\<in> Suc ` {..n} \\<rightarrow> carrier (ideals_set R)\" by auto\n  ultimately have \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {(Suc 0)..Suc n}. I k) <+> (I (Suc (Suc n))) = carrier R\"\n    using ISet.finprod_reindex[of I \"\\<lambda>i. Suc i\" \"{..n}\"] by (simp add: atMost_atLeast0) \n\n  hence \"(carrier R) \\<cdot> (I 0) = ((\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) <+> I (Suc (Suc n))) \\<cdot> (I 0)\"\n    by auto\n  moreover have fprod_cl1: \"ideal (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) R\"\n    by (metis I'_carr ISet.finprod_closed One_nat_def ideals_set_def image_Suc_atMost\n        mem_Collect_eq partial_object.select_convs(1))\n  ultimately\n  have \"I 0 = (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) \\<cdot> (I 0) <+> I (Suc (Suc n)) \\<cdot> (I 0)\"\n    by (metis PiE Suc.prems(1) atLeast0_atMost_Suc atLeast0_atMost_Suc_eq_insert_0\n        atMost_atLeast0 ideal_prod_commute ideal_prod_distr(2) ideal_prod_one insertI1\n        mem_Collect_eq oneideal)\n  also have \" ... = (I 0) \\<cdot> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) <+> I (Suc (Suc n)) \\<cdot> (I 0)\"\n    using fprod_cl1 ideal_prod_commute Suc.prems(1)\n    by (simp add: atLeast0_atMost_Suc_eq_insert_0 atMost_atLeast0) \n  also have \" ... = (I 0) \\<otimes>\\<^bsub>(ideals_set R)\\<^esub> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) <+>\n                     I (Suc (Suc n)) \\<cdot> (I 0)\"\n    by (simp add: ideals_set_def)\n  finally have I0: \"I 0 = (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) <+> I (Suc (Suc n)) \\<cdot> (I 0)\"\n    using ISet.finprod_insert[of \"{Suc 0..Suc n}\" 0 I]\n          I_carr I'_carr atMost_atLeast0 ISet.finprod_0' atMost_Suc by auto\n\n  have I_SucSuc_I0: \"ideal (I (Suc (Suc n))) R \\<and> ideal (I 0) R\"\n    using Suc.prems(1) by auto\n  have fprod_cl2: \"ideal (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) R\"\n    by (metis (no_types) ISet.finprod_closed I_carr Pi_split_insert_domain atMost_Suc ideals_set_def mem_Collect_eq partial_object.select_convs(1))\n  have \"carrier R = I (Suc (Suc n)) <+> I 0\"\n    by (simp add: Suc.prems(2))\n  also have \" ... = I (Suc (Suc n)) <+>\n                    ((\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) <+> I (Suc (Suc n)) \\<cdot> (I 0))\"\n    using I0 by auto\n  also have \" ... = I (Suc (Suc n)) <+>\n                    (I (Suc (Suc n)) \\<cdot> (I 0) <+> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k))\"\n    using fprod_cl2 I_SucSuc_I0 by (metis Un_commute ideal_prod_is_ideal union_genideal)\n  also have \" ... = (I (Suc (Suc n)) <+> I (Suc (Suc n)) \\<cdot> (I 0)) <+>\n                    (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k)\"\n    using fprod_cl2 I_SucSuc_I0 by (metis add.set_mult_assoc ideal_def ideal_prod_in_carrier\n                                          oneideal ring.ideal_prod_one set_add_defs(1)) \n  also have \" ... = I (Suc (Suc n)) <+> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k)\"\n    using ideal_prod_simp[of \"I (Suc (Suc n))\" \"I 0\"] I_SucSuc_I0 by simp \n  also have \" ... = (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) <+> I (Suc (Suc n))\"\n    using fprod_cl2 I_SucSuc_I0 by (metis Un_commute union_genideal)\n  finally show ?case by simp\nqed\n\ntheorem (in cring) ideal_prod_eq_Inter:\n  assumes \"I: {..n :: nat} \\<rightarrow> { J. ideal J R }\" \n    and \"\\<And>i j. \\<lbrakk> i \\<in> {..n}; j \\<in> {..n} \\<rbrakk> \\<Longrightarrow> i \\<noteq> j \\<Longrightarrow> (I i) <+> (I j) = carrier R\"\n  shows \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. I k) = (\\<Inter> k \\<in> {..n}. I k)\" using assms\nproof (induct n)\n  case 0 thus ?case\n    using comm_monoid.finprod_0[OF ideals_set_is_comm_monoid] by (simp add: ideals_set_def) \nnext\n  interpret ISet: comm_monoid \"ideals_set R\"\n    by (simp add: ideals_set_is_comm_monoid)\n\n  case (Suc n)\n  hence IH: \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. I k) = (\\<Inter> k \\<in> {..n}. I k)\"\n    by (simp add: atMost_Suc)\n  hence \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) = I (Suc n) \\<otimes>\\<^bsub>(ideals_set R)\\<^esub> (\\<Inter> k \\<in> {..n}. I k)\"\n    using ISet.finprod_insert[of \"{Suc 0..Suc n}\" 0 I] atMost_Suc_eq_insert_0[of n]\n    by (metis ISet.finprod_Suc Suc.prems(1) ideals_set_def partial_object.select_convs(1))\n  hence \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) = I (Suc n) \\<cdot> (\\<Inter> k \\<in> {..n}. I k)\"\n    by (simp add: ideals_set_def)\n  moreover have \"(\\<Inter> k \\<in> {..n}. I k) <+> I (Suc n) = carrier R\"\n    using ideal_prod_eq_Inter_aux[of I n] by (simp add: Suc.prems IH)\n  moreover have \"ideal (\\<Inter> k \\<in> {..n}. I k) R\"\n    using ring.i_Intersect[of R \"I ` {..n}\"]\n    by (metis IH ISet.finprod_closed Pi_split_insert_domain Suc.prems(1) atMost_Suc\n              ideals_set_def mem_Collect_eq partial_object.select_convs(1))\n  ultimately\n  have \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) = (\\<Inter> k \\<in> {..n}. I k) \\<inter> I (Suc n)\"\n    using ideal_prod_eq_inter[of \"\\<Inter> k \\<in> {..n}. I k\" \"I (Suc n)\"]\n          ideal_prod_commute[of \"\\<Inter> k \\<in> {..n}. I k\" \"I (Suc n)\"]\n    by (metis PiE Suc.prems(1) atMost_iff mem_Collect_eq order_refl)\n  thus ?case by (simp add: Int_commute atMost_Suc) \nqed\n\ncorollary (in cring) inter_plus_ideal_eq_carrier:\n  assumes \"\\<And>i. i \\<le> Suc n \\<Longrightarrow> ideal (I i) R\" \n      and \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n; i \\<noteq> j \\<rbrakk> \\<Longrightarrow> I i <+> I j = carrier R\"\n  shows \"(\\<Inter> i \\<le> n. I i) <+> (I (Suc n)) = carrier R\"\n  using ideal_prod_eq_Inter[of I n] ideal_prod_eq_Inter_aux[of I n] by (auto simp add: assms)\n\ncorollary (in cring) inter_plus_ideal_eq_carrier_arbitrary:\n  assumes \"\\<And>i. i \\<le> Suc n \\<Longrightarrow> ideal (I i) R\" \n      and \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n; i \\<noteq> j \\<rbrakk> \\<Longrightarrow> I i <+> I j = carrier R\"\n      and \"j \\<le> Suc n\"\n  shows \"(\\<Inter> i \\<in> ({..(Suc n)} - { j }). I i) <+> (I j) = carrier R\"\nproof -\n  define I' where \"I' = (\\<lambda>i. if i = Suc n then (I j) else\n                             if i = j     then (I (Suc n))\n                                          else (I i))\"\n  have \"\\<And>i. i \\<le> Suc n \\<Longrightarrow> ideal (I' i) R\"\n    using I'_def assms(1) assms(3) by auto\n  moreover have \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n; i \\<noteq> j \\<rbrakk> \\<Longrightarrow> I' i <+> I' j = carrier R\"\n    using I'_def assms(2-3) by force\n  ultimately have \"(\\<Inter> i \\<le> n. I' i) <+> (I' (Suc n)) = carrier R\"\n    using inter_plus_ideal_eq_carrier by simp\n\n  moreover have \"I' ` {..n} = I ` ({..(Suc n)} - { j })\"\n  proof\n    show \"I' ` {..n} \\<subseteq> I ` ({..Suc n} - {j})\"\n    proof\n      fix x assume \"x \\<in> I' ` {..n}\"\n      then obtain i where i: \"i \\<in> {..n}\" \"I' i = x\" by blast\n      thus \"x \\<in> I ` ({..Suc n} - {j})\"\n      proof (cases)\n        assume \"i = j\" thus ?thesis using i I'_def by auto\n      next\n        assume \"i \\<noteq> j\" thus ?thesis using I'_def i insert_iff by auto\n      qed\n    qed\n  next\n    show \"I ` ({..Suc n} - {j}) \\<subseteq> I' ` {..n}\"\n    proof\n      fix x assume \"x \\<in> I ` ({..Suc n} - {j})\"\n      then obtain i where i: \"i \\<in> {..Suc n}\" \"i \\<noteq> j\" \"I i = x\" by blast\n      thus \"x \\<in> I' ` {..n}\"\n      proof (cases)\n        assume \"i = Suc n\" thus ?thesis using I'_def assms(3) i(2-3) by auto\n      next\n        assume \"i \\<noteq> Suc n\" thus ?thesis using I'_def i by auto\n      qed\n    qed\n  qed\n  ultimately show ?thesis using I'_def by metis \nqed\n\n\nsubsection \\<open>Another Characterization of Prime Ideals\\<close>\n\ntext \\<open>With product of ideals being defined, we can give another definition of a prime ideal\\<close>\n\nlemma (in ring) primeideal_divides_ideal_prod:\n  assumes \"primeideal P R\" \"ideal I R\" \"ideal J R\"\n      and \"I \\<cdot> J \\<subseteq> P\"\n    shows \"I \\<subseteq> P \\<or> J \\<subseteq> P\"\nproof (cases)\n  assume \"\\<exists> i \\<in> I. i \\<notin> P\"\n  then obtain i where i: \"i \\<in> I\" \"i \\<notin> P\" by blast\n  have \"J \\<subseteq> P\"\n  proof\n    fix j assume j: \"j \\<in> J\"\n    hence \"i \\<otimes> j \\<in> P\"\n      using ideal_prod.prod[OF i(1) j, of R] assms(4) by auto\n    thus \"j \\<in> P\"\n      using primeideal.I_prime[OF assms(1), of i j] i j\n      by (meson assms(2-3) ideal.Icarr) \n  qed\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (\\<exists> i \\<in> I. i \\<notin> P)\" thus ?thesis by blast\nqed\n\nlemma (in cring) divides_ideal_prod_imp_primeideal:\n  assumes \"ideal P R\"\n    and \"P \\<noteq> carrier R\"\n    and \"\\<And>I J. \\<lbrakk> ideal I R; ideal J R; I \\<cdot> J \\<subseteq> P \\<rbrakk> \\<Longrightarrow> I \\<subseteq> P \\<or> J \\<subseteq> P\"\n  shows \"primeideal P R\"\nproof -\n  have \"\\<And>a b. \\<lbrakk> a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> P \\<rbrakk> \\<Longrightarrow> a \\<in> P \\<or> b \\<in> P\"\n  proof -\n    fix a b assume A: \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"a \\<otimes> b \\<in> P\"\n    have \"(PIdl a) \\<cdot> (PIdl b) = Idl (PIdl (a \\<otimes> b))\"\n      using ideal_prod_eq_genideal[of \"Idl { a }\" \"Idl { b }\"]\n            A(1-2) cgenideal_eq_genideal cgenideal_ideal cgenideal_prod by auto\n    hence \"(PIdl a) \\<cdot> (PIdl b) = PIdl (a \\<otimes> b)\"\n      by (simp add: A Idl_subset_ideal cgenideal_ideal cgenideal_minimal\n                    genideal_self oneideal subset_antisym)\n    hence \"(PIdl a) \\<cdot> (PIdl b) \\<subseteq> P\"\n      by (simp add: A(3) assms(1) cgenideal_minimal)\n    hence \"(PIdl a) \\<subseteq> P \\<or> (PIdl b) \\<subseteq> P\"\n      by (simp add: A assms(3) cgenideal_ideal)\n    thus \"a \\<in> P \\<or> b \\<in> P\"\n      using A cgenideal_self by blast\n  qed\n  thus ?thesis\n    using assms is_cring by (simp add: primeidealI)\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Algebra/Ideal_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7642272529775592}}
{"text": "(*  Title:      HOL/Computational_Algebra/Euclidean_Algorithm.thy\n    Author:     Manuel Eberl, TU Muenchen\n*)\n\nsection \\<open>Abstract euclidean algorithm in euclidean (semi)rings\\<close>\n\ntheory Euclidean_Algorithm\n  imports Factorial_Ring\nbegin\n\nsubsection \\<open>Generic construction of the (simple) euclidean algorithm\\<close>\n\nclass normalization_euclidean_semiring = euclidean_semiring + normalization_semidom\nbegin\n\nlemma euclidean_size_normalize [simp]:\n  \"euclidean_size (normalize a) = euclidean_size a\"\nproof (cases \"a = 0\")\n  case True\n  then show ?thesis\n    by simp\nnext\n  case [simp]: False\n  have \"euclidean_size (normalize a) \\<le> euclidean_size (normalize a * unit_factor a)\"\n    by (rule size_mult_mono) simp\n  moreover have \"euclidean_size a \\<le> euclidean_size (a * (1 div unit_factor a))\"\n    by (rule size_mult_mono) simp\n  ultimately show ?thesis\n    by simp\nqed\n\ncontext\nbegin\n\nqualified function gcd :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"gcd a b = (if b = 0 then normalize a else gcd b (a mod b))\"\n  by pat_completeness simp\ntermination\n  by (relation \"measure (euclidean_size \\<circ> snd)\") (simp_all add: mod_size_less)\n\ndeclare gcd.simps [simp del]\n\nlemma eucl_induct [case_names zero mod]:\n  assumes H1: \"\\<And>b. P b 0\"\n  and H2: \"\\<And>a b. b \\<noteq> 0 \\<Longrightarrow> P b (a mod b) \\<Longrightarrow> P a b\"\n  shows \"P a b\"\nproof (induct a b rule: gcd.induct)\n  case (1 a b)\n  show ?case\n  proof (cases \"b = 0\")\n    case True then show \"P a b\" by simp (rule H1)\n  next\n    case False\n    then have \"P b (a mod b)\"\n      by (rule \"1.hyps\")\n    with \\<open>b \\<noteq> 0\\<close> show \"P a b\"\n      by (blast intro: H2)\n  qed\nqed\n  \nqualified lemma gcd_0:\n  \"gcd a 0 = normalize a\"\n  by (simp add: gcd.simps [of a 0])\n  \nqualified lemma gcd_mod:\n  \"a \\<noteq> 0 \\<Longrightarrow> gcd a (b mod a) = gcd b a\"\n  by (simp add: gcd.simps [of b 0] gcd.simps [of b a])\n\nqualified definition lcm :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"lcm a b = normalize (a * b div gcd a b)\"\n\nqualified definition Lcm :: \"'a set \\<Rightarrow> 'a\" \\<comment> \\<open>Somewhat complicated definition of Lcm that has the advantage of working\n    for infinite sets as well\\<close>\n  where\n  [code del]: \"Lcm A = (if \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd l) then\n     let l = SOME l. l \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd l) \\<and> euclidean_size l =\n       (LEAST n. \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd l) \\<and> euclidean_size l = n)\n       in normalize l \n      else 0)\"\n\nqualified definition Gcd :: \"'a set \\<Rightarrow> 'a\"\n  where [code del]: \"Gcd A = Lcm {d. \\<forall>a\\<in>A. d dvd a}\"\n\nend    \n\nlemma semiring_gcd:\n  \"class.semiring_gcd one zero times gcd lcm\n    divide plus minus unit_factor normalize\"\nproof\n  show \"gcd a b dvd a\"\n    and \"gcd a b dvd b\" for a b\n    by (induct a b rule: eucl_induct)\n      (simp_all add: local.gcd_0 local.gcd_mod dvd_mod_iff)\nnext\n  show \"c dvd a \\<Longrightarrow> c dvd b \\<Longrightarrow> c dvd gcd a b\" for a b c\n  proof (induct a b rule: eucl_induct)\n    case (zero a) from \\<open>c dvd a\\<close> show ?case\n      by (rule dvd_trans) (simp add: local.gcd_0)\n  next\n    case (mod a b)\n    then show ?case\n      by (simp add: local.gcd_mod dvd_mod_iff)\n  qed\nnext\n  show \"normalize (gcd a b) = gcd a b\" for a b\n    by (induct a b rule: eucl_induct)\n      (simp_all add: local.gcd_0 local.gcd_mod)\nnext\n  show \"lcm a b = normalize (a * b div gcd a b)\" for a b\n    by (fact local.lcm_def)\nqed\n\ninterpretation semiring_gcd one zero times gcd lcm\n  divide plus minus unit_factor normalize\n  by (fact semiring_gcd)\n  \nlemma semiring_Gcd:\n  \"class.semiring_Gcd one zero times gcd lcm Gcd Lcm\n    divide plus minus unit_factor normalize\"\nproof -\n  show ?thesis\n  proof\n    have \"(\\<forall>a\\<in>A. a dvd Lcm A) \\<and> (\\<forall>b. (\\<forall>a\\<in>A. a dvd b) \\<longrightarrow> Lcm A dvd b)\" for A\n    proof (cases \"\\<exists>l. l \\<noteq>  0 \\<and> (\\<forall>a\\<in>A. a dvd l)\")\n      case False\n      then have \"Lcm A = 0\"\n        by (auto simp add: local.Lcm_def)\n      with False show ?thesis\n        by auto\n    next\n      case True\n      then obtain l\\<^sub>0 where l\\<^sub>0_props: \"l\\<^sub>0 \\<noteq> 0\" \"\\<forall>a\\<in>A. a dvd l\\<^sub>0\" by blast\n      define n where \"n = (LEAST n. \\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd l) \\<and> euclidean_size l = n)\"\n      define l where \"l = (SOME l. l \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd l) \\<and> euclidean_size l = n)\"\n      have \"\\<exists>l. l \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd l) \\<and> euclidean_size l = n\"\n        apply (subst n_def)\n        apply (rule LeastI [of _ \"euclidean_size l\\<^sub>0\"])\n        apply (rule exI [of _ l\\<^sub>0])\n        apply (simp add: l\\<^sub>0_props)\n        done\n      from someI_ex [OF this] have \"l \\<noteq> 0\" and \"\\<forall>a\\<in>A. a dvd l\"\n        and \"euclidean_size l = n\" \n        unfolding l_def by simp_all\n      {\n        fix l' assume \"\\<forall>a\\<in>A. a dvd l'\"\n        with \\<open>\\<forall>a\\<in>A. a dvd l\\<close> have \"\\<forall>a\\<in>A. a dvd gcd l l'\"\n          by (auto intro: gcd_greatest)\n        moreover from \\<open>l \\<noteq> 0\\<close> have \"gcd l l' \\<noteq> 0\"\n          by simp\n        ultimately have \"\\<exists>b. b \\<noteq> 0 \\<and> (\\<forall>a\\<in>A. a dvd b) \\<and> \n          euclidean_size b = euclidean_size (gcd l l')\"\n          by (intro exI [of _ \"gcd l l'\"], auto)\n        then have \"euclidean_size (gcd l l') \\<ge> n\"\n          by (subst n_def) (rule Least_le)\n        moreover have \"euclidean_size (gcd l l') \\<le> n\"\n        proof -\n          have \"gcd l l' dvd l\"\n            by simp\n          then obtain a where \"l = gcd l l' * a\" ..\n          with \\<open>l \\<noteq> 0\\<close> have \"a \\<noteq> 0\"\n            by auto\n          hence \"euclidean_size (gcd l l') \\<le> euclidean_size (gcd l l' * a)\"\n            by (rule size_mult_mono)\n          also have \"gcd l l' * a = l\" using \\<open>l = gcd l l' * a\\<close> ..\n          also note \\<open>euclidean_size l = n\\<close>\n          finally show \"euclidean_size (gcd l l') \\<le> n\" .\n        qed\n        ultimately have *: \"euclidean_size l = euclidean_size (gcd l l')\" \n          by (intro le_antisym, simp_all add: \\<open>euclidean_size l = n\\<close>)\n        from \\<open>l \\<noteq> 0\\<close> have \"l dvd gcd l l'\"\n          by (rule dvd_euclidean_size_eq_imp_dvd) (auto simp add: *)\n        hence \"l dvd l'\" by (rule dvd_trans [OF _ gcd_dvd2])\n      }\n      with \\<open>\\<forall>a\\<in>A. a dvd l\\<close> and \\<open>l \\<noteq> 0\\<close>\n        have \"(\\<forall>a\\<in>A. a dvd normalize l) \\<and> \n          (\\<forall>l'. (\\<forall>a\\<in>A. a dvd l') \\<longrightarrow> normalize l dvd l')\"\n        by auto\n      also from True have \"normalize l = Lcm A\"\n        by (simp add: local.Lcm_def Let_def n_def l_def)\n      finally show ?thesis .\n    qed\n    then show dvd_Lcm: \"a \\<in> A \\<Longrightarrow> a dvd Lcm A\"\n      and Lcm_least: \"(\\<And>a. a \\<in> A \\<Longrightarrow> a dvd b) \\<Longrightarrow> Lcm A dvd b\" for A and a b\n      by auto\n    show \"a \\<in> A \\<Longrightarrow> Gcd A dvd a\" for A and a\n      by (auto simp add: local.Gcd_def intro: Lcm_least)\n    show \"(\\<And>a. a \\<in> A \\<Longrightarrow> b dvd a) \\<Longrightarrow> b dvd Gcd A\" for A and b\n      by (auto simp add: local.Gcd_def intro: dvd_Lcm)\n    show [simp]: \"normalize (Lcm A) = Lcm A\" for A\n      by (simp add: local.Lcm_def)\n    show \"normalize (Gcd A) = Gcd A\" for A\n      by (simp add: local.Gcd_def)\n  qed\nqed\n\ninterpretation semiring_Gcd one zero times gcd lcm Gcd Lcm\n    divide plus minus unit_factor normalize\n  by (fact semiring_Gcd)\n\nsubclass factorial_semiring\nproof -\n  show \"class.factorial_semiring divide plus minus zero times one\n     unit_factor normalize\"\n  proof (standard, rule factorial_semiring_altI_aux) \\<comment> \\<open>FIXME rule\\<close>\n    fix x assume \"x \\<noteq> 0\"\n    thus \"finite {p. p dvd x \\<and> normalize p = p}\"\n    proof (induction \"euclidean_size x\" arbitrary: x rule: less_induct)\n      case (less x)\n      show ?case\n      proof (cases \"\\<exists>y. y dvd x \\<and> \\<not>x dvd y \\<and> \\<not>is_unit y\")\n        case False\n        have \"{p. p dvd x \\<and> normalize p = p} \\<subseteq> {1, normalize x}\"\n        proof\n          fix p assume p: \"p \\<in> {p. p dvd x \\<and> normalize p = p}\"\n          with False have \"is_unit p \\<or> x dvd p\" by blast\n          thus \"p \\<in> {1, normalize x}\"\n          proof (elim disjE)\n            assume \"is_unit p\"\n            hence \"normalize p = 1\" by (simp add: is_unit_normalize)\n            with p show ?thesis by simp\n          next\n            assume \"x dvd p\"\n            with p have \"normalize p = normalize x\" by (intro associatedI) simp_all\n            with p show ?thesis by simp\n          qed\n        qed\n        moreover have \"finite \\<dots>\" by simp\n        ultimately show ?thesis by (rule finite_subset)\n      next\n        case True\n        then obtain y where y: \"y dvd x\" \"\\<not>x dvd y\" \"\\<not>is_unit y\" by blast\n        define z where \"z = x div y\"\n        let ?fctrs = \"\\<lambda>x. {p. p dvd x \\<and> normalize p = p}\"\n        from y have x: \"x = y * z\" by (simp add: z_def)\n        with less.prems have \"y \\<noteq> 0\" \"z \\<noteq> 0\" by auto\n        have normalized_factors_product:\n          \"{p. p dvd a * b \\<and> normalize p = p} \\<subseteq>\n             (\\<lambda>(x,y). normalize (x * y)) ` ({p. p dvd a \\<and> normalize p = p} \\<times> {p. p dvd b \\<and> normalize p = p})\"\n          for a b\n        proof safe\n          fix p assume p: \"p dvd a * b\" \"normalize p = p\"\n          from p(1) obtain x y where xy: \"p = x * y\" \"x dvd a\" \"y dvd b\"\n            by (rule dvd_productE)\n          define x' y' where \"x' = normalize x\" and \"y' = normalize y\"\n          have \"p = normalize (x' * y')\"\n            using p by (simp add: xy x'_def y'_def)\n          moreover have \"x' dvd a \\<and> normalize x' = x'\" and \"y' dvd b \\<and> normalize y' = y'\"\n            using xy by (auto simp: x'_def y'_def)\n          ultimately show \"p \\<in> (\\<lambda>(x, y). normalize (x * y)) `\n              ({p. p dvd a \\<and> normalize p = p} \\<times> {p. p dvd b \\<and> normalize p = p})\" by fast\n        qed\n        from x y have \"\\<not>is_unit z\" by (auto simp: mult_unit_dvd_iff)\n        have \"?fctrs x \\<subseteq> (\\<lambda>(p,p'). normalize (p * p')) ` (?fctrs y \\<times> ?fctrs z)\"\n          by (subst x) (rule normalized_factors_product)\n        moreover have \"\\<not>y * z dvd y * 1\" \"\\<not>y * z dvd 1 * z\"\n          by (subst dvd_times_left_cancel_iff dvd_times_right_cancel_iff; fact)+\n        hence \"finite ((\\<lambda>(p,p'). normalize (p * p')) ` (?fctrs y \\<times> ?fctrs z))\"\n          by (intro finite_imageI finite_cartesian_product less dvd_proper_imp_size_less)\n             (auto simp: x)\n        ultimately show ?thesis by (rule finite_subset)\n      qed\n    qed\n  next\n    fix p\n    assume \"irreducible p\"\n    then show \"prime_elem p\"\n      by (rule irreducible_imp_prime_elem_gcd)\n  qed\nqed\n\nlemma Gcd_eucl_set [code]:\n  \"Gcd (set xs) = fold gcd xs 0\"\n  by (fact Gcd_set_eq_fold)\n\nlemma Lcm_eucl_set [code]:\n  \"Lcm (set xs) = fold lcm xs 1\"\n  by (fact Lcm_set_eq_fold)\n \nend\n\nhide_const (open) gcd lcm Gcd Lcm\n\nlemma prime_elem_int_abs_iff [simp]:\n  fixes p :: int\n  shows \"prime_elem \\<bar>p\\<bar> \\<longleftrightarrow> prime_elem p\"\n  using prime_elem_normalize_iff [of p] by simp\n  \nlemma prime_elem_int_minus_iff [simp]:\n  fixes p :: int\n  shows \"prime_elem (- p) \\<longleftrightarrow> prime_elem p\"\n  using prime_elem_normalize_iff [of \"- p\"] by simp\n\nlemma prime_int_iff:\n  fixes p :: int\n  shows \"prime p \\<longleftrightarrow> p > 0 \\<and> prime_elem p\"\n  by (auto simp add: prime_def dest: prime_elem_not_zeroI)\n  \n  \nsubsection \\<open>The (simple) euclidean algorithm as gcd computation\\<close>\n  \nclass euclidean_semiring_gcd = normalization_euclidean_semiring + gcd + Gcd +\n  assumes gcd_eucl: \"Euclidean_Algorithm.gcd = GCD.gcd\"\n    and lcm_eucl: \"Euclidean_Algorithm.lcm = GCD.lcm\"\n  assumes Gcd_eucl: \"Euclidean_Algorithm.Gcd = GCD.Gcd\"\n    and Lcm_eucl: \"Euclidean_Algorithm.Lcm = GCD.Lcm\"\nbegin\n\nsubclass semiring_gcd\n  unfolding gcd_eucl [symmetric] lcm_eucl [symmetric]\n  by (fact semiring_gcd)\n\nsubclass semiring_Gcd\n  unfolding  gcd_eucl [symmetric] lcm_eucl [symmetric]\n    Gcd_eucl [symmetric] Lcm_eucl [symmetric]\n  by (fact semiring_Gcd)\n\nsubclass factorial_semiring_gcd\nproof\n  show \"gcd a b = gcd_factorial a b\" for a b\n    apply (rule sym)\n    apply (rule gcdI)\n       apply (fact gcd_lcm_factorial)+\n    done\n  then show \"lcm a b = lcm_factorial a b\" for a b\n    by (simp add: lcm_factorial_gcd_factorial lcm_gcd)\n  show \"Gcd A = Gcd_factorial A\" for A\n    apply (rule sym)\n    apply (rule GcdI)\n       apply (fact gcd_lcm_factorial)+\n    done\n  show \"Lcm A = Lcm_factorial A\" for A\n    apply (rule sym)\n    apply (rule LcmI)\n       apply (fact gcd_lcm_factorial)+\n    done\nqed\n\nlemma gcd_mod_right [simp]:\n  \"a \\<noteq> 0 \\<Longrightarrow> gcd a (b mod a) = gcd a b\"\n  unfolding gcd.commute [of a b]\n  by (simp add: gcd_eucl [symmetric] local.gcd_mod)\n\nlemma gcd_mod_left [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> gcd (a mod b) b = gcd a b\"\n  by (drule gcd_mod_right [of _ a]) (simp add: gcd.commute)\n\nlemma euclidean_size_gcd_le1 [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"euclidean_size (gcd a b) \\<le> euclidean_size a\"\nproof -\n  from gcd_dvd1 obtain c where A: \"a = gcd a b * c\" ..\n  with assms have \"c \\<noteq> 0\"\n    by auto\n  moreover from this\n  have \"euclidean_size (gcd a b) \\<le> euclidean_size (gcd a b * c)\"\n    by (rule size_mult_mono)\n  with A show ?thesis\n    by simp\nqed\n\nlemma euclidean_size_gcd_le2 [simp]:\n  \"b \\<noteq> 0 \\<Longrightarrow> euclidean_size (gcd a b) \\<le> euclidean_size b\"\n  by (subst gcd.commute, rule euclidean_size_gcd_le1)\n\nlemma euclidean_size_gcd_less1:\n  assumes \"a \\<noteq> 0\" and \"\\<not> a dvd b\"\n  shows \"euclidean_size (gcd a b) < euclidean_size a\"\nproof (rule ccontr)\n  assume \"\\<not>euclidean_size (gcd a b) < euclidean_size a\"\n  with \\<open>a \\<noteq> 0\\<close> have A: \"euclidean_size (gcd a b) = euclidean_size a\"\n    by (intro le_antisym, simp_all)\n  have \"a dvd gcd a b\"\n    by (rule dvd_euclidean_size_eq_imp_dvd) (simp_all add: assms A)\n  hence \"a dvd b\" using dvd_gcdD2 by blast\n  with \\<open>\\<not> a dvd b\\<close> show False by contradiction\nqed\n\nlemma euclidean_size_gcd_less2:\n  assumes \"b \\<noteq> 0\" and \"\\<not> b dvd a\"\n  shows \"euclidean_size (gcd a b) < euclidean_size b\"\n  using assms by (subst gcd.commute, rule euclidean_size_gcd_less1)\n\nlemma euclidean_size_lcm_le1: \n  assumes \"a \\<noteq> 0\" and \"b \\<noteq> 0\"\n  shows \"euclidean_size a \\<le> euclidean_size (lcm a b)\"\nproof -\n  have \"a dvd lcm a b\" by (rule dvd_lcm1)\n  then obtain c where A: \"lcm a b = a * c\" ..\n  with \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close> have \"c \\<noteq> 0\" by (auto simp: lcm_eq_0_iff)\n  then show ?thesis by (subst A, intro size_mult_mono)\nqed\n\nlemma euclidean_size_lcm_le2:\n  \"a \\<noteq> 0 \\<Longrightarrow> b \\<noteq> 0 \\<Longrightarrow> euclidean_size b \\<le> euclidean_size (lcm a b)\"\n  using euclidean_size_lcm_le1 [of b a] by (simp add: ac_simps)\n\nlemma euclidean_size_lcm_less1:\n  assumes \"b \\<noteq> 0\" and \"\\<not> b dvd a\"\n  shows \"euclidean_size a < euclidean_size (lcm a b)\"\nproof (rule ccontr)\n  from assms have \"a \\<noteq> 0\" by auto\n  assume \"\\<not>euclidean_size a < euclidean_size (lcm a b)\"\n  with \\<open>a \\<noteq> 0\\<close> and \\<open>b \\<noteq> 0\\<close> have \"euclidean_size (lcm a b) = euclidean_size a\"\n    by (intro le_antisym, simp, intro euclidean_size_lcm_le1)\n  with assms have \"lcm a b dvd a\" \n    by (rule_tac dvd_euclidean_size_eq_imp_dvd) (auto simp: lcm_eq_0_iff)\n  hence \"b dvd a\" by (rule lcm_dvdD2)\n  with \\<open>\\<not>b dvd a\\<close> show False by contradiction\nqed\n\nlemma euclidean_size_lcm_less2:\n  assumes \"a \\<noteq> 0\" and \"\\<not> a dvd b\"\n  shows \"euclidean_size b < euclidean_size (lcm a b)\"\n  using assms euclidean_size_lcm_less1 [of a b] by (simp add: ac_simps)\n\nend\n\nlemma factorial_euclidean_semiring_gcdI:\n  \"OFCLASS('a::{factorial_semiring_gcd, normalization_euclidean_semiring}, euclidean_semiring_gcd_class)\"\nproof\n  interpret semiring_Gcd 1 0 times\n    Euclidean_Algorithm.gcd Euclidean_Algorithm.lcm\n    Euclidean_Algorithm.Gcd Euclidean_Algorithm.Lcm\n    divide plus minus unit_factor normalize\n    rewrites \"dvd.dvd (*) = Rings.dvd\"\n    by (fact semiring_Gcd) (simp add: dvd.dvd_def dvd_def fun_eq_iff)\n  show [simp]: \"Euclidean_Algorithm.gcd = (gcd :: 'a \\<Rightarrow> _)\"\n  proof (rule ext)+\n    fix a b :: 'a\n    show \"Euclidean_Algorithm.gcd a b = gcd a b\"\n    proof (induct a b rule: eucl_induct)\n      case zero\n      then show ?case\n        by simp\n    next\n      case (mod a b)\n      moreover have \"gcd b (a mod b) = gcd b a\"\n        using GCD.gcd_add_mult [of b \"a div b\" \"a mod b\", symmetric]\n          by (simp add: div_mult_mod_eq)\n      ultimately show ?case\n        by (simp add: Euclidean_Algorithm.gcd_mod ac_simps)\n    qed\n  qed\n  show [simp]: \"Euclidean_Algorithm.Lcm = (Lcm :: 'a set \\<Rightarrow> _)\"\n    by (auto intro!: Lcm_eqI GCD.dvd_Lcm GCD.Lcm_least)\n  show \"Euclidean_Algorithm.lcm = (lcm :: 'a \\<Rightarrow> _)\"\n    by (simp add: fun_eq_iff Euclidean_Algorithm.lcm_def semiring_gcd_class.lcm_gcd)\n  show \"Euclidean_Algorithm.Gcd = (Gcd :: 'a set \\<Rightarrow> _)\"\n    by (simp add: fun_eq_iff Euclidean_Algorithm.Gcd_def semiring_Gcd_class.Gcd_Lcm)\nqed\n\n\nsubsection \\<open>The extended euclidean algorithm\\<close>\n  \nclass euclidean_ring_gcd = euclidean_semiring_gcd + idom\nbegin\n\nsubclass euclidean_ring ..\nsubclass ring_gcd ..\nsubclass factorial_ring_gcd ..\n\nfunction euclid_ext_aux :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<times> 'a) \\<times> 'a\"\n  where \"euclid_ext_aux s' s t' t r' r = (\n     if r = 0 then let c = 1 div unit_factor r' in ((s' * c, t' * c), normalize r')\n     else let q = r' div r\n          in euclid_ext_aux s (s' - q * s) t (t' - q * t) r (r' mod r))\"\n  by auto\ntermination\n  by (relation \"measure (\\<lambda>(_, _, _, _, _, b). euclidean_size b)\")\n    (simp_all add: mod_size_less)\n\nabbreviation (input) euclid_ext :: \"'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<times> 'a) \\<times> 'a\"\n  where \"euclid_ext \\<equiv> euclid_ext_aux 1 0 0 1\"\n    \nlemma\n  assumes \"gcd r' r = gcd a b\"\n  assumes \"s' * a + t' * b = r'\"\n  assumes \"s * a + t * b = r\"\n  assumes \"euclid_ext_aux s' s t' t r' r = ((x, y), c)\"\n  shows euclid_ext_aux_eq_gcd: \"c = gcd a b\"\n    and euclid_ext_aux_bezout: \"x * a + y * b = gcd a b\"\nproof -\n  have \"case euclid_ext_aux s' s t' t r' r of ((x, y), c) \\<Rightarrow> \n    x * a + y * b = c \\<and> c = gcd a b\" (is \"?P (euclid_ext_aux s' s t' t r' r)\")\n    using assms(1-3)\n  proof (induction s' s t' t r' r rule: euclid_ext_aux.induct)\n    case (1 s' s t' t r' r)\n    show ?case\n    proof (cases \"r = 0\")\n      case True\n      hence \"euclid_ext_aux s' s t' t r' r = \n               ((s' div unit_factor r', t' div unit_factor r'), normalize r')\"\n        by (subst euclid_ext_aux.simps) (simp add: Let_def)\n      also have \"?P \\<dots>\"\n      proof safe\n        have \"s' div unit_factor r' * a + t' div unit_factor r' * b = \n                (s' * a + t' * b) div unit_factor r'\"\n          by (cases \"r' = 0\") (simp_all add: unit_div_commute)\n        also have \"s' * a + t' * b = r'\" by fact\n        also have \"\\<dots> div unit_factor r' = normalize r'\" by simp\n        finally show \"s' div unit_factor r' * a + t' div unit_factor r' * b = normalize r'\" .\n      next\n        from \"1.prems\" True show \"normalize r' = gcd a b\"\n          by simp\n      qed\n      finally show ?thesis .\n    next\n      case False\n      hence \"euclid_ext_aux s' s t' t r' r = \n             euclid_ext_aux s (s' - r' div r * s) t (t' - r' div r * t) r (r' mod r)\"\n        by (subst euclid_ext_aux.simps) (simp add: Let_def)\n      also from \"1.prems\" False have \"?P \\<dots>\"\n      proof (intro \"1.IH\")\n        have \"(s' - r' div r * s) * a + (t' - r' div r * t) * b =\n              (s' * a + t' * b) - r' div r * (s * a + t * b)\" by (simp add: algebra_simps)\n        also have \"s' * a + t' * b = r'\" by fact\n        also have \"s * a + t * b = r\" by fact\n        also have \"r' - r' div r * r = r' mod r\" using div_mult_mod_eq [of r' r]\n          by (simp add: algebra_simps)\n        finally show \"(s' - r' div r * s) * a + (t' - r' div r * t) * b = r' mod r\" .\n      qed (auto simp: algebra_simps minus_mod_eq_div_mult [symmetric] gcd.commute)\n      finally show ?thesis .\n    qed\n  qed\n  with assms(4) show \"c = gcd a b\" \"x * a + y * b = gcd a b\"\n    by simp_all\nqed\n\ndeclare euclid_ext_aux.simps [simp del]\n\ndefinition bezout_coefficients :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<times> 'a\"\n  where [code]: \"bezout_coefficients a b = fst (euclid_ext a b)\"\n\nlemma bezout_coefficients_0: \n  \"bezout_coefficients a 0 = (1 div unit_factor a, 0)\"\n  by (simp add: bezout_coefficients_def euclid_ext_aux.simps)\n\nlemma bezout_coefficients_left_0: \n  \"bezout_coefficients 0 a = (0, 1 div unit_factor a)\"\n  by (simp add: bezout_coefficients_def euclid_ext_aux.simps)\n\nlemma bezout_coefficients:\n  assumes \"bezout_coefficients a b = (x, y)\"\n  shows \"x * a + y * b = gcd a b\"\n  using assms by (simp add: bezout_coefficients_def\n    euclid_ext_aux_bezout [of a b a b 1 0 0 1 x y] prod_eq_iff)\n\nlemma bezout_coefficients_fst_snd:\n  \"fst (bezout_coefficients a b) * a + snd (bezout_coefficients a b) * b = gcd a b\"\n  by (rule bezout_coefficients) simp\n\nlemma euclid_ext_eq [simp]:\n  \"euclid_ext a b = (bezout_coefficients a b, gcd a b)\" (is \"?p = ?q\")\nproof\n  show \"fst ?p = fst ?q\"\n    by (simp add: bezout_coefficients_def)\n  have \"snd (euclid_ext_aux 1 0 0 1 a b) = gcd a b\"\n    by (rule euclid_ext_aux_eq_gcd [of a b a b 1 0 0 1])\n      (simp_all add: prod_eq_iff)\n  then show \"snd ?p = snd ?q\"\n    by simp\nqed\n\ndeclare euclid_ext_eq [symmetric, code_unfold]\n\nend\n\nclass normalization_euclidean_semiring_multiplicative =\n  normalization_euclidean_semiring + normalization_semidom_multiplicative\nbegin\n\nsubclass factorial_semiring_multiplicative ..\n\nend\n\nclass field_gcd =\n  field + unique_euclidean_ring + euclidean_ring_gcd + normalization_semidom_multiplicative\nbegin\n\nsubclass normalization_euclidean_semiring_multiplicative ..\n\nsubclass normalization_euclidean_semiring ..\n\nsubclass semiring_gcd_mult_normalize ..\n\nend\n\n\nsubsection \\<open>Typical instances\\<close>\n\ninstance nat :: normalization_euclidean_semiring ..\n\ninstance nat :: euclidean_semiring_gcd\nproof\n  interpret semiring_Gcd 1 0 times\n    \"Euclidean_Algorithm.gcd\" \"Euclidean_Algorithm.lcm\"\n    \"Euclidean_Algorithm.Gcd\" \"Euclidean_Algorithm.Lcm\"\n    divide plus minus unit_factor normalize\n    rewrites \"dvd.dvd (*) = Rings.dvd\"\n    by (fact semiring_Gcd) (simp add: dvd.dvd_def dvd_def fun_eq_iff)\n  show [simp]: \"(Euclidean_Algorithm.gcd :: nat \\<Rightarrow> _) = gcd\"\n  proof (rule ext)+\n    fix m n :: nat\n    show \"Euclidean_Algorithm.gcd m n = gcd m n\"\n    proof (induct m n rule: eucl_induct)\n      case zero\n      then show ?case\n        by simp\n    next\n      case (mod m n)\n      then have \"gcd n (m mod n) = gcd n m\"\n        using gcd_nat.simps [of m n] by (simp add: ac_simps)\n      with mod show ?case\n        by (simp add: Euclidean_Algorithm.gcd_mod ac_simps)\n    qed\n  qed\n  show [simp]: \"(Euclidean_Algorithm.Lcm :: nat set \\<Rightarrow> _) = Lcm\"\n    by (auto intro!: ext Lcm_eqI)\n  show \"(Euclidean_Algorithm.lcm :: nat \\<Rightarrow> _) = lcm\"\n    by (simp add: fun_eq_iff Euclidean_Algorithm.lcm_def semiring_gcd_class.lcm_gcd)\n  show \"(Euclidean_Algorithm.Gcd :: nat set \\<Rightarrow> _) = Gcd\"\n    by (simp add: fun_eq_iff Euclidean_Algorithm.Gcd_def semiring_Gcd_class.Gcd_Lcm)\nqed\n\ninstance nat :: normalization_euclidean_semiring_multiplicative ..\n\nlemma prime_factorization_Suc_0 [simp]: \"prime_factorization (Suc 0) = {#}\"\n  unfolding One_nat_def [symmetric] using prime_factorization_1 .\n\ninstance int :: normalization_euclidean_semiring ..\n\ninstance int :: euclidean_ring_gcd\nproof\n  interpret semiring_Gcd 1 0 times\n    \"Euclidean_Algorithm.gcd\" \"Euclidean_Algorithm.lcm\"\n    \"Euclidean_Algorithm.Gcd\" \"Euclidean_Algorithm.Lcm\"\n    divide plus minus unit_factor normalize\n    rewrites \"dvd.dvd (*) = Rings.dvd\"\n    by (fact semiring_Gcd) (simp add: dvd.dvd_def dvd_def fun_eq_iff)\n  show [simp]: \"(Euclidean_Algorithm.gcd :: int \\<Rightarrow> _) = gcd\"\n  proof (rule ext)+\n    fix k l :: int\n    show \"Euclidean_Algorithm.gcd k l = gcd k l\"\n    proof (induct k l rule: eucl_induct)\n      case zero\n      then show ?case\n        by simp\n    next\n      case (mod k l)\n      have \"gcd l (k mod l) = gcd l k\"\n      proof (cases l \"0::int\" rule: linorder_cases)\n        case less\n        then show ?thesis\n          using gcd_non_0_int [of \"- l\" \"- k\"] by (simp add: ac_simps)\n      next\n        case equal\n        with mod show ?thesis\n          by simp\n      next\n        case greater\n        then show ?thesis\n          using gcd_non_0_int [of l k] by (simp add: ac_simps)\n      qed\n      with mod show ?case\n        by (simp add: Euclidean_Algorithm.gcd_mod ac_simps)\n    qed\n  qed\n  show [simp]: \"(Euclidean_Algorithm.Lcm :: int set \\<Rightarrow> _) = Lcm\"\n    by (auto intro!: ext Lcm_eqI)\n  show \"(Euclidean_Algorithm.lcm :: int \\<Rightarrow> _) = lcm\"\n    by (simp add: fun_eq_iff Euclidean_Algorithm.lcm_def semiring_gcd_class.lcm_gcd)\n  show \"(Euclidean_Algorithm.Gcd :: int set \\<Rightarrow> _) = Gcd\"\n    by (simp add: fun_eq_iff Euclidean_Algorithm.Gcd_def semiring_Gcd_class.Gcd_Lcm)\nqed\n\ninstance int :: normalization_euclidean_semiring_multiplicative ..\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Computational_Algebra/Euclidean_Algorithm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.8459424334245618, "lm_q1q2_score": 0.7641348949128268}}
{"text": "theory Homework5_1\nimports Main\nbegin\n\n  (*\n    ISSUED: Wednesday, October 18\n    DUE: Wednesday, October 25, 11:59pm\n    POINTS: 5\n  *)\n\n  (*\n    Recall the LTS formalization from the tutorial. \n    I copied the important parts here:\n  *)\n  \nsection \\<open>Parts of LTS from Tutorial\\<close>  \ntype_synonym ('q,'a) lts = \"'q \\<Rightarrow> 'a \\<Rightarrow> 'q \\<Rightarrow> bool\"\n\n\ninductive word :: \"('q,'a) lts \\<Rightarrow> 'q \\<Rightarrow> 'a list \\<Rightarrow> 'q \\<Rightarrow> bool\" \n  where\n    empty: \"word L q [] q\"\n  | cons: \"\\<lbrakk> L p a q; word L q as r \\<rbrakk> \\<Longrightarrow> word L p (a#as) r\"\n\nlemma word_Nil_conv: \"word L p [] q \\<longleftrightarrow> p=q\"\n  by (auto elim: word.cases intro: word.intros)\n  \nlemma word_Cons_conv: \"word L p (a#bs) r \\<longleftrightarrow> (\\<exists>q. L p a q \\<and> word L q bs r)\"\n  by (auto elim: word.cases intro: word.intros)\n  \nlemma word_append_conv: \"word L p (as@bs) r \\<longleftrightarrow> (\\<exists>q. word L p as q \\<and> word L q bs r)\"\n  (* Slightly changed proof compared to tutorial *)\n  by (induction as arbitrary: p) (auto simp: word_Nil_conv word_Cons_conv)\n\nsection \\<open>Product Construction\\<close>  \n(* Here starts the homework assignment *)  \n  \n(*\n  For a labeled transition system, we define the language\n  from state p to state q as the set of all words from p to q. \n*)\ndefinition \"lang L p q = {w. word L p w q}\"  \n\n\n(*\n  The product \"prod L1 L2\" of two labeled transition systems L1 :: ('p,'a) lts \n  and L2 :: ('q,'a) lts is a labeled transition system over states of\n  type 'p\\<times>'q. We define (prod L1 L2) (p1,q1) a (p2,q2) iff \n  L1 p1 a p2 and L2 q1 a q2.\n*)\ndefinition L_prod :: \"('p,'a) lts \\<Rightarrow> ('q,'a) lts \\<Rightarrow> ('p\\<times>'q,'a) lts\" where\n  \"L_prod L1 L2 \\<equiv> \\<lambda>(p1,p2) l (q1,q2). L1 p1 l q1 \\<and> L2 p2 l q2\"\n\n(*\n  Intuitively, a transition of the product corresponds to a transition \n  of both components, with the same label.\n*)  \n\n(*\n  Show that the language of the product LTS corresponds to the \n  intersection of the languages of the component LTSs.\n  \n  Proof sketch:\n    assume we have a word w in the product language.\n    hence, we have \"word (L_prod L1 L2) (p1, p2) w (q1, q2)\"\n    by induction on w, we get word L1 p1 w q1 and word L2 p2 w q2\n    from which, by definition of lang, we get the proposition.\n  \n    the proof of the other direction is symmetric.\n    \n  Use an Isar proof! Note: There is no notion of \"symmetric\" in Isar, so \n    you will have to actually prove both directions.\n    \n  Hint: In the induction proofs, use the structural equations  \n     word_Cons_conv word_Nil_conv as simp rules, rather than \n     the word.intros and word.cases rules. \n     Don't forget to generalize over some variables!\n    \n*)\n\nlemma \"lang (L_prod L1 L2) (p1,p2) (q1,q2) = (lang L1 p1 q1 \\<inter> lang L2 p2 q2)\"\nproof (intro equalityI subsetI)  \n  fix w\n  assume \"w \\<in> lang (L_prod L1 L2) (p1, p2) (q1, q2)\" \n  (* Insert proof of first direction here *)\n  show \"w \\<in> lang L1 p1 q1 \\<inter> lang L2 p2 q2\" sorry\nnext\n  fix w\n  assume \"w \\<in> lang L1 p1 q1 \\<inter> lang L2 p2 q2\"\n  (* Insert proof of other direction here *)\n  show \"w \\<in> lang (L_prod L1 L2) (p1, p2) (q1, q2)\" sorry\nqed\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Homeworks/Homework5_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7641348949128268}}
{"text": "(*  Title       : LeapingFrog.thy\n    Author      : Vincent Bürgin\n\n    This theory formalizes Conway's Soldiers, also known as the Leaping Frog game.\n\n    The game is played on the infinite grid (Z x N), where the top row corresponds to an y\n      coordinate of 0. An arbitrary amount of coins can be placed on the grid below the line y = 5,\n      i.e. starting at the sixth row.\n    Then the coins can be moved according to peg solitaire rules:\n      A coin may jump over an adjacent coin vertically or horizontally. The coin it jumped over\n      is removed from the board.\n    The objective is to get a coin to the top row (y = 0). John Conway proved that this is not\n      possible, using a number related to the golden ratio phi: Let w = 1/phi = phi - 1.\n      Assign to the field (x, y) the power w^(|x|+y). Then the sum of all fields occupied by an\n      initial coin configuration is at most 1. Furthermore, performing moves cannot increase the\n      sum of occupied fields. However the value of the goal field (0, 0) is 1 as well:\n      From this, it is shown that the goal field cannot be reached in a finite number of moves.\n\n          ................... <-- Goal row.\n          ...................\n          ...................\n          ...................\n          ...................\n          ooooooooooooooooooo <-- On this row and below, coins may be placed.\n          ooooooooooooooooooo\n          ooooooooooooooooooo     The grid extends infinitely to the left, right and bottom.\n\n    References:\n    - E. Berlekamp, J. Conway and R. Guy, Winning Ways for Your Mathematical Plays\n    - Claudi Alsina and Roger B. Nelsen, Charming Proofs: A Journey Into Elegant Mathematics\n    - Miguel de Guzmán, https://www.oma.org.ar/red/la_rana.htm (online explanation of the proof\n        as performed here, in Spanish)\n*)\n\ntheory LeapingFrog\n  imports Main HOL.Real HOL.NthRoot HOL.Boolean_Algebras HOL.Series \"HOL-IMP.Star\"\nbegin\n\nsection \\<open>The number w\\<close>\n\n(*\n  Definition of the number w = (golden ratio) - 1\n*)\ndefinition w :: \"real\" where\n\"w = (sqrt 5 - 1)/2\"\n\n(*\n  Recurrence relations the powers of w satisfy:\n    -   w^2 = 1 - w\n    -   w^(n+1) + w^(n+2) = w^n\n\n  These relations will be crucial for the whole argument to work.\n*)\nlemma w_squared: \"w^2 = 1 - w\"\nproof -\n  have \"w^2 = (sqrt 5 - 1)^2 / 4\"\n    by (simp add: w_def power_divide)\n  moreover have \"(sqrt 5 - 1)^2 = (sqrt 5)^2 - 2*(sqrt 5)*1 + 1^2\"\n    by (simp add: power2_diff)\n  ultimately have w_squared: \"w^2 = (3 - (sqrt 5))/2\" by force\n  moreover have \"1 - w = (3 - sqrt(5))/2\" using w_def by auto\n  ultimately show \"w^2 = 1 - w\" by force\nqed\n\nlemma w_recurrence: \"w^(n+1) + w^(n+2) = w^n\"\nproof -\n  have \"w^(n+1) + w^(n+2) = w^n*(w + w^2)\"\n    by (smt (verit) power_add power_one_right right_diff_distrib)\n  moreover have \"w + w^2 = 1\" using w_squared by simp\n  ultimately show ?thesis by simp\nqed\n\n(*\n  w is in (0, 1): We will need this to prove the limit of the geometric series with base w.\n*)\nlemma w_range: \"w > 0 \\<and> w < 1\"\nproof -\n  have \"sqrt 5 > 1\" by force\n  then have 1: \"w > 0\" by (simp add: w_def)\n  have \"w^2 < 1\" using w_def w_squared using 1 by linarith\n  then have 2: \"w < 1\" by (smt (verit) one_le_power)\n  then show ?thesis using 1 2 by blast\nqed\n\n(*\n  We will use this to have an upper bound for 1/(1-w).\n*)\nlemma w_bound:\"1 - w > 1/4\"\nproof -\n  have \"sqrt 5 - 1 > 1\" by (smt (verit, ccfv_SIG) real_sqrt_four real_sqrt_less_iff)\n  then have \"w > 1/2\" using w_def by force\n  then have \"w^2 > 1/4\" by (simp add: power_divide w_def)\n  then show ?thesis by (simp add: w_squared)\nqed\n\nsection \\<open>Leaping Frog game definitions\\<close>\n\n(*\n  The game is played on a grid in the half-plane: grid cells have `int` x coordinates and `nat`\n    y coordinates. A coin configuration `coins` is a set of grid cell positions.\n*)\ntype_synonym position = \"(int \\<times> nat)\"\ntype_synonym coins = \"position set\"\n\nsubsection \\<open>Jumping predicates\\<close>\n(*\n  A coin configuration A can transition to a coin configuration B as follows: A coin in A can jump\n    over an (horizontally or vertically) adjacent coin if the next cell behind is unoccupied.\n    The coin that it jumped over is removed. The resulting configuration is B, and A and B are\n    related via `jump`.\n\n  Example: |o|o|.|  \\<longrightarrow>  |.|.|o| (left coin jumps over the middle coin).\n*)\ninductive jump :: \"coins \\<Rightarrow> coins \\<Rightarrow> bool\" where\n  left: \"\\<lbrakk>(x,y) \\<in> A; (x-1, y) \\<in> A; (x-2, y) \\<notin> A; B = (A - {(x,y), (x-1,y)}) \\<union> {(x-2, y)}\\<rbrakk>\n    \\<Longrightarrow> jump A B\"\n| right: \"\\<lbrakk>(x,y) \\<in> A; (x+1, y) \\<in> A; (x+2, y) \\<notin> A; B = (A - {(x,y), (x+1,y)}) \\<union> {(x+2, y)}\\<rbrakk>\n    \\<Longrightarrow> jump A B\"\n| up: \"\\<lbrakk>(x,y) \\<in> A; (x, y-1) \\<in> A; (x, y-2) \\<notin> A; B = (A - {(x,y), (x,y-1)}) \\<union> {(x, y-2)}\\<rbrakk>\n    \\<Longrightarrow> jump A B\"\n| down: \"\\<lbrakk>(x,y) \\<in> A; (x, y+1) \\<in> A; (x, y+2) \\<notin> A; B = (A - {(x,y), (x,y+1)}) \\<union> {(x, y+2)}\\<rbrakk>\n    \\<Longrightarrow> jump A B\"\n\n(*\n  A and B are related via `jumps` if B can be reached from A via a chain of multiple `jump`s.\n*)\ndefinition jumps :: \"coins \\<Rightarrow> coins \\<Rightarrow> bool\"  where\n\"jumps = star jump\"\n\n(*\n  Some examples of the `jump` and `jumps` predicates\n*)\nlemma example_right: \"jump {(0, 0), (1, 0)} {(2, 0)}\"\n  by (rule jump.right[of 0 0]) auto\nlemma example_left: \"jump {(0, 0), (-1, 0)} {(-2, 0)}\"\n  by (rule jump.left[of 0 0]) auto\nlemma example_up: \"jump {(0, 2), (0, 1)} {(0, 0)}\"\n  by (rule jump.up[of 0 2]) auto\nlemma example_down: \"jump {(0, 0), (0, 1)} {(0, 2)}\"\n  by (rule jump.down[of 0 0]) auto\nlemma example_two_jumps: \"jumps {(0,0), (0,1), (1,2)} {(2,2)}\"\nunfolding jumps_def proof (rule star.step)\n  show \"jump {(0,0), (0,1), (1,2)} {(0,2), (1,2)}\"\n    by (rule jump.down[of 0 0]) auto\n  have \"jump {(0,2), (1,2)} {(2,2)}\"\n    by (rule jump.right[of 0 2]) auto \n  then show \"star jump {(0, 2), (1, 2)} {(2, 2)}\" by blast\nqed\n\nsubsection \\<open>Coin grid and initial configurations\\<close>\n(*\n  Definitions and facts about initial configurations:\n\n  In the beginning of the game, coins may be placed below the line \"y = 5\". Coin configurations\n    where all coins are below this line are initial configurations. Any initial configuration is a\n    subset of the maximal initial configuration, where all coins below the line are present.\n*)\nfun below_the_line :: \"position \\<Rightarrow> bool\" where\n\"below_the_line (_, y) = (y \\<ge> 5)\"\n\ndefinition initial_coins :: \"coins \\<Rightarrow> bool\" where\n\"initial_coins coins \\<longleftrightarrow> (\\<forall>coin \\<in> coins. below_the_line coin)\"\n\ndefinition max_initial_coins :: \"coins\" where\n\"max_initial_coins = {(x, y) |x y. y \\<ge> 5}\" \n\ndefinition all_coins :: \"coins\" where\n\"all_coins = {(x,y)|x y. True}\"\n\nlemma initial_coins_subset: \"initial_coins coins \\<Longrightarrow> coins \\<subseteq> max_initial_coins\"\n  using initial_coins_def max_initial_coins_def by fastforce\n\nsubsection \\<open>Assigning powers of w to grid cells/Sums of powers of w to coin configurations\\<close>\n\n(*\n  In the original proof, every grid cell is assigned the power w^(|x|+y).\n\n  We want to avoid series over `int` since `Series.thy` uses series over `nat`. We therefore assign\n    powers as follows:\n  - The coordinate (0::nat, y::nat) is assigned w^y\n  - The coordinate (x::nat, y::nat), x > 0, is assigned 2*w^(x+y) and captures the sum of the powers\n      assigned to the grid cells (-x::int, y) and (x::int, y)\n\n  `point_pow` defines this assignment for all positions (x, y) contained in a coin configuration.\n*)\nfun point_pow :: \"coins \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> real\" where\n\"point_pow c x y = (if (int(x), y) \\<in> c then w^(x+y) else 0)\n  + (if (-int(x), y) \\<in> c \\<and> x > 0 then w^(x+y) else 0)\"\n\n(*\n  `power_sum` sums up the values of w^(x+y) for all coin positions in a coin configuration via\n    a double series.\n*)\nfun power_sum :: \"coins \\<Rightarrow> real\" where\n\"power_sum c = suminf (\\<lambda>x. suminf (point_pow c x))\"\n\nsection \\<open>Properties of power sums of w\\<close>\ntext \\<open>This section contains proofs about the `power_sum` function:\n  - The inner series and the outer series that define `power_sum` converge,\n  - the value of `power_sum` for finite coin configurations can be computed via `sum`,\n  - considering a (proper) subset of coins (strictly) decreases the power sum\\<close>\n\nsubsection \\<open>Preliminary lemmas\\<close>\n\n(* \n  Kind of specific lemma about transforming geometric series, but an argument of this form\n   is needed quite often in the following and is a bit of work to prove.\n*)\nlemma geometric_sums_transformation: \"norm (b::real) < 1 \\<Longrightarrow> (\\<lambda>y. c*b^(a+y)) sums (c*b^(a)/(1-b))\"\nproof -\n  let ?s = \"1/(1-b)\"\n  assume \"norm b < 1\"\n  then have \"(\\<lambda>y. b^y) sums ?s\" using geometric_sums by blast\n  (* Convert the series to a limit so we can apply multiplication lemmas about limits *)\n  then have sum_unfold: \"(\\<lambda>n. \\<Sum>i<n. (\\<lambda>y. b^y) i) \\<longlonglongrightarrow> ?s\" by (simp add: sums_def)\n  have \"(\\<lambda>_. c*w^a) \\<longlonglongrightarrow> c*w^a\" by simp\n  from this sum_unfold have \n    \"(\\<lambda>n. c*b^a * (\\<Sum>i<n. (\\<lambda>y. b^y) i)) \\<longlonglongrightarrow> c*b^a * ?s\"\n    using tendsto_mult by blast\n  moreover have \"c*b^a * (\\<Sum>i<(n::nat). (\\<lambda>y. b^y) i) \n      = (\\<Sum>i<n. (\\<lambda>y. c*b^a * b^y) i)\" for n\n    using sum_distrib_left by blast\n  moreover have \"(\\<Sum>i<n. (\\<lambda>y. c*b^a * b^y) i) = (\\<Sum>i<n. (\\<lambda>y. c*b^(a+y)) i)\"\n    for n by (metis ab_semigroup_mult_class.mult_ac(1) power_add)\n  ultimately have \"(\\<lambda>n. (\\<Sum>i<n. (\\<lambda>y. c*b^(a+y)) i)) \\<longlonglongrightarrow> c*b^a * ?s\" by simp\n  then have \"(\\<lambda>y. c*b^(a+y)) sums (c*b^a * ?s)\" by (simp add: sums_def)\n  then show ?thesis by simp\nqed\n\n(*\n  The geometric sum transformation lemma holds for b=w, because w is in (0, 1).\n*)\ncorollary geometric_w_sums_transformation: \"(\\<lambda>y. c*w^(a+y)) sums (c*w^(a)/(1-w))\"\n  using w_range geometric_sums_transformation[where b=w] by simp\n\n(*\n  Variant of the comparison test: if a sequence f is summable and dominates another non-negative\n    sequence g, then g is summable as well.\n*)\nlemma summable_nonneg_comparison_test:\n  assumes f_summable: \"summable (f::nat \\<Rightarrow> real)\"\n      and f_dom_g: \"\\<And>i. g i \\<le> f i\"\n      and nonneg: \"\\<And>i. 0 \\<le> g i\"\nshows \"summable g\"\nproof -\n  have \"\\<forall>n. norm (g n) \\<le> f n\" by (simp add: f_dom_g nonneg)\n  then show ?thesis using summable_comparison_test f_summable by blast\nqed\n\n(*\n  Changing one term of a summable series by d changes the sum by d.\n*)\nlemma series_one_term_different:\n  assumes f_g_diff: \"(g :: nat \\<Rightarrow> real) (k::nat) = f k + d\"\n      and f_g_eq: \"\\<And>i. i \\<noteq> k \\<Longrightarrow> f i = g i\"\n      and \"summable f\"\n    shows \"suminf g = suminf f + d\"\nproof -\n  (* Decompose series into initial part until the different element, and equal tail part *)\n  have f_initsum:  \"(\\<lambda>i. f (i + (k+1))) sums s \\<longleftrightarrow> f sums (s + (\\<Sum>i<k+1. f i))\" \n    for s using sums_iff_shift by blast\n  have g_initsum:  \"(\\<lambda>i. g (i + (k+1))) sums s \\<longleftrightarrow> g sums (s + (\\<Sum>i<k+1. g i))\" \n    for s using sums_iff_shift by blast\n  (* The the initial parts differ by d... *)\n  have init_diff: \"(\\<Sum>i<k+1. g i) = (\\<Sum>i<k+1. f i) + d\"\n  proof -\n    have \"(\\<Sum>i<k+1. g i) = (\\<Sum>i<k. g i) + g k\" by simp\n    moreover have \"(\\<Sum>i<k+1. f i) = (\\<Sum>i<k. f i) + f k\" by simp\n    moreover have \"(\\<Sum>i<k. g i) = (\\<Sum>i<k. f i)\" using f_g_eq by simp\n    ultimately show ?thesis using f_g_diff by simp\n  qed\n  (* ...and the tails are equal *)\n  have tails_eq: \"(\\<lambda>i. f (i + (k+1))) = (\\<lambda>i. g (i + (k+1)))\" using f_g_eq by simp\n  have \"f sums s \\<Longrightarrow> g sums (s + d)\" for s\n  proof -\n    assume \"f sums s\"\n    then have \"(\\<lambda>i. f (i + (k+1))) sums (s - (\\<Sum>i<k+1. f i))\"\n      using f_initsum by auto\n    then have \"(\\<lambda>i. f (i + (k+1))) sums (s - (\\<Sum>i<k+1. f i))\"\n      using tails_eq by simp\n    then have \"(\\<lambda>i. f (i + (k+1))) sums (s - ((\\<Sum>i<k+1. g i) - d))\"\n      using init_diff by simp\n    then show \"g sums (s + d)\" using g_initsum tails_eq by simp\n  qed\n  then show ?thesis using \\<open>summable f\\<close> sums_iff by blast\nqed\n\nsubsection \\<open>Summability of inner/outer series defining `power_sum`\\<close>\n\n(*\n  Value of inner series for x = 0, given that all coins are present.\n*)\nlemma point_pow_all_coins_row_sum_x_eq_0:\n  \"x = 0 \\<Longrightarrow> (point_pow all_coins x) sums (1/(1-w))\"\nproof -\n  assume \"x = 0\"\n  (* Since x = 0, point_pow only counts the x = 0 column *)\n  then have \"point_pow all_coins x y = w^y\" for y by (simp add: all_coins_def)\n  moreover have \"(\\<lambda>y. w^y) sums (1/(1-w))\" using geometric_sums w_range by force\n  ultimately show ?thesis using sums_cong by blast\nqed\n\n(*\n  Value of inner series for x > 0, given that all coins are present.\n*)\nlemma point_pow_all_coins_row_sum_x_ge_0:\n  \"x > 0 \\<Longrightarrow> (point_pow all_coins x) sums (2*w^x/(1-w))\"\nproof -\n  assume \"x > 0\"\n  (* Since x > 0, point_pow only counts the x and the -x columns (hence the factor of 2) *)\n  then have \"point_pow all_coins x y = 2 * w^(x+y)\" for y by (simp add: all_coins_def)\n  moreover have \"(\\<lambda>y. 2 * w^(x+y)) sums (2*w^x/(1-w))\" \n    using geometric_w_sums_transformation by fastforce\n  ultimately show ?thesis by presburger\nqed\n\n(*\n  The inner series converges if all coins are present.\n*)\nlemma point_pow_all_coins_row_summable: \"summable (point_pow all_coins x)\"\nproof (cases \"x = 0\")\n  case True \n  then show ?thesis using point_pow_all_coins_row_sum_x_eq_0 using summable_def by blast\nnext\n  case False\n  then show ?thesis using point_pow_all_coins_row_sum_x_ge_0 using summable_def by blast\nqed\n\n(*\n  The inner series converges for any coin configuration.\n*)\nlemma point_pow_summable: \"summable (point_pow coins x)\" \nproof -\n  have \"summable (point_pow all_coins x)\" by (rule point_pow_all_coins_row_summable)\n  (* Use that point_pow for all coins dominates point_pow for a subset of coins *)\n  moreover have \"point_pow coins x y \\<le> point_pow all_coins x y\" for y\n    using all_coins_def w_range by auto\n  ultimately show ?thesis using summable_nonneg_comparison_test w_range by fastforce\nqed\n\n(*\n  The outer series converges for any coin configuration.\n*)\nlemma power_sum_summable: \"summable (\\<lambda>x. suminf (point_pow coins x))\"\nproof -\n  let ?f = \"\\<lambda>x. suminf (point_pow all_coins x)\"\n  (* Both the x = 0 and x > 0 case can be upper-bounded by 2*1/(1-w).\n     For convenience, we upper-bound the factor 2*1/(1-w) by 8 *)\n  have \"1/(1-w) < 4\" using w_bound w_range by (simp add: mult_imp_div_pos_less)\n  then have \"1/(1-w) \\<le> 4\" by simp\n  have \"?f x \\<le> 8 * w^x\" for x proof (cases \"x = 0\")\n    case xeq0: True\n    then have \"?f x = 1/(1-w)\" using point_pow_all_coins_row_sum_x_eq_0 sums_unique by force\n    moreover have \"1/(1-w) \\<le> 2/(1-w) * w^0\"\n      by (metis diff_ge_0_iff_ge divide_right_mono less_le mult.commute mult_cancel_right2 \n          one_le_numeral power_0 w_range)\n    ultimately show ?thesis using xeq0 \\<open>1/(1-w) < 4\\<close> by fastforce\n  next\n    case False\n    then have \"?f x = 2*w^x/(1-w)\"\n      by (metis bot_nat_0.not_eq_extremum point_pow_all_coins_row_sum_x_ge_0 sums_unique)\n    moreover have \"1/(1-w) * w^x < 4 * w^x\" using \\<open>1/(1-w) < 4\\<close> w_range\n      by (meson mult_less_cancel_right_disj zero_less_power)\n    ultimately show ?thesis by force\n  qed\n  (* This upper bound is now easily shown to be summable. *)\n  moreover have \"(\\<lambda>x. 8*w^x) sums (8/(1-w))\"\n    using geometric_w_sums_transformation[where a=0] by simp\n  then have \"summable (\\<lambda>x. 8*w^x)\" using sums_summable by blast\n  moreover have \"0 \\<le> suminf (point_pow all_coins x)\" for x\n    using point_pow_summable suminf_nonneg w_range by force\n  (* The original series (with all coins) is dominated by the upper bound, i.e. also summable. *)\n  ultimately have \"summable ?f\" using summable_nonneg_comparison_test by presburger\n\n  (* Furthermore, the series with all coins dominates the one with just a subset of coins, ...*)\n  have \"point_pow coins x y \\<le> point_pow all_coins x y\" for x y using all_coins_def w_range by auto\n  then have \"suminf (point_pow coins x) \\<le> suminf (point_pow all_coins x)\" for x \n    by (meson point_pow_summable suminf_le)\n  moreover have \"0 \\<le> suminf (point_pow coins x)\" for x\n    using point_pow_summable suminf_nonneg w_range by force\n\n  (* ...therefore this is summable as well. *)\n  ultimately show ?thesis\n    using \\<open>summable ?f\\<close> summable_nonneg_comparison_test by presburger\nqed\n\n\nsubsection \\<open>Computing `power_sum` for finite coin configurations\\<close>\n\n(*\n  Adding a single coin (x, y) to a coin configuration increases its `power_sum` by w^(|x| + y)\n*)\nlemma power_sum_union_singleton:\n  \"(x,y) \\<notin> F \\<Longrightarrow> power_sum (F \\<union> {(x,y)}) = power_sum F + w^(nat (abs x) + y)\"\nproof -\n  assume notinF: \"(x,y) \\<notin> F\"\n  let ?Fnew = \"insert (x,y) F\"\n  (* ?x is the `nat` absolute value of x that is used as index in the series *)\n  let ?x = \"nat (abs x)\"\n\n  (* \n    We have some fixed coin (x, y) and show that the double series that defines `power_sum`\n      differs by w^(?x + y).\n  \n    Proceed in four steps:\n    - for all x' \\<noteq> ?x, the value of the inner series remains equal\n    - for all y' \\<noteq> y and all x', the value of point_pow remains equal\n    - for ?x and y, the value of point_pow differs by w^(?x + y)\n    - for ?x, the value of the inner series differs by w^(?x + y)\n\n    Then, the outer series only differs by the single term for ?x, and `series_one_term_different`\n      can be applied.\n  *)\n\n  have otherx: \"x' \\<noteq> ?x \\<Longrightarrow> suminf (point_pow ?Fnew x') = suminf (point_pow F x')\" for x'\n  proof -\n    assume xneq: \"x' \\<noteq> ?x\"\n    from xneq have poseq: \"(x', y) \\<in> F \\<longleftrightarrow> (x', y) \\<in> ?Fnew\" by fastforce\n    from xneq have negeq: \"(-x', y) \\<in> F \\<longleftrightarrow> (-x', y) \\<in> ?Fnew\" by fastforce\n    from poseq negeq show ?thesis by (smt (verit, ccfv_threshold) Pair_inject case_prod_conv\n          insert_iff point_pow.elims suminf_cong notinF)\n  qed\n\n  have othery: \"y' \\<noteq> y \\<Longrightarrow> point_pow ?Fnew ?x y' = point_pow F ?x y'\" for y'\n  proof -\n    assume yneq: \"y' \\<noteq> y\"\n    from yneq have yinFeq: \"(x', y') \\<in> F \\<longleftrightarrow> (x', y') \\<in> ?Fnew\" for x'  by simp\n    from this show ?thesis by force\n  qed\n\n  have samexy: \"point_pow ?Fnew ?x y = point_pow F ?x y + w^(?x+y)\"\n  proof (cases \"(x, y) \\<in> F\")\n    case True\n    then show ?thesis using notinF by fastforce\n  next\n    case False\n    then show ?thesis proof (cases \"(-x, y) \\<in> F\")\n      case True\n      then show ?thesis\n        by (smt (verit, ccfv_SIG) notinF insertCI nat_0_le point_pow.elims zero_less_nat_eq)\n    next\n      case False\n      then show ?thesis by (smt (verit, del_insts) notinF insert_iff \n            int_nat_eq point_pow.elims prod.inject zero_less_nat_eq)\n    qed\n  qed\n\n  have samex: \"suminf (point_pow ?Fnew ?x) = suminf (point_pow F ?x) + w^(?x+y)\"\n    using series_one_term_different samexy othery point_pow_summable by presburger\n\n  have \"suminf (\\<lambda>x. suminf (point_pow ?Fnew x)) = suminf (\\<lambda>x. suminf (point_pow F x)) + w^(?x+y)\"\n    using series_one_term_different samex otherx power_sum_summable by presburger\n  then show ?thesis by simp\nqed\n\n(*\n  Removing a single coin (x, y) from a coin configuration decreases its `power_sum` by w^(|x| + y)\n*)\ncorollary power_sum_minus_singleton:\n  \"(x,y) \\<in> F \\<Longrightarrow> power_sum (F - {(x,y)}) = power_sum F - w^(nat (abs x) + y)\"\n  using mk_disjoint_insert power_sum_union_singleton by fastforce\n\n(*\n  For a finite coin configuration, we can compute the `power_sum` using the `sum` function.\n*)\nlemma finite_power_sum:\n  assumes finite: \"finite coins\"\n  shows \"power_sum coins = sum (\\<lambda>(x,y). w ^ (nat (abs x) + y)) coins\"\nusing finite proof (induction coins)\n  case empty\n  have \"point_pow {} x y = 0\" for x y by simp\n  then have \"suminf (point_pow {} x) = 0\" for x by (metis sums_0 sums_unique)\n  then show ?case by simp\nnext\n  case (insert t F)\n  then obtain x y where xy: \"t = (x, y)\" by (meson surj_pair)\n  have 1: \"power_sum (insert t F) = power_sum F + w^(nat (abs x) + y)\"\n    using insert.hyps(2) power_sum_union_singleton xy by fastforce\n  have 2: \"sum (\\<lambda>(x,y). w ^ (nat (abs x) + y)) (insert t F)\n    = sum (\\<lambda>(x,y). w ^ (nat (abs x) + y)) F + w^(nat (abs x) + y)\" using insert xy by force\n  from 1 2 insert show ?case by simp\nqed\n\nsubsection \\<open>Monotonicity of `power_sum` in the coin configuration\\<close>\n\n(*\n  Lemmas showing that `power_sum` weakly increases with a  \\<subseteq>-increasing coin configuration.\n*)\nlemma point_pow_subset_leq: \"A \\<subseteq> B \\<Longrightarrow> point_pow A x y \\<le> point_pow B x y\"\n  using w_range by auto\n\nlemma powersum_inner_subset_leq: \"A \\<subseteq> B \\<Longrightarrow> suminf (point_pow A x) \\<le> suminf (point_pow B x)\"\n  by (meson point_pow_subset_leq point_pow_summable suminf_le)\n\nlemma powersum_subset_leq:\n  \"A \\<subseteq> B \\<Longrightarrow> power_sum A \\<le> power_sum B\"\nproof -\n  assume \"A \\<subseteq> B\"\n  then have \"\\<lbrakk>(\\<lambda>x. suminf (point_pow A x)) sums s; (\\<lambda>x. suminf (point_pow B x)) sums t\\<rbrakk>\n    \\<Longrightarrow> s \\<le> t\" for s t by (metis (full_types) sums_le powersum_inner_subset_leq)\n  then show ?thesis by (simp add: power_sum_summable summable_sums)\nqed\n\n(*\n  Lemmas showing that `power_sum` strictly increases with a \\<subset>-increasing coin configuration.\n*)\nlemma point_pow_subset_less: \"A \\<subseteq> B \\<and> (x,y) \\<in> B - A \n    \\<Longrightarrow> point_pow A (nat (abs x)) y < point_pow B (nat (abs x)) y\"\n  by (smt (verit, best) DiffD2 Diff_partition Un_iff nat_eq_iff point_pow.elims w_range\n        zero_less_nat_eq zero_less_power)\n\nlemma powersum_subset_less:\n  \"A \\<subset> B \\<Longrightarrow> power_sum A < power_sum B\"\nproof -\n  assume subset: \"A \\<subset> B\"\n  then obtain x y where xy: \"(x,y) \\<in> B - A\" by auto\n  let ?x = \"nat (abs x)\"\n\n  (*\n    Proof strategy: Show that the differences of the series is > 0. We start from the innermost\n      terms in the series and work our way outward. Along the way we need the `suminf_diff` lemma\n      and some summability statements.\n  *)\n\n  (* Show that the series of differences of inner series terms for ?x sums to something > 0  *)\n  have \"point_pow B ?x y - point_pow A ?x y > 0\" using xy point_pow_subset_less\n    by (simp add: order_less_imp_le subset)\n  moreover have \"summable (\\<lambda>y. point_pow B ?x y - point_pow A ?x y)\"\n    using point_pow_summable summable_diff by blast\n  ultimately have \"suminf (\\<lambda>y. point_pow B ?x y - point_pow A ?x y) > 0\"\n    by (smt (verit) order_less_imp_le point_pow_subset_leq subset suminf_pos_iff)\n\n  (* Pull this apart to show that the difference of the inner series for ?x is > 0 *)\n  moreover have \"suminf (\\<lambda>y. point_pow B ?x y - point_pow A ?x y)\n    = suminf (point_pow B ?x) - suminf (point_pow A ?x)\" \n    using suminf_diff[of \"point_pow B ?x\" \"point_pow A ?x\"] point_pow_summable by simp\n  ultimately have \"suminf (point_pow B ?x) - suminf (point_pow A ?x) > 0\" by simp\n\n  (* Using that the inner series difference for other x is \\<ge> 0 ...*) \n  moreover have \"suminf (point_pow B x) - suminf (point_pow A x) \\<ge> 0\" for x\n    by (simp add: order_less_imp_le powersum_inner_subset_leq subset)\n  moreover have \"summable (\\<lambda>x. suminf (point_pow B x) - suminf (point_pow A x))\"\n    by (simp add: power_sum_summable summable_diff)\n  (* ...show that the series of differences of outer series terms is > 0 *)\n  ultimately have \"suminf (\\<lambda>x. suminf (point_pow B x) - suminf (point_pow A x)) > 0\" \n    using suminf_pos_iff[where f=\"(\\<lambda>x. suminf (point_pow B x) - suminf (point_pow A x))\"] by blast\n\n  (* Pull this apart to get that the difference of the outer series is > 0 *)\n  then have \"suminf (\\<lambda>x. suminf (point_pow B x)) - suminf (\\<lambda>x. suminf (point_pow A x)) > 0\" \n    using suminf_diff[of \"(\\<lambda>x. suminf (point_pow B x))\" \"(\\<lambda>x. suminf (point_pow A x))\"]\n          power_sum_summable by presburger\n  then show ?thesis by simp\nqed\n\n\nsection \\<open>Power sums for game configurations\\<close>\n\ntext \\<open>This section shows some facts about `power_sum`s of coin configurations relevant to the game:\n  - the goal field has a `power_sum` value of 1,\n  - the maximal initial configuration has a `power_sum` value of 1,\n  - initial configurations have a `power_sum` value of at most 1.\\<close>\n\nsubsection \\<open>Power sum of goal field\\<close>\n\n(*\n  The set containing only the goal field {(0,0)} has a `power_sum` value of 1\n*)\ncorollary goal_field_value_1: \"power_sum {(0,0)} = 1\"\n  using finite_power_sum by simp\n\n\nsubsection \\<open>Power sums of initial coin configurations\\<close>\n\n(*\n  The `power_sum` of the maximal initial coin configuration is 1.\n  (This is the first crucial property of the number w.)\n*)\ntheorem max_initial_coins_eq_one: \"power_sum max_initial_coins = 1\"\nproof -\n  (* Compute the inner series for the x = 0 column *)\n  have x_eq_0: \"x = 0 \\<Longrightarrow> suminf (point_pow max_initial_coins x) = w^3\" for x\n  proof -\n    assume \"x = 0\"\n    have point_pow_unfold: \"point_pow max_initial_coins x y = (if y \\<ge> 5 then w^y else 0)\" for y\n      by (simp add: \\<open>x = 0\\<close> max_initial_coins_def)\n    let ?f = \"(\\<lambda>y. (if y \\<ge> 5 then w^y else 0))\"\n\n    (* Drop the initial (zero) segment of the series, by shifting the index by 5 *)\n    have 1: \"(\\<lambda>y. w^(y+5)) sums s \\<Longrightarrow> ?f sums s\" for s\n    proof -\n      assume \"(\\<lambda>y. w^(y+5)) sums s\"\n      then have \"(\\<lambda>y. ?f (y + 5)) sums s\" using le_add2 by presburger\n      then have \"?f sums (s + (\\<Sum>i<5. ?f i))\" using sums_iff_shift by blast\n      then have \"?f sums s\" by simp\n      then show ?thesis by simp\n    qed\n\n    (* Compute the geometric sum and do some work to show w^5/(1-w) = w^3 *)\n    have \"(\\<lambda>y. w^(5+y)) sums (w^5/(1-w))\" using geometric_w_sums_transformation[where c=1] by simp\n    then have \"(\\<lambda>y. w^(5+y)) sums (w^5/w^2)\" using w_squared by auto\n    moreover have \"(w^5/w^2) = w^(Suc(Suc(Suc(Suc(Suc 0)))))/w^(Suc(Suc 0))\"\n      by (simp add: numeral_2_eq_2 numeral_Bit1)\n    then have \"w^5/w^2 = w^3\" by (simp add: numeral_3_eq_3)\n    ultimately have \"(\\<lambda>y. w^(y+5)) sums w^3\" by (metis (no_types, lifting) add.commute sums_cong)\n    from this 1 have \"?f sums w^3\" by simp\n    from this show ?thesis by (smt (verit, best) point_pow_unfold suminf_cong sums_unique)\n  qed\n\n  (* Compute the inner series for the x > 0 columns *)\n  have x_ge_0: \"x > 0 \\<Longrightarrow> suminf (point_pow max_initial_coins x) = 2*w^(x+3)\" for x\n  proof -\n    assume \"x > 0\"\n    have point_pow_unfold: \"point_pow max_initial_coins x y = (if y \\<ge> 5 then 2*w^(x+y) else 0)\" \n      for y by (simp add: \\<open>x > 0\\<close> max_initial_coins_def)\n    let ?f = \"(\\<lambda>y. (if y \\<ge> 5 then 2*w^(x+y) else 0))\"\n\n    (* Drop the initial (zero) segment of the series, by shifting the index by 5 *)\n    have 1: \"(\\<lambda>y. 2*w^(x+y+5)) sums s \\<Longrightarrow> ?f sums s\" for s\n    proof -\n      assume \"(\\<lambda>y. 2*w^(x+y+5)) sums s\"\n      then have \"(\\<lambda>y. ?f (y + 5)) sums s\" using le_add2\n        by (smt (verit, ccfv_SIG) group_cancel.add1 sums_cong)\n      then have \"?f sums (s + (\\<Sum>i<5. ?f i))\" using sums_iff_shift by blast\n      then have \"?f sums s\" by simp\n      then show ?thesis by simp\n    qed\n\n    (* Compute the geometric sum and do some work to show 2*w^(x+5)/(1-w) = 2*w^(x+3) *)\n    have \"(\\<lambda>y. 2*w^(x+5+y)) sums (2*w^(x+5)/(1-w))\" using geometric_w_sums_transformation by simp\n    then have 2: \"(\\<lambda>y. 2*w^(x+y+5)) sums (2*w^(x+5)/(1-w))\"\n      by (smt (verit) Groups.add_ac(2) group_cancel.add1 sums_cong)\n\n    have \"2 \\<le> x+5\" by simp\n    then have \"2*w^(x+5)/w^2 = 2*w^(x+5-2)\" using power_diff\n      by (smt (verit, ccfv_threshold) comm_semiring_class.distrib divide_eq_0_iff\n          field_class.field_divide_inverse real_sqrt_eq_1_iff w_def)\n    moreover have \"x+5-2 = x+3\" by simp\n    ultimately have w_pow_diff: \"2*w^(x+5)/w^2 = 2*w^(x+3)\" by simp\n\n\n    from 2 have \"(\\<lambda>y. 2*w^(x+y+5)) sums (2*w^(x+5)/w^2)\" using w_squared by auto\n    from this w_pow_diff have \"(\\<lambda>y. 2*w^(x+y+5)) sums (2*w^(x+3))\" by metis\n    from this 1 have \"?f sums (2*w^(x+3))\" by blast\n    from this show ?thesis\n      by (smt (verit, best) point_pow_unfold suminf_cong sums_unique)\n  qed\n\n  (* Summary of above results: inner series values for x = 0 / x > 0 *)\n  from x_eq_0 x_ge_0 have x_inner_sum:\n    \"suminf (point_pow max_initial_coins x) = (if x = 0 then w^3 else 2*w^(x+3))\" for x by simp\n\n  (* From this, compute the outer series *)\n  let ?f = \"\\<lambda>x. if x = 0 then w^3 else 2*w^(x+3)\"\n\n  (* Split the series in the first term (i.e. the x = 0 inner series term) and the tail series\n    (i.e. the x > 0 inner series terms), since the latter all have the same form. *)\n  have \"(\\<lambda>x. ?f (x+1)) sums s \\<Longrightarrow> ?f sums (s + (\\<Sum>x<1. ?f x))\" for s\n    using sums_iff_shift by fastforce\n  then have sum_split: \"(\\<lambda>x. ?f (x+1)) sums s \\<Longrightarrow> ?f sums (s + ?f 0)\" for s by simp\n\n  (* Compute the tail of the outer series *)\n  have \"(\\<lambda>x. ?f (x+1)) sums (2*w^2)\"\n  proof -\n    (* Compute the geometric sum *)\n    have \"?f (x+1) = 2*w^(x+1+3)\" for x by simp\n    then have 1: \"?f (x+1) = 2*w^(4+x)\" for x by auto\n    have 2: \"(\\<lambda>x. 2*w^(4+x)) sums (2*w^4/(1-w))\"\n      using geometric_w_sums_transformation by simp\n\n    (* Simplify it to 2*w^2 *)\n    from 2 have \"(\\<lambda>x. 2*w^(4+x)) sums (2*w^4/w^2)\" using w_squared by simp\n    moreover have \"2*w^4/w^2 = 2*w^(Suc(Suc(Suc(Suc 0))))/w^Suc(Suc 0)\"\n      by (simp add: numeral_2_eq_2 power4_eq_xxxx)\n    then have \"2*w^4/w^2 = 2*w^2\" by (simp add: numeral_2_eq_2)\n    ultimately have 3: \"(\\<lambda>x. 2*w^(4+x)) sums (2*w^2)\" by simp\n    from 1 3 show ?thesis by simp\n  qed\n  (* From the first term and the tail, compute the outer series to be 2*w^2 + w^3 *)\n  then have f_sums: \"?f sums (2*w^2 + w^3)\" using sum_split by simp\n\n  (* Now show that 2*w^2 + w^3 = 1 *, which concludes the proof *)\n  have \"2*w^2 + w^3 = w^2 + w^(2+1) + 1 - w\" using w_squared by force\n  moreover have \"w^2 + w^(2+1) + 1 - w = w - w + 1\" using w_recurrence\n    by (metis add.commute diff_diff_eq2 diff_eq_eq one_add_one power_one_right)\n  ultimately have two_w2_plus_w3: \"2*w^2 + w^3 = 1\" by auto\n\n  from two_w2_plus_w3 f_sums have \"suminf ?f = 1\" using sums_unique by force \n  moreover have \"power_sum max_initial_coins = suminf ?f\" using x_inner_sum by simp\n  ultimately show ?thesis by simp\nqed\n\n(*\n  The maximal initial coin configuration is an infinite set.\n*)\nlemma max_initial_coins_infinite: \"infinite max_initial_coins\"\nproof (rule ccontr)\n  (* Project the set of tuples to a set of naturals *)\n  let ?proj = \"((\\<lambda>(x, _). x) ` max_initial_coins)\"\n\n  assume \"\\<not>infinite max_initial_coins\"\n  (* If the set of tuples is finite, so is the projection *)\n  then have \"finite max_initial_coins\" by simp\n  then have \"finite ?proj\" by auto\n\n  (* ?proj is non-empty and finite, so it has a maximal element k *)\n  moreover have \"?proj \\<noteq> {}\" \n  (* interesting shortcut sledgehammer found here: if max_initial_coins was empty, it would have\n     `power_sum` of 0, but it has `power_sum` of 1 *)\n    using finite_power_sum max_initial_coins_eq_one by force\n  ultimately obtain k where max_k: \"k \\<in> ?proj \\<and> (\\<forall>j \\<in> ?proj. k \\<le> j \\<longrightarrow> k = j)\"\n    using finite_has_maximal by metis\n\n  (* But (k+1, 5) is in max_initial_coins, hence k+1 is in the projection: contradiction *)\n  have \"(k+1, 5) \\<in> max_initial_coins\" using max_initial_coins_def by auto\n  then have \"k+1 \\<in> ?proj\" by auto\n  then show \"False\" using max_k by auto\nqed\n\n(*\n  Any finite initial coin configuration has a `power_sum` less than 1.\n*)\nlemma initial_finite_coins_less_one:\n  assumes initial: \"initial_coins coins\"\n      and finite:\"finite coins\"\nshows \"power_sum coins < 1\"\nproof -\n  have \"coins \\<subseteq> max_initial_coins\" by (simp add: initial initial_coins_subset)\n  (* Since `coins` is finite but `max_initial_coins` is infinite, `coins` is a proper subset *)\n  moreover have \"coins \\<noteq> max_initial_coins\" using finite max_initial_coins_infinite by blast\n  ultimately have \"coins \\<subset> max_initial_coins\" by blast\n  then have \"power_sum coins < power_sum max_initial_coins\" using powersum_subset_less by auto\n  then show ?thesis using max_initial_coins_eq_one by simp\nqed\n\n(* Any initial coin configuration has a `power_sum` of at most 1. *)\nlemma initial_coins_leq_one:\n  assumes \"initial_coins coins\"\n  shows \"power_sum coins \\<le> 1\"\n  by (metis assms initial_coins_subset max_initial_coins_eq_one powersum_subset_leq)\n\nsection \\<open>Power sums and jumps\\<close>\n\n(*\n  A `jump` transition from one coin configuration to another weakly decreases the `power_sum`.\n  (This is the second crucial property of the number w.)\n*)\ntheorem jump_decreases_power_sum: \"jump A B \\<Longrightarrow> power_sum B \\<le> power_sum A\"\n(*\n  We prove this for the four directions we can jump to:\n  The \"left\" and \"right\" directions are complicated because x coordinates are integers:\n    we need extra cases depending on if we're on the negative side, positive side, or both\n  The \"up\" direction is easier because y coordinates are natural numbers; we just have to take\n    care when we're close to zero.\n  The \"down\" direction is easiest because we don't even have to be careful close to zero.\n*)\nproof (induction rule: jump.induct)\n  case (left x y A B)\n  let ?x = \"nat (abs x)\"\n  (* Show that the two power sums differ by the terms of the three coin positions that changed *)\n  let ?full_diff = \"w^(y + nat (abs (x-2))) - w^(y + nat (abs (x-1))) - w^(y + nat (abs x))\"\n  have power_sum_B: \"power_sum (A - {(x, y), (x - 1, y)} \\<union> {(x - 2, y)})\n      = power_sum A + ?full_diff\"\n    using \\<open>(x, y) \\<in> A\\<close> \\<open>(x-1, y) \\<in> A\\<close> \\<open>(x-2, y) \\<notin> A\\<close> power_sum_minus_singleton \n      power_sum_union_singleton\n    by (smt (verit, del_insts) Diff_iff Diff_insert2 add.commute insertE insert_Diff prod.inject)\n\n  (* Factor out w^y to simplify the remaining argument: the other factor is now called ?diff *)\n  then have \"?full_diff = w^y*w^(nat (abs (x-2))) - w^y*w^(nat (abs (x-1))) - w^y*w^(nat (abs x))\"\n    by (metis power_add)\n  then have full_diff_diff: \n    \"?full_diff = w^y * (w^(nat (abs (x-2))) - w^(nat (abs (x-1))) - w^(nat (abs x)))\" \n    (is \"?full_diff = w^y * ?diff\") by (simp add: right_diff_distrib)\n\n  (* Show that ?diff is non-positive, i.e. the power sum weakly decreases, by three cases *)\n  have \"?diff  \\<le> 0\"\n  proof (cases \"x \\<le> 0\")\n    (* If x \\<le> 0, a left jump goes in the direction of increasing exponents: \n      the power sum strictly decreases *)\n    case x_nonpos: True\n    then have \"?diff = w^(?x+2) - w^(?x+1) - w^(?x)\"\n      by (smt (verit, ccfv_threshold) nat_1_add_1 nat_add_distrib nat_numeral numeral_eq_one_iff)\n    then show ?thesis\n      by (smt (verit, del_insts) w_range w_recurrence zero_less_power)\n  next\n    case x_pos: False\n    then show ?thesis proof (cases \"x \\<ge> 2\")\n      case x_geq_2: True\n      (* If x \\<ge> 2, a left jump goes in the direction of decreasing exponents: \n        the power sum is unchanged because of the w recurrence relation *)\n      have \"?diff = w^(?x-2) - w^(?x-1) - w^(?x)\" proof -\n        have \"nat (abs (x-2)) = ?x - 2\" using x_geq_2 by (simp add: nat_diff_distrib')\n        moreover have \"nat (abs (x-1)) = ?x - 1\" using x_geq_2 by (simp add: nat_diff_distrib')\n        ultimately show ?thesis by presburger\n      qed\n      then have \"?diff = w^(?x-2) - w^(?x-2+1) - w^(?x-2+2)\"\n        by (smt (verit, del_insts) Nat.add_diff_assoc2 Nat.diff_diff_right One_nat_def\n            cancel_comm_monoid_add_class.diff_cancel diff_is_0_eq' diff_zero le_add2 linorder_linear\n            nat_0_iff nat_1_add_1 nat_2 nat_diff_distrib plus_1_eq_Suc x_geq_2)\n      then show ?thesis by (smt (verit, ccfv_SIG) w_recurrence)\n    next\n      case x_eq_1: False\n      (* If x = 1, a left jump crosses the x = 0 column and ?diff = w - 1 - w < 0 *)\n      then have \"x = 1\" using x_pos by auto\n      then show ?thesis by auto\n    qed\n  qed\n  moreover have \"w^y > 0\" by (simp add: w_range)\n  ultimately have \"?full_diff \\<le> 0\" using full_diff_diff zero_less_mult_iff by smt\n  then show ?case using left.hyps(4) by (smt (verit, best) power_sum_B)\nnext\n  (* \n    Luckily, the \"right\" part is more or less the \"left\" part with signs changed\n  *)\n  case (right x y A B)\n  let ?x = \"nat (abs x)\"\n  (* Show that the two power sums differ by the terms of the three coin positions that changed *)\n  let ?full_diff = \"w^(y + nat (abs (x+2))) - w^(y + nat (abs (x+1))) - w^(y + nat (abs x))\"\n  have power_sum_B: \"power_sum (A - {(x, y), (x + 1, y)} \\<union> {(x + 2, y)})\n      = power_sum A + ?full_diff\"\n    using \\<open>(x, y) \\<in> A\\<close> \\<open>(x+1, y) \\<in> A\\<close> \\<open>(x+2, y) \\<notin> A\\<close> power_sum_minus_singleton\n      power_sum_union_singleton\n    by (smt (z3) Diff_iff Diff_insert2 add.commute insertE insert_Diff prod.inject)\n\n  (* Factor out w^y to simplify the remaining argument: the other factor is now called ?diff *)\n  then have \"?full_diff = w^y*w^(nat (abs (x+2))) - w^y*w^(nat (abs (x+1))) - w^y*w^(nat (abs x))\" \n    by (metis power_add)\n  then have full_diff_diff:\n      \"?full_diff = w^y * (w^(nat (abs (x+2))) - w^(nat (abs (x+1))) - w^(nat (abs x)))\" \n    (is \"?full_diff = w^y * ?diff\") by (simp add: right_diff_distrib)\n\n  (* Show that ?diff is non-positive, i.e. the power sum weakly decreases, by three cases *)\n  have \"?diff  \\<le> 0\"\n  proof (cases \"x \\<ge> 0\")\n    (* If x \\<ge> 0, a right jump goes in the direction of increasing exponents: \n      the power sum strictly decreases *)\n    case x_nonneg: True\n    then have \"?diff = w^(?x+2) - w^(?x+1) - w^(?x)\"\n      by (smt (verit, ccfv_threshold) nat_1_add_1 nat_add_distrib nat_numeral numeral_eq_one_iff)\n    then show ?thesis\n      by (smt (verit, del_insts) w_range w_recurrence zero_less_power)\n  next\n    case x_neg: False\n    then show ?thesis proof (cases \"x \\<le> -2\")\n      case x_leq_minus2: True\n      (* If x \\<le> -2, a right jump goes in the direction of decreasing exponents: \n        the power sum is unchanged because of the w recurrence relation *)\n      have \"?diff = w^(?x-2) - w^(?x-1) - w^(?x)\" proof -\n        have \"nat (abs (x+2)) = ?x - 2\" using x_leq_minus2 by (simp add: nat_diff_distrib')\n        moreover have \"nat (abs (x+1)) = ?x - 1\" using x_leq_minus2 by (simp add: nat_diff_distrib')\n        ultimately show ?thesis by presburger\n      qed\n      then have \"?diff = w^(?x-2) - w^(?x-2+1) - w^(?x-2+2)\"\n        by (smt (verit, del_insts) Nat.add_diff_assoc2 Nat.diff_diff_right One_nat_def\n            cancel_comm_monoid_add_class.diff_cancel diff_is_0_eq' diff_zero le_add2 linorder_linear\n            nat_0_iff nat_1_add_1 nat_2 nat_diff_distrib plus_1_eq_Suc x_leq_minus2)\n      then show ?thesis by (smt (verit, ccfv_SIG) w_recurrence)\n    next\n      case x_eq_minus_1: False\n      (* If x = -1, a right jump crosses the x = 0 column and ?diff = w - 1 - w < 0 *)   \n      then have \"x = -1\" using x_neg by auto\n      then show ?thesis by auto\n    qed\n  qed\n  moreover have \"w^y > 0\" by (simp add: w_range)\n  ultimately have \"?full_diff \\<le> 0\" using full_diff_diff zero_less_mult_iff by smt\n  then show ?case using right.hyps(4) by (smt (verit, best) power_sum_B)\nnext\n  case (up x y A B)\n  (*\n    The \"up\" part is simpler (don't need to deal with crossing the x = 0 column).\n  *)\n  let ?x = \"nat (abs x)\"\n\n  (* Show that the two power sums differ by the terms of the three coin positions that changed *)\n  let ?full_diff = \"w^(?x + (y-2)) - w^(?x + (y-1)) - w^(?x + y)\"\n  have power_sum_B: \"power_sum (A - {(x, y), (x, y-1)} \\<union> {(x, y-2)})\n      = power_sum A + ?full_diff\"\n    using \\<open>(x, y) \\<in> A\\<close> \\<open>(x, y-1) \\<in> A\\<close> \\<open>(x, y-2) \\<notin> A\\<close> power_sum_minus_singleton\n      power_sum_union_singleton\n    by (smt (verit) Diff_insert2 diff_diff_left insert_Diff insert_iff nat_1_add_1 prod.inject)\n\n  (* Factor out w^y to simplify the remaining argument: the other factor is now called ?diff *)\n  then have \"?full_diff = w^(?x)*w^(y-2) - w^(?x)*w^(y-1) - w^(?x)*w^y\" by (metis power_add)\n  then have full_diff_diff: \"?full_diff = w^(?x) * (w^(y-2) - w^(y-1) - w^y)\" \n    (is \"?full_diff = w^(?x) * ?diff\") by (simp add: right_diff_distrib)\n\n  (* Show that ?diff is non-positive, i.e. the power sum weakly decreases: only y \\<ge> 2 is possible *)\n  have \"?diff  \\<le> 0\"\n  proof (cases \"y \\<ge> 2\")\n    (* The up jump goes in the direction of decreasing exponents: the power sum is unchanged *)\n    case True\n    then have \"?diff = w^(y-2) - w^(y-2+1) - w^(y-2+2)\" using nat_le_iff_add by auto\n    then have \"?diff = 0\" using w_recurrence[where n=\"y-2\"] by simp\n    then show ?thesis by simp\n  next\n    case False \n    (* This case is impossible: you cannot jump up when too close to the upper border. *)\n    then have \"False\" using \\<open>(x, y - 1) \\<in> A\\<close> \\<open>(x, y - 2) \\<notin> A\\<close> by auto\n    then show ?thesis ..\n  qed\n  moreover have \"w^?x > 0\" by (simp add: w_range)\n  ultimately have \"?full_diff \\<le> 0\" using full_diff_diff zero_less_mult_iff by smt\n  then show ?case using up.hyps(4) by (smt (verit, best) power_sum_B)\nnext\n  case (down x y A B)\n  (*\n    The \"down\" part is even shorter (don't need to deal with the y = 0 upper border).\n  *)\n  let ?x = \"nat (abs x)\"\n\n  (* Show that the two power sums differ by the terms of the three coin positions that changed *)\n  let ?full_diff = \"w^(?x + (y+2)) - w^(?x + (y+1)) - w^(?x + y)\"\n  have power_sum_B: \"power_sum (A - {(x, y), (x, y+1)} \\<union> {(x, y+2)})\n      = power_sum A + ?full_diff\"\n    using \\<open>(x, y) \\<in> A\\<close> \\<open>(x, y+1) \\<in> A\\<close> \\<open>(x, y+2) \\<notin> A\\<close> power_sum_minus_singleton\n      power_sum_union_singleton\n    by (smt (verit) Diff_iff Diff_insert2 add_diff_cancel_left' diff_is_0_eq' insertE insert_Diff\n        nle_le one_neq_zero prod.inject)\n\n  (* Factor out w^y to simplify the remaining argument: the other factor is now called ?diff *)\n  then have \"?full_diff = w^(?x)*w^(y+2) - w^(?x)*w^(y+1) - w^(?x)*w^y\" by (metis power_add)\n  then have full_diff_diff: \"?full_diff = w^(?x) * (w^(y+2) - w^(y+1) - w^y)\" \n    (is \"?full_diff = w^(?x) * ?diff\") by (simp add: right_diff_distrib)\n\n  (* Show that ?diff is non-positive, i.e. the power sum weakly decreases \n     (it actually strictly decreases: down jumps are in the direction of increasing exponents *)\n  have \"?diff  \\<le> 0\" by (smt (verit) w_range w_recurrence zero_less_power)\n  moreover have \"w^?x > 0\" by (simp add: w_range)\n  ultimately have \"?full_diff \\<le> 0\" using full_diff_diff zero_less_mult_iff by smt\n  then show ?case using down.hyps(4) by (smt (verit, best) power_sum_B)\nqed\n\n(*\n  A `jumps` transition also weakly decreases the `power_sum`.\n*)\ncorollary jumps_decrease_power_sum:\n  \"jumps A B \\<Longrightarrow> power_sum B \\<le> power_sum A\"\nunfolding jumps_def by (induction rule: star.induct) (fastforce dest: jump_decreases_power_sum)+\n\nsection \\<open>Game unwinnable (1) (Goal field/finite initial configuration)\\<close>\n\ntext \\<open>This section gives the first (and weakest) version of the final theorem: We show that\n  from a finite initial configuration, the goal field (0, 0) cannot be reached.\n  \n  The theorem is strengthened in the following sections\n  - to allow any (possibly non-finite) initial configuration and\n  - to show that not only the goal field (0, 0), but also no other field (x, 0) on the row y = 0\n      can be reached.\\<close>\n\n(*\n  The game cannot be won from a finite initial configuration, if the objective is to reach the\n    goal field (0, 0).\n*)\ntheorem finite_initial_coins_cannot_reach_goal_field:\n  assumes finite: \"finite A\"\n      and initial: \"initial_coins A\"\n      and reaches: \"jumps A B\"\n    shows \"(0, 0) \\<notin> B\"\nproof (rule ccontr)\n  (* Assume the goal field is reached *)\n  assume \"\\<not> (0, 0) \\<notin> B\"\n  then have \"{(0, 0)} \\<subseteq> B\" by simp\n\n  (* But A has a power sum less than 1,...*)\n  have \"power_sum A < 1\"\n    using initial initial_finite_coins_less_one finite by blast\n  (* ...while B has a power sum \\<ge> 1... *)\n  moreover have \"power_sum B \\<ge> 1\"\n    by (metis \\<open>{(0, 0)} \\<subseteq> B\\<close> goal_field_value_1 powersum_subset_leq)\n  (* ...and the power sum of B cannot be greater than that of A. Contradiction! *)\n  moreover have \"power_sum A \\<ge> power_sum B\"\n    using jumps_decrease_power_sum reaches by blast\n  ultimately show \"False\" by simp\nqed\n\nsection \\<open>Game unwinnable (2) (Goal row/finite initial configuration)\\<close>\n\ntext \\<open>This section strengthens the first version of the unwinnability theorem: we show that the\n  goal field (0, 0) is not special, and that in fact no cell (x, 0) on the goal row y = 0 can be\n  reached.\n\n  We introduce a shift operation and show that any gameplay reaching a field (x, 0) can be\n  shifted in order to reach (0, 0).\\<close>\n\nsubsection \\<open>Shift operation\\<close>\n\n(*\n  Shifts a coin configuration in the x direction by some amount.\n*)\nfun shift :: \"coins \\<Rightarrow> int \\<Rightarrow> coins\" where\n\"shift coins d = {(x+d, y) |x y. (x, y) \\<in> coins}\"\n\n(*\n  Auxilliary lemma about sets of tuples, allows to shorten the following proofs.\n*)\nlemma tuple_set_eq_iff: \"(\\<forall>x y. ((x, y) \\<in> A) = ((x, y) \\<in> B)) \\<Longrightarrow> A = B\"\n  by fastforce\n\n(*\n  Shifting back and forth by the same amount gives the original set.\n*)\nlemma shift_inverse: \"shift (shift A d) (-d) = A\" (is \"?lhs = ?rhs\")\n  by (rule tuple_set_eq_iff) force\n\n(*\n  `shift` commutes with set differences.\n*)\nlemma shift_minus: \"shift (A - B) d = shift A d - shift B d\" (is \"?lhs = ?rhs\")\n  by (rule tuple_set_eq_iff) force\n\n(*\n  `shift` commutes with set unions.\n*)\nlemma shift_union: \"shift (A \\<union> B) d = shift A d \\<union> shift B d\" (is \"?lhs = ?rhs\")\n  by (rule tuple_set_eq_iff) force\n\n(*\n  `shift` preserves finiteness.\n*)\nlemma shift_finite: \"finite A \\<Longrightarrow> finite (shift A d)\"\nproof (induction rule: finite_induct)\n  case (insert t F)\n  obtain x y where xy: \"t = (x, y)\" by fastforce\n  have \"insert t F = F \\<union> {t}\" by auto\n  then have \"shift (insert t F) d = (shift F d) \\<union> (shift {t} d)\"\n    using shift_union by presburger\n  moreover have \"shift {(x, y)} d = {(x+d, y)}\" by simp\n  ultimately show ?case using insert.IH xy by auto\nqed simp\n\n(*\n  Auxilliary lemma to generalize an argument that will be made in each of the four jumping\n    directions in the following proof.\n*)\nlemma jump_shift_inv_aux:\n  assumes A': \"A' = shift A d\"\n      and B': \"B' = shift B d\"\n      and BA: \"B = A - {(x1, y1), (x2, y2)} \\<union> {(x3, y3)}\"\n    shows \"B' = A' - {(x1+d, y1), (x2+d, y2)} \\<union> {(x3+d, y3)}\" (is \"B' = A' - ?oldshift \\<union> ?newshift\")\nproof -\n  let ?old = \"{(x1, y1), (x2, y2)}\" (* ?old are the removed coin positions *)\n  let ?new = \"{(x3, y3)}\" (* ?new is the added coin position *)\n  from B' BA have \"B' = shift (A - ?old \\<union> ?new) d\" by simp\n  (* Use that `shift` commute with set differences and unions *)\n  then have \"B' = shift A d - shift ?old d \\<union> shift ?new d\"\n    using shift_union shift_minus by presburger\n  moreover have \"shift ?old d = ?oldshift\" by force\n  moreover have \"shift ?new d = ?newshift\" by force\n  ultimately show \"B' = A' - ?oldshift \\<union> ?newshift\" using A' by presburger\nqed\n\n(*\n  If `jump` transitions A to B, then it transitions the shifted versions A', B' as well.\n*)\nlemma jump_shift_inv:\n  assumes \"jump A B\"\n      and A': \"A' = shift A d\"\n      and B': \"B' = shift B d\"\n    shows \"jump A' B'\"\n  using \\<open>jump A B\\<close> A' B' proof (induction rule: jump.induct)\n(* Distinguish the four jump directions, and for each one apply the previous auxilliary lemma \n    to show that the corresponding `jump` conditions hold for the shifted versions. *)\n  case (left x y A B)\n  then have \"(x+d, y) \\<in> A' \\<and> (x-1+d, y) \\<in> A' \\<and> (x-2+d, y) \\<notin> A'\" by simp\n  moreover from left have \"B' = A' - {(x+d, y), (x-1+d, y)} \\<union> {(x-2+d, y)}\" \n    using jump_shift_inv_aux by simp\n  ultimately show ?case by (smt (verit, ccfv_threshold) jump.left)\nnext\n  case (right x y A B)\n  then have \"(x+d, y) \\<in> A' \\<and> (x+1+d, y) \\<in> A' \\<and> (x+2+d, y) \\<notin> A'\" by simp\n  moreover from right have \"B' = A' - {(x+d, y), (x+1+d, y)} \\<union> {(x+2+d, y)}\" \n    using jump_shift_inv_aux by simp\n  ultimately show ?case by (smt (verit, ccfv_threshold) jump.right)\nnext\n  case (up x y A B)\n  then have \"(x+d, y) \\<in> A' \\<and> (x+d, y-1) \\<in> A' \\<and> (x+d, y-2) \\<notin> A'\" by simp\n  moreover from up have \"B' = A' - {(x+d, y), (x+d, y-1)} \\<union> {(x+d, y-2)}\" \n    using jump_shift_inv_aux by simp\n  ultimately show ?case by (smt (verit, ccfv_threshold) jump.up)\nnext\n  case (down x y A B)\n  then have \"(x+d, y) \\<in> A' \\<and> (x+d, y+1) \\<in> A' \\<and> (x+d, y+2) \\<notin> A'\" by simp\n  moreover from down have \"B' = A' - {(x+d, y), (x+d, y+1)} \\<union> {(x+d, y+2)}\"\n    using jump_shift_inv_aux by simp\n  ultimately show ?case by (smt (verit, ccfv_threshold) jump.down)\nqed\n\n(*\n  Even stronger, `jump` transitions A to B iff it transitions A' to B'.\n*)\nlemma jump_shift_inv_eq:\n  assumes A': \"A' = shift A d\"\n      and B': \"B' = shift B d\"\n    shows \"jump A B \\<longleftrightarrow> jump A' B'\"\nproof\n  (* One direction was already shown, the other direction follows by shifting back *)\n  show \"jump A B \\<Longrightarrow> jump A' B'\" using A' B' jump_shift_inv by blast\n  assume \"jump A' B'\"\n  moreover have \"A = shift A' (-d)\" using A' shift_inverse by presburger\n  moreover have \"B = shift B' (-d)\" using B' shift_inverse by presburger\n  ultimately show \"jump A B\" using jump_shift_inv by blast\nqed\n\n(*\n  If `jumps` transitions A to B, it also transitions `(shift A d)` to `(shift B d)`.\n*)\nlemma jumps_shift_inv:\n  \"jumps A B \\<Longrightarrow> jumps (shift A d) (shift B d)\"\nunfolding jumps_def by (induction rule: star.induct) (meson jump_shift_inv star.simps)+\n\nsubsection \\<open>Game unwinnable (2) theorem\\<close>\n\n(*\n  The game cannot be won from a finite initial configuration, if the objective is to reach\n    any field (x, 0) on the goal row y = 0.\n*)\ntheorem finite_initial_coins_cannot_reach_goal_row:\n  assumes finite: \"finite A\"\n      and initial: \"initial_coins A\"\n      and reaches: \"jumps A B\"\n    shows \"\\<forall>x. (x, 0) \\<notin> B\"\nproof (rule ccontr)\n  (* Assume some field (x, 0) on the goal row is reached *)\n  assume \"\\<not> (\\<forall>x. (x, 0) \\<notin> B)\"\n  then obtain x where \"(x, 0) \\<in> B\" by blast\n\n  (* Shift A and B by -x and show that now (0, 0) is reached, as well as the other conditions\n       of the first version of the theorem are satisfied *)\n  let ?A' = \"shift A (-x)\"\n  let ?B' = \"shift B (-x)\"\n  have \"finite ?A'\" using finite shift_finite by blast\n  moreover have \"initial_coins ?A'\" using initial initial_coins_def by fastforce\n  moreover have \"(0, 0) \\<in> ?B'\" using \\<open>(x, 0) \\<in> B\\<close> by force\n  moreover have \"jumps ?A' ?B'\" using jumps_shift_inv reaches by blast\n\n  (* Use the first version of the theorem to show the contradiction *)\n  ultimately show \"False\" using finite_initial_coins_cannot_reach_goal_field by blast\nqed\n\nsection \\<open>Game unwinnable (3) (Goal field/any initial configuration)\\<close>\n\ntext \\<open>This section strengthens another aspect of the first version of the unwinnability theorem: \n  we show that the the finiteness assumption on the initial configuration is not needed.\n\n  To this end, we show that a `jump` only removes a finite number of coins from the initial\n  configuration. This implies that if A is an infinite initial configuration that reaches some B\n  that contains the goal field, then there is still some element from A left in B. From this\n  we get that the `power_sum` of such a B is strictly greater than 1.\\<close>\n\n(*\n  If `jump` transitions A to B, all but a finite number of elements from A are also in B.\n*)\nlemma jump_keeps_cofinite_coins:\n  assumes \"jump A B\"\n    shows \"\\<exists>D. finite D \\<and> A \\<inter> B = A - D\"\nusing \\<open>jump A B\\<close> proof (induction rule: jump.induct)\n(* Show that only a finite number of coins change for each of the four jumping directions *)\n  case (left x y A B)\n  then have \"A \\<inter> B = A - {(x, y), (x-1, y)}\" by force\n  then show ?case by (meson finite.simps)\nnext\n  case (right x y A B)\n  then have \"A \\<inter> B = A - {(x, y), (x+1, y)}\" by force\n  then show ?case by (meson finite.simps)\nnext\n  case (up x y A B)\n  then have \"A \\<inter> B = A - {(x, y), (x, y-1)}\" by force\n  then show ?case by (meson finite.simps)\nnext\n  case (down x y A B)\n  then have \"A \\<inter> B = A - {(x, y), (x, y+1)}\" by force\n  then show ?case by (meson finite.simps)\nqed\n\n(*  \n  Moreover, if a sequence of `jump`s transitions an infinite A to B, all but a finite number of\n    elements from A are also in B.\n  (We will only use that A \\<inter> B is non-empty, but co-finiteness is needed to pull through the\n    induction here.)\n*)\nlemma jumps_keeps_cofinite_coins:\n  assumes reaches: \"jumps A B\"\n      and infinite: \"infinite A\"\n    shows \"\\<exists>D. finite D \\<and> A \\<inter> B = A - D\"\n  using reaches infinite unfolding jumps_def\nproof (induction rule: star.induct)\n  case (refl X)\n  then show ?case by auto\nnext\n  case (step X Y Z)\n  (* Obtain finite sets D1 = X - (X \\<inter> Y) and D2 = Y - (Y \\<inter> Z) *)\n  then obtain D1 where D1: \"finite D1 \\<and> X \\<inter> Y = X - D1\"\n    using jump_keeps_cofinite_coins by presburger\n  then have \"infinite Y\"\n    by (metis Diff_infinite_finite finite_Int step.prems)\n  from this step obtain D2 where D2: \"finite D2 \\<and> Y \\<inter> Z = Y - D2\" by blast\n\n  (* Define a set ?D3 = X - (X \\<inter> Z) *)\n  let ?D3 = \"X - (X \\<inter> Z)\"\n  (* Show that the set X - (D1 \\<union> D2), which is co-finite wrt. X, is contained in X \\<inter> Z *)\n  have \"(X \\<inter> Y) \\<inter> (Y \\<inter> Z) \\<subseteq> X \\<inter> Z\" by blast\n  moreover have \"(X \\<inter> Y) \\<inter> (Y \\<inter> Z) = X - (D1 \\<union> D2)\" using D1 D2 by blast\n  (* From this, show that ?D3 is finite *)\n  ultimately have \"finite ?D3\"\n    by (metis D1 D2 Diff_Diff_Int Diff_Int finite_Int finite_UnI sup.absorb_iff1)\n  then show ?case by blast\nqed\n\n(*\n  The game cannot be won from any (possibly infinite) initial configuration, if the objective is\n    to reach the goal field (0, 0).\n*)\ntheorem initial_coins_cannot_reach_goal_field:\n  assumes initial: \"initial_coins A\"\n      and reaches: \"jumps A B\"\n    shows \"(0, 0) \\<notin> B\"\nproof (cases \"finite A\")\n  case True\n  (* For a finite set, use the first version of the theorem *)\n  then show ?thesis using finite_initial_coins_cannot_reach_goal_field initial reaches by simp\nnext\n  case infiniteA: False\n  (* For an infinite set, argue that at least one initial coin is still in place, which makes\n       the power sum of B strictly greater than one if it contains the goal field *)\n  show ?thesis\n  proof (rule ccontr)\n    (* Assume the goal field is reached *)\n    assume \"\\<not> (0, 0) \\<notin> B\"\n    then have \"{(0, 0)} \\<subseteq> B\" by simp\n    (* The power sum of A is \\<le> 1 (but now, differently than before, possibly equal to 1) *)\n    have \"power_sum A \\<le> 1\"\n      using initial initial_coins_leq_one by blast\n    (* Show that the power sum of B is > 1: *)\n    moreover have \"power_sum B > 1\"\n    proof -\n      (* Obtain some element (x, y) from A that is still in place in B *)\n      have \"\\<exists>D. finite D \\<and> A \\<inter> B = A - D\" \n        using reaches infiniteA jumps_keeps_cofinite_coins by blast\n      then have \"A \\<inter> B \\<noteq> {}\" by (metis finite.emptyI finite_Diff2 infiniteA)\n      then obtain x y where xy: \"(x, y) \\<in> A \\<inter> B\" by  fastforce\n\n      (* Show that both (x, y) and (0, 0) are in B and are different *)\n      then have \"{(x,y), (0,0)} \\<subseteq> B\" using \\<open>{(0, 0)} \\<subseteq> B\\<close> by auto\n      have \"(x,y) \\<noteq> (0, 0)\" proof -\n        have \"(x, y) \\<in> A\" using xy by simp\n        then have \"below_the_line (x, y)\" using initial initial_coins_def by blast\n        then show ?thesis by force\n      qed\n\n      (* Then show that the power sum of B is strictly greater than 1 *)\n      then have \"power_sum {(x,y), (0,0)} = w^(nat (abs x) + y) + 1\"\n        by (smt (verit) Diff_insert_absorb goal_field_value_1 insertCI insert_absorb\n           power_sum_minus_singleton singleton_insert_inj_eq)\n      then show ?thesis using \\<open>{(x,y), (0,0)} \\<subseteq> B\\<close>\n        by (smt (verit, ccfv_SIG) powersum_subset_leq w_range zero_less_power)\n    qed\n    (* Moreover, `power_sum A \\<ge> power_sum B`. Contradiction! *)\n    moreover have \"power_sum A \\<ge> power_sum B\"\n      using jumps_decrease_power_sum reaches by blast\n    ultimately show \"False\" by simp\n  qed\nqed\n\nsection \\<open>Game unwinnable (4) (Goal row/any initial configuration)\\<close>\n\ntext \\<open>Finally, we put the previous results together to obtain the strongest version of the\n  unwinnability theorem: The goal row cannot be reached from any initial configuration.\\<close>\n\n(*\n  The game cannot be won from any (possibly infinite) initial configuration, if the objective is\n    to reach any field (x, 0) on the goal row y = 0.\n*)\ntheorem initial_coins_cannot_reach_goal_row:\n  assumes initial: \"initial_coins A\"\n      and reaches: \"jumps A B\"\n    shows \"\\<forall>x. (x, 0) \\<notin> B\"\nproof (rule ccontr)\n  (* Assume some field (x, 0) on the goal row is reached *)\n  assume \"\\<not> (\\<forall>x. (x, 0) \\<notin> B)\"\n  then obtain x where \"(x, 0) \\<in> B\" by blast\n\n  (* Shift A and B by -x and show that now (0, 0) is reached, as well as the other conditions\n       of the third version of the theorem are satisfied *)\n  let ?A' = \"shift A (-x)\"\n  let ?B' = \"shift B (-x)\"\n  have \"initial_coins ?A'\" using initial initial_coins_def by fastforce\n  moreover have \"(0, 0) \\<in> ?B'\" using \\<open>(x, 0) \\<in> B\\<close> by force\n  moreover have \"jumps ?A' ?B'\" using jumps_shift_inv reaches by blast\n\n  (* Use the third version of the theorem to show the contradiction *)\n  ultimately show \"False\" using initial_coins_cannot_reach_goal_field by blast\nqed\n\n\nsection \\<open>The second-highest row can be reached\\<close>\n\ntext \\<open>Finally, a positive result: The second-highest row can actually be reached.\n  This is shown by an example, which is minimal according to https://www.oma.org.ar/red/la_rana.htm.\n\\<close>\n\n(*\n  The start configuration looks like this, and has 20 coins: (Column 0 is marked with |)\n\n      ------|----\n      ..ooooooo..  5\n      ....ooooo..  6\n      ...oooooo..  7\n      .....oo....  8\n      ...........  9\n\n  From this, we can reach {(0, 1)} in 19 jumps.\n*)\nlemma \"jumps {(-1,5), (-1,6), (0,5), (0,6), (1,5), (1,6), (2,5), (2,6),(-1,7), (-1,8), (0,7), (0,8),\n        (1,7), (2,7), (-2,7), (-3,7),(-2,6), (-2,5),(-3,5), (-4,5)}\n      {(0,1)}\"\n(* The proof is in apply style as this turned out to be more convenient for this kind of proof. *)\n  unfolding jumps_def\n  apply (rule star.step[where y=\"{(-1,4),(0,5),(0,6),(1,5),(1,6),(2,5),(2,6),(-1,7),(-1,8),(0,7),\n    (0,8),(1,7),(2,7),(-2,7),(-3,7),(-2,6),(-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of \"-1\" 6]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,5),(1,6),(2,5),(2,6),(-1,7),(-1,8),(0,7),(0,8),\n    (1,7),(2,7),(-2,7),(-3,7),(-2,6),(-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of 0 6]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,5),(2,6),(-1,7),(-1,8),(0,7),(0,8),(1,7),\n    (2,7),(-2,7),(-3,7),(-2,6),(-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of 1 6]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,7),(-1,8),(0,7),(0,8),(1,7),(2,7),\n    (-2,7),(-3,7),(-2,6),(-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of 2 6]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,6),(0,7),(0,8),(1,7),(2,7),(-2,7),\n    (-3,7),(-2,6),(-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of \"-1\" 8]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,6),(0,6),(1,7),(2,7),(-2,7),(-3,7),\n    (-2,6),(-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of \"0\" 8]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,6),(0,6),(0,7),(-2,7),(-3,7),(-2,6),\n    (-2,5),(-3,5),(-4,5)}\"])\n  apply (rule jump.left[of \"2\" 7]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,6),(0,6),(0,7),(-1,7),(-2,6),(-2,5),\n    (-3,5),(-4,5)}\"])\n  apply (rule jump.right[of \"-3\" 7]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,5),(0,6),(0,7),(-2,6),(-2,5),(-3,5),\n    (-4,5)}\"])\n  apply (rule jump.up[of \"-1\" 7]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,5),(0,5),(-2,6),(-2,5),(-3,5),\n    (-4,5)}\"])\n  apply (rule jump.up[of \"0\" 7]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,5),(0,5),(-2,4),(-3,5),(-4,5)}\"])\n  apply (rule jump.up[of \"-2\" 6]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,4),(1,4),(2,4),(-1,5),(0,5),(-2,4),(-2,5)}\"])\n  apply (rule jump.right[of \"-4\" 5]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,3),(1,4),(2,4),(-1,5),(-2,4),(-2,5)}\"])\n  apply (rule jump.up[of 0 5]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,3),(0,4),(-1,5),(-2,4),(-2,5)}\"])\n  apply (rule jump.left[of 2 4]) apply(force)+\n  apply (rule star.step[where y=\"{(-1,4),(0,2),(-1,5),(-2,4),(-2,5)}\"])\n  apply (rule jump.up[of 0 4]) apply(force)+\n  apply (rule star.step[where y=\"{(0,4),(0,2),(-1,5),(-2,5)}\"])\n  apply (rule jump.right[of \"-2\" 4]) apply(force)+\n  apply (rule star.step[where y=\"{(0,4),(0,2),(0,5)}\"])\n  apply (rule jump.right[of \"-2\" 5]) apply(force)+\n  apply (rule star.step[where y=\"{(0,3),(0,2)}\"])\n  apply (rule jump.up[of 0 5]) apply(force)+\n  apply (rule star.step[where y=\"{(0,1)}\"])\n  apply (rule jump.up[of 0 3]) apply(force)+\n  done\n\nend", "meta": {"author": "Vuenc", "repo": "Conways-Soldiers-Isabelle", "sha": "6cd90732a46180e474e2e2cf6fc2d3139cec9b4e", "save_path": "github-repos/isabelle/Vuenc-Conways-Soldiers-Isabelle", "path": "github-repos/isabelle/Vuenc-Conways-Soldiers-Isabelle/Conways-Soldiers-Isabelle-6cd90732a46180e474e2e2cf6fc2d3139cec9b4e/LeapingFrog.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7640721363118077}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nparagraph \\<open>Transitive\\<close>\ntheory Binary_Relations_Transitive\n  imports\n    Binary_Relation_Functions\n    Functions_Monotone\nbegin\n\nconsts transitive_on :: \"'a \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> bool\"\n\noverloading\n  transitive_on_pred \\<equiv> \"transitive_on :: ('a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> bool\"\nbegin\n  definition \"transitive_on_pred P R \\<equiv> \\<forall>x y z. P x \\<and> P y \\<and> P z \\<and> R x y \\<and> R y z \\<longrightarrow> R x z\"\nend\n\nlemma transitive_onI [intro]:\n  assumes \"\\<And>x y z. P x \\<Longrightarrow> P y \\<Longrightarrow> P z \\<Longrightarrow> R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\n  shows \"transitive_on P R\"\n  unfolding transitive_on_pred_def using assms by blast\n\nlemma transitive_onD:\n  assumes \"transitive_on P R\"\n  and \"P x\" \"P y\" \"P z\"\n  and \"R x y\" \"R y z\"\n  shows \"R x z\"\n  using assms unfolding transitive_on_pred_def by blast\n\nlemma transitive_on_if_rel_comp_self_imp:\n  assumes \"\\<And>x y. P x \\<Longrightarrow> P y \\<Longrightarrow> (R \\<circ>\\<circ> R) x y \\<Longrightarrow> R x y\"\n  shows \"transitive_on P R\"\nproof (rule transitive_onI)\n  fix x y z assume \"R x y\" \"R y z\"\n  then have \"(R \\<circ>\\<circ> R) x z\" by (intro rel_compI)\n  moreover assume \"P x\" \"P y\" \"P z\"\n  ultimately show \"R x z\" by (simp only: assms)\nqed\n\nlemma transitive_on_rel_inv_iff_transitive_on [iff]:\n  \"transitive_on P R\\<inverse> \\<longleftrightarrow> transitive_on (P :: 'a \\<Rightarrow> bool) (R :: 'a \\<Rightarrow> _)\"\n  by (auto intro!: transitive_onI dest: transitive_onD)\n\nlemma antimono_transitive_on [iff]:\n  \"antimono (\\<lambda>(P :: 'a \\<Rightarrow> bool). transitive_on P (R :: 'a \\<Rightarrow> _))\"\n  by (intro antimonoI) (auto dest: transitive_onD)\n\nlemma transitive_on_if_le_pred_if_transitive_on:\n  fixes P P' :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"transitive_on P R\"\n  and \"P' \\<le> P\"\n  shows \"transitive_on P' R\"\n  using assms by (auto dest: transitive_onD)\n\ndefinition \"transitive (R :: 'a \\<Rightarrow> _) \\<equiv> transitive_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n\nlemma transitive_eq_transitive_on:\n  \"transitive (R :: 'a \\<Rightarrow> _) = transitive_on (\\<top> :: 'a \\<Rightarrow> bool) R\"\n  unfolding transitive_def ..\n\nlemma transitiveI [intro]:\n  assumes \"\\<And>x y z. R x y \\<Longrightarrow> R y z \\<Longrightarrow> R x z\"\n  shows \"transitive R\"\n  unfolding transitive_eq_transitive_on using assms by (intro transitive_onI)\n\nlemma transitiveD [dest]:\n  assumes \"transitive R\"\n  and \"R x y\" \"R y z\"\n  shows \"R x z\"\n  using assms unfolding transitive_eq_transitive_on\n  by (auto dest: transitive_onD)\n\nlemma transitive_on_if_transitive:\n  fixes P :: \"'a \\<Rightarrow> bool\" and R :: \"'a \\<Rightarrow> _\"\n  assumes \"transitive R\"\n  shows \"transitive_on P R\"\n  using assms by (intro transitive_onI) blast\n\nlemma transitive_if_rel_comp_le_self:\n  assumes \"R \\<circ>\\<circ> R \\<le> R\"\n  shows \"transitive R\"\n  using assms unfolding transitive_eq_transitive_on\n    by (intro transitive_on_if_rel_comp_self_imp) blast\n\nlemma rel_comp_le_self_if_transitive:\n  assumes \"transitive R\"\n  shows \"R \\<circ>\\<circ> R \\<le> R\"\n  using assms by blast\n\ncorollary transitive_iff_rel_comp_le_self: \"transitive R \\<longleftrightarrow> R \\<circ>\\<circ> R \\<le> R\"\n  using transitive_if_rel_comp_le_self rel_comp_le_self_if_transitive by blast\n\nlemma transitive_if_transitive_on_in_field:\n  assumes \"transitive_on (in_field R) R\"\n  shows \"transitive R\"\n  using assms by (intro transitiveI) (blast dest: transitive_onD)\n\ncorollary transitive_on_in_field_iff_transitive [simp]:\n  \"transitive_on (in_field R) R \\<longleftrightarrow> transitive R\"\n  using transitive_if_transitive_on_in_field transitive_on_if_transitive\n  by blast\n\nlemma transitive_rel_inv_iff_transitive [iff]:\n  \"transitive R\\<inverse> \\<longleftrightarrow> transitive R\"\n  by (auto intro!: transitiveI)\n\nparagraph \\<open>Instantiations\\<close>\n\nlemma transitive_eq: \"transitive (=)\"\n  by (rule transitiveI) (rule trans)\n\nlemma transitive_top: \"transitive \\<top>\"\n  by (rule transitiveI) auto\n\n\nend", "meta": {"author": "kappelmann", "repo": "transport-isabelle", "sha": "b6d2cb56ea4abf6e496d1c258d5b3d2a816d75ff", "save_path": "github-repos/isabelle/kappelmann-transport-isabelle", "path": "github-repos/isabelle/kappelmann-transport-isabelle/transport-isabelle-b6d2cb56ea4abf6e496d1c258d5b3d2a816d75ff/HOL_Basics/Binary_Relations/Properties/Binary_Relations_Transitive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318195, "lm_q2_score": 0.8596637451167997, "lm_q1q2_score": 0.7640337205180934}}
{"text": "theory Saturation \n  imports Main \"Well_Quasi_Orders.Well_Quasi_Orders\" ReverseWellQuasiOrder \nbegin\n\nsubsection \\<open>Well-quasi-ordered saturation\\<close>\n\ntype_synonym 't saturation_rule = \"'t \\<Rightarrow> 't \\<Rightarrow> bool\"\n\ndefinition saturated :: \"'t saturation_rule \\<Rightarrow> 't \\<Rightarrow> bool\" where\n  \"saturated rule val \\<longleftrightarrow> (\\<nexists>val'. rule val val')\"\n\ndefinition saturation :: \"'t saturation_rule \\<Rightarrow> 't \\<Rightarrow> 't \\<Rightarrow> bool\" where\n  \"saturation rule val val' \\<longleftrightarrow> rule\\<^sup>*\\<^sup>* val val' \\<and> saturated rule val'\"\n\n\nlemma wqo_no_infinite: \n  assumes \"wqo_on P UNIV\"\n  assumes \"\\<And>f f'. rule f f' \\<Longrightarrow> strict P f' f\"\n  assumes \"\\<forall>i :: nat. rule (seq i) (seq (Suc i))\"\n  shows \"False\"\nproof -\n  have decreasing:\"\\<And>i. strict P (seq (Suc i)) (seq i)\" using assms by simp\n  have trans: \"\\<And>a b c. strict P a b \\<Longrightarrow> strict P b c \\<Longrightarrow> strict P a c\" using assms(1) unfolding wqo_on_def transp_on_def by blast\n  have \"\\<exists>i j. i < j \\<and> P (seq i) (seq j)\" using assms(1) unfolding wqo_on_def almost_full_on_def good_def by simp\n  moreover have \"\\<forall>i j. i < j \\<longrightarrow> strict P (seq j) (seq i)\"\n  proof\n    fix i\n    show \"\\<forall>j>i. strict P (seq j) (seq i)\"\n    proof \n      fix j\n      have \"i < j \\<Longrightarrow> strict P (seq j) (seq i)\"\n      proof (induction \"j\")\n        case 0\n        then show ?case by simp\n      next\n        case (Suc j)\n        then have \"i\\<noteq>j \\<Longrightarrow> strict P (seq (Suc j)) (seq i)\" using decreasing trans not_less_less_Suc_eq by blast\n        then show ?case by (cases \"i=j\", auto simp add: decreasing)\n      qed\n      then show \"i < j \\<longrightarrow> strict P (seq j) (seq i)\" by auto\n    qed\n  qed\n  ultimately show ?thesis by auto\nqed\n\nlemma wqo_saturation_termination:\n  assumes \"wqo_on P UNIV\"\n  assumes \"\\<And>f f'. rule f f' \\<Longrightarrow> strict P f' f\"\n  shows \"\\<not>(\\<exists>seq. (\\<forall>i :: nat. rule (seq i) (seq (Suc i))))\"\n  using assms wqo_no_infinite by blast \n\nlemma wqo_saturation_exi:\n  assumes \"wqo_on P UNIV\"\n  assumes \"\\<And>f f'. rule f f' \\<Longrightarrow> strict P f' f\"\n  shows \"\\<exists>f'. saturation rule f f'\"\nproof (rule ccontr)\n  assume a: \"\\<nexists>f'. saturation rule f f'\"\n  define g where \"g f = (SOME f'. rule f f')\" for f\n  define seq where \"seq i = (g ^^ i) f\" for i\n  have \"\\<forall>i :: nat. rule\\<^sup>*\\<^sup>* f (seq i) \\<and> rule (seq i) (seq (Suc i))\"\n  proof \n    fix i\n    show \"rule\\<^sup>*\\<^sup>* f (seq i) \\<and> rule (seq i) (seq (Suc i))\"\n      proof (induction i)\n    case 0\n      have \"rule f (g f)\" by (metis g_def a rtranclp.rtrancl_refl saturation_def saturated_def someI)\n      then show ?case using seq_def a by auto\n    next\n      case (Suc i)\n      then have sat_Suc: \"rule\\<^sup>*\\<^sup>* f (seq (Suc i))\" by fastforce\n      then have \"rule (g ((g ^^ i) f)) (g (g ((g ^^ i) f)))\"\n        by (metis Suc.IH seq_def g_def a r_into_rtranclp rtranclp_trans saturation_def saturated_def someI)\n      then have \"rule (seq (Suc i)) (seq (Suc (Suc i)))\" unfolding seq_def by simp\n      then show ?case using sat_Suc by auto\n    qed\n  qed\n  then have \"\\<forall>i. rule (seq i) (seq (Suc i))\" by auto\n  then show False using wqo_no_infinite assms by auto\nqed\n\n\nlemma wqo_class_no_infinite: \n  assumes \"\\<And>f f' ::('t::wqo). rule f f' \\<Longrightarrow> f' < f\"\n  assumes \"\\<forall>i :: nat. rule (seq i) (seq (Suc i))\"\n  shows \"False\"\nusing assms wqo_no_infinite[of \"(\\<le>)\"] wqo_on_class less_le_not_le by metis\n\nlemma wqo_class_saturation_termination:\n  assumes \"\\<And>f f' ::('t::wqo). rule f f' \\<Longrightarrow> f' < f\"\n  shows \"\\<not>(\\<exists>seq. (\\<forall>i :: nat. rule (seq i) (seq (Suc i))))\"\n  using assms wqo_class_no_infinite by blast \n\nlemma wqo_class_saturation_exi:\n  assumes \"\\<And>f f' ::('t::wqo). rule f f' \\<Longrightarrow> f' < f\"\n  shows \"\\<exists>f'. saturation rule f f'\"\nusing assms wqo_saturation_exi[of \"(\\<le>)\"] wqo_on_class less_le_not_le by metis\n\nlemma reverse_wqo_class_no_infinite: \n  assumes \"\\<And>f f' ::('t::reverse_wqo). rule f f' \\<Longrightarrow> f < f'\"\n  assumes \"\\<forall>i :: nat. rule (seq i) (seq (Suc i))\"\n  shows \"False\"\n  using assms wqo_no_infinite[of \"(\\<ge>)\"] reverse_wqo_on_class less_le_not_le by metis\n\nlemma reverse_wqo_class_saturation_termination:\n  assumes \"\\<And>f f' ::('t::reverse_wqo). rule f f' \\<Longrightarrow> f < f'\"\n  shows \"\\<not>(\\<exists>seq. (\\<forall>i :: nat. rule (seq i) (seq (Suc i))))\"\n  using assms reverse_wqo_class_no_infinite by blast \n\nlemma reverse_wqo_class_saturation_exi:\n  assumes \"\\<And>f f' ::('t::reverse_wqo). rule f f' \\<Longrightarrow> f < f'\"\n  shows \"\\<exists>f'. saturation rule f f'\"\nusing assms wqo_saturation_exi[of \"(\\<ge>)\"] reverse_wqo_on_class less_le_not_le by metis\n\n\nsubsection \\<open>Set saturation\\<close>\n\nlemma finite_card_le_wqo:\n  assumes \"finite A\"\n  shows \"wqo_on (\\<lambda>x y. card x \\<ge> card y) A\"\nproof -\n  have \"reflp_on (\\<lambda>x y. card x \\<ge> card y) A\" unfolding reflp_on_def by blast\n  moreover have \"transp_on (\\<lambda>x y. card x \\<ge> card y) A\" unfolding transp_on_def by simp\n  ultimately show ?thesis using finite_wqo_on[of \"A\" \"(\\<lambda>x y. card x \\<ge> card y)\"] using assms by simp\nqed\n\nlemma no_infinite: \n  assumes \"\\<And>ts ts' :: 'a::finite set. rule ts ts' \\<Longrightarrow> card ts' = Suc (card ts)\"\n  assumes \"\\<forall>i :: nat. rule (tts i) (tts (Suc i))\"\n  shows \"False\"\nusing assms wqo_no_infinite[of \"\\<lambda>x y. card x \\<ge> card y\" \"rule\" \"tts\"] finite_card_le_wqo\n  by (metis (mono_tags, lifting) finite_class.finite_UNIV nle_le not_less_eq_eq)\n\nlemma saturation_termination:\n  assumes \"\\<And>ts ts' :: 'a::finite set. rule ts ts' \\<Longrightarrow> card ts' = Suc (card ts)\"\n  shows \"\\<not>(\\<exists>tts. (\\<forall>i :: nat. rule (tts i) (tts (Suc i))))\"\n  using assms no_infinite by blast \n\nlemma saturation_exi: \n  assumes \"\\<And>ts ts' :: 'a::finite set. rule ts ts' \\<Longrightarrow> card ts' = Suc (card ts)\"\n  shows \"\\<exists>ts'. saturation rule ts ts'\"\n  using assms wqo_saturation_exi[of \"\\<lambda>x y. card x \\<ge> card y\" \"rule\" \"ts\"] finite_card_le_wqo\n  by (metis (mono_tags, lifting) finite_class.finite_UNIV nle_le not_less_eq_eq)\n\nend", "meta": {"author": "anderssch", "repo": "LTS-formalization", "sha": "e761728271f161898be5685723cecf711872514f", "save_path": "github-repos/isabelle/anderssch-LTS-formalization", "path": "github-repos/isabelle/anderssch-LTS-formalization/LTS-formalization-e761728271f161898be5685723cecf711872514f/WPDS/Saturation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.8596637469145053, "lm_q1q2_score": 0.7640337069180604}}
{"text": "\n\n(*<*) theory ex1_5 imports Main begin (*>*)\n\ntext{*\nDefine a function @{term occurs}, such that @{term\"occurs x xs\"} is\nthe number of occurrences of the element @{term x} in the list @{term\nxs}.\n*}\n\nprimrec  occurs :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"occurs x [] = 0\"\n|\"occurs a (x#xs) = (if a=x then Suc (occurs a xs) else occurs a xs)\"\n\n\ntext {*\nProve (or let Isabelle disprove) the lemmas that follow. You may have\nto prove additional lemmas first.  Use the @{text \"[simp]\"}-attribute\nonly if the equation is truly a simplification and is necessary for\nsome later proof.\n*}\nlemma occur_1 :\"occurs a (a#xs) =Suc (occurs a xs) \"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"occurs a xs = occurs a (rev xs)\"\n  apply (induct xs)\n   apply (auto simp add:occur_1)\n  oops\n\nlemma \"occurs a xs <= length xs\"\n  apply(induct xs)\n   apply auto\n  done\n\n\ntext{* Function @{text map} applies a function to all elements of a list:\n@{text\"map f [x\\<^isub>1,\\<dots>,x\\<^isub>n] = [f x\\<^isub>1,\\<dots>,f x\\<^isub>n]\"}. *}\nprimrec map ::\"('a\\<Rightarrow>'a) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"map f [] = []\"\n|\"map f (x#xs) = (f x) # map f xs\" \n\n\nlemma \"occurs a (map f xs) = occurs (f a) xs\"\n  quickcheck\n(*<*)oops(*>*)\n\ntext{*\nFunction @{text\"filter :: ('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"} is defined\nby @{thm[display]filter.simps[no_vars]} Find an expression @{text e}\nnot containing @{text filter} such that the following becomes a true\nlemma, and prove it:\n*}\n\nlemma \"occurs a (filter P xs) = (if P a then occurs a xs else 0)\"\n  apply (induct xs)\n   apply auto\ndone\n\n\ntext{*\nWith the help of @{term occurs}, define a function @{term remDups}\nthat removes all duplicates from a list.\n*}\n\nprimrec remDups :: \"'a list \\<Rightarrow> 'a list\" where\n\"remDups [] = []\"\n|\" remDups (x#xs) = (if occurs x xs =0 then ( x# (remDups xs) )else remDups xs)\" \n\n\ntext{*\nFind an expression @{text e} not containing @{text remDups} such that\nthe following becomes a true lemma, and prove it:\n*}\n\n\nlemma \"occurs x (remDups xs) = (if (occurs x xs) =0 then 0 else 1)\"\n  apply (induct xs)\n   apply auto\n  oops\n\n\ntext{*\nWith the help of @{term occurs} define a function @{term unique}, such\nthat @{term \"unique xs\"} is true iff every element in @{term xs}\noccurs only once.\n*}\n\nprimrec unique :: \"'a list \\<Rightarrow> bool\"\n  where \"unique [] = True\" \n  |\"unique (x#xs) = (if occurs x xs \\<noteq>0 then False else unique xs)\"\n\n\ntext{* Show that the result of @{term remDups} is @{term unique}. *}\n\nlemma remDups_1: \" occurs x (remDups xs) = min 1 (occurs x xs)\"\n  apply (induct xs)\n   apply auto\n  done\n\nlemma \"unique (remDups xs)\"\n  apply (induct xs)\n   apply (auto simp add: remDups_1)\n  oops\n\n(*<*) end (*>*)", "meta": {"author": "hei411", "repo": "Isabelle", "sha": "9126e84b3e39af28336f25e3b7563a01f70625fa", "save_path": "github-repos/isabelle/hei411-Isabelle", "path": "github-repos/isabelle/hei411-Isabelle/Isabelle-9126e84b3e39af28336f25e3b7563a01f70625fa/Online_exercises/ex1_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8740772286044094, "lm_q1q2_score": 0.7640109986975913}}
{"text": "(*  Title:    HOL/Probability/Distribution_Functions.thy\n    Authors:  Jeremy Avigad (CMU) and Luke Serafin (CMU)\n*)\n\nsection \\<open>Distribution Functions\\<close>\n\ntext \\<open>\nShows that the cumulative distribution function (cdf) of a distribution (a measure on the reals) is\nnondecreasing and right continuous, which tends to 0 and 1 in either direction.\n\nConversely, every such function is the cdf of a unique distribution. This direction defines the\nmeasure in the obvious way on half-open intervals, and then applies the Caratheodory extension\ntheorem.\n\\<close>\n\n(* TODO: the locales \"finite_borel_measure\" and \"real_distribution\" are defined here, but maybe they\n should be somewhere else. *)\n\ntheory Distribution_Functions\n  imports Probability_Measure\nbegin\n\nlemma UN_Ioc_eq_UNIV: \"(\\<Union>n. { -real n <.. real n}) = UNIV\"\n  by auto\n     (metis le_less_trans minus_minus neg_less_iff_less not_le real_arch_simple\n            of_nat_0_le_iff reals_Archimedean2)\n\nsubsection \\<open>Properties of cdf's\\<close>\n\ndefinition\n  cdf :: \"real measure \\<Rightarrow> real \\<Rightarrow> real\"\nwhere\n  \"cdf M \\<equiv> \\<lambda>x. measure M {..x}\"\n\nlemma cdf_def2: \"cdf M x = measure M {..x}\"\n  by (simp add: cdf_def)\n\nlocale finite_borel_measure = finite_measure M for M :: \"real measure\" +\n  assumes M_is_borel: \"sets M = sets borel\"\nbegin\n\nlemma sets_M[intro]: \"a \\<in> sets borel \\<Longrightarrow> a \\<in> sets M\"\n  using M_is_borel by auto\n\nlemma cdf_diff_eq:\n  assumes \"x < y\"\n  shows \"cdf M y - cdf M x = measure M {x<..y}\"\nproof -\n  from assms have *: \"{..x} \\<union> {x<..y} = {..y}\" by auto\n  have \"measure M {..y} = measure M {..x} + measure M {x<..y}\"\n    by (subst finite_measure_Union [symmetric], auto simp add: *)\n  thus ?thesis\n    unfolding cdf_def by auto\nqed\n\nlemma cdf_nondecreasing: \"x \\<le> y \\<Longrightarrow> cdf M x \\<le> cdf M y\"\n  unfolding cdf_def by (auto intro!: finite_measure_mono)\n\nlemma borel_UNIV: \"space M = UNIV\"\n by (metis in_mono sets.sets_into_space space_in_borel top_le M_is_borel)\n\nlemma cdf_nonneg: \"cdf M x \\<ge> 0\"\n  unfolding cdf_def by (rule measure_nonneg)\n\nlemma cdf_bounded: \"cdf M x \\<le> measure M (space M)\"\n  unfolding cdf_def by (intro bounded_measure)\n\nlemma cdf_lim_infty:\n  \"((\\<lambda>i. cdf M (real i)) \\<longlonglongrightarrow> measure M (space M))\"\nproof -\n  have \"(\\<lambda>i. cdf M (real i)) \\<longlonglongrightarrow> measure M (\\<Union> i::nat. {..real i})\"\n    unfolding cdf_def by (rule finite_Lim_measure_incseq) (auto simp: incseq_def)\n  also have \"(\\<Union> i::nat. {..real i}) = space M\"\n    by (auto simp: borel_UNIV intro: real_arch_simple)\n  finally show ?thesis .\nqed\n\nlemma cdf_lim_at_top: \"(cdf M \\<longlongrightarrow> measure M (space M)) at_top\"\n  by (rule tendsto_at_topI_sequentially_real)\n     (simp_all add: mono_def cdf_nondecreasing cdf_lim_infty)\n\nlemma cdf_lim_neg_infty: \"((\\<lambda>i. cdf M (- real i)) \\<longlonglongrightarrow> 0)\"\nproof -\n  have \"(\\<lambda>i. cdf M (- real i)) \\<longlonglongrightarrow> measure M (\\<Inter> i::nat. {.. - real i })\"\n    unfolding cdf_def by (rule finite_Lim_measure_decseq) (auto simp: decseq_def)\n  also have \"(\\<Inter> i::nat. {..- real i}) = {}\"\n    by auto (metis leD le_minus_iff reals_Archimedean2)\n  finally show ?thesis\n    by simp\nqed\n\nlemma cdf_lim_at_bot: \"(cdf M \\<longlongrightarrow> 0) at_bot\"\nproof -\n  have *: \"((\\<lambda>x :: real. - cdf M (- x)) \\<longlongrightarrow> 0) at_top\"\n    by (intro tendsto_at_topI_sequentially_real monoI)\n       (auto simp: cdf_nondecreasing cdf_lim_neg_infty tendsto_minus_cancel_left[symmetric])\n  from filterlim_compose [OF *, OF filterlim_uminus_at_top_at_bot]\n  show ?thesis\n    unfolding tendsto_minus_cancel_left[symmetric] by simp\nqed\n\nlemma cdf_is_right_cont: \"continuous (at_right a) (cdf M)\"\n  unfolding continuous_within\nproof (rule tendsto_at_right_sequentially[where b=\"a + 1\"])\n  fix f :: \"nat \\<Rightarrow> real\" and x assume f: \"decseq f\" \"f \\<longlonglongrightarrow> a\"\n  then have \"(\\<lambda>n. cdf M (f n)) \\<longlonglongrightarrow> measure M (\\<Inter>i. {.. f i})\"\n    using \\<open>decseq f\\<close> unfolding cdf_def\n    by (intro finite_Lim_measure_decseq) (auto simp: decseq_def)\n  also have \"(\\<Inter>i. {.. f i}) = {.. a}\"\n    using decseq_ge[OF f] by (auto intro: order_trans LIMSEQ_le_const[OF f(2)])\n  finally show \"(\\<lambda>n. cdf M (f n)) \\<longlonglongrightarrow> cdf M a\"\n    by (simp add: cdf_def)\nqed simp\n\nlemma cdf_at_left: \"(cdf M \\<longlongrightarrow> measure M {..<a}) (at_left a)\"\nproof (rule tendsto_at_left_sequentially[of \"a - 1\"])\n  fix f :: \"nat \\<Rightarrow> real\" and x assume f: \"incseq f\" \"f \\<longlonglongrightarrow> a\" \"\\<And>x. f x < a\" \"\\<And>x. a - 1 < f x\"\n  then have \"(\\<lambda>n. cdf M (f n)) \\<longlonglongrightarrow> measure M (\\<Union>i. {.. f i})\"\n    using \\<open>incseq f\\<close> unfolding cdf_def\n    by (intro finite_Lim_measure_incseq) (auto simp: incseq_def)\n  also have \"(\\<Union>i. {.. f i}) = {..<a}\"\n    by (auto dest!: order_tendstoD(1)[OF f(2)] eventually_happens'[OF sequentially_bot]\n             intro: less_imp_le le_less_trans f(3))\n  finally show \"(\\<lambda>n. cdf M (f n)) \\<longlonglongrightarrow> measure M {..<a}\"\n    by (simp add: cdf_def)\nqed auto\n\nlemma isCont_cdf: \"isCont (cdf M) x \\<longleftrightarrow> measure M {x} = 0\"\nproof -\n  have \"isCont (cdf M) x \\<longleftrightarrow> cdf M x = measure M {..<x}\"\n    by (auto simp: continuous_at_split cdf_is_right_cont continuous_within[where s=\"{..< _}\"]\n                   cdf_at_left tendsto_unique[OF _ cdf_at_left])\n  also have \"cdf M x = measure M {..<x} \\<longleftrightarrow> measure M {x} = 0\"\n    unfolding cdf_def ivl_disj_un(2)[symmetric]\n    by (subst finite_measure_Union) auto\n  finally show ?thesis .\nqed\n\nlemma countable_atoms: \"countable {x. measure M {x} > 0}\"\n  using countable_support unfolding zero_less_measure_iff .\n\nend\n\nlocale real_distribution = prob_space M for M :: \"real measure\" +\n  assumes events_eq_borel [simp, measurable_cong]: \"sets M = sets borel\"\nbegin\n\nlemma finite_borel_measure_M: \"finite_borel_measure M\"\n  by standard auto\n\nsublocale finite_borel_measure M\n  by (rule finite_borel_measure_M)\n\nlemma space_eq_univ [simp]: \"space M = UNIV\"\n  using events_eq_borel[THEN sets_eq_imp_space_eq] by simp\n\nlemma cdf_bounded_prob: \"\\<And>x. cdf M x \\<le> 1\"\n  by (subst prob_space [symmetric], rule cdf_bounded)\n\nlemma cdf_lim_infty_prob: \"(\\<lambda>i. cdf M (real i)) \\<longlonglongrightarrow> 1\"\n  by (subst prob_space [symmetric], rule cdf_lim_infty)\n\nlemma cdf_lim_at_top_prob: \"(cdf M \\<longlongrightarrow> 1) at_top\"\n  by (subst prob_space [symmetric], rule cdf_lim_at_top)\n\nlemma measurable_finite_borel [simp]:\n  \"f \\<in> borel_measurable borel \\<Longrightarrow> f \\<in> borel_measurable M\"\n  by (rule borel_measurable_subalgebra[where N=borel]) auto\n\nend\n\nlemma (in prob_space) real_distribution_distr [intro, simp]:\n  \"random_variable borel X \\<Longrightarrow> real_distribution (distr M borel X)\"\n  unfolding real_distribution_def real_distribution_axioms_def by (auto intro!: prob_space_distr)\n\nsubsection \\<open>Uniqueness\\<close>\n\nlemma (in finite_borel_measure) emeasure_Ioc:\n  assumes \"a \\<le> b\" shows \"emeasure M {a <.. b} = cdf M b - cdf M a\"\nproof -\n  have \"{a <.. b} = {..b} - {..a}\"\n    by auto\n  moreover have \"{..x} \\<in> sets M\" for x\n    using atMost_borel[of x] M_is_borel by auto\n  moreover note \\<open>a \\<le> b\\<close>\n  ultimately show ?thesis\n    by (simp add: emeasure_eq_measure finite_measure_Diff cdf_def)\nqed\n\nlemma cdf_unique':\n  fixes M1 M2\n  assumes \"finite_borel_measure M1\" and \"finite_borel_measure M2\"\n  assumes \"cdf M1 = cdf M2\"\n  shows \"M1 = M2\"\nproof (rule measure_eqI_generator_eq[where \\<Omega>=UNIV])\n  fix X assume \"X \\<in> range (\\<lambda>(a, b). {a<..b::real})\"\n  then obtain a b where Xeq: \"X = {a<..b}\" by auto\n  then show \"emeasure M1 X = emeasure M2 X\"\n    by (cases \"a \\<le> b\")\n       (simp_all add: assms(1,2)[THEN finite_borel_measure.emeasure_Ioc] assms(3))\nnext\n  show \"(\\<Union>i. {- real (i::nat)<..real i}) = UNIV\"\n    by (rule UN_Ioc_eq_UNIV)\nqed (auto simp: finite_borel_measure.emeasure_Ioc[OF assms(1)]\n  assms(1,2)[THEN finite_borel_measure.M_is_borel] borel_sigma_sets_Ioc\n  Int_stable_def)\n\nlemma cdf_unique:\n  \"real_distribution M1 \\<Longrightarrow> real_distribution M2 \\<Longrightarrow> cdf M1 = cdf M2 \\<Longrightarrow> M1 = M2\"\n  using cdf_unique'[of M1 M2] by (simp add: real_distribution.finite_borel_measure_M)\n\nlemma\n  fixes F :: \"real \\<Rightarrow> real\"\n  assumes nondecF : \"\\<And> x y. x \\<le> y \\<Longrightarrow> F x \\<le> F y\"\n    and right_cont_F : \"\\<And>a. continuous (at_right a) F\"\n    and lim_F_at_bot : \"(F \\<longlongrightarrow> 0) at_bot\"\n    and lim_F_at_top : \"(F \\<longlongrightarrow> m) at_top\"\n    and m: \"0 \\<le> m\"\n  shows interval_measure_UNIV: \"emeasure (interval_measure F) UNIV = m\"\n    and finite_borel_measure_interval_measure: \"finite_borel_measure (interval_measure F)\"\nproof -\n  let ?F = \"interval_measure F\"\n  { have \"ennreal (m - 0) = (SUP i. ennreal (F (real i) - F (- real i)))\"\n      by (intro LIMSEQ_unique[OF _ LIMSEQ_SUP] tendsto_ennrealI tendsto_intros\n                lim_F_at_bot[THEN filterlim_compose] lim_F_at_top[THEN filterlim_compose]\n                lim_F_at_bot[THEN filterlim_compose] filterlim_real_sequentially\n                filterlim_uminus_at_top[THEN iffD1])\n         (auto simp: incseq_def nondecF intro!: diff_mono)\n    also have \"\\<dots> = (SUP i. emeasure ?F {- real i<..real i})\"\n      by (subst emeasure_interval_measure_Ioc) (simp_all add: nondecF right_cont_F)\n    also have \"\\<dots> = emeasure ?F (\\<Union>i::nat. {- real i<..real i})\"\n      by (rule SUP_emeasure_incseq) (auto simp: incseq_def)\n    also have \"(\\<Union>i. {- real (i::nat)<..real i}) = space ?F\"\n      by (simp add: UN_Ioc_eq_UNIV)\n    finally have \"emeasure ?F (space ?F) = m\"\n      by simp }\n  note * = this\n  then show \"emeasure (interval_measure F) UNIV = m\"\n    by simp\n\n  interpret finite_measure ?F\n  proof\n    show \"emeasure ?F (space ?F) \\<noteq> \\<infinity>\"\n      using * by simp\n  qed\n  show \"finite_borel_measure (interval_measure F)\"\n    proof qed simp_all\nqed\n\nlemma real_distribution_interval_measure:\n  fixes F :: \"real \\<Rightarrow> real\"\n  assumes nondecF : \"\\<And> x y. x \\<le> y \\<Longrightarrow> F x \\<le> F y\" and\n    right_cont_F : \"\\<And>a. continuous (at_right a) F\" and\n    lim_F_at_bot : \"(F \\<longlongrightarrow> 0) at_bot\" and\n    lim_F_at_top : \"(F \\<longlongrightarrow> 1) at_top\"\n  shows \"real_distribution (interval_measure F)\"\nproof -\n  let ?F = \"interval_measure F\"\n  interpret prob_space ?F\n    proof qed (use interval_measure_UNIV[OF assms] in simp)\n  show ?thesis\n    proof qed simp_all\nqed\n\nlemma\n  fixes F :: \"real \\<Rightarrow> real\"\n  assumes nondecF : \"\\<And> x y. x \\<le> y \\<Longrightarrow> F x \\<le> F y\" and\n    right_cont_F : \"\\<And>a. continuous (at_right a) F\" and\n    lim_F_at_bot : \"(F \\<longlongrightarrow> 0) at_bot\"\n  shows emeasure_interval_measure_Iic: \"emeasure (interval_measure F) {.. x} = F x\"\n    and measure_interval_measure_Iic: \"measure (interval_measure F) {.. x} = F x\"\n  unfolding cdf_def\nproof -\n  have F_nonneg[simp]: \"0 \\<le> F y\" for y\n    using lim_F_at_bot by (rule tendsto_upperbound) (auto simp: eventually_at_bot_linorder nondecF intro!: exI[of _ y])\n\n  have \"emeasure (interval_measure F) (\\<Union>i::nat. {-real i <.. x}) = F x - ennreal 0\"\n  proof (intro LIMSEQ_unique[OF Lim_emeasure_incseq])\n    have \"(\\<lambda>i. F x - F (- real i)) \\<longlonglongrightarrow> F x - 0\"\n      by (intro tendsto_intros lim_F_at_bot[THEN filterlim_compose] filterlim_real_sequentially\n                filterlim_uminus_at_top[THEN iffD1])\n    from tendsto_ennrealI[OF this]\n    show \"(\\<lambda>i. emeasure (interval_measure F) {- real i<..x}) \\<longlonglongrightarrow> F x - ennreal 0\"\n      apply (rule filterlim_cong[THEN iffD1, rotated 3])\n        apply simp\n       apply simp\n      apply (rule eventually_sequentiallyI[where c=\"nat (ceiling (- x))\"])\n      apply (simp add: emeasure_interval_measure_Ioc right_cont_F nondecF)\n      done\n  qed (auto simp: incseq_def)\n  also have \"(\\<Union>i::nat. {-real i <.. x}) = {..x}\"\n    by auto (metis minus_minus neg_less_iff_less reals_Archimedean2)\n  finally show \"emeasure (interval_measure F) {..x} = F x\"\n    by simp\n  then show \"measure (interval_measure F) {..x} = F x\"\n    by (simp add: measure_def)\nqed\n\nlemma cdf_interval_measure:\n  \"(\\<And> x y. x \\<le> y \\<Longrightarrow> F x \\<le> F y) \\<Longrightarrow> (\\<And>a. continuous (at_right a) F) \\<Longrightarrow> (F \\<longlongrightarrow> 0) at_bot \\<Longrightarrow> cdf (interval_measure F) = F\"\n  by (simp add: cdf_def fun_eq_iff measure_interval_measure_Iic)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Probability/Distribution_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.7639904972388817}}
{"text": "(*<*)theory AB imports Main begin(*>*)\n\nsection\\<open>Case Study: A Context Free Grammar\\<close>\n\ntext\\<open>\\label{sec:CFG}\n\\index{grammars!defining inductively|(}%\nGrammars are nothing but shorthands for inductive definitions of nonterminals\nwhich represent sets of strings. For example, the production\n$A \\to B c$ is short for\n\\[ w \\in B \\Longrightarrow wc \\in A \\]\nThis section demonstrates this idea with an example\ndue to Hopcroft and Ullman, a grammar for generating all words with an\nequal number of $a$'s and~$b$'s:\n\\begin{eqnarray}\nS &\\to& \\epsilon \\mid b A \\mid a B \\nonumber\\\\\nA &\\to& a S \\mid b A A \\nonumber\\\\\nB &\\to& b S \\mid a B B \\nonumber\n\\end{eqnarray}\nAt the end we say a few words about the relationship between\nthe original proof \\<^cite>\\<open>\\<open>p.\\ts81\\<close> in HopcroftUllman\\<close> and our formal version.\n\nWe start by fixing the alphabet, which consists only of \\<^term>\\<open>a\\<close>'s\nand~\\<^term>\\<open>b\\<close>'s:\n\\<close>\n\ndatatype alfa = a | b\n\ntext\\<open>\\noindent\nFor convenience we include the following easy lemmas as simplification rules:\n\\<close>\n\n\n\ntext\\<open>\\noindent\nWords over this alphabet are of type \\<^typ>\\<open>alfa list\\<close>, and\nthe three nonterminals are declared as sets of such words.\nThe productions above are recast as a \\emph{mutual} inductive\ndefinition\\index{inductive definition!simultaneous}\nof \\<^term>\\<open>S\\<close>, \\<^term>\\<open>A\\<close> and~\\<^term>\\<open>B\\<close>:\n\\<close>\n\ninductive_set\n  S :: \"alfa list set\" and\n  A :: \"alfa list set\" and\n  B :: \"alfa list set\"\nwhere\n  \"[] \\<in> S\"\n| \"w \\<in> A \\<Longrightarrow> b#w \\<in> S\"\n| \"w \\<in> B \\<Longrightarrow> a#w \\<in> S\"\n\n| \"w \\<in> S        \\<Longrightarrow> a#w   \\<in> A\"\n| \"\\<lbrakk> v\\<in>A; w\\<in>A \\<rbrakk> \\<Longrightarrow> b#v@w \\<in> A\"\n\n| \"w \\<in> S            \\<Longrightarrow> b#w   \\<in> B\"\n| \"\\<lbrakk> v \\<in> B; w \\<in> B \\<rbrakk> \\<Longrightarrow> a#v@w \\<in> B\"\n\ntext\\<open>\\noindent\nFirst we show that all words in \\<^term>\\<open>S\\<close> contain the same number of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s. Since the definition of \\<^term>\\<open>S\\<close> is by mutual\ninduction, so is the proof: we show at the same time that all words in\n\\<^term>\\<open>A\\<close> contain one more \\<^term>\\<open>a\\<close> than \\<^term>\\<open>b\\<close> and all words in \\<^term>\\<open>B\\<close> contain one more \\<^term>\\<open>b\\<close> than \\<^term>\\<open>a\\<close>.\n\\<close>\n\nlemma correctness:\n  \"(w \\<in> S \\<longrightarrow> size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b])     \\<and>\n   (w \\<in> A \\<longrightarrow> size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b] + 1) \\<and>\n   (w \\<in> B \\<longrightarrow> size[x\\<leftarrow>w. x=b] = size[x\\<leftarrow>w. x=a] + 1)\"\n\ntxt\\<open>\\noindent\nThese propositions are expressed with the help of the predefined \\<^term>\\<open>filter\\<close> function on lists, which has the convenient syntax \\<open>[x\\<leftarrow>xs. P\nx]\\<close>, the list of all elements \\<^term>\\<open>x\\<close> in \\<^term>\\<open>xs\\<close> such that \\<^prop>\\<open>P x\\<close>\nholds. Remember that on lists \\<open>size\\<close> and \\<open>length\\<close> are synonymous.\n\nThe proof itself is by rule induction and afterwards automatic:\n\\<close>\n\nby (rule S_A_B.induct, auto)\n\ntext\\<open>\\noindent\nThis may seem surprising at first, and is indeed an indication of the power\nof inductive definitions. But it is also quite straightforward. For example,\nconsider the production $A \\to b A A$: if $v,w \\in A$ and the elements of $A$\ncontain one more $a$ than~$b$'s, then $bvw$ must again contain one more $a$\nthan~$b$'s.\n\nAs usual, the correctness of syntactic descriptions is easy, but completeness\nis hard: does \\<^term>\\<open>S\\<close> contain \\emph{all} words with an equal number of\n\\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s? It turns out that this proof requires the\nfollowing lemma: every string with two more \\<^term>\\<open>a\\<close>'s than \\<^term>\\<open>b\\<close>'s can be cut somewhere such that each half has one more \\<^term>\\<open>a\\<close> than\n\\<^term>\\<open>b\\<close>. This is best seen by imagining counting the difference between the\nnumber of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s starting at the left end of the\nword. We start with 0 and end (at the right end) with 2. Since each move to the\nright increases or decreases the difference by 1, we must have passed through\n1 on our way from 0 to 2. Formally, we appeal to the following discrete\nintermediate value theorem @{thm[source]nat0_intermed_int_val}\n@{thm[display,margin=60]nat0_intermed_int_val[no_vars]}\nwhere \\<^term>\\<open>f\\<close> is of type \\<^typ>\\<open>nat \\<Rightarrow> int\\<close>, \\<^typ>\\<open>int\\<close> are the integers,\n\\<open>\\<bar>.\\<bar>\\<close> is the absolute value function\\footnote{See\nTable~\\ref{tab:ascii} in the Appendix for the correct \\textsc{ascii}\nsyntax.}, and \\<^term>\\<open>1::int\\<close> is the integer 1 (see \\S\\ref{sec:numbers}).\n\nFirst we show that our specific function, the difference between the\nnumbers of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s, does indeed only change by 1 in every\nmove to the right. At this point we also start generalizing from \\<^term>\\<open>a\\<close>'s\nand \\<^term>\\<open>b\\<close>'s to an arbitrary property \\<^term>\\<open>P\\<close>. Otherwise we would have\nto prove the desired lemma twice, once as stated above and once with the\nroles of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s interchanged.\n\\<close>\n\nlemma step1: \"\\<forall>i < size w.\n  \\<bar>(int(size[x\\<leftarrow>take (i+1) w. P x])-int(size[x\\<leftarrow>take (i+1) w. \\<not>P x]))\n   - (int(size[x\\<leftarrow>take i w. P x])-int(size[x\\<leftarrow>take i w. \\<not>P x]))\\<bar> \\<le> 1\"\n\ntxt\\<open>\\noindent\nThe lemma is a bit hard to read because of the coercion function\n\\<open>int :: nat \\<Rightarrow> int\\<close>. It is required because \\<^term>\\<open>size\\<close> returns\na natural number, but subtraction on type~\\<^typ>\\<open>nat\\<close> will do the wrong thing.\nFunction \\<^term>\\<open>take\\<close> is predefined and \\<^term>\\<open>take i xs\\<close> is the prefix of\nlength \\<^term>\\<open>i\\<close> of \\<^term>\\<open>xs\\<close>; below we also need \\<^term>\\<open>drop i xs\\<close>, which\nis what remains after that prefix has been dropped from \\<^term>\\<open>xs\\<close>.\n\nThe proof is by induction on \\<^term>\\<open>w\\<close>, with a trivial base case, and a not\nso trivial induction step. Since it is essentially just arithmetic, we do not\ndiscuss it.\n\\<close>\n\napply(induct_tac w)\napply(auto simp add: abs_if take_Cons split: nat.split)\ndone\n\ntext\\<open>\nFinally we come to the above-mentioned lemma about cutting in half a word with two more elements of one sort than of the other sort:\n\\<close>\n\nlemma part1:\n \"size[x\\<leftarrow>w. P x] = size[x\\<leftarrow>w. \\<not>P x]+2 \\<Longrightarrow>\n  \\<exists>i\\<le>size w. size[x\\<leftarrow>take i w. P x] = size[x\\<leftarrow>take i w. \\<not>P x]+1\"\n\ntxt\\<open>\\noindent\nThis is proved by \\<open>force\\<close> with the help of the intermediate value theorem,\ninstantiated appropriately and with its first premise disposed of by lemma\n@{thm[source]step1}:\n\\<close>\n\napply(insert nat0_intermed_int_val[OF step1, of \"P\" \"w\" \"1\"])\nby force\n\ntext\\<open>\\noindent\n\nLemma @{thm[source]part1} tells us only about the prefix \\<^term>\\<open>take i w\\<close>.\nAn easy lemma deals with the suffix \\<^term>\\<open>drop i w\\<close>:\n\\<close>\n\n\nlemma part2:\n  \"\\<lbrakk>size[x\\<leftarrow>take i w @ drop i w. P x] =\n    size[x\\<leftarrow>take i w @ drop i w. \\<not>P x]+2;\n    size[x\\<leftarrow>take i w. P x] = size[x\\<leftarrow>take i w. \\<not>P x]+1\\<rbrakk>\n   \\<Longrightarrow> size[x\\<leftarrow>drop i w. P x] = size[x\\<leftarrow>drop i w. \\<not>P x]+1\"\nby(simp del: append_take_drop_id)\n\ntext\\<open>\\noindent\nIn the proof we have disabled the normally useful lemma\n\\begin{isabelle}\n@{thm append_take_drop_id[no_vars]}\n\\rulename{append_take_drop_id}\n\\end{isabelle}\nto allow the simplifier to apply the following lemma instead:\n@{text[display]\"[x\\<in>xs@ys. P x] = [x\\<in>xs. P x] @ [x\\<in>ys. P x]\"}\n\nTo dispose of trivial cases automatically, the rules of the inductive\ndefinition are declared simplification rules:\n\\<close>\n\ndeclare S_A_B.intros[simp]\n\ntext\\<open>\\noindent\nThis could have been done earlier but was not necessary so far.\n\nThe completeness theorem tells us that if a word has the same number of\n\\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s, then it is in \\<^term>\\<open>S\\<close>, and similarly \nfor \\<^term>\\<open>A\\<close> and \\<^term>\\<open>B\\<close>:\n\\<close>\n\ntheorem completeness:\n  \"(size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b]     \\<longrightarrow> w \\<in> S) \\<and>\n   (size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b] + 1 \\<longrightarrow> w \\<in> A) \\<and>\n   (size[x\\<leftarrow>w. x=b] = size[x\\<leftarrow>w. x=a] + 1 \\<longrightarrow> w \\<in> B)\"\n\ntxt\\<open>\\noindent\nThe proof is by induction on \\<^term>\\<open>w\\<close>. Structural induction would fail here\nbecause, as we can see from the grammar, we need to make bigger steps than\nmerely appending a single letter at the front. Hence we induct on the length\nof \\<^term>\\<open>w\\<close>, using the induction rule @{thm[source]length_induct}:\n\\<close>\n\napply(induct_tac w rule: length_induct)\napply(rename_tac w)\n\ntxt\\<open>\\noindent\nThe \\<open>rule\\<close> parameter tells \\<open>induct_tac\\<close> explicitly which induction\nrule to use. For details see \\S\\ref{sec:complete-ind} below.\nIn this case the result is that we may assume the lemma already\nholds for all words shorter than \\<^term>\\<open>w\\<close>. Because the induction step renames\nthe induction variable we rename it back to \\<open>w\\<close>.\n\nThe proof continues with a case distinction on \\<^term>\\<open>w\\<close>,\non whether \\<^term>\\<open>w\\<close> is empty or not.\n\\<close>\n\napply(case_tac w)\n apply(simp_all)\n(*<*)apply(rename_tac x v)(*>*)\n\ntxt\\<open>\\noindent\nSimplification disposes of the base case and leaves only a conjunction\nof two step cases to be proved:\nif \\<^prop>\\<open>w = a#v\\<close> and @{prop[display]\"size[x\\<in>v. x=a] = size[x\\<in>v. x=b]+2\"} then\n\\<^prop>\\<open>b#v \\<in> A\\<close>, and similarly for \\<^prop>\\<open>w = b#v\\<close>.\nWe only consider the first case in detail.\n\nAfter breaking the conjunction up into two cases, we can apply\n@{thm[source]part1} to the assumption that \\<^term>\\<open>w\\<close> contains two more \\<^term>\\<open>a\\<close>'s than \\<^term>\\<open>b\\<close>'s.\n\\<close>\n\napply(rule conjI)\n apply(clarify)\n apply(frule part1[of \"\\<lambda>x. x=a\", simplified])\n apply(clarify)\ntxt\\<open>\\noindent\nThis yields an index \\<^prop>\\<open>i \\<le> length v\\<close> such that\n@{prop[display]\"length [x\\<leftarrow>take i v . x = a] = length [x\\<leftarrow>take i v . x = b] + 1\"}\nWith the help of @{thm[source]part2} it follows that\n@{prop[display]\"length [x\\<leftarrow>drop i v . x = a] = length [x\\<leftarrow>drop i v . x = b] + 1\"}\n\\<close>\n\n apply(drule part2[of \"\\<lambda>x. x=a\", simplified])\n  apply(assumption)\n\ntxt\\<open>\\noindent\nNow it is time to decompose \\<^term>\\<open>v\\<close> in the conclusion \\<^prop>\\<open>b#v \\<in> A\\<close>\ninto \\<^term>\\<open>take i v @ drop i v\\<close>,\n\\<close>\n\n apply(rule_tac n1=i and t=v in subst[OF append_take_drop_id])\n\ntxt\\<open>\\noindent\n(the variables \\<^term>\\<open>n1\\<close> and \\<^term>\\<open>t\\<close> are the result of composing the\ntheorems @{thm[source]subst} and @{thm[source]append_take_drop_id})\nafter which the appropriate rule of the grammar reduces the goal\nto the two subgoals \\<^prop>\\<open>take i v \\<in> A\\<close> and \\<^prop>\\<open>drop i v \\<in> A\\<close>:\n\\<close>\n\n apply(rule S_A_B.intros)\n\ntxt\\<open>\nBoth subgoals follow from the induction hypothesis because both \\<^term>\\<open>take i\nv\\<close> and \\<^term>\\<open>drop i v\\<close> are shorter than \\<^term>\\<open>w\\<close>:\n\\<close>\n\n  apply(force simp add: min_less_iff_disj)\n apply(force split: nat_diff_split)\n\ntxt\\<open>\nThe case \\<^prop>\\<open>w = b#v\\<close> is proved analogously:\n\\<close>\n\napply(clarify)\napply(frule part1[of \"\\<lambda>x. x=b\", simplified])\napply(clarify)\napply(drule part2[of \"\\<lambda>x. x=b\", simplified])\n apply(assumption)\napply(rule_tac n1=i and t=v in subst[OF append_take_drop_id])\napply(rule S_A_B.intros)\n apply(force simp add: min_less_iff_disj)\nby(force simp add: min_less_iff_disj split: nat_diff_split)\n\ntext\\<open>\nWe conclude this section with a comparison of our proof with \nHopcroft\\index{Hopcroft, J. E.} and Ullman's\\index{Ullman, J. D.}\n\\<^cite>\\<open>\\<open>p.\\ts81\\<close> in HopcroftUllman\\<close>.\nFor a start, the textbook\ngrammar, for no good reason, excludes the empty word, thus complicating\nmatters just a little bit: they have 8 instead of our 7 productions.\n\nMore importantly, the proof itself is different: rather than\nseparating the two directions, they perform one induction on the\nlength of a word. This deprives them of the beauty of rule induction,\nand in the easy direction (correctness) their reasoning is more\ndetailed than our \\<open>auto\\<close>. For the hard part (completeness), they\nconsider just one of the cases that our \\<open>simp_all\\<close> disposes of\nautomatically. Then they conclude the proof by saying about the\nremaining cases: ``We do this in a manner similar to our method of\nproof for part (1); this part is left to the reader''. But this is\nprecisely the part that requires the intermediate value theorem and\nthus is not at all similar to the other cases (which are automatic in\nIsabelle). The authors are at least cavalier about this point and may\neven have overlooked the slight difficulty lurking in the omitted\ncases.  Such errors are found in many pen-and-paper proofs when they\nare scrutinized formally.%\n\\index{grammars!defining inductively|)}\n\\<close>\n\n(*<*)end(*>*)\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/Inductive/AB.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.8757869900269367, "lm_q1q2_score": 0.7639904815273293}}
{"text": "(*  Author:  Sébastien Gouëzel   sebastien.gouezel@univ-rennes1.fr\n    License: BSD\n*)\n\nsection \\<open>Isometries\\<close>\n\ntheory Isometries\n  imports Library_Complements Hausdorff_Distance\nbegin\n\ntext \\<open>Isometries, i.e., functions that preserve distances, show up very often in mathematics.\nWe introduce a dedicated definition, and show its basic properties.\\<close>\n\ndefinition isometry_on::\"('a::metric_space) set \\<Rightarrow> ('a \\<Rightarrow> ('b::metric_space)) \\<Rightarrow> bool\"\n  where \"isometry_on X f = (\\<forall>x \\<in> X. \\<forall>y \\<in> X. dist (f x) (f y) = dist x y)\"\n\ndefinition isometry :: \"('a::metric_space \\<Rightarrow> 'b::metric_space) \\<Rightarrow> bool\"\n  where \"isometry f \\<equiv> isometry_on UNIV f \\<and> range f = UNIV\"\n\nlemma isometry_on_subset:\n  assumes \"isometry_on X f\"\n          \"Y \\<subseteq> X\"\n  shows \"isometry_on Y f\"\nusing assms unfolding isometry_on_def by auto\n\nlemma isometry_onI [intro?]:\n  assumes \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) = dist x y\"\n  shows \"isometry_on X f\"\nusing assms unfolding isometry_on_def by auto\n\nlemma isometry_onD:\n  assumes \"isometry_on X f\"\n          \"x \\<in> X\" \"y \\<in> X\"\n  shows \"dist (f x) (f y) = dist x y\"\nusing assms unfolding isometry_on_def by auto\n\nlemma isometryI [intro?]:\n  assumes \"\\<And>x y. dist (f x) (f y) = dist x y\"\n          \"range f = UNIV\"\n  shows \"isometry f\"\nunfolding isometry_def isometry_on_def using assms by auto\n\nlemma\n  assumes \"isometry_on X f\"\n  shows isometry_on_lipschitz: \"1-lipschitz_on X f\"\n    and isometry_on_uniformly_continuous: \"uniformly_continuous_on X f\"\n    and isometry_on_continuous: \"continuous_on X f\"\nproof -\n  show \"1-lipschitz_on X f\" apply (rule lipschitz_onI) using isometry_onD[OF assms] by auto\n  then show \"uniformly_continuous_on X f\" \"continuous_on X f\"\n    using lipschitz_on_uniformly_continuous lipschitz_on_continuous_on by auto\nqed\n\nlemma isometryD:\n  assumes \"isometry f\"\n  shows \"isometry_on UNIV f\"\n        \"dist (f x) (f y) = dist x y\"\n        \"range f = UNIV\"\n        \"1-lipschitz_on UNIV f\"\n        \"uniformly_continuous_on UNIV f\"\n        \"continuous_on UNIV f\"\nusing assms unfolding isometry_def isometry_on_def apply auto\nusing isometry_on_lipschitz isometry_on_uniformly_continuous isometry_on_continuous assms unfolding isometry_def by blast+\n\nlemma isometry_on_injective:\n  assumes \"isometry_on X f\"\n  shows \"inj_on f X\"\nusing assms inj_on_def isometry_on_def by force\n\nlemma isometry_on_compose:\n  assumes \"isometry_on X f\"\n          \"isometry_on (f`X) g\"\n  shows \"isometry_on X (\\<lambda>x. g(f x))\"\nusing assms unfolding isometry_on_def by auto\n\n\n\nlemma isometry_on_inverse:\n  assumes \"isometry_on X f\"\n  shows \"isometry_on (f`X) (inv_into X f)\"\n        \"\\<And>x. x \\<in> X \\<Longrightarrow> (inv_into X f) (f x) = x\"\n        \"\\<And>y. y \\<in> f`X \\<Longrightarrow> f (inv_into X f y) = y\"\n        \"bij_betw f X (f`X)\"\nproof -\n  show *: \"bij_betw f X (f`X)\"\n    using assms unfolding bij_betw_def inj_on_def isometry_on_def by force\n  show \"isometry_on (f`X) (inv_into X f)\"\n    using assms unfolding isometry_on_def\n    by (auto) (metis (mono_tags, lifting) dist_eq_0_iff inj_on_def inv_into_f_f)\n  fix x assume \"x \\<in> X\"\n  then show \"(inv_into X f) (f x) = x\"\n    using * by (simp add: bij_betw_def)\nnext\n  fix y assume \"y \\<in> f`X\"\n  then show \"f (inv_into X f y) = y\"\n    by (simp add: f_inv_into_f)\nqed\n\nlemma isometry_inverse:\n  assumes \"isometry f\"\n  shows \"isometry (inv f)\"\n        \"bij f\"\nusing isometry_on_inverse[OF isometryD(1)[OF assms]] isometryD(3)[OF assms]\nunfolding isometry_def by (auto simp add: bij_imp_bij_inv bij_is_surj)\n\nlemma isometry_on_homeomorphism:\n  assumes \"isometry_on X f\"\n  shows \"homeomorphism X (f`X) f (inv_into X f)\"\n        \"homeomorphism_on X f\"\n        \"X homeomorphic f`X\"\nproof -\n  show *: \"homeomorphism X (f`X) f (inv_into X f)\"\n    apply (rule homeomorphismI) using uniformly_continuous_imp_continuous[OF isometry_on_uniformly_continuous]\n    isometry_on_inverse[OF assms] assms by auto\n  then show \"X homeomorphic f`X\"\n    unfolding homeomorphic_def by auto\n  show \"homeomorphism_on X f\"\n    unfolding homeomorphism_on_def using * by auto\nqed\n\nlemma isometry_homeomorphism:\n  fixes f::\"('a::metric_space) \\<Rightarrow> ('b::metric_space)\"\n  assumes \"isometry f\"\n  shows \"homeomorphism UNIV UNIV f (inv f)\"\n        \"(UNIV::'a set) homeomorphic (UNIV::'b set)\"\nusing isometry_on_homeomorphism[OF isometryD(1)[OF assms]] isometryD(3)[OF assms] by auto\n\nlemma isometry_on_closure:\n  assumes \"isometry_on X f\"\n          \"continuous_on (closure X) f\"\n  shows \"isometry_on (closure X) f\"\nproof (rule isometry_onI)\n  fix x y assume \"x \\<in> closure X\" \"y \\<in> closure X\"\n  obtain u v::\"nat \\<Rightarrow> 'a\" where *: \"\\<And>n. u n \\<in> X\" \"u \\<longlonglongrightarrow> x\"\n                                   \"\\<And>n. v n \\<in> X\" \"v \\<longlonglongrightarrow> y\"\n    using \\<open>x \\<in> closure X\\<close> \\<open>y \\<in> closure X\\<close> unfolding closure_sequential by blast\n  have \"(\\<lambda>n. f (u n)) \\<longlonglongrightarrow> f x\"\n    using *(1) *(2) \\<open>x \\<in> closure X\\<close> \\<open>continuous_on (closure X) f\\<close>\n    unfolding comp_def continuous_on_closure_sequentially[of X f] by auto\n  moreover have \"(\\<lambda>n. f (v n)) \\<longlonglongrightarrow> f y\"\n    using *(3) *(4) \\<open>y \\<in> closure X\\<close> \\<open>continuous_on (closure X) f\\<close>\n    unfolding comp_def continuous_on_closure_sequentially[of X f] by auto\n  ultimately have \"(\\<lambda>n. dist (f (u n)) (f (v n))) \\<longlonglongrightarrow> dist (f x) (f y)\"\n    by (simp add: tendsto_dist)\n  then have \"(\\<lambda>n. dist (u n) (v n)) \\<longlonglongrightarrow> dist (f x) (f y)\"\n    using assms(1) *(1) *(3) unfolding isometry_on_def by auto\n  moreover have \"(\\<lambda>n. dist (u n) (v n)) \\<longlonglongrightarrow> dist x y\"\n    using *(2) *(4) by (simp add: tendsto_dist)\n  ultimately show \"dist (f x) (f y) = dist x y\" using LIMSEQ_unique by auto\nqed\n\nlemma isometry_extend_closure:\n  fixes f::\"('a::metric_space) \\<Rightarrow> ('b::complete_space)\"\n  assumes \"isometry_on X f\"\n  shows \"\\<exists>g. isometry_on (closure X) g \\<and> (\\<forall>x\\<in>X. g x = f x)\"\nproof -\n  obtain g where g: \"\\<And>x. x \\<in> X \\<Longrightarrow> g x = f x\" \"uniformly_continuous_on (closure X) g\"\n    using uniformly_continuous_on_extension_on_closure[OF isometry_on_uniformly_continuous[OF assms]] by metis\n  have \"isometry_on (closure X) g\"\n    apply (rule isometry_on_closure, rule isometry_on_cong[OF assms])\n    using g uniformly_continuous_imp_continuous[OF g(2)] by auto\n  then show ?thesis using g(1) by auto\nqed\n\nlemma isometry_on_complete_image:\n  assumes \"isometry_on X f\"\n          \"complete X\"\n  shows \"complete (f`X)\"\nproof (rule completeI)\n  fix u :: \"nat \\<Rightarrow> 'b\" assume u: \"\\<forall>n. u n \\<in> f`X\" \"Cauchy u\"\n  define v where \"v = (\\<lambda>n. inv_into X f (u n))\"\n  have \"v n \\<in> X\" for n\n    unfolding v_def by (simp add: inv_into_into u(1))\n  have \"dist (v n) (v m) = dist (u n) (u m)\" for m n\n    using u(1) isometry_on_inverse[OF \\<open>isometry_on X f\\<close>] unfolding isometry_on_def v_def by (auto simp add: inv_into_into)\n  then have \"Cauchy v\"\n    using u(2) unfolding Cauchy_def by auto\n  obtain l where \"l \\<in> X\" \"v \\<longlonglongrightarrow> l\"\n    apply (rule completeE[OF \\<open>complete X\\<close> _ \\<open>Cauchy v\\<close>]) using \\<open>\\<And>n. v n \\<in> X\\<close> by auto\n  have \"(\\<lambda>n. f (v n)) \\<longlonglongrightarrow> f l\"\n    apply (rule continuous_on_tendsto_compose[OF isometry_on_continuous[OF \\<open>isometry_on X f\\<close>]])\n    using \\<open>\\<And>n. v n \\<in> X\\<close> \\<open>l \\<in> X\\<close> \\<open>v \\<longlonglongrightarrow> l\\<close> by auto\n  moreover have \"f(v n) = u n\" for n\n    unfolding v_def by (simp add: f_inv_into_f u(1))\n  ultimately have \"u \\<longlonglongrightarrow> f l\" by auto\n  then show \"\\<exists>m \\<in> f`X. u \\<longlonglongrightarrow> m\" using \\<open>l \\<in> X\\<close> by auto\nqed\n\nlemma isometry_on_id [simp]:\n  \"isometry_on A (\\<lambda>x. x)\"\n  \"isometry_on A id\"\nunfolding isometry_on_def by auto\n\nlemma isometry_on_add [simp]:\n  \"isometry_on A (\\<lambda>x. x + (t::'a::real_normed_vector))\"\nunfolding isometry_on_def by auto\n\nlemma isometry_on_minus [simp]:\n  \"isometry_on A (\\<lambda>(x::'a::real_normed_vector). -x)\"\nunfolding isometry_on_def by (auto simp add: dist_minus)\n\nlemma isometry_on_diff [simp]:\n  \"isometry_on A (\\<lambda>x. (t::'a::real_normed_vector) - x)\"\nunfolding isometry_on_def by (auto, metis add_uminus_conv_diff dist_add_cancel dist_minus)\n\nlemma isometry_preserves_bounded:\n  assumes \"isometry_on X f\"\n          \"A \\<subseteq> X\"\n  shows \"bounded (f`A) \\<longleftrightarrow> bounded A\"\nunfolding bounded_two_points using assms(2) isometry_onD[OF assms(1)] by auto (metis assms(2) rev_subsetD)+\n\nlemma isometry_preserves_infdist:\n  \"infdist (f x) (f`A) = infdist x A\"\n  if \"isometry_on X f\" \"A \\<subseteq> X\" \"x \\<in> X\"\n  using that by (simp add: infdist_def image_comp isometry_on_def subset_iff)\n\nlemma isometry_preserves_hausdorff_distance:\n  \"hausdorff_distance (f`A) (f`B) = hausdorff_distance A B\"\n  if \"isometry_on X f\" \"A \\<subseteq> X\" \"B \\<subseteq> X\"\n  using that isometry_preserves_infdist [OF that(1) that(2)]\n  isometry_preserves_infdist [OF that(1) that(3)]\n  isometry_preserves_bounded [OF that(1) that(2)]\n  isometry_preserves_bounded [OF that(1) that(3)]\n  by (simp add: hausdorff_distance_def image_comp subset_eq)\n\nlemma isometry_on_UNIV_iterates:\n  fixes f::\"('a::metric_space) \\<Rightarrow> 'a\"\n  assumes \"isometry_on UNIV f\"\n  shows \"isometry_on UNIV (f^^n)\"\nby (induction n, auto, rule isometry_on_compose[of _ _ f], auto intro: isometry_on_subset[OF assms])\n\nlemma isometry_iterates:\n  fixes f::\"('a::metric_space) \\<Rightarrow> 'a\"\n  assumes \"isometry f\"\n  shows \"isometry (f^^n)\"\nusing isometry_on_UNIV_iterates[OF isometryD(1)[OF assms], of n] bij_fn[OF isometry_inverse(2)[OF assms], of n]\nunfolding isometry_def by (simp add: bij_is_surj)\n\nsection \\<open>Geodesic spaces\\<close>\n\ntext \\<open>A geodesic space is a metric space in which any pair of points can be joined by a geodesic segment,\ni.e., an isometrically embedded copy of a segment in the real line. Most spaces in geometry are\ngeodesic. We introduce in this section the corresponding class of metric spaces. First, we study\nproperties of general geodesic segments in metric spaces.\\<close>\n\nsubsection \\<open>Geodesic segments in general metric spaces\\<close>\n\ndefinition geodesic_segment_between::\"('a::metric_space) set \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"geodesic_segment_between G x y = (\\<exists>g::(real \\<Rightarrow> 'a). g 0 = x \\<and> g (dist x y) = y \\<and> isometry_on {0..dist x y} g \\<and> G = g`{0..dist x y})\"\n\ndefinition geodesic_segment::\"('a::metric_space) set \\<Rightarrow> bool\"\n  where \"geodesic_segment G = (\\<exists>x y. geodesic_segment_between G x y)\"\n\ntext \\<open>We also introduce the parametrization of a geodesic segment. It is convenient to use the\nfollowing definition, which guarantees that the point is on $G$ even without checking that $G$\nis a geodesic segment or that the parameter is in the reasonable range: this shortens some\narguments below.\\<close>\n\ndefinition geodesic_segment_param::\"('a::metric_space) set \\<Rightarrow> 'a \\<Rightarrow> real \\<Rightarrow> 'a\"\n  where \"geodesic_segment_param G x t = (if \\<exists>w. w \\<in> G \\<and> dist x w = t then SOME w. w \\<in> G \\<and> dist x w = t else SOME w. w \\<in> G)\"\n\nlemma geodesic_segment_betweenI:\n  assumes \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n  shows \"geodesic_segment_between G x y\"\nunfolding geodesic_segment_between_def apply (rule exI[of _ g]) using assms by auto\n\nlemma geodesic_segmentI [intro, simp]:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"geodesic_segment G\"\nunfolding geodesic_segment_def using assms by auto\n\nlemma geodesic_segmentI2 [intro]:\n  assumes \"isometry_on {a..b} g\" \"a \\<le> (b::real)\"\n  shows \"geodesic_segment_between (g`{a..b}) (g a) (g b)\"\n        \"geodesic_segment (g`{a..b})\"\nproof -\n  define h where \"h = (\\<lambda>t. g (t+a))\"\n  have *: \"isometry_on {0..b-a} h\"\n    apply (rule isometry_onI)\n    using \\<open>isometry_on {a..b} g\\<close> \\<open>a \\<le> b\\<close> by (auto simp add: isometry_on_def h_def)\n  have **: \"dist (h 0) (h (b-a)) = b-a\"\n    using isometry_onD[OF \\<open>isometry_on {0..b-a} h\\<close>, of 0 \"b-a\"] \\<open>a \\<le> b\\<close> unfolding dist_real_def by auto\n  have \"geodesic_segment_between (h`{0..b-a}) (h 0) (h (b-a))\"\n    unfolding geodesic_segment_between_def apply (rule exI[of _ h]) unfolding ** using * by auto\n  moreover have \"g`{a..b} = h`{0..b-a}\"\n    unfolding h_def apply (auto simp add: image_iff)\n    by (metis add.commute atLeastAtMost_iff diff_ge_0_iff_ge diff_right_mono le_add_diff_inverse)\n  moreover have \"h 0 = g a\" \"h (b-a) = g b\" unfolding h_def by auto\n  ultimately show \"geodesic_segment_between (g`{a..b}) (g a) (g b)\" by auto\n  then show \"geodesic_segment (g`{a..b})\" unfolding geodesic_segment_def by auto\nqed\n\nlemma geodesic_segmentD:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"\\<exists>g::(real \\<Rightarrow> _). (g t = x \\<and> g (t + dist x y) = y \\<and> isometry_on {t..t+dist x y} g \\<and> G = g`{t..t+dist x y})\"\nproof -\n  obtain h where h: \"h 0 = x\" \"h (dist x y) = y\" \"isometry_on {0..dist x y} h\" \"G = h`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  have * [simp]: \"(\\<lambda>x. x - t) ` {t..t + dist x y} = {0..dist x y}\" by auto\n  define g where \"g = (\\<lambda>s. h (s - t))\"\n  have \"g t = x\" \"g (t + dist x y) = y\" using h assms(1) unfolding g_def by auto\n  moreover have \"isometry_on {t..t+dist x y} g\"\n    unfolding g_def apply (rule isometry_on_compose[of _ _ h])\n    by (simp add: dist_real_def isometry_on_def, simp add: h(3))\n  moreover have \"g` {t..t + dist x y} = G\" unfolding g_def h(4) using * by (metis image_image)\n  ultimately show ?thesis by auto\nqed\n\nlemma geodesic_segment_endpoints [simp]:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"x \\<in> G\" \"y \\<in> G\" \"G \\<noteq> {}\"\nusing assms unfolding geodesic_segment_between_def\n  by (auto, metis atLeastAtMost_iff image_eqI less_eq_real_def zero_le_dist)\n\nlemma geodesic_segment_commute:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"geodesic_segment_between G y x\"\nproof -\n  obtain g::\"real\\<Rightarrow>'a\" where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  define h::\"real\\<Rightarrow>'a\" where \"h = (\\<lambda>t. g(dist x y-t))\"\n  have \"(\\<lambda>t. dist x y -t)`{0..dist x y} = {0..dist x y}\" by auto\n  then have \"h`{0..dist x y} = G\" unfolding g(4) h_def by (metis image_image)\n  moreover have \"h 0 = y\" \"h (dist x y) = x\" unfolding h_def using g by auto\n  moreover have \"isometry_on {0..dist x y} h\"\n    unfolding h_def apply (rule isometry_on_compose[of _ _ g]) using g(3) by auto\n  ultimately show ?thesis\n    unfolding geodesic_segment_between_def by (auto simp add: dist_commute)\nqed\n\nlemma geodesic_segment_dist:\n  assumes \"geodesic_segment_between G x y\" \"a \\<in> G\"\n  shows \"dist x a + dist a y = dist x y\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  obtain t where t: \"t \\<in> {0..dist x y}\" \"a = g t\"\n    using g(4) assms by auto\n  have \"dist x a = t\" using isometry_onD[OF g(3) _ t(1), of 0]\n    unfolding g(1) dist_real_def t(2) using t(1) by auto\n  moreover have \"dist a y = dist x y - t\" using isometry_onD[OF g(3) _ t(1), of \"dist x y\"]\n    unfolding g(2) dist_real_def t(2) using t(1) by (auto simp add: dist_commute)\n  ultimately show ?thesis by auto\nqed\n\nlemma geodesic_segment_dist_unique:\n  assumes \"geodesic_segment_between G x y\" \"a \\<in> G\" \"b \\<in> G\" \"dist x a = dist x b\"\n  shows \"a = b\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  obtain ta where ta: \"ta \\<in> {0..dist x y}\" \"a = g ta\"\n    using g(4) assms by auto\n  have *: \"dist x a = ta\"\n    unfolding g(1)[symmetric] ta(2) using isometry_onD[OF g(3), of 0 ta]\n    unfolding dist_real_def using ta(1) by auto\n  obtain tb where tb: \"tb \\<in> {0..dist x y}\" \"b = g tb\"\n    using g(4) assms by auto\n  have \"dist x b = tb\"\n    unfolding g(1)[symmetric] tb(2) using isometry_onD[OF g(3), of 0 tb]\n    unfolding dist_real_def using tb(1) by auto\n  then have \"ta = tb\" using * \\<open>dist x a = dist x b\\<close> by auto\n  then show \"a = b\" using ta(2) tb(2) by auto\nqed\n\nlemma geodesic_segment_union:\n  assumes \"dist x z = dist x y + dist y z\"\n          \"geodesic_segment_between G x y\" \"geodesic_segment_between H y z\"\n  shows \"geodesic_segment_between (G \\<union> H) x z\"\n        \"G \\<inter> H = {y}\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  obtain h where h: \"h (dist x y) = y\" \"h (dist x z) = z\" \"isometry_on {dist x y..dist x z} h\" \"H = h`{dist x y..dist x z}\"\n    unfolding \\<open>dist x z = dist x y + dist y z\\<close>\n    using geodesic_segmentD[OF \\<open>geodesic_segment_between H y z\\<close>, of \"dist x y\"] by auto\n  define f where \"f = (\\<lambda>t. if t \\<le> dist x y then g t else h t)\"\n  have fg: \"f t = g t\" if \"t \\<le> dist x y\" for t\n    unfolding f_def using that by auto\n  have fh: \"f t = h t\" if \"t \\<ge> dist x y\" for t\n    unfolding f_def apply (cases \"t > dist x y\") using that g(2) h(1) by auto\n\n  have \"f 0 = x\" \"f (dist x z) = z\" using fg fh g(1) h(2) assms(1) by auto\n\n  have \"f`{0..dist x z} = f`{0..dist x y} \\<union> f`{dist x y..dist x z}\"\n    unfolding assms(1) image_Un[symmetric] by (simp add: ivl_disj_un_two_touch(4))\n  moreover have \"f`{0..dist x y} = G\"\n    unfolding g(4) using fg image_cong by force\n  moreover have \"f`{dist x y..dist x z} = H\"\n    unfolding h(4) using fh image_cong by force\n  ultimately have \"f`{0..dist x z} = G \\<union> H\" by simp\n\n  have Ifg: \"dist (f s) (f t) = s-t\" if \"0 \\<le> t\" \"t \\<le> s\" \"s \\<le> dist x y\" for s t\n    using that fg[of s] fg[of t] isometry_onD[OF g(3), of s t] unfolding dist_real_def by auto\n  have Ifh: \"dist (f s) (f t) = s-t\" if \"dist x y \\<le> t\" \"t \\<le> s\" \"s \\<le> dist x z\" for s t\n    using that fh[of s] fh[of t] isometry_onD[OF h(3), of s t] unfolding dist_real_def by auto\n\n  have I: \"dist (f s) (f t) = s-t\" if \"0 \\<le> t\" \"t \\<le> s\" \"s \\<le> dist x z\" for s t\n  proof -\n    consider \"t \\<le> dist x y \\<and> s \\<ge> dist x y\" | \"s \\<le> dist x y\" | \"t \\<ge> dist x y\" by fastforce\n    then show ?thesis\n    proof (cases)\n      case 1\n      have \"dist (f t) (f s) \\<le> dist (f t) (f (dist x y)) + dist (f (dist x y)) (f s)\"\n        using dist_triangle by auto\n      also have \"... \\<le> (dist x y - t) + (s - dist x y)\"\n        using that 1 Ifg[of t \"dist x y\"] Ifh[of \"dist x y\" s] by (auto simp add: dist_commute intro: mono_intros)\n      finally have *: \"dist (f t) (f s) \\<le> s - t\" by simp\n\n      have \"dist x z \\<le> dist (f 0) (f t) + dist (f t) (f s) + dist (f s) (f (dist x z))\"\n        unfolding \\<open>f 0 = x\\<close> \\<open>f (dist x z) = z\\<close> using dist_triangle4 by auto\n      also have \"... \\<le> t + dist (f t) (f s) + (dist x z - s)\"\n        using that 1 Ifg[of 0 t] Ifh[of s \"dist x z\"] by (auto simp add: dist_commute intro: mono_intros)\n      finally have \"s - t \\<le> dist (f t) (f s)\" by auto\n      then show \"dist (f s) (f t) = s-t\" using * dist_commute by auto\n    next\n      case 2\n      then show ?thesis using Ifg that by auto\n    next\n      case 3\n      then show ?thesis using Ifh that by auto\n    qed\n  qed\n  have \"isometry_on {0..dist x z} f\"\n    unfolding isometry_on_def dist_real_def using I\n    by (auto, metis abs_of_nonneg dist_commute dist_real_def le_cases zero_le_dist)\n  then show \"geodesic_segment_between (G \\<union> H) x z\"\n    unfolding geodesic_segment_between_def\n    using \\<open>f 0 = x\\<close> \\<open>f (dist x z) = z\\<close> \\<open>f`{0..dist x z} = G \\<union> H\\<close> by auto\n  have \"G \\<inter> H \\<subseteq> {y}\"\n  proof (auto)\n    fix a assume a: \"a \\<in> G\" \"a \\<in> H\"\n    obtain s where s: \"s \\<in> {0..dist x y}\" \"a = g s\" using a g(4) by auto\n    obtain t where t: \"t \\<in> {dist x y..dist x z}\" \"a = h t\" using a h(4) by auto\n    have \"a = f s\" using fg s by auto\n    moreover have \"a = f t\" using fh t by auto\n    ultimately have \"s = t\" using isometry_onD[OF \\<open>isometry_on {0..dist x z} f\\<close>, of s t] s(1) t(1) by auto\n    then have \"s = dist x y\" using s t by auto\n    then show \"a = y\" using s(2) g by auto\n  qed\n  then show \"G \\<inter> H = {y}\" using assms by auto\nqed\n\nlemma geodesic_segment_dist_le:\n  assumes \"geodesic_segment_between G x y\" \"a \\<in> G\" \"b \\<in> G\"\n  shows \"dist a b \\<le> dist x y\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  obtain s t where st: \"s \\<in> {0..dist x y}\" \"t \\<in> {0..dist x y}\" \"a = g s\" \"b = g t\"\n    using g(4) assms by auto\n  have \"dist a b = abs(s-t)\" using isometry_onD[OF g(3) st(1) st(2)]\n    unfolding st(3) st(4) dist_real_def by simp\n  then show \"dist a b \\<le> dist x y\" using st(1) st(2) unfolding dist_real_def by auto\nqed\n\nlemma geodesic_segment_param [simp]:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"geodesic_segment_param G x 0 = x\"\n        \"geodesic_segment_param G x (dist x y) = y\"\n        \"t \\<in> {0..dist x y} \\<Longrightarrow> geodesic_segment_param G x t \\<in> G\"\n        \"isometry_on {0..dist x y} (geodesic_segment_param G x)\"\n        \"(geodesic_segment_param G x)`{0..dist x y} = G\"\n        \"t \\<in> {0..dist x y} \\<Longrightarrow> dist x (geodesic_segment_param G x t) = t\"\n        \"s \\<in> {0..dist x y} \\<Longrightarrow> t \\<in> {0..dist x y} \\<Longrightarrow> dist (geodesic_segment_param G x s) (geodesic_segment_param G x t) = abs(s-t)\"\n        \"z \\<in> G \\<Longrightarrow> z = geodesic_segment_param G x (dist x z)\"\nproof -\n  obtain g::\"real\\<Rightarrow>'a\" where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  have *: \"g t \\<in> G \\<and> dist x (g t) = t\" if \"t \\<in> {0..dist x y}\" for t\n    using isometry_onD[OF g(3), of 0 t] that g(1) g(4) unfolding dist_real_def by auto\n  have G: \"geodesic_segment_param G x t = g t\" if \"t \\<in> {0..dist x y}\" for t\n  proof -\n    have A: \"geodesic_segment_param G x t \\<in> G \\<and> dist x (geodesic_segment_param G x t) = t\"\n      using *[OF that] unfolding geodesic_segment_param_def apply auto\n      using *[OF that] by (metis (mono_tags, lifting) someI)+\n    obtain s where s: \"geodesic_segment_param G x t = g s\" \"s \\<in> {0..dist x y}\"\n      using A g(4) by auto\n    have \"s = t\" using *[OF \\<open>s \\<in> {0..dist x y}\\<close>] A unfolding s(1) by auto\n    then show ?thesis using s by auto\n  qed\n  show \"geodesic_segment_param G x 0 = x\"\n       \"geodesic_segment_param G x (dist x y) = y\"\n       \"t \\<in> {0..dist x y} \\<Longrightarrow> geodesic_segment_param G x t \\<in> G\"\n       \"isometry_on {0..dist x y} (geodesic_segment_param G x)\"\n       \"(geodesic_segment_param G x)`{0..dist x y} = G\"\n       \"t \\<in> {0..dist x y} \\<Longrightarrow> dist x (geodesic_segment_param G x t) = t\"\n       \"s \\<in> {0..dist x y} \\<Longrightarrow> t \\<in> {0..dist x y} \\<Longrightarrow> dist (geodesic_segment_param G x s) (geodesic_segment_param G x t) = abs(s-t)\"\n       \"z \\<in> G \\<Longrightarrow> z = geodesic_segment_param G x (dist x z)\"\n    using G g apply (auto simp add: rev_image_eqI)\n    using G isometry_on_cong * atLeastAtMost_iff apply blast\n    using G isometry_on_cong * atLeastAtMost_iff apply blast\n    by (auto simp add: * dist_real_def isometry_onD)\nqed\n\n\n\nlemma geodesic_segment_reverse_param:\n  assumes \"geodesic_segment_between G x y\"\n          \"t \\<in> {0..dist x y}\"\n  shows \"geodesic_segment_param G y (dist x y - t) = geodesic_segment_param G x t\"\nproof -\n  have * [simp]: \"geodesic_segment_between G y x\"\n    using geodesic_segment_commute[OF assms(1)] by simp\n  have \"geodesic_segment_param G y (dist x y - t) \\<in> G\"\n    apply (rule geodesic_segment_param(3)[of _ _ x])\n    using assms(2) by (auto simp add: dist_commute)\n  moreover have \"dist (geodesic_segment_param G y (dist x y - t)) x = t\"\n    using geodesic_segment_param(2)[OF *] geodesic_segment_param(7)[OF *, of \"dist x y -t\" \"dist x y\"] assms(2) by (auto simp add: dist_commute)\n  moreover have \"geodesic_segment_param G x t \\<in> G\"\n    apply (rule geodesic_segment_param(3)[OF assms(1)])\n    using assms(2) by auto\n  moreover have \"dist (geodesic_segment_param G x t) x = t\"\n    using geodesic_segment_param(6)[OF assms] by (simp add: dist_commute)\n  ultimately show ?thesis\n    using geodesic_segment_dist_unique[OF assms(1)] by (simp add: dist_commute)\nqed\n\nlemma dist_along_geodesic_wrt_endpoint:\n  assumes \"geodesic_segment_between G x y\"\n          \"u \\<in> G\" \"v \\<in> G\"\n  shows \"dist u v = abs(dist u x - dist v x)\"\nproof -\n  have *: \"u = geodesic_segment_param G x (dist x u)\" \"v = geodesic_segment_param G x (dist x v)\"\n    using assms by auto\n  have \"dist u v = dist (geodesic_segment_param G x (dist x u)) (geodesic_segment_param G x (dist x v))\"\n    using * by auto\n  also have \"... = abs(dist x u - dist x v)\"\n    apply (rule geodesic_segment_param(7)[OF assms(1)]) using assms apply auto\n    using geodesic_segment_dist_le geodesic_segment_endpoints(1) by blast+\n  finally show ?thesis by (simp add: dist_commute)\nqed\n\ntext \\<open>One often needs to restrict a geodesic segment to a subsegment. We introduce the tools\nto express this conveniently.\\<close>\ndefinition geodesic_subsegment::\"('a::metric_space) set \\<Rightarrow> 'a \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> 'a set\"\n  where \"geodesic_subsegment G x s t = G \\<inter> {z. dist x z \\<ge> s \\<and> dist x z \\<le> t}\"\n\ntext \\<open>A subsegment is always contained in the original segment.\\<close>\nlemma geodesic_subsegment_subset:\n  \"geodesic_subsegment G x s t \\<subseteq> G\"\nunfolding geodesic_subsegment_def by simp\n\ntext \\<open>A subsegment is indeed a geodesic segment, and its endpoints and parametrization can be\nexpressed in terms of the original segment.\\<close>\nlemma geodesic_subsegment:\n  assumes \"geodesic_segment_between G x y\"\n          \"0 \\<le> s\" \"s \\<le> t\" \"t \\<le> dist x y\"\n  shows \"geodesic_subsegment G x s t = (geodesic_segment_param G x)`{s..t}\"\n        \"geodesic_segment_between (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (geodesic_segment_param G x t)\"\n        \"\\<And>u. s \\<le> u \\<Longrightarrow> u \\<le> t \\<Longrightarrow> geodesic_segment_param (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (u - s) = geodesic_segment_param G x u\"\nproof -\n  show A: \"geodesic_subsegment G x s t = (geodesic_segment_param G x)`{s..t}\"\n  proof (auto)\n    fix y assume y: \"y \\<in> geodesic_subsegment G x s t\"\n    have \"y = geodesic_segment_param G x (dist x y)\"\n      apply (rule geodesic_segment_param(8)[OF assms(1)])\n      using y geodesic_subsegment_subset by force\n    moreover have \"dist x y \\<ge> s \\<and> dist x y \\<le> t\"\n      using y unfolding geodesic_subsegment_def by auto\n    ultimately show \"y \\<in> geodesic_segment_param G x ` {s..t}\" by auto\n  next\n    fix u assume H: \"s \\<le> u\" \"u \\<le> t\"\n    have *: \"dist x (geodesic_segment_param G x u) = u\"\n      apply (rule geodesic_segment_param(6)[OF assms(1)]) using H assms by auto\n    show \"geodesic_segment_param G x u \\<in> geodesic_subsegment G x s t\"\n      unfolding geodesic_subsegment_def\n      using geodesic_segment_param_in_segment[OF geodesic_segment_endpoints(3)[OF assms(1)]] by (auto simp add: * H)\n  qed\n\n  have *: \"isometry_on {s..t} (geodesic_segment_param G x)\"\n    by (rule isometry_on_subset[of \"{0..dist x y}\"]) (auto simp add: assms)\n  show B: \"geodesic_segment_between (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (geodesic_segment_param G x t)\"\n    unfolding A apply (rule geodesic_segmentI2) using * assms by auto\n\n  fix u assume u: \"s \\<le> u\" \"u \\<le> t\"\n  show \"geodesic_segment_param (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (u - s) = geodesic_segment_param G x u\"\n  proof (rule geodesic_segment_dist_unique[OF B])\n    show \"geodesic_segment_param (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (u - s) \\<in> geodesic_subsegment G x s t\"\n      by (rule geodesic_segment_param_in_segment[OF geodesic_segment_endpoints(3)[OF B]])\n    show \"geodesic_segment_param G x u \\<in> geodesic_subsegment G x s t\"\n      unfolding A using u by auto\n    have \"dist (geodesic_segment_param G x s) (geodesic_segment_param (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (u - s)) = u - s\"\n      using B assms u by auto\n    moreover have \"dist (geodesic_segment_param G x s) (geodesic_segment_param G x u) = u -s\"\n      using assms u by auto\n    ultimately show \"dist (geodesic_segment_param G x s) (geodesic_segment_param (geodesic_subsegment G x s t) (geodesic_segment_param G x s) (u - s)) =\n        dist (geodesic_segment_param G x s) (geodesic_segment_param G x u)\"\n      by simp\n  qed\nqed\n\ntext \\<open>The parameterizations of a segment and a subsegment sharing an endpoint coincide where defined.\\<close>\nlemma geodesic_segment_subparam:\n  assumes \"geodesic_segment_between G x z\" \"geodesic_segment_between H x y\" \"H \\<subseteq> G\" \"t \\<in> {0..dist x y}\"\n  shows \"geodesic_segment_param G x t = geodesic_segment_param H x t\"\nproof -\n  have \"geodesic_segment_param H x t \\<in> G\"\n    using assms(3) geodesic_segment_param(3)[OF assms(2) assms(4)] by auto\n  then have \"geodesic_segment_param H x t = geodesic_segment_param G x (dist x (geodesic_segment_param H x t))\"\n    using geodesic_segment_param(8)[OF assms(1)] by auto\n  then show ?thesis using geodesic_segment_param(6)[OF assms(2) assms(4)] by auto\nqed\n\ntext \\<open>A segment contains a subsegment between any of its points\\<close>\nlemma geodesic_subsegment_exists:\n  assumes \"geodesic_segment G\" \"x \\<in> G\" \"y \\<in> G\"\n  shows \"\\<exists>H. H \\<subseteq> G \\<and> geodesic_segment_between H x y\"\nproof -\n  obtain a0 b0 where Ga0b0: \"geodesic_segment_between G a0 b0\"\n    using assms(1) unfolding geodesic_segment_def by auto\n  text \\<open>Permuting the endpoints if necessary, we can ensure that the first endpoint $a$ is closer\n  to $x$ than $y$.\\<close>\n  have \"\\<exists> a b. geodesic_segment_between G a b \\<and> dist x a \\<le> dist y a\"\n  proof (cases \"dist x a0 \\<le> dist y a0\")\n    case True\n    show ?thesis\n      apply (rule exI[of _ a0], rule exI[of _ b0]) using True Ga0b0 by auto\n  next\n    case False\n    show ?thesis\n      apply (rule exI[of _ b0], rule exI[of _ a0])\n      using Ga0b0 geodesic_segment_commute geodesic_segment_dist[OF Ga0b0 \\<open>x \\<in> G\\<close>] geodesic_segment_dist[OF Ga0b0 \\<open>y \\<in> G\\<close>] False\n      by (auto simp add: dist_commute)\n  qed\n  then obtain a b where Gab: \"geodesic_segment_between G a b\" \"dist x a \\<le> dist y a\"\n    by auto\n  have *: \"0 \\<le> dist x a\" \"dist x a \\<le> dist y a\" \"dist y a \\<le> dist a b\"\n    using Gab assms by (meson geodesic_segment_dist_le geodesic_segment_endpoints(1) zero_le_dist)+\n  have **: \"x = geodesic_segment_param G a (dist x a)\" \"y = geodesic_segment_param G a (dist y a)\"\n    using Gab \\<open>x \\<in> G\\<close> \\<open>y \\<in> G\\<close> by (metis dist_commute geodesic_segment_param(8))+\n  define H where \"H = geodesic_subsegment G a (dist x a) (dist y a)\"\n  have \"H \\<subseteq> G\"\n    unfolding H_def by (rule geodesic_subsegment_subset)\n  moreover have \"geodesic_segment_between H x y\"\n    unfolding H_def using geodesic_subsegment(2)[OF Gab(1) *] ** by auto\n  ultimately show ?thesis by auto\nqed\n\ntext \\<open>A geodesic segment is homeomorphic to an interval.\\<close>\nlemma geodesic_segment_homeo_interval:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"{0..dist x y} homeomorphic G\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  show ?thesis using isometry_on_homeomorphism(3)[OF g(3)] unfolding g(4) by simp\nqed\n\ntext \\<open>Just like an interval, a geodesic segment is compact, connected, path connected, bounded,\nclosed, nonempty, and proper.\\<close>\nlemma geodesic_segment_topology:\n  assumes \"geodesic_segment G\"\n  shows \"compact G\" \"connected G\" \"path_connected G\" \"bounded G\" \"closed G\" \"G \\<noteq> {}\" \"proper G\"\nproof -\n  show \"compact G\"\n    using assms geodesic_segment_homeo_interval homeomorphic_compactness\n    unfolding geodesic_segment_def by force\n  show \"path_connected G\"\n    using assms is_interval_path_connected geodesic_segment_homeo_interval homeomorphic_path_connectedness\n    unfolding geodesic_segment_def\n    by (metis is_interval_cc)\n  then show \"connected G\"\n    using path_connected_imp_connected by auto\n  show \"bounded G\"\n    by (rule compact_imp_bounded, fact)\n  show \"closed G\"\n    by (rule compact_imp_closed, fact)\n  show \"G \\<noteq> {}\"\n    using assms geodesic_segment_def geodesic_segment_endpoints(3) by auto\n  show \"proper G\"\n    using proper_of_compact \\<open>compact G\\<close> by auto\nqed\n\nlemma geodesic_segment_between_x_x [simp]:\n  \"geodesic_segment_between {x} x x\"\n  \"geodesic_segment {x}\"\n  \"geodesic_segment_between G x x \\<longleftrightarrow> G = {x}\"\nproof -\n  show *: \"geodesic_segment_between {x} x x\"\n    unfolding geodesic_segment_between_def apply (rule exI[of _ \"\\<lambda>_. x\"]) unfolding isometry_on_def by auto\n  then show \"geodesic_segment {x}\" by auto\n  show \"geodesic_segment_between G x x \\<longleftrightarrow> G = {x}\"\n    using geodesic_segment_dist_le geodesic_segment_endpoints(2) * by fastforce\nqed\n\nlemma geodesic_segment_disconnection:\n  assumes \"geodesic_segment_between G x y\" \"z \\<in> G\"\n  shows \"(connected (G - {z})) = (z = x \\<or> z = y)\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  obtain t where t: \"t \\<in> {0..dist x y}\" \"z = g t\" using \\<open>z \\<in> G\\<close> g(4) by auto\n  have \"({0..dist x y} - {t}) homeomorphic (G - {g t})\"\n  proof -\n    have *: \"isometry_on ({0..dist x y} - {t}) g\"\n      apply (rule isometry_on_subset[OF g(3)]) by auto\n    have \"({0..dist x y} - {t}) homeomorphic g`({0..dist x y} - {t})\"\n      by (rule isometry_on_homeomorphism(3)[OF *])\n    moreover have \"g`({0..dist x y} - {t}) = G - {g t}\"\n      unfolding g(4) using isometry_on_injective[OF g(3)] t by (auto simp add: inj_onD)\n    ultimately show ?thesis by auto\n  qed\n  moreover have \"connected({0..dist x y} - {t}) = (t = 0 \\<or> t = dist x y)\"\n    using t(1) by (auto simp add: connected_iff_interval, fastforce)\n  ultimately have \"connected (G - {z}) = (t = 0 \\<or> t = dist x y)\"\n    unfolding \\<open>z = g t\\<close>[symmetric]using homeomorphic_connectedness by blast\n  moreover have \"(t = 0 \\<or> t = dist x y) = (z = x \\<or> z = y)\"\n    using t g apply auto\n    by (metis atLeastAtMost_iff isometry_on_inverse(2) order_refl zero_le_dist)+\n  ultimately show ?thesis by auto\nqed\n\nlemma geodesic_segment_unique_endpoints:\n  assumes \"geodesic_segment_between G x y\"\n          \"geodesic_segment_between G a b\"\n  shows \"{x, y} = {a, b}\"\nby (metis geodesic_segment_disconnection assms(1) assms(2) doubleton_eq_iff geodesic_segment_endpoints(1) geodesic_segment_endpoints(2))\n\nlemma geodesic_segment_subsegment:\n  assumes \"geodesic_segment G\" \"H \\<subseteq> G\" \"compact H\" \"connected H\" \"H \\<noteq> {}\"\n  shows \"geodesic_segment H\"\nproof -\n  obtain x y where \"geodesic_segment_between G x y\"\n    using assms unfolding geodesic_segment_def by auto\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  define L where \"L = (inv_into {0..dist x y} g)`H\"\n  have \"L \\<subseteq> {0..dist x y}\"\n    unfolding L_def using isometry_on_inverse[OF \\<open>isometry_on {0..dist x y} g\\<close>] assms(2) g(4) by auto\n  have \"isometry_on G (inv_into {0..dist x y} g)\"\n    using isometry_on_inverse[OF \\<open>isometry_on {0..dist x y} g\\<close>] g(4) by auto\n  then have \"isometry_on H (inv_into {0..dist x y} g)\"\n    using \\<open>H \\<subseteq> G\\<close> isometry_on_subset by auto\n  then have \"H homeomorphic L\" unfolding L_def using isometry_on_homeomorphism(3) by auto\n  then have \"compact L \\<and> connected L\"\n    using assms homeomorphic_compactness homeomorphic_connectedness by blast\n  then obtain a b where \"L = {a..b}\"\n    using connected_compact_interval_1[of L] by auto\n  have \"a \\<le> b\" using \\<open>H \\<noteq> {}\\<close> \\<open>L = {a..b}\\<close> unfolding L_def by auto\n  then have \"0 \\<le> a\" \"b \\<le> dist x y\" using \\<open>L \\<subseteq> {0..dist x y}\\<close> \\<open>L = {a..b}\\<close> by auto\n  have *: \"H = g`{a..b}\"\n    by (metis L_def \\<open>L = {a..b}\\<close> assms(2) g(4) image_inv_into_cancel)\n  show \"geodesic_segment H\"\n    unfolding * apply (rule geodesic_segmentI2[OF _ \\<open>a \\<le> b\\<close>])\n    apply (rule isometry_on_subset[OF g(3)]) using \\<open>0 \\<le> a\\<close> \\<open>b \\<le> dist x y\\<close> by auto\nqed\n\ntext \\<open>The image under an isometry of a geodesic segment is still obviously a geodesic segment.\\<close>\nlemma isometry_preserves_geodesic_segment_between:\n  assumes \"isometry_on X f\"\n          \"G \\<subseteq> X\" \"geodesic_segment_between G x y\"\n  shows \"geodesic_segment_between (f`G) (f x) (f y)\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  then have *: \"f`G = (f o g) `{0..dist x y}\" \"f x = (f o g) 0\" \"f y = (f o g) (dist x y)\"\n    by auto\n  show ?thesis\n    unfolding * apply (intro geodesic_segmentI2(1))\n    unfolding comp_def apply (rule isometry_on_compose[of _ g])\n    using g(3) g(4) assms by (auto intro: isometry_on_subset)\nqed\n\ntext \\<open>The sum of distances $d(w, x) + d(w, y)$ can be controlled using the distance from $w$\nto a geodesic segment between $x$ and $y$.\\<close>\nlemma geodesic_segment_distance:\n  assumes \"geodesic_segment_between G x y\"\n  shows \"dist w x + dist w y \\<le> dist x y + 2 * infdist w G\"\nproof -\n  have \"\\<exists>z \\<in> G. infdist w G = dist w z\"\n    apply (rule infdist_proper_attained) using assms by (auto simp add: geodesic_segment_topology)\n  then obtain z where z: \"z \\<in> G\" \"infdist w G = dist w z\" by auto\n  have \"dist w x + dist w y \\<le> (dist w z + dist z x) + (dist w z + dist z y)\"\n    by (intro mono_intros)\n  also have \"... = dist x z + dist z y + 2 * dist w z\"\n    by (auto simp add: dist_commute)\n  also have \"... = dist x y + 2 * infdist w G\"\n    using z(1) assms geodesic_segment_dist unfolding z(2) by auto\n  finally show ?thesis by auto\nqed\n\ntext \\<open>If a point $y$ is on a geodesic segment between $x$ and its closest projection $p$ on a set $A$,\nthen $p$ is also a closest projection of $y$, and the closest projection set of $y$ is contained in\nthat of $x$.\\<close>\n\n\n\nlemma proj_set_subset:\n  assumes \"p \\<in> proj_set x A\" \"geodesic_segment_between G p x\" \"y \\<in> G\"\n  shows \"proj_set y A \\<subseteq> proj_set x A\"\nproof -\n  have \"z \\<in> proj_set x A\" if \"z \\<in> proj_set y A\" for z\n  proof (rule proj_setI)\n    show \"z \\<in> A\" using that proj_setD by auto\n    have \"dist x z \\<le> dist x y + dist y z\"\n      by (intro mono_intros)\n    also have \"... \\<le> dist x y + dist y p\"\n      using proj_set_dist_le[OF proj_setD(1)[OF \\<open>p \\<in> proj_set x A\\<close>] that] by auto\n    also have \"... = dist x p\"\n      using assms geodesic_segment_commute geodesic_segment_dist by blast\n    also have \"... = infdist x A\"\n      using proj_setD(2)[OF assms(1)] by simp\n    finally show \"dist x z \\<le> infdist x A\"\n      by simp\n  qed\n  then show ?thesis by auto\nqed\n\nlemma proj_set_thickening:\n  assumes \"p \\<in> proj_set x Z\"\n          \"0 \\<le> D\"\n          \"D \\<le> dist p x\"\n          \"geodesic_segment_between G p x\"\n  shows \"geodesic_segment_param G p D \\<in> proj_set x (\\<Union>z\\<in>Z. cball z D)\"\nproof (rule proj_setI')\n  have \"dist p (geodesic_segment_param G p D) = D\"\n    using geodesic_segment_param(7)[OF assms(4), of 0 D]\n    unfolding geodesic_segment_param(1)[OF assms(4)] using assms by simp\n  then show \"geodesic_segment_param G p D \\<in> (\\<Union>z\\<in>Z. cball z D)\"\n    using proj_setD(1)[OF \\<open>p \\<in> proj_set x Z\\<close>] by force\n  show \"dist x (geodesic_segment_param G p D) \\<le> dist x y\" if \"y \\<in> (\\<Union>z\\<in>Z. cball z D)\" for y\n  proof -\n    obtain z where y: \"y \\<in> cball z D\" \"z \\<in> Z\" using \\<open>y \\<in> (\\<Union>z\\<in>Z. cball z D)\\<close> by auto\n    have \"dist (geodesic_segment_param G p D) x + D = dist p x\"\n      using geodesic_segment_param(7)[OF assms(4), of D \"dist p x\"]\n      unfolding geodesic_segment_param(2)[OF assms(4)] using assms by simp\n    also have \"... \\<le> dist z x\"\n      using proj_setD(2)[OF \\<open>p \\<in> proj_set x Z\\<close>] infdist_le[OF \\<open>z \\<in> Z\\<close>, of x] by (simp add: dist_commute)\n    also have \"... \\<le> dist z y + dist y x\"\n      by (intro mono_intros)\n    also have \"... \\<le> D + dist y x\"\n      using y by simp\n    finally show ?thesis by (simp add: dist_commute)\n  qed\nqed\n\nlemma proj_set_thickening':\n  assumes \"p \\<in> proj_set x Z\"\n          \"0 \\<le> D\"\n          \"D \\<le> E\"\n          \"E \\<le> dist p x\"\n          \"geodesic_segment_between G p x\"\n  shows \"geodesic_segment_param G p D \\<in> proj_set (geodesic_segment_param G p E) (\\<Union>z\\<in>Z. cball z D)\"\nproof -\n  define H where \"H = geodesic_subsegment G p D (dist p x)\"\n  have H1: \"geodesic_segment_between H (geodesic_segment_param G p D) x\"\n    apply (subst geodesic_segment_param(2)[OF \\<open>geodesic_segment_between G p x\\<close>, symmetric])\n    unfolding H_def apply (rule geodesic_subsegment(2)) using assms by auto\n  have H2: \"geodesic_segment_param G p E \\<in> H\"\n    unfolding H_def using assms geodesic_subsegment(1) by force\n  have \"geodesic_segment_param G p D \\<in> proj_set x (\\<Union>z\\<in>Z. cball z D)\"\n    apply (rule proj_set_thickening) using assms by auto\n  then show ?thesis\n    by (rule proj_set_geodesic_same_basepoint[OF _ H1 H2])\nqed\n\ntext \\<open>It is often convenient to use \\emph{one} geodesic between $x$ and $y$, even if it is not unique.\nWe introduce a notation for such a choice of a geodesic, denoted \\verb+{x--S--y}+ for such a geodesic\nthat moreover remains in the set $S$. We also enforce\nthe condition \\verb+{x--S--y} = {y--S--x}+. When there is no such geodesic, we simply take\n\\verb+{x--S--y} = {x, y}+ for definiteness. It would be even better to enforce that, if\n$a$ is on \\verb+{x--S--y}+, then \\verb+{x--S--y}+ is the union of \\verb+{x--S--a}+ and \\verb+{a--S--y}+, but\nI do not know if such a choice is always possible -- such a choice of geodesics is\ncalled a geodesic bicombing.\nWe also write \\verb+{x--y}+ for \\verb+{x--UNIV--y}+.\\<close>\n\ndefinition some_geodesic_segment_between::\"'a::metric_space \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set\" (\"(1{_--_--_})\")\n  where \"some_geodesic_segment_between = (SOME f. \\<forall> x y S. f x S y = f y S x\n    \\<and> (if (\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S) then (geodesic_segment_between (f x S y) x y \\<and> (f x S y \\<subseteq> S))\n        else f x S y = {x, y}))\"\n\nabbreviation some_geodesic_segment_between_UNIV::\"'a::metric_space \\<Rightarrow> 'a \\<Rightarrow> 'a set\" (\"(1{_--_})\")\n  where \"some_geodesic_segment_between_UNIV x y \\<equiv> {x--UNIV--y}\"\n\ntext \\<open>We prove that there is such a choice of geodesics, compatible with direction reversal. What\nwe do is choose arbitrarily a geodesic between $x$ and $y$ if it exists, and then use the geodesic\nbetween $\\min(x, y)$ and $\\max(x,y)$, for any total order on the space, to ensure that we get the\nsame result from $x$ to $y$ or from $y$ to $x$.\\<close>\n\nlemma some_geodesic_segment_between_exists:\n  \"\\<exists>f. \\<forall> x y S. f x S y = f y S x\n    \\<and> (if (\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S) then (geodesic_segment_between (f x S y) x y \\<and> (f x S y \\<subseteq> S))\n        else f x S y = {x, y})\"\nproof -\n  define g::\"'a \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set\" where\n    \"g = (\\<lambda>x S y. if (\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S) then (SOME G. geodesic_segment_between G x y \\<and> G \\<subseteq> S) else {x, y})\"\n  have g1: \"geodesic_segment_between (g x S y) x y \\<and> (g x S y \\<subseteq> S)\" if \"\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\" for x y S\n    unfolding g_def using someI_ex[OF that] by auto\n  have g2: \"g x S y = {x, y}\" if \"\\<not>(\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S)\" for x y S\n    unfolding g_def using that by auto\n  obtain r::\"'a rel\" where r: \"well_order_on UNIV r\"\n    using well_order_on by auto\n  have A: \"x = y\" if \"(x, y) \\<in> r\" \"(y, x) \\<in> r\" for x y\n    using r that unfolding well_order_on_def linear_order_on_def partial_order_on_def antisym_def by auto\n  have B: \"(x, y) \\<in> r \\<or> (y, x) \\<in> r\" for x y\n    using r unfolding well_order_on_def linear_order_on_def total_on_def partial_order_on_def preorder_on_def refl_on_def by force\n\n  define f where \"f = (\\<lambda>x S y. if (x, y) \\<in> r then g x S y else g y S x)\"\n  have \"f x S y = f y S x\" for x y S unfolding f_def using r A B by auto\n  moreover have \"geodesic_segment_between (f x S y) x y \\<and> (f x S y \\<subseteq> S)\" if \"\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\" for x y S\n    unfolding f_def using g1 geodesic_segment_commute that by smt\n  moreover have \"f x S y = {x, y}\" if \"\\<not>(\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S)\" for x y S\n    unfolding f_def using g2 that geodesic_segment_commute doubleton_eq_iff by metis\n  ultimately show ?thesis by metis\nqed\n\n\n\nlemma some_geodesic_segment_description:\n  \"(\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S) \\<Longrightarrow> geodesic_segment_between {x--S--y} x y\"\n  \"(\\<not>(\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S)) \\<Longrightarrow> {x--S--y} = {x, y}\"\nunfolding some_geodesic_segment_between_def by (simp add: someI_ex[OF some_geodesic_segment_between_exists])+\n\ntext \\<open>Basic topological properties of our chosen set of geodesics.\\<close>\n\nlemma some_geodesic_compact [simp]:\n  \"compact {x--S--y}\"\napply (cases \"\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\")\nusing some_geodesic_segment_description[of x y] geodesic_segment_topology[of \"{x--S--y}\"] geodesic_segment_def apply auto\n  by blast\n\nlemma some_geodesic_closed [simp]:\n  \"closed {x--S--y}\"\nby (rule compact_imp_closed[OF some_geodesic_compact[of x S y]])\n\nlemma some_geodesic_bounded [simp]:\n  \"bounded {x--S--y}\"\nby (rule compact_imp_bounded[OF some_geodesic_compact[of x S y]])\n\n\n\nlemma some_geodesic_subsegment:\n  assumes \"H \\<subseteq> {x--S--y}\" \"compact H\" \"connected H\" \"H \\<noteq> {}\"\n  shows \"geodesic_segment H\"\napply (cases \"\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\")\nusing some_geodesic_segment_description[of x y] geodesic_segment_subsegment[OF _ assms] geodesic_segment_def apply auto[1]\nusing some_geodesic_segment_description[of x y] assms\nby (metis connected_finite_iff_sing finite.emptyI finite.insertI finite_subset geodesic_segment_between_x_x(2))\n\nlemma some_geodesic_in_subset:\n  assumes \"x \\<in> S\" \"y \\<in> S\"\n  shows \"{x--S--y} \\<subseteq> S\"\napply (cases \"\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\")\nunfolding some_geodesic_segment_between_def by (simp add: assms someI_ex[OF some_geodesic_segment_between_exists])+\n\nlemma some_geodesic_same_endpoints [simp]:\n  \"{x--S--x} = {x}\"\napply (cases \"\\<exists>G. geodesic_segment_between G x x \\<and> G \\<subseteq> S\")\napply (meson geodesic_segment_between_x_x(3) some_geodesic_segment_description(1))\nby (simp add: some_geodesic_segment_description(2))\n\nsubsection \\<open>Geodesic subsets\\<close>\n\ntext \\<open>A subset is \\emph{geodesic} if any two of its points can be joined by a geodesic segment.\nWe prove basic properties of such a subset in this paragraph -- notably connectedness. A basic\nexample is given by convex subsets of vector spaces, as closed segments are geodesic.\\<close>\n\ndefinition geodesic_subset::\"('a::metric_space) set \\<Rightarrow> bool\"\n  where \"geodesic_subset S = (\\<forall>x\\<in>S. \\<forall>y\\<in>S. \\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S)\"\n\nlemma geodesic_subsetD:\n  assumes \"geodesic_subset S\" \"x \\<in> S\" \"y \\<in> S\"\n  shows \"geodesic_segment_between {x--S--y} x y\"\nusing assms some_geodesic_segment_description(1) unfolding geodesic_subset_def by blast\n\nlemma geodesic_subsetI:\n  assumes \"\\<And>x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> \\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\"\n  shows \"geodesic_subset S\"\nusing assms unfolding geodesic_subset_def by auto\n\nlemma geodesic_subset_empty:\n  \"geodesic_subset {}\"\nusing geodesic_subsetI by auto\n\nlemma geodesic_subset_singleton:\n  \"geodesic_subset {x}\"\nby (auto intro!: geodesic_subsetI geodesic_segment_between_x_x(1))\n\nlemma geodesic_subset_path_connected:\n  assumes \"geodesic_subset S\"\n  shows \"path_connected S\"\nproof -\n  have \"\\<exists>g. path g \\<and> path_image g \\<subseteq> S \\<and> pathstart g = x \\<and> pathfinish g = y\" if \"x \\<in> S\" \"y \\<in> S\" for x y\n  proof -\n    define G where \"G = {x--S--y}\"\n    have *: \"geodesic_segment_between G x y\" \"G \\<subseteq> S\" \"x \\<in> G\" \"y \\<in> G\"\n      using assms that by (auto simp add: G_def geodesic_subsetD some_geodesic_in_subset that(1) that(2))\n    then have \"path_connected G\"\n      using geodesic_segment_topology(3) unfolding geodesic_segment_def by auto\n    then have \"\\<exists>g. path g \\<and> path_image g \\<subseteq> G \\<and> pathstart g = x \\<and> pathfinish g = y\"\n      using * unfolding path_connected_def by auto\n    then show ?thesis using \\<open>G \\<subseteq> S\\<close> by auto\n  qed\n  then show ?thesis\n    unfolding path_connected_def by auto\nqed\n\ntext \\<open>To show that a segment in a normed vector space is geodesic, we will need to use its\nlength parametrization, which is given in the next lemma.\\<close>\n\nlemma closed_segment_as_isometric_image:\n  \"((\\<lambda>t. x + (t/dist x y) *\\<^sub>R (y - x))`{0..dist x y}) = closed_segment x y\"\nproof (auto simp add: closed_segment_def image_iff)\n  fix t assume H: \"0 \\<le> t\" \"t \\<le> dist x y\"\n  show \"\\<exists>u. x + (t / dist x y) *\\<^sub>R (y - x) = (1 - u) *\\<^sub>R x + u *\\<^sub>R y \\<and> 0 \\<le> u \\<and> u \\<le> 1\"\n    apply (rule exI[of _ \"t/dist x y\"])\n    using H apply (auto simp add: algebra_simps divide_simps)\n    apply (metis add_diff_cancel_left' add_diff_eq add_divide_distrib dist_eq_0_iff scaleR_add_left vector_fraction_eq_iff)\n    done\nnext\n  fix u::real assume H: \"0 \\<le> u\" \"u \\<le> 1\"\n  show \"\\<exists>t\\<in>{0..dist x y}. (1 - u) *\\<^sub>R x + u *\\<^sub>R y = x + (t / dist x y) *\\<^sub>R (y - x)\"\n    apply (rule bexI[of _ \"u * dist x y\"])\n    using H by (auto simp add: algebra_simps mult_left_le_one_le)\nqed\n\nproposition closed_segment_is_geodesic:\n  fixes x y::\"'a::real_normed_vector\"\n  shows \"isometry_on {0..dist x y} (\\<lambda>t. x + (t/dist x y) *\\<^sub>R (y - x))\"\n        \"geodesic_segment_between (closed_segment x y) x y\"\n        \"geodesic_segment (closed_segment x y)\"\nproof -\n  show *: \"isometry_on {0..dist x y} (\\<lambda>t. x + (t/dist x y) *\\<^sub>R (y - x))\"\n    unfolding isometry_on_def dist_norm\n    apply (cases \"x = y\")\n    by (auto simp add: scaleR_diff_left[symmetric] diff_divide_distrib[symmetric] norm_minus_commute)\n  show \"geodesic_segment_between (closed_segment x y) x y\"\n    unfolding closed_segment_as_isometric_image[symmetric]\n    apply (rule geodesic_segment_betweenI[OF _ _ *]) by auto\n  then show \"geodesic_segment (closed_segment x y)\"\n    by auto\nqed\n\ntext \\<open>We deduce that a convex set is geodesic.\\<close>\n\nproposition convex_is_geodesic:\n  assumes \"convex (S::'a::real_normed_vector set)\"\n  shows \"geodesic_subset S\"\nproof (rule geodesic_subsetI)\n  fix x y assume H: \"x \\<in> S\" \"y \\<in> S\"\n  show \"\\<exists>G. geodesic_segment_between G x y \\<and> G \\<subseteq> S\"\n    apply (rule exI[of _ \"closed_segment x y\"])\n    apply (auto simp add: closed_segment_is_geodesic)\n    using H assms convex_contains_segment by blast\nqed\n\n\nsubsection \\<open>Geodesic spaces\\<close>\n\ntext \\<open>In this subsection, we define geodesic spaces (metric spaces in which there is a geodesic\nsegment joining any pair of points). We specialize the previous statements on geodesic segments to\nthese situations.\\<close>\n\nclass geodesic_space = metric_space +\n  assumes geodesic: \"geodesic_subset (UNIV::('a::metric_space) set)\"\n\ntext \\<open>The simplest example of a geodesic space is a real normed vector space. Significant examples\nalso include graphs (with the graph distance), Riemannian manifolds, and $CAT(\\kappa)$ spaces.\\<close>\n\ninstance real_normed_vector \\<subseteq> geodesic_space\nby (standard, simp add: convex_is_geodesic)\n\nlemma (in geodesic_space) some_geodesic_is_geodesic_segment [simp]:\n  \"geodesic_segment_between {x--y} x (y::'a)\"\n  \"geodesic_segment {x--y}\"\nusing some_geodesic_segment_description(1)[of x y] geodesic_subsetD[OF geodesic] by (auto, blast)\n\nlemma (in geodesic_space) some_geodesic_connected [simp]:\n  \"connected {x--y}\" \"path_connected {x--y}\"\nby (auto intro!: geodesic_segment_topology)\n\ntext \\<open>In geodesic spaces, we restate as simp rules all properties of the geodesic segment\nparametrizations.\\<close>\n\nlemma (in geodesic_space) geodesic_segment_param_in_geodesic_spaces [simp]:\n  \"geodesic_segment_param {x--y} x 0 = x\"\n  \"geodesic_segment_param {x--y} x (dist x y) = y\"\n  \"t \\<in> {0..dist x y} \\<Longrightarrow> geodesic_segment_param {x--y} x t \\<in> {x--y}\"\n  \"isometry_on {0..dist x y} (geodesic_segment_param {x--y} x)\"\n  \"(geodesic_segment_param {x--y} x)`{0..dist x y} = {x--y}\"\n  \"t \\<in> {0..dist x y} \\<Longrightarrow> dist x (geodesic_segment_param {x--y} x t) = t\"\n  \"s \\<in> {0..dist x y} \\<Longrightarrow> t \\<in> {0..dist x y} \\<Longrightarrow> dist (geodesic_segment_param {x--y} x s) (geodesic_segment_param {x--y} x t) = abs(s-t)\"\n  \"z \\<in> {x--y} \\<Longrightarrow> z = geodesic_segment_param {x--y} x (dist x z)\"\nusing geodesic_segment_param[OF some_geodesic_is_geodesic_segment(1)[of x y]] by auto\n\n\nsubsection \\<open>Uniquely geodesic spaces\\<close>\n\ntext \\<open>In this subsection, we define uniquely geodesic spaces, i.e., geodesic spaces in which,\nadditionally, there is a unique geodesic between any pair of points.\\<close>\n\nclass uniquely_geodesic_space = geodesic_space +\n  assumes uniquely_geodesic: \"\\<And>x y G H. geodesic_segment_between G x y \\<Longrightarrow> geodesic_segment_between H x y \\<Longrightarrow> G = H\"\n\ntext \\<open>To prove that a geodesic space is uniquely geodesic, it suffices to show that there is no loop,\ni.e., if two geodesic segments intersect only at their endpoints, then they coincide.\n\nIndeed, assume this holds, and consider two geodesics with the same endpoints. If they differ at\nsome time $t$, then consider the last time $a$ before $t$ where they coincide, and the first time\n$b$ after $t$ where they coincide. Then the restrictions of the two geodesics to $[a,b]$ give\na loop, and a contradiction.\\<close>\n\nlemma (in geodesic_space) uniquely_geodesic_spaceI:\n  assumes \"\\<And>G H x (y::'a). geodesic_segment_between G x y \\<Longrightarrow> geodesic_segment_between H x y \\<Longrightarrow> G \\<inter> H = {x, y} \\<Longrightarrow> x = y\"\n          \"geodesic_segment_between G x y\" \"geodesic_segment_between H x (y::'a)\"\n  shows \"G = H\"\nproof -\n  obtain g where g: \"g 0 = x\" \"g (dist x y) = y\" \"isometry_on {0..dist x y} g\" \"G = g`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between G x y\\<close> geodesic_segment_between_def)\n  obtain h where h: \"h 0 = x\" \"h (dist x y) = y\" \"isometry_on {0..dist x y} h\" \"H = h`{0..dist x y}\"\n    by (meson \\<open>geodesic_segment_between H x y\\<close> geodesic_segment_between_def)\n  have \"g t = h t\" if \"t \\<in> {0..dist x y}\" for t\n  proof (rule ccontr)\n    assume \"g t \\<noteq> h t\"\n    define Z where \"Z = {s \\<in> {0..dist x y}. g s = h s}\"\n    have \"0 \\<in> Z\" \"dist x y \\<in> Z\" unfolding Z_def using g h by auto\n    have \"t \\<notin> Z\" unfolding Z_def using \\<open>g t \\<noteq> h t\\<close> by auto\n    have [simp]: \"closed Z\"\n    proof -\n      have *: \"Z = (\\<lambda>s. dist (g s) (h s))-`{0} \\<inter> {0..dist x y}\"\n        unfolding Z_def by auto\n      show ?thesis\n        unfolding * apply (rule closed_vimage_Int)\n        using isometry_on_continuous[OF g(3)] isometry_on_continuous[OF h(3)] continuous_on_dist by auto\n    qed\n    define a where \"a = Sup (Z \\<inter> {0..t})\"\n    have a: \"a \\<in> Z \\<inter> {0..t}\"\n      unfolding a_def apply (rule closed_contains_Sup, auto)\n      using \\<open>0 \\<in> Z\\<close> that by auto\n    then have \"h a = g a\" unfolding Z_def by auto\n    define b where \"b = Inf (Z \\<inter> {t..dist x y})\"\n    have b: \"b \\<in> Z \\<inter> {t..dist x y}\"\n      unfolding b_def apply (rule closed_contains_Inf, auto)\n      using \\<open>dist x y \\<in> Z\\<close> that by auto\n    then have \"h b = g b\" unfolding Z_def by auto\n    have notZ: \"s \\<notin> Z\" if \"s \\<in> {a<..<b}\" for s\n    proof (rule ccontr, auto, cases \"s \\<le> t\")\n      case True\n      assume \"s \\<in> Z\"\n      then have *: \"s \\<in> Z \\<inter> {0..t}\" using that a True by auto\n      have \"s \\<le> a\" unfolding a_def apply (rule cSup_upper) using * by auto\n      then show False using that by auto\n    next\n      case False\n      assume \"s \\<in> Z\"\n      then have *: \"s \\<in> Z \\<inter> {t..dist x y}\" using that b False by auto\n      have \"s \\<ge> b\" unfolding b_def apply (rule cInf_lower) using * by auto\n      then show False using that by auto\n    qed\n    have \"t \\<in> {a<..<b}\" using a b \\<open>t \\<notin> Z\\<close> less_eq_real_def by auto\n    then have \"a \\<le> b\" by auto\n    then have \"dist (h a) (h b) = b-a\"\n      using isometry_onD[OF h(3), of a b] a b that unfolding dist_real_def by auto\n    then have \"dist (h a) (h b) > 0\" using \\<open>t \\<in> {a<..<b}\\<close> by auto\n    then have \"h a \\<noteq> h b\" by auto\n\n    define G2 where \"G2 = g`{a..b}\"\n    define H2 where \"H2 = h`{a..b}\"\n    have \"G2 \\<inter> H2 \\<subseteq> {h a, h b}\"\n    proof\n      fix z assume z: \"z \\<in> G2 \\<inter> H2\"\n      obtain sg where sg: \"z = g sg\" \"sg \\<in> {a..b}\" using z unfolding G2_def by auto\n      obtain sh where sh: \"z = h sh\" \"sh \\<in> {a..b}\" using z unfolding H2_def by auto\n      have \"sg = dist x z\"\n        using isometry_onD[OF g(3), of 0 sg] a b sg(2) unfolding sg(1) g(1)[symmetric] dist_real_def by auto\n      moreover have \"sh = dist x z\"\n        using isometry_onD[OF h(3), of 0 sh] a b sh(2) unfolding sh(1) h(1)[symmetric] dist_real_def by auto\n      ultimately have \"sg = sh\" by auto\n      then have \"sh \\<in> Z\" using sg(1) sh(1) a b sh(2) unfolding Z_def by auto\n      then have \"sh \\<in> {a, b}\" using notZ sh(2)\n        by (metis IntD2 atLeastAtMost_iff atLeastAtMost_singleton greaterThanLessThan_iff inf_bot_left insertI2 insert_inter_insert not_le)\n      then show \"z \\<in> {h a, h b}\" using sh(1) by auto\n    qed\n    then have \"G2 \\<inter> H2 = {h a, h b}\"\n      using \\<open>h a = g a\\<close> \\<open>h b = g b\\<close> \\<open>a \\<le> b\\<close> unfolding H2_def G2_def apply auto\n      unfolding \\<open>h a = g a\\<close>[symmetric] \\<open>h b = g b\\<close>[symmetric] by auto\n    moreover have \"geodesic_segment_between G2 (h a) (h b)\"\n      unfolding G2_def \\<open>h a = g a\\<close> \\<open>h b = g b\\<close>\n      apply (rule geodesic_segmentI2) apply (rule isometry_on_subset[OF g(3)])\n      using a b that by auto\n    moreover have \"geodesic_segment_between H2 (h a) (h b)\"\n      unfolding H2_def apply (rule geodesic_segmentI2) apply (rule isometry_on_subset[OF h(3)])\n      using a b that by auto\n    ultimately have \"h a = h b\" using assms(1) by auto\n    then show False using \\<open>h a \\<noteq> h b\\<close> by simp\n  qed\n  then show \"G = H\" using g(4) h(4) by (simp add: image_def)\nqed\n\ncontext uniquely_geodesic_space\nbegin\n\nlemma geodesic_segment_unique:\n  \"geodesic_segment_between G x y = (G = {x--(y::'a)})\"\nusing uniquely_geodesic[of _ x y] by (meson some_geodesic_is_geodesic_segment)\n\nlemma geodesic_segment_dist':\n  assumes \"dist x z = dist x y + dist y z\"\n  shows \"y \\<in> {x--z}\" \"{x--z} = {x--y} \\<union> {y--z}\"\nproof -\n  have \"geodesic_segment_between ({x--y} \\<union> {y--z}) x z\"\n    using geodesic_segment_union[OF assms] by auto\n  then show \"{x--z} = {x--y} \\<union> {y--z}\"\n    using geodesic_segment_unique by auto\n  then show \"y \\<in> {x--z}\" by auto\nqed\n\nlemma geodesic_segment_expression:\n  \"{x--z} = {y. dist x z = dist x y + dist y z}\"\nusing geodesic_segment_dist'(1) geodesic_segment_dist[OF some_geodesic_is_geodesic_segment(1)] by auto\n\nlemma geodesic_segment_split:\n  assumes \"(y::'a) \\<in> {x--z}\"\n  shows \"{x--z} = {x--y} \\<union> {y--z}\"\n        \"{x--y} \\<inter> {y--z} = {y}\"\napply (metis assms geodesic_segment_dist geodesic_segment_dist'(2) some_geodesic_is_geodesic_segment(1))\napply (rule geodesic_segment_union(2)[of x z], auto simp add: assms)\nusing assms geodesic_segment_expression by blast\n\nlemma geodesic_segment_subparam':\n  assumes \"y \\<in> {x--z}\" \"t \\<in> {0..dist x y}\"\n  shows \"geodesic_segment_param {x--z} x t = geodesic_segment_param {x--y} x t\"\napply (rule geodesic_segment_subparam[of _ _ z _ y]) using assms apply auto\nusing geodesic_segment_split(1)[OF assms(1)] by auto\n\nend (*of context uniquely_geodesic_space*)\n\n\nsubsection \\<open>A complete metric space with middles is geodesic.\\<close>\n\ntext \\<open>A complete space in which every pair of points has a middle (i.e., a point $m$ which\nis half distance of $x$ and $y$) is geodesic: to construct a geodesic between $x_0$\nand $y_0$, first choose a middle $m$, then middles of the pairs $(x_0,m)$ and $(m, y_0)$, and so\non. This will define the geodesic on dyadic points (and this is indeed an isometry on these dyadic\npoints. Then, extend it by uniform continuity to the whole segment $[0, dist x0 y0]$.\n\nThe formal proof will be done in a locale where $x_0$ and $y_0$ are fixed, for notational simplicity.\nWe define inductively the sequence of middles, in a function \\verb+geod+ of two natural variables:\n$geod n m$ corresponds to the image of the dyadic point $m/2^n$. It is defined inductively, by\n$geod (n+1) (2m) = geod n m$, and $geod (n+1) (2m+1)$ is a middle of $geod n m$ and $geod n (m+1)$.\nThis is not a completely classical inductive definition, so one has to use \\verb+function+ to define\nit. Then, one checks inductively that it has all the properties we want, and use it to define the\ngeodesic segment on dyadic points. We will not use a canonical\nrepresentative for a dyadic point, but any representative (i.e., numerator and denominator\nwill not have to be coprime) -- this will not create problems as $geod$ does not depend on the choice\nof the representative, by construction.\\<close>\n\nlocale complete_space_with_middle =\n  fixes x0 y0::\"'a::complete_space\"\n  assumes middles: \"\\<And>x y::'a. \\<exists>z. dist x z = (dist x y)/2 \\<and> dist z y = (dist x y)/2\"\nbegin\n\ndefinition middle::\"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"\n  where \"middle x y = (SOME z. dist x z = (dist x y)/2 \\<and> dist z y = (dist x y)/2)\"\n\nlemma middle:\n  \"dist x (middle x y) = (dist x y)/2\"\n  \"dist (middle x y) y = (dist x y)/2\"\nunfolding middle_def using middles[of x y] by (metis (mono_tags, lifting) someI_ex)+\n\nfunction geod::\"nat \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n \"geod 0 0 = x0\"\n|\"geod 0 (Suc m) = y0\"\n|\"geod (Suc n) (2 * m) = geod n m\"\n|\"geod (Suc n) (Suc (2*m)) = middle (geod n m) (geod n (Suc m))\"\napply (auto simp add: double_not_eq_Suc_double)\nby (metis One_nat_def dvd_mult_div_cancel list_decode.cases odd_Suc_minus_one odd_two_times_div_two_nat)\ntermination by lexicographic_order\n\ntext \\<open>By induction, the distance between successive points is $D/2^n$.\\<close>\n\nlemma geod_distance_successor:\n  \"\\<forall>a < 2^n. dist (geod n a) (geod n (Suc a)) = dist x0 y0 / 2^n\"\nproof (induction n)\n  case 0\n  show ?case by auto\nnext\n  case (Suc n)\n  show ?case\n  proof (auto)\n    fix a::nat assume a: \"a < 2 * 2^n\"\n    obtain m where m: \"a = 2 * m \\<or> a = Suc (2 * m)\" by (metis geod.elims)\n    then have \"m < 2^n\" using a by auto\n    consider \"a = 2 * m\" | \"a = Suc(2*m)\" using m by auto\n    then show \"dist (geod (Suc n) a) (geod (Suc n) (Suc a)) = dist x0 y0 / (2 * 2 ^ n)\"\n    proof (cases)\n      case 1\n      show ?thesis\n        unfolding 1 apply auto\n        unfolding middle using Suc.IH \\<open>m < 2^n\\<close> by auto\n    next\n      case 2\n      have *: \"Suc (Suc (2 * m)) = 2 * (Suc m)\" by auto\n      show ?thesis\n        unfolding 2 apply auto\n        unfolding * geod.simps(3) middle using Suc.IH \\<open>m < 2^n\\<close> by auto\n    qed\n  qed\nqed\n\nlemma geod_mult:\n  \"geod n a = geod (n + k) (a * 2^k)\"\napply (induction k, auto) using geod.simps(3) by (metis mult.left_commute)\n\nlemma geod_0:\n  \"geod n 0 = x0\"\nby (induction n, auto, metis geod.simps(3) semiring_normalization_rules(10))\n\nlemma geod_end:\n  \"geod n (2^n) = y0\"\nby (induction n, auto)\n\ntext \\<open>By the triangular inequality, the distance between points separated by $(b-a)/2^n$ is at\nmost $D * (b-a)/2^n$.\\<close>\n\nlemma geod_upper:\n  assumes \"a \\<le> b\" \"b \\<le> 2^n\"\n  shows \"dist (geod n a) (geod n b) \\<le> (b-a) * dist x0 y0 / 2^n\"\nproof -\n  have *: \"a+k > 2^n \\<or> dist (geod n a) (geod n (a+k)) \\<le> k * dist x0 y0 / 2^n\" for k\n  proof (induction k)\n    case 0 then show ?case by auto\n  next\n    case (Suc k)\n    show ?case\n    proof (cases \"2 ^ n < a + Suc k\")\n      case True then show ?thesis by auto\n    next\n      case False\n      then have *: \"a + k < 2 ^ n\" by auto\n      have \"dist (geod n a) (geod n (a + Suc k)) \\<le> dist (geod n a) (geod n (a+k)) + dist (geod n (a+k)) (geod n (a+Suc k))\"\n        using dist_triangle by auto\n      also have \"... \\<le> k * dist x0 y0 / 2^n + dist x0 y0 / 2^n\"\n        using Suc.IH * geod_distance_successor by auto\n      finally show ?thesis\n        by (simp add: add_divide_distrib distrib_left mult.commute)\n    qed\n  qed\n  show ?thesis using *[of \"b-a\"] assms by (simp add: of_nat_diff)\nqed\n\ntext \\<open>In fact, the distance is exactly $D * (b-a)/2^n$, otherwise the extremities of the interval\nwould be closer than $D$, a contradiction.\\<close>\n\nlemma geod_dist:\n  assumes \"a \\<le> b\" \"b \\<le> 2^n\"\n  shows \"dist (geod n a) (geod n b) = (b-a) * dist x0 y0 / 2^n\"\nproof -\n  have \"dist (geod n a) (geod n b) \\<le> (real b-a) * dist x0 y0 / 2^n\"\n    using geod_upper[of a b n] assms by auto\n  moreover have \"\\<not> (dist (geod n a) (geod n b) < (real b-a) * dist x0 y0 / 2^n)\"\n  proof (rule ccontr, simp)\n    assume *: \"dist (geod n a) (geod n b) < (real b-a) * dist x0 y0 / 2^n\"\n    have \"dist x0 y0 = dist (geod n 0) (geod n (2^n))\"\n      using geod_0 geod_end by auto\n    also have \"... \\<le> dist (geod n 0) (geod n a) + dist (geod n a) (geod n b) + dist (geod n b) (geod n (2^n))\"\n      using dist_triangle4 by auto\n    also have \"... < a * dist x0 y0 / 2^n + (real b-a) * dist x0 y0 / 2^n + (2^n - real b) * dist x0 y0 / 2^n\"\n      using * assms geod_upper[of 0 a n] geod_upper[of b \"2^n\" n] by (auto intro: mono_intros)\n    also have \"... = dist x0 y0\"\n      using assms by (auto simp add: algebra_simps divide_simps)\n    finally show \"False\" by auto\n  qed\n  ultimately show ?thesis by auto\nqed\n\ntext \\<open>We deduce the same statement but for points that are not on the same level, by putting\nthem on a common multiple level.\\<close>\n\nlemma geod_dist2:\n  assumes \"a \\<le> 2^n\" \"b \\<le> 2^p\" \"a/2^n \\<le> b / 2^p\"\n  shows \"dist (geod n a) (geod p b) = (b/2^p - a/2^n) * dist x0 y0\"\nproof -\n  define r where \"r = max n p\"\n  define ar where \"ar = a * 2^(r - n)\"\n  have a: \"ar / 2^r = a / 2^n\"\n    unfolding ar_def r_def by (auto simp add: divide_simps semiring_normalization_rules(26))\n  have A: \"geod r ar = geod n a\"\n    unfolding ar_def r_def using geod_mult[of n a \"max n p - n\"] by auto\n  define br where \"br = b * 2^(r - p)\"\n  have b: \"br / 2^r = b / 2^p\"\n    unfolding br_def r_def by (auto simp add: divide_simps semiring_normalization_rules(26))\n  have B: \"geod r br = geod p b\"\n    unfolding br_def r_def using geod_mult[of p b \"max n p - p\"] by auto\n\n  have \"dist (geod n a) (geod p b) = dist (geod r ar) (geod r br)\"\n    using A B by auto\n  also have \"... = (real br - ar) * dist x0 y0 / 2 ^r\"\n    apply (rule geod_dist)\n    using \\<open>a/2^n \\<le> b / 2^p\\<close> unfolding a[symmetric] b[symmetric] apply (auto simp add: divide_simps)\n    using \\<open>b \\<le> 2^p\\<close> b apply (auto simp add: divide_simps)\n    by (metis br_def le_add_diff_inverse2 max.cobounded2 mult.commute mult_le_mono2 r_def semiring_normalization_rules(26))\n  also have \"... = (real br / 2^r - real ar / 2^r) * dist x0 y0\"\n    by (auto simp add: algebra_simps divide_simps)\n  finally show ?thesis using a b by auto\nqed\n\ntext \\<open>Same thing but without a priori ordering of the points.\\<close>\n\nlemma geod_dist3:\n  assumes \"a \\<le> 2^n\" \"b \\<le> 2^p\"\n  shows \"dist (geod n a) (geod p b) = abs(b/2^p - a/2^n) * dist x0 y0\"\napply (cases \"a /2^n \\<le> b/2^p\", auto)\napply (rule geod_dist2[OF assms], auto)\napply (subst dist_commute, rule geod_dist2[OF assms(2) assms(1)], auto)\ndone\n\ntext \\<open>Finally, we define a geodesic by extending what we have already defined on dyadic points,\nthanks to the result of isometric extension of isometries taking their values\nin complete spaces.\\<close>\n\nlemma geod:\n  shows \"\\<exists>g. isometry_on {0..dist x0 y0} g \\<and> g 0 = x0 \\<and> g (dist x0 y0) = y0\"\nproof (cases \"x0 = y0\")\n  case True\n  show ?thesis apply (rule exI[of _ \"\\<lambda>_. x0\"]) unfolding isometry_on_def using True by auto\nnext\n  case False\n  define A where \"A = {(real k/2^n) * dist x0 y0 |k n. k \\<le> 2^n}\"\n  have \"{0..dist x0 y0} \\<subseteq> closure A\"\n  proof (auto simp add: closure_approachable dist_real_def)\n    fix t::real assume t: \"0 \\<le> t\" \"t \\<le> dist x0 y0\"\n    fix e:: real assume \"e > 0\"\n    then obtain n::nat where n: \"dist x0 y0/e < 2^n\"\n      using one_less_numeral_iff real_arch_pow semiring_norm(76) by blast\n    define k where \"k = floor (2^n * t/ dist x0 y0)\"\n    have \"k \\<le> 2^n * t/ dist x0 y0\" unfolding k_def by auto\n    also have \"... \\<le> 2^n\" using t False by (auto simp add: algebra_simps divide_simps)\n    finally have \"k \\<le> 2^n\" by auto\n    have \"k \\<ge> 0\" using t False unfolding k_def by auto\n    define l where \"l = nat k\"\n    have \"k = int l\" \"l \\<le> 2^n\" using \\<open>k \\<ge> 0\\<close> \\<open>k \\<le> 2^n\\<close> nat_le_iff unfolding l_def by auto\n\n    have \"abs (2^n * t/dist x0 y0 - k) \\<le> 1\" unfolding k_def by linarith\n    then have \"abs(t - k/2^n * dist x0 y0) \\<le> dist x0 y0 / 2^n\"\n      by (auto simp add: algebra_simps divide_simps False)\n    also have \"... < e\" using n \\<open>e > 0\\<close> by (auto simp add: algebra_simps divide_simps)\n    finally have \"abs(t - k/2^n * dist x0 y0) < e\" by auto\n    then have \"abs(t - l/2^n * dist x0 y0) < e\" using \\<open>k = int l\\<close> by auto\n    moreover have \"l/2^n * dist x0 y0 \\<in> A\" unfolding A_def using \\<open>l \\<le> 2^n\\<close> by auto\n    ultimately show \"\\<exists>u\\<in>A. abs(u - t) < e\" by force\n  qed\n\n  text \\<open>For each dyadic point, we choose one representation of the form $K/2^N$, it is not important\n  for us that it is the minimal one.\\<close>\n  define index where \"index = (\\<lambda>t. SOME i. t = real (fst i)/2^(snd i) * dist x0 y0 \\<and> (fst i) \\<le> 2^(snd i))\"\n  define K where \"K = (\\<lambda>t. fst (index t))\"\n  define N where \"N = (\\<lambda>t. snd (index t))\"\n  have t: \"t = K t/ 2^(N t) * dist x0 y0 \\<and> K t \\<le> 2^(N t)\" if \"t \\<in> A\" for t\n  proof -\n    obtain n k::nat where \"t = k/2^n * dist x0 y0\" \"k \\<le> 2^n\" using \\<open>t\\<in> A\\<close> unfolding A_def by auto\n    then have *: \"\\<exists>i. t = real (fst i)/2^(snd i) * dist x0 y0 \\<and> (fst i) \\<le> 2^(snd i)\" by auto\n    show ?thesis unfolding K_def N_def index_def using someI_ex[OF *] by auto\n  qed\n\n  text \\<open>We can now define our function on dyadic points.\\<close>\n  define f where \"f = (\\<lambda>t. geod (N t) (K t))\"\n  have \"0 \\<in> A\" unfolding A_def by auto\n  have \"f 0 = x0\"\n  proof -\n    have \"0 = K 0 /2^(N 0) * dist x0 y0\" using t \\<open>0 \\<in> A\\<close> by auto\n    then have \"K 0 = 0\" using False by auto\n    then show ?thesis unfolding f_def using geod_0 by auto\n  qed\n  have \"dist x0 y0 = (real 1/2^0) * dist x0 y0\" by auto\n  then have \"dist x0 y0 \\<in> A\" unfolding A_def by force\n  have \"f (dist x0 y0) = y0\"\n  proof -\n    have \"dist x0 y0 = K (dist x0 y0) / 2^(N (dist x0 y0)) * dist x0 y0\"\n      using t \\<open>dist x0 y0 \\<in> A\\<close> by auto\n    then have \"K (dist x0 y0) = 2^(N(dist x0 y0))\" using False by (auto simp add: divide_simps)\n    then show ?thesis unfolding f_def using geod_end by auto\n  qed\n  text \\<open>By construction, it is an isometry on dyadic points.\\<close>\n  have \"isometry_on A f\"\n  proof (rule isometry_onI)\n    fix s t assume inA: \"s \\<in> A\" \"t \\<in> A\"\n    have \"dist (f s) (f t) = abs (K t/2^(N t) - K s/2^(N s)) * dist x0 y0\"\n      unfolding f_def apply (rule geod_dist3) using t inA by auto\n    also have \"... = abs(K t/2^(N t) * dist x0 y0 - K s/2^(N s) * dist x0 y0)\"\n      by (auto simp add: abs_mult_pos left_diff_distrib)\n    also have \"... = abs(t - s)\"\n      using t inA by auto\n    finally show \"dist (f s) (f t) = dist s t\" unfolding dist_real_def by auto\n  qed\n  text \\<open>We can thus extend it to an isometry on the closure of dyadic points.\n  It is the desired geodesic.\\<close>\n  then obtain g where g: \"isometry_on (closure A) g\" \"\\<And>t. t \\<in> A \\<Longrightarrow> g t = f t\"\n    using isometry_extend_closure by metis\n  have \"isometry_on {0..dist x0 y0} g\"\n    by (rule isometry_on_subset[OF \\<open>isometry_on (closure A) g\\<close> \\<open>{0..dist x0 y0} \\<subseteq> closure A\\<close>])\n  moreover have \"g 0 = x0\"\n    using g(2)[OF \\<open>0 \\<in> A\\<close>] \\<open>f 0 = x0\\<close> by simp\n  moreover have \"g (dist x0 y0) = y0\"\n    using g(2)[OF \\<open>dist x0 y0 \\<in> A\\<close>] \\<open>f (dist x0 y0) = y0\\<close> by simp\n  ultimately show ?thesis by auto\nqed\n\nend\n\ntext \\<open>We can now complete the proof that a complete space with middles is in fact geodesic:\nall the work has been done in the locale \\verb+complete_space_with_middle+, in Lemma~\\verb+geod+.\\<close>\n\ntheorem complete_with_middles_imp_geodesic:\n  assumes \"\\<And>x y::('a::complete_space). \\<exists>m. dist x m = dist x y /2 \\<and> dist m y = dist x y /2\"\n  shows \"OFCLASS('a, geodesic_space_class)\"\nproof (standard, rule geodesic_subsetI)\n  fix x0 y0::'a\n  interpret complete_space_with_middle x0 y0\n    apply standard using assms by auto\n  have \"\\<exists>g. g 0 = x0 \\<and> g (dist x0 y0) = y0 \\<and> isometry_on {0..dist x0 y0} g\"\n    using geod by auto\n  then show \"\\<exists>G. geodesic_segment_between G x0 y0 \\<and> G \\<subseteq> UNIV\"\n    unfolding geodesic_segment_between_def by auto\nqed\n\n\nsection \\<open>Quasi-isometries\\<close>\n\ntext \\<open>A $(\\lambda, C)$ quasi-isometry is a function which behaves like an isometry, up to\nan additive error $C$ and a multiplicative error $\\lambda$. It can be very different from an\nisometry on small scales (for instance, the function integer part is a quasi-isometry between\n$\\mathbb{R}$ and $\\mathbb{Z}$), but on large scales it captures many important features of\nisometries.\n\nWhen the space is unbounded, one checks easily that $C \\geq 0$ and $\\lambda \\geq 1$. As this\nis the only case of interest (any two bounded sets are quasi-isometric), we incorporate\nthis requirement in the definition.\\<close>\n\ndefinition quasi_isometry_on::\"real \\<Rightarrow> real \\<Rightarrow> ('a::metric_space) set \\<Rightarrow> ('a \\<Rightarrow> ('b::metric_space)) \\<Rightarrow> bool\"\n  (\"_ _ -quasi'_isometry'_on\" [1000, 999])\n  where \"lambda C-quasi_isometry_on X f = ((lambda \\<ge> 1) \\<and> (C \\<ge> 0) \\<and>\n    (\\<forall>x \\<in> X. \\<forall>y \\<in> X. (dist (f x) (f y) \\<le> lambda * dist x y + C \\<and> dist (f x) (f y) \\<ge> (1/lambda) * dist x y - C)))\"\n\nabbreviation quasi_isometry :: \"real \\<Rightarrow> real \\<Rightarrow> ('a::metric_space \\<Rightarrow> 'b::metric_space) \\<Rightarrow> bool\"\n  (\"_ _ -quasi'_isometry\" [1000, 999])\n  where \"quasi_isometry lambda C f \\<equiv> lambda C-quasi_isometry_on UNIV f\"\n\nsubsection \\<open>Basic properties of quasi-isometries\\<close>\n\nlemma quasi_isometry_onD:\n  assumes \"lambda C-quasi_isometry_on X f\"\n  shows \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) \\<le> lambda * dist x y + C\"\n        \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) \\<ge> (1/lambda) * dist x y - C\"\n        \"lambda \\<ge> 1\" \"C \\<ge> 0\"\nusing assms unfolding quasi_isometry_on_def by auto\n\nlemma quasi_isometry_onI [intro]:\n  assumes \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) \\<le> lambda * dist x y + C\"\n          \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) \\<ge> (1/lambda) * dist x y - C\"\n          \"lambda \\<ge> 1\" \"C \\<ge> 0\"\n  shows \"lambda C-quasi_isometry_on X f\"\nusing assms unfolding quasi_isometry_on_def by auto\n\nlemma isometry_quasi_isometry_on:\n  assumes \"isometry_on X f\"\n  shows \"1 0-quasi_isometry_on X f\"\nusing assms unfolding isometry_on_def quasi_isometry_on_def by auto\n\nlemma quasi_isometry_on_change_params:\n  assumes \"lambda C-quasi_isometry_on X f\" \"mu \\<ge> lambda\" \"D \\<ge> C\"\n  shows \"mu D-quasi_isometry_on X f\"\nproof (rule quasi_isometry_onI)\n  have P1: \"lambda \\<ge> 1\" \"C \\<ge> 0\" using quasi_isometry_onD[OF assms(1)] by auto\n  then show P2: \"mu \\<ge> 1\" \"D \\<ge> 0\" using assms by auto\n  fix x y assume inX: \"x \\<in> X\" \"y \\<in> X\"\n  have \"dist (f x) (f y) \\<le> lambda * dist x y + C\"\n    using quasi_isometry_onD[OF assms(1)] inX by auto\n  also have \"... \\<le> mu * dist x y + D\"\n    using assms by (auto intro!: mono_intros)\n  finally show \"dist (f x) (f y) \\<le> mu * dist x y + D\" by simp\n  have \"dist (f x) (f y) \\<ge> (1/lambda) * dist x y - C\"\n    using quasi_isometry_onD[OF assms(1)] inX by auto\n  moreover have \"(1/lambda) * dist x y + (- C) \\<ge> (1/mu) * dist x y + (- D)\"\n    apply (intro mono_intros)\n    using P1 P2 assms by (auto simp add: divide_simps)\n  ultimately show \"dist (f x) (f y) \\<ge> (1/mu) * dist x y - D\" by simp\nqed\n\nlemma quasi_isometry_on_subset:\n  assumes \"lambda C-quasi_isometry_on X f\"\n          \"Y \\<subseteq> X\"\n  shows \"lambda C-quasi_isometry_on Y f\"\nusing assms unfolding quasi_isometry_on_def by auto\n\nlemma quasi_isometry_on_perturb:\n  assumes \"lambda C-quasi_isometry_on X f\"\n          \"D \\<ge> 0\"\n          \"\\<And>x. x \\<in> X \\<Longrightarrow> dist (f x) (g x) \\<le> D\"\n  shows \"lambda (C + 2 * D)-quasi_isometry_on X g\"\nproof (rule quasi_isometry_onI)\n  show \"lambda \\<ge> 1\" \"C + 2 * D \\<ge> 0\" using \\<open>D \\<ge> 0\\<close> quasi_isometry_onD[OF assms(1)] by auto\n  fix x y assume *: \"x \\<in> X\" \"y \\<in> X\"\n  have \"dist (g x) (g y) \\<le> dist (f x) (f y) + 2 * D\"\n    using assms(3)[OF *(1)] assms(3)[OF *(2)] dist_triangle4[of \"g x\" \"g y\" \"f x\" \"f y\"] by (simp add: dist_commute)\n  then show \"dist (g x) (g y) \\<le> lambda * dist x y + (C + 2 * D)\"\n    using quasi_isometry_onD(1)[OF assms(1) *] by auto\n  have \"dist (g x) (g y) \\<ge> dist (f x) (f y) - 2 * D\"\n    using assms(3)[OF *(1)] assms(3)[OF *(2)] dist_triangle4[of \"f x\" \"f y\" \"g x\" \"g y\"] by (simp add: dist_commute)\n  then show \"dist (g x) (g y) \\<ge> (1/lambda) * dist x y - (C + 2 * D)\"\n    using quasi_isometry_onD(2)[OF assms(1) *] by auto\nqed\n\nlemma quasi_isometry_on_compose:\n  assumes \"lambda C-quasi_isometry_on X f\"\n          \"mu D-quasi_isometry_on Y g\"\n          \"f`X \\<subseteq> Y\"\n  shows \"(lambda * mu) (C * mu + D)-quasi_isometry_on X (g o f)\"\nproof (rule quasi_isometry_onI)\n  have I: \"lambda \\<ge> 1\" \"C \\<ge> 0\" \"mu \\<ge> 1\" \"D \\<ge> 0\"\n    using quasi_isometry_onD[OF assms(1)] quasi_isometry_onD[OF assms(2)] by auto\n  then show \"lambda * mu \\<ge> 1\" \"C * mu + D \\<ge> 0\"\n    by (auto, metis dual_order.order_iff_strict le_numeral_extra(2) mult_le_cancel_right1 order.strict_trans1)\n  fix x y assume inX: \"x \\<in> X\" \"y \\<in> X\"\n  then have inY: \"f x \\<in> Y\" \"f y \\<in> Y\" using \\<open>f`X \\<subseteq> Y\\<close> by auto\n  have \"dist ((g o f) x) ((g o f) y) \\<le> mu * dist (f x) (f y) + D\"\n    using quasi_isometry_onD(1)[OF assms(2) inY] by simp\n  also have \"... \\<le> mu * (lambda * dist x y + C) + D\"\n    using \\<open>mu \\<ge> 1\\<close> quasi_isometry_onD(1)[OF assms(1) inX] by auto\n  finally show \"dist ((g o f) x) ((g o f) y) \\<le> (lambda * mu) * dist x y + (C * mu + D)\"\n    by (auto simp add: algebra_simps)\n\n  have \"(1/(lambda * mu)) * dist x y - (C * mu + D) \\<le> (1/(lambda * mu)) * dist x y - (C/mu + D)\"\n    using \\<open>mu \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> apply (auto, auto simp add: divide_simps)\n    by (metis eq_iff less_eq_real_def mult.commute mult_eq_0_iff mult_le_cancel_right1 order.trans)\n  also have \"... = (1/mu) * ((1/lambda) * dist x y - C) - D\"\n    by (auto simp add: algebra_simps)\n  also have \"... \\<le> (1/mu) * dist (f x) (f y) - D\"\n    using \\<open>mu \\<ge> 1\\<close> quasi_isometry_onD(2)[OF assms(1) inX] by (auto simp add: divide_simps)\n  also have \"... \\<le> dist ((g o f) x) ((g o f) y)\"\n    using quasi_isometry_onD(2)[OF assms(2) inY] by auto\n  finally show \"1 / (lambda * mu) * dist x y - (C * mu + D) \\<le> dist ((g \\<circ> f) x) ((g \\<circ> f) y)\"\n    by auto\nqed\n\nlemma quasi_isometry_on_bounded:\n  assumes \"lambda C-quasi_isometry_on X f\"\n          \"bounded X\"\n  shows \"bounded (f`X)\"\nproof (cases \"X = {}\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  obtain x where \"x \\<in> X\" using False by auto\n  obtain e where e: \"\\<And>z. z \\<in> X \\<Longrightarrow> dist x z \\<le> e\"\n    using bounded_any_center assms(2) by metis\n  have \"dist (f x) y \\<le> C + lambda * e\" if \"y \\<in> f`X\" for y\n  proof -\n    obtain z where *: \"z \\<in> X\" \"y = f z\" using \\<open>y \\<in> f`X\\<close> by auto\n    have \"dist (f x) y \\<le> lambda * dist x z + C\"\n      unfolding \\<open>y = f z\\<close> using * quasi_isometry_onD(1)[OF assms(1) \\<open>x \\<in> X\\<close> \\<open>z \\<in> X\\<close>] by (auto simp add: add_mono)\n    also have \"... \\<le> C + lambda * e\" using e[OF \\<open>z \\<in> X\\<close>] quasi_isometry_onD(3)[OF assms(1)] by auto\n    finally show ?thesis by simp\n  qed\n  then show ?thesis unfolding bounded_def by auto\nqed\n\nlemma quasi_isometry_on_empty:\n  assumes \"C \\<ge> 0\" \"lambda \\<ge> 1\"\n  shows \"lambda C-quasi_isometry_on {} f\"\nusing assms unfolding quasi_isometry_on_def by auto\n\ntext \\<open>Quasi-isometries change the distance to a set by at most $\\lambda \\cdot + C$, this follows\nreadily from the fact that this inequality holds pointwise.\\<close>\n\nlemma quasi_isometry_on_infdist:\n  assumes \"lambda C-quasi_isometry_on X f\"\n          \"w \\<in> X\"\n          \"S \\<subseteq> X\"\n  shows \"infdist (f w) (f`S) \\<le> lambda * infdist w S + C\"\n        \"infdist (f w) (f`S) \\<ge> (1/lambda) * infdist w S - C\"\nproof -\n  have \"lambda \\<ge> 1\" \"C \\<ge> 0\" using quasi_isometry_onD[OF assms(1)] by auto\n  show \"infdist (f w) (f`S) \\<le> lambda * infdist w S + C\"\n  proof (cases \"S = {}\")\n    case True\n    then show ?thesis\n      using \\<open>C \\<ge> 0\\<close> unfolding infdist_def by auto\n  next\n    case False\n    then have \"(INF x\\<in>S. dist (f w) (f x)) \\<le> (INF x\\<in>S. lambda * dist w x + C)\"\n      apply (rule cINF_superset_mono)\n        apply (meson bdd_belowI2 zero_le_dist) using assms by (auto intro!: quasi_isometry_onD(1)[OF assms(1)])\n    also have \"... = (INF t\\<in>(dist w)`S. lambda * t + C)\"\n      by (auto simp add: image_comp)\n    also have \"... = lambda * Inf ((dist w)`S) + C\"\n      apply (rule continuous_at_Inf_mono[symmetric])\n      unfolding mono_def using \\<open>lambda \\<ge> 1\\<close> False by (auto intro!: continuous_intros)\n    finally show ?thesis unfolding infdist_def using False by (auto simp add: image_comp)\n  qed\n  show \"1 / lambda * infdist w S - C \\<le> infdist (f w) (f ` S)\"\n  proof (cases \"S = {}\")\n    case True\n    then show ?thesis\n      using \\<open>C \\<ge> 0\\<close> unfolding infdist_def by auto\n  next\n    case False\n    then have \"(1/lambda) * infdist w S - C = (1/lambda) * Inf ((dist w)`S) - C\"\n      unfolding infdist_def by auto\n    also have \"... = (INF t\\<in>(dist w)`S. (1/lambda) * t - C)\"\n      apply (rule continuous_at_Inf_mono)\n      unfolding mono_def using \\<open>lambda \\<ge> 1\\<close> False by (auto simp add: divide_simps intro!: continuous_intros)\n    also have \"... = (INF x\\<in>S. (1/lambda) * dist w x - C)\"\n      by (auto simp add: image_comp)\n    also have \"... \\<le> (INF x\\<in>S. dist (f w) (f x))\"\n      apply (rule cINF_superset_mono[OF False]) apply (rule bdd_belowI2[of _ \"-C\"])\n      using assms \\<open>lambda \\<ge> 1\\<close> apply simp apply simp apply (rule quasi_isometry_onD(2)[OF assms(1)])\n      using assms by auto\n    finally show ?thesis unfolding infdist_def using False by (auto simp add: image_comp)\n  qed\nqed\n\nsubsection \\<open>Quasi-isometric isomorphisms\\<close>\n\ntext \\<open>The notion of isomorphism for quasi-isometries is not that it should be a bijection, as it is\na coarse notion, but that it is a bijection up to a bounded displacement. For instance, the\ninclusion of $\\mathbb{Z}$ in $\\mathbb{R}$ is a quasi-isometric isomorphism between these spaces,\nwhose (quasi)-inverse (which is non-unique) is given by the function integer part. This is\nformalized in the next definition.\\<close>\n\ndefinition quasi_isometry_between::\"real \\<Rightarrow> real \\<Rightarrow> ('a::metric_space) set \\<Rightarrow> ('b::metric_space) set \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  (\"_ _ -quasi'_isometry'_between\" [1000, 999])\n  where \"lambda C-quasi_isometry_between X Y f = ((lambda C-quasi_isometry_on X f) \\<and> (f`X \\<subseteq> Y) \\<and> (\\<forall>y\\<in>Y. \\<exists>x\\<in>X. dist (f x) y \\<le> C))\"\n\ndefinition quasi_isometric::\"('a::metric_space) set \\<Rightarrow> ('b::metric_space) set \\<Rightarrow> bool\"\n  where \"quasi_isometric X Y = (\\<exists>lambda C f. lambda C-quasi_isometry_between X Y f)\"\n\nlemma quasi_isometry_betweenD:\n  assumes \"lambda C-quasi_isometry_between X Y f\"\n  shows \"lambda C-quasi_isometry_on X f\"\n        \"f`X \\<subseteq> Y\"\n        \"\\<And>y. y \\<in> Y \\<Longrightarrow> \\<exists>x\\<in>X. dist (f x) y \\<le> C\"\n        \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) \\<le> lambda * dist x y + C\"\n        \"\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> dist (f x) (f y) \\<ge> (1/lambda) * dist x y - C\"\n        \"lambda \\<ge> 1\" \"C \\<ge> 0\"\nusing assms unfolding quasi_isometry_between_def quasi_isometry_on_def by auto\n\nlemma quasi_isometry_betweenI:\n  assumes \"lambda C-quasi_isometry_on X f\"\n          \"f`X \\<subseteq> Y\"\n          \"\\<And>y. y \\<in> Y \\<Longrightarrow> \\<exists>x\\<in>X. dist (f x) y \\<le> C\"\n  shows \"lambda C-quasi_isometry_between X Y f\"\nusing assms unfolding quasi_isometry_between_def by auto\n\nlemma quasi_isometry_on_between:\n  assumes \"lambda C-quasi_isometry_on X f\"\n  shows \"lambda C-quasi_isometry_between X (f`X) f\"\nusing assms unfolding quasi_isometry_between_def quasi_isometry_on_def by force\n\nlemma quasi_isometry_between_change_params:\n  assumes \"lambda C-quasi_isometry_between X Y f\" \"mu \\<ge> lambda\" \"D \\<ge> C\"\n  shows \"mu D-quasi_isometry_between X Y f\"\nproof (rule quasi_isometry_betweenI)\n  show \"mu D-quasi_isometry_on X f\"\n    by (rule quasi_isometry_on_change_params[OF quasi_isometry_betweenD(1)[OF assms(1)] assms(2) assms(3)])\n  show \"f`X \\<subseteq> Y\" using quasi_isometry_betweenD[OF assms(1)] by auto\n  fix y assume \"y \\<in> Y\"\n  show \"\\<exists>x\\<in>X. dist (f x) y \\<le> D\" using quasi_isometry_betweenD(3)[OF assms(1) \\<open>y \\<in> Y\\<close>] \\<open>D \\<ge> C\\<close> by force\nqed\n\nlemma quasi_isometry_subset:\n  assumes \"X \\<subseteq> Y\" \"\\<And>y. y \\<in> Y \\<Longrightarrow> \\<exists>x\\<in>X. dist x y \\<le> C\" \"C \\<ge> 0\"\n  shows \"1 C-quasi_isometry_between X Y (\\<lambda>x. x)\"\nunfolding quasi_isometry_between_def using assms by auto\n\nlemma isometry_quasi_isometry_between:\n  assumes \"isometry f\"\n  shows \"1 0-quasi_isometry_between UNIV UNIV f\"\nusing assms unfolding quasi_isometry_between_def quasi_isometry_on_def isometry_def isometry_on_def surj_def by (auto) metis\n\nproposition quasi_isometry_inverse:\n  assumes \"lambda C-quasi_isometry_between X Y f\"\n  shows \"\\<exists>g. lambda (3 * C * lambda)-quasi_isometry_between Y X g\n          \\<and> (\\<forall>x\\<in>X. dist x (g (f x)) \\<le> 3 * C * lambda)\n          \\<and> (\\<forall>y\\<in>Y. dist y (f (g y)) \\<le> 3 * C * lambda)\"\nproof -\n  define g where \"g = (\\<lambda>y. SOME x. x \\<in> X \\<and> dist (f x) y \\<le> C)\"\n  have *: \"g y \\<in> X \\<and> dist (f (g y)) y \\<le> C\" if \"y \\<in> Y\" for y\n    unfolding g_def using quasi_isometry_betweenD(3)[OF assms that] by (metis (no_types, lifting) someI_ex)\n  have \"lambda \\<ge> 1\" \"C \\<ge> 0\" using quasi_isometry_betweenD[OF assms] by auto\n\n  have \"C \\<le> 3 * C * lambda\" using \\<open>lambda \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close>\n    by (simp add: algebra_simps mult_ge1_mono)\n  then have A: \"dist y (f (g y)) \\<le> 3 * C * lambda\" if \"y \\<in> Y\" for y\n    using *[OF that] by (simp add: dist_commute)\n\n  have B: \"dist x (g (f x)) \\<le> 3 * C * lambda\" if \"x \\<in> X\" for x\n  proof -\n    have \"f x \\<in> Y\" using that quasi_isometry_betweenD(2)[OF assms] by auto\n    have \"(1/lambda) * dist x (g (f x)) - C \\<le> dist (f x) (f (g (f x)))\"\n      apply (rule quasi_isometry_betweenD(5)[OF assms]) using that *[OF \\<open>f x \\<in> Y\\<close>] by auto\n    also have \"... \\<le> C\" using *[OF \\<open>f x \\<in> Y\\<close>] by (simp add: dist_commute)\n    finally have \"dist x (g (f x)) \\<le> 2 * C * lambda\"\n      using \\<open>lambda \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> by (simp add: divide_simps)\n    also have \"... \\<le> 3 * C * lambda\"\n      using \\<open>lambda \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> by (simp add: divide_simps)\n    finally show ?thesis by auto\n  qed\n\n  have \"lambda (3 * C * lambda)-quasi_isometry_on Y g\"\n  proof (rule quasi_isometry_onI)\n    show \"lambda \\<ge> 1\" \"3 * C * lambda \\<ge> 0\" using \\<open>lambda \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> by auto\n    fix y1 y2 assume inY: \"y1 \\<in> Y\" \"y2 \\<in> Y\"\n    then have inX: \"g y1 \\<in> X\" \"g y2 \\<in> X\" using * by auto\n    have \"dist y1 y2 \\<le> dist y1 (f (g y1)) + dist (f (g y1)) (f (g y2)) + dist (f (g y2)) y2\"\n      using dist_triangle4 by auto\n    also have \"... \\<le> C + dist (f (g y1)) (f (g y2)) + C\"\n      using *[OF inY(1)] *[OF inY(2)] by (auto simp add: dist_commute intro: add_mono)\n    also have \"... \\<le> C + (lambda * dist (g y1) (g y2) + C) + C\"\n      using quasi_isometry_betweenD(4)[OF assms inX] by (auto intro: add_mono)\n    finally have \"dist y1 y2 - 3 * C \\<le> lambda * dist (g y1) (g y2)\" by auto\n    then have \"dist (g y1) (g y2) \\<ge> (1/lambda) * dist y1 y2 - 3 * C / lambda\"\n      using \\<open>lambda \\<ge> 1\\<close> by (auto simp add: divide_simps mult.commute)\n    moreover have \"3 * C / lambda \\<le> 3 * C * lambda\"\n      using \\<open>lambda \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> apply (auto simp add: divide_simps mult_le_cancel_left1)\n      by (metis dual_order.order_iff_strict less_1_mult mult.left_neutral)\n    ultimately show \"dist (g y1) (g y2) \\<ge> (1/lambda) * dist y1 y2 - 3 * C * lambda\"\n      by auto\n\n    have \"(1/lambda) * dist (g y1) (g y2) - C \\<le> dist (f (g y1)) (f (g y2))\"\n      using quasi_isometry_betweenD(5)[OF assms inX] by auto\n    also have \"... \\<le> dist (f (g y1)) y1 + dist y1 y2 + dist y2 (f (g y2))\"\n      using dist_triangle4 by auto\n    also have \"... \\<le> C + dist y1 y2 + C\"\n      using *[OF inY(1)] *[OF inY(2)] by (auto simp add: dist_commute intro: add_mono)\n    finally show \"dist (g y1) (g y2) \\<le> lambda * dist y1 y2 + 3 * C * lambda\"\n      using \\<open>lambda \\<ge> 1\\<close> by (auto simp add: divide_simps algebra_simps)\n  qed\n  then have \"lambda (3 * C * lambda)-quasi_isometry_between Y X g\"\n  proof (rule quasi_isometry_betweenI)\n    show \"g ` Y \\<subseteq> X\" using * by auto\n    fix x assume \"x \\<in> X\"\n    have \"f x \\<in> Y\" \"dist (g (f x)) x \\<le> 3 * C * lambda\"\n      using B[OF \\<open>x \\<in> X\\<close>] quasi_isometry_betweenD(2)[OF assms] \\<open>x \\<in> X\\<close> by (auto simp add: dist_commute)\n    then show \"\\<exists>y\\<in>Y. dist (g y) x \\<le> 3 * C * lambda\" by blast\n  qed\n  then show ?thesis using A B by blast\nqed\n\nproposition quasi_isometry_compose:\n  assumes \"lambda C-quasi_isometry_between X Y f\"\n          \"mu D-quasi_isometry_between Y Z g\"\n  shows \"(lambda * mu) (C * mu + 2 * D)-quasi_isometry_between X Z (g o f)\"\nproof (rule quasi_isometry_betweenI)\n  have \"(lambda * mu) (C * mu + D)-quasi_isometry_on X (g \\<circ> f)\"\n    by (rule quasi_isometry_on_compose[OF quasi_isometry_betweenD(1)[OF assms(1)]\n        quasi_isometry_betweenD(1)[OF assms(2)] quasi_isometry_betweenD(2)[OF assms(1)]])\n  then show \"(lambda * mu) (C * mu + 2 * D)-quasi_isometry_on X (g \\<circ> f)\"\n    apply (rule quasi_isometry_on_change_params) using quasi_isometry_betweenD(7)[OF assms(2)] by auto\n\n  show \"(g \\<circ> f) ` X \\<subseteq> Z\"\n    using quasi_isometry_betweenD(2)[OF assms(1)] quasi_isometry_betweenD(2)[OF assms(2)]\n    by auto\n  fix z assume \"z \\<in> Z\"\n  obtain y where y: \"y \\<in> Y\" \"dist (g y) z \\<le> D\"\n    using quasi_isometry_betweenD(3)[OF assms(2) \\<open>z \\<in> Z\\<close>] by auto\n  obtain x where x: \"x \\<in> X\" \"dist (f x) y \\<le> C\"\n    using quasi_isometry_betweenD(3)[OF assms(1) \\<open>y \\<in> Y\\<close>] by auto\n  have \"dist ((g o f) x) z \\<le> dist (g (f x)) (g y) + dist (g y) z\"\n    using dist_triangle by auto\n  also have \"... \\<le> (mu * dist (f x) y + D) + D\"\n    apply (rule add_mono, rule quasi_isometry_betweenD(4)[OF assms(2)])\n    using x y quasi_isometry_betweenD(2)[OF assms(1)] by auto\n  also have \"... \\<le> C * mu + 2 * D\"\n    using x(2) quasi_isometry_betweenD(6)[OF assms(2)] by auto\n  finally show \"\\<exists>x\\<in>X. dist ((g \\<circ> f) x) z \\<le> C * mu + 2 * D\"\n    using x(1) by auto\nqed\n\ntheorem quasi_isometric_equiv_rel:\n  \"quasi_isometric X X\"\n  \"quasi_isometric X Y \\<Longrightarrow> quasi_isometric Y Z \\<Longrightarrow> quasi_isometric X Z\"\n  \"quasi_isometric X Y \\<Longrightarrow> quasi_isometric Y X\"\nproof -\n  show \"quasi_isometric X X\"\n    unfolding quasi_isometric_def using quasi_isometry_subset[of X X 0] by auto\n  assume H: \"quasi_isometric X Y\"\n  then show \"quasi_isometric Y X\"\n    unfolding quasi_isometric_def using quasi_isometry_inverse by blast\n  assume \"quasi_isometric Y Z\"\n  then show \"quasi_isometric X Z\"\n    using H unfolding quasi_isometric_def using quasi_isometry_compose by blast\nqed\n\ntext \\<open>Many interesting properties in geometric group theory are invariant under quasi-isometry.\nWe prove the most basic ones here.\\<close>\n\nlemma quasi_isometric_empty:\n  assumes \"X = {}\" \"quasi_isometric X Y\"\n  shows \"Y = {}\"\nusing assms unfolding quasi_isometric_def quasi_isometry_between_def quasi_isometry_on_def by blast\n\nlemma quasi_isometric_bounded:\n  assumes \"bounded X\" \"quasi_isometric X Y\"\n  shows \"bounded Y\"\nproof (cases \"X = {}\")\n  case True\n  show ?thesis using quasi_isometric_empty[OF True assms(2)] by auto\nnext\n  case False\n  obtain lambda C f where QI: \"lambda C-quasi_isometry_between X Y f\"\n    using assms(2) unfolding quasi_isometric_def by auto\n  obtain x where \"x \\<in> X\" using False by auto\n  obtain e where e: \"\\<And>z. z \\<in> X \\<Longrightarrow> dist x z \\<le> e\"\n    using bounded_any_center assms(1) by metis\n  have \"dist (f x) y \\<le> 2 * C + lambda * e\" if \"y \\<in> Y\" for y\n  proof -\n    obtain z where *: \"z \\<in> X\" \"dist (f z) y \\<le> C\"\n      using quasi_isometry_betweenD(3)[OF QI \\<open>y \\<in> Y\\<close>] by auto\n    have \"dist (f x) y \\<le> dist (f x) (f z) + dist (f z) y\" using dist_triangle by auto\n    also have \"... \\<le> (lambda * dist x z + C) + C\"\n      using * quasi_isometry_betweenD(4)[OF QI \\<open>x \\<in> X\\<close> \\<open>z \\<in> X\\<close>] by (auto simp add: add_mono)\n    also have \"... \\<le> 2 * C + lambda * e\"\n      using quasi_isometry_betweenD(6)[OF QI] e[OF \\<open>z \\<in> X\\<close>] by (auto simp add: algebra_simps)\n    finally show ?thesis by simp\n  qed\n  then show ?thesis unfolding bounded_def by auto\nqed\n\nlemma quasi_isometric_bounded_iff:\n  assumes \"bounded X\" \"X \\<noteq> {}\" \"bounded Y\" \"Y \\<noteq> {}\"\n  shows \"quasi_isometric X Y\"\nproof -\n  obtain x y where \"x \\<in> X\" \"y \\<in> Y\" using assms by auto\n  obtain C where C: \"\\<And>z. z \\<in> Y \\<Longrightarrow> dist y z \\<le> C\"\n    using \\<open>bounded Y\\<close> bounded_any_center by metis\n  have \"C \\<ge> 0\" using C[OF \\<open>y \\<in> Y\\<close>] by auto\n  obtain D where D: \"\\<And>z. z \\<in> X \\<Longrightarrow> dist x z \\<le> D\"\n    using \\<open>bounded X\\<close> bounded_any_center by metis\n  have \"D \\<ge> 0\" using D[OF \\<open>x \\<in> X\\<close>] by auto\n\n  define f::\"'a \\<Rightarrow> 'b\" where \"f = (\\<lambda>_. y)\"\n  have \"1 (C + 2 * D)-quasi_isometry_between X Y f\"\n  proof (rule quasi_isometry_betweenI)\n    show \"f`X \\<subseteq> Y\" unfolding f_def using \\<open>y \\<in> Y\\<close> by auto\n    show \"1 (C + 2 * D)-quasi_isometry_on X f\"\n    proof (rule quasi_isometry_onI, auto simp add: \\<open>C \\<ge> 0\\<close> \\<open>D \\<ge> 0\\<close> f_def)\n      fix a b assume \"a \\<in> X\" \"b \\<in> X\"\n      have \"dist a b \\<le> dist a x + dist x b\"\n        using dist_triangle by auto\n      also have \"... \\<le> D + D\"\n        using D[OF \\<open>a \\<in> X\\<close>] D[OF \\<open>b \\<in> X\\<close>] by (auto simp add: dist_commute)\n      finally show \"dist a b \\<le> C + 2 * D\" using \\<open>C \\<ge> 0\\<close> by auto\n    qed\n    show \"\\<exists>a\\<in>X. dist (f a) z \\<le> C + 2 * D\" if \"z \\<in> Y\" for z\n      unfolding f_def using \\<open>x \\<in> X\\<close> C[OF \\<open>z \\<in> Y\\<close>] \\<open>D \\<ge> 0\\<close> by auto\n  qed\n  then show ?thesis unfolding quasi_isometric_def by auto\nqed\n\nsubsection \\<open>Quasi-isometries of Euclidean spaces.\\<close>\n\ntext \\<open>A less trivial fact is that the dimension of euclidean spaces is invariant under\nquasi-isometries. It is proved below using growth argument, as quasi-isometries preserve the\ngrowth rate.\n\nThe growth of the space is asymptotic behavior of the number of well-separated points that\nfit in a ball of radius $R$, when $R$ tends to infinity. Up to a suitable equivalence, it is\nclearly a quasi-isometry invariance. We show below that, in a Euclidean space of dimension $d$,\nthe growth is like $R^d$: the upper bound is obtained by using the fact that we have disjoint balls\ninside a big ball, hence volume controls conclude the argument, while the lower bound is obtained\nby considering integer points.\\<close>\n\ntext \\<open>First, we show that the growth rate of a Euclidean space of dimension $d$ is bounded\nfrom above by $R^d$, using the control on measure of disjoint balls and a volume argument.\\<close>\n\nproposition growth_rate_euclidean_above:\n  fixes D::real\n  assumes \"D > (0::real)\"\n      and H: \"F \\<subseteq> cball (0::'a::euclidean_space) R\" \"R \\<ge> 0\"\n          \"\\<And>x y. x \\<in> F \\<Longrightarrow> y \\<in> F \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> dist x y \\<ge> D\"\n  shows \"finite F \\<and> card F \\<le> 1 + ((6/D)^(DIM('a))) * R^(DIM('a))\"\nproof -\n  define C::real where \"C = ((6/D)^(DIM('a)))\"\n  have \"C \\<ge> 0\" unfolding C_def using \\<open>D > 0\\<close> by auto\n  have \"D/3 \\<ge> 0\" using assms by auto\n  have \"finite F \\<and> card F \\<le> 1 + C * R^(DIM('a))\"\n  proof (cases \"R < D/2\")\n    case True\n    have \"x = y\" if \"x \\<in> F\" \"y \\<in> F\" for x y\n    proof (rule ccontr)\n      assume \"\\<not>(x = y)\"\n      then have \"D \\<le> dist x y\" using H \\<open>x \\<in> F\\<close> \\<open>y \\<in> F\\<close> by auto\n      also have \"... \\<le> dist x 0 + dist 0 y\" by (rule dist_triangle)\n      also have \"... \\<le> R + R\"\n        using H(1) \\<open>x \\<in> F\\<close> \\<open>y \\<in> F\\<close> by (intro add_mono, auto)\n      also have \"... < D\" using \\<open>R < D/2\\<close> by auto\n      finally show False by simp\n    qed\n    then have \"finite F \\<and> card F \\<le> 1\" using finite_at_most_singleton by auto\n    moreover have \"1 + 0 * R^(DIM('a)) \\<le> 1 + C * R^(DIM('a))\"\n      using \\<open>C \\<ge> 0\\<close> \\<open>R \\<ge> 0\\<close> by (auto intro: mono_intros)\n    ultimately show ?thesis by auto\n  next\n    case False\n    have \"card G \\<le> 1 + C * R^(DIM('a))\" if \"G \\<subseteq> F\" \"finite G\" for G\n    proof -\n      have \"norm y \\<le> 2*R\" if \"y \\<in> cball x (D/3)\" \"x \\<in> G\" for x y\n      proof -\n        have \"norm y = dist 0 y\" by auto\n        also have \"... \\<le> dist 0 x + dist x y\" by (rule dist_triangle)\n        also have \"... \\<le> R + D/3\"\n          using \\<open>x \\<in> G\\<close> \\<open>G \\<subseteq> F\\<close> \\<open>y \\<in> cball x (D/3)\\<close> \\<open>F \\<subseteq> cball 0 R\\<close> by (auto intro: add_mono)\n        finally show ?thesis using False \\<open>D > 0\\<close> by auto\n      qed\n      then have I: \"(\\<Union>x\\<in>G. cball x (D/3)) \\<subseteq> cball 0 (2*R)\"\n        by auto\n      have \"disjoint_family_on (\\<lambda>x. cball x (D/3)) G\"\n        unfolding disjoint_family_on_def proof (auto)\n        fix a b x assume *: \"a \\<in> G\" \"b \\<in> G\" \"a \\<noteq> b\" \"dist a x * 3 \\<le> D\" \"dist b x * 3 \\<le> D\"\n        then have \"D \\<le> dist a b\" using H \\<open>G \\<subseteq> F\\<close> by auto\n        also have \"... \\<le> dist a x + dist x b\" by (rule dist_triangle)\n        also have \"... \\<le> D/3 + D/3\"\n          using * by (auto simp add: dist_commute intro: mono_intros)\n        also have \"... < D\" using \\<open>D > 0\\<close> by auto\n        finally show False by simp\n      qed\n\n      have \"2 * R \\<ge> 0\" using \\<open>R \\<ge> 0\\<close> by auto\n      define A where \"A = measure lborel (cball (0::'a) 1)\"\n      have \"A > 0\" unfolding A_def using lebesgue_measure_ball_pos by auto\n      have \"card G * ((D/3)^(DIM('a)) * A) = (\\<Sum>x\\<in>G. ((D/3)^(DIM('a)) * A))\"\n        by auto\n      also have \"... = (\\<Sum>x\\<in>G. measure lborel (cball x (D/3)))\"\n        unfolding lebesgue_measure_ball[OF \\<open>D/3 \\<ge> 0\\<close>] A_def by auto\n      also have \"... = measure lborel (\\<Union>x\\<in>G. cball x (D/3))\"\n        apply (rule measure_finite_Union[symmetric, OF \\<open>finite G\\<close> _ \\<open>disjoint_family_on (\\<lambda>x. cball x (D/3)) G\\<close>])\n        apply auto using emeasure_bounded_finite less_imp_neq by auto\n      also have \"... \\<le> measure lborel (cball (0::'a) (2*R))\"\n        apply (rule measure_mono_fmeasurable) using I \\<open>finite G\\<close> emeasure_bounded_finite\n        unfolding fmeasurable_def by auto\n      also have \"... = (2*R)^(DIM('a)) * A\"\n        unfolding A_def using lebesgue_measure_ball[OF \\<open>2*R \\<ge> 0\\<close>] by auto\n      finally have \"card G * (D/3)^(DIM('a)) \\<le> (2*R)^(DIM('a))\"\n        using \\<open>A > 0\\<close> by (auto simp add: divide_simps)\n      then have \"card G \\<le> C * R^(DIM('a))\"\n        unfolding C_def using \\<open>D > 0\\<close> apply (auto simp add: algebra_simps divide_simps)\n        by (metis numeral_times_numeral power_mult_distrib semiring_norm(12) semiring_norm(14))\n      then show ?thesis by auto\n    qed\n    then show \"finite F \\<and> card F \\<le> 1 + C * R^(DIM('a))\"\n      by (rule finite_finite_subset_caract')\n  qed\n  then show ?thesis unfolding C_def by blast\nqed\n\ntext \\<open>Then, we show that the growth rate of a Euclidean space of dimension $d$ is bounded\nfrom below by $R^d$, using integer points.\\<close>\n\nproposition growth_rate_euclidean_below:\n  fixes D::real\n  assumes \"R \\<ge> 0\"\n  shows \"\\<exists>F. (F \\<subseteq> cball (0::'a::euclidean_space) R\n            \\<and> (\\<forall>x\\<in>F. \\<forall>y\\<in>F. x = y \\<or> dist x y \\<ge> D) \\<and> finite F \\<and> card F \\<ge> (1/((max D 1) * DIM('a)))^(DIM('a)) * R^(DIM('a)))\"\nproof -\n  define E where \"E = max D 1\"\n  have \"E > 0\" unfolding E_def by auto\n  define c where \"c = (1/(E * DIM('a)))^(DIM('a))\"\n  have \"c > 0\" unfolding c_def using \\<open>E > 0\\<close> by auto\n\n  define n where \"n = nat (floor (R/(E * DIM('a)))) + 1\"\n  then have \"n > 0\" using \\<open>R \\<ge> 0\\<close> by auto\n\n  have \"R/(E * DIM('a)) \\<le> n\" unfolding n_def by linarith\n  then have \"c * R^(DIM('a)) \\<le> n^(DIM('a))\"\n    unfolding c_def power_mult_distrib[symmetric] by (auto simp add: \\<open>0 < E\\<close> \\<open>0 \\<le> R\\<close> less_imp_le power_mono)\n  have \"n-1 \\<le> R/(E * DIM('a))\"\n    unfolding n_def using \\<open>R \\<ge> 0\\<close> \\<open>E > 0\\<close> by auto\n  then have \"E * DIM('a) * (n-1) \\<le> R\"\n    using \\<open>R \\<ge> 0\\<close> \\<open>E > 0\\<close> by (simp add: mult.commute pos_le_divide_eq)\n\n  text \\<open>We want to consider the set of linear combinations of basis elements with integer\n  coefficients bounded by $n$ (multiplied by $E$ to guarantee the $D$ separation).\n  The formal way to write these elements is to consider all\n  the functions from the basis to $\\{0,\\dotsc, n-1\\}$, and associate to such a function\n  $f$ the point $\\sum E f(i) \\cdot i$ where the sum is over all basis elements $i$. This is\n  what the next definition does.\\<close>\n  define F::\"'a set\" where \"F = (\\<lambda>f. (\\<Sum>i\\<in>Basis. (E * real (f i)) *\\<^sub>R i))`((Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n})\"\n\n  have \"f = g\" if \"f \\<in> (Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n}\" \"g \\<in> Basis \\<rightarrow>\\<^sub>E {0..<n}\"\n                  \"(\\<Sum>i\\<in>Basis. (E * real (f i)) *\\<^sub>R i) = (\\<Sum>i\\<in>Basis. (E * real (g i)) *\\<^sub>R i)\" for f g\n  proof (rule ext)\n    fix i show \"f i = g i\"\n    proof (cases \"i \\<in> Basis\")\n      case True\n      then have \"E * real(f i) = E * real(g i)\"\n        using inner_sum_left_Basis[OF True, of \"\\<lambda>i. E * real(f i)\"] inner_sum_left_Basis[OF True, of \"\\<lambda>i. E * real(g i)\"] that(3)\n        by auto\n      then show \"f i = g i\" using \\<open>E > 0\\<close> by auto\n    next\n      case False\n      then have \"f i = undefined\" \"g i = undefined\" using that by auto\n      then show \"f i = g i\" by auto\n    qed\n  qed\n  then have \"inj_on (\\<lambda>f. (\\<Sum>i\\<in>Basis. (E * real (f i)) *\\<^sub>R i)) ((Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n})\"\n    by (simp add: inj_onI)\n  then have \"card F = card ((Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n})\" unfolding F_def\n    using card_image by blast\n  also have \"... = n^(DIM('a))\"\n    unfolding card_PiE[OF finite_Basis] by (auto simp add: prod_constant)\n  finally have \"card F = n^(DIM('a))\" by auto\n  then have \"finite F\" using \\<open>n > 0\\<close>\n    using card_infinite by force\n  have \"card F \\<ge> c * R^(DIM('a))\"\n    using \\<open>c * R^(DIM('a)) \\<le> n^(DIM('a))\\<close> \\<open>card F = n^(DIM('a))\\<close> by auto\n\n  have separation: \"dist x y \\<ge> D\" if \"x \\<in> F\" \"y \\<in> F\" \"x \\<noteq> y\" for x y\n  proof -\n    obtain f where x: \"f \\<in> (Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n}\" \"x = (\\<Sum>i\\<in>Basis. (E * real (f i)) *\\<^sub>R i)\"\n      using \\<open>x \\<in> F\\<close> unfolding F_def by auto\n    obtain g where y: \"g \\<in> (Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n}\" \"y = (\\<Sum>i\\<in>Basis. (E * real (g i)) *\\<^sub>R i)\"\n      using \\<open>y \\<in> F\\<close> unfolding F_def by auto\n    obtain i where \"f i \\<noteq> g i\" using x y \\<open>x \\<noteq>y\\<close> by force\n    moreover have \"f j = g j\" if \"j \\<notin> Basis\" for j\n      using x(1) y(1) that by fastforce\n    ultimately have \"i \\<in> Basis\" by auto\n    have \"D \\<le> E\" unfolding E_def by auto\n    also have \"... \\<le> abs(E * (real (f i) - real (g i)))\" using \\<open>E > 0\\<close>\n      using \\<open>f i \\<noteq> g i\\<close> by (auto simp add: divide_simps abs_mult)\n    also have \"... = abs(inner x i - inner y i)\"\n      unfolding x(2) y(2) inner_sum_left_Basis[OF \\<open>i \\<in> Basis\\<close>] by (auto simp add: algebra_simps)\n    also have \"... = abs(inner (x-y) i)\"\n      by (simp add: inner_diff_left)\n    also have \"... \\<le> norm (x-y)\" using Basis_le_norm[OF \\<open>i \\<in> Basis\\<close>] by blast\n    finally show \"dist x y \\<ge> D\" by (simp add: dist_norm)\n  qed\n\n  have \"norm x \\<le> R\" if \"x \\<in> F\" for x\n  proof -\n    obtain f where x: \"f \\<in> (Basis::('a set)) \\<rightarrow>\\<^sub>E {0..<n}\" \"x = (\\<Sum>i\\<in>Basis. (E * real (f i)) *\\<^sub>R i)\"\n      using \\<open>x \\<in> F\\<close> unfolding F_def by auto\n    then have \"norm x = norm (\\<Sum>i\\<in>Basis. (E * real (f i)) *\\<^sub>R i)\" by simp\n    also have \"... \\<le> (\\<Sum>i\\<in>Basis. norm((E * real (f i)) *\\<^sub>R i))\"\n      by (rule norm_sum)\n    also have \"... = (\\<Sum>i\\<in>Basis. abs(E * real (f i)))\" by auto\n    also have \"... = (\\<Sum>i\\<in>Basis. E * real (f i))\" using \\<open>E > 0\\<close> by auto\n    also have \"... \\<le> (\\<Sum>i\\<in>(Basis::'a set). E * (n-1))\"\n      apply (rule sum_mono) using PiE_mem[OF x(1)] \\<open>E > 0\\<close> apply (auto simp add: divide_simps)\n      using \\<open>n > 0\\<close> by fastforce\n    also have \"... = DIM('a) * E * (n-1)\"\n      by auto\n    finally show \"norm x \\<le> R\" using \\<open>E * DIM('a) * (n-1) \\<le> R\\<close> by (auto simp add: algebra_simps)\n  qed\n  then have \"F \\<subseteq> cball 0 R\" by auto\n  then show ?thesis using \\<open>card F \\<ge> c * R^(DIM('a))\\<close> \\<open>finite F\\<close> separation c_def E_def by blast\nqed\n\ntext \\<open>As the growth is invariant under quasi-isometries, we deduce that it is impossible\nto map quasi-isometrically a Euclidean space in a space of strictly smaller dimension.\\<close>\n\nproposition quasi_isometry_on_euclidean:\n  fixes f::\"'a::euclidean_space\\<Rightarrow>'b::euclidean_space\"\n  assumes \"lambda C-quasi_isometry_on UNIV f\"\n  shows \"DIM('a) \\<le> DIM('b)\"\nproof -\n  have C: \"lambda \\<ge> 1\" \"C \\<ge> 0\" using quasi_isometry_onD[OF assms] by auto\n  define D where \"D = lambda * (C+1)\"\n  define Ca where \"Ca = (1/((max D 1) * DIM('a)))^(DIM('a))\"\n  have \"Ca > 0\" unfolding Ca_def by auto\n  have A: \"\\<And>R::real. R \\<ge> 0 \\<Longrightarrow> (\\<exists>F. (F \\<subseteq> cball (0::'a::euclidean_space) R\n        \\<and> (\\<forall>x\\<in>F. \\<forall>y\\<in>F. x = y \\<or> dist x y \\<ge> D) \\<and> finite F \\<and> card F \\<ge> Ca * R^(DIM('a))))\"\n    using growth_rate_euclidean_below[of _ D] unfolding Ca_def by blast\n  define Cb::real where \"Cb = ((6/1)^(DIM('b)))\"\n  have B: \"\\<And>F (R::real). (F \\<subseteq> cball (0::'b::euclidean_space) R \\<Longrightarrow> R \\<ge> 0 \\<Longrightarrow> (\\<forall>x\\<in>F. \\<forall>y\\<in>F. x = y \\<or> dist x y \\<ge> 1) \\<Longrightarrow> (finite F \\<and> card F \\<le> 1 + Cb * R^(DIM('b))))\"\n    using growth_rate_euclidean_above[of 1] unfolding Cb_def by fastforce\n\n  have M: \"Ca * R^(DIM('a)) \\<le> 1 + Cb * (lambda * R + C + norm(f 0))^(DIM('b))\" if \"R \\<ge> 0\" for R::real\n  proof -\n    obtain F::\"'a set\" where F: \"F \\<subseteq> cball 0 R\" \"\\<forall>x\\<in>F. \\<forall>y\\<in>F. x = y \\<or> dist x y \\<ge> D\"\n                                \"finite F\" \"card F \\<ge> Ca * R^(DIM('a))\"\n      using A[OF \\<open>R \\<ge> 0\\<close>] by auto\n    define G where \"G = f`F\"\n    have *: \"dist (f x) (f y) \\<ge> 1\" if \"x \\<noteq> y\" \"x \\<in> F\" \"y \\<in> F\" for x y\n    proof -\n      have \"dist x y \\<ge> D\" using that F(2) by auto\n      have \"1 = (1/lambda) * D - C\" using \\<open>lambda \\<ge> 1\\<close> unfolding D_def by auto\n      also have \"... \\<le> (1/lambda) * dist x y - C\"\n        using \\<open>dist x y \\<ge> D\\<close> \\<open>lambda \\<ge> 1\\<close> by (auto simp add: divide_simps)\n      also have \"... \\<le> dist (f x) (f y)\"\n        using quasi_isometry_onD[OF assms] by auto\n      finally show ?thesis by simp\n    qed\n    then have \"inj_on f F\" unfolding inj_on_def by force\n    then have \"card G = card F\" unfolding G_def by (simp add: card_image)\n    then have \"card G \\<ge> Ca * R^(DIM('a))\" using F by auto\n\n    moreover have \"finite G \\<and> card G \\<le> 1 + Cb * (lambda * R + C + norm(f 0))^(DIM('b))\"\n    proof (rule B)\n      show \"0 \\<le> lambda * R + C + norm (f 0)\" using \\<open>R \\<ge> 0\\<close> \\<open>C \\<ge> 0\\<close> \\<open>lambda \\<ge> 1\\<close> by auto\n      show \"\\<forall>x\\<in>G. \\<forall>y\\<in>G. x = y \\<or> 1 \\<le> dist x y\" using * unfolding G_def by (auto, metis)\n      show \"G \\<subseteq> cball 0 (lambda * R + C + norm (f 0))\"\n      unfolding G_def proof (auto)\n        fix x assume \"x \\<in> F\"\n        have \"norm (f x) \\<le> norm (f 0) + dist (f x) (f 0)\"\n          by (metis dist_0_norm dist_triangle2)\n        also have \"... \\<le> norm (f 0) + (lambda * dist x 0 + C)\"\n          by (intro mono_intros quasi_isometry_onD(1)[OF assms]) auto\n        also have \"... \\<le> norm (f 0) + lambda * R + C\"\n          using \\<open>x \\<in> F\\<close> \\<open>F \\<subseteq> cball 0 R\\<close> \\<open>lambda \\<ge> 1\\<close> by auto\n        finally show \"norm (f x) \\<le> lambda * R + C + norm (f 0)\" by auto\n      qed\n    qed\n    ultimately show \"Ca * R^(DIM('a)) \\<le> 1 + Cb * (lambda * R + C + norm(f 0))^(DIM('b))\"\n      by auto\n  qed\n  define CB where \"CB = max Cb 0\"\n  have \"CB \\<ge> 0\" \"CB \\<ge> Cb\" unfolding CB_def by auto\n  define D::real where \"D = (1 + CB * (lambda + C + norm(f 0))^(DIM('b)))/Ca\"\n  have Rineq: \"R^(DIM('a)) \\<le> D * R^(DIM('b))\" if \"R \\<ge> 1\" for R::real\n  proof -\n    have \"Ca * R^(DIM('a)) \\<le> 1 + Cb * (lambda * R + C + norm(f 0))^(DIM('b))\"\n      using M \\<open>R \\<ge> 1\\<close> by auto\n    also have \"... \\<le> 1 + CB * (lambda * R + C + norm(f 0))^(DIM('b))\"\n      using \\<open>CB \\<ge> Cb\\<close> \\<open>lambda \\<ge> 1\\<close> \\<open>R \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> by (auto intro!: mult_right_mono)\n    also have \"... \\<le> R^(DIM('b)) + CB * (lambda * R + C * R + norm(f 0) * R)^(DIM('b))\"\n      using \\<open>lambda \\<ge> 1\\<close> \\<open>R \\<ge> 1\\<close> \\<open>C \\<ge> 0\\<close> \\<open>CB \\<ge> 0\\<close> by (auto intro!: mono_intros)\n    also have \"... = (1 + CB * (lambda + C + norm(f 0))^(DIM('b))) * R^(DIM('b))\"\n      by (auto simp add: algebra_simps power_mult_distrib[symmetric])\n    finally show ?thesis\n      using \\<open>Ca > 0\\<close> unfolding D_def by (auto simp add: divide_simps algebra_simps)\n  qed\n  show \"DIM('a) \\<le> DIM('b)\"\n  proof (rule ccontr)\n    assume \"\\<not>(DIM('a) \\<le> DIM('b))\"\n    then obtain n where \"DIM('a) = DIM('b) + n\" \"n > 0\"\n      by (metis less_imp_add_positive not_le)\n    have \"D \\<ge> 1\" using Rineq[of 1] by auto\n    define R where \"R = 2 * D\"\n    then have \"R \\<ge> 1\" using \\<open>D \\<ge> 1\\<close> by auto\n    have \"R^n * R^(DIM('b)) = R^(DIM('a))\"\n      unfolding \\<open>DIM('a) = DIM('b) + n\\<close> by (auto simp add: power_add)\n    also have \"... \\<le> D * R^(DIM('b))\" using Rineq[OF \\<open>R \\<ge> 1\\<close>] by auto\n    finally have \"R^n \\<le> D\" using \\<open>R \\<ge> 1\\<close> by auto\n    moreover have \"2 * D \\<le> R^n\" unfolding R_def using \\<open>D \\<ge> 1\\<close> \\<open>n > 0\\<close>\n      by (metis One_nat_def Suc_leI \\<open>1 \\<le> R\\<close> \\<open>R \\<equiv> 2 * D\\<close> less_eq_real_def power_increasing_iff power_one power_one_right)\n    ultimately show False using \\<open>D \\<ge> 1\\<close> by auto\n  qed\nqed\n\ntext \\<open>As a particular case, we deduce that two quasi-isometric Euclidean spaces have the\nsame dimension.\\<close>\n\ntheorem quasi_isometric_euclidean:\n  assumes \"quasi_isometric (UNIV::'a::euclidean_space set) (UNIV::'b::euclidean_space set)\"\n  shows \"DIM('a) = DIM('b)\"\nproof -\n  obtain lambda C and f::\"'a \\<Rightarrow>'b\" where \"lambda C-quasi_isometry_on UNIV f\"\n    using assms unfolding quasi_isometric_def quasi_isometry_between_def by auto\n  then have *: \"DIM('a) \\<le> DIM('b)\" using quasi_isometry_on_euclidean by auto\n\n  have \"quasi_isometric (UNIV::'b::euclidean_space set) (UNIV::'a::euclidean_space set)\"\n    using quasi_isometric_equiv_rel(3)[OF assms] by auto\n  then obtain lambda C and f::\"'b \\<Rightarrow>'a\" where \"lambda C-quasi_isometry_on UNIV f\"\n    unfolding quasi_isometric_def quasi_isometry_between_def by auto\n  then have \"DIM('b) \\<le> DIM('a)\" using quasi_isometry_on_euclidean by auto\n  then show ?thesis using * by auto\nqed\n\ntext \\<open>A different (and important) way to prove the above statement would be to use asymptotic\ncones. Here, it can be done in an elementary way: start with a quasi-isometric map $f$, and\nconsider a limit (defined with a ultrafilter) of $x\\mapsto f(n x)/n$. This is a map which\ncontracts and expands the distances by at most $\\lambda$. In particular, it is a homeomorphism\non its image. No such map exists if the dimension of the target is smaller than the dimension\nof the source (invariance of domain theorem, already available in the library).\n\nThe above argument using growth is more elementary to write, though.\\<close>\n\n\nsubsection \\<open>Quasi-geodesics\\<close>\n\ntext \\<open>A quasi-geodesic is a quasi-isometric embedding of a real segment into a metric space. As the\nembedding need not be continuous, a quasi-geodesic does not have to be compact, nor connected, which\ncan be a problem. However, in a geodesic space, it is always possible to deform a quasi-geodesic\ninto a continuous one (at the price of worsening the quasi-isometry constants). This is the content\nof the proposition \\verb+quasi_geodesic_made_lipschitz+ below, which is a variation around Lemma\nIII.H.1.11 in~\\cite{bridson_haefliger}. The strategy of the proof is simple: assume that the\nquasi-geodesic $c$ is defined on $[a,b]$. Then, on the points $a$, $a+C/\\lambda$, $\\cdots$,\n$a+ N \\cdot C/\\lambda$, $b$, take $d$ equal to $c$, where $N$ is chosen so that the distance\nbetween the last point and $b$ is in $[C/\\lambda, 2C/\\lambda)$. In the intervals, take $d$ to\nbe geodesic.\\<close>\n\nproposition (in geodesic_space) quasi_geodesic_made_lipschitz:\n  fixes c::\"real \\<Rightarrow> 'a\"\n  assumes \"lambda C-quasi_isometry_on {a..b} c\" \"dist (c a) (c b) \\<ge> 2 * C\"\n  shows \"\\<exists>d. continuous_on {a..b} d \\<and> d a = c a \\<and> d b = c b\n              \\<and> (\\<forall>x\\<in>{a..b}. dist (c x) (d x) \\<le> 4 * C)\n              \\<and> lambda (4 * C)-quasi_isometry_on {a..b} d\n              \\<and> (2 * lambda)-lipschitz_on {a..b} d\n              \\<and> hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\"\nproof -\n  consider \"C = 0\" | \"C > 0 \\<and> b \\<le> a\" | \"C > 0 \\<and> a < b \\<and> b \\<le> a + 2 * C/lambda\" | \"C > 0 \\<and> a +2 * C/lambda < b\"\n    using quasi_isometry_onD(4)[OF assms(1)] by fastforce\n  then show ?thesis\n  proof (cases)\n    text \\<open>If the original function is Lipschitz, we can use it directly.\\<close>\n    case 1\n    have \"lambda-lipschitz_on {a..b} c\"\n      apply (rule lipschitz_onI) using 1 quasi_isometry_onD[OF assms(1)] by auto\n    then have a: \"(2 * lambda)-lipschitz_on {a..b} c\"\n      apply (rule lipschitz_on_mono) using quasi_isometry_onD[OF assms(1)] assms by (auto simp add: divide_simps)\n    then have b: \"continuous_on {a..b} c\"\n      using lipschitz_on_continuous_on by blast\n    have \"continuous_on {a..b} c \\<and> c a = c a \\<and> c b = c b\n                \\<and> (\\<forall>x\\<in>{a..b}. dist (c x) (c x) \\<le> 4 * C)\n                \\<and> lambda (4 * C)-quasi_isometry_on {a..b} c\n                \\<and> (2 * lambda)-lipschitz_on {a..b} c\n                \\<and> hausdorff_distance (c`{a..b}) (c`{a..b}) \\<le> 2 * C\"\n      using 1 a b assms(1) by auto\n    then show ?thesis by blast\n  next\n    text \\<open>If the original interval is empty, anything will do.\\<close>\n    case 2\n    then have \"b < a\" using assms(2) less_eq_real_def by auto\n    then have *: \"{a..b} = {}\" by auto\n    have a: \"(2 * lambda)-lipschitz_on {a..b} c\"\n      unfolding * apply (rule lipschitz_intros) using quasi_isometry_onD[OF assms(1)] assms by (auto simp add: divide_simps)\n    then have b: \"continuous_on {a..b} c\"\n      using lipschitz_on_continuous_on by blast\n    have \"continuous_on {a..b} c \\<and> c a = c a \\<and> c b = c b\n                \\<and> (\\<forall>x\\<in>{a..b}. dist (c x) (c x) \\<le> 4 * C)\n                \\<and> lambda (4 * C)-quasi_isometry_on {a..b} c\n                \\<and> (2 * lambda)-lipschitz_on {a..b} c\n                \\<and> hausdorff_distance (c`{a..b}) (c`{a..b}) \\<le> 2 * C\"\n      using a b quasi_isometry_on_empty assms(1) quasi_isometry_onD[OF assms(1)] * assms by auto\n    then show ?thesis by blast\n  next\n    text \\<open>If the original interval is short, we can use a direct geodesic interpolation between\n    its endpoints\\<close>\n    case 3\n    then have C: \"C > 0\" \"lambda \\<ge> 1\" using quasi_isometry_onD[OF assms(1)] by auto\n    have [mono_intros]: \"1/lambda \\<le> lambda\" using C by (simp add: divide_simps mult_ge1_powers(1))\n    have \"a < b\" using 3 by simp\n    have \"2 * C \\<le> dist (c a) (c b)\" using assms by auto\n    also have \"... \\<le> lambda * dist a b + C\"\n      using quasi_isometry_onD[OF assms(1)] \\<open>a < b\\<close> by auto\n    also have \"... = lambda * (b-a) + C\"\n      using \\<open>a < b\\<close> dist_real_def by auto\n    finally have *: \"C \\<le> (b-a) * lambda\" by (auto simp add: algebra_simps)\n    define d where \"d = (\\<lambda>x. geodesic_segment_param {(c a)--(c b)} (c a) ((dist (c a) (c b) /(b-a)) * (x-a)))\"\n    have dend: \"d a = c a\" \"d b = c b\" unfolding d_def using \\<open>a < b\\<close> by auto\n\n    have Lip: \"(2 * lambda)-lipschitz_on {a..b} d\"\n    proof -\n      have \"(1 * (((2 * lambda)) * (1+0)))-lipschitz_on {a..b} (\\<lambda>x. geodesic_segment_param {(c a)--(c b)} (c a) ((dist (c a) (c b) /(b-a)) * (x-a)))\"\n      proof (rule lipschitz_on_compose2[of _ _ \"\\<lambda>x. ((dist (c a) (c b) /(b-a)) * (x-a))\"], intro lipschitz_intros)\n        have \"(\\<lambda>x. dist (c a) (c b) / (b-a) * (x - a)) ` {a..b} \\<subseteq> {0..dist (c a) (c b)}\"\n          apply auto using \\<open>a < b\\<close> by (auto simp add: algebra_simps divide_simps intro: mult_right_mono)\n        moreover have \"1-lipschitz_on {0..dist (c a) (c b)} (geodesic_segment_param {c a--c b} (c a))\"\n          by (rule isometry_on_lipschitz, simp)\n        ultimately show \"1-lipschitz_on ((\\<lambda>x. dist (c a) (c b) / (b-a) * (x - a)) ` {a..b}) (geodesic_segment_param {c a--c b} (c a))\"\n          using lipschitz_on_subset by auto\n\n        have \"dist (c a) (c b) \\<le> lambda * dist a b + C\"\n          apply (rule quasi_isometry_onD(1)[OF assms(1)])\n          using \\<open>a < b\\<close> by auto\n        also have \"... = lambda * (b - a) + C\"\n          unfolding dist_real_def using \\<open>a < b\\<close> by auto\n        also have \"... \\<le> 2 * lambda * (b-a)\"\n          using * by (auto simp add: algebra_simps)\n        finally show \"\\<bar>dist (c a) (c b) / (b - a)\\<bar> \\<le> 2 * lambda\"\n          using \\<open>a < b\\<close> by (auto simp add: divide_simps)\n      qed\n      then show ?thesis unfolding d_def by auto\n    qed\n    have dist_c_d: \"dist (c x) (d x) \\<le> 4 * C\" if H: \"x \\<in> {a..b}\" for x\n    proof -\n      have \"(x-a) + (b - x) \\<le> 2 * C/lambda\"\n        using that 3 by auto\n      then consider \"x-a \\<le> C/lambda\" | \"b - x \\<le> C/lambda\" by linarith\n      then have \"\\<exists>v\\<in>{a,b}. dist x v \\<le> C/lambda\"\n      proof (cases)\n        case 1\n        show ?thesis\n          apply (rule bexI[of _ a]) using 1 H by (auto simp add: dist_real_def)\n      next\n        case 2\n        show ?thesis\n          apply (rule bexI[of _ b]) using 2 H by (auto simp add: dist_real_def)\n      qed\n      then obtain v where v: \"v \\<in> {a,b}\" \"dist x v \\<le> C/lambda\" by auto\n      have \"dist (c x) (d x) \\<le> dist (c x) (c v) + dist (c v) (d v) + dist (d v) (d x)\"\n        by (intro mono_intros)\n      also have \"... \\<le> (lambda * dist x v + C) + 0 + ((2 * lambda) * dist v x)\"\n        apply (intro mono_intros quasi_isometry_onD(1)[OF assms(1)] that lipschitz_onD[OF Lip])\n        using v \\<open>a < b\\<close> dend by auto\n      also have \"... \\<le> (lambda * (C/lambda) + C) + 0 + ((2 * lambda) * (C/lambda))\"\n        apply (intro mono_intros) using C v by (auto simp add: metric_space_class.dist_commute)\n      finally show ?thesis\n        using C by (auto simp add: algebra_simps divide_simps)\n    qed\n    text \\<open>A similar argument shows that the Hausdorff distance between the images is bounded by $2C$.\\<close>\n    have \"hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\"\n    proof (rule hausdorff_distanceI2)\n      show \"0 \\<le> 2 * C\" using C by auto\n      fix z assume \"z \\<in> c`{a..b}\"\n      then obtain x where x: \"x \\<in> {a..b}\" \"z = c x\" by auto\n      have \"(x-a) + (b - x) \\<le> 2 * C/lambda\"\n        using x 3 by auto\n      then consider \"x-a \\<le> C/lambda\" | \"b - x \\<le> C/lambda\" by linarith\n      then have \"\\<exists>v\\<in>{a,b}. dist x v \\<le> C/lambda\"\n      proof (cases)\n        case 1\n        show ?thesis\n          apply (rule bexI[of _ a]) using 1 x by (auto simp add: dist_real_def)\n      next\n        case 2\n        show ?thesis\n          apply (rule bexI[of _ b]) using 2 x by (auto simp add: dist_real_def)\n      qed\n      then obtain v where v: \"v \\<in> {a,b}\" \"dist x v \\<le> C/lambda\" by auto\n      have \"dist z (d v) = dist (c x) (c v)\" unfolding x(2) using v dend by auto\n      also have \"... \\<le> lambda * dist x v + C\"\n        apply (rule quasi_isometry_onD(1)[OF assms(1)]) using v(1) x(1) by auto\n      also have \"... \\<le> lambda * (C/lambda) + C\"\n        apply (intro mono_intros) using C v(2) by auto\n      also have \"... = 2 * C\"\n        using C by (simp add: divide_simps)\n      finally have *: \"dist z (d v) \\<le> 2 * C\" by simp\n      show \"\\<exists>y\\<in>d ` {a..b}. dist z y \\<le> 2 * C\"\n        apply (rule bexI[of _ \"d v\"]) using * v(1) \\<open>a < b\\<close> by auto\n    next\n      fix z assume \"z \\<in> d`{a..b}\"\n      then obtain x where x: \"x \\<in> {a..b}\" \"z = d x\" by auto\n      have \"(x-a) + (b - x) \\<le> 2 * C/lambda\"\n        using x 3 by auto\n      then consider \"x-a \\<le> C/lambda\" | \"b - x \\<le> C/lambda\" by linarith\n      then have \"\\<exists>v\\<in>{a,b}. dist x v \\<le> C/lambda\"\n      proof (cases)\n        case 1\n        show ?thesis\n          apply (rule bexI[of _ a]) using 1 x by (auto simp add: dist_real_def)\n      next\n        case 2\n        show ?thesis\n          apply (rule bexI[of _ b]) using 2 x by (auto simp add: dist_real_def)\n      qed\n      then obtain v where v: \"v \\<in> {a,b}\" \"dist x v \\<le> C/lambda\" by auto\n      have \"dist z (c v) = dist (d x) (d v)\" unfolding x(2) using v dend by auto\n      also have \"... \\<le> 2 * lambda * dist x v\"\n        apply (rule lipschitz_onD(1)[OF Lip]) using v(1) x(1) by auto\n      also have \"... \\<le> 2 * lambda * (C/lambda)\"\n        apply (intro mono_intros) using C v(2) by auto\n      also have \"... = 2 * C\"\n        using C by (simp add: divide_simps)\n      finally have *: \"dist z (c v) \\<le> 2 * C\" by simp\n      show \"\\<exists>y\\<in>c`{a..b}. dist z y \\<le> 2 * C\"\n        apply (rule bexI[of _ \"c v\"]) using * v(1) \\<open>a < b\\<close> by auto\n    qed\n    have \"lambda (4 * C)-quasi_isometry_on {a..b} d\"\n    proof\n      show \"1 \\<le> lambda\" using C by auto\n      show \"0 \\<le> 4 * C\" using C by auto\n      show \"dist (d x) (d y) \\<le> lambda * dist x y + 4 * C\" if \"x \\<in> {a..b}\" \"y \\<in> {a..b}\" for x y\n      proof -\n        have \"dist (d x) (d y) \\<le> 2 * lambda * dist x y\"\n          apply (rule lipschitz_onD[OF Lip]) using that by auto\n        also have \"... = lambda * dist x y + lambda * dist x y\"\n          by auto\n        also have \"... \\<le> lambda * dist x y + lambda * (2 * C/lambda)\"\n          apply (intro mono_intros) using 3 that C unfolding dist_real_def by auto\n        also have \"... = lambda * dist x y + 2 * C\"\n          using C by (simp add: algebra_simps divide_simps)\n        finally show ?thesis using C by auto\n      qed\n      show \"1 / lambda * dist x y - 4 * C \\<le> dist (d x) (d y)\" if \"x \\<in> {a..b}\" \"y \\<in> {a..b}\" for x y\n      proof -\n        have \"1/lambda * dist x y - 4 * C \\<le> lambda * dist x y - 2 * C\"\n          apply (intro mono_intros) using C by auto\n        also have \"... \\<le> lambda * (2 * C/lambda) - 2 * C\"\n          apply (intro mono_intros) using that 3 C unfolding dist_real_def by auto\n        also have \"... = 0\"\n          using C by (auto simp add: algebra_simps divide_simps)\n        also have \"... \\<le> dist (d x) (d y)\" by auto\n        finally show ?thesis by simp\n      qed\n    qed\n\n    then have \"continuous_on {a..b} d \\<and> d a = c a \\<and> d b = c b\n          \\<and> lambda (4 * C)-quasi_isometry_on {a..b} d\n          \\<and> (\\<forall>x\\<in>{a..b}. dist (c x) (d x) \\<le> 4 *C)\n          \\<and> (2*lambda)-lipschitz_on {a..b} d\n          \\<and> hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\"\n      using dist_c_d \\<open>d a = c a\\<close> \\<open>d b = c b\\<close> \\<open>(2*lambda)-lipschitz_on {a..b} d\\<close>\n            \\<open>hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\\<close> lipschitz_on_continuous_on by auto\n    then show ?thesis by auto\n  next\n    text \\<open>Now, for the only nontrivial case, we use geodesic interpolation between the points\n    $a$, $a + C/\\lambda$, $\\cdots$, $a+N\\cdot C/\\lambda$, $b'$, $b$ where $N$ is chosen so that\n    the distance between $a+N C/\\lambda$ and $b$ belongs to $[2C/\\lambda, 3C/\\lambda)$, and\n    $b'$ is the middle of this interval. This gives a decomposition into intervals of length\n    at most $3/2\\cdot C/\\lambda$.\\<close>\n    case 4\n    then have C: \"C > 0\" \"lambda \\<ge> 1\" using quasi_isometry_onD[OF assms(1)] by auto\n    have \"a < b\" using 4 C by (smt divide_pos_pos)\n\n    have [mono_intros]: \"1/lambda \\<le> lambda\" using C by (simp add: divide_simps mult_ge1_powers(1))\n    define N where \"N = floor((b-a)/(C/lambda)) - 2\"\n    have N: \"N \\<le> (b-a)/(C/lambda)-2\" \"(b-a)/(C/lambda) \\<le> N + (3::real)\"\n      unfolding N_def by linarith+\n\n    have \"2 < (b-a)/(C/lambda)\"\n      using C 4 by (auto simp add: divide_simps algebra_simps)\n    then have N0 : \"0 \\<le> N\" unfolding N_def by auto\n    define p where \"p = (\\<lambda>t::int. a + (C/lambda) * t)\"\n    have pmono: \"p i \\<le> p j\" if \"i \\<le> j\" for i j\n      unfolding p_def using that C by (auto simp add: algebra_simps divide_simps)\n    have pmono': \"p i < p j\" if \"i < j\" for i j\n      unfolding p_def using that C by (auto simp add: algebra_simps divide_simps)\n    have \"p (N+1) \\<le> b\"\n      unfolding p_def using C N by (auto simp add: algebra_simps divide_simps)\n    then have pb: \"p i \\<le> b\" if \"i \\<in> {0..N}\" for i\n      using that pmono by (meson atLeastAtMost_iff linear not_le order_trans zle_add1_eq_le)\n    have bpN: \"b - p N \\<in> {2 * C/lambda .. 3 * C/lambda}\"\n      unfolding p_def using C N apply (auto simp add: divide_simps)\n      by (auto simp add: algebra_simps)\n    have \"p N < b\" using pmono'[of N \"N+1\"] \\<open>p (N+1) \\<le> b\\<close> by auto\n    define b' where \"b' = (b + p N)/2\"\n    have b': \"p N < b'\" \"b' < b\" using \\<open>p N < b\\<close> unfolding b'_def by auto\n    have pb': \"p i \\<le> b'\" if \"i \\<in> {0..N}\" for i\n      using pmono[of i N] b' that by auto\n\n    text \\<open>Introduce the set $A$ along which one will discretize.\\<close>\n    define A where \"A = p`{0..N} \\<union> {b', b}\"\n    have \"finite A\" unfolding A_def by auto\n    have \"b \\<in> A\" unfolding A_def by auto\n    have \"p 0 \\<in> A\" unfolding A_def using \\<open>0 \\<le> N\\<close> by auto\n    moreover have pa: \"p 0 = a\" unfolding p_def by auto\n    ultimately have \"a \\<in> A\" by auto\n    have \"A \\<subseteq> {a..b}\"\n      unfolding A_def using \\<open>a < b\\<close> b' pa pb pmono N0 by fastforce\n    then have \"b' \\<in> {a..<b}\" unfolding A_def using \\<open>b' < b\\<close> by auto\n\n    have A : \"finite A\" \"A \\<subseteq> {a..b}\" \"a \\<in> A\" \"b \\<in> A\" \"a < b\" by fact+\n\n    have nx: \"next_in A x = x + C/lambda\" if \"x \\<in> A\" \"x \\<noteq> b\" \"x \\<noteq> b'\" \"x \\<noteq> p N\" for x\n    proof (rule next_inI[OF A])\n      show \"x \\<in> {a..<b}\" using \\<open>x \\<in> A\\<close> \\<open>A \\<subseteq> {a..b}\\<close> \\<open>x \\<noteq> b\\<close> by auto\n      obtain i where i: \"x = p i\" \"i \\<in> {0..N}\"\n        using \\<open>x \\<in> A\\<close> \\<open>x \\<noteq> b\\<close> \\<open>x \\<noteq> b'\\<close> unfolding A_def by auto\n      have *: \"p (i+1) = x + C/lambda\" unfolding i(1) p_def by (auto simp add: algebra_simps)\n      have \"i \\<noteq> N\" using that i by auto\n      then have \"i + 1 \\<in> {0..N}\" using \\<open>i \\<in> {0..N}\\<close> by auto\n      then have \"p (i+1) \\<in> A\" unfolding A_def by fastforce\n      then show \"x + C/lambda \\<in> A\" unfolding * by auto\n      show \"x < x + C / lambda\" using C by auto\n      show \"{x<..<x + C / lambda} \\<inter> A = {}\"\n      proof (auto)\n        fix y assume y: \"y \\<in> A\" \"x < y\" \"y < x + C/lambda\"\n        consider \"y = b\" | \"y = b'\" | \"\\<exists>j\\<le>i. y = p j\" | \"\\<exists>j>i. y = p j\"\n          using \\<open>y \\<in> A\\<close> not_less unfolding A_def by auto\n        then show False\n        proof (cases)\n          case 1\n          have \"x + C/lambda \\<le> b\" unfolding *[symmetric] using \\<open>i + 1 \\<in> {0..N}\\<close> pb by auto\n          then show False using y(3) unfolding 1 i(1) by auto\n        next\n          case 2\n          have \"x + C/lambda \\<le> b'\" unfolding *[symmetric] using \\<open>i + 1 \\<in> {0..N}\\<close> pb' by auto\n          then show False using y(3) unfolding 2 i(1) by auto\n        next\n          case 3\n          then obtain j where j: \"j \\<le> i\" \"y = p j\" by auto\n          have \"y \\<le> x\" unfolding j(2) i(1) using pmono[OF \\<open>j \\<le> i\\<close>] by simp\n          then show False using \\<open>x < y\\<close> by auto\n        next\n          case 4\n          then obtain j where j: \"j > i\" \"y = p j\" by auto\n          then have \"i+1 \\<le> j\" by auto\n          have \"x + C/lambda \\<le> y\" unfolding j(2) *[symmetric] using pmono[OF \\<open>i+1 \\<le> j\\<close>] by auto\n          then show False using \\<open>y < x + C/lambda\\<close> by auto\n        qed\n      qed\n    qed\n    have npN: \"next_in A (p N) = b'\"\n    proof (rule next_inI[OF A])\n      show \"p N \\<in> {a..<b}\" using pa pmono \\<open>0 \\<le> N\\<close> \\<open>p N < b\\<close> by auto\n      show \"p N < b'\" by fact\n      show \"b' \\<in> A\" unfolding A_def by auto\n      show \"{p N<..<b'} \\<inter> A = {}\"\n        unfolding A_def using pmono b' by force\n    qed\n    have nb': \"next_in A (b') = b\"\n    proof (rule next_inI[OF A])\n      show \"b' \\<in> {a..<b}\" using A_def A \\<open>b' < b\\<close> by auto\n      show \"b' < b\" by fact\n      show \"b \\<in> A\" by fact\n      show \"{b'<..<b} \\<inter> A = {}\"\n        unfolding A_def using pmono b' by force\n    qed\n    have gap: \"next_in A x - x \\<in> {C/lambda.. 3/2 * C/lambda}\" if \"x \\<in> A - {b}\" for x\n    proof (cases \"x = p N \\<or> x = b'\")\n      case True\n      then show ?thesis using npN nb' bpN b'_def by force\n    next\n      case False\n      have *: \"next_in A x = x + C/lambda\"\n        apply (rule nx) using that False by auto\n      show ?thesis unfolding * using C by (auto simp add: algebra_simps divide_simps)\n    qed\n\n    text \\<open>We can now define the function $d$, by geodesic interpolation between points in $A$.\\<close>\n    define d where \"d x = (if x \\<in> A then c x\n        else geodesic_segment_param {c (prev_in A x) -- c (next_in A x)} (c (prev_in A x))\n            ((x - prev_in A x)/(next_in A x - prev_in A x) * dist (c(prev_in A x)) (c(next_in A x))))\" for x\n    have \"d a = c a\" \"d b = c b\" unfolding d_def using \\<open>a \\<in> A\\<close> \\<open>b \\<in> A\\<close> by auto\n\n    text \\<open>To prove the Lipschitz continuity, we argue that $d$ is Lipschitz on finitely many intervals,\n    that cover the interval $[a,b]$, the intervals between points in $A$.\n    There is a formula for $d$ on them (the nontrivial point is that the above formulas for $d$\n    match at the boundaries).\\<close>\n\n    have *: \"d x = geodesic_segment_param {(c u)--(c v)} (c u) ((dist (c u) (c v) /(v-u)) * (x-u))\"\n      if \"u \\<in> A - {b}\" \"v = next_in A u\" \"x \\<in> {u..v}\" for x u v\n    proof -\n      have \"u \\<in> {a..<b}\" using that \\<open>A \\<subseteq> {a..b}\\<close> by fastforce\n      have H: \"u \\<in> A\" \"v \\<in> A\" \"u < v\" \"A \\<inter> {u<..<v} = {}\" using that next_in_basics[OF A \\<open>u \\<in> {a..<b}\\<close>] by auto\n      consider \"x = u\" | \"x = v\" | \"x \\<in> {u<..<v}\" using \\<open>x \\<in> {u..v}\\<close> by fastforce\n      then show ?thesis\n      proof (cases)\n        case 1\n        then have \"d x = c u\" unfolding d_def using \\<open>u \\<in> A- {b}\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n        then show ?thesis unfolding 1 by auto\n      next\n        case 2\n        then have \"d x = c v\" unfolding d_def using \\<open>v \\<in> A\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n        then show ?thesis unfolding 2 using \\<open>u < v\\<close> by auto\n      next\n        case 3\n        have *: \"prev_in A x = u\"\n          apply (rule prev_inI[OF A]) using 3 H \\<open>A \\<subseteq> {a..b}\\<close> by auto\n        have **: \"next_in A x = v\"\n          apply (rule next_inI[OF A]) using 3 H \\<open>A \\<subseteq> {a..b}\\<close> by auto\n        show ?thesis unfolding d_def * ** using 3 H \\<open>A \\<inter> {u<..<v} = {}\\<close> \\<open>A \\<subseteq> {a..b}\\<close>\n          by (auto simp add: algebra_simps)\n      qed\n    qed\n\n    text \\<open>From the above formula, we deduce that $d$ is Lipschitz on those intervals.\\<close>\n    have lip0: \"(lambda + C / (next_in A u - u))-lipschitz_on {u..next_in A u} d\" if \"u \\<in> A - {b}\" for u\n    proof -\n      define v where \"v = next_in A u\"\n      have \"u \\<in> {a..<b}\" using that \\<open>A \\<subseteq> {a..b}\\<close> by fastforce\n      have \"u \\<in> A\" \"v \\<in> A\" \"u < v\" \"A \\<inter> {u<..<v} = {}\"\n        unfolding v_def using that next_in_basics[OF A \\<open>u \\<in> {a..<b}\\<close>] by auto\n\n      have \"(1 * (((lambda + C / (next_in A u - u))) * (1+0)))-lipschitz_on {u..v} (\\<lambda>x. geodesic_segment_param {(c u)--(c v)} (c u) ((dist (c u) (c v) /(v-u)) * (x-u)))\"\n      proof (rule lipschitz_on_compose2[of _ _ \"\\<lambda>x. ((dist (c u) (c v) /(v-u)) * (x-u))\"], intro lipschitz_intros)\n        have \"(\\<lambda>x. dist (c u) (c v) / (v - u) * (x - u)) ` {u..v} \\<subseteq> {0..dist (c u) (c v)}\"\n          apply auto using \\<open>u < v\\<close> by (auto simp add: algebra_simps divide_simps intro: mult_right_mono)\n        moreover have \"1-lipschitz_on {0..dist (c u) (c v)} (geodesic_segment_param {c u--c v} (c u))\"\n          by (rule isometry_on_lipschitz, simp)\n        ultimately show \"1-lipschitz_on ((\\<lambda>x. dist (c u) (c v) / (v - u) * (x - u)) ` {u..v}) (geodesic_segment_param {c u--c v} (c u))\"\n          using lipschitz_on_subset by auto\n\n        have \"dist (c u) (c v) \\<le> lambda * dist u v + C\"\n          apply (rule quasi_isometry_onD(1)[OF assms(1)])\n          using \\<open>u \\<in> A\\<close> \\<open>v \\<in> A\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n        also have \"... = lambda * (v - u) + C\"\n          unfolding dist_real_def using \\<open>u < v\\<close> by auto\n        finally show \"\\<bar>dist (c u) (c v) / (v - u)\\<bar> \\<le> lambda + C / (next_in A u - u)\"\n          using \\<open>u < v\\<close> unfolding v_def by (auto simp add: divide_simps)\n      qed\n      then show ?thesis\n        using *[OF \\<open>u \\<in> A -{b}\\<close> \\<open>v = next_in A u\\<close>] unfolding v_def\n        by (auto intro: lipschitz_on_transform)\n    qed\n    have lip: \"(2 * lambda)-lipschitz_on {u..next_in A u} d\" if \"u \\<in> A - {b}\" for u\n    proof (rule lipschitz_on_mono[OF lip0[OF that]], auto)\n      define v where \"v = next_in A u\"\n      have \"u \\<in> {a..<b}\" using that \\<open>A \\<subseteq> {a..b}\\<close> by fastforce\n      have \"u \\<in> A\" \"v \\<in> A\" \"u < v\" \"A \\<inter> {u<..<v} = {}\"\n        unfolding v_def using that next_in_basics[OF A \\<open>u \\<in> {a..<b}\\<close>] by auto\n      have Duv: \"v - u \\<in> {C/lambda .. 2 * C/lambda}\"\n        unfolding v_def using gap[OF \\<open>u \\<in> A - {b}\\<close>] by simp\n      then show \" C / (next_in A u - u) \\<le> lambda\"\n        using \\<open>u < v\\<close> C unfolding v_def by (auto simp add: algebra_simps divide_simps)\n    qed\n\n    text \\<open>The Lipschitz continuity of $d$ now follows from its Lipschitz continuity on each\n    subinterval in $I$.\\<close>\n    have Lip: \"(2 * lambda)-lipschitz_on {a..b} d\"\n      apply (rule lipschitz_on_closed_Union[of \"{{u..next_in A u} |u. u \\<in> A - {b}}\" _ \"\\<lambda>x. x\"])\n      using lip \\<open>finite A\\<close> C intervals_decomposition[OF A] using assms by auto\n    then have \"continuous_on {a..b} d\"\n      using lipschitz_on_continuous_on by auto\n\n    text \\<open>$d$ has good upper controls on each basic interval.\\<close>\n    have QI0: \"dist (d x) (d y) \\<le> lambda * dist x y + C\"\n      if H: \"u \\<in> A - {b}\" \"x \\<in> {u..next_in A u}\" \"y \\<in> {u..next_in A u}\" for u x y\n    proof -\n      have \"u < next_in A u\" using H(1) A next_in_basics(2)[OF A] by auto\n      moreover have \"dist x y \\<le> next_in A u - u\" unfolding dist_real_def using H by auto\n      ultimately have *: \"dist x y / (next_in A u - u) \\<le> 1\" by (simp add: divide_simps)\n      have \"dist (d x) (d y) \\<le> (lambda + C / (next_in A u - u)) * dist x y\"\n        by (rule lipschitz_onD[OF lip0[OF H(1)] H(2) H(3)])\n      also have \"... = lambda * dist x y + C * (dist x y / (next_in A u - u))\"\n        by (simp add: algebra_simps)\n      also have \"... \\<le> lambda * dist x y + C * 1\"\n        apply (intro mono_intros) using C * by auto\n      finally show ?thesis by simp\n    qed\n\n    text \\<open>We can now show that $c$ and $d$ are pointwise close. This follows from the fact that they\n    coincide on $A$ and are well controlled in between (for $c$, this is a consequence of the choice\n    of $A$. For $d$, it follows from the fact that it is geodesic in the intervals).\\<close>\n\n    have dist_c_d: \"dist (c x) (d x) \\<le> 4 * C\" if \"x \\<in> {a..b}\" for x\n    proof -\n      obtain u where u: \"u \\<in> A - {b}\" \"x \\<in> {u..next_in A u}\"\n        using \\<open>x \\<in> {a..b}\\<close> intervals_decomposition[OF A] by blast\n      have \"(x-u) + (next_in A u - x) \\<le> 2 * C/lambda\"\n        using gap[OF u(1)] by auto\n      then consider \"x-u \\<le> C/lambda\" | \"next_in A u - x \\<le> C/lambda\" by linarith\n      then have \"\\<exists>v\\<in>A. dist x v \\<le> C/lambda\"\n      proof (cases)\n        case 1\n        show ?thesis\n          apply (rule bexI[of _ u]) using 1 u by (auto simp add: dist_real_def)\n      next\n        case 2\n        show ?thesis\n          apply (rule bexI[of _ \"next_in A u\"]) using 2 u A(2)\n          by (auto simp add: dist_real_def intro!:next_in_basics[OF A])\n      qed\n      then obtain v where v: \"v \\<in> A\" \"dist x v \\<le> C/lambda\" by auto\n      have \"dist (c x) (d x) \\<le> dist (c x) (c v) + dist (c v) (d v) + dist (d v) (d x)\"\n        by (intro mono_intros)\n      also have \"... \\<le> (lambda * dist x v + C) + 0 + ((2 * lambda) * dist v x)\"\n        apply (intro mono_intros quasi_isometry_onD(1)[OF assms(1)] that lipschitz_onD[OF Lip])\n        using A(2) \\<open>v \\<in> A\\<close> apply blast\n        using \\<open>v \\<in> A\\<close> d_def apply auto[1]\n        using A(2) \\<open>v \\<in> A\\<close> by blast\n      also have \"... \\<le> (lambda * (C/lambda) + C) + 0 + ((2 * lambda) * (C/lambda))\"\n        apply (intro mono_intros) using v(2) C by (auto simp add: metric_space_class.dist_commute)\n      finally show ?thesis\n        using C by (auto simp add: algebra_simps divide_simps)\n    qed\n    text \\<open>A similar argument shows that the Hausdorff distance between the images is bounded by $2C$.\\<close>\n    have \"hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\"\n    proof (rule hausdorff_distanceI2)\n      show \"0 \\<le> 2 * C\" using C by auto\n      fix z assume \"z \\<in> c`{a..b}\"\n      then obtain x where x: \"x \\<in> {a..b}\" \"z = c x\" by auto\n      then obtain u where u: \"u \\<in> A - {b}\" \"x \\<in> {u..next_in A u}\"\n        using intervals_decomposition[OF A] by blast\n      have \"(x-u) + (next_in A u - x) \\<le> 2 * C/lambda\"\n        using gap[OF u(1)] by auto\n      then consider \"x-u \\<le> C/lambda\" | \"next_in A u - x \\<le> C/lambda\" by linarith\n      then have \"\\<exists>v\\<in>A. dist x v \\<le> C/lambda\"\n      proof (cases)\n        case 1\n        show ?thesis\n          apply (rule bexI[of _ u]) using 1 u by (auto simp add: dist_real_def)\n      next\n        case 2\n        show ?thesis\n          apply (rule bexI[of _ \"next_in A u\"]) using 2 u A(2)\n          by (auto simp add: dist_real_def intro!:next_in_basics[OF A])\n      qed\n      then obtain v where v: \"v \\<in> A\" \"dist x v \\<le> C/lambda\" by auto\n      have \"dist z (d v) = dist (c x) (c v)\" unfolding x(2) d_def using \\<open>v \\<in> A\\<close> by auto\n      also have \"... \\<le> lambda * dist x v + C\"\n        apply (rule quasi_isometry_onD(1)[OF assms(1)]) using v(1) A(2) x(1) by auto\n      also have \"... \\<le> lambda * (C/lambda) + C\"\n        apply (intro mono_intros) using C v(2) by auto\n      also have \"... = 2 * C\"\n        using C by (simp add: divide_simps)\n      finally have *: \"dist z (d v) \\<le> 2 * C\" by simp\n      show \"\\<exists>y\\<in>d ` {a..b}. dist z y \\<le> 2 * C\"\n        apply (rule bexI[of _ \"d v\"]) using * v(1) A(2) by auto\n    next\n      fix z assume \"z \\<in> d`{a..b}\"\n      then obtain x where x: \"x \\<in> {a..b}\" \"z = d x\" by auto\n      then obtain u where u: \"u \\<in> A - {b}\" \"x \\<in> {u..next_in A u}\"\n        using intervals_decomposition[OF A] by blast\n      have \"(x-u) + (next_in A u - x) \\<le> 2 * C/lambda\"\n        using gap[OF u(1)] by auto\n      then consider \"x-u \\<le> C/lambda\" | \"next_in A u - x \\<le> C/lambda\" by linarith\n      then have \"\\<exists>v\\<in>A. dist x v \\<le> C/lambda\"\n      proof (cases)\n        case 1\n        show ?thesis\n          apply (rule bexI[of _ u]) using 1 u by (auto simp add: dist_real_def)\n      next\n        case 2\n        show ?thesis\n          apply (rule bexI[of _ \"next_in A u\"]) using 2 u A(2)\n          by (auto simp add: dist_real_def intro!:next_in_basics[OF A])\n      qed\n      then obtain v where v: \"v \\<in> A\" \"dist x v \\<le> C/lambda\" by auto\n      have \"dist z (c v) = dist (d x) (d v)\" unfolding x(2) d_def using \\<open>v \\<in> A\\<close> by auto\n      also have \"... \\<le> 2 * lambda * dist x v\"\n        apply (rule lipschitz_onD(1)[OF Lip]) using v(1) A(2) x(1) by auto\n      also have \"... \\<le> 2 * lambda * (C/lambda)\"\n        apply (intro mono_intros) using C v(2) by auto\n      also have \"... = 2 * C\"\n        using C by (simp add: divide_simps)\n      finally have *: \"dist z (c v) \\<le> 2 * C\" by simp\n      show \"\\<exists>y\\<in>c`{a..b}. dist z y \\<le> 2 * C\"\n        apply (rule bexI[of _ \"c v\"]) using * v(1) A(2) by auto\n    qed\n\n    text \\<open>From the above controls, we check that $d$ is a quasi-isometry, with explicit constants.\\<close>\n    have \"lambda (4 * C)-quasi_isometry_on {a..b} d\"\n    proof\n      show \"1 \\<le> lambda\" using C by auto\n      show \"0 \\<le> 4 * C\" using C by auto\n      have I : \"dist (d x) (d y) \\<le> lambda * dist x y + 4 * C\" if H: \"x \\<in> {a..b}\" \"y \\<in> {a..b}\" \"x < y\" for x y\n      proof -\n        obtain u where u: \"u \\<in> A - {b}\" \"x \\<in> {u..next_in A u}\"\n          using intervals_decomposition[OF A] H(1) by force\n        have \"u \\<in> {a..<b}\" using u(1) A by auto\n        have \"next_in A u \\<in> A\" using next_in_basics(1)[OF A \\<open>u \\<in> {a..<b}\\<close>] by auto\n        obtain v where v: \"v \\<in> A - {b}\" \"y \\<in> {v..next_in A v}\"\n          using intervals_decomposition[OF A] H(2) by force\n        have \"v \\<in> {a..<b}\" using v(1) A by auto\n        have \"u < next_in A v\" using H(3) u(2) v(2) by auto\n        then have \"u \\<le> v\"\n          using u(1) next_in_basics(3)[OF A, OF \\<open>v \\<in> {a..<b}\\<close>] by auto\n        show ?thesis\n        proof (cases \"u = v\")\n          case True\n          have \"dist (d x) (d y) \\<le> lambda * dist x y + C\"\n            apply (rule QI0[OF u]) using v(2) True by auto\n          also have \"... \\<le> lambda * dist x y + 4 * C\"\n            using C by auto\n          finally show ?thesis by simp\n        next\n          case False\n          then have \"u < v\" using \\<open>u \\<le> v\\<close> by auto\n          then have \"next_in A u \\<le> v\" using v(1) next_in_basics(3)[OF A, OF \\<open>u \\<in> {a..<b}\\<close>] by auto\n          have d1: \"d (next_in A u) = c (next_in A u)\"\n            using \\<open>next_in A u \\<in> A\\<close> unfolding d_def by auto\n          have d2: \"d v = c v\"\n            using v(1) unfolding d_def by auto\n          have \"dist (d x) (d y) \\<le> dist (d x) (d (next_in A u)) + dist (d (next_in A u)) (d v) + dist (d v) (d y)\"\n            by (intro mono_intros)\n          also have \"... \\<le> (lambda * dist x (next_in A u) + C) + (lambda * dist (next_in A u) v + C)\n                            + (lambda * dist v y + C)\"\n            apply (intro mono_intros)\n              apply (rule QI0[OF u]) using u(2) apply simp\n             apply (simp add: d1 d2) apply (rule quasi_isometry_onD(1)[OF assms(1)])\n            using \\<open>next_in A u \\<in> A\\<close> \\<open>A \\<subseteq> {a..b}\\<close> apply auto[1]\n            using \\<open>v \\<in> A - {b}\\<close> \\<open>A \\<subseteq> {a..b}\\<close> apply auto[1]\n            apply (rule QI0[OF v(1)]) using v(2) by auto\n          also have \"... = lambda * dist x y + 3 * C\"\n            unfolding dist_real_def\n            using \\<open>x \\<in> {u..next_in A u}\\<close> \\<open>y \\<in> {v..next_in A v}\\<close> \\<open>x < y\\<close> \\<open>next_in A u \\<le> v\\<close>\n            by (auto simp add: algebra_simps)\n          finally show ?thesis using C by simp\n        qed\n      qed\n      show \"dist (d x) (d y) \\<le> lambda * dist x y + 4 * C\" if H: \"x \\<in> {a..b}\" \"y \\<in> {a..b}\" for x y\n      proof -\n        consider \"x < y\" | \"x = y\" | \"x > y\" by linarith\n        then show ?thesis\n        proof (cases)\n          case 1\n          then show ?thesis using I[OF H(1) H(2) 1] by simp\n        next\n          case 2\n          show ?thesis unfolding 2 using C by auto\n        next\n          case 3\n          show ?thesis using I [OF H(2) H(1) 3] by (simp add: metric_space_class.dist_commute)\n        qed\n      qed\n      text \\<open>The lower bound is more tricky. We separate the case where $x$ and $y$ are in the same\n      interval, when they are in different nearby intervals, and when they are in different\n      separated intervals. The latter case is more difficult. In this case, one of the intervals\n      has length $C/\\lambda$ and the other one has length at most $3/2\\cdot C/\\lambda$. There,\n      we approximate $dist (d x) (d y)$ by $dist (d u') (d v')$ where $u'$ and $v'$ are suitable\n      endpoints of the intervals containing respectively $x$ and $y$. We use the inner endpoint\n      (between $x$ and $y$) if the distance between $x$ or $y$ and this point is less than $2/5$\n      of the length of the interval, and the outer endpoint otherwise. The reason is that, with\n      the outer endpoints, we get right away an upper bound for the distance between $x$ and $y$,\n      while this is not the case with the inner endpoints where there is an additional error.\n      The equilibrium is reached at proportion $2/5$. \\<close>\n      have J : \"dist (d x) (d y) \\<ge> (1/lambda) * dist x y - 4 * C\" if H: \"x \\<in> {a..b}\" \"y \\<in> {a..b}\" \"x < y\" for x y\n      proof -\n        obtain u where u: \"u \\<in> A - {b}\" \"x \\<in> {u..next_in A u}\"\n          using intervals_decomposition[OF A] H(1) by force\n        have \"u \\<in> {a..<b}\" using u(1) A by auto\n        have \"next_in A u \\<in> A\" using next_in_basics(1)[OF A \\<open>u \\<in> {a..<b}\\<close>] by auto\n        obtain v where v: \"v \\<in> A - {b}\" \"y \\<in> {v..next_in A v}\"\n          using intervals_decomposition[OF A] H(2) by force\n        have \"v \\<in> {a..<b}\" using v(1) A by auto\n        have \"next_in A v \\<in> A\" using next_in_basics(1)[OF A \\<open>v \\<in> {a..<b}\\<close>] by auto\n        have \"u < next_in A v\" using H(3) u(2) v(2) by auto\n        then have \"u \\<le> v\"\n          using u(1) next_in_basics(3)[OF A, OF \\<open>v \\<in> {a..<b}\\<close>] by auto\n        consider \"v = u\" | \"v = next_in A u\" | \"v \\<noteq> u \\<and> v \\<noteq> next_in A u\" by auto\n        then show ?thesis\n        proof (cases)\n          case 1\n          have \"(1/lambda) * dist x y - 4 * C \\<le> lambda * dist x y - 4 * C\"\n            apply (intro mono_intros) by auto\n          also have \"... \\<le> lambda * (3/2 * C/lambda) - 3/2 * C\"\n            apply (intro mono_intros)\n            using u(2) v(2) unfolding 1 using C gap[OF u(1)] dist_real_def \\<open>x < y\\<close> by auto\n          also have \"... = 0\"\n            using C by auto\n          also have \"... \\<le> dist (d x) (d y)\"\n            by auto\n          finally show ?thesis by simp\n        next\n          case 2\n          have \"dist x y \\<le> dist x (next_in A u) + dist v y\"\n            unfolding 2 by (intro mono_intros)\n          also have \"... \\<le> 3/2 * C/lambda + 3/2 * C/lambda\"\n            apply (intro mono_intros)\n            unfolding dist_real_def using u(2) v(2) gap[OF u(1)] gap[OF v(1)] by auto\n          finally have *: \"dist x y \\<le> 3 * C/lambda\" by auto\n          have \"(1/lambda) * dist x y - 4 * C \\<le> lambda * dist x y - 4 * C\"\n            apply (intro mono_intros) by auto\n          also have \"... \\<le> lambda * (3 * C/lambda) - 3 * C\"\n            apply (intro mono_intros)\n            using * C by auto\n          also have \"... = 0\"\n            using C by auto\n          also have \"... \\<le> dist (d x) (d y)\"\n            by auto\n          finally show ?thesis by simp\n        next\n          case 3\n          then have \"u < v\" using \\<open>u \\<le> v\\<close> by auto\n          then have *: \"next_in A u < v\" using v(1) next_in_basics(3)[OF A \\<open>u \\<in> {a..<b}\\<close>] 3 by auto\n          have nu: \"next_in A u = u + C/lambda\"\n          proof (rule nx)\n            show \"u \\<in> A\" using u(1) by auto\n            show \"u \\<noteq> b\" using u(1) by auto\n            show \"u \\<noteq> b'\"\n            proof\n              assume H: \"u = b'\"\n              have \"b < v\" using * unfolding H nb' by simp\n              then show False using \\<open>v \\<in> {a..<b}\\<close> by auto\n            qed\n            show \"u \\<noteq> p N\"\n            proof\n              assume H: \"u = p N\"\n              have \"b' < v\" using * unfolding H npN by simp\n              then have \"next_in A b' \\<le> v\" using next_in_basics(3)[OF A \\<open>b' \\<in> {a..<b}\\<close>] v by force\n              then show False unfolding nb' using \\<open>v \\<in> {a..<b}\\<close> by auto\n            qed\n          qed\n          have nv: \"next_in A v \\<le> v + 3/2 * C/lambda\" using gap[OF v(1)] by auto\n\n          have d: \"d u = c u\" \"d (next_in A u) = c (next_in A u)\" \"d v = c v\" \"d (next_in A v) = c (next_in A v)\"\n            using \\<open>u \\<in> A - {b}\\<close> \\<open>next_in A u \\<in> A\\<close> \\<open>v \\<in> A - {b}\\<close> \\<open>next_in A v \\<in> A\\<close> unfolding d_def by auto\n\n          text \\<open>The interval containing $x$ has length $C/\\lambda$, while the interval containing\n          $y$ has length at most $\\leq 3/2 C/\\lambda$. Therefore, $x$ is at proportion $2/5$ of the inner point\n          if $x > u + (3/5) C/\\lambda$, and $y$ is at proportion $2/5$ of the inner point if\n          $y < v + (2/5) \\cdot 3/2 \\cdot C/\\lambda = v + (3/5)C/\\lambda$.\\<close>\n          consider \"x \\<le> u + (3/5) * C/lambda \\<and> y \\<le> v + (3/5) * C/lambda\"\n                 | \"x \\<ge> u + (3/5) * C/lambda \\<and> y \\<le> v + (3/5) * C/lambda\"\n                 | \"x \\<le> u + (3/5) * C/lambda \\<and> y \\<ge> v + (3/5) * C/lambda\"\n                 | \"x \\<ge> u + (3/5) * C/lambda \\<and> y \\<ge> v + (3/5) * C/lambda\"\n            by linarith\n          then show ?thesis\n          proof (cases)\n            case 1\n            have \"(1/lambda) * dist u v - C \\<le> dist (c u) (c v)\"\n              apply (rule quasi_isometry_onD(2)[OF assms(1)])\n              using \\<open>u \\<in> A - {b}\\<close> \\<open>v \\<in> A - {b}\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n            also have \"... = dist (d u) (d v)\"\n              using d by auto\n            also have \"... \\<le> dist (d u) (d x) + dist (d x) (d y) + dist (d y) (d v)\"\n              by (intro mono_intros)\n            also have \"... \\<le> (2 * lambda * dist u x) + dist (d x) (d y) + (2 * lambda * dist y v)\"\n              apply (intro mono_intros)\n              apply (rule lipschitz_onD[OF lip[OF u(1)]]) using u(2) apply auto[1] using u(2) apply auto[1]\n              apply (rule lipschitz_onD[OF lip[OF v(1)]]) using v(2) by auto\n            also have \"... \\<le> (2 * lambda * (3/5 * C/lambda)) + dist (d x) (d y) + (2 * lambda * (3/5 * C/lambda))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 1 u v C by auto\n            also have \"... = 12/5 * C + dist (d x) (d y)\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            finally have *: \"(1/lambda) * dist u v \\<le> dist (d x) (d y) + 17/5 * C\" by auto\n\n            have \"(1/lambda) * dist x y \\<le> (1/lambda) * (dist u v + dist v y)\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using C u(2) v(2) \\<open>x < y\\<close> by auto\n            also have \"... \\<le> (1/lambda) * (dist u v + 3/5 * C/lambda)\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 1 v(2) C by auto\n            also have \"... = (1/lambda) * dist u v + 3/5 * C * (1/(lambda * lambda))\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            also have \"... \\<le> (1/lambda) * dist u v + 3/5 * C * 1\"\n              apply (intro mono_intros)\n              using C by (auto simp add: divide_simps algebra_simps mult_ge1_powers(1))\n            also have \"... \\<le> (dist (d x) (d y) + 17/5 * C) + 3/5 * C * 1\"\n              using * by auto\n            finally show ?thesis by auto\n          next\n            case 2\n            have \"(1/lambda) * dist (next_in A u) v - C \\<le> dist (c (next_in A u)) (c v)\"\n              apply (rule quasi_isometry_onD(2)[OF assms(1)])\n              using \\<open>next_in A u \\<in> A\\<close> \\<open>v \\<in> A - {b}\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n            also have \"... = dist (d (next_in A u)) (d v)\"\n              using d by auto\n            also have \"... \\<le> dist (d (next_in A u)) (d x) + dist (d x) (d y) + dist (d y) (d v)\"\n              by (intro mono_intros)\n            also have \"... \\<le> (2 * lambda * dist (next_in A u) x) + dist (d x) (d y) + (2 * lambda * dist y v)\"\n              apply (intro mono_intros)\n              apply (rule lipschitz_onD[OF lip[OF u(1)]]) using u(2) apply auto[1] using u(2) apply auto[1]\n              apply (rule lipschitz_onD[OF lip[OF v(1)]]) using v(2) by auto\n            also have \"... \\<le> (2 * lambda * (2/5 * C/lambda)) + dist (d x) (d y) + (2 * lambda * (3/5 * C/lambda))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 2 u v C nu by auto\n            also have \"... = 2 * C + dist (d x) (d y)\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            finally have *: \"(1/lambda) * dist (next_in A u) v \\<le> dist (d x) (d y) + 3 * C\" by auto\n\n            have \"(1/lambda) * dist x y \\<le> (1/lambda) * (dist x (next_in A u) + dist (next_in A u) v + dist v y)\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using C u(2) v(2) \\<open>x < y\\<close> by auto\n            also have \"... \\<le> (1/lambda) * ((2/5 * C/lambda) + dist (next_in A u) v  + (3/5 * C/lambda))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 2 u(2) v(2) C nu by auto\n            also have \"... = (1/lambda) * dist (next_in A u) v + C * (1/(lambda * lambda))\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            also have \"... \\<le> (1/lambda) * dist (next_in A u) v + C * 1\"\n              apply (intro mono_intros)\n              using C by (auto simp add: divide_simps algebra_simps mult_ge1_powers(1))\n            also have \"... \\<le> (dist (d x) (d y) + 3 * C) + C * 1\"\n              using * by auto\n            finally show ?thesis by auto\n          next\n            case 3\n            have \"(1/lambda) * dist u (next_in A v) - C \\<le> dist (c u) (c (next_in A v))\"\n              apply (rule quasi_isometry_onD(2)[OF assms(1)])\n              using \\<open>u \\<in> A - {b}\\<close> \\<open>next_in A v \\<in> A\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n            also have \"... = dist (d u) (d (next_in A v))\"\n              using d by auto\n            also have \"... \\<le> dist (d u) (d x) + dist (d x) (d y) + dist (d y) (d (next_in A v))\"\n              by (intro mono_intros)\n            also have \"... \\<le> (2 * lambda * dist u x) + dist (d x) (d y) + (2 * lambda * dist y (next_in A v))\"\n              apply (intro mono_intros)\n              apply (rule lipschitz_onD[OF lip[OF u(1)]]) using u(2) apply auto[1] using u(2) apply auto[1]\n              apply (rule lipschitz_onD[OF lip[OF v(1)]]) using v(2) by auto\n            also have \"... \\<le> (2 * lambda * (3/5 * C/lambda)) + dist (d x) (d y) + (2 * lambda * (9/10 * C/lambda))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 3 u v C nv by auto\n            also have \"... = 3 * C + dist (d x) (d y)\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            finally have *: \"(1/lambda) * dist u (next_in A v) \\<le> dist (d x) (d y) + 4 * C\" by auto\n\n            have \"(1/lambda) * dist x y \\<le> (1/lambda) * dist u (next_in A v)\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using C u(2) v(2) \\<open>x < y\\<close> by auto\n            also have \"... \\<le> dist (d x) (d y) + 4 * C\"\n              using * by auto\n            finally show ?thesis by auto\n          next\n            case 4\n            have \"(1/lambda) * dist (next_in A u) (next_in A v) - C \\<le> dist (c (next_in A u)) (c (next_in A v))\"\n              apply (rule quasi_isometry_onD(2)[OF assms(1)])\n              using \\<open>next_in A u \\<in> A\\<close> \\<open>next_in A v \\<in> A\\<close> \\<open>A \\<subseteq> {a..b}\\<close> by auto\n            also have \"... = dist (d (next_in A u)) (d (next_in A v))\"\n              using d by auto\n            also have \"... \\<le> dist (d (next_in A u)) (d x) + dist (d x) (d y) + dist (d y) (d (next_in A v))\"\n              by (intro mono_intros)\n            also have \"... \\<le> (2 * lambda * dist (next_in A u) x) + dist (d x) (d y) + (2 * lambda * dist y (next_in A v))\"\n              apply (intro mono_intros)\n              apply (rule lipschitz_onD[OF lip[OF u(1)]]) using u(2) apply auto[1] using u(2) apply auto[1]\n              apply (rule lipschitz_onD[OF lip[OF v(1)]]) using v(2) by auto\n            also have \"... \\<le> (2 * lambda * (2/5 * C/lambda)) + dist (d x) (d y) + (2 * lambda * (9/10 * C/lambda))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 4 u v C nu nv by auto\n            also have \"... = 13/5 * C + dist (d x) (d y)\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            finally have *: \"(1/lambda) * dist (next_in A u) (next_in A v) \\<le> dist (d x) (d y) + 18/5 * C\" by auto\n\n            have \"(1/lambda) * dist x y \\<le> (1/lambda) * (dist x (next_in A u) + dist (next_in A u) (next_in A v))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using C u(2) v(2) \\<open>x < y\\<close> by auto\n            also have \"... \\<le> (1/lambda) * ((2/5 *C/lambda) + dist (next_in A u) (next_in A v))\"\n              apply (intro mono_intros)\n              unfolding dist_real_def using 4 u(2) v(2) C nu by auto\n            also have \"... = (1/lambda) * dist (next_in A u) (next_in A v) + 2/5 * C * (1/(lambda * lambda))\"\n              using C by (auto simp add: algebra_simps divide_simps)\n            also have \"... \\<le> (1/lambda) * dist (next_in A u) (next_in A v) + 2/5 * C * 1\"\n              apply (intro mono_intros)\n              using C by (auto simp add: divide_simps algebra_simps mult_ge1_powers(1))\n            also have \"... \\<le> (dist (d x) (d y) + 18/5 * C) + 2/5 * C * 1\"\n              using * by auto\n            finally show ?thesis by auto\n          qed\n        qed\n      qed\n      show \"dist (d x) (d y) \\<ge> (1/lambda) * dist x y - 4 * C\" if H: \"x \\<in> {a..b}\" \"y \\<in> {a..b}\" for x y\n      proof -\n        consider \"x < y\" | \"x = y\" | \"x > y\" by linarith\n        then show ?thesis\n        proof (cases)\n          case 1\n          then show ?thesis using J[OF H(1) H(2) 1] by simp\n        next\n          case 2\n          show ?thesis unfolding 2 using C by auto\n        next\n          case 3\n          show ?thesis using J[OF H(2) H(1) 3] by (simp add: metric_space_class.dist_commute)\n        qed\n      qed\n    qed\n\n    text \\<open>We have proved that $d$ has all the properties we wanted.\\<close>\n    then have \"continuous_on {a..b} d \\<and> d a = c a \\<and> d b = c b\n          \\<and> lambda (4 * C)-quasi_isometry_on {a..b} d\n          \\<and> (\\<forall>x\\<in>{a..b}. dist (c x) (d x) \\<le> 4 *C)\n          \\<and> (2*lambda)-lipschitz_on {a..b} d\n          \\<and> hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\"\n      using dist_c_d \\<open>continuous_on {a..b} d\\<close> \\<open>d a = c a\\<close> \\<open>d b = c b\\<close> \\<open>(2*lambda)-lipschitz_on {a..b} d\\<close>\n            \\<open>hausdorff_distance (c`{a..b}) (d`{a..b}) \\<le> 2 * C\\<close> by auto\n    then show ?thesis by auto\n  qed\nqed\n\nend (*of theory Isometries*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gromov_Hyperbolicity/Isometries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8723473713594992, "lm_q1q2_score": 0.7639904687222592}}
{"text": "theory conditions_positive\n  imports \"../boolean_algebra/boolean_algebra_functional\"\nbegin\n\n(** We define and interrelate some useful axiomatic conditions on unary operations (operators) \nhaving a 'w-parametric type @{type \"'w \\<sigma> \\<Rightarrow> 'w \\<sigma>\"}.\nBoolean algebras extended with such operators give us different sorts of topological Boolean algebras.*)\n\n\n(**Monotonicity (MONO).*)\ndefinition MONO::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"MONO\")\n  where \"MONO \\<phi> \\<equiv> \\<forall>A B. A \\<preceq> B \\<longrightarrow> \\<phi> A \\<preceq> \\<phi> B\"\n\nnamed_theorems cond (*(*to group together axiomatic conditions*)*)\ndeclare MONO_def[cond]\n\n(**MONO is self-dual*)\nlemma MONO_dual: \"MONO \\<phi> = MONO \\<phi>\\<^sup>d\" by (smt (verit) BA_cp MONO_def dual_invol op_dual_def)\n\n\n(**Expansive/extensive (EXPN) and its dual contractive (CNTR).*)\ndefinition EXPN::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"EXPN\")\n  where \"EXPN \\<phi>  \\<equiv> \\<forall>A. A \\<preceq> \\<phi> A\"\ndefinition CNTR::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"CNTR\")\n  where \"CNTR \\<phi> \\<equiv> \\<forall>A. \\<phi> A \\<preceq> A\"\n\ndeclare EXPN_def[cond] CNTR_def[cond]\n\n(**EXPN and CNTR are dual to each other *)\nlemma EXPN_CNTR_dual1: \"EXPN \\<phi> = CNTR \\<phi>\\<^sup>d\" unfolding cond by (metis BA_cp BA_dn op_dual_def setequ_ext)\nlemma EXPN_CNTR_dual2: \"CNTR \\<phi> = EXPN \\<phi>\\<^sup>d\" by (simp add: EXPN_CNTR_dual1 dual_invol)\n\n\n(**Normality (NORM) and its dual (DNRM).*)\ndefinition NORM::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"NORM\")\n  where \"NORM \\<phi>  \\<equiv> (\\<phi> \\<^bold>\\<bottom>) \\<approx> \\<^bold>\\<bottom>\"\ndefinition DNRM::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"DNRM\")\n  where \"DNRM \\<phi> \\<equiv> (\\<phi> \\<^bold>\\<top>) \\<approx> \\<^bold>\\<top>\" \n\ndeclare NORM_def[cond] DNRM_def[cond]\n\n(**NORM and DNRM are dual to each other *)\nlemma NOR_dual1: \"NORM \\<phi> = DNRM \\<phi>\\<^sup>d\" unfolding cond by (simp add: bottom_def compl_def op_dual_def setequ_def top_def)\nlemma NOR_dual2: \"DNRM \\<phi> = NORM \\<phi>\\<^sup>d\" by (simp add: NOR_dual1 dual_invol) \n\n(**EXPN (CNTR) entail DNRM (NORM).*)\nlemma EXPN_impl_DNRM: \"EXPN \\<phi> \\<longrightarrow> DNRM \\<phi>\" unfolding cond by (simp add: setequ_def subset_def top_def)\nlemma CNTR_impl_NORM: \"CNTR \\<phi> \\<longrightarrow> NORM \\<phi>\" by (simp add: EXPN_CNTR_dual2 EXPN_impl_DNRM NOR_dual1 dual_invol)\n\n\n(**Idempotence (IDEM).*)\ndefinition IDEM::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"IDEM\") \n  where \"IDEM \\<phi>  \\<equiv> \\<forall>A. \\<phi>(\\<phi> A) \\<approx> (\\<phi> A)\"\ndefinition IDEM_a::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"IDEM\\<^sup>a\") \n  where \"IDEM\\<^sup>a \\<phi> \\<equiv> \\<forall>A. \\<phi>(\\<phi> A) \\<preceq> (\\<phi> A)\"\ndefinition IDEM_b::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"IDEM\\<^sup>b\") \n  where \"IDEM\\<^sup>b \\<phi> \\<equiv> \\<forall>A.  (\\<phi> A) \\<preceq> \\<phi>(\\<phi> A)\"\n\ndeclare IDEM_def[cond] IDEM_a_def[cond] IDEM_b_def[cond]\n\n(**IDEM-a and IDEM-b are dual to each other *)\nlemma IDEM_dual1: \"IDEM\\<^sup>a \\<phi> = IDEM\\<^sup>b \\<phi>\\<^sup>d\" unfolding cond by (metis (mono_tags, opaque_lifting) BA_cp BA_dn op_dual_def setequ_ext)\nlemma IDEM_dual2: \"IDEM\\<^sup>b \\<phi> = IDEM\\<^sup>a \\<phi>\\<^sup>d\" by (simp add: IDEM_dual1 dual_invol)\n\nlemma IDEM_char: \"IDEM \\<phi> = (IDEM\\<^sup>a \\<phi> \\<and> IDEM\\<^sup>b \\<phi>)\" unfolding cond setequ_char by blast\nlemma IDEM_dual: \"IDEM \\<phi> = IDEM \\<phi>\\<^sup>d\" using IDEM_char IDEM_dual1 IDEM_dual2 by blast\n\n\n(**EXPN (CNTR) entail IDEM-b (IDEM-a).*)\nlemma EXPN_impl_IDEM_b: \"EXPN \\<phi> \\<longrightarrow> IDEM\\<^sup>b \\<phi>\" by (simp add: EXPN_def IDEM_b_def)\nlemma CNTR_impl_IDEM_a: \"CNTR \\<phi> \\<longrightarrow> IDEM\\<^sup>a \\<phi>\" by (simp add: CNTR_def IDEM_a_def)\n\n(**Moreover, IDEM has some other interesting characterizations. For instance, *)\n(**as having the property of collapsing the range and the set of fixed-points of an operator*)\nlemma IDEM_range_fp_char: \"IDEM \\<phi> = (\\<lbrakk>\\<phi> _\\<rbrakk> = fp \\<phi>)\" unfolding cond range_def fixpoints_def by (metis setequ_ext)\n(**and via function composition*)\nlemma IDEM_fun_comp_char: \"IDEM \\<phi> = (\\<phi> = \\<phi> \\<circ> \\<phi>)\" unfolding cond fun_comp_def by (metis setequ_ext)\n\n(**Distribution over joins or additivity (ADDI) and its dual...*)\ndefinition ADDI::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"ADDI\")\n  where \"ADDI \\<phi>   \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<approx> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\" \ndefinition ADDI_a::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"ADDI\\<^sup>a\")\n  where \"ADDI\\<^sup>a \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<or> B) \\<preceq> (\\<phi> A) \\<^bold>\\<or> (\\<phi> B)\"\ndefinition ADDI_b::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"ADDI\\<^sup>b\")\n  where \"ADDI\\<^sup>b \\<phi> \\<equiv> \\<forall>A B.  (\\<phi> A) \\<^bold>\\<or> (\\<phi> B) \\<preceq> \\<phi>(A \\<^bold>\\<or> B)\" \n\n(**... distribution over meets or multiplicativity (MULT).*)\ndefinition MULT::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"MULT\") \n  where \"MULT \\<phi>   \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<approx> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" \ndefinition MULT_a::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"MULT\\<^sup>a\")\n  where \"MULT\\<^sup>a \\<phi> \\<equiv> \\<forall>A B. \\<phi>(A \\<^bold>\\<and> B) \\<preceq> (\\<phi> A) \\<^bold>\\<and> (\\<phi> B)\" \ndefinition MULT_b::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> bool\" (\"MULT\\<^sup>b\")\n  where \"MULT\\<^sup>b \\<phi> \\<equiv> \\<forall>A B. (\\<phi> A) \\<^bold>\\<and> (\\<phi> B) \\<preceq> \\<phi>(A \\<^bold>\\<and> B)\"\n\ndeclare ADDI_def[cond] ADDI_a_def[cond] ADDI_b_def[cond]\n        MULT_def[cond] MULT_a_def[cond] MULT_b_def[cond]\n\nlemma ADDI_char: \"ADDI \\<phi> = (ADDI\\<^sup>a \\<phi> \\<and> ADDI\\<^sup>b \\<phi>)\" unfolding cond using setequ_char by blast\nlemma MULT_char: \"MULT \\<phi> = (MULT\\<^sup>a \\<phi> \\<and> MULT\\<^sup>b \\<phi>)\" unfolding cond using setequ_char by blast\n\n(**MONO, MULT-a and ADDI-b are equivalent.*)\nlemma MONO_MULTa: \"MULT\\<^sup>a \\<phi> = MONO \\<phi>\" unfolding cond by (metis L10 L3 L4 L5 L8 setequ_char setequ_ext)\nlemma MONO_ADDIb: \"ADDI\\<^sup>b \\<phi> = MONO \\<phi>\" unfolding cond by (metis (mono_tags, lifting) L7 L9 join_def setequ_ext subset_def)\n\n(**Below we prove several duality relationships between ADDI(a/b) and MULT(a/b).*)\n\n(**Duality between MULT-a and ADDI-b (an easy corollary from the self-duality of MONO).*)\nlemma MULTa_ADDIb_dual1: \"MULT\\<^sup>a \\<phi> = ADDI\\<^sup>b \\<phi>\\<^sup>d\" by (metis MONO_ADDIb MONO_MULTa MONO_dual)\nlemma MULTa_ADDIb_dual2: \"ADDI\\<^sup>b \\<phi> = MULT\\<^sup>a \\<phi>\\<^sup>d\" by (simp add: MULTa_ADDIb_dual1 dual_invol)\n(**Duality between ADDI-a and MULT-b.*)\nlemma ADDIa_MULTb_dual1: \"ADDI\\<^sup>a \\<phi> = MULT\\<^sup>b \\<phi>\\<^sup>d\" unfolding cond op_dual_def by (metis BA_cp BA_deMorgan1 BA_dn setequ_ext)\nlemma ADDIa_MULTb_dual2: \"MULT\\<^sup>b \\<phi> = ADDI\\<^sup>a \\<phi>\\<^sup>d\" by (simp add: ADDIa_MULTb_dual1 dual_invol)\n(**Duality between ADDI and MULT.*)\nlemma ADDI_MULT_dual1: \"ADDI \\<phi> = MULT \\<phi>\\<^sup>d\" using ADDI_char ADDIa_MULTb_dual1 MULT_char MULTa_ADDIb_dual2 by blast\nlemma ADDI_MULT_dual2: \"MULT \\<phi> = ADDI \\<phi>\\<^sup>d\" by (simp add: ADDI_MULT_dual1 dual_invol)\n\n\n(**We verify properties regarding closure over meets/joins for fixed-points.*)\n\n(**MULT implies meet-closedness of the set of fixed-points (the converse requires additional assumptions)*)\nlemma MULT_meetclosed: \"MULT \\<phi> \\<Longrightarrow> meet_closed (fp \\<phi>)\" by (simp add: MULT_def fixpoints_def meet_closed_def setequ_ext)\nlemma \"meet_closed (fp \\<phi>) \\<Longrightarrow> MULT \\<phi>\" nitpick oops (*countermodel found: needs further assumptions*)\nlemma meetclosed_MULT: \"MONO \\<phi> \\<Longrightarrow> CNTR \\<phi> \\<Longrightarrow> IDEM\\<^sup>b \\<phi> \\<Longrightarrow> meet_closed (fp \\<phi>) \\<Longrightarrow> MULT \\<phi>\" by (smt (z3) CNTR_def IDEM_b_def MONO_MULTa MONO_def MULT_a_def MULT_def fixpoints_def meet_closed_def meet_def setequ_char setequ_ext subset_def)\n\n(**ADDI implies join-closedness of the set of fixed-points (the converse requires additional assumptions)*)\nlemma ADDI_joinclosed: \"ADDI \\<phi> \\<Longrightarrow> join_closed (fp \\<phi>)\" by (simp add: ADDI_def fixpoints_def join_closed_def setequ_ext)\nlemma \"join_closed (fp \\<phi>) \\<Longrightarrow> ADDI \\<phi>\" nitpick oops (*countermodel found: needs further assumptions*)\nlemma joinclosed_ADDI: \"MONO \\<phi> \\<Longrightarrow> EXPN \\<phi> \\<Longrightarrow> IDEM\\<^sup>a \\<phi> \\<Longrightarrow> join_closed (fp \\<phi>) \\<Longrightarrow> ADDI \\<phi>\" by (smt (verit, ccfv_threshold) ADDI_MULT_dual1 BA_deMorgan2 EXPN_CNTR_dual1 IDEM_dual1 MONO_dual fp_dual join_closed_def meet_closed_def meetclosed_MULT sdfun_dcompl_def setequ_ext)\n\n(**Assuming MONO, we have that EXPN (CNTR) implies meet-closed (join-closed) for the set of fixed-points.*)\nlemma EXPN_meetclosed: \"MONO \\<phi> \\<Longrightarrow> EXPN \\<phi> \\<Longrightarrow> meet_closed (fp \\<phi>)\" by (smt (verit) EXPN_def MONO_MULTa MULT_a_def fixpoints_def meet_closed_def setequ_char setequ_ext)\nlemma CNTR_joinclosed: \"MONO \\<phi> \\<Longrightarrow> CNTR \\<phi> \\<Longrightarrow> join_closed (fp \\<phi>)\" by (smt (verit, best) ADDI_b_def CNTR_def MONO_ADDIb fixpoints_def join_closed_def setequ_char setequ_ext)\n\n(**Further assuming IDEM the above results can be stated to the whole range of an operator.*)\nlemma \"MONO \\<phi> \\<Longrightarrow> EXPN \\<phi> \\<Longrightarrow> IDEM \\<phi> \\<Longrightarrow> meet_closed (\\<lbrakk>\\<phi> _\\<rbrakk>)\" by (simp add: EXPN_meetclosed IDEM_range_fp_char)\nlemma \"MONO \\<phi> \\<Longrightarrow> CNTR \\<phi> \\<Longrightarrow> IDEM \\<phi> \\<Longrightarrow> join_closed (\\<lbrakk>\\<phi> _\\<rbrakk>)\" by (simp add: CNTR_joinclosed IDEM_range_fp_char) \n\nend\n", "meta": {"author": "davfuenmayor", "repo": "topological-semantics", "sha": "770a84ffa2cf8498bd5f60853d11be4d77fc8cd3", "save_path": "github-repos/isabelle/davfuenmayor-topological-semantics", "path": "github-repos/isabelle/davfuenmayor-topological-semantics/topological-semantics-770a84ffa2cf8498bd5f60853d11be4d77fc8cd3/conditions/conditions_positive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033682, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.763990462830977}}
{"text": "theory \"Mono-Nat-Fun\"\nimports \"HOL-Library.Infinite_Set\"\nbegin\n\ntext \\<open>\nThe following lemma proves that a monotonous function from and to the natural numbers is either eventually\nconstant or unbounded.\n\\<close>\n\nlemma nat_mono_characterization:\n  fixes f :: \"nat \\<Rightarrow> nat\"\n  assumes \"mono f\"\n  obtains n where \"\\<And>m . n \\<le> m \\<Longrightarrow> f n = f m\" | \"\\<And> m . \\<exists> n . m \\<le> f n\"\nproof (cases \"finite (range f)\")\n  case True\n  from Max_in[OF True]\n  obtain n where Max: \"f n = Max (range f)\" by auto\n  show thesis\n  proof(rule that(1))\n    fix m\n    assume \"n \\<le> m\"\n    hence \"f n \\<le> f m\" using \\<open>mono f\\<close> by (metis monoD)\n    also\n    have \"f m \\<le> f n\" unfolding Max by (rule Max_ge[OF True rangeI])\n    finally\n    show \"f n = f m\".\n  qed\nnext\n  case False\n  thus thesis by (fastforce intro: that(2) simp add: infinite_nat_iff_unbounded_le)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Launchbury/Mono-Nat-Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9425067179697694, "lm_q2_score": 0.8104789063814617, "lm_q1q2_score": 0.7638818140373195}}
{"text": "(*<*)\ntheory CodeGen imports Main begin\n(*>*)\n\nsection\\<open>Case Study: Compiling Expressions\\<close>\n\ntext\\<open>\\label{sec:ExprCompiler}\n\\index{compiling expressions example|(}%\nThe task is to develop a compiler from a generic type of expressions (built\nfrom variables, constants and binary operations) to a stack machine.  This\ngeneric type of expressions is a generalization of the boolean expressions in\n\\S\\ref{sec:boolex}.  This time we do not commit ourselves to a particular\ntype of variables or values but make them type parameters.  Neither is there\na fixed set of binary operations: instead the expression contains the\nappropriate function itself.\n\\<close>\n\ntype_synonym 'v binop = \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v\"\ndatatype (dead 'a, 'v) expr = Cex 'v\n                      | Vex 'a\n                      | Bex \"'v binop\"  \"('a,'v)expr\"  \"('a,'v)expr\"\n\ntext\\<open>\\noindent\nThe three constructors represent constants, variables and the application of\na binary operation to two subexpressions.\n\nThe value of an expression with respect to an environment that maps variables to\nvalues is easily defined:\n\\<close>\n\nprimrec \"value\" :: \"('a,'v)expr \\<Rightarrow> ('a \\<Rightarrow> 'v) \\<Rightarrow> 'v\" where\n\"value (Cex v) env = v\" |\n\"value (Vex a) env = env a\" |\n\"value (Bex f e1 e2) env = f (value e1 env) (value e2 env)\"\n\ntext\\<open>\nThe stack machine has three instructions: load a constant value onto the\nstack, load the contents of an address onto the stack, and apply a\nbinary operation to the two topmost elements of the stack, replacing them by\nthe result. As for \\<open>expr\\<close>, addresses and values are type parameters:\n\\<close>\n\ndatatype (dead 'a, 'v) instr = Const 'v\n                       | Load 'a\n                       | Apply \"'v binop\"\n\ntext\\<open>\nThe execution of the stack machine is modelled by a function\n\\<open>exec\\<close> that takes a list of instructions, a store (modelled as a\nfunction from addresses to values, just like the environment for\nevaluating expressions), and a stack (modelled as a list) of values,\nand returns the stack at the end of the execution --- the store remains\nunchanged:\n\\<close>\n\nprimrec exec :: \"('a,'v)instr list \\<Rightarrow> ('a\\<Rightarrow>'v) \\<Rightarrow> 'v list \\<Rightarrow> 'v list\"\nwhere\n\"exec [] s vs = vs\" |\n\"exec (i#is) s vs = (case i of\n    Const v  \\<Rightarrow> exec is s (v#vs)\n  | Load a   \\<Rightarrow> exec is s ((s a)#vs)\n  | Apply f  \\<Rightarrow> exec is s ((f (hd vs) (hd(tl vs)))#(tl(tl vs))))\"\n\ntext\\<open>\\noindent\nRecall that \\<^term>\\<open>hd\\<close> and \\<^term>\\<open>tl\\<close>\nreturn the first element and the remainder of a list.\nBecause all functions are total, \\cdx{hd} is defined even for the empty\nlist, although we do not know what the result is. Thus our model of the\nmachine always terminates properly, although the definition above does not\ntell us much about the result in situations where \\<^term>\\<open>Apply\\<close> was executed\nwith fewer than two elements on the stack.\n\nThe compiler is a function from expressions to a list of instructions. Its\ndefinition is obvious:\n\\<close>\n\nprimrec compile :: \"('a,'v)expr \\<Rightarrow> ('a,'v)instr list\" where\n\"compile (Cex v)       = [Const v]\" |\n\"compile (Vex a)       = [Load a]\" |\n\"compile (Bex f e1 e2) = (compile e2) @ (compile e1) @ [Apply f]\"\n\ntext\\<open>\nNow we have to prove the correctness of the compiler, i.e.\\ that the\nexecution of a compiled expression results in the value of the expression:\n\\<close>\ntheorem \"exec (compile e) s [] = [value e s]\"\n(*<*)oops(*>*)\ntext\\<open>\\noindent\nThis theorem needs to be generalized:\n\\<close>\n\ntheorem \"\\<forall>vs. exec (compile e) s vs = (value e s) # vs\"\n\ntxt\\<open>\\noindent\nIt will be proved by induction on \\<^term>\\<open>e\\<close> followed by simplification.  \nFirst, we must prove a lemma about executing the concatenation of two\ninstruction sequences:\n\\<close>\n(*<*)oops(*>*)\nlemma exec_app[simp]:\n  \"\\<forall>vs. exec (xs@ys) s vs = exec ys s (exec xs s vs)\" \n\ntxt\\<open>\\noindent\nThis requires induction on \\<^term>\\<open>xs\\<close> and ordinary simplification for the\nbase cases. In the induction step, simplification leaves us with a formula\nthat contains two \\<open>case\\<close>-expressions over instructions. Thus we add\nautomatic case splitting, which finishes the proof:\n\\<close>\napply(induct_tac xs, simp, simp split: instr.split)\n(*<*)done(*>*)\ntext\\<open>\\noindent\nNote that because both \\methdx{simp_all} and \\methdx{auto} perform simplification, they can\nbe modified in the same way as \\<open>simp\\<close>.  Thus the proof can be\nrewritten as\n\\<close>\n(*<*)\ndeclare exec_app[simp del]\n\n\nWe could now go back and prove \\<^prop>\\<open>exec (compile e) s [] = [value e s]\\<close>\nmerely by simplification with the generalized version we just proved.\nHowever, this is unnecessary because the generalized version fully subsumes\nits instance.%\n\\index{compiling expressions example|)}\n\\<close>\n(*<*)\ntheorem \"\\<forall>vs. exec (compile e) s vs = (value e s) # vs\"\nby(induct_tac e, auto)\nend\n(*>*)\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/CodeGen/CodeGen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.7638262553113693}}
{"text": "theory Exercise_2_11\n  imports Main\nbegin\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n  \nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"eval Var v = v\" |\n  \"eval (Const a) _ = a\" |\n  \"eval (Add a b) v = (eval a v) + (eval b v)\" |\n  \"eval (Mult a b) v = (eval a v) * (eval b v)\"\n  \nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"evalp [] v = 0\" |\n  \"evalp (x#xs) v = x + v*(evalp xs v)\"\n\nfun mulc :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"mulc a [] = []\" |\n  \"mulc a (x#xs) = (a*x)#(mulc a xs)\"\n  \nfun addp :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"addp [] [] = []\" |\n  \"addp [] ys = ys\" |\n  \"addp xs [] = xs\" |\n  \"addp (x#xs) (y#ys) = (x+y)#(addp xs ys)\"\n  \nfun multp :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"multp [] [] = []\" |\n  \"multp [] ys = []\" |\n  \"multp xs [] = []\" |\n  \"multp (a#xs) (b#ys) = addp ((a*b)#(addp (mulc b xs) (mulc a ys))) (0#0#(multp xs ys))\"\n  \nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n  \"coeffs Var = [0,1]\" |\n  \"coeffs (Const a) = [a]\" |\n  \"coeffs (Add a b) = addp (coeffs a) (coeffs b)\" |\n  \"coeffs (Mult a b) = multp (coeffs a) (coeffs b)\"\n\nlemma evalp_addp: \"evalp (addp p1 p2) v = (evalp p1 v) + (evalp p2 v)\"\n  apply(induction p1 rule:addp.induct)\n  apply(auto simp add: algebra_simps)\n  done\n\nlemma evalp_mulc: \"evalp (mulc a p) v = a * (evalp p v)\"\n  apply(induction p)\n  apply(auto simp add: algebra_simps)\n  done\n\nlemma evalp_multp: \"evalp (multp p1 p2) v = (evalp p1 v) * (evalp p2 v)\"\n  apply(induction p1 rule:multp.induct)\n  apply(auto simp add: algebra_simps simp add:evalp_addp simp add: evalp_mulc)\n  done\n\nlemma preserve: \"evalp(coeffs e) x = eval e x\"\n  apply(induction e)\n  apply(auto simp add: algebra_simps simp add:evalp_addp simp add: evalp_multp)\n  done\n", "meta": {"author": "AlexeyAkhunov", "repo": "isabelle", "sha": "3a46e94f04c64b12f806fe50750a5463786593d9", "save_path": "github-repos/isabelle/AlexeyAkhunov-isabelle", "path": "github-repos/isabelle/AlexeyAkhunov-isabelle/isabelle-3a46e94f04c64b12f806fe50750a5463786593d9/Exercise_2_11.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7636998974366404}}
{"text": "theory RegLangs\n  imports Main \"HOL-Library.Sublist\"\nbegin\n\nsection \\<open>Sequential Composition of Languages\\<close>\n\ndefinition\n  Sequ :: \"string set \\<Rightarrow> string set \\<Rightarrow> string set\" (\"_ ;; _\" [100,100] 100)\nwhere \n  \"A ;; B = {s1 @ s2 | s1 s2. s1 \\<in> A \\<and> s2 \\<in> B}\"\n\ntext \\<open>Two Simple Properties about Sequential Composition\\<close>\n\nlemma Sequ_empty_string [simp]:\n  shows \"A ;; {[]} = A\"\n  and   \"{[]} ;; A = A\"\nby (simp_all add: Sequ_def)\n\nlemma Sequ_empty [simp]:\n  shows \"A ;; {} = {}\"\n  and   \"{} ;; A = {}\"\n  by (simp_all add: Sequ_def)\n\nlemma concI[simp,intro]: \"u : A \\<Longrightarrow> v : B \\<Longrightarrow> u@v : A ;; B\"\nby (auto simp add: Sequ_def)\n\nlemma concE[elim]: \nassumes \"w \\<in> A ;; B\"\nobtains u v where \"u \\<in> A\" \"v \\<in> B\" \"w = u@v\"\nusing assms by (auto simp: Sequ_def)\n\nlemma concI_if_Nil2: \"[] \\<in> B \\<Longrightarrow> xs : A \\<Longrightarrow> xs \\<in> A ;; B\"\nby (metis append_Nil2 concI)\n\nlemma conc_assoc: \"(A ;; B) ;; C = A ;; (B ;; C)\"\nby (auto elim!: concE) (simp only: append_assoc[symmetric] concI)\n\n\ntext \\<open>Language power operations\\<close>\n\noverloading lang_pow == \"compow :: nat \\<Rightarrow> string set \\<Rightarrow> string set\"\nbegin\n  primrec lang_pow :: \"nat \\<Rightarrow> string set \\<Rightarrow> string set\" where\n  \"lang_pow 0 A = {[]}\" |\n  \"lang_pow (Suc n) A = A ;; (lang_pow n A)\"\nend\n\n\n\n\nlemma lang_pow_add: \"A ^^ (n + m) = (A ^^ n) ;; (A ^^ m)\"\n  by (induct n) (auto simp: conc_assoc)\n\nlemma lang_empty: \n  fixes A::\"string set\"\n  shows \"A ^^ 0 = {[]}\"\n  by simp\n\nsection \\<open>Semantic Derivative (Left Quotient) of Languages\\<close>\n\ndefinition\n  Der :: \"char \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Der c A \\<equiv> {s. c # s \\<in> A}\"\n\ndefinition\n  Ders :: \"string \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Ders s A \\<equiv> {s'. s @ s' \\<in> A}\"\n\nlemma Der_null [simp]:\n  shows \"Der c {} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_empty [simp]:\n  shows \"Der c {[]} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_char [simp]:\n  shows \"Der c {[d]} = (if c = d then {[]} else {})\"\nunfolding Der_def\nby auto\n\nlemma Der_union [simp]:\n  shows \"Der c (A \\<union> B) = Der c A \\<union> Der c B\"\nunfolding Der_def\nby auto\n\nlemma Der_Sequ [simp]:\n  shows \"Der c (A ;; B) = (Der c A) ;; B \\<union> (if [] \\<in> A then Der c B else {})\"\nunfolding Der_def Sequ_def\nby (auto simp add: Cons_eq_append_conv)\n\n\nsection \\<open>Kleene Star for Languages\\<close>\n\ninductive_set\n  Star :: \"string set \\<Rightarrow> string set\" (\"_\\<star>\" [101] 102)\n  for A :: \"string set\"\nwhere\n  start[intro]: \"[] \\<in> A\\<star>\"\n| step[intro]:  \"\\<lbrakk>s1 \\<in> A; s2 \\<in> A\\<star>\\<rbrakk> \\<Longrightarrow> s1 @ s2 \\<in> A\\<star>\"\n\n(* Arden's lemma *)\n\nlemma Star_cases:\n  shows \"A\\<star> = {[]} \\<union> A ;; A\\<star>\"\nunfolding Sequ_def\nby (auto) (metis Star.simps)\n\nlemma Star_decomp: \n  assumes \"c # x \\<in> A\\<star>\" \n  shows \"\\<exists>s1 s2. x = s1 @ s2 \\<and> c # s1 \\<in> A \\<and> s2 \\<in> A\\<star>\"\nusing assms\nby (induct x\\<equiv>\"c # x\" rule: Star.induct) \n   (auto simp add: append_eq_Cons_conv)\n\nlemma Star_Der_Sequ: \n  shows \"Der c (A\\<star>) \\<subseteq> (Der c A) ;; A\\<star>\"\nunfolding Der_def Sequ_def\nby(auto simp add: Star_decomp)\n\nlemma Der_inter[simp]:   \"Der a (A \\<inter> B) = Der a A \\<inter> Der a B\"\n  and Der_compl[simp]:   \"Der a (-A) = - Der a A\"\n  and Der_Union[simp]:   \"Der a (Union M) = Union(Der a ` M)\"\n  and Der_UN[simp]:      \"Der a (UN x:I. S x) = (UN x:I. Der a (S x))\"\nby (auto simp: Der_def)\n\nlemma Der_star[simp]:\n  shows \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\"\nproof -    \n  have \"Der c (A\\<star>) = Der c ({[]} \\<union> A ;; A\\<star>)\"  \n    by (simp only: Star_cases[symmetric])\n  also have \"... = Der c (A ;; A\\<star>)\"\n    by (simp only: Der_union Der_empty) (simp)\n  also have \"... = (Der c A) ;; A\\<star> \\<union> (if [] \\<in> A then Der c (A\\<star>) else {})\"\n    by simp\n  also have \"... =  (Der c A) ;; A\\<star>\"\n    using Star_Der_Sequ by auto\n  finally show \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\" .\nqed\n\nlemma Der_pow[simp]:\n  shows \"Der c (A ^^ n) = (if n = 0 then {} else (Der c A) ;; (A ^^ (n - 1)))\"\n  apply(induct n arbitrary: A)\n   apply(auto simp add: Cons_eq_append_conv)\n  by (metis Suc_pred concI_if_Nil2 conc_assoc conc_pow_comm lang_pow.simps(2))\n\n\nlemma Star_concat:\n  assumes \"\\<forall>s \\<in> set ss. s \\<in> A\"  \n  shows \"concat ss \\<in> A\\<star>\"\nusing assms by (induct ss) (auto)\n\nlemma Star_split:\n  assumes \"s \\<in> A\\<star>\"\n  shows \"\\<exists>ss. concat ss = s \\<and> (\\<forall>s \\<in> set ss. s \\<in> A \\<and> s \\<noteq> [])\"\nusing assms\n  apply(induct rule: Star.induct)\n  using concat.simps(1) apply fastforce\n  apply(clarify)\n  by (metis append_Nil concat.simps(2) set_ConsD)\n\n\n\nsection \\<open>Regular Expressions\\<close>\n\ndatatype rexp =\n  ZERO\n| ONE\n| CH char\n| SEQ rexp rexp\n| ALT rexp rexp\n| STAR rexp\n| NTIMES rexp nat\n\nsection \\<open>Semantics of Regular Expressions\\<close>\n \nfun\n  L :: \"rexp \\<Rightarrow> string set\"\nwhere\n  \"L (ZERO) = {}\"\n| \"L (ONE) = {[]}\"\n| \"L (CH c) = {[c]}\"\n| \"L (SEQ r1 r2) = (L r1) ;; (L r2)\"\n| \"L (ALT r1 r2) = (L r1) \\<union> (L r2)\"\n| \"L (STAR r) = (L r)\\<star>\"\n| \"L (NTIMES r n) = (L r) ^^ n\"\n\nsection \\<open>Nullable, Derivatives\\<close>\n\nfun\n nullable :: \"rexp \\<Rightarrow> bool\"\nwhere\n  \"nullable (ZERO) = False\"\n| \"nullable (ONE) = True\"\n| \"nullable (CH c) = False\"\n| \"nullable (ALT r1 r2) = (nullable r1 \\<or> nullable r2)\"\n| \"nullable (SEQ r1 r2) = (nullable r1 \\<and> nullable r2)\"\n| \"nullable (STAR r) = True\"\n| \"nullable (NTIMES r n) = (if n = 0 then True else nullable r)\"\n\nfun\n der :: \"char \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"der c (ZERO) = ZERO\"\n| \"der c (ONE) = ZERO\"\n| \"der c (CH d) = (if c = d then ONE else ZERO)\"\n| \"der c (ALT r1 r2) = ALT (der c r1) (der c r2)\"\n| \"der c (SEQ r1 r2) = \n     (if nullable r1\n      then ALT (SEQ (der c r1) r2) (der c r2)\n      else SEQ (der c r1) r2)\"\n| \"der c (STAR r) = SEQ (der c r) (STAR r)\"\n| \"der c (NTIMES r n) = (if n = 0 then ZERO else SEQ (der c r) (NTIMES r (n - 1)))\"\n\n\nfun \n ders :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"ders [] r = r\"\n| \"ders (c # s) r = ders s (der c r)\"\n\n\nlemma pow_empty_iff:\n  shows \"[] \\<in> (L r) ^^ n \\<longleftrightarrow> (if n = 0 then True else [] \\<in> (L r))\"\n  by (induct n) (auto simp add: Sequ_def)\n\nlemma nullable_correctness:\n  shows \"nullable r  \\<longleftrightarrow> [] \\<in> (L r)\"\n  by (induct r) (auto simp add: Sequ_def pow_empty_iff) \n\nlemma der_correctness:\n  shows \"L (der c r) = Der c (L r)\"\n  apply (induct r) \n        apply(auto simp add: nullable_correctness Sequ_def)\n  using Der_def apply force\n  using Der_def apply auto[1]\n  apply (smt (verit, ccfv_SIG) Der_def append_eq_Cons_conv mem_Collect_eq)\n  using Der_def apply force\n  using Der_Sequ Sequ_def by auto\n\nlemma ders_correctness:\n  shows \"L (ders s r) = Ders s (L r)\"\n  by (induct s arbitrary: r)\n     (simp_all add: Ders_def der_correctness Der_def)\n\nlemma ders_append:\n  shows \"ders (s1 @ s2) r = ders s2 (ders s1 r)\"\n  by (induct s1 arbitrary: s2 r) (auto)\n\nlemma ders_snoc:\n  shows \"ders (s @ [c]) r = der c (ders s r)\"\n  by (simp add: ders_append)\n\n\nend", "meta": {"author": "urbanchr", "repo": "posix", "sha": "40b6abbce4250c82e4492aabae900d5fe5bca0d6", "save_path": "github-repos/isabelle/urbanchr-posix", "path": "github-repos/isabelle/urbanchr-posix/posix-40b6abbce4250c82e4492aabae900d5fe5bca0d6/RegLangs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7636825661887877}}
{"text": "(*  Title:      HOL/Examples/Sqrt.thy\n    Author:     Makarius\n    Author:     Tobias Nipkow, TU Muenchen\n*)\n\nsection \\<open>Square roots of primes are irrational\\<close>\n\ntheory Sqrt\n  imports Complex_Main \"HOL-Computational_Algebra.Primes\"\nbegin\n\ntext \\<open>\n  The square root of any prime number (including 2) is irrational.\n\\<close>\n\ntheorem sqrt_prime_irrational:\n  fixes p :: nat\n  assumes \"prime p\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"p > 1\" by (rule prime_gt_1_nat)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat\n    where n: \"n \\<noteq> 0\"\n      and sqrt_rat: \"\\<bar>sqrt p\\<bar> = m / n\"\n      and \"coprime m n\" by (rule Rats_abs_nat_div_natE)\n  have eq: \"m\\<^sup>2 = p * n\\<^sup>2\"\n  proof -\n    from n and sqrt_rat have \"m = \\<bar>sqrt p\\<bar> * n\" by simp\n    then have \"m\\<^sup>2 = (sqrt p)\\<^sup>2 * n\\<^sup>2\" by (simp add: power_mult_distrib)\n    also have \"(sqrt p)\\<^sup>2 = p\" by simp\n    also have \"\\<dots> * n\\<^sup>2 = p * n\\<^sup>2\" by simp\n    finally show ?thesis by linarith\n  qed\n  have \"p dvd m \\<and> p dvd n\"\n  proof\n    from eq have \"p dvd m\\<^sup>2\" ..\n    with \\<open>prime p\\<close> show \"p dvd m\" by (rule prime_dvd_power)\n    then obtain k where \"m = p * k\" ..\n    with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by algebra\n    with p have \"n\\<^sup>2 = p * k\\<^sup>2\" by (simp add: power2_eq_square)\n    then have \"p dvd n\\<^sup>2\" ..\n    with \\<open>prime p\\<close> show \"p dvd n\" by (rule prime_dvd_power)\n  qed\n  then have \"p dvd gcd m n\" by simp\n  with \\<open>coprime m n\\<close> have \"p = 1\" by simp\n  with p show False by simp\nqed\n\ncorollary sqrt_2_not_rat: \"sqrt 2 \\<notin> \\<rat>\"\n  using sqrt_prime_irrational [of 2] by simp\n\ntext \\<open>\n  Here is an alternative version of the main proof, using mostly linear\n  forward-reasoning. While this results in less top-down structure, it is\n  probably closer to proofs seen in mathematics.\n\\<close>\n\ntheorem\n  fixes p :: nat\n  assumes \"prime p\"\n  shows \"sqrt p \\<notin> \\<rat>\"\nproof\n  from \\<open>prime p\\<close> have p: \"p > 1\" by (rule prime_gt_1_nat)\n  assume \"sqrt p \\<in> \\<rat>\"\n  then obtain m n :: nat\n    where n: \"n \\<noteq> 0\"\n      and sqrt_rat: \"\\<bar>sqrt p\\<bar> = m / n\"\n      and \"coprime m n\" by (rule Rats_abs_nat_div_natE)\n  from n and sqrt_rat have \"m = \\<bar>sqrt p\\<bar> * n\" by simp\n  then have \"m\\<^sup>2 = (sqrt p)\\<^sup>2 * n\\<^sup>2\" by (auto simp add: power2_eq_square)\n  also have \"(sqrt p)\\<^sup>2 = p\" by simp\n  also have \"\\<dots> * n\\<^sup>2 = p * n\\<^sup>2\" by simp\n  finally have eq: \"m\\<^sup>2 = p * n\\<^sup>2\" by linarith\n  then have \"p dvd m\\<^sup>2\" ..\n  with \\<open>prime p\\<close> have dvd_m: \"p dvd m\" by (rule prime_dvd_power)\n  then obtain k where \"m = p * k\" ..\n  with eq have \"p * n\\<^sup>2 = p\\<^sup>2 * k\\<^sup>2\" by algebra\n  with p have \"n\\<^sup>2 = p * k\\<^sup>2\" by (simp add: power2_eq_square)\n  then have \"p dvd n\\<^sup>2\" ..\n  with \\<open>prime p\\<close> have \"p dvd n\" by (rule prime_dvd_power)\n  with dvd_m have \"p dvd gcd m n\" by (rule gcd_greatest)\n  with \\<open>coprime m n\\<close> have \"p = 1\" by simp\n  with p show False by simp\nqed\n\n\ntext \\<open>\n  Another old chestnut, which is a consequence of the irrationality of\n  \\<^term>\\<open>sqrt 2\\<close>.\n\\<close>\n\nlemma \"\\<exists>a b::real. a \\<notin> \\<rat> \\<and> b \\<notin> \\<rat> \\<and> a powr b \\<in> \\<rat>\" (is \"\\<exists>a b. ?P a b\")\nproof (cases \"sqrt 2 powr sqrt 2 \\<in> \\<rat>\")\n  case True\n  with sqrt_2_not_rat have \"?P (sqrt 2) (sqrt 2)\" by simp\n  then show ?thesis by blast\nnext\n  case False\n  with sqrt_2_not_rat powr_powr have \"?P (sqrt 2 powr sqrt 2) (sqrt 2)\" by simp\n  then show ?thesis by blast\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Examples/Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.880797068590724, "lm_q1q2_score": 0.7636825495446801}}
{"text": "subsubsection \\<open>Addition\\<close>\ntheory Nat_Add\n  imports Nat_Rec\nbegin\n\ndefinition \"nat_add m n \\<equiv> nat_rec m n succ\"\n\nlemma nat_add_type [type]: \"nat_add : Nat \\<Rightarrow> Nat \\<Rightarrow> Nat\"\n  unfolding nat_add_def by auto\n\nbundle isa_set_nat_add_syntax begin notation nat_add (infixl \"+\" 65) end\nbundle no_isa_set_nat_add_syntax begin no_notation nat_add (infixl \"+\" 65) end\n\nunbundle no_HOL_groups_syntax\nunbundle isa_set_nat_add_syntax\n\nlemma zero_add_eq [iff]: \"0 + n = n\"\n  unfolding nat_add_def by simp\n\nlemma Nat_add_zero_eq [simp]: \"n : Nat \\<Longrightarrow> n + 0 = n\"\n  unfolding nat_add_def by (induction n rule: Nat_induct) auto\n\nlemma Nat_add_assoc:\n  \"\\<lbrakk>l : Nat; m : Nat; n: Nat\\<rbrakk> \\<Longrightarrow> l + m + n = l + (m + n)\"\n  unfolding nat_add_def by (induction l rule: Nat_induct) auto\n\nlemma Nat_succ_add_eq [simp]: \"m : Nat \\<Longrightarrow> succ m + n = succ (m + n)\"\n  unfolding nat_add_def by simp\n\nlemma Nat_add_succ_eq [simp]: \"m : Nat \\<Longrightarrow> m + succ n = succ (m + n)\"\n  by (induction m rule: Nat_induct) auto\n\ncorollary Nat_succ_add_eq_add_succ: \"m : Nat \\<Longrightarrow> succ m + n = m + succ n\"\n  by simp\n\nlemma Nat_add_comm: \"m : Nat \\<Longrightarrow> n : Nat \\<Longrightarrow> m + n = n + m\"\n  by (induction m rule: Nat_induct) auto\n\nlemma Nat_add_comm_left:\n  \"\\<lbrakk>l : Nat; m : Nat; n: Nat\\<rbrakk> \\<Longrightarrow> l + (m + n) = m + (l + n)\"\n  by (induction l rule: Nat_induct) auto\n\nlemmas Nat_add_AC_rules = Nat_add_comm Nat_add_assoc Nat_add_comm_left\n\nlemma Nat_one_add_eq_succ: \"1 + n = succ n\"\n  unfolding nat_one_def by (simp add: nat_add_def)\n\nlemma nat_add_one_eq_succ: \"n : Nat \\<Longrightarrow> n + 1 = succ n\"\n  by (simp only: Nat_add_comm Nat_one_add_eq_succ)\n\nlemma Nat_add_ne_zero_if_ne_zero_left:\n  assumes \"m : Nat\"\n  and \"m \\<noteq> 0\"\n  shows \"m + n \\<noteq> 0\"\n  using assms by (cases m rule: NatE) auto\n\nlemma Nat_add_ne_zero_if_ne_zero_right [simp]:\n  assumes \"m : Nat\"\n  and \"n \\<noteq> 0\"\n  shows \"m + n \\<noteq> 0\"\n  using assms by (cases m rule: NatE) auto\n\nlemma Nat_pred_add_eq [simp]:\n  \"\\<lbrakk>m : Nat; n : Nat; m \\<noteq> 0\\<rbrakk> \\<Longrightarrow> pred m + n = pred (m + n)\"\n  by (cases m rule: NatE) auto\n\ncorollary Nat_add_pred_eq [simp]:\n  \"\\<lbrakk>m : Nat; n : Nat; n \\<noteq> 0\\<rbrakk> \\<Longrightarrow> m + pred n = pred (m + n)\"\n  by (auto simp only: Nat_add_comm[of m] intro: Nat_pred_add_eq)\n\nlemma Nat_succ_add_pred_eq [simp]:\n  \"\\<lbrakk>m : Nat; n : Nat; n \\<noteq> 0\\<rbrakk> \\<Longrightarrow> succ m + pred n = m + n\"\n  by (cases m rule: NatE) auto\n\ncorollary nat_pred_add_succ [simp]:\n  \"\\<lbrakk>m : Nat; n : Nat; m \\<noteq> 0\\<rbrakk> \\<Longrightarrow> pred m + succ n = m + n\"\n  by (auto simp only: Nat_add_comm[of m] Nat_add_comm[of \"pred m\"]\n    intro: Nat_succ_add_pred_eq)\n\nunbundle no_HOL_order_syntax\n\nlemma Nat_le_add [intro]: \"m : Nat \\<Longrightarrow> n : Nat \\<Longrightarrow> m \\<le> m + n\"\n  by (induction m rule: Nat_induct) auto\n\nlemma Nat_lt_add_if_ne_zero: \"\\<lbrakk>m : Nat; n : Nat; n \\<noteq> 0\\<rbrakk> \\<Longrightarrow> m < m + n\"\n  by (induction m rule: Nat_induct) (auto simp: Nat_zero_lt_iff_ne_zero)\n\nlemma Nat_lt_if_add_lt: \"\\<lbrakk>l : Nat; m : Nat; n: Nat; l + m < n\\<rbrakk> \\<Longrightarrow> l < n\"\n  using Nat_lt_if_lt_if_le[OF _ Nat_le_add[of l m]] by auto\n\nlemma Nat_le_if_add_le: \"\\<lbrakk>l : Nat; m : Nat; n: Nat; l + m \\<le> n\\<rbrakk> \\<Longrightarrow> l \\<le> n\"\n  using Nat_le_trans[OF _ Nat_le_add[of l m]] by auto\n\nlemma Nat_lt_add_if_lt:\n  assumes \"m : Nat\" \"n : Nat\"\n  and \"l < m\"\n  shows \"l < m + n\"\nproof -\n  note \\<open>l < m\\<close>\n  moreover have \"... \\<le> m + n\" by auto\n  ultimately show \"l < m + n\" using Nat_lt_if_le_if_lt by auto\n(*TODO: Transitivity rules have typing assumptions. Proof should more\n  look like this:\n  note \\<open>l < m\\<close>\n  also have \"... \\<le> m + n\" by auto\n  finally show \"l < m + n\" .\n*)\nqed\n\nlemma Nat_add_lt_add_if_lt:\n  assumes \"m : Nat\" \"n : Nat\"\n  and \"l < m\"\n  shows \"l + n < m + n\"\nusing \\<open>n : Nat\\<close>\nproof (induction n rule: Nat_induct)\n  (*TODO: should be derivable automatically*)\n  from assms have \"l : Nat\" using Nat_if_lt_Nat by auto\n  case zero then show \"?case\" by simp\n  case (succ n)\n  have \"l + succ n = succ (l + n)\" by simp\n  moreover with succ.IH have \"... < succ (m + n)\"\n    by (auto intro: Nat_succ_lt_succ_if_lt)\n  moreover have \"... = m + succ n\" by simp\n  (*TODO: transitivity proofs are ugly at the moment*)\n  ultimately show \"?case\" by (simp only:)\nqed\n\nlemma Nat_lt_if_add_lt_add:\n  assumes \"l : Nat\" \"m : Nat\" \"n : Nat\"\n  shows \"l + n < m + n \\<Longrightarrow> l < m\"\nusing \\<open>n : Nat\\<close>\nproof (induction n rule: Nat_induct)\n  (* case zero then show \"?case\" by simp *)\n  case (succ n)\n  have \"succ (l + n) = l + succ n\" by simp\n  moreover have \"... < m + succ n\" by fact\n  moreover have \"... = succ (m + n)\" by simp\n  (*TODO: transitivity proofs are ugly at the moment*)\n  ultimately have \"succ (l + n) < succ (m + n)\" by (simp only:)\n  then have \"l + n < m + n\" by simp\n  then show \"l < m\" by (rule succ.IH)\nqed simp\n\ncorollary Nat_add_lt_add_iff_lt:\n  assumes \"l : Nat\" \"m : Nat\" \"n : Nat\"\n  shows \"l + n < m + n \\<longleftrightarrow> l < m\"\nusing assms Nat_lt_if_add_lt_add Nat_add_lt_add_if_lt by blast\n\n\nend\n", "meta": {"author": "kappelmann", "repo": "Isabelle-Set", "sha": "2ac3e1cb6bf847d413f06978b7c82e4d0c103477", "save_path": "github-repos/isabelle/kappelmann-Isabelle-Set", "path": "github-repos/isabelle/kappelmann-Isabelle-Set/Isabelle-Set-2ac3e1cb6bf847d413f06978b7c82e4d0c103477/Isabelle_Set/Nat/Nat_Add.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.8652240721511739, "lm_q1q2_score": 0.7634978426943759}}
{"text": "(*  \n   File:     HOL/Analysis/Ball_Volume.thy\n   Author:   Manuel Eberl, TU München\n*)\n\nsection \\<open>The Volume of an \\<open>n\\<close>-Dimensional Ball\\<close>\n\ntheory Ball_Volume\n  imports Gamma_Function Lebesgue_Integral_Substitution\nbegin\n\ntext \\<open>\n  We define the volume of the unit ball in terms of the Gamma function. Note that the\n  dimension need not be an integer; we also allow fractional dimensions, although we do\n  not use this case or prove anything about it for now.\n\\<close>\ndefinition\\<^marker>\\<open>tag important\\<close> unit_ball_vol :: \"real \\<Rightarrow> real\" where\n  \"unit_ball_vol n = pi powr (n / 2) / Gamma (n / 2 + 1)\"\n\nlemma unit_ball_vol_pos [simp]: \"n \\<ge> 0 \\<Longrightarrow> unit_ball_vol n > 0\"\n  by (force simp: unit_ball_vol_def intro: divide_nonneg_pos)\n\nlemma unit_ball_vol_nonneg [simp]: \"n \\<ge> 0 \\<Longrightarrow> unit_ball_vol n \\<ge> 0\"\n  by (simp add: dual_order.strict_implies_order)\n\ntext \\<open>\n  We first need the value of the following integral, which is at the core of\n  computing the measure of an \\<open>n + 1\\<close>-dimensional ball in terms of the measure of an \n  \\<open>n\\<close>-dimensional one.\n\\<close>\nlemma emeasure_cball_aux_integral:\n  \"(\\<integral>\\<^sup>+x. indicator {-1..1} x * sqrt (1 - x\\<^sup>2) ^ n \\<partial>lborel) = \n      ennreal (Beta (1 / 2) (real n / 2 + 1))\"\nproof -\n  have \"((\\<lambda>t. t powr (-1 / 2) * (1 - t) powr (real n / 2)) has_integral\n          Beta (1 / 2) (real n / 2 + 1)) {0..1}\"\n    using has_integral_Beta_real[of \"1/2\" \"n / 2 + 1\"] by simp\n  from nn_integral_has_integral_lebesgue[OF _ this] have\n     \"ennreal (Beta (1 / 2) (real n / 2 + 1)) =\n        nn_integral lborel (\\<lambda>t. ennreal (t powr (-1 / 2) * (1 - t) powr (real n / 2) * \n                                indicator {0^2..1^2} t))\"\n    by (simp add: mult_ac ennreal_mult' ennreal_indicator)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal (x\\<^sup>2 powr - (1 / 2) * (1 - x\\<^sup>2) powr (real n / 2) * (2 * x) *\n                          indicator {0..1} x) \\<partial>lborel)\"\n    by (subst nn_integral_substitution[where g = \"\\<lambda>x. x ^ 2\" and g' = \"\\<lambda>x. 2 * x\"])\n       (auto intro!: derivative_eq_intros continuous_intros simp: set_borel_measurable_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. 2 * ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {0..1} x) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{0}\"]) \n       (auto simp: indicator_def powr_minus powr_half_sqrt field_split_simps ennreal_mult')\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {0..1} x) \\<partial>lborel) +\n                    (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {0..1} x) \\<partial>lborel)\"\n    (is \"_ = ?I + _\") by (simp add: mult_2 nn_integral_add)\n  also have \"?I = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {-1..0} x) \\<partial>lborel)\"\n    by (subst nn_integral_real_affine[of _ \"-1\" 0])\n       (auto simp: indicator_def intro!: nn_integral_cong)\n  hence \"?I + ?I = \\<dots> + ?I\" by simp\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * \n                    (indicator {-1..0} x + indicator{0..1} x)) \\<partial>lborel)\"\n    by (subst nn_integral_add [symmetric]) (auto simp: algebra_simps)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal ((1 - x\\<^sup>2) powr (real n / 2) * indicator {-1..1} x) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{0}\"]) (auto simp: indicator_def)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal (indicator {-1..1} x * sqrt (1 - x\\<^sup>2) ^ n) \\<partial>lborel)\"\n    by (intro nn_integral_cong_AE AE_I[of _ _ \"{1, -1}\"])\n       (auto simp: powr_half_sqrt [symmetric] indicator_def abs_square_le_1\n          abs_square_eq_1 powr_def exp_of_nat_mult [symmetric] emeasure_lborel_countable)\n  finally show ?thesis ..\nqed\n\nlemma real_sqrt_le_iff': \"x \\<ge> 0 \\<Longrightarrow> y \\<ge> 0 \\<Longrightarrow> sqrt x \\<le> y \\<longleftrightarrow> x \\<le> y ^ 2\"\n  using real_le_lsqrt sqrt_le_D by blast\n\nlemma power2_le_iff_abs_le: \"y \\<ge> 0 \\<Longrightarrow> (x::real) ^ 2 \\<le> y ^ 2 \\<longleftrightarrow> abs x \\<le> y\"\n  by (subst real_sqrt_le_iff' [symmetric]) auto\n\ntext \\<open>\n  Isabelle's type system makes it very difficult to do an induction over the dimension \n  of a Euclidean space type, because the type would change in the inductive step. To avoid \n  this problem, we instead formulate the problem in a more concrete way by unfolding the \n  definition of the Euclidean norm.\n\\<close>\nlemma emeasure_cball_aux:\n  assumes \"finite A\" \"r > 0\"\n  shows   \"emeasure (Pi\\<^sub>M A (\\<lambda>_. lborel))\n             ({f. sqrt (\\<Sum>i\\<in>A. (f i)\\<^sup>2) \\<le> r} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) =\n             ennreal (unit_ball_vol (real (card A)) * r ^ card A)\"\n  using assms\nproof (induction arbitrary: r)\n  case (empty r)\n  thus ?case\n    by (simp add: unit_ball_vol_def space_PiM)\nnext\n  case (insert i A r)\n  interpret product_sigma_finite \"\\<lambda>_. lborel\"\n    by standard\n  have \"emeasure (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel)) \n            ({f. sqrt (\\<Sum>i\\<in>insert i A. (f i)\\<^sup>2) \\<le> r} \\<inter> space (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))) =\n        nn_integral (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))\n          (indicator ({f. sqrt (\\<Sum>i\\<in>insert i A. (f i)\\<^sup>2) \\<le> r} \\<inter>\n          space (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))))\"\n    by (subst nn_integral_indicator) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ y. \\<integral>\\<^sup>+ x. indicator ({f. sqrt ((f i)\\<^sup>2 + (\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \\<le> r} \\<inter> \n                                space (Pi\\<^sub>M (insert i A) (\\<lambda>_. lborel))) (x(i := y)) \n                   \\<partial>Pi\\<^sub>M A (\\<lambda>_. lborel) \\<partial>lborel)\"\n    using insert.prems insert.hyps by (subst product_nn_integral_insert_rev) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). \\<integral>\\<^sup>+ x. indicator {-r..r} y * indicator ({f. sqrt ((\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \\<le> \n               sqrt (r ^ 2 - y ^ 2)} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) x \\<partial>Pi\\<^sub>M A (\\<lambda>_. lborel) \\<partial>lborel)\"\n  proof (intro nn_integral_cong, goal_cases)\n    case (1 y f)\n    have *: \"y \\<in> {-r..r}\" if \"y ^ 2 + c \\<le> r ^ 2\" \"c \\<ge> 0\" for c\n    proof -\n      have \"y ^ 2 \\<le> y ^ 2 + c\" using that by simp\n      also have \"\\<dots> \\<le> r ^ 2\" by fact\n      finally show ?thesis\n        using \\<open>r > 0\\<close> by (simp add: power2_le_iff_abs_le abs_if split: if_splits)\n    qed\n    have \"(\\<Sum>x\\<in>A. (if x = i then y else f x)\\<^sup>2) = (\\<Sum>x\\<in>A. (f x)\\<^sup>2)\"\n      using insert.hyps by (intro sum.cong) auto\n    thus ?case using 1 \\<open>r > 0\\<close>\n      by (auto simp: sum_nonneg real_sqrt_le_iff' indicator_def PiE_def space_PiM dest!: *)\n  qed\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * (\\<integral>\\<^sup>+ x. indicator ({f. sqrt ((\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \n                                   \\<le> sqrt (r ^ 2 - y ^ 2)} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) x\n                  \\<partial>Pi\\<^sub>M A (\\<lambda>_. lborel)) \\<partial>lborel)\" by (subst nn_integral_cmult) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * emeasure (PiM A (\\<lambda>_. lborel)) \n      ({f. sqrt ((\\<Sum>i\\<in>A. (f i)\\<^sup>2)) \\<le> sqrt (r ^ 2 - y ^ 2)} \\<inter> space (Pi\\<^sub>M A (\\<lambda>_. lborel))) \\<partial>lborel)\"\n    using \\<open>finite A\\<close> by (intro nn_integral_cong, subst nn_integral_indicator) auto\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * ennreal (unit_ball_vol (real (card A)) * \n                                  (sqrt (r ^ 2 - y ^ 2)) ^ card A) \\<partial>lborel)\"\n  proof (intro nn_integral_cong_AE, goal_cases)\n    case 1\n    have \"AE y in lborel. y \\<notin> {-r,r}\"\n      by (intro AE_not_in countable_imp_null_set_lborel) auto\n    thus ?case\n    proof eventually_elim\n      case (elim y)\n      show ?case\n      proof (cases \"y \\<in> {-r<..<r}\")\n        case True\n        hence \"y\\<^sup>2 < r\\<^sup>2\" by (subst real_sqrt_less_iff [symmetric]) auto\n        thus ?thesis by (subst insert.IH) (auto)\n      qed (insert elim, auto)\n    qed\n  qed\n  also have \"\\<dots> = ennreal (unit_ball_vol (real (card A))) * \n                    (\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * (sqrt (r ^ 2 - y ^ 2)) ^ card A \\<partial>lborel)\"\n    by (subst nn_integral_cmult [symmetric])\n       (auto simp: mult_ac ennreal_mult' [symmetric] indicator_def intro!: nn_integral_cong)\n  also have \"(\\<integral>\\<^sup>+ (y::real). indicator {-r..r} y * (sqrt (r ^ 2 - y ^ 2)) ^ card A \\<partial>lborel) =\n               (\\<integral>\\<^sup>+ (y::real). r ^ card A * indicator {-1..1} y * (sqrt (1 - y ^ 2)) ^ card A  \n               \\<partial>(distr lborel borel ((*) (1/r))))\" using \\<open>r > 0\\<close>\n    by (subst nn_integral_distr)\n       (auto simp: indicator_def field_simps real_sqrt_divide intro!: nn_integral_cong)\n  also have \"\\<dots> = (\\<integral>\\<^sup>+ x. ennreal (r ^ Suc (card A)) * \n               (indicator {- 1..1} x * sqrt (1 - x\\<^sup>2) ^ card A) \\<partial>lborel)\" using \\<open>r > 0\\<close>\n    by (subst lborel_distr_mult) (auto simp: nn_integral_density ennreal_mult' [symmetric] mult_ac)\n  also have \"\\<dots> = ennreal (r ^ Suc (card A)) * (\\<integral>\\<^sup>+ x. indicator {- 1..1} x * \n                    sqrt (1 - x\\<^sup>2) ^ card A \\<partial>lborel)\"\n    by (subst nn_integral_cmult) auto\n  also note emeasure_cball_aux_integral\n  also have \"ennreal (unit_ball_vol (real (card A))) * (ennreal (r ^ Suc (card A)) *\n                 ennreal (Beta (1/2) (card A / 2 + 1))) = \n               ennreal (unit_ball_vol (card A) * Beta (1/2) (card A / 2 + 1) * r ^ Suc (card A))\"\n    using \\<open>r > 0\\<close> by (simp add: ennreal_mult' [symmetric] mult_ac)\n  also have \"unit_ball_vol (card A) * Beta (1/2) (card A / 2 + 1) = unit_ball_vol (Suc (card A))\"\n    by (auto simp: unit_ball_vol_def Beta_def Gamma_eq_zero_iff field_simps \n          Gamma_one_half_real powr_half_sqrt [symmetric] powr_add [symmetric])\n  also have \"Suc (card A) = card (insert i A)\" using insert.hyps by simp\n  finally show ?case .\nqed\n\n\ntext \\<open>\n  We now get the main theorem very easily by just applying the above lemma.\n\\<close>\ncontext\n  fixes c :: \"'a :: euclidean_space\" and r :: real\n  assumes r: \"r \\<ge> 0\"\nbegin\n\ntheorem\\<^marker>\\<open>tag unimportant\\<close> emeasure_cball:\n  \"emeasure lborel (cball c r) = ennreal (unit_ball_vol (DIM('a)) * r ^ DIM('a))\"\nproof (cases \"r = 0\")\n  case False\n  with r have r: \"r > 0\" by simp\n  have \"(lborel :: 'a measure) = \n          distr (Pi\\<^sub>M Basis (\\<lambda>_. lborel)) borel (\\<lambda>f. \\<Sum>b\\<in>Basis. f b *\\<^sub>R b)\"\n    by (rule lborel_eq)\n  also have \"emeasure \\<dots> (cball 0 r) = \n               emeasure (Pi\\<^sub>M Basis (\\<lambda>_. lborel)) \n               ({y. dist 0 (\\<Sum>b\\<in>Basis. y b *\\<^sub>R b :: 'a) \\<le> r} \\<inter> space (Pi\\<^sub>M Basis (\\<lambda>_. lborel)))\"\n    by (subst emeasure_distr) (auto simp: cball_def)\n  also have \"{f. dist 0 (\\<Sum>b\\<in>Basis. f b *\\<^sub>R b :: 'a) \\<le> r} = {f. sqrt (\\<Sum>i\\<in>Basis. (f i)\\<^sup>2) \\<le> r}\"\n    by (subst euclidean_dist_l2) (auto simp: L2_set_def)\n  also have \"emeasure (Pi\\<^sub>M Basis (\\<lambda>_. lborel)) (\\<dots> \\<inter> space (Pi\\<^sub>M Basis (\\<lambda>_. lborel))) =\n               ennreal (unit_ball_vol (real DIM('a)) * r ^ DIM('a))\"\n    using r by (subst emeasure_cball_aux) simp_all\n  also have \"emeasure lborel (cball 0 r :: 'a set) =\n               emeasure (distr lborel borel (\\<lambda>x. c + x)) (cball c r)\"\n    by (subst emeasure_distr) (auto simp: cball_def dist_norm norm_minus_commute)\n  also have \"distr lborel borel (\\<lambda>x. c + x) = lborel\"\n    using lborel_affine[of 1 c] by (simp add: density_1)\n  finally show ?thesis .\nqed auto\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_cball:\n  \"content (cball c r) = unit_ball_vol (DIM('a)) * r ^ DIM('a)\"\n  by (simp add: measure_def emeasure_cball r)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> emeasure_ball:\n  \"emeasure lborel (ball c r) = ennreal (unit_ball_vol (DIM('a)) * r ^ DIM('a))\"\nproof -\n  from negligible_sphere[of c r] have \"sphere c r \\<in> null_sets lborel\"\n    by (auto simp: null_sets_completion_iff negligible_iff_null_sets negligible_convex_frontier)\n  hence \"emeasure lborel (ball c r \\<union> sphere c r :: 'a set) = emeasure lborel (ball c r :: 'a set)\"\n    by (intro emeasure_Un_null_set) auto\n  also have \"ball c r \\<union> sphere c r = (cball c r :: 'a set)\" by auto\n  also have \"emeasure lborel \\<dots> = ennreal (unit_ball_vol (real DIM('a)) * r ^ DIM('a))\"\n    by (rule emeasure_cball)\n  finally show ?thesis ..\nqed\n\ncorollary\\<^marker>\\<open>tag important\\<close> content_ball:\n  \"content (ball c r) = unit_ball_vol (DIM('a)) * r ^ DIM('a)\"\n  by (simp add: measure_def r emeasure_ball)\n\nend\n\n\ntext \\<open>\n  Lastly, we now prove some nicer explicit formulas for the volume of the unit balls in \n  the cases of even and odd integer dimensions.\n\\<close>\nlemma unit_ball_vol_even:\n  \"unit_ball_vol (real (2 * n)) = pi ^ n / fact n\"\n  by (simp add: unit_ball_vol_def add_ac powr_realpow Gamma_fact)\n\nlemma unit_ball_vol_odd':\n        \"unit_ball_vol (real (2 * n + 1)) = pi ^ n / pochhammer (1 / 2) (Suc n)\"\n  and unit_ball_vol_odd:\n        \"unit_ball_vol (real (2 * n + 1)) =\n           (2 ^ (2 * Suc n) * fact (Suc n)) / fact (2 * Suc n) * pi ^ n\"\nproof -\n  have \"unit_ball_vol (real (2 * n + 1)) = \n          pi powr (real n + 1 / 2) / Gamma (1 / 2 + real (Suc n))\"\n    by (simp add: unit_ball_vol_def field_simps)\n  also have \"pochhammer (1 / 2) (Suc n) = Gamma (1 / 2 + real (Suc n)) / Gamma (1 / 2)\"\n    by (intro pochhammer_Gamma) auto\n  hence \"Gamma (1 / 2 + real (Suc n)) = sqrt pi * pochhammer (1 / 2) (Suc n)\"\n    by (simp add: Gamma_one_half_real)\n  also have \"pi powr (real n + 1 / 2) / \\<dots> = pi ^ n / pochhammer (1 / 2) (Suc n)\"\n    by (simp add: powr_add powr_half_sqrt powr_realpow)\n  finally show \"unit_ball_vol (real (2 * n + 1)) = \\<dots>\" .\n  also have \"pochhammer (1 / 2 :: real) (Suc n) = \n               fact (2 * Suc n) / (2 ^ (2 * Suc n) * fact (Suc n))\"\n    using fact_double[of \"Suc n\", where ?'a = real] by (simp add: divide_simps mult_ac)\n  also have \"pi ^n / \\<dots> = (2 ^ (2 * Suc n) * fact (Suc n)) / fact (2 * Suc n) * pi ^ n\"\n    by simp\n  finally show \"unit_ball_vol (real (2 * n + 1)) = \\<dots>\" .\nqed\n\nlemma unit_ball_vol_numeral:\n  \"unit_ball_vol (numeral (Num.Bit0 n)) = pi ^ numeral n / fact (numeral n)\" (is ?th1)\n  \"unit_ball_vol (numeral (Num.Bit1 n)) = 2 ^ (2 * Suc (numeral n)) * fact (Suc (numeral n)) /\n    fact (2 * Suc (numeral n)) * pi ^ numeral n\" (is ?th2)\nproof -\n  have \"numeral (Num.Bit0 n) = (2 * numeral n :: nat)\" \n    by (simp only: numeral_Bit0 mult_2 ring_distribs)\n  also have \"unit_ball_vol \\<dots> = pi ^ numeral n / fact (numeral n)\"\n    by (rule unit_ball_vol_even)\n  finally show ?th1 by simp\nnext\n  have \"numeral (Num.Bit1 n) = (2 * numeral n + 1 :: nat)\"\n    by (simp only: numeral_Bit1 mult_2)\n  also have \"unit_ball_vol \\<dots> = 2 ^ (2 * Suc (numeral n)) * fact (Suc (numeral n)) /\n                                  fact (2 * Suc (numeral n)) * pi ^ numeral n\"\n    by (rule unit_ball_vol_odd)\n  finally show ?th2 by simp\nqed\n\nlemmas eval_unit_ball_vol = unit_ball_vol_numeral fact_numeral\n\n\ntext \\<open>\n  Just for fun, we compute the volume of unit balls for a few dimensions.\n\\<close>\nlemma unit_ball_vol_0 [simp]: \"unit_ball_vol 0 = 1\"\n  using unit_ball_vol_even[of 0] by simp\n\nlemma unit_ball_vol_1 [simp]: \"unit_ball_vol 1 = 2\"\n  using unit_ball_vol_odd[of 0] by simp\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close>\n          unit_ball_vol_2: \"unit_ball_vol 2 = pi\"\n      and unit_ball_vol_3: \"unit_ball_vol 3 = 4 / 3 * pi\"\n      and unit_ball_vol_4: \"unit_ball_vol 4 = pi\\<^sup>2 / 2\"\n      and unit_ball_vol_5: \"unit_ball_vol 5 = 8 / 15 * pi\\<^sup>2\"\n  by (simp_all add: eval_unit_ball_vol)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> circle_area:\n  \"r \\<ge> 0 \\<Longrightarrow> content (ball c r :: (real ^ 2) set) = r ^ 2 * pi\"\n  by (simp add: content_ball unit_ball_vol_2)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> sphere_volume:\n  \"r \\<ge> 0 \\<Longrightarrow> content (ball c r :: (real ^ 3) set) = 4 / 3 * r ^ 3 * pi\"\n  by (simp add: content_ball unit_ball_vol_3)\n\ntext \\<open>\n  Useful equivalent forms\n\\<close>\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_ball_eq_0_iff [simp]: \"content (ball c r) = 0 \\<longleftrightarrow> r \\<le> 0\"\nproof -\n  have \"r > 0 \\<Longrightarrow> content (ball c r) > 0\"\n    by (simp add: content_ball unit_ball_vol_def)\n  then show ?thesis\n    by (fastforce simp: ball_empty)\nqed\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_ball_gt_0_iff [simp]: \"0 < content (ball z r) \\<longleftrightarrow> 0 < r\"\n  by (auto simp: zero_less_measure_iff)\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_cball_eq_0_iff [simp]: \"content (cball c r) = 0 \\<longleftrightarrow> r \\<le> 0\"\nproof (cases \"r = 0\")\n  case False\n  moreover have \"r > 0 \\<Longrightarrow> content (cball c r) > 0\"\n    by (simp add: content_cball unit_ball_vol_def)\n  ultimately show ?thesis\n    by fastforce\nqed auto\n\ncorollary\\<^marker>\\<open>tag unimportant\\<close> content_cball_gt_0_iff [simp]: \"0 < content (cball z r) \\<longleftrightarrow> 0 < r\"\n  by (auto simp: zero_less_measure_iff)\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Analysis/Ball_Volume.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427857178614, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7634978331677924}}
{"text": "(*  Title:      HOL/SMT_Examples/SMT_Tests.thy\n    Author:     Sascha Boehme, TU Muenchen\n    Author:     Mathias Fleury, MPII, JKU\n*)\n\nsection \\<open>Tests for the SMT binding\\<close>\n\ntheory SMT_Tests_Verit\nimports Complex_Main\nbegin\n\ndeclare [[smt_solver=verit]]\nsmt_status\n\ntext \\<open>Most examples are taken from the equivalent Z3 theory called \\<^file>\\<open>SMT_Tests.thy\\<close>,\nand have been taken from various Isabelle and HOL4 developments.\\<close>\n\n\nsection \\<open>Propositional logic\\<close>\n\nlemma\n  \"True\"\n  \"\\<not> False\"\n  \"\\<not> \\<not> True\"\n  \"True \\<and> True\"\n  \"True \\<or> False\"\n  \"False \\<longrightarrow> True\"\n  \"\\<not> (False \\<longleftrightarrow> True)\"\n  by smt+\n\nlemma\n  \"P \\<or> \\<not> P\"\n  \"\\<not> (P \\<and> \\<not> P)\"\n  \"(True \\<and> P) \\<or> \\<not> P \\<or> (False \\<and> P) \\<or> P\"\n  \"P \\<longrightarrow> P\"\n  \"P \\<and> \\<not> P \\<longrightarrow> False\"\n  \"P \\<and> Q \\<longrightarrow> Q \\<and> P\"\n  \"P \\<or> Q \\<longrightarrow> Q \\<or> P\"\n  \"P \\<and> Q \\<longrightarrow> P \\<or> Q\"\n  \"\\<not> (P \\<or> Q) \\<longrightarrow> \\<not> P\"\n  \"\\<not> (P \\<or> Q) \\<longrightarrow> \\<not> Q\"\n  \"\\<not> P \\<longrightarrow> \\<not> (P \\<and> Q)\"\n  \"\\<not> Q \\<longrightarrow> \\<not> (P \\<and> Q)\"\n  \"(P \\<and> Q) \\<longleftrightarrow> (\\<not> (\\<not> P \\<or> \\<not> Q))\"\n  \"(P \\<and> Q) \\<and> R \\<longrightarrow> P \\<and> (Q \\<and> R)\"\n  \"(P \\<or> Q) \\<or> R \\<longrightarrow> P \\<or> (Q \\<or> R)\"\n  \"(P \\<and> Q) \\<or> R  \\<longrightarrow> (P \\<or> R) \\<and> (Q \\<or> R)\"\n  \"(P \\<or> R) \\<and> (Q \\<or> R) \\<longrightarrow> (P \\<and> Q) \\<or> R\"\n  \"(P \\<or> Q) \\<and> R \\<longrightarrow> (P \\<and> R) \\<or> (Q \\<and> R)\"\n  \"(P \\<and> R) \\<or> (Q \\<and> R) \\<longrightarrow> (P \\<or> Q) \\<and> R\"\n  \"((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P\"\n  \"(P \\<longrightarrow> R) \\<and> (Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<or> Q \\<longrightarrow> R)\"\n  \"(P \\<and> Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<longrightarrow> (Q \\<longrightarrow> R))\"\n  \"((P \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow>  ((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> (P \\<and> Q \\<longrightarrow> R) \\<longrightarrow> R\"\n  \"\\<not> (P \\<longrightarrow> R) \\<longrightarrow>  \\<not> (Q \\<longrightarrow> R) \\<longrightarrow> \\<not> (P \\<and> Q \\<longrightarrow> R)\"\n  \"(P \\<longrightarrow> Q \\<and> R) \\<longleftrightarrow> (P \\<longrightarrow> Q) \\<and> (P \\<longrightarrow> R)\"\n  \"P \\<longrightarrow> (Q \\<longrightarrow> P)\"\n  \"(P \\<longrightarrow> Q \\<longrightarrow> R) \\<longrightarrow> (P \\<longrightarrow> Q)\\<longrightarrow> (P \\<longrightarrow> R)\"\n  \"(P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R) \\<longrightarrow> (P \\<longrightarrow> Q \\<or> R)\"\n  \"((((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P) \\<longrightarrow> Q) \\<longrightarrow> Q\"\n  \"(P \\<longrightarrow> Q) \\<longrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\"\n  \"(P \\<longrightarrow> Q \\<or> R) \\<longrightarrow> (P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R)\"\n  \"(P \\<longrightarrow> Q) \\<and> (Q  \\<longrightarrow> P) \\<longrightarrow> (P \\<longleftrightarrow> Q)\"\n  \"(P \\<longleftrightarrow> Q) \\<longleftrightarrow> (Q \\<longleftrightarrow> P)\"\n  \"\\<not> (P \\<longleftrightarrow> \\<not> P)\"\n  \"(P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\"\n  \"P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P \\<longleftrightarrow> P\"\n  by smt+\n\nlemma\n  \"(if P then Q1 else Q2) \\<longleftrightarrow> ((P \\<longrightarrow> Q1) \\<and> (\\<not> P \\<longrightarrow> Q2))\"\n  \"if P then (Q \\<longrightarrow> P) else (P \\<longrightarrow> Q)\"\n  \"(if P1 \\<or> P2 then Q1 else Q2) \\<longleftrightarrow> (if P1 then Q1 else if P2 then Q1 else Q2)\"\n  \"(if P1 \\<and> P2 then Q1 else Q2) \\<longleftrightarrow> (if P1 then if P2 then Q1 else Q2 else Q2)\"\n  \"(P1 \\<longrightarrow> (if P2 then Q1 else Q2)) \\<longleftrightarrow>\n   (if P1 \\<longrightarrow> P2 then P1 \\<longrightarrow> Q1 else P1 \\<longrightarrow> Q2)\"\n  by smt+\n\nlemma\n  \"case P of True \\<Rightarrow> P | False \\<Rightarrow> \\<not> P\"\n  \"case P of False \\<Rightarrow> \\<not> P | True \\<Rightarrow> P\"\n  \"case \\<not> P of True \\<Rightarrow> \\<not> P | False \\<Rightarrow> P\"\n  \"case P of True \\<Rightarrow> (Q \\<longrightarrow> P) | False \\<Rightarrow> (P \\<longrightarrow> Q)\"\n  by smt+\n\n\nsection \\<open>First-order logic with equality\\<close>\n\nlemma\n  \"x = x\"\n  \"x = y \\<longrightarrow> y = x\"\n  \"x = y \\<and> y = z \\<longrightarrow> x = z\"\n  \"x = y \\<longrightarrow> f x = f y\"\n  \"x = y \\<longrightarrow> g x y = g y x\"\n  \"f (f x) = x \\<and> f (f (f (f (f x)))) = x \\<longrightarrow> f x = x\"\n  \"((if a then b else c) = d) = ((a \\<longrightarrow> (b = d)) \\<and> (\\<not> a \\<longrightarrow> (c = d)))\"\n  by smt+\n\nlemma\n  \"\\<forall>x. x = x\"\n  \"(\\<forall>x. P x) \\<longleftrightarrow> (\\<forall>y. P y)\"\n  \"\\<forall>x. P x \\<longrightarrow> (\\<forall>y. P x \\<or> P y)\"\n  \"(\\<forall>x. P x \\<and> Q x) \\<longleftrightarrow> (\\<forall>x. P x) \\<and> (\\<forall>x. Q x)\"\n  \"(\\<forall>x. P x) \\<or> R \\<longleftrightarrow> (\\<forall>x. P x \\<or> R)\"\n  \"(\\<forall>x y z. S x z) \\<longleftrightarrow> (\\<forall>x z. S x z)\"\n  \"(\\<forall>x y. S x y \\<longrightarrow> S y x) \\<longrightarrow> (\\<forall>x. S x y) \\<longrightarrow> S y x\"\n  \"(\\<forall>x. P x \\<longrightarrow> P (f x)) \\<and> P d \\<longrightarrow> P (f(f(f(d))))\"\n  \"(\\<forall>x y. s x y = s y x) \\<longrightarrow> a = a \\<and> s a b = s b a\"\n  \"(\\<forall>s. q s \\<longrightarrow> r s) \\<and> \\<not> r s \\<and> (\\<forall>s. \\<not> r s \\<and> \\<not> q s \\<longrightarrow> p t \\<or> q t) \\<longrightarrow> p t \\<or> r t\"\n  by smt+\n\nlemma\n  \"(\\<forall>x. P x) \\<and> R \\<longleftrightarrow> (\\<forall>x. P x \\<and> R)\"\n  by smt\n\nlemma\n  \"\\<exists>x. x = x\"\n  \"(\\<exists>x. P x) \\<longleftrightarrow> (\\<exists>y. P y)\"\n  \"(\\<exists>x. P x \\<or> Q x) \\<longleftrightarrow> (\\<exists>x. P x) \\<or> (\\<exists>x. Q x)\"\n  \"(\\<exists>x. P x) \\<and> R \\<longleftrightarrow> (\\<exists>x. P x \\<and> R)\"\n  \"(\\<exists>x y z. S x z) \\<longleftrightarrow> (\\<exists>x z. S x z)\"\n  \"\\<not> ((\\<exists>x. \\<not> P x) \\<and> ((\\<exists>x. P x) \\<or> (\\<exists>x. P x \\<and> Q x)) \\<and> \\<not> (\\<exists>x. P x))\"\n  by smt+\n\nlemma\n  \"\\<exists>x y. x = y\"\n  \"(\\<exists>x. P x) \\<or> R \\<longleftrightarrow> (\\<exists>x. P x \\<or> R)\"\n  \"\\<exists>x. P x \\<longrightarrow> P a \\<and> P b\"\n  \"(\\<exists>x. Q \\<longrightarrow> P x) \\<longleftrightarrow> (Q \\<longrightarrow> (\\<exists>x. P x))\"\n  by smt+\n\nlemma\n  \"(P False \\<or> P True) \\<or> \\<not> P False\"\n  by smt\n\nlemma\n  \"(\\<not> (\\<exists>x. P x)) \\<longleftrightarrow> (\\<forall>x. \\<not> P x)\"\n  \"(\\<exists>x. P x \\<longrightarrow> Q) \\<longleftrightarrow> (\\<forall>x. P x) \\<longrightarrow> Q\"\n  \"(\\<forall>x y. R x y = x) \\<longrightarrow> (\\<exists>y. R x y) = R x c\"\n  \"(if P x then \\<not> (\\<exists>y. P y) else (\\<forall>y. \\<not> P y)) \\<longrightarrow> P x \\<longrightarrow> P y\"\n  \"(\\<forall>x y. R x y = x) \\<and> (\\<forall>x. \\<exists>y. R x y) = (\\<forall>x. R x c) \\<longrightarrow> (\\<exists>y. R x y) = R x c\"\n  by smt+\n\nlemma\n  \"\\<forall>x. \\<exists>y. f x y = f x (g x)\"\n  \"(\\<not> \\<not> (\\<exists>x. P x)) \\<longleftrightarrow> (\\<not> (\\<forall>x. \\<not> P x))\"\n  \"\\<forall>u. \\<exists>v. \\<forall>w. \\<exists>x. f u v w x = f u (g u) w (h u w)\"\n  \"\\<exists>x. if x = y then (\\<forall>y. y = x \\<or> y \\<noteq> x) else (\\<forall>y. y = (x, x) \\<or> y \\<noteq> (x, x))\"\n  \"\\<exists>x. if x = y then (\\<exists>y. y = x \\<or> y \\<noteq> x) else (\\<exists>y. y = (x, x) \\<or> y \\<noteq> (x, x))\"\n  \"(\\<exists>x. \\<forall>y. P x \\<longleftrightarrow> P y) \\<longrightarrow> ((\\<exists>x. P x) \\<longleftrightarrow> (\\<forall>y. P y))\"\n  \"(\\<exists>y. \\<forall>x. R x y) \\<longrightarrow> (\\<forall>x. \\<exists>y. R x y)\"\n  by smt+\n\nlemma\n  \"(\\<exists>!x. P x) \\<longrightarrow> (\\<exists>x. P x)\"\n  \"(\\<exists>!x. P x) \\<longleftrightarrow> (\\<exists>x. P x \\<and> (\\<forall>y. y \\<noteq> x \\<longrightarrow> \\<not> P y))\"\n  \"P a \\<longrightarrow> (\\<forall>x. P x \\<longrightarrow> x = a) \\<longrightarrow> (\\<exists>!x. P x)\"\n  \"(\\<exists>x. P x) \\<and> (\\<forall>x y. P x \\<and> P y \\<longrightarrow> x = y) \\<longrightarrow> (\\<exists>!x. P x)\"\n  \"(\\<exists>!x. P x) \\<and> (\\<forall>x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> y = x) \\<longrightarrow> R) \\<longrightarrow> R\"\n  by smt+\n\nlemma\n  \"(\\<forall>x\\<in>M. P x) \\<and> c \\<in> M \\<longrightarrow> P c\"\n  \"(\\<exists>x\\<in>M. P x) \\<or> \\<not> (P c \\<and> c \\<in> M)\"\n  by smt+\n\nlemma\n  \"let P = True in P\"\n  \"let P = P1 \\<or> P2 in P \\<or> \\<not> P\"\n  \"let P1 = True; P2 = False in P1 \\<and> P2 \\<longrightarrow> P2 \\<or> P1\"\n  \"(let x = y in x) = y\"\n  \"(let x = y in Q x) \\<longleftrightarrow> (let z = y in Q z)\"\n  \"(let x = y1; z = y2 in R x z) \\<longleftrightarrow> (let z = y2; x = y1 in R x z)\"\n  \"(let x = y1; z = y2 in R x z) \\<longleftrightarrow> (let z = y1; x = y2 in R z x)\"\n  \"let P = (\\<forall>x. Q x) in if P then P else \\<not> P\"\n  by smt+\n\nlemma\n  \"a \\<noteq> b \\<and> a \\<noteq> c \\<and> b \\<noteq> c \\<and> (\\<forall>x y. f x = f y \\<longrightarrow> y = x) \\<longrightarrow> f a \\<noteq> f b\"\n  by smt\n\nlemma\n  \"(\\<forall>x y z. f x y = f x z \\<longrightarrow> y = z) \\<and> b \\<noteq> c \\<longrightarrow> f a b \\<noteq> f a c\"\n  \"(\\<forall>x y z. f x y = f z y \\<longrightarrow> x = z) \\<and> a \\<noteq> d \\<longrightarrow> f a b \\<noteq> f d b\"\n  by smt+\n\n\nsection \\<open>Guidance for quantifier heuristics: patterns\\<close>\n\nlemma\n  assumes \"\\<forall>x.\n    SMT.trigger (SMT.Symb_Cons (SMT.Symb_Cons (SMT.pat (f x)) SMT.Symb_Nil) SMT.Symb_Nil)\n    (f x = x)\"\n  shows \"f 1 = 1\"\n  using assms by smt\n\nlemma\n  assumes \"\\<forall>x y.\n    SMT.trigger (SMT.Symb_Cons (SMT.Symb_Cons (SMT.pat (f x))\n      (SMT.Symb_Cons (SMT.pat (g y)) SMT.Symb_Nil)) SMT.Symb_Nil) (f x = g y)\"\n  shows \"f a = g b\"\n  using assms by smt\n\n\nsection \\<open>Meta-logical connectives\\<close>\n\nlemma\n  \"True \\<Longrightarrow> True\"\n  \"False \\<Longrightarrow> True\"\n  \"False \\<Longrightarrow> False\"\n  \"P' x \\<Longrightarrow> P' x\"\n  \"P \\<Longrightarrow> P \\<or> Q\"\n  \"Q \\<Longrightarrow> P \\<or> Q\"\n  \"\\<not> P \\<Longrightarrow> P \\<longrightarrow> Q\"\n  \"Q \\<Longrightarrow> P \\<longrightarrow> Q\"\n  \"\\<lbrakk>P; \\<not> Q\\<rbrakk> \\<Longrightarrow> \\<not> (P \\<longrightarrow> Q)\"\n  \"P' x \\<equiv> P' x\"\n  \"P' x \\<equiv> Q' x \\<Longrightarrow> P' x = Q' x\"\n  \"P' x = Q' x \\<Longrightarrow> P' x \\<equiv> Q' x\"\n  \"x \\<equiv> y \\<Longrightarrow> y \\<equiv> z \\<Longrightarrow> x \\<equiv> (z::'a::type)\"\n  \"x \\<equiv> y \\<Longrightarrow> (f x :: 'b::type) \\<equiv> f y\"\n  \"(\\<And>x. g x) \\<Longrightarrow> g a \\<or> a\"\n  \"(\\<And>x y. h x y \\<and> h y x) \\<Longrightarrow> \\<forall>x. h x x\"\n  \"(p \\<or> q) \\<and> \\<not> p \\<Longrightarrow> q\"\n  \"(a \\<and> b) \\<or> (c \\<and> d) \\<Longrightarrow> (a \\<and> b) \\<or> (c \\<and> d)\"\n  by smt+\n\n\nsection \\<open>Natural numbers\\<close>\n\ndeclare [[smt_nat_as_int]]\n\nlemma\n  \"(0::nat) = 0\"\n  \"(1::nat) = 1\"\n  \"(0::nat) < 1\"\n  \"(0::nat) \\<le> 1\"\n  \"(123456789::nat) < 2345678901\"\n  by smt+\n\nlemma\n  \"Suc 0 = 1\"\n  \"Suc x = x + 1\"\n  \"x < Suc x\"\n  \"(Suc x = Suc y) = (x = y)\"\n  \"Suc (x + y) < Suc x + Suc y\"\n  by smt+\n\nlemma\n  \"(x::nat) + 0 = x\"\n  \"0 + x = x\"\n  \"x + y = y + x\"\n  \"x + (y + z) = (x + y) + z\"\n  \"(x + y = 0) = (x = 0 \\<and> y = 0)\"\n  by smt+\n\nlemma\n  \"(x::nat) - 0 = x\"\n  \"x < y \\<longrightarrow> x - y = 0\"\n  \"x - y = 0 \\<or> y - x = 0\"\n  \"(x - y) + y = (if x < y then y else x)\"\n   \"x - y - z = x - (y + z)\"\n  by smt+\n\nlemma\n  \"(x::nat) * 0 = 0\"\n  \"0 * x = 0\"\n  \"x * 1 = x\"\n  \"1 * x = x\"\n  \"3 * x = x * 3\"\n  by smt+\n\nlemma\n  \"min (x::nat) y \\<le> x\"\n  \"min x y \\<le> y\"\n  \"min x y \\<le> x + y\"\n  \"z < x \\<and> z < y \\<longrightarrow> z < min x y\"\n  \"min x y = min y x\"\n  \"min x 0 = 0\"\n  by smt+\n\nlemma\n  \"max (x::nat) y \\<ge> x\"\n  \"max x y \\<ge> y\"\n  \"max x y \\<ge> (x - y) + (y - x)\"\n  \"z > x \\<and> z > y \\<longrightarrow> z > max x y\"\n  \"max x y = max y x\"\n  \"max x 0 = x\"\n  by smt+\n\nlemma\n  \"0 \\<le> (x::nat)\"\n  \"0 < x \\<and> x \\<le> 1 \\<longrightarrow> x = 1\"\n  \"x \\<le> x\"\n  \"x \\<le> y \\<longrightarrow> 3 * x \\<le> 3 * y\"\n  \"x < y \\<longrightarrow> 3 * x < 3 * y\"\n  \"x < y \\<longrightarrow> x \\<le> y\"\n  \"(x < y) = (x + 1 \\<le> y)\"\n  \"\\<not> (x < x)\"\n  \"x \\<le> y \\<longrightarrow> y \\<le> z \\<longrightarrow> x \\<le> z\"\n  \"x < y \\<longrightarrow> y \\<le> z \\<longrightarrow> x \\<le> z\"\n  \"x \\<le> y \\<longrightarrow> y < z \\<longrightarrow> x \\<le> z\"\n  \"x < y \\<longrightarrow> y < z \\<longrightarrow> x < z\"\n  \"x < y \\<and> y < z \\<longrightarrow> \\<not> (z < x)\"\n  by smt+\n\ndeclare [[smt_nat_as_int = false]]\n\n\nsection \\<open>Integers\\<close>\n\nlemma\n  \"(0::int) = 0\"\n  \"(0::int) = (- 0)\"\n  \"(1::int) = 1\"\n  \"\\<not> (-1 = (1::int))\"\n  \"(0::int) < 1\"\n  \"(0::int) \\<le> 1\"\n  \"-123 + 345 < (567::int)\"\n  \"(123456789::int) < 2345678901\"\n  \"(-123456789::int) < 2345678901\"\n  by smt+\n\nlemma\n  \"(x::int) + 0 = x\"\n  \"0 + x = x\"\n  \"x + y = y + x\"\n  \"x + (y + z) = (x + y) + z\"\n  \"(x + y = 0) = (x = -y)\"\n  by smt+\n\nlemma\n  \"(-1::int) = - 1\"\n  \"(-3::int) = - 3\"\n  \"-(x::int) < 0 \\<longleftrightarrow> x > 0\"\n  \"x > 0 \\<longrightarrow> -x < 0\"\n  \"x < 0 \\<longrightarrow> -x > 0\"\n  by smt+\n\nlemma\n  \"(x::int) - 0 = x\"\n  \"0 - x = -x\"\n  \"x < y \\<longrightarrow> x - y < 0\"\n  \"x - y = -(y - x)\"\n  \"x - y = -y + x\"\n  \"x - y - z = x - (y + z)\"\n  by smt+\n\nlemma\n  \"(x::int) * 0 = 0\"\n  \"0 * x = 0\"\n  \"x * 1 = x\"\n  \"1 * x = x\"\n  \"x * -1 = -x\"\n  \"-1 * x = -x\"\n  \"3 * x = x * 3\"\n  by smt+\n\nlemma\n  \"\\<bar>x::int\\<bar> \\<ge> 0\"\n  \"(\\<bar>x\\<bar> = 0) = (x = 0)\"\n  \"(x \\<ge> 0) = (\\<bar>x\\<bar> = x)\"\n  \"(x \\<le> 0) = (\\<bar>x\\<bar> = -x)\"\n  \"\\<bar>\\<bar>x\\<bar>\\<bar> = \\<bar>x\\<bar>\"\n  by smt+\n\nlemma\n  \"min (x::int) y \\<le> x\"\n  \"min x y \\<le> y\"\n  \"z < x \\<and> z < y \\<longrightarrow> z < min x y\"\n  \"min x y = min y x\"\n  \"x \\<ge> 0 \\<longrightarrow> min x 0 = 0\"\n  \"min x y \\<le> \\<bar>x + y\\<bar>\"\n  by smt+\n\nlemma\n  \"max (x::int) y \\<ge> x\"\n  \"max x y \\<ge> y\"\n  \"z > x \\<and> z > y \\<longrightarrow> z > max x y\"\n  \"max x y = max y x\"\n  \"x \\<ge> 0 \\<longrightarrow> max x 0 = x\"\n  \"max x y \\<ge> - \\<bar>x\\<bar> - \\<bar>y\\<bar>\"\n  by smt+\n\nlemma\n  \"0 < (x::int) \\<and> x \\<le> 1 \\<longrightarrow> x = 1\"\n  \"x \\<le> x\"\n  \"x \\<le> y \\<longrightarrow> 3 * x \\<le> 3 * y\"\n  \"x < y \\<longrightarrow> 3 * x < 3 * y\"\n  \"x < y \\<longrightarrow> x \\<le> y\"\n  \"(x < y) = (x + 1 \\<le> y)\"\n  \"\\<not> (x < x)\"\n  \"x \\<le> y \\<longrightarrow> y \\<le> z \\<longrightarrow> x \\<le> z\"\n  \"x < y \\<longrightarrow> y \\<le> z \\<longrightarrow> x \\<le> z\"\n  \"x \\<le> y \\<longrightarrow> y < z \\<longrightarrow> x \\<le> z\"\n  \"x < y \\<longrightarrow> y < z \\<longrightarrow> x < z\"\n  \"x < y \\<and> y < z \\<longrightarrow> \\<not> (z < x)\"\n  by smt+\n\n\nsection \\<open>Reals\\<close>\n\nlemma\n  \"(0::real) = 0\"\n  \"(0::real) = -0\"\n  \"(0::real) = (- 0)\"\n  \"(1::real) = 1\"\n  \"\\<not> (-1 = (1::real))\"\n  \"(0::real) < 1\"\n  \"(0::real) \\<le> 1\"\n  \"-123 + 345 < (567::real)\"\n  \"(123456789::real) < 2345678901\"\n  \"(-123456789::real) < 2345678901\"\n  by smt+\n\nlemma\n  \"(x::real) + 0 = x\"\n  \"0 + x = x\"\n  \"x + y = y + x\"\n  \"x + (y + z) = (x + y) + z\"\n  \"(x + y = 0) = (x = -y)\"\n  by smt+\n\nlemma\n  \"(-1::real) = - 1\"\n  \"(-3::real) = - 3\"\n  \"-(x::real) < 0 \\<longleftrightarrow> x > 0\"\n  \"x > 0 \\<longrightarrow> -x < 0\"\n  \"x < 0 \\<longrightarrow> -x > 0\"\n  by smt+\n\nlemma\n  \"(x::real) - 0 = x\"\n  \"0 - x = -x\"\n  \"x < y \\<longrightarrow> x - y < 0\"\n  \"x - y = -(y - x)\"\n  \"x - y = -y + x\"\n  \"x - y - z = x - (y + z)\"\n  by smt+\n\nlemma\n  \"(x::real) * 0 = 0\"\n  \"0 * x = 0\"\n  \"x * 1 = x\"\n  \"1 * x = x\"\n  \"x * -1 = -x\"\n  \"-1 * x = -x\"\n  \"3 * x = x * 3\"\n  by smt+\n\nlemma\n  \"\\<bar>x::real\\<bar> \\<ge> 0\"\n  \"(\\<bar>x\\<bar> = 0) = (x = 0)\"\n  \"(x \\<ge> 0) = (\\<bar>x\\<bar> = x)\"\n  \"(x \\<le> 0) = (\\<bar>x\\<bar> = -x)\"\n  \"\\<bar>\\<bar>x\\<bar>\\<bar> = \\<bar>x\\<bar>\"\n  by smt+\n\nlemma\n  \"min (x::real) y \\<le> x\"\n  \"min x y \\<le> y\"\n  \"z < x \\<and> z < y \\<longrightarrow> z < min x y\"\n  \"min x y = min y x\"\n  \"x \\<ge> 0 \\<longrightarrow> min x 0 = 0\"\n  \"min x y \\<le> \\<bar>x + y\\<bar>\"\n  by smt+\n\nlemma\n  \"max (x::real) y \\<ge> x\"\n  \"max x y \\<ge> y\"\n  \"z > x \\<and> z > y \\<longrightarrow> z > max x y\"\n  \"max x y = max y x\"\n  \"x \\<ge> 0 \\<longrightarrow> max x 0 = x\"\n  \"max x y \\<ge> - \\<bar>x\\<bar> - \\<bar>y\\<bar>\"\n  by smt+\n\nlemma\n  \"x \\<le> (x::real)\"\n  \"x \\<le> y \\<longrightarrow> 3 * x \\<le> 3 * y\"\n  \"x < y \\<longrightarrow> 3 * x < 3 * y\"\n  \"x < y \\<longrightarrow> x \\<le> y\"\n  \"\\<not> (x < x)\"\n  \"x \\<le> y \\<longrightarrow> y \\<le> z \\<longrightarrow> x \\<le> z\"\n  \"x < y \\<longrightarrow> y \\<le> z \\<longrightarrow> x \\<le> z\"\n  \"x \\<le> y \\<longrightarrow> y < z \\<longrightarrow> x \\<le> z\"\n  \"x < y \\<longrightarrow> y < z \\<longrightarrow> x < z\"\n  \"x < y \\<and> y < z \\<longrightarrow> \\<not> (z < x)\"\n  by smt+\n\n\nsection \\<open>Datatypes, records, and typedefs\\<close>\n\nsubsection \\<open>Without support by the SMT solver\\<close>\n\nsubsubsection \\<open>Algebraic datatypes\\<close>\n\nlemma\n  \"x = fst (x, y)\"\n  \"y = snd (x, y)\"\n  \"((x, y) = (y, x)) = (x = y)\"\n  \"((x, y) = (u, v)) = (x = u \\<and> y = v)\"\n  \"(fst (x, y, z) = fst (u, v, w)) = (x = u)\"\n  \"(snd (x, y, z) = snd (u, v, w)) = (y = v \\<and> z = w)\"\n  \"(fst (snd (x, y, z)) = fst (snd (u, v, w))) = (y = v)\"\n  \"(snd (snd (x, y, z)) = snd (snd (u, v, w))) = (z = w)\"\n  \"(fst (x, y) = snd (x, y)) = (x = y)\"\n  \"p1 = (x, y) \\<and> p2 = (y, x) \\<longrightarrow> fst p1 = snd p2\"\n  \"(fst (x, y) = snd (x, y)) = (x = y)\"\n  \"(fst p = snd p) = (p = (snd p, fst p))\"\n  using fst_conv snd_conv prod.collapse\n  by smt+\n\nlemma\n  \"[x] \\<noteq> Nil\"\n  \"[x, y] \\<noteq> Nil\"\n  \"x \\<noteq> y \\<longrightarrow> [x] \\<noteq> [y]\"\n  \"hd (x # xs) = x\"\n  \"tl (x # xs) = xs\"\n  \"hd [x, y, z] = x\"\n  \"tl [x, y, z] = [y, z]\"\n  \"hd (tl [x, y, z]) = y\"\n  \"tl (tl [x, y, z]) = [z]\"\n  using list.sel(1,3) list.simps\n  by smt+\n\nlemma\n  \"fst (hd [(a, b)]) = a\"\n  \"snd (hd [(a, b)]) = b\"\n  using fst_conv snd_conv prod.collapse list.sel(1,3) list.simps\n  by smt+\n\n\nsubsubsection \\<open>Records\\<close>\n\nrecord point =\n  cx :: int\n  cy :: int\n\nrecord bw_point = point +\n  black :: bool\n\nlemma\n  \"\\<lparr>cx = x, cy = y\\<rparr> = \\<lparr>cx = x', cy = y'\\<rparr> \\<Longrightarrow> x = x' \\<and> y = y'\"\n  using point.simps\n  by smt\n\nlemma\n  \"cx \\<lparr> cx = 3, cy = 4 \\<rparr> = 3\"\n  \"cy \\<lparr> cx = 3, cy = 4 \\<rparr> = 4\"\n  \"cx \\<lparr> cx = 3, cy = 4 \\<rparr> \\<noteq> cy \\<lparr> cx = 3, cy = 4 \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4 \\<rparr> \\<lparr> cx := 5 \\<rparr> = \\<lparr> cx = 5, cy = 4 \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4 \\<rparr> \\<lparr> cy := 6 \\<rparr> = \\<lparr> cx = 3, cy = 6 \\<rparr>\"\n  \"p = \\<lparr> cx = 3, cy = 4 \\<rparr> \\<longrightarrow> p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p\"\n  \"p = \\<lparr> cx = 3, cy = 4 \\<rparr> \\<longrightarrow> p \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr> = p\"\n  using point.simps\n  by smt+\n\nlemma\n  \"\\<lparr>cx = x, cy = y, black = b\\<rparr> = \\<lparr>cx = x', cy = y', black = b'\\<rparr> \\<Longrightarrow> x = x' \\<and> y = y' \\<and> b = b'\"\n  using point.simps bw_point.simps\n  by smt\n\nlemma\n  \"cx \\<lparr> cx = 3, cy = 4, black = b \\<rparr> = 3\"\n  \"cy \\<lparr> cx = 3, cy = 4, black = b \\<rparr> = 4\"\n  \"black \\<lparr> cx = 3, cy = 4, black = b \\<rparr> = b\"\n  \"cx \\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<noteq> cy \\<lparr> cx = 3, cy = 4, black = b \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<lparr> cx := 5 \\<rparr> = \\<lparr> cx = 5, cy = 4, black = b \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<lparr> cy := 6 \\<rparr> = \\<lparr> cx = 3, cy = 6, black = b \\<rparr>\"\n  \"p = \\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<longrightarrow>\n     p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> \\<lparr> black := True \\<rparr> = p\"\n  \"p = \\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<longrightarrow>\n     p \\<lparr> cy := 4 \\<rparr> \\<lparr> black := True \\<rparr> \\<lparr> cx := 3 \\<rparr> = p\"\n  \"p = \\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<longrightarrow>\n     p \\<lparr> black := True \\<rparr> \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p\"\n  using point.simps bw_point.simps\n  by smt+\n\nlemma\n  \"\\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<lparr> black := w \\<rparr> = \\<lparr> cx = 3, cy = 4, black = w \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<lparr> black := False \\<rparr> =\n     \\<lparr> cx = 3, cy = 4, black = False \\<rparr>\"\n  \"p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> \\<lparr> black := True \\<rparr> =\n     p \\<lparr> black := True \\<rparr> \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr>\"\n    apply (smt add_One add_inc bw_point.update_convs(1) default_unit_def inc.simps(2) one_plus_BitM\n      semiring_norm(6,26))\n   apply (smt bw_point.update_convs(1))\n  apply (smt bw_point.cases_scheme bw_point.update_convs(1) point.update_convs(1,2))\n  done\n\n\nsubsubsection \\<open>Type definitions\\<close>\n\ntypedef int' = \"UNIV::int set\" by (rule UNIV_witness)\n\ndefinition n0 where \"n0 = Abs_int' 0\"\ndefinition n1 where \"n1 = Abs_int' 1\"\ndefinition n2 where \"n2 = Abs_int' 2\"\ndefinition plus' where \"plus' n m = Abs_int' (Rep_int' n + Rep_int' m)\"\n\nlemma\n  \"n0 \\<noteq> n1\"\n  \"plus' n1 n1 = n2\"\n  \"plus' n0 n2 = n2\"\n  by (smt n0_def n1_def n2_def plus'_def Abs_int'_inverse Rep_int'_inverse UNIV_I)+\n\n\nsubsection \\<open>With support by the SMT solver (but without proofs)\\<close>\n\nsubsubsection \\<open>Algebraic datatypes\\<close>\n\nlemma\n  \"x = fst (x, y)\"\n  \"y = snd (x, y)\"\n  \"((x, y) = (y, x)) = (x = y)\"\n  \"((x, y) = (u, v)) = (x = u \\<and> y = v)\"\n  \"(fst (x, y, z) = fst (u, v, w)) = (x = u)\"\n  \"(snd (x, y, z) = snd (u, v, w)) = (y = v \\<and> z = w)\"\n  \"(fst (snd (x, y, z)) = fst (snd (u, v, w))) = (y = v)\"\n  \"(snd (snd (x, y, z)) = snd (snd (u, v, w))) = (z = w)\"\n  \"(fst (x, y) = snd (x, y)) = (x = y)\"\n  \"p1 = (x, y) \\<and> p2 = (y, x) \\<longrightarrow> fst p1 = snd p2\"\n  \"(fst (x, y) = snd (x, y)) = (x = y)\"\n  \"(fst p = snd p) = (p = (snd p, fst p))\"\n  using fst_conv snd_conv prod.collapse\n  by smt+\n\nlemma\n  \"x \\<noteq> y \\<longrightarrow> [x] \\<noteq> [y]\"\n  \"hd (x # xs) = x\"\n  \"tl (x # xs) = xs\"\n  \"hd [x, y, z] = x\"\n  \"tl [x, y, z] = [y, z]\"\n  \"hd (tl [x, y, z]) = y\"\n  \"tl (tl [x, y, z]) = [z]\"\n  using list.sel(1,3)\n  by smt+\n\nlemma\n  \"fst (hd [(a, b)]) = a\"\n  \"snd (hd [(a, b)]) = b\"\n  using fst_conv snd_conv prod.collapse list.sel(1,3)\n  by smt+\n\n\nsubsubsection \\<open>Records\\<close>\ntext \\<open>The equivalent theory for Z3 contains more example, but unlike Z3, we are able\nto reconstruct the proofs.\\<close>\n\nlemma\n  \"cx \\<lparr> cx = 3, cy = 4 \\<rparr> = 3\"\n  \"cy \\<lparr> cx = 3, cy = 4 \\<rparr> = 4\"\n  \"cx \\<lparr> cx = 3, cy = 4 \\<rparr> \\<noteq> cy \\<lparr> cx = 3, cy = 4 \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4 \\<rparr> \\<lparr> cx := 5 \\<rparr> = \\<lparr> cx = 5, cy = 4 \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4 \\<rparr> \\<lparr> cy := 6 \\<rparr> = \\<lparr> cx = 3, cy = 6 \\<rparr>\"\n  \"p = \\<lparr> cx = 3, cy = 4 \\<rparr> \\<longrightarrow> p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p\"\n  \"p = \\<lparr> cx = 3, cy = 4 \\<rparr> \\<longrightarrow> p \\<lparr> cy := 4 \\<rparr> \\<lparr> cx := 3 \\<rparr> = p\"\n  using point.simps\n  by smt+\n\n\nlemma\n  \"cx \\<lparr> cx = 3, cy = 4, black = b \\<rparr> = 3\"\n  \"cy \\<lparr> cx = 3, cy = 4, black = b \\<rparr> = 4\"\n  \"black \\<lparr> cx = 3, cy = 4, black = b \\<rparr> = b\"\n  \"cx \\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<noteq> cy \\<lparr> cx = 3, cy = 4, black = b \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<lparr> cx := 5 \\<rparr> = \\<lparr> cx = 5, cy = 4, black = b \\<rparr>\"\n  \"\\<lparr> cx = 3, cy = 4, black = b \\<rparr> \\<lparr> cy := 6 \\<rparr> = \\<lparr> cx = 3, cy = 6, black = b \\<rparr>\"\n  \"p = \\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<longrightarrow>\n     p \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> \\<lparr> black := True \\<rparr> = p\"\n  \"p = \\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<longrightarrow>\n     p \\<lparr> cy := 4 \\<rparr> \\<lparr> black := True \\<rparr> \\<lparr> cx := 3 \\<rparr> = p\"\n  \"p = \\<lparr> cx = 3, cy = 4, black = True \\<rparr> \\<longrightarrow>\n     p \\<lparr> black := True \\<rparr> \\<lparr> cx := 3 \\<rparr> \\<lparr> cy := 4 \\<rparr> = p\"\n  using point.simps bw_point.simps\n  by smt+\n\n\nsection \\<open>Functions\\<close>\n\nlemma \"\\<exists>f. map_option f (Some x) = Some (y + x)\"\n  by (smt option.map(2))\n\nlemma\n  \"(f (i := v)) i = v\"\n  \"i1 \\<noteq> i2 \\<longrightarrow> (f (i1 := v)) i2 = f i2\"\n  \"i1 \\<noteq> i2 \\<longrightarrow> (f (i1 := v1, i2 := v2)) i1 = v1\"\n  \"i1 \\<noteq> i2 \\<longrightarrow> (f (i1 := v1, i2 := v2)) i2 = v2\"\n  \"i1 = i2 \\<longrightarrow> (f (i1 := v1, i2 := v2)) i1 = v2\"\n  \"i1 = i2 \\<longrightarrow> (f (i1 := v1, i2 := v2)) i1 = v2\"\n  \"i1 \\<noteq> i2 \\<and>i1 \\<noteq> i3 \\<and>  i2 \\<noteq> i3 \\<longrightarrow> (f (i1 := v1, i2 := v2)) i3 = f i3\"\n  using fun_upd_same fun_upd_apply\n  by smt+\n\n\nsection \\<open>Sets\\<close>\n\nlemma Empty: \"x \\<notin> {}\" by simp\n\nlemmas smt_sets = Empty UNIV_I Un_iff Int_iff\n\nlemma\n  \"x \\<notin> {}\"\n  \"x \\<in> UNIV\"\n  \"x \\<in> A \\<union> B \\<longleftrightarrow> x \\<in> A \\<or> x \\<in> B\"\n  \"x \\<in> P \\<union> {} \\<longleftrightarrow> x \\<in> P\"\n  \"x \\<in> P \\<union> UNIV\"\n  \"x \\<in> P \\<union> Q \\<longleftrightarrow> x \\<in> Q \\<union> P\"\n  \"x \\<in> P \\<union> P \\<longleftrightarrow> x \\<in> P\"\n  \"x \\<in> P \\<union> (Q \\<union> R) \\<longleftrightarrow> x \\<in> (P \\<union> Q) \\<union> R\"\n  \"x \\<in> A \\<inter> B \\<longleftrightarrow> x \\<in> A \\<and> x \\<in> B\"\n  \"x \\<notin> P \\<inter> {}\"\n  \"x \\<in> P \\<inter> UNIV \\<longleftrightarrow> x \\<in> P\"\n  \"x \\<in> P \\<inter> Q \\<longleftrightarrow> x \\<in> Q \\<inter> P\"\n  \"x \\<in> P \\<inter> P \\<longleftrightarrow> x \\<in> P\"\n  \"x \\<in> P \\<inter> (Q \\<inter> R) \\<longleftrightarrow> x \\<in> (P \\<inter> Q) \\<inter> R\"\n  \"{x. x \\<in> P} = {y. y \\<in> P}\"\n  by (smt smt_sets)+\n\n\ncontext\n  fixes in_multiset :: \"'d \\<Rightarrow> 'd_multiset \\<Rightarrow> bool\" and\n    add_mset :: \"'d \\<Rightarrow> 'd_multiset \\<Rightarrow> 'd_multiset\" and\n    set_mset :: \"'d_multiset \\<Rightarrow> 'd set\"\nbegin\nlemma\n  assumes \"\\<And>a b A. ((a::'d) \\<in> insert b A) = (a = b \\<or> a \\<in> A)\"\n    \"\\<And>a A. set_mset (add_mset (a::'d) A) = insert a (set_mset A)\"\n    \"\\<And>r. transp (r::'d \\<Rightarrow> 'd \\<Rightarrow> bool) = (\\<forall>x y z. r x y \\<longrightarrow> r y z \\<longrightarrow> r x z)\"\n  shows\n    \"transp (\\<lambda>x y. (x::'d) \\<in> set_mset (add_mset m M) \\<and> y \\<in> set_mset (add_mset m M) \\<and> R x y) \\<Longrightarrow>\n     transp (\\<lambda>x y. x \\<in> set_mset M \\<and> y \\<in> set_mset M \\<and> R x y)\"\n   by (smt (verit) assms)\nend\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/SMT_Examples/SMT_Tests_Verit.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8824278633625322, "lm_q1q2_score": 0.7634978293181899}}
{"text": "(*  Title:       HOL/Zorn.thy\n    Author:      Jacques D. Fleuriot\n    Author:      Tobias Nipkow, TUM\n    Author:      Christian Sternagel, JAIST\n\nZorn's Lemma (ported from Larry Paulson's Zorn.thy in ZF).\n*)\n\nsection \\<open>Zorn's Lemma and the Well-ordering Theorem\\<close>\n\ntheory Zorn\n  imports Order_Relation Hilbert_Choice\nbegin\n\nsubsection \\<open>Zorn's Lemma for the Subset Relation\\<close>\n\nsubsubsection \\<open>Results that do not require an order\\<close>\n\ntext \\<open>Let \\<open>P\\<close> be a binary predicate on the set \\<open>A\\<close>.\\<close>\nlocale pred_on =\n  fixes A :: \"'a set\"\n    and P :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infix \"\\<sqsubset>\" 50)\nbegin\n\nabbreviation Peq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infix \"\\<sqsubseteq>\" 50)\n  where \"x \\<sqsubseteq> y \\<equiv> P\\<^sup>=\\<^sup>= x y\"\n\ntext \\<open>A chain is a totally ordered subset of \\<open>A\\<close>.\\<close>\ndefinition chain :: \"'a set \\<Rightarrow> bool\"\n  where \"chain C \\<longleftrightarrow> C \\<subseteq> A \\<and> (\\<forall>x\\<in>C. \\<forall>y\\<in>C. x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x)\"\n\ntext \\<open>\n  We call a chain that is a proper superset of some set \\<open>X\\<close>,\n  but not necessarily a chain itself, a superchain of \\<open>X\\<close>.\n\\<close>\nabbreviation superchain :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infix \"<c\" 50)\n  where \"X <c C \\<equiv> chain C \\<and> X \\<subset> C\"\n\ntext \\<open>A maximal chain is a chain that does not have a superchain.\\<close>\ndefinition maxchain :: \"'a set \\<Rightarrow> bool\"\n  where \"maxchain C \\<longleftrightarrow> chain C \\<and> (\\<nexists>S. C <c S)\"\n\ntext \\<open>\n  We define the successor of a set to be an arbitrary\n  superchain, if such exists, or the set itself, otherwise.\n\\<close>\ndefinition suc :: \"'a set \\<Rightarrow> 'a set\"\n  where \"suc C = (if \\<not> chain C \\<or> maxchain C then C else (SOME D. C <c D))\"\n\nlemma chainI [Pure.intro?]: \"C \\<subseteq> A \\<Longrightarrow> (\\<And>x y. x \\<in> C \\<Longrightarrow> y \\<in> C \\<Longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x) \\<Longrightarrow> chain C\"\n  unfolding chain_def by blast\n\nlemma chain_total: \"chain C \\<Longrightarrow> x \\<in> C \\<Longrightarrow> y \\<in> C \\<Longrightarrow> x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n  by (simp add: chain_def)\n\nlemma not_chain_suc [simp]: \"\\<not> chain X \\<Longrightarrow> suc X = X\"\n  by (simp add: suc_def)\n\nlemma maxchain_suc [simp]: \"maxchain X \\<Longrightarrow> suc X = X\"\n  by (simp add: suc_def)\n\nlemma suc_subset: \"X \\<subseteq> suc X\"\n  by (auto simp: suc_def maxchain_def intro: someI2)\n\nlemma chain_empty [simp]: \"chain {}\"\n  by (auto simp: chain_def)\n\nlemma not_maxchain_Some: \"chain C \\<Longrightarrow> \\<not> maxchain C \\<Longrightarrow> C <c (SOME D. C <c D)\"\n  by (rule someI_ex) (auto simp: maxchain_def)\n\nlemma suc_not_equals: \"chain C \\<Longrightarrow> \\<not> maxchain C \\<Longrightarrow> suc C \\<noteq> C\"\n  using not_maxchain_Some by (auto simp: suc_def)\n\nlemma subset_suc:\n  assumes \"X \\<subseteq> Y\"\n  shows \"X \\<subseteq> suc Y\"\n  using assms by (rule subset_trans) (rule suc_subset)\n\ntext \\<open>\n  We build a set \\<^term>\\<open>\\<C>\\<close> that is closed under applications\n  of \\<^term>\\<open>suc\\<close> and contains the union of all its subsets.\n\\<close>\ninductive_set suc_Union_closed (\"\\<C>\")\n  where\n    suc: \"X \\<in> \\<C> \\<Longrightarrow> suc X \\<in> \\<C>\"\n  | Union [unfolded Pow_iff]: \"X \\<in> Pow \\<C> \\<Longrightarrow> \\<Union>X \\<in> \\<C>\"\n\ntext \\<open>\n  Since the empty set as well as the set itself is a subset of\n  every set, \\<^term>\\<open>\\<C>\\<close> contains at least \\<^term>\\<open>{} \\<in> \\<C>\\<close> and\n  \\<^term>\\<open>\\<Union>\\<C> \\<in> \\<C>\\<close>.\n\\<close>\nlemma suc_Union_closed_empty: \"{} \\<in> \\<C>\"\n  and suc_Union_closed_Union: \"\\<Union>\\<C> \\<in> \\<C>\"\n  using Union [of \"{}\"] and Union [of \"\\<C>\"] by simp_all\n\ntext \\<open>Thus closure under \\<^term>\\<open>suc\\<close> will hit a maximal chain\n  eventually, as is shown below.\\<close>\n\nlemma suc_Union_closed_induct [consumes 1, case_names suc Union, induct pred: suc_Union_closed]:\n  assumes \"X \\<in> \\<C>\"\n    and \"\\<And>X. X \\<in> \\<C> \\<Longrightarrow> Q X \\<Longrightarrow> Q (suc X)\"\n    and \"\\<And>X. X \\<subseteq> \\<C> \\<Longrightarrow> \\<forall>x\\<in>X. Q x \\<Longrightarrow> Q (\\<Union>X)\"\n  shows \"Q X\"\n  using assms by induct blast+\n\nlemma suc_Union_closed_cases [consumes 1, case_names suc Union, cases pred: suc_Union_closed]:\n  assumes \"X \\<in> \\<C>\"\n    and \"\\<And>Y. X = suc Y \\<Longrightarrow> Y \\<in> \\<C> \\<Longrightarrow> Q\"\n    and \"\\<And>Y. X = \\<Union>Y \\<Longrightarrow> Y \\<subseteq> \\<C> \\<Longrightarrow> Q\"\n  shows \"Q\"\n  using assms by cases simp_all\n\ntext \\<open>On chains, \\<^term>\\<open>suc\\<close> yields a chain.\\<close>\nlemma chain_suc:\n  assumes \"chain X\"\n  shows \"chain (suc X)\"\n  using assms\n  by (cases \"\\<not> chain X \\<or> maxchain X\") (force simp: suc_def dest: not_maxchain_Some)+\n\nlemma chain_sucD:\n  assumes \"chain X\"\n  shows \"suc X \\<subseteq> A \\<and> chain (suc X)\"\nproof -\n  from \\<open>chain X\\<close> have *: \"chain (suc X)\"\n    by (rule chain_suc)\n  then have \"suc X \\<subseteq> A\"\n    unfolding chain_def by blast\n  with * show ?thesis by blast\nqed\n\nlemma suc_Union_closed_total':\n  assumes \"X \\<in> \\<C>\" and \"Y \\<in> \\<C>\"\n    and *: \"\\<And>Z. Z \\<in> \\<C> \\<Longrightarrow> Z \\<subseteq> Y \\<Longrightarrow> Z = Y \\<or> suc Z \\<subseteq> Y\"\n  shows \"X \\<subseteq> Y \\<or> suc Y \\<subseteq> X\"\n  using \\<open>X \\<in> \\<C>\\<close>\nproof induct\n  case (suc X)\n  with * show ?case by (blast del: subsetI intro: subset_suc)\nnext\n  case Union\n  then show ?case by blast\nqed\n\nlemma suc_Union_closed_subsetD:\n  assumes \"Y \\<subseteq> X\" and \"X \\<in> \\<C>\" and \"Y \\<in> \\<C>\"\n  shows \"X = Y \\<or> suc Y \\<subseteq> X\"\n  using assms(2,3,1)\nproof (induct arbitrary: Y)\n  case (suc X)\n  note * = \\<open>\\<And>Y. Y \\<in> \\<C> \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> X = Y \\<or> suc Y \\<subseteq> X\\<close>\n  with suc_Union_closed_total' [OF \\<open>Y \\<in> \\<C>\\<close> \\<open>X \\<in> \\<C>\\<close>]\n  have \"Y \\<subseteq> X \\<or> suc X \\<subseteq> Y\" by blast\n  then show ?case\n  proof\n    assume \"Y \\<subseteq> X\"\n    with * and \\<open>Y \\<in> \\<C>\\<close> subset_suc show ?thesis\n      by fastforce\n  next\n    assume \"suc X \\<subseteq> Y\"\n    with \\<open>Y \\<subseteq> suc X\\<close> show ?thesis by blast\n  qed\nnext\n  case (Union X)\n  show ?case\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    with \\<open>Y \\<subseteq> \\<Union>X\\<close> obtain x y z\n      where \"\\<not> suc Y \\<subseteq> \\<Union>X\"\n        and \"x \\<in> X\" and \"y \\<in> x\" and \"y \\<notin> Y\"\n        and \"z \\<in> suc Y\" and \"\\<forall>x\\<in>X. z \\<notin> x\" by blast\n    with \\<open>X \\<subseteq> \\<C>\\<close> have \"x \\<in> \\<C>\" by blast\n    from Union and \\<open>x \\<in> X\\<close> have *: \"\\<And>y. y \\<in> \\<C> \\<Longrightarrow> y \\<subseteq> x \\<Longrightarrow> x = y \\<or> suc y \\<subseteq> x\"\n      by blast\n    with suc_Union_closed_total' [OF \\<open>Y \\<in> \\<C>\\<close> \\<open>x \\<in> \\<C>\\<close>] have \"Y \\<subseteq> x \\<or> suc x \\<subseteq> Y\"\n      by blast\n    then show False\n    proof\n      assume \"Y \\<subseteq> x\"\n      with * [OF \\<open>Y \\<in> \\<C>\\<close>] \\<open>y \\<in> x\\<close> \\<open>y \\<notin> Y\\<close> \\<open>x \\<in> X\\<close> \\<open>\\<not> suc Y \\<subseteq> \\<Union>X\\<close> show False\n        by blast\n    next\n      assume \"suc x \\<subseteq> Y\"\n      with \\<open>y \\<notin> Y\\<close> suc_subset \\<open>y \\<in> x\\<close> show False by blast\n    qed\n  qed\nqed\n\ntext \\<open>The elements of \\<^term>\\<open>\\<C>\\<close> are totally ordered by the subset relation.\\<close>\nlemma suc_Union_closed_total:\n  assumes \"X \\<in> \\<C>\" and \"Y \\<in> \\<C>\"\n  shows \"X \\<subseteq> Y \\<or> Y \\<subseteq> X\"\nproof (cases \"\\<forall>Z\\<in>\\<C>. Z \\<subseteq> Y \\<longrightarrow> Z = Y \\<or> suc Z \\<subseteq> Y\")\n  case True\n  with suc_Union_closed_total' [OF assms]\n  have \"X \\<subseteq> Y \\<or> suc Y \\<subseteq> X\" by blast\n  with suc_subset [of Y] show ?thesis by blast\nnext\n  case False\n  then obtain Z where \"Z \\<in> \\<C>\" and \"Z \\<subseteq> Y\" and \"Z \\<noteq> Y\" and \"\\<not> suc Z \\<subseteq> Y\"\n    by blast\n  with suc_Union_closed_subsetD and \\<open>Y \\<in> \\<C>\\<close> show ?thesis\n    by blast\nqed\n\ntext \\<open>Once we hit a fixed point w.r.t. \\<^term>\\<open>suc\\<close>, all other elements\n  of \\<^term>\\<open>\\<C>\\<close> are subsets of this fixed point.\\<close>\nlemma suc_Union_closed_suc:\n  assumes \"X \\<in> \\<C>\" and \"Y \\<in> \\<C>\" and \"suc Y = Y\"\n  shows \"X \\<subseteq> Y\"\n  using \\<open>X \\<in> \\<C>\\<close>\nproof induct\n  case (suc X)\n  with \\<open>Y \\<in> \\<C>\\<close> and suc_Union_closed_subsetD have \"X = Y \\<or> suc X \\<subseteq> Y\"\n    by blast\n  then show ?case\n    by (auto simp: \\<open>suc Y = Y\\<close>)\nnext\n  case Union\n  then show ?case by blast\nqed\n\nlemma eq_suc_Union:\n  assumes \"X \\<in> \\<C>\"\n  shows \"suc X = X \\<longleftrightarrow> X = \\<Union>\\<C>\"\n    (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?lhs\n  then have \"\\<Union>\\<C> \\<subseteq> X\"\n    by (rule suc_Union_closed_suc [OF suc_Union_closed_Union \\<open>X \\<in> \\<C>\\<close>])\n  with \\<open>X \\<in> \\<C>\\<close> show ?rhs\n    by blast\nnext\n  from \\<open>X \\<in> \\<C>\\<close> have \"suc X \\<in> \\<C>\" by (rule suc)\n  then have \"suc X \\<subseteq> \\<Union>\\<C>\" by blast\n  moreover assume ?rhs\n  ultimately have \"suc X \\<subseteq> X\" by simp\n  moreover have \"X \\<subseteq> suc X\" by (rule suc_subset)\n  ultimately show ?lhs ..\nqed\n\nlemma suc_in_carrier:\n  assumes \"X \\<subseteq> A\"\n  shows \"suc X \\<subseteq> A\"\n  using assms\n  by (cases \"\\<not> chain X \\<or> maxchain X\") (auto dest: chain_sucD)\n\nlemma suc_Union_closed_in_carrier:\n  assumes \"X \\<in> \\<C>\"\n  shows \"X \\<subseteq> A\"\n  using assms\n  by induct (auto dest: suc_in_carrier)\n\ntext \\<open>All elements of \\<^term>\\<open>\\<C>\\<close> are chains.\\<close>\nlemma suc_Union_closed_chain:\n  assumes \"X \\<in> \\<C>\"\n  shows \"chain X\"\n  using assms\nproof induct\n  case (suc X)\n  then show ?case\n    using not_maxchain_Some by (simp add: suc_def)\nnext\n  case (Union X)\n  then have \"\\<Union>X \\<subseteq> A\"\n    by (auto dest: suc_Union_closed_in_carrier)\n  moreover have \"\\<forall>x\\<in>\\<Union>X. \\<forall>y\\<in>\\<Union>X. x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n  proof (intro ballI)\n    fix x y\n    assume \"x \\<in> \\<Union>X\" and \"y \\<in> \\<Union>X\"\n    then obtain u v where \"x \\<in> u\" and \"u \\<in> X\" and \"y \\<in> v\" and \"v \\<in> X\"\n      by blast\n    with Union have \"u \\<in> \\<C>\" and \"v \\<in> \\<C>\" and \"chain u\" and \"chain v\"\n      by blast+\n    with suc_Union_closed_total have \"u \\<subseteq> v \\<or> v \\<subseteq> u\"\n      by blast\n    then show \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n    proof\n      assume \"u \\<subseteq> v\"\n      from \\<open>chain v\\<close> show ?thesis\n      proof (rule chain_total)\n        show \"y \\<in> v\" by fact\n        show \"x \\<in> v\" using \\<open>u \\<subseteq> v\\<close> and \\<open>x \\<in> u\\<close> by blast\n      qed\n    next\n      assume \"v \\<subseteq> u\"\n      from \\<open>chain u\\<close> show ?thesis\n      proof (rule chain_total)\n        show \"x \\<in> u\" by fact\n        show \"y \\<in> u\" using \\<open>v \\<subseteq> u\\<close> and \\<open>y \\<in> v\\<close> by blast\n      qed\n    qed\n  qed\n  ultimately show ?case unfolding chain_def ..\nqed\n\nsubsubsection \\<open>Hausdorff's Maximum Principle\\<close>\n\ntext \\<open>There exists a maximal totally ordered subset of \\<open>A\\<close>. (Note that we do not\n  require \\<open>A\\<close> to be partially ordered.)\\<close>\n\ntheorem Hausdorff: \"\\<exists>C. maxchain C\"\nproof -\n  let ?M = \"\\<Union>\\<C>\"\n  have \"maxchain ?M\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"suc ?M \\<noteq> ?M\"\n      using suc_not_equals and suc_Union_closed_chain [OF suc_Union_closed_Union] by simp\n    moreover have \"suc ?M = ?M\"\n      using eq_suc_Union [OF suc_Union_closed_Union] by simp\n    ultimately show False by contradiction\n  qed\n  then show ?thesis by blast\nqed\n\ntext \\<open>Make notation \\<^term>\\<open>\\<C>\\<close> available again.\\<close>\nno_notation suc_Union_closed  (\"\\<C>\")\n\nlemma chain_extend: \"chain C \\<Longrightarrow> z \\<in> A \\<Longrightarrow> \\<forall>x\\<in>C. x \\<sqsubseteq> z \\<Longrightarrow> chain ({z} \\<union> C)\"\n  unfolding chain_def by blast\n\nlemma maxchain_imp_chain: \"maxchain C \\<Longrightarrow> chain C\"\n  by (simp add: maxchain_def)\n\nend\n\ntext \\<open>Hide constant \\<^const>\\<open>pred_on.suc_Union_closed\\<close>, which was just needed\n  for the proof of Hausforff's maximum principle.\\<close>\nhide_const pred_on.suc_Union_closed\n\nlemma chain_mono:\n  assumes \"\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> P x y \\<Longrightarrow> Q x y\"\n    and \"pred_on.chain A P C\"\n  shows \"pred_on.chain A Q C\"\n  using assms unfolding pred_on.chain_def by blast\n\n\nsubsubsection \\<open>Results for the proper subset relation\\<close>\n\ninterpretation subset: pred_on \"A\" \"(\\<subset>)\" for A .\n\nlemma subset_maxchain_max:\n  assumes \"subset.maxchain A C\"\n    and \"X \\<in> A\"\n    and \"\\<Union>C \\<subseteq> X\"\n  shows \"\\<Union>C = X\"\nproof (rule ccontr)\n  let ?C = \"{X} \\<union> C\"\n  from \\<open>subset.maxchain A C\\<close> have \"subset.chain A C\"\n    and *: \"\\<And>S. subset.chain A S \\<Longrightarrow> \\<not> C \\<subset> S\"\n    by (auto simp: subset.maxchain_def)\n  moreover have \"\\<forall>x\\<in>C. x \\<subseteq> X\" using \\<open>\\<Union>C \\<subseteq> X\\<close> by auto\n  ultimately have \"subset.chain A ?C\"\n    using subset.chain_extend [of A C X] and \\<open>X \\<in> A\\<close> by auto\n  moreover assume **: \"\\<Union>C \\<noteq> X\"\n  moreover from ** have \"C \\<subset> ?C\" using \\<open>\\<Union>C \\<subseteq> X\\<close> by auto\n  ultimately show False using * by blast\nqed\n\nlemma subset_chain_def: \"\\<And>\\<A>. subset.chain \\<A> \\<C> = (\\<C> \\<subseteq> \\<A> \\<and> (\\<forall>X\\<in>\\<C>. \\<forall>Y\\<in>\\<C>. X \\<subseteq> Y \\<or> Y \\<subseteq> X))\"\n  by (auto simp: subset.chain_def)\n\nlemma subset_chain_insert:\n  \"subset.chain \\<A> (insert B \\<B>) \\<longleftrightarrow> B \\<in> \\<A> \\<and> (\\<forall>X\\<in>\\<B>. X \\<subseteq> B \\<or> B \\<subseteq> X) \\<and> subset.chain \\<A> \\<B>\"\n  by (fastforce simp add: subset_chain_def)\n\nsubsubsection \\<open>Zorn's lemma\\<close>\n\ntext \\<open>If every chain has an upper bound, then there is a maximal set.\\<close>\ntheorem subset_Zorn:\n  assumes \"\\<And>C. subset.chain A C \\<Longrightarrow> \\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U\"\n  shows \"\\<exists>M\\<in>A. \\<forall>X\\<in>A. M \\<subseteq> X \\<longrightarrow> X = M\"\nproof -\n  from subset.Hausdorff [of A] obtain M where \"subset.maxchain A M\" ..\n  then have \"subset.chain A M\"\n    by (rule subset.maxchain_imp_chain)\n  with assms obtain Y where \"Y \\<in> A\" and \"\\<forall>X\\<in>M. X \\<subseteq> Y\"\n    by blast\n  moreover have \"\\<forall>X\\<in>A. Y \\<subseteq> X \\<longrightarrow> Y = X\"\n  proof (intro ballI impI)\n    fix X\n    assume \"X \\<in> A\" and \"Y \\<subseteq> X\"\n    show \"Y = X\"\n    proof (rule ccontr)\n      assume \"\\<not> ?thesis\"\n      with \\<open>Y \\<subseteq> X\\<close> have \"\\<not> X \\<subseteq> Y\" by blast\n      from subset.chain_extend [OF \\<open>subset.chain A M\\<close> \\<open>X \\<in> A\\<close>] and \\<open>\\<forall>X\\<in>M. X \\<subseteq> Y\\<close>\n      have \"subset.chain A ({X} \\<union> M)\"\n        using \\<open>Y \\<subseteq> X\\<close> by auto\n      moreover have \"M \\<subset> {X} \\<union> M\"\n        using \\<open>\\<forall>X\\<in>M. X \\<subseteq> Y\\<close> and \\<open>\\<not> X \\<subseteq> Y\\<close> by auto\n      ultimately show False\n        using \\<open>subset.maxchain A M\\<close> by (auto simp: subset.maxchain_def)\n    qed\n  qed\n  ultimately show ?thesis by blast\nqed\n\ntext \\<open>Alternative version of Zorn's lemma for the subset relation.\\<close>\nlemma subset_Zorn':\n  assumes \"\\<And>C. subset.chain A C \\<Longrightarrow> \\<Union>C \\<in> A\"\n  shows \"\\<exists>M\\<in>A. \\<forall>X\\<in>A. M \\<subseteq> X \\<longrightarrow> X = M\"\nproof -\n  from subset.Hausdorff [of A] obtain M where \"subset.maxchain A M\" ..\n  then have \"subset.chain A M\"\n    by (rule subset.maxchain_imp_chain)\n  with assms have \"\\<Union>M \\<in> A\" .\n  moreover have \"\\<forall>Z\\<in>A. \\<Union>M \\<subseteq> Z \\<longrightarrow> \\<Union>M = Z\"\n  proof (intro ballI impI)\n    fix Z\n    assume \"Z \\<in> A\" and \"\\<Union>M \\<subseteq> Z\"\n    with subset_maxchain_max [OF \\<open>subset.maxchain A M\\<close>]\n      show \"\\<Union>M = Z\" .\n  qed\n  ultimately show ?thesis by blast\nqed\n\n\nsubsection \\<open>Zorn's Lemma for Partial Orders\\<close>\n\ntext \\<open>Relate old to new definitions.\\<close>\n\ndefinition chain_subset :: \"'a set set \\<Rightarrow> bool\"  (\"chain\\<^sub>\\<subseteq>\")  (* Define globally? In Set.thy? *)\n  where \"chain\\<^sub>\\<subseteq> C \\<longleftrightarrow> (\\<forall>A\\<in>C. \\<forall>B\\<in>C. A \\<subseteq> B \\<or> B \\<subseteq> A)\"\n\ndefinition chains :: \"'a set set \\<Rightarrow> 'a set set set\"\n  where \"chains A = {C. C \\<subseteq> A \\<and> chain\\<^sub>\\<subseteq> C}\"\n\ndefinition Chains :: \"('a \\<times> 'a) set \\<Rightarrow> 'a set set\"  (* Define globally? In Relation.thy? *)\n  where \"Chains r = {C. \\<forall>a\\<in>C. \\<forall>b\\<in>C. (a, b) \\<in> r \\<or> (b, a) \\<in> r}\"\n\nlemma chains_extend: \"c \\<in> chains S \\<Longrightarrow> z \\<in> S \\<Longrightarrow> \\<forall>x \\<in> c. x \\<subseteq> z \\<Longrightarrow> {z} \\<union> c \\<in> chains S\"\n  for z :: \"'a set\"\n  unfolding chains_def chain_subset_def by blast\n\nlemma mono_Chains: \"r \\<subseteq> s \\<Longrightarrow> Chains r \\<subseteq> Chains s\"\n  unfolding Chains_def by blast\n\nlemma chain_subset_alt_def: \"chain\\<^sub>\\<subseteq> C = subset.chain UNIV C\"\n  unfolding chain_subset_def subset.chain_def by fast\n\nlemma chains_alt_def: \"chains A = {C. subset.chain A C}\"\n  by (simp add: chains_def chain_subset_alt_def subset.chain_def)\n\nlemma Chains_subset: \"Chains r \\<subseteq> {C. pred_on.chain UNIV (\\<lambda>x y. (x, y) \\<in> r) C}\"\n  by (force simp add: Chains_def pred_on.chain_def)\n\nlemma Chains_subset':\n  assumes \"refl r\"\n  shows \"{C. pred_on.chain UNIV (\\<lambda>x y. (x, y) \\<in> r) C} \\<subseteq> Chains r\"\n  using assms\n  by (auto simp add: Chains_def pred_on.chain_def refl_on_def)\n\nlemma Chains_alt_def:\n  assumes \"refl r\"\n  shows \"Chains r = {C. pred_on.chain UNIV (\\<lambda>x y. (x, y) \\<in> r) C}\"\n  using assms Chains_subset Chains_subset' by blast\n\nlemma Chains_relation_of:\n  assumes \"C \\<in> Chains (relation_of P A)\" shows \"C \\<subseteq> A\"\n  using assms unfolding Chains_def relation_of_def by auto\n\nlemma pairwise_chain_Union:\n  assumes P: \"\\<And>S. S \\<in> \\<C> \\<Longrightarrow> pairwise R S\" and \"chain\\<^sub>\\<subseteq> \\<C>\"\n  shows \"pairwise R (\\<Union>\\<C>)\"\n  using \\<open>chain\\<^sub>\\<subseteq> \\<C>\\<close> unfolding pairwise_def chain_subset_def\n  by (blast intro: P [unfolded pairwise_def, rule_format])\n\nlemma Zorn_Lemma: \"\\<forall>C\\<in>chains A. \\<Union>C \\<in> A \\<Longrightarrow> \\<exists>M\\<in>A. \\<forall>X\\<in>A. M \\<subseteq> X \\<longrightarrow> X = M\"\n  using subset_Zorn' [of A] by (force simp: chains_alt_def)\n\nlemma Zorn_Lemma2: \"\\<forall>C\\<in>chains A. \\<exists>U\\<in>A. \\<forall>X\\<in>C. X \\<subseteq> U \\<Longrightarrow> \\<exists>M\\<in>A. \\<forall>X\\<in>A. M \\<subseteq> X \\<longrightarrow> X = M\"\n  using subset_Zorn [of A] by (auto simp: chains_alt_def)\n\nsubsection \\<open>Other variants of Zorn's Lemma\\<close>\n\nlemma chainsD: \"c \\<in> chains S \\<Longrightarrow> x \\<in> c \\<Longrightarrow> y \\<in> c \\<Longrightarrow> x \\<subseteq> y \\<or> y \\<subseteq> x\"\n  unfolding chains_def chain_subset_def by blast\n\nlemma chainsD2: \"c \\<in> chains S \\<Longrightarrow> c \\<subseteq> S\"\n  unfolding chains_def by blast\n\nlemma Zorns_po_lemma:\n  assumes po: \"Partial_order r\"\n    and u: \"\\<And>C. C \\<in> Chains r \\<Longrightarrow> \\<exists>u\\<in>Field r. \\<forall>a\\<in>C. (a, u) \\<in> r\"\n  shows \"\\<exists>m\\<in>Field r. \\<forall>a\\<in>Field r. (m, a) \\<in> r \\<longrightarrow> a = m\"\nproof -\n  have \"Preorder r\"\n    using po by (simp add: partial_order_on_def)\n  txt \\<open>Mirror \\<open>r\\<close> in the set of subsets below (wrt \\<open>r\\<close>) elements of \\<open>A\\<close>.\\<close>\n  let ?B = \"\\<lambda>x. r\\<inverse> `` {x}\"\n  let ?S = \"?B ` Field r\"\n  have \"\\<exists>u\\<in>Field r. \\<forall>A\\<in>C. A \\<subseteq> r\\<inverse> `` {u}\"  (is \"\\<exists>u\\<in>Field r. ?P u\")\n    if 1: \"C \\<subseteq> ?S\" and 2: \"\\<forall>A\\<in>C. \\<forall>B\\<in>C. A \\<subseteq> B \\<or> B \\<subseteq> A\" for C\n  proof -\n    let ?A = \"{x\\<in>Field r. \\<exists>M\\<in>C. M = ?B x}\"\n    from 1 have \"C = ?B ` ?A\" by (auto simp: image_def)\n    have \"?A \\<in> Chains r\"\n    proof (simp add: Chains_def, intro allI impI, elim conjE)\n      fix a b\n      assume \"a \\<in> Field r\" and \"?B a \\<in> C\" and \"b \\<in> Field r\" and \"?B b \\<in> C\"\n      with 2 have \"?B a \\<subseteq> ?B b \\<or> ?B b \\<subseteq> ?B a\" by auto\n      then show \"(a, b) \\<in> r \\<or> (b, a) \\<in> r\"\n        using \\<open>Preorder r\\<close> and \\<open>a \\<in> Field r\\<close> and \\<open>b \\<in> Field r\\<close>\n        by (simp add:subset_Image1_Image1_iff)\n    qed\n    then obtain u where uA: \"u \\<in> Field r\" \"\\<forall>a\\<in>?A. (a, u) \\<in> r\"\n      by (auto simp: dest: u)\n    have \"?P u\"\n    proof auto\n      fix a B assume aB: \"B \\<in> C\" \"a \\<in> B\"\n      with 1 obtain x where \"x \\<in> Field r\" and \"B = r\\<inverse> `` {x}\" by auto\n      then show \"(a, u) \\<in> r\"\n        using uA and aB and \\<open>Preorder r\\<close>\n        unfolding preorder_on_def refl_on_def by simp (fast dest: transD)\n    qed\n    then show ?thesis\n      using \\<open>u \\<in> Field r\\<close> by blast\n  qed\n  then have \"\\<forall>C\\<in>chains ?S. \\<exists>U\\<in>?S. \\<forall>A\\<in>C. A \\<subseteq> U\"\n    by (auto simp: chains_def chain_subset_def)\n  from Zorn_Lemma2 [OF this] obtain m B\n    where \"m \\<in> Field r\"\n      and \"B = r\\<inverse> `` {m}\"\n      and \"\\<forall>x\\<in>Field r. B \\<subseteq> r\\<inverse> `` {x} \\<longrightarrow> r\\<inverse> `` {x} = B\"\n    by auto\n  then have \"\\<forall>a\\<in>Field r. (m, a) \\<in> r \\<longrightarrow> a = m\"\n    using po and \\<open>Preorder r\\<close> and \\<open>m \\<in> Field r\\<close>\n    by (auto simp: subset_Image1_Image1_iff Partial_order_eq_Image1_Image1_iff)\n  then show ?thesis\n    using \\<open>m \\<in> Field r\\<close> by blast\nqed\n\nlemma predicate_Zorn:\n  assumes po: \"partial_order_on A (relation_of P A)\"\n    and ch: \"\\<And>C. C \\<in> Chains (relation_of P A) \\<Longrightarrow> \\<exists>u \\<in> A. \\<forall>a \\<in> C. P a u\"\n  shows \"\\<exists>m \\<in> A. \\<forall>a \\<in> A. P m a \\<longrightarrow> a = m\"\nproof -\n  have \"a \\<in> A\" if \"C \\<in> Chains (relation_of P A)\" and \"a \\<in> C\" for C a\n    using that unfolding Chains_def relation_of_def by auto\n  moreover have \"(a, u) \\<in> relation_of P A\" if \"a \\<in> A\" and \"u \\<in> A\" and \"P a u\" for a u\n    unfolding relation_of_def using that by auto\n  ultimately have \"\\<exists>m\\<in>A. \\<forall>a\\<in>A. (m, a) \\<in> relation_of P A \\<longrightarrow> a = m\"\n    using Zorns_po_lemma[OF Partial_order_relation_ofI[OF po], rule_format] ch\n    unfolding Field_relation_of[OF partial_order_onD(1)[OF po]] by blast\n  then show ?thesis\n    by (auto simp: relation_of_def)\nqed\n\nlemma Union_in_chain: \"\\<lbrakk>finite \\<B>; \\<B> \\<noteq> {}; subset.chain \\<A> \\<B>\\<rbrakk> \\<Longrightarrow> \\<Union>\\<B> \\<in> \\<B>\"\nproof (induction \\<B> rule: finite_induct)\n  case (insert B \\<B>)\n  show ?case\n  proof (cases \"\\<B> = {}\")\n    case False\n    then show ?thesis\n      using insert sup.absorb2 by (auto simp: subset_chain_insert dest!: bspec [where x=\"\\<Union>\\<B>\"])\n  qed auto\nqed simp\n\nlemma Inter_in_chain: \"\\<lbrakk>finite \\<B>; \\<B> \\<noteq> {}; subset.chain \\<A> \\<B>\\<rbrakk> \\<Longrightarrow> \\<Inter>\\<B> \\<in> \\<B>\"\nproof (induction \\<B> rule: finite_induct)\n  case (insert B \\<B>)\n  show ?case\n  proof (cases \"\\<B> = {}\")\n    case False\n    then show ?thesis\n      using insert inf.absorb2 by (auto simp: subset_chain_insert dest!: bspec [where x=\"\\<Inter>\\<B>\"])\n  qed auto\nqed simp\n\nlemma finite_subset_Union_chain:\n  assumes \"finite A\" \"A \\<subseteq> \\<Union>\\<B>\" \"\\<B> \\<noteq> {}\" and sub: \"subset.chain \\<A> \\<B>\"\n  obtains B where \"B \\<in> \\<B>\" \"A \\<subseteq> B\"\nproof -\n  obtain \\<F> where \\<F>: \"finite \\<F>\" \"\\<F> \\<subseteq> \\<B>\" \"A \\<subseteq> \\<Union>\\<F>\"\n    using assms by (auto intro: finite_subset_Union)\n  show thesis\n  proof (cases \"\\<F> = {}\")\n    case True\n    then show ?thesis\n      using \\<open>A \\<subseteq> \\<Union>\\<F>\\<close> \\<open>\\<B> \\<noteq> {}\\<close> that by fastforce\n  next\n    case False\n    show ?thesis\n    proof\n      show \"\\<Union>\\<F> \\<in> \\<B>\"\n        using sub \\<open>\\<F> \\<subseteq> \\<B>\\<close> \\<open>finite \\<F>\\<close>\n        by (simp add: Union_in_chain False subset.chain_def subset_iff)\n      show \"A \\<subseteq> \\<Union>\\<F>\"\n        using \\<open>A \\<subseteq> \\<Union>\\<F>\\<close> by blast\n    qed\n  qed\nqed\n\nlemma subset_Zorn_nonempty:\n  assumes \"\\<A> \\<noteq> {}\" and ch: \"\\<And>\\<C>. \\<lbrakk>\\<C>\\<noteq>{}; subset.chain \\<A> \\<C>\\<rbrakk> \\<Longrightarrow> \\<Union>\\<C> \\<in> \\<A>\"\n  shows \"\\<exists>M\\<in>\\<A>. \\<forall>X\\<in>\\<A>. M \\<subseteq> X \\<longrightarrow> X = M\"\nproof (rule subset_Zorn)\n  show \"\\<exists>U\\<in>\\<A>. \\<forall>X\\<in>\\<C>. X \\<subseteq> U\" if \"subset.chain \\<A> \\<C>\" for \\<C>\n  proof (cases \"\\<C> = {}\")\n    case True\n    then show ?thesis\n      using \\<open>\\<A> \\<noteq> {}\\<close> by blast\n  next\n    case False\n    show ?thesis\n      by (blast intro!: ch False that Union_upper)\n  qed\nqed\n\nsubsection \\<open>The Well Ordering Theorem\\<close>\n\n(* The initial segment of a relation appears generally useful.\n   Move to Relation.thy?\n   Definition correct/most general?\n   Naming?\n*)\ndefinition init_seg_of :: \"(('a \\<times> 'a) set \\<times> ('a \\<times> 'a) set) set\"\n  where \"init_seg_of = {(r, s). r \\<subseteq> s \\<and> (\\<forall>a b c. (a, b) \\<in> s \\<and> (b, c) \\<in> r \\<longrightarrow> (a, b) \\<in> r)}\"\n\nabbreviation initial_segment_of_syntax :: \"('a \\<times> 'a) set \\<Rightarrow> ('a \\<times> 'a) set \\<Rightarrow> bool\"\n    (infix \"initial'_segment'_of\" 55)\n  where \"r initial_segment_of s \\<equiv> (r, s) \\<in> init_seg_of\"\n\nlemma refl_on_init_seg_of [simp]: \"r initial_segment_of r\"\n  by (simp add: init_seg_of_def)\n\nlemma trans_init_seg_of:\n  \"r initial_segment_of s \\<Longrightarrow> s initial_segment_of t \\<Longrightarrow> r initial_segment_of t\"\n  by (simp (no_asm_use) add: init_seg_of_def) blast\n\nlemma antisym_init_seg_of: \"r initial_segment_of s \\<Longrightarrow> s initial_segment_of r \\<Longrightarrow> r = s\"\n  unfolding init_seg_of_def by safe\n\nlemma Chains_init_seg_of_Union: \"R \\<in> Chains init_seg_of \\<Longrightarrow> r\\<in>R \\<Longrightarrow> r initial_segment_of \\<Union>R\"\n  by (auto simp: init_seg_of_def Ball_def Chains_def) blast\n\nlemma chain_subset_trans_Union:\n  assumes \"chain\\<^sub>\\<subseteq> R\" \"\\<forall>r\\<in>R. trans r\"\n  shows \"trans (\\<Union>R)\"\nproof (intro transI, elim UnionE)\n  fix S1 S2 :: \"'a rel\" and x y z :: 'a\n  assume \"S1 \\<in> R\" \"S2 \\<in> R\"\n  with assms(1) have \"S1 \\<subseteq> S2 \\<or> S2 \\<subseteq> S1\"\n    unfolding chain_subset_def by blast\n  moreover assume \"(x, y) \\<in> S1\" \"(y, z) \\<in> S2\"\n  ultimately have \"((x, y) \\<in> S1 \\<and> (y, z) \\<in> S1) \\<or> ((x, y) \\<in> S2 \\<and> (y, z) \\<in> S2)\"\n    by blast\n  with \\<open>S1 \\<in> R\\<close> \\<open>S2 \\<in> R\\<close> assms(2) show \"(x, z) \\<in> \\<Union>R\"\n    by (auto elim: transE)\nqed\n\nlemma chain_subset_antisym_Union:\n  assumes \"chain\\<^sub>\\<subseteq> R\" \"\\<forall>r\\<in>R. antisym r\"\n  shows \"antisym (\\<Union>R)\"\nproof (intro antisymI, elim UnionE)\n  fix S1 S2 :: \"'a rel\" and x y :: 'a\n  assume \"S1 \\<in> R\" \"S2 \\<in> R\"\n  with assms(1) have \"S1 \\<subseteq> S2 \\<or> S2 \\<subseteq> S1\"\n    unfolding chain_subset_def by blast\n  moreover assume \"(x, y) \\<in> S1\" \"(y, x) \\<in> S2\"\n  ultimately have \"((x, y) \\<in> S1 \\<and> (y, x) \\<in> S1) \\<or> ((x, y) \\<in> S2 \\<and> (y, x) \\<in> S2)\"\n    by blast\n  with \\<open>S1 \\<in> R\\<close> \\<open>S2 \\<in> R\\<close> assms(2) show \"x = y\"\n    unfolding antisym_def by auto\nqed\n\nlemma chain_subset_Total_Union:\n  assumes \"chain\\<^sub>\\<subseteq> R\" and \"\\<forall>r\\<in>R. Total r\"\n  shows \"Total (\\<Union>R)\"\nproof (simp add: total_on_def Ball_def, auto del: disjCI)\n  fix r s a b\n  assume A: \"r \\<in> R\" \"s \\<in> R\" \"a \\<in> Field r\" \"b \\<in> Field s\" \"a \\<noteq> b\"\n  from \\<open>chain\\<^sub>\\<subseteq> R\\<close> and \\<open>r \\<in> R\\<close> and \\<open>s \\<in> R\\<close> have \"r \\<subseteq> s \\<or> s \\<subseteq> r\"\n    by (auto simp add: chain_subset_def)\n  then show \"(\\<exists>r\\<in>R. (a, b) \\<in> r) \\<or> (\\<exists>r\\<in>R. (b, a) \\<in> r)\"\n  proof\n    assume \"r \\<subseteq> s\"\n    then have \"(a, b) \\<in> s \\<or> (b, a) \\<in> s\"\n      using assms(2) A mono_Field[of r s]\n      by (auto simp add: total_on_def)\n    then show ?thesis\n      using \\<open>s \\<in> R\\<close> by blast\n  next\n    assume \"s \\<subseteq> r\"\n    then have \"(a, b) \\<in> r \\<or> (b, a) \\<in> r\"\n      using assms(2) A mono_Field[of s r]\n      by (fastforce simp add: total_on_def)\n    then show ?thesis\n      using \\<open>r \\<in> R\\<close> by blast\n  qed\nqed\n\nlemma wf_Union_wf_init_segs:\n  assumes \"R \\<in> Chains init_seg_of\"\n    and \"\\<forall>r\\<in>R. wf r\"\n  shows \"wf (\\<Union>R)\"\nproof (simp add: wf_iff_no_infinite_down_chain, rule ccontr, auto)\n  fix f\n  assume 1: \"\\<forall>i. \\<exists>r\\<in>R. (f (Suc i), f i) \\<in> r\"\n  then obtain r where \"r \\<in> R\" and \"(f (Suc 0), f 0) \\<in> r\" by auto\n  have \"(f (Suc i), f i) \\<in> r\" for i\n  proof (induct i)\n    case 0\n    show ?case by fact\n  next\n    case (Suc i)\n    then obtain s where s: \"s \\<in> R\" \"(f (Suc (Suc i)), f(Suc i)) \\<in> s\"\n      using 1 by auto\n    then have \"s initial_segment_of r \\<or> r initial_segment_of s\"\n      using assms(1) \\<open>r \\<in> R\\<close> by (simp add: Chains_def)\n    with Suc s show ?case by (simp add: init_seg_of_def) blast\n  qed\n  then show False\n    using assms(2) and \\<open>r \\<in> R\\<close>\n    by (simp add: wf_iff_no_infinite_down_chain) blast\nqed\n\nlemma initial_segment_of_Diff: \"p initial_segment_of q \\<Longrightarrow> p - s initial_segment_of q - s\"\n  unfolding init_seg_of_def by blast\n\nlemma Chains_inits_DiffI: \"R \\<in> Chains init_seg_of \\<Longrightarrow> {r - s |r. r \\<in> R} \\<in> Chains init_seg_of\"\n  unfolding Chains_def by (blast intro: initial_segment_of_Diff)\n\ntheorem well_ordering: \"\\<exists>r::'a rel. Well_order r \\<and> Field r = UNIV\"\nproof -\n\\<comment> \\<open>The initial segment relation on well-orders:\\<close>\n  let ?WO = \"{r::'a rel. Well_order r}\"\n  define I where \"I = init_seg_of \\<inter> ?WO \\<times> ?WO\"\n  then have I_init: \"I \\<subseteq> init_seg_of\" by simp\n  then have subch: \"\\<And>R. R \\<in> Chains I \\<Longrightarrow> chain\\<^sub>\\<subseteq> R\"\n    unfolding init_seg_of_def chain_subset_def Chains_def by blast\n  have Chains_wo: \"\\<And>R r. R \\<in> Chains I \\<Longrightarrow> r \\<in> R \\<Longrightarrow> Well_order r\"\n    by (simp add: Chains_def I_def) blast\n  have FI: \"Field I = ?WO\"\n    by (auto simp add: I_def init_seg_of_def Field_def)\n  then have 0: \"Partial_order I\"\n    by (auto simp: partial_order_on_def preorder_on_def antisym_def antisym_init_seg_of refl_on_def\n        trans_def I_def elim!: trans_init_seg_of)\n\\<comment> \\<open>\\<open>I\\<close>-chains have upper bounds in \\<open>?WO\\<close> wrt \\<open>I\\<close>: their Union\\<close>\n  have \"\\<Union>R \\<in> ?WO \\<and> (\\<forall>r\\<in>R. (r, \\<Union>R) \\<in> I)\" if \"R \\<in> Chains I\" for R\n  proof -\n    from that have Ris: \"R \\<in> Chains init_seg_of\"\n      using mono_Chains [OF I_init] by blast\n    have subch: \"chain\\<^sub>\\<subseteq> R\"\n      using \\<open>R \\<in> Chains I\\<close> I_init by (auto simp: init_seg_of_def chain_subset_def Chains_def)\n    have \"\\<forall>r\\<in>R. Refl r\" and \"\\<forall>r\\<in>R. trans r\" and \"\\<forall>r\\<in>R. antisym r\"\n      and \"\\<forall>r\\<in>R. Total r\" and \"\\<forall>r\\<in>R. wf (r - Id)\"\n      using Chains_wo [OF \\<open>R \\<in> Chains I\\<close>] by (simp_all add: order_on_defs)\n    have \"Refl (\\<Union>R)\"\n      using \\<open>\\<forall>r\\<in>R. Refl r\\<close> unfolding refl_on_def by fastforce\n    moreover have \"trans (\\<Union>R)\"\n      by (rule chain_subset_trans_Union [OF subch \\<open>\\<forall>r\\<in>R. trans r\\<close>])\n    moreover have \"antisym (\\<Union>R)\"\n      by (rule chain_subset_antisym_Union [OF subch \\<open>\\<forall>r\\<in>R. antisym r\\<close>])\n    moreover have \"Total (\\<Union>R)\"\n      by (rule chain_subset_Total_Union [OF subch \\<open>\\<forall>r\\<in>R. Total r\\<close>])\n    moreover have \"wf ((\\<Union>R) - Id)\"\n    proof -\n      have \"(\\<Union>R) - Id = \\<Union>{r - Id | r. r \\<in> R}\" by blast\n      with \\<open>\\<forall>r\\<in>R. wf (r - Id)\\<close> and wf_Union_wf_init_segs [OF Chains_inits_DiffI [OF Ris]]\n      show ?thesis by fastforce\n    qed\n    ultimately have \"Well_order (\\<Union>R)\"\n      by (simp add:order_on_defs)\n    moreover have \"\\<forall>r \\<in> R. r initial_segment_of \\<Union>R\"\n      using Ris by (simp add: Chains_init_seg_of_Union)\n    ultimately show ?thesis\n      using mono_Chains [OF I_init] Chains_wo[of R] and \\<open>R \\<in> Chains I\\<close>\n      unfolding I_def by blast\n  qed\n  then have 1: \"\\<exists>u\\<in>Field I. \\<forall>r\\<in>R. (r, u) \\<in> I\" if \"R \\<in> Chains I\" for R\n    using that by (subst FI) blast\n\\<comment> \\<open>Zorn's Lemma yields a maximal well-order \\<open>m\\<close>:\\<close>\n  then obtain m :: \"'a rel\"\n    where \"Well_order m\"\n      and max: \"\\<forall>r. Well_order r \\<and> (m, r) \\<in> I \\<longrightarrow> r = m\"\n    using Zorns_po_lemma[OF 0 1] unfolding FI by fastforce\n\\<comment> \\<open>Now show by contradiction that \\<open>m\\<close> covers the whole type:\\<close>\n  have False if \"x \\<notin> Field m\" for x :: 'a\n  proof -\n\\<comment> \\<open>Assuming that \\<open>x\\<close> is not covered and extend \\<open>m\\<close> at the top with \\<open>x\\<close>\\<close>\n    have \"m \\<noteq> {}\"\n    proof\n      assume \"m = {}\"\n      moreover have \"Well_order {(x, x)}\"\n        by (simp add: order_on_defs refl_on_def trans_def antisym_def total_on_def Field_def)\n      ultimately show False using max\n        by (auto simp: I_def init_seg_of_def simp del: Field_insert)\n    qed\n    then have \"Field m \\<noteq> {}\" by (auto simp: Field_def)\n    moreover have \"wf (m - Id)\"\n      using \\<open>Well_order m\\<close> by (simp add: well_order_on_def)\n\\<comment> \\<open>The extension of \\<open>m\\<close> by \\<open>x\\<close>:\\<close>\n    let ?s = \"{(a, x) | a. a \\<in> Field m}\"\n    let ?m = \"insert (x, x) m \\<union> ?s\"\n    have Fm: \"Field ?m = insert x (Field m)\"\n      by (auto simp: Field_def)\n    have \"Refl m\" and \"trans m\" and \"antisym m\" and \"Total m\" and \"wf (m - Id)\"\n      using \\<open>Well_order m\\<close> by (simp_all add: order_on_defs)\n\\<comment> \\<open>We show that the extension is a well-order\\<close>\n    have \"Refl ?m\"\n      using \\<open>Refl m\\<close> Fm unfolding refl_on_def by blast\n    moreover have \"trans ?m\" using \\<open>trans m\\<close> and \\<open>x \\<notin> Field m\\<close>\n      unfolding trans_def Field_def by blast\n    moreover have \"antisym ?m\"\n      using \\<open>antisym m\\<close> and \\<open>x \\<notin> Field m\\<close> unfolding antisym_def Field_def by blast\n    moreover have \"Total ?m\"\n      using \\<open>Total m\\<close> and Fm by (auto simp: total_on_def)\n    moreover have \"wf (?m - Id)\"\n    proof -\n      have \"wf ?s\"\n        using \\<open>x \\<notin> Field m\\<close> by (auto simp: wf_eq_minimal Field_def Bex_def)\n      then show ?thesis\n        using \\<open>wf (m - Id)\\<close> and \\<open>x \\<notin> Field m\\<close> wf_subset [OF \\<open>wf ?s\\<close> Diff_subset]\n        by (auto simp: Un_Diff Field_def intro: wf_Un)\n    qed\n    ultimately have \"Well_order ?m\"\n      by (simp add: order_on_defs)\n\\<comment> \\<open>We show that the extension is above \\<open>m\\<close>\\<close>\n    moreover have \"(m, ?m) \\<in> I\"\n      using \\<open>Well_order ?m\\<close> and \\<open>Well_order m\\<close> and \\<open>x \\<notin> Field m\\<close>\n      by (fastforce simp: I_def init_seg_of_def Field_def)\n    ultimately\n\\<comment> \\<open>This contradicts maximality of \\<open>m\\<close>:\\<close>\n    show False\n      using max and \\<open>x \\<notin> Field m\\<close> unfolding Field_def by blast\n  qed\n  then have \"Field m = UNIV\" by auto\n  with \\<open>Well_order m\\<close> show ?thesis by blast\nqed\n\ncorollary well_order_on: \"\\<exists>r::'a rel. well_order_on A r\"\nproof -\n  obtain r :: \"'a rel\" where wo: \"Well_order r\" and univ: \"Field r = UNIV\"\n    using well_ordering [where 'a = \"'a\"] by blast\n  let ?r = \"{(x, y). x \\<in> A \\<and> y \\<in> A \\<and> (x, y) \\<in> r}\"\n  have 1: \"Field ?r = A\"\n    using wo univ by (fastforce simp: Field_def order_on_defs refl_on_def)\n  from \\<open>Well_order r\\<close> have \"Refl r\" \"trans r\" \"antisym r\" \"Total r\" \"wf (r - Id)\"\n    by (simp_all add: order_on_defs)\n  from \\<open>Refl r\\<close> have \"Refl ?r\"\n    by (auto simp: refl_on_def 1 univ)\n  moreover from \\<open>trans r\\<close> have \"trans ?r\"\n    unfolding trans_def by blast\n  moreover from \\<open>antisym r\\<close> have \"antisym ?r\"\n    unfolding antisym_def by blast\n  moreover from \\<open>Total r\\<close> have \"Total ?r\"\n    by (simp add:total_on_def 1 univ)\n  moreover have \"wf (?r - Id)\"\n    by (rule wf_subset [OF \\<open>wf (r - Id)\\<close>]) blast\n  ultimately have \"Well_order ?r\"\n    by (simp add: order_on_defs)\n  with 1 show ?thesis by auto\nqed\n\nlemma dependent_wf_choice:\n  fixes P :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  assumes \"wf R\"\n    and adm: \"\\<And>f g x r. (\\<And>z. (z, x) \\<in> R \\<Longrightarrow> f z = g z) \\<Longrightarrow> P f x r = P g x r\"\n    and P: \"\\<And>x f. (\\<And>y. (y, x) \\<in> R \\<Longrightarrow> P f y (f y)) \\<Longrightarrow> \\<exists>r. P f x r\"\n  shows \"\\<exists>f. \\<forall>x. P f x (f x)\"\nproof (intro exI allI)\n  fix x\n  define f where \"f \\<equiv> wfrec R (\\<lambda>f x. SOME r. P f x r)\"\n  from \\<open>wf R\\<close> show \"P f x (f x)\"\n  proof (induct x)\n    case (less x)\n    show \"P f x (f x)\"\n    proof (subst (2) wfrec_def_adm[OF f_def \\<open>wf R\\<close>])\n      show \"adm_wf R (\\<lambda>f x. SOME r. P f x r)\"\n        by (auto simp: adm_wf_def intro!: arg_cong[where f=Eps] adm)\n      show \"P f x (Eps (P f x))\"\n        using P by (rule someI_ex) fact\n    qed\n  qed\nqed\n\nlemma (in wellorder) dependent_wellorder_choice:\n  assumes \"\\<And>r f g x. (\\<And>y. y < x \\<Longrightarrow> f y = g y) \\<Longrightarrow> P f x r = P g x r\"\n    and P: \"\\<And>x f. (\\<And>y. y < x \\<Longrightarrow> P f y (f y)) \\<Longrightarrow> \\<exists>r. P f x r\"\n  shows \"\\<exists>f. \\<forall>x. P f x (f x)\"\n  using wf by (rule dependent_wf_choice) (auto intro!: assms)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Zorn.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240686758841, "lm_q2_score": 0.8824278602705731, "lm_q1q2_score": 0.7634978235762597}}
{"text": "(*  Title:      HOL/Computational_Algebra/Primes.thy\n    Author:     Christophe Tabacznyj\n    Author:     Lawrence C. Paulson\n    Author:     Amine Chaieb\n    Author:     Thomas M. Rasmussen\n    Author:     Jeremy Avigad\n    Author:     Tobias Nipkow\n    Author:     Manuel Eberl\n\nThis theory deals with properties of primes. Definitions and lemmas are\nproved uniformly for the natural numbers and integers.\n\nThis file combines and revises a number of prior developments.\n\nThe original theories \"GCD\" and \"Primes\" were by Christophe Tabacznyj\nand Lawrence C. Paulson, based on @{cite davenport92}. They introduced\ngcd, lcm, and prime for the natural numbers.\n\nThe original theory \"IntPrimes\" was by Thomas M. Rasmussen, and\nextended gcd, lcm, primes to the integers. Amine Chaieb provided\nanother extension of the notions to the integers, and added a number\nof results to \"Primes\" and \"GCD\". IntPrimes also defined and developed\nthe congruence relations on the integers. The notion was extended to\nthe natural numbers by Chaieb.\n\nJeremy Avigad combined all of these, made everything uniform for the\nnatural numbers and the integers, and added a number of new theorems.\n\nTobias Nipkow cleaned up a lot.\n\nFlorian Haftmann and Manuel Eberl put primality and prime factorisation\nonto an algebraic foundation and thus generalised these concepts to \nother rings, such as polynomials. (see also the Factorial_Ring theory).\n\nThere were also previous formalisations of unique factorisation by \nThomas Marthedal Rasmussen, Jeremy Avigad, and David Gray.\n*)\n\nsection \\<open>Primes\\<close>\n\ntheory Primes\nimports Euclidean_Algorithm\nbegin\n\nsubsection \\<open>Primes on \\<^typ>\\<open>nat\\<close> and \\<^typ>\\<open>int\\<close>\\<close>\n\nlemma Suc_0_not_prime_nat [simp]: \"\\<not> prime (Suc 0)\"\n  using not_prime_1 [where ?'a = nat] by simp\n\nlemma prime_ge_2_nat:\n  \"p \\<ge> 2\" if \"prime p\" for p :: nat\nproof -\n  from that have \"p \\<noteq> 0\" and \"p \\<noteq> 1\"\n    by (auto dest: prime_elem_not_zeroI prime_elem_not_unit)\n  then show ?thesis\n    by simp\nqed\n\nlemma prime_ge_2_int:\n  \"p \\<ge> 2\" if \"prime p\" for p :: int\nproof -\n  from that have \"prime_elem p\" and \"\\<bar>p\\<bar> = p\"\n    by (auto dest: normalize_prime)\n  then have \"p \\<noteq> 0\" and \"\\<bar>p\\<bar> \\<noteq> 1\" and \"p \\<ge> 0\"\n    by (auto dest: prime_elem_not_zeroI prime_elem_not_unit)\n  then show ?thesis\n    by simp\nqed\n\nlemma prime_ge_0_int: \"prime p \\<Longrightarrow> p \\<ge> (0::int)\"\n  using prime_ge_2_int [of p] by simp\n\nlemma prime_gt_0_nat: \"prime p \\<Longrightarrow> p > (0::nat)\"\n  using prime_ge_2_nat [of p] by simp\n\n(* As a simp or intro rule,\n\n     prime p \\<Longrightarrow> p > 0\n\n   wreaks havoc here. When the premise includes \\<forall>x \\<in># M. prime x, it\n   leads to the backchaining\n\n     x > 0\n     prime x\n     x \\<in># M   which is, unfortunately,\n     count M x > 0  FIXME no, this is obsolete\n*)\n\nlemma prime_gt_0_int: \"prime p \\<Longrightarrow> p > (0::int)\"\n  using prime_ge_2_int [of p] by simp\n\nlemma prime_ge_1_nat: \"prime p \\<Longrightarrow> p \\<ge> (1::nat)\"\n  using prime_ge_2_nat [of p] by simp\n\nlemma prime_ge_Suc_0_nat: \"prime p \\<Longrightarrow> p \\<ge> Suc 0\"\n  using prime_ge_1_nat [of p] by simp\n\nlemma prime_ge_1_int: \"prime p \\<Longrightarrow> p \\<ge> (1::int)\"\n  using prime_ge_2_int [of p] by simp\n\nlemma prime_gt_1_nat: \"prime p \\<Longrightarrow> p > (1::nat)\"\n  using prime_ge_2_nat [of p] by simp\n\nlemma prime_gt_Suc_0_nat: \"prime p \\<Longrightarrow> p > Suc 0\"\n  using prime_gt_1_nat [of p] by simp\n\nlemma prime_gt_1_int: \"prime p \\<Longrightarrow> p > (1::int)\"\n  using prime_ge_2_int [of p] by simp\n\nlemma prime_natI:\n  \"prime p\" if \"p \\<ge> 2\" and \"\\<And>m n. p dvd m * n \\<Longrightarrow> p dvd m \\<or> p dvd n\" for p :: nat\n  using that by (auto intro!: primeI prime_elemI)\n\nlemma prime_intI:\n  \"prime p\" if \"p \\<ge> 2\" and \"\\<And>m n. p dvd m * n \\<Longrightarrow> p dvd m \\<or> p dvd n\" for p :: int\n  using that by (auto intro!: primeI prime_elemI)\n\nlemma prime_elem_nat_iff [simp]:\n  \"prime_elem n \\<longleftrightarrow> prime n\" for n :: nat\n  by (simp add: prime_def)\n\nlemma prime_elem_iff_prime_abs [simp]:\n  \"prime_elem k \\<longleftrightarrow> prime \\<bar>k\\<bar>\" for k :: int\n  by (auto intro: primeI)\n\nlemma prime_nat_int_transfer [simp]:\n  \"prime (int n) \\<longleftrightarrow> prime n\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume ?P\n  then have \"n \\<ge> 2\"\n    by (auto dest: prime_ge_2_int)\n  then show ?Q\n  proof (rule prime_natI)\n    fix r s\n    assume \"n dvd r * s\"\n    with of_nat_dvd_iff [of n \"r * s\"] have \"int n dvd int r * int s\"\n      by simp\n    with \\<open>?P\\<close> have \"int n dvd int r \\<or> int n dvd int s\"\n      using prime_dvd_mult_iff [of \"int n\" \"int r\" \"int s\"]\n      by simp\n    then show \"n dvd r \\<or> n dvd s\"\n      by simp\n  qed\nnext\n  assume ?Q\n  then have \"int n \\<ge> 2\"\n    by (auto dest: prime_ge_2_nat)\n  then show ?P\n  proof (rule prime_intI)\n    fix r s\n    assume \"int n dvd r * s\"\n    then have \"n dvd nat \\<bar>r * s\\<bar>\"\n      by simp\n    then have \"n dvd nat \\<bar>r\\<bar> * nat \\<bar>s\\<bar>\"\n      by (simp add: nat_abs_mult_distrib)\n    with \\<open>?Q\\<close> have \"n dvd nat \\<bar>r\\<bar> \\<or> n dvd nat \\<bar>s\\<bar>\"\n      using prime_dvd_mult_iff [of \"n\" \"nat \\<bar>r\\<bar>\" \"nat \\<bar>s\\<bar>\"]\n      by simp\n    then show \"int n dvd r \\<or> int n dvd s\"\n      by simp\n  qed\nqed\n\nlemma prime_nat_iff_prime [simp]:\n  \"prime (nat k) \\<longleftrightarrow> prime k\"\nproof (cases \"k \\<ge> 0\")\n  case True\n  then show ?thesis\n    using prime_nat_int_transfer [of \"nat k\"] by simp\nnext\n  case False\n  then show ?thesis\n    by (auto dest: prime_ge_2_int)\nqed\n\nlemma prime_int_nat_transfer:\n  \"prime k \\<longleftrightarrow> k \\<ge> 0 \\<and> prime (nat k)\"\n  by (auto dest: prime_ge_2_int)\n\nlemma prime_nat_naiveI:\n  \"prime p\" if \"p \\<ge> 2\" and dvd: \"\\<And>n. n dvd p \\<Longrightarrow> n = 1 \\<or> n = p\" for p :: nat\nproof (rule primeI, rule prime_elemI)\n  fix m n :: nat\n  assume \"p dvd m * n\"\n  then obtain r s where \"p = r * s\" \"r dvd m\" \"s dvd n\"\n    by (blast dest: division_decomp)\n  moreover have \"r = 1 \\<or> r = p\"\n    using \\<open>r dvd m\\<close> \\<open>p = r * s\\<close> dvd [of r] by simp\n  ultimately show \"p dvd m \\<or> p dvd n\"\n    by auto\nqed (use \\<open>p \\<ge> 2\\<close> in simp_all)\n\nlemma prime_int_naiveI:\n  \"prime p\" if \"p \\<ge> 2\" and dvd: \"\\<And>k. k dvd p \\<Longrightarrow> \\<bar>k\\<bar> = 1 \\<or> \\<bar>k\\<bar> = p\" for p :: int\nproof -\n  from \\<open>p \\<ge> 2\\<close> have \"nat p \\<ge> 2\"\n    by simp\n  then have \"prime (nat p)\"\n  proof (rule prime_nat_naiveI)\n    fix n\n    assume \"n dvd nat p\"\n    with \\<open>p \\<ge> 2\\<close> have \"n dvd nat \\<bar>p\\<bar>\"\n      by simp\n    then have \"int n dvd p\"\n      by simp\n    with dvd [of \"int n\"] show \"n = 1 \\<or> n = nat p\"\n      by auto\n  qed\n  then show ?thesis\n    by simp\nqed\n\nlemma prime_nat_iff:\n  \"prime (n :: nat) \\<longleftrightarrow> (1 < n \\<and> (\\<forall>m. m dvd n \\<longrightarrow> m = 1 \\<or> m = n))\"\nproof (safe intro!: prime_gt_1_nat)\n  assume \"prime n\"\n  then have *: \"prime_elem n\"\n    by simp\n  fix m assume m: \"m dvd n\" \"m \\<noteq> n\"\n  from * \\<open>m dvd n\\<close> have \"n dvd m \\<or> is_unit m\"\n    by (intro irreducibleD' prime_elem_imp_irreducible)\n  with m show \"m = 1\" by (auto dest: dvd_antisym)\nnext\n  assume \"n > 1\" \"\\<forall>m. m dvd n \\<longrightarrow> m = 1 \\<or> m = n\"\n  then show \"prime n\"\n    using prime_nat_naiveI [of n] by auto\nqed\n\nlemma prime_int_iff:\n  \"prime (n::int) \\<longleftrightarrow> (1 < n \\<and> (\\<forall>m. m \\<ge> 0 \\<and> m dvd n \\<longrightarrow> m = 1 \\<or> m = n))\"\nproof (intro iffI conjI allI impI; (elim conjE)?)\n  assume *: \"prime n\"\n  hence irred: \"irreducible n\" by (auto intro: prime_elem_imp_irreducible)\n  from * have \"n \\<ge> 0\" \"n \\<noteq> 0\" \"n \\<noteq> 1\"\n    by (auto simp add: prime_ge_0_int)\n  thus \"n > 1\" by presburger\n  fix m assume \"m dvd n\" \\<open>m \\<ge> 0\\<close>\n  with irred have \"m dvd 1 \\<or> n dvd m\" by (auto simp: irreducible_altdef)\n  with \\<open>m dvd n\\<close> \\<open>m \\<ge> 0\\<close> \\<open>n > 1\\<close> show \"m = 1 \\<or> m = n\"\n    using associated_iff_dvd[of m n] by auto\nnext\n  assume n: \"1 < n\" \"\\<forall>m. m \\<ge> 0 \\<and> m dvd n \\<longrightarrow> m = 1 \\<or> m = n\"\n  hence \"nat n > 1\" by simp\n  moreover have \"\\<forall>m. m dvd nat n \\<longrightarrow> m = 1 \\<or> m = nat n\"\n  proof (intro allI impI)\n    fix m assume \"m dvd nat n\"\n    with \\<open>n > 1\\<close> have \"m dvd nat \\<bar>n\\<bar>\"\n      by simp\n    then have \"int m dvd n\"\n      by simp\n    with n(2) have \"int m = 1 \\<or> int m = n\"\n      using of_nat_0_le_iff by blast\n    thus \"m = 1 \\<or> m = nat n\" by auto\n  qed\n  ultimately show \"prime n\" \n    unfolding prime_int_nat_transfer prime_nat_iff by auto\nqed\n\nlemma prime_nat_not_dvd:\n  assumes \"prime p\" \"p > n\" \"n \\<noteq> (1::nat)\"\n  shows   \"\\<not>n dvd p\"\nproof\n  assume \"n dvd p\"\n  from assms(1) have \"irreducible p\" by (simp add: prime_elem_imp_irreducible)\n  from irreducibleD'[OF this \\<open>n dvd p\\<close>] \\<open>n dvd p\\<close> \\<open>p > n\\<close> assms show False\n    by (cases \"n = 0\") (auto dest!: dvd_imp_le)\nqed\n\nlemma prime_int_not_dvd:\n  assumes \"prime p\" \"p > n\" \"n > (1::int)\"\n  shows   \"\\<not>n dvd p\"\nproof\n  assume \"n dvd p\"\n  from assms(1) have \"irreducible p\" by (auto intro: prime_elem_imp_irreducible)\n  from irreducibleD'[OF this \\<open>n dvd p\\<close>] \\<open>n dvd p\\<close> \\<open>p > n\\<close> assms show False\n    by (auto dest!: zdvd_imp_le)\nqed\n\nlemma prime_odd_nat: \"prime p \\<Longrightarrow> p > (2::nat) \\<Longrightarrow> odd p\"\n  by (intro prime_nat_not_dvd) auto\n\nlemma prime_odd_int: \"prime p \\<Longrightarrow> p > (2::int) \\<Longrightarrow> odd p\"\n  by (intro prime_int_not_dvd) auto\n\nlemma prime_int_altdef:\n  \"prime p = (1 < p \\<and> (\\<forall>m::int. m \\<ge> 0 \\<longrightarrow> m dvd p \\<longrightarrow>\n    m = 1 \\<or> m = p))\"\n  unfolding prime_int_iff by blast\n\nlemma not_prime_eq_prod_nat:\n  assumes \"m > 1\" \"\\<not> prime (m::nat)\"\n  shows   \"\\<exists>n k. n = m * k \\<and> 1 < m \\<and> m < n \\<and> 1 < k \\<and> k < n\"\n  using assms irreducible_altdef[of m]\n  by (auto simp: prime_elem_iff_irreducible irreducible_altdef)\n\n    \nsubsection \\<open>Largest exponent of a prime factor\\<close>\n\ntext\\<open>Possibly duplicates other material, but avoid the complexities of multisets.\\<close>\n  \nlemma prime_power_cancel_less:\n  assumes \"prime p\" and eq: \"m * (p ^ k) = m' * (p ^ k')\" and less: \"k < k'\" and \"\\<not> p dvd m\"\n  shows False\nproof -\n  obtain l where l: \"k' = k + l\" and \"l > 0\"\n    using less less_imp_add_positive by auto\n  have \"m = m * (p ^ k) div (p ^ k)\"\n    using \\<open>prime p\\<close> by simp\n  also have \"\\<dots> = m' * (p ^ k') div (p ^ k)\"\n    using eq by simp\n  also have \"\\<dots> = m' * (p ^ l) * (p ^ k) div (p ^ k)\"\n    by (simp add: l mult.commute mult.left_commute power_add)\n  also have \"... = m' * (p ^ l)\"\n    using \\<open>prime p\\<close> by simp\n  finally have \"p dvd m\"\n    using \\<open>l > 0\\<close> by simp\n  with assms show False\n    by simp\nqed\n\nlemma prime_power_cancel:\n  assumes \"prime p\" and eq: \"m * (p ^ k) = m' * (p ^ k')\" and \"\\<not> p dvd m\" \"\\<not> p dvd m'\"\n  shows \"k = k'\"\n  using prime_power_cancel_less [OF \\<open>prime p\\<close>] assms\n  by (metis linorder_neqE_nat)\n\nlemma prime_power_cancel2:\n  assumes \"prime p\" \"m * (p ^ k) = m' * (p ^ k')\" \"\\<not> p dvd m\" \"\\<not> p dvd m'\"\n  obtains \"m = m'\" \"k = k'\"\n  using prime_power_cancel [OF assms] assms by auto\n\nlemma prime_power_canonical:\n  fixes m :: nat\n  assumes \"prime p\" \"m > 0\"\n  shows \"\\<exists>k n. \\<not> p dvd n \\<and> m = n * p ^ k\"\nusing \\<open>m > 0\\<close>\nproof (induction m rule: less_induct)\n  case (less m)\n  show ?case\n  proof (cases \"p dvd m\")\n    case True\n    then obtain m' where m': \"m = p * m'\"\n      using dvdE by blast\n    with \\<open>prime p\\<close> have \"0 < m'\" \"m' < m\"\n      using less.prems prime_nat_iff by auto\n    with m' less show ?thesis\n      by (metis power_Suc mult.left_commute)\n  next\n    case False\n    then show ?thesis\n      by (metis mult.right_neutral power_0)\n  qed\nqed\n\n\nsubsubsection \\<open>Make prime naively executable\\<close>\n\nlemma prime_nat_iff':\n  \"prime (p :: nat) \\<longleftrightarrow> p > 1 \\<and> (\\<forall>n \\<in> {2..<p}. \\<not> n dvd p)\"\nproof safe\n  assume \"p > 1\" and *: \"\\<forall>n\\<in>{2..<p}. \\<not>n dvd p\"\n  show \"prime p\" unfolding prime_nat_iff\n  proof (intro conjI allI impI)\n    fix m assume \"m dvd p\"\n    with \\<open>p > 1\\<close> have \"m \\<noteq> 0\" by (intro notI) auto\n    hence \"m \\<ge> 1\" by simp\n    moreover from \\<open>m dvd p\\<close> and * have \"m \\<notin> {2..<p}\" by blast\n    with \\<open>m dvd p\\<close> and \\<open>p > 1\\<close> have \"m \\<le> 1 \\<or> m = p\" by (auto dest: dvd_imp_le)\n    ultimately show \"m = 1 \\<or> m = p\" by simp\n  qed fact+\nqed (auto simp: prime_nat_iff)\n\nlemma prime_int_iff':\n  \"prime (p :: int) \\<longleftrightarrow> p > 1 \\<and> (\\<forall>n \\<in> {2..<p}. \\<not> n dvd p)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof (cases \"p \\<ge> 0\")\n  case True\n  have \"?P \\<longleftrightarrow> prime (nat p)\"\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> p > 1 \\<and> (\\<forall>n\\<in>{2..<nat p}. \\<not> n dvd nat \\<bar>p\\<bar>)\"\n    using True by (simp add: prime_nat_iff')\n  also have \"{2..<nat p} = nat ` {2..<p}\"\n    using True int_eq_iff by fastforce \n  finally show \"?P \\<longleftrightarrow> ?Q\" by simp\nnext\n  case False\n  then show ?thesis\n    by (auto simp add: prime_ge_0_int) \nqed\n\nlemma prime_int_numeral_eq [simp]:\n  \"prime (numeral m :: int) \\<longleftrightarrow> prime (numeral m :: nat)\"\n  by (simp add: prime_int_nat_transfer)\n\nlemma two_is_prime_nat [simp]: \"prime (2::nat)\"\n  by (simp add: prime_nat_iff')\n\nlemma prime_nat_numeral_eq [simp]:\n  \"prime (numeral m :: nat) \\<longleftrightarrow>\n    (1::nat) < numeral m \\<and>\n    (\\<forall>n::nat \\<in> set [2..<numeral m]. \\<not> n dvd numeral m)\"\n  by (simp only: prime_nat_iff' set_upt)  \\<comment> \\<open>TODO Sieve Of Erathosthenes might speed this up\\<close>\n\n\ntext\\<open>A bit of regression testing:\\<close>\n\nlemma \"prime(97::nat)\" by simp\nlemma \"prime(97::int)\" by simp\n\nlemma prime_factor_nat: \n  \"n \\<noteq> (1::nat) \\<Longrightarrow> \\<exists>p. prime p \\<and> p dvd n\"\n  using prime_divisor_exists[of n]\n  by (cases \"n = 0\") (auto intro: exI[of _ \"2::nat\"])\n\nlemma prime_factor_int:\n  fixes k :: int\n  assumes \"\\<bar>k\\<bar> \\<noteq> 1\"\n  obtains p where \"prime p\" \"p dvd k\"\nproof (cases \"k = 0\")\n  case True\n  then have \"prime (2::int)\" and \"2 dvd k\"\n    by simp_all\n  with that show thesis\n    by blast\nnext\n  case False\n  with assms prime_divisor_exists [of k] obtain p where \"prime p\" \"p dvd k\"\n    by auto\n  with that show thesis\n    by blast\nqed\n\n\nsubsection \\<open>Infinitely many primes\\<close>\n\nlemma next_prime_bound: \"\\<exists>p::nat. prime p \\<and> n < p \\<and> p \\<le> fact n + 1\"\nproof-\n  have f1: \"fact n + 1 \\<noteq> (1::nat)\" using fact_ge_1 [of n, where 'a=nat] by arith\n  from prime_factor_nat [OF f1]\n  obtain p :: nat where \"prime p\" and \"p dvd fact n + 1\" by auto\n  then have \"p \\<le> fact n + 1\" apply (intro dvd_imp_le) apply auto done\n  { assume \"p \\<le> n\"\n    from \\<open>prime p\\<close> have \"p \\<ge> 1\"\n      by (cases p, simp_all)\n    with \\<open>p <= n\\<close> have \"p dvd fact n\"\n      by (intro dvd_fact)\n    with \\<open>p dvd fact n + 1\\<close> have \"p dvd fact n + 1 - fact n\"\n      by (rule dvd_diff_nat)\n    then have \"p dvd 1\" by simp\n    then have \"p <= 1\" by auto\n    moreover from \\<open>prime p\\<close> have \"p > 1\"\n      using prime_nat_iff by blast\n    ultimately have False by auto}\n  then have \"n < p\" by presburger\n  with \\<open>prime p\\<close> and \\<open>p <= fact n + 1\\<close> show ?thesis by auto\nqed\n\nlemma bigger_prime: \"\\<exists>p. prime p \\<and> p > (n::nat)\"\n  using next_prime_bound by auto\n\nlemma primes_infinite: \"\\<not> (finite {(p::nat). prime p})\"\nproof\n  assume \"finite {(p::nat). prime p}\"\n  with Max_ge have \"(\\<exists>b. (\\<forall>x \\<in> {(p::nat). prime p}. x \\<le> b))\"\n    by auto\n  then obtain b where \"\\<forall>(x::nat). prime x \\<longrightarrow> x \\<le> b\"\n    by auto\n  with bigger_prime [of b] show False\n    by auto\nqed\n\nsubsection \\<open>Powers of Primes\\<close>\n\ntext\\<open>Versions for type nat only\\<close>\n\nlemma prime_product:\n  fixes p::nat\n  assumes \"prime (p * q)\"\n  shows \"p = 1 \\<or> q = 1\"\nproof -\n  from assms have\n    \"1 < p * q\" and P: \"\\<And>m. m dvd p * q \\<Longrightarrow> m = 1 \\<or> m = p * q\"\n    unfolding prime_nat_iff by auto\n  from \\<open>1 < p * q\\<close> have \"p \\<noteq> 0\" by (cases p) auto\n  then have Q: \"p = p * q \\<longleftrightarrow> q = 1\" by auto\n  have \"p dvd p * q\" by simp\n  then have \"p = 1 \\<or> p = p * q\" by (rule P)\n  then show ?thesis by (simp add: Q)\nqed\n\n(* TODO: Generalise? *)\nlemma prime_power_mult_nat:\n  fixes p :: nat\n  assumes p: \"prime p\" and xy: \"x * y = p ^ k\"\n  shows \"\\<exists>i j. x = p ^ i \\<and> y = p^ j\"\nusing xy\nproof(induct k arbitrary: x y)\n  case 0 thus ?case apply simp by (rule exI[where x=\"0\"], simp)\nnext\n  case (Suc k x y)\n  from Suc.prems have pxy: \"p dvd x*y\" by auto\n  from prime_dvd_multD [OF p pxy] have pxyc: \"p dvd x \\<or> p dvd y\" .\n  from p have p0: \"p \\<noteq> 0\" by - (rule ccontr, simp)\n  {assume px: \"p dvd x\"\n    then obtain d where d: \"x = p*d\" unfolding dvd_def by blast\n    from Suc.prems d  have \"p*d*y = p^Suc k\" by simp\n    hence th: \"d*y = p^k\" using p0 by simp\n    from Suc.hyps[OF th] obtain i j where ij: \"d = p^i\" \"y = p^j\" by blast\n    with d have \"x = p^Suc i\" by simp\n    with ij(2) have ?case by blast}\n  moreover\n  {assume px: \"p dvd y\"\n    then obtain d where d: \"y = p*d\" unfolding dvd_def by blast\n    from Suc.prems d  have \"p*d*x = p^Suc k\" by (simp add: mult.commute)\n    hence th: \"d*x = p^k\" using p0 by simp\n    from Suc.hyps[OF th] obtain i j where ij: \"d = p^i\" \"x = p^j\" by blast\n    with d have \"y = p^Suc i\" by simp\n    with ij(2) have ?case by blast}\n  ultimately show ?case  using pxyc by blast\nqed\n\nlemma prime_power_exp_nat:\n  fixes p::nat\n  assumes p: \"prime p\" and n: \"n \\<noteq> 0\"\n    and xn: \"x^n = p^k\" shows \"\\<exists>i. x = p^i\"\n  using n xn\nproof(induct n arbitrary: k)\n  case 0 thus ?case by simp\nnext\n  case (Suc n k) hence th: \"x*x^n = p^k\" by simp\n  {assume \"n = 0\" with Suc have ?case by simp (rule exI[where x=\"k\"], simp)}\n  moreover\n  {assume n: \"n \\<noteq> 0\"\n    from prime_power_mult_nat[OF p th]\n    obtain i j where ij: \"x = p^i\" \"x^n = p^j\"by blast\n    from Suc.hyps[OF n ij(2)] have ?case .}\n  ultimately show ?case by blast\nqed\n\nlemma divides_primepow_nat:\n  fixes p :: nat\n  assumes p: \"prime p\"\n  shows \"d dvd p ^ k \\<longleftrightarrow> (\\<exists>i\\<le>k. d = p ^ i)\"\n  using assms divides_primepow [of p d k] by (auto intro: le_imp_power_dvd)\n\n\nsubsection \\<open>Chinese Remainder Theorem Variants\\<close>\n\nlemma bezout_gcd_nat:\n  fixes a::nat shows \"\\<exists>x y. a * x - b * y = gcd a b \\<or> b * x - a * y = gcd a b\"\n  using bezout_nat[of a b]\nby (metis bezout_nat diff_add_inverse gcd_add_mult gcd.commute\n  gcd_nat.right_neutral mult_0)\n\nlemma gcd_bezout_sum_nat:\n  fixes a::nat\n  assumes \"a * x + b * y = d\"\n  shows \"gcd a b dvd d\"\nproof-\n  let ?g = \"gcd a b\"\n    have dv: \"?g dvd a*x\" \"?g dvd b * y\"\n      by simp_all\n    from dvd_add[OF dv] assms\n    show ?thesis by auto\nqed\n\n\ntext \\<open>A binary form of the Chinese Remainder Theorem.\\<close>\n\n(* TODO: Generalise? *)\nlemma chinese_remainder:\n  fixes a::nat  assumes ab: \"coprime a b\" and a: \"a \\<noteq> 0\" and b: \"b \\<noteq> 0\"\n  shows \"\\<exists>x q1 q2. x = u + q1 * a \\<and> x = v + q2 * b\"\nproof-\n  from bezout_add_strong_nat[OF a, of b] bezout_add_strong_nat[OF b, of a]\n  obtain d1 x1 y1 d2 x2 y2 where dxy1: \"d1 dvd a\" \"d1 dvd b\" \"a * x1 = b * y1 + d1\"\n    and dxy2: \"d2 dvd b\" \"d2 dvd a\" \"b * x2 = a * y2 + d2\" by blast\n  then have d12: \"d1 = 1\" \"d2 = 1\"\n    using ab coprime_common_divisor_nat [of a b] by blast+\n  let ?x = \"v * a * x1 + u * b * x2\"\n  let ?q1 = \"v * x1 + u * y2\"\n  let ?q2 = \"v * y1 + u * x2\"\n  from dxy2(3)[simplified d12] dxy1(3)[simplified d12]\n  have \"?x = u + ?q1 * a\" \"?x = v + ?q2 * b\"\n    by algebra+\n  thus ?thesis by blast\nqed\n\ntext \\<open>Primality\\<close>\n\nlemma coprime_bezout_strong:\n  fixes a::nat assumes \"coprime a b\"  \"b \\<noteq> 1\"\n  shows \"\\<exists>x y. a * x = b * y + 1\"\n  by (metis add.commute add.right_neutral assms(1) assms(2) chinese_remainder coprime_1_left coprime_1_right coprime_crossproduct_nat mult.commute mult.right_neutral mult_cancel_left)\n\nlemma bezout_prime:\n  assumes p: \"prime p\" and pa: \"\\<not> p dvd a\"\n  shows \"\\<exists>x y. a*x = Suc (p*y)\"\nproof -\n  have ap: \"coprime a p\"\n    using coprime_commute p pa prime_imp_coprime by auto\n  moreover from p have \"p \\<noteq> 1\" by auto\n  ultimately have \"\\<exists>x y. a * x = p * y + 1\"\n    by (rule coprime_bezout_strong)\n  then show ?thesis by simp    \nqed\n(* END TODO *)\n\n\n\nsubsection \\<open>Multiplicity and primality for natural numbers and integers\\<close>\n\nlemma prime_factors_gt_0_nat:\n  \"p \\<in> prime_factors x \\<Longrightarrow> p > (0::nat)\"\n  by (simp add: in_prime_factors_imp_prime prime_gt_0_nat)\n\nlemma prime_factors_gt_0_int:\n  \"p \\<in> prime_factors x \\<Longrightarrow> p > (0::int)\"\n  by (simp add: in_prime_factors_imp_prime prime_gt_0_int)\n\nlemma prime_factors_ge_0_int [elim]: (* FIXME !? *)\n  fixes n :: int\n  shows \"p \\<in> prime_factors n \\<Longrightarrow> p \\<ge> 0\"\n  by (drule prime_factors_gt_0_int) simp\n  \nlemma prod_mset_prime_factorization_int:\n  fixes n :: int\n  assumes \"n > 0\"\n  shows   \"prod_mset (prime_factorization n) = n\"\n  using assms by (simp add: prod_mset_prime_factorization)\n\nlemma prime_factorization_exists_nat:\n  \"n > 0 \\<Longrightarrow> (\\<exists>M. (\\<forall>p::nat \\<in> set_mset M. prime p) \\<and> n = (\\<Prod>i \\<in># M. i))\"\n  using prime_factorization_exists[of n] by auto\n\nlemma prod_mset_prime_factorization_nat [simp]: \n  \"(n::nat) > 0 \\<Longrightarrow> prod_mset (prime_factorization n) = n\"\n  by (subst prod_mset_prime_factorization) simp_all\n\nlemma prime_factorization_nat:\n    \"n > (0::nat) \\<Longrightarrow> n = (\\<Prod>p \\<in> prime_factors n. p ^ multiplicity p n)\"\n  by (simp add: prod_prime_factors)\n\nlemma prime_factorization_int:\n    \"n > (0::int) \\<Longrightarrow> n = (\\<Prod>p \\<in> prime_factors n. p ^ multiplicity p n)\"\n  by (simp add: prod_prime_factors)\n\nlemma prime_factorization_unique_nat:\n  fixes f :: \"nat \\<Rightarrow> _\"\n  assumes S_eq: \"S = {p. 0 < f p}\"\n    and \"finite S\"\n    and S: \"\\<forall>p\\<in>S. prime p\" \"n = (\\<Prod>p\\<in>S. p ^ f p)\"\n  shows \"S = prime_factors n \\<and> (\\<forall>p. prime p \\<longrightarrow> f p = multiplicity p n)\"\n  using assms by (intro prime_factorization_unique'') auto\n\nlemma prime_factorization_unique_int:\n  fixes f :: \"int \\<Rightarrow> _\"\n  assumes S_eq: \"S = {p. 0 < f p}\"\n    and \"finite S\"\n    and S: \"\\<forall>p\\<in>S. prime p\" \"abs n = (\\<Prod>p\\<in>S. p ^ f p)\"\n  shows \"S = prime_factors n \\<and> (\\<forall>p. prime p \\<longrightarrow> f p = multiplicity p n)\"\n  using assms by (intro prime_factorization_unique'') auto\n\nlemma prime_factors_characterization_nat:\n  \"S = {p. 0 < f (p::nat)} \\<Longrightarrow>\n    finite S \\<Longrightarrow> \\<forall>p\\<in>S. prime p \\<Longrightarrow> n = (\\<Prod>p\\<in>S. p ^ f p) \\<Longrightarrow> prime_factors n = S\"\n  by (rule prime_factorization_unique_nat [THEN conjunct1, symmetric])\n\nlemma prime_factors_characterization'_nat:\n  \"finite {p. 0 < f (p::nat)} \\<Longrightarrow>\n    (\\<forall>p. 0 < f p \\<longrightarrow> prime p) \\<Longrightarrow>\n      prime_factors (\\<Prod>p | 0 < f p. p ^ f p) = {p. 0 < f p}\"\n  by (rule prime_factors_characterization_nat) auto\n\nlemma prime_factors_characterization_int:\n  \"S = {p. 0 < f (p::int)} \\<Longrightarrow> finite S \\<Longrightarrow>\n    \\<forall>p\\<in>S. prime p \\<Longrightarrow> abs n = (\\<Prod>p\\<in>S. p ^ f p) \\<Longrightarrow> prime_factors n = S\"\n  by (rule prime_factorization_unique_int [THEN conjunct1, symmetric])\n\n(* TODO Move *)\nlemma abs_prod: \"abs (prod f A :: 'a :: linordered_idom) = prod (\\<lambda>x. abs (f x)) A\"\n  by (cases \"finite A\", induction A rule: finite_induct) (simp_all add: abs_mult)\n\nlemma primes_characterization'_int [rule_format]:\n  \"finite {p. p \\<ge> 0 \\<and> 0 < f (p::int)} \\<Longrightarrow> \\<forall>p. 0 < f p \\<longrightarrow> prime p \\<Longrightarrow>\n      prime_factors (\\<Prod>p | p \\<ge> 0 \\<and> 0 < f p. p ^ f p) = {p. p \\<ge> 0 \\<and> 0 < f p}\"\n  by (rule prime_factors_characterization_int) (auto simp: abs_prod prime_ge_0_int)\n\nlemma multiplicity_characterization_nat:\n  \"S = {p. 0 < f (p::nat)} \\<Longrightarrow> finite S \\<Longrightarrow> \\<forall>p\\<in>S. prime p \\<Longrightarrow> prime p \\<Longrightarrow>\n    n = (\\<Prod>p\\<in>S. p ^ f p) \\<Longrightarrow> multiplicity p n = f p\"\n  by (frule prime_factorization_unique_nat [of S f n, THEN conjunct2, rule_format, symmetric]) auto\n\nlemma multiplicity_characterization'_nat: \"finite {p. 0 < f (p::nat)} \\<longrightarrow>\n    (\\<forall>p. 0 < f p \\<longrightarrow> prime p) \\<longrightarrow> prime p \\<longrightarrow>\n      multiplicity p (\\<Prod>p | 0 < f p. p ^ f p) = f p\"\n  by (intro impI, rule multiplicity_characterization_nat) auto\n\nlemma multiplicity_characterization_int: \"S = {p. 0 < f (p::int)} \\<Longrightarrow>\n    finite S \\<Longrightarrow> \\<forall>p\\<in>S. prime p \\<Longrightarrow> prime p \\<Longrightarrow> n = (\\<Prod>p\\<in>S. p ^ f p) \\<Longrightarrow> multiplicity p n = f p\"\n  by (frule prime_factorization_unique_int [of S f n, THEN conjunct2, rule_format, symmetric]) \n     (auto simp: abs_prod power_abs prime_ge_0_int intro!: prod.cong)\n\nlemma multiplicity_characterization'_int [rule_format]:\n  \"finite {p. p \\<ge> 0 \\<and> 0 < f (p::int)} \\<Longrightarrow>\n    (\\<forall>p. 0 < f p \\<longrightarrow> prime p) \\<Longrightarrow> prime p \\<Longrightarrow>\n      multiplicity p (\\<Prod>p | p \\<ge> 0 \\<and> 0 < f p. p ^ f p) = f p\"\n  by (rule multiplicity_characterization_int) (auto simp: prime_ge_0_int)\n\nlemma multiplicity_one_nat [simp]: \"multiplicity p (Suc 0) = 0\"\n  unfolding One_nat_def [symmetric] by (rule multiplicity_one)\n\nlemma multiplicity_eq_nat:\n  fixes x and y::nat\n  assumes \"x > 0\" \"y > 0\" \"\\<And>p. prime p \\<Longrightarrow> multiplicity p x = multiplicity p y\"\n  shows \"x = y\"\n  using multiplicity_eq_imp_eq[of x y] assms by simp\n\nlemma multiplicity_eq_int:\n  fixes x y :: int\n  assumes \"x > 0\" \"y > 0\" \"\\<And>p. prime p \\<Longrightarrow> multiplicity p x = multiplicity p y\"\n  shows \"x = y\"\n  using multiplicity_eq_imp_eq[of x y] assms by simp\n\nlemma multiplicity_prod_prime_powers:\n  assumes \"finite S\" \"\\<And>x. x \\<in> S \\<Longrightarrow> prime x\" \"prime p\"\n  shows   \"multiplicity p (\\<Prod>p \\<in> S. p ^ f p) = (if p \\<in> S then f p else 0)\"\nproof -\n  define g where \"g = (\\<lambda>x. if x \\<in> S then f x else 0)\"\n  define A where \"A = Abs_multiset g\"\n  have \"{x. g x > 0} \\<subseteq> S\" by (auto simp: g_def)\n  from finite_subset[OF this assms(1)] have [simp]: \"finite {x. 0 < g x}\"\n    by simp\n  from assms have count_A: \"count A x = g x\" for x unfolding A_def\n    by simp\n  have set_mset_A: \"set_mset A = {x\\<in>S. f x > 0}\"\n    unfolding set_mset_def count_A by (auto simp: g_def)\n  with assms have prime: \"prime x\" if \"x \\<in># A\" for x using that by auto\n  from set_mset_A assms have \"(\\<Prod>p \\<in> S. p ^ f p) = (\\<Prod>p \\<in> S. p ^ g p) \"\n    by (intro prod.cong) (auto simp: g_def)\n  also from set_mset_A assms have \"\\<dots> = (\\<Prod>p \\<in> set_mset A. p ^ g p)\"\n    by (intro prod.mono_neutral_right) (auto simp: g_def set_mset_A)\n  also have \"\\<dots> = prod_mset A\"\n    by (auto simp: prod_mset_multiplicity count_A set_mset_A intro!: prod.cong)\n  also from assms have \"multiplicity p \\<dots> = sum_mset (image_mset (multiplicity p) A)\"\n    by (subst prime_elem_multiplicity_prod_mset_distrib) (auto dest: prime)\n  also from assms have \"image_mset (multiplicity p) A = image_mset (\\<lambda>x. if x = p then 1 else 0) A\"\n    by (intro image_mset_cong) (auto simp: prime_multiplicity_other dest: prime)\n  also have \"sum_mset \\<dots> = (if p \\<in> S then f p else 0)\" by (simp add: sum_mset_delta count_A g_def)\n  finally show ?thesis .\nqed\n\nlemma prime_factorization_prod_mset:\n  assumes \"0 \\<notin># A\"\n  shows \"prime_factorization (prod_mset A) = \\<Sum>\\<^sub>#(image_mset prime_factorization A)\"\n  using assms by (induct A) (auto simp add: prime_factorization_mult)\n\nlemma prime_factors_prod:\n  assumes \"finite A\" and \"0 \\<notin> f ` A\"\n  shows \"prime_factors (prod f A) = \\<Union>((prime_factors \\<circ> f) ` A)\"\n  using assms by (simp add: prod_unfold_prod_mset prime_factorization_prod_mset)\n\nlemma prime_factors_fact:\n  \"prime_factors (fact n) = {p \\<in> {2..n}. prime p}\" (is \"?M = ?N\")\nproof (rule set_eqI)\n  fix p\n  { fix m :: nat\n    assume \"p \\<in> prime_factors m\"\n    then have \"prime p\" and \"p dvd m\" by auto\n    moreover assume \"m > 0\" \n    ultimately have \"2 \\<le> p\" and \"p \\<le> m\"\n      by (auto intro: prime_ge_2_nat dest: dvd_imp_le)\n    moreover assume \"m \\<le> n\"\n    ultimately have \"2 \\<le> p\" and \"p \\<le> n\"\n      by (auto intro: order_trans)\n  } note * = this\n  show \"p \\<in> ?M \\<longleftrightarrow> p \\<in> ?N\"\n    by (auto simp add: fact_prod prime_factors_prod Suc_le_eq dest!: prime_prime_factors intro: *)\nqed\n\nlemma prime_dvd_fact_iff:\n  assumes \"prime p\"\n  shows \"p dvd fact n \\<longleftrightarrow> p \\<le> n\"\n  using assms\n  by (auto simp add: prime_factorization_subset_iff_dvd [symmetric]\n    prime_factorization_prime prime_factors_fact prime_ge_2_nat)\n\n(* TODO Legacy names *)\nlemmas prime_imp_coprime_nat = prime_imp_coprime[where ?'a = nat]\nlemmas prime_imp_coprime_int = prime_imp_coprime[where ?'a = int]\nlemmas prime_dvd_mult_nat = prime_dvd_mult_iff[where ?'a = nat]\nlemmas prime_dvd_mult_int = prime_dvd_mult_iff[where ?'a = int]\nlemmas prime_dvd_mult_eq_nat = prime_dvd_mult_iff[where ?'a = nat]\nlemmas prime_dvd_mult_eq_int = prime_dvd_mult_iff[where ?'a = int]\nlemmas prime_dvd_power_nat = prime_dvd_power[where ?'a = nat]\nlemmas prime_dvd_power_int = prime_dvd_power[where ?'a = int]\nlemmas prime_dvd_power_nat_iff = prime_dvd_power_iff[where ?'a = nat]\nlemmas prime_dvd_power_int_iff = prime_dvd_power_iff[where ?'a = int]\nlemmas prime_imp_power_coprime_nat = prime_imp_power_coprime[where ?'a = nat]\nlemmas prime_imp_power_coprime_int = prime_imp_power_coprime[where ?'a = int]\nlemmas primes_coprime_nat = primes_coprime[where ?'a = nat]\nlemmas primes_coprime_int = primes_coprime[where ?'a = nat]\nlemmas prime_divprod_pow_nat = prime_elem_divprod_pow[where ?'a = nat]\nlemmas prime_exp = prime_elem_power_iff[where ?'a = nat]\n\ntext \\<open>Code generation\\<close>\n  \ncontext\nbegin\n\nqualified definition prime_nat :: \"nat \\<Rightarrow> bool\"\n  where [simp, code_abbrev]: \"prime_nat = prime\"\n\nlemma prime_nat_naive [code]:\n  \"prime_nat p \\<longleftrightarrow> p > 1 \\<and> (\\<forall>n \\<in>{1<..<p}. \\<not> n dvd p)\"\n  by (auto simp add: prime_nat_iff')\n\nqualified definition prime_int :: \"int \\<Rightarrow> bool\"\n  where [simp, code_abbrev]: \"prime_int = prime\"\n\nlemma prime_int_naive [code]:\n  \"prime_int p \\<longleftrightarrow> p > 1 \\<and> (\\<forall>n \\<in>{1<..<p}. \\<not> n dvd p)\"\n  by (auto simp add: prime_int_iff')\n\nlemma \"prime(997::nat)\" by eval\n\nlemma \"prime(997::int)\" by eval\n  \nend\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Computational_Algebra/Primes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.9046505428129514, "lm_q1q2_score": 0.7634301483963682}}
{"text": "theory count\nimports Main\nbegin\n\ndatatype nat = zero | s nat\ndatatype lst = nil | cons nat lst\n\ninductive leq :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\nzero: \"leq zero n\" |\nstep: \"leq n m \\<Longrightarrow> leq (s n) (s m)\"\n\nfun leq_fn :: \"nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"leq_fn zero n = True\" |\n\"leq_fn (s m) zero = False\" |\n\"leq_fn (s m) (s n) = leq_fn m n\"\n\ndeclare leq.intros[simp,intro]\n\nfun length :: \"lst \\<Rightarrow> nat\" where\n\"length nil = zero\" |\n\"length (cons x xs) = s (length xs)\"\n\nfun count :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> lst \\<Rightarrow> nat\" where\n\"count p nil = zero\" |\n\"count p (cons y ys) = (if (p y) then s (count p ys) else count p ys)\"\n\nlemma leq_s_right: \"\\<And>n. \\<And>m. leq n m \\<Longrightarrow> leq n (s m)\"\nproof -\nfix n\nshow \"\\<And>m. leq n m \\<Longrightarrow> leq n (s m)\" proof(induct n)\ncase zero\nthen show ?case by simp\nnext\ncase (s n)\nthen show ?case by (metis nat.inject leq.simps)\nqed\nqed\n\nlemma leq_fn_s_right: \"\\<And>n. \\<And>m. leq_fn n m \\<Longrightarrow> leq_fn n (s m)\"\nproof -\nfix n\nshow \"\\<And>m. leq_fn n m \\<Longrightarrow> leq_fn n (s m)\" proof(induct n)\ncase zero\nthen show ?case by simp\nnext\ncase (s n)\nthen show ?case by (metis leq_fn.elims(2) leq_fn.simps(1) leq_fn.simps(3))\nqed\nqed\n\ntheorem \"\\<And>p. \\<And>xs. leq (count p xs) (length xs)\" proof -\nfix xs\nshow \"\\<And>p. leq (count p xs) (length xs)\" proof(induct xs)\ncase nil\nthen show ?case by simp\nnext\ncase (cons y ys)\nthen show ?case by (simp add: leq_s_right)\nqed\nqed\n\ntheorem \"\\<And>xs. \\<And>x. leq_fn (count x xs) (length xs)\" proof -\nfix xs\nshow \"\\<And>x. leq_fn (count x xs) (length xs)\" proof(induct xs)\ncase nil\nthen show ?case by simp\nnext\ncase (cons y ys)\nthen show ?case by (simp add: leq_fn_s_right)\nqed\nqed\n\nend", "meta": {"author": "fachammer", "repo": "induction_project", "sha": "7ed850794a51fe4601f3fa518d9a3c8ace9283ef", "save_path": "github-repos/isabelle/fachammer-induction_project", "path": "github-repos/isabelle/fachammer-induction_project/induction_project-7ed850794a51fe4601f3fa518d9a3c8ace9283ef/isabelle/dty/list/crafted_assorted/isabelle/count.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605947, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7634166768357111}}
{"text": "(* Title: Block_Designs.thy\n   Author: Chelsea Edmonds\n*)\n\nsection \\<open>Block and Balanced Designs\\<close>\ntext \\<open>We define a selection of the many different types of block and balanced designs, building up \nto properties required for defining a BIBD, in addition to several base generalisations\\<close> \n\ntheory Block_Designs imports Design_Operations\nbegin\n\nsubsection \\<open>Block Designs\\<close>\ntext \\<open>A block design is a design where all blocks have the same size.\\<close>\n\nsubsubsection \\<open>K Block Designs\\<close> \ntext \\<open>An important generalisation of a typical block design is the $\\mathcal{K}$ block design, \nwhere all blocks must have a size $x$ where $x \\in \\mathcal{K}$\\<close>\nlocale K_block_design = proper_design +\n  fixes sizes :: \"nat set\" (\"\\<K>\")\n  assumes block_sizes: \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<in> \\<K>\"\n  assumes positive_ints: \"x \\<in> \\<K> \\<Longrightarrow> x > 0\"\nbegin\n\nlemma sys_block_size_subset: \"sys_block_sizes \\<subseteq> \\<K>\"\n  using block_sizes sys_block_sizes_obtain_bl by blast\n\nend\n\nsubsubsection\\<open>Uniform Block Design\\<close>\ntext \\<open>The typical uniform block design is defined below\\<close>\nlocale block_design = proper_design + \n  fixes u_block_size :: nat (\"\\<k>\")\n  assumes uniform [simp]: \"bl \\<in># \\<B> \\<Longrightarrow> card bl = \\<k>\"\nbegin\n\nlemma k_non_zero: \"\\<k> \\<ge> 1\"\nproof -\n  obtain bl where bl_in: \"bl \\<in># \\<B>\"\n    using design_blocks_nempty by auto \n  then have \"card bl \\<ge> 1\" using block_size_gt_0\n    by (metis less_not_refl less_one not_le_imp_less) \n  thus ?thesis by (simp add: bl_in)\nqed\n\nlemma uniform_alt_def_all: \"\\<forall> bl \\<in># \\<B> .card bl = \\<k>\"\n  using uniform by auto \n\nlemma uniform_unfold_point_set: \"bl \\<in># \\<B> \\<Longrightarrow> card {p \\<in> \\<V>. p \\<in> bl} = \\<k>\"\n  using uniform wellformed by (simp add: Collect_conj_eq inf.absorb_iff2) \n\nlemma uniform_unfold_point_set_mset: \"bl \\<in># \\<B> \\<Longrightarrow> size {#p \\<in># mset_set \\<V>. p \\<in> bl #} = \\<k>\"\n  using uniform_unfold_point_set by (simp add: finite_sets) \n\nlemma sys_block_sizes_uniform [simp]:  \"sys_block_sizes  = {\\<k>}\"\nproof -\n  have \"sys_block_sizes = {bs . \\<exists> bl . bs = card bl \\<and> bl\\<in># \\<B>}\" by (simp add: sys_block_sizes_def)\n  then have \"sys_block_sizes  = {bs . bs = \\<k>}\" using uniform uniform_unfold_point_set \n      b_positive block_set_nempty_imp_block_ex\n    by (smt (verit, best) Collect_cong design_blocks_nempty)\n  thus ?thesis by auto\nqed\n\nlemma sys_block_sizes_uniform_single: \"is_singleton (sys_block_sizes)\"\n  by simp\n\nlemma uniform_size_incomp: \"\\<k> \\<le> \\<v> - 1 \\<Longrightarrow> bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  using uniform k_non_zero \n  by (metis block_size_lt_v diff_diff_cancel diff_is_0_eq' less_numeral_extra(1) nat_less_le)\n\nlemma uniform_complement_block_size:\n  assumes \"bl \\<in># \\<B>\\<^sup>C\"\n  shows \"card bl = \\<v> - \\<k>\"\nproof -\n  obtain bl' where bl_assm: \"bl = bl'\\<^sup>c \\<and> bl' \\<in># \\<B>\" \n    using wellformed assms by (auto simp add: complement_blocks_def)\n  then have \"int (card bl') = \\<k>\" by simp\n  thus ?thesis using bl_assm block_complement_size wellformed\n    by (simp add: block_size_lt_order of_nat_diff) \nqed\n\nlemma uniform_complement[intro]: \n  assumes \"\\<k> \\<le> \\<v> - 1\"\n  shows \"block_design \\<V> \\<B>\\<^sup>C (\\<v> - \\<k>)\"\nproof - \n  interpret des: proper_design \\<V> \"\\<B>\\<^sup>C\" \n    using  uniform_size_incomp assms complement_proper_design by auto \n  show ?thesis using assms uniform_complement_block_size by (unfold_locales) (simp)\nqed\n\nlemma block_size_lt_v: \"\\<k> \\<le> \\<v>\"\n  using v_non_zero block_size_lt_v design_blocks_nempty uniform by auto \n\nend\n\nlemma (in proper_design) block_designI[intro]: \"(\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> card bl = k) \n  \\<Longrightarrow> block_design \\<V> \\<B> k\"\n  by (unfold_locales) (auto)\n\ncontext block_design \nbegin\n\nlemma block_design_multiple: \"n > 0 \\<Longrightarrow> block_design \\<V> (multiple_blocks n) \\<k>\"\n  using elem_in_repeat_in_original multiple_proper_design proper_design.block_designI \n  by (metis uniform_alt_def_all)\n\nend\ntext \\<open>A uniform block design is clearly a type of $K$\\_block\\_design with a singleton $K$ set\\<close>\nsublocale block_design \\<subseteq> K_block_design \\<V> \\<B> \"{\\<k>}\"\n  using k_non_zero uniform by unfold_locales simp_all\n\nsubsubsection \\<open>Incomplete Designs\\<close>\ntext \\<open>An incomplete design is a design where $k < v$, i.e. no block is equal to the point set\\<close>\nlocale incomplete_design = block_design + \n  assumes incomplete: \"\\<k> < \\<v>\"\n\nbegin\n\nlemma incomplete_imp_incomp_block: \"bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  using incomplete uniform uniform_size_incomp by fastforce  \n\nlemma incomplete_imp_proper_subset: \"bl \\<in># \\<B> \\<Longrightarrow> bl \\<subset> \\<V>\"\n  using incomplete_block_proper_subset incomplete_imp_incomp_block by auto\nend\n\nlemma (in block_design) incomplete_designI[intro]: \"\\<k> < \\<v> \\<Longrightarrow> incomplete_design \\<V> \\<B> \\<k>\"\n  by unfold_locales auto\n\ncontext incomplete_design\nbegin\n\nlemma multiple_incomplete: \"n > 0 \\<Longrightarrow> incomplete_design \\<V> (multiple_blocks n) \\<k>\"\n  using block_design_multiple incomplete by (simp add: block_design.incomplete_designI) \n\nlemma complement_incomplete: \"incomplete_design \\<V> (\\<B>\\<^sup>C) (\\<v> - \\<k>)\"\nproof -\n  have \"\\<v> - \\<k> < \\<v>\" using v_non_zero k_non_zero by linarith\n  thus ?thesis using uniform_complement incomplete incomplete_designI\n    by (simp add: block_design.incomplete_designI) \nqed\n\nend\n\nsubsection \\<open>Balanced Designs\\<close>\ntext \\<open>t-wise balance is a design with the property that all point subsets of size $t$ occur in \n$\\lambda_t$ blocks\\<close>\n\nlocale t_wise_balance = proper_design + \n  fixes grouping :: nat (\"\\<t>\") and index :: nat (\"\\<Lambda>\\<^sub>t\")\n  assumes t_non_zero: \"\\<t> \\<ge> 1\"\n  assumes t_lt_order: \"\\<t> \\<le> \\<v>\"\n  assumes balanced [simp]: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps = \\<Lambda>\\<^sub>t\"\nbegin\n\nlemma t_non_zero_suc: \"\\<t> \\<ge> Suc 0\"\n  using t_non_zero by auto\n\nlemma balanced_alt_def_all: \"\\<forall> ps \\<subseteq> \\<V> . card ps = \\<t> \\<longrightarrow> \\<B> index ps = \\<Lambda>\\<^sub>t\"\n  using balanced by auto\n\nend\n\nlemma (in proper_design) t_wise_balanceI[intro]: \"\\<t> \\<le> \\<v> \\<Longrightarrow> \\<t> \\<ge> 1 \\<Longrightarrow> \n  (\\<And> ps . ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t>  \\<Longrightarrow> \\<B> index ps = \\<Lambda>\\<^sub>t) \\<Longrightarrow> t_wise_balance \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t\"\n  by (unfold_locales) auto\n\ncontext t_wise_balance\nbegin\n\nlemma obtain_t_subset_points:\n  obtains T where \"T \\<subseteq> \\<V>\" \"card T = \\<t>\" \"finite T\"\n  using obtain_subset_with_card_n design_points_nempty t_lt_order t_non_zero finite_sets by auto\n\nlemma multiple_t_wise_balance_index [simp]:\n  assumes \"ps \\<subseteq> \\<V>\"\n  assumes \"card ps = \\<t>\"\n  shows \"(multiple_blocks n) index ps = \\<Lambda>\\<^sub>t * n\"\n  using multiple_point_index balanced assms by fastforce \n\nlemma multiple_t_wise_balance: \n  assumes \"n > 0\" \n  shows \"t_wise_balance \\<V> (multiple_blocks n) \\<t> (\\<Lambda>\\<^sub>t * n)\"\nproof - \n  interpret des: proper_design \\<V> \"(multiple_blocks n)\" by (simp add: assms multiple_proper_design)  \n  show ?thesis using t_non_zero t_lt_order multiple_t_wise_balance_index \n    by (unfold_locales) (simp_all)\nqed\n\nlemma twise_set_pair_index: \"ps \\<subseteq> \\<V> \\<Longrightarrow> ps2 \\<subseteq> \\<V> \\<Longrightarrow> ps \\<noteq> ps2 \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> card ps2 = \\<t> \n  \\<Longrightarrow> \\<B> index ps = \\<B> index ps2\"\n  using balanced by simp \n\nlemma t_wise_balance_alt: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps = l2 \n  \\<Longrightarrow> (\\<And> ps . ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps = l2)\"\n  using twise_set_pair_index by blast\n\nlemma index_1_imp_mult_1 [simp]: \n  assumes \"\\<Lambda>\\<^sub>t = 1\"\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"card bl \\<ge> \\<t>\"\n  shows \"multiplicity bl = 1\"\nproof (rule ccontr)\n  assume \"\\<not> (multiplicity bl = 1)\"\n  then have not: \"multiplicity bl \\<noteq> 1\" by simp\n  have \"multiplicity bl \\<noteq> 0\" using assms by simp \n  then have m: \"multiplicity bl \\<ge> 2\" using not by linarith\n  obtain ps where ps: \"ps \\<subseteq> bl \\<and> card ps = \\<t>\"\n    using assms obtain_t_subset_points\n    by (metis obtain_subset_with_card_n) \n  then have \"\\<B> index ps \\<ge> 2\"\n    using m points_index_count_min ps by blast\n  then show False using balanced ps antisym_conv2 not_numeral_less_zero numeral_le_one_iff \n      points_index_ps_nin semiring_norm(69) zero_neq_numeral\n    by (metis assms(1))\nqed\n\nend\n\nsubsubsection \\<open>Sub-types of t-wise balance\\<close>\n\ntext \\<open>Pairwise balance is when $t = 2$. These are commonly of interest\\<close>\nlocale pairwise_balance = t_wise_balance \\<V> \\<B> 2 \\<Lambda> \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and index (\"\\<Lambda>\")\n\ntext \\<open>We can combine the balance properties with $K$\\_block design to define tBD's \n(t-wise balanced designs), and PBD's (pairwise balanced designs)\\<close>\n\nlocale tBD = t_wise_balance + K_block_design +\n  assumes block_size_gt_t: \"k \\<in> \\<K> \\<Longrightarrow> k \\<ge> \\<t>\"\n\nlocale \\<Lambda>_PBD = pairwise_balance + K_block_design + \n  assumes block_size_gt_t: \"k \\<in> \\<K> \\<Longrightarrow> k \\<ge> 2\"\n\nsublocale \\<Lambda>_PBD \\<subseteq> tBD \\<V> \\<B> 2 \\<Lambda> \\<K>\n  using t_lt_order block_size_gt_t by (unfold_locales) (simp_all)\n\nlocale PBD = \\<Lambda>_PBD \\<V> \\<B> 1 \\<K> for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and sizes (\"\\<K>\")\nbegin\nlemma multiplicity_is_1:\n  assumes \"bl \\<in># \\<B>\"\n  shows \"multiplicity bl = 1\"\n  using block_size_gt_t index_1_imp_mult_1 by (simp add: assms block_sizes) \n\nend\n\nsublocale PBD \\<subseteq> simple_design\n  using multiplicity_is_1 by (unfold_locales)\n\ntext \\<open>PBD's are often only used in the case where $k$ is uniform, defined here.\\<close>\nlocale k_\\<Lambda>_PBD = pairwise_balance + block_design + \n  assumes block_size_t: \"2 \\<le> \\<k>\"\n\nsublocale k_\\<Lambda>_PBD \\<subseteq> \\<Lambda>_PBD \\<V> \\<B> \\<Lambda> \"{\\<k>}\"\n  using k_non_zero uniform block_size_t by(unfold_locales) (simp_all)\n\nlocale k_PBD = k_\\<Lambda>_PBD \\<V> \\<B> 1 \\<k> for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and u_block_size (\"\\<k>\")\n\nsublocale k_PBD \\<subseteq> PBD \\<V> \\<B> \"{\\<k>}\"\n  using  block_size_t by (unfold_locales, simp_all)\n\nsubsubsection \\<open>Covering and Packing Designs\\<close>\ntext \\<open>Covering and packing designs involve a looser balance restriction. Upper/lower bounds\nare placed on the points index, instead of a strict equality\\<close>\n\ntext \\<open>A t-covering design is a relaxed version of a tBD, where, for all point subsets of size t, \na lower bound is put on the points index\\<close>\nlocale t_covering_design = block_design +\n  fixes grouping :: nat (\"\\<t>\")\n  fixes min_index :: nat (\"\\<Lambda>\\<^sub>t\")\n  assumes covering: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps \\<ge> \\<Lambda>\\<^sub>t\" \n  assumes block_size_t: \"\\<t> \\<le> \\<k>\"\n  assumes t_non_zero: \"\\<t> \\<ge> 1\"\nbegin\n\nlemma covering_alt_def_all: \"\\<forall> ps \\<subseteq> \\<V> . card ps = \\<t> \\<longrightarrow> \\<B> index ps \\<ge> \\<Lambda>\\<^sub>t\"\n  using covering by auto\n\nend\n\nlemma (in block_design) t_covering_designI [intro]: \"t \\<le> \\<k> \\<Longrightarrow> t \\<ge> 1 \\<Longrightarrow> \n  (\\<And> ps. ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = t \\<Longrightarrow> \\<B> index ps \\<ge> \\<Lambda>\\<^sub>t) \\<Longrightarrow> t_covering_design \\<V> \\<B> \\<k> t \\<Lambda>\\<^sub>t\"\n  by (unfold_locales) simp_all\n\ntext \\<open>A t-packing design is a relaxed version of a tBD, where, for all point subsets of size t, \nan upper bound is put on the points index\\<close>\nlocale t_packing_design = block_design + \n  fixes grouping :: nat (\"\\<t>\")\n  fixes min_index :: nat (\"\\<Lambda>\\<^sub>t\")\n  assumes packing: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B> index ps \\<le> \\<Lambda>\\<^sub>t\"\n  assumes block_size_t: \"\\<t> \\<le> \\<k>\"\n  assumes t_non_zero: \"\\<t> \\<ge> 1\"\nbegin\n\nlemma packing_alt_def_all: \"\\<forall> ps \\<subseteq> \\<V> . card ps = \\<t> \\<longrightarrow> \\<B> index ps \\<le> \\<Lambda>\\<^sub>t\"\n  using packing by auto\n\nend\n\nlemma (in block_design) t_packing_designI [intro]: \"t \\<le> \\<k> \\<Longrightarrow> t \\<ge> 1 \\<Longrightarrow> \n  (\\<And> ps . ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = t \\<Longrightarrow> \\<B> index ps \\<le> \\<Lambda>\\<^sub>t) \\<Longrightarrow> t_packing_design \\<V> \\<B> \\<k> t \\<Lambda>\\<^sub>t\"\n  by (unfold_locales) simp_all\n\nlemma packing_covering_imp_balance: \n  assumes \"t_packing_design V B k t \\<Lambda>\\<^sub>t\" \n  assumes \"t_covering_design V B k t \\<Lambda>\\<^sub>t\" \n  shows \"t_wise_balance V B t \\<Lambda>\\<^sub>t\"\nproof -\n  from assms interpret des: proper_design V B \n    using block_design.axioms(1) t_covering_design.axioms(1) by blast\n  show ?thesis \n  proof (unfold_locales)\n    show \"1 \\<le> t\" using assms t_packing_design.t_non_zero by auto\n    show \"t \\<le> des.\\<v>\" using block_design.block_size_lt_v t_packing_design.axioms(1) \n      by (metis assms(1) dual_order.trans t_packing_design.block_size_t)\n    show \"\\<And>ps. ps \\<subseteq> V \\<Longrightarrow> card ps = t \\<Longrightarrow> B index ps = \\<Lambda>\\<^sub>t\" \n      using t_packing_design.packing t_covering_design.covering by (metis assms dual_order.antisym) \n  qed\nqed\n\nsubsection \\<open>Constant Replication Design\\<close>\ntext \\<open>When the replication number for all points in a design is constant, it is the \ndesign replication number.\\<close>\nlocale constant_rep_design = proper_design +\n  fixes design_rep_number :: nat (\"\\<r>\")\n  assumes rep_number [simp]: \"x \\<in> \\<V> \\<Longrightarrow>  \\<B> rep x = \\<r>\" \n\nbegin\n\nlemma rep_number_alt_def_all: \"\\<forall> x \\<in> \\<V>. \\<B> rep x = \\<r>\"\n  by (simp)\n\nlemma rep_number_unfold_set: \"x \\<in> \\<V> \\<Longrightarrow> size {#bl \\<in># \\<B> . x \\<in> bl#} = \\<r>\"\n  using rep_number by (simp add: point_replication_number_def)\n\nlemma rep_numbers_constant [simp]: \"replication_numbers  = {\\<r>}\"\n  unfolding replication_numbers_def using rep_number design_points_nempty Collect_cong finite.cases \n    finite_sets insertCI singleton_conv\n  by (smt (verit, ccfv_threshold) fst_conv snd_conv) \n\nlemma replication_number_single: \"is_singleton (replication_numbers)\"\n  using is_singleton_the_elem by simp\n\nlemma constant_rep_point_pair: \"x1 \\<in> \\<V> \\<Longrightarrow> x2 \\<in> \\<V> \\<Longrightarrow> x1 \\<noteq> x2 \\<Longrightarrow> \\<B> rep x1 = \\<B> rep x2\"\n  using rep_number by auto\n\nlemma constant_rep_alt: \"x1 \\<in> \\<V> \\<Longrightarrow> \\<B> rep x1 = r2 \\<Longrightarrow> (\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x = r2)\"\n  by (simp)\n\nlemma constant_rep_point_not_0:\n  assumes \"x \\<in> \\<V>\" \n  shows \"\\<B> rep x \\<noteq> 0\"\nproof (rule ccontr)\n  assume \"\\<not> \\<B> rep x \\<noteq> 0\"\n  then have \"\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x = 0\" using rep_number assms by auto\n  then have \"\\<And> x . x \\<in> \\<V> \\<Longrightarrow>  size {#bl \\<in># \\<B> . x \\<in> bl#} = 0\" \n    by (simp add: point_replication_number_def)\n  then show False using design_blocks_nempty wf_design wf_design_iff wf_invalid_point\n    by (metis ex_in_conv filter_mset_empty_conv multiset_nonemptyE size_eq_0_iff_empty)\nqed\n\nlemma rep_not_zero: \"\\<r> \\<noteq> 0\"\n  using rep_number constant_rep_point_not_0 design_points_nempty by auto \n\nlemma r_gzero: \"\\<r> > 0\"\n  using rep_not_zero by auto \n\nlemma r_lt_eq_b: \"\\<r> \\<le> \\<b>\"\n  using rep_number max_point_rep\n  by (metis all_not_in_conv design_points_nempty) \n\nlemma complement_rep_number: \n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"\n  shows \"constant_rep_design \\<V> \\<B>\\<^sup>C (\\<b> - \\<r>)\"\nproof - \n  interpret d: proper_design \\<V> \"(\\<B>\\<^sup>C)\" using complement_proper_design\n    by (simp add: assms) \n  show ?thesis using complement_rep_number rep_number by (unfold_locales) simp\nqed\n\nlemma multiple_rep_number: \n  assumes \"n > 0\"\n  shows \"constant_rep_design \\<V> (multiple_blocks n) (\\<r> * n)\"\nproof - \n  interpret d: proper_design \\<V> \"(multiple_blocks n)\" using multiple_proper_design\n    by (simp add: assms) \n  show ?thesis using multiple_point_rep_num by (unfold_locales) (simp_all)\nqed\nend\n\nlemma (in proper_design) constant_rep_designI [intro]: \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x = \\<r>) \n    \\<Longrightarrow> constant_rep_design \\<V> \\<B> \\<r>\"\n  by unfold_locales auto\n\nsubsection \\<open>T-designs\\<close>\ntext \\<open>All the before mentioned designs build up to the concept of a t-design, which has uniform \nblock size and is t-wise balanced. We limit $t$ to be less than $k$, so the balance condition has \nrelevance\\<close>\nlocale t_design = incomplete_design + t_wise_balance + \n  assumes block_size_t: \"\\<t> \\<le> \\<k>\"\nbegin\n\nlemma point_indices_balanced: \"point_indices \\<t> = {\\<Lambda>\\<^sub>t}\" \nproof -\n  have \"point_indices \\<t> = {i . \\<exists> ps . i = \\<B> index ps \\<and> card ps = \\<t> \\<and> ps \\<subseteq> \\<V>}\"\n    by (simp add: point_indices_def) \n  then have \"point_indices  \\<t> = {i . i = \\<Lambda>\\<^sub>t}\" using balanced Collect_cong obtain_t_subset_points \n     by (smt (verit, best)) \n  thus ?thesis by auto\nqed\n\nlemma point_indices_singleton: \"is_singleton (point_indices \\<t>)\"\n  using point_indices_balanced is_singleton_the_elem by simp\n\nend\n\nlemma t_designI [intro]: \n  assumes \"incomplete_design V B k\"\n  assumes \"t_wise_balance V B t \\<Lambda>\\<^sub>t\"\n  assumes \"t \\<le> k\"\n  shows \"t_design V B k t \\<Lambda>\\<^sub>t\"\n  by (simp add: assms(1) assms(2) assms(3) t_design.intro t_design_axioms.intro)\n\nsublocale t_design \\<subseteq> t_covering_design \\<V> \\<B> \\<k> \\<t> \\<Lambda>\\<^sub>t\n  using t_non_zero by (unfold_locales) (auto simp add: block_size_t)\n\nsublocale t_design \\<subseteq> t_packing_design \\<V> \\<B> \\<k> \\<t> \\<Lambda>\\<^sub>t\n  using t_non_zero by (unfold_locales) (auto simp add: block_size_t)\n\nlemma t_design_pack_cov [intro]: \n  assumes \"k < card V\"\n  assumes \"t_covering_design V B k t \\<Lambda>\\<^sub>t\"\n  assumes \"t_packing_design V B k t \\<Lambda>\\<^sub>t\"\n  shows \"t_design V B k t \\<Lambda>\\<^sub>t\"\nproof -\n  from assms interpret id: incomplete_design V B k\n    using block_design.incomplete_designI t_packing_design.axioms(1)\n    by blast \n  from assms interpret balance: t_wise_balance V B t \\<Lambda>\\<^sub>t \n    using packing_covering_imp_balance by blast \n  show ?thesis using assms(3) \n    by (unfold_locales) (simp_all add: t_packing_design.block_size_t)\nqed\n\nsublocale t_design \\<subseteq> tBD \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t \"{\\<k>}\"\n  using uniform k_non_zero block_size_t by (unfold_locales) simp_all\n\ncontext t_design \nbegin\n\nlemma multiple_t_design: \"n > 0 \\<Longrightarrow> t_design \\<V> (multiple_blocks n) \\<k> \\<t> (\\<Lambda>\\<^sub>t * n)\"\n  using multiple_t_wise_balance multiple_incomplete block_size_t by (simp add: t_designI)\n\nlemma t_design_min_v: \"\\<v> > 1\"\n  using k_non_zero incomplete by simp\n\nend\n\nsubsection \\<open>Steiner Systems\\<close>\n\ntext \\<open>Steiner systems are a special type of t-design where $\\Lambda_t = 1$\\<close>\nlocale steiner_system = t_design \\<V> \\<B> \\<k> \\<t> 1 \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and u_block_size (\"\\<k>\") and grouping (\"\\<t>\")\n\nbegin\n\nlemma block_multiplicity [simp]: \n  assumes \"bl \\<in># \\<B>\"\n  shows \"multiplicity bl = 1\"\n  by (simp add: assms block_size_t)\n\nend\n\nsublocale steiner_system \\<subseteq> simple_design\n  by unfold_locales (simp)\n\nlemma (in t_design) steiner_systemI[intro]: \"\\<Lambda>\\<^sub>t = 1 \\<Longrightarrow> steiner_system \\<V> \\<B> \\<k> \\<t>\"\n  using t_non_zero t_lt_order block_size_t\n  by unfold_locales auto\n\nsubsection \\<open>Combining block designs\\<close>\ntext \\<open>We define some closure properties for various block designs under the combine operator.\nThis is done using locales to reason on multiple instances of the same type of design, building \non what was presented in the design operations theory\\<close>\n\nlocale two_t_wise_eq_points = two_designs_proper \\<V> \\<B> \\<V> \\<B>' + des1: t_wise_balance \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t + \n  des2: t_wise_balance \\<V> \\<B>' \\<t> \\<Lambda>\\<^sub>t' for \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t \\<B>' \\<Lambda>\\<^sub>t'\nbegin\n\nlemma combine_t_wise_balance_index: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> \\<B>\\<^sup>+ index ps = (\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using des1.balanced des2.balanced by (simp add: combine_points_index)\n\nlemma combine_t_wise_balance: \"t_wise_balance \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<t> (\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\nproof (unfold_locales, simp add: des1.t_non_zero_suc)\n  have \"card \\<V>\\<^sup>+  \\<ge> card \\<V>\" by simp \n  then show \"\\<t> \\<le> card (\\<V>\\<^sup>+)\" using des1.t_lt_order by linarith \n  show \"\\<And>ps. ps \\<subseteq> \\<V>\\<^sup>+ \\<Longrightarrow> card ps = \\<t> \\<Longrightarrow> (\\<B>\\<^sup>+ index ps) = \\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t'\" \n    using combine_t_wise_balance_index by blast \nqed\n\nsublocale combine_t_wise_des: t_wise_balance \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<t>\" \"(\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using combine_t_wise_balance by auto\n\nend\n\nlocale two_k_block_designs = two_designs_proper \\<V> \\<B> \\<V>' \\<B>' + des1: block_design \\<V> \\<B> \\<k> + \n  des2: block_design \\<V>' \\<B>' \\<k> for \\<V> \\<B> \\<k> \\<V>' \\<B>'\nbegin\n\nlemma block_design_combine: \"block_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<k>\"\n  using des1.uniform des2.uniform by (unfold_locales) (auto)\n\nsublocale combine_block_des: block_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<k>\"\n  using block_design_combine by simp\n\nend\n\nlocale two_rep_designs_eq_points = two_designs_proper \\<V> \\<B> \\<V> \\<B>' + des1: constant_rep_design \\<V> \\<B> \\<r> + \n  des2: constant_rep_design \\<V> \\<B>' \\<r>' for \\<V> \\<B> \\<r> \\<B>' \\<r>' \nbegin\n\nlemma combine_rep_number: \"constant_rep_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ (\\<r> + \\<r>')\"\n  using combine_rep_number des1.rep_number des2.rep_number by (unfold_locales) (simp)\n\nsublocale combine_const_rep: constant_rep_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"(\\<r> + \\<r>')\"\n  using combine_rep_number by simp\n\nend\n\nlocale two_incomplete_designs = two_k_block_designs \\<V> \\<B> \\<k> \\<V>' \\<B>' + des1: incomplete_design \\<V> \\<B> \\<k> + \n  des2: incomplete_design \\<V>' \\<B>' \\<k> for \\<V> \\<B> \\<k> \\<V>' \\<B>'\nbegin\n\nlemma combine_is_incomplete: \"incomplete_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<k>\"\n  using combine_order des1.incomplete des2.incomplete by (unfold_locales) (simp)\n\nsublocale combine_incomplete: incomplete_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<k>\"\n  using combine_is_incomplete by simp\nend\n\nlocale two_t_designs_eq_points = two_incomplete_designs \\<V> \\<B> \\<k> \\<V> \\<B>' \n  + two_t_wise_eq_points \\<V> \\<B> \\<t> \\<Lambda>\\<^sub>t \\<B>' \\<Lambda>\\<^sub>t' + des1: t_design \\<V> \\<B> \\<k> \\<t> \\<Lambda>\\<^sub>t + \n  des2: t_design \\<V> \\<B>' \\<k> \\<t> \\<Lambda>\\<^sub>t' for \\<V> \\<B> \\<k> \\<B>' \\<t> \\<Lambda>\\<^sub>t \\<Lambda>\\<^sub>t'\nbegin\n\nlemma combine_is_t_des: \"t_design \\<V>\\<^sup>+ \\<B>\\<^sup>+ \\<k> \\<t> (\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using des1.block_size_t des2.block_size_t by (unfold_locales)\n\nsublocale combine_t_des: t_design \"\\<V>\\<^sup>+\" \"\\<B>\\<^sup>+\" \"\\<k>\" \"\\<t>\" \"(\\<Lambda>\\<^sub>t + \\<Lambda>\\<^sub>t')\"\n  using combine_is_t_des by blast\n\nend\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Design_Theory/Block_Designs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.8333245994514084, "lm_q1q2_score": 0.763416676797988}}
{"text": "theory E2_10\n  imports Main\nbegin\n\ndatatype tree0 = Leaf | Node tree0 tree0\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Leaf = 1\" |\n  \"nodes (Node l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n  \"explode 0 t = t\" |\n  \"explode (Suc n) t = explode n (Node t t)\"\n\nlemma \"nodes (explode n t) = (nodes t) * (2 ^ n) + 2 ^ n - 1\"\n  apply(induction n arbitrary: t)\n  apply(simp_all add: algebra_simps)\n  done\n\nend\n", "meta": {"author": "MU001999", "repo": "isabelle-exercises", "sha": "86a32cf8396210c2764fd113c735622347f88754", "save_path": "github-repos/isabelle/MU001999-isabelle-exercises", "path": "github-repos/isabelle/MU001999-isabelle-exercises/isabelle-exercises-86a32cf8396210c2764fd113c735622347f88754/chapter2/E2_10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.8333245911726382, "lm_q1q2_score": 0.7634166634878079}}
{"text": "theory week03B_demo_automation imports Main begin\n\ndefinition \n  xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"xor A B \\<equiv> (A \\<and> \\<not>B) \\<or> (\\<not>A \\<and> B)\"\n\n\n  \n  \n  \n  \n  \n  \n  \n  \n  \n  \n  \n  \n  \n\nlemma xorI [intro!]:\n  \"\\<lbrakk> \\<lbrakk>A; B\\<rbrakk> \\<Longrightarrow> False; \\<not>B \\<Longrightarrow> A \\<rbrakk> \\<Longrightarrow> xor A B\"\n  apply (unfold xor_def)\n  apply blast\n  done\n\nlemma xorE:\n  \"\\<lbrakk> xor A B; \\<lbrakk>A; \\<not>B\\<rbrakk> \\<Longrightarrow> R; \\<lbrakk>\\<not>A; B\\<rbrakk> \\<Longrightarrow> R \\<rbrakk> \\<Longrightarrow> R\"\n  apply (unfold xor_def)\n  apply blast\n  done\n\nlemma \"xor A A = False\" by (blast elim!: xorE)\n\ndeclare xorE [elim!]\n\nlemma \"xor A B = xor B A\" by blast\n\nend", "meta": {"author": "tecty", "repo": "COMP4161", "sha": "95aa77d289c14cb85477c7f91467f81cd66fcd62", "save_path": "github-repos/isabelle/tecty-COMP4161", "path": "github-repos/isabelle/tecty-COMP4161/COMP4161-95aa77d289c14cb85477c7f91467f81cd66fcd62/demo/week03B_demo_automation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7633884655752005}}
{"text": "theory List_Demo\nimports Main\nbegin\n\ndatatype 'a list = Nil | Cons \"'a\" \"'a list\"\n\nterm \"Nil\"\n\ndeclare [[names_short]]\n\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\nvalue \"rev(Cons a (Cons b Nil))\"\n\n\nlemma app_Nil2[simp]: \"app xs Nil = xs\"\napply (induction xs)\napply auto\ndone\n\nlemma app_assoc[simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply (induction xs)\napply auto\ndone\n\nlemma rev_app[simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"\napply (induction xs)\napply auto\ndone\n\ntheorem rev_rev[simp]: \"rev (rev xs) = xs\"\napply (induction xs)\napply auto\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Complete/List_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.8311430415844385, "lm_q1q2_score": 0.7633884636543894}}
{"text": "(*  Author:     Steven Obua, TU Muenchen *)\n\nsection \\<open>Various algebraic structures combined with a lattice\\<close>\n\ntheory Lattice_Algebras\n  imports Complex_MainRLT\nbegin\n\nclass semilattice_inf_ab_group_add = ordered_ab_group_add + semilattice_inf\nbegin\n\nlemma add_inf_distrib_left: \"a + inf b c = inf (a + b) (a + c)\"\n  apply (rule order.antisym)\n   apply (simp_all add: le_infI)\n  apply (rule add_le_imp_le_left [of \"uminus a\"])\n  apply (simp only: add.assoc [symmetric], simp add: diff_le_eq add.commute)\n  done\n\nlemma add_inf_distrib_right: \"inf a b + c = inf (a + c) (b + c)\"\nproof -\n  have \"c + inf a b = inf (c + a) (c + b)\"\n    by (simp add: add_inf_distrib_left)\n  then show ?thesis\n    by (simp add: add.commute)\nqed\n\nend\n\nclass semilattice_sup_ab_group_add = ordered_ab_group_add + semilattice_sup\nbegin\n\nlemma add_sup_distrib_left: \"a + sup b c = sup (a + b) (a + c)\"\n  apply (rule order.antisym)\n   apply (rule add_le_imp_le_left [of \"uminus a\"])\n   apply (simp only: add.assoc [symmetric], simp)\n   apply (simp add: le_diff_eq add.commute)\n  apply (rule le_supI)\n   apply (rule add_le_imp_le_left [of \"a\"], simp only: add.assoc[symmetric], simp)+\n  done\n\nlemma add_sup_distrib_right: \"sup a b + c = sup (a + c) (b + c)\"\nproof -\n  have \"c + sup a b = sup (c+a) (c+b)\"\n    by (simp add: add_sup_distrib_left)\n  then show ?thesis\n    by (simp add: add.commute)\nqed\n\nend\n\nclass lattice_ab_group_add = ordered_ab_group_add + lattice\nbegin\n\nsubclass semilattice_inf_ab_group_add ..\nsubclass semilattice_sup_ab_group_add ..\n\nlemmas add_sup_inf_distribs =\n  add_inf_distrib_right add_inf_distrib_left add_sup_distrib_right add_sup_distrib_left\n\nlemma inf_eq_neg_sup: \"inf a b = - sup (- a) (- b)\"\nproof (rule inf_unique)\n  fix a b c :: 'a\n  show \"- sup (- a) (- b) \\<le> a\"\n    by (rule add_le_imp_le_right [of _ \"sup (uminus a) (uminus b)\"])\n      (simp, simp add: add_sup_distrib_left)\n  show \"- sup (-a) (-b) \\<le> b\"\n    by (rule add_le_imp_le_right [of _ \"sup (uminus a) (uminus b)\"])\n      (simp, simp add: add_sup_distrib_left)\n  assume \"a \\<le> b\" \"a \\<le> c\"\n  then show \"a \\<le> - sup (-b) (-c)\"\n    by (subst neg_le_iff_le [symmetric]) (simp add: le_supI)\nqed\n\nlemma sup_eq_neg_inf: \"sup a b = - inf (- a) (- b)\"\nproof (rule sup_unique)\n  fix a b c :: 'a\n  show \"a \\<le> - inf (- a) (- b)\"\n    by (rule add_le_imp_le_right [of _ \"inf (uminus a) (uminus b)\"])\n      (simp, simp add: add_inf_distrib_left)\n  show \"b \\<le> - inf (- a) (- b)\"\n    by (rule add_le_imp_le_right [of _ \"inf (uminus a) (uminus b)\"])\n      (simp, simp add: add_inf_distrib_left)\n  show \"- inf (- a) (- b) \\<le> c\" if \"a \\<le> c\" \"b \\<le> c\"\n    using that by (subst neg_le_iff_le [symmetric]) (simp add: le_infI)\nqed\n\nlemma neg_inf_eq_sup: \"- inf a b = sup (- a) (- b)\"\n  by (simp add: inf_eq_neg_sup)\n\nlemma diff_inf_eq_sup: \"a - inf b c = a + sup (- b) (- c)\"\n  using neg_inf_eq_sup [of b c, symmetric] by simp\n\nlemma neg_sup_eq_inf: \"- sup a b = inf (- a) (- b)\"\n  by (simp add: sup_eq_neg_inf)\n\nlemma diff_sup_eq_inf: \"a - sup b c = a + inf (- b) (- c)\"\n  using neg_sup_eq_inf [of b c, symmetric] by simp\n\nlemma add_eq_inf_sup: \"a + b = sup a b + inf a b\"\nproof -\n  have \"0 = - inf 0 (a - b) + inf (a - b) 0\"\n    by (simp add: inf_commute)\n  then have \"0 = sup 0 (b - a) + inf (a - b) 0\"\n    by (simp add: inf_eq_neg_sup)\n  then have \"0 = (- a + sup a b) + (inf a b + (- b))\"\n    by (simp only: add_sup_distrib_left add_inf_distrib_right) simp\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\n\nsubsection \\<open>Positive Part, Negative Part, Absolute Value\\<close>\n\ndefinition nprt :: \"'a \\<Rightarrow> 'a\"\n  where \"nprt x = inf x 0\"\n\ndefinition pprt :: \"'a \\<Rightarrow> 'a\"\n  where \"pprt x = sup x 0\"\n\nlemma pprt_neg: \"pprt (- x) = - nprt x\"\nproof -\n  have \"sup (- x) 0 = sup (- x) (- 0)\"\n    by (simp only: minus_zero)\n  also have \"\\<dots> = - inf x 0\"\n    by (simp only: neg_inf_eq_sup)\n  finally have \"sup (- x) 0 = - inf x 0\" .\n  then show ?thesis\n    by (simp only: pprt_def nprt_def)\nqed\n\nlemma nprt_neg: \"nprt (- x) = - pprt x\"\nproof -\n  from pprt_neg have \"pprt (- (- x)) = - nprt (- x)\" .\n  then have \"pprt x = - nprt (- x)\" by simp\n  then show ?thesis by simp\nqed\n\nlemma prts: \"a = pprt a + nprt a\"\n  by (simp add: pprt_def nprt_def flip: add_eq_inf_sup)\n\nlemma zero_le_pprt[simp]: \"0 \\<le> pprt a\"\n  by (simp add: pprt_def)\n\nlemma nprt_le_zero[simp]: \"nprt a \\<le> 0\"\n  by (simp add: nprt_def)\n\nlemma le_eq_neg: \"a \\<le> - b \\<longleftrightarrow> a + b \\<le> 0\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n    by (rule add_le_imp_le_right[of _ \"uminus b\" _]) (simp add: add.assoc \\<open>?lhs\\<close>)\nnext\n  assume ?rhs\n  show ?lhs\n    by (rule add_le_imp_le_right[of _ \"b\" _]) (simp add: \\<open>?rhs\\<close>)\nqed\n\nlemma pprt_0[simp]: \"pprt 0 = 0\" by (simp add: pprt_def)\nlemma nprt_0[simp]: \"nprt 0 = 0\" by (simp add: nprt_def)\n\nlemma pprt_eq_id [simp, no_atp]: \"0 \\<le> x \\<Longrightarrow> pprt x = x\"\n  by (simp add: pprt_def sup_absorb1)\n\nlemma nprt_eq_id [simp, no_atp]: \"x \\<le> 0 \\<Longrightarrow> nprt x = x\"\n  by (simp add: nprt_def inf_absorb1)\n\nlemma pprt_eq_0 [simp, no_atp]: \"x \\<le> 0 \\<Longrightarrow> pprt x = 0\"\n  by (simp add: pprt_def sup_absorb2)\n\nlemma nprt_eq_0 [simp, no_atp]: \"0 \\<le> x \\<Longrightarrow> nprt x = 0\"\n  by (simp add: nprt_def inf_absorb2)\n\nlemma sup_0_imp_0:\n  assumes \"sup a (- a) = 0\"\n  shows \"a = 0\"\nproof -\n  have pos: \"0 \\<le> a\" if \"sup a (- a) = 0\" for a :: 'a\n  proof -\n    from that have \"sup a (- a) + a = a\"\n      by simp\n    then have \"sup (a + a) 0 = a\"\n      by (simp add: add_sup_distrib_right)\n    then have \"sup (a + a) 0 \\<le> a\"\n      by simp\n    then show ?thesis\n      by (blast intro: order_trans inf_sup_ord)\n  qed\n  from assms have **: \"sup (-a) (-(-a)) = 0\"\n    by (simp add: sup_commute)\n  from pos[OF assms] pos[OF **] show \"a = 0\"\n    by simp\nqed\n\nlemma inf_0_imp_0: \"inf a (- a) = 0 \\<Longrightarrow> a = 0\"\n  apply (simp add: inf_eq_neg_sup)\n  apply (simp add: sup_commute)\n  apply (erule sup_0_imp_0)\n  done\n\nlemma inf_0_eq_0 [simp, no_atp]: \"inf a (- a) = 0 \\<longleftrightarrow> a = 0\"\n  apply (rule iffI)\n   apply (erule inf_0_imp_0)\n  apply simp\n  done\n\nlemma sup_0_eq_0 [simp, no_atp]: \"sup a (- a) = 0 \\<longleftrightarrow> a = 0\"\n  apply (rule iffI)\n   apply (erule sup_0_imp_0)\n  apply simp\n  done\n\nlemma zero_le_double_add_iff_zero_le_single_add [simp]: \"0 \\<le> a + a \\<longleftrightarrow> 0 \\<le> a\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  show ?rhs if ?lhs\n  proof -\n    from that have a: \"inf (a + a) 0 = 0\"\n      by (simp add: inf_commute inf_absorb1)\n    have \"inf a 0 + inf a 0 = inf (inf (a + a) 0) a\"  (is \"?l = _\")\n      by (simp add: add_sup_inf_distribs inf_aci)\n    then have \"?l = 0 + inf a 0\"\n      by (simp add: a, simp add: inf_commute)\n    then have \"inf a 0 = 0\"\n      by (simp only: add_right_cancel)\n    then show ?thesis\n      unfolding le_iff_inf by (simp add: inf_commute)\n  qed\n  show ?lhs if ?rhs\n    by (simp add: add_mono[OF that that, simplified])\nqed\n\nlemma double_zero [simp]: \"a + a = 0 \\<longleftrightarrow> a = 0\"\n  using add_nonneg_eq_0_iff order.eq_iff by auto\n\nlemma zero_less_double_add_iff_zero_less_single_add [simp]: \"0 < a + a \\<longleftrightarrow> 0 < a\"\n  by (meson le_less_trans less_add_same_cancel2 less_le_not_le\n      zero_le_double_add_iff_zero_le_single_add)\n\nlemma double_add_le_zero_iff_single_add_le_zero [simp]: \"a + a \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\nproof -\n  have \"a + a \\<le> 0 \\<longleftrightarrow> 0 \\<le> - (a + a)\"\n    by (subst le_minus_iff) simp\n  moreover have \"\\<dots> \\<longleftrightarrow> a \\<le> 0\"\n    by (simp only: minus_add_distrib zero_le_double_add_iff_zero_le_single_add) simp\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma double_add_less_zero_iff_single_less_zero [simp]: \"a + a < 0 \\<longleftrightarrow> a < 0\"\nproof -\n  have \"a + a < 0 \\<longleftrightarrow> 0 < - (a + a)\"\n    by (subst less_minus_iff) simp\n  moreover have \"\\<dots> \\<longleftrightarrow> a < 0\"\n    by (simp only: minus_add_distrib zero_less_double_add_iff_zero_less_single_add) simp\n  ultimately show ?thesis\n    by blast\nqed\n\ndeclare neg_inf_eq_sup [simp]\n  and neg_sup_eq_inf [simp]\n  and diff_inf_eq_sup [simp]\n  and diff_sup_eq_inf [simp]\n\nlemma le_minus_self_iff: \"a \\<le> - a \\<longleftrightarrow> a \\<le> 0\"\nproof -\n  from add_le_cancel_left [of \"uminus a\" \"plus a a\" zero]\n  have \"a \\<le> - a \\<longleftrightarrow> a + a \\<le> 0\"\n    by (simp flip: add.assoc)\n  then show ?thesis\n    by simp\nqed\n\nlemma minus_le_self_iff: \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a\"\nproof -\n  have \"- a \\<le> a \\<longleftrightarrow> 0 \\<le> a + a\"\n    using add_le_cancel_left [of \"uminus a\" zero \"plus a a\"]\n    by (simp flip: add.assoc)\n  then show ?thesis\n    by simp\nqed\n\nlemma zero_le_iff_zero_nprt: \"0 \\<le> a \\<longleftrightarrow> nprt a = 0\"\n  unfolding le_iff_inf by (simp add: nprt_def inf_commute)\n\nlemma le_zero_iff_zero_pprt: \"a \\<le> 0 \\<longleftrightarrow> pprt a = 0\"\n  unfolding le_iff_sup by (simp add: pprt_def sup_commute)\n\nlemma le_zero_iff_pprt_id: \"0 \\<le> a \\<longleftrightarrow> pprt a = a\"\n  unfolding le_iff_sup by (simp add: pprt_def sup_commute)\n\nlemma zero_le_iff_nprt_id: \"a \\<le> 0 \\<longleftrightarrow> nprt a = a\"\n  unfolding le_iff_inf by (simp add: nprt_def inf_commute)\n\nlemma pprt_mono [simp, no_atp]: \"a \\<le> b \\<Longrightarrow> pprt a \\<le> pprt b\"\n  unfolding le_iff_sup by (simp add: pprt_def sup_aci sup_assoc [symmetric, of a])\n\nlemma nprt_mono [simp, no_atp]: \"a \\<le> b \\<Longrightarrow> nprt a \\<le> nprt b\"\n  unfolding le_iff_inf by (simp add: nprt_def inf_aci inf_assoc [symmetric, of a])\n\nend\n\nlemmas add_sup_inf_distribs =\n  add_inf_distrib_right add_inf_distrib_left add_sup_distrib_right add_sup_distrib_left\n\n\nclass lattice_ab_group_add_abs = lattice_ab_group_add + abs +\n  assumes abs_lattice: \"\\<bar>a\\<bar> = sup a (- a)\"\nbegin\n\nlemma abs_prts: \"\\<bar>a\\<bar> = pprt a - nprt a\"\nproof -\n  have \"0 \\<le> \\<bar>a\\<bar>\"\n  proof -\n    have a: \"a \\<le> \\<bar>a\\<bar>\" and b: \"- a \\<le> \\<bar>a\\<bar>\"\n      by (auto simp add: abs_lattice)\n    show ?thesis\n      by (rule add_mono [OF a b, simplified])\n  qed\n  then have \"0 \\<le> sup a (- a)\"\n    unfolding abs_lattice .\n  then have \"sup (sup a (- a)) 0 = sup a (- a)\"\n    by (rule sup_absorb1)\n  then show ?thesis\n    by (simp add: add_sup_inf_distribs ac_simps pprt_def nprt_def abs_lattice)\nqed\n\nsubclass ordered_ab_group_add_abs\nproof\n  have abs_ge_zero [simp]: \"0 \\<le> \\<bar>a\\<bar>\" for a\n  proof -\n    have a: \"a \\<le> \\<bar>a\\<bar>\" and b: \"- a \\<le> \\<bar>a\\<bar>\"\n      by (auto simp add: abs_lattice)\n    show \"0 \\<le> \\<bar>a\\<bar>\"\n      by (rule add_mono [OF a b, simplified])\n  qed\n  have abs_leI: \"a \\<le> b \\<Longrightarrow> - a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\" for a b\n    by (simp add: abs_lattice le_supI)\n  fix a b\n  show \"0 \\<le> \\<bar>a\\<bar>\"\n    by simp\n  show \"a \\<le> \\<bar>a\\<bar>\"\n    by (auto simp add: abs_lattice)\n  show \"\\<bar>-a\\<bar> = \\<bar>a\\<bar>\"\n    by (simp add: abs_lattice sup_commute)\n  show \"- a \\<le> b \\<Longrightarrow> \\<bar>a\\<bar> \\<le> b\" if \"a \\<le> b\"\n    using that by (rule abs_leI)\n  show \"\\<bar>a + b\\<bar> \\<le> \\<bar>a\\<bar> + \\<bar>b\\<bar>\"\n  proof -\n    have g: \"\\<bar>a\\<bar> + \\<bar>b\\<bar> = sup (a + b) (sup (- a - b) (sup (- a + b) (a + (- b))))\"\n      (is \"_ = sup ?m ?n\")\n      by (simp add: abs_lattice add_sup_inf_distribs ac_simps)\n    have a: \"a + b \\<le> sup ?m ?n\"\n      by simp\n    have b: \"- a - b \\<le> ?n\"\n      by simp\n    have c: \"?n \\<le> sup ?m ?n\"\n      by simp\n    from b c have d: \"- a - b \\<le> sup ?m ?n\"\n      by (rule order_trans)\n    have e: \"- a - b = - (a + b)\"\n      by simp\n    from a d e have \"\\<bar>a + b\\<bar> \\<le> sup ?m ?n\"\n      apply -\n      apply (drule abs_leI)\n       apply (simp_all only: algebra_simps minus_add)\n      apply (metis add_uminus_conv_diff d sup_commute uminus_add_conv_diff)\n      done\n    with g[symmetric] show ?thesis by simp\n  qed\nqed\n\nend\n\nlemma sup_eq_if:\n  fixes a :: \"'a::{lattice_ab_group_add,linorder}\"\n  shows \"sup a (- a) = (if a < 0 then - a else a)\"\n  using add_le_cancel_right [of a a \"- a\", symmetric, simplified]\n    and add_le_cancel_right [of \"-a\" a a, symmetric, simplified]\n  by (auto simp: sup_max max.absorb1 max.absorb2)\n\nlemma abs_if_lattice:\n  fixes a :: \"'a::{lattice_ab_group_add_abs,linorder}\"\n  shows \"\\<bar>a\\<bar> = (if a < 0 then - a else a)\"\n  by auto\n\nlemma estimate_by_abs:\n  fixes a b c :: \"'a::lattice_ab_group_add_abs\"\n  assumes \"a + b \\<le> c\"\n  shows \"a \\<le> c + \\<bar>b\\<bar>\"\nproof -\n  from assms have \"a \\<le> c + (- b)\"\n    by (simp add: algebra_simps)\n  have \"- b \\<le> \\<bar>b\\<bar>\"\n    by (rule abs_ge_minus_self)\n  then have \"c + (- b) \\<le> c + \\<bar>b\\<bar>\"\n    by (rule add_left_mono)\n  with \\<open>a \\<le> c + (- b)\\<close> show ?thesis\n    by (rule order_trans)\nqed\n\nclass lattice_ring = ordered_ring + lattice_ab_group_add_abs\nbegin\n\nsubclass semilattice_inf_ab_group_add ..\nsubclass semilattice_sup_ab_group_add ..\n\nend\n\nlemma abs_le_mult:\n  fixes a b :: \"'a::lattice_ring\"\n  shows \"\\<bar>a * b\\<bar> \\<le> \\<bar>a\\<bar> * \\<bar>b\\<bar>\"\nproof -\n  let ?x = \"pprt a * pprt b - pprt a * nprt b - nprt a * pprt b + nprt a * nprt b\"\n  let ?y = \"pprt a * pprt b + pprt a * nprt b + nprt a * pprt b + nprt a * nprt b\"\n  have a: \"\\<bar>a\\<bar> * \\<bar>b\\<bar> = ?x\"\n    by (simp only: abs_prts[of a] abs_prts[of b] algebra_simps)\n  have bh: \"u = a \\<Longrightarrow> v = b \\<Longrightarrow>\n            u * v = pprt a * pprt b + pprt a * nprt b +\n                    nprt a * pprt b + nprt a * nprt b\" for u v :: 'a\n    apply (subst prts[of u], subst prts[of v])\n    apply (simp add: algebra_simps)\n    done\n  note b = this[OF refl[of a] refl[of b]]\n  have xy: \"- ?x \\<le> ?y\"\n    apply simp\n    apply (metis (full_types) add_increasing add_uminus_conv_diff\n      lattice_ab_group_add_class.minus_le_self_iff minus_add_distrib mult_nonneg_nonneg\n      mult_nonpos_nonpos nprt_le_zero zero_le_pprt)\n    done\n  have yx: \"?y \\<le> ?x\"\n    apply simp\n    apply (metis (full_types) add_nonpos_nonpos add_uminus_conv_diff\n      lattice_ab_group_add_class.le_minus_self_iff minus_add_distrib mult_nonneg_nonpos\n      mult_nonpos_nonneg nprt_le_zero zero_le_pprt)\n    done\n  have i1: \"a * b \\<le> \\<bar>a\\<bar> * \\<bar>b\\<bar>\"\n    by (simp only: a b yx)\n  have i2: \"- (\\<bar>a\\<bar> * \\<bar>b\\<bar>) \\<le> a * b\"\n    by (simp only: a b xy)\n  show ?thesis\n    apply (rule abs_leI)\n    apply (simp add: i1)\n    apply (simp add: i2[simplified minus_le_iff])\n    done\nqed\n\ninstance lattice_ring \\<subseteq> ordered_ring_abs\nproof\n  fix a b :: \"'a::lattice_ring\"\n  assume a: \"(0 \\<le> a \\<or> a \\<le> 0) \\<and> (0 \\<le> b \\<or> b \\<le> 0)\"\n  show \"\\<bar>a * b\\<bar> = \\<bar>a\\<bar> * \\<bar>b\\<bar>\"\n  proof -\n    have s: \"(0 \\<le> a * b) \\<or> (a * b \\<le> 0)\"\n      apply auto\n      apply (rule_tac split_mult_pos_le)\n      apply (rule_tac contrapos_np[of \"a * b \\<le> 0\"])\n      apply simp\n      apply (rule_tac split_mult_neg_le)\n      using a\n      apply blast\n      done\n    have mulprts: \"a * b = (pprt a + nprt a) * (pprt b + nprt b)\"\n      by (simp flip: prts)\n    show ?thesis\n    proof (cases \"0 \\<le> a * b\")\n      case True\n      then show ?thesis\n        apply (simp_all add: mulprts abs_prts)\n        using a\n        apply (auto simp add:\n          algebra_simps\n          iffD1[OF zero_le_iff_zero_nprt] iffD1[OF le_zero_iff_zero_pprt]\n          iffD1[OF le_zero_iff_pprt_id] iffD1[OF zero_le_iff_nprt_id])\n        apply(drule (1) mult_nonneg_nonpos[of a b], simp)\n        apply(drule (1) mult_nonneg_nonpos2[of b a], simp)\n        done\n    next\n      case False\n      with s have \"a * b \\<le> 0\"\n        by simp\n      then show ?thesis\n        apply (simp_all add: mulprts abs_prts)\n        apply (insert a)\n        apply (auto simp add: algebra_simps)\n        apply(drule (1) mult_nonneg_nonneg[of a b],simp)\n        apply(drule (1) mult_nonpos_nonpos[of a b],simp)\n        done\n    qed\n  qed\nqed\n\nlemma mult_le_prts:\n  fixes a b :: \"'a::lattice_ring\"\n  assumes \"a1 \\<le> a\"\n    and \"a \\<le> a2\"\n    and \"b1 \\<le> b\"\n    and \"b \\<le> b2\"\n  shows \"a * b \\<le>\n    pprt a2 * pprt b2 + pprt a1 * nprt b2 + nprt a2 * pprt b1 + nprt a1 * nprt b1\"\nproof -\n  have \"a * b = (pprt a + nprt a) * (pprt b + nprt b)\"\n    by (subst prts[symmetric])+ simp\n  then have \"a * b = pprt a * pprt b + pprt a * nprt b + nprt a * pprt b + nprt a * nprt b\"\n    by (simp add: algebra_simps)\n  moreover have \"pprt a * pprt b \\<le> pprt a2 * pprt b2\"\n    by (simp_all add: assms mult_mono)\n  moreover have \"pprt a * nprt b \\<le> pprt a1 * nprt b2\"\n  proof -\n    have \"pprt a * nprt b \\<le> pprt a * nprt b2\"\n      by (simp add: mult_left_mono assms)\n    moreover have \"pprt a * nprt b2 \\<le> pprt a1 * nprt b2\"\n      by (simp add: mult_right_mono_neg assms)\n    ultimately show ?thesis\n      by simp\n  qed\n  moreover have \"nprt a * pprt b \\<le> nprt a2 * pprt b1\"\n  proof -\n    have \"nprt a * pprt b \\<le> nprt a2 * pprt b\"\n      by (simp add: mult_right_mono assms)\n    moreover have \"nprt a2 * pprt b \\<le> nprt a2 * pprt b1\"\n      by (simp add: mult_left_mono_neg assms)\n    ultimately show ?thesis\n      by simp\n  qed\n  moreover have \"nprt a * nprt b \\<le> nprt a1 * nprt b1\"\n  proof -\n    have \"nprt a * nprt b \\<le> nprt a * nprt b1\"\n      by (simp add: mult_left_mono_neg assms)\n    moreover have \"nprt a * nprt b1 \\<le> nprt a1 * nprt b1\"\n      by (simp add: mult_right_mono_neg assms)\n    ultimately show ?thesis\n      by simp\n  qed\n  ultimately show ?thesis\n    by - (rule add_mono | simp)+\nqed\n\nlemma mult_ge_prts:\n  fixes a b :: \"'a::lattice_ring\"\n  assumes \"a1 \\<le> a\"\n    and \"a \\<le> a2\"\n    and \"b1 \\<le> b\"\n    and \"b \\<le> b2\"\n  shows \"a * b \\<ge>\n    nprt a1 * pprt b2 + nprt a2 * nprt b2 + pprt a1 * pprt b1 + pprt a2 * nprt b1\"\nproof -\n  from assms have a1: \"- a2 \\<le> -a\"\n    by auto\n  from assms have a2: \"- a \\<le> -a1\"\n    by auto\n  from mult_le_prts[of \"- a2\" \"- a\" \"- a1\" \"b1\" b \"b2\",\n    OF a1 a2 assms(3) assms(4), simplified nprt_neg pprt_neg]\n  have le: \"- (a * b) \\<le>\n    - nprt a1 * pprt b2 + - nprt a2 * nprt b2 +\n    - pprt a1 * pprt b1 + - pprt a2 * nprt b1\"\n    by simp\n  then have \"- (- nprt a1 * pprt b2 + - nprt a2 * nprt b2 +\n      - pprt a1 * pprt b1 + - pprt a2 * nprt b1) \\<le> a * b\"\n    by (simp only: minus_le_iff)\n  then show ?thesis\n    by (simp add: algebra_simps)\nqed\n\ninstance int :: lattice_ring\nproof\n  show \"\\<bar>k\\<bar> = sup k (- k)\" for k :: int\n    by (auto simp add: sup_int_def)\nqed\n\ninstance real :: lattice_ring\nproof\n  show \"\\<bar>a\\<bar> = sup a (- a)\" for a :: real\n    by (auto simp add: sup_real_def)\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Lattice_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011834, "lm_q2_score": 0.8633916029436189, "lm_q1q2_score": 0.7632720951696242}}
{"text": "(*\n    $Id: sol.thy,v 1.3 2011/06/28 18:11:38 webertj Exp $\n    Author: Tjark Weber\n*)\n\nheader {* Quantifying Lists *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {* Define a universal and an existential quantifier on lists\nusing primitive recursion.  Expression @{term \"alls P xs\"} should\nbe true iff @{term \"P x\"} holds for every element @{term x} of\n@{term xs}, and @{term \"exs P xs\"} should be true iff @{term \"P x\"}\nholds for some element @{term x} of @{term xs}.\n*}\n\nprimrec alls :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"alls P []     = True\"\n| \"alls P (x#xs) = (P x \\<and> alls P xs)\"\n\nprimrec exs  :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"exs P []     = False\"\n| \"exs P (x#xs) = (P x \\<or> exs P xs)\"\n\ntext {*\nProve or disprove (by counterexample) the following theorems.\nYou may have to prove some lemmas first.\n\nUse the @{text \"[simp]\"}-attribute only if the equation is truly a\nsimplification and is necessary for some later proof.\n*}\n\nlemma \"alls (\\<lambda>x. P x \\<and> Q x) xs = (alls P xs \\<and> alls Q xs)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma alls_append: \"alls P (xs @ ys) = (alls P xs \\<and> alls P ys)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma \"alls P (rev xs) = alls P xs\"\n  apply (induct \"xs\")\n  apply (auto simp add: alls_append)\ndone\n\nlemma \"exs (\\<lambda>x. P x \\<and> Q x) xs = (exs P xs \\<and> exs Q xs)\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample is:\n  P = even, Q = odd, xs = [0, 1]\n*}\n\nlemma \"exs P (map f xs) = exs (P o f) xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma exs_append: \"exs P (xs @ ys) = (exs P xs \\<or> exs P ys)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma \"exs P (rev xs) = exs P xs\"\n  apply (induct \"xs\")\n  apply (auto simp add: exs_append)\ndone\n\ntext {* Find a (non-trivial) term @{text Z} such that the following equation holds: *}\n\nlemma \"exs (\\<lambda>x. P x \\<or> Q x) xs = Z\"\n(*<*)oops(*>*)\n\nlemma \"exs (\\<lambda>x. P x \\<or> Q x) xs = (exs P xs \\<or> exs Q xs)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntext {* Express the existential via the universal quantifier --\n@{text exs} should not occur on the right-hand side: *}\n\nlemma \"exs P xs = Z\"\n(*<*)oops(*>*)\n\nlemma \"exs P xs = (\\<not> alls (\\<lambda>x. \\<not> P x) xs)\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntext {*\nDefine a primitive-recursive function @{term \"is_in x xs\"} that\nchecks if @{term x} occurs in @{term xs}. Now express\n@{text is_in} via @{term exs}:\n*}\n\nprimrec is_in :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"is_in x []     = False\"\n| \"is_in x (z#zs) = (x=z \\<or> is_in x zs)\"\n\nlemma \"is_in a xs = exs (\\<lambda>x. x=a) xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\ntext {* Define a primitive-recursive function @{term \"nodups xs\"}\nthat is true iff @{term xs} does not contain duplicates, and a\nfunction @{term \"deldups xs\"} that removes all duplicates.  Note\nthat @{term \"deldups[x,y,x]\"} (where @{term x} and @{term y} are\ndistinct) can be either @{term \"[x,y]\"} or @{term \"[y,x]\"}.\n*}\n\nprimrec nodups :: \"'a list \\<Rightarrow> bool\" where\n  \"nodups []     = True\"\n| \"nodups (x#xs) = (\\<not> is_in x xs \\<and> nodups xs)\"\n\nprimrec deldups :: \"'a list \\<Rightarrow> 'a list\" where\n  \"deldups []     = []\"\n| \"deldups (x#xs) = (if is_in x xs then deldups xs else x # deldups xs)\"\n\ntext {*\nProve or disprove (by counterexample) the following theorems.\n*}\n\nlemma \"length (deldups xs) <= length xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma is_in_deldups: \"is_in a (deldups xs) = is_in a xs\"\n  apply (induct \"xs\")\n  apply auto\ndone\n\nlemma \"nodups (deldups xs)\"\n  apply (induct \"xs\")\n  apply (auto simp add: is_in_deldups)\ndone\n\nlemma \"deldups (rev xs) = rev (deldups xs)\"\n  quickcheck\noops\n\ntext {*\n  A possible counterexample is:\n  xs = [0, 1, 0]\n*}\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/lists/quant/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7632720889546849}}
{"text": "(*  \n    Author:      René Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Gram-Schmidt Orthogonalization\\<close>\n\ntext \\<open>\n  This theory provides the Gram-Schmidt orthogonalization algorithm,\n  that takes the conjugate operation into account. It works over fields\n  like the rational, real, or complex numbers. \n\\<close>\n\ntheory Gram_Schmidt\nimports \n  VS_Connect \n  Missing_VectorSpace\n  Conjugate\nbegin\n\nsubsection \\<open>Orthogonality with Conjugates\\<close>\n\ndefinition \"corthogonal vs \\<equiv>\n    \\<forall>i < length vs. \\<forall>j < length vs. vs ! i \\<bullet>c vs ! j = 0 \\<longleftrightarrow> i \\<noteq> j\"\n\nlemma corthogonalD[elim]:\n  \"corthogonal vs \\<Longrightarrow> i < length vs \\<Longrightarrow> j < length vs \\<Longrightarrow>\n   vs ! i \\<bullet>c vs ! j = 0 \\<longleftrightarrow> i \\<noteq> j\"\n  unfolding corthogonal_def by auto\n\nlemma corthogonalI[intro]:\n  \"(\\<And>i j. i < length vs \\<Longrightarrow> j < length vs \\<Longrightarrow> vs ! i \\<bullet>c vs ! j = 0 \\<longleftrightarrow> i \\<noteq> j) \\<Longrightarrow>\n   corthogonal vs\"\n  unfolding corthogonal_def by auto\n\nlemma corthogonal_distinct: \"corthogonal us \\<Longrightarrow> distinct us\"\nproof (induct us)\n  case (Cons u us)\n    have \"u \\<notin> set us\"\n    proof\n      assume \"u : set us\"\n      then obtain j where uj: \"u = us!j\" and j: \"j < length us\"\n        using in_set_conv_nth by metis\n      hence j': \"j+1 < length (u#us)\" by auto\n      have \"u \\<bullet>c us!j = 0\"\n        using corthogonalD[OF Cons(2) _ j',of 0] by auto\n      hence \"u \\<bullet>c u = 0\" using uj by simp\n      thus False using corthogonalD[OF Cons(2),of 0 0] by auto\n    qed\n    moreover have \"distinct us\"\n    proof (rule Cons(1),intro corthogonalI)\n      fix i j assume \"i < length (us)\" \"j < length (us)\"\n      hence len: \"i+1 < length (u#us)\" \"j+1 < length (u#us)\" by auto\n      show \"(us!i \\<bullet>c us!j = 0) = (i\\<noteq>j)\"\n        using corthogonalD[OF Cons(2) len] by simp\n    qed\n    ultimately show ?case by simp\nqed simp\n\nlemma corthogonal_sort:\n  assumes dist': \"distinct us'\"\n      and mem: \"set us = set us'\"\n  shows \"corthogonal us \\<Longrightarrow> corthogonal us'\"\nproof\n  assume orth: \"corthogonal us\"\n  hence dist: \"distinct us\" using corthogonal_distinct by auto\n  fix i' j' assume i': \"i' < length us'\" and j': \"j' < length us'\"\n  obtain i where ii': \"us!i = us'!i'\" and i: \"i < length us\"\n    using mem i' in_set_conv_nth by metis\n  obtain j where jj': \"us!j = us'!j'\" and j: \"j < length us\"\n    using mem j' in_set_conv_nth by metis\n  from corthogonalD[OF orth i j]\n  have \"(us!i \\<bullet>c us!j = 0) = (i \\<noteq> j)\".\n  hence \"(us'!i' \\<bullet>c us'!j' = 0) = (i \\<noteq> j)\" using ii' jj' by auto\n  also have \"... = (us!i \\<noteq> us!j)\" using nth_eq_iff_index_eq dist i j by auto\n  also have \"... = (us'!i' \\<noteq> us'!j')\" using ii' jj' by auto\n  also have \"... = (i' \\<noteq> j')\" using nth_eq_iff_index_eq dist' i' j' by auto\n  finally show \"(us'!i' \\<bullet>c us'!j' = 0) = (i' \\<noteq> j')\".\nqed\n\nsubsection\\<open>The Algorithm\\<close>\n\nfun adjuster :: \"nat \\<Rightarrow> 'a :: conjugatable_field vec \\<Rightarrow> 'a vec list \\<Rightarrow> 'a vec\"\n  where \"adjuster n w [] = 0\\<^sub>v n\"\n    |  \"adjuster n w (u#us) = -(w \\<bullet>c u)/(u \\<bullet>c u) \\<cdot>\\<^sub>v u + adjuster n w us\"\n\ntext \\<open>\n  The following formulation is easier to analyze,\n  but outputs of the subroutine should be properly reversed.\n\\<close>\n\nfun gram_schmidt_sub\n  where \"gram_schmidt_sub n us [] = us\"\n  | \"gram_schmidt_sub n us (w # ws) =\n     gram_schmidt_sub n ((adjuster n w us + w) # us) ws\"\n\ndefinition gram_schmidt :: \"nat \\<Rightarrow> 'a :: conjugatable_field vec list \\<Rightarrow> 'a vec list\"\n  where \"gram_schmidt n ws = rev (gram_schmidt_sub n [] ws)\"\n\ntext \\<open>\n  The following formulation requires no reversal.\n\\<close>\n\nfun gram_schmidt_sub2\n  where \"gram_schmidt_sub2 n us [] = []\"\n  | \"gram_schmidt_sub2 n us (w # ws) =\n     (let u = adjuster n w us + w in\n      u # gram_schmidt_sub2 n (u # us) ws)\"\n\nlemma gram_schmidt_sub_eq:\n  \"rev (gram_schmidt_sub n us ws) = rev us @ gram_schmidt_sub2 n us ws\"\n  by (induct ws arbitrary:us, auto simp:Let_def)\n\nlemma gram_schmidt_code[code]:\n  \"gram_schmidt n ws = gram_schmidt_sub2 n [] ws\"\n  unfolding gram_schmidt_def\n  apply(subst gram_schmidt_sub_eq) by simp\n\nsubsection \\<open>Properties of the Algorithms\\<close>\n\nlocale cof_vec_space = vec_space f_ty for\n  f_ty :: \"'a :: conjugatable_ordered_field itself\"\nbegin\n\nlemma adjuster_finsum:\n  assumes U: \"set us \\<subseteq> carrier_vec n\"\n    and dist: \"distinct (us :: 'a vec list)\"\n  shows \"adjuster n w us = finsum V (\\<lambda>u. -(w \\<bullet>c u)/(u \\<bullet>c u) \\<cdot>\\<^sub>v u) (set us)\"\n  using assms\nproof (induct us)\n  case Cons show ?case unfolding set_simps\n  by (subst finsum_insert[OF finite_set], insert Cons, auto)\nqed simp\n\nlemma adjuster_lincomb:\n  assumes w: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"adjuster n w us = lincomb (\\<lambda>u. -(w \\<bullet>c u)/(u \\<bullet>c u)) (set us)\"\n    (is \"_ = lincomb ?a _\")\n  using us dist unfolding lincomb_def\nproof (induct us)\n  case (Cons u us)\n    let ?f = \"\\<lambda>u. ?a u \\<cdot>\\<^sub>v u\"\n    have \"?f : (set us) \\<rightarrow> carrier_vec n\" and \"?f u : carrier_vec n\" using w Cons by auto\n    moreover have \"u \\<notin> set us\" using Cons by auto\n    ultimately show ?case\n      unfolding adjuster.simps\n      unfolding set_simps\n      using finsum_insert[OF finite_set] Cons by auto\nqed simp\n\nlemma adjuster_in_span:\n  assumes w: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"adjuster n w us : span (set us)\"\n  using adjuster_lincomb[OF assms]\n  unfolding finite_span[OF finite_set us] by auto\n\nlemma adjuster_carrier[simp]:\n  assumes w: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"adjuster n w us : carrier_vec n\"\n  using adjuster_in_span span_closed assms by auto\n\nlemma adjust_not_in_span:\n  assumes w[simp]: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n    and ind: \"w \\<notin> span (set us)\"\n  shows \"adjuster n w us + w \\<notin> span (set us)\"\n  using span_add[OF us adjuster_in_span[OF w us dist] w]\n  using comm_add_vec ind by auto\n\nlemma adjust_not_mem:\n  assumes w[simp]: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n    and ind: \"w \\<notin> span (set us)\"\n  shows \"adjuster n w us + w \\<notin> set us\"\n  using adjust_not_in_span[OF assms] span_mem[OF us] by auto\n\nlemma adjust_in_span:\n  assumes w[simp]: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"adjuster n w us + w : span (insert w (set us))\" (is \"?v + _ : span ?U\")\nproof -\n  let ?a = \"\\<lambda>u. -(w \\<bullet>c u)/(u \\<bullet>c u)\"\n  have \"?v = lincomb ?a (set us)\" using adjuster_lincomb[OF assms].\n  hence vU: \"?v : span (set us)\" unfolding finite_span[OF finite_set us] by auto\n  hence v[simp]: \"?v : carrier_vec n\" using span_closed[OF us] by auto\n  have vU': \"?v : span ?U\" using vU span_is_monotone[OF subset_insertI] by auto\n\n  have \"{w} \\<subseteq> ?U\" by simp\n  from span_is_monotone[OF this]\n  have wU': \"w : span ?U\" using span_self[OF w] by auto\n\n  have \"?U \\<subseteq> carrier_vec n\" using us w by simp\n  from span_add[OF this wU' v] vU' comm_add_vec[OF w]\n  show ?thesis by simp\nqed\n\nlemma adjust_not_lindep:\n  assumes w[simp]: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n    and wus: \"w \\<notin> span (set us)\"\n    and ind: \"~ lin_dep (set us)\"\n  shows \"~ lin_dep (insert (adjuster n w us + w) (set us))\"\n    (is \"~ _ (insert ?v _)\")\nproof -\n  have v: \"?v : carrier_vec n\" using assms by auto\n  have \"?v \\<notin> span (set us)\"\n    using adjust_not_in_span[OF w us dist wus]\n    using comm_add_vec[OF adjuster_carrier[OF w us dist] w] by auto\n  thus ?thesis\n    using lin_dep_iff_in_span[OF us ind v] adjust_not_mem[OF w us dist wus] by auto\nqed\n\nlemma adjust_preserves_span:\n  assumes w[simp]: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"w : span (set us) \\<longleftrightarrow> adjuster n w us + w : span (set us)\"\n    (is \"_ \\<longleftrightarrow> ?v + _ : _\")\nproof -\n  have \"?v : span (set us)\"\n    using adjuster_lincomb[OF assms]\n    unfolding finite_span[OF finite_set us] by auto\n  hence [simp]: \"?v : carrier_vec n\" using span_closed[OF us] by auto\n  show ?thesis\n    using span_add[OF us adjuster_in_span[OF w us] w] comm_add_vec[OF w] dist\n    by auto\nqed\n\nlemma in_span_adjust:\n  assumes w[simp]: \"(w :: 'a vec) : carrier_vec n\"\n    and us: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"w : span (insert (adjuster n w us + w) (set us))\"\n    (is \"_ : span (insert ?v _)\")\nproof -\n  have v: \"?v : carrier_vec n\" using assms by auto\n  have a[simp]: \"adjuster n w us : carrier_vec n\"\n   and neg: \"- adjuster n w us : carrier_vec n\" using assms by auto\n  hence vU: \"insert ?v (set us) \\<subseteq> carrier_vec n\" using us by auto\n  have aS: \"adjuster n w us : span (insert ?v (set us))\"\n    using adjuster_in_span[OF w us] span_is_monotone[OF subset_insertI] dist\n    by auto\n  have negS: \"- adjuster n w us : span (insert ?v (set us))\"\n    using span_neg[OF vU aS] us by simp\n  have [simp]:\"- adjuster n w us + (adjuster n w us + w) = w\"\n    unfolding a_assoc[OF neg a w,symmetric] by simp\n  have \"{?v} \\<subseteq> insert ?v (set us)\" by simp\n  from span_is_monotone[OF this]\n  have vS: \"?v : span (insert ?v (set us))\" using span_self[OF v] by auto\n  thus ?thesis using span_add[OF vU negS v] by auto\nqed\n\nlemma adjust_zero:\n  assumes U: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and orth: \"corthogonal us\"\n    and w[simp]: \"w : carrier_vec n\"\n    and i: \"i < length us\"\n  shows \"(adjuster n w us + w) \\<bullet>c us!i = 0\"\nproof -\n  define u where \"u = us!i\"\n  have u[simp]: \"u : carrier_vec n\" using i U u_def by auto\n  hence cu[simp]: \"conjugate u : carrier_vec n\" by auto\n  have uU: \"u : set us\" using i u_def by auto\n  let ?g = \"\\<lambda>u'::'a vec. (-(w \\<bullet>c u')/(u' \\<bullet>c u') \\<cdot>\\<^sub>v u')\"\n  have g: \"?g : set us \\<rightarrow> carrier_vec n\" using w U by auto\n  hence carrier: \"finsum V ?g (set us) : carrier_vec n\" by simp\n  let ?f = \"\\<lambda>u'. ?g u' \\<bullet>c u\"\n  let ?U = \"set us - {u}\"\n  { fix u' assume u': \"(u'::'a vec) : carrier_vec n\"\n    have [simp]: \"dim_vec u = n\" by auto\n    have \"?f u' = (- (w \\<bullet>c u') / (u' \\<bullet>c u')) * (u' \\<bullet>c u)\"\n      using scalar_prod_smult_left[of \"u'\" \"conjugate u\"]\n      unfolding carrier_vecD[OF u] carrier_vecD[OF u'] by auto\n  } note conv = this\n  have \"?f : ?U \\<rightarrow> {0}\"\n  proof (intro Pi_I)\n    fix u' assume u'Uu: \"u' : set us - {u}\"\n    hence u'U: \"u' : set us\" by auto\n    hence u'[simp]: \"u' : carrier_vec n\" using U by auto\n    obtain j where j: \"j < length us\" and u'j: \"u' = us ! j\"\n      using u'U in_set_conv_nth by metis\n    have \"i \\<noteq> j\" using u'Uu u'j u_def by auto\n    hence \"u' \\<bullet>c u = 0\"\n      unfolding u'j using corthogonalD[OF orth j i] u_def by auto\n    hence \"?f u' = 0\" using mult_zero_right conv[OF u'] by auto\n    thus \"?f u' : {0}\" by auto\n  qed\n  hence \"restrict ?f ?U = restrict (\\<lambda>u. 0) ?U\" by force\n  hence \"sum ?f ?U = sum (\\<lambda>u. 0) ?U\"\n    by (intro R.finsum_restrict, auto)\n  hence fU'0: \"sum ?f ?U = 0\" by auto\n  have uU': \"u \\<notin> ?U\" by auto\n  have \"set us = insert u ?U\"\n    using insert_Diff_single uU by auto\n  hence \"sum ?f (set us) = ?f u + sum ?f ?U\"\n    using R.finsum_insert[OF _ uU'] by auto\n  also have \"... = ?f u\" using fU'0 by auto\n  also have \"... = - (w \\<bullet>c u) / (u \\<bullet>c u) * (u \\<bullet>c u)\"\n    using conv[OF u] by auto\n  finally have main: \"sum ?f (set us) = - (w \\<bullet>c u)\"\n    unfolding u_def\n    by (simp add: i orth corthogonalD)\n  show ?thesis\n    unfolding u_def[symmetric]\n    unfolding adjuster_finsum[OF U corthogonal_distinct[OF orth]]\n    unfolding add_scalar_prod_distrib[OF carrier w cu]\n    unfolding finsum_scalar_prod_sum[OF g cu]\n    unfolding main\n    unfolding comm_scalar_prod[OF cu w]\n    using left_minus by auto\nqed\n\nlemma adjust_nonzero:\n  assumes U: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n    and w[simp]: \"w : carrier_vec n\"\n    and wsU: \"w \\<notin> span (set us)\"\n  shows \"adjuster n w us + w \\<noteq> 0\\<^sub>v n\" (is \"?a + _ \\<noteq> _\")\nproof\n  have [simp]: \"?a : carrier_vec n\" using U dist by auto\n  have [simp]: \"- ?a : carrier_vec n\" by auto\n  have [simp]: \"?a + w : carrier_vec n\" by auto\n  assume \"?a + w = 0\\<^sub>v n\"\n  hence \"- ?a = - ?a + (?a + w)\" by auto\n  also have \"... = (- ?a + ?a) + w\" apply(subst a_assoc) by auto\n  also have \"- ?a + ?a = 0\\<^sub>v n\" using r_neg[OF w] unfolding vec_neg[OF w] by auto\n  finally have \"- ?a = w\" by auto\n  moreover have \"- ?a : span (set us)\"\n    using span_neg[OF U adjuster_in_span[OF w U dist]] by auto\n  ultimately show \"False\" using wsU by auto\nqed\n\nlemma adjust_orthogonal:\n  assumes U: \"set (us :: 'a vec list) \\<subseteq> carrier_vec n\"\n    and orth: \"corthogonal us\"\n    and w[simp]: \"w : carrier_vec n\"\n    and wsU: \"w \\<notin> span (set us)\"\n  shows \"corthogonal ((adjuster n w us + w) # us)\"\n    (is \"corthogonal (?aw # _)\")\nproof\n  have dist: \"distinct us\" using corthogonal_distinct orth by auto\n  have aw[simp]: \"?aw : carrier_vec n\" using U dist by auto\n  note adjust_nonzero[OF U dist w] wsU\n  hence aw0: \"?aw \\<bullet>c ?aw \\<noteq> 0\" using conjugate_square_eq_0_vec[OF aw] by auto\n  fix i j assume i: \"i < length (?aw # us)\" and j: \"j < length (?aw # us)\"\n  show \"((?aw # us) ! i \\<bullet>c (?aw # us) ! j = 0) = (i \\<noteq> j)\"\n  proof (cases \"i = 0\")\n    case True note i0 = this\n      show ?thesis\n      proof (cases \"j = 0\")\n        case True show ?thesis unfolding True i0 using aw0 by auto\n        next case False\n          define j' where \"j' = j-1\"\n          hence jfold: \"j = j'+1\" using False by auto\n          hence j': \"j' < length us\" using j by auto\n          show ?thesis unfolding i0 jfold\n            using adjust_zero[OF U orth w j'] by auto\n      qed\n    next case False\n      define i' where \"i' = i-1\"\n      hence ifold: \"i = i'+1\" using False by auto\n      hence i': \"i' < length us\" using i by auto\n      have [simp]: \"us ! i' : carrier_vec n\" using U i' by auto\n      hence cu': \"conjugate (us ! i') : carrier_vec n\" by auto\n      show ?thesis\n      proof (cases \"j = 0\")\n        case True\n          { assume \"?aw \\<bullet>c us ! i' = 0\"\n            hence \"conjugate (?aw \\<bullet>c us ! i') = 0\" using conjugate_zero by auto\n            hence \"conjugate ?aw \\<bullet> us ! i' = 0\"\n              using conjugate_sprod_vec[OF aw cu'] by auto\n          }\n          thus ?thesis unfolding True ifold\n          using adjust_zero[OF U orth w i']\n          by (subst comm_scalar_prod[of _ n], auto)\n        next case False\n          define j' where \"j' = j-1\"\n          hence jfold: \"j = j'+1\" using False by auto\n          hence j': \"j' < length us\" using j by auto\n          show ?thesis\n            unfolding ifold jfold\n            using orth i' j' by (auto simp: corthogonalD)\n     qed\n  qed\nqed\n\nlemma gram_schmidt_sub_span:\n  assumes w[simp]: \"w : carrier_vec n\"\n    and us: \"set us \\<subseteq> carrier_vec n\"\n    and dist: \"distinct us\"\n  shows \"span (set ((adjuster n w us + w) # us)) = span (set (w # us))\"\n  (is \"span (set (?v # _)) = span ?wU\")\nproof (cases \"w : span (set us)\")\n  case True\n    hence \"?v : span (set us)\"\n      using adjust_preserves_span[OF assms] by auto\n    thus ?thesis using already_in_span[OF us] True by auto next\n  case False show ?thesis\n    proof\n      have wU: \"?wU \\<subseteq> carrier_vec n\" using us by simp \n      have vswU: \"?v : span ?wU\" using adjust_in_span[OF assms] by auto\n      hence v: \"?v : carrier_vec n\" using span_closed[OF wU] by auto\n      have wsvU: \"w : span (insert ?v (set us))\" using in_span_adjust[OF assms].\n      show \"span ?wU \\<subseteq> span (set (?v # us))\"\n        using span_swap[OF finite_set us w False v wsvU] by auto\n      have \"?v \\<notin> span (set us)\"\n        using False adjust_preserves_span[OF assms] by auto\n      thus \"span (set (?v # us)) \\<subseteq> span ?wU\"\n        using span_swap[OF finite_set us v _ w] vswU by auto\n    qed\nqed\n\nlemma gram_schmidt_sub_result:\n  assumes \"gram_schmidt_sub n us ws = us'\"\n    and \"set ws \\<subseteq> carrier_vec n\"\n    and \"set us \\<subseteq> carrier_vec n\"\n    and \"distinct (us @ ws)\"\n    and \"~ lin_dep (set (us @ ws))\"\n    and \"corthogonal us\"\n  shows \"set us' \\<subseteq> carrier_vec n \\<and>\n         distinct us' \\<and>\n         corthogonal us' \\<and>\n         span (set (us @ ws)) = span (set us') \\<and> length us' = length us + length ws\"  \n  using assms\nproof (induct ws arbitrary: us us')\ncase (Cons w ws)\n  let ?v = \"adjuster n w us\"\n  have wW[simp]: \"set (w#ws) \\<subseteq> carrier_vec n\" using Cons by simp\n  hence W[simp]: \"set ws \\<subseteq> carrier_vec n\"\n   and w[simp]: \"w : carrier_vec n\" by auto\n  have U[simp]: \"set us \\<subseteq> carrier_vec n\" using Cons by simp\n  have UW: \"set (us@ws) \\<subseteq> carrier_vec n\" by simp\n  have wU: \"set (w#us) \\<subseteq> carrier_vec n\" by simp\n  have dist: \"distinct (us @ w # ws)\" using Cons by simp\n  hence dist_U: \"distinct us\"\n    and dist_W: \"distinct ws\"\n    and dist_UW: \"distinct (us @ ws)\"\n    and w_U: \"w \\<notin> set us\"\n    and w_W: \"w \\<notin> set ws\"\n    and w_UW: \"w \\<notin> set (us @ ws)\" by auto\n  have ind: \"~ lin_dep (set (us @ w # ws))\" using Cons by simp\n  have ind_U: \"~ lin_dep (set us)\"\n    and ind_W: \"~ lin_dep (set ws)\"\n    and ind_wU: \"~ lin_dep (insert w (set us))\"\n    and ind_UW: \"~ lin_dep (set (us @ ws))\"\n    by (subst subset_li_is_li[OF ind];auto)+\n  have corth: \"corthogonal us\" using Cons by simp\n  have U'def: \"gram_schmidt_sub n ((?v + w)#us) ws = us'\" using Cons by simp\n\n  have v: \"?v : carrier_vec n\" using dist_U by auto\n  hence vw: \"?v + w : carrier_vec n\" by auto\n  hence vwU: \"set ((?v + w) # us) \\<subseteq> carrier_vec n\" by auto\n  have vsU: \"?v : span (set us)\" using adjuster_in_span[OF w] dist by auto\n  hence vsUW: \"?v : span (set (us @ ws))\"\n    using span_is_monotone[of \"set us\" \"set (us@ws)\"] by auto\n  have wsU: \"w \\<notin> span (set us)\"\n    using lin_dep_iff_in_span[OF U ind_U w w_U] ind_wU by auto\n  hence vwU: \"?v + w \\<notin> span (set us)\" using adjust_not_in_span[OF w U dist_U] by auto\n\n  have \"w \\<notin> span (set (us@ws))\" using lin_dep_iff_in_span[OF _ ind_UW] dist ind by auto\n  hence span: \"?v + w \\<notin> span (set (us@ws))\" using span_add[OF UW vsUW w] by auto\n  hence vwUS: \"?v + w \\<notin> set (us @ ws)\" using span_mem by auto\n  hence ind2: \"~ lin_dep (set (((?v + w) # us) @ ws))\"\n    using lin_dep_iff_in_span[OF UW ind_UW vw] span by auto\n\n  have vwU: \"set ((?v + w) # us) \\<subseteq> carrier_vec n\" using U w dist by auto\n  have dist2: \"distinct (((?v + w) # us) @ ws)\" using dist vwUS by simp\n\n  have orth2: \"corthogonal ((adjuster n w us + w) # us)\"\n    using adjust_orthogonal[OF U corth w wsU].\n\n  show ?case\n    using Cons(1)[OF U'def W vwU dist2 ind2] orth2\n    using span_Un[OF vwU wU gram_schmidt_sub_span[OF w U dist_U] W W] by auto\n    \nqed simp\n\nlemma gram_schmidt_hd [simp]:\n  assumes [simp]: \"w : carrier_vec n\" shows \"hd (gram_schmidt n (w#ws)) = w\"\n  unfolding gram_schmidt_code by simp\n\ntheorem gram_schmidt_result:\n  assumes ws: \"set ws \\<subseteq> carrier_vec n\"\n    and dist: \"distinct ws\"\n    and ind: \"~ lin_dep (set ws)\"\n    and us: \"us = gram_schmidt n ws\"\n  shows \"span (set ws) = span (set us)\"\n    and \"corthogonal us\"\n    and \"set us \\<subseteq> carrier_vec n\"\n    and \"length us = length ws\"\n    and \"distinct us\"\nproof -\n  have main: \"gram_schmidt_sub n [] ws = rev us\"\n    using us unfolding gram_schmidt_def\n    using gram_schmidt_sub_eq by auto\n  have orth: \"corthogonal []\" by auto\n  have \"span (set ws) = span (set (rev us))\"\n   and orth2: \"corthogonal (rev us)\"\n   and \"set us \\<subseteq> carrier_vec n\"\n   and \"length us = length ws\"\n   and dist: \"distinct us\" \n    using gram_schmidt_sub_result[OF main ws]\n    by (auto simp: assms orth)\n  thus \"span (set ws) = span (set us)\" by simp\n  show \"set us \\<subseteq> carrier_vec n\" by fact\n  show \"length us = length ws\" by fact\n  show \"distinct us\" by fact\n  show \"corthogonal us\"\n    using corthogonal_distinct[OF orth2] unfolding distinct_rev\n    using corthogonal_sort[OF _ set_rev orth2] by auto\nqed\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Jordan_Normal_Form/Gram_Schmidt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.891811054783143, "lm_q1q2_score": 0.7632575141142344}}
{"text": "section\\<open>Lindelöf spaces\\<close>\n\ntheory Lindelof_Spaces\nimports T1_Spaces\nbegin\n\ndefinition Lindelof_space where\n  \"Lindelof_space X \\<equiv>\n        \\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> \\<Union>\\<U> = topspace X\n            \\<longrightarrow> (\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> \\<Union>\\<V> = topspace X)\"\n\nlemma Lindelof_spaceD:\n  \"\\<lbrakk>Lindelof_space X; \\<And>U. U \\<in> \\<U> \\<Longrightarrow> openin X U; \\<Union>\\<U> = topspace X\\<rbrakk>\n  \\<Longrightarrow> \\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> \\<Union>\\<V> = topspace X\"\n  by (auto simp: Lindelof_space_def)\n\nlemma Lindelof_space_alt:\n   \"Lindelof_space X \\<longleftrightarrow>\n        (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> topspace X \\<subseteq> \\<Union>\\<U>\n             \\<longrightarrow> (\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> topspace X \\<subseteq> \\<Union>\\<V>))\"\n  unfolding Lindelof_space_def\n  using openin_subset by fastforce\n\nlemma compact_imp_Lindelof_space:\n   \"compact_space X \\<Longrightarrow> Lindelof_space X\"\n  unfolding Lindelof_space_def compact_space\n  by (meson uncountable_infinite)\n\nlemma Lindelof_space_topspace_empty:\n   \"topspace X = {} \\<Longrightarrow> Lindelof_space X\"\n  using compact_imp_Lindelof_space compact_space_topspace_empty by blast\n\nlemma Lindelof_space_Union:\n  assumes \\<U>: \"countable \\<U>\" and lin: \"\\<And>U. U \\<in> \\<U> \\<Longrightarrow> Lindelof_space (subtopology X U)\"\n  shows \"Lindelof_space (subtopology X (\\<Union>\\<U>))\"\nproof -\n  have \"\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<F> \\<and> \\<Union>\\<U> \\<inter> \\<Union>\\<V> = topspace X \\<inter> \\<Union>\\<U>\"\n    if \\<F>: \"\\<F> \\<subseteq> Collect (openin X)\" and UF: \"\\<Union>\\<U> \\<inter> \\<Union>\\<F> = topspace X \\<inter> \\<Union>\\<U>\"\n    for \\<F>\n  proof -\n    have \"\\<And>U. \\<lbrakk>U \\<in> \\<U>; U \\<inter> \\<Union>\\<F> = topspace X \\<inter> U\\<rbrakk>\n               \\<Longrightarrow> \\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<F> \\<and> U \\<inter> \\<Union>\\<V> = topspace X \\<inter> U\"\n      using lin \\<F>\n      unfolding Lindelof_space_def openin_subtopology_alt Ball_def subset_iff [symmetric]\n      by (simp add: all_subset_image imp_conjL ex_countable_subset_image)\n    then obtain g where g: \"\\<And>U. \\<lbrakk>U \\<in> \\<U>; U \\<inter> \\<Union>\\<F> = topspace X \\<inter> U\\<rbrakk>\n                               \\<Longrightarrow> countable (g U) \\<and> (g U) \\<subseteq> \\<F> \\<and> U \\<inter> \\<Union>(g U) = topspace X \\<inter> U\"\n      by metis\n    show ?thesis\n    proof (intro exI conjI)\n      show \"countable (\\<Union>(g ` \\<U>))\"\n        using Int_commute UF g  by (fastforce intro: countable_UN [OF \\<U>])\n      show \"\\<Union>(g ` \\<U>) \\<subseteq> \\<F>\"\n        using g UF by blast\n      show \"\\<Union>\\<U> \\<inter> \\<Union>(\\<Union>(g ` \\<U>)) = topspace X \\<inter> \\<Union>\\<U>\"\n      proof\n        show \"\\<Union>\\<U> \\<inter> \\<Union>(\\<Union>(g ` \\<U>)) \\<subseteq> topspace X \\<inter> \\<Union>\\<U>\"\n          using g UF by blast\n        show \"topspace X \\<inter> \\<Union>\\<U> \\<subseteq> \\<Union>\\<U> \\<inter> \\<Union>(\\<Union>(g ` \\<U>))\"\n        proof clarsimp\n          show \"\\<exists>y\\<in>\\<U>. \\<exists>W\\<in>g y. x \\<in> W\"\n            if \"x \\<in> topspace X\" \"x \\<in> V\" \"V \\<in> \\<U>\" for x V\n          proof -\n            have \"V \\<inter> \\<Union>\\<F> = topspace X \\<inter> V\"\n              using UF \\<open>V \\<in> \\<U>\\<close> by blast\n            with that g [OF \\<open>V \\<in> \\<U>\\<close>]  show ?thesis by blast\n          qed\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis\n      unfolding Lindelof_space_def openin_subtopology_alt Ball_def subset_iff [symmetric]\n      by (simp add: all_subset_image imp_conjL ex_countable_subset_image)\nqed\n\nlemma countable_imp_Lindelof_space:\n  assumes \"countable(topspace X)\"\n  shows \"Lindelof_space X\"\nproof -\n  have \"Lindelof_space (subtopology X (\\<Union>x \\<in> topspace X. {x}))\"\n  proof (rule Lindelof_space_Union)\n    show \"countable ((\\<lambda>x. {x}) ` topspace X)\"\n      using assms by blast\n    show \"Lindelof_space (subtopology X U)\"\n      if \"U \\<in> (\\<lambda>x. {x}) ` topspace X\" for U\n    proof -\n      have \"compactin X U\"\n        using that by force\n      then show ?thesis\n        by (meson compact_imp_Lindelof_space compact_space_subtopology)\n    qed\n  qed\n  then show ?thesis\n    by simp\nqed\nlemma Lindelof_space_subtopology:\n   \"Lindelof_space(subtopology X S) \\<longleftrightarrow>\n        (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> topspace X \\<inter> S \\<subseteq> \\<Union>\\<U>\n            \\<longrightarrow> (\\<exists>V. countable V \\<and> V \\<subseteq> \\<U> \\<and> topspace X \\<inter> S \\<subseteq> \\<Union>V))\"\nproof -\n  have *: \"(S \\<inter> \\<Union>\\<U> = topspace X \\<inter> S) = (topspace X \\<inter> S \\<subseteq> \\<Union>\\<U>)\"\n    if \"\\<And>x. x \\<in> \\<U> \\<Longrightarrow> openin X x\" for \\<U>\n    by (blast dest: openin_subset [OF that])\n  moreover have \"(\\<V> \\<subseteq> \\<U> \\<and> S \\<inter> \\<Union>\\<V> = topspace X \\<inter> S) = (\\<V> \\<subseteq> \\<U> \\<and> topspace X \\<inter> S \\<subseteq> \\<Union>\\<V>)\"\n    if \"\\<forall>x. x \\<in> \\<U> \\<longrightarrow> openin X x\" \"topspace X \\<inter> S \\<subseteq> \\<Union>\\<U>\" \"countable \\<V>\" for \\<U> \\<V>\n    using that * by blast\n  ultimately show ?thesis\n    unfolding Lindelof_space_def openin_subtopology_alt Ball_def\n    apply (simp add: all_subset_image imp_conjL ex_countable_subset_image flip: subset_iff)\n    apply (intro all_cong1 imp_cong ex_cong, auto)\n    done\nqed\n\nlemma Lindelof_space_subtopology_subset:\n   \"S \\<subseteq> topspace X\n        \\<Longrightarrow> (Lindelof_space(subtopology X S) \\<longleftrightarrow>\n             (\\<forall>\\<U>. (\\<forall>U \\<in> \\<U>. openin X U) \\<and> S \\<subseteq> \\<Union>\\<U>\n                 \\<longrightarrow> (\\<exists>V. countable V \\<and> V \\<subseteq> \\<U> \\<and> S \\<subseteq> \\<Union>V)))\"\n  by (metis Lindelof_space_subtopology topspace_subtopology topspace_subtopology_subset)\n\nlemma Lindelof_space_closedin_subtopology:\n  assumes X: \"Lindelof_space X\" and clo: \"closedin X S\"\n  shows \"Lindelof_space (subtopology X S)\"\nproof -\n  have \"S \\<subseteq> topspace X\"\n    by (simp add: clo closedin_subset)\n  then show ?thesis\n  proof (clarsimp simp add: Lindelof_space_subtopology_subset)\n    show \"\\<exists>V. countable V \\<and> V \\<subseteq> \\<F> \\<and> S \\<subseteq> \\<Union>V\"\n      if \"\\<forall>U\\<in>\\<F>. openin X U\" and \"S \\<subseteq> \\<Union>\\<F>\" for \\<F>\n    proof -\n      have \"\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> insert (topspace X - S) \\<F> \\<and> \\<Union>\\<V> = topspace X\"\n      proof (rule Lindelof_spaceD [OF X, of \"insert (topspace X - S) \\<F>\"])\n        show \"openin X U\"\n          if \"U \\<in> insert (topspace X - S) \\<F>\" for U\n          using that \\<open>\\<forall>U\\<in>\\<F>. openin X U\\<close> clo by blast\n        show \"\\<Union>(insert (topspace X - S) \\<F>) = topspace X\"\n          apply auto\n          apply (meson in_mono openin_closedin_eq that(1))\n          using UnionE \\<open>S \\<subseteq> \\<Union>\\<F>\\<close> by auto\n      qed\n      then obtain \\<V> where \"countable \\<V>\" \"\\<V> \\<subseteq> insert (topspace X - S) \\<F>\" \"\\<Union>\\<V> = topspace X\"\n        by metis\n      with \\<open>S \\<subseteq> topspace X\\<close>\n      show ?thesis\n        by (rule_tac x=\"(\\<V> - {topspace X - S})\" in exI) auto\n    qed\n  qed\nqed\n\nlemma Lindelof_space_continuous_map_image:\n  assumes X: \"Lindelof_space X\" and f: \"continuous_map X Y f\" and fim: \"f ` (topspace X) = topspace Y\"\n  shows \"Lindelof_space Y\"\nproof -\n  have \"\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> \\<Union>\\<V> = topspace Y\"\n    if \\<U>: \"\\<And>U. U \\<in> \\<U> \\<Longrightarrow> openin Y U\" and UU: \"\\<Union>\\<U> = topspace Y\" for \\<U>\n  proof -\n    define \\<V> where \"\\<V> \\<equiv> (\\<lambda>U. {x \\<in> topspace X. f x \\<in> U}) ` \\<U>\"\n    have \"\\<And>V. V \\<in> \\<V> \\<Longrightarrow> openin X V\"\n      unfolding \\<V>_def using \\<U> continuous_map f by fastforce\n    moreover have \"\\<Union>\\<V> = topspace X\"\n      unfolding \\<V>_def using UU fim by fastforce\n    ultimately have \"\\<exists>\\<W>. countable \\<W> \\<and> \\<W> \\<subseteq> \\<V> \\<and> \\<Union>\\<W> = topspace X\"\n      using X by (simp add: Lindelof_space_def)\n    then obtain \\<C> where \"countable \\<C>\" \"\\<C> \\<subseteq> \\<U>\" and \\<C>: \"(\\<Union>U\\<in>\\<C>. {x \\<in> topspace X. f x \\<in> U}) = topspace X\"\n      by (metis (no_types, lifting) \\<V>_def countable_subset_image)\n    moreover have \"\\<Union>\\<C> = topspace Y\"\n    proof\n      show \"\\<Union>\\<C> \\<subseteq> topspace Y\"\n        using UU \\<C> \\<open>\\<C> \\<subseteq> \\<U>\\<close> by fastforce\n      have \"y \\<in> \\<Union>\\<C>\" if \"y \\<in> topspace Y\" for y\n      proof -\n        obtain x where \"x \\<in> topspace X\" \"y = f x\"\n          using that fim by (metis \\<open>y \\<in> topspace Y\\<close> imageE)\n        with \\<C> show ?thesis by auto\n      qed\n      then show \"topspace Y \\<subseteq> \\<Union>\\<C>\" by blast\n    qed\n    ultimately show ?thesis\n      by blast\n  qed\n  then show ?thesis\n    unfolding Lindelof_space_def\n    by auto\nqed\n\nlemma Lindelof_space_quotient_map_image:\n   \"\\<lbrakk>quotient_map X Y q; Lindelof_space X\\<rbrakk> \\<Longrightarrow> Lindelof_space Y\"\n  by (meson Lindelof_space_continuous_map_image quotient_imp_continuous_map quotient_imp_surjective_map)\n\nlemma Lindelof_space_retraction_map_image:\n   \"\\<lbrakk>retraction_map X Y r; Lindelof_space X\\<rbrakk> \\<Longrightarrow> Lindelof_space Y\"\n  using Abstract_Topology.retraction_imp_quotient_map Lindelof_space_quotient_map_image by blast\n\nlemma locally_finite_cover_of_Lindelof_space:\n  assumes X: \"Lindelof_space X\" and UU: \"topspace X \\<subseteq> \\<Union>\\<U>\" and fin: \"locally_finite_in X \\<U>\"\n  shows \"countable \\<U>\"\nproof -\n  have UU_eq: \"\\<Union>\\<U> = topspace X\"\n    by (meson UU fin locally_finite_in_def subset_antisym)\n  obtain T where T: \"\\<And>x. x \\<in> topspace X \\<Longrightarrow> openin X (T x) \\<and> x \\<in> T x \\<and> finite {U \\<in> \\<U>. U \\<inter> T x \\<noteq> {}}\"\n    using fin unfolding locally_finite_in_def by metis\n  then obtain I where \"countable I\" \"I \\<subseteq> topspace X\" and I: \"topspace X \\<subseteq> \\<Union>(T ` I)\"\n    using X unfolding Lindelof_space_alt\n    by (drule_tac x=\"image T (topspace X)\" in spec) (auto simp: ex_countable_subset_image)\n  show ?thesis\n  proof (rule countable_subset)\n    have \"\\<And>i. i \\<in> I \\<Longrightarrow> countable {U \\<in> \\<U>. U \\<inter> T i \\<noteq> {}}\"\n      using T\n      by (meson \\<open>I \\<subseteq> topspace X\\<close> in_mono uncountable_infinite)\n    then show \"countable (insert {} (\\<Union>i\\<in>I. {U \\<in> \\<U>. U \\<inter> T i \\<noteq> {}}))\"\n      by (simp add: \\<open>countable I\\<close>)\n  qed (use UU_eq I in auto)\nqed\n\n\nlemma Lindelof_space_proper_map_preimage:\n  assumes f: \"proper_map X Y f\" and Y: \"Lindelof_space Y\"\n  shows \"Lindelof_space X\"\nproof (clarsimp simp: Lindelof_space_alt)\n  show \"\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> topspace X \\<subseteq> \\<Union>\\<V>\"\n    if \\<U>: \"\\<forall>U\\<in>\\<U>. openin X U\" and sub_UU: \"topspace X \\<subseteq> \\<Union>\\<U>\" for \\<U>\n  proof -\n    have \"\\<exists>\\<V>. finite \\<V> \\<and> \\<V> \\<subseteq> \\<U> \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>\\<V>\" if \"y \\<in> topspace Y\" for y\n    proof (rule compactinD)\n      show \"compactin X {x \\<in> topspace X. f x = y}\"\n        using f proper_map_def that by fastforce\n    qed (use sub_UU \\<U> in auto)\n    then obtain \\<V> where \\<V>: \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> finite (\\<V> y) \\<and> \\<V> y \\<subseteq> \\<U> \\<and> {x \\<in> topspace X. f x = y} \\<subseteq> \\<Union>(\\<V> y)\"\n      by meson\n    define \\<W> where \"\\<W> \\<equiv> (\\<lambda>y. topspace Y - image f (topspace X - \\<Union>(\\<V> y))) ` topspace Y\"\n    have \"\\<forall>U \\<in> \\<W>. openin Y U\"\n      using f \\<U> \\<V> unfolding \\<W>_def proper_map_def closed_map_def\n      by (simp add: closedin_diff openin_Union openin_diff subset_iff)\n    moreover have \"topspace Y \\<subseteq> \\<Union>\\<W>\"\n      using \\<V> unfolding \\<W>_def by clarsimp fastforce\n    ultimately have \"\\<exists>\\<V>. countable \\<V> \\<and> \\<V> \\<subseteq> \\<W> \\<and> topspace Y \\<subseteq> \\<Union>\\<V>\"\n      using Y by (simp add: Lindelof_space_alt)\n    then obtain I where \"countable I\" \"I \\<subseteq> topspace Y\"\n      and I: \"topspace Y \\<subseteq> (\\<Union>i\\<in>I. topspace Y - f ` (topspace X - \\<Union>(\\<V> i)))\"\n      unfolding \\<W>_def ex_countable_subset_image by metis\n    show ?thesis\n    proof (intro exI conjI)\n      have \"\\<And>i. i \\<in> I \\<Longrightarrow> countable (\\<V> i)\"\n        by (meson \\<V> \\<open>I \\<subseteq> topspace Y\\<close> in_mono uncountable_infinite)\n      with \\<open>countable I\\<close> show \"countable (\\<Union>(\\<V> ` I))\"\n        by auto\n      show \"\\<Union>(\\<V> ` I) \\<subseteq> \\<U>\"\n        using \\<V> \\<open>I \\<subseteq> topspace Y\\<close> by fastforce\n      show \"topspace X \\<subseteq> \\<Union>(\\<Union>(\\<V> ` I))\"\n      proof\n        show \"x \\<in> \\<Union> (\\<Union> (\\<V> ` I))\" if \"x \\<in> topspace X\" for x\n        proof -\n          have \"f x \\<in> topspace Y\"\n            by (meson f image_subset_iff proper_map_imp_subset_topspace that)\n          then show ?thesis\n            using that I by auto\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma Lindelof_space_perfect_map_image:\n   \"\\<lbrakk>Lindelof_space X; perfect_map X Y f\\<rbrakk> \\<Longrightarrow> Lindelof_space Y\"\n  using Lindelof_space_quotient_map_image perfect_imp_quotient_map by blast\n\nlemma Lindelof_space_perfect_map_image_eq:\n   \"perfect_map X Y f \\<Longrightarrow> Lindelof_space X \\<longleftrightarrow> Lindelof_space Y\"\n  using Lindelof_space_perfect_map_image Lindelof_space_proper_map_preimage perfect_map_def by blast\n\nend\n\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/Lindelof_Spaces.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.763257506934097}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_nat_TSortSorts\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Tree = TNode \"Tree\" \"Nat\" \"Tree\" | TNil\n\nfun le :: \"Nat => Nat => bool\" where\n\"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun ordered :: \"Nat list => bool\" where\n\"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun flatten :: \"Tree => Nat list => Nat list\" where\n\"flatten (TNode q z r) y = flatten q (cons2 z (flatten r y))\"\n| \"flatten (TNil) y = y\"\n\nfun add :: \"Nat => Tree => Tree\" where\n\"add x (TNode q z r) =\n   (if le x z then TNode (add x q) z r else TNode q z (add x r))\"\n| \"add x (TNil) = TNode TNil x TNil\"\n\nfun toTree :: \"Nat list => Tree\" where\n\"toTree (nil2) = TNil\"\n| \"toTree (cons2 y xs) = add y (toTree xs)\"\n\nfun tsort :: \"Nat list => Nat list\" where\n\"tsort x = flatten (toTree x) (nil2)\"\n\ntheorem property0 :\n  \"ordered (tsort xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_nat_TSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8376199572530449, "lm_q1q2_score": 0.7632223077296554}}
{"text": "theory Exercises2 imports Main begin\n\nsubsection \"primitive recursion and induction\"\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\ntext {* \n  define a function that converts a tree into \n  a list in post order by primitive recursion \n*}\n\nconsts \n  postorder :: \"'a tree \\<Rightarrow> 'a list\"\n\n\n\ntext {* \n  define another function that does the same, \n  but with tail recursion (recursive call at \n  top level only) \n*} \n\nconsts\n  postorder_it :: \"['a tree, 'a list] \\<Rightarrow> 'a list\"\n\n\n\nlemma \"postorder_it t [] = postorder t\"\n  oops\n\n\nsubsection \"inductively defined sets\"\n\nconsts Ev :: \"nat set\"\ninductive Ev\nintros\nZeroI: \"0 \\<in> Ev\"\nAdd2I: \"n \\<in> Ev \\<Longrightarrow> Suc(Suc n) \\<in> Ev\"\n\nlemma \"\\<lbrakk> n \\<in> Ev; m \\<in> Ev \\<rbrakk> \\<Longrightarrow> m+n \\<in> Ev\"\noops\n\n\ntext {* use method arith to solve linear arithmetic problems *}\n\nlemma \"n \\<in> Ev \\<Longrightarrow> \\<exists>k. n = 2*k\"\noops\n\n\nlemma \"n = 2*k \\<longrightarrow> n \\<in> Ev\" \noops\n\n\ntext {* Solve in Isar: *}\n\nlemma \"A \\<and> B \\<longrightarrow> B \\<and> A\"\noops\n\nlemma \"A \\<and> (B \\<or> C) \\<longrightarrow> (A \\<and> B) \\<or> (A \\<and> C)\"\noops  \n\n\nend", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/IJCAR04/Exercises2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308091776496, "lm_q2_score": 0.8175744850834649, "lm_q1q2_score": 0.7631492131744588}}
{"text": "(*  Title:      HOL/Algebra/Ideal_Product.thy\n    Author:     Paulo Emílio de Vilhena\n*)\n\ntheory Ideal_Product\n  imports Ideal\nbegin\n\nsection \\<open>Product of Ideals\\<close>\n\ntext \\<open>In this section, we study the structure of the set of ideals of a given ring.\\<close>\n\ninductive_set\n  ideal_prod :: \"[ ('a, 'b) ring_scheme, 'a set, 'a set ] \\<Rightarrow> 'a set\" (infixl \"\\<cdot>\\<index>\" 80)\n  for R and I and J (* both I and J are supposed ideals *) where\n    prod: \"\\<lbrakk> i \\<in> I; j \\<in> J \\<rbrakk> \\<Longrightarrow> i \\<otimes>\\<^bsub>R\\<^esub> j \\<in> ideal_prod R I J\"\n  |  sum: \"\\<lbrakk> s1 \\<in> ideal_prod R I J; s2 \\<in> ideal_prod R I J \\<rbrakk> \\<Longrightarrow> s1 \\<oplus>\\<^bsub>R\\<^esub> s2 \\<in> ideal_prod R I J\"\n\ndefinition ideals_set :: \"('a, 'b) ring_scheme \\<Rightarrow> ('a set) ring\"\n  where \"ideals_set R = \\<lparr> carrier = { I. ideal I R },\n                             mult = ideal_prod R,\n                              one = carrier R,\n                             zero = { \\<zero>\\<^bsub>R\\<^esub> },\n                              add = set_add R \\<rparr>\"\n\n\nsubsection \\<open>Basic Properties\\<close>\n\nlemma (in ring) ideal_prod_in_carrier:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J \\<subseteq> carrier R\"\nproof\n  fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> carrier R\"\n    by (induct s rule: ideal_prod.induct) (auto, meson assms ideal.I_l_closed ideal.Icarr) \nqed\n\nlemma (in ring) ideal_prod_inter:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J \\<subseteq> I \\<inter> J\"\nproof\n  fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> I \\<inter> J\"\n    apply (induct s rule: ideal_prod.induct)\n    apply (auto, (meson assms ideal.I_r_closed ideal.I_l_closed ideal.Icarr)+)\n    apply (simp_all add: additive_subgroup.a_closed assms ideal.axioms(1))\n    done\nqed\n\nlemma (in ring) ideal_prod_is_ideal:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"ideal (I \\<cdot> J) R\"\nproof (rule idealI)\n  show \"ring R\" using is_ring .\nnext\n  show \"subgroup (I \\<cdot> J) (add_monoid R)\"\n    unfolding subgroup_def\n  proof (auto)\n    show \"\\<zero> \\<in> I \\<cdot> J\" using ideal_prod.prod[of \\<zero> I \\<zero> J R]\n      by (simp add: additive_subgroup.zero_closed assms ideal.axioms(1))\n  next\n    fix s1 s2 assume s1: \"s1 \\<in> I \\<cdot> J\" and s2: \"s2 \\<in> I \\<cdot> J\"\n    have IJcarr: \"\\<And>a. a \\<in> I \\<cdot> J \\<Longrightarrow> a \\<in> carrier R\"\n      by (meson assms subsetD ideal_prod_in_carrier)\n    show \"s1 \\<in> carrier R\" using ideal_prod_in_carrier[OF assms] s1 by blast\n    show \"s1 \\<oplus> s2 \\<in> I \\<cdot> J\" by (simp add: ideal_prod.sum[OF s1 s2])\n    show \"inv\\<^bsub>add_monoid R\\<^esub> s1 \\<in> I \\<cdot> J\" using s1\n    proof (induct s1 rule: ideal_prod.induct)\n      case (prod i j)\n      hence \"inv\\<^bsub>add_monoid R\\<^esub> (i \\<otimes> j) = (inv\\<^bsub>add_monoid R\\<^esub> i) \\<otimes> j\"\n        by (metis a_inv_def assms(1) assms(2) ideal.Icarr l_minus)\n      thus ?case using ideal_prod.prod[of \"inv\\<^bsub>add_monoid R\\<^esub> i\" I j J R] assms\n        by (simp add: additive_subgroup.a_subgroup ideal.axioms(1) prod.hyps subgroup.m_inv_closed)\n    next\n      case (sum s1 s2) thus ?case\n        by (metis (no_types) IJcarr a_inv_def add.inv_mult_group ideal_prod.sum sum.hyps)\n    qed\n  qed\nnext\n  fix s x assume s: \"s \\<in> I \\<cdot> J\" and x: \"x \\<in> carrier R\"\n  show \"x \\<otimes> s \\<in> I \\<cdot> J\" using s\n  proof (induct s rule: ideal_prod.induct)\n    case (prod i j) thus ?case using ideal_prod.prod[of \"x \\<otimes> i\" I j J R] assms\n      by (simp add: x ideal.I_l_closed ideal.Icarr m_assoc)\n  next\n    case (sum s1 s2) thus ?case\n    proof -\n      have IJ: \"I \\<cdot> J \\<subseteq> carrier R\"\n        by (metis (no_types) assms(1) assms(2) ideal.axioms(2) ring.ideal_prod_in_carrier)\n      then have \"s2 \\<in> carrier R\"\n        using sum.hyps(3) by blast\n      moreover have \"s1 \\<in> carrier R\"\n        using IJ sum.hyps(1) by blast\n      ultimately show ?thesis\n        by (simp add: ideal_prod.sum r_distr sum.hyps x)\n    qed\n  qed\n  show \"s \\<otimes> x \\<in> I \\<cdot> J\" using s\n  proof (induct s rule: ideal_prod.induct)\n    case (prod i j) thus ?case using ideal_prod.prod[of i I \"j \\<otimes> x\" J R] assms x\n      by (simp add: x ideal.I_r_closed ideal.Icarr m_assoc)\n  next\n    case (sum s1 s2) thus ?case \n    proof -\n      have \"s1 \\<in> carrier R\" \"s2 \\<in> carrier R\"\n        by (meson assms subsetD ideal_prod_in_carrier sum.hyps)+\n      then show ?thesis\n        by (metis ideal_prod.sum l_distr sum.hyps(2) sum.hyps(4) x)\n    qed\n  qed\nqed\n\nlemma (in ring) ideal_prod_eq_genideal:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J = Idl (I <#> J)\"\nproof\n  have \"I <#> J \\<subseteq> I \\<cdot> J\"\n  proof\n    fix s assume \"s \\<in> I <#> J\"\n    then obtain i j where \"i \\<in> I\" \"j \\<in> J\" \"s = i \\<otimes> j\"\n      unfolding set_mult_def by blast\n    thus \"s \\<in> I \\<cdot> J\" using ideal_prod.prod by simp\n  qed\n  thus \"Idl (I <#> J) \\<subseteq> I \\<cdot> J\"\n    unfolding genideal_def using ideal_prod_is_ideal[OF assms] by blast\nnext\n  show \"I \\<cdot> J \\<subseteq> Idl (I <#> J)\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> Idl (I <#> J)\"\n    proof (induct s rule: ideal_prod.induct)\n      case (prod i j) hence \"i \\<otimes> j \\<in> I <#> J\" unfolding set_mult_def by blast\n      thus ?case unfolding genideal_def by blast \n    next\n      case (sum s1 s2) thus ?case\n        by (simp add: additive_subgroup.a_closed additive_subgroup.a_subset\n            assms genideal_ideal ideal.axioms(1) set_mult_closed)\n    qed\n  qed\nqed\n\n\nlemma (in ring) ideal_prod_simp:\n  assumes \"ideal I R\" \"ideal J R\" (* the second assumption could be suppressed *)\n  shows \"I = I <+> (I \\<cdot> J)\"\nproof\n  show \"I \\<subseteq> I <+> I \\<cdot> J\"\n  proof\n    fix i assume \"i \\<in> I\" hence \"i \\<oplus> \\<zero> \\<in> I <+> I \\<cdot> J\"\n      using set_add_def'[of R I \"I \\<cdot> J\"] ideal_prod_is_ideal[OF assms]\n            additive_subgroup.zero_closed[OF ideal.axioms(1), of \"I \\<cdot> J\" R] by auto\n    thus \"i \\<in> I <+> I \\<cdot> J\"\n      using \\<open>i \\<in> I\\<close> assms(1) ideal.Icarr by fastforce \n  qed\nnext\n  show \"I <+> I \\<cdot> J \\<subseteq> I\"\n  proof\n    fix s assume \"s \\<in> I <+> I \\<cdot> J\"\n    then obtain i ij where \"i \\<in> I\" \"ij \\<in> I \\<cdot> J\" \"s = i \\<oplus> ij\"\n      using set_add_def'[of R I \"I \\<cdot> J\"] by auto\n    thus \"s \\<in> I\"\n      using ideal_prod_inter[OF assms]\n      by (meson additive_subgroup.a_closed assms(1) ideal.axioms(1) inf_sup_ord(1) subsetCE) \n  qed\nqed\n\nlemma (in ring) ideal_prod_one:\n  assumes \"ideal I R\"\n  shows \"I \\<cdot> (carrier R) = I\"\nproof\n  show \"I \\<cdot> (carrier R) \\<subseteq> I\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> (carrier R)\" thus \"s \\<in> I\"\n      by (induct s rule: ideal_prod.induct)\n         (simp_all add: assms ideal.I_r_closed additive_subgroup.a_closed ideal.axioms(1))\n  qed\nnext\n  show \"I \\<subseteq> I \\<cdot> (carrier R)\"\n  proof\n    fix i assume \"i \\<in> I\" thus \"i \\<in>  I \\<cdot> (carrier R)\"\n      by (metis assms ideal.Icarr ideal_prod.simps one_closed r_one)\n  qed\nqed\n\nlemma (in ring) ideal_prod_zero:\n  assumes \"ideal I R\"\n  shows \"I \\<cdot> { \\<zero> } = { \\<zero> }\"\nproof\n  show \"I \\<cdot> { \\<zero> } \\<subseteq> { \\<zero> }\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> {\\<zero>}\" thus \"s \\<in> { \\<zero> }\"\n      using assms ideal.Icarr by (induct s rule: ideal_prod.induct) (fastforce, simp)\n  qed\nnext\n  show \"{ \\<zero> } \\<subseteq> I \\<cdot> { \\<zero> }\"\n    by (simp add: additive_subgroup.zero_closed assms\n                  ideal.axioms(1) ideal_prod_is_ideal zeroideal)\nqed\n\nlemma (in ring) ideal_prod_assoc:\n  assumes \"ideal I R\" \"ideal J R\" \"ideal K R\"\n  shows \"(I \\<cdot> J) \\<cdot> K = I \\<cdot> (J \\<cdot> K)\"\nproof\n  show \"(I \\<cdot> J) \\<cdot> K \\<subseteq> I \\<cdot> (J \\<cdot> K)\"\n  proof\n    fix s assume \"s \\<in> (I \\<cdot> J) \\<cdot> K\" thus \"s \\<in> I \\<cdot> (J \\<cdot> K)\"\n    proof (induct s rule: ideal_prod.induct)\n      case (sum s1 s2) thus ?case\n        by (simp add: ideal_prod.sum)\n    next\n      case (prod i k) thus ?case\n      proof (induct i rule: ideal_prod.induct)\n        case (prod i j) thus ?case\n          using ideal_prod.prod[OF prod(1) ideal_prod.prod[OF prod(2-3),of R], of R]\n          by (metis assms ideal.Icarr m_assoc) \n      next\n        case (sum s1 s2) thus ?case\n        proof -\n          have \"s1 \\<in> carrier R\" \"s2 \\<in> carrier R\"\n            by (meson assms subsetD ideal.axioms(2) ring.ideal_prod_in_carrier sum.hyps)+\n          moreover have \"k \\<in> carrier R\"\n            by (meson additive_subgroup.a_Hcarr assms(3) ideal.axioms(1) sum.prems)\n          ultimately show ?thesis\n            by (metis ideal_prod.sum l_distr sum.hyps(2) sum.hyps(4) sum.prems)\n        qed\n      qed\n    qed\n  qed\nnext\n  show \"I \\<cdot> (J \\<cdot> K) \\<subseteq> (I \\<cdot> J) \\<cdot> K\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> (J \\<cdot> K)\" thus \"s \\<in> (I \\<cdot> J) \\<cdot> K\"\n    proof (induct s rule: ideal_prod.induct)\n      case (sum s1 s2) thus ?case by (simp add: ideal_prod.sum)\n    next\n      case (prod i j) show ?case using prod(2) prod(1)\n      proof (induct j rule: ideal_prod.induct)\n        case (prod j k) thus ?case\n          using ideal_prod.prod[OF ideal_prod.prod[OF prod(3) prod(1), of R] prod (2), of R]\n          by (metis assms ideal.Icarr m_assoc)\n      next\n        case (sum s1 s2) thus ?case\n        proof -\n          have \"\\<And>a A B. \\<lbrakk>a \\<in> B \\<cdot> A; ideal A R; ideal B R\\<rbrakk> \\<Longrightarrow> a \\<in> carrier R\"\n            by (meson subsetD ideal_prod_in_carrier)\n          moreover have \"i \\<in> carrier R\"\n            by (meson additive_subgroup.a_Hcarr assms(1) ideal.axioms(1) sum.prems)\n          ultimately show ?thesis\n            by (metis (no_types) assms(2) assms(3) ideal_prod.sum r_distr sum)\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma (in ring) ideal_prod_r_distr:\n  assumes \"ideal I R\" \"ideal J R\" \"ideal K R\"\n  shows \"I \\<cdot> (J <+> K) = (I \\<cdot> J) <+>  (I \\<cdot> K)\"\nproof\n  show \"I \\<cdot> (J <+> K) \\<subseteq> I \\<cdot> J <+> I \\<cdot> K\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> (J <+> K)\" thus \"s \\<in> I \\<cdot> J <+> I \\<cdot> K\"\n    proof(induct s rule: ideal_prod.induct)\n      case (prod i jk)\n      then obtain j k where j: \"j \\<in> J\" and k: \"k \\<in> K\" and jk: \"jk = j \\<oplus> k\"\n        using set_add_def'[of R J K] by auto\n      hence \"i \\<otimes> j \\<oplus> i \\<otimes> k \\<in> I \\<cdot> J <+> I \\<cdot> K\"\n        using ideal_prod.prod[OF prod(1) j,of R]\n              ideal_prod.prod[OF prod(1) k,of R]\n              set_add_def'[of R \"I \\<cdot> J\" \"I \\<cdot> K\"] by auto\n      thus ?case\n        using assms ideal.Icarr r_distr jk j k prod(1) by metis \n    next\n      case (sum s1 s2) thus ?case\n        by (simp add: add_ideals additive_subgroup.a_closed assms ideal.axioms(1)\n                      local.ring_axioms ring.ideal_prod_is_ideal) \n    qed\n  qed\nnext\n  { fix s J K assume A: \"ideal J R\" \"ideal K R\" \"s \\<in> I \\<cdot> J\"\n    have \"s \\<in> I \\<cdot> (J <+> K) \\<and> s \\<in> I \\<cdot> (K <+> J)\"\n    proof -\n      from \\<open>s \\<in> I \\<cdot> J\\<close> have \"s \\<in> I \\<cdot> (J <+> K)\"\n      proof (induct s rule: ideal_prod.induct)\n        case (prod i j)\n        hence \"(j \\<oplus> \\<zero>) \\<in> J <+> K\"\n          using set_add_def'[of R J K]\n                additive_subgroup.zero_closed[OF ideal.axioms(1), of K R] A(2) by auto\n        thus ?case\n          by (metis A(1) additive_subgroup.a_Hcarr ideal.axioms(1) ideal_prod.prod prod r_zero)  \n      next\n        case (sum s1 s2) thus ?case\n          by (simp add: ideal_prod.sum) \n      qed\n      thus ?thesis\n        by (metis A(1) A(2) ideal_def ring.union_genideal sup_commute) \n    qed } note aux_lemma = this\n\n  show \"I \\<cdot> J <+> I \\<cdot> K \\<subseteq> I \\<cdot> (J <+> K)\"\n  proof\n    fix s assume \"s \\<in> I \\<cdot> J <+> I \\<cdot> K\"\n    then obtain s1 s2 where s1: \"s1 \\<in> I \\<cdot> J\" and s2: \"s2 \\<in> I \\<cdot> K\" and  s: \"s = s1 \\<oplus> s2\"\n      using set_add_def'[of R \"I \\<cdot> J\" \"I \\<cdot> K\"] by auto\n    thus \"s \\<in> I \\<cdot> (J <+> K)\"\n      using aux_lemma[OF assms(2) assms(3) s1]\n            aux_lemma[OF assms(3) assms(2) s2] by (simp add: ideal_prod.sum)\n  qed\nqed\n\nlemma (in cring) ideal_prod_commute:\n  assumes \"ideal I R\" \"ideal J R\"\n  shows \"I \\<cdot> J = J \\<cdot> I\"\nproof -\n  { fix I J assume A: \"ideal I R\" \"ideal J R\"\n    have \"I \\<cdot> J \\<subseteq> J \\<cdot> I\"\n    proof\n      fix s assume \"s \\<in> I \\<cdot> J\" thus \"s \\<in> J \\<cdot> I\"\n      proof (induct s rule: ideal_prod.induct)\n        case (prod i j) thus ?case\n          using m_comm[OF ideal.Icarr[OF A(1) prod(1)] ideal.Icarr[OF A(2) prod(2)]]\n          by (simp add: ideal_prod.prod)\n      next\n        case (sum s1 s2) thus ?case by (simp add: ideal_prod.sum) \n      qed\n    qed }\n  thus ?thesis using assms by blast \nqed\n\ntext \\<open>The following result would also be true for locale ring\\<close>\nlemma (in cring) ideal_prod_distr:\n  assumes \"ideal I R\" \"ideal J R\" \"ideal K R\"\n  shows \"I \\<cdot> (J <+> K) = (I \\<cdot> J) <+>  (I \\<cdot> K)\"\n    and \"(J <+> K) \\<cdot> I = (J \\<cdot> I) <+>  (K \\<cdot> I)\"\n  by (simp_all add: assms ideal_prod_commute local.ring_axioms\n                    ring.add_ideals ring.ideal_prod_r_distr)\n\nlemma (in cring) ideal_prod_eq_inter:\n  assumes \"ideal I R\" \"ideal J R\"\n    and \"I <+> J = carrier R\"\n  shows \"I \\<cdot> J = I \\<inter> J\"\nproof\n  show \"I \\<cdot> J \\<subseteq> I \\<inter> J\"\n    using assms ideal_prod_inter by auto\nnext\n  show \"I \\<inter> J \\<subseteq> I \\<cdot> J\"\n  proof\n    have \"\\<one> \\<in> I <+> J\" using assms(3) one_closed by simp \n    then obtain i j where ij: \"i \\<in> I\" \"j \\<in> J\" \"\\<one> = i \\<oplus> j\"\n      using set_add_def'[of R I J] by auto\n\n    fix s assume s: \"s \\<in> I \\<inter> J\"\n    hence \"(i \\<otimes> s \\<in> I \\<cdot> J) \\<and> (s \\<otimes> j \\<in> I \\<cdot> J)\"\n      using ij(1-2) by (simp add: ideal_prod.prod)\n    moreover have \"s = (i \\<otimes> s) \\<oplus> (s \\<otimes> j)\"\n      using ideal.Icarr[OF assms(1) ij(1)]\n            ideal.Icarr[OF assms(2) ij(2)]\n            ideal.Icarr[OF assms(1), of s]\n      by (metis ij(3) s m_comm[of s i] Int_iff r_distr r_one)\n    ultimately show \"s \\<in>  I \\<cdot> J\"\n      using ideal_prod.sum by fastforce\n  qed\nqed\n\n\nsubsection \\<open>Structure of the Set of Ideals\\<close>\n\ntext \\<open>We focus on commutative rings for convenience.\\<close>\n\nlemma (in cring) ideals_set_is_semiring: \"semiring (ideals_set R)\"\nproof -\n  have \"abelian_monoid (ideals_set R)\"\n    apply (rule abelian_monoidI) unfolding ideals_set_def\n    apply (simp_all add: add_ideals zeroideal)\n    apply (simp add: add.set_mult_assoc additive_subgroup.a_subset ideal.axioms(1) set_add_defs(1))\n    apply (metis Un_absorb1 additive_subgroup.a_subset additive_subgroup.zero_closed\n        cgenideal_minimal cgenideal_self empty_iff genideal_minimal ideal.axioms(1)\n        local.ring_axioms order_refl ring.genideal_self subset_antisym subset_singletonD\n        union_genideal zero_closed zeroideal)\n    by (metis sup_commute union_genideal)\n\n  moreover have \"monoid (ideals_set R)\"\n    apply (rule monoidI) unfolding ideals_set_def\n    apply (simp_all add: ideal_prod_is_ideal oneideal\n                         ideal_prod_commute ideal_prod_one)\n    by (metis ideal_prod_assoc ideal_prod_commute)\n\n  ultimately show ?thesis\n    unfolding semiring_def semiring_axioms_def ideals_set_def\n    by (simp_all add: ideal_prod_distr ideal_prod_commute ideal_prod_zero zeroideal) \nqed\n\nlemma (in cring) ideals_set_is_comm_monoid: \"comm_monoid (ideals_set R)\"\nproof -\n  have \"monoid (ideals_set R)\"\n    apply (rule monoidI) unfolding ideals_set_def\n    apply (simp_all add: ideal_prod_is_ideal oneideal\n                         ideal_prod_commute ideal_prod_one)\n    by (metis ideal_prod_assoc ideal_prod_commute)\n  thus ?thesis\n    unfolding comm_monoid_def comm_monoid_axioms_def\n    by (simp add: ideal_prod_commute ideals_set_def)\nqed\n\nlemma (in cring) ideal_prod_eq_Inter_aux:\n  assumes \"I: {..(Suc n)} \\<rightarrow> { J. ideal J R }\" \n    and \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n \\<rbrakk> \\<Longrightarrow>\n                 i \\<noteq> j \\<Longrightarrow> (I i) <+> (I j) = carrier R\"\n  shows \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. I k) <+> (I (Suc n)) = carrier R\" using assms\nproof (induct n arbitrary: I)\n  case 0\n  hence \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..0}. I k) <+> I (Suc 0) = (I 0) <+> (I (Suc 0))\"\n    using comm_monoid.finprod_0[OF ideals_set_is_comm_monoid, of I]\n    by (simp add: atMost_Suc ideals_set_def)\n  also have \" ... = carrier R\"\n    using 0(2)[of 0 \"Suc 0\"] by simp\n  finally show ?case .\nnext\n  interpret ISet: comm_monoid \"ideals_set R\"\n    by (simp add: ideals_set_is_comm_monoid)\n\n  case (Suc n)\n  let ?I' = \"\\<lambda>i. I (Suc i)\"\n  have \"?I': {..(Suc n)} \\<rightarrow> { J. ideal J R }\"\n    using Suc.prems(1) by auto\n  moreover have \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n \\<rbrakk> \\<Longrightarrow>\n                         i \\<noteq> j \\<Longrightarrow> (?I' i) <+> (?I' j) = carrier R\"\n    by (simp add: Suc.prems(2))\n  ultimately have \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. ?I' k) <+> (?I' (Suc n)) = carrier R\"\n    using Suc.hyps by metis\n\n  moreover have I_carr: \"I: {..Suc (Suc n)} \\<rightarrow> carrier (ideals_set R)\"\n    unfolding ideals_set_def using Suc by simp\n  hence I'_carr: \"I \\<in> Suc ` {..n} \\<rightarrow> carrier (ideals_set R)\" by auto\n  ultimately have \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {(Suc 0)..Suc n}. I k) <+> (I (Suc (Suc n))) = carrier R\"\n    using ISet.finprod_reindex[of I \"\\<lambda>i. Suc i\" \"{..n}\"] by (simp add: atMost_atLeast0) \n\n  hence \"(carrier R) \\<cdot> (I 0) = ((\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) <+> I (Suc (Suc n))) \\<cdot> (I 0)\"\n    by auto\n  moreover have fprod_cl1: \"ideal (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) R\"\n    by (metis I'_carr ISet.finprod_closed One_nat_def ideals_set_def image_Suc_atMost\n        mem_Collect_eq partial_object.select_convs(1))\n  ultimately\n  have \"I 0 = (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) \\<cdot> (I 0) <+> I (Suc (Suc n)) \\<cdot> (I 0)\"\n    by (metis PiE Suc.prems(1) atLeast0_atMost_Suc atLeast0_atMost_Suc_eq_insert_0\n        atMost_atLeast0 ideal_prod_commute ideal_prod_distr(2) ideal_prod_one insertI1\n        mem_Collect_eq oneideal)\n  also have \" ... = (I 0) \\<cdot> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) <+> I (Suc (Suc n)) \\<cdot> (I 0)\"\n    using fprod_cl1 ideal_prod_commute Suc.prems(1)\n    by (simp add: atLeast0_atMost_Suc_eq_insert_0 atMost_atLeast0) \n  also have \" ... = (I 0) \\<otimes>\\<^bsub>(ideals_set R)\\<^esub> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {Suc 0..Suc n}. I k) <+>\n                     I (Suc (Suc n)) \\<cdot> (I 0)\"\n    by (simp add: ideals_set_def)\n  finally have I0: \"I 0 = (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) <+> I (Suc (Suc n)) \\<cdot> (I 0)\"\n    using ISet.finprod_insert[of \"{Suc 0..Suc n}\" 0 I]\n          I_carr I'_carr atMost_atLeast0 ISet.finprod_0' atMost_Suc by auto\n\n  have I_SucSuc_I0: \"ideal (I (Suc (Suc n))) R \\<and> ideal (I 0) R\"\n    using Suc.prems(1) by auto\n  have fprod_cl2: \"ideal (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) R\"\n    by (metis (no_types) ISet.finprod_closed I_carr Pi_split_insert_domain atMost_Suc ideals_set_def mem_Collect_eq partial_object.select_convs(1))\n  have \"carrier R = I (Suc (Suc n)) <+> I 0\"\n    by (simp add: Suc.prems(2))\n  also have \" ... = I (Suc (Suc n)) <+>\n                    ((\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) <+> I (Suc (Suc n)) \\<cdot> (I 0))\"\n    using I0 by auto\n  also have \" ... = I (Suc (Suc n)) <+>\n                    (I (Suc (Suc n)) \\<cdot> (I 0) <+> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k))\"\n    using fprod_cl2 I_SucSuc_I0 by (metis Un_commute ideal_prod_is_ideal union_genideal)\n  also have \" ... = (I (Suc (Suc n)) <+> I (Suc (Suc n)) \\<cdot> (I 0)) <+>\n                    (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k)\"\n    using fprod_cl2 I_SucSuc_I0 by (metis add.set_mult_assoc ideal_def ideal_prod_in_carrier\n                                          oneideal ring.ideal_prod_one set_add_defs(1)) \n  also have \" ... = I (Suc (Suc n)) <+> (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k)\"\n    using ideal_prod_simp[of \"I (Suc (Suc n))\" \"I 0\"] I_SucSuc_I0 by simp \n  also have \" ... = (\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) <+> I (Suc (Suc n))\"\n    using fprod_cl2 I_SucSuc_I0 by (metis Un_commute union_genideal)\n  finally show ?case by simp\nqed\n\ntheorem (in cring) ideal_prod_eq_Inter:\n  assumes \"I: {..n :: nat} \\<rightarrow> { J. ideal J R }\" \n    and \"\\<And>i j. \\<lbrakk> i \\<in> {..n}; j \\<in> {..n} \\<rbrakk> \\<Longrightarrow> i \\<noteq> j \\<Longrightarrow> (I i) <+> (I j) = carrier R\"\n  shows \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. I k) = (\\<Inter> k \\<in> {..n}. I k)\" using assms\nproof (induct n)\n  case 0 thus ?case\n    using comm_monoid.finprod_0[OF ideals_set_is_comm_monoid] by (simp add: ideals_set_def) \nnext\n  interpret ISet: comm_monoid \"ideals_set R\"\n    by (simp add: ideals_set_is_comm_monoid)\n\n  case (Suc n)\n  hence IH: \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..n}. I k) = (\\<Inter> k \\<in> {..n}. I k)\"\n    by (simp add: atMost_Suc)\n  hence \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) = I (Suc n) \\<otimes>\\<^bsub>(ideals_set R)\\<^esub> (\\<Inter> k \\<in> {..n}. I k)\"\n    using ISet.finprod_insert[of \"{Suc 0..Suc n}\" 0 I] atMost_Suc_eq_insert_0[of n]\n    by (metis ISet.finprod_Suc Suc.prems(1) ideals_set_def partial_object.select_convs(1))\n  hence \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) = I (Suc n) \\<cdot> (\\<Inter> k \\<in> {..n}. I k)\"\n    by (simp add: ideals_set_def)\n  moreover have \"(\\<Inter> k \\<in> {..n}. I k) <+> I (Suc n) = carrier R\"\n    using ideal_prod_eq_Inter_aux[of I n] by (simp add: Suc.prems IH)\n  moreover have \"ideal (\\<Inter> k \\<in> {..n}. I k) R\"\n    using ring.i_Intersect[of R \"I ` {..n}\"]\n    by (metis IH ISet.finprod_closed Pi_split_insert_domain Suc.prems(1) atMost_Suc\n              ideals_set_def mem_Collect_eq partial_object.select_convs(1))\n  ultimately\n  have \"(\\<Otimes>\\<^bsub>(ideals_set R)\\<^esub> k \\<in> {..Suc n}. I k) = (\\<Inter> k \\<in> {..n}. I k) \\<inter> I (Suc n)\"\n    using ideal_prod_eq_inter[of \"\\<Inter> k \\<in> {..n}. I k\" \"I (Suc n)\"]\n          ideal_prod_commute[of \"\\<Inter> k \\<in> {..n}. I k\" \"I (Suc n)\"]\n    by (metis PiE Suc.prems(1) atMost_iff mem_Collect_eq order_refl)\n  thus ?case by (simp add: Int_commute atMost_Suc) \nqed\n\ncorollary (in cring) inter_plus_ideal_eq_carrier:\n  assumes \"\\<And>i. i \\<le> Suc n \\<Longrightarrow> ideal (I i) R\" \n      and \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n; i \\<noteq> j \\<rbrakk> \\<Longrightarrow> I i <+> I j = carrier R\"\n  shows \"(\\<Inter> i \\<le> n. I i) <+> (I (Suc n)) = carrier R\"\n  using ideal_prod_eq_Inter[of I n] ideal_prod_eq_Inter_aux[of I n] by (auto simp add: assms)\n\ncorollary (in cring) inter_plus_ideal_eq_carrier_arbitrary:\n  assumes \"\\<And>i. i \\<le> Suc n \\<Longrightarrow> ideal (I i) R\" \n      and \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n; i \\<noteq> j \\<rbrakk> \\<Longrightarrow> I i <+> I j = carrier R\"\n      and \"j \\<le> Suc n\"\n  shows \"(\\<Inter> i \\<in> ({..(Suc n)} - { j }). I i) <+> (I j) = carrier R\"\nproof -\n  define I' where \"I' = (\\<lambda>i. if i = Suc n then (I j) else\n                             if i = j     then (I (Suc n))\n                                          else (I i))\"\n  have \"\\<And>i. i \\<le> Suc n \\<Longrightarrow> ideal (I' i) R\"\n    using I'_def assms(1) assms(3) by auto\n  moreover have \"\\<And>i j. \\<lbrakk> i \\<le> Suc n; j \\<le> Suc n; i \\<noteq> j \\<rbrakk> \\<Longrightarrow> I' i <+> I' j = carrier R\"\n    using I'_def assms(2-3) by force\n  ultimately have \"(\\<Inter> i \\<le> n. I' i) <+> (I' (Suc n)) = carrier R\"\n    using inter_plus_ideal_eq_carrier by simp\n\n  moreover have \"I' ` {..n} = I ` ({..(Suc n)} - { j })\"\n  proof\n    show \"I' ` {..n} \\<subseteq> I ` ({..Suc n} - {j})\"\n    proof\n      fix x assume \"x \\<in> I' ` {..n}\"\n      then obtain i where i: \"i \\<in> {..n}\" \"I' i = x\" by blast\n      thus \"x \\<in> I ` ({..Suc n} - {j})\"\n      proof (cases)\n        assume \"i = j\" thus ?thesis using i I'_def by auto\n      next\n        assume \"i \\<noteq> j\" thus ?thesis using I'_def i insert_iff by auto\n      qed\n    qed\n  next\n    show \"I ` ({..Suc n} - {j}) \\<subseteq> I' ` {..n}\"\n    proof\n      fix x assume \"x \\<in> I ` ({..Suc n} - {j})\"\n      then obtain i where i: \"i \\<in> {..Suc n}\" \"i \\<noteq> j\" \"I i = x\" by blast\n      thus \"x \\<in> I' ` {..n}\"\n      proof (cases)\n        assume \"i = Suc n\" thus ?thesis using I'_def assms(3) i(2-3) by auto\n      next\n        assume \"i \\<noteq> Suc n\" thus ?thesis using I'_def i by auto\n      qed\n    qed\n  qed\n  ultimately show ?thesis using I'_def by metis \nqed\n\n\nsubsection \\<open>Another Characterization of Prime Ideals\\<close>\n\ntext \\<open>With product of ideals being defined, we can give another definition of a prime ideal\\<close>\n\nlemma (in ring) primeideal_divides_ideal_prod:\n  assumes \"primeideal P R\" \"ideal I R\" \"ideal J R\"\n      and \"I \\<cdot> J \\<subseteq> P\"\n    shows \"I \\<subseteq> P \\<or> J \\<subseteq> P\"\nproof (cases)\n  assume \"\\<exists> i \\<in> I. i \\<notin> P\"\n  then obtain i where i: \"i \\<in> I\" \"i \\<notin> P\" by blast\n  have \"J \\<subseteq> P\"\n  proof\n    fix j assume j: \"j \\<in> J\"\n    hence \"i \\<otimes> j \\<in> P\"\n      using ideal_prod.prod[OF i(1) j, of R] assms(4) by auto\n    thus \"j \\<in> P\"\n      using primeideal.I_prime[OF assms(1), of i j] i j\n      by (meson assms(2-3) ideal.Icarr) \n  qed\n  thus ?thesis by blast\nnext\n  assume \"\\<not> (\\<exists> i \\<in> I. i \\<notin> P)\" thus ?thesis by blast\nqed\n\nlemma (in cring) divides_ideal_prod_imp_primeideal:\n  assumes \"ideal P R\"\n    and \"P \\<noteq> carrier R\"\n    and \"\\<And>I J. \\<lbrakk> ideal I R; ideal J R; I \\<cdot> J \\<subseteq> P \\<rbrakk> \\<Longrightarrow> I \\<subseteq> P \\<or> J \\<subseteq> P\"\n  shows \"primeideal P R\"\nproof -\n  have \"\\<And>a b. \\<lbrakk> a \\<in> carrier R; b \\<in> carrier R; a \\<otimes> b \\<in> P \\<rbrakk> \\<Longrightarrow> a \\<in> P \\<or> b \\<in> P\"\n  proof -\n    fix a b assume A: \"a \\<in> carrier R\" \"b \\<in> carrier R\" \"a \\<otimes> b \\<in> P\"\n    have \"(PIdl a) \\<cdot> (PIdl b) = Idl (PIdl (a \\<otimes> b))\"\n      using ideal_prod_eq_genideal[of \"Idl { a }\" \"Idl { b }\"]\n            A(1-2) cgenideal_eq_genideal cgenideal_ideal cgenideal_prod by auto\n    hence \"(PIdl a) \\<cdot> (PIdl b) = PIdl (a \\<otimes> b)\"\n      by (simp add: A Idl_subset_ideal cgenideal_ideal cgenideal_minimal\n                    genideal_self oneideal subset_antisym)\n    hence \"(PIdl a) \\<cdot> (PIdl b) \\<subseteq> P\"\n      by (simp add: A(3) assms(1) cgenideal_minimal)\n    hence \"(PIdl a) \\<subseteq> P \\<or> (PIdl b) \\<subseteq> P\"\n      by (simp add: A assms(3) cgenideal_ideal)\n    thus \"a \\<in> P \\<or> b \\<in> P\"\n      using A cgenideal_self by blast\n  qed\n  thus ?thesis\n    using assms is_cring by (simp add: primeidealI)\nqed\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Algebra/Ideal_Product.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952893703477, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7630151256057796}}
{"text": "section {* \\isaheader{Operations on sorted Lists} *}\ntheory Sorted_List_Operations\nimports Main \"../../Automatic_Refinement/Lib/Misc\"\nbegin \n\nfun inter_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"inter_sorted [] l2 = []\"\n | \"inter_sorted l1 [] = []\"\n | \"inter_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then (inter_sorted l1 (x2 # l2)) else \n     (if (x1 = x2) then x1 # (inter_sorted l1 l2) else inter_sorted (x1 # l1) l2))\"\n\nlemma inter_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"distinct (inter_sorted l1 l2) \\<and> sorted (inter_sorted l1 l2) \\<and> \n       set (inter_sorted l1 l2) = set l1 \\<inter> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply (auto simp add: sorted_Cons Ball_def)\n        apply (metis linorder_not_le)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis by (simp add: x1_eq_x2 sorted_Cons Ball_def)\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n        show ?thesis \n          apply (auto simp add: x2_less_x1 sorted_Cons Ball_def)\n          apply (metis linorder_not_le x2_less_x1)\n        done\n      qed\n    qed\n  qed\nqed\n\nfun diff_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"diff_sorted [] l2 = []\"\n | \"diff_sorted l1 [] = l1\"\n | \"diff_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then x1 # (diff_sorted l1 (x2 # l2)) else \n     (if (x1 = x2) then (diff_sorted l1 l2) else diff_sorted (x1 # l1) l2))\"\n\nlemma diff_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"distinct (diff_sorted l1 l2) \\<and> sorted (diff_sorted l1 l2) \\<and> \n       set (diff_sorted l1 l2) = set l1 - set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply simp\n        apply (simp add: sorted_Cons Ball_def set_eq_iff)\n        apply (metis linorder_not_le order_less_imp_not_eq2)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis by (simp add: x1_eq_x2 sorted_Cons Ball_def)\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from x2_less_x1 x1_le have x2_nin_l1: \"x2 \\<notin> set l1\"\n           by (metis linorder_not_less)\n\n        from ind_hyp_l2 x1_le x2_nin_l1\n        show ?thesis \n          apply (simp add: x2_less_x1 x1_neq_x2 x2_le_x1 x1_nin_l1 sorted_Cons Ball_def set_eq_iff)\n          apply (metis x1_neq_x2)\n        done\n      qed\n    qed\n  qed\nqed\n\nfun subset_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n   \"subset_sorted [] l2 = True\"\n | \"subset_sorted (x1 # l1) [] = False\"\n | \"subset_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then False else \n     (if (x1 = x2) then (subset_sorted l1 l2) else subset_sorted (x1 # l1) l2))\"\n\nlemma subset_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"subset_sorted l1 l2 \\<longleftrightarrow> set l1 \\<subseteq> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: sorted_Cons Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply (auto simp add: sorted_Cons Ball_def)\n        apply (metis linorder_not_le)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis \n          apply (simp add: subset_iff x1_eq_x2 sorted_Cons Ball_def)\n          apply metis\n        done\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n        show ?thesis \n          apply (simp add: subset_iff x2_less_x1 sorted_Cons Ball_def)\n          apply (metis linorder_not_le x2_less_x1)\n        done\n      qed\n    qed\n  qed\nqed\n\nlemma set_eq_sorted_correct :\n  assumes l1_OK: \"distinct l1 \\<and> sorted l1\"\n  assumes l2_OK: \"distinct l2 \\<and> sorted l2\"\n  shows \"l1 = l2 \\<longleftrightarrow> set l1 = set l2\"\n  using assms\nproof -\n  have l12_eq: \"l1 = l2 \\<longleftrightarrow> subset_sorted l1 l2 \\<and> subset_sorted l2 l1\"\n  proof (induct l1 arbitrary: l2)\n    case Nil thus ?case by (cases l2) auto\n  next\n    case (Cons x1 l1')\n    note ind_hyp = Cons(1)\n\n    show ?case\n    proof (cases l2)\n      case Nil thus ?thesis by simp\n    next\n      case (Cons x2 l2')\n      thus ?thesis by (simp add: ind_hyp)\n    qed\n  qed\n  also have \"\\<dots> \\<longleftrightarrow> ((set l1 \\<subseteq> set l2) \\<and> (set l2 \\<subseteq> set l1))\"\n    using subset_sorted_correct[OF l1_OK l2_OK] subset_sorted_correct[OF l2_OK l1_OK]\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> set l1 = set l2\" by auto\n  finally show ?thesis .\nqed\n\nfun memb_sorted where\n   \"memb_sorted [] x = False\"\n | \"memb_sorted (y # xs) x =\n    (if (y < x) then memb_sorted xs x else (x = y))\"\n\nlemma memb_sorted_correct :\n  \"sorted xs \\<Longrightarrow> memb_sorted xs x \\<longleftrightarrow> x \\<in> set xs\"\nby (induct xs) (auto simp add: sorted_Cons Ball_def)\n\n\nfun insertion_sort where\n   \"insertion_sort x [] = [x]\"\n | \"insertion_sort x (y # xs) =\n    (if (y < x) then y # insertion_sort x xs else \n     (if (x = y) then y # xs else x # y # xs))\"\n\nlemma insertion_sort_correct :\n  \"sorted xs \\<Longrightarrow> distinct xs \\<Longrightarrow>\n   distinct (insertion_sort x xs) \\<and> \n   sorted (insertion_sort x xs) \\<and>\n   set (insertion_sort x xs) = set (x # xs)\"\nby (induct xs) (auto simp add: sorted_Cons Ball_def)\n\nfun delete_sorted where\n   \"delete_sorted x [] = []\"\n | \"delete_sorted x (y # xs) =\n    (if (y < x) then y # delete_sorted x xs else \n     (if (x = y) then xs else y # xs))\"\n\nlemma delete_sorted_correct :\n  \"sorted xs \\<Longrightarrow> distinct xs \\<Longrightarrow>\n   distinct (delete_sorted x xs) \\<and> \n   sorted (delete_sorted x xs) \\<and>\n   set (delete_sorted x xs) = set xs - {x}\"\napply (induct xs) \napply simp\napply (simp add: sorted_Cons Ball_def set_eq_iff)\napply (metis order_less_le)\ndone\n\nend\n", "meta": {"author": "andredidier", "repo": "phd", "sha": "113f7c8b360a3914a571db13d9513e313954f4b2", "save_path": "github-repos/isabelle/andredidier-phd", "path": "github-repos/isabelle/andredidier-phd/phd-113f7c8b360a3914a571db13d9513e313954f4b2/thesis/Collections/Lib/Sorted_List_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8856314723088733, "lm_q1q2_score": 0.7630053623143438}}
{"text": "theory MathOlympiadProblems\nimports Complex_Main Dirichlet_Series.Arithmetic_Summatory Dirichlet_Series.Divisor_Count \nbegin\n\nsection \\<open>India 2014 Question 2\\<close>\n\n(*\nhttps://www.youtube.com/watch?v=SEHhzkH3ZqM\nhttps://en.wikipedia.org/wiki/Floor_and_ceiling_functions#Equivalences\nhttps://www.youtube.com/watch?v=KMyQIPc4pgA&feature=youtu.be\nhttps://math.stackexchange.com/questions/338432/how-to-prove-the-relation-between-the-floor-function-and-the-number-of-divisors\n*)\n\nsledgehammer_params[debug=true,timeout=600]\n\nabbreviation divisors :: \"nat \\<Rightarrow> int\" where\n  \"divisors n \\<equiv> card { d. d dvd n }\"\n\nabbreviation psq where\n  \"psq n \\<equiv> (\\<exists>a. n = a\\<^sup>2)\"\n\nlemma not_psq:\n  fixes n::nat\n  assumes \"\\<not> (psq n)\"\n  shows \"\\<forall>a::nat. n \\<noteq> a\\<^sup>2\"  using assms by simp\n\n(* Proof borrowed from sum_upto_sum_divisors; seems easier than trying to fit proof to use sum_upto_sum_divisors *)\nlemma sum_div_sum_divisors:\n  fixes n::nat\n  shows  \"(\\<Sum>k \\<in> {1..n}.  \\<lfloor>n / k \\<rfloor>) = (\\<Sum>i \\<in> {1..n}. divisors(i))\" \nproof - \n  let ?A = \"SIGMA  i: {1..n}. {d. d dvd i}\"\n  let ?B = \"SIGMA  k: {1..n}. {1.. nat \\<lfloor>n / k \\<rfloor> }\"\n\n  have bij: \"bij_betw (\\<lambda>(k,d). (d * k, k)) ?B ?A\"\n    apply(rule bij_betwI[where g = \"\\<lambda>(k,d). (d, k div d)\"],auto+ )\n    apply(metis floor_divide_of_nat_eq le_trans mult.commute mult_le_mono2 nat_int times_div_less_eq_dividend)\n     apply(meson Suc_le_lessD dvd_imp_le le_trans)\n  by (simp add: div_le_mono floor_divide_of_nat_eq)\n\n  \n  have \"(\\<Sum>i \\<in> {1..n}. divisors(i)) = (\\<Sum>(k,d)\\<in>?A. 1)\" \n    using sum.Sigma[of \"{1..n}\" \"\\<lambda>i. {d. d dvd i}\"  \"\\<lambda>_ _. 1\"] by simp\n  also have \"... = (\\<Sum>(k,d)\\<in>?B. 1)\"   by (subst sum.reindex_bij_betw[OF bij, symmetric]) (auto simp: case_prod_unfold)\n  also have \"... = (\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n / real k \\<rfloor>)\" using\n   sum.Sigma[of \"{1..n}\" \"\\<lambda>k. {1.. nat \\<lfloor>real n / real k \\<rfloor> }\" \"\\<lambda>_ _.1\" ] by simp\n  finally show ?thesis by auto\nqed\n\n\n(* From ME *)\nlemma bij_betw_submultisets:\n  \"card {B. B \\<subseteq># A} = (\\<Prod>x\\<in>set_mset A. count A x + 1)\"\nproof -\n  define f :: \"'a multiset \\<Rightarrow> 'a \\<Rightarrow> nat\"\n    where \"f = (\\<lambda>B x. if x \\<in># A then count B x else undefined)\"\n  define g :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a multiset\"\n    where \"g = (\\<lambda>h. Abs_multiset (\\<lambda>x. if x \\<in># A then h x else 0))\"\n\n  have count_g: \"count (g h) x = (if x \\<in># A then h x else 0)\"\n    if \"h \\<in> (\\<Pi>\\<^sub>E x\\<in>set_mset A. {0..count A x})\" for h x\n  proof -\n    have \"finite {x. (if x \\<in># A then h x else 0) > 0}\"\n      by (rule finite_subset[of _ \"set_mset A\"]) (use that in auto)\n    thus ?thesis by (simp add: multiset_def g_def)\n  qed\n\n  have f: \"f B \\<in> (\\<Pi>\\<^sub>E x\\<in>set_mset A. {0..count A x})\" if \"B \\<subseteq># A\" for B\n      using that by (auto simp: f_def subseteq_mset_def)\n\n  have \"bij_betw f {B. B \\<subseteq># A} (\\<Pi>\\<^sub>E x\\<in>set_mset A. {0..count A x})\"\n  proof (rule bij_betwI[where g = g], goal_cases)\n    case 1\n    thus ?case using f by auto\n  next\n    case 2\n    show ?case\n      by (auto simp: Pi_def PiE_def count_g subseteq_mset_def)\n  next\n    case (3 B)\n    have \"count (g (f B)) x  = count B x\" for x\n    proof -\n      have \"count (g (f B)) x = (if x \\<in># A then f B x else 0)\"\n        using f 3 by (simp add: count_g)\n      also have \"\\<dots> = count B x\"\n        using 3 by (auto simp: f_def dest: mset_subset_eqD)\n      finally show ?thesis .\n    qed\n    thus ?case\n      by (auto simp: multiset_eq_iff)\n  next\n    case 4\n    thus ?case\n      by (auto simp: fun_eq_iff f_def count_g)\n  qed\n  hence \"card {B. B \\<subseteq># A} = card (\\<Pi>\\<^sub>E x\\<in>set_mset A. {0..count A x})\"\n    using bij_betw_same_card by blast\n  thm card_PiE\n  thus ?thesis\n    by (simp add: card_PiE)\nqed\n\nlemma count_multiplicity:\n  fixes n::nat\n  assumes  \"p \\<in> prime_factors n\"\n  shows \"count (prime_factorization n) p = multiplicity p n\"\n  using assms  count_prime_factorization_prime by blast\n\nlemma num_divisors:\n  fixes n :: nat\n  assumes \"n \\<noteq> 0\"\n  shows  \"card { d. d dvd n } = (\\<Prod>p\\<in> prime_factors n.  multiplicity p n + 1)\"\nproof - \n  define f :: \"nat multiset \\<Rightarrow> nat\" where \"f = prod_mset\"\n  define g :: \"nat \\<Rightarrow> nat multiset\" where \"g = prime_factorization\"\n\n  have \"bij_betw f  { B . B \\<subseteq># prime_factorization n} { d. d dvd n }\" \n  proof (rule bij_betwI[where g = g], goal_cases)\n    case 1\n    {\n      fix x\n      assume \"x \\<in> {B. B \\<subseteq># prime_factorization n}\" \n      hence \"f x \\<in> { d . d dvd n}\" using prime_factorization_subset_iff_dvd \n        using assms f_def prod_mset_subset_imp_dvd by fastforce\n    }\n    then show ?case by simp\n  next\n    case 2\n    {\n      fix x\n      assume \"x \\<in> { d . d dvd n}\" \n      hence \"g x \\<in>  {B. B \\<subseteq># prime_factorization n}\" using prime_factorization_subset_iff_dvd \n        using assms f_def prod_mset_subset_imp_dvd \n        by (metis g_def mem_Collect_eq prime_factorization_0 subset_mset.bot.extremum)\n    }\n    then show ?case by simp \n  next\n    case (3 x)\n    hence \"(\\<And>p. p \\<in># x \\<Longrightarrow> prime p)\"  using mset_subset_eqD by fastforce\n    then show ?case using f_def g_def assms prime_factorization_prod_mset_primes[of x] normalize_nat_def by auto\n  next\n    case (4 y)\n    then show ?case using f_def g_def assms prod_mset_prime_factorization normalize_nat_def by auto\n  qed\n\n  hence  \"card { d. d dvd n } = card {B. B \\<subseteq># prime_factorization n}\" \n    using prime_factorization_subset_iff_dvd bij_betw_same_card by force\n  moreover have \"(\\<Prod>x\\<in>prime_factors n. count (prime_factorization n) x + 1) = (\\<Prod>p\\<in>prime_factors n. multiplicity p n + 1)\"\n    using count_multiplicity \n    by (metis (no_types, lifting) prod.cong)\n  ultimately show ?thesis using bij_betw_submultisets[of \"prime_factorization n\"] by simp\nqed\n\nlemma even_psq:\n  fixes n::nat\n  assumes \"B =  prime_factorization n\" and\n         \"\\<forall>p \\<in>#  B.  even( count B p )\" and \"n \\<noteq> 0\"\n  shows \"psq n\"\nproof -\n\n  define f where \"f = (\\<lambda>p. if p \\<in># B then (count B p)  div 2 else 0)\" \n  define A where \"A = Abs_multiset f\"\n\n  have fm: \"f  \\<in> multiset\" proof -\n    have \"finite {x. 0 < f x}\" using f_def \n      by (metis finite_nat_set_iff_bounded finite_set_mset mem_Collect_eq nat_neq_iff)\n    thus ?thesis using multiset_def by auto\n  qed\n\n  have \"A + A = B\" proof  -\n    have \"(\\<forall>p. count (A + A) p = count B p)\"  using A_def assms fm f_def Abs_multiset_inverse  dvd_div_eq_iff by fastforce     \n    thus ?thesis  using  multiset_eq_iff[of \"A + A\" B] by simp\n  qed\n\n  obtain a::nat where a:\"a = prod_mset A\"  by simp\n \n  have \"(\\<And>p. p \\<in># A \\<Longrightarrow> prime p)\" \n  proof -\n    fix p\n    assume \"p \\<in> set_mset A\"\n    hence \"count A p > 0\" by auto\n    hence \"count B p > 0\" using assms \n      by (metis \\<open>A + A = B\\<close> count_eq_zero_iff neq0_conv union_iff)\n    thus  \"prime p\" using assms prime_factorization_def by auto\n  qed\n \n  hence a2:\"A = prime_factorization a\"\n    using  prime_factorization_exists[of a] normalize_nat_def prime_factorization_unique prime_factorization_prod_mset_primes            \n    by (simp add: prime_factorization_prod_mset_primes a)\n  hence \"a \\<noteq> 0\" using a \n    by (metis prime_factorization_0 prod_mset_empty zero_neq_one)\n  hence \"prime_factorization (a * a) = A + A\" \n     using prime_factorization_mult \\<open>a \\<noteq> 0\\<close> a2 by auto\n  hence \"prime_factorization (a * a) = prime_factorization n\" using  \\<open>A + A = B\\<close> assms by auto\n  hence \"n = a\\<^sup>2\" using prime_factorization_unique[of \"a*a\" n] normalize_nat_def a2 a \n    a2 a assms power2_eq_square \\<open>a \\<noteq> 0\\<close>\n    by (metis id_apply mult_is_0)\n  thus ?thesis by simp\nqed\n\nlemma psq_even:\n  fixes n::nat\n  assumes  \"psq n\" and \"B =  prime_factorization n\"\n  shows \"\\<forall>p \\<in># B.  even ( count B p)\"\nusing assms proof(cases \"n=0\")\n  case True\n  then show ?thesis  by (simp add: assms(2))\nnext\n  case False\n \n  obtain a::nat where a: \"n = a\\<^sup>2\" using assms by auto\n\n  define A where \"A = prime_factorization a\" \n  have \"a \\<noteq> 0\"  using a False by simp\n  hence \"A + A = B\" using prime_factorization_mult[of a a] a assms \n    by (simp add: A_def power2_eq_square)\n\n  hence \"\\<forall>p \\<in># B. count B p = count A p + count A p\" using count_union by auto\n  thus ?thesis by simp\nqed\n\nlemma num_divisors2:\n  fixes n::nat\n  assumes \"n \\<noteq> 0\" and \"A = prime_factorization n\"\n  shows \"card {d. d dvd n} = (\\<Prod>p \\<in> set_mset A. count A p  + 1)\" \nproof -\n  have \"\\<forall>p \\<in> set_mset A. count A p + 1 = multiplicity p n + 1\" using count_prime_factorization_prime \n    by (simp add: assms(2) count_multiplicity)\n  hence *:\"(\\<Prod>p \\<in> set_mset A. multiplicity p n + 1) =  (\\<Prod>p \\<in> set_mset A. count A p  + 1)\" \n    using assms prime_factorsI by auto   \n  hence \"(\\<Prod>p \\<in> prime_factors n . multiplicity p n + 1) =  (\\<Prod>p \\<in> set_mset A. multiplicity p n + 1)\" \n    unfolding  prod_mset_def \n    using assms(2) by auto\n  thus ?thesis using num_divisors[of n] assms * by auto\nqed\n\n\nlemma odd_even:\n  fixes A::\"'a set\" \n  assumes \"finite A\"\n  shows \"odd (\\<Prod>p \\<in> A. (f p  + 1)) = (\\<forall>p \\<in> A. even (f p ))\"\nusing assms proof(induct A rule:finite_induct)\n  case empty\n  then show ?case by auto\nnext\n  case (insert x F)\n  hence \"(\\<Prod>p\\<in>insert x F. (f p + 1)) = (\\<Prod>p\\<in>F. f p + 1) * (f x + 1)\" \n    by (simp add: mult.commute)\n  then show ?case using insert \n    by auto\nqed\n\nlemma psq_odd_card_divisors:\n  fixes n::nat\n  assumes \"n \\<noteq> 0\"\n  shows \"psq n \\<longleftrightarrow> odd (divisors n)\"\nproof -\n  obtain A where A:\"A =  prime_factorization n\" by auto\n  hence *:\"finite (set_mset A)\" \n    by simp\n  hence \"odd (divisors n) = (\\<forall>p \\<in># A.  even ( count A p))\" using num_divisors2[OF assms A]  \n         odd_even[OF *, where f=\"count A\"] \n    by presburger\n  thus ?thesis using psq_even even_psq assms A by metis\nqed\n \n\nlemma sum_divisors_eq_sum_psq:\n  fixes n::nat\n  shows  \"(\\<Sum>k \\<in> {1..n}. divisors(k)) mod 2 = ((\\<Sum>k \\<in> {1..n}. if psq k then 1 else 0)) mod 2\"\nproof(induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc m)\n  have \"Suc m \\<noteq> 0\" by auto\n  hence *: \"(if psq (Suc m) then 1 else 0) =  divisors (Suc m) mod 2\" using psq_odd_card_divisors[of \"Suc m\"] \n    by (metis parity_cases) \n\n  have \"sum divisors {1..Suc m} mod 2  = (sum divisors {1..m} + divisors (Suc m) ) mod 2\" \n    by auto\n  also have \"... = (sum divisors {1..m} mod 2 + divisors (Suc m) mod 2 ) mod 2\" by presburger\n  also have \"... = (((\\<Sum>k = 1..m. if psq k then 1 else 0) mod 2) +  divisors (Suc m) mod 2 ) mod 2\" \n    using Suc by argo\n  also have \"... = (((\\<Sum>k = 1..m. if psq k then 1 else 0) mod 2) + (if psq (Suc m) then 1 else 0) mod 2) mod 2\" \n    using * by presburger\n   also have \"... = (((\\<Sum>k = 1..m. if psq k then 1 else 0) + (if psq (Suc m) then 1 else 0)) mod 2) mod 2\"      \n     by (simp add: mod_add_left_eq)\n   also have \"... =  (\\<Sum>k = 1..Suc m. if psq k then 1 else 0) mod 2\"\n     by auto\n  finally show ?case by auto\nqed\n\n\n\nlemma divsuc:\n  fixes n::nat\n  assumes \"n \\<noteq> 0\" and \"k dvd (n+1)\" and \"k \\<noteq> 1\"\n  shows \"\\<not> (k dvd n)\"\nusing assms proof(induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc m)\n  then show ?case using dvd_def \n    by (metis One_nat_def dvd_1_iff_1 dvd_add_right_iff)\nqed  \n\n\nlemma suc_n_product:\n  fixes k::nat and n::nat\n  assumes \"n+1 = k * x\" \n  shows \"n = k*(x-1) + (k-1)\"\nproof -\n  have \"k*(x-1) + (k-1) = k*x - k + (k - 1)\" using assms \n    by (simp add: right_diff_distrib')\n  also have \"... = k*x - 1\" \n    using Nat.add_diff_assoc Suc_diff_1 assms diff_is_0_eq' le_add2 le_numeral_extra\n      less_numeral_extra(1) one_le_mult_iff ordered_cancel_comm_monoid_diff_class.diff_add \n    \n    by (metis add_right_imp_eq calculation mult.right_neutral nat_less_le no_zero_divisors zero_less_diff)\n  finally have \"k*(x-1) + (k-1) = n\" using assms by simp\n  thus ?thesis by simp\nqed\n\nlemma div_suc_n_mod_n:\n  fixes k::nat and n::nat\n  assumes \"(n+1) mod k = 0\" and \"k > 0\" and \"n > 0\" \n  shows \"n mod k = k-1\" using assms \n  by (smt Suc_lessI add.right_neutral add_eq_0_iff_both_eq_0 diff_Suc_1 \n         group_cancel.add2 mod_add_left_eq mod_less plus_1_eq_Suc unique_euclidean_semiring_numeral_class.pos_mod_bound zero_neq_one)\n\nlemma div_suc_n_div_n:\n  fixes k::nat and n::nat\n  assumes \"(n+1) div k = x\" and \"(n+1) mod k = 0\"\n  shows \"n div k = x - 1\"\nproof - \n  have \"n+1 = k * x\" using assms \n    by auto\n  hence \"n = k*(x-1) + (k-1)\" using assms suc_n_product[of n k x] by auto\n  moreover have \"n mod k = k-1\" using assms div_suc_n_mod_n \n    by (metis \\<open>n + 1 = k * x\\<close> add_gr_0 calculation mod_mod_trivial nat_0_less_mult_iff not_gr_zero)\n  ultimately show ?thesis using div_mult_mod_eq[of n k] \n    by (metis Nat.add_0_right \\<open>n + 1 = k * x\\<close> assms(1) diff_0_eq_0 div_mult_self4 mod_div_trivial mult_eq_0_iff)\nqed\n\n\n\nlemma divstep:\n  fixes k::nat and n::nat\n  assumes \"n \\<noteq> 0\" and \"k dvd (n+1)\" and \"k > 1\"\n  shows \"\\<lfloor>(n+1)/k\\<rfloor> = \\<lfloor>n/k\\<rfloor> + 1\"\nproof -\n  have \"\\<lfloor>(n+1)/k\\<rfloor> = (n+1) div k\" using assms by fastforce\n  hence \"n div k = \\<lfloor>(n+1)/k\\<rfloor> - 1\" using assms div_suc_n_div_n[of n k] \n    using dvd_div_gt0 int_ops(6) by auto\n  moreover have \"\\<lfloor>n/k\\<rfloor> = n div k\" using assms \n    by (simp add: floor_divide_of_nat_eq)\n  ultimately show ?thesis using assms by simp\nqed\n\n\n\nlemma sqrt_suc_le_suc_sqrt:\n fixes n::nat \n shows  \"sqrt(n+1) \\<le> sqrt(n) + 1\"\nproof -\n  have \"n + 1 \\<le> n + 2*sqrt(n) + 1\" by simp\n  moreover have \"n + 2*sqrt(n) + 1 = (sqrt(n) + 1)\\<^sup>2\" proof -\n    have \"(sqrt(n) + 1)\\<^sup>2 = (sqrt(n) + 1) * (sqrt(n) + 1)\" \n      by (simp add: power2_eq_square)\n    also have \"... = sqrt(n)*sqrt(n) + 2*sqrt(n) + 1\" by argo\n    finally show ?thesis by auto\n  qed\n\n  ultimately have \"n + 1 \\<le> (sqrt(n) + 1)\\<^sup>2\" by simp\n  thus ?thesis \n    by (smt \\<open>real n + 2 * sqrt (real n) + 1 = (sqrt (real n) + 1)\\<^sup>2\\<close> of_nat_0 of_nat_le_0_iff real_le_lsqrt sqrt_le_D)\nqed\n\n\nlemma sqrt_suc_le_suc_sqrt2:\n  fixes n::nat\n  shows \"\\<lfloor>sqrt (n+1)\\<rfloor> - \\<lfloor>sqrt n\\<rfloor> \\<le> 1\"\n  using sqrt_suc_le_suc_sqrt[of n] \n  by linarith\n\n\nlemma psq_imp_sqrt_suc_suc:\n  fixes n::nat\n  assumes \"psq (n+1)\"\n  shows \"\\<lfloor>sqrt (n+1)\\<rfloor> = \\<lfloor>sqrt n\\<rfloor>+1\" \nproof -\n  obtain a::nat where a:\"n+1=a\\<^sup>2\" using assms by auto\n  hence \"\\<lfloor>sqrt (n+1)\\<rfloor> = a\" by auto\n  have \"a - \\<lfloor>sqrt n\\<rfloor> = 1\" proof(rule ccontr)\n    assume \"a - \\<lfloor>sqrt n\\<rfloor> \\<noteq> 1\"\n    hence \"\\<lfloor>sqrt n\\<rfloor> = a\" using sqrt_suc_le_suc_sqrt2\n      by (smt \\<open>\\<lfloor>sqrt (real (n + 1))\\<rfloor> = int a\\<close> floor_mono of_nat_1 of_nat_add real_sqrt_le_iff)\n    hence \"sqrt n \\<ge> a\" by linarith\n    hence \"n \\<ge> a\\<^sup>2\" \n      using  a le_add2 of_nat_1 of_nat_add of_nat_le_of_nat_power_cancel_iff one_power2 power2_nat_le_eq_le real_le_lsqrt real_sqrt_eq_iff real_sqrt_unique      \n      by (metis of_nat_0_le_iff power_mono real_sqrt_pow2_iff)\n    thus False using a by simp\n  qed\n  thus ?thesis using a by simp\nqed\n\nlemma not_psq_imp_sqrt_suc_eq:\n  fixes n::nat\n  assumes \"\\<not> psq (n+1)\"\n  shows \"\\<lfloor>sqrt (n+1)\\<rfloor> = \\<lfloor>sqrt n\\<rfloor>\" \nproof -\n  have psq: \"\\<forall>a::nat. n+1 \\<noteq> a\\<^sup>2\" using assms not_psq[of \"n+1\"] by auto\n  obtain a::nat where a_def:\" a = \\<lfloor>sqrt (n+1)\\<rfloor>\" \n    using nat_0_le of_nat_0_le_iff real_sqrt_ge_0_iff zero_le_floor by blast\n  have 2:\"n+1 < (a+1)\\<^sup>2\" proof(rule ccontr)\n    assume \"\\<not> n + 1 < (a + 1)\\<^sup>2\" \n    hence \"n+1 \\<ge> (a + 1)\\<^sup>2\" by auto\n    hence \"sqrt (n+1) \\<ge> a + 1\" \n      using of_nat_le_of_nat_power_cancel_iff real_le_rsqrt by blast\n    thus False using a_def by linarith\n  qed\n  moreover have 1:\"a\\<^sup>2 \\<le> n\" proof(rule ccontr)\n    assume \"\\<not> (a\\<^sup>2 \\<le> n)\" \n    hence **:\"a\\<^sup>2 \\<ge> n+1\" by auto\n    show False proof(cases \"a\\<^sup>2 = n+1\")\n      case True\n      then show ?thesis using psq by metis\n    next\n      case False\n      hence \"a > sqrt(n+1)\" using ** \n        by (smt add_leD2 le_antisym of_nat_1 of_nat_le_of_nat_power_cancel_iff one_power2 power2_nat_le_eq_le real_less_lsqrt real_sqrt_lt_0_iff)\n      then show ?thesis using a_def by linarith\n    qed    \n  qed\n  moreover have 3:\"n < n+1\" by auto\n  ultimately have  \"a \\<le> sqrt n \\<and> sqrt n < (a+1)\" proof -\n    have \"a \\<le> sqrt n\" using 1 a_def \n      by (simp add: real_le_rsqrt)\n    moreover have \"sqrt n < (a+1)\" using 2 3 real_le_rsqrt \n      by (smt le_add2 of_nat_1 of_nat_add of_nat_mono of_nat_power_less_of_nat_cancel_iff real_less_lsqrt)\n    ultimately show ?thesis by auto\n  qed\n  hence \"\\<lfloor>sqrt n\\<rfloor> = a\" by linarith\n  thus ?thesis using a_def by simp\nqed\n\n\n\nlemma sum_psq_eq_sqrt:\n  fixes n::nat \n  shows  \"((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0) =  \\<lfloor>sqrt n\\<rfloor>)\"\nproof(induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc m)\n  then show ?case proof(cases \"psq (Suc m)\")\n    case True  \n    hence \"\\<lfloor>sqrt (m+1)\\<rfloor> = \\<lfloor>sqrt m\\<rfloor>+1\"  using psq_imp_sqrt_suc_suc  by auto\n    moreover have \"(if psq (Suc m) then 1 else 0) = 1\" using True by simp\n    ultimately show ?thesis using Suc by auto\n  next\n    case False\n    hence \"\\<lfloor>sqrt (m+1)\\<rfloor> = \\<lfloor>sqrt m\\<rfloor>\" using not_psq_imp_sqrt_suc_eq by simp\n    moreover have \"(if psq (Suc m) then 1 else 0) = 0\" using False by simp\n    ultimately show ?thesis using Suc by auto\n  qed\nqed\n\n\nlemma sum_div_sum_psq:\n  fixes n::nat\n  shows  \"((\\<Sum>k \\<in> {1..n}.   \\<lfloor>n/k\\<rfloor>)) mod 2 = ((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0)) mod 2\" \nproof -\n  have \"(\\<Sum>k \\<in> {1..n}.  (\\<lfloor>n / k \\<rfloor>)) mod 2 = (\\<Sum>i \\<in> {1..n}. divisors(i)) mod 2\" using sum_div_sum_divisors by presburger\n  also have \"... = ((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0)) mod 2\" using sum_divisors_eq_sum_psq[of n] by argo\n  finally show ?thesis by auto\nqed\n\nlemma sum_div_suc_sum_psq:\n  fixes n::nat\n  shows \"((\\<Sum>k \\<in> {1..Suc n}.  \\<lfloor>real (Suc n)/real k\\<rfloor>) mod 2) = (((\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n/ real k\\<rfloor>)) + (if psq (n+1) then 1 else 0)) mod 2\" (is \"?A = ?B \")\nproof -\n  have \"?A = ((\\<Sum>k \\<in> {1..n+1}.  if psq k then 1 else 0)) mod 2\" using sum_div_sum_psq[of \"Suc n\"] by auto\n  also have \"... = (((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0))  + ((if psq (n+1) then 1 else 0))) mod 2\" by auto\n  also have \"... = (((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0) mod 2)  + ((if psq (n+1) then 1 else 0) mod 2)) mod 2\" \n    by (metis (no_types, lifting) mod_add_eq)\n  also have \"... = (((\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n/ real k\\<rfloor>) mod 2 ) + ((if psq (n+1) then 1 else 0) mod 2)) mod 2\" using sum_div_sum_psq by metis\n  finally show ?thesis using mod_add_eq by metis\nqed\n\nlemma soln1:\n  fixes n::nat\n  shows \"even ((\\<Sum>k \\<in> {1..n}.  \\<lfloor>n/k\\<rfloor>) +  \\<lfloor>sqrt n\\<rfloor>) \"\nproof(induct n)\n  case 0\n  then show ?case by auto\nnext\n  case (Suc n) \n  then show ?case proof(cases \"\\<exists>a. n+1 = a\\<^sup>2\")\n    case True\n    hence \" \\<lfloor>sqrt (real n)\\<rfloor> + 1 = \\<lfloor>sqrt (real (Suc n))\\<rfloor>\" using psq_imp_sqrt_suc_suc by simp\n    moreover have \"((\\<Sum>k \\<in> {1..Suc n}.  \\<lfloor>real (Suc n)/real k\\<rfloor>) mod 2) = (((\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n/ real k\\<rfloor>) ) + 1) mod 2\" \n      using sum_div_suc_sum_psq True by simp\n    ultimately have  \"((\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n/real k\\<rfloor>) + \\<lfloor>sqrt (real n)\\<rfloor>) mod 2 = ((\\<Sum>k \\<in> {1..Suc n}.  \\<lfloor>real (Suc n)/ real k\\<rfloor>) + \\<lfloor>sqrt (real (Suc n))\\<rfloor>) mod 2\"      \n      by presburger\n    thus ?thesis using Suc by (metis odd_iff_mod_2_eq_one)\n  next\n    case False\n    hence \" \\<lfloor>sqrt (real n)\\<rfloor>  = \\<lfloor>sqrt (real (Suc n))\\<rfloor>\" using not_psq_imp_sqrt_suc_eq by simp\n    moreover have \"((\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n/ real k\\<rfloor>) mod 2) = ((\\<Sum>k \\<in> {1..Suc n}.  \\<lfloor>real (Suc n)/real k\\<rfloor>) mod 2)\" using sum_div_suc_sum_psq False by auto\n    ultimately have  \"((\\<Sum>k \\<in> {1..n}.  \\<lfloor>real n/real k\\<rfloor>) + \\<lfloor>sqrt (real n)\\<rfloor>) mod 2 = ((\\<Sum>k \\<in> {1..Suc n}.  \\<lfloor>real (Suc n)/ real k\\<rfloor>) + \\<lfloor>sqrt (real (Suc n))\\<rfloor>) mod 2\"      \n      by presburger\n    thus ?thesis using Suc by (metis odd_iff_mod_2_eq_one)\n  qed\nqed\n\nlemma soln2:\n  fixes n::nat\n  shows  \"even ((\\<Sum>k \\<in> {1..n}.   \\<lfloor>n/k\\<rfloor>) +   \\<lfloor>sqrt n\\<rfloor>)\"\nproof  -\n  have \"(\\<Sum>k \\<in> {1..n}.  (\\<lfloor>n / k \\<rfloor>)) mod 2 = (\\<Sum>i \\<in> {1..n}. divisors(i)) mod 2\" using sum_div_sum_divisors by presburger\n  also have \"... = ((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0)) mod 2\" using sum_divisors_eq_sum_psq[of n] by argo\n  finally have \"((\\<Sum>k \\<in> {1..n}.   \\<lfloor>n/k\\<rfloor>)) mod 2 = ((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0)) mod 2\"\n    by auto\n  hence  \"((\\<Sum>k \\<in> {1..n}.   \\<lfloor> n/ k\\<rfloor>) +   \\<lfloor>sqrt n\\<rfloor>) mod 2 = (((\\<Sum>k \\<in> {1..n}.  if psq k then 1 else 0) +  \\<lfloor>sqrt n\\<rfloor>) mod 2)\" \n    using mod_add_cong by blast\n  thus ?thesis using sum_psq_eq_sqrt[of n] \n    by (metis odd_add odd_iff_mod_2_eq_one)\nqed  \n\n\nlemma card_eq_sum: \"card A = sum (\\<lambda>x. 1) A\"\nproof -\n  have \"plus \\<circ> (\\<lambda>_. Suc 0) = (\\<lambda>_. Suc)\"\n    by (simp add: fun_eq_iff)\n  then have \"Finite_Set.fold (plus \\<circ> (\\<lambda>_. Suc 0)) = Finite_Set.fold (\\<lambda>_. Suc)\"\n    by (rule arg_cong)\n  then have \"Finite_Set.fold (plus \\<circ> (\\<lambda>_. Suc 0)) 0 A = Finite_Set.fold (\\<lambda>_. Suc) 0 A\"\n    by (blast intro: fun_cong)\n  then show ?thesis\n    by (simp add: card.eq_fold sum.eq_fold)\nqed\n\nlemma\n  shows \"(\\<Sum>k\\<in> S. (\\<Sum>d\\<in> P k. 1)) = (\\<Sum>k\\<in> S. card (P k))\"\n  using card_eq_sum by auto\n\n\nlemma \n  fixes S::\"'a set\" and P::\"'a \\<Rightarrow> 'b set\"\n  assumes  \"finite S\" and \"\\<forall>k. finite (P k)\"\n  shows \"card {(k,d) . k \\<in> S  \\<and> d \\<in> P k  } = (\\<Sum>k\\<in> S. card (P k))\"\nproof -\n  obtain A::\"'a \\<Rightarrow> ('a*'b) set\" where A:\"A = (\\<lambda>k. {k} \\<times> P k )\" by auto\n  have \"card (\\<Union> (A ` S)) = (\\<Sum>i\\<in>S. card (A i))\" proof(rule card_UN_disjoint)\n    show \"finite S\" using assms by auto  \n    show \"\\<forall>i\\<in>S. finite (A i)\" using assms A by auto\n    show \"\\<forall>i\\<in>S. \\<forall>j\\<in>S. i \\<noteq> j \\<longrightarrow> A i \\<inter> A j = {}\" using A by auto\n  qed\n\n  moreover have \"\\<forall>i \\<in> S. card (A i) = card (P i)\" proof\n    fix i\n    assume *:\"i \\<in> S\"\n    have \"A i = {i} \\<times> P i\" using A by auto\n    then show \"card (A i) = card (P i)\" using * \n      by (simp add: card_cartesian_product_singleton)\n  qed\n  moreover have \"\\<Union> (A ` S) =  {(k,d) . k \\<in> S  \\<and> d \\<in> P k  }\" unfolding image_def\n    apply(auto)\n    using A by blast+\n  ultimately show ?thesis by auto\nqed\n\nend", "meta": {"author": "mpwassell", "repo": "isabelle-accessible-maths", "sha": "586272b177807b168ff730fd0a11cf8037828e2d", "save_path": "github-repos/isabelle/mpwassell-isabelle-accessible-maths", "path": "github-repos/isabelle/mpwassell-isabelle-accessible-maths/isabelle-accessible-maths-586272b177807b168ff730fd0a11cf8037828e2d/thy/MathOlympiadProblems.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7630053598489522}}
{"text": "(*  Title:      HOL/Analysis/Determinants.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection \\<open>Traces, Determinant of square matrices and some properties\\<close>\n\ntheory Determinants\nimports\n  Cartesian_Euclidean_Space\n  \"~~/src/HOL/Library/Permutations\"\nbegin\n\nsubsection \\<open>Trace\\<close>\n\ndefinition trace :: \"'a::semiring_1^'n^'n \\<Rightarrow> 'a\"\n  where \"trace A = sum (\\<lambda>i. ((A$i)$i)) (UNIV::'n set)\"\n\nlemma trace_0: \"trace (mat 0) = 0\"\n  by (simp add: trace_def mat_def)\n\nlemma trace_I: \"trace (mat 1 :: 'a::semiring_1^'n^'n) = of_nat(CARD('n))\"\n  by (simp add: trace_def mat_def)\n\nlemma trace_add: \"trace ((A::'a::comm_semiring_1^'n^'n) + B) = trace A + trace B\"\n  by (simp add: trace_def sum.distrib)\n\nlemma trace_sub: \"trace ((A::'a::comm_ring_1^'n^'n) - B) = trace A - trace B\"\n  by (simp add: trace_def sum_subtractf)\n\nlemma trace_mul_sym: \"trace ((A::'a::comm_semiring_1^'n^'m) ** B) = trace (B**A)\"\n  apply (simp add: trace_def matrix_matrix_mult_def)\n  apply (subst sum.commute)\n  apply (simp add: mult.commute)\n  done\n\ntext \\<open>Definition of determinant.\\<close>\n\ndefinition det:: \"'a::comm_ring_1^'n^'n \\<Rightarrow> 'a\" where\n  \"det A =\n    sum (\\<lambda>p. of_int (sign p) * prod (\\<lambda>i. A$i$p i) (UNIV :: 'n set))\n      {p. p permutes (UNIV :: 'n set)}\"\n\ntext \\<open>A few general lemmas we need below.\\<close>\n\nlemma prod_permute:\n  assumes p: \"p permutes S\"\n  shows \"prod f S = prod (f \\<circ> p) S\"\n  using assms by (fact prod.permute)\n\nlemma product_permute_nat_interval:\n  fixes m n :: nat\n  shows \"p permutes {m..n} \\<Longrightarrow> prod f {m..n} = prod (f \\<circ> p) {m..n}\"\n  by (blast intro!: prod_permute)\n\ntext \\<open>Basic determinant properties.\\<close>\n\nlemma det_transpose: \"det (transpose A) = det (A::'a::comm_ring_1 ^'n^'n)\"\nproof -\n  let ?di = \"\\<lambda>A i j. A$i$j\"\n  let ?U = \"(UNIV :: 'n set)\"\n  have fU: \"finite ?U\" by simp\n  {\n    fix p\n    assume p: \"p \\<in> {p. p permutes ?U}\"\n    from p have pU: \"p permutes ?U\"\n      by blast\n    have sth: \"sign (inv p) = sign p\"\n      by (metis sign_inverse fU p mem_Collect_eq permutation_permutes)\n    from permutes_inj[OF pU]\n    have pi: \"inj_on p ?U\"\n      by (blast intro: subset_inj_on)\n    from permutes_image[OF pU]\n    have \"prod (\\<lambda>i. ?di (transpose A) i (inv p i)) ?U =\n      prod (\\<lambda>i. ?di (transpose A) i (inv p i)) (p ` ?U)\"\n      by simp\n    also have \"\\<dots> = prod ((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) ?U\"\n      unfolding prod.reindex[OF pi] ..\n    also have \"\\<dots> = prod (\\<lambda>i. ?di A i (p i)) ?U\"\n    proof -\n      {\n        fix i\n        assume i: \"i \\<in> ?U\"\n        from i permutes_inv_o[OF pU] permutes_in_image[OF pU]\n        have \"((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) i = ?di A i (p i)\"\n          unfolding transpose_def by (simp add: fun_eq_iff)\n      }\n      then show \"prod ((\\<lambda>i. ?di (transpose A) i (inv p i)) \\<circ> p) ?U =\n        prod (\\<lambda>i. ?di A i (p i)) ?U\"\n        by (auto intro: prod.cong)\n    qed\n    finally have \"of_int (sign (inv p)) * (prod (\\<lambda>i. ?di (transpose A) i (inv p i)) ?U) =\n      of_int (sign p) * (prod (\\<lambda>i. ?di A i (p i)) ?U)\"\n      using sth by simp\n  }\n  then show ?thesis\n    unfolding det_def\n    apply (subst sum_permutations_inverse)\n    apply (rule sum.cong)\n    apply (rule refl)\n    apply blast\n    done\nqed\n\nlemma det_lowerdiagonal:\n  fixes A :: \"'a::comm_ring_1^('n::{finite,wellorder})^('n::{finite,wellorder})\"\n  assumes ld: \"\\<And>i j. i < j \\<Longrightarrow> A$i$j = 0\"\n  shows \"det A = prod (\\<lambda>i. A$i$i) (UNIV:: 'n set)\"\nproof -\n  let ?U = \"UNIV:: 'n set\"\n  let ?PU = \"{p. p permutes ?U}\"\n  let ?pp = \"\\<lambda>p. of_int (sign p) * prod (\\<lambda>i. A$i$p i) (UNIV :: 'n set)\"\n  have fU: \"finite ?U\"\n    by simp\n  from finite_permutations[OF fU] have fPU: \"finite ?PU\" .\n  have id0: \"{id} \\<subseteq> ?PU\"\n    by (auto simp add: permutes_id)\n  {\n    fix p\n    assume p: \"p \\<in> ?PU - {id}\"\n    from p have pU: \"p permutes ?U\" and pid: \"p \\<noteq> id\"\n      by blast+\n    from permutes_natset_le[OF pU] pid obtain i where i: \"p i > i\"\n      by (metis not_le)\n    from ld[OF i] have ex:\"\\<exists>i \\<in> ?U. A$i$p i = 0\"\n      by blast\n    from prod_zero[OF fU ex] have \"?pp p = 0\"\n      by simp\n  }\n  then have p0: \"\\<forall>p \\<in> ?PU - {id}. ?pp p = 0\"\n    by blast\n  from sum.mono_neutral_cong_left[OF fPU id0 p0] show ?thesis\n    unfolding det_def by (simp add: sign_id)\nqed\n\nlemma det_upperdiagonal:\n  fixes A :: \"'a::comm_ring_1^'n::{finite,wellorder}^'n::{finite,wellorder}\"\n  assumes ld: \"\\<And>i j. i > j \\<Longrightarrow> A$i$j = 0\"\n  shows \"det A = prod (\\<lambda>i. A$i$i) (UNIV:: 'n set)\"\nproof -\n  let ?U = \"UNIV:: 'n set\"\n  let ?PU = \"{p. p permutes ?U}\"\n  let ?pp = \"(\\<lambda>p. of_int (sign p) * prod (\\<lambda>i. A$i$p i) (UNIV :: 'n set))\"\n  have fU: \"finite ?U\"\n    by simp\n  from finite_permutations[OF fU] have fPU: \"finite ?PU\" .\n  have id0: \"{id} \\<subseteq> ?PU\"\n    by (auto simp add: permutes_id)\n  {\n    fix p\n    assume p: \"p \\<in> ?PU - {id}\"\n    from p have pU: \"p permutes ?U\" and pid: \"p \\<noteq> id\"\n      by blast+\n    from permutes_natset_ge[OF pU] pid obtain i where i: \"p i < i\"\n      by (metis not_le)\n    from ld[OF i] have ex:\"\\<exists>i \\<in> ?U. A$i$p i = 0\"\n      by blast\n    from prod_zero[OF fU ex] have \"?pp p = 0\"\n      by simp\n  }\n  then have p0: \"\\<forall>p \\<in> ?PU -{id}. ?pp p = 0\"\n    by blast\n  from sum.mono_neutral_cong_left[OF fPU id0 p0] show ?thesis\n    unfolding det_def by (simp add: sign_id)\nqed\n\nlemma det_diagonal:\n  fixes A :: \"'a::comm_ring_1^'n^'n\"\n  assumes ld: \"\\<And>i j. i \\<noteq> j \\<Longrightarrow> A$i$j = 0\"\n  shows \"det A = prod (\\<lambda>i. A$i$i) (UNIV::'n set)\"\nproof -\n  let ?U = \"UNIV:: 'n set\"\n  let ?PU = \"{p. p permutes ?U}\"\n  let ?pp = \"\\<lambda>p. of_int (sign p) * prod (\\<lambda>i. A$i$p i) (UNIV :: 'n set)\"\n  have fU: \"finite ?U\" by simp\n  from finite_permutations[OF fU] have fPU: \"finite ?PU\" .\n  have id0: \"{id} \\<subseteq> ?PU\"\n    by (auto simp add: permutes_id)\n  {\n    fix p\n    assume p: \"p \\<in> ?PU - {id}\"\n    then have \"p \\<noteq> id\"\n      by simp\n    then obtain i where i: \"p i \\<noteq> i\"\n      unfolding fun_eq_iff by auto\n    from ld [OF i [symmetric]] have ex:\"\\<exists>i \\<in> ?U. A$i$p i = 0\"\n      by blast\n    from prod_zero [OF fU ex] have \"?pp p = 0\"\n      by simp\n  }\n  then have p0: \"\\<forall>p \\<in> ?PU - {id}. ?pp p = 0\"\n    by blast\n  from sum.mono_neutral_cong_left[OF fPU id0 p0] show ?thesis\n    unfolding det_def by (simp add: sign_id)\nqed\n\nlemma det_I: \"det (mat 1 :: 'a::comm_ring_1^'n^'n) = 1\"\nproof -\n  let ?A = \"mat 1 :: 'a::comm_ring_1^'n^'n\"\n  let ?U = \"UNIV :: 'n set\"\n  let ?f = \"\\<lambda>i j. ?A$i$j\"\n  {\n    fix i\n    assume i: \"i \\<in> ?U\"\n    have \"?f i i = 1\"\n      using i by (vector mat_def)\n  }\n  then have th: \"prod (\\<lambda>i. ?f i i) ?U = prod (\\<lambda>x. 1) ?U\"\n    by (auto intro: prod.cong)\n  {\n    fix i j\n    assume i: \"i \\<in> ?U\" and j: \"j \\<in> ?U\" and ij: \"i \\<noteq> j\"\n    have \"?f i j = 0\" using i j ij\n      by (vector mat_def)\n  }\n  then have \"det ?A = prod (\\<lambda>i. ?f i i) ?U\"\n    using det_diagonal by blast\n  also have \"\\<dots> = 1\"\n    unfolding th prod.neutral_const ..\n  finally show ?thesis .\nqed\n\nlemma det_0: \"det (mat 0 :: 'a::comm_ring_1^'n^'n) = 0\"\n  by (simp add: det_def prod_zero)\n\nlemma det_permute_rows:\n  fixes A :: \"'a::comm_ring_1^'n^'n\"\n  assumes p: \"p permutes (UNIV :: 'n::finite set)\"\n  shows \"det (\\<chi> i. A$p i :: 'a^'n^'n) = of_int (sign p) * det A\"\n  apply (simp add: det_def sum_distrib_left mult.assoc[symmetric])\n  apply (subst sum_permutations_compose_right[OF p])\nproof (rule sum.cong)\n  let ?U = \"UNIV :: 'n set\"\n  let ?PU = \"{p. p permutes ?U}\"\n  fix q\n  assume qPU: \"q \\<in> ?PU\"\n  have fU: \"finite ?U\"\n    by simp\n  from qPU have q: \"q permutes ?U\"\n    by blast\n  from p q have pp: \"permutation p\" and qp: \"permutation q\"\n    by (metis fU permutation_permutes)+\n  from permutes_inv[OF p] have ip: \"inv p permutes ?U\" .\n  have \"prod (\\<lambda>i. A$p i$ (q \\<circ> p) i) ?U = prod ((\\<lambda>i. A$p i$(q \\<circ> p) i) \\<circ> inv p) ?U\"\n    by (simp only: prod_permute[OF ip, symmetric])\n  also have \"\\<dots> = prod (\\<lambda>i. A $ (p \\<circ> inv p) i $ (q \\<circ> (p \\<circ> inv p)) i) ?U\"\n    by (simp only: o_def)\n  also have \"\\<dots> = prod (\\<lambda>i. A$i$q i) ?U\"\n    by (simp only: o_def permutes_inverses[OF p])\n  finally have thp: \"prod (\\<lambda>i. A$p i$ (q \\<circ> p) i) ?U = prod (\\<lambda>i. A$i$q i) ?U\"\n    by blast\n  show \"of_int (sign (q \\<circ> p)) * prod (\\<lambda>i. A$ p i$ (q \\<circ> p) i) ?U =\n    of_int (sign p) * of_int (sign q) * prod (\\<lambda>i. A$i$q i) ?U\"\n    by (simp only: thp sign_compose[OF qp pp] mult.commute of_int_mult)\nqed rule\n\nlemma det_permute_columns:\n  fixes A :: \"'a::comm_ring_1^'n^'n\"\n  assumes p: \"p permutes (UNIV :: 'n set)\"\n  shows \"det(\\<chi> i j. A$i$ p j :: 'a^'n^'n) = of_int (sign p) * det A\"\nproof -\n  let ?Ap = \"\\<chi> i j. A$i$ p j :: 'a^'n^'n\"\n  let ?At = \"transpose A\"\n  have \"of_int (sign p) * det A = det (transpose (\\<chi> i. transpose A $ p i))\"\n    unfolding det_permute_rows[OF p, of ?At] det_transpose ..\n  moreover\n  have \"?Ap = transpose (\\<chi> i. transpose A $ p i)\"\n    by (simp add: transpose_def vec_eq_iff)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma det_identical_rows:\n  fixes A :: \"'a::linordered_idom^'n^'n\"\n  assumes ij: \"i \\<noteq> j\"\n    and r: \"row i A = row j A\"\n  shows \"det A = 0\"\nproof-\n  have tha: \"\\<And>(a::'a) b. a = b \\<Longrightarrow> b = - a \\<Longrightarrow> a = 0\"\n    by simp\n  have th1: \"of_int (-1) = - 1\" by simp\n  let ?p = \"Fun.swap i j id\"\n  let ?A = \"\\<chi> i. A $ ?p i\"\n  from r have \"A = ?A\" by (simp add: vec_eq_iff row_def Fun.swap_def)\n  then have \"det A = det ?A\" by simp\n  moreover have \"det A = - det ?A\"\n    by (simp add: det_permute_rows[OF permutes_swap_id] sign_swap_id ij th1)\n  ultimately show \"det A = 0\" by (metis tha)\nqed\n\nlemma det_identical_columns:\n  fixes A :: \"'a::linordered_idom^'n^'n\"\n  assumes ij: \"i \\<noteq> j\"\n    and r: \"column i A = column j A\"\n  shows \"det A = 0\"\n  apply (subst det_transpose[symmetric])\n  apply (rule det_identical_rows[OF ij])\n  apply (metis row_transpose r)\n  done\n\nlemma det_zero_row:\n  fixes A :: \"'a::{idom, ring_char_0}^'n^'n\"\n  assumes r: \"row i A = 0\"\n  shows \"det A = 0\"\n  using r\n  apply (simp add: row_def det_def vec_eq_iff)\n  apply (rule sum.neutral)\n  apply (auto simp: sign_nz)\n  done\n\nlemma det_zero_column:\n  fixes A :: \"'a::{idom,ring_char_0}^'n^'n\"\n  assumes r: \"column i A = 0\"\n  shows \"det A = 0\"\n  apply (subst det_transpose[symmetric])\n  apply (rule det_zero_row [of i])\n  apply (metis row_transpose r)\n  done\n\nlemma det_row_add:\n  fixes a b c :: \"'n::finite \\<Rightarrow> _ ^ 'n\"\n  shows \"det((\\<chi> i. if i = k then a i + b i else c i)::'a::comm_ring_1^'n^'n) =\n    det((\\<chi> i. if i = k then a i else c i)::'a::comm_ring_1^'n^'n) +\n    det((\\<chi> i. if i = k then b i else c i)::'a::comm_ring_1^'n^'n)\"\n  unfolding det_def vec_lambda_beta sum.distrib[symmetric]\nproof (rule sum.cong)\n  let ?U = \"UNIV :: 'n set\"\n  let ?pU = \"{p. p permutes ?U}\"\n  let ?f = \"(\\<lambda>i. if i = k then a i + b i else c i)::'n \\<Rightarrow> 'a::comm_ring_1^'n\"\n  let ?g = \"(\\<lambda> i. if i = k then a i else c i)::'n \\<Rightarrow> 'a::comm_ring_1^'n\"\n  let ?h = \"(\\<lambda> i. if i = k then b i else c i)::'n \\<Rightarrow> 'a::comm_ring_1^'n\"\n  fix p\n  assume p: \"p \\<in> ?pU\"\n  let ?Uk = \"?U - {k}\"\n  from p have pU: \"p permutes ?U\"\n    by blast\n  have kU: \"?U = insert k ?Uk\"\n    by blast\n  {\n    fix j\n    assume j: \"j \\<in> ?Uk\"\n    from j have \"?f j $ p j = ?g j $ p j\" and \"?f j $ p j= ?h j $ p j\"\n      by simp_all\n  }\n  then have th1: \"prod (\\<lambda>i. ?f i $ p i) ?Uk = prod (\\<lambda>i. ?g i $ p i) ?Uk\"\n    and th2: \"prod (\\<lambda>i. ?f i $ p i) ?Uk = prod (\\<lambda>i. ?h i $ p i) ?Uk\"\n    apply -\n    apply (rule prod.cong, simp_all)+\n    done\n  have th3: \"finite ?Uk\" \"k \\<notin> ?Uk\"\n    by auto\n  have \"prod (\\<lambda>i. ?f i $ p i) ?U = prod (\\<lambda>i. ?f i $ p i) (insert k ?Uk)\"\n    unfolding kU[symmetric] ..\n  also have \"\\<dots> = ?f k $ p k * prod (\\<lambda>i. ?f i $ p i) ?Uk\"\n    apply (rule prod.insert)\n    apply simp\n    apply blast\n    done\n  also have \"\\<dots> = (a k $ p k * prod (\\<lambda>i. ?f i $ p i) ?Uk) + (b k$ p k * prod (\\<lambda>i. ?f i $ p i) ?Uk)\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = (a k $ p k * prod (\\<lambda>i. ?g i $ p i) ?Uk) + (b k$ p k * prod (\\<lambda>i. ?h i $ p i) ?Uk)\"\n    by (metis th1 th2)\n  also have \"\\<dots> = prod (\\<lambda>i. ?g i $ p i) (insert k ?Uk) + prod (\\<lambda>i. ?h i $ p i) (insert k ?Uk)\"\n    unfolding  prod.insert[OF th3] by simp\n  finally have \"prod (\\<lambda>i. ?f i $ p i) ?U = prod (\\<lambda>i. ?g i $ p i) ?U + prod (\\<lambda>i. ?h i $ p i) ?U\"\n    unfolding kU[symmetric] .\n  then show \"of_int (sign p) * prod (\\<lambda>i. ?f i $ p i) ?U =\n    of_int (sign p) * prod (\\<lambda>i. ?g i $ p i) ?U + of_int (sign p) * prod (\\<lambda>i. ?h i $ p i) ?U\"\n    by (simp add: field_simps)\nqed rule\n\nlemma det_row_mul:\n  fixes a b :: \"'n::finite \\<Rightarrow> _ ^ 'n\"\n  shows \"det((\\<chi> i. if i = k then c *s a i else b i)::'a::comm_ring_1^'n^'n) =\n    c * det((\\<chi> i. if i = k then a i else b i)::'a::comm_ring_1^'n^'n)\"\n  unfolding det_def vec_lambda_beta sum_distrib_left\nproof (rule sum.cong)\n  let ?U = \"UNIV :: 'n set\"\n  let ?pU = \"{p. p permutes ?U}\"\n  let ?f = \"(\\<lambda>i. if i = k then c*s a i else b i)::'n \\<Rightarrow> 'a::comm_ring_1^'n\"\n  let ?g = \"(\\<lambda> i. if i = k then a i else b i)::'n \\<Rightarrow> 'a::comm_ring_1^'n\"\n  fix p\n  assume p: \"p \\<in> ?pU\"\n  let ?Uk = \"?U - {k}\"\n  from p have pU: \"p permutes ?U\"\n    by blast\n  have kU: \"?U = insert k ?Uk\"\n    by blast\n  {\n    fix j\n    assume j: \"j \\<in> ?Uk\"\n    from j have \"?f j $ p j = ?g j $ p j\"\n      by simp\n  }\n  then have th1: \"prod (\\<lambda>i. ?f i $ p i) ?Uk = prod (\\<lambda>i. ?g i $ p i) ?Uk\"\n    apply -\n    apply (rule prod.cong)\n    apply simp_all\n    done\n  have th3: \"finite ?Uk\" \"k \\<notin> ?Uk\"\n    by auto\n  have \"prod (\\<lambda>i. ?f i $ p i) ?U = prod (\\<lambda>i. ?f i $ p i) (insert k ?Uk)\"\n    unfolding kU[symmetric] ..\n  also have \"\\<dots> = ?f k $ p k  * prod (\\<lambda>i. ?f i $ p i) ?Uk\"\n    apply (rule prod.insert)\n    apply simp\n    apply blast\n    done\n  also have \"\\<dots> = (c*s a k) $ p k * prod (\\<lambda>i. ?f i $ p i) ?Uk\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = c* (a k $ p k * prod (\\<lambda>i. ?g i $ p i) ?Uk)\"\n    unfolding th1 by (simp add: ac_simps)\n  also have \"\\<dots> = c* (prod (\\<lambda>i. ?g i $ p i) (insert k ?Uk))\"\n    unfolding prod.insert[OF th3] by simp\n  finally have \"prod (\\<lambda>i. ?f i $ p i) ?U = c* (prod (\\<lambda>i. ?g i $ p i) ?U)\"\n    unfolding kU[symmetric] .\n  then show \"of_int (sign p) * prod (\\<lambda>i. ?f i $ p i) ?U =\n    c * (of_int (sign p) * prod (\\<lambda>i. ?g i $ p i) ?U)\"\n    by (simp add: field_simps)\nqed rule\n\nlemma det_row_0:\n  fixes b :: \"'n::finite \\<Rightarrow> _ ^ 'n\"\n  shows \"det((\\<chi> i. if i = k then 0 else b i)::'a::comm_ring_1^'n^'n) = 0\"\n  using det_row_mul[of k 0 \"\\<lambda>i. 1\" b]\n  apply simp\n  apply (simp only: vector_smult_lzero)\n  done\n\nlemma det_row_operation:\n  fixes A :: \"'a::linordered_idom^'n^'n\"\n  assumes ij: \"i \\<noteq> j\"\n  shows \"det (\\<chi> k. if k = i then row i A + c *s row j A else row k A) = det A\"\nproof -\n  let ?Z = \"(\\<chi> k. if k = i then row j A else row k A) :: 'a ^'n^'n\"\n  have th: \"row i ?Z = row j ?Z\" by (vector row_def)\n  have th2: \"((\\<chi> k. if k = i then row i A else row k A) :: 'a^'n^'n) = A\"\n    by (vector row_def)\n  show ?thesis\n    unfolding det_row_add [of i] det_row_mul[of i] det_identical_rows[OF ij th] th2\n    by simp\nqed\n\nlemma det_row_span:\n  fixes A :: \"real^'n^'n\"\n  assumes x: \"x \\<in> span {row j A |j. j \\<noteq> i}\"\n  shows \"det (\\<chi> k. if k = i then row i A + x else row k A) = det A\"\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  let ?S = \"{row j A |j. j \\<noteq> i}\"\n  let ?d = \"\\<lambda>x. det (\\<chi> k. if k = i then x else row k A)\"\n  let ?P = \"\\<lambda>x. ?d (row i A + x) = det A\"\n  {\n    fix k\n    have \"(if k = i then row i A + 0 else row k A) = row k A\"\n      by simp\n  }\n  then have P0: \"?P 0\"\n    apply -\n    apply (rule cong[of det, OF refl])\n    apply (vector row_def)\n    done\n  moreover\n  {\n    fix c z y\n    assume zS: \"z \\<in> ?S\" and Py: \"?P y\"\n    from zS obtain j where j: \"z = row j A\" \"i \\<noteq> j\"\n      by blast\n    let ?w = \"row i A + y\"\n    have th0: \"row i A + (c*s z + y) = ?w + c*s z\"\n      by vector\n    have thz: \"?d z = 0\"\n      apply (rule det_identical_rows[OF j(2)])\n      using j\n      apply (vector row_def)\n      done\n    have \"?d (row i A + (c*s z + y)) = ?d (?w + c*s z)\"\n      unfolding th0 ..\n    then have \"?P (c*s z + y)\"\n      unfolding thz Py det_row_mul[of i] det_row_add[of i]\n      by simp\n  }\n  ultimately show ?thesis\n    apply -\n    apply (rule span_induct_alt[of ?P ?S, OF P0, folded scalar_mult_eq_scaleR])\n    apply blast\n    apply (rule x)\n    done\nqed\n\ntext \\<open>\n  May as well do this, though it's a bit unsatisfactory since it ignores\n  exact duplicates by considering the rows/columns as a set.\n\\<close>\n\nlemma det_dependent_rows:\n  fixes A:: \"real^'n^'n\"\n  assumes d: \"dependent (rows A)\"\n  shows \"det A = 0\"\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  from d obtain i where i: \"row i A \\<in> span (rows A - {row i A})\"\n    unfolding dependent_def rows_def by blast\n  {\n    fix j k\n    assume jk: \"j \\<noteq> k\" and c: \"row j A = row k A\"\n    from det_identical_rows[OF jk c] have ?thesis .\n  }\n  moreover\n  {\n    assume H: \"\\<And> i j. i \\<noteq> j \\<Longrightarrow> row i A \\<noteq> row j A\"\n    have th0: \"- row i A \\<in> span {row j A|j. j \\<noteq> i}\"\n      apply (rule span_neg)\n      apply (rule set_rev_mp)\n      apply (rule i)\n      apply (rule span_mono)\n      using H i\n      apply (auto simp add: rows_def)\n      done\n    from det_row_span[OF th0]\n    have \"det A = det (\\<chi> k. if k = i then 0 *s 1 else row k A)\"\n      unfolding right_minus vector_smult_lzero ..\n    with det_row_mul[of i \"0::real\" \"\\<lambda>i. 1\"]\n    have \"det A = 0\" by simp\n  }\n  ultimately show ?thesis by blast\nqed\n\nlemma det_dependent_columns:\n  assumes d: \"dependent (columns (A::real^'n^'n))\"\n  shows \"det A = 0\"\n  by (metis d det_dependent_rows rows_transpose det_transpose)\n\ntext \\<open>Multilinearity and the multiplication formula.\\<close>\n\nlemma Cart_lambda_cong: \"(\\<And>x. f x = g x) \\<Longrightarrow> (vec_lambda f::'a^'n) = (vec_lambda g :: 'a^'n)\"\n  by (rule iffD1[OF vec_lambda_unique]) vector\n\nlemma det_linear_row_sum:\n  assumes fS: \"finite S\"\n  shows \"det ((\\<chi> i. if i = k then sum (a i) S else c i)::'a::comm_ring_1^'n^'n) =\n    sum (\\<lambda>j. det ((\\<chi> i. if i = k then a  i j else c i)::'a^'n^'n)) S\"\nproof (induct rule: finite_induct[OF fS])\n  case 1\n  then show ?case\n    apply simp\n    unfolding sum.empty det_row_0[of k]\n    apply rule\n    done\nnext\n  case (2 x F)\n  then show ?case\n    by (simp add: det_row_add cong del: if_weak_cong)\nqed\n\nlemma finite_bounded_functions:\n  assumes fS: \"finite S\"\n  shows \"finite {f. (\\<forall>i \\<in> {1.. (k::nat)}. f i \\<in> S) \\<and> (\\<forall>i. i \\<notin> {1 .. k} \\<longrightarrow> f i = i)}\"\nproof (induct k)\n  case 0\n  have th: \"{f. \\<forall>i. f i = i} = {id}\"\n    by auto\n  show ?case\n    by (auto simp add: th)\nnext\n  case (Suc k)\n  let ?f = \"\\<lambda>(y::nat,g) i. if i = Suc k then y else g i\"\n  let ?S = \"?f ` (S \\<times> {f. (\\<forall>i\\<in>{1..k}. f i \\<in> S) \\<and> (\\<forall>i. i \\<notin> {1..k} \\<longrightarrow> f i = i)})\"\n  have \"?S = {f. (\\<forall>i\\<in>{1.. Suc k}. f i \\<in> S) \\<and> (\\<forall>i. i \\<notin> {1.. Suc k} \\<longrightarrow> f i = i)}\"\n    apply (auto simp add: image_iff)\n    apply (rule_tac x=\"x (Suc k)\" in bexI)\n    apply (rule_tac x = \"\\<lambda>i. if i = Suc k then i else x i\" in exI)\n    apply auto\n    done\n  with finite_imageI[OF finite_cartesian_product[OF fS Suc.hyps(1)], of ?f]\n  show ?case\n    by metis\nqed\n\n\nlemma det_linear_rows_sum_lemma:\n  assumes fS: \"finite S\"\n    and fT: \"finite T\"\n  shows \"det ((\\<chi> i. if i \\<in> T then sum (a i) S else c i):: 'a::comm_ring_1^'n^'n) =\n    sum (\\<lambda>f. det((\\<chi> i. if i \\<in> T then a i (f i) else c i)::'a^'n^'n))\n      {f. (\\<forall>i \\<in> T. f i \\<in> S) \\<and> (\\<forall>i. i \\<notin> T \\<longrightarrow> f i = i)}\"\n  using fT\nproof (induct T arbitrary: a c set: finite)\n  case empty\n  have th0: \"\\<And>x y. (\\<chi> i. if i \\<in> {} then x i else y i) = (\\<chi> i. y i)\"\n    by vector\n  from empty.prems show ?case\n    unfolding th0 by (simp add: eq_id_iff)\nnext\n  case (insert z T a c)\n  let ?F = \"\\<lambda>T. {f. (\\<forall>i \\<in> T. f i \\<in> S) \\<and> (\\<forall>i. i \\<notin> T \\<longrightarrow> f i = i)}\"\n  let ?h = \"\\<lambda>(y,g) i. if i = z then y else g i\"\n  let ?k = \"\\<lambda>h. (h(z),(\\<lambda>i. if i = z then i else h i))\"\n  let ?s = \"\\<lambda> k a c f. det((\\<chi> i. if i \\<in> T then a i (f i) else c i)::'a^'n^'n)\"\n  let ?c = \"\\<lambda>j i. if i = z then a i j else c i\"\n  have thif: \"\\<And>a b c d. (if a \\<or> b then c else d) = (if a then c else if b then c else d)\"\n    by simp\n  have thif2: \"\\<And>a b c d e. (if a then b else if c then d else e) =\n     (if c then (if a then b else d) else (if a then b else e))\"\n    by simp\n  from \\<open>z \\<notin> T\\<close> have nz: \"\\<And>i. i \\<in> T \\<Longrightarrow> i = z \\<longleftrightarrow> False\"\n    by auto\n  have \"det (\\<chi> i. if i \\<in> insert z T then sum (a i) S else c i) =\n    det (\\<chi> i. if i = z then sum (a i) S else if i \\<in> T then sum (a i) S else c i)\"\n    unfolding insert_iff thif ..\n  also have \"\\<dots> = (\\<Sum>j\\<in>S. det (\\<chi> i. if i \\<in> T then sum (a i) S else if i = z then a i j else c i))\"\n    unfolding det_linear_row_sum[OF fS]\n    apply (subst thif2)\n    using nz\n    apply (simp cong del: if_weak_cong cong add: if_cong)\n    done\n  finally have tha:\n    \"det (\\<chi> i. if i \\<in> insert z T then sum (a i) S else c i) =\n     (\\<Sum>(j, f)\\<in>S \\<times> ?F T. det (\\<chi> i. if i \\<in> T then a i (f i)\n                                else if i = z then a i j\n                                else c i))\"\n    unfolding insert.hyps unfolding sum.cartesian_product by blast\n  show ?case unfolding tha\n    using \\<open>z \\<notin> T\\<close>\n    by (intro sum.reindex_bij_witness[where i=\"?k\" and j=\"?h\"])\n       (auto intro!: cong[OF refl[of det]] simp: vec_eq_iff)\nqed\n\nlemma det_linear_rows_sum:\n  fixes S :: \"'n::finite set\"\n  assumes fS: \"finite S\"\n  shows \"det (\\<chi> i. sum (a i) S) =\n    sum (\\<lambda>f. det (\\<chi> i. a i (f i) :: 'a::comm_ring_1 ^ 'n^'n)) {f. \\<forall>i. f i \\<in> S}\"\nproof -\n  have th0: \"\\<And>x y. ((\\<chi> i. if i \\<in> (UNIV:: 'n set) then x i else y i) :: 'a^'n^'n) = (\\<chi> i. x i)\"\n    by vector\n  from det_linear_rows_sum_lemma[OF fS, of \"UNIV :: 'n set\" a, unfolded th0, OF finite]\n  show ?thesis by simp\nqed\n\nlemma matrix_mul_sum_alt:\n  fixes A B :: \"'a::comm_ring_1^'n^'n\"\n  shows \"A ** B = (\\<chi> i. sum (\\<lambda>k. A$i$k *s B $ k) (UNIV :: 'n set))\"\n  by (vector matrix_matrix_mult_def sum_component)\n\n\n\nlemma det_mul:\n  fixes A B :: \"'a::linordered_idom^'n^'n\"\n  shows \"det (A ** B) = det A * det B\"\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  let ?F = \"{f. (\\<forall>i\\<in> ?U. f i \\<in> ?U) \\<and> (\\<forall>i. i \\<notin> ?U \\<longrightarrow> f i = i)}\"\n  let ?PU = \"{p. p permutes ?U}\"\n  have fU: \"finite ?U\"\n    by simp\n  have fF: \"finite ?F\"\n    by (rule finite)\n  {\n    fix p\n    assume p: \"p permutes ?U\"\n    have \"p \\<in> ?F\" unfolding mem_Collect_eq permutes_in_image[OF p]\n      using p[unfolded permutes_def] by simp\n  }\n  then have PUF: \"?PU \\<subseteq> ?F\" by blast\n  {\n    fix f\n    assume fPU: \"f \\<in> ?F - ?PU\"\n    have fUU: \"f ` ?U \\<subseteq> ?U\"\n      using fPU by auto\n    from fPU have f: \"\\<forall>i \\<in> ?U. f i \\<in> ?U\" \"\\<forall>i. i \\<notin> ?U \\<longrightarrow> f i = i\" \"\\<not>(\\<forall>y. \\<exists>!x. f x = y)\"\n      unfolding permutes_def by auto\n\n    let ?A = \"(\\<chi> i. A$i$f i *s B$f i) :: 'a^'n^'n\"\n    let ?B = \"(\\<chi> i. B$f i) :: 'a^'n^'n\"\n    {\n      assume fni: \"\\<not> inj_on f ?U\"\n      then obtain i j where ij: \"f i = f j\" \"i \\<noteq> j\"\n        unfolding inj_on_def by blast\n      from ij\n      have rth: \"row i ?B = row j ?B\"\n        by (vector row_def)\n      from det_identical_rows[OF ij(2) rth]\n      have \"det (\\<chi> i. A$i$f i *s B$f i) = 0\"\n        unfolding det_rows_mul by simp\n    }\n    moreover\n    {\n      assume fi: \"inj_on f ?U\"\n      from f fi have fith: \"\\<And>i j. f i = f j \\<Longrightarrow> i = j\"\n        unfolding inj_on_def by metis\n      note fs = fi[unfolded surjective_iff_injective_gen[OF fU fU refl fUU, symmetric]]\n      {\n        fix y\n        from fs f have \"\\<exists>x. f x = y\"\n          by blast\n        then obtain x where x: \"f x = y\"\n          by blast\n        {\n          fix z\n          assume z: \"f z = y\"\n          from fith x z have \"z = x\"\n            by metis\n        }\n        with x have \"\\<exists>!x. f x = y\"\n          by blast\n      }\n      with f(3) have \"det (\\<chi> i. A$i$f i *s B$f i) = 0\"\n        by blast\n    }\n    ultimately have \"det (\\<chi> i. A$i$f i *s B$f i) = 0\"\n      by blast\n  }\n  then have zth: \"\\<forall> f\\<in> ?F - ?PU. det (\\<chi> i. A$i$f i *s B$f i) = 0\"\n    by simp\n  {\n    fix p\n    assume pU: \"p \\<in> ?PU\"\n    from pU have p: \"p permutes ?U\"\n      by blast\n    let ?s = \"\\<lambda>p. of_int (sign p)\"\n    let ?f = \"\\<lambda>q. ?s p * (\\<Prod>i\\<in> ?U. A $ i $ p i) * (?s q * (\\<Prod>i\\<in> ?U. B $ i $ q i))\"\n    have \"(sum (\\<lambda>q. ?s q *\n        (\\<Prod>i\\<in> ?U. (\\<chi> i. A $ i $ p i *s B $ p i :: 'a^'n^'n) $ i $ q i)) ?PU) =\n      (sum (\\<lambda>q. ?s p * (\\<Prod>i\\<in> ?U. A $ i $ p i) * (?s q * (\\<Prod>i\\<in> ?U. B $ i $ q i))) ?PU)\"\n      unfolding sum_permutations_compose_right[OF permutes_inv[OF p], of ?f]\n    proof (rule sum.cong)\n      fix q\n      assume qU: \"q \\<in> ?PU\"\n      then have q: \"q permutes ?U\"\n        by blast\n      from p q have pp: \"permutation p\" and pq: \"permutation q\"\n        unfolding permutation_permutes by auto\n      have th00: \"of_int (sign p) * of_int (sign p) = (1::'a)\"\n        \"\\<And>a. of_int (sign p) * (of_int (sign p) * a) = a\"\n        unfolding mult.assoc[symmetric]\n        unfolding of_int_mult[symmetric]\n        by (simp_all add: sign_idempotent)\n      have ths: \"?s q = ?s p * ?s (q \\<circ> inv p)\"\n        using pp pq permutation_inverse[OF pp] sign_inverse[OF pp]\n        by (simp add:  th00 ac_simps sign_idempotent sign_compose)\n      have th001: \"prod (\\<lambda>i. B$i$ q (inv p i)) ?U = prod ((\\<lambda>i. B$i$ q (inv p i)) \\<circ> p) ?U\"\n        by (rule prod_permute[OF p])\n      have thp: \"prod (\\<lambda>i. (\\<chi> i. A$i$p i *s B$p i :: 'a^'n^'n) $i $ q i) ?U =\n        prod (\\<lambda>i. A$i$p i) ?U * prod (\\<lambda>i. B$i$ q (inv p i)) ?U\"\n        unfolding th001 prod.distrib[symmetric] o_def permutes_inverses[OF p]\n        apply (rule prod.cong[OF refl])\n        using permutes_in_image[OF q]\n        apply vector\n        done\n      show \"?s q * prod (\\<lambda>i. (((\\<chi> i. A$i$p i *s B$p i) :: 'a^'n^'n)$i$q i)) ?U =\n        ?s p * (prod (\\<lambda>i. A$i$p i) ?U) * (?s (q \\<circ> inv p) * prod (\\<lambda>i. B$i$(q \\<circ> inv p) i) ?U)\"\n        using ths thp pp pq permutation_inverse[OF pp] sign_inverse[OF pp]\n        by (simp add: sign_nz th00 field_simps sign_idempotent sign_compose)\n    qed rule\n  }\n  then have th2: \"sum (\\<lambda>f. det (\\<chi> i. A$i$f i *s B$f i)) ?PU = det A * det B\"\n    unfolding det_def sum_product\n    by (rule sum.cong [OF refl])\n  have \"det (A**B) = sum (\\<lambda>f.  det (\\<chi> i. A $ i $ f i *s B $ f i)) ?F\"\n    unfolding matrix_mul_sum_alt det_linear_rows_sum[OF fU]\n    by simp\n  also have \"\\<dots> = sum (\\<lambda>f. det (\\<chi> i. A$i$f i *s B$f i)) ?PU\"\n    using sum.mono_neutral_cong_left[OF fF PUF zth, symmetric]\n    unfolding det_rows_mul by auto\n  finally show ?thesis unfolding th2 .\nqed\n\ntext \\<open>Relation to invertibility.\\<close>\n\nlemma invertible_left_inverse:\n  fixes A :: \"real^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> (\\<exists>(B::real^'n^'n). B** A = mat 1)\"\n  by (metis invertible_def matrix_left_right_inverse)\n\nlemma invertible_righ_inverse:\n  fixes A :: \"real^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> (\\<exists>(B::real^'n^'n). A** B = mat 1)\"\n  by (metis invertible_def matrix_left_right_inverse)\n\nlemma invertible_det_nz:\n  fixes A::\"real ^'n^'n\"\n  shows \"invertible A \\<longleftrightarrow> det A \\<noteq> 0\"\nproof -\n  {\n    assume \"invertible A\"\n    then obtain B :: \"real ^'n^'n\" where B: \"A ** B = mat 1\"\n      unfolding invertible_righ_inverse by blast\n    then have \"det (A ** B) = det (mat 1 :: real ^'n^'n)\"\n      by simp\n    then have \"det A \\<noteq> 0\"\n      by (simp add: det_mul det_I) algebra\n  }\n  moreover\n  {\n    assume H: \"\\<not> invertible A\"\n    let ?U = \"UNIV :: 'n set\"\n    have fU: \"finite ?U\"\n      by simp\n    from H obtain c i where c: \"sum (\\<lambda>i. c i *s row i A) ?U = 0\"\n      and iU: \"i \\<in> ?U\"\n      and ci: \"c i \\<noteq> 0\"\n      unfolding invertible_righ_inverse\n      unfolding matrix_right_invertible_independent_rows\n      by blast\n    have *: \"\\<And>(a::real^'n) b. a + b = 0 \\<Longrightarrow> -a = b\"\n      apply (drule_tac f=\"op + (- a)\" in cong[OF refl])\n      apply (simp only: ab_left_minus add.assoc[symmetric])\n      apply simp\n      done\n    from c ci\n    have thr0: \"- row i A = sum (\\<lambda>j. (1/ c i) *s (c j *s row j A)) (?U - {i})\"\n      unfolding sum.remove[OF fU iU] sum_cmul\n      apply -\n      apply (rule vector_mul_lcancel_imp[OF ci])\n      apply (auto simp add: field_simps)\n      unfolding *\n      apply rule\n      done\n    have thr: \"- row i A \\<in> span {row j A| j. j \\<noteq> i}\"\n      unfolding thr0\n      apply (rule span_sum)\n      apply simp\n      apply (rule span_mul [where 'a=\"real^'n\", folded scalar_mult_eq_scaleR])+\n      apply (rule span_superset)\n      apply auto\n      done\n    let ?B = \"(\\<chi> k. if k = i then 0 else row k A) :: real ^'n^'n\"\n    have thrb: \"row i ?B = 0\" using iU by (vector row_def)\n    have \"det A = 0\"\n      unfolding det_row_span[OF thr, symmetric] right_minus\n      unfolding det_zero_row[OF thrb] ..\n  }\n  ultimately show ?thesis\n    by blast\nqed\n\ntext \\<open>Cramer's rule.\\<close>\n\nlemma cramer_lemma_transpose:\n  fixes A:: \"real^'n^'n\"\n    and x :: \"real^'n\"\n  shows \"det ((\\<chi> i. if i = k then sum (\\<lambda>i. x$i *s row i A) (UNIV::'n set)\n                             else row i A)::real^'n^'n) = x$k * det A\"\n  (is \"?lhs = ?rhs\")\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  let ?Uk = \"?U - {k}\"\n  have U: \"?U = insert k ?Uk\"\n    by blast\n  have fUk: \"finite ?Uk\"\n    by simp\n  have kUk: \"k \\<notin> ?Uk\"\n    by simp\n  have th00: \"\\<And>k s. x$k *s row k A + s = (x$k - 1) *s row k A + row k A + s\"\n    by (vector field_simps)\n  have th001: \"\\<And>f k . (\\<lambda>x. if x = k then f k else f x) = f\"\n    by auto\n  have \"(\\<chi> i. row i A) = A\" by (vector row_def)\n  then have thd1: \"det (\\<chi> i. row i A) = det A\"\n    by simp\n  have thd0: \"det (\\<chi> i. if i = k then row k A + (\\<Sum>i \\<in> ?Uk. x $ i *s row i A) else row i A) = det A\"\n    apply (rule det_row_span)\n    apply (rule span_sum)\n    apply (rule span_mul [where 'a=\"real^'n\", folded scalar_mult_eq_scaleR])+\n    apply (rule span_superset)\n    apply auto\n    done\n  show \"?lhs = x$k * det A\"\n    apply (subst U)\n    unfolding sum.insert[OF fUk kUk]\n    apply (subst th00)\n    unfolding add.assoc\n    apply (subst det_row_add)\n    unfolding thd0\n    unfolding det_row_mul\n    unfolding th001[of k \"\\<lambda>i. row i A\"]\n    unfolding thd1\n    apply (simp add: field_simps)\n    done\nqed\n\nlemma cramer_lemma:\n  fixes A :: \"real^'n^'n\"\n  shows \"det((\\<chi> i j. if j = k then (A *v x)$i else A$i$j):: real^'n^'n) = x$k * det A\"\nproof -\n  let ?U = \"UNIV :: 'n set\"\n  have *: \"\\<And>c. sum (\\<lambda>i. c i *s row i (transpose A)) ?U = sum (\\<lambda>i. c i *s column i A) ?U\"\n    by (auto simp add: row_transpose intro: sum.cong)\n  show ?thesis\n    unfolding matrix_mult_vsum\n    unfolding cramer_lemma_transpose[of k x \"transpose A\", unfolded det_transpose, symmetric]\n    unfolding *[of \"\\<lambda>i. x$i\"]\n    apply (subst det_transpose[symmetric])\n    apply (rule cong[OF refl[of det]])\n    apply (vector transpose_def column_def row_def)\n    done\nqed\n\nlemma cramer:\n  fixes A ::\"real^'n^'n\"\n  assumes d0: \"det A \\<noteq> 0\"\n  shows \"A *v x = b \\<longleftrightarrow> x = (\\<chi> k. det(\\<chi> i j. if j=k then b$i else A$i$j) / det A)\"\nproof -\n  from d0 obtain B where B: \"A ** B = mat 1\" \"B ** A = mat 1\"\n    unfolding invertible_det_nz[symmetric] invertible_def\n    by blast\n  have \"(A ** B) *v b = b\"\n    by (simp add: B matrix_vector_mul_lid)\n  then have \"A *v (B *v b) = b\"\n    by (simp add: matrix_vector_mul_assoc)\n  then have xe: \"\\<exists>x. A *v x = b\"\n    by blast\n  {\n    fix x\n    assume x: \"A *v x = b\"\n    have \"x = (\\<chi> k. det(\\<chi> i j. if j=k then b$i else A$i$j) / det A)\"\n      unfolding x[symmetric]\n      using d0 by (simp add: vec_eq_iff cramer_lemma field_simps)\n  }\n  with xe show ?thesis\n    by auto\nqed\n\ntext \\<open>Orthogonality of a transformation and matrix.\\<close>\n\ndefinition \"orthogonal_transformation f \\<longleftrightarrow> linear f \\<and> (\\<forall>v w. f v \\<bullet> f w = v \\<bullet> w)\"\n\nlemma orthogonal_transformation:\n  \"orthogonal_transformation f \\<longleftrightarrow> linear f \\<and> (\\<forall>(v::real ^_). norm (f v) = norm v)\"\n  unfolding orthogonal_transformation_def\n  apply auto\n  apply (erule_tac x=v in allE)+\n  apply (simp add: norm_eq_sqrt_inner)\n  apply (simp add: dot_norm  linear_add[symmetric])\n  done\n\ndefinition \"orthogonal_matrix (Q::'a::semiring_1^'n^'n) \\<longleftrightarrow>\n  transpose Q ** Q = mat 1 \\<and> Q ** transpose Q = mat 1\"\n\nlemma orthogonal_matrix: \"orthogonal_matrix (Q:: real ^'n^'n) \\<longleftrightarrow> transpose Q ** Q = mat 1\"\n  by (metis matrix_left_right_inverse orthogonal_matrix_def)\n\nlemma orthogonal_matrix_id: \"orthogonal_matrix (mat 1 :: _^'n^'n)\"\n  by (simp add: orthogonal_matrix_def transpose_mat matrix_mul_lid)\n\nlemma orthogonal_matrix_mul:\n  fixes A :: \"real ^'n^'n\"\n  assumes oA : \"orthogonal_matrix A\"\n    and oB: \"orthogonal_matrix B\"\n  shows \"orthogonal_matrix(A ** B)\"\n  using oA oB\n  unfolding orthogonal_matrix matrix_transpose_mul\n  apply (subst matrix_mul_assoc)\n  apply (subst matrix_mul_assoc[symmetric])\n  apply (simp add: matrix_mul_rid)\n  done\n\nlemma orthogonal_transformation_matrix:\n  fixes f:: \"real^'n \\<Rightarrow> real^'n\"\n  shows \"orthogonal_transformation f \\<longleftrightarrow> linear f \\<and> orthogonal_matrix(matrix f)\"\n  (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof -\n  let ?mf = \"matrix f\"\n  let ?ot = \"orthogonal_transformation f\"\n  let ?U = \"UNIV :: 'n set\"\n  have fU: \"finite ?U\" by simp\n  let ?m1 = \"mat 1 :: real ^'n^'n\"\n  {\n    assume ot: ?ot\n    from ot have lf: \"linear f\" and fd: \"\\<forall>v w. f v \\<bullet> f w = v \\<bullet> w\"\n      unfolding  orthogonal_transformation_def orthogonal_matrix by blast+\n    {\n      fix i j\n      let ?A = \"transpose ?mf ** ?mf\"\n      have th0: \"\\<And>b (x::'a::comm_ring_1). (if b then 1 else 0)*x = (if b then x else 0)\"\n        \"\\<And>b (x::'a::comm_ring_1). x*(if b then 1 else 0) = (if b then x else 0)\"\n        by simp_all\n      from fd[rule_format, of \"axis i 1\" \"axis j 1\",\n        simplified matrix_works[OF lf, symmetric] dot_matrix_vector_mul]\n      have \"?A$i$j = ?m1 $ i $ j\"\n        by (simp add: inner_vec_def matrix_matrix_mult_def columnvector_def rowvector_def\n            th0 sum.delta[OF fU] mat_def axis_def)\n    }\n    then have \"orthogonal_matrix ?mf\"\n      unfolding orthogonal_matrix\n      by vector\n    with lf have ?rhs\n      by blast\n  }\n  moreover\n  {\n    assume lf: \"linear f\" and om: \"orthogonal_matrix ?mf\"\n    from lf om have ?lhs\n      apply (simp only: orthogonal_matrix_def norm_eq orthogonal_transformation)\n      apply (simp only: matrix_works[OF lf, symmetric])\n      apply (subst dot_matrix_vector_mul)\n      apply (simp add: dot_matrix_product matrix_mul_lid)\n      done\n  }\n  ultimately show ?thesis\n    by blast\nqed\n\nlemma det_orthogonal_matrix:\n  fixes Q:: \"'a::linordered_idom^'n^'n\"\n  assumes oQ: \"orthogonal_matrix Q\"\n  shows \"det Q = 1 \\<or> det Q = - 1\"\nproof -\n  have th: \"\\<And>x::'a. x = 1 \\<or> x = - 1 \\<longleftrightarrow> x*x = 1\" (is \"\\<And>x::'a. ?ths x\")\n  proof -\n    fix x:: 'a\n    have th0: \"x * x - 1 = (x - 1) * (x + 1)\"\n      by (simp add: field_simps)\n    have th1: \"\\<And>(x::'a) y. x = - y \\<longleftrightarrow> x + y = 0\"\n      apply (subst eq_iff_diff_eq_0)\n      apply simp\n      done\n    have \"x * x = 1 \\<longleftrightarrow> x * x - 1 = 0\"\n      by simp\n    also have \"\\<dots> \\<longleftrightarrow> x = 1 \\<or> x = - 1\"\n      unfolding th0 th1 by simp\n    finally show \"?ths x\" ..\n  qed\n  from oQ have \"Q ** transpose Q = mat 1\"\n    by (metis orthogonal_matrix_def)\n  then have \"det (Q ** transpose Q) = det (mat 1:: 'a^'n^'n)\"\n    by simp\n  then have \"det Q * det Q = 1\"\n    by (simp add: det_mul det_I det_transpose)\n  then show ?thesis unfolding th .\nqed\n\ntext \\<open>Linearity of scaling, and hence isometry, that preserves origin.\\<close>\n\nlemma scaling_linear:\n  fixes f :: \"real ^'n \\<Rightarrow> real ^'n\"\n  assumes f0: \"f 0 = 0\"\n    and fd: \"\\<forall>x y. dist (f x) (f y) = c * dist x y\"\n  shows \"linear f\"\nproof -\n  {\n    fix v w\n    {\n      fix x\n      note fd[rule_format, of x 0, unfolded dist_norm f0 diff_0_right]\n    }\n    note th0 = this\n    have \"f v \\<bullet> f w = c\\<^sup>2 * (v \\<bullet> w)\"\n      unfolding dot_norm_neg dist_norm[symmetric]\n      unfolding th0 fd[rule_format] by (simp add: power2_eq_square field_simps)}\n  note fc = this\n  show ?thesis\n    unfolding linear_iff vector_eq[where 'a=\"real^'n\"] scalar_mult_eq_scaleR\n    by (simp add: inner_add fc field_simps)\nqed\n\nlemma isometry_linear:\n  \"f (0:: real^'n) = (0:: real^'n) \\<Longrightarrow> \\<forall>x y. dist(f x) (f y) = dist x y \\<Longrightarrow> linear f\"\n  by (rule scaling_linear[where c=1]) simp_all\n\ntext \\<open>Hence another formulation of orthogonal transformation.\\<close>\n\nlemma orthogonal_transformation_isometry:\n  \"orthogonal_transformation f \\<longleftrightarrow> f(0::real^'n) = (0::real^'n) \\<and> (\\<forall>x y. dist(f x) (f y) = dist x y)\"\n  unfolding orthogonal_transformation\n  apply (rule iffI)\n  apply clarify\n  apply (clarsimp simp add: linear_0 linear_diff[symmetric] dist_norm)\n  apply (rule conjI)\n  apply (rule isometry_linear)\n  apply simp\n  apply simp\n  apply clarify\n  apply (erule_tac x=v in allE)\n  apply (erule_tac x=0 in allE)\n  apply (simp add: dist_norm)\n  done\n\ntext \\<open>Can extend an isometry from unit sphere.\\<close>\n\nlemma isometry_sphere_extend:\n  fixes f:: \"real ^'n \\<Rightarrow> real ^'n\"\n  assumes f1: \"\\<forall>x. norm x = 1 \\<longrightarrow> norm (f x) = 1\"\n    and fd1: \"\\<forall> x y. norm x = 1 \\<longrightarrow> norm y = 1 \\<longrightarrow> dist (f x) (f y) = dist x y\"\n  shows \"\\<exists>g. orthogonal_transformation g \\<and> (\\<forall>x. norm x = 1 \\<longrightarrow> g x = f x)\"\nproof -\n  {\n    fix x y x' y' x0 y0 x0' y0' :: \"real ^'n\"\n    assume H:\n      \"x = norm x *\\<^sub>R x0\"\n      \"y = norm y *\\<^sub>R y0\"\n      \"x' = norm x *\\<^sub>R x0'\" \"y' = norm y *\\<^sub>R y0'\"\n      \"norm x0 = 1\" \"norm x0' = 1\" \"norm y0 = 1\" \"norm y0' = 1\"\n      \"norm(x0' - y0') = norm(x0 - y0)\"\n    then have *: \"x0 \\<bullet> y0 = x0' \\<bullet> y0' + y0' \\<bullet> x0' - y0 \\<bullet> x0 \"\n      by (simp add: norm_eq norm_eq_1 inner_add inner_diff)\n    have \"norm(x' - y') = norm(x - y)\"\n      apply (subst H(1))\n      apply (subst H(2))\n      apply (subst H(3))\n      apply (subst H(4))\n      using H(5-9)\n      apply (simp add: norm_eq norm_eq_1)\n      apply (simp add: inner_diff scalar_mult_eq_scaleR)\n      unfolding *\n      apply (simp add: field_simps)\n      done\n  }\n  note th0 = this\n  let ?g = \"\\<lambda>x. if x = 0 then 0 else norm x *\\<^sub>R f (inverse (norm x) *\\<^sub>R x)\"\n  {\n    fix x:: \"real ^'n\"\n    assume nx: \"norm x = 1\"\n    have \"?g x = f x\"\n      using nx by auto\n  }\n  then have thfg: \"\\<forall>x. norm x = 1 \\<longrightarrow> ?g x = f x\"\n    by blast\n  have g0: \"?g 0 = 0\"\n    by simp\n  {\n    fix x y :: \"real ^'n\"\n    {\n      assume \"x = 0\" \"y = 0\"\n      then have \"dist (?g x) (?g y) = dist x y\"\n        by simp\n    }\n    moreover\n    {\n      assume \"x = 0\" \"y \\<noteq> 0\"\n      then have \"dist (?g x) (?g y) = dist x y\"\n        apply (simp add: dist_norm)\n        apply (rule f1[rule_format])\n        apply (simp add: field_simps)\n        done\n    }\n    moreover\n    {\n      assume \"x \\<noteq> 0\" \"y = 0\"\n      then have \"dist (?g x) (?g y) = dist x y\"\n        apply (simp add: dist_norm)\n        apply (rule f1[rule_format])\n        apply (simp add: field_simps)\n        done\n    }\n    moreover\n    {\n      assume z: \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n      have th00:\n        \"x = norm x *\\<^sub>R (inverse (norm x) *\\<^sub>R x)\"\n        \"y = norm y *\\<^sub>R (inverse (norm y) *\\<^sub>R y)\"\n        \"norm x *\\<^sub>R f ((inverse (norm x) *\\<^sub>R x)) = norm x *\\<^sub>R f (inverse (norm x) *\\<^sub>R x)\"\n        \"norm y *\\<^sub>R f (inverse (norm y) *\\<^sub>R y) = norm y *\\<^sub>R f (inverse (norm y) *\\<^sub>R y)\"\n        \"norm (inverse (norm x) *\\<^sub>R x) = 1\"\n        \"norm (f (inverse (norm x) *\\<^sub>R x)) = 1\"\n        \"norm (inverse (norm y) *\\<^sub>R y) = 1\"\n        \"norm (f (inverse (norm y) *\\<^sub>R y)) = 1\"\n        \"norm (f (inverse (norm x) *\\<^sub>R x) - f (inverse (norm y) *\\<^sub>R y)) =\n          norm (inverse (norm x) *\\<^sub>R x - inverse (norm y) *\\<^sub>R y)\"\n        using z\n        by (auto simp add: field_simps intro: f1[rule_format] fd1[rule_format, unfolded dist_norm])\n      from z th0[OF th00] have \"dist (?g x) (?g y) = dist x y\"\n        by (simp add: dist_norm)\n    }\n    ultimately have \"dist (?g x) (?g y) = dist x y\"\n      by blast\n  }\n  note thd = this\n    show ?thesis\n    apply (rule exI[where x= ?g])\n    unfolding orthogonal_transformation_isometry\n    using g0 thfg thd\n    apply metis\n    done\nqed\n\ntext \\<open>Rotation, reflection, rotoinversion.\\<close>\n\ndefinition \"rotation_matrix Q \\<longleftrightarrow> orthogonal_matrix Q \\<and> det Q = 1\"\ndefinition \"rotoinversion_matrix Q \\<longleftrightarrow> orthogonal_matrix Q \\<and> det Q = - 1\"\n\nlemma orthogonal_rotation_or_rotoinversion:\n  fixes Q :: \"'a::linordered_idom^'n^'n\"\n  shows \" orthogonal_matrix Q \\<longleftrightarrow> rotation_matrix Q \\<or> rotoinversion_matrix Q\"\n  by (metis rotoinversion_matrix_def rotation_matrix_def det_orthogonal_matrix)\n\ntext \\<open>Explicit formulas for low dimensions.\\<close>\n\nlemma prod_neutral_const: \"prod f {(1::nat)..1} = f 1\"\n  by simp\n\nlemma prod_2: \"prod f {(1::nat)..2} = f 1 * f 2\"\n  by (simp add: eval_nat_numeral atLeastAtMostSuc_conv mult.commute)\n\nlemma prod_3: \"prod f {(1::nat)..3} = f 1 * f 2 * f 3\"\n  by (simp add: eval_nat_numeral atLeastAtMostSuc_conv mult.commute)\n\nlemma det_1: \"det (A::'a::comm_ring_1^1^1) = A$1$1\"\n  by (simp add: det_def of_nat_Suc sign_id)\n\nlemma det_2: \"det (A::'a::comm_ring_1^2^2) = A$1$1 * A$2$2 - A$1$2 * A$2$1\"\nproof -\n  have f12: \"finite {2::2}\" \"1 \\<notin> {2::2}\" by auto\n  show ?thesis\n    unfolding det_def UNIV_2\n    unfolding sum_over_permutations_insert[OF f12]\n    unfolding permutes_sing\n    by (simp add: sign_swap_id sign_id swap_id_eq)\nqed\n\nlemma det_3:\n  \"det (A::'a::comm_ring_1^3^3) =\n    A$1$1 * A$2$2 * A$3$3 +\n    A$1$2 * A$2$3 * A$3$1 +\n    A$1$3 * A$2$1 * A$3$2 -\n    A$1$1 * A$2$3 * A$3$2 -\n    A$1$2 * A$2$1 * A$3$3 -\n    A$1$3 * A$2$2 * A$3$1\"\nproof -\n  have f123: \"finite {2::3, 3}\" \"1 \\<notin> {2::3, 3}\"\n    by auto\n  have f23: \"finite {3::3}\" \"2 \\<notin> {3::3}\"\n    by auto\n\n  show ?thesis\n    unfolding det_def UNIV_3\n    unfolding sum_over_permutations_insert[OF f123]\n    unfolding sum_over_permutations_insert[OF f23]\n    unfolding permutes_sing\n    by (simp add: sign_swap_id permutation_swap_id sign_compose sign_id swap_id_eq)\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Analysis/Determinants.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8615382094310357, "lm_q1q2_score": 0.763005359370418}}
{"text": "(*  Title:      HOL/Fun.thy\n    Author:     Tobias Nipkow, Cambridge University Computer Laboratory\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   1994, 2012\n*)\n\nsection {* Notions about functions *}\n\ntheory Fun\nimports Set\nkeywords \"functor\" :: thy_goal\nbegin\n\nlemma apply_inverse:\n  \"f x = u \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> g (f x) = x) \\<Longrightarrow> P x \\<Longrightarrow> x = g u\"\n  by auto\n\n\nsubsection {* The Identity Function @{text id} *}\n\ndefinition id :: \"'a \\<Rightarrow> 'a\" where\n  \"id = (\\<lambda>x. x)\"\n\nlemma id_apply [simp]: \"id x = x\"\n  by (simp add: id_def)\n\nlemma image_id [simp]: \"image id = id\"\n  by (simp add: id_def fun_eq_iff)\n\nlemma vimage_id [simp]: \"vimage id = id\"\n  by (simp add: id_def fun_eq_iff)\n\ncode_printing\n  constant id \\<rightharpoonup> (Haskell) \"id\"\n\n\nsubsection {* The Composition Operator @{text \"f \\<circ> g\"} *}\n\ndefinition comp :: \"('b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'c\" (infixl \"o\" 55) where\n  \"f o g = (\\<lambda>x. f (g x))\"\n\nnotation (xsymbols)\n  comp  (infixl \"\\<circ>\" 55)\n\nnotation (HTML output)\n  comp  (infixl \"\\<circ>\" 55)\n\nlemma comp_apply [simp]: \"(f o g) x = f (g x)\"\n  by (simp add: comp_def)\n\nlemma comp_assoc: \"(f o g) o h = f o (g o h)\"\n  by (simp add: fun_eq_iff)\n\nlemma id_comp [simp]: \"id o g = g\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_id [simp]: \"f o id = f\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_eq_dest:\n  \"a o b = c o d \\<Longrightarrow> a (b v) = c (d v)\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_eq_elim:\n  \"a o b = c o d \\<Longrightarrow> ((\\<And>v. a (b v) = c (d v)) \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by (simp add: fun_eq_iff) \n\nlemma comp_eq_dest_lhs: \"a o b = c \\<Longrightarrow> a (b v) = c v\"\n  by clarsimp\n\nlemma comp_eq_id_dest: \"a o b = id o c \\<Longrightarrow> a (b v) = c v\"\n  by clarsimp\n\nlemma image_comp:\n  \"f ` (g ` r) = (f o g) ` r\"\n  by auto\n\nlemma vimage_comp:\n  \"f -` (g -` x) = (g \\<circ> f) -` x\"\n  by auto\n\ncode_printing\n  constant comp \\<rightharpoonup> (SML) infixl 5 \"o\" and (Haskell) infixr 9 \".\"\n\n\nsubsection {* The Forward Composition Operator @{text fcomp} *}\n\ndefinition fcomp :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'c) \\<Rightarrow> 'a \\<Rightarrow> 'c\" (infixl \"\\<circ>>\" 60) where\n  \"f \\<circ>> g = (\\<lambda>x. g (f x))\"\n\nlemma fcomp_apply [simp]:  \"(f \\<circ>> g) x = g (f x)\"\n  by (simp add: fcomp_def)\n\nlemma fcomp_assoc: \"(f \\<circ>> g) \\<circ>> h = f \\<circ>> (g \\<circ>> h)\"\n  by (simp add: fcomp_def)\n\nlemma id_fcomp [simp]: \"id \\<circ>> g = g\"\n  by (simp add: fcomp_def)\n\nlemma fcomp_id [simp]: \"f \\<circ>> id = f\"\n  by (simp add: fcomp_def)\n\ncode_printing\n  constant fcomp \\<rightharpoonup> (Eval) infixl 1 \"#>\"\n\nno_notation fcomp (infixl \"\\<circ>>\" 60)\n\n\nsubsection {* Mapping functions *}\n\ndefinition map_fun :: \"('c \\<Rightarrow> 'a) \\<Rightarrow> ('b \\<Rightarrow> 'd) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'c \\<Rightarrow> 'd\" where\n  \"map_fun f g h = g \\<circ> h \\<circ> f\"\n\nlemma map_fun_apply [simp]:\n  \"map_fun f g h x = g (h (f x))\"\n  by (simp add: map_fun_def)\n\n\nsubsection {* Injectivity and Bijectivity *}\n\ndefinition inj_on :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where -- \"injective\"\n  \"inj_on f A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. f x = f y \\<longrightarrow> x = y)\"\n\ndefinition bij_betw :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> bool\" where -- \"bijective\"\n  \"bij_betw f A B \\<longleftrightarrow> inj_on f A \\<and> f ` A = B\"\n\ntext{*A common special case: functions injective, surjective or bijective over\nthe entire domain type.*}\n\nabbreviation\n  \"inj f \\<equiv> inj_on f UNIV\"\n\nabbreviation surj :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\" where -- \"surjective\"\n  \"surj f \\<equiv> (range f = UNIV)\"\n\nabbreviation\n  \"bij f \\<equiv> bij_betw f UNIV UNIV\"\n\ntext{* The negated case: *}\ntranslations\n\"\\<not> CONST surj f\" <= \"CONST range f \\<noteq> CONST UNIV\"\n\nlemma injI:\n  assumes \"\\<And>x y. f x = f y \\<Longrightarrow> x = y\"\n  shows \"inj f\"\n  using assms unfolding inj_on_def by auto\n\ntheorem range_ex1_eq: \"inj f \\<Longrightarrow> b : range f = (EX! x. b = f x)\"\n  by (unfold inj_on_def, blast)\n\nlemma injD: \"[| inj(f); f(x) = f(y) |] ==> x=y\"\nby (simp add: inj_on_def)\n\nlemma inj_on_eq_iff: \"inj_on f A ==> x:A ==> y:A ==> (f(x) = f(y)) = (x=y)\"\nby (force simp add: inj_on_def)\n\nlemma inj_on_cong:\n  \"(\\<And> a. a : A \\<Longrightarrow> f a = g a) \\<Longrightarrow> inj_on f A = inj_on g A\"\nunfolding inj_on_def by auto\n\nlemma inj_on_strict_subset:\n  \"inj_on f B \\<Longrightarrow> A \\<subset> B \\<Longrightarrow> f ` A \\<subset> f ` B\"\n  unfolding inj_on_def by blast\n\nlemma inj_comp:\n  \"inj f \\<Longrightarrow> inj g \\<Longrightarrow> inj (f \\<circ> g)\"\n  by (simp add: inj_on_def)\n\nlemma inj_fun: \"inj f \\<Longrightarrow> inj (\\<lambda>x y. f x)\"\n  by (simp add: inj_on_def fun_eq_iff)\n\nlemma inj_eq: \"inj f ==> (f(x) = f(y)) = (x=y)\"\nby (simp add: inj_on_eq_iff)\n\nlemma inj_on_id[simp]: \"inj_on id A\"\n  by (simp add: inj_on_def)\n\nlemma inj_on_id2[simp]: \"inj_on (%x. x) A\"\nby (simp add: inj_on_def)\n\nlemma inj_on_Int: \"inj_on f A \\<or> inj_on f B \\<Longrightarrow> inj_on f (A \\<inter> B)\"\nunfolding inj_on_def by blast\n\nlemma surj_id: \"surj id\"\nby simp\n\nlemma bij_id[simp]: \"bij id\"\nby (simp add: bij_betw_def)\n\nlemma inj_onI:\n    \"(!! x y. [|  x:A;  y:A;  f(x) = f(y) |] ==> x=y) ==> inj_on f A\"\nby (simp add: inj_on_def)\n\nlemma inj_on_inverseI: \"(!!x. x:A ==> g(f(x)) = x) ==> inj_on f A\"\nby (auto dest:  arg_cong [of concl: g] simp add: inj_on_def)\n\nlemma inj_onD: \"[| inj_on f A;  f(x)=f(y);  x:A;  y:A |] ==> x=y\"\nby (unfold inj_on_def, blast)\n\nlemma inj_on_iff: \"[| inj_on f A;  x:A;  y:A |] ==> (f(x)=f(y)) = (x=y)\"\n  by (fact inj_on_eq_iff)\n\nlemma comp_inj_on:\n     \"[| inj_on f A;  inj_on g (f`A) |] ==> inj_on (g o f) A\"\nby (simp add: comp_def inj_on_def)\n\nlemma inj_on_imageI: \"inj_on (g o f) A \\<Longrightarrow> inj_on g (f ` A)\"\n  by (simp add: inj_on_def) blast\n\nlemma inj_on_image_iff: \"\\<lbrakk> ALL x:A. ALL y:A. (g(f x) = g(f y)) = (g x = g y);\n  inj_on f A \\<rbrakk> \\<Longrightarrow> inj_on g (f ` A) = inj_on g A\"\napply(unfold inj_on_def)\napply blast\ndone\n\nlemma inj_on_contraD: \"[| inj_on f A;  ~x=y;  x:A;  y:A |] ==> ~ f(x)=f(y)\"\nby (unfold inj_on_def, blast)\n\nlemma inj_singleton: \"inj (%s. {s})\"\nby (simp add: inj_on_def)\n\nlemma inj_on_empty[iff]: \"inj_on f {}\"\nby(simp add: inj_on_def)\n\nlemma subset_inj_on: \"[| inj_on f B; A <= B |] ==> inj_on f A\"\nby (unfold inj_on_def, blast)\n\nlemma inj_on_Un:\n \"inj_on f (A Un B) =\n  (inj_on f A & inj_on f B & f`(A-B) Int f`(B-A) = {})\"\napply(unfold inj_on_def)\napply (blast intro:sym)\ndone\n\nlemma inj_on_insert[iff]:\n  \"inj_on f (insert a A) = (inj_on f A & f a ~: f`(A-{a}))\"\napply(unfold inj_on_def)\napply (blast intro:sym)\ndone\n\nlemma inj_on_diff: \"inj_on f A ==> inj_on f (A-B)\"\napply(unfold inj_on_def)\napply (blast)\ndone\n\nlemma comp_inj_on_iff:\n  \"inj_on f A \\<Longrightarrow> inj_on f' (f ` A) \\<longleftrightarrow> inj_on (f' o f) A\"\nby(auto simp add: comp_inj_on inj_on_def)\n\nlemma inj_on_imageI2:\n  \"inj_on (f' o f) A \\<Longrightarrow> inj_on f A\"\nby(auto simp add: comp_inj_on inj_on_def)\n\nlemma inj_img_insertE:\n  assumes \"inj_on f A\"\n  assumes \"x \\<notin> B\" and \"insert x B = f ` A\"\n  obtains x' A' where \"x' \\<notin> A'\" and \"A = insert x' A'\"\n    and \"x = f x'\" and \"B = f ` A'\"\nproof -\n  from assms have \"x \\<in> f ` A\" by auto\n  then obtain x' where *: \"x' \\<in> A\" \"x = f x'\" by auto\n  then have \"A = insert x' (A - {x'})\" by auto\n  with assms * have \"B = f ` (A - {x'})\"\n    by (auto dest: inj_on_contraD)\n  have \"x' \\<notin> A - {x'}\" by simp\n  from `x' \\<notin> A - {x'}` `A = insert x' (A - {x'})` `x = f x'` `B = image f (A - {x'})`\n  show ?thesis ..\nqed\n\nlemma linorder_injI:\n  assumes hyp: \"\\<And>x y. x < (y::'a::linorder) \\<Longrightarrow> f x \\<noteq> f y\"\n  shows \"inj f\"\n  -- {* Courtesy of Stephan Merz *}\nproof (rule inj_onI)\n  fix x y\n  assume f_eq: \"f x = f y\"\n  show \"x = y\" by (rule linorder_cases) (auto dest: hyp simp: f_eq)\nqed\n\nlemma surj_def: \"surj f \\<longleftrightarrow> (\\<forall>y. \\<exists>x. y = f x)\"\n  by auto\n\nlemma surjI: assumes *: \"\\<And> x. g (f x) = x\" shows \"surj g\"\n  using *[symmetric] by auto\n\nlemma surjD: \"surj f \\<Longrightarrow> \\<exists>x. y = f x\"\n  by (simp add: surj_def)\n\nlemma surjE: \"surj f \\<Longrightarrow> (\\<And>x. y = f x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (simp add: surj_def, blast)\n\nlemma comp_surj: \"[| surj f;  surj g |] ==> surj (g o f)\"\napply (simp add: comp_def surj_def, clarify)\napply (drule_tac x = y in spec, clarify)\napply (drule_tac x = x in spec, blast)\ndone\n\nlemma bij_betw_imageI:\n  \"\\<lbrakk> inj_on f A; f ` A = B \\<rbrakk> \\<Longrightarrow> bij_betw f A B\"\nunfolding bij_betw_def by clarify\n\nlemma bij_betw_imp_surj_on: \"bij_betw f A B \\<Longrightarrow> f ` A = B\"\n  unfolding bij_betw_def by clarify\n\nlemma bij_betw_imp_surj: \"bij_betw f A UNIV \\<Longrightarrow> surj f\"\n  unfolding bij_betw_def by auto\n\nlemma bij_betw_empty1:\n  assumes \"bij_betw f {} A\"\n  shows \"A = {}\"\nusing assms unfolding bij_betw_def by blast\n\nlemma bij_betw_empty2:\n  assumes \"bij_betw f A {}\"\n  shows \"A = {}\"\nusing assms unfolding bij_betw_def by blast\n\nlemma inj_on_imp_bij_betw:\n  \"inj_on f A \\<Longrightarrow> bij_betw f A (f ` A)\"\nunfolding bij_betw_def by simp\n\nlemma bij_def: \"bij f \\<longleftrightarrow> inj f \\<and> surj f\"\n  unfolding bij_betw_def ..\n\nlemma bijI: \"[| inj f; surj f |] ==> bij f\"\nby (simp add: bij_def)\n\nlemma bij_is_inj: \"bij f ==> inj f\"\nby (simp add: bij_def)\n\nlemma bij_is_surj: \"bij f ==> surj f\"\nby (simp add: bij_def)\n\nlemma bij_betw_imp_inj_on: \"bij_betw f A B \\<Longrightarrow> inj_on f A\"\nby (simp add: bij_betw_def)\n\nlemma bij_betw_trans:\n  \"bij_betw f A B \\<Longrightarrow> bij_betw g B C \\<Longrightarrow> bij_betw (g o f) A C\"\nby(auto simp add:bij_betw_def comp_inj_on)\n\nlemma bij_comp: \"bij f \\<Longrightarrow> bij g \\<Longrightarrow> bij (g o f)\"\n  by (rule bij_betw_trans)\n\nlemma bij_betw_comp_iff:\n  \"bij_betw f A A' \\<Longrightarrow> bij_betw f' A' A'' \\<longleftrightarrow> bij_betw (f' o f) A A''\"\nby(auto simp add: bij_betw_def inj_on_def)\n\nlemma bij_betw_comp_iff2:\n  assumes BIJ: \"bij_betw f' A' A''\" and IM: \"f ` A \\<le> A'\"\n  shows \"bij_betw f A A' \\<longleftrightarrow> bij_betw (f' o f) A A''\"\nusing assms\nproof(auto simp add: bij_betw_comp_iff)\n  assume *: \"bij_betw (f' \\<circ> f) A A''\"\n  thus \"bij_betw f A A'\"\n  using IM\n  proof(auto simp add: bij_betw_def)\n    assume \"inj_on (f' \\<circ> f) A\"\n    thus \"inj_on f A\" using inj_on_imageI2 by blast\n  next\n    fix a' assume **: \"a' \\<in> A'\"\n    hence \"f' a' \\<in> A''\" using BIJ unfolding bij_betw_def by auto\n    then obtain a where 1: \"a \\<in> A \\<and> f'(f a) = f' a'\" using *\n    unfolding bij_betw_def by force\n    hence \"f a \\<in> A'\" using IM by auto\n    hence \"f a = a'\" using BIJ ** 1 unfolding bij_betw_def inj_on_def by auto\n    thus \"a' \\<in> f ` A\" using 1 by auto\n  qed\nqed\n\nlemma bij_betw_inv: assumes \"bij_betw f A B\" shows \"EX g. bij_betw g B A\"\nproof -\n  have i: \"inj_on f A\" and s: \"f ` A = B\"\n    using assms by(auto simp:bij_betw_def)\n  let ?P = \"%b a. a:A \\<and> f a = b\" let ?g = \"%b. The (?P b)\"\n  { fix a b assume P: \"?P b a\"\n    hence ex1: \"\\<exists>a. ?P b a\" using s by blast\n    hence uex1: \"\\<exists>!a. ?P b a\" by(blast dest:inj_onD[OF i])\n    hence \" ?g b = a\" using the1_equality[OF uex1, OF P] P by simp\n  } note g = this\n  have \"inj_on ?g B\"\n  proof(rule inj_onI)\n    fix x y assume \"x:B\" \"y:B\" \"?g x = ?g y\"\n    from s `x:B` obtain a1 where a1: \"?P x a1\" by blast\n    from s `y:B` obtain a2 where a2: \"?P y a2\" by blast\n    from g[OF a1] a1 g[OF a2] a2 `?g x = ?g y` show \"x=y\" by simp\n  qed\n  moreover have \"?g ` B = A\"\n  proof(auto simp: image_def)\n    fix b assume \"b:B\"\n    with s obtain a where P: \"?P b a\" by blast\n    thus \"?g b \\<in> A\" using g[OF P] by auto\n  next\n    fix a assume \"a:A\"\n    then obtain b where P: \"?P b a\" using s by blast\n    then have \"b:B\" using s by blast\n    with g[OF P] show \"\\<exists>b\\<in>B. a = ?g b\" by blast\n  qed\n  ultimately show ?thesis by(auto simp:bij_betw_def)\nqed\n\nlemma bij_betw_cong:\n  \"(\\<And> a. a \\<in> A \\<Longrightarrow> f a = g a) \\<Longrightarrow> bij_betw f A A' = bij_betw g A A'\"\nunfolding bij_betw_def inj_on_def by force\n\nlemma bij_betw_id[intro, simp]:\n  \"bij_betw id A A\"\nunfolding bij_betw_def id_def by auto\n\nlemma bij_betw_id_iff:\n  \"bij_betw id A B \\<longleftrightarrow> A = B\"\nby(auto simp add: bij_betw_def)\n\nlemma bij_betw_combine:\n  assumes \"bij_betw f A B\" \"bij_betw f C D\" \"B \\<inter> D = {}\"\n  shows \"bij_betw f (A \\<union> C) (B \\<union> D)\"\n  using assms unfolding bij_betw_def inj_on_Un image_Un by auto\n\nlemma bij_betw_subset:\n  assumes BIJ: \"bij_betw f A A'\" and\n          SUB: \"B \\<le> A\" and IM: \"f ` B = B'\"\n  shows \"bij_betw f B B'\"\nusing assms\nby(unfold bij_betw_def inj_on_def, auto simp add: inj_on_def)\n\nlemma bij_pointE:\n  assumes \"bij f\"\n  obtains x where \"y = f x\" and \"\\<And>x'. y = f x' \\<Longrightarrow> x' = x\"\nproof -\n  from assms have \"inj f\" by (rule bij_is_inj)\n  moreover from assms have \"surj f\" by (rule bij_is_surj)\n  then have \"y \\<in> range f\" by simp\n  ultimately have \"\\<exists>!x. y = f x\" by (simp add: range_ex1_eq)\n  with that show thesis by blast\nqed\n\nlemma surj_image_vimage_eq: \"surj f ==> f ` (f -` A) = A\"\nby simp\n\nlemma surj_vimage_empty:\n  assumes \"surj f\" shows \"f -` A = {} \\<longleftrightarrow> A = {}\"\n  using surj_image_vimage_eq[OF `surj f`, of A]\n  by (intro iffI) fastforce+\n\nlemma inj_vimage_image_eq: \"inj f ==> f -` (f ` A) = A\"\nby (simp add: inj_on_def, blast)\n\nlemma vimage_subsetD: \"surj f ==> f -` B <= A ==> B <= f ` A\"\nby (blast intro: sym)\n\nlemma vimage_subsetI: \"inj f ==> B <= f ` A ==> f -` B <= A\"\nby (unfold inj_on_def, blast)\n\nlemma vimage_subset_eq: \"bij f ==> (f -` B <= A) = (B <= f ` A)\"\napply (unfold bij_def)\napply (blast del: subsetI intro: vimage_subsetI vimage_subsetD)\ndone\n\nlemma inj_on_image_eq_iff: \"\\<lbrakk> inj_on f C; A \\<subseteq> C; B \\<subseteq> C \\<rbrakk> \\<Longrightarrow> f ` A = f ` B \\<longleftrightarrow> A = B\"\nby(fastforce simp add: inj_on_def)\n\nlemma inj_on_Un_image_eq_iff: \"inj_on f (A \\<union> B) \\<Longrightarrow> f ` A = f ` B \\<longleftrightarrow> A = B\"\nby(erule inj_on_image_eq_iff) simp_all\n\nlemma inj_on_image_Int:\n   \"[| inj_on f C;  A<=C;  B<=C |] ==> f`(A Int B) = f`A Int f`B\"\napply (simp add: inj_on_def, blast)\ndone\n\nlemma inj_on_image_set_diff:\n   \"[| inj_on f C;  A<=C;  B<=C |] ==> f`(A-B) = f`A - f`B\"\napply (simp add: inj_on_def, blast)\ndone\n\nlemma image_Int: \"inj f ==> f`(A Int B) = f`A Int f`B\"\nby (simp add: inj_on_def, blast)\n\nlemma image_set_diff: \"inj f ==> f`(A-B) = f`A - f`B\"\nby (simp add: inj_on_def, blast)\n\nlemma inj_image_mem_iff: \"inj f ==> (f a : f`A) = (a : A)\"\nby (blast dest: injD)\n\nlemma inj_image_subset_iff: \"inj f ==> (f`A <= f`B) = (A<=B)\"\nby (simp add: inj_on_def, blast)\n\nlemma inj_image_eq_iff: \"inj f ==> (f`A = f`B) = (A = B)\"\nby (blast dest: injD)\n\nlemma surj_Compl_image_subset: \"surj f ==> -(f`A) <= f`(-A)\"\nby auto\n\nlemma inj_image_Compl_subset: \"inj f ==> f`(-A) <= -(f`A)\"\nby (auto simp add: inj_on_def)\n\nlemma bij_image_Compl_eq: \"bij f ==> f`(-A) = -(f`A)\"\napply (simp add: bij_def)\napply (rule equalityI)\napply (simp_all (no_asm_simp) add: inj_image_Compl_subset surj_Compl_image_subset)\ndone\n\nlemma inj_vimage_singleton: \"inj f \\<Longrightarrow> f -` {a} \\<subseteq> {THE x. f x = a}\"\n  -- {* The inverse image of a singleton under an injective function\n         is included in a singleton. *}\n  apply (auto simp add: inj_on_def)\n  apply (blast intro: the_equality [symmetric])\n  done\n\nlemma inj_on_vimage_singleton:\n  \"inj_on f A \\<Longrightarrow> f -` {a} \\<inter> A \\<subseteq> {THE x. x \\<in> A \\<and> f x = a}\"\n  by (auto simp add: inj_on_def intro: the_equality [symmetric])\n\nlemma (in ordered_ab_group_add) inj_uminus[simp, intro]: \"inj_on uminus A\"\n  by (auto intro!: inj_onI)\n\nlemma (in linorder) strict_mono_imp_inj_on: \"strict_mono f \\<Longrightarrow> inj_on f A\"\n  by (auto intro!: inj_onI dest: strict_mono_eq)\n\nlemma bij_betw_byWitness:\nassumes LEFT: \"\\<forall>a \\<in> A. f'(f a) = a\" and\n        RIGHT: \"\\<forall>a' \\<in> A'. f(f' a') = a'\" and\n        IM1: \"f ` A \\<le> A'\" and IM2: \"f' ` A' \\<le> A\"\nshows \"bij_betw f A A'\"\nusing assms\nproof(unfold bij_betw_def inj_on_def, safe)\n  fix a b assume *: \"a \\<in> A\" \"b \\<in> A\" and **: \"f a = f b\"\n  have \"a = f'(f a) \\<and> b = f'(f b)\" using * LEFT by simp\n  with ** show \"a = b\" by simp\nnext\n  fix a' assume *: \"a' \\<in> A'\"\n  hence \"f' a' \\<in> A\" using IM2 by blast\n  moreover\n  have \"a' = f(f' a')\" using * RIGHT by simp\n  ultimately show \"a' \\<in> f ` A\" by blast\nqed\n\ncorollary notIn_Un_bij_betw:\nassumes NIN: \"b \\<notin> A\" and NIN': \"f b \\<notin> A'\" and\n       BIJ: \"bij_betw f A A'\"\nshows \"bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\nproof-\n  have \"bij_betw f {b} {f b}\"\n  unfolding bij_betw_def inj_on_def by simp\n  with assms show ?thesis\n  using bij_betw_combine[of f A A' \"{b}\" \"{f b}\"] by blast\nqed\n\nlemma notIn_Un_bij_betw3:\nassumes NIN: \"b \\<notin> A\" and NIN': \"f b \\<notin> A'\"\nshows \"bij_betw f A A' = bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\nproof\n  assume \"bij_betw f A A'\"\n  thus \"bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\n  using assms notIn_Un_bij_betw[of b A f A'] by blast\nnext\n  assume *: \"bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\n  have \"f ` A = A'\"\n  proof(auto)\n    fix a assume **: \"a \\<in> A\"\n    hence \"f a \\<in> A' \\<union> {f b}\" using * unfolding bij_betw_def by blast\n    moreover\n    {assume \"f a = f b\"\n     hence \"a = b\" using * ** unfolding bij_betw_def inj_on_def by blast\n     with NIN ** have False by blast\n    }\n    ultimately show \"f a \\<in> A'\" by blast\n  next\n    fix a' assume **: \"a' \\<in> A'\"\n    hence \"a' \\<in> f`(A \\<union> {b})\"\n    using * by (auto simp add: bij_betw_def)\n    then obtain a where 1: \"a \\<in> A \\<union> {b} \\<and> f a = a'\" by blast\n    moreover\n    {assume \"a = b\" with 1 ** NIN' have False by blast\n    }\n    ultimately have \"a \\<in> A\" by blast\n    with 1 show \"a' \\<in> f ` A\" by blast\n  qed\n  thus \"bij_betw f A A'\" using * bij_betw_subset[of f \"A \\<union> {b}\" _ A] by blast\nqed\n\n\nsubsection{*Function Updating*}\n\ndefinition fun_upd :: \"('a => 'b) => 'a => 'b => ('a => 'b)\" where\n  \"fun_upd f a b == % x. if x=a then b else f x\"\n\nnonterminal updbinds and updbind\n\nsyntax\n  \"_updbind\" :: \"['a, 'a] => updbind\"             (\"(2_ :=/ _)\")\n  \"\"         :: \"updbind => updbinds\"             (\"_\")\n  \"_updbinds\":: \"[updbind, updbinds] => updbinds\" (\"_,/ _\")\n  \"_Update\"  :: \"['a, updbinds] => 'a\"            (\"_/'((_)')\" [1000, 0] 900)\n\ntranslations\n  \"_Update f (_updbinds b bs)\" == \"_Update (_Update f b) bs\"\n  \"f(x:=y)\" == \"CONST fun_upd f x y\"\n\n(* Hint: to define the sum of two functions (or maps), use case_sum.\n         A nice infix syntax could be defined by\nnotation\n  case_sum  (infixr \"'(+')\"80)\n*)\n\nlemma fun_upd_idem_iff: \"(f(x:=y) = f) = (f x = y)\"\napply (simp add: fun_upd_def, safe)\napply (erule subst)\napply (rule_tac [2] ext, auto)\ndone\n\nlemma fun_upd_idem: \"f x = y ==> f(x:=y) = f\"\n  by (simp only: fun_upd_idem_iff)\n\nlemma fun_upd_triv [iff]: \"f(x := f x) = f\"\n  by (simp only: fun_upd_idem)\n\nlemma fun_upd_apply [simp]: \"(f(x:=y))z = (if z=x then y else f z)\"\nby (simp add: fun_upd_def)\n\n(* fun_upd_apply supersedes these two,   but they are useful\n   if fun_upd_apply is intentionally removed from the simpset *)\nlemma fun_upd_same: \"(f(x:=y)) x = y\"\nby simp\n\nlemma fun_upd_other: \"z~=x ==> (f(x:=y)) z = f z\"\nby simp\n\nlemma fun_upd_upd [simp]: \"f(x:=y,x:=z) = f(x:=z)\"\nby (simp add: fun_eq_iff)\n\nlemma fun_upd_twist: \"a ~= c ==> (m(a:=b))(c:=d) = (m(c:=d))(a:=b)\"\nby (rule ext, auto)\n\nlemma inj_on_fun_updI:\n  \"inj_on f A \\<Longrightarrow> y \\<notin> f ` A \\<Longrightarrow> inj_on (f(x := y)) A\"\n  by (fastforce simp: inj_on_def)\n\nlemma fun_upd_image:\n     \"f(x:=y) ` A = (if x \\<in> A then insert y (f ` (A-{x})) else f ` A)\"\nby auto\n\nlemma fun_upd_comp: \"f \\<circ> (g(x := y)) = (f \\<circ> g)(x := f y)\"\n  by auto\n\n\nsubsection {* @{text override_on} *}\n\ndefinition override_on :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'b\" where\n  \"override_on f g A = (\\<lambda>a. if a \\<in> A then g a else f a)\"\n\nlemma override_on_emptyset[simp]: \"override_on f g {} = f\"\nby(simp add:override_on_def)\n\nlemma override_on_apply_notin[simp]: \"a ~: A ==> (override_on f g A) a = f a\"\nby(simp add:override_on_def)\n\nlemma override_on_apply_in[simp]: \"a : A ==> (override_on f g A) a = g a\"\nby(simp add:override_on_def)\n\n\nsubsection {* @{text swap} *}\n\ndefinition swap :: \"'a \\<Rightarrow> 'a \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b)\"\nwhere\n  \"swap a b f = f (a := f b, b:= f a)\"\n\nlemma swap_apply [simp]:\n  \"swap a b f a = f b\"\n  \"swap a b f b = f a\"\n  \"c \\<noteq> a \\<Longrightarrow> c \\<noteq> b \\<Longrightarrow> swap a b f c = f c\"\n  by (simp_all add: swap_def)\n\nlemma swap_self [simp]:\n  \"swap a a f = f\"\n  by (simp add: swap_def)\n\nlemma swap_commute:\n  \"swap a b f = swap b a f\"\n  by (simp add: fun_upd_def swap_def fun_eq_iff)\n\nlemma swap_nilpotent [simp]:\n  \"swap a b (swap a b f) = f\"\n  by (rule ext, simp add: fun_upd_def swap_def)\n\nlemma swap_comp_involutory [simp]:\n  \"swap a b \\<circ> swap a b = id\"\n  by (rule ext) simp\n\nlemma swap_triple:\n  assumes \"a \\<noteq> c\" and \"b \\<noteq> c\"\n  shows \"swap a b (swap b c (swap a b f)) = swap a c f\"\n  using assms by (simp add: fun_eq_iff swap_def)\n\nlemma comp_swap: \"f \\<circ> swap a b g = swap a b (f \\<circ> g)\"\n  by (rule ext, simp add: fun_upd_def swap_def)\n\nlemma swap_image_eq [simp]:\n  assumes \"a \\<in> A\" \"b \\<in> A\" shows \"swap a b f ` A = f ` A\"\nproof -\n  have subset: \"\\<And>f. swap a b f ` A \\<subseteq> f ` A\"\n    using assms by (auto simp: image_iff swap_def)\n  then have \"swap a b (swap a b f) ` A \\<subseteq> (swap a b f) ` A\" .\n  with subset[of f] show ?thesis by auto\nqed\n\nlemma inj_on_imp_inj_on_swap:\n  \"\\<lbrakk>inj_on f A; a \\<in> A; b \\<in> A\\<rbrakk> \\<Longrightarrow> inj_on (swap a b f) A\"\n  by (simp add: inj_on_def swap_def, blast)\n\nlemma inj_on_swap_iff [simp]:\n  assumes A: \"a \\<in> A\" \"b \\<in> A\" shows \"inj_on (swap a b f) A \\<longleftrightarrow> inj_on f A\"\nproof\n  assume \"inj_on (swap a b f) A\"\n  with A have \"inj_on (swap a b (swap a b f)) A\"\n    by (iprover intro: inj_on_imp_inj_on_swap)\n  thus \"inj_on f A\" by simp\nnext\n  assume \"inj_on f A\"\n  with A show \"inj_on (swap a b f) A\" by (iprover intro: inj_on_imp_inj_on_swap)\nqed\n\nlemma surj_imp_surj_swap: \"surj f \\<Longrightarrow> surj (swap a b f)\"\n  by simp\n\nlemma surj_swap_iff [simp]: \"surj (swap a b f) \\<longleftrightarrow> surj f\"\n  by simp\n\nlemma bij_betw_swap_iff [simp]:\n  \"\\<lbrakk> x \\<in> A; y \\<in> A \\<rbrakk> \\<Longrightarrow> bij_betw (swap x y f) A B \\<longleftrightarrow> bij_betw f A B\"\n  by (auto simp: bij_betw_def)\n\nlemma bij_swap_iff [simp]: \"bij (swap a b f) \\<longleftrightarrow> bij f\"\n  by simp\n\nhide_const (open) swap\n\n\nsubsection {* Inversion of injective functions *}\n\ndefinition the_inv_into :: \"'a set => ('a => 'b) => ('b => 'a)\" where\n  \"the_inv_into A f == %x. THE y. y : A & f y = x\"\n\nlemma the_inv_into_f_f:\n  \"[| inj_on f A;  x : A |] ==> the_inv_into A f (f x) = x\"\napply (simp add: the_inv_into_def inj_on_def)\napply blast\ndone\n\nlemma f_the_inv_into_f:\n  \"inj_on f A ==> y : f`A  ==> f (the_inv_into A f y) = y\"\napply (simp add: the_inv_into_def)\napply (rule the1I2)\n apply(blast dest: inj_onD)\napply blast\ndone\n\nlemma the_inv_into_into:\n  \"[| inj_on f A; x : f ` A; A <= B |] ==> the_inv_into A f x : B\"\napply (simp add: the_inv_into_def)\napply (rule the1I2)\n apply(blast dest: inj_onD)\napply blast\ndone\n\nlemma the_inv_into_onto[simp]:\n  \"inj_on f A ==> the_inv_into A f ` (f ` A) = A\"\nby (fast intro:the_inv_into_into the_inv_into_f_f[symmetric])\n\nlemma the_inv_into_f_eq:\n  \"[| inj_on f A; f x = y; x : A |] ==> the_inv_into A f y = x\"\n  apply (erule subst)\n  apply (erule the_inv_into_f_f, assumption)\n  done\n\nlemma the_inv_into_comp:\n  \"[| inj_on f (g ` A); inj_on g A; x : f ` g ` A |] ==>\n  the_inv_into A (f o g) x = (the_inv_into A g o the_inv_into (g ` A) f) x\"\napply (rule the_inv_into_f_eq)\n  apply (fast intro: comp_inj_on)\n apply (simp add: f_the_inv_into_f the_inv_into_into)\napply (simp add: the_inv_into_into)\ndone\n\nlemma inj_on_the_inv_into:\n  \"inj_on f A \\<Longrightarrow> inj_on (the_inv_into A f) (f ` A)\"\nby (auto intro: inj_onI simp: the_inv_into_f_f)\n\nlemma bij_betw_the_inv_into:\n  \"bij_betw f A B \\<Longrightarrow> bij_betw (the_inv_into A f) B A\"\nby (auto simp add: bij_betw_def inj_on_the_inv_into the_inv_into_into)\n\nabbreviation the_inv :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a)\" where\n  \"the_inv f \\<equiv> the_inv_into UNIV f\"\n\nlemma the_inv_f_f:\n  assumes \"inj f\"\n  shows \"the_inv f (f x) = x\" using assms UNIV_I\n  by (rule the_inv_into_f_f)\n\n\nsubsection {* Cantor's Paradox *}\n\nlemma Cantors_paradox:\n  \"\\<not>(\\<exists>f. f ` A = Pow A)\"\nproof clarify\n  fix f assume \"f ` A = Pow A\" hence *: \"Pow A \\<le> f ` A\" by blast\n  let ?X = \"{a \\<in> A. a \\<notin> f a}\"\n  have \"?X \\<in> Pow A\" unfolding Pow_def by auto\n  with * obtain x where \"x \\<in> A \\<and> f x = ?X\" by blast\n  thus False by best\nqed\n\nsubsection {* Setup *} \n\nsubsubsection {* Proof tools *}\n\ntext {* simplifies terms of the form\n  f(...,x:=y,...,x:=z,...) to f(...,x:=z,...) *}\n\nsimproc_setup fun_upd2 (\"f(v := w, x := y)\") = {* fn _ =>\nlet\n  fun gen_fun_upd NONE T _ _ = NONE\n    | gen_fun_upd (SOME f) T x y = SOME (Const (@{const_name fun_upd}, T) $ f $ x $ y)\n  fun dest_fun_T1 (Type (_, T :: Ts)) = T\n  fun find_double (t as Const (@{const_name fun_upd},T) $ f $ x $ y) =\n    let\n      fun find (Const (@{const_name fun_upd},T) $ g $ v $ w) =\n            if v aconv x then SOME g else gen_fun_upd (find g) T v w\n        | find t = NONE\n    in (dest_fun_T1 T, gen_fun_upd (find f) T x y) end\n\n  val ss = simpset_of @{context}\n\n  fun proc ctxt ct =\n    let\n      val t = Thm.term_of ct\n    in\n      case find_double t of\n        (T, NONE) => NONE\n      | (T, SOME rhs) =>\n          SOME (Goal.prove ctxt [] [] (Logic.mk_equals (t, rhs))\n            (fn _ =>\n              resolve_tac [eq_reflection] 1 THEN\n              resolve_tac @{thms ext} 1 THEN\n              simp_tac (put_simpset ss ctxt) 1))\n    end\nin proc end\n*}\n\n\nsubsubsection {* Functorial structure of types *}\n\nML_file \"Tools/functor.ML\"\n\nfunctor map_fun: map_fun\n  by (simp_all add: fun_eq_iff)\n\nfunctor vimage\n  by (simp_all add: fun_eq_iff vimage_comp)\n\ntext {* Legacy theorem names *}\n\nlemmas o_def = comp_def\nlemmas o_apply = comp_apply\nlemmas o_assoc = comp_assoc [symmetric]\nlemmas id_o = id_comp\nlemmas o_id = comp_id\nlemmas o_eq_dest = comp_eq_dest\nlemmas o_eq_elim = comp_eq_elim\nlemmas o_eq_dest_lhs = comp_eq_dest_lhs\nlemmas o_eq_id_dest = comp_eq_id_dest\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.8615382058759128, "lm_q1q2_score": 0.763005345819234}}
{"text": "(*  Title:      Simple Groups\n    Author:     Jakob von Raumer, Karlsruhe Institute of Technology\n    Maintainer: Jakob von Raumer <jakob.raumer@student.kit.edu>\n*)\n\ntheory SimpleGroups\nimports Coset \"HOL-Computational_Algebra.Primes\"\nbegin\n\nsection \\<open>Simple Groups\\<close>\n\nlocale simple_group = group +\n  assumes order_gt_one: \"order G > 1\"\n  assumes no_real_normal_subgroup: \"\\<And>H. H \\<lhd> G \\<Longrightarrow> (H = carrier G \\<or> H = {\\<one>})\"\n\nlemma (in simple_group) is_simple_group: \"simple_group G\" \n  by (rule simple_group_axioms)\n\ntext \\<open>Simple groups are non-trivial.\\<close>\n\nlemma (in simple_group) simple_not_triv: \"carrier G \\<noteq> {\\<one>}\" \n  using order_gt_one unfolding order_def by auto\n\ntext \\<open>Every group of prime order is simple\\<close>\n\nlemma (in group) prime_order_simple:\n  assumes prime: \"prime (order G)\"\n  shows \"simple_group G\"\nproof\n  from prime show \"1 < order G\" \n    unfolding prime_nat_iff by auto\nnext\n  fix H\n  assume \"H \\<lhd> G\"\n  hence HG: \"subgroup H G\" unfolding normal_def by simp\n  hence \"card H dvd order G\"\n    by (metis dvd_triv_right lagrange)\n  with prime have \"card H = 1 \\<or> card H = order G\" \n    unfolding prime_nat_iff by simp\n  thus \"H = carrier G \\<or> H = {\\<one>}\"\n  proof\n    assume \"card H = 1\"\n    moreover from HG have \"\\<one> \\<in> H\" by (metis subgroup.one_closed)\n    ultimately show ?thesis by (auto simp: card_Suc_eq)\n  next\n    assume \"card H = order G\"\n    moreover from HG have \"H \\<subseteq> carrier G\" unfolding subgroup_def by simp\n    moreover from prime have \"finite (carrier G)\"\n      using order_gt_0_iff_finite by force\n    ultimately show ?thesis \n      unfolding order_def by (metis card_subset_eq)\n  qed\nqed\n\ntext \\<open>Being simple is a property that is preserved by isomorphisms.\\<close>\n\nlemma (in simple_group) iso_simple:\n  assumes H: \"group H\"\n  assumes iso: \"\\<phi> \\<in> iso G H\"\n  shows \"simple_group H\"\nunfolding simple_group_def simple_group_axioms_def \nproof (intro conjI strip H)\n  from iso have \"order G = order H\" unfolding iso_def order_def using bij_betw_same_card by auto\n  with order_gt_one show \"1 < order H\" by simp\nnext\n  have inv_iso: \"(inv_into (carrier G) \\<phi>) \\<in> iso H G\" using iso\n    by (simp add: iso_set_sym)    \n  fix N\n  assume NH: \"N \\<lhd> H\" \n  then interpret Nnormal: normal N H by simp\n  define M where \"M = (inv_into (carrier G) \\<phi>) ` N\"\n  hence MG: \"M \\<lhd> G\" \n    using inv_iso NH H by (metis is_group iso_normal_subgroup)\n  have surj: \"\\<phi> ` carrier G = carrier H\" \n    using iso unfolding iso_def bij_betw_def by simp\n  hence MN: \"\\<phi> ` M = N\" \n    unfolding M_def using Nnormal.subset image_inv_into_cancel by metis\n  then have \"N = {\\<one>\\<^bsub>H\\<^esub>}\" if \"M = {\\<one>}\"\n    using Nnormal.subgroup_axioms subgroup.one_closed that by force\n  then show \"N = carrier H \\<or> N = {\\<one>\\<^bsub>H\\<^esub>}\"\n    by (metis MG MN no_real_normal_subgroup surj)\nqed\n\ntext \\<open>As a corollary of this: Factorizing a group by itself does not result in a simple group!\\<close>\n\nlemma (in group) self_factor_not_simple: \"\\<not> simple_group (G Mod (carrier G))\"\nproof\n  assume assm: \"simple_group (G Mod (carrier G))\"\n  with self_factor_iso simple_group.iso_simple have \"simple_group (G\\<lparr>carrier := {\\<one>}\\<rparr>)\"\n    using subgroup_imp_group triv_subgroup by blast\n  thus False \n    using simple_group.simple_not_triv by force\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Algebra/SimpleGroups.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7629973119452039}}
{"text": "section \"Permutation Lemmas\"\n\ntheory PermutationLemmas\nimports \"HOL-Library.Permutation\" \"HOL-Library.Multiset\"\nbegin\n\n  \\<comment> \\<open>following function is very close to that in multisets- now we can make the connection that x <~~> y iff the multiset of x is the same as that of y\\<close>\n\nsubsection \"perm, count equivalence\"\n\nprimrec count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\"\nwhere\n  \"count x [] = 0\"\n| \"count x (y#ys) = (if x=y then 1 else 0) + count x ys\"\n\nlemma perm_count: \"A <~~> B \\<Longrightarrow> (\\<forall> x. count x A = count x B)\"\n  by(induct set: perm) auto\n\nlemma count_0: \"(\\<forall>x. count x B = 0) = (B = [])\"\n  by(induct B) auto\n\nlemma count_Suc: \"count a B = Suc m \\<Longrightarrow> a : set B\"\n  apply(induct B)\n   apply auto\n  apply(case_tac \"a = aa\")\n   apply auto\n  done\n\nlemma count_append: \"count a (xs@ys) = count a xs + count a ys\"\n  by(induct xs) auto\n\nlemma count_perm: \"!! B. (\\<forall> x. count x A = count x B) \\<Longrightarrow> A <~~> B\"\n  apply(induct A)\n  apply(simp add: count_0)\nproof -\n  fix a list B\n  assume a: \"\\<And>B. \\<forall>x. count x list = count x B \\<Longrightarrow> list <~~> B\"\n    and b: \"\\<forall>x. count x (a # list) = count x B\"\n  from b have \"a : set B\"\n    apply auto\n    apply (drule_tac x=a in spec, simp) apply(metis count_Suc) done\n  from split_list[OF this] obtain xs ys where B: \"B = xs@a#ys\" by blast\n  let ?B' = \"xs@ys\"\n  from b have \"\\<forall>x. count x list = count x ?B'\" by(simp add: count_append B)\n  from a[OF this] have c: \"list <~~> xs@ys\" .\n  hence \"a#list <~~> a#(xs@ys)\" by rule\n  also have \"a#(xs@ys) <~~> xs@a#ys\" by(rule perm_append_Cons)\n  also (perm.trans) note B[symmetric]\n  finally show \"a # list <~~> B\" .\nqed\n\nlemma perm_count_conv: \"A <~~> B = (\\<forall> x. count x A = count x B)\"\n  apply(blast intro!: perm_count count_perm) done \n\n\nsubsection \"Properties closed under Perm and Contr hold for x iff hold for remdups x\"\n\nlemma remdups_append: \"y : set ys --> remdups (ws@y#ys) = remdups (ws@ys)\"\n  apply (induct ws, simp)\n  apply (case_tac \"y = a\", simp, simp)\n  done\n\nlemma perm_contr': assumes perm[rule_format]: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and contr'[rule_format]: \"! x xs. P(x#x#xs) = P (x#xs)\" \n  shows \"! xs. length xs = n --> (P xs = P (remdups xs))\"\n  apply(induct n rule: nat_less_induct)\nproof (safe)\n  fix xs :: \"'a list\"\n  assume a[rule_format]: \"\\<forall>m<length xs. \\<forall>ys. length ys = m \\<longrightarrow> P ys = P (remdups ys)\"\n  show \"P xs = P (remdups xs)\"\n  proof (cases \"distinct xs\")\n    case True\n    thus ?thesis by(simp add:distinct_remdups_id)\n  next\n    case False\n    from not_distinct_decomp[OF this] obtain ws ys zs y where xs: \"xs = ws@[y]@ys@[y]@zs\" by force\n    have \"P xs = P (ws@[y]@ys@[y]@zs)\" by (simp add: xs)\n    also have \"... = P ([y,y]@ws@ys@zs)\" \n      apply(rule perm) apply(rule iffD2[OF perm_count_conv]) apply rule apply(simp add: count_append) done\n    also have \"... = P ([y]@ws@ys@zs)\" apply simp apply(rule contr') done\n    also have \"... = P (ws@ys@[y]@zs)\" \n      apply(rule perm) apply(rule iffD2[OF perm_count_conv]) apply rule apply(simp add: count_append) done\n    also have \"... = P (remdups (ws@ys@[y]@zs))\"\n      apply(rule a) by(auto simp: xs)\n    also have \"(remdups (ws@ys@[y]@zs)) = (remdups xs)\"\n      apply(simp add: xs remdups_append) done \n    finally show \"P xs = P (remdups xs)\" .\n  qed\nqed\n\nlemma perm_contr: assumes perm: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and contr': \"! x xs. P(x#x#xs) = P (x#xs)\" \n  shows \"(P xs = P (remdups xs))\"\n  apply(rule perm_contr'[OF perm contr', rule_format]) by force\n\n\nsubsection \"List properties closed under Perm, Weak and Contr are monotonic in the set of the list\"\n\ndefinition\n  rem :: \"'a => 'a list => 'a list\" where\n  \"rem x xs = filter (%y. y ~= x) xs\"\n\nlemma rem: \"x ~: set (rem x xs)\"\n  by(simp add: rem_def)\n\nlemma length_rem: \"length (rem x xs) <= length xs\"\n  by(simp add: rem_def)\n\nlemma rem_notin: \"x ~: set xs ==> rem x xs = xs\"\n  apply(simp add: rem_def)\n  apply(rule filter_True)\n  apply force\n  done\n\n\nlemma perm_weak_filter': assumes perm[rule_format]: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and weak[rule_format]: \"! x xs. P xs --> P (x#xs)\"\n  shows \"! ys. P (ys@filter Q xs) --> P (ys@xs)\"\n  apply (induct xs, simp, rule)\n  apply rule\n  apply simp\n  apply (case_tac \"Q a\", simp)\n   apply(drule_tac x=\"ys@[a]\" in spec) apply simp\n  apply simp\n  apply(drule_tac x=\"ys@[a]\" in spec) apply simp\n  apply(erule impE)\n   apply(subgoal_tac \"(ys @ a # filter Q xs) <~~> a#ys@filter Q xs\")\n    apply(simp add: perm)\n    apply(rule weak) apply simp\n   apply(rule perm_sym) apply(rule perm_append_Cons)\n  .\n\nlemma perm_weak_filter: assumes perm: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and weak: \"! x xs. P xs --> P (x#xs)\"\n  shows \"P (filter Q xs) ==> P xs\"\n  using perm_weak_filter'[OF perm weak, rule_format, of \"[]\", simplified]\n  by blast\n\n  \\<comment> \\<open>right, now in a position to prove that in presence of perm, contr and weak, set x leq set y and x : ded implies y : ded\\<close>\n\nlemma perm_weak_contr_mono: \n  assumes perm: \"! xs ys. xs <~~> ys --> (P xs = P ys)\"\n  and contr: \"! x xs. P (x#x#xs) --> P (x#xs)\"\n  and weak: \"! x xs. P xs --> P (x#xs)\"\n  and xy: \"set x <= set y\"\n  and Px : \"P x\"\n  shows \"P y\"\nproof -\n  from contr weak have contr': \"! x xs. P(x#x#xs) = P (x#xs)\" by blast\n\n  define y' where \"y' = filter (% z. z : set x) y\"\n  from xy have \"set x = set y'\" apply(simp add: y'_def) apply blast done\n  hence rxry': \"remdups x <~~> remdups y'\" by(simp add: perm_remdups_iff_eq_set)\n\n  from Px perm_contr[OF perm contr'] have Prx: \"P (remdups x)\" by simp\n  with rxry' have \"P (remdups y')\" by(simp add: perm)\n  \n  with perm_contr[OF perm contr'] have \"P y'\" by simp\n  thus \"P y\" \n    apply(simp add: y'_def)\n    apply(rule perm_weak_filter[OF perm weak]) .\nqed\n\n(* No, not used\nsubsection \"Following used in Soundness\"\n\nprimrec multiset_of_list :: \"'a list \\<Rightarrow> 'a multiset\"\nwhere\n  \"multiset_of_list [] = {#}\"\n| \"multiset_of_list (x#xs) = {#x#} + multiset_of_list xs\"\n\nlemma count_count[symmetric]: \"count x A = Multiset.count (multiset_of_list A) x\"\n  by (induct A) simp_all\n\nlemma perm_multiset: \"A <~~> B = (multiset_of_list A = multiset_of_list B)\"\n  apply(simp add: perm_count_conv)\n  apply(simp add: multiset_eq_iff)\n  apply(simp add: count_count)\n  done\n\nlemma set_of_multiset_of_list: \"set_of (multiset_of_list A) = set A\"\n  by (induct A) auto\n*)\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Completeness/PermutationLemmas.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7629729745681444}}
{"text": "\ntext \\<open>Extensions to Discrete.thy, in particular an implementation of square root by bisection\\<close>\n\ntheory Discrete_Extensions\n  imports \"HOL-Library.Discrete\" \"HOL-Eisbach.Eisbach\"\nbegin\n\n(* Internal 'loop' for the algorithm, takes lower and upper bound for root, returns root *)\nfunction dsqrt' :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"dsqrt' y L R = (if Suc L < R then let M = (L+R) div 2 in if M*M \\<le> y then dsqrt' y M R else dsqrt' y L M else L)\"\n  by auto\ntermination by (relation \"Wellfounded.measure (\\<lambda>(y,L,R). R - L)\") auto\n\ndeclare dsqrt'.simps[simp del]\n\n(* Probably not better... *)\nlemma dsqrt'_simps[]:\n  \"Suc L < R \\<Longrightarrow> ((L+R) div 2)^2 \\<le> y \\<Longrightarrow> dsqrt' y L R = dsqrt' y ((L+R) div 2) R\"\n  \"Suc L < R \\<Longrightarrow> ((L+R) div 2)^2 > y \\<Longrightarrow> dsqrt' y L R = dsqrt' y L ((L+R) div 2)\"\n  \"Suc L \\<ge> R \\<Longrightarrow> dsqrt' y L R = L\"\n  by (simp_all add: dsqrt'.simps power2_eq_square Let_def)\n\ndefinition dsqrt :: \"nat \\<Rightarrow> nat\" where\n  \"dsqrt y = dsqrt' y 0 (Suc y)\"\n\n(* I am still not sure if there is a better way to state multiple simultaneous goals for induction*)\nlemma dsqrt'_correct': \n  \"(0::nat) \\<le> L \\<Longrightarrow> L < R \\<Longrightarrow> L\\<^sup>2 \\<le> y \\<Longrightarrow> y < R\\<^sup>2 \\<Longrightarrow> (dsqrt' y L R)\\<^sup>2 \\<le> y \\<and> y < (Suc (dsqrt' y L R))\\<^sup>2\"\nproof (induction y L R rule: dsqrt'.induct)\n  case (1 y L R)\n  then show ?case\n  proof(cases \"Suc L < R\")\n    case True\n    then show ?thesis\n      (*Real proof needed*)\n      by (smt (verit, ccfv_threshold) \"1.IH\"(1) \"1.IH\"(2) \"1.prems\"(3) \"1.prems\"(4) dsqrt'_simps(1) \n          dsqrt'_simps(2) le_sqrt_iff less_eq_nat.simps(1) linorder_not_le order_trans power2_eq_square)\n  next\n    case False \n    hence \"Suc L = R\"\n      using 1 by linarith\n    then show ?thesis\n      using \"1.prems\" False by (fastforce simp add: dsqrt'.simps)\n  qed\nqed\n\n(* This is what I would like *)\nlemma dsqrt'_correct'': \n  assumes \"(0::nat) \\<le> L\" \"L < R\" \"L\\<^sup>2 \\<le> y\" \"y < R\\<^sup>2\" \n  shows \"(dsqrt' y L R)\\<^sup>2 \\<le> y\" \"y < (Suc (dsqrt' y L R))\\<^sup>2\"\n  using assms dsqrt'_correct' by blast+\n\nlemma dsqrt_correct': \n  \"(dsqrt y)\\<^sup>2 \\<le> y\" \"y < (Suc (dsqrt y))\\<^sup>2\"\n  unfolding dsqrt_def by (all \\<open>rule dsqrt'_correct''\\<close>) (simp_all add: power2_eq_square)\n\ncorollary dsqrt_correct: \"dsqrt y = Discrete.sqrt y\"\n  by (intro sqrt_unique[symmetric] dsqrt_correct')\n\nend", "meta": {"author": "AlexiosFan", "repo": "BA_NP_Reduction", "sha": "0e37ddc58cb822b0a09b2ce7c15e7b88652e154c", "save_path": "github-repos/isabelle/AlexiosFan-BA_NP_Reduction", "path": "github-repos/isabelle/AlexiosFan-BA_NP_Reduction/BA_NP_Reduction-0e37ddc58cb822b0a09b2ce7c15e7b88652e154c/poly-reductions/Lib/Discrete_Extensions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.8596637487122112, "lm_q1q2_score": 0.7626976269095423}}
{"text": "(* The types of finite sets and bags *)\ntheory FSets_Bags\nimports \"../NonFreeInput\"\nbegin\n\n\n(* Datatype of finite sets: *)\nnonfree_datatype 'a fset = Emp | Ins 'a \"'a fset\"\nwhere\n  Ins1: \"Ins a (Ins a A) = Ins a A\"\n| Ins2: \"Ins a1 (Ins a2 A) = Ins a2 (Ins a1 A)\"\n\ndeclare Ins1[simp]\n\n(* Datatype of bags: *)\nnonfree_datatype 'a bag = BEmp | BIns 'a \"'a bag\"\nwhere BIns: \"BIns a1 (BIns a2 B) = BIns a2 (BIns a1 B)\"\n\n\nnonfree_primrec fset_map :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a fset \\<Rightarrow> 'b fset\"\nwhere\n  \"fset_map f Emp = Emp\"\n| \"fset_map f (Ins a A) = Ins (f a) (fset_map f A)\"\nby (auto simp: Ins1 Ins2)\n\nnonfree_primrec bag_map :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a bag \\<Rightarrow> 'b bag\"\nwhere\n  \"bag_map f BEmp = BEmp\"\n| \"bag_map f (BIns a B) = BIns (f a) (bag_map f B)\"\nby (auto simp: BIns)\n\n(* Membership of an item in a finite set *)\nnonfree_primrec mem :: \"'a \\<Rightarrow> 'a fset \\<Rightarrow> bool\"\nwhere\n  \"mem a Emp = False\"\n| \"mem a (Ins b B) = (a = b \\<or> mem a B)\"\nby auto\n\nlemma mem_Ins[simp]: \"mem a A \\<Longrightarrow> Ins a A = A\"\nby (induction arbitrary: a rule: fset_induct) (auto simp: Ins2)\n\n(* Multiplicity of an item in bag *)\nnonfree_primrec mult :: \"'a \\<Rightarrow> 'a bag \\<Rightarrow> nat\"\nwhere\n  \"mult a BEmp = 0\"\n| \"mult a (BIns b B) = (if a = b then Suc (mult a B) else mult a B)\"\nby (auto simp: BIns)\n\n(* Flattening operator from bags to finite sets *)\nnonfree_primrec flat :: \"'a bag \\<Rightarrow> 'a fset\"\nwhere\n  \"flat BEmp = Emp\"\n| \"flat (BIns a B) = Ins a (flat B)\"\nby (auto simp: Ins2)\n\nlemma mem_flat_mult[simp]: \"mem a (flat A) \\<longleftrightarrow> mult a A \\<noteq> 0\"\nby (induction rule: bag_induct) auto\n\n(* Embedding of finite sets into bags *)\nnonfree_primrec embed :: \"'a fset \\<Rightarrow> 'a bag\"\nwhere\n  \"embed Emp = BEmp\"\n| \"embed (Ins a A) = (if mult a (embed A) = 0 then BIns a (embed A) else embed A)\"\nby (auto simp: BIns)\n\nlemma mult_embed_mem[simp]: \"mult a (embed A) \\<noteq> 0 \\<longleftrightarrow> mem a A\"\nby (induction rule: fset_induct) auto\n\n(* Cardinal of finite sets: *)\nnonfree_primrec card1 :: \"'a fset \\<Rightarrow> 'a fset * nat\"\nwhere\n  \"card1 Emp = (Emp, 0)\"\n| \"card1 (Ins a A) = (case card1 A of (A,n) \\<Rightarrow> (Ins a A, if mem a A then n else Suc n))\"\nby (auto simp: Ins2)\n\nlemma card1: \"card1 A = (A',n) \\<Longrightarrow> A = A'\"\nby (induct arbitrary: A' n rule: fset_induct) (auto split: prod.splits)\n\ndefinition card :: \"'a fset \\<Rightarrow> nat\" where \"card \\<equiv> snd o card1\"\n\nlemma card_simps[simp]:\n  \"card Emp = 0\"\n  \"card (Ins a A) = (if mem a A then card A else Suc (card A))\"\nunfolding card_def using card1 by (auto split: prod.splits)\n\n(* Sum of a numeric function over a finite set: *)\nnonfree_primrec sum1 :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset \\<times> nat\"\nwhere\n  \"sum1 f Emp = (Emp, 0)\"\n| \"sum1 f (Ins a A) = (case sum1 f A of (A,n) \\<Rightarrow> (Ins a A, if mem a A then n else n + f a))\"\nby (auto simp: Ins2)\n\nlemma sum1: \"sum1 f A = (A',n) \\<Longrightarrow> A = A'\"\nby (induct arbitrary: A' n rule: fset_induct) (auto split: prod.splits)\n\ndefinition sum :: \" ('a \\<Rightarrow> nat) \\<Rightarrow> 'a fset \\<Rightarrow> nat\" where \"sum f \\<equiv> snd o sum1 f\"\n\nlemma sum_simps[simp]:\n  \"sum f Emp = 0\"\n  \"sum f (Ins a A) = (if mem a A then sum f A else sum f A + f a)\"\nunfolding sum_def using sum1 by (auto split: prod.splits)\n\n(* Sum of a numeric function over a bag: *)\nnonfree_primrec bsum' :: \"('a \\<Rightarrow> nat) \\<Rightarrow> 'a bag \\<Rightarrow> nat\"\nwhere\n  \"bsum' f BEmp = 0\"\n| \"bsum' f (BIns a B) = bsum' f B + f a\"\nby auto\n\n(* More generally: Sum of a commutative-monoid-valed function over a bag: *)\nnonfree_primrec bsum :: \"('a \\<Rightarrow> 'b::comm_monoid_add) \\<Rightarrow> 'a bag \\<Rightarrow> 'b\"\nwhere\n  \"bsum f BEmp = 0\"\n| \"bsum f (BIns a B) = bsum f B + f a\"\nby (auto simp: algebra_simps)\n\n(* Embedding of finite sets as sets: *)\nnonfree_primrec asSet :: \"'a fset \\<Rightarrow> 'a set\"\nwhere\n  \"asSet Emp = {}\"\n| \"asSet (Ins a A) = insert a (asSet A)\"\nby auto\n\nlemma in_asSet[simp]: \"a \\<in> asSet F \\<longleftrightarrow> mem a F\"\nby (induction F) auto\n\nlemma mem_ex_Ins: \"mem a F \\<Longrightarrow> \\<exists> F'. \\<not> mem a F' \\<and> F = Ins a F'\"\nby (induction F) (metis Ins2 mem.simps mem_Ins)+\n\nlemma finite_asSet[simp, intro]: \"finite (asSet A)\"\nby (induction rule: fset_induct) auto\n\nlemma finite_imp_asSet: \"finite A \\<Longrightarrow> (\\<exists> F. A = asSet F)\"\nby (induction rule: finite_induct) (metis asSet.simps)+\n\nlemma asSet_eq_emp[simp]: \"asSet F = {} \\<Longrightarrow> Emp = F\"\nby (induction F) auto\n\nlemma asSet_inj[simp]: \"asSet F1 = asSet F2 \\<longleftrightarrow> F1 = F2\"\nproof(safe, induction F1 arbitrary: F2)\n  fix a F1 F2 assume IH: \"\\<And>F2. asSet F1 = asSet F2 \\<Longrightarrow> F1 = F2\"\n  and e: \"asSet (Ins a F1) = asSet F2\"\n  hence \"mem a F2\" by auto\n  then obtain F2' where F2': \"\\<not> mem a F2'\" and F2: \"F2 = Ins a F2'\" using mem_ex_Ins[of a F2] by blast\n  show \"Ins a F1 = F2\"\n  proof(cases \"mem a F1\")\n    case False\n    hence \"asSet F1 = asSet F2'\" using e F2' unfolding F2 by auto\n    thus ?thesis unfolding F2 using IH by auto\n  qed(insert e IH, auto)\nqed auto\n\ndefinition asFset :: \"'a set \\<Rightarrow> 'a fset\" where\n\"asFset A \\<equiv> SOME F. asSet F = A\"\n\nlemma asSet_asFset[simp]:\nassumes \"finite A\"  shows \"asSet (asFset A) = A\"\nunfolding asFset_def apply(rule someI_ex) using finite_imp_asSet[OF assms] by blast\n\nlemma asFset_asSet[simp]: \"asFset (asSet A) = A\"\nby (metis asSet_asFset asSet_inj finite_asSet)\n\nlemma asFset_emp[simp]: \"asFset {} = Emp\"\nby (metis asFset_asSet asSet.simps)\n\nlemma asFset_insert[simp]: \"finite A \\<Longrightarrow> asFset (insert a A) = Ins a (asFset A)\"\nby (metis asFset_asSet asSet.simps finite_imp_asSet)\n\n(* ACIU view: *)\ndefinition \"Singl a \\<equiv> Ins a Emp\"\n\nnonfree_primrec Uni :: \"'a fset \\<Rightarrow> 'a fset \\<Rightarrow> 'a fset\"\nwhere\n  \"Uni Emp = (\\<lambda> B. B)\"\n| \"Uni (Ins a A) = (\\<lambda> B. Ins a (Uni A B))\"\nby (auto simp: Ins2)\n\nlemma Uni_Emp[simp]: \"Uni Emp B = B\"\nand Uni_Ins[simp]: \"Uni (Ins a A) B = Ins a (Uni A B)\"\nby auto\n\ndeclare Uni.simps[simp del]\n\nlemma Uni_Emp2[simp]: \"Uni A Emp = A\"\nby(induction A) auto\n\nlemma Uni_Ins2[simp]: \"Uni A (Ins b B) = Ins b (Uni A B)\"\nby (induction A) (auto simp: Ins2)\n\nlemma Uni_assoc: \"Uni (Uni A B) C = Uni A (Uni B C)\"\nby (induction A) auto\n\nlemma Uni_com: \"Uni A B = Uni B A\"\nby (induction A) auto\n\nlemma Uni_idem[simp]: \"Uni A A = A\"\nby (induction A) auto\n\nlemma Ins_not_Emp[simp]: \"Ins a A \\<noteq> Emp\"\nby (induct A) (metis mem.simps)+\n\nlemma Singl_not_Emp[simp]: \"Singl a \\<noteq> Emp\"\nunfolding Singl_def by simp\n\nlemma Uni_eq_Emp[simp]: \"Uni A B = Emp \\<longleftrightarrow> A = Emp \\<and> B = Emp\"\nby (induct A) auto\n\nlemma mem_Uni[simp]: \"mem a (Uni A B) \\<longleftrightarrow> mem a A \\<or> mem a B\"\nby (induction A) auto\n\nlemma asFset_Uni[simp]:\nassumes \"finite A\" and \"finite B\"\nshows \"asFset (A \\<union> B) = Uni (asFset A) (asFset B)\"\nusing assms by (induct) auto\n\nlemma asFset_eq_Emp[simp]: assumes \"finite A\"  shows \"asFset A = Emp \\<longleftrightarrow> A = {}\"\nusing assms by (induction, auto)\n\n\n\nend\n\n\n", "meta": {"author": "metaforcy", "repo": "nonfree-data", "sha": "f3ce28278a88fdd240faa2e51f893fee5c15f2f2", "save_path": "github-repos/isabelle/metaforcy-nonfree-data", "path": "github-repos/isabelle/metaforcy-nonfree-data/nonfree-data-f3ce28278a88fdd240faa2e51f893fee5c15f2f2/Examples/FSets_Bags.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7626976195608862}}
{"text": " (*  Author:  Florian Haftmann, TUM\n*)\n\nsection \\<open>Proof(s) of concept for algebraically founded lists of bits\\<close>\n\ntheory Bit_Lists\n  imports\n    \"HOL-Library.Word\" \"HOL-Library.More_List\"\nbegin\n\nsubsection \\<open>Fragments of algebraic bit representations\\<close>\n\ncontext comm_semiring_1\nbegin\n \nabbreviation (input) unsigned_of_bits :: \"bool list \\<Rightarrow> 'a\"\n  where \"unsigned_of_bits \\<equiv> horner_sum of_bool 2\"\n\nlemma unsigned_of_bits_replicate_False [simp]:\n  \"unsigned_of_bits (replicate n False) = 0\"\n  by (induction n) simp_all\n\nend\n\ncontext unique_euclidean_semiring_with_bit_shifts\nbegin\n\nlemma unsigned_of_bits_append [simp]:\n  \"unsigned_of_bits (bs @ cs) = unsigned_of_bits bs\n    + push_bit (length bs) (unsigned_of_bits cs)\"\n  by (induction bs) (simp_all add: push_bit_double,\n    simp_all add: algebra_simps)\n\nlemma unsigned_of_bits_take [simp]:\n  \"unsigned_of_bits (take n bs) = take_bit n (unsigned_of_bits bs)\"\nproof (induction bs arbitrary: n)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons b bs)\n  then show ?case\n    by (cases n) (simp_all add: ac_simps take_bit_Suc)\nqed\n\nlemma unsigned_of_bits_drop [simp]:\n  \"unsigned_of_bits (drop n bs) = drop_bit n (unsigned_of_bits bs)\"\nproof (induction bs arbitrary: n)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons b bs)\n  then show ?case\n    by (cases n) (simp_all add: drop_bit_Suc)\nqed\n\nlemma bit_unsigned_of_bits_iff:\n  \\<open>bit (unsigned_of_bits bs) n \\<longleftrightarrow> nth_default False bs n\\<close>\nproof (induction bs arbitrary: n)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons b bs)\n  then show ?case\n    by (cases n) (simp_all add: bit_Suc)\nqed\n\nprimrec n_bits_of :: \"nat \\<Rightarrow> 'a \\<Rightarrow> bool list\"\n  where\n    \"n_bits_of 0 a = []\"\n  | \"n_bits_of (Suc n) a = odd a # n_bits_of n (a div 2)\"\n\nlemma n_bits_of_eq_iff:\n  \"n_bits_of n a = n_bits_of n b \\<longleftrightarrow> take_bit n a = take_bit n b\"\n  apply (induction n arbitrary: a b)\n   apply (auto elim!: evenE oddE simp add: take_bit_Suc mod_2_eq_odd)\n    apply (metis dvd_triv_right even_plus_one_iff odd_iff_mod_2_eq_one)\n   apply (metis dvd_triv_right even_plus_one_iff odd_iff_mod_2_eq_one)\n  done\n\nlemma take_n_bits_of [simp]:\n  \"take m (n_bits_of n a) = n_bits_of (min m n) a\"\nproof -\n  define q and v and w where \"q = min m n\" and \"v = m - q\" and \"w = n - q\"\n  then have \"v = 0 \\<or> w = 0\"\n    by auto\n  then have \"take (q + v) (n_bits_of (q + w) a) = n_bits_of q a\"\n    by (induction q arbitrary: a) auto\n  with q_def v_def w_def show ?thesis\n    by simp\nqed\n\nlemma unsigned_of_bits_n_bits_of [simp]:\n  \"unsigned_of_bits (n_bits_of n a) = take_bit n a\"\n  by (induction n arbitrary: a) (simp_all add: ac_simps take_bit_Suc mod_2_eq_odd)\n\nend\n\n\nsubsection \\<open>Syntactic bit representation\\<close>\n\nclass bit_representation =\n  fixes bits_of :: \"'a \\<Rightarrow> bool list\"\n    and of_bits :: \"bool list \\<Rightarrow> 'a\"\n  assumes of_bits_of [simp]: \"of_bits (bits_of a) = a\"\n\ntext \\<open>Unclear whether a \\<^typ>\\<open>bool\\<close> instantiation is needed or not\\<close>\n\ninstantiation nat :: bit_representation\nbegin\n\nfun bits_of_nat :: \"nat \\<Rightarrow> bool list\"\n  where \"bits_of (n::nat) =\n    (if n = 0 then [] else odd n # bits_of (n div 2))\"\n\nlemma bits_of_nat_simps [simp]:\n  \"bits_of (0::nat) = []\"\n  \"n > 0 \\<Longrightarrow> bits_of n = odd n # bits_of (n div 2)\" for n :: nat\n  by simp_all\n\ndeclare bits_of_nat.simps [simp del]\n\ndefinition of_bits_nat :: \"bool list \\<Rightarrow> nat\"\n  where [simp]: \"of_bits_nat = unsigned_of_bits\"\n  \\<comment> \\<open>remove simp\\<close>\n\ninstance proof\n  show \"of_bits (bits_of n) = n\" for n :: nat\n    by (induction n rule: nat_bit_induct) simp_all\nqed\n\nend\n\nlemma bit_of_bits_nat_iff:\n  \\<open>bit (of_bits bs :: nat) n \\<longleftrightarrow> nth_default False bs n\\<close>\n  by (simp add: bit_unsigned_of_bits_iff)\n\nlemma bits_of_Suc_0 [simp]:\n  \"bits_of (Suc 0) = [True]\"\n  by simp\n\nlemma bits_of_1_nat [simp]:\n  \"bits_of (1 :: nat) = [True]\"\n  by simp\n\nlemma bits_of_nat_numeral_simps [simp]:\n  \"bits_of (numeral Num.One :: nat) = [True]\" (is ?One)\n  \"bits_of (numeral (Num.Bit0 n) :: nat) = False # bits_of (numeral n :: nat)\" (is ?Bit0)\n  \"bits_of (numeral (Num.Bit1 n) :: nat) = True # bits_of (numeral n :: nat)\" (is ?Bit1)\nproof -\n  show ?One\n    by simp\n  define m :: nat where \"m = numeral n\"\n  then have \"m > 0\" and *: \"numeral n = m\" \"numeral (Num.Bit0 n) = 2 * m\" \"numeral (Num.Bit1 n) = Suc (2 * m)\"\n    by simp_all\n  from \\<open>m > 0\\<close> show ?Bit0 ?Bit1\n    by (simp_all add: *)\nqed\n\nlemma unsigned_of_bits_of_nat [simp]:\n  \"unsigned_of_bits (bits_of n) = n\" for n :: nat\n  using of_bits_of [of n] by simp\n\ninstantiation int :: bit_representation\nbegin\n\nfun bits_of_int :: \"int \\<Rightarrow> bool list\"\n  where \"bits_of_int k = odd k #\n    (if k = 0 \\<or> k = - 1 then [] else bits_of_int (k div 2))\"\n\nlemma bits_of_int_simps [simp]:\n  \"bits_of (0 :: int) = [False]\"\n  \"bits_of (- 1 :: int) = [True]\"\n  \"k \\<noteq> 0 \\<Longrightarrow> k \\<noteq> - 1 \\<Longrightarrow> bits_of k = odd k # bits_of (k div 2)\" for k :: int\n  by simp_all\n\nlemma bits_of_not_Nil [simp]:\n  \"bits_of k \\<noteq> []\" for k :: int\n  by simp\n\ndeclare bits_of_int.simps [simp del]\n\ndefinition of_bits_int :: \"bool list \\<Rightarrow> int\"\n  where \"of_bits_int bs = (if bs = [] \\<or> \\<not> last bs then unsigned_of_bits bs\n    else unsigned_of_bits bs - 2 ^ length bs)\"\n\nlemma of_bits_int_simps [simp]:\n  \"of_bits [] = (0 :: int)\"\n  \"of_bits [False] = (0 :: int)\"\n  \"of_bits [True] = (- 1 :: int)\"\n  \"of_bits (bs @ [b]) = (unsigned_of_bits bs :: int) - (2 ^ length bs) * of_bool b\"\n  \"of_bits (False # bs) = 2 * (of_bits bs :: int)\"\n  \"bs \\<noteq> [] \\<Longrightarrow> of_bits (True # bs) = 1 + 2 * (of_bits bs :: int)\"\n  by (simp_all add: of_bits_int_def push_bit_of_1)\n\ninstance proof\n  show \"of_bits (bits_of k) = k\" for k :: int\n    by (induction k rule: int_bit_induct) simp_all\nqed\n\nlemma bits_of_1_int [simp]:\n  \"bits_of (1 :: int) = [True, False]\"\n  by simp\n\nlemma bits_of_int_numeral_simps [simp]:\n  \"bits_of (numeral Num.One :: int) = [True, False]\" (is ?One)\n  \"bits_of (numeral (Num.Bit0 n) :: int) = False # bits_of (numeral n :: int)\" (is ?Bit0)\n  \"bits_of (numeral (Num.Bit1 n) :: int) = True # bits_of (numeral n :: int)\" (is ?Bit1)\n  \"bits_of (- numeral (Num.Bit0 n) :: int) = False # bits_of (- numeral n :: int)\" (is ?nBit0)\n  \"bits_of (- numeral (Num.Bit1 n) :: int) = True # bits_of (- numeral (Num.inc n) :: int)\" (is ?nBit1)\nproof -\n  show ?One\n    by simp\n  define k :: int where \"k = numeral n\"\n  then have \"k > 0\" and *: \"numeral n = k\" \"numeral (Num.Bit0 n) = 2 * k\" \"numeral (Num.Bit1 n) = 2 * k + 1\"\n    \"numeral (Num.inc n) = k + 1\"\n    by (simp_all add: add_One)\n  have \"- (2 * k) div 2 = - k\" \"(- (2 * k) - 1) div 2 = - k - 1\"\n    by simp_all\n  with \\<open>k > 0\\<close> show ?Bit0 ?Bit1 ?nBit0 ?nBit1\n    by (simp_all add: *)\nqed\n\nlemma bit_of_bits_int_iff:\n  \\<open>bit (of_bits bs :: int) n \\<longleftrightarrow> nth_default (bs \\<noteq> [] \\<and> last bs) bs n\\<close>\nproof (induction bs arbitrary: n)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons b bs)\n  then show ?case\n    by (cases n; cases b; cases bs) (simp_all add: bit_Suc)\nqed\n\nlemma of_bits_append [simp]:\n  \"of_bits (bs @ cs) = of_bits bs + push_bit (length bs) (of_bits cs :: int)\"\n    if \"bs \\<noteq> []\" \"\\<not> last bs\"\nusing that proof (induction bs rule: list_nonempty_induct)\n  case (single b)\n  then show ?case\n    by simp\nnext\n  case (cons b bs)\n  then show ?case\n    by (cases b) (simp_all add: push_bit_double)\nqed\n\nlemma of_bits_replicate_False [simp]:\n  \"of_bits (replicate n False) = (0 :: int)\"\n  by (auto simp add: of_bits_int_def)\n\nlemma of_bits_drop [simp]:\n  \"of_bits (drop n bs) = drop_bit n (of_bits bs :: int)\"\n    if \"n < length bs\"\nusing that proof (induction bs arbitrary: n)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons b bs)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by simp\n  next\n    case (Suc n)\n    with Cons.prems have \"bs \\<noteq> []\"\n      by auto\n    with Suc Cons.IH [of n] Cons.prems show ?thesis\n      by (cases b) (simp_all add: drop_bit_Suc)\n  qed\nqed\n\nend\n\nlemma unsigned_of_bits_eq_of_bits:\n  \"unsigned_of_bits bs = (of_bits (bs @ [False]) :: int)\"\n  by (simp add: of_bits_int_def)\n\nunbundle word.lifting\n\ninstantiation word :: (len) bit_representation\nbegin\n\nlift_definition bits_of_word :: \"'a word \\<Rightarrow> bool list\"\n  is \"n_bits_of LENGTH('a)\"\n  by (simp add: n_bits_of_eq_iff)\n\nlift_definition of_bits_word :: \"bool list \\<Rightarrow> 'a word\"\n  is unsigned_of_bits .\n\ninstance proof\n  fix a :: \"'a word\"\n  show \"of_bits (bits_of a) = a\"\n    by transfer simp\nqed\n\nend\n\nlifting_update word.lifting\nlifting_forget word.lifting\n\n\nsubsection \\<open>Bit representations with bit operations\\<close>\n\nclass semiring_bit_representation = semiring_bit_operations + bit_representation +\n  assumes and_eq: \"length bs = length cs \\<Longrightarrow>\n      of_bits bs AND of_bits cs = of_bits (map2 (\\<and>) bs cs)\"\n    and or_eq: \"length bs = length cs \\<Longrightarrow>\n      of_bits bs OR of_bits cs = of_bits (map2 (\\<or>) bs cs)\"\n    and xor_eq: \"length bs = length cs \\<Longrightarrow>\n      of_bits bs XOR of_bits cs = of_bits (map2 (\\<noteq>) bs cs)\"\n    and push_bit_eq: \"push_bit n a = of_bits (replicate n False @ bits_of a)\"\n    and drop_bit_eq: \"n < length (bits_of a) \\<Longrightarrow> drop_bit n a = of_bits (drop n (bits_of a))\"\n\nclass ring_bit_representation = ring_bit_operations + semiring_bit_representation +\n  assumes not_eq: \"not = of_bits \\<circ> map Not \\<circ> bits_of\"\n\ninstance nat :: semiring_bit_representation\n  by standard (simp_all add: bit_eq_iff bit_unsigned_of_bits_iff nth_default_map2 [of _ _ _ False False]\n    bit_and_iff bit_or_iff bit_xor_iff)\n\ninstance int :: ring_bit_representation\nproof\n  {\n    fix bs cs :: \\<open>bool list\\<close>\n    assume \\<open>length bs = length cs\\<close>\n    then have \\<open>cs = [] \\<longleftrightarrow> bs = []\\<close>\n      by auto\n    with \\<open>length bs = length cs\\<close> have \\<open>zip bs cs \\<noteq> [] \\<and> last (map2 (\\<and>) bs cs) \\<longleftrightarrow> (bs \\<noteq> [] \\<and> last bs) \\<and> (cs \\<noteq> [] \\<and> last cs)\\<close>\n      and \\<open>zip bs cs \\<noteq> [] \\<and> last (map2 (\\<or>) bs cs) \\<longleftrightarrow> (bs \\<noteq> [] \\<and> last bs) \\<or> (cs \\<noteq> [] \\<and> last cs)\\<close>\n      and \\<open>zip bs cs \\<noteq> [] \\<and> last (map2 (\\<noteq>) bs cs) \\<longleftrightarrow> ((bs \\<noteq> [] \\<and> last bs) \\<noteq> (cs \\<noteq> [] \\<and> last cs))\\<close>\n      by (auto simp add: last_map last_zip zip_eq_Nil_iff prod_eq_iff)\n    then show \\<open>of_bits bs AND of_bits cs = (of_bits (map2 (\\<and>) bs cs) :: int)\\<close>\n      and \\<open>of_bits bs OR of_bits cs = (of_bits (map2 (\\<or>) bs cs) :: int)\\<close>\n      and \\<open>of_bits bs XOR of_bits cs = (of_bits (map2 (\\<noteq>) bs cs) :: int)\\<close>\n      by (simp_all add: fun_eq_iff bit_eq_iff bit_and_iff bit_or_iff bit_xor_iff bit_not_iff bit_of_bits_int_iff \\<open>length bs = length cs\\<close> nth_default_map2 [of bs cs _ \\<open>bs \\<noteq> [] \\<and> last bs\\<close> \\<open>cs \\<noteq> [] \\<and> last cs\\<close>])\n  }\n  show \\<open>push_bit n k = of_bits (replicate n False @ bits_of k)\\<close>\n    for k :: int and n :: nat\n    by (cases \"n = 0\") simp_all\n  show \\<open>drop_bit n k = of_bits (drop n (bits_of k))\\<close>\n    if \\<open>n < length (bits_of k)\\<close> for k :: int and n :: nat\n    using that by simp\n  show \\<open>(not :: int \\<Rightarrow> _) = of_bits \\<circ> map Not \\<circ> bits_of\\<close>\n  proof (rule sym, rule ext)\n    fix k :: int\n    show \\<open>(of_bits \\<circ> map Not \\<circ> bits_of) k = NOT k\\<close>\n      by (induction k rule: int_bit_induct) (simp_all add: not_int_def)\n  qed\nqed\n\nend\n", "meta": {"author": "object-logics", "repo": "isabelle_para", "sha": "fd37dea4fd86b40bde51d9ca7adeba3e009d87c4", "save_path": "github-repos/isabelle/object-logics-isabelle_para", "path": "github-repos/isabelle/object-logics-isabelle_para/isabelle_para-fd37dea4fd86b40bde51d9ca7adeba3e009d87c4/src/HOL/ex/Bit_Lists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8723473862936942, "lm_q1q2_score": 0.7624989915148911}}
{"text": "(*<*)theory AB imports Main begin(*>*)\n\nsection\\<open>Case Study: A Context Free Grammar\\<close>\n\ntext\\<open>\\label{sec:CFG}\n\\index{grammars!defining inductively|(}%\nGrammars are nothing but shorthands for inductive definitions of nonterminals\nwhich represent sets of strings. For example, the production\n$A \\to B c$ is short for\n\\[ w \\in B \\Longrightarrow wc \\in A \\]\nThis section demonstrates this idea with an example\ndue to Hopcroft and Ullman, a grammar for generating all words with an\nequal number of $a$'s and~$b$'s:\n\\begin{eqnarray}\nS &\\to& \\epsilon \\mid b A \\mid a B \\nonumber\\\\\nA &\\to& a S \\mid b A A \\nonumber\\\\\nB &\\to& b S \\mid a B B \\nonumber\n\\end{eqnarray}\nAt the end we say a few words about the relationship between\nthe original proof @{cite \\<open>p.\\ts81\\<close> HopcroftUllman} and our formal version.\n\nWe start by fixing the alphabet, which consists only of \\<^term>\\<open>a\\<close>'s\nand~\\<^term>\\<open>b\\<close>'s:\n\\<close>\n\ndatatype alfa = a | b\n\ntext\\<open>\\noindent\nFor convenience we include the following easy lemmas as simplification rules:\n\\<close>\n\n\n\ntext\\<open>\\noindent\nWords over this alphabet are of type \\<^typ>\\<open>alfa list\\<close>, and\nthe three nonterminals are declared as sets of such words.\nThe productions above are recast as a \\emph{mutual} inductive\ndefinition\\index{inductive definition!simultaneous}\nof \\<^term>\\<open>S\\<close>, \\<^term>\\<open>A\\<close> and~\\<^term>\\<open>B\\<close>:\n\\<close>\n\ninductive_set\n  S :: \"alfa list set\" and\n  A :: \"alfa list set\" and\n  B :: \"alfa list set\"\nwhere\n  \"[] \\<in> S\"\n| \"w \\<in> A \\<Longrightarrow> b#w \\<in> S\"\n| \"w \\<in> B \\<Longrightarrow> a#w \\<in> S\"\n\n| \"w \\<in> S        \\<Longrightarrow> a#w   \\<in> A\"\n| \"\\<lbrakk> v\\<in>A; w\\<in>A \\<rbrakk> \\<Longrightarrow> b#v@w \\<in> A\"\n\n| \"w \\<in> S            \\<Longrightarrow> b#w   \\<in> B\"\n| \"\\<lbrakk> v \\<in> B; w \\<in> B \\<rbrakk> \\<Longrightarrow> a#v@w \\<in> B\"\n\ntext\\<open>\\noindent\nFirst we show that all words in \\<^term>\\<open>S\\<close> contain the same number of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s. Since the definition of \\<^term>\\<open>S\\<close> is by mutual\ninduction, so is the proof: we show at the same time that all words in\n\\<^term>\\<open>A\\<close> contain one more \\<^term>\\<open>a\\<close> than \\<^term>\\<open>b\\<close> and all words in \\<^term>\\<open>B\\<close> contain one more \\<^term>\\<open>b\\<close> than \\<^term>\\<open>a\\<close>.\n\\<close>\n\nlemma correctness:\n  \"(w \\<in> S \\<longrightarrow> size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b])     \\<and>\n   (w \\<in> A \\<longrightarrow> size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b] + 1) \\<and>\n   (w \\<in> B \\<longrightarrow> size[x\\<leftarrow>w. x=b] = size[x\\<leftarrow>w. x=a] + 1)\"\n\ntxt\\<open>\\noindent\nThese propositions are expressed with the help of the predefined \\<^term>\\<open>filter\\<close> function on lists, which has the convenient syntax \\<open>[x\\<leftarrow>xs. P\nx]\\<close>, the list of all elements \\<^term>\\<open>x\\<close> in \\<^term>\\<open>xs\\<close> such that \\<^prop>\\<open>P x\\<close>\nholds. Remember that on lists \\<open>size\\<close> and \\<open>length\\<close> are synonymous.\n\nThe proof itself is by rule induction and afterwards automatic:\n\\<close>\n\nby (rule S_A_B.induct, auto)\n\ntext\\<open>\\noindent\nThis may seem surprising at first, and is indeed an indication of the power\nof inductive definitions. But it is also quite straightforward. For example,\nconsider the production $A \\to b A A$: if $v,w \\in A$ and the elements of $A$\ncontain one more $a$ than~$b$'s, then $bvw$ must again contain one more $a$\nthan~$b$'s.\n\nAs usual, the correctness of syntactic descriptions is easy, but completeness\nis hard: does \\<^term>\\<open>S\\<close> contain \\emph{all} words with an equal number of\n\\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s? It turns out that this proof requires the\nfollowing lemma: every string with two more \\<^term>\\<open>a\\<close>'s than \\<^term>\\<open>b\\<close>'s can be cut somewhere such that each half has one more \\<^term>\\<open>a\\<close> than\n\\<^term>\\<open>b\\<close>. This is best seen by imagining counting the difference between the\nnumber of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s starting at the left end of the\nword. We start with 0 and end (at the right end) with 2. Since each move to the\nright increases or decreases the difference by 1, we must have passed through\n1 on our way from 0 to 2. Formally, we appeal to the following discrete\nintermediate value theorem @{thm[source]nat0_intermed_int_val}\n@{thm[display,margin=60]nat0_intermed_int_val[no_vars]}\nwhere \\<^term>\\<open>f\\<close> is of type \\<^typ>\\<open>nat \\<Rightarrow> int\\<close>, \\<^typ>\\<open>int\\<close> are the integers,\n\\<open>\\<bar>.\\<bar>\\<close> is the absolute value function\\footnote{See\nTable~\\ref{tab:ascii} in the Appendix for the correct \\textsc{ascii}\nsyntax.}, and \\<^term>\\<open>1::int\\<close> is the integer 1 (see \\S\\ref{sec:numbers}).\n\nFirst we show that our specific function, the difference between the\nnumbers of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s, does indeed only change by 1 in every\nmove to the right. At this point we also start generalizing from \\<^term>\\<open>a\\<close>'s\nand \\<^term>\\<open>b\\<close>'s to an arbitrary property \\<^term>\\<open>P\\<close>. Otherwise we would have\nto prove the desired lemma twice, once as stated above and once with the\nroles of \\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s interchanged.\n\\<close>\n\nlemma step1: \"\\<forall>i < size w.\n  \\<bar>(int(size[x\\<leftarrow>take (i+1) w. P x])-int(size[x\\<leftarrow>take (i+1) w. \\<not>P x]))\n   - (int(size[x\\<leftarrow>take i w. P x])-int(size[x\\<leftarrow>take i w. \\<not>P x]))\\<bar> \\<le> 1\"\n\ntxt\\<open>\\noindent\nThe lemma is a bit hard to read because of the coercion function\n\\<open>int :: nat \\<Rightarrow> int\\<close>. It is required because \\<^term>\\<open>size\\<close> returns\na natural number, but subtraction on type~\\<^typ>\\<open>nat\\<close> will do the wrong thing.\nFunction \\<^term>\\<open>take\\<close> is predefined and \\<^term>\\<open>take i xs\\<close> is the prefix of\nlength \\<^term>\\<open>i\\<close> of \\<^term>\\<open>xs\\<close>; below we also need \\<^term>\\<open>drop i xs\\<close>, which\nis what remains after that prefix has been dropped from \\<^term>\\<open>xs\\<close>.\n\nThe proof is by induction on \\<^term>\\<open>w\\<close>, with a trivial base case, and a not\nso trivial induction step. Since it is essentially just arithmetic, we do not\ndiscuss it.\n\\<close>\n\napply(induct_tac w)\napply(auto simp add: abs_if take_Cons split: nat.split)\ndone\n\ntext\\<open>\nFinally we come to the above-mentioned lemma about cutting in half a word with two more elements of one sort than of the other sort:\n\\<close>\n\nlemma part1:\n \"size[x\\<leftarrow>w. P x] = size[x\\<leftarrow>w. \\<not>P x]+2 \\<Longrightarrow>\n  \\<exists>i\\<le>size w. size[x\\<leftarrow>take i w. P x] = size[x\\<leftarrow>take i w. \\<not>P x]+1\"\n\ntxt\\<open>\\noindent\nThis is proved by \\<open>force\\<close> with the help of the intermediate value theorem,\ninstantiated appropriately and with its first premise disposed of by lemma\n@{thm[source]step1}:\n\\<close>\n\napply(insert nat0_intermed_int_val[OF step1, of \"P\" \"w\" \"1\"])\nby force\n\ntext\\<open>\\noindent\n\nLemma @{thm[source]part1} tells us only about the prefix \\<^term>\\<open>take i w\\<close>.\nAn easy lemma deals with the suffix \\<^term>\\<open>drop i w\\<close>:\n\\<close>\n\n\nlemma part2:\n  \"\\<lbrakk>size[x\\<leftarrow>take i w @ drop i w. P x] =\n    size[x\\<leftarrow>take i w @ drop i w. \\<not>P x]+2;\n    size[x\\<leftarrow>take i w. P x] = size[x\\<leftarrow>take i w. \\<not>P x]+1\\<rbrakk>\n   \\<Longrightarrow> size[x\\<leftarrow>drop i w. P x] = size[x\\<leftarrow>drop i w. \\<not>P x]+1\"\nby(simp del: append_take_drop_id)\n\ntext\\<open>\\noindent\nIn the proof we have disabled the normally useful lemma\n\\begin{isabelle}\n@{thm append_take_drop_id[no_vars]}\n\\rulename{append_take_drop_id}\n\\end{isabelle}\nto allow the simplifier to apply the following lemma instead:\n@{text[display]\"[x\\<in>xs@ys. P x] = [x\\<in>xs. P x] @ [x\\<in>ys. P x]\"}\n\nTo dispose of trivial cases automatically, the rules of the inductive\ndefinition are declared simplification rules:\n\\<close>\n\ndeclare S_A_B.intros[simp]\n\ntext\\<open>\\noindent\nThis could have been done earlier but was not necessary so far.\n\nThe completeness theorem tells us that if a word has the same number of\n\\<^term>\\<open>a\\<close>'s and \\<^term>\\<open>b\\<close>'s, then it is in \\<^term>\\<open>S\\<close>, and similarly \nfor \\<^term>\\<open>A\\<close> and \\<^term>\\<open>B\\<close>:\n\\<close>\n\ntheorem completeness:\n  \"(size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b]     \\<longrightarrow> w \\<in> S) \\<and>\n   (size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b] + 1 \\<longrightarrow> w \\<in> A) \\<and>\n   (size[x\\<leftarrow>w. x=b] = size[x\\<leftarrow>w. x=a] + 1 \\<longrightarrow> w \\<in> B)\"\n\ntxt\\<open>\\noindent\nThe proof is by induction on \\<^term>\\<open>w\\<close>. Structural induction would fail here\nbecause, as we can see from the grammar, we need to make bigger steps than\nmerely appending a single letter at the front. Hence we induct on the length\nof \\<^term>\\<open>w\\<close>, using the induction rule @{thm[source]length_induct}:\n\\<close>\n\napply(induct_tac w rule: length_induct)\napply(rename_tac w)\n\ntxt\\<open>\\noindent\nThe \\<open>rule\\<close> parameter tells \\<open>induct_tac\\<close> explicitly which induction\nrule to use. For details see \\S\\ref{sec:complete-ind} below.\nIn this case the result is that we may assume the lemma already\nholds for all words shorter than \\<^term>\\<open>w\\<close>. Because the induction step renames\nthe induction variable we rename it back to \\<open>w\\<close>.\n\nThe proof continues with a case distinction on \\<^term>\\<open>w\\<close>,\non whether \\<^term>\\<open>w\\<close> is empty or not.\n\\<close>\n\napply(case_tac w)\n apply(simp_all)\n(*<*)apply(rename_tac x v)(*>*)\n\ntxt\\<open>\\noindent\nSimplification disposes of the base case and leaves only a conjunction\nof two step cases to be proved:\nif \\<^prop>\\<open>w = a#v\\<close> and @{prop[display]\"size[x\\<in>v. x=a] = size[x\\<in>v. x=b]+2\"} then\n\\<^prop>\\<open>b#v \\<in> A\\<close>, and similarly for \\<^prop>\\<open>w = b#v\\<close>.\nWe only consider the first case in detail.\n\nAfter breaking the conjunction up into two cases, we can apply\n@{thm[source]part1} to the assumption that \\<^term>\\<open>w\\<close> contains two more \\<^term>\\<open>a\\<close>'s than \\<^term>\\<open>b\\<close>'s.\n\\<close>\n\napply(rule conjI)\n apply(clarify)\n apply(frule part1[of \"\\<lambda>x. x=a\", simplified])\n apply(clarify)\ntxt\\<open>\\noindent\nThis yields an index \\<^prop>\\<open>i \\<le> length v\\<close> such that\n@{prop[display]\"length [x\\<leftarrow>take i v . x = a] = length [x\\<leftarrow>take i v . x = b] + 1\"}\nWith the help of @{thm[source]part2} it follows that\n@{prop[display]\"length [x\\<leftarrow>drop i v . x = a] = length [x\\<leftarrow>drop i v . x = b] + 1\"}\n\\<close>\n\n apply(drule part2[of \"\\<lambda>x. x=a\", simplified])\n  apply(assumption)\n\ntxt\\<open>\\noindent\nNow it is time to decompose \\<^term>\\<open>v\\<close> in the conclusion \\<^prop>\\<open>b#v \\<in> A\\<close>\ninto \\<^term>\\<open>take i v @ drop i v\\<close>,\n\\<close>\n\n apply(rule_tac n1=i and t=v in subst[OF append_take_drop_id])\n\ntxt\\<open>\\noindent\n(the variables \\<^term>\\<open>n1\\<close> and \\<^term>\\<open>t\\<close> are the result of composing the\ntheorems @{thm[source]subst} and @{thm[source]append_take_drop_id})\nafter which the appropriate rule of the grammar reduces the goal\nto the two subgoals \\<^prop>\\<open>take i v \\<in> A\\<close> and \\<^prop>\\<open>drop i v \\<in> A\\<close>:\n\\<close>\n\n apply(rule S_A_B.intros)\n\ntxt\\<open>\nBoth subgoals follow from the induction hypothesis because both \\<^term>\\<open>take i\nv\\<close> and \\<^term>\\<open>drop i v\\<close> are shorter than \\<^term>\\<open>w\\<close>:\n\\<close>\n\n  apply(force simp add: min_less_iff_disj)\n apply(force split: nat_diff_split)\n\ntxt\\<open>\nThe case \\<^prop>\\<open>w = b#v\\<close> is proved analogously:\n\\<close>\n\napply(clarify)\napply(frule part1[of \"\\<lambda>x. x=b\", simplified])\napply(clarify)\napply(drule part2[of \"\\<lambda>x. x=b\", simplified])\n apply(assumption)\napply(rule_tac n1=i and t=v in subst[OF append_take_drop_id])\napply(rule S_A_B.intros)\n apply(force simp add: min_less_iff_disj)\nby(force simp add: min_less_iff_disj split: nat_diff_split)\n\ntext\\<open>\nWe conclude this section with a comparison of our proof with \nHopcroft\\index{Hopcroft, J. E.} and Ullman's\\index{Ullman, J. D.}\n@{cite \\<open>p.\\ts81\\<close> HopcroftUllman}.\nFor a start, the textbook\ngrammar, for no good reason, excludes the empty word, thus complicating\nmatters just a little bit: they have 8 instead of our 7 productions.\n\nMore importantly, the proof itself is different: rather than\nseparating the two directions, they perform one induction on the\nlength of a word. This deprives them of the beauty of rule induction,\nand in the easy direction (correctness) their reasoning is more\ndetailed than our \\<open>auto\\<close>. For the hard part (completeness), they\nconsider just one of the cases that our \\<open>simp_all\\<close> disposes of\nautomatically. Then they conclude the proof by saying about the\nremaining cases: ``We do this in a manner similar to our method of\nproof for part (1); this part is left to the reader''. But this is\nprecisely the part that requires the intermediate value theorem and\nthus is not at all similar to the other cases (which are automatic in\nIsabelle). The authors are at least cavalier about this point and may\neven have overlooked the slight difficulty lurking in the omitted\ncases.  Such errors are found in many pen-and-paper proofs when they\nare scrutinized formally.%\n\\index{grammars!defining inductively|)}\n\\<close>\n\n(*<*)end(*>*)\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/Doc/Tutorial/Inductive/AB.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7624577699873277}}
{"text": "(*  Title:      HOL/Hahn_Banach/Vector_Space.thy\n    Author:     Gertrud Bauer, TU Munich\n*)\n\nsection \\<open>Vector spaces\\<close>\n\ntheory Vector_Space\nimports Complex_Main Bounds\nbegin\n\nsubsection \\<open>Signature\\<close>\n\ntext \\<open>\n  For the definition of real vector spaces a type @{typ 'a} of the\n  sort @{text \"{plus, minus, zero}\"} is considered, on which a real\n  scalar multiplication @{text \\<cdot>} is declared.\n\\<close>\n\nconsts\n  prod :: \"real \\<Rightarrow> 'a::{plus,minus,zero} \\<Rightarrow> 'a\"  (infixr \"\\<cdot>\" 70)\n\n\nsubsection \\<open>Vector space laws\\<close>\n\ntext \\<open>\n  A \\emph{vector space} is a non-empty set @{text V} of elements from\n  @{typ 'a} with the following vector space laws: The set @{text V} is\n  closed under addition and scalar multiplication, addition is\n  associative and commutative; @{text \"- x\"} is the inverse of @{text\n  x} w.~r.~t.~addition and @{text 0} is the neutral element of\n  addition.  Addition and multiplication are distributive; scalar\n  multiplication is associative and the real number @{text \"1\"} is\n  the neutral element of scalar multiplication.\n\\<close>\n\nlocale vectorspace =\n  fixes V\n  assumes non_empty [iff, intro?]: \"V \\<noteq> {}\"\n    and add_closed [iff]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x + y \\<in> V\"\n    and mult_closed [iff]: \"x \\<in> V \\<Longrightarrow> a \\<cdot> x \\<in> V\"\n    and add_assoc: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> z \\<in> V \\<Longrightarrow> (x + y) + z = x + (y + z)\"\n    and add_commute: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x + y = y + x\"\n    and diff_self [simp]: \"x \\<in> V \\<Longrightarrow> x - x = 0\"\n    and add_zero_left [simp]: \"x \\<in> V \\<Longrightarrow> 0 + x = x\"\n    and add_mult_distrib1: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> a \\<cdot> (x + y) = a \\<cdot> x + a \\<cdot> y\"\n    and add_mult_distrib2: \"x \\<in> V \\<Longrightarrow> (a + b) \\<cdot> x = a \\<cdot> x + b \\<cdot> x\"\n    and mult_assoc: \"x \\<in> V \\<Longrightarrow> (a * b) \\<cdot> x = a \\<cdot> (b \\<cdot> x)\"\n    and mult_1 [simp]: \"x \\<in> V \\<Longrightarrow> 1 \\<cdot> x = x\"\n    and negate_eq1: \"x \\<in> V \\<Longrightarrow> - x = (- 1) \\<cdot> x\"\n    and diff_eq1: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x - y = x + - y\"\nbegin\n\nlemma negate_eq2: \"x \\<in> V \\<Longrightarrow> (- 1) \\<cdot> x = - x\"\n  by (rule negate_eq1 [symmetric])\n\nlemma negate_eq2a: \"x \\<in> V \\<Longrightarrow> -1 \\<cdot> x = - x\"\n  by (simp add: negate_eq1)\n\nlemma diff_eq2: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x + - y = x - y\"\n  by (rule diff_eq1 [symmetric])\n\nlemma diff_closed [iff]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x - y \\<in> V\"\n  by (simp add: diff_eq1 negate_eq1)\n\nlemma neg_closed [iff]: \"x \\<in> V \\<Longrightarrow> - x \\<in> V\"\n  by (simp add: negate_eq1)\n\nlemma add_left_commute: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> z \\<in> V \\<Longrightarrow> x + (y + z) = y + (x + z)\"\nproof -\n  assume xyz: \"x \\<in> V\"  \"y \\<in> V\"  \"z \\<in> V\"\n  then have \"x + (y + z) = (x + y) + z\"\n    by (simp only: add_assoc)\n  also from xyz have \"\\<dots> = (y + x) + z\" by (simp only: add_commute)\n  also from xyz have \"\\<dots> = y + (x + z)\" by (simp only: add_assoc)\n  finally show ?thesis .\nqed\n\ntheorems add_ac = add_assoc add_commute add_left_commute\n\n\ntext \\<open>The existence of the zero element of a vector space\n  follows from the non-emptiness of carrier set.\\<close>\n\nlemma zero [iff]: \"0 \\<in> V\"\nproof -\n  from non_empty obtain x where x: \"x \\<in> V\" by blast\n  then have \"0 = x - x\" by (rule diff_self [symmetric])\n  also from x x have \"\\<dots> \\<in> V\" by (rule diff_closed)\n  finally show ?thesis .\nqed\n\nlemma add_zero_right [simp]: \"x \\<in> V \\<Longrightarrow>  x + 0 = x\"\nproof -\n  assume x: \"x \\<in> V\"\n  from this and zero have \"x + 0 = 0 + x\" by (rule add_commute)\n  also from x have \"\\<dots> = x\" by (rule add_zero_left)\n  finally show ?thesis .\nqed\n\nlemma mult_assoc2: \"x \\<in> V \\<Longrightarrow> a \\<cdot> b \\<cdot> x = (a * b) \\<cdot> x\"\n  by (simp only: mult_assoc)\n\nlemma diff_mult_distrib1: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> a \\<cdot> (x - y) = a \\<cdot> x - a \\<cdot> y\"\n  by (simp add: diff_eq1 negate_eq1 add_mult_distrib1 mult_assoc2)\n\nlemma diff_mult_distrib2: \"x \\<in> V \\<Longrightarrow> (a - b) \\<cdot> x = a \\<cdot> x - (b \\<cdot> x)\"\nproof -\n  assume x: \"x \\<in> V\"\n  have \" (a - b) \\<cdot> x = (a + - b) \\<cdot> x\"\n    by simp\n  also from x have \"\\<dots> = a \\<cdot> x + (- b) \\<cdot> x\"\n    by (rule add_mult_distrib2)\n  also from x have \"\\<dots> = a \\<cdot> x + - (b \\<cdot> x)\"\n    by (simp add: negate_eq1 mult_assoc2)\n  also from x have \"\\<dots> = a \\<cdot> x - (b \\<cdot> x)\"\n    by (simp add: diff_eq1)\n  finally show ?thesis .\nqed\n\nlemmas distrib =\n  add_mult_distrib1 add_mult_distrib2\n  diff_mult_distrib1 diff_mult_distrib2\n\n\ntext \\<open>\\medskip Further derived laws:\\<close>\n\nlemma mult_zero_left [simp]: \"x \\<in> V \\<Longrightarrow> 0 \\<cdot> x = 0\"\nproof -\n  assume x: \"x \\<in> V\"\n  have \"0 \\<cdot> x = (1 - 1) \\<cdot> x\" by simp\n  also have \"\\<dots> = (1 + - 1) \\<cdot> x\" by simp\n  also from x have \"\\<dots> =  1 \\<cdot> x + (- 1) \\<cdot> x\"\n    by (rule add_mult_distrib2)\n  also from x have \"\\<dots> = x + (- 1) \\<cdot> x\" by simp\n  also from x have \"\\<dots> = x + - x\" by (simp add: negate_eq2a)\n  also from x have \"\\<dots> = x - x\" by (simp add: diff_eq2)\n  also from x have \"\\<dots> = 0\" by simp\n  finally show ?thesis .\nqed\n\nlemma mult_zero_right [simp]: \"a \\<cdot> 0 = (0::'a)\"\nproof -\n  have \"a \\<cdot> 0 = a \\<cdot> (0 - (0::'a))\" by simp\n  also have \"\\<dots> =  a \\<cdot> 0 - a \\<cdot> 0\"\n    by (rule diff_mult_distrib1) simp_all\n  also have \"\\<dots> = 0\" by simp\n  finally show ?thesis .\nqed\n\nlemma minus_mult_cancel [simp]: \"x \\<in> V \\<Longrightarrow> (- a) \\<cdot> - x = a \\<cdot> x\"\n  by (simp add: negate_eq1 mult_assoc2)\n\nlemma add_minus_left_eq_diff: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> - x + y = y - x\"\nproof -\n  assume xy: \"x \\<in> V\"  \"y \\<in> V\"\n  then have \"- x + y = y + - x\" by (simp add: add_commute)\n  also from xy have \"\\<dots> = y - x\" by (simp add: diff_eq1)\n  finally show ?thesis .\nqed\n\nlemma add_minus [simp]: \"x \\<in> V \\<Longrightarrow> x + - x = 0\"\n  by (simp add: diff_eq2)\n\nlemma add_minus_left [simp]: \"x \\<in> V \\<Longrightarrow> - x + x = 0\"\n  by (simp add: diff_eq2 add_commute)\n\nlemma minus_minus [simp]: \"x \\<in> V \\<Longrightarrow> - (- x) = x\"\n  by (simp add: negate_eq1 mult_assoc2)\n\nlemma minus_zero [simp]: \"- (0::'a) = 0\"\n  by (simp add: negate_eq1)\n\nlemma minus_zero_iff [simp]:\n  assumes x: \"x \\<in> V\"\n  shows \"(- x = 0) = (x = 0)\"\nproof\n  from x have \"x = - (- x)\" by simp\n  also assume \"- x = 0\"\n  also have \"- \\<dots> = 0\" by (rule minus_zero)\n  finally show \"x = 0\" .\nnext\n  assume \"x = 0\"\n  then show \"- x = 0\" by simp\nqed\n\nlemma add_minus_cancel [simp]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x + (- x + y) = y\"\n  by (simp add: add_assoc [symmetric])\n\nlemma minus_add_cancel [simp]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> - x + (x + y) = y\"\n  by (simp add: add_assoc [symmetric])\n\nlemma minus_add_distrib [simp]: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> - (x + y) = - x + - y\"\n  by (simp add: negate_eq1 add_mult_distrib1)\n\nlemma diff_zero [simp]: \"x \\<in> V \\<Longrightarrow> x - 0 = x\"\n  by (simp add: diff_eq1)\n\nlemma diff_zero_right [simp]: \"x \\<in> V \\<Longrightarrow> 0 - x = - x\"\n  by (simp add: diff_eq1)\n\nlemma add_left_cancel:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and z: \"z \\<in> V\"\n  shows \"(x + y = x + z) = (y = z)\"\nproof\n  from y have \"y = 0 + y\" by simp\n  also from x y have \"\\<dots> = (- x + x) + y\" by simp\n  also from x y have \"\\<dots> = - x + (x + y)\" by (simp add: add.assoc)\n  also assume \"x + y = x + z\"\n  also from x z have \"- x + (x + z) = - x + x + z\" by (simp add: add.assoc)\n  also from x z have \"\\<dots> = z\" by simp\n  finally show \"y = z\" .\nnext\n  assume \"y = z\"\n  then show \"x + y = x + z\" by (simp only:)\nqed\n\nlemma add_right_cancel: \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> z \\<in> V \\<Longrightarrow> (y + x = z + x) = (y = z)\"\n  by (simp only: add_commute add_left_cancel)\n\nlemma add_assoc_cong:\n  \"x \\<in> V \\<Longrightarrow> y \\<in> V \\<Longrightarrow> x' \\<in> V \\<Longrightarrow> y' \\<in> V \\<Longrightarrow> z \\<in> V\n    \\<Longrightarrow> x + y = x' + y' \\<Longrightarrow> x + (y + z) = x' + (y' + z)\"\n  by (simp only: add_assoc [symmetric])\n\nlemma mult_left_commute: \"x \\<in> V \\<Longrightarrow> a \\<cdot> b \\<cdot> x = b \\<cdot> a \\<cdot> x\"\n  by (simp add: mult.commute mult_assoc2)\n\nlemma mult_zero_uniq:\n  assumes x: \"x \\<in> V\"  \"x \\<noteq> 0\" and ax: \"a \\<cdot> x = 0\"\n  shows \"a = 0\"\nproof (rule classical)\n  assume a: \"a \\<noteq> 0\"\n  from x a have \"x = (inverse a * a) \\<cdot> x\" by simp\n  also from \\<open>x \\<in> V\\<close> have \"\\<dots> = inverse a \\<cdot> (a \\<cdot> x)\" by (rule mult_assoc)\n  also from ax have \"\\<dots> = inverse a \\<cdot> 0\" by simp\n  also have \"\\<dots> = 0\" by simp\n  finally have \"x = 0\" .\n  with \\<open>x \\<noteq> 0\\<close> show \"a = 0\" by contradiction\nqed\n\nlemma mult_left_cancel:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and a: \"a \\<noteq> 0\"\n  shows \"(a \\<cdot> x = a \\<cdot> y) = (x = y)\"\nproof\n  from x have \"x = 1 \\<cdot> x\" by simp\n  also from a have \"\\<dots> = (inverse a * a) \\<cdot> x\" by simp\n  also from x have \"\\<dots> = inverse a \\<cdot> (a \\<cdot> x)\"\n    by (simp only: mult_assoc)\n  also assume \"a \\<cdot> x = a \\<cdot> y\"\n  also from a y have \"inverse a \\<cdot> \\<dots> = y\"\n    by (simp add: mult_assoc2)\n  finally show \"x = y\" .\nnext\n  assume \"x = y\"\n  then show \"a \\<cdot> x = a \\<cdot> y\" by (simp only:)\nqed\n\nlemma mult_right_cancel:\n  assumes x: \"x \\<in> V\" and neq: \"x \\<noteq> 0\"\n  shows \"(a \\<cdot> x = b \\<cdot> x) = (a = b)\"\nproof\n  from x have \"(a - b) \\<cdot> x = a \\<cdot> x - b \\<cdot> x\"\n    by (simp add: diff_mult_distrib2)\n  also assume \"a \\<cdot> x = b \\<cdot> x\"\n  with x have \"a \\<cdot> x - b \\<cdot> x = 0\" by simp\n  finally have \"(a - b) \\<cdot> x = 0\" .\n  with x neq have \"a - b = 0\" by (rule mult_zero_uniq)\n  then show \"a = b\" by simp\nnext\n  assume \"a = b\"\n  then show \"a \\<cdot> x = b \\<cdot> x\" by (simp only:)\nqed\n\nlemma eq_diff_eq:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and z: \"z \\<in> V\"\n  shows \"(x = z - y) = (x + y = z)\"\nproof\n  assume \"x = z - y\"\n  then have \"x + y = z - y + y\" by simp\n  also from y z have \"\\<dots> = z + - y + y\"\n    by (simp add: diff_eq1)\n  also have \"\\<dots> = z + (- y + y)\"\n    by (rule add_assoc) (simp_all add: y z)\n  also from y z have \"\\<dots> = z + 0\"\n    by (simp only: add_minus_left)\n  also from z have \"\\<dots> = z\"\n    by (simp only: add_zero_right)\n  finally show \"x + y = z\" .\nnext\n  assume \"x + y = z\"\n  then have \"z - y = (x + y) - y\" by simp\n  also from x y have \"\\<dots> = x + y + - y\"\n    by (simp add: diff_eq1)\n  also have \"\\<dots> = x + (y + - y)\"\n    by (rule add_assoc) (simp_all add: x y)\n  also from x y have \"\\<dots> = x\" by simp\n  finally show \"x = z - y\" ..\nqed\n\nlemma add_minus_eq_minus:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and xy: \"x + y = 0\"\n  shows \"x = - y\"\nproof -\n  from x y have \"x = (- y + y) + x\" by simp\n  also from x y have \"\\<dots> = - y + (x + y)\" by (simp add: add_ac)\n  also note xy\n  also from y have \"- y + 0 = - y\" by simp\n  finally show \"x = - y\" .\nqed\n\nlemma add_minus_eq:\n  assumes x: \"x \\<in> V\" and y: \"y \\<in> V\" and xy: \"x - y = 0\"\n  shows \"x = y\"\nproof -\n  from x y xy have eq: \"x + - y = 0\" by (simp add: diff_eq1)\n  with _ _ have \"x = - (- y)\"\n    by (rule add_minus_eq_minus) (simp_all add: x y)\n  with x y show \"x = y\" by simp\nqed\n\nlemma add_diff_swap:\n  assumes vs: \"a \\<in> V\"  \"b \\<in> V\"  \"c \\<in> V\"  \"d \\<in> V\"\n    and eq: \"a + b = c + d\"\n  shows \"a - c = d - b\"\nproof -\n  from assms have \"- c + (a + b) = - c + (c + d)\"\n    by (simp add: add_left_cancel)\n  also have \"\\<dots> = d\" using \\<open>c \\<in> V\\<close> \\<open>d \\<in> V\\<close> by (rule minus_add_cancel)\n  finally have eq: \"- c + (a + b) = d\" .\n  from vs have \"a - c = (- c + (a + b)) + - b\"\n    by (simp add: add_ac diff_eq1)\n  also from vs eq have \"\\<dots>  = d + - b\"\n    by (simp add: add_right_cancel)\n  also from vs have \"\\<dots> = d - b\" by (simp add: diff_eq2)\n  finally show \"a - c = d - b\" .\nqed\n\nlemma vs_add_cancel_21:\n  assumes vs: \"x \\<in> V\"  \"y \\<in> V\"  \"z \\<in> V\"  \"u \\<in> V\"\n  shows \"(x + (y + z) = y + u) = (x + z = u)\"\nproof\n  from vs have \"x + z = - y + y + (x + z)\" by simp\n  also have \"\\<dots> = - y + (y + (x + z))\"\n    by (rule add_assoc) (simp_all add: vs)\n  also from vs have \"y + (x + z) = x + (y + z)\"\n    by (simp add: add_ac)\n  also assume \"x + (y + z) = y + u\"\n  also from vs have \"- y + (y + u) = u\" by simp\n  finally show \"x + z = u\" .\nnext\n  assume \"x + z = u\"\n  with vs show \"x + (y + z) = y + u\"\n    by (simp only: add_left_commute [of x])\nqed\n\nlemma add_cancel_end:\n  assumes vs: \"x \\<in> V\"  \"y \\<in> V\"  \"z \\<in> V\"\n  shows \"(x + (y + z) = y) = (x = - z)\"\nproof\n  assume \"x + (y + z) = y\"\n  with vs have \"(x + z) + y = 0 + y\" by (simp add: add_ac)\n  with vs have \"x + z = 0\" by (simp only: add_right_cancel add_closed zero)\n  with vs show \"x = - z\" by (simp add: add_minus_eq_minus)\nnext\n  assume eq: \"x = - z\"\n  then have \"x + (y + z) = - z + (y + z)\" by simp\n  also have \"\\<dots> = y + (- z + z)\" by (rule add_left_commute) (simp_all add: vs)\n  also from vs have \"\\<dots> = y\"  by simp\n  finally show \"x + (y + z) = y\" .\nqed\n\nend\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Hahn_Banach/Vector_Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.8757869948899665, "lm_q1q2_score": 0.762457765458772}}
{"text": "(*  Title:      HOL/Number_Theory/Cong.thy\n    Authors:    Christophe Tabacznyj, Lawrence C. Paulson, Amine Chaieb,\n                Thomas M. Rasmussen, Jeremy Avigad\n\nDefines congruence (notation: [x = y] (mod z)) for natural numbers and\nintegers.\n\nThis file combines and revises a number of prior developments.\n\nThe original theories \"GCD\" and \"Primes\" were by Christophe Tabacznyj\nand Lawrence C. Paulson, based on @{cite davenport92}. They introduced\ngcd, lcm, and prime for the natural numbers.\n\nThe original theory \"IntPrimes\" was by Thomas M. Rasmussen, and\nextended gcd, lcm, primes to the integers. Amine Chaieb provided\nanother extension of the notions to the integers, and added a number\nof results to \"Primes\" and \"GCD\".\n\nThe original theory, \"IntPrimes\", by Thomas M. Rasmussen, defined and\ndeveloped the congruence relations on the integers. The notion was\nextended to the natural numbers by Chaieb. Jeremy Avigad combined\nthese, revised and tidied them, made the development uniform for the\nnatural numbers and the integers, and added a number of new theorems.\n*)\n\nsection {* Congruence *}\n\ntheory Cong\nimports Primes\nbegin\n\nsubsection {* Turn off @{text One_nat_def} *}\n\nlemma power_eq_one_eq_nat [simp]: \"((x::nat)^m = 1) = (m = 0 | x = 1)\"\n  by (induct m) auto\n\ndeclare mod_pos_pos_trivial [simp]\n\n\nsubsection {* Main definitions *}\n\nclass cong =\n  fixes cong :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (\"(1[_ = _] '(()mod _'))\")\nbegin\n\nabbreviation notcong :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (\"(1[_ \\<noteq> _] '(()mod _'))\")\n  where \"notcong x y m \\<equiv> \\<not> cong x y m\"\n\nend\n\n(* definitions for the natural numbers *)\n\ninstantiation nat :: cong\nbegin\n\ndefinition cong_nat :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where \"cong_nat x y m = ((x mod m) = (y mod m))\"\n\ninstance ..\n\nend\n\n\n(* definitions for the integers *)\n\ninstantiation int :: cong\nbegin\n\ndefinition cong_int :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> bool\"\n  where \"cong_int x y m = ((x mod m) = (y mod m))\"\n\ninstance ..\n\nend\n\n\nsubsection {* Set up Transfer *}\n\n\nlemma transfer_nat_int_cong:\n  \"(x::int) >= 0 \\<Longrightarrow> y >= 0 \\<Longrightarrow> m >= 0 \\<Longrightarrow>\n    ([(nat x) = (nat y)] (mod (nat m))) = ([x = y] (mod m))\"\n  unfolding cong_int_def cong_nat_def\n  by (metis Divides.transfer_int_nat_functions(2) nat_0_le nat_mod_distrib)\n\n\ndeclare transfer_morphism_nat_int[transfer add return:\n    transfer_nat_int_cong]\n\nlemma transfer_int_nat_cong:\n  \"[(int x) = (int y)] (mod (int m)) = [x = y] (mod m)\"\n  apply (auto simp add: cong_int_def cong_nat_def)\n  apply (auto simp add: zmod_int [symmetric])\n  done\n\ndeclare transfer_morphism_int_nat[transfer add return:\n    transfer_int_nat_cong]\n\n\nsubsection {* Congruence *}\n\n(* was zcong_0, etc. *)\nlemma cong_0_nat [simp, presburger]: \"([(a::nat) = b] (mod 0)) = (a = b)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_0_int [simp, presburger]: \"([(a::int) = b] (mod 0)) = (a = b)\"\n  unfolding cong_int_def by auto\n\nlemma cong_1_nat [simp, presburger]: \"[(a::nat) = b] (mod 1)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_Suc_0_nat [simp, presburger]: \"[(a::nat) = b] (mod Suc 0)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_1_int [simp, presburger]: \"[(a::int) = b] (mod 1)\"\n  unfolding cong_int_def by auto\n\nlemma cong_refl_nat [simp]: \"[(k::nat) = k] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_refl_int [simp]: \"[(k::int) = k] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_sym_nat: \"[(a::nat) = b] (mod m) \\<Longrightarrow> [b = a] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_sym_int: \"[(a::int) = b] (mod m) \\<Longrightarrow> [b = a] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_sym_eq_nat: \"[(a::nat) = b] (mod m) = [b = a] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_sym_eq_int: \"[(a::int) = b] (mod m) = [b = a] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_trans_nat [trans]:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow> [b = c] (mod m) \\<Longrightarrow> [a = c] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_trans_int [trans]:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [b = c] (mod m) \\<Longrightarrow> [a = c] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_add_nat:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a + c = b + d] (mod m)\"\n  unfolding cong_nat_def  by (metis mod_add_cong)\n\nlemma cong_add_int:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a + c = b + d] (mod m)\"\n  unfolding cong_int_def  by (metis mod_add_cong)\n\nlemma cong_diff_int:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a - c = b - d] (mod m)\"\n  unfolding cong_int_def  by (metis mod_diff_cong) \n\nlemma cong_diff_aux_int:\n  \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow>\n   (a::int) >= c \\<Longrightarrow> b >= d \\<Longrightarrow> [tsub a c = tsub b d] (mod m)\"\n  by (metis cong_diff_int tsub_eq)\n\nlemma cong_diff_nat:\n  assumes\"[a = b] (mod m)\" \"[c = d] (mod m)\" \"(a::nat) >= c\" \"b >= d\" \n  shows \"[a - c = b - d] (mod m)\"\n  using assms by (rule cong_diff_aux_int [transferred])\n\nlemma cong_mult_nat:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a * c = b * d] (mod m)\"\n  unfolding cong_nat_def  by (metis mod_mult_cong) \n\nlemma cong_mult_int:\n    \"[(a::int) = b] (mod m) \\<Longrightarrow> [c = d] (mod m) \\<Longrightarrow> [a * c = b * d] (mod m)\"\n  unfolding cong_int_def  by (metis mod_mult_cong) \n\nlemma cong_exp_nat: \"[(x::nat) = y] (mod n) \\<Longrightarrow> [x^k = y^k] (mod n)\"\n  by (induct k) (auto simp add: cong_mult_nat)\n\nlemma cong_exp_int: \"[(x::int) = y] (mod n) \\<Longrightarrow> [x^k = y^k] (mod n)\"\n  by (induct k) (auto simp add: cong_mult_int)\n\nlemma cong_setsum_nat [rule_format]:\n    \"(ALL x: A. [((f x)::nat) = g x] (mod m)) \\<longrightarrow>\n      [(SUM x:A. f x) = (SUM x:A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_add_nat)\n  done\n\nlemma cong_setsum_int [rule_format]:\n    \"(ALL x: A. [((f x)::int) = g x] (mod m)) \\<longrightarrow>\n      [(SUM x:A. f x) = (SUM x:A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_add_int)\n  done\n\nlemma cong_setprod_nat [rule_format]:\n    \"(ALL x: A. [((f x)::nat) = g x] (mod m)) \\<longrightarrow>\n      [(PROD x:A. f x) = (PROD x:A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_mult_nat)\n  done\n\nlemma cong_setprod_int [rule_format]:\n    \"(ALL x: A. [((f x)::int) = g x] (mod m)) \\<longrightarrow>\n      [(PROD x:A. f x) = (PROD x:A. g x)] (mod m)\"\n  apply (cases \"finite A\")\n  apply (induct set: finite)\n  apply (auto intro: cong_mult_int)\n  done\n\nlemma cong_scalar_nat: \"[(a::nat)= b] (mod m) \\<Longrightarrow> [a * k = b * k] (mod m)\"\n  by (rule cong_mult_nat) simp_all\n\nlemma cong_scalar_int: \"[(a::int)= b] (mod m) \\<Longrightarrow> [a * k = b * k] (mod m)\"\n  by (rule cong_mult_int) simp_all\n\nlemma cong_scalar2_nat: \"[(a::nat)= b] (mod m) \\<Longrightarrow> [k * a = k * b] (mod m)\"\n  by (rule cong_mult_nat) simp_all\n\nlemma cong_scalar2_int: \"[(a::int)= b] (mod m) \\<Longrightarrow> [k * a = k * b] (mod m)\"\n  by (rule cong_mult_int) simp_all\n\nlemma cong_mult_self_nat: \"[(a::nat) * m = 0] (mod m)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_mult_self_int: \"[(a::int) * m = 0] (mod m)\"\n  unfolding cong_int_def by auto\n\nlemma cong_eq_diff_cong_0_int: \"[(a::int) = b] (mod m) = [a - b = 0] (mod m)\"\n  by (metis cong_add_int cong_diff_int cong_refl_int diff_add_cancel diff_self)\n\nlemma cong_eq_diff_cong_0_aux_int: \"a >= b \\<Longrightarrow>\n    [(a::int) = b] (mod m) = [tsub a b = 0] (mod m)\"\n  by (subst tsub_eq, assumption, rule cong_eq_diff_cong_0_int)\n\nlemma cong_eq_diff_cong_0_nat:\n  assumes \"(a::nat) >= b\"\n  shows \"[a = b] (mod m) = [a - b = 0] (mod m)\"\n  using assms by (rule cong_eq_diff_cong_0_aux_int [transferred])\n\nlemma cong_diff_cong_0'_nat:\n  \"[(x::nat) = y] (mod n) \\<longleftrightarrow>\n    (if x <= y then [y - x = 0] (mod n) else [x - y = 0] (mod n))\"\n  by (metis cong_eq_diff_cong_0_nat cong_sym_nat nat_le_linear)\n\nlemma cong_altdef_nat: \"(a::nat) >= b \\<Longrightarrow> [a = b] (mod m) = (m dvd (a - b))\"\n  apply (subst cong_eq_diff_cong_0_nat, assumption)\n  apply (unfold cong_nat_def)\n  apply (simp add: dvd_eq_mod_eq_0 [symmetric])\n  done\n\nlemma cong_altdef_int: \"[(a::int) = b] (mod m) = (m dvd (a - b))\"\n  by (metis cong_int_def zmod_eq_dvd_iff)\n\nlemma cong_abs_int: \"[(x::int) = y] (mod abs m) = [x = y] (mod m)\"\n  by (simp add: cong_altdef_int)\n\nlemma cong_square_int:\n  fixes a::int\n  shows \"\\<lbrakk> prime p; 0 < a; [a * a = 1] (mod p) \\<rbrakk>\n    \\<Longrightarrow> [a = 1] (mod p) \\<or> [a = - 1] (mod p)\"\n  apply (simp only: cong_altdef_int)\n  apply (subst prime_dvd_mult_eq_int [symmetric], assumption)\n  apply (auto simp add: field_simps)\n  done\n\nlemma cong_mult_rcancel_int:\n    \"coprime k (m::int) \\<Longrightarrow> [a * k = b * k] (mod m) = [a = b] (mod m)\"\n  by (metis cong_altdef_int left_diff_distrib coprime_dvd_mult_iff_int gcd_int.commute)\n\nlemma cong_mult_rcancel_nat:\n    \"coprime k (m::nat) \\<Longrightarrow> [a * k = b * k] (mod m) = [a = b] (mod m)\"\n  by (metis cong_mult_rcancel_int [transferred])\n\nlemma cong_mult_lcancel_nat:\n    \"coprime k (m::nat) \\<Longrightarrow> [k * a = k * b ] (mod m) = [a = b] (mod m)\"\n  by (simp add: mult.commute cong_mult_rcancel_nat)\n\nlemma cong_mult_lcancel_int:\n    \"coprime k (m::int) \\<Longrightarrow> [k * a = k * b] (mod m) = [a = b] (mod m)\"\n  by (simp add: mult.commute cong_mult_rcancel_int)\n\n(* was zcong_zgcd_zmult_zmod *)\nlemma coprime_cong_mult_int:\n  \"[(a::int) = b] (mod m) \\<Longrightarrow> [a = b] (mod n) \\<Longrightarrow> coprime m n\n    \\<Longrightarrow> [a = b] (mod m * n)\"\nby (metis divides_mult_int cong_altdef_int)\n\nlemma coprime_cong_mult_nat:\n  assumes \"[(a::nat) = b] (mod m)\" and \"[a = b] (mod n)\" and \"coprime m n\"\n  shows \"[a = b] (mod m * n)\"\n  by (metis assms coprime_cong_mult_int [transferred])\n\nlemma cong_less_imp_eq_nat: \"0 \\<le> (a::nat) \\<Longrightarrow>\n    a < m \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> b < m \\<Longrightarrow> [a = b] (mod m) \\<Longrightarrow> a = b\"\n  by (auto simp add: cong_nat_def)\n\nlemma cong_less_imp_eq_int: \"0 \\<le> (a::int) \\<Longrightarrow>\n    a < m \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> b < m \\<Longrightarrow> [a = b] (mod m) \\<Longrightarrow> a = b\"\n  by (auto simp add: cong_int_def)\n\nlemma cong_less_unique_nat:\n    \"0 < (m::nat) \\<Longrightarrow> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  by (auto simp: cong_nat_def) (metis mod_less_divisor mod_mod_trivial)\n\nlemma cong_less_unique_int:\n    \"0 < (m::int) \\<Longrightarrow> (\\<exists>!b. 0 \\<le> b \\<and> b < m \\<and> [a = b] (mod m))\"\n  by (auto simp: cong_int_def)  (metis mod_mod_trivial pos_mod_conj)\n\nlemma cong_iff_lin_int: \"([(a::int) = b] (mod m)) = (\\<exists>k. b = a + m * k)\"\n  apply (auto simp add: cong_altdef_int dvd_def)\n  apply (rule_tac [!] x = \"-k\" in exI, auto)\n  done\n\nlemma cong_iff_lin_nat: \n   \"([(a::nat) = b] (mod m)) \\<longleftrightarrow> (\\<exists>k1 k2. b + k1 * m = a + k2 * m)\" (is \"?lhs = ?rhs\")\nproof (rule iffI)\n  assume eqm: ?lhs\n  show ?rhs\n  proof (cases \"b \\<le> a\")\n    case True\n    then show ?rhs using eqm\n      by (metis cong_altdef_nat dvd_def le_add_diff_inverse add_0_right mult_0 mult.commute)\n  next\n    case False\n    then show ?rhs using eqm \n      apply (subst (asm) cong_sym_eq_nat)\n      apply (auto simp: cong_altdef_nat)\n      apply (metis add_0_right add_diff_inverse dvd_div_mult_self less_or_eq_imp_le mult_0)\n      done\n  qed\nnext\n  assume ?rhs\n  then show ?lhs\n    by (metis cong_nat_def mod_mult_self2 mult.commute)\nqed\n\nlemma cong_gcd_eq_int: \"[(a::int) = b] (mod m) \\<Longrightarrow> gcd a m = gcd b m\"\n  by (metis cong_int_def gcd_red_int)\n\nlemma cong_gcd_eq_nat:\n    \"[(a::nat) = b] (mod m) \\<Longrightarrow>gcd a m = gcd b m\"\n  by (metis assms cong_gcd_eq_int [transferred])\n\nlemma cong_imp_coprime_nat: \"[(a::nat) = b] (mod m) \\<Longrightarrow> coprime a m \\<Longrightarrow> coprime b m\"\n  by (auto simp add: cong_gcd_eq_nat)\n\nlemma cong_imp_coprime_int: \"[(a::int) = b] (mod m) \\<Longrightarrow> coprime a m \\<Longrightarrow> coprime b m\"\n  by (auto simp add: cong_gcd_eq_int)\n\nlemma cong_cong_mod_nat: \"[(a::nat) = b] (mod m) = [a mod m = b mod m] (mod m)\"\n  by (auto simp add: cong_nat_def)\n\nlemma cong_cong_mod_int: \"[(a::int) = b] (mod m) = [a mod m = b mod m] (mod m)\"\n  by (auto simp add: cong_int_def)\n\nlemma cong_minus_int [iff]: \"[(a::int) = b] (mod -m) = [a = b] (mod m)\"\n  by (metis cong_iff_lin_int minus_equation_iff mult_minus_left mult_minus_right)\n\n(*\nlemma mod_dvd_mod_int:\n    \"0 < (m::int) \\<Longrightarrow> m dvd b \\<Longrightarrow> (a mod b mod m) = (a mod m)\"\n  apply (unfold dvd_def, auto)\n  apply (rule mod_mod_cancel)\n  apply auto\n  done\n\nlemma mod_dvd_mod:\n  assumes \"0 < (m::nat)\" and \"m dvd b\"\n  shows \"(a mod b mod m) = (a mod m)\"\n\n  apply (rule mod_dvd_mod_int [transferred])\n  using assms apply auto\n  done\n*)\n\nlemma cong_add_lcancel_nat:\n    \"[(a::nat) + x = a + y] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_lcancel_int:\n    \"[(a::int) + x = a + y] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_add_rcancel_nat: \"[(x::nat) + a = y + a] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_rcancel_int: \"[(x::int) + a = y + a] (mod n) \\<longleftrightarrow> [x = y] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_add_lcancel_0_nat: \"[(a::nat) + x = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_lcancel_0_int: \"[(a::int) + x = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_add_rcancel_0_nat: \"[x + (a::nat) = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_nat)\n\nlemma cong_add_rcancel_0_int: \"[x + (a::int) = a] (mod n) \\<longleftrightarrow> [x = 0] (mod n)\"\n  by (simp add: cong_iff_lin_int)\n\nlemma cong_dvd_modulus_nat: \"[(x::nat) = y] (mod m) \\<Longrightarrow> n dvd m \\<Longrightarrow>\n    [x = y] (mod n)\"\n  apply (auto simp add: cong_iff_lin_nat dvd_def)\n  apply (rule_tac x=\"k1 * k\" in exI)\n  apply (rule_tac x=\"k2 * k\" in exI)\n  apply (simp add: field_simps)\n  done\n\nlemma cong_dvd_modulus_int: \"[(x::int) = y] (mod m) \\<Longrightarrow> n dvd m \\<Longrightarrow> [x = y] (mod n)\"\n  by (auto simp add: cong_altdef_int dvd_def)\n\nlemma cong_dvd_eq_nat: \"[(x::nat) = y] (mod n) \\<Longrightarrow> n dvd x \\<longleftrightarrow> n dvd y\"\n  unfolding cong_nat_def by (auto simp add: dvd_eq_mod_eq_0)\n\nlemma cong_dvd_eq_int: \"[(x::int) = y] (mod n) \\<Longrightarrow> n dvd x \\<longleftrightarrow> n dvd y\"\n  unfolding cong_int_def by (auto simp add: dvd_eq_mod_eq_0)\n\nlemma cong_mod_nat: \"(n::nat) ~= 0 \\<Longrightarrow> [a mod n = a] (mod n)\"\n  by (simp add: cong_nat_def)\n\nlemma cong_mod_int: \"(n::int) ~= 0 \\<Longrightarrow> [a mod n = a] (mod n)\"\n  by (simp add: cong_int_def)\n\nlemma mod_mult_cong_nat: \"(a::nat) ~= 0 \\<Longrightarrow> b ~= 0\n    \\<Longrightarrow> [x mod (a * b) = y] (mod a) \\<longleftrightarrow> [x = y] (mod a)\"\n  by (simp add: cong_nat_def mod_mult2_eq  mod_add_left_eq)\n\nlemma neg_cong_int: \"([(a::int) = b] (mod m)) = ([-a = -b] (mod m))\"\n  by (metis cong_int_def minus_minus zminus_zmod)\n\nlemma cong_modulus_neg_int: \"([(a::int) = b] (mod m)) = ([a = b] (mod -m))\"\n  by (auto simp add: cong_altdef_int)\n\nlemma mod_mult_cong_int: \"(a::int) ~= 0 \\<Longrightarrow> b ~= 0\n    \\<Longrightarrow> [x mod (a * b) = y] (mod a) \\<longleftrightarrow> [x = y] (mod a)\"\n  apply (cases \"b > 0\", simp add: cong_int_def mod_mod_cancel mod_add_left_eq)\n  apply (subst (1 2) cong_modulus_neg_int)\n  apply (unfold cong_int_def)\n  apply (subgoal_tac \"a * b = (-a * -b)\")\n  apply (erule ssubst)\n  apply (subst zmod_zmult2_eq)\n  apply (auto simp add: mod_add_left_eq mod_minus_right div_minus_right)\n  apply (metis mod_diff_left_eq mod_diff_right_eq mod_mult_self1_is_0 semiring_numeral_div_class.diff_zero)+\n  done\n\nlemma cong_to_1_nat: \"([(a::nat) = 1] (mod n)) \\<Longrightarrow> (n dvd (a - 1))\"\n  apply (cases \"a = 0\", force)\n  by (metis cong_altdef_nat leI less_one)\n\nlemma cong_0_1_nat': \"[(0::nat) = Suc 0] (mod n) = (n = Suc 0)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_0_1_nat: \"[(0::nat) = 1] (mod n) = (n = 1)\"\n  unfolding cong_nat_def by auto\n\nlemma cong_0_1_int: \"[(0::int) = 1] (mod n) = ((n = 1) | (n = -1))\"\n  unfolding cong_int_def by (auto simp add: zmult_eq_1_iff)\n\nlemma cong_to_1'_nat: \"[(a::nat) = 1] (mod n) \\<longleftrightarrow>\n    a = 0 \\<and> n = 1 \\<or> (\\<exists>m. a = 1 + m * n)\"\n  apply (cases \"n = 1\")\n  apply auto [1]\n  apply (drule_tac x = \"a - 1\" in spec)\n  apply force\n  apply (cases \"a = 0\", simp add: cong_0_1_nat)\n  apply (rule iffI)\n  apply (metis cong_to_1_nat dvd_def monoid_mult_class.mult.right_neutral mult.commute mult_eq_if)\n  apply (metis cong_add_lcancel_0_nat cong_mult_self_nat)\n  done\n\nlemma cong_le_nat: \"(y::nat) <= x \\<Longrightarrow> [x = y] (mod n) \\<longleftrightarrow> (\\<exists>q. x = q * n + y)\"\n  by (metis cong_altdef_nat Nat.le_imp_diff_is_add dvd_def mult.commute)\n\nlemma cong_solve_nat: \"(a::nat) \\<noteq> 0 \\<Longrightarrow> EX x. [a * x = gcd a n] (mod n)\"\n  apply (cases \"n = 0\")\n  apply force\n  apply (frule bezout_nat [of a n], auto)\n  by (metis cong_add_rcancel_0_nat cong_mult_self_nat mult.commute)\n\nlemma cong_solve_int: \"(a::int) \\<noteq> 0 \\<Longrightarrow> EX x. [a * x = gcd a n] (mod n)\"\n  apply (cases \"n = 0\")\n  apply (cases \"a \\<ge> 0\")\n  apply auto\n  apply (rule_tac x = \"-1\" in exI)\n  apply auto\n  apply (insert bezout_int [of a n], auto)\n  by (metis cong_iff_lin_int mult.commute)\n\nlemma cong_solve_dvd_nat:\n  assumes a: \"(a::nat) \\<noteq> 0\" and b: \"gcd a n dvd d\"\n  shows \"EX x. [a * x = d] (mod n)\"\nproof -\n  from cong_solve_nat [OF a] obtain x where \"[a * x = gcd a n](mod n)\"\n    by auto\n  then have \"[(d div gcd a n) * (a * x) = (d div gcd a n) * gcd a n] (mod n)\"\n    by (elim cong_scalar2_nat)\n  also from b have \"(d div gcd a n) * gcd a n = d\"\n    by (rule dvd_div_mult_self)\n  also have \"(d div gcd a n) * (a * x) = a * (d div gcd a n * x)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma cong_solve_dvd_int:\n  assumes a: \"(a::int) \\<noteq> 0\" and b: \"gcd a n dvd d\"\n  shows \"EX x. [a * x = d] (mod n)\"\nproof -\n  from cong_solve_int [OF a] obtain x where \"[a * x = gcd a n](mod n)\"\n    by auto\n  then have \"[(d div gcd a n) * (a * x) = (d div gcd a n) * gcd a n] (mod n)\"\n    by (elim cong_scalar2_int)\n  also from b have \"(d div gcd a n) * gcd a n = d\"\n    by (rule dvd_div_mult_self)\n  also have \"(d div gcd a n) * (a * x) = a * (d div gcd a n * x)\"\n    by auto\n  finally show ?thesis\n    by auto\nqed\n\nlemma cong_solve_coprime_nat: \"coprime (a::nat) n \\<Longrightarrow> EX x. [a * x = 1] (mod n)\"\n  apply (cases \"a = 0\")\n  apply force\n  apply (metis cong_solve_nat)\n  done\n\nlemma cong_solve_coprime_int: \"coprime (a::int) n \\<Longrightarrow> EX x. [a * x = 1] (mod n)\"\n  apply (cases \"a = 0\")\n  apply auto\n  apply (cases \"n \\<ge> 0\")\n  apply auto\n  apply (metis cong_solve_int)\n  done\n\nlemma coprime_iff_invertible_nat: \"m > 0 \\<Longrightarrow> coprime a m = (EX x. [a * x = Suc 0] (mod m))\"\n  apply (auto intro: cong_solve_coprime_nat simp: One_nat_def)\n  apply (metis cong_Suc_0_nat cong_solve_nat gcd_nat.left_neutral)\n  apply (metis One_nat_def cong_gcd_eq_nat coprime_lmult_nat \n      gcd_lcm_complete_lattice_nat.inf_bot_right gcd_nat.commute)\n  done\n\nlemma coprime_iff_invertible_int: \"m > (0::int) \\<Longrightarrow> coprime a m = (EX x. [a * x = 1] (mod m))\"\n  apply (auto intro: cong_solve_coprime_int)\n  apply (metis cong_int_def coprime_mul_eq_int gcd_1_int gcd_int.commute gcd_red_int)\n  done\n\nlemma coprime_iff_invertible'_nat: \"m > 0 \\<Longrightarrow> coprime a m =\n    (EX x. 0 \\<le> x & x < m & [a * x = Suc 0] (mod m))\"\n  apply (subst coprime_iff_invertible_nat)\n  apply auto\n  apply (auto simp add: cong_nat_def)\n  apply (metis mod_less_divisor mod_mult_right_eq)\n  done\n\nlemma coprime_iff_invertible'_int: \"m > (0::int) \\<Longrightarrow> coprime a m =\n    (EX x. 0 <= x & x < m & [a * x = 1] (mod m))\"\n  apply (subst coprime_iff_invertible_int)\n  apply (auto simp add: cong_int_def)\n  apply (metis mod_mult_right_eq pos_mod_conj)\n  done\n\nlemma cong_cong_lcm_nat: \"[(x::nat) = y] (mod a) \\<Longrightarrow>\n    [x = y] (mod b) \\<Longrightarrow> [x = y] (mod lcm a b)\"\n  apply (cases \"y \\<le> x\")\n  apply (metis cong_altdef_nat lcm_least_nat)\n  apply (metis cong_altdef_nat cong_diff_cong_0'_nat lcm_semilattice_nat.sup.bounded_iff le0 minus_nat.diff_0)\n  done\n\nlemma cong_cong_lcm_int: \"[(x::int) = y] (mod a) \\<Longrightarrow>\n    [x = y] (mod b) \\<Longrightarrow> [x = y] (mod lcm a b)\"\n  by (auto simp add: cong_altdef_int lcm_least_int) [1]\n\nlemma cong_cong_setprod_coprime_nat [rule_format]: \"finite A \\<Longrightarrow>\n    (ALL i:A. (ALL j:A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))) \\<longrightarrow>\n    (ALL i:A. [(x::nat) = y] (mod m i)) \\<longrightarrow>\n      [x = y] (mod (PROD i:A. m i))\"\n  apply (induct set: finite)\n  apply auto\n  apply (metis coprime_cong_mult_nat gcd_semilattice_nat.inf_commute setprod_coprime_nat)\n  done\n\nlemma cong_cong_setprod_coprime_int [rule_format]: \"finite A \\<Longrightarrow>\n    (ALL i:A. (ALL j:A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))) \\<longrightarrow>\n    (ALL i:A. [(x::int) = y] (mod m i)) \\<longrightarrow>\n      [x = y] (mod (PROD i:A. m i))\"\n  apply (induct set: finite)\n  apply auto\n  apply (metis coprime_cong_mult_int gcd_int.commute setprod_coprime_int)\n  done\n\nlemma binary_chinese_remainder_aux_nat:\n  assumes a: \"coprime (m1::nat) m2\"\n  shows \"EX b1 b2. [b1 = 1] (mod m1) \\<and> [b1 = 0] (mod m2) \\<and>\n    [b2 = 0] (mod m1) \\<and> [b2 = 1] (mod m2)\"\nproof -\n  from cong_solve_coprime_nat [OF a] obtain x1 where one: \"[m1 * x1 = 1] (mod m2)\"\n    by auto\n  from a have b: \"coprime m2 m1\"\n    by (subst gcd_commute_nat)\n  from cong_solve_coprime_nat [OF b] obtain x2 where two: \"[m2 * x2 = 1] (mod m1)\"\n    by auto\n  have \"[m1 * x1 = 0] (mod m1)\"\n    by (subst mult.commute, rule cong_mult_self_nat)\n  moreover have \"[m2 * x2 = 0] (mod m2)\"\n    by (subst mult.commute, rule cong_mult_self_nat)\n  moreover note one two\n  ultimately show ?thesis by blast\nqed\n\nlemma binary_chinese_remainder_aux_int:\n  assumes a: \"coprime (m1::int) m2\"\n  shows \"EX b1 b2. [b1 = 1] (mod m1) \\<and> [b1 = 0] (mod m2) \\<and>\n    [b2 = 0] (mod m1) \\<and> [b2 = 1] (mod m2)\"\nproof -\n  from cong_solve_coprime_int [OF a] obtain x1 where one: \"[m1 * x1 = 1] (mod m2)\"\n    by auto\n  from a have b: \"coprime m2 m1\"\n    by (subst gcd_commute_int)\n  from cong_solve_coprime_int [OF b] obtain x2 where two: \"[m2 * x2 = 1] (mod m1)\"\n    by auto\n  have \"[m1 * x1 = 0] (mod m1)\"\n    by (subst mult.commute, rule cong_mult_self_int)\n  moreover have \"[m2 * x2 = 0] (mod m2)\"\n    by (subst mult.commute, rule cong_mult_self_int)\n  moreover note one two\n  ultimately show ?thesis by blast\nqed\n\nlemma binary_chinese_remainder_nat:\n  assumes a: \"coprime (m1::nat) m2\"\n  shows \"EX x. [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  from binary_chinese_remainder_aux_nat [OF a] obtain b1 b2\n      where \"[b1 = 1] (mod m1)\" and \"[b1 = 0] (mod m2)\" and\n            \"[b2 = 0] (mod m1)\" and \"[b2 = 1] (mod m2)\"\n    by blast\n  let ?x = \"u1 * b1 + u2 * b2\"\n  have \"[?x = u1 * 1 + u2 * 0] (mod m1)\"\n    apply (rule cong_add_nat)\n    apply (rule cong_scalar2_nat)\n    apply (rule `[b1 = 1] (mod m1)`)\n    apply (rule cong_scalar2_nat)\n    apply (rule `[b2 = 0] (mod m1)`)\n    done\n  then have \"[?x = u1] (mod m1)\" by simp\n  have \"[?x = u1 * 0 + u2 * 1] (mod m2)\"\n    apply (rule cong_add_nat)\n    apply (rule cong_scalar2_nat)\n    apply (rule `[b1 = 0] (mod m2)`)\n    apply (rule cong_scalar2_nat)\n    apply (rule `[b2 = 1] (mod m2)`)\n    done\n  then have \"[?x = u2] (mod m2)\" by simp\n  with `[?x = u1] (mod m1)` show ?thesis by blast\nqed\n\nlemma binary_chinese_remainder_int:\n  assumes a: \"coprime (m1::int) m2\"\n  shows \"EX x. [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  from binary_chinese_remainder_aux_int [OF a] obtain b1 b2\n    where \"[b1 = 1] (mod m1)\" and \"[b1 = 0] (mod m2)\" and\n          \"[b2 = 0] (mod m1)\" and \"[b2 = 1] (mod m2)\"\n    by blast\n  let ?x = \"u1 * b1 + u2 * b2\"\n  have \"[?x = u1 * 1 + u2 * 0] (mod m1)\"\n    apply (rule cong_add_int)\n    apply (rule cong_scalar2_int)\n    apply (rule `[b1 = 1] (mod m1)`)\n    apply (rule cong_scalar2_int)\n    apply (rule `[b2 = 0] (mod m1)`)\n    done\n  then have \"[?x = u1] (mod m1)\" by simp\n  have \"[?x = u1 * 0 + u2 * 1] (mod m2)\"\n    apply (rule cong_add_int)\n    apply (rule cong_scalar2_int)\n    apply (rule `[b1 = 0] (mod m2)`)\n    apply (rule cong_scalar2_int)\n    apply (rule `[b2 = 1] (mod m2)`)\n    done\n  then have \"[?x = u2] (mod m2)\" by simp\n  with `[?x = u1] (mod m1)` show ?thesis by blast\nqed\n\nlemma cong_modulus_mult_nat: \"[(x::nat) = y] (mod m * n) \\<Longrightarrow>\n    [x = y] (mod m)\"\n  apply (cases \"y \\<le> x\")\n  apply (simp add: cong_altdef_nat)\n  apply (erule dvd_mult_left)\n  apply (rule cong_sym_nat)\n  apply (subst (asm) cong_sym_eq_nat)\n  apply (simp add: cong_altdef_nat)\n  apply (erule dvd_mult_left)\n  done\n\nlemma cong_modulus_mult_int: \"[(x::int) = y] (mod m * n) \\<Longrightarrow>\n    [x = y] (mod m)\"\n  apply (simp add: cong_altdef_int)\n  apply (erule dvd_mult_left)\n  done\n\nlemma cong_less_modulus_unique_nat:\n    \"[(x::nat) = y] (mod m) \\<Longrightarrow> x < m \\<Longrightarrow> y < m \\<Longrightarrow> x = y\"\n  by (simp add: cong_nat_def)\n\nlemma binary_chinese_remainder_unique_nat:\n  assumes a: \"coprime (m1::nat) m2\"\n    and nz: \"m1 \\<noteq> 0\" \"m2 \\<noteq> 0\"\n  shows \"EX! x. x < m1 * m2 \\<and> [x = u1] (mod m1) \\<and> [x = u2] (mod m2)\"\nproof -\n  from binary_chinese_remainder_nat [OF a] obtain y where\n      \"[y = u1] (mod m1)\" and \"[y = u2] (mod m2)\"\n    by blast\n  let ?x = \"y mod (m1 * m2)\"\n  from nz have less: \"?x < m1 * m2\"\n    by auto\n  have one: \"[?x = u1] (mod m1)\"\n    apply (rule cong_trans_nat)\n    prefer 2\n    apply (rule `[y = u1] (mod m1)`)\n    apply (rule cong_modulus_mult_nat)\n    apply (rule cong_mod_nat)\n    using nz apply auto\n    done\n  have two: \"[?x = u2] (mod m2)\"\n    apply (rule cong_trans_nat)\n    prefer 2\n    apply (rule `[y = u2] (mod m2)`)\n    apply (subst mult.commute)\n    apply (rule cong_modulus_mult_nat)\n    apply (rule cong_mod_nat)\n    using nz apply auto\n    done\n  have \"ALL z. z < m1 * m2 \\<and> [z = u1] (mod m1) \\<and> [z = u2] (mod m2) \\<longrightarrow> z = ?x\"\n  proof clarify\n    fix z\n    assume \"z < m1 * m2\"\n    assume \"[z = u1] (mod m1)\" and  \"[z = u2] (mod m2)\"\n    have \"[?x = z] (mod m1)\"\n      apply (rule cong_trans_nat)\n      apply (rule `[?x = u1] (mod m1)`)\n      apply (rule cong_sym_nat)\n      apply (rule `[z = u1] (mod m1)`)\n      done\n    moreover have \"[?x = z] (mod m2)\"\n      apply (rule cong_trans_nat)\n      apply (rule `[?x = u2] (mod m2)`)\n      apply (rule cong_sym_nat)\n      apply (rule `[z = u2] (mod m2)`)\n      done\n    ultimately have \"[?x = z] (mod m1 * m2)\"\n      by (auto intro: coprime_cong_mult_nat a)\n    with `z < m1 * m2` `?x < m1 * m2` show \"z = ?x\"\n      apply (intro cong_less_modulus_unique_nat)\n      apply (auto, erule cong_sym_nat)\n      done\n  qed\n  with less one two show ?thesis by auto\n qed\n\nlemma chinese_remainder_aux_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and cop: \"ALL i : A. (ALL j : A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))\"\n  shows \"EX b. (ALL i : A. [b i = 1] (mod m i) \\<and> [b i = 0] (mod (PROD j : A - {i}. m j)))\"\nproof (rule finite_set_choice, rule fin, rule ballI)\n  fix i\n  assume \"i : A\"\n  with cop have \"coprime (PROD j : A - {i}. m j) (m i)\"\n    by (intro setprod_coprime_nat, auto)\n  then have \"EX x. [(PROD j : A - {i}. m j) * x = 1] (mod m i)\"\n    by (elim cong_solve_coprime_nat)\n  then obtain x where \"[(PROD j : A - {i}. m j) * x = 1] (mod m i)\"\n    by auto\n  moreover have \"[(PROD j : A - {i}. m j) * x = 0]\n    (mod (PROD j : A - {i}. m j))\"\n    by (subst mult.commute, rule cong_mult_self_nat)\n  ultimately show \"\\<exists>a. [a = 1] (mod m i) \\<and> [a = 0]\n      (mod setprod m (A - {i}))\"\n    by blast\nqed\n\nlemma chinese_remainder_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n    and u :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and cop: \"ALL i:A. (ALL j : A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))\"\n  shows \"EX x. (ALL i:A. [x = u i] (mod m i))\"\nproof -\n  from chinese_remainder_aux_nat [OF fin cop] obtain b where\n    bprop: \"ALL i:A. [b i = 1] (mod m i) \\<and>\n      [b i = 0] (mod (PROD j : A - {i}. m j))\"\n    by blast\n  let ?x = \"SUM i:A. (u i) * (b i)\"\n  show \"?thesis\"\n  proof (rule exI, clarify)\n    fix i\n    assume a: \"i : A\"\n    show \"[?x = u i] (mod m i)\"\n    proof -\n      from fin a have \"?x = (SUM j:{i}. u j * b j) +\n          (SUM j:A-{i}. u j * b j)\"\n        by (subst setsum.union_disjoint [symmetric], auto intro: setsum.cong)\n      then have \"[?x = u i * b i + (SUM j:A-{i}. u j * b j)] (mod m i)\"\n        by auto\n      also have \"[u i * b i + (SUM j:A-{i}. u j * b j) =\n                  u i * 1 + (SUM j:A-{i}. u j * 0)] (mod m i)\"\n        apply (rule cong_add_nat)\n        apply (rule cong_scalar2_nat)\n        using bprop a apply blast\n        apply (rule cong_setsum_nat)\n        apply (rule cong_scalar2_nat)\n        using bprop apply auto\n        apply (rule cong_dvd_modulus_nat)\n        apply (drule (1) bspec)\n        apply (erule conjE)\n        apply assumption\n        apply rule\n        using fin a apply auto\n        done\n      finally show ?thesis\n        by simp\n    qed\n  qed\nqed\n\nlemma coprime_cong_prod_nat [rule_format]: \"finite A \\<Longrightarrow>\n    (ALL i: A. (ALL j: A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))) \\<longrightarrow>\n      (ALL i: A. [(x::nat) = y] (mod m i)) \\<longrightarrow>\n         [x = y] (mod (PROD i:A. m i))\"\n  apply (induct set: finite)\n  apply auto\n  apply (metis coprime_cong_mult_nat mult.commute setprod_coprime_nat)\n  done\n\nlemma chinese_remainder_unique_nat:\n  fixes A :: \"'a set\"\n    and m :: \"'a \\<Rightarrow> nat\"\n    and u :: \"'a \\<Rightarrow> nat\"\n  assumes fin: \"finite A\"\n    and nz: \"ALL i:A. m i \\<noteq> 0\"\n    and cop: \"ALL i:A. (ALL j : A. i \\<noteq> j \\<longrightarrow> coprime (m i) (m j))\"\n  shows \"EX! x. x < (PROD i:A. m i) \\<and> (ALL i:A. [x = u i] (mod m i))\"\nproof -\n  from chinese_remainder_nat [OF fin cop]\n  obtain y where one: \"(ALL i:A. [y = u i] (mod m i))\"\n    by blast\n  let ?x = \"y mod (PROD i:A. m i)\"\n  from fin nz have prodnz: \"(PROD i:A. m i) \\<noteq> 0\"\n    by auto\n  then have less: \"?x < (PROD i:A. m i)\"\n    by auto\n  have cong: \"ALL i:A. [?x = u i] (mod m i)\"\n    apply auto\n    apply (rule cong_trans_nat)\n    prefer 2\n    using one apply auto\n    apply (rule cong_dvd_modulus_nat)\n    apply (rule cong_mod_nat)\n    using prodnz apply auto\n    apply rule\n    apply (rule fin)\n    apply assumption\n    done\n  have unique: \"ALL z. z < (PROD i:A. m i) \\<and>\n      (ALL i:A. [z = u i] (mod m i)) \\<longrightarrow> z = ?x\"\n  proof (clarify)\n    fix z\n    assume zless: \"z < (PROD i:A. m i)\"\n    assume zcong: \"(ALL i:A. [z = u i] (mod m i))\"\n    have \"ALL i:A. [?x = z] (mod m i)\"\n      apply clarify\n      apply (rule cong_trans_nat)\n      using cong apply (erule bspec)\n      apply (rule cong_sym_nat)\n      using zcong apply auto\n      done\n    with fin cop have \"[?x = z] (mod (PROD i:A. m i))\"\n      apply (intro coprime_cong_prod_nat)\n      apply auto\n      done\n    with zless less show \"z = ?x\"\n      apply (intro cong_less_modulus_unique_nat)\n      apply (auto, erule cong_sym_nat)\n      done\n  qed\n  from less cong unique show ?thesis by blast\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Number_Theory/Cong.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.8757869916479466, "lm_q1q2_score": 0.7624577567554385}}
{"text": "(*  Title:      HOL/Parity.thy\n    Author:     Jeremy Avigad\n    Author:     Jacques D. Fleuriot\n*)\n\nsection \\<open>Parity in rings and semirings\\<close>\n\ntheory Parity\n  imports Nat_Transfer\nbegin\n\nsubsection \\<open>Ring structures with parity and \\<open>even\\<close>/\\<open>odd\\<close> predicates\\<close>\n\nclass semiring_parity = comm_semiring_1_cancel + numeral +\n  assumes odd_one [simp]: \"\\<not> 2 dvd 1\"\n  assumes odd_even_add: \"\\<not> 2 dvd a \\<Longrightarrow> \\<not> 2 dvd b \\<Longrightarrow> 2 dvd a + b\"\n  assumes even_multD: \"2 dvd a * b \\<Longrightarrow> 2 dvd a \\<or> 2 dvd b\"\n  assumes odd_ex_decrement: \"\\<not> 2 dvd a \\<Longrightarrow> \\<exists>b. a = b + 1\"\nbegin\n\nsubclass semiring_numeral ..\n\nabbreviation even :: \"'a \\<Rightarrow> bool\"\n  where \"even a \\<equiv> 2 dvd a\"\n\nabbreviation odd :: \"'a \\<Rightarrow> bool\"\n  where \"odd a \\<equiv> \\<not> 2 dvd a\"\n\nlemma even_zero [simp]: \"even 0\"\n  by (fact dvd_0_right)\n\nlemma even_plus_one_iff [simp]: \"even (a + 1) \\<longleftrightarrow> odd a\"\n  by (auto simp add: dvd_add_right_iff intro: odd_even_add)\n\nlemma evenE [elim?]:\n  assumes \"even a\"\n  obtains b where \"a = 2 * b\"\n  using assms by (rule dvdE)\n\nlemma oddE [elim?]:\n  assumes \"odd a\"\n  obtains b where \"a = 2 * b + 1\"\nproof -\n  from assms obtain b where *: \"a = b + 1\"\n    by (blast dest: odd_ex_decrement)\n  with assms have \"even (b + 2)\" by simp\n  then have \"even b\" by simp\n  then obtain c where \"b = 2 * c\" ..\n  with * have \"a = 2 * c + 1\" by simp\n  with that show thesis .\nqed\n\nlemma even_times_iff [simp]: \"even (a * b) \\<longleftrightarrow> even a \\<or> even b\"\n  by (auto dest: even_multD)\n\nlemma even_numeral [simp]: \"even (numeral (Num.Bit0 n))\"\nproof -\n  have \"even (2 * numeral n)\"\n    unfolding even_times_iff by simp\n  then have \"even (numeral n + numeral n)\"\n    unfolding mult_2 .\n  then show ?thesis\n    unfolding numeral.simps .\nqed\n\nlemma odd_numeral [simp]: \"odd (numeral (Num.Bit1 n))\"\nproof\n  assume \"even (numeral (num.Bit1 n))\"\n  then have \"even (numeral n + numeral n + 1)\"\n    unfolding numeral.simps .\n  then have \"even (2 * numeral n + 1)\"\n    unfolding mult_2 .\n  then have \"2 dvd numeral n * 2 + 1\"\n    by (simp add: ac_simps)\n  then have \"2 dvd 1\"\n    using dvd_add_times_triv_left_iff [of 2 \"numeral n\" 1] by simp\n  then show False by simp\nqed\n\nlemma even_add [simp]: \"even (a + b) \\<longleftrightarrow> (even a \\<longleftrightarrow> even b)\"\n  by (auto simp add: dvd_add_right_iff dvd_add_left_iff odd_even_add)\n\nlemma odd_add [simp]: \"odd (a + b) \\<longleftrightarrow> (\\<not> (odd a \\<longleftrightarrow> odd b))\"\n  by simp\n\nlemma even_power [simp]: \"even (a ^ n) \\<longleftrightarrow> even a \\<and> n > 0\"\n  by (induct n) auto\n\nend\n\nclass ring_parity = ring + semiring_parity\nbegin\n\nsubclass comm_ring_1 ..\n\nlemma even_minus [simp]: \"even (- a) \\<longleftrightarrow> even a\"\n  by (fact dvd_minus_iff)\n\nlemma even_diff [simp]: \"even (a - b) \\<longleftrightarrow> even (a + b)\"\n  using even_add [of a \"- b\"] by simp\n\nend\n\n\nsubsection \\<open>Instances for @{typ nat} and @{typ int}\\<close>\n\nlemma even_Suc_Suc_iff [simp]: \"2 dvd Suc (Suc n) \\<longleftrightarrow> 2 dvd n\"\n  using dvd_add_triv_right_iff [of 2 n] by simp\n\nlemma even_Suc [simp]: \"2 dvd Suc n \\<longleftrightarrow> \\<not> 2 dvd n\"\n  by (induct n) auto\n\nlemma even_diff_nat [simp]: \"2 dvd (m - n) \\<longleftrightarrow> m < n \\<or> 2 dvd (m + n)\"\n  for m n :: nat\nproof (cases \"n \\<le> m\")\n  case True\n  then have \"m - n + n * 2 = m + n\" by (simp add: mult_2_right)\n  moreover have \"2 dvd (m - n) \\<longleftrightarrow> 2 dvd (m - n + n * 2)\" by simp\n  ultimately have \"2 dvd (m - n) \\<longleftrightarrow> 2 dvd (m + n)\" by (simp only:)\n  then show ?thesis by auto\nnext\n  case False\n  then show ?thesis by simp\nqed\n\ninstance nat :: semiring_parity\nproof\n  show \"\\<not> 2 dvd (1 :: nat)\"\n    by (rule notI, erule dvdE) simp\nnext\n  fix m n :: nat\n  assume \"\\<not> 2 dvd m\"\n  moreover assume \"\\<not> 2 dvd n\"\n  ultimately have *: \"2 dvd Suc m \\<and> 2 dvd Suc n\"\n    by simp\n  then have \"2 dvd (Suc m + Suc n)\"\n    by (blast intro: dvd_add)\n  also have \"Suc m + Suc n = m + n + 2\"\n    by simp\n  finally show \"2 dvd (m + n)\"\n    using dvd_add_triv_right_iff [of 2 \"m + n\"] by simp\nnext\n  fix m n :: nat\n  assume *: \"2 dvd (m * n)\"\n  show \"2 dvd m \\<or> 2 dvd n\"\n  proof (rule disjCI)\n    assume \"\\<not> 2 dvd n\"\n    then have \"2 dvd (Suc n)\" by simp\n    then obtain r where \"Suc n = 2 * r\" ..\n    moreover from * obtain s where \"m * n = 2 * s\" ..\n    then have \"2 * s + m = m * Suc n\" by simp\n    ultimately have \" 2 * s + m = 2 * (m * r)\"\n      by (simp add: algebra_simps)\n    then have \"m = 2 * (m * r - s)\" by simp\n    then show \"2 dvd m\" ..\n  qed\nnext\n  fix n :: nat\n  assume \"\\<not> 2 dvd n\"\n  then show \"\\<exists>m. n = m + 1\"\n    by (cases n) simp_all\nqed\n\nlemma odd_pos: \"odd n \\<Longrightarrow> 0 < n\"\n  for n :: nat\n  by (auto elim: oddE)\n\nlemma Suc_double_not_eq_double: \"Suc (2 * m) \\<noteq> 2 * n\"\n  for m n :: nat\nproof\n  assume \"Suc (2 * m) = 2 * n\"\n  moreover have \"odd (Suc (2 * m))\" and \"even (2 * n)\"\n    by simp_all\n  ultimately show False by simp\nqed\n\nlemma double_not_eq_Suc_double: \"2 * m \\<noteq> Suc (2 * n)\"\n  for m n :: nat\n  using Suc_double_not_eq_double [of n m] by simp\n\nlemma even_diff_iff [simp]: \"2 dvd (k - l) \\<longleftrightarrow> 2 dvd (k + l)\"\n  for k l :: int\n  using dvd_add_times_triv_right_iff [of 2 \"k - l\" l] by (simp add: mult_2_right)\n\nlemma even_abs_add_iff [simp]: \"2 dvd (\\<bar>k\\<bar> + l) \\<longleftrightarrow> 2 dvd (k + l)\"\n  for k l :: int\n  by (cases \"k \\<ge> 0\") (simp_all add: ac_simps)\n\nlemma even_add_abs_iff [simp]: \"2 dvd (k + \\<bar>l\\<bar>) \\<longleftrightarrow> 2 dvd (k + l)\"\n  for k l :: int\n  using even_abs_add_iff [of l k] by (simp add: ac_simps)\n\nlemma odd_Suc_minus_one [simp]: \"odd n \\<Longrightarrow> Suc (n - Suc 0) = n\"\n  by (auto elim: oddE)\n\ninstance int :: ring_parity\nproof\n  show \"\\<not> 2 dvd (1 :: int)\"\n    by (simp add: dvd_int_unfold_dvd_nat)\nnext\n  fix k l :: int\n  assume \"\\<not> 2 dvd k\"\n  moreover assume \"\\<not> 2 dvd l\"\n  ultimately have \"2 dvd (nat \\<bar>k\\<bar> + nat \\<bar>l\\<bar>)\"\n    by (auto simp add: dvd_int_unfold_dvd_nat intro: odd_even_add)\n  then have \"2 dvd (\\<bar>k\\<bar> + \\<bar>l\\<bar>)\"\n    by (simp add: dvd_int_unfold_dvd_nat nat_add_distrib)\n  then show \"2 dvd (k + l)\"\n    by simp\nnext\n  fix k l :: int\n  assume \"2 dvd (k * l)\"\n  then show \"2 dvd k \\<or> 2 dvd l\"\n    by (simp add: dvd_int_unfold_dvd_nat even_multD nat_abs_mult_distrib)\nnext\n  fix k :: int\n  have \"k = (k - 1) + 1\" by simp\n  then show \"\\<exists>l. k = l + 1\" ..\nqed\n\nlemma even_int_iff [simp]: \"even (int n) \\<longleftrightarrow> even n\"\n  by (simp add: dvd_int_iff)\n\nlemma even_nat_iff: \"0 \\<le> k \\<Longrightarrow> even (nat k) \\<longleftrightarrow> even k\"\n  by (simp add: even_int_iff [symmetric])\n\n\nsubsection \\<open>Parity and powers\\<close>\n\ncontext ring_1\nbegin\n\nlemma power_minus_even [simp]: \"even n \\<Longrightarrow> (- a) ^ n = a ^ n\"\n  by (auto elim: evenE)\n\nlemma power_minus_odd [simp]: \"odd n \\<Longrightarrow> (- a) ^ n = - (a ^ n)\"\n  by (auto elim: oddE)\n\nlemma neg_one_even_power [simp]: \"even n \\<Longrightarrow> (- 1) ^ n = 1\"\n  by simp\n\nlemma neg_one_odd_power [simp]: \"odd n \\<Longrightarrow> (- 1) ^ n = - 1\"\n  by simp\n\nend\n\ncontext linordered_idom\nbegin\n\nlemma zero_le_even_power: \"even n \\<Longrightarrow> 0 \\<le> a ^ n\"\n  by (auto elim: evenE)\n\nlemma zero_le_odd_power: \"odd n \\<Longrightarrow> 0 \\<le> a ^ n \\<longleftrightarrow> 0 \\<le> a\"\n  by (auto simp add: power_even_eq zero_le_mult_iff elim: oddE)\n\nlemma zero_le_power_eq: \"0 \\<le> a ^ n \\<longleftrightarrow> even n \\<or> odd n \\<and> 0 \\<le> a\"\n  by (auto simp add: zero_le_even_power zero_le_odd_power)\n\nlemma zero_less_power_eq: \"0 < a ^ n \\<longleftrightarrow> n = 0 \\<or> even n \\<and> a \\<noteq> 0 \\<or> odd n \\<and> 0 < a\"\nproof -\n  have [simp]: \"0 = a ^ n \\<longleftrightarrow> a = 0 \\<and> n > 0\"\n    unfolding power_eq_0_iff [of a n, symmetric] by blast\n  show ?thesis\n    unfolding less_le zero_le_power_eq by auto\nqed\n\nlemma power_less_zero_eq [simp]: \"a ^ n < 0 \\<longleftrightarrow> odd n \\<and> a < 0\"\n  unfolding not_le [symmetric] zero_le_power_eq by auto\n\nlemma power_le_zero_eq: \"a ^ n \\<le> 0 \\<longleftrightarrow> n > 0 \\<and> (odd n \\<and> a \\<le> 0 \\<or> even n \\<and> a = 0)\"\n  unfolding not_less [symmetric] zero_less_power_eq by auto\n\nlemma power_even_abs: \"even n \\<Longrightarrow> \\<bar>a\\<bar> ^ n = a ^ n\"\n  using power_abs [of a n] by (simp add: zero_le_even_power)\n\nlemma power_mono_even:\n  assumes \"even n\" and \"\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\"\n  shows \"a ^ n \\<le> b ^ n\"\nproof -\n  have \"0 \\<le> \\<bar>a\\<bar>\" by auto\n  with \\<open>\\<bar>a\\<bar> \\<le> \\<bar>b\\<bar>\\<close> have \"\\<bar>a\\<bar> ^ n \\<le> \\<bar>b\\<bar> ^ n\"\n    by (rule power_mono)\n  with \\<open>even n\\<close> show ?thesis\n    by (simp add: power_even_abs)\nqed\n\nlemma power_mono_odd:\n  assumes \"odd n\" and \"a \\<le> b\"\n  shows \"a ^ n \\<le> b ^ n\"\nproof (cases \"b < 0\")\n  case True\n  with \\<open>a \\<le> b\\<close> have \"- b \\<le> - a\" and \"0 \\<le> - b\" by auto\n  then have \"(- b) ^ n \\<le> (- a) ^ n\" by (rule power_mono)\n  with \\<open>odd n\\<close> show ?thesis by simp\nnext\n  case False\n  then have \"0 \\<le> b\" by auto\n  show ?thesis\n  proof (cases \"a < 0\")\n    case True\n    then have \"n \\<noteq> 0\" and \"a \\<le> 0\" using \\<open>odd n\\<close> [THEN odd_pos] by auto\n    then have \"a ^ n \\<le> 0\" unfolding power_le_zero_eq using \\<open>odd n\\<close> by auto\n    moreover from \\<open>0 \\<le> b\\<close> have \"0 \\<le> b ^ n\" by auto\n    ultimately show ?thesis by auto\n  next\n    case False\n    then have \"0 \\<le> a\" by auto\n    with \\<open>a \\<le> b\\<close> show ?thesis\n      using power_mono by auto\n  qed\nqed\n\nlemma (in comm_ring_1) uminus_power_if: \"(- x) ^ n = (if even n then x^n else - (x ^ n))\"\n  by auto\n\ntext \\<open>Simplify, when the exponent is a numeral\\<close>\n\nlemma zero_le_power_eq_numeral [simp]:\n  \"0 \\<le> a ^ numeral w \\<longleftrightarrow> even (numeral w :: nat) \\<or> odd (numeral w :: nat) \\<and> 0 \\<le> a\"\n  by (fact zero_le_power_eq)\n\nlemma zero_less_power_eq_numeral [simp]:\n  \"0 < a ^ numeral w \\<longleftrightarrow>\n    numeral w = (0 :: nat) \\<or>\n    even (numeral w :: nat) \\<and> a \\<noteq> 0 \\<or>\n    odd (numeral w :: nat) \\<and> 0 < a\"\n  by (fact zero_less_power_eq)\n\nlemma power_le_zero_eq_numeral [simp]:\n  \"a ^ numeral w \\<le> 0 \\<longleftrightarrow>\n    (0 :: nat) < numeral w \\<and>\n    (odd (numeral w :: nat) \\<and> a \\<le> 0 \\<or> even (numeral w :: nat) \\<and> a = 0)\"\n  by (fact power_le_zero_eq)\n\nlemma power_less_zero_eq_numeral [simp]:\n  \"a ^ numeral w < 0 \\<longleftrightarrow> odd (numeral w :: nat) \\<and> a < 0\"\n  by (fact power_less_zero_eq)\n\nlemma power_even_abs_numeral [simp]:\n  \"even (numeral w :: nat) \\<Longrightarrow> \\<bar>a\\<bar> ^ numeral w = a ^ numeral w\"\n  by (fact power_even_abs)\n\nend\n\n\nsubsubsection \\<open>Tool setup\\<close>\n\ndeclare transfer_morphism_int_nat [transfer add return: even_int_iff]\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Parity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7624577523448086}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \"Skew Heap Analysis\"\n\ntheory Skew_Heap_Analysis\nimports\n  Complex_Main\n  Skew_Heap.Skew_Heap\n  Amortized_Framework\n  Priority_Queue_ops_merge\nbegin\n\ntext\\<open>The following proof is a simplified version of the one by Kaldewaij and\nSchoenmakers~\\cite{KaldewaijS-IPL91}.\\<close>\n\ntext \\<open>right-heavy:\\<close>\ndefinition rh :: \"'a tree => 'a tree => nat\" where\n\"rh l r = (if size l < size r then 1 else 0)\"\n\ntext \\<open>Function \\<open>\\<Gamma>\\<close> in \\cite{KaldewaijS-IPL91}: number of right-heavy nodes on left spine.\\<close>\nfun lrh :: \"'a tree \\<Rightarrow> nat\" where\n\"lrh Leaf = 0\" |\n\"lrh (Node l _ r) = rh l r + lrh l\"\n\ntext \\<open>Function \\<open>\\<Delta>\\<close> in \\cite{KaldewaijS-IPL91}: number of not-right-heavy nodes on right spine.\\<close>\nfun rlh :: \"'a tree \\<Rightarrow> nat\" where\n\"rlh Leaf = 0\" |\n\"rlh (Node l _ r) = (1 - rh l r) + rlh r\"\n\nlemma Gexp: \"2 ^ lrh h \\<le> size h + 1\"\nby (induction h) (auto simp: rh_def)\n\ncorollary Glog: \"lrh h \\<le> log 2 (size1 h)\"\nby (metis Gexp le_log2_of_power size1_size)\n\nlemma Dexp: \"2 ^ rlh h \\<le> size h + 1\"\nby (induction h) (auto simp: rh_def)\n\ncorollary Dlog: \"rlh h \\<le> log 2 (size1 h)\"\nby (metis Dexp le_log2_of_power size1_size)\n\nfunction t_merge :: \"'a::linorder heap \\<Rightarrow> 'a heap \\<Rightarrow> nat\" where\n\"t_merge Leaf h = 1\" |\n\"t_merge h Leaf = 1\" |\n\"t_merge (Node l1 a1 r1) (Node l2 a2 r2) =\n   (if a1 \\<le> a2 then t_merge (Node l2 a2 r2) r1 else t_merge (Node l1 a1 r1) r2) + 1\"\nby pat_completeness auto\ntermination\nby (relation \"measure (\\<lambda>(x, y). size x + size y)\") auto\n\nfun \\<Phi> :: \"'a heap \\<Rightarrow> int\" where\n\"\\<Phi> Leaf = 0\" |\n\"\\<Phi> (Node l _ r) = \\<Phi> l + \\<Phi> r + rh l r\"\n\nlemma \\<Phi>_nneg: \"\\<Phi> t \\<ge> 0\"\nby (induction t) auto\n\nlemma plus_log_le_2log_plus: \"\\<lbrakk> x > 0; y > 0; b > 1 \\<rbrakk>\n  \\<Longrightarrow> log b x + log b y \\<le> 2 * log b (x + y)\"\nby(subst mult_2; rule add_mono; auto)\n\nlemma rh1: \"rh l r \\<le> 1\"\nby(simp add: rh_def)\n\nlemma amor_le_long:\n  \"t_merge t1 t2 + \\<Phi> (merge t1 t2) - \\<Phi> t1 - \\<Phi> t2 \\<le>\n   lrh(merge t1 t2) + rlh t1 + rlh t2 + 1\"\nproof (induction t1 t2 rule: merge.induct)\n  case 1 thus ?case by simp\nnext\n  case 2 thus ?case by simp\nnext\n  case (3 l1 a1 r1 l2 a2 r2)\n  show ?case\n  proof (cases \"a1 \\<le> a2\")\n    case True\n    let ?t1 = \"Node l1 a1 r1\" let ?t2 = \"Node l2 a2 r2\" let ?m = \"merge ?t2 r1\"\n    have \"t_merge ?t1 ?t2 + \\<Phi> (merge ?t1 ?t2) - \\<Phi> ?t1 - \\<Phi> ?t2\n          = t_merge ?t2 r1 + 1 + \\<Phi> ?m + \\<Phi> l1 + rh ?m l1 - \\<Phi> ?t1 - \\<Phi> ?t2\"\n      using True by (simp)\n    also have \"\\<dots> = t_merge ?t2 r1 + 1 + \\<Phi> ?m + rh ?m l1 - \\<Phi> r1 - rh l1 r1 - \\<Phi> ?t2\"\n      by simp\n    also have \"\\<dots> \\<le> lrh ?m + rlh ?t2 + rlh r1 + rh ?m l1 + 2 - rh l1 r1\"\n      using \"3.IH\"(1)[OF True] by linarith\n    also have \"\\<dots> = lrh ?m + rlh ?t2 + rlh r1 + rh ?m l1 + 1 + (1 - rh l1 r1)\"\n      using rh1[of l1 r1] by (simp)\n    also have \"\\<dots> = lrh ?m + rlh ?t2 + rlh ?t1 + rh ?m l1 + 1\"\n      by (simp)\n    also have \"\\<dots> = lrh (merge ?t1 ?t2) + rlh ?t1 + rlh ?t2 + 1\"\n      using True by(simp)\n    finally show ?thesis .\n  next\n    case False with 3 show ?thesis by auto\n  qed\nqed\n\nlemma amor_le:\n  \"t_merge t1 t2 + \\<Phi> (merge t1 t2) - \\<Phi> t1 - \\<Phi> t2 \\<le>\n   lrh(merge t1 t2) + rlh t1 + rlh t2 + 1\"\nby(induction t1 t2 rule: merge.induct)(auto)\n\nlemma a_merge:\n  \"t_merge t1 t2 + \\<Phi>(merge t1 t2) - \\<Phi> t1 - \\<Phi> t2 \\<le>\n   3 * log 2 (size1 t1 + size1 t2) + 1\" (is \"?l \\<le> _\")\nproof -\n  have \"?l \\<le> lrh(merge t1 t2) + rlh t1 + rlh t2 + 1\" using amor_le[of t1 t2] by arith\n  also have \"\\<dots> = real(lrh(merge t1 t2)) + rlh t1 + rlh t2 + 1\" by simp\n  also have \"\\<dots> = real(lrh(merge t1 t2)) + (real(rlh t1) + rlh t2) + 1\" by simp\n  also have \"rlh t1 \\<le> log 2 (size1 t1)\" by(rule Dlog)\n  also have \"rlh t2 \\<le> log 2 (size1 t2)\" by(rule Dlog)\n  also have \"lrh (merge t1 t2) \\<le> log 2 (size1(merge t1 t2))\" by(rule Glog)\n  also have \"size1(merge t1 t2) = size1 t1 + size1 t2 - 1\" by(simp add: size1_size)\n  also have \"log 2 (size1 t1 + size1 t2 - 1) \\<le> log 2 (size1 t1 + size1 t2)\" by(simp add: size1_size)\n  also have \"log 2 (size1 t1) + log 2 (size1 t2) \\<le> 2 * log 2 (real(size1 t1) + (size1 t2))\"\n    by(rule plus_log_le_2log_plus) (auto simp: size1_size)\n  finally show ?thesis by(simp)\nqed\n\ndefinition t_insert :: \"'a::linorder \\<Rightarrow> 'a heap \\<Rightarrow> int\" where\n\"t_insert a h = t_merge (Node Leaf a Leaf) h + 1\"\n\nlemma a_insert: \"t_insert a h + \\<Phi>(Skew_Heap.insert a h) - \\<Phi> h \\<le> 3 * log 2 (size1 h + 2) + 2\"\nusing a_merge[of \"Node Leaf a Leaf\" \"h\"]\nby (simp add: numeral_eq_Suc t_insert_def Skew_Heap.insert_def rh_def)\n\ndefinition t_del_min :: \"('a::linorder) heap \\<Rightarrow> int\" where\n\"t_del_min h = (case h of Leaf \\<Rightarrow> 1 | Node t1 a t2 \\<Rightarrow> t_merge t1 t2 + 1)\"\n\nlemma a_del_min: \"t_del_min h + \\<Phi>(del_min h) - \\<Phi> h \\<le> 3 * log 2 (size1 h + 2) + 2\"\nproof (cases h)\n  case Leaf thus ?thesis by (simp add: t_del_min_def)\nnext\n  case (Node t1 _ t2)\n  have [arith]: \"log 2 (2 + (real (size t1) + real (size t2))) \\<le>\n                log 2 (4 + (real (size t1) + real (size t2)))\" by simp\n  from Node show ?thesis using a_merge[of t1 t2]\n    by (simp add: size1_size t_del_min_def rh_def)\nqed\n\n\nsubsubsection \"Instantiation of Amortized Framework\"\n\nlemma t_merge_nneg: \"t_merge h1 h2 \\<ge> 0\"\nby(induction h1 h2 rule: t_merge.induct) auto\n\nfun exec :: \"'a::linorder op \\<Rightarrow> 'a heap list \\<Rightarrow> 'a heap\" where\n\"exec Empty [] = Leaf\" |\n\"exec (Insert a) [h] = Skew_Heap.insert a h\" |\n\"exec Del_min [h] = del_min h\" |\n\"exec Merge [h1,h2] = merge h1 h2\"\n\nfun cost :: \"'a::linorder op \\<Rightarrow> 'a heap list \\<Rightarrow> nat\" where\n\"cost Empty [] = 1\" |\n\"cost (Insert a) [h] = t_merge (Node Leaf a Leaf) h\" |\n\"cost Del_min [h] = (case h of Leaf \\<Rightarrow> 1 | Node t1 a t2 \\<Rightarrow> t_merge t1 t2)\" |\n\"cost Merge [h1,h2] = t_merge h1 h2\"\n\nfun U where\n\"U Empty [] = 1\" |\n\"U (Insert _) [h] = 3 * log 2 (size1 h + 2) + 1\" |\n\"U Del_min [h] = 3 * log 2 (size1 h + 2) + 3\" |\n\"U Merge [h1,h2] = 3 * log 2 (size1 h1 + size1 h2) + 1\"\n\ninterpretation Amortized\nwhere arity = arity and exec = exec and inv = \"\\<lambda>_. True\"\nand cost = cost and \\<Phi> = \\<Phi> and U = U\nproof (standard, goal_cases)\n  case 1 show ?case by simp\nnext\n  case (2 h) show ?case using \\<Phi>_nneg[of h] by linarith\nnext\n  case (3 ss f)\n  show ?case\n  proof (cases f)\n    case Empty thus ?thesis using 3(2) by (auto)\n  next\n    case [simp]: (Insert a)\n    obtain h where [simp]: \"ss = [h]\" using 3(2) by (auto)\n    thus ?thesis using a_merge[of \"Node Leaf a Leaf\" \"h\"]\n      by (simp add: numeral_eq_Suc insert_def rh_def t_merge_nneg)\n  next\n    case [simp]: Del_min\n    obtain h where [simp]: \"ss = [h]\" using 3(2) by (auto)\n    thus ?thesis\n    proof (cases h)\n      case Leaf with Del_min show ?thesis by simp\n    next\n      case (Node t1 _ t2)\n      have [arith]: \"log 2 (2 + (real (size t1) + real (size t2))) \\<le>\n               log 2 (4 + (real (size t1) + real (size t2)))\" by simp\n      from Del_min Node show ?thesis using a_merge[of t1 t2]\n        by (simp add: size1_size t_merge_nneg)\n    qed\n  next\n    case [simp]: Merge\n    obtain h1 h2 where \"ss = [h1,h2]\" using 3(2) by (auto simp: numeral_eq_Suc)\n    thus ?thesis using a_merge[of h1 h2] by (simp add: t_merge_nneg)\n  qed\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Amortized_Complexity/Skew_Heap_Analysis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533126145179, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7623500265635065}}
{"text": "(*  \n    Title:      Inverse_IArrays.thy\n    Author:     Jose Divasón <jose.divasonm at unirioja.es>\n    Author:     Jesús Aransay <jesus-maria.aransay at unirioja.es>\n*)\n\nheader{*Inverse of a matrix using the Gauss Jordan algorithm over nested IArrays*}\n\ntheory Inverse_IArrays\nimports \n  Inverse\n  Gauss_Jordan_PA_IArrays\nbegin\n\nsubsection{*Definitions*}\n\ndefinition \"invertible_iarray A = (rank_iarray A = nrows_iarray A)\"\ndefinition \"inverse_matrix_iarray A = (if invertible_iarray A then Some(fst(Gauss_Jordan_iarrays_PA A)) else None)\"\ndefinition \"matrix_to_iarray_option A = (if A \\<noteq> None then Some (matrix_to_iarray (the A)) else None)\"\n\nsubsection{*Some lemmas and code generation*}\nlemma matrix_inv_Gauss_Jordan_iarrays_PA:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nassumes inv_A: \"invertible A\"\nshows \"matrix_to_iarray (matrix_inv A) = fst (Gauss_Jordan_iarrays_PA (matrix_to_iarray A))\"\nby (metis inv_A matrix_inv_Gauss_Jordan_PA matrix_to_iarray_fst_Gauss_Jordan_PA)\n\nlemma matrix_to_iarray_invertible[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"invertible A = invertible_iarray (matrix_to_iarray A)\"\nunfolding invertible_iarray_def invertible_eq_full_rank[of A] matrix_to_iarray_rank matrix_to_iarray_nrows ..\n\nlemma matrix_to_iarray_option_inverse_matrix:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"matrix_to_iarray_option (inverse_matrix A) = (inverse_matrix_iarray (matrix_to_iarray A))\"\nproof (unfold inverse_matrix_def, auto)\nassume inv_A: \"invertible A\"\nshow \"matrix_to_iarray_option (Some (matrix_inv A)) = inverse_matrix_iarray (matrix_to_iarray A)\"\nunfolding matrix_to_iarray_option_def unfolding inverse_matrix_iarray_def using inv_A unfolding matrix_to_iarray_invertible\nusing matrix_inv_Gauss_Jordan_iarrays_PA[OF inv_A] by auto\nnext\nassume not_inv_A: \"\\<not> invertible A\"\nshow \"matrix_to_iarray_option None = inverse_matrix_iarray (matrix_to_iarray A)\"\nunfolding matrix_to_iarray_option_def inverse_matrix_iarray_def\nusing not_inv_A unfolding matrix_to_iarray_invertible by simp\nqed\n\nlemma matrix_to_iarray_option_inverse_matrix_code[code_unfold]:\nfixes A::\"'a::{field}^'n::{mod_type}^'n::{mod_type}\"\nshows \"matrix_to_iarray_option (inverse_matrix A) = (let matrix_to_iarray_A = matrix_to_iarray A; GJ = Gauss_Jordan_iarrays_PA matrix_to_iarray_A\n  in if nrows_iarray matrix_to_iarray_A = length [x\\<leftarrow>IArray.list_of (snd GJ) . \\<not> is_zero_iarray x] then Some (fst GJ) else None)\"\nunfolding matrix_to_iarray_option_inverse_matrix\nunfolding inverse_matrix_iarray_def\nunfolding invertible_iarray_def\nunfolding rank_iarrays_code\nunfolding Let_def\nunfolding matrix_to_iarray_snd_Gauss_Jordan_PA[symmetric]\nunfolding Gauss_Jordan_PA_eq\nunfolding matrix_to_iarray_Gauss_Jordan by presburger\n\n\n\n\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Gauss_Jordan/Inverse_IArrays.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789468908171, "lm_q2_score": 0.851952809486198, "lm_q1q2_score": 0.7623184019349794}}
{"text": "theory Chapter3\nimports Main HOL.Fun\nbegin\n\n(** Section 3.1 Arithmetic expressions **)\n\ndatatype var_name = VarName string\n\n(*\nfun abc_var :: \"var_name\" where\n\"abc_var = VarName ''abc''\"\n*)\n\ndatatype aexp =\n    N int\n  | V var_name\n  | Plus aexp aexp\n\ntype_synonym val   = int\ntype_synonym state = \"var_name \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n)      _ = n\"   |\n\"aval (V v)      s = s v\" |\n\"aval (Plus x y) s = aval x s + aval y s\"\n\nvalue \"aval (Plus (N 3) (V (VarName ''x''))) ((\\<lambda> _. 0) (VarName ''x'' := 5))\"\n\nfun undef_state :: \"state\" where\n\"undef_state (VarName []) = 1\"\n\nvalue \"aval (Plus (N 3) (V (VarName ''x''))) undef_state\"\n\n(*fun mk_state :: \"int \\<Rightarrow> (string * int) list \\<Rightarrow> state\" where\n\"mk_state initial bindings = \"\n*)\n\nfun init_state :: \"state\" where\n\"init_state _ = 0\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V v) = V v\" |\n\"asimp_const (Plus x y) =\n (case (asimp_const x, asimp_const y) of\n   (N x', N y') \\<Rightarrow> N (x' + y') |\n   (x',   y')   \\<Rightarrow> Plus x' y')\"\n\ntheorem asimp_const_preserves_semantics : \"aval (asimp_const e) s = aval e s\"\napply(induction e)\napply(auto split: aexp.split)\ndone\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N x) (N y) = N (x + y)\"                               |\n\"plus (N x) y     = (if x = 0 then y else Plus (N x) y)\"     |\n\"plus x     (N y) = (if y = 0 then x else Plus x     (N y))\" |\n\"plus x     y     = Plus x y\"\n\nlemma plus_adds : \"aval (plus e1 e2) s = aval e1 s + aval e2 s\"\napply(induction e1 e2 rule: plus.induct)\napply(auto)\ndone\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N x)      = N x\" |\n\"asimp (V x)      = V x\" |\n\"asimp (Plus x y) = plus x y\"\n\ntheorem asimp_preserves_semantics : \"aval (asimp e) s = aval e s\"\napply(induction e)\napply(auto simp add: plus_adds)\ndone\n\n(* Exercise 3.1 *)\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N _)              = True\"  |\n\"optimal (V _)              = True\"  |\n\"optimal (Plus (N _) (N _)) = False\" |\n\"optimal (Plus x     y)     = (optimal x \\<and> optimal y)\"\n\ntheorem \"optimal (asimp_const e)\"\napply(induction e)\napply(auto split: aexp.split)\ndone\n\n(* Exercise 3.2 *)\n\nvalue \"Some 1\"\nvalue \"None\"\ntype \"fst\"\nvalue \"let (x, y) = (1, 2 :: int) in x + y\"\n\ndatatype aexp_simplified =\n    Constant int\n  | VanillaTerm aexp\n  (* Term plus some constant *)\n  | Term aexp int (* integer is always nonzero *)\n\nfun unsimplify :: \"aexp_simplified \\<Rightarrow> aexp\" where\n\"unsimplify (Constant n)    = N n\" |\n\"unsimplify (VanillaTerm e) = e\"   |\n\"unsimplify (Term e n)      = Plus e (N n)\"\n\nfun addConstant :: \"int \\<Rightarrow> aexp_simplified \\<Rightarrow> aexp_simplified\" where\n\"addConstant n e =\n (if n = 0\n  then e\n  else case e of\n    Constant m    \\<Rightarrow> Constant (n + m) |\n    VanillaTerm e \\<Rightarrow> Term e n         |\n    Term e m      \\<Rightarrow> Term e (n + m)\n  )\"\n(*\n  \"addConstant n (Constant m)    = Constant (n + m)\"                            |\n\"addConstant n (VanillaTerm e) = (if n = 0 then VanillaTerm e else Term e n)\" |\n\"addConstant n (Term e m)      = Term e (n + m)\"\n*)\n\nfun full_asimp_helper :: \"aexp \\<Rightarrow> aexp_simplified\" where\n\"full_asimp_helper (N n)      = Constant n\"        |\n\"full_asimp_helper (V v)      = VanillaTerm (V v)\" |\n\"full_asimp_helper (Plus x y) =\n (case (full_asimp_helper x, full_asimp_helper y) of\n   (Constant n,    e)              \\<Rightarrow> addConstant n e         |\n   (e,             Constant m)     \\<Rightarrow> addConstant m e         |\n   (VanillaTerm e, VanillaTerm e') \\<Rightarrow> VanillaTerm (Plus e e') |\n   (VanillaTerm e, Term e' m)      \\<Rightarrow> Term (Plus e e') m      |\n   (Term e n,      VanillaTerm e') \\<Rightarrow> Term (Plus e e') n      |\n   (Term e n,      Term e' m)      \\<Rightarrow> Term (Plus e e') (n + m))\"\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp x = (unsimplify \\<circ> full_asimp_helper) x\" (* Enter composition via \\circ *)\n\nlemma addConstant_preserves_semantics :\n  \"aval (unsimplify (addConstant n e)) s = n + aval (unsimplify e) s\"\napply(induction e)\napply(auto split: aexp_simplified.split)\ndone\n\ntheorem full_asimp_preserves_semantics : \"aval (full_asimp e) s = aval e s\"\napply(induction e)\napply(auto split: aexp_simplified.split simp add: addConstant_preserves_semantics)\n(* apply(auto simp add: split_def Let_def split: option.split) (* split_def is needed to expand cases over tuples *) *)\ndone\n\n(* Exercise 3.3 *)\n\nfun subst :: \"var_name \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst _ _ (N n)       = N n\"                          |\n\"subst v x (V v')      = (if v = v' then x else V v')\" |\n\"subst v x (Plus e e') = Plus (subst v x e) (subst v x e')\"\n\nlemma substitution_lemma : \"aval (subst v x e) s = aval e (s (v := aval x s))\"\napply(induction e)\napply(auto)\ndone\n\ntheorem substitute_equals_preserves_semantics : \"aval x s = aval y s \\<Longrightarrow> aval (subst v x e) s = aval (subst v y e) s\"\napply(induction e)\napply(auto)\ndone\n\n(* Exercise 3.4 - See file Chapter3_ex3_04_AExp.thy *)\n\n(* Exercise 3.5 *)\n\ndatatype aexp\\<^sub>2 =\n    N\\<^sub>2 int\n  | V\\<^sub>2 var_name\n  | Plus\\<^sub>2 aexp\\<^sub>2 aexp\\<^sub>2\n  | Div aexp\\<^sub>2 aexp\\<^sub>2\n  | PostIncrement var_name\n\nfun liftOpt :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'a option \\<Rightarrow> 'b option \\<Rightarrow> 'c option\" where\n\"liftOpt _ None     _        = None\" |\n\"liftOpt _ _        None     = None\" |\n\"liftOpt f (Some x) (Some y) = Some (f x y)\"\n\nfun aval\\<^sub>2 :: \"aexp\\<^sub>2 \\<Rightarrow> state \\<Rightarrow> val option \\<times> state\" where\n\"aval\\<^sub>2 (N\\<^sub>2 n)       s  = (Some n, s)\"   |\n\"aval\\<^sub>2 (V\\<^sub>2 v)       s  = (Some (s v), s)\" |\n\"aval\\<^sub>2 (Plus\\<^sub>2 e\\<^sub>1 e\\<^sub>2) s\\<^sub>1 =\n (let (v\\<^sub>1, s\\<^sub>2) = aval\\<^sub>2 e\\<^sub>1 s\\<^sub>1;\n      (v\\<^sub>2, s\\<^sub>3) = aval\\<^sub>2 e\\<^sub>2 s\\<^sub>2 in\n  (liftOpt (op +) v\\<^sub>1 v\\<^sub>2, s\\<^sub>3))\" |\n\"aval\\<^sub>2 (Div e\\<^sub>1 e\\<^sub>2) s\\<^sub>1 =\n (let (v\\<^sub>1, s\\<^sub>2) = aval\\<^sub>2 e\\<^sub>1 s\\<^sub>1;\n      (v\\<^sub>2, s\\<^sub>3) = aval\\<^sub>2 e\\<^sub>2 s\\<^sub>2;\n      v        = if v\\<^sub>2 = Some 0\n                 then None\n                 else liftOpt (op div) v\\<^sub>1 v\\<^sub>2\n  in (v, s\\<^sub>3))\" |\n\"aval\\<^sub>2 (PostIncrement v) s =\n (let v' = s v in\n  (Some v', s (v := v' + 1)))\"\n\nvalue \"\naval\\<^sub>2\n  (Plus\\<^sub>2\n    (PostIncrement (VarName ''x''))\n    (Plus\\<^sub>2\n      (PostIncrement (VarName ''x''))\n      (Div\n        (PostIncrement (VarName ''x''))\n        (N\\<^sub>2 2))))\n  (\\<lambda> _ \\<Rightarrow> 0)\"\n\n(* Exercise 3.6 *)\n\ndatatype lexp =\n    Nl int\n  | Vl var_name\n  | Plusl lexp lexp\n  | LET var_name lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"lval (Nl n)      _ = n\"                   |\n\"lval (Vl v)      s = s v\"                 |\n\"lval (Plusl x y) s = lval x s + lval y s\" |\n\"lval (LET v x y) s = lval y (s (v := lval x s))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl n)      = N n\"                        |\n\"inline (Vl v)      = V v\"                        |\n\"inline (Plusl x y) = Plus (inline x) (inline y)\" |\n\"inline (LET v x y) = subst v (inline x) (inline y)\"\n\ntheorem inline_preserves_semantics : \"lval e s = aval (inline e) s\"\napply(induction e arbitrary: s)\napply(auto)\napply(simp add: substitution_lemma)\ndone\n\n(** Section 3.2 Boolean expressions **)\n\ndatatype bexp =\n    Bc bool\n  | Not bexp\n  | And bexp bexp\n  | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc x)     _ = x\" |\n\"bval (Not e)    s = (\\<not> bval e s)\" |\n\"bval (And x y)  s = (bval x s \\<and> bval y s)\" |\n\"bval (Less x y) s = (aval x s < aval y s)\"\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc b)     = Bc (\\<not> b)\"      |\n\"not (Not e)    = e\"             |\n\"not (And x y)  = Not (And x y)\" |\n\"not (Less x y) = Not (Less x y)\"\n\nlemma not_preserves_semantics : \"bval (not e) s = (\\<not> bval e s)\"\napply(induction e)\napply(auto)\ndone\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and x          (Bc True)  = x\"        |\n\"and (Bc True)  y          = y\"        |\n\"and _          (Bc False) = Bc False\" |\n\"and (Bc False) _          = Bc False\" |\n\"and x          y          = And x y\"\n\nvalue \"False = False\"\nvalue \"bval (and (Bc True) (Bc False)) undef_state\"\nvalue \"bval (Bc True) undef_state \\<and> bval (Bc False) undef_state\"\nvalue \"bval (and (Bc True) (Bc False)) undef_state = (bval (Bc True) undef_state \\<and> bval (Bc False) undef_state)\"\n\nlemma and_preserves_semantics : \"bval (and e\\<^sub>1 e\\<^sub>2) s = (bval e\\<^sub>1 s \\<and> bval e\\<^sub>2 s)\"\napply(induction e\\<^sub>1 e\\<^sub>2 rule: and.induct)\napply(auto)\ndone\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N x) (N y) = Bc (x < y)\" |\n\"less x     y     = Less x y\"\n\nlemma less_preserves_semantics : \"bval (less e\\<^sub>1 e\\<^sub>2) s = (aval e\\<^sub>1 s < aval e\\<^sub>2 s)\"\napply(induction e\\<^sub>1 e\\<^sub>2 rule: less.induct)\napply(auto)\ndone\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc x)     = Bc x\"    |\n\"bsimp (Not e)    = not e\"   |\n\"bsimp (And x y)  = and x y\" |\n\"bsimp (Less x y) = less (asimp x) (asimp y)\"\n\ntheorem bsimp_preserves_semantics : \"bval (bsimp e) s = bval e s\"\napply(induction e)\napply(auto simp add: not_preserves_semantics and_preserves_semantics)\napply(auto simp add: less_preserves_semantics asimp_preserves_semantics)\ndone\n\n(* Exercise 3.7 *)\n\nfun Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq x y = And (Not (Less x y)) (Not (Less y x))\"\n\nfun Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le x y = Not (Less y x)\"\n\ntheorem eq_is_correct : \"bval (Eq e\\<^sub>1 e\\<^sub>2) s = (aval e\\<^sub>1 s = aval e\\<^sub>2 s)\"\napply(auto)\ndone\n\ntheorem le_is_correct : \"bval (Le e\\<^sub>1 e\\<^sub>2) s = (aval e\\<^sub>1 s \\<le> aval e\\<^sub>2 s)\"\napply(auto)\ndone\n\n(* Exercise 3.8 *)\n\ndatatype ifexp =\n    Bc2 bool\n  | If ifexp ifexp ifexp\n  | Less2 aexp aexp\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 b)     _ = b\"                                            |\n\"ifval (If c t f)  s = (if ifval c s then ifval t s else ifval f s)\" |\n\"ifval (Less2 x y) s = (aval x s < aval y s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc b)     = Bc2 b\"                                  |\n\"b2ifexp (Not x)    = If (b2ifexp x) (Bc2 False) (Bc2 True)\"  |\n\"b2ifexp (And x y)  = If (b2ifexp x) (b2ifexp y) (Bc2 False)\" |\n\"b2ifexp (Less x y) = Less2 x y\"\n\nlemma b2ifexp_preserves_semantics : \"ifval (b2ifexp e) s = bval e s\"\napply(induction e)\napply(auto)\ndone\n\nfun or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"or x y = Not (And (Not x) (Not y))\"\n\nlemma or_is_correct : \"bval (or e\\<^sub>1 e\\<^sub>2) s = (bval e\\<^sub>1 s \\<or> bval e\\<^sub>2 s)\"\napply(auto)\ndone\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 b)     = Bc b\"                                                                 |\n\"if2bexp (If c t f)  = or (And (if2bexp c) (if2bexp t)) (And (Not (if2bexp c)) (if2bexp f))\" |\n\"if2bexp (Less2 x y) = Less x y\"\n\ntheorem if2bexp_preserves_semantics : \"bval (if2bexp e) s = ifval e s\"\napply(induction e)\napply(auto)\ndone \n\n(* Exercise 3.9 *)\n\ndatatype pbexp =\n    VAR var_name\n  | NOT pbexp\n  | AND pbexp pbexp\n  | OR pbexp pbexp\n\nfun pbval :: \"pbexp \\<Rightarrow> (var_name \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR v)    s = s v\"                       |\n\"pbval (NOT e)    s = (\\<not> pbval e s)\"             |\n\"pbval (AND e\\<^sub>1 e\\<^sub>2) s = (pbval e\\<^sub>1 s \\<and> pbval e\\<^sub>2 s)\" |\n\"pbval (OR e\\<^sub>1 e\\<^sub>2)  s = (pbval e\\<^sub>1 s \\<or> pbval e\\<^sub>2 s)\"\n\n(* Is argument expression in Negation Normal Form - i.e. NOT is only applied to variables *)\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR _)       = True\"                  |\n\"is_nnf (NOT (VAR _)) = True\"                  |\n\"is_nnf (NOT _)       = False\"                 |\n\"is_nnf (AND x y)     = (is_nnf x \\<and> is_nnf y)\" |\n\"is_nnf (OR x y)      = (is_nnf x \\<or> is_nnf y)\"\n\n(* Convert expression to NNF *)\nfun nnf_go :: \"bool \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n\"nnf_go negate (VAR v)   = (if negate then NOT (VAR v) else VAR v)\"  |\n\"nnf_go negate (NOT x)   = nnf_go (\\<not> negate) x\"                      |\n\"nnf_go False  (AND x y) = AND (nnf_go False x) (nnf_go False y)\"     |\n\"nnf_go False  (OR x y)  = OR  (nnf_go False x) (nnf_go False y)\"     |\n\"nnf_go True   (AND x y) = OR  (nnf_go True x)  (nnf_go True y)\"      |\n\"nnf_go True   (OR x y)  = AND (nnf_go True x)  (nnf_go True y)\"\n\nlemma nnf_go_preserves_semantics : \"pbval (nnf_go b e) s = (if b then \\<not> pbval e s else pbval e s)\"\napply(induction b e rule: nnf_go.induct)\napply(simp_all)\ndone\n\nlemma nnf_go_is_correct : \"is_nnf (nnf_go b e)\"\napply(induction b e rule: nnf_go.induct)\napply(auto)\ndone\n\n\ndefinition nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf x = nnf_go False x\"\n\ntheorem nnf_preserves_semantics : \"pbval (nnf e) s = pbval e s\"\napply(simp add: nnf_def nnf_go_preserves_semantics)\ndone\n\ntheorem nnf_is_correct : \"is_nnf (nnf e)\"\napply(induction e)\napply(auto simp add: nnf_def nnf_go_is_correct)\ndone\n\nfun is_conjunct :: \"pbexp \\<Rightarrow> bool\" where\n\"is_conjunct (VAR _)   = True\"                            |\n\"is_conjunct (NOT _)   = True\"                            |\n\"is_conjunct (AND x y) = (is_conjunct x \\<and> is_conjunct y)\" |\n\"is_conjunct (OR x y)  = False\"\n\nfun is_disj_of_conj :: \"pbexp \\<Rightarrow> bool\" where\n\"is_disj_of_conj (VAR _)   = True\"                            |\n\"is_disj_of_conj (NOT _)   = True\"                            |\n\"is_disj_of_conj (AND x y) = (is_conjunct x \\<and> is_conjunct y)\" |\n\"is_disj_of_conj (OR x y)  = (is_disj_of_conj x \\<and> is_disj_of_conj y)\"\n\ndefinition is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf e = (is_nnf e \\<and> is_disj_of_conj e)\"\n\nfun mk_dnf_conj :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n(*\"mk_dnf_conj (OR x\\<^sub>1 y\\<^sub>1) (OR x\\<^sub>2 y\\<^sub>2) =\n  OR (mk_dnf_conj x\\<^sub>1 y\\<^sub>1)\n     (OR (mk_dnf_conj x\\<^sub>1 y\\<^sub>2)\n         (OR (mk_dnf_conj x\\<^sub>2 y\\<^sub>1)\n             (mk_dnf_conj x\\<^sub>2 y\\<^sub>2)))\" | *)\n\"mk_dnf_conj e         (OR y\\<^sub>1 y\\<^sub>2) = OR (mk_dnf_conj e y\\<^sub>1) (mk_dnf_conj e y\\<^sub>2)\" |\n\"mk_dnf_conj (OR x\\<^sub>1 x\\<^sub>2) e         = OR (mk_dnf_conj x\\<^sub>1 e) (mk_dnf_conj x\\<^sub>2 e)\" |\n\"mk_dnf_conj x          y         = AND x y\"\n\nlemma mk_dnf_conj_preserves_semantics : \"pbval (mk_dnf_conj e\\<^sub>1 e\\<^sub>2) s = (pbval e\\<^sub>1 s \\<and> pbval e\\<^sub>2 s)\"\napply(induction e\\<^sub>1 e\\<^sub>2 rule: mk_dnf_conj.induct)\napply(auto)\ndone\n\nlemma mk_dnf_conj_maintains_is_nnf : \"is_nnf e\\<^sub>1 \\<Longrightarrow> is_nnf e\\<^sub>2 \\<Longrightarrow> is_nnf (mk_dnf_conj e\\<^sub>1 e\\<^sub>2)\"\napply(induction e\\<^sub>1 e\\<^sub>2 rule: mk_dnf_conj.induct)\napply(auto)\ndone\n\nlemma mk_dnf_conj_maintains_is_disj_of_conj : \"is_disj_of_conj e\\<^sub>1 \\<Longrightarrow> is_disj_of_conj e\\<^sub>2 \\<Longrightarrow> is_disj_of_conj (mk_dnf_conj e\\<^sub>1 e\\<^sub>2)\"\napply(induction e\\<^sub>1 e\\<^sub>2 rule: mk_dnf_conj.induct)\napply(auto)\ndone\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR v)   = VAR v\"                                     |\n\"dnf_of_nnf (NOT e)   = NOT (dnf_of_nnf e)\"                        |\n\"dnf_of_nnf (AND x y) = mk_dnf_conj (dnf_of_nnf x) (dnf_of_nnf y)\" |\n\"dnf_of_nnf (OR x y)  = OR (dnf_of_nnf x) (dnf_of_nnf y)\"\n\ntheorem dnf_of_nnf_preserves_semantics : \"pbval (dnf_of_nnf e) s = pbval e s\"\napply(induction e)\napply(simp_all add: mk_dnf_conj_preserves_semantics)\ndone\n\n\nlemma nnf_of_negation : \"is_nnf (NOT e) \\<Longrightarrow> is_nnf e\"\napply(induction e)\napply(simp_all)\ndone\n\nlemma is_nnf_of_not : \"is_nnf (NOT e) \\<Longrightarrow> is_nnf (dnf_of_nnf e) \\<Longrightarrow> is_nnf (NOT (dnf_of_nnf e))\"\napply(induction e)\napply(simp_all)\ndone\n\nlemma dnf_of_nnf_maintains_is_nnf : \"is_nnf e \\<Longrightarrow> is_nnf (dnf_of_nnf e)\"\napply(induction e)\napply(auto simp add: nnf_of_negation)\napply(simp add: is_nnf_of_not)\napply(simp add: mk_dnf_conj_maintains_is_nnf)\ndone\n\nlemma dnf_of_nnf_maintains_is_disj_of_conj : \"is_disj_of_conj (dnf_of_nnf e)\"\napply(induction e)\napply(auto simp add: mk_dnf_conj_maintains_is_disj_of_conj)\ndone\n\ntheorem dnf_of_nnf_is_correct : \"is_nnf e \\<Longrightarrow> is_dnf (dnf_of_nnf e)\"\napply(induction e)\napply(simp_all add: is_dnf_def)\napply(simp add: dnf_of_nnf_maintains_is_nnf nnf_of_negation is_nnf_of_not)\napply(auto simp add: dnf_of_nnf_maintains_is_nnf dnf_of_nnf_maintains_is_disj_of_conj)\napply(simp add: dnf_of_nnf_maintains_is_nnf mk_dnf_conj_maintains_is_nnf)\napply(simp add: dnf_of_nnf_maintains_is_disj_of_conj mk_dnf_conj_maintains_is_disj_of_conj)\ndone\n\n(** Section 3.3 Stack Machine and Compilation **)\n\ndatatype instr = LOADI val | LOAD var_name | ADD\n\ndatatype stack = Stack \"val list\"\n\nfun push :: \"val \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"push x (Stack xs) = Stack (x # xs)\"\n\nfun top :: \"stack \\<Rightarrow> val\" where\n\"top (Stack (x # _)) = x\"\n\nfun top2 :: \"stack \\<Rightarrow> val\" where\n\"top2 (Stack (_ # x # _)) = x\"\n\nfun drop2 :: \"stack \\<Rightarrow> stack\" where\n\"drop2 (Stack (_ # _ # xs)) = Stack xs\"\n\nlemma top_of_push : \"top (push x xs) = x\"\napply(induction xs)\napply(simp)\ndone\n\nlemma top2_of_push_push : \"top2 (push x (push y zs)) = y\"\napply(induction zs)\napply(simp)\ndone\n\nlemma drop2_of_push_push : \"drop2 (push x (push y zs)) = zs\"\napply(induction)\napply(simp)\ndone\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk = push n stk\"     |\n\"exec1 (LOAD v)  s stk = push (s v) stk\" |\n\"exec1 ADD       _ stk = push (top stk + top2 stk) (drop2 stk)\"\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec []       _ stk = stk\" |\n\"exec (i # is) s stk = exec is s (exec1 i s stk)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n)      = [LOADI n]\" |\n\"comp (V v)      = [LOAD v]\"  |\n\"comp (Plus x y) = comp x @ comp y @ [ADD]\"\n\nlemma exec_composite_list_of_instructions : \"exec (is\\<^sub>1 @ is\\<^sub>2) s stk = exec is\\<^sub>2 s (exec is\\<^sub>1 s stk)\"\napply(induction is\\<^sub>1 arbitrary: stk)\napply(simp_all)\ndone\n\nlemma comp_is_correct : \"exec (comp e) s stk = push (aval e s) stk\"\napply(induction e arbitrary: stk)\napply(simp_all add: exec_composite_list_of_instructions)\napply(simp add: top_of_push top2_of_push_push drop2_of_push_push algebra_simps)\ndone\n\n(* Exercise 3.10 - See file Chapter3_ex3_10_ASM.thy *)\n\n(* Exercise 3.11 *)\n\ntype_synonym reg = nat\n\ndatatype reg_instr =\n    LDI int reg\n  | LD var_name reg\n  | ADD reg reg\n\nfun reg_exec1 :: \"reg_instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> (reg \\<Rightarrow> int)\" where\n\"reg_exec1 (LDI n r)  _ rs = rs (r := n)\"   |\n\"reg_exec1 (LD v r)   s rs = rs (r := s v)\" |\n\"reg_exec1 (ADD r\\<^sub>1 r\\<^sub>2) _ rs = rs (r\\<^sub>1 := rs r\\<^sub>1 + rs r\\<^sub>2)\"\n\nfun reg_exec :: \"reg_instr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> (reg \\<Rightarrow> int)\" where\n\"reg_exec []       _ f = f\" |\n\"reg_exec (i # is) s f = reg_exec is s (reg_exec1 i s f)\"\n\nlemma reg_exec_instruction_sequence : \"reg_exec (xs @ ys) s rs r = reg_exec ys s (reg_exec xs s rs) r\"\napply(induction xs arbitrary: rs)\napply(auto)\ndone\n\nfun reg_comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> reg_instr list\" where\n\"reg_comp (N n)      r = [LDI n r]\" |\n\"reg_comp (V v)      r = [LD v r]\"  |\n\"reg_comp (Plus x y) r =\n  (let r' = Suc r\n   in  reg_comp x r @ reg_comp y r' @ [ADD r r'])\"\n\nlemma reg_comp_preserves_lower_registers : \"r < r' \\<Longrightarrow> reg_exec (reg_comp e r') s rs r = rs r\"\napply(induction e arbitrary: rs r')\napply(auto simp add: reg_exec_instruction_sequence)\ndone\n\ntheorem reg_comp_preserves_semantics : \"reg_exec (reg_comp e r) s rs r = aval e s\"\napply(induction e arbitrary: rs r)\napply(auto)\napply(auto simp add: reg_exec_instruction_sequence reg_comp_preserves_lower_registers)\ndone\n\n(* Exercise 3.12 *)\n\n(* All operations except MV0 leave their result in register 0. MV0 takes its input from register 0 *)\ndatatype instr0 =\n    LDI0 val\n  | LD0 var_name\n  | MV0 reg\n  | ADD0 reg\n\nfun exec0_1 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> val) \\<Rightarrow> (reg \\<Rightarrow> val)\" where\n\"exec0_1 (LDI0 n) _ rs = rs (0 := n)\"    |\n\"exec0_1 (LD0 v)  s rs = rs (0 := s v)\"  |\n\"exec0_1 (MV0 r)  _ rs = rs (r := rs 0)\" |\n\"exec0_1 (ADD0 r) _ rs = rs (0 := rs 0 + rs r)\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> val) \\<Rightarrow> (reg \\<Rightarrow> val)\" where\n\"exec0 []       _ rs = rs\" |\n\"exec0 (i # is) s rs = exec0 is s (exec0_1 i s rs)\"\n\nlemma exec0_of_composite_instruction_list : \"exec0 (xs @ ys) s rs r = exec0 ys s (exec0 xs s rs) r\"\napply(induction xs arbitrary: rs)\napply(auto)\ndone\n\nfun comp0_with_intermed_reg :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0_with_intermed_reg (N n)      _ = [LDI0 n]\" |\n\"comp0_with_intermed_reg (V v)      _ = [LD0 v]\"  |\n\"comp0_with_intermed_reg (Plus x y) r = \n    comp0_with_intermed_reg x (Suc r)\n  @ [MV0 r]\n  @ comp0_with_intermed_reg y (Suc r)\n  @ [ADD0 r]\"\n\nlemma comp0_with_intermed_reg_preserves_lower_registers : \"0 < r \\<Longrightarrow> r < r' \\<Longrightarrow> exec0 (comp0_with_intermed_reg e r') s rs r = rs r\"\napply(induction e arbitrary: r' rs)\napply(auto simp add: exec0_of_composite_instruction_list)\ndone\n\nlemma comp0_with_intermed_reg_preserves_semantics : \"0 < r \\<Longrightarrow> exec0 (comp0_with_intermed_reg e r) s rs 0 = aval e s\"\napply(induction e arbitrary: r rs)\napply(auto simp add: exec0_of_composite_instruction_list comp0_with_intermed_reg_preserves_lower_registers)\ndone\n\nfun comp0 :: \"aexp \\<Rightarrow> instr0 list\" where\n\"comp0 e = comp0_with_intermed_reg e (Suc 0)\"\n\ntheorem comp0_preserves_semantics : \"exec0 (comp0 e) s rs 0 = aval e s\"\napply(induction e)\napply(simp_all add:\n      exec0_of_composite_instruction_list\n      comp0_with_intermed_reg_preserves_lower_registers\n      comp0_with_intermed_reg_preserves_semantics)\ndone\n\nend\n", "meta": {"author": "sergv", "repo": "isabelle-playground", "sha": "ab4fc19ca9d393a63584f42bea1ca23b651babce", "save_path": "github-repos/isabelle/sergv-isabelle-playground", "path": "github-repos/isabelle/sergv-isabelle-playground/isabelle-playground-ab4fc19ca9d393a63584f42bea1ca23b651babce/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194281, "lm_q2_score": 0.8519528038477824, "lm_q1q2_score": 0.7623184016703106}}
{"text": "theory Bondy\nimports Main\nbegin\n\nlemma card_less_if_surj_not_inj:\n  \"\\<lbrakk> finite A; f ` A = B; \\<not> inj_on f A \\<rbrakk> \\<Longrightarrow> card B < card A\"\nby (metis card_image_le inj_on_iff_eq_card order_le_neq_trans)\n\ntheorem Bondy : \n  assumes \"\\<forall>A \\<in> F. A \\<subseteq> X\" and \"card X \\<ge> 1\" and \"card F = card X\"\n  shows \"\\<exists>D. D \\<subseteq> X & card D < card X & card (inter D ` F) = card F\"\nproof -\n  from assms(2,3) have \"finite F\" and \"finite X\"\n    by (metis card.infinite not_one_le_zero)+\n  { fix m\n    have \"m < card F \\<Longrightarrow> \\<exists>D. D \\<subseteq> X & card D \\<le> m & card (inter D ` F) \\<ge> m + 1\"\n    proof (induction m)\n      case 0\n      hence \"{} \\<subseteq> X & card {} \\<le> 0 & card (inter {} ` F) \\<ge> 0 + 1\"\n        by auto (metis Suc_leI card_eq_0_iff empty_is_image finite_imageI gr0I)\n      thus \"\\<exists>D. (D \\<subseteq> X & card D \\<le> 0 & card (inter D ` F) \\<ge> 0 + 1)\" by blast\n    next\n      case (Suc m)\n      hence \"m < card F\" by arith\n      with Suc.IH obtain D\n        where D: \"D \\<subseteq> X \\<and> card D \\<le> m \\<and> m + 1 \\<le> card (inter D ` F)\" by auto\n      with \\<open>finite X\\<close> have \"finite D\" by (auto intro: finite_subset)\n      show ?case\n      proof (cases \"card (inter D ` F) = card F\")\n        case True\n        hence \"D \\<subseteq> X \\<and> card D \\<le> Suc m \\<and> Suc m + 1 \\<le> card(inter D ` F)\"\n          using D Suc.prems by auto\n        thus ?thesis by blast\n      next\n        case False\n        hence \"~ inj_on (inter D) F\" by (auto simp: card_image)\n        then obtain A1 A2 where \"A1 \\<in> F\" and \"A2 \\<in> F\" and \n          \"D \\<inter> A1 = D \\<inter> A2\" and \"A1 \\<noteq> A2\"  by (auto simp: inj_on_def)\n        then obtain x where x: \"x : (A1 - A2) \\<union> (A2 - A1)\" by auto\n        from \\<open>\\<forall>A \\<in> F. A \\<subseteq> X\\<close> \\<open>A1 \\<in> F\\<close> \\<open>A2 \\<in> F\\<close> x have \"x : X\" by auto\n        let ?E = \"insert x D\"\n        from D \\<open>finite D\\<close> have \"card ?E \\<le> Suc m\"\n          by (metis (full_types) Suc_le_mono card_insert_if le_Suc_eq)\n        moreover with D \\<open>x:X\\<close> have \"?E \\<subseteq> X\" by auto\n        moreover have \"Suc m < card (inter ?E ` F)\"\n        proof -\n          from \\<open>D \\<inter> A1 = D \\<inter> A2\\<close> have 1: \"(D \\<inter> (?E \\<inter> A1)) = (D \\<inter> (?E \\<inter> A2))\"\n            by auto\n          from x have 2: \"?E Int A1 \\<noteq> ?E Int A2\" by auto\n          have 3: \"inter D \\<circ> inter ?E = inter D\" by auto\n          have 4: \"~ inj_on (inter D) (inter ?E ` F)\"\n            unfolding inj_on_def using 1 2 \\<open>A1 \\<in> F\\<close> \\<open>A2 \\<in> F\\<close> by blast\n          from D have \"Suc m \\<le> card (inter D ` F)\" by auto\n          also have \"... < card (inter ?E ` F)\"\n            by (rule card_less_if_surj_not_inj[of _ \"inter D\"])\n              (auto simp add: image_image 3 4 \\<open>finite F\\<close>)\n          finally show ?thesis .\n        qed\n        ultimately have \"?E\\<subseteq>X \\<and> card ?E \\<le> Suc m \\<and> Suc m + 1 \\<le> card (inter ?E ` F)\" \n          by auto\n        thus \"\\<exists>D\\<subseteq>X. card D \\<le> Suc m \\<and> Suc m + 1 \\<le> card (inter D ` F)\" by blast\n      qed\n    qed\n  }\n  moreover from assms(2,3) have \"card X - 1 < card F\" by auto\n  ultimately obtain D where \n    \"D \\<subseteq> X & card D \\<le> card X - 1 & card (inter D ` F) \\<ge> (card X - 1) + 1\"\n    by auto\n  moreover with \\<open>finite F\\<close> have \"card (inter D ` F) \\<le> card F\"\n    by (elim card_image_le)\n  ultimately have \"D \\<subseteq> X & card D < card X & card (inter D ` F) = card F\"\n    using \\<open>card F = card X\\<close> by auto\n  thus ?thesis by auto\nqed\n\nend\n\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Bondy/Bondy.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8438951025545427, "lm_q1q2_score": 0.7622855594002443}}
{"text": "theory Bondy\nimports Main\nbegin\n\nlemma card_less_if_surj_not_inj:\n  \"\\<lbrakk> finite A; f ` A = B; \\<not> inj_on f A \\<rbrakk> \\<Longrightarrow> card B < card A\"\nby (metis card_image_le inj_on_iff_eq_card order_le_neq_trans)\n\ntheorem Bondy : \n  assumes \"\\<forall>A \\<in> F. A \\<subseteq> X\" and \"card X \\<ge> 1\" and \"card F = card X\"\n  shows \"\\<exists>D. D \\<subseteq> X & card D < card X & card (inter D ` F) = card F\"\nproof -\n  from assms(2,3) have \"finite F\" and \"finite X\"\n    by (metis card_infinite not_one_le_zero)+\n  { fix m\n    have \"m < card F \\<Longrightarrow> \\<exists>D. D \\<subseteq> X & card D \\<le> m & card (inter D ` F) \\<ge> m + 1\"\n    proof (induction m)\n      case 0\n      hence \"{} \\<subseteq> X & card {} \\<le> 0 & card (inter {} ` F) \\<ge> 0 + 1\"\n        by auto (metis Suc_leI card_eq_0_iff empty_is_image finite_imageI gr0I)\n      thus \"\\<exists>D. (D \\<subseteq> X & card D \\<le> 0 & card (inter D ` F) \\<ge> 0 + 1)\" by blast\n    next\n      case (Suc m)\n      hence \"m < card F\" by arith\n      with Suc.IH obtain D\n        where D: \"D \\<subseteq> X \\<and> card D \\<le> m \\<and> m + 1 \\<le> card (inter D ` F)\" by auto\n      with \\<open>finite X\\<close> have \"finite D\" by (auto intro: finite_subset)\n      show ?case\n      proof (cases \"card (inter D ` F) = card F\")\n        case True\n        hence \"D \\<subseteq> X \\<and> card D \\<le> Suc m \\<and> Suc m + 1 \\<le> card(inter D ` F)\"\n          using D Suc.prems by auto\n        thus ?thesis by blast\n      next\n        case False\n        hence \"~ inj_on (inter D) F\" by (auto simp: card_image)\n        then obtain A1 A2 where \"A1 \\<in> F\" and \"A2 \\<in> F\" and \n          \"D \\<inter> A1 = D \\<inter> A2\" and \"A1 \\<noteq> A2\"  by (auto simp: inj_on_def)\n        then obtain x where x: \"x : (A1 - A2) \\<union> (A2 - A1)\" by auto\n        from \\<open>\\<forall>A \\<in> F. A \\<subseteq> X\\<close> \\<open>A1 \\<in> F\\<close> \\<open>A2 \\<in> F\\<close> x have \"x : X\" by auto\n        let ?E = \"insert x D\"\n        from D \\<open>finite D\\<close> have \"card ?E \\<le> Suc m\"\n          by (metis (full_types) Suc_le_mono card_insert_if le_Suc_eq)\n        moreover with D \\<open>x:X\\<close> have \"?E \\<subseteq> X\" by auto\n        moreover have \"Suc m < card (inter ?E ` F)\"\n        proof -\n          from \\<open>D \\<inter> A1 = D \\<inter> A2\\<close> have 1: \"(D \\<inter> (?E \\<inter> A1)) = (D \\<inter> (?E \\<inter> A2))\"\n            by auto\n          from x have 2: \"?E Int A1 \\<noteq> ?E Int A2\" by auto\n          have 3: \"inter D \\<circ> inter ?E = inter D\" by auto\n          have 4: \"~ inj_on (inter D) (inter ?E ` F)\"\n            unfolding inj_on_def using 1 2 \\<open>A1 \\<in> F\\<close> \\<open>A2 \\<in> F\\<close> by blast\n          from D have \"Suc m \\<le> card (inter D ` F)\" by auto\n          also have \"... < card (inter ?E ` F)\"\n            by (rule card_less_if_surj_not_inj[of _ \"inter D\"])\n              (auto simp add: image_image 3 4 \\<open>finite F\\<close>)\n          finally show ?thesis .\n        qed\n        ultimately have \"?E\\<subseteq>X \\<and> card ?E \\<le> Suc m \\<and> Suc m + 1 \\<le> card (inter ?E ` F)\" \n          by auto\n        thus \"\\<exists>D\\<subseteq>X. card D \\<le> Suc m \\<and> Suc m + 1 \\<le> card (inter D ` F)\" by blast\n      qed\n    qed\n  }\n  moreover from assms(2,3) have \"card X - 1 < card F\" by auto\n  ultimately obtain D where \n    \"D \\<subseteq> X & card D \\<le> card X - 1 & card (inter D ` F) \\<ge> (card X - 1) + 1\"\n    by auto\n  moreover with \\<open>finite F\\<close> have \"card (inter D ` F) \\<le> card F\"\n    by (elim card_image_le)\n  ultimately have \"D \\<subseteq> X & card D < card X & card (inter D ` F) = card F\"\n    using \\<open>card F = card X\\<close> by auto\n  thus ?thesis by auto\nqed\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Bondy/Bondy.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7622855585527152}}
{"text": "(* \n  Title: Galois Connections\n  Author: Georg Struth \n  Maintainer: Georg Struth <g.struth@sheffield.ac.uk> \n*)\n\nsection \\<open>Galois Connections\\<close>\n\ntheory Galois_Connections\n  imports Order_Lattice_Props\n\nbegin\n\nsubsection \\<open>Definitions and Basic Properties\\<close>\n\ntext \\<open>The approach follows the Compendium of Continuous Lattices~\\<^cite>\\<open>\"GierzHKLMS80\"\\<close>, without attempting completeness. \nFirst, left and right adjoints of a Galois connection are defined.\\<close>\n\ndefinition adj :: \"('a::ord \\<Rightarrow> 'b::ord) \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> bool\" (infixl \"\\<stileturn>\" 70) where \n  \"(f \\<stileturn> g) = (\\<forall>x y. (f x \\<le> y) = (x \\<le> g y))\"\n\ndefinition \"ladj (g::'a::Inf \\<Rightarrow> 'b::ord) = (\\<lambda>x. \\<Sqinter>{y. x \\<le> g y})\"\n\ndefinition \"radj (f::'a::Sup \\<Rightarrow> 'b::ord)  = (\\<lambda>y. \\<Squnion>{x. f x \\<le> y})\"\n\nlemma ladj_radj_dual:\n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::ord_with_dual\"\n  shows \"ladj f x = \\<partial> (radj (\\<partial>\\<^sub>F f) (\\<partial> x))\"\nproof-\n  have \"ladj f x = \\<partial> (\\<Squnion>(\\<partial> ` {y. \\<partial> (f y) \\<le> \\<partial> x}))\"\n    unfolding ladj_def by (metis (no_types, lifting) Collect_cong Inf_dual_var dual_dual_ord dual_iff)\n  also have \"... =  \\<partial> (\\<Squnion>{\\<partial> y|y. \\<partial> (f y) \\<le> \\<partial> x})\"\n    by (simp add: setcompr_eq_image)\n  ultimately show ?thesis\n    unfolding ladj_def radj_def map_dual_def comp_def\n    by (smt Collect_cong invol_dual_var)\nqed\n\nlemma radj_ladj_dual: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::ord_with_dual\"\n  shows \"radj f x = \\<partial> (ladj (\\<partial>\\<^sub>F f) (\\<partial> x))\"\n  by (metis fun_dual5 invol_dual_var ladj_radj_dual map_dual_def)\n\nlemma ladj_prop: \n  fixes g :: \"'b::Inf \\<Rightarrow> 'a::ord_with_dual\"\n  shows \"ladj g = Inf \\<circ> (-`) g \\<circ> \\<up>\"\n  unfolding ladj_def vimage_def upset_prop fun_eq_iff comp_def by simp\n\nlemma radj_prop: \n  fixes f :: \"'b::Sup \\<Rightarrow> 'a::ord\"\n  shows \"radj f = Sup \\<circ> (-`) f \\<circ> \\<down>\"\n  unfolding radj_def vimage_def downset_prop fun_eq_iff comp_def by simp\n\ntext \\<open>The first set of properties holds without any sort assumptions.\\<close>\n\nlemma adj_iso1: \"f \\<stileturn> g \\<Longrightarrow> mono f\"\n  unfolding adj_def mono_def by (meson dual_order.refl dual_order.trans) \n\nlemma adj_iso2: \"f \\<stileturn> g \\<Longrightarrow> mono g\"\n  unfolding adj_def mono_def by (meson dual_order.refl dual_order.trans) \n\nlemma adj_comp: \"f \\<stileturn> g \\<Longrightarrow> adj h k \\<Longrightarrow> (f \\<circ> h) \\<stileturn> (k \\<circ> g)\"\n  by (simp add: adj_def)\n\nlemma adj_dual: \n  fixes f :: \"'a::ord_with_dual \\<Rightarrow> 'b::ord_with_dual\"\n  shows \"f \\<stileturn> g = (\\<partial>\\<^sub>F g) \\<stileturn> (\\<partial>\\<^sub>F f)\"\n  unfolding adj_def map_dual_def comp_def by (metis (mono_tags, opaque_lifting) dual_dual_ord invol_dual_var)\n\nsubsection \\<open>Properties for (Pre)Orders\\<close>\n\ntext \\<open>The next set of properties holds in preorders or orders.\\<close>\n\nlemma adj_cancel1: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::ord\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> f \\<circ> g \\<le> id\"\n  by (simp add: adj_def le_funI)\n\nlemma adj_cancel2: \n  fixes f :: \"'a::ord \\<Rightarrow> 'b::preorder\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> id \\<le> g \\<circ> f\"\n  by (simp add: adj_def eq_iff le_funI)\n\nlemma adj_prop: \n  fixes f :: \"'a::preorder \\<Rightarrow>'a\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> f \\<circ> g \\<le> g \\<circ> f\"\n  using adj_cancel1 adj_cancel2 order_trans by blast\n\nlemma adj_cancel_eq1: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> f \\<circ> g \\<circ> f = f\"\n  unfolding adj_def comp_def fun_eq_iff by (meson eq_iff order_refl order_trans)\n\nlemma adj_cancel_eq2: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::preorder\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> g \\<circ> f \\<circ> g = g\"\n  unfolding adj_def comp_def fun_eq_iff by (meson eq_iff order_refl order_trans) \n\nlemma adj_idem1: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> (f \\<circ> g) \\<circ> (f \\<circ> g) = f \\<circ> g\"\n  by (simp add: adj_cancel_eq1 rewriteL_comp_comp)\n\nlemma adj_idem2: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::preorder\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> (g \\<circ> f) \\<circ> (g \\<circ> f) = g \\<circ> f\"\n  by (simp add: adj_cancel_eq2 rewriteL_comp_comp)\n\nlemma adj_iso3: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> mono (f \\<circ> g)\"\n   by (simp add: adj_iso1 adj_iso2 monoD monoI)\n\nlemma adj_iso4: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> mono (g \\<circ> f)\"\n  by (simp add: adj_iso1 adj_iso2 monoD monoI)\n\nlemma adj_canc1: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::ord\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((f \\<circ> g) x = (f \\<circ> g) y \\<longrightarrow> g x = g y)\"\n  unfolding adj_def comp_def by (metis eq_iff)\n \nlemma adj_canc2: \n  fixes f :: \"'a::ord \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((g \\<circ> f) x = (g \\<circ> f) y \\<longrightarrow> f x = f y)\"\n  unfolding adj_def comp_def by (metis eq_iff)\n\nlemma adj_sur_inv: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((surj f) = (f \\<circ> g = id))\"\n  unfolding adj_def surj_def comp_def by (metis eq_id_iff eq_iff order_refl order_trans)\n\nlemma adj_surj_inj: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((surj f) = (inj g))\"\n  unfolding adj_def inj_def surj_def by (metis eq_iff order_trans)\n\nlemma adj_inj_inv: \n  fixes f :: \"'a::preorder \\<Rightarrow> 'b::order\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> ((inj f) = (g \\<circ> f = id))\"\n  by (metis adj_cancel_eq1 eq_id_iff inj_def o_apply)\n\nlemma adj_inj_surj: \n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\" \n  shows \"f \\<stileturn> g \\<Longrightarrow> ((inj f) = (surj g))\"\n  unfolding adj_def inj_def surj_def by (metis eq_iff order_trans)\n\nlemma surj_id_the_inv: \"surj f \\<Longrightarrow> g \\<circ> f = id \\<Longrightarrow> g = the_inv f\"\n  by (metis comp_apply id_apply inj_on_id inj_on_imageI2 surj_fun_eq the_inv_f_f)\n\nlemma inj_id_the_inv: \"inj f \\<Longrightarrow> f \\<circ> g = id \\<Longrightarrow> f = the_inv g\"\nproof -\n  assume a1: \"inj f\"\n  assume \"f \\<circ> g = id\"\n  hence \"\\<forall>x. the_inv g x = f x\"\n    using a1 by (metis (no_types) comp_apply eq_id_iff inj_on_id inj_on_imageI2 the_inv_f_f)\n  thus ?thesis \n    by presburger\nqed\n\n\nsubsection \\<open>Properties for Complete Lattices\\<close>\n\ntext \\<open>The next laws state that a function between complete lattices preserves infs \n  if and only if it has a lower adjoint.\\<close>\n\nlemma radj_Inf_pres: \n  fixes g :: \"'b::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  shows \"(\\<exists>f. f \\<stileturn> g) \\<Longrightarrow> Inf_pres g\"\n  apply (rule antisym, simp_all add: le_fun_def adj_def, safe)\n  apply (meson INF_greatest Inf_lower dual_order.refl dual_order.trans)\n  by (meson Inf_greatest dual_order.refl le_INF_iff)\n\nlemma ladj_Sup_pres: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows \"(\\<exists>g. f \\<stileturn> g) \\<Longrightarrow> Sup_pres f\"\n  using Sup_pres_map_dual_var adj_dual radj_Inf_pres by blast\n\nlemma radj_adj: \n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"f \\<stileturn> g \\<Longrightarrow> g = (radj f)\"\n  unfolding adj_def radj_def by (metis (mono_tags, lifting) cSup_eq_maximum eq_iff mem_Collect_eq)\n\nlemma ladj_adj: \n  fixes g :: \"'b::complete_lattice_with_dual \\<Rightarrow> 'a::complete_lattice_with_dual\" \n  shows \"f \\<stileturn> g \\<Longrightarrow> f = (ladj g)\"\n  unfolding adj_def ladj_def by (metis (no_types, lifting) cInf_eq_minimum eq_iff mem_Collect_eq)\n\nlemma Inf_pres_radj_aux: \n  fixes g :: \"'a::complete_lattice \\<Rightarrow> 'b::complete_lattice\"\n  shows \"Inf_pres g \\<Longrightarrow> (ladj g) \\<stileturn> g\"\nproof-\n  assume a: \"Inf_pres g\"\n  {fix x y\n   assume b: \"ladj g x \\<le> y\" \n  hence \"g (ladj g x) \\<le> g y\"\n    by (simp add: Inf_subdistl_iso a monoD)\n  hence \"\\<Sqinter>{g y |y. x \\<le> g y} \\<le> g y\"\n    by (metis a comp_eq_dest_lhs setcompr_eq_image ladj_def)\n  hence \"x \\<le> g y\"\n    using dual_order.trans le_Inf_iff by blast  \n  hence \"ladj g x \\<le> y \\<longrightarrow> x \\<le> g y\"\n    by simp}\n  thus ?thesis \n    unfolding adj_def ladj_def by (meson CollectI Inf_lower)\nqed\n\nlemma Sup_pres_ladj_aux: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\" \n  shows \"Sup_pres f \\<Longrightarrow> f \\<stileturn> (radj f)\"\n  by (metis (no_types, opaque_lifting) Inf_pres_radj_aux Sup_pres_map_dual_var adj_dual fun_dual5 map_dual_def radj_adj)\n\nlemma Inf_pres_radj: \n  fixes g :: \"'b::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  shows \"Inf_pres g \\<Longrightarrow> (\\<exists>f. f \\<stileturn> g)\"\n  using Inf_pres_radj_aux by fastforce\n\nlemma Sup_pres_ladj: \n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows \"Sup_pres f \\<Longrightarrow> (\\<exists>g. f \\<stileturn> g)\"\n  using Sup_pres_ladj_aux by fastforce\n\nlemma Inf_pres_upper_adj_eq: \n  fixes g :: \"'b::complete_lattice \\<Rightarrow> 'a::complete_lattice\"\n  shows \"(Inf_pres g) = (\\<exists>f. f \\<stileturn> g)\"\n  using radj_Inf_pres Inf_pres_radj by blast\n\nlemma Sup_pres_ladj_eq:\n  fixes f :: \"'a::complete_lattice_with_dual \\<Rightarrow> 'b::complete_lattice_with_dual\"\n  shows  \"(Sup_pres f) = (\\<exists>g. f \\<stileturn> g)\"\n  using Sup_pres_ladj ladj_Sup_pres by blast\n\nlemma Sup_downset_adj: \"(Sup::'a::complete_lattice set \\<Rightarrow> 'a) \\<stileturn> \\<down>\"\n  unfolding adj_def downset_prop Sup_le_iff by force\n\nlemma Sup_downset_adj_var: \"(Sup (X::'a::complete_lattice set) \\<le> y) = (X \\<subseteq> \\<down>y)\"\n  using Sup_downset_adj adj_def by auto\n\ntext \\<open>Once again many statements arise by duality, which Isabelle usually picks up.\\<close>\n\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Order_Lattice_Props/Galois_Connections.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.8438950947024556, "lm_q1q2_score": 0.7622855567014005}}
{"text": "theory Ex3_8\nimports\n  \"~~/src/HOL/IMP/BExp\"\nbegin\n\n(*\nBy: Vadim Zaliva <vzaliva@cmu.edu>\nFrom: T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL. Springer, 2014.\nExercise 3.8:\n*)\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n  \"ifval (Bc2 v) s = v\" \n  | \"ifval (If cond_exp then_branch else_branch) s = ifval (if ifval cond_exp s then then_branch else else_branch) s\"\n  | \"ifval (Less2 a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n  \"b2ifexp (Bc v) = Bc2 v\" \n  | \"b2ifexp (Less a1 a2) = Less2 a1 a2\"\n  | \"b2ifexp (Not b) = If (b2ifexp b) (Bc2 False) (Bc2 True)\" \n  | \"b2ifexp (And b1 b2) = If (b2ifexp b1) (If (b2ifexp b2) (Bc2 True) (Bc2 False)) (Bc2 False)\" \n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n  \"if2bexp (Bc2 v) = Bc v\" \n  | \"if2bexp (Less2 a1 a2) = Less a1 a2\"\n  | \"if2bexp (If cond_exp then_branch else_branch) = \n  (Not \n  (And \n     (Not (And (if2bexp cond_exp) (if2bexp then_branch)))\n     (Not (And (Not (if2bexp cond_exp)) (if2bexp else_branch)))\n  ))\"\n\ntheorem \"bval exp s = ifval (b2ifexp exp) s\"\n  apply(induction exp)\n  apply(auto)\ndone\n\ntheorem \"ifval exp s = bval (if2bexp exp) s\"\n  apply(induction exp)\n  apply(auto)\ndone\n\nend\n\n\n", "meta": {"author": "vzaliva", "repo": "isabelle-semantics-ex", "sha": "4e1acf1c9850f17057dd98454e42262d01301670", "save_path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex", "path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex/isabelle-semantics-ex-4e1acf1c9850f17057dd98454e42262d01301670/Ex3_8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8670357701094303, "lm_q1q2_score": 0.7622516891160265}}
{"text": "theory Ex1_7\n  imports Main \nbegin \n  \n  \nprimrec  list_union :: \"['a list , 'a list] \\<Rightarrow> 'a list\" where \n  \"list_union [] ys = ys\"|\n  \"list_union (x # xs) ys = (let res = list_union xs ys in if x \\<in> set res then res else x # res)\"  \n\n\nlemma \"set (list_union xs ys) = set xs \\<union> set ys\" \nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume hyp:\"set (list_union xs ys) = set xs \\<union> set ys\"\n  let ?tmp = \"list_union xs ys\"\n  have \"set (list_union (a # xs) ys) =  set (if a \\<in> set ?tmp then ?tmp else a # ?tmp )\" by simp\n  then show ?case \n  proof (cases \"a \\<in> set ?tmp\")\n    case True\n    assume a:\"a \\<in> set (list_union xs ys)\"\n    then show ?thesis by (auto simp add : hyp)\n  next\n    case False\n    then show ?thesis by (auto simp add : hyp)\n  qed\nqed\n  \n  \nlemma [rule_format] : \"distinct xs \\<longrightarrow> distinct ys \\<longrightarrow> (distinct (list_union xs ys))\" \nproof (induct xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  assume hyp:\"distinct xs \\<longrightarrow> distinct ys \\<longrightarrow> distinct (list_union xs ys)\"\n  show ?case  \n  proof (cases \"a \\<in> set (list_union xs ys)\")\n    case True\n    assume \"a \\<in> set (list_union xs ys)\"    \n    then show ?thesis using hyp by simp \n  next\n    case False\n    assume \"a \\<notin> set (list_union xs ys)\"\n    then show ?thesis using hyp by simp\n  qed\nqed\n  \n  \nlemma \"((\\<forall> x \\<in> A . P x) \\<and> (\\<forall> x \\<in> B . P x)) \\<longrightarrow> (\\<forall> x \\<in> A \\<union> B  . P x)\" \n  using [[simp_trace_new mode=full]]\nproof -\n  {\n    assume a:\"(\\<forall> x \\<in> A . P x) \\<and> (\\<forall> x \\<in> B . P x)\"\n    hence b:\"\\<forall> x \\<in> A . P x\" by simp\n    from a have c:\"\\<forall> x \\<in> B . P x\" by simp\n    with b have \"\\<forall> x \\<in> A \\<union> B . P x\" by auto\n  }\n  thus ?thesis by (rule impI)\nqed\n  \nlemma \"\\<forall>x \\<in> A . Q (f x) \\<Longrightarrow> \\<forall> y \\<in> f ` A . Q y\"  by blast", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/1. Lists/Ex1_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.7620868583276917}}
{"text": "theory week12A_demo imports Main begin\n\n-- ------------------------------------------------------------------\n\ntext {* Motivation *}\n\nlemma \"(A \\<longrightarrow> B) = (B \\<or> \\<not>A)\"\nby blast\n\nvalue \"True \\<longrightarrow> False\"\nvalue \"False \\<or> \\<not> True\"\n\nlemma \"(A \\<longrightarrow> B) = (B \\<or> \\<not>A)\"\n  (* apply style *)\n  apply(rule iffI)\n   apply(case_tac A)\n    apply(erule (1) impE)\n    apply(erule disjI1)\n   apply(erule disjI2)\n  apply(erule disjE)\n   apply(rule impI)\n   apply assumption\n  apply(rule impI)\n  apply(erule notE)\n  apply assumption\n  done\n\nlemma \"(A \\<longrightarrow> B) = (B \\<or> \\<not>A)\"\nproof (rule iffI)\n  assume AB: \"A \\<longrightarrow> B\"\n  show \"B \\<or> \\<not> A\"\n  proof (case_tac A)\n    assume A: \"A\"\n    from AB A have \"B\" by(rule impE)\n    thus ?thesis by(rule disjI1)\n  next\n    assume \"\\<not> A\"\n    thus ?thesis by (rule disjI2)\n  qed\nnext\n  assume \"B \\<or> \\<not> A\"\n  thus \"A \\<longrightarrow> B\"\n  proof (rule disjE)\n    assume \"B\"\n    thus ?thesis by(rule impI)\n  next\n    assume notA: \"\\<not> A\"\n    show ?thesis\n    proof (rule impI)\n      assume \"A\"\n      from notA this show \"B\" by (rule notE)\n    qed\n  qed\nqed\n\n\n-- ----------------------------------------\n\ntext {* Isar *}\n\nlemma \"\\<lbrakk> A; B \\<rbrakk> \\<Longrightarrow> A \\<and> B\"\nproof\n  assume \"A\"\n  from this show \"A\" by assumption\nnext\n  assume \"B\"\n  from this show \"B\" by assumption\nqed\n\nlemma\n  assumes PorQ: \"P \\<or> Q\"\n  shows \"Q \\<or> P\"\nusing PorQ proof\n  assume P: \"P\"\n  from P show \"Q \\<or> P\" by(rule disjI2)\nnext\n  assume \"Q\"\n  from this show \"Q \\<or> P\" by(rule disjI1)\nqed\n\nlemma\n  assumes \"A\"\n  assumes B_is_true: \"B\"\n  shows \"A \\<and> B\"\nproof(rule conjI)\n  show \"B\" by (rule B_is_true)\n  from `A` show \"A\" by assumption\nqed\n\nlemma \"(x::nat) + 1 = 1 + x\"\nproof -\n  have l: \"x + 1 = Suc x\" by simp\n  have r: \"1 + x = Suc x\" by simp\n  show \"x + 1 = 1 + x\" by (simp only: l r)\nqed\n\n-- ------------------------------------------------------------------\n\nsection \"More Isar\"\n\ntext {* . = by assumption,  .. = by rule *}\n\nlemma \"\\<lbrakk> A; B \\<rbrakk> \\<Longrightarrow> B \\<and> A\"\nproof\n  assume \"B\"\n  from `B` show \"B\"  .\nnext\n  assume \"A\" from this show \"A\" .\nqed\n\nlemma \"\\<lbrakk> A; B \\<rbrakk> \\<Longrightarrow> B \\<and> A\"\nproof -\n  assume B: \"B\" and A: \"A\"\n  from B A show \"B \\<and> A\" by(rule conjI)\nqed\n\ntext {* backward/forward *}\n\nlemma \"A \\<and> B \\<longrightarrow> B \\<and> A\"\nproof\n  assume \"A \\<and> B\"\n  from this have \"A\" ..\n  from `A \\<and> B` have \"B\" ..\n  from `B` `A` show \"B \\<and> A\" ..\nqed\n\ntext{* fix *}\n\nlemma\n  assumes P: \"\\<forall>x. P x\"\n  shows \"\\<forall>x. P (f x)\"\nproof\n  fix a\n  from P show \"P (f a)\" by(rule spec)\nqed\n\ntext{* Proof text can only refer to global constants, free variables\nin the lemma, and local names introduced via fix or obtain. *}\n\nlemma\n  assumes Pf: \"\\<exists>x. P (f x)\"\n  shows \"\\<exists>y. P y\"\nproof -\n  from Pf show ?thesis\n  proof\n    fix x\n    assume \"P (f x)\"\n    from this show ?thesis ..\n  qed\nqed\n\ntext {* obtain *}\n\nlemma\n  assumes Pf: \"\\<exists>x. P (f x)\"\n  shows \"\\<exists>y. P y\"\nproof -\n  from Pf obtain x where \"P (f x)\" ..\n  from this show ?thesis ..\nqed\n\nlemma\n  assumes ex: \"\\<exists>x. \\<forall>y. P x y\"\n  shows \"\\<forall>y. \\<exists>x. P x y\"\nproof\n  fix y\n  show \"\\<exists>x. P x y\"\n  proof -\n    from ex obtain x where \"\\<forall>y. P x y\" ..\n    hence \"P x y\" ..\n    thus ?thesis ..\n  qed\nqed\n\n\ntext {* moreover *}\n\nlemma \"A \\<and> B \\<longrightarrow> B \\<and> A\"\nproof\n  assume \"A \\<and> B\"\n  from `A \\<and> B` have \"B\" ..\n  moreover from `A \\<and> B` have \"A\" ..\n  ultimately show \"B \\<and> A\" ..\nqed\n\nthm mono_def\nthm monoI\n\nlemma\n  assumes mono_f: \"mono (f::int\\<Rightarrow>int)\"\n      and mono_g: \"mono (g::int\\<Rightarrow>int)\"\n  shows \"mono (\\<lambda>i. f i + g i)\"\nproof\n  fix x y\n  assume le: \"(x::int) \\<le> y\"\n  from mono_f le have \"f x \\<le> f y\" ..\n  moreover from mono_g le have \"g x \\<le> g y\" ..\n  ultimately show \"f x + g x \\<le> f y + g y\" by(rule add_mono)\nqed\n\n-- ---------------------------------------------------------------\n\n-- {* Isar, case distinction *}\n\ndeclare length_tl[simp del]\n\n(* isar style, just using \"proof (cases xs)\", not using case *)\nlemma \"length (tl xs) = length xs - 1\"\nproof(cases xs)\n  assume \"xs = []\" thus ?thesis by simp\nnext\n  fix y ys assume \"xs = y#ys\" thus ?thesis by simp\nqed\n\n(* isar style, using case *)\nlemma \"length (tl xs) = length xs - 1\"\nproof(cases xs)\n  case Nil\n  thus ?thesis by simp\nnext\n  case (Cons y ys)\n  from Cons show ?thesis by simp\nqed\n\n\n-- {* structural induction *}\n\n(* apply style *)\nlemma \"2 * (\\<Sum>i<n+1. i) = n*(n+1::nat)\"\n  apply(induct n, simp_all)\n  done\n\n(* isar style, not using case *)\nlemma \"2 * (\\<Sum>i<n+1. i) = n*(n+1::nat)\" (is \"?P n\")\nproof(induct n)\n  show \"?P 0\" by simp\nnext\n  fix n\n  assume \"?P n\"\n  thus \"?P (Suc n)\" by simp\nqed\n\n(* isar style, using case *)\nlemma \"2 * (\\<Sum>i<n+1. i) = n*(n+1::nat)\"\nproof(induct n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  from Suc show ?case by simp\nqed\n\n\nlemma\n  fixes n::nat\n  shows \"n < n*n + 1\"\nproof(induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n) from this show ?case by simp\nqed\n\n-- {* induction with @{text\"\\<And>\"} or @{text\"\\<Longrightarrow>\"} *}\n\nlemma\n  assumes A: \"(\\<And>n. (\\<And>m. m < n \\<Longrightarrow> P m) \\<Longrightarrow> P n)\"\n  shows \"P (n::nat)\"\nproof(rule A)\n  show \"\\<And>m. m < n \\<Longrightarrow> P m\"\n  proof(induct n)\n    case 0\n    thus ?case by simp\n  next\n    case (Suc n)\n    show ?case\n    proof(cases)\n      assume eq: \"m = n\"\n      from A Suc have \"P n\" by blast\n      with eq show \"P m\" by simp\n    next\n      assume neq: \"m \\<noteq> n\"\n      from Suc neq have \"m < n\" by arith\n      thus \"P m\" by(rule Suc)\n    qed\n  qed\nqed\n\n\n-- ---------------------------------------------------------------\n\n-- \"calculational reasoning\"\n\n-- \"also/finally\"\n\n\nlemma right_inverse:\n  fixes prod :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"    (infixl \"\\<cdot>\" 70)\n  fixes inv :: \"'a \\<Rightarrow> 'a\"    (\"(_\\<^sup>-)\" [1000] 999)\n  fixes one :: 'a    (\"\\<one>\")\n\n  assumes assoc: \"\\<And>x y z. (x \\<cdot> y) \\<cdot> z = x \\<cdot> (y \\<cdot> z)\"\n  assumes left_inv: \"\\<And>x. x\\<^sup>- \\<cdot> x = \\<one>\"\n  assumes left_one: \"\\<And>x. \\<one> \\<cdot> x = x\"\n\n  shows \"x \\<cdot> x\\<^sup>- = \\<one>\"\nproof -\n  have \"x \\<cdot> x\\<^sup>- = \\<one> \\<cdot> (x \\<cdot> x\\<^sup>-)\" by (simp only: left_one)\n  also have \"\\<dots> = \\<one> \\<cdot> x \\<cdot> x\\<^sup>-\" by (simp only: assoc)\n  also have \"\\<dots> = (x\\<^sup>-)\\<^sup>- \\<cdot> x\\<^sup>- \\<cdot> x \\<cdot> x\\<^sup>-\" by (simp only: left_inv)\n  also have \"\\<dots> = (x\\<^sup>-)\\<^sup>- \\<cdot> (x\\<^sup>- \\<cdot> x) \\<cdot> x\\<^sup>-\" by (simp only: assoc)\n  also have \"\\<dots> = (x\\<^sup>-)\\<^sup>- \\<cdot> \\<one> \\<cdot> x\\<^sup>-\" by (simp only: left_inv)\n  also have \"\\<dots> = (x\\<^sup>-)\\<^sup>- \\<cdot> (\\<one> \\<cdot> x\\<^sup>-)\" by (simp only: assoc)\n  also have \"\\<dots> = (x\\<^sup>-)\\<^sup>- \\<cdot> x\\<^sup>-\" by (simp only: left_one)\n  also have \"\\<dots> = \\<one>\" by (simp only: left_inv)\n  finally show ?thesis .\nqed\n\n\nprint_trans_rules\n\n-- \"mixed operators\"\nlemma \"1 < (5::nat)\"\nproof -\n  have \"1 < Suc 1\" by simp\n  also\n  have \"Suc 1 = 2\" by simp\n  also\n  have \"2 \\<le> (5::nat)\" by simp\n  finally\n  show ?thesis .\nqed\n\n-- \"substitution\"\nlemma blah\nproof -\n  have \"2*y + 2*y = (0::nat)\" sorry\n  also\n  have \"2*y = x\" sorry\n  also\n  have \"(0::nat) \\<le> 2*c\" sorry\n  also\n  have \"c = d div 2\" sorry\n  also\n  have \"d = 2 * x\" sorry\n  finally\n  have \"x + x \\<le> 2 * x \" by simp\noops\n\nprint_trans_rules\n\n-- \"antisymmetry\"\nlemma blub\nproof -\n  have \"a < (b::nat)\" sorry\n  also\n  have \"b < a\" sorry\n  finally\n  show blub .\nqed\n\n\n-- \"notE as trans\"\n\nthm notE\ndeclare notE [trans]\n\nlemma blub\nproof -\n  have \"\\<not>P\" sorry\n  also\n  have \"P\" sorry\n  finally\n  show blub .\nqed\n\n\n-- \"monotonicity\"\n\nlemma \"a+b \\<le> 2*a + 2*(b::nat)\"\nproof -\n  have \"a + b \\<le> 2*a + b\" by simp\n  also\n  have \"b \\<le> 2*b\" by simp\n  finally\n  show \"a+b \\<le> 2*a + 2*b\" by simp\nqed\n\nlemma \"a+b \\<le> 2*a + 2*(b::nat)\"\nproof -\n  have \"a + b \\<le> 2*a + b\" by simp\n  also\n  have \"b \\<le> 2*b\" by simp\n  also\n  have \"\\<And>x y. x \\<le> y \\<Longrightarrow> 2 * a + x \\<le> 2 * a + y\" by simp\n  ultimately\n  show \"a+b \\<le> 2*a + 2*(b::nat)\" .\nqed\n\ndeclare algebra_simps [simp]\nlemma \"(a+b::int)\\<^sup>2 \\<le> 2*(a\\<^sup>2 + b\\<^sup>2)\"\nproof -\n       have \"(a+b)\\<^sup>2 \\<le> (a+b)\\<^sup>2 + (a-b)\\<^sup>2\" by simp thm numeral_2_eq_2\n  also have \"(a+b)\\<^sup>2 \\<le> a\\<^sup>2 + b\\<^sup>2 + 2*a*b\" by (simp add: numeral_2_eq_2)\n  also have \"(a-b)\\<^sup>2 = a\\<^sup>2 + b\\<^sup>2 - 2*a*b\" by (simp add:numeral_2_eq_2)\n  finally show ?thesis by simp\nqed\n\n-- ---------------------------------------------------------------\n\nend", "meta": {"author": "z5146542", "repo": "TOR", "sha": "9a82d491288a6d013e0764f68e602a63e48f92cf", "save_path": "github-repos/isabelle/z5146542-TOR", "path": "github-repos/isabelle/z5146542-TOR/TOR-9a82d491288a6d013e0764f68e602a63e48f92cf/181211/week12A_demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8807970826714614, "lm_q1q2_score": 0.762086853913001}}
{"text": "(* Authors: Heiko Loetzbeyer, Robert Sandner, Tobias Nipkow *)\n\nsection \"Denotational Semantics of Commands\"\n\ntheory Denotational imports Big_Step begin\n\ntype_synonym com_den = \"(state \\<times> state) set\"\n\ndefinition W :: \"(state \\<Rightarrow> bool) \\<Rightarrow> com_den \\<Rightarrow> (com_den \\<Rightarrow> com_den)\" where\n\"W db dc = (\\<lambda>dw. {(s,t). if db s then (s,t) \\<in> dc O dw else s=t})\"\n\nfun D :: \"com \\<Rightarrow> com_den\" where\n\"D SKIP   = Id\" |\n\"D (x ::= a) = {(s,t). t = s(x := aval a s)}\" |\n\"D (c1;;c2)  = D(c1) O D(c2)\" |\n\"D (IF b THEN c1 ELSE c2)\n = {(s,t). if bval b s then (s,t) \\<in> D c1 else (s,t) \\<in> D c2}\" |\n\"D (WHILE b DO c) = lfp (W (bval b) (D c))\"\n\nlemma W_mono: \"mono (W b r)\"\nby (unfold W_def mono_def) auto\n\nlemma D_While_If:\n  \"D(WHILE b DO c) = D(IF b THEN c;;WHILE b DO c ELSE SKIP)\"\nproof-\n  let ?w = \"WHILE b DO c\" let ?f = \"W (bval b) (D c)\"\n  have \"D ?w = lfp ?f\" by simp\n  also have \"\\<dots> = ?f (lfp ?f)\" by(rule lfp_unfold [OF W_mono])\n  also have \"\\<dots> = D(IF b THEN c;;?w ELSE SKIP)\" by (simp add: W_def)\n  finally show ?thesis .\nqed\n\ntext\\<open>Equivalence of denotational and big-step semantics:\\<close>\n\nlemma D_if_big_step:  \"(c,s) \\<Rightarrow> t \\<Longrightarrow> (s,t) \\<in> D(c)\"\nproof (induction rule: big_step_induct)\n  case WhileFalse\n  with D_While_If show ?case by auto\nnext\n  case WhileTrue\n  show ?case unfolding D_While_If using WhileTrue by auto\nqed auto\n\nabbreviation Big_step :: \"com \\<Rightarrow> com_den\" where\n\"Big_step c \\<equiv> {(s,t). (c,s) \\<Rightarrow> t}\"\n\nlemma Big_step_if_D:  \"(s,t) \\<in> D(c) \\<Longrightarrow> (s,t) \\<in> Big_step c\"\nproof (induction c arbitrary: s t)\n  case Seq thus ?case by fastforce\nnext\n  case (While b c)\n  let ?B = \"Big_step (WHILE b DO c)\" let ?f = \"W (bval b) (D c)\"\n  have \"?f ?B \\<subseteq> ?B\" using While.IH by (auto simp: W_def)\n  from lfp_lowerbound[where ?f = \"?f\", OF this] While.prems\n  show ?case by auto\nqed (auto split: if_splits)\n\ntheorem denotational_is_big_step:\n  \"(s,t) \\<in> D(c)  =  ((c,s) \\<Rightarrow> t)\"\nby (metis D_if_big_step Big_step_if_D[simplified])\n\ncorollary equiv_c_iff_equal_D: \"(c1 \\<sim> c2) \\<longleftrightarrow> D c1 = D c2\"\nby(simp add: denotational_is_big_step[symmetric] set_eq_iff)\n\n\nsubsection \"Continuity\"\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> bool\" where\n\"chain S = (\\<forall>i. S i \\<subseteq> S(Suc i))\"\n\nlemma chain_total: \"chain S \\<Longrightarrow> S i \\<le> S j \\<or> S j \\<le> S i\"\nby (metis chain_def le_cases lift_Suc_mono_le)\n\ndefinition cont :: \"('a set \\<Rightarrow> 'b set) \\<Rightarrow> bool\" where\n\"cont f = (\\<forall>S. chain S \\<longrightarrow> f(UN n. S n) = (UN n. f(S n)))\"\n\nlemma mono_if_cont: fixes f :: \"'a set \\<Rightarrow> 'b set\"\n  assumes \"cont f\" shows \"mono f\"\nproof\n  fix a b :: \"'a set\" assume \"a \\<subseteq> b\"\n  let ?S = \"\\<lambda>n::nat. if n=0 then a else b\"\n  have \"chain ?S\" using \\<open>a \\<subseteq> b\\<close> by(auto simp: chain_def)\n  hence \"f(UN n. ?S n) = (UN n. f(?S n))\"\n    using assms by (simp add: cont_def del: if_image_distrib)\n  moreover have \"(UN n. ?S n) = b\" using \\<open>a \\<subseteq> b\\<close> by (auto split: if_splits)\n  moreover have \"(UN n. f(?S n)) = f a \\<union> f b\" by (auto split: if_splits)\n  ultimately show \"f a \\<subseteq> f b\" by (metis Un_upper1)\nqed\n\nlemma chain_iterates: fixes f :: \"'a set \\<Rightarrow> 'a set\"\n  assumes \"mono f\" shows \"chain(\\<lambda>n. (f^^n) {})\"\nproof-\n  have \"(f ^^ n) {} \\<subseteq> (f ^^ Suc n) {}\" for n\n  proof (induction n)\n    case 0 show ?case by simp\n  next\n    case (Suc n) thus ?case using assms by (auto simp: mono_def)\n  qed\n  thus ?thesis by(auto simp: chain_def assms)\nqed\n\ntheorem lfp_if_cont:\n  assumes \"cont f\" shows \"lfp f = (UN n. (f^^n) {})\" (is \"_ = ?U\")\nproof\n  from assms mono_if_cont\n  have mono: \"(f ^^ n) {} \\<subseteq> (f ^^ Suc n) {}\" for n\n    using funpow_decreasing [of n \"Suc n\"] by auto\n  show \"lfp f \\<subseteq> ?U\"\n  proof (rule lfp_lowerbound)\n    have \"f ?U = (UN n. (f^^Suc n){})\"\n      using chain_iterates[OF mono_if_cont[OF assms]] assms\n      by(simp add: cont_def)\n    also have \"\\<dots> = (f^^0){} \\<union> \\<dots>\" by simp\n    also have \"\\<dots> = ?U\"\n      using mono by auto (metis funpow_simps_right(2) funpow_swap1 o_apply)\n    finally show \"f ?U \\<subseteq> ?U\" by simp\n  qed\nnext\n  have \"(f^^n){} \\<subseteq> p\" if \"f p \\<subseteq> p\" for n p\n  proof -\n    show ?thesis\n    proof(induction n)\n      case 0 show ?case by simp\n    next\n      case Suc\n      from monoD[OF mono_if_cont[OF assms] Suc] \\<open>f p \\<subseteq> p\\<close>\n      show ?case by simp\n    qed\n  qed\n  thus \"?U \\<subseteq> lfp f\" by(auto simp: lfp_def)\nqed\n\nlemma cont_W: \"cont(W b r)\"\nby(auto simp: cont_def W_def)\n\n\nsubsection\\<open>The denotational semantics is deterministic\\<close>\n\nlemma single_valued_UN_chain:\n  assumes \"chain S\" \"(\\<And>n. single_valued (S n))\"\n  shows \"single_valued(UN n. S n)\"\nproof(auto simp: single_valued_def)\n  fix m n x y z assume \"(x, y) \\<in> S m\" \"(x, z) \\<in> S n\"\n  with chain_total[OF assms(1), of m n] assms(2)\n  show \"y = z\" by (auto simp: single_valued_def)\nqed\n\nlemma single_valued_lfp: fixes f :: \"com_den \\<Rightarrow> com_den\"\nassumes \"cont f\" \"\\<And>r. single_valued r \\<Longrightarrow> single_valued (f r)\"\nshows \"single_valued(lfp f)\"\nunfolding lfp_if_cont[OF assms(1)]\nproof(rule single_valued_UN_chain[OF chain_iterates[OF mono_if_cont[OF assms(1)]]])\n  fix n show \"single_valued ((f ^^ n) {})\"\n  by(induction n)(auto simp: assms(2))\nqed\n\nlemma single_valued_D: \"single_valued (D c)\"\nproof(induction c)\n  case Seq thus ?case by(simp add: single_valued_relcomp)\nnext\n  case (While b c)\n  let ?f = \"W (bval b) (D c)\"\n  have \"single_valued (lfp ?f)\"\n  proof(rule single_valued_lfp[OF cont_W])\n    show \"\\<And>r. single_valued r \\<Longrightarrow> single_valued (?f r)\"\n      using While.IH by(force simp: single_valued_def W_def)\n  qed\n  thus ?case by simp\nqed (auto simp add: single_valued_def)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/IMP/Denotational.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.8558511396138366, "lm_q1q2_score": 0.7619593330005894}}
{"text": "(*  Title:      HOL/Inductive.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Knaster-Tarski Fixpoint Theorem and inductive definitions\\<close>\n\ntheory Inductive\n  imports Complete_Lattices Ctr_Sugar\n  keywords\n    \"inductive\" \"coinductive\" \"inductive_cases\" \"inductive_simps\" :: thy_defn and\n    \"monos\" and\n    \"print_inductives\" :: diag and\n    \"old_rep_datatype\" :: thy_goal and\n    \"primrec\" :: thy_defn\nbegin\n\nsubsection \\<open>Least fixed points\\<close>\n\ncontext complete_lattice\nbegin\n\ndefinition lfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"lfp f = Inf {u. f u \\<le> u}\"\n\nlemma lfp_lowerbound: \"f A \\<le> A \\<Longrightarrow> lfp f \\<le> A\"\n  unfolding lfp_def by (rule Inf_lower) simp\n\nlemma lfp_greatest: \"(\\<And>u. f u \\<le> u \\<Longrightarrow> A \\<le> u) \\<Longrightarrow> A \\<le> lfp f\"\n  unfolding lfp_def by (rule Inf_greatest) simp\n\nend\n\nlemma lfp_fixpoint:\n  assumes \"mono f\"\n  shows \"f (lfp f) = lfp f\"\n  unfolding lfp_def\nproof (rule order_antisym)\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a \\<le> ?a\"\n  proof (rule Inf_greatest)\n    fix x\n    assume \"x \\<in> ?H\"\n    then have \"?a \\<le> x\" by (rule Inf_lower)\n    with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n    also from \\<open>x \\<in> ?H\\<close> have \"f x \\<le> x\" ..\n    finally show \"f ?a \\<le> x\" .\n  qed\n  show \"?a \\<le> f ?a\"\n  proof (rule Inf_lower)\n    from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n    then show \"f ?a \\<in> ?H\" ..\n  qed\nqed\n\n\n\nlemma lfp_const: \"lfp (\\<lambda>x. t) = t\"\n  by (rule lfp_unfold) (simp add: mono_def)\n\nlemma lfp_eqI: \"mono F \\<Longrightarrow> F x = x \\<Longrightarrow> (\\<And>z. F z = z \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> lfp F = x\"\n  by (rule antisym) (simp_all add: lfp_lowerbound lfp_unfold[symmetric])\n\n\nsubsection \\<open>General induction rules for least fixed points\\<close>\n\nlemma lfp_ordinal_induct [case_names mono step union]:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes mono: \"mono f\"\n    and P_f: \"\\<And>S. P S \\<Longrightarrow> S \\<le> lfp f \\<Longrightarrow> P (f S)\"\n    and P_Union: \"\\<And>M. \\<forall>S\\<in>M. P S \\<Longrightarrow> P (Sup M)\"\n  shows \"P (lfp f)\"\nproof -\n  let ?M = \"{S. S \\<le> lfp f \\<and> P S}\"\n  from P_Union have \"P (Sup ?M)\" by simp\n  also have \"Sup ?M = lfp f\"\n  proof (rule antisym)\n    show \"Sup ?M \\<le> lfp f\"\n      by (blast intro: Sup_least)\n    then have \"f (Sup ?M) \\<le> f (lfp f)\"\n      by (rule mono [THEN monoD])\n    then have \"f (Sup ?M) \\<le> lfp f\"\n      using mono [THEN lfp_unfold] by simp\n    then have \"f (Sup ?M) \\<in> ?M\"\n      using P_Union by simp (intro P_f Sup_least, auto)\n    then have \"f (Sup ?M) \\<le> Sup ?M\"\n      by (rule Sup_upper)\n    then show \"lfp f \\<le> Sup ?M\"\n      by (rule lfp_lowerbound)\n  qed\n  finally show ?thesis .\nqed\n\ntheorem lfp_induct:\n  assumes mono: \"mono f\"\n    and ind: \"f (inf (lfp f) P) \\<le> P\"\n  shows \"lfp f \\<le> P\"\nproof (induct rule: lfp_ordinal_induct)\n  case mono\n  show ?case by fact\nnext\n  case (step S)\n  then show ?case\n    by (intro order_trans[OF _ ind] monoD[OF mono]) auto\nnext\n  case (union M)\n  then show ?case\n    by (auto intro: Sup_least)\nqed\n\nlemma lfp_induct_set:\n  assumes lfp: \"a \\<in> lfp f\"\n    and mono: \"mono f\"\n    and hyp: \"\\<And>x. x \\<in> f (lfp f \\<inter> {x. P x}) \\<Longrightarrow> P x\"\n  shows \"P a\"\n  by (rule lfp_induct [THEN subsetD, THEN CollectD, OF mono _ lfp]) (auto intro: hyp)\n\nlemma lfp_ordinal_induct_set:\n  assumes mono: \"mono f\"\n    and P_f: \"\\<And>S. P S \\<Longrightarrow> P (f S)\"\n    and P_Union: \"\\<And>M. \\<forall>S\\<in>M. P S \\<Longrightarrow> P (\\<Union>M)\"\n  shows \"P (lfp f)\"\n  using assms by (rule lfp_ordinal_induct)\n\n\ntext \\<open>Definition forms of \\<open>lfp_unfold\\<close> and \\<open>lfp_induct\\<close>, to control unfolding.\\<close>\n\nlemma def_lfp_unfold: \"h \\<equiv> lfp f \\<Longrightarrow> mono f \\<Longrightarrow> h = f h\"\n  by (auto intro!: lfp_unfold)\n\nlemma def_lfp_induct: \"A \\<equiv> lfp f \\<Longrightarrow> mono f \\<Longrightarrow> f (inf A P) \\<le> P \\<Longrightarrow> A \\<le> P\"\n  by (blast intro: lfp_induct)\n\nlemma def_lfp_induct_set:\n  \"A \\<equiv> lfp f \\<Longrightarrow> mono f \\<Longrightarrow> a \\<in> A \\<Longrightarrow> (\\<And>x. x \\<in> f (A \\<inter> {x. P x}) \\<Longrightarrow> P x) \\<Longrightarrow> P a\"\n  by (blast intro: lfp_induct_set)\n\ntext \\<open>Monotonicity of \\<open>lfp\\<close>!\\<close>\nlemma lfp_mono: \"(\\<And>Z. f Z \\<le> g Z) \\<Longrightarrow> lfp f \\<le> lfp g\"\n  by (rule lfp_lowerbound [THEN lfp_greatest]) (blast intro: order_trans)\n\n\nsubsection \\<open>Greatest fixed points\\<close>\n\ncontext complete_lattice\nbegin\n\ndefinition gfp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"gfp f = Sup {u. u \\<le> f u}\"\n\nlemma gfp_upperbound: \"X \\<le> f X \\<Longrightarrow> X \\<le> gfp f\"\n  by (auto simp add: gfp_def intro: Sup_upper)\n\nlemma gfp_least: \"(\\<And>u. u \\<le> f u \\<Longrightarrow> u \\<le> X) \\<Longrightarrow> gfp f \\<le> X\"\n  by (auto simp add: gfp_def intro: Sup_least)\n\nend\n\nlemma lfp_le_gfp: \"mono f \\<Longrightarrow> lfp f \\<le> gfp f\"\n  by (rule gfp_upperbound) (simp add: lfp_fixpoint)\n\nlemma gfp_fixpoint:\n  assumes \"mono f\"\n  shows \"f (gfp f) = gfp f\"\n  unfolding gfp_def\nproof (rule order_antisym)\n  let ?H = \"{u. u \\<le> f u}\"\n  let ?a = \"\\<Squnion>?H\"\n  show \"?a \\<le> f ?a\"\n  proof (rule Sup_least)\n    fix x\n    assume \"x \\<in> ?H\"\n    then have \"x \\<le> f x\" ..\n    also from \\<open>x \\<in> ?H\\<close> have \"x \\<le> ?a\" by (rule Sup_upper)\n    with \\<open>mono f\\<close> have \"f x \\<le> f ?a\" ..\n    finally show \"x \\<le> f ?a\" .\n  qed\n  show \"f ?a \\<le> ?a\"\n  proof (rule Sup_upper)\n    from \\<open>mono f\\<close> and \\<open>?a \\<le> f ?a\\<close> have \"f ?a \\<le> f (f ?a)\" ..\n    then show \"f ?a \\<in> ?H\" ..\n  qed\nqed\n\nlemma gfp_unfold: \"mono f \\<Longrightarrow> gfp f = f (gfp f)\"\n  by (rule gfp_fixpoint [symmetric])\n\nlemma gfp_const: \"gfp (\\<lambda>x. t) = t\"\n  by (rule gfp_unfold) (simp add: mono_def)\n\nlemma gfp_eqI: \"mono F \\<Longrightarrow> F x = x \\<Longrightarrow> (\\<And>z. F z = z \\<Longrightarrow> z \\<le> x) \\<Longrightarrow> gfp F = x\"\n  by (rule antisym) (simp_all add: gfp_upperbound gfp_unfold[symmetric])\n\n\nsubsection \\<open>Coinduction rules for greatest fixed points\\<close>\n\ntext \\<open>Weak version.\\<close>\nlemma weak_coinduct: \"a \\<in> X \\<Longrightarrow> X \\<subseteq> f X \\<Longrightarrow> a \\<in> gfp f\"\n  by (rule gfp_upperbound [THEN subsetD]) auto\n\nlemma weak_coinduct_image: \"a \\<in> X \\<Longrightarrow> g`X \\<subseteq> f (g`X) \\<Longrightarrow> g a \\<in> gfp f\"\n  apply (erule gfp_upperbound [THEN subsetD])\n  apply (erule imageI)\n  done\n\nlemma coinduct_lemma: \"X \\<le> f (sup X (gfp f)) \\<Longrightarrow> mono f \\<Longrightarrow> sup X (gfp f) \\<le> f (sup X (gfp f))\"\n  apply (frule gfp_unfold [THEN eq_refl])\n  apply (drule mono_sup)\n  apply (rule le_supI)\n   apply assumption\n  apply (rule order_trans)\n   apply (rule order_trans)\n    apply assumption\n   apply (rule sup_ge2)\n  apply assumption\n  done\n\ntext \\<open>Strong version, thanks to Coen and Frost.\\<close>\nlemma coinduct_set: \"mono f \\<Longrightarrow> a \\<in> X \\<Longrightarrow> X \\<subseteq> f (X \\<union> gfp f) \\<Longrightarrow> a \\<in> gfp f\"\n  by (rule weak_coinduct[rotated], rule coinduct_lemma) blast+\n\nlemma gfp_fun_UnI2: \"mono f \\<Longrightarrow> a \\<in> gfp f \\<Longrightarrow> a \\<in> f (X \\<union> gfp f)\"\n  by (blast dest: gfp_fixpoint mono_Un)\n\nlemma gfp_ordinal_induct[case_names mono step union]:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes mono: \"mono f\"\n    and P_f: \"\\<And>S. P S \\<Longrightarrow> gfp f \\<le> S \\<Longrightarrow> P (f S)\"\n    and P_Union: \"\\<And>M. \\<forall>S\\<in>M. P S \\<Longrightarrow> P (Inf M)\"\n  shows \"P (gfp f)\"\nproof -\n  let ?M = \"{S. gfp f \\<le> S \\<and> P S}\"\n  from P_Union have \"P (Inf ?M)\" by simp\n  also have \"Inf ?M = gfp f\"\n  proof (rule antisym)\n    show \"gfp f \\<le> Inf ?M\"\n      by (blast intro: Inf_greatest)\n    then have \"f (gfp f) \\<le> f (Inf ?M)\"\n      by (rule mono [THEN monoD])\n    then have \"gfp f \\<le> f (Inf ?M)\"\n      using mono [THEN gfp_unfold] by simp\n    then have \"f (Inf ?M) \\<in> ?M\"\n      using P_Union by simp (intro P_f Inf_greatest, auto)\n    then have \"Inf ?M \\<le> f (Inf ?M)\"\n      by (rule Inf_lower)\n    then show \"Inf ?M \\<le> gfp f\"\n      by (rule gfp_upperbound)\n  qed\n  finally show ?thesis .\nqed\n\nlemma coinduct:\n  assumes mono: \"mono f\"\n    and ind: \"X \\<le> f (sup X (gfp f))\"\n  shows \"X \\<le> gfp f\"\nproof (induct rule: gfp_ordinal_induct)\n  case mono\n  then show ?case by fact\nnext\n  case (step S)\n  then show ?case\n    by (intro order_trans[OF ind _] monoD[OF mono]) auto\nnext\n  case (union M)\n  then show ?case\n    by (auto intro: mono Inf_greatest)\nqed\n\n\nsubsection \\<open>Even Stronger Coinduction Rule, by Martin Coen\\<close>\n\ntext \\<open>Weakens the condition \\<^term>\\<open>X \\<subseteq> f X\\<close> to one expressed using both\n  \\<^term>\\<open>lfp\\<close> and \\<^term>\\<open>gfp\\<close>\\<close>\nlemma coinduct3_mono_lemma: \"mono f \\<Longrightarrow> mono (\\<lambda>x. f x \\<union> X \\<union> B)\"\n  by (iprover intro: subset_refl monoI Un_mono monoD)\n\nlemma coinduct3_lemma:\n  \"X \\<subseteq> f (lfp (\\<lambda>x. f x \\<union> X \\<union> gfp f)) \\<Longrightarrow> mono f \\<Longrightarrow>\n    lfp (\\<lambda>x. f x \\<union> X \\<union> gfp f) \\<subseteq> f (lfp (\\<lambda>x. f x \\<union> X \\<union> gfp f))\"\n  apply (rule subset_trans)\n   apply (erule coinduct3_mono_lemma [THEN lfp_unfold [THEN eq_refl]])\n  apply (rule Un_least [THEN Un_least])\n    apply (rule subset_refl, assumption)\n  apply (rule gfp_unfold [THEN equalityD1, THEN subset_trans], assumption)\n  apply (rule monoD, assumption)\n  apply (subst coinduct3_mono_lemma [THEN lfp_unfold], auto)\n  done\n\nlemma coinduct3: \"mono f \\<Longrightarrow> a \\<in> X \\<Longrightarrow> X \\<subseteq> f (lfp (\\<lambda>x. f x \\<union> X \\<union> gfp f)) \\<Longrightarrow> a \\<in> gfp f\"\n  apply (rule coinduct3_lemma [THEN [2] weak_coinduct])\n    apply (rule coinduct3_mono_lemma [THEN lfp_unfold, THEN ssubst])\n     apply simp_all\n  done\n\ntext  \\<open>Definition forms of \\<open>gfp_unfold\\<close> and \\<open>coinduct\\<close>, to control unfolding.\\<close>\n\nlemma def_gfp_unfold: \"A \\<equiv> gfp f \\<Longrightarrow> mono f \\<Longrightarrow> A = f A\"\n  by (auto intro!: gfp_unfold)\n\nlemma def_coinduct: \"A \\<equiv> gfp f \\<Longrightarrow> mono f \\<Longrightarrow> X \\<le> f (sup X A) \\<Longrightarrow> X \\<le> A\"\n  by (iprover intro!: coinduct)\n\nlemma def_coinduct_set: \"A \\<equiv> gfp f \\<Longrightarrow> mono f \\<Longrightarrow> a \\<in> X \\<Longrightarrow> X \\<subseteq> f (X \\<union> A) \\<Longrightarrow> a \\<in> A\"\n  by (auto intro!: coinduct_set)\n\nlemma def_Collect_coinduct:\n  \"A \\<equiv> gfp (\\<lambda>w. Collect (P w)) \\<Longrightarrow> mono (\\<lambda>w. Collect (P w)) \\<Longrightarrow> a \\<in> X \\<Longrightarrow>\n    (\\<And>z. z \\<in> X \\<Longrightarrow> P (X \\<union> A) z) \\<Longrightarrow> a \\<in> A\"\n  by (erule def_coinduct_set) auto\n\nlemma def_coinduct3: \"A \\<equiv> gfp f \\<Longrightarrow> mono f \\<Longrightarrow> a \\<in> X \\<Longrightarrow> X \\<subseteq> f (lfp (\\<lambda>x. f x \\<union> X \\<union> A)) \\<Longrightarrow> a \\<in> A\"\n  by (auto intro!: coinduct3)\n\ntext \\<open>Monotonicity of \\<^term>\\<open>gfp\\<close>!\\<close>\nlemma gfp_mono: \"(\\<And>Z. f Z \\<le> g Z) \\<Longrightarrow> gfp f \\<le> gfp g\"\n  by (rule gfp_upperbound [THEN gfp_least]) (blast intro: order_trans)\n\n\nsubsection \\<open>Rules for fixed point calculus\\<close>\n\nlemma lfp_rolling:\n  assumes \"mono g\" \"mono f\"\n  shows \"g (lfp (\\<lambda>x. f (g x))) = lfp (\\<lambda>x. g (f x))\"\nproof (rule antisym)\n  have *: \"mono (\\<lambda>x. f (g x))\"\n    using assms by (auto simp: mono_def)\n  show \"lfp (\\<lambda>x. g (f x)) \\<le> g (lfp (\\<lambda>x. f (g x)))\"\n    by (rule lfp_lowerbound) (simp add: lfp_unfold[OF *, symmetric])\n  show \"g (lfp (\\<lambda>x. f (g x))) \\<le> lfp (\\<lambda>x. g (f x))\"\n  proof (rule lfp_greatest)\n    fix u\n    assume u: \"g (f u) \\<le> u\"\n    then have \"g (lfp (\\<lambda>x. f (g x))) \\<le> g (f u)\"\n      by (intro assms[THEN monoD] lfp_lowerbound)\n    with u show \"g (lfp (\\<lambda>x. f (g x))) \\<le> u\"\n      by auto\n  qed\nqed\n\nlemma lfp_lfp:\n  assumes f: \"\\<And>x y w z. x \\<le> y \\<Longrightarrow> w \\<le> z \\<Longrightarrow> f x w \\<le> f y z\"\n  shows \"lfp (\\<lambda>x. lfp (f x)) = lfp (\\<lambda>x. f x x)\"\nproof (rule antisym)\n  have *: \"mono (\\<lambda>x. f x x)\"\n    by (blast intro: monoI f)\n  show \"lfp (\\<lambda>x. lfp (f x)) \\<le> lfp (\\<lambda>x. f x x)\"\n    by (intro lfp_lowerbound) (simp add: lfp_unfold[OF *, symmetric])\n  show \"lfp (\\<lambda>x. lfp (f x)) \\<ge> lfp (\\<lambda>x. f x x)\" (is \"?F \\<ge> _\")\n  proof (intro lfp_lowerbound)\n    have *: \"?F = lfp (f ?F)\"\n      by (rule lfp_unfold) (blast intro: monoI lfp_mono f)\n    also have \"\\<dots> = f ?F (lfp (f ?F))\"\n      by (rule lfp_unfold) (blast intro: monoI lfp_mono f)\n    finally show \"f ?F ?F \\<le> ?F\"\n      by (simp add: *[symmetric])\n  qed\nqed\n\nlemma gfp_rolling:\n  assumes \"mono g\" \"mono f\"\n  shows \"g (gfp (\\<lambda>x. f (g x))) = gfp (\\<lambda>x. g (f x))\"\nproof (rule antisym)\n  have *: \"mono (\\<lambda>x. f (g x))\"\n    using assms by (auto simp: mono_def)\n  show \"g (gfp (\\<lambda>x. f (g x))) \\<le> gfp (\\<lambda>x. g (f x))\"\n    by (rule gfp_upperbound) (simp add: gfp_unfold[OF *, symmetric])\n  show \"gfp (\\<lambda>x. g (f x)) \\<le> g (gfp (\\<lambda>x. f (g x)))\"\n  proof (rule gfp_least)\n    fix u\n    assume u: \"u \\<le> g (f u)\"\n    then have \"g (f u) \\<le> g (gfp (\\<lambda>x. f (g x)))\"\n      by (intro assms[THEN monoD] gfp_upperbound)\n    with u show \"u \\<le> g (gfp (\\<lambda>x. f (g x)))\"\n      by auto\n  qed\nqed\n\nlemma gfp_gfp:\n  assumes f: \"\\<And>x y w z. x \\<le> y \\<Longrightarrow> w \\<le> z \\<Longrightarrow> f x w \\<le> f y z\"\n  shows \"gfp (\\<lambda>x. gfp (f x)) = gfp (\\<lambda>x. f x x)\"\nproof (rule antisym)\n  have *: \"mono (\\<lambda>x. f x x)\"\n    by (blast intro: monoI f)\n  show \"gfp (\\<lambda>x. f x x) \\<le> gfp (\\<lambda>x. gfp (f x))\"\n    by (intro gfp_upperbound) (simp add: gfp_unfold[OF *, symmetric])\n  show \"gfp (\\<lambda>x. gfp (f x)) \\<le> gfp (\\<lambda>x. f x x)\" (is \"?F \\<le> _\")\n  proof (intro gfp_upperbound)\n    have *: \"?F = gfp (f ?F)\"\n      by (rule gfp_unfold) (blast intro: monoI gfp_mono f)\n    also have \"\\<dots> = f ?F (gfp (f ?F))\"\n      by (rule gfp_unfold) (blast intro: monoI gfp_mono f)\n    finally show \"?F \\<le> f ?F ?F\"\n      by (simp add: *[symmetric])\n  qed\nqed\n\n\nsubsection \\<open>Inductive predicates and sets\\<close>\n\ntext \\<open>Package setup.\\<close>\n\nlemmas basic_monos =\n  subset_refl imp_refl disj_mono conj_mono ex_mono all_mono if_bool_eq_conj\n  Collect_mono in_mono vimage_mono\n\nlemma le_rel_bool_arg_iff: \"X \\<le> Y \\<longleftrightarrow> X False \\<le> Y False \\<and> X True \\<le> Y True\"\n  unfolding le_fun_def le_bool_def using bool_induct by auto\n\nlemma imp_conj_iff: \"((P \\<longrightarrow> Q) \\<and> P) = (P \\<and> Q)\"\n  by blast\n\nlemma meta_fun_cong: \"P \\<equiv> Q \\<Longrightarrow> P a \\<equiv> Q a\"\n  by auto\n\nML_file \\<open>Tools/inductive.ML\\<close>\n\nlemmas [mono] =\n  imp_refl disj_mono conj_mono ex_mono all_mono if_bool_eq_conj\n  imp_mono not_mono\n  Ball_def Bex_def\n  induct_rulify_fallback\n\n\nsubsection \\<open>The Schroeder-Bernstein Theorem\\<close>\n\ntext \\<open>\n  See also:\n  \\<^item> \\<^file>\\<open>$ISABELLE_HOME/src/HOL/ex/Set_Theory.thy\\<close>\n  \\<^item> \\<^url>\\<open>http://planetmath.org/proofofschroederbernsteintheoremusingtarskiknastertheorem\\<close>\n  \\<^item> Springer LNCS 828 (cover page)\n\\<close>\n\ntheorem Schroeder_Bernstein:\n  fixes f :: \"'a \\<Rightarrow> 'b\" and g :: \"'b \\<Rightarrow> 'a\"\n    and A :: \"'a set\" and B :: \"'b set\"\n  assumes inj1: \"inj_on f A\" and sub1: \"f ` A \\<subseteq> B\"\n    and inj2: \"inj_on g B\" and sub2: \"g ` B \\<subseteq> A\"\n  shows \"\\<exists>h. bij_betw h A B\"\nproof (rule exI, rule bij_betw_imageI)\n  define X where \"X = lfp (\\<lambda>X. A - (g ` (B - (f ` X))))\"\n  define g' where \"g' = the_inv_into (B - (f ` X)) g\"\n  let ?h = \"\\<lambda>z. if z \\<in> X then f z else g' z\"\n\n  have X: \"X = A - (g ` (B - (f ` X)))\"\n    unfolding X_def by (rule lfp_unfold) (blast intro: monoI)\n  then have X_compl: \"A - X = g ` (B - (f ` X))\"\n    using sub2 by blast\n\n  from inj2 have inj2': \"inj_on g (B - (f ` X))\"\n    by (rule inj_on_subset) auto\n  with X_compl have *: \"g' ` (A - X) = B - (f ` X)\"\n    by (simp add: g'_def)\n\n  from X have X_sub: \"X \\<subseteq> A\" by auto\n  from X sub1 have fX_sub: \"f ` X \\<subseteq> B\" by auto\n\n  show \"?h ` A = B\"\n  proof -\n    from X_sub have \"?h ` A = ?h ` (X \\<union> (A - X))\" by auto\n    also have \"\\<dots> = ?h ` X \\<union> ?h ` (A - X)\" by (simp only: image_Un)\n    also have \"?h ` X = f ` X\" by auto\n    also from * have \"?h ` (A - X) = B - (f ` X)\" by auto\n    also from fX_sub have \"f ` X \\<union> (B - f ` X) = B\" by blast\n    finally show ?thesis .\n  qed\n  show \"inj_on ?h A\"\n  proof -\n    from inj1 X_sub have on_X: \"inj_on f X\"\n      by (rule subset_inj_on)\n\n    have on_X_compl: \"inj_on g' (A - X)\"\n      unfolding g'_def X_compl\n      by (rule inj_on_the_inv_into) (rule inj2')\n\n    have impossible: False if eq: \"f a = g' b\" and a: \"a \\<in> X\" and b: \"b \\<in> A - X\" for a b\n    proof -\n      from a have fa: \"f a \\<in> f ` X\" by (rule imageI)\n      from b have \"g' b \\<in> g' ` (A - X)\" by (rule imageI)\n      with * have \"g' b \\<in> - (f ` X)\" by simp\n      with eq fa show False by simp\n    qed\n\n    show ?thesis\n    proof (rule inj_onI)\n      fix a b\n      assume h: \"?h a = ?h b\"\n      assume \"a \\<in> A\" and \"b \\<in> A\"\n      then consider \"a \\<in> X\" \"b \\<in> X\" | \"a \\<in> A - X\" \"b \\<in> A - X\"\n        | \"a \\<in> X\" \"b \\<in> A - X\" | \"a \\<in> A - X\" \"b \\<in> X\"\n        by blast\n      then show \"a = b\"\n      proof cases\n        case 1\n        with h on_X show ?thesis by (simp add: inj_on_eq_iff)\n      next\n        case 2\n        with h on_X_compl show ?thesis by (simp add: inj_on_eq_iff)\n      next\n        case 3\n        with h impossible [of a b] have False by simp\n        then show ?thesis ..\n      next\n        case 4\n        with h impossible [of b a] have False by simp\n        then show ?thesis ..\n      qed\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Inductive datatypes and primitive recursion\\<close>\n\ntext \\<open>Package setup.\\<close>\n\nML_file \\<open>Tools/Old_Datatype/old_datatype_aux.ML\\<close>\nML_file \\<open>Tools/Old_Datatype/old_datatype_prop.ML\\<close>\nML_file \\<open>Tools/Old_Datatype/old_datatype_data.ML\\<close>\nML_file \\<open>Tools/Old_Datatype/old_rep_datatype.ML\\<close>\nML_file \\<open>Tools/Old_Datatype/old_datatype_codegen.ML\\<close>\nML_file \\<open>Tools/BNF/bnf_fp_rec_sugar_util.ML\\<close>\nML_file \\<open>Tools/Old_Datatype/old_primrec.ML\\<close>\nML_file \\<open>Tools/BNF/bnf_lfp_rec_sugar.ML\\<close>\n\ntext \\<open>Lambda-abstractions with pattern matching:\\<close>\nsyntax (ASCII)\n  \"_lam_pats_syntax\" :: \"cases_syn \\<Rightarrow> 'a \\<Rightarrow> 'b\"  (\"(%_)\" 10)\nsyntax\n  \"_lam_pats_syntax\" :: \"cases_syn \\<Rightarrow> 'a \\<Rightarrow> 'b\"  (\"(\\<lambda>_)\" 10)\nparse_translation \\<open>\n  let\n    fun fun_tr ctxt [cs] =\n      let\n        val x = Syntax.free (fst (Name.variant \"x\" (Term.declare_term_frees cs Name.context)));\n        val ft = Case_Translation.case_tr true ctxt [x, cs];\n      in lambda x ft end\n  in [(\\<^syntax_const>\\<open>_lam_pats_syntax\\<close>, fun_tr)] end\n\\<close>\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Inductive.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942290328344, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7619593305093733}}
{"text": "theory Tut4Practice\nimports Main\nbegin\n\nlemma \"(P \\<longrightarrow> (Q \\<longrightarrow> R)) \\<longrightarrow> ((P \\<longrightarrow> Q) \\<longrightarrow> (P \\<longrightarrow> R))\"\nproof (rule impI)+\n  assume \"P\" \"P \\<longrightarrow> Q \\<longrightarrow> R\" then have qr: \"Q \\<longrightarrow> R\"\n    by blast\n  assume \"P\" \"P \\<longrightarrow> Q\" then have \"Q\"\n    by blast\n  then show \"R\" using qr\n    by simp\nqed\n\nlemma \"(\\<forall>x. P x \\<longrightarrow> Q) \\<longrightarrow> (\\<exists>x. P x \\<longrightarrow> Q)\"\nproof \n  fix a\n  assume \"(\\<forall>x. P x \\<longrightarrow> Q)\" then have pq: \"P a \\<longrightarrow> Q\"\n    by blast\n  then show \"(\\<exists>x. P x \\<longrightarrow> Q)\"\n    by blast\nqed\n\nlemma one: assumes ex:\"(\\<nexists>x. P x)\" shows  all:\"(\\<forall>x. \\<not>P x)\"\nproof\n  fix x\n  show \"\\<not> P x\"\n  proof\n    assume \"P x\" then have \"\\<exists>x. P x\"\n      by auto\n    then show False\n      using ex by blast\n  qed\nqed\n\nlemma assumes n_all: \"\\<not>(\\<forall>x. P x)\" shows \"\\<exists>x. \\<not>P x\"\nproof (rule ccontr)\n  assume \"\\<nexists>x. \\<not>P x\"\n  then have \"\\<forall>x. \\<not>\\<not>P x\" by (rule one)\n  then have \"\\<forall>x. P x\" by simp\n  from n_all this show False\n    by simp\nqed\n\n\n\n\nlemma \"(R \\<longrightarrow> P) \\<longrightarrow> (((\\<not>R \\<or> P) \\<longrightarrow> (Q \\<longrightarrow> S)) \\<longrightarrow> (Q \\<longrightarrow> S))\"\n  oops\n\nend", "meta": {"author": "celinadongye", "repo": "Isabelle-exercises", "sha": "f94a03f43d23a8055d9c195acf1390107fed3395", "save_path": "github-repos/isabelle/celinadongye-Isabelle-exercises", "path": "github-repos/isabelle/celinadongye-Isabelle-exercises/Isabelle-exercises-f94a03f43d23a8055d9c195acf1390107fed3395/Tut4Practice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122113355091, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7619008776836396}}
{"text": "theory Homework4_1_sol\nimports \"../IMP/AExp\"\nbegin\n\n(*\n  The objective of this homework is to compile to a register machine.\n\n  Hint: To solve this homework, it is best to have ASM.thy \n    open for reference in another window!\n\n*)  \n  \n(* We assume we have an unlimited amount of registers, register names are \n  just natural numbers *)\ntype_synonym reg = nat\n  \n(* Instructions of our register machine *)  \ndatatype inst = \n    MOVI val reg      (* MOVI v r  -- move constant (immediate value) v to register r *)\n  | LOAD vname reg    (* LOAD x r  -- load variable x to register r *)\n  | ADD reg reg       (* ADD r1 r2 -- add values contained in registers r1 and r2, place the result in r1 *)\n\n(* The state of our machine's register bank is described by a function mapping\n  register names to values.\n*)    \ntype_synonym rstate = \"reg \\<Rightarrow> val\"\n\n(*\n  Specify the semantics for executing a single instruction. \n  Note: As there is no store instruction, the variable state is not modified.\n*)  \nfun exec1 :: \"inst \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n(*<*)  \n  \"exec1 (MOVI v r) s t = t(r:=v)\"\n| \"exec1 (LOAD x r) s t = t(r:=s x)\"\n| \"exec1 (ADD r1 r2) s t = t(r1:=t r1 + t r2)\"\n(*>*)  \n\n(*\n  Specify the semantics of executing a list of instructions\n*)  \nfun exec :: \"inst list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n(*<*)  \n  \"exec [] s t = t\"\n| \"exec (i#is) s t = exec is s (exec1 i s t)\"  \n(*>*)  \n  \nlemma exec_append[simp]:\n  \"exec (is1@is2) s t = exec is2 s (exec is1 s t)\"\n  (* Prove that! *)\n(*<*)  \napply(induction is1 arbitrary: t)\napply (auto)\ndone\n(*>*)\n\n(*\n  In order to compile an arithmetic expression, the intermediate results must be assigned \n  to intermediate registers, and it must be ensured that fresh intermediate registers are used.\n\n  For example, when compiling a1+a2, we first generate code that compiles a1 \n  and places the result in some register r1, then we generate code to compile a2,\n  place the result in some register r2, and finally add the two registers, the \n  final result going to register r1. \n  However, we must ensure that the code generated for a2 does not overwrite register r1.\n  \n  We use the following strategy: We pass an additional parameter r to the compiler,\n  which is the register that should contain the result value. Additionally, all \n  registers less than r must not be changed by the generated code.\n\n  That is, to compile an expression a1 + a2 to register r, we do the following:\n    1. generate code that evaluates a1 to register r, not changing registers <r\n    2. generate code that evaluates a2 to register r+1, not changing registers <r+1 \n        (in particular, register r is not changed!)\n    3. add register r and r+1, placing the result in register r\n\n\n*)  \n  \nhide_const (open) comp  \nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> inst list\" where\n(*<*)  \n  \"comp (N v) r = [MOVI v r]\"\n| \"comp (V x) r = [LOAD x r]\"  \n| \"comp (Plus e1 e2) r = comp e1 r @ comp e2 (r+1) @ [ADD r (r+1)]\"\n(*>*)  \n  \n(* Test case *)\n  \nvalue \"comp (Plus (Plus (N 3) (V ''x'')) (Plus (N 1) (V ''y''))) 1 = \n[MOVI 3 (Suc 0), LOAD ''x'' (Suc (Suc 0)), ADD (Suc 0) (Suc (Suc 0)), MOVI 1 (Suc (Suc 0)),\n  LOAD ''y'' (Suc (Suc (Suc 0))), ADD (Suc (Suc 0)) (Suc (Suc (Suc 0))), ADD (Suc 0) (Suc (Suc 0))]\n\"\n  \n  \n(* Show that the produced code does not change registers less than r! *)  \n\n\n\n\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Homeworks/Homework4_1_sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8633916117313211, "lm_q1q2_score": 0.7618808151852027}}
{"text": "(*  Title:      ListSlice.thy\n    Date:       Oct 2006\n    Author:     David Trachtenherz\n*)\n\nsection \\<open>Additional definitions and results for lists\\<close>\n\ntheory ListSlice\nimports \"List-Infinite.ListInf\"\nbegin\n\nsubsection \\<open>Slicing lists into lists of lists\\<close>\n\ndefinition ilist_slice  :: \"'a ilist \\<Rightarrow> nat \\<Rightarrow> 'a list ilist\"\n  where \"ilist_slice f k \\<equiv> \\<lambda>x. map f [x * k..<Suc x * k]\"\n\nprimrec list_slice_aux :: \"'a list \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list list\"\nwhere\n  \"list_slice_aux xs k 0 = []\"\n| \"list_slice_aux xs k (Suc n) = take k xs # list_slice_aux (xs \\<up> k) k n\"\n\ndefinition list_slice :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list list\"\n  where \"list_slice xs k \\<equiv> list_slice_aux xs k (length xs div k)\"\n\ndefinition list_slice2 :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list list\"\n  where \"list_slice2 xs k \\<equiv>\n    list_slice xs k @ (if length xs mod k = 0 then [] else [xs \\<up> (length xs div k * k)])\"\n\ntext \\<open>\n  No function \\<open>list_unslice\\<close> for finite lists is needed \n  because the corresponding functionality is already provided by \\<open>concat\\<close>. \n  Therefore, only a \\<open>ilist_unslice\\<close> function for infinite lists is defined.\\<close>\n\ndefinition ilist_unslice  :: \"'a list ilist \\<Rightarrow> 'a ilist\"\n  where \"ilist_unslice f \\<equiv> \\<lambda>n. f (n div length (f 0)) ! (n mod length (f 0))\"\n\n\nlemma list_slice_aux_length: \"\\<And>xs. length (list_slice_aux xs k n) = n\"\nby (induct n, simp+)\n\nlemma list_slice_aux_nth: \"\n \\<And>m xs. m < n \\<Longrightarrow> (list_slice_aux xs k n) ! m = (xs \\<up> (m * k) \\<down> k)\"\napply (induct n)\n apply simp\napply (simp add: nth_Cons' diff_mult_distrib)\ndone\n\nlemma list_slice_length: \"length (list_slice xs k) = length xs div k\"\nby (simp add: list_slice_def list_slice_aux_length)\n\nlemma list_slice_0: \"list_slice xs 0 = []\"\nby (simp add: list_slice_def)\n\nlemma list_slice_1: \"list_slice xs (Suc 0) = map (\\<lambda>x. [x]) xs\"\nby (fastforce simp: list_eq_iff list_slice_def list_slice_aux_nth list_slice_aux_length)\n\nlemma list_slice_less: \"length xs < k \\<Longrightarrow> list_slice xs k = []\"\nby (simp add: list_slice_def)\n\nlemma list_slice_Nil: \"list_slice [] k = []\"\nby (simp add: list_slice_def)\n\nlemma list_slice_nth: \"\n  m < length xs div k \\<Longrightarrow> list_slice xs k ! m = xs \\<up> (m * k) \\<down> k\"\nby (simp add: list_slice_def list_slice_aux_nth)\n\nlemma list_slice_nth_length: \"\n  m < length xs div k \\<Longrightarrow> length ((list_slice xs k) ! m) = k\"\napply (case_tac \"length xs < k\")\n apply simp\napply (simp add: list_slice_nth)\nthm less_div_imp_mult_add_divisor_le\napply (drule less_div_imp_mult_add_divisor_le)\napply simp\ndone\n\nlemma list_slice_nth_eq_sublist_list: \"\n  m < length xs div k \\<Longrightarrow> list_slice xs k ! m = sublist_list xs [m * k..<m * k + k]\"\napply (simp add: list_slice_nth)\napply (rule take_drop_eq_sublist_list)\napply (rule less_div_imp_mult_add_divisor_le, assumption+)\ndone\n\nlemma list_slice_nth_nth: \"\n  \\<lbrakk> m < length xs div k; n < k \\<rbrakk> \\<Longrightarrow> \n  (list_slice xs k) ! m ! n = xs ! (m * k + n)\"\napply (frule list_slice_nth_length[of m xs k])\napply (simp add: list_slice_nth)\ndone\n\nlemma list_slice_nth_nth_rev: \"\n  n < length xs div k * k \\<Longrightarrow>\n  (list_slice xs k) ! (n div k) ! (n mod k) = xs ! n\"\napply (case_tac \"k = 0\", simp)\napply (simp add: list_slice_nth_nth div_less_conv)\ndone\n\nlemma list_slice_eq_list_slice_take: \"\n  list_slice (xs \\<down> (length xs div k * k)) k = list_slice xs k\"\napply (case_tac \"k = 0\")\n apply (simp add: list_slice_0)\napply (simp add: list_eq_iff list_slice_length)\napply (simp add: div_mult_le min_eqR list_slice_nth)\napply (clarify, rename_tac i)\napply (subgoal_tac \"k \\<le> length xs div k * k - i * k\")\n prefer 2\n apply (drule_tac m=i in Suc_leI)\n apply (drule mult_le_mono1[of _ _ k])\n apply simp\napply (subgoal_tac \"length xs div k * k - i * k \\<le> length xs - i * k\")\n prefer 2\n apply (simp add: div_mult_cancel)\napply (simp add: min_eqR)\nby (simp add: less_diff_conv)\n\nlemma list_slice_append_mult: \"\n  \\<And>xs. length xs = m * k \\<Longrightarrow>\n  list_slice (xs @ ys) k = list_slice xs k @ list_slice ys k\"\napply (case_tac \"k = 0\")\n apply (simp add: list_slice_0)\napply (induct m)\n apply (simp add: list_slice_Nil)\napply (simp add: list_slice_def)\napply (simp add: list_slice_def add.commute[of _ \"length ys\"] add.assoc[symmetric])\ndone\n\nlemma list_slice_append_mod: \"\n  length xs mod k = 0 \\<Longrightarrow>\n  list_slice (xs @ ys) k = list_slice xs k @ list_slice ys k\"\n  by (auto intro: list_slice_append_mult elim!: dvdE)\n\nlemma list_slice_div_eq_1[rule_format]: \"\n  length xs div k = Suc 0 \\<Longrightarrow> list_slice xs k = [take k xs]\"\nby (simp add: list_slice_def)\n\nlemma list_slice_div_eq_Suc[rule_format]: \"\n  length xs div k = Suc n \\<Longrightarrow>\n  list_slice xs k = list_slice (xs \\<down> (n * k)) k @ [xs \\<up> (n * k) \\<down> k]\"\napply (case_tac \"k = 0\", simp)\napply (subgoal_tac \"n * k < length xs\")\n prefer 2\n apply (case_tac \"length xs = 0\", simp)\n apply (drule_tac arg_cong[where f=\"\\<lambda>x. x - Suc 0\"], drule sym)\n apply (simp add: diff_mult_distrib div_mult_cancel)\napply (insert list_slice_append_mult[of \"take (n * k) xs\" n k \"drop (n * k) xs\"])\napply (simp add: min_eqR)\napply (rule list_slice_div_eq_1)\napply (simp add: div_diff_mult_self1)\ndone\n\nlemma list_slice2_mod_0: \"\n  length xs mod k = 0 \\<Longrightarrow> list_slice2 xs k = list_slice xs k\"\nby (simp add: list_slice2_def)\n\nlemma list_slice2_mod_gr0: \"\n  0 < length xs mod k \\<Longrightarrow> list_slice2 xs k = list_slice xs k @ [xs \\<up> (length xs div k * k)]\"\nby (simp add: list_slice2_def)\n\nlemma list_slice2_length: \"\n  length (list_slice2 xs k) = (\n  if length xs mod k = 0 then length xs div k else Suc (length xs div k))\"\nby (simp add: list_slice2_def list_slice_length)\n\nlemma list_slice2_0: \"\n  list_slice2 xs 0 = (if (length xs = 0) then [] else [xs])\"\nby (simp add: list_slice2_def list_slice_0)\n\nlemma list_slice2_1: \"list_slice2 xs (Suc 0) = map (\\<lambda>x. [x]) xs\"\nby (simp add: list_slice2_def list_slice_1)\n\nlemma list_slice2_le: \"\n  length xs \\<le> k \\<Longrightarrow> list_slice2 xs k = (if length xs = 0 then [] else [xs])\"\napply (case_tac \"k = 0\")\n apply (simp add: list_slice2_0)\napply (drule order_le_less[THEN iffD1], erule disjE)\n apply (simp add: list_slice2_def list_slice_def)\napply (simp add: list_slice2_def list_slice_div_eq_1)\ndone\n\nlemma list_slice2_Nil: \"list_slice2 [] k = []\"\nby (simp add: list_slice2_def list_slice_Nil)\n\n\n\nlemma list_slice2_last: \"\n  \\<lbrakk> length xs mod k > 0; m = length xs div k \\<rbrakk> \\<Longrightarrow>\n  list_slice2 xs k ! m = xs \\<up> (length xs div k * k)\"\nby (simp add: list_slice2_def nth_append list_slice_length)\n\nlemma list_slice2_nth: \"\n  \\<lbrakk> m < length xs div k \\<rbrakk> \\<Longrightarrow> \n  list_slice2 xs k ! m = xs \\<up> (m * k) \\<down> k\"\nby (simp add: list_slice2_def list_slice_length nth_append list_slice_nth)\n\nlemma list_slice2_nth_length_eq1: \"\n  m < length xs div k \\<Longrightarrow> length (list_slice2 xs k ! m) = k\"\nby (simp add: list_slice2_def nth_append list_slice_length list_slice_nth_length)\n\nlemma list_slice2_nth_length_eq2: \"\n  \\<lbrakk> length xs mod k > 0; m = length xs div k \\<rbrakk> \\<Longrightarrow> \n  length (list_slice2 xs k ! m) = length xs mod k\"\nby (simp add: list_slice2_def list_slice_length nth_append minus_div_mult_eq_mod [symmetric])\n\nlemma list_slice2_nth_nth_eq1: \"\n  \\<lbrakk> m < length xs div k; n < k \\<rbrakk> \\<Longrightarrow> \n  (list_slice2 xs k) ! m ! n = xs ! (m * k + n)\"\nby (simp add: list_slice2_list_slice_nth list_slice_nth_nth)\n\nlemma list_slice2_nth_nth_eq2: \"\n  \\<lbrakk> m = length xs div k; n < length xs mod k \\<rbrakk> \\<Longrightarrow> \n  (list_slice2 xs k) ! m ! n = xs ! (m * k + n)\"\nby (simp add: mult.commute[of _ k] minus_mod_eq_mult_div [symmetric] list_slice2_last)\n\nlemma list_slice2_nth_nth_rev: \"\n  n < length xs \\<Longrightarrow> (list_slice2 xs k) ! (n div k) ! (n mod k) = xs ! n\"\napply (case_tac \"k = 0\")\n apply (clarsimp simp: list_slice2_0)\napply (case_tac \"n div k < length xs div k\")\n apply (simp add: list_slice2_nth_nth_eq1)\napply (frule div_le_mono[OF less_imp_le, of _ _ k])\napply simp\napply (drule sym)\napply (subgoal_tac \"n mod k < length xs mod k\")\n prefer 2\n apply (rule ccontr)\n apply (simp add: linorder_not_less)\n apply (drule less_mod_ge_imp_div_less[of n \"length xs\" k], simp+)\napply (simp add: list_slice2_nth_nth_eq2)\ndone\n\nlemma list_slice2_append_mult: \"\n  length xs = m * k \\<Longrightarrow>\n  list_slice2 (xs @ ys) k = list_slice2 xs k @ list_slice2 ys k\"\napply (case_tac \"k = 0\")\n apply (simp add: list_slice2_0)\napply (clarsimp simp: list_slice2_def list_slice_append_mult)\napply (simp add: add.commute[of \"m * k\"] add_mult_distrib)\ndone\n\nlemma list_slice2_append_mod: \"\n  length xs mod k = 0 \\<Longrightarrow>\n  list_slice2 (xs @ ys) k = list_slice2 xs k @ list_slice2 ys k\"\n  by (auto intro: list_slice2_append_mult elim!: dvdE)\n\nlemma ilist_slice_nth: \"\n  (ilist_slice f k) m = map f [m * k..<Suc m * k]\"\nby (simp add: ilist_slice_def)\n\nlemma ilist_slice_nth_length: \"length ((ilist_slice f k) m) = k\"\nby (simp add: ilist_slice_def)\n\nlemma ilist_slice_nth_nth: \"\n  n < k \\<Longrightarrow> (ilist_slice f k) m ! n = f (m * k + n)\"\nby (simp add: ilist_slice_def)\n\nlemma ilist_slice_nth_nth_rev: \"\n  0 < k \\<Longrightarrow> (ilist_slice f k) (n div k) ! (n mod k) = f n\"\nby (simp add: ilist_slice_nth_nth)\n\nlemma list_slice_concat: \"\n  concat (list_slice xs k) = xs \\<down> (length xs div k * k)\"\n  (is \"?P xs k\")\napply (case_tac \"k = 0\")\n apply (simp add: list_slice_0)\napply simp\napply (subgoal_tac \"\\<And>m. \\<forall>xs. length xs div k = m \\<longrightarrow> ?P xs k\", simp)\napply (induct_tac m)\n apply (intro allI impI)\n apply (simp add: in_set_conv_nth div_eq_0_conv' list_slice_less)\napply clarify\napply (simp add: add.commute[of k])\napply (subgoal_tac \"n * k + k \\<le> length xs\")\n prefer 2\n apply (simp add: le_less_div_conv[symmetric])\napply (simp add: list_slice_div_eq_Suc)\napply (drule_tac x=\"xs \\<down> (n * k)\" in spec)\napply (simp add: min_eqR)\napply (simp add: take_add)\ndone\n\nlemma list_slice_unslice_mult: \"\n  length xs = m * k \\<Longrightarrow> concat (list_slice xs k) = xs\"\napply (case_tac \"k = 0\")\n apply (simp add: list_slice_Nil)\napply (simp add: list_slice_concat)\ndone\n\nlemma ilist_slice_unslice: \"0 < k \\<Longrightarrow> ilist_unslice (ilist_slice f k) = f\"\nby (simp add: ilist_unslice_def ilist_slice_nth_length ilist_slice_nth_nth)\n\nlemma i_take_ilist_slice_eq_list_slice: \"\n  0 < k \\<Longrightarrow> ilist_slice f k \\<Down> n = list_slice (f \\<Down> (n * k)) k\"\napply (simp add: list_eq_iff list_slice_length ilist_slice_nth list_slice_nth)\napply (clarify, rename_tac i)\napply (subgoal_tac \"k \\<le> n * k - i * k\")\n prefer 2\n apply (drule_tac m=i in Suc_leI)\n apply (drule mult_le_mono1[of _ _ k])\n apply simp\napply simp\ndone\n\nlemma list_slice_i_take_eq_i_take_ilist_slice: \"\n  list_slice (f \\<Down> n) k = ilist_slice f k \\<Down> (n div k)\"\napply (case_tac \"k = 0\")\n apply (simp add: list_slice_0)\napply (simp add: i_take_ilist_slice_eq_list_slice)\napply (subst list_slice_eq_list_slice_take[of \"f \\<Down> n\", symmetric])\napply (simp add: div_mult_le min_eqR)\ndone\n\n\nlemma ilist_slice_i_append_mod: \"\n  length xs mod k = 0 \\<Longrightarrow> \n  ilist_slice (xs \\<frown> f) k = list_slice xs k \\<frown> ilist_slice f k\"\napply (simp add: ilist_eq_iff ilist_slice_nth i_append_nth list_slice_length)\napply (clarsimp simp: mult.commute[of k] elim!: dvdE, rename_tac n i)\napply (intro conjI impI)\n apply (simp add: list_slice_nth)\n apply (subgoal_tac \"k \\<le> n * k - i * k\")\n  prefer 2\n  apply (drule_tac m=i in Suc_leI)\n  apply (drule mult_le_mono1[of _ _ k])\n  apply simp\n apply (fastforce simp: list_eq_iff i_append_nth min_eqR)\napply (simp add: ilist_eq_iff list_eq_iff i_append_nth linorder_not_less)\napply (clarify, rename_tac j)\napply (subgoal_tac \"n * k \\<le> i * k + j\")\n prefer 2\n apply (simp add: trans_le_add1) \napply (simp add: diff_mult_distrib)\ndone\n\ncorollary ilist_slice_append_mult: \"\n  length xs = m * k \\<Longrightarrow> \n  ilist_slice (xs \\<frown> f) k = list_slice xs k \\<frown> ilist_slice f k\"\nby (simp add: ilist_slice_i_append_mod)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/AutoFocus-Stream/ListSlice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544911, "lm_q2_score": 0.8633916011860785, "lm_q1q2_score": 0.7618808085493581}}
{"text": "theory Lists\nimports Main\nbegin\n\nsection {* Lists *}\nsubsection {* Pairs of Numbers *}\n\ndatatype natprod = pair nat nat\n\nvalue \"pair 3 5\"\n  (* \\<Longrightarrow> \"pair (Suc (Suc (Suc 0))) (Suc (Suc (Suc (Suc (Suc 0)))))\" :: \"natprod\" *)\n\nfun fst :: \"natprod \\<Rightarrow> nat\" where\n  \"fst (pair x _) = x\"\nfun snd :: \"natprod \\<Rightarrow> nat\" where\n  \"snd (pair _ y) = y\"\nfun swap_pair :: \"natprod \\<Rightarrow> natprod\" where\n  \"swap_pair (pair x y) = pair y x\"\n\nvalue \"fst (pair 3 5)\"\n  (* \\<Longrightarrow> \"Suc (Suc (Suc 0))\" :: \"nat\" *)\n\n(* value \"fst (3,5)\" *)\n  (* \\<Longrightarrow> \"Suc (Suc (Suc 0))\" :: \"nat\" *)\n\ntheorem surjective_pairing': \"\\<forall>n m :: nat. pair n m = pair (fst (pair n m)) (snd (pair n m))\" by simp\ntheorem surjective_pairing_stuck: \"\\<forall>(p :: natprod). p = pair (fst p) (snd p)\"\napply auto by (case_tac p, simp)\n\n(* Exercise: 1 star (snd_fst_is_swap) *)\n\ntheorem snd_fst_is_swap: \"\\<forall>(p :: natprod). pair (snd p) (fst p) = swap_pair p\"\napply auto by (case_tac p, simp)\n\n(* Exercise: 1 star, optional (fst_swap_is_snd) *)\n\ntheorem fst_swap_is_snd: \"\\<forall>(p :: natprod). fst (swap_pair p) = snd p\"\napply auto by (case_tac p, simp)\n\nsubsection {* Lists of Numbers *}\n\ndatatype natlist = nil | cons nat natlist\n\ndefinition \"mylist \\<equiv> cons 1 (cons 2 (cons 3 nil))\"\n\nno_notation\n  List.Nil (\"[]\")\n\nnotation\n  nil (\"[]\") and\n  cons (infixr \";\" 60)\n\nno_syntax\n  \"_list\" :: \"args \\<Rightarrow> 'a list\" (\"[(_)]\")\n\nsyntax\n  \"_natlist\" :: \"args \\<Rightarrow> natlist\" (\"[(_)]\")\n\ntranslations\n  \"[x; xs]\" == \"x;[xs]\"\n  \"[x]\" == \"x;[]\"\n\ndefinition \"mylist1 \\<equiv> 1 ; (2 ; (3 ; nil))\"\ndefinition \"mylist2 \\<equiv> 1 ; 2 ; 3 ; nil\"\ndefinition \"mylist3 \\<equiv> [1;2;3]\"\n\nsubsubsection {* Repeat *}\n\nfun repeat :: \"nat \\<Rightarrow> nat \\<Rightarrow> natlist\" where\n  \"repeat n 0 = []\"\n  | \"repeat n (Suc count) = n ; (repeat n count)\"\n\nsubsubsection {* Length *}\n\nfun length :: \"natlist \\<Rightarrow> nat\" where\n  \"length nil = 0\"\n  | \"length (h ; t) = Suc (length t)\"\n\nsubsubsection {* Append *}\n\nno_notation\n  Map.map_add (infixl \"++\" 100)\n\nfun app :: \"natlist \\<Rightarrow> natlist \\<Rightarrow> natlist\" (infixr \"++\" 80) where\n  \"app nil l2 = l2\"\n  | \"app (h ; t) l2 = h ; (app t l2)\"\n\nlemma test_app1: \"[1;2;3] ++ [4;5] = [1;2;3;4;5]\" by simp\nlemma test_app2: \"nil ++ [4;5] = [4;5]\" by simp\nlemma test_app3: \"[1;2;3] ++ nil = [1;2;3]\" by simp\n\nsubsubsection {* Head (with default) and Tail *}\n\nfun hd :: \"nat \\<Rightarrow> natlist \\<Rightarrow> nat\" where\n  \"hd d nil = d\"\n  | \"hd _ (h ; t) = h\"\n\nfun tl :: \"natlist \\<Rightarrow> natlist\" where\n  \"tl nil = nil\"\n  | \"tl (h ; t) = t\"\n\nlemma test_hd1: \"hd 0 [1;2;3] = 1\" by simp\nlemma test_hd2: \"hd 0 [] = 0\" by simp\nlemma test_tl: \"tl [1;2;3] = [2;3]\" by simp\n\n(* Exercise: 2 stars (list_funs) *)\n\nfun nonzeros :: \"natlist \\<Rightarrow> natlist\" where\n  \"nonzeros nil = nil\"\n  | \"nonzeros (h ; t) = (if h = 0 then nonzeros t else h ; nonzeros t)\"\n\nlemma test_nonzeros: \"nonzeros [0;1;0;2;3;0;0] = [1;2;3]\" by simp\n\nfun oddmembers :: \"natlist \\<Rightarrow> natlist\" where\n  \"oddmembers nil = nil\"\n  | \"oddmembers (h ; t) = (if h mod 2 = 0 then oddmembers t else h ; oddmembers t)\"\n\nlemma test_oddmembers: \"oddmembers [0;1;0;2;3;0;0] = [1;3]\" by simp\n\nfun countoddmembers :: \"natlist \\<Rightarrow> nat\" where\n  \"countoddmembers l = length (oddmembers l)\"\n\nlemma test_countoddmembers1: \"countoddmembers [1;0;3;1;4;5] = 4\" by simp\nlemma test_countoddmembers2: \"countoddmembers [0;2;4] = 0\" by simp\nlemma test_countoddmembers3: \"countoddmembers nil = 0\" by simp\n\n(* Exercise: 3 stars, advanced (alternate) *)\n\nfun alternate :: \"natlist \\<Rightarrow> natlist \\<Rightarrow> natlist\" where\n  \"alternate nil l2 = l2\"\n  | \"alternate l1 nil = l1\"\n  | \"alternate (h1;t1) (h2;t2) = h1 ; h2 ; alternate t1 t2\"\n\nlemma test_alternate1: \"alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6]\" by simp\nlemma test_alternate2: \"alternate [1] [4;5;6] = [1;4;5;6]\" by simp\nlemma test_alternate3: \"alternate [1;2;3] [4] = [1;4;2;3]\" by simp\nlemma test_alternate4: \"alternate [] [20;30] = [20;30]\" by simp\n\nsubsubsection {* Bags via Lists *}\n\ntype_synonym bag = natlist\n\n(* Exercise: 3 stars (bag_functions) *)\n\nfun count :: \"nat \\<Rightarrow> bag \\<Rightarrow> nat\" where\n  \"count _ nil = 0\"\n  | \"count a (h ; t) = (if a = h then 1 + count a t else count a t)\"\n\nlemma test_count1: \"count 1 [1;2;3;1;4;1] = 3\" by simp\nlemma test_count2: \"count 6 [1;2;3;1;4;1] = 0\" by simp\n\nfun sum :: \"bag \\<Rightarrow> bag \\<Rightarrow> bag\" where\n  \"sum l1 l2 = l1 ++ l2\"\n\nlemma test_sum1: \"count 1 (sum [1;2;3] [1;4;1]) = 3\" by simp\n\nfun add :: \"nat \\<Rightarrow> bag \\<Rightarrow> bag\" where\n  \"add x xs = x ; xs\"\n\nlemma test_add1: \"count 1 (add 1 [1;4;1]) = 3\" by simp\nlemma test_add2: \"count 5 (add 1 [1;4;1]) = 0\" by simp\n\nfun member :: \"nat \\<Rightarrow> bag \\<Rightarrow> bool\" where\n  \"member x nil = False\"\n  | \"member x (h; t) = (if x = h then True else member x t)\"\n\nlemma test_member1: \"member 1 [1;4;1] = True\" by simp\nlemma test_member2: \"member 2 [1;4;1] = False\" by simp\n\n(* Exercise: 3 stars, optional (bag_more_functions) *)\n\nfun remove_one :: \"nat \\<Rightarrow> bag \\<Rightarrow> bag\" where\n  \"remove_one _ nil = nil\"\n  | \"remove_one x (h;t) = (if x = h then t else h ; remove_one x t)\"\n\nlemma test_remove_one1: \"count 5 (remove_one 5 [2;1;5;4;1]) = 0\" by simp\nlemma test_remove_one2: \"count 5 (remove_one 5 [2;1;4;1]) = 0\" by simp\nlemma test_remove_one3: \"count 4 (remove_one 5 [2;1;4;5;1;4]) = 2\" by simp\nlemma test_remove_one4: \"count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1\" by simp\n\nfun remove_all :: \"nat \\<Rightarrow> bag \\<Rightarrow> bag\" where\n  \"remove_all _ nil = nil\"\n  | \"remove_all x (h;t) = (if x = h then remove_all x t else h ; remove_all x t)\"\n\nlemma test_remove_all1: \"count 5 (remove_all 5 [2;1;5;4;1]) = 0\" by simp\nlemma test_remove_all2: \"count 5 (remove_all 5 [2;1;4;1]) = 0\" by simp\nlemma test_remove_all3: \"count 4 (remove_all 5 [2;1;4;5;1;4]) = 2\" by simp\nlemma test_remove_all4: \"count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0\" by simp\n\nfun subset :: \"bag \\<Rightarrow> bag \\<Rightarrow> bool\" where\n  \"subset nil _ = True\"\n  | \"subset (x ; xs) ys = (if count x ys = 0 then False else subset xs (remove_one x ys))\"\n\nlemma test_subset1: \"subset [1;2] [2;1;4;1] = True\" by simp\nlemma test_subset2: \"subset [1;2;2] [2;1;4;1] = False\" by simp\n\n(* Exercise: 3 stars (bag_theorem) *)\n\nsubsection {* Reasoning About Lists *}\n\ntheorem nil_app: \"\\<forall>l::natlist. [] ++ l = l\" by simp\n\nfun pred :: \"nat \\<Rightarrow> nat\" where\n  \"pred 0 = 0\"\n  | \"pred (Suc n) = n\"\n\ntheorem tl_length_pred: \"\\<forall>l::natlist. pred (length l) = length (tl l)\"\napply auto by (case_tac l, auto)\n\nsubsubsection {* Micro-Sermon *}\nsubsubsection {* Induction on Lists *}\n\ntheorem app_assoc: \"\\<forall>l1 l2 l3 :: natlist. (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)\"\napply auto by (induct_tac l1, auto)\n\nsubsubsection {* Informal version *}\n\n(* Informal version of the proof *)\ntheorem app_assoc_Isar: \"\\<forall>l1 l2 l3 :: natlist. (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)\"\nproof (auto, induct_tac l1)\n  (* case l1 = [] *)\n  show \"\\<And>l1 l2 l3. ([] ++ l2) ++ l3 = [] ++ l2 ++ l3\" by simp\nnext\n  (* case l1 = nat ; natlist *)\n  fix l1 l2 l3 nat natlist\n  assume hyp: \"(natlist ++ l2) ++ l3 = natlist ++ l2 ++ l3\"\n  show \"((nat ; natlist) ++ l2) ++ l3 = (nat ; natlist) ++ l2 ++ l3\"\n    using hyp by simp\nqed\n\nsubsubsection {* Another example *}\n\ntheorem app_length: \"\\<forall>l1 l2 :: natlist. length (l1 ++ l2) = (length l1) + (length l2)\"\napply auto by (induct_tac l1, auto)\n\nsubsubsection {* Reversing a list *}\n\nfun snoc :: \"natlist \\<Rightarrow> nat \\<Rightarrow> natlist\" where\n  \"snoc nil v = [v]\"\n  | \"snoc (h;t) v = h ; (snoc t v)\"\n\nfun rev :: \"natlist \\<Rightarrow> natlist\" where\n  \"rev nil = nil\"\n  | \"rev (h ; t) = snoc (rev t) h\"\n\nlemma test_rev1: \"rev [1;2;3] = [3;2;1]\" by simp\nlemma test_rev2: \"rev nil = nil\" by simp\n\nsubsubsection {* Proofs about reverse *}\n\ntheorem length_snoc: \"\\<forall>n :: nat. \\<forall>l :: natlist. length (snoc l n) = Suc (length l)\"\napply auto by (induct_tac l, auto)\n\ntheorem rev_length: \"\\<forall>l :: natlist. length (rev l) = length l\"\napply auto by (induct_tac l, auto simp add: length_snoc)\n\ntheorem length_snoc_Isar: \"\\<forall>n :: nat. \\<forall>l :: natlist. length (snoc l n) = Suc (length l)\"\nproof (auto, induct_tac l)\n  (* case l = [] *)\n  fix n l\n  show \"Lists.length (snoc [] n) = Suc (Lists.length [])\" by simp\nnext\n  (* case l = nat ; natlist *)\n  fix n l nat natlist\n  assume hyp: \"Lists.length (snoc natlist n) = Suc (Lists.length natlist)\"\n  show \"Lists.length (snoc (nat ; natlist) n) = Suc (Lists.length (nat ; natlist))\"\n    using hyp by simp\nqed\n\n(* theorem rev_length_Isar: \"\\<forall>l :: natlist. length (rev l) = length l\" *)\n\nsubsubsection {* SearchAbout *}\nsubsubsection {* List Exercises, Part 1 *}\n\n(* Exercise: 3 stars (list_exercises) *)\n\ntheorem app_nil_end: \"\\<forall>l :: natlist. l ++ [] = l\"\napply auto by (induct_tac l, auto)\n\nlemma rev_involutive_lem: \"\\<And>x :: nat. \\<And>l :: natlist. rev (snoc l x) = x ; rev l\"\nby (induct_tac l, auto)\n\ntheorem rev_involutive: \"\\<forall>l :: natlist. rev (rev l) = l\"\napply auto by (induct_tac l, auto simp add: rev_involutive_lem)\n\ntheorem app_assoc4: \"\\<forall>l1 l2 l3 l4 :: natlist. l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4\"\napply auto by (induct_tac l1, auto simp add: app_assoc)\n\ntheorem snoc_append: \"\\<forall>(l::natlist) (n::nat). snoc l n = l ++ [n]\"\napply auto by (induct_tac l, auto)\n\ntheorem distr_rev: \"\\<forall>l1 l2 :: natlist. rev (l1 ++ l2) = (rev l2) ++ (rev l1)\"\napply auto by (induct_tac l1, auto simp add: app_nil_end snoc_append app_assoc)\n\nlemma nonzeros_app: \"\\<forall>l1 l2 :: natlist. nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2)\"\napply auto by (induct_tac l1, auto)\n\n(* Exercise: 2 stars (beq_natlist) *)\n\nfun beq_natlist :: \"natlist \\<Rightarrow> natlist \\<Rightarrow> bool\" where\n  \"beq_natlist nil nil = True\"\n  | \"beq_natlist nil _ = False\"\n  | \"beq_natlist _ nil = False\"\n  | \"beq_natlist (h1;t1) (h2;t2) = (if h1 = h2 then beq_natlist t1 t2 else False)\"\n\nlemma test_beq_natlist1: \"beq_natlist nil nil = True\" by simp\nlemma test_beq_natlist2: \"beq_natlist [1;2;3] [1;2;3] = True\" by simp\nlemma test_beq_natlist3: \"beq_natlist [1;2;3] [1;2;4] = False\" by simp\n\ntheorem beq_natlist_refl: \"\\<forall>l::natlist. True = beq_natlist l l\"\napply auto by (induct_tac l, auto)\n\nsubsubsection {* List Exercises, Part 2 *}\n\n(* Exercise: 2 stars (list_design) *)\n(* Exercise: 3 stars, advanced (bag_proofs) *)\n\n(* ble_nat = \\<le> *)\ntheorem count_member_nonzero: \"\\<forall>(s :: bag). 1 \\<le> (count 1 (1 ; s)) = True\" by simp\n\ntheorem ble_n_Sn : \"\\<forall>n. n \\<le> (Suc n) = True\" by simp\n\ntheorem remove_decreases_count: \"\\<forall>(s :: bag). count 0 (remove_one 0 s) \\<le> count 0 s = True\"\napply auto by (induct_tac s, auto)\n\n(* Exercise: 3 stars, optional (bag_count_sum) *)\n(* Exercise: 4 stars, advanced (rev_injective) *)\n\nlemma rev_injective_lem: \"\\<And>l1 l2. rev (rev l1) = rev (rev l2) \\<Longrightarrow> l1 = l2\"\nby (auto simp add: rev_involutive)\n\ntheorem rev_injective: \"\\<forall>l1 l2 :: natlist. rev l1 = rev l2 \\<longrightarrow> l1 = l2\"\napply auto by (auto simp add: rev_injective_lem)\n\n(* a hard way? *)\n\nsubsection {* Options *}\n\ndatatype natoption = Some nat | None\n\nfun index :: \"nat \\<Rightarrow> natlist \\<Rightarrow> natoption\" where\n  \"index n nil = None\"\n  | \"index n (a ; l) = (if n = 0 then Some a else index (pred n) l)\"\n\nlemma test_index1: \"index 0 [4;5;6;7] = Some 4\" by simp\nlemma test_index2: \"index 3 [4;5;6;7] = Some 7\"\nproof -\n  have 3: \"3 = Suc (Suc 1)\" by simp\n  show ?thesis by (simp add: 3)\nqed\nlemma test_index3: \"index 10 [4;5;6;7] = None\"\nproof -\n  have 10: \"10 = Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc (Suc 1))))))))\" by simp\n  show ?thesis by (simp add: 10)\nqed\n\nfun option_elim :: \"nat \\<Rightarrow> natoption \\<Rightarrow> nat\" where\n  \"option_elim d (Some n) = n\"\n  | \"option_elim d None = d\"\n\n(* Exercise: 2 stars (hd_opt) *)\n\nfun hd_opt :: \"natlist \\<Rightarrow> natoption\" where\n  \"hd_opt nil = None\"\n  | \"hd_opt l = Some (hd 0 l)\"\n\nlemma test_hd_opt1: \"hd_opt [] = None\" by simp\nlemma test_hd_opt2: \"hd_opt [1] = Some 1\" by simp\nlemma test_hd_opt3: \"hd_opt [5;6] = Some 5\" by simp\n\n(* Exercise: 1 star, optional (option_elim_hd) *)\n\ntheorem option_elim_hd: \"\\<forall>(l::natlist) (default::nat). hd default l = option_elim default (hd_opt l)\"\napply auto by (induct_tac l, auto)\n\nsubsection {* Dictionaries *}\n\ndatatype dictionary = empty | record' nat nat dictionary\n\nfun insert :: \"nat \\<Rightarrow> nat \\<Rightarrow> dictionary \\<Rightarrow> dictionary\" where\n  \"insert key value d = record' key value d\"\n\nfun find :: \"nat \\<Rightarrow> dictionary \\<Rightarrow> natoption\" where\n  \"find key empty = None\"\n  | \"find key (record' k v d) = (if key = k then Some v else find key d)\"\n\n(* Exercise: 1 star (dictionary_invariant1) *)\n\ntheorem dictionary_invariant1': \"\\<forall>(d :: dictionary) k (v :: nat). (find k (insert k v d)) = Some v\"\nby simp\n\n(* Exercise: 1 star (dictionary_invariant2) *)\n\ntheorem dictionary_invariant2': \"\\<forall>(d :: dictionary) (m :: nat) n o'. m = n = False \\<longrightarrow> find m d = find m (insert n o' d)\"\nby simp\n\nend\n", "meta": {"author": "myuon", "repo": "isabelle-software-foundations", "sha": "8dd28cd2628050549278a922ee72612459585de1", "save_path": "github-repos/isabelle/myuon-isabelle-software-foundations", "path": "github-repos/isabelle/myuon-isabelle-software-foundations/isabelle-software-foundations-8dd28cd2628050549278a922ee72612459585de1/src/Lists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278571786138, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.7618808036424489}}
{"text": "(*  Title:      HOL/Examples/Knaster_Tarski.thy\n    Author:     Makarius\n\nTypical textbook proof example.\n*)\n\nsection \\<open>Textbook-style reasoning: the Knaster-Tarski Theorem\\<close>\n\ntheory Knaster_Tarski\n  imports Main\nbegin\n\nunbundle lattice_syntax\n\n\nsubsection \\<open>Prose version\\<close>\n\ntext \\<open>\n  According to the textbook \\<^cite>\\<open>\\<open>pages 93--94\\<close> in \"davey-priestley\"\\<close>, the\n  Knaster-Tarski fixpoint theorem is as follows.\\<^footnote>\\<open>We have dualized the\n  argument, and tuned the notation a little bit.\\<close>\n\n  \\<^bold>\\<open>The Knaster-Tarski Fixpoint Theorem.\\<close> Let \\<open>L\\<close> be a complete lattice and\n  \\<open>f: L \\<rightarrow> L\\<close> an order-preserving map. Then \\<open>\\<Sqinter>{x \\<in> L | f(x) \\<le> x}\\<close> is a fixpoint\n  of \\<open>f\\<close>.\n\n  \\<^bold>\\<open>Proof.\\<close> Let \\<open>H = {x \\<in> L | f(x) \\<le> x}\\<close> and \\<open>a = \\<Sqinter>H\\<close>. For all \\<open>x \\<in> H\\<close> we have\n  \\<open>a \\<le> x\\<close>, so \\<open>f(a) \\<le> f(x) \\<le> x\\<close>. Thus \\<open>f(a)\\<close> is a lower bound of \\<open>H\\<close>, whence\n  \\<open>f(a) \\<le> a\\<close>. We now use this inequality to prove the reverse one (!) and\n  thereby complete the proof that \\<open>a\\<close> is a fixpoint. Since \\<open>f\\<close> is\n  order-preserving, \\<open>f(f(a)) \\<le> f(a)\\<close>. This says \\<open>f(a) \\<in> H\\<close>, so \\<open>a \\<le> f(a)\\<close>.\\<close>\n\n\nsubsection \\<open>Formal versions\\<close>\n\ntext \\<open>\n  The Isar proof below closely follows the original presentation. Virtually\n  all of the prose narration has been rephrased in terms of formal Isar\n  language elements. Just as many textbook-style proofs, there is a strong\n  bias towards forward proof, and several bends in the course of reasoning.\n\\<close>\n\ntheorem Knaster_Tarski:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"\\<exists>a. f a = a\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof -\n    {\n      fix x\n      assume \"x \\<in> ?H\"\n      then have \"?a \\<le> x\" by (rule Inf_lower)\n      with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n      also from \\<open>x \\<in> ?H\\<close> have \"\\<dots> \\<le> x\" ..\n      finally have \"f ?a \\<le> x\" .\n    }\n    then have \"f ?a \\<le> ?a\" by (rule Inf_greatest)\n    {\n      also presume \"\\<dots> \\<le> f ?a\"\n      finally (order_antisym) show ?thesis .\n    }\n    from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n    then have \"f ?a \\<in> ?H\" ..\n    then show \"?a \\<le> f ?a\" by (rule Inf_lower)\n  qed\nqed\n\ntext \\<open>\n  Above we have used several advanced Isar language elements, such as explicit\n  block structure and weak assumptions. Thus we have mimicked the particular\n  way of reasoning of the original text.\n\n  In the subsequent version the order of reasoning is changed to achieve\n  structured top-down decomposition of the problem at the outer level, while\n  only the inner steps of reasoning are done in a forward manner. We are\n  certainly more at ease here, requiring only the most basic features of the\n  Isar language.\n\\<close>\n\ntheorem Knaster_Tarski':\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"\\<exists>a. f a = a\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof (rule order_antisym)\n    show \"f ?a \\<le> ?a\"\n    proof (rule Inf_greatest)\n      fix x\n      assume \"x \\<in> ?H\"\n      then have \"?a \\<le> x\" by (rule Inf_lower)\n      with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n      also from \\<open>x \\<in> ?H\\<close> have \"\\<dots> \\<le> x\" ..\n      finally show \"f ?a \\<le> x\" .\n    qed\n    show \"?a \\<le> f ?a\"\n    proof (rule Inf_lower)\n      from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n      then show \"f ?a \\<in> ?H\" ..\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Examples/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.884039278690883, "lm_q1q2_score": 0.7616336172300476}}
{"text": "(*\n  File:     Complex_Lexorder.thy\n  Author:   Manuel Eberl, TU München\n*)\nsection \\<open>The lexicographic ordering on complex numbers\\<close>\ntheory Complex_Lexorder\n  imports Complex_Main \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>\n  We define a lexicographic order on the complex numbers, comparing first the real parts\n  and, if they are equal, the imaginary parts. This ordering is of course not compatible with\n  multiplication, but it is compatible with addition.\n\\<close>\n\ndefinition less_eq_complex_lex (infix \"\\<le>\\<^sub>\\<complex>\" 50)  where\n  \"less_eq_complex_lex x y \\<longleftrightarrow> Re x < Re y \\<or> Re x = Re y \\<and> Im x \\<le> Im y\"\n\ndefinition less_complex_lex (infix \"<\\<^sub>\\<complex>\" 50) where\n  \"less_complex_lex x y \\<longleftrightarrow> Re x < Re y \\<or> Re x = Re y \\<and> Im x < Im y\"\n\ninterpretation complex_lex:\n  linordered_ab_group_add \"(+)\" 0 \"(-)\" \"uminus\" less_eq_complex_lex less_complex_lex\n  by standard (auto simp: less_eq_complex_lex_def less_complex_lex_def complex_eq_iff)\n\nlemmas [trans] =\n  complex_lex.order.trans complex_lex.less_le_trans\n  complex_lex.less_trans complex_lex.le_less_trans\n\nlemma (in ordered_comm_monoid_add) sum_mono_complex_lex:\n  \"(\\<And>i. i\\<in>K \\<Longrightarrow> f i \\<le>\\<^sub>\\<complex> g i) \\<Longrightarrow> (\\<Sum>i\\<in>K. f i) \\<le>\\<^sub>\\<complex> (\\<Sum>i\\<in>K. g i)\"\n  by (induct K rule: infinite_finite_induct) (use complex_lex.add_mono in auto)\n\nlemma sum_strict_mono_ex1_complex_lex:\n  fixes f g :: \"'i \\<Rightarrow> complex\"\n  assumes \"finite A\"\n    and \"\\<forall>x\\<in>A. f x \\<le>\\<^sub>\\<complex> g x\"\n    and \"\\<exists>a\\<in>A. f a <\\<^sub>\\<complex> g a\"\n  shows \"sum f A <\\<^sub>\\<complex> sum g A\"\nproof-\n  from assms(3) obtain a where a: \"a \\<in> A\" \"f a <\\<^sub>\\<complex> g a\" by blast\n  have \"sum f A = sum f ((A - {a}) \\<union> {a})\"\n    by (simp add: insert_absorb[OF \\<open>a \\<in> A\\<close>])\n  also have \"\\<dots> = sum f (A - {a}) + sum f {a}\"\n    using \\<open>finite A\\<close> by (subst sum.union_disjoint) auto\n  also have \"\\<dots> \\<le>\\<^sub>\\<complex> sum g (A - {a}) + sum f {a}\"\n    by (intro complex_lex.add_mono sum_mono_complex_lex) (simp_all add: assms)\n  also have \"\\<dots> <\\<^sub>\\<complex> sum g (A - {a}) + sum g {a}\"\n    using a by (intro complex_lex.add_strict_left_mono) auto\n  also have \"\\<dots> = sum g ((A - {a}) \\<union> {a})\"\n    using \\<open>finite A\\<close> by (subst sum.union_disjoint[symmetric]) auto\n  also have \"\\<dots> = sum g A\" by (simp add: insert_absorb[OF \\<open>a \\<in> A\\<close>])\n  finally show ?thesis\n    by simp\nqed\n\nlemma sum_list_mono_complex_lex:\n  assumes \"list_all2 (\\<le>\\<^sub>\\<complex>) xs ys\"\n  shows   \"sum_list xs \\<le>\\<^sub>\\<complex> sum_list ys\"\n  using assms by induction (auto intro: complex_lex.add_mono)\n\nlemma sum_mset_mono_complex_lex:\n  assumes \"rel_mset (\\<le>\\<^sub>\\<complex>) A B\"\n  shows   \"sum_mset A \\<le>\\<^sub>\\<complex> sum_mset B\"\n  using assms by (auto simp: rel_mset_def sum_mset_sum_list intro: sum_list_mono_complex_lex)\n\nlemma rel_msetI:\n  assumes \"list_all2 R xs ys\" \"mset xs = A\" \"mset ys = B\"\n  shows   \"rel_mset R A B\"\n  using assms by (auto simp: rel_mset_def)\n\nlemma mset_replicate [simp]: \"mset (replicate n x) = replicate_mset n x\"\n  by (induction n) auto\n\nlemma rel_mset_replicate_mset_right:\n  assumes \"\\<And>x. x \\<in># A \\<Longrightarrow> R x y\" \"size A = n\"\n  shows   \"rel_mset R A (replicate_mset n y)\"\nproof -\n  obtain xs where [simp]: \"A = mset xs\"\n    by (metis ex_mset)\n  from assms have \"\\<forall>x\\<in>set xs. R x y\"\n    by auto\n  hence \"list_all2 R xs (replicate (length xs) y)\"\n    by (induction xs) auto\n  with assms(2) show ?thesis\n    by (intro rel_msetI[of R xs \"replicate n y\"]) auto\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Hermite_Lindemann/Complex_Lexorder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.8615382058759129, "lm_q1q2_score": 0.7616336114550507}}
{"text": "theory \"selection-sort\"\n  imports Main \"HOL-Library.Multiset\"\nbegin\n\ntext \\<open>no tail-recursive\\<close>\n\nlemma remove_member: \"y \\<in> set (x#xs) \\<Longrightarrow> length (remove1 y (x#xs)) < length (x#xs)\"\nproof(induct xs arbitrary: y x)\n  case Nil\n  have \"length (remove1 y [x]) = length (remove1 x [x])\" using Nil.prems by simp\n  also have \"length (remove1 x [x]) = length []\" by simp\n  also have \"length [] < length [x]\" by simp\n  finally show \"length (remove1 y [x]) < length [x]\" by this\nnext\n  case (Cons a xs)\n  then show \"length (remove1 y (x # a # xs)) < length (x # a # xs)\"\n  proof(cases \"y \\<in> set (a # xs)\")\n    case True\n    have \"length (remove1 y (x # a # xs)) = length (x#remove1 y (a # xs))\" using One_nat_def Suc_pred True length_Cons length_pos_if_in_set length_remove1 remove1.simps(2)  by metis\n    also have \"... = length [x] + length (remove1 y (a # xs))\"  by simp\n    also have \"... < length [x] + length (a # xs)\" using Cons.hyps True by simp\n    also have \"... = length (x # a # xs)\" by simp\n    finally show \"length (remove1 y (x # a # xs)) < length (x # a # xs)\" by this\n  next\n    case False\n    have \"length (remove1 y (x # a # xs)) = length (remove1 x (x # a # xs))\" using Cons.prems False by simp\n    also have \"... = length (a # xs)\" by simp\n    also have \"... < length (x # a # xs)\" by simp\n    finally show \"length (remove1 y (x # a # xs)) < length (x # a # xs)\" by this\n  qed\nqed\n\nfunction selection_sort:: \"nat list \\<Rightarrow> nat list\" where\nselection_sort_Null:  \"selection_sort [] = []\" |\nselection_sort_Cons: \"selection_sort (x#xs) = (let minimum = Min (set(x#xs)); rest = remove1 minimum (x#xs) in minimum#selection_sort(rest))\"\nby pat_completeness auto       \ntermination\nproof (relation \"measure (\\<lambda>(xs). length xs)\")\n  show \"wf (measure length)\"  by simp\nnext\n  fix minimum x ::nat\n  fix rest xs:: \"nat list\"\n  assume a1: \"minimum =  Min (set (x # xs))\"\n  assume a2: \"rest = remove1 minimum (x # xs)\"\n  show \"(rest, x # xs) \\<in> measure length\"\n  proof (simp only: in_measure)\n    have p1: \"minimum \\<in> set (x#xs)\" using a1 eq_Min_iff by blast\n    show \"length rest < length (x # xs)\" using a2 p1 by (simp only:remove_member)\n  qed\nqed\n\nvalue \"selection_sort [2,4,10,0,0]\"\n\ntheorem selection_sort_permutation: \"mset (selection_sort(xs)) = mset xs\"\nproof(induct xs rule: selection_sort.induct)\n  case 1\n  then show \"mset (selection_sort []) = mset []\" by simp\nnext\n  case (2 x xs)\n  let ?minimum = \"Min (set (x # xs))\"\n  let ?rest = \"remove1 ?minimum (x # xs)\"\n  have IH: \"mset (selection_sort ?rest) = mset ?rest\" using \"2.hyps\" by simp\n  then show \"mset (selection_sort (x # xs)) = mset (x # xs)\"\n  proof(cases \"?minimum = x\")\n    case True\n    have \"mset (selection_sort (x # xs)) = mset(?minimum#selection_sort(?rest))\" using True by simp\n    also have \"... = {#?minimum#} + mset(selection_sort(?rest))\" by simp\n    also have \"... = {#?minimum#} + mset(?rest)\" using IH by simp\n    also have \"... = {#?minimum#} + mset(remove1 x (x # xs))\" using True by simp\n    also have \"... = {#?minimum#} + mset(xs)\" by simp\n    also have \"... = {#x#} + mset(xs)\" using True by simp\n    also have \"... = mset (x#xs)\" by simp\n    finally show \"mset (selection_sort (x # xs)) = mset (x # xs)\" by this\n  next\n    case False\n    have c1: \"mset (selection_sort (x # xs)) = mset(?minimum#selection_sort(?rest))\" by (metis \"selection-sort.selection_sort_Cons\")\n    also have c2:\"... = {#?minimum#} + mset(selection_sort(?rest))\" by simp\n    also have c3:\"... = {#?minimum#} + mset(?rest)\" using IH by simp\n    also have c4:\"... = {#?minimum#} + mset(x # xs) - {#?minimum#}\" by (metis List.finite_set Min_in diff_union_single_conv list.distinct(1) mset_remove1 set_empty set_mset_mset)\n    also have c5:\"... = mset (x # xs)\" by simp\n    finally show \"mset (selection_sort (x # xs)) = mset (x # xs)\" by this\n  qed\nqed                        \n\ntheorem selection_sort_order: \"sorted (selection_sort(xs))\"\nproof(induct xs rule:selection_sort.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 x xs)\n  let ?minimum = \"Min (set (x # xs))\"\n  let ?rest = \"remove1 ?minimum (x # xs)\"\n  show \"sorted (selection_sort (x # xs))\"\n  proof(simp only:selection_sort_Cons Let_def)\n    show \"sorted (?minimum # selection_sort (?rest))\"\n    proof (simp only:Let_def sorted.simps)\n      show \"Ball (set (selection_sort (?rest))) ((\\<le>) (?minimum)) \\<and> sorted (selection_sort (?rest))\"\n      proof (rule conjI)\n        have p1: \"mset(selection_sort(?rest)) = mset(x # xs) - {#?minimum#}\" \n        proof -\n          have c1:\"mset(selection_sort(?rest)) = mset(?rest)\"  using selection_sort_permutation by blast\n          also have c2:\"... = mset(x # xs) - {#?minimum#}\"  using c1 by simp\n          finally show \"mset(selection_sort(?rest)) = mset(x # xs) - {#?minimum#}\" by this\n        qed\n        show \"Ball (set (selection_sort (?rest))) ((\\<le>) (?minimum))\"  by (metis List.finite_set Min_le in_diffD p1 set_mset_mset)\n      next\n        have \"sorted (selection_sort (?rest))\" using \"2.hyps\" by simp\n        then show \"sorted (selection_sort (?rest))\" by assumption\n      qed\n    qed \n  qed\nqed\n\ntext \\<open>tail-recursive\\<close>\n\nlemma max_membership: \"m = Max(set (x#xs)) \\<Longrightarrow> m \\<in> set (x#xs)\"\nproof(induct xs arbitrary: x m)\n  case Nil  \n  have \"m = Max (set [x])\" using Nil.prems by simp\n  also have \"... \\<in> set [x]\" by simp\n  finally show \"m \\<in> set [x]\" by this\nnext\n  case (Cons a xs)\n   have \"m = Max (set (x # a # xs))\" using Cons.prems by simp\n   also have \"... \\<in> set (x # a # xs)\"  using Max_in by blast\n   finally show \"m \\<in> set (x # a # xs)\" by this\nqed\n\nfunction tr_selection_sort:: \"nat list \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n\"tr_selection_sort [] accum = accum\" |\n\"tr_selection_sort (x#xs) accum = (let max = Max (set(x#xs)); rest =remove1 max (x#xs) in tr_selection_sort(rest) (max#accum))\"\nby pat_completeness auto\ntermination\nproof(relation \"measure (\\<lambda>(xs, accum). size xs)\")\n  show \"wf (measure (\\<lambda>(xs, accum). length xs))\"  by simp\nnext\n  fix maximum x ::nat\n  fix rest xs accum:: \"nat list\"\n  assume a1: \"maximum =  Max (set (x # xs))\"\n  assume a2: \"rest = remove1 maximum (x # xs)\"\n  show \"((rest, maximum # accum), x # xs, accum) \\<in> measure (\\<lambda>(xs, accum). length xs)\"\n  proof (simp only: in_measure)\n    show \"(case (rest, maximum # accum) of (xs, accum) \\<Rightarrow> length xs) < (case (x # xs, accum) of (xs, accum) \\<Rightarrow> length xs)\" \n    proof(simp only: prod.case)\n      have p1: \"maximum \\<in> set (x#xs)\" using a1 by (simp only: max_membership)\n      show \"length rest < length (x # xs)\" using a2 p1 by (simp only:remove_member)\n    qed\n  qed\nqed\n\nvalue \"tr_selection_sort [2,4,10,0,0] []\"\n\ntheorem tr_selection_sort_output_sorted: \"\\<lbrakk>sorted (ACCUM);  \\<forall>A e. A \\<in> (set ACCUM) \\<and> e \\<in> set xs \\<and> e \\<le> A\\<rbrakk>\\<Longrightarrow> sorted (tr_selection_sort xs ACCUM)\"\nproof(induct xs arbitrary: ACCUM rule:tr_selection_sort.induct)\n  case (1 zs)\n  then show ?case  by (simp add: sorted01)\nnext\n  case (2 v va zs)\n  then show \"sorted (tr_selection_sort zs ACCUM)\"  by (simp add: sorted01)\nqed\n\ntheorem tr_selection_sort_is_permutation_of_input: \"\\<lbrakk>sorted (ACCUM); \\<forall>A e. A \\<in> (set ACCUM) \\<and> e \\<in> set xs \\<and> e \\<le> A\\<rbrakk>  \\<Longrightarrow> mset (tr_selection_sort xs ACCUM) = mset xs + mset ACCUM\"\nproof(induct xs arbitrary: ACCUM)\n  case Nil\n  show ?case by simp\nnext\n  case (Cons a xs)\n  show \"mset (tr_selection_sort (a # xs) ACCUM) = mset (a # xs) + mset ACCUM\"  using Cons.prems(2) by blast\nqed\n\n", "meta": {"author": "marco10507", "repo": "formalization-of-sorting-algorithms", "sha": "de905424e53d55829d54c2cd3c8f5241ac5ca904", "save_path": "github-repos/isabelle/marco10507-formalization-of-sorting-algorithms", "path": "github-repos/isabelle/marco10507-formalization-of-sorting-algorithms/formalization-of-sorting-algorithms-de905424e53d55829d54c2cd3c8f5241ac5ca904/selection-sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.8840392710530071, "lm_q1q2_score": 0.7616336106497256}}
{"text": "theory pascalsIdentity\n  imports Main \"HOL-Number_Theory.Number_Theory\" \nbegin\n\nfun comb :: \"nat ⇒ nat ⇒ real\" where\n  \"comb n k = (if n < k then 0 else fact n / (fact k * fact (n - k)))\"\n\ntheorem pascals_identity:\n  fixes n k :: nat\n  assumes \"n > 0 ∧ k > 0\"\n  shows \"comb n k = comb (n - 1) (k - 1) + comb (n - 1) k\" \nproof cases\n  {\n    assume nLessThank: \"n < k\"\n    then have lessThanRule: \"n - 1 < k - 1\" using assms by linarith\n    thus ?thesis by auto\n  }\nnext\n  {\n  assume nNotLessk:\"¬ n < k\"\n  hence \"n ≥ k\" by auto\n  show ?thesis  \n  proof cases\n    {\n      assume nEqualk: \"n = k\"\n      thus ?thesis using assms by auto\n    }\n  next\n    {\n      assume \"¬ n = k\"\n      hence nGreaterk: \"n > k\" using nNotLessk by auto\n\n      have \"comb n k = fact n / (fact k * fact (n - k))\"\n        by (simp add: nNotLessk)\n\n      also have \"fact n / (fact k * fact (n - k)) = fact(n - 1) * n  / (fact k * fact (n - k))\"\n        by (simp add: assms fact_reduce semiring_normalization_rules(7))\n\n      also have \"fact(n - 1) * n  / (fact k * fact (n - k)) = \n                 fact(n - 1) * ((n - k) / (fact k * fact (n - k)) + k / (fact k * fact (n - k)))\"\n        by (metis (no_types, hide_lams) ‹k ≤ n› add_divide_distrib le_add_diff_inverse2 of_nat_add of_nat_fact of_nat_mult times_divide_eq_right)\n\n      also have \"fact(n - 1) * ((n - k) / (fact k * fact (n - k)) + k / (fact k * fact (n - k))) =\n                    fact (n - 1) * (1 / (fact k * fact (n - k - 1)) + 1 / (fact (k - 1) * fact (n - k)))\"\n      proof -\n        have part1: \" (n - k) / (fact k * fact (n - k)) = (n - k) / fact (n - k) / fact k\" by auto\n        have part2: \"(n - k) / fact(n - k) = 1 / fact(n - k - 1)\"\n          by (metis ‹k ≤ n› ‹n ≠ k› diff_is_0_eq divide_divide_eq_left divide_self_if fact_reduce le_antisym nGreaterk of_nat_eq_0_iff zero_less_diff)\n        have part3: \"k / (fact k * fact (n - k)) =  1 / (fact (k - 1) * fact (n - k))\"\n          by (metis (no_types, lifting) assms divide_divide_eq_left divide_self_if fact_reduce neq0_conv of_nat_eq_0_iff)\n        show ?thesis using part1 part2 part3 by auto\n      qed\n      \n      also have \"fact (n - 1) * (1 / (fact k * fact (n - k - 1)) + 1 / (fact (k - 1) * fact (n - k))) = \n                       fact (n - 1) * 1 / (fact k * fact (n - k - 1)) + fact (n - 1) * 1 / (fact (k - 1) * fact (n - k))\"\n      proof -\n        show ?thesis sorry\n      qed\n\n      also have \"fact (n - 1) * 1 / (fact k * fact (n - k - 1)) + fact (n - 1) * 1 / (fact (k - 1) * fact (n - k)) =\n                fact (n - 1) / (fact k * fact (n - k - 1)) + fact (n - 1) / (fact (k - 1) * fact (n - k))\"\n        by auto\n\n      also have \"fact (n - 1) / (fact k * fact (n - k - 1)) + fact (n - 1) / (fact (k - 1) * fact (n - k)) =\n                 comb (n - 1) (k - 1) + comb (n - 1) k\"\n        using ‹n ≠ k› assms nNotLessk by auto\n\n      finally show ?thesis by auto\n    }\nqed\n}\nend\n", "meta": {"author": "s-nandi", "repo": "automated-proofs", "sha": "719103028f53ded647e34fa88fff0383b09865e9", "save_path": "github-repos/isabelle/s-nandi-automated-proofs", "path": "github-repos/isabelle/s-nandi-automated-proofs/automated-proofs-719103028f53ded647e34fa88fff0383b09865e9/pascalsIdentity.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9425067244294588, "lm_q2_score": 0.8080672089305841, "lm_q1q2_score": 0.76160877820802}}
{"text": "theory Demo\nimports \"$HIPSTER_HOME/IsaHipster\"\nbegin\n\n(* Normal list datatype *)\ndatatype 'a Lst = \n   Nil\n  | Cons \"'a\" \"'a Lst\" (infix \";\" 65)\n\n(* The append function. Syntactic sugar: we use +++ instead of Haskell's ++ *)\nfun app :: \"'a Lst \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\" (infix \"+++\" 60)\nwhere \n  \"Nil +++ xs = xs\"\n| \"(x;xs) +++ ys = x;(xs +++ ys)\"\n\n(* The reverse function *)\nfun rev :: \"'a Lst \\<Rightarrow> 'a Lst\"\nwhere \n  \"rev Nil = Nil\"\n| \"rev (x;xs) = (rev xs) +++ (x;Nil)\"\n\n(* Datatype for binary trees from your exercises *)\ndatatype 'a Tree = \n  Empty  \n  | Node \"'a\" \"'a Tree\" \"'a Tree\"\n\n(* The swap function: swaps the left and right subtree. *)\nfun swap :: \"'a Tree => 'a Tree\"\nwhere\n  \"swap Empty = Empty\"\n| \"swap (Node data l r) = Node data (swap r) (swap l)\"\n\n(* The flatten function: turn a tree into a list *)\nfun flatten :: \"'a Tree \\<Rightarrow> 'a Lst\"\nwhere\n  \"flatten Empty = Nil\"\n| \"flatten (Node data l r) =  ((flatten l) +++ (data;Nil)) +++ (flatten r)\"\n\nhipster app rev\nlemma lemma_a [thy_expl]: \"y +++ Lst.Nil = y\"\napply (induct y)\nby simp_all\n\nlemma lemma_aa [thy_expl]: \"(y +++ z) +++ x2 = y +++ (z +++ x2)\"\napply (induct y arbitrary: x2 z)\nby simp_all\n\nlemma lemma_ab [thy_expl]: \"Demo.rev z +++ Demo.rev y = Demo.rev (y +++ z)\"\napply (induct y arbitrary: z)\napply (simp_all add: Demo.lemma_a)\nby (metis lemma_aa)\n\nlemma lemma_ac [thy_expl]: \"Demo.rev (Demo.rev y) = y\"\napply (induct y)\napply simp_all\nby (metis Demo.rev.simps(1) Demo.rev.simps(2) Lst.distinct(1) app.elims app.simps(2) lemma_ab)\n\n\n\nhipster swap flatten\nlemma lemma_ad [thy_expl]: \"swap (swap y) = y\"\napply (induct y)\nby simp_all\n\n\n(* Last week's exercise 10 *)\ntheorem exercise10: \"flatten (swap p) = rev (flatten p)\"\n(*  apply hipster_induct *)\n  apply (induct p)\n  apply simp_all\n  by (metis Demo.rev.simps(1) Demo.rev.simps(2) lemma_a lemma_aa lemma_ab)\n\n(* Hard exercise (optional) *)\nfun qrev :: \"'a Lst \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\"\nwhere \n  \"qrev Nil acc  = acc\"\n| \"qrev (x;xs) acc = qrev xs (x;acc)\"\n\nhipster qrev rev\nlemma lemma_ae [thy_expl]: \"Demo.rev y +++ z = qrev y z\"\n  apply (induct y arbitrary: z)\n  apply simp_all\n  by (metis Demo.rev.simps(2) app.simps(1) lemma_aa lemma_ab lemma_ac)\n\ntheorem hardExercise: \"rev xs = qrev xs Nil\"\nsledgehammer\n  by (metis lemma_a lemma_ae)\n\n\n\n\n(* The spine function: turns a list into a tree. *)\nfun spine :: \"'a Lst \\<Rightarrow> 'a Tree\"\nwhere\n  \"spine Nil = Empty\"\n| \"spine (x;xs) = Node x Empty (spine xs)\"\n\nhipster spine flatten\nlemma lemma_af [thy_expl]: \"flatten (spine y) = y\"\n  apply (induct y)\n  by simp_all\n\n(* Example: Histering a buggy rot function *)\nfun rot :: \"nat \\<Rightarrow> 'a Lst \\<Rightarrow> 'a Lst\"\n  where\n    \"rot 0 xs = xs\"\n  | \"rot (Suc n) Nil = Nil\"\n  | \"rot (Suc n) (x;xs) = rot n (xs+++(Cons x Nil))\" \n (* | \"rot (Suc n) (x;xs) = rot n xs+++(Cons x Nil)\" <--- This is the buggy version*)\n    \nfun len :: \"'a Lst \\<Rightarrow> nat\"  \n  where\n    \"len Nil = 0\"\n  | \"len (x;xs) = Suc(len xs)\"\n\n  \nhipster rot len \n\n(* Properties discovered  for the buggy definition of rot. Note the first one, indicates that\n  rotating around the length is reversing! \n\nlemma lemma_ag [thy_expl]: \"rot (len y) y = Demo.rev y\"\napply (induct y)\napply simp\napply simp\ndone\n\nlemma lemma_ah [thy_expl]: \"rot (Suc (len y)) y = Demo.rev y\"\napply (induct y)\napply simp\napply simp\ndone\n\nlemma lemma_ai [thy_expl]: \"rot (len z) (z +++ y) = y +++ Demo.rev z\"\napply (induct z arbitrary: y)\napply simp\napply (simp add: lemma_a)\napply simp\nusing lemma_aa apply blast\ndone\n\nlemma lemma_aj [thy_expl]: \"rot (len (z +++ y)) z = Demo.rev z\"\napply (induct z arbitrary: y)\napply simp\napply (metis rot.elims rot.simps(2))\napply simp\ndone\n\n*)\n\nend", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/Examples/Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129514, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7615580305349736}}
{"text": "section \\<open>Specification\\<close>\n\ntheory Goodstein_Lambda\n  imports Main \"Eval_Base.Eval_Base\" \nbegin\n\nsubsection \\<open>Hereditary base representation\\<close>\n\ntext \\<open>We define a data type of trees and an evaluation function that sums siblings and\n  exponentiates with respect to the given base on nesting.\\<close>\n\ndatatype C = C (unC: \"C list\")\n\nfun evalC where\n  \"evalC b (C []) = 0\"\n| \"evalC b (C (x # xs)) = b^evalC b x + evalC b (C xs)\"\n\nvalue \"evalC 2 (C [])\" \\<comment> \\<open>$0$\\<close>\nvalue \"evalC 2 (C [C []])\" \\<comment> \\<open>$2^0 = 1$\\<close>\nvalue \"evalC 2 (C [C [C []]])\" \\<comment> \\<open>$2^1 = 2$\\<close>\nvalue \"evalC 2 (C [C [], C []])\" \\<comment> \\<open>$2^0 + 2^0 = 2^0 \\cdot 2 = 2$; not in hereditary base $2$\\<close>\n\ntext \\<open>The hereditary base representation is characterized as trees (i.e., nested lists) whose\n  lists have monotonically increasing evaluations, with fewer than @{term \"b\"} repetitions for\n  each value. We will show later that this representation is unique.\\<close>\n\ninductive_set hbase for b where\n  \"C [] \\<in> hbase b\"\n| \"i \\<noteq> 0 \\<Longrightarrow> i < b \\<Longrightarrow> n \\<in> hbase b \\<Longrightarrow>\n   C ms \\<in> hbase b \\<Longrightarrow> (\\<And>m'. m' \\<in> set ms \\<Longrightarrow> evalC b n < evalC b m') \\<Longrightarrow>\n   C (replicate i n @ ms) \\<in> hbase b\"\n\ntext \\<open>We can convert to and from natural numbers as follows.\\<close>\n\ndefinition H2N where\n  \"H2N b n = evalC b n\"\n\ntext \\<open>As we will show later, @{term \"H2N b\"} restricted to @{term \"hbase n\"} is bijective\n  if @{prop \"b \\<ge> (2 :: nat)\"}, so we can convert from natural numbers by taking the inverse.\\<close>\n\ndefinition N2H where\n  \"N2H b n = inv_into (hbase b) (H2N b) n\"\n\nsubsection \\<open>The Goodstein function\\<close>\n\ntext \\<open>We define a function that computes the length of the Goodstein sequence whose $c$-th element\n  is $g_c = n$. Termination will be shown later, thereby establishing Goodstein's theorem.\\<close>\n\nfunction (sequential) goodstein :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"goodstein 0 n = 0\"\n  \\<comment> \\<open>we start counting at 1; also note that the initial base is @{term \"c+1 :: nat\"} and\\<close>\n  \\<comment> \\<open>hereditary base 1 makes no sense, so we have to avoid this case\\<close>\n| \"goodstein c 0 = c\"\n| \"goodstein c n = goodstein (c+1) (H2N (c+2) (N2H (c+1) n) - 1)\"\n  by pat_completeness auto\n\nabbreviation \\<G> where\n  \"\\<G> n \\<equiv> goodstein (Suc 0) n\"\n\nsection \\<open>Ordinals\\<close>\n\ntext \\<open>The following type contains countable ordinals, by the usual case distinction into 0,\n  successor ordinal, or limit ordinal; limit ordinals are given by their fundamental sequence.\n  Hereditary base @{term \"b\"} representations carry over to such ordinals by replacing each\n  occurrence of the base by @{term \"\\<omega>\"}.\\<close>\n\ndatatype Ord = Z | S Ord | L \"nat \\<Rightarrow> Ord\"\n\ntext \\<open>Note that the following arithmetic operations are not correct for all ordinals. However, they\n  will only be used in cases where they actually correspond to the ordinal arithmetic operations.\\<close>\n\nprimrec addO where\n  \"addO n Z = n\"\n| \"addO n (S m) = S (addO n m)\"\n| \"addO n (L f) = L (\\<lambda>i. addO n (f i))\"\n\nprimrec mulO where\n  \"mulO n Z = Z\"\n| \"mulO n (S m) = addO (mulO n m) n\"\n| \"mulO n (L f) = L (\\<lambda>i. mulO n (f i))\"\n\ndefinition \\<omega> where\n  \"\\<omega> = L (\\<lambda>n. (S ^^ n) Z)\"\n\nprimrec exp\\<omega> where\n  \"exp\\<omega> Z = S Z\"\n| \"exp\\<omega> (S n) = mulO (exp\\<omega> n) \\<omega>\"\n| \"exp\\<omega> (L f) = L (\\<lambda>i. exp\\<omega> (f i))\"\n\nsubsection \\<open>Evaluation\\<close>\n\ntext \\<open>Evaluating an ordinal number at base $b$ is accomplished by taking the $b$-th element of\n  all fundamental sequences and interpreting zero and successor over the natural numbers.\\<close>\n\nprimrec evalO where\n  \"evalO b Z = 0\"\n| \"evalO b (S n) = Suc (evalO b n)\"\n| \"evalO b (L f) = evalO b (f b)\"\n\nsubsection \\<open>Goodstein function and sequence\\<close>\n\ntext \\<open>We can define the Goodstein function very easily, but proving correctness will take a while.\\<close>\n\nprimrec goodsteinO where\n  \"goodsteinO c Z = c\"\n| \"goodsteinO c (S n) = goodsteinO (c+1) n\"\n| \"goodsteinO c (L f) = goodsteinO c (f (c+2))\"\n\nprimrec stepO where\n  \"stepO c Z = Z\"\n| \"stepO c (S n) = n\"\n| \"stepO c (L f) = stepO c (f (c+2))\"\n\ntext \\<open>We can compute a few values of the Goodstein sequence starting at $4$.\\<close>\n\ndefinition g4O where\n  \"g4O n = fold stepO [1..<Suc n] ((exp\\<omega> ^^ 3) Z)\"\n\nvalue \"map (\\<lambda>n. evalO (n+2) (g4O n)) [0..<10]\"\n\\<comment> \\<open>@{value \"[4, 26, 41, 60, 83, 109, 139, 173, 211, 253] :: nat list\"}\\<close>\n\nsubsection \\<open>Properties of evaluation\\<close>\n\nlemma evalO_addO [simp]:\n  \"evalO b (addO n m) = evalO b n + evalO b m\"\n  apply2 (induct m) by auto\n\nlemma evalO_mulO [simp]:\n  \"evalO b (mulO n m) = evalO b n * evalO b m\"\n  apply2 (induct m) by auto\n\nlemma evalO_n [simp]:\n  \"evalO b ((S ^^ n) Z) = n\"\n  apply2 (induct n) by auto\n\nlemma evalO_\\<omega> [simp]:\n  \"evalO b \\<omega> = b\"\n  by (auto simp: \\<omega>_def)\n\nlemma evalO_exp\\<omega> [simp]:\n  \"evalO b (exp\\<omega> n) = b^(evalO b n)\"\n  apply2 (induct n) by auto\n\ntext \\<open>Note that evaluation is useful for proving that @{type \"Ord\"} values are distinct:\\<close>\nnotepad begin\n  have \"addO n (exp\\<omega> m) \\<noteq> n\" for n m by (auto dest: arg_cong[of _ _ \"evalO 1\"])\nend\n\nsubsection \\<open>Arithmetic properties\\<close>\n\nlemma addO_Z [simp]:\n  \"addO Z n = n\"\n  apply2 (induct n) by auto\n\nlemma addO_assoc [simp]:\n  \"addO n (addO m p) = addO (addO n m) p\"\n  apply2 (induct p) by auto\n\nlemma mul0_distrib [simp]:\n  \"mulO n (addO p q) = addO (mulO n p) (mulO n q)\"\n  apply2 (induct q) by auto\n\nlemma mulO_assoc [simp]:\n  \"mulO n (mulO m p) = mulO (mulO n m) p\"\n  apply2 (induct p) by auto\n\n\n\n\nsection \\<open>Cantor normal form\\<close>\n\ntext \\<open>The previously introduced tree type @{type C} can be used to represent Cantor normal forms;\n  they are trees (evaluated at base @{term \\<omega>}) such that siblings are in non-decreasing order.\n  One can think of this as hereditary base @{term \\<omega>}. The plan is to mirror selected operations on\n  ordinals in Cantor normal forms.\\<close>\n\nsubsection \\<open>Conversion to and from the ordinal type @{type Ord}\\<close>\n\nfun C2O where\n  \"C2O (C []) = Z\"\n| \"C2O (C (n # ns)) = addO (C2O (C ns)) (exp\\<omega> (C2O n))\"\n\ndefinition O2C where\n  \"O2C = inv C2O\"\n\ntext \\<open>We show that @{term C2O} is injective, meaning the inverse is unique.\\<close>\n\nlemma addO_exp\\<omega>_inj:\n  assumes \"addO n (exp\\<omega> m) = addO n' (exp\\<omega> m')\"\n  shows \"n = n'\" and \"m = m'\"\nproof -\n  have \"addO n (exp\\<omega> m) = addO n' (exp\\<omega> m') \\<Longrightarrow> n = n'\"\n    apply2 (induct m arbitrary: m') by(case_tac m';\n      force simp: \\<omega>_def dest!: fun_cong[of _ _ 1])+\n  moreover have \"addO n (exp\\<omega> m) = addO n (exp\\<omega> m') \\<Longrightarrow> m = m'\"\n    apply2 (induct m arbitrary: n m'; case_tac m')\n    apply (auto 0 3 simp: \\<omega>_def intro: rangeI\n      dest: arg_cong[of _ _ \"evalO 1\"] fun_cong[of _ _ 0] fun_cong[of _ _ 1])[8] (* 1 left *)\n    by simp (meson ext rangeI)\n  ultimately show \"n = n'\" and \"m = m'\" using assms by simp_all\nqed\n\nlemma C2O_inj:\n  \"C2O n = C2O m \\<Longrightarrow> n = m\"\n  apply2 (induct n arbitrary: m rule: C2O.induct; case_tac m rule: C2O.cases)\n    by (auto dest: addO_exp\\<omega>_inj arg_cong[of _ _ \"evalO 1\"])\n\nlemma O2C_C2O [simp]:\n  \"O2C (C2O n) = n\"\n  by (auto intro!: inv_f_f simp: O2C_def inj_def C2O_inj)\n\nlemma O2C_Z [simp]:\n  \"O2C Z = C []\"\n  using O2C_C2O[of \"C []\", unfolded C2O.simps] .\n\nlemma C2O_replicate:\n  \"C2O (C (replicate i n)) = mulO (exp\\<omega> (C2O n)) ((S ^^ i) Z)\"\n  apply2 (induct i) by auto\n\nlemma C2O_app:\n  \"C2O (C (xs @ ys)) = addO (C2O (C ys)) (C2O (C xs))\"\n  apply2 (induct xs arbitrary: ys) by auto\n\nsubsection \\<open>Evaluation\\<close>\n\nlemma evalC_def':\n  \"evalC b n = evalO b (C2O n)\"\n  apply2 (induct n rule: C2O.induct) by auto\n\nlemma evalC_app [simp]:\n  \"evalC b (C (ns @ ms)) = evalC b (C ns) + evalC b (C ms)\"\n  apply2 (induct ns) by auto\n\nlemma evalC_replicate [simp]:\n  \"evalC b (C (replicate c n)) = c * evalC b (C [n])\"\n  apply2 (induct c) by auto\n\nsubsection \\<open>Transfer of the @{type Ord} induction principle to @{type C}\\<close>\n\nfun funC where \\<comment> \\<open>@{term funC} computes the fundamental sequence on @{type C}\\<close>\n  \"funC (C []) = (\\<lambda>i. [C []])\"\n| \"funC (C (C [] # ns)) = (\\<lambda>i. replicate i (C ns))\"\n| \"funC (C (n # ns)) = (\\<lambda>i. [C (funC n i @ ns)])\"\n\nlemma C2O_cons:\n  \"C2O (C (n # ns)) =\n    (if n = C [] then S (C2O (C ns)) else L (\\<lambda>i. C2O (C (funC n i @ ns))))\"\n  apply2 (induct n arbitrary: ns rule: funC.induct)\n  by (simp_all add: \\<omega>_def C2O_replicate C2O_app flip: exp\\<omega>_addO)\n\nlemma C_Ord_induct:\n  assumes \"P (C [])\"\n  and \"\\<And>ns. P (C ns) \\<Longrightarrow> P (C (C [] # ns))\"\n  and \"\\<And>n ns ms. (\\<And>i. P (C (funC (C (n # ns)) i @ ms))) \\<Longrightarrow>\n    P (C (C (n # ns) # ms))\"\n  shows \"P n\"\nproof -\n  have \"\\<forall>n. C2O n = m \\<longrightarrow> P n\" for m\n    apply2 (induct m; intro allI; case_tac n rule: funC.cases)\n  by (auto simp: C2O_cons simp del: C2O.simps(2) intro: assms)\n  then show ?thesis by simp\nqed\n\nsubsection \\<open>Goodstein function and sequence on @{type C}\\<close>\n\nfunction (domintros) goodsteinC where\n  \"goodsteinC c (C []) = c\"\n| \"goodsteinC c (C (C [] # ns)) = goodsteinC (c+1) (C ns)\"\n| \"goodsteinC c (C (C (n # ns) # ms)) =\n    goodsteinC c (C (funC (C (n # ns)) (c+2) @ ms))\"\n  by pat_completeness auto\n\ntermination\nproof -\n  have \"goodsteinC_dom (c, n)\" for c n\n    apply2 (induct n arbitrary: c rule: C_Ord_induct) by(auto intro: goodsteinC.domintros)\n  then show ?thesis by simp\nqed\n\nlemma goodsteinC_def':\n  \"goodsteinC c n = goodsteinO c (C2O n)\"\n  apply2 (induct c n rule: goodsteinC.induct) by(simp_all add: C2O_cons del: C2O.simps(2))\n\nfunction (domintros) stepC where\n  \"stepC c (C []) = C []\"\n| \"stepC c (C (C [] # ns)) = C ns\"\n| \"stepC c (C (C (n # ns) # ms)) =\n    stepC c (C (funC (C (n # ns)) (Suc (Suc c)) @ ms))\"\n  by pat_completeness auto\n\ntermination\nproof -\n  have \"stepC_dom (c, n)\" for c n\n    apply2 (induct n arbitrary: c rule: C_Ord_induct) by(auto intro: stepC.domintros)\n  then show ?thesis by simp\nqed\n\ndefinition g4C where\n  \"g4C n = fold stepC [1..<Suc n] (C [C [C [C []]]])\"\n\nvalue \"map (\\<lambda>n. evalC (n+2) (g4C n)) [0..<10]\"\n\\<comment> \\<open>@{value \"[4, 26, 41, 60, 83, 109, 139, 173, 211, 253] :: nat list\"}\\<close>\n\nsubsection \\<open>Properties\\<close>\n\nlemma stepC_def':\n  \"stepC c n = O2C (stepO c (C2O n))\"\n  apply2 (induct c n rule: stepC.induct) by(simp_all add: C2O_cons del: C2O.simps(2))\n\nlemma funC_ne [simp]:\n  \"funC m (Suc n) \\<noteq> []\"\n  by (cases m rule: funC.cases) simp_all\n\nlemma evalC_funC [simp]:\n  \"evalC b (C (funC n b)) = evalC b (C [n])\"\n  apply2 (induct n rule: funC.induct) by simp_all\n\nlemma stepC_app [simp]:\n  \"n \\<noteq> C [] \\<Longrightarrow> stepC c (C (unC n @ ns)) = C (unC (stepC c n) @ ns)\"\n  apply2 (induct n arbitrary: ns rule: stepC.induct) by simp_all\n\nlemma stepC_cons [simp]:\n  \"ns \\<noteq> [] \\<Longrightarrow> stepC c (C (n # ns)) = C (unC (stepC c (C [n])) @ ns)\"\n  using stepC_app[of \"C[n]\" c ns] by simp\n\nlemma stepC_dec:\n  \"n \\<noteq> C [] \\<Longrightarrow> Suc (evalC (Suc (Suc c)) (stepC c n)) = evalC (Suc (Suc c)) n\"\n  apply2 (induct c n rule: stepC.induct) by simp_all\n\nlemma stepC_dec':\n  \"n \\<noteq> C [] \\<Longrightarrow> evalC (c+3) (stepC c n) < evalC (c+3) n\"\nproof2 (induct c n rule: stepC.induct)\n  case (3 c n ns ms)\n  have \"evalC (c+3) (C (funC (C (n # ns)) (Suc (Suc c)))) \\<le>\n      (c+3) ^ ((c+3) ^ evalC (c+3) n + evalC (c+3) (C ns))\"\n    apply2 (induct n rule: funC.induct) by(simp_all add: distrib_right)\n  then show ?case using 3 by simp\nqed simp_all\n\n\nsection \\<open>Hereditary base @{term b} representation\\<close>\n\ntext \\<open>We now turn to properties of the @{term \"hbase b\"} subset of trees.\\<close>\n\nsubsection \\<open>Uniqueness\\<close>\n\ntext \\<open>We show uniqueness of the hereditary base representation by showing that @{term \"evalC b\"}\n  restricted to @{term \"hbase b\"} is injective.\\<close>\n\nlemma hbaseI2:\n  \"i < b \\<Longrightarrow> n \\<in> hbase b \\<Longrightarrow> C m \\<in> hbase b \\<Longrightarrow>\n    (\\<And>m'. m' \\<in> set m \\<Longrightarrow> evalC b n < evalC b m') \\<Longrightarrow>\n    C (replicate i n @ m) \\<in> hbase b\"\n  by (cases i) (auto intro: hbase.intros simp del: replicate.simps(2))\n\nlemmas hbase_singletonI =\n  hbase.intros(2)[of 1 \"Suc (Suc b)\" for b, OF _ _ _ hbase.intros(1), simplified]\n\nlemma hbase_hd:\n  \"C ns \\<in> hbase b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> hd ns \\<in> hbase b\"\n  by (cases rule: hbase.cases) auto\n\nlemmas hbase_hd' [dest] = hbase_hd[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_tl:\n  \"C ns \\<in> hbase b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> C (tl ns) \\<in> hbase b\"\n  by (cases \"C ns\" b rule: hbase.cases) (auto intro: hbaseI2)\n\nlemmas hbase_tl' [dest] = hbase_tl[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_elt [dest]:\n  \"C ns \\<in> hbase b \\<Longrightarrow> n \\<in> set ns \\<Longrightarrow> n \\<in> hbase b\"\n  apply2 (induct ns) by auto\n\nlemma evalC_sum_list:\n  \"evalC b (C ns) = sum_list (map (\\<lambda>n. b^evalC b n) ns)\"\n  apply2 (induct ns) by auto\n\nlemma sum_list_replicate:\n  \"sum_list (replicate n x) = n * x\"\n  apply2 (induct n) by auto\n\nlemma base_red:\n  fixes b :: nat\n  assumes n: \"\\<And>n'. n' \\<in> set ns \\<Longrightarrow> n < n'\" \"i < b\" \"i \\<noteq> 0\"\n  and m: \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> m < m'\" \"j < b\" \"j \\<noteq> 0\"\n  and s: \"i * b^n + sum_list (map (\\<lambda>n. b^n) ns) = j * b^m + sum_list (map (\\<lambda>n. b^n) ms)\"\n  shows \"i = j \\<and> n = m\"\n  using n(1) m(1) s\nproof2 (induct n arbitrary: m ns ms)\n  { fix ns ms :: \"nat list\" and i j m :: nat\n    assume n': \"\\<And>n'. n' \\<in> set ns \\<Longrightarrow> 0 < n'\" \"i < b\" \"i \\<noteq> 0\"\n    assume m': \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> m < m'\" \"j < b\" \"j \\<noteq> 0\"\n    assume s': \"i * b^0 + sum_list (map (\\<lambda>n. b^n) ns) = j * b^m + sum_list (map (\\<lambda>n. b^n) ms)\"\n    obtain x where [simp]: \"sum_list (map ((^) b) ns) = x*b\"\n      using n'(1)\n      by (intro that[of \"sum_list (map (\\<lambda>n. b^(n-1)) ns)\"])\n        (simp add: ac_simps flip: sum_list_const_mult power_Suc cong: map_cong)\n    obtain y where [simp]: \"sum_list (map ((^) b) ms) = y*b\"\n      using order.strict_trans1[OF le0 m'(1)]\n      by (intro that[of \"sum_list (map (\\<lambda>n. b^(n-1)) ms)\"])\n        (simp add: ac_simps flip: sum_list_const_mult power_Suc cong: map_cong)\n    have [simp]: \"m = 0\"\n      using s' n'(2,3)\n      by (cases m, simp_all)\n        (metis Groups.mult_ac(2) Groups.mult_ac(3) Suc_pred div_less mod_div_mult_eq\n          mod_mult_self2 mod_mult_self2_is_0 mult_zero_right nat.simps(3))\n    have \"i = j \\<and> 0 = m\" using s' n'(2,3) m'(2,3)\n      by simp (metis div_less mod_div_mult_eq mod_mult_self1)\n  } note BASE = this\n  {\n    case 0 show ?case by (rule BASE; fact)\n  next\n    case (Suc n m')\n    have \"j = i \\<and> 0 = Suc n\" if \"m' = 0\" using Suc(2-4)\n      by (intro BASE[of ms j ns \"Suc n\" i]) (simp_all add: ac_simps that n(2,3) m(2,3))\n    then obtain m where m' [simp]: \"m' = Suc m\"\n      by (cases m') auto\n    obtain ns' where [simp]: \"ns = map Suc ns'\" \"\\<And>n'. n' \\<in> set ns' \\<Longrightarrow> n < n'\"\n      using Suc(2) less_trans[OF zero_less_Suc Suc(2)]\n      by (intro that[of \"map (\\<lambda>n. n-1) ns\"]; force cong: map_cong)\n    obtain ms' where [simp]: \"ms = map Suc ms'\" \"\\<And>m'. m' \\<in> set ms' \\<Longrightarrow> m < m'\"\n      using Suc(3)[unfolded m'] less_trans[OF zero_less_Suc Suc(3)[unfolded m']]\n      by (intro that[of \"map (\\<lambda>n. n-1) ms\"]; force cong: map_cong)\n    have *: \"b * x = b * y \\<Longrightarrow> x = y\" for x y using n(2) by simp\n    have \"i = j \\<and> n = m\"\n    proof (rule Suc(1)[of \"map (\\<lambda>n. n-1) ns\" \"map (\\<lambda>n. n-1) ms\" m, OF _ _ *], goal_cases)\n      case 3 show ?case using Suc(4) unfolding add_mult_distrib2\n        by (simp add: comp_def ac_simps flip: sum_list_const_mult)\n    qed simp_all\n    then show ?case by simp\n  }\nqed\n\nlemma evalC_inj_on_hbase:\n  \"n \\<in> hbase b \\<Longrightarrow> m \\<in> hbase b \\<Longrightarrow> evalC b n = evalC b m \\<Longrightarrow> n = m\"\nproof2 (induct n arbitrary: m rule: hbase.induct)\n  case 1\n  then show ?case by (cases m rule: hbase.cases) simp_all\nnext\n  case (2 i n ns m')\n  obtain j m ms where [simp]: \"m' = C (replicate j m @ ms)\" and\n    m: \"j \\<noteq> 0\" \"j < b\" \"m \\<in> hbase b\" \"C ms \\<in> hbase b\" \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> evalC b m < evalC b m'\"\n    using 2(8,1,2,9) by (cases m' rule: hbase.cases) simp_all\n  have \"i = j \\<and> evalC b n = evalC b m\" using 2(1,2,7,9) m(1,2,5)\n    by (intro base_red[of \"map (evalC b) ns\" _ _ b \"map (evalC b) ms\"])\n      (auto simp: comp_def evalC_sum_list sum_list_replicate)\n  then show ?case\n    using 2(4)[OF m(3)] 2(6)[OF m(4)] 2(9) by simp\nqed\n\nsubsection \\<open>Correctness of @{const stepC}\\<close>\n\ntext \\<open>We show that @{term \"stepC c\"} preserves hereditary base @{term \"c + 2 :: nat\"}\n  representations. In order to cover intermediate results produced by @{const stepC}, we extend\n  the hereditary base representation to allow the least significant digit to be equal to @{term b},\n  which essentially means that we may have an extra sibling in front on every level.\\<close>\n\ninductive_set hbase_ext for b where\n  \"n \\<in> hbase b \\<Longrightarrow> n \\<in> hbase_ext b\"\n| \"n \\<in> hbase_ext b \\<Longrightarrow>\n   C m \\<in> hbase b \\<Longrightarrow> (\\<And>m'. m' \\<in> set m \\<Longrightarrow> evalC b n \\<le> evalC b m') \\<Longrightarrow>\n   C (n # m) \\<in> hbase_ext b\"\n\nlemma hbase_ext_hd' [dest]:\n  \"C (n # ns) \\<in> hbase_ext b \\<Longrightarrow> n \\<in> hbase_ext b\"\n  by (cases rule: hbase_ext.cases) (auto intro: hbase_ext.intros(1))\n\nlemma hbase_ext_tl:\n  \"C ns \\<in> hbase_ext b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> C (tl ns) \\<in> hbase b\"\n  by (cases \"C ns\" b rule: hbase_ext.cases; cases ns) (simp_all add: hbase_tl')\n\nlemmas hbase_ext_tl' [dest] = hbase_ext_tl[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_funC:\n  \"c \\<noteq> 0 \\<Longrightarrow> C (n # ns) \\<in> hbase_ext (Suc c) \\<Longrightarrow>\n    C (funC n (Suc c) @ ns) \\<in> hbase_ext (Suc c)\"\nproof2 (induct n arbitrary: ns rule: funC.induct)\n  case (2 ms)\n  have [simp]: \"evalC (Suc c) (C ms) < evalC (Suc c) m'\" if \"m' \\<in> set ns\" for m'\n    using 2(2)\n  proof (cases rule: hbase_ext.cases)\n    case 1 then show ?thesis using that\n      by (cases rule: hbase.cases, case_tac i) (auto intro: Suc_lessD)\n  qed (auto simp: Suc_le_eq that)\n  show ?case using 2\n    by (auto 0 4 intro: hbase_ext.intros hbase.intros(2) order.strict_implies_order)\nnext\n  case (3 m ms ms')\n  show ?case\n    unfolding funC.simps append_Cons append_Nil\n  proof (rule hbase_ext.intros(2), goal_cases 31 32 33)\n    case (33 m')\n    show ?case using 3(3)\n    proof (cases rule: hbase_ext.cases)\n      case 1 show ?thesis using 1 3(1,2) 33\n        by (cases rule: hbase.cases, case_tac i) (auto intro: less_or_eq_imp_le)\n    qed (insert 33, simp)\n  qed (insert 3, blast+)\nqed auto\n\nlemma stepC_sound:\n  \"n \\<in> hbase_ext (Suc (Suc c)) \\<Longrightarrow> stepC c n \\<in> hbase (Suc (Suc c))\"\nproof2 (induct c n rule: stepC.induct)\n  case (3 c n ns ms)\n  show ?case using 3(2,1)\n    by (cases rule: hbase_ext.cases; unfold stepC.simps) (auto intro: hbase_funC)\nqed (auto intro: hbase.intros)\n\nsubsection \\<open>Surjectivity of @{const evalC}\\<close>\n\ntext \\<open>Note that the base must be at least @{term \"2 :: nat\"}.\\<close>\n\nlemma evalC_surjective:\n  \"\\<exists>n' \\<in> hbase (Suc (Suc b)). evalC (Suc (Suc b)) n' = n\"\nproof2 (induct n)\n  case 0 then show ?case by (auto intro: bexI[of _ \"C []\"] hbase.intros)\nnext\n  have [simp]: \"Suc x \\<le> Suc (Suc b)^x\" for x apply2 (induct x) by auto\n  case (Suc n)\n  then guess n' by (rule bexE)\n  then obtain n' j where n': \"Suc n \\<le> j\" \"j = evalC (Suc (Suc b)) n'\" \"n' \\<in> hbase (Suc (Suc b))\"\n    by (intro that[of _ \"C [n']\"])\n      (auto intro!: intro: hbase.intros(1) dest!: hbaseI2[of 1 \"b+2\" n' \"[]\", simplified])\n  then show ?case\n  proof2 (induct rule: inc_induct)\n    case (step m)\n    guess n' using step(3)[OF step(4,5)] by (rule bexE)\n    then show ?case using stepC_dec[of n' \"b\"]\n      by (cases n' rule: C2O.cases) (auto intro: stepC_sound hbase_ext.intros(1))\n  qed blast\nqed\n\nsubsection \\<open>Monotonicity of @{const hbase}\\<close>\n\ntext \\<open>Here we show that every hereditary base @{term \"b :: nat\"} number is also a valid hereditary\n  base @{term \"b+1 :: nat\"} number. This is not immediate because we have to show that monotonicity\n  of siblings is preserved.\\<close>\n\nlemma hbase_evalC_mono:\n  assumes \"n \\<in> hbase b\" \"m \\<in> hbase b\" \"evalC b n < evalC b m\"\n  shows \"evalC (Suc b) n < evalC (Suc b) m\"\nproof (cases \"b < 2\")\n  case True show ?thesis using assms(2,3) True by (cases rule: hbase.cases) simp_all\nnext\n  case False\n  then obtain b' where [simp]: \"b = Suc (Suc b')\"\n    by (auto simp: numeral_2_eq_2 not_less_eq dest: less_imp_Suc_add)\n  show ?thesis using assms(3,1,2)\n  proof2 (induct \"evalC b n\" \"evalC b m\" arbitrary: n m rule: less_Suc_induct)\n    case 1 then show ?case using stepC_sound[of m b', OF hbase_ext.intros(1)]\n      stepC_dec[of m b'] stepC_dec'[of m b'] evalC_inj_on_hbase\n      by (cases m rule: C2O.cases) (fastforce simp: eval_nat_numeral)+\n  next\n    case (2 j) then show ?case\n      using evalC_surjective[of b' j] less_trans by fastforce\n  qed\nqed\n\nlemma hbase_mono:\n  \"n \\<in> hbase b \\<Longrightarrow> n \\<in> hbase (Suc b)\"\n  apply2 (induct n rule: hbase.induct) by(auto 0 3 intro: hbase.intros hbase_evalC_mono)\n\nsubsection \\<open>Conversion to and from @{type nat}\\<close>\n\ntext \\<open>We have previously defined @{term \"H2N b = evalC b\"} and @{term \"N2H b\"} as its inverse.\n  So we can use the injectivity and surjectivity of @{term \"evalC b\"} for simplification.\\<close>\n\nlemma N2H_inv:\n  \"n \\<in> hbase b \\<Longrightarrow> N2H b (H2N b n) = n\"\n  using evalC_inj_on_hbase\n  by (auto simp: N2H_def H2N_def[abs_def] inj_on_def intro!: inv_into_f_f)\n\n\n\nlemma N2H_eqI:\n  \"n \\<in> hbase (Suc (Suc b)) \\<Longrightarrow>\n   H2N (Suc (Suc b)) n = m \\<Longrightarrow> N2H (Suc (Suc b)) m = n\"\n  using N2H_inv by blast\n\nlemma N2H_neI:\n  \"n \\<in> hbase (Suc (Suc b)) \\<Longrightarrow>\n   H2N (Suc (Suc b)) n \\<noteq> m \\<Longrightarrow> N2H (Suc (Suc b)) m \\<noteq> n\"\n  using H2N_inv by blast\n\nlemma N2H_0 [simp]:\n  \"N2H (Suc (Suc c)) 0 = C []\"\n  using H2N_def N2H_inv hbase.intros(1) by fastforce\n\nlemma N2H_nz [simp]:\n  \"0 < n \\<Longrightarrow> N2H (Suc (Suc c)) n \\<noteq> C []\"\n  by (metis N2H_0 H2N_inv neq0_conv)\n\n\nsection \\<open>The Goodstein function revisited\\<close>\n\ntext \\<open>We are now ready to prove termination of the Goodstein function @{const goodstein} as well\n  as its relation to @{const goodsteinC} and @{const goodsteinO}.\\<close>\n\nlemma goodstein_aux:\n  \"goodsteinC (Suc c) (N2H (Suc (Suc c)) (Suc n)) =\n    goodsteinC (c+2) (N2H (c+3) (H2N (c+3) (N2H (c+2) (n+1)) - 1))\"\nproof -\n  have [simp]: \"n \\<noteq> C [] \\<Longrightarrow> goodsteinC c n = goodsteinC (c+1) (stepC c n)\" for c n\n    apply2 (induct c n rule: stepC.induct) by simp_all\n  have [simp]: \"stepC (Suc c) (N2H (Suc (Suc c)) (Suc n)) \\<in> hbase (Suc (Suc (Suc c)))\"\n    by (metis H2N_def N2H_inv evalC_surjective hbase_ext.intros(1) hbase_mono stepC_sound)\n  show ?thesis\n    using arg_cong[OF stepC_dec[of \"N2H (c+2) (n+1)\" \"c+1\", folded H2N_def], of \"\\<lambda>n. N2H (c+3) (n-1)\"]\n    by (simp add: eval_nat_numeral N2H_inv)\nqed\n\ntermination goodstein\nproof (relation \"measure (\\<lambda>(c, n). goodsteinC c (N2H (c+1) n) - c)\", goal_cases _ 1)\n  case (1 c n)\n  have *: \"goodsteinC c n \\<ge> c\" for c n\n    apply2 (induct c n rule: goodsteinC.induct) by simp_all\n  show ?case by (simp add: goodstein_aux eval_nat_numeral) (meson Suc_le_eq diff_less_mono2 lessI *)\nqed simp\n\nlemma goodstein_def':\n  \"c \\<noteq> 0 \\<Longrightarrow> goodstein c n = goodsteinC c (N2H (c+1) n)\"\n  apply2 (induct c n rule: goodstein.induct) by(simp_all add: goodstein_aux eval_nat_numeral)\n\nlemma goodstein_impl:\n  \"c \\<noteq> 0 \\<Longrightarrow> goodstein c n = goodsteinO c (C2O (N2H (c+1) n))\"\n  \\<comment> \\<open>but note that @{term N2H} is not executable as currently defined\\<close>\n  using goodstein_def'[unfolded goodsteinC_def'] .\n\nlemma goodstein_16:\n  \"\\<G> 16 = goodsteinO 1 (exp\\<omega> (exp\\<omega> (exp\\<omega> (exp\\<omega> Z))))\"\nproof -\n  have \"N2H (Suc (Suc 0)) 16 = C [C [C [C [C []]]]]\"\n    by (auto simp: H2N_def intro!: N2H_eqI hbase_singletonI hbase.intros(1))\n  then show ?thesis by (simp add: goodstein_impl)\nqed\n\n\nsection \\<open>Translation to $\\lambda$-calculus\\<close>\n\ntext \\<open>We define Church encodings for @{type nat} and @{type Ord}. Note that we are basically in a\n  Hindley-Milner type system, so we cannot use a proper polymorphic type. We can still express\n  Church encodings as folds over values of the original type.\\<close>\n\nabbreviation Z\\<^sub>N where \"Z\\<^sub>N \\<equiv> (\\<lambda>s z. z)\"\nabbreviation S\\<^sub>N where \"S\\<^sub>N \\<equiv> (\\<lambda>n s z. s (n s z))\"\n\nprimrec fold_nat (\"\\<langle>_\\<rangle>\\<^sub>N\") where\n  \"\\<langle>0\\<rangle>\\<^sub>N = Z\\<^sub>N\"\n| \"\\<langle>Suc n\\<rangle>\\<^sub>N = S\\<^sub>N \\<langle>n\\<rangle>\\<^sub>N\"\n\nlemma one\\<^sub>N:\n  \"\\<langle>1\\<rangle>\\<^sub>N = (\\<lambda>x. x)\"\n  by simp\n\nabbreviation Z\\<^sub>O where \"Z\\<^sub>O \\<equiv> (\\<lambda>z s l. z)\"\nabbreviation S\\<^sub>O where \"S\\<^sub>O \\<equiv> (\\<lambda>n z s l. s (n z s l))\"\nabbreviation L\\<^sub>O where \"L\\<^sub>O \\<equiv> (\\<lambda>f z s l. l (\\<lambda>i. f i z s l))\"\n\nprimrec fold_Ord (\"\\<langle>_\\<rangle>\\<^sub>O\") where\n  \"\\<langle>Z\\<rangle>\\<^sub>O = Z\\<^sub>O\"\n| \"\\<langle>S n\\<rangle>\\<^sub>O = S\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\n| \"\\<langle>L f\\<rangle>\\<^sub>O = L\\<^sub>O (\\<lambda>i. \\<langle>f i\\<rangle>\\<^sub>O)\"\n\ntext \\<open>The following abbreviations and lemmas show how to implement the arithmetic functions and\n  the Goodstein function on a Church-encoded @{type Ord} in lambda calculus.\\<close>\n\nabbreviation (input) add\\<^sub>O where\n  \"add\\<^sub>O n m \\<equiv> (\\<lambda>z s l. m (n z s l) s l)\"\n\nlemma add\\<^sub>O:\n  \"\\<langle>addO n m\\<rangle>\\<^sub>O = add\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\n  apply2 (induct m) by simp_all\n\nabbreviation (input) mul\\<^sub>O where\n  \"mul\\<^sub>O n m \\<equiv> (\\<lambda>z s l. m z (\\<lambda>m. n m s l) l)\"\n\nlemma mul\\<^sub>O:\n  \"\\<langle>mulO n m\\<rangle>\\<^sub>O = mul\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\n  apply2 (induct m) by(simp_all add: add\\<^sub>O)\n\nabbreviation (input) \\<omega>\\<^sub>O where\n  \"\\<omega>\\<^sub>O \\<equiv> (\\<lambda>z s l. l (\\<lambda>n. \\<langle>n\\<rangle>\\<^sub>N s z))\"\n\nlemma \\<omega>\\<^sub>O:\n  \"\\<langle>\\<omega>\\<rangle>\\<^sub>O = \\<omega>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>(S ^^ i) Z\\<rangle>\\<^sub>O z s l = \\<langle>i\\<rangle>\\<^sub>N s z\" for i z s l apply2 (induct i) by simp_all\n  show ?thesis by (simp add: \\<omega>_def)\nqed\n\nabbreviation (input) exp\\<omega>\\<^sub>O where\n  \"exp\\<omega>\\<^sub>O n \\<equiv> (\\<lambda>z s l. n s (\\<lambda>x z. l (\\<lambda>n. \\<langle>n\\<rangle>\\<^sub>N x z)) (\\<lambda>f z. l (\\<lambda>n. f n z)) z)\"\n\nlemma exp\\<omega>\\<^sub>O:\n  \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = exp\\<omega>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\n  apply2 (induct n) by (simp_all add: mul\\<^sub>O \\<omega>\\<^sub>O)\n\nabbreviation (input) goodstein\\<^sub>O where\n  \"goodstein\\<^sub>O \\<equiv> (\\<lambda>c n. n (\\<lambda>x. x) (\\<lambda>n m. n (m + 1)) (\\<lambda>f m. f (m + 2) m) c)\"\n\nlemma goodstein\\<^sub>O:\n  \"goodsteinO c n = goodstein\\<^sub>O c \\<langle>n\\<rangle>\\<^sub>O\"\n  apply2 (induct n arbitrary: c) by simp_all\n\ntext \\<open>Note that modeling Church encodings with folds is still limited. For example, the meaningful\n  expression @{text \"\\<langle>n\\<rangle>\\<^sub>N exp\\<omega>\\<^sub>O Z\\<^sub>O\"} cannot be typed in Isabelle/HOL, as that would require rank-2\n  polymorphism.\\<close>\n\nsubsection \\<open>Alternative: free theorems\\<close>\n\ntext \\<open>The following is essentially the free theorem for Church-encoded @{type Ord} values.\\<close>\n\nlemma freeOrd:\n  assumes \"\\<And>n. h (s n) = s' (h n)\" and \"\\<And>f. h (l f) = l' (\\<lambda>i. h (f i))\"\n  shows \"h (\\<langle>n\\<rangle>\\<^sub>O z s l) = \\<langle>n\\<rangle>\\<^sub>O (h z) s' l'\"\n  apply2 (induct n) by(simp_all add: assms)\n\ntext \\<open>Each of the following proofs first states a naive definition of the corresponding function\n  (which is proved correct by induction), from which we then derive the optimized version using\n  the free theorem, by (conditional) rewriting (without induction).\\<close>\n\nlemma add\\<^sub>O':\n  \"\\<langle>addO n m\\<rangle>\\<^sub>O = add\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>addO n m\\<rangle>\\<^sub>O = \\<langle>m\\<rangle>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O S\\<^sub>O L\\<^sub>O\"\n    apply2 (induct m) by simp_all\n  show ?thesis\n    by (intro ext) (simp add: freeOrd[where h = \"\\<lambda>n. n _ _ _\"])\nqed\n\nlemma mul\\<^sub>O':\n  \"\\<langle>mulO n m\\<rangle>\\<^sub>O = mul\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>mulO n m\\<rangle>\\<^sub>O = \\<langle>m\\<rangle>\\<^sub>O Z\\<^sub>O (\\<lambda>m. add\\<^sub>O m \\<langle>n\\<rangle>\\<^sub>O) L\\<^sub>O\"\n    apply2 (induct m) by(simp_all add: add\\<^sub>O)\n  show ?thesis\n    by (intro ext) (simp add: freeOrd[where h = \"\\<lambda>n. n _ _ _\"])\nqed\n\nlemma exp\\<omega>\\<^sub>O':\n  \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = exp\\<omega>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = \\<langle>n\\<rangle>\\<^sub>O (S\\<^sub>O Z\\<^sub>O) (\\<lambda>m. mul\\<^sub>O m \\<omega>\\<^sub>O) L\\<^sub>O\"\n    apply2 (induct n) by(simp_all add: mul\\<^sub>O \\<omega>\\<^sub>O)\n  show ?thesis\n    by (intro ext) (simp add: fun_cong[OF freeOrd[where h = \"\\<lambda>n z. n z _ _\"]])\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation_PLDI_Small/Goodstein_Lambda/Goodstein_Lambda.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.8539127585282744, "lm_q1q2_score": 0.7615288323512706}}
{"text": "(*\n  File:    Pi_pmf.thy\n  Authors: Manuel Eberl, Max W. Haslbeck\n*)\nsection \\<open>Indexed products of PMFs\\<close>\ntheory Pi_pmf\n  imports \"HOL-Probability.Probability\"\nbegin\n\nsubsection \\<open>Preliminaries\\<close>\n\nlemma pmf_expectation_eq_infsetsum: \"measure_pmf.expectation p f = infsetsum (\\<lambda>x. pmf p x * f x) UNIV\"\n  unfolding infsetsum_def measure_pmf_eq_density by (subst integral_density) simp_all\n\nlemma measure_pmf_prob_product:\n  assumes \"countable A\" \"countable B\"\n  shows \"measure_pmf.prob (pair_pmf M N) (A \\<times> B) = measure_pmf.prob M A * measure_pmf.prob N B\"\nproof -\n  have \"measure_pmf.prob (pair_pmf M N) (A \\<times> B) = (\\<Sum>\\<^sub>a(a, b)\\<in>A \\<times> B. pmf M a * pmf N b)\"\n    by (auto intro!: infsetsum_cong simp add: measure_pmf_conv_infsetsum pmf_pair)\n  also have \"\\<dots> = measure_pmf.prob M A * measure_pmf.prob N B\"\n    using assms by (subst infsetsum_product) (auto simp add: measure_pmf_conv_infsetsum)\n  finally show ?thesis\n    by simp\nqed\n\n\nsubsection \\<open>Definition\\<close>\n\ntext \\<open>\n  In analogy to @{const PiM}, we define an indexed product of PMFs. In the literature, this\n  is typically called taking a vector of independent random variables. Note that the components\n  do not have to be identically distributed.\n\n  The operation takes an explicit index set \\<^term>\\<open>A :: 'a set\\<close> and a function \\<^term>\\<open>f :: 'a \\<Rightarrow> 'b pmf\\<close>\n  that maps each element from \\<^term>\\<open>A\\<close> to a PMF and defines the product measure\n  $\\bigotimes_{i\\in A} f(i)$ , which is represented as a \\<^typ>\\<open>('a \\<Rightarrow> 'b) pmf\\<close>.\n\n  Note that unlike @{const PiM}, this only works for \\<^emph>\\<open>finite\\<close> index sets. It could\n  be extended to countable sets and beyond, but the construction becomes somewhat more involved.\n\\<close>\ndefinition Pi_pmf :: \"'a set \\<Rightarrow> 'b \\<Rightarrow> ('a \\<Rightarrow> 'b pmf) \\<Rightarrow> ('a \\<Rightarrow> 'b) pmf\" where\n  \"Pi_pmf A dflt p =\n     embed_pmf (\\<lambda>f. if (\\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt) then \\<Prod>x\\<in>A. pmf (p x) (f x) else 0)\"\n\ntext \\<open>\n  A technical subtlety that needs to be addressed is this: Intuitively, the functions in the\n  support of a product distribution have domain \\<open>A\\<close>. However, since HOL is a total logic, these\n  functions must still return \\<^emph>\\<open>some\\<close> value for inputs outside \\<open>A\\<close>. The product measure\n  @{const PiM} simply lets these functions return @{const undefined} in these cases. We chose a\n  different solution here, which is to supply a default value \\<^term>\\<open>dflt :: 'b\\<close> that is returned\n  in these cases.\n\n  As one possible application, one could model the result of \\<open>n\\<close> different independent coin\n  tosses as @{term \"Pi_pmf {0..<n} False (\\<lambda>_. bernoulli_pmf (1 / 2))\"}. This returns a function\n  of type \\<^typ>\\<open>nat \\<Rightarrow> bool\\<close> that maps every natural number below \\<open>n\\<close> to the result of the\n  corresponding coin toss, and every other natural number to \\<^term>\\<open>False\\<close>.\n\\<close>\n\nlemma pmf_Pi:\n  assumes A: \"finite A\"\n  shows   \"pmf (Pi_pmf A dflt p) f =\n             (if (\\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt) then \\<Prod>x\\<in>A. pmf (p x) (f x) else 0)\"\n  unfolding Pi_pmf_def\nproof (rule pmf_embed_pmf, goal_cases)\n  case 2\n  define S where \"S = {f. \\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt}\"\n  define B where \"B = (\\<lambda>x. set_pmf (p x))\"\n\n  have neutral_left: \"(\\<Prod>xa\\<in>A. pmf (p xa) (f xa)) = 0\"\n    if \"f \\<in> PiE A B - (\\<lambda>f. restrict f A) ` S\" for f\n  proof -\n    have \"restrict (\\<lambda>x. if x \\<in> A then f x else dflt) A \\<in> (\\<lambda>f. restrict f A) ` S\"\n      by (intro imageI) (auto simp: S_def)\n    also have \"restrict (\\<lambda>x. if x \\<in> A then f x else dflt) A = f\"\n      using that by (auto simp: PiE_def Pi_def extensional_def fun_eq_iff)\n    finally show ?thesis using that by blast\n  qed\n  have neutral_right: \"(\\<Prod>xa\\<in>A. pmf (p xa) (f xa)) = 0\"\n    if \"f \\<in> (\\<lambda>f. restrict f A) ` S - PiE A B\" for f\n  proof -\n    from that obtain f' where f': \"f = restrict f' A\" \"f' \\<in> S\" by auto\n    moreover from this and that have \"restrict f' A \\<notin> PiE A B\" by simp\n    then obtain x where \"x \\<in> A\" \"pmf (p x) (f' x) = 0\" by (auto simp: B_def set_pmf_eq)\n    with f' and A show ?thesis by auto\n  qed\n\n  have \"(\\<lambda>f. \\<Prod>x\\<in>A. pmf (p x) (f x)) abs_summable_on PiE A B\"\n    by (intro abs_summable_on_prod_PiE A) (auto simp: B_def)\n  also have \"?this \\<longleftrightarrow> (\\<lambda>f. \\<Prod>x\\<in>A. pmf (p x) (f x)) abs_summable_on (\\<lambda>f. restrict f A) ` S\"\n    by (intro abs_summable_on_cong_neutral neutral_left neutral_right) auto\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>f. \\<Prod>x\\<in>A. pmf (p x) (restrict f A x)) abs_summable_on S\"\n    by (rule abs_summable_on_reindex_iff [symmetric]) (force simp: inj_on_def fun_eq_iff S_def)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>f. if \\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt then \\<Prod>x\\<in>A. pmf (p x) (f x) else 0)\n                          abs_summable_on UNIV\"\n    by (intro abs_summable_on_cong_neutral) (auto simp: S_def)\n  finally have summable: \\<dots> .\n\n  have \"1 = (\\<Prod>x\\<in>A. 1::real)\" by simp\n  also have \"(\\<Prod>x\\<in>A. 1) = (\\<Prod>x\\<in>A. \\<Sum>\\<^sub>ay\\<in>B x. pmf (p x) y)\"\n    unfolding B_def by (subst infsetsum_pmf_eq_1) auto\n  also have \"(\\<Prod>x\\<in>A. \\<Sum>\\<^sub>ay\\<in>B x. pmf (p x) y) = (\\<Sum>\\<^sub>af\\<in>Pi\\<^sub>E A B. \\<Prod>x\\<in>A. pmf (p x) (f x))\"\n    by (intro infsetsum_prod_PiE [symmetric] A) (auto simp: B_def)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>af\\<in>(\\<lambda>f. restrict f A) ` S. \\<Prod>x\\<in>A. pmf (p x) (f x))\" using A\n    by (intro infsetsum_cong_neutral neutral_left neutral_right refl)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>af\\<in>S. \\<Prod>x\\<in>A. pmf (p x) (restrict f A x))\"\n    by (rule infsetsum_reindex) (force simp: inj_on_def fun_eq_iff S_def)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>af\\<in>S. \\<Prod>x\\<in>A. pmf (p x) (f x))\"\n    by (intro infsetsum_cong) (auto simp: S_def)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>af. if \\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt then \\<Prod>x\\<in>A. pmf (p x) (f x) else 0)\"\n    by (intro infsetsum_cong_neutral) (auto simp: S_def)\n  also have \"ennreal \\<dots> = (\\<integral>\\<^sup>+f. ennreal (if \\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt\n                             then \\<Prod>x\\<in>A. pmf (p x) (f x) else 0) \\<partial>count_space UNIV)\"\n    by (intro nn_integral_conv_infsetsum [symmetric] summable) (auto simp: prod_nonneg)\n  finally show ?case by simp\nqed (auto simp: prod_nonneg)\n\nlemma pmf_Pi':\n  assumes \"finite A\" \"\\<And>x. x \\<notin> A \\<Longrightarrow> f x = dflt\"\n  shows   \"pmf (Pi_pmf A dflt p) f = (\\<Prod>x\\<in>A. pmf (p x) (f x))\"\n  using assms by (subst pmf_Pi) auto\n\nlemma pmf_Pi_outside:\n  assumes \"finite A\" \"\\<exists>x. x \\<notin> A \\<and> f x \\<noteq> dflt\"\n  shows   \"pmf (Pi_pmf A dflt p) f = 0\"\n  using assms by (subst pmf_Pi) auto\n\nlemma pmf_Pi_empty [simp]: \"Pi_pmf {} dflt p = return_pmf (\\<lambda>_. dflt)\"\n  by (intro pmf_eqI, subst pmf_Pi) (auto simp: indicator_def)\n\nlemma set_Pi_pmf_subset: \"finite A \\<Longrightarrow> set_pmf (Pi_pmf A dflt p) \\<subseteq> {f. \\<forall>x. x \\<notin> A \\<longrightarrow> f x = dflt}\"\n  by (auto simp: set_pmf_eq pmf_Pi)\n\nlemma Pi_pmf_cong [cong]:\n  assumes \"A = A'\" \"dflt = dflt'\" \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = f' x\"\n  shows   \"Pi_pmf A dflt f = Pi_pmf A' dflt' f'\"\nproof -\n  have \"(\\<lambda>g. \\<Prod>x\\<in>A. pmf (f x) (g x)) = (\\<lambda>g. \\<Prod>x\\<in>A. pmf (f' x) (g x))\"\n    by (intro ext prod.cong) (auto simp: assms)\n  with assms show ?thesis by (simp add: Pi_pmf_def cong: if_cong)\nqed\n\n\nsubsection \\<open>Dependent product sets with a default\\<close>\n\ntext \\<open>\n  The following describes a dependent product of sets where the functions are required to return\n  the default value \\<^term>\\<open>dflt\\<close> outside their domain, in analogy to @{const PiE}, which uses\n  @{const undefined}.\n\\<close>\ndefinition PiE_dflt\n  where \"PiE_dflt A dflt B = {f. \\<forall>x. (x \\<in> A \\<longrightarrow> f x \\<in> B x) \\<and> (x \\<notin> A \\<longrightarrow> f x = dflt)}\"\n\nlemma restrict_PiE_dflt: \"(\\<lambda>h. restrict h A) ` PiE_dflt A dflt B = PiE A B\"\nproof (intro equalityI subsetI)\n  fix h assume \"h \\<in> (\\<lambda>h. restrict h A) ` PiE_dflt A dflt B\"\n  thus \"h \\<in> PiE A B\"\n    by (auto simp: PiE_dflt_def)\nnext\n  fix h assume h: \"h \\<in> PiE A B\"\n  hence \"restrict (\\<lambda>x. if x \\<in> A then h x else dflt) A \\<in> (\\<lambda>h. restrict h A) ` PiE_dflt A dflt B\"\n    by (intro imageI) (auto simp: PiE_def extensional_def PiE_dflt_def)\n  also have \"restrict (\\<lambda>x. if x \\<in> A then h x else dflt) A = h\"\n    using h by (auto simp: fun_eq_iff)\n  finally show \"h \\<in> (\\<lambda>h. restrict h A) ` PiE_dflt A dflt B\" .\nqed\n\nlemma dflt_image_PiE: \"(\\<lambda>h x. if x \\<in> A then h x else dflt) ` PiE A B = PiE_dflt A dflt B\"\n  (is \"?f ` ?X = ?Y\")\nproof (intro equalityI subsetI)\n  fix h assume \"h \\<in> ?f ` ?X\"\n  thus \"h \\<in> ?Y\"\n    by (auto simp: PiE_dflt_def PiE_def)\nnext\n  fix h assume h: \"h \\<in> ?Y\"\n  hence \"?f (restrict h A) \\<in> ?f ` ?X\"\n    by (intro imageI) (auto simp: PiE_def extensional_def PiE_dflt_def)\n  also have \"?f (restrict h A) = h\"\n    using h by (auto simp: fun_eq_iff PiE_dflt_def)\n  finally show \"h \\<in> ?f ` ?X\" .\nqed\n\nlemma finite_PiE_dflt [intro]:\n  assumes \"finite A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> finite (B x)\"\n  shows   \"finite (PiE_dflt A d B)\"\nproof -\n  have \"PiE_dflt A d B = (\\<lambda>f x. if x \\<in> A then f x else d) ` PiE A B\"\n    by (rule dflt_image_PiE [symmetric])\n  also have \"finite \\<dots>\"\n    by (intro finite_imageI finite_PiE assms)\n  finally show ?thesis .\nqed\n\nlemma card_PiE_dflt:\n  assumes \"finite A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> finite (B x)\"\n  shows   \"card (PiE_dflt A d B) = (\\<Prod>x\\<in>A. card (B x))\"\nproof -\n  from assms have \"(\\<Prod>x\\<in>A. card (B x)) = card (PiE A B)\"\n    by (intro card_PiE [symmetric]) auto\n  also have \"PiE A B = (\\<lambda>f. restrict f A) ` PiE_dflt A d B\"\n    by (rule restrict_PiE_dflt [symmetric])\n  also have \"card \\<dots> = card (PiE_dflt A d B)\"\n    by (intro card_image) (force simp: inj_on_def restrict_def fun_eq_iff PiE_dflt_def)\n  finally show ?thesis ..\nqed\n\nlemma PiE_dflt_empty_iff [simp]: \"PiE_dflt A dflt B = {} \\<longleftrightarrow> (\\<exists>x\\<in>A. B x = {})\"\n  by (simp add: dflt_image_PiE [symmetric] PiE_eq_empty_iff)\n\ntext \\<open>\n  The probability of an independent combination of events is precisely the product\n  of the probabilities of each individual event.\n\\<close>\nlemma measure_Pi_pmf_PiE_dflt:\n  assumes [simp]: \"finite A\"\n  shows   \"measure_pmf.prob (Pi_pmf A dflt p) (PiE_dflt A dflt B) =\n             (\\<Prod>x\\<in>A. measure_pmf.prob (p x) (B x))\"\nproof -\n  define B' where \"B' = (\\<lambda>x. B x \\<inter> set_pmf (p x))\"\n  have \"measure_pmf.prob (Pi_pmf A dflt p) (PiE_dflt A dflt B) =\n          (\\<Sum>\\<^sub>ah\\<in>PiE_dflt A dflt B. pmf (Pi_pmf A dflt p) h)\"\n    by (rule measure_pmf_conv_infsetsum)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ah\\<in>PiE_dflt A dflt B. \\<Prod>x\\<in>A. pmf (p x) (h x))\"\n    by (intro infsetsum_cong, subst pmf_Pi') (auto simp: PiE_dflt_def)\n  also have \"\\<dots> = (\\<Sum>\\<^sub>ah\\<in>(\\<lambda>h. restrict h A) ` PiE_dflt A dflt B. \\<Prod>x\\<in>A. pmf (p x) (h x))\"\n    by (subst infsetsum_reindex) (force simp: inj_on_def PiE_dflt_def fun_eq_iff)+\n  also have \"(\\<lambda>h. restrict h A) ` PiE_dflt A dflt B = PiE A B\"\n    by (rule restrict_PiE_dflt)\n  also have \"(\\<Sum>\\<^sub>ah\\<in>PiE A B. \\<Prod>x\\<in>A. pmf (p x) (h x)) = (\\<Sum>\\<^sub>ah\\<in>PiE A B'. \\<Prod>x\\<in>A. pmf (p x) (h x))\"\n    by (intro infsetsum_cong_neutral) (auto simp: B'_def set_pmf_eq)\n  also have \"(\\<Sum>\\<^sub>ah\\<in>PiE A B'. \\<Prod>x\\<in>A. pmf (p x) (h x)) = (\\<Prod>x\\<in>A. infsetsum (pmf (p x)) (B' x))\"\n    by (intro infsetsum_prod_PiE) (auto simp: B'_def)\n  also have \"\\<dots> = (\\<Prod>x\\<in>A. infsetsum (pmf (p x)) (B x))\"\n    by (intro prod.cong infsetsum_cong_neutral) (auto simp: B'_def set_pmf_eq)\n  also have \"\\<dots> = (\\<Prod>x\\<in>A. measure_pmf.prob (p x) (B x))\"\n    by (subst measure_pmf_conv_infsetsum) (rule refl)\n  finally show ?thesis .\nqed\n\nlemma set_Pi_pmf_subset':\n  assumes \"finite A\"\n  shows   \"set_pmf (Pi_pmf A dflt p) \\<subseteq> PiE_dflt A dflt (set_pmf \\<circ> p)\"\n  using assms by (auto simp: set_pmf_eq pmf_Pi PiE_dflt_def)\n\nlemma Pi_pmf_return_pmf [simp]:\n  assumes \"finite A\"\n  shows   \"Pi_pmf A dflt (\\<lambda>x. return_pmf (f x)) = return_pmf (\\<lambda>x. if x \\<in> A then f x else dflt)\"\nproof -\n  have \"set_pmf (Pi_pmf A dflt (\\<lambda>x. return_pmf (f x))) \\<subseteq>\n          PiE_dflt A dflt (set_pmf \\<circ> (\\<lambda>x. return_pmf (f x)))\"\n    by (intro set_Pi_pmf_subset' assms)\n  also have \"\\<dots> \\<subseteq> {\\<lambda>x. if x \\<in> A then f x else dflt}\"\n    by (auto simp: PiE_dflt_def)\n  finally show ?thesis\n    by (simp add: set_pmf_subset_singleton)\nqed\n\nlemma Pi_pmf_return_pmf' [simp]:\n  assumes \"finite A\"\n  shows   \"Pi_pmf A dflt (\\<lambda>_. return_pmf dflt) = return_pmf (\\<lambda>_. dflt)\"\n  using assms by simp\n\nlemma measure_Pi_pmf_Pi:\n  fixes t::nat\n  assumes [simp]: \"finite A\"\n  shows   \"measure_pmf.prob (Pi_pmf A dflt p) (Pi A B) =\n             (\\<Prod>x\\<in>A. measure_pmf.prob (p x) (B x))\" (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = measure_pmf.prob (Pi_pmf A dflt p) (PiE_dflt A dflt B)\"\n    by (intro measure_prob_cong_0)\n       (auto simp: PiE_dflt_def PiE_def intro!: pmf_Pi_outside)+\n  also have \"\\<dots> = ?rhs\"\n    using assms by (simp add: measure_Pi_pmf_PiE_dflt)\n  finally show ?thesis\n    by simp\nqed\n\n\nsubsection \\<open>Common PMF operations on products\\<close>\n\ntext \\<open>\n  @{const Pi_pmf} distributes over the `bind' operation in the Giry monad:\n\\<close>\nlemma Pi_pmf_bind:\n  assumes \"finite A\"\n  shows   \"Pi_pmf A d (\\<lambda>x. bind_pmf (p x) (q x)) =\n             do {f \\<leftarrow> Pi_pmf A d' p; Pi_pmf A d (\\<lambda>x. q x (f x))}\" (is \"?lhs = ?rhs\")\nproof (rule pmf_eqI, goal_cases)\n  case (1 f)\n  show ?case\n  proof (cases \"\\<exists>x\\<in>-A. f x \\<noteq> d\")\n    case False\n    define B where \"B = (\\<lambda>x. set_pmf (p x))\"\n    have [simp]: \"countable (B x)\" for x by (auto simp: B_def)\n\n    {\n      fix x :: 'a\n      have \"(\\<lambda>a. pmf (p x) a * 1) abs_summable_on B x\"\n        by (simp add: pmf_abs_summable)\n      moreover have \"norm (pmf (p x) a * 1) \\<ge> norm (pmf (p x) a * pmf (q x a) (f x))\" for a\n        unfolding norm_mult by (intro mult_left_mono) (auto simp: pmf_le_1)\n      ultimately have \"(\\<lambda>a. pmf (p x) a * pmf (q x a) (f x)) abs_summable_on B x\"\n        by (rule abs_summable_on_comparison_test)\n    } note summable = this\n\n    have \"pmf ?rhs f = (\\<Sum>\\<^sub>ag. pmf (Pi_pmf A d' p) g * (\\<Prod>x\\<in>A. pmf (q x (g x)) (f x)))\"\n      by (subst pmf_bind, subst pmf_Pi')\n         (insert assms False, simp_all add: pmf_expectation_eq_infsetsum)\n    also have \"\\<dots> = (\\<Sum>\\<^sub>ag\\<in>PiE_dflt A d' B.\n                      pmf (Pi_pmf A d' p) g * (\\<Prod>x\\<in>A. pmf (q x (g x)) (f x)))\" unfolding B_def\n      using assms by (intro infsetsum_cong_neutral) (auto simp: pmf_Pi PiE_dflt_def set_pmf_eq)\n    also have \"\\<dots> = (\\<Sum>\\<^sub>ag\\<in>PiE_dflt A d' B.\n                      (\\<Prod>x\\<in>A. pmf (p x) (g x) * pmf (q x (g x)) (f x)))\"\n      using assms by (intro infsetsum_cong) (auto simp: pmf_Pi PiE_dflt_def prod.distrib)\n    also have \"\\<dots> = (\\<Sum>\\<^sub>ag\\<in>(\\<lambda>g. restrict g A) ` PiE_dflt A d' B.\n                      (\\<Prod>x\\<in>A. pmf (p x) (g x) * pmf (q x (g x)) (f x)))\"\n      by (subst infsetsum_reindex) (force simp: PiE_dflt_def inj_on_def fun_eq_iff)+\n    also have \"(\\<lambda>g. restrict g A) ` PiE_dflt A d' B = PiE A B\"\n      by (rule restrict_PiE_dflt)\n    also have \"(\\<Sum>\\<^sub>ag\\<in>\\<dots>. (\\<Prod>x\\<in>A. pmf (p x) (g x) * pmf (q x (g x)) (f x))) =\n                 (\\<Prod>x\\<in>A. \\<Sum>\\<^sub>aa\\<in>B x. pmf (p x) a * pmf (q x a) (f x))\"\n      using assms summable by (subst infsetsum_prod_PiE) simp_all\n    also have \"\\<dots> = (\\<Prod>x\\<in>A. \\<Sum>\\<^sub>aa. pmf (p x) a * pmf (q x a) (f x))\"\n      by (intro prod.cong infsetsum_cong_neutral) (auto simp: B_def set_pmf_eq)\n    also have \"\\<dots> = pmf ?lhs f\"\n      using False assms by (subst pmf_Pi') (simp_all add: pmf_bind pmf_expectation_eq_infsetsum)\n    finally show ?thesis ..\n  next\n    case True\n    have \"pmf ?rhs f =\n            measure_pmf.expectation (Pi_pmf A d' p) (\\<lambda>x. pmf (Pi_pmf A d (\\<lambda>xa. q xa (x xa))) f)\"\n      using assms by (simp add: pmf_bind)\n    also have \"\\<dots> = measure_pmf.expectation (Pi_pmf A d' p) (\\<lambda>x. 0)\"\n      using assms True by (intro Bochner_Integration.integral_cong pmf_Pi_outside) auto\n    also have \"\\<dots> = pmf ?lhs f\"\n      using assms True by (subst pmf_Pi_outside) auto\n    finally show ?thesis ..\n  qed\nqed\n\ntext \\<open>\n  Analogously any componentwise mapping can be pulled outside the product:\n\\<close>\nlemma Pi_pmf_map:\n  assumes [simp]: \"finite A\" and \"f dflt = dflt'\"\n  shows   \"Pi_pmf A dflt' (\\<lambda>x. map_pmf f (g x)) = map_pmf (\\<lambda>h. f \\<circ> h) (Pi_pmf A dflt g)\"\nproof -\n  have \"Pi_pmf A dflt' (\\<lambda>x. map_pmf f (g x)) =\n          Pi_pmf A dflt' (\\<lambda>x. g x \\<bind> (\\<lambda>x. return_pmf (f x)))\"\n    using assms by (simp add: map_pmf_def Pi_pmf_bind)\n  also have \"\\<dots> = Pi_pmf A dflt g \\<bind> (\\<lambda>h. return_pmf (\\<lambda>x. if x \\<in> A then f (h x) else dflt'))\"\n   by (subst Pi_pmf_bind[where d' = dflt]) auto\n  also have \"\\<dots> = map_pmf (\\<lambda>h. f \\<circ> h) (Pi_pmf A dflt g)\"\n    unfolding map_pmf_def using set_Pi_pmf_subset'[of A dflt g]\n    by (intro bind_pmf_cong refl arg_cong[of _ _ return_pmf])\n       (auto dest: simp: fun_eq_iff PiE_dflt_def assms(2))\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  We can exchange the default value in a product of PMFs like this:\n\\<close>\nlemma Pi_pmf_default_swap:\n  assumes \"finite A\"\n  shows   \"map_pmf (\\<lambda>f x. if x \\<in> A then f x else dflt') (Pi_pmf A dflt p) =\n             Pi_pmf A dflt' p\" (is \"?lhs = ?rhs\")\nproof (rule pmf_eqI, goal_cases)\n  case (1 f)\n  let ?B = \"(\\<lambda>f x. if x \\<in> A then f x else dflt') -` {f} \\<inter> PiE_dflt A dflt (\\<lambda>_. UNIV)\"\n  show ?case\n  proof (cases \"\\<exists>x\\<in>-A. f x \\<noteq> dflt'\")\n    case False\n    let ?f' = \"\\<lambda>x. if x \\<in> A then f x else dflt\"\n    from False have \"pmf ?lhs f = measure_pmf.prob (Pi_pmf A dflt p) ?B\"\n      using assms unfolding pmf_map\n      by (intro measure_prob_cong_0) (auto simp: PiE_dflt_def pmf_Pi_outside)\n    also from False have \"?B = {?f'}\"\n      by (auto simp: fun_eq_iff PiE_dflt_def)\n    also have \"measure_pmf.prob (Pi_pmf A dflt p) {?f'} = pmf (Pi_pmf A dflt p) ?f'\"\n      by (simp add: measure_pmf_single)\n    also have \"\\<dots> = pmf ?rhs f\"\n      using False assms by (subst (1 2) pmf_Pi) auto\n    finally show ?thesis .\n  next\n    case True\n    have \"pmf ?lhs f = measure_pmf.prob (Pi_pmf A dflt p) ?B\"\n      using assms unfolding pmf_map\n      by (intro measure_prob_cong_0) (auto simp: PiE_dflt_def pmf_Pi_outside)\n    also from True have \"?B = {}\" by auto\n    also have \"measure_pmf.prob (Pi_pmf A dflt p) \\<dots> = 0\"\n      by simp\n    also have \"0 = pmf ?rhs f\"\n      using True assms by (intro pmf_Pi_outside [symmetric]) auto\n    finally show ?thesis .\n  qed\nqed\n\ntext \\<open>\n  The following rule allows reindexing the product:\n\\<close>\nlemma Pi_pmf_bij_betw:\n  assumes \"finite A\" \"bij_betw h A B\" \"\\<And>x. x \\<notin> A \\<Longrightarrow> h x \\<notin> B\"\n  shows \"Pi_pmf A dflt (\\<lambda>_. f) = map_pmf (\\<lambda>g. g \\<circ> h) (Pi_pmf B dflt (\\<lambda>_. f))\"\n    (is \"?lhs = ?rhs\")\nproof -\n  have B: \"finite B\"\n    using assms bij_betw_finite by auto\n  have \"pmf ?lhs g = pmf ?rhs g\" for g\n  proof (cases \"\\<forall>a. a \\<notin> A \\<longrightarrow> g a = dflt\")\n    case True\n    define h' where \"h' = the_inv_into A h\"\n    have h': \"h' (h x) = x\" if \"x \\<in> A\" for x\n      unfolding h'_def using that assms by (auto simp add: bij_betw_def the_inv_into_f_f)\n    have h: \"h (h' x) = x\" if \"x \\<in> B\" for x\n      unfolding h'_def using that assms f_the_inv_into_f_bij_betw by fastforce\n    have \"pmf ?rhs g = measure_pmf.prob (Pi_pmf B dflt (\\<lambda>_. f)) ((\\<lambda>g. g \\<circ> h) -` {g})\"\n      unfolding pmf_map by simp\n    also have \"\\<dots> = measure_pmf.prob (Pi_pmf B dflt (\\<lambda>_. f))\n                                (((\\<lambda>g. g \\<circ> h) -` {g}) \\<inter> PiE_dflt B dflt (\\<lambda>_. UNIV))\"\n      using B by (intro measure_prob_cong_0) (auto simp: PiE_dflt_def pmf_Pi_outside)\n    also have \"\\<dots> = pmf (Pi_pmf B dflt (\\<lambda>_. f)) (\\<lambda>x. if x \\<in> B then g (h' x) else dflt)\"\n    proof -\n      have \"(if h x \\<in> B then g (h' (h x)) else dflt) = g x\" for x\n        using h' assms True by (cases \"x \\<in> A\") (auto simp add: bij_betwE)\n      then have \"(\\<lambda>g. g \\<circ> h) -` {g} \\<inter> PiE_dflt B dflt (\\<lambda>_. UNIV) =\n            {(\\<lambda>x. if x \\<in> B then g (h' x) else dflt)}\"\n        using assms h' h True unfolding PiE_dflt_def by auto\n      then show ?thesis\n        by (simp add: measure_pmf_single)\n    qed\n    also have \"\\<dots> = pmf (Pi_pmf A dflt (\\<lambda>_. f)) g\"\n      using B assms True  h'_def\n      by (auto simp add: pmf_Pi intro!: prod.reindex_bij_betw bij_betw_the_inv_into)\n    finally show ?thesis\n      by simp\n  next\n    case False\n    have \"pmf ?rhs g = infsetsum (pmf (Pi_pmf B dflt (\\<lambda>_. f))) ((\\<lambda>g. g \\<circ> h) -` {g})\"\n      using assms by (auto simp add: measure_pmf_conv_infsetsum pmf_map)\n    also have \"\\<dots> = infsetsum (\\<lambda>_. 0) ((\\<lambda>g x. g (h x)) -` {g})\"\n      using B False assms by (intro infsetsum_cong pmf_Pi_outside) fastforce+\n    also have \"\\<dots> = 0\"\n      by simp\n    finally show ?thesis\n      using assms False by (auto simp add: pmf_Pi pmf_map)\n  qed\n  then show ?thesis\n    by (rule pmf_eqI)\nqed\n\ntext \\<open>\n  A product of uniform random choices is again a uniform distribution.\n\\<close>\nlemma Pi_pmf_of_set:\n  assumes \"finite A\" \"\\<And>x. x \\<in> A \\<Longrightarrow> finite (B x)\" \"\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<noteq> {}\"\n  shows   \"Pi_pmf A d (\\<lambda>x. pmf_of_set (B x)) = pmf_of_set (PiE_dflt A d B)\" (is \"?lhs = ?rhs\")\nproof (rule pmf_eqI, goal_cases)\n  case (1 f)\n  show ?case\n  proof (cases \"\\<exists>x. x \\<notin> A \\<and> f x \\<noteq> d\")\n    case True\n    hence \"pmf ?lhs f = 0\"\n      using assms by (intro pmf_Pi_outside) (auto simp: PiE_dflt_def)\n    also from True have \"f \\<notin> PiE_dflt A d B\"\n      by (auto simp: PiE_dflt_def)\n    hence \"0 = pmf ?rhs f\"\n      using assms by (subst pmf_of_set) auto\n    finally show ?thesis .\n  next\n    case False\n    hence \"pmf ?lhs f = (\\<Prod>x\\<in>A. pmf (pmf_of_set (B x)) (f x))\"\n      using assms by (subst pmf_Pi') auto\n    also have \"\\<dots> = (\\<Prod>x\\<in>A. indicator (B x) (f x) / real (card (B x)))\"\n      by (intro prod.cong refl, subst pmf_of_set) (use assms False in auto)\n    also have \"\\<dots> = (\\<Prod>x\\<in>A. indicator (B x) (f x)) / real (\\<Prod>x\\<in>A. card (B x))\"\n      by (subst prod_dividef) simp_all\n    also have \"(\\<Prod>x\\<in>A. indicator (B x) (f x) :: real) = indicator (PiE_dflt A d B) f\"\n      using assms False by (auto simp: indicator_def PiE_dflt_def)\n    also have \"(\\<Prod>x\\<in>A. card (B x)) = card (PiE_dflt A d B)\"\n      using assms by (intro card_PiE_dflt [symmetric]) auto\n    also have \"indicator (PiE_dflt A d B) f / \\<dots> = pmf ?rhs f\"\n      using assms by (intro pmf_of_set [symmetric]) auto\n    finally show ?thesis .\n  qed\nqed\n\n\nsubsection \\<open>Merging and splitting PMF products\\<close>\n\ntext \\<open>\n  The following lemma shows that we can add a single PMF to a product:\n\\<close>\nlemma Pi_pmf_insert:\n  assumes \"finite A\" \"x \\<notin> A\"\n  shows   \"Pi_pmf (insert x A) dflt p = map_pmf (\\<lambda>(y,f). f(x:=y)) (pair_pmf (p x) (Pi_pmf A dflt p))\"\nproof (intro pmf_eqI)\n  fix f\n  let ?M = \"pair_pmf (p x) (Pi_pmf A dflt p)\"\n  have \"pmf (map_pmf (\\<lambda>(y, f). f(x := y)) ?M) f =\n          measure_pmf.prob ?M ((\\<lambda>(y, f). f(x := y)) -` {f})\"\n    by (subst pmf_map) auto\n  also have \"((\\<lambda>(y, f). f(x := y)) -` {f}) = (\\<Union>y'. {(f x, f(x := y'))})\"\n    by (auto simp: fun_upd_def fun_eq_iff)\n  also have \"measure_pmf.prob ?M \\<dots> = measure_pmf.prob ?M {(f x, f(x := dflt))}\"\n    using assms by (intro measure_prob_cong_0) (auto simp: pmf_pair pmf_Pi split: if_splits)\n  also have \"\\<dots> = pmf (p x) (f x) * pmf (Pi_pmf A dflt p) (f(x := dflt))\"\n    by (simp add: measure_pmf_single pmf_pair pmf_Pi)\n  also have \"\\<dots> = pmf (Pi_pmf (insert x A) dflt p) f\"\n  proof (cases \"\\<forall>y. y \\<notin> insert x A \\<longrightarrow> f y = dflt\")\n    case True\n    with assms have \"pmf (p x) (f x) * pmf (Pi_pmf A dflt p) (f(x := dflt)) =\n                       pmf (p x) (f x) * (\\<Prod>xa\\<in>A. pmf (p xa) ((f(x := dflt)) xa))\"\n      by (subst pmf_Pi') auto\n    also have \"(\\<Prod>xa\\<in>A. pmf (p xa) ((f(x := dflt)) xa)) = (\\<Prod>xa\\<in>A. pmf (p xa) (f xa))\"\n      using assms by (intro prod.cong) auto\n    also have \"pmf (p x) (f x) * \\<dots> = pmf (Pi_pmf (insert x A) dflt p) f\"\n      using assms True by (subst pmf_Pi') auto\n    finally show ?thesis .\n  qed (insert assms, auto simp: pmf_Pi)\n  finally show \"\\<dots> = pmf (map_pmf (\\<lambda>(y, f). f(x := y)) ?M) f\" ..\nqed\n\nlemma Pi_pmf_insert':\n  assumes \"finite A\"  \"x \\<notin> A\"\n  shows   \"Pi_pmf (insert x A) dflt p =\n             do {y \\<leftarrow> p x; f \\<leftarrow> Pi_pmf A dflt p; return_pmf (f(x := y))}\"\n  using assms\n  by (subst Pi_pmf_insert)\n     (auto simp add: map_pmf_def pair_pmf_def case_prod_beta' bind_return_pmf bind_assoc_pmf)\n\nlemma Pi_pmf_singleton:\n  \"Pi_pmf {x} dflt p = map_pmf (\\<lambda>a b. if b = x then a else dflt) (p x)\"\nproof -\n  have \"Pi_pmf {x} dflt p = map_pmf (fun_upd (\\<lambda>_. dflt) x) (p x)\"\n    by (subst Pi_pmf_insert) (simp_all add: pair_return_pmf2 pmf.map_comp o_def)\n  also have \"fun_upd (\\<lambda>_. dflt) x = (\\<lambda>z y. if y = x then z else dflt)\"\n    by (simp add: fun_upd_def fun_eq_iff)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Projecting a product of PMFs onto a component yields the expected result:\n\\<close>\nlemma Pi_pmf_component:\n  assumes \"finite A\"\n  shows   \"map_pmf (\\<lambda>f. f x) (Pi_pmf A dflt p) = (if x \\<in> A then p x else return_pmf dflt)\"\nproof (cases \"x \\<in> A\")\n  case True\n  define A' where \"A' = A - {x}\"\n  from assms and True have A': \"A = insert x A'\"\n    by (auto simp: A'_def)\n  from assms have \"map_pmf (\\<lambda>f. f x) (Pi_pmf A dflt p) = p x\" unfolding A'\n    by (subst Pi_pmf_insert)\n       (auto simp: A'_def pmf.map_comp o_def case_prod_unfold map_fst_pair_pmf)\n  with True show ?thesis by simp\nnext\n  case False\n  have \"map_pmf (\\<lambda>f. f x) (Pi_pmf A dflt p) = map_pmf (\\<lambda>_. dflt) (Pi_pmf A dflt p)\"\n    using assms False set_Pi_pmf_subset[of A dflt p]\n    by (intro pmf.map_cong refl) (auto simp: set_pmf_eq pmf_Pi_outside)\n  with False show ?thesis by simp\nqed\n\ntext \\<open>\n  We can take merge two PMF products on disjoint sets like this:\n\\<close>\nlemma Pi_pmf_union:\n  assumes \"finite A\" \"finite B\" \"A \\<inter> B = {}\"\n  shows   \"Pi_pmf (A \\<union> B) dflt p =\n             map_pmf (\\<lambda>(f,g) x. if x \\<in> A then f x else g x)\n             (pair_pmf (Pi_pmf A dflt p) (Pi_pmf B dflt p))\" (is \"_ = map_pmf (?h A) (?q A)\")\n  using assms(1,3)\nproof (induction rule: finite_induct)\n  case (insert x A)\n  have \"map_pmf (?h (insert x A)) (?q (insert x A)) =\n          do {v \\<leftarrow> p x; (f, g) \\<leftarrow> pair_pmf (Pi_pmf A dflt p) (Pi_pmf B dflt p);\n              return_pmf (\\<lambda>y. if y \\<in> insert x A then (f(x := v)) y else g y)}\"\n    by (subst Pi_pmf_insert)\n       (insert insert.hyps insert.prems,\n        simp_all add: pair_pmf_def map_bind_pmf bind_map_pmf bind_assoc_pmf bind_return_pmf)\n  also have \"\\<dots> = do {v \\<leftarrow> p x; (f, g) \\<leftarrow> ?q A; return_pmf ((?h A (f,g))(x := v))}\"\n    by (intro bind_pmf_cong refl) (auto simp: fun_eq_iff)\n  also have \"\\<dots> = do {v \\<leftarrow> p x; f \\<leftarrow> map_pmf (?h A) (?q A); return_pmf (f(x := v))}\"\n    by (simp add: bind_map_pmf map_bind_pmf case_prod_unfold cong: if_cong)\n  also have \"\\<dots> = do {v \\<leftarrow> p x; f \\<leftarrow> Pi_pmf (A \\<union> B) dflt p; return_pmf (f(x := v))}\"\n    using insert.hyps and insert.prems by (intro bind_pmf_cong insert.IH [symmetric] refl) auto\n  also have \"\\<dots> = Pi_pmf (insert x (A \\<union> B)) dflt p\"\n    by (subst Pi_pmf_insert)\n       (insert assms insert.hyps insert.prems, auto simp: pair_pmf_def map_bind_pmf)\n  also have \"insert x (A \\<union> B) = insert x A \\<union> B\"\n    by simp\n  finally show ?case ..\nqed (simp_all add: case_prod_unfold map_snd_pair_pmf)\n\ntext \\<open>\n  We can also project a product to a subset of the indices by mapping all the other\n  indices to the default value:\n\\<close>\nlemma Pi_pmf_subset:\n  assumes \"finite A\" \"A' \\<subseteq> A\"\n  shows   \"Pi_pmf A' dflt p = map_pmf (\\<lambda>f x. if x \\<in> A' then f x else dflt) (Pi_pmf A dflt p)\"\nproof -\n  let ?P = \"pair_pmf (Pi_pmf A' dflt p) (Pi_pmf (A - A') dflt p)\"\n  from assms have [simp]: \"finite A'\"\n    by (blast dest: finite_subset)\n  from assms have \"A = A' \\<union> (A - A')\"\n    by blast\n  also have \"Pi_pmf \\<dots> dflt p = map_pmf (\\<lambda>(f,g) x. if x \\<in> A' then f x else g x) ?P\"\n    using assms by (intro Pi_pmf_union) auto\n  also have \"map_pmf (\\<lambda>f x. if x \\<in> A' then f x else dflt) \\<dots> = map_pmf fst ?P\"\n    unfolding map_pmf_comp o_def case_prod_unfold\n    using set_Pi_pmf_subset[of A' dflt p] by (intro map_pmf_cong refl) (auto simp: fun_eq_iff)\n  also have \"\\<dots> = Pi_pmf A' dflt p\"\n    by (simp add: map_fst_pair_pmf)\n  finally show ?thesis ..\nqed\n\nlemma Pi_pmf_subset':\n  fixes f :: \"'a \\<Rightarrow> 'b pmf\"\n  assumes \"finite A\" \"B \\<subseteq> A\" \"\\<And>x. x \\<in> A - B \\<Longrightarrow> f x = return_pmf dflt\"\n  shows \"Pi_pmf A dflt f = Pi_pmf B dflt f\"\nproof -\n  have \"Pi_pmf (B \\<union> (A - B)) dflt f =\n          map_pmf (\\<lambda>(f, g) x. if x \\<in> B then f x else g x)\n                  (pair_pmf (Pi_pmf B dflt f) (Pi_pmf (A - B) dflt f))\"\n    using assms by (intro Pi_pmf_union) (auto dest: finite_subset)\n  also have \"Pi_pmf (A - B) dflt f = Pi_pmf (A - B) dflt (\\<lambda>_. return_pmf dflt)\"\n    using assms by (intro Pi_pmf_cong) auto\n  also have \"\\<dots> = return_pmf (\\<lambda>_. dflt)\"\n    using assms by simp\n  also have \"map_pmf (\\<lambda>(f, g) x. if x \\<in> B then f x else g x)\n                  (pair_pmf (Pi_pmf B dflt f) (return_pmf (\\<lambda>_. dflt))) =\n             map_pmf (\\<lambda>f x. if x \\<in> B then f x else dflt) (Pi_pmf B dflt f)\"\n    by (simp add: map_pmf_def pair_pmf_def bind_assoc_pmf bind_return_pmf bind_return_pmf')\n  also have \"\\<dots> = Pi_pmf B dflt f\"\n    using assms by (intro Pi_pmf_default_swap) (auto dest: finite_subset)\n  also have \"B \\<union> (A - B) = A\"\n    using assms by auto\n  finally show ?thesis .\nqed\n\nlemma Pi_pmf_if_set:\n  assumes \"finite A\"\n  shows \"Pi_pmf A dflt (\\<lambda>x. if b x then f x else return_pmf dflt) =\n           Pi_pmf {x\\<in>A. b x} dflt f\"\nproof -\n  have \"Pi_pmf A dflt (\\<lambda>x. if b x then f x else return_pmf dflt) =\n          Pi_pmf {x\\<in>A. b x} dflt (\\<lambda>x. if b x then f x else return_pmf dflt)\"\n    using assms by (intro Pi_pmf_subset') auto\n  also have \"\\<dots> = Pi_pmf {x\\<in>A. b x} dflt f\"\n    by (intro Pi_pmf_cong) auto\n  finally show ?thesis .\nqed\n\nlemma Pi_pmf_if_set':\n  assumes \"finite A\"\n  shows \"Pi_pmf A dflt (\\<lambda>x. if b x then return_pmf dflt else f x) =\n         Pi_pmf {x\\<in>A. \\<not>b x} dflt f\"\nproof -\n  have \"Pi_pmf A dflt (\\<lambda>x. if b x then return_pmf dflt else  f x) =\n          Pi_pmf {x\\<in>A. \\<not>b x} dflt (\\<lambda>x. if b x then return_pmf dflt else  f x)\"\n    using assms by (intro Pi_pmf_subset') auto\n  also have \"\\<dots> = Pi_pmf {x\\<in>A. \\<not>b x} dflt f\"\n    by (intro Pi_pmf_cong) auto\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Lastly, we can delete a single component from a product:\n\\<close>\nlemma Pi_pmf_remove:\n  assumes \"finite A\"\n  shows   \"Pi_pmf (A - {x}) dflt p = map_pmf (\\<lambda>f. f(x := dflt)) (Pi_pmf A dflt p)\"\nproof -\n  have \"Pi_pmf (A - {x}) dflt p =\n          map_pmf (\\<lambda>f xa. if xa \\<in> A - {x} then f xa else dflt) (Pi_pmf A dflt p)\"\n    using assms by (intro Pi_pmf_subset) auto\n  also have \"\\<dots> = map_pmf (\\<lambda>f. f(x := dflt)) (Pi_pmf A dflt p)\"\n    using set_Pi_pmf_subset[of A dflt p] assms\n    by (intro map_pmf_cong refl) (auto simp: fun_eq_iff)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Applications\\<close>\n\ntext \\<open>\n  Choosing a subset of a set uniformly at random is equivalent to tossing a fair coin\n  independently for each element and collecting all the elements that came up heads.\n\\<close>\nlemma pmf_of_set_Pow_conv_bernoulli:\n  assumes \"finite (A :: 'a set)\"\n  shows \"map_pmf (\\<lambda>b. {x\\<in>A. b x}) (Pi_pmf A P (\\<lambda>_. bernoulli_pmf (1/2))) = pmf_of_set (Pow A)\"\nproof -\n  have \"Pi_pmf A P (\\<lambda>_. bernoulli_pmf (1/2)) = pmf_of_set (PiE_dflt A P (\\<lambda>x. UNIV))\"\n    using assms by (simp add: bernoulli_pmf_half_conv_pmf_of_set Pi_pmf_of_set)\n  also have \"map_pmf (\\<lambda>b. {x\\<in>A. b x}) \\<dots> = pmf_of_set (Pow A)\"\n  proof -\n    have \"bij_betw (\\<lambda>b. {x \\<in> A. b x}) (PiE_dflt A P (\\<lambda>_. UNIV)) (Pow A)\"\n      by (rule bij_betwI[of _ _ _ \"\\<lambda>B b. if b \\<in> A then b \\<in> B else P\"]) (auto simp add: PiE_dflt_def)\n    then show ?thesis\n      using assms by (intro map_pmf_of_set_bij_betw) auto\n  qed\n  finally show ?thesis\n    by simp\nqed\n\ntext \\<open>\n  A binomial distribution can be seen as the number of successes in \\<open>n\\<close> independent coin tosses.\n\\<close>\nlemma binomial_pmf_altdef':\n  fixes A :: \"'a set\"\n  assumes \"finite A\" and \"card A = n\" and p: \"p \\<in> {0..1}\"\n  shows   \"binomial_pmf n p =\n             map_pmf (\\<lambda>f. card {x\\<in>A. f x}) (Pi_pmf A dflt (\\<lambda>_. bernoulli_pmf p))\" (is \"?lhs = ?rhs\")\nproof -\n  from assms have \"?lhs = binomial_pmf (card A) p\"\n    by simp\n  also have \"\\<dots> = ?rhs\"\n  using assms(1)\n  proof (induction rule: finite_induct)\n    case empty\n    with p show ?case by (simp add: binomial_pmf_0)\n  next\n    case (insert x A)\n    from insert.hyps have \"card (insert x A) = Suc (card A)\"\n      by simp\n    also have \"binomial_pmf \\<dots> p = do {\n                                     b \\<leftarrow> bernoulli_pmf p;\n                                     f \\<leftarrow> Pi_pmf A dflt (\\<lambda>_. bernoulli_pmf p);\n                                     return_pmf ((if b then 1 else 0) + card {y \\<in> A. f y})\n                                   }\"\n      using p by (simp add: binomial_pmf_Suc insert.IH bind_map_pmf)\n    also have \"\\<dots> = do {\n                      b \\<leftarrow> bernoulli_pmf p;\n                      f \\<leftarrow> Pi_pmf A dflt (\\<lambda>_. bernoulli_pmf p);\n                      return_pmf (card {y \\<in> insert x A. (f(x := b)) y})\n                    }\"\n    proof (intro bind_pmf_cong refl, goal_cases)\n      case (1 b f)\n      have \"(if b then 1 else 0) + card {y\\<in>A. f y} = card ((if b then {x} else {}) \\<union> {y\\<in>A. f y})\"\n        using insert.hyps by auto\n      also have \"(if b then {x} else {}) \\<union> {y\\<in>A. f y} = {y\\<in>insert x A. (f(x := b)) y}\"\n        using insert.hyps by auto\n      finally show ?case by simp\n    qed\n    also have \"\\<dots> = map_pmf (\\<lambda>f. card {y\\<in>insert x A. f y})\n                      (Pi_pmf (insert x A) dflt (\\<lambda>_. bernoulli_pmf p))\"\n      using insert.hyps by (subst Pi_pmf_insert) (simp_all add: pair_pmf_def map_bind_pmf)\n    finally show ?case .\n  qed\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Skip_Lists/Pi_pmf.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.8539127473751341, "lm_q1q2_score": 0.7615288273155439}}
{"text": "section \"Weights for Dijkstra's Algorithm\"\ntheory Weight\nimports Complex_Main\nbegin\n\ntext \\<open>\n  In this theory, we set up a type class for weights, and\n  a typeclass for weights with an infinity element. The latter\n  one is used internally in Dijkstra's algorithm.\n\n  Moreover, we provide a datatype that adds an infinity element to a given\n  base type.\n\\<close>\n\nsubsection \\<open>Type Classes Setup\\<close>\n\nclass weight = ordered_ab_semigroup_add + comm_monoid_add + linorder\nbegin\n\nlemma add_nonneg_nonneg [simp]:\n  assumes \"0 \\<le> a\" and \"0 \\<le> b\" shows \"0 \\<le> a + b\"\nproof -\n  have \"0 + 0 \\<le> a + b\" \n    using assms by (rule add_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_nonpos_nonpos[simp]:\n  assumes \"a \\<le> 0\" and \"b \\<le> 0\" shows \"a + b \\<le> 0\"\nproof -\n  have \"a + b \\<le> 0 + 0\"\n    using assms by (rule add_mono)\n  then show ?thesis by simp\nqed\n\nlemma add_nonneg_eq_0_iff:\n  assumes x: \"0 \\<le> x\" and y: \"0 \\<le> y\"\n  shows \"x + y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (metis local.add_0_left local.add_0_right local.add_left_mono local.antisym_conv x y)\n\nlemma add_incr: \"0\\<le>b \\<Longrightarrow> a \\<le> a+b\"\n  by (metis add.comm_neutral add_left_mono)\n\nlemma add_incr_left[simp, intro!]: \"0\\<le>b \\<Longrightarrow> a \\<le> b + a\"\n  by (metis add_incr add.commute)\n\nlemma sum_not_less[simp, intro!]: \n  \"0\\<le>b \\<Longrightarrow> \\<not> (a+b < a)\"\n  \"0\\<le>a \\<Longrightarrow> \\<not> (a+b < b)\"\n  apply (metis add_incr less_le_not_le)\n  apply (metis add_incr_left less_le_not_le)\n  done\n\nend\n\ninstance nat :: weight ..\ninstance int :: weight ..\ninstance rat :: weight ..\ninstance real :: weight ..\n\nterm top\n\n\nclass top_weight = order_top + weight +\n  assumes inf_add_right[simp]: \"a + top = top\"\nbegin\n\nlemma inf_add_left[simp]: \"top + a = top\"\n  by (metis add.commute inf_add_right)\n\nlemmas [simp] = top_unique less_top[symmetric]\n  \nlemma not_less_inf[simp]:\n  \"\\<not> (a < top) \\<longleftrightarrow> a=top\"\n  by simp\n  \nend\n\nsubsection \\<open>Adding Infinity\\<close>\ntext \\<open>\n  We provide a standard way to add an infinity element to any type.\n\\<close>\n\ndatatype 'a infty = Infty | Num 'a\n\nprimrec val where \"val (Num d) = d\"\n\nlemma num_val_iff[simp]: \"e\\<noteq>Infty \\<Longrightarrow> Num (val e) = e\" by (cases e) auto\n\ntype_synonym NatB = \"nat infty\"\n\ninstantiation infty :: (weight) top_weight\nbegin\n  definition \"(0::'a infty) == Num 0\"\n  definition \"top \\<equiv> Infty\"\n\n  fun less_eq_infty where\n    \"less_eq Infty (Num _) \\<longleftrightarrow> False\" |\n    \"less_eq _ Infty \\<longleftrightarrow> True\" |\n    \"less_eq (Num a) (Num b) \\<longleftrightarrow> a\\<le>b\"\n\n  \n\n  fun less_infty where\n    \"less Infty _ \\<longleftrightarrow> False\" |\n    \"less (Num _) Infty \\<longleftrightarrow> True\" |\n    \"less (Num a) (Num b) \\<longleftrightarrow> a<b\"\n\n  lemma [simp]: \"less a Infty \\<longleftrightarrow> a \\<noteq> Infty\"\n    by (cases a) auto\n\n  fun plus_infty where \n    \"plus _ Infty = Infty\" |\n    \"plus Infty _ = Infty\" |\n    \"plus (Num a) (Num b) = Num (a+b)\"\n\n  lemma [simp]: \"plus Infty a = Infty\" by (cases a) simp_all\n\n\n  instance\n    apply (intro_classes)\n    apply (case_tac [!] x) [4]\n    apply simp_all\n    apply (case_tac [!] y) [3]\n    apply (simp_all add: less_le_not_le)\n    apply (case_tac z)\n    apply (simp_all add: top_infty_def zero_infty_def)\n    apply (case_tac [!] a) [4]\n    apply simp_all\n    apply (case_tac [!] b) [3]\n    apply (simp_all add: ac_simps)\n    apply (case_tac [!] c) [2]\n    apply (simp_all add: ac_simps add_right_mono)\n    apply (case_tac \"(x,y)\" rule: less_eq_infty.cases)\n    apply (simp_all add: linear)\n    done\nend\n\nsubsubsection \\<open>Unboxing\\<close>\n\ntext \\<open>Conversion between the constants defined by the\n  typeclass, and the concrete functions on the @{typ \"'a infty\"} type. \n\\<close>\nlemma infty_inf_unbox:\n  \"Num a \\<noteq> top\"\n  \"top \\<noteq> Num a\"\n  \"Infty = top\"\n  by (auto simp add: top_infty_def)\n\nlemma infty_ord_unbox:\n  \"Num a \\<le> Num b \\<longleftrightarrow> a \\<le> b\"\n  \"Num a < Num b \\<longleftrightarrow> a < b\"\n  by auto\n\nlemma infty_plus_unbox:\n  \"Num a + Num b = Num (a+b)\"\n  by (auto)\n\nlemma infty_zero_unbox:\n  \"Num a = 0 \\<longleftrightarrow> a = 0\"\n  \"Num 0 = 0\"\n  by (auto simp: zero_infty_def)\n\nlemmas infty_unbox = \n  infty_inf_unbox infty_zero_unbox infty_ord_unbox infty_plus_unbox\n\nlemma inf_not_zero[simp]:\n  \"top\\<noteq>(0::_ infty)\" \"(0::_ infty)\\<noteq>top\"\n  apply (unfold zero_infty_def top_infty_def)\n  apply auto\n  done\n\nlemma num_val_iff'[simp]: \"e\\<noteq>top \\<Longrightarrow> Num (val e) = e\" \n  by (cases e) (auto simp add: infty_unbox)\n\nlemma infty_neE: \n  \"\\<lbrakk>a\\<noteq>Infty; \\<And>d. a=Num d \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  \"\\<lbrakk>a\\<noteq>top; \\<And>d. a=Num d \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by (case_tac [!] a) (auto simp add: infty_unbox)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Dijkstra_Shortest_Path/Weight.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110454379296, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7615288249226398}}
{"text": "(*  Title:      HOL/Fun.thy\n    Author:     Tobias Nipkow, Cambridge University Computer Laboratory\n    Author:     Andrei Popescu, TU Muenchen\n    Copyright   1994, 2012\n*)\n\nsection \\<open>Notions about functions\\<close>\n\ntheory Fun\n  imports Set\n  keywords \"functor\" :: thy_goal_defn\nbegin\n\nlemma apply_inverse: \"f x = u \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> g (f x) = x) \\<Longrightarrow> P x \\<Longrightarrow> x = g u\"\n  by auto\n\ntext \\<open>Uniqueness, so NOT the axiom of choice.\\<close>\nlemma uniq_choice: \"\\<forall>x. \\<exists>!y. Q x y \\<Longrightarrow> \\<exists>f. \\<forall>x. Q x (f x)\"\n  by (force intro: theI')\n\nlemma b_uniq_choice: \"\\<forall>x\\<in>S. \\<exists>!y. Q x y \\<Longrightarrow> \\<exists>f. \\<forall>x\\<in>S. Q x (f x)\"\n  by (force intro: theI')\n\n\nsubsection \\<open>The Identity Function \\<open>id\\<close>\\<close>\n\ndefinition id :: \"'a \\<Rightarrow> 'a\"\n  where \"id = (\\<lambda>x. x)\"\n\nlemma id_apply [simp]: \"id x = x\"\n  by (simp add: id_def)\n\nlemma image_id [simp]: \"image id = id\"\n  by (simp add: id_def fun_eq_iff)\n\nlemma vimage_id [simp]: \"vimage id = id\"\n  by (simp add: id_def fun_eq_iff)\n\nlemma eq_id_iff: \"(\\<forall>x. f x = x) \\<longleftrightarrow> f = id\"\n  by auto\n\ncode_printing\n  constant id \\<rightharpoonup> (Haskell) \"id\"\n\n\nsubsection \\<open>The Composition Operator \\<open>f \\<circ> g\\<close>\\<close>\n\ndefinition comp :: \"('b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'c\"  (infixl \"\\<circ>\" 55)\n  where \"f \\<circ> g = (\\<lambda>x. f (g x))\"\n\nnotation (ASCII)\n  comp  (infixl \"o\" 55)\n\nlemma comp_apply [simp]: \"(f \\<circ> g) x = f (g x)\"\n  by (simp add: comp_def)\n\nlemma comp_assoc: \"(f \\<circ> g) \\<circ> h = f \\<circ> (g \\<circ> h)\"\n  by (simp add: fun_eq_iff)\n\nlemma id_comp [simp]: \"id \\<circ> g = g\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_id [simp]: \"f \\<circ> id = f\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_eq_dest: \"a \\<circ> b = c \\<circ> d \\<Longrightarrow> a (b v) = c (d v)\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_eq_elim: \"a \\<circ> b = c \\<circ> d \\<Longrightarrow> ((\\<And>v. a (b v) = c (d v)) \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by (simp add: fun_eq_iff)\n\nlemma comp_eq_dest_lhs: \"a \\<circ> b = c \\<Longrightarrow> a (b v) = c v\"\n  by clarsimp\n\nlemma comp_eq_id_dest: \"a \\<circ> b = id \\<circ> c \\<Longrightarrow> a (b v) = c v\"\n  by clarsimp\n\nlemma image_comp: \"f ` (g ` r) = (f \\<circ> g) ` r\"\n  by auto\n\nlemma vimage_comp: \"f -` (g -` x) = (g \\<circ> f) -` x\"\n  by auto\n\nlemma image_eq_imp_comp: \"f ` A = g ` B \\<Longrightarrow> (h \\<circ> f) ` A = (h \\<circ> g) ` B\"\n  by (auto simp: comp_def elim!: equalityE)\n\nlemma image_bind: \"f ` (Set.bind A g) = Set.bind A ((`) f \\<circ> g)\"\n  by (auto simp add: Set.bind_def)\n\nlemma bind_image: \"Set.bind (f ` A) g = Set.bind A (g \\<circ> f)\"\n  by (auto simp add: Set.bind_def)\n\nlemma (in group_add) minus_comp_minus [simp]: \"uminus \\<circ> uminus = id\"\n  by (simp add: fun_eq_iff)\n\nlemma (in boolean_algebra) minus_comp_minus [simp]: \"uminus \\<circ> uminus = id\"\n  by (simp add: fun_eq_iff)\n\ncode_printing\n  constant comp \\<rightharpoonup> (SML) infixl 5 \"o\" and (Haskell) infixr 9 \".\"\n\n\nsubsection \\<open>The Forward Composition Operator \\<open>fcomp\\<close>\\<close>\n\ndefinition fcomp :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'c) \\<Rightarrow> 'a \\<Rightarrow> 'c\"  (infixl \"\\<circ>>\" 60)\n  where \"f \\<circ>> g = (\\<lambda>x. g (f x))\"\n\nlemma fcomp_apply [simp]:  \"(f \\<circ>> g) x = g (f x)\"\n  by (simp add: fcomp_def)\n\nlemma fcomp_assoc: \"(f \\<circ>> g) \\<circ>> h = f \\<circ>> (g \\<circ>> h)\"\n  by (simp add: fcomp_def)\n\nlemma id_fcomp [simp]: \"id \\<circ>> g = g\"\n  by (simp add: fcomp_def)\n\nlemma fcomp_id [simp]: \"f \\<circ>> id = f\"\n  by (simp add: fcomp_def)\n\nlemma fcomp_comp: \"fcomp f g = comp g f\"\n  by (simp add: ext)\n\ncode_printing\n  constant fcomp \\<rightharpoonup> (Eval) infixl 1 \"#>\"\n\nno_notation fcomp (infixl \"\\<circ>>\" 60)\n\n\nsubsection \\<open>Mapping functions\\<close>\n\ndefinition map_fun :: \"('c \\<Rightarrow> 'a) \\<Rightarrow> ('b \\<Rightarrow> 'd) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'c \\<Rightarrow> 'd\"\n  where \"map_fun f g h = g \\<circ> h \\<circ> f\"\n\nlemma map_fun_apply [simp]: \"map_fun f g h x = g (h (f x))\"\n  by (simp add: map_fun_def)\n\n\nsubsection \\<open>Injectivity and Bijectivity\\<close>\n\ndefinition inj_on :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> bool\"  \\<comment> \\<open>injective\\<close>\n  where \"inj_on f A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. f x = f y \\<longrightarrow> x = y)\"\n\ndefinition bij_betw :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> bool\"  \\<comment> \\<open>bijective\\<close>\n  where \"bij_betw f A B \\<longleftrightarrow> inj_on f A \\<and> f ` A = B\"\n\ntext \\<open>\n  A common special case: functions injective, surjective or bijective over\n  the entire domain type.\n\\<close>\n\nabbreviation inj :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"inj f \\<equiv> inj_on f UNIV\"\n\nabbreviation surj :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"surj f \\<equiv> range f = UNIV\"\n\ntranslations \\<comment> \\<open>The negated case:\\<close>\n  \"\\<not> CONST surj f\" \\<leftharpoondown> \"CONST range f \\<noteq> CONST UNIV\"\n\nabbreviation bij :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"bij f \\<equiv> bij_betw f UNIV UNIV\"\n\nlemma inj_def: \"inj f \\<longleftrightarrow> (\\<forall>x y. f x = f y \\<longrightarrow> x = y)\"\n  unfolding inj_on_def by blast\n\nlemma injI: \"(\\<And>x y. f x = f y \\<Longrightarrow> x = y) \\<Longrightarrow> inj f\"\n  unfolding inj_def by blast\n\ntheorem range_ex1_eq: \"inj f \\<Longrightarrow> b \\<in> range f \\<longleftrightarrow> (\\<exists>!x. b = f x)\"\n  unfolding inj_def by blast\n\nlemma injD: \"inj f \\<Longrightarrow> f x = f y \\<Longrightarrow> x = y\"\n  by (simp add: inj_def)\n\nlemma inj_on_eq_iff: \"inj_on f A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x = f y \\<longleftrightarrow> x = y\"\n  by (auto simp: inj_on_def)\n\nlemma inj_on_cong: \"(\\<And>a. a \\<in> A \\<Longrightarrow> f a = g a) \\<Longrightarrow> inj_on f A \\<longleftrightarrow> inj_on g A\"\n  by (auto simp: inj_on_def)\n\nlemma image_strict_mono: \"inj_on f B \\<Longrightarrow> A \\<subset> B \\<Longrightarrow> f ` A \\<subset> f ` B\"\n  unfolding inj_on_def by blast\n\nlemma inj_compose: \"inj f \\<Longrightarrow> inj g \\<Longrightarrow> inj (f \\<circ> g)\"\n  by (simp add: inj_def)\n\nlemma inj_fun: \"inj f \\<Longrightarrow> inj (\\<lambda>x y. f x)\"\n  by (simp add: inj_def fun_eq_iff)\n\nlemma inj_eq: \"inj f \\<Longrightarrow> f x = f y \\<longleftrightarrow> x = y\"\n  by (simp add: inj_on_eq_iff)\n\nlemma inj_on_iff_Uniq: \"inj_on f A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<exists>\\<^sub>\\<le>\\<^sub>1y. y\\<in>A \\<and> f x = f y)\"\n  by (auto simp: Uniq_def inj_on_def)\n\nlemma inj_on_id[simp]: \"inj_on id A\"\n  by (simp add: inj_on_def)\n\nlemma inj_on_id2[simp]: \"inj_on (\\<lambda>x. x) A\"\n  by (simp add: inj_on_def)\n\nlemma inj_on_Int: \"inj_on f A \\<or> inj_on f B \\<Longrightarrow> inj_on f (A \\<inter> B)\"\n  unfolding inj_on_def by blast\n\nlemma surj_id: \"surj id\"\n  by simp\n\nlemma bij_id[simp]: \"bij id\"\n  by (simp add: bij_betw_def)\n\nlemma bij_uminus: \"bij (uminus :: 'a \\<Rightarrow> 'a::group_add)\"\n  unfolding bij_betw_def inj_on_def\n  by (force intro: minus_minus [symmetric])\n\nlemma bij_betwE: \"bij_betw f A B \\<Longrightarrow> \\<forall>a\\<in>A. f a \\<in> B\"\n  unfolding bij_betw_def by auto\n\nlemma inj_onI [intro?]: \"(\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x = f y \\<Longrightarrow> x = y) \\<Longrightarrow> inj_on f A\"\n  by (simp add: inj_on_def)\n\nlemma inj_on_inverseI: \"(\\<And>x. x \\<in> A \\<Longrightarrow> g (f x) = x) \\<Longrightarrow> inj_on f A\"\n  by (auto dest: arg_cong [of concl: g] simp add: inj_on_def)\n\nlemma inj_onD: \"inj_on f A \\<Longrightarrow> f x = f y \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> x = y\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_subset:\n  assumes \"inj_on f A\"\n    and \"B \\<subseteq> A\"\n  shows \"inj_on f B\"\nproof (rule inj_onI)\n  fix a b\n  assume \"a \\<in> B\" and \"b \\<in> B\"\n  with assms have \"a \\<in> A\" and \"b \\<in> A\"\n    by auto\n  moreover assume \"f a = f b\"\n  ultimately show \"a = b\"\n    using assms by (auto dest: inj_onD)\nqed\n\nlemma comp_inj_on: \"inj_on f A \\<Longrightarrow> inj_on g (f ` A) \\<Longrightarrow> inj_on (g \\<circ> f) A\"\n  by (simp add: comp_def inj_on_def)\n\nlemma inj_on_imageI: \"inj_on (g \\<circ> f) A \\<Longrightarrow> inj_on g (f ` A)\"\n  by (auto simp add: inj_on_def)\n\nlemma inj_on_image_iff:\n  \"\\<forall>x\\<in>A. \\<forall>y\\<in>A. g (f x) = g (f y) \\<longleftrightarrow> g x = g y \\<Longrightarrow> inj_on f A \\<Longrightarrow> inj_on g (f ` A) \\<longleftrightarrow> inj_on g A\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_contraD: \"inj_on f A \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> f x \\<noteq> f y\"\n  unfolding inj_on_def by blast\n\nlemma inj_singleton [simp]: \"inj_on (\\<lambda>x. {x}) A\"\n  by (simp add: inj_on_def)\n\nlemma inj_on_empty[iff]: \"inj_on f {}\"\n  by (simp add: inj_on_def)\n\nlemma subset_inj_on: \"inj_on f B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> inj_on f A\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_Un: \"inj_on f (A \\<union> B) \\<longleftrightarrow> inj_on f A \\<and> inj_on f B \\<and> f ` (A - B) \\<inter> f ` (B - A) = {}\"\n  unfolding inj_on_def by (blast intro: sym)\n\nlemma inj_on_insert [iff]: \"inj_on f (insert a A) \\<longleftrightarrow> inj_on f A \\<and> f a \\<notin> f ` (A - {a})\"\n  unfolding inj_on_def by (blast intro: sym)\n\nlemma inj_on_diff: \"inj_on f A \\<Longrightarrow> inj_on f (A - B)\"\n  unfolding inj_on_def by blast\n\nlemma comp_inj_on_iff: \"inj_on f A \\<Longrightarrow> inj_on f' (f ` A) \\<longleftrightarrow> inj_on (f' \\<circ> f) A\"\n  by (auto simp: comp_inj_on inj_on_def)\n\nlemma inj_on_imageI2: \"inj_on (f' \\<circ> f) A \\<Longrightarrow> inj_on f A\"\n  by (auto simp: comp_inj_on inj_on_def)\n\nlemma inj_img_insertE:\n  assumes \"inj_on f A\"\n  assumes \"x \\<notin> B\"\n    and \"insert x B = f ` A\"\n  obtains x' A' where \"x' \\<notin> A'\" and \"A = insert x' A'\" and \"x = f x'\" and \"B = f ` A'\"\nproof -\n  from assms have \"x \\<in> f ` A\" by auto\n  then obtain x' where *: \"x' \\<in> A\" \"x = f x'\" by auto\n  then have A: \"A = insert x' (A - {x'})\" by auto\n  with assms * have B: \"B = f ` (A - {x'})\" by (auto dest: inj_on_contraD)\n  have \"x' \\<notin> A - {x'}\" by simp\n  from this A \\<open>x = f x'\\<close> B show ?thesis ..\nqed\n\nlemma linorder_inj_onI:\n  fixes A :: \"'a::order set\"\n  assumes ne: \"\\<And>x y. \\<lbrakk>x < y; x\\<in>A; y\\<in>A\\<rbrakk> \\<Longrightarrow> f x \\<noteq> f y\" and lin: \"\\<And>x y. \\<lbrakk>x\\<in>A; y\\<in>A\\<rbrakk> \\<Longrightarrow> x\\<le>y \\<or> y\\<le>x\"\n  shows \"inj_on f A\"\nproof (rule inj_onI)\n  fix x y\n  assume eq: \"f x = f y\" and \"x\\<in>A\" \"y\\<in>A\"\n  then show \"x = y\"\n    using lin [of x y] ne by (force simp: dual_order.order_iff_strict)\nqed\n\nlemma linorder_inj_onI':\n  fixes A :: \"'a :: linorder set\"\n  assumes \"\\<And>i j. i \\<in> A \\<Longrightarrow> j \\<in> A \\<Longrightarrow> i < j \\<Longrightarrow> f i \\<noteq> f j\"\n  shows   \"inj_on f A\"\n  by (intro linorder_inj_onI) (auto simp add: assms)\n\nlemma linorder_injI:\n  assumes \"\\<And>x y::'a::linorder. x < y \\<Longrightarrow> f x \\<noteq> f y\"\n  shows \"inj f\"\n    \\<comment> \\<open>Courtesy of Stephan Merz\\<close>\nusing assms by (simp add: linorder_inj_onI')\n\nlemma inj_on_image_Pow: \"inj_on f A \\<Longrightarrow>inj_on (image f) (Pow A)\"\n  unfolding Pow_def inj_on_def by blast\n\nlemma bij_betw_image_Pow: \"bij_betw f A B \\<Longrightarrow> bij_betw (image f) (Pow A) (Pow B)\"\n  by (auto simp add: bij_betw_def inj_on_image_Pow image_Pow_surj)\n\nlemma surj_def: \"surj f \\<longleftrightarrow> (\\<forall>y. \\<exists>x. y = f x)\"\n  by auto\n\nlemma surjI:\n  assumes \"\\<And>x. g (f x) = x\"\n  shows \"surj g\"\n  using assms [symmetric] by auto\n\nlemma surjD: \"surj f \\<Longrightarrow> \\<exists>x. y = f x\"\n  by (simp add: surj_def)\n\nlemma surjE: \"surj f \\<Longrightarrow> (\\<And>x. y = f x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (simp add: surj_def) blast\n\nlemma comp_surj: \"surj f \\<Longrightarrow> surj g \\<Longrightarrow> surj (g \\<circ> f)\"\n  using image_comp [of g f UNIV] by simp\n\nlemma bij_betw_imageI: \"inj_on f A \\<Longrightarrow> f ` A = B \\<Longrightarrow> bij_betw f A B\"\n  unfolding bij_betw_def by clarify\n\nlemma bij_betw_imp_surj_on: \"bij_betw f A B \\<Longrightarrow> f ` A = B\"\n  unfolding bij_betw_def by clarify\n\nlemma bij_betw_imp_surj: \"bij_betw f A UNIV \\<Longrightarrow> surj f\"\n  unfolding bij_betw_def by auto\n\nlemma bij_betw_empty1: \"bij_betw f {} A \\<Longrightarrow> A = {}\"\n  unfolding bij_betw_def by blast\n\nlemma bij_betw_empty2: \"bij_betw f A {} \\<Longrightarrow> A = {}\"\n  unfolding bij_betw_def by blast\n\nlemma inj_on_imp_bij_betw: \"inj_on f A \\<Longrightarrow> bij_betw f A (f ` A)\"\n  unfolding bij_betw_def by simp\n\nlemma bij_betw_DiffI:\n  assumes \"bij_betw f A B\" \"bij_betw f C D\" \"C \\<subseteq> A\" \"D \\<subseteq> B\"\n  shows   \"bij_betw f (A - C) (B - D)\"\n  using assms unfolding bij_betw_def inj_on_def by auto\n\nlemma bij_betw_singleton_iff [simp]: \"bij_betw f {x} {y} \\<longleftrightarrow> f x = y\"\n  by (auto simp: bij_betw_def)\n\nlemma bij_betw_singletonI [intro]: \"f x = y \\<Longrightarrow> bij_betw f {x} {y}\"\n  by auto\n\nlemma bij_betw_apply: \"\\<lbrakk>bij_betw f A B; a \\<in> A\\<rbrakk> \\<Longrightarrow> f a \\<in> B\"\n  unfolding bij_betw_def by auto\n\nlemma bij_def: \"bij f \\<longleftrightarrow> inj f \\<and> surj f\"\n  by (rule bij_betw_def)\n\nlemma bijI: \"inj f \\<Longrightarrow> surj f \\<Longrightarrow> bij f\"\n  by (rule bij_betw_imageI)\n\nlemma bij_is_inj: \"bij f \\<Longrightarrow> inj f\"\n  by (simp add: bij_def)\n\nlemma bij_is_surj: \"bij f \\<Longrightarrow> surj f\"\n  by (simp add: bij_def)\n\nlemma bij_betw_imp_inj_on: \"bij_betw f A B \\<Longrightarrow> inj_on f A\"\n  by (simp add: bij_betw_def)\n\nlemma bij_betw_trans: \"bij_betw f A B \\<Longrightarrow> bij_betw g B C \\<Longrightarrow> bij_betw (g \\<circ> f) A C\"\n  by (auto simp add:bij_betw_def comp_inj_on)\n\nlemma bij_comp: \"bij f \\<Longrightarrow> bij g \\<Longrightarrow> bij (g \\<circ> f)\"\n  by (rule bij_betw_trans)\n\nlemma bij_betw_comp_iff: \"bij_betw f A A' \\<Longrightarrow> bij_betw f' A' A'' \\<longleftrightarrow> bij_betw (f' \\<circ> f) A A''\"\n  by (auto simp add: bij_betw_def inj_on_def)\n\nlemma bij_betw_comp_iff2:\n  assumes bij: \"bij_betw f' A' A''\"\n    and img: \"f ` A \\<le> A'\"\n  shows \"bij_betw f A A' \\<longleftrightarrow> bij_betw (f' \\<circ> f) A A''\" (is \"?L \\<longleftrightarrow> ?R\")\nproof\n  assume \"?L\"\n  then show \"?R\"\n    using assms by (auto simp add: bij_betw_comp_iff)\n  next\n    assume *: \"?R\"\n    have \"inj_on (f' \\<circ> f) A \\<Longrightarrow> inj_on f A\"\n      using inj_on_imageI2 by blast\n    moreover have \"A' \\<subseteq> f ` A\"\n    proof\n      fix a'\n      assume **: \"a' \\<in> A'\"\n      with bij have \"f' a' \\<in> A''\"\n        unfolding bij_betw_def by auto\n      with * obtain a where 1: \"a \\<in> A \\<and> f' (f a) = f' a'\"\n        unfolding bij_betw_def by force\n      with img have \"f a \\<in> A'\" by auto\n      with bij ** 1 have \"f a = a'\"\n        unfolding bij_betw_def inj_on_def by auto\n      with 1 show \"a' \\<in> f ` A\" by auto\n    qed\n    ultimately show \"?L\"\n      using img * by (auto simp add: bij_betw_def)\nqed\n\nlemma bij_betw_inv:\n  assumes \"bij_betw f A B\"\n  shows \"\\<exists>g. bij_betw g B A\"\nproof -\n  have i: \"inj_on f A\" and s: \"f ` A = B\"\n    using assms by (auto simp: bij_betw_def)\n  let ?P = \"\\<lambda>b a. a \\<in> A \\<and> f a = b\"\n  let ?g = \"\\<lambda>b. The (?P b)\"\n  have g: \"?g b = a\" if P: \"?P b a\" for a b\n  proof -\n    from that s have ex1: \"\\<exists>a. ?P b a\" by blast\n    then have uex1: \"\\<exists>!a. ?P b a\" by (blast dest:inj_onD[OF i])\n    then show ?thesis\n      using the1_equality[OF uex1, OF P] P by simp\n  qed\n  have \"inj_on ?g B\"\n  proof (rule inj_onI)\n    fix x y\n    assume \"x \\<in> B\" \"y \\<in> B\" \"?g x = ?g y\"\n    from s \\<open>x \\<in> B\\<close> obtain a1 where a1: \"?P x a1\" by blast\n    from s \\<open>y \\<in> B\\<close> obtain a2 where a2: \"?P y a2\" by blast\n    from g [OF a1] a1 g [OF a2] a2 \\<open>?g x = ?g y\\<close> show \"x = y\" by simp\n  qed\n  moreover have \"?g ` B = A\"\n  proof safe\n    fix b\n    assume \"b \\<in> B\"\n    with s obtain a where P: \"?P b a\" by blast\n    with g[OF P] show \"?g b \\<in> A\" by auto\n  next\n    fix a\n    assume \"a \\<in> A\"\n    with s obtain b where P: \"?P b a\" by blast\n    with s have \"b \\<in> B\" by blast\n    with g[OF P] have \"\\<exists>b\\<in>B. a = ?g b\" by blast\n    then show \"a \\<in> ?g ` B\"\n      by auto\n  qed\n  ultimately show ?thesis\n    by (auto simp: bij_betw_def)\nqed\n\nlemma bij_betw_cong: \"(\\<And>a. a \\<in> A \\<Longrightarrow> f a = g a) \\<Longrightarrow> bij_betw f A A' = bij_betw g A A'\"\n  unfolding bij_betw_def inj_on_def by safe force+  (* somewhat slow *)\n\nlemma bij_betw_id[intro, simp]: \"bij_betw id A A\"\n  unfolding bij_betw_def id_def by auto\n\nlemma bij_betw_id_iff: \"bij_betw id A B \\<longleftrightarrow> A = B\"\n  by (auto simp add: bij_betw_def)\n\nlemma bij_betw_combine:\n  \"bij_betw f A B \\<Longrightarrow> bij_betw f C D \\<Longrightarrow> B \\<inter> D = {} \\<Longrightarrow> bij_betw f (A \\<union> C) (B \\<union> D)\"\n  unfolding bij_betw_def inj_on_Un image_Un by auto\n\nlemma bij_betw_subset: \"bij_betw f A A' \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> f ` B = B' \\<Longrightarrow> bij_betw f B B'\"\n  by (auto simp add: bij_betw_def inj_on_def)\n\nlemma bij_betw_ball: \"bij_betw f A B \\<Longrightarrow> (\\<forall>b \\<in> B. phi b) = (\\<forall>a \\<in> A. phi (f a))\"\n  unfolding bij_betw_def inj_on_def by blast\n\nlemma bij_pointE:\n  assumes \"bij f\"\n  obtains x where \"y = f x\" and \"\\<And>x'. y = f x' \\<Longrightarrow> x' = x\"\nproof -\n  from assms have \"inj f\" by (rule bij_is_inj)\n  moreover from assms have \"surj f\" by (rule bij_is_surj)\n  then have \"y \\<in> range f\" by simp\n  ultimately have \"\\<exists>!x. y = f x\" by (simp add: range_ex1_eq)\n  with that show thesis by blast\nqed\n\nlemma bij_iff: \\<^marker>\\<open>contributor \\<open>Amine Chaieb\\<close>\\<close>\n  \\<open>bij f \\<longleftrightarrow> (\\<forall>x. \\<exists>!y. f y = x)\\<close>  (is \\<open>?P \\<longleftrightarrow> ?Q\\<close>)\nproof\n  assume ?P\n  then have \\<open>inj f\\<close> \\<open>surj f\\<close>\n    by (simp_all add: bij_def)\n  show ?Q\n  proof\n    fix y\n    from \\<open>surj f\\<close> obtain x where \\<open>y = f x\\<close>\n      by (auto simp add: surj_def)\n    with \\<open>inj f\\<close> show \\<open>\\<exists>!x. f x = y\\<close>\n      by (auto simp add: inj_def)\n  qed\nnext\n  assume ?Q\n  then have \\<open>inj f\\<close>\n    by (auto simp add: inj_def)\n  moreover have \\<open>\\<exists>x. y = f x\\<close> for y\n  proof -\n    from \\<open>?Q\\<close> obtain x where \\<open>f x = y\\<close>\n      by blast\n    then have \\<open>y = f x\\<close>\n      by simp\n    then show ?thesis ..\n  qed\n  then have \\<open>surj f\\<close>\n    by (auto simp add: surj_def)\n  ultimately show ?P\n    by (rule bijI)\nqed\n\nlemma bij_betw_partition:\n  \\<open>bij_betw f A B\\<close>\n  if \\<open>bij_betw f (A \\<union> C) (B \\<union> D)\\<close> \\<open>bij_betw f C D\\<close> \\<open>A \\<inter> C = {}\\<close> \\<open>B \\<inter> D = {}\\<close>\nproof -\n  from that have \\<open>inj_on f (A \\<union> C)\\<close> \\<open>inj_on f C\\<close> \\<open>f ` (A \\<union> C) = B \\<union> D\\<close> \\<open>f ` C = D\\<close>\n    by (simp_all add: bij_betw_def)\n  then have \\<open>inj_on f A\\<close> and \\<open>f ` (A - C) \\<inter> f ` (C - A) = {}\\<close>\n    by (simp_all add: inj_on_Un)\n  with \\<open>A \\<inter> C = {}\\<close> have \\<open>f ` A \\<inter> f ` C = {}\\<close>\n    by auto\n  with \\<open>f ` (A \\<union> C) = B \\<union> D\\<close> \\<open>f ` C = D\\<close>  \\<open>B \\<inter> D = {}\\<close>\n  have \\<open>f ` A = B\\<close>\n    by blast\n  with \\<open>inj_on f A\\<close> show ?thesis\n    by (simp add: bij_betw_def)\nqed\n\nlemma surj_image_vimage_eq: \"surj f \\<Longrightarrow> f ` (f -` A) = A\"\n  by simp\n\nlemma surj_vimage_empty:\n  assumes \"surj f\"\n  shows \"f -` A = {} \\<longleftrightarrow> A = {}\"\n  using surj_image_vimage_eq [OF \\<open>surj f\\<close>, of A]\n  by (intro iffI) fastforce+\n\nlemma inj_vimage_image_eq: \"inj f \\<Longrightarrow> f -` (f ` A) = A\"\n  unfolding inj_def by blast\n\nlemma vimage_subsetD: \"surj f \\<Longrightarrow> f -` B \\<subseteq> A \\<Longrightarrow> B \\<subseteq> f ` A\"\n  by (blast intro: sym)\n\nlemma vimage_subsetI: \"inj f \\<Longrightarrow> B \\<subseteq> f ` A \\<Longrightarrow> f -` B \\<subseteq> A\"\n  unfolding inj_def by blast\n\nlemma vimage_subset_eq: \"bij f \\<Longrightarrow> f -` B \\<subseteq> A \\<longleftrightarrow> B \\<subseteq> f ` A\"\n  unfolding bij_def by (blast del: subsetI intro: vimage_subsetI vimage_subsetD)\n\nlemma inj_on_image_eq_iff: \"inj_on f C \\<Longrightarrow> A \\<subseteq> C \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> f ` A = f ` B \\<longleftrightarrow> A = B\"\n  by (fastforce simp: inj_on_def)\n\nlemma inj_on_Un_image_eq_iff: \"inj_on f (A \\<union> B) \\<Longrightarrow> f ` A = f ` B \\<longleftrightarrow> A = B\"\n  by (erule inj_on_image_eq_iff) simp_all\n\nlemma inj_on_image_Int: \"inj_on f C \\<Longrightarrow> A \\<subseteq> C \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> f ` (A \\<inter> B) = f ` A \\<inter> f ` B\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_image_set_diff: \"inj_on f C \\<Longrightarrow> A - B \\<subseteq> C \\<Longrightarrow> B \\<subseteq> C \\<Longrightarrow> f ` (A - B) = f ` A - f ` B\"\n  unfolding inj_on_def by blast\n\nlemma image_Int: \"inj f \\<Longrightarrow> f ` (A \\<inter> B) = f ` A \\<inter> f ` B\"\n  unfolding inj_def by blast\n\nlemma image_set_diff: \"inj f \\<Longrightarrow> f ` (A - B) = f ` A - f ` B\"\n  unfolding inj_def by blast\n\nlemma inj_on_image_mem_iff: \"inj_on f B \\<Longrightarrow> a \\<in> B \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f a \\<in> f ` A \\<longleftrightarrow> a \\<in> A\"\n  by (auto simp: inj_on_def)\n\nlemma inj_image_mem_iff: \"inj f \\<Longrightarrow> f a \\<in> f ` A \\<longleftrightarrow> a \\<in> A\"\n  by (blast dest: injD)\n\nlemma inj_image_subset_iff: \"inj f \\<Longrightarrow> f ` A \\<subseteq> f ` B \\<longleftrightarrow> A \\<subseteq> B\"\n  by (blast dest: injD)\n\nlemma inj_image_eq_iff: \"inj f \\<Longrightarrow> f ` A = f ` B \\<longleftrightarrow> A = B\"\n  by (blast dest: injD)\n\nlemma surj_Compl_image_subset: \"surj f \\<Longrightarrow> - (f ` A) \\<subseteq> f ` (- A)\"\n  by auto\n\nlemma inj_image_Compl_subset: \"inj f \\<Longrightarrow> f ` (- A) \\<subseteq> - (f ` A)\"\n  by (auto simp: inj_def)\n\nlemma bij_image_Compl_eq: \"bij f \\<Longrightarrow> f ` (- A) = - (f ` A)\"\n  by (simp add: bij_def inj_image_Compl_subset surj_Compl_image_subset equalityI)\n\nlemma inj_vimage_singleton: \"inj f \\<Longrightarrow> f -` {a} \\<subseteq> {THE x. f x = a}\"\n  \\<comment> \\<open>The inverse image of a singleton under an injective function is included in a singleton.\\<close>\n  by (simp add: inj_def) (blast intro: the_equality [symmetric])\n\nlemma inj_on_vimage_singleton: \"inj_on f A \\<Longrightarrow> f -` {a} \\<inter> A \\<subseteq> {THE x. x \\<in> A \\<and> f x = a}\"\n  by (auto simp add: inj_on_def intro: the_equality [symmetric])\n\nlemma bij_betw_byWitness:\n  assumes left: \"\\<forall>a \\<in> A. f' (f a) = a\"\n    and right: \"\\<forall>a' \\<in> A'. f (f' a') = a'\"\n    and \"f ` A \\<subseteq> A'\"\n    and img2: \"f' ` A' \\<subseteq> A\"\n  shows \"bij_betw f A A'\"\n  using assms\n  unfolding bij_betw_def inj_on_def\nproof safe\n  fix a b\n  assume \"a \\<in> A\" \"b \\<in> A\"\n  with left have \"a = f' (f a) \\<and> b = f' (f b)\" by simp\n  moreover assume \"f a = f b\"\n  ultimately show \"a = b\" by simp\nnext\n  fix a' assume *: \"a' \\<in> A'\"\n  with img2 have \"f' a' \\<in> A\" by blast\n  moreover from * right have \"a' = f (f' a')\" by simp\n  ultimately show \"a' \\<in> f ` A\" by blast\nqed\n\ncorollary notIn_Un_bij_betw:\n  assumes \"b \\<notin> A\"\n    and \"f b \\<notin> A'\"\n    and \"bij_betw f A A'\"\n  shows \"bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\nproof -\n  have \"bij_betw f {b} {f b}\"\n    unfolding bij_betw_def inj_on_def by simp\n  with assms show ?thesis\n    using bij_betw_combine[of f A A' \"{b}\" \"{f b}\"] by blast\nqed\n\nlemma notIn_Un_bij_betw3:\n  assumes \"b \\<notin> A\"\n    and \"f b \\<notin> A'\"\n  shows \"bij_betw f A A' = bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\nproof\n  assume \"bij_betw f A A'\"\n  then show \"bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\n    using assms notIn_Un_bij_betw [of b A f A'] by blast\nnext\n  assume *: \"bij_betw f (A \\<union> {b}) (A' \\<union> {f b})\"\n  have \"f ` A = A'\"\n  proof safe\n    fix a\n    assume **: \"a \\<in> A\"\n    then have \"f a \\<in> A' \\<union> {f b}\"\n      using * unfolding bij_betw_def by blast\n    moreover\n    have False if \"f a = f b\"\n    proof -\n      have \"a = b\"\n        using * ** that unfolding bij_betw_def inj_on_def by blast\n      with \\<open>b \\<notin> A\\<close> ** show ?thesis by blast\n    qed\n    ultimately show \"f a \\<in> A'\" by blast\n  next\n    fix a'\n    assume **: \"a' \\<in> A'\"\n    then have \"a' \\<in> f ` (A \\<union> {b})\"\n      using * by (auto simp add: bij_betw_def)\n    then obtain a where 1: \"a \\<in> A \\<union> {b} \\<and> f a = a'\" by blast\n    moreover\n    have False if \"a = b\" using 1 ** \\<open>f b \\<notin> A'\\<close> that by blast\n    ultimately have \"a \\<in> A\" by blast\n    with 1 show \"a' \\<in> f ` A\" by blast\n  qed\n  then show \"bij_betw f A A'\"\n    using * bij_betw_subset[of f \"A \\<union> {b}\" _ A] by blast\nqed\n\nlemma inj_on_disjoint_Un:\n  assumes \"inj_on f A\" and \"inj_on g B\" \n  and \"f ` A \\<inter> g ` B = {}\"\n  shows \"inj_on (\\<lambda>x. if x \\<in> A then f x else g x) (A \\<union> B)\"\n  using assms by (simp add: inj_on_def disjoint_iff) (blast)\n\nlemma bij_betw_disjoint_Un:\n  assumes \"bij_betw f A C\" and \"bij_betw g B D\" \n  and \"A \\<inter> B = {}\"\n  and \"C \\<inter> D = {}\"\n  shows \"bij_betw (\\<lambda>x. if x \\<in> A then f x else g x) (A \\<union> B) (C \\<union> D)\"\n  using assms by (auto simp: inj_on_disjoint_Un bij_betw_def)\n\nlemma involuntory_imp_bij:\n  \\<open>bij f\\<close> if \\<open>\\<And>x. f (f x) = x\\<close>\nproof (rule bijI)\n  from that show \\<open>surj f\\<close>\n    by (rule surjI)\n  show \\<open>inj f\\<close>\n  proof (rule injI)\n    fix x y\n    assume \\<open>f x = f y\\<close>\n    then have \\<open>f (f x) = f (f y)\\<close>\n      by simp\n    then show \\<open>x = y\\<close>\n      by (simp add: that)\n  qed\nqed\n\n\nsubsubsection \\<open>Inj/surj/bij of Algebraic Operations\\<close>\n\ncontext cancel_semigroup_add\nbegin\n\nlemma inj_on_add [simp]:\n  \"inj_on ((+) a) A\"\n  by (rule inj_onI) simp\n\nlemma inj_on_add' [simp]:\n  \"inj_on (\\<lambda>b. b + a) A\"\n  by (rule inj_onI) simp\n\nlemma bij_betw_add [simp]:\n  \"bij_betw ((+) a) A B \\<longleftrightarrow> (+) a ` A = B\"\n  by (simp add: bij_betw_def)\n\nend\n\ncontext group_add\nbegin\n\nlemma diff_left_imp_eq: \"a - b = a - c \\<Longrightarrow> b = c\"\nunfolding add_uminus_conv_diff[symmetric]\nby(drule local.add_left_imp_eq) simp\n\nlemma inj_uminus[simp, intro]: \"inj_on uminus A\"\n  by (auto intro!: inj_onI)\n\nlemma surj_uminus[simp]: \"surj uminus\"\nusing surjI minus_minus by blast\n\nlemma surj_plus [simp]:\n  \"surj ((+) a)\"\nproof (standard, simp, standard, simp)\n  fix x\n  have \"x = a + (-a + x)\" by (simp add: add.assoc)\n  thus \"x \\<in> range ((+) a)\" by blast\nqed\n\nlemma surj_plus_right [simp]:\n  \"surj (\\<lambda>b. b+a)\"\nproof (standard, simp, standard, simp)\n  fix b show \"b \\<in> range (\\<lambda>b. b+a)\"\n    using diff_add_cancel[of b a, symmetric] by blast\nqed\n\nlemma inj_on_diff_left [simp]:\n  \\<open>inj_on ((-) a) A\\<close>\nby (auto intro: inj_onI dest!: diff_left_imp_eq)\n\nlemma inj_on_diff_right [simp]:\n  \\<open>inj_on (\\<lambda>b. b - a) A\\<close>\nby (auto intro: inj_onI simp add: algebra_simps)\n\nlemma surj_diff [simp]:\n  \"surj ((-) a)\"\nproof (standard, simp, standard, simp)\n  fix x\n  have \"x = a - (- x + a)\" by (simp add: algebra_simps)\n  thus \"x \\<in> range ((-) a)\" by blast\nqed\n\nlemma surj_diff_right [simp]:\n  \"surj (\\<lambda>x. x - a)\"\nproof (standard, simp, standard, simp)\n  fix x\n  have \"x = x + a - a\" by simp\n  thus \"x \\<in> range (\\<lambda>x. x - a)\" by fast\nqed\n\nlemma shows bij_plus: \"bij ((+) a)\" and bij_plus_right: \"bij (\\<lambda>x. x + a)\"\n  and bij_uminus: \"bij uminus\"\n  and bij_diff: \"bij ((-) a)\" and bij_diff_right: \"bij (\\<lambda>x. x - a)\"\nby(simp_all add: bij_def)\n\nlemma translation_subtract_Compl:\n  \"(\\<lambda>x. x - a) ` (- t) = - ((\\<lambda>x. x - a) ` t)\"\nby(rule bij_image_Compl_eq)\n  (auto simp add: bij_def surj_def inj_def diff_eq_eq intro!: add_diff_cancel[symmetric])\n\nlemma translation_diff:\n  \"(+) a ` (s - t) = ((+) a ` s) - ((+) a ` t)\"\n  by auto\n\nlemma translation_subtract_diff:\n  \"(\\<lambda>x. x - a) ` (s - t) = ((\\<lambda>x. x - a) ` s) - ((\\<lambda>x. x - a) ` t)\"\nby(rule image_set_diff)(simp add: inj_on_def diff_eq_eq)\n\nlemma translation_Int:\n  \"(+) a ` (s \\<inter> t) = ((+) a ` s) \\<inter> ((+) a ` t)\"\n  by auto\n\nlemma translation_subtract_Int:\n  \"(\\<lambda>x. x - a) ` (s \\<inter> t) = ((\\<lambda>x. x - a) ` s) \\<inter> ((\\<lambda>x. x - a) ` t)\"\nby(rule image_Int)(simp add: inj_on_def diff_eq_eq)\n\nend\n\n(* TODO: prove in group_add *)\ncontext ab_group_add\nbegin\n\nlemma translation_Compl:\n  \"(+) a ` (- t) = - ((+) a ` t)\"\nproof (rule set_eqI)\n  fix b\n  show \"b \\<in> (+) a ` (- t) \\<longleftrightarrow> b \\<in> - (+) a ` t\"\n    by (auto simp: image_iff algebra_simps intro!: bexI [of _ \"b - a\"])\nqed\n\nend\n\n\nsubsection \\<open>Function Updating\\<close>\n\ndefinition fun_upd :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> ('a \\<Rightarrow> 'b)\"\n  where \"fun_upd f a b = (\\<lambda>x. if x = a then b else f x)\"\n\nnonterminal updbinds and updbind\n\nsyntax\n  \"_updbind\" :: \"'a \\<Rightarrow> 'a \\<Rightarrow> updbind\"             (\"(2_ :=/ _)\")\n  \"\"         :: \"updbind \\<Rightarrow> updbinds\"             (\"_\")\n  \"_updbinds\":: \"updbind \\<Rightarrow> updbinds \\<Rightarrow> updbinds\" (\"_,/ _\")\n  \"_Update\"  :: \"'a \\<Rightarrow> updbinds \\<Rightarrow> 'a\"            (\"_/'((_)')\" [1000, 0] 900)\n\ntranslations\n  \"_Update f (_updbinds b bs)\" \\<rightleftharpoons> \"_Update (_Update f b) bs\"\n  \"f(x:=y)\" \\<rightleftharpoons> \"CONST fun_upd f x y\"\n\n(* Hint: to define the sum of two functions (or maps), use case_sum.\n         A nice infix syntax could be defined by\nnotation\n  case_sum  (infixr \"'(+')\"80)\n*)\n\nlemma fun_upd_idem_iff: \"f(x:=y) = f \\<longleftrightarrow> f x = y\"\n  unfolding fun_upd_def\n  apply safe\n   apply (erule subst)\n   apply auto\n  done\n\nlemma fun_upd_idem: \"f x = y \\<Longrightarrow> f(x := y) = f\"\n  by (simp only: fun_upd_idem_iff)\n\nlemma fun_upd_triv [iff]: \"f(x := f x) = f\"\n  by (simp only: fun_upd_idem)\n\nlemma fun_upd_apply [simp]: \"(f(x := y)) z = (if z = x then y else f z)\"\n  by (simp add: fun_upd_def)\n\n(* fun_upd_apply supersedes these two, but they are useful\n   if fun_upd_apply is intentionally removed from the simpset *)\nlemma fun_upd_same: \"(f(x := y)) x = y\"\n  by simp\n\nlemma fun_upd_other: \"z \\<noteq> x \\<Longrightarrow> (f(x := y)) z = f z\"\n  by simp\n\nlemma fun_upd_upd [simp]: \"f(x := y, x := z) = f(x := z)\"\n  by (simp add: fun_eq_iff)\n\nlemma fun_upd_twist: \"a \\<noteq> c \\<Longrightarrow> (m(a := b))(c := d) = (m(c := d))(a := b)\"\n  by auto\n\nlemma inj_on_fun_updI: \"inj_on f A \\<Longrightarrow> y \\<notin> f ` A \\<Longrightarrow> inj_on (f(x := y)) A\"\n  by (auto simp: inj_on_def)\n\nlemma fun_upd_image: \"f(x := y) ` A = (if x \\<in> A then insert y (f ` (A - {x})) else f ` A)\"\n  by auto\n\nlemma fun_upd_comp: \"f \\<circ> (g(x := y)) = (f \\<circ> g)(x := f y)\"\n  by auto\n\nlemma fun_upd_eqD: \"f(x := y) = g(x := z) \\<Longrightarrow> y = z\"\n  by (simp add: fun_eq_iff split: if_split_asm)\n\n\nsubsection \\<open>\\<open>override_on\\<close>\\<close>\n\ndefinition override_on :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where \"override_on f g A = (\\<lambda>a. if a \\<in> A then g a else f a)\"\n\nlemma override_on_emptyset[simp]: \"override_on f g {} = f\"\n  by (simp add: override_on_def)\n\nlemma override_on_apply_notin[simp]: \"a \\<notin> A \\<Longrightarrow> (override_on f g A) a = f a\"\n  by (simp add: override_on_def)\n\nlemma override_on_apply_in[simp]: \"a \\<in> A \\<Longrightarrow> (override_on f g A) a = g a\"\n  by (simp add: override_on_def)\n\nlemma override_on_insert: \"override_on f g (insert x X) = (override_on f g X)(x:=g x)\"\n  by (simp add: override_on_def fun_eq_iff)\n\nlemma override_on_insert': \"override_on f g (insert x X) = (override_on (f(x:=g x)) g X)\"\n  by (simp add: override_on_def fun_eq_iff)\n\n\nsubsection \\<open>Inversion of injective functions\\<close>\n\ndefinition the_inv_into :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a)\"\n  where \"the_inv_into A f = (\\<lambda>x. THE y. y \\<in> A \\<and> f y = x)\"\n\nlemma the_inv_into_f_f: \"inj_on f A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> the_inv_into A f (f x) = x\"\n  unfolding the_inv_into_def inj_on_def by blast\n\nlemma f_the_inv_into_f: \"inj_on f A \\<Longrightarrow> y \\<in> f ` A  \\<Longrightarrow> f (the_inv_into A f y) = y\"\n  unfolding the_inv_into_def\n  by (rule the1I2; blast dest: inj_onD)\n\nlemma f_the_inv_into_f_bij_betw:\n  \"bij_betw f A B \\<Longrightarrow> (bij_betw f A B \\<Longrightarrow> x \\<in> B) \\<Longrightarrow> f (the_inv_into A f x) = x\"\n  unfolding bij_betw_def by (blast intro: f_the_inv_into_f)\n\nlemma the_inv_into_into: \"inj_on f A \\<Longrightarrow> x \\<in> f ` A \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> the_inv_into A f x \\<in> B\"\n  unfolding the_inv_into_def\n  by (rule the1I2; blast dest: inj_onD)\n\nlemma the_inv_into_onto [simp]: \"inj_on f A \\<Longrightarrow> the_inv_into A f ` (f ` A) = A\"\n  by (fast intro: the_inv_into_into the_inv_into_f_f [symmetric])\n\nlemma the_inv_into_f_eq: \"inj_on f A \\<Longrightarrow> f x = y \\<Longrightarrow> x \\<in> A \\<Longrightarrow> the_inv_into A f y = x\"\n  by (force simp add: the_inv_into_f_f)\n\nlemma the_inv_into_comp:\n  \"inj_on f (g ` A) \\<Longrightarrow> inj_on g A \\<Longrightarrow> x \\<in> f ` g ` A \\<Longrightarrow>\n    the_inv_into A (f \\<circ> g) x = (the_inv_into A g \\<circ> the_inv_into (g ` A) f) x\"\n  apply (rule the_inv_into_f_eq)\n    apply (fast intro: comp_inj_on)\n   apply (simp add: f_the_inv_into_f the_inv_into_into)\n  apply (simp add: the_inv_into_into)\n  done\n\nlemma inj_on_the_inv_into: \"inj_on f A \\<Longrightarrow> inj_on (the_inv_into A f) (f ` A)\"\n  by (auto intro: inj_onI simp: the_inv_into_f_f)\n\nlemma bij_betw_the_inv_into: \"bij_betw f A B \\<Longrightarrow> bij_betw (the_inv_into A f) B A\"\n  by (auto simp add: bij_betw_def inj_on_the_inv_into the_inv_into_into)\n\nlemma bij_betw_iff_bijections:\n  \"bij_betw f A B \\<longleftrightarrow> (\\<exists>g. (\\<forall>x \\<in> A. f x \\<in> B \\<and> g(f x) = x) \\<and> (\\<forall>y \\<in> B. g y \\<in> A \\<and> f(g y) = y))\"\n  (is \"?lhs = ?rhs\")\nproof\n  show \"?lhs \\<Longrightarrow> ?rhs\"\n    by (auto simp: bij_betw_def f_the_inv_into_f the_inv_into_f_f the_inv_into_into\n        exI[where ?x=\"the_inv_into A f\"])\nnext\n  show \"?rhs \\<Longrightarrow> ?lhs\"\n    by (force intro: bij_betw_byWitness)\nqed\n\nabbreviation the_inv :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> ('b \\<Rightarrow> 'a)\"\n  where \"the_inv f \\<equiv> the_inv_into UNIV f\"\n\nlemma the_inv_f_f: \"the_inv f (f x) = x\" if \"inj f\"\n  using that UNIV_I by (rule the_inv_into_f_f)\n\n\nsubsection \\<open>Monotonicity\\<close>\n\ndefinition monotone_on :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"monotone_on A orda ordb f \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. orda x y \\<longrightarrow> ordb (f x) (f y))\"\n\nabbreviation monotone :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"monotone \\<equiv> monotone_on UNIV\"\n\nlemma monotone_def[no_atp]: \"monotone orda ordb f \\<longleftrightarrow> (\\<forall>x y. orda x y \\<longrightarrow> ordb (f x) (f y))\"\n  by (simp add: monotone_on_def)\n\ntext \\<open>Lemma @{thm [source] monotone_def} is provided for backward compatibility.\\<close>\n\nlemma monotone_onI:\n  \"(\\<And>x y. x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> orda x y \\<Longrightarrow> ordb (f x) (f y)) \\<Longrightarrow> monotone_on A orda ordb f\"\n  by (simp add: monotone_on_def)\n\nlemma monotoneI[intro?]: \"(\\<And>x y. orda x y \\<Longrightarrow> ordb (f x) (f y)) \\<Longrightarrow> monotone orda ordb f\"\n  by (rule monotone_onI)\n\nlemma monotone_onD:\n  \"monotone_on A orda ordb f \\<Longrightarrow> x \\<in> A \\<Longrightarrow> y \\<in> A \\<Longrightarrow> orda x y \\<Longrightarrow> ordb (f x) (f y)\"\n  by (simp add: monotone_on_def)\n\nlemma monotoneD[dest?]: \"monotone orda ordb f \\<Longrightarrow> orda x y \\<Longrightarrow> ordb (f x) (f y)\"\n  by (rule monotone_onD[of UNIV, simplified])\n\nlemma monotone_on_subset: \"monotone_on A orda ordb f \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> monotone_on B orda ordb f\"\n  by (auto intro: monotone_onI dest: monotone_onD)\n\nlemma monotone_on_empty[simp]: \"monotone_on {} orda ordb f\"\n  by (auto intro: monotone_onI dest: monotone_onD)\n\nlemma monotone_on_o:\n  assumes\n    mono_f: \"monotone_on A orda ordb f\" and\n    mono_g: \"monotone_on B ordc orda g\" and\n    \"g ` B \\<subseteq> A\"\n  shows \"monotone_on B ordc ordb (f \\<circ> g)\"\nproof (rule monotone_onI)\n  fix x y assume \"x \\<in> B\" and \"y \\<in> B\" and \"ordc x y\"\n  hence \"orda (g x) (g y)\"\n    by (rule mono_g[THEN monotone_onD])\n  moreover from \\<open>g ` B \\<subseteq> A\\<close> \\<open>x \\<in> B\\<close> \\<open>y \\<in> B\\<close> have \"g x \\<in> A\" and \"g y \\<in> A\"\n    unfolding image_subset_iff by simp_all\n  ultimately show \"ordb ((f \\<circ> g) x) ((f \\<circ> g) y)\"\n    using mono_f[THEN monotone_onD] by simp\nqed\n\n\nsubsubsection \\<open>Specializations For @{class ord} Type Class And More\\<close>\n\ncontext ord begin\n\nabbreviation mono_on :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b :: ord) \\<Rightarrow> bool\"\n  where \"mono_on A \\<equiv> monotone_on A (\\<le>) (\\<le>)\"\n\nabbreviation strict_mono_on :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b :: ord) \\<Rightarrow> bool\"\n  where \"strict_mono_on A \\<equiv> monotone_on A (<) (<)\"\n\nlemma mono_on_def[no_atp]: \"mono_on A f \\<longleftrightarrow> (\\<forall>r s. r \\<in> A \\<and> s \\<in> A \\<and> r \\<le> s \\<longrightarrow> f r \\<le> f s)\"\n  by (auto simp add: monotone_on_def)\n\nlemma strict_mono_on_def[no_atp]:\n  \"strict_mono_on A f \\<longleftrightarrow> (\\<forall>r s. r \\<in> A \\<and> s \\<in> A \\<and> r < s \\<longrightarrow> f r < f s)\"\n  by (auto simp add: monotone_on_def)\n\ntext \\<open>Lemmas @{thm [source] mono_on_def} and @{thm [source] strict_mono_on_def} are provided for\nbackward compatibility.\\<close>\n\nlemma mono_onI:\n  \"(\\<And>r s. r \\<in> A \\<Longrightarrow> s \\<in> A \\<Longrightarrow> r \\<le> s \\<Longrightarrow> f r \\<le> f s) \\<Longrightarrow> mono_on A f\"\n  by (rule monotone_onI)\n\nlemma strict_mono_onI:\n  \"(\\<And>r s. r \\<in> A \\<Longrightarrow> s \\<in> A \\<Longrightarrow> r < s \\<Longrightarrow> f r < f s) \\<Longrightarrow> strict_mono_on A f\"\n  by (rule monotone_onI)\n\nlemma mono_onD: \"\\<lbrakk>mono_on A f; r \\<in> A; s \\<in> A; r \\<le> s\\<rbrakk> \\<Longrightarrow> f r \\<le> f s\"\n  by (rule monotone_onD)\n\nlemma strict_mono_onD: \"\\<lbrakk>strict_mono_on A f; r \\<in> A; s \\<in> A; r < s\\<rbrakk> \\<Longrightarrow> f r < f s\"\n  by (rule monotone_onD)\n\nlemma mono_on_subset: \"mono_on A f \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> mono_on B f\"\n  by (rule monotone_on_subset)\n\nend\n\nlemma mono_on_greaterD:\n  assumes \"mono_on A g\" \"x \\<in> A\" \"y \\<in> A\" \"g x > (g (y::_::linorder) :: _ :: linorder)\"\n  shows \"x > y\"\nproof (rule ccontr)\n  assume \"\\<not>x > y\"\n  hence \"x \\<le> y\" by (simp add: not_less)\n  from assms(1-3) and this have \"g x \\<le> g y\" by (rule mono_onD)\n  with assms(4) show False by simp\nqed\n\ncontext order begin\n\nabbreviation mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\"\n  where \"mono \\<equiv> mono_on UNIV\"\n\nabbreviation strict_mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\"\n  where \"strict_mono \\<equiv> strict_mono_on UNIV\"\n\nabbreviation antimono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\"\n  where \"antimono \\<equiv> monotone (\\<le>) (\\<lambda>x y. y \\<le> x)\"\n\nlemma mono_def[no_atp]: \"mono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n  by (simp add: monotone_on_def)\n\nlemma strict_mono_def[no_atp]: \"strict_mono f \\<longleftrightarrow> (\\<forall>x y. x < y \\<longrightarrow> f x < f y)\"\n  by (simp add: monotone_on_def)\n\nlemma antimono_def[no_atp]: \"antimono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<ge> f y)\"\n  by (simp add: monotone_on_def)\n\ntext \\<open>Lemmas @{thm [source] mono_def}, @{thm [source] strict_mono_def}, and\n@{thm [source] antimono_def} are provided for backward compatibility.\\<close>\n\nlemma monoI [intro?]: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> mono f\"\n  by (rule monotoneI)\n\nlemma strict_monoI [intro?]: \"(\\<And>x y. x < y \\<Longrightarrow> f x < f y) \\<Longrightarrow> strict_mono f\"\n  by (rule monotoneI)\n\nlemma antimonoI [intro?]: \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> antimono f\"\n  by (rule monotoneI)\n\nlemma monoD [dest?]: \"mono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  by (rule monotoneD)\n\nlemma strict_monoD [dest?]: \"strict_mono f \\<Longrightarrow> x < y \\<Longrightarrow> f x < f y\"\n  by (rule monotoneD)\n\nlemma antimonoD [dest?]: \"antimono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  by (rule monotoneD)\n\nlemma monoE:\n  assumes \"mono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<le> f y\"\nproof\n  from assms show \"f x \\<le> f y\" by (simp add: mono_def)\nqed\n\nlemma antimonoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"antimono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<ge> f y\"\nproof\n  from assms show \"f x \\<ge> f y\" by (simp add: antimono_def)\nqed\n\nlemma mono_imp_mono_on: \"mono f \\<Longrightarrow> mono_on A f\"\n  by (rule monotone_on_subset[OF _ subset_UNIV])\n\nlemma strict_mono_mono [dest?]:\n  assumes \"strict_mono f\"\n  shows \"mono f\"\nproof (rule monoI)\n  fix x y\n  assume \"x \\<le> y\"\n  show \"f x \\<le> f y\"\n  proof (cases \"x = y\")\n    case True then show ?thesis by simp\n  next\n    case False with \\<open>x \\<le> y\\<close> have \"x < y\" by simp\n    with assms strict_monoD have \"f x < f y\" by auto\n    then show ?thesis by simp\n\n  qed\nqed\n\nend\n\ncontext linorder begin\n\nlemma mono_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x \\<le> y\"\nproof\n  show \"x \\<le> y\"\n  proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma mono_strict_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x < y\"\nproof\n  show \"x < y\"\n  proof (rule ccontr)\n    assume \"\\<not> x < y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_eq:\n  assumes \"strict_mono f\"\n  shows \"f x = f y \\<longleftrightarrow> x = y\"\nproof\n  assume \"f x = f y\"\n  show \"x = y\" proof (cases x y rule: linorder_cases)\n    case less with assms strict_monoD have \"f x < f y\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  next\n    case equal then show ?thesis .\n  next\n    case greater with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  qed\nqed simp\n\nlemma strict_mono_less_eq:\n  assumes \"strict_mono f\"\n  shows \"f x \\<le> f y \\<longleftrightarrow> x \\<le> y\"\nproof\n  assume \"x \\<le> y\"\n  with assms strict_mono_mono monoD show \"f x \\<le> f y\" by auto\nnext\n  assume \"f x \\<le> f y\"\n  show \"x \\<le> y\" proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\" then have \"y < x\" by simp\n    with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x \\<le> f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_less:\n  assumes \"strict_mono f\"\n  shows \"f x < f y \\<longleftrightarrow> x < y\"\n  using assms\n    by (auto simp add: less_le Orderings.less_le strict_mono_eq strict_mono_less_eq)\n\nend\n\nlemma strict_mono_inv:\n  fixes f :: \"('a::linorder) \\<Rightarrow> ('b::linorder)\"\n  assumes \"strict_mono f\" and \"surj f\" and inv: \"\\<And>x. g (f x) = x\"\n  shows \"strict_mono g\"\nproof\n  fix x y :: 'b assume \"x < y\"\n  from \\<open>surj f\\<close> obtain x' y' where [simp]: \"x = f x'\" \"y = f y'\" by blast\n  with \\<open>x < y\\<close> and \\<open>strict_mono f\\<close> have \"x' < y'\" by (simp add: strict_mono_less)\n  with inv show \"g x < g y\" by simp\nqed\n\n\n\nlemma strict_mono_on_leD:\n  assumes \"strict_mono_on A (f :: (_ :: linorder) \\<Rightarrow> _ :: preorder)\" \"x \\<in> A\" \"y \\<in> A\" \"x \\<le> y\"\n  shows \"f x \\<le> f y\"\nproof (cases \"x = y\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  with assms have \"f x < f y\"\n    using strict_mono_onD[OF assms(1)] by simp\n  then show ?thesis by (rule less_imp_le)\nqed\n\nlemma strict_mono_on_eqD:\n  fixes f :: \"(_ :: linorder) \\<Rightarrow> (_ :: preorder)\"\n  assumes \"strict_mono_on A f\" \"f x = f y\" \"x \\<in> A\" \"y \\<in> A\"\n  shows \"y = x\"\n  using assms by (cases rule: linorder_cases) (auto dest: strict_mono_onD)\n\nlemma strict_mono_on_imp_mono_on:\n  \"strict_mono_on A (f :: (_ :: linorder) \\<Rightarrow> _ :: preorder) \\<Longrightarrow> mono_on A f\"\n  by (rule mono_onI, rule strict_mono_on_leD)\n\nlemma mono_compose: \"mono Q \\<Longrightarrow> mono (\\<lambda>i x. Q i (f x))\"\n  unfolding mono_def le_fun_def by auto\n\nlemma mono_add:\n  fixes a :: \"'a::ordered_ab_semigroup_add\" \n  shows \"mono ((+) a)\"\n  by (simp add: add_left_mono monoI)\n\nlemma (in semilattice_inf) mono_inf: \"mono f \\<Longrightarrow> f (A \\<sqinter> B) \\<le> f A \\<sqinter> f B\"\n  for f :: \"'a \\<Rightarrow> 'b::semilattice_inf\"\n  by (auto simp add: mono_def intro: Lattices.inf_greatest)\n\nlemma (in semilattice_sup) mono_sup: \"mono f \\<Longrightarrow> f A \\<squnion> f B \\<le> f (A \\<squnion> B)\"\n  for f :: \"'a \\<Rightarrow> 'b::semilattice_sup\"\n  by (auto simp add: mono_def intro: Lattices.sup_least)\n\nlemma (in linorder) min_of_mono: \"mono f \\<Longrightarrow> min (f m) (f n) = f (min m n)\"\n  by (auto simp: mono_def Orderings.min_def min_def intro: Orderings.antisym)\n\nlemma (in linorder) max_of_mono: \"mono f \\<Longrightarrow> max (f m) (f n) = f (max m n)\"\n  by (auto simp: mono_def Orderings.max_def max_def intro: Orderings.antisym)\n\nlemma (in linorder)\n  max_of_antimono: \"antimono f \\<Longrightarrow> max (f x) (f y) = f (min x y)\" and\n  min_of_antimono: \"antimono f \\<Longrightarrow> min (f x) (f y) = f (max x y)\"\n  by (auto simp: antimono_def Orderings.max_def max_def Orderings.min_def min_def intro!: antisym)\n\nlemma (in linorder) strict_mono_imp_inj_on: \"strict_mono f \\<Longrightarrow> inj_on f A\"\n  by (auto intro!: inj_onI dest: strict_mono_eq)\n\nlemma mono_Int: \"mono f \\<Longrightarrow> f (A \\<inter> B) \\<subseteq> f A \\<inter> f B\"\n  by (fact mono_inf)\n\nlemma mono_Un: \"mono f \\<Longrightarrow> f A \\<union> f B \\<subseteq> f (A \\<union> B)\"\n  by (fact mono_sup)\n\n\nsubsubsection \\<open>Least value operator\\<close>\n\nlemma Least_mono: \"mono f \\<Longrightarrow> \\<exists>x\\<in>S. \\<forall>y\\<in>S. x \\<le> y \\<Longrightarrow> (LEAST y. y \\<in> f ` S) = f (LEAST x. x \\<in> S)\"\n  for f :: \"'a::order \\<Rightarrow> 'b::order\"\n  \\<comment> \\<open>Courtesy of Stephan Merz\\<close>\n  apply clarify\n  apply (erule_tac P = \"\\<lambda>x. x \\<in> S\" in LeastI2_order)\n   apply fast\n  apply (rule LeastI2_order)\n    apply (auto elim: monoD intro!: order_antisym)\n  done\n\n\nsubsection \\<open>Setup\\<close>\n\nsubsubsection \\<open>Proof tools\\<close>\n\ntext \\<open>Simplify terms of the form \\<open>f(\\<dots>,x:=y,\\<dots>,x:=z,\\<dots>)\\<close> to \\<open>f(\\<dots>,x:=z,\\<dots>)\\<close>\\<close>\n\nsimproc_setup fun_upd2 (\"f(v := w, x := y)\") = \\<open>fn _ =>\n  let\n    fun gen_fun_upd NONE T _ _ = NONE\n      | gen_fun_upd (SOME f) T x y = SOME (Const (\\<^const_name>\\<open>fun_upd\\<close>, T) $ f $ x $ y)\n    fun dest_fun_T1 (Type (_, T :: Ts)) = T\n    fun find_double (t as Const (\\<^const_name>\\<open>fun_upd\\<close>,T) $ f $ x $ y) =\n      let\n        fun find (Const (\\<^const_name>\\<open>fun_upd\\<close>,T) $ g $ v $ w) =\n              if v aconv x then SOME g else gen_fun_upd (find g) T v w\n          | find t = NONE\n      in (dest_fun_T1 T, gen_fun_upd (find f) T x y) end\n\n    val ss = simpset_of \\<^context>\n\n    fun proc ctxt ct =\n      let\n        val t = Thm.term_of ct\n      in\n        (case find_double t of\n          (T, NONE) => NONE\n        | (T, SOME rhs) =>\n            SOME (Goal.prove ctxt [] [] (Logic.mk_equals (t, rhs))\n              (fn _ =>\n                resolve_tac ctxt [eq_reflection] 1 THEN\n                resolve_tac ctxt @{thms ext} 1 THEN\n                simp_tac (put_simpset ss ctxt) 1)))\n      end\n  in proc end\n\\<close>\n\n\nsubsubsection \\<open>Functorial structure of types\\<close>\n\nML_file \\<open>Tools/functor.ML\\<close>\n\nfunctor map_fun: map_fun\n  by (simp_all add: fun_eq_iff)\n\nfunctor vimage\n  by (simp_all add: fun_eq_iff vimage_comp)\n\n\ntext \\<open>Legacy theorem names\\<close>\n\nlemmas o_def = comp_def\nlemmas o_apply = comp_apply\nlemmas o_assoc = comp_assoc [symmetric]\nlemmas id_o = id_comp\nlemmas o_id = comp_id\nlemmas o_eq_dest = comp_eq_dest\nlemmas o_eq_elim = comp_eq_elim\nlemmas o_eq_dest_lhs = comp_eq_dest_lhs\nlemmas o_eq_id_dest = comp_eq_id_dest\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.8856314768368161, "lm_q1q2_score": 0.761345286499802}}
{"text": "theory Chapter10_2_Typechecking\nimports Chapter10_1_Language\nbegin\n\ninductive typecheck :: \"type env => expr => type => bool\"\nwhere tc_var [simp]: \"lookup gam x = Some t ==> typecheck gam (Var x) t\"\n    | tc_zero [simp]: \"typecheck gam Zero Nat\"\n    | tc_suc [simp]: \"typecheck gam e Nat ==> typecheck gam (Suc e) Nat\"\n    | tc_rec [simp]: \"typecheck gam et Nat ==> typecheck gam e0 t ==> \n                typecheck (extend (extend gam t) Nat) es t ==> typecheck gam (Rec et e0 es) t\"\n    | tc_lam [simp]: \"typecheck (extend gam t1) e t2 ==> typecheck gam (Lam t1 e) (Arrow t1 t2)\"\n    | tc_appl [simp]: \"typecheck gam e1 (Arrow t2 t) ==> typecheck gam e2 t2 ==> \n                typecheck gam (Appl e1 e2) t\"\n    | tc_triv [simp]: \"typecheck gam Triv Unit\"\n    | tc_pair [simp]: \"typecheck gam e1 t1 ==> typecheck gam e2 t2 ==> \n                typecheck gam (Pair e1 e2) (Prod t1 t2)\"\n    | tc_projl [simp]: \"typecheck gam e (Prod t1 t2) ==> typecheck gam (ProjL e) t1\"\n    | tc_projr [simp]: \"typecheck gam e (Prod t1 t2) ==> typecheck gam (ProjR e) t2\"\n\ninductive_cases [elim!]: \"typecheck gam (Var x) t\"\ninductive_cases [elim!]: \"typecheck gam Zero t\"\ninductive_cases [elim!]: \"typecheck gam (Suc e) t\"\ninductive_cases [elim!]: \"typecheck gam (Rec et e0 es) t\"\ninductive_cases [elim!]: \"typecheck gam (Lam t1 e) t\"\ninductive_cases [elim!]: \"typecheck gam (Appl e1 e2) t\"\ninductive_cases [elim!]: \"typecheck gam Triv t\"\ninductive_cases [elim!]: \"typecheck gam (Pair e1 e2) t\"\ninductive_cases [elim!]: \"typecheck gam (ProjL e) t\"\ninductive_cases [elim!]: \"typecheck gam (ProjR e) t\"\n\n\n\nlemma [simp]: \"typecheck (extend_at n gam t') e t ==> n in gam ==> typecheck gam e' t' ==> \n                  typecheck gam (subst e' n e) t\"\nby (induction \"extend_at n gam t'\" e t arbitrary: n gam t' e' rule: typecheck.induct, fastforce+)\n\nend\n", "meta": {"author": "xtreme-james-cooper", "repo": "Harper", "sha": "ec2c52a05a5695cdaeb42bbcaa885aa55eac994f", "save_path": "github-repos/isabelle/xtreme-james-cooper-Harper", "path": "github-repos/isabelle/xtreme-james-cooper-Harper/Harper-ec2c52a05a5695cdaeb42bbcaa885aa55eac994f/isabelle/Chapter10_2_Typechecking.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.911179705187943, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7612756467598031}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nsection \\<open>Ordinal Induction\\<close>\n\ntheory OrdinalInduct\nimports OrdinalDef\nbegin\n\nsubsection \\<open>Zero and successor ordinals\\<close>\n\ndefinition\n  oSuc :: \"ordinal \\<Rightarrow> ordinal\" where\n    \"oSuc x = oStrictLimit (\\<lambda>n. x)\"\n\nlemma less_oSuc[iff]: \"x < oSuc x\"\n  by (metis oStrictLimit_ub oSuc_def)\n\nlemma oSuc_leI: \"x < y \\<Longrightarrow> oSuc x \\<le> y\"\n  by (simp add: oStrictLimit_lub oSuc_def)\n\ninstantiation ordinal :: \"{zero, one}\"\nbegin\n\ndefinition\n  ordinal_zero_def:       \"(0::ordinal) = oZero\"\n\ndefinition\n  ordinal_one_def [simp]: \"(1::ordinal) = oSuc 0\"\n\ninstance ..\n\nend\n\n\nsubsubsection \\<open>Derived properties of 0 and oSuc\\<close>\n\nlemma less_oSuc_eq_le: \"(x < oSuc y) = (x \\<le> y)\"\n  by (metis dual_order.strict_trans1 less_oSuc linorder_not_le oSuc_leI)\n\nlemma ordinal_0_le [iff]: \"0 \\<le> (x::ordinal)\"\n  by (simp add: oZero_least ordinal_zero_def)\n\nlemma ordinal_not_less_0 [iff]: \"\\<not> (x::ordinal) < 0\"\n  by (simp add: linorder_not_less)\n\nlemma ordinal_le_0 [iff]: \"(x \\<le> 0) = (x = (0::ordinal))\"\n  by (simp add: order_le_less)\n\nlemma ordinal_neq_0 [iff]: \"(x \\<noteq> 0) = (0 < (x::ordinal))\"\n  by (simp add: order_less_le)\n\nlemma ordinal_not_0_less [iff]: \"(\\<not> 0 < x) = (x = (0::ordinal))\"\n  by (simp add: linorder_not_less)\n\n\n\nlemma zero_less_oSuc [iff]: \"0 < oSuc x\"\n  by (rule order_le_less_trans, rule ordinal_0_le, rule less_oSuc)\n\nlemma oSuc_not_0 [iff]: \"oSuc x \\<noteq> 0\"\n  by simp\n\nlemma less_oSuc0 [iff]: \"(x < oSuc 0) = (x = 0)\"\n  by (simp add: less_oSuc_eq_le)\n\nlemma oSuc_less_oSuc [iff]: \"(oSuc x < oSuc y) = (x < y)\"\n  by (simp add: less_oSuc_eq_le oSuc_le_eq_less)\n\nlemma oSuc_eq_oSuc [iff]: \"(oSuc x = oSuc y) = (x = y)\"\n  by (metis less_oSuc less_oSuc_eq_le order_antisym)\n\nlemma oSuc_le_oSuc [iff]: \"(oSuc x \\<le> oSuc y) = (x \\<le> y)\"\n  by (simp add: order_le_less)\n\nlemma le_oSucE: \n  \"\\<lbrakk>x \\<le> oSuc y; x \\<le> y \\<Longrightarrow> R; x = oSuc y \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  by (auto simp add: order_le_less less_oSuc_eq_le)\n\nlemma less_oSucE:\n  \"\\<lbrakk>x < oSuc y; x < y \\<Longrightarrow> P; x = y \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by (auto simp add: less_oSuc_eq_le order_le_less)\n\n\nsubsection \\<open>Strict monotonicity\\<close>\n\nlocale strict_mono =\n  fixes f\n  assumes strict_mono: \"A < B \\<Longrightarrow> f A < f B\"\n\nlemmas strict_monoI = strict_mono.intro\n  and strict_monoD = strict_mono.strict_mono\n\nlemma strict_mono_natI:\n  fixes f :: \"nat \\<Rightarrow> 'a::order\"\n  shows \"(\\<And>n. f n < f (Suc n)) \\<Longrightarrow> strict_mono f\"\n  using OrdinalInduct.strict_monoI lift_Suc_mono_less by blast\n\nlemma mono_natI:\n  fixes f :: \"nat \\<Rightarrow> 'a::order\"\n  shows \"(\\<And>n. f n \\<le> f (Suc n)) \\<Longrightarrow> mono f\"\n  by (simp add: mono_iff_le_Suc)\n\nlemma strict_mono_mono:\n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"strict_mono f \\<Longrightarrow> mono f\"\n  by (auto intro!: monoI simp add: order_le_less strict_monoD)\n\nlemma strict_mono_monoD:\n  fixes f :: \"'a::order \\<Rightarrow> 'b::order\"\n  shows \"\\<lbrakk>strict_mono f; A \\<le> B\\<rbrakk> \\<Longrightarrow> f A \\<le> f B\"\n  by (rule monoD[OF strict_mono_mono])\n\nlemma strict_mono_cancel_eq:\n  fixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\n  shows \"strict_mono f \\<Longrightarrow> (f x = f y) = (x = y)\"\n  by (metis OrdinalInduct.strict_monoD not_less_iff_gr_or_eq)\n\nlemma strict_mono_cancel_less: \n  fixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\n  shows \"strict_mono f \\<Longrightarrow> (f x < f y) = (x < y)\"\n  using OrdinalInduct.strict_monoD linorder_neq_iff by fastforce\n\nlemma strict_mono_cancel_le:\n  fixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\n  shows \"strict_mono f \\<Longrightarrow> (f x \\<le> f y) = (x \\<le> y)\"\n  by (meson linorder_not_less strict_mono_cancel_less)\n\n\nsubsection \\<open>Limit ordinals\\<close>\n\ndefinition\n  oLimit :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> ordinal\" where\n  \"oLimit f = (LEAST k. \\<forall>n. f n \\<le> k)\"\n\nlemma oLimit_leI: \"\\<forall>n. f n \\<le> x \\<Longrightarrow> oLimit f \\<le> x\"\n  by (simp add: oLimit_def wellorder_Least_lemma(2))\n\nlemma le_oLimit [iff]: \"f n \\<le> oLimit f\"\n  by (smt (verit, best) LeastI_ex leD oLimit_def oStrictLimit_ub ordinal_linear)\n\nlemma le_oLimitI: \"x \\<le> f n \\<Longrightarrow> x \\<le> oLimit f\"\n  by (erule order_trans, rule le_oLimit)\n\nlemma less_oLimitI: \"x < f n \\<Longrightarrow> x < oLimit f\"\n  by (erule order_less_le_trans, rule le_oLimit)\n\nlemma less_oLimitD: \"x < oLimit f \\<Longrightarrow> \\<exists>n. x < f n\"\n  by (meson linorder_not_le oLimit_leI)\n\nlemma less_oLimitE: \"\\<lbrakk>x < oLimit f; \\<And>n. x < f n \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\n  by (auto dest: less_oLimitD)\n\nlemma le_oLimitE:\n  \"\\<lbrakk>x \\<le> oLimit f; \\<And>n. x \\<le> f n \\<Longrightarrow> R; x = oLimit f \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  by (auto simp add: order_le_less dest: less_oLimitD)\n\nlemma oLimit_const [simp]: \"oLimit (\\<lambda>n. x) = x\"\n  by (meson dual_order.refl le_oLimit oLimit_leI order_antisym)\n\nlemma strict_mono_less_oLimit: \"strict_mono f \\<Longrightarrow> f n < oLimit f\"\n  by (meson OrdinalInduct.strict_monoD lessI less_oLimitI)\n\nlemma oLimit_eqI:\n  \"\\<lbrakk>\\<And>n. \\<exists>m. f n \\<le> g m; \\<And>n. \\<exists>m. g n \\<le> f m\\<rbrakk> \\<Longrightarrow> oLimit f = oLimit g\"\n  by (meson le_oLimitI nle_le oLimit_leI)\n\nlemma oLimit_Suc:\n  \"f 0 < oLimit f \\<Longrightarrow> oLimit (\\<lambda>n. f (Suc n)) = oLimit f\"\n  by (smt (verit, ccfv_SIG) linorder_not_le nle_le oLimit_eqI oLimit_leI old.nat.exhaust)\n\nlemma oLimit_shift:\n  \"\\<forall>n. f n < oLimit f \\<Longrightarrow> oLimit (\\<lambda>n. f (n + k)) = oLimit f\"\n  apply (induct_tac k, simp)\n  by (metis (no_types, lifting) add_Suc_shift leD le_oLimit less_oLimitD not_less_iff_gr_or_eq oLimit_Suc)\n\nlemma oLimit_shift_mono:\n  \"mono f \\<Longrightarrow> oLimit (\\<lambda>n. f (n + k)) = oLimit f\"\n  by (meson le_add1 monoD oLimit_eqI)\n\n\ntext \"limit ordinal predicate\"\n\ndefinition\n  limit_ordinal :: \"ordinal \\<Rightarrow> bool\" where\n  \"limit_ordinal x \\<longleftrightarrow> (x \\<noteq> 0) \\<and> (\\<forall>y. x \\<noteq> oSuc y)\"\n\nlemma limit_ordinal_not_0 [simp]: \"\\<not> limit_ordinal 0\"\n  by (simp add: limit_ordinal_def)\n\nlemma zero_less_limit_ordinal [simp]: \"limit_ordinal x \\<Longrightarrow> 0 < x\"\n  by (simp add: limit_ordinal_def)\n\nlemma limit_ordinal_not_oSuc [simp]: \"\\<not> limit_ordinal (oSuc p)\"\n  by (simp add: limit_ordinal_def)\n\nlemma oSuc_less_limit_ordinal:\n  \"limit_ordinal x \\<Longrightarrow> (oSuc w < x) = (w < x)\"\n  by (metis limit_ordinal_not_oSuc oSuc_le_eq_less order_le_less)\n\nlemma limit_ordinal_oLimitI:\n  \"\\<forall>n. f n < oLimit f \\<Longrightarrow> limit_ordinal (oLimit f)\"\n  by (metis less_oLimitD less_oSuc less_oSucE limit_ordinal_def order_less_imp_triv ordinal_neq_0)\n\nlemma strict_mono_limit_ordinal:\n  \"strict_mono f \\<Longrightarrow> limit_ordinal (oLimit f)\"\n  by (simp add: limit_ordinal_oLimitI strict_mono_less_oLimit)\n\nlemma limit_ordinalI:\n  \"\\<lbrakk>0 < z; \\<forall>x<z. oSuc x < z\\<rbrakk> \\<Longrightarrow> limit_ordinal z\"\n  using limit_ordinal_def by blast\n\n\nsubsubsection \\<open>Making strict monotonic sequences\\<close>\n\nprimrec make_mono :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"make_mono f 0       = 0\"\n  | \"make_mono f (Suc n) = (LEAST x. f (make_mono f n) < f x)\"\n\n\n\nlemma strict_mono_f_make_mono:\n  \"\\<forall>n. f n < oLimit f \\<Longrightarrow> strict_mono (\\<lambda>n. f (make_mono f n))\"\n  by (rule strict_mono_natI, erule f_make_mono_less)\n\nlemma le_f_make_mono:\n  \"\\<lbrakk>\\<forall>n. f n < oLimit f; m \\<le> make_mono f n\\<rbrakk> \\<Longrightarrow> f m \\<le> f (make_mono f n)\"\n  apply (auto simp add: order_le_less)\n  apply (case_tac n, simp_all)\n  by (metis LeastI less_oLimitD linorder_le_less_linear not_less_Least order_le_less_trans)\n\nlemma make_mono_less:\n  \"\\<forall>n. f n < oLimit f \\<Longrightarrow> make_mono f n < make_mono f (Suc n)\"\n  by (meson f_make_mono_less le_f_make_mono linorder_not_less)\n\ndeclare make_mono.simps [simp del]\n\nlemma oLimit_make_mono_eq:\n  assumes \"\\<forall>n. f n < oLimit f\" shows \"oLimit (\\<lambda>n. f (make_mono f n)) = oLimit f\"\nproof -\n  have \"k \\<le> make_mono f k\" for k\n    by (induction k) (auto simp: Suc_leI assms make_mono_less order_le_less_trans)\n  then show ?thesis\n    by (meson assms le_f_make_mono oLimit_eqI)\nqed\n\nsubsection \\<open>Induction principle for ordinals\\<close>\n\nlemma oLimit_le_oStrictLimit: \"oLimit f \\<le> oStrictLimit f\"\n  by (simp add: oLimit_leI oStrictLimit_ub order_less_imp_le)\n\nlemma oLimit_induct [case_names zero suc lim]:\nassumes zero: \"P 0\"\n    and suc:  \"\\<And>x. P x \\<Longrightarrow> P (oSuc x)\"\n    and lim:  \"\\<And>f. \\<lbrakk>strict_mono f; \\<forall>n. P (f n)\\<rbrakk> \\<Longrightarrow> P (oLimit f)\"\nshows \"P a\"\n apply (rule oStrictLimit_induct)\n  apply (rule zero[unfolded ordinal_zero_def])\n apply (cut_tac f=f in oLimit_le_oStrictLimit)\n apply (simp add: order_le_less, erule disjE)\n  apply (metis dual_order.order_iff_strict leD le_oLimit less_oStrictLimitD oSuc_le_eq_less suc)\n  by (metis lim oLimit_make_mono_eq oStrictLimit_ub strict_mono_f_make_mono)\n\nlemma ordinal_cases [case_names zero suc lim]:\nassumes zero: \"a = 0 \\<Longrightarrow> P\"\n    and suc:  \"\\<And>x. a = oSuc x \\<Longrightarrow> P\"\n    and lim:  \"\\<And>f. \\<lbrakk>strict_mono f; a = oLimit f\\<rbrakk> \\<Longrightarrow> P\"\n  shows \"P\"\n apply (subgoal_tac \"\\<forall>x. a = x \\<longrightarrow> P\", force)\n apply (rule allI)\n apply (rule_tac a=x in oLimit_induct)\n   apply (rule impI, erule zero)\n  apply (rule impI, erule suc)\n apply (rule impI, erule lim, assumption)\ndone\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Ordinal/OrdinalInduct.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206844384594, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7611264538017266}}
{"text": "section \\<open>Simulation Systems\\<close>\n\ntheory \"Transition_Systems-Simulation_Systems\"\nimports\n  \"Transition_Systems-Foundations\"\n  \"HOL-Eisbach.Eisbach\"\nbegin\n\nunbundle lattice_syntax\n\nlocale simulation_system =\n  fixes original_transition :: \"'a \\<Rightarrow> 'p relation\" (\\<open>'(\\<rightharpoonup>\\<lparr>_\\<rparr>')\\<close>)\n  fixes simulating_transition :: \"'a \\<Rightarrow> 'p relation\" (\\<open>'(\\<rightharpoondown>\\<lparr>_\\<rparr>')\\<close>)\nbegin\n\nabbreviation original_transition_std :: \"'p \\<Rightarrow> 'a \\<Rightarrow> 'p \\<Rightarrow> bool\" (\\<open>(_ \\<rightharpoonup>\\<lparr>_\\<rparr>/ _)\\<close> [51, 0, 51] 50) where\n  \"p \\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr> q \\<equiv> (\\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr>) p q\"\nabbreviation simulating_transition_std :: \"'p \\<Rightarrow> 'a \\<Rightarrow> 'p \\<Rightarrow> bool\" (\\<open>(_ \\<rightharpoondown>\\<lparr>_\\<rparr> _)\\<close> [51, 0, 51] 50) where\n  \"p \\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr> q \\<equiv> (\\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr>) p q\"\n\nsubsection \\<open>Simulations and Bisimulations\\<close>\n\ndefinition unilateral_progression :: \"'p relation \\<Rightarrow> 'p relation \\<Rightarrow> bool\" (infix \\<open>\\<hookrightarrow>\\<close> 50) where\n  [iff]: \"K \\<hookrightarrow> L \\<longleftrightarrow> (\\<forall>\\<alpha>. K\\<inverse>\\<inverse> OO (\\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr>) \\<le> (\\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr>) OO L\\<inverse>\\<inverse>)\"\n\ndefinition bilateral_progression :: \"'p relation \\<Rightarrow> 'p relation \\<Rightarrow> bool\" (infix \\<open>\\<mapsto>\\<close> 50) where\n  [iff]: \"K \\<mapsto> L \\<longleftrightarrow> K \\<hookrightarrow> L \\<and> K\\<inverse>\\<inverse> \\<hookrightarrow> L\\<inverse>\\<inverse>\"\n\ndefinition simulation :: \"'p relation \\<Rightarrow> bool\" (\\<open>sim\\<close>) where\n  [iff]: \"sim K \\<longleftrightarrow> K \\<hookrightarrow> K\"\n\ndefinition bisimulation :: \"'p relation \\<Rightarrow> bool\" (\\<open>bisim\\<close>) where\n  [iff]: \"bisim K \\<longleftrightarrow> K \\<mapsto> K\"\n\nsubsection \\<open>Bisimilarity\\<close>\n\ncoinductive bisimilarity :: \"'p relation\" (infix \\<open>\\<sim>\\<close> 50) where\n  bisimilarity:\n    \"p \\<sim> q\"\n    if\n      \"\\<And>\\<alpha> p'. p \\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr> p' \\<Longrightarrow> \\<exists>q'. q \\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr> q' \\<and> p' \\<sim> q'\"\n    and\n      \"\\<And>\\<alpha> q'. q \\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr> q' \\<Longrightarrow> \\<exists>p'. p \\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr> p' \\<and> p' \\<sim> q'\"\n\nlemma bisimilarity_symmetry_rule [sym]:\n  assumes \"p \\<sim> q\"\n  shows \"q \\<sim> p\"\n  using assms by (coinduction arbitrary: p q) (simp, blast elim: bisimilarity.cases)\n\nlemma bisimilarity_symmetry: \"symp (\\<sim>)\"\n  using bisimilarity_symmetry_rule ..\n\ntext \\<open>\n  The following two transitivity rules are useful for calculational reasoning with both equality and\n  bisimilarity.\n\\<close>\n\nlemma equality_bisimilarity_transitivity_rule [trans]:\n  assumes \"p = q\" and \"q \\<sim> r\"\n  shows \"p \\<sim> r\"\n  using assms\n  by simp\n\nlemma bisimilarity_equality_transititity_rule [trans]:\n  assumes \"p \\<sim> q\" and \"q = r\"\n  shows \"p \\<sim> r\"\n  using assms\n  by simp\n\nlemma bisimilarity_is_bisimulation:\n  shows \"bisim (\\<sim>)\"\n  by (blast elim: bisimilarity.cases)\n\nlemma bisimilarity_is_simulation:\n  shows \"sim (\\<sim>)\"\n  using bisimilarity_is_bisimulation by simp\n\nlemma bisimulation_in_bisimilarity:\n  assumes \"bisim K\"\n  shows \"K \\<le> (\\<sim>)\"\nproof\n  fix p and q\n  assume \"K p q\"\n  with \\<open>bisim K\\<close> show \"p \\<sim> q\"\n    by (coinduction arbitrary: p q) (simp, blast)\nqed\n\ntheorem bisimilarity_is_greatest_bisimulation:\n  shows \"(\\<sim>) = (GREATEST K. bisim K)\"\n  using bisimilarity_is_bisimulation and bisimulation_in_bisimilarity\n  by (simp add: Greatest_equality)\n\nsubsection \\<open>Respectful Functions\\<close>\n\ndefinition shortcut_progression :: \"'p relation \\<Rightarrow> 'p relation \\<Rightarrow> bool\" (infix \\<open>\\<leadsto>\\<close> 50) where\n  [simp]: \"(\\<leadsto>) = (\\<le>) \\<sqinter> (\\<mapsto>)\"\n\ntext \\<open>\n  We chose the term ``shortcut progression'', because \\<open>(\\<le>)\\<close> is \\<open>(\\<mapsto>)\\<close> for\n  \\<open>(\\<rightharpoonup>)\\<lparr>\\<alpha>\\<rparr> = (=) \\<and> (\\<rightharpoondown>)\\<lparr>\\<alpha>\\<rparr> = (=)\\<close> and we have \\<open>(=) = (\\<rightharpoonup>)\\<lparr>\\<alpha>\\<rparr>\\<^bsup>0\\<^esup> \\<and> (=) = (\\<rightharpoondown>)\\<lparr>\\<alpha>\\<rparr>\\<^bsup>0\\<^esup>\\<close>. This is made\n  formal in the following note.\n\\<close>\n\nnotepad begin\n  interpret shortcut: simulation_system \\<open>\\<lambda>\\<alpha>. (\\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr>)\\<^bsup>0\\<^esup>\\<close> \\<open>\\<lambda>\\<alpha>. (\\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr>)\\<^bsup>0\\<^esup>\\<close> .\n  have \"shortcut.unilateral_progression = (\\<le>)\"\n    unfolding shortcut.unilateral_progression_def\n    by auto\n  have \"shortcut.bilateral_progression = (\\<le>)\"\n    unfolding shortcut.unilateral_progression_def and shortcut.bilateral_progression_def\n    by auto\nend\n\nlemma general_union_shortcut_progression:\n  assumes \"\\<forall>K \\<in> \\<K>. \\<exists>L \\<in> \\<L>. K \\<leadsto> L\"\n  shows \"\\<Squnion> \\<K> \\<leadsto> \\<Squnion> \\<L>\"\n  using assms by (simp, fast)\n\ndefinition respectful :: \"('p relation \\<Rightarrow> 'p relation) \\<Rightarrow> bool\" where\n  [iff]: \"respectful \\<F> \\<longleftrightarrow> (\\<forall>K L. K \\<leadsto> L \\<longrightarrow> \\<F> K \\<leadsto> \\<F> L)\"\n\nsubsubsection \\<open>Automatic Proof of Respectfulness\\<close>\n\ntext \\<open>\n  We work with a single list of respectfulness facts anyhow. It would be weird to have this single\n  fact list and the same \\<^theory_text>\\<open>respectful\\<close> method based on it in each concrete interpretation. When\n  invoking the method in the theory context, we would have to pick it from an interpretation, but\n  which interpretation we chose would be arbitrary. Therefore we temporarily leave the locale\n  context.\n\\<close>\n\nend\n\nnamed_theorems respectful\n\ntext \\<open>\n  Note that the \\<^theory_text>\\<open>respectful\\<close> methods works also on conclusions that contain function\n  variables~\\<^term>\\<open>\\<F>\\<close> if there are premises \\<^term>\\<open>respectful \\<F>\\<close>.\n\\<close>\n\nmethod respectful = (intro respectful ballI | elim emptyE insertE | simp only:)+\n\ncontext simulation_system begin\n\nsubsubsection \\<open>Common Respectful Functions and Respectful Function Combinators\\<close>\n\n(*FIXME:\n  Explain that we want \\<open>\\<bottom>\\<close> for those cases where bisimilarity holds, because no transitions are\n  possible at all.\n*)\n\nlemma bottom_is_respectful [respectful]:\n  shows \"respectful \\<bottom>\"\n  by auto\n\ndefinition constant_bisimilarity :: \"'p relation \\<Rightarrow> 'p relation\" (\\<open>[\\<sim>]\\<close>) where\n  [simp]: \"[\\<sim>] = (\\<lambda>_. (\\<sim>))\"\n\nlemma constant_bisimilarity_is_respectful [respectful]:\n  shows \"respectful [\\<sim>]\"\n  using bisimilarity_is_bisimulation by simp\n\nlemma identity_is_respectful [respectful]:\n  shows \"respectful id\"\n  by simp\n\nlemma function_composition_is_respectful [respectful]:\n  assumes \"respectful \\<F>\" and \"respectful \\<G>\"\n  shows \"respectful (\\<F> \\<circ> \\<G>)\"\n  using assms by simp\n\nlemma general_union_is_respectful [respectful]:\n  assumes \"\\<forall>\\<F> \\<in> \\<FF>. respectful \\<F>\"\n  shows \"respectful (\\<Squnion> \\<FF>)\"\nproof -\n  have \"(\\<Squnion> \\<FF>) K \\<leadsto> (\\<Squnion> \\<FF>) L\" if \"K \\<leadsto> L\" for K and L\n  proof -\n    from \\<open>\\<forall>\\<F> \\<in> \\<FF>. respectful \\<F>\\<close> and \\<open>K \\<leadsto> L\\<close> have \"\\<forall>\\<F> \\<in> \\<FF>. \\<F> K \\<leadsto> \\<F> L\"\n      by simp\n    then have \"\\<forall>K' \\<in> {\\<F> K | \\<F>. \\<F> \\<in> \\<FF>}. \\<exists>L' \\<in> {\\<F> L | \\<F>. \\<F> \\<in> \\<FF>}. K' \\<leadsto> L'\"\n      by blast\n    then have \"\\<Squnion> {\\<F> K | \\<F>. \\<F> \\<in> \\<FF>} \\<leadsto> \\<Squnion> {\\<F> L | \\<F>. \\<F> \\<in> \\<FF>}\"\n      by (fact general_union_shortcut_progression)\n    moreover have \"\\<Squnion> {\\<F> M | \\<F>. \\<F> \\<in> \\<FF>} = (\\<Squnion> \\<FF>) M\" for M\n      by auto\n    ultimately show ?thesis\n      by simp\n  qed\n  then show ?thesis by simp\nqed\n\nlemma union_is_respectful [respectful]:\n  assumes \"respectful \\<F>\" and \"respectful \\<G>\"\n  shows \"respectful (\\<F> \\<squnion> \\<G>)\"\nproof-\n  from assms have \"\\<forall>\\<H> \\<in> {\\<F>, \\<G>}. respectful \\<H>\"\n    by simp\n  then have \"respectful (\\<Squnion> {\\<F>, \\<G>})\"\n    by (fact general_union_is_respectful)\n  then show ?thesis\n    by simp\nqed\n\nlemma dual_is_respectful [respectful]:\n  assumes \"respectful \\<F>\"\n  shows \"respectful \\<F>\\<^sup>\\<dagger>\"\n  using assms by simp\n\nsubsubsection \\<open>Respectfully Transformed Bisimilarity\\<close>\n\ntheorem respectfully_transformed_bisimilarity_in_bisimilarity:\n  assumes \"respectful \\<F>\"\n  shows \"\\<F> (\\<sim>) \\<le> (\\<sim>)\"\nproof -\n  from \\<open>respectful \\<F>\\<close> have \"bisim (\\<F> (\\<sim>))\"\n    using bisimilarity_is_bisimulation\n    by simp\n  then show ?thesis\n    using bisimulation_in_bisimilarity\n    by simp\nqed\n\nsubsection \\<open>``Up to'' Methods\\<close>\n\ndefinition simulation_up_to :: \"('p relation \\<Rightarrow> 'p relation) \\<Rightarrow> 'p relation \\<Rightarrow> bool\" (\\<open>sim\\<^bsub>_\\<^esub>\\<close>) where\n  [iff]: \"sim\\<^bsub>\\<F>\\<^esub> K \\<longleftrightarrow> K \\<hookrightarrow> \\<F> K\"\n\ndefinition bisimulation_up_to :: \"('p relation \\<Rightarrow> 'p relation) \\<Rightarrow> 'p relation \\<Rightarrow> bool\" (\\<open>bisim\\<^bsub>_\\<^esub>\\<close>) where\n  [iff]: \"bisim\\<^bsub>\\<F>\\<^esub> K \\<longleftrightarrow> K \\<mapsto> \\<F> K\"\n\nlemma simulation_up_to_identity_is_simulation_and_vice_versa:\n  shows \"sim\\<^bsub>id\\<^esub> K \\<longleftrightarrow> sim K\"\n  by simp\n\nlemma bisimulation_up_to_identity_is_bisimulation_and_vice_versa:\n  shows \"bisim\\<^bsub>id\\<^esub> K \\<longleftrightarrow> bisim K\"\n  by simp\n\nsubsubsection \\<open>Soundness\\<close>\n\ncontext begin\n\nprivate definition\n  expansion :: \"('p relation \\<Rightarrow> 'p relation) \\<Rightarrow> ('p relation \\<Rightarrow> 'p relation)\"\n  (\\<open>(\\<langle>_\\<rangle>)\\<close>)\nwhere\n  [simp]: \"\\<langle>\\<F>\\<rangle> = id \\<squnion> \\<F>\"\n\nprivate lemma expansion_is_respectful:\n  assumes \"respectful \\<F>\"\n  shows \"respectful \\<langle>\\<F>\\<rangle>\"\n  unfolding expansion_def\n  using identity_is_respectful and union_is_respectful and assms\n  by iprover\n\nprivate lemma bisimulation_from_bisimulation_up_to:\n  assumes \"respectful \\<F>\" and \"bisim\\<^bsub>\\<F>\\<^esub> K\"\n  shows \"bisim (\\<Squnion>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K)\"\nproof -\n  have \"\\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K \\<leadsto> \\<langle>\\<F>\\<rangle>\\<^bsup>Suc n\\<^esup> K\" for n\n  proof (induction n)\n    case 0\n    from \\<open>bisim\\<^bsub>\\<F>\\<^esub> K\\<close> show ?case\n      by (simp, blast)\n  next\n    case Suc\n    with \\<open>respectful \\<F>\\<close> show ?case\n      using expansion_is_respectful\n      by (simp del: shortcut_progression_def expansion_def)\n  qed\n  then have \"\\<forall>K' \\<in> range (\\<lambda>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K). \\<exists>L' \\<in> range (\\<lambda>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K). K' \\<leadsto> L'\"\n    by blast\n  then have \"(\\<Squnion>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K) \\<leadsto> (\\<Squnion>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K)\"\n    by (fact general_union_shortcut_progression)\n  then show ?thesis\n    by simp\nqed\n\ntheorem up_to_is_sound:\n  assumes \"respectful \\<F>\" and \"bisim\\<^bsub>\\<F>\\<^esub> K\"\n  shows \"K \\<le> (\\<sim>)\"\nproof -\n  from assms have \"bisim (\\<Squnion>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K)\"\n    by (fact bisimulation_from_bisimulation_up_to)\n  then have \"(\\<Squnion>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K) \\<le> (\\<sim>)\"\n    by (fact bisimulation_in_bisimilarity)\n  moreover have \"K \\<le> (\\<Squnion>n. \\<langle>\\<F>\\<rangle>\\<^bsup>n\\<^esup> K)\"\n    by (subst funpow_0 [of \"\\<langle>\\<F>\\<rangle>\" K, symmetric], blast)\n  ultimately show ?thesis\n    by simp\nqed\n\nend\n\ncontext begin\n\nprivate lemma bisimulation_up_to_from_simulation_up_to:\n  assumes \"symp K\" and \"sim\\<^bsub>\\<F>\\<^esub> K\"\n  shows \"bisim\\<^bsub>\\<F> \\<squnion> \\<F>\\<^sup>\\<dagger>\\<^esub> K\"\nproof -\n  from \\<open>symp K\\<close> have \"K\\<inverse>\\<inverse> = K\"\n    by (blast elim: sympE)\n  with \\<open>sim\\<^bsub>\\<F>\\<^esub> K\\<close> show ?thesis\n    by auto\nqed\n\ntheorem symmetric_up_to_is_sound:\n  assumes \"respectful \\<F>\" and \"symp K\" and \"sim\\<^bsub>\\<F>\\<^esub> K\"\n  shows \"K \\<le> (\\<sim>)\"\nproof -\n  from \\<open>respectful \\<F>\\<close> have \"respectful (\\<F> \\<squnion> \\<F>\\<^sup>\\<dagger>)\"\n    by respectful\n  moreover from \\<open>symp K\\<close> and \\<open>sim\\<^bsub>\\<F>\\<^esub> K\\<close> have \"bisim\\<^bsub>\\<F> \\<squnion> \\<F>\\<^sup>\\<dagger>\\<^esub> K\"\n    by (fact bisimulation_up_to_from_simulation_up_to)\n  ultimately show ?thesis\n    by (fact up_to_is_sound)\nqed\n\nend\n\nsubsubsection \\<open>Coinduction Rules\\<close>\n\ntext \\<open>\n  The following corollaries are coinduction rules that correspond to the above soundness lemmas. To\n  use an ``up to'' method, pick the corresponding rule, instantiate the variable~\\<^term>\\<open>\\<F>\\<close>\n  appropriately, and pass the resulting fact to the \\<^theory_text>\\<open>coinduction\\<close> method via a \\<^theory_text>\\<open>rule\\<close>\n  specification, along with an appropriate \\<^theory_text>\\<open>arbitrary\\<close> specification. The \\<^theory_text>\\<open>coinduction\\<close> method\n  automatically derives the relation~\\<^term>\\<open>K\\<close> from the goal and proves the assumption \\<^term>\\<open>K s t\\<close>.\n\\<close>\n\ncorollary up_to_rule [case_names respectful forward_simulation backward_simulation]:\n  assumes\n    \"K s t\"\n  and\n    \"respectful \\<F>\"\n  and\n    \"\\<And>\\<alpha> s t s'. K s t \\<Longrightarrow> s \\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr> s' \\<Longrightarrow> \\<exists>t'. t \\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr> t' \\<and> \\<F> K s' t'\"\n  and\n    \"\\<And>\\<alpha> s t t'. K s t \\<Longrightarrow> t \\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr> t' \\<Longrightarrow> \\<exists>s'. s \\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr> s' \\<and> \\<F> K s' t'\"\n  shows \"s \\<sim> t\"\n  using up_to_is_sound [OF \\<open>respectful \\<F>\\<close>, of K] and assms(1,3-4)\n  by blast\n\ncorollary symmetric_up_to_rule [case_names respectful symmetry simulation]:\n  assumes\n    \"K s t\"\n  and\n    \"respectful \\<F>\"\n  and\n    \"\\<And>s t. K s t \\<Longrightarrow> K t s\"\n  and\n    \"\\<And>\\<alpha> s t s'. K s t \\<Longrightarrow> s \\<rightharpoonup>\\<lparr>\\<alpha>\\<rparr> s' \\<Longrightarrow> \\<exists>t'. t \\<rightharpoondown>\\<lparr>\\<alpha>\\<rparr> t' \\<and> \\<F> K s' t'\"\n  shows \"s \\<sim> t\"\n  using symmetric_up_to_is_sound [OF \\<open>respectful \\<F>\\<close>, of K] and assms (1,3-4)\n  unfolding symp_def\n  by blast\n\nend\n\nend\n", "meta": {"author": "input-output-hk", "repo": "transition-systems", "sha": "6a640f5967e2b4eca0467601646050d9389deb92", "save_path": "github-repos/isabelle/input-output-hk-transition-systems", "path": "github-repos/isabelle/input-output-hk-transition-systems/transition-systems-6a640f5967e2b4eca0467601646050d9389deb92/src/Transition_Systems-Simulation_Systems.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.8438951045175643, "lm_q1q2_score": 0.7611264435864485}}
{"text": "(* GEB MIU Puzzle *)\n\ntheory \"miu\"\n  imports Main\n\nbegin\n\ndatatype miu = M | I | U\n\ninductive_set MIU :: \"miu list set\" where\n  \"[M, I] : MIU\" |\n  \"x @ [I] : MIU \\<Longrightarrow> x @ [I, U] : MIU\" |  (* \\<Longrightarrow> abbreviation is \"= = >\" *)\n  \"[M] @ x : MIU \\<Longrightarrow> [M] @ x @ x : MIU\" |\n  \"x @ [I, I, I] @ y : MIU \\<Longrightarrow> x @ [U] @ y : MIU\" |\n  \"x @ [U, U] @ y : MIU \\<Longrightarrow> x @ y : MIU\"\n\nfun ci :: \"miu list \\<Rightarrow> nat\" where        (* \\<Rightarrow> abbreviation is \"= >\" *)\n  \"ci [] = 0\" |\n  \"ci (x # xs) = (if x = I then ci xs + 1 else ci xs)\"\n\nlemma [rule_format, simp] : \"\\<forall> y. ci (x @ y) = ci x + ci y\"\n  apply (induct_tac x)\n   apply (auto)\n  done\n                                              (* \\<noteq> abbs \"~ =\" *)\nlemma miu_inv : \"x \\<in> MIU \\<Longrightarrow> ci x mod 3 \\<noteq> 0\"  (* \\<in> abbs \"i n\" *)\n  apply (erule MIU.induct)\n      apply (auto)\n  apply (arith)\n  done\n\ntheorem th_miu'' : \"[M, U] \\<notin> MIU\"    (* \\<notin> abbs \"~ :\" *)\n  (* \\<not> [M, U] \\<notin> S \\<Longrightarrow> [M, U] \\<notin> S *)\n  apply (rule classical)\n  apply (simp)\n  apply (drule miu_inv)\n  apply (simp)\n  done\n\ntheorem th_miu' : \"[M, U] \\<notin> MIU\"\nproof (rule classical)  (* \\<not> [M, U] \\<notin> S \\<Longrightarrow> [M, U] \\<notin> S *)\n  assume \"\\<not> [M, U] \\<notin> MIU\"\n  from this have 1 : \"[M, U] : MIU\" by simp\n  from this have \"ci [M, U] mod 3 \\<noteq> 0\" by (rule miu_inv)\n  from this have  2: \"\\<not> [M, U] : MIU\" by simp\n  from 1 and 2 have \"False\" by simp\n  from this show \"[M, U] \\<notin> MIU\" by simp\nqed\n\ntheorem th_miu : \"[M, U] \\<notin> MIU\"\nproof (rule classical)  (* \\<not> [M, U] \\<notin> S \\<Longrightarrow> [M, U] \\<notin> S *)\n  assume \"\\<not> [M, U] \\<notin> MIU\"\n  hence 1 : \"[M, U] : MIU\" by simp\n  hence \"ci [M, U] mod 3 \\<noteq> 0\" by (rule miu_inv)\n  hence 2: \"\\<not> [M, U] : MIU\" by simp\n  from 1 and 2 have \"False\" by simp\n  thus \"[M, U] \\<notin> MIU\" by simp\nqed\n\n(* END *)\n", "meta": {"author": "suharahiromichi", "repo": "isabelle", "sha": "9c4969e67b9cbbf87edfc926d609c446c8d71824", "save_path": "github-repos/isabelle/suharahiromichi-isabelle", "path": "github-repos/isabelle/suharahiromichi-isabelle/isabelle-9c4969e67b9cbbf87edfc926d609c446c8d71824/miu.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7611264333711698}}
{"text": "section \\<open>Sphere\\<close>\ntheory Sphere\n  imports Differentiable_Manifold\nbegin\n\ntypedef (overloaded) ('a::real_normed_vector) sphere =\n  \"{a::'a\\<times>real. norm a = 1}\"\nproof -\n  have \"norm (0::'a,1::real) = 1\" by simp\n  then show ?thesis by blast\nqed\n\nsetup_lifting type_definition_sphere\n\n(* First stereographic projection: between S^n - (0,1) and R^n. *)\nlift_definition top_sphere :: \"('a::real_normed_vector) sphere\" is \"(0, 1)\" by simp\n\nlift_definition st_proj1 :: \"('a::real_normed_vector) sphere \\<Rightarrow> 'a\" is\n  \"\\<lambda>(x,z). x /\\<^sub>R (1 - z)\" .\n\nlift_definition st_proj1_inv :: \"('a::real_normed_vector) \\<Rightarrow> 'a sphere\" is\n  \"\\<lambda>x. ((2 / ((norm x) ^ 2 + 1)) *\\<^sub>R x, ((norm x) ^ 2 - 1) / ((norm x) ^ 2 + 1))\"\n  apply (auto simp: norm_prod_def divide_simps algebra_simps)\n   apply (auto simp: add_nonneg_eq_0_iff)\n  by (auto simp: power2_eq_square algebra_simps)\n\n(* Second stereographic projection: between S^n - (0,-1) and R^n. *)\nlift_definition bot_sphere :: \"('a::real_normed_vector) sphere\" is \"(0, -1)\" by simp\n\nlift_definition st_proj2 :: \"('a::real_normed_vector) sphere \\<Rightarrow> 'a\" is\n  \"\\<lambda>(x,z). x /\\<^sub>R (1 + z)\" .\n\nlift_definition st_proj2_inv :: \"('a::real_normed_vector) \\<Rightarrow> 'a sphere\" is\n  \"\\<lambda>x. ((2 / ((norm x) ^ 2 + 1)) *\\<^sub>R x, (1 - (norm x) ^ 2) / ((norm x) ^ 2 + 1))\"\n  apply (auto simp: norm_prod_def divide_simps algebra_simps)\n   apply (auto simp: add_nonneg_eq_0_iff)\n  by (auto simp: power2_eq_square algebra_simps)\n\ninstantiation sphere :: (real_normed_vector) topological_space\nbegin\n\nlift_definition open_sphere :: \"'a sphere set \\<Rightarrow> bool\" is\n  \"openin (subtopology (euclidean::('a\\<times>real) topology) {a. norm a = 1})\" .\n\ninstance\n  apply standard\n  apply (transfer; auto)\n  apply (transfer; auto)\n  apply (transfer; auto)\n  done\n\nend\n\ninstance sphere :: (real_normed_vector) t2_space\n  apply standard\n  apply transfer\n  subgoal for x y\n    apply (drule hausdorff[of x y])\n    apply clarsimp\n    subgoal for U V\n      apply (rule exI[where x=\"U \\<inter> {a. norm a = 1}\"])\n      apply clarsimp\n      apply (rule conjI) defer\n       apply (rule exI[where x=\"V \\<inter> {a. norm a = 1}\"])\n      by auto\n    done\n  done\n\ninstance sphere :: (euclidean_space) second_countable_topology\nproof standard\n  obtain BB::\"('a\\<times>real) set set\" where BB: \"countable BB\" \"open = generate_topology BB\"\n    by (metis ex_countable_subbasis)\n  let ?B = \"(\\<lambda>B. B \\<inter> {x. norm x = 1}) ` BB\"\n  show \"\\<exists>B::'a sphere set set. countable B \\<and> open = generate_topology B\"\n    apply transfer\n    apply (rule bexI[where x = ?B])\n    apply (rule conjI)\n    subgoal using BB by force\n    subgoal using BB apply clarsimp\n      apply (subst openin_subtopology_eq_generate_topology[where BB=BB])\n      by (auto )\n    subgoal by auto\n    done\nqed\n\nlemma transfer_continuous_on1[transfer_rule]:\n  includes lifting_syntax\n  shows \"(rel_set (=) ===> ((=) ===> pcr_sphere (=)) ===> (=)) (\\<lambda>X::'a::t2_space set. continuous_on X) continuous_on\"\n  apply (rule continuous_on_transfer_right_total2)\n        apply transfer_step\n       apply transfer_step\n      apply transfer_step\n     apply transfer_prover\n    apply transfer_step\n   apply transfer_step\n  apply transfer_prover\n  done\n\nlemma transfer_continuous_on2[transfer_rule]:\n  includes lifting_syntax\n  shows \"(rel_set (pcr_sphere (=)) ===> (pcr_sphere (=) ===> (=)) ===> (=)) (\\<lambda>X. continuous_on (X \\<inter> {x. norm x = 1})) (\\<lambda>X. continuous_on X)\"\n  apply (rule continuous_on_transfer_right_total)\n        apply transfer_step\n       apply transfer_step\n      apply transfer_step\n     apply transfer_prover\n    apply transfer_step\n   apply transfer_step\n  apply transfer_prover\n  done\n\nlemma st_proj1_inv_continuous:\n  \"continuous_on UNIV st_proj1_inv\"\n  by transfer (auto intro!: continuous_intros simp: add_nonneg_eq_0_iff)\n\nlemma st_proj1_continuous:\n  \"continuous_on (UNIV - {top_sphere}) st_proj1\"\n  by transfer (auto intro!: continuous_intros simp: add_nonneg_eq_0_iff split_beta' norm_prod_def)\n\nlemma st_proj1_inv: \"st_proj1_inv (st_proj1 x) = x\"\n  if \"x \\<noteq> top_sphere\"\n  using that\n  apply transfer\nproof (clarsimp, rule conjI)\n  fix a::'a and b::real\n  assume *: \"norm (a, b) = 1\" and ab: \"a = 0 \\<longrightarrow> b \\<noteq> 1\"\n  then have \"b \\<noteq> 1\" by (auto simp: norm_prod_def)\n  have na: \"(norm a)\\<^sup>2 = 1 - b\\<^sup>2\"\n    using *\n    unfolding norm_prod_def\n    by (auto simp: algebra_simps)\n  define S where \"S = norm (a /\\<^sub>R (1 - b))\"\n  have \"b = (S\\<^sup>2 - 1) / (S\\<^sup>2 + 1)\"\n    by (auto simp: S_def divide_simps \\<open>b \\<noteq> 1\\<close> na)\n       (auto simp: power2_eq_square algebra_simps \\<open>b \\<noteq> 1\\<close>)\n  then show \"((inverse \\<bar>1 - b\\<bar> * norm a)\\<^sup>2 - 1) / ((inverse \\<bar>1 - b\\<bar> * norm a)\\<^sup>2 + 1) = b\"\n    by (simp add: S_def)\n\n  have \"1 = (2 / (1 - b) / (S\\<^sup>2 + 1))\"\n    by (auto simp: S_def divide_simps \\<open>b \\<noteq> 1\\<close> na) (auto simp: power2_eq_square algebra_simps \\<open>b \\<noteq> 1\\<close>)\n  then have \"a = (2 / (1 - b) / (S\\<^sup>2 + 1)) *\\<^sub>R a\"\n    by simp \n  then show \"(2 * inverse (1 - b) / ((inverse \\<bar>1 - b\\<bar> * norm a)\\<^sup>2 + 1)) *\\<^sub>R a = a\"\n    by (auto simp: S_def divide_simps)\nqed\n\nlemma st_proj1_inv_inv: \"st_proj1 (st_proj1_inv x) = x\"\n  by transfer (auto simp: divide_simps add_nonneg_eq_0_iff)\n\nlemma st_proj1_inv_ne_top: \"st_proj1_inv xa \\<noteq> top_sphere\"\n  by transfer (auto simp: divide_simps add_nonneg_eq_0_iff)\n\nlemma homeomorphism_st_proj1: \"homeomorphism (UNIV - {top_sphere}) UNIV st_proj1 st_proj1_inv\"\n  apply (auto simp: homeomorphism_def st_proj1_continuous st_proj1_inv_continuous st_proj1_inv_inv\n      st_proj1_inv st_proj1_inv_ne_top)\n  subgoal for x\n    by (rule image_eqI[where x=\"st_proj1_inv x\"]) (auto simp: st_proj1_inv_inv st_proj1_inv_ne_top)\n  by (metis rangeI st_proj1_inv)\n\nlemma st_proj2_inv_continuous:\n  \"continuous_on UNIV st_proj2_inv\"\n  by transfer (auto intro!: continuous_intros simp: add_nonneg_eq_0_iff)\n\nlemma st_proj2_continuous:\n  \"continuous_on (UNIV - {bot_sphere}) st_proj2\"\n  apply (transfer; auto intro!: continuous_intros simp: add_nonneg_eq_0_iff split_beta' norm_prod_def)\nproof -\n  fix a b assume 1: \"(norm a)^2 + b^2 = 1\" and 2: \"1 + b = 0\"\n  have \"b = -1\" using 2 by auto\n  then show \"a = 0\"\n    using 1 by auto\nqed\n\nlemma st_proj2_inv: \"st_proj2_inv (st_proj2 x) = x\"\n  if \"x \\<noteq> bot_sphere\"\n  using that\n  apply transfer\nproof (clarsimp, rule conjI)\n  fix a::'a and b::real\n  assume *: \"norm (a, b) = 1\" and ab: \"a = 0 \\<longrightarrow> b \\<noteq> -1\"\n  then have \"b \\<noteq> -1\" by (auto simp: norm_prod_def)\n  then have \"1 + b \\<noteq> 0\" by auto\n  then have \"2 + b * 2 \\<noteq> 0\" by auto\n  have na: \"(norm a)\\<^sup>2 = 1 - b\\<^sup>2\"\n    using *\n    unfolding norm_prod_def\n    by (auto simp: algebra_simps)\n  define S where \"S = norm (a /\\<^sub>R (1 + b))\"\n  have \"b = (1 - S\\<^sup>2) / (S\\<^sup>2 + 1)\"\n    by (auto simp: S_def divide_simps \\<open>b \\<noteq> -1\\<close> na)\n       (auto simp: power2_eq_square algebra_simps \\<open>b \\<noteq> -1\\<close> \\<open>1 + b \\<noteq> 0\\<close> \\<open>2 + b * 2 \\<noteq> 0\\<close>)\n  then show \"(1 - (inverse \\<bar>1 + b\\<bar> * norm a)\\<^sup>2) / ((inverse \\<bar>1 + b\\<bar> * norm a)\\<^sup>2 + 1) = b\"\n    by (simp add: S_def)\n  have \"1 = (2 / (1 + b) / (S\\<^sup>2 + 1))\"\n    by (auto simp: S_def divide_simps \\<open>b \\<noteq> -1\\<close> na)\n       (auto simp: power2_eq_square algebra_simps \\<open>b \\<noteq> -1\\<close> \\<open>1 + b \\<noteq> 0\\<close> \\<open>2 + b * 2 \\<noteq> 0\\<close>)\n  then have \"a = (2 / (1 + b) / (S\\<^sup>2 + 1)) *\\<^sub>R a\"\n    by simp \n  then show \"(2 * inverse (1 + b) / ((inverse \\<bar>1 + b\\<bar> * norm a)\\<^sup>2 + 1)) *\\<^sub>R a = a\"\n    by (auto simp: S_def divide_simps)\nqed\n\nlemma st_proj2_inv_inv: \"st_proj2 (st_proj2_inv x) = x\"\n  by transfer (auto simp: divide_simps add_nonneg_eq_0_iff)\n\nlemma st_proj2_inv_ne_top: \"st_proj2_inv xa \\<noteq> bot_sphere\"\n  by transfer (auto simp: divide_simps add_nonneg_eq_0_iff)\n\nlemma homeomorphism_st_proj2: \"homeomorphism (UNIV - {bot_sphere}) UNIV st_proj2 st_proj2_inv\"\n  apply (auto simp: homeomorphism_def st_proj2_continuous st_proj2_inv_continuous st_proj2_inv_inv\n      st_proj2_inv st_proj2_inv_ne_top)\n  subgoal for x\n    by (rule image_eqI[where x=\"st_proj2_inv x\"]) (auto simp: st_proj2_inv_inv st_proj2_inv_ne_top)\n  by (metis rangeI st_proj2_inv)\n\nlift_definition st_proj1_chart :: \"('a sphere, 'a::euclidean_space) chart\"\n  is \"(UNIV - {top_sphere::'a sphere}, UNIV::'a set, st_proj1, st_proj1_inv)\"\n  using homeomorphism_st_proj1 by blast\n  \nlift_definition st_proj2_chart :: \"('a sphere, 'a::euclidean_space) chart\"\n  is \"(UNIV - {bot_sphere::'a sphere}, UNIV::'a set, st_proj2, st_proj2_inv)\"\n  using homeomorphism_st_proj2 by blast\n\nlemma st_projs_compat:\n  includes lifting_syntax\n  shows \"\\<infinity>-smooth_compat st_proj1_chart st_proj2_chart\"\n  unfolding smooth_compat_def\n  apply (transfer; auto)\nproof goal_cases\n  case 1\n  have *: \"smooth_on ((\\<lambda>(x::'a, z). x /\\<^sub>R (1 - z)) ` (({a. norm a = 1} - {(0, 1)}) \\<inter> ({a. norm a = 1} - {(0, - 1)})))\n     ((\\<lambda>(x, z). x /\\<^sub>R (1 + z)) \\<circ> (\\<lambda>x. ((2 / ((norm x)\\<^sup>2 + 1)) *\\<^sub>R x, ((norm x)\\<^sup>2 - 1) / ((norm x)\\<^sup>2 + 1))))\"\n    apply (rule smooth_on_subset[where T=\"UNIV - {0}\"])\n    subgoal\n      by (auto intro!: smooth_on_divide smooth_on_inverse smooth_on_scaleR smooth_on_mult smooth_on_add\n          smooth_on_minus smooth_on_norm simp: o_def power2_eq_square add_nonneg_eq_0_iff divide_simps)\n    apply (auto simp: norm_prod_def power2_eq_square) apply sos\n    done\n  show ?case\n    by transfer (rule *)\nnext\n  case 2\n  have *: \"smooth_on ((\\<lambda>(x::'a, z). x /\\<^sub>R (1 + z)) ` (({a. norm a = 1} - {(0, 1)}) \\<inter> ({a. norm a = 1} - {(0, - 1)})))\n     ((\\<lambda>(x, z). x /\\<^sub>R (1 - z)) \\<circ> (\\<lambda>x. ((2 / ((norm x)\\<^sup>2 + 1)) *\\<^sub>R x, (1 - (norm x)\\<^sup>2) / ((norm x)\\<^sup>2 + 1))))\"\n    apply (rule smooth_on_subset[where T=\"UNIV - {0}\"])\n    subgoal\n      by (auto intro!: smooth_on_divide smooth_on_inverse smooth_on_scaleR smooth_on_mult smooth_on_add\n          smooth_on_minus smooth_on_norm simp: o_def power2_eq_square add_nonneg_eq_0_iff divide_simps)\n    apply (auto simp: norm_prod_def add_eq_0_iff) apply sos\n    done\n  show ?case\n    by transfer (rule *)\nqed\n\ndefinition charts_sphere :: \"('a::euclidean_space sphere, 'a) chart set\" where\n  \"charts_sphere \\<equiv> {st_proj1_chart, st_proj2_chart}\"\n\nlemma c_manifold_atlas_sphere: \"c_manifold charts_sphere \\<infinity>\"\n  apply (unfold_locales)\n  unfolding charts_sphere_def\n  using smooth_compat_commute smooth_compat_refl st_projs_compat by fastforce\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Smooth_Manifolds/Sphere.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.8519528094861981, "lm_q1q2_score": 0.7610574582284494}}
{"text": "header{*The Hereditarily Finite Sets*}\n\ntheory HF imports \"~~/src/HOL/Library/Nat_Bijection\"\nbegin\n\ntext{*From \"Finite sets and Gödel's Incompleteness Theorems\" by S. Swierczkowski.\n      Thanks for Brian Huffman for this development, up to the cases and induct rules.*}\n\nsection {* Basic Definitions and Lemmas *}\n\ntypedef hf = \"UNIV :: nat set\" ..\n\ndefinition hfset :: \"hf \\<Rightarrow> hf set\"\n  where \"hfset a = Abs_hf ` set_decode (Rep_hf a)\"\n\ndefinition HF :: \"hf set \\<Rightarrow> hf\"\n  where \"HF A = Abs_hf (set_encode (Rep_hf ` A))\"\n\ndefinition hinsert :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"hinsert a b = HF (insert a (hfset b))\"\n\ndefinition hmem :: \"hf \\<Rightarrow> hf \\<Rightarrow> bool\"     (infixl \"<:\" 50)\n  where \"hmem a b \\<longleftrightarrow> a \\<in> hfset b\"\n\n\ninstantiation hf :: zero\nbegin\n\ndefinition\n  Zero_hf_def: \"0 = HF {}\"\n\ninstance ..\n\nend\n\ntext {* HF Set enumerations *}\n\nsyntax\n  \"_HFinset\" :: \"args \\<Rightarrow> hf\"      (\"{|(_)|}\")\n\nsyntax (xsymbols)\n  \"_HFinset\" :: \"args \\<Rightarrow> hf\"      (\"\\<lbrace>_\\<rbrace>\")\n  \"_inserthf\" :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"  (infixl \"\\<triangleleft>\" 60)\n\nnotation (xsymbols)\n  hmem             (infixl \"\\<^bold>\\<in>\" 50)\n\ntranslations\n  \"y \\<triangleleft> x\"    == \"CONST hinsert x y\"\n  \"{|x, y|}\" == \"\\<lbrace>y\\<rbrace> \\<triangleleft> x\"\n  \"{|x|}\"    == \"0 \\<triangleleft> x\"\n\nlemma finite_hfset [simp]: \"finite (hfset a)\"\n  unfolding hfset_def by simp\n\nlemma HF_hfset [simp]: \"HF (hfset a) = a\"\n  unfolding HF_def hfset_def\n  by (simp add: image_image Abs_hf_inverse Rep_hf_inverse)\n\nlemma hfset_HF [simp]: \"finite A \\<Longrightarrow> hfset (HF A) = A\"\n  unfolding HF_def hfset_def\n  by (simp add: image_image Abs_hf_inverse Rep_hf_inverse)\n\nlemma hmem_hempty [simp]: \"\\<not> a \\<^bold>\\<in> 0\"\n  unfolding hmem_def Zero_hf_def by simp\n\nlemmas hemptyE [elim!] = hmem_hempty [THEN notE]\n\nlemma hmem_hinsert [iff]:\n  \"hmem a (c \\<triangleleft>  b) \\<longleftrightarrow> a = b \\<or> a \\<^bold>\\<in> c\"\n  unfolding hmem_def hinsert_def by simp\n\nlemma hf_ext: \"a = b \\<longleftrightarrow> (\\<forall>x. x \\<^bold>\\<in> a \\<longleftrightarrow> x \\<^bold>\\<in> b)\"\n  unfolding hmem_def set_eq_iff [symmetric]\n  by (metis HF_hfset)\n\nlemma finite_cases [consumes 1, case_names empty insert]:\n  \"\\<lbrakk>finite F; F = {} \\<Longrightarrow> P; \\<And>A x. \\<lbrakk>F = insert x A; x \\<notin> A; finite A\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (induct F rule: finite_induct, simp_all)\n\nlemma hf_cases [cases type: hf, case_names 0 hinsert]:\n  obtains \"y = 0\" | a b where \"y = b \\<triangleleft> a\" and \"\\<not> a \\<^bold>\\<in> b\"\nproof -\n  have \"finite (hfset y)\" by (rule finite_hfset)\n  thus thesis\n    by (metis Zero_hf_def finite_cases hf_ext hfset_HF hinsert_def hmem_def that)\nqed\n\nlemma Rep_hf_hinsert:\n  \"\\<not> a \\<^bold>\\<in> b \\<Longrightarrow> Rep_hf (hinsert a b) = 2 ^ (Rep_hf a) + Rep_hf b\"\n  unfolding hinsert_def HF_def hfset_def\n  apply (simp add: image_image Abs_hf_inverse Rep_hf_inverse)\n  apply (subst set_encode_insert, simp)\n  apply (clarsimp simp add: hmem_def hfset_def image_def\n    Rep_hf_inject [symmetric] Abs_hf_inverse, simp)\n  done\n\nlemma less_two_power: \"n < 2 ^ n\"\n  by (induct n, auto)\n\nsection{*Verifying the Axioms of HF*}\n\ntext{*HF1*}\nlemma hempty_iff: \"z=0 \\<longleftrightarrow> (\\<forall>x. \\<not> x \\<^bold>\\<in> z)\"\n  by (simp add: hf_ext)\n\ntext{*HF2*}\nlemma hinsert_iff: \"z = x \\<triangleleft> y \\<longleftrightarrow> (\\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> u \\<^bold>\\<in> x | u = y)\"\n  by (auto simp: hf_ext)\n\ntext{*HF induction*}\nlemma hf_induct [induct type: hf, case_names 0 hinsert]:\n  assumes [simp]: \"P 0\"\n                  \"\\<And>x y. \\<lbrakk>P x; P y; \\<not> x \\<^bold>\\<in> y\\<rbrakk> \\<Longrightarrow> P (y \\<triangleleft> x)\"\n  shows \"P z\"\nproof (induct z rule: wf_induct [where r=\"measure Rep_hf\", OF wf_measure])\n  case (1 x) show ?case\n    proof (cases x rule: hf_cases)\n      case 0 thus ?thesis by simp\n    next\n      case (hinsert a b)\n      thus ?thesis using 1\n        by (simp add: Rep_hf_hinsert\n                      less_le_trans [OF less_two_power le_add1])\n    qed\nqed\n\ntext{*HF3*}\nlemma hf_induct_ax: \"\\<lbrakk>P 0; \\<forall>x. P x \\<longrightarrow> (\\<forall>y. P y \\<longrightarrow> P (x \\<triangleleft> y))\\<rbrakk> \\<Longrightarrow> P x\"\n  by (induct x, auto)\n\nlemma hf_equalityI [intro]: \"(\\<And>x. x \\<^bold>\\<in> a \\<longleftrightarrow> x \\<^bold>\\<in> b) \\<Longrightarrow> a = b\"\n  by (simp add: hf_ext)\n\nlemma hinsert_nonempty [simp]: \"A \\<triangleleft> a \\<noteq> 0\"\n  by (auto simp: hf_ext)\n\nlemma hinsert_commute: \"(z \\<triangleleft> y) \\<triangleleft> x = (z \\<triangleleft> x) \\<triangleleft> y\"\n  by (auto simp: hf_ext)\n\nlemma singleton_eq_iff [iff]: \"\\<lbrace>a\\<rbrace> = \\<lbrace>b\\<rbrace> \\<longleftrightarrow> a=b\"\n  by (metis hmem_hempty hmem_hinsert)\n\nlemma doubleton_eq_iff: \"\\<lbrace>a,b\\<rbrace> = \\<lbrace>c,d\\<rbrace> \\<longleftrightarrow> (a=c & b=d) | (a=d & b=c)\"\n  by (metis (hide_lams, no_types) hinsert_commute hmem_hempty hmem_hinsert)\n\nsection {* Ordered Pairs, from ZF/ZF.thy *}\n\ndefinition hpair :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"hpair a b = \\<lbrace>\\<lbrace>a\\<rbrace>,\\<lbrace>a,b\\<rbrace>\\<rbrace>\"\n\ndefinition hfst :: \"hf \\<Rightarrow> hf\"\n  where \"hfst p \\<equiv> THE x. \\<exists>y. p = hpair x y\"\n\ndefinition hsnd :: \"hf \\<Rightarrow> hf\"\n  where \"hsnd p \\<equiv> THE y. \\<exists>x. p = hpair x y\"\n\ndefinition hsplit :: \"[[hf, hf] \\<Rightarrow> 'a, hf] \\<Rightarrow> 'a::{}\"  --{*for pattern-matching*}\n  where \"hsplit c \\<equiv> %p. c (hfst p) (hsnd p)\"\n\ntext {* Ordered Pairs, from ZF/ZF.thy *}\n\nnonterminal hfs\nsyntax\n  \"\"          :: \"hf \\<Rightarrow> hfs\"                    (\"_\")\n  \"_Enum\"     :: \"[hf, hfs] \\<Rightarrow> hfs\"             (\"_,/ _\")\n  \"_Tuple\"    :: \"[hf, hfs] \\<Rightarrow> hf\"              (\"<(_,/ _)>\")\n  \"_hpattern\" :: \"[pttrn, patterns] \\<Rightarrow> pttrn\"   (\"<_,/ _>\")\nsyntax (xsymbols)\n  \"_Tuple\"    :: \"[hf, hfs] \\<Rightarrow> hf\"              (\"\\<langle>(_,/ _)\\<rangle>\")\n  \"_hpattern\" :: \"[pttrn, patterns] \\<Rightarrow> pttrn\"   (\"\\<langle>_,/ _\\<rangle>\")\nsyntax (HTML output)\n  \"_Tuple\"    :: \"[hf, hfs] \\<Rightarrow> hf\"              (\"\\<langle>(_,/ _)\\<rangle>\")\n  \"_hpattern\" :: \"[pttrn, patterns] \\<Rightarrow> pttrn\"   (\"\\<langle>_,/ _\\<rangle>\")\n\ntranslations\n  \"<x, y, z>\"    == \"<x, <y, z>>\"\n  \"<x, y>\"       == \"CONST hpair x y\"\n  \"<x, y, z>\"    == \"<x, <y, z>>\"\n  \"%<x,y,zs>. b\" == \"CONST hsplit(%x <y,zs>. b)\"\n  \"%<x,y>. b\"    == \"CONST hsplit(%x y. b)\"\n\n\nlemma hpair_def': \"hpair a b = \\<lbrace>\\<lbrace>a,a\\<rbrace>,\\<lbrace>a,b\\<rbrace>\\<rbrace>\"\n  by (auto simp: hf_ext hpair_def)\n\nlemma hpair_iff [simp]: \"hpair a b = hpair a' b' \\<longleftrightarrow> a=a' & b=b'\"\n  by (auto simp: hpair_def' doubleton_eq_iff)\n\nlemmas hpair_inject = hpair_iff [THEN iffD1, THEN conjE, elim!]\n\nlemma hfst_conv [simp]: \"hfst \\<langle>a,b\\<rangle> = a\"\n  by (simp add: hfst_def)\n\nlemma hsnd_conv [simp]: \"hsnd \\<langle>a,b\\<rangle> = b\"\n  by (simp add: hsnd_def)\n\nlemma hsplit [simp]: \"hsplit c \\<langle>a,b\\<rangle> = c a b\"\n  by (simp add: hsplit_def)\n\n\nsection{*Unions, Comprehensions, Intersections*}\n\nsubsection{*Unions*}\n\ntext{*Theorem 1.5 (Existence of the union of two sets).*}\nlemma binary_union: \"\\<exists>z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> u \\<^bold>\\<in> x | u \\<^bold>\\<in> y\"\nproof (induct x rule: hf_induct)\n  case 0 thus ?case by auto\nnext\n  case (hinsert a b) thus ?case by (metis hmem_hinsert)\nqed\n\ntext{*Theorem 1.6 (Existence of the union of a set of sets).*}\nlemma union_of_set: \"\\<exists>z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> (\\<exists>y. y \\<^bold>\\<in> x & u \\<^bold>\\<in> y)\"\nproof (induct x rule: hf_induct)\n  case 0 thus ?case by (metis hmem_hempty)\nnext\n  case (hinsert a b)\n  then show ?case\n    by (metis hmem_hinsert binary_union [of a])\nqed\n\nsubsection {* Set comprehensions *}\n\ntext{*Theorem 1.7, comprehension scheme*}\nlemma comprehension: \"\\<exists>z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> u \\<^bold>\\<in> x & P u\"\nproof (induct x rule: hf_induct)\n  case 0 thus ?case by (metis hmem_hempty)\nnext\n  case (hinsert a b) thus ?case by (metis hmem_hinsert)\nqed\n\ndefinition HCollect :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf\" -- \"comprehension\"\n  where \"HCollect P A = (THE z. \\<forall>u. u \\<^bold>\\<in> z = (P u & u \\<^bold>\\<in> A))\"\n\nsyntax\n  \"_HCollect\" :: \"idt \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> hf\"    (\"(1\\<lbrace>_ <:/ _./ _\\<rbrace>)\")\nsyntax (xsymbols)\n  \"_HCollect\" :: \"idt \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> hf\"    (\"(1\\<lbrace>_ \\<^bold>\\<in>/ _./ _\\<rbrace>)\")\ntranslations\n  \"\\<lbrace>x <: A. P\\<rbrace>\" == \"CONST HCollect (%x. P) A\"\n\nlemma HCollect_iff [iff]: \"hmem x (HCollect P A) \\<longleftrightarrow> P x & x \\<^bold>\\<in> A\"\napply (insert comprehension [of A P], clarify)\napply (simp add: HCollect_def)\napply (rule theI2, blast)\napply (auto simp: hf_ext)\ndone\n\nlemma HCollectI: \"a \\<^bold>\\<in> A \\<Longrightarrow> P a \\<Longrightarrow> hmem a \\<lbrace>x \\<^bold>\\<in> A. P x\\<rbrace>\"\n  by simp\n\nlemma HCollectE:\n  assumes \"a \\<^bold>\\<in> \\<lbrace>x \\<^bold>\\<in> A. P x\\<rbrace>\" obtains \"a \\<^bold>\\<in> A\" \"P a\"\n  using assms by auto\n\nlemma HCollect_hempty [simp]: \"HCollect P 0 = 0\"\n  by (simp add: hf_ext)\n\nsubsection{*Union operators*}\n\ninstantiation hf :: sup\n  begin\n  definition sup_hf :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n    where \"sup_hf a b = (THE z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> u \\<^bold>\\<in> a | u \\<^bold>\\<in> b)\"\n  instance ..\n  end\n\nabbreviation hunion :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\" (infixl \"\\<squnion>\" 65) where\n  \"hunion \\<equiv> sup\"\n\nlemma hunion_iff [iff]: \"hmem x (a \\<squnion> b) \\<longleftrightarrow> x \\<^bold>\\<in> a | x \\<^bold>\\<in> b\"\napply (insert binary_union [of a b], clarify)\napply (simp add: sup_hf_def)\napply (rule theI2)\napply (auto simp: hf_ext)\ndone\n\ndefinition HUnion :: \"hf \\<Rightarrow> hf\"        (\"\\<Squnion>_\" [900] 900)\n  where \"HUnion A = (THE z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> (\\<exists>y. y \\<^bold>\\<in> A & u \\<^bold>\\<in> y))\"\n\nlemma HUnion_iff [iff]: \"hmem x (\\<Squnion> A) \\<longleftrightarrow> (\\<exists>y. y \\<^bold>\\<in> A & x \\<^bold>\\<in> y)\"\napply (insert union_of_set [of A], clarify)\napply (simp add: HUnion_def)\napply (rule theI2)\napply (auto simp: hf_ext)\ndone\n\nlemma HUnion_hempty [simp]: \"\\<Squnion> 0 = 0\"\n  by (simp add: hf_ext)\n\nlemma HUnion_hinsert [simp]: \"\\<Squnion>(A \\<triangleleft> a) = a \\<squnion> \\<Squnion>A\"\n  by (auto simp: hf_ext)\n\nlemma HUnion_hunion [simp]: \"\\<Squnion>(A \\<squnion> B) =  \\<Squnion>A \\<squnion> \\<Squnion>B\"\n  by blast\n\nsubsection{*Definition 1.8, Intersections*}\n\ninstantiation hf :: inf\nbegin\n\ndefinition inf_hf :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"inf_hf a b = \\<lbrace>x \\<^bold>\\<in> a. x \\<^bold>\\<in> b\\<rbrace>\"\n\ninstance ..\n\nend\n\nabbreviation hinter :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\" (infixl \"\\<sqinter>\" 70) where\n  \"hinter \\<equiv> inf\"\n\nlemma hinter_iff [iff]: \"hmem u (x \\<sqinter> y) \\<longleftrightarrow> u \\<^bold>\\<in> x & u \\<^bold>\\<in> y\"\n  by (metis HCollect_iff inf_hf_def)\n\ndefinition HInter :: \"hf \\<Rightarrow> hf\"           (\"\\<Sqinter>_\" [900] 900)\n  where \"HInter(A) = \\<lbrace>x \\<^bold>\\<in> HUnion(A). \\<forall>y. y \\<^bold>\\<in> A \\<longrightarrow> x \\<^bold>\\<in> y\\<rbrace>\"\n\nlemma HInter_hempty [iff]: \"\\<Sqinter> 0 = 0\"\n  by (metis HCollect_hempty HUnion_hempty HInter_def)\n\nlemma HInter_iff [simp]: \"A\\<noteq>0 \\<Longrightarrow> hmem x (\\<Sqinter> A) \\<longleftrightarrow> (\\<forall>y. y \\<^bold>\\<in> A \\<longrightarrow> x \\<^bold>\\<in> y)\"\n  by (auto simp: HInter_def)\n\nlemma HInter_hinsert [simp]: \"A\\<noteq>0 \\<Longrightarrow> \\<Sqinter>(A \\<triangleleft> a) = a \\<sqinter> \\<Sqinter>A\"\n  by (auto simp: hf_ext HInter_iff [OF hinsert_nonempty])\n\nsubsection{*Set Difference*}\n\ninstantiation hf :: minus\n  begin\n  definition minus_hf where \"minus A B = \\<lbrace>x \\<^bold>\\<in> A. \\<not> x \\<^bold>\\<in> B\\<rbrace>\"\n  instance proof qed\n  end\n\nlemma hdiff_iff [iff]: \"hmem u (x - y) \\<longleftrightarrow> u \\<^bold>\\<in> x & \\<not> u \\<^bold>\\<in> y\"\n  by (auto simp: minus_hf_def)\n\nlemma hdiff_zero [simp]: fixes x :: hf shows \"(x - 0) = x\"\n  by blast\n\nlemma zero_hdiff [simp]: fixes x :: hf shows \"(0 - x) = 0\"\n  by blast\n\nlemma hdiff_insert: \"A - (B \\<triangleleft> a) = A - B - \\<lbrace>a\\<rbrace>\"\n  by blast\n\nlemma hinsert_hdiff_if:\n  \"(A \\<triangleleft> x) - B = (if x \\<^bold>\\<in> B then A - B else (A - B) \\<triangleleft> x)\"\n  by auto\n\n\nsection{*Replacement*}\n\ntext{*Theorem 1.9 (Replacement Scheme).*}\nlemma replacement:\n  \"(\\<forall>u v v'. u \\<^bold>\\<in> x \\<longrightarrow> R u v \\<longrightarrow> R u v' \\<longrightarrow> v'=v) \\<Longrightarrow> \\<exists>z. \\<forall>v. v \\<^bold>\\<in> z \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> x & R u v)\"\nproof (induct x rule: hf_induct)\n  case 0 thus ?case\n    by (metis hmem_hempty)\nnext\n  case (hinsert a b) thus ?case\n    by simp (metis hmem_hinsert)\nqed\n\nlemma replacement_fun: \"\\<exists>z. \\<forall>v. v \\<^bold>\\<in> z \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> x & v = f u)\"\n  by (rule replacement [where R = \"\\<lambda>u v. v = f u\"]) auto\n\ndefinition PrimReplace :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf\"\n  where \"PrimReplace A R = (THE z. \\<forall>v. v \\<^bold>\\<in> z \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> A & R u v))\"\n\ndefinition Replace :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf\"\n  where \"Replace A R = PrimReplace A (\\<lambda>x y. (\\<exists>!z. R x z) & R x y)\"\n\ndefinition RepFun :: \"hf \\<Rightarrow> (hf \\<Rightarrow> hf) \\<Rightarrow> hf\"\n  where \"RepFun A f = Replace A (\\<lambda>x y. y = f x)\"\n\n\nsyntax\n  \"_HReplace\"  :: \"[pttrn, pttrn, hf, bool] \\<Rightarrow> hf\" (\"(1{|_ ./ _<: _, _|})\")\n  \"_HRepFun\"   :: \"[hf, pttrn, hf] \\<Rightarrow> hf\"          (\"(1{|_ ./ _<: _|})\" [51,0,51])\n  \"_HINTER\"    :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"          (\"(3INT _<:_./ _)\" 10)\n  \"_HUNION\"    :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"          (\"(3UN _<:_./ _)\" 10)\n\nsyntax (xsymbols)\n  \"_HReplace\"  :: \"[pttrn, pttrn, hf, bool] \\<Rightarrow> hf\" (\"(1\\<lbrace>_ ./ _ \\<^bold>\\<in> _, _\\<rbrace>)\")\n  \"_HRepFun\"   :: \"[hf, pttrn, hf] \\<Rightarrow> hf\"          (\"(1\\<lbrace>_ ./ _ \\<^bold>\\<in> _\\<rbrace>)\" [51,0,51])\n  \"_HUNION\"    :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"          (\"(3\\<Squnion>_\\<^bold>\\<in>_./ _)\" 10)\n  \"_HINTER\"    :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"          (\"(3\\<Sqinter>_\\<^bold>\\<in>_./ _)\" 10)\n\nsyntax (HTML output)\n  \"_HReplace\"  :: \"[pttrn, pttrn, hf, bool] \\<Rightarrow> hf\" (\"(1\\<lbrace>_ ./ _ \\<^bold>\\<in> _, _\\<rbrace>)\")\n  \"_HRepFun\"   :: \"[hf, pttrn, hf] \\<Rightarrow> hf\"          (\"(1\\<lbrace>_ ./ _ \\<^bold>\\<in> _\\<rbrace>)\" [51,0,51])\n  \"_HUNION\"    :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"          (\"(3\\<Squnion>_\\<^bold>\\<in>_./ _)\" 10)\n  \"_HINTER\"    :: \"[pttrn, hf, hf] \\<Rightarrow> hf\"          (\"(3\\<Sqinter>_\\<^bold>\\<in>_./ _)\" 10)\n\ntranslations\n  \"{|y. x<:A, Q|}\" == \"CONST Replace A (%x y. Q)\"\n  \"{|b. x<:A|}\"    == \"CONST RepFun A (%x. b)\"\n  \"INT x<:A. B\"    == \"CONST HInter(CONST RepFun A (%x. B))\"\n  \"UN x<:A. B\"     == \"CONST HUnion(CONST RepFun A (%x. B))\"\n\nlemma PrimReplace_iff:\n  assumes sv: \"\\<forall>u v v'. u \\<^bold>\\<in> A \\<longrightarrow> R u v \\<longrightarrow> R u v' \\<longrightarrow> v'=v\"\n  shows \"v \\<^bold>\\<in> (PrimReplace A R) \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> A & R u v)\"\napply (insert replacement [OF sv], clarify)\napply (simp add: PrimReplace_def)\napply (rule theI2)\napply (auto simp: hf_ext)\ndone\n\nlemma Replace_iff [iff]:\n  \"v \\<^bold>\\<in> Replace A R \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> A & R u v & (\\<forall>y. R u y \\<longrightarrow> y=v))\"\napply (simp add: Replace_def)\napply (subst PrimReplace_iff, auto)\ndone\n\nlemma Replace_0 [simp]: \"Replace 0 R = 0\"\n  by blast\n\nlemma Replace_hunion [simp]: \"Replace (A \\<squnion> B) R = Replace A R  \\<squnion>  Replace B R\"\n  by blast\n\nlemma Replace_cong [cong]:\n    \"\\<lbrakk> A=B;  !!x y. x \\<^bold>\\<in> B \\<Longrightarrow> P x y \\<longleftrightarrow> Q x y \\<rbrakk>  \\<Longrightarrow> Replace A P = Replace B Q\"\n  by (simp add: hf_ext cong: conj_cong)\n\nlemma RepFun_iff [iff]: \"v \\<^bold>\\<in> (RepFun A f) \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> A & v = f u)\"\n  by (auto simp: RepFun_def)\n\nlemma RepFun_cong [cong]:\n    \"\\<lbrakk> A=B;  !!x. x \\<^bold>\\<in> B \\<Longrightarrow> f(x)=g(x) \\<rbrakk>  \\<Longrightarrow> RepFun A f = RepFun B g\"\nby (simp add: RepFun_def)\n\nlemma triv_RepFun [simp]: \"RepFun A (\\<lambda>x. x) = A\"\nby blast\n\nlemma RepFun_0 [simp]: \"RepFun 0 f = 0\"\n  by blast\n\nlemma RepFun_hinsert [simp]: \"RepFun (hinsert a b) f = hinsert (f a) (RepFun b f)\"\n  by blast\n\nlemma RepFun_hunion [simp]:\n  \"RepFun (A \\<squnion> B) f = RepFun A f  \\<squnion>  RepFun B f\"\n  by blast\n\n\nsection{*Subset relation and the Lattice Properties*}\n\ntext{*Definition 1.10 (Subset relation).*}\ninstantiation hf :: order\n  begin\n  definition less_eq_hf where \"A \\<le> B \\<longleftrightarrow> (\\<forall>x. x \\<^bold>\\<in> A \\<longrightarrow> x \\<^bold>\\<in> B)\"\n\n  definition less_hf    where \"A < B \\<longleftrightarrow> A \\<le> B & A \\<noteq> (B::hf)\"\n\n  instance proof qed (auto simp: less_eq_hf_def less_hf_def)\n  end\n\nsubsection{*Rules for subsets*}\n\nlemma hsubsetI [intro!]:\n    \"(!!x. x\\<^bold>\\<in>A \\<Longrightarrow> x\\<^bold>\\<in>B) \\<Longrightarrow> A \\<le> B\"\n  by (simp add: less_eq_hf_def)\n\ntext{*Classical elimination rule*}\nlemma hsubsetCE [elim]: \"\\<lbrakk> A \\<le> B;  ~(c\\<^bold>\\<in>A) \\<Longrightarrow> P;  c\\<^bold>\\<in>B \\<Longrightarrow> P \\<rbrakk>  \\<Longrightarrow> P\"\n  by (auto simp: less_eq_hf_def)\n\ntext{*Rule in Modus Ponens style*}\nlemma hsubsetD [elim]: \"\\<lbrakk> A \\<le> B;  c\\<^bold>\\<in>A \\<rbrakk> \\<Longrightarrow> c\\<^bold>\\<in>B\"\n  by (simp add: less_eq_hf_def)\n\ntext{*Sometimes useful with premises in this order*}\nlemma rev_hsubsetD: \"\\<lbrakk> c\\<^bold>\\<in>A; A\\<le>B \\<rbrakk> \\<Longrightarrow> c\\<^bold>\\<in>B\"\n  by blast\n\nlemma contra_hsubsetD: \"\\<lbrakk> A \\<le> B; c \\<notin> B \\<rbrakk>  \\<Longrightarrow> c \\<notin> A\"\n  by blast\n\nlemma rev_contra_hsubsetD: \"\\<lbrakk> c \\<notin> B;  A \\<le> B \\<rbrakk>  \\<Longrightarrow> c \\<notin> A\"\n  by blast\n\nlemma hf_equalityE:\n  fixes A :: hf shows \"A = B \\<Longrightarrow> (A \\<le> B \\<Longrightarrow> B \\<le> A \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (metis order_refl)\n\n\nsubsection{*Lattice properties*}\n\ninstantiation hf :: distrib_lattice\n  begin\n  instance proof qed (auto simp: less_eq_hf_def less_hf_def inf_hf_def)\n  end\n\ninstantiation hf :: bounded_lattice_bot\n  begin\n  definition bot_hf where \"bot_hf = (0::hf)\"\n  instance proof qed (auto simp: less_eq_hf_def bot_hf_def)\n  end\n\nlemma hinter_hempty_left [simp]: \"0 \\<sqinter> A = 0\"\n  by (metis bot_hf_def inf_bot_left)\n\nlemma hinter_hempty_right [simp]: \"A \\<sqinter> 0 = 0\"\n  by (metis bot_hf_def inf_bot_right)\n\nlemma hunion_hempty_left [simp]: \"0 \\<squnion> A = A\"\n  by (metis bot_hf_def sup_bot_left)\n\nlemma hunion_hempty_right [simp]: \"A \\<squnion> 0 = A\"\n  by (metis bot_hf_def sup_bot_right)\n\nlemma less_eq_hempty [simp]: \"u \\<le> 0 \\<longleftrightarrow> u = (0::hf)\"\n  by (metis hempty_iff less_eq_hf_def)\n\nlemma less_eq_insert1_iff [iff]: \"(hinsert x y) \\<le> z \\<longleftrightarrow> x \\<^bold>\\<in> z & y \\<le> z\"\n  by (auto simp: less_eq_hf_def)\n\nlemma less_eq_insert2_iff:\n  \"z \\<le> (hinsert x y) \\<longleftrightarrow> z \\<le> y \\<or> (\\<exists>u. hinsert x u = z \\<and> ~ x \\<^bold>\\<in> u \\<and> u \\<le> y)\"\nproof (cases \"x \\<^bold>\\<in> z\")\n  case True\n  hence u: \"hinsert x (z - \\<lbrace>x\\<rbrace>) = z\" by auto\n  show ?thesis\n    proof\n      assume \"z \\<le> (hinsert x y)\"\n      thus \"z \\<le> y \\<or> (\\<exists>u. hinsert x u = z \\<and> \\<not> x \\<^bold>\\<in> u \\<and> u \\<le> y)\"\n        by (simp add: less_eq_hf_def) (metis u hdiff_iff hmem_hinsert)\n    next\n      assume \"z \\<le> y \\<or> (\\<exists>u. hinsert x u = z \\<and> \\<not> x \\<^bold>\\<in> u \\<and> u \\<le> y)\"\n      thus \"z \\<le> (hinsert x y)\"\n        by (auto simp: less_eq_hf_def)\n    qed\nnext\n  case False thus ?thesis\n    by (metis hmem_hinsert less_eq_hf_def)\nqed\n\nlemma zero_le [simp]: \"0 \\<le> (x::hf)\"\n  by blast\n\nlemma hinsert_eq_sup: \"b \\<triangleleft> a = b \\<squnion> \\<lbrace>a\\<rbrace>\"\n  by blast\n\nlemma hunion_hinsert_left: \"hinsert x A \\<squnion> B = hinsert x (A \\<squnion> B)\"\n  by blast\n\nlemma hunion_hinsert_right: \"B \\<squnion> hinsert x A = hinsert x (B \\<squnion> A)\"\n  by blast\n\nlemma hinter_hinsert_left: \"hinsert x A \\<sqinter> B = (if x \\<^bold>\\<in> B then hinsert x (A \\<sqinter> B) else A \\<sqinter> B)\"\n  by auto\n\nlemma hinter_hinsert_right: \"B \\<sqinter> hinsert x A = (if x \\<^bold>\\<in> B then hinsert x (B \\<sqinter> A) else B \\<sqinter> A)\"\n  by auto\n\n\nsection{*Foundation, Cardinality, Powersets*}\n\nsubsection{*Foundation*}\n\ntext{*Theorem 1.13: Foundation (Regularity) Property.*}\nlemma foundation:\n  assumes z: \"z \\<noteq> 0\" shows \"\\<exists>w. w \\<^bold>\\<in> z & w \\<sqinter> z = 0\"\nproof -\n  { fix x\n    assume z: \"(\\<forall>w. w \\<^bold>\\<in> z \\<longrightarrow> w \\<sqinter> z \\<noteq> 0)\"\n    have \"~ x \\<^bold>\\<in> z \\<and> x \\<sqinter> z = 0\"\n    proof (induction x rule: hf_induct)\n      case 0 thus ?case\n        by (metis hinter_hempty_left z)\n    next\n      case (hinsert x y) thus ?case\n        by (metis hinter_hinsert_left z)\n    qed\n  }\n  thus ?thesis using z\n    by (metis z hempty_iff)\nqed\n\nlemma hmem_not_refl: \"~ (x \\<^bold>\\<in> x)\"\n  using foundation [of \"\\<lbrace>x\\<rbrace>\"]\n  by (metis hinter_iff hmem_hempty hmem_hinsert)\n\nlemma hmem_not_sym: \"~ (x \\<^bold>\\<in> y \\<and> y \\<^bold>\\<in> x)\"\n  using foundation [of \"\\<lbrace>x,y\\<rbrace>\"]\n  by (metis hinter_iff hmem_hempty hmem_hinsert)\n\nlemma hmem_ne: \"x \\<^bold>\\<in> y \\<Longrightarrow> x \\<noteq> y\"\n  by (metis hmem_not_refl)\n\nlemma hmem_Sup_ne: \"x <: y \\<Longrightarrow> \\<Squnion>x \\<noteq> y\"\n  by (metis HUnion_iff hmem_not_sym)\n\nlemma hpair_neq_fst: \"\\<langle>a,b\\<rangle> \\<noteq> a\"\n  by (metis hpair_def hinsert_iff hmem_not_sym)\n\nlemma hpair_neq_snd: \"\\<langle>a,b\\<rangle> \\<noteq> b\"\n  by (metis hpair_def hinsert_iff hmem_not_sym)\n\nlemma hpair_nonzero [simp]: \"\\<langle>x,y\\<rangle> \\<noteq> 0\"\n  by (auto simp: hpair_def)\n\nlemma zero_notin_hpair: \"~ 0 \\<^bold>\\<in> \\<langle>x,y\\<rangle>\"\n  by (auto simp: hpair_def)\n\n\nsubsection{*Cardinality*}\n\ntext{*First we need to hack the underlying representation*}\nlemma hfset_0: \"hfset 0 = {}\"\n  by (metis Zero_hf_def finite.emptyI hfset_HF)\n\nlemma hfset_hinsert: \"hfset (b \\<triangleleft> a) = insert a (hfset b)\"\n  by (metis finite_insert hinsert_def HF.finite_hfset hfset_HF)\n\nlemma hfset_hdiff: \"hfset (x - y) = hfset x - hfset y\"\nproof (induct x arbitrary: y rule: hf_induct)\n  case 0 thus ?case\n    by (simp add: hfset_0)\nnext\n  case (hinsert a b) thus ?case\n    by (simp add: hfset_hinsert Set.insert_Diff_if hinsert_hdiff_if hmem_def)\nqed\n\ndefinition hcard :: \"hf \\<Rightarrow> nat\"\n  where \"hcard x = card (hfset x)\"\n\nlemma hcard_0 [simp]: \"hcard 0 = 0\"\n  by (simp add: hcard_def hfset_0)\n\nlemma hcard_hinsert_if: \"hcard (hinsert x y) = (if x \\<^bold>\\<in> y then hcard y else Suc (hcard y))\"\n  by (simp add: hcard_def hfset_hinsert card_insert_if hmem_def)\n\nlemma hcard_union_inter: \"hcard (x \\<squnion> y) + hcard (x \\<sqinter> y) = hcard x + hcard y\"\n  apply (induct x arbitrary: y rule: hf_induct)\n  apply (auto simp: hcard_hinsert_if hunion_hinsert_left hinter_hinsert_left)\n  done\n\nlemma hcard_hdiff1_less: \"x \\<^bold>\\<in> z \\<Longrightarrow> hcard (z - \\<lbrace>x\\<rbrace>) < hcard z\"\n  by (simp add: hcard_def hfset_hdiff hfset_hinsert hfset_0)\n     (metis card_Diff1_less finite_hfset hmem_def)\n\nsubsection{*Powerset Operator*}\n\ntext{*Theorem 1.11 (Existence of the power set).*}\nlemma powerset: \"\\<exists>z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> u \\<le> x\"\nproof (induction x rule: hf_induct)\n case 0 thus ?case\n    by (metis hmem_hempty hmem_hinsert less_eq_hempty)\nnext\n  case (hinsert a b)\n  then obtain Pb where Pb: \"\\<forall>u. u \\<^bold>\\<in> Pb \\<longleftrightarrow> u \\<le> b\"\n    by auto\n  obtain RPb where RPb: \"\\<forall>v. v \\<^bold>\\<in> RPb \\<longleftrightarrow> (\\<exists>u. u \\<^bold>\\<in> Pb & v = hinsert a u)\"\n    using replacement_fun ..\n  thus ?case using Pb binary_union [of Pb RPb]\n    apply (simp add: less_eq_insert2_iff, clarify)\n    apply (rule_tac x=z in exI)\n    apply (metis hinsert.hyps less_eq_hf_def)\n    done\nqed\n\ndefinition HPow :: \"hf \\<Rightarrow> hf\"\n  where \"HPow x = (THE z. \\<forall>u. u \\<^bold>\\<in> z \\<longleftrightarrow> u \\<le> x)\"\n\nlemma HPow_iff [iff]: \"u \\<^bold>\\<in> HPow x \\<longleftrightarrow> u \\<le> x\"\napply (insert powerset [of x], clarify)\napply (simp add: HPow_def)\napply (rule theI2)\napply (auto simp: hf_ext)\ndone\n\nlemma HPow_mono: \"x \\<le> y \\<Longrightarrow> HPow x \\<le> HPow y\"\n  by (metis HPow_iff less_eq_hf_def order_trans)\n\nlemma HPow_mono_strict: \"x < y \\<Longrightarrow> HPow x < HPow y\"\n  by (metis HPow_iff HPow_mono less_le_not_le order_eq_iff)\n\nlemma HPow_mono_iff [simp]: \"HPow x \\<le> HPow y \\<longleftrightarrow> x \\<le> y\"\n  by (metis HPow_iff HPow_mono hsubsetCE order_refl)\n\nlemma HPow_mono_strict_iff [simp]: \"HPow x < HPow y \\<longleftrightarrow> x < y\"\n  by (metis HPow_mono_iff less_le_not_le)\n\n\nsection{*Bounded Quantifiers*}\n\ndefinition HBall :: \"hf \\<Rightarrow> (hf \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"HBall A P \\<longleftrightarrow> (\\<forall>x. x <: A \\<longrightarrow> P x)\"   -- \"bounded universal quantifiers\"\n\ndefinition HBex :: \"hf \\<Rightarrow> (hf \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n  \"HBex A P \\<longleftrightarrow> (\\<exists>x. x <: A \\<and> P x)\"   -- \"bounded existential quantifiers\"\n\nsyntax\n  \"_HBall\"       :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3ALL _<:_./ _)\" [0, 0, 10] 10)\n  \"_HBex\"        :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3EX _<:_./ _)\"  [0, 0, 10] 10)\n  \"_HBex1\"       :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3EX! _<:_./ _)\" [0, 0, 10] 10)\n\nsyntax (xsymbols)\n  \"_HBall\"       :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3\\<forall>_\\<^bold>\\<in>_./ _)\"  [0, 0, 10] 10)\n  \"_HBex\"        :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3\\<exists>_\\<^bold>\\<in>_./ _)\"  [0, 0, 10] 10)\n  \"_HBex1\"       :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3\\<exists>!_\\<^bold>\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax (HTML output)\n  \"_HBall\"       :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3\\<forall>_\\<^bold>\\<in>_./ _)\"  [0, 0, 10] 10)\n  \"_HBex\"        :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3\\<exists>_\\<^bold>\\<in>_./ _)\"  [0, 0, 10] 10)\n  \"_HBex1\"       :: \"pttrn \\<Rightarrow> hf \\<Rightarrow> bool \\<Rightarrow> bool\"      (\"(3\\<exists>!_\\<^bold>\\<in>_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"ALL x<:A. P\" == \"CONST HBall A (%x. P)\"\n  \"EX x<:A. P\" == \"CONST HBex A (%x. P)\"\n  \"EX! x<:A. P\" => \"EX! x. x:A & P\"\n\nlemma hball_cong [cong]:\n    \"\\<lbrakk> A=A';  !!x. x \\<^bold>\\<in> A' \\<Longrightarrow> P(x) \\<longleftrightarrow> P'(x) \\<rbrakk>  \\<Longrightarrow> (\\<forall>x\\<^bold>\\<in>A. P(x)) \\<longleftrightarrow> (\\<forall>x\\<^bold>\\<in>A'. P'(x))\"\n  by (simp add: HBall_def)\n\nlemma hballI [intro!]: \"(!!x. x<:A \\<Longrightarrow> P x) \\<Longrightarrow> ALL x<:A. P x\"\n  by (simp add: HBall_def)\n\nlemma hbspec [dest?]: \"ALL x<:A. P x \\<Longrightarrow> x<:A \\<Longrightarrow> P x\"\n  by (simp add: HBall_def)\n\n\n\nlemma hbex_cong [cong]:\n    \"\\<lbrakk> A=A';  !!x. x \\<^bold>\\<in> A' \\<Longrightarrow> P(x) \\<longleftrightarrow> P'(x) \\<rbrakk>  \\<Longrightarrow> (\\<exists>x\\<^bold>\\<in>A. P(x)) \\<longleftrightarrow> (\\<exists>x\\<^bold>\\<in>A'. P'(x))\"\n  by (simp add: HBex_def cong: conj_cong)\n\nlemma hbexI [intro]: \"P x \\<Longrightarrow> x<:A \\<Longrightarrow> EX x<:A. P x\"\n  by (unfold HBex_def) blast\n\nlemma rev_hbexI [intro?]: \"x<:A \\<Longrightarrow> P x \\<Longrightarrow> EX x<:A. P x\"\n  by (unfold HBex_def) blast\n\nlemma bexCI: \"(ALL x<:A. ~P x \\<Longrightarrow> P a) \\<Longrightarrow> a<:A \\<Longrightarrow> EX x<:A. P x\"\n  by (unfold HBex_def) blast\n\nlemma hbexE [elim!]: \"EX x<:A. P x \\<Longrightarrow> (!!x. x<:A \\<Longrightarrow> P x \\<Longrightarrow> Q) \\<Longrightarrow> Q\"\n  by (unfold HBex_def) blast\n\nlemma hball_triv [simp]: \"(ALL x<:A. P) = ((EX x. x<:A) --> P)\"\n  -- {* Trival rewrite rule. *}\n  by (simp add: HBall_def)\n\nlemma hbex_triv [simp]: \"(EX x<:A. P) = ((EX x. x<:A) & P)\"\n  -- {* Dual form for existentials. *}\n  by (simp add: HBex_def)\n\nlemma hbex_triv_one_point1 [simp]: \"(EX x<:A. x = a) = (a<:A)\"\n  by blast\n\nlemma hbex_triv_one_point2 [simp]: \"(EX x<:A. a = x) = (a<:A)\"\n  by blast\n\nlemma hbex_one_point1 [simp]: \"(EX x<:A. x = a & P x) = (a<:A & P a)\"\n  by blast\n\nlemma hbex_one_point2 [simp]: \"(EX x<:A. a = x & P x) = (a<:A & P a)\"\n  by blast\n\nlemma hball_one_point1 [simp]: \"(ALL x<:A. x = a --> P x) = (a<:A --> P a)\"\n  by blast\n\nlemma hball_one_point2 [simp]: \"(ALL x<:A. a = x --> P x) = (a<:A --> P a)\"\n  by blast\n\nlemma hball_conj_distrib:\n  \"(\\<forall>x\\<^bold>\\<in>A. P x \\<and> Q x) \\<longleftrightarrow> ((\\<forall>x\\<^bold>\\<in>A. P x) \\<and> (\\<forall>x\\<^bold>\\<in>A. Q x))\"\n  by blast\n\nlemma hbex_disj_distrib:\n  \"(\\<exists>x\\<^bold>\\<in>A. P x \\<or> Q x) \\<longleftrightarrow> ((\\<exists>x\\<^bold>\\<in>A. P x) \\<or> (\\<exists>x\\<^bold>\\<in>A. Q x))\"\n  by blast\n\nlemma hb_all_simps [simp, no_atp]:\n  \"\\<And>A P Q. (\\<forall>x \\<^bold>\\<in> A. P x \\<or> Q) \\<longleftrightarrow> ((\\<forall>x \\<^bold>\\<in> A. P x) \\<or> Q)\"\n  \"\\<And>A P Q. (\\<forall>x \\<^bold>\\<in> A. P \\<or> Q x) \\<longleftrightarrow> (P \\<or> (\\<forall>x \\<^bold>\\<in> A. Q x))\"\n  \"\\<And>A P Q. (\\<forall>x \\<^bold>\\<in> A. P \\<longrightarrow> Q x) \\<longleftrightarrow> (P \\<longrightarrow> (\\<forall>x \\<^bold>\\<in> A. Q x))\"\n  \"\\<And>A P Q. (\\<forall>x \\<^bold>\\<in> A. P x \\<longrightarrow> Q) \\<longleftrightarrow> ((\\<exists>x \\<^bold>\\<in> A. P x) \\<longrightarrow> Q)\"\n  \"\\<And>P. (\\<forall>x \\<^bold>\\<in> 0. P x) \\<longleftrightarrow> True\"\n  \"\\<And>a B P. (\\<forall>x \\<^bold>\\<in> B \\<triangleleft> a. P x) \\<longleftrightarrow> (P a \\<and> (\\<forall>x \\<^bold>\\<in> B. P x))\"\n  \"\\<And>P Q. (\\<forall>x \\<^bold>\\<in> HCollect Q A. P x) \\<longleftrightarrow> (\\<forall>x \\<^bold>\\<in> A. Q x \\<longrightarrow> P x)\"\n  \"\\<And>A P. (\\<not> (\\<forall>x \\<^bold>\\<in> A. P x)) \\<longleftrightarrow> (\\<exists>x \\<^bold>\\<in> A. \\<not> P x)\"\n  by auto\n\nlemma hb_ex_simps [simp, no_atp]:\n  \"\\<And>A P Q. (\\<exists>x \\<^bold>\\<in> A. P x \\<and> Q) \\<longleftrightarrow> ((\\<exists>x \\<^bold>\\<in> A. P x) \\<and> Q)\"\n  \"\\<And>A P Q. (\\<exists>x \\<^bold>\\<in> A. P \\<and> Q x) \\<longleftrightarrow> (P \\<and> (\\<exists>x \\<^bold>\\<in> A. Q x))\"\n  \"\\<And>P. (\\<exists>x \\<^bold>\\<in> 0. P x) \\<longleftrightarrow> False\"\n  \"\\<And>a B P. (\\<exists>x \\<^bold>\\<in> B \\<triangleleft> a. P x) \\<longleftrightarrow> (P a | (\\<exists>x \\<^bold>\\<in> B. P x))\"\n  \"\\<And>P Q. (\\<exists>x \\<^bold>\\<in> HCollect Q A. P x) \\<longleftrightarrow> (\\<exists>x \\<^bold>\\<in> A. Q x \\<and> P x)\"\n  \"\\<And>A P. (\\<not>(\\<exists>x \\<^bold>\\<in> A. P x)) \\<longleftrightarrow> (\\<forall>x \\<^bold>\\<in> A. \\<not> P x)\"\n  by auto\n\nlemma le_HCollect_iff: \"A \\<le> \\<lbrace>x \\<^bold>\\<in> B. P x\\<rbrace> \\<longleftrightarrow> A \\<le> B \\<and> (\\<forall>x \\<^bold>\\<in> A. P x)\"\n  by blast\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/HereditarilyFinite/HF.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.857768108626046, "lm_q1q2_score": 0.7610158063170623}}
{"text": "(*  Gauss-Jordan elimination for matrices represented as functions\n    Author: Tobias Nipkow\n*)\nsection \\<open>Gauss-Jordan elimination algorithm\\<close>\ntheory Gauss_Jordan_Elim_Fun\n  imports\n    \"HOL-Combinatorics.Transposition\"\nbegin\n\ntext\\<open>Matrices are functions:\\<close>\n\ntype_synonym 'a matrix = \"nat \\<Rightarrow> nat \\<Rightarrow> 'a\"\n\ntext\\<open>In order to restrict to finite matrices, a matrix is usually combined\nwith one or two natural numbers indicating the maximal row and column of the\nmatrix.\n\nGauss-Jordan elimination is parameterized with a natural number \\<open>n\\<close>. It indicates that the matrix \\<open>A\\<close> has \\<open>n\\<close> rows and columns.\nIn fact, \\<open>A\\<close> is the augmented matrix with \\<open>n+1\\<close> columns. Column\n\\<open>n\\<close> is the ``right-hand side'', i.e.\\ the constant vector \\<open>b\\<close>. The result is the unit matrix augmented with the solution in column\n\\<open>n\\<close>; see the correctness theorem below.\\<close>\n\nfun gauss_jordan :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> ('a)matrix option\" where\n\"gauss_jordan A 0 = Some(A)\" |\n\"gauss_jordan A (Suc m) =\n (case dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] of\n   [] \\<Rightarrow> None |\n   p # _ \\<Rightarrow>\n    (let Ap' = (\\<lambda>j. A p j / A p m);\n         A' = (\\<lambda>i. if i=p then Ap' else (\\<lambda>j. A i j - A i m * Ap' j))\n     in gauss_jordan (Fun.swap p m A') m))\"\n\ntext\\<open>Some auxiliary functions:\\<close>\n\ndefinition solution :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"solution A n x = (\\<forall>i<n. (\\<Sum> j=0..<n. A i j * x j) = A i n)\"\n\ndefinition unit :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"unit A m n =\n (\\<forall>i j::nat. m\\<le>j \\<longrightarrow> j<n \\<longrightarrow> A i j = (if i=j then 1 else 0))\"\n\nlemma solution_swap:\nassumes \"p1 < n\" \"p2 < n\"\nshows \"solution (Fun.swap p1 p2 A) n x = solution A n x\" (is \"?L = ?R\")\nproof(cases \"p1=p2\")\n  case True thus ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?R thus ?L using assms False by(simp add: solution_def Fun.swap_def)\n  next\n   assume ?L\n   show ?R\n   proof(auto simp: solution_def)\n     fix i assume \"i<n\"\n     show \"(\\<Sum>j = 0..<n. A i j * x j) = A i n\"\n     proof cases\n       assume \"i=p1\"\n       with \\<open>?L\\<close> assms False show ?thesis\n         by(fastforce simp add: solution_def Fun.swap_def)\n     next\n       assume \"i\\<noteq>p1\"\n       show ?thesis\n       proof cases\n         assume \"i=p2\"\n         with \\<open>?L\\<close> assms False show ?thesis\n           by(fastforce simp add: solution_def Fun.swap_def)\n       next\n         assume \"i\\<noteq>p2\"\n         with \\<open>i\\<noteq>p1\\<close> \\<open>?L\\<close> \\<open>i<n\\<close> assms False show ?thesis\n           by(fastforce simp add: solution_def Fun.swap_def)\n       qed\n     qed\n   qed\n qed\nqed\n\n(* Converting these apply scripts makes them blow up - see above *)\n\nlemma solution_upd1:\n  \"c \\<noteq> 0 \\<Longrightarrow> solution (A(p:=(\\<lambda>j. A p j / c))) n x = solution A n x\"\napply(cases \"p<n\")\n prefer 2\n apply(simp add: solution_def)\napply(clarsimp simp add: solution_def)\napply rule\n apply clarsimp\n apply(case_tac \"i=p\")\n  apply (simp add: sum_divide_distrib[symmetric] eq_divide_eq field_simps)\n apply simp\napply (simp add: sum_divide_distrib[symmetric] eq_divide_eq field_simps)\ndone\n\nlemma solution_upd_but1: \"\\<lbrakk> ap = A p; \\<forall>i j. i\\<noteq>p \\<longrightarrow> a i j = A i j; p<n \\<rbrakk> \\<Longrightarrow>\n solution (\\<lambda>i. if i=p then ap else (\\<lambda>j. a i j - c i * ap j)) n x =\n solution A n x\"\napply(clarsimp simp add: solution_def)\napply rule\n prefer 2\n apply (simp add: field_simps sum_subtractf sum_distrib_left[symmetric])\napply(clarsimp)\napply(case_tac \"i=p\")\n apply simp\napply (auto simp add: field_simps sum_subtractf sum_distrib_left[symmetric] all_conj_distrib)\ndone\n\nsubsection\\<open>Correctness\\<close>\n\ntext\\<open>The correctness proof:\\<close>\n\nlemma gauss_jordan_lemma: \"m\\<le>n \\<Longrightarrow> unit A m n \\<Longrightarrow> gauss_jordan A m = Some B \\<Longrightarrow>\n  unit B 0 n \\<and> solution A n (\\<lambda>j. B j n)\"\nproof(induct m arbitrary: A B)\n  case 0\n  { fix a and b c d :: \"'a\"\n    have \"(if a then b else c) * d = (if a then b*d else c*d)\" by simp\n  } with 0 show ?case by(simp add: unit_def solution_def sum.If_cases)\nnext\n  case (Suc m)\n  let \"?Ap' p\" = \"(\\<lambda>j. A p j / A p m)\"\n  let \"?A' p\" = \"(\\<lambda>i. if i=p then ?Ap' p else (\\<lambda>j. A i j - A i m * ?Ap' p j))\"\n  from \\<open>gauss_jordan A (Suc m) = Some B\\<close>\n  obtain p ks where \"dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] = p#ks\" and\n    rec: \"gauss_jordan (Fun.swap p m (?A' p)) m = Some B\"\n    by (auto split: list.splits)\n  from this have p: \"p\\<le>m\" \"A p m \\<noteq> 0\"\n    apply(simp_all add: dropWhile_eq_Cons_conv del:upt_Suc)\n    by (metis set_upt atLeast0AtMost atLeastLessThanSuc_atLeastAtMost atMost_iff in_set_conv_decomp)\n  have \"m\\<le>n\" \"m<n\" using \\<open>Suc m \\<le> n\\<close> by arith+\n  have \"unit (Fun.swap p m (?A' p)) m n\" using Suc.prems(2) p\n    unfolding unit_def Fun.swap_def Suc_le_eq by (auto simp: le_less)\n  from Suc.hyps[OF \\<open>m\\<le>n\\<close> this rec] \\<open>m<n\\<close> p\n  show ?case\n    by (simp only: solution_swap) (simp_all add: solution_swap solution_upd_but1 [where A = \"A(p := ?Ap' p)\"] solution_upd1)\nqed\n\ntheorem gauss_jordan_correct:\n  \"gauss_jordan A n = Some B \\<Longrightarrow> solution A n (\\<lambda>j. B j n)\"\nby(simp add:gauss_jordan_lemma[of n n] unit_def  field_simps)\n\ndefinition solution2 :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\nwhere \"solution2 A m n x = (\\<forall>i<m. (\\<Sum> j=0..<m. A i j * x j) = A i n)\"\n\ndefinition \"usolution A m n x \\<longleftrightarrow>\n  solution2 A m n x \\<and> (\\<forall>y. solution2 A m n y \\<longrightarrow> (\\<forall>j<m. y j = x j))\"\n\nlemma non_null_if_pivot:\n  assumes \"usolution A m n x\" and \"q < m\" shows \"\\<exists>p<m. A p q \\<noteq> 0\"\nproof(rule ccontr)\n  assume \"\\<not>(\\<exists>p<m. A p q \\<noteq> 0)\"\n  hence 1: \"\\<And>p. p<m \\<Longrightarrow> A p q = 0\" by simp\n  { fix y assume 2: \"\\<forall>j. j\\<noteq>q \\<longrightarrow> y j = x j\"\n    { fix i assume \"i<m\"\n      with assms(1) have \"A i n = (\\<Sum>j = 0..<m. A i j * x j)\"\n        by (auto simp: solution2_def usolution_def)\n      with 1[OF \\<open>i<m\\<close>] 2\n      have \"(\\<Sum>j = 0..<m. A i j * y j) = A i n\"\n        by (auto intro!: sum.cong)\n    }\n    hence \"solution2 A m n y\" by(simp add: solution2_def)\n  }\n  hence \"solution2 A m n (x(q:=0))\" and \"solution2 A m n (x(q:=1))\" by auto\n  with assms(1) zero_neq_one \\<open>q < m\\<close>\n  show False\n    by (simp add: usolution_def)\n       (metis fun_upd_same zero_neq_one)\nqed\n\nlemma lem1:\n  fixes f :: \"'a \\<Rightarrow> 'b::field\"\n  shows \"(\\<Sum>x\\<in>A. f x * (a * g x)) = a * (\\<Sum>x\\<in>A. f x * g x)\"\n  by (simp add: sum_distrib_left field_simps)\n\n\n\nsubsection\\<open>Complete\\<close>\n\nlemma gauss_jordan_complete:\n  \"m \\<le> n \\<Longrightarrow> usolution A m n x \\<Longrightarrow> \\<exists>B. gauss_jordan A m = Some B\"\nproof(induction m arbitrary: A)\n  case 0 show ?case by simp\nnext\n  case (Suc m A)\n  from \\<open>Suc m \\<le> n\\<close> have \"m\\<le>n\" and \"m<Suc m\" by arith+\n  from non_null_if_pivot[OF Suc.prems(2) \\<open>m<Suc m\\<close>]\n  obtain p' where \"p'<Suc m\" and \"A p' m \\<noteq> 0\" by blast\n  hence \"dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] \\<noteq> []\"\n    by (simp add: atLeast0LessThan) (metis lessThan_iff linorder_neqE_nat not_less_eq)\n  then obtain p xs where 1: \"dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] = p#xs\"\n    by (metis list.exhaust)\n  from this have \"p\\<le>m\" \"A p m \\<noteq> 0\"\n    by (simp_all add: dropWhile_eq_Cons_conv del: upt_Suc)\n       (metis set_upt atLeast0AtMost atLeastLessThanSuc_atLeastAtMost atMost_iff in_set_conv_decomp)\n  then have p: \"p < Suc m\" \"A p m \\<noteq> 0\"\n    by auto\n  let ?Ap' = \"(\\<lambda>j. A p j / A p m)\"\n  let ?A' = \"(\\<lambda>i. if i=p then ?Ap' else (\\<lambda>j. A i j - A i m * ?Ap' j))\"\n  let ?A = \"Fun.swap p m ?A'\"\n  have A: \"solution2 A (Suc m) n x\" using Suc.prems(2) by(simp add: usolution_def)\n  { fix i assume le_m: \"p < Suc m\" \"i < Suc m\" \"A p m \\<noteq> 0\"\n    have \"(\\<Sum>j = 0..<m. (A i j - A i m * A p j / A p m) * x j) =\n      ((\\<Sum>j = 0..<Suc m. A i j * x j) - A i m * x m) -\n      ((\\<Sum>j = 0..<Suc m. A p j * x j) - A p m * x m) * A i m / A p m\"\n      by (simp add: field_simps sum_subtractf sum_divide_distrib\n                    sum_distrib_left)\n    also have \"\\<dots> = A i n - A p n * A i m / A p m\"\n      using A le_m\n      by (simp add: solution2_def field_simps del: sum.op_ivl_Suc)\n    finally have \"(\\<Sum>j = 0..<m. (A i j - A i m * A p j / A p m) * x j) =\n      A i n - A p n * A i m / A p m\" . }\n  then have \"solution2 ?A m n x\" using p\n    by (auto simp add: solution2_def Fun.swap_def field_simps)\n  moreover\n  { fix y assume a: \"solution2 ?A m n y\"\n    let ?y = \"y(m := A p n / A p m - (\\<Sum>j = 0..<m. A p j * y j) / A p m)\"\n    have \"solution2 A (Suc m) n ?y\" unfolding solution2_def\n    proof safe\n      fix i assume \"i < Suc m\"\n      show \"(\\<Sum>j=0..<Suc m. A i j * ?y j) = A i n\"\n      proof (cases \"i = p\")\n        assume \"i = p\" with p show ?thesis by (simp add: field_simps)\n      next\n        assume \"i \\<noteq> p\"\n        show ?thesis\n        proof (cases \"i = m\")\n          assume \"i = m\"\n          with p \\<open>i \\<noteq> p\\<close> have \"p < m\" by simp\n          with a[unfolded solution2_def, THEN spec, of p] p(2)\n          have \"A p m * (A m m * A p n + A p m * (\\<Sum>j = 0..<m. y j * A m j)) = A p m * (A m n * A p m + A m m * (\\<Sum>j = 0..<m. y j * A p j))\"\n            by (simp add: Fun.swap_def field_simps sum_subtractf lem1 lem2 sum_divide_distrib[symmetric]\n                     split: if_splits)\n          with \\<open>A p m \\<noteq> 0\\<close> show ?thesis unfolding \\<open>i = m\\<close>\n            by simp (simp add: field_simps)\n        next\n          assume \"i \\<noteq> m\"\n          then have \"i < m\" using \\<open>i < Suc m\\<close> by simp\n          with a[unfolded solution2_def, THEN spec, of i] p(2)\n          have \"A p m * (A i m * A p n + A p m * (\\<Sum>j = 0..<m. y j * A i j)) = A p m * (A i n * A p m + A i m * (\\<Sum>j = 0..<m. y j * A p j))\"\n            by (simp add: Fun.swap_def split: if_splits)\n              (simp add: field_simps sum_subtractf lem1 lem2 sum_divide_distrib [symmetric])\n          with \\<open>A p m \\<noteq> 0\\<close> show ?thesis\n            by simp (simp add: field_simps)\n        qed\n      qed\n    qed\n    with \\<open>usolution A (Suc m) n x\\<close>\n    have \"\\<forall>j<Suc m. ?y j = x j\" by (simp add: usolution_def)\n    hence \"\\<forall>j<m. y j = x j\"\n      by simp (metis less_SucI nat_neq_iff)\n  } ultimately have \"usolution ?A m n x\" \n    by (simp add: usolution_def)\n  note * = Suc.IH [OF \\<open>m \\<le> n\\<close> this]\n  from 1 show ?case\n    by auto (use * in blast)\nqed\n\ntext\\<open>Future work: extend the proof to matrix inversion.\\<close>\n\nhide_const (open) unit\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Gauss-Jordan-Elim-Fun/Gauss_Jordan_Elim_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8577680977182187, "lm_q1q2_score": 0.7610157966395877}}
{"text": "theory LeftistHeap\n  imports Main \"HOL-Library.Multiset\"\nbegin\n\ndatatype 'a LHeap = Null | Node \"'a LHeap\" 'a nat  \"'a LHeap\"\n\n(* Racunamo rastojanje do null-a koristeci sledece svojstvo leftist hipa:\n    dist(right(i)) <= dist(left(i))\n*)\nfun dist :: \"'a LHeap \\<Rightarrow> nat\" where\n  \"dist Null = 0\"\n| \"dist (Node _ _ _ r) = dist r + 1\"\n\n\n(* Citamo rastojanje prosledjenog cvora *)\nfun readDist :: \"'a LHeap \\<Rightarrow> nat\" where\n  \"readDist Null = 0\"\n| \"readDist (Node _ _ n _) = n\"\n\n\n(* Ukoliko uslov dist(right(i)) <= dist(left(i) nije ispunjen rotiramo levo i desno\n    podstablo i racunamo razdaljinu za koreni cvor\n*)\ndefinition node :: \"'a LHeap \\<Rightarrow> 'a \\<Rightarrow> 'a LHeap \\<Rightarrow> 'a LHeap\" where\n  \"node l v r =\n    (let dl = readDist l; dr = readDist r \n     in if dl \\<ge> dr then Node l v (dr+1) r else Node r v (dl+1) l)\"\n\nfun merge :: \"'a::ord LHeap \\<Rightarrow> 'a LHeap \\<Rightarrow> 'a LHeap\" where\n  \"merge Null t2 = t2\"\n| \"merge t1 Null = t1\"\n| \"merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2) = \n    (if v1 \\<le> v2 then node l1 v1 (merge r1 (Node l2 v2 n2 r2))\n     else node l2 v2 (merge (Node l1 v1 n1 r1) r2))\"\n\nvalue \"merge Null (Node Null 4 1 Null)::nat LHeap\"\n\ndefinition insert :: \"'a::ord \\<Rightarrow> 'a LHeap \\<Rightarrow> 'a LHeap\" where\n  \"insert v t = merge (Node Null v 1 Null) t\"\n\n(* testiranje insert-a *)\ndefinition test_tree_1 :: \"nat LHeap\" where\n  \"test_tree_1 = (insert 7 (insert 6 (insert 8 (insert 14 Null))))\"\n\ndefinition test_tree_2 :: \"nat LHeap\" where\n    \"test_tree_2 = insert 8 (insert 25 (insert 12 (insert 15 (insert 4 (insert 20 (insert 19 (insert 27 (insert 43 Null))))))))\"\n\n(* testiranje merge-a*)\nvalue \"merge test_tree_1 test_tree_2\"\n\n(* brisemo najmanji element (koren) stabla *)\nfun delMin :: \"'a::ord LHeap \\<Rightarrow> 'a LHeap\" where\n\"delMin Null = Null\" |\n\"delMin (Node l v n r) = merge l r\"\n\nvalue \"delMin test_tree_1\"\n\n(* Uzimamo najmanji element iz stabla *)\nfun getMin :: \"'a LHeap \\<Rightarrow> 'a\" where\n  \"getMin (Node l v n r) = v\"\n\nvalue \"getMin test_tree_1\"\n\ndatatype ('a, 'b) Tree = TNull | TNode \"('a, 'b) Tree\" 'a 'b \"('a, 'b) Tree\"\n\n(* Pravimo multiset elemenata iz drveta *)\nfun treeToMSet :: \"'a LHeap \\<Rightarrow> 'a multiset\" where\n  \"treeToMSet Null = {#}\" \n| \"treeToMSet (Node l v _ r) = treeToMSet l + {#v#} + treeToMSet r\"\n\n(* Proverava \"Normal Min Heap Property\" svojstvo:\n    key(i) >= key(parent(i))\n*)\nfun isHeap :: \"'a::ord LHeap \\<Rightarrow> bool\" where\n  \"isHeap Null = True\"\n| \"isHeap (Node l v _ r) = ((\\<forall>x \\<in> set_mset(treeToMSet l + treeToMSet r).v \\<le> x) \n                            \\<and> isHeap l \\<and> isHeap r)\"\n\ndefinition heap :: \"nat LHeap\" where\n  \"heap = (Node (Node (Node Null 4 20 Null) 2 5 (Node Null 5 25 Null)) 1 11 (Node Null 3 7 Null))\"\ndefinition not_heap :: \"nat LHeap\" where\n  \"not_heap = (Node (Node (Node Null 14 20 Null) 21 5 (Node Null 5 25 Null)) 19 11 (Node Null 6 7 Null))\"\n\nvalue \"isHeap heap\"\nvalue \"isHeap not_heap\"\n\n\n(* Proverava \"Heavier on left side\" svojstvo:\n     dist(right(i)) <= dist(left(i))\n*)\nfun isLHeap :: \"'a LHeap \\<Rightarrow> bool\" where\n  \"isLHeap Null = True\"\n| \"isLHeap (Node l v n r) = (n = dist r + 1 \\<and> dist l \\<ge> dist r \n                             \\<and> (isLHeap l \\<and> isLHeap r))\"\n\n(* Prosledjeno leftist drvo*) \nvalue \"isLHeap test_tree_1\"\n\n\n(* Prosledjeno drvo koje nije leftist *)\ndefinition not_ltree :: \"nat LHeap\" where\n  \"not_ltree = (Node (Node Null 6 1 Null) 4 3 (Node (Node Null 6 1 Null) 8 2 (Node Null 10 1 Null)))\"\nvalue \"isLHeap not_ltree\"\n\n(* Prazan multiset nekog drveta znaci da je drvo null *)\nlemma emptyMSetEQNullTree[simp]: \"treeToMSet tree = {#} \\<longleftrightarrow> tree = Null\"\n  by (induction tree) auto\n\nlemma getDistEQDist[simp]: \"isLHeap tree \\<Longrightarrow> readDist tree = dist tree\"\n  by (induction tree) auto\n\n(* Ako primenimo node funkciju na dva leftist stabla, dobijeno stablo\n    ostaje leftist\n *)\nlemma isLHeapNode[simp]: \"isLHeap l \\<and> isLHeap r \\<longleftrightarrow> isLHeap (node l v r)\"\n  using node_def\n  by (smt getDistEQDist isLHeap.simps(2) linear)\n\n(* Izvrsavanjem node funkcije drvo ne gubi \"Normal Min Heap Property\" svojstvo:\n    key(i) >= key(parent(i))\n*)\nlemma heapNode[simp]: \"isHeap (node l v r) \\<longleftrightarrow>\n  isHeap l \\<and> isHeap r \\<and> (\\<forall>x \\<in> set_mset(treeToMSet l + treeToMSet r). v \\<le> x)\"\n  using node_def\n  by (smt add.commute isHeap.simps(2))\n\n\n(* Multiskup dva spojena drveta je jednak uniji multiskupova pojedinacnih dveta *)\nlemma mergeMSet[simp]: \"treeToMSet (merge tree1 tree2) = treeToMSet tree1 + treeToMSet tree2\"\nproof (induction tree1 tree2 rule: merge.induct)\ncase (1 t2)\nthen show ?case\n  by simp\nnext\n  case (2 v va vb vc)\n  then show ?case\n    by simp\nnext\n  case (3 l1 v1 n1 r1 l2 v2 n2 r2)\n  then show ?case\n  proof cases\n    assume \"v1 \\<le> v2\"\n    hence \"treeToMSet (merge r1 (Node l2 v2 n2 r2)) = treeToMSet r1 + treeToMSet (Node l2 v2 n2 r2)\"\n      by (simp add: \"3.IH\"(1))\n    thus \"treeToMSet (merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2)) = treeToMSet (Node l1 v1 n1 r1) + treeToMSet (Node l2 v2 n2 r2)\"\n      using  LHeap.simps(1)  LHeap.simps(3)  merge.simps(3) node_def treeToMSet.simps(2)\n    by (smt \\<open>v1 \\<le> v2\\<close> add.commute add.left_commute )\n  next\n    assume \"\\<not> v1 \\<le> v2\"\n    hence \"treeToMSet (merge (Node l1 v1 n1 r1) r2) = treeToMSet (Node l1 v1 n1 r1) + treeToMSet r2\"\n      by (simp add: \"3.IH\"(2))\n    thus \"treeToMSet (merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2)) = treeToMSet (Node l1 v1 n1 r1) + treeToMSet (Node l2 v2 n2 r2)\"\n      using  merge.simps(3) node_def treeToMSet.simps(2)\n  by (smt \\<open>\\<not> v1 \\<le> v2\\<close> add.assoc add.commute)\n  qed\nqed\n\n(* Multiskup drveta nakon ubacivanja elemenata je jednak multiskupu kojem smo dodali novi element*)\nlemma insertMSet[simp]: \"treeToMSet (insert v tree) = treeToMSet tree + {#v#}\"\n  using insert_def\n  by (metis add.commute add_mset_add_single mergeMSet treeToMSet.simps(1) treeToMSet.simps(2))\n\n\n(* Ukoliko je drvo hip i nije Null tada je njegov najmanji element jednak najmanjem \n  elementu multiskupa tog drveta*)\nlemma minHeapEQminMSet[simp]:\n  assumes \"isHeap tree\" and \"tree \\<noteq> Null\"\n  shows \"getMin tree = Min_mset (treeToMSet tree)\"\n  by (smt Min_insert2 add_mset_add_single assms(1) assms(2) finite_set_mset\n      getMin.simps isHeap.simps(2) set_mset_add_mset_insert treeToMSet.elims\n      union_mset_add_mset_left)\n\n(* Multiskup drveta sa izbrisanim najmanjim elementom jednak je razlici  multiskupu\n celog drveta i najmanjeg elementa. *)\nlemma delMinMSet[simp]: \"treeToMSet (delMin tree) = treeToMSet tree - {#getMin tree#}\"\n  by (smt add_mset_add_single add_mset_not_empty add_mset_remove_trivial\n      add_mset_remove_trivial_If delMin.simps(1) delMin.simps(2) diff_single_trivial\n      getMin.simps mergeMSet treeToMSet.elims union_mset_add_mset_left)\n\n\n(* Ako pretpostavimo da je levo podstablo leftist i desno podstablo leftist kad ih \n  spojimo novo stablo je takodje leftist. *)\nlemma LHeapMerge[simp]: \n  assumes \"isLHeap l\" and \"isLHeap r\"\n  shows \"isLHeap (merge l r)\"\n  using assms\nproof (induction l r rule: merge.induct)\ncase (1 t2)\n  then show ?case\n    by simp\nnext\n  case (2 v va vb vc)\n  then show ?case\n    by simp\nnext\n  case (3 l1 v1 n1 r1 l2 v2 n2 r2)\n  then show ?case\n    by (metis isLHeap.simps(2) isLHeapNode merge.simps(3))\nqed\n\nlemma heapMerge: \n  assumes \"isHeap l\" and \"isHeap r\"\n  shows \"isHeap (merge l r)\"\n  using assms\n  proof (induction l r rule: merge.induct)\ncase (1 t2)\nthen show ?case\n  by simp\nnext\n  case (2 v va vb vc)\n  then show ?case by simp\nnext\n  case (3 l1 v1 n1 r1 l2 v2 n2 r2)\n  then show ?case\n  proof(cases)\n    assume \"v1 \\<le> v2\"\n    hence \"isHeap r1\" \n      using \"3.prems\"(1) by auto\n    hence \"isHeap (Node l2 v2 n2 r2)\"\n  using \"3.prems\"(2) by auto\n  hence *:\"isHeap (merge r1 (Node l2 v2 n2 r2))\"\n    by (simp add: \"3.IH\"(1) \\<open>isHeap r1\\<close> \\<open>v1 \\<le> v2\\<close>)\n  have **: \"isHeap (Node l1 v1 n1 r1)\" \n    using \"3.prems\"(1) by blast\n  have \"isHeap (Node l2 v2 n2 r2)\"\n    using \"3.prems\"(2) by auto\n  thus \"isHeap (merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2))\"\n    using * ** \n    sorry\n\nnext\n  assume \"\\<not> v1 \\<le> v2\"\n  hence \"isHeap (Node l1 v1 n1 r1)\"\n    using \"3.prems\"(1) by blast\n  hence \"isHeap r2\"\n    using \"3.prems\"(2) isHeap.simps(2) by blast\n  hence \"isHeap (merge (Node l1 v1 n1 r1) r2)\"\n    using \"3.IH\"(2) \"3.prems\"(1) \\<open>\\<not> v1 \\<le> v2\\<close> by blast\n  thus \"isHeap (merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2))\"\n    sorry\n  qed\nqed\n\n(* U narednim lemama se proverava da li drvo posle ubacivanja elementa ili\n    brisanja najmanjeg elementa zadrzava sledeca svojstva:\n    -\"Normal Min Heap Property\": value(i) >= value(parent(i))\n    -\"Heavier on left side\": dist(right(i)) <= dist(left(i))\n*)\nlemma insertIsLHeap: \"isLHeap tree \\<Longrightarrow> isLHeap (insert v tree)\"\n  by (simp add: LeftistHeap.insert_def)\n\nlemma isertIsHeap: \"isHeap tree \\<Longrightarrow> isHeap (insert v tree)\"\n  by (simp add: LeftistHeap.insert_def heapMerge)\n\nlemma delMinIsLHeap: \"isLHeap tree \\<Longrightarrow> isLHeap (delMin tree)\"\n  by (metis LHeapMerge delMin.simps(1) delMin.simps(2) isLHeap.elims(2))\n\nlemma delMinIsHeap: \"isHeap tree \\<Longrightarrow> isHeap (delMin tree)\"\n  by (metis (full_types) delMin.elims heapMerge isHeap.simps(2))\n\n(*\nImplementiramo red sa prioritetom zasnovan na leftist drvetu sa sledecim operacijama:\n  push: Ubacujemo element sa njegovim prioritetom.\n  top: Ocitavamo element sa najmanjim prioritetom.\n  pop: Brisemo element sa najmanjim prioritetom.\n  empty: Proveravamo da li je red prazan.\n *)\n\ntype_synonym PriorityQueue = \"nat LHeap\"\n\nfun push :: \"nat \\<Rightarrow> PriorityQueue \\<Rightarrow> PriorityQueue\" where\n  \"push pr PQ  = insert pr PQ\"\n\nfun top :: \"PriorityQueue \\<Rightarrow> nat\" where\n  \"top PQ = getMin PQ\"\n\nfun pop :: \"PriorityQueue \\<Rightarrow> PriorityQueue\" where\n  \"pop PQ = delMin PQ\"\n\nfun empty :: \"PriorityQueue \\<Rightarrow> bool\" where\n  \"empty PQ \\<longleftrightarrow> PQ = Null\"\n\ndefinition bank :: \"PriorityQueue\" where\n  \"bank = push 5 (push 150 (push 112 Null))\"\n\nvalue \"top bank\"\nvalue \"top (pop bank)\"\nvalue \"empty bank\"\n\n\n(* Hipsort zasnovan na leftist drvetu *)\n\nfun listToLHeap :: \"'a::ord list \\<Rightarrow> 'a LHeap\" where\n  \"listToLHeap [] = Null\"\n| \"listToLHeap (x # xs) = insert x (listToLHeap xs)\"\n\nvalue \"listToLHeap [2::nat,7,1,9,6]\"\n\nfun size :: \"'a::ord LHeap \\<Rightarrow> nat\" where\n  \"size Null = 0\"\n| \"size (Node Null _ _ Null) = 1\"\n| \"size (Node l _ _ Null) = 1 + size l\" \n| \"size (Node Null _ _ r) = 1 + size r\"\n| \"size (Node l _ _ r) = 1 + size l + size r\"\n\n\n\nlemma sizeMerge[simp]: \"size t1 + size t2 = size (merge t1 t2)\"\nproof (induction t1 t2 rule: merge.induct)\n  case (1 t2)\nthen show ?case by simp\nnext\n  case (2 v va vb vc)\n  then show ?case by simp\nnext\n  case (3 l1 v1 n1 r1 l2 v2 n2 r2)\n  then show ?case\n  proof (cases)\n    assume \"v1 \\<le> v2\"\n    hence \"LeftistHeap.size r1 + LeftistHeap.size (Node l2 v2 n2 r2) = LeftistHeap.size (merge r1 (Node l2 v2 n2 r2))\"\n      by (simp add: \"3.IH\"(1))\n    thus \"LeftistHeap.size (Node l1 v1 n1 r1) + LeftistHeap.size (Node l2 v2 n2 r2) = LeftistHeap.size (merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2))\"\n      using node_def\n      sorry\nnext\n  assume \"\\<not>v1 \\<le> v2\"\n  hence \" LeftistHeap.size (Node l1 v1 n1 r1) + LeftistHeap.size r2 = LeftistHeap.size (merge (Node l1 v1 n1 r1) r2)\"\n    by (simp add: \"3.IH\"(2))\n  thus \"LeftistHeap.size (Node l1 v1 n1 r1) + LeftistHeap.size (Node l2 v2 n2 r2) = LeftistHeap.size (merge (Node l1 v1 n1 r1) (Node l2 v2 n2 r2))\"\n    sorry\nqed\nqed\n\nfunction heapsort' :: \"nat LHeap \\<Rightarrow> nat list\" where\n  \"heapsort' Null = []\"\n| \"heapsort' (Node Null v _ Null) = [v]\"\n| \"heapsort' (Node l v _ r) = v # heapsort' (merge l r)\" \n  apply pat_completeness \napply   auto\n\nend", "meta": {"author": "DavidNedeljkovic", "repo": "MATF-Implementation-Leftist-Tree", "sha": "81b77a277a945348d8ad1ecdaf3686663625f99a", "save_path": "github-repos/isabelle/DavidNedeljkovic-MATF-Implementation-Leftist-Tree", "path": "github-repos/isabelle/DavidNedeljkovic-MATF-Implementation-Leftist-Tree/MATF-Implementation-Leftist-Tree-81b77a277a945348d8ad1ecdaf3686663625f99a/LeftistHeap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7610106420415568}}
{"text": "theory Tutorial2_2\nimports Main\nbegin\n\n  section \\<open>Arithmetic Expressions with Exceptions\\<close>\n    \n  text \\<open>Model arithmetic expressions that have constants, variables, plus, and div.\\<close>  \n    \n  type_synonym vname = string\n  type_synonym val = int\n  type_synonym state = \"vname \\<Rightarrow> val\"\n  \n  datatype aexp = N int | V vname | Plus aexp aexp | Div aexp aexp\n\n  text \\<open>Model the evaluation to return \\<open>None\\<close> if a division by zero occurs, and \\<open>Some v\\<close> otherwise.\n    Use case distinctions to distinguish between None and Some results.\n  \\<close>  \n\n  fun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val option\" where\n    \"aval (N i) s = Some i\"\n  | \"aval (V x) s = Some (s x)\"\n  | \"aval (Plus a1 a2) s = (case aval a1 s of\n      None \\<Rightarrow> None\n    | Some v1 \\<Rightarrow> (case aval a2 s of\n        None \\<Rightarrow> None\n      | Some v2 \\<Rightarrow> Some (v1+v2)\n      )\n    )\"  \n  | \"aval (Div a1 a2) s = (case aval a1 s of\n      None \\<Rightarrow> None\n    | Some v1 \\<Rightarrow> (case aval a2 s of\n        None \\<Rightarrow> None\n      | Some v2 \\<Rightarrow> (if v2=0 then None else Some (v1 div v2))\n      )\n    )\"  \n    \ntext {* A little syntax magic to write larger states compactly: *}\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\n  \nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n\ntext \\<open>Add constant folding to divisions. Consider division of two constants and division by one.\n  Be careful not to accidentally \"define\" division by zero to be \\<open>x div 0\\<close>.\n\\<close>\n\nfun division :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"division (N i1) (N i2) = (if i2\\<noteq>0 then N (i1 div i2) else Div (N i1) (N i2))\"\n| \"division a (N i) = (if i=1 then a else Div a (N i))\"\n| \"division a b = Div a b\"  \n \n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval (Plus a1 a2) s\"\napply(induction a1 a2 rule: plus.induct)\napply (auto split: option.splits)\ndone\n\nlemma aval_div[simp]:\n  \"aval (division a1 a2) s = aval (Div a1 a2) s\"\n  apply (induction a1 a2 rule: division.induct)\n  apply (auto split: option.splits)  \n  done  \n  \n  \nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\" |\n\"asimp (Div a\\<^sub>1 a\\<^sub>2) = division (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n(* Add an equation for division *)\n\n(* Show correctness of constant folding. *)\ntheorem aval_asimp[simp]: \"aval (asimp a) s = aval a s\" \n  apply (induction a)\n  apply (auto split: option.splits)  \n  done  \n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Tutorials/Tutorial2_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8705972566572504, "lm_q1q2_score": 0.7609692373295712}}
{"text": "(*  Title:      HOL/Analysis/Operator_Norm.thy\n    Author:     Amine Chaieb, University of Cambridge\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Operator Norm\\<close>\n\ntheory Operator_Norm\nimports Complex_Main\nbegin\n\ntext \\<open>This formulation yields zero if \\<open>'a\\<close> is the trivial vector space.\\<close>\n\ndefinition onorm :: \"('a::real_normed_vector \\<Rightarrow> 'b::real_normed_vector) \\<Rightarrow> real\"\n  where \"onorm f = (SUP x. norm (f x) / norm x)\"\n\nlemma onorm_bound:\n  assumes \"0 \\<le> b\" and \"\\<And>x. norm (f x) \\<le> b * norm x\"\n  shows \"onorm f \\<le> b\"\n  unfolding onorm_def\nproof (rule cSUP_least)\n  fix x\n  show \"norm (f x) / norm x \\<le> b\"\n    using assms by (cases \"x = 0\") (simp_all add: pos_divide_le_eq)\nqed simp\n\ntext \\<open>In non-trivial vector spaces, the first assumption is redundant.\\<close>\n\nlemma onorm_le:\n  fixes f :: \"'a::{real_normed_vector, perfect_space} \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"\\<And>x. norm (f x) \\<le> b * norm x\"\n  shows \"onorm f \\<le> b\"\nproof (rule onorm_bound [OF _ assms])\n  have \"{0::'a} \\<noteq> UNIV\" by (metis not_open_singleton open_UNIV)\n  then obtain a :: 'a where \"a \\<noteq> 0\" by fast\n  have \"0 \\<le> b * norm a\"\n    by (rule order_trans [OF norm_ge_zero assms])\n  with \\<open>a \\<noteq> 0\\<close> show \"0 \\<le> b\"\n    by (simp add: zero_le_mult_iff)\nqed\n\nlemma le_onorm:\n  assumes \"bounded_linear f\"\n  shows \"norm (f x) / norm x \\<le> onorm f\"\nproof -\n  interpret f: bounded_linear f by fact\n  obtain b where \"0 \\<le> b\" and \"\\<forall>x. norm (f x) \\<le> norm x * b\"\n    using f.nonneg_bounded by auto\n  then have \"\\<forall>x. norm (f x) / norm x \\<le> b\"\n    by (clarify, case_tac \"x = 0\",\n      simp_all add: f.zero pos_divide_le_eq mult.commute)\n  then have \"bdd_above (range (\\<lambda>x. norm (f x) / norm x))\"\n    unfolding bdd_above_def by fast\n  with UNIV_I show ?thesis\n    unfolding onorm_def by (rule cSUP_upper)\nqed\n\nlemma onorm:\n  assumes \"bounded_linear f\"\n  shows \"norm (f x) \\<le> onorm f * norm x\"\nproof -\n  interpret f: bounded_linear f by fact\n  show ?thesis\n  proof (cases)\n    assume \"x = 0\"\n    then show ?thesis by (simp add: f.zero)\n  next\n    assume \"x \\<noteq> 0\"\n    have \"norm (f x) / norm x \\<le> onorm f\"\n      by (rule le_onorm [OF assms])\n    then show \"norm (f x) \\<le> onorm f * norm x\"\n      by (simp add: pos_divide_le_eq \\<open>x \\<noteq> 0\\<close>)\n  qed\nqed\n\nlemma onorm_pos_le:\n  assumes f: \"bounded_linear f\"\n  shows \"0 \\<le> onorm f\"\n  using le_onorm [OF f, where x=0] by simp\n\nlemma onorm_zero: \"onorm (\\<lambda>x. 0) = 0\"\nproof (rule order_antisym)\n  show \"onorm (\\<lambda>x. 0) \\<le> 0\"\n    by (simp add: onorm_bound)\n  show \"0 \\<le> onorm (\\<lambda>x. 0)\"\n    using bounded_linear_zero by (rule onorm_pos_le)\nqed\n\nlemma onorm_eq_0:\n  assumes f: \"bounded_linear f\"\n  shows \"onorm f = 0 \\<longleftrightarrow> (\\<forall>x. f x = 0)\"\n  using onorm [OF f] by (auto simp: fun_eq_iff [symmetric] onorm_zero)\n\nlemma onorm_pos_lt:\n  assumes f: \"bounded_linear f\"\n  shows \"0 < onorm f \\<longleftrightarrow> \\<not> (\\<forall>x. f x = 0)\"\n  by (simp add: less_le onorm_pos_le [OF f] onorm_eq_0 [OF f])\n\nlemma onorm_id_le: \"onorm (\\<lambda>x. x) \\<le> 1\"\n  by (rule onorm_bound) simp_all\n\nlemma onorm_id: \"onorm (\\<lambda>x. x::'a::{real_normed_vector, perfect_space}) = 1\"\nproof (rule antisym[OF onorm_id_le])\n  have \"{0::'a} \\<noteq> UNIV\" by (metis not_open_singleton open_UNIV)\n  then obtain x :: 'a where \"x \\<noteq> 0\" by fast\n  hence \"1 \\<le> norm x / norm x\"\n    by simp\n  also have \"\\<dots> \\<le> onorm (\\<lambda>x::'a. x)\"\n    by (rule le_onorm) (rule bounded_linear_ident)\n  finally show \"1 \\<le> onorm (\\<lambda>x::'a. x)\" .\nqed\n\nlemma onorm_compose:\n  assumes f: \"bounded_linear f\"\n  assumes g: \"bounded_linear g\"\n  shows \"onorm (f \\<circ> g) \\<le> onorm f * onorm g\"\nproof (rule onorm_bound)\n  show \"0 \\<le> onorm f * onorm g\"\n    by (intro mult_nonneg_nonneg onorm_pos_le f g)\nnext\n  fix x\n  have \"norm (f (g x)) \\<le> onorm f * norm (g x)\"\n    by (rule onorm [OF f])\n  also have \"onorm f * norm (g x) \\<le> onorm f * (onorm g * norm x)\"\n    by (rule mult_left_mono [OF onorm [OF g] onorm_pos_le [OF f]])\n  finally show \"norm ((f \\<circ> g) x) \\<le> onorm f * onorm g * norm x\"\n    by (simp add: mult.assoc)\nqed\n\nlemma onorm_scaleR_lemma:\n  assumes f: \"bounded_linear f\"\n  shows \"onorm (\\<lambda>x. r *\\<^sub>R f x) \\<le> \\<bar>r\\<bar> * onorm f\"\nproof (rule onorm_bound)\n  show \"0 \\<le> \\<bar>r\\<bar> * onorm f\"\n    by (intro mult_nonneg_nonneg onorm_pos_le abs_ge_zero f)\nnext\n  fix x\n  have \"\\<bar>r\\<bar> * norm (f x) \\<le> \\<bar>r\\<bar> * (onorm f * norm x)\"\n    by (intro mult_left_mono onorm abs_ge_zero f)\n  then show \"norm (r *\\<^sub>R f x) \\<le> \\<bar>r\\<bar> * onorm f * norm x\"\n    by (simp only: norm_scaleR mult.assoc)\nqed\n\nlemma onorm_scaleR:\n  assumes f: \"bounded_linear f\"\n  shows \"onorm (\\<lambda>x. r *\\<^sub>R f x) = \\<bar>r\\<bar> * onorm f\"\nproof (cases \"r = 0\")\n  assume \"r \\<noteq> 0\"\n  show ?thesis\n  proof (rule order_antisym)\n    show \"onorm (\\<lambda>x. r *\\<^sub>R f x) \\<le> \\<bar>r\\<bar> * onorm f\"\n      using f by (rule onorm_scaleR_lemma)\n  next\n    have \"bounded_linear (\\<lambda>x. r *\\<^sub>R f x)\"\n      using bounded_linear_scaleR_right f by (rule bounded_linear_compose)\n    then have \"onorm (\\<lambda>x. inverse r *\\<^sub>R r *\\<^sub>R f x) \\<le> \\<bar>inverse r\\<bar> * onorm (\\<lambda>x. r *\\<^sub>R f x)\"\n      by (rule onorm_scaleR_lemma)\n    with \\<open>r \\<noteq> 0\\<close> show \"\\<bar>r\\<bar> * onorm f \\<le> onorm (\\<lambda>x. r *\\<^sub>R f x)\"\n      by (simp add: inverse_eq_divide pos_le_divide_eq mult.commute)\n  qed\nqed (simp add: onorm_zero)\n\nlemma onorm_scaleR_left_lemma:\n  assumes r: \"bounded_linear r\"\n  shows \"onorm (\\<lambda>x. r x *\\<^sub>R f) \\<le> onorm r * norm f\"\nproof (rule onorm_bound)\n  fix x\n  have \"norm (r x *\\<^sub>R f) = norm (r x) * norm f\"\n    by simp\n  also have \"\\<dots> \\<le> onorm r * norm x * norm f\"\n    by (intro mult_right_mono onorm r norm_ge_zero)\n  finally show \"norm (r x *\\<^sub>R f) \\<le> onorm r * norm f * norm x\"\n    by (simp add: ac_simps)\nqed (intro mult_nonneg_nonneg norm_ge_zero onorm_pos_le r)\n\nlemma onorm_scaleR_left:\n  assumes f: \"bounded_linear r\"\n  shows \"onorm (\\<lambda>x. r x *\\<^sub>R f) = onorm r * norm f\"\nproof (cases \"f = 0\")\n  assume \"f \\<noteq> 0\"\n  show ?thesis\n  proof (rule order_antisym)\n    show \"onorm (\\<lambda>x. r x *\\<^sub>R f) \\<le> onorm r * norm f\"\n      using f by (rule onorm_scaleR_left_lemma)\n  next\n    have bl1: \"bounded_linear (\\<lambda>x. r x *\\<^sub>R f)\"\n      by (metis bounded_linear_scaleR_const f)\n    have \"bounded_linear (\\<lambda>x. r x * norm f)\"\n      by (metis bounded_linear_mult_const f)\n    from onorm_scaleR_left_lemma[OF this, of \"inverse (norm f)\"]\n    have \"onorm r \\<le> onorm (\\<lambda>x. r x * norm f) * inverse (norm f)\"\n      using \\<open>f \\<noteq> 0\\<close>\n      by (simp add: inverse_eq_divide)\n    also have \"onorm (\\<lambda>x. r x * norm f) \\<le> onorm (\\<lambda>x. r x *\\<^sub>R f)\"\n      by (rule onorm_bound)\n        (auto simp: abs_mult bl1 onorm_pos_le intro!: order_trans[OF _ onorm])\n    finally show \"onorm r * norm f \\<le> onorm (\\<lambda>x. r x *\\<^sub>R f)\"\n      using \\<open>f \\<noteq> 0\\<close>\n      by (simp add: inverse_eq_divide pos_le_divide_eq mult.commute)\n  qed\nqed (simp add: onorm_zero)\n\nlemma onorm_neg:\n  shows \"onorm (\\<lambda>x. - f x) = onorm f\"\n  unfolding onorm_def by simp\n\nlemma onorm_triangle:\n  assumes f: \"bounded_linear f\"\n  assumes g: \"bounded_linear g\"\n  shows \"onorm (\\<lambda>x. f x + g x) \\<le> onorm f + onorm g\"\nproof (rule onorm_bound)\n  show \"0 \\<le> onorm f + onorm g\"\n    by (intro add_nonneg_nonneg onorm_pos_le f g)\nnext\n  fix x\n  have \"norm (f x + g x) \\<le> norm (f x) + norm (g x)\"\n    by (rule norm_triangle_ineq)\n  also have \"norm (f x) + norm (g x) \\<le> onorm f * norm x + onorm g * norm x\"\n    by (intro add_mono onorm f g)\n  finally show \"norm (f x + g x) \\<le> (onorm f + onorm g) * norm x\"\n    by (simp only: distrib_right)\nqed\n\nlemma onorm_triangle_le:\n  assumes \"bounded_linear f\"\n  assumes \"bounded_linear g\"\n  assumes \"onorm f + onorm g \\<le> e\"\n  shows \"onorm (\\<lambda>x. f x + g x) \\<le> e\"\n  using assms by (rule onorm_triangle [THEN order_trans])\n\nlemma onorm_triangle_lt:\n  assumes \"bounded_linear f\"\n  assumes \"bounded_linear g\"\n  assumes \"onorm f + onorm g < e\"\n  shows \"onorm (\\<lambda>x. f x + g x) < e\"\n  using assms by (rule onorm_triangle [THEN order_le_less_trans])\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Analysis/Operator_Norm.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899665, "lm_q2_score": 0.8688267677469952, "lm_q1q2_score": 0.7609071840051037}}
{"text": "theory Homework3_template\n  imports \"HOL-IMP.Hoare_Examples\"\nbegin\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  for r where\n  refl:  \"star r x x\"\n| step:  \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\n(* Problem 1 *)\n\n\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n  pal0: \"palindrome []\" | \n  palaxsa: \"palindrome xs \\<Longrightarrow>  palindrome (s # xs @ [s]) \"  (* complete definition *)\n\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply (induction rule: palindrome.induct )\n  by auto  (* replace with proof *)\n\n\n(* Problem 2 *)\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl': \"star' r x x\"\n| step': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\n\n\nlemma star_one: \"r a b \\<Longrightarrow> star r a b\"\n  (* After applying rule step, ?y appears because Isabelle does\n     not know what to instantiate for y in theorem step. *)\n  apply (rule step)\n  (* apply assumption means looking for an assumption that matches\n     the goal. Isabelle will see that r a ?y matches r a b with ?y = b. *)\n   apply assumption\n  (* The remaining goal is just refl rule. *)\n  apply (rule refl)\n  done\n\n\n\nlemma star_step2_detailed: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  (* Induction on proof trees begin with induction rule followed\n     by the name of the induction theorem. Isabelle will figure out\n     what need to be proved for induction. Here we show detailed\n     application of introduction rules. *)\n  apply (induction rule: star.induct)\n   apply (rule step)\n    apply assumption\n   apply (rule refl)\n  subgoal for x y z'\n    apply (rule step[where y=y])\n     apply assumption\n    by auto\n  done\n\n\n\nlemma  \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule:star'.induct) \n  apply (rule refl)\n  apply (rule star_step2_detailed)\n   apply assumption\n  apply assumption\n  \n\n\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n  by (auto simp: refl')\n  \n   (* replace with proof *)\n\n\n(* Problem 3 *)\n\nlemma\n  \"\\<turnstile> {\\<lambda>s. s ''x'' = x \\<and> s ''y'' = y \\<and> 0 \\<le> x}\n     WHILE Less (N 0) (V ''x'') DO (\n       ''x'' ::= Plus (V ''x'') (N (-1));;\n       ''y'' ::= Plus (V ''y'') (N (-1))\n     )\n     {\\<lambda>t. t ''y'' = y - x}\"\napply (rule strengthen_pre)\n  prefer 2\n  apply (rule While'[where P=\"\\<lambda>s. s ''y'' = y - x + s ''x'' \\<and>   0 \\<le> s ''x''\"])\n prefer 2\n   apply simp\n  apply (rule Seq)\n  prefer 2\n  apply (rule Assign)\n  apply simp\n   apply (rule Assign')\n  apply simp\n  by auto   (* replace with proof *)\n\n\n(* Problem 4 *)\n\n(* Hint: use algebra_simps and power2_eq_square *)\nthm algebra_simps\nthm power2_eq_square\n\nlemma\n  \"\\<turnstile> { \\<lambda>s. s ''x'' = i \\<and> 0 \\<le> i}                  \\<comment> \\<open>x = i \\<and> 0 \\<le> i\\<close>\n     ''r'' ::= N 0;; ''r2'' ::= N 1;;             \\<comment> \\<open>r := 0; r2 := 1;\\<close>\n     WHILE (Not (Less (V ''x'') (V ''r2'')))      \\<comment> \\<open>while (!x < r2)) {\\<close>\n     DO (''r'' ::= Plus (V ''r'') (N 1);;         \\<comment> \\<open>   r := r + 1\\<close>\n         ''r2'' ::= Plus (V ''r2'')               \\<comment> \\<open>   r2 := r2 + (r + r + 1)\\<close>\n            (Plus (Plus (V ''r'') (V ''r'')) (N 1)))\n     {\\<lambda>s. (s ''r'')^2 \\<le> i \\<and> i < (s ''r'' + 1)^2}\"  \\<comment> \\<open>r ^ 2 \\<le> i \\<and> i < (r+1) ^ 2\\<close>\n   (* replace with proof *)\n  apply (rule strengthen_pre)\n  prefer 2\n  apply (rule Seq)\n  prefer 2\n    apply (rule While'[where P=\"\\<lambda>s. s ''x'' = i \\<and> (s ''r'')^2 \\<le> i \\<and> s ''r2'' = (s ''r''+1)^2\"])\n     apply (rule Seq)\n      apply simp\n      prefer 2\n      apply (rule Assign)\n  apply simp\n     apply (rule Assign')\n     apply simp\n  apply auto\n   by (auto simp add: algebra_simps  power2_eq_square)\n", "meta": {"author": "hong-code", "repo": "ucas_Pro_theory", "sha": "94c5e854987ba4bea5ce906ef166afe48b136eef", "save_path": "github-repos/isabelle/hong-code-ucas_Pro_theory", "path": "github-repos/isabelle/hong-code-ucas_Pro_theory/ucas_Pro_theory-94c5e854987ba4bea5ce906ef166afe48b136eef/Homework3_template.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.8774767762675405, "lm_q1q2_score": 0.7608037494494737}}
{"text": "section\\<open>Basics needed\\<close>\n\ntheory PerfectBasics\nimports Main \"HOL-Computational_Algebra.Primes\" \"HOL-Algebra.Exponent\"\nbegin\n\nlemma sum_mono2_nat: \"finite (B::nat set) \\<Longrightarrow> A <= B \\<Longrightarrow> \\<Sum> A <= \\<Sum> B\"\n  by (auto simp add: sum_mono2)\n\n(* TODO Move *)\nlemma multiplicity_0 [simp]: \"multiplicity 0 x = 0\" \n  by (cases \"x = 0\") (auto intro: not_dvd_imp_multiplicity_0)\n  \n\nlemma exp_is_max_div:\n   assumes m0:\"m \\<noteq> 0\" and p: \"prime p\"\n   shows \"~ p dvd (m div (p^(multiplicity p m)))\"\nproof (rule ccontr)\n  assume \"~ ~ p dvd (m div (p^(multiplicity p m)))\"\n  hence a:\"p dvd (m div (p^(multiplicity p m)))\" by auto\n  from m0 have \"p^(multiplicity p m) dvd m\" by (auto simp add: multiplicity_dvd)\n  with a have \"p^Suc (multiplicity p m) dvd m\"\n    by (subst (asm) dvd_div_iff_mult) auto\n  with m0 p show False\n    by (subst (asm) power_dvd_iff_le_multiplicity) auto\nqed\n\nlemma coprime_multiplicity:\n  assumes \"prime (p::nat)\" and \"m > 0\"\n  shows \"coprime p (m div (p ^ multiplicity p m))\"\nproof (rule ccontr)\n  assume \"\\<not> coprime p (m div p ^ multiplicity p m)\"\n  with \\<open>prime p\\<close> have \"\\<exists>q. prime q \\<and> q dvd p \\<and> q dvd m div p ^ multiplicity p m\"\n    by (metis dvd_refl prime_imp_coprime)\n  with \\<open>prime p\\<close> have \"\\<exists>q. q = p \\<and> q dvd m div p ^ multiplicity p m\"\n    by (metis not_prime_1 prime_nat_iff)\n  then have \"p dvd m div p ^ multiplicity p m\"\n    by auto\n  with assms show False\n    by (auto simp add: exp_is_max_div)\nqed\n\nlemma add_mult_distrib_three: \"(x::nat)*(a+b+c)=x*a+x*b+x*c\" \nproof -\n  have \"(x::nat)*(a+b+c) = x*((a+b)+c)\" by auto\n  hence \"x*(a+b+c) = x*(a+b)+x*c\" by (simp add: algebra_simps)\n  thus \"x*(a+b+c) = x*a+x*b+x*c\" by (simp add: algebra_simps) \nqed\n\nlemma nat_interval_minus_zero: \"{0..Suc n} = {0} Un {Suc 0..Suc n}\" by auto\nlemma nat_interval_minus_zero2:\n assumes \"n>0\"\n shows \"{0..n} = {0} Un {Suc 0..n}\" by (auto simp add: nat_interval_minus_zero)\n\ntheorem simplify_sum_of_powers: \"(x - 1::nat) * (\\<Sum>i=0 .. n . x^i)  = x^(n + 1) - 1\" (is \"?l = ?r\")\nproof (cases)\n  assume \"n = 0\"\n  thus \"?l = x^(n+1) - 1\" by auto\n  next\n  assume \"n~=0\"\n  hence n0: \"n>0\" by auto \n  have \"?l  = (x::nat)*(\\<Sum>i=0 .. n . x^i) - (\\<Sum>i=0 .. n . x^i)\"\n    by (metis diff_mult_distrib nat_mult_1)\n  also have \"... = (\\<Sum>i=0 .. n . x^(Suc i))    - (\\<Sum>i=0 .. n . x^i)\"\n    by (simp add: sum_distrib_left)\n  also have \"... = (\\<Sum>i=Suc 0 .. Suc n . x^i)  - (\\<Sum>i=0 .. n . x^i)\"\n    by (metis sum.shift_bounds_cl_Suc_ivl)\n  also with n0\n  have \"... = ((\\<Sum>i=Suc 0 .. n. x^i)+x^(Suc n)) - (x^0 + (\\<Sum>i=Suc 0 .. n. x^i))\"\n    by (auto simp add: sum.union_disjoint nat_interval_minus_zero2)\n  finally show \"?thesis\" by auto\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Perfect-Number-Thm/PerfectBasics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600902, "lm_q2_score": 0.8397339716830606, "lm_q1q2_score": 0.7607904344380444}}
{"text": "(*\n  File: Interval.thy\n  Author: Bohua Zhan\n*)\n\nsection \\<open>Intervals\\<close>\n\ntheory Interval\n  imports \"Auto2_HOL.Auto2_Main\"\nbegin\n\ntext \\<open>Basic definition of intervals.\\<close>\n\nsubsection \\<open>Definition of interval\\<close>\n\ndatatype 'a interval = Interval (low: 'a) (high: 'a)\nsetup \\<open>add_simple_datatype \"interval\"\\<close>\n\ninstantiation interval :: (linorder) linorder begin\n\ndefinition int_less: \"(a < b) = (low a < low b | (low a = low b \\<and> high a < high b))\"\ndefinition int_less_eq: \"(a \\<le> b) = (low a < low b | (low a = low b \\<and> high a \\<le> high b))\"\n\ninstance proof\n  fix x y z :: \"'a interval\"\n  show a: \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    using int_less int_less_eq by force\n  show b: \"x \\<le> x\"\n    by (simp add: int_less_eq)\n  show c: \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (smt int_less_eq dual_order.trans less_trans)\n  show d: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    using int_less_eq a interval.expand int_less by fastforce\n  show e: \"x \\<le> y \\<or> y \\<le> x\"\n    by (meson int_less_eq leI not_less_iff_gr_or_eq)\nqed end\n\ndefinition is_interval :: \"('a::linorder) interval \\<Rightarrow> bool\" where [rewrite]:\n  \"is_interval it \\<longleftrightarrow> (low it \\<le> high it)\"\n\nsubsection \\<open>Definition of interval with an index\\<close>\n\ndatatype 'a idx_interval = IdxInterval (int: \"'a interval\") (idx: nat)\nsetup \\<open>add_simple_datatype \"idx_interval\"\\<close>\n\ninstantiation idx_interval :: (linorder) linorder begin\n\ndefinition iint_less: \"(a < b) = (int a < int b | (int a = int b \\<and> idx a < idx b))\"\ndefinition iint_less_eq: \"(a \\<le> b) = (int a < int b | (int a = int b \\<and> idx a \\<le> idx b))\"\n\ninstance proof\n  fix x y z :: \"'a idx_interval\"\n  show a: \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    using iint_less iint_less_eq by force\n  show b: \"x \\<le> x\"\n    by (simp add: iint_less_eq)\n  show c: \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    by (smt iint_less_eq dual_order.trans less_trans)\n  show d: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    using a idx_interval.expand iint_less iint_less_eq by auto\n  show e: \"x \\<le> y \\<or> y \\<le> x\"\n    by (meson iint_less_eq leI not_less_iff_gr_or_eq)\nqed end\n\nlemma interval_less_to_le_low [forward]:\n  \"(a::('a::linorder idx_interval)) < b \\<Longrightarrow> low (int a) \\<le> low (int b)\"\n  by (metis eq_iff iint_less int_less less_imp_le)\n\nsubsection \\<open>Overlapping intervals\\<close>\n\ndefinition is_overlap :: \"('a::linorder) interval \\<Rightarrow> 'a interval \\<Rightarrow> bool\" where [rewrite]:\n  \"is_overlap x y \\<longleftrightarrow> (high x \\<ge> low y \\<and> high y \\<ge> low x)\"\n\ndefinition has_overlap :: \"('a::linorder) idx_interval set \\<Rightarrow> 'a interval \\<Rightarrow> bool\" where [rewrite]:\n  \"has_overlap xs y \\<longleftrightarrow> (\\<exists>x\\<in>xs. is_overlap (int x) y)\"\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Auto2_Imperative_HOL/Functional/Interval.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7607904293020407}}
{"text": "\ntheory Alexander\n  imports \n    Simplicial_complex\nbegin\n\nsection\\<open>Definition of the Alexander dual of a simplicial complex\\<close>\n\ncontext simplicial_complex\nbegin\n\nabbreviation \"univ_n == {..<n}\"\n\ndefinition simplex_complement\n  where \"simplex_complement s == univ_n - s\"\n\nsubsubsection \\<open>Set complement\\<close>\n\nlemma\n  simplex_complement_simplex:\n  assumes v: \"v \\<in> simplices\"\n  shows \"simplex_complement v \\<in> simplices\"\n  using v\n  by (simp add: atLeast0LessThan simplex_complement_def simplices_def)\n\nlemma\n  simplex_Compl_in:\n  assumes s: \"s \\<in> simplices\" and c: \"c \\<in> s\"\n  shows \"c \\<notin> simplex_complement s\"\n  using s c\n  unfolding simplices_def \n  unfolding simplex_complement_def by simp\n\nlemma\n  simplex_Compl_notin:\n  assumes s: \"s \\<in> simplices\" and c: \"c \\<in> simplex_complement s\"\n  shows \"c \\<notin> s\"\n  using s c \n  unfolding simplices_def \n  unfolding simplex_complement_def by simp\n\nlemma\n  simplex_Compl_iff [simp]:\n  assumes s: \"s \\<in> simplices\" and c: \"c < n\"\n  shows \"c \\<in> simplex_complement s \\<longleftrightarrow> c \\<notin> s\"\n  unfolding simplex_complement_def\n  using s c unfolding simplices_def by simp\n\nlemma\n  simplex_complement_idempotent:\n  assumes \"x \\<in> simplices\"\n  shows \"x = simplex_complement (simplex_complement x)\"\n  using assms atLeast0LessThan simplex_complement_def simplices_def by auto\n\nlemma\n  simplice_complement:\n  assumes \"x \\<in> simplices\"\n  obtains vx where \"x = simplex_complement vx\"\nproof -\n  have \"simplex_complement (simplex_complement x) = x\"\n    using assms atLeast0LessThan simplex_complement_def simplices_def by auto\n  then show ?thesis\n    using that by blast \nqed\n\ntext\\<open>We define the complement or the ``no faces'' of a simplicial complex\n  as the simplices in @{term \"{..n::nat}\"} that are not in the simplicial \n  complex. Note that the set obtained is not a simplicial complex (except \n  for particular cases such as the empty set or the total set).\\<close>\n\ndefinition nofaces_simplicial_complex\n  where \"nofaces_simplicial_complex s = {v. v \\<in> simplices \\<and> v \\<notin> s}\"\n\nlemma simpl_compl_not_in [simp]:\n  assumes \"v \\<in> nofaces_simplicial_complex s\" \n  shows \"v \\<notin> s\"\n  using assms nofaces_simplicial_complex_def by fastforce\n\nlemma simpl_compl_simplice [simp]:\n  assumes \"v \\<in> nofaces_simplicial_complex s\" \n  shows \"v \\<in> simplices\"\n  by (metis (no_types, lifting) assms mem_Collect_eq nofaces_simplicial_complex_def)\n\ndefinition Alexander_dual\n  where \"Alexander_dual s = \n            {v. \\<exists>x. v = simplex_complement x \\<and> x \\<in> nofaces_simplicial_complex s}\"\n\nlemma Alexander_dual_empty: \"Alexander_dual {} = Pow {..<n}\"\n  unfolding Alexander_dual_def\n  unfolding nofaces_simplicial_complex_def\n  unfolding simplex_complement_def\n  unfolding simplices_def\n  by auto\n\nsubsection\\<open>The Alexander dual of a simplicial complex is a simplicial complex\\<close>\n\nlemma\n  simplicial_complex_Alexander_dual:\n  assumes \"simplicial_complex s\"\n  shows \"simplicial_complex (Alexander_dual s)\"\nproof (unfold simplicial_complex_def, standard, intro conjI)\n  fix \\<sigma> :: \"nat set\"\n  assume sigma: \"\\<sigma> \\<in> Alexander_dual s\"\n  show sigma_simplice: \"\\<sigma> \\<in> simplices\"\n    using sigma unfolding Alexander_dual_def using simplex_complement_simplex [OF ]\n    by fastforce\n  show \"Pow \\<sigma> \\<subseteq> Alexander_dual s\"\n  proof\n    fix x :: \"nat set\"\n    assume x: \"x \\<in> Pow \\<sigma>\"\n    show \"x \\<in> Alexander_dual s\"\n    proof (rule ccontr)\n      assume xnin: \"x \\<notin> Alexander_dual s\"\n      from x have x_in_sigma: \"x \\<subseteq> \\<sigma>\" and x_simplice: \"x \\<in> simplices\" \n        using sigma_simplice\n        apply simp\n        using sigma_simplice simplices_def x by force\n      from sigma obtain v\n        where sigma_complement: \"\\<sigma> = simplex_complement v\" \n          and v_noface: \"v \\<in> nofaces_simplicial_complex s\"\n        unfolding Alexander_dual_def by auto\n      from x_simplice\n      obtain vx where x_complement: \"x = simplex_complement vx\" and vx_simplice: \"vx \\<in> simplices\"\n        using simplice_complement [OF x_simplice]\n        using simplex_complement_simplex [OF x_simplice]\n        by (metis PowD Pow_top atLeast0LessThan double_diff simplex_complement_def simplices_def)\n      show False\n      proof (cases \"vx \\<in> nofaces_simplicial_complex s\")\n        case True\n        hence \"x \\<in> Alexander_dual s\" using x_complement unfolding Alexander_dual_def by auto\n        thus ?thesis using xnin by contradiction\n      next\n        case False\n        hence vx_in_s: \"vx \\<in> s\"\n          by (metis (mono_tags, lifting) mem_Collect_eq nofaces_simplicial_complex_def vx_simplice) \n        have \"v \\<subseteq> vx\"\n          using sigma_complement x_complement x_in_sigma\n          by (smt (verit, ccfv_threshold) Diff_iff PowD atLeast0LessThan simplices_def simplicial_complex.simpl_compl_simplice simplicial_complex.simplex_complement_def subset_eq v_noface)\n        hence \"v \\<in> s\" using assms vx_in_s unfolding simplicial_complex_def by auto\n        thus ?thesis using v_noface by simp\n      qed\n    qed\n  qed\nqed\n\nend\n\nsection\\<open>Definition of the Alexander dual of a Boolean function\\<close>\n\ncontext boolean_functions\nbegin\n\ntext\\<open>The notion of @{const simplicial_complex.nofaces_simplicial_complex} \n  in simplicial complexes becomes now in boolean functions just the \n  @{const HOL.Not} boolean operator.\\<close>\n\n(*definition nofaces_boolean_function\n  where \"nofaces_boolean_function f = {b. b \\<in> carrier_vec n \\<and> \\<not> f b}\"\n\nlemma nofaces_not [simp]:\n  assumes \"b \\<in> nofaces_boolean_function f\"\n  shows \"\\<not> f b\"\n  using assms nofaces_boolean_function_def by fastforce\n\nlemma nofaces_carrier_vec [simp]:\n  assumes \"b \\<in> nofaces_boolean_function f\"\n  shows \"b \\<in> carrier_vec n\"\n  using assms nofaces_boolean_function_def by auto\n\nlemma \"nofaces_boolean_function f \\<union> {b. b \\<in> carrier_vec n \\<and> f b} \n  = carrier_vec n\"\n  unfolding nofaces_boolean_function_def by auto*)\n\ntext\\<open>The notion of @{const simplicial_complex.simplex_complement}\n  becomes now in boolean functions the negation, or the complement in base \n  @{term \"2::nat\"}, of each @{typ \"bool vec\"}.\\<close>\n\ndefinition not :: \"bool vec \\<Rightarrow> bool vec\"  (*\"\\<not> _\" [20] 20*)\n  where \"not v = vec (dim_vec v) (\\<lambda>n. \\<not> v $ n)\"\n\nlemma\n  dim_vec_not:\n  assumes d: \"dim_vec v = k\"\n  shows \"dim_vec (not v) = k\"\n  using d unfolding not_def by simp\n\nlemma\n  assumes d: \"k < dim_vec v\"\n  shows \"v $ k \\<longleftrightarrow> \\<not> (not v $ k)\"\n  using d unfolding not_def by simp\n\nlemma\n  not_v_in_carrier:\n  assumes \"v \\<in> carrier_vec k\"\n  shows \"not v \\<in> carrier_vec k\"\n  using assms not_def by fastforce\n\nlemma\n  assumes d: \"k < dim_vec v\"\n  shows \"\\<not> v $ k \\<longleftrightarrow> (not v $ k)\"\n  using d unfolding not_def by simp\n\ntext\\<open>The operation @{const not} is ``antimonotone'', in the sense that\n  for every @{term x}, @{term y} such that @{term \"x \\<le> y\"}, \n  then @{term \"not y \\<le> not x\"}.\\<close>\n\nlemma\n  not_vec_antimono: \n  assumes rs: \"r \\<le> s\"\n  shows \"not s \\<le> not r\"\n  using rs \n  unfolding not_def\n  unfolding less_eq_vec_def by auto\n\ntext\\<open>The operation @{const HOL.Not} is ``antimonotone'', in the sense that\n  for every @{term x}, @{term y} such that @{term \"x \\<le> y\"},\n  and @{term f} such that @{term \"monotone_bool_fun f\"},\n  then @{term \"HOL.Not (f y) \\<le> HOL.Not (f x)\"}.\\<close>\n\nlemma\n  not_antimono:\n  assumes m: \"monotone_bool_fun f\"\n  and x: \"x \\<in> carrier_vec n\" and y: \"y \\<in> carrier_vec n\"\n  and xy: \"x \\<le> y\"\n  shows \"(\\<not> f y) \\<le> (\\<not> f x)\"\n  by (metis (mono_tags, opaque_lifting) le_boolE le_boolI' m mono_on_def monotone_bool_fun_def x xy y)\n\ntext\\<open>The definition of the Alexander dual now for a Boolean function @{term f}\n  becomes just the negation of @{term f} over the ``complement'' of every vector.\\<close>\n\ndefinition \"Alexander_dual f = (\\<lambda>x. \\<not> f (not x))\"\n\nlemma Alexander_dual_False: \n  \"boolean_functions.Alexander_dual (\\<lambda>x. False) =\n   (\\<lambda>x. True)\"\n  unfolding Alexander_dual_def \n  by simp\n\nsubsection\\<open>The Alexander dual of a \\emph{monotone} Boolean function \n  is a \\emph{monotone} Boolean function\\<close>\n\nlemma\n  monotone_boolean_function_Alexander_dual:\n  assumes f: \"monotone_bool_fun f\"\n  shows \"monotone_bool_fun (Alexander_dual f)\"\nproof (unfold monotone_bool_fun_def, unfold mono_on_def, intro allI, safe)\n  fix r s :: \"bool vec\"\n  assume r: \"r \\<in> carrier_vec n\" and s: \"s \\<in> carrier_vec n\" and r_le_s: \"r \\<le> s\"\n  have nr: \"not r \\<in> carrier_vec n\" and ns: \"not s \\<in> carrier_vec n\" and ns_le_nr: \"not s \\<le> not r\"\n    using not_v_in_carrier [OF r]\n        and not_v_in_carrier [OF s] \n        and not_vec_antimono [OF r_le_s] by simp_all\n  show \"Alexander_dual f r \\<le> Alexander_dual f s\"\n    unfolding Alexander_dual_def using not_antimono [OF f ns nr ns_le_nr] by simp\nqed\n\nend\n\nlemmas [code] = boolean_functions.not_def boolean_functions.Alexander_dual_def\n\nend", "meta": {"author": "jmaransay", "repo": "morse", "sha": "99d05d63fad13f5b4827f2f656ebbad989e90e09", "save_path": "github-repos/isabelle/jmaransay-morse", "path": "github-repos/isabelle/jmaransay-morse/morse-99d05d63fad13f5b4827f2f656ebbad989e90e09/Alexander.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9252299632771661, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7607140150085512}}
{"text": "theory Ex1_6\n  imports Main \nbegin \n\n  \nprimrec sum :: \"nat list \\<Rightarrow> nat\" where \n  \"sum [] = 0\"|\n  \"sum (x#xs) = x + sum xs\"\n  \n\nprimrec flatten :: \"'a list list \\<Rightarrow> 'a list\" where \n  \"flatten [] = []\"|\n  \"flatten (x#xs) = x @ flatten xs\"\n  \nlemma \"sum [2::nat ,4,8] = 14\" by simp\n\nlemma \"flatten [[2::nat, 3], [4,5], [7,9]] = [2,3,4,5,7,9]\" by simp\n    \nlemma \"length (flatten xs) = sum (map length xs)\" by (induct xs; simp)\n    \nlemma sum_append : \"sum (xs @ ys) = sum xs + sum ys\" by (induct xs; simp)\n    \nlemma flatten_append : \"flatten (xs @ ys) = flatten xs @ flatten ys\" by (induct xs; simp)\n    \nlemma \"flatten (map rev (rev xs)) = rev (flatten xs)\" by (induct xs; simp add : flatten_append)\n\nlemma \"flatten (rev (map rev xs)) = rev (flatten xs)\" by (induct xs; simp add : flatten_append)    \n    \nlemma \"list_all (list_all P) xs = list_all P (flatten xs)\" by (induct xs; simp)\n    \n(*lemma \"flatten (rev xs) = flatten xs\" quickcheck *)\n    \nlemma \"flatten (rev [[1::nat,2],[3::nat,4]]) = flatten [[1::nat,2],[3::nat,4]] \\<Longrightarrow> False\" by simp\n    \nlemma \"sum (rev xs) = sum xs\" by (induct xs; simp add : sum_append)\n    \nlemma \"list_all (op \\<le> 1) xs \\<longrightarrow> length xs \\<le> sum xs\" by (induct xs; auto)\n    \nprimrec list_exists :: \"('a \\<Rightarrow> bool) \\<Rightarrow> ('a list \\<Rightarrow> bool)\" where\n  \"list_exists _ [] = False\"|\n  \"list_exists P (x#xs) = (P x \\<or> list_exists P xs)\"\n  \nlemma \"list_exists (\\<lambda>n .  n < 3 ) [4::nat , 3, 7] = False\" by simp\n \nlemma \"list_exists (\\<lambda>n .  n < 4 ) [4::nat , 3, 7] = True\" by simp\n    \nlemma list_exists_append : \"list_exists P (xs @ ys) = (list_exists P xs \\<or> list_exists P ys)\" by (induct xs; simp)\n    \nlemma \"list_exists (list_exists P) xs = list_exists P (flatten xs)\" by (induct xs; simp add : list_exists_append)\n    \ndefinition \"list_exists2 P ls = (\\<not> (list_all (\\<lambda>x . \\<not>(P x))) ls)\"\n\nlemma \"list_exists P xs = list_exists2 P xs\" by (induct xs; simp add : list_exists2_def)", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/1. Lists/Ex1_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.8652240877899776, "lm_q1q2_score": 0.7606589544725986}}
{"text": "\\<^marker>\\<open>creator \"Kevin Kappelmann\"\\<close>\nsubsubsection \\<open>Basic Functions\\<close>\ntheory Binary_Relation_Functions\n  imports\n    HOL.HOL\nbegin\n\nparagraph \\<open>Summary\\<close>\ntext \\<open>Basic functions on binary relations.\\<close>\n\ndefinition \"rel_comp R S x y \\<equiv> \\<exists>z. R x z \\<and> S z y\"\n\nbundle rel_comp_syntax begin notation rel_comp (infixl \"\\<circ>\\<circ>\" 55) end\nbundle no_rel_comp_syntax begin no_notation rel_comp (infixl \"\\<circ>\\<circ>\" 55) end\nunbundle rel_comp_syntax\n\nlemma rel_compI [intro]:\n  assumes \"R x y\"\n  and \"S y z\"\n  shows \"(R \\<circ>\\<circ> S) x z\"\n  using assms unfolding rel_comp_def by blast\n\nlemma rel_compE [elim]:\n  assumes \"(R \\<circ>\\<circ> S) x y\"\n  obtains z where \"R x z\" \"S z y\"\n  using assms unfolding rel_comp_def by blast\n\nlemma rel_comp_assoc: \"R \\<circ>\\<circ> (S \\<circ>\\<circ> T) = (R \\<circ>\\<circ> S) \\<circ>\\<circ> T\"\n  by (intro ext) blast\n\ndefinition rel_inv :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'b \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where \"rel_inv R x y \\<equiv> R y x\"\n\nbundle rel_inv_syntax begin notation rel_inv (\"(_\\<inverse>)\" [1000]) end\nbundle no_rel_inv_syntax begin no_notation rel_inv (\"(_\\<inverse>)\" [1000]) end\nunbundle rel_inv_syntax\n\nlemma rel_invI [intro]:\n  assumes \"R x y\"\n  shows \"R\\<inverse> y x\"\n  using assms unfolding rel_inv_def .\n\nlemma rel_invD [dest]:\n  assumes \"R\\<inverse> x y\"\n  shows \"R y x\"\n  using assms unfolding rel_inv_def .\n\nlemma rel_inv_iff_rel [simp]: \"R\\<inverse> x y \\<longleftrightarrow> R y x\"\n  by blast\n\nlemma rel_inv_comp_eq [simp]: \"(R \\<circ>\\<circ> S)\\<inverse> = S\\<inverse> \\<circ>\\<circ> R\\<inverse>\"\n  by (intro ext) blast\n\nlemma rel_inv_inv_eq_self [simp]: \"R\\<inverse>\\<inverse> = R\"\n  by blast\n\nlemma rel_inv_eq_iff_eq [iff]: \"R\\<inverse> = S\\<inverse> \\<longleftrightarrow> R = S\"\n  by (blast dest: fun_cong)\n\ndefinition \"in_dom R x \\<equiv> \\<exists>y. R x y\"\n\nlemma in_domI [intro]:\n  assumes \"R x y\"\n  shows \"in_dom R x\"\n  using assms unfolding in_dom_def by blast\n\nlemma in_domE [elim]:\n  assumes \"in_dom R x\"\n  obtains y where \"R x y\"\n  using assms unfolding in_dom_def by blast\n\nlemma in_dom_if_in_dom_rel_comp:\n  assumes \"in_dom (R \\<circ>\\<circ> S) x\"\n  shows \"in_dom R x\"\n  using assms by blast\n\ndefinition \"in_codom R y \\<equiv> \\<exists>x. R x y\"\n\nlemma in_codomI [intro]:\n  assumes \"R x y\"\n  shows \"in_codom R y\"\n  using assms unfolding in_codom_def by blast\n\nlemma in_codomE [elim]:\n  assumes \"in_codom R y\"\n  obtains x where \"R x y\"\n  using assms unfolding in_codom_def by blast\n\nlemma in_codom_if_in_codom_rel_comp:\n  assumes \"in_codom (R \\<circ>\\<circ> S) y\"\n  shows \"in_codom S y\"\n  using assms by blast\n\nlemma in_codom_rel_inv_eq_in_dom [simp]: \"in_codom (R\\<inverse>) = in_dom R\"\n  by (intro ext) blast\n\nlemma in_dom_rel_inv_eq_in_codom [simp]: \"in_dom (R\\<inverse>) = in_codom R\"\n  by (intro ext) blast\n\ndefinition \"in_field R x \\<equiv> in_dom R x \\<or> in_codom R x\"\n\nlemma in_field_if_in_dom:\n  assumes \"in_dom R x\"\n  shows \"in_field R x\"\n  unfolding in_field_def using assms by blast\n\nlemma in_field_if_in_codom:\n  assumes \"in_codom R x\"\n  shows \"in_field R x\"\n  unfolding in_field_def using assms by blast\n\nlemma in_fieldE [elim]:\n  assumes \"in_field R x\"\n  obtains (in_dom) x' where \"R x x'\" | (in_codom) x' where \"R x' x\"\n  using assms unfolding in_field_def by blast\n\nlemma in_fieldE':\n  assumes \"in_field R x\"\n  obtains (in_dom) \"in_dom R x\" | (in_codom) \"in_codom R x\"\n  using assms by blast\n\nlemma in_fieldI [intro]:\n  assumes \"R x y\"\n  shows \"in_field R x\" \"in_field R y\"\n  using assms by (auto intro: in_field_if_in_dom in_field_if_in_codom)\n\nlemma in_field_iff_in_dom_or_in_codom:\n  \"in_field L x \\<longleftrightarrow> in_dom L x \\<or> in_codom L x\"\n  by blast\n\nlemma in_field_rel_inv_eq [simp]: \"in_field R\\<inverse> = in_field R\"\n  by (intro ext) auto\n\nlemma in_field_compE [elim]:\n  assumes \"in_field (R \\<circ>\\<circ> S) x\"\n  obtains (in_dom) \"in_dom R x\" | (in_codom) \"in_codom S x\"\n  using assms by blast\n\nlemma in_field_eq_in_dom_if_in_codom_eq_in_dom:\n  assumes \"in_codom R = in_dom R\"\n  shows \"in_field R = in_dom R\"\n  using assms by (intro ext) (auto elim: in_fieldE')\n\ndefinition \"rel_if B R x y \\<equiv> B \\<longrightarrow> R x y\"\n\nbundle rel_if_syntax begin notation (output) rel_if (infixl \"\\<longrightarrow>\" 50) end\nbundle no_rel_if_syntax begin no_notation (output) rel_if (infixl \"\\<longrightarrow>\" 50) end\nunbundle rel_if_syntax\n\nlemma rel_if_if_impI [intro]:\n  assumes \"B \\<Longrightarrow> R x y\"\n  shows \"(rel_if B R) x y\"\n  unfolding rel_if_def using assms by blast\n\nlemma rel_if_if_notI [simp]:\n  assumes \"\\<not>B\"\n  shows \"(rel_if B R) x y\"\n  unfolding rel_if_def using assms by blast\n\nlemma rel_ifE [elim]:\n  assumes \"(rel_if B R) x y\"\n  obtains \"\\<not>B\" | \"B\" \"R x y\"\n  using assms unfolding rel_if_def by blast\n\nlemma rel_ifD:\n  assumes \"(rel_if B R) x y\"\n  and \"B\"\n  shows \"R x y\"\n  using assms by blast\n\nlemma rel_if_eq_if_pred [simp]:\n  assumes \"B\"\n  shows \"(rel_if B R) x y = R x y\"\n  using assms by blast\n\nconsts restrict_left :: \"('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'c \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n\ndefinition \"restrict_right R P \\<equiv> (restrict_left R\\<inverse> P)\\<inverse>\"\n\noverloading\n  restrict_left_pred \\<equiv> \"restrict_left :: ('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\nbegin\n  definition \"restrict_left_pred R P x y \\<equiv> P x \\<and> R x y\"\nend\n\nbundle restrict_syntax\nbegin\nnotation restrict_left (\"(_)\\<restriction>(\\<^bsub>_\\<^esub>)\" [1000])\nnotation restrict_right (\"(_)\\<upharpoonleft>(\\<^bsub>_\\<^esub>)\" [1000])\nend\nbundle no_restrict_syntax\nbegin\nno_notation restrict_left (\"(_)\\<restriction>(\\<^bsub>_\\<^esub>)\" [1000])\nno_notation restrict_right (\"(_)\\<upharpoonleft>(\\<^bsub>_\\<^esub>)\" [1000])\nend\nunbundle restrict_syntax\n\nlemma restrict_leftI [intro]:\n  assumes \"R x y\"\n  and \"P x\"\n  shows \"R\\<restriction>\\<^bsub>P\\<^esub> x y\"\n  using assms unfolding restrict_left_pred_def by blast\n\nlemma restrict_leftE [elim]:\n  assumes \"R\\<restriction>\\<^bsub>P\\<^esub> x y\"\n  obtains \"P x\" \"R x y\"\n  using assms unfolding restrict_left_pred_def by blast\n\nlemma restrict_right_eq: \"R\\<upharpoonleft>\\<^bsub>P\\<^esub> = ((R\\<inverse>)\\<restriction>\\<^bsub>P\\<^esub>)\\<inverse>\"\n  unfolding restrict_right_def ..\n\nlemma rel_inv_restrict_right_rel_inv_eq_restrict_left [simp]: \"((R\\<inverse>)\\<upharpoonleft>\\<^bsub>P\\<^esub>)\\<inverse> = R\\<restriction>\\<^bsub>P\\<^esub>\"\n  by (simp add: restrict_right_eq)\n\nlemma restrict_right_iff_restrict_left: \"R\\<upharpoonleft>\\<^bsub>P\\<^esub> x y = (R\\<inverse>)\\<restriction>\\<^bsub>P\\<^esub> y x\"\n  unfolding restrict_right_eq by simp\n\nlemma restrict_rightI [intro]:\n  assumes \"R x y\"\n  and \"P y\"\n  shows \"R\\<upharpoonleft>\\<^bsub>P\\<^esub> x y\"\n  using assms by (auto iff: restrict_right_iff_restrict_left)\n\nlemma restrict_rightE [elim]:\n  assumes \"R\\<upharpoonleft>\\<^bsub>P\\<^esub> x y\"\n  obtains \"P y\" \"R x y\"\n  using assms by (auto iff: restrict_right_iff_restrict_left)\n\nlemma rel_inv_restrict_left_inv_restrict_left_eq:\n  fixes R :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\" and P :: \"'a \\<Rightarrow> bool\" and Q :: \"'b \\<Rightarrow> bool\"\n  shows \"(((R\\<restriction>\\<^bsub>P\\<^esub>)\\<inverse>)\\<restriction>\\<^bsub>Q\\<^esub>)\\<inverse> = (((R\\<inverse>)\\<restriction>\\<^bsub>Q\\<^esub>)\\<inverse>)\\<restriction>\\<^bsub>P\\<^esub>\"\n  by (intro ext iffI restrict_leftI rel_invI) auto\n\nlemma restrict_left_right_eq_restrict_right_left:\n  fixes R :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\" and P :: \"'a \\<Rightarrow> bool\" and Q :: \"'b \\<Rightarrow> bool\"\n  shows \"R\\<restriction>\\<^bsub>P\\<^esub>\\<upharpoonleft>\\<^bsub>Q\\<^esub> = R\\<upharpoonleft>\\<^bsub>Q\\<^esub>\\<restriction>\\<^bsub>P\\<^esub>\"\n  unfolding restrict_right_eq\n  by (fact rel_inv_restrict_left_inv_restrict_left_eq)\n\nlemma in_dom_restrict_leftI [intro]:\n  assumes \"R x y\"\n  and \"P x\"\n  shows \"in_dom R\\<restriction>\\<^bsub>P\\<^esub> x\"\n  using assms by blast\n\nlemma in_dom_restrict_left_if_in_dom:\n  assumes \"in_dom R x\"\n  and \"P x\"\n  shows \"in_dom R\\<restriction>\\<^bsub>P\\<^esub> x\"\n  using assms by blast\n\nlemma in_dom_restrict_leftE [elim]:\n  assumes \"in_dom R\\<restriction>\\<^bsub>P\\<^esub> x\"\n  obtains y where \"P x\" \"R x y\"\n  using assms by blast\n\nlemma in_codom_restrict_leftI [intro]:\n  assumes \"R x y\"\n  and \"P x\"\n  shows \"in_codom R\\<restriction>\\<^bsub>P\\<^esub> y\"\n  using assms by blast\n\nlemma in_codom_restrict_leftE [elim]:\n  assumes \"in_codom R\\<restriction>\\<^bsub>P\\<^esub> y\"\n  obtains x where \"P x\" \"R x y\"\n  using assms by blast\n\ndefinition \"rel_bimap f g (R :: 'a \\<Rightarrow> 'b \\<Rightarrow> bool) x y \\<equiv> R (f x) (g y)\"\n\nlemma rel_bimap_eq [simp]: \"rel_bimap f g R x y = R (f x) (g y)\"\n  unfolding rel_bimap_def by simp\n\ndefinition \"rel_map f R \\<equiv> rel_bimap f f R\"\n\nlemma rel_bimap_self_eq_rel_map [simp]: \"rel_bimap f f R = rel_map f R\"\n  unfolding rel_map_def by simp\n\nlemma rel_map_eq [simp]: \"rel_map f R x y = R (f x) (f y)\"\n  by (simp only: rel_bimap_self_eq_rel_map[symmetric] rel_bimap_eq)\n\n\nend", "meta": {"author": "kappelmann", "repo": "transport-isabelle", "sha": "b6d2cb56ea4abf6e496d1c258d5b3d2a816d75ff", "save_path": "github-repos/isabelle/kappelmann-transport-isabelle", "path": "github-repos/isabelle/kappelmann-transport-isabelle/transport-isabelle-b6d2cb56ea4abf6e496d1c258d5b3d2a816d75ff/HOL_Basics/Binary_Relations/Binary_Relation_Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.8887587831798666, "lm_q1q2_score": 0.760645210890876}}
{"text": "section \"Integer Paritions\"\n\ntheory Integer_Partitions\n  imports\n    \"HOL-Library.Multiset\"\n    Common_Lemmas\n    Card_Number_Partitions.Card_Number_Partitions\nbegin\n\nsubsection\"Definition\"\n\ndefinition integer_partitions :: \"nat \\<Rightarrow> nat multiset set\" where\n  \"integer_partitions i = {A. sum_mset A = i \\<and> 0 \\<notin># A}\"\ntext \\<open>Cardinality: \\<open>Partition i\\<close> (from \\<open>Card_Number_Partitions.Card_Number_Partitions\\<close> \\cite{AFPnumpat})\\<close>\ntext \"Example: \\<open>integer_partitions 4 = {{4}, {3,1}, {2,2} {2,1,1}, {1,1,1,1}}\\<close>\"\n\nsubsection\"Algorithm\"\n\nfun integer_partitions_enum_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat list list\" where\n  \"integer_partitions_enum_aux 0 m = [[]]\"\n| \"integer_partitions_enum_aux n m =\n  [h#r . h \\<leftarrow> [1..< Suc (min n m)], r \\<leftarrow> integer_partitions_enum_aux (n-h) h]\"\n\nfun integer_partitions_enum :: \"nat \\<Rightarrow> nat list list\" where\n \"integer_partitions_enum n = integer_partitions_enum_aux n n\"\n\nsubsection\"Verification\"\n\nsubsubsection\"Correctness\"\n\nlemma integer_partitions_empty: \"[] \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> n = 0\"\n  by(induct n) auto\n\nlemma integer_partitions_enum_aux_first:\n  \"x # xs \\<in> set (integer_partitions_enum_aux n m)\n    \\<Longrightarrow> xs \\<in> set (integer_partitions_enum_aux (n-x) x)\"\n  by(induct n) auto\n\nlemma integer_partitions_enum_aux_max_n:\n  \"x#xs \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> x \\<le> n\"\n  by (induct n) auto\n\nlemma integer_partitions_enum_aux_max_head:\n  \"x#xs \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> x \\<le> m\"\n  by (induct n) auto\n\n(*not used, but nice to have nonetheless*)\nlemma integer_partitions_enum_aux_max:\n  \"xs \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> x \\<le> m\"\nproof(induct xs arbitrary: n m x)\n  case Nil\n  then show ?case using integer_partitions_enum_aux_max_head by simp\nnext\n  case (Cons y xs)\n  then show ?case \n    using integer_partitions_enum_aux_max_head integer_partitions_enum_aux_first  \n    by fastforce                                         \nqed\n\nlemma integer_partitions_enum_aux_sum:\n  \"xs \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> sum_list xs = n\"\nproof(induct xs arbitrary: n m)\n  case Nil\n  then show ?case using integer_partitions_empty by simp\nnext\n  case (Cons x xs)\n  then have \"\\<lbrakk>xs \\<in> set (integer_partitions_enum_aux (n-x) x)\\<rbrakk> \\<Longrightarrow> sum_list xs = (n-x)\"\n    by simp\n  moreover have \"xs \\<in> set (integer_partitions_enum_aux (n-x) x)\"\n    using Cons integer_partitions_enum_aux_first by simp\n  moreover have \"x \\<le> n\"\n    using Cons integer_partitions_enum_aux_max_n by simp\n  ultimately show ?case\n    by simp\nqed\n\nlemma integer_partitions_enum_aux_not_null_aux:\n  \"x#xs \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> x \\<noteq> 0\"\n  by (induct n) auto\n\nlemma integer_partitions_enum_aux_not_null:\n  \"xs \\<in> set (integer_partitions_enum_aux n m) \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> x \\<noteq> 0\"\nproof(induct xs arbitrary: x n m)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons y xs)\n  show ?case proof(cases \"y = x\")\n    case True\n    then show ?thesis\n      using Cons integer_partitions_enum_aux_not_null_aux by simp \n  next\n    case False\n    then show ?thesis\n       using Cons integer_partitions_enum_aux_not_null_aux integer_partitions_enum_aux_first\n       by fastforce\n  qed\nqed\n\nlemma integer_partitions_enum_aux_head_minus:\n     \"h \\<le> m \\<Longrightarrow> h > 0 \\<Longrightarrow> n \\<ge> h \\<Longrightarrow>\n  ys \\<in> set (integer_partitions_enum_aux (n-h) h)\\<Longrightarrow> h#ys \\<in> set (integer_partitions_enum_aux n m)\"\nproof(induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have 1: \"1 \\<le> m\" by simp\n\n  have 2: \"(\\<exists>x. (x = min (Suc n) m \\<or> Suc 0 \\<le> x \\<and> x < Suc n \\<and> x < m) \\<and> h # ys\n      \\<in> (#) x ` set (integer_partitions_enum_aux (Suc n - x) x))\"\n    unfolding image_def using Suc by auto\n\n  from 1 2 have \"Suc 0 \\<le> m \\<and>(\\<exists>x. (x = min (Suc n) m \\<or> Suc 0 \\<le> x \\<and> x < Suc n \\<and> x < m)\n         \\<and> h # ys \\<in> (#) x ` set (integer_partitions_enum_aux (Suc n - x) x))\"\n    by simp\n    \n  then show ?case by auto\nqed\n\nlemma integer_partitions_enum_aux_head_plus:\n  \"h \\<le> m \\<Longrightarrow> h > 0 \\<Longrightarrow> ys \\<in> set (integer_partitions_enum_aux n h)\n    \\<Longrightarrow> h#ys \\<in> set (integer_partitions_enum_aux (h + n) m)\"\n  using integer_partitions_enum_aux_head_minus by simp \n\nlemma integer_partitions_enum_correct_aux1:\n  assumes \"0 \\<notin># A \"\n  and \"\\<forall>x \\<in># A. x \\<le> m\"\nshows\" \\<exists>xs\\<in>set (integer_partitions_enum_aux (\\<Sum>\\<^sub># A) m). A = mset xs\"\nusing assms proof(induct A arbitrary: m rule: multiset_induct_max)\n  case empty\n  then show ?case by simp\nnext\n  case (add h A)\n  have hc1: \"h \\<le> m\"\n    using add by simp\n\n  have hc2: \"h > 0\"\n    using add by simp\n\n  obtain ys where o1: \"ys \\<in> set (integer_partitions_enum_aux (\\<Sum>\\<^sub># A) h)\" and o2: \" A = mset ys\"\n    using add by force\n\n  have \"h#ys \\<in> set (integer_partitions_enum_aux (h + \\<Sum>\\<^sub># A) m)\"\n    using integer_partitions_enum_aux_head_plus hc1 o1 hc2 by blast \n\n  then show ?case\n    using o2 by force\nqed\n\ntheorem integer_partitions_enum_correct:\n  \"set (map mset (integer_partitions_enum n)) = integer_partitions n\"\nproof(standard)\n  have \"\\<lbrakk>xs \\<in> set (integer_partitions_enum_aux n n)\\<rbrakk> \\<Longrightarrow> \\<Sum>\\<^sub># (mset xs) = n\" for xs\n    by (simp add: integer_partitions_enum_aux_sum sum_mset_sum_list)\n  moreover have \"xs \\<in> set (integer_partitions_enum_aux n n) \\<Longrightarrow> 0 \\<notin># mset xs\" for xs\n    using integer_partitions_enum_aux_not_null by auto\n  ultimately show \"set (map mset (integer_partitions_enum n)) \\<subseteq> integer_partitions n\"\n    unfolding integer_partitions_def by auto\nnext\n  have \"0 \\<notin># A \\<Longrightarrow> A \\<in> mset ` set (integer_partitions_enum_aux (\\<Sum>\\<^sub># A) (\\<Sum>\\<^sub># A))\" for A\n    unfolding image_def\n    using integer_partitions_enum_correct_aux1 by (simp add: sum_mset.remove)\n  then show \"integer_partitions n \\<subseteq> set (map mset (integer_partitions_enum n))\"\n    unfolding integer_partitions_def by auto\nqed\n\nsubsubsection\"Distinctness\"\n\nlemma integer_partitions_enum_aux_distinct:\n  \"distinct (integer_partitions_enum_aux n m)\"\nproof(induct n m rule:integer_partitions_enum_aux.induct)\n  case (1 m)\n  then show ?case by simp\nnext\n  case (2 n m)\n  have \"distinct [h#r . h \\<leftarrow> [1..< Suc (min (Suc n) m)], r \\<leftarrow> integer_partitions_enum_aux ((Suc n)-h) h]\"\n    apply(subst Cons_distinct_concat_map_function)\n    using 2 by auto\n  then show ?case by simp\nqed\n\ntheorem integer_partitions_enum_distinct:\n  \"distinct (integer_partitions_enum n)\"\n  using integer_partitions_enum_aux_distinct by simp\n\nsubsubsection\"Cardinality\"\n\nlemma partitions_bij_betw_count:\n  \"bij_betw count {N. count N partitions n} {p. p partitions n}\"\n  by (rule bij_betw_byWitness[where f'=\"Abs_multiset\"]) (auto simp: partitions_imp_finite_elements)\n\nlemma card_partitions_count_partitions:\n  \"card {p. p partitions n} = card {N. count N partitions n}\"\n  using bij_betw_same_card partitions_bij_betw_count by metis\n\ntext\"this sadly is not proven in \\<open>Card_Number_Partitions.Card_Number_Partitions\\<close>\"\nlemma card_partitions_number_partition:\n  \"card {p. p partitions n} = card {N. number_partition n N}\"\n  using card_partitions_count_partitions count_partitions_iff by simp\n\nlemma integer_partitions_number_partition_eq:\n  \"integer_partitions n = {N. number_partition n N}\"\n  using integer_partitions_def number_partition_def by auto\n\nlemma integer_partitions_cardinality_aux:\n  \"card (integer_partitions n) = (\\<Sum>k\\<le>n. Partition n k)\"\n  using card_partitions_number_partition integer_partitions_number_partition_eq card_partitions\n  by simp\n\ntheorem integer_partitions_cardinality:\n  \"card (integer_partitions n) = Partition (2*n) n\"\n  using integer_partitions_cardinality_aux Partition_sum_Partition_diff add_implies_diff le_add1 mult_2\n  by simp  \n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Combinatorial_Enumeration_Algorithms/Integer_Partitions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.8459424353665382, "lm_q1q2_score": 0.7606049344379391}}
{"text": "(* Author: Bernhard Stöckl *)\n\ntheory Selectivities\n  imports Complex_Main \"HOL-Library.Multiset\"\nbegin\n\nsection \\<open>Selectivities\\<close>\n\ntype_synonym 'a selectivity = \"'a \\<Rightarrow> 'a \\<Rightarrow> real\"\n\ndefinition sel_symm :: \"'a selectivity \\<Rightarrow> bool\" where\n  \"sel_symm sel = (\\<forall>x y. sel x y = sel y x)\"\n\ndefinition sel_reasonable :: \"'a selectivity \\<Rightarrow> bool\" where\n  \"sel_reasonable sel = (\\<forall>x y. sel x y \\<le> 1 \\<and> sel x y > 0)\"\n\nsubsection \\<open>Selectivity Functions\\<close>\n\nfun list_sel_aux :: \"'a selectivity \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> real\" where\n  \"list_sel_aux sel x [] = 1\"\n| \"list_sel_aux sel x (y#ys) = sel x y * list_sel_aux sel x ys\"\n\nfun list_sel :: \"'a selectivity \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> real\" where\n  \"list_sel sel [] y = 1\"\n| \"list_sel sel (x#xs) y = list_sel_aux sel x y * list_sel sel xs y\"\n\nfun list_sel_aux' :: \"'a selectivity \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> real\" where\n  \"list_sel_aux' sel [] y = 1\"\n| \"list_sel_aux' sel (x#xs) y = sel x y * list_sel_aux' sel xs y\"\n\nfun list_sel':: \"'a selectivity \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> real\" where\n  \"list_sel' sel x [] = 1\"\n| \"list_sel' sel x (y#ys) = list_sel_aux' sel x y * list_sel' sel x ys\"\n\ndefinition set_sel_aux :: \"'a selectivity \\<Rightarrow> 'a \\<Rightarrow> 'a set \\<Rightarrow> real\" where\n  \"set_sel_aux sel x Y = (\\<Prod>y \\<in> Y. sel x y)\"\n\ndefinition set_sel :: \"'a selectivity \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> real\" where\n  \"set_sel sel X Y = (\\<Prod>x \\<in> X. set_sel_aux sel x Y)\"\n\ndefinition set_sel_aux' :: \"'a selectivity \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> real\" where\n  \"set_sel_aux' sel X y = (\\<Prod>x \\<in> X. sel x y)\"\n\ndefinition set_sel' :: \"'a selectivity \\<Rightarrow> 'a set \\<Rightarrow> 'a set \\<Rightarrow> real\" where\n  \"set_sel' sel X Y = (\\<Prod>y \\<in> Y. set_sel_aux' sel X y)\"\n\nfun ldeep_s :: \"'a selectivity \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> real\" where\n  \"ldeep_s f [] = (\\<lambda>_. 1)\"\n| \"ldeep_s f (x#xs) = (\\<lambda>a. if a=x then list_sel_aux' f xs a else ldeep_s f xs a)\"\n\nsubsection \\<open>Proofs\\<close>\n\nlemma distinct_alt: \"(\\<forall>x\\<in># mset xs. count (mset xs) x = 1) \\<longleftrightarrow> distinct xs\"\n  by(induction xs) auto\n\nlemma mset_y_eq_list_sel_aux_eq: \"mset y = mset z \\<Longrightarrow> list_sel_aux f x y = list_sel_aux f x z\"\nproof(induction \"length y\" arbitrary: y z)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have \"length y > 0\" by auto\n  then obtain y' ys where y_def[simp]: \"y=y'#ys\" using list.exhaust_sel by blast\n  have \"length z > 0\" using Suc by auto\n  then obtain z' zs where z_def[simp]: \"z=z'#zs\" using list.exhaust_sel by blast\n  then have \"length zs = n\" using Suc by (metis length_Cons mset_eq_length nat.inject)\n  then show ?case\n  proof(cases \"y'=z'\")\n    case True\n    then show ?thesis using Suc by simp\n  next\n    case False\n    have \"y' \\<in># mset y\" by simp\n    moreover have \"z' \\<in># mset y\" using Suc by simp\n    ultimately have \"\\<exists>c. mset y = mset (y'#z'#c)\"\n      using False ex_mset in_set_member multi_member_split set_mset_mset\n      by (metis (mono_tags, opaque_lifting) member_rec(1) mset.simps(2))\n    then obtain c where c_def[simp]: \"mset y = mset (y'#z'#c)\" by blast\n    then have 0: \"mset ys = mset (z'#c)\" by simp\n    then have 1: \"mset zs = mset (y'#c)\" using Suc.prems by simp\n    have \"list_sel_aux f x y = list_sel_aux f x (y' # ys)\" by simp\n    also have \"\\<dots> = f x y' * list_sel_aux f x ys\" by simp\n    also have \"\\<dots> = f x y' * list_sel_aux f x (z'#c)\" using Suc.hyps 0 by fastforce\n    also have \"\\<dots> = f x z' * list_sel_aux f x (y'#c)\" by simp\n    also have \"\\<dots> = f x z' * list_sel_aux f x zs\"\n      using 1 Suc.hyps(1) \\<open>length zs = n\\<close> by presburger\n    finally show ?thesis by simp\n  qed\nqed\n\nlemma mset_y_eq_list_sel_eq: \"mset y = mset y' \\<Longrightarrow> list_sel f x y = list_sel f x y'\"\n  apply(induction x)\n   apply(auto)[2]\n  using mset_y_eq_list_sel_aux_eq by fast\n\nlemma mset_x_eq_list_sel_eq: \"mset x = mset z \\<Longrightarrow> list_sel f x y = list_sel f z y\"\nproof(induction \"length x\" arbitrary: x z)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  then have \"length x > 0\" by auto\n  then obtain x' xs where y_def[simp]: \"x=x'#xs\" using list.exhaust_sel by blast\n  have \"length z > 0\" using Suc by auto\n  then obtain z' zs where z_def[simp]: \"z=z'#zs\" using list.exhaust_sel by blast\n  then have \"length zs = n\" using Suc by (metis length_Cons mset_eq_length nat.inject)\n  then show ?case\n  proof(cases \"x'=z'\")\n    case True\n    then show ?thesis using Suc by simp\n  next\n    case False\n    have \"x' \\<in># mset x\" by simp\n    moreover have \"z' \\<in># mset x\" using Suc by simp\n    ultimately have \"\\<exists>c. mset x = mset (x'#z'#c)\"\n      using False ex_mset in_set_member multi_member_split set_mset_mset\n      by (metis (mono_tags, opaque_lifting) member_rec(1) mset.simps(2))\n    then obtain c where c_def[simp]: \"mset x = mset (x'#z'#c)\" by blast\n    then have 0: \"mset xs = mset (z'#c)\" by simp\n    then have 1: \"mset zs = mset (x'#c)\" using Suc.prems by simp\n    have \"list_sel f x y = list_sel f (x'#xs) y\" by simp\n    also have \"\\<dots> = list_sel_aux f x' y * list_sel f xs y\" by simp\n    also have \"\\<dots> = list_sel_aux f x' y * list_sel f (z'#c) y\" using Suc.hyps 0 by fastforce\n    also have \"\\<dots> = list_sel_aux f z' y * list_sel f (x'#c) y\" by simp\n    also have \"\\<dots> = list_sel_aux f z' y * list_sel f zs y\"\n      using 1 Suc.hyps(1) \\<open>length zs = n\\<close> by presburger\n    finally show ?thesis by simp\n  qed\nqed\n\nlemma list_sel_empty: \"list_sel f x [] = 1\"\n  by(induction x) auto\n\nlemma list_sel'_empty: \"list_sel' f [] y = 1\"\n  by(induction y) auto\n\nlemma list_sel_symm_app:\n    \"sel_symm f \\<Longrightarrow> list_sel_aux f x y * list_sel f y xs = list_sel f y (x # xs)\"\n  by(induction y) (auto simp: sel_symm_def)\n\nlemma list_sel_symm: \"sel_symm f \\<Longrightarrow> list_sel f x y = list_sel f y x\"\n  by(induction x) (auto simp: sel_symm_def list_sel_empty list_sel_symm_app)\n\nlemma list_sel_symm_aux_eq': \"sel_symm f \\<Longrightarrow> list_sel_aux f x y = list_sel_aux' f y x\"\n  by(induction y) (auto simp: sel_symm_def)\n\nlemma list_sel_sing_aux': \"list_sel f x [y] = list_sel_aux' f x y\"\n  by(induction x) auto\n\nlemma list_sel_sing_aux: \"list_sel f [x] y = list_sel_aux f x y\"\n  by(induction y) auto\n\nlemma list_sel'_sing_aux': \"list_sel' f x [y] = list_sel_aux' f x y\"\n  by(induction x) auto\n\nlemma list_sel'_sing_aux: \"list_sel' f [x] y = list_sel_aux f x y\"\n  by(induction y) auto\n\nlemma list_sel'_split_aux: \"list_sel' f (x#xs) y = list_sel_aux f x y * list_sel' f xs y\"\n  by(induction y) auto\n\nlemma list_sel_eq': \"list_sel f x y = list_sel' f x y\"\n  by(induction x) (auto simp: list_sel'_empty list_sel'_split_aux)\n\nlemma mset_x_eq_list_sel_aux'_eq: \"mset x = mset z \\<Longrightarrow> list_sel_aux' f x y = list_sel_aux' f z y\"\n  using list_sel_sing_aux' mset_x_eq_list_sel_eq by metis\n\nlemma foldl_acc_extr: \"foldl (\\<lambda>a b. a * f x b) z y = z * foldl (\\<lambda>a b. a * f x b) (1::real) y\"\nproof(induction y arbitrary: z)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons y ys)\n  have \"foldl (\\<lambda>a b. a * f x b) z (y # ys) = foldl (\\<lambda>a b. a * f x b) (z * f x y) ys\" by simp\n  also have \"\\<dots> =  (z * f x y) * foldl (\\<lambda>a b. a * f x b) 1 ys\" using Cons by blast\n  also have \"\\<dots> = z * foldl (\\<lambda>a b. a * f x b) 1 (y#ys)\"\n    by (smt (verit, ccfv_SIG) Cons.IH foldl_Cons mult.assoc mult.left_commute)\n  finally show ?case .\nqed\n\nlemma list_sel_aux_eq_foldl: \"list_sel_aux f x y = foldl (\\<lambda>a b. a * f x b) 1 y\"\n  apply(induction y)\n   apply(auto)[2]\n  using foldl_acc_extr by metis\n\nlemma list_sel_eq_foldl: \"list_sel f x y = foldl (\\<lambda>a b. a * list_sel_aux f b y) 1 x\"\n  apply(induction x)\n   apply(auto)[2]\n  using foldl_acc_extr by metis\n\ncorollary list_sel_eq_foldl2: \"list_sel f x y = foldl (\\<lambda>a x. a * foldl (\\<lambda>a b. a * f x b) 1 y) 1 x\"\n  by (simp add: list_sel_aux_eq_foldl list_sel_eq_foldl)\n\nlemma list_sel_aux_eq_foldr: \"list_sel_aux f x y = foldr (\\<lambda>b a. a * f x b) y 1\"\n  by(induction y) auto\n\nlemma sel_foldl_eq_foldr:\n  \"foldl (\\<lambda>a b. a * f x b) 1 y = foldr (\\<lambda>b a. a * (f::'a selectivity) x b) y 1\"\n  using list_sel_aux_eq_foldl list_sel_aux_eq_foldr by metis\n\nlemma list_sel_eq_foldr: \"list_sel f x y = foldr (\\<lambda>b a. a * list_sel_aux f b y) x 1\"\n  by(induction x) auto\n\nlemma list_sel_eq_foldr2: \"list_sel f x y = foldr (\\<lambda>x a. a * foldr (\\<lambda>b a. a * f x b) y 1) x 1\"\n  by (simp add: list_sel_aux_eq_foldr list_sel_eq_foldr)\n\nlemma list_sel_aux_reasonable:\n    \"sel_reasonable f \\<Longrightarrow> list_sel_aux f x y \\<le> 1 \\<and> list_sel_aux f x y > 0\"\n  by(induction y) (auto simp: sel_reasonable_def mult_le_one)\n\nlemma list_sel_aux'_reasonable:\n    \"sel_reasonable f \\<Longrightarrow> list_sel_aux' f x y \\<le> 1 \\<and> list_sel_aux' f x y > 0\"\n  by(induction x) (auto simp: sel_reasonable_def mult_le_one)\n\nlemma list_sel_reasonable: \"sel_reasonable f \\<Longrightarrow> list_sel f x y \\<le> 1 \\<and> list_sel f x y > 0\"\n  by(induction x) (auto simp: sel_reasonable_def mult_le_one list_sel_aux_reasonable)\n\nlemma list_sel'_reasonable: \"sel_reasonable f \\<Longrightarrow> list_sel' f x y \\<le> 1 \\<and> list_sel' f x y > 0\"\n  using list_sel_eq' list_sel_reasonable by metis\n\nlemma list_sel_aux_eq_set_sel_aux:\n  \"distinct ys \\<Longrightarrow> list_sel_aux f x ys = set_sel_aux f x (set ys)\"\n  by(induction ys) (auto simp: set_sel_aux_def)\n\nlemma list_sel_eq_set_sel:\n  \"\\<lbrakk>distinct xs; distinct ys\\<rbrakk> \\<Longrightarrow> list_sel f xs ys = set_sel f (set xs) (set ys)\"\n  by(induction xs) (auto simp: set_sel_def list_sel_aux_eq_set_sel_aux list_sel_empty)\n\nlemma list_sel'_eq_set_sel:\n  \"\\<lbrakk>distinct xs; distinct ys\\<rbrakk> \\<Longrightarrow> list_sel' f xs ys = set_sel f (set xs) (set ys)\"\n  by (auto simp add: list_sel_eq' dest: list_sel_eq_set_sel)\n\nlemma set_sel_symm_if_finite: \"\\<lbrakk>finite X; finite Y; sel_symm f\\<rbrakk> \\<Longrightarrow> set_sel f X Y = set_sel f Y X\"\n  using finite_distinct_list list_sel_symm list_sel_eq_set_sel by metis\n\nlemma set_sel_aux_1_if_notfin: \"\\<not>finite Y \\<Longrightarrow> set_sel_aux f x Y = 1\"\n  unfolding set_sel_aux_def by simp\n\nlemma set_sel_1_if_notfin1: \"\\<not>finite X \\<Longrightarrow> set_sel f X Y = 1\"\n  unfolding set_sel_def set_sel_aux_def by simp\n\nlemma set_sel_1_if_notfin2: \"\\<not>finite Y \\<Longrightarrow> set_sel f X Y = 1\"\n  unfolding set_sel_def set_sel_aux_def by simp\n\nlemma set_sel_symm: \"sel_symm f \\<Longrightarrow> set_sel f X Y = set_sel f Y X\"\n  using set_sel_symm_if_finite[of X Y]\n  by (fastforce simp: set_sel_1_if_notfin1 set_sel_1_if_notfin2)\n\nlemma list_sel_aux'_eq_set_sel_aux':\n  \"distinct xs \\<Longrightarrow> list_sel_aux' f xs x = set_sel_aux' f (set xs) x\"\n  by(induction xs) (auto simp: set_sel_aux'_def)\n\nlemma list_sel'_eq_set_sel':\n  \"\\<lbrakk>distinct xs; distinct ys\\<rbrakk> \\<Longrightarrow> list_sel' f xs ys = set_sel' f (set xs) (set ys)\"\n  by(induction ys) (auto simp: set_sel'_def list_sel_aux'_eq_set_sel_aux' list_sel_empty)\n\nlemma list_sel_eq_set_sel':\n  \"\\<lbrakk>distinct xs; distinct ys\\<rbrakk> \\<Longrightarrow> list_sel f xs ys = set_sel' f (set xs) (set ys)\"\n  by (simp add: list_sel'_eq_set_sel' list_sel_eq')\n\nlemma set_sel'_symm_if_finite: \"\\<lbrakk>finite X; finite Y; sel_symm f\\<rbrakk> \\<Longrightarrow> set_sel' f X Y = set_sel' f Y X\"\n  using finite_distinct_list list_sel_symm list_sel_eq_set_sel' by metis\n\nlemma set_sel_aux'_1_if_notfin: \"\\<not>finite X \\<Longrightarrow> set_sel_aux' f X y = 1\"\n  unfolding set_sel_aux'_def by simp\n\nlemma set_sel'_1_if_notfin1: \"\\<not>finite X \\<Longrightarrow> set_sel' f X Y = 1\"\n  unfolding set_sel'_def set_sel_aux'_def by simp\n\nlemma set_sel'_1_if_notfin2: \"\\<not>finite Y \\<Longrightarrow> set_sel' f X Y = 1\"\n  unfolding set_sel'_def set_sel_aux'_def by simp\n\nlemma set_sel'_symm: \"sel_symm f \\<Longrightarrow> set_sel' f X Y = set_sel' f Y X\"\n  using set_sel'_symm_if_finite[of X Y]\n  by (fastforce simp: set_sel'_1_if_notfin1 set_sel'_1_if_notfin2)\n\nlemma set_sel'_eq_set_sel: \"set_sel' f X Y = set_sel f X Y\"\n  unfolding set_sel_def set_sel_aux_def set_sel'_def set_sel_aux'_def using prod.swap by fast\n\nlemma set_sel_aux_reasonable_fin:\n  \"\\<lbrakk>finite y; sel_reasonable f\\<rbrakk> \\<Longrightarrow> set_sel_aux f x y \\<le> 1 \\<and> set_sel_aux f x y > 0\"\n  unfolding set_sel_aux_def\n  by(induction y rule: finite_induct) (auto simp: sel_reasonable_def mult_le_one)\n\nlemma set_sel_aux_reasonable:\n  \"sel_reasonable f \\<Longrightarrow> set_sel_aux f x y \\<le> 1 \\<and> set_sel_aux f x y > 0\"\n  by(cases \"finite y\") (auto simp: set_sel_aux_reasonable_fin set_sel_aux_1_if_notfin)\n\nlemma set_sel_aux'_reasonable_fin:\n  \"\\<lbrakk>finite x; sel_reasonable f\\<rbrakk> \\<Longrightarrow> set_sel_aux' f x y \\<le> 1 \\<and> set_sel_aux' f x y > 0\"\n  unfolding set_sel_aux'_def\n  by(induction x rule: finite_induct) (auto simp: sel_reasonable_def mult_le_one)\n\nlemma set_sel_aux'_reasonable:\n  \"sel_reasonable f \\<Longrightarrow> set_sel_aux' f x y \\<le> 1 \\<and> set_sel_aux' f x y > 0\"\n  by(cases \"finite x\") (auto simp: set_sel_aux'_reasonable_fin set_sel_aux'_1_if_notfin)\n\nlemma set_sel_reasonable_fin:\n  \"\\<lbrakk>finite x; sel_reasonable f\\<rbrakk> \\<Longrightarrow> set_sel f x y \\<le> 1 \\<and> set_sel f x y > 0\"\n  unfolding set_sel_def\n  apply(induction x rule: finite_induct)\n   using set_sel_aux'_reasonable_fin apply(simp)\n  by (smt (verit) prod_le_1 prod_pos set_sel_aux_reasonable)\n\nlemma set_sel_reasonable: \"sel_reasonable f \\<Longrightarrow> set_sel f x y \\<le> 1 \\<and> set_sel f x y > 0\"\n  by(cases \"finite x\") (auto simp: set_sel_reasonable_fin set_sel_1_if_notfin1)\n\nlemma set_sel'_reasonable_fin:\n  \"\\<lbrakk>finite y; sel_reasonable f\\<rbrakk> \\<Longrightarrow> set_sel' f x y \\<le> 1 \\<and> set_sel' f x y > 0\"\n  unfolding set_sel'_def\n  apply(induction y rule: finite_induct)\n   using set_sel_aux'_reasonable_fin apply(simp)\n  by (smt (verit) prod_le_1 prod_pos set_sel_aux'_reasonable)\n\nlemma set_sel'_reasonable: \"sel_reasonable f \\<Longrightarrow> set_sel' f x y \\<le> 1 \\<and> set_sel' f x y > 0\"\n  by (cases \"finite y\") (auto simp: set_sel'_reasonable_fin set_sel'_1_if_notfin2)\n\nlemma ldeep_s_pos: \"sel_reasonable f \\<Longrightarrow> ldeep_s f xs x > 0\"\n  by (induction xs) (auto simp: list_sel_aux'_reasonable)\n\nlemma distinct_app_trans_r: \"distinct (ys@xs) \\<Longrightarrow> distinct xs\"\n  by simp\n\nlemma distinct_app_trans_l: \"distinct (ys@xs) \\<Longrightarrow> distinct ys\"\n  by simp\n\nlemma ldeep_s_reasonable: \"sel_reasonable f \\<Longrightarrow> ldeep_s f xs y \\<le> 1 \\<and> ldeep_s f xs y > 0\"\n  by (induction xs) (auto simp: list_sel_aux'_reasonable)\n\nlemma ldeep_s_eq_list_sel_aux'_split:\n  \"y \\<in> set xs \\<Longrightarrow> \\<exists>as bs. as @ y # bs = xs \\<and> ldeep_s sel xs y = list_sel_aux' sel bs y\"\nproof(induction xs)\n  case (Cons x xs)\n  then show ?case\n  proof(cases \"x = y\")\n    case False\n    then obtain as bs where as_def: \"as @ y # bs = xs\" \"ldeep_s sel xs y = list_sel_aux' sel bs y\"\n      using Cons by auto\n    then have \"(x#as) @ y # bs = x#xs\" by simp\n    then show ?thesis using False as_def(2) by fastforce\n  qed(auto)\nqed(simp)\n\nlemma distinct_ldeep_s_eq_aux:\n  \"distinct xs \\<Longrightarrow> \\<exists>xs'. xs'@y#ys=xs \\<Longrightarrow> ldeep_s f xs y = list_sel_aux' f ys y\"\nproof(induction xs arbitrary: ys)\n  case (Cons x xs)\n  then show ?case\n  proof(cases \"x=y \\<and> ys=xs\")\n    case True\n    then show ?thesis using Cons.prems by simp\n  next\n    case False\n    then have \"\\<exists>xs'. xs'@y#ys=x#xs \\<and> xs' \\<noteq> []\" using Cons.prems by auto\n    then have 0: \"\\<exists>xs''. x#xs''@y#ys=x#xs\" by (metis list.sel(3) tl_append2)\n    have 1: \"distinct xs\" using Cons.prems(1) by fastforce\n    then show ?thesis\n    proof(cases \"x=y\")\n      case True\n      then have \"count (mset (x#xs)) x \\<ge> 2\" using 0 by auto\n      then show ?thesis using Cons.prems by simp\n    next\n      case False\n      then have \"ldeep_s f (x # xs) y\n              = (\\<lambda>a. if a=x then list_sel_aux' f xs a else ldeep_s f xs a) y\" by simp\n      also have \"\\<dots> =  ldeep_s f xs y\" using False by simp\n      finally show ?thesis using Cons.IH 0 1 by simp\n    qed\n  qed\nqed(simp)\n\nlemma distinct_ldeep_s_eq_aux':\n  \"\\<lbrakk>distinct xs; as @ y # bs = xs\\<rbrakk> \\<Longrightarrow> ldeep_s sel xs y = list_sel_aux' sel bs y\"\n  using distinct_ldeep_s_eq_aux by fast\n\nlemma ldeep_s_last1_if_distinct: \"distinct xs \\<Longrightarrow> ldeep_s sel xs (last xs) = 1\"\n  by (induction xs) auto\n\nlemma ldeep_s_revhd1_if_distinct: \"distinct xs \\<Longrightarrow> ldeep_s sel (rev xs) (hd xs) = 1\"\n  using ldeep_s_last1_if_distinct[of \"rev xs\"] by (simp add: last_rev)\n\nlemma ldeep_s_1_if_nelem: \"x \\<notin> set xs \\<Longrightarrow> ldeep_s sel xs x = 1\"\n  by (induction xs) auto\n\nlemma distinct_xs_not_ys: \"distinct (xs@ys) \\<Longrightarrow> x \\<in> set xs \\<Longrightarrow> x \\<notin> set ys\"\n  by auto\n\nlemma distinct_ys_not_xs: \"distinct (xs@ys) \\<Longrightarrow> x \\<in> set ys \\<Longrightarrow> x \\<notin> set xs\"\n  by auto\n\nlemma distinct_change_order_first_eq_nempty:\n  assumes \"distinct (xs@ys@zs@rs)\"\n      and \"ys \\<noteq> []\"\n      and \"zs \\<noteq> []\"\n      and \"take 1 (xs@ys@zs@rs) = take 1 (xs@zs@ys@rs)\"\n    shows \"xs \\<noteq> []\"\nproof\n  assume \"xs = []\"\n  then have \"take 1 (ys@zs@rs) = take 1 (zs@ys@rs)\" using assms(4) by simp\n  then have \"\\<exists>r rs1 rs2. ys@zs@rs = r#rs1 \\<and> zs@ys@rs = r#rs2\"\n    by (metis append_Cons append_take_drop_id assms(3) neq_Nil_conv take_eq_Nil zero_neq_one)\n  then obtain r rs1 rs2 where r_def: \"ys@zs@rs = r#rs1 \\<and> zs@ys@rs = r#rs2\" by blast\n  then have 0: \"r \\<in> set ys \\<and> r \\<in> set zs\"\n    using assms(2,3) by (metis Cons_eq_append_conv list.set_intros(1))\n  then show False using 0 assms(1) by auto\nqed\n\nlemma distinct_change_order_first_elem:\n  \"\\<lbrakk>distinct (xs@ys@zs@rs); ys \\<noteq> []; zs \\<noteq> []; take 1 (xs@ys@zs@rs) = take 1 (xs@zs@ys@rs)\\<rbrakk>\n    \\<Longrightarrow> take 1 (xs@ys@zs@rs) = take 1  xs\"\n  by (cases xs) (fastforce dest!: distinct_change_order_first_eq_nempty)+\n\nlemma take1_singleton_app: \"take 1 xs = [r] \\<Longrightarrow> take 1 (xs@ys) = [r]\"\n  by (induction xs) (auto)\n\nlemma hd_eq_take1: \"take 1 xs = [r] \\<Longrightarrow> hd xs = r\"\n  using hd_take[of 1 xs] by simp\n\nlemma take1_eq_hd: \"\\<lbrakk>xs \\<noteq> []; hd xs = r\\<rbrakk> \\<Longrightarrow> take 1 xs = [r]\"\n  by (simp add: take_Suc)\n\nlemma nempty_if_take1: \"take 1 xs = [r] \\<Longrightarrow> xs \\<noteq> []\"\n  by force\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Query_Optimization/Selectivities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8459424314825853, "lm_q1q2_score": 0.7606049240857069}}
{"text": "\n\n(*<*) theory ex1_7 imports Main begin (*>*)\n\ntext {* Finite sets can obviously be implemented by lists.  In the\nfollowing, you will be asked to implement the set operations union,\nintersection and difference and to show that these implementations are\ncorrect.  Thus, for a function *}\nprimrec exists ::\"'a \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"exists x [] = False\"|\n\"exists x (y#ys) = ((x=y) \\<or>exists x ys)\"\n\n\nprimrec  list_union :: \"['a list, 'a list] \\<Rightarrow> 'a list\"\n  where \"list_union [] y = y\"\n  |\"list_union (x#xs) y = (if x: set y then list_union xs y else x#(list_union xs y))\"\n\ntext {* to be defined by you it has to be shown that *}\n\n\nlemma \"set (list_union xs ys) = set xs \\<union> set ys\"\n  apply (induct xs)\n  apply auto\ndone\n  \n  \n\ntext {* In addition, the functions should be space efficient in the\nsense that one obtains lists without duplicates (@{text \"distinct\"})\nwhenever the parameters of the functions are duplicate-free.  Thus, for\nexample, *}\nlemma l1:\"\\<lbrakk>a \\<notin> set ys; a \\<notin> set xs\\<rbrakk> \\<Longrightarrow>  a \\<notin> set (list_union xs ys)\"\n  apply(induct xs)\n   apply auto\n  done\nlemma [rule_format]: \n  \"distinct xs \\<longrightarrow> distinct ys \\<longrightarrow> (distinct (list_union xs ys))\"\n  apply (induct xs)\n   apply (auto simp add: l1)\n  done\n\ntext {* \\emph{Hint:} @{text \"distinct\"} is defined in @{text List.thy}. *}\n\n\nsubsubsection {* Quantification over Sets *}\n\ntext {* Define a (non-trivial) set @{text S} such that the following\nproposition holds: *}\n\nlemma \"((\\<forall> x \\<in> A. P x) \\<and> (\\<forall> x \\<in> B. P x)) \\<longrightarrow> (\\<forall> x \\<in> (A \\<union> B). P x)\"\n  apply auto\n  done\n\ntext {* Define a (non-trivial) predicate @{text P} such that *}\n\nlemma \"\\<forall> x \\<in> A. Q (f x) \\<Longrightarrow>  \\<forall> y \\<in> f ` A. Q y\"\n  apply auto\n  done\n\n(*<*) end (*>*)", "meta": {"author": "hei411", "repo": "Isabelle", "sha": "9126e84b3e39af28336f25e3b7563a01f70625fa", "save_path": "github-repos/isabelle/hei411-Isabelle", "path": "github-repos/isabelle/hei411-Isabelle/Isabelle-9126e84b3e39af28336f25e3b7563a01f70625fa/Online_exercises/ex1_7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856559, "lm_q2_score": 0.8499711794579723, "lm_q1q2_score": 0.7605452507156363}}
{"text": "(*\n   Authors: Asta Halkjær From, Agnes Moesgård Eschen & Jørgen Villadsen, DTU Compute\n*)\n\nchapter \\<open>Formalizing Rasiowa's Axioms for Propositional Logic\\<close>\n\ntheory System_R imports Main begin\n\ntext \\<open>All references are to Alonzo Church (1956): Introduction to Mathematical Logic\\<close>\n\nsection \\<open>Syntax / Axiomatics / Semantics\\<close>\n\ndatatype form = Pro nat | Neg form | Dis form form (infix \\<open>\\<Or>\\<close> 0)\n\nabbreviation Imp (infix \\<open>\\<rightarrow>\\<close> 0) where \\<open>(p \\<rightarrow> q) \\<equiv> (Neg p \\<Or> q)\\<close>\n\ntext \\<open>Rasiowa 1949 building on Russell 1908, Bernays 1926 and Götlind 1947 [Church page 157]\\<close>\n\ninductive Axiomatics (\\<open>\\<turnstile>\\<close>) where\n  \\<open>\\<turnstile> q\\<close> if \\<open>\\<turnstile> p\\<close> and \\<open>\\<turnstile> (p \\<rightarrow> q)\\<close> |\n  \\<open>\\<turnstile> ((p \\<Or> p) \\<rightarrow> p)\\<close> |\n  \\<open>\\<turnstile> (p \\<rightarrow> (p \\<Or> q))\\<close> |\n  \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> ((r \\<Or> p) \\<rightarrow> (q \\<Or> r)))\\<close>\n\nabbreviation Truth (\\<open>\\<top>\\<close>) where \\<open>\\<top> \\<equiv> (undefined \\<rightarrow> undefined)\\<close>\n\ntheorem \\<open>\\<turnstile> \\<top>\\<close> using Axiomatics.intros by metis\n\nprimrec semantics (infix \\<open>\\<Turnstile>\\<close> 0) where\n  \\<open>(I \\<Turnstile> Pro n) = I n\\<close> |\n  \\<open>(I \\<Turnstile> Neg p) = (if I \\<Turnstile> p then False else True)\\<close> |\n  \\<open>(I \\<Turnstile> (p \\<Or> q)) = (if I \\<Turnstile> p then True else (I \\<Turnstile> q))\\<close>\n\ntheorem \\<open>I \\<Turnstile> p\\<close> if \\<open>\\<turnstile> p\\<close> using that by induct auto\n\ndefinition \\<open>valid p \\<equiv> \\<forall>I. (I \\<Turnstile> p)\\<close>\n\ntheorem \\<open>valid p = \\<turnstile> p\\<close> oops \\<comment> \\<open>Proof at end\\<close>\n\nabbreviation Falsity (\\<open>\\<bottom>\\<close>) where \\<open>\\<bottom> \\<equiv> Neg \\<top>\\<close>\n\ntheorem \\<open>\\<turnstile> (\\<bottom> \\<rightarrow> p)\\<close> using Axiomatics.intros by metis\n\nlemmas MP = Axiomatics.intros(1)\nlemmas Idem = Axiomatics.intros(2)\nlemmas AddR = Axiomatics.intros(3)\nlemmas Swap = Axiomatics.intros(4)\n\nsection \\<open>Soundness\\<close>\n\ntheorem soundness: \\<open>\\<turnstile> p \\<Longrightarrow> I \\<Turnstile> p\\<close>\n  by (induct rule: Axiomatics.induct) auto\n\nsection \\<open>Derived Rules\\<close>\n\nproposition alternative_axiom: \\<open>\\<turnstile> (p \\<rightarrow> (p \\<Or> q))\\<close> if \\<open>\\<And>p q. \\<turnstile> (p \\<rightarrow> (q \\<Or> p))\\<close>\n  by (metis MP Idem Swap that)\n\nlemma AddL: \\<open>\\<turnstile> (p \\<rightarrow> (q \\<Or> p))\\<close>\n  by (metis MP Idem Swap AddR)\n\nlemma Perm: \\<open>\\<turnstile> ((p \\<Or> q) \\<rightarrow> (q \\<Or> p))\\<close>\n  by (metis Idem AddL AddR Swap MP)\n\nlemma SwapCon: \\<open>\\<turnstile> ((p \\<rightarrow> (q \\<Or> r)) \\<rightarrow> (p \\<rightarrow> (r \\<Or> q)))\\<close>\n  by (meson MP Perm Swap)\n\nlemma SubR: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> ((r \\<Or> p) \\<rightarrow> (r \\<Or> q)))\\<close>\n  by (meson MP SwapCon Swap)\n\ntext \\<open>Russell 1908 and Bernays 1926 [Church page 157]\\<close>\n\ninductive RB (\\<open>\\<tturnstile>\\<close>) where\n  \\<open>\\<tturnstile> q\\<close> if \\<open>\\<tturnstile> p\\<close> and \\<open>\\<tturnstile> (p \\<rightarrow> q)\\<close> |\n  \\<open>\\<tturnstile> ((p \\<Or> p) \\<rightarrow> p)\\<close> |\n  \\<open>\\<tturnstile> (p \\<rightarrow> (q \\<Or> p))\\<close> |\n  \\<open>\\<tturnstile> ((p \\<Or> q) \\<rightarrow> (q \\<Or> p))\\<close> |\n  \\<open>\\<tturnstile> ((p \\<rightarrow> q) \\<rightarrow> ((r \\<Or> p) \\<rightarrow> (r \\<Or> q)))\\<close>\n\ntheorem Axiomatics_RB: \\<open>\\<turnstile> p \\<longleftrightarrow> \\<tturnstile> p\\<close>\nproof\n  show \\<open>\\<turnstile> p\\<close> if \\<open>\\<tturnstile> p\\<close>\n    using that by induct (use SubR Axiomatics.intros in meson)+\n  show \\<open>\\<tturnstile> p\\<close> if \\<open>\\<turnstile> p\\<close>\n    using that by induct (use RB.intros in meson)+\nqed\n\nlemma SwapAnte: \\<open>\\<turnstile> (((p \\<Or> q) \\<rightarrow> r) \\<rightarrow> ((q \\<Or> p) \\<rightarrow> r))\\<close>\n  by (metis AddR Idem MP Perm Swap)\n\nlemma SubL: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> ((p \\<Or> r) \\<rightarrow> (q \\<Or> r)))\\<close>\n  by (meson MP SwapAnte Swap)\n\nlemma AddM: \\<open>\\<turnstile> ((p \\<Or> q) \\<rightarrow> ((p \\<Or> r) \\<Or> q))\\<close>\n  by (meson SubL MP AddR)\n\nlemma Church1: \\<open>\\<turnstile> ((p \\<Or> (p \\<Or> q)) \\<rightarrow> (p \\<Or> q))\\<close>\n  by (meson Idem MP SubL SubR AddR)\n\nlemma Church2: \\<open>\\<turnstile> (p \\<Or> ((p \\<Or> q) \\<rightarrow> q))\\<close>\n  by (metis Church1 MP Swap AddL AddM)\n\nlemma Imp1: \\<open>\\<turnstile> (p \\<rightarrow> p)\\<close>\n  by (metis Idem AddL AddR Swap MP)\n\nlemma Neg': \\<open>\\<turnstile> ((p \\<Or> q) \\<rightarrow> (Neg q \\<rightarrow> p))\\<close>\n  using Imp1 MP Swap by blast\n\nlemma Tran: \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> (p \\<rightarrow> r)))\\<close>\n  by (meson Neg' SubL MP)\n\nlemma Church3: \\<open>\\<turnstile> ((p \\<rightarrow> (q \\<rightarrow> r)) \\<rightarrow> (q \\<rightarrow> (p \\<rightarrow> r)))\\<close>\n  by (meson Church2 Tran MP)\n\nlemma Neg: \\<open>\\<turnstile> ((p \\<rightarrow> \\<bottom>) \\<rightarrow> Neg p)\\<close>\n  by (metis Church3 Imp1 MP Perm)\n\nlemma ImpER: \\<open>\\<turnstile> ((p \\<Or> (q \\<rightarrow> r)) \\<rightarrow> (q \\<rightarrow> (p \\<Or> r)))\\<close>\n  using SubR by (metis Church2 MP)\n\nlemma SubR': \\<open>\\<turnstile> ((p \\<Or> q) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> (p \\<Or> r)))\\<close>\n  using SubR Church3 MP by blast\n\nlemma SubL': \\<open>\\<turnstile> ((p \\<Or> q) \\<rightarrow> ((p \\<rightarrow> r) \\<rightarrow> (r \\<Or> q)))\\<close>\n  using SubL Church3 MP by blast\n\nlemma FalsityE': \\<open>\\<turnstile> ((p \\<Or> q) \\<rightarrow> ((Neg p \\<Or> q) \\<rightarrow> q))\\<close>\n  by (meson SubR SubL' MP Idem)\n\nlemma FalsityE'': \\<open>\\<turnstile> ((Neg p \\<Or> r) \\<rightarrow> ((p \\<Or> q) \\<rightarrow> (q \\<Or> r)))\\<close>\n  by (meson ImpER MP SubR' SwapAnte)\n\nlemma FalsityEImpER: \\<open>\\<turnstile> ((Neg p \\<Or> r) \\<rightarrow> ((p \\<Or> q) \\<rightarrow> ((Neg q \\<Or> r) \\<rightarrow> r)))\\<close>\n  using FalsityE'' FalsityE' by (meson SubR MP)\n\nlemma DisE: \\<open>\\<turnstile> ((p \\<rightarrow> r) \\<rightarrow> ((q \\<rightarrow> r) \\<rightarrow> ((p \\<Or> q) \\<rightarrow> r)))\\<close>\n  using FalsityEImpER by (meson MP ImpER Tran)\n\nlemma Imp2: \\<open>\\<turnstile> ((p \\<Or> (q \\<rightarrow> r)) \\<rightarrow> ((p \\<Or> q) \\<rightarrow> (p \\<Or> r)))\\<close>\n  using DisE SubR MP AddL AddR by metis\n\nlemma Imp2': \\<open>\\<turnstile> ((p \\<rightarrow> q) \\<rightarrow> ((p \\<rightarrow> (q \\<rightarrow> r)) \\<rightarrow> (p \\<rightarrow> r)))\\<close>\n  by (metis AddL Imp2 Tran MP)\n\nprimrec imply :: \\<open>form list \\<Rightarrow> form \\<Rightarrow> form\\<close> where\n  \\<open>imply [] q = q\\<close>\n| \\<open>imply (p # ps) q = (p \\<rightarrow> imply ps q)\\<close>\n\nlemma imply_head: \\<open>\\<turnstile> (imply (p # ps) p)\\<close>\n  by (induct ps) (simp add: Imp1, metis AddL Imp2 MP imply.simps(2))\n\nlemma imply_Cons: \\<open>\\<turnstile> (imply ps q) \\<Longrightarrow> \\<turnstile> (imply (p # ps) q)\\<close>\n  by (metis AddL MP imply.simps(2))\n\nlemma imply_mem: \\<open>p \\<in> set ps \\<Longrightarrow> \\<turnstile> (imply ps p)\\<close>\n  using imply_head imply_Cons by (induct ps) auto\n\nlemma imply_MP: \\<open>\\<turnstile> (imply ps p \\<rightarrow> (imply ps (p \\<rightarrow> q) \\<rightarrow> imply ps q))\\<close>\nproof (induct ps)\n  case Nil\n  then show ?case\n    by (simp add: Church2)\nnext\n  case (Cons r ps)\n  then show ?case\n  proof -\n    have \\<open>\\<turnstile> ((r \\<rightarrow> imply ps p) \\<rightarrow> (r \\<rightarrow> (imply ps (p \\<rightarrow> q) \\<rightarrow> imply ps q)))\\<close>\n      by (meson Cons.hyps AddL Imp2 MP)\n    then have \\<open>\\<turnstile> ((r \\<rightarrow> imply ps p) \\<rightarrow> ((r \\<rightarrow> imply ps (p \\<rightarrow> q)) \\<rightarrow> (r \\<rightarrow> imply ps q)))\\<close>\n      by (meson Imp2' Church3 Tran MP)\n    then show ?thesis\n      by simp\n  qed\nqed\n\nlemma imply_mp': \\<open>\\<turnstile> (imply ps p) \\<Longrightarrow> \\<turnstile> (imply ps (p \\<rightarrow> q)) \\<Longrightarrow> \\<turnstile> (imply ps q)\\<close>\n  using imply_MP by (meson MP)\n\nlemma add_imply: \\<open>\\<turnstile> q \\<Longrightarrow> \\<turnstile> (imply ps q)\\<close>\n  using imply_Cons by (induct ps) simp_all\n\nlemma imply_append: \\<open>imply (ps @ qs) r = imply ps (imply qs r)\\<close>\n  by (induct ps) simp_all\n\nlemma imply_swap: \\<open>\\<turnstile> (imply (ps @ qs) r) \\<Longrightarrow> \\<turnstile> (imply (qs @ ps) r)\\<close>\nproof (induct qs arbitrary: ps)\n  case (Cons q qs)\n  then show ?case\n    by (metis imply_Cons imply_head imply_mp' imply.simps(2) imply_append)\nqed simp\n\nlemma deduct: \\<open>\\<turnstile> (imply (p # ps) q) \\<longleftrightarrow> \\<turnstile> (imply ps (p \\<rightarrow> q))\\<close>\n  using imply_swap by (metis imply.simps(1-2) imply_append)\n\ntheorem imply_weaken: \\<open>\\<turnstile> (imply ps q) \\<Longrightarrow> set ps \\<subseteq> set ps' \\<Longrightarrow> \\<turnstile> (imply ps' q)\\<close>\nproof (induct ps arbitrary: q)\n  case (Cons p ps)\n  note \\<open>\\<turnstile> (imply (p # ps) q)\\<close>\n  then have \\<open>\\<turnstile> (imply ps (p \\<rightarrow> q))\\<close>\n    using deduct by blast\n  then have \\<open>\\<turnstile> (imply ps' (p \\<rightarrow> q))\\<close>\n    using Cons by simp\n  then show ?case\n    using Cons(3) by (meson imply_mem imply_mp' list.set_intros(1) subset_code(1))\nqed (simp add: add_imply)\n\nlemma cut: \\<open>\\<turnstile> (imply ps p) \\<Longrightarrow> \\<turnstile> (imply (p # ps) q) \\<Longrightarrow> \\<turnstile> (imply ps q)\\<close>\n  using deduct imply_mp' by blast\n\nlemma imply4: \\<open>\\<turnstile> (imply (p # q # ps) r) \\<Longrightarrow> \\<turnstile> (imply (q # p # ps) r)\\<close>\n  by (metis ImpER MP imply.simps(2))\n\nlemma cut': \\<open>\\<turnstile> (imply (p # ps) r) \\<Longrightarrow> \\<turnstile> (imply (q # ps) p) \\<Longrightarrow> \\<turnstile> (imply (q # ps) r)\\<close>\n  using imply_Cons cut imply4 by blast\n\nlemma imply_lift: \\<open>\\<turnstile> (p \\<rightarrow> q) \\<Longrightarrow> \\<turnstile> (imply ps p \\<rightarrow> imply ps q)\\<close>\n  by (metis Imp1 add_imply imply.simps(2) imply_mp')\n\nlemma DNeg: \\<open>\\<turnstile> (Neg (Neg p) \\<rightarrow> p)\\<close>\n  by (metis Idem AddR Swap MP)\n\nlemma imply_DNeg: \\<open>\\<turnstile> (imply ps (Neg (Neg p)) \\<rightarrow> imply ps p)\\<close>\n  using DNeg imply_lift by simp\n\nlemma Boole: \\<open>\\<turnstile> (imply ((Neg p) # ps) \\<bottom>) \\<Longrightarrow> \\<turnstile> (imply ps p)\\<close>\n  by (meson Neg MP imply_DNeg deduct imply_lift)\n\nlemma imply_front: \\<open>\\<turnstile> (imply S p) \\<Longrightarrow> set S - {q} \\<subseteq> set S' \\<Longrightarrow> \\<turnstile> (imply (q # S') p)\\<close>\n  by (metis Diff_single_insert imply_weaken list.set(2))\n\nlemma FalsityE: \\<open>\\<turnstile> (p \\<rightarrow> (Neg p \\<rightarrow> q))\\<close>\n  using AddM Imp1 MP Perm by blast\n\nsection \\<open>Consistent\\<close>\n\ndefinition consistent :: \\<open>form set \\<Rightarrow> bool\\<close> where\n  \\<open>consistent S \\<equiv> \\<nexists>S'. set S' \\<subseteq> S \\<and> \\<turnstile> (imply S' \\<bottom>)\\<close>\n\nlemma UN_finite_bound:\n  assumes \\<open>finite p\\<close> \\<open>p \\<subseteq> (\\<Union>n. f n)\\<close>\n  shows \\<open>\\<exists>m :: nat. p \\<subseteq> (\\<Union>n \\<le> m. f n)\\<close>\n  using assms\nproof (induct rule: finite_induct)\n  case (insert x p)\n  then obtain m where \\<open>p \\<subseteq> (\\<Union>n \\<le> m. f n)\\<close>\n    by fast\n  then have \\<open>p \\<subseteq> (\\<Union>n \\<le> (m + k). f n)\\<close> for k\n    by fastforce\n  moreover obtain m' where \\<open>x \\<in> f m'\\<close>\n    using insert(4) by blast\n  ultimately have \\<open>{x} \\<union> p \\<subseteq> (\\<Union>n \\<le> m + m'. f n)\\<close>\n    by auto\n  then show ?case\n    by blast\nqed simp\n\nsection \\<open>Extension\\<close>\n\nprimrec extend :: \\<open>form set \\<Rightarrow> (nat \\<Rightarrow> form) \\<Rightarrow> nat \\<Rightarrow> form set\\<close> where\n  \\<open>extend S f 0 = S\\<close>\n| \\<open>extend S f (Suc n) =\n    (if consistent ({f n} \\<union> extend S f n)\n     then {f n} \\<union> extend S f n\n     else extend S f n)\\<close>\n\ndefinition Extend :: \\<open>form set \\<Rightarrow> (nat \\<Rightarrow> form) \\<Rightarrow> form set\\<close> where\n  \\<open>Extend S f \\<equiv> \\<Union>n. extend S f n\\<close>\n\nlemma Extend_subset: \\<open>S \\<subseteq> Extend S f\\<close>\n  unfolding Extend_def by (metis Union_upper extend.simps(1) range_eqI)\n\nlemma extend_bound: \\<open>(\\<Union>n \\<le> m. extend S f n) = extend S f m\\<close>\n  by (induct m) (simp_all add: atMost_Suc)\n\nlemma consistent_extend: \\<open>consistent S \\<Longrightarrow> consistent (extend S f n)\\<close>\n  by (induct n) simp_all\n\nlemma consistent_Extend:\n  assumes \\<open>consistent S\\<close>\n  shows \\<open>consistent (Extend S f)\\<close>\n  unfolding Extend_def\nproof (rule ccontr)\n  assume \\<open>\\<not> consistent (\\<Union>n. extend S f n)\\<close>\n  then obtain S' where \\<open>\\<turnstile> (imply S' \\<bottom>)\\<close> \\<open>set S' \\<subseteq> (\\<Union>n. extend S f n)\\<close>\n    unfolding consistent_def by blast\n  then obtain m where \\<open>set S' \\<subseteq> (\\<Union>n \\<le> m. extend S f n)\\<close>\n    using UN_finite_bound by (metis List.finite_set)\n  then have \\<open>set S' \\<subseteq> extend S f m\\<close>\n    using extend_bound by blast\n  moreover have \\<open>consistent (extend S f m)\\<close>\n    using assms consistent_extend by blast\n  ultimately show False\n    unfolding consistent_def using \\<open>\\<turnstile> (imply S' \\<bottom>)\\<close> by blast\nqed\n\nsection \\<open>Maximal\\<close>\n\ndefinition maximal :: \\<open>form set \\<Rightarrow> bool\\<close> where\n  \\<open>maximal S \\<equiv> \\<forall>p. p \\<notin> S \\<longrightarrow> \\<not> consistent ({p} \\<union> S)\\<close>\n\nlemma maximal_Extend:\n  assumes \\<open>surj f\\<close>\n  shows \\<open>maximal (Extend S f)\\<close>\nproof (rule ccontr)\n  assume \\<open>\\<not> maximal (Extend S f)\\<close>\n  then obtain p where \\<open>p \\<notin> Extend S f\\<close> \\<open>consistent ({p} \\<union> Extend S f)\\<close>\n    unfolding maximal_def using assms consistent_Extend by blast\n  obtain k where n: \\<open>f k = p\\<close>\n    using \\<open>surj f\\<close> unfolding surj_def by metis\n  then have \\<open>p \\<notin> extend S f (Suc k)\\<close>\n    using \\<open>p \\<notin> Extend S f\\<close> unfolding Extend_def by blast\n  then have \\<open>\\<not> consistent ({p} \\<union> extend S f k)\\<close>\n    using n by fastforce\n  moreover have \\<open>{p} \\<union> extend S f k \\<subseteq> {p} \\<union> Extend S f\\<close>\n    unfolding Extend_def by blast\n  ultimately have \\<open>\\<not> consistent ({p} \\<union> Extend S f)\\<close>\n    unfolding consistent_def by fastforce\n  then show False\n    using \\<open>consistent ({p} \\<union> Extend S f)\\<close> by blast\nqed\n\nsection \\<open>Hintikka\\<close>\n\nlocale Hintikka =\n  fixes H :: \\<open>form set\\<close>\n  assumes\n    NoFalsity: \\<open>\\<bottom> \\<notin> H\\<close> and\n    ProP: \\<open>Pro n \\<in> H \\<Longrightarrow> (Neg (Pro n)) \\<notin> H\\<close> and\n    DisP: \\<open>(p \\<Or> q) \\<in> H \\<Longrightarrow> p \\<in> H \\<or> q \\<in> H\\<close> and\n    DisN: \\<open>(Neg (p \\<Or> q)) \\<in> H \\<Longrightarrow> (Neg p) \\<in> H \\<and> (Neg q) \\<in> H\\<close> and\n    NegN: \\<open>(Neg (Neg p)) \\<in> H \\<Longrightarrow> p \\<in> H\\<close>\n\nabbreviation (input) \\<open>model H n \\<equiv> Pro n \\<in> H\\<close>\n\nlemma Hintikka_model:\n  \\<open>Hintikka H \\<Longrightarrow> (p \\<in> H \\<longrightarrow> (model H \\<Turnstile> p)) \\<and> ((Neg p) \\<in> H \\<longrightarrow> \\<not> (model H \\<Turnstile> p))\\<close>\n  by (induct p) (simp; unfold Hintikka_def, blast)+\n\nlemma inconsistent_head:\n  assumes \\<open>maximal S\\<close> \\<open>consistent S\\<close> \\<open>p \\<notin> S\\<close>\n  shows \\<open>\\<exists>S'. \\<turnstile> (imply (p # S') \\<bottom>) \\<and> set S' \\<subseteq> S\\<close>\nproof -\n  obtain S' where S': \\<open>\\<turnstile> (imply S' \\<bottom>)\\<close> \\<open>set S' \\<subseteq> {p} \\<union> S\\<close> \\<open>p \\<in> set S'\\<close>\n    using assms unfolding maximal_def consistent_def by fast\n  then obtain S'' where S'': \\<open>\\<turnstile> (imply (p # S'') \\<bottom>)\\<close> \\<open>set S'' = set S' - {p}\\<close>\n    by (metis imply_front set_removeAll subset_refl)\n  then show ?thesis\n    using S'(2) by fast\nqed\n\nlemma Hintikka_Extend:\n  assumes \\<open>maximal S\\<close> \\<open>consistent S\\<close>\n  shows \\<open>Hintikka S\\<close>\nproof\n  show \\<open>\\<bottom> \\<notin> S\\<close>\n    using assms(2) imply_head imply_mem unfolding consistent_def\n    by (metis List.set_insert empty_set insert_Diff insert_is_Un singletonI sup.cobounded1)\nnext\n  fix n\n  assume \\<open>Pro n \\<in> S\\<close>\n  moreover have \\<open>\\<turnstile> (imply [Pro n, Neg (Pro n)] \\<bottom>)\\<close>\n    by (simp add: FalsityE)\n  ultimately show \\<open>(Neg (Pro n)) \\<notin> S\\<close>\n    using assms(2) unfolding consistent_def\n    by (metis bot.extremum empty_set insert_subset list.set(2))\nnext\n  fix p q\n  assume *: \\<open>(p \\<Or> q) \\<in> S\\<close>\n  show \\<open>p \\<in> S \\<or> q \\<in> S\\<close>\n  proof (rule disjCI, rule ccontr)\n    assume **: \\<open>q \\<notin> S\\<close>\n    then obtain Sq' where Sq': \\<open>\\<turnstile> (imply (q # Sq') \\<bottom>)\\<close> \\<open>set Sq' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    assume \\<open>p \\<notin> S\\<close>\n    then obtain Sp' where Sp': \\<open>\\<turnstile> (imply (p # Sp') \\<bottom>)\\<close> \\<open>set Sp' \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    obtain S' where S': \\<open>set S' = set Sp' \\<union> set Sq'\\<close> \\<open>set S' \\<subseteq> S\\<close>\n      using Sq'(2) Sp'(2) by (metis le_sup_iff set_union)\n    then have \\<open>\\<turnstile> (imply (p # S') \\<bottom>)\\<close> \\<open>\\<turnstile> (imply (q # S') \\<bottom>)\\<close>\n      using Sq' Sp' deduct imply_weaken by simp_all\n    then have \\<open>\\<turnstile> (imply ((p \\<Or> q) # S') \\<bottom>)\\<close>\n      by (metis DisE MP imply.simps(2))\n    moreover have \\<open>set ((p \\<Or> q) # S') \\<subseteq> S\\<close>\n      using * S' Sp'(2) Sq'(2) by auto\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  qed\nnext\n  fix p q\n  assume *: \\<open>(Neg (p \\<Or> q)) \\<in> S\\<close>\n  show \\<open>(Neg p) \\<in> S \\<and> (Neg q) \\<in> S\\<close>\n  proof (rule conjI; rule ccontr)\n    assume \\<open>(Neg p) \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> (imply ((Neg p) # S') \\<bottom>)\\<close> \\<open>set S' \\<subseteq> S - {Neg p}\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> (imply ((Neg (p \\<Or> q)) # S') (Neg p))\\<close>\n      using Idem AddR Tran add_imply deduct MP by metis\n    ultimately have \\<open>\\<turnstile> (imply ((Neg (p \\<Or> q)) # S') \\<bottom>)\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((Neg (p \\<Or> q)) # S') \\<subseteq> S\\<close>\n      using * S'(2) by auto\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  next\n    assume \\<open>(Neg q) \\<notin> S\\<close>\n    then obtain S' where S': \\<open>\\<turnstile> (imply ((Neg q) # S') \\<bottom>)\\<close> \\<open>set S' \\<subseteq> S - {Neg q}\\<close>\n      using assms inconsistent_head by blast\n    moreover have \\<open>\\<turnstile> (imply ((Neg (p \\<Or> q)) # S') (Neg q))\\<close>\n      using Idem AddR AddL Tran add_imply deduct MP Neg' by metis\n    ultimately have \\<open>\\<turnstile> (imply ((Neg (p \\<Or> q)) # S') \\<bottom>)\\<close>\n      using cut' by blast\n    moreover have \\<open>set ((Neg (p \\<Or> q)) # S') \\<subseteq> S\\<close>\n      using *(1) S'(2) by auto\n    ultimately show False\n      using assms unfolding consistent_def by blast\n  qed\nnext\n  fix p\n  assume *: \\<open>(Neg (Neg p)) \\<in> S\\<close>\n  show \\<open>p \\<in> S\\<close>\n  proof (rule ccontr)\n    assume \\<open>p \\<notin> S\\<close>\n    then obtain SNA where SNA: \\<open>\\<turnstile> (imply (p # SNA) \\<bottom>)\\<close> \\<open>set SNA \\<subseteq> S\\<close>\n      using assms inconsistent_head by blast\n    from * obtain SA where SA: \\<open>\\<turnstile> (imply SA p)\\<close> \\<open>set SA \\<subseteq> S\\<close>\n      using imply_DNeg MP\n      by (metis empty_set empty_subsetI imply_head insert_absorb insert_mono list.simps(15))\n    obtain S' where S': \\<open>set S' = set SA \\<union> set SNA\\<close> \\<open>set S' \\<subseteq> S\\<close>\n      using SA(2) SNA(2) by (metis Un_subset_iff set_union)\n    with SNA SA have \\<open>\\<turnstile> (imply (p # S') \\<bottom>)\\<close> \\<open>\\<turnstile> (imply S' p)\\<close>\n      using deduct imply_weaken by simp_all\n    with S' assms show \\<open>False\\<close> unfolding consistent_def\n      using cut by meson\n  qed\nqed\n\nsection \\<open>Countable Formulas\\<close>\n\nprimrec diag :: \\<open>nat \\<Rightarrow> (nat \\<times> nat)\\<close> where\n  \\<open>diag 0 = (0, 0)\\<close>\n| \\<open>diag (Suc n) =\n     (let (x, y) = diag n\n      in case y of\n          0 \\<Rightarrow> (0, Suc x)\n        | Suc y \\<Rightarrow> (Suc x, y))\\<close>\n\ntheorem diag_le1: \\<open>fst (diag (Suc n)) < Suc n\\<close>\n  by (induct n) (simp_all add: Let_def split_def split: nat.split)\n\ntheorem diag_le2: \\<open>snd (diag (Suc (Suc n))) < Suc (Suc n)\\<close>\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n')\n  then show ?case\n  proof (induct n')\n    case 0\n    then show ?case by simp\n  next\n    case (Suc _)\n    then show ?case\n      using diag_le1 by (simp add: Let_def split_def split: nat.split)\n  qed\nqed\n\ntheorem diag_le3: \\<open>fst (diag n) = Suc x \\<Longrightarrow> snd (diag n) < n\\<close>\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n')\n  then show ?case\n  proof (induct n')\n    case 0\n    then show ?case by simp\n  next\n    case (Suc n'')\n    then show ?case using diag_le2 by simp\n  qed\nqed\n\ntheorem diag_le4: \\<open>fst (diag n) = Suc x \\<Longrightarrow> x < n\\<close>\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n')\n  then have \\<open>fst (diag (Suc n')) < Suc n'\\<close>\n    using diag_le1 by blast\n  then show ?case using Suc by simp\nqed\n\nfunction undiag :: \\<open>nat \\<times> nat \\<Rightarrow> nat\\<close> where\n  \\<open>undiag (0, 0) = 0\\<close>\n| \\<open>undiag (0, Suc y) = Suc (undiag (y, 0))\\<close>\n| \\<open>undiag (Suc x, y) = Suc (undiag (x, Suc y))\\<close>\n  by pat_completeness auto\ntermination\n  by (relation \\<open>measure (\\<lambda>(x, y). ((x + y) * (x + y + 1)) div 2 + x)\\<close>) auto\n\ntheorem diag_undiag [simp]: \\<open>diag (undiag (x, y)) = (x, y)\\<close>\n  by (induct rule: undiag.induct) simp_all\n\ndatatype btree = Leaf nat | Branch btree btree\n\nfunction diag_btree :: \\<open>nat \\<Rightarrow> btree\\<close> where\n  \\<open>diag_btree n = (case fst (diag n) of\n       0 \\<Rightarrow> Leaf (snd (diag n))\n     | Suc x \\<Rightarrow> Branch (diag_btree x) (diag_btree (snd (diag n))))\\<close>\n  by auto\ntermination\n  by (relation \\<open>measure id\\<close>) (auto intro: diag_le3 diag_le4)\n\nprimrec undiag_btree :: \\<open>btree \\<Rightarrow> nat\\<close> where\n  \\<open>undiag_btree (Leaf n) = undiag (0, n)\\<close>\n| \\<open>undiag_btree (Branch t1 t2) = undiag (Suc (undiag_btree t1), undiag_btree t2)\\<close>\n\ntheorem diag_undiag_btree [simp]: \\<open>diag_btree (undiag_btree t) = t\\<close>\n  by (induct t) simp_all\n\ndeclare diag_btree.simps [simp del] undiag_btree.simps [simp del]\n\nfun form_of_btree :: \\<open>btree \\<Rightarrow> form\\<close> where\n  \\<open>form_of_btree (Leaf n) = undefined\\<close>\n| \\<open>form_of_btree (Branch (Leaf 0) (Leaf n)) = Pro n\\<close>\n| \\<open>form_of_btree (Branch (Leaf (Suc 0)) (Branch t1 t2)) =\n     Dis (form_of_btree t1) (form_of_btree t2)\\<close>\n| \\<open>form_of_btree (Branch (Leaf 0) (Branch t _)) = Neg (form_of_btree t)\\<close>\n| \\<open>form_of_btree (Branch (Leaf (Suc 0)) (Leaf _)) = undefined\\<close>\n| \\<open>form_of_btree (Branch (Leaf (Suc (Suc _))) _) = undefined\\<close>\n| \\<open>form_of_btree (Branch (Branch _ _) _) = undefined\\<close>\n\nprimrec btree_of_form :: \\<open>form \\<Rightarrow> btree\\<close> where\n  \\<open>btree_of_form (Pro n) = Branch (Leaf 0) (Leaf n)\\<close>\n| \\<open>btree_of_form (Neg p) = Branch (Leaf 0) (Branch (btree_of_form p) (Leaf 0))\\<close>\n| \\<open>btree_of_form (Dis p q) = Branch (Leaf (Suc 0))\n     (Branch (btree_of_form p) (btree_of_form q))\\<close>\n\ndefinition diag_form :: \\<open>nat \\<Rightarrow> form\\<close> where\n  \\<open>diag_form n = form_of_btree (diag_btree n)\\<close>\n\ndefinition undiag_form :: \\<open>form \\<Rightarrow> nat\\<close> where\n  \\<open>undiag_form p = undiag_btree (btree_of_form p)\\<close>\n\ntheorem diag_undiag_form [simp]: \\<open>diag_form (undiag_form p) = p\\<close>\n  unfolding diag_form_def undiag_form_def by (induct p) simp_all\n\nabbreviation \\<open>from_nat \\<equiv> diag_form\\<close>\nabbreviation \\<open>to_nat \\<equiv> undiag_form\\<close>\n\nlemma surj_from_nat: \\<open>surj from_nat\\<close>\n  by (metis diag_undiag_form surj_def)\n\nsection \\<open>Completeness\\<close>\n\nlemma imply_completeness:\n  assumes valid: \\<open>\\<forall>I s. list_all (\\<lambda>q. (I \\<Turnstile> q)) ps \\<longrightarrow> (I \\<Turnstile> p)\\<close>\n  shows \\<open>\\<turnstile> (imply ps p)\\<close>\nproof (rule ccontr)\n  assume \\<open>\\<not> \\<turnstile> (imply ps p)\\<close>\n  then have *: \\<open>\\<not> \\<turnstile> (imply ((Neg p) # ps) \\<bottom>)\\<close>\n    using Boole by blast\n\n  let ?S = \\<open>set ((Neg p) # ps)\\<close>\n  let ?H = \\<open>Extend ?S from_nat\\<close>\n\n  have \\<open>consistent ?S\\<close>\n    unfolding consistent_def using * imply_weaken by blast\n  then have \\<open>consistent ?H\\<close> \\<open>maximal ?H\\<close>\n    using consistent_Extend maximal_Extend surj_from_nat by blast+\n  then have \\<open>Hintikka ?H\\<close>\n    using Hintikka_Extend by blast\n\n  have \\<open>model ?H \\<Turnstile> p\\<close> if \\<open>p \\<in> ?S\\<close> for p\n    using that Extend_subset Hintikka_model \\<open>Hintikka ?H\\<close> by blast\n  then have \\<open>model ?H \\<Turnstile> (Neg p)\\<close> \\<open>list_all (\\<lambda>p. (model ?H \\<Turnstile> p)) ps\\<close>\n    unfolding list_all_def by fastforce+\n  then have \\<open>model ?H \\<Turnstile> p\\<close>\n    using valid by blast\n  then show False\n    using \\<open>model ?H \\<Turnstile> (Neg p)\\<close> by simp\nqed\n\ntheorem completeness: \\<open>\\<forall>I. (I \\<Turnstile> p) \\<Longrightarrow> \\<turnstile> p\\<close>\n  using imply_completeness[where ps=\\<open>[]\\<close>] by simp\n\nsection \\<open>Main Result\\<close>\n\ntheorem main: \\<open>valid p = \\<turnstile> p\\<close>\nproof\n  assume \\<open>valid p\\<close>\n  with completeness show \\<open>\\<turnstile> p\\<close>\n    unfolding valid_def .\nnext\n  assume \\<open>\\<turnstile> p\\<close>\n  with soundness show \\<open>valid p\\<close>\n    unfolding valid_def by (intro allI)\nqed\n\nsection \\<open>Using Unnecessary Axiom in Principia Mathematica (PM) by Whitehead and Russell 1910\\<close>\n\ntext \\<open>First appeared in Russell 1908 and derived from the other axioms in Bernays 1926 (system RB)\\<close>\n\ninductive PM (\\<open>\\<then>\\<close>) where\n  \\<open>\\<then> q\\<close> if \\<open>\\<then> p\\<close> and \\<open>\\<then> (p \\<rightarrow> q)\\<close> |\n  \\<open>\\<then> ((p \\<Or> p) \\<rightarrow> p)\\<close> |\n  \\<open>\\<then> (p \\<rightarrow> (q \\<Or> p))\\<close> |\n  \\<open>\\<then> ((p \\<Or> q) \\<rightarrow> (q \\<Or> p))\\<close> |\n  \\<open>\\<then> ((p \\<Or> (q \\<Or> r)) \\<rightarrow> (q \\<Or> (p \\<Or> r)))\\<close> |\n  \\<open>\\<then> ((p \\<rightarrow> q) \\<rightarrow> ((r \\<Or> p) \\<rightarrow> (r \\<Or> q)))\\<close>\n\nproposition PM_extends_RB: \\<open>\\<tturnstile> p \\<Longrightarrow> \\<then> p\\<close>\n  by (induct rule: RB.induct) (auto intro: PM.intros)\n\ntheorem equivalence: \\<open>\\<then> p \\<longleftrightarrow> \\<turnstile> p\\<close>\nproof\n  have *: \\<open>\\<turnstile> ((p \\<Or> (q \\<Or> r)) \\<rightarrow> (q \\<Or> (p \\<Or> r)))\\<close> for p q r\n    using completeness by simp\n  show \\<open>\\<turnstile> p\\<close> if \\<open>\\<then> p\\<close>\n    using that by induct (use * SubR Axiomatics.intros in meson)+\n  show \\<open>\\<then> p\\<close> if \\<open>\\<turnstile> p\\<close>\n    using that by induct (use PM.intros in meson)+\nqed\n\ncorollary associativity:\n  \\<open>\\<then> (((p \\<Or> q) \\<Or> r) \\<rightarrow> (p \\<Or> (q \\<Or> r)))\\<close>\n  \\<open>\\<then> ((p \\<Or> (q \\<Or> r)) \\<rightarrow> ((p \\<Or> q) \\<Or> r))\\<close>\n  using equivalence completeness by simp_all\n\nend\n", "meta": {"author": "logic-tools", "repo": "axiom", "sha": "394be29d57fc4049b6c75f6eb9c85b15e30343ea", "save_path": "github-repos/isabelle/logic-tools-axiom", "path": "github-repos/isabelle/logic-tools-axiom/axiom-394be29d57fc4049b6c75f6eb9c85b15e30343ea/System_R.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7605452500312104}}
{"text": "(*\n  File:      HOL/Computational_Algebra/Squarefree.thy\n  Author:    Manuel Eberl <eberlm@in.tum.de>\n\n  Squarefreeness and decomposition of ring elements into square part and squarefree part\n*)\nsection \\<open>Squarefreeness\\<close>\ntheory Squarefree\nimports Primes\nbegin\n  \n(* TODO: Generalise to n-th powers *)\n\ndefinition squarefree :: \"'a :: comm_monoid_mult \\<Rightarrow> bool\" where\n  \"squarefree n \\<longleftrightarrow> (\\<forall>x. x ^ 2 dvd n \\<longrightarrow> x dvd 1)\"\n  \nlemma squarefreeI: \"(\\<And>x. x ^ 2 dvd n \\<Longrightarrow> x dvd 1) \\<Longrightarrow> squarefree n\"\n  by (auto simp: squarefree_def)\n\nlemma squarefreeD: \"squarefree n \\<Longrightarrow> x ^ 2 dvd n \\<Longrightarrow> x dvd 1\"\n  by (auto simp: squarefree_def)\n\nlemma not_squarefreeI: \"x ^ 2 dvd n \\<Longrightarrow> \\<not>x dvd 1 \\<Longrightarrow> \\<not>squarefree n\"\n  by (auto simp: squarefree_def)\n\nlemma not_squarefreeE [case_names square_dvd]: \n  \"\\<not>squarefree n \\<Longrightarrow> (\\<And>x. x ^ 2 dvd n \\<Longrightarrow> \\<not>x dvd 1 \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by (auto simp: squarefree_def)\n\nlemma not_squarefree_0 [simp]: \"\\<not>squarefree (0 :: 'a :: comm_semiring_1)\"\n  by (rule not_squarefreeI[of 0]) auto\n\nlemma squarefree_factorial_semiring:\n  assumes \"n \\<noteq> 0\"\n  shows   \"squarefree (n :: 'a :: factorial_semiring) \\<longleftrightarrow> (\\<forall>p. prime p \\<longrightarrow> \\<not>p ^ 2 dvd n)\"\n  unfolding squarefree_def\nproof safe\n  assume *: \"\\<forall>p. prime p \\<longrightarrow> \\<not>p ^ 2 dvd n\"\n  fix x :: 'a assume x: \"x ^ 2 dvd n\"\n  {\n    assume \"\\<not>is_unit x\"\n    moreover from assms and x have \"x \\<noteq> 0\" by auto\n    ultimately obtain p where \"p dvd x\" \"prime p\"\n      using prime_divisor_exists by blast\n    with * have \"\\<not>p ^ 2 dvd n\" by blast\n    moreover from \\<open>p dvd x\\<close> have \"p ^ 2 dvd x ^ 2\" by (rule dvd_power_same)\n    ultimately have \"\\<not>x ^ 2 dvd n\" by (blast dest: dvd_trans)\n    with x have False by contradiction\n  }\n  thus \"is_unit x\" by blast\nqed auto\n\nlemma squarefree_factorial_semiring':\n  assumes \"n \\<noteq> 0\"\n  shows   \"squarefree (n :: 'a :: factorial_semiring) \\<longleftrightarrow> \n             (\\<forall>p\\<in>prime_factors n. multiplicity p n = 1)\"\nproof (subst squarefree_factorial_semiring [OF assms], safe)\n  fix p assume \"\\<forall>p\\<in>#prime_factorization n. multiplicity p n = 1\" \"prime p\" \"p^2 dvd n\"\n  with assms show False\n    by (cases \"p dvd n\")\n       (auto simp: prime_factors_dvd power_dvd_iff_le_multiplicity not_dvd_imp_multiplicity_0)\nqed (auto intro!: multiplicity_eqI simp: power2_eq_square [symmetric])\n\nlemma squarefree_factorial_semiring'':\n  assumes \"n \\<noteq> 0\"\n  shows   \"squarefree (n :: 'a :: factorial_semiring) \\<longleftrightarrow> \n             (\\<forall>p. prime p \\<longrightarrow> multiplicity p n \\<le> 1)\"\n  by (subst squarefree_factorial_semiring'[OF assms]) (auto simp: prime_factors_multiplicity)\n\nlemma squarefree_unit [simp]: \"is_unit n \\<Longrightarrow> squarefree n\"\nproof (rule squarefreeI) \n  fix x assume \"x^2 dvd n\" \"n dvd 1\"\n  hence \"is_unit (x^2)\" by (rule dvd_unit_imp_unit)\n  thus \"is_unit x\" by (simp add: is_unit_power_iff)\nqed\n\nlemma squarefree_1 [simp]: \"squarefree (1 :: 'a :: algebraic_semidom)\"\n  by simp\n\nlemma squarefree_minus [simp]: \"squarefree (-n :: 'a :: comm_ring_1) \\<longleftrightarrow> squarefree n\"\n  by (simp add: squarefree_def)\n\nlemma squarefree_mono: \"a dvd b \\<Longrightarrow> squarefree b \\<Longrightarrow> squarefree a\"\n  by (auto simp: squarefree_def intro: dvd_trans)\n\nlemma squarefree_multD:\n  assumes \"squarefree (a * b)\"\n  shows   \"squarefree a\" \"squarefree b\"\n  by (rule squarefree_mono[OF _ assms], simp)+\n    \nlemma squarefree_prime_elem: \n  assumes \"prime_elem (p :: 'a :: factorial_semiring)\"\n  shows   \"squarefree p\"\nproof -\n  from assms have \"p \\<noteq> 0\" by auto\n  show ?thesis\n  proof (subst squarefree_factorial_semiring [OF \\<open>p \\<noteq> 0\\<close>]; safe)\n    fix q assume *: \"prime q\" \"q^2 dvd p\"\n    with assms have \"multiplicity q p \\<ge> 2\" by (intro multiplicity_geI) auto\n    thus False using assms \\<open>prime q\\<close> prime_multiplicity_other[of q \"normalize p\"]\n      by (cases \"q = normalize p\") simp_all\n  qed\nqed\n\nlemma squarefree_prime: \n  assumes \"prime (p :: 'a :: factorial_semiring)\"\n  shows   \"squarefree p\"\n  using assms by (intro squarefree_prime_elem) auto\n\nlemma squarefree_mult_coprime:\n  fixes a b :: \"'a :: factorial_semiring_gcd\"\n  assumes \"coprime a b\" \"squarefree a\" \"squarefree b\"\n  shows   \"squarefree (a * b)\"\nproof -\n  from assms have nz: \"a * b \\<noteq> 0\" by auto\n  show ?thesis unfolding squarefree_factorial_semiring'[OF nz]\n  proof\n    fix p assume p: \"p \\<in> prime_factors (a * b)\"\n    with nz have \"prime p\"\n      by (simp add: prime_factors_dvd)\n    have \"\\<not> (p dvd a \\<and> p dvd b)\"\n    proof\n      assume \"p dvd a \\<and> p dvd b\"\n      with \\<open>coprime a b\\<close> have \"is_unit p\"\n        by (auto intro: coprime_common_divisor)\n      with \\<open>prime p\\<close> show False\n        by simp\n    qed\n    moreover from p have \"p dvd a \\<or> p dvd b\" using nz \n      by (auto simp: prime_factors_dvd prime_dvd_mult_iff)\n    ultimately show \"multiplicity p (a * b) = 1\" using nz p assms(2,3)\n      by (auto simp: prime_elem_multiplicity_mult_distrib prime_factors_multiplicity\n            not_dvd_imp_multiplicity_0 squarefree_factorial_semiring')\n  qed\nqed\n\nlemma squarefree_prod_coprime:\n  fixes f :: \"'a \\<Rightarrow> 'b :: factorial_semiring_gcd\"\n  assumes \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> coprime (f a) (f b)\"\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> squarefree (f a)\"\n  shows   \"squarefree (prod f A)\"\n  using assms \n  by (induction A rule: infinite_finite_induct) \n     (auto intro!: squarefree_mult_coprime prod_coprime_right)\n\nlemma squarefree_powerD: \"m > 0 \\<Longrightarrow> squarefree (n ^ m) \\<Longrightarrow> squarefree n\"\n  by (cases m) (auto dest: squarefree_multD)\n\nlemma squarefree_power_iff: \n  \"squarefree (n ^ m) \\<longleftrightarrow> m = 0 \\<or> is_unit n \\<or> (squarefree n \\<and> m = 1)\"\nproof safe\n  assume \"squarefree (n ^ m)\" \"m > 0\" \"\\<not>is_unit n\"\n  show \"m = 1\"\n  proof (rule ccontr)\n    assume \"m \\<noteq> 1\"\n    with \\<open>m > 0\\<close> have \"n ^ 2 dvd n ^ m\" by (intro le_imp_power_dvd) auto\n    from this and \\<open>\\<not>is_unit n\\<close> have \"\\<not>squarefree (n ^ m)\" by (rule not_squarefreeI)\n    with \\<open>squarefree (n ^ m)\\<close> show False by contradiction\n  qed\nqed (auto simp: is_unit_power_iff dest: squarefree_powerD)\n\ndefinition squarefree_nat :: \"nat \\<Rightarrow> bool\" where\n  [code_abbrev]: \"squarefree_nat = squarefree\"\n  \nlemma squarefree_nat_code_naive [code]: \n  \"squarefree_nat n \\<longleftrightarrow> n \\<noteq> 0 \\<and> (\\<forall>k\\<in>{2..n}. \\<not>k ^ 2 dvd n)\"\nproof safe\n  assume *: \"\\<forall>k\\<in>{2..n}. \\<not> k\\<^sup>2 dvd n\" and n: \"n > 0\"\n  show \"squarefree_nat n\" unfolding squarefree_nat_def\n  proof (rule squarefreeI)\n    fix k assume k: \"k ^ 2 dvd n\"\n    have \"k dvd n\" by (rule dvd_trans[OF _ k]) auto\n    with n have \"k \\<le> n\" by (intro dvd_imp_le)\n    with bspec[OF *, of k] k have \"\\<not>k > 1\" by (intro notI) auto\n    moreover from k and n have \"k \\<noteq> 0\" by (intro notI) auto\n    ultimately have \"k = 1\" by presburger\n    thus \"is_unit k\" by simp\n  qed\nqed (auto simp: squarefree_nat_def squarefree_def intro!: Nat.gr0I)\n\n\n\ndefinition square_part :: \"'a :: factorial_semiring \\<Rightarrow> 'a\" where\n  \"square_part n = (if n = 0 then 0 else \n     normalize (\\<Prod>p\\<in>prime_factors n. p ^ (multiplicity p n div 2)))\"\n  \nlemma square_part_nonzero: \n  \"n \\<noteq> 0 \\<Longrightarrow> square_part n = normalize (\\<Prod>p\\<in>prime_factors n. p ^ (multiplicity p n div 2))\"\n  by (simp add: square_part_def)\n  \nlemma square_part_0 [simp]: \"square_part 0 = 0\"\n  by (simp add: square_part_def)\n\nlemma square_part_unit [simp]: \"is_unit x \\<Longrightarrow> square_part x = 1\"\n  by (auto simp: square_part_def prime_factorization_unit)\n\nlemma square_part_1 [simp]: \"square_part 1 = 1\"\n  by simp\n    \nlemma square_part_0_iff [simp]: \"square_part n = 0 \\<longleftrightarrow> n = 0\"\n  by (simp add: square_part_def)\n\nlemma normalize_uminus [simp]: \n  \"normalize (-x :: 'a :: {normalization_semidom, comm_ring_1}) = normalize x\"\n  by (rule associatedI) auto\n\nlemma multiplicity_uminus_right [simp]:\n  \"multiplicity (x :: 'a :: {factorial_semiring, comm_ring_1}) (-y) = multiplicity x y\"\nproof -\n  have \"multiplicity x (-y) = multiplicity x (normalize (-y))\"\n    by (rule multiplicity_normalize_right [symmetric])\n  also have \"\\<dots> = multiplicity x y\" by simp\n  finally show ?thesis .\nqed\n\nlemma multiplicity_uminus_left [simp]:\n  \"multiplicity (-x :: 'a :: {factorial_semiring, comm_ring_1}) y = multiplicity x y\"\nproof -\n  have \"multiplicity (-x) y = multiplicity (normalize (-x)) y\"\n    by (rule multiplicity_normalize_left [symmetric])\n  also have \"\\<dots> = multiplicity x y\" by simp\n  finally show ?thesis .\nqed\n\nlemma prime_factorization_uminus [simp]:\n  \"prime_factorization (-x :: 'a :: {factorial_semiring, comm_ring_1}) = prime_factorization x\"\n  by (rule prime_factorization_cong) simp_all\n\nlemma square_part_uminus [simp]: \n    \"square_part (-x :: 'a :: {factorial_semiring, comm_ring_1}) = square_part x\"\n  by (simp add: square_part_def)\n  \nlemma prime_multiplicity_square_part:\n  assumes \"prime p\"\n  shows   \"multiplicity p (square_part n) = multiplicity p n div 2\"\nproof (cases \"n = 0\")\n  case False\n  thus ?thesis unfolding square_part_nonzero[OF False] multiplicity_normalize_right\n    using finite_prime_divisors[of n] assms\n    by (subst multiplicity_prod_prime_powers)\n       (auto simp: not_dvd_imp_multiplicity_0 prime_factors_dvd multiplicity_prod_prime_powers)\nqed auto\n\nlemma square_part_square_dvd [simp, intro]: \"square_part n ^ 2 dvd n\"\nproof (cases \"n = 0\")\n  case False\n  thus ?thesis\n    by (intro multiplicity_le_imp_dvd) \n       (auto simp: prime_multiplicity_square_part prime_elem_multiplicity_power_distrib)\nqed auto\n  \nlemma prime_multiplicity_le_imp_dvd:\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"\n  shows   \"x dvd y \\<longleftrightarrow> (\\<forall>p. prime p \\<longrightarrow> multiplicity p x \\<le> multiplicity p y)\"\n  using assms by (auto intro: multiplicity_le_imp_dvd dvd_imp_multiplicity_le)\n\nlemma dvd_square_part_iff: \"x dvd square_part n \\<longleftrightarrow> x ^ 2 dvd n\"\nproof (cases \"x = 0\"; cases \"n = 0\")\n  assume nz: \"x \\<noteq> 0\" \"n \\<noteq> 0\"\n  thus ?thesis\n    by (subst (1 2) prime_multiplicity_le_imp_dvd)\n       (auto simp: prime_multiplicity_square_part prime_elem_multiplicity_power_distrib)\nqed auto\n\n\ndefinition squarefree_part :: \"'a :: factorial_semiring \\<Rightarrow> 'a\" where\n  \"squarefree_part n = (if n = 0 then 1 else n div square_part n ^ 2)\"\n\nlemma squarefree_part_0 [simp]: \"squarefree_part 0 = 1\"\n  by (simp add: squarefree_part_def)\n\nlemma squarefree_part_unit [simp]: \"is_unit n \\<Longrightarrow> squarefree_part n = n\"\n  by (auto simp add: squarefree_part_def)\n  \nlemma squarefree_part_1 [simp]: \"squarefree_part 1 = 1\"\n  by simp\n    \nlemma squarefree_decompose: \"n = squarefree_part n * square_part n ^ 2\"\n  by (simp add: squarefree_part_def)\n\nlemma squarefree_part_uminus [simp]: \n  assumes \"x \\<noteq> 0\"\n  shows   \"squarefree_part (-x :: 'a :: {factorial_semiring, comm_ring_1}) = -squarefree_part x\"\nproof -\n  have \"-(squarefree_part x * square_part x ^ 2) = -x\" \n    by (subst squarefree_decompose [symmetric]) auto\n  also have \"\\<dots> = squarefree_part (-x) * square_part (-x) ^ 2\" by (rule squarefree_decompose)\n  finally have \"(- squarefree_part x) * square_part x ^ 2 = \n                  squarefree_part (-x) * square_part x ^ 2\" by simp\n  thus ?thesis using assms by (subst (asm) mult_right_cancel) auto\nqed\n\nlemma squarefree_part_nonzero [simp]: \"squarefree_part n \\<noteq> 0\"\n  using squarefree_decompose[of n] by (cases \"n \\<noteq> 0\") auto    \n\nlemma prime_multiplicity_squarefree_part:\n  assumes \"prime p\"\n  shows   \"multiplicity p (squarefree_part n) = multiplicity p n mod 2\"\nproof (cases \"n = 0\")\n  case False\n  hence n: \"n \\<noteq> 0\" by auto\n  have \"multiplicity p n mod 2 + 2 * (multiplicity p n div 2) = multiplicity p n\" by simp\n  also have \"\\<dots> = multiplicity p (squarefree_part n * square_part n ^ 2)\"\n    by (subst squarefree_decompose[of n]) simp\n  also from assms n have \"\\<dots> = multiplicity p (squarefree_part n) + 2 * (multiplicity p n div 2)\"\n    by (subst prime_elem_multiplicity_mult_distrib) \n       (auto simp: prime_elem_multiplicity_power_distrib prime_multiplicity_square_part)\n  finally show ?thesis by (subst (asm) add_right_cancel) simp\nqed auto\n  \nlemma prime_multiplicity_squarefree_part_le_Suc_0 [intro]:\n  assumes \"prime p\"\n  shows   \"multiplicity p (squarefree_part n) \\<le> Suc 0\"\n  by (simp add: assms prime_multiplicity_squarefree_part)\n\nlemma squarefree_squarefree_part [simp, intro]: \"squarefree (squarefree_part n)\"\n  by (subst squarefree_factorial_semiring'')\n     (auto simp: prime_multiplicity_squarefree_part_le_Suc_0)\n  \nlemma squarefree_decomposition_unique:\n  assumes \"square_part m = square_part n\"\n  assumes \"squarefree_part m = squarefree_part n\"\n  shows   \"m = n\"\n  by (subst (1 2) squarefree_decompose) (simp_all add: assms)\n    \nlemma normalize_square_part [simp]: \"normalize (square_part x) = square_part x\"\n  by (simp add: square_part_def)\n\nlemma square_part_even_power': \"square_part (x ^ (2 * n)) = normalize (x ^ n)\"\nproof (cases \"x = 0\")\n  case False\n  have \"normalize (square_part (x ^ (2 * n))) = normalize (x ^ n)\" using False\n    by (intro multiplicity_eq_imp_eq)\n       (auto simp: prime_multiplicity_square_part prime_elem_multiplicity_power_distrib)\n  thus ?thesis by simp\nqed (auto simp: power_0_left)\n\nlemma square_part_even_power: \"even n \\<Longrightarrow> square_part (x ^ n) = normalize (x ^ (n div 2))\"\n  by (subst square_part_even_power' [symmetric]) auto\n\nlemma square_part_odd_power': \"square_part (x ^ (Suc (2 * n))) = normalize (x ^ n * square_part x)\"\nproof (cases \"x = 0\")\n  case False\n  have \"normalize (square_part (x ^ (Suc (2 * n)))) = normalize (square_part x * x ^ n)\" \n  proof (rule multiplicity_eq_imp_eq, goal_cases)\n    case (3 p)\n    hence \"multiplicity p (square_part (x ^ Suc (2 * n))) = \n             (2 * (n * multiplicity p x) + multiplicity p x) div 2\"\n      by (subst prime_multiplicity_square_part)\n         (auto simp: False prime_elem_multiplicity_power_distrib algebra_simps simp del: power_Suc)\n    also from 3 False have \"\\<dots> = multiplicity p (square_part x * x ^ n)\"\n      by (subst div_mult_self4) (auto simp: prime_multiplicity_square_part \n            prime_elem_multiplicity_mult_distrib prime_elem_multiplicity_power_distrib)\n    finally show ?case .\n  qed (insert False, auto)\n  thus ?thesis by (simp add: mult_ac)\nqed auto\n\nlemma square_part_odd_power: \n  \"odd n \\<Longrightarrow> square_part (x ^ n) = normalize (x ^ (n div 2) * square_part x)\"\n  by (subst square_part_odd_power' [symmetric]) auto\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Computational_Algebra/Squarefree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7604728180219164}}
{"text": "section \\<open>Combinatory Logic\\<close>\n\n(*:maxLineLen=78:*)\n\ntheory Combinators\n  imports \"../implication_logic\"\nbegin\n\nsubsection \\<open>Definitions\\<close>\n\ntext \\<open>Combinatory logic, following Curry (TODO: citeme), can be formulated as\n      follows.\\<close>\n\ndatatype Var = Var nat (\"\\<X>\")\n\ndatatype SKComb =\n    Var_Comb Var (\"\\<^bold>\\<langle>_\\<^bold>\\<rangle>\" [100] 100)\n  | S_Comb (\"S\")\n  | K_Comb (\"K\")\n  | Comb_App \"SKComb\" \"SKComb\"  (infixl \"\\<cdot>\" 75)\n\ntext \\<open> Note that in addition to \\<^term>\\<open>S\\<close> and \\<^term>\\<open>K\\<close> combinators,\n       \\<^typ>\\<open>SKComb\\<close> provides terms for \\<^emph>\\<open>variables\\<close>. This is helpful when\n       studying \\<open>\\<lambda>\\<close>-abstraction embedding.\\<close>\n\nsubsection \\<open>Typing\\<close>\n\n\ntext \\<open>The fragment of the \\<^typ>\\<open>SKComb\\<close> types without\n      \\<^term>\\<open>Var_Comb\\<close> terms can be given \\<^emph>\\<open>simple types\\<close>:\\<close>\n\ndatatype 'a Simple_Type =\n    Atom 'a  (\"\\<^bold>\\<lbrace> _ \\<^bold>\\<rbrace>\" [100] 100)\n  | To \"'a Simple_Type\" \"'a Simple_Type\" (infixr \"\\<^bold>\\<Rightarrow>\" 70)\n\ninductive\nSimply_Typed_SKComb\n   :: \"SKComb \\<Rightarrow> 'a Simple_Type \\<Rightarrow> bool\" (infix \"\\<Colon>\" 65)\nwhere\n    S_type : \"S \\<Colon> (\\<phi> \\<^bold>\\<Rightarrow> \\<psi> \\<^bold>\\<Rightarrow> \\<chi>) \\<^bold>\\<Rightarrow> (\\<phi> \\<^bold>\\<Rightarrow> \\<psi>) \\<^bold>\\<Rightarrow> \\<phi> \\<^bold>\\<Rightarrow> \\<chi>\"\n  | K_type : \"K \\<Colon> \\<phi> \\<^bold>\\<Rightarrow> \\<psi> \\<^bold>\\<Rightarrow> \\<phi>\"\n  | Application_type : \"E\\<^sub>1 \\<Colon> \\<phi> \\<^bold>\\<Rightarrow> \\<psi> \\<Longrightarrow> E\\<^sub>2 \\<Colon> \\<phi> \\<Longrightarrow> E\\<^sub>1 \\<cdot> E\\<^sub>2 \\<Colon> \\<psi>\"\n\nsubsection \\<open>Lambda Abstraction\\<close>\n\ntext \\<open>Here a simple embedding of the \\<open>\\<lambda>\\<close>-calculus into combinator logic is\n      presented.\\<close>\n\ntext \\<open>The SKI embedding below is originally due to David Turner\n      @{cite turnerAnotherAlgorithmBracket1979}.\\<close>\n\ntext \\<open>Abstraction over combinators where the abstracted variable is not free\n      are simplified using the \\<^term>\\<open>K\\<close> combinator.\\<close>\n\nprimrec free_variables_in_SKComb :: \"SKComb \\<Rightarrow> Var set\" (\"free\\<^sub>S\\<^sub>K\")\n  where\n    \"free\\<^sub>S\\<^sub>K (\\<^bold>\\<langle>x\\<^bold>\\<rangle>) = {x}\"\n  | \"free\\<^sub>S\\<^sub>K S = {}\"\n  | \"free\\<^sub>S\\<^sub>K K = {}\"\n  | \"free\\<^sub>S\\<^sub>K (E\\<^sub>1 \\<cdot> E\\<^sub>2) = (free\\<^sub>S\\<^sub>K E\\<^sub>1) \\<union> (free\\<^sub>S\\<^sub>K E\\<^sub>2)\"\n\nprimrec Turner_Abstraction\n  :: \"Var \\<Rightarrow> SKComb \\<Rightarrow> SKComb\" (\"\\<^bold>\\<lambda>_. _\" [90,90] 90)\n  where\n    abst_S: \"\\<^bold>\\<lambda>x. S = K \\<cdot> S\"\n  | abst_K: \"\\<^bold>\\<lambda>x. K = K \\<cdot> K\"\n  | abst_var: \"\\<^bold>\\<lambda>x. \\<^bold>\\<langle>y\\<^bold>\\<rangle> = (if x = y then S \\<cdot> K \\<cdot> K else K \\<cdot> \\<^bold>\\<langle>y\\<^bold>\\<rangle>)\"\n  | abst_app:\n     \"\\<^bold>\\<lambda> x. (E\\<^sub>1 \\<cdot> E\\<^sub>2) = (if (x \\<in> free\\<^sub>S\\<^sub>K (E\\<^sub>1 \\<cdot> E\\<^sub>2))\n                       then S \\<cdot> (\\<^bold>\\<lambda> x. E\\<^sub>1) \\<cdot> (\\<^bold>\\<lambda> x. E\\<^sub>2)\n                       else K \\<cdot> (E\\<^sub>1 \\<cdot> E\\<^sub>2))\"\n\nsubsection \\<open>Common Combinators\\<close>\n\ntext \\<open>This section presents various common combinators.  Some combinators are\n      simple enough to express in using \\<^term>\\<open>S\\<close> and \\<^term>\\<open>K\\<close>, however others\n      are more easily expressed using \\<open>\\<lambda>\\<close>-abstraction.\n      TODO: Cite Haskell Curry's PhD thesis.\\<close>\n\ntext \\<open>A useful lemma is the type of the \\<^emph>\\<open>identity\\<close> combinator, designated by\n      \\<^emph>\\<open>I\\<close> in the literature.\\<close>\n\nlemma Identity_type: \"S \\<cdot> K \\<cdot> K \\<Colon> \\<phi> \\<^bold>\\<Rightarrow> \\<phi>\"\n  using K_type S_type Application_type by blast\n\ntext \\<open>Another significant combinator is the \\<open>C\\<close> combinator, which\n      corresponds to \\<^verbatim>\\<open>flip\\<close> in Haskell.\\<close>\n\nlemma C_type:\n  \"\\<^bold>\\<lambda> \\<X> 1. \\<^bold>\\<lambda> \\<X> 2. \\<^bold>\\<lambda> \\<X> 3. (\\<^bold>\\<langle>\\<X> 1\\<^bold>\\<rangle> \\<cdot> \\<^bold>\\<langle>\\<X> 3\\<^bold>\\<rangle> \\<cdot> \\<^bold>\\<langle>\\<X> 2\\<^bold>\\<rangle>)\n       \\<Colon> (\\<phi> \\<^bold>\\<Rightarrow> \\<psi> \\<^bold>\\<Rightarrow> \\<chi>) \\<^bold>\\<Rightarrow> \\<psi> \\<^bold>\\<Rightarrow> \\<phi> \\<^bold>\\<Rightarrow> \\<chi>\"\n  by (simp, meson Identity_type Simply_Typed_SKComb.simps)\n\ntext \\<open>Haskell also has a function \\<^verbatim>\\<open>(.)\\<close>, which is referred to as the \\<^emph>\\<open>B\\<close>\n      combinator.\\<close>\n\nlemma B_type: \"S \\<cdot> (K \\<cdot> S) \\<cdot> K \\<Colon> (\\<psi> \\<^bold>\\<Rightarrow> \\<chi>) \\<^bold>\\<Rightarrow> (\\<phi> \\<^bold>\\<Rightarrow> \\<psi>) \\<^bold>\\<Rightarrow> \\<phi> \\<^bold>\\<Rightarrow> \\<chi>\"\n  by (meson Simply_Typed_SKComb.simps)\n\ntext \\<open>The final combinator given is the \\<^emph>\\<open>B\\<close> combinator.\\<close>\n\nlemma W_type:\n  \"\\<^bold>\\<lambda> \\<X> 1. \\<^bold>\\<lambda> \\<X> 2. (\\<^bold>\\<langle>\\<X> 1\\<^bold>\\<rangle> \\<cdot> \\<^bold>\\<langle>\\<X> 2\\<^bold>\\<rangle> \\<cdot> \\<^bold>\\<langle>\\<X> 2\\<^bold>\\<rangle>) \\<Colon> (\\<phi> \\<^bold>\\<Rightarrow> \\<phi> \\<^bold>\\<Rightarrow> \\<chi>) \\<^bold>\\<Rightarrow> \\<phi> \\<^bold>\\<Rightarrow> \\<chi>\"\n  by (simp, meson Identity_type Simply_Typed_SKComb.simps)\n\nsubsection \\<open> The Curry Howard Correspondence \\<close>\n\ntext \\<open> The (polymorphic) typing for a combinator \\<^term>\\<open>X\\<close> is given by the\n       relation \\<^term>\\<open>X \\<Colon> \\<phi>\\<close>. \\<close>\n\ntext \\<open> Combinator types form an instance of implicational intuitionistic logic. \\<close>\n\ninterpretation Combinator_implication_logic:\n  implication_logic \"\\<lambda> \\<phi>. \\<exists> X. X \\<Colon> \\<phi>\" \"(\\<^bold>\\<Rightarrow>)\"\nproof qed (meson Simply_Typed_SKComb.intros)+\n\ntext \\<open> The implicational intuitionistic logic generated by combinator logic is \\<^emph>\\<open>free\\<close> in the\n       following sense: If \\<^term>\\<open>X \\<Colon> \\<phi>\\<close> holds for some combinator \\<^term>\\<open>X\\<close>\n       then \\<^term>\\<open>\\<phi>\\<close> may be interpreted as logical consequence in any given\n       implicational intuitionistic logic instance. \\<close>\n\ntext \\<open> The fact that any valid type in combinator logic may be interpreted in\n       implicational intuitionistic logic is a form of the \\<^emph>\\<open>Curry-Howard correspondence\\<close>. TODO: Cite \\<close>\n\nprimrec (in implication_logic) Simple_Type_interpretation\n                           :: \"'a Simple_Type \\<Rightarrow> 'a\" (\"\\<^bold>\\<lparr> _ \\<^bold>\\<rparr>\" [50]) where\n     \"\\<^bold>\\<lparr> Atom p \\<^bold>\\<rparr> = p\"\n   | \"\\<^bold>\\<lparr> \\<phi> \\<^bold>\\<Rightarrow> \\<psi> \\<^bold>\\<rparr> = \\<^bold>\\<lparr> \\<phi> \\<^bold>\\<rparr> \\<rightarrow> \\<^bold>\\<lparr> \\<psi> \\<^bold>\\<rparr>\"\n\nlemma (in implication_logic) Curry_Howard_correspondence:\n  \"X \\<Colon> \\<phi> \\<Longrightarrow> \\<turnstile> \\<^bold>\\<lparr> \\<phi> \\<^bold>\\<rparr>\"\n  by (induct rule: Simply_Typed_SKComb.induct,\n      (simp add: axiom_k axiom_s modus_ponens)+)\n\nend\n", "meta": {"author": "xcthulhu", "repo": "DutchBook", "sha": "812f451bc89e11d7717280572775a54cea91b138", "save_path": "github-repos/isabelle/xcthulhu-DutchBook", "path": "github-repos/isabelle/xcthulhu-DutchBook/DutchBook-812f451bc89e11d7717280572775a54cea91b138/Logic/Intuitionistic/Implication/Combinators.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7604728033305022}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_nat_MSortBU2IsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(Nat list) list => (Nat list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(Nat list) list => Nat list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun risers :: \"Nat list => (Nat list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if le y y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun msortbu2 :: \"Nat list => Nat list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\nfun insert :: \"Nat => Nat list => Nat list\" where\n  \"insert x (nil2) = cons2 x (nil2)\"\n| \"insert x (cons2 z xs) =\n     (if le x z then cons2 x (cons2 z xs) else cons2 z (insert x xs))\"\n\nfun isort :: \"Nat list => Nat list\" where\n  \"isort (nil2) = nil2\"\n| \"isort (cons2 y xs) = insert y (isort xs)\"\n\ntheorem property0 :\n  \"((msortbu2 xs) = (isort xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_nat_MSortBU2IsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.8418256532040707, "lm_q1q2_score": 0.7604162355939452}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_TSortIsSort\nimports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Tree = TNode \"Tree\" \"Nat\" \"Tree\" | TNil\n\nfun le :: \"Nat => Nat => bool\" where\n\"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun insert :: \"Nat => Nat list => Nat list\" where\n\"insert x (nil2) = cons2 x (nil2)\"\n| \"insert x (cons2 z xs) =\n     (if le x z then cons2 x (cons2 z xs) else cons2 z (insert x xs))\"\n\nfun isort :: \"Nat list => Nat list\" where\n\"isort (nil2) = nil2\"\n| \"isort (cons2 y xs) = insert y (isort xs)\"\n\nfun flatten :: \"Tree => Nat list => Nat list\" where\n\"flatten (TNode q z r) y = flatten q (cons2 z (flatten r y))\"\n| \"flatten (TNil) y = y\"\n\nfun add :: \"Nat => Tree => Tree\" where\n\"add x (TNode q z r) =\n   (if le x z then TNode (add x q) z r else TNode q z (add x r))\"\n| \"add x (TNil) = TNode TNil x TNil\"\n\nfun toTree :: \"Nat list => Tree\" where\n\"toTree (nil2) = TNil\"\n| \"toTree (cons2 y xs) = add y (toTree xs)\"\n\nfun tsort :: \"Nat list => Nat list\" where\n\"tsort x = flatten (toTree x) (nil2)\"\n\ntheorem property0 :\n  \"((tsort xs) = (isort xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_TSortIsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.8311430520409023, "lm_q1q2_score": 0.760413577833568}}
{"text": "theory Inductive_Demo\nimports Main\nbegin\n\nsubsection \"Inductive definition of the even numbers\"\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nthm ev0 evSS\nthm ev.intros\n\ntext \\<open>Using the introduction rules:\\<close>\n\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\napply(rule evSS)\napply(rule evSS)\napply(rule ev0)\ndone\n\nthm evSS[OF evSS[OF ev0]]\n\ntext \\<open>A recursive definition of evenness:\\<close>\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\ntext \\<open>A simple example of rule induction:\\<close>\n\nlemma \"ev n \\<Longrightarrow> evn n\"\napply(induction rule: ev.induct)\n apply(simp)\napply(simp)\ndone\n\ntext \\<open>An induction on the computation of @{const evn}:\\<close>\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\n  apply (simp add: ev0)\n apply simp\napply(simp add: evSS)\ndone\n\ntext \\<open>No problem with termination\nbecause the premises are always smaller than the conclusion:\\<close>\n\ndeclare ev.intros[simp,intro]\n\ntext \\<open>A shorter proof:\\<close>\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\napply(simp_all)\ndone\n\ntext \\<open>The power of \"arith\":\\<close>\n\nlemma \"ev n \\<Longrightarrow> \\<exists>k. n = 2*k\"\napply(induction rule: ev.induct)\n apply(simp)\napply arith\ndone\n\n\nsubsection \"Inductive definition of the reflexive transitive closure\"\n\ninductive\n  star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nfor r where\nrefl:  \"star r x x\" |\nstep:  \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans:\n  \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\napply(induction rule: star.induct)\napply(assumption)\napply(rename_tac u x y)\napply(metis step)\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/Complete/Inductive_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7603877773193196}}
{"text": "theory Ex01\nimports Main\nbegin\n\n(* Exercise 1.1 *)\n                                  \nvalue \"2 + (2::nat)\"\nvalue \"(2::nat) * (5 + 3)\"\nvalue \"(3::nat) * 4 - 2 * (7 + 1)\"\n\n(* Exercise 1.2 *)\n\nlemma nat_add_comm: \"(a::nat) + b = b + a\"\n  by auto\n\nlemma nat_add_assoc: \n  fixes a b c :: nat \n  shows \"(a + b) + c = a + (b + c)\"\n  by auto\n\nlemma \n  fixes a b c :: nat \n  shows \"(a + b) + c = a + (c + b)\"\n  by auto\n\n(* Exercise 1.3 *)\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count []     e = 0\"\n| \"count (x#xs) e = (if x = e then 1 + count xs e else count xs e)\"\n\nvalue \"count [] 1\"\nvalue \"count [1::nat,2,4,5,2,3,1,3,4,1] 1\"\n\ntheorem \"count xs x \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n(* Exercise 1.4 *)\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc []     e = e # []\"\n| \"snoc (x#xs) e = x # snoc xs e\"\n\nvalue \"snoc [] 2\"\nvalue \"snoc [1,2,3] (4::int)\"\n\nlemma \"snoc [] e = [e]\"\n  by auto\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse []     = []\"\n| \"reverse (x#xs) = snoc (reverse xs) x\"\n\nvalue \"reverse []\"\nvalue \"reverse [1,2,4,5,3::int]\"\nvalue \"reverse [a,b,c]\"\n\nlemma \"reverse [a,b,c] = [c,b,a]\"\n  by auto\n\nlemma aux: \"reverse (snoc xs x) = (x # (reverse xs))\"\n  apply(induction xs)\n  apply(auto)\n  done\n\ntheorem \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n  apply(auto simp: aux)\n  done\n\n(* Homework 1.1 *)\n\nfun pow2 :: \"nat \\<Rightarrow> nat\" where\n  \"pow2 0       = 1\"\n| \"pow2 (Suc n) = 2 * pow2 n\"\n\nvalue \"pow2 3 = 8\"\n\n(* \n   Informal proof of \"pow2 (n + m) = pow2 n * pow2 m\"\n\n   We use induction over n.\n   Base case n=0:\n   pow2 (0 + m) = pow2 0 * pow2 m\n =  < 0 + m = m >\n   pow2 m = pow2 0 * pow2 m\n =  < pow2 0 = 1 >\n   pow2 m = 1 * pow2 m\n =  < 1 * m = m, in which [m:=pow2 m] >\n   pow2 m = pow2 m\n\n   Inductive case: \n   (IH): pow2 (n + m) = pow2 n * pow2 m\n\n   pow2 ((Suc n) + m) = pow2 (Suc n) * pow2 m\n =  < pow2 (Suc n) = 2 * pow2 n >\n   pow2 ((Suc n) + m) = (2 * pow2 n) * pow2 m >\n =  < (a*b)*c = a*(b*c), in which [a,b,c:=2,pow2 n, pow2 m] >\n   pow2 ((Suc n) + m) = 2 * (pow2 n * pow2 m)\n =  < Using Inductive Hypothesis >\n   pow2 ((Suc n) + m) = 2 * pow2 (n + m)\n =  < (Suc n) + m = Suc(n + m) >\n   pow2 (Suc(n + m)) = 2 * pow2 (n + m)\n =  < pow2 (Suc n() = 2 * pow2 n, in which [n:=n+m] >\n   2 * pow2 (n + m) = 2 * pow2 (n + m)\n\n*)\n\nlemma \"pow2 (n + m) = pow2 n * pow2 m\"\n  apply(induction n)\n  apply(auto)\n  done\n\n(* Homework 1.2 *)\n\nfun double :: \"'a list \\<Rightarrow> 'a list\" where\n  \"double []       = []\"\n| \"double (x # xs) = x # x # double xs\"\n\nvalue \"double []\"\nvalue \"double [a,b,c,d]\"\n\nlemma aux2: \"double(xs @ [x]) = double xs @ [x,x]\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nlemma rev_double: \"rev(double xs) = double(rev xs)\"\n  apply(induction xs)\n  apply(auto simp: aux2)\n  done\n\nend\n", "meta": {"author": "glimonta", "repo": "Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "save_path": "github-repos/isabelle/glimonta-Semantics", "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise1/Ex01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361509525462, "lm_q2_score": 0.8333245953120234, "lm_q1q2_score": 0.7603554862405908}}
{"text": "theory sumOfFirstN\n  imports Main\nbegin\n\ntheorem sum_of_first_n:\n  shows \"(∑i::nat = 0..n. i) = (n * (n + 1)) div 2\" (is \"?P n\")\nproof (induction n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc n)\n  thus ?case by simp\nqed\n\nend\n", "meta": {"author": "s-nandi", "repo": "automated-proofs", "sha": "719103028f53ded647e34fa88fff0383b09865e9", "save_path": "github-repos/isabelle/s-nandi-automated-proofs", "path": "github-repos/isabelle/s-nandi-automated-proofs/automated-proofs-719103028f53ded647e34fa88fff0383b09865e9/sumOfFirstN.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9353465098415279, "lm_q2_score": 0.8128673087708699, "lm_q1q2_score": 0.7603126002231088}}
{"text": "\ntheory Simplicial_complex\n  imports\n    Boolean_functions\nbegin\n\nsection\\<open>Simplicial Complexes\\<close>\n\nlemma Pow_singleton: \"Pow {a} = {{},{a}}\" by auto\n\nlemma Pow_pair: \"Pow {a,b} = {{},{a},{b},{a,b}}\" by auto\n\nlocale simplicial_complex\n  = fixes n::\"nat\"\nbegin\n\ntext\\<open>A simplex (in $n$ vertexes) is any set of vertexes,\n  including the empty set.\\<close>\n\ndefinition simplices :: \"nat set set\"\n  where \"simplices = Pow {0..<n}\"\n\nlemma \"{} \\<in> simplices\"\n  unfolding simplices_def by simp\n\nlemma \"{0..<n} \\<in> simplices\"\n  unfolding simplices_def by simp\n\n\n\ntext\\<open>A simplicial complex (in $n$ vertexes) is a collection of\n  sets of vertexes such that every subset of\n  a set of vertexes also belongs to the simplicial complex.\\<close>\n\ndefinition simplicial_complex :: \"nat set set => bool\"\n  where \"simplicial_complex K \\<equiv>  (\\<forall>\\<sigma>\\<in>K. (\\<sigma> \\<in> simplices) \\<and> (Pow \\<sigma>) \\<subseteq> K)\"\n\nlemma\n  finite_simplicial_complex:\n  assumes \"simplicial_complex K\"\n  shows \"finite K\"\n  by (metis assms finite_Pow_iff finite_atLeastLessThan rev_finite_subset simplices_def simplicial_complex_def subsetI)\n\nlemma finite_simplices:\n  assumes \"simplicial_complex K\"\n  and \"v \\<in> K\"\nshows \"finite v\"\n  using assms finite_simplex simplicial_complex.simplicial_complex_def by blast\n\n\ndefinition simplicial_complex_set :: \"nat set set set\"\n  where \"simplicial_complex_set = (Collect simplicial_complex)\"\n\nlemma simplicial_complex_empty_set:\n  fixes K::\"nat set set\"\n  assumes k: \"simplicial_complex K\"\n  shows \"K = {} \\<or> {} \\<in> K\" using k unfolding simplicial_complex_def Pow_def by auto\n\nlemma\n  simplicial_complex_monotone:\n  fixes K::\"nat set set\"\n  assumes k: \"simplicial_complex K\" and s: \"s \\<in> K\" and rs: \"r \\<subseteq> s\"\n  shows \"r \\<in> K\"\n  using k rs s\n  unfolding simplicial_complex_def Pow_def by auto\n\ntext\\<open>One example of simplicial complex with four simplices.\\<close>\n\nlemma\n  assumes three: \"(3::nat) < n\"\n  shows \"simplicial_complex {{},{0},{1},{2},{3}}\"\n  apply (simp_all add: Pow_singleton simplicial_complex_def simplices_def)\n  using Suc_lessD three by presburger\n\nlemma \"\\<not> simplicial_complex {{0,1},{1}}\"\n  by (simp add: Pow_pair simplicial_complex_def)\n\ntext\\<open>Another example of simplicial complex with five simplices.\\<close>\n\nlemma\n  assumes three: \"(3::nat) < n\"\n  shows \"simplicial_complex {{},{0},{1},{2},{3},{0,1}}\"\n  apply (simp add: Pow_pair Pow_singleton simplicial_complex_def simplices_def)\n  using Suc_lessD three by presburger\n\ntext\\<open>Another example of simplicial complex with ten simplices.\\<close>\n\nlemma\n  assumes three: \"(3::nat) < n\"\n  shows \"simplicial_complex\n    {{2,3},{1,3},{1,2},{0,3},{0,2},{3},{2},{1},{0},{}}\"\n  apply (simp add: Pow_pair Pow_singleton simplicial_complex_def simplices_def)\n  using Suc_lessD three by presburger\n\nend\n\nsection\\<open>Simplicial complex induced by a monotone Boolean function\\<close>\n\ntext\\<open>In this section we introduce the definition of the\n  simplicial complex induced by a monotone Boolean function,\n  following the definition in Scoville~\\<^cite>\\<open>\\<open>Def. 6.9\\<close> in \"SC19\"\\<close>.\\<close>\n\ntext\\<open>First we introduce the set of tuples for which\n  a Boolean function is @{term False}.\\<close>\n\ndefinition ceros_of_boolean_input :: \"bool vec => nat set\"\n  where \"ceros_of_boolean_input v = {x. x < dim_vec v \\<and> vec_index v x = False}\"\n\nlemma\n  ceros_of_boolean_input_l_dim:\n  assumes a: \"a \\<in> ceros_of_boolean_input v\"\n  shows \"a < dim_vec v\"\n  using a unfolding ceros_of_boolean_input_def by simp\n\nlemma \"ceros_of_boolean_input v = {x. x < dim_vec v \\<and> \\<not> vec_index v x}\"\n  unfolding ceros_of_boolean_input_def by simp\n\nlemma\n  ceros_of_boolean_input_complementary:\n  shows \"ceros_of_boolean_input v = {x. x < dim_vec v} - {x. vec_index v x}\"\n  unfolding ceros_of_boolean_input_def by auto\n\n(*lemma ceros_in_UNIV: \"ceros_of_boolean_input f \\<subseteq> (UNIV::nat set)\"\n  using subset_UNIV .*)\n\nlemma monotone_ceros_of_boolean_input:\n  fixes r and s::\"bool vec\"\n  assumes r_le_s: \"r \\<le> s\"\n  shows \"ceros_of_boolean_input s \\<subseteq> ceros_of_boolean_input r\"\nproof (intro subsetI, unfold ceros_of_boolean_input_def, intro CollectI, rule conjI)\n  fix x\n  assume \"x \\<in> {x. x < dim_vec s \\<and> vec_index s x = False}\"\n  hence xl: \"x < dim_vec s\" and nr: \"vec_index s x = False\" by simp_all\n  show \"vec_index r x = False\"\n    using r_le_s nr xl unfolding less_eq_vec_def\n    by auto\n  show \"x < dim_vec r\"\n  using r_le_s xl unfolding less_eq_vec_def\n    by auto\nqed\n\n\ntext\\<open>We introduce here instantiations of the typ\\<open>bool\\<close>\n  type for the type classes class\\<open>zero\\<close> and class\\<open>one\\<close>\n  that will simplify notation at some points:\\<close>\n\ninstantiation bool :: \"{zero,one}\"\nbegin\n\ndefinition\n zero_bool_def: \"0 == False\"\n\ndefinition\n one_bool_def: \"1 == True\"\n\ninstance  proof  qed\n\nend\n\ntext\\<open>Definition of the simplicial complex induced\n  by a Boolean function \\<open>f\\<close> in dimension \\<open>n\\<close>.\\<close>\n\ndefinition\n  simplicial_complex_induced_by_monotone_boolean_function\n    :: \"nat => (bool vec => bool) => nat set set\"\n  where \"simplicial_complex_induced_by_monotone_boolean_function n f =\n        {y. \\<exists>x. dim_vec x = n \\<and> f x \\<and> ceros_of_boolean_input x = y}\"\n\ntext\\<open>The simplicial complex induced by a Boolean function\n  is a subset of the powerset of the set of vertexes.\\<close>\n\nlemma\n  simplicial_complex_induced_by_monotone_boolean_function_subset:\n  \"simplicial_complex_induced_by_monotone_boolean_function n (v::bool vec => bool)\n    \\<subseteq> Pow (({0..n}::nat set))\"\n  using ceros_of_boolean_input_def\n   simplicial_complex_induced_by_monotone_boolean_function_def\n  by force\n\ncorollary\n  \"simplicial_complex_induced_by_monotone_boolean_function n (v::bool vec => bool)\n    \\<subseteq> Pow ((UNIV::nat set))\" by simp\n\ntext\\<open>The simplicial complex induced by a\n  monotone Boolean function is a simplicial complex.\n  This result is proven in Scoville as part of the\n  proof of Proposition 6.16~\\<^cite>\\<open>\\<open>Prop. 6.16\\<close> in \"SC19\"\\<close>.\\<close>\n\ncontext simplicial_complex\nbegin\n\nlemma\n  monotone_bool_fun_induces_simplicial_complex:\n  assumes mon: \"boolean_functions.monotone_bool_fun n f\"\n  shows \"simplicial_complex (simplicial_complex_induced_by_monotone_boolean_function n f)\"\n  unfolding simplicial_complex_def\nproof (rule, unfold simplicial_complex_induced_by_monotone_boolean_function_def, safe)\n    fix \\<sigma> :: \"nat set\" and x :: \"bool vec\"\n    assume fx: \"f x\" and dim_vec_x: \"n = dim_vec x\"\n    show \"ceros_of_boolean_input x \\<in> simplicial_complex.simplices (dim_vec x)\"\n      using ceros_of_boolean_input_def dim_vec_x simplices_def by force\n  next\n    fix \\<sigma> :: \"nat set\" and x :: \"bool vec\" and \\<tau> :: \"nat set\"\n    assume fx: \"f x\" and dim_vec_x: \"n = dim_vec x\" and tau_def: \"\\<tau> \\<subseteq> ceros_of_boolean_input x\"\n    show \"\\<exists>xb. dim_vec xb = dim_vec x \\<and> f xb \\<and> ceros_of_boolean_input xb = \\<tau>\"\n    proof (rule exI [of _ \"vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)\"], intro conjI)\n     show \"dim_vec (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)) = dim_vec x\"\n      unfolding dim_vec using dim_vec_x .\n     from mon have mono: \"mono_on (carrier_vec n) f\"\n      unfolding boolean_functions.monotone_bool_fun_def .\n     show \"f (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True))\"\n     proof -\n      have \"f x \\<le> f (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True))\"\n      proof (rule mono_onD [OF mono])\n        show \"x \\<in> carrier_vec n\" using dim_vec_x by simp\n        show \"vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True) \\<in> carrier_vec n\" by simp\n        show \"x \\<le> vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)\"\n          using tau_def dim_vec_x unfolding ceros_of_boolean_input_def\n          using less_eq_vec_def by fastforce\n      qed\n      thus ?thesis using fx by simp\n    qed\n    show \"ceros_of_boolean_input (vec n (\\<lambda>i. if i \\<in> \\<tau> then False else True)) = \\<tau>\"\n      using \\<open>\\<tau> \\<subseteq> ceros_of_boolean_input x\\<close> ceros_of_boolean_input_def dim_vec_x by auto\n  qed\nqed\n\nend\n\ntext\\<open>Example 6.10 in Scoville, the threshold function\n  for $2$ in dimension $4$ (with vertexes $0$,$1$,$2$,$3$)\\<close>\n\ndefinition bool_fun_threshold_2_3 :: \"bool vec => bool\"\n  where \"bool_fun_threshold_2_3 = (\\<lambda>v. if 2 \\<le> count_true v then True else False)\"\n\nlemma set_list_four: shows \"{0..<4} = set [0,1,2,3::nat]\" by auto\n\nlemma comp_fun_commute_lambda:\n  \"comp_fun_commute_on UNIV ((+)\n  \\<circ> (\\<lambda>i. if vec 4 f $ i then 1 else (0::nat)))\"\n  unfolding comp_fun_commute_on_def by auto\n\nlemma \"bool_fun_threshold_2_3\n          (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False)) = True\"\n  unfolding bool_fun_threshold_2_3_def\n  unfolding count_true_def\n  unfolding dim_vec\n  unfolding sum.eq_fold\n  using index_vec [of _ 4]\n  apply auto\n  unfolding set_list_four\n  unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n  by simp\n\nlemma\n  \"0 \\<notin> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"1 \\<notin> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"2 \\<in> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"3 \\<in> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  and \"{2,3} \\<subseteq> ceros_of_boolean_input (vec 4 (\\<lambda>i. if i = 0 \\<or> i = 1 then True else False))\"\n  unfolding ceros_of_boolean_input_def by simp_all\n\nlemma \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i = 3 then True else False)) = False\"\n  unfolding bool_fun_threshold_2_3_def\n  unfolding count_true_def\n  unfolding dim_vec\n  unfolding sum.eq_fold\n  using index_vec [of _ 4]\n  apply auto\n  unfolding set_list_four\n  unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n  by simp\n\nlemma \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i = 0 then False else True))\"\n  unfolding bool_fun_threshold_2_3_def\n  unfolding count_true_def\n  unfolding dim_vec\n  unfolding sum.eq_fold\n  using index_vec [of _ 4]\n  apply auto\n  unfolding set_list_four\n  unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n  by simp\n\nsection\\<open>The simplicial complex induced by the threshold function\\<close>\n\nlemma\n  empty_set_in_simplicial_complex_induced:\n  \"{} \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n  unfolding bool_fun_threshold_2_3_def\n  apply rule\n  apply (rule exI [of _ \"vec 4 (\\<lambda>x. True)\"])\n  unfolding count_true_def ceros_of_boolean_input_def by auto\n\nlemma singleton_in_simplicial_complex_induced:\n  assumes x: \"x < 4\"\n  shows \"{x} \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  (is \"?A \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\")\nproof (unfold simplicial_complex_induced_by_monotone_boolean_function_def, rule,\n      rule exI [of _ \"vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)\"],\n      intro conjI)\n  show \"dim_vec (vec 4 (\\<lambda>i. if i \\<in> {x} then False else True)) = 4\" by simp\n  show \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True))\"\n    unfolding bool_fun_threshold_2_3_def\n    unfolding count_true_def\n    unfolding dim_vec\n    unfolding sum.eq_fold\n    using index_vec [of _ 4]\n    apply auto\n    unfolding set_list_four\n    unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n    by simp\n  show \"ceros_of_boolean_input (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)) = ?A\"\n    unfolding ceros_of_boolean_input_def using x by auto\nqed\n\nlemma pair_in_simplicial_complex_induced:\n  assumes x: \"x < 4\" and y: \"y < 4\"\n  shows \"{x,y} \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  (is \"?A \\<in> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\")\nproof (unfold simplicial_complex_induced_by_monotone_boolean_function_def, rule,\n      rule exI [of _ \"vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)\"],\n      intro conjI)\n  show \"dim_vec (vec 4 (\\<lambda>i. if i \\<in> {x, y} then False else True)) = 4\" by simp\n  show \"bool_fun_threshold_2_3 (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True))\"\n    unfolding bool_fun_threshold_2_3_def\n    unfolding count_true_def\n    unfolding dim_vec\n    unfolding sum.eq_fold\n    using index_vec [of _ 4]\n    apply auto\n    unfolding set_list_four\n    unfolding comp_fun_commute_on.fold_set_fold_remdups [OF comp_fun_commute_lambda, simplified]\n    by simp\n  show \"ceros_of_boolean_input (vec 4 (\\<lambda>i. if i \\<in> ?A then False else True)) = ?A\"\n    unfolding ceros_of_boolean_input_def using x y by auto\nqed\n\nlemma finite_False: \"finite {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False}\" by auto\n\nlemma finite_True: \"finite {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True}\" by auto\n\nlemma UNIV_disjoint: \"{x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True}\n  \\<inter> {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False} = {}\"\n  by auto\n\nlemma UNIV_union: \"{x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True}\n  \\<union> {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False} = {x. x < dim_vec a}\"\n  by auto\n\nlemma card_UNIV_union:\n  \"card {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = True}\n  + card {x. x < dim_vec a \\<and> vec_index (a::bool vec) x = False}\n  = card {x. x < dim_vec a}\"\n  (is \"card ?true + card ?false = _\")\nproof -\n  have \"card ?true + card ?false = card (?true \\<union> ?false) + card (?true \\<inter> ?false)\"\n    using card_Un_Int [OF finite_True [of a] finite_False [of a]] .\n  also have \"... = card {x. x < dim_vec a}\"\n    unfolding UNIV_union UNIV_disjoint by simp\n  finally show ?thesis by simp\nqed\n\nlemma card_complementary:\n  \"card (ceros_of_boolean_input v)\n    + card {x. x < (dim_vec v) \\<and> (vec_index v x = True)} = (dim_vec v)\"\n  unfolding ceros_of_boolean_input_def\n  using card_UNIV_union [of v] by simp\n\ncorollary\n  card_ceros_of_boolean_input:\n  shows \"card (ceros_of_boolean_input a) \\<le> dim_vec a\"\n using card_complementary [of a] by simp\n\nlemma\n  vec_fun:\n  assumes \"v \\<in> carrier_vec n\"\n  shows \"\\<exists>f. v = vec n f\" using assms unfolding carrier_vec_def by fastforce\n\ncorollary\n  assumes \"dim_vec v = n\"\n  shows \"\\<exists>f. v = vec n f\"\n  using carrier_vecI [OF assms] unfolding carrier_vec_def by fastforce\n\nlemma\n  vec_l_eq:\n  assumes \"i < n\"\n  shows \"vec (Suc n) f $ i = vec n f $ i\"\n  by (simp add: assms less_SucI)\n\nlemma\n  card_boolean_function:\n  assumes d: \"v \\<in> carrier_vec n\"\n  shows \"card {x. x < n  \\<and> v $ x = True} = (\\<Sum>i = 0..<n. if v $ i then 1 else (0::nat))\"\nusing d proof (induction n arbitrary: v rule: nat_less_induct)\n  case (1 n)\n  assume hyp: \"\\<forall>m<n. \\<forall>x. x \\<in> carrier_vec m \\<longrightarrow>\n      card {xa. xa < m \\<and> x $ xa = True} = (\\<Sum>i = 0..<m. if x $ i then 1 else 0)\"\n    and d: \"v \\<in> carrier_vec n\"\n  show \"card {x. x < n \\<and> v $ x = True} = (\\<Sum>i = 0..<n. if v $ i then 1 else 0)\"\n  using d proof (cases n)\n    case 0\n    then show ?thesis by simp\n  next\n    case (Suc m)\n    assume v: \"v \\<in> carrier_vec n\"\n    obtain f :: \"nat => bool\" where v_f: \"v = vec n f\" using vec_fun [OF v] by auto\n    have \"card {x. x < m \\<and> (vec m f) $ x = True} = (\\<Sum>i = 0..<m. if (vec m f) $ i then 1 else 0)\"\n      using hyp v Suc by simp\n    show ?thesis unfolding v_f unfolding Suc\n    proof (cases \"vec (Suc m) f $ m = True\")\n      case True\n      have one: \"{x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n          ({x. x < m \\<and> vec (Suc m) f $ x = True} \\<union> {x. x = m \\<and> (vec (Suc m) f) $ x = True})\"\n        by auto\n      have two: \"disjnt {x. x < m \\<and> vec (Suc m) f $ x = True} {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        using disjnt_iff by blast\n      have \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True}\n            = card {x. x < m \\<and> (vec (Suc m) f) $ x = True} + card {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        unfolding one\n        by (rule card_Un_disjnt [OF _ _ two], simp_all)\n      also have \"... = card {x. x < m \\<and> (vec  m f) $ x = True} + 1\"\n      proof -\n        have one: \"{x. x < m \\<and> vec (Suc m) f $ x = True} = {x. x < m \\<and> vec m f $ x = True}\"\n          using vec_l_eq [of _ m] by auto\n        have eq: \"{x. x = m \\<and> vec (Suc m) f $ x = True} = {m}\" using True by auto\n        hence two: \"card {x. x = m \\<and> vec (Suc m) f $ x = True} = 1\" by simp\n        show ?thesis using one two by simp\n      qed\n      finally have lhs: \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} = card {x. x < m \\<and> vec m f $ x = True} + 1\" .\n      have \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) =\n           (\\<Sum>i = 0..<m. if vec (Suc m) f $ i then 1 else 0) + (if vec (Suc m) f $ m then 1 else 0)\"\n        by simp\n      also have \"... = (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0) + 1\"\n        using vec_l_eq [of _ m] True by simp\n      finally have rhs: \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) =\n        (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0) + 1\" .\n      show \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n        (\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0)\"\n        unfolding lhs rhs using hyp Suc by simp\n    next\n      case False\n      have one: \"{x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n          ({x. x < m \\<and> vec (Suc m) f $ x = True} \\<union> {x. x = m \\<and> (vec (Suc m) f) $ x = True})\"\n        by auto\n      have two: \"disjnt {x. x < m \\<and> vec (Suc m) f $ x = True} {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        using disjnt_iff by blast\n      have \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True}\n            = card {x. x < m \\<and> (vec (Suc m) f) $ x = True} + card {x. x = m \\<and> (vec (Suc m) f) $ x = True}\"\n        unfolding one\n        by (rule card_Un_disjnt [OF _ _ two], simp_all)\n      also have \"... = card {x. x < m \\<and> (vec  m f) $ x = True} + 0\"\n      proof -\n        have one: \"{x. x < m \\<and> vec (Suc m) f $ x = True} = {x. x < m \\<and> vec m f $ x = True}\"\n          using vec_l_eq [of _ m] by auto\n        have eq: \"{x. x = m \\<and> vec (Suc m) f $ x = True} = {}\" using False by auto\n        hence two: \"card {x. x = m \\<and> vec (Suc m) f $ x = True} = 0\" by simp\n        show ?thesis using one two by simp\n      qed\n      finally have lhs: \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} = card {x. x < m \\<and> vec m f $ x = True} + 0\" .\n      have \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) =\n           (\\<Sum>i = 0..<m. if vec (Suc m) f $ i then 1 else 0) + (if vec (Suc m) f $ m then 1 else 0)\"\n        by simp\n      also have \"... = (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0)\"\n        using vec_l_eq [of _ m] False by simp\n      finally have rhs: \"(\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0) =\n        (\\<Sum>i = 0..<m. if vec m f $ i then 1 else 0)\" .\n      show \"card {x. x < Suc m \\<and> vec (Suc m) f $ x = True} =\n        (\\<Sum>i = 0..<Suc m. if vec (Suc m) f $ i then 1 else 0)\"\n        unfolding lhs rhs using hyp Suc by simp\n    qed\n  qed\nqed\n\nlemma card_ceros_count_UNIV:\n  shows \"card (ceros_of_boolean_input a) + count_true ((a::bool vec)) = dim_vec a\"\n  using card_complementary [of a]\n  using card_boolean_function\n  unfolding ceros_of_boolean_input_def\n  unfolding count_true_def by simp\n\ntext\\<open>We calculate the carrier set of the @{const ceros_of_boolean_input}\n  function for dimensions $2$, $3$ and $4$.\\<close>\n\n\ntext\\<open>Vectors of dimension $2$.\\<close>\n\nlemma\n  dim_vec_2_cases:\n  assumes dx: \"dim_vec x = 2\"\n  shows \"(x $ 0 = x $ 1 = True) \\<or> (x $ 0 = False \\<and> x $ 1 = True)\n       \\<or> (x $ 0 = True \\<and> x $ 1 = False) \\<or> (x $ 0 = x $ 1 = False)\"\n  by auto\n\nlemma tt_2: assumes dx: \"dim_vec x = 2\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True\"\n  shows \"ceros_of_boolean_input x = {}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma tf_2: assumes dx: \"dim_vec x = 2\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False\"\n  shows \"ceros_of_boolean_input x = {1}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma ft_2: assumes dx: \"dim_vec x = 2\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True\"\n  shows \"ceros_of_boolean_input x = {0}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma ff_2: assumes dx: \"dim_vec x = 2\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False\"\n  shows \"ceros_of_boolean_input x = {0,1}\"\n  using dx be unfolding ceros_of_boolean_input_def using less_2_cases by auto\n\nlemma\n  assumes dx: \"dim_vec x = 2\"\n  shows \"ceros_of_boolean_input x \\<in> {{},{0},{1},{0,1}}\"\n  using dim_vec_2_cases [OF ]\n  using tt_2 [OF dx] tf_2 [OF dx] ft_2 [OF dx] ff_2 [OF dx]\n  by (metis insertCI)\n\ntext\\<open>Vectors of dimension $3$.\\<close>\n\nlemma less_3_cases:\n  assumes n: \"n < 3\" shows \"n = 0 \\<or> n = 1 \\<or> n = (2::nat)\"\n  using n by linarith\n\nlemma\n  dim_vec_3_cases:\n  assumes dx: \"dim_vec x = 3\"\n  shows \"(x $ 0 = x $ 1 = x $ 2 = False) \\<or> (x $ 0 = x $ 1 = False \\<and> x $ 2 = True)\n       \\<or> (x $ 0 = x $ 2 = False \\<and> x $ 1 = True) \\<or> (x $ 0 = False \\<and> x $ 1 = x $ 2 = True)\n       \\<or> (x $ 0 = True \\<and> x $ 1 = x $ 2 = False) \\<or> (x $ 0 = x $ 2 = True \\<and> x $ 1 = False)\n       \\<or> (x $ 0 = x $ 1 = True \\<and> x $ 2 = False) \\<or> (x $ 0 = x $ 1 = x $ 2 = True)\"\n  by auto\n\nlemma fff_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {0,1,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma fft_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {0,1}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma ftf_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {0,2}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by fastforce\n\nlemma ftt_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {0}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma tff_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {1,2}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma tft_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {1}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma ttf_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = False\"\n  shows \"ceros_of_boolean_input x = {2}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by fastforce\n\nlemma ttt_3: assumes dx: \"dim_vec x = 3\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = True\"\n  shows \"ceros_of_boolean_input x = {}\"\n  using dx be unfolding ceros_of_boolean_input_def\n  using less_3_cases by auto\n\nlemma\n  assumes dx: \"dim_vec x = 3\"\n  shows \"ceros_of_boolean_input x \\<in> {{},{0},{1},{2},{0,1},{0,2},{1,2},{0,1,2}}\"\n  using dim_vec_3_cases [OF ]\n  using fff_3 [OF dx] fft_3 [OF dx] ftf_3 [OF dx] ftt_3 [OF dx]\n  using tff_3 [OF dx] tft_3 [OF dx] ttf_3 [OF dx] ttt_3 [OF dx]\n  by (smt (z3) insertCI)\n\ntext\\<open>Vectors of dimension $4$.\\<close>\n\nlemma less_4_cases:\n  assumes n: \"n < 4\"\n  shows \"n = 0 \\<or> n = 1 \\<or> n = 2 \\<or> n = (3::nat)\"\n  using n by linarith\n\nlemma\n  dim_vec_4_cases:\n  assumes dx: \"dim_vec x = 4\"\n  shows \"(x $ 0 = x $ 1 = x $ 2 = x $ 3 = False) \\<or> (x $ 0 = x $ 1 = x $ 2 = False \\<and> x $ 3 = True)\n       \\<or> (x $ 0 = x $ 1 = x $ 3 = False \\<and> x $ 2 = True) \\<or> (x $ 0 = x $ 1 = False \\<and> x $ 2 = x $ 3 = True)\n       \\<or> (x $ 0 = x $ 2 = x $ 3 = False \\<and> x $ 1 = True) \\<or> (x $ 0 = x $ 2 = False \\<and> x $ 1 = x $ 3 = True)\n       \\<or> (x $ 0 = x $ 3 = False \\<and> x $ 1 = x $ 2 = True) \\<or> (x $ 0 = False \\<and> x $ 1 = x $ 2 = x $ 3 = True)\n       \\<or> (x $ 0 = True \\<and> x $ 1 = x $ 2 = x $ 3 = False) \\<or> (x $ 0 = x $ 3 = True \\<and> x $ 1 = x $ 2 = False)\n       \\<or> (x $ 0 = x $ 2 = True \\<and> x $ 1 = x $ 3 = False) \\<or> (x $ 0 = x $ 2 = x $ 3 = True \\<and> x $ 1 = False)\n       \\<or> (x $ 0 = x $ 1 = True \\<and> x $ 2 = x $ 3 = False) \\<or> (x $ 0 = x $ 1 = x $ 3 = True \\<and> x $ 2 = False)\n       \\<or> (x $ 0 = x $ 1 = x $ 2 = True \\<and> x $ 3 = False) \\<or> (x $ 0 = x $ 1 = x $ 2 = x $ 3 = True)\"\n  by blast\n\nlemma ffff_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,1,2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma ffft_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0,1,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma fftf_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,1,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma fftt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0,1}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma ftff_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma ftft_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma fttf_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {0,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma fttt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = False \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {0}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma tfff_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {1,2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma tfft_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {1,2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma tftf_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {1,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma tftt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = False \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {1}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma ttff_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {2,3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma ttft_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = False \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {2}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma tttf_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = False\"\n  shows \"ceros_of_boolean_input x = {3}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma tttt_4: assumes dx: \"dim_vec x = 4\"\n  and be: \"x $ 0 = True \\<and> x $ 1 = True \\<and> x $ 2 = True \\<and> x $ 3 = True\"\n  shows \"ceros_of_boolean_input x = {}\"\n  using dx be\n  unfolding ceros_of_boolean_input_def\n  using less_4_cases by auto\n\nlemma\n  ceros_of_boolean_input_set:\n  assumes dx: \"dim_vec x = 4\"\n  shows \"ceros_of_boolean_input x \\<in> {{},{0},{1},{2},{3},{0,1},{0,2},{0,3},{1,2},{1,3},{2,3},\n    {0,1,2},{0,1,3},{0,2,3},{1,2,3},{0,1,2,3}}\"\n  using dim_vec_4_cases [OF ]\n  using ffff_4 [OF dx] ffft_4 [OF dx] fftf_4 [OF dx] fftt_4 [OF dx]\n  using ftff_4 [OF dx] ftft_4 [OF dx] fttf_4 [OF dx] fttt_4 [OF dx]\n  using tfff_4 [OF dx] tfft_4 [OF dx] tftf_4 [OF dx] tftt_4 [OF dx]\n  using ttff_4 [OF dx] ttft_4 [OF dx] tttf_4 [OF dx] tttt_4 [OF dx]\n  by (smt (z3) insertCI)\n\ncontext simplicial_complex\nbegin\n\ntext\\<open>The simplicial complex induced by the monotone Boolean function\n  @{const bool_fun_threshold_2_3} has the following explicit expression.\\<close>\n\nlemma\n  simplicial_complex_induced_by_monotone_boolean_function_4_bool_fun_threshold_2_3:\n  shows \"{{},{0},{1},{2},{3},{0,1},{0,2},{0,3},{1,2},{1,3},{2,3}}\n    = simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n  (is \"{{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j} = _\")\nproof (rule)\n  show \"{{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\n    \\<subseteq> simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\"\n    by (simp add:\n        empty_set_in_simplicial_complex_induced\n        singleton_in_simplicial_complex_induced pair_in_simplicial_complex_induced)+\n  show \"simplicial_complex_induced_by_monotone_boolean_function 4 bool_fun_threshold_2_3\n    \\<subseteq> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n      unfolding simplicial_complex_induced_by_monotone_boolean_function_def\n      unfolding bool_fun_threshold_2_3_def\n    proof\n    fix y::\"nat set\"\n    assume y: \"y \\<in> {y. \\<exists>x. dim_vec x = 4 \\<and> (if 2 \\<le> count_true x then True else False) \\<and> ceros_of_boolean_input x = y}\"\n      then obtain x::\"bool vec\"\n        where ct_ge_2: \"(if 2 \\<le> count_true x then True else False)\"\n          and cx: \"ceros_of_boolean_input x = y\" and dx: \"dim_vec x = 4\" by auto\n      have \"count_true x + card (ceros_of_boolean_input x) = dim_vec x\"\n       using card_ceros_count_UNIV [of x] by simp\n      hence \"card (ceros_of_boolean_input x) \\<le> 2\"\n        using ct_ge_2\n        using card_boolean_function\n        using dx by presburger\n      hence card_le: \"card y \\<le> 2\" using cx by simp\n      have \"y \\<in> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n      proof (rule ccontr)\n        assume \"y \\<notin> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n        then have y_nin: \"y \\<notin> set [{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j]\" by simp\n        have \"y \\<in> set [{0,1,2},{0,1,3},{0,2,3},{1,2,3},{0,1,2,3}]\"\n          using ceros_of_boolean_input_set [OF dx] y_nin\n          unfolding cx by simp\n        hence \"card y \\<ge> 3\" by auto\n        thus False using card_le by simp\n      qed\n      then show \"y \\<in> {{},?a,?b,?c,?d,?e,?f,?g,?h,?i,?j}\"\n      by simp\n  qed\nqed\n\nend\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Simplicial_complexes_and_boolean_functions/Simplicial_complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942348544448, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7602336010215902}}
{"text": "theory Util\nimports Main\nbegin\n\nsection \\<open>Utility Lemmata\\<close>\n\nsubsection \\<open>Find\\<close>\n\nlemma find_result_props : \n  assumes \"find P xs = Some x\" \n  shows \"x \\<in> set xs\" and \"P x\"\nproof -\n  show \"x \\<in> set xs\" using assms by (metis find_Some_iff nth_mem)\n  show \"P x\" using assms by (metis find_Some_iff)\nqed\n\nlemma find_set : \n  assumes \"find P xs = Some x\"\n  shows \"x \\<in> set xs\"\nusing assms proof(induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  then show ?case\n    by (metis find.simps(2) list.set_intros(1) list.set_intros(2) option.inject) \nqed\n\nlemma find_condition : \n  assumes \"find P xs = Some x\"\n  shows \"P x\"\nusing assms proof(induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  then show ?case\n    by (metis find.simps(2) option.inject)     \nqed\n\nlemma find_from : \n  assumes \"\\<exists> x \\<in> set xs . P x\"\n  shows \"find P xs \\<noteq> None\"\n  by (metis assms find_None_iff)\n\n\nlemma find_sort_containment :\n  assumes \"find P (sort xs) = Some x\"\nshows \"x \\<in> set xs\"\n  using assms find_set by force\n\n\nlemma find_sort_index :\n  assumes \"find P xs = Some x\"\n  shows \"\\<exists> i < length xs . xs ! i = x \\<and> (\\<forall> j < i . \\<not> P (xs ! j))\"\nusing assms proof (induction xs arbitrary: x)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  show ?case proof (cases \"P a\")\n    case True\n    then show ?thesis \n      using Cons.prems unfolding find.simps by auto\n  next\n    case False\n    then have \"find P (a#xs) = find P xs\"\n      unfolding find.simps by auto\n    then have \"find P xs = Some x\"\n      using Cons.prems by auto\n    then show ?thesis \n      using Cons.IH False\n      by (metis Cons.prems find_Some_iff)  \n  qed\nqed\n\n\nlemma find_sort_least :\n  assumes \"find P (sort xs) = Some x\"\n  shows \"\\<forall> x' \\<in> set xs . x \\<le> x' \\<or> \\<not> P x'\"\n  and   \"x = (LEAST x' \\<in> set xs . P x')\"\nproof -\n  obtain i where \"i < length (sort xs)\" and \"(sort xs) ! i = x\" and \"(\\<forall> j < i . \\<not> P ((sort xs) ! j))\"\n    using find_sort_index[OF assms] by blast\n  \n  have \"\\<And> j . j > i \\<Longrightarrow> j < length xs \\<Longrightarrow> (sort xs) ! i \\<le> (sort xs) ! j\"\n    by (simp add: sorted_nth_mono)\n  then have \"\\<And> j . j < length xs \\<Longrightarrow> (sort xs) ! i \\<le> (sort xs) ! j \\<or> \\<not> P ((sort xs) ! j)\"\n    using \\<open>(\\<forall> j < i . \\<not> P ((sort xs) ! j))\\<close>\n    by (metis not_less_iff_gr_or_eq order_refl) \n  then show \"\\<forall> x' \\<in> set xs . x \\<le> x' \\<or> \\<not> P x'\"\n    by (metis \\<open>sort xs ! i = x\\<close> in_set_conv_nth length_sort set_sort)\n  then show \"x = (LEAST x' \\<in> set xs . P x')\"\n    using find_set[OF assms] find_condition[OF assms]\n    by (metis (mono_tags, lifting) Least_equality set_sort) \nqed\n\n\n\n\n\nsubsection \\<open>Enumerating Lists\\<close>\n\nfun lists_of_length :: \"'a list \\<Rightarrow> nat \\<Rightarrow> 'a list list\" where\n  \"lists_of_length T 0 = [[]]\" |\n  \"lists_of_length T (Suc n) = concat (map (\\<lambda> xs . map (\\<lambda> x . x#xs) T ) (lists_of_length T n))\" \n\nlemma lists_of_length_containment :\n  assumes \"set xs \\<subseteq> set T\"\n  and     \"length xs = n\"\nshows \"xs \\<in> set (lists_of_length T n)\"\nusing assms proof (induction xs arbitrary: n)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  then obtain k where \"n = Suc k\" \n    by auto\n  then have \"xs \\<in> set (lists_of_length T k)\" \n    using Cons by auto\n  moreover have \"a \\<in> set T\" \n    using Cons by auto\n  ultimately show ?case \n    using \\<open>n = Suc k\\<close> by auto\nqed\n\n\nlemma lists_of_length_length :\n  assumes \"xs \\<in> set (lists_of_length T n)\"\n  shows \"length xs = n\"\nproof -\n  have \"\\<forall> xs \\<in> set (lists_of_length T n) . length xs = n\"\n    by (induction n; simp)\n  then show ?thesis using assms by blast\nqed\n\nlemma lists_of_length_elems :\n  assumes \"xs \\<in> set (lists_of_length T n)\"\n  shows \"set xs \\<subseteq> set T\"\nproof -\n  have \"\\<forall> xs \\<in> set (lists_of_length T n) . set xs \\<subseteq> set T\"\n    by (induction n; simp)\n  then show ?thesis using assms by blast\nqed\n  \nlemma lists_of_length_list_set : \"set (lists_of_length xs k) = {xs' . length xs' = k \\<and> set xs' \\<subseteq> set xs}\"\n  using lists_of_length_containment[of _ xs k] lists_of_length_length[of _ xs k] lists_of_length_elems[of _ xs k] by blast\n    \n\nvalue \"lists_of_length [1,2,3::nat] 3\"\n\n\n\n\nfun cartesian_product_list :: \"'a list \\<Rightarrow> 'b list \\<Rightarrow> ('a \\<times> 'b) list\" where \n  \"cartesian_product_list xs ys = concat (map (\\<lambda> x . map (\\<lambda> y . (x,y)) ys) xs)\"\n\nvalue \"cartesian_product_list [1,2,3::nat] [10,20,30::nat]\"\n\nlemma cartesian_product_list_set : \"set (cartesian_product_list xs ys) = {(x,y) | x y . x \\<in> set xs \\<and> y \\<in> set ys}\"\n  by auto\n\n\n\nsubsection \\<open>Filter\\<close>\n\nlemma filter_double :\n  assumes \"x \\<in> set (filter P1 xs)\"\n  and     \"P2 x\"\nshows \"x \\<in> set (filter P2 (filter P1 xs))\"\n  by (metis (no_types) assms(1) assms(2) filter_set member_filter)\n\nlemma filter_list_set :\n  assumes \"x \\<in> set xs\"\n  and     \"P x\"\nshows \"x \\<in> set (filter P xs)\"\n  by (simp add: assms(1) assms(2))\n\nlemma filter_list_set_not_contained :\n  assumes \"x \\<in> set xs\"\n  and     \"\\<not> P x\"\nshows \"x \\<notin> set (filter P xs)\"\n  by (simp add: assms(1) assms(2))\n\n\nlemma filter_map_elem : \"t \\<in> set (map g (filter f xs)) \\<Longrightarrow> \\<exists> x \\<in> set xs . f x \\<and> t = g x\" by auto\n\n\nsubsection \\<open>Concat\\<close>\n\nlemma concat_map_elem :\n  assumes \"y \\<in> set (concat (map f xs))\"\n  obtains x where \"x \\<in> set xs\"\n              and \"y \\<in> set (f x)\"\nusing assms proof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  then show ?case \n  proof (cases \"y \\<in> set (f a)\")\n    case True\n    then show ?thesis \n      using Cons.prems(1) by auto\n  next\n    case False\n    then have \"y \\<in> set (concat (map f xs))\"\n      using Cons by auto\n    have \"\\<exists> x . x \\<in> set xs \\<and> y \\<in> set (f x)\"  \n    proof (rule ccontr)\n      assume \"\\<not>(\\<exists>x. x \\<in> set xs \\<and> y \\<in> set (f x))\"\n      then have \"\\<not>(y \\<in> set (concat (map f xs)))\"\n        by auto\n      then show False \n        using \\<open>y \\<in> set (concat (map f xs))\\<close> by auto\n    qed\n    then show ?thesis\n      using Cons.prems(1) by auto     \n  qed\nqed\n\nlemma set_concat_map_sublist :\n  assumes \"x \\<in> set (concat (map f xs))\"\n  and     \"set xs \\<subseteq> set xs'\"\nshows \"x \\<in> set (concat (map f xs'))\"\nusing assms by (induction xs) (auto)\n\nlemma set_concat_map_elem :\n  assumes \"x \\<in> set (concat (map f xs))\"\n  shows \"\\<exists> x' \\<in> set xs . x \\<in> set (f x')\"\nusing assms by auto\n\nlemma concat_replicate_length : \"length (concat (replicate n xs)) = n * (length xs)\"\n  by (induction n; simp)\n\n\nsubsection \\<open>Enumerating List Subsets\\<close>\n\nfun generate_selector_lists :: \"nat \\<Rightarrow> bool list list\" where\n  \"generate_selector_lists k = lists_of_length [False,True] k\"\n  \n\nvalue \"generate_selector_lists 4\"\n\nlemma generate_selector_lists_set : \"set (generate_selector_lists k) = {(bs :: bool list) . length bs = k}\"\n  using lists_of_length_list_set by auto \n\nlemma selector_list_index_set:\n  assumes \"length ms = length bs\"\n  shows \"set (map fst (filter snd (zip ms bs))) = { ms ! i | i . i < length bs \\<and> bs ! i}\"\nusing assms proof (induction bs arbitrary: ms rule: rev_induct)\n  case Nil\n  then show ?case by auto\nnext\n  case (snoc b bs)\n  let ?ms = \"butlast ms\"\n  let ?m = \"last ms\"\n\n  have \"length ?ms = length bs\" using snoc.prems by auto\n\n  have \"map fst (filter snd (zip ms (bs @ [b]))) = (map fst (filter snd (zip ?ms bs))) @ (map fst (filter snd (zip [?m] [b])))\"\n    by (metis \\<open>length (butlast ms) = length bs\\<close> append_eq_conv_conj filter_append length_0_conv map_append snoc.prems snoc_eq_iff_butlast zip_append2)\n  then have *: \"set (map fst (filter snd (zip ms (bs @ [b])))) = set (map fst (filter snd (zip ?ms bs))) \\<union> set (map fst (filter snd (zip [?m] [b])))\"\n    by simp\n    \n\n  have \"{ms ! i |i. i < length (bs @ [b]) \\<and> (bs @ [b]) ! i} = {ms ! i |i. i \\<le> (length bs) \\<and> (bs @ [b]) ! i}\"\n    by auto\n  moreover have \"{ms ! i |i. i \\<le> (length bs) \\<and> (bs @ [b]) ! i} = {ms ! i |i. i < length bs \\<and> (bs @ [b]) ! i} \\<union> {ms ! i |i. i = length bs \\<and> (bs @ [b]) ! i}\"\n    by fastforce\n  moreover have \"{ms ! i |i. i < length bs \\<and> (bs @ [b]) ! i} = {?ms ! i |i. i < length bs \\<and> bs ! i}\"\n    using \\<open>length ?ms = length bs\\<close> by (metis butlast_snoc nth_butlast)  \n  ultimately have **: \"{ms ! i |i. i < length (bs @ [b]) \\<and> (bs @ [b]) ! i} = {?ms ! i |i. i < length bs \\<and> bs ! i} \\<union> {ms ! i |i. i = length bs \\<and> (bs @ [b]) ! i}\"\n    by simp\n  \n\n  have \"set (map fst (filter snd (zip [?m] [b]))) = {ms ! i |i. i = length bs \\<and> (bs @ [b]) ! i}\"\n  proof (cases b)\n    case True\n    then have \"set (map fst (filter snd (zip [?m] [b]))) = {?m}\" by fastforce\n    moreover have \"{ms ! i |i. i = length bs \\<and> (bs @ [b]) ! i} = {?m}\" \n    proof -\n      have \"(bs @ [b]) ! length bs\"\n        by (simp add: True) \n      moreover have \"ms ! length bs = ?m\"\n        by (metis last_conv_nth length_0_conv length_butlast snoc.prems snoc_eq_iff_butlast) \n      ultimately show ?thesis by fastforce\n    qed\n    ultimately show ?thesis by auto\n  next\n    case False\n    then show ?thesis by auto\n  qed\n\n  then have \"set (map fst (filter snd (zip (butlast ms) bs))) \\<union> set (map fst (filter snd (zip [?m] [b])))\n             = {butlast ms ! i |i. i < length bs \\<and> bs ! i} \\<union> {ms ! i |i. i = length bs \\<and> (bs @ [b]) ! i}\"\n    using snoc.IH[OF \\<open>length ?ms = length bs\\<close>] by blast\n\n  then show ?case using * **\n    by simp \nqed\n\nlemma selector_list_ex :\n  assumes \"set xs \\<subseteq> set ms\"\n  shows \"\\<exists> bs . length bs = length ms \\<and> set xs = set (map fst (filter snd (zip ms bs)))\"\nusing assms proof (induction xs rule: rev_induct)\n  case Nil\n  let ?bs = \"replicate (length ms) False\"\n  have \"set [] = set (map fst (filter snd (zip ms ?bs)))\"\n    by (metis filter_False in_set_zip length_replicate list.simps(8) nth_replicate)\n  moreover have \"length ?bs = length ms\" by auto\n  ultimately show ?case by blast\nnext\n  case (snoc a xs)\n  then have \"set xs \\<subseteq> set ms\" and \"a \\<in> set ms\" by auto\n  then obtain bs where \"length bs = length ms\" and \"set xs = set (map fst (filter snd (zip ms bs)))\" using snoc.IH by auto\n\n  from \\<open>a \\<in> set ms\\<close> obtain i where \"i < length ms\" and \"ms ! i = a\"\n    by (meson in_set_conv_nth) \n\n  let ?bs = \"list_update bs i True\"\n  have \"length ms = length ?bs\" using \\<open>length bs = length ms\\<close> by auto\n  have \"length ?bs = length bs\" by auto\n\n  have \"set (map fst (filter snd (zip ms ?bs))) = {ms ! i |i. i < length ?bs \\<and> ?bs ! i}\"\n    using selector_list_index_set[OF \\<open>length ms = length ?bs\\<close>] by assumption\n\n  have \"\\<And> j . j < length ?bs \\<Longrightarrow> j \\<noteq> i \\<Longrightarrow> ?bs ! j = bs ! j\"\n    by auto\n  then have \"{ms ! j |j. j < length bs \\<and> j \\<noteq> i \\<and> bs ! j} = {ms ! j |j. j < length ?bs \\<and> j \\<noteq> i \\<and> ?bs ! j}\"\n    using \\<open>length ?bs = length bs\\<close> by fastforce\n  \n  \n  \n  have \"{ms ! j |j. j < length ?bs \\<and> j = i \\<and> ?bs ! j} = {a}\"\n    using \\<open>length bs = length ms\\<close> \\<open>i < length ms\\<close> \\<open>ms ! i = a\\<close> by auto\n  then have \"{ms ! i |i. i < length ?bs \\<and> ?bs ! i} = insert a {ms ! j |j. j < length ?bs \\<and> j \\<noteq> i \\<and> ?bs ! j}\"\n    by fastforce\n  \n\n  have \"{ms ! j |j. j < length bs \\<and> j = i \\<and> bs ! j} \\<subseteq> {ms ! j |j. j < length ?bs \\<and> j = i \\<and> ?bs ! j}\"\n    by (simp add: Collect_mono)\n  then have \"{ms ! j |j. j < length bs \\<and> j = i \\<and> bs ! j} \\<subseteq> {a}\"\n    using \\<open>{ms ! j |j. j < length ?bs \\<and> j = i \\<and> ?bs ! j} = {a}\\<close> by auto\n  moreover have \"{ms ! j |j. j < length bs \\<and> bs ! j} = {ms ! j |j. j < length bs \\<and> j = i \\<and> bs ! j} \\<union> {ms ! j |j. j < length bs \\<and> j \\<noteq> i \\<and> bs ! j}\"\n    by fastforce\n\n  ultimately have \"{ms ! i |i. i < length ?bs \\<and> ?bs ! i} = insert a {ms ! i |i. i < length bs \\<and> bs ! i}\"\n    using \\<open>{ms ! j |j. j < length bs \\<and> j \\<noteq> i \\<and> bs ! j} = {ms ! j |j. j < length ?bs \\<and> j \\<noteq> i \\<and> ?bs ! j}\\<close>\n    using \\<open>{ms ! ia |ia. ia < length (bs[i := True]) \\<and> bs[i := True] ! ia} = insert a {ms ! j |j. j < length (bs[i := True]) \\<and> j \\<noteq> i \\<and> bs[i := True] ! j}\\<close> by auto \n\n  moreover have \"set (map fst (filter snd (zip ms bs))) = {ms ! i |i. i < length bs \\<and> bs ! i}\"\n    using selector_list_index_set[of ms bs] \\<open>length bs = length ms\\<close> by auto\n\n  ultimately have \"set (a#xs) = set (map fst (filter snd (zip ms ?bs)))\"\n    using \\<open>set (map fst (filter snd (zip ms ?bs))) = {ms ! i |i. i < length ?bs \\<and> ?bs ! i}\\<close> \\<open>set xs = set (map fst (filter snd (zip ms bs)))\\<close> by auto\n  then show ?case\n    using \\<open>length ms = length ?bs\\<close>\n    by (metis Un_commute insert_def list.set(1) list.simps(15) set_append singleton_conv) \nqed\n\nsubsection \\<open>Enumerating Choices from Lists of Lists\\<close>\n\n\nfun generate_choices :: \"('a \\<times> ('b list)) list \\<Rightarrow> ('a \\<times> 'b option) list list\" where\n  \"generate_choices [] = [[]]\" |\n  \"generate_choices (xys#xyss) = concat (map (\\<lambda> xy' . map (\\<lambda> xys' . xy' # xys') (generate_choices xyss)) ((fst xys, None) # (map (\\<lambda> y . (fst xys, Some y)) (snd xys))))\"\n\nvalue \"generate_choices [(0::nat,[0::nat,1,2])]\"\nvalue \"generate_choices [(0::nat,[0::nat,1]),(1,[10,20])]\"\n\nlemma concat_map_hd_tl_elem: \n  assumes \"hd cs \\<in> set P1\"\n  and     \"tl cs \\<in> set P2\"\n  and     \"length cs > 0\"\nshows \"cs \\<in> set (concat (map (\\<lambda> xy' . map (\\<lambda> xys' . xy' # xys') P2) P1))\"\nproof -\n  have \"hd cs # tl cs = cs\" using assms(3) by auto\n  moreover have \"hd cs # tl cs \\<in> set (concat (map (\\<lambda> xy' . map (\\<lambda> xys' . xy' # xys') P2) P1))\" using assms(1,2) by auto\n  ultimately show ?thesis by auto\nqed\n\n\n\n\n\nlemma generate_choices_hd_tl : \"cs \\<in> set (generate_choices (xys#xyss)) = (length cs = length (xys#xyss) \\<and> fst (hd cs) = fst xys \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))) \\<and> (tl cs \\<in> set (generate_choices xyss)))\"\nproof (induction xyss arbitrary: cs xys)\n  case Nil\n  have \"(cs \\<in> set (generate_choices [xys])) = (cs \\<in> set ([(fst xys, None)] # map (\\<lambda>y. [(fst xys, Some y)]) (snd xys)))\" \n    unfolding generate_choices.simps by auto\n  moreover have \"(cs \\<in> set ([(fst xys, None)] # map (\\<lambda>y. [(fst xys, Some y)]) (snd xys))) \\<Longrightarrow> (length cs = length [xys] \\<and>\n     fst (hd cs) = fst xys \\<and>\n     (snd (hd cs) = None \\<or> snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)) \\<and>\n     tl cs \\<in> set (generate_choices []))\"\n    by auto\n  moreover have \"(length cs = length [xys] \\<and>\n     fst (hd cs) = fst xys \\<and>\n     (snd (hd cs) = None \\<or> snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)) \\<and>\n     tl cs \\<in> set (generate_choices [])) \\<Longrightarrow> (cs \\<in> set ([(fst xys, None)] # map (\\<lambda>y. [(fst xys, Some y)]) (snd xys)))\"\n    unfolding generate_choices.simps(1)\n  proof -\n    assume a1: \"length cs = length [xys] \\<and> fst (hd cs) = fst xys \\<and> (snd (hd cs) = None \\<or> snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)) \\<and> tl cs \\<in> set [[]]\"\n    have f2: \"\\<forall>ps. ps = [] \\<or> ps = (hd ps::'a \\<times> 'b option) # tl ps\"\n      by (meson list.exhaust_sel)\n    have f3: \"cs \\<noteq> []\"\n      using a1 by fastforce\n    have \"snd (hd cs) = None \\<longrightarrow> (fst xys, None) = hd cs\"\n      using a1 by (metis prod.exhaust_sel)\n    moreover\n    { assume \"hd cs # tl cs \\<noteq> [(fst xys, Some (the (snd (hd cs))))]\"\n      then have \"snd (hd cs) = None\"\n        using a1 by (metis (no_types) length_0_conv length_tl list.sel(3) option.collapse prod.exhaust_sel) }\n    ultimately have \"cs \\<in> insert [(fst xys, None)] ((\\<lambda>b. [(fst xys, Some b)]) ` set (snd xys))\"\n      using f3 f2 a1 by fastforce\n    then show ?thesis\n      by simp\n  qed \n  ultimately show ?case by blast\nnext\n  case (Cons a xyss)\n\n  have \"length cs = length (xys#a#xyss) \\<Longrightarrow> fst (hd cs) = fst xys \\<Longrightarrow> (snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys))) \\<Longrightarrow> (tl cs \\<in> set (generate_choices (a#xyss))) \\<Longrightarrow> cs \\<in> set (generate_choices (xys#a#xyss)) \"\n  proof -\n    assume \"length cs = length (xys#a#xyss)\" and \"fst (hd cs) = fst xys\" and \"(snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))\" and \"(tl cs \\<in> set (generate_choices (a#xyss)))\"\n    then have \"length cs > 0\" by auto\n\n    have \"(hd cs) \\<in> set ((fst xys, None) # (map (\\<lambda> y . (fst xys, Some y)) (snd xys)))\"\n      using \\<open>fst (hd cs) = fst xys\\<close> \\<open>(snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))\\<close>\n      by (metis (no_types, lifting) image_eqI list.set_intros(1) list.set_intros(2) option.collapse prod.collapse set_map)  \n    \n    show \"cs \\<in> set (generate_choices ((xys#(a#xyss))))\"\n      using generate_choices.simps(2)[of xys \"a#xyss\"] using concat_map_hd_tl_elem[OF \\<open>(hd cs) \\<in> set ((fst xys, None) # (map (\\<lambda> y . (fst xys, Some y)) (snd xys)))\\<close> \\<open>(tl cs \\<in> set (generate_choices (a#xyss)))\\<close> \\<open>length cs > 0\\<close>] by auto\n  qed\n\n  moreover have \"cs \\<in> set (generate_choices (xys#a#xyss)) \\<Longrightarrow> length cs = length (xys#a#xyss) \\<and> fst (hd cs) = fst xys \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))) \\<and> (tl cs \\<in> set (generate_choices (a#xyss)))\"\n  proof -\n    assume \"cs \\<in> set (generate_choices (xys#a#xyss))\"\n    then have p3: \"tl cs \\<in> set (generate_choices (a#xyss))\"\n      using generate_choices.simps(2)[of xys \"a#xyss\"] by fastforce\n    then have \"length (tl cs) = length (a # xyss)\" using Cons.IH[of \"tl cs\" \"a\"] by simp\n    then have p1: \"length cs = length (xys#a#xyss)\" by auto\n\n    have p2 : \"fst (hd cs) = fst xys \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys))))\"\n      using \\<open>cs \\<in> set (generate_choices (xys#a#xyss))\\<close> generate_choices.simps(2)[of xys \"a#xyss\"] by fastforce\n    \n    show ?thesis using p1 p2 p3 by simp\n  qed\n\n  ultimately show ?case by blast\nqed \n\nlemma list_append_idx_prop : \n  \"(\\<forall> i . (i < length xs \\<longrightarrow> P (xs ! i))) = (\\<forall> j . ((j < length (ys@xs) \\<and> j \\<ge> length ys) \\<longrightarrow> P ((ys@xs) ! j)))\"\nproof -\n  have \"\\<And> j . \\<forall>i<length xs. P (xs ! i) \\<Longrightarrow> j < length (ys @ xs) \\<Longrightarrow> length ys \\<le> j \\<longrightarrow> P ((ys @ xs) ! j)\"\n    by (simp add: nth_append)\n  moreover have \"\\<And> i . (\\<forall> j . ((j < length (ys@xs) \\<and> j \\<ge> length ys) \\<longrightarrow> P ((ys@xs) ! j))) \\<Longrightarrow> i < length xs \\<Longrightarrow> P (xs ! i)\"\n  proof -\n    fix i assume \"(\\<forall> j . ((j < length (ys@xs) \\<and> j \\<ge> length ys) \\<longrightarrow> P ((ys@xs) ! j)))\" and \"i < length xs\"\n    then have \"P ((ys@xs) ! (length ys + i))\"\n      by (metis add_strict_left_mono le_add1 length_append)\n    moreover have \"P (xs ! i) = P ((ys@xs) ! (length ys + i))\"\n      by simp\n    ultimately show \"P (xs ! i)\" by blast\n  qed\n  ultimately show ?thesis by blast\nqed\n\nlemma list_append_idx_prop2 : \n  assumes \"length xs' = length xs\"\n      and \"length ys' = length ys\"\n  shows \"(\\<forall> i . (i < length xs \\<longrightarrow> P (xs ! i) (xs' ! i))) = (\\<forall> j . ((j < length (ys@xs) \\<and> j \\<ge> length ys) \\<longrightarrow> P ((ys@xs) ! j) ((ys'@xs') ! j)))\"\nproof -\n\n  have \"\\<forall>i<length xs. P (xs ! i) (xs' ! i) \\<Longrightarrow>\n    \\<forall>j. j < length (ys @ xs) \\<and> length ys \\<le> j \\<longrightarrow> P ((ys @ xs) ! j) ((ys' @ xs') ! j)\"\n    using assms\n  proof -\n    assume a1: \"\\<forall>i<length xs. P (xs ! i) (xs' ! i)\"\n    { fix nn :: nat\n      have ff1: \"\\<forall>n na. (na::nat) + n - n = na\"\n        by simp\n      have ff2: \"\\<forall>n na. (na::nat) \\<le> n + na\"\n        by auto\n      then have ff3: \"\\<forall>as n. (ys' @ as) ! n = as ! (n - length ys) \\<or> \\<not> length ys \\<le> n\"\n        using ff1 by (metis (no_types) add.commute assms(2) eq_diff_iff nth_append_length_plus)\n      have ff4: \"\\<forall>n bs bsa. ((bsa @ bs) ! n::'b) = bs ! (n - length bsa) \\<or> \\<not> length bsa \\<le> n\"\n        using ff2 ff1 by (metis (no_types) add.commute eq_diff_iff nth_append_length_plus)\n      have \"\\<forall>n na nb. ((n::nat) + nb \\<le> na \\<or> \\<not> n \\<le> na - nb) \\<or> \\<not> nb \\<le> na\"\n        using ff2 ff1 by (metis le_diff_iff)\n      then have \"(\\<not> nn < length (ys @ xs) \\<or> \\<not> length ys \\<le> nn) \\<or> P ((ys @ xs) ! nn) ((ys' @ xs') ! nn)\"\n        using ff4 ff3 a1 by (metis add.commute length_append not_le) }\n    then show ?thesis\n      by blast\n  qed\n\n  moreover have \"(\\<forall>j. j < length (ys @ xs) \\<and> length ys \\<le> j \\<longrightarrow> P ((ys @ xs) ! j) ((ys' @ xs') ! j)) \\<Longrightarrow>\\<forall>i<length xs. P (xs ! i) (xs' ! i)\"\n    using assms\n    by (metis le_add1 length_append nat_add_left_cancel_less nth_append_length_plus) \n\n  ultimately show ?thesis by blast\nqed\n\nlemma generate_choices_idx : \"cs \\<in> set (generate_choices xyss) = (length cs = length xyss \\<and> (\\<forall> i < length cs . (fst (cs ! i)) = (fst (xyss ! i)) \\<and> ((snd (cs ! i)) = None \\<or> ((snd (cs ! i)) \\<noteq> None \\<and> the (snd (cs ! i)) \\<in> set (snd (xyss ! i))))))\"\nproof (induction xyss arbitrary: cs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons xys xyss)\n\n\n\n  have \"cs \\<in> set (generate_choices (xys#xyss)) = (length cs = length (xys#xyss) \\<and> fst (hd cs) = fst xys \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))) \\<and> (tl cs \\<in> set (generate_choices xyss)))\"\n    using generate_choices_hd_tl by metis\n\n  then have \"cs \\<in> set (generate_choices (xys#xyss)) \n    = (length cs = length (xys#xyss) \n      \\<and> fst (hd cs) = fst xys \n      \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))) \n      \\<and> (length (tl cs) = length xyss \\<and>\n        (\\<forall>i<length (tl cs).\n          fst (tl cs ! i) = fst (xyss ! i) \\<and>\n          (snd (tl cs ! i) = None \\<or> snd (tl cs ! i) \\<noteq> None \\<and> the (snd (tl cs ! i)) \\<in> set (snd (xyss ! i))))))\"\n    using Cons.IH[of \"tl cs\"] by blast\n  then have *: \"cs \\<in> set (generate_choices (xys#xyss)) \n    = (length cs = length (xys#xyss) \n      \\<and> fst (hd cs) = fst xys \n      \\<and> ((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys)))) \n      \\<and> (\\<forall>i<length (tl cs).\n          fst (tl cs ! i) = fst (xyss ! i) \\<and>\n          (snd (tl cs ! i) = None \\<or> snd (tl cs ! i) \\<noteq> None \\<and> the (snd (tl cs ! i)) \\<in> set (snd (xyss ! i)))))\"\n    by auto\n\n\n  have \"cs \\<in> set (generate_choices (xys#xyss)) \\<Longrightarrow> (length cs = length (xys # xyss) \\<and>\n                    (\\<forall>i<length cs.\n                        fst (cs ! i) = fst ((xys # xyss) ! i) \\<and>\n                        (snd (cs ! i) = None \\<or>\n                        snd (cs ! i) \\<noteq> None \\<and> the (snd (cs ! i)) \\<in> set (snd ((xys # xyss) ! i)))))\"\n  proof -\n    assume \"cs \\<in> set (generate_choices (xys#xyss))\"\n    then have p1: \"length cs = length (xys#xyss)\"\n          and p2: \"fst (hd cs) = fst xys \"\n          and p3: \"((snd (hd cs) = None \\<or> (snd (hd cs) \\<noteq> None \\<and> the (snd (hd cs)) \\<in> set (snd xys))))\"\n          and p4: \"(\\<forall>i<length (tl cs).\n                  fst (tl cs ! i) = fst (xyss ! i) \\<and>\n                  (snd (tl cs ! i) = None \\<or> snd (tl cs ! i) \\<noteq> None \\<and> the (snd (tl cs ! i)) \\<in> set (snd (xyss ! i))))\"\n      using * by blast+\n    then have \"length xyss = length (tl cs)\" and \"length (xys # xyss) = length ([hd cs] @ tl cs)\"\n      by auto\n    \n    have \"[hd cs]@(tl cs) = cs\"\n      by (metis (no_types) p1 append.left_neutral append_Cons length_greater_0_conv list.collapse list.simps(3)) \n    then have p4b: \"(\\<forall>i<length cs. i > 0 \\<longrightarrow>\n                    (fst (cs ! i) = fst ((xys#xyss) ! i) \\<and>\n                      (snd (cs ! i) = None \\<or> snd (cs ! i) \\<noteq> None \\<and> the (snd (cs ! i)) \\<in> set (snd ((xys#xyss) ! i)))))\"\n      using p4 list_append_idx_prop2[of xyss \"tl cs\" \"xys#xyss\" \"[hd cs]@(tl cs)\" \"\\<lambda> x y . fst x = fst y \\<and>\n                    (snd x = None \\<or> snd x \\<noteq> None \\<and> the (snd x) \\<in> set (snd y))\", OF \\<open>length xyss = length (tl cs)\\<close> \\<open>length (xys # xyss) = length ([hd cs] @ tl cs)\\<close>]\n      by (metis (no_types, lifting) One_nat_def Suc_pred \\<open>length (xys # xyss) = length ([hd cs] @ tl cs)\\<close> \\<open>length xyss = length (tl cs)\\<close> length_Cons list.size(3) not_less_eq nth_Cons_pos nth_append) \n\n    have p4a :\"(fst (cs ! 0) = fst ((xys#xyss) ! 0) \\<and> (snd (cs ! 0) = None \\<or> snd (cs ! 0) \\<noteq> None \\<and> the (snd (cs ! 0)) \\<in> set (snd ((xys#xyss) ! 0))))\"\n      using p1 p2 p3 by (metis hd_conv_nth length_greater_0_conv list.simps(3) nth_Cons_0)\n\n    show ?thesis using p1 p4a p4b by fastforce\n  qed\n\n\n  moreover have \"(length cs = length (xys # xyss) \\<and>\n                    (\\<forall>i<length cs.\n                        fst (cs ! i) = fst ((xys # xyss) ! i) \\<and>\n                        (snd (cs ! i) = None \\<or>\n                        snd (cs ! i) \\<noteq> None \\<and> the (snd (cs ! i)) \\<in> set (snd ((xys # xyss) ! i))))) \\<Longrightarrow> cs \\<in> set (generate_choices (xys#xyss))\"\n    using * \n    by (metis (no_types, lifting) Nitpick.size_list_simp(2) Suc_mono hd_conv_nth length_greater_0_conv length_tl list.sel(3) list.simps(3) nth_Cons_0 nth_tl) \n\n  ultimately show ?case by blast\nqed\n\n\nsubsection \\<open>Finding the Index of the First Element of a List Satisfying a Property\\<close>\n\n\nfun find_index :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat option\" where\n  \"find_index f []  = None\" |\n  \"find_index f (x#xs) = (if f x then Some 0 else (case find_index f xs of Some k \\<Rightarrow> Some (Suc k) | None \\<Rightarrow> None))\" \n\nlemma find_index_index :\n  assumes \"find_index f xs = Some k\"\n  shows \"k < length xs\" and \"f (xs ! k)\" and \"\\<And> j . j < k \\<Longrightarrow> \\<not> f (xs ! j)\"\nproof -\n  have \"(k < length xs) \\<and> (f (xs ! k)) \\<and> (\\<forall> j < k . \\<not> (f (xs ! j)))\"\n    using assms proof (induction xs arbitrary: k)\n    case Nil\n    then show ?case by auto\n  next\n    case (Cons x xs)\n    \n    show ?case proof (cases \"f x\")\n      case True\n      then show ?thesis using Cons.prems by auto\n    next\n      case False\n      then have \"find_index f (x#xs) = (case find_index f xs of Some k \\<Rightarrow> Some (Suc k) | None \\<Rightarrow> None)\"\n        by auto\n      then have \"(case find_index f xs of Some k \\<Rightarrow> Some (Suc k) | None \\<Rightarrow> None) = Some k\"\n        using Cons.prems by auto\n      then obtain k' where \"find_index f xs = Some k'\" and \"k = Suc k'\"\n        by (metis option.case_eq_if option.collapse option.distinct(1) option.sel)\n        \n      have \"k < length (x # xs) \\<and> f ((x # xs) ! k)\" using Cons.IH[OF \\<open>find_index f xs = Some k'\\<close>] using \\<open>k = Suc k'\\<close> by auto\n      moreover have \"(\\<forall>j<k. \\<not> f ((x # xs) ! j))\"\n        using Cons.IH[OF \\<open>find_index f xs = Some k'\\<close>] using \\<open>k = Suc k'\\<close> False\n        using less_Suc_eq_0_disj by auto \n      ultimately show ?thesis by presburger\n    qed\n  qed\n  then show \"k < length xs\" and \"f (xs ! k)\" and \"\\<And> j . j < k \\<Longrightarrow> \\<not> f (xs ! j)\" by simp+\nqed\n\nlemma find_index_exhaustive : \n  assumes \"\\<exists> x \\<in> set xs . f x\"\n  shows \"find_index f xs \\<noteq> None\"\n  using assms proof (induction xs)\ncase Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  then show ?case by (cases \"f x\"; auto)\nqed\n\n\n\nsubsection \\<open>List Distinctness from Sorting\\<close>\n\nlemma non_distinct_repetition_indices :\n  assumes \"\\<not> distinct xs\"\n  shows \"\\<exists> i j . i < j \\<and> j < length xs \\<and> xs ! i = xs ! j\"\n  by (metis assms distinct_conv_nth le_neq_implies_less not_le)\n\nlemma ordered_list_distinct :\n  fixes xs :: \"('a::preorder) list\"\n  assumes \"\\<And> i . Suc i < length xs \\<Longrightarrow> (xs ! i) < (xs ! (Suc i))\"\n  shows \"distinct xs\"\nproof -\n  have \"\\<And> i j . i < j \\<Longrightarrow> j < length xs \\<Longrightarrow> (xs ! i) < (xs ! j)\"\n  proof -\n    fix i j assume \"i < j\" and \"j < length xs\"\n    then show \"xs ! i < xs ! j\"\n      using assms proof (induction xs arbitrary: i j rule: rev_induct)\n      case Nil\n      then show ?case by auto\n    next\n      case (snoc a xs)\n      show ?case proof (cases \"j < length xs\")\n        case True\n        show ?thesis using snoc.IH[OF snoc.prems(1) True] snoc.prems(3)\n        proof -\n          have f1: \"i < length xs\"\n            using True less_trans snoc.prems(1) by blast\n          have f2: \"\\<forall>is isa n. if n < length is then (is @ isa) ! n = (is ! n::integer) else (is @ isa) ! n = isa ! (n - length is)\"\n            by (meson nth_append)\n          then have f3: \"(xs @ [a]) ! i = xs ! i\"\n            using f1\n            by (simp add: nth_append)\n          have \"xs ! i < xs ! j\"\n            using f2\n            by (metis Suc_lessD \\<open>(\\<And>i. Suc i < length xs \\<Longrightarrow> xs ! i < xs ! Suc i) \\<Longrightarrow> xs ! i < xs ! j\\<close> butlast_snoc length_append_singleton less_SucI nth_butlast snoc.prems(3)) \n          then show ?thesis\n            using f3 f2 True\n            by (simp add: nth_append) \n        qed\n      next\n        case False\n        then have \"(xs @ [a]) ! j = a\"\n          using snoc.prems(2)\n          by (metis length_append_singleton less_SucE nth_append_length)  \n        \n        consider \"j = 1\" | \"j > 1\"\n          using \\<open>i < j\\<close>\n          by linarith \n        then show ?thesis proof cases\n          case 1\n          then have \"i = 0\" and \"j = Suc i\" using \\<open>i < j\\<close> by linarith+ \n          then show ?thesis \n            using snoc.prems(3)\n            using snoc.prems(2) by blast \n        next\n          case 2\n          then consider \"i < j - 1\" | \"i = j - 1\" using \\<open>i < j\\<close> by linarith+\n          then show ?thesis proof cases\n            case 1\n            \n            have \"(\\<And>i. Suc i < length xs \\<Longrightarrow> xs ! i < xs ! Suc i) \\<Longrightarrow> xs ! i < xs ! (j - 1)\"\n              using snoc.IH[OF 1] snoc.prems(2) 2 by simp \n            then have le1: \"(xs @ [a]) ! i < (xs @ [a]) ! (j -1)\"\n              using snoc.prems(2)\n              by (metis \"2\" False One_nat_def Suc_diff_Suc Suc_lessD diff_zero length_append_singleton less_SucE not_less_eq nth_append snoc.prems(1) snoc.prems(3))\n            moreover have le2: \"(xs @ [a]) ! (j -1) < (xs @ [a]) ! j\"\n              using snoc.prems(2,3) 2\n              by (metis (full_types) One_nat_def Suc_diff_Suc diff_zero less_numeral_extra(1) less_trans)  \n            ultimately show ?thesis \n              using less_trans by blast\n          next\n            case 2\n            then have \"j = Suc i\" using \\<open>1 < j\\<close> by linarith\n            then show ?thesis \n              using snoc.prems(3)\n              using snoc.prems(2) by blast\n          qed\n        qed\n      qed\n    qed \n  qed\n\n  then show ?thesis\n    by (metis less_asym non_distinct_repetition_indices)\nqed\n\n\n\n\nlemma ordered_list_distinct_rev :\n  fixes xs :: \"('a::preorder) list\"\n  assumes \"\\<And> i . Suc i < length xs \\<Longrightarrow> (xs ! i) > (xs ! (Suc i))\"\n  shows \"distinct xs\"\nproof -\n  have \"\\<And> i . Suc i < length (rev xs) \\<Longrightarrow> ((rev xs) ! i) < ((rev xs) ! (Suc i))\"\n    using assms\n  proof -\n    fix i :: nat\n    assume a1: \"Suc i < length (rev xs)\"\n    obtain nn :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n      \"\\<forall>x0 x1. (\\<exists>v2. x1 = Suc v2 \\<and> v2 < x0) = (x1 = Suc (nn x0 x1) \\<and> nn x0 x1 < x0)\"\n      by moura\n    then have f2: \"\\<forall>n na. (\\<not> n < Suc na \\<or> n = 0 \\<or> n = Suc (nn na n) \\<and> nn na n < na) \\<and> (n < Suc na \\<or> n \\<noteq> 0 \\<and> (\\<forall>nb. n \\<noteq> Suc nb \\<or> \\<not> nb < na))\"\n      by (meson less_Suc_eq_0_disj)\n    have f3: \"Suc (length xs - Suc (Suc i)) = length (rev xs) - Suc i\"\n      using a1 by (simp add: Suc_diff_Suc)\n    have \"i < length (rev xs)\"\n      using a1 by (meson Suc_lessD)\n    then have \"i < length xs\"\n      by simp\n    then show \"rev xs ! i < rev xs ! Suc i\"\n      using f3 f2 a1 by (metis (no_types) assms diff_less length_rev not_less_iff_gr_or_eq rev_nth)\n  qed \n  then have \"distinct (rev xs)\" \n    using ordered_list_distinct[of \"rev xs\"] by blast\n  then show ?thesis by auto\nqed\n\n\nsubsection \\<open>Calculating Prefixes and Suffixes\\<close>\n\nfun suffixes :: \"'a list \\<Rightarrow> 'a list list\" where\n  \"suffixes [] = [[]]\" |\n  \"suffixes (x#xs) = (suffixes xs) @ [x#xs]\"\n\nlemma suffixes_set : \n  \"set (suffixes xs) = {zs . \\<exists> ys . ys@zs = xs}\"\nproof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n  then have *: \"set (suffixes (x#xs)) = {zs . \\<exists> ys . ys@zs = xs} \\<union> {x#xs}\"\n    by auto\n  \n  have \"{zs . \\<exists> ys . ys@zs = xs} = {zs . \\<exists> ys . x#ys@zs = x#xs}\"\n    by force\n  then have \"{zs . \\<exists> ys . ys@zs = xs} = {zs . \\<exists> ys . ys@zs = x#xs \\<and> ys \\<noteq> []}\"\n    by (metis Cons_eq_append_conv list.distinct(1))\n  moreover have \"{x#xs} = {zs . \\<exists> ys . ys@zs = x#xs \\<and> ys = []}\"\n    by force\n    \n  ultimately show ?case using * by force\nqed\n\n(* old definition\nfun prefixes :: \"'a list \\<Rightarrow> 'a list list\" where\n  \"prefixes [] = [[]]\" |\n  \"prefixes (x#xs) = [] # (map (\\<lambda> xs' . x#xs') (prefixes xs))\"\n*)\nfun prefixes :: \"'a list \\<Rightarrow> 'a list list\" where\n  \"prefixes [] = [[]]\" |\n  \"prefixes xs = (prefixes (butlast xs)) @ [xs]\"\n\n\n\nvalue \"prefixes [1::nat,2,3,4]\"\n\nlemma prefixes_set : \"set (prefixes xs) = {xs' . \\<exists> xs'' . xs'@xs'' = xs}\"\nproof (induction xs rule: rev_induct)\n  case Nil\n  then show ?case by auto\nnext\n  case (snoc x xs)\n  moreover have \"prefixes (xs@[x]) = (prefixes xs) @ [xs@[x]]\"\n    by (metis prefixes.elims snoc_eq_iff_butlast)\n  ultimately have *: \"set (prefixes (xs@[x])) = {xs'. \\<exists>xs''. xs' @ xs'' = xs} \\<union> {xs@[x]}\"\n    by auto\n  \n  have \"{xs'. \\<exists>xs''. xs' @ xs'' = xs} = {xs'. \\<exists>xs''. xs' @ xs'' @ [x] = xs @[x]}\"\n    by force\n  then have \"{xs'. \\<exists>xs''. xs' @ xs'' = xs} = {xs'. \\<exists>xs''. xs' @ xs'' = xs@[x] \\<and> xs'' \\<noteq> []}\"\n    by (metis (no_types, hide_lams) append.assoc snoc_eq_iff_butlast)\n  moreover have \"{xs@[x]} = {xs'. \\<exists>xs''. xs' @ xs'' = xs@[x] \\<and> xs'' = []}\"\n    by auto\n  ultimately show ?case \n    using * by force\nqed\n\n  \n\n\n\nfun add_prefixes :: \"'a list list \\<Rightarrow> 'a list list\" where\n  \"add_prefixes xs = concat (map prefixes xs)\"\n\nvalue \"add_prefixes [[1::nat,2,3], [], [10,100,1000,1000]]\"\n\nlemma add_prefixes_set : \"set (add_prefixes xs) = {xs' . \\<exists> xs'' . xs'@xs'' \\<in> set xs}\"\nproof -\n  have \"set (add_prefixes xs) = {xs' . \\<exists> x \\<in> set xs . xs' \\<in> set (prefixes x)}\"\n    unfolding add_prefixes.simps by auto\n  also have \"\\<dots> = {xs' . \\<exists> xs'' . xs'@xs'' \\<in> set xs}\"\n  proof (induction xs)\n    case Nil\n    then show ?case using prefixes_set by auto\n  next\n    case (Cons a xs)\n    then show ?case \n    proof -\n      have \"\\<And> xs' . xs' \\<in> {xs'. \\<exists>x\\<in>set (a # xs). xs' \\<in> set (prefixes x)} \\<longleftrightarrow> xs' \\<in> {xs'. \\<exists>xs''. xs' @ xs'' \\<in> set (a # xs)}\"\n      proof -\n        fix xs' \n        show \"xs' \\<in> {xs'. \\<exists>x\\<in>set (a # xs). xs' \\<in> set (prefixes x)} \\<longleftrightarrow> xs' \\<in> {xs'. \\<exists>xs''. xs' @ xs'' \\<in> set (a # xs)}\"\n          using prefixes_set by (cases \"xs' \\<in> set (prefixes a)\"; auto)\n      qed\n      then show ?thesis by blast\n    qed\n  qed\n  finally show ?thesis by blast\nqed\n\n\n\n\n\nsubsection \\<open>Set-Operations on Lists\\<close>\n\n(* TODO: use selector_lists instead? *)\nfun pow_list :: \"'a list \\<Rightarrow> 'a list list\" where\n  \"pow_list [] = [[]]\" |\n  \"pow_list (x#xs) = (let pxs = pow_list xs in pxs @ map (\\<lambda> ys . x#ys) pxs)\"\n\nvalue \"pow_list [1,2,3::nat]\"\n\n\nlemma pow_list_set :\n  \"set (map set (pow_list xs)) = Pow (set xs)\"\nproof (induction xs)\ncase Nil\n  then show ?case by auto\nnext\n  case (Cons x xs)\n\n  moreover have \"Pow (set (x # xs)) = Pow (set xs) \\<union> (image (insert x) (Pow (set xs)))\"\n    by (simp add: Pow_insert)\n    \n  moreover have \"set (map set (pow_list (x#xs))) =  set (map set (pow_list xs)) \\<union> (image (insert x) (set (map set (pow_list xs))))\"\n  proof -\n    have \"\\<And> ys . ys \\<in> set (map set (pow_list (x#xs))) \\<Longrightarrow> ys \\<in> set (map set (pow_list xs)) \\<union> (image (insert x) (set (map set (pow_list xs))))\" \n    proof -\n      fix ys assume \"ys \\<in> set (map set (pow_list (x#xs)))\"\n      then consider (a) \"ys \\<in> set (map set (pow_list xs))\" |\n                    (b) \"ys \\<in> set (map set (map ((#) x) (pow_list xs)))\"\n        unfolding pow_list.simps Let_def by auto\n      then show \"ys \\<in> set (map set (pow_list xs)) \\<union> (image (insert x) (set (map set (pow_list xs))))\" \n        by (cases; auto)\n    qed\n    moreover have \"\\<And> ys . ys \\<in> set (map set (pow_list xs)) \\<union> (image (insert x) (set (map set (pow_list xs)))) \\<Longrightarrow> ys \\<in> set (map set (pow_list (x#xs)))\"\n    proof -\n      fix ys assume \"ys \\<in> set (map set (pow_list xs)) \\<union> (image (insert x) (set (map set (pow_list xs))))\"\n      then consider (a) \"ys \\<in> set (map set (pow_list xs))\" |\n                    (b) \"ys \\<in> (image (insert x) (set (map set (pow_list xs))))\"\n        by blast\n      then show \"ys \\<in> set (map set (pow_list (x#xs)))\" \n        unfolding pow_list.simps Let_def by (cases; auto)\n    qed\n    ultimately show ?thesis by blast\n  qed\n    \n  ultimately show ?case\n    by auto \nqed\n\n\nfun inter_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"inter_list xs ys = filter (\\<lambda> x . x \\<in> set ys) xs\"\n\nlemma inter_list_set : \"set (inter_list xs ys) = (set xs) \\<inter> (set ys)\"\n  by auto\n\nfun subset_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"subset_list xs ys = list_all (\\<lambda> x . x \\<in> set ys) xs\"\n\nlemma subset_list_set : \"subset_list xs ys = ((set xs) \\<subseteq> (set ys))\" \n  unfolding subset_list.simps\n  by (simp add: Ball_set subset_code(1)) \n\n\n\nsubsection \\<open>Calculating Distinct Non-Reflexive Pairs over List Elements\\<close> \n\n(* Could be used to calculate tuples ((q1,q2),A), where A is a separator for q1 q2, such that\n   ((q2,q1),_) is skipped *)\n\nfun non_sym_dist_pairs' :: \"'a list \\<Rightarrow> ('a \\<times> 'a) list\" where\n  \"non_sym_dist_pairs' [] = []\" |\n  \"non_sym_dist_pairs' (x#xs) = (map (\\<lambda> y. (x,y)) xs) @ non_sym_dist_pairs' xs\"\n\nfun non_sym_dist_pairs :: \"'a list \\<Rightarrow> ('a \\<times> 'a) list\" where\n  \"non_sym_dist_pairs xs = non_sym_dist_pairs' (remdups xs)\"\n\nvalue \"non_sym_dist_pairs' [1,2,3::nat]\"\nvalue \"non_sym_dist_pairs' [1,2,1,3::nat]\"\nvalue \"non_sym_dist_pairs [1,2,1,3::nat]\"\n\nlemma non_sym_dist_pairs_subset : \"set (non_sym_dist_pairs xs) \\<subseteq> (set xs) \\<times> (set xs)\"\n  by (induction xs; auto)\n\nlemma non_sym_dist_pairs'_elems_distinct:\n  assumes \"distinct xs\"\n  and     \"(x,y) \\<in> set (non_sym_dist_pairs' xs)\"\nshows \"x \\<in> set xs\" \nand   \"y \\<in> set xs\"\nand   \"x \\<noteq> y\"\nproof -\n  show \"x \\<in> set xs\" and \"y \\<in> set xs\"\n    using non_sym_dist_pairs_subset assms(2) by (induction xs; auto)+\n  show \"x \\<noteq> y\"\n    using assms by (induction xs; auto)\nqed\n\nlemma non_sym_dist_pairs_elems_distinct:\n  assumes \"(x,y) \\<in> set (non_sym_dist_pairs xs)\"\nshows \"x \\<in> set xs\" \nand   \"y \\<in> set xs\"\nand   \"x \\<noteq> y\"\n  using non_sym_dist_pairs'_elems_distinct assms\n  unfolding non_sym_dist_pairs.simps by fastforce+\n\n\nlemma non_sym_dist_pairs_elems :\n  assumes \"x \\<in> set xs\"\n  and     \"y \\<in> set xs\"\n  and     \"x \\<noteq> y\"\nshows \"(x,y) \\<in> set (non_sym_dist_pairs xs) \\<or> (y,x) \\<in> set (non_sym_dist_pairs xs)\"\n  using assms by (induction xs; auto)\n\n\n\nlemma non_sym_dist_pairs'_elems_non_refl :\n  assumes \"distinct xs\"\n  and     \"(x,y) \\<in> set (non_sym_dist_pairs' xs)\"\nshows \"(y,x) \\<notin> set (non_sym_dist_pairs' xs)\"\n  using assms  \nproof (induction xs arbitrary: x y)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons z zs)\n  then have \"distinct zs\" by auto\n\n  have \"x \\<noteq> y\"\n    using non_sym_dist_pairs'_elems_distinct[OF Cons.prems] by simp\n\n  consider (a) \"(x,y) \\<in> set (map (Pair z) zs)\" |\n           (b) \"(x,y) \\<in> set (non_sym_dist_pairs' zs)\"\n    using \\<open>(x,y) \\<in> set (non_sym_dist_pairs' (z#zs))\\<close> unfolding non_sym_dist_pairs'.simps by auto\n  then show ?case proof cases\n    case a\n    then have \"x = z\" by auto\n    then have \"(y,x) \\<notin> set (map (Pair z) zs)\"\n      using \\<open>x \\<noteq> y\\<close> by auto\n    moreover have \"x \\<notin> set zs\"\n      using \\<open>x = z\\<close> \\<open>distinct (z#zs)\\<close> by auto\n    ultimately show ?thesis \n      using \\<open>distinct zs\\<close> non_sym_dist_pairs'_elems_distinct(2) by fastforce\n  next\n    case b\n    then have \"x \\<noteq> z\" and \"y \\<noteq> z\"\n      using Cons.prems unfolding non_sym_dist_pairs'.simps \n      by (meson distinct.simps(2) non_sym_dist_pairs'_elems_distinct(1,2))+\n    \n    then show ?thesis \n      using Cons.IH[OF \\<open>distinct zs\\<close> b] by auto\n  qed\nqed\n\n\nlemma non_sym_dist_pairs_elems_non_refl :\n  assumes \"(x,y) \\<in> set (non_sym_dist_pairs xs)\"\n  shows \"(y,x) \\<notin> set (non_sym_dist_pairs xs)\"\n  using assms by (simp add: non_sym_dist_pairs'_elems_non_refl)\n\n\nlemma non_sym_dist_pairs_set_iff :\n  \"(x,y) \\<in> set (non_sym_dist_pairs xs) \\<longleftrightarrow> (x \\<noteq> y \\<and> x \\<in> set xs \\<and> y \\<in> set xs \\<and> (y,x) \\<notin> set (non_sym_dist_pairs xs))\"\n  using non_sym_dist_pairs_elems_non_refl[of x y xs] \n        non_sym_dist_pairs_elems[of x xs y] \n        non_sym_dist_pairs_elems_distinct[of x y xs] by blast \n\n\n\nsubsection \\<open>Other Lemmata\\<close>\n\nlemma list_append_subset3 : \"set xs1 \\<subseteq> set ys1 \\<Longrightarrow> set xs2 \\<subseteq> set ys2 \\<Longrightarrow> set xs3 \\<subseteq> set ys3 \\<Longrightarrow> set (xs1@xs2@xs3) \\<subseteq> set(ys1@ys2@ys3)\" by auto\n\nlemma subset_filter : \"set xs \\<subseteq> set ys \\<Longrightarrow> set xs = set (filter (\\<lambda> x . x \\<in> set xs) ys)\"\n  by auto\n\n\nlemma filter_length_weakening :\n  assumes \"\\<And> q . f1 q \\<Longrightarrow> f2 q\"\n  shows \"length (filter f1 p) \\<le> length (filter f2 p)\"\nproof (induction p)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a p)\n  then show ?case using assms by (cases \"f1 a\"; auto)\nqed\n\nlemma max_length_elem :\n  fixes xs :: \"'a list set\"\n  assumes \"finite xs\"\n  and     \"xs \\<noteq> {}\"\nshows \"\\<exists> x \\<in> xs . \\<not>(\\<exists> y \\<in> xs . length y > length x)\" \nusing assms proof (induction xs)\n  case empty\n  then show ?case by auto\nnext\n  case (insert x F)\n  then show ?case proof (cases \"F = {}\")\n    case True\n    then show ?thesis by blast\n  next\n    case False\n    then obtain y where \"y \\<in> F\" and \"\\<not>(\\<exists> y' \\<in> F . length y' > length y)\"\n      using insert.IH by blast\n    then show ?thesis using dual_order.strict_trans by (cases \"length x > length y\"; auto)\n  qed\nqed\n\nlemma list_property_from_index_property :\n  assumes \"\\<And> i . i < length xs \\<Longrightarrow> P (xs ! i)\"\n  shows \"\\<And> x . x \\<in> set xs \\<Longrightarrow> P x\"\n  by (metis assms in_set_conv_nth) \n\nlemma list_distinct_prefix :\n  assumes \"\\<And> i . i < length xs \\<Longrightarrow> xs ! i \\<notin> set (take i xs)\"\n  shows \"distinct xs\"\nproof -\n  have \"\\<And> j . distinct (take j xs)\"\n  proof -\n    fix j \n    show \"distinct (take j xs)\"\n    proof (induction j)\n      case 0\n      then show ?case by auto\n    next\n      case (Suc j)\n      then show ?case proof (cases \"Suc j \\<le> length xs\")\n        case True\n        then have \"take (Suc j) xs = (take j xs) @ [xs ! j]\"\n          by (simp add: Suc_le_eq take_Suc_conv_app_nth)\n        then show ?thesis using Suc.IH assms[of j] True by auto\n      next\n        case False\n        then have \"take (Suc j) xs = take j xs\" by auto\n        then show ?thesis using Suc.IH by auto\n      qed\n    qed \n  qed\n  then have \"distinct (take (length xs) xs)\"\n    by blast\n  then show ?thesis by auto \nqed\n\n\nlemma concat_pair_set :\n  \"set (concat (map (\\<lambda>x. map (Pair x) ys) xs)) = {xy . fst xy \\<in> set xs \\<and> snd xy \\<in> set ys}\"\n  by auto\n\nlemma list_set_sym :\n  \"set (x@y) = set (y@x)\" by auto\n\n\n\nlemma list_contains_last_take :\n  assumes \"x \\<in> set xs\"\n  shows \"\\<exists> i . 0 < i \\<and> i \\<le> length xs \\<and> last (take i xs) = x\"\n  by (metis Suc_leI assms hd_drop_conv_nth in_set_conv_nth last_snoc take_hd_drop zero_less_Suc)\n  \nlemma take_last_index :\n  assumes \"i < length xs\"\n  shows \"last (take (Suc i) xs) = xs ! i\"\n  by (simp add: assms take_Suc_conv_app_nth)\n\nlemma integer_singleton_least :\n  assumes \"{x . P x} = {a::integer}\"\n  shows \"a = (LEAST x . P x)\"\n  by (metis Collect_empty_eq Least_equality assms insert_not_empty mem_Collect_eq order_refl singletonD)\n\n\nlemma sort_list_split :\n  \"\\<forall> x \\<in> set (take i (sort xs)) . \\<forall> y \\<in> set (drop i (sort xs)) . x \\<le> y\"\n  using sorted_append by fastforce\n\n\nlemma set_map_subset :\n  assumes \"x \\<in> set xs\"\n  and     \"t \\<in> set (map f [x])\"\nshows \"t \\<in> set (map f xs)\"\n  using assms by auto\n\nlemma rev_induct2[consumes 1, case_names Nil snoc]: \n  assumes \"length xs = length ys\" \n      and \"P [] []\"\n      and \"(\\<And>x xs y ys. length xs = length ys \\<Longrightarrow> P xs ys \\<Longrightarrow> P (xs@[x]) (ys@[y]))\"\n    shows \"P xs ys\"\nusing assms proof (induct xs arbitrary: ys rule: rev_induct)\n  case Nil\n  then show ?case by auto\nnext\n  case (snoc x xs)\n  then show ?case proof (cases ys)\n    case Nil\n    then show ?thesis\n      using snoc.prems(1) by auto \n  next\n    case (Cons a list)\n    then show ?thesis\n      by (metis append_butlast_last_id diff_Suc_1 length_append_singleton list.distinct(1) snoc.hyps snoc.prems) \n  qed\nqed\n\nlemma finite_set_min_param_ex :\n  assumes \"finite XS\"\n  and     \"\\<And> x . x \\<in> XS \\<Longrightarrow> \\<exists> k . \\<forall> k' . k \\<le> k' \\<longrightarrow> P x k'\"\nshows \"\\<exists> (k::nat) . \\<forall> x \\<in> XS . P x k\"\nproof -\n  obtain f where f_def : \"\\<And> x . x \\<in> XS \\<Longrightarrow> \\<forall> k' . (f x) \\<le> k' \\<longrightarrow> P x k'\"\n    using assms(2) by meson\n  let ?k = \"Max (image f XS)\"\n  have \"\\<forall> x \\<in> XS . P x ?k\"\n    using f_def by (simp add: assms(1)) \n  then show ?thesis by blast\nqed\n\nfun list_max :: \"nat list \\<Rightarrow> nat\" where\n  \"list_max [] = 0\" |\n  \"list_max xs = Max (set xs)\"\n\nlemma list_max_is_max : \"q \\<in> set xs \\<Longrightarrow> q \\<le> list_max xs\"\n  by (metis List.finite_set Max_ge length_greater_0_conv length_pos_if_in_set list_max.elims) \n\nlemma list_prefix_subset : \"\\<exists> ys . ts = xs@ys \\<Longrightarrow> set xs \\<subseteq> set ts\" by auto\nlemma list_map_set_prop : \"x \\<in> set (map f xs) \\<Longrightarrow> \\<forall> y . P (f y) \\<Longrightarrow> P x\" by auto\nlemma list_concat_non_elem : \"x \\<notin> set xs \\<Longrightarrow> x \\<notin> set ys \\<Longrightarrow> x \\<notin> set (xs@ys)\" by auto\nlemma list_prefix_elem : \"x \\<in> set (xs@ys) \\<Longrightarrow> x \\<notin> set ys \\<Longrightarrow> x \\<in> set xs\" by auto\nlemma list_map_source_elem : \"x \\<in> set (map f xs) \\<Longrightarrow> \\<exists> x' \\<in> set xs . x = f x'\" by auto\n\n\nlemma maximal_set_cover : \n  fixes X :: \"'a set set\"\n  assumes \"finite X\" \n  and     \"S \\<in> X\"  \nshows \"\\<exists> S' \\<in> X . S \\<subseteq> S' \\<and> (\\<forall> S'' \\<in> X . \\<not>(S' \\<subset> S''))\"\nproof (rule ccontr)\n  assume \"\\<not> (\\<exists>S'\\<in>X. S \\<subseteq> S' \\<and> (\\<forall>S''\\<in>X. \\<not> S' \\<subset> S''))\"\n  then have *: \"\\<And> T . T \\<in> X \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> \\<exists> T' \\<in> X . T \\<subset> T'\"\n    by auto\n\n  have \"\\<And> k . \\<exists> ss . (length ss = Suc k) \\<and> (hd ss = S) \\<and> (\\<forall> i < k . ss ! i \\<subset> ss ! (Suc i)) \\<and> (set ss \\<subseteq> X)\"\n  proof -\n    fix k show \"\\<exists> ss . (length ss = Suc k) \\<and> (hd ss = S) \\<and> (\\<forall> i < k . ss ! i \\<subset> ss ! (Suc i)) \\<and> (set ss \\<subseteq> X)\"\n    proof (induction k)\n      case 0\n      have \"length [S] = Suc 0 \\<and> hd [S] = S \\<and> (\\<forall> i < 0 . [S] ! i \\<subset> [S] ! (Suc i)) \\<and> (set [S] \\<subseteq> X)\" using assms(2) by auto\n      then show ?case by blast\n    next\n      case (Suc k)\n      then obtain ss where \"length ss = Suc k\" \n                       and \"hd ss = S\" \n                       and \"(\\<forall>i<k. ss ! i \\<subset> ss ! Suc i)\" \n                       and \"set ss \\<subseteq> X\"\n        by blast\n      then have \"ss ! k \\<in> X\"\n        by auto\n      moreover have \"S \\<subseteq> (ss ! k)\"\n      proof -\n        have \"\\<And> i . i < Suc k \\<Longrightarrow> S \\<subseteq> (ss ! i)\"\n        proof -\n          fix i assume \"i < Suc k\"\n          then show \"S \\<subseteq> (ss ! i)\"\n          proof (induction i)\n            case 0\n            then show ?case using \\<open>hd ss = S\\<close> \\<open>length ss = Suc k\\<close>\n              by (metis hd_conv_nth list.size(3) nat.distinct(1) order_refl) \n          next\n            case (Suc i)\n            then have \"S \\<subseteq> ss ! i\" and \"i < k\" by auto\n            then have \"ss ! i \\<subset> ss ! Suc i\" using \\<open>(\\<forall>i<k. ss ! i \\<subset> ss ! Suc i)\\<close> by blast\n            then show ?case using \\<open>S \\<subseteq> ss ! i\\<close> by auto\n          qed\n        qed\n        then show ?thesis using \\<open>length ss = Suc k\\<close> by auto \n      qed\n      ultimately obtain T' where \"T' \\<in> X\" and \"ss ! k \\<subset> T'\"\n        using * by meson \n\n      let ?ss = \"ss@[T']\"\n\n      have \"length ?ss = Suc (Suc k)\" \n        using \\<open>length ss = Suc k\\<close> by auto\n      moreover have \"hd ?ss = S\" \n        using \\<open>hd ss = S\\<close> by (metis \\<open>length ss = Suc k\\<close> hd_append list.size(3) nat.distinct(1)) \n      moreover have \"(\\<forall>i < Suc k. ?ss ! i \\<subset> ?ss ! Suc i)\" \n        using \\<open>(\\<forall>i<k. ss ! i \\<subset> ss ! Suc i)\\<close> \\<open>ss ! k \\<subset> T'\\<close> \n        by (metis Suc_lessI \\<open>length ss = Suc k\\<close> diff_Suc_1 less_SucE nth_append nth_append_length) \n      moreover have \"set ?ss \\<subseteq> X\" \n        using \\<open>set ss \\<subseteq> X\\<close> \\<open>T' \\<in> X\\<close> by auto\n      ultimately show ?case by blast\n    qed\n  qed\n\n  then obtain ss where \"(length ss = Suc (card X))\"\n                   and \"(hd ss = S)\" \n                   and \"(\\<forall> i < card X . ss ! i \\<subset> ss ! (Suc i))\" \n                   and \"(set ss \\<subseteq> X)\" \n    by blast\n  then have \"(\\<forall> i < length ss - 1 . ss ! i \\<subset> ss ! (Suc i))\"\n    by auto\n\n  have **: \"\\<And> i (ss :: 'a set list) . (\\<forall> i < length ss - 1 . ss ! i \\<subset> ss ! (Suc i)) \\<Longrightarrow> i < length ss  \\<Longrightarrow> \\<forall> s \\<in> set (take i ss) . s \\<subset> ss ! i\"\n  proof -\n    fix i \n    fix ss :: \"'a set list\"\n    assume \"i < length ss \" and \"(\\<forall> i < length ss - 1 . ss ! i \\<subset> ss ! (Suc i))\"\n    then show \"\\<forall> s \\<in> set (take i ss) . s \\<subset> ss ! i\"\n    proof (induction i)\n      case 0\n      then show ?case by auto\n    next\n      case (Suc i)\n      then have \"\\<forall>s\\<in>set (take i ss). s \\<subset> ss ! i\" by auto\n      then have \"\\<forall>s\\<in>set (take i ss). s \\<subset> ss ! (Suc i)\" using Suc.prems\n        by (metis One_nat_def Suc_diff_Suc Suc_lessE diff_zero dual_order.strict_trans nat.inject zero_less_Suc) \n      moreover have \"ss ! i \\<subset> ss ! (Suc i)\" using Suc.prems by auto\n      moreover have \"(take (Suc i) ss) = (take i ss)@[ss ! i]\" using Suc.prems(1)\n        by (simp add: take_Suc_conv_app_nth)\n      ultimately show ?case by auto \n    qed\n  qed\n\n  have \"distinct ss\"\n    using \\<open>(\\<forall> i < length ss - 1 . ss ! i \\<subset> ss ! (Suc i))\\<close>\n  proof (induction ss rule: rev_induct)\n    case Nil\n    then show ?case by auto\n  next\n    case (snoc a ss)\n    from snoc.prems have \"\\<forall>i<length ss - 1. ss ! i \\<subset> ss ! Suc i\"\n      by (metis Suc_lessD diff_Suc_1 diff_Suc_eq_diff_pred length_append_singleton nth_append zero_less_diff) \n    then have \"distinct ss\"\n      using snoc.IH by auto\n    moreover have \"a \\<notin> set ss\"\n      using **[OF snoc.prems, of \"length (ss @ [a]) - 1\"] by auto\n    ultimately show ?case by auto\n  qed\n\n  then have \"card (set ss) = Suc (card X)\"\n    using \\<open>(length ss = Suc (card X))\\<close> by (simp add: distinct_card) \n  then show \"False\"\n    using \\<open>set ss \\<subseteq> X\\<close> \\<open>finite X\\<close> by (metis Suc_n_not_le_n card_mono) \nqed\n\n\n\nlemma map_set : \n  assumes \"x \\<in> set xs\"\n  shows \"f x \\<in> set (map f xs)\" using assms by auto\n\n\nend", "meta": {"author": "RobertSachtleben", "repo": "Refined-Adaptive-State-Counting", "sha": "3691de6f16cec5ec74282465495c12e6a40133aa", "save_path": "github-repos/isabelle/RobertSachtleben-Refined-Adaptive-State-Counting", "path": "github-repos/isabelle/RobertSachtleben-Refined-Adaptive-State-Counting/Refined-Adaptive-State-Counting-3691de6f16cec5ec74282465495c12e6a40133aa/FSM/Util.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942377652497, "lm_q2_score": 0.8539127492339909, "lm_q1q2_score": 0.7602336001973047}}
{"text": "section \\<open> Example of probabilistic relation programming: cancer diagnosis \\<close>\n\ntext \\<open> This example is developed based on the machine learning exercise that Dr. Thomas Gabel delivered \nand could be found at \\url{https://ml.informatik.uni-freiburg.de/former/_media/teaching/ss11/ml_ex07_solution.pdf}.\nWe also refer to Jason Brownlee's ``A Gentle Introduction to Bayes Theorem for Machine Learning'' at \n\\url{https://machinelearningmastery.com/bayes-theorem-for-machine-learning/} for some used terminologies.\n\nIf a randomly selected patient has a laboratory test for cancer, such as breast cancer, and \nthe result is positive. Then what's the probability that the patient has cancer? \n\nIf the patient has the second laboratory test, would it be helpful to determine if the patient has \ncancer or not? How much could it contribute? This example aims to answer these questions.\n\\<close>\n\ntheory utp_prob_rel_cancer_diagnosis\n  imports \n    \"UTP_prob_relations.utp_prob_rel_lattice_laws\" \nbegin \n\nunbundle UTP_Syntax\n\ndeclare [[show_types]]\n\ndatatype LabTest = Pos | Neg\n\ntext \\<open> @{text \"c\"}: true for cancer and false for no cancer. \\<close>\nalphabet state = \n  c :: bool\n  lt :: LabTest\n\n(*\ndefinition FirstTest :: \"ureal \\<Rightarrow> ureal \\<Rightarrow> ureal \\<Rightarrow> state prhfun\" where\n\"FirstTest p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 = (if\\<^sub>p p\\<^sub>1 then (c := True) else (c := False)) ; \n       (if\\<^sub>c (c\\<^sup><) then \n          (if\\<^sub>p p\\<^sub>2 then (lt := Pos) else (lt := Neg)) \n        else \n          (if\\<^sub>p p\\<^sub>3 then (lt := Pos) else (lt := Neg))\n  )\"\n\ndefinition T:: \"state prhfun \\<Rightarrow> state prhfun \\<Rightarrow> state prhfun \\<Rightarrow> state prhfun\" where\n\"T p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 \\<equiv> (FirstTest p\\<^sub>1 p\\<^sub>2 p\\<^sub>3) \\<parallel> ((lt := Pos)::state prhfun)\"\n\ndefinition FirstTestPos:: \"state prhfun \\<Rightarrow> state prhfun \\<Rightarrow> state prhfun \\<Rightarrow> state prhfun\" where\n\"FirstTestPos p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 \\<equiv> (FirstTest p\\<^sub>1 p\\<^sub>2 p\\<^sub>3) \\<parallel> \\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e\"\n\nlemma \n  assumes \"p\\<^sub>1 = 0.002\" \"p\\<^sub>2 = 0.86\" \"p\\<^sub>3 = 0.05\"\n  shows \"FirstTest p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 = (\\<lbrakk>lt\\<^sup>> = Pos \\<and> c\\<^sup>> = True\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * 0.002 * 0.86)\\<^sub>e\"\n*)\n\ntext \\<open> The probability of a randomly selected patient has a cancer. It is the base rate or the prior. \\<close>\nabbreviation \"p\\<^sub>1 \\<equiv> 0.002\"\ntext \\<open> The sensitivity of the laboratory test or the true positive rate. \\<close>\nabbreviation \"p\\<^sub>2 \\<equiv> 0.89\"\ntext \\<open> The false negative rate. The specificity of the laboratory test or the true negative rate: @{text \"1 - p\\<^sub>3\"}. \\<close>\nabbreviation \"p\\<^sub>3 \\<equiv> 0.05\"\n\ndefinition TestAction :: \"state prhfun\" where\n\"TestAction = (if\\<^sub>c (c\\<^sup><) then \n    (if\\<^sub>p p\\<^sub>2 then (lt := Pos) else (lt := Neg))\n  else \n    (if\\<^sub>p p\\<^sub>3 then (lt := Pos) else (lt := Neg))\n  )\n\"\n\ntext \\<open> New knowledge or data learned: the test result is positive. \\<close>\ndefinition TestResultPos where\n\" TestResultPos = \\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e\"\n\ndefinition TestAction_altdef :: \"state rvhfun\" where\n\"TestAction_altdef = (\n    (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>> = c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>2) + \n    (\\<lbrakk>lt\\<^sup>> = Neg\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>> = c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e *(1-p\\<^sub>2)) + \n    (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>> = c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e *p\\<^sub>3) + \n    (\\<lbrakk>lt\\<^sup>> = Neg\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>> = c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e *(1-p\\<^sub>3))\n)\\<^sub>e\"\n\n(* P(A|B) = P(B|A) * P(A) / P(B) \nhere A is \"Cancer\" and B is \"Test is positive\"\n  P(Cancer | Test=Pos) = P(Test=Pos|Cancer) * P(Cancer) / P(Test=Pos)\n\nwhere\n  P(Cancer) = p\\<^sub>1               -- the base rate\n  P(Test=Pos|Cancer) = p\\<^sub>2 -- sensitivity\n  P(Test=Pos)             -- not directly known\n\nActually,\n  P(Test=Pos) \n= P(Test=Pos|Cancer) * P(Cancer) + P(Test=Pos|\\<not>Cancer) * P(\\<not>Cancer)\n= p\\<^sub>2 * p\\<^sub>1 + (1 - P(Test=Neg|\\<not>Cancer)) * (1 - p\\<^sub>1)\n= p\\<^sub>2 * p\\<^sub>1 + (1 - (1-p\\<^sub>3)) * (1 - p\\<^sub>1)\n= p\\<^sub>2 * p\\<^sub>1 + p\\<^sub>3 * (1 - p\\<^sub>1)\n\nSo,\n  P(Cancer | Test=Pos) = p\\<^sub>2 * p\\<^sub>1 / (p\\<^sub>2 * p\\<^sub>1 + p\\<^sub>3 * (1 - p\\<^sub>1))\n*)\ntext \\<open> Initial knowledge, or prior. \\<close>\ndefinition FirstTest :: \"state prhfun\" where\n\"FirstTest = (if\\<^sub>p p\\<^sub>1 then (c := True) else (c := False)) ; TestAction\"\n\ndefinition FirstTest_altdef :: \"state rvhfun\" where\n\"FirstTest_altdef = (\n    (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>1 * p\\<^sub>2) + \n    (\\<lbrakk>lt\\<^sup>> = Neg\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>1 * (1 - p\\<^sub>2)) + \n    (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * (1-p\\<^sub>1) * p\\<^sub>3) + \n    (\\<lbrakk>lt\\<^sup>> = Neg\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * (1-p\\<^sub>1) * (1 - p\\<^sub>3))\n)\\<^sub>e\"\n\ntext \\<open> The result of the first laboratory test is positive. \\<close>\ndefinition FirstTestPos :: \"state prhfun\" where\n\"FirstTestPos = (FirstTest \\<parallel> TestResultPos)\"\n\ndefinition FirstTestPos_altdef :: \"state rvhfun\" where\n\"FirstTestPos_altdef = (\n    ((\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>1 * p\\<^sub>2) + (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * (1 - p\\<^sub>1) * p\\<^sub>3)) / \n    (p\\<^sub>1 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3)\n)\\<^sub>e\"\n\ntext \\<open> The result of the second laboratory test (which is independent to the first one) is also positive. \\<close>\ndefinition SecondTest :: \"state prhfun\" where\n\"SecondTest = (FirstTestPos ; TestAction)\"\n\ndefinition SecondTest_altdef :: \"state rvhfun\" where\n\"SecondTest_altdef = ((\n     (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>1 * p\\<^sub>2 * p\\<^sub>2) + \n     (\\<lbrakk>lt\\<^sup>> = Neg\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>1 * p\\<^sub>2 * (1 - p\\<^sub>2)) +\n     (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * (1 - p\\<^sub>1) * p\\<^sub>3 * p\\<^sub>3) + \n     (\\<lbrakk>lt\\<^sup>> = Neg\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * (1 - p\\<^sub>1) * p\\<^sub>3 * (1 - p\\<^sub>3))\n    ) / (p\\<^sub>1 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3)\n)\\<^sub>e\"\n\ndefinition SecondTestPos :: \"state prhfun\" where\n\"SecondTestPos = (SecondTest \\<parallel> TestResultPos)\"\n\ndefinition SecondTestPos_altdef :: \"state rvhfun\" where\n\"SecondTestPos_altdef = (\n    ((\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * p\\<^sub>1 * p\\<^sub>2 * p\\<^sub>2) + (\\<lbrakk>lt\\<^sup>> = Pos\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * \\<lbrakk>\\<not>c\\<^sup>>\\<rbrakk>\\<^sub>\\<I>\\<^sub>e * (1 - p\\<^sub>1) * p\\<^sub>3 * p\\<^sub>3)) / \n    (p\\<^sub>1 * p\\<^sub>2 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3 * p\\<^sub>3)\n)\\<^sub>e\"\n\nlemma TestAction: \"TestAction = prfun_of_rvfun TestAction_altdef\"\n  apply (simp only: TestAction_def TestAction_altdef_def)\n  apply (simp add: prfun_seqcomp_right_unit)\n  apply (simp add: prfun_pcond_altdef)\n  apply (simp only: pchoice_def passigns_def)\n  apply (simp only: rvfun_assignment_inverse)\n  apply (simp only: rvfun_of_prfun_const)\n  apply (subst rvfun_pchoice_inverse_c''')\n  apply (simp add: rvfun_assignment_is_prob)\n  apply (simp add: rvfun_assignment_is_prob)\n  apply (simp)\n  apply (subst rvfun_pchoice_inverse_c''')\n  apply (simp add: rvfun_assignment_is_prob)\n  apply (simp add: rvfun_assignment_is_prob)\n  apply (simp)\n  apply (expr_simp_1 add: rel)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (subst fun_eq_iff)\n  by (pred_simp)\n\nlemma pos_false: \"{s::state. lt\\<^sub>v s = Pos \\<and> \\<not> c\\<^sub>v s} = {\\<lparr>c\\<^sub>v = False,lt\\<^sub>v = Pos\\<rparr>}\"\n  apply (simp add: set_eq_iff)\n  apply (rule allI)\n  apply (rule iffI)\n  by simp+\nlemma neg_false: \"{s::state. lt\\<^sub>v s = Neg \\<and> \\<not> c\\<^sub>v s} = {\\<lparr>c\\<^sub>v = False,lt\\<^sub>v = Neg\\<rparr>}\"\n  apply (simp add: set_eq_iff)\n  apply (rule allI)\n  apply (rule iffI)\n  by simp+\nlemma summable_pos_false: \"(\\<lambda>x::state. if lt\\<^sub>v x = Pos \\<and> \\<not> c\\<^sub>v x then 1::\\<real> else (0::\\<real>)) summable_on UNIV\"\n  apply (rule infsum_constant_finite_states_summable)\n  by (simp add: pos_false)\nlemma summable_neg_false: \"(\\<lambda>x::state. if lt\\<^sub>v x = Neg \\<and> \\<not> c\\<^sub>v x then 1::\\<real> else (0::\\<real>)) summable_on UNIV\"\n  apply (rule infsum_constant_finite_states_summable)\n  by (simp add: neg_false)\nlemma pos_true: \"{s::state. lt\\<^sub>v s = Pos \\<and> c\\<^sub>v s} = {\\<lparr>c\\<^sub>v = True,lt\\<^sub>v = Pos\\<rparr>}\"\n  apply (simp add: set_eq_iff)\n  apply (rule allI)\n  apply (rule iffI)\n  by simp+\nlemma neg_true: \"{s::state. lt\\<^sub>v s = Neg \\<and> c\\<^sub>v s} = {\\<lparr>c\\<^sub>v = True,lt\\<^sub>v = Neg\\<rparr>}\"\n  apply (simp add: set_eq_iff)\n  apply (rule allI)\n  apply (rule iffI)\n  by simp+\nlemma summable_pos_true: \"(\\<lambda>x::state. if lt\\<^sub>v x = Pos \\<and> c\\<^sub>v x then 1::\\<real> else (0::\\<real>)) summable_on UNIV\"\n  apply (rule infsum_constant_finite_states_summable)\n  by (simp add: pos_true)\nlemma summable_neg_true: \"(\\<lambda>x::state. if lt\\<^sub>v x = Neg \\<and> c\\<^sub>v x then 1::\\<real> else (0::\\<real>)) summable_on UNIV\"\n  apply (rule infsum_constant_finite_states_summable)\n  by (simp add: neg_true)\nlemma TestAction_altdef_final: \"is_final_distribution TestAction_altdef\"\n  apply (simp add: dist_defs expr_defs TestAction_altdef_def)\n  apply (pred_auto)\nproof -\n  fix c\n  have \"(\\<Sum>\\<^sub>\\<infinity>s::state.\n          (if lt\\<^sub>v s = Pos then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) / (20::\\<real>) +\n          (if lt\\<^sub>v s = Neg then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)) =\n       (\\<Sum>\\<^sub>\\<infinity>s::state.\n          (if lt\\<^sub>v s = Pos \\<and> \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) / (20::\\<real>) +\n          (if lt\\<^sub>v s = Neg \\<and> \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>))\"\n    by (smt (verit, ccfv_SIG) infsum_cong mult_cancel_right1 mult_eq_0_iff)\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>s::state. (if lt\\<^sub>v s = Pos \\<and> \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)) +\n          (\\<Sum>\\<^sub>\\<infinity>s::state. (if lt\\<^sub>v s = Neg \\<and> \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>))\"\n    apply (subst infsum_add)\n    apply (rule summable_on_cdiv_left)\n    using summable_pos_false apply blast\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_left)\n    using summable_neg_false apply blast\n    by simp\n  also have \"... = 1\"\n    apply (subst infsum_cdiv_left)\n    using summable_pos_false apply blast\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_left)\n    using summable_neg_false apply blast\n    apply (subst infsum_constant_finite_states)\n     apply (simp add: pos_false)\n    apply (subst infsum_cmult_left)\n    using summable_neg_false apply blast\n    apply (subst infsum_constant_finite_states)\n    apply (simp add: neg_false)\n    by (simp add: pos_false neg_false)\n  then show \"(\\<Sum>\\<^sub>\\<infinity>s::state.\n          (if lt\\<^sub>v s = Pos then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) / (20::\\<real>) +\n          (if lt\\<^sub>v s = Neg then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)) =\n       (1::\\<real>)\"\n    using calculation by presburger\nnext\n  fix c\n  have \"(\\<Sum>\\<^sub>\\<infinity>s::state.\n          (if lt\\<^sub>v s = Pos then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n          (if lt\\<^sub>v s = Neg then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>)) =\n       (\\<Sum>\\<^sub>\\<infinity>s::state.\n          (if lt\\<^sub>v s = Pos \\<and> c\\<^sub>v s then 1::\\<real> else (0::\\<real>))* (89::\\<real>) / (100::\\<real>) +\n          (if lt\\<^sub>v s = Neg \\<and> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>))\"\n    by (smt (verit, ccfv_SIG) infsum_cong mult_cancel_right1 mult_eq_0_iff)\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>s::state. (if lt\\<^sub>v s = Pos \\<and> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>)) +\n          (\\<Sum>\\<^sub>\\<infinity>s::state. (if lt\\<^sub>v s = Neg \\<and> c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>))\"\n    apply (subst infsum_add)\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_left)\n    using summable_pos_true apply blast\n    apply (rule summable_on_cdiv_left)\n    apply (rule summable_on_cmult_left)\n    using summable_neg_true apply blast\n    by simp\n  also have \"... = 1\"\n    apply (subst infsum_cdiv_left)\n    apply (rule summable_on_cmult_left)\n    using summable_pos_true apply blast\n    apply (subst infsum_cdiv_left)\n     apply (rule summable_on_cmult_left)\n    using summable_neg_true apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_true apply blast\n    apply (subst infsum_constant_finite_states)\n     apply (simp add: pos_true)\n    apply (subst infsum_cmult_left)\n    using summable_neg_true apply blast\n    apply (subst infsum_constant_finite_states)\n    apply (simp add: neg_true)\n    by (simp add: pos_true neg_true)\n\n  then show \"(\\<Sum>\\<^sub>\\<infinity>s::state.\n          (if lt\\<^sub>v s = Pos then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n          (if lt\\<^sub>v s = Neg then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v s then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>)) =\n       (1::\\<real>)\"\n    using calculation by presburger\nqed\n\nlemma FirstTest_simp:\n  shows \"FirstTest = prfun_of_rvfun FirstTest_altdef\"\n  apply (simp only: FirstTest_def FirstTest_altdef_def)\n  apply (simp add: TestAction)\n  apply (simp only: pseqcomp_def)\n  apply (subst rvfun_inverse) \n  using TestAction_altdef_final rvfun_prob_sum1_summable'(1) apply blast\n  apply (subst prfun_pchoice_assigns_inverse_c')\n  apply (simp add: TestAction_altdef_def)\n  apply (expr_simp_1)\n  apply (simp add: real2eureal_inverse)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (subst fun_eq_iff)\n  apply (pred_auto)\nproof -\n  fix lt c\n  let ?f = \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)))\"\n  have \"?f = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)))\"\n    by (smt (verit) divide_eq_0_iff infsum_cong mult_eq_0_iff)\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)))\"\n    by (simp add: infsum_cong)\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0 \\<in> {\\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr>}. ((499::\\<real>) / (10000::\\<real>)))\"\n    apply (subst infsum_cong_neutral[where S=\"UNIV\" and T=\"{\\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr>}\" and \n         f = \"\\<lambda>v\\<^sub>0. ((499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>))\" and\n         g = \"\\<lambda>v\\<^sub>0. ((499::\\<real>) / (10000::\\<real>))\"])\n    apply blast\n    by simp+\n  also have \"... = ((499::\\<real>) / (10000::\\<real>))\"\n    by simp\n  then show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>))) *\n       (10000::\\<real>) = (499::\\<real>)\"\n    using calculation by linarith\nnext\n  fix lt c\n  have \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)))\n    = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state. ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>)))\"\n    apply (subst infsum_cong[where g = \"\\<lambda>v\\<^sub>0::state. ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>))\"])\n    by auto\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state\\<in>{\\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr>}. ((89::\\<real>) / (50000::\\<real>)))\"\n    apply (subst infsum_cong_neutral[where S=\"UNIV\" and T=\"{\\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr>}\" and \n         f = \"\\<lambda>v\\<^sub>0. (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>)\" and\n         g = \"\\<lambda>v\\<^sub>0. ((89::\\<real>) / (50000::\\<real>))\"])\n    by simp+\n  then show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>))) *\n       (50000::\\<real>) = (89::\\<real>)\"\n    using calculation by fastforce\nnext\n  fix lt c\n  have \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>))) =\n      (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((9481::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (10000::\\<real>)))\"\n    apply (subst infsum_cong[where g = \"\\<lambda>v\\<^sub>0::state. ((9481::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (10000::\\<real>))\"])\n    by auto\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state\\<in>{\\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr>}. ((9481::\\<real>) / (10000::\\<real>)))\"\n    apply (subst infsum_cong_neutral[where S=\"UNIV\" and T=\"{\\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr>}\" and \n         f = \"\\<lambda>v\\<^sub>0. ((9481::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (10000::\\<real>))\" and\n         g = \"\\<lambda>v\\<^sub>0. ((9481::\\<real>) / (10000::\\<real>))\"])\n    by simp+\n  then show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n        ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n         (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n        ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n         (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>))) *\n     (10000::\\<real>) = (9481::\\<real>)\"\n    using calculation by fastforce\nnext\n  fix lt c\n  have \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)))\n      = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state. (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) *(11::\\<real>) / (50000::\\<real>))\"\n    apply (subst infsum_cong[where g = \"\\<lambda>v\\<^sub>0::state. (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) *(11::\\<real>) / (50000::\\<real>)\"])\n    by auto\n  also have \"... = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state\\<in>{\\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr>}. ((11::\\<real>) / (50000::\\<real>)))\"\n    apply (subst infsum_cong_neutral[where S=\"UNIV\" and T=\"{\\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr>}\" and \n         f = \"\\<lambda>v\\<^sub>0. (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) *(11::\\<real>) / (50000::\\<real>)\" and\n         g = \"\\<lambda>v\\<^sub>0. ((11::\\<real>) / (50000::\\<real>))\"])\n    by simp+\n  then show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if v\\<^sub>0 = \\<lparr>c\\<^sub>v = True, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>) +\n           (499::\\<real>) * (if v\\<^sub>0 = \\<lparr>c\\<^sub>v = False, lt\\<^sub>v = lt\\<rparr> then 1::\\<real> else (0::\\<real>)) / (500::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>))) *\n       (50000::\\<real>) = (11::\\<real>)\"\n    using calculation by force\nqed\n\nlemma FirstTestPos: \"FirstTestPos = prfun_of_rvfun FirstTestPos_altdef\"\n  apply (simp add: FirstTestPos_def FirstTestPos_altdef_def)\n  apply (simp add: FirstTest_simp TestResultPos_def)\n  apply (simp add: pfun_defs)\n  apply (subst rvfun_inverse)\n  apply (simp add: FirstTest_altdef_def)\n  apply (expr_simp_1 add: dist_defs)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (subst fun_eq_iff)\n  apply (simp add: FirstTest_altdef_def dist_defs)\n  apply (pred_auto) \nproof -\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / (10000::\\<real>) +\n            (9481::\\<real>) * ((if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>))) / (10000::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) = \n        (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos \\<and> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos \\<and> \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / (10000::\\<real>)))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = (89::\\<real>) / (50000::\\<real>) + (499::\\<real>) / (10000::\\<real>)\"\n    apply (subst infsum_add)\n    apply (simp add: summable_on_cdiv_left summable_on_cmult_left summable_pos_true)\n    apply (simp add: summable_on_cdiv_left summable_on_cmult_left summable_pos_false)\n    apply (subst infsum_cdiv_left)\n    using summable_on_cmult_left summable_pos_true apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_true apply blast\n    apply (subst infsum_cdiv_left)\n    using summable_on_cmult_left summable_pos_false apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_false apply blast\n    apply (subst infsum_constant_finite_states)\n    using pos_true apply force\n    apply (subst infsum_constant_finite_states)\n    using pos_false apply force\n    using pos_false pos_true by force\n  show \"(161177::\\<real>) /\n       ((1250::\\<real>) *\n        (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / (10000::\\<real>) +\n            (9481::\\<real>) * ((if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>))) / (10000::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)))) = (2495::\\<real>)\"\n    by (simp add: f1 f2)\nnext\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / (10000::\\<real>) +\n            (9481::\\<real>) * ((if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>))) / (10000::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) =\n      (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos \\<and> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos \\<and> \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / (10000::\\<real>)))\"\n    apply (rule infsum_cong)\n    by simp\n  have f2: \"... = (89::\\<real>) / (50000::\\<real>) + (499::\\<real>) / (10000::\\<real>)\"\n    apply (subst infsum_add)\n    apply (simp add: summable_on_cdiv_left summable_on_cmult_left summable_pos_true)\n    apply (simp add: summable_on_cdiv_left summable_on_cmult_left summable_pos_false)\n    apply (subst infsum_cdiv_left)\n    using summable_on_cmult_left summable_pos_true apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_true apply blast\n    apply (subst infsum_cdiv_left)\n    using summable_on_cmult_left summable_pos_false apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_false apply blast\n    apply (subst infsum_constant_finite_states)\n    using pos_true apply force\n    apply (subst infsum_constant_finite_states)\n    using pos_false apply force\n    using pos_false pos_true by force\n  show \"(28747::\\<real>) /\n       ((6250::\\<real>) *\n        (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (50000::\\<real>) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / (10000::\\<real>) +\n            (9481::\\<real>) * ((if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>))) / (10000::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)))) = (89::\\<real>)\"\n    by (simp add: f1 f2)\nqed\n\ntext \\<open> What's the probability that the patient has cancer, given a positive test? @{text \"P(Cancer | Test=Pos)\"} \\<close>\nlemma FirstTestPos_Cancer: \n  \"rvfun_of_prfun FirstTestPos ; \\<lbrakk>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e = ((p\\<^sub>1 * p\\<^sub>2) / (p\\<^sub>1 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3))\\<^sub>e\"\n  apply (simp add: FirstTestPos_altdef_def FirstTestPos)\n  apply (subst rvfun_inverse)\n  apply (expr_simp_1 add: dist_defs)\n  apply (pred_auto)\nproof -\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n        (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n       (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (323::\\<real>)) = \n    (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state. (((if c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * ((89::\\<real>) / (8::\\<real>) / (323::\\<real>))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((89::\\<real>) / (8::\\<real>) / (323::\\<real>))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_true)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_true apply auto[1]\n    by (smt (verit) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1 pos_true)\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n        (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n       (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (323::\\<real>)) * (2584::\\<real>) = (89::\\<real>) \"\n    using f1 f2 by linarith\nqed\n\ntext \\<open> What's the probability that the patient has no cancer, given a positive test? @{text \"P(\\<not>Cancer | Test=Pos)\"} \\<close>\nlemma FirstTestPos_NotCancer:\n  \"rvfun_of_prfun FirstTestPos ; \\<lbrakk>\\<not>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e = ((1 - p\\<^sub>1) * p\\<^sub>3 / (p\\<^sub>1 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3))\\<^sub>e\"\n  apply (simp add: FirstTestPos_altdef_def FirstTestPos)\n  apply (subst rvfun_inverse)\n  apply (expr_simp_1 add: dist_defs)\n  apply (pred_auto)\nproof -\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n        (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n       (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (323::\\<real>)) = \n    (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state. (((if \\<not> c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * ((2495::\\<real>) / (8::\\<real>) / (323::\\<real>))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((2495::\\<real>) / (8::\\<real>) / (323::\\<real>))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_false)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_false apply auto[1]\n    by (smt (verit) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1 pos_false)\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n        (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n       (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (323::\\<real>)) * (2584::\\<real>) = (2495::\\<real>)\"\n    using f1 f2 by linarith\nqed\n\nlemma SecondTest: \"SecondTest = prfun_of_rvfun SecondTest_altdef\"\n  apply (simp add: SecondTest_def SecondTest_altdef_def)\n  apply (simp add: FirstTestPos TestAction)\n  apply (simp add: pseqcomp_def)\n  apply (subst rvfun_inverse)\n  apply (simp add: FirstTestPos_altdef_def)\n  apply (expr_simp_1 add: dist_defs)\n  apply (subst rvfun_inverse)\n  apply (simp add: TestAction_altdef_def)\n  apply (expr_simp_1 add: dist_defs)\n  apply (simp add: FirstTestPos_altdef_def TestAction_altdef_def)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (subst fun_eq_iff)\n  apply (simp add: FirstTest_altdef_def dist_defs)\n  apply (pred_auto)\nproof -\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)) / (323::\\<real>)) \n    = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if \\<not> c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * ((2495::\\<real>) / ((8::\\<real>) * (20::\\<real>)*(323::\\<real>)))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((2495::\\<real>) / ((8::\\<real>) * (20::\\<real>)*(323::\\<real>)))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_false)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_false apply auto[1]\n    by (smt (verit, best) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1_eq_iff pos_false)\n  show \"(10336::\\<real>) *\n       (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)) /\n          (323::\\<real>)) = (499::\\<real>)\"\n    using f1 f2 by linarith\nnext\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)) /\n          (323::\\<real>)) \n    = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((if \\<not> c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) * ((2495::\\<real>)*19 / ((8::\\<real>) * (20::\\<real>)*(323::\\<real>)))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((2495::\\<real>)*19 / ((8::\\<real>) * (20::\\<real>)*(323::\\<real>)))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_false)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_false apply auto[1]\n    by (smt (verit, best) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1_eq_iff pos_false)\n  show \"(544::\\<real>) *\n       (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)) /\n          (323::\\<real>)) = (499::\\<real>)\"\n    using f1 f2 by linarith\nnext\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)) / (323::\\<real>))\n    = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          (((if c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * (89 * (89::\\<real>) / ((100::\\<real>) * (323::\\<real>) * (8::\\<real>)))))\"\n    apply (rule infsum_cong)\n    by simp\n  have f2: \"... = (89 * (89::\\<real>) / ((100::\\<real>) * (323::\\<real>) * (8::\\<real>)))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_true)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_true apply auto[1]\n    by (smt (verit, best) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1_eq_iff pos_true)\n  show \"(258400::\\<real>) *\n       (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (89::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (20::\\<real>)) / (323::\\<real>)) =\n       (7921::\\<real>)\"\n    using f1 f2 by linarith\nnext\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)) / (323::\\<real>))\n    = (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          (((if c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * (89 * (11::\\<real>) / ((100::\\<real>) * (323::\\<real>) * (8::\\<real>)))))\"\n    apply (rule infsum_cong)\n    by simp\n  have f2: \"... = (89 * (11::\\<real>) / ((100::\\<real>) * (323::\\<real>) * (8::\\<real>)))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_true)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_true apply auto[1]\n    by (smt (verit, best) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1_eq_iff pos_true)\n  show \"(258400::\\<real>) *\n       (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n          ((89::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>) +\n           (2495::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (8::\\<real>)) *\n          ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (11::\\<real>) / (100::\\<real>) +\n           (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (19::\\<real>) / (20::\\<real>)) / (323::\\<real>)) =\n       (979::\\<real>)\"\n    using f1 f2 by linarith\nqed\n  \nlemma SecondTestPos: \"SecondTestPos = prfun_of_rvfun SecondTestPos_altdef\"\n  apply (simp add: SecondTestPos_def SecondTestPos_altdef_def)\n  apply (simp add: SecondTest)\n  apply (simp add: pfun_defs)\n  apply (subst rvfun_inverse)\n  apply (simp add: SecondTest_altdef_def)\n  apply (expr_simp_1 add: dist_defs)\n  apply (rule HOL.arg_cong[where f=\"prfun_of_rvfun\"])\n  apply (subst fun_eq_iff)\n  apply (simp add: SecondTest_altdef_def TestResultPos_def dist_defs)\n  apply (pred_auto) \nproof -\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (979::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (499::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (32::\\<real>) +\n            (9481::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (32::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) / (323::\\<real>)) = \n        (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           (((if c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * ((7921::\\<real>) / ((800::\\<real>) * 323)) +\n            ((if \\<not> c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * ((499::\\<real>) / ((32::\\<real>) * (323::\\<real>)))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((7921::\\<real>) / ((800::\\<real>) * 323)) + ((499::\\<real>) / ((32::\\<real>) * (323::\\<real>)))\"\n    apply (subst infsum_add)\n    apply (subst summable_on_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_true)\n    apply (simp)\n    apply (subst summable_on_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_false)\n     apply (simp)\n    apply (subst infsum_cmult_left)\n     apply (smt (verit, ccfv_SIG) summable_on_cong summable_pos_true)\n    apply (subst infsum_cmult_left)\n    apply (smt (verit, ccfv_SIG) summable_on_cong summable_pos_false)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_true apply auto[1]\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_false apply auto[1]\n    by (metis (no_types, lifting) Collect_cong One_nat_def card.empty card.insert equals0D finite.emptyI mult_cancel_right2 of_nat_1 pos_false pos_true)\n  show \"(2544401::\\<real>) / ((2584::\\<real>) *\n        (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (979::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (499::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (32::\\<real>) +\n            (9481::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (32::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) / (323::\\<real>))) = (12475::\\<real>)\"\n    apply (simp only: f1 f2)\n    by auto\nnext\n  fix c\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (979::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (499::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (32::\\<real>) +\n            (9481::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (32::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) / (323::\\<real>)) =\n      (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((if lt\\<^sub>v v\\<^sub>0 = Pos \\<and> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (7921::\\<real>) / ((800::\\<real>)*(323::\\<real>)) +\n            (if lt\\<^sub>v v\\<^sub>0 = Pos \\<and> \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (499::\\<real>) / ((32::\\<real>)*(323::\\<real>))))\"\n    apply (rule infsum_cong)\n    by simp\n  have f2: \"... = (7921::\\<real>) / ((800::\\<real>)*(323::\\<real>)) + (499::\\<real>) / ((32::\\<real>)*(323::\\<real>))\"\n    apply (subst infsum_add)\n    apply (simp add: summable_on_cdiv_left summable_on_cmult_left summable_pos_true)\n    apply (simp add: summable_on_cdiv_left summable_on_cmult_left summable_pos_false)\n    apply (subst infsum_cdiv_left)\n    using summable_on_cmult_left summable_pos_true apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_true apply blast\n    apply (subst infsum_cdiv_left)\n    using summable_on_cmult_left summable_pos_false apply blast\n    apply (subst infsum_cmult_left)\n    using summable_pos_false apply blast\n    apply (subst infsum_constant_finite_states)\n    using pos_true apply force\n    apply (subst infsum_constant_finite_states)\n    using pos_false apply force\n    using pos_false pos_true by force\n  show \"(40389179::\\<real>) / ((64600::\\<real>) *\n        (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n           ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (979::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (800::\\<real>) +\n            (499::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (32::\\<real>) +\n            (9481::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Neg then 1::\\<real> else (0::\\<real>))) / (32::\\<real>)) *\n           (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>)) / (323::\\<real>))) = (7921::\\<real>)\"\n    apply (simp only: f1 f2)\n    by auto\nqed\n\ntext \\<open> What's the probability that the patient has cancer, given a positive test? @{text \"P(Cancer | Test=Pos)\"} \\<close>\nlemma SecondTestPos_Cancer: \n  \"rvfun_of_prfun SecondTestPos ; \\<lbrakk>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e = ((p\\<^sub>1 * p\\<^sub>2 * p\\<^sub>2) / (p\\<^sub>1 * p\\<^sub>2 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3 * p\\<^sub>3))\\<^sub>e\"\n  apply (simp add: SecondTestPos_altdef_def SecondTestPos)\n  apply (subst rvfun_inverse)\n  apply (expr_simp_1 add: dist_defs)\n  apply (pred_auto)\nproof -\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>) +\n        (12475::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>)) *\n       (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (5099::\\<real>)) = \n    (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state. (((if c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * ((7921::\\<real>) / (4::\\<real>) / (5099::\\<real>))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((7921::\\<real>) / (4::\\<real>) / (5099::\\<real>))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_true)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_true apply auto[1]\n    by (smt (verit) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1 pos_true)\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>) +\n        (12475::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>)) *\n       (if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (5099::\\<real>)) * (20396::\\<real>) = (7921::\\<real>)\"\n    using f1 f2 by linarith\nqed\n\ntext \\<open> What's the probability that the patient has no cancer, given a positive test? @{text \"P(\\<not>Cancer | Test=Pos)\"} \\<close>\nlemma SecondTestPos_NotCancer:\n  \"rvfun_of_prfun SecondTestPos ; \\<lbrakk>\\<not>c\\<^sup><\\<rbrakk>\\<^sub>\\<I>\\<^sub>e = ((1 - p\\<^sub>1) * p\\<^sub>3 * p\\<^sub>3 / (p\\<^sub>1 * p\\<^sub>2 * p\\<^sub>2 + (1 - p\\<^sub>1) * p\\<^sub>3 * p\\<^sub>3))\\<^sub>e\"\n  apply (simp add: SecondTestPos_altdef_def SecondTestPos)\n  apply (subst rvfun_inverse)\n  apply (expr_simp_1 add: dist_defs)\n  apply (pred_auto)\nproof -\n  have f1: \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>) +\n        (12475::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>)) *\n       (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (5099::\\<real>)) = \n    (\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state. (((if \\<not> c\\<^sub>v v\\<^sub>0 \\<and> lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) * ((12475::\\<real>) / (4::\\<real>) / (5099::\\<real>))))\"\n    apply (rule infsum_cong)\n    by simp\n  also have f2: \"... = ((12475::\\<real>) / (4::\\<real>) / (5099::\\<real>))\"\n    apply (subst infsum_cmult_left)\n    apply (smt (verit) summable_on_cong summable_pos_false)\n    apply (simp)\n    apply (subst infsum_constant_finite_states)\n    using finite.simps pos_false apply auto[1]\n    by (smt (verit) Collect_cong One_nat_def card.empty card.insert empty_iff finite.emptyI of_nat_1 pos_false)\n  show \"(\\<Sum>\\<^sub>\\<infinity>v\\<^sub>0::state.\n       ((7921::\\<real>) * ((if c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>) +\n        (12475::\\<real>) * ((if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) * (if lt\\<^sub>v v\\<^sub>0 = Pos then 1::\\<real> else (0::\\<real>))) / (4::\\<real>)) *\n       (if \\<not> c\\<^sub>v v\\<^sub>0 then 1::\\<real> else (0::\\<real>)) / (5099::\\<real>)) * (20396::\\<real>) = (12475::\\<real>)\"\n    using f1 f2 by linarith\nqed\n\nend\n", "meta": {"author": "RandallYe", "repo": "probabilistic_programming_utp", "sha": "3b8572782bef93200c01a0663a62e667113b2448", "save_path": "github-repos/isabelle/RandallYe-probabilistic_programming_utp", "path": "github-repos/isabelle/RandallYe-probabilistic_programming_utp/probabilistic_programming_utp-3b8572782bef93200c01a0663a62e667113b2448/probability/probabilistic_relations/Examples/machine_learning_examples/utp_prob_rel_cancer_diagnosis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.8539127529517043, "lm_q1q2_score": 0.7602335910792953}}
{"text": "theory ex4_01 imports Main begin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\" |\n\"set (Node l x r) = set l \\<union> {x} \\<union> set r\"\n\nvalue \"set (Node (Node Tip 1 Tip) 2 (Node Tip 1 Tip))\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node l x r) = ((\\<forall>lv \\<in> (set l). (lv < x)) \\<and> (\\<forall>rv \\<in> (set r). (rv > x)))\"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins x Tip = Node Tip x Tip\" |\n\"ins x (Node l v r) = (\n if x < v then Node (ins x l) v r\n else if x > v then Node l v (ins x r)\n else Node l v r\n)\"\n\ntheorem[simp]: \"set (ins x t) = {x} \\<union> set t\"\napply (induction t)\napply auto\ndone\n\ntheorem \"ord t \\<Longrightarrow> ord (ins i t)\"\napply(induction t)\napply auto\ndone\n\nend", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter4/ex4_01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897558991954, "lm_q2_score": 0.8080672066194945, "lm_q1q2_score": 0.7602213500656989}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_MSortBU2IsSort\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun risers :: \"int list => (int list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if y <= y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun lmerge :: \"int list => int list => int list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if z <= x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(int list) list => (int list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(int list) list => int list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun msortbu2 :: \"int list => int list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\nfun insert :: \"int => int list => int list\" where\n  \"insert x (nil2) = cons2 x (nil2)\"\n| \"insert x (cons2 z xs) =\n     (if x <= z then cons2 x (cons2 z xs) else cons2 z (insert x xs))\"\n\nfun isort :: \"int list => int list\" where\n  \"isort (nil2) = nil2\"\n| \"isort (cons2 y xs) = insert y (isort xs)\"\n\ntheorem property0 :\n  \"((msortbu2 xs) = (isort xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_MSortBU2IsSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513842182777, "lm_q2_score": 0.847967764140929, "lm_q1q2_score": 0.7599922823837856}}
{"text": "(*  Title:      HOL/Orderings.thy\n    Author:     Tobias Nipkow, Markus Wenzel, and Larry Paulson\n*)\n\nsection \\<open>Abstract orderings\\<close>\n\ntheory Orderings\nimports HOL\nkeywords \"print_orders\" :: diag\nbegin\n\nML_file \\<open>~~/src/Provers/order.ML\\<close>\n\nsubsection \\<open>Abstract ordering\\<close>\n\nlocale ordering =\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<^bold>\\<le>\" 50)\n   and less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<^bold><\" 50)\n  assumes strict_iff_order: \"a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> a \\<noteq> b\"\n  assumes refl: \"a \\<^bold>\\<le> a\" \\<comment> \\<open>not \\<open>iff\\<close>: makes problems due to multiple (dual) interpretations\\<close>\n    and antisym: \"a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>\\<le> a \\<Longrightarrow> a = b\"\n    and trans: \"a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>\\<le> c \\<Longrightarrow> a \\<^bold>\\<le> c\"\nbegin\n\nlemma strict_implies_order:\n  \"a \\<^bold>< b \\<Longrightarrow> a \\<^bold>\\<le> b\"\n  by (simp add: strict_iff_order)\n\nlemma strict_implies_not_eq:\n  \"a \\<^bold>< b \\<Longrightarrow> a \\<noteq> b\"\n  by (simp add: strict_iff_order)\n\nlemma not_eq_order_implies_strict:\n  \"a \\<noteq> b \\<Longrightarrow> a \\<^bold>\\<le> b \\<Longrightarrow> a \\<^bold>< b\"\n  by (simp add: strict_iff_order)\n\nlemma order_iff_strict:\n  \"a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\"\n  by (auto simp add: strict_iff_order refl)\n\nlemma irrefl: \\<comment> \\<open>not \\<open>iff\\<close>: makes problems due to multiple (dual) interpretations\\<close>\n  \"\\<not> a \\<^bold>< a\"\n  by (simp add: strict_iff_order)\n\nlemma asym:\n  \"a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< a \\<Longrightarrow> False\"\n  by (auto simp add: strict_iff_order intro: antisym)\n\nlemma strict_trans1:\n  \"a \\<^bold>\\<le> b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  by (auto simp add: strict_iff_order intro: trans antisym)\n\nlemma strict_trans2:\n  \"a \\<^bold>< b \\<Longrightarrow> b \\<^bold>\\<le> c \\<Longrightarrow> a \\<^bold>< c\"\n  by (auto simp add: strict_iff_order intro: trans antisym)\n\nlemma strict_trans:\n  \"a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  by (auto intro: strict_trans1 strict_implies_order)\n\nlemma eq_iff: \"a = b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> b \\<^bold>\\<le> a\"\n  by (auto simp add: refl intro: antisym)\n\nend\n\ntext \\<open>Alternative introduction rule with bias towards strict order\\<close>\n\nlemma ordering_strictI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes less_eq_less: \"\\<And>a b. a \\<^bold>\\<le> b \\<longleftrightarrow> a \\<^bold>< b \\<or> a = b\"\n    assumes asym: \"\\<And>a b. a \\<^bold>< b \\<Longrightarrow> \\<not> b \\<^bold>< a\"\n  assumes irrefl: \"\\<And>a. \\<not> a \\<^bold>< a\"\n  assumes trans: \"\\<And>a b c. a \\<^bold>< b \\<Longrightarrow> b \\<^bold>< c \\<Longrightarrow> a \\<^bold>< c\"\n  shows \"ordering less_eq less\"\nproof\n  fix a b\n  show \"a \\<^bold>< b \\<longleftrightarrow> a \\<^bold>\\<le> b \\<and> a \\<noteq> b\"\n    by (auto simp add: less_eq_less asym irrefl)\nnext\n  fix a\n  show \"a \\<^bold>\\<le> a\"\n    by (auto simp add: less_eq_less)\nnext\n  fix a b c\n  assume \"a \\<^bold>\\<le> b\" and \"b \\<^bold>\\<le> c\" then show \"a \\<^bold>\\<le> c\"\n    by (auto simp add: less_eq_less intro: trans)\nnext\n  fix a b\n  assume \"a \\<^bold>\\<le> b\" and \"b \\<^bold>\\<le> a\" then show \"a = b\"\n    by (auto simp add: less_eq_less asym)\nqed\n\nlemma ordering_dualI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"ordering (\\<lambda>a b. b \\<^bold>\\<le> a) (\\<lambda>a b. b \\<^bold>< a)\"\n  shows \"ordering less_eq less\"\nproof -\n  from assms interpret ordering \"\\<lambda>a b. b \\<^bold>\\<le> a\" \"\\<lambda>a b. b \\<^bold>< a\" .\n  show ?thesis\n    by standard (auto simp: strict_iff_order refl intro: antisym trans)\nqed\n\nlocale ordering_top = ordering +\n  fixes top :: \"'a\"  (\"\\<^bold>\\<top>\")\n  assumes extremum [simp]: \"a \\<^bold>\\<le> \\<^bold>\\<top>\"\nbegin\n\nlemma extremum_uniqueI:\n  \"\\<^bold>\\<top> \\<^bold>\\<le> a \\<Longrightarrow> a = \\<^bold>\\<top>\"\n  by (rule antisym) auto\n\nlemma extremum_unique:\n  \"\\<^bold>\\<top> \\<^bold>\\<le> a \\<longleftrightarrow> a = \\<^bold>\\<top>\"\n  by (auto intro: antisym)\n\nlemma extremum_strict [simp]:\n  \"\\<not> (\\<^bold>\\<top> \\<^bold>< a)\"\n  using extremum [of a] by (auto simp add: order_iff_strict intro: asym irrefl)\n\nlemma not_eq_extremum:\n  \"a \\<noteq> \\<^bold>\\<top> \\<longleftrightarrow> a \\<^bold>< \\<^bold>\\<top>\"\n  by (auto simp add: order_iff_strict intro: not_eq_order_implies_strict extremum)\n\nend\n\n\nsubsection \\<open>Syntactic orders\\<close>\n\nclass ord =\n  fixes less_eq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n    and less :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation\n  less_eq  (\"'(\\<le>')\") and\n  less_eq  (\"(_/ \\<le> _)\"  [51, 51] 50) and\n  less  (\"'(<')\") and\n  less  (\"(_/ < _)\"  [51, 51] 50)\n\nabbreviation (input)\n  greater_eq  (infix \"\\<ge>\" 50)\n  where \"x \\<ge> y \\<equiv> y \\<le> x\"\n\nabbreviation (input)\n  greater  (infix \">\" 50)\n  where \"x > y \\<equiv> y < x\"\n\nnotation (ASCII)\n  less_eq  (\"'(<=')\") and\n  less_eq  (\"(_/ <= _)\" [51, 51] 50)\n\nnotation (input)\n  greater_eq  (infix \">=\" 50)\n\nend\n\n\nsubsection \\<open>Quasi orders\\<close>\n\nclass preorder = ord +\n  assumes less_le_not_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> \\<not> (y \\<le> x)\"\n  and order_refl [iff]: \"x \\<le> x\"\n  and order_trans: \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\nbegin\n\ntext \\<open>Reflexivity.\\<close>\n\nlemma eq_refl: \"x = y \\<Longrightarrow> x \\<le> y\"\n    \\<comment> \\<open>This form is useful with the classical reasoner.\\<close>\nby (erule ssubst) (rule order_refl)\n\nlemma less_irrefl [iff]: \"\\<not> x < x\"\nby (simp add: less_le_not_le)\n\nlemma less_imp_le: \"x < y \\<Longrightarrow> x \\<le> y\"\nby (simp add: less_le_not_le)\n\n\ntext \\<open>Asymmetry.\\<close>\n\nlemma less_not_sym: \"x < y \\<Longrightarrow> \\<not> (y < x)\"\nby (simp add: less_le_not_le)\n\nlemma less_asym: \"x < y \\<Longrightarrow> (\\<not> P \\<Longrightarrow> y < x) \\<Longrightarrow> P\"\nby (drule less_not_sym, erule contrapos_np) simp\n\n\ntext \\<open>Transitivity.\\<close>\n\nlemma less_trans: \"x < y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\nlemma le_less_trans: \"x \\<le> y \\<Longrightarrow> y < z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\nlemma less_le_trans: \"x < y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x < z\"\nby (auto simp add: less_le_not_le intro: order_trans)\n\n\ntext \\<open>Useful for simplification, but too risky to include by default.\\<close>\n\nlemma less_imp_not_less: \"x < y \\<Longrightarrow> (\\<not> y < x) \\<longleftrightarrow> True\"\nby (blast elim: less_asym)\n\nlemma less_imp_triv: \"x < y \\<Longrightarrow> (y < x \\<longrightarrow> P) \\<longleftrightarrow> True\"\nby (blast elim: less_asym)\n\n\ntext \\<open>Transitivity rules for calculational reasoning\\<close>\n\nlemma less_asym': \"a < b \\<Longrightarrow> b < a \\<Longrightarrow> P\"\nby (rule less_asym)\n\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_preorder:\n  \"class.preorder (\\<ge>) (>)\"\n  by standard (auto simp add: less_le_not_le intro: order_trans)\n\nend\n\n\nsubsection \\<open>Partial orders\\<close>\n\nclass order = preorder +\n  assumes antisym: \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma less_le: \"x < y \\<longleftrightarrow> x \\<le> y \\<and> x \\<noteq> y\"\n  by (auto simp add: less_le_not_le intro: antisym)\n\nsublocale order: ordering less_eq less + dual_order: ordering greater_eq greater\nproof -\n  interpret ordering less_eq less\n    by standard (auto intro: antisym order_trans simp add: less_le)\n  show \"ordering less_eq less\"\n    by (fact ordering_axioms)\n  then show \"ordering greater_eq greater\"\n    by (rule ordering_dualI)\nqed\n\ntext \\<open>Reflexivity.\\<close>\n\nlemma le_less: \"x \\<le> y \\<longleftrightarrow> x < y \\<or> x = y\"\n    \\<comment> \\<open>NOT suitable for iff, since it can cause PROOF FAILED.\\<close>\nby (fact order.order_iff_strict)\n\nlemma le_imp_less_or_eq: \"x \\<le> y \\<Longrightarrow> x < y \\<or> x = y\"\nby (simp add: less_le)\n\n\ntext \\<open>Useful for simplification, but too risky to include by default.\\<close>\n\nlemma less_imp_not_eq: \"x < y \\<Longrightarrow> (x = y) \\<longleftrightarrow> False\"\nby auto\n\nlemma less_imp_not_eq2: \"x < y \\<Longrightarrow> (y = x) \\<longleftrightarrow> False\"\nby auto\n\n\ntext \\<open>Transitivity rules for calculational reasoning\\<close>\n\nlemma neq_le_trans: \"a \\<noteq> b \\<Longrightarrow> a \\<le> b \\<Longrightarrow> a < b\"\nby (fact order.not_eq_order_implies_strict)\n\nlemma le_neq_trans: \"a \\<le> b \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a < b\"\nby (rule order.not_eq_order_implies_strict)\n\n\ntext \\<open>Asymmetry.\\<close>\n\nlemma eq_iff: \"x = y \\<longleftrightarrow> x \\<le> y \\<and> y \\<le> x\"\n  by (fact order.eq_iff)\n\nlemma antisym_conv: \"y \\<le> x \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x = y\"\n  by (simp add: eq_iff)\n\nlemma less_imp_neq: \"x < y \\<Longrightarrow> x \\<noteq> y\"\n  by (fact order.strict_implies_not_eq)\n\nlemma antisym_conv1: \"\\<not> x < y \\<Longrightarrow> x \\<le> y \\<longleftrightarrow> x = y\"\n  by (simp add: local.le_less)\n\nlemma antisym_conv2: \"x \\<le> y \\<Longrightarrow> \\<not> x < y \\<longleftrightarrow> x = y\"\n  by (simp add: local.less_le)\n\nlemma leD: \"y \\<le> x \\<Longrightarrow> \\<not> x < y\"\n  by (auto simp: less_le antisym)\n\ntext \\<open>Least value operator\\<close>\n\ndefinition (in ord)\n  Least :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \"LEAST \" 10) where\n  \"Least P = (THE x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<le> y))\"\n\nlemma Least_equality:\n  assumes \"P x\"\n    and \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n  shows \"Least P = x\"\nunfolding Least_def by (rule the_equality)\n  (blast intro: assms antisym)+\n\nlemma LeastI2_order:\n  assumes \"P x\"\n    and \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n    and \"\\<And>x. P x \\<Longrightarrow> \\<forall>y. P y \\<longrightarrow> x \\<le> y \\<Longrightarrow> Q x\"\n  shows \"Q (Least P)\"\nunfolding Least_def by (rule theI2)\n  (blast intro: assms antisym)+\n\nlemma Least_ex1:\n  assumes   \"\\<exists>!x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<le> y)\"\n  shows     Least1I: \"P (Least P)\" and Least1_le: \"P z \\<Longrightarrow> Least P \\<le> z\"\n  using     theI'[OF assms]\n  unfolding Least_def\n  by        auto\n\ntext \\<open>Greatest value operator\\<close>\n\ndefinition Greatest :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \"GREATEST \" 10) where\n\"Greatest P = (THE x. P x \\<and> (\\<forall>y. P y \\<longrightarrow> x \\<ge> y))\"\n\nlemma GreatestI2_order:\n  \"\\<lbrakk> P x;\n    \\<And>y. P y \\<Longrightarrow> x \\<ge> y;\n    \\<And>x. \\<lbrakk> P x; \\<forall>y. P y \\<longrightarrow> x \\<ge> y \\<rbrakk> \\<Longrightarrow> Q x \\<rbrakk>\n  \\<Longrightarrow> Q (Greatest P)\"\nunfolding Greatest_def\nby (rule theI2) (blast intro: antisym)+\n\nlemma Greatest_equality:\n  \"\\<lbrakk> P x;  \\<And>y. P y \\<Longrightarrow> x \\<ge> y \\<rbrakk> \\<Longrightarrow> Greatest P = x\"\nunfolding Greatest_def\nby (rule the_equality) (blast intro: antisym)+\n\nend\n\nlemma ordering_orderI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"ordering less_eq less\"\n  shows \"class.order less_eq less\"\nproof -\n  from assms interpret ordering less_eq less .\n  show ?thesis\n    by standard (auto intro: antisym trans simp add: refl strict_iff_order)\nqed\n\nlemma order_strictI:\n  fixes less (infix \"\\<sqsubset>\" 50)\n    and less_eq (infix \"\\<sqsubseteq>\" 50)\n  assumes \"\\<And>a b. a \\<sqsubseteq> b \\<longleftrightarrow> a \\<sqsubset> b \\<or> a = b\"\n    assumes \"\\<And>a b. a \\<sqsubset> b \\<Longrightarrow> \\<not> b \\<sqsubset> a\"\n  assumes \"\\<And>a. \\<not> a \\<sqsubset> a\"\n  assumes \"\\<And>a b c. a \\<sqsubset> b \\<Longrightarrow> b \\<sqsubset> c \\<Longrightarrow> a \\<sqsubset> c\"\n  shows \"class.order less_eq less\"\n  by (rule ordering_orderI) (rule ordering_strictI, (fact assms)+)\n\ncontext order\nbegin\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_order:\n  \"class.order (\\<ge>) (>)\"\n  using dual_order.ordering_axioms by (rule ordering_orderI)\n\nend\n\n\nsubsection \\<open>Linear (total) orders\\<close>\n\nclass linorder = order +\n  assumes linear: \"x \\<le> y \\<or> y \\<le> x\"\nbegin\n\nlemma less_linear: \"x < y \\<or> x = y \\<or> y < x\"\nunfolding less_le using less_le linear by blast\n\nlemma le_less_linear: \"x \\<le> y \\<or> y < x\"\nby (simp add: le_less less_linear)\n\nlemma le_cases [case_names le ge]:\n  \"(x \\<le> y \\<Longrightarrow> P) \\<Longrightarrow> (y \\<le> x \\<Longrightarrow> P) \\<Longrightarrow> P\"\nusing linear by blast\n\nlemma (in linorder) le_cases3:\n  \"\\<lbrakk>\\<lbrakk>x \\<le> y; y \\<le> z\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>y \\<le> x; x \\<le> z\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>x \\<le> z; z \\<le> y\\<rbrakk> \\<Longrightarrow> P;\n    \\<lbrakk>z \\<le> y; y \\<le> x\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>y \\<le> z; z \\<le> x\\<rbrakk> \\<Longrightarrow> P; \\<lbrakk>z \\<le> x; x \\<le> y\\<rbrakk> \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (blast intro: le_cases)\n\nlemma linorder_cases [case_names less equal greater]:\n  \"(x < y \\<Longrightarrow> P) \\<Longrightarrow> (x = y \\<Longrightarrow> P) \\<Longrightarrow> (y < x \\<Longrightarrow> P) \\<Longrightarrow> P\"\nusing less_linear by blast\n\nlemma linorder_wlog[case_names le sym]:\n  \"(\\<And>a b. a \\<le> b \\<Longrightarrow> P a b) \\<Longrightarrow> (\\<And>a b. P b a \\<Longrightarrow> P a b) \\<Longrightarrow> P a b\"\n  by (cases rule: le_cases[of a b]) blast+\n\nlemma not_less: \"\\<not> x < y \\<longleftrightarrow> y \\<le> x\"\n  unfolding less_le\n  using linear by (blast intro: antisym)\n\nlemma not_less_iff_gr_or_eq: \"\\<not>(x < y) \\<longleftrightarrow> (x > y \\<or> x = y)\"\n  by (auto simp add:not_less le_less)\n\nlemma not_le: \"\\<not> x \\<le> y \\<longleftrightarrow> y < x\"\n  unfolding less_le\n  using linear by (blast intro: antisym)\n\nlemma neq_iff: \"x \\<noteq> y \\<longleftrightarrow> x < y \\<or> y < x\"\nby (cut_tac x = x and y = y in less_linear, auto)\n\nlemma neqE: \"x \\<noteq> y \\<Longrightarrow> (x < y \\<Longrightarrow> R) \\<Longrightarrow> (y < x \\<Longrightarrow> R) \\<Longrightarrow> R\"\nby (simp add: neq_iff) blast\n\nlemma antisym_conv3: \"\\<not> y < x \\<Longrightarrow> \\<not> x < y \\<longleftrightarrow> x = y\"\nby (blast intro: antisym dest: not_less [THEN iffD1])\n\nlemma leI: \"\\<not> x < y \\<Longrightarrow> y \\<le> x\"\nunfolding not_less .\n\nlemma not_le_imp_less: \"\\<not> y \\<le> x \\<Longrightarrow> x < y\"\nunfolding not_le .\n\nlemma linorder_less_wlog[case_names less refl sym]:\n     \"\\<lbrakk>\\<And>a b. a < b \\<Longrightarrow> P a b;  \\<And>a. P a a;  \\<And>a b. P b a \\<Longrightarrow> P a b\\<rbrakk> \\<Longrightarrow> P a b\"\n  using antisym_conv3 by blast\n\ntext \\<open>Dual order\\<close>\n\nlemma dual_linorder:\n  \"class.linorder (\\<ge>) (>)\"\nby (rule class.linorder.intro, rule dual_order) (unfold_locales, rule linear)\n\nend\n\n\ntext \\<open>Alternative introduction rule with bias towards strict order\\<close>\n\nlemma linorder_strictI:\n  fixes less_eq (infix \"\\<^bold>\\<le>\" 50)\n    and less (infix \"\\<^bold><\" 50)\n  assumes \"class.order less_eq less\"\n  assumes trichotomy: \"\\<And>a b. a \\<^bold>< b \\<or> a = b \\<or> b \\<^bold>< a\"\n  shows \"class.linorder less_eq less\"\nproof -\n  interpret order less_eq less\n    by (fact \\<open>class.order less_eq less\\<close>)\n  show ?thesis\n  proof\n    fix a b\n    show \"a \\<^bold>\\<le> b \\<or> b \\<^bold>\\<le> a\"\n      using trichotomy by (auto simp add: le_less)\n  qed\nqed\n\n\nsubsection \\<open>Reasoning tools setup\\<close>\n\nML \\<open>\nsignature ORDERS =\nsig\n  val print_structures: Proof.context -> unit\n  val order_tac: Proof.context -> thm list -> int -> tactic\n  val add_struct: string * term list -> string -> attribute\n  val del_struct: string * term list -> attribute\nend;\n\nstructure Orders: ORDERS =\nstruct\n\n(* context data *)\n\nfun struct_eq ((s1: string, ts1), (s2, ts2)) =\n  s1 = s2 andalso eq_list (op aconv) (ts1, ts2);\n\nstructure Data = Generic_Data\n(\n  type T = ((string * term list) * Order_Tac.less_arith) list;\n    (* Order structures:\n       identifier of the structure, list of operations and record of theorems\n       needed to set up the transitivity reasoner,\n       identifier and operations identify the structure uniquely. *)\n  val empty = [];\n  val extend = I;\n  fun merge data = AList.join struct_eq (K fst) data;\n);\n\nfun print_structures ctxt =\n  let\n    val structs = Data.get (Context.Proof ctxt);\n    fun pretty_term t = Pretty.block\n      [Pretty.quote (Syntax.pretty_term ctxt t), Pretty.brk 1,\n        Pretty.str \"::\", Pretty.brk 1,\n        Pretty.quote (Syntax.pretty_typ ctxt (type_of t))];\n    fun pretty_struct ((s, ts), _) = Pretty.block\n      [Pretty.str s, Pretty.str \":\", Pretty.brk 1,\n       Pretty.enclose \"(\" \")\" (Pretty.breaks (map pretty_term ts))];\n  in\n    Pretty.writeln (Pretty.big_list \"order structures:\" (map pretty_struct structs))\n  end;\n\nval _ =\n  Outer_Syntax.command \\<^command_keyword>\\<open>print_orders\\<close>\n    \"print order structures available to transitivity reasoner\"\n    (Scan.succeed (Toplevel.keep (print_structures o Toplevel.context_of)));\n\n\n(* tactics *)\n\nfun struct_tac ((s, ops), thms) ctxt facts =\n  let\n    val [eq, le, less] = ops;\n    fun decomp thy (\\<^const>\\<open>Trueprop\\<close> $ t) =\n          let\n            fun excluded t =\n              (* exclude numeric types: linear arithmetic subsumes transitivity *)\n              let val T = type_of t\n              in\n                T = HOLogic.natT orelse T = HOLogic.intT orelse T = HOLogic.realT\n              end;\n            fun rel (bin_op $ t1 $ t2) =\n                  if excluded t1 then NONE\n                  else if Pattern.matches thy (eq, bin_op) then SOME (t1, \"=\", t2)\n                  else if Pattern.matches thy (le, bin_op) then SOME (t1, \"<=\", t2)\n                  else if Pattern.matches thy (less, bin_op) then SOME (t1, \"<\", t2)\n                  else NONE\n              | rel _ = NONE;\n            fun dec (Const (\\<^const_name>\\<open>Not\\<close>, _) $ t) =\n                  (case rel t of NONE =>\n                    NONE\n                  | SOME (t1, rel, t2) => SOME (t1, \"~\" ^ rel, t2))\n              | dec x = rel x;\n          in dec t end\n      | decomp _ _ = NONE;\n  in\n    (case s of\n      \"order\" => Order_Tac.partial_tac decomp thms ctxt facts\n    | \"linorder\" => Order_Tac.linear_tac decomp thms ctxt facts\n    | _ => error (\"Unknown order kind \" ^ quote s ^ \" encountered in transitivity reasoner\"))\n  end\n\nfun order_tac ctxt facts =\n  FIRST' (map (fn s => CHANGED o struct_tac s ctxt facts) (Data.get (Context.Proof ctxt)));\n\n\n(* attributes *)\n\nfun add_struct s tag =\n  Thm.declaration_attribute\n    (fn thm => Data.map (AList.map_default struct_eq (s, Order_Tac.empty TrueI) (Order_Tac.update tag thm)));\nfun del_struct s =\n  Thm.declaration_attribute\n    (fn _ => Data.map (AList.delete struct_eq s));\n\nend;\n\\<close>\n\nattribute_setup order = \\<open>\n  Scan.lift ((Args.add -- Args.name >> (fn (_, s) => SOME s) || Args.del >> K NONE) --|\n    Args.colon (* FIXME || Scan.succeed true *) ) -- Scan.lift Args.name --\n    Scan.repeat Args.term\n    >> (fn ((SOME tag, n), ts) => Orders.add_struct (n, ts) tag\n         | ((NONE, n), ts) => Orders.del_struct (n, ts))\n\\<close> \"theorems controlling transitivity reasoner\"\n\nmethod_setup order = \\<open>\n  Scan.succeed (fn ctxt => SIMPLE_METHOD' (Orders.order_tac ctxt []))\n\\<close> \"transitivity reasoner\"\n\n\ntext \\<open>Declarations to set up transitivity reasoner of partial and linear orders.\\<close>\n\ncontext order\nbegin\n\n(* The type constraint on @{term (=}) below is necessary since the operation\n   is not a parameter of the locale. *)\n\ndeclare less_irrefl [THEN notE, order add less_reflE: order \"(=) :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" \"(<=)\" \"(<)\"]\n\ndeclare order_refl  [order add le_refl: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_imp_le [order add less_imp_le: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare antisym [order add eqI: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare eq_refl [order add eqD1: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare sym [THEN eq_refl, order add eqD2: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_trans [order add less_trans: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_le_trans [order add less_le_trans: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare le_less_trans [order add le_less_trans: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare order_trans [order add le_trans: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare le_neq_trans [order add le_neq_trans: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare neq_le_trans [order add neq_le_trans: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_imp_neq [order add less_imp_neq: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare eq_neq_eq_imp_neq [order add eq_neq_eq_imp_neq: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare not_sym [order add not_sym: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\nend\n\ncontext linorder\nbegin\n\ndeclare [[order del: order \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]]\n\ndeclare less_irrefl [THEN notE, order add less_reflE: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare order_refl [order add le_refl: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_imp_le [order add less_imp_le: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare not_less [THEN iffD2, order add not_lessI: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare not_le [THEN iffD2, order add not_leI: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare not_less [THEN iffD1, order add not_lessD: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare not_le [THEN iffD1, order add not_leD: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare antisym [order add eqI: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare eq_refl [order add eqD1: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare sym [THEN eq_refl, order add eqD2: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_trans [order add less_trans: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_le_trans [order add less_le_trans: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare le_less_trans [order add le_less_trans: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare order_trans [order add le_trans: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare le_neq_trans [order add le_neq_trans: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare neq_le_trans [order add neq_le_trans: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare less_imp_neq [order add less_imp_neq: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare eq_neq_eq_imp_neq [order add eq_neq_eq_imp_neq: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\ndeclare not_sym [order add not_sym: linorder \"(=) :: 'a => 'a => bool\" \"(<=)\" \"(<)\"]\n\nend\n\nsetup \\<open>\n  map_theory_simpset (fn ctxt0 => ctxt0 addSolver\n    mk_solver \"Transitivity\" (fn ctxt => Orders.order_tac ctxt (Simplifier.prems_of ctxt)))\n  (*Adding the transitivity reasoners also as safe solvers showed a slight\n    speed up, but the reasoning strength appears to be not higher (at least\n    no breaking of additional proofs in the entire HOL distribution, as\n    of 5 March 2004, was observed).*)\n\\<close>\n\nML \\<open>\nlocal\n  fun prp t thm = Thm.prop_of thm = t;  (* FIXME proper aconv!? *)\nin\n\nfun antisym_le_simproc ctxt ct =\n  (case Thm.term_of ct of\n    (le as Const (_, T)) $ r $ s =>\n     (let\n        val prems = Simplifier.prems_of ctxt;\n        val less = Const (\\<^const_name>\\<open>less\\<close>, T);\n        val t = HOLogic.mk_Trueprop(le $ s $ r);\n      in\n        (case find_first (prp t) prems of\n          NONE =>\n            let val t = HOLogic.mk_Trueprop(HOLogic.Not $ (less $ r $ s)) in\n              (case find_first (prp t) prems of\n                NONE => NONE\n              | SOME thm => SOME(mk_meta_eq(thm RS @{thm antisym_conv1})))\n             end\n         | SOME thm => SOME (mk_meta_eq (thm RS @{thm order_class.antisym_conv})))\n      end handle THM _ => NONE)\n  | _ => NONE);\n\nfun antisym_less_simproc ctxt ct =\n  (case Thm.term_of ct of\n    NotC $ ((less as Const(_,T)) $ r $ s) =>\n     (let\n       val prems = Simplifier.prems_of ctxt;\n       val le = Const (\\<^const_name>\\<open>less_eq\\<close>, T);\n       val t = HOLogic.mk_Trueprop(le $ r $ s);\n      in\n        (case find_first (prp t) prems of\n          NONE =>\n            let val t = HOLogic.mk_Trueprop (NotC $ (less $ s $ r)) in\n              (case find_first (prp t) prems of\n                NONE => NONE\n              | SOME thm => SOME (mk_meta_eq(thm RS @{thm linorder_class.antisym_conv3})))\n            end\n        | SOME thm => SOME (mk_meta_eq (thm RS @{thm antisym_conv2})))\n      end handle THM _ => NONE)\n  | _ => NONE);\n\nend;\n\\<close>\n\nsimproc_setup antisym_le (\"(x::'a::order) \\<le> y\") = \"K antisym_le_simproc\"\nsimproc_setup antisym_less (\"\\<not> (x::'a::linorder) < y\") = \"K antisym_less_simproc\"\n\n\nsubsection \\<open>Bounded quantifiers\\<close>\n\nsyntax (ASCII)\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _<=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _<=_./ _)\" [0, 0, 10] 10)\n\n  \"_All_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _>_./ _)\"  [0, 0, 10] 10)\n  \"_All_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _>=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _>=_./ _)\" [0, 0, 10] 10)\n\n  \"_All_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3ALL _~=_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3EX _~=_./ _)\"  [0, 0, 10] 10)\n\nsyntax\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<le>_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<le>_./ _)\" [0, 0, 10] 10)\n\n  \"_All_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_greater\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_>_./ _)\"  [0, 0, 10] 10)\n  \"_All_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<ge>_./ _)\" [0, 0, 10] 10)\n  \"_Ex_greater_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<ge>_./ _)\" [0, 0, 10] 10)\n\n  \"_All_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<forall>_\\<noteq>_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3\\<exists>_\\<noteq>_./ _)\"  [0, 0, 10] 10)\n\nsyntax (input)\n  \"_All_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _<_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_less\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _<_./ _)\"  [0, 0, 10] 10)\n  \"_All_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _<=_./ _)\" [0, 0, 10] 10)\n  \"_Ex_less_eq\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _<=_./ _)\" [0, 0, 10] 10)\n  \"_All_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3! _~=_./ _)\"  [0, 0, 10] 10)\n  \"_Ex_neq\" :: \"[idt, 'a, bool] => bool\"    (\"(3? _~=_./ _)\"  [0, 0, 10] 10)\n\ntranslations\n  \"\\<forall>x<y. P\" \\<rightharpoonup> \"\\<forall>x. x < y \\<longrightarrow> P\"\n  \"\\<exists>x<y. P\" \\<rightharpoonup> \"\\<exists>x. x < y \\<and> P\"\n  \"\\<forall>x\\<le>y. P\" \\<rightharpoonup> \"\\<forall>x. x \\<le> y \\<longrightarrow> P\"\n  \"\\<exists>x\\<le>y. P\" \\<rightharpoonup> \"\\<exists>x. x \\<le> y \\<and> P\"\n  \"\\<forall>x>y. P\" \\<rightharpoonup> \"\\<forall>x. x > y \\<longrightarrow> P\"\n  \"\\<exists>x>y. P\" \\<rightharpoonup> \"\\<exists>x. x > y \\<and> P\"\n  \"\\<forall>x\\<ge>y. P\" \\<rightharpoonup> \"\\<forall>x. x \\<ge> y \\<longrightarrow> P\"\n  \"\\<exists>x\\<ge>y. P\" \\<rightharpoonup> \"\\<exists>x. x \\<ge> y \\<and> P\"\n  \"\\<forall>x\\<noteq>y. P\" \\<rightharpoonup> \"\\<forall>x. x \\<noteq> y \\<longrightarrow> P\"\n  \"\\<exists>x\\<noteq>y. P\" \\<rightharpoonup> \"\\<exists>x. x \\<noteq> y \\<and> P\"\n\nprint_translation \\<open>\nlet\n  val All_binder = Mixfix.binder_name \\<^const_syntax>\\<open>All\\<close>;\n  val Ex_binder = Mixfix.binder_name \\<^const_syntax>\\<open>Ex\\<close>;\n  val impl = \\<^const_syntax>\\<open>HOL.implies\\<close>;\n  val conj = \\<^const_syntax>\\<open>HOL.conj\\<close>;\n  val less = \\<^const_syntax>\\<open>less\\<close>;\n  val less_eq = \\<^const_syntax>\\<open>less_eq\\<close>;\n\n  val trans =\n   [((All_binder, impl, less),\n    (\\<^syntax_const>\\<open>_All_less\\<close>, \\<^syntax_const>\\<open>_All_greater\\<close>)),\n    ((All_binder, impl, less_eq),\n    (\\<^syntax_const>\\<open>_All_less_eq\\<close>, \\<^syntax_const>\\<open>_All_greater_eq\\<close>)),\n    ((Ex_binder, conj, less),\n    (\\<^syntax_const>\\<open>_Ex_less\\<close>, \\<^syntax_const>\\<open>_Ex_greater\\<close>)),\n    ((Ex_binder, conj, less_eq),\n    (\\<^syntax_const>\\<open>_Ex_less_eq\\<close>, \\<^syntax_const>\\<open>_Ex_greater_eq\\<close>))];\n\n  fun matches_bound v t =\n    (case t of\n      Const (\\<^syntax_const>\\<open>_bound\\<close>, _) $ Free (v', _) => v = v'\n    | _ => false);\n  fun contains_var v = Term.exists_subterm (fn Free (x, _) => x = v | _ => false);\n  fun mk x c n P = Syntax.const c $ Syntax_Trans.mark_bound_body x $ n $ P;\n\n  fun tr' q = (q, fn _ =>\n    (fn [Const (\\<^syntax_const>\\<open>_bound\\<close>, _) $ Free (v, T),\n        Const (c, _) $ (Const (d, _) $ t $ u) $ P] =>\n        (case AList.lookup (=) trans (q, c, d) of\n          NONE => raise Match\n        | SOME (l, g) =>\n            if matches_bound v t andalso not (contains_var v u) then mk (v, T) l u P\n            else if matches_bound v u andalso not (contains_var v t) then mk (v, T) g t P\n            else raise Match)\n      | _ => raise Match));\nin [tr' All_binder, tr' Ex_binder] end\n\\<close>\n\n\nsubsection \\<open>Transitivity reasoning\\<close>\n\ncontext ord\nbegin\n\nlemma ord_le_eq_trans: \"a \\<le> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<le> c\"\n  by (rule subst)\n\nlemma ord_eq_le_trans: \"a = b \\<Longrightarrow> b \\<le> c \\<Longrightarrow> a \\<le> c\"\n  by (rule ssubst)\n\nlemma ord_less_eq_trans: \"a < b \\<Longrightarrow> b = c \\<Longrightarrow> a < c\"\n  by (rule subst)\n\nlemma ord_eq_less_trans: \"a = b \\<Longrightarrow> b < c \\<Longrightarrow> a < c\"\n  by (rule ssubst)\n\nend\n\nlemma order_less_subst2: \"(a::'a::order) < b ==> f b < (c::'c::order) ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b < c\"\n  finally (less_trans) show ?thesis .\nqed\n\nlemma order_less_subst1: \"(a::'a::order) < f b ==> (b::'b::order) < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (less_trans) show ?thesis .\nqed\n\nlemma order_le_less_subst2: \"(a::'a::order) <= b ==> f b < (c::'c::order) ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b < c\"\n  finally (le_less_trans) show ?thesis .\nqed\n\nlemma order_le_less_subst1: \"(a::'a::order) <= f b ==> (b::'b::order) < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a <= f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (le_less_trans) show ?thesis .\nqed\n\nlemma order_less_le_subst2: \"(a::'a::order) < b ==> f b <= (c::'c::order) ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b <= c\"\n  finally (less_le_trans) show ?thesis .\nqed\n\nlemma order_less_le_subst1: \"(a::'a::order) < f b ==> (b::'b::order) <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a < f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (less_le_trans) show ?thesis .\nqed\n\nlemma order_subst1: \"(a::'a::order) <= f b ==> (b::'b::order) <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a <= f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (order_trans) show ?thesis .\nqed\n\nlemma order_subst2: \"(a::'a::order) <= b ==> f b <= (c::'c::order) ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a <= c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b <= c\"\n  finally (order_trans) show ?thesis .\nqed\n\nlemma ord_le_eq_subst: \"a <= b ==> f b = c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> f a <= c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a <= b\" hence \"f a <= f b\" by (rule r)\n  also assume \"f b = c\"\n  finally (ord_le_eq_trans) show ?thesis .\nqed\n\nlemma ord_eq_le_subst: \"a = f b ==> b <= c ==>\n  (!!x y. x <= y ==> f x <= f y) ==> a <= f c\"\nproof -\n  assume r: \"!!x y. x <= y ==> f x <= f y\"\n  assume \"a = f b\"\n  also assume \"b <= c\" hence \"f b <= f c\" by (rule r)\n  finally (ord_eq_le_trans) show ?thesis .\nqed\n\nlemma ord_less_eq_subst: \"a < b ==> f b = c ==>\n  (!!x y. x < y ==> f x < f y) ==> f a < c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a < b\" hence \"f a < f b\" by (rule r)\n  also assume \"f b = c\"\n  finally (ord_less_eq_trans) show ?thesis .\nqed\n\nlemma ord_eq_less_subst: \"a = f b ==> b < c ==>\n  (!!x y. x < y ==> f x < f y) ==> a < f c\"\nproof -\n  assume r: \"!!x y. x < y ==> f x < f y\"\n  assume \"a = f b\"\n  also assume \"b < c\" hence \"f b < f c\" by (rule r)\n  finally (ord_eq_less_trans) show ?thesis .\nqed\n\ntext \\<open>\n  Note that this list of rules is in reverse order of priorities.\n\\<close>\n\nlemmas [trans] =\n  order_less_subst2\n  order_less_subst1\n  order_le_less_subst2\n  order_le_less_subst1\n  order_less_le_subst2\n  order_less_le_subst1\n  order_subst2\n  order_subst1\n  ord_le_eq_subst\n  ord_eq_le_subst\n  ord_less_eq_subst\n  ord_eq_less_subst\n  forw_subst\n  back_subst\n  rev_mp\n  mp\n\nlemmas (in order) [trans] =\n  neq_le_trans\n  le_neq_trans\n\nlemmas (in preorder) [trans] =\n  less_trans\n  less_asym'\n  le_less_trans\n  less_le_trans\n  order_trans\n\nlemmas (in order) [trans] =\n  antisym\n\nlemmas (in ord) [trans] =\n  ord_le_eq_trans\n  ord_eq_le_trans\n  ord_less_eq_trans\n  ord_eq_less_trans\n\nlemmas [trans] =\n  trans\n\nlemmas order_trans_rules =\n  order_less_subst2\n  order_less_subst1\n  order_le_less_subst2\n  order_le_less_subst1\n  order_less_le_subst2\n  order_less_le_subst1\n  order_subst2\n  order_subst1\n  ord_le_eq_subst\n  ord_eq_le_subst\n  ord_less_eq_subst\n  ord_eq_less_subst\n  forw_subst\n  back_subst\n  rev_mp\n  mp\n  neq_le_trans\n  le_neq_trans\n  less_trans\n  less_asym'\n  le_less_trans\n  less_le_trans\n  order_trans\n  antisym\n  ord_le_eq_trans\n  ord_eq_le_trans\n  ord_less_eq_trans\n  ord_eq_less_trans\n  trans\n\ntext \\<open>These support proving chains of decreasing inequalities\n    a >= b >= c ... in Isar proofs.\\<close>\n\nlemma xt1 [no_atp]:\n  \"a = b \\<Longrightarrow> b > c \\<Longrightarrow> a > c\"\n  \"a > b \\<Longrightarrow> b = c \\<Longrightarrow> a > c\"\n  \"a = b \\<Longrightarrow> b \\<ge> c \\<Longrightarrow> a \\<ge> c\"\n  \"a \\<ge> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<ge> c\"\n  \"(x::'a::order) \\<ge> y \\<Longrightarrow> y \\<ge> x \\<Longrightarrow> x = y\"\n  \"(x::'a::order) \\<ge> y \\<Longrightarrow> y \\<ge> z \\<Longrightarrow> x \\<ge> z\"\n  \"(x::'a::order) > y \\<Longrightarrow> y \\<ge> z \\<Longrightarrow> x > z\"\n  \"(x::'a::order) \\<ge> y \\<Longrightarrow> y > z \\<Longrightarrow> x > z\"\n  \"(a::'a::order) > b \\<Longrightarrow> b > a \\<Longrightarrow> P\"\n  \"(x::'a::order) > y \\<Longrightarrow> y > z \\<Longrightarrow> x > z\"\n  \"(a::'a::order) \\<ge> b \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> a > b\"\n  \"(a::'a::order) \\<noteq> b \\<Longrightarrow> a \\<ge> b \\<Longrightarrow> a > b\"\n  \"a = f b \\<Longrightarrow> b > c \\<Longrightarrow> (\\<And>x y. x > y \\<Longrightarrow> f x > f y) \\<Longrightarrow> a > f c\"\n  \"a > b \\<Longrightarrow> f b = c \\<Longrightarrow> (\\<And>x y. x > y \\<Longrightarrow> f x > f y) \\<Longrightarrow> f a > c\"\n  \"a = f b \\<Longrightarrow> b \\<ge> c \\<Longrightarrow> (\\<And>x y. x \\<ge> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> a \\<ge> f c\"\n  \"a \\<ge> b \\<Longrightarrow> f b = c \\<Longrightarrow> (\\<And>x y. x \\<ge> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> f a \\<ge> c\"\n  by auto\n\nlemma xt2 [no_atp]:\n  \"(a::'a::order) >= f b ==> b >= c ==> (!!x y. x >= y ==> f x >= f y) ==> a >= f c\"\nby (subgoal_tac \"f b >= f c\", force, force)\n\nlemma xt3 [no_atp]: \"(a::'a::order) >= b ==> (f b::'b::order) >= c ==>\n    (!!x y. x >= y ==> f x >= f y) ==> f a >= c\"\nby (subgoal_tac \"f a >= f b\", force, force)\n\nlemma xt4 [no_atp]: \"(a::'a::order) > f b ==> (b::'b::order) >= c ==>\n  (!!x y. x >= y ==> f x >= f y) ==> a > f c\"\nby (subgoal_tac \"f b >= f c\", force, force)\n\nlemma xt5 [no_atp]: \"(a::'a::order) > b ==> (f b::'b::order) >= c==>\n    (!!x y. x > y ==> f x > f y) ==> f a > c\"\nby (subgoal_tac \"f a > f b\", force, force)\n\nlemma xt6 [no_atp]: \"(a::'a::order) >= f b ==> b > c ==>\n    (!!x y. x > y ==> f x > f y) ==> a > f c\"\nby (subgoal_tac \"f b > f c\", force, force)\n\nlemma xt7 [no_atp]: \"(a::'a::order) >= b ==> (f b::'b::order) > c ==>\n    (!!x y. x >= y ==> f x >= f y) ==> f a > c\"\nby (subgoal_tac \"f a >= f b\", force, force)\n\nlemma xt8 [no_atp]: \"(a::'a::order) > f b ==> (b::'b::order) > c ==>\n    (!!x y. x > y ==> f x > f y) ==> a > f c\"\nby (subgoal_tac \"f b > f c\", force, force)\n\nlemma xt9 [no_atp]: \"(a::'a::order) > b ==> (f b::'b::order) > c ==>\n    (!!x y. x > y ==> f x > f y) ==> f a > c\"\nby (subgoal_tac \"f a > f b\", force, force)\n\nlemmas xtrans = xt1 xt2 xt3 xt4 xt5 xt6 xt7 xt8 xt9\n\n(*\n  Since \"a >= b\" abbreviates \"b <= a\", the abbreviation \"...\" stands\n  for the wrong thing in an Isar proof.\n\n  The extra transitivity rules can be used as follows:\n\nlemma \"(a::'a::order) > z\"\nproof -\n  have \"a >= b\" (is \"_ >= ?rhs\")\n    sorry\n  also have \"?rhs >= c\" (is \"_ >= ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs = d\" (is \"_ = ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs >= e\" (is \"_ >= ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs > f\" (is \"_ > ?rhs\")\n    sorry\n  also (xtrans) have \"?rhs > z\"\n    sorry\n  finally (xtrans) show ?thesis .\nqed\n\n  Alternatively, one can use \"declare xtrans [trans]\" and then\n  leave out the \"(xtrans)\" above.\n*)\n\n\nsubsection \\<open>Monotonicity\\<close>\n\ncontext order\nbegin\n\ndefinition mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"mono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nlemma monoI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> mono f\"\n  unfolding mono_def by iprover\n\nlemma monoD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"mono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  unfolding mono_def by iprover\n\nlemma monoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<le> f y\"\nproof\n  from assms show \"f x \\<le> f y\" by (simp add: mono_def)\nqed\n\ndefinition antimono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"antimono f \\<longleftrightarrow> (\\<forall>x y. x \\<le> y \\<longrightarrow> f x \\<ge> f y)\"\n\nlemma antimonoI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"(\\<And>x y. x \\<le> y \\<Longrightarrow> f x \\<ge> f y) \\<Longrightarrow> antimono f\"\n  unfolding antimono_def by iprover\n\nlemma antimonoD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  shows \"antimono f \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<ge> f y\"\n  unfolding antimono_def by iprover\n\nlemma antimonoE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"antimono f\"\n  assumes \"x \\<le> y\"\n  obtains \"f x \\<ge> f y\"\nproof\n  from assms show \"f x \\<ge> f y\" by (simp add: antimono_def)\nqed\n\ndefinition strict_mono :: \"('a \\<Rightarrow> 'b::order) \\<Rightarrow> bool\" where\n  \"strict_mono f \\<longleftrightarrow> (\\<forall>x y. x < y \\<longrightarrow> f x < f y)\"\n\nlemma strict_monoI [intro?]:\n  assumes \"\\<And>x y. x < y \\<Longrightarrow> f x < f y\"\n  shows \"strict_mono f\"\n  using assms unfolding strict_mono_def by auto\n\nlemma strict_monoD [dest?]:\n  \"strict_mono f \\<Longrightarrow> x < y \\<Longrightarrow> f x < f y\"\n  unfolding strict_mono_def by auto\n\nlemma strict_mono_mono [dest?]:\n  assumes \"strict_mono f\"\n  shows \"mono f\"\nproof (rule monoI)\n  fix x y\n  assume \"x \\<le> y\"\n  show \"f x \\<le> f y\"\n  proof (cases \"x = y\")\n    case True then show ?thesis by simp\n  next\n    case False with \\<open>x \\<le> y\\<close> have \"x < y\" by simp\n    with assms strict_monoD have \"f x < f y\" by auto\n    then show ?thesis by simp\n  qed\nqed\n\nend\n\ncontext linorder\nbegin\n\nlemma mono_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x \\<le> y\"\nproof\n  show \"x \\<le> y\"\n  proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma mono_strict_invE:\n  fixes f :: \"'a \\<Rightarrow> 'b::order\"\n  assumes \"mono f\"\n  assumes \"f x < f y\"\n  obtains \"x < y\"\nproof\n  show \"x < y\"\n  proof (rule ccontr)\n    assume \"\\<not> x < y\"\n    then have \"y \\<le> x\" by simp\n    with \\<open>mono f\\<close> obtain \"f y \\<le> f x\" by (rule monoE)\n    with \\<open>f x < f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_eq:\n  assumes \"strict_mono f\"\n  shows \"f x = f y \\<longleftrightarrow> x = y\"\nproof\n  assume \"f x = f y\"\n  show \"x = y\" proof (cases x y rule: linorder_cases)\n    case less with assms strict_monoD have \"f x < f y\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  next\n    case equal then show ?thesis .\n  next\n    case greater with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x = f y\\<close> show ?thesis by simp\n  qed\nqed simp\n\nlemma strict_mono_less_eq:\n  assumes \"strict_mono f\"\n  shows \"f x \\<le> f y \\<longleftrightarrow> x \\<le> y\"\nproof\n  assume \"x \\<le> y\"\n  with assms strict_mono_mono monoD show \"f x \\<le> f y\" by auto\nnext\n  assume \"f x \\<le> f y\"\n  show \"x \\<le> y\" proof (rule ccontr)\n    assume \"\\<not> x \\<le> y\" then have \"y < x\" by simp\n    with assms strict_monoD have \"f y < f x\" by auto\n    with \\<open>f x \\<le> f y\\<close> show False by simp\n  qed\nqed\n\nlemma strict_mono_less:\n  assumes \"strict_mono f\"\n  shows \"f x < f y \\<longleftrightarrow> x < y\"\n  using assms\n    by (auto simp add: less_le Orderings.less_le strict_mono_eq strict_mono_less_eq)\n\nend\n\n\nsubsection \\<open>min and max -- fundamental\\<close>\n\ndefinition (in ord) min :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"min a b = (if a \\<le> b then a else b)\"\n\ndefinition (in ord) max :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"max a b = (if a \\<le> b then b else a)\"\n\nlemma min_absorb1: \"x \\<le> y \\<Longrightarrow> min x y = x\"\n  by (simp add: min_def)\n\nlemma max_absorb2: \"x \\<le> y \\<Longrightarrow> max x y = y\"\n  by (simp add: max_def)\n\nlemma min_absorb2: \"(y::'a::order) \\<le> x \\<Longrightarrow> min x y = y\"\n  by (simp add:min_def)\n\nlemma max_absorb1: \"(y::'a::order) \\<le> x \\<Longrightarrow> max x y = x\"\n  by (simp add: max_def)\n\nlemma max_min_same [simp]:\n  fixes x y :: \"'a :: linorder\"\n  shows \"max x (min x y) = x\" \"max (min x y) x = x\" \"max (min x y) y = y\" \"max y (min x y) = y\"\nby(auto simp add: max_def min_def)\n\n\nsubsection \\<open>(Unique) top and bottom elements\\<close>\n\nclass bot =\n  fixes bot :: 'a (\"\\<bottom>\")\n\nclass order_bot = order + bot +\n  assumes bot_least: \"\\<bottom> \\<le> a\"\nbegin\n\nsublocale bot: ordering_top greater_eq greater bot\n  by standard (fact bot_least)\n\nlemma le_bot:\n  \"a \\<le> \\<bottom> \\<Longrightarrow> a = \\<bottom>\"\n  by (fact bot.extremum_uniqueI)\n\nlemma bot_unique:\n  \"a \\<le> \\<bottom> \\<longleftrightarrow> a = \\<bottom>\"\n  by (fact bot.extremum_unique)\n\nlemma not_less_bot:\n  \"\\<not> a < \\<bottom>\"\n  by (fact bot.extremum_strict)\n\nlemma bot_less:\n  \"a \\<noteq> \\<bottom> \\<longleftrightarrow> \\<bottom> < a\"\n  by (fact bot.not_eq_extremum)\n\nlemma max_bot[simp]: \"max bot x = x\"\nby(simp add: max_def bot_unique)\n\nlemma max_bot2[simp]: \"max x bot = x\"\nby(simp add: max_def bot_unique)\n\nlemma min_bot[simp]: \"min bot x = bot\"\nby(simp add: min_def bot_unique)\n\nlemma min_bot2[simp]: \"min x bot = bot\"\nby(simp add: min_def bot_unique)\n\nend\n\nclass top =\n  fixes top :: 'a (\"\\<top>\")\n\nclass order_top = order + top +\n  assumes top_greatest: \"a \\<le> \\<top>\"\nbegin\n\nsublocale top: ordering_top less_eq less top\n  by standard (fact top_greatest)\n\nlemma top_le:\n  \"\\<top> \\<le> a \\<Longrightarrow> a = \\<top>\"\n  by (fact top.extremum_uniqueI)\n\nlemma top_unique:\n  \"\\<top> \\<le> a \\<longleftrightarrow> a = \\<top>\"\n  by (fact top.extremum_unique)\n\nlemma not_top_less:\n  \"\\<not> \\<top> < a\"\n  by (fact top.extremum_strict)\n\nlemma less_top:\n  \"a \\<noteq> \\<top> \\<longleftrightarrow> a < \\<top>\"\n  by (fact top.not_eq_extremum)\n\nlemma max_top[simp]: \"max top x = top\"\nby(simp add: max_def top_unique)\n\nlemma max_top2[simp]: \"max x top = top\"\nby(simp add: max_def top_unique)\n\nlemma min_top[simp]: \"min top x = x\"\nby(simp add: min_def top_unique)\n\nlemma min_top2[simp]: \"min x top = x\"\nby(simp add: min_def top_unique)\n\nend\n\n\nsubsection \\<open>Dense orders\\<close>\n\nclass dense_order = order +\n  assumes dense: \"x < y \\<Longrightarrow> (\\<exists>z. x < z \\<and> z < y)\"\n\nclass dense_linorder = linorder + dense_order\nbegin\n\nlemma dense_le:\n  fixes y z :: 'a\n  assumes \"\\<And>x. x < y \\<Longrightarrow> x \\<le> z\"\n  shows \"y \\<le> z\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"z < y\" by simp\n  from dense[OF this]\n  obtain x where \"x < y\" and \"z < x\" by safe\n  moreover have \"x \\<le> z\" using assms[OF \\<open>x < y\\<close>] .\n  ultimately show False by auto\nqed\n\nlemma dense_le_bounded:\n  fixes x y z :: 'a\n  assumes \"x < y\"\n  assumes *: \"\\<And>w. \\<lbrakk> x < w ; w < y \\<rbrakk> \\<Longrightarrow> w \\<le> z\"\n  shows \"y \\<le> z\"\nproof (rule dense_le)\n  fix w assume \"w < y\"\n  from dense[OF \\<open>x < y\\<close>] obtain u where \"x < u\" \"u < y\" by safe\n  from linear[of u w]\n  show \"w \\<le> z\"\n  proof (rule disjE)\n    assume \"u \\<le> w\"\n    from less_le_trans[OF \\<open>x < u\\<close> \\<open>u \\<le> w\\<close>] \\<open>w < y\\<close>\n    show \"w \\<le> z\" by (rule *)\n  next\n    assume \"w \\<le> u\"\n    from \\<open>w \\<le> u\\<close> *[OF \\<open>x < u\\<close> \\<open>u < y\\<close>]\n    show \"w \\<le> z\" by (rule order_trans)\n  qed\nqed\n\nlemma dense_ge:\n  fixes y z :: 'a\n  assumes \"\\<And>x. z < x \\<Longrightarrow> y \\<le> x\"\n  shows \"y \\<le> z\"\nproof (rule ccontr)\n  assume \"\\<not> ?thesis\"\n  hence \"z < y\" by simp\n  from dense[OF this]\n  obtain x where \"x < y\" and \"z < x\" by safe\n  moreover have \"y \\<le> x\" using assms[OF \\<open>z < x\\<close>] .\n  ultimately show False by auto\nqed\n\nlemma dense_ge_bounded:\n  fixes x y z :: 'a\n  assumes \"z < x\"\n  assumes *: \"\\<And>w. \\<lbrakk> z < w ; w < x \\<rbrakk> \\<Longrightarrow> y \\<le> w\"\n  shows \"y \\<le> z\"\nproof (rule dense_ge)\n  fix w assume \"z < w\"\n  from dense[OF \\<open>z < x\\<close>] obtain u where \"z < u\" \"u < x\" by safe\n  from linear[of u w]\n  show \"y \\<le> w\"\n  proof (rule disjE)\n    assume \"w \\<le> u\"\n    from \\<open>z < w\\<close> le_less_trans[OF \\<open>w \\<le> u\\<close> \\<open>u < x\\<close>]\n    show \"y \\<le> w\" by (rule *)\n  next\n    assume \"u \\<le> w\"\n    from *[OF \\<open>z < u\\<close> \\<open>u < x\\<close>] \\<open>u \\<le> w\\<close>\n    show \"y \\<le> w\" by (rule order_trans)\n  qed\nqed\n\nend\n\nclass no_top = order +\n  assumes gt_ex: \"\\<exists>y. x < y\"\n\nclass no_bot = order +\n  assumes lt_ex: \"\\<exists>y. y < x\"\n\nclass unbounded_dense_linorder = dense_linorder + no_top + no_bot\n\n\nsubsection \\<open>Wellorders\\<close>\n\nclass wellorder = linorder +\n  assumes less_induct [case_names less]: \"(\\<And>x. (\\<And>y. y < x \\<Longrightarrow> P y) \\<Longrightarrow> P x) \\<Longrightarrow> P a\"\nbegin\n\nlemma wellorder_Least_lemma:\n  fixes k :: 'a\n  assumes \"P k\"\n  shows LeastI: \"P (LEAST x. P x)\" and Least_le: \"(LEAST x. P x) \\<le> k\"\nproof -\n  have \"P (LEAST x. P x) \\<and> (LEAST x. P x) \\<le> k\"\n  using assms proof (induct k rule: less_induct)\n    case (less x) then have \"P x\" by simp\n    show ?case proof (rule classical)\n      assume assm: \"\\<not> (P (LEAST a. P a) \\<and> (LEAST a. P a) \\<le> x)\"\n      have \"\\<And>y. P y \\<Longrightarrow> x \\<le> y\"\n      proof (rule classical)\n        fix y\n        assume \"P y\" and \"\\<not> x \\<le> y\"\n        with less have \"P (LEAST a. P a)\" and \"(LEAST a. P a) \\<le> y\"\n          by (auto simp add: not_le)\n        with assm have \"x < (LEAST a. P a)\" and \"(LEAST a. P a) \\<le> y\"\n          by auto\n        then show \"x \\<le> y\" by auto\n      qed\n      with \\<open>P x\\<close> have Least: \"(LEAST a. P a) = x\"\n        by (rule Least_equality)\n      with \\<open>P x\\<close> show ?thesis by simp\n    qed\n  qed\n  then show \"P (LEAST x. P x)\" and \"(LEAST x. P x) \\<le> k\" by auto\nqed\n\n\\<comment> \\<open>The following 3 lemmas are due to Brian Huffman\\<close>\nlemma LeastI_ex: \"\\<exists>x. P x \\<Longrightarrow> P (Least P)\"\n  by (erule exE) (erule LeastI)\n\nlemma LeastI2:\n  \"P a \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> Q (Least P)\"\n  by (blast intro: LeastI)\n\nlemma LeastI2_ex:\n  \"\\<exists>a. P a \\<Longrightarrow> (\\<And>x. P x \\<Longrightarrow> Q x) \\<Longrightarrow> Q (Least P)\"\n  by (blast intro: LeastI_ex)\n\nlemma LeastI2_wellorder:\n  assumes \"P a\"\n  and \"\\<And>a. \\<lbrakk> P a; \\<forall>b. P b \\<longrightarrow> a \\<le> b \\<rbrakk> \\<Longrightarrow> Q a\"\n  shows \"Q (Least P)\"\nproof (rule LeastI2_order)\n  show \"P (Least P)\" using \\<open>P a\\<close> by (rule LeastI)\nnext\n  fix y assume \"P y\" thus \"Least P \\<le> y\" by (rule Least_le)\nnext\n  fix x assume \"P x\" \"\\<forall>y. P y \\<longrightarrow> x \\<le> y\" thus \"Q x\" by (rule assms(2))\nqed\n\nlemma LeastI2_wellorder_ex:\n  assumes \"\\<exists>x. P x\"\n  and \"\\<And>a. \\<lbrakk> P a; \\<forall>b. P b \\<longrightarrow> a \\<le> b \\<rbrakk> \\<Longrightarrow> Q a\"\n  shows \"Q (Least P)\"\nusing assms by clarify (blast intro!: LeastI2_wellorder)\n\nlemma not_less_Least: \"k < (LEAST x. P x) \\<Longrightarrow> \\<not> P k\"\napply (simp add: not_le [symmetric])\napply (erule contrapos_nn)\napply (erule Least_le)\ndone\n\nlemma exists_least_iff: \"(\\<exists>n. P n) \\<longleftrightarrow> (\\<exists>n. P n \\<and> (\\<forall>m < n. \\<not> P m))\" (is \"?lhs \\<longleftrightarrow> ?rhs\")\nproof\n  assume ?rhs thus ?lhs by blast\nnext\n  assume H: ?lhs then obtain n where n: \"P n\" by blast\n  let ?x = \"Least P\"\n  { fix m assume m: \"m < ?x\"\n    from not_less_Least[OF m] have \"\\<not> P m\" . }\n  with LeastI_ex[OF H] show ?rhs by blast\nqed\n\nend\n\n\nsubsection \\<open>Order on \\<^typ>\\<open>bool\\<close>\\<close>\n\ninstantiation bool :: \"{order_bot, order_top, linorder}\"\nbegin\n\ndefinition\n  le_bool_def [simp]: \"P \\<le> Q \\<longleftrightarrow> P \\<longrightarrow> Q\"\n\ndefinition\n  [simp]: \"(P::bool) < Q \\<longleftrightarrow> \\<not> P \\<and> Q\"\n\ndefinition\n  [simp]: \"\\<bottom> \\<longleftrightarrow> False\"\n\ndefinition\n  [simp]: \"\\<top> \\<longleftrightarrow> True\"\n\ninstance proof\nqed auto\n\nend\n\nlemma le_boolI: \"(P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<le> Q\"\n  by simp\n\nlemma le_boolI': \"P \\<longrightarrow> Q \\<Longrightarrow> P \\<le> Q\"\n  by simp\n\nlemma le_boolE: \"P \\<le> Q \\<Longrightarrow> P \\<Longrightarrow> (Q \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by simp\n\nlemma le_boolD: \"P \\<le> Q \\<Longrightarrow> P \\<longrightarrow> Q\"\n  by simp\n\nlemma bot_boolE: \"\\<bottom> \\<Longrightarrow> P\"\n  by simp\n\nlemma top_boolI: \\<top>\n  by simp\n\n\n\n\nsubsection \\<open>Order on \\<^typ>\\<open>_ \\<Rightarrow> _\\<close>\\<close>\n\ninstantiation \"fun\" :: (type, ord) ord\nbegin\n\ndefinition\n  le_fun_def: \"f \\<le> g \\<longleftrightarrow> (\\<forall>x. f x \\<le> g x)\"\n\ndefinition\n  \"(f::'a \\<Rightarrow> 'b) < g \\<longleftrightarrow> f \\<le> g \\<and> \\<not> (g \\<le> f)\"\n\ninstance ..\n\nend\n\ninstance \"fun\" :: (type, preorder) preorder proof\nqed (auto simp add: le_fun_def less_fun_def\n  intro: order_trans antisym)\n\ninstance \"fun\" :: (type, order) order proof\nqed (auto simp add: le_fun_def intro: antisym)\n\ninstantiation \"fun\" :: (type, bot) bot\nbegin\n\ndefinition\n  \"\\<bottom> = (\\<lambda>x. \\<bottom>)\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, order_bot) order_bot\nbegin\n\nlemma bot_apply [simp, code]:\n  \"\\<bottom> x = \\<bottom>\"\n  by (simp add: bot_fun_def)\n\ninstance proof\nqed (simp add: le_fun_def)\n\nend\n\ninstantiation \"fun\" :: (type, top) top\nbegin\n\ndefinition\n  [no_atp]: \"\\<top> = (\\<lambda>x. \\<top>)\"\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, order_top) order_top\nbegin\n\nlemma top_apply [simp, code]:\n  \"\\<top> x = \\<top>\"\n  by (simp add: top_fun_def)\n\ninstance proof\nqed (simp add: le_fun_def)\n\nend\n\nlemma le_funI: \"(\\<And>x. f x \\<le> g x) \\<Longrightarrow> f \\<le> g\"\n  unfolding le_fun_def by simp\n\nlemma le_funE: \"f \\<le> g \\<Longrightarrow> (f x \\<le> g x \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding le_fun_def by simp\n\nlemma le_funD: \"f \\<le> g \\<Longrightarrow> f x \\<le> g x\"\n  by (rule le_funE)\n\nlemma mono_compose: \"mono Q \\<Longrightarrow> mono (\\<lambda>i x. Q i (f x))\"\n  unfolding mono_def le_fun_def by auto\n\n\nsubsection \\<open>Order on unary and binary predicates\\<close>\n\nlemma predicate1I:\n  assumes PQ: \"\\<And>x. P x \\<Longrightarrow> Q x\"\n  shows \"P \\<le> Q\"\n  apply (rule le_funI)\n  apply (rule le_boolI)\n  apply (rule PQ)\n  apply assumption\n  done\n\nlemma predicate1D:\n  \"P \\<le> Q \\<Longrightarrow> P x \\<Longrightarrow> Q x\"\n  apply (erule le_funE)\n  apply (erule le_boolE)\n  apply assumption+\n  done\n\nlemma rev_predicate1D:\n  \"P x \\<Longrightarrow> P \\<le> Q \\<Longrightarrow> Q x\"\n  by (rule predicate1D)\n\nlemma predicate2I:\n  assumes PQ: \"\\<And>x y. P x y \\<Longrightarrow> Q x y\"\n  shows \"P \\<le> Q\"\n  apply (rule le_funI)+\n  apply (rule le_boolI)\n  apply (rule PQ)\n  apply assumption\n  done\n\nlemma predicate2D:\n  \"P \\<le> Q \\<Longrightarrow> P x y \\<Longrightarrow> Q x y\"\n  apply (erule le_funE)+\n  apply (erule le_boolE)\n  apply assumption+\n  done\n\nlemma rev_predicate2D:\n  \"P x y \\<Longrightarrow> P \\<le> Q \\<Longrightarrow> Q x y\"\n  by (rule predicate2D)\n\nlemma bot1E [no_atp]: \"\\<bottom> x \\<Longrightarrow> P\"\n  by (simp add: bot_fun_def)\n\nlemma bot2E: \"\\<bottom> x y \\<Longrightarrow> P\"\n  by (simp add: bot_fun_def)\n\nlemma top1I: \"\\<top> x\"\n  by (simp add: top_fun_def)\n\nlemma top2I: \"\\<top> x y\"\n  by (simp add: top_fun_def)\n\n\nsubsection \\<open>Name duplicates\\<close>\n\nlemmas order_eq_refl = preorder_class.eq_refl\nlemmas order_less_irrefl = preorder_class.less_irrefl\nlemmas order_less_imp_le = preorder_class.less_imp_le\nlemmas order_less_not_sym = preorder_class.less_not_sym\nlemmas order_less_asym = preorder_class.less_asym\nlemmas order_less_trans = preorder_class.less_trans\nlemmas order_le_less_trans = preorder_class.le_less_trans\nlemmas order_less_le_trans = preorder_class.less_le_trans\nlemmas order_less_imp_not_less = preorder_class.less_imp_not_less\nlemmas order_less_imp_triv = preorder_class.less_imp_triv\nlemmas order_less_asym' = preorder_class.less_asym'\n\nlemmas order_less_le = order_class.less_le\nlemmas order_le_less = order_class.le_less\nlemmas order_le_imp_less_or_eq = order_class.le_imp_less_or_eq\nlemmas order_less_imp_not_eq = order_class.less_imp_not_eq\nlemmas order_less_imp_not_eq2 = order_class.less_imp_not_eq2\nlemmas order_neq_le_trans = order_class.neq_le_trans\nlemmas order_le_neq_trans = order_class.le_neq_trans\nlemmas order_antisym = order_class.antisym\nlemmas order_eq_iff = order_class.eq_iff\nlemmas order_antisym_conv = order_class.antisym_conv\n\nlemmas linorder_linear = linorder_class.linear\nlemmas linorder_less_linear = linorder_class.less_linear\nlemmas linorder_le_less_linear = linorder_class.le_less_linear\nlemmas linorder_le_cases = linorder_class.le_cases\nlemmas linorder_not_less = linorder_class.not_less\nlemmas linorder_not_le = linorder_class.not_le\nlemmas linorder_neq_iff = linorder_class.neq_iff\nlemmas linorder_neqE = linorder_class.neqE\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Orderings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7599922648411775}}
{"text": "theory Ex034\n  imports Main \nbegin \n  \nlemma \"(A \\<or> ((B \\<longrightarrow> C) \\<and> D)) \\<longrightarrow> ((B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D))\"  \nproof -\n  {\n    assume a:\"A \\<or> ((B \\<longrightarrow> C) \\<and> D)\"\n    {\n      assume A \n      hence \"B \\<or> A\" by (rule disjI2)\n      hence \"(B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D)\" by (rule disjI1)\n    }\n    note b=this\n    {\n      assume c:\"(B \\<longrightarrow> C) \\<and> D\"\n      hence d:\"B \\<longrightarrow> C\" by (rule conjE)\n      from c have e:D by (rule conjE)\n      {\n        assume f:\"\\<not>((B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D))\"\n        {\n          assume g:\"\\<not>(\\<not>C \\<longrightarrow> D)\"\n          {\n            assume \"\\<not>C\"\n            have D by (rule e)\n          }\n          hence \"\\<not>C \\<longrightarrow> D\" by (rule impI)\n          with g have False by contradiction\n        }\n        hence \"\\<not>\\<not>(\\<not>C \\<longrightarrow> D)\" by (rule notI)\n        hence \"\\<not>C \\<longrightarrow> D\" by (rule notnotD)\n        hence \"(B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D)\" by (rule disjI2)\n        with f have False by contradiction\n      }\n      hence \"\\<not>\\<not>((B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D))\" by (rule notI)\n      hence \"(B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D)\" by (rule notnotD)\n    }\n    from a and b and this have \"(B \\<or> A) \\<or> (\\<not>C \\<longrightarrow> D)\" by (rule disjE)\n  }\n  thus ?thesis by (rule impI)\nqed\n  \n        \n    \n  ", "meta": {"author": "SvenWille", "repo": "LogicForwardProofs", "sha": "b03c110b073eb7c34a561fce94b860b14cde75f7", "save_path": "github-repos/isabelle/SvenWille-LogicForwardProofs", "path": "github-repos/isabelle/SvenWille-LogicForwardProofs/LogicForwardProofs-b03c110b073eb7c34a561fce94b860b14cde75f7/src/propLogic/Ex034.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403959948495, "lm_q2_score": 0.8175744828610095, "lm_q1q2_score": 0.759886751105621}}
{"text": "section \\<open>Examples\\<close>\ntheory LLVM_Examples\nimports \n  \"../ds/LLVM_DS_All\"\n  \"../ds/LLVM_DS_Array_List\"\nbegin\n\ntext \\<open>Examples on top of Isabelle-LLVM basic layer. \n  For the verification of more complex algorithms, consider using\n  Isabelle-LLVM with the Refinement Framework, and the Sepref tool.\n  See, e.g., @{file Bin_Search.thy}.\n\\<close>\n\n(* TODO: Parts of this file are incomplete, the examples could me more elaborate! *)\n\nsubsection \\<open>Numeric Algorithms\\<close>\n\nsubsubsection \\<open>Exponentiation\\<close>\n\ndefinition exp :: \"'a::len word \\<Rightarrow> 'b::len word llM\" where [llvm_code]: \"exp r \\<equiv> doM {\n  a \\<leftarrow> ll_const (unsigned 1);\n  (a,r) \\<leftarrow> llc_while \n    (\\<lambda>(a,r). doM { ll_icmp_ult (unsigned 0) r}) \n    (\\<lambda>(a,r). doM {\n      return (a*unsigned 2,r-unsigned 1)\n    })\n    (a,r);\n  return a\n}\"\n\nabbreviation exp32::\"32 word \\<Rightarrow> 32 word llM\" where \"exp32 \\<equiv> exp\"\nabbreviation exp64::\"64 word \\<Rightarrow> 64 word llM\" where \"exp64 \\<equiv> exp\"\n\nexport_llvm \n  exp32 is \"uint32_t exp32 (uint32_t)\" \n  exp64 is \"uint64_t exp64 (uint64_t)\" \n  file \"code/exp.ll\"\n\nlemma exp_aux1: \n  assumes \"2 ^ nat k < (N::int)\" \"t \\<le> k\" \"0 < t\" \n  shows \"2 * 2 ^ nat (k - t) < N\"\nproof -\n  have \"\\<lbrakk>2 ^ k < N; 0 < t; t \\<le> k\\<rbrakk> \\<Longrightarrow> 2 * 2 ^ (k - t) < (N::int)\" for k t :: nat\n    by (metis Suc_leI diff_less less_le_trans not_less power.simps(2) power_increasing_iff rel_simps(49) semiring_norm(76))\n  with assms show ?thesis\n    by (auto simp add: nat_diff_distrib' dest!: nat_mono simp flip: zero_less_nat_eq)\nqed  \n  \nlemma exp_aux2:  \"\\<lbrakk>t \\<le> k; 0 < t\\<rbrakk> \\<Longrightarrow> nat (1+k-t) = Suc (nat (k-t))\" by simp\n\nlemma exp_correct:\n  assumes \"LENGTH('b::len) \\<ge> 2\"\n  shows \"llvm_htriple \n    (\\<upharpoonleft>uint.assn k (ki::'a::len word) ** \\<up>(2^nat k \\<in> uints LENGTH('b))) \n    (exp ki) \n    (\\<lambda>r::'b word. \\<upharpoonleft>uint.assn (2^nat k) r ** \\<upharpoonleft>uint.assn k ki)\"\n  unfolding exp_def\n  apply (rewrite annotate_llc_while[where \n    I=\"\\<lambda>(ai,ri) t. EXS a r. \\<upharpoonleft>uint.assn a ai ** \\<upharpoonleft>uint.assn r ri ** \\<up>\\<^sub>d( 0\\<le>r \\<and> r\\<le>k \\<and> a = 2^nat (k-r) ) ** \\<up>\\<^sub>!(t = r)\"\n    and R=\"measure nat\"\n    ])\n  apply vcg_monadify  \n  apply (vcg'; (clarsimp simp: algebra_simps)?)\n  using assms\n  apply (simp_all add: exp_aux1 exp_aux2)\n  done\n\n\ntext \\<open>Executability of semantics inside Isabelle\\<close>\nvalue \"run (exp64 32) llvm_empty_memory\"\n\nsubsubsection \\<open>Euclid's Algorithm\\<close>\n\n                       \ndefinition [llvm_code]: \"euclid (a::'a::len word) b \\<equiv> doM {\n  (a,b) \\<leftarrow> llc_while \n    (\\<lambda>(a,b) \\<Rightarrow> ll_cmp (a \\<noteq> b))\n    (\\<lambda>(a,b) \\<Rightarrow> if (a\\<le>b) then return (a,b-a) else return (a-b,b))\n    (a,b);\n  return a\n}\"\n  \nexport_llvm (debug) (*no_while*) \n  \"euclid :: 64 word \\<Rightarrow> 64 word \\<Rightarrow> 64 word llM\" is \"uint64_t euclid (uint64_t, uint64_t)\"\n  file \"code/euclid.ll\"\n\n  \nlemma gcd_diff1': \"gcd (a::int) (b-a) = gcd a b\"\n  by (metis gcd.commute gcd_diff1)   \n  \n\nlemma \"llvm_htriple \n  (\\<upharpoonleft>uint.assn a\\<^sub>0 ai ** \\<upharpoonleft>uint.assn b\\<^sub>0 bi ** \\<up>\\<^sub>d(0<a\\<^sub>0 \\<and> 0<b\\<^sub>0)) \n  (euclid ai bi) \n  (\\<lambda>ri. \\<upharpoonleft>uint.assn (gcd a\\<^sub>0 b\\<^sub>0) ri)\"\n  unfolding euclid_def\n  apply (rewrite annotate_llc_while[where \n    I=\"\\<lambda>(ai,bi) t. EXS a b. \\<upharpoonleft>uint.assn a ai ** \\<upharpoonleft>uint.assn b bi \n        ** \\<up>\\<^sub>a(t=a+b) ** \\<up>\\<^sub>d(0<a \\<and> 0<b \\<and> gcd a b = gcd a\\<^sub>0 b\\<^sub>0)\" \n    and R=\"measure nat\"  \n  ])\n  apply vcg_monadify\n  apply (vcg'; clarsimp?)\n  apply (simp_all add: gcd_diff1 gcd_diff1')\n  done\n\nsubsubsection \\<open>Fibonacci Numbers\\<close>\n\ndefinition fib :: \"'n::len word \\<Rightarrow> 'n word llM\" where [llvm_code]: \"fib n \\<equiv> REC (\\<lambda>fib' n. \n  if n\\<le>unsigned 1 then return n \n  else doM { \n    n\\<^sub>1 \\<leftarrow> fib' (n-unsigned 1); \n    n\\<^sub>2 \\<leftarrow> fib' (n-unsigned 2); \n    return (n\\<^sub>1+n\\<^sub>2)     \n  }) n\"\n\nabbreviation fib64 :: \"64 word \\<Rightarrow> 64 word llM\" where \"fib64 \\<equiv> fib\"\nexport_llvm thms: fib64\n  \n(* TODO: Arbitrary fixed-point reasoning not yet supported in VCG!\n  set up a rule with pre and post consequence rule, \n  and seplogic-assertions\n\nlemma\n  assumes MONO: \"\\<And>x. M.mono_body (\\<lambda>fa. F fa x)\"\n  assumes \"P x s m\"\n  assumes \"wf R\"\n  assumes \"\\<And>D x s m. \\<lbrakk> P x s m; \\<And>x' s' m'. \\<lbrakk> P x' s' m'; (m',m)\\<in>R \\<rbrakk> \\<Longrightarrow> wp (D x') Q s' \\<rbrakk> \\<Longrightarrow> wp (F D x) Q s\"\n  shows \"wp (REC F x) Q s\"\n  using assms(3,2)\n  apply (induction m arbitrary: x s rule: wf_induct_rule)\n  apply (subst REC_unfold) apply simp apply (rule MONO)\n  using assms(4) by simp\n  \n  \n\nlemma \"llvm_htriple (\\<upharpoonleft>uint.assn n ni) (fib ni) (\\<lambda>ri. \\<upharpoonleft>uint.assn x ri)\"\n  unfolding fib_def\n  apply vcg_monadify\n  apply vcg\n  find_theorems wp REC\n*)\n  \nprepare_code_thms (LLVM) [code] fib_def  (* Set up code equation. Required to execute semantics in Isabelle. *)\n\nvalue \"map (\\<lambda>n. run (fib64 n) (LLVM_MEMORY (MEMORY []))) [0,1,2,3]\"\n\n\n(*\nlemmas [named_ss llvm_inline cong] = refl[of \"numeral _\"]\n*)\n\ndefinition test :: \"64 word \\<Rightarrow> 64 word \\<Rightarrow> _ llM\"\nwhere [llvm_code]: \"test a b \\<equiv> doM {\n\n  return (a,b) \n}\"\n\nML_val \\<open>\n  local open LLC_Preprocessor\n    val ctxt = @{context}\n  in\n\n    val thm = @{thm test_def}\n      |> cthm_inline ctxt\n      |> cthm_monadify ctxt\n  \n  end\n\\<close>\n\n\nfind_theorems llc_while\n\nlemma \"foo (test)\"\n  unfolding test_def\n  apply (simp named_ss llvm_inline:)\n  oops\n\nexport_llvm test\n\n\n\ntext \\<open>Example and Regression Tests using LLVM-VCG directly, \ni.e., without Refinement Framework\\<close>\n\nsubsection \\<open>Custom and Named Structures\\<close>\ntypedef ('a,'b) my_pair = \"UNIV :: ('a::llvm_rep \\<times> 'b::llvm_rep) set\" by simp\n\nlemmas my_pair_bij[simp] = Abs_my_pair_inverse[simplified] Rep_my_pair_inverse\n\ninstantiation my_pair :: (llvm_rep,llvm_rep)llvm_rep\nbegin\n  definition \"from_val_my_pair \\<equiv> Abs_my_pair o from_val\"\n  definition \"to_val_my_pair \\<equiv> to_val o Rep_my_pair\"\n  definition [simp]: \"struct_of_my_pair (_:: ('a,'b)my_pair itself) \\<equiv> struct_of TYPE('a \\<times> 'b)\"\n  definition \"init_my_pair \\<equiv> Abs_my_pair init\"\n\n  instance\n    apply standard\n    unfolding from_val_my_pair_def to_val_my_pair_def struct_of_my_pair_def init_my_pair_def\n    apply (auto simp: to_val_word_def init_zero)\n    done\n\nend\n\ndefinition \"my_sel_fst \\<equiv> fst o Rep_my_pair\"\ndefinition \"my_sel_snd \\<equiv> snd o Rep_my_pair\"\n\nlemma my_pair_to_val[ll_to_val]: \"to_val x = llvm_struct [to_val (my_sel_fst x), to_val (my_sel_snd x)]\"\n  by (auto simp: my_sel_fst_def my_sel_snd_def to_val_my_pair_def to_val_prod)\n\n\ndefinition my_fst :: \"('a::llvm_rep,'b::llvm_rep)my_pair \\<Rightarrow> 'a llM\" where [llvm_inline]: \"my_fst x \\<equiv> ll_extract_value x 0\"\ndefinition my_snd :: \"('a::llvm_rep,'b::llvm_rep)my_pair \\<Rightarrow> 'b llM\" where [llvm_inline]: \"my_snd x \\<equiv> ll_extract_value x 1\"\ndefinition my_ins_fst :: \"('a::llvm_rep,'b::llvm_rep)my_pair \\<Rightarrow> 'a \\<Rightarrow> ('a,'b)my_pair llM\" where [llvm_inline]: \"my_ins_fst x a \\<equiv> ll_insert_value x a 0\"\ndefinition my_ins_snd :: \"('a::llvm_rep,'b::llvm_rep)my_pair \\<Rightarrow> 'b \\<Rightarrow> ('a,'b)my_pair llM\" where [llvm_inline]: \"my_ins_snd x a \\<equiv> ll_insert_value x a 1\"\ndefinition my_gep_fst :: \"('a::llvm_rep,'b::llvm_rep)my_pair ptr \\<Rightarrow> 'a ptr llM\" where [llvm_inline]: \"my_gep_fst x \\<equiv> ll_gep_struct x 0\"\ndefinition my_gep_snd :: \"('a::llvm_rep,'b::llvm_rep)my_pair ptr \\<Rightarrow> 'b ptr llM\" where [llvm_inline]: \"my_gep_snd x \\<equiv> ll_gep_struct x 1\"\n\n\ndefinition [llvm_code]: \"add_add (a::_ word) \\<equiv> doM {\n  x \\<leftarrow> ll_add a a;\n  x \\<leftarrow> ll_add x x;\n  return x\n}\"\n\ndefinition [llvm_code]: \"test_named (a::32 word) (b::64 word) \\<equiv> doM {\n  a \\<leftarrow> add_add a;\n  b \\<leftarrow> add_add b;\n  let n = (init::(32 word,64 word)my_pair);\n  a \\<leftarrow> my_fst n;\n  b \\<leftarrow> my_snd n;\n  n \\<leftarrow> my_ins_fst n init;\n  n \\<leftarrow> my_ins_snd n init;\n  \n  p \\<leftarrow> ll_malloc TYPE((1 word,16 word)my_pair) (1::64 word);\n  p1 \\<leftarrow> my_gep_fst p;\n  p2 \\<leftarrow> my_gep_snd p;\n  \n  return b\n}\"\n\nlemma my_pair_id_struct[ll_identified_structures]: \"ll_is_identified_structure ''my_pair'' TYPE((_,_)my_pair)\"\n  unfolding ll_is_identified_structure_def\n  apply (simp add: llvm_s_struct_def)\n  done\n\nthm ll_identified_structures\n\n\n\n(*lemma [ll_is_pair_type_thms]: \"ll_is_pair_type False TYPE(my_pair) TYPE(64 word) TYPE(32 word)\"\n  unfolding ll_is_pair_type_def\n  by auto\n*)  \n\nexport_llvm (debug) test_named file \"code/test_named.ll\"\n\ndefinition test_foo :: \"(64 word \\<times> 64 word ptr) ptr \\<Rightarrow> 64 word \\<Rightarrow> 64 word llM\" \n  where [llvm_code]:\n  \"test_foo a b \\<equiv> return 0\"\n\n  export_llvm test_foo is \\<open>int64_t test_foo(larray_t*, elem_t)\\<close> \n  defines \\<open>\n    typedef uint64_t elem_t;\n    typedef struct {\n      int64_t len;\n      elem_t *data;\n    } larray_t;\n  \\<close>\n\n\nsubsubsection \\<open>Linked List\\<close>\n\ndatatype 'a list_cell = CELL (data: 'a) (\"next\": \"'a list_cell ptr\")\n\ninstantiation list_cell :: (llvm_rep)llvm_rep\nbegin\n  definition \"to_val_list_cell \\<equiv> \\<lambda>CELL a b \\<Rightarrow> llvm_struct [to_val a, to_val b]\"\n  definition \"from_val_list_cell p \\<equiv> case llvm_the_struct p of [a,b] \\<Rightarrow> CELL (from_val a) (from_val b)\"\n  definition [simp]: \"struct_of_list_cell (_::(('a) list_cell) itself) \\<equiv> llvm_s_struct [struct_of TYPE('a), struct_of TYPE('a list_cell ptr)]\"\n  definition [simp]: \"init_list_cell ::('a) list_cell \\<equiv> CELL init init\"\n  \n  instance\n    apply standard\n    unfolding from_val_list_cell_def to_val_list_cell_def struct_of_list_cell_def init_list_cell_def\n    (* TODO: Clean proof here, not breaking abstraction barriers! *)\n    apply (auto simp: to_val_word_def init_zero fun_eq_iff split: list_cell.splits)\n    apply (smt (z3) from_to_id' list.case(1) list.case(2) list_cell.sel(1) list_cell.sel(2) llvm_the_struct_inv struct_of_prod_def struct_of_ptr_def to_from_id to_val_prod)\n    by (metis init_ptr_def init_zero llvm_zero_initializer_simps(2) struct_of_ptr_def)\n    \n\nend\n\nlemma to_val_list_cell[ll_to_val]: \"to_val x = llvm_struct [to_val (data x), to_val (next x)]\"\n  apply (cases x)\n  apply (auto simp: to_val_list_cell_def)\n  done\n\nlemma [ll_identified_structures]: \"ll_is_identified_structure ''list_cell'' TYPE(_ list_cell)\"  \n  unfolding ll_is_identified_structure_def\n  by (simp add: llvm_s_struct_def)\n\n  \nfind_theorems \"prod_insert_fst\"\n\nlemma cell_insert_value:\n  \"ll_insert_value (CELL x n) x' 0 = return (CELL x' n)\"\n  \"ll_insert_value (CELL x n) n' (Suc 0) = return (CELL x n')\"\n\n  apply (simp_all add: ll_insert_value_def Let_def checked_from_val_def \n                to_val_list_cell_def from_val_list_cell_def)\n  done\n\nlemma cell_extract_value:\n  \"ll_extract_value (CELL x n) 0 = return x\"  \n  \"ll_extract_value (CELL x n) (Suc 0) = return n\"  \n  apply (simp_all add: ll_extract_value_def Let_def checked_from_val_def \n                to_val_list_cell_def from_val_list_cell_def)\n  done\n  \nfind_theorems \"ll_insert_value\"\n\nlemma inline_return_cell[llvm_inline]: \"return (CELL a x) = doM {\n    r \\<leftarrow> ll_insert_value init a 0;\n    r \\<leftarrow> ll_insert_value r x 1;\n    return r\n  }\"\n  apply (auto simp: cell_insert_value)\n  done\n\nlemma inline_cell_case[llvm_inline]: \"(case x of (CELL a n) \\<Rightarrow> f a n) = doM {\n  a \\<leftarrow> ll_extract_value x 0;\n  n \\<leftarrow> ll_extract_value x 1;\n  f a n\n}\"  \n  apply (cases x)\n  apply (auto simp: cell_extract_value)\n  done\n  \nlemma inline_return_cell_case[llvm_inline]: \"doM {return (case x of (CELL a n) \\<Rightarrow> f a n)} = doM {\n  a \\<leftarrow> ll_extract_value x 0;\n  n \\<leftarrow> ll_extract_value x 1;\n  return (f a n)\n}\"  \n  apply (cases x)\n  apply (auto simp: cell_extract_value)\n  done\n\ndefinition [llvm_code]: \"llist_append x l \\<equiv> return (CELL x l)\"\ndefinition [llvm_code]: \"llist_split l \\<equiv> doM {\n  c \\<leftarrow> ll_load l;\n  return (case c of CELL x n \\<Rightarrow> (x,n))\n}\"  \n\nexport_llvm \n  \"llist_append::1 word \\<Rightarrow>1 word list_cell ptr \\<Rightarrow> _ llM\"\n  file \"code/list_cell.ll\"\n\n  \nsubsection \\<open>Array List Examples\\<close>\n\ndefinition [llvm_code]: \"cr_big_al (n::64 word) \\<equiv> doM {\n  a \\<leftarrow> arl_new TYPE(64 word) TYPE(64);\n  (_,a) \\<leftarrow> llc_while \n    (\\<lambda>(n,a). ll_icmp_ult (signed_nat 0) n) \n    (\\<lambda>(n,a). doM { a \\<leftarrow> arl_push_back a n; n \\<leftarrow> ll_sub n (signed_nat 1); return (n,a) }) \n    (n,a);\n  \n  (_,s) \\<leftarrow> llc_while \n    (\\<lambda>(n,s). ll_icmp_ult (signed_nat 0) n) \n    (\\<lambda>(n,s). doM { n \\<leftarrow> ll_sub n (signed_nat 1); x \\<leftarrow> arl_nth a n; s\\<leftarrow>ll_add x s; return (n,s) }) \n    (n,signed_nat 0);\n    \n  return s    \n}\"\n\ndeclare Let_def[llvm_inline]\nexport_llvm (debug) cr_big_al is \"cr_big_al\" file \"code/cr_big_al.ll\"\n\n\nsubsection \\<open>Sorting\\<close>\n\ndefinition [llvm_inline]: \"llc_for_range l h c s \\<equiv> doM {\n  (_,s) \\<leftarrow> llc_while (\\<lambda>(i,s). ll_cmp (i<h)) (\\<lambda>(i,s). doM { \n    s\\<leftarrow>c i s; \n    i \\<leftarrow> ll_add i 1; \n    return (i,s)}\n  ) (l,s);\n  return s\n}\"\n\nlemma llc_for_range_rule:\n  assumes [vcg_rules]: \"\\<And>i ii si. llvm_htripleF F \n      (\\<upharpoonleft>snat.assn i ii ** \\<up>\\<^sub>d(lo\\<le>i \\<and> i<hi) ** I i si) \n      (c ii si) \n      (\\<lambda>si. I (i+1) si)\"\n  shows \"llvm_htripleF F\n      (\\<upharpoonleft>snat.assn lo loi ** \\<upharpoonleft>snat.assn hi hii ** \\<up>(lo\\<le>hi) ** I lo si)\n      (llc_for_range loi hii c si)\n      (\\<lambda>si. I hi si)\"\n  unfolding llc_for_range_def\n  apply (rewrite at 1 to \"signed_nat 1\" signed_nat_def[symmetric])\n  apply (rewrite annotate_llc_while[where \n    I=\"\\<lambda>(ii,si) t. EXS i. \\<upharpoonleft>snat.assn i ii ** \\<up>(lo\\<le>i \\<and> i\\<le>hi) ** \\<up>\\<^sub>!(t=hi-i) ** I i si\" \n    and R=\"measure id\"])\n  apply vcg_monadify\n  apply vcg'\n  done\n  \ndefinition llc_for_range_annot :: \"(nat \\<Rightarrow> 'b::llvm_rep \\<Rightarrow> ll_assn)\n  \\<Rightarrow> 'a::len word \\<Rightarrow> 'a word \\<Rightarrow> ('a word \\<Rightarrow> 'b \\<Rightarrow> 'b llM) \\<Rightarrow> 'b \\<Rightarrow> 'b llM\"\n  where [llvm_inline]: \"llc_for_range_annot I \\<equiv> llc_for_range\"  \ndeclare [[vcg_const \"llc_for_range_annot I\"]]\n  \nlemmas annotate_llc_for_range = llc_for_range_annot_def[symmetric]\n\nlemmas llc_for_range_annot_rule[vcg_rules] \n  = llc_for_range_rule[where I=I, unfolded annotate_llc_for_range[of I]] for I\n\n\n(* TODO: Move *)\nlemma sep_red_idx_setI:  \n  assumes \"\\<And>I I'. I\\<inter>I'={} \\<Longrightarrow> A (I\\<union>I') = (A I ** A I')\"\n  shows \"is_sep_red (A (I-I')) (A (I'-I)) (A I) (A I')\"\nproof -\n  define I\\<^sub>1 where \"I\\<^sub>1 \\<equiv> I-I'\"\n  define I\\<^sub>2 where \"I\\<^sub>2 \\<equiv> I'-I\"\n  define C where \"C \\<equiv> I\\<inter>I'\"\n\n  have S1: \"I = I\\<^sub>1 \\<union> C\" \"I'=I\\<^sub>2 \\<union> C\" and S2: \"I-I' = I\\<^sub>1\" \"I'-I=I\\<^sub>2\" and DJ: \"I\\<^sub>1\\<inter>C={}\" \"I\\<^sub>2\\<inter>C={}\"\n    unfolding I\\<^sub>1_def I\\<^sub>2_def C_def by auto\n\n  show ?thesis  \n    apply (rule is_sep_redI)\n    apply (simp only: S2; simp only: S1)\n    apply (auto simp: DJ assms)\n    by (simp add: conj_entails_mono sep_conj_left_commute)\n    \nqed    \n\nlemma sep_set_img_reduce:\n  \"is_sep_red (\\<Union>*i\\<in>I-I'. f i) (\\<Union>*i\\<in>I'-I. f i) (\\<Union>*i\\<in>I. f i) (\\<Union>*i\\<in>I'. f i)\"\n  by (rule sep_red_idx_setI) simp\n\n(* TODO: Move *)  \n  \nlemma is_sep_red_false[simp]: \"is_sep_red P' Q' sep_false Q\"\n  by (auto simp: is_sep_red_def)\n\n  \n(* TODO: Move *)  \nlemma entails_pre_pure[sep_algebra_simps]: \n  \"(\\<up>\\<Phi> \\<turnstile> Q) \\<longleftrightarrow> (\\<Phi> \\<longrightarrow> \\<box>\\<turnstile>Q)\"  \n  \"(\\<up>\\<Phi>**P \\<turnstile> Q) \\<longleftrightarrow> (\\<Phi> \\<longrightarrow> P\\<turnstile>Q)\"  \n  by (auto simp: entails_def sep_algebra_simps pred_lift_extract_simps)\n  \n  \n  \ndefinition \"lstr_assn A I \\<equiv> mk_assn (\\<lambda>as cs. \\<up>(length cs = length as \\<and> (\\<forall>i\\<in>I. i<length as)) ** (\\<Union>*i\\<in>I. \\<upharpoonleft>A (as!i) (cs!i)))\"\n\nlemma lstr_assn_union: \"I\\<inter>I'={} \\<Longrightarrow> \n  \\<upharpoonleft>(lstr_assn A (I\\<union>I')) as cs = (\\<upharpoonleft>(lstr_assn A I) as cs ** \\<upharpoonleft>(lstr_assn A I') as cs)\"\n  by (auto simp: lstr_assn_def sep_algebra_simps pred_lift_extract_simps)\n\n  \nlemma lstr_assn_red: \"is_sep_red \n  (\\<upharpoonleft>(lstr_assn A (I-I')) as cs) (\\<upharpoonleft>(lstr_assn A (I'-I)) as cs)\n  (\\<upharpoonleft>(lstr_assn A I) as cs) (\\<upharpoonleft>(lstr_assn A I') as cs)\"  \n  by (rule sep_red_idx_setI) (simp add: lstr_assn_union)\n\nlemma lstr_assn_red': \"PRECOND (SOLVE_AUTO (I\\<inter>I'\\<noteq>{})) \\<Longrightarrow> is_sep_red \n  (\\<upharpoonleft>(lstr_assn A (I-I')) as cs) (\\<upharpoonleft>(lstr_assn A (I'-I)) as cs)\n  (\\<upharpoonleft>(lstr_assn A I) as cs) (\\<upharpoonleft>(lstr_assn A I') as cs)\"  \n  by (rule sep_red_idx_setI) (simp add: lstr_assn_union)\n  \n    \nlemma lstr_assn_singleton: \"\\<upharpoonleft>(lstr_assn A {i}) as cs = (\\<up>(length cs = length as \\<and> i<length as) ** \\<upharpoonleft>A (as!i) (cs!i))\"  \n  by (auto simp: lstr_assn_def sep_algebra_simps pred_lift_extract_simps)\n  \nlemma lstr_assn_empty: \"\\<upharpoonleft>(lstr_assn A {}) as cs = \\<up>(length cs = length as)\"  \n  by (auto simp: lstr_assn_def sep_algebra_simps pred_lift_extract_simps)\n    \nlemma lstr_assn_out_of_range: \n  \"\\<not>(length cs = length as \\<and> (\\<forall>i\\<in>I. i<length as)) \\<Longrightarrow> \\<upharpoonleft>(lstr_assn A I) as cs = sep_false\"  \n  \"i\\<in>I \\<Longrightarrow> \\<not>i<length as \\<Longrightarrow> \\<upharpoonleft>(lstr_assn A I) as cs = sep_false\"  \n  \"i\\<in>I \\<Longrightarrow> \\<not>i<length cs \\<Longrightarrow> \\<upharpoonleft>(lstr_assn A I) as cs = sep_false\"  \n  \"length cs \\<noteq> length as \\<Longrightarrow> \\<upharpoonleft>(lstr_assn A I) as cs = sep_false\"  \n  by (auto simp: lstr_assn_def sep_algebra_simps pred_lift_extract_simps)\n  \n  \n  \nlemma lstr_assn_idx_left[fri_red_rules]:\n  assumes \"PRECOND (SOLVE_AUTO (length cs = length as \\<and> i\\<in>I \\<and> i<length as))\"\n  shows \"is_sep_red \\<box> (\\<upharpoonleft>(lstr_assn A (I-{i})) as cs) (\\<upharpoonleft>A ai (cs!i)) (\\<upharpoonleft>(lstr_assn A I) (as[i:=ai]) cs)\"\nproof -\n\n  from assms have [simp]: \"{i} - I = {}\" \"length cs = length as\" \"i<length as\" and \"i\\<in>I\" \n    unfolding vcg_tag_defs by auto\n\n  have \"(\\<Union>*i\\<in>I - {i}. \\<upharpoonleft>A (as ! i) (cs ! i)) \n    = (\\<Union>*ia\\<in>I - {i}. \\<upharpoonleft>A (as[i := ai] ! ia) (cs ! ia))\"\n    by (rule sep_set_img_cong) auto\n  then have 1: \"\\<upharpoonleft>(lstr_assn A (I-{i})) as cs = \\<upharpoonleft>(lstr_assn A (I-{i})) (as[i:=ai]) cs\"\n    by (auto simp: lstr_assn_def sep_algebra_simps pred_lift_extract_simps)\n  \n  show ?thesis\n    using lstr_assn_red[of A \"{i}\" I \"as[i:=ai]\" cs]\n    by (simp add: 1 lstr_assn_singleton lstr_assn_empty sep_algebra_simps)\n    \nqed\n  \nlemma lstr_assn_idx_right[fri_red_rules]:\n  assumes \"PRECOND (SOLVE_AUTO (i\\<in>I))\"\n  shows \"is_sep_red (\\<upharpoonleft>(lstr_assn A (I-{i})) as cs) \\<box> (\\<upharpoonleft>(lstr_assn A I) as cs) (\\<upharpoonleft>A (as!i) (cs!i))\"\nproof -  \n  from assms have [simp]: \"{i} - I = {}\" \"i\\<in>I\" \n    unfolding vcg_tag_defs by auto\n  \n  show ?thesis\n    using lstr_assn_red[of A I \"{i}\" \"as\" cs]\n    apply (cases \"length cs = length as \\<and> (\\<forall>i\\<in>I. i<length as )\"; simp add: lstr_assn_out_of_range)\n    apply (simp add: lstr_assn_singleton lstr_assn_empty sep_algebra_simps)\n    done\nqed  \n  \n(* TODO: Move *)\nlemma is_pure_lst_assn[is_pure_rule]: \"is_pure A \\<Longrightarrow> is_pure (lstr_assn A I)\"\n  unfolding lstr_assn_def is_pure_def\n  by (auto simp: sep_is_pure_assn_conjI sep_is_pure_assn_imgI)\n  \nlemma vcg_prep_lstr_assn: (* TODO: Need mechanism to recursively prepare pure parts of A! *)\n  \"pure_part (\\<upharpoonleft>(lstr_assn A I) as cs) \\<Longrightarrow> length cs = length as \\<and> (\\<forall>i\\<in>I. i<length as)\"\n  by (auto simp: lstr_assn_def sep_algebra_simps dest: pure_part_split_conj)\n\n\n(* TODO: Move *)  \nlemma pure_fri_auto_rule: \"PRECOND (SOLVE_AUTO (\\<flat>\\<^sub>pA a c)) \\<Longrightarrow> \\<box> \\<turnstile> \\<upharpoonleft>\\<^sub>pA a c\"\n  using pure_fri_rule\n  unfolding vcg_tag_defs .\n\n\nlemma pure_part_prepD: \"pure_part (\\<Union>*i\\<in>I. f i) \\<Longrightarrow> \\<forall>i\\<in>I. pure_part (f i)\"\n  by (metis Set.set_insert pure_part_split_conj sep_set_img_insert)\n\nlemma pure_part_imp_pure_assn: \"is_pure A \\<Longrightarrow> pure_part (\\<upharpoonleft>A a c) \\<Longrightarrow> \\<flat>\\<^sub>pA a c\"\n  by (simp add: extract_pure_assn)  \n  \n  \n    \ndefinition \"aa_assn A \\<equiv> mk_assn (\\<lambda>as p. EXS cs. \n  \\<upharpoonleft>array_assn cs p ** \\<up>(is_pure A \\<and> list_all2 (\\<flat>\\<^sub>pA) as cs))\"  \n\n   \nlemma aa_nth_rule[vcg_rules]: \"llvm_htriple \n  (\\<upharpoonleft>(aa_assn A) as p ** \\<upharpoonleft>snat.assn i ii ** \\<up>\\<^sub>d(i<length as))\n  (array_nth p ii)\n  (\\<lambda>c. \\<upharpoonleft>(aa_assn A) as p ** \\<upharpoonleft>A (as!i) c)\"\n  unfolding aa_assn_def\n  apply (clarsimp simp: list_all2_conv_all_nth)\n  supply pure_fri_auto_rule[fri_rules]\n  apply vcg\n  done  \n\nlemma aa_upd_rule[vcg_rules]: \"llvm_htriple \n  (\\<upharpoonleft>(aa_assn A) as p ** \\<upharpoonleft>snat.assn i ii ** \\<upharpoonleft>A a c ** \\<up>\\<^sub>d(i<length as))\n  (array_upd p ii c)\n  (\\<lambda>c. \\<upharpoonleft>(aa_assn A) (as[i:=a]) p)\"\nproof (cases \"is_pure A\")\n  case [is_pure_rule,simp]: True\n  (*note thin_dr_pure[vcg_prep_external_drules del]*)\n  note [simp] = nth_list_update pure_part_imp_pure_assn\n  \n  show ?thesis\n    unfolding aa_assn_def list_all2_conv_all_nth\n    supply pure_fri_auto_rule[fri_rules]\n    apply vcg\n    done\nqed (clarsimp simp: aa_assn_def)      \n\n\n\n\ndefinition [llvm_inline]: \"qs_swap A i j \\<equiv> doM {\n  llc_if (ll_cmp' (i\\<noteq>j)) (doM {\n    x \\<leftarrow> array_nth A i;\n    y \\<leftarrow> array_nth A j;\n    array_upd A i y;\n    array_upd A j x;\n    return ()\n  }) (return ())\n}\"\n\ndefinition [llvm_code]: \"qs_partition A lo hi \\<equiv> doM {\n  hi \\<leftarrow> ll_sub hi (signed_nat 1);\n  pivot \\<leftarrow> array_nth A hi;\n  let i = lo;\n  \n  i \\<leftarrow> llc_for_range lo hi (\\<lambda>j i. doM {\n    Aj \\<leftarrow> array_nth A j;\n    if Aj < pivot then doM {\n      qs_swap A i j;\n      i \\<leftarrow> ll_add i (signed_nat 1);\n      return i\n    } else return i\n  }) i;\n  \n  qs_swap A i hi;\n  return i\n}\"\n\n\ndefinition [llvm_code]: \"qs_quicksort A lo hi \\<equiv> doM {\n  REC (\\<lambda>quicksort (lo,hi). doM {\n    if lo < hi then doM {\n      p \\<leftarrow> qs_partition A lo hi;\n      quicksort (lo, p-1);\n      quicksort (p+1,hi)\n    } else\n      return ()\n  \n  }) (lo,hi);\n  return ()\n}\"\n\n(* TODO: Prepare-code-thms after inlining! *)\n(* prepare_code_thms  qs_partition_def[unfolded llc_for_range_def] *)\n\n\n(*prepare_code_thms [llvm_code] qs_quicksort_def*)\n\n\nllvm_deps foo: \"qs_quicksort :: 64 word ptr \\<Rightarrow> 64 word \\<Rightarrow> 64 word \\<Rightarrow> unit llM\"\n\n\nexport_llvm \"qs_quicksort :: 64 word ptr \\<Rightarrow> 64 word \\<Rightarrow> 64 word \\<Rightarrow> unit llM\" is \"qs_quicksort\"\n  file \\<open>code/qs_quicksort.ll\\<close>\n\n  \nlemma qs_swap_aa_rule[vcg_rules]: \"llvm_htriple \n  (\\<upharpoonleft>(aa_assn A) xs p ** \\<upharpoonleft>snat.assn i ii ** \\<upharpoonleft>snat.assn j ji ** \\<up>\\<^sub>d(i<length xs \\<and> j<length xs))\n  (qs_swap p ii ji)\n  (\\<lambda>_. \\<upharpoonleft>(aa_assn A) (swap xs i j) p)\"  \n  unfolding qs_swap_def swap_def\n  apply vcg_monadify\n  apply vcg'\n  done\n  \nlemma qs_swap_rule[vcg_rules]: \"llvm_htriple \n  (\\<upharpoonleft>array_assn xs A ** \\<upharpoonleft>snat.assn i ii ** \\<upharpoonleft>snat.assn j ji ** \\<up>\\<^sub>d(i<length xs \\<and> j<length xs))\n  (qs_swap A ii ji)\n  (\\<lambda>_. \\<upharpoonleft>array_assn (swap xs i j) A)\"  \n  unfolding qs_swap_def swap_def\n  apply vcg_monadify\n  apply vcg'\n  done\n  \n\n  \n    \nfun at_idxs :: \"'a list \\<Rightarrow> nat list \\<Rightarrow> 'a list\" (infixl \"\\<exclamdown>\" 100) where\n  \"at_idxs xs [] = []\"\n| \"at_idxs xs (i#is) = xs!i # at_idxs xs is\"  \n  \nlemma at_idxs_eq_map_nth: \"at_idxs xs is = map (nth xs) is\"\n  by (induction \"is\") auto\n\nlemma at_idxs_append[simp]: \"at_idxs xs (is\\<^sub>1@is\\<^sub>2) = at_idxs xs is\\<^sub>1 @ at_idxs xs is\\<^sub>2\"  \n  by (induction is\\<^sub>1) auto\n  \nlemma at_idxs_ran_zero: \"hi\\<le>length xs \\<Longrightarrow> at_idxs xs [0..<hi] = take hi xs\"  \n  by (induction hi) (auto simp: take_Suc_conv_app_nth)\n  \nlemma at_idxs_slice: \"hi\\<le>length xs \\<Longrightarrow> at_idxs xs [lo..<hi] = Misc.slice lo hi xs\"\n  apply (induction lo)\n  apply (auto simp: Misc.slice_def at_idxs_ran_zero)\n  by (simp add: at_idxs_eq_map_nth drop_take map_nth_upt_drop_take_conv)\n\n(* TODO: Move *)     \nlemma pure_part_split_img:\n  assumes \"pure_part (\\<Union>*i\\<in>I. f i)\"  \n  shows \"(\\<forall>i\\<in>I. pure_part (f i))\"  \nproof (cases \"finite I\")\n  assume \"finite I\"\n  then show ?thesis using assms\n    by (induction) (auto dest: pure_part_split_conj)\nnext\n  assume \"infinite I\" with assms show ?thesis by simp    \nqed\n\n  \nlemma \"pure_part (\\<upharpoonleft>(lstr_assn A I) as cs) \\<Longrightarrow> (length cs = length as) \\<and> (\\<forall>i\\<in>I. i<length as \\<and> pure_part (\\<upharpoonleft>A (as!i) (cs!i)))\"\n  by (auto simp: lstr_assn_def is_pure_def list_all2_conv_all_nth sep_algebra_simps \n    dest!: pure_part_split_conj pure_part_split_img)\n\n(* TODO: Move *)    \nlemma lstr_assn_insert: \"i\\<notin>I \\<Longrightarrow> \\<upharpoonleft>(lstr_assn A (insert i I)) as cs = (\\<up>(i < length as) ** \\<upharpoonleft>A (as!i) (cs!i) ** \\<upharpoonleft>(lstr_assn A I) as cs)\"\n  by (auto simp: lstr_assn_def sep_algebra_simps pred_lift_extract_simps)\n    \n\nlemma fri_lstr_pure_rl[fri_rules]:\n  \"PRECOND (SOLVE_ASM (\\<flat>\\<^sub>p(lstr_assn A I) as cs)) \\<Longrightarrow> PRECOND (SOLVE_AUTO (i\\<in>I)) \\<Longrightarrow> \\<box> \\<turnstile> \\<upharpoonleft>\\<^sub>pA (as!i) (cs!i)\"\n  unfolding vcg_tag_defs\n  by (auto simp: dr_assn_pure_asm_prefix_def lstr_assn_insert dr_assn_pure_prefix_def\n    simp: sep_algebra_simps\n    elim!: Set.set_insert dest!: pure_part_split_conj)\n  \n\nlemma length_swap[simp]: \"length (swap xs i j) = length xs\"\n  by (auto simp: swap_def)    \n\n  \nlemma at_idxs_cong:\n  assumes \"\\<And>i. i\\<in>List.set I \\<Longrightarrow> xs!i = ys!i\"\n  shows \"xs\\<exclamdown>I = ys\\<exclamdown>I\"\n  using assms \n  apply (induction I)\n  apply auto\n  done\n    \nlemma at_idxs_upd_out[simp]: \"i\\<notin>List.set I \\<Longrightarrow> xs[i:=x] \\<exclamdown> I = xs\\<exclamdown>I\"\n  by (auto intro: at_idxs_cong simp: nth_list_update')\n  \nlemma at_idxs_swap_out[simp]: \"i\\<notin>List.set I \\<Longrightarrow> j\\<notin>List.set I \\<Longrightarrow> (swap xs i j)\\<exclamdown>I = xs\\<exclamdown>I\"  \n  unfolding swap_def\n  by auto\n\nlemma mset_swap'[simp]: \"\\<lbrakk>i<length xs; j<length xs\\<rbrakk> \\<Longrightarrow> mset (swap xs i j) = mset xs\"\n  unfolding swap_def\n  apply (auto simp: mset_swap)\n  done  \n  \n  \nfind_theorems at_idxs Misc.slice  \nfind_theorems mset nth    \n\n\n        \nlemma \"llvm_htriple \n  (\\<upharpoonleft>(aa_assn snat.assn) as A ** \\<upharpoonleft>snat.assn lo loi  ** \\<upharpoonleft>snat.assn hi hii \n    ** \\<up>\\<^sub>d(lo<hi \\<and> hi\\<le>length as)) \n  (qs_partition A loi hii)\n  (\\<lambda>pi. EXS as' p. \\<upharpoonleft>(aa_assn snat.assn) as' A ** \\<upharpoonleft>snat.assn p pi \n    ** \\<up>( lo\\<le>p \\<and> p<hi \n        \\<and> length as' = length as\n        \\<and> as'\\<exclamdown>[0..<lo] = as\\<exclamdown>[0..<lo]     \n        \\<and> as'\\<exclamdown>[hi..<length as] = as\\<exclamdown>[hi..<length as]\n        \\<and> mset (as') = mset (as)\n        \\<and> (\\<forall>i\\<in>{lo..<p}. as!i \\<le> as!p)\n        \\<and> (\\<forall>i\\<in>{p..<hi}. as!p \\<le> as!i)\n         ))\"\n  unfolding qs_partition_def\n  apply (rewrite annotate_llc_for_range[where \n    I=\"\\<lambda>j ii. EXS i as'. \\<upharpoonleft>snat.assn i ii ** \\<upharpoonleft>(aa_assn snat.assn) as' A \n      ** \\<up>(length as'=length as \n        \\<and> lo\\<le>i \\<and> i<hi\n        \\<and> as'\\<exclamdown>[0..<lo] = as\\<exclamdown>[0..<lo]     \n        \\<and> as'\\<exclamdown>[hi..<length as] = as\\<exclamdown>[hi..<length as]\n        \\<and> mset (as') = mset (as)\n      )\n    \n    \"])\n  apply vcg_monadify\n  apply vcg'\n  apply clarsimp_all\n  apply auto\n  prefer 2\n  apply (subst at_idxs_swap_out)\n  apply simp \n  apply simp\n  apply linarith\n  apply simp\n  oops \n(*  \nxxx, ctd here: sharpen invariant!\n  \n    \n  xxx, try \"arr_assn A \\<equiv> array o lst A\"\n  try to set up rules for nth and upd, using a set of externalized indexes (and their intermediate values).\n    supplement frame inference by internalize/externalize rules\n  \n  \n  \n  \n  apply vcg_try_solve\n  apply vcg_try_solve\n  \n  apply vcg_rl back back\n  apply vcg_try_solve\n  apply (fri_dbg_step) back\n  apply vcg_try_solve\n  \n  \n  \n  oops\n  xxx, ctd here: Intro-trule for pure lstr-assn\n  \n  oops\n  xxx, ctd here: The array itself contains data, which needs to be abstracted over!\n    we will need to relate xs!i to some abstract value!\n  \n\n  oops\n  \n  \n  \n  \n  xxx, integrate reduction rules into frame inference!\n  xxx: simplify the resulting set differences during frame inference!\n    Most important: Elimination of empty sets!\n    \n      \n\n\n  xxx, ctd here: Integrate into frame inference  \n    \"cut\" is a bad name for this concept\n        \n        \n  find_theorems sep_set_img  \n    \n  ML_val \\<open>@{term \\<open>\\<Union>*x\\<in>y. p\\<close>}\\<close>  \n    \n  lemma\n    assumes \"\\<upharpoonleft>(lstr_assn A (I-I')) as cs \\<turnstile> \\<upharpoonleft>(lstr_assn A (I'-I)) as cs\"  \n    shows \"\\<upharpoonleft>(lstr_assn A I) as cs \\<turnstile> \\<upharpoonleft>(lstr_assn A I') as cs\"\n    \n    \n    oops\n  xxx, ctd here: do list_assn, with index set. \n  \n  derive rules to split/join those assertions. also rules for pure-case.\n  in practice, let the lstr-assertions fragment, until some rule/frame forces a re-union.\n    \n    \n    \n      \n    \n      \n  thm vcg_frame_erules\n  \n  apply vcg_rl\n         \n         \n  \nterm \"xs\\<exclamdown>[2..<5]\"\n\nfind_consts \"nat \\<Rightarrow> nat \\<Rightarrow> _ list \\<Rightarrow> _ list\"  \n  \n*)  \n  \n  \n\nend\n\n", "meta": {"author": "lammich", "repo": "isabelle_llvm", "sha": "6be37a9c3cae74a1134dbef2979e312abb5f7f42", "save_path": "github-repos/isabelle/lammich-isabelle_llvm", "path": "github-repos/isabelle/lammich-isabelle_llvm/isabelle_llvm-6be37a9c3cae74a1134dbef2979e312abb5f7f42/thys/examples/LLVM_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.8577681104440172, "lm_q1q2_score": 0.7596664436146265}}
{"text": "(*  Title:      HOL/HOLCF/Cont.thy\n    Author:     Franz Regensburger\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Continuity and monotonicity\\<close>\n\ntheory Cont\n  imports Pcpo\nbegin\n\ntext \\<open>\n   Now we change the default class! Form now on all untyped type variables are\n   of default class po\n\\<close>\n\ndefault_sort po\n\nsubsection \\<open>Definitions\\<close>\n\ndefinition monofun :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"  \\<comment> \\<open>monotonicity\\<close>\n  where \"monofun f \\<longleftrightarrow> (\\<forall>x y. x \\<sqsubseteq> y \\<longrightarrow> f x \\<sqsubseteq> f y)\"\n\ndefinition cont :: \"('a::cpo \\<Rightarrow> 'b::cpo) \\<Rightarrow> bool\"\n  where \"cont f = (\\<forall>Y. chain Y \\<longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i))\"\n\nlemma contI: \"(\\<And>Y. chain Y \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)) \\<Longrightarrow> cont f\"\n  by (simp add: cont_def)\n\nlemma contE: \"cont f \\<Longrightarrow> chain Y \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)\"\n  by (simp add: cont_def)\n\nlemma monofunI: \"(\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y) \\<Longrightarrow> monofun f\"\n  by (simp add: monofun_def)\n\nlemma monofunE: \"monofun f \\<Longrightarrow> x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\"\n  by (simp add: monofun_def)\n\n\nsubsection \\<open>Equivalence of alternate definition\\<close>\n\ntext \\<open>monotone functions map chains to chains\\<close>\n\nlemma ch2ch_monofun: \"monofun f \\<Longrightarrow> chain Y \\<Longrightarrow> chain (\\<lambda>i. f (Y i))\"\n  apply (rule chainI)\n  apply (erule monofunE)\n  apply (erule chainE)\n  done\n\ntext \\<open>monotone functions map upper bound to upper bounds\\<close>\n\nlemma ub2ub_monofun: \"monofun f \\<Longrightarrow> range Y <| u \\<Longrightarrow> range (\\<lambda>i. f (Y i)) <| f u\"\n  apply (rule ub_rangeI)\n  apply (erule monofunE)\n  apply (erule ub_rangeD)\n  done\n\ntext \\<open>a lemma about binary chains\\<close>\n\nlemma binchain_cont: \"cont f \\<Longrightarrow> x \\<sqsubseteq> y \\<Longrightarrow> range (\\<lambda>i::nat. f (if i = 0 then x else y)) <<| f y\"\n  apply (subgoal_tac \"f (\\<Squnion>i::nat. if i = 0 then x else y) = f y\")\n   apply (erule subst)\n   apply (erule contE)\n   apply (erule bin_chain)\n  apply (rule_tac f=f in arg_cong)\n  apply (erule is_lub_bin_chain [THEN lub_eqI])\n  done\n\ntext \\<open>continuity implies monotonicity\\<close>\n\nlemma cont2mono: \"cont f \\<Longrightarrow> monofun f\"\n  apply (rule monofunI)\n  apply (drule (1) binchain_cont)\n  apply (drule_tac i=0 in is_lub_rangeD1)\n  apply simp\n  done\n\nlemmas cont2monofunE = cont2mono [THEN monofunE]\n\nlemmas ch2ch_cont = cont2mono [THEN ch2ch_monofun]\n\ntext \\<open>continuity implies preservation of lubs\\<close>\n\nlemma cont2contlubE: \"cont f \\<Longrightarrow> chain Y \\<Longrightarrow> f (\\<Squnion>i. Y i) = (\\<Squnion>i. f (Y i))\"\n  apply (rule lub_eqI [symmetric])\n  apply (erule (1) contE)\n  done\n\nlemma contI2:\n  fixes f :: \"'a::cpo \\<Rightarrow> 'b::cpo\"\n  assumes mono: \"monofun f\"\n  assumes below: \"\\<And>Y. \\<lbrakk>chain Y; chain (\\<lambda>i. f (Y i))\\<rbrakk> \\<Longrightarrow> f (\\<Squnion>i. Y i) \\<sqsubseteq> (\\<Squnion>i. f (Y i))\"\n  shows \"cont f\"\nproof (rule contI)\n  fix Y :: \"nat \\<Rightarrow> 'a\"\n  assume Y: \"chain Y\"\n  with mono have fY: \"chain (\\<lambda>i. f (Y i))\"\n    by (rule ch2ch_monofun)\n  have \"(\\<Squnion>i. f (Y i)) = f (\\<Squnion>i. Y i)\"\n    apply (rule below_antisym)\n     apply (rule lub_below [OF fY])\n     apply (rule monofunE [OF mono])\n     apply (rule is_ub_thelub [OF Y])\n    apply (rule below [OF Y fY])\n    done\n  with fY show \"range (\\<lambda>i. f (Y i)) <<| f (\\<Squnion>i. Y i)\"\n    by (rule thelubE)\nqed\n\n\nsubsection \\<open>Collection of continuity rules\\<close>\n\nnamed_theorems cont2cont \"continuity intro rule\"\n\n\nsubsection \\<open>Continuity of basic functions\\<close>\n\ntext \\<open>The identity function is continuous\\<close>\n\nlemma cont_id [simp, cont2cont]: \"cont (\\<lambda>x. x)\"\n  apply (rule contI)\n  apply (erule cpo_lubI)\n  done\n\ntext \\<open>constant functions are continuous\\<close>\n\nlemma cont_const [simp, cont2cont]: \"cont (\\<lambda>x. c)\"\n  using is_lub_const by (rule contI)\n\ntext \\<open>application of functions is continuous\\<close>\n\nlemma cont_apply:\n  fixes f :: \"'a::cpo \\<Rightarrow> 'b::cpo \\<Rightarrow> 'c::cpo\" and t :: \"'a \\<Rightarrow> 'b\"\n  assumes 1: \"cont (\\<lambda>x. t x)\"\n  assumes 2: \"\\<And>x. cont (\\<lambda>y. f x y)\"\n  assumes 3: \"\\<And>y. cont (\\<lambda>x. f x y)\"\n  shows \"cont (\\<lambda>x. (f x) (t x))\"\nproof (rule contI2 [OF monofunI])\n  fix x y :: \"'a\"\n  assume \"x \\<sqsubseteq> y\"\n  then show \"f x (t x) \\<sqsubseteq> f y (t y)\"\n    by (auto intro: cont2monofunE [OF 1]\n        cont2monofunE [OF 2]\n        cont2monofunE [OF 3]\n        below_trans)\nnext\n  fix Y :: \"nat \\<Rightarrow> 'a\"\n  assume \"chain Y\"\n  then show \"f (\\<Squnion>i. Y i) (t (\\<Squnion>i. Y i)) \\<sqsubseteq> (\\<Squnion>i. f (Y i) (t (Y i)))\"\n    by (simp only: cont2contlubE [OF 1] ch2ch_cont [OF 1]\n        cont2contlubE [OF 2] ch2ch_cont [OF 2]\n        cont2contlubE [OF 3] ch2ch_cont [OF 3]\n        diag_lub below_refl)\nqed\n\nlemma cont_compose: \"cont c \\<Longrightarrow> cont (\\<lambda>x. f x) \\<Longrightarrow> cont (\\<lambda>x. c (f x))\"\n  by (rule cont_apply [OF _ _ cont_const])\n\ntext \\<open>Least upper bounds preserve continuity\\<close>\n\nlemma cont2cont_lub [simp]:\n  assumes chain: \"\\<And>x. chain (\\<lambda>i. F i x)\"\n    and cont: \"\\<And>i. cont (\\<lambda>x. F i x)\"\n  shows \"cont (\\<lambda>x. \\<Squnion>i. F i x)\"\n  apply (rule contI2)\n   apply (simp add: monofunI cont2monofunE [OF cont] lub_mono chain)\n  apply (simp add: cont2contlubE [OF cont])\n  apply (simp add: diag_lub ch2ch_cont [OF cont] chain)\n  done\n\ntext \\<open>if-then-else is continuous\\<close>\n\nlemma cont_if [simp, cont2cont]: \"cont f \\<Longrightarrow> cont g \\<Longrightarrow> cont (\\<lambda>x. if b then f x else g x)\"\n  by (induct b) simp_all\n\n\nsubsection \\<open>Finite chains and flat pcpos\\<close>\n\ntext \\<open>Monotone functions map finite chains to finite chains.\\<close>\n\nlemma monofun_finch2finch: \"monofun f \\<Longrightarrow> finite_chain Y \\<Longrightarrow> finite_chain (\\<lambda>n. f (Y n))\"\n  by (force simp add: finite_chain_def ch2ch_monofun max_in_chain_def)\n\ntext \\<open>The same holds for continuous functions.\\<close>\n\nlemma cont_finch2finch: \"cont f \\<Longrightarrow> finite_chain Y \\<Longrightarrow> finite_chain (\\<lambda>n. f (Y n))\"\n  by (rule cont2mono [THEN monofun_finch2finch])\n\ntext \\<open>All monotone functions with chain-finite domain are continuous.\\<close>\n\nlemma chfindom_monofun2cont: \"monofun f \\<Longrightarrow> cont f\"\n  for f :: \"'a::chfin \\<Rightarrow> 'b::cpo\"\n  apply (erule contI2)\n  apply (frule chfin2finch)\n  apply (clarsimp simp add: finite_chain_def)\n  apply (subgoal_tac \"max_in_chain i (\\<lambda>i. f (Y i))\")\n   apply (simp add: maxinch_is_thelub ch2ch_monofun)\n  apply (force simp add: max_in_chain_def)\n  done\n\ntext \\<open>All strict functions with flat domain are continuous.\\<close>\n\nlemma flatdom_strict2mono: \"f \\<bottom> = \\<bottom> \\<Longrightarrow> monofun f\"\n  for f :: \"'a::flat \\<Rightarrow> 'b::pcpo\"\n  apply (rule monofunI)\n  apply (drule ax_flat)\n  apply auto\n  done\n\nlemma flatdom_strict2cont: \"f \\<bottom> = \\<bottom> \\<Longrightarrow> cont f\"\n  for f :: \"'a::flat \\<Rightarrow> 'b::pcpo\"\n  by (rule flatdom_strict2mono [THEN chfindom_monofun2cont])\n\ntext \\<open>All functions with discrete domain are continuous.\\<close>\n\nlemma cont_discrete_cpo [simp, cont2cont]: \"cont f\"\n  for f :: \"'a::discrete_cpo \\<Rightarrow> 'b::cpo\"\n  apply (rule contI)\n  apply (drule discrete_chain_const, clarify)\n  apply simp\n  done\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/HOLCF/Cont.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.7596664387844689}}
{"text": "(*  Title:      HOL/Induct/Comb.thy\n    Author:     Lawrence C Paulson\n    Copyright   1996  University of Cambridge\n*)\n\nsection \\<open>Combinatory Logic example: the Church-Rosser Theorem\\<close>\n\ntheory Comb\nimports Main\nbegin\n\ntext \\<open>\n  Combinator terms do not have free variables.\n  Example taken from \\<^cite>\\<open>camilleri92\\<close>.\n\\<close>\n\nsubsection \\<open>Definitions\\<close>\n\ntext \\<open>Datatype definition of combinators \\<open>S\\<close> and \\<open>K\\<close>.\\<close>\n\ndatatype comb = K\n              | S\n              | Ap comb comb (infixl \"\\<bullet>\" 90)\n\ntext \\<open>\n  Inductive definition of contractions, \\<open>\\<rightarrow>\\<^sup>1\\<close> and\n  (multi-step) reductions, \\<open>\\<rightarrow>\\<close>.\n\\<close>\n\ninductive contract1 :: \"[comb,comb] \\<Rightarrow> bool\"  (infixl \"\\<rightarrow>\\<^sup>1\" 50)\n  where\n    K:     \"K\\<bullet>x\\<bullet>y \\<rightarrow>\\<^sup>1 x\"\n  | S:     \"S\\<bullet>x\\<bullet>y\\<bullet>z \\<rightarrow>\\<^sup>1 (x\\<bullet>z)\\<bullet>(y\\<bullet>z)\"\n  | Ap1:   \"x \\<rightarrow>\\<^sup>1 y \\<Longrightarrow> x\\<bullet>z \\<rightarrow>\\<^sup>1 y\\<bullet>z\"\n  | Ap2:   \"x \\<rightarrow>\\<^sup>1 y \\<Longrightarrow> z\\<bullet>x \\<rightarrow>\\<^sup>1 z\\<bullet>y\"\n\nabbreviation\n  contract :: \"[comb,comb] \\<Rightarrow> bool\"   (infixl \"\\<rightarrow>\" 50) where\n  \"contract \\<equiv> contract1\\<^sup>*\\<^sup>*\"\n\ntext \\<open>\n  Inductive definition of parallel contractions, \\<open>\\<Rrightarrow>\\<^sup>1\\<close> and\n  (multi-step) parallel reductions, \\<open>\\<Rrightarrow>\\<close>.\n\\<close>\n\ninductive parcontract1 :: \"[comb,comb] \\<Rightarrow> bool\"  (infixl \"\\<Rrightarrow>\\<^sup>1\" 50)\n  where\n    refl:  \"x \\<Rrightarrow>\\<^sup>1 x\"\n  | K:     \"K\\<bullet>x\\<bullet>y \\<Rrightarrow>\\<^sup>1 x\"\n  | S:     \"S\\<bullet>x\\<bullet>y\\<bullet>z \\<Rrightarrow>\\<^sup>1 (x\\<bullet>z)\\<bullet>(y\\<bullet>z)\"\n  | Ap:    \"\\<lbrakk>x \\<Rrightarrow>\\<^sup>1 y; z \\<Rrightarrow>\\<^sup>1 w\\<rbrakk> \\<Longrightarrow> x\\<bullet>z \\<Rrightarrow>\\<^sup>1 y\\<bullet>w\"\n\nabbreviation\n  parcontract :: \"[comb,comb] \\<Rightarrow> bool\"   (infixl \"\\<Rrightarrow>\" 50) where\n  \"parcontract \\<equiv> parcontract1\\<^sup>*\\<^sup>*\"\n\ntext \\<open>\n  Misc definitions.\n\\<close>\n\ndefinition\n  I :: comb where\n  \"I \\<equiv> S\\<bullet>K\\<bullet>K\"\n\ndefinition\n  diamond   :: \"([comb,comb] \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n    \\<comment> \\<open>confluence; Lambda/Commutation treats this more abstractly\\<close>\n  \"diamond r \\<equiv> \\<forall>x y. r x y \\<longrightarrow>\n                  (\\<forall>y'. r x y' \\<longrightarrow> \n                    (\\<exists>z. r y z \\<and> r y' z))\"\n\n\nsubsection \\<open>Reflexive/Transitive closure preserves Church-Rosser property\\<close>\n\ntext\\<open>Remark: So does the Transitive closure, with a similar proof\\<close>\n\ntext\\<open>Strip lemma.  \n   The induction hypothesis covers all but the last diamond of the strip.\\<close>\nlemma strip_lemma [rule_format]: \n  assumes \"diamond r\" and r: \"r\\<^sup>*\\<^sup>* x y\" \"r x y'\"\n  shows \"\\<exists>z. r\\<^sup>*\\<^sup>* y' z \\<and> r y z\"\n  using r\nproof (induction rule: rtranclp_induct)\n  case base\n  then show ?case\n    by blast\nnext\n  case (step y z)\n  then show ?case\n    using \\<open>diamond r\\<close> unfolding diamond_def\n    by (metis rtranclp.rtrancl_into_rtrancl)\nqed\n\nproposition diamond_rtrancl:\n  assumes \"diamond r\" \n  shows \"diamond(r\\<^sup>*\\<^sup>*)\"\n  unfolding diamond_def\nproof (intro strip)\n  fix x y y'\n  assume \"r\\<^sup>*\\<^sup>* x y\" \"r\\<^sup>*\\<^sup>* x y'\"\n  then show \"\\<exists>z. r\\<^sup>*\\<^sup>* y z \\<and> r\\<^sup>*\\<^sup>* y' z\"\n  proof (induction rule: rtranclp_induct)\n    case base\n    then show ?case\n      by blast\n  next\n    case (step y z)\n    then show ?case\n      by (meson assms strip_lemma rtranclp.rtrancl_into_rtrancl)\n  qed\nqed\n\n\nsubsection \\<open>Non-contraction results\\<close>\n\ntext \\<open>Derive a case for each combinator constructor.\\<close>\n\ninductive_cases\n  K_contractE [elim!]: \"K \\<rightarrow>\\<^sup>1 r\"\n  and S_contractE [elim!]: \"S \\<rightarrow>\\<^sup>1 r\"\n  and Ap_contractE [elim!]: \"p\\<bullet>q \\<rightarrow>\\<^sup>1 r\"\n\ndeclare contract1.K [intro!] contract1.S [intro!]\ndeclare contract1.Ap1 [intro] contract1.Ap2 [intro]\n\nlemma I_contract_E [iff]: \"\\<not> I \\<rightarrow>\\<^sup>1 z\"\n  unfolding I_def by blast\n\nlemma K1_contractD [elim!]: \"K\\<bullet>x \\<rightarrow>\\<^sup>1 z \\<Longrightarrow> (\\<exists>x'. z = K\\<bullet>x' \\<and> x \\<rightarrow>\\<^sup>1 x')\"\n  by blast\n\nlemma Ap_reduce1 [intro]: \"x \\<rightarrow> y \\<Longrightarrow> x\\<bullet>z \\<rightarrow> y\\<bullet>z\"\n  by (induction rule: rtranclp_induct; blast intro: rtranclp_trans)\n\nlemma Ap_reduce2 [intro]: \"x \\<rightarrow> y \\<Longrightarrow> z\\<bullet>x \\<rightarrow> z\\<bullet>y\"\n  by (induction rule: rtranclp_induct; blast intro: rtranclp_trans)\n\ntext \\<open>Counterexample to the diamond property for \\<^term>\\<open>x \\<rightarrow>\\<^sup>1 y\\<close>\\<close>\n\nlemma not_diamond_contract: \"\\<not> diamond(contract1)\"\n  unfolding diamond_def by (metis S_contractE contract1.K) \n\n\nsubsection \\<open>Results about Parallel Contraction\\<close>\n\ntext \\<open>Derive a case for each combinator constructor.\\<close>\n\ninductive_cases\n      K_parcontractE [elim!]: \"K \\<Rrightarrow>\\<^sup>1 r\"\n  and S_parcontractE [elim!]: \"S \\<Rrightarrow>\\<^sup>1 r\"\n  and Ap_parcontractE [elim!]: \"p\\<bullet>q \\<Rrightarrow>\\<^sup>1 r\"\n\ndeclare parcontract1.intros [intro]\n\nsubsection \\<open>Basic properties of parallel contraction\\<close>\ntext\\<open>The rules below are not essential but make proofs much faster\\<close>\n\nlemma K1_parcontractD [dest!]: \"K\\<bullet>x \\<Rrightarrow>\\<^sup>1 z \\<Longrightarrow> (\\<exists>x'. z = K\\<bullet>x' \\<and> x \\<Rrightarrow>\\<^sup>1 x')\"\n  by blast\n\nlemma S1_parcontractD [dest!]: \"S\\<bullet>x \\<Rrightarrow>\\<^sup>1 z \\<Longrightarrow> (\\<exists>x'. z = S\\<bullet>x' \\<and> x \\<Rrightarrow>\\<^sup>1 x')\"\n  by blast\n\nlemma S2_parcontractD [dest!]: \"S\\<bullet>x\\<bullet>y \\<Rrightarrow>\\<^sup>1 z \\<Longrightarrow> (\\<exists>x' y'. z = S\\<bullet>x'\\<bullet>y' \\<and> x \\<Rrightarrow>\\<^sup>1 x' \\<and> y \\<Rrightarrow>\\<^sup>1 y')\"\n  by blast\n\ntext\\<open>Church-Rosser property for parallel contraction\\<close>\nproposition diamond_parcontract: \"diamond parcontract1\"\nproof -\n  have \"(\\<exists>z. w \\<Rrightarrow>\\<^sup>1 z \\<and> y' \\<Rrightarrow>\\<^sup>1 z)\" if \"y \\<Rrightarrow>\\<^sup>1 w\" \"y \\<Rrightarrow>\\<^sup>1 y'\" for w y y'\n    using that by (induction arbitrary: y' rule: parcontract1.induct) fast+\n  then show ?thesis\n    by (auto simp: diamond_def)\nqed\n\nsubsection \\<open>Equivalence of \\<^prop>\\<open>p \\<rightarrow> q\\<close> and \\<^prop>\\<open>p \\<Rrightarrow> q\\<close>.\\<close>\n\nlemma contract_imp_parcontract: \"x \\<rightarrow>\\<^sup>1 y \\<Longrightarrow> x \\<Rrightarrow>\\<^sup>1 y\"\n  by (induction rule: contract1.induct; blast)\n\ntext\\<open>Reductions: simply throw together reflexivity, transitivity and\n  the one-step reductions\\<close>\n\nproposition reduce_I: \"I\\<bullet>x \\<rightarrow> x\"\n  unfolding I_def\n  by (meson contract1.K contract1.S r_into_rtranclp rtranclp.rtrancl_into_rtrancl)\n\nlemma parcontract_imp_reduce: \"x \\<Rrightarrow>\\<^sup>1 y \\<Longrightarrow> x \\<rightarrow> y\"\nproof (induction rule: parcontract1.induct)\n  case (Ap x y z w)\n  then show ?case\n    by (meson Ap_reduce1 Ap_reduce2 rtranclp_trans)\nqed auto\n\nlemma reduce_eq_parreduce: \"x \\<rightarrow> y  \\<longleftrightarrow>  x \\<Rrightarrow> y\"\n  by (metis contract_imp_parcontract parcontract_imp_reduce predicate2I rtranclp_subset)\n\ntheorem diamond_reduce: \"diamond(contract)\"\n  using diamond_parcontract diamond_rtrancl reduce_eq_parreduce by presburger\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Induct/Comb.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8856314647623016, "lm_q1q2_score": 0.7596664296889791}}
{"text": "(*\n  File:    Triangle.thy\n  Author:  Manuel Eberl <manuel@pruvisto.org>\n\n  Sine and cosine laws, angle sum in a triangle, congruence theorems,\n  Isosceles Triangle Theorem\n*)\n\nsection \\<open>Basic Properties of Triangles\\<close>\ntheory Triangle\nimports\n  Angles\nbegin\n\ntext \\<open>\n  We prove a number of basic geometric properties of triangles. All theorems hold\n  in any real inner product space.\n\\<close>\nsubsection \\<open>Thales' theorem\\<close>\n\ntheorem thales:\n  fixes A B C :: \"'a :: real_inner\"\n  assumes \"dist B (midpoint A C) = dist A C / 2\"\n  shows   \"orthogonal (A - B) (C - B)\"\nproof -\n  have \"dist A C ^ 2 = dist B (midpoint A C) ^ 2 * 4\"\n    by (subst assms) (simp add: field_simps power2_eq_square)\n  thus ?thesis\n    by (auto simp: orthogonal_def dist_norm power2_norm_eq_inner midpoint_def\n                   algebra_simps inner_commute)\nqed\n\nsubsection \\<open>Sine and cosine laws\\<close>\n\ntext \\<open>\n  The proof of the Law of Cosines follows trivially from the definition of the angle,\n  the definition of the norm in vector spaces with an inner product and the bilinearity\n  of the inner product.\n\\<close>\n\nlemma cosine_law_vector:\n  \"norm (u - v) ^ 2 = norm u ^ 2 + norm v ^ 2 - 2 * norm u * norm v * cos (vangle u v)\"\n  by (simp add: power2_norm_eq_inner cos_vangle algebra_simps inner_commute)\n\nlemma cosine_law_triangle:\n  \"dist b c ^ 2 = dist a b ^ 2 + dist a c ^ 2 - 2 * dist a b * dist a c * cos (angle b a c)\"\n  using cosine_law_vector[of \"b - a\" \"c - a\"]\n  by (simp add: dist_norm angle_def vangle_commute norm_minus_commute)\n\n\ntext \\<open>\n  According to our definition, angles are always between $0$ and $\\pi$ and therefore,\n  the sign of an angle is always non-negative. We can therefore look at\n  $\\sin(\\alpha)^2$, which we can express in terms of $\\cos(\\alpha)$ using the\n  identity $\\sin(\\alpha)^2 + \\cos(\\alpha)^2 = 1$. The remaining proof is then a\n  trivial consequence of the definitions.\n\\<close>\nlemma sine_law_triangle:\n  \"sin (angle a b c) * dist b c = sin (angle b a c) * dist a c\" (is \"?A = ?B\")\nproof (cases \"a = b\")\n  assume neq: \"a \\<noteq> b\"\n  show ?thesis\n  proof (rule power2_eq_imp_eq)\n    from neq have \"(sin (angle a b c) * dist b c) ^ 2 * dist a b ^ 2 =\n                     dist a b ^ 2 * dist b c ^ 2 - ((a - b) \\<bullet> (c - b)) ^ 2\"\n      by (simp add: sin_squared_eq cos_angle dist_commute field_simps)\n    also have \"\\<dots> = dist a b ^ 2 * dist a c ^ 2 - ((b - a) \\<bullet> (c - a)) ^ 2\"\n      by (simp only: dist_norm power2_norm_eq_inner)\n         (simp add: power2_eq_square algebra_simps inner_commute)\n    also from neq have \"\\<dots> = (sin (angle b a c) * dist a c) ^ 2 * dist a b ^ 2\"\n      by (simp add: sin_squared_eq cos_angle dist_commute field_simps)\n    finally show \"?A^2 = ?B^2\" using neq by (subst (asm) mult_cancel_right) simp_all\n  qed (auto intro!: mult_nonneg_nonneg sin_angle_nonneg)\nqed simp_all\n\n\ntext \\<open>\n  The following forms of the Law of Sines/Cosines are more convenient for eliminating\n  sines/cosines from a goal completely.\n\\<close>\n\nlemma cosine_law_triangle':\n  \"2 * dist a b * dist a c * cos (angle b a c) = (dist a b ^ 2 + dist a c ^ 2 - dist b c ^ 2)\"\n  using cosine_law_triangle[of b c a] by simp\n\nlemma cosine_law_triangle'':\n  \"cos (angle b a c) = (dist a b ^ 2 + dist a c ^ 2 - dist b c ^ 2) / (2 * dist a b * dist a c)\"\n  using cosine_law_triangle[of b c a] by simp\n\nlemma sine_law_triangle':\n  \"b \\<noteq> c \\<Longrightarrow> sin (angle a b c) = sin (angle b a c) * dist a c / dist b c\"\n  using sine_law_triangle[of a b c] by (simp add: divide_simps)\n\nlemma sine_law_triangle'':\n  \"b \\<noteq> c \\<Longrightarrow> sin (angle c b a) = sin (angle b a c) * dist a c / dist b c\"\n  using sine_law_triangle[of a b c] by (simp add: divide_simps angle_commute)\n\n\nsubsection \\<open>Sum of angles\\<close>\n\ncontext\nbegin\n\nprivate lemma gather_squares: \"a * (a * b) = a^2 * (b :: real)\"\n  by (simp_all add: power2_eq_square)\n\nprivate lemma eval_power: \"x ^ numeral n = x * x ^ pred_numeral n\"\n  by (subst numeral_eq_Suc, subst power_Suc) simp\n\ntext \\<open>\n  The proof that the sum of the angles in a triangle is $\\pi$ is somewhat more\n  involved. Following the HOL Light proof by John Harrison, we first prove\n  that $\\cos(\\alpha + \\beta + \\gamma) = -1$ and $\\alpha + \\beta + \\gamma \\in [0;3\\pi)$,\n  which then implies the theorem.\n\n  The main work is proving $\\cos(\\alpha + \\beta + \\gamma)$. This is done using the\n  addition theorems for the sine and cosine, then using the Laws of Sines to eliminate\n  all $\\sin$ terms save $\\sin(\\gamma)^2$, which only appears squared in the remaining goal.\n  We then use $\\sin(\\gamma)^2 = 1 - \\cos(\\gamma)^2$ to eliminate this term and apply\n  the law of cosines to eliminate this term as well.\n\n  The remaining goal is a non-linear equation containing only the length of the sides\n  of the triangle. It can be shown by simple algebraic rewriting.\n\\<close>\nlemma angle_sum_triangle:\n  assumes \"a \\<noteq> b \\<or> b \\<noteq> c \\<or> a \\<noteq> c\"\n  shows   \"angle c a b + angle a b c + angle b c a = pi\"\nproof (rule cos_minus1_imp_pi)\n  show \"cos (angle c a b + angle a b c + angle b c a) = - 1\"\n  proof (cases \"a \\<noteq> b\")\n    case True\n    thus \"cos (angle c a b + angle a b c + angle b c a) = -1\"\n      apply (simp add: cos_add sin_add cosine_law_triangle'' field_simps\n                       sine_law_triangle''[of a b c] sine_law_triangle''[of b a c]\n                       angle_commute dist_commute gather_squares sin_squared_eq)\n      apply (simp add: eval_power algebra_simps dist_commute)\n      done\n  qed (insert assms, auto)\n\n  show \"angle c a b + angle a b c + angle b c a < 3 * pi\"\n  proof (rule ccontr)\n    assume \"\\<not>(angle c a b + angle a b c + angle b c a < 3 * pi)\"\n    with angle_le_pi[of c a b] angle_le_pi[of a b c] angle_le_pi[of b c a]\n      have A: \"angle c a b = pi\" \"angle a b c = pi\" by simp_all\n    thus False using angle_eq_pi_imp_dist_additive[of c a b]\n                     angle_eq_pi_imp_dist_additive[of a b c] by (simp add: dist_commute)\n  qed\nqed (auto intro!: add_nonneg_nonneg angle_nonneg)\n\nend\n\n\nsubsection \\<open>Congruence Theorems\\<close>\n\ntext \\<open>\n  If two triangles agree on two angles at a non-degenerate side, the third angle\n  must also be equal.\n\\<close>\nlemma similar_triangle_aa:\n  assumes \"b1 \\<noteq> c1\" \"b2 \\<noteq> c2\"\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  assumes \"angle b1 c1 a1 = angle b2 c2 a2\"\n  shows   \"angle b1 a1 c1 = angle b2 a2 c2\"\nproof -\n  from assms angle_sum_triangle[of a1 b1 c1] angle_sum_triangle[of a2 b2 c2, symmetric]\n    show ?thesis by (auto simp: algebra_simps angle_commute)\nqed\n\ntext \\<open>\n  A triangle is defined by its three angles and the lengths of three sides up to congruence.\n  Two triangles are congruent if they have their angles are the same and their sides have\n  the same length.\n\\<close>\n\nlocale congruent_triangle =\n  fixes a1 b1 c1 :: \"'a :: real_inner\" and a2 b2 c2 :: \"'b :: real_inner\"\n  assumes sides':  \"dist a1 b1 = dist a2 b2\" \"dist a1 c1 = dist a2 c2\" \"dist b1 c1 = dist b2 c2\"\n      and angles': \"angle b1 a1 c1 = angle b2 a2 c2\" \"angle a1 b1 c1 = angle a2 b2 c2\"\n                   \"angle a1 c1 b1 = angle a2 c2 b2\"\nbegin\n\n\n\nlemma angles:\n  \"angle b1 a1 c1 = angle b2 a2 c2\" \"angle a1 b1 c1 = angle a2 b2 c2\" \"angle a1 c1 b1 = angle a2 c2 b2\"\n  \"angle c1 a1 b1 = angle b2 a2 c2\" \"angle c1 b1 a1 = angle a2 b2 c2\" \"angle b1 c1 a1 = angle a2 c2 b2\"\n  \"angle b1 a1 c1 = angle c2 a2 b2\" \"angle a1 b1 c1 = angle c2 b2 a2\" \"angle a1 c1 b1 = angle b2 c2 a2\"\n  \"angle c1 a1 b1 = angle c2 a2 b2\" \"angle c1 b1 a1 = angle c2 b2 a2\" \"angle b1 c1 a1 = angle b2 c2 a2\"\n  using angles' by (simp_all add: angle_commute)\n\nend\n\nlemmas congruent_triangleD = congruent_triangle.sides congruent_triangle.angles\n\n\n\ntext \\<open>\n  Given two triangles that agree on a subset of its side lengths and angles that are\n  sufficient to define a triangle uniquely up to congruence, one can conclude that they\n  must also agree on all remaining quantities, i.e. that they are congruent.\n\n  The following four congruence theorems state what constitutes such a uniquely-defining\n  subset of quantities. Each theorem states in its name which quantities are required and\n  in which order (clockwise or counter-clockwise): an ``s'' stands for a side,\n  an ``a'' stands for an angle.\n\n  The lemma ``congruent-triangleI-sas, for example, requires that two adjacent sides and the\n  angle inbetween are the same in both triangles.\n\\<close>\n\nlemma congruent_triangleI_sss:\n  fixes a1 b1 c1 :: \"'a :: real_inner\" and a2 b2 c2 :: \"'b :: real_inner\"\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"dist b1 c1 = dist b2 c2\"\n  assumes \"dist a1 c1 = dist a2 c2\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof -\n  have A: \"angle a1 b1 c1 = angle a2 b2 c2\"\n    if \"dist a1 b1 = dist a2 b2\" \"dist b1 c1 = dist b2 c2\" \"dist a1 c1 = dist a2 c2\"\n    for a1 b1 c1 :: 'a and a2 b2 c2 :: 'b\n  proof -\n    from that cosine_law_triangle''[of a1 b1 c1] cosine_law_triangle''[of a2 b2 c2]\n      show ?thesis by (intro cos_angle_eqD) (simp add: dist_commute)\n  qed\n  from assms show ?thesis by unfold_locales (auto intro!: A simp: dist_commute)\nqed\n\nlemmas congruent_triangle_sss = congruent_triangleD[OF congruent_triangleI_sss]\n\nlemma congruent_triangleI_sas:\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"dist b1 c1 = dist b2 c2\"\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof (rule congruent_triangleI_sss)\n  show \"dist a1 c1 = dist a2 c2\"\n  proof (rule power2_eq_imp_eq)\n    from cosine_law_triangle[of a1 c1 b1] cosine_law_triangle[of a2 c2 b2] assms\n      show \"(dist a1 c1)\\<^sup>2 = (dist a2 c2)\\<^sup>2\" by (simp add: dist_commute)\n  qed simp_all\nqed fact+\n\nlemmas congruent_triangle_sas = congruent_triangleD[OF congruent_triangleI_sas]\n\nlemma congruent_triangleI_aas:\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  assumes \"angle b1 c1 a1 = angle b2 c2 a2\"\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"\\<not>collinear {a1,b1,c1}\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof (rule congruent_triangleI_sas)\n  from \\<open>\\<not>collinear {a1,b1,c1}\\<close> have neq: \"a1 \\<noteq> b1\" by auto\n  with assms(3) have neq': \"a2 \\<noteq> b2\" by auto\n  have A: \"angle c1 a1 b1 = angle c2 a2 b2\" using neq neq' assms\n    using angle_sum_triangle[of a1 b1 c1] angle_sum_triangle[of a2 b2 c2]\n    by simp\n  from assms have B: \"angle b1 a1 c1 \\<in> {0<..<pi}\"\n    by (intro not_collinear_angle) (simp_all add: insert_commute)\n  from sine_law_triangle[of c1 a1 b1] sine_law_triangle[of c2 a2 b2] assms A B\n    show \"dist b1 c1 = dist b2 c2\"\n    by (auto simp: angle_commute dist_commute sin_angle_zero_iff)\nqed fact+\n\nlemmas congruent_triangle_aas = congruent_triangleD[OF congruent_triangleI_aas]\n\nlemma congruent_triangleI_asa:\n  assumes \"angle a1 b1 c1 = angle a2 b2 c2\"\n  assumes \"dist a1 b1 = dist a2 b2\"\n  assumes \"angle b1 a1 c1 = angle b2 a2 c2\"\n  assumes \"\\<not>collinear {a1, b1, c1}\"\n  shows   \"congruent_triangle a1 b1 c1 a2 b2 c2\"\nproof (rule congruent_triangleI_aas)\n  from assms have neq: \"a1 \\<noteq> b1\" \"a2 \\<noteq> b2\" by auto\n  show \"angle b1 c1 a1 = angle b2 c2 a2\"\n    by (rule similar_triangle_aa) (insert assms neq, simp_all add: angle_commute)\nqed fact+\n\nlemmas congruent_triangle_asa = congruent_triangleD[OF congruent_triangleI_asa]\n\n\nsubsection \\<open>Isosceles Triangle Theorem\\<close>\n\ntext \\<open>\n  We now prove the Isosceles Triangle Theorem: in a triangle where two sides have\n  the same length, the two angles that are adjacent to only one of the two sides\n  must be equal.\n\\<close>\nlemma isosceles_triangle:\n  assumes \"dist a c = dist b c\"\n  shows   \"angle b a c = angle a b c\"\n  by (rule congruent_triangle_sss) (insert assms, simp_all add: dist_commute)\n\n\ntext \\<open>\n  For the non-degenerate case (i.e. the three points are not collinear), We also\n  prove the converse.\n\\<close>\nlemma isosceles_triangle_converse:\n  assumes \"angle a b c = angle b a c\" \"\\<not>collinear {a,b,c}\"\n  shows   \"dist a c = dist b c\"\n  by (rule congruent_triangle_asa[OF assms(1) _ _ assms(2)])\n     (simp_all add: dist_commute angle_commute assms)\n\n\nsubsection\\<open>Contributions by Lukas Bulwahn\\<close>\n  \nlemma Pythagoras:\n  fixes A B C :: \"'a :: real_inner\"\n  assumes \"orthogonal (A - C) (B - C)\"\n  shows \"(dist B C) ^ 2 + (dist C A) ^ 2 = (dist A B) ^ 2\"\nproof -\n  from assms have \"cos (angle A C B) = 0\"\n    by (metis orthogonal_iff_angle cos_pi_half)\n  from this show ?thesis\n    by (simp add: cosine_law_triangle[of A B C] dist_commute)\nqed\n\nlemma isosceles_triangle_orthogonal_on_midpoint:\n  fixes A B C :: \"'a :: euclidean_space\"\n  assumes \"dist C A = dist C B\"\n  shows \"orthogonal (C - midpoint A B) (A - midpoint A B)\"\nproof (cases \"A = B\")\n  assume \"A \\<noteq> B\"\n  let ?M = \"midpoint A B\"\n  from \\<open>A \\<noteq> B\\<close> have \"angle A ?M C = pi - angle B ?M C\"\n    by (intro angle_inverse between_midpoint)\n       (auto simp: between_midpoint eq_commute[of _ \"midpoint A B\" for A B])\n  moreover have \"angle A ?M C = angle C ?M B\"\n  proof -\n    have congruence: \"congruent_triangle C A ?M C B ?M\"\n    proof (rule congruent_triangleI_sss)\n      show \"dist C A = dist C B\" using assms .\n      show \"dist A ?M = dist B ?M\" by (simp add: dist_midpoint)\n      show \"dist C (midpoint A B) = dist C (midpoint A B)\" ..\n    qed\n    from this show ?thesis by (simp add: congruent_triangle.angles(6))\n  qed\n  ultimately have \"angle A ?M C = pi / 2\" by (simp add: angle_commute)\n  from this show ?thesis\n    by (simp add: orthogonal_iff_angle orthogonal_commute)\nnext\n  assume \"A = B\"\n  from this show ?thesis\n    by (simp add: orthogonal_clauses(1))\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Triangle/Triangle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.839733963661418, "lm_q2_score": 0.9046505402422644, "lm_q1q2_score": 0.7596657838860797}}
{"text": "theory Exercises2\n  imports Main\nbegin\n\n(* Exercise 2.1 *)\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n(* Exercise 2.2 *)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc (add m n)\"\n\nlemma add_assoc[simp]: \"add (add x y) z = add x (add y z)\"\n  apply (induction x)\n   apply (auto)\n  done\n\nlemma add_r_0[simp]: \"add x 0 = x\"\n  apply (induction x)\n  apply (auto)\n  done\n\nlemma add_succ_1[simp]: \"add x (Suc y) = Suc (add x y)\"\n  apply (induction x)\n   apply (auto)\n  done\n\nlemma add_commut[simp]: \"add x y = add y x\"\n  apply (induction x)\n  apply (auto)\n  done\n\n(* Exercise 2.3 *)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count _ [] = 0\" |\n\"count x (y # ys) = (if (x = y) then 1 else 0) +  (count x ys)\"\n\ntheorem count_lt_length[simp]: \"count x xs \\<le> length xs\"\n  apply (induction xs)\n   apply (auto)\n  done\n\n(* Exercise 2.4 *)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] x = [x]\"|\n\"snoc (y#ys) x = y # (snoc ys x)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\"|\n\"reverse (x#xs) = snoc (reverse xs) x\"\n\ntheorem rev_snoc[simp]: \"reverse (snoc xs x) = (x#(reverse xs))\"\n  apply (induction xs)\n   apply (auto)\n  done\n\ntheorem rev_rev_id[simp] : \"reverse (reverse x) = x\"\n  apply (induction x)\n   apply (auto)\n  done\n\n(* Exercise 2.5 *)\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\"|\n\"sum_upto (Suc n) = (Suc n) + (sum_upto n)\"\n\ntheorem sum_upto_sol[simp]: \"sum_upto n = n * (n + 1) div 2\"\n  apply (induction n)\n   apply (auto)\n  done\n\n(* Exercise 2.6 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents:: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = Nil\"|\n\"contents (Node l a r) = [a] @ (contents l) @ (contents r)\"\n\nfun sum_tree:: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\"|\n\"sum_tree (Node l a r) = a + (sum_tree l) + (sum_tree r)\"\n\ntheorem sum_tree_thm[simp]: \"sum_tree t = sum_list (contents t)\"\n  apply (induction t)\n   apply (auto)\n  done\n\n(* Exercise 2.7 *)\n\ndatatype 'a tree2 = Leaf 'a | Node2 \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror2 :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror2 (Leaf x) = Leaf x\"|\n\"mirror2 (Node2 l a r) = (Node2 (mirror2 r) a (mirror2 l))\"\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order (Leaf x) = [x]\" |\n\"pre_order (Node2 l a r) = a # (pre_order l @ pre_order r)\"\n\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order (Leaf x) = [x]\" |\n\"post_order (Node2 l a r) = post_order l @ post_order r @ [a]\"\n\ntheorem rev_pre_is_pos[simp]: \"pre_order (mirror2 t) = rev (post_order t)\"\n  apply (induction t rule: post_order.induct)\n   apply (auto)\n  done\n\n(* Exercise 2.8 *)\nfun intersperse:: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse a [] = []\"|\n\"intersperse a [x] = [x]\"|\n\"intersperse a (x1 # x2 # xs) = x1 # a # x2 # (intersperse a xs)\"\n\ntheorem intersperse_map[simp]:\n  \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply (induction xs rule: intersperse.induct)\n    apply (auto)\n  done\n\n(* exercise 2.9 *)\nfun itadd:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"itadd 0 n = n\"|\n\"itadd (Suc m) n = itadd m (Suc n)\"\n\nlemma \"itadd m n = add m n\"\n  apply (induction m arbitrary : n)\n   apply (auto)\n  done\n\n(* exercise 2.10 *)\ndatatype tree0 = Nil0 | Node0 tree0 tree0\n\nfun nodes::\"tree0 \\<Rightarrow> nat\" where\n\"nodes Nil0 = 1\"|\n\"nodes (Node0 l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\"|\n\"explode (Suc n) t = explode n (Node0 t t)\"\n\ndefinition explode_size :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> nat\" where\n\"explode_size n t = (2^n) * (1 + (nodes t)) - 1\"\n\nlemma [simp] : \"nodes (explode n (Node0 t t)) = 1 + 2 * nodes (explode n t)\"\n  apply (induction n arbitrary : t)ifexp=Bc2bool|If ifexp ifexp ifexp|Less2aexp aexp\n  apply (auto)\n  done\n\nlemma [simp] : \"Suc (2 * 2 ^ n + nodes t * (2 * 2 ^ n) - Suc (Suc 0)) = 2 * 2 ^ n + nodes t * (2 * 2 ^ n) - Suc 0\"\n  apply (induction n)\n   apply (auto)\n  done\n\n\nlemma \"(nodes (explode n t)) = explode_size n t\"\n  apply (induction n)\n   apply (simp_all add : explode_size_def)\n  apply (simp add : algebra_simps)  \n  done\n\ndatatype exp=Var|Const int|Add exp exp|Mult exp exp\n\nvalue \"(1 * (2::int))\"\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\" |\n\"eval (Const x) _ = x\" |\n\"eval (Add a b) x = (eval a x) + (eval b x)\" |\n\"eval (Mult a b) x = (eval a x) * (eval b x)\"\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] _ = 0\"|\n\"evalp (c#cs) x = c * (x^(length (c#cs))) + (evalp cs x)\"\n\nfun degree :: \"exp \\<Rightarrow> int\" where\n\"degree (Mult Var Var) = 2\"|\n\"degree (Mult Var x) = 1 + (degree x)\"|\n\"degree (Mult x Var) = 1 + (degree x)\"|\n\"degree x = 0\"\n\nfun factor :: \"exp \\<Rightarrow> int\" where\n\"factor (Mult x y) = (factor x) * (factor y)\"|\n\"factor (Const x) = x\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs (Const x) = [x]\"|\n\"coeffs (Add a b) = (factor a) # (coeffs b)\"\n\ntheorem \"evalp (coeffs e) x = eval e x\"\n  apply (induction e arbitrary : x rule : coeffs.induct)\n  apply (simp_all)\n\nend", "meta": {"author": "tomssem", "repo": "concrete_semantics", "sha": "a1c52efba72b4abb85a52c489812b32c2d1aee36", "save_path": "github-repos/isabelle/tomssem-concrete_semantics", "path": "github-repos/isabelle/tomssem-concrete_semantics/concrete_semantics-a1c52efba72b4abb85a52c489812b32c2d1aee36/Chapter2/Exercises2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505325302033, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7596657828525876}}
{"text": "theory Assertion imports\n\"State\"\n\nbegin\n\nno_notation FForm (\"F _\")\nno_notation EExp (\"E _\")\n\n(*evalF defines the semantics of assertions written in first-order logic*)\nprimrec evalF :: \"state => fform => bool\" where\n\"evalF (f,WTrue) = (True)\" |\n\"evalF (f,WFalse) = (False)\" |\n\"evalF (f,e1 [=] e2) = (case (evalE (f,e1), evalE (f,e2)) of\n                            (RR (r1),RR (r2)) => ((r1::real) = r2) |\n                            (SS (r1),SS (r2)) => ((r1::string) = r2) | \n                            (BB (r1),BB (r2)) => ((r1::bool) = r2) | \n                            (_,_) => False)\" |\n\"evalF (f,e1 [<] e2) = (case (evalE (f,e1), evalE (f,e2)) of\n                            (RR (r1),RR (r2)) => ((r1::real) < r2) | \n                            (_,_) => False)\" |\n\"evalF (f,e1 [>] e2) = (case (evalE (f,e1), evalE (f,e2)) of\n                            (RR (r1),RR (r2)) => (r1::real) > r2 | \n                            (_,_) => False)\" |\n\"evalF (f,[~] form1) = (~ (evalF (f,form1)))\" |\n\"evalF (f,form1 [&] form2) = ((evalF (f,form1)) & (evalF (f,form2)))\" |\n\"evalF (f,form1 [|] form2) = ((evalF (f,form1)) | (evalF (f,form2)))\" |\n\"evalF (f,form1 [-->] form2) = ((evalF (f,form1)) --> (evalF (f,form2)))\" |\n\"evalF (f,form1 [<->] form2) = ((evalF (f,form1)) \\<longleftrightarrow> (evalF (f,form2)))\" |\n\"evalF (f,WALL x form1)= (ALL (v::real). (evalF((%a. %i. (if (a=x) then (RR (v)) else (f(a, i)))), form1)))\" |\n\"evalF (f,WEX x form1)= (EX (v::real). evalF((%a. %i. (if (a=x) then (RR (v)) else f(a, i))), form1))\"\n\n\ndefinition evalFP :: \"cstate => fform => now => bool\" where\n\"evalFP(f,P,c) == ALL s. inList(s,f(c)) --> evalF(s,P)\"\n\n(*ievalF defines the semantics of assertions written in interval logic and duration calculus*)\nconsts ievalF :: \"cstate => fform => now => now => bool\"\naxiomatization where\nchop_eval: \"ievalF (f, P[^]Q, c, d) =  (EX k s1 s2. s1@s2=f(k) & ievalF (%t. if t=k then s1 else f(t), P, c, k)\n                                                  & ievalF (%t. if t=k then s2 else f(t), Q, k, d))\" and\nchop_sep: \"ievalF (f, P, c, d) = (ALL k s1 s2. s1@s2=f(k) --> ievalF (%t. if t=k then s1 else f(t), P, c, k)\n                                                  & ievalF (%t. if t=k then s2 else f(t), P, k, d))\" and\npf_eval: \"ievalF (f, pf (P), c, d) = (c=d & (EX s. inList(s, f(c))) & evalF (s, P))\" and\nhigh_eval: \"ievalF (f, high P, c, d) = ((ALL (k::real). (c<k & k<d) --> evalFP (f, P, k)))\" and\nchop_interval: \"(ALL t. (c=d --> f(c)=g(c)) & (c<=t & t<=d --> f(t)=g(t))) ==> ievalF(f,P,c,d)=ievalF(g,P,c,d)\"\n\nlemma chop_eval1: \"(EX k. ievalF (f, P, c, k) & ievalF (f, Q, k, d)) ==> ievalF (f, P[^]Q, c, d)\"\napply (simp add: chop_eval,auto)\napply (cut_tac x=k in exI,auto)\napply (cut_tac x=\"f(k)\" in exI,auto)\napply (subgoal_tac \"f = (%t. if t = k then f(k) else f(t))\",auto)\napply (subgoal_tac \"(ALL ka s1 s2. s1@s2=f(ka) --> ievalF (%t. if t=ka then s1 else f(t), Q, k, ka)\n                                                  & ievalF (%t. if t=ka then s2 else f(t), Q, ka, d))\")\napply (subgoal_tac \"ievalF(%t. if t = k then f(k) else f(t), Q, k, k) &\n               ievalF(%t. if t = k then [] else f(t), Q, k, d)\")\napply blast\napply (erule allE)+\napply blast\napply (cut_tac f=f and P=Q and c=k and d=d in chop_sep,auto)\ndone\n\n(*The following axioms define the evaluation of formulas of part of first-order interval logic.*)\naxiomatization where\nTrue_eval : \"ievalF (f,WTrue, c, d) = (True)\"  and\nFalse_eval : \"ievalF (f,WFalse,c,d) = (False)\" and\nL_eval : \"ievalF (f, (l [=] Real L), c, d) = (d-c = L)\" and \n(*Equal_eval : \"ievalF (f,e1 [=] e2,c,d) = evalFP(f,e1 [=] e2,c)\" and\nLess_eval : \"ievalF (f,e1 [<] e2,c,d) = evalFP(f,e1 [<] e2,c)\" and\nGreat_eval: \"ievalF (f,e1 [>] e2,c,d) = evalFP(f,e1 [>] e2,c)\" and*)\nNot_eval: \"ievalF (f,[~] form1,c,d) = (~ (ievalF (f,form1,c,d)))\" and\nAnd_eval: \"ievalF (f,form1 [&] form2,c,d) = ((ievalF (f,form1,c,d)) & (ievalF (f,form2,c,d)))\" and\nOr_eval: \"ievalF (f,F' [|] G,c,d) = ((ievalF (f,F',c,d)) | (ievalF (f,G,c,d)))\" and\nImply_eval: \"ievalF (f,form1 [-->] form2,c,d) = ((ievalF (f,form1,c,d)) --> (ievalF (f,form2,c,d)))\" and\nEquiv_eval: \"ievalF (f,form1 [<->] form2,c,d) = ((ievalF (f,form1,c,d)) \\<longleftrightarrow> (ievalF (f,form2,c,d)))\" and\nALL_eval: \"ievalF (f,WALL x form1,c,d)= (ALL (v::real). ievalF((%t. List.map(%s. %y i. if y=x & i=R then RR(v) else s(y,i),f(t))), form1, c, d))\" and\nEX_eval: \"ievalF (f,WEX x form1,c,d)= (EX (v::real). ievalF((%t. List.map(%s. %y i. if y=x & i=R then RR(v) else s(y,i),f(t))), form1, c, d))\"\n\n(*The following axioms define the semantic meanings of closure of formulas.*)\naxiomatization where\nclose_fact1: \"ALL t. (t>=b & t<c --> evalF (f, p)) --> (evalF (f, close(p)))\" and\nclose_fact2: \"ALL t. (t>=b & t<c --> evalF (f, p)) --> (evalF (f, close([~]p)))\" and\nclose_fact3: \"evalF (s,p) ==> evalF (s,close(p))\"\n\nend\n", "meta": {"author": "bzhan", "repo": "mars", "sha": "d10e489a8ddf128a4cbac13291efdece458d732d", "save_path": "github-repos/isabelle/bzhan-mars", "path": "github-repos/isabelle/bzhan-mars/mars-d10e489a8ddf128a4cbac13291efdece458d732d/HHLProver/Assertion.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.8198933425148213, "lm_q1q2_score": 0.7594702649507348}}
{"text": "theory Concrete_Semantics_5_1\n  imports Main\nbegin\n\nlemma \"\\<not> surj (f::'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"surj f\"\n(*\nfrom 0 have 1: \"8A: 9 a: A = f a\" by(simp add: surj_def )\nfrom 1 have 2: \"9 a: fx : x =2 f x g = f a\" by blast\nfrom 2 show \"False\" by blast\n*)\n  hence 1: \"\\<exists>a. {x. x \\<notin> f x} = f a\" by (auto simp add: surj_def)\n  thus \"False\" by blast\nqed\n\nlemma \n  fixes f :: \"'a \\<Rightarrow> 'a set\"\n  assumes s: \"surj f\"\n  shows \"False\"\nproof -\n  have \"\\<exists>a. {x. x \\<notin> f x} = f a\" using s by (auto simp: surj_def)\n  thus \"False\" by blast\nqed\n\nlemma \"\\<not> surj (f::'a \\<Rightarrow> 'a set)\"\nproof\n  assume\"surj f\"\n  hence \"\\<exists> a. {x. x \\<notin> f x} = f a\" by (auto simp: surj_def)\n  then obtain a where \"{x. x \\<notin> f x} = f a\" by blast\n  hence \"a \\<notin> f a \\<longleftrightarrow> a \\<in> f a\" by blast\n  thus \"False\" by blast\nqed\n\n\nlemma \n  fixes a b :: int\n  assumes \"b dvd (a + b)\"\n  shows \"b dvd a\"\nproof-\n  have \"\\<exists>k'. a = b * k'\" if asm: \"a + b = b*k\" for k\n  proof \n    show \"a = b *(k - 1)\" using asm by (simp add: algebra_simps)\n  qed\n  thus ?thesis using assms by(auto simp add: dvd_def)\nqed\n\n(* Exercise 5.1. *)\nlemma assumes T: \"\\<forall> x y. T x y \\<or> T y x\"\n  and A: \"\\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n  and TA: \"\\<forall> x y. T x y \\<longrightarrow> A x y\" \n  and \"A x y\"\n  shows \"T x y\"\nproof(rule ccontr)\n  assume \"\\<not> T x y\"\n  hence \"T y x\" using T by blast\n  hence \"A y x\" using TA by blast\n  hence \"x = y\" using assms by auto\n  hence \"T x x\" using T by auto\n  hence \"T x y\" using `x = y` by auto \n  thus \"False\" using `\\<not> T x y` by auto\nqed\n\n(* Exercise 5.2. *)\nlemma \"\\<exists> ys zs. xs = ys @ zs \\<and>\n        (length ys = length zs \\<or> length ys = length zs + 1)\"\nproof cases\n  assume \"even (length xs)\"\n  then obtain a where \"length xs = 2 * a\" by auto\n    let ?ys = \"take a xs\"\n    let ?zs = \"drop a xs\"\n    have \"xs = ?ys @ ?zs \\<and>length ?ys = length ?zs\" by(simp add: `length xs = 2 * a`)\n    hence \"xs = ?ys @ ?zs \\<and>\n        (length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1)\" by (auto)\n    thus ?thesis by blast\nnext\n  assume \"odd (length xs)\"\n  then obtain a where \"length xs = (2 * a) + 1\" \n    using oddE by blast\n    let ?ys = \"take (a + 1) xs\"\n    let ?zs = \"drop (a + 1) xs\"\n    have \"xs = ?ys @ ?zs \\<and> length ?ys = length ?zs + 1\" by (simp add: \\<open>length xs = 2 * a + 1\\<close>)\n    hence \"xs = ?ys @ ?zs \\<and>\n        (length ?ys = length ?zs \\<or> length ?ys = length ?zs + 1)\" by (auto)\n    thus ?thesis  by blast\nqed\n\n\n(* Chap 5.4 *)\n\nlemma \"length(tl xs) = length xs - 1\"\nproof (cases xs)\n(*\n  assume \"xs = []\"\n*)\n  case Nil\n  then show ?thesis by simp\nnext\n(*\n  fix y ys assume \"xs = y#ys\"\n*)\n  case (Cons y ys)\n  then show ?thesis \n    by simp\nqed\n\nlemma \"\\<Sum>{0..n::nat} = n*(n+1) div 2\" (is \"?P n\")\nproof(induction n)\n  show \"?P 0\" by simp\nnext\n  fix n assume  \"?P n\"\n  thus  \"?P (Suc n)\" by simp\nqed\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\nlemma \"ev n \\<Longrightarrow> evn n\"\nproof(induction rule: ev.induct)\n  case ev0\n  show ?case by simp\n(*case ev0 show ?case by simp*)\nnext\n  case evSS\n  thus ?case by simp\n(* case (evSS m)\nhave \"evn(Suc(Suc m)) = evn m\" by simp\nthus ?case using hevn mi by blast *)\nqed\n\nlemma not_even_1:\"\\<not> ev(Suc 0)\"\nproof\n  assume \"ev(Suc 0)\" then show False by cases\nqed\n\n(* Exercise 5.4. *)\n\nlemma \"\\<not> ev(Suc(Suc(Suc 0)))\"\nproof\n  assume \"ev(Suc(Suc(Suc 0)))\" thus False\n  proof cases\n    assume \"ev(Suc 0)\" thus False by cases\n  qed\n(*  assume \"ev(Suc(Suc(Suc 0)))\" \n  hence \"ev(Suc 0)\" \n    using ev.cases by auto\n  then show False by (auto simp add: not_even_1)*)\nqed\n\nlemma \"ev(Suc m) \\<Longrightarrow> \\<not> ev m\"\nproof(induction \"Suc m\" arbitrary: m rule: ev.induct)\n  fix n assume IH: \"\\<And>m. n = Suc m \\<Longrightarrow> \\<not> ev m\"\n  show \"\\<not> ev (Suc n)\"\n  proof \n    assume \"ev (Suc n)\"\n    thus False\n    proof cases\n      fix k assume \"n = Suc k\" \"ev k\"\n      thus False using IH by auto\n    qed\n  qed\nqed\n\n(* Exercise 5.3. *)\n\n(*it is not able to use rule: ev.induct, because if n = 0 then it were failed.*)\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\nproof -\n  show \"ev n\" \n    using assms ev.cases by blast\nqed\n\n(* Exercise 5.5. *) \n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter:: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter_refl: \"iter r n x x\" |\niter_step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r n x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof(induction rule:iter.induct)\ncase (iter_refl n x)\n  then show ?case \n    by (simp add: star.refl)\nnext\n  case (iter_step x y n z)\nthen show ?case \n  by (meson star.step)\nqed\n\n(*Exercise 5.6.*)\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (x#xs) = {x} \\<union> elems xs\" \n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\ncase Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  show ?case \n  proof cases\n    assume \"x = a\"\n    then obtain zs where \"x#zs = a#xs\" by blast\n    let ?ys = \"[]\"\n    have \"x \\<notin> elems ?ys\" \n      by simp\n    show ?case \n      using \\<open>x = a\\<close> \\<open>x \\<notin> elems []\\<close> by blast\n  next\n    assume \"x \\<noteq> a\"\n(* get lists `ys` and `zs`, which were introduced from IH *)\n(* it is not possible to use the following:\n\"by (auto simp add:`x \\<in> elems(Cons a xs)`)\"\n. So I use \"from A B have ...\".\n*)\n    from this `x \\<in> elems(Cons a xs)` have \"x \\<in> elems xs\" by auto\n    then obtain ys zs where \"xs = ys @ x # zs \\<and> x \\<notin> elems ys\" \n      using Cons.IH by auto\n(*It is not possible to derive ?case from this result.\nBecause we need the case of \"a # xs =...\"\n*)\n    from this `x \\<noteq> a` obtain ys' where \"a # xs = ys' @ x # zs \\<and> x \\<notin> elems ys'\" by force      \n    show ?case \n      using \\<open>a # xs = ys' @ x # zs \\<and> x \\<notin> elems ys'\\<close> by auto\n  qed\nqed\n\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\ns_emp: \"S[]\" |\ns_list: \"S xs \\<Longrightarrow> S (a # xs @ [b])\" |\ns_const: \"S xs \\<Longrightarrow> S ys \\<Longrightarrow> S(xs@ys)\"\n\n(* Should not use S in def of balanced.\n0 abab \\<Rightarrow> 1 bab \\<Rightarrow> 0 ab \\<Rightarrow> 1 b \\<Rightarrow> 0 []: True\n\n0 abb \\<Rightarrow> 1 bb \\<Rightarrow> 0 b \\<Rightarrow> -1 b \\<Rightarrow> -2 []: False\n\n0 aab \\<Rightarrow> 1 ab \\<Rightarrow> 2 b \\<Rightarrow> 1 [] : False \n*)\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n\"balanced 0 [] = True\" |\n\"balanced n (a#xs) = balanced (Suc n) xs\" |\n\"balanced (Suc n) (b#xs) = balanced n xs\" |\n\"balanced _ _ = False\"\n\nlemma\n  fixes n w\n  assumes b: \"balanced n w\"\n  shows \"S (replicate n a @ w)\"\nproof -\n  from b show ?thesis\n  proof(induction w)\n    case Nil\n    then show ?case \n    proof (induction n)\n      case 0\n      then show ?case \n        by (simp add: s_emp)\n    next\n      case (Suc n)\n      then show ?case \n        by simp\n    qed\n  next\n    case (Cons a w)\n    then show ?case \n    proof (induction n)\n      case 0\n      then show ?case sorry\n    next\n      case (Suc n)\n      then show ?case sorry\n        \n    qed\n  qed\nqed\n\nlemma \n  fixes n w\n  assumes s: \"S (replicate n a @ w)\"\n  shows \"balanced n w\"\nproof (induction w)\n  case Nil\n  then show ?case sorry\nnext\n  case (Cons a w)\n  then show ?case sorry\nqed\n\ncorollary \"balanced n w \\<longleftrightarrow> S (replicate n a @ w)\"\nproof (induction w)\n  case Nil\n  then have \"balanced n [] \\<Longrightarrow> S(replicate n a @ [])\"\n  proof (induction n)\n    case 0\n    then show ?case \n      by (simp add: s_emp)\n  next\n    case (Suc n)\n    then show ?case sorry\n  qed\n  then have \"S(replicate n a @ []) \\<Longrightarrow> balanced n w\"\n  proof (induction n)\n    case 0\n    then show ?case sorry\n  next\n    case (Suc n)\n    then show ?case sorry\n  qed\n  then show ?case sorry\nnext\n  case (Cons a w)\n  then have \"balanced n w \\<Longrightarrow> S(replicate n a @ w)\"\n  proof(induction n)\n    case 0\n    then show ?case sorry\n  next\n    case (Suc n)\n    then show ?case sorry\n  qed\n\n  then have \"S(replicate n a @ w) \\<Longrightarrow> balanced n w\"\n  proof(induction n)\n    case 0\n    then show ?case sorry\n  next\n    case (Suc n)\n    then show ?case sorry\n  qed\n  then show ?case sorry\nqed\n\n\n\nend\n", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/previous_studied_result/Concrete_Semantics_5_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.8723473813156294, "lm_q1q2_score": 0.7594632531343165}}
{"text": "(*\n  File:                      Duplicate_Free_Multiset.thy\n  Authors and contributors:  Mathias Fleury, Daniela Kaufmann, JKU;\n                             Jose Divasón, Sebastiaan Joosten, René Thiemann, Akihisa Yamada\n*)\n\ntheory Duplicate_Free_Multiset\nimports Multiset_More\nbegin\n\nsection \\<open>Duplicate Free Multisets\\<close>\n\ntext \\<open>Duplicate free multisets are isomorphic to finite sets, but it can be useful to reason about\n  duplication to speak about intermediate execution steps in the refinements.\n\\<close>\n\ndefinition distinct_mset :: \"'a multiset \\<Rightarrow> bool\" where\n  \"distinct_mset S \\<longleftrightarrow> (\\<forall>a. a \\<in># S \\<longrightarrow> count S a = 1)\"\n\nlemma distinct_mset_count_less_1: \"distinct_mset S \\<longleftrightarrow> (\\<forall>a. count S a \\<le> 1)\"\n  using eq_iff nat_le_linear unfolding distinct_mset_def by fastforce\n\nlemma distinct_mset_empty[simp]: \"distinct_mset {#}\"\n  unfolding distinct_mset_def by auto\n\nlemma distinct_mset_singleton: \"distinct_mset {#a#}\"\n  unfolding distinct_mset_def by auto\n\nlemma distinct_mset_union:\n  assumes dist: \"distinct_mset (A + B)\"\n  shows \"distinct_mset A\"\n  unfolding distinct_mset_count_less_1\nproof (rule allI)\n  fix a\n  have \\<open>count A a \\<le> count (A + B) a\\<close> by auto\n  moreover have \\<open>count (A + B) a \\<le> 1\\<close>\n    using dist unfolding distinct_mset_count_less_1 by auto\n  ultimately show \\<open>count A a \\<le> 1\\<close>\n    by simp\nqed\n\nlemma distinct_mset_minus[simp]: \"distinct_mset A \\<Longrightarrow> distinct_mset (A - B)\"\n  by (metis diff_subset_eq_self mset_subset_eq_exists_conv distinct_mset_union)\n\nlemma distinct_mset_rempdups_union_mset:\n  assumes \"distinct_mset A\" and \"distinct_mset B\"\n  shows \"A \\<union># B = remdups_mset (A + B)\"\n  using assms nat_le_linear unfolding remdups_mset_def\n  by (force simp add: multiset_eq_iff max_def count_mset_set_if distinct_mset_def not_in_iff)\n\nlemma distinct_mset_add_mset[simp]: \"distinct_mset (add_mset a L) \\<longleftrightarrow> a \\<notin># L \\<and> distinct_mset L\"\n  unfolding distinct_mset_def\n  apply (rule iffI)\n   apply (auto split: if_split_asm; fail)[]\n  by (auto simp: not_in_iff; fail)\n\nlemma distinct_mset_size_eq_card: \"distinct_mset C \\<Longrightarrow> size C = card (set_mset C)\"\n  by (induction C) auto\n\nlemma distinct_mset_add:\n  \"distinct_mset (L + L') \\<longleftrightarrow> distinct_mset L \\<and> distinct_mset L' \\<and> L \\<inter># L' = {#}\"\n  by (induction L arbitrary: L') auto\n\nlemma distinct_mset_set_mset_ident[simp]: \"distinct_mset M \\<Longrightarrow> mset_set (set_mset M) = M\"\n  by (induction M) auto\n\nlemma distinct_finite_set_mset_subseteq_iff[iff]:\n  assumes \"distinct_mset M\" \"finite N\"\n  shows \"set_mset M \\<subseteq> N \\<longleftrightarrow> M \\<subseteq># mset_set N\"\n  by (metis assms distinct_mset_set_mset_ident finite_set_mset msubset_mset_set_iff)\n\nlemma distinct_mem_diff_mset:\n  assumes dist: \"distinct_mset M\" and mem: \"x \\<in> set_mset (M - N)\"\n  shows \"x \\<notin> set_mset N\"\nproof -\n  have \"count M x = 1\"\n    using dist mem by (meson distinct_mset_def in_diffD)\n  then show ?thesis\n    using mem by (metis count_greater_eq_one_iff in_diff_count not_less)\nqed\n\nlemma distinct_set_mset_eq:\n  assumes \"distinct_mset M\" \"distinct_mset N\" \"set_mset M = set_mset N\"\n  shows \"M = N\"\n  using assms distinct_mset_set_mset_ident by fastforce\n\nlemma distinct_mset_union_mset[simp]:\n  \\<open>distinct_mset (D \\<union># C) \\<longleftrightarrow> distinct_mset D \\<and> distinct_mset C\\<close>\n  unfolding distinct_mset_count_less_1 by force\n\nlemma distinct_mset_inter_mset:\n  \"distinct_mset C \\<Longrightarrow> distinct_mset (C \\<inter># D)\"\n  \"distinct_mset D \\<Longrightarrow> distinct_mset (C \\<inter># D)\"\n  by (auto simp add: distinct_mset_def min_def count_eq_zero_iff elim!: le_SucE)\n\nlemma distinct_mset_remove1_All: \"distinct_mset C \\<Longrightarrow> remove1_mset L C = removeAll_mset L C\"\n  by (auto simp: multiset_eq_iff distinct_mset_count_less_1)\n\nlemma distinct_mset_size_2: \"distinct_mset {#a, b#} \\<longleftrightarrow> a \\<noteq> b\"\n  by auto\n\nlemma distinct_mset_filter: \"distinct_mset M \\<Longrightarrow> distinct_mset {# L \\<in># M. P L#}\"\n  by (simp add: distinct_mset_def)\n\nlemma distinct_mset_mset_distinct[simp]: \\<open>distinct_mset (mset xs) = distinct xs\\<close>\n  by (induction xs) auto\n\nlemma distinct_image_mset_inj:\n  \\<open>inj_on f (set_mset M) \\<Longrightarrow> distinct_mset (image_mset f M) \\<longleftrightarrow> distinct_mset M\\<close>\n  by (induction M) (auto simp: inj_on_def)\n\nlemma distinct_mset_remdups_mset_id: \\<open>distinct_mset C \\<Longrightarrow> remdups_mset C = C\\<close>\n  by (induction C)  auto\n\nlemma distinct_mset_image_mset:\n  \\<open>distinct_mset (image_mset f (mset xs)) \\<longleftrightarrow> distinct (map f xs)\\<close>\n  apply (subst mset_map[symmetric])\n  apply (subst distinct_mset_mset_distinct)\n  ..\n\nlemma distinct_mset_mono: \\<open>D' \\<subseteq># D \\<Longrightarrow> distinct_mset D \\<Longrightarrow> distinct_mset D'\\<close>\n  by (metis distinct_mset_union subset_mset.le_iff_add)\n\nlemma distinct_mset_mono_strict: \\<open>D' \\<subset># D \\<Longrightarrow> distinct_mset D \\<Longrightarrow> distinct_mset D'\\<close>\n  using distinct_mset_mono by auto\n\nlemma distinct_set_mset_eq_iff:\n  assumes \\<open>distinct_mset M\\<close> \\<open>distinct_mset N\\<close>\n  shows \\<open>set_mset M = set_mset N \\<longleftrightarrow> M = N\\<close>\n  using assms distinct_mset_set_mset_ident by fastforce\n\nlemma distinct_mset_union2:\n  \\<open>distinct_mset (A + B) \\<Longrightarrow> distinct_mset B\\<close>\n  using distinct_mset_union[of B A]\n  by (auto simp: ac_simps)\n\nlemma distinct_mset_mset_set: \\<open>distinct_mset (mset_set A)\\<close>\n  unfolding distinct_mset_def count_mset_set_if by (auto simp: not_in_iff)\n\nlemma distinct_mset_inter_remdups_mset:\n  assumes dist: \\<open>distinct_mset A\\<close>\n  shows \\<open>A \\<inter># remdups_mset B = A \\<inter># B\\<close>\nproof -\n  have [simp]: \\<open>A' \\<inter># remove1_mset a (remdups_mset Aa) = A' \\<inter># Aa\\<close>\n    if\n      \\<open>A' \\<inter># remdups_mset Aa = A' \\<inter># Aa\\<close> and\n      \\<open>a \\<notin># A'\\<close> and\n      \\<open>a \\<in># Aa\\<close>\n    for A' Aa :: \\<open>'a multiset\\<close> and a\n  by (metis insert_DiffM inter_add_right1 set_mset_remdups_mset that)\n\n  show ?thesis\n    using dist\n    apply (induction A)\n    subgoal by auto\n     subgoal for a A'\n       by (cases \\<open>a \\<in># B\\<close>)\n         (use multi_member_split[of a \\<open>B\\<close>]  multi_member_split[of a \\<open>A\\<close>] in\n           \\<open>auto simp: mset_set.insert_remove\\<close>)\n    done\nqed\n\nabbreviation (input) is_mset_set :: \\<open>'a multiset \\<Rightarrow> bool\\<close>\n  where \\<open>is_mset_set \\<equiv> distinct_mset\\<close>\n\nlemma is_mset_set_def:\n  \\<open>is_mset_set X \\<longleftrightarrow> (\\<forall>x \\<in># X. count X x = 1)\\<close>\n  by (auto simp add: distinct_mset_def)\n\nlemma is_mset_setD[dest]: \"is_mset_set X \\<Longrightarrow> x \\<in># X \\<Longrightarrow> count X x = 1\"\n  unfolding is_mset_set_def by auto\n\nlemma is_mset_setI[intro]:\n  assumes \"\\<And>x. x \\<in># X \\<Longrightarrow> count X x = 1\"\n  shows \"is_mset_set X\"\n  using assms unfolding is_mset_set_def by auto\n\nlemma is_mset_set[simp]: \"is_mset_set (mset_set X)\"\n  by (fact distinct_mset_mset_set)\n\nlemma is_mset_set_add[simp]:\n  \"is_mset_set (X + {#x#}) \\<longleftrightarrow> is_mset_set X \\<and> x \\<notin># X\" (is \"?L \\<longleftrightarrow> ?R\")\nproof(intro iffI conjI)\n  assume L: ?L\n  with count_eq_zero_iff count_single show \"is_mset_set X\"\n    unfolding is_mset_set_def\n    by (metis (no_types, opaque_lifting) add_mset_add_single count_add_mset nat.inject set_mset_add_mset_insert union_single_eq_member)\n  show \"x \\<notin># X\"\n  proof\n    assume \"x \\<in># X\"\n    then have \"count (X + {#x#}) x > 1\" by auto\n    with L show False by (auto simp: is_mset_set_def)\n  qed\nnext\n  assume R: ?R show ?L\n  proof\n    fix x' assume x': \"x' \\<in># X + {#x#}\"\n    show \"count (X + {#x#}) x' = 1\"\n    proof(cases \"x' \\<in># X\")\n      case True with R have \"count X x' = 1\" by auto\n        moreover from True R have \"count {#x#} x' = 0\" by auto\n        ultimately show ?thesis by auto\n    next\n      case False then have \"count X x' = 0\" by (simp add: not_in_iff)\n        with R x' show ?thesis by auto\n    qed\n  qed\nqed\n\nlemma mset_set_id:\n  assumes \"is_mset_set X\"\n  shows \"mset_set (set_mset X) = X\"\n  using assms by (fact distinct_mset_set_mset_ident)\n\nlemma is_mset_set_image:\n  assumes \"inj_on f (set_mset X)\" and \"is_mset_set X\"\n  shows \"is_mset_set (image_mset f X)\"\nproof (cases X)\n  case empty then show ?thesis by auto\nnext\n  case (add x X)\n    define X' where \"X' \\<equiv> add_mset x X\"\n    with assms add have inj:\"inj_on f (set_mset X')\"\n          and X': \"is_mset_set X'\" by auto\n  show ?thesis\n  proof(unfold add, intro is_mset_setI, fold X'_def)\n    fix y assume \"y \\<in># image_mset f X'\"\n    then have \"y \\<in> f ` set_mset X'\" by auto \n    with inj have \"\\<exists>!x'. x' \\<in># X' \\<and> y = f x'\" by (meson imageE inj_onD)\n    then obtain x' where x': \"{x'. x' \\<in># X' \\<and> y = f x'} = {x'}\" by auto\n    then have \"count (image_mset f X') y = count X' x'\"\n      by (simp add: count_image_mset')\n    also from X' x' have \"... = 1\" by auto\n    finally show \"count (image_mset f X') y = 1\".\n  qed\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Nested_Multisets_Ordinals/Duplicate_Free_Multiset.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.8688267728417087, "lm_q1q2_score": 0.7594216977427936}}
{"text": "(*\n    $Id: sol.thy,v 1.5 2012/08/13 15:59:05 webertj Exp $\n    Author: Gerwin Klein\n*)\n\nheader {* The Towers of Hanoi *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {*\nWe are given 3 pegs $A$, $B$ and $C$, and $n$ disks with a hole, such that no\ntwo disks have the same diameter.  Initially all $n$ disks rest on peg $A$,\nordered according to their size, with the largest one at the bottom.  The aim\nis to transfer all $n$ disks from $A$ to $C$ by a sequence of single-disk moves\nsuch that we never place a larger disk on top of a smaller one.  Peg $B$ may be\nused for intermediate storage.\n\n\\begin{center}\n\\includegraphics[width=0.8\\textwidth]{Hanoi}\n\\end{center}\n\n\\medskip The pegs and moves can be modelled as follows:\n*}\n\ndatatype peg = A | B | C\n\ntype_synonym move = \"peg * peg\"\n\ntext {*\nDefine a primitive recursive function\n\n  @{text \"move :: nat => peg => peg => move list\"}\n\nsuch that @{term move}$~n~a~b$ returns a list of (legal) moves that transfer\n$n$ disks from peg $a$ to peg $c$.\n*}\n\nprimrec other :: \"peg \\<Rightarrow> peg \\<Rightarrow> peg\" where\n  \"other A x = (if x = B then C else B)\"\n| \"other B x = (if x = A then C else A)\"\n| \"other C x = (if x = A then B else A)\"\n\nprimrec move :: \"nat \\<Rightarrow> peg \\<Rightarrow> peg \\<Rightarrow> move list\" where\n  \"move 0       src dst = []\"\n| \"move (Suc n) src dst = (move n src (other src dst)) @ [(src,dst)] @ (move n (other src dst) dst)\"\n\n\ntext {*\nShow that this requires $2^n - 1$ moves:\n*}\n\ntheorem \"length (move n a b) = 2^n - 1\"\n(*<*) oops (*>*)\n\ntext {*\nHint: You need to strengthen the theorem for the induction to go through.\nBeware: subtraction on natural numbers behaves oddly: $n - m = 0$ if $n \\le m$.\n*}\n\nlemma \"\\<forall>x y. length (move n x y) = 2^n - 1\"\n  apply (induct n)\n    apply simp\n  apply auto\ndone\n\n\nsubsection {* Correctness *}\n\ntext {*\nIn the last section we introduced the towers of Hanoi and defined a function\n@{term move} to generate the moves to solve the puzzle.  Now it is time to show\nthat @{term move} is correct.  This means that\n\\begin{itemize}\n\\item when executing the list of moves, the result is indeed the intended one,\n      i.e.\\ all disks are moved from one peg to another, and\n\\item all of the moves are legal, i.e.\\ never is a larger disk placed on top of\n      a smaller one.\n\\end{itemize}\n\nHint: This is a non-trivial undertaking.  The complexity of your proofs will\ndepend crucially on your choice of model, and you may have to revise your model\nas you proceed with the proof.\n*}\n\ntype_synonym\n  config = \"peg \\<Rightarrow> nat list\"\n\nprimrec lt :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"lt n [] = True\"\n| \"lt n (x#xs) = (n < x \\<and> lt n xs)\"\n\nprimrec ordered :: \"nat list \\<Rightarrow> bool\" where\n  \"ordered [] = True\"\n | \"ordered (x#xs) = (lt x xs \\<and> ordered xs)\"\n\ndefinition hanoi :: \"config \\<Rightarrow> bool\" where\n  \"hanoi cfg \\<equiv> \\<forall>s. ordered (cfg s)\"\n\ndefinition step :: \"config \\<Rightarrow> move \\<Rightarrow> config option\" where\n  \"step c x \\<equiv> let (src,dst) = x in \n    if c src = [] then None\n    else let src' = tl (c src); \n             m = hd (c src); \n             dst' = m # (c dst);\n             c' = (c (src:= src')) (dst:= dst') \n         in if hanoi c' then Some c' else None\"\n\nprimrec exec :: \"config \\<Rightarrow> move list \\<Rightarrow> config option\" where\n  \"exec c [] = Some c\"\n| \"exec c (x#xs) = (let cfg' = step c x in if cfg' = None then None else exec (the cfg') xs)\"\n\nprimrec tower :: \"nat \\<Rightarrow> nat list\" where\n  \"tower 0 = []\"\n| \"tower (Suc n) = tower n @ [Suc n]\"\n\n\n\nlemma \"move 1 A C = [(A,C)]\"\n  by simp\n\nlemma \"move 2 A C = [(A, B), (A, C), (B, C)]\"\n  by (simp add: numeral_2_eq_2)\n\nlemma \"move 3 A C = [(A, C), (A, B), (C, B), (A, C), (B, A), (B, C), (A, C)]\"\n  by (simp add: numeral_3_eq_3)\n\nlemma [simp]:\n  \"\\<forall>cfg. exec cfg (a@b) = (let cfg' = exec cfg a in if cfg' = None then None else exec (the cfg') b)\"\n  by (induct a, auto simp add: Let_def)\n \nlemma neq_Nil_snoC:\n  \"\\<forall>n. length xs = Suc n \\<longrightarrow> (\\<exists>x' xs'. xs = xs' @ [x'])\"\n  apply (induct xs)\n  apply simp\n  apply clarsimp\n  apply (case_tac xs)\n   apply simp\n  apply clarsimp\n  done\n\nlemma otherF [simp]: \"x = other x y \\<Longrightarrow> False\"\n  apply (cases x, auto split: split_if_asm)\n  done\n\nlemma [simp]: \"x\\<noteq>y \\<Longrightarrow> other x (other x y) = y\"\n  apply (cases x)\n  apply (cases y, auto)+\n  done\n\nlemma [simp]: \"x\\<noteq>y \\<Longrightarrow> other (other x y) y = x\"\n  apply (cases x)\n  apply (cases y, auto)+\n  done\n\nprimrec gt :: \"nat \\<Rightarrow> nat list \\<Rightarrow> bool\" where\n  \"gt n [] = True\"\n| \"gt n (x#xs) = (x < n \\<and>  gt n xs)\"\n\nlemma [simp]:\n  \"lt n (a@b) = (lt n a \\<and> lt n b)\"\n  apply (induct a)\n  apply auto\n  done\n\nlemma [simp]:\n  \"gt n (a@b) = (gt n a \\<and> gt n b)\"\n  apply (induct a)\n  apply auto\ndone\n\nlemma lt_mono [rule_format, simp]:\n  \"a < b \\<longrightarrow> lt b xs \\<longrightarrow> lt a xs\"\n  apply (induct xs)\n  apply auto\ndone\n\nlemma [simp]:\n  \"ordered (a@n#b) = (ordered a \\<and> lt n b \\<and> gt n a \\<and> ordered b)\"\n  apply (induct a)\n   apply simp\n  apply auto\ndone  \n  \nlemma gt_iff:\n  \"gt n xs = (\\<forall>x \\<in> set xs. x < n)\"\n  by (induct xs, auto)\n  \nlemma [simp]:\n  \"xs \\<noteq> [] \\<longrightarrow> last xs \\<in> set xs\"\n  by (induct xs, auto)\n\nlemma [simp]:\n  \"\\<lbrakk>cfg src = ts' @ t' # xs; hanoi cfg; ts' \\<noteq> []\\<rbrakk> \\<Longrightarrow> last ts' < t'\"\n  apply (unfold hanoi_def)\n  apply (erule_tac x = src in allE)\n  apply (clarsimp simp add: gt_iff)\ndone\n\nlemma neq_other:\n  \"\\<lbrakk> s \\<noteq> src; s \\<noteq> dst; src\\<noteq>dst \\<rbrakk> \\<Longrightarrow> s = other src dst\"\n  apply (cases src, auto)\n  apply (cases s, auto)\n  apply (cases s, auto)\n  apply (cases dst, auto)\n  apply (cases s, auto)\n  apply (cases s, auto)\n  apply (cases dst, auto)\n  apply (cases s, auto)\n  apply (cases s, auto)  \n  apply (cases dst, auto)\n  done\n\nlemma ordered_appendI [rule_format]:\n  \"ordered a \\<longrightarrow> lt t b \\<longrightarrow> gt t a \\<longrightarrow> ordered b \\<longrightarrow> ordered (a@b)\"\n  by (induct a, auto)\n\nlemma [simp]:\n  \"\\<forall>cfg. exec cfg xs = Some cfg' \\<longrightarrow> hanoi cfg \\<longrightarrow> hanoi cfg'\"\n  apply (induct xs)\n   apply simp\n  apply (auto simp add: step_def Let_def split: split_if_asm)\ndone\n\nlemma hanoi_lemma:\n  \"\\<forall>cfg src dst t xs ys zs. \n       cfg src = t @ xs \\<longrightarrow> cfg dst = ys \\<longrightarrow> cfg (other src dst) = zs \\<longrightarrow> \n       length t = n \\<longrightarrow>\n       hanoi cfg \\<longrightarrow> \n       lt (last t) ys \\<longrightarrow> lt (last t) zs \\<longrightarrow>\n       src \\<noteq> dst \\<longrightarrow>\n  (\\<exists>cfg'. exec cfg (move n src dst) = Some cfg' \\<and> cfg' src = xs \\<and> cfg' dst = t @ ys \\<and> cfg' (other src dst) = zs)\"\napply (induct n) \n apply simp\napply clarsimp\napply (case_tac \"n=0\")\n apply (simp add: Let_def)\n apply (case_tac t)\n  apply simp\n apply simp\n apply (rule conjI)\n  apply (clarsimp simp add: step_def Let_def hanoi_def)\n  apply (erule_tac x = src in allE)\n  apply simp\n apply (clarsimp simp add: step_def Let_def)\napply clarsimp\napply (subgoal_tac \"\\<exists>t' ts'. t = ts' @ [t']\")\n prefer 2 \n apply (simp add: neq_Nil_snoC)\napply clarsimp\napply (frule spec, erule allE, erule_tac x = \"other src dst\" in allE, erule allE, erule allE, erule impE, assumption)\napply (erule impE, rule refl)\napply (erule impE, assumption)\napply simp\napply (subgoal_tac \"last ts' < t'\")\n apply (erule impE)\n  apply (erule lt_mono, assumption)\n apply (erule impE)\n  apply (erule lt_mono, assumption)\n apply (erule impE)\n  apply rule\n  apply (erule otherF)\n prefer 2\n apply simp \napply clarsimp\napply (clarsimp simp add: Let_def)\napply (rule conjI)\n apply (clarsimp simp add: step_def Let_def hanoi_def)\n apply (rule conjI)\n  apply (erule_tac x=src in allE)\n  apply clarsimp\n apply clarsimp\n apply (drule neq_other, assumption, assumption)\n apply simp\n apply (frule_tac x=\"other src dst\" in spec)\n apply (drule_tac x=\"src\" in spec)\n apply clarsimp\n apply (rule ordered_appendI, assumption+)\napply (clarsimp simp add: step_def Let_def)\napply (erule_tac x=\"cfg'(src := xs, dst := t' # cfg dst)\" in allE)\napply (erule_tac x=\"other src dst\" in allE)\napply (erule_tac x=\"dst\" in allE)\napply (erule allE)+ \napply (erule impE)\n apply simp\napply (erule impE, rule refl)\napply (erule impE)\n apply simp\napply (erule impE)\n apply simp \n apply (rule lt_mono)\n apply (subgoal_tac \"last ts' < t'\")\n  prefer 2 \n  apply simp\n apply assumption+\napply (erule impE)\n apply (subgoal_tac \"last ts' < t'\")\n  prefer 2 \n  apply simp\n apply (unfold hanoi_def)\n apply (erule_tac x = src in allE)\n apply (erule lt_mono)\n apply simp\napply clarsimp\ndone\n\nlemma [simp]: \"length (tower n) = n\"\n  by (induct n, auto)\n\nlemma \"lt 0 (tower n)\"\n  by (induct n, auto)\n\nlemma gt_mono [rule_format, simp]: \"x < y \\<longrightarrow> gt x xs \\<longrightarrow> gt y xs\"\n  apply (induct xs)\n  apply auto\ndone\n\nlemma [simp]: \"gt (Suc n) (tower n)\"\n  apply (induct n)\n  apply auto\n  apply (rule gt_mono)\n  defer\n  apply assumption\n  apply simp\ndone\n\nlemma [simp]: \"ordered (tower n)\"\n  apply (induct n)\n  apply auto\ndone\n\nlemma hanoi_start:\n  \"\\<lbrakk> cfg A = tower n; cfg B = []; cfg C = [] \\<rbrakk> \\<Longrightarrow>\n  hanoi cfg\"\n  apply (unfold hanoi_def)\n  apply (rule allI)\n  apply (case_tac s)\n  apply auto\ndone\n\ntheorem hanoi:\n  \"\\<lbrakk>cfg A = tower n; \n    cfg B = []; \n    cfg C = []\\<rbrakk> \\<Longrightarrow> \n  \\<exists>cfg'. exec cfg (move n A C) = Some cfg' \\<and> \n    cfg' A = [] \\<and>\n    cfg' B = [] \\<and>\n    cfg' C = tower n\"\n  apply (frule hanoi_start, assumption+)\n  apply (insert hanoi_lemma [of n])\n  apply (erule_tac x=cfg in allE)\n  apply (erule_tac x=A in allE)\n  apply (erule_tac x=C in allE)\n  apply (erule_tac x=\"tower n\" in allE)\n  apply (erule allE)+\n  apply (erule impE)\n   apply simp\n  apply (erule impE, assumption)+\n  apply (erule impE, simp)\n  apply clarsimp\ndone\n\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/proj/hanoi/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8688267660487572, "lm_q1q2_score": 0.759421697505131}}
{"text": "\ntheory Lists1_4\nimports Main\nbegin\n\nprimrec first_pos :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat\"\nwhere\n  \"first_pos P [] = 0\"\n| \"first_pos P (x#xs) = (if (P x) then 0 else (Suc (first_pos P xs)))\"\n\nlemma \"first_pos (\\<lambda>x. x=3) [1::nat,3,5,3,1] = 1\"\n  by auto\n\nlemma \"first_pos (\\<lambda>x. x > 4) [1::nat, 3, 5, 7] = 2\"\n  by auto\n\nlemma \"first_pos (\\<lambda>x. (length x) > 1) [[], [1, 2], [3]] = 1\"\n  by auto\n\n(* different from text *)\nlemma \"list_all (\\<lambda>x. \\<not>P x) xs \\<longrightarrow> first_pos P xs = length xs\"\n  apply (induct xs)\n  apply simp+\ndone\n\nvalue \"take 3 [1::int,1,2,3]\"\n\nlemma \"list_all (\\<lambda>x. \\<not>P x) (take (first_pos P xs) xs)\"\n  apply (induct xs)\n  apply simp+\ndone\n\nlemma \"first_pos (\\<lambda>x. P x \\<or> Q x) xs = (min (first_pos P xs) (first_pos Q xs))\"\n  apply (induct xs)\n  apply simp+\ndone\n\nlemma \"first_pos (\\<lambda>x. P x \\<and> Q x) xs \\<ge> (max (first_pos P xs) (first_pos Q xs))\"\n  apply (induct xs)\n  apply simp+\ndone\n\n(* different from text *)\nlemma \"(list_all P xs) \\<longrightarrow> (list_all Q xs) \\<longrightarrow> (first_pos P xs \\<ge> first_pos Q xs)\"\n  apply (induct xs)\n  apply simp+\ndone\n\nprimrec count :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> nat\"\nwhere\n  \"count P [] = 0\"\n| \"count P (x#xs) = (if (P x) then Suc (count P xs) else count P xs)\"\n\nvalue \"count (\\<lambda>x. x>2) [3::nat]\"\nvalue \"count (\\<lambda>x. x>2) [1::nat,2,3,4,5]\"\n\nlemma count_append: \"count P (xs@ys) = count P xs + count P ys\"\n  apply (induct xs)\n  apply simp+\ndone\n\nlemma \"count P xs = count P (rev xs)\"\n  apply (induct xs)\n  apply (simp add:count_append)+\ndone\n\nvalue \"filter (\\<lambda>x. x>2) [1,2,3,4,5::int]\"\n\nlemma \"length (filter P xs) = count P xs\"\n  apply (induct xs)\n  apply simp+\ndone\n\nend\n\n", "meta": {"author": "jineshkj", "repo": "cis700_assured_systems", "sha": "9fb270e519a3644f9713bee8cef082aefbc8228f", "save_path": "github-repos/isabelle/jineshkj-cis700_assured_systems", "path": "github-repos/isabelle/jineshkj-cis700_assured_systems/cis700_assured_systems-9fb270e519a3644f9713bee8cef082aefbc8228f/Isabelle_HOL_Exercies/Lists1_4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096204605947, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.7593988151406743}}
{"text": "(* Author: Tobias Nipkow *)\n\nheader \"Extended Regular Expressions\"\n\ntheory Regular_Exp2\nimports Regular_Set\nbegin\n\ndatatype (atoms: 'a) rexp =\n  is_Zero: Zero |\n  is_One: One |\n  Atom 'a |\n  Plus \"('a rexp)\" \"('a rexp)\" |\n  Times \"('a rexp)\" \"('a rexp)\" |\n  Star \"('a rexp)\" |\n  Not \"('a rexp)\" |\n  Inter \"('a rexp)\" \"('a rexp)\"\n\ncontext\nfixes S :: \"'a set\"\nbegin\n\nprimrec lang :: \"'a rexp => 'a lang\" where\n\"lang Zero = {}\" |\n\"lang One = {[]}\" |\n\"lang (Atom a) = {[a]}\" |\n\"lang (Plus r s) = (lang r) Un (lang s)\" |\n\"lang (Times r s) = conc (lang r) (lang s)\" |\n\"lang (Star r) = star(lang r)\" |\n\"lang (Not r) = lists S - lang r\" |\n\"lang (Inter r s) = (lang r Int lang s)\"\n\nend\n\nlemma lang_subset_lists: \"atoms r \\<subseteq> S \\<Longrightarrow> lang S r \\<subseteq> lists S\"\nby(induction r)(auto simp: conc_subset_lists star_subset_lists)\n\nprimrec nullable :: \"'a rexp \\<Rightarrow> bool\" where\n\"nullable Zero = False\" |\n\"nullable One = True\" |\n\"nullable (Atom c) = False\" |\n\"nullable (Plus r1 r2) = (nullable r1 \\<or> nullable r2)\" |\n\"nullable (Times r1 r2) = (nullable r1 \\<and> nullable r2)\" |\n\"nullable (Star r) = True\" |\n\"nullable (Not r) = (\\<not> (nullable r))\" |\n\"nullable (Inter r s) = (nullable r \\<and> nullable s)\"\n\nlemma nullable_iff: \"nullable r \\<longleftrightarrow> [] \\<in> lang S r\"\nby (induct r) (auto simp add: conc_def split: if_splits)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Regular-Sets/Regular_Exp2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.8311430415844384, "lm_q1q2_score": 0.759395880787078}}
{"text": "section \\<open>Algorithms to compute all complex and real roots of a cubic polynomial\\<close>\n\ntheory Cubic_Polynomials\n  imports \n    Cardanos_Formula\n    Complex_Roots\nbegin\n\ntext \\<open>The real case where a result is only delivered if the discriminant is negative\\<close>\n\ndefinition solve_depressed_cubic_Cardano_real :: \"real \\<Rightarrow> real \\<Rightarrow> real option\" where\n  \"solve_depressed_cubic_Cardano_real e f = (\n    if e = 0 then Some (root 3 (-f)) else\n     let v = - (e ^ 3 / 27) in\n     case rroots2 [:v,f,1:] of \n       [u,_] \\<Rightarrow> let rt = root 3 u in Some (rt - e / (3 * rt))\n     | _ \\<Rightarrow> None)\" \n\nlemma solve_depressed_cubic_Cardano_real: \n  assumes \"solve_depressed_cubic_Cardano_real e f = Some y\" \n  shows \"{y. y^3 + e * y + f = 0} = {y}\"\nproof (cases \"e = 0\")\n  case True\n  have \"{y. y^3 + e * y + f = 0} = {y. y^3 = -f}\" unfolding True \n    by (auto simp add: field_simps)\n  also have \"\\<dots> = {root 3 (-f)}\" \n    using odd_real_root_unique[of 3 _ \"-f\"] odd_real_root_pow[of 3] by auto\n  also have \"root 3 (-f) = y\" using assms unfolding True solve_depressed_cubic_Cardano_real_def\n    by auto\n  finally show ?thesis .\nnext\n  case False\n  define v where \"v = - (e ^ 3 / 27)\" \n  note * = assms[unfolded solve_depressed_cubic_Cardano_real_def Let_def, folded v_def]\n  let ?rr = \"rroots2 [:v,f,1:]\" \n  from * False obtain u u' where rr: \"?rr = [u,u']\" \n    by (cases ?rr; cases \"tl ?rr\"; cases \"tl (tl ?rr)\"; auto split: if_splits)\n  from *[unfolded rr list.simps] False \n  have y: \"y = root 3 u - e / (3 * root 3 u)\" by auto\n  have \"u \\<in> set (rroots2 [:v,f,1:])\" unfolding rr by auto\n  also have \"set (rroots2 [:v,f,1:]) = {u. poly [:v,f,1:] u = 0}\" \n    by (subst rroots2, auto)\n  finally have u: \"u^2 + f * u + v = 0\" by (simp add: field_simps power2_eq_square)\n  note Cardano = solve_cubic_depressed_Cardano_real[OF False v_def u]\n  have 2: \"2 = Suc (Suc 0)\" by simp\n  from rr have 0: \"f\\<^sup>2 - 4 * v \\<noteq> 0\" unfolding rroots2_def Let_def\n    by (auto split: if_splits simp: 2)\n  hence 0: \"discriminant_cubic_depressed e f \\<noteq> 0\" \n    unfolding discriminant_cubic_depressed_def v_def by auto\n  show ?thesis using Cardano(1) Cardano(2)[OF 0] unfolding y[symmetric] by blast\nqed\n\ntext \\<open>The complex case\\<close>\n\ndefinition solve_depressed_cubic_complex :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex list\" where\n  \"solve_depressed_cubic_complex e f = (let\n          ys = (if e = 0 then all_croots 3 (- f) else (let\n       u = hd (croots2 [: - (e ^ 3 / 27) ,f,1:]); \n       zs = all_croots 3 u \n       in map (\\<lambda> z. z - e / (3 * z)) zs))\n      in remdups ys)\" \n\nlemma solve_depressed_cubic_complex_code[code]: \n  \"solve_depressed_cubic_complex e f = (let\n          ys = (if e = 0 then all_croots 3 (- f) else (let\n            f2 = f / 2;\n            u = - f2 + csqrt (f2^2 + e ^ 3 / 27);\n            zs = all_croots 3 u \n            in map (\\<lambda> z. z - e / (3 * z)) zs))\n      in remdups ys)\" \n  unfolding solve_depressed_cubic_complex_def Let_def croots2_def \n  by (simp add: numeral_2_eq_2)\n\n\nlemma solve_depressed_cubic_complex: \"y \\<in> set (solve_depressed_cubic_complex e f) \n  \\<longleftrightarrow> (y^3 + e * y + f = 0)\"\nproof (cases \"e = 0\")\n  case True\n  thus ?thesis by (simp add: solve_depressed_cubic_complex_def Let_def all_croots eq_neg_iff_add_eq_0)\nnext\n  case e0: False\n  hence id: \"(if e = 0 then x else y) = y\" for x y :: \"complex list\" by simp\n  define v where \"v = - (e ^ 3 / 27)\" \n  define p where \"p = [:v, f, 1:]\" \n  have p2: \"degree p = 2\" unfolding p_def by auto\n  let ?u = \"hd (croots2 p)\" \n  define u where \"u = ?u\" \n  have \"u \\<in> set (croots2 p)\" unfolding croots2_def Let_def u_def by auto\n  with croots2[OF p2] have \"poly p u = 0\" by auto\n  hence u: \"u^2 + f * u + v = 0\" unfolding p_def\n    by (simp add: field_simps power2_eq_square)\n  note cube_roots = all_croots[of 3, simplified]\n  show ?thesis unfolding solve_depressed_cubic_complex_def Let_def set_remdups set_map id cube_roots\n    unfolding v_def[symmetric] p_def[symmetric] set_concat set_map\n      u_def[symmetric]\n  proof - \n    have p: \"{x. poly p x = 0} = {u. u^2 + f * u + v = 0}\" unfolding p_def by (auto simp: field_simps power2_eq_square)\n    have cube: \"\\<Union> (set ` all_croots 3 ` {x. poly p x = 0}) = {z. \\<exists> u. u\\<^sup>2 + f * u + v = 0 \\<and> z ^ 3 = u}\" \n      unfolding p by (auto simp: cube_roots)\n    show \"(y \\<in> (\\<lambda>z. z - e / (3 * z)) ` {y. y ^ 3 = u}) = (y ^ 3 + e * y + f = 0)\"\n      using solve_cubic_depressed_Cardano_complex[OF e0 v_def u] cube by blast\n  qed\nqed\n\ntext \\<open>For the general real case, we first try Cardano with negative discrimiant and only if it is not applicable,\n   then we go for the calculation using complex numbers. Note that for for non-negative delta \n   no filter is required to identify the real roots from the list of complex roots, since in that case we \n   already know that all roots are real.\\<close>\ndefinition solve_depressed_cubic_real :: \"real \\<Rightarrow> real \\<Rightarrow> real list\" where\n  \"solve_depressed_cubic_real e f = (case solve_depressed_cubic_Cardano_real e f \n      of Some y \\<Rightarrow> [y] \n       | None \\<Rightarrow> map Re (solve_depressed_cubic_complex (of_real e) (of_real f)))\"\n\nlemma solve_depressed_cubic_real_code[code]: \"solve_depressed_cubic_real e f =\n  (if e = 0 then [root 3 (-f)] else \n   let v = e ^ 3 / 27; \n       f2 = f / 2;\n       f2v = f2^2 + v in\n   if f2v > 0 then \n     let u = -f2 + sqrt f2v;\n         rt = root 3 u\n      in [rt - e / (3 * rt)]\n  else \n  let ce3 = of_real e / 3; \n      u = - of_real f2 + csqrt (of_real f2v) in\n   map Re (remdups (map (\\<lambda>rt. rt - ce3 / rt) (all_croots 3 u))))\" \nproof -\n  have id: \"rroots2 [:v, f, 1:] = (let \n     f2 = f / 2;\n     bac = f2\\<^sup>2 - v in \n     if bac = 0 then [- f2] else \n     if bac < 0 then [] else let e = sqrt bac in [- f2 + e, - f2 - e])\" for v\n    unfolding rroots2_def Let_def numeral_2_eq_2 by auto\n  define foo :: \"real \\<Rightarrow> real \\<Rightarrow> real option\" where \n    \"foo f2v f2 = (case (if f2v = 0 then [- f2] else []) of [] \\<Rightarrow> None | _ \\<Rightarrow> None)\" \n    for f2v f2\n  have \"solve_depressed_cubic_real e f = (if e = 0 then [root 3 (-f)] else \n   let v = e ^ 3 / 27; \n       f2 = f / 2;\n       f2v = f2\\<^sup>2 + v in\n   if f2v > 0 then \n     let u = -f2 + sqrt f2v;\n         rt = root 3 u\n      in [rt - e / (3 * rt)]\n  else \n  (case foo f2v f2 of\n     None \\<Rightarrow> let u = - cor f2 + csqrt (cor f2v) in\n   map Re\n    (remdups (map (\\<lambda>z. z - cor e / (3 * z)) (all_croots 3 u)))\n   | Some y \\<Rightarrow> []))\" \n    unfolding solve_depressed_cubic_real_def solve_depressed_cubic_Cardano_real_def \n      solve_depressed_cubic_complex_code\n      Let_def id foo_def\n    by (auto split: if_splits)\n  also have id: \"foo f2v f2 = None\" \n    for f2v f2 unfolding foo_def by auto\n  ultimately show ?thesis by (auto simp: Let_def)\nqed\n\nlemma solve_depressed_cubic_real: \"y \\<in> set (solve_depressed_cubic_real e f) \n  \\<longleftrightarrow> (y^3 + e * y + f = 0)\" \nproof (cases \"solve_depressed_cubic_Cardano_real e f\")\n  case (Some x)\n  show ?thesis unfolding solve_depressed_cubic_real_def Some option.simps\n    using solve_depressed_cubic_Cardano_real[OF Some] by auto\nnext\n  case None\n  from this[unfolded solve_depressed_cubic_Cardano_real_def Let_def rroots2_def]\n  have disc: \"0 \\<le> discriminant_cubic_depressed e f\" unfolding discriminant_cubic_depressed_def\n    by (auto split: if_splits simp: numeral_2_eq_2)\n  let ?c = \"complex_of_real\" \n  let ?y = \"?c y\" \n  let ?e = \"?c e\" \n  let ?f = \"?c f\" \n  have sub: \"set (solve_depressed_cubic_complex ?e ?f) \\<subseteq> \\<real>\" \n  proof \n    fix y\n    assume y: \"y \\<in> set (solve_depressed_cubic_complex ?e ?f)\" \n    show \"y \\<in> \\<real>\" \n      by (rule solve_cubic_depressed_Cardano_all_real_roots[OF disc y[unfolded solve_depressed_cubic_complex]])\n  qed\n  have \"y^3 + e * y + f = 0 \\<longleftrightarrow> (?c (y^3 + e * y + f) = ?c 0)\" unfolding of_real_eq_iff by simp\n  also have \"\\<dots> \\<longleftrightarrow> ?y^3 + ?e * ?y + ?f = 0\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> ?y \\<in> set (solve_depressed_cubic_complex ?e ?f)\" \n    unfolding solve_depressed_cubic_complex ..\n  also have \"\\<dots> \\<longleftrightarrow> y \\<in> Re ` set (solve_depressed_cubic_complex ?e ?f)\" using sub by force\n  finally show ?thesis unfolding solve_depressed_cubic_real_def None by auto\nqed\n\ntext \\<open>Combining the various algorithms\\<close>\n\nlemma degree3_coeffs: \"degree p = 3 \\<Longrightarrow>\n  \\<exists> a b c d. p = [: d, c, b, a :] \\<and> a \\<noteq> 0\"\n  by (metis One_nat_def Suc_1 degree2_coeffs degree_pCons_eq_if nat.inject numeral_3_eq_3 pCons_cases zero_neq_numeral)\n\ndefinition roots3_generic :: \"('a :: field_char_0 \\<Rightarrow> 'a \\<Rightarrow> 'a list) \\<Rightarrow> 'a poly \\<Rightarrow> 'a list\" where\n  \"roots3_generic depressed_solver p = (let \n     cs = coeffs p; \n     a = cs ! 3; b = cs ! 2; c = cs ! 1; d = cs ! 0;\n     a3 = 3 * a;\n     ba3 = b / a3;\n     b2 = b * b;\n     b3 = b2 * b;\n     e = (c - b2 / a3) / a;\n     f = (d + 2 * b3 / (27 * a^2) - b * c / a3) / a;\n     roots = depressed_solver e f\n     in map (\\<lambda> y. y - ba3) roots)\" \n\nlemma roots3_generic: assumes deg: \"degree p = 3\" \n  and solver: \"\\<And> e f y. y \\<in> set (depressed_solver e f) \\<longleftrightarrow> y^3 + e * y + f = 0\" \n  shows \"set (roots3_generic depressed_solver p) = {x. poly p x = 0}\" \nproof -\n  note powers = field_simps power3_eq_cube power2_eq_square\n  from degree3_coeffs[OF deg] obtain a b c d where\n    p: \"p = [:d,c,b,a:]\" and a: \"a \\<noteq> 0\" by auto\n  have coeffs: \"coeffs p ! 3 = a\" \"coeffs p ! 2 = b\" \"coeffs p ! 1 = c\" \"coeffs p ! 0 = d\" \n    unfolding p using a by auto\n  define e where \"e = (c - b^2 / (3 * a)) / a\" \n  define f where \"f = (d + 2 * b^3 / (27 * a^2) - b * c / (3 * a)) / a\" \n  note def = roots3_generic_def[of depressed_solver p, unfolded Let_def coeffs,\n      folded power3_eq_cube, folded power2_eq_square,  folded e_def f_def]\n  {\n    fix x :: 'a\n    define y where \"y = x + b / (3 * a)\" \n    have xy: \"x = y - b / (3 * a)\" unfolding y_def by auto\n    have \"poly p x = 0 \\<longleftrightarrow> a * x^3 + b * x^2 + c * x + d = 0\" unfolding p\n      by (simp add: powers)\n    also have \"\\<dots> \\<longleftrightarrow> (y ^ 3 + e * y + f = 0)\" \n      unfolding to_depressed_cubic[OF a xy e_def f_def] ..\n    also have \"\\<dots> \\<longleftrightarrow> y \\<in> set (depressed_solver e f)\" \n      unfolding solver ..\n    also have \"\\<dots> \\<longleftrightarrow> x \\<in> set (roots3_generic depressed_solver p)\" unfolding xy def by auto\n    finally have \"poly p x = 0 \\<longleftrightarrow> x \\<in> set (roots3_generic depressed_solver p)\" by auto\n  }\n  thus ?thesis by auto\nqed\n\ndefinition croots3 :: \"complex poly \\<Rightarrow> complex list\" where\n  \"croots3 = roots3_generic solve_depressed_cubic_complex\"\n\nlemma croots3: assumes deg: \"degree p = 3\" \n  shows \"set (croots3 p) = { x. poly p x = 0}\" \n  unfolding croots3_def by (rule roots3_generic[OF deg solve_depressed_cubic_complex])\n\ndefinition rroots3 :: \"real poly \\<Rightarrow> real list\" where\n  \"rroots3 = roots3_generic solve_depressed_cubic_real\"\n\nlemma rroots3: assumes deg: \"degree p = 3\" \n  shows \"set (rroots3 p) = { x. poly p x = 0}\" \n  unfolding rroots3_def by (rule roots3_generic[OF deg solve_depressed_cubic_real])\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Cubic_Quartic_Equations/Cubic_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319862, "lm_q2_score": 0.8670357735451834, "lm_q1q2_score": 0.7593386573861808}}
{"text": "(*\n  File:     Random_BSTs.thy\n  Author:   Manuel Eberl <manuel@pruvisto.org>\n\n  Expected shape of random Binary Search Trees\n*)\nsection \\<open>Expected shape of random Binary Search Trees\\<close>\ntheory Random_BSTs\n  imports\n    Complex_Main\n    \"HOL-Probability.Random_Permutations\"\n    \"HOL-Data_Structures.Tree_Set\"\n    Quick_Sort_Cost.Quick_Sort_Average_Case\nbegin\n\n(* TODO: Hide this in the proper place *)\nhide_const (open) Tree_Set.insert\n\nsubsection \\<open>Auxiliary lemmas\\<close>\n\n(* TODO: Move? *)\nlemma linorder_on_linorder_class [intro]:\n  \"linorder_on UNIV {(x, y). x \\<le> (y :: 'a :: linorder)}\"\n  by (auto simp: linorder_on_def refl_on_def antisym_def trans_def total_on_def)\n\nlemma Nil_in_permutations_of_set_iff [simp]: \"[] \\<in> permutations_of_set A \\<longleftrightarrow> A = {}\"\n  by (auto simp: permutations_of_set_def)\n\nlemma max_power_distrib_right:\n  fixes a :: \"'a :: linordered_semidom\"\n  shows \"a > 1 \\<Longrightarrow> max (a ^ b) (a ^ c) = a ^ max b c\"\n  by (auto simp: max_def)\n\nlemma set_tree_empty_iff [simp]: \"set_tree t = {} \\<longleftrightarrow> t = Leaf\"\n  by (cases t) auto\n\nlemma card_set_tree_bst: \"bst t \\<Longrightarrow> card (set_tree t) = size t\"\nproof (induction t)\n  case (Node l x r)\n  have \"set_tree \\<langle>l, x, r\\<rangle> = insert x (set_tree l \\<union> set_tree r)\" by simp\n  also from Node.prems have \"card \\<dots> = Suc (card (set_tree l \\<union> set_tree r))\"\n    by (intro card_insert_disjoint) auto\n  also from Node have \"card (set_tree l \\<union> set_tree r) = size l + size r\"\n    by (subst card_Un_disjoint) force+\n  finally show ?case by simp\nqed simp_all\n\nlemma pair_pmf_cong:\n  \"p = p' \\<Longrightarrow> q = q' \\<Longrightarrow> pair_pmf p q = pair_pmf p' q'\"\n  by simp\n\nlemma expectation_add_pair_pmf:\n  fixes f :: \"'a \\<Rightarrow> 'c::{banach, second_countable_topology}\"\n  assumes \"finite (set_pmf p)\" and \"finite (set_pmf q)\"\n  shows \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>(x,y). f x + g y) =\n           measure_pmf.expectation p f + measure_pmf.expectation q g\"\nproof -\n  have \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>(x,y). f x + g y) =\n          measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. f (fst z) + g (snd z))\"\n    by (simp add: case_prod_unfold)\n  also have \"\\<dots> = measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. f (fst z)) +\n                  measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. g (snd z))\"\n    by (intro Bochner_Integration.integral_add integrable_measure_pmf_finite) (auto intro: assms)\n  also have \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. f (fst z)) =\n               measure_pmf.expectation (map_pmf fst (pair_pmf p q)) f\" by simp\n  also have \"map_pmf fst (pair_pmf p q) = p\" by (rule map_fst_pair_pmf)\n  also have \"measure_pmf.expectation (pair_pmf p q) (\\<lambda>z. g (snd z)) =\n               measure_pmf.expectation (map_pmf snd (pair_pmf p q)) g\" by simp\n  also have \"map_pmf snd (pair_pmf p q) = q\" by (rule map_snd_pair_pmf)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Creating a BST from a list\\<close>\n\ntext \\<open>\n  The following recursive function creates a binary search tree from a given list of\n  elements by inserting them into an initially empty BST from left to right. We will prove\n  that this is the case later, but the recursive definition has the advantage of giving us\n  a useful induction rule, so we chose that definition and prove the alternative definitions later.\n\n  This recursion, which already almost looks like QuickSort, will be key in analysing the\n  shape distributions of random BSTs.\n\\<close>\nfun bst_of_list :: \"'a :: linorder list \\<Rightarrow> 'a tree\" where\n  \"bst_of_list [] = Leaf\"\n| \"bst_of_list (x # xs) =\n     Node (bst_of_list [y \\<leftarrow> xs. y < x]) x (bst_of_list [y \\<leftarrow> xs. y > x])\"\n\nlemma bst_of_list_eq_Leaf_iff [simp]: \"bst_of_list xs = Leaf \\<longleftrightarrow> xs = []\"\n  by (induction xs) auto\n\nlemma bst_of_list_snoc [simp]:\n  \"bst_of_list (xs @ [y]) = Tree_Set.insert y (bst_of_list xs)\"\n  by (induction xs rule: bst_of_list.induct) auto\n\nlemma bst_of_list_append:\n  \"bst_of_list (xs @ ys) = fold Tree_Set.insert ys (bst_of_list xs)\"\nproof (induction ys arbitrary: xs)\n  case (Cons y ys)\n  have \"bst_of_list (xs @ (y # ys)) = bst_of_list ((xs @ [y]) @ ys)\" by simp\n  also have \"\\<dots> = fold Tree_Set.insert ys (bst_of_list (xs @ [y]))\"\n    by (rule Cons.IH)\n  finally show ?case by simp\nqed simp_all\n\ntext \\<open>\n  The following now shows that the recursive function indeed corresponds to the\n  notion of inserting the elements from the list from left to right.\n\\<close>\nlemma bst_of_list_altdef: \"bst_of_list xs = fold Tree_Set.insert xs Leaf\"\n  using bst_of_list_append[of \"[]\" xs] by simp\n\nlemma size_bst_insert: \"x \\<notin> set_tree t \\<Longrightarrow> size (Tree_Set.insert x t) = Suc (size t)\"\n  by (induction t) auto\n\nlemma set_bst_insert [simp]: \"set_tree (Tree_Set.insert x t) = insert x (set_tree t)\"\n  by (induction t) auto\n\nlemma set_bst_of_list [simp]: \"set_tree (bst_of_list xs) = set xs\"\n  by (induction xs rule: rev_induct) simp_all\n\nlemma size_bst_of_list_distinct [simp]:\n  assumes \"distinct xs\"\n  shows   \"size (bst_of_list xs) = length xs\"\n  using assms by (induction xs rule: rev_induct) (auto simp: size_bst_insert)\n\nlemma strict_mono_on_imp_less_iff:\n  assumes \"strict_mono_on A f\" \"x \\<in> A\" \"y \\<in> A\"\n  shows   \"f x < (f y :: 'b :: linorder) \\<longleftrightarrow> x < (y :: 'a :: linorder)\"\n  using assms by (cases x y rule: linorder_cases; force simp: strict_mono_on_def)+\n\nlemma bst_of_list_map: \n  fixes f :: \"'a :: linorder \\<Rightarrow> 'b :: linorder\"\n  assumes \"strict_mono_on A f\" \"set xs \\<subseteq> A\"\n  shows   \"bst_of_list (map f xs) = map_tree f (bst_of_list xs)\"\n  using assms\nproof (induction xs rule: bst_of_list.induct)\n  case (2 x xs)\n  have \"[xa\\<leftarrow>xs . f xa < f x] = [xa\\<leftarrow>xs . xa < x]\" and \"[xa\\<leftarrow>xs . f xa > f x] = [xa\\<leftarrow>xs . xa > x]\"\n    using \"2.prems\" by (auto simp: strict_mono_on_imp_less_iff intro!: filter_cong)\n  with 2 show ?case by (auto simp: filter_map o_def)\nqed auto  \n\n\nsubsection \\<open>Random BSTs\\<close>\n\ntext \\<open>\n  Analogously to the previous section, we can now view the concept of a random BST\n  (i.\\,e.\\ a BST obtained by inserting a given set of elements in random order) in two\n  different ways.\n\n  We again start with the recursive variant:\n\\<close>\nfunction random_bst :: \"'a :: linorder set \\<Rightarrow> 'a tree pmf\" where\n  \"random_bst A =\n     (if \\<not>finite A \\<or> A = {} then\n        return_pmf Leaf\n      else do {\n        x \\<leftarrow> pmf_of_set A;\n        l \\<leftarrow> random_bst {y \\<in> A. y < x};\n        r \\<leftarrow> random_bst {y \\<in> A. y > x};\n        return_pmf (Node l x r)\n     })\"\n  by auto\ntermination by (relation finite_psubset) auto\n\ndeclare random_bst.simps [simp del]\n\nlemma random_bst_empty [simp]: \"random_bst {} = return_pmf Leaf\"\n  by (simp add: random_bst.simps)\n\nlemma set_pmf_random_permutation [simp]:\n  \"finite A \\<Longrightarrow> set_pmf (pmf_of_set (permutations_of_set A)) = {xs. distinct xs \\<and> set xs = A}\"\n  by (subst set_pmf_of_set) (auto dest: permutations_of_setD)\n\ntext \\<open>\n  The alternative characterisation is the more intuitive one where we simply pick a\n  random permutation of the set elements uniformly at random and insert them into an empty\n  tree from left to right:\n\\<close>\nlemma random_bst_altdef:\n  assumes \"finite A\"\n  shows   \"random_bst A = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\nusing assms\nproof (induction A rule: finite_psubset_induct)\n  case (psubset A)\n  define L R where \"L = (\\<lambda>x. {y\\<in>A. y < x})\" and \"R = (\\<lambda>x. {y\\<in>A. y > x})\"\n  {\n    fix x assume x: \"x \\<in> A\"\n    hence *: \"L x \\<subset> A\" \"R x \\<subset> A\" by (auto simp: L_def R_def)\n    note this [THEN psubset.IH]\n  } note IH = this\n\n  show ?case\n  proof (cases \"A = {}\")\n    case False\n    note A = \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    have \"random_bst A =\n            do {\n              x \\<leftarrow> pmf_of_set A;\n              (l, r) \\<leftarrow> pair_pmf (random_bst (L x)) (random_bst (R x));\n              return_pmf (Node l x r)\n            }\" using A unfolding pair_pmf_def L_def R_def\n      by (subst random_bst.simps) (simp add: bind_return_pmf bind_assoc_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (l, r) \\<leftarrow> pair_pmf\n                        (map_pmf bst_of_list (pmf_of_set (permutations_of_set (L x))))\n                        (map_pmf bst_of_list (pmf_of_set (permutations_of_set (R x))));\n                      return_pmf (Node l x r)\n                    }\"\n     using A by (intro bind_pmf_cong refl) (simp_all add: IH)\n    also have \"\\<dots> = do {\n                     x \\<leftarrow> pmf_of_set A;\n                     (ls, rs) \\<leftarrow> pair_pmf (pmf_of_set (permutations_of_set (L x)))\n                                          (pmf_of_set (permutations_of_set (R x)));\n                     return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n                   }\" unfolding map_pair [symmetric]\n      by (simp add: map_pmf_def case_prod_unfold bind_return_pmf bind_assoc_pmf)\n    also have \"L = (\\<lambda>x. {y \\<in> A - {x}. y \\<le> x})\" by (auto simp: L_def)\n    also have \"R = (\\<lambda>x. {y \\<in> A - {x}. \\<not>y \\<le> x})\" by (auto simp: R_def)\n    also have \"do {\n                 x \\<leftarrow> pmf_of_set A;\n                 (ls, rs) \\<leftarrow> pair_pmf (pmf_of_set (permutations_of_set {y \\<in> A - {x}. y \\<le> x}))\n                                      (pmf_of_set (permutations_of_set {y \\<in> A - {x}. \\<not>y \\<le> x}));\n                 return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n               } =\n               do {\n                 x \\<leftarrow> pmf_of_set A;\n                 (ls, rs) \\<leftarrow> map_pmf (partition (\\<lambda>y. y \\<le> x))\n                               (pmf_of_set (permutations_of_set (A - {x})));\n                 return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n               }\" using \\<open>finite A\\<close>\n      by (intro bind_pmf_cong refl partition_random_permutations [symmetric]) auto\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (ls, rs) \\<leftarrow> map_pmf (\\<lambda>xs. ([y\\<leftarrow>xs. y < x], [y\\<leftarrow>xs. y > x]))\n                                    (pmf_of_set (permutations_of_set (A - {x})));\n                      return_pmf (Node (bst_of_list ls) x (bst_of_list rs))\n                    }\" using A\n      by (intro bind_pmf_cong refl map_pmf_cong)\n         (auto intro!: filter_cong dest: permutations_of_setD simp: order.strict_iff_order)\n    also have \"\\<dots> = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\n      using A by (subst random_permutation_of_set[of A])\n                 (auto simp: map_pmf_def bind_return_pmf o_def bind_assoc_pmf not_le)\n    finally show ?thesis .\n  qed (simp_all add: pmf_of_set_singleton)\nqed\n\nlemma finite_set_random_bst [simp, intro]:\n  \"finite A \\<Longrightarrow> finite (set_pmf (random_bst A))\"\n  by (simp add: random_bst_altdef)\n\nlemma random_bst_code [code]:\n  \"random_bst (set xs) = map_pmf bst_of_list (pmf_of_set (permutations_of_set (set xs)))\"\n  by (rule random_bst_altdef) simp_all\n\nlemma random_bst_singleton [simp]: \"random_bst {x} = return_pmf (Node Leaf x Leaf)\"\n  by (simp add: random_bst_altdef pmf_of_set_singleton)\n\nlemma size_random_bst:\n  assumes \"t \\<in> set_pmf (random_bst A)\" \"finite A\"\n  shows   \"size t = card A\"\nproof -\n  from assms obtain xs where \"distinct xs\" \"A = set xs\" \"t = bst_of_list xs\"\n    by (auto simp: random_bst_altdef dest: permutations_of_setD)\n  thus ?thesis using \\<open>finite A\\<close> by (simp add: distinct_card)\nqed\n\nlemma random_bst_image:\n  assumes \"finite A\" \"strict_mono_on A f\"\n  shows   \"random_bst (f ` A) = map_pmf (map_tree f) (random_bst A)\"\nproof -\n  from assms(2) have inj: \"inj_on f A\" by (rule strict_mono_on_imp_inj_on)\n  with assms have \"inj_on (map f) (permutations_of_set A)\"\n    by (intro inj_on_mapI) auto\n  with assms inj have \"random_bst (f ` A) = \n                         map_pmf (\\<lambda>x. bst_of_list (map f x)) (pmf_of_set (permutations_of_set A))\"\n    by (simp add: random_bst_altdef permutations_of_set_image_inj map_pmf_of_set_inj [symmetric]\n                  pmf.map_comp o_def)\n  also have \"\\<dots> = map_pmf (map_tree f) (random_bst A)\"\n    unfolding random_bst_altdef[OF \\<open>finite A\\<close>] pmf.map_comp o_def using assms\n    by (intro map_pmf_cong refl bst_of_list_map[of A f]) (auto dest: permutations_of_setD)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>\n  We can also re-phrase the non-recursive definition using the @{const fold_random_permutation}\n  combinator from the HOL-Probability library, which folds over a given set in random order.\n\\<close>\nlemma random_bst_altdef':\n  assumes \"finite A\"\n  shows   \"random_bst A = fold_random_permutation Tree_Set.insert Leaf A\"\nproof -\n  have \"random_bst A = map_pmf bst_of_list (pmf_of_set (permutations_of_set A))\"\n    using assms by (simp add: random_bst_altdef)\n  also have \"\\<dots> = map_pmf (\\<lambda>xs. fold Tree_Set.insert xs Leaf) (pmf_of_set (permutations_of_set A))\"\n    using assms by (intro map_pmf_cong refl) (auto simp: bst_of_list_altdef)\n  also from assms have \"\\<dots> = fold_random_permutation Tree_Set.insert Leaf A\"\n    by (simp add: fold_random_permutation_fold)\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Expected height\\<close>\n\ntext \\<open>\n  For the purposes of the analysis of the expected height, we define the following notion\n  of `expected height', which is essentially two to the power of the height (as defined\n  by Cormen \\textit{et al.}) with a special treatment for the empty tree, which has exponential\n  height 0.\n\n  Note that the height defined by Cormen \\textit{et al.}\\ differs from the @{const height}\n  function here in Isabelle in that for them, the height of the empty tree is undefined and\n  the height of a singleton tree is 0 etc., whereas in Isabelle, the height of the empty tree is\n  0 and the height of a singleton tree is 1.\n\\<close>\ndefinition eheight :: \"'a tree \\<Rightarrow> nat\" where\n  \"eheight t = (if t = Leaf then 0 else 2 ^ (height t - 1))\"\n\nlemma eheight_Leaf [simp]: \"eheight Leaf = 0\"\n  by (simp add: eheight_def)\n\nlemma eheight_Node_singleton [simp]: \"eheight (Node Leaf x Leaf) = 1\"\n  by (simp add: eheight_def)\n\nlemma eheight_Node:\n  \"l \\<noteq> Leaf \\<or> r \\<noteq> Leaf \\<Longrightarrow> eheight (Node l x r) = 2 * max (eheight l) (eheight r)\"\n  by (cases l; cases r) (simp_all add: eheight_def max_power_distrib_right)\n\n\nfun eheight_rbst :: \"nat \\<Rightarrow> nat pmf\" where\n  \"eheight_rbst 0 = return_pmf 0\"\n| \"eheight_rbst (Suc 0) = return_pmf 1\"\n| \"eheight_rbst (Suc n) =\n     do {\n       k \\<leftarrow> pmf_of_set {..n};\n       h1 \\<leftarrow> eheight_rbst k;\n       h2 \\<leftarrow> eheight_rbst (n - k);\n       return_pmf (2 * max h1 h2)}\"\n\ndefinition eheight_exp :: \"nat \\<Rightarrow> real\" where\n  \"eheight_exp n = measure_pmf.expectation (eheight_rbst n) real\"\n\nlemma eheight_rbst_reduce:\n  assumes \"n > 1\"\n  shows   \"eheight_rbst n =\n             do {k \\<leftarrow> pmf_of_set {..<n}; h1 \\<leftarrow> eheight_rbst k; h2 \\<leftarrow> eheight_rbst (n - k - 1);\n                 return_pmf (2 * max h1 h2)}\"\n  using assms by (cases n rule: eheight_rbst.cases) (simp_all add: lessThan_Suc_atMost)\n\nlemma Leaf_in_set_random_bst_iff:\n  assumes \"finite A\"\n  shows   \"Leaf \\<in> set_pmf (random_bst A) \\<longleftrightarrow> A = {}\"\nproof\n  assume \"Leaf \\<in> set_pmf (random_bst A)\"\n  from size_random_bst[OF this] and assms show \"A = {}\" by auto\nqed auto  \n\n\n\n    hence \"map_pmf eheight (random_bst A) = \n             do {\n               x \\<leftarrow> pmf_of_set A;\n               l \\<leftarrow> random_bst {y \\<in> A. y < x};\n               r \\<leftarrow> random_bst {y \\<in> A. y > x};\n               return_pmf (eheight (Node l x r))\n             }\"\n      using \\<open>finite A\\<close> by (subst random_bst.simps) (auto simp: map_bind_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      l \\<leftarrow> random_bst {y \\<in> A. y < x};\n                      r \\<leftarrow> random_bst {y \\<in> A. y > x};\n                      return_pmf (2 * max (eheight l) (eheight r))\n                    }\"\n      using 3 \\<open>finite A\\<close> exists_other\n      by (intro bind_pmf_cong refl, subst eheight_Node)\n         (force simp: Leaf_in_set_random_bst_iff not_less nonempty eheight_Node)+\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      h1 \\<leftarrow> map_pmf eheight (random_bst {y \\<in> A. y < x});\n                      h2 \\<leftarrow> map_pmf eheight (random_bst {y \\<in> A. y > x});\n                      return_pmf (2 * max h1 h2)\n                    }\"\n      by (simp add: bind_map_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      h1 \\<leftarrow> eheight_rbst (card {y \\<in> A. y < x});\n                      h2 \\<leftarrow> eheight_rbst (card {y \\<in> A. y > x});\n                      return_pmf (2 * max h1 h2)\n                    }\"\n      using \\<open>A \\<noteq> {}\\<close> \\<open>finite A\\<close> by (intro bind_pmf_cong psubset.IH [symmetric] refl) auto\n    also have \"\\<dots> = do {\n                      k \\<leftarrow> map_pmf rank (pmf_of_set A);\n                      h1 \\<leftarrow> eheight_rbst k;\n                      h2 \\<leftarrow> eheight_rbst (card A - k - 1);\n                      return_pmf (2 * max h1 h2)\n                    }\"\n      unfolding bind_map_pmf\n    proof (intro bind_pmf_cong refl, goal_cases)\n      case (1 x)\n      have \"rank x = card {y\\<in>A-{x}. y \\<le> x}\" by (simp add: rank_def linorder_rank_def)\n      also have \"{y\\<in>A-{x}. y \\<le> x} = {y\\<in>A. y < x}\" by auto\n      finally show ?case by simp\n    next\n      case (2 x)\n      have \"A - {x} = {y\\<in>A-{x}. y \\<le> x} \\<union> {y\\<in>A. y > x}\" by auto\n      also have \"card \\<dots> = rank x + card {y\\<in>A. y > x}\"\n        using \\<open>finite A\\<close> by (subst card_Un_disjoint) (auto simp: rank_def linorder_rank_def)\n      finally have \"card {y\\<in>A. y > x} = card A - rank x - 1\"\n        using 2 \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close> by simp\n      thus ?case by simp\n    qed\n    also have \"map_pmf rank (pmf_of_set A) = pmf_of_set {..<card A}\"\n      using \\<open>A \\<noteq> {}\\<close> \\<open>finite A\\<close> unfolding rank_def\n      by (intro map_pmf_of_set_bij_betw bij_betw_linorder_rank[of UNIV]) auto\n    also have \"do {\n                 k \\<leftarrow> pmf_of_set {..<card A};\n                 h1 \\<leftarrow> eheight_rbst k;\n                 h2 \\<leftarrow> eheight_rbst (card A - k - 1);\n                 return_pmf (2 * max h1 h2)\n               } = eheight_rbst (card A)\"\n      by (rule eheight_rbst_reduce [symmetric]) fact+\n    finally show ?thesis ..\n  qed (auto simp: is_singleton_def)\nqed\n\nlemma finite_pmf_set_eheight_rbst [simp, intro]: \"finite (set_pmf (eheight_rbst n))\"\nproof -\n  have \"eheight_rbst n = map_pmf eheight (random_bst {..<n})\"\n    by (subst eheight_rbst [symmetric]) auto\n  also have \"finite (set_pmf \\<dots>)\" by simp\n  finally show ?thesis .\nqed\n\n\n\nlemma eheight_exp_1 [simp]: \"eheight_exp (Suc 0) = 1\"\n  by (simp add: eheight_exp_def lessThan_Suc)\n\nlemma eheight_exp_reduce_bound:\n  assumes \"n > 1\"\n  shows   \"eheight_exp n \\<le> 4 / n * (\\<Sum>k<n. eheight_exp k)\"\nproof -\n  have [simp]: \"real (max a b) = max (real a) (real b)\" for a b\n    by (simp add: max_def)\n  let ?f = \"\\<lambda>(h1,h2). max h1 h2\"\n  let ?p = \"\\<lambda>k. pair_pmf (eheight_rbst k) (eheight_rbst (n - Suc k))\"\n  have \"eheight_exp n = measure_pmf.expectation (eheight_rbst n) real\"\n    by (simp add: eheight_exp_def)\n  also have \"\\<dots> = 1 / real n * (\\<Sum>k<n. measure_pmf.expectation\n                                         (map_pmf (\\<lambda>(h1,h2). 2 * max h1 h2) (?p k)) real)\"\n    (is \"_ = _ * ?S\") unfolding pair_pmf_def map_bind_pmf\n    by (subst eheight_rbst_reduce [OF assms], subst pmf_expectation_bind_pmf_of_set)\n       (insert assms, auto simp: sum_divide_distrib divide_simps)\n  also have \"?S = (\\<Sum>k<n. measure_pmf.expectation (map_pmf (\\<lambda>x. 2 * x) (map_pmf ?f (?p k))) real)\"\n    by (simp only: pmf.map_comp o_def case_prod_unfold)\n  also have \"\\<dots> = 2 * (\\<Sum>k<n. measure_pmf.expectation (map_pmf ?f (?p k)) real)\" (is \"_ = _ * ?S'\")\n    by (subst integral_map_pmf) (simp add: sum_distrib_left)\n  also have \"?S' = (\\<Sum>k<n. measure_pmf.expectation (?p k) (\\<lambda>(h1,h2). max (real h1) (real h2)))\"\n    by (simp add: case_prod_unfold)\n  also have \"\\<dots> \\<le> (\\<Sum>k<n. measure_pmf.expectation (?p k) (\\<lambda>(h1,h2). real h1 + real h2))\"\n    unfolding integral_map_pmf case_prod_unfold\n    by (intro sum_mono Bochner_Integration.integral_mono integrable_measure_pmf_finite) auto\n  also have \"\\<dots> = (\\<Sum>k<n. eheight_exp k) + (\\<Sum>k<n. eheight_exp (n - Suc k))\"\n    by (subst expectation_add_pair_pmf) (auto simp: sum.distrib eheight_exp_def)\n  also have \"(\\<Sum>k<n. eheight_exp (n - Suc k)) = (\\<Sum>k<n. eheight_exp k)\"\n    by (intro sum.reindex_bij_witness[of _ \"\\<lambda>k. n - Suc k\" \"\\<lambda>k. n - Suc k\"]) auto\n  also have \"1 / real n * (2 * (\\<dots> + \\<dots>)) = 4 / real n * \\<dots>\" by simp\n  finally show ?thesis using assms by (simp_all add: mult_left_mono divide_right_mono)\nqed\n\n\ntext \\<open>\n  We now define the following upper bound on the expected exponential height due to\n  Cormen\\ \\textit{et\\ al.}~\\<^cite>\\<open>\"cormen\"\\<close>:\n\\<close>\nlemma eheight_exp_bound: \"eheight_exp n \\<le> real ((n + 3) choose 3) / 4\"\nproof (induction n rule: less_induct)\n  case (less n)\n  consider \"n = 0\" | \"n = 1\" | \"n > 1\" by force\n  thus ?case\n  proof cases\n    case 3\n    hence \"eheight_exp n \\<le> 4 / n * (\\<Sum>k<n. eheight_exp k)\"\n      by (rule eheight_exp_reduce_bound)\n    also have \"(\\<Sum>k<n. eheight_exp k) \\<le> (\\<Sum>k<n. real ((k + 3) choose 3) / 4)\"\n      by (intro sum_mono less.IH) auto\n    also have \"\\<dots> = real (\\<Sum>k<n. ((k + 3) choose 3)) / 4\"\n      by (simp add: sum_divide_distrib)\n    also have \"(\\<Sum>k<n. ((k + 3) choose 3)) = (\\<Sum>k\\<le>n - 1. ((k + 3) choose 3))\"\n      using \\<open>n > 1\\<close> by (intro sum.cong) auto\n    also have \"\\<dots> = ((n + 3) choose 4)\"\n      using choose_rising_sum(1)[of 3 \"n - 1\"] and \\<open>n > 1\\<close> by (simp add: add_ac Suc3_eq_add_3)\n    also have \"4 / real n * (\\<dots> / 4) = real ((n + 3) choose 3) / 4\" using \\<open>n > 1\\<close>\n      by (cases n) (simp_all add: binomial_fact fact_numeral divide_simps)\n    finally show ?thesis using \\<open>n > 1\\<close> by (simp add: mult_left_mono divide_right_mono)\n  qed (auto simp: eval_nat_numeral)\nqed\n\n\ntext \\<open>\n  We then show that this is indeed an upper bound on the expected exponential height by induction\n  over the set of elements. This proof mostly follows that by Cormen\\ \\textit{et al.}~\\<^cite>\\<open>\"cormen\"\\<close>,\n  and partially an answer on the Computer Science Stack Exchange~\\<^cite>\\<open>\"sofl\"\\<close>.\n\\<close>\n\ntext \\<open>\n  Since the function $\\uplambda x.\\ 2 ^ x$ is convex, we can then easily derive a bound on the\n  actual height using Jensen's inequality:\n\\<close>\ndefinition height_exp_approx :: \"nat \\<Rightarrow> real\" where\n  \"height_exp_approx n = log 2 (real ((n + 3) choose 3) / 4) + 1\"\n\ntheorem height_expectation_bound:\n  assumes \"finite A\" \"A \\<noteq> {}\"\n  shows   \"measure_pmf.expectation (random_bst A) height\n             \\<le> height_exp_approx (card A)\"\nproof -\n  have \"convex_on UNIV ((powr) 2)\"\n    by (intro convex_on_realI[where f' = \"\\<lambda>x. ln 2 * 2 powr x\"])\n       (auto intro!: derivative_eq_intros DERIV_powr simp: powr_def [abs_def])\n  hence \"2 powr measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t - 1)) \\<le>\n          measure_pmf.expectation (random_bst A) (\\<lambda>t. 2 powr real (height t - 1))\"\n    using assms\n    by (intro measure_pmf.jensens_inequality[where I = UNIV])\n       (auto intro!: integrable_measure_pmf_finite)\n  also have \"(\\<lambda>t. 2 powr real (height t - 1)) = (\\<lambda>t. 2 ^ (height t - 1))\"\n    by (simp add: powr_realpow)\n  also have \"measure_pmf.expectation (random_bst A) (\\<lambda>t. 2 ^ (height t - 1)) =\n               measure_pmf.expectation (random_bst A) (\\<lambda>t. real (eheight t))\"\n    using assms\n    by (intro integral_cong_AE)\n       (auto simp: AE_measure_pmf_iff random_bst_altdef eheight_def)\n  also have \"\\<dots> = measure_pmf.expectation (map_pmf eheight (random_bst A)) real\"\n    by simp\n  also have \"map_pmf eheight (random_bst A) = eheight_rbst (card A)\"\n    by (rule eheight_rbst [symmetric]) fact+\n  also have \"measure_pmf.expectation \\<dots> real = eheight_exp (card A)\"\n    by (simp add: eheight_exp_def)\n  also have \"\\<dots> \\<le> real ((card A + 3) choose 3) / 4\" by (rule eheight_exp_bound)\n  also have \"measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t - 1)) =\n               measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)\"\n  proof (intro integral_cong_AE AE_pmfI, goal_cases)\n    case (3 t)\n    with \\<open>A \\<noteq> {}\\<close> and assms show ?case\n      by (subst of_nat_diff) (auto simp: Suc_le_eq random_bst_altdef)\n  qed auto\n  finally have \"2 powr measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)\n                  \\<le> real ((card A + 3) choose 3) / 4\" .\n  hence \"log 2 (2 powr measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)) \\<le>\n           log 2 (real ((card A + 3) choose 3) / 4)\" (is \"?lhs \\<le> ?rhs\")\n    by (subst log_le_cancel_iff) auto\n  also have \"?lhs = measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t) - 1)\"\n    by simp\n  also have \"\\<dots> = measure_pmf.expectation (random_bst A) (\\<lambda>t. real (height t)) - 1\"\n    using assms\n    by (subst Bochner_Integration.integral_diff) (auto intro!: integrable_measure_pmf_finite)\n  finally show ?thesis by (simp add: height_exp_approx_def)\nqed\n\ntext \\<open>\n  This upper bound is asymptotically equivalent to $c \\ln n$ with\n  $c = \\frac{3}{\\ln 2} \\approx 4.328$. This is actually a relatively tight upper bound, since\n  the exact asymptotics of the expected height of a random BST is $c \\ln n$ with\n  $c \\approx 4.311$.~\\<^cite>\\<open>\"reed\"\\<close> However, the proof of these precise asymptotics is very intricate\n  and we will therefore be content with the upper bound.\n\n  In particular, we can now show that the expected height is $O(\\log n)$.\n\\<close>\nlemma ln_sum_bigo_ln: \"(\\<lambda>x::real. ln (x + c)) \\<in> O(ln)\"\nproof (rule bigoI_tendsto)\n  from eventually_gt_at_top[of \"1::real\"] show \"eventually (\\<lambda>x::real. ln x \\<noteq> 0) at_top\"\n    by eventually_elim simp_all\nnext\n  show \"((\\<lambda>x. ln (x + c) / ln x) \\<longlongrightarrow> 1) at_top\"\n  proof (rule lhospital_at_top_at_top)\n    show \"eventually (\\<lambda>x. ((\\<lambda>x. ln (x + c)) has_real_derivative inverse (x + c)) (at x)) at_top\"\n      using eventually_gt_at_top[of \"-c\"]\n      by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\n    show \"eventually (\\<lambda>x. ((\\<lambda>x. ln x) has_real_derivative inverse x) (at x)) at_top\"\n      using eventually_gt_at_top[of 0]\n      by eventually_elim (auto intro!: derivative_eq_intros simp: field_simps)\n    show \"((\\<lambda>x. inverse (x + c) / inverse x) \\<longlongrightarrow> 1) at_top\"\n    proof (rule Lim_transform_eventually)\n      show \"eventually (\\<lambda>x. inverse (1 + c / x) = inverse (x + c) / inverse x) at_top\"\n        using eventually_gt_at_top[of \"0::real\"] eventually_gt_at_top[of \"-c\"]\n        by eventually_elim (simp add: field_simps)\n      have \"((\\<lambda>x. inverse (1 + c / x)) \\<longlongrightarrow> inverse (1 + 0)) at_top\"\n        by (intro tendsto_inverse tendsto_add tendsto_const\n              real_tendsto_divide_at_top[OF tendsto_const] filterlim_ident) simp_all\n      thus \"((\\<lambda>x. inverse (1 + c / x)) \\<longlongrightarrow> 1) at_top\" by simp\n    qed\n  qed (auto simp: ln_at_top eventually_at_top_not_equal)\nqed\n\ncorollary height_expectation_bigo: \"height_exp_approx \\<in> O(ln)\"\nproof -\n  let ?T = \"\\<lambda>x::real. log 2 (x + 1) + log 2 (x + 2) + log 2 (x + 3) + (1 - log 2 24)\"\n  have \"eventually (\\<lambda>n. height_exp_approx n =\n          log 2 (real n + 1) + log 2 (real n + 2) + log 2 (real n + 3) + (1 - log 2 24)) at_top\"\n    (is \"eventually (\\<lambda>n. _ = ?T n) at_top\") using eventually_gt_at_top[of \"0::nat\"]\n  proof eventually_elim\n    case (elim n)\n    have \"height_exp_approx n = log 2 (real (n + 3 choose 3) / 4) + 1\"\n      by (simp add: height_exp_approx_def log_divide)\n    also have \"real ((n + 3) choose 3) = real (n + 3) gchoose 3\"\n      by (simp add: binomial_gbinomial)\n    also have \"\\<dots> / 4 = (real n + 1) * (real n + 2) * (real n + 3) / 24\"\n      by (simp add: gbinomial_pochhammer' numeral_3_eq_3 pochhammer_Suc add_ac)\n    also have \"log 2 \\<dots> = log 2 (real n + 1) + log 2 (real n + 2) + log 2 (real n + 3) - log 2 24\"\n      by (simp add: log_divide log_mult)\n    finally show ?case by simp\n  qed\n  hence \"height_exp_approx \\<in> \\<Theta>(?T)\" by (rule bigthetaI_cong)\n  also have *: \"(\\<lambda>x. ln (x + c) / ln 2) \\<in> O(ln)\" for c :: real\n    by (subst landau_o.big.cdiv_in_iff') (auto intro!: ln_sum_bigo_ln)\n  have \"?T \\<in> O(\\<lambda>n. ln (real n))\" unfolding log_def\n    by (intro bigo_real_nat_transfer sum_in_bigo ln_sum_bigo_ln *) simp_all\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Lookup costs\\<close>\n\ntext \\<open>\n  The following function describes the cost incurred when looking up a specific element\n  in a specific BST. The cost corresponds to the number of edges traversed in the lookup.\n\\<close>\n\nprimrec lookup_cost :: \"'a :: linorder \\<Rightarrow> 'a tree \\<Rightarrow> nat\" where\n  \"lookup_cost x Leaf = 0\"\n| \"lookup_cost x (Node l y r) =\n     (if x = y then 0\n      else if x < y then Suc (lookup_cost x l)\n      else Suc (lookup_cost x r))\"\n\ntext \\<open>\n  Some of the literature defines these costs as 1 in the case that the current node is\n  the correct one, i.\\,e.\\ their costs are our costs plus 1. These alternative costs are\n  exactly the number of comparisons performed in the lookup. Our cost function has the\n  advantage of precisely summing up to the internal path length and therefore gives us\n  slightly nicer results, and since the difference is only a ${}+1$ in the end, this\n  variant seemed more reasonable.\n\\<close>\n\ntext \\<open>\n  It can be shown with a simple induction that The sum of all lookup costs in a tree is the\n  internal path length of the tree.\n\\<close>\ntheorem sum_lookup_costs:\n  fixes t :: \"'a :: linorder tree\"\n  assumes \"bst t\"\n  shows   \"(\\<Sum>x\\<in>set_tree t. lookup_cost x t) = ipl t\"\nusing assms\nproof (induction t)\n  case (Node l x r)\n  from Node.prems\n    have disj: \"x \\<notin> set_tree l\" \"x \\<notin> set_tree r\" \"set_tree l \\<inter> set_tree r = {}\" by force+\n  have \"set_tree (Node l x r) = insert x (set_tree l \\<union> set_tree r)\" by simp\n  also have \"(\\<Sum>y\\<in>\\<dots>. lookup_cost y (Node l x r)) = lookup_cost x \\<langle>l, x, r\\<rangle> +\n               (\\<Sum>y\\<in>set_tree l. lookup_cost y \\<langle>l, x, r\\<rangle>) + (\\<Sum>y\\<in>set_tree r. lookup_cost y \\<langle>l, x, r\\<rangle>)\"\n    using disj by (simp add: sum.union_disjoint)\n  also have \"(\\<Sum>y\\<in>set_tree l. lookup_cost y \\<langle>l, x, r\\<rangle>) = (\\<Sum>y\\<in>set_tree l. 1 + lookup_cost y l)\"\n    using disj and Node by (intro sum.cong refl) auto\n  also have \"\\<dots> = size l + ipl l\" using Node\n    by (subst sum.distrib) (simp_all add: card_set_tree_bst)\n  also have \"(\\<Sum>y\\<in>set_tree r. lookup_cost y \\<langle>l, x, r\\<rangle>) = (\\<Sum>y\\<in>set_tree r. 1 + lookup_cost y r)\"\n    using disj and Node by (intro sum.cong refl) auto\n  also have \"\\<dots> = size r + ipl r\" using Node\n    by (subst sum.distrib) (simp_all add: card_set_tree_bst)\n  finally show ?case by simp\nqed simp_all\n\ntext \\<open>\n  This allows us to easily show that the expected cost of looking up a random element in a\n  fixed tree is the internal path length divided by the number of elements.\n\\<close>\ntheorem expected_lookup_cost:\n  assumes \"bst t\" \"t \\<noteq> Leaf\"\n  shows   \"measure_pmf.expectation (pmf_of_set (set_tree t)) (\\<lambda>x. lookup_cost x t) =\n             ipl t / size t\"\n  using assms by (subst integral_pmf_of_set)\n                 (simp_all add: sum_lookup_costs of_nat_sum [symmetric] card_set_tree_bst)\n\ntext \\<open>\n  Therefore, we will now turn to analysing the internal path length of a random BST. This\n  then clearly related to the expected lookup costs of a random element in a random BST by\n  the above result.\n\\<close>\n\n\nsubsection \\<open>Average Path Length\\<close>\n\ntext \\<open>\n  The internal path length satisfies the recursive equation @{thm ipl.simps(2)[of l x r]}.\n  This is quite similar to the number of comparisons performed by QuickSort, and indeed, we can\n  reduce the internal path length of a random BST to the number of comparisons performed by\n  QuickSort on a randomly-ordered list relatively easily:\n\\<close>\ntheorem map_pmf_random_bst_eq_rqs_cost:\n  assumes \"finite A\"\n  shows   \"map_pmf ipl (random_bst A) = rqs_cost (card A)\"\nusing assms\nproof (induction A rule: finite_psubset_induct)\n  case (psubset A)\n  show ?case\n  proof (cases \"A = {}\")\n    case False\n    note A = \\<open>finite A\\<close> \\<open>A \\<noteq> {}\\<close>\n    define n where \"n = card A - 1\"\n    define rank :: \"'a \\<Rightarrow> nat\" where \"rank = linorder_rank {(x,y). x \\<le> y} A\"\n    from A have card: \"card A = Suc n\" by (cases \"card A\") (auto simp: n_def)\n    from A have \"map_pmf ipl (random_bst A) =\n                   do {\n                     x \\<leftarrow> pmf_of_set A;\n                     (l,r) \\<leftarrow> pair_pmf (random_bst {y \\<in> A. y < x}) (random_bst {y \\<in> A. y > x});\n                     return_pmf (ipl (Node l x r))\n                   }\"\n      by (subst random_bst.simps)\n         (simp_all add: pair_pmf_def card map_pmf_def bind_assoc_pmf bind_return_pmf)\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (l,r) \\<leftarrow> pair_pmf (random_bst {y \\<in> A. y < x}) (random_bst {y \\<in> A. y > x});\n                      return_pmf (n + ipl l + ipl r)\n                    }\"\n    proof (intro bind_pmf_cong refl, clarify, goal_cases)\n      case (1 x l r)\n      from 1 and A have \"n = card (A - {x})\" by (simp add: n_def)\n      also have \"A - {x} = {y\\<in>A. y < x} \\<union> {y\\<in>A. y > x}\" by auto\n      also have \"card \\<dots> = card {y\\<in>A. y < x} + card {y\\<in>A. y > x}\"\n        using \\<open>finite A\\<close> by (intro card_Un_disjoint) auto\n      also from 1 and A have \"card {y\\<in>A. y < x} = size l\" by (auto dest: size_random_bst)\n      also from 1 and A have \"card {y\\<in>A. y > x} = size r\" by (auto dest: size_random_bst)\n      finally show ?case by simp\n    qed\n    also have \"\\<dots> = do {\n                      x \\<leftarrow> pmf_of_set A;\n                      (l,r) \\<leftarrow> pair_pmf (map_pmf ipl (random_bst {y \\<in> A. y < x}))\n                                        (map_pmf ipl (random_bst {y \\<in> A. y > x}));\n                      return_pmf (n + l + r)\n                    }\" by (simp add: map_pair [symmetric] case_prod_unfold bind_map_pmf)\n    also have \"\\<dots> = do {\n                      i \\<leftarrow> map_pmf rank (pmf_of_set A);\n                      (l,r) \\<leftarrow> pair_pmf (rqs_cost i) (rqs_cost (n - i));\n                      return_pmf (n + l + r)\n                    }\" (is \"_ = bind_pmf _ ?f\") unfolding bind_map_pmf\n    proof (intro bind_pmf_cong refl pair_pmf_cong, goal_cases)\n      case (1 x)\n      have \"map_pmf ipl (random_bst {y \\<in> A. y < x}) = rqs_cost (card {y \\<in> A. y < x})\"\n        using 1 and A by (intro psubset.IH) auto\n      also have \"{y \\<in> A. y < x} = {y \\<in> A - {x}. y \\<le> x}\" by auto\n      hence \"card {y \\<in> A. y < x} = rank x\" by (simp add: rank_def linorder_rank_def)\n      finally show ?case .\n    next\n      case (2 x)\n      have \"map_pmf ipl (random_bst {y \\<in> A. y > x}) = rqs_cost (card {y \\<in> A. y > x})\"\n        using 2 and A by (intro psubset.IH) auto\n      also have \"{y \\<in> A. y > x} = A - {x} - {y \\<in> A - {x}. y \\<le> x}\" by auto\n      hence \"card {y \\<in> A. y > x} = card \\<dots>\" by (simp only:)\n      also from 2 and A have \"\\<dots> = n - rank x\"\n        by (subst card_Diff_subset) (auto simp: rank_def linorder_rank_def n_def)\n      finally show ?case .\n    qed\n    also from A have \"map_pmf rank (pmf_of_set A) = pmf_of_set {..<card A}\"\n      unfolding rank_def by (intro map_pmf_of_set_bij_betw bij_betw_linorder_rank[of UNIV]) auto\n    also have \"{..<card A} = {..n}\" by (auto simp: card)\n    also have \"pmf_of_set \\<dots> \\<bind> ?f = rqs_cost (card A)\"\n      by (simp add: pair_pmf_def bind_assoc_pmf bind_return_pmf card)\n    finally show ?thesis .\n  qed simp_all\nqed\n\ntext \\<open>\n  In particular, this means that the expected values are the same:\n\\<close>\ncorollary expected_ipl_random_bst_eq:\n  assumes \"finite A\"\n  shows   \"measure_pmf.expectation (random_bst A) ipl = rqs_cost_exp (card A)\"\nproof -\n  have \"measure_pmf.expectation (random_bst A) ipl =\n          measure_pmf.expectation (map_pmf ipl (random_bst A)) real\" by simp\n  also from assms have \"map_pmf ipl (random_bst A) = rqs_cost (card A)\"\n    by (rule map_pmf_random_bst_eq_rqs_cost)\n  also have \"measure_pmf.expectation \\<dots> real = rqs_cost_exp (card A)\"\n    by (rule expectation_rqs_cost)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Therefore, the results about the expected number of comparisons of QuickSort carry over\n  to the expected internal path length:\n\\<close>\ncorollary expected_ipl_random_bst_eq':\n  assumes \"finite A\"\n  shows   \"measure_pmf.expectation (random_bst A) ipl =\n             2 * real (card A + 1) * harm (card A) - 4 * real (card A)\"\n  by (simp add: expected_ipl_random_bst_eq rqs_cost_exp_eq assms)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Random_BSTs/Random_BSTs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7593386573861808}}
{"text": "header {*Preliminaries*}\n\ntheory Measure\nimports Sigma_Algebra MonConv\nbegin\n\n(*We use a modified version of the simple Sigma_Algebra Theory by\nMarkus Wenzel here,\n  which does not need an explicit definition of countable,\n  changing the names according to Joe Hurd*)\ntext {* Now we are already set for the central concept of\n  measure. The following definitions are translated as faithfully as possible\n  from those in Joe Hurd's thesis \\cite{hurd2002}. *}\n\ndefinition\n  measurable:: \"'a set set \\<Rightarrow> 'b set set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\" where\n  \"measurable F G = {f. \\<forall>g\\<in>G. f -` g \\<in> F}\"\n\ntext {*So a function is called $F$-$G$-measurable if and only if the inverse\n  image of any set in $G$ is in $F$. $F$ and $G$ are usually the sets of\n  measurable sets, the first component of a measure space\\footnote{In\n  standard mathematical notation, the universe is first in a\n  measure space triple, but in our definitions, following Joe Hurd, it is always the\n  whole type universe and therefore omitted.}.*}\n\n\ndefinition\n  measurable_sets:: \"('a set set * ('a set \\<Rightarrow> real)) \\<Rightarrow> 'a set set\" where\n  \"measurable_sets = fst\"\n\ndefinition\n  measure:: \"('a set set * ('a set \\<Rightarrow> real)) \\<Rightarrow> ('a set \\<Rightarrow> real)\" where\n  \"measure = snd\"\n\ntext {*The other component is the measure itself. It is a function that\n  assigns a nonnegative real number to every measurable set and has\n  the property of being\n  countably additive for disjoint sets.*}\n\n\ndefinition\n  positive:: \"('a set set * ('a set \\<Rightarrow> real)) \\<Rightarrow> bool\" where\n  \"positive M \\<longleftrightarrow> measure M {} = 0 \\<and> \n  (\\<forall>A. A\\<in> measurable_sets M \\<longrightarrow> 0 \\<le> measure M A)\"\n  (*Remark: This definition of measure space is not minimal,\n  in the sense that the containment of the UNION in the measurable sets \n  is implied by the measurable sets being a sigma algebra*)\n\ndefinition\n  countably_additive:: \"('a set set * ('a set => real)) => bool\" where\n  \"countably_additive M \\<longleftrightarrow> (\\<forall>f::(nat => 'a set). range f \\<subseteq> measurable_sets M\n  \\<and> (\\<forall>m n. m \\<noteq> n \\<longrightarrow> f m \\<inter> f n = {}) \\<and>  (\\<Union>i. f i) \\<in> measurable_sets M\n  \\<longrightarrow> (\\<lambda>n. measure M (f n)) sums  measure M (\\<Union>i. f i))\" \n\ntext {*This last property deserves some comments. The conclusion is\n  usually --- also in the aforementioned source --- phrased as\n  \n  @{text \"measure M (\\<Union>i. f i) = (\\<Sum>n. measure M (f n))\"}.\n\n  In our formal setting this is unsatisfactory, because the\n  sum operator\\footnote{Which is merely syntactic sugar for the\n  \\isa{suminf} functional from the \\isa{Series} theory\n  \\cite{Fleuriot:2000:MNR}.}, like any HOL function, is total, although\n  a series obviously need not converge. It is defined using the @{text \\<epsilon>} operator, and its\n  behavior is unspecified in the diverging case. Hence, the above assertion\n  would give no information about the convergence of the series. \n  \n  Furthermore, the definition contains redundancy. Assuming that the\n  countable union of sets is measurable is unnecessary when the\n  measurable sets form a sigma algebra, which is postulated in the\n  final definition\\footnote{Joe Hurd inherited this practice from a very\n  influential probability textbook \\cite{Williams.mart}}. \n  *}\n\ndefinition\n  measure_space:: \"('a set set * ('a set \\<Rightarrow> real)) \\<Rightarrow> bool\" where\n  \"measure_space M \\<longleftrightarrow> sigma_algebra (measurable_sets M) \\<and> \n  positive M \\<and> countably_additive M\"\n\ntext {*Note that our definition is restricted to finite measure\n  spaces --- that is, @{text \"measure M UNIV < \\<infinity>\"} --- since the measure\n  must be a real number for any measurable set. In probability, this\n  is naturally the case.    \n\n  Two important theorems close this section. Both appear in\n  Hurd's work as well, but are shown anyway, owing to their central\n  role in measure theory. The first one is a mighty tool for proving measurability. It states\n  that for a function mapping one sigma algebra into another, it is\n  sufficient to be measurable regarding only a generator of the target\n  sigma algebra. Formalizing the interesting proof out of Bauer's\n  textbook \\cite{Bauer} is relatively straightforward using rule\n  induction. *}\n\ntheorem assumes sig: \"sigma_algebra a\" and meas: \"f \\<in> measurable a b\" shows \n  measurable_lift: \"f \\<in> measurable a (sigma b)\"\nproof -\n  def Q \\<equiv> \"{q. f -` q \\<in> a}\"\n  with meas have 1: \"b \\<subseteq> Q\" by (auto simp add: measurable_def) \n\n  { fix x assume \"x\\<in>sigma b\"\n    hence \"x\\<in>Q\"\n    proof (induct rule: sigma.induct)\n      case basic\n      from 1 show \" \\<And>a. a \\<in> b \\<Longrightarrow> a \\<in> Q\" ..\n    next\n      case empty\n      from sig have \"{}\\<in>a\" \n        by (simp only: sigma_algebra_def)     \n      thus \"{} \\<in> Q\" \n        by (simp add: Q_def)\n    next\n      case complement\n      fix r assume \"r \\<in> Q\"\n      then obtain r1 where im: \"r1 = f -` r\" and a: \"r1 \\<in> a\" \n        by (simp add: Q_def)\n      with sig have \"-r1 \\<in> a\" \n        by (simp only: sigma_algebra_def)\n      with im Q_def show \"-r \\<in> Q\" \n        by (simp add: vimage_Compl)\n    next\n      case Union\n      fix r assume \"\\<And>i::nat. r i \\<in> Q\"\n      then obtain r1 where im: \"\\<And>i. r1 i =  f -` r i\" and a: \"\\<And>i. r1 i \\<in>        a\" \n        by (simp add: Q_def)\n      from a sig have \"UNION UNIV r1 \\<in> a\" \n        by (auto simp only: sigma_algebra_def)\n      with im Q_def show \"UNION UNIV r \\<in> Q\" \n        by (auto simp add: vimage_UN)\n    qed }\n        \n  hence \"(sigma b) \\<subseteq> Q\" ..\n  thus \"f \\<in> measurable a (sigma b)\" \n    by (auto simp add: measurable_def Q_def)\nqed\n\ntext {*The case is different for the second theorem. It is only five\n  lines in the book (ibid.), but almost 200 in formal text. Precision\n  still pays here, gaining a detailed view of a technique that\n  is often employed in measure theory --- making a sequence of sets\n  disjoint. Moreover, the necessity for the above-mentioned change in the\n  definition of countably additive was detected only in the\n  formalization of this proof. \n\n  To enable application of the additivity of measures, the following construction\n  yields disjoint sets. We skip the justification of the lemmata for\n  brevity. *} \n\nprimrec mkdisjoint:: \"(nat \\<Rightarrow> 'a set) \\<Rightarrow> (nat \\<Rightarrow> 'a set)\"\nwhere\n  \"mkdisjoint A 0 = A 0\"\n| \"mkdisjoint A (Suc n) = A (Suc n) - A n\"\n\nlemma mkdisjoint_un: \n  assumes up: \"\\<And>n. A n \\<subseteq> A (Suc n)\"\n  shows \"A n = (\\<Union>i\\<in>{..n}. mkdisjoint A i)\"\n(*<*)proof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  hence \"A n = (\\<Union>i\\<in>{..n}. mkdisjoint A i)\" .\n  moreover\n  have \"(\\<Union>i\\<in>{..(Suc n)}. mkdisjoint A i) = mkdisjoint A (Suc n) \\<union>\n    (\\<Union>i\\<in>{..n}. mkdisjoint A i)\" by (simp add: atMost_Suc) \n  moreover\n  have \"mkdisjoint A (Suc n) \\<union> A n = A (Suc n) \\<union> A n\" by simp\n  moreover\n  from up have \"\\<dots> = A (Suc n)\" by auto\n  ultimately\n  show ?case by simp\nqed(*>*)\n\n\nlemma mkdisjoint_disj: \n  assumes up: \"\\<And>n. A n \\<subseteq> A (Suc n)\" and ne: \"m \\<noteq> n\"\n  shows \"mkdisjoint A m \\<inter> mkdisjoint A n = {}\"\n(*<*)proof -\n  { fix m1 m2::nat assume less: \"m1 < m2\"\n    hence \"0 < m2\" by simp\n    then obtain n where eq: \"m2 = Suc n\" by (auto simp add: gr0_conv_Suc)\n    with less have less2: \"m1 < Suc n\" by simp\n    \n    {\n      fix y assume y: \"y \\<in> mkdisjoint A m1\"\n      fix x assume x: \"x \\<in> mkdisjoint A m2\"\n      with eq have\"x \\<notin> A n\" by simp\n      also from up have \"A n = (\\<Union>i\\<in>{..n}. mkdisjoint A i)\" \n        by (rule mkdisjoint_un) \n      also \n      from less2 have \"m1 \\<in> {..n}\" by simp\n      hence \"mkdisjoint A m1 \\<subseteq> (\\<Union>i\\<in>{..n}. mkdisjoint A i)\" by auto\n      ultimately \n      have \"x \\<notin> mkdisjoint A m1\" by fast\n      with y have \"y \\<noteq> x\" by fast\n    }\n    hence \"mkdisjoint A m1 \\<inter> mkdisjoint A m2 = {}\" \n      by (simp add: disjoint_iff_not_equal)\n  } hence 1: \"\\<And>m1 m2. m1 < m2 \\<Longrightarrow>  mkdisjoint A m1 \\<inter> mkdisjoint A m2 = {}\" .\n  \n  show ?thesis\n  proof (cases \"m < n\")\n    case True\n    thus ?thesis by (rule 1)\n  next\n    case False\n    with ne have \"n < m\" by arith\n    hence \"mkdisjoint A n \\<inter> mkdisjoint A m = {}\" by (rule 1)\n    thus ?thesis by fast\n  qed\nqed(*>*)\n   \n\nlemma mkdisjoint_mon_conv:\n  assumes mc: \"A\\<up>B\" \n  shows \"(\\<Union>i. mkdisjoint A i) = B\"\n(*<*)proof\n  { fix x assume \"x \\<in> (\\<Union>i. mkdisjoint A i)\"\n    then obtain i where \"x \\<in> mkdisjoint A i\" by auto\n    hence \"x \\<in> A i\" by (cases i) simp_all\n    with mc have \"x \\<in> B\" by (auto simp add: set_mon_conv)\n  }\n  thus \"(\\<Union>i. mkdisjoint A i) \\<subseteq> B\" by fast\n     \n  { fix x assume \"x \\<in> B\"\n    with mc obtain i where \"x \\<in> A i\" by (auto simp add: set_mon_conv)\n    also from mc have \"\\<And>n. A n \\<subseteq> A (Suc n)\" by (simp only: set_mon_conv)\n    hence \"A i = (\\<Union>r\\<in>{..i}. mkdisjoint A r)\" by (rule mkdisjoint_un)\n    also have \"\\<dots> \\<subseteq> (\\<Union>r. mkdisjoint A r)\" by auto\n    finally have \"x \\<in> (\\<Union>i. mkdisjoint A i)\".\n  }\n  thus \"B \\<subseteq> (\\<Union>i. mkdisjoint A i)\" by fast\nqed(*>*)\n\n  \n(*This is in Joe Hurd's Thesis (p. 35) as Monotone Convergence theorem. Check the real name \\<dots> . \n    Also, it's not as strong as it could be,\n    but we need no more.*)\n\ntext {* Joe Hurd calls the following the Monotone Convergence Theorem,\n  though in mathematical literature this name is often reserved for a\n  similar fact\n  about integrals that we will prove in \\ref{nnfis}, which depends on this\n  one. The claim made here is that the measures of monotonically convergent sets\n  approach the measure of their limit. A strengthened version would\n  imply monotone convergence of the measures, but is not needed in the\n  development.\n  *}\n\ntheorem measure_mon_conv: \n  assumes ms: \"measure_space M\" and \n  Ams: \"\\<And>n. A n \\<in> measurable_sets M\" and AB: \"A\\<up>B\" \n  shows \"(\\<lambda>n. measure M (A n)) ----> measure M B\"\nproof -\n  \n  from AB have up: \"\\<And>n. A n \\<subseteq> A (Suc n)\" \n    by (simp only: set_mon_conv)\n  \n  { fix i\n    have \"mkdisjoint A i \\<in> measurable_sets M\" \n    proof (cases i)\n      case 0 with Ams show ?thesis by simp\n    next\n      case (Suc i)\n      have \"A (Suc i) - A i = A (Suc i) \\<inter> - A i\" by blast\n      with Suc ms Ams show ?thesis \n        by (auto simp add: measure_space_def sigma_algebra_def sigma_algebra_inter)\n    qed\n  } \n  hence i: \"\\<And>i. mkdisjoint A i \\<in> measurable_sets M\" .\n      \n  with ms have un: \"(\\<Union>i. mkdisjoint A i) \\<in> measurable_sets M\" \n    by (simp add: measure_space_def sigma_algebra_def)\n  moreover\n  from i have range: \"range (mkdisjoint A) \\<subseteq> measurable_sets M\" \n    by fast\n  moreover\n  from up have \"\\<forall>i j. i \\<noteq> j \\<longrightarrow>  mkdisjoint A i \\<inter> mkdisjoint A j = {}\" \n    by (simp add: mkdisjoint_disj)\n  moreover note ms\n  ultimately\n  have sums:\n    \"(\\<lambda>i. measure M (mkdisjoint A i)) sums (measure M (\\<Union>i. mkdisjoint A i))\"\n    by (simp add: measure_space_def countably_additive_def)\n  hence \"(\\<Sum>i. measure M (mkdisjoint A i)) = (measure M (\\<Union>i. mkdisjoint A i))\" \n    by (rule sums_unique[THEN sym])\n  \n  also\n  from sums have \"summable (\\<lambda>i. measure M (mkdisjoint A i))\" \n    by (rule sums_summable)\n\n  hence \"(\\<lambda>n. \\<Sum>i<n. measure M (mkdisjoint A i))\n    ----> (\\<Sum>i. measure M (mkdisjoint A i))\"\n    by (rule summable_LIMSEQ)\n                                         \n  hence \"(\\<lambda>n. \\<Sum>i<Suc n. measure M (mkdisjoint A i)) ----> (\\<Sum>i. measure M (mkdisjoint A i))\"\n    by (rule LIMSEQ_Suc)\n  \n  ultimately have \"(\\<lambda>n. \\<Sum>i<Suc n. measure M (mkdisjoint A i))\n    ----> (measure M (\\<Union>i. mkdisjoint A i))\" by simp\n    \n  also \n  { fix n \n    from up have \"A n = (\\<Union>i\\<in>{..n}. mkdisjoint A i)\" \n      by (rule mkdisjoint_un)\n    hence \"measure M (A n) = measure M (\\<Union>i\\<in>{..n}. mkdisjoint A i)\"\n      by simp\n    \n    also have \n      \"(\\<Union>i\\<in>{..n}. mkdisjoint A i) = (\\<Union>i. if i\\<le>n then mkdisjoint A i else {})\"\n    proof -\n      have \"UNIV = {..n} \\<union> {n<..}\" by auto\n      hence \"(\\<Union>i. if i\\<le>n then mkdisjoint A i else {}) = \n        (\\<Union>i\\<in>{..n}. if i\\<le>n then mkdisjoint A i else {}) \n        \\<union>  (\\<Union>i\\<in>{n<..}. if i\\<le>n then mkdisjoint A i else {})\" \n        by (auto split: if_splits)\n      moreover\n      { have \"(\\<Union>i\\<in>{n<..}. if i\\<le>n then mkdisjoint A i else {}) = {}\"\n          by force }\n      hence \"\\<dots> = (\\<Union>i\\<in>{..n}. mkdisjoint A i)\" \n        by auto\n      ultimately show \n        \"(\\<Union>i\\<in>{..n}. mkdisjoint A i) = (\\<Union>i. if i\\<le>n then mkdisjoint A i else {})\" by simp\n    qed\n    \n    ultimately have \n      \"measure M (A n) = measure M (\\<Union>i. if i\\<le>n then mkdisjoint A i else {})\" \n      by simp\n\n    also \n    from i ms have \n      un: \"(\\<Union>i. if i\\<le>n then mkdisjoint A i else {}) \\<in> measurable_sets M\" \n      by (simp add: measure_space_def sigma_algebra_def)\n    moreover\n    from i ms have \n      \"range (\\<lambda>i. if i\\<le>n then mkdisjoint A i else {}) \\<subseteq> measurable_sets M\" \n      by (auto simp add: measure_space_def sigma_algebra_def)\n    moreover\n    from up have \"\\<forall>i j. i \\<noteq> j \\<longrightarrow> \n      (if i\\<le>n then mkdisjoint A i else {}) \\<inter> \n      (if j\\<le>n then mkdisjoint A j else {}) = {}\" \n      by (simp add: mkdisjoint_disj)\n    moreover note ms\n    ultimately have \n      \"measure M (A n) = (\\<Sum>i. measure M (if i \\<le> n then mkdisjoint A i else {}))\"\n      by (simp add: measure_space_def countably_additive_def sums_unique)\n    \n    also\n    from ms have \n      \"\\<forall>i. (Suc n)\\<le>i \\<longrightarrow> measure M (if i \\<le> n then mkdisjoint A i else {}) = 0\"\n      by (simp add: measure_space_def positive_def)\n    hence \"(\\<lambda>i. measure M (if i \\<le> n then mkdisjoint A i else {})) sums\n      (\\<Sum>i<Suc n. measure M (if i \\<le> n then mkdisjoint A i else {}))\"\n      by (intro sums_finite) auto\n    hence \"(\\<Sum>i. measure M (if i \\<le> n then mkdisjoint A i else {})) = \n      (\\<Sum>i<Suc n. measure M (if i \\<le> n then mkdisjoint A i else {}))\"\n      by (rule sums_unique[THEN sym])\n    also\n    have \"\\<dots> = (\\<Sum>i<Suc n. measure M (mkdisjoint A i))\"\n      by simp\n    finally have \n      \"measure M (A n) = (\\<Sum>i<Suc n. measure M (mkdisjoint A i))\" .\n  }\n  \n  ultimately have \n    \"(\\<lambda>n. measure M (A n)) ----> (measure M (\\<Union>i. mkdisjoint A i))\" \n    by simp\n  \n  with AB show ?thesis \n    by (simp add: mkdisjoint_mon_conv)\nqed(*>*)\n\n\n(*<*)\nprimrec trivial_series2:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> (nat \\<Rightarrow> 'a set)\"\nwhere\n  \"trivial_series2 a b 0 = a\"\n| \"trivial_series2 a b (Suc n) = (if (n=0) then b else {})\"\n\nlemma measure_additive: assumes ms: \"measure_space M\"\n  and disj: \"a \\<inter> b = {}\" and a: \"a \\<in> measurable_sets M\"\n  and b:\"b \\<in> measurable_sets M\"\n  shows \"measure M (a \\<union> b) = measure M a + measure M b\"\n(*<*)proof -\n  have \"(a \\<union> b) = (\\<Union>i. trivial_series2 a b i)\"\n  proof (rule set_eqI)\n    fix x\n    {\n      assume \"x \\<in> a \\<union> b\"\n      hence \"\\<exists>i. x \\<in> trivial_series2 a b i\"\n      proof \n        assume \"x \\<in> a\"\n        hence \"x \\<in> trivial_series2 a b 0\"\n          by simp\n        thus \"\\<exists>i. x \\<in> trivial_series2 a b i\"\n          by fast\n      next\n        assume \"x \\<in> b\"\n        hence \"x \\<in> trivial_series2 a b 1\"\n          by simp\n        thus \"\\<exists>i. x \\<in> trivial_series2 a b i\"\n          by fast\n      qed\n    }\n    hence \"(x \\<in> a \\<union> b) \\<Longrightarrow> (x \\<in> (\\<Union>i. trivial_series2 a b i))\"\n      by simp\n    also\n    { \n      assume \"x \\<in> (\\<Union>i. trivial_series2 a b i)\"\n      then obtain i where x: \"x \\<in> trivial_series2 a b i\"\n        by auto\n      hence \"x \\<in> a \\<union> b\"\n      proof (cases i)\n        case 0\n        with x show ?thesis by simp\n      next\n        case (Suc n)\n        with x show ?thesis\n          by (cases n) auto\n      qed\n    }\n    ultimately show \"(x \\<in> a \\<union> b) = (x \\<in> (\\<Union>i. trivial_series2 a b i))\"\n      by fast\n  qed\n  also \n  { fix i\n    from a b ms have \"trivial_series2 a b i \\<in> measurable_sets M\"\n      by (cases i) (auto simp add: measure_space_def sigma_algebra_def)\n  }\n  hence m1: \"range (trivial_series2 a b) \\<subseteq> measurable_sets M\"\n    and m2: \"(\\<Union>i. trivial_series2 a b i) \\<in> measurable_sets M\"\n    using ms\n    by (auto simp add: measure_space_def sigma_algebra_def)\n  \n  { fix i j::nat\n    assume \"i \\<noteq> j\"\n    hence \"trivial_series2 a b i \\<inter> trivial_series2 a b j = {}\"\n      using disj\n      by (cases i, cases j, auto)(cases j, auto)\n  }\n  with m1 m2 have \"(\\<lambda>n. measure M (trivial_series2 a b n)) sums  measure M (\\<Union>i. trivial_series2 a b i)\" \n    using ms \n    by (simp add: measure_space_def countably_additive_def)\n  moreover\n  from ms have \"\\<forall>m. Suc(Suc 0) \\<le> m \\<longrightarrow> measure M (trivial_series2 a b m) = 0\"\n  proof (clarify)\n    fix m \n    assume \"Suc (Suc 0) \\<le> m\"\n    thus \"measure M (trivial_series2 a b m) = 0\"\n      using ms\n      by (cases m) (auto simp add: measure_space_def positive_def) \n  qed\n  hence \"(\\<lambda>n. measure M (trivial_series2 a b n)) sums (\\<Sum>n<Suc(Suc 0). measure M (trivial_series2 a b n))\"\n    by (intro sums_finite) auto\n  moreover\n  have \"(\\<Sum>n=0..<Suc(Suc 0). measure M (trivial_series2 a b n)) =\n    measure M a + measure M b\"\n    by simp\n  ultimately\n  have \"measure M (a \\<union> b) = (\\<Sum>n. measure M (trivial_series2 a b n))\"\n    and \"Measure.measure M a + Measure.measure M b = (\\<Sum>n. measure M (trivial_series2 a b n))\"\n    by (simp_all add: sums_unique)\n  thus ?thesis by simp\nqed\n(*>*)\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Integration/Measure.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.875787001374006, "lm_q1q2_score": 0.7593386511701641}}
{"text": "(*\n  File:    Efficient_Discrete_Sqrt.thy\n  Author:  Markus Großer, Manuel Eberl\n\n  A reasonably efficient algorithm to compute the square root of a natural number (rounded down)\n  and to test if a natural number is a perfect square.\n*)\ntheory Efficient_Discrete_Sqrt\nimports\n  Complex_Main\n  \"HOL-Computational_Algebra.Computational_Algebra\"\n  \"HOL-Library.Discrete\"\n  \"HOL-Library.Tree\"\n  \"HOL-Library.IArray\"\nbegin\nsection \\<open>Efficient Algorithms for the Square Root on \\<open>\\<nat>\\<close>\\<close>\n\n(*\n  TODO: This could perhaps be moved somewhere else. Thre is also probably some overlap\n  with Sqrt_Babylonian\n*)\n\nsubsection \\<open>A Discrete Variant of Heron's Algorithm\\<close>\n\ntext \\<open>\n  An algorithm for calculating the discrete square root, taken from \n  Cohen~\\cite{cohen2010algebraic}. This algorithm is essentially a discretised variant of\n  Heron's method or Newton's method specialised to the square root function.\n\\<close>\n\nlemma sqrt_eq_floor_sqrt: \"Discrete.sqrt n = nat \\<lfloor>sqrt n\\<rfloor>\"\nproof -\n  have \"real ((nat \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2) = (real (nat \\<lfloor>sqrt n\\<rfloor>))\\<^sup>2\"\n    by simp\n  also have \"\\<dots> \\<le> sqrt (real n) ^ 2\"\n    by (intro power_mono) auto\n  also have \"\\<dots> = real n\" by simp\n  finally have \"(nat \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2 \\<le> n\"\n    by (simp only: of_nat_le_iff)\n  moreover have \"n < (Suc (nat \\<lfloor>sqrt n\\<rfloor>))\\<^sup>2\" proof -\n    have \"(1 + \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2 > n\"\n      using floor_correct[of \"sqrt n\"] real_le_rsqrt[of \"1 + \\<lfloor>sqrt n\\<rfloor>\" n]\n        of_int_less_iff[of n \"(1 + \\<lfloor>sqrt n\\<rfloor>)\\<^sup>2\"] not_le\n      by fastforce\n    then show ?thesis\n      using le_nat_floor[of \"Suc (nat \\<lfloor>sqrt n\\<rfloor>)\" \"sqrt n\"]\n        of_nat_le_iff[of \"(Suc (nat \\<lfloor>sqrt n\\<rfloor>))\\<^sup>2\" n] real_le_rsqrt[of _ n] not_le\n      by fastforce\n  qed\n  ultimately show ?thesis using sqrt_unique by fast\nqed\n\nfun newton_sqrt_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"newton_sqrt_aux x n =\n     (let y = (x + n div x) div 2\n      in if y < x then newton_sqrt_aux y n else x)\"\n\ndeclare newton_sqrt_aux.simps [simp del]\n\nlemma newton_sqrt_aux_simps:\n  \"(x + n div x) div 2 < x \\<Longrightarrow> newton_sqrt_aux x n = newton_sqrt_aux ((x + n div x) div 2) n\"\n  \"(x + n div x) div 2 \\<ge> x \\<Longrightarrow> newton_sqrt_aux x n = x\"\n  by (subst newton_sqrt_aux.simps; simp add: Let_def)+\n\nlemma heron_step_real: \"\\<lbrakk>t > 0; n \\<ge> 0\\<rbrakk> \\<Longrightarrow> (t + n/t) / 2 \\<ge> sqrt n\"\n  using arith_geo_mean_sqrt[of t \"n/t\"] by simp\n\nlemma heron_step_div_eq_floored:\n  \"(t::nat) > 0 \\<Longrightarrow> (t + (n::nat) div t) div 2 = nat \\<lfloor>(t + n/t) / 2\\<rfloor>\"\nproof -\n  assume \"t > 0\"\n  then have \"\\<lfloor>(t + n/t) / 2\\<rfloor> = \\<lfloor>(t*t + n) / (2*t)\\<rfloor>\"\n    by (simp add: mult_divide_mult_cancel_right[of t \"t + n/t\" 2, symmetric]\n        algebra_simps)\n  also have \"\\<dots> = (t*t + n) div (2*t)\"\n    using floor_divide_of_nat_eq by blast\n  also have \"\\<dots> = (t*t + n) div t div 2\"\n    by (simp add: Divides.div_mult2_eq mult.commute)\n  also have \"\\<dots> = (t + n div t) div 2\"\n    by (simp add: \\<open>0 < t\\<close> power2_eq_square)\n  finally show ?thesis by simp\nqed\n\nlemma heron_step: \"t > 0 \\<Longrightarrow> (t + n div t) div 2 \\<ge> Discrete.sqrt n\"\nproof -\n  assume \"t > 0\"\n  have \"Discrete.sqrt n = nat \\<lfloor>sqrt n\\<rfloor>\" by (rule sqrt_eq_floor_sqrt)\n  also have \"\\<dots> \\<le> nat \\<lfloor>(t + n/t) / 2\\<rfloor>\"\n    using heron_step_real[of t n] \\<open>t > 0\\<close> by linarith\n  also have \"\\<dots> = (t + n div t) div 2\"\n    using heron_step_div_eq_floored[OF \\<open>t > 0\\<close>] by simp\n  finally show ?thesis .\nqed\n\nlemma newton_sqrt_aux_correct:\n  assumes \"x \\<ge> Discrete.sqrt n\"\n  shows   \"newton_sqrt_aux x n = Discrete.sqrt n\"\n  using assms\nproof (induction x n rule: newton_sqrt_aux.induct)\n  case (1 x n)\n  show ?case\n  proof (cases \"x = Discrete.sqrt n\")\n    case True\n    then have \"(x ^ 2) div x \\<le> n div x\" by (intro div_le_mono) simp_all\n    also have \"(x ^ 2) div x = x\" by (simp add: power2_eq_square)\n    finally have \"(x + n div x) div 2 \\<ge> x\" by linarith\n    with True show ?thesis by (auto simp: newton_sqrt_aux_simps)\n  next\n    case False\n    with \"1.prems\" have x_gt_sqrt: \"x > Discrete.sqrt n\" by auto\n    with Discrete.le_sqrt_iff[of x n] have \"n < x ^ 2\" by simp\n    have \"x * (n div x) \\<le> n\" using mult_div_mod_eq[of x n] by linarith\n    also have \"\\<dots> < x ^ 2\" using Discrete.le_sqrt_iff[of x n] and x_gt_sqrt by simp\n    also have \"\\<dots> = x * x\" by (simp add: power2_eq_square)\n    finally have \"n div x < x\" by (subst (asm) mult_less_cancel1) auto\n    then have step_decreasing: \"(x + n div x) div 2 < x\" by linarith\n    with x_gt_sqrt have step_ge_sqrt: \"(x + n div x) div 2 \\<ge> Discrete.sqrt n\"\n      by (simp add: heron_step)\n    from step_decreasing have \"newton_sqrt_aux x n = newton_sqrt_aux ((x + n div x) div 2) n\"\n      by (simp add: newton_sqrt_aux_simps)\n    also have \"\\<dots> = Discrete.sqrt n\"\n      by (intro \"1.IH\" step_decreasing step_ge_sqrt) simp_all\n    finally show ?thesis .\n  qed\nqed\n\ndefinition newton_sqrt :: \"nat \\<Rightarrow> nat\" where\n  \"newton_sqrt n = newton_sqrt_aux n n\"\n\ndeclare Discrete.sqrt_code [code del]\n\ntheorem Discrete_sqrt_eq_newton_sqrt [code]: \"Discrete.sqrt n = newton_sqrt n\"\n  unfolding newton_sqrt_def by (simp add: newton_sqrt_aux_correct Discrete.sqrt_le)\n\n\nsubsection \\<open>Square Testing\\<close>\n\ntext \\<open>\n  Next, we implement an algorithm to determine whether a given natural number is a perfect square,\n  as described by Cohen~\\cite{cohen2010algebraic}. Essentially, the number first determines whether\n  the number is a square. Essentially\n\\<close>\n\ndefinition q11 :: \"nat set\"\n  where \"q11 = {0, 1, 3, 4, 5, 9}\"\ndefinition q63 :: \"nat set\"\n  where \"q63 = {0, 1, 4, 7, 9, 16, 28, 18, 22, 25, 36, 58, 46, 49, 37, 43}\"\ndefinition q64 :: \"nat set\"\n  where \"q64 = {0, 1, 4, 9, 16, 17, 25, 36, 33, 49, 41, 57}\"\ndefinition q65 :: \"nat set\"\n  where \"q65 = {0, 1, 4, 10, 14, 9, 16, 26, 30, 25, 29, 40, 56, 36, 49, 61, 35, 51, 39, 55, 64}\"\n\n\ndefinition q11_array where\n  \"q11_array = IArray [True,True,False,True,True,True,False,False,False,True,False]\"\n\ndefinition q63_array where\n  \"q63_array = IArray [True,True,False,False,True,False,False,True,False,True,False,False,\n     False,False,False,False,True,False,True,False,False,False,True,False,False,True,False,\n     False,True,False,False,False,False,False,False,False,True,True,False,False,False,False,\n     False,True,False,False,True,False,False,True,False,False,False,False,False,False,False,\n     False,True,False,False,False,False,False]\"\n\ndefinition q64_array where\n  \"q64_array = IArray [True,True,False,False,True,False,False,False,False,True,False,False,\n     False,False,False,False,True,True,False,False,False,False,False,False,False,True,False,\n     False,False,False,False,False,False,True,False,False,True,False,False,False,False,True,\n     False,False,False,False,False,False,False,True,False,False,False,False,False,False,\n     False,True,False,False,False,False,False,False, False]\"\n\ndefinition q65_array where\n  \"q65_array = IArray [True,True,False,False,True,False,False,False,False,True,True,False,\n     False,False,True,False,True,False,False,False,False,False,False,False,False,True,True,\n     False,False,True,True,False,False,False,False,True,True,False,False,True,True,False,\n     False,False,False,False,False,False,False,True,False,True,False,False,False,True,True\n     ,False,False,False,False,True,False,False,True,False]\"\n\nlemma sub_q11_array: \"i \\<in> {..<11} \\<Longrightarrow> IArray.sub q11_array i \\<longleftrightarrow> i \\<in> q11\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q11_def q11_array_def, elim disjE; simp)\n\nlemma sub_q63_array: \"i \\<in> {..<63} \\<Longrightarrow> IArray.sub q63_array i \\<longleftrightarrow> i \\<in> q63\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q63_def q63_array_def, elim disjE; simp)\n\nlemma sub_q64_array: \"i \\<in> {..<64} \\<Longrightarrow> IArray.sub q64_array i \\<longleftrightarrow> i \\<in> q64\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q64_def q64_array_def, elim disjE; simp)\n\nlemma sub_q65_array: \"i \\<in> {..<65} \\<Longrightarrow> IArray.sub q65_array i \\<longleftrightarrow> i \\<in> q65\"\n  by (simp add: lessThan_nat_numeral lessThan_Suc q65_def q65_array_def, elim disjE; simp)\n\n\nlemma in_q11_code: \"x mod 11 \\<in> q11 \\<longleftrightarrow> IArray.sub q11_array (x mod 11)\"\n  by (subst sub_q11_array) auto\n\nlemma in_q63_code: \"x mod 63 \\<in> q63 \\<longleftrightarrow> IArray.sub q63_array (x mod 63)\"\n  by (subst sub_q63_array) auto\n\nlemma in_q64_code: \"x mod 64 \\<in> q64 \\<longleftrightarrow> IArray.sub q64_array (x mod 64)\"\n  by (subst sub_q64_array) auto\n\nlemma in_q65_code: \"x mod 65 \\<in> q65 \\<longleftrightarrow> IArray.sub q65_array (x mod 65)\"\n  by (subst sub_q65_array) auto\n\n\ndefinition square_test :: \"nat \\<Rightarrow> bool\" where\n  \"square_test n =\n    (n mod 64 \\<in> q64 \\<and> (let r = n mod 45045 in\n      r mod 63 \\<in> q63 \\<and> r mod 65 \\<in> q65 \\<and> r mod 11 \\<in> q11 \\<and> n = (Discrete.sqrt n)\\<^sup>2))\"\n\nlemma square_test_code [code]:\n  \"square_test n =\n    (IArray.sub q64_array (n mod 64) \\<and> (let r = n mod 45045 in\n           IArray.sub q63_array (r mod 63) \\<and> \n           IArray.sub q65_array (r mod 65) \\<and>\n           IArray.sub q11_array (r mod 11) \\<and> n = (Discrete.sqrt n)\\<^sup>2))\"\n    using in_q11_code [symmetric] in_q63_code [symmetric] \n          in_q64_code [symmetric] in_q65_code [symmetric]\n  by (simp add: Let_def square_test_def)\n\nlemma square_mod_lower: \"m > 0 \\<Longrightarrow> (q\\<^sup>2 :: nat) mod m = a \\<Longrightarrow> \\<exists>q' < m. q'\\<^sup>2 mod m = a\"\n  using mod_less_divisor mod_mod_trivial power_mod by blast\n\nlemma q11_upto_def: \"q11 = (\\<lambda>k. k\\<^sup>2 mod 11) ` {..<11}\"\n  by (simp add: q11_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q11_infinite_def: \"q11 = (\\<lambda>k. k\\<^sup>2 mod 11) ` {0..}\"\n  unfolding q11_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 11 xa \"xa\\<^sup>2 mod 11\"]\n      ex_nat_less_eq[of 11 \"\\<lambda>x. xa\\<^sup>2 mod 11 = x\\<^sup>2 mod 11\"]\n    by auto\nqed\n\nlemma q63_upto_def: \"q63 = (\\<lambda>k. k\\<^sup>2 mod 63) ` {..<63}\"\n  by (simp add: q63_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q63_infinite_def: \"q63 = (\\<lambda>k. k\\<^sup>2 mod 63) ` {0..}\"\n  unfolding q63_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 63 xa \"xa\\<^sup>2 mod 63\"]\n      ex_nat_less_eq[of 63 \"\\<lambda>x. xa\\<^sup>2 mod 63 = x\\<^sup>2 mod 63\"]\n    by auto\nqed\n\nlemma q64_upto_def: \"q64 = (\\<lambda>k. k\\<^sup>2 mod 64) ` {..<64}\"\n  by (simp add: q64_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q64_infinite_def: \"q64 = (\\<lambda>k. k\\<^sup>2 mod 64) ` {0..}\"\n  unfolding q64_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 64 xa \"xa\\<^sup>2 mod 64\"]\n      ex_nat_less_eq[of 64 \"\\<lambda>x. xa\\<^sup>2 mod 64 = x\\<^sup>2 mod 64\"]\n    by auto\nqed\n\nlemma q65_upto_def: \"q65 = (\\<lambda>k. k\\<^sup>2 mod 65) ` {..<65}\"\n  by (simp add: q65_def lessThan_nat_numeral lessThan_Suc insert_commute)\n\nlemma q65_infinite_def: \"q65 = (\\<lambda>k. k\\<^sup>2 mod 65) ` {0..}\"\n  unfolding q65_upto_def image_def proof (auto, goal_cases)\n  case (1 xa)\n  show ?case\n    using square_mod_lower[of 65 xa \"xa\\<^sup>2 mod 65\"]\n      ex_nat_less_eq[of 65 \"\\<lambda>x. xa\\<^sup>2 mod 65 = x\\<^sup>2 mod 65\"]\n    by auto\nqed\n\nlemma square_mod_existence:\n  fixes n k :: nat\n  assumes \"\\<exists>q. q\\<^sup>2 = n\"\n  shows \"\\<exists>q. n mod k = q\\<^sup>2 mod k\"\n  using assms by auto\n\ntheorem square_test_correct: \"square_test n \\<longleftrightarrow> is_square n\"\nproof cases\n  assume \"is_square n\"\n  hence  rhs: \"\\<exists>q. q\\<^sup>2 = n\" by (auto elim: is_nth_powerE)\n  note sq_mod = square_mod_existence[OF this]\n  have q64_member: \"n mod 64 \\<in> q64\" using sq_mod[of 64]\n    unfolding q64_infinite_def image_def by simp\n  let ?r = \"n mod 45045\"\n  have \"11 dvd (45045::nat)\" \"63 dvd (45045::nat)\" \"65 dvd (45045::nat)\" by force+\n  then have mod_45045: \"?r mod 11 = n mod 11\" \"?r mod 63 = n mod 63\" \"?r mod 65 = n mod 65\"\n    using mod_mod_cancel[of _ 45045 n] by presburger+\n  then have \"?r mod 11 \\<in> q11\" \"?r mod 63 \\<in> q63\" \"?r mod 65 \\<in> q65\"\n    using sq_mod[of 11] sq_mod[of 63] sq_mod[of 65]\n    unfolding q11_infinite_def q63_infinite_def q65_infinite_def image_def mod_45045\n    by fast+\n  then show ?thesis unfolding square_test_def Let_def using q64_member rhs by auto\nnext\n  assume not_rhs: \"\\<not>is_square n\"\n  hence \"\\<nexists>q. q\\<^sup>2 = n\" by auto\n  then have \"(Discrete.sqrt n)\\<^sup>2 \\<noteq> n\" by simp\n  then show ?thesis unfolding square_test_def by (auto simp: is_nth_power_def)\nqed\n\n\ndefinition get_nat_sqrt :: \"nat \\<Rightarrow> nat option\" \n  where \"get_nat_sqrt n = (if is_square n then Some (Discrete.sqrt n) else None)\"\n\nlemma get_nat_sqrt_code [code]:\n  \"get_nat_sqrt n = \n    (if IArray.sub q64_array (n mod 64) \\<and> (let r = n mod 45045 in\n           IArray.sub q63_array (r mod 63) \\<and> \n           IArray.sub q65_array (r mod 65) \\<and>\n           IArray.sub q11_array (r mod 11)) then\n       (let x = Discrete.sqrt n in if x\\<^sup>2 = n then Some x else None) else None)\"\n  unfolding get_nat_sqrt_def square_test_correct [symmetric] square_test_def\n  using in_q11_code [symmetric] in_q63_code [symmetric] \n        in_q64_code [symmetric] in_q65_code [symmetric]\n  by (auto split: if_splits simp: Let_def )\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Pell/Efficient_Discrete_Sqrt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7593386502597925}}
{"text": "   \ntheory SpecExt\n  imports Main \"~~/src/HOL/Library/Sublist\"\nbegin\n\nsection {* Sequential Composition of Languages *}\n\ndefinition\n  Sequ :: \"string set \\<Rightarrow> string set \\<Rightarrow> string set\" (\"_ ;; _\" [100,100] 100)\nwhere \n  \"A ;; B = {s1 @ s2 | s1 s2. s1 \\<in> A \\<and> s2 \\<in> B}\"\n\ntext {* Two Simple Properties about Sequential Composition *}\n\nlemma Sequ_empty_string [simp]:\n  shows \"A ;; {[]} = A\"\n  and   \"{[]} ;; A = A\"\nby (simp_all add: Sequ_def)\n\nlemma Sequ_empty [simp]:\n  shows \"A ;; {} = {}\"\n  and   \"{} ;; A = {}\"\nby (simp_all add: Sequ_def)\n\nlemma Sequ_assoc:\n  shows \"(A ;; B) ;; C = A ;; (B ;; C)\"\napply(auto simp add: Sequ_def)\napply blast\nby (metis append_assoc)\n\nlemma Sequ_Union_in:\n  shows \"(A ;; (\\<Union>x\\<in> B. C x)) = (\\<Union>x\\<in> B. A ;; C x)\" \nby (auto simp add: Sequ_def)\n\nsection {* Semantic Derivative (Left Quotient) of Languages *}\n\ndefinition\n  Der :: \"char \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Der c A \\<equiv> {s. c # s \\<in> A}\"\n\ndefinition\n  Ders :: \"string \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Ders s A \\<equiv> {s'. s @ s' \\<in> A}\"\n\nlemma Der_null [simp]:\n  shows \"Der c {} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_empty [simp]:\n  shows \"Der c {[]} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_char [simp]:\n  shows \"Der c {[d]} = (if c = d then {[]} else {})\"\nunfolding Der_def\nby auto\n\nlemma Der_union [simp]:\n  shows \"Der c (A \\<union> B) = Der c A \\<union> Der c B\"\nunfolding Der_def\nby auto\n\nlemma Der_UNION [simp]: \n  shows \"Der c (\\<Union>x\\<in>A. B x) = (\\<Union>x\\<in>A. Der c (B x))\"\nby (auto simp add: Der_def)\n\nlemma Der_Sequ [simp]:\n  shows \"Der c (A ;; B) = (Der c A) ;; B \\<union> (if [] \\<in> A then Der c B else {})\"\nunfolding Der_def Sequ_def\n  by (auto simp add: Cons_eq_append_conv)\n\n\nsection {* Kleene Star for Languages *}\n\ninductive_set\n  Star :: \"string set \\<Rightarrow> string set\" (\"_\\<star>\" [101] 102)\n  for A :: \"string set\"\nwhere\n  start[intro]: \"[] \\<in> A\\<star>\"\n| step[intro]:  \"\\<lbrakk>s1 \\<in> A; s2 \\<in> A\\<star>\\<rbrakk> \\<Longrightarrow> s1 @ s2 \\<in> A\\<star>\"\n\n(* Arden's lemma *)\n\nlemma Star_cases:\n  shows \"A\\<star> = {[]} \\<union> A ;; A\\<star>\"\nunfolding Sequ_def\nby (auto) (metis Star.simps)\n\nlemma Star_decomp: \n  assumes \"c # x \\<in> A\\<star>\" \n  shows \"\\<exists>s1 s2. x = s1 @ s2 \\<and> c # s1 \\<in> A \\<and> s2 \\<in> A\\<star>\"\nusing assms\nby (induct x\\<equiv>\"c # x\" rule: Star.induct) \n   (auto simp add: append_eq_Cons_conv)\n\nlemma Star_Der_Sequ: \n  shows \"Der c (A\\<star>) \\<subseteq> (Der c A) ;; A\\<star>\"\nunfolding Der_def Sequ_def\nby(auto simp add: Star_decomp)\n\n\nlemma Der_star [simp]:\n  shows \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\"\nproof -    \n  have \"Der c (A\\<star>) = Der c ({[]} \\<union> A ;; A\\<star>)\"  \n    by (simp only: Star_cases[symmetric])\n  also have \"... = Der c (A ;; A\\<star>)\"\n    by (simp only: Der_union Der_empty) (simp)\n  also have \"... = (Der c A) ;; A\\<star> \\<union> (if [] \\<in> A then Der c (A\\<star>) else {})\"\n    by simp\n  also have \"... =  (Der c A) ;; A\\<star>\"\n    using Star_Der_Sequ by auto\n  finally show \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\" .\nqed\n\nsection {* Power operation for Sets *}\n\nfun \n  Pow :: \"string set \\<Rightarrow> nat \\<Rightarrow> string set\" (\"_ \\<up> _\" [101, 102] 101)\nwhere\n   \"A \\<up> 0 = {[]}\"\n|  \"A \\<up> (Suc n) = A ;; (A \\<up> n)\"\n\nlemma Pow_empty [simp]:\n  shows \"[] \\<in> A \\<up> n \\<longleftrightarrow> (n = 0 \\<or> [] \\<in> A)\"\nby(induct n) (auto simp add: Sequ_def)\n\nlemma Pow_Suc_rev:\n  \"A \\<up> (Suc n) =  (A \\<up> n) ;; A\"\napply(induct n arbitrary: A)\napply(simp_all)\nby (metis Sequ_assoc)\n\n\nlemma Pow_decomp: \n  assumes \"c # x \\<in> A \\<up> n\" \n  shows \"\\<exists>s1 s2. x = s1 @ s2 \\<and> c # s1 \\<in> A \\<and> s2 \\<in> A \\<up> (n - 1)\"\nusing assms\napply(induct n) \napply(auto simp add: Cons_eq_append_conv Sequ_def)\napply(case_tac n)\napply(auto simp add: Sequ_def)\napply(blast)\ndone\n\nlemma Star_Pow:\n  assumes \"s \\<in> A\\<star>\"\n  shows \"\\<exists>n. s \\<in> A \\<up> n\"\nusing assms\napply(induct)\napply(auto)\napply(rule_tac x=\"Suc n\" in exI)\napply(auto simp add: Sequ_def)\ndone\n\nlemma Pow_Star:\n  assumes \"s \\<in> A \\<up> n\"\n  shows \"s \\<in> A\\<star>\"\nusing assms\napply(induct n arbitrary: s)\napply(auto simp add: Sequ_def)\ndone\n\nlemma Der_Pow_0:\n  shows \"Der c (A \\<up> 0) = {}\"\nby(simp add: Der_def)\n\nlemma Der_Pow_Suc:\n  shows \"Der c (A \\<up> (Suc n)) = (Der c A) ;; (A \\<up> n)\"\nunfolding Der_def Sequ_def \napply(auto simp add: Cons_eq_append_conv Sequ_def dest!: Pow_decomp)\napply(case_tac n)\napply(force simp add: Sequ_def)+\ndone\n\nlemma Der_Pow [simp]:\n  shows \"Der c (A \\<up> n) = (if n = 0 then {} else (Der c A) ;; (A \\<up> (n - 1)))\"\napply(case_tac n)\napply(simp_all del: Pow.simps add: Der_Pow_0 Der_Pow_Suc)\ndone\n\nlemma Der_Pow_Sequ [simp]:\n  shows \"Der c (A ;; A \\<up> n) = (Der c A) ;; (A \\<up> n)\"\nby (simp only: Pow.simps[symmetric] Der_Pow) (simp)\n\n\nlemma Pow_Sequ_Un:\n  assumes \"0 < x\"\n  shows \"(\\<Union>n \\<in> {..x}. (A \\<up> n)) = ({[]} \\<union> (\\<Union>n \\<in> {..x - Suc 0}. A ;; (A \\<up> n)))\"\nusing assms\napply(auto simp add: Sequ_def)\napply(smt Pow.elims Sequ_def Suc_le_mono Suc_pred atMost_iff empty_iff insert_iff mem_Collect_eq)\napply(rule_tac x=\"Suc xa\" in bexI)\napply(auto simp add: Sequ_def)\ndone\n\nlemma Pow_Sequ_Un2:\n  assumes \"0 < x\"\n  shows \"(\\<Union>n \\<in> {x..}. (A \\<up> n)) = (\\<Union>n \\<in> {x - Suc 0..}. A ;; (A \\<up> n))\"\nusing assms\napply(auto simp add: Sequ_def)\napply(case_tac n)\napply(auto simp add: Sequ_def)\napply fastforce\napply(case_tac x)\napply(auto)\napply(rule_tac x=\"Suc xa\" in bexI)\napply(auto simp add: Sequ_def)\ndone\n\nsection {* Regular Expressions *}\n\ndatatype rexp =\n  ZERO\n| ONE\n| CHAR char\n| SEQ rexp rexp\n| ALT rexp rexp\n| STAR rexp\n| UPNTIMES rexp nat\n| NTIMES rexp nat\n| FROMNTIMES rexp nat\n| NMTIMES rexp nat nat\n\nsection {* Semantics of Regular Expressions *}\n \nfun\n  L :: \"rexp \\<Rightarrow> string set\"\nwhere\n  \"L (ZERO) = {}\"\n| \"L (ONE) = {[]}\"\n| \"L (CHAR c) = {[c]}\"\n| \"L (SEQ r1 r2) = (L r1) ;; (L r2)\"\n| \"L (ALT r1 r2) = (L r1) \\<union> (L r2)\"\n| \"L (STAR r) = (L r)\\<star>\"\n| \"L (UPNTIMES r n) = (\\<Union>i\\<in>{..n} . (L r) \\<up> i)\"\n| \"L (NTIMES r n) = (L r) \\<up> n\"\n| \"L (FROMNTIMES r n) = (\\<Union>i\\<in>{n..} . (L r) \\<up> i)\"\n| \"L (NMTIMES r n m) = (\\<Union>i\\<in>{n..m} . (L r) \\<up> i)\" \n\nsection {* Nullable, Derivatives *}\n\nfun\n nullable :: \"rexp \\<Rightarrow> bool\"\nwhere\n  \"nullable (ZERO) = False\"\n| \"nullable (ONE) = True\"\n| \"nullable (CHAR c) = False\"\n| \"nullable (ALT r1 r2) = (nullable r1 \\<or> nullable r2)\"\n| \"nullable (SEQ r1 r2) = (nullable r1 \\<and> nullable r2)\"\n| \"nullable (STAR r) = True\"\n| \"nullable (UPNTIMES r n) = True\"\n| \"nullable (NTIMES r n) = (if n = 0 then True else nullable r)\"\n| \"nullable (FROMNTIMES r n) = (if n = 0 then True else nullable r)\"\n| \"nullable (NMTIMES r n m) = (if m < n then False else (if n = 0 then True else nullable r))\"\n\nfun\n der :: \"char \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"der c (ZERO) = ZERO\"\n| \"der c (ONE) = ZERO\"\n| \"der c (CHAR d) = (if c = d then ONE else ZERO)\"\n| \"der c (ALT r1 r2) = ALT (der c r1) (der c r2)\"\n| \"der c (SEQ r1 r2) = \n     (if nullable r1\n      then ALT (SEQ (der c r1) r2) (der c r2)\n      else SEQ (der c r1) r2)\"\n| \"der c (STAR r) = SEQ (der c r) (STAR r)\"\n| \"der c (UPNTIMES r n) = (if n = 0 then ZERO else SEQ (der c r) (UPNTIMES r (n - 1)))\"\n| \"der c (NTIMES r n) = (if n = 0 then ZERO else SEQ (der c r) (NTIMES r (n - 1)))\"\n| \"der c (FROMNTIMES r n) = \n     (if n = 0 \n      then SEQ (der c r) (STAR r)\n      else SEQ (der c r) (FROMNTIMES r (n - 1)))\"\n| \"der c (NMTIMES r n m) = \n     (if m < n then ZERO \n      else (if n = 0 then (if m = 0 then ZERO else \n                           SEQ (der c r) (UPNTIMES r (m - 1))) else \n                           SEQ (der c r) (NMTIMES r (n - 1) (m - 1))))\" \n\nfun \n ders :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"ders [] r = r\"\n| \"ders (c # s) r = ders s (der c r)\"\n\n\nlemma nullable_correctness:\n  shows \"nullable r  \\<longleftrightarrow> [] \\<in> (L r)\"\nby(induct r) (auto simp add: Sequ_def) \n\n\nlemma der_correctness:\n  shows \"L (der c r) = Der c (L r)\"\napply(induct r) \napply(simp add: nullable_correctness del: Der_UNION)\napply(simp add: nullable_correctness del: Der_UNION)\napply(simp add: nullable_correctness del: Der_UNION)\napply(simp add: nullable_correctness del: Der_UNION)\napply(simp add: nullable_correctness del: Der_UNION)\napply(simp add: nullable_correctness del: Der_UNION)\nprefer 2\napply(simp add: nullable_correctness del: Der_UNION)\napply(simp add: nullable_correctness del: Der_UNION)\napply(rule impI)\napply(subst Sequ_Union_in)\napply(subst Der_Pow_Sequ[symmetric])\napply(subst Pow.simps[symmetric])\napply(subst Der_UNION[symmetric])\napply(subst Pow_Sequ_Un)\napply(simp)\napply(simp only: Der_union Der_empty)\n    apply(simp)\n(* FROMNTIMES *)    \n   apply(simp add: nullable_correctness del: Der_UNION)\n  apply(rule conjI)\nprefer 2    \napply(subst Sequ_Union_in)\napply(subst Der_Pow_Sequ[symmetric])\napply(subst Pow.simps[symmetric])\napply(case_tac x2)\nprefer 2\napply(subst Pow_Sequ_Un2)\napply(simp)\napply(simp)\n    apply(auto simp add: Sequ_def Der_def)[1]\n   apply(auto simp add: Sequ_def split: if_splits)[1]\n  using Star_Pow apply fastforce\n  using Pow_Star apply blast\n(* NMTIMES *)    \napply(simp add: nullable_correctness del: Der_UNION)\napply(rule impI)\napply(rule conjI)\napply(rule impI)\napply(subst Sequ_Union_in)\napply(subst Der_Pow_Sequ[symmetric])\napply(subst Pow.simps[symmetric])\napply(subst Der_UNION[symmetric])\napply(case_tac x3a)\napply(simp)\napply(clarify)\napply(auto simp add: Sequ_def Der_def Cons_eq_append_conv)[1]\napply(rule_tac x=\"Suc xa\" in bexI)\napply(auto simp add: Sequ_def)[2]\napply (metis append_Cons)\napply (metis (no_types, hide_lams) Pow_decomp atMost_iff diff_Suc_eq_diff_pred diff_is_0_eq)\napply(rule impI)+\napply(subst Sequ_Union_in)\napply(subst Der_Pow_Sequ[symmetric])\napply(subst Pow.simps[symmetric])\napply(subst Der_UNION[symmetric])\napply(case_tac x2)\napply(simp)\napply(simp del: Pow.simps)\napply(auto simp add: Sequ_def Der_def)\napply (metis One_nat_def Suc_le_D Suc_le_mono atLeastAtMost_iff diff_Suc_1 not_le)\nby fastforce\n\n\n\nlemma ders_correctness:\n  shows \"L (ders s r) = Ders s (L r)\"\nby (induct s arbitrary: r)\n   (simp_all add: Ders_def der_correctness Der_def)\n\n\nsection {* Values *}\n\ndatatype val = \n  Void\n| Char char\n| Seq val val\n| Right val\n| Left val\n| Stars \"val list\"\n\n\nsection {* The string behind a value *}\n\nfun \n  flat :: \"val \\<Rightarrow> string\"\nwhere\n  \"flat (Void) = []\"\n| \"flat (Char c) = [c]\"\n| \"flat (Left v) = flat v\"\n| \"flat (Right v) = flat v\"\n| \"flat (Seq v1 v2) = (flat v1) @ (flat v2)\"\n| \"flat (Stars []) = []\"\n| \"flat (Stars (v#vs)) = (flat v) @ (flat (Stars vs))\" \n\nabbreviation\n  \"flats vs \\<equiv> concat (map flat vs)\"\n\nlemma flat_Stars [simp]:\n \"flat (Stars vs) = flats vs\"\nby (induct vs) (auto)\n\nlemma Star_concat:\n  assumes \"\\<forall>s \\<in> set ss. s \\<in> A\"  \n  shows \"concat ss \\<in> A\\<star>\"\nusing assms by (induct ss) (auto)\n\nlemma Star_cstring:\n  assumes \"s \\<in> A\\<star>\"\n  shows \"\\<exists>ss. concat ss = s \\<and> (\\<forall>s \\<in> set ss. s \\<in> A \\<and> s \\<noteq> [])\"\nusing assms\napply(induct rule: Star.induct)\napply(auto)[1]\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(erule exE)\napply(clarify)\napply(case_tac \"s1 = []\")\napply(rule_tac x=\"ss\" in exI)\napply(simp)\napply(rule_tac x=\"s1#ss\" in exI)\napply(simp)\ndone\n\nlemma Aux:\n  assumes \"\\<forall>s\\<in>set ss. s = []\"\n  shows \"concat ss = []\"\nusing assms\nby (induct ss) (auto)\n\nlemma Pow_cstring_nonempty:\n  assumes \"s \\<in> A \\<up> n\"\n  shows \"\\<exists>ss. concat ss = s \\<and> length ss \\<le> n \\<and> (\\<forall>s \\<in> set ss. s \\<in> A \\<and> s \\<noteq> [])\"\nusing assms\napply(induct n arbitrary: s)\napply(auto)\napply(simp add: Sequ_def)\napply(erule exE)+\napply(clarify)\napply(drule_tac x=\"s2\" in meta_spec)\napply(simp)\napply(clarify)\napply(case_tac \"s1 = []\")\napply(simp)\napply(rule_tac x=\"ss\" in exI)\napply(simp)\napply(rule_tac x=\"s1 # ss\" in exI)\napply(simp)\ndone\n\nlemma Pow_cstring:\n  assumes \"s \\<in> A \\<up> n\"\n  shows \"\\<exists>ss1 ss2. concat (ss1 @ ss2) = s \\<and> length (ss1 @ ss2) = n \\<and> \n         (\\<forall>s \\<in> set ss1. s \\<in> A \\<and> s \\<noteq> []) \\<and> (\\<forall>s \\<in> set ss2. s \\<in> A \\<and> s = [])\"\nusing assms\napply(induct n arbitrary: s)\napply(auto)[1]\napply(simp only: Pow_Suc_rev)\napply(simp add: Sequ_def)\napply(erule exE)+\napply(clarify)\napply(drule_tac x=\"s1\" in meta_spec)\napply(simp)\napply(erule exE)+\napply(clarify)\napply(case_tac \"s2 = []\")\napply(simp)\napply(rule_tac x=\"ss1\" in exI)\napply(rule_tac x=\"s2#ss2\" in exI)\napply(simp)\napply(rule_tac x=\"ss1 @ [s2]\" in exI)\napply(rule_tac x=\"ss2\" in exI)\napply(simp)\napply(subst Aux)\napply(auto)[1]\napply(subst Aux)\napply(auto)[1]\napply(simp)\ndone\n\n\nsection {* Lexical Values *}\n\n\n\ninductive \n  Prf :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<Turnstile> _ : _\" [100, 100] 100)\nwhere\n \"\\<lbrakk>\\<Turnstile> v1 : r1; \\<Turnstile> v2 : r2\\<rbrakk> \\<Longrightarrow> \\<Turnstile>  Seq v1 v2 : SEQ r1 r2\"\n| \"\\<Turnstile> v1 : r1 \\<Longrightarrow> \\<Turnstile> Left v1 : ALT r1 r2\"\n| \"\\<Turnstile> v2 : r2 \\<Longrightarrow> \\<Turnstile> Right v2 : ALT r1 r2\"\n| \"\\<Turnstile> Void : ONE\"\n| \"\\<Turnstile> Char c : CHAR c\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars vs : STAR r\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> []; length vs \\<le> n\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars vs : UPNTIMES r n\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs1. \\<Turnstile> v : r \\<and> flat v \\<noteq> []; \n    \\<forall>v \\<in> set vs2. \\<Turnstile> v : r \\<and> flat v = []; \n    length (vs1 @ vs2) = n\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars (vs1 @ vs2) : NTIMES r n\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs1. \\<Turnstile> v : r  \\<and> flat v \\<noteq> []; \n    \\<forall>v \\<in> set vs2. \\<Turnstile> v : r \\<and> flat v = []; \n    length (vs1 @ vs2) = n\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars (vs1 @ vs2) : FROMNTIMES r n\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs. \\<Turnstile> v : r  \\<and> flat v \\<noteq> []; length vs > n\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars vs : FROMNTIMES r n\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs1. \\<Turnstile> v : r \\<and> flat v \\<noteq> [];\n    \\<forall>v \\<in> set vs2. \\<Turnstile> v : r \\<and> flat v = []; \n    length (vs1 @ vs2) = n; length (vs1 @ vs2) \\<le> m\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars (vs1 @ vs2) : NMTIMES r n m\"\n| \"\\<lbrakk>\\<forall>v \\<in> set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> [];\n    length vs > n; length vs \\<le> m\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars vs : NMTIMES r n m\"\n\n  \ninductive_cases Prf_elims:\n  \"\\<Turnstile> v : ZERO\"\n  \"\\<Turnstile> v : SEQ r1 r2\"\n  \"\\<Turnstile> v : ALT r1 r2\"\n  \"\\<Turnstile> v : ONE\"\n  \"\\<Turnstile> v : CHAR c\"\n  \"\\<Turnstile> vs : STAR r\"\n  \"\\<Turnstile> vs : UPNTIMES r n\"\n  \"\\<Turnstile> vs : NTIMES r n\"\n  \"\\<Turnstile> vs : FROMNTIMES r n\"\n  \"\\<Turnstile> vs : NMTIMES r n m\"\n\nlemma Prf_Stars_appendE:\n  assumes \"\\<Turnstile> Stars (vs1 @ vs2) : STAR r\"\n  shows \"\\<Turnstile> Stars vs1 : STAR r \\<and> \\<Turnstile> Stars vs2 : STAR r\" \nusing assms\nby (auto intro: Prf.intros elim!: Prf_elims)\n\n\n\nlemma flats_empty:\n  assumes \"(\\<forall>v\\<in>set vs. flat v = [])\"\n  shows \"flats vs = []\"\nusing assms\nby(induct vs) (simp_all)\n\nlemma Star_cval:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<Turnstile> v : r\"\n  shows \"\\<exists>vs. flats vs = concat ss \\<and> (\\<forall>v\\<in>set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> [])\"\nusing assms\napply(induct ss)\napply(auto)\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(case_tac \"flat v = []\")\napply(rule_tac x=\"vs\" in exI)\napply(simp)\napply(rule_tac x=\"v#vs\" in exI)\napply(simp)\ndone\n\n\nlemma flats_cval:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<Turnstile> v : r\"\n  shows \"\\<exists>vs1 vs2. flats (vs1 @ vs2) = concat ss \\<and> length (vs1 @ vs2) = length ss \\<and> \n          (\\<forall>v\\<in>set vs1. \\<Turnstile> v : r \\<and> flat v \\<noteq> []) \\<and>\n          (\\<forall>v\\<in>set vs2. \\<Turnstile> v : r \\<and> flat v = [])\"\nusing assms\napply(induct ss rule: rev_induct)\napply(rule_tac x=\"[]\" in exI)+\napply(simp)\napply(simp)\napply(clarify)\napply(case_tac \"flat v = []\")\napply(rule_tac x=\"vs1\" in exI)\napply(rule_tac x=\"v#vs2\" in exI)\napply(simp)\napply(rule_tac x=\"vs1 @ [v]\" in exI)\napply(rule_tac x=\"vs2\" in exI)\napply(simp)\napply(subst (asm) (2) flats_empty)\napply(simp)\napply(simp)\ndone\n\nlemma flats_cval_nonempty:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<Turnstile> v : r\"\n  shows \"\\<exists>vs. flats vs = concat ss \\<and> length vs \\<le> length ss \\<and> \n          (\\<forall>v\\<in>set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> [])\" \nusing assms\napply(induct ss)\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(simp)\napply(clarify)\napply(case_tac \"flat v = []\")\napply(rule_tac x=\"vs\" in exI)\napply(simp)\napply(rule_tac x=\"v # vs\" in exI)\napply(simp)\ndone\n\nlemma Pow_flats:\n  assumes \"\\<forall>v \\<in> set vs. flat v \\<in> A\"\n  shows \"flats vs \\<in> A \\<up> length vs\"\nusing assms\nby(induct vs)(auto simp add: Sequ_def)\n\nlemma Pow_flats_appends:\n  assumes \"\\<forall>v \\<in> set vs1. flat v \\<in> A\" \"\\<forall>v \\<in> set vs2. flat v \\<in> A\"\n  shows \"flats vs1 @ flats vs2 \\<in> A \\<up> (length vs1 + length vs2)\"\nusing assms\napply(induct vs1)\napply(auto simp add: Sequ_def Pow_flats)\ndone\n\nlemma L_flat_Prf1:\n  assumes \"\\<Turnstile> v : r\" \n  shows \"flat v \\<in> L r\"\nusing assms\napply(induct) \napply(auto simp add: Sequ_def Star_concat Pow_flats)\napply(meson Pow_flats atMost_iff)\nusing Pow_flats_appends apply blast\nusing Pow_flats_appends apply blast\napply (meson Pow_flats atLeast_iff less_imp_le)\napply(rule_tac x=\"length vs1 + length vs2\" in  bexI)\napply(meson Pow_flats_appends atLeastAtMost_iff)\napply(simp)\napply(meson Pow_flats atLeastAtMost_iff less_or_eq_imp_le)\ndone\n\nlemma L_flat_Prf2:\n  assumes \"s \\<in> L r\" \n  shows \"\\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\"\nusing assms\nproof(induct r arbitrary: s)\n  case (STAR r s)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (STAR r)\" by fact\n  then obtain ss where \"concat ss = s\" \"\\<forall>s \\<in> set ss. s \\<in> L r \\<and> s \\<noteq> []\"\n  using Star_cstring by auto  \n  then obtain vs where \"flats vs = s\" \"\\<forall>v\\<in>set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\"\n  using IH Star_cval by metis \n  then show \"\\<exists>v. \\<Turnstile> v : STAR r \\<and> flat v = s\"\n  using Prf.intros(6) flat_Stars by blast\nnext \n  case (SEQ r1 r2 s)\n  then show \"\\<exists>v. \\<Turnstile> v : SEQ r1 r2 \\<and> flat v = s\"\n  unfolding Sequ_def L.simps by (fastforce intro: Prf.intros)\nnext\n  case (ALT r1 r2 s)\n  then show \"\\<exists>v. \\<Turnstile> v : ALT r1 r2 \\<and> flat v = s\"\n  unfolding L.simps by (fastforce intro: Prf.intros)\nnext\n  case (NTIMES r n)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (NTIMES r n)\" by fact\n  then obtain ss1 ss2 where \"concat (ss1 @ ss2) = s\" \"length (ss1 @ ss2) = n\" \n    \"\\<forall>s \\<in> set ss1. s \\<in> L r \\<and> s \\<noteq> []\" \"\\<forall>s \\<in> set ss2. s \\<in> L r \\<and> s = []\"\n  using Pow_cstring by force\n  then obtain vs1 vs2 where \"flats (vs1 @ vs2) = s\" \"length (vs1 @ vs2) = n\" \n      \"\\<forall>v\\<in>set vs1. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\" \"\\<forall>v\\<in>set vs2. \\<Turnstile> v : r \\<and> flat v = []\"\n  using IH flats_cval \n  apply -\n  apply(drule_tac x=\"ss1 @ ss2\" in meta_spec)\n  apply(drule_tac x=\"r\" in meta_spec)\n  apply(drule meta_mp)\n  apply(simp)\n  apply (metis Un_iff)\n  apply(clarify)\n  apply(drule_tac x=\"vs1\" in meta_spec)\n  apply(drule_tac x=\"vs2\" in meta_spec)\n  apply(simp)\n  done\n  then show \"\\<exists>v. \\<Turnstile> v : NTIMES r n \\<and> flat v = s\"\n  using Prf.intros(8) flat_Stars by blast\nnext \n  case (FROMNTIMES r n)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (FROMNTIMES r n)\" by fact \n  then obtain ss1 ss2 k where \"concat (ss1 @ ss2) = s\" \"length (ss1 @ ss2) = k\"  \"n \\<le> k\"\n    \"\\<forall>s \\<in> set ss1. s \\<in> L r \\<and> s \\<noteq> []\" \"\\<forall>s \\<in> set ss2. s \\<in> L r \\<and> s = []\"\n    using Pow_cstring by force \n  then obtain vs1 vs2 where \"flats (vs1 @ vs2) = s\" \"length (vs1 @ vs2) = k\" \"n \\<le> k\"\n      \"\\<forall>v\\<in>set vs1. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\" \"\\<forall>v\\<in>set vs2. \\<Turnstile> v : r \\<and> flat v = []\"\n  using IH flats_cval \n  apply -\n  apply(drule_tac x=\"ss1 @ ss2\" in meta_spec)\n  apply(drule_tac x=\"r\" in meta_spec)\n  apply(drule meta_mp)\n  apply(simp)\n  apply (metis Un_iff)\n  apply(clarify)\n  apply(drule_tac x=\"vs1\" in meta_spec)\n  apply(drule_tac x=\"vs2\" in meta_spec)\n  apply(simp)\n  done\n  then show \"\\<exists>v. \\<Turnstile> v : FROMNTIMES r n \\<and> flat v = s\"\n  apply(case_tac \"length vs1 \\<le> n\")\n  apply(rule_tac x=\"Stars (vs1 @ take (n - length vs1) vs2)\" in exI)\n  apply(simp)\n  apply(subgoal_tac \"flats (take (n - length vs1) vs2) = []\")\n  prefer 2\n  apply (meson flats_empty in_set_takeD)\n  apply(clarify)\n    apply(rule conjI)\n      apply(rule Prf.intros)\n        apply(simp)\n       apply (meson in_set_takeD)\n      apply(simp)\n     apply(simp)\n     apply (simp add: flats_empty)\n      apply(rule_tac x=\"Stars vs1\" in exI)\n  apply(simp)\n    apply(rule conjI)\n     apply(rule Prf.intros(10))\n      apply(auto)\n  done    \nnext \n  case (NMTIMES r n m)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (NMTIMES r n m)\" by fact \n  then obtain ss1 ss2 k where \"concat (ss1 @ ss2) = s\" \"length (ss1 @ ss2) = k\" \"n \\<le> k\" \"k \\<le> m\" \n    \"\\<forall>s \\<in> set ss1. s \\<in> L r \\<and> s \\<noteq> []\" \"\\<forall>s \\<in> set ss2. s \\<in> L r \\<and> s = []\"\n  using Pow_cstring by (auto, blast)\n  then obtain vs1 vs2 where \"flats (vs1 @ vs2) = s\" \"length (vs1 @ vs2) = k\" \"n \\<le> k\" \"k \\<le> m\"\n      \"\\<forall>v\\<in>set vs1. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\" \"\\<forall>v\\<in>set vs2. \\<Turnstile> v : r \\<and> flat v = []\"\n  using IH flats_cval \n  apply -\n  apply(drule_tac x=\"ss1 @ ss2\" in meta_spec)\n  apply(drule_tac x=\"r\" in meta_spec)\n  apply(drule meta_mp)\n  apply(simp)\n  apply (metis Un_iff)\n  apply(clarify)\n  apply(drule_tac x=\"vs1\" in meta_spec)\n  apply(drule_tac x=\"vs2\" in meta_spec)\n  apply(simp)\n  done\n  then show \"\\<exists>v. \\<Turnstile> v : NMTIMES r n m \\<and> flat v = s\"\n    apply(case_tac \"length vs1 \\<le> n\")\n  apply(rule_tac x=\"Stars (vs1 @ take (n - length vs1) vs2)\" in exI)\n  apply(simp)\n  apply(subgoal_tac \"flats (take (n - length vs1) vs2) = []\")\n  prefer 2\n  apply (meson flats_empty in_set_takeD)\n  apply(clarify)\n    apply(rule conjI)\n      apply(rule Prf.intros)\n        apply(simp)\n       apply (meson in_set_takeD)\n      apply(simp)\n     apply(simp)\n     apply (simp add: flats_empty)\n      apply(rule_tac x=\"Stars vs1\" in exI)\n  apply(simp)\n    apply(rule conjI)\n     apply(rule Prf.intros)\n      apply(auto)\n  done    \nnext \n  case (UPNTIMES r n s)\n  have IH: \"\\<And>s. s \\<in> L r \\<Longrightarrow> \\<exists>v. \\<Turnstile> v : r \\<and> flat v = s\" by fact\n  have \"s \\<in> L (UPNTIMES r n)\" by fact\n  then obtain ss where \"concat ss = s\" \"\\<forall>s \\<in> set ss. s \\<in> L r \\<and> s \\<noteq> []\" \"length ss \\<le> n\"\n  using Pow_cstring_nonempty by force\n  then obtain vs where \"flats vs = s\" \"\\<forall>v\\<in>set vs. \\<Turnstile> v : r \\<and> flat v \\<noteq> []\" \"length vs \\<le> n\"\n  using IH flats_cval_nonempty by (smt order.trans) \n  then show \"\\<exists>v. \\<Turnstile> v : UPNTIMES r n \\<and> flat v = s\"\n  using Prf.intros(7) flat_Stars by blast\nqed (auto intro: Prf.intros)\n\n\nlemma L_flat_Prf:\n  shows \"L(r) = {flat v | v. \\<Turnstile> v : r}\"\nusing L_flat_Prf1 L_flat_Prf2 by blast\n\n\n\nsection {* Sets of Lexical Values *}\n\ntext {*\n  Shows that lexical values are finite for a given regex and string.\n*}\n\ndefinition\n  LV :: \"rexp \\<Rightarrow> string \\<Rightarrow> val set\"\nwhere  \"LV r s \\<equiv> {v. \\<Turnstile> v : r \\<and> flat v = s}\"\n\nlemma LV_simps:\n  shows \"LV ZERO s = {}\"\n  and   \"LV ONE s = (if s = [] then {Void} else {})\"\n  and   \"LV (CHAR c) s = (if s = [c] then {Char c} else {})\"\n  and   \"LV (ALT r1 r2) s = Left ` LV r1 s \\<union> Right ` LV r2 s\"\nunfolding LV_def\napply(auto intro: Prf.intros elim: Prf.cases)\ndone\n\nabbreviation\n  \"Prefixes s \\<equiv> {s'. prefix s' s}\"\n\nabbreviation\n  \"Suffixes s \\<equiv> {s'. suffix s' s}\"\n\nabbreviation\n  \"SSuffixes s \\<equiv> {s'. strict_suffix s' s}\"\n\nlemma Suffixes_cons [simp]:\n  shows \"Suffixes (c # s) = Suffixes s \\<union> {c # s}\"\nby (auto simp add: suffix_def Cons_eq_append_conv)\n\n\nlemma finite_Suffixes: \n  shows \"finite (Suffixes s)\"\nby (induct s) (simp_all)\n\nlemma finite_SSuffixes: \n  shows \"finite (SSuffixes s)\"\nproof -\n  have \"SSuffixes s \\<subseteq> Suffixes s\"\n   unfolding suffix_def strict_suffix_def by auto\n  then show \"finite (SSuffixes s)\"\n   using finite_Suffixes finite_subset by blast\nqed\n\nlemma finite_Prefixes: \n  shows \"finite (Prefixes s)\"\nproof -\n  have \"finite (Suffixes (rev s))\" \n    by (rule finite_Suffixes)\n  then have \"finite (rev ` Suffixes (rev s))\" by simp\n  moreover\n  have \"rev ` (Suffixes (rev s)) = Prefixes s\"\n  unfolding suffix_def prefix_def image_def\n   by (auto)(metis rev_append rev_rev_ident)+\n  ultimately show \"finite (Prefixes s)\" by simp\nqed\n\ndefinition\n  \"Stars_Cons V Vs \\<equiv> {Stars (v # vs) | v vs. v \\<in> V \\<and> Stars vs \\<in> Vs}\"\n  \ndefinition\n  \"Stars_Append Vs1 Vs2 \\<equiv> {Stars (vs1 @ vs2) | vs1 vs2. Stars vs1 \\<in> Vs1 \\<and> Stars vs2 \\<in> Vs2}\"\n\nfun Stars_Pow :: \"val set \\<Rightarrow> nat \\<Rightarrow> val set\"\nwhere  \n  \"Stars_Pow Vs 0 = {Stars []}\"\n| \"Stars_Pow Vs (Suc n) = Stars_Cons Vs (Stars_Pow Vs n)\"\n  \nlemma finite_Stars_Cons:\n  assumes \"finite V\" \"finite Vs\"\n  shows \"finite (Stars_Cons V Vs)\"\n  using assms  \nproof -\n  from assms(2) have \"finite (Stars -` Vs)\"\n    by(simp add: finite_vimageI inj_on_def) \n  with assms(1) have \"finite (V \\<times> (Stars -` Vs))\"\n    by(simp)\n  then have \"finite ((\\<lambda>(v, vs). Stars (v # vs)) ` (V \\<times> (Stars -` Vs)))\"\n    by simp\n  moreover have \"Stars_Cons V Vs = (\\<lambda>(v, vs). Stars (v # vs)) ` (V \\<times> (Stars -` Vs))\"\n    unfolding Stars_Cons_def by auto    \n  ultimately show \"finite (Stars_Cons V Vs)\"   \n    by simp\nqed\n\nlemma finite_Stars_Append:\n  assumes \"finite Vs1\" \"finite Vs2\"\n  shows \"finite (Stars_Append Vs1 Vs2)\"\n  using assms  \nproof -\n  define UVs1 where \"UVs1 \\<equiv> Stars -` Vs1\"\n  define UVs2 where \"UVs2 \\<equiv> Stars -` Vs2\"  \n  from assms have \"finite UVs1\" \"finite UVs2\"\n    unfolding UVs1_def UVs2_def\n    by(simp_all add: finite_vimageI inj_on_def) \n  then have \"finite ((\\<lambda>(vs1, vs2). Stars (vs1 @ vs2)) ` (UVs1 \\<times> UVs2))\"\n    by simp\n  moreover \n    have \"Stars_Append Vs1 Vs2 = (\\<lambda>(vs1, vs2). Stars (vs1 @ vs2)) ` (UVs1 \\<times> UVs2)\"\n    unfolding Stars_Append_def UVs1_def UVs2_def by auto    \n  ultimately show \"finite (Stars_Append Vs1 Vs2)\"   \n    by simp\nqed \n \nlemma finite_Stars_Pow:\n  assumes \"finite Vs\"\n  shows \"finite (Stars_Pow Vs n)\"    \nby (induct n) (simp_all add: finite_Stars_Cons assms)\n    \nlemma LV_STAR_finite:\n  assumes \"\\<forall>s. finite (LV r s)\"\n  shows \"finite (LV (STAR r) s)\"\nproof(induct s rule: length_induct)\n  fix s::\"char list\"\n  assume \"\\<forall>s'. length s' < length s \\<longrightarrow> finite (LV (STAR r) s')\"\n  then have IH: \"\\<forall>s' \\<in> SSuffixes s. finite (LV (STAR r) s')\"\n    apply(auto simp add: strict_suffix_def suffix_def)\n    by force    \n  define f where \"f \\<equiv> \\<lambda>(v, vs). Stars (v # vs)\"\n  define S1 where \"S1 \\<equiv> \\<Union>s' \\<in> Prefixes s. LV r s'\"\n  define S2 where \"S2 \\<equiv> \\<Union>s2 \\<in> SSuffixes s. LV (STAR r) s2\"\n  have \"finite S1\" using assms\n    unfolding S1_def by (simp_all add: finite_Prefixes)\n  moreover \n  with IH have \"finite S2\" unfolding S2_def\n    by (auto simp add: finite_SSuffixes)\n  ultimately \n  have \"finite ({Stars []} \\<union> Stars_Cons S1 S2)\" \n    by (simp add: finite_Stars_Cons)\n  moreover \n  have \"LV (STAR r) s \\<subseteq> {Stars []} \\<union> (Stars_Cons S1 S2)\" \n  unfolding S1_def S2_def f_def LV_def Stars_Cons_def\n  unfolding prefix_def strict_suffix_def \n  unfolding image_def\n  apply(auto)\n  apply(case_tac x)\n  apply(auto elim: Prf_elims)\n  apply(erule Prf_elims)\n  apply(auto)\n  apply(case_tac vs)\n  apply(auto intro: Prf.intros)  \n  apply(rule exI)\n  apply(rule conjI)\n  apply(rule_tac x=\"flats list\" in exI)\n   apply(rule conjI)\n  apply(simp add: suffix_def)\n  apply(blast)\n  using Prf.intros(6) flat_Stars by blast  \n  ultimately\n  show \"finite (LV (STAR r) s)\" by (simp add: finite_subset)\nqed  \n    \nlemma LV_UPNTIMES_STAR:\n  \"LV (UPNTIMES r n) s \\<subseteq> LV (STAR r) s\"\nby(auto simp add: LV_def intro: Prf.intros elim: Prf_elims)\n\nlemma LV_NTIMES_3:\n  shows \"LV (NTIMES r (Suc n)) [] = (\\<lambda>(v,vs). Stars (v#vs)) ` (LV r [] \\<times> (Stars -` (LV (NTIMES r n) [])))\"\nunfolding LV_def\napply(auto elim!: Prf_elims simp add: image_def)\napply(case_tac vs1)\napply(auto)\napply(case_tac vs2)\napply(auto)\napply(subst append.simps(1)[symmetric])\napply(rule Prf.intros)\napply(auto)\napply(subst append.simps(1)[symmetric])\napply(rule Prf.intros)\napply(auto)\n  done \n    \nlemma LV_FROMNTIMES_3:\n  shows \"LV (FROMNTIMES r (Suc n)) [] = \n    (\\<lambda>(v,vs). Stars (v#vs)) ` (LV r [] \\<times> (Stars -` (LV (FROMNTIMES r n) [])))\"\nunfolding LV_def\napply(auto elim!: Prf_elims simp add: image_def)\napply(case_tac vs1)\napply(auto)\napply(case_tac vs2)\napply(auto)\napply(subst append.simps(1)[symmetric])\napply(rule Prf.intros)\n     apply(auto)\n  apply (metis le_imp_less_Suc length_greater_0_conv less_antisym list.exhaust list.set_intros(1) not_less_eq zero_le)\n  prefer 2\n  using nth_mem apply blast\n  apply(case_tac vs1)\n  apply (smt Groups.add_ac(2) Prf.intros(9) add.right_neutral add_Suc_right append.simps(1) insert_iff length_append list.set(2) list.size(3) list.size(4))\n    apply(auto)\ndone     \n  \nlemma LV_NTIMES_4:\n \"LV (NTIMES r n) [] = Stars_Pow (LV r []) n\" \n  apply(induct n)\n   apply(simp add: LV_def)    \n   apply(auto elim!: Prf_elims simp add: image_def)[1]\n   apply(subst append.simps[symmetric])\n    apply(rule Prf.intros)\n      apply(simp_all)\n    apply(simp add: LV_NTIMES_3 image_def Stars_Cons_def)\n  apply blast\n done   \n\nlemma LV_NTIMES_5:\n  \"LV (NTIMES r n) s \\<subseteq> Stars_Append (LV (STAR r) s) (\\<Union>i\\<le>n. LV (NTIMES r i) [])\"\napply(auto simp add: LV_def)\napply(auto elim!: Prf_elims)\n  apply(auto simp add: Stars_Append_def)\n  apply(rule_tac x=\"vs1\" in exI)\n  apply(rule_tac x=\"vs2\" in exI)  \n  apply(auto)\n    using Prf.intros(6) apply(auto)\n      apply(rule_tac x=\"length vs2\" in bexI)\n    thm Prf.intros\n      apply(subst append.simps(1)[symmetric])\n    apply(rule Prf.intros)\n      apply(auto)[1]\n      apply(auto)[1]\n     apply(simp)\n    apply(simp)\n      done\n      \nlemma ttty:\n \"LV (FROMNTIMES r n) [] = Stars_Pow (LV r []) n\" \n  apply(induct n)\n   apply(simp add: LV_def)    \n   apply(auto elim: Prf_elims simp add: image_def)[1]\n   prefer 2\n    apply(subst append.simps[symmetric])\n    apply(rule Prf.intros)\n      apply(simp_all)\n   apply(erule Prf_elims) \n    apply(case_tac vs1)\n     apply(simp)\n    apply(simp)\n   apply(case_tac x)\n    apply(simp_all)\n    apply(simp add: LV_FROMNTIMES_3 image_def Stars_Cons_def)\n  apply blast\n done     \n\nlemma LV_FROMNTIMES_5:\n  \"LV (FROMNTIMES r n) s \\<subseteq> Stars_Append (LV (STAR r) s) (\\<Union>i\\<le>n. LV (FROMNTIMES r i) [])\"\napply(auto simp add: LV_def)\napply(auto elim!: Prf_elims)\n  apply(auto simp add: Stars_Append_def)\n  apply(rule_tac x=\"vs1\" in exI)\n  apply(rule_tac x=\"vs2\" in exI)  \n  apply(auto)\n    using Prf.intros(6) apply(auto)\n      apply(rule_tac x=\"length vs2\" in bexI)\n    thm Prf.intros\n      apply(subst append.simps(1)[symmetric])\n    apply(rule Prf.intros)\n      apply(auto)[1]\n      apply(auto)[1]\n     apply(simp)\n     apply(simp)\n      apply(rule_tac x=\"vs\" in exI)\n    apply(rule_tac x=\"[]\" in exI) \n    apply(auto)\n    by (metis Prf.intros(9) append_Nil atMost_iff empty_iff le_imp_less_Suc less_antisym list.set(1) nth_mem zero_le)\n\nlemma LV_FROMNTIMES_6:\n  assumes \"\\<forall>s. finite (LV r s)\"\n  shows \"finite (LV (FROMNTIMES r n) s)\"\n  apply(rule finite_subset)\n   apply(rule LV_FROMNTIMES_5)\n  apply(rule finite_Stars_Append)\n    apply(rule LV_STAR_finite)\n   apply(rule assms)\n  apply(rule finite_UN_I)\n   apply(auto)\n  by (simp add: assms finite_Stars_Pow ttty)\n    \nlemma LV_NMTIMES_5:\n  \"LV (NMTIMES r n m) s \\<subseteq> Stars_Append (LV (STAR r) s) (\\<Union>i\\<le>n. LV (FROMNTIMES r i) [])\"\napply(auto simp add: LV_def)\napply(auto elim!: Prf_elims)\n  apply(auto simp add: Stars_Append_def)\n  apply(rule_tac x=\"vs1\" in exI)\n  apply(rule_tac x=\"vs2\" in exI)  \n  apply(auto)\n    using Prf.intros(6) apply(auto)\n      apply(rule_tac x=\"length vs2\" in bexI)\n    thm Prf.intros\n      apply(subst append.simps(1)[symmetric])\n    apply(rule Prf.intros)\n      apply(auto)[1]\n      apply(auto)[1]\n     apply(simp)\n     apply(simp)\n      apply(rule_tac x=\"vs\" in exI)\n    apply(rule_tac x=\"[]\" in exI) \n    apply(auto)\n    by (metis Prf.intros(9) append_Nil atMost_iff empty_iff le_imp_less_Suc less_antisym list.set(1) nth_mem zero_le)\n\nlemma LV_NMTIMES_6:\n  assumes \"\\<forall>s. finite (LV r s)\"\n  shows \"finite (LV (NMTIMES r n m) s)\"\n  apply(rule finite_subset)\n   apply(rule LV_NMTIMES_5)\n  apply(rule finite_Stars_Append)\n    apply(rule LV_STAR_finite)\n   apply(rule assms)\n  apply(rule finite_UN_I)\n   apply(auto)\n  by (simp add: assms finite_Stars_Pow ttty)\n        \n    \nlemma LV_finite:\n  shows \"finite (LV r s)\"\nproof(induct r arbitrary: s)\n  case (ZERO s) \n  show \"finite (LV ZERO s)\" by (simp add: LV_simps)\nnext\n  case (ONE s)\n  show \"finite (LV ONE s)\" by (simp add: LV_simps)\nnext\n  case (CHAR c s)\n  show \"finite (LV (CHAR c) s)\" by (simp add: LV_simps)\nnext \n  case (ALT r1 r2 s)\n  then show \"finite (LV (ALT r1 r2) s)\" by (simp add: LV_simps)\nnext \n  case (SEQ r1 r2 s)\n  define f where \"f \\<equiv> \\<lambda>(v1, v2). Seq v1 v2\"\n  define S1 where \"S1 \\<equiv> \\<Union>s' \\<in> Prefixes s. LV r1 s'\"\n  define S2 where \"S2 \\<equiv> \\<Union>s' \\<in> Suffixes s. LV r2 s'\"\n  have IHs: \"\\<And>s. finite (LV r1 s)\" \"\\<And>s. finite (LV r2 s)\" by fact+\n  then have \"finite S1\" \"finite S2\" unfolding S1_def S2_def\n    by (simp_all add: finite_Prefixes finite_Suffixes)\n  moreover\n  have \"LV (SEQ r1 r2) s \\<subseteq> f ` (S1 \\<times> S2)\"\n    unfolding f_def S1_def S2_def \n    unfolding LV_def image_def prefix_def suffix_def\n    apply (auto elim!: Prf_elims)\n    by (metis (mono_tags, lifting) mem_Collect_eq)\n  ultimately \n  show \"finite (LV (SEQ r1 r2) s)\"\n    by (simp add: finite_subset)\nnext\n  case (STAR r s)\n  then show \"finite (LV (STAR r) s)\" by (simp add: LV_STAR_finite)\nnext \n  case (UPNTIMES r n s)\n  have \"\\<And>s. finite (LV r s)\" by fact\n  then show \"finite (LV (UPNTIMES r n) s)\"\n  by (meson LV_STAR_finite LV_UPNTIMES_STAR rev_finite_subset)\nnext \n  case (FROMNTIMES r n s)\n  have \"\\<And>s. finite (LV r s)\" by fact\n  then show \"finite (LV (FROMNTIMES r n) s)\"\n    by (simp add: LV_FROMNTIMES_6)\nnext \n  case (NTIMES r n s)\n  have \"\\<And>s. finite (LV r s)\" by fact\n  then show \"finite (LV (NTIMES r n) s)\"\n    by (metis (no_types, lifting) LV_NTIMES_4 LV_NTIMES_5 LV_STAR_finite finite_Stars_Append finite_Stars_Pow finite_UN_I finite_atMost finite_subset)\nnext\n  case (NMTIMES r n m s)\n  have \"\\<And>s. finite (LV r s)\" by fact\n  then show \"finite (LV (NMTIMES r n m) s)\"\n    by (simp add: LV_NMTIMES_6)         \nqed\n\n\n\nsection {* Our POSIX Definition *}\n\ninductive \n  Posix :: \"string \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ \\<in> _ \\<rightarrow> _\" [100, 100, 100] 100)\nwhere\n  Posix_ONE: \"[] \\<in> ONE \\<rightarrow> Void\"\n| Posix_CHAR: \"[c] \\<in> (CHAR c) \\<rightarrow> (Char c)\"\n| Posix_ALT1: \"s \\<in> r1 \\<rightarrow> v \\<Longrightarrow> s \\<in> (ALT r1 r2) \\<rightarrow> (Left v)\"\n| Posix_ALT2: \"\\<lbrakk>s \\<in> r2 \\<rightarrow> v; s \\<notin> L(r1)\\<rbrakk> \\<Longrightarrow> s \\<in> (ALT r1 r2) \\<rightarrow> (Right v)\"\n| Posix_SEQ: \"\\<lbrakk>s1 \\<in> r1 \\<rightarrow> v1; s2 \\<in> r2 \\<rightarrow> v2;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\\<rbrakk> \\<Longrightarrow> \n    (s1 @ s2) \\<in> (SEQ r1 r2) \\<rightarrow> (Seq v1 v2)\"\n| Posix_STAR1: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> STAR r \\<rightarrow> Stars vs; flat v \\<noteq> [];\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> STAR r \\<rightarrow> Stars (v # vs)\"\n| Posix_STAR2: \"[] \\<in> STAR r \\<rightarrow> Stars []\"\n| Posix_NTIMES1: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> NTIMES r (n - 1) \\<rightarrow> Stars vs; flat v \\<noteq> []; 0 < n;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (NTIMES r (n - 1)))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> NTIMES r n \\<rightarrow> Stars (v # vs)\"\n| Posix_NTIMES2: \"\\<lbrakk>\\<forall>v \\<in> set vs. [] \\<in> r \\<rightarrow> v; length vs = n\\<rbrakk>\n    \\<Longrightarrow> [] \\<in> NTIMES r n \\<rightarrow> Stars vs\"  \n| Posix_UPNTIMES1: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> UPNTIMES r (n - 1) \\<rightarrow> Stars vs; flat v \\<noteq> []; 0 < n;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (UPNTIMES r (n - 1)))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> UPNTIMES r n \\<rightarrow> Stars (v # vs)\"\n| Posix_UPNTIMES2: \"[] \\<in> UPNTIMES r n \\<rightarrow> Stars []\"\n| Posix_FROMNTIMES2: \"\\<lbrakk>\\<forall>v \\<in> set vs. [] \\<in> r \\<rightarrow> v; length vs = n\\<rbrakk>\n    \\<Longrightarrow> [] \\<in> FROMNTIMES r n \\<rightarrow> Stars vs\"\n| Posix_FROMNTIMES1: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> FROMNTIMES r (n - 1) \\<rightarrow> Stars vs; flat v \\<noteq> []; 0 < n;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (FROMNTIMES r (n - 1)))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> FROMNTIMES r n \\<rightarrow> Stars (v # vs)\"  \n| Posix_FROMNTIMES3: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> STAR r \\<rightarrow> Stars vs; flat v \\<noteq> [];\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> FROMNTIMES r 0 \\<rightarrow> Stars (v # vs)\"  \n| Posix_NMTIMES2: \"\\<lbrakk>\\<forall>v \\<in> set vs. [] \\<in> r \\<rightarrow> v; length vs = n; n \\<le> m\\<rbrakk>\n    \\<Longrightarrow> [] \\<in> NMTIMES r n m \\<rightarrow> Stars vs\"  \n| Posix_NMTIMES1: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> NMTIMES r (n - 1) (m - 1) \\<rightarrow> Stars vs; flat v \\<noteq> []; 0 < n; n \\<le> m;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (NMTIMES r (n - 1) (m - 1)))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> NMTIMES r n m \\<rightarrow> Stars (v # vs)\"  \n| Posix_NMTIMES3: \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> UPNTIMES r (m - 1) \\<rightarrow> Stars vs; flat v \\<noteq> []; 0 < m;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (UPNTIMES r (m - 1)))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> NMTIMES r 0 m \\<rightarrow> Stars (v # vs)\"    \n  \ninductive_cases Posix_elims:\n  \"s \\<in> ZERO \\<rightarrow> v\"\n  \"s \\<in> ONE \\<rightarrow> v\"\n  \"s \\<in> CHAR c \\<rightarrow> v\"\n  \"s \\<in> ALT r1 r2 \\<rightarrow> v\"\n  \"s \\<in> SEQ r1 r2 \\<rightarrow> v\"\n  \"s \\<in> STAR r \\<rightarrow> v\"\n  \"s \\<in> NTIMES r n \\<rightarrow> v\"\n  \"s \\<in> UPNTIMES r n \\<rightarrow> v\"\n  \"s \\<in> FROMNTIMES r n \\<rightarrow> v\"\n  \"s \\<in> NMTIMES r n m \\<rightarrow> v\"\n  \nlemma Posix1:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"s \\<in> L r\" \"flat v = s\"\nusing assms\n  apply(induct s r v rule: Posix.induct)\n                    apply(auto simp add: Sequ_def)[18]\n            apply(case_tac n)\n             apply(simp)\n  apply(simp add: Sequ_def)\n            apply(auto)[1]\n           apply(simp)\n  apply(clarify)\n  apply(rule_tac x=\"Suc x\" in bexI)\n  apply(simp add: Sequ_def)\n            apply(auto)[5]\n  using nth_mem nullable.simps(9) nullable_correctness apply auto[1]\n  apply simp\n       apply(simp)\n       apply(clarify)\n       apply(rule_tac x=\"Suc x\" in bexI)\n        apply(simp add: Sequ_def)\n          apply(auto)[3]\n    defer\n     apply(simp)\n  apply fastforce\n    apply(simp)\n   apply(simp)\n    apply(clarify)\n   apply(rule_tac x=\"Suc x\" in bexI)\n    apply(auto simp add: Sequ_def)[2]\n   apply(simp)\n    apply(simp)\n    apply(clarify)\n     apply(rule_tac x=\"Suc x\" in bexI)\n    apply(auto simp add: Sequ_def)[2]\n   apply(simp)\n  apply(simp add: Star.step Star_Pow)\ndone  \n    \ntext {*\n  Our Posix definition determines a unique value.\n*}\n  \nlemma List_eq_zipI:\n  assumes \"\\<forall>(v1, v2) \\<in> set (zip vs1 vs2). v1 = v2\" \n  and \"length vs1 = length vs2\"\n  shows \"vs1 = vs2\"  \n using assms\n  apply(induct vs1 arbitrary: vs2)\n   apply(case_tac vs2)\n   apply(simp)    \n   apply(simp)\n   apply(case_tac vs2)\n   apply(simp)\n  apply(simp)\ndone    \n\nlemma Posix_determ:\n  assumes \"s \\<in> r \\<rightarrow> v1\" \"s \\<in> r \\<rightarrow> v2\"\n  shows \"v1 = v2\"\nusing assms\nproof (induct s r v1 arbitrary: v2 rule: Posix.induct)\n  case (Posix_ONE v2)\n  have \"[] \\<in> ONE \\<rightarrow> v2\" by fact\n  then show \"Void = v2\" by cases auto\nnext \n  case (Posix_CHAR c v2)\n  have \"[c] \\<in> CHAR c \\<rightarrow> v2\" by fact\n  then show \"Char c = v2\" by cases auto\nnext \n  case (Posix_ALT1 s r1 v r2 v2)\n  have \"s \\<in> ALT r1 r2 \\<rightarrow> v2\" by fact\n  moreover\n  have \"s \\<in> r1 \\<rightarrow> v\" by fact\n  then have \"s \\<in> L r1\" by (simp add: Posix1)\n  ultimately obtain v' where eq: \"v2 = Left v'\" \"s \\<in> r1 \\<rightarrow> v'\" by cases auto \n  moreover\n  have IH: \"\\<And>v2. s \\<in> r1 \\<rightarrow> v2 \\<Longrightarrow> v = v2\" by fact\n  ultimately have \"v = v'\" by simp\n  then show \"Left v = v2\" using eq by simp\nnext \n  case (Posix_ALT2 s r2 v r1 v2)\n  have \"s \\<in> ALT r1 r2 \\<rightarrow> v2\" by fact\n  moreover\n  have \"s \\<notin> L r1\" by fact\n  ultimately obtain v' where eq: \"v2 = Right v'\" \"s \\<in> r2 \\<rightarrow> v'\" \n    by cases (auto simp add: Posix1) \n  moreover\n  have IH: \"\\<And>v2. s \\<in> r2 \\<rightarrow> v2 \\<Longrightarrow> v = v2\" by fact\n  ultimately have \"v = v'\" by simp\n  then show \"Right v = v2\" using eq by simp\nnext\n  case (Posix_SEQ s1 r1 v1 s2 r2 v2 v')\n  have \"(s1 @ s2) \\<in> SEQ r1 r2 \\<rightarrow> v'\" \n       \"s1 \\<in> r1 \\<rightarrow> v1\" \"s2 \\<in> r2 \\<rightarrow> v2\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\" by fact+\n  then obtain v1' v2' where \"v' = Seq v1' v2'\" \"s1 \\<in> r1 \\<rightarrow> v1'\" \"s2 \\<in> r2 \\<rightarrow> v2'\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n  using Posix1(1) by fastforce+\n  moreover\n  have IHs: \"\\<And>v1'. s1 \\<in> r1 \\<rightarrow> v1' \\<Longrightarrow> v1 = v1'\"\n            \"\\<And>v2'. s2 \\<in> r2 \\<rightarrow> v2' \\<Longrightarrow> v2 = v2'\" by fact+\n  ultimately show \"Seq v1 v2 = v'\" by simp\nnext\n  case (Posix_STAR1 s1 r v s2 vs v2)\n  have \"(s1 @ s2) \\<in> STAR r \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> STAR r \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (STAR r) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n  using Posix1(1) apply fastforce\n  apply (metis Posix1(1) Posix_STAR1.hyps(6) append_Nil append_Nil2)\n  using Posix1(2) by blast\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> STAR r \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto\nnext\n  case (Posix_STAR2 r v2)\n  have \"[] \\<in> STAR r \\<rightarrow> v2\" by fact\n  then show \"Stars [] = v2\" by cases (auto simp add: Posix1)\nnext\n  case (Posix_NTIMES2 vs r n v2)\n  then show \"Stars vs = v2\"\n    apply(erule_tac Posix_elims)\n     apply(auto)\n     apply (simp add: Posix1(2))\n    apply(rule List_eq_zipI)\n     apply(auto)\n    by (meson in_set_zipE)\nnext\n  case (Posix_NTIMES1 s1 r v s2 n vs v2)\n  have \"(s1 @ s2) \\<in> NTIMES r n \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> NTIMES r (n - 1) \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (NTIMES r (n - 1 )))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (NTIMES r (n - 1)) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n    using Posix1(1) apply fastforce\n    apply (metis One_nat_def Posix1(1) Posix_NTIMES1.hyps(7) append.right_neutral append_self_conv2)\n  using Posix1(2) by blast\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> NTIMES r (n - 1) \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto\nnext\n  case (Posix_UPNTIMES1 s1 r v s2 n vs v2)\n  have \"(s1 @ s2) \\<in> UPNTIMES r n \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> UPNTIMES r (n - 1) \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (UPNTIMES r (n - 1 )))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (UPNTIMES r (n - 1)) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n    using Posix1(1) apply fastforce\n    apply (metis One_nat_def Posix1(1) Posix_UPNTIMES1.hyps(7) append.right_neutral append_self_conv2)\n  using Posix1(2) by blast\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> UPNTIMES r (n - 1) \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto\nnext\n  case (Posix_UPNTIMES2 r n v2)\n  then show \"Stars [] = v2\"\n    apply(erule_tac Posix_elims)\n     apply(auto)\n    by (simp add: Posix1(2))\nnext\n  case (Posix_FROMNTIMES1 s1 r v s2 n vs v2)\n  have \"(s1 @ s2) \\<in> FROMNTIMES r n \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> FROMNTIMES r (n - 1) \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\" \"0 < n\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (FROMNTIMES r (n - 1 )))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (FROMNTIMES r (n - 1)) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n    using Posix1(1) Posix1(2) apply blast \n     apply(case_tac n)\n      apply(simp)\n      apply(simp)\n    apply(drule_tac x=\"va\" in meta_spec)\n    apply(drule_tac x=\"vs\" in meta_spec)\n    apply(simp)\n     apply(drule meta_mp)\n    apply (metis L.simps(9) Posix1(1) UN_E append.right_neutral append_Nil diff_Suc_1 local.Posix_FROMNTIMES1(4) val.inject(5))\n    apply (metis L.simps(9) Posix1(1) UN_E append.right_neutral append_Nil)\n    by (metis One_nat_def Posix1(1) Posix_FROMNTIMES1.hyps(7) self_append_conv self_append_conv2)\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> FROMNTIMES r (n - 1) \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto    \nnext\n  case (Posix_FROMNTIMES2 vs r n v2)  \n  then show \"Stars vs = v2\"\n    apply(erule_tac Posix_elims)\n     apply(auto)\n    apply(rule List_eq_zipI)\n     apply(auto)\n      apply(meson in_set_zipE)\n     apply (simp add: Posix1(2))\n    using Posix1(2) by blast\nnext\n  case (Posix_FROMNTIMES3 s1 r v s2 vs v2)  \n    have \"(s1 @ s2) \\<in> FROMNTIMES r 0 \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> STAR r \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (STAR r) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n    using Posix1(2) apply fastforce\n    using Posix1(1) apply fastforce\n    by (metis Posix1(1) Posix_FROMNTIMES3.hyps(6) append.right_neutral append_Nil)\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> STAR r \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto     \nnext    \n  case (Posix_NMTIMES1 s1 r v s2 n m vs v2)\n  have \"(s1 @ s2) \\<in> NMTIMES r n m \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> NMTIMES r (n - 1) (m - 1) \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\" \n       \"0 < n\" \"n \\<le> m\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (NMTIMES r (n - 1) (m - 1)))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \n    \"s2 \\<in> (NMTIMES r (n - 1) (m - 1)) \\<rightarrow> (Stars vs')\"\n  apply(cases) apply (auto simp add: append_eq_append_conv2)\n    using Posix1(1) Posix1(2) apply blast \n     apply(case_tac n)\n      apply(simp)\n     apply(simp)\n       apply(case_tac m)\n      apply(simp)\n     apply(simp)\n    apply(drule_tac x=\"va\" in meta_spec)\n    apply(drule_tac x=\"vs\" in meta_spec)\n    apply(simp)\n     apply(drule meta_mp)\n      apply(drule Posix1(1))\n      apply(drule Posix1(1))\n      apply(drule Posix1(1))\n      apply(frule Posix1(1))\n      apply(simp)\n    using Posix_NMTIMES1.hyps(4) apply force\n     apply (metis L.simps(10) Posix1(1) UN_E append_Nil2 append_self_conv2)\n    by (metis One_nat_def Posix1(1) Posix_NMTIMES1.hyps(8) append.right_neutral append_Nil)      \n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> NMTIMES r (n - 1) (m - 1) \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto     \nnext\n  case (Posix_NMTIMES2 vs r n m v2)\n  then show \"Stars vs = v2\"\n    apply(erule_tac Posix_elims)\n      apply(simp)\n      apply(rule List_eq_zipI)\n       apply(auto)\n      apply (meson in_set_zipE)\n    apply (simp add: Posix1(2))\n    apply(erule_tac Posix_elims)\n     apply(auto)\n    apply (simp add: Posix1(2))+\n    done  \nnext\n  case (Posix_NMTIMES3 s1 r v s2 m vs v2)\n   have \"(s1 @ s2) \\<in> NMTIMES r 0 m \\<rightarrow> v2\" \n       \"s1 \\<in> r \\<rightarrow> v\" \"s2 \\<in> UPNTIMES r (m - 1) \\<rightarrow> Stars vs\" \"flat v \\<noteq> []\" \"0 < m\"\n       \"\\<not> (\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> s1 @ s\\<^sub>3 \\<in> L r \\<and> s\\<^sub>4 \\<in> L (UPNTIMES r (m - 1 )))\" by fact+\n  then obtain v' vs' where \"v2 = Stars (v' # vs')\" \"s1 \\<in> r \\<rightarrow> v'\" \"s2 \\<in> (UPNTIMES r (m - 1)) \\<rightarrow> (Stars vs')\"\n    apply(cases) apply (auto simp add: append_eq_append_conv2)\n    using Posix1(2) apply blast\n    apply (smt L.simps(7) Posix1(1) UN_E append_eq_append_conv2)\n    by (metis One_nat_def Posix1(1) Posix_NMTIMES3.hyps(7) append.right_neutral append_Nil)\n  moreover\n  have IHs: \"\\<And>v2. s1 \\<in> r \\<rightarrow> v2 \\<Longrightarrow> v = v2\"\n            \"\\<And>v2. s2 \\<in> UPNTIMES r (m - 1) \\<rightarrow> v2 \\<Longrightarrow> Stars vs = v2\" by fact+\n  ultimately show \"Stars (v # vs) = v2\" by auto  \nqed\n\n\ntext {*\n  Our POSIX value is a lexical value.\n*}\n\nlemma Posix_LV:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"v \\<in> LV r s\"\nusing assms unfolding LV_def\napply(induct rule: Posix.induct)\n            apply(auto simp add: intro!: Prf.intros elim!: Prf_elims)[7]\n     defer\n  defer\n     apply(auto simp add: intro!: Prf.intros elim!: Prf_elims)[2]\n  apply (metis (mono_tags, lifting) Prf.intros(9) append_Nil empty_iff flat_Stars flats_empty list.set(1) mem_Collect_eq)\n     apply(simp)\n     apply(clarify)\n     apply(case_tac n)\n      apply(simp)\n     apply(simp)\n     apply(erule Prf_elims)\n      apply(simp)\n  apply(subst append.simps(2)[symmetric])\n      apply(rule Prf.intros) \n        apply(simp)\n       apply(simp)\n      apply(simp)\n     apply(simp)\n     apply(rule Prf.intros)  \n      apply(simp)\n     apply(simp)\n    apply(simp)\n   apply(clarify)\n   apply(erule Prf_elims)\n      apply(simp)\n  apply(rule Prf.intros)  \n       apply(simp)\n     apply(simp)\n  (* NTIMES *)\n   prefer 4\n   apply(simp)\n   apply(case_tac n)\n    apply(simp)\n   apply(simp)\n   apply(clarify)\n   apply(rotate_tac 5)\n   apply(erule Prf_elims)\n   apply(simp)\n  apply(subst append.simps(2)[symmetric])\n      apply(rule Prf.intros) \n        apply(simp)\n       apply(simp)\n   apply(simp)\n  prefer 4\n  apply(simp)\n  apply (metis Prf.intros(8) length_removeAll_less less_irrefl_nat removeAll.simps(1) self_append_conv2)\n  (* NMTIMES *)\n  apply(simp)\n  apply (metis Prf.intros(11) append_Nil empty_iff list.set(1))\n  apply(simp)\n  apply(clarify)\n  apply(rotate_tac 6)\n  apply(erule Prf_elims)\n   apply(simp)\n  apply(subst append.simps(2)[symmetric])\n      apply(rule Prf.intros) \n        apply(simp)\n       apply(simp)\n  apply(simp)\n  apply(simp)\n  apply(rule Prf.intros) \n        apply(simp)\n  apply(simp)\n  apply(simp)\n  apply(simp)\n  apply(clarify)\n  apply(rotate_tac 6)\n  apply(erule Prf_elims)\n   apply(simp)\n      apply(rule Prf.intros) \n        apply(simp)\n       apply(simp)\n  apply(simp)\ndone    \n  \nend", "meta": {"author": "fahadausaf", "repo": "POSIX-Parsing", "sha": "f077315e6dafc02f4d49c1669bb9bcb303fea23a", "save_path": "github-repos/isabelle/fahadausaf-POSIX-Parsing", "path": "github-repos/isabelle/fahadausaf-POSIX-Parsing/POSIX-Parsing-f077315e6dafc02f4d49c1669bb9bcb303fea23a/Theorems/SpecExt.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639065, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.759338631097452}}
{"text": "(* ---------------------------------------------------------------------------- *)\nsection \\<open>Homogeneous coordinates in extended complex plane\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Extended complex plane $\\mathbb{\\overline{C}}$ is complex plane with an additional element \n(treated as the infinite point). The extended complex plane $\\mathbb{\\overline{C}}$ is identified \nwith a complex projective line (the one-dimensional projective space over the complex field, sometimes denoted by $\\mathbb{C}P^1$).\nEach point of $\\mathbb{\\overline{C}}$ is represented by a pair of complex homogeneous coordinates (not\nboth equal to zero), and two pairs of homogeneous coordinates represent the same\npoint in $\\mathbb{\\overline{C}}$ iff they are proportional by a non-zero complex factor.\\<close>\n\ntheory Homogeneous_Coordinates\nimports More_Complex Matrices\nbegin\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Definition of homogeneous coordinates\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Two complex vectors are equivalent iff they are proportional.\\<close>\n\ndefinition complex_cvec_eq :: \"complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> bool\" (infix \"\\<approx>\\<^sub>v\" 50)  where\n  [simp]: \"z1 \\<approx>\\<^sub>v z2 \\<longleftrightarrow> (\\<exists> k. k \\<noteq> (0::complex) \\<and> z2 = k *\\<^sub>s\\<^sub>v z1)\"\n\nlemma complex_cvec_eq_mix:\n  assumes \"(z1, z2) \\<noteq> vec_zero\" and \"(w1, w2) \\<noteq> vec_zero\"\n  shows \"(z1, z2) \\<approx>\\<^sub>v (w1, w2) \\<longleftrightarrow> z1*w2 = z2*w1\"\nproof safe\n  assume \"(z1, z2) \\<approx>\\<^sub>v (w1, w2)\"\n  thus \"z1 * w2 = z2 * w1\"\n    by auto\nnext\n  assume *: \"z1 * w2 = z2 * w1\"\n  show \"(z1, z2) \\<approx>\\<^sub>v (w1, w2)\"\n  proof (cases \"z2 = 0\")\n    case True\n    thus ?thesis\n      using * assms\n      by auto\n  next\n    case False\n    hence \"w1 = (w2/z2)*z1 \\<and> w2 = (w2/z2)*z2\" \"w2/z2 \\<noteq> 0\"\n      using * assms\n      by (auto simp add: field_simps)\n    thus \"(z1, z2) \\<approx>\\<^sub>v (w1, w2)\"\n      by (metis complex_cvec_eq_def mult_sv.simps)\n  qed\nqed\n\nlemma complex_eq_cvec_reflp [simp]:\n  shows \"reflp (\\<approx>\\<^sub>v)\"\n  unfolding reflp_def complex_cvec_eq_def\n  by safe (rule_tac x=\"1\" in exI, simp)\n\nlemma complex_eq_cvec_symp [simp]:\n  shows \"symp (\\<approx>\\<^sub>v)\"\n  unfolding symp_def complex_cvec_eq_def\n  by safe (rule_tac x=\"1/k\" in exI, simp)\n\nlemma complex_eq_cvec_transp [simp]:\n  shows \"transp (\\<approx>\\<^sub>v)\"\n  unfolding transp_def complex_cvec_eq_def\n  by safe (rule_tac x=\"k*ka\" in exI, simp)\n\nlemma complex_eq_cvec_equivp [simp]:\n  shows \"equivp (\\<approx>\\<^sub>v)\"\n  by (auto intro: equivpI)\n\ntext \\<open>Non-zero pairs of complex numbers (also treated as non-zero complex vectors)\\<close>\n\ntypedef complex_homo_coords = \"{v::complex_vec. v \\<noteq> vec_zero}\"\n  by (rule_tac x=\"(1, 0)\" in exI, simp)\n\nsetup_lifting type_definition_complex_homo_coords\n\nlift_definition complex_homo_coords_eq :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> bool\" (infix \"\\<approx>\" 50) is complex_cvec_eq\n  done\n\nlemma complex_homo_coords_eq_reflp [simp]:\n  shows \"reflp (\\<approx>)\"\n  using complex_eq_cvec_reflp\n  unfolding reflp_def\n  by transfer blast\n\nlemma complex_homo_coords_eq_symp [simp]:\n  shows \"symp (\\<approx>)\"\n  using complex_eq_cvec_symp\n  unfolding symp_def\n  by transfer blast\n\nlemma complex_homo_coords_eq_transp [simp]: \n  shows \"transp (\\<approx>)\"\n  using complex_eq_cvec_transp\n  unfolding transp_def\n  by transfer blast\n\nlemma complex_homo_coords_eq_equivp:\n  shows \"equivp (\\<approx>)\"\n  by (auto intro: equivpI)\n\nlemma complex_homo_coords_eq_refl [simp]:\n  shows \"z \\<approx> z\"\n  using complex_homo_coords_eq_reflp\n  unfolding reflp_def refl_on_def\n  by blast\n\nlemma complex_homo_coords_eq_sym:\n  assumes \"z1 \\<approx> z2\"\n  shows \"z2 \\<approx> z1\"\n  using assms complex_homo_coords_eq_symp\n  unfolding symp_def\n  by blast\n\nlemma complex_homo_coords_eq_trans:\n  assumes \"z1 \\<approx> z2\" and \"z2 \\<approx> z3\"\n  shows \"z1 \\<approx> z3\"\n  using assms complex_homo_coords_eq_transp\n  unfolding transp_def\n  by blast\n\ntext \\<open>Quotient type of homogeneous coordinates\\<close>\nquotient_type\n  complex_homo = complex_homo_coords / \"complex_homo_coords_eq\"\n  by (rule complex_homo_coords_eq_equivp)\n\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Some characteristic points in $\\mathbb{C}P^1$\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Infinite point\\<close>\ndefinition inf_cvec :: \"complex_vec\" (\"\\<infinity>\\<^sub>v\") where\n  [simp]: \"inf_cvec = (1, 0)\"\nlift_definition inf_hcoords :: \"complex_homo_coords\"  (\"\\<infinity>\\<^sub>h\\<^sub>c\") is inf_cvec\n  by simp\nlift_definition inf :: \"complex_homo\"  (\"\\<infinity>\\<^sub>h\")  is inf_hcoords\ndone\n\nlemma inf_cvec_z2_zero_iff:\n  assumes \"(z1, z2) \\<noteq> vec_zero\"\n  shows \"(z1, z2) \\<approx>\\<^sub>v \\<infinity>\\<^sub>v \\<longleftrightarrow> z2 = 0\"\n  using assms\n  by auto\n\ntext \\<open>Zero\\<close>\ndefinition zero_cvec :: \"complex_vec\" (\"0\\<^sub>v\") where\n  [simp]: \"zero_cvec = (0, 1)\"\nlift_definition zero_hcoords :: \"complex_homo_coords\" (\"0\\<^sub>h\\<^sub>c\") is zero_cvec\n  by simp\nlift_definition zero :: \"complex_homo\" (\"0\\<^sub>h\") is zero_hcoords\n  done\n\nlemma zero_cvec_z1_zero_iff:\n  assumes \"(z1, z2) \\<noteq> vec_zero\"\n  shows \"(z1, z2) \\<approx>\\<^sub>v 0\\<^sub>v \\<longleftrightarrow> z1 = 0\"\n  using assms\n  by auto\n\ntext \\<open>One\\<close>\ndefinition one_cvec :: \"complex_vec\" (\"1\\<^sub>v\")where\n  [simp]: \"one_cvec = (1, 1)\"\nlift_definition one_hcoords :: \"complex_homo_coords\" (\"1\\<^sub>h\\<^sub>c\") is one_cvec\n  by simp\nlift_definition one :: \"complex_homo\" (\"1\\<^sub>h\") is one_hcoords\n  done\n\n\n\ntext \\<open>Imaginary unit\\<close>\ndefinition ii_cvec :: \"complex_vec\" (\"ii\\<^sub>v\") where\n  [simp]: \"ii_cvec = (\\<i>, 1)\"\nlift_definition ii_hcoords :: \"complex_homo_coords\" (\"ii\\<^sub>h\\<^sub>c\") is ii_cvec\n  by simp\nlift_definition ii :: \"complex_homo\" (\"ii\\<^sub>h\") is ii_hcoords\n  done\n\nlemma ex_3_different_points:\n  fixes z::complex_homo\n  shows \"\\<exists> z1 z2. z \\<noteq> z1 \\<and> z1 \\<noteq> z2 \\<and> z \\<noteq> z2\"\nproof (cases \"z \\<noteq> 0\\<^sub>h \\<and> z \\<noteq> 1\\<^sub>h\")\n  case True\n  thus ?thesis\n    by (rule_tac x=\"0\\<^sub>h\" in exI, rule_tac x=\"1\\<^sub>h\" in exI, auto)\nnext\n  case False\n  hence \"z = 0\\<^sub>h \\<or> z = 1\\<^sub>h\"\n    by simp\n  thus ?thesis\n  proof\n    assume \"z = 0\\<^sub>h\"\n    thus ?thesis\n      by (rule_tac x=\"\\<infinity>\\<^sub>h\" in exI, rule_tac x=\"1\\<^sub>h\" in exI, auto)\n  next\n    assume \"z = 1\\<^sub>h\"\n    thus ?thesis\n      by (rule_tac x=\"\\<infinity>\\<^sub>h\" in exI, rule_tac x=\"0\\<^sub>h\" in exI, auto)\n  qed\nqed\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Connection to ordinary complex plane $\\mathbb{C}$\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Conversion from complex\\<close>\n\ndefinition of_complex_cvec :: \"complex \\<Rightarrow> complex_vec\" where\n  [simp]: \"of_complex_cvec z = (z, 1)\"\nlift_definition of_complex_hcoords :: \"complex \\<Rightarrow> complex_homo_coords\" is of_complex_cvec\n  by simp\nlift_definition of_complex :: \"complex \\<Rightarrow> complex_homo\" is of_complex_hcoords\n  done\n\nlemma of_complex_inj:\n  assumes \"of_complex x = of_complex y\"\n  shows \"x = y\"\n  using assms\n  by (transfer, transfer, simp)\n\nlemma of_complex_image_inj:\n  assumes \"of_complex ` A = of_complex ` B\"\n  shows \"A = B\"\n  using assms\n  using of_complex_inj\n  by auto\n\nlemma of_complex_not_inf [simp]:\n  shows \"of_complex x \\<noteq> \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma inf_not_of_complex [simp]:\n  shows \"\\<infinity>\\<^sub>h \\<noteq> of_complex x\"\n  by (transfer, transfer, simp)\n\nlemma inf_or_of_complex:\n  shows \"z = \\<infinity>\\<^sub>h \\<or> (\\<exists> x. z = of_complex x)\"\nproof (transfer, transfer)\n  fix z :: complex_vec\n  obtain z1 z2 where *: \"z = (z1, z2)\"\n    by (cases z) auto\n  assume \"z \\<noteq> vec_zero\"\n  thus \"z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v \\<or> (\\<exists>x. z \\<approx>\\<^sub>v of_complex_cvec x)\"\n    using *\n    by (cases \"z2 = 0\", auto)\nqed\n\nlemma of_complex_zero [simp]:\n  shows \"of_complex 0 = 0\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma of_complex_one [simp]:\n  shows \"of_complex 1 = 1\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma of_complex_ii [simp]:\n  shows \"of_complex \\<i> = ii\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma of_complex_zero_iff [simp]:\n  shows \"of_complex x = 0\\<^sub>h \\<longleftrightarrow> x = 0\"\n  by (subst of_complex_zero[symmetric]) (auto simp add: of_complex_inj)\n\nlemma of_complex_one_iff [simp]:\n  shows \"of_complex x = 1\\<^sub>h \\<longleftrightarrow> x = 1\"\n  by (subst of_complex_one[symmetric]) (auto simp add: of_complex_inj)\n\nlemma of_complex_ii_iff [simp]:\n  shows \"of_complex x = ii\\<^sub>h \\<longleftrightarrow> x = \\<i>\"\n  by (subst of_complex_ii[symmetric]) (auto simp add: of_complex_inj)\n\ntext \\<open>Conversion to complex\\<close>\n\ndefinition to_complex_cvec :: \"complex_vec \\<Rightarrow> complex\" where\n  [simp]: \"to_complex_cvec z = (let (z1, z2) = z in z1/z2)\"\nlift_definition to_complex_homo_coords :: \"complex_homo_coords \\<Rightarrow> complex\" is to_complex_cvec\n  done\nlift_definition to_complex :: \"complex_homo \\<Rightarrow> complex\" is to_complex_homo_coords\nproof-\n  fix z w\n  assume \"z \\<approx> w\"\n  thus \"to_complex_homo_coords z = to_complex_homo_coords w\"\n    by transfer auto\nqed\n\nlemma to_complex_of_complex [simp]:\n  shows \"to_complex (of_complex z) = z\"\n  by (transfer, transfer, simp)\n\nlemma of_complex_to_complex [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"(of_complex (to_complex z)) = z\"\n  using assms\nproof (transfer, transfer)\n  fix z :: complex_vec\n  obtain z1 z2 where *: \"z = (z1, z2)\"\n    by (cases z, auto)\n  assume \"z \\<noteq> vec_zero\" \"\\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n  hence \"z2 \\<noteq> 0\"\n    using *\n    by (simp, erule_tac x=\"1/z1\" in allE, auto)\n  thus \"(of_complex_cvec (to_complex_cvec z)) \\<approx>\\<^sub>v z\"\n    using *\n    by simp\nqed\n\nlemma to_complex_zero_zero [simp]:\n  shows \"to_complex 0\\<^sub>h = 0\"\n  by (metis of_complex_zero to_complex_of_complex)\n\nlemma to_complex_one_one [simp]:\n  shows \"to_complex 1\\<^sub>h = 1\"\n  by (metis of_complex_one to_complex_of_complex)\n\nlemma to_complex_img_one [simp]:\n  shows \"to_complex ii\\<^sub>h = \\<i>\"\n  by (metis of_complex_ii to_complex_of_complex)\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Arithmetic operations\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Due to the requirement of HOL that all functions are total, we could not define the function\nonly for the well-defined cases, and in the lifting proofs we must also handle the ill-defined\ncases. For example, $\\infty_h +_h \\infty_h$ is ill-defined, but we must define it, so we define it\narbitrarily to be $\\infty_h$.\\<close>\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Addition\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>$\\infty_h\\ +_h\\ \\infty_h$ is ill-defined. Since functions must be total, for formal reasons we\ndefine it arbitrarily to be $\\infty_h$.\\<close>\n\ndefinition add_cvec :: \"complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_vec\" (infixl \"+\\<^sub>v\" 60) where\n  [simp]: \"add_cvec z w = (let (z1, z2) = z; (w1, w2) = w\n                                in if z2 \\<noteq> 0 \\<or> w2 \\<noteq> 0 then\n                                      (z1*w2 + w1*z2, z2*w2)\n                                   else\n                                      (1, 0))\"\nlift_definition add_hcoords :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> complex_homo_coords\" (infixl \"+\\<^sub>h\\<^sub>c\" 60) is add_cvec\n  by (auto split: if_split_asm)\n\nlift_definition add :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" (infixl \"+\\<^sub>h\" 60) is add_hcoords\nproof transfer\n  fix z w z' w' :: complex_vec\n  obtain z1 z2 w1 w2 z'1 z'2 w'1 w'2 where\n    *: \"z = (z1, z2)\" \"w = (w1, w2)\" \"z' = (z'1, z'2)\" \"w' = (w'1, w'2)\"\n    by (cases z, auto, cases w, auto, cases z', auto, cases w', auto)\n  assume **:\n         \"z \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\" \"z \\<approx>\\<^sub>v z'\"\n         \"z' \\<noteq> vec_zero\" \"w' \\<noteq> vec_zero\" \"w \\<approx>\\<^sub>v w'\"\n  show \"z +\\<^sub>v w \\<approx>\\<^sub>v z' +\\<^sub>v w'\"\n  proof (cases \"z2 \\<noteq> 0 \\<or> w2 \\<noteq> 0\")\n    case True\n    hence \"z'2 \\<noteq> 0 \\<or> w'2 \\<noteq> 0\"\n      using * **\n      by auto\n    show ?thesis\n      using \\<open>z2 \\<noteq> 0 \\<or> w2 \\<noteq> 0\\<close> \\<open>z'2 \\<noteq> 0 \\<or> w'2 \\<noteq> 0\\<close>\n      using * **\n      by simp ((erule exE)+, rule_tac x=\"k*ka\" in exI, simp add: field_simps)\n  next\n    case False\n    hence \"z'2 = 0 \\<or> w'2 = 0\"\n      using * **\n      by auto\n    show ?thesis\n      using \\<open>\\<not> (z2 \\<noteq> 0 \\<or> w2 \\<noteq> 0)\\<close> \\<open>z'2 = 0 \\<or> w'2 = 0\\<close>\n      using * **\n      by auto\n  qed\nqed\n\nlemma add_commute:\n  shows \"z +\\<^sub>h w = w +\\<^sub>h z\"\n  apply (transfer, transfer)\n  unfolding complex_cvec_eq_def\n  by (rule_tac x=\"1\" in exI, auto split: if_split_asm)\n\nlemma add_zero_right [simp]:\n  shows \"z +\\<^sub>h 0\\<^sub>h = z\"\n  by (transfer, transfer, force)\n\nlemma add_zero_left [simp]:\n  shows \"0\\<^sub>h +\\<^sub>h z = z\"\n  by (subst add_commute) simp\n\nlemma of_complex_add_of_complex [simp]:\n  shows \"(of_complex x) +\\<^sub>h (of_complex y) = of_complex (x + y)\"\n  by (transfer, transfer, simp)\n\nlemma of_complex_add_inf [simp]:\n  shows \"(of_complex x) +\\<^sub>h \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma inf_add_of_complex [simp]:\n  shows \"\\<infinity>\\<^sub>h +\\<^sub>h (of_complex x) = \\<infinity>\\<^sub>h\"\n  by (subst add_commute) simp\n\nlemma inf_add_right:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"z +\\<^sub>h \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  using assms\n  using inf_or_of_complex[of z]\n  by auto\n\nlemma inf_add_left:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"\\<infinity>\\<^sub>h +\\<^sub>h z = \\<infinity>\\<^sub>h\"\n  using assms\n  by (subst add_commute) (rule inf_add_right, simp)\n\ntext \\<open>This is ill-defined, but holds by our definition\\<close>\nlemma inf_add_inf:\n  shows \"\\<infinity>\\<^sub>h +\\<^sub>h \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp)\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Unary minus\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition uminus_cvec :: \"complex_vec \\<Rightarrow> complex_vec\" (\"~\\<^sub>v\") where\n  [simp]: \"~\\<^sub>v z = (let (z1, z2) = z in (-z1, z2))\"\nlift_definition uminus_hcoords :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords\" (\"~\\<^sub>h\\<^sub>c\") is uminus_cvec\n  by auto\nlift_definition uminus :: \"complex_homo \\<Rightarrow> complex_homo\" (\"~\\<^sub>h\") is uminus_hcoords\n  by transfer auto\n\nlemma uminus_of_complex [simp]:\n  shows \"~\\<^sub>h (of_complex z) = of_complex (-z)\"\n  by (transfer, transfer, simp)\n\nlemma uminus_zero [simp]:\n  shows \"~\\<^sub>h 0\\<^sub>h = 0\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma uminus_inf [simp]:\n  shows \"~\\<^sub>h \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  apply (transfer, transfer)\n  unfolding complex_cvec_eq_def\n  by (rule_tac x=\"-1\" in exI, simp)\n\nlemma uminus_inf_iff:\n  shows \"~\\<^sub>h z = \\<infinity>\\<^sub>h \\<longleftrightarrow> z = \\<infinity>\\<^sub>h\"\n  apply (transfer, transfer)\n  by auto (rule_tac x=\"-1/a\" in exI, auto)\n\nlemma uminus_id_iff:\n  shows \"~\\<^sub>h z = z \\<longleftrightarrow> z = 0\\<^sub>h \\<or> z = \\<infinity>\\<^sub>h\"\n  apply (transfer, transfer)\n  apply auto\n   apply (erule_tac x=\"1/a\" in allE, simp)\n  apply (rule_tac x=\"-1\" in exI, simp)\n  done\n\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Subtraction\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Operation $\\infty_h\\ -_h\\ \\infty_h$ is ill-defined, but we define it arbitrarily to $0_h$. It breaks the connection between\n   subtraction with addition and unary minus, but seems more intuitive.\\<close>\n\ndefinition sub :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" (infixl \"-\\<^sub>h\" 60) where\n  \"z -\\<^sub>h w = (if z = \\<infinity>\\<^sub>h \\<and> w = \\<infinity>\\<^sub>h then 0\\<^sub>h else z +\\<^sub>h (~\\<^sub>h w))\"\n\nlemma of_complex_sub_of_complex [simp]:\n  shows \"(of_complex x) -\\<^sub>h (of_complex y) = of_complex (x - y)\"\n  unfolding sub_def\n  by simp\n\nlemma zero_sub_right[simp]:\n  shows \"z -\\<^sub>h 0\\<^sub>h = z\"\n  unfolding sub_def\n  by simp\n\nlemma zero_sub_left[simp]:\n  shows \"0\\<^sub>h -\\<^sub>h of_complex x = of_complex (-x)\"\n  by (subst of_complex_zero[symmetric], simp del: of_complex_zero)\n\nlemma zero_sub_one[simp]:\n  shows \"0\\<^sub>h -\\<^sub>h 1\\<^sub>h = of_complex (-1)\"\n  by (metis of_complex_one zero_sub_left)\n\nlemma of_complex_sub_one [simp]:\n  shows \"of_complex x -\\<^sub>h 1\\<^sub>h = of_complex (x - 1)\"\n  by (metis of_complex_one of_complex_sub_of_complex)\n\n\n\nlemma sub_eq_zero_iff:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h \\<or> w \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"z -\\<^sub>h w = 0\\<^sub>h \\<longleftrightarrow> z = w\"\nproof\n  assume \"z -\\<^sub>h w = 0\\<^sub>h\"\n  thus \"z = w\"\n    using assms\n    unfolding sub_def\n  proof (transfer, transfer)\n    fix z w :: complex_vec\n    obtain z1 z2 w1 w2 where *: \"z = (z1, z2)\" \"w = (w1, w2)\"\n      by (cases z, auto, cases w, auto)\n    assume \"z \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\" \"\\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v \\<or> \\<not> w \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\" and\n           **: \"(if z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v \\<and> w \\<approx>\\<^sub>v \\<infinity>\\<^sub>v then 0\\<^sub>v else z +\\<^sub>v ~\\<^sub>v w) \\<approx>\\<^sub>v 0\\<^sub>v\"\n    have \"z2 \\<noteq> 0 \\<or> w2 \\<noteq> 0\"\n      using * \\<open>\\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v \\<or> \\<not> w \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\\<close> \\<open>z \\<noteq> vec_zero\\<close> \\<open>w \\<noteq> vec_zero\\<close>\n      apply auto\n       apply (erule_tac x=\"1/z1\" in allE, simp)\n      apply (erule_tac x=\"1/w1\" in allE, simp)\n      done\n\n    thus \"z \\<approx>\\<^sub>v w\"\n      using * **\n      by simp (rule_tac x=\"w2/z2\" in exI, auto simp add: field_simps)\n  qed\nnext\n  assume \"z = w\"\n  thus \"z -\\<^sub>h w = 0\\<^sub>h\"\n    using sub_eq_zero[of z] assms\n    by auto\nqed\n\nlemma inf_sub_left [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"\\<infinity>\\<^sub>h -\\<^sub>h z = \\<infinity>\\<^sub>h\"\n  using assms\n  using uminus_inf_iff\n  using inf_or_of_complex\n  unfolding sub_def\n  by force\n\nlemma inf_sub_right [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"z -\\<^sub>h \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  using assms\n  using inf_or_of_complex\n  unfolding sub_def\n  by force\n\ntext \\<open>This is ill-defined, but holds by our definition\\<close>\nlemma inf_sub_inf:\n  shows \"\\<infinity>\\<^sub>h -\\<^sub>h \\<infinity>\\<^sub>h = 0\\<^sub>h\"\n  unfolding sub_def\n  by simp\n\nlemma sub_noteq_inf:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\" and \"w \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"z -\\<^sub>h w \\<noteq> \\<infinity>\\<^sub>h\"\n  using assms\n  using inf_or_of_complex[of z]\n  using inf_or_of_complex[of w]\n  using inf_or_of_complex[of \"z -\\<^sub>h w\"]\n  using of_complex_sub_of_complex\n  by auto\n\nlemma sub_eq_inf:\n  assumes \"z -\\<^sub>h w = \\<infinity>\\<^sub>h\"\n  shows \"z = \\<infinity>\\<^sub>h \\<or> w = \\<infinity>\\<^sub>h\"\n  using assms sub_noteq_inf\n  by blast\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Multiplication\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Operations $0_h \\cdot_h \\infty_h$ and $\\infty_h \\cdot_h 0_h$ are ill defined. Since all\nfunctions must be total, for formal reasons we define it arbitrarily to be $1_h$.\\<close>\n\ndefinition mult_cvec :: \"complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_vec\" (infixl \"*\\<^sub>v\" 70) where\n [simp]: \"z *\\<^sub>v w = (let (z1, z2) = z; (w1, w2) = w\n                     in if (z1 = 0 \\<and> w2 = 0) \\<or> (w1 = 0 \\<and> z2 = 0) then\n                          (1, 1)\n                        else\n                          (z1*w1, z2*w2))\"\nlift_definition mult_hcoords :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> complex_homo_coords\" (infixl \"*\\<^sub>h\\<^sub>c\" 70) is mult_cvec\n  by (auto split: if_split_asm)\n\nlift_definition mult :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" (infixl \"*\\<^sub>h\" 70) is mult_hcoords\nproof transfer\n  fix z w z' w' :: complex_vec\n  obtain z1 z2 w1 w2 z'1 z'2 w'1 w'2 where\n    *: \"z = (z1, z2)\" \"w = (w1, w2)\" \"z' = (z'1, z'2)\" \"w' = (w'1, w'2)\"\n    by (cases z, auto, cases w, auto, cases z', auto, cases w', auto)\n  assume **:\n         \"z \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\" \"z \\<approx>\\<^sub>v z'\"\n         \"z' \\<noteq> vec_zero\" \"w' \\<noteq> vec_zero\" \"w \\<approx>\\<^sub>v w'\"\n  show \"z *\\<^sub>v w \\<approx>\\<^sub>v z' *\\<^sub>v w'\"\n  proof (cases \"(z1 = 0 \\<and> w2 = 0) \\<or> (w1 = 0 \\<and> z2 = 0)\")\n    case True\n    hence \"(z'1 = 0 \\<and> w'2 = 0) \\<or> (w'1 = 0 \\<and> z'2 = 0)\"\n      using * **\n      by auto\n    show ?thesis\n      using \\<open>(z1 = 0 \\<and> w2 = 0) \\<or> (w1 = 0 \\<and> z2 = 0)\\<close> \\<open>(z'1 = 0 \\<and> w'2 = 0) \\<or> (w'1 = 0 \\<and> z'2 = 0)\\<close>\n      using * **\n      by simp\n  next\n    case False\n    hence \"\\<not>((z'1 = 0 \\<and> w'2 = 0) \\<or> (w'1 = 0 \\<and> z'2 = 0))\"\n      using * **\n      by auto\n    hence ***: \"z *\\<^sub>v w = (z1*w1, z2*w2)\" \"z' *\\<^sub>v w' = (z'1*w'1, z'2*w'2)\"\n      using \\<open>\\<not>((z1 = 0 \\<and> w2 = 0) \\<or> (w1 = 0 \\<and> z2 = 0))\\<close> \\<open>\\<not>((z'1 = 0 \\<and> w'2 = 0) \\<or> (w'1 = 0 \\<and> z'2 = 0))\\<close>\n      using *\n      by auto\n    show ?thesis\n      apply (subst ***)+\n      using * **\n      by simp ((erule exE)+, rule_tac x=\"k*ka\" in exI, simp)\n  qed\nqed\n\nlemma of_complex_mult_of_complex [simp]:\n  shows \"(of_complex z1) *\\<^sub>h (of_complex z2) = of_complex (z1 * z2)\"\n  by (transfer, transfer, simp)\n\nlemma mult_commute:\n  shows \"z1 *\\<^sub>h z2 = z2 *\\<^sub>h z1\"\n  apply (transfer, transfer)\n  unfolding complex_cvec_eq_def\n  by (rule_tac x=\"1\" in exI, auto split: if_split_asm)\n\nlemma mult_zero_left [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"0\\<^sub>h *\\<^sub>h z = 0\\<^sub>h\"\n  using assms\nproof (transfer, transfer)\n  fix z :: complex_vec\n  obtain z1 z2 where *: \"z = (z1, z2)\"\n    by (cases z, auto)\n  assume \"z \\<noteq> vec_zero\" \"\\<not> (z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v)\"\n  hence \"z2 \\<noteq> 0\"\n    using *\n    by force\n  thus \"0\\<^sub>v *\\<^sub>v z \\<approx>\\<^sub>v 0\\<^sub>v\"\n    using *\n    by simp\nqed\n\nlemma mult_zero_right [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"z *\\<^sub>h 0\\<^sub>h = 0\\<^sub>h\"\n  using mult_zero_left[OF assms]\n  by (simp add: mult_commute)\n\nlemma mult_inf_right [simp]:\n  assumes \"z \\<noteq> 0\\<^sub>h\"\n  shows \"z *\\<^sub>h \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\nusing assms\nproof (transfer, transfer)\n  fix z :: complex_vec\n  obtain z1 z2 where *: \"z = (z1, z2)\"\n    by (cases z, auto)\n  assume \"z \\<noteq> vec_zero\" \"\\<not> (z \\<approx>\\<^sub>v 0\\<^sub>v)\"\n  hence \"z1 \\<noteq> 0\"\n    using *\n    by force\n  thus \"z *\\<^sub>v \\<infinity>\\<^sub>v \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n    using *\n    by simp\nqed\n\nlemma mult_inf_left [simp]:\n  assumes \"z \\<noteq> 0\\<^sub>h\"\n  shows \"\\<infinity>\\<^sub>h *\\<^sub>h z = \\<infinity>\\<^sub>h\"\n  using mult_inf_right[OF assms]\n  by (simp add: mult_commute)\n\nlemma mult_one_left [simp]:\n  shows \"1\\<^sub>h *\\<^sub>h z = z\"\n  by (transfer, transfer, force)\n\nlemma mult_one_right [simp]:\n  shows \"z *\\<^sub>h 1\\<^sub>h = z\"\n  using mult_one_left[of z]\n  by (simp add: mult_commute)\n\ntext \\<open>This is ill-defined, but holds by our definition\\<close>\nlemma inf_mult_zero:\n  shows \"\\<infinity>\\<^sub>h *\\<^sub>h 0\\<^sub>h = 1\\<^sub>h\"\n  by (transfer, transfer, simp)\nlemma zero_mult_inf: \n  shows \"0\\<^sub>h *\\<^sub>h \\<infinity>\\<^sub>h = 1\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma mult_eq_inf:\n  assumes \"z *\\<^sub>h w = \\<infinity>\\<^sub>h\"\n  shows \"z = \\<infinity>\\<^sub>h \\<or> w = \\<infinity>\\<^sub>h\"\n  using assms\n  using inf_or_of_complex[of z]\n  using inf_or_of_complex[of w]\n  using inf_or_of_complex[of \"z *\\<^sub>h w\"]\n  using of_complex_mult_of_complex\n  by auto\n\n\n\nsubsubsection \\<open>Reciprocal\\<close>\ndefinition reciprocal_cvec :: \"complex_vec \\<Rightarrow> complex_vec\" where\n  [simp]: \"reciprocal_cvec z = (let (z1, z2) = z in (z2, z1))\"\nlift_definition reciprocal_hcoords :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords\" is reciprocal_cvec\n  by auto\n\nlift_definition reciprocal :: \"complex_homo \\<Rightarrow> complex_homo\" is reciprocal_hcoords\n  by transfer auto\n\nlemma reciprocal_involution [simp]: \"reciprocal (reciprocal z) = z\"\n  by (transfer, transfer, auto)\n\nlemma reciprocal_zero [simp]: \"reciprocal 0\\<^sub>h = \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma reciprocal_inf [simp]: \"reciprocal \\<infinity>\\<^sub>h = 0\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma reciprocal_one [simp]: \"reciprocal 1\\<^sub>h = 1\\<^sub>h\"\n  by (transfer, transfer, simp)\n\nlemma reciprocal_inf_iff [iff]: \"reciprocal z = \\<infinity>\\<^sub>h \\<longleftrightarrow> z = 0\\<^sub>h\"\n  by (transfer, transfer, auto)\n\nlemma reciprocal_zero_iff [iff]: \"reciprocal z = 0\\<^sub>h \\<longleftrightarrow> z = \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, auto)\n\nlemma reciprocal_of_complex [simp]:\n  assumes \"z \\<noteq> 0\"\n  shows \"reciprocal (of_complex z) = of_complex (1 / z)\"\n  using assms\n  by (transfer, transfer, simp)\n\nlemma reciprocal_real:\n  assumes \"is_real (to_complex z)\" and \"z \\<noteq> 0\\<^sub>h\" and \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"Re (to_complex (reciprocal z)) = 1 / Re (to_complex z)\"\nproof-\n  obtain c where \"z = of_complex c\" \"c \\<noteq> 0\" \"is_real c\"\n    using assms inf_or_of_complex[of z]\n    by auto\n  thus ?thesis\n    by (simp add: Re_divide_real)\nqed\n\nlemma reciprocal_id_iff: \n  shows \"reciprocal z = z \\<longleftrightarrow> z = of_complex 1 \\<or> z = of_complex (-1)\"\nproof (cases \"z = 0\\<^sub>h\")\n  case True\n  thus ?thesis\n    by (metis inf_not_of_complex of_complex_zero_iff reciprocal_inf_iff zero_neq_neg_one zero_neq_one)\nnext\n  case False\n  thus ?thesis\n    using inf_or_of_complex[of z]\n    by (smt complex_sqrt_1 of_complex_zero_iff reciprocal_inf_iff reciprocal_of_complex to_complex_of_complex)\nqed\n\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Division\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Operations $0_h :_h 0_h$ and $\\infty_h :_h \\infty_h$ are ill-defined. For formal reasons they\nare defined to be $1_h$ (by the definition of multiplication).\\<close>\n\ndefinition divide :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" (infixl \":\\<^sub>h\" 70) where\n  \"x :\\<^sub>h y = x *\\<^sub>h (reciprocal y)\"\n\nlemma divide_zero_right [simp]:\n  assumes \"z \\<noteq> 0\\<^sub>h\"\n  shows \"z :\\<^sub>h 0\\<^sub>h = \\<infinity>\\<^sub>h\"\n  using assms\n  unfolding divide_def\n  by simp\n\nlemma divide_zero_left [simp]:\n  assumes \"z \\<noteq> 0\\<^sub>h\"\n  shows \"0\\<^sub>h :\\<^sub>h z = 0\\<^sub>h\"\n  using assms\n  unfolding divide_def\n  by simp\n\nlemma divide_inf_right [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"z :\\<^sub>h \\<infinity>\\<^sub>h = 0\\<^sub>h\"\n  using assms\n  unfolding divide_def\n  by simp\n\nlemma divide_inf_left [simp]:\n  assumes \"z \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"\\<infinity>\\<^sub>h :\\<^sub>h z = \\<infinity>\\<^sub>h\"\n  using assms reciprocal_zero_iff[of z] mult_inf_left\n  unfolding divide_def\n  by simp\n\nlemma divide_eq_inf:\n  assumes \"z :\\<^sub>h w = \\<infinity>\\<^sub>h\"\n  shows \"z = \\<infinity>\\<^sub>h \\<or> w = 0\\<^sub>h\"\n  using assms\n  using reciprocal_inf_iff[of w] mult_eq_inf\n  unfolding divide_def\n  by auto\n\nlemma inf_divide_zero [simp]:\n  shows \"\\<infinity>\\<^sub>h :\\<^sub>h 0\\<^sub>h = \\<infinity>\\<^sub>h\"\n  unfolding divide_def\n  by (transfer, simp)\n\nlemma zero_divide_inf [simp]:\n  shows \"0\\<^sub>h :\\<^sub>h \\<infinity>\\<^sub>h =  0\\<^sub>h\"\n  unfolding divide_def\n  by (transfer, simp)\n\nlemma divide_one_right [simp]:\n  shows \"z :\\<^sub>h 1\\<^sub>h = z\"\n  unfolding divide_def\n  by simp\n\nlemma of_complex_divide_of_complex [simp]:\n  assumes \"z2 \\<noteq> 0\"\n  shows \"(of_complex z1) :\\<^sub>h (of_complex z2) = of_complex (z1 / z2)\"\nusing assms\n  unfolding divide_def\n  apply transfer\n  apply transfer\n  by (simp, rule_tac x=\"1/z2\" in exI, simp)\n\nlemma one_div_of_complex [simp]:\n  assumes \"x \\<noteq> 0\"\n  shows \"1\\<^sub>h :\\<^sub>h of_complex x = of_complex (1 / x)\"\n  using assms\n  unfolding divide_def\n  by simp\n\ntext \\<open> This is ill-defined, but holds by our definition\\<close>\nlemma inf_divide_inf: \n  shows \"\\<infinity>\\<^sub>h :\\<^sub>h \\<infinity>\\<^sub>h = 1\\<^sub>h\"\n  unfolding divide_def\n  by (simp add: inf_mult_zero)\n\ntext \\<open> This is ill-defined, but holds by our definition\\<close>\nlemma zero_divide_zero:\n  shows \"0\\<^sub>h :\\<^sub>h 0\\<^sub>h = 1\\<^sub>h\"\n  unfolding divide_def\n  by (simp add: zero_mult_inf)\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Conjugate\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ndefinition conjugate_cvec :: \"complex_vec \\<Rightarrow> complex_vec\" where\n  [simp]: \"conjugate_cvec z = vec_cnj z\"\nlift_definition conjugate_hcoords :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords\" is conjugate_cvec\n  by (auto simp add: vec_cnj_def)\nlift_definition conjugate :: \"complex_homo \\<Rightarrow> complex_homo\" is conjugate_hcoords\n  by transfer (auto simp add: vec_cnj_def)\n\nlemma conjugate_involution [simp]:\n  shows \"conjugate (conjugate z) = z\"\n  by (transfer, transfer, auto)\n\nlemma conjugate_conjugate_comp [simp]:\n  shows \"conjugate \\<circ> conjugate = id\"\n  by (rule ext, simp)\n\nlemma inv_conjugate [simp]:\n  shows \"inv conjugate = conjugate\"\n  using inv_unique_comp[of conjugate conjugate]\n  by simp\n\nlemma conjugate_of_complex [simp]:\n  shows \"conjugate (of_complex z) = of_complex (cnj z)\"\n  by (transfer, transfer, simp add: vec_cnj_def)\n\nlemma conjugate_inf [simp]:\n  shows \"conjugate \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  by (transfer, transfer, simp add: vec_cnj_def)\n\nlemma conjugate_zero [simp]:\n  shows \"conjugate 0\\<^sub>h = 0\\<^sub>h\"\n  by (transfer, transfer, simp add: vec_cnj_def)\n\nlemma conjugate_one [simp]:\n  shows \"conjugate 1\\<^sub>h = 1\\<^sub>h\"\n  by (transfer, transfer, simp add: vec_cnj_def)\n\nlemma conjugate_inj:\n  assumes \"conjugate x = conjugate y\"\n  shows \"x = y\"\n  using assms\n  using conjugate_involution[of x] conjugate_involution[of y]\n  by metis\n\nlemma bij_conjugate [simp]:\n  shows \"bij conjugate\"\n  unfolding bij_def inj_on_def\nproof auto\n  fix x y\n  assume \"conjugate x = conjugate y\"\n  thus \"x = y\"\n   by (simp add: conjugate_inj)\nnext\n  fix x\n  show \"x \\<in> range conjugate\"\n    by (metis conjugate_involution range_eqI)\nqed\n\nlemma conjugate_id_iff: \n  shows \"conjugate a = a \\<longleftrightarrow> is_real (to_complex a) \\<or> a = \\<infinity>\\<^sub>h\"\n  using inf_or_of_complex[of a]\n  by (metis conjugate_inf conjugate_of_complex eq_cnj_iff_real to_complex_of_complex)\n\nsubsubsection \\<open>Inversion\\<close>\n\ntext \\<open>Geometric inversion wrt. the unit circle\\<close>\n\ndefinition inversion where\n  \"inversion = conjugate \\<circ> reciprocal\"\n\nlemma inversion_sym:\n  shows \"inversion = reciprocal \\<circ> conjugate\"\n  unfolding inversion_def\n  apply (rule ext, simp)\n  apply transfer\n  apply transfer\n  apply (auto simp add: vec_cnj_def)\n  using one_neq_zero\n  by blast+\n\nlemma inversion_involution [simp]:\n  shows \"inversion (inversion z) = z\"\nproof-\n  have *: \"conjugate \\<circ> reciprocal = reciprocal \\<circ> conjugate\"\n    using inversion_sym\n    by (simp add: inversion_def)\n  show ?thesis\n    unfolding inversion_def\n    by (subst *) simp\nqed\n\nlemma inversion_inversion_id [simp]:\n  shows \"inversion \\<circ> inversion = id\"\n  by (rule ext, simp)\n\nlemma inversion_zero [simp]:\n  shows \"inversion 0\\<^sub>h = \\<infinity>\\<^sub>h\"\n  by (simp add: inversion_def)\n\nlemma inversion_infty [simp]:\n  shows \"inversion \\<infinity>\\<^sub>h = 0\\<^sub>h\"\n  by (simp add: inversion_def)\n\nlemma inversion_of_complex [simp]:\n  assumes \"z \\<noteq> 0\"\n  shows \"inversion (of_complex z) = of_complex (1 / cnj z)\"\n  using assms\n  by (simp add: inversion_def)\n\nlemma is_real_inversion:\n  assumes \"is_real x\" and \"x \\<noteq> 0\"\n  shows \"is_real (to_complex (inversion (of_complex x)))\"\n  using assms eq_cnj_iff_real[of x]\n  by simp\n\nlemma inversion_id_iff: \n  shows \"a = inversion a \\<longleftrightarrow> a \\<noteq> \\<infinity>\\<^sub>h \\<and> (to_complex a) * cnj (to_complex a) = 1\" (is \"?lhs = ?rhs\")\nproof\n  assume \"a = inversion a\"\n  thus ?rhs\n    unfolding inversion_def\n    using inf_or_of_complex[of a]\n    by (metis (full_types) comp_apply complex_cnj_cancel_iff complex_cnj_zero inversion_def inversion_infty inversion_of_complex inversion_sym nonzero_eq_divide_eq of_complex_zero reciprocal_zero to_complex_of_complex zero_one_infty_not_equal(5))\nnext\n  assume ?rhs\n  thus ?lhs\n    using inf_or_of_complex[of a]\n    by (metis inversion_of_complex mult_not_zero nonzero_mult_div_cancel_right one_neq_zero to_complex_of_complex)\nqed\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Ratio and cross-ratio\\<close>\n(* ---------------------------------------------------------------------------- *)\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Ratio\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Ratio of points $z$, $v$ and $w$ is usually defined as\n$\\frac{z-v}{z-w}$. Our definition introduces it in homogeneous\ncoordinates. It is well-defined if $z_1 \\neq z_2 \\vee z_1 \\neq z_3$ and $z_1 \\neq \\infty_h$ and \n$z_2 \\neq \\infty_h \\vee z_3 \\neq \\infty_h$\\<close>\n\ndefinition ratio :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" where\n  \"ratio za zb zc = (za -\\<^sub>h zb) :\\<^sub>h (za -\\<^sub>h zc)\"\n\ntext \\<open>This is ill-defined, but holds by our definition\\<close>\nlemma\n  assumes \"zb \\<noteq> \\<infinity>\\<^sub>h\" and \"zc \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"ratio \\<infinity>\\<^sub>h zb zc = 1\\<^sub>h\"\n  using assms\n  using inf_sub_left[OF assms(1)]\n  using inf_sub_left[OF assms(2)]\n  unfolding ratio_def\n  by (simp add: inf_divide_inf)\n\nlemma\n  assumes \"za \\<noteq> \\<infinity>\\<^sub>h\" and \"zc \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"ratio za \\<infinity>\\<^sub>h zc = \\<infinity>\\<^sub>h\"\n  using assms\n  unfolding ratio_def\n  using inf_sub_right[OF assms(1)]\n  using sub_noteq_inf[OF assms]\n  using divide_inf_left\n  by simp\n\nlemma\n  assumes \"za \\<noteq> \\<infinity>\\<^sub>h\" and \"zb \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"ratio za zb \\<infinity>\\<^sub>h = 0\\<^sub>h\"\n  unfolding ratio_def\n  using sub_noteq_inf[OF assms]\n  using inf_sub_right[OF assms(1)]\n  using divide_inf_right\n  by simp\n\nlemma\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"ratio z1 z2 z1 = \\<infinity>\\<^sub>h\"\n  using assms\n  unfolding ratio_def\n  using divide_zero_right[of \"z1 -\\<^sub>h z2\"]\n  using sub_eq_zero_iff[of z1 z2]\n  by simp\n\n(* ---------------------------------------------------------------------------- *)\nsubsubsection \\<open>Cross-ratio\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>The cross-ratio is defined over 4 points $(z, u, v, w)$, usually as\n$\\frac{(z-u)(v-w)}{(z-w)(v-u)}$. We define it using homogeneous coordinates. Cross ratio is\nill-defined when $z = u \\vee v = w$ and $z = w$ and $v = u$ i.e. when 3 points are equal. Since\nfunction must be total, in that case we define it arbitrarily to 1.\\<close>\n\ndefinition cross_ratio_cvec :: \"complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_vec \\<Rightarrow> complex_vec\" where\n  [simp]: \"cross_ratio_cvec z u v w =\n     (let (z', z'') = z;\n          (u', u'') = u;\n          (v', v'') = v;\n          (w', w'') = w;\n          n1 = z'*u'' - u'*z'';\n          n2 = v'*w'' - w'*v'';\n          d1 = z'*w'' - w'*z'';\n          d2 = v'*u'' - u'*v''\n       in\n         if n1 * n2 \\<noteq> 0 \\<or> d1 * d2 \\<noteq> 0 then\n              (n1 * n2, d1 * d2)\n         else\n              (1, 1))\"\n\nlift_definition cross_ratio_hcoords :: \"complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> complex_homo_coords \\<Rightarrow> complex_homo_coords\" is cross_ratio_cvec\n  by (auto split: if_split_asm)\n\nlift_definition cross_ratio :: \"complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" is cross_ratio_hcoords\nproof transfer\n  fix z u v w z' u' v' w' :: complex_vec\n  obtain z1 z2 u1 u2 v1 v2 w1 w2 z'1 z'2 u'1 u'2 v'1 v'2 w'1 w'2\n    where *: \"z = (z1, z2)\" \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n             \"z' = (z'1, z'2)\" \"u' = (u'1, u'2)\" \"v' = (v'1, v'2)\" \"w' = (w'1, w'2)\"\n    by (cases z, auto, cases u, auto, cases v, auto, cases w, auto,\n        cases z', auto, cases u', auto, cases v', auto, cases w', auto)\n  let ?n1 = \"z1*u2 - u1*z2\"\n  let ?n2 = \"v1*w2 - w1*v2\"\n  let ?d1 = \"z1*w2 - w1*z2\"\n  let ?d2 = \"v1*u2 - u1*v2\"\n  let ?n1' = \"z'1*u'2 - u'1*z'2\"\n  let ?n2' = \"v'1*w'2 - w'1*v'2\"\n  let ?d1' = \"z'1*w'2 - w'1*z'2\"\n  let ?d2' = \"v'1*u'2 - u'1*v'2\"\n\n  assume **:\n         \"z \\<noteq> vec_zero\" \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n         \"z' \\<noteq> vec_zero\" \"u' \\<noteq> vec_zero\" \"v' \\<noteq> vec_zero\" \"w' \\<noteq> vec_zero\"\n         \"z \\<approx>\\<^sub>v z'\" \"v \\<approx>\\<^sub>v v'\" \"u \\<approx>\\<^sub>v u'\" \"w \\<approx>\\<^sub>v w'\"\n  show \"cross_ratio_cvec z u v w \\<approx>\\<^sub>v cross_ratio_cvec z' u' v' w'\"\n  proof (cases \"?n1*?n2 \\<noteq> 0 \\<or> ?d1*?d2 \\<noteq> 0\")\n    case True\n    hence \"?n1'*?n2' \\<noteq> 0 \\<or> ?d1'*?d2' \\<noteq> 0\"\n      using * **\n      by simp ((erule exE)+, simp)\n    show ?thesis\n      using \\<open>?n1*?n2 \\<noteq> 0 \\<or> ?d1*?d2 \\<noteq> 0\\<close>\n      using \\<open>?n1'*?n2' \\<noteq> 0 \\<or> ?d1'*?d2' \\<noteq> 0\\<close>\n      using * **\n      by simp ((erule exE)+, rule_tac x=\"k*ka*kb*kc\" in exI, simp add: field_simps)\n  next\n    case False\n    hence \"\\<not> (?n1'*?n2' \\<noteq> 0 \\<or> ?d1'*?d2' \\<noteq> 0)\"\n      using * **\n      by simp ((erule exE)+, simp)\n    show ?thesis\n      using \\<open>\\<not> (?n1*?n2 \\<noteq> 0 \\<or> ?d1*?d2 \\<noteq> 0)\\<close>\n      using \\<open>\\<not> (?n1'*?n2' \\<noteq> 0 \\<or> ?d1'*?d2' \\<noteq> 0)\\<close>\n      using * **\n      by simp blast\n  qed\nqed\n\nlemma cross_ratio_01inf_id [simp]:\n  shows \"cross_ratio z 0\\<^sub>h 1\\<^sub>h \\<infinity>\\<^sub>h = z\"\nproof (transfer, transfer)\n  fix z :: complex_vec\n  obtain z1 z2 where *: \"z = (z1, z2)\"\n    by (cases z, auto)\n  assume \"z \\<noteq> vec_zero\"\n  thus \"cross_ratio_cvec z 0\\<^sub>v 1\\<^sub>v \\<infinity>\\<^sub>v \\<approx>\\<^sub>v z\"\n    using *\n    by simp (rule_tac x=\"-1\" in exI, simp)\nqed\n\nlemma cross_ratio_0:\n  assumes \"u \\<noteq> v\" and \"u \\<noteq> w\"\n  shows \"cross_ratio u u v w = 0\\<^sub>h\"\n  using assms\nproof (transfer, transfer)\n  fix u v w  :: complex_vec\n  obtain u1 u2 v1 v2 w1 w2\n    where *: \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n    by (cases u, auto, cases v, auto, cases w, auto)\n  assume \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\" \"\\<not> u \\<approx>\\<^sub>v v\" \"\\<not> u \\<approx>\\<^sub>v w\"\n  thus \"cross_ratio_cvec u u v w \\<approx>\\<^sub>v 0\\<^sub>v\"\n    using * complex_cvec_eq_mix[of u1 u2 v1 v2] complex_cvec_eq_mix[of u1 u2 w1 w2]\n    by (force simp add: mult.commute)\nqed\n\nlemma cross_ratio_1:\n  assumes \"u \\<noteq> v\" and \"v \\<noteq> w\"\n  shows \"cross_ratio v u v w = 1\\<^sub>h\"\n  using assms\nproof (transfer, transfer)\n  fix u v w  :: complex_vec\n  obtain u1 u2 v1 v2 w1 w2\n    where *: \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n    by (cases u, auto, cases v, auto, cases w, auto)\n  let ?n1 = \"v1*u2 - u1*v2\"\n  let ?n2 = \"v1*w2 - w1*v2\"\n  assume \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\" \"\\<not> u \\<approx>\\<^sub>v v\" \"\\<not> v \\<approx>\\<^sub>v w\"\n  hence \"?n1 \\<noteq> 0 \\<and> ?n2 \\<noteq> 0\"\n    using * complex_cvec_eq_mix[of u1 u2 v1 v2] complex_cvec_eq_mix[of v1 v2 w1 w2]\n    by (auto simp add: field_simps)\n  thus \"cross_ratio_cvec v u v w \\<approx>\\<^sub>v 1\\<^sub>v\"\n    using *\n    by simp (rule_tac x=\"1 / (?n1 * ?n2)\" in exI, simp)\nqed\n\nlemma cross_ratio_inf:\n  assumes \"u \\<noteq> w\" and \"v \\<noteq> w\"\n  shows \"cross_ratio w u v w = \\<infinity>\\<^sub>h\"\n  using assms\nproof (transfer, transfer)\n  fix u v w  :: complex_vec\n  obtain u1 u2 v1 v2 w1 w2\n    where *: \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n    by (cases u, auto, cases v, auto, cases w, auto)\n  let ?n1 = \"w1*u2 - u1*w2\"\n  let ?n2 = \"v1*w2 - w1*v2\"\n  assume \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\" \"\\<not> u \\<approx>\\<^sub>v w\" \"\\<not> v \\<approx>\\<^sub>v w\"\n  hence \"?n1 \\<noteq> 0 \\<and> ?n2 \\<noteq> 0\"\n    using * complex_cvec_eq_mix[of u1 u2 w1 w2] complex_cvec_eq_mix[of v1 v2 w1 w2]\n    by (auto simp add: field_simps)\n  thus \"cross_ratio_cvec w u v w \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n    using *\n    by simp\nqed\n\nlemma cross_ratio_0inf:\n  assumes \"y \\<noteq> 0\"\n  shows \"cross_ratio (of_complex x) 0\\<^sub>h (of_complex y) \\<infinity>\\<^sub>h = (of_complex (x / y))\"\n  using assms\n  by (transfer, transfer) (simp, rule_tac x=\"-1/y\" in exI, simp)\n\nlemma cross_ratio_commute_13:\n  shows \"cross_ratio z u v w = reciprocal (cross_ratio v u z w)\"\n  by (transfer, transfer, case_tac z, case_tac u, case_tac v, case_tac w, simp)\n\nlemma cross_ratio_commute_24:\n  shows \"cross_ratio z u v w = reciprocal (cross_ratio z w v u)\"\n  by (transfer, transfer, case_tac z, case_tac u, case_tac v, case_tac w, simp)\n\nlemma cross_ratio_not_inf:\n  assumes \"z \\<noteq> w\" and \"u \\<noteq> v\"\n  shows \"cross_ratio z u v w \\<noteq> \\<infinity>\\<^sub>h\"\n  using assms\nproof (transfer, transfer)\n  fix z u v w\n  assume nz: \"z \\<noteq> vec_zero\" \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n  obtain z1 z2 u1 u2 v1 v2 w1 w2 where *: \"z = (z1, z2)\" \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n    by (cases z, cases u, cases v, cases w, auto)\n  obtain x1 x2 where **: \"cross_ratio_cvec z u v w = (x1, x2)\"\n    by (cases \"cross_ratio_cvec z u v w\", auto)\n  assume \"\\<not> z \\<approx>\\<^sub>v w\" \"\\<not> u \\<approx>\\<^sub>v v\"\n  hence \"z1*w2 \\<noteq> z2*w1\" \"u1*v2 \\<noteq> u2*v1\"\n    using * nz complex_cvec_eq_mix\n    by blast+\n  hence \"x2 \\<noteq> 0\"\n    using * **\n    by (auto split: if_split_asm) (simp add: field_simps)\n  thus \"\\<not> cross_ratio_cvec z u v w \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n    using inf_cvec_z2_zero_iff * **\n    by simp\nqed\n\nlemma cross_ratio_not_zero:\n  assumes \"z \\<noteq> u\" and \"v \\<noteq> w\"\n  shows \"cross_ratio z u v w \\<noteq> 0\\<^sub>h\"\n  using assms\nproof (transfer, transfer)\n  fix z u v w\n  assume nz: \"z \\<noteq> vec_zero\" \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n  obtain z1 z2 u1 u2 v1 v2 w1 w2 where *: \"z = (z1, z2)\" \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n    by (cases z, cases u, cases v, cases w, auto)\n  obtain x1 x2 where **: \"cross_ratio_cvec z u v w = (x1, x2)\"\n    by (cases \"cross_ratio_cvec z u v w\", auto)\n  assume \"\\<not> z \\<approx>\\<^sub>v u\" \"\\<not> v \\<approx>\\<^sub>v w\"\n  hence \"z1*u2 \\<noteq> z2*u1\" \"v1*w2 \\<noteq> v2*w1\"\n    using * nz complex_cvec_eq_mix\n    by blast+\n  hence \"x1 \\<noteq> 0\"\n    using * **\n    by (auto split: if_split_asm)\n  thus \"\\<not> cross_ratio_cvec z u v w \\<approx>\\<^sub>v 0\\<^sub>v\"\n    using zero_cvec_z1_zero_iff * **\n    by simp\nqed\n\nlemma cross_ratio_real:\n  assumes \"is_real z\" and \"is_real u\" and \"is_real v\" and \"is_real w\" \n  assumes \"z \\<noteq> u \\<and> v \\<noteq> w \\<or> z \\<noteq> w \\<and> u \\<noteq> v\"\n  shows \"is_real (to_complex (cross_ratio (of_complex z) (of_complex u) (of_complex v) (of_complex w)))\"\n  using assms\n  by (transfer, transfer, auto)\n\nlemma cross_ratio:\n  assumes \"(z \\<noteq> u \\<and> v \\<noteq> w) \\<or> (z \\<noteq> w \\<and> u \\<noteq> v)\" and\n          \"z \\<noteq> \\<infinity>\\<^sub>h\" and  \"u \\<noteq> \\<infinity>\\<^sub>h\" and \"v \\<noteq> \\<infinity>\\<^sub>h\" and \"w \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"cross_ratio z u v w = ((z -\\<^sub>h u) *\\<^sub>h (v -\\<^sub>h w)) :\\<^sub>h ((z -\\<^sub>h w) *\\<^sub>h (v -\\<^sub>h u))\"\n  unfolding sub_def divide_def\n  using assms\n  apply transfer\n  apply simp\n  apply transfer\nproof-\n  fix z u v w :: complex_vec\n  obtain z1 z2 u1 u2 v1 v2 w1 w2\n    where *: \"z = (z1, z2)\" \"u = (u1, u2)\" \"v = (v1, v2)\" \"w = (w1, w2)\"\n    by (cases z, auto, cases u, auto, cases v, auto, cases w, auto)\n\n  let ?n1 = \"z1*u2 - u1*z2\"\n  let ?n2 = \"v1*w2 - w1*v2\"\n  let ?d1 = \"z1*w2 - w1*z2\"\n  let ?d2 = \"v1*u2 - u1*v2\"\n  assume **: \"z \\<noteq> vec_zero\" \"u \\<noteq> vec_zero\" \"v \\<noteq> vec_zero\" \"w \\<noteq> vec_zero\"\n         \"\\<not> z \\<approx>\\<^sub>v u \\<and> \\<not> v \\<approx>\\<^sub>v w \\<or> \\<not> z \\<approx>\\<^sub>v w \\<and> \\<not> u \\<approx>\\<^sub>v v\"\n         \"\\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\" \"\\<not> u \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\" \"\\<not> v \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\" \"\\<not> w \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n\n  hence ***: \"?n1 * ?n2 \\<noteq> 0 \\<or> ?d1 * ?d2 \\<noteq> 0\"\n    using *\n    using complex_cvec_eq_mix[of z1 z2 u1 u2] complex_cvec_eq_mix[of v1 v2 w1 w2]\n    using complex_cvec_eq_mix[of z1 z2 w1 w2] complex_cvec_eq_mix[of u1 u2 v1 v2]\n    by (metis eq_iff_diff_eq_0 mult.commute mult_eq_0_iff)\n\n  have ****: \"z2 \\<noteq> 0\" \"w2 \\<noteq> 0\" \"u2 \\<noteq> 0\" \"v2 \\<noteq> 0\"\n    using * **(1-4) **(6-9)\n    using inf_cvec_z2_zero_iff[of z1 z2]\n    using inf_cvec_z2_zero_iff[of u1 u2]\n    using inf_cvec_z2_zero_iff[of v1 v2]\n    using inf_cvec_z2_zero_iff[of w1 w2]\n    by blast+\n\n  have \"cross_ratio_cvec z u v w = (?n1*?n2, ?d1*?d2)\"\n    using * ***\n    by simp\n  moreover\n  let ?k = \"z2*u2*v2*w2\"\n  have \"(z +\\<^sub>v ~\\<^sub>v u) *\\<^sub>v (v +\\<^sub>v ~\\<^sub>v w) *\\<^sub>v reciprocal_cvec ((z +\\<^sub>v ~\\<^sub>v w) *\\<^sub>v (v +\\<^sub>v ~\\<^sub>v u)) = (?k * ?n1 * ?n2, ?k * ?d1 * ?d2)\"\n    using * *** ****\n    by auto\n  ultimately\n  show \"cross_ratio_cvec z u v w \\<approx>\\<^sub>v\n           (z +\\<^sub>v ~\\<^sub>v u) *\\<^sub>v (v +\\<^sub>v ~\\<^sub>v w) *\\<^sub>v reciprocal_cvec ((z +\\<^sub>v ~\\<^sub>v w) *\\<^sub>v (v +\\<^sub>v ~\\<^sub>v u))\"\n    using ****\n    unfolding complex_cvec_eq_def\n    by (rule_tac x=\"?k\" in exI) simp\nqed\n\nend\n\n(*\n(* Although it seems useful, we did not use this. *)\n\ntext \\<open>Transfer extended complex plane to complex plane\\<close>\n\ndefinition HC :: \"complex_homo \\<Rightarrow> complex \\<Rightarrow> bool\"\n  where \"HC = (\\<lambda> h c. h = of_complex c)\"\n\nlemma Domainp_HC [transfer_domain_rule]: \"Domainp HC = (\\<lambda> x. x \\<noteq> \\<infinity>\\<^sub>h)\"\n  unfolding HC_def Domainp_iff[abs_def]\n  apply (rule ext)\n  using inf_or_of_complex\n  by auto\n\nlemma bi_unique_HC [transfer_rule]: \"bi_unique HC\"\n  using of_complex_inj\n  unfolding HC_def bi_unique_def\n  by auto\n\nlemma right_total_HC [transfer_rule]: \"right_total HC\"\n  unfolding HC_def right_total_def\n  by auto\n\nlemma HC_0 [transfer_rule]: \"HC 0\\<^sub>h 0\"\n  unfolding HC_def\n  by simp\n\nlemma HC_1 [transfer_rule]: \"HC 1\\<^sub>h 1\"\n  unfolding HC_def\n  by simp\n\ncontext includes lifting_syntax\nbegin\nlemma HC_add [transfer_rule]: \"(HC ===> HC ===> HC) (op +\\<^sub>h) (op +)\"\n  unfolding rel_fun_def HC_def\n  by auto\n\nlemma HC_mult [transfer_rule]: \"(HC ===> HC ===> HC) (op *\\<^sub>h) ( op * )\"\n  unfolding rel_fun_def HC_def\n  by auto\n\nlemma HC_All [transfer_rule]:\n  \"((HC ===> op =) ===> op =) (Ball {z. z \\<noteq> \\<infinity>\\<^sub>h}) All\"\n  using inf_or_of_complex\n  unfolding rel_fun_def HC_def\n  by auto\n\nlemma HC_transfer_forall [transfer_rule]:\n  \"((HC ===> op =) ===> op =) (transfer_bforall (\\<lambda>x. x \\<noteq> \\<infinity>\\<^sub>h)) transfer_forall\"\n  using inf_or_of_complex\n  unfolding transfer_forall_def transfer_bforall_def\n  unfolding rel_fun_def HC_def\n  by auto\nend\n*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/Homogeneous_Coordinates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869851639066, "lm_q2_score": 0.867035752930664, "lm_q1q2_score": 0.7593386280884641}}
{"text": "theory Seq2less\n  imports Main\nbegin\n\n(* Here we have basic definitions of 2-less relation and sequence *)\n\n(* Base: Triple, lt, lt_all, is_less *)\n\ntype_synonym Tri = \"nat \\<times> nat \\<times> nat\"\n(* PS: We could also use nat, but then complements get complicated. *)\n\nfun lt :: \"Tri \\<Rightarrow> Tri \\<Rightarrow> bool\" (infixl \"\\<prec>\" 70) where\n  \"lt (x1, x2, x3) (y1, y2, y3) =\n    (x1 < y1 \\<and> (x2 < y2 \\<or> x3 < y3) \\<or> (x2 < y2) \\<and> (x3 < y3))\"\n\nprimrec lt_all :: \"Tri \\<Rightarrow> Tri list \\<Rightarrow> bool\" where\n  \"lt_all x [] = True\" |\n  \"lt_all x (h#t) = (x \\<prec> h \\<and> lt_all x t)\"\n\nprimrec is_2less :: \"Tri list \\<Rightarrow> bool\" where\n  \"is_2less [] = True\" |\n  \"is_2less (h#t) = (lt_all h t \\<and> is_2less t)\"\n\n\n(* Addon: gt_all, valid_candidate *)\n\nprimrec gt_all :: \"Tri \\<Rightarrow> Tri list \\<Rightarrow> bool\" where\n  \"gt_all x [] = True\" |\n  \"gt_all x (h#t) = (h \\<prec> x \\<and> gt_all x t)\"\n\nlemma relate_gt_all_to_lt_all:\n  \"lt_all h t \\<and> gt_all x (h#t) \\<longrightarrow> lt_all h (t@[x])\"\n  apply (induction t arbitrary: x h)\n  by auto\n\nlemma valid_candidate:\n  \"is_2less s \\<and> gt_all x s  \\<longrightarrow> is_2less (s@[x])\"\n  apply (induction s arbitrary: x)\n  apply simp\n  using relate_gt_all_to_lt_all\n  by auto\n\n\n(* Some additional relations *)\n\nfun lt3 :: \"Tri \\<Rightarrow> Tri \\<Rightarrow> bool\" where\n  \"lt3 (x1, x2, x3) (y1, y2, y3) =\n    (x1 < y1 \\<and> x2 < y2 \\<and> x3 < y3)\"\n\nfun le3 :: \"Tri \\<Rightarrow> Tri \\<Rightarrow> bool\" where\n  \"le3 (a, b, c) (x, y, z) =\n\t  (a \\<le> x \\<and> b \\<le> y \\<and> c \\<le> z)\"\n\nlemma lt3_implies_lt:\n  \"lt3 x y \\<longrightarrow> lt x y\"\n  by (smt Pair_inject lt.elims(3) lt3.elims(2))\n\nlemma lt3_implies_le3:\n  \"lt3 x y \\<longrightarrow> le3 x y\"\n  by (smt Pair_inject le3.elims(3) less_le lt3.elims(2))\n\nlemma transitive_le3_and_lt:\n  \"le3 x y \\<and> y \\<prec> z \\<longrightarrow> x \\<prec> z\"\n  by (smt Pair_inject le3.elims(2) le_less_trans lt.elims(2) lt.elims(3))\n\nend\n", "meta": {"author": "jurem", "repo": "2-less", "sha": "26e658e511e48bdfe81de6588c07133b35244fbb", "save_path": "github-repos/isabelle/jurem-2-less", "path": "github-repos/isabelle/jurem-2-less/2-less-26e658e511e48bdfe81de6588c07133b35244fbb/isabelle/Seq2less.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8267117898012105, "lm_q1q2_score": 0.7593184427456976}}
{"text": "theory tp5bis\n  imports Main \nbegin\n\n(* les glob sont les chaînes unix qui utilisent les jokers ?, * et + pour décrire des ensembles de noms *)\n\n(* Définition du type glob (ici nommé pattern) *)\ndatatype symbol = Char char | Star | Qmark | Plus\n\ntype_synonym word= \"char list\"\ntype_synonym pattern= \"symbol list\" \n\n(* La fonction qui dit si un mot est accepté par un pattern/glob  *)\nfun accept::\"pattern \\<Rightarrow> word \\<Rightarrow> bool\"\n  where\n\"accept [] [] = True\" |\n\"accept [Star] _ = True\" |\n\"accept [] (_#_) = False\" |\n\"accept ((Char x)#_) [] = False\" | \n\"accept ((Char x)#r1) (y#r2) = (if x=y then (accept r1 r2) else False)\"  |\n\"accept (Qmark#r1) [] = False\" |\n\"accept (Qmark#r1) (_#r2) = (accept r1 r2)\" |\n\"accept (Plus#r1) [] = False\" |\n\"accept (Plus#r1) (a#r2) = (accept (Star#r1) r2)\" |\n\"accept (Star#r1) [] = (accept r1 [])\" |\n\"accept (Star#r1) (a#r2) = ((accept r1 (a#r2)) \\<or> (accept r1 r2) \\<or> (accept (Star#r1) r2))\"\n\n(* Les caractères en Isabelle/HOL *)\nvalue \"(CHR ''a'')\"\n\n(* Quelques exemples d'utilisation de la fonction accept *)\nvalue \"accept [Star,(Char (CHR ''a''))] [(CHR ''a'')]\"\nvalue \"accept [Star,(Char (CHR ''a''))] [(CHR ''b''),(CHR ''a'')]\"\nvalue \"accept [Star,(Char (CHR ''a''))] [(CHR ''a''),(CHR ''b'')]\"\nvalue \"accept [Star,Star] []\"\nvalue \"accept [Plus,Star,Star] []\"\nvalue \"accept [Qmark] []\"\nvalue \"accept [Qmark,Plus] [(CHR ''a''),(CHR ''a'')]\"\nvalue \"accept [Plus,Plus] [(CHR ''a''),(CHR ''a'')]\"\nvalue \"accept [Plus,Plus] [(CHR ''a'')]\"\n\n(* ----------------------------- Votre TP commence ici! ---------------------------------------- *)\nfun simplify::\"pattern \\<Rightarrow> pattern\"\n  where\n  \"simplify [] = []\"\n| \"simplify (Plus#(Char x) #t) = (Plus#(Char x)#(simplify t))\"\n| \"simplify (Plus#Plus #t) = (Qmark#(simplify (Plus#t)))\"\n| \"simplify (Plus#Star#t) = ((simplify (Plus#t)))\"\n| \"simplify (Plus#Qmark#t) = (Plus#(simplify (Qmark#t)))\"\n| \"simplify (Star#(Char x) #t) = (Star#(Char x)#(simplify t))\"\n| \"simplify (Star#Star #t) = ((simplify (Star#t)))\"\n| \"simplify (Star#Plus #t) = ((simplify (Plus#t)))\"\n| \"simplify (Star#Qmark #t) = ((simplify (Plus#t)))\"\n| \"simplify (Qmark#(Char x) #t) = (Qmark#(Char x)#(simplify t))\"\n| \"simplify (Qmark#Plus #t) = (Qmark#(simplify (Plus#t)))\"\n| \"simplify (Qmark#Star #t) = ((simplify (Plus#t)))\"\n| \"simplify (Qmark#Qmark #t) = (Qmark#(simplify (Qmark#t)))\"\n| \"simplify ((Char x)#t) = ((Char x)#(simplify (t)))\"\n| \"simplify (h#t) = (h#(simplify t))\"\n\nvalue \"simplify [Star,Star,Plus,Qmark,(Char (CHR ''a'')), Qmark, Qmark, Plus] \"\n\n(* Le lemme de correction de la fonction simplify... Pour le prouver voir les lemmes intermédiaires à définir, plus bas. *)\nlemma \" accept l m = accept (simplify l) m \"\n  nitpick [timeout = 60]\n  quickcheck [tester=narrowing, size = 100, timeout = 10000]\n  oops\n\n\n(* Le lemme de minimalité dit que le pattern simplifié est le plus petit de tous les\n   patterns équivalents. Reformulé ici sous la forme de sa contraposée: s'il existe un pattern \n   plus petit que le pattern simplifié alors il n'est pas équivalent. Il n'est pas équivalent\n   si il existe au moins pour lequel l'acceptation par \"accept\" sera différente. *)\n\nlemma \"((length p)< (length (simplify p2))) \\<longrightarrow> (\\<exists> w. (accept p w) \\<noteq> (accept (simplify p2) w))\"\n (* La preuve de ce lemme n'est pas demandée. *)\n (* Utiliser le lemme suivant pour trouver des contre-exemples *)\n  oops\n\n(* Pour trouver (efficacement) des contre-exemples sur ce lemme de minimalité, on va limiter \n   la complexité des patterns considérés qu'on nommera \"basicPattern\" : Ici des patterns \n    avec *, ?, + et uniquement le caractère A *)\n\n\nfun basicPattern:: \"pattern \\<Rightarrow> bool\"\n  where\n\"basicPattern [] = True\" |\n\"basicPattern ((Char CHR ''A'') # r) = basicPattern r\" |\n\"basicPattern ((Char _) # r) = False\" |\n\"basicPattern (_ # r) = basicPattern r\"\n\n(* Le lemme de minimalité pour les basicPatterns *)\nlemma \"(basicPattern p) \\<longrightarrow> ((length p)< (length (simplify p2))) \\<longrightarrow> (\\<exists> w. (accept p w) \\<noteq> (accept (simplify p2) w))\"\n  quickcheck [tester=narrowing,size = 100, timeout=100]\n   (* nitpick ne trouve que des contre-exemples qui n'en sont pas *)\n  oops\n\n(* La directive d'export du code Scala *)\n(* A ne pas modifier! *)\ncode_reserved Scala\n  symbol \ncode_printing\n   type_constructor symbol \\<rightharpoonup> (Scala) \"Symbol\"\n   | constant Char \\<rightharpoonup> (Scala) \"Char\"\n   | constant Star \\<rightharpoonup> (Scala) \"Star\"\n   | constant Plus \\<rightharpoonup> (Scala) \"Plus\"\n   | constant Qmark \\<rightharpoonup> (Scala) \"Qmark\"\n\nexport_code simplify in Scala\n\n\n(* Pour prouver le lemme de correction, il vous sera nécessaire de prouver tous ces lemmes intermédiaires! *)\n\n(* Le pattern vide n'accepte que le mot vide *)\nlemma acceptVide: \"(accept [] w) \\<longrightarrow> w=[]\"\n  apply (induct w)\n  apply simp\n  by simp\n  \n(* Le seul pattern n'acceptant que le mot vide est le pattern vide *)\nlemma acceptVide2: \"(\\<forall> w. w\\<noteq>[] \\<longrightarrow> \\<not>(accept p w)) \\<longrightarrow> p=[]\"\n  apply (induct p)\n   apply auto\n  by (metis (full_types) accept.simps(1) accept.simps(2) accept.simps(5) accept.simps(7) accept.simps(9) list.simps(3) symbol.exhaust) \n\n\n(* Le seul pattern n'acceptant que le langage ? est ? *)\nlemma acceptQmark: \"(\\<forall> w. (accept [Qmark] w = (accept p w))) \\<longrightarrow> p=[Qmark]\"\n  apply (induct p arbitrary: w rule: simplify.induct)\n   apply simp\n  using accept.simps(1) accept.simps(6) apply blast\n  sorry\n\n(* Si le pattern commence par un caractère ou un point d'interrogation alors le mot accepté\n   commence forcément par un caractère (il ne peut être vide) *)\nlemma charAndQmarkRemoval: \"((x\\<noteq>Star) \\<and> (x\\<noteq> Plus) \\<and> (accept (x#r) m)) \\<longrightarrow> (\\<exists> x2 r2. m=x2#r2 \\<and> (accept r r2))\"\n  apply (induct m)\n   apply simp\n   apply (metis accept.simps(4) accept.simps(6) symbol.exhaust)\n  sorry\n  \n(* Si le pattern commence par une étoile, on peut soit l'oublier soit oublier le premier caractère du mot accepté *)\nlemma patternStartsWithStar: \"((accept (Star#r) m)) \\<longrightarrow> ((accept r m) \\<or> (\\<exists> x2 r2. m=x2#r2 \\<and> (accept (Star#r) r2)))\"\n  apply (induct m)\n   apply simp\n   apply (metis accept.simps(1) accept.simps(10) list.exhaust)\n\n  oops\n    \n(* On peut compléter à gauche n'importe quel pattern par une étoile *)\nlemma completePatternWithStar: \"(accept r m) \\<longrightarrow> (accept (Star#r) m)\"\n  apply (induct r)\n   apply simp\n  by (metis (full_types) accept.simps(10) accept.simps(11) list.exhaust)\n\n    \nlemma completePatternWithStar2: \"(accept r m) \\<longrightarrow> (accept (Star#r) (m1@m))\"\n  oops\n   \n\n(* On peut oublier une étoile dès qu'il y en a une juste après *)\nlemma forgetOneStar:\"(accept (Star#(Star#r)) w) = (accept (Star#r) w)\"\n  oops\n  \n\n(* Etoile suivie de point d'interrogation est équivalent à point d'interrogation étoile *)\nlemma starQmark:\"((accept (Star#(Qmark#r)) w) = (accept (Qmark#(Star#r)) w))\"\n  oops\n  \n(* Si deux patterns sont équivalents on peut les compléter à gauche... *)\n\n(* ... par une étoile *)\nlemma equivalentPatternStar:\"((\\<forall> w1. (accept p1 w1) = (accept p2 w1))) \\<longrightarrow> ((accept (Star#p1) w) = (accept (Star#p2) w))\"\n  oops\n    \n(* ... par un caractère (identique) *)\nlemma equivalentPatternChar:\"((\\<forall> w. (accept p1 w) = (accept p2 w))) \\<longrightarrow> ((accept ((Char x)#p1) w) = (accept ((Char x)#p2) w))\"\n  oops\n  \n(* ... par un point d'interrogation *)\nlemma equivalentPatternQmark:\"((\\<forall> w. (accept p1 w) = (accept p2 w))) \\<longrightarrow> ((accept (Qmark#p1) w) = (accept (Qmark#p2) w))\"\n  oops\n  \n(* Par un plus *)\nlemma equivalentPatternPlus:\"((\\<forall> w. (accept p1 w) = (accept p2 w))) \\<longrightarrow> ((accept (Plus#p1) w) = (accept (Plus#p2) w))\"\n  oops\n  \nlemma plusStarQmark:\"((accept (Star#(Qmark#r)) w) = (accept (Plus#r) w))\"\n  oops\n  \n\nlemma plusStarStar:\"((accept (Plus#(Star#r)) w) = (accept (Plus#r) w))\"\n  oops\n  \n\nlemma plusPlus1:\"((accept (Plus#(Plus#r)) w) = (accept (Qmark#(Plus#r)) w))\"\n  oops\n  \n(* Le lemme de correction final *)\nlemma correction:\"accept l m = accept (simplify l) m\"\n  oops\n\n  \nend\n ", "meta": {"author": "SaraKasim", "repo": "TP_Globs", "sha": "5e0949ac44f468bb3448e004830292938523acf3", "save_path": "github-repos/isabelle/SaraKasim-TP_Globs", "path": "github-repos/isabelle/SaraKasim-TP_Globs/TP_Globs-5e0949ac44f468bb3448e004830292938523acf3/tp5bis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7593150714679128}}
{"text": "(* Author: Tobias Nipkow, Daniel Stüwe *)\n\nsection \\<open>Three-Way Comparison\\<close>\n\ntheory Cmp\nimports MainRLT\nbegin\n\ndatatype cmp_val = LT | EQ | GT\n\ndefinition cmp :: \"'a:: linorder \\<Rightarrow> 'a \\<Rightarrow> cmp_val\" where\n\"cmp x y = (if x < y then LT else if x=y then EQ else GT)\"\n\nlemma \n    LT[simp]: \"cmp x y = LT \\<longleftrightarrow> x < y\"\nand EQ[simp]: \"cmp x y = EQ \\<longleftrightarrow> x = y\"\nand GT[simp]: \"cmp x y = GT \\<longleftrightarrow> x > y\"\nby (auto simp: cmp_def)\n\nlemma case_cmp_if[simp]: \"(case c of EQ \\<Rightarrow> e | LT \\<Rightarrow> l | GT \\<Rightarrow> g) =\n  (if c = LT then l else if c = GT then g else e)\"\nby(simp split: cmp_val.split)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Data_Structures/Cmp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.7593150689154259}}
{"text": "(* Title:      Involutive Residuated Structures\n   Author:     Victor Gomes\n   Maintainer: Victor Gomes <vborgesferreiragomes1 at sheffield.ac.uk>\n*)\n\nsection \\<open>Involutive Residuated Structures\\<close>\n\ntheory Involutive_Residuated\n  imports Residuated_Lattices\nbegin\n\nclass uminus' =\n  fixes uminus' :: \"'a \\<Rightarrow> 'a\" (\"-'' _\" [81] 80)\n\ntext \\<open>\n  Involutive posets is a structure where the double negation property holds for the \n  negation operations, and a Galois connection for negations exists.\n\\<close>\nclass involutive_order = order + uminus + uminus' +\n  assumes gn: \"x \\<le> -'y \\<longleftrightarrow> y \\<le> -x\"\n  and dn1[simp]: \"-'(-x) = x\"\n  and dn2[simp]: \"-(-'x) = x\"\n(* The involutive pair (-', -) is compatible with multiplication *)\nclass involutive_pogroupoid = order + times + involutive_order +\n  assumes ipg1: \"x\\<cdot>y \\<le> z \\<longleftrightarrow> (-z)\\<cdot>x \\<le> -y\"\n  and ipg2: \"x\\<cdot>y \\<le> z \\<longleftrightarrow> y\\<cdot>(-'z) \\<le> -'x\"\nbegin\n\nlemma neg_antitone: \"x \\<le> y \\<Longrightarrow> -y \\<le> -x\"\n  by (metis local.dn1 local.gn)\n\nlemma neg'_antitone: \"x \\<le> y \\<Longrightarrow> -'y \\<le> -'x\"\n  by (metis local.dn2 local.gn)\n  \nsubclass pogroupoid\nproof\n  fix x y z assume assm: \"x \\<le> y\"\n  show \"x \\<cdot> z \\<le> y \\<cdot> z\"\n    by (metis assm local.ipg2 local.order_refl local.order_trans neg'_antitone)\n  show \"z \\<cdot> x \\<le> z \\<cdot> y\"\n    by (metis assm local.dual_order.trans local.ipg1 local.order_refl neg_antitone)\nqed\n\nabbreviation inv_resl :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"inv_resl y x \\<equiv> -(x\\<cdot>(-'y))\"\n  \nabbreviation inv_resr :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"inv_resr x y \\<equiv> -'((-y)\\<cdot>x)\"\n\nsublocale residuated_pogroupoid _ _ _ inv_resl inv_resr\nproof\n  fix x y z\n  show \"(x \\<le> - (y \\<cdot> -' z)) = (x \\<cdot> y \\<le> z)\"\n    by (metis local.gn local.ipg2)\n  show \"(x \\<cdot> y \\<le> z) = (y \\<le> -' (- z \\<cdot> x))\"\n    by (metis local.gn local.ipg1)\nqed\n\nend\n\nclass division_order = order + residual_l_op + residual_r_op +\n  assumes div_galois: \"x \\<le> z \\<leftarrow> y \\<longleftrightarrow> y \\<le> x \\<rightarrow> z\"\n  \nclass involutive_division_order = division_order + involutive_order +\n  assumes contraposition: \"y \\<rightarrow> -x = -'y \\<leftarrow> x\"\n  \ncontext involutive_pogroupoid begin\n  \nsublocale involutive_division_order _ _ inv_resl inv_resr \nproof\n  fix x y z\n  show \"(x \\<le> - (y \\<cdot> -' z)) = (y \\<le> -' (- z \\<cdot> x))\"\n    by (metis local.gn local.ipg1 local.ipg2)\n  show \"-' (- (- x) \\<cdot> y) = - (x \\<cdot> -' (-' y))\"\n    by (metis local.dn1 local.dn2 local.eq_iff local.gn local.jipsen1l local.jipsen1r local.resl_galois local.resr_galois)\nqed\n\nlemma inv_resr_neg [simp]: \"inv_resr (-x) (-y) = inv_resl x y\"\n  by (metis local.contraposition local.dn1)\n\nlemma inv_resl_neg' [simp]: \"inv_resl (-'x) (-'y) = inv_resr x y\"\n  by (metis local.contraposition local.dn2)\n  \nlemma neg'_mult_resl: \"-'((-y)\\<cdot>(-x)) = inv_resl x (-'y)\"\n  by (metis inv_resr_neg local.dn2)\n  \nlemma neg_mult_resr: \"-((-'y)\\<cdot>(-'x)) = inv_resr (-x) y\"\n  by (metis neg'_mult_resl)\n  \nlemma resr_de_morgan1: \"-'(inv_resr (-y) (-x)) = -'(inv_resl y x)\"\n  by (metis local.dn1 neg_mult_resr)\n\nlemma resr_de_morgan2: \"-(inv_resl (-'x) (-'y)) = -(inv_resr x y)\"\n  by (metis inv_resl_neg')\n  \nend\n\ntext \\<open>\n  We prove that an involutive division poset is equivalent to an involutive po-groupoid\n  by a lemma to avoid cyclic definitions\n\\<close>\nlemma (in involutive_division_order) inv_pogroupoid: \n  \"class.involutive_pogroupoid (\\<lambda>x y. -(y \\<rightarrow> -'x)) uminus uminus' (\\<le>) (<)\"\nproof\n  fix x y z\n  have \"(- (y \\<rightarrow> -' x) \\<le> z) = (-z \\<le> -y \\<leftarrow> x)\"\n    by (metis local.contraposition local.dn1 local.dn2 local.gn local.div_galois)\n  thus \"(- (y \\<rightarrow> -' x) \\<le> z) = (- (x \\<rightarrow> -' (- z)) \\<le> - y)\"\n    by (metis local.contraposition local.div_galois local.dn1 local.dn2 local.gn)\n  moreover have \"(- (x \\<rightarrow> -' (- z)) \\<le> - y) = (- (-' z \\<rightarrow> -' y) \\<le> -' x)\"\n    apply (auto, metis local.contraposition local.div_galois local.dn1 local.dn2 local.gn)\n    by (metis local.contraposition local.div_galois local.dn1 local.dn2 local.gn)\n  ultimately show \"(- (y \\<rightarrow> -' x) \\<le> z) = (- (-' z \\<rightarrow> -' y) \\<le> -' x)\" \n    by metis\nqed\n\ncontext involutive_pogroupoid begin\n\ndefinition negation_constant :: \"'a \\<Rightarrow> bool\" where\n  \"negation_constant a \\<equiv> \\<forall>x. -'x = inv_resr x a \\<and> -x = inv_resl a x\"   \n  \ndefinition division_unit :: \"'a \\<Rightarrow> bool\" where\n  \"division_unit a \\<equiv> \\<forall>x. x = inv_resr a x \\<and> x = inv_resl x a\"\n  \nlemma neg_iff_div_unit: \"(\\<exists>a. negation_constant a) \\<longleftrightarrow> (\\<exists>b. division_unit b)\"\n  unfolding negation_constant_def division_unit_def\n  apply safe\n  apply (rule_tac x=\"-a\" in exI, auto)\n  apply (metis local.dn1 local.dn2)\n  apply (metis local.dn2)\n  apply (rule_tac x=\"-b\" in exI, auto)\n  apply (metis local.contraposition)\n  apply (metis local.dn2)\ndone\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Residuated_Lattices/Involutive_Residuated.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699185, "lm_q2_score": 0.855851154320682, "lm_q1q2_score": 0.7593150679939361}}
{"text": "theory Booleanos\nimports Main\nbegin\n\nsection \"Ejemplo de cálculo con booleanos\"\n\nvalue \"True \\<and> \\<not>False\"                        \n  (* da \"True\" :: \"bool\"*)\nvalue \"\\<not>(True \\<or> \\<not>False)\"                     \n  (* da \"False\" :: \"bool\"*)\nvalue \"(True \\<and> \\<not>False) = (True \\<or> \\<not>False)\"    \n  (* da \"True\" :: \"bool\"*)\nvalue \"True \\<and> \\<not>False \\<longleftrightarrow> True \\<or> \\<not>False\"      \n  (* da \"True\" :: \"bool\"*)\nvalue \"True \\<and> B\"                              \n  (* da B :: \"bool\"*)\nvalue \"True \\<or> B\"                              \n (* da \"True\" :: \"bool\"*)\n\nsection \"Ejemplo de definición no recursiva con definition\"\n\ntext {* (xor F G) se verifica si exactamente una de de las fórmulas F y\n  G es verdadera. Por ejemplo, \n     xor True True  = False\n     xor True False = True\n*}\ndefinition xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" \nwhere\n  \"xor F G \\<equiv> (F \\<noteq> G)\"\n    \nvalue \"xor True True\"  (* da False *)\nvalue \"xor True False\" (* da True *)\n  \nsection \"Ejemplo de definición con patrones usando fun\"\n\ntext {* (conjuncion F G) se verifica si F y G son verdaderas. Por\n  ejemplo,  \n     conjuncion True  True = True \n     conjuncion False True = False\n*} \nfun conjuncion :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" \nwhere\n  \"conjuncion True G  = G\"\n| \"conjuncion False _ = False\"  \n\nvalue \"conjuncion True  True\" (* da True *)\nvalue \"conjuncion False True\" (* da False *)\n\nsection \"Ejemplo de demostración por simplificación\" \n\nlemma \"conjuncion True B = B\" by simp\n\nsection \"Ejemplo de exportación a Haskell\"\n\nexport_code conjuncion in Haskell\n\n(* da\n  module Booleanos(conjuncion) where {\n\n  import Prelude ...\n  import qualified Prelude;\n\n  conjuncion :: Bool -> Bool -> Bool;\n  conjuncion True g = g;\n  conjuncion False uu = False;\n\n  }\n*)\n\nend\n", "meta": {"author": "jaalonso", "repo": "SLP", "sha": "799e829200ea0a4fbb526f47356135d98a190864", "save_path": "github-repos/isabelle/jaalonso-SLP", "path": "github-repos/isabelle/jaalonso-SLP/SLP-799e829200ea0a4fbb526f47356135d98a190864/Temas/Ejemplos/Booleanos.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.7593150642344142}}
{"text": "theory Ordinal\n  imports \"../GST_Features\"\nbegin\n\ncontext Ordinal begin\n(*Recalling signature and axioms of feature:*)\n(* - Types and axioms for \\<open>zero\\<close>, \\<open>succ\\<close> and \\<open>\\<omega>\\<close>: *)\nthm zero_typ succ_typ omega_typ zero_ax succ_ax omega_ax Limit_ax\n(* - Axioms specifying that \\<open><\\<close> is a well-order on the ordinals:*)  \nthm lt_trans lt_notsym lt_linear lt_induct\n\nlemmas zero_ord = zero_typ\nlemmas succ_ord = funE[OF succ_typ]\n\nsubsection \\<open>Initial Finite Ordinals\\<close>\n\nlemma zero_lt : \n  assumes \"b : Ord\"\n    shows \"\\<not> b < 0\"\n  using zero_ax assms \n  by auto\n\n(*Don't think we actually ever use this lemma,\n  it's just analagous to the one in ZF/Ordinal.thy*)\nlemmas zero_ltE = zero_lt [THEN notE]\n\n(* definition one   :: \"'d\" (\\<open>1\\<close>) where \"1 \\<equiv> succ 0\"\ndefinition two   :: \"'d\" (\\<open>2\\<close>) where \"2 \\<equiv> succ 1\"\ndefinition three :: \"'d\" (\\<open>3\\<close>) where \"3 \\<equiv> succ 2\"\nlemma one_ord   : \"1 : Ord\" unfolding one_def   by (rule succ_ord[OF zero_typ])\nlemma two_ord   : \"2 : Ord\" unfolding two_def   by (rule succ_ord[OF one_ord])\nlemma three_ord : \"3 : Ord\" unfolding three_def by (rule succ_ord[OF two_ord])\n *)\nsubsection \\<open>Well-Ordering properties of < \\<close>\n\nlemma trans :\n  assumes \"i : Ord\" \"j : Ord\" \"k : Ord\" \n      and \"i < j\" \"j < k\"\n    shows \"i < k\"\n  using lt_trans assms\n  by auto\n\nlemma asym :\n  assumes \"i : Ord\" \"j : Ord\"\n      and \"i < j\" \"\\<not> P \\<Longrightarrow> j < i\"\n    shows \"P\"\n  using lt_notsym assms\n  by auto\n\nlemma lt_reflE : \n  assumes \"i : Ord\" \n    shows \"i < i \\<Longrightarrow> P\"\n  using asym assms \n  by auto\n\ncorollary not_refl :\n  assumes \"i : Ord\"\n    shows \"\\<not> i < i\"\n  using lt_reflE[OF assms] \n  by auto\n\nlemma lt_neq :\n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"i < j \\<Longrightarrow> i \\<noteq> j\"\n  using lt_reflE assms \n  by auto\n\nlemma linear : \n  assumes \"i : Ord\" \"j : Ord\"\n  obtains (lt) \"i < j\" | (eq)  \"i = j\" | \"j < i\"\n  using assms lt_linear\n  by auto\n\nsubsection \\<open>succ - Successor operation\\<close>\n\nlemma succ_lt :\n  assumes \"i : Ord\"\n    shows \"i < succ i\"\n  using succ_ax assms by auto\n\nlemma succ_neq : \n  assumes \"i : Ord\"\n  shows \"i \\<noteq> succ i\"\n  by (rule lt_neq[OF assms succ_ord[OF assms] succ_lt[OF assms]])\n\nlemma succ_nonzero :\n  assumes \"i : Ord\"\n  shows \"succ i \\<noteq> 0\"\n  using succ_lt zero_lt assms by auto\n\nsubsection \\<open>leq - Less Than or Equal To\\<close>\n\nlemma leq_iff : \n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"i \\<le> j \\<longleftrightarrow> i < j \\<or> i = j\"\n  using succ_ax assms unfolding tall_def \n  by auto\n\nlemma leqI1 :\n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"i < j \\<Longrightarrow> i \\<le> j\"\n  using leq_iff[OF assms] \n  by auto\n\nlemma leqI2 :\n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"i = j \\<Longrightarrow> i \\<le> j\"\n  using leq_iff[OF assms] \n  by auto\n    \nlemma leqE :\n  assumes \"i : Ord\" \"j : Ord\" \"i \\<le> j\"\n      and \"i < j \\<Longrightarrow> P\" \"i = j \\<Longrightarrow> P\"\n    shows \"P\"\n  using leq_iff assms \n  by auto\n\nlemma leq_refl :\n  assumes \"i : Ord\"\n    shows \"i \\<le> i\"\n  using leqI2 assms \n  by auto\n\nlemma linear_lt_leq :\n  assumes \"i : Ord\" \"j : Ord\"\n  obtains (lt) \"i < j\" | (ge) \"j \\<le> i\"\n  by (rule linear[OF assms], use leqI1 leqI2 assms in auto)\n\nlemma linear_leq :\n  assumes \"i : Ord\" \"j : Ord\"\n  obtains (le) \"i \\<le> j\" | (ge) \"j \\<le> i\"\n  by (rule linear_lt_leq[OF assms], \n      blast intro: leqI1 leqI2 assms)\n\nlemma not_lt_leq : \n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"\\<not> i < j \\<Longrightarrow> j \\<le> i\"\n  by (rule linear_lt_leq[OF assms], auto)\n\nlemma leq_not_lt :\n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"j \\<le> i \\<Longrightarrow> \\<not> i < j\"\n  using leqE asym assms \n  by blast\n\nlemma not_leq_iff_lt :\n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"\\<not> i < j \\<longleftrightarrow> j \\<le> i\"\n  using not_lt_leq leq_not_lt assms \n  by auto  \n\nlemma neq_zero_lt :\n  assumes \"i : Ord\"\n    shows \"i \\<noteq> 0 \\<Longrightarrow> 0 < i\"\nproof -\n  have \"0 \\<le> i\" using zero_lt[OF assms] not_leq_iff_lt[OF assms zero_typ] by auto\n  assume \"i \\<noteq> 0\" \n  thus \"0 < i\" using leqE[OF zero_typ assms \\<open>0 \\<le> i\\<close>] by auto\nqed\n\nlemma leqCI : \n  assumes \"i : Ord\" \"j : Ord\"\n      and \"i \\<noteq> j \\<Longrightarrow> i < j\"\n    shows \"i \\<le> j\"\n  unfolding leq_iff[OF assms(1,2)] using assms(3) \n  by auto\n\nlemma leq_antisym : \n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"i \\<le> j \\<Longrightarrow> j \\<le> i \\<Longrightarrow> i = j\"\n  using leq_iff asym assms by auto\n\nlemma leq_zero_iff :\n  assumes \"i : Ord\"\n    shows \"i \\<le> 0 \\<longleftrightarrow> i = 0\"\n  unfolding leq_iff[OF \\<open>i : Ord\\<close> zero_typ] using zero_lt[OF \\<open>i : Ord\\<close>]\n  by auto\n\nlemma leq_zeroD :\n  assumes \"i : Ord\"\n    shows \"i \\<le> 0 \\<Longrightarrow> i = 0\"\n  by (rule leq_zero_iff[OF \\<open>i : Ord\\<close>, THEN iffD1])\n\nlemma zero_leq :\n  assumes \"i : Ord\"\n    shows \"0 \\<le> i\"\n  using not_lt_leq[OF _ zero_typ] zero_lt assms\n  by auto\n\nlemma zero_lt_iff : \n  assumes \"i : Ord\"\n    shows \"i \\<noteq> 0 \\<longleftrightarrow> 0 < i\"\n  using zero_leq[OF assms] leq_iff[OF zero_typ assms] not_refl[OF zero_typ] by auto\n\nlemma all_lt_leq : \n  assumes \"i : Ord\" \"j : Ord\"\n      and lt: \"\\<And>x. x : Ord \\<Longrightarrow> x < j \\<Longrightarrow> x < i\"  \n    shows \"j \\<le> i\"\n  using not_lt_leq not_refl assms \n  by auto\n\nlemma leq_succ_iff :\n  assumes \"i : Ord\" \"j : Ord\"\n    shows \"i \\<le> succ j \\<longleftrightarrow> i \\<le> j \\<or> i = succ j\"\n  unfolding leq_iff[OF \\<open>i : Ord\\<close> succ_ord[OF \\<open>j : Ord\\<close>]] \n  by rule\n\nlemma succ_leq : \n  assumes \"i : Ord\" \n  shows \"i \\<le> succ i\"\n  using succ_lt leqI1 assms succ_ord by auto\n\n\nsubsection \\<open>Transitivity Rules\\<close>\n\nlemma lt_trans1 : \n  assumes \"i : Ord\" \"j : Ord\" \"k : Ord\"\n  shows \"i \\<le> j \\<Longrightarrow> j < k \\<Longrightarrow> i < k\"\n  by (blast elim!: leqE[OF \\<open>i : Ord\\<close> \\<open>j : Ord\\<close>] \n            intro: trans[OF assms])\n\nlemma lt_trans2 : \n  assumes \"i : Ord\" \"j : Ord\" \"k : Ord\"\n  shows \"i < j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> i < k\"\n  by (blast elim!: leqE[OF \\<open>j : Ord\\<close> \\<open>k : Ord\\<close>] \n            intro: trans[OF assms])\n\nlemma leq_trans2 : \n  assumes \"i : Ord\" \"j : Ord\" \"k : Ord\"\n  shows \"i \\<le> j \\<Longrightarrow> j \\<le> k \\<Longrightarrow> i \\<le> k\"\n  by (blast intro: lt_trans1[OF \\<open>i : Ord\\<close> \\<open>j : Ord\\<close> succ_ord[OF \\<open>k : Ord\\<close>]])\n\nlemma succ_leqI :\n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"i<j \\<Longrightarrow> succ i \\<le> j\"\nproof (rule not_leq_iff_lt[OF \\<open>j : Ord\\<close> succ_ord[OF \\<open>i : Ord\\<close>], THEN iffD1])\n  assume \"i < j\" thus \"\\<not> j \\<le> i\" \n    using not_leq_iff_lt[OF \\<open>i : Ord\\<close> \\<open>j : Ord\\<close>] by auto\nqed\n\nlemma succ_leqE : \n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"succ i \\<le> j \\<Longrightarrow> i < j\"\nproof - \n  assume \"succ i \\<le> j\"\n  hence \"\\<not> j \\<le> i\" using not_leq_iff_lt[OF \\<open>j : Ord\\<close> succ_ord[OF \\<open>i : Ord\\<close>]] by auto\n  thus \"i < j\" using not_leq_iff_lt[OF \\<open>i : Ord\\<close> \\<open>j : Ord\\<close>] by auto\nqed\n\nlemma succ_leq_iff : \n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"succ i \\<le> j \\<longleftrightarrow> i < j\"\n  using succ_leqI succ_leqE assms\n  by auto\n\nlemma succ_leq_imp_leq : \n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"succ i \\<le> succ j \\<longleftrightarrow> i \\<le> j\"\n  using succ_leq_iff assms succ_ord \n  by auto\n\nlemma lt_zero_lt :\n  assumes \"i : Ord\" \"j : Ord\"\n  shows \"j < i \\<Longrightarrow> 0 < i\"\n  using lt_trans1[OF zero_typ \\<open>j : Ord\\<close> \\<open>i : Ord\\<close>]\n        zero_leq[OF \\<open>j : Ord\\<close>] \n  by auto\n\n\nsubsection \\<open>Limit Ordinals\\<close>\n\nlemma Limit_def : \n  \"Limit = (Ord \\<triangle> (\\<lambda>\\<mu>. 0 < \\<mu> \\<and> (\\<forall>j : Ord. j < \\<mu> \\<longrightarrow> succ j < \\<mu>)))\"\n  using Limit_ax by auto\n\nlemma limit_ord : \n  assumes \"\\<mu> : Limit\"\n    shows \"\\<mu> : Ord\"\n  using assms unfolding Limit_def \n  by unfold_typs\n\nlemma limit_lt_zero : \n  assumes \"\\<mu> : Limit\"\n    shows \"0 < \\<mu>\"\n  using assms unfolding Limit_def \n  by unfold_typs  \n\nlemma limit_nonzero : \n  assumes \"\\<mu> : Limit\"\n  shows \"\\<mu> \\<noteq> 0\"\n  using zero_lt_iff[OF limit_ord] limit_lt_zero assms\n  by auto\n\nlemma limit_lt_succ :\n  assumes \"\\<mu> : Limit\" \"\\<beta> : Ord\" \"\\<beta> < \\<mu>\"\n    shows \"succ \\<beta> < \\<mu>\"\n  using assms unfolding Limit_def by unfold_typs\n  \nlemma limit_succE : \n  assumes i:\"i : Ord\" and succ_i:\"succ i : Limit\"\n  shows \"P\"\nproof (rule ccontr)\n  have succ_i_ord:\"succ i : Ord\" by (rule limit_ord[OF succ_i])\n  hence \"\\<not> succ i < succ i\" by (rule not_refl)\n  thus \"False\" using limit_lt_succ[OF succ_i i leq_refl[OF i]] by auto\nqed\n\ndefinition nonLimit where [typdef] : \"nonLimit \\<equiv> Ord \\<triangle> (\\<lambda>i. \\<not> i : Limit)\"\n\nlemma nonLimitI : \n  assumes \"i : Ord\" \"\\<not> i : Limit\"\n  shows \"i : nonLimit\"\n  using assms by unfold_typs\n\nlemma nonLimitD :\n  assumes \"i : nonLimit\" \n  shows \"i : Ord \\<and> \\<not> i : Limit\"\n  using assms by unfold_typs\n\nlemmas nonLimitE = conjE[OF nonLimitD]\nlemma nonlimit_ord :\n  assumes i:\"i : nonLimit\"\n  shows \"i : Ord\"\n    using i by unfold_typs\n\nthm Ordinal.limit_succE Ordinal_axioms\nlemma not_succ_limit : \n  assumes i:\"i : Ord\"\n  shows \"\\<not> succ i : Limit\"\n  by (meson i limit_succE)\n  \n(* lemma limit_lt_one :\n  assumes \\<mu>:\"\\<mu> : Limit\"\n  shows \"1 < \\<mu>\"\n  unfolding one_def \n  by (rule limit_lt_succ[OF \\<mu> zero_typ limit_lt_zero[OF \\<mu>]]) *)\n\nlemma limit_succ_lt_iff : \n  assumes \\<mu>:\"\\<mu> : Limit\" and i:\"i : Ord\"\n  shows \"succ i < \\<mu> \\<longleftrightarrow> i < \\<mu>\"\nproof (rule)\n  assume \"succ i < \\<mu>\"\n  moreover have \"i < succ i\" by (rule succ_lt[OF i])\n  ultimately show \"i < \\<mu>\" using trans[OF i succ_ord[OF i] limit_ord[OF \\<mu>]] by auto\nnext\n  assume \"i < \\<mu>\" \n  thus \"succ i < \\<mu>\" by (rule limit_lt_succ[OF \\<mu> i]) \nqed\n\nlemma not_zero_limit : \"\\<not> 0 : Limit\"\n  using not_refl[OF zero_typ] unfolding Limit_def has_ty_def inter_ty_def \n  by auto\n\nlemmas zero_nonlimit = nonLimitI[OF zero_typ not_zero_limit]\n\nlemma succ_nonlimit : \n  assumes i:\"i : Ord\"\n  shows \"succ i : nonLimit\"\n  using nonLimitI not_succ_limit i succ_ord by auto\n\nlemma limit_leq_succD : \n  assumes \\<mu>:\"\\<mu> : Limit\" and i:\"i : Ord\"\n  shows \"\\<mu> \\<le> succ i \\<Longrightarrow> \\<mu> \\<le> i\"\n  by (rule leqE[OF limit_ord[OF \\<mu>] succ_ord[OF i]], \n      use not_succ_limit[OF i] \\<mu> in auto)\n      \nlemma limitI : \n  assumes \"i : Ord\" \n    and \"0 < i\" \"\\<forall>j : Ord. succ j \\<noteq> i\"\n  shows \"i : Limit\" unfolding Limit_def \nproof (rule intI[OF \\<open>i : Ord\\<close>], rule tyI, rule, rule \\<open>0 < i\\<close>, rule, rule)\n  fix j assume \"j : Ord\" \"j < i\"\n  hence \"\\<not> i \\<le> j\" \"succ j \\<noteq> i\" using leq_not_lt[OF _ \\<open>i : Ord\\<close>] assms(3) by auto\n  thus \"succ j < i\" using assms(3) linear[OF succ_ord[OF \\<open>j : Ord\\<close>] \\<open>i : Ord\\<close>] by auto\nqed\n\nlemma increasing_limitI : \n  assumes \\<mu>:\"\\<mu> : Ord\" and zero: \"0 < \\<mu>\" \n  and lt:\"\\<forall>i : Ord. i < \\<mu> \\<longrightarrow> (\\<exists>j : Ord. j < \\<mu> \\<and> i < j)\"\n  shows \"\\<mu> : Limit\"\n  unfolding Limit_def\nproof (rule Soft_Types.intI[OF \\<mu>], rule tyI, rule conjI[OF zero], auto)\n  fix i assume i:\"i : Ord\" and \"i < \\<mu>\" \n  then obtain j where j:\"j : Ord\" and \"j < \\<mu>\" \"i < j\" using lt by auto\n  show \"succ i < \\<mu>\" by (rule lt_trans1[OF succ_ord[OF i] j \\<mu> succ_leqI[OF i j \\<open>i < j\\<close>] \\<open>j < \\<mu>\\<close>])\nqed\n\nsubsection \\<open>Trichotomy of Ordinals, Transfinite Induction\\<close>\n\nlemma ord_cases_disj :\n  assumes \"i : Ord\"\n  shows \"i = 0 \\<or> (\\<exists>j : Ord. i = succ j) \\<or> i : Limit\"\n  using limitI neq_zero_lt assms \n  by auto \n\nlemma ord_cases : \n  assumes \"i : Ord\"\n  obtains (zero) \"i = 0\" \n        | (succ) j where \"j : Ord\" \"i = succ j\" \n        | (limit) \"i : Limit\"\n  using ord_cases_disj[OF assms]\n  by auto\n\nlemma trans_induct [consumes 1, case_names step] :\n  assumes \"i : Ord\" \"\\<And>j. j : Ord \\<Longrightarrow> (\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> P k) \\<Longrightarrow> P j\" \n  shows \"P i\"\n  using lt_induct assms unfolding tall_def \n  by auto \n\nlemma trans_induct3 [case_names zero succ lim, consumes 1] :\n  assumes \"i : Ord\" \n     and zero: \"P 0\" \n     and succ: \"\\<And>j. \\<lbrakk> j : Ord; P j \\<rbrakk> \\<Longrightarrow> P (succ j)\"\n     and lim : \"\\<And>\\<mu>. \\<lbrakk> \\<mu> : Limit; \\<forall>j : Ord. j < \\<mu> \\<longrightarrow> P j \\<rbrakk> \\<Longrightarrow> P \\<mu>\"\n   shows \"P i\" \nproof (rule trans_induct[OF \\<open>i : Ord\\<close>])\n  fix j assume j:\"j : Ord\" \n  and IH: \"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> P k\"\n  show \"P j\" proof (rule ord_cases[OF j])\n    assume \"j = 0\" thus \"P j\" using zero by auto\n  next\n    fix k assume \"k : Ord\" \"j = succ k\"\n    hence \"k < j\" using succ_lt by auto\n    thus \"P j\" using IH[OF \\<open>k : Ord\\<close>] succ[OF \\<open>k : Ord\\<close>] \\<open>j = succ k\\<close> by auto\n  next\n    assume \"j : Limit\"\n    thus \"P j\" using lim IH by auto\n  qed\nqed  \n\n\n\nsubsection \\<open>\\<omega> - The Smallest Limit Ordinal\\<close>\n\nthm omega_typ\n\nlemma omega_ord : \"\\<omega> : Ord\" by (rule limit_ord[OF omega_typ])\nlemma omega_zero : \"0 < \\<omega>\" by (rule limit_lt_zero[OF omega_typ])\n\nlemma omega_succ :\n  assumes i:\"i : Ord\" \n  shows \"i < \\<omega> \\<Longrightarrow> succ i < \\<omega>\"\n  by (rule limit_lt_succ[OF omega_typ i])\n\n(* lemma omega_one : \"1 < \\<omega>\" unfolding one_def\n  by (rule omega_succ[OF zero_typ omega_zero]) *)\n\nlemma omega_lt_cases :\n  assumes i:\"i : Ord\" and lt:\"i < \\<omega>\"\n  obtains (zero) \"i = 0\" | (succ) j where \"j : Ord\" \"i = succ j\"\nproof (rule ord_cases[OF i], auto, rule ccontr)\n  assume \"i : Limit\" hence \"\\<omega> < i\" \n    using lt_neq[OF i omega_ord lt] omega_ax by auto\n  thus \"False\" using lt asym[OF i omega_ord] by auto\nqed\n\nlemma omega_lt_not_limit :\n  assumes i:\"i : Ord\" and lt:\"i < \\<omega>\" \n  shows \"\\<not> i : Limit\"\n  by (rule omega_lt_cases[OF i lt], \n      use not_zero_limit not_succ_limit in auto)\n\n\nsubsection \\<open>Least Ordinal operator\\<close>\n\ndefinition least :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a\" (binder \\<open>least \\<close> 10)\n  where \"least x. P x \\<equiv> \\<iota> i. i : Ord \\<and> P i \\<and> (\\<forall>j : Ord. j < i \\<longrightarrow> \\<not> P j) else Ordinal_default\"\n\nlemma least_eq :\n  assumes i:\"i : Ord\" and \"P i\"\n    and lt:\"\\<And>j. j : Ord \\<Longrightarrow> j < i \\<Longrightarrow> \\<not> P j\"\n  shows \"(least i. P i) = i\" unfolding least_def\nproof (rule the_def_eq, use assms in auto)\n  fix k assume k:\"k : Ord\" and \"P k\" and j:\"\\<forall>j. j : Ord \\<longrightarrow> j < k \\<longrightarrow> \\<not> P j\"\n  show \"k = i\" by (rule linear[OF k i], use i k \\<open>P i\\<close> \\<open>P k\\<close> lt j in auto)\nqed\n\nlemma least_ord : \n  assumes i:\"i : Ord\"\n  shows \"P i \\<Longrightarrow> (least i. P i) : Ord\"\nproof (induct rule: trans_induct[OF i])\n  fix j assume j:\"j : Ord\" and \"P j\"\n  and k:\"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> P k \\<Longrightarrow> (least i. P i) : Ord\"\n  show \"(least i. P i) : Ord\"\n  proof (cases \"(least i. P i) : Ord\")\n    case True \n    then show ?thesis .\n  next\n    case False\n    hence \"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> \\<not> P k\" using k by auto\n    hence \"(least i. P i) = j\" using k least_eq[OF j, of P, OF \\<open>P j\\<close>] by auto\n    then show ?thesis using \\<open>j : Ord\\<close> by auto\n  qed\nqed\n\n\nlemma leastI : \n  assumes i:\"i : Ord\"\n  shows \"P i \\<Longrightarrow> P (least i. P i)\"\nproof (induct rule: trans_induct[OF i])\n  fix j assume j:\"j : Ord\" and \"P j\"\n  and k:\"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> P k \\<Longrightarrow> P (least i. P i)\"\n  show \"P (least i. P i)\"\n  proof (cases \"P (least i. P i)\")\n    case True \n    then show ?thesis .\n  next\n    case False\n    hence \"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> \\<not> P k\" using k by auto\n    hence \"(least i. P i) = j\" using k least_eq[OF j, of P, OF \\<open>P j\\<close>] by auto\n    then show ?thesis using \\<open>P j\\<close> by auto\n  qed\nqed\n\n(*MESSY PROOF: needs tidying*)\nlemma least_leqI :\n  assumes i:\"i : Ord\"\n  shows \"P i \\<Longrightarrow> (least i. P i) \\<le> i\"\nproof (induct rule: trans_induct[OF i]) \n  fix j assume j:\"j : Ord\" and \"P j\"\n  and k : \"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> P k \\<Longrightarrow> (least i. P i) \\<le> k\"\n  show \"(least i. P i) \\<le> j\" \n  proof (cases \"(least i. P i) \\<le> j\")\n    case True\n    then show ?thesis .\n  next\n    case False\n    hence kj: \"\\<And>k. k : Ord \\<Longrightarrow> k < j \\<Longrightarrow> \\<not> (least i. P i) \\<le> j\" using k by auto\n    have \"(least i. P i) = j\" \n    proof (rule least_eq[OF j, of P, OF \\<open>P j\\<close>])\n      fix k assume \"k : Ord\" \"k < j\" \n      hence lj:\"\\<not> (least i. P i) \\<le> j\" using kj by auto\n      show \"\\<not> P k\" proof\n        assume \"P k\" hence l:\"(least i. P i) : Ord\" using least_ord[OF \\<open>k : Ord\\<close>] by auto\n        have pk:\"(least i. P i) \\<le> k\" using k[OF \\<open>k : Ord\\<close> \\<open>k < j\\<close> \\<open>P k\\<close>] by auto\n        show \"False\" using leqI1[OF l j lt_trans1[OF l \\<open>k : Ord\\<close> j pk \\<open>k < j\\<close>]] lj by auto\n      qed\n    qed\n    then show ?thesis using leq_refl[OF j] by auto\n  qed\nqed\n\nlemma lt_leastE :\n  assumes i:\"i : Ord\" and \"P i\"\n    and lt : \"i < (least i. P i)\"\n  shows \"Q\"\n  using lt_trans2[OF i least_ord[OF i, of P, OF \\<open>P i\\<close>] i lt least_leqI[OF i, of P, OF \\<open>P i\\<close>]]  \n        not_refl[OF i]\n  by auto\n\n(*Easier to apply than leastI: conclusion has only one occurrence of P*)\nlemma leastI2 :\n  assumes i:\"i : Ord\" and \"P i\"\n  and lt: \"\\<And>j. j : Ord \\<Longrightarrow> P j \\<Longrightarrow> Q j\"\n  shows \"Q (least j. P j)\"\n  by (rule lt[OF least_ord[of i P, OF i \\<open>P i\\<close>] \n                 leastI[of i P, OF i \\<open>P i\\<close>]])\n\nlemma least_default :\n  \"\\<not> (\\<exists>i : Ord. P i) \\<Longrightarrow> (least i. P i) = Ordinal_default\"\n  unfolding least_def tex_def\n  by (rule the_def_default, auto)\n\n\nsubsection \\<open>Ordinal case operator\\<close>\n\ndefinition caseof_ord :: \\<open>['a, 'a, 'a, 'a] \\<Rightarrow> 'a\\<close>\n  where \"caseof_ord z s l i \\<equiv>\n    if i = 0 then z else \n      if (\\<exists>j : Ord. i = succ j) then s else \n        if i : Limit then l else Ordinal_default\"\n        \nlemma case_ord_zero :\n  \"caseof_ord b f g 0 = b\"\n  unfolding caseof_ord_def by auto\n\nlemma case_ord_succ :\n  assumes j:\"j : Ord\"\n  shows \"caseof_ord b s l (succ j) = s\"\n  unfolding caseof_ord_def \n  using succ_nonzero[OF j] not_succ_limit[OF j] j by auto\n\nlemma case_ord_lim :\n  assumes u:\"u : Limit\"\n  shows \"caseof_ord b s l u = l\"\n  unfolding caseof_ord_def \n  using limit_nonzero u not_succ_limit by auto\n\nlemma case_ordE :\n  assumes i: \"i : Ord\" and\n    \"P z\" \"P s\" \"P l\"\n  shows \"P (caseof_ord z s l i)\"\n  using ord_cases[OF i] case_ord_zero case_ord_succ case_ord_lim assms\n  by metis\nend\n\nML \\<open>fun mk_ord_thm z _ 0 = z\n      | mk_ord_thm z s n = s OF [mk_ord_thm z s (n-1)]\\<close>\n\nML \\<open>fun n_ord_thm 0 = @{thm zero_ord}\n      | n_ord_thm n = @{thm succ_ord} OF [n_ord_thm (n-1)]\\<close>\n\nML \\<open>fun omega_lt_thm 0 = @{thm omega_zero}\n      | omega_lt_thm n = @{thm omega_succ} OF [n_ord_thm (n-1), omega_lt_thm (n-1)]\\<close>\n\nML \\<open>fun leq_thm (i,j) =\n      if j < i then error \"j<i\" else\n      if i = j \n      then @{thm leq_refl} OF [n_ord_thm i]\n      else if i+1 = j \n        then @{thm succ_leq} OF [n_ord_thm i]\n        else @{thm leq_trans2} OF [n_ord_thm i, n_ord_thm (i+1), n_ord_thm j, \n                  leq_thm (i,i+1), leq_thm (i+1,j)]\\<close>\n\nlemmas if_P_trans = HOL.trans[OF if_not_P]\n\nML \\<open>fun neq_thm (i,j) = not_sym OF [@{thm lt_neq} OF [n_ord_thm j, n_ord_thm i, leq_thm (j,i-1)]] \\<close>\nML \\<open>fun if_thm' _ 0 = @{thm if_P} OF [@{thm refl}]\n      | if_thm' i k = @{thm if_P_trans} OF [neq_thm (i,i-k), if_thm' i (k-1)]\\<close>\nML \\<open>fun if_thm i = if_thm' i i\\<close>\n\nend", "meta": {"author": "ultra-group", "repo": "isabelle-gst", "sha": "e0ccdde0105eac05f3f4bbccdd58a9860e642eca", "save_path": "github-repos/isabelle/ultra-group-isabelle-gst", "path": "github-repos/isabelle/ultra-group-isabelle-gst/isabelle-gst-e0ccdde0105eac05f3f4bbccdd58a9860e642eca/src/Ordinal/Ordinal.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.8558511524823265, "lm_q1q2_score": 0.7593150638104514}}
{"text": "(*  Title:      HOL/Matrix_LP/SparseMatrix.thy\n    Author:     Steven Obua\n*)\n\ntheory SparseMatrix\nimports Matrix\nbegin\n\ntype_synonym 'a spvec = \"(nat * 'a) list\"\ntype_synonym 'a spmat = \"'a spvec spvec\"\n\ndefinition sparse_row_vector :: \"('a::ab_group_add) spvec \\<Rightarrow> 'a matrix\"\n  where \"sparse_row_vector arr = foldl (% m x. m + (singleton_matrix 0 (fst x) (snd x))) 0 arr\"\n\ndefinition sparse_row_matrix :: \"('a::ab_group_add) spmat \\<Rightarrow> 'a matrix\"\n  where \"sparse_row_matrix arr = foldl (% m r. m + (move_matrix (sparse_row_vector (snd r)) (int (fst r)) 0)) 0 arr\"\n\ncode_datatype sparse_row_vector sparse_row_matrix\n\nlemma sparse_row_vector_empty [simp]: \"sparse_row_vector [] = 0\"\n  by (simp add: sparse_row_vector_def)\n\nlemma sparse_row_matrix_empty [simp]: \"sparse_row_matrix [] = 0\"\n  by (simp add: sparse_row_matrix_def)\n\nlemmas [code] = sparse_row_vector_empty [symmetric]\n\nlemma foldl_distrstart: \"! a x y. (f (g x y) a = g x (f y a)) \\<Longrightarrow> (foldl f (g x y) l = g x (foldl f y l))\"\n  by (induct l arbitrary: x y, auto)\n\nlemma sparse_row_vector_cons[simp]:\n  \"sparse_row_vector (a # arr) = (singleton_matrix 0 (fst a) (snd a)) + (sparse_row_vector arr)\"\n  apply (induct arr)\n  apply (auto simp add: sparse_row_vector_def)\n  apply (simp add: foldl_distrstart [of \"\\<lambda>m x. m + singleton_matrix 0 (fst x) (snd x)\" \"\\<lambda>x m. singleton_matrix 0 (fst x) (snd x) + m\"])\n  done\n\nlemma sparse_row_vector_append[simp]:\n  \"sparse_row_vector (a @ b) = (sparse_row_vector a) + (sparse_row_vector b)\"\n  by (induct a) auto\n\nlemma nrows_spvec[simp]: \"nrows (sparse_row_vector x) <= (Suc 0)\"\n  apply (induct x)\n  apply (simp_all add: add_nrows)\n  done\n\nlemma sparse_row_matrix_cons: \"sparse_row_matrix (a#arr) = ((move_matrix (sparse_row_vector (snd a)) (int (fst a)) 0)) + sparse_row_matrix arr\"\n  apply (induct arr)\n  apply (auto simp add: sparse_row_matrix_def)\n  apply (simp add: foldl_distrstart[of \"\\<lambda>m x. m + (move_matrix (sparse_row_vector (snd x)) (int (fst x)) 0)\" \n    \"% a m. (move_matrix (sparse_row_vector (snd a)) (int (fst a)) 0) + m\"])\n  done\n\nlemma sparse_row_matrix_append: \"sparse_row_matrix (arr@brr) = (sparse_row_matrix arr) + (sparse_row_matrix brr)\"\n  apply (induct arr)\n  apply (auto simp add: sparse_row_matrix_cons)\n  done\n\nprimrec sorted_spvec :: \"'a spvec \\<Rightarrow> bool\"\nwhere\n  \"sorted_spvec [] = True\"\n| sorted_spvec_step: \"sorted_spvec (a#as) = (case as of [] \\<Rightarrow> True | b#bs \\<Rightarrow> ((fst a < fst b) & (sorted_spvec as)))\" \n\nprimrec sorted_spmat :: \"'a spmat \\<Rightarrow> bool\"\nwhere\n  \"sorted_spmat [] = True\"\n| \"sorted_spmat (a#as) = ((sorted_spvec (snd a)) & (sorted_spmat as))\"\n\ndeclare sorted_spvec.simps [simp del]\n\nlemma sorted_spvec_empty[simp]: \"sorted_spvec [] = True\"\nby (simp add: sorted_spvec.simps)\n\nlemma sorted_spvec_cons1: \"sorted_spvec (a#as) \\<Longrightarrow> sorted_spvec as\"\napply (induct as)\napply (auto simp add: sorted_spvec.simps)\ndone\n\nlemma sorted_spvec_cons2: \"sorted_spvec (a#b#t) \\<Longrightarrow> sorted_spvec (a#t)\"\napply (induct t)\napply (auto simp add: sorted_spvec.simps)\ndone\n\nlemma sorted_spvec_cons3: \"sorted_spvec(a#b#t) \\<Longrightarrow> fst a < fst b\"\napply (auto simp add: sorted_spvec.simps)\ndone\n\nlemma sorted_sparse_row_vector_zero[rule_format]: \"m <= n \\<Longrightarrow> sorted_spvec ((n,a)#arr) \\<longrightarrow> Rep_matrix (sparse_row_vector arr) j m = 0\"\napply (induct arr)\napply (auto)\napply (frule sorted_spvec_cons2,simp)+\napply (frule sorted_spvec_cons3, simp)\ndone\n\nlemma sorted_sparse_row_matrix_zero[rule_format]: \"m <= n \\<Longrightarrow> sorted_spvec ((n,a)#arr) \\<longrightarrow> Rep_matrix (sparse_row_matrix arr) m j = 0\"\n  apply (induct arr)\n  apply (auto)\n  apply (frule sorted_spvec_cons2, simp)\n  apply (frule sorted_spvec_cons3, simp)\n  apply (simp add: sparse_row_matrix_cons)\n  done\n\nprimrec minus_spvec :: \"('a::ab_group_add) spvec \\<Rightarrow> 'a spvec\"\nwhere\n  \"minus_spvec [] = []\"\n| \"minus_spvec (a#as) = (fst a, -(snd a))#(minus_spvec as)\"\n\nprimrec abs_spvec :: \"('a::lattice_ab_group_add_abs) spvec \\<Rightarrow> 'a spvec\"\nwhere\n  \"abs_spvec [] = []\"\n| \"abs_spvec (a#as) = (fst a, \\<bar>snd a\\<bar>)#(abs_spvec as)\"\n\nlemma sparse_row_vector_minus: \n  \"sparse_row_vector (minus_spvec v) = - (sparse_row_vector v)\"\n  apply (induct v)\n  apply (simp_all add: sparse_row_vector_cons)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply simp\n  done\n\ninstance matrix :: (lattice_ab_group_add_abs) lattice_ab_group_add_abs\n  apply standard\n  unfolding abs_matrix_def\n  apply rule\n  done\n  (*FIXME move*)\n\nlemma sparse_row_vector_abs:\n  \"sorted_spvec (v :: 'a::lattice_ring spvec) \\<Longrightarrow> sparse_row_vector (abs_spvec v) = \\<bar>sparse_row_vector v\\<bar>\"\n  apply (induct v)\n  apply simp_all\n  apply (frule_tac sorted_spvec_cons1, simp)\n  apply (simp only: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply auto\n  apply (subgoal_tac \"Rep_matrix (sparse_row_vector v) 0 a = 0\")\n  apply (simp)\n  apply (rule sorted_sparse_row_vector_zero)\n  apply auto\n  done\n\nlemma sorted_spvec_minus_spvec:\n  \"sorted_spvec v \\<Longrightarrow> sorted_spvec (minus_spvec v)\"\n  apply (induct v)\n  apply (simp)\n  apply (frule sorted_spvec_cons1, simp)\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_spvec_abs_spvec:\n  \"sorted_spvec v \\<Longrightarrow> sorted_spvec (abs_spvec v)\"\n  apply (induct v)\n  apply (simp)\n  apply (frule sorted_spvec_cons1, simp)\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n  \ndefinition \"smult_spvec y = map (% a. (fst a, y * snd a))\"  \n\nlemma smult_spvec_empty[simp]: \"smult_spvec y [] = []\"\n  by (simp add: smult_spvec_def)\n\nlemma smult_spvec_cons: \"smult_spvec y (a#arr) = (fst a, y * (snd a)) # (smult_spvec y arr)\"\n  by (simp add: smult_spvec_def)\n\nfun addmult_spvec :: \"('a::ring) \\<Rightarrow> 'a spvec \\<Rightarrow> 'a spvec \\<Rightarrow> 'a spvec\"\nwhere\n  \"addmult_spvec y arr [] = arr\"\n| \"addmult_spvec y [] brr = smult_spvec y brr\"\n| \"addmult_spvec y ((i,a)#arr) ((j,b)#brr) = (\n    if i < j then ((i,a)#(addmult_spvec y arr ((j,b)#brr))) \n    else (if (j < i) then ((j, y * b)#(addmult_spvec y ((i,a)#arr) brr))\n    else ((i, a + y*b)#(addmult_spvec y arr brr))))\"\n(* Steven used termination \"measure (% (y, a, b). length a + (length b))\" *)\n\nlemma addmult_spvec_empty1[simp]: \"addmult_spvec y [] a = smult_spvec y a\"\n  by (induct a) auto\n\nlemma addmult_spvec_empty2[simp]: \"addmult_spvec y a [] = a\"\n  by (induct a) auto\n\nlemma sparse_row_vector_map: \"(! x y. f (x+y) = (f x) + (f y)) \\<Longrightarrow> (f::'a\\<Rightarrow>('a::lattice_ring)) 0 = 0 \\<Longrightarrow> \n  sparse_row_vector (map (% x. (fst x, f (snd x))) a) = apply_matrix f (sparse_row_vector a)\"\n  apply (induct a)\n  apply (simp_all add: apply_matrix_add)\n  done\n\nlemma sparse_row_vector_smult: \"sparse_row_vector (smult_spvec y a) = scalar_mult y (sparse_row_vector a)\"\n  apply (induct a)\n  apply (simp_all add: smult_spvec_cons scalar_mult_add)\n  done\n\nlemma sparse_row_vector_addmult_spvec: \"sparse_row_vector (addmult_spvec (y::'a::lattice_ring) a b) = \n  (sparse_row_vector a) + (scalar_mult y (sparse_row_vector b))\"\n  apply (induct y a b rule: addmult_spvec.induct)\n  apply (simp add: scalar_mult_add smult_spvec_cons sparse_row_vector_smult singleton_matrix_add)+\n  done\n\nlemma sorted_smult_spvec: \"sorted_spvec a \\<Longrightarrow> sorted_spvec (smult_spvec y a)\"\n  apply (auto simp add: smult_spvec_def)\n  apply (induct a)\n  apply (auto simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_spvec_addmult_spvec_helper: \"\\<lbrakk>sorted_spvec (addmult_spvec y ((a, b) # arr) brr); aa < a; sorted_spvec ((a, b) # arr); \n  sorted_spvec ((aa, ba) # brr)\\<rbrakk> \\<Longrightarrow> sorted_spvec ((aa, y * ba) # addmult_spvec y ((a, b) # arr) brr)\"  \n  apply (induct brr)\n  apply (auto simp add: sorted_spvec.simps)\n  done\n\nlemma sorted_spvec_addmult_spvec_helper2: \n \"\\<lbrakk>sorted_spvec (addmult_spvec y arr ((aa, ba) # brr)); a < aa; sorted_spvec ((a, b) # arr); sorted_spvec ((aa, ba) # brr)\\<rbrakk>\n       \\<Longrightarrow> sorted_spvec ((a, b) # addmult_spvec y arr ((aa, ba) # brr))\"\n  apply (induct arr)\n  apply (auto simp add: smult_spvec_def sorted_spvec.simps)\n  done\n\nlemma sorted_spvec_addmult_spvec_helper3[rule_format]:\n  \"sorted_spvec (addmult_spvec y arr brr) \\<longrightarrow> sorted_spvec ((aa, b) # arr) \\<longrightarrow> sorted_spvec ((aa, ba) # brr)\n     \\<longrightarrow> sorted_spvec ((aa, b + y * ba) # (addmult_spvec y arr brr))\"\n  apply (induct y arr brr rule: addmult_spvec.induct)\n  apply (simp_all add: sorted_spvec.simps smult_spvec_def split:list.split)\n  done\n\nlemma sorted_addmult_spvec: \"sorted_spvec a \\<Longrightarrow> sorted_spvec b \\<Longrightarrow> sorted_spvec (addmult_spvec y a b)\"\n  apply (induct y a b rule: addmult_spvec.induct)\n  apply (simp_all add: sorted_smult_spvec)\n  apply (rule conjI, intro strip)\n  apply (case_tac \"~(i < j)\")\n  apply (simp_all)\n  apply (frule_tac as=brr in sorted_spvec_cons1)\n  apply (simp add: sorted_spvec_addmult_spvec_helper)\n  apply (intro strip | rule conjI)+\n  apply (frule_tac as=arr in sorted_spvec_cons1)\n  apply (simp add: sorted_spvec_addmult_spvec_helper2)\n  apply (intro strip)\n  apply (frule_tac as=arr in sorted_spvec_cons1)\n  apply (frule_tac as=brr in sorted_spvec_cons1)\n  apply (simp)\n  apply (simp_all add: sorted_spvec_addmult_spvec_helper3)\n  done\n\nfun mult_spvec_spmat :: \"('a::lattice_ring) spvec \\<Rightarrow> 'a spvec \\<Rightarrow> 'a spmat  \\<Rightarrow> 'a spvec\"\nwhere\n  \"mult_spvec_spmat c [] brr = c\"\n| \"mult_spvec_spmat c arr [] = c\"\n| \"mult_spvec_spmat c ((i,a)#arr) ((j,b)#brr) = (\n     if (i < j) then mult_spvec_spmat c arr ((j,b)#brr)\n     else if (j < i) then mult_spvec_spmat c ((i,a)#arr) brr \n     else mult_spvec_spmat (addmult_spvec a c b) arr brr)\"\n\nlemma sparse_row_mult_spvec_spmat[rule_format]: \"sorted_spvec (a::('a::lattice_ring) spvec) \\<longrightarrow> sorted_spvec B \\<longrightarrow> \n  sparse_row_vector (mult_spvec_spmat c a B) = (sparse_row_vector c) + (sparse_row_vector a) * (sparse_row_matrix B)\"\nproof -\n  have comp_1: \"!! a b. a < b \\<Longrightarrow> Suc 0 <= nat ((int b)-(int a))\" by arith\n  have not_iff: \"!! a b. a = b \\<Longrightarrow> (~ a) = (~ b)\" by simp\n  have max_helper: \"!! a b. ~ (a <= max (Suc a) b) \\<Longrightarrow> False\"\n    by arith\n  {\n    fix a \n    fix v\n    assume a:\"a < nrows(sparse_row_vector v)\"\n    have b:\"nrows(sparse_row_vector v) <= 1\" by simp\n    note dummy = less_le_trans[of a \"nrows (sparse_row_vector v)\" 1, OF a b]   \n    then have \"a = 0\" by simp\n  }\n  note nrows_helper = this\n  show ?thesis\n    apply (induct c a B rule: mult_spvec_spmat.induct)\n    apply simp+\n    apply (rule conjI)\n    apply (intro strip)\n    apply (frule_tac as=brr in sorted_spvec_cons1)\n    apply (simp add: algebra_simps sparse_row_matrix_cons)\n    apply (simplesubst Rep_matrix_zero_imp_mult_zero) \n    apply (simp)\n    apply (rule disjI2)\n    apply (intro strip)\n    apply (subst nrows)\n    apply (rule  order_trans[of _ 1])\n    apply (simp add: comp_1)+\n    apply (subst Rep_matrix_zero_imp_mult_zero)\n    apply (intro strip)\n    apply (case_tac \"k <= j\")\n    apply (rule_tac m1 = k and n1 = i and a1 = a in ssubst[OF sorted_sparse_row_vector_zero])\n    apply (simp_all)\n    apply (rule disjI2)\n    apply (rule nrows)\n    apply (rule order_trans[of _ 1])\n    apply (simp_all add: comp_1)\n    \n    apply (intro strip | rule conjI)+\n    apply (frule_tac as=arr in sorted_spvec_cons1)\n    apply (simp add: algebra_simps)\n    apply (subst Rep_matrix_zero_imp_mult_zero)\n    apply (simp)\n    apply (rule disjI2)\n    apply (intro strip)\n    apply (simp add: sparse_row_matrix_cons)\n    apply (case_tac \"i <= j\")  \n    apply (erule sorted_sparse_row_matrix_zero)  \n    apply (simp_all)\n    apply (intro strip)\n    apply (case_tac \"i=j\")\n    apply (simp_all)\n    apply (frule_tac as=arr in sorted_spvec_cons1)\n    apply (frule_tac as=brr in sorted_spvec_cons1)\n    apply (simp add: sparse_row_matrix_cons algebra_simps sparse_row_vector_addmult_spvec)\n    apply (rule_tac B1 = \"sparse_row_matrix brr\" in ssubst[OF Rep_matrix_zero_imp_mult_zero])\n    apply (auto)\n    apply (rule sorted_sparse_row_matrix_zero)\n    apply (simp_all)\n    apply (rule_tac A1 = \"sparse_row_vector arr\" in ssubst[OF Rep_matrix_zero_imp_mult_zero])\n    apply (auto)\n    apply (rule_tac m=k and n = j and a = a and arr=arr in sorted_sparse_row_vector_zero)\n    apply (simp_all)\n    apply (drule nrows_notzero)\n    apply (drule nrows_helper)\n    apply (arith)\n    \n    apply (subst Rep_matrix_inject[symmetric])\n    apply (rule ext)+\n    apply (simp)\n    apply (subst Rep_matrix_mult)\n    apply (rule_tac j1=j in ssubst[OF foldseq_almostzero])\n    apply (simp_all)\n    apply (intro strip, rule conjI)\n    apply (intro strip)\n    apply (drule_tac max_helper)\n    apply (simp)\n    apply (auto)\n    apply (rule zero_imp_mult_zero)\n    apply (rule disjI2)\n    apply (rule nrows)\n    apply (rule order_trans[of _ 1])\n    apply (simp)\n    apply (simp)\n    done\nqed\n\nlemma sorted_mult_spvec_spmat[rule_format]: \n  \"sorted_spvec (c::('a::lattice_ring) spvec) \\<longrightarrow> sorted_spmat B \\<longrightarrow> sorted_spvec (mult_spvec_spmat c a B)\"\n  apply (induct c a B rule: mult_spvec_spmat.induct)\n  apply (simp_all add: sorted_addmult_spvec)\n  done\n\nprimrec mult_spmat :: \"('a::lattice_ring) spmat \\<Rightarrow> 'a spmat \\<Rightarrow> 'a spmat\"\nwhere\n  \"mult_spmat [] A = []\"\n| \"mult_spmat (a#as) A = (fst a, mult_spvec_spmat [] (snd a) A)#(mult_spmat as A)\"\n\nlemma sparse_row_mult_spmat: \n  \"sorted_spmat A \\<Longrightarrow> sorted_spvec B \\<Longrightarrow>\n   sparse_row_matrix (mult_spmat A B) = (sparse_row_matrix A) * (sparse_row_matrix B)\"\n  apply (induct A)\n  apply (auto simp add: sparse_row_matrix_cons sparse_row_mult_spvec_spmat algebra_simps move_matrix_mult)\n  done\n\nlemma sorted_spvec_mult_spmat[rule_format]:\n  \"sorted_spvec (A::('a::lattice_ring) spmat) \\<longrightarrow> sorted_spvec (mult_spmat A B)\"\n  apply (induct A)\n  apply (auto)\n  apply (drule sorted_spvec_cons1, simp)\n  apply (case_tac A)\n  apply (auto simp add: sorted_spvec.simps)\n  done\n\nlemma sorted_spmat_mult_spmat:\n  \"sorted_spmat (B::('a::lattice_ring) spmat) \\<Longrightarrow> sorted_spmat (mult_spmat A B)\"\n  apply (induct A)\n  apply (auto simp add: sorted_mult_spvec_spmat) \n  done\n\n\nfun add_spvec :: \"('a::lattice_ab_group_add) spvec \\<Rightarrow> 'a spvec \\<Rightarrow> 'a spvec\"\nwhere\n(* \"measure (% (a, b). length a + (length b))\" *)\n  \"add_spvec arr [] = arr\"\n| \"add_spvec [] brr = brr\"\n| \"add_spvec ((i,a)#arr) ((j,b)#brr) = (\n     if i < j then (i,a)#(add_spvec arr ((j,b)#brr)) \n     else if (j < i) then (j,b) # add_spvec ((i,a)#arr) brr\n     else (i, a+b) # add_spvec arr brr)\"\n\nlemma add_spvec_empty1[simp]: \"add_spvec [] a = a\"\nby (cases a, auto)\n\nlemma sparse_row_vector_add: \"sparse_row_vector (add_spvec a b) = (sparse_row_vector a) + (sparse_row_vector b)\"\n  apply (induct a b rule: add_spvec.induct)\n  apply (simp_all add: singleton_matrix_add)\n  done\n\nfun add_spmat :: \"('a::lattice_ab_group_add) spmat \\<Rightarrow> 'a spmat \\<Rightarrow> 'a spmat\"\nwhere\n(* \"measure (% (A,B). (length A)+(length B))\" *)\n  \"add_spmat [] bs = bs\"\n| \"add_spmat as [] = as\"\n| \"add_spmat ((i,a)#as) ((j,b)#bs) = (\n    if i < j then \n      (i,a) # add_spmat as ((j,b)#bs)\n    else if j < i then\n      (j,b) # add_spmat ((i,a)#as) bs\n    else\n      (i, add_spvec a b) # add_spmat as bs)\"\n\nlemma add_spmat_Nil2[simp]: \"add_spmat as [] = as\"\nby(cases as) auto\n\nlemma sparse_row_add_spmat: \"sparse_row_matrix (add_spmat A B) = (sparse_row_matrix A) + (sparse_row_matrix B)\"\n  apply (induct A B rule: add_spmat.induct)\n  apply (auto simp add: sparse_row_matrix_cons sparse_row_vector_add move_matrix_add)\n  done\n\nlemmas [code] = sparse_row_add_spmat [symmetric]\nlemmas [code] = sparse_row_vector_add [symmetric]\n\nlemma sorted_add_spvec_helper1[rule_format]: \"add_spvec ((a,b)#arr) brr = (ab, bb) # list \\<longrightarrow> (ab = a | (brr \\<noteq> [] & ab = fst (hd brr)))\"\n  proof - \n    have \"(! x ab a. x = (a,b)#arr \\<longrightarrow> add_spvec x brr = (ab, bb) # list \\<longrightarrow> (ab = a | (ab = fst (hd brr))))\"\n      by (induct brr rule: add_spvec.induct) (auto split:if_splits)\n    then show ?thesis\n      by (case_tac brr, auto)\n  qed\n\nlemma sorted_add_spmat_helper1[rule_format]: \"add_spmat ((a,b)#arr) brr = (ab, bb) # list \\<longrightarrow> (ab = a | (brr \\<noteq> [] & ab = fst (hd brr)))\"\n  proof - \n    have \"(! x ab a. x = (a,b)#arr \\<longrightarrow> add_spmat x brr = (ab, bb) # list \\<longrightarrow> (ab = a | (ab = fst (hd brr))))\"\n      by (rule add_spmat.induct) (auto split:if_splits)\n    then show ?thesis\n      by (case_tac brr, auto)\n  qed\n\nlemma sorted_add_spvec_helper: \"add_spvec arr brr = (ab, bb) # list \\<Longrightarrow> ((arr \\<noteq> [] & ab = fst (hd arr)) | (brr \\<noteq> [] & ab = fst (hd brr)))\"\n  apply (induct arr brr rule: add_spvec.induct)\n  apply (auto split:if_splits)\n  done\n\nlemma sorted_add_spmat_helper: \"add_spmat arr brr = (ab, bb) # list \\<Longrightarrow> ((arr \\<noteq> [] & ab = fst (hd arr)) | (brr \\<noteq> [] & ab = fst (hd brr)))\"\n  apply (induct arr brr rule: add_spmat.induct)\n  apply (auto split:if_splits)\n  done\n\nlemma add_spvec_commute: \"add_spvec a b = add_spvec b a\"\nby (induct a b rule: add_spvec.induct) auto\n\nlemma add_spmat_commute: \"add_spmat a b = add_spmat b a\"\n  apply (induct a b rule: add_spmat.induct)\n  apply (simp_all add: add_spvec_commute)\n  done\n  \nlemma sorted_add_spvec_helper2: \"add_spvec ((a,b)#arr) brr = (ab, bb) # list \\<Longrightarrow> aa < a \\<Longrightarrow> sorted_spvec ((aa, ba) # brr) \\<Longrightarrow> aa < ab\"\n  apply (drule sorted_add_spvec_helper1)\n  apply (auto)\n  apply (case_tac brr)\n  apply (simp_all)\n  apply (drule_tac sorted_spvec_cons3)\n  apply (simp)\n  done\n\nlemma sorted_add_spmat_helper2: \"add_spmat ((a,b)#arr) brr = (ab, bb) # list \\<Longrightarrow> aa < a \\<Longrightarrow> sorted_spvec ((aa, ba) # brr) \\<Longrightarrow> aa < ab\"\n  apply (drule sorted_add_spmat_helper1)\n  apply (auto)\n  apply (case_tac brr)\n  apply (simp_all)\n  apply (drule_tac sorted_spvec_cons3)\n  apply (simp)\n  done\n\nlemma sorted_spvec_add_spvec[rule_format]: \"sorted_spvec a \\<longrightarrow> sorted_spvec b \\<longrightarrow> sorted_spvec (add_spvec a b)\"\n  apply (induct a b rule: add_spvec.induct)\n  apply (simp_all)\n  apply (rule conjI)\n  apply (clarsimp)\n  apply (frule_tac as=brr in sorted_spvec_cons1)\n  apply (simp)\n  apply (subst sorted_spvec_step)\n  apply (clarsimp simp: sorted_add_spvec_helper2 split: list.split)\n  apply (clarify)\n  apply (rule conjI)\n  apply (clarify)\n  apply (frule_tac as=arr in sorted_spvec_cons1, simp)\n  apply (subst sorted_spvec_step)\n  apply (clarsimp simp: sorted_add_spvec_helper2 add_spvec_commute split: list.split)\n  apply (clarify)\n  apply (frule_tac as=arr in sorted_spvec_cons1)\n  apply (frule_tac as=brr in sorted_spvec_cons1)\n  apply (simp)\n  apply (subst sorted_spvec_step)\n  apply (simp split: list.split)\n  apply (clarsimp)\n  apply (drule_tac sorted_add_spvec_helper)\n  apply (auto simp: neq_Nil_conv)\n  apply (drule sorted_spvec_cons3)\n  apply (simp)\n  apply (drule sorted_spvec_cons3)\n  apply (simp)\n  done\n\nlemma sorted_spvec_add_spmat[rule_format]: \"sorted_spvec A \\<longrightarrow> sorted_spvec B \\<longrightarrow> sorted_spvec (add_spmat A B)\"\n  apply (induct A B rule: add_spmat.induct)\n  apply (simp_all)\n  apply (rule conjI)\n  apply (intro strip)\n  apply (simp)\n  apply (frule_tac as=bs in sorted_spvec_cons1)\n  apply (simp)\n  apply (subst sorted_spvec_step)\n  apply (simp split: list.split)\n  apply (clarify, simp)\n  apply (simp add: sorted_add_spmat_helper2)\n  apply (clarify)\n  apply (rule conjI)\n  apply (clarify)\n  apply (frule_tac as=as in sorted_spvec_cons1, simp)\n  apply (subst sorted_spvec_step)\n  apply (clarsimp simp: sorted_add_spmat_helper2 add_spmat_commute split: list.split)\n  apply (clarsimp)\n  apply (frule_tac as=as in sorted_spvec_cons1)\n  apply (frule_tac as=bs in sorted_spvec_cons1)\n  apply (simp)\n  apply (subst sorted_spvec_step)\n  apply (simp split: list.split)\n  apply (clarify, simp)\n  apply (drule_tac sorted_add_spmat_helper)\n  apply (auto simp:neq_Nil_conv)\n  apply (drule sorted_spvec_cons3)\n  apply (simp)\n  apply (drule sorted_spvec_cons3)\n  apply (simp)\n  done\n\nlemma sorted_spmat_add_spmat[rule_format]: \"sorted_spmat A \\<Longrightarrow> sorted_spmat B \\<Longrightarrow> sorted_spmat (add_spmat A B)\"\n  apply (induct A B rule: add_spmat.induct)\n  apply (simp_all add: sorted_spvec_add_spvec)\n  done\n\nfun le_spvec :: \"('a::lattice_ab_group_add) spvec \\<Rightarrow> 'a spvec \\<Rightarrow> bool\"\nwhere\n(* \"measure (% (a,b). (length a) + (length b))\" *)\n  \"le_spvec [] [] = True\"\n| \"le_spvec ((_,a)#as) [] = (a <= 0 & le_spvec as [])\"\n| \"le_spvec [] ((_,b)#bs) = (0 <= b & le_spvec [] bs)\"\n| \"le_spvec ((i,a)#as) ((j,b)#bs) = (\n    if (i < j) then a <= 0 & le_spvec as ((j,b)#bs)\n    else if (j < i) then 0 <= b & le_spvec ((i,a)#as) bs\n    else a <= b & le_spvec as bs)\"\n\nfun le_spmat :: \"('a::lattice_ab_group_add) spmat \\<Rightarrow> 'a spmat \\<Rightarrow> bool\"\nwhere\n(* \"measure (% (a,b). (length a) + (length b))\" *)\n  \"le_spmat [] [] = True\"\n| \"le_spmat ((i,a)#as) [] = (le_spvec a [] & le_spmat as [])\"\n| \"le_spmat [] ((j,b)#bs) = (le_spvec [] b & le_spmat [] bs)\"\n| \"le_spmat ((i,a)#as) ((j,b)#bs) = (\n    if i < j then (le_spvec a [] & le_spmat as ((j,b)#bs))\n    else if j < i then (le_spvec [] b & le_spmat ((i,a)#as) bs)\n    else (le_spvec a b & le_spmat as bs))\"\n\ndefinition disj_matrices :: \"('a::zero) matrix \\<Rightarrow> 'a matrix \\<Rightarrow> bool\" where\n  \"disj_matrices A B \\<longleftrightarrow>\n    (! j i. (Rep_matrix A j i \\<noteq> 0) \\<longrightarrow> (Rep_matrix B j i = 0)) & (! j i. (Rep_matrix B j i \\<noteq> 0) \\<longrightarrow> (Rep_matrix A j i = 0))\"  \n\ndeclare [[simp_depth_limit = 6]]\n\nlemma disj_matrices_contr1: \"disj_matrices A B \\<Longrightarrow> Rep_matrix A j i \\<noteq> 0 \\<Longrightarrow> Rep_matrix B j i = 0\"\n   by (simp add: disj_matrices_def)\n\nlemma disj_matrices_contr2: \"disj_matrices A B \\<Longrightarrow> Rep_matrix B j i \\<noteq> 0 \\<Longrightarrow> Rep_matrix A j i = 0\"\n   by (simp add: disj_matrices_def)\n\n\nlemma disj_matrices_add: \"disj_matrices A B \\<Longrightarrow> disj_matrices C D \\<Longrightarrow> disj_matrices A D \\<Longrightarrow> disj_matrices B C \\<Longrightarrow> \n  (A + B <= C + D) = (A <= C & B <= (D::('a::lattice_ab_group_add) matrix))\"\n  apply (auto)\n  apply (simp (no_asm_use) only: le_matrix_def disj_matrices_def)\n  apply (intro strip)\n  apply (erule conjE)+\n  apply (drule_tac j=j and i=i in spec2)+\n  apply (case_tac \"Rep_matrix B j i = 0\")\n  apply (case_tac \"Rep_matrix D j i = 0\")\n  apply (simp_all)\n  apply (simp (no_asm_use) only: le_matrix_def disj_matrices_def)\n  apply (intro strip)\n  apply (erule conjE)+\n  apply (drule_tac j=j and i=i in spec2)+\n  apply (case_tac \"Rep_matrix A j i = 0\")\n  apply (case_tac \"Rep_matrix C j i = 0\")\n  apply (simp_all)\n  apply (erule add_mono)\n  apply (assumption)\n  done\n\nlemma disj_matrices_zero1[simp]: \"disj_matrices 0 B\"\nby (simp add: disj_matrices_def)\n\nlemma disj_matrices_zero2[simp]: \"disj_matrices A 0\"\nby (simp add: disj_matrices_def)\n\nlemma disj_matrices_commute: \"disj_matrices A B = disj_matrices B A\"\nby (auto simp add: disj_matrices_def)\n\nlemma disj_matrices_add_le_zero: \"disj_matrices A B \\<Longrightarrow>\n  (A + B <= 0) = (A <= 0 & (B::('a::lattice_ab_group_add) matrix) <= 0)\"\nby (rule disj_matrices_add[of A B 0 0, simplified])\n \nlemma disj_matrices_add_zero_le: \"disj_matrices A B \\<Longrightarrow>\n  (0 <= A + B) = (0 <= A & 0 <= (B::('a::lattice_ab_group_add) matrix))\"\nby (rule disj_matrices_add[of 0 0 A B, simplified])\n\nlemma disj_matrices_add_x_le: \"disj_matrices A B \\<Longrightarrow> disj_matrices B C \\<Longrightarrow> \n  (A <= B + C) = (A <= C & 0 <= (B::('a::lattice_ab_group_add) matrix))\"\nby (auto simp add: disj_matrices_add[of 0 A B C, simplified])\n\nlemma disj_matrices_add_le_x: \"disj_matrices A B \\<Longrightarrow> disj_matrices B C \\<Longrightarrow> \n  (B + A <= C) = (A <= C &  (B::('a::lattice_ab_group_add) matrix) <= 0)\"\nby (auto simp add: disj_matrices_add[of B A 0 C,simplified] disj_matrices_commute)\n\nlemma disj_sparse_row_singleton: \"i <= j \\<Longrightarrow> sorted_spvec((j,y)#v) \\<Longrightarrow> disj_matrices (sparse_row_vector v) (singleton_matrix 0 i x)\"\n  apply (simp add: disj_matrices_def)\n  apply (rule conjI)\n  apply (rule neg_imp)\n  apply (simp)\n  apply (intro strip)\n  apply (rule sorted_sparse_row_vector_zero)\n  apply (simp_all)\n  apply (intro strip)\n  apply (rule sorted_sparse_row_vector_zero)\n  apply (simp_all)\n  done \n\nlemma disj_matrices_x_add: \"disj_matrices A B \\<Longrightarrow> disj_matrices A C \\<Longrightarrow> disj_matrices (A::('a::lattice_ab_group_add) matrix) (B+C)\"\n  apply (simp add: disj_matrices_def)\n  apply (auto)\n  apply (drule_tac j=j and i=i in spec2)+\n  apply (case_tac \"Rep_matrix B j i = 0\")\n  apply (case_tac \"Rep_matrix C j i = 0\")\n  apply (simp_all)\n  done\n\nlemma disj_matrices_add_x: \"disj_matrices A B \\<Longrightarrow> disj_matrices A C \\<Longrightarrow> disj_matrices (B+C) (A::('a::lattice_ab_group_add) matrix)\" \n  by (simp add: disj_matrices_x_add disj_matrices_commute)\n\nlemma disj_singleton_matrices[simp]: \"disj_matrices (singleton_matrix j i x) (singleton_matrix u v y) = (j \\<noteq> u | i \\<noteq> v | x = 0 | y = 0)\" \n  by (auto simp add: disj_matrices_def)\n\nlemma disj_move_sparse_vec_mat[simplified disj_matrices_commute]: \n  \"j <= a \\<Longrightarrow> sorted_spvec((a,c)#as) \\<Longrightarrow> disj_matrices (move_matrix (sparse_row_vector b) (int j) i) (sparse_row_matrix as)\"\n  apply (auto simp add: disj_matrices_def)\n  apply (drule nrows_notzero)\n  apply (drule less_le_trans[OF _ nrows_spvec])\n  apply (subgoal_tac \"ja = j\")\n  apply (simp add: sorted_sparse_row_matrix_zero)\n  apply (arith)\n  apply (rule nrows)\n  apply (rule order_trans[of _ 1 _])\n  apply (simp)\n  apply (case_tac \"nat (int ja - int j) = 0\")\n  apply (case_tac \"ja = j\")\n  apply (simp add: sorted_sparse_row_matrix_zero)\n  apply arith+\n  done\n\nlemma disj_move_sparse_row_vector_twice:\n  \"j \\<noteq> u \\<Longrightarrow> disj_matrices (move_matrix (sparse_row_vector a) j i) (move_matrix (sparse_row_vector b) u v)\"\n  apply (auto simp add: disj_matrices_def)\n  apply (rule nrows, rule order_trans[of _ 1], simp, drule nrows_notzero, drule less_le_trans[OF _ nrows_spvec], arith)+\n  done\n\nlemma le_spvec_iff_sparse_row_le[rule_format]: \"(sorted_spvec a) \\<longrightarrow> (sorted_spvec b) \\<longrightarrow> (le_spvec a b) = (sparse_row_vector a <= sparse_row_vector b)\"\n  apply (induct a b rule: le_spvec.induct)\n  apply (simp_all add: sorted_spvec_cons1 disj_matrices_add_le_zero disj_matrices_add_zero_le \n    disj_sparse_row_singleton[OF order_refl] disj_matrices_commute)\n  apply (rule conjI, intro strip)\n  apply (simp add: sorted_spvec_cons1)\n  apply (subst disj_matrices_add_x_le)\n  apply (simp add: disj_sparse_row_singleton[OF less_imp_le] disj_matrices_x_add disj_matrices_commute)\n  apply (simp add: disj_sparse_row_singleton[OF order_refl] disj_matrices_commute)\n  apply (simp, blast)\n  apply (intro strip, rule conjI, intro strip)\n  apply (simp add: sorted_spvec_cons1)\n  apply (subst disj_matrices_add_le_x)\n  apply (simp_all add: disj_sparse_row_singleton[OF order_refl] disj_sparse_row_singleton[OF less_imp_le] disj_matrices_commute disj_matrices_x_add)\n  apply (blast)\n  apply (intro strip)\n  apply (simp add: sorted_spvec_cons1)\n  apply (case_tac \"a=b\", simp_all)\n  apply (subst disj_matrices_add)\n  apply (simp_all add: disj_sparse_row_singleton[OF order_refl] disj_matrices_commute)\n  done\n\nlemma le_spvec_empty2_sparse_row[rule_format]: \"sorted_spvec b \\<longrightarrow> le_spvec b [] = (sparse_row_vector b <= 0)\"\n  apply (induct b)\n  apply (simp_all add: sorted_spvec_cons1)\n  apply (intro strip)\n  apply (subst disj_matrices_add_le_zero)\n  apply (auto simp add: disj_matrices_commute disj_sparse_row_singleton[OF order_refl] sorted_spvec_cons1)\n  done\n\nlemma le_spvec_empty1_sparse_row[rule_format]: \"(sorted_spvec b) \\<longrightarrow> (le_spvec [] b = (0 <= sparse_row_vector b))\"\n  apply (induct b)\n  apply (simp_all add: sorted_spvec_cons1)\n  apply (intro strip)\n  apply (subst disj_matrices_add_zero_le)\n  apply (auto simp add: disj_matrices_commute disj_sparse_row_singleton[OF order_refl] sorted_spvec_cons1)\n  done\n\nlemma le_spmat_iff_sparse_row_le[rule_format]: \"(sorted_spvec A) \\<longrightarrow> (sorted_spmat A) \\<longrightarrow> (sorted_spvec B) \\<longrightarrow> (sorted_spmat B) \\<longrightarrow> \n  le_spmat A B = (sparse_row_matrix A <= sparse_row_matrix B)\"\n  apply (induct A B rule: le_spmat.induct)\n  apply (simp add: sparse_row_matrix_cons disj_matrices_add_le_zero disj_matrices_add_zero_le disj_move_sparse_vec_mat[OF order_refl] \n    disj_matrices_commute sorted_spvec_cons1 le_spvec_empty2_sparse_row le_spvec_empty1_sparse_row)+ \n  apply (rule conjI, intro strip)\n  apply (simp add: sorted_spvec_cons1)\n  apply (subst disj_matrices_add_x_le)\n  apply (rule disj_matrices_add_x)\n  apply (simp add: disj_move_sparse_row_vector_twice)\n  apply (simp add: disj_move_sparse_vec_mat[OF less_imp_le] disj_matrices_commute)\n  apply (simp add: disj_move_sparse_vec_mat[OF order_refl] disj_matrices_commute)\n  apply (simp, blast)\n  apply (intro strip, rule conjI, intro strip)\n  apply (simp add: sorted_spvec_cons1)\n  apply (subst disj_matrices_add_le_x)\n  apply (simp add: disj_move_sparse_vec_mat[OF order_refl])\n  apply (rule disj_matrices_x_add)\n  apply (simp add: disj_move_sparse_row_vector_twice)\n  apply (simp add: disj_move_sparse_vec_mat[OF less_imp_le] disj_matrices_commute)\n  apply (simp, blast)\n  apply (intro strip)\n  apply (case_tac \"i=j\")\n  apply (simp_all)\n  apply (subst disj_matrices_add)\n  apply (simp_all add: disj_matrices_commute disj_move_sparse_vec_mat[OF order_refl])\n  apply (simp add: sorted_spvec_cons1 le_spvec_iff_sparse_row_le)\n  done\n\ndeclare [[simp_depth_limit = 999]]\n\nprimrec abs_spmat :: \"('a::lattice_ring) spmat \\<Rightarrow> 'a spmat\"\nwhere\n  \"abs_spmat [] = []\"\n| \"abs_spmat (a#as) = (fst a, abs_spvec (snd a))#(abs_spmat as)\"\n\nprimrec minus_spmat :: \"('a::lattice_ring) spmat \\<Rightarrow> 'a spmat\"\nwhere\n  \"minus_spmat [] = []\"\n| \"minus_spmat (a#as) = (fst a, minus_spvec (snd a))#(minus_spmat as)\"\n\nlemma sparse_row_matrix_minus:\n  \"sparse_row_matrix (minus_spmat A) = - (sparse_row_matrix A)\"\n  apply (induct A)\n  apply (simp_all add: sparse_row_vector_minus sparse_row_matrix_cons)\n  apply (subst Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply simp\n  done\n\nlemma Rep_sparse_row_vector_zero: \"x \\<noteq> 0 \\<Longrightarrow> Rep_matrix (sparse_row_vector v) x y = 0\"\nproof -\n  assume x:\"x \\<noteq> 0\"\n  have r:\"nrows (sparse_row_vector v) <= Suc 0\" by (rule nrows_spvec)\n  show ?thesis\n    apply (rule nrows)\n    apply (subgoal_tac \"Suc 0 <= x\")\n    apply (insert r)\n    apply (simp only:)\n    apply (insert x)\n    apply arith\n    done\nqed\n    \nlemma sparse_row_matrix_abs:\n  \"sorted_spvec A \\<Longrightarrow> sorted_spmat A \\<Longrightarrow> sparse_row_matrix (abs_spmat A) = \\<bar>sparse_row_matrix A\\<bar>\"\n  apply (induct A)\n  apply (simp_all add: sparse_row_vector_abs sparse_row_matrix_cons)\n  apply (frule_tac sorted_spvec_cons1, simp)\n  apply (simplesubst Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply auto\n  apply (case_tac \"x=a\")\n  apply (simp)\n  apply (simplesubst sorted_sparse_row_matrix_zero)\n  apply auto\n  apply (simplesubst Rep_sparse_row_vector_zero)\n  apply simp_all\n  done\n\nlemma sorted_spvec_minus_spmat: \"sorted_spvec A \\<Longrightarrow> sorted_spvec (minus_spmat A)\"\n  apply (induct A)\n  apply (simp)\n  apply (frule sorted_spvec_cons1, simp)\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done \n\nlemma sorted_spvec_abs_spmat: \"sorted_spvec A \\<Longrightarrow> sorted_spvec (abs_spmat A)\" \n  apply (induct A)\n  apply (simp)\n  apply (frule sorted_spvec_cons1, simp)\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_spmat_minus_spmat: \"sorted_spmat A \\<Longrightarrow> sorted_spmat (minus_spmat A)\"\n  apply (induct A)\n  apply (simp_all add: sorted_spvec_minus_spvec)\n  done\n\nlemma sorted_spmat_abs_spmat: \"sorted_spmat A \\<Longrightarrow> sorted_spmat (abs_spmat A)\"\n  apply (induct A)\n  apply (simp_all add: sorted_spvec_abs_spvec)\n  done\n\ndefinition diff_spmat :: \"('a::lattice_ring) spmat \\<Rightarrow> 'a spmat \\<Rightarrow> 'a spmat\"\n  where \"diff_spmat A B = add_spmat A (minus_spmat B)\"\n\nlemma sorted_spmat_diff_spmat: \"sorted_spmat A \\<Longrightarrow> sorted_spmat B \\<Longrightarrow> sorted_spmat (diff_spmat A B)\"\n  by (simp add: diff_spmat_def sorted_spmat_minus_spmat sorted_spmat_add_spmat)\n\nlemma sorted_spvec_diff_spmat: \"sorted_spvec A \\<Longrightarrow> sorted_spvec B \\<Longrightarrow> sorted_spvec (diff_spmat A B)\"\n  by (simp add: diff_spmat_def sorted_spvec_minus_spmat sorted_spvec_add_spmat)\n\nlemma sparse_row_diff_spmat: \"sparse_row_matrix (diff_spmat A B ) = (sparse_row_matrix A) - (sparse_row_matrix B)\"\n  by (simp add: diff_spmat_def sparse_row_add_spmat sparse_row_matrix_minus)\n\ndefinition sorted_sparse_matrix :: \"'a spmat \\<Rightarrow> bool\"\n  where \"sorted_sparse_matrix A \\<longleftrightarrow> sorted_spvec A & sorted_spmat A\"\n\nlemma sorted_sparse_matrix_imp_spvec: \"sorted_sparse_matrix A \\<Longrightarrow> sorted_spvec A\"\n  by (simp add: sorted_sparse_matrix_def)\n\nlemma sorted_sparse_matrix_imp_spmat: \"sorted_sparse_matrix A \\<Longrightarrow> sorted_spmat A\"\n  by (simp add: sorted_sparse_matrix_def)\n\nlemmas sorted_sp_simps = \n  sorted_spvec.simps\n  sorted_spmat.simps\n  sorted_sparse_matrix_def\n\nlemma bool1: \"(\\<not> True) = False\"  by blast\nlemma bool2: \"(\\<not> False) = True\"  by blast\nlemma bool3: \"((P::bool) \\<and> True) = P\" by blast\nlemma bool4: \"(True \\<and> (P::bool)) = P\" by blast\nlemma bool5: \"((P::bool) \\<and> False) = False\" by blast\nlemma bool6: \"(False \\<and> (P::bool)) = False\" by blast\nlemma bool7: \"((P::bool) \\<or> True) = True\" by blast\nlemma bool8: \"(True \\<or> (P::bool)) = True\" by blast\nlemma bool9: \"((P::bool) \\<or> False) = P\" by blast\nlemma bool10: \"(False \\<or> (P::bool)) = P\" by blast\nlemmas boolarith = bool1 bool2 bool3 bool4 bool5 bool6 bool7 bool8 bool9 bool10\n\nlemma if_case_eq: \"(if b then x else y) = (case b of True => x | False => y)\" by simp\n\nprimrec pprt_spvec :: \"('a::{lattice_ab_group_add}) spvec \\<Rightarrow> 'a spvec\"\nwhere\n  \"pprt_spvec [] = []\"\n| \"pprt_spvec (a#as) = (fst a, pprt (snd a)) # (pprt_spvec as)\"\n\nprimrec nprt_spvec :: \"('a::{lattice_ab_group_add}) spvec \\<Rightarrow> 'a spvec\"\nwhere\n  \"nprt_spvec [] = []\"\n| \"nprt_spvec (a#as) = (fst a, nprt (snd a)) # (nprt_spvec as)\"\n\nprimrec pprt_spmat :: \"('a::{lattice_ab_group_add}) spmat \\<Rightarrow> 'a spmat\"\nwhere\n  \"pprt_spmat [] = []\"\n| \"pprt_spmat (a#as) = (fst a, pprt_spvec (snd a))#(pprt_spmat as)\"\n\nprimrec nprt_spmat :: \"('a::{lattice_ab_group_add}) spmat \\<Rightarrow> 'a spmat\"\nwhere\n  \"nprt_spmat [] = []\"\n| \"nprt_spmat (a#as) = (fst a, nprt_spvec (snd a))#(nprt_spmat as)\"\n\n\nlemma pprt_add: \"disj_matrices A (B::(_::lattice_ring) matrix) \\<Longrightarrow> pprt (A+B) = pprt A + pprt B\"\n  apply (simp add: pprt_def sup_matrix_def)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply simp\n  apply (case_tac \"Rep_matrix A x xa \\<noteq> 0\")\n  apply (simp_all add: disj_matrices_contr1)\n  done\n\nlemma nprt_add: \"disj_matrices A (B::(_::lattice_ring) matrix) \\<Longrightarrow> nprt (A+B) = nprt A + nprt B\"\n  apply (simp add: nprt_def inf_matrix_def)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply simp\n  apply (case_tac \"Rep_matrix A x xa \\<noteq> 0\")\n  apply (simp_all add: disj_matrices_contr1)\n  done\n\nlemma pprt_singleton[simp]: \"pprt (singleton_matrix j i (x::_::lattice_ring)) = singleton_matrix j i (pprt x)\"\n  apply (simp add: pprt_def sup_matrix_def)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply simp\n  done\n\nlemma nprt_singleton[simp]: \"nprt (singleton_matrix j i (x::_::lattice_ring)) = singleton_matrix j i (nprt x)\"\n  apply (simp add: nprt_def inf_matrix_def)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply simp\n  done\n\nlemma less_imp_le: \"a < b \\<Longrightarrow> a <= (b::_::order)\" by (simp add: less_def)\n\nlemma sparse_row_vector_pprt: \"sorted_spvec (v :: 'a::lattice_ring spvec) \\<Longrightarrow> sparse_row_vector (pprt_spvec v) = pprt (sparse_row_vector v)\"\n  apply (induct v)\n  apply (simp_all)\n  apply (frule sorted_spvec_cons1, auto)\n  apply (subst pprt_add)\n  apply (subst disj_matrices_commute)\n  apply (rule disj_sparse_row_singleton)\n  apply auto\n  done\n\nlemma sparse_row_vector_nprt: \"sorted_spvec (v :: 'a::lattice_ring spvec) \\<Longrightarrow> sparse_row_vector (nprt_spvec v) = nprt (sparse_row_vector v)\"\n  apply (induct v)\n  apply (simp_all)\n  apply (frule sorted_spvec_cons1, auto)\n  apply (subst nprt_add)\n  apply (subst disj_matrices_commute)\n  apply (rule disj_sparse_row_singleton)\n  apply auto\n  done\n  \n  \nlemma pprt_move_matrix: \"pprt (move_matrix (A::('a::lattice_ring) matrix) j i) = move_matrix (pprt A) j i\"\n  apply (simp add: pprt_def)\n  apply (simp add: sup_matrix_def)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply (simp)\n  done\n\nlemma nprt_move_matrix: \"nprt (move_matrix (A::('a::lattice_ring) matrix) j i) = move_matrix (nprt A) j i\"\n  apply (simp add: nprt_def)\n  apply (simp add: inf_matrix_def)\n  apply (simp add: Rep_matrix_inject[symmetric])\n  apply (rule ext)+\n  apply (simp)\n  done\n\nlemma sparse_row_matrix_pprt: \"sorted_spvec (m :: 'a::lattice_ring spmat) \\<Longrightarrow> sorted_spmat m \\<Longrightarrow> sparse_row_matrix (pprt_spmat m) = pprt (sparse_row_matrix m)\"\n  apply (induct m)\n  apply simp\n  apply simp\n  apply (frule sorted_spvec_cons1)\n  apply (simp add: sparse_row_matrix_cons sparse_row_vector_pprt)\n  apply (subst pprt_add)\n  apply (subst disj_matrices_commute)\n  apply (rule disj_move_sparse_vec_mat)\n  apply auto\n  apply (simp add: sorted_spvec.simps)\n  apply (simp split: list.split)\n  apply auto\n  apply (simp add: pprt_move_matrix)\n  done\n\nlemma sparse_row_matrix_nprt: \"sorted_spvec (m :: 'a::lattice_ring spmat) \\<Longrightarrow> sorted_spmat m \\<Longrightarrow> sparse_row_matrix (nprt_spmat m) = nprt (sparse_row_matrix m)\"\n  apply (induct m)\n  apply simp\n  apply simp\n  apply (frule sorted_spvec_cons1)\n  apply (simp add: sparse_row_matrix_cons sparse_row_vector_nprt)\n  apply (subst nprt_add)\n  apply (subst disj_matrices_commute)\n  apply (rule disj_move_sparse_vec_mat)\n  apply auto\n  apply (simp add: sorted_spvec.simps)\n  apply (simp split: list.split)\n  apply auto\n  apply (simp add: nprt_move_matrix)\n  done\n\nlemma sorted_pprt_spvec: \"sorted_spvec v \\<Longrightarrow> sorted_spvec (pprt_spvec v)\"\n  apply (induct v)\n  apply (simp)\n  apply (frule sorted_spvec_cons1)\n  apply simp\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_nprt_spvec: \"sorted_spvec v \\<Longrightarrow> sorted_spvec (nprt_spvec v)\"\n  apply (induct v)\n  apply (simp)\n  apply (frule sorted_spvec_cons1)\n  apply simp\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_spvec_pprt_spmat: \"sorted_spvec m \\<Longrightarrow> sorted_spvec (pprt_spmat m)\"\n  apply (induct m)\n  apply (simp)\n  apply (frule sorted_spvec_cons1)\n  apply simp\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_spvec_nprt_spmat: \"sorted_spvec m \\<Longrightarrow> sorted_spvec (nprt_spmat m)\"\n  apply (induct m)\n  apply (simp)\n  apply (frule sorted_spvec_cons1)\n  apply simp\n  apply (simp add: sorted_spvec.simps split:list.split_asm)\n  done\n\nlemma sorted_spmat_pprt_spmat: \"sorted_spmat m \\<Longrightarrow> sorted_spmat (pprt_spmat m)\"\n  apply (induct m)\n  apply (simp_all add: sorted_pprt_spvec)\n  done\n\nlemma sorted_spmat_nprt_spmat: \"sorted_spmat m \\<Longrightarrow> sorted_spmat (nprt_spmat m)\"\n  apply (induct m)\n  apply (simp_all add: sorted_nprt_spvec)\n  done\n\ndefinition mult_est_spmat :: \"('a::lattice_ring) spmat \\<Rightarrow> 'a spmat \\<Rightarrow> 'a spmat \\<Rightarrow> 'a spmat \\<Rightarrow> 'a spmat\" where\n  \"mult_est_spmat r1 r2 s1 s2 =\n  add_spmat (mult_spmat (pprt_spmat s2) (pprt_spmat r2)) (add_spmat (mult_spmat (pprt_spmat s1) (nprt_spmat r2)) \n  (add_spmat (mult_spmat (nprt_spmat s2) (pprt_spmat r1)) (mult_spmat (nprt_spmat s1) (nprt_spmat r1))))\"  \n\nlemmas sparse_row_matrix_op_simps =\n  sorted_sparse_matrix_imp_spmat sorted_sparse_matrix_imp_spvec\n  sparse_row_add_spmat sorted_spvec_add_spmat sorted_spmat_add_spmat\n  sparse_row_diff_spmat sorted_spvec_diff_spmat sorted_spmat_diff_spmat\n  sparse_row_matrix_minus sorted_spvec_minus_spmat sorted_spmat_minus_spmat\n  sparse_row_mult_spmat sorted_spvec_mult_spmat sorted_spmat_mult_spmat\n  sparse_row_matrix_abs sorted_spvec_abs_spmat sorted_spmat_abs_spmat\n  le_spmat_iff_sparse_row_le\n  sparse_row_matrix_pprt sorted_spvec_pprt_spmat sorted_spmat_pprt_spmat\n  sparse_row_matrix_nprt sorted_spvec_nprt_spmat sorted_spmat_nprt_spmat\n\nlemmas sparse_row_matrix_arith_simps = \n  mult_spmat.simps mult_spvec_spmat.simps \n  addmult_spvec.simps \n  smult_spvec_empty smult_spvec_cons\n  add_spmat.simps add_spvec.simps\n  minus_spmat.simps minus_spvec.simps\n  abs_spmat.simps abs_spvec.simps\n  diff_spmat_def\n  le_spmat.simps le_spvec.simps\n  pprt_spmat.simps pprt_spvec.simps\n  nprt_spmat.simps nprt_spvec.simps\n  mult_est_spmat_def\n\n\n(*lemma spm_linprog_dual_estimate_1:\n  assumes  \n  \"sorted_sparse_matrix A1\"\n  \"sorted_sparse_matrix A2\"\n  \"sorted_sparse_matrix c1\"\n  \"sorted_sparse_matrix c2\"\n  \"sorted_sparse_matrix y\"\n  \"sorted_spvec b\"\n  \"sorted_spvec r\"\n  \"le_spmat ([], y)\"\n  \"A * x \\<le> sparse_row_matrix (b::('a::lattice_ring) spmat)\"\n  \"sparse_row_matrix A1 <= A\"\n  \"A <= sparse_row_matrix A2\"\n  \"sparse_row_matrix c1 <= c\"\n  \"c <= sparse_row_matrix c2\"\n  \"\\<bar>x\\<bar> \\<le> sparse_row_matrix r\"\n  shows\n  \"c * x \\<le> sparse_row_matrix (add_spmat (mult_spmat y b, mult_spmat (add_spmat (add_spmat (mult_spmat y (diff_spmat A2 A1), \n  abs_spmat (diff_spmat (mult_spmat y A1) c1)), diff_spmat c2 c1)) r))\"\n  by (insert prems, simp add: sparse_row_matrix_op_simps linprog_dual_estimate_1[where A=A])\n*)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Matrix_LP/SparseMatrix.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.8333245973817158, "lm_q1q2_score": 0.7593084710177739}}
{"text": "(*  Title:      HOL/Algebra/Bij.thy\n    Author:     Florian Kammueller, with new proofs by L C Paulson\n*)\n\ntheory Bij\nimports Group\nbegin\n\nsection {* Bijections of a Set, Permutation and Automorphism Groups *}\n\ndefinition\n  Bij :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n    --{*Only extensional functions, since otherwise we get too many.*}\n   where \"Bij S = extensional S \\<inter> {f. bij_betw f S S}\"\n\ndefinition\n  BijGroup :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"BijGroup S =\n    \\<lparr>carrier = Bij S,\n     mult = \\<lambda>g \\<in> Bij S. \\<lambda>f \\<in> Bij S. compose S g f,\n     one = \\<lambda>x \\<in> S. x\\<rparr>\"\n\n\ndeclare Id_compose [simp] compose_Id [simp]\n\nlemma Bij_imp_extensional: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> extensional S\"\n  by (simp add: Bij_def)\n\nlemma Bij_imp_funcset: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> S \\<rightarrow> S\"\n  by (auto simp add: Bij_def bij_betw_imp_funcset)\n\n\nsubsection {*Bijections Form a Group *}\n\nlemma restrict_inv_into_Bij: \"f \\<in> Bij S \\<Longrightarrow> (\\<lambda>x \\<in> S. (inv_into S f) x) \\<in> Bij S\"\n  by (simp add: Bij_def bij_betw_inv_into)\n\nlemma id_Bij: \"(\\<lambda>x\\<in>S. x) \\<in> Bij S \"\n  by (auto simp add: Bij_def bij_betw_def inj_on_def)\n\nlemma compose_Bij: \"\\<lbrakk>x \\<in> Bij S; y \\<in> Bij S\\<rbrakk> \\<Longrightarrow> compose S x y \\<in> Bij S\"\n  by (auto simp add: Bij_def bij_betw_compose) \n\nlemma Bij_compose_restrict_eq:\n     \"f \\<in> Bij S \\<Longrightarrow> compose S (restrict (inv_into S f) S) f = (\\<lambda>x\\<in>S. x)\"\n  by (simp add: Bij_def compose_inv_into_id)\n\ntheorem group_BijGroup: \"group (BijGroup S)\"\napply (simp add: BijGroup_def)\napply (rule groupI)\n    apply (simp add: compose_Bij)\n   apply (simp add: id_Bij)\n  apply (simp add: compose_Bij)\n  apply (blast intro: compose_assoc [symmetric] dest: Bij_imp_funcset)\n apply (simp add: id_Bij Bij_imp_funcset Bij_imp_extensional, simp)\napply (blast intro: Bij_compose_restrict_eq restrict_inv_into_Bij)\ndone\n\n\nsubsection{*Automorphisms Form a Group*}\n\nlemma Bij_inv_into_mem: \"\\<lbrakk> f \\<in> Bij S;  x \\<in> S\\<rbrakk> \\<Longrightarrow> inv_into S f x \\<in> S\"\nby (simp add: Bij_def bij_betw_def inv_into_into)\n\nlemma Bij_inv_into_lemma:\n assumes eq: \"\\<And>x y. \\<lbrakk>x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> h(g x y) = g (h x) (h y)\"\n shows \"\\<lbrakk>h \\<in> Bij S;  g \\<in> S \\<rightarrow> S \\<rightarrow> S;  x \\<in> S;  y \\<in> S\\<rbrakk>\n        \\<Longrightarrow> inv_into S h (g x y) = g (inv_into S h x) (inv_into S h y)\"\napply (simp add: Bij_def bij_betw_def)\napply (subgoal_tac \"\\<exists>x'\\<in>S. \\<exists>y'\\<in>S. x = h x' & y = h y'\", clarify)\n apply (simp add: eq [symmetric] inv_f_f funcset_mem [THEN funcset_mem], blast)\ndone\n\n\ndefinition\n  auto :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n  where \"auto G = hom G G \\<inter> Bij (carrier G)\"\n\ndefinition\n  AutoGroup :: \"('a, 'c) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"AutoGroup G = BijGroup (carrier G) \\<lparr>carrier := auto G\\<rparr>\"\n\nlemma (in group) id_in_auto: \"(\\<lambda>x \\<in> carrier G. x) \\<in> auto G\"\n  by (simp add: auto_def hom_def restrictI group.axioms id_Bij)\n\nlemma (in group) mult_funcset: \"mult G \\<in> carrier G \\<rightarrow> carrier G \\<rightarrow> carrier G\"\n  by (simp add:  Pi_I group.axioms)\n\nlemma (in group) restrict_inv_into_hom:\n      \"\\<lbrakk>h \\<in> hom G G; h \\<in> Bij (carrier G)\\<rbrakk>\n       \\<Longrightarrow> restrict (inv_into (carrier G) h) (carrier G) \\<in> hom G G\"\n  by (simp add: hom_def Bij_inv_into_mem restrictI mult_funcset\n                group.axioms Bij_inv_into_lemma)\n\nlemma inv_BijGroup:\n     \"f \\<in> Bij S \\<Longrightarrow> m_inv (BijGroup S) f = (\\<lambda>x \\<in> S. (inv_into S f) x)\"\napply (rule group.inv_equality)\napply (rule group_BijGroup)\napply (simp_all add:BijGroup_def restrict_inv_into_Bij Bij_compose_restrict_eq)\ndone\n\nlemma (in group) subgroup_auto:\n      \"subgroup (auto G) (BijGroup (carrier G))\"\nproof (rule subgroup.intro)\n  show \"auto G \\<subseteq> carrier (BijGroup (carrier G))\"\n    by (force simp add: auto_def BijGroup_def)\nnext\n  fix x y\n  assume \"x \\<in> auto G\" \"y \\<in> auto G\" \n  thus \"x \\<otimes>\\<^bsub>BijGroup (carrier G)\\<^esub> y \\<in> auto G\"\n    by (force simp add: BijGroup_def is_group auto_def Bij_imp_funcset \n                        group.hom_compose compose_Bij)\nnext\n  show \"\\<one>\\<^bsub>BijGroup (carrier G)\\<^esub> \\<in> auto G\" by (simp add:  BijGroup_def id_in_auto)\nnext\n  fix x \n  assume \"x \\<in> auto G\" \n  thus \"inv\\<^bsub>BijGroup (carrier G)\\<^esub> x \\<in> auto G\"\n    by (simp del: restrict_apply\n        add: inv_BijGroup auto_def restrict_inv_into_Bij restrict_inv_into_hom)\nqed\n\ntheorem (in group) AutoGroup: \"group (AutoGroup G)\"\nby (simp add: AutoGroup_def subgroup.subgroup_is_group subgroup_auto \n              group_BijGroup)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Algebra/Bij.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.7593084550624147}}
{"text": "(*  Title:       HOL/Complex.thy\n    Author:      Jacques D. Fleuriot, 2001 University of Edinburgh\n    Author:      Lawrence C Paulson, 2003/4\n*)\n\nsection \\<open>Complex Numbers: Rectangular and Polar Representations\\<close>\n\ntheory Complex\nimports Transcendental Real_Vector_Spaces\nbegin\n\ntext \\<open>\n  We use the \\<^theory_text>\\<open>codatatype\\<close> command to define the type of complex numbers. This\n  allows us to use \\<^theory_text>\\<open>primcorec\\<close> to define complex functions by defining their\n  real and imaginary result separately.\n\\<close>\n\ncodatatype complex = Complex (Re: real) (Im: real)\n\nlemma complex_surj: \"Complex (Re z) (Im z) = z\"\n  by (rule complex.collapse)\n\nlemma complex_eqI [intro?]: \"Re x = Re y \\<Longrightarrow> Im x = Im y \\<Longrightarrow> x = y\"\n  by (rule complex.expand) simp\n\nlemma complex_eq_iff: \"x = y \\<longleftrightarrow> Re x = Re y \\<and> Im x = Im y\"\n  by (auto intro: complex.expand)\n\nsubsection \\<open>Addition and Subtraction\\<close>\n\ninstantiation complex :: ab_group_add\nbegin\n\nprimcorec zero_complex\n  where\n    \"Re 0 = 0\"\n  | \"Im 0 = 0\"\n\nprimcorec plus_complex\n  where\n    \"Re (x + y) = Re x + Re y\"\n  | \"Im (x + y) = Im x + Im y\"\n\nprimcorec uminus_complex\n  where\n    \"Re (- x) = - Re x\"\n  | \"Im (- x) = - Im x\"\n\nprimcorec minus_complex\n  where\n    \"Re (x - y) = Re x - Re y\"\n  | \"Im (x - y) = Im x - Im y\"\n\ninstance\n  by standard (simp_all add: complex_eq_iff)\n\nend\n\n\nsubsection \\<open>Multiplication and Division\\<close>\n\ninstantiation complex :: field\nbegin\n\nprimcorec one_complex\n  where\n    \"Re 1 = 1\"\n  | \"Im 1 = 0\"\n\nprimcorec times_complex\n  where\n    \"Re (x * y) = Re x * Re y - Im x * Im y\"\n  | \"Im (x * y) = Re x * Im y + Im x * Re y\"\n\nprimcorec inverse_complex\n  where\n    \"Re (inverse x) = Re x / ((Re x)\\<^sup>2 + (Im x)\\<^sup>2)\"\n  | \"Im (inverse x) = - Im x / ((Re x)\\<^sup>2 + (Im x)\\<^sup>2)\"\n\ndefinition \"x div y = x * inverse y\" for x y :: complex\n\ninstance\n  by standard\n     (simp_all add: complex_eq_iff divide_complex_def\n      distrib_left distrib_right right_diff_distrib left_diff_distrib\n      power2_eq_square add_divide_distrib [symmetric])\n\nend\n\nlemma Re_divide: \"Re (x / y) = (Re x * Re y + Im x * Im y) / ((Re y)\\<^sup>2 + (Im y)\\<^sup>2)\"\n  by (simp add: divide_complex_def add_divide_distrib)\n\nlemma Im_divide: \"Im (x / y) = (Im x * Re y - Re x * Im y) / ((Re y)\\<^sup>2 + (Im y)\\<^sup>2)\"\n  by (simp add: divide_complex_def diff_divide_distrib)\n\nlemma Complex_divide:\n    \"(x / y) = Complex ((Re x * Re y + Im x * Im y) / ((Re y)\\<^sup>2 + (Im y)\\<^sup>2))\n                       ((Im x * Re y - Re x * Im y) / ((Re y)\\<^sup>2 + (Im y)\\<^sup>2))\"\n  by (metis Im_divide Re_divide complex_surj)\n\nlemma Re_power2: \"Re (x ^ 2) = (Re x)^2 - (Im x)^2\"\n  by (simp add: power2_eq_square)\n\nlemma Im_power2: \"Im (x ^ 2) = 2 * Re x * Im x\"\n  by (simp add: power2_eq_square)\n\nlemma Re_power_real [simp]: \"Im x = 0 \\<Longrightarrow> Re (x ^ n) = Re x ^ n \"\n  by (induct n) simp_all\n\nlemma Im_power_real [simp]: \"Im x = 0 \\<Longrightarrow> Im (x ^ n) = 0\"\n  by (induct n) simp_all\n\n\nsubsection \\<open>Scalar Multiplication\\<close>\n\ninstantiation complex :: real_field\nbegin\n\nprimcorec scaleR_complex\n  where\n    \"Re (scaleR r x) = r * Re x\"\n  | \"Im (scaleR r x) = r * Im x\"\n\ninstance\nproof\n  fix a b :: real and x y :: complex\n  show \"scaleR a (x + y) = scaleR a x + scaleR a y\"\n    by (simp add: complex_eq_iff distrib_left)\n  show \"scaleR (a + b) x = scaleR a x + scaleR b x\"\n    by (simp add: complex_eq_iff distrib_right)\n  show \"scaleR a (scaleR b x) = scaleR (a * b) x\"\n    by (simp add: complex_eq_iff mult.assoc)\n  show \"scaleR 1 x = x\"\n    by (simp add: complex_eq_iff)\n  show \"scaleR a x * y = scaleR a (x * y)\"\n    by (simp add: complex_eq_iff algebra_simps)\n  show \"x * scaleR a y = scaleR a (x * y)\"\n    by (simp add: complex_eq_iff algebra_simps)\nqed\n\nend\n\n\nsubsection \\<open>Numerals, Arithmetic, and Embedding from R\\<close>\n\ndeclare [[coercion \"of_real :: real \\<Rightarrow> complex\"]]\ndeclare [[coercion \"of_rat :: rat \\<Rightarrow> complex\"]]\ndeclare [[coercion \"of_int :: int \\<Rightarrow> complex\"]]\ndeclare [[coercion \"of_nat :: nat \\<Rightarrow> complex\"]]\n\nabbreviation complex_of_nat::\"nat \\<Rightarrow> complex\"\n  where \"complex_of_nat \\<equiv> of_nat\"\n\nabbreviation complex_of_int::\"int \\<Rightarrow> complex\"\n  where \"complex_of_int \\<equiv> of_int\"\n\nabbreviation complex_of_rat::\"rat \\<Rightarrow> complex\"\n  where \"complex_of_rat \\<equiv> of_rat\"\n\nabbreviation complex_of_real :: \"real \\<Rightarrow> complex\"\n  where \"complex_of_real \\<equiv> of_real\"\n\nlemma complex_Re_of_nat [simp]: \"Re (of_nat n) = of_nat n\"\n  by (induct n) simp_all\n\nlemma complex_Im_of_nat [simp]: \"Im (of_nat n) = 0\"\n  by (induct n) simp_all\n\nlemma complex_Re_of_int [simp]: \"Re (of_int z) = of_int z\"\n  by (cases z rule: int_diff_cases) simp\n\nlemma complex_Im_of_int [simp]: \"Im (of_int z) = 0\"\n  by (cases z rule: int_diff_cases) simp\n\nlemma complex_Re_numeral [simp]: \"Re (numeral v) = numeral v\"\n  using complex_Re_of_int [of \"numeral v\"] by simp\n\nlemma complex_Im_numeral [simp]: \"Im (numeral v) = 0\"\n  using complex_Im_of_int [of \"numeral v\"] by simp\n\nlemma Re_complex_of_real [simp]: \"Re (complex_of_real z) = z\"\n  by (simp add: of_real_def)\n\nlemma Im_complex_of_real [simp]: \"Im (complex_of_real z) = 0\"\n  by (simp add: of_real_def)\n\nlemma Re_divide_numeral [simp]: \"Re (z / numeral w) = Re z / numeral w\"\n  by (simp add: Re_divide sqr_conv_mult)\n\nlemma Im_divide_numeral [simp]: \"Im (z / numeral w) = Im z / numeral w\"\n  by (simp add: Im_divide sqr_conv_mult)\n\nlemma Re_divide_of_nat [simp]: \"Re (z / of_nat n) = Re z / of_nat n\"\n  by (cases n) (simp_all add: Re_divide field_split_simps power2_eq_square del: of_nat_Suc)\n\nlemma Im_divide_of_nat [simp]: \"Im (z / of_nat n) = Im z / of_nat n\"\n  by (cases n) (simp_all add: Im_divide field_split_simps power2_eq_square del: of_nat_Suc)\n\nlemma Re_inverse [simp]: \"r \\<in> \\<real> \\<Longrightarrow> Re (inverse r) = inverse (Re r)\"\n  by (metis Re_complex_of_real Reals_cases of_real_inverse)\n\nlemma Im_inverse [simp]: \"r \\<in> \\<real> \\<Longrightarrow> Im (inverse r) = 0\"\n  by (metis Im_complex_of_real Reals_cases of_real_inverse)\n\nlemma of_real_Re [simp]: \"z \\<in> \\<real> \\<Longrightarrow> of_real (Re z) = z\"\n  by (auto simp: Reals_def)\n\nlemma complex_Re_fact [simp]: \"Re (fact n) = fact n\"\nproof -\n  have \"(fact n :: complex) = of_real (fact n)\"\n    by simp\n  also have \"Re \\<dots> = fact n\"\n    by (subst Re_complex_of_real) simp_all\n  finally show ?thesis .\nqed\n\nlemma surj_Re: \"surj Re\"\n  by (metis Re_complex_of_real surj_def)\n\nlemma surj_Im: \"surj Im\"\n  by (metis complex.sel(2) surj_def)\n\nlemma complex_Im_fact [simp]: \"Im (fact n) = 0\"\n  by (metis complex_Im_of_nat of_nat_fact)\n\nlemma Re_prod_Reals: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> \\<real>) \\<Longrightarrow> Re (prod f A) = prod (\\<lambda>x. Re (f x)) A\"\nproof (induction A rule: infinite_finite_induct)\n  case (insert x A)\n  hence \"Re (prod f (insert x A)) = Re (f x) * Re (prod f A) - Im (f x) * Im (prod f A)\"\n    by simp\n  also from insert.prems have \"f x \\<in> \\<real>\" by simp\n  hence \"Im (f x) = 0\" by (auto elim!: Reals_cases)\n  also have \"Re (prod f A) = (\\<Prod>x\\<in>A. Re (f x))\"\n    by (intro insert.IH insert.prems) auto\n  finally show ?case using insert.hyps by simp\nqed auto\n\n\nsubsection \\<open>The Complex Number $i$\\<close>\n\nprimcorec imaginary_unit :: complex  (\"\\<i>\")\n  where\n    \"Re \\<i> = 0\"\n  | \"Im \\<i> = 1\"\n\nlemma Complex_eq: \"Complex a b = a + \\<i> * b\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_eq: \"a = Re a + \\<i> * Im a\"\n  by (simp add: complex_eq_iff)\n\nlemma fun_complex_eq: \"f = (\\<lambda>x. Re (f x) + \\<i> * Im (f x))\"\n  by (simp add: fun_eq_iff complex_eq)\n\nlemma i_squared [simp]: \"\\<i> * \\<i> = -1\"\n  by (simp add: complex_eq_iff)\n\nlemma power2_i [simp]: \"\\<i>\\<^sup>2 = -1\"\n  by (simp add: power2_eq_square)\n\nlemma inverse_i [simp]: \"inverse \\<i> = - \\<i>\"\n  by (rule inverse_unique) simp\n\nlemma divide_i [simp]: \"x / \\<i> = - \\<i> * x\"\n  by (simp add: divide_complex_def)\n\nlemma complex_i_mult_minus [simp]: \"\\<i> * (\\<i> * x) = - x\"\n  by (simp add: mult.assoc [symmetric])\n\nlemma complex_i_not_zero [simp]: \"\\<i> \\<noteq> 0\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_i_not_one [simp]: \"\\<i> \\<noteq> 1\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_i_not_numeral [simp]: \"\\<i> \\<noteq> numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_i_not_neg_numeral [simp]: \"\\<i> \\<noteq> - numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_split_polar: \"\\<exists>r a. z = complex_of_real r * (cos a + \\<i> * sin a)\"\n  by (simp add: complex_eq_iff polar_Ex)\n\nlemma i_even_power [simp]: \"\\<i> ^ (n * 2) = (-1) ^ n\"\n  by (metis mult.commute power2_i power_mult)\n\nlemma i_even_power' [simp]: \"even n \\<Longrightarrow> \\<i> ^ n = (-1) ^ (n div 2)\"\n  by (metis dvd_mult_div_cancel power2_i power_mult)\n\nlemma Re_i_times [simp]: \"Re (\\<i> * z) = - Im z\"\n  by simp\n\nlemma Im_i_times [simp]: \"Im (\\<i> * z) = Re z\"\n  by simp\n\nlemma i_times_eq_iff: \"\\<i> * w = z \\<longleftrightarrow> w = - (\\<i> * z)\"\n  by auto\n\nlemma divide_numeral_i [simp]: \"z / (numeral n * \\<i>) = - (\\<i> * z) / numeral n\"\n  by (metis divide_divide_eq_left divide_i mult.commute mult_minus_right)\n\nlemma imaginary_eq_real_iff [simp]:\n  assumes \"y \\<in> Reals\" \"x \\<in> Reals\"\n  shows \"\\<i> * y = x \\<longleftrightarrow> x=0 \\<and> y=0\"\n  by (metis Im_complex_of_real Im_i_times assms mult_zero_right of_real_0 of_real_Re)\n\nlemma real_eq_imaginary_iff [simp]:\n  assumes \"y \\<in> Reals\" \"x \\<in> Reals\"\n  shows \"x = \\<i> * y  \\<longleftrightarrow> x=0 \\<and> y=0\"\n    using assms imaginary_eq_real_iff by fastforce\n\nsubsection \\<open>Vector Norm\\<close>\n\ninstantiation complex :: real_normed_field\nbegin\n\ndefinition \"norm z = sqrt ((Re z)\\<^sup>2 + (Im z)\\<^sup>2)\"\n\nabbreviation cmod :: \"complex \\<Rightarrow> real\"\n  where \"cmod \\<equiv> norm\"\n\ndefinition complex_sgn_def: \"sgn x = x /\\<^sub>R cmod x\"\n\ndefinition dist_complex_def: \"dist x y = cmod (x - y)\"\n\ndefinition uniformity_complex_def [code del]:\n  \"(uniformity :: (complex \\<times> complex) filter) = (INF e\\<in>{0 <..}. principal {(x, y). dist x y < e})\"\n\ndefinition open_complex_def [code del]:\n  \"open (U :: complex set) \\<longleftrightarrow> (\\<forall>x\\<in>U. eventually (\\<lambda>(x', y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n\ninstance\nproof\n  fix r :: real and x y :: complex and S :: \"complex set\"\n  show \"(norm x = 0) = (x = 0)\"\n    by (simp add: norm_complex_def complex_eq_iff)\n  show \"norm (x + y) \\<le> norm x + norm y\"\n    by (simp add: norm_complex_def complex_eq_iff real_sqrt_sum_squares_triangle_ineq)\n  show \"norm (scaleR r x) = \\<bar>r\\<bar> * norm x\"\n    by (simp add: norm_complex_def complex_eq_iff power_mult_distrib distrib_left [symmetric]\n        real_sqrt_mult)\n  show \"norm (x * y) = norm x * norm y\"\n    by (simp add: norm_complex_def complex_eq_iff real_sqrt_mult [symmetric]\n        power2_eq_square algebra_simps)\nqed (rule complex_sgn_def dist_complex_def open_complex_def uniformity_complex_def)+\n\nend\n\ndeclare uniformity_Abort[where 'a = complex, code]\n\nlemma norm_ii [simp]: \"norm \\<i> = 1\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_unit_one: \"cmod (cos a + \\<i> * sin a) = 1\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_complex_polar: \"cmod (r * (cos a + \\<i> * sin a)) = \\<bar>r\\<bar>\"\n  by (simp add: norm_mult cmod_unit_one)\n\nlemma complex_Re_le_cmod: \"Re x \\<le> cmod x\"\n  unfolding norm_complex_def by (rule real_sqrt_sum_squares_ge1)\n\nlemma complex_mod_minus_le_complex_mod: \"- cmod x \\<le> cmod x\"\n  by (rule order_trans [OF _ norm_ge_zero]) simp\n\nlemma complex_mod_triangle_ineq2: \"cmod (b + a) - cmod b \\<le> cmod a\"\n  by (rule ord_le_eq_trans [OF norm_triangle_ineq2]) simp\n\nlemma abs_Re_le_cmod: \"\\<bar>Re x\\<bar> \\<le> cmod x\"\n  by (simp add: norm_complex_def)\n\nlemma abs_Im_le_cmod: \"\\<bar>Im x\\<bar> \\<le> cmod x\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_le: \"cmod z \\<le> \\<bar>Re z\\<bar> + \\<bar>Im z\\<bar>\"\n  using norm_complex_def sqrt_sum_squares_le_sum_abs by presburger\n\nlemma cmod_eq_Re: \"Im z = 0 \\<Longrightarrow> cmod z = \\<bar>Re z\\<bar>\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_eq_Im: \"Re z = 0 \\<Longrightarrow> cmod z = \\<bar>Im z\\<bar>\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_power2: \"(cmod z)\\<^sup>2 = (Re z)\\<^sup>2 + (Im z)\\<^sup>2\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_plus_Re_le_0_iff: \"cmod z + Re z \\<le> 0 \\<longleftrightarrow> Re z = - cmod z\"\n  using abs_Re_le_cmod[of z] by auto\n\nlemma cmod_Re_le_iff: \"Im x = Im y \\<Longrightarrow> cmod x \\<le> cmod y \\<longleftrightarrow> \\<bar>Re x\\<bar> \\<le> \\<bar>Re y\\<bar>\"\n  by (metis add.commute add_le_cancel_left norm_complex_def real_sqrt_abs real_sqrt_le_iff)\n\nlemma cmod_Im_le_iff: \"Re x = Re y \\<Longrightarrow> cmod x \\<le> cmod y \\<longleftrightarrow> \\<bar>Im x\\<bar> \\<le> \\<bar>Im y\\<bar>\"\n  by (metis add_le_cancel_left norm_complex_def real_sqrt_abs real_sqrt_le_iff)\n\nlemma Im_eq_0: \"\\<bar>Re z\\<bar> = cmod z \\<Longrightarrow> Im z = 0\"\n  by (subst (asm) power_eq_iff_eq_base[symmetric, where n=2]) (auto simp add: norm_complex_def)\n\nlemma abs_sqrt_wlog: \"(\\<And>x. x \\<ge> 0 \\<Longrightarrow> P x (x\\<^sup>2)) \\<Longrightarrow> P \\<bar>x\\<bar> (x\\<^sup>2)\"\n  for x::\"'a::linordered_idom\"\n  by (metis abs_ge_zero power2_abs)\n\nlemma complex_abs_le_norm: \"\\<bar>Re z\\<bar> + \\<bar>Im z\\<bar> \\<le> sqrt 2 * norm z\"\n  unfolding norm_complex_def\n  apply (rule abs_sqrt_wlog [where x=\"Re z\"])\n  apply (rule abs_sqrt_wlog [where x=\"Im z\"])\n  apply (rule power2_le_imp_le)\n   apply (simp_all add: power2_sum add.commute sum_squares_bound real_sqrt_mult [symmetric])\n  done\n\nlemma complex_unit_circle: \"z \\<noteq> 0 \\<Longrightarrow> (Re z / cmod z)\\<^sup>2 + (Im z / cmod z)\\<^sup>2 = 1\"\n  by (simp add: norm_complex_def complex_eq_iff power2_eq_square add_divide_distrib [symmetric])\n\n\ntext \\<open>Properties of complex signum.\\<close>\n\nlemma sgn_eq: \"sgn z = z / complex_of_real (cmod z)\"\n  by (simp add: sgn_div_norm divide_inverse scaleR_conv_of_real mult.commute)\n\nlemma Re_sgn [simp]: \"Re(sgn z) = Re(z)/cmod z\"\n  by (simp add: complex_sgn_def divide_inverse)\n\nlemma Im_sgn [simp]: \"Im(sgn z) = Im(z)/cmod z\"\n  by (simp add: complex_sgn_def divide_inverse)\n\n\nsubsection \\<open>Absolute value\\<close>\n\n\ninstantiation complex :: field_abs_sgn\nbegin\n\ndefinition abs_complex :: \"complex \\<Rightarrow> complex\"\n  where \"abs_complex = of_real \\<circ> norm\"\n\ninstance\n  proof qed (auto simp add: abs_complex_def complex_sgn_def norm_divide norm_mult scaleR_conv_of_real field_simps)\nend\n\n\nsubsection \\<open>Completeness of the Complexes\\<close>\n\nlemma bounded_linear_Re: \"bounded_linear Re\"\n  by (rule bounded_linear_intro [where K=1]) (simp_all add: norm_complex_def)\n\nlemma bounded_linear_Im: \"bounded_linear Im\"\n  by (rule bounded_linear_intro [where K=1]) (simp_all add: norm_complex_def)\n\nlemmas Cauchy_Re = bounded_linear.Cauchy [OF bounded_linear_Re]\nlemmas Cauchy_Im = bounded_linear.Cauchy [OF bounded_linear_Im]\nlemmas tendsto_Re [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Re]\nlemmas tendsto_Im [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Im]\nlemmas isCont_Re [simp] = bounded_linear.isCont [OF bounded_linear_Re]\nlemmas isCont_Im [simp] = bounded_linear.isCont [OF bounded_linear_Im]\nlemmas continuous_Re [simp] = bounded_linear.continuous [OF bounded_linear_Re]\nlemmas continuous_Im [simp] = bounded_linear.continuous [OF bounded_linear_Im]\nlemmas continuous_on_Re [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Re]\nlemmas continuous_on_Im [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Im]\nlemmas has_derivative_Re [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Re]\nlemmas has_derivative_Im [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Im]\nlemmas sums_Re = bounded_linear.sums [OF bounded_linear_Re]\nlemmas sums_Im = bounded_linear.sums [OF bounded_linear_Im]\nlemmas Re_suminf = bounded_linear.suminf[OF bounded_linear_Re]\nlemmas Im_suminf = bounded_linear.suminf[OF bounded_linear_Im]\n\nlemma tendsto_Complex [tendsto_intros]:\n  \"(f \\<longlongrightarrow> a) F \\<Longrightarrow> (g \\<longlongrightarrow> b) F \\<Longrightarrow> ((\\<lambda>x. Complex (f x) (g x)) \\<longlongrightarrow> Complex a b) F\"\n  unfolding Complex_eq by (auto intro!: tendsto_intros)\n\nlemma tendsto_complex_iff:\n  \"(f \\<longlongrightarrow> x) F \\<longleftrightarrow> (((\\<lambda>x. Re (f x)) \\<longlongrightarrow> Re x) F \\<and> ((\\<lambda>x. Im (f x)) \\<longlongrightarrow> Im x) F)\"\nproof safe\n  assume \"((\\<lambda>x. Re (f x)) \\<longlongrightarrow> Re x) F\" \"((\\<lambda>x. Im (f x)) \\<longlongrightarrow> Im x) F\"\n  from tendsto_Complex[OF this] show \"(f \\<longlongrightarrow> x) F\"\n    unfolding complex.collapse .\nqed (auto intro: tendsto_intros)\n\nlemma continuous_complex_iff:\n  \"continuous F f \\<longleftrightarrow> continuous F (\\<lambda>x. Re (f x)) \\<and> continuous F (\\<lambda>x. Im (f x))\"\n  by (simp only: continuous_def tendsto_complex_iff)\n\nlemma continuous_on_of_real_o_iff [simp]:\n     \"continuous_on S (\\<lambda>x. complex_of_real (g x)) = continuous_on S g\"\n  using continuous_on_Re continuous_on_of_real  by fastforce\n\nlemma continuous_on_of_real_id [simp]:\n     \"continuous_on S (of_real :: real \\<Rightarrow> 'a::real_normed_algebra_1)\"\n  by (rule continuous_on_of_real [OF continuous_on_id])\n\nlemma has_vector_derivative_complex_iff: \"(f has_vector_derivative x) F \\<longleftrightarrow>\n    ((\\<lambda>x. Re (f x)) has_field_derivative (Re x)) F \\<and>\n    ((\\<lambda>x. Im (f x)) has_field_derivative (Im x)) F\"\n  by (simp add: has_vector_derivative_def has_field_derivative_def has_derivative_def\n      tendsto_complex_iff algebra_simps bounded_linear_scaleR_left bounded_linear_mult_right)\n\nlemma has_field_derivative_Re[derivative_intros]:\n  \"(f has_vector_derivative D) F \\<Longrightarrow> ((\\<lambda>x. Re (f x)) has_field_derivative (Re D)) F\"\n  unfolding has_vector_derivative_complex_iff by safe\n\nlemma has_field_derivative_Im[derivative_intros]:\n  \"(f has_vector_derivative D) F \\<Longrightarrow> ((\\<lambda>x. Im (f x)) has_field_derivative (Im D)) F\"\n  unfolding has_vector_derivative_complex_iff by safe\n\ninstance complex :: banach\nproof\n  fix X :: \"nat \\<Rightarrow> complex\"\n  assume X: \"Cauchy X\"\n  then have \"(\\<lambda>n. Complex (Re (X n)) (Im (X n))) \\<longlonglongrightarrow>\n    Complex (lim (\\<lambda>n. Re (X n))) (lim (\\<lambda>n. Im (X n)))\"\n    by (intro tendsto_Complex convergent_LIMSEQ_iff[THEN iffD1]\n        Cauchy_convergent_iff[THEN iffD1] Cauchy_Re Cauchy_Im)\n  then show \"convergent X\"\n    unfolding complex.collapse by (rule convergentI)\nqed\n\ndeclare DERIV_power[where 'a=complex, unfolded of_nat_def[symmetric], derivative_intros]\n\n\nsubsection \\<open>Complex Conjugation\\<close>\n\nprimcorec cnj :: \"complex \\<Rightarrow> complex\"\n  where\n    \"Re (cnj z) = Re z\"\n  | \"Im (cnj z) = - Im z\"\n\nlemma complex_cnj_cancel_iff [simp]: \"cnj x = cnj y \\<longleftrightarrow> x = y\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_cnj [simp]: \"cnj (cnj z) = z\"\n  by (simp add: complex_eq_iff)\n\nlemma in_image_cnj_iff: \"z \\<in> cnj ` A \\<longleftrightarrow> cnj z \\<in> A\"\n  by (metis complex_cnj_cnj image_iff)\n\nlemma image_cnj_conv_vimage_cnj: \"cnj ` A = cnj -` A\"\n  using in_image_cnj_iff by blast\n\nlemma complex_cnj_zero [simp]: \"cnj 0 = 0\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_zero_iff [iff]: \"cnj z = 0 \\<longleftrightarrow> z = 0\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_one_iff [simp]: \"cnj z = 1 \\<longleftrightarrow> z = 1\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_add [simp]: \"cnj (x + y) = cnj x + cnj y\"\n  by (simp add: complex_eq_iff)\n\nlemma cnj_sum [simp]: \"cnj (sum f s) = (\\<Sum>x\\<in>s. cnj (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma complex_cnj_diff [simp]: \"cnj (x - y) = cnj x - cnj y\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_minus [simp]: \"cnj (- x) = - cnj x\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_one [simp]: \"cnj 1 = 1\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_mult [simp]: \"cnj (x * y) = cnj x * cnj y\"\n  by (simp add: complex_eq_iff)\n\nlemma cnj_prod [simp]: \"cnj (prod f s) = (\\<Prod>x\\<in>s. cnj (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma complex_cnj_inverse [simp]: \"cnj (inverse x) = inverse (cnj x)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_divide [simp]: \"cnj (x / y) = cnj x / cnj y\"\n  by (simp add: divide_complex_def)\n\nlemma complex_cnj_power [simp]: \"cnj (x ^ n) = cnj x ^ n\"\n  by (induct n) simp_all\n\nlemma complex_cnj_of_nat [simp]: \"cnj (of_nat n) = of_nat n\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_of_int [simp]: \"cnj (of_int z) = of_int z\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_numeral [simp]: \"cnj (numeral w) = numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_neg_numeral [simp]: \"cnj (- numeral w) = - numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_scaleR [simp]: \"cnj (scaleR r x) = scaleR r (cnj x)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_mod_cnj [simp]: \"cmod (cnj z) = cmod z\"\n  by (simp add: norm_complex_def)\n\nlemma complex_cnj_complex_of_real [simp]: \"cnj (of_real x) = of_real x\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_i [simp]: \"cnj \\<i> = - \\<i>\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_add_cnj: \"z + cnj z = complex_of_real (2 * Re z)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_diff_cnj: \"z - cnj z = complex_of_real (2 * Im z) * \\<i>\"\n  by (simp add: complex_eq_iff)\n\nlemma Ints_cnj [intro]: \"x \\<in> \\<int> \\<Longrightarrow> cnj x \\<in> \\<int>\"\n  by (auto elim!: Ints_cases)\n\nlemma cnj_in_Ints_iff [simp]: \"cnj x \\<in> \\<int> \\<longleftrightarrow> x \\<in> \\<int>\"\n  using Ints_cnj[of x] Ints_cnj[of \"cnj x\"] by auto\n\nlemma complex_mult_cnj: \"z * cnj z = complex_of_real ((Re z)\\<^sup>2 + (Im z)\\<^sup>2)\"\n  by (simp add: complex_eq_iff power2_eq_square)\n\nlemma cnj_add_mult_eq_Re: \"z * cnj w + cnj z * w = 2 * Re (z * cnj w)\"\n  by (rule complex_eqI) auto\n\nlemma complex_mod_mult_cnj: \"cmod (z * cnj z) = (cmod z)\\<^sup>2\"\n  by (simp add: norm_mult power2_eq_square)\n\nlemma complex_mod_sqrt_Re_mult_cnj: \"cmod z = sqrt (Re (z * cnj z))\"\n  by (simp add: norm_complex_def power2_eq_square)\n\nlemma complex_In_mult_cnj_zero [simp]: \"Im (z * cnj z) = 0\"\n  by simp\n\nlemma complex_cnj_fact [simp]: \"cnj (fact n) = fact n\"\n  by (subst of_nat_fact [symmetric], subst complex_cnj_of_nat) simp\n\nlemma complex_cnj_pochhammer [simp]: \"cnj (pochhammer z n) = pochhammer (cnj z) n\"\n  by (induct n arbitrary: z) (simp_all add: pochhammer_rec)\n\nlemma bounded_linear_cnj: \"bounded_linear cnj\"\n  using complex_cnj_add complex_cnj_scaleR by (rule bounded_linear_intro [where K=1]) simp\n\nlemma linear_cnj: \"linear cnj\"\n  using bounded_linear.linear[OF bounded_linear_cnj] .\n\nlemmas tendsto_cnj [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_cnj]\n  and isCont_cnj [simp] = bounded_linear.isCont [OF bounded_linear_cnj]\n  and continuous_cnj [simp, continuous_intros] = bounded_linear.continuous [OF bounded_linear_cnj]\n  and continuous_on_cnj [simp, continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_cnj]\n  and has_derivative_cnj [simp, derivative_intros] = bounded_linear.has_derivative [OF bounded_linear_cnj]\n\nlemma lim_cnj: \"((\\<lambda>x. cnj(f x)) \\<longlongrightarrow> cnj l) F \\<longleftrightarrow> (f \\<longlongrightarrow> l) F\"\n  by (simp add: tendsto_iff dist_complex_def complex_cnj_diff [symmetric] del: complex_cnj_diff)\n\nlemma sums_cnj: \"((\\<lambda>x. cnj(f x)) sums cnj l) \\<longleftrightarrow> (f sums l)\"\n  by (simp add: sums_def lim_cnj cnj_sum [symmetric] del: cnj_sum)\n\nlemma differentiable_cnj_iff:\n  \"(\\<lambda>z. cnj (f z)) differentiable at x within A \\<longleftrightarrow> f differentiable at x within A\"\nproof\n  assume \"(\\<lambda>z. cnj (f z)) differentiable at x within A\"\n  then obtain D where \"((\\<lambda>z. cnj (f z)) has_derivative D) (at x within A)\"\n    by (auto simp: differentiable_def)\n  from has_derivative_cnj[OF this] show \"f differentiable at x within A\"\n    by (auto simp: differentiable_def)\nnext\n  assume \"f differentiable at x within A\"\n  then obtain D where \"(f has_derivative D) (at x within A)\"\n    by (auto simp: differentiable_def)\n  from has_derivative_cnj[OF this] show \"(\\<lambda>z. cnj (f z)) differentiable at x within A\"\n    by (auto simp: differentiable_def)\nqed\n\nlemma has_vector_derivative_cnj [derivative_intros]:\n  assumes \"(f has_vector_derivative f') (at z within A)\"\n  shows   \"((\\<lambda>z. cnj (f z)) has_vector_derivative cnj f') (at z within A)\"\n  using assms by (auto simp: has_vector_derivative_complex_iff intro: derivative_intros)\n\nlemma has_field_derivative_cnj_cnj:\n  assumes \"(f has_field_derivative F) (at (cnj z))\"\n  shows   \"((cnj \\<circ> f \\<circ> cnj) has_field_derivative cnj F) (at z)\"\nproof -\n  have \"cnj \\<midarrow>0\\<rightarrow> cnj 0\"\n    by (subst lim_cnj) auto\n  also have \"cnj 0 = 0\"\n    by simp\n  finally have *: \"filterlim cnj (at 0) (at 0)\"\n    by (auto simp: filterlim_at eventually_at_filter)\n  have \"(\\<lambda>h. (f (cnj z + cnj h) - f (cnj z)) / cnj h) \\<midarrow>0\\<rightarrow> F\"\n    by (rule filterlim_compose[OF _ *]) (use assms in \\<open>auto simp: DERIV_def\\<close>)\n  thus ?thesis\n    by (subst (asm) lim_cnj [symmetric]) (simp add: DERIV_def)\nqed\n\n\nsubsection \\<open>Basic Lemmas\\<close>\n\nlemma complex_of_real_code[code_unfold]: \"of_real = (\\<lambda>x. Complex x 0)\" \n  by (intro ext, auto simp: complex_eq_iff)\n\nlemma complex_eq_0: \"z=0 \\<longleftrightarrow> (Re z)\\<^sup>2 + (Im z)\\<^sup>2 = 0\"\n  by (metis zero_complex.sel complex_eqI sum_power2_eq_zero_iff)\n\nlemma complex_neq_0: \"z\\<noteq>0 \\<longleftrightarrow> (Re z)\\<^sup>2 + (Im z)\\<^sup>2 > 0\"\n  by (metis complex_eq_0 less_numeral_extra(3) sum_power2_gt_zero_iff)\n\nlemma complex_norm_square: \"of_real ((norm z)\\<^sup>2) = z * cnj z\"\n  by (cases z)\n    (auto simp: complex_eq_iff norm_complex_def power2_eq_square[symmetric] of_real_power[symmetric]\n      simp del: of_real_power)\n\nlemma complex_div_cnj: \"a / b = (a * cnj b) / (norm b)\\<^sup>2\"\n  using complex_norm_square by auto\n\nlemma Re_complex_div_eq_0: \"Re (a / b) = 0 \\<longleftrightarrow> Re (a * cnj b) = 0\"\n  by (auto simp add: Re_divide)\n\nlemma Im_complex_div_eq_0: \"Im (a / b) = 0 \\<longleftrightarrow> Im (a * cnj b) = 0\"\n  by (auto simp add: Im_divide)\n\nlemma complex_div_gt_0: \"(Re (a / b) > 0 \\<longleftrightarrow> Re (a * cnj b) > 0) \\<and> (Im (a / b) > 0 \\<longleftrightarrow> Im (a * cnj b) > 0)\"\nproof (cases \"b = 0\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have \"0 < (Re b)\\<^sup>2 + (Im b)\\<^sup>2\"\n    by (simp add: complex_eq_iff sum_power2_gt_zero_iff)\n  then show ?thesis\n    by (simp add: Re_divide Im_divide zero_less_divide_iff)\nqed\n\nlemma Re_complex_div_gt_0: \"Re (a / b) > 0 \\<longleftrightarrow> Re (a * cnj b) > 0\"\n  and Im_complex_div_gt_0: \"Im (a / b) > 0 \\<longleftrightarrow> Im (a * cnj b) > 0\"\n  using complex_div_gt_0 by auto\n\nlemma Re_complex_div_ge_0: \"Re (a / b) \\<ge> 0 \\<longleftrightarrow> Re (a * cnj b) \\<ge> 0\"\n  by (metis le_less Re_complex_div_eq_0 Re_complex_div_gt_0)\n\nlemma Im_complex_div_ge_0: \"Im (a / b) \\<ge> 0 \\<longleftrightarrow> Im (a * cnj b) \\<ge> 0\"\n  by (metis Im_complex_div_eq_0 Im_complex_div_gt_0 le_less)\n\nlemma Re_complex_div_lt_0: \"Re (a / b) < 0 \\<longleftrightarrow> Re (a * cnj b) < 0\"\n  by (metis less_asym neq_iff Re_complex_div_eq_0 Re_complex_div_gt_0)\n\nlemma Im_complex_div_lt_0: \"Im (a / b) < 0 \\<longleftrightarrow> Im (a * cnj b) < 0\"\n  by (metis Im_complex_div_eq_0 Im_complex_div_gt_0 less_asym neq_iff)\n\nlemma Re_complex_div_le_0: \"Re (a / b) \\<le> 0 \\<longleftrightarrow> Re (a * cnj b) \\<le> 0\"\n  by (metis not_le Re_complex_div_gt_0)\n\nlemma Im_complex_div_le_0: \"Im (a / b) \\<le> 0 \\<longleftrightarrow> Im (a * cnj b) \\<le> 0\"\n  by (metis Im_complex_div_gt_0 not_le)\n\nlemma Re_divide_of_real [simp]: \"Re (z / of_real r) = Re z / r\"\n  by (simp add: Re_divide power2_eq_square)\n\nlemma Im_divide_of_real [simp]: \"Im (z / of_real r) = Im z / r\"\n  by (simp add: Im_divide power2_eq_square)\n\nlemma Re_divide_Reals [simp]: \"r \\<in> \\<real> \\<Longrightarrow> Re (z / r) = Re z / Re r\"\n  by (metis Re_divide_of_real of_real_Re)\n\nlemma Im_divide_Reals [simp]: \"r \\<in> \\<real> \\<Longrightarrow> Im (z / r) = Im z / Re r\"\n  by (metis Im_divide_of_real of_real_Re)\n\nlemma Re_sum[simp]: \"Re (sum f s) = (\\<Sum>x\\<in>s. Re (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma Im_sum[simp]: \"Im (sum f s) = (\\<Sum>x\\<in>s. Im(f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma sum_Re_le_cmod: \"(\\<Sum>i\\<in>I. Re (z i)) \\<le> cmod (\\<Sum>i\\<in>I. z i)\"\n  by (metis Re_sum complex_Re_le_cmod)\n\nlemma sum_Im_le_cmod: \"(\\<Sum>i\\<in>I. Im (z i)) \\<le> cmod (\\<Sum>i\\<in>I. z i)\"\n  by (smt (verit, best) Im_sum abs_Im_le_cmod sum.cong)\n\nlemma sums_complex_iff: \"f sums x \\<longleftrightarrow> ((\\<lambda>x. Re (f x)) sums Re x) \\<and> ((\\<lambda>x. Im (f x)) sums Im x)\"\n  unfolding sums_def tendsto_complex_iff Im_sum Re_sum ..\n\nlemma summable_complex_iff: \"summable f \\<longleftrightarrow> summable (\\<lambda>x. Re (f x)) \\<and>  summable (\\<lambda>x. Im (f x))\"\n  unfolding summable_def sums_complex_iff[abs_def] by (metis complex.sel)\n\nlemma summable_complex_of_real [simp]: \"summable (\\<lambda>n. complex_of_real (f n)) \\<longleftrightarrow> summable f\"\n  unfolding summable_complex_iff by simp\n\nlemma summable_Re: \"summable f \\<Longrightarrow> summable (\\<lambda>x. Re (f x))\"\n  unfolding summable_complex_iff by blast\n\nlemma summable_Im: \"summable f \\<Longrightarrow> summable (\\<lambda>x. Im (f x))\"\n  unfolding summable_complex_iff by blast\n\nlemma complex_is_Nat_iff: \"z \\<in> \\<nat> \\<longleftrightarrow> Im z = 0 \\<and> (\\<exists>i. Re z = of_nat i)\"\n  by (auto simp: Nats_def complex_eq_iff)\n\nlemma complex_is_Int_iff: \"z \\<in> \\<int> \\<longleftrightarrow> Im z = 0 \\<and> (\\<exists>i. Re z = of_int i)\"\n  by (auto simp: Ints_def complex_eq_iff)\n\nlemma complex_is_Real_iff: \"z \\<in> \\<real> \\<longleftrightarrow> Im z = 0\"\n  by (auto simp: Reals_def complex_eq_iff)\n\nlemma Reals_cnj_iff: \"z \\<in> \\<real> \\<longleftrightarrow> cnj z = z\"\n  by (auto simp: complex_is_Real_iff complex_eq_iff)\n\nlemma in_Reals_norm: \"z \\<in> \\<real> \\<Longrightarrow> norm z = \\<bar>Re z\\<bar>\"\n  by (simp add: complex_is_Real_iff norm_complex_def)\n\nlemma Re_Reals_divide: \"r \\<in> \\<real> \\<Longrightarrow> Re (r / z) = Re r * Re z / (norm z)\\<^sup>2\"\n  by (simp add: Re_divide complex_is_Real_iff cmod_power2)\n\nlemma Im_Reals_divide: \"r \\<in> \\<real> \\<Longrightarrow> Im (r / z) = -Re r * Im z / (norm z)\\<^sup>2\"\n  by (simp add: Im_divide complex_is_Real_iff cmod_power2)\n\nlemma series_comparison_complex:\n  fixes f:: \"nat \\<Rightarrow> 'a::banach\"\n  assumes sg: \"summable g\"\n    and \"\\<And>n. g n \\<in> \\<real>\" \"\\<And>n. Re (g n) \\<ge> 0\"\n    and fg: \"\\<And>n. n \\<ge> N \\<Longrightarrow> norm(f n) \\<le> norm(g n)\"\n  shows \"summable f\"\nproof -\n  have g: \"\\<And>n. cmod (g n) = Re (g n)\"\n    using assms by (metis abs_of_nonneg in_Reals_norm)\n  show ?thesis\n    by (metis fg g sg summable_comparison_test summable_complex_iff)\nqed\n\n\nsubsection \\<open>Polar Form for Complex Numbers\\<close>\n\nlemma complex_unimodular_polar:\n  assumes \"norm z = 1\"\n  obtains t where \"0 \\<le> t\" \"t < 2 * pi\" \"z = Complex (cos t) (sin t)\"\n  by (metis cmod_power2 one_power2 complex_surj sincos_total_2pi [of \"Re z\" \"Im z\"] assms)\n\n\nsubsubsection \\<open>$\\cos \\theta + i \\sin \\theta$\\<close>\n\nprimcorec cis :: \"real \\<Rightarrow> complex\"\n  where\n    \"Re (cis a) = cos a\"\n  | \"Im (cis a) = sin a\"\n\nlemma cis_zero [simp]: \"cis 0 = 1\"\n  by (simp add: complex_eq_iff)\n\nlemma norm_cis [simp]: \"norm (cis a) = 1\"\n  by (simp add: norm_complex_def)\n\nlemma sgn_cis [simp]: \"sgn (cis a) = cis a\"\n  by (simp add: sgn_div_norm)\n\nlemma cis_2pi [simp]: \"cis (2 * pi) = 1\"\n  by (simp add: cis.ctr complex_eq_iff)\n\nlemma cis_neq_zero [simp]: \"cis a \\<noteq> 0\"\n  by (metis norm_cis norm_zero zero_neq_one)\n\nlemma cis_cnj: \"cnj (cis t) = cis (-t)\"\n  by (simp add: complex_eq_iff)\n\nlemma cis_mult: \"cis a * cis b = cis (a + b)\"\n  by (simp add: complex_eq_iff cos_add sin_add)\n\nlemma DeMoivre: \"(cis a) ^ n = cis (real n * a)\"\n  by (induct n) (simp_all add: algebra_simps cis_mult)\n\nlemma cis_inverse [simp]: \"inverse (cis a) = cis (- a)\"\n  by (simp add: complex_eq_iff)\n\nlemma cis_divide: \"cis a / cis b = cis (a - b)\"\n  by (simp add: divide_complex_def cis_mult)\n\nlemma divide_conv_cnj: \"norm z = 1 \\<Longrightarrow> x / z = x * cnj z\"\n  by (metis complex_div_cnj div_by_1 mult_1 of_real_1 power2_eq_square)\n\nlemma i_not_in_Reals [simp, intro]: \"\\<i> \\<notin> \\<real>\"\n  by (auto simp: complex_is_Real_iff)\n\nlemma powr_power_complex: \"z \\<noteq> 0 \\<or> n \\<noteq> 0 \\<Longrightarrow> (z powr u :: complex) ^ n = z powr (of_nat n * u)\"\n  by (induction n) (auto simp: algebra_simps powr_add)\n  \nlemma cos_n_Re_cis_pow_n: \"cos (real n * a) = Re (cis a ^ n)\"\n  by (auto simp add: DeMoivre)\n\nlemma sin_n_Im_cis_pow_n: \"sin (real n * a) = Im (cis a ^ n)\"\n  by (auto simp add: DeMoivre)\n\nlemma cis_pi [simp]: \"cis pi = -1\"\n  by (simp add: complex_eq_iff)\n\nlemma cis_pi_half[simp]: \"cis (pi / 2) = \\<i>\"\n  by (simp add: cis.ctr complex_eq_iff)\n\nlemma cis_minus_pi_half[simp]: \"cis (-(pi / 2)) = -\\<i>\"\n  by (simp add: cis.ctr complex_eq_iff)\n\nlemma cis_multiple_2pi[simp]: \"n \\<in> \\<int> \\<Longrightarrow> cis (2 * pi * n) = 1\"\n  by (auto elim!: Ints_cases simp: cis.ctr one_complex.ctr)\n\nlemma minus_cis: \"-cis x = cis (x + pi)\"\n  by (simp flip: cis_mult)\n\nlemma minus_cis': \"-cis x = cis (x - pi)\"\n  by (simp flip: cis_divide)\n\nsubsubsection \\<open>$r(\\cos \\theta + i \\sin \\theta)$\\<close>\n\ndefinition rcis :: \"real \\<Rightarrow> real \\<Rightarrow> complex\"\n  where \"rcis r a = complex_of_real r * cis a\"\n\nlemma Re_rcis [simp]: \"Re(rcis r a) = r * cos a\"\n  by (simp add: rcis_def)\n\nlemma Im_rcis [simp]: \"Im(rcis r a) = r * sin a\"\n  by (simp add: rcis_def)\n\nlemma rcis_Ex: \"\\<exists>r a. z = rcis r a\"\n  by (simp add: complex_eq_iff polar_Ex)\n\nlemma complex_mod_rcis [simp]: \"cmod (rcis r a) = \\<bar>r\\<bar>\"\n  by (simp add: rcis_def norm_mult)\n\nlemma cis_rcis_eq: \"cis a = rcis 1 a\"\n  by (simp add: rcis_def)\n\nlemma rcis_mult: \"rcis r1 a * rcis r2 b = rcis (r1 * r2) (a + b)\"\n  by (simp add: rcis_def cis_mult)\n\nlemma rcis_zero_mod [simp]: \"rcis 0 a = 0\"\n  by (simp add: rcis_def)\n\nlemma rcis_zero_arg [simp]: \"rcis r 0 = complex_of_real r\"\n  by (simp add: rcis_def)\n\nlemma rcis_eq_zero_iff [simp]: \"rcis r a = 0 \\<longleftrightarrow> r = 0\"\n  by (simp add: rcis_def)\n\nlemma DeMoivre2: \"(rcis r a) ^ n = rcis (r ^ n) (real n * a)\"\n  by (simp add: rcis_def power_mult_distrib DeMoivre)\n\nlemma rcis_inverse: \"inverse(rcis r a) = rcis (1 / r) (- a)\"\n  by (simp add: divide_inverse rcis_def)\n\nlemma rcis_divide: \"rcis r1 a / rcis r2 b = rcis (r1 / r2) (a - b)\"\n  by (simp add: rcis_def cis_divide [symmetric])\n\nsubsubsection \\<open>Complex exponential\\<close>\n\nlemma exp_Reals_eq:\n  assumes \"z \\<in> \\<real>\"\n  shows   \"exp z = of_real (exp (Re z))\"\n  using assms by (auto elim!: Reals_cases simp: exp_of_real)\n\nlemma cis_conv_exp: \"cis b = exp (\\<i> * b)\"\nproof -\n  have \"(\\<i> * complex_of_real b) ^ n /\\<^sub>R fact n =\n      of_real (cos_coeff n * b^n) + \\<i> * of_real (sin_coeff n * b^n)\"\n    for n :: nat\n  proof -\n    have \"\\<i> ^ n = fact n *\\<^sub>R (cos_coeff n + \\<i> * sin_coeff n)\"\n      by (induct n)\n        (simp_all add: sin_coeff_Suc cos_coeff_Suc complex_eq_iff Re_divide Im_divide field_simps\n          power2_eq_square add_nonneg_eq_0_iff)\n    then show ?thesis\n      by (simp add: field_simps)\n  qed\n  then show ?thesis\n    using sin_converges [of b] cos_converges [of b]\n    by (auto simp add: Complex_eq cis.ctr exp_def simp del: of_real_mult\n        intro!: sums_unique sums_add sums_mult sums_of_real)\nqed\n\nlemma exp_eq_polar: \"exp z = exp (Re z) * cis (Im z)\"\n  unfolding cis_conv_exp exp_of_real [symmetric] mult_exp_exp\n  by (cases z) (simp add: Complex_eq)\n\nlemma Re_exp: \"Re (exp z) = exp (Re z) * cos (Im z)\"\n  unfolding exp_eq_polar by simp\n\nlemma Im_exp: \"Im (exp z) = exp (Re z) * sin (Im z)\"\n  unfolding exp_eq_polar by simp\n\nlemma norm_cos_sin [simp]: \"norm (Complex (cos t) (sin t)) = 1\"\n  by (simp add: norm_complex_def)\n\nlemma norm_exp_eq_Re [simp]: \"norm (exp z) = exp (Re z)\"\n  by (simp add: cis.code cmod_complex_polar exp_eq_polar Complex_eq)\n\nlemma complex_exp_exists: \"\\<exists>a r. z = complex_of_real r * exp a\"\n  using cis_conv_exp rcis_Ex rcis_def by force\n\nlemma exp_pi_i [simp]: \"exp (of_real pi * \\<i>) = -1\"\n  by (metis cis_conv_exp cis_pi mult.commute)\n\nlemma exp_pi_i' [simp]: \"exp (\\<i> * of_real pi) = -1\"\n  using cis_conv_exp cis_pi by auto\n\nlemma exp_two_pi_i [simp]: \"exp (2 * of_real pi * \\<i>) = 1\"\n  by (simp add: exp_eq_polar complex_eq_iff)\n\nlemma exp_two_pi_i' [simp]: \"exp (\\<i> * (of_real pi * 2)) = 1\"\n  by (metis exp_two_pi_i mult.commute)\n\nlemma continuous_on_cis [continuous_intros]:\n  \"continuous_on A f \\<Longrightarrow> continuous_on A (\\<lambda>x. cis (f x))\"\n  by (auto simp: cis_conv_exp intro!: continuous_intros)\n\nlemma tendsto_exp_0_Re_at_bot: \"(exp \\<longlongrightarrow> 0) (filtercomap Re at_bot)\"\nproof -\n  have \"((\\<lambda>z. cmod (exp z)) \\<longlongrightarrow> 0) (filtercomap Re at_bot)\"\n    by (auto intro!: filterlim_filtercomapI exp_at_bot)\n  thus ?thesis\n    using tendsto_norm_zero_iff by blast\nqed\n\nlemma filterlim_exp_at_infinity_Re_at_top: \"filterlim exp at_infinity (filtercomap Re at_top)\"\nproof -\n  have \"filterlim (\\<lambda>z. norm (exp z)) at_top (filtercomap Re at_top)\"\n    by (auto intro!: filterlim_filtercomapI exp_at_top)\n  thus ?thesis\n    using filterlim_norm_at_top_imp_at_infinity by blast\nqed\n\nsubsubsection \\<open>Complex argument\\<close>\n\ndefinition Arg :: \"complex \\<Rightarrow> real\"\n  where \"Arg z = (if z = 0 then 0 else (SOME a. sgn z = cis a \\<and> - pi < a \\<and> a \\<le> pi))\"\n\nlemma Arg_zero: \"Arg 0 = 0\"\n  by (simp add: Arg_def)\n\nlemma cis_Arg_unique:\n  assumes \"sgn z = cis x\" and \"-pi < x\" and \"x \\<le> pi\"\n  shows \"Arg z = x\"\nproof -\n  from assms have \"z \\<noteq> 0\" by auto\n  have \"(SOME a. sgn z = cis a \\<and> -pi < a \\<and> a \\<le> pi) = x\"\n  proof\n    fix a\n    define d where \"d = a - x\"\n    assume a: \"sgn z = cis a \\<and> - pi < a \\<and> a \\<le> pi\"\n    from a assms have \"- (2*pi) < d \\<and> d < 2*pi\"\n      unfolding d_def by simp\n    moreover\n    from a assms have \"cos a = cos x\" and \"sin a = sin x\"\n      by (simp_all add: complex_eq_iff)\n    then have cos: \"cos d = 1\"\n      by (simp add: d_def cos_diff)\n    moreover from cos have \"sin d = 0\"\n      by (rule cos_one_sin_zero)\n    ultimately have \"d = 0\"\n      by (auto simp: sin_zero_iff elim!: evenE dest!: less_2_cases)\n    then show \"a = x\"\n      by (simp add: d_def)\n  qed (simp add: assms del: Re_sgn Im_sgn)\n  with \\<open>z \\<noteq> 0\\<close> show \"Arg z = x\"\n    by (simp add: Arg_def)\nqed\n\nlemma Arg_correct:\n  assumes \"z \\<noteq> 0\"\n  shows \"sgn z = cis (Arg z) \\<and> -pi < Arg z \\<and> Arg z \\<le> pi\"\nproof (simp add: Arg_def assms, rule someI_ex)\n  obtain r a where z: \"z = rcis r a\"\n    using rcis_Ex by fast\n  with assms have \"r \\<noteq> 0\" by auto\n  define b where \"b = (if 0 < r then a else a + pi)\"\n  have b: \"sgn z = cis b\"\n    using \\<open>r \\<noteq> 0\\<close> by (simp add: z b_def rcis_def of_real_def sgn_scaleR sgn_if complex_eq_iff)\n  have cis_2pi_nat: \"cis (2 * pi * real_of_nat n) = 1\" for n\n    by (induct n) (simp_all add: distrib_left cis_mult [symmetric] complex_eq_iff)\n  have cis_2pi_int: \"cis (2 * pi * real_of_int x) = 1\" for x\n    by (cases x rule: int_diff_cases)\n      (simp add: right_diff_distrib cis_divide [symmetric] cis_2pi_nat)\n  define c where \"c = b - 2 * pi * of_int \\<lceil>(b - pi) / (2 * pi)\\<rceil>\"\n  have \"sgn z = cis c\"\n    by (simp add: b c_def cis_divide [symmetric] cis_2pi_int)\n  moreover have \"- pi < c \\<and> c \\<le> pi\"\n    using ceiling_correct [of \"(b - pi) / (2*pi)\"]\n    by (simp add: c_def less_divide_eq divide_le_eq algebra_simps del: le_of_int_ceiling)\n  ultimately show \"\\<exists>a. sgn z = cis a \\<and> -pi < a \\<and> a \\<le> pi\"\n    by fast\nqed\n\nlemma Arg_bounded: \"- pi < Arg z \\<and> Arg z \\<le> pi\"\n  by (cases \"z = 0\") (simp_all add: Arg_zero Arg_correct)\n\nlemma cis_Arg: \"z \\<noteq> 0 \\<Longrightarrow> cis (Arg z) = sgn z\"\n  by (simp add: Arg_correct)\n\nlemma rcis_cmod_Arg: \"rcis (cmod z) (Arg z) = z\"\n  by (cases \"z = 0\") (simp_all add: rcis_def cis_Arg sgn_div_norm of_real_def)\n\nlemma rcis_cnj:\n  shows \"cnj a = rcis (cmod a) (- Arg a)\"\n  by (metis cis_cnj complex_cnj_complex_of_real complex_cnj_mult rcis_cmod_Arg rcis_def)\n\nlemma cos_Arg_i_mult_zero [simp]: \"y \\<noteq> 0 \\<Longrightarrow> Re y = 0 \\<Longrightarrow> cos (Arg y) = 0\"\n  using cis_Arg [of y] by (simp add: complex_eq_iff)\n\nlemma Arg_ii [simp]: \"Arg \\<i> = pi/2\"\n  by (rule cis_Arg_unique; simp add: sgn_eq)\n\nlemma Arg_minus_ii [simp]: \"Arg (-\\<i>) = -pi/2\"\nproof (rule cis_Arg_unique)\n  show \"sgn (- \\<i>) = cis (- pi / 2)\"\n    by (simp add: sgn_eq)\n  show \"- pi / 2 \\<le> pi\"\n    using pi_not_less_zero by linarith\nqed auto\n\nlemma cos_Arg: \"z \\<noteq> 0 \\<Longrightarrow> cos (Arg z) = Re z / norm z\"\n  by (metis Re_sgn cis.sel(1) cis_Arg)\n\nlemma sin_Arg: \"z \\<noteq> 0 \\<Longrightarrow> sin (Arg z) = Im z / norm z\"\n  by (metis Im_sgn cis.sel(2) cis_Arg)\n\nsubsection \\<open>Complex n-th roots\\<close>\n\nlemma bij_betw_roots_unity:\n  assumes \"n > 0\"\n  shows   \"bij_betw (\\<lambda>k. cis (2 * pi * real k / real n)) {..<n} {z. z ^ n = 1}\"\n    (is \"bij_betw ?f _ _\")\n  unfolding bij_betw_def\nproof (intro conjI)\n  show inj: \"inj_on ?f {..<n}\" unfolding inj_on_def\n  proof (safe, goal_cases)\n    case (1 k l)\n    hence kl: \"k < n\" \"l < n\" by simp_all\n    from 1 have \"1 = ?f k / ?f l\" by simp\n    also have \"\\<dots> = cis (2*pi*(real k - real l)/n)\"\n      using assms by (simp add: field_simps cis_divide)\n    finally have \"cos (2*pi*(real k - real l) / n) = 1\"\n      by (simp add: complex_eq_iff)\n    then obtain m :: int where \"2 * pi * (real k - real l) / real n = real_of_int m * 2 * pi\"\n      by (subst (asm) cos_one_2pi_int) blast\n    hence \"real_of_int (int k - int l) = real_of_int (m * int n)\"\n      unfolding of_int_diff of_int_mult using assms\n      by (simp add: nonzero_divide_eq_eq)\n    also note of_int_eq_iff\n    finally have *: \"abs m * n = abs (int k - int l)\" by (simp add: abs_mult)\n    also have \"\\<dots> < int n\" using kl by linarith\n    finally have \"m = 0\" using assms by simp\n    with * show \"k = l\" by simp\n  qed\n\n  have subset: \"?f ` {..<n} \\<subseteq> {z. z ^ n = 1}\"\n  proof safe\n    fix k :: nat\n    have \"cis (2 * pi * real k / real n) ^ n = cis (2 * pi) ^ k\"\n      using assms by (simp add: DeMoivre mult_ac)\n    also have \"cis (2 * pi) = 1\" by (simp add: complex_eq_iff)\n    finally show \"?f k ^ n = 1\" by simp\n  qed\n\n  have \"n = card {..<n}\" by simp\n  also from assms and subset have \"\\<dots> \\<le> card {z::complex. z ^ n = 1}\"\n    by (intro card_inj_on_le[OF inj]) (auto simp: finite_roots_unity)\n  finally have card: \"card {z::complex. z ^ n = 1} = n\"\n    using assms by (intro antisym card_roots_unity) auto\n\n  have \"card (?f ` {..<n}) = card {z::complex. z ^ n = 1}\"\n    using card inj by (subst card_image) auto\n  with subset and assms show \"?f ` {..<n} = {z::complex. z ^ n = 1}\"\n    by (intro card_subset_eq finite_roots_unity) auto\nqed\n\nlemma card_roots_unity_eq:\n  assumes \"n > 0\"\n  shows   \"card {z::complex. z ^ n = 1} = n\"\n  using bij_betw_same_card [OF bij_betw_roots_unity [OF assms]] by simp\n\nlemma bij_betw_nth_root_unity:\n  fixes c :: complex and n :: nat\n  assumes c: \"c \\<noteq> 0\" and n: \"n > 0\"\n  defines \"c' \\<equiv> root n (norm c) * cis (Arg c / n)\"\n  shows \"bij_betw (\\<lambda>z. c' * z) {z. z ^ n = 1} {z. z ^ n = c}\"\nproof -\n  have \"c' ^ n = of_real (root n (norm c) ^ n) * cis (Arg c)\"\n    unfolding of_real_power using n by (simp add: c'_def power_mult_distrib DeMoivre)\n  also from n have \"root n (norm c) ^ n = norm c\" by simp\n  also from c have \"of_real \\<dots> * cis (Arg c) = c\" by (simp add: cis_Arg Complex.sgn_eq)\n  finally have [simp]: \"c' ^ n = c\" .\n\n  show ?thesis unfolding bij_betw_def inj_on_def\n  proof safe\n    fix z :: complex assume \"z ^ n = 1\"\n    hence \"(c' * z) ^ n = c' ^ n\" by (simp add: power_mult_distrib)\n    also have \"c' ^ n = of_real (root n (norm c) ^ n) * cis (Arg c)\"\n      unfolding of_real_power using n by (simp add: c'_def power_mult_distrib DeMoivre)\n    also from n have \"root n (norm c) ^ n = norm c\" by simp\n    also from c have \"\\<dots> * cis (Arg c) = c\" by (simp add: cis_Arg Complex.sgn_eq)\n    finally show \"(c' * z) ^ n = c\" .\n  next\n    fix z assume z: \"c = z ^ n\"\n    define z' where \"z' = z / c'\"\n    from c and n have \"c' \\<noteq> 0\" by (auto simp: c'_def)\n    with n c have \"z = c' * z'\" and \"z' ^ n = 1\"\n      by (auto simp: z'_def power_divide z)\n    thus \"z \\<in> (\\<lambda>z. c' * z) ` {z. z ^ n = 1}\" by blast\n  qed (insert c n, auto simp: c'_def)\nqed\n\nlemma finite_nth_roots [intro]:\n  assumes \"n > 0\"\n  shows   \"finite {z::complex. z ^ n = c}\"\nproof (cases \"c = 0\")\n  case True\n  with assms have \"{z::complex. z ^ n = c} = {0}\" by auto\n  thus ?thesis by simp\nnext\n  case False\n  from assms have \"finite {z::complex. z ^ n = 1}\" by (intro finite_roots_unity) simp_all\n  also have \"?this \\<longleftrightarrow> ?thesis\"\n    by (rule bij_betw_finite, rule bij_betw_nth_root_unity) fact+\n  finally show ?thesis .\nqed\n\nlemma card_nth_roots:\n  assumes \"c \\<noteq> 0\" \"n > 0\"\n  shows   \"card {z::complex. z ^ n = c} = n\"\nproof -\n  have \"card {z. z ^ n = c} = card {z::complex. z ^ n = 1}\"\n    by (rule sym, rule bij_betw_same_card, rule bij_betw_nth_root_unity) fact+\n  also have \"\\<dots> = n\" by (rule card_roots_unity_eq) fact+\n  finally show ?thesis .\nqed\n\nlemma sum_roots_unity:\n  assumes \"n > 1\"\n  shows   \"\\<Sum>{z::complex. z ^ n = 1} = 0\"\nproof -\n  define \\<omega> where \"\\<omega> = cis (2 * pi / real n)\"\n  have [simp]: \"\\<omega> \\<noteq> 1\"\n  proof\n    assume \"\\<omega> = 1\"\n    with assms obtain k :: int where \"2 * pi / real n = 2 * pi * of_int k\"\n      by (auto simp: \\<omega>_def complex_eq_iff cos_one_2pi_int)\n    with assms have \"real n * of_int k = 1\" by (simp add: field_simps)\n    also have \"real n * of_int k = of_int (int n * k)\" by simp\n    also have \"1 = (of_int 1 :: real)\" by simp\n    also note of_int_eq_iff\n    finally show False using assms by (auto simp: zmult_eq_1_iff)\n  qed\n\n  have \"(\\<Sum>z | z ^ n = 1. z :: complex) = (\\<Sum>k<n. cis (2 * pi * real k / real n))\"\n    using assms by (intro sum.reindex_bij_betw [symmetric] bij_betw_roots_unity) auto\n  also have \"\\<dots> = (\\<Sum>k<n. \\<omega> ^ k)\"\n    by (intro sum.cong refl) (auto simp: \\<omega>_def DeMoivre mult_ac)\n  also have \"\\<dots> = (\\<omega> ^ n - 1) / (\\<omega> - 1)\"\n    by (subst geometric_sum) auto\n  also have \"\\<omega> ^ n - 1 = cis (2 * pi) - 1\" using assms by (auto simp: \\<omega>_def DeMoivre)\n  also have \"\\<dots> = 0\" by (simp add: complex_eq_iff)\n  finally show ?thesis by simp\nqed\n\nlemma sum_nth_roots:\n  assumes \"n > 1\"\n  shows   \"\\<Sum>{z::complex. z ^ n = c} = 0\"\nproof (cases \"c = 0\")\n  case True\n  with assms have \"{z::complex. z ^ n = c} = {0}\" by auto\n  also have \"\\<Sum>\\<dots> = 0\" by simp\n  finally show ?thesis .\nnext\n  case False\n  define c' where \"c' = root n (norm c) * cis (Arg c / n)\"\n  from False and assms have \"(\\<Sum>{z. z ^ n = c}) = (\\<Sum>z | z ^ n = 1. c' * z)\"\n    by (subst sum.reindex_bij_betw [OF bij_betw_nth_root_unity, symmetric])\n       (auto simp: sum_distrib_left finite_roots_unity c'_def)\n  also from assms have \"\\<dots> = 0\"\n    by (simp add: sum_distrib_left [symmetric] sum_roots_unity)\n  finally show ?thesis .\nqed\n\nsubsection \\<open>Square root of complex numbers\\<close>\n\nprimcorec csqrt :: \"complex \\<Rightarrow> complex\"\n  where\n    \"Re (csqrt z) = sqrt ((cmod z + Re z) / 2)\"\n  | \"Im (csqrt z) = (if Im z = 0 then 1 else sgn (Im z)) * sqrt ((cmod z - Re z) / 2)\"\n\nlemma csqrt_of_real_nonneg [simp]: \"Im x = 0 \\<Longrightarrow> Re x \\<ge> 0 \\<Longrightarrow> csqrt x = sqrt (Re x)\"\n  by (simp add: complex_eq_iff norm_complex_def)\n\nlemma csqrt_of_real_nonpos [simp]: \"Im x = 0 \\<Longrightarrow> Re x \\<le> 0 \\<Longrightarrow> csqrt x = \\<i> * sqrt \\<bar>Re x\\<bar>\"\n  by (simp add: complex_eq_iff norm_complex_def)\n\nlemma of_real_sqrt: \"x \\<ge> 0 \\<Longrightarrow> of_real (sqrt x) = csqrt (of_real x)\"\n  by (simp add: complex_eq_iff norm_complex_def)\n\nlemma csqrt_0 [simp]: \"csqrt 0 = 0\"\n  by simp\n\nlemma csqrt_1 [simp]: \"csqrt 1 = 1\"\n  by simp\n\nlemma csqrt_ii [simp]: \"csqrt \\<i> = (1 + \\<i>) / sqrt 2\"\n  by (simp add: complex_eq_iff Re_divide Im_divide real_sqrt_divide real_div_sqrt)\n\nlemma power2_csqrt[simp,algebra]: \"(csqrt z)\\<^sup>2 = z\"\nproof (cases \"Im z = 0\")\n  case True\n  then show ?thesis\n    using real_sqrt_pow2[of \"Re z\"] real_sqrt_pow2[of \"- Re z\"]\n    by (cases \"0::real\" \"Re z\" rule: linorder_cases)\n      (simp_all add: complex_eq_iff Re_power2 Im_power2 power2_eq_square cmod_eq_Re)\nnext\n  case False\n  moreover have \"cmod z * cmod z - Re z * Re z = Im z * Im z\"\n    by (simp add: norm_complex_def power2_eq_square)\n  moreover have \"\\<bar>Re z\\<bar> \\<le> cmod z\"\n    by (simp add: norm_complex_def)\n  ultimately show ?thesis\n    by (simp add: Re_power2 Im_power2 complex_eq_iff real_sgn_eq\n        field_simps real_sqrt_mult[symmetric] real_sqrt_divide)\nqed\n\nlemma csqrt_power_even:\n  assumes \"even n\"\n  shows   \"csqrt z ^ n = z ^ (n div 2)\"\n  by (metis assms dvd_mult_div_cancel power2_csqrt power_mult)\n\nlemma norm_csqrt [simp]: \"norm (csqrt z) = sqrt (norm z)\"\n  by (metis abs_of_nonneg norm_ge_zero norm_mult power2_csqrt power2_eq_square real_sqrt_abs)\n\nlemma csqrt_eq_0 [simp]: \"csqrt z = 0 \\<longleftrightarrow> z = 0\"\n  by auto (metis power2_csqrt power_eq_0_iff)\n\nlemma csqrt_eq_1 [simp]: \"csqrt z = 1 \\<longleftrightarrow> z = 1\"\n  by auto (metis power2_csqrt power2_eq_1_iff)\n\nlemma csqrt_principal: \"0 < Re (csqrt z) \\<or> Re (csqrt z) = 0 \\<and> 0 \\<le> Im (csqrt z)\"\n  by (auto simp add: not_less cmod_plus_Re_le_0_iff Im_eq_0)\n\nlemma Re_csqrt: \"0 \\<le> Re (csqrt z)\"\n  by (metis csqrt_principal le_less)\n\nlemma csqrt_square:\n  assumes \"0 < Re b \\<or> (Re b = 0 \\<and> 0 \\<le> Im b)\"\n  shows \"csqrt (b^2) = b\"\nproof -\n  have \"csqrt (b^2) = b \\<or> csqrt (b^2) = - b\"\n    by (simp add: power2_eq_iff[symmetric])\n  moreover have \"csqrt (b^2) \\<noteq> -b \\<or> b = 0\"\n    using csqrt_principal[of \"b ^ 2\"] assms\n    by (intro disjCI notI) (auto simp: complex_eq_iff)\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma csqrt_unique: \"w\\<^sup>2 = z \\<Longrightarrow> 0 < Re w \\<or> Re w = 0 \\<and> 0 \\<le> Im w \\<Longrightarrow> csqrt z = w\"\n  by (auto simp: csqrt_square)\n\nlemma csqrt_minus [simp]:\n  assumes \"Im x < 0 \\<or> (Im x = 0 \\<and> 0 \\<le> Re x)\"\n  shows \"csqrt (- x) = \\<i> * csqrt x\"\nproof -\n  have \"csqrt ((\\<i> * csqrt x)^2) = \\<i> * csqrt x\"\n  proof (rule csqrt_square)\n    have \"Im (csqrt x) \\<le> 0\"\n      using assms by (auto simp add: cmod_eq_Re mult_le_0_iff field_simps complex_Re_le_cmod)\n    then show \"0 < Re (\\<i> * csqrt x) \\<or> Re (\\<i> * csqrt x) = 0 \\<and> 0 \\<le> Im (\\<i> * csqrt x)\"\n      by (auto simp add: Re_csqrt simp del: csqrt.simps)\n  qed\n  also have \"(\\<i> * csqrt x)^2 = - x\"\n    by (simp add: power_mult_distrib)\n  finally show ?thesis .\nqed\n\n\ntext \\<open>Legacy theorem names\\<close>\n\nlemmas cmod_def = norm_complex_def\n\nlemma legacy_Complex_simps:\n  shows Complex_eq_0: \"Complex a b = 0 \\<longleftrightarrow> a = 0 \\<and> b = 0\"\n    and complex_add: \"Complex a b + Complex c d = Complex (a + c) (b + d)\"\n    and complex_minus: \"- (Complex a b) = Complex (- a) (- b)\"\n    and complex_diff: \"Complex a b - Complex c d = Complex (a - c) (b - d)\"\n    and Complex_eq_1: \"Complex a b = 1 \\<longleftrightarrow> a = 1 \\<and> b = 0\"\n    and Complex_eq_neg_1: \"Complex a b = - 1 \\<longleftrightarrow> a = - 1 \\<and> b = 0\"\n    and complex_mult: \"Complex a b * Complex c d = Complex (a * c - b * d) (a * d + b * c)\"\n    and complex_inverse: \"inverse (Complex a b) = Complex (a / (a\\<^sup>2 + b\\<^sup>2)) (- b / (a\\<^sup>2 + b\\<^sup>2))\"\n    and Complex_eq_numeral: \"Complex a b = numeral w \\<longleftrightarrow> a = numeral w \\<and> b = 0\"\n    and Complex_eq_neg_numeral: \"Complex a b = - numeral w \\<longleftrightarrow> a = - numeral w \\<and> b = 0\"\n    and complex_scaleR: \"scaleR r (Complex a b) = Complex (r * a) (r * b)\"\n    and Complex_eq_i: \"Complex x y = \\<i> \\<longleftrightarrow> x = 0 \\<and> y = 1\"\n    and i_mult_Complex: \"\\<i> * Complex a b = Complex (- b) a\"\n    and Complex_mult_i: \"Complex a b * \\<i> = Complex (- b) a\"\n    and i_complex_of_real: \"\\<i> * complex_of_real r = Complex 0 r\"\n    and complex_of_real_i: \"complex_of_real r * \\<i> = Complex 0 r\"\n    and Complex_add_complex_of_real: \"Complex x y + complex_of_real r = Complex (x+r) y\"\n    and complex_of_real_add_Complex: \"complex_of_real r + Complex x y = Complex (r+x) y\"\n    and Complex_mult_complex_of_real: \"Complex x y * complex_of_real r = Complex (x*r) (y*r)\"\n    and complex_of_real_mult_Complex: \"complex_of_real r * Complex x y = Complex (r*x) (r*y)\"\n    and complex_eq_cancel_iff2: \"(Complex x y = complex_of_real xa) = (x = xa \\<and> y = 0)\"\n    and complex_cnj: \"cnj (Complex a b) = Complex a (- b)\"\n    and Complex_sum': \"sum (\\<lambda>x. Complex (f x) 0) s = Complex (sum f s) 0\"\n    and Complex_sum: \"Complex (sum f s) 0 = sum (\\<lambda>x. Complex (f x) 0) s\"\n    and complex_of_real_def: \"complex_of_real r = Complex r 0\"\n    and complex_norm: \"cmod (Complex x y) = sqrt (x\\<^sup>2 + y\\<^sup>2)\"\n  by (simp_all add: norm_complex_def field_simps complex_eq_iff Re_divide Im_divide)\n\nlemma Complex_in_Reals: \"Complex x 0 \\<in> \\<real>\"\n  by (metis Reals_of_real complex_of_real_def)\n\ntext \\<open>Express a complex number as a linear combination of two others, not collinear with the origin\\<close>\nlemma complex_axes:\n  assumes \"Im (y/x) \\<noteq> 0\"\n  obtains a b where \"z = of_real a * x + of_real b * y\"\nproof -\n  define dd where \"dd \\<equiv> Re y * Im x -  Im y * Re x\"\n  define a where \"a = (Im z * Re y - Re z * Im y) / dd\"\n  define b where \"b = (Re z * Im x - Im z * Re x) / dd\"\n  have \"dd \\<noteq> 0\" \n    using assms by (auto simp: dd_def Im_complex_div_eq_0)\n  have \"a * Re x + b * Re y = Re z\"\n    using \\<open>dd \\<noteq> 0\\<close>  \n    apply (simp add: a_def b_def field_simps)\n    by (metis dd_def diff_add_cancel distrib_right mult.assoc mult.commute)\n  moreover have \"a * Im x + b * Im y = Im z\"\n    using \\<open>dd \\<noteq> 0\\<close> \n    apply (simp add: a_def b_def field_simps)\n    by (metis (no_types) dd_def diff_add_cancel distrib_right mult.assoc mult.commute)\n  ultimately have \"z = of_real a * x + of_real b * y\"\n    by (simp add: complex_eqI)\n  then show ?thesis using that by simp\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7592872477874503}}
{"text": "theory Chapter2\nimports Main\nbegin\n\ntext{*\n\\section*{Chapter 2}\n\n\\exercise\nUse the \\textbf{value} command to evaluate the following expressions:\n*}\nvalue \"bool\"\nvalue \"True\"\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\nvalue \"[a,b] @ [c,d]\"\nvalue \"(+) (1::nat) 1\"\nvalue \"(=) 1 (1::nat)\"\n\nfun \"conj\" :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"conj True True = True\" |\n\"conj _ _ = False\"\n\ntext{*\n\\endexercise\n\\exercise\nRecall the definition of our own addition function on @{typ nat}:\n*}\n\nfun \"add\" :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\ntext{*\nProve that @{const add} is associative and commutative.\nYou will need additional lemmas.\n*}\n\n\n\nlemma \"add (add m n) p = add m (add n p)\"\nproof (induction m)\n  case 0\n  have \"add (add 0 n) p = add n p\" by simp\n  also have \"add n p = add 0 (add n p)\" by simp\n  finally show \"add (add 0 n) p = add 0 (add n p)\" by simp\nnext \n  case ind : (Suc m)\n  have \"add (add (Suc m) n) p = add (Suc (add m n)) p\" by simp\n  also have \"add (Suc (add m n)) p = Suc (add (add m n) p)\" by simp\n  also have \"Suc (add (add m n) p) = Suc (add m (add n p))\" by (simp add : ind.IH)  \n  also have \"Suc (add m (add n p)) = add (Suc m) (add n p)\" by simp\n  finally show \"add (add (Suc m) n) p = add (Suc m) (add n p)\" by simp\nqed\nlemma add_comm_aux_1 [simp] : \"add m 0 = m\"\n  apply (induction m)\n  apply (auto)\n  done\n\nlemma add_comm_aux_2 [simp] : \"add m (Suc n) = Suc (add m n)\"\n  apply (induction m)\n   apply (auto)\n  done\n\nlemma add_comm: \"add m n = add n m\"\n  apply (induction m)\n   apply (auto)\ndone\n\nlemma add_comm_isar : \"add m n = add n m\"\nproof (induction m)\n  case 0\n  have \"add 0 n = n\" by simp\n  also have \"add n 0 = n\" \n  proof (induction n)\n    case 0 \n    show \"add 0 0 = 0\" by simp\n  next\n    case ind: (Suc n)\n    have \"add (Suc n) 0 = Suc (add n 0)\" by simp\n    also have \"Suc (add n 0) = Suc n\" by (simp add : ind.IH)\n    finally show \"add (Suc n) 0 = Suc n\" by simp\n  qed\n  then show \"add 0 n = add n 0\" by simp\nnext \n  case ind: (Suc m)\n  have \"add m n = add n m\" by (simp add : ind.IH)\n  also have \"add (Suc m) n = Suc (add m n)\" by simp\n  have \"add n (Suc m) = Suc (add n m)\" by simp\n  finally show \"add (Suc m) n = add n (Suc m)\" by (simp add : ind.IH)\nqed\n\n\ntext{* Define a recursive function *}\nfun \"double\" :: \"nat \\<Rightarrow> nat\" where\n  \"double 0 = 0\"|\n  \"double (Suc n) = Suc (Suc (double n))\"\n\ntext{* and prove that *}\n\nlemma double_add: \"double m = add m m\"\n  apply (induction m)\n   apply (auto)\n  done\n\nlemma double_add_isar : \"double m = add m m\"\nproof (induction m)\n  case 0\n  show \"double 0 = add 0 0\" by simp\nnext\n  case ind : (Suc m)\n  have \"double (Suc m) = Suc (Suc (double m))\" by simp\n  also have \"Suc (Suc (double m)) = Suc (Suc (add m m))\" by (simp add : ind.IH)\n  also have \"Suc (Suc (add m m)) = Suc (add (Suc m) m)\" by simp\n  also have \"Suc (add (Suc m) m) = add (Suc m) (Suc m)\" by simp\n  finally show \"double (Suc m) = add (Suc m) (Suc m)\" by simp\nqed\n\n\n\ntext{*\n\\endexercise\n\n\n\\exercise\nDefine a function that counts the number of occurrences of\nan element in a list:\n*}\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count [] _ = 0\"\n| \"count (x#xs) y = ((if x = y then 1 else 0) + count xs y)\"\n\nvalue \"count [1,2,5,5] (5::nat)\"\n\ntext {*\nTest your definition of @{term count} on some examples.\nProve the following inequality:\n*}\n\ntheorem \"count xs x \\<le> length xs\"\n  apply(induction xs)\n   apply auto\n  done\nfind_theorems count\nthm count.simps\ntheorem \"count xs y \\<le> length xs\"\nproof (induction xs)\n  case Nil\n  have \"count [] y = 0\" by simp\n  also have \"0 \\<le> length []\" by simp\n  finally show \"count [] y \\<le> length []\" by auto\nnext\n  case ind : (Cons x xs)\n  have \"count (x # xs) y \\<le> 1 + count xs y\" by simp\n  also have \"1 + count xs y \\<le> 1 + length xs\" using ind.IH by simp\n  also have \"1 + length xs = length (x # xs)\" by simp\n  finally show \"count (x # xs) y \\<le> length (x # xs)\" by simp\nqed\n\ntext{*\n\\endexercise\n\\exercise\nDefine a function @{text snoc} that appends an element to the end of a list.\nDo not use the existing append operator @{text \"@\"} for lists.\n*}\n\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n  \"snoc [] x = [x]\"\n| \"snoc (y#ys) x = y # (snoc ys x)\"\n\nvalue \"snoc [1,2,3::nat] 4\"\n\ntext {*\nConvince yourself on some test cases that your definition\nof @{term snoc} behaves as expected.\nWith the help of @{text snoc} define a recursive function @{text reverse}\nthat reverses a list. Do not use the predefined function @{const rev}.\n*}\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n  \"reverse [] = []\"\n| \"reverse (x#xs) = snoc (reverse xs) x\"\n\nvalue \"reverse [1,2,3::nat]\"\n\ntext {*\nProve the following theorem. You will need an additional lemma.\n*}\n\nlemma rev_snoc : \"reverse (snoc xs a) = a # (reverse xs)\"  \n  apply (induction xs)\n   apply (auto)\n  done\n\nlemma rev_snoc_isar : \"reverse (snoc xs a) = a # (reverse xs)\"\nproof (induction xs)\n  case Nil\n  have \"reverse (snoc [] a) = [a]\" by simp\n  also have \"a # (reverse []) = [a]\" by simp\n  finally show \"reverse (snoc [] a) = a # (reverse [])\" by simp\nnext\n  case ind : (Cons x xs)\n  show \"reverse (snoc (x # xs) a) = a # reverse (x # xs)\" by (simp add : ind.IH)\nqed\n\ntheorem \"reverse (reverse xs) = xs\"\n  apply (induction xs)\n   apply (simp_all add : rev_snoc )\n  done\n\ntheorem \"reverse (reverse xs) = xs\"\nproof (induction xs)\n  case Nil\n  show ?case by simp\nnext\n  case ind : (Cons a xs)\n  have \"reverse (reverse (a # xs)) = reverse (snoc (reverse xs) a)\" by simp\n  also have \"... = a # (reverse (reverse xs))\" by (simp add : rev_snoc)\n  also have \"... = a # xs\" by (simp add : ind.IH)\n  finally show \"reverse (reverse (a # xs)) = a # xs\" by auto\nqed\n\n  \ntext{*\n\\endexercise\n\n\n\\exercise\nThe aim of this exercise is to prove the summation formula\n\\[ \\sum_{i=0}^{n}i = \\frac{n(n+1)}{2} \\]\nDefine a recursive function @{text \"sum_upto n = 0 + ... + n\"}:\n*}\n\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n  \"sum_upto 0 = 0\"\n| \"sum_upto (Suc n) = Suc n + sum_upto n\"\n\nvalue \"sum_upto 3\"\n\ntext {*\nNow prove the summation formula by induction on @{text \"n\"}.\nFirst, write a clear but informal proof by hand following the examples\nin the main text. Then prove the same property in Isabelle:\n*}\n\nlemma \"sum_upto n = n * (n+1) div 2\"\n  apply (induction n)\n   apply (simp_all)\n  done\nlemma \"sum_upto n = n * (n+1) div 2\"\nproof (induction n)\n  case 0\n  have \"sum_upto (0::nat) = 0\" by simp\n  also have \"(0::nat) * ((0 + 1) div 2) = 0\" by simp\n  finally show \"sum_upto 0 = 0 * (0 + 1) div 2\" by simp\nnext\n  case ind : (Suc n)\n  have \"sum_upto (Suc n) = (Suc n) + sum_upto n\" by simp\n  also have \"Suc n + sum_upto n = Suc n + (n * (n + 1) div 2)\" by (simp add : ind.IH)\n  finally show \"sum_upto (Suc n) = Suc n * (Suc n + 1) div 2\" by simp\nqed\n\n\nfun itrev :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"itrev [] ys = ys\"\n| \"itrev (x # xs) ys = itrev xs (x # ys)\"\n\nvalue \"itrev [1,2,3::nat] []\"\n\nlemma \"itrev xs [] = rev xs\"\n  apply (induction xs)\n  sorry\n\nlemma \"itrev xs [x] = (itrev xs []) @ [x]\"\n  apply (induction xs)\n  apply (auto)\n  sorry\n\nlemma \"itrev xs ys = (rev xs) @ ys\"\nproof (induction xs arbitrary : ys)\n  case Nil\n  show \"itrev [] ys = rev [] @ ys\" by simp\nnext  \n  case ind : (Cons a xs)\n  have \"itrev (a # xs) ys = itrev xs (a # ys)\" by simp\n  also have \"itrev xs (a # ys) = (rev xs) @ (a # ys)\" by (auto simp add : ind.IH)\n  also have \"(rev xs) @ (a # ys) = rev (a # xs) @ ys\" by simp\n  finally show \"itrev (a # xs) ys = rev (a # xs) @ ys\" by simp\nqed\n\n\nlemma \"itrev xs ys = (rev xs) @ ys\"\n  apply (induction xs arbitrary : ys)\n   apply (auto)\n  done\n\n  \n\n\ntext{*\n\\endexercise\n\n\n\\exercise\nStarting from the type @{text \"'a tree\"} defined in the text, define\na function that collects all values in a tree in a list, in any order,\nwithout removing duplicates.\n*}\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"contents Tip = []\"\n| \"contents (Node T1 x T2) = x # (contents T1) @ (contents T2)\"\n\nvalue \"contents t1\"\n\ntext{*\nThen define a function that sums up all values in a tree of natural numbers\n*}\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n  \"sum_tree Tip = 0\"\n| \"sum_tree (Node T1 x T2) = x + (sum_tree T1) + (sum_tree T2)\"\n\nfun sum_list :: \"nat list \\<Rightarrow> nat\" where\n  \"sum_list [] = 0\"\n| \"sum_list (x#xs) = x + sum_list xs\"\n\nvalue \"sum_tree t1\"\nvalue \"sum_list [1,2,3]\"\n\ntext{* and prove *}\n\nlemma sum_list_aux : \"sum_list (l1 @ l2) = sum_list l1 + sum_list l2\"\n  apply (induction l1)\n   apply (auto)\n  done\n\nlemma \"sum_tree t = sum_list (contents t)\"\n  apply (induction t rule : sum_tree.induct)\n   apply (auto simp add : sum_list_aux)\n  done\n\nlemma \"sum_tree t = sum_list (contents t)\"\nproof (induction t)\n  case Tip\n  have \"sum_tree Tip = 0\" by simp\n  also have \"Chapter2.sum_list (contents Tip) = 0\" by simp\n  finally show ?case by simp\nnext\n  case ind : (Node T1 x T2)\n  have \"sum_tree (Node T1 x T2) = x + (sum_tree T1) + (sum_tree T2)\" by simp\n  also have \"... = x + (Chapter2.sum_list (contents T1)) + (Chapter2.sum_list (contents T2))\" \n    by (simp add : ind.IH)\n  also have \"... = Chapter2.sum_list (contents (Node T1 x T2))\" by (simp add : sum_list_aux)\n  finally show \"sum_tree (Node T1 x T2) = Chapter2.sum_list (contents (Node T1 x T2))\" by simp\nqed\n \ntext{*\n\\endexercise\n\n\\exercise\nDefine a new type @{text \"'a tree2\"} of binary trees where values are also\nstored in the leaves of the tree.  Also reformulate the\n@{text mirror} function accordingly. Define two functions *}\n\ndatatype 'a tree2 = Tip2 'a | Node2 \"'a tree2\" 'a \"'a tree2\"\n\nfun \"mirror2\" :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n  \"mirror2 (Tip2 x) = Tip2 x\"\n| \"mirror2 (Node2 (t1 :: 'a tree2) x t2) = Node2 (mirror2 t2) x (mirror2 t1)\"\n\nfun pre_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"pre_order (Tip2 x) = [x]\"\n| \"pre_order (Node2 t1 x t2) = (pre_order t1) @ [x] @ (pre_order t2)\"\n\nfun post_order :: \"'a tree2 \\<Rightarrow> 'a list\" where\n  \"post_order (Tip2 x) = [x]\"\n| \"post_order (Node2 t1 x t2) = (post_order t2) @ [x] @ (post_order t1)\"\n\ntext{*\nthat traverse a tree and collect all stored values in the respective order in\na list. Prove *}\n\nlemma \"pre_order (mirror2 t) = post_order t\"\n  apply (induction t)\n   apply (auto)\n  done\n\nlemma \"pre_order (mirror2 t) = post_order t\"\nproof (induction t)\n  case Tip2\n  show ?case by simp\nnext\n  case ind : (Node2 t1 x t2)\n  show ?case by (auto simp add : ind.IH)\nqed\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a recursive function\n*}\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"intersperse _ [] = []\"\n| \"intersperse a (x # xs) = [x,a] @ (intersperse a xs)\"\n\ntext{*\nsuch that @{text \"intersperse a [x\\<^sub>1, ..., x\\<^sub>n] = [x\\<^sub>1, a, x\\<^sub>2, a, ..., a, x\\<^sub>n]\"}.\nProve\n*}\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply (induction xs)\n   apply (auto)\n  done\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\nproof (induction xs)\n  case Nil\n  show ?case by simp \nnext\n  case ind : (Cons a xs)\n  show ?case by (auto simp add : ind.IH)\nqed\n\ntext{*\n\\endexercise\n\n\n\\exercise\nWrite a tail-recursive variant of the @{text add} function on @{typ nat}:\n*}\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"itadd 0 n = n\"\n| \"itadd (Suc m) n = itadd m (Suc n)\"\n\ntext{*\nTail-recursive means that in the recursive case, @{const itadd} needs to call\nitself directly: \\mbox{@{term\"itadd (Suc m) n\"}} @{text\"= itadd \\<dots>\"}.\nProve\n*}\n\nlemma \"itadd m n = add m n\"\n  by (induction m arbitrary : n) auto\n\nlemma \"itadd m n = add m n\"\nproof (induction m arbitrary : n)\n  case 0\n  show ?case by simp\nnext\n  case ind : (Suc m)\n  have \"itadd (Suc m) n = itadd m (Suc n)\" by simp\n  also have \"... = add m (Suc n)\" by (simp add : ind.IH)\n  also have \"add m (Suc n) = add (Suc m) n\" by simp\n  finally show \"itadd (Suc m) n = add (Suc m) n\" by simp\nqed\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:tree0}\nDefine a datatype @{text tree0} of binary tree skeletons which do not store\nany information, neither in the inner nodes nor in the leaves.\nDefine a function that counts the number of all nodes (inner nodes and leaves)\nin such a tree:\n*}\n\ndatatype tree0 = Tip | Node \"tree0\" \"tree0\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\" where\n  \"nodes Tip = 1\"\n| \"nodes (Node t1 t2) = 1 + nodes t1 + nodes t2\"\n\ntext {*\nConsider the following recursive function:\n*}\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t)\"\n\ntext {*\nExperiment how @{text explode} influences the size of a binary tree\nand find an equation expressing the size of a tree after exploding it\n(\\noquotes{@{term [source] \"nodes (explode n t)\"}}) as a function\nof @{term \"nodes t\"} and @{text n}. Prove your equation.\nYou may use the usual arithmetic operations including the exponentiation\noperator ``@{text\"^\"}''. For example, \\noquotes{@{prop [source] \"2 ^ 2 = 4\"}}.\n\nHint: simplifying with the list of theorems @{thm[source] algebra_simps}\ntakes care of common algebraic properties of the arithmetic operators.\n\\endexercise\n*}\n\nlemma \"nodes (explode n t) = 2^n * (nodes t) + 2^n - 1\"\n  apply (induction n arbitrary : t)\n   apply (auto simp add : algebra_simps)\n  done\n\nlemma \"nodes (explode n t) = 2^n * (nodes t) + 2^n - 1\"\nproof (induction n arbitrary : t)\n  case 0\n  show ?case by simp\nnext\n  case ind : (Suc n)\n  show ?case by (simp add : algebra_simps ind.IH)\nqed\n  \ntext{*\n\n\\exercise\nDefine arithmetic expressions in one variable over integers (type @{typ int})\nas a data type:\n*}\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\ntext{*\nDefine a function @{text eval} that evaluates an expression at some value:\n*}\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"eval Var a = a\"\n| \"eval (Const k) _ = k\"\n| \"eval (Add e1 e2) a = (eval e1) a + (eval e2) a\"\n| \"eval (Mult e1 e2) a = (eval e1) a * (eval e2) a\"\n\nvalue \"eval (Add (Mult (Const 2) Var) (Const 3)) 5 = 2*i+3\"\n\ntext{*\nFor example, @{prop\"eval (Add (Mult (Const 2) Var) (Const 3)) i = 2*i+3\"}.\n\nA polynomial can be represented as a list of coefficients, starting with\nthe constant. For example, @{term \"[4, 2, -1, 3::int]\"} represents the\npolynomial $4 + 2x - x^2 + 3x^3$.\nDefine a function @{text evalp} that evaluates a polynomial at a given value:\n*}\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"evalp [] _ = 0\"\n| \"evalp (c#cs) k = c + k * (evalp cs k)\"\n\nvalue \"evalp [4,2,-1,3] 1\"\n\ntext{*\nDefine a function @{text coeffs} that transforms an expression into a polynomial.\nThis will require auxiliary functions.\n*}\n\nfun add_intlist_intlist :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"add_intlist_intlist [] ys = ys\"\n| \"add_intlist_intlist xs [] = xs\"\n| \"add_intlist_intlist (x#xs) (y#ys) = (x+y)#(add_intlist_intlist xs ys)\"\n\nfun mult_int_intlist :: \"int \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"mult_int_intlist _ [] = []\"\n| \"mult_int_intlist x (y#ys) = (x*y) # (mult_int_intlist x ys)\"\n\nfun mult_intlist_intlist :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"mult_intlist_intlist [] ys = ys\"\n| \"mult_intlist_intlist (x#xs) ys =\n   add_intlist_intlist (mult_int_intlist x ys) (0#(mult_intlist_intlist xs ys))\" \n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n  \"coeffs Var = [0,1]\"\n| \"coeffs (Const c) = [c]\"\n| \"coeffs (Add e1 e2) = add_intlist_intlist (coeffs e1) (coeffs e2)\"\n| \"coeffs (Mult e1 e2) = mult_intlist_intlist (coeffs e1) (coeffs e2)\"\n\ntext{*\nProve that @{text coeffs} preserves the value of the expression:\n*}\n\nlemma \"evalp (add_intlist_intlist xs ys) x = evalp xs x + evalp ys x\"\n  apply (induction xs arbitrary:x)\n   apply (simp_all)\n  apply (induction ys)\n  apply (simp_all)\n\ntheorem evalp_coeffs: \"evalp (coeffs e) x = eval e x\"\n  apply (induction e arbitrary:x)\n  apply (simp_all)\n\ntheorem evalp_coeffs: \"evalp (coeffs e) x = eval e x\"\nproof (induction e arbitrary:x)\n  case Var\n  show ?case by simp\nnext\n  case (Const x)\n  show ?case by simp\nnext\n  case ind_add : (Add e1 e2)\n  have \"evalp (coeffs (Add e1 e2)) x = evalp (add_intlist_intlist (coeffs e1) (coeffs e2)) x\" by simp\n  \n\n\ntext{*\nHint: consider the hint in Exercise~\\ref{exe:tree0}.\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "Qdake", "repo": "M2-LMFI_MPRI_programming_exo", "sha": "22c51738c66a79d5ce91be923edd76e7e0c68ca1", "save_path": "github-repos/isabelle/Qdake-M2-LMFI_MPRI_programming_exo", "path": "github-repos/isabelle/Qdake-M2-LMFI_MPRI_programming_exo/M2-LMFI_MPRI_programming_exo-22c51738c66a79d5ce91be923edd76e7e0c68ca1/isabelle/concrete semantics/templates/Chapter2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515684, "lm_q2_score": 0.90192067652954, "lm_q1q2_score": 0.7592599572890525}}
{"text": "(*  Title       : NthRoot.thy\n    Author      : Jacques D. Fleuriot\n    Copyright   : 1998  University of Cambridge\n    Conversion to Isar and new proofs by Lawrence C Paulson, 2004\n*)\n\nsection {* Nth Roots of Real Numbers *}\n\ntheory NthRoot\nimports Deriv\nbegin\n\nlemma abs_sgn_eq: \"abs (sgn x :: real) = (if x = 0 then 0 else 1)\"\n  by (simp add: sgn_real_def)\n\nlemma inverse_sgn: \"sgn (inverse a) = inverse (sgn a :: real)\"\n  by (simp add: sgn_real_def)\n\nlemma power_eq_iff_eq_base: \n  fixes a b :: \"_ :: linordered_semidom\"\n  shows \"0 < n \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> a ^ n = b ^ n \\<longleftrightarrow> a = b\"\n  using power_eq_imp_eq_base[of a n b] by auto\n\nsubsection {* Existence of Nth Root *}\n\ntext {* Existence follows from the Intermediate Value Theorem *}\n\nlemma realpow_pos_nth:\n  assumes n: \"0 < n\"\n  assumes a: \"0 < a\"\n  shows \"\\<exists>r>0. r ^ n = (a::real)\"\nproof -\n  have \"\\<exists>r\\<ge>0. r \\<le> (max 1 a) \\<and> r ^ n = a\"\n  proof (rule IVT)\n    show \"0 ^ n \\<le> a\" using n a by (simp add: power_0_left)\n    show \"0 \\<le> max 1 a\" by simp\n    from n have n1: \"1 \\<le> n\" by simp\n    have \"a \\<le> max 1 a ^ 1\" by simp\n    also have \"max 1 a ^ 1 \\<le> max 1 a ^ n\"\n      using n1 by (rule power_increasing, simp)\n    finally show \"a \\<le> max 1 a ^ n\" .\n    show \"\\<forall>r. 0 \\<le> r \\<and> r \\<le> max 1 a \\<longrightarrow> isCont (\\<lambda>x. x ^ n) r\"\n      by simp\n  qed\n  then obtain r where r: \"0 \\<le> r \\<and> r ^ n = a\" by fast\n  with n a have \"r \\<noteq> 0\" by (auto simp add: power_0_left)\n  with r have \"0 < r \\<and> r ^ n = a\" by simp\n  thus ?thesis ..\nqed\n\n(* Used by Integration/RealRandVar.thy in AFP *)\nlemma realpow_pos_nth2: \"(0::real) < a \\<Longrightarrow> \\<exists>r>0. r ^ Suc n = a\"\nby (blast intro: realpow_pos_nth)\n\ntext {* Uniqueness of nth positive root *}\n\nlemma realpow_pos_nth_unique: \"\\<lbrakk>0 < n; 0 < a\\<rbrakk> \\<Longrightarrow> \\<exists>!r. 0 < r \\<and> r ^ n = (a::real)\"\n  by (auto intro!: realpow_pos_nth simp: power_eq_iff_eq_base)\n\nsubsection {* Nth Root *}\n\ntext {* We define roots of negative reals such that\n  @{term \"root n (- x) = - root n x\"}. This allows\n  us to omit side conditions from many theorems. *}\n\nlemma inj_sgn_power: assumes \"0 < n\" shows \"inj (\\<lambda>y. sgn y * \\<bar>y\\<bar>^n :: real)\" (is \"inj ?f\")\nproof (rule injI)\n  have x: \"\\<And>a b :: real. (0 < a \\<and> b < 0) \\<or> (a < 0 \\<and> 0 < b) \\<Longrightarrow> a \\<noteq> b\" by auto\n  fix x y assume \"?f x = ?f y\" with power_eq_iff_eq_base[of n \"\\<bar>x\\<bar>\" \"\\<bar>y\\<bar>\"] `0<n` show \"x = y\"\n    by (cases rule: linorder_cases[of 0 x, case_product linorder_cases[of 0 y]])\n       (simp_all add: x)\nqed\n\nlemma sgn_power_injE: \"sgn a * \\<bar>a\\<bar> ^ n = x \\<Longrightarrow> x = sgn b * \\<bar>b\\<bar> ^ n \\<Longrightarrow> 0 < n \\<Longrightarrow> a = (b::real)\"\n  using inj_sgn_power[THEN injD, of n a b] by simp\n\ndefinition root :: \"nat \\<Rightarrow> real \\<Rightarrow> real\" where\n  \"root n x = (if n = 0 then 0 else the_inv (\\<lambda>y. sgn y * \\<bar>y\\<bar>^n) x)\"\n\nlemma root_0 [simp]: \"root 0 x = 0\"\n  by (simp add: root_def)\n\nlemma root_sgn_power: \"0 < n \\<Longrightarrow> root n (sgn y * \\<bar>y\\<bar>^n) = y\"\n  using the_inv_f_f[OF inj_sgn_power] by (simp add: root_def)\n\nlemma sgn_power_root:\n  assumes \"0 < n\" shows \"sgn (root n x) * \\<bar>(root n x)\\<bar>^n = x\" (is \"?f (root n x) = x\")\nproof cases\n  assume \"x \\<noteq> 0\"\n  with realpow_pos_nth[OF `0 < n`, of \"\\<bar>x\\<bar>\"] obtain r where \"0 < r\" \"r ^ n = \\<bar>x\\<bar>\" by auto\n  with `x \\<noteq> 0` have S: \"x \\<in> range ?f\"\n    by (intro image_eqI[of _ _ \"sgn x * r\"])\n       (auto simp: abs_mult sgn_mult power_mult_distrib abs_sgn_eq mult_sgn_abs)\n  from `0 < n` f_the_inv_into_f[OF inj_sgn_power[OF `0 < n`] this]  show ?thesis\n    by (simp add: root_def)\nqed (insert `0 < n` root_sgn_power[of n 0], simp)\n\nlemma split_root: \"P (root n x) \\<longleftrightarrow> (n = 0 \\<longrightarrow> P 0) \\<and> (0 < n \\<longrightarrow> (\\<forall>y. sgn y * \\<bar>y\\<bar>^n = x \\<longrightarrow> P y))\"\n  apply (cases \"n = 0\")\n  apply simp_all\n  apply (metis root_sgn_power sgn_power_root)\n  done\n\nlemma real_root_zero [simp]: \"root n 0 = 0\"\n  by (simp split: split_root add: sgn_zero_iff)\n\nlemma real_root_minus: \"root n (- x) = - root n x\"\n  by (clarsimp split: split_root elim!: sgn_power_injE simp: sgn_minus)\n\nlemma real_root_less_mono: \"\\<lbrakk>0 < n; x < y\\<rbrakk> \\<Longrightarrow> root n x < root n y\"\nproof (clarsimp split: split_root)\n  have x: \"\\<And>a b :: real. (0 < b \\<and> a < 0) \\<Longrightarrow> \\<not> a > b\" by auto\n  fix a b :: real assume \"0 < n\" \"sgn a * \\<bar>a\\<bar> ^ n < sgn b * \\<bar>b\\<bar> ^ n\" then show \"a < b\"\n    using power_less_imp_less_base[of a n b]  power_less_imp_less_base[of \"-b\" n \"-a\"]\n    by (simp add: sgn_real_def power_less_zero_eq x[of \"a ^ n\" \"- ((- b) ^ n)\"] split: split_if_asm)\nqed\n\nlemma real_root_gt_zero: \"\\<lbrakk>0 < n; 0 < x\\<rbrakk> \\<Longrightarrow> 0 < root n x\"\n  using real_root_less_mono[of n 0 x] by simp\n\nlemma real_root_ge_zero: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> root n x\"\n  using real_root_gt_zero[of n x] by (cases \"n = 0\") (auto simp add: le_less)\n\nlemma real_root_pow_pos: (* TODO: rename *)\n  \"\\<lbrakk>0 < n; 0 < x\\<rbrakk> \\<Longrightarrow> root n x ^ n = x\"\n  using sgn_power_root[of n x] real_root_gt_zero[of n x] by simp\n\nlemma real_root_pow_pos2 [simp]: (* TODO: rename *)\n  \"\\<lbrakk>0 < n; 0 \\<le> x\\<rbrakk> \\<Longrightarrow> root n x ^ n = x\"\nby (auto simp add: order_le_less real_root_pow_pos)\n\nlemma sgn_root: \"0 < n \\<Longrightarrow> sgn (root n x) = sgn x\"\n  by (auto split: split_root simp: sgn_real_def power_less_zero_eq)\n\nlemma odd_real_root_pow: \"odd n \\<Longrightarrow> root n x ^ n = x\"\n  using sgn_power_root[of n x] by (simp add: odd_pos sgn_real_def split: split_if_asm)\n\nlemma real_root_power_cancel: \"\\<lbrakk>0 < n; 0 \\<le> x\\<rbrakk> \\<Longrightarrow> root n (x ^ n) = x\"\n  using root_sgn_power[of n x] by (auto simp add: le_less power_0_left)\n\nlemma odd_real_root_power_cancel: \"odd n \\<Longrightarrow> root n (x ^ n) = x\"\n  using root_sgn_power[of n x] by (simp add: odd_pos sgn_real_def power_0_left split: split_if_asm)\n\nlemma real_root_pos_unique: \"\\<lbrakk>0 < n; 0 \\<le> y; y ^ n = x\\<rbrakk> \\<Longrightarrow> root n x = y\"\n  using root_sgn_power[of n y] by (auto simp add: le_less power_0_left)\n\nlemma odd_real_root_unique:\n  \"\\<lbrakk>odd n; y ^ n = x\\<rbrakk> \\<Longrightarrow> root n x = y\"\nby (erule subst, rule odd_real_root_power_cancel)\n\nlemma real_root_one [simp]: \"0 < n \\<Longrightarrow> root n 1 = 1\"\nby (simp add: real_root_pos_unique)\n\ntext {* Root function is strictly monotonic, hence injective *}\n\nlemma real_root_le_mono: \"\\<lbrakk>0 < n; x \\<le> y\\<rbrakk> \\<Longrightarrow> root n x \\<le> root n y\"\n  by (auto simp add: order_le_less real_root_less_mono)\n\nlemma real_root_less_iff [simp]:\n  \"0 < n \\<Longrightarrow> (root n x < root n y) = (x < y)\"\napply (cases \"x < y\")\napply (simp add: real_root_less_mono)\napply (simp add: linorder_not_less real_root_le_mono)\ndone\n\nlemma real_root_le_iff [simp]:\n  \"0 < n \\<Longrightarrow> (root n x \\<le> root n y) = (x \\<le> y)\"\napply (cases \"x \\<le> y\")\napply (simp add: real_root_le_mono)\napply (simp add: linorder_not_le real_root_less_mono)\ndone\n\nlemma real_root_eq_iff [simp]:\n  \"0 < n \\<Longrightarrow> (root n x = root n y) = (x = y)\"\nby (simp add: order_eq_iff)\n\nlemmas real_root_gt_0_iff [simp] = real_root_less_iff [where x=0, simplified]\nlemmas real_root_lt_0_iff [simp] = real_root_less_iff [where y=0, simplified]\nlemmas real_root_ge_0_iff [simp] = real_root_le_iff [where x=0, simplified]\nlemmas real_root_le_0_iff [simp] = real_root_le_iff [where y=0, simplified]\nlemmas real_root_eq_0_iff [simp] = real_root_eq_iff [where y=0, simplified]\n\nlemma real_root_gt_1_iff [simp]: \"0 < n \\<Longrightarrow> (1 < root n y) = (1 < y)\"\nby (insert real_root_less_iff [where x=1], simp)\n\nlemma real_root_lt_1_iff [simp]: \"0 < n \\<Longrightarrow> (root n x < 1) = (x < 1)\"\nby (insert real_root_less_iff [where y=1], simp)\n\nlemma real_root_ge_1_iff [simp]: \"0 < n \\<Longrightarrow> (1 \\<le> root n y) = (1 \\<le> y)\"\nby (insert real_root_le_iff [where x=1], simp)\n\nlemma real_root_le_1_iff [simp]: \"0 < n \\<Longrightarrow> (root n x \\<le> 1) = (x \\<le> 1)\"\nby (insert real_root_le_iff [where y=1], simp)\n\nlemma real_root_eq_1_iff [simp]: \"0 < n \\<Longrightarrow> (root n x = 1) = (x = 1)\"\nby (insert real_root_eq_iff [where y=1], simp)\n\ntext {* Roots of multiplication and division *}\n\nlemma real_root_mult: \"root n (x * y) = root n x * root n y\"\n  by (auto split: split_root elim!: sgn_power_injE simp: sgn_mult abs_mult power_mult_distrib)\n\nlemma real_root_inverse: \"root n (inverse x) = inverse (root n x)\"\n  by (auto split: split_root elim!: sgn_power_injE simp: inverse_sgn power_inverse)\n\nlemma real_root_divide: \"root n (x / y) = root n x / root n y\"\n  by (simp add: divide_inverse real_root_mult real_root_inverse)\n\nlemma real_root_abs: \"0 < n \\<Longrightarrow> root n \\<bar>x\\<bar> = \\<bar>root n x\\<bar>\"\n  by (simp add: abs_if real_root_minus)\n\nlemma real_root_power: \"0 < n \\<Longrightarrow> root n (x ^ k) = root n x ^ k\"\n  by (induct k) (simp_all add: real_root_mult)\n\ntext {* Roots of roots *}\n\nlemma real_root_Suc_0 [simp]: \"root (Suc 0) x = x\"\nby (simp add: odd_real_root_unique)\n\nlemma real_root_mult_exp: \"root (m * n) x = root m (root n x)\"\n  by (auto split: split_root elim!: sgn_power_injE\n           simp: sgn_zero_iff sgn_mult power_mult[symmetric] abs_mult power_mult_distrib abs_sgn_eq)\n\nlemma real_root_commute: \"root m (root n x) = root n (root m x)\"\n  by (simp add: real_root_mult_exp [symmetric] mult.commute)\n\ntext {* Monotonicity in first argument *}\n\nlemma real_root_strict_decreasing:\n  \"\\<lbrakk>0 < n; n < N; 1 < x\\<rbrakk> \\<Longrightarrow> root N x < root n x\"\napply (subgoal_tac \"root n (root N x) ^ n < root N (root n x) ^ N\", simp)\napply (simp add: real_root_commute power_strict_increasing\n            del: real_root_pow_pos2)\ndone\n\nlemma real_root_strict_increasing:\n  \"\\<lbrakk>0 < n; n < N; 0 < x; x < 1\\<rbrakk> \\<Longrightarrow> root n x < root N x\"\napply (subgoal_tac \"root N (root n x) ^ N < root n (root N x) ^ n\", simp)\napply (simp add: real_root_commute power_strict_decreasing\n            del: real_root_pow_pos2)\ndone\n\nlemma real_root_decreasing:\n  \"\\<lbrakk>0 < n; n < N; 1 \\<le> x\\<rbrakk> \\<Longrightarrow> root N x \\<le> root n x\"\nby (auto simp add: order_le_less real_root_strict_decreasing)\n\nlemma real_root_increasing:\n  \"\\<lbrakk>0 < n; n < N; 0 \\<le> x; x \\<le> 1\\<rbrakk> \\<Longrightarrow> root n x \\<le> root N x\"\nby (auto simp add: order_le_less real_root_strict_increasing)\n\ntext {* Continuity and derivatives *}\n\nlemma isCont_real_root: \"isCont (root n) x\"\nproof cases\n  assume n: \"0 < n\"\n  let ?f = \"\\<lambda>y::real. sgn y * \\<bar>y\\<bar>^n\"\n  have \"continuous_on ({0..} \\<union> {.. 0}) (\\<lambda>x. if 0 < x then x ^ n else - ((-x) ^ n) :: real)\"\n    using n by (intro continuous_on_If continuous_intros) auto\n  then have \"continuous_on UNIV ?f\"\n    by (rule continuous_on_cong[THEN iffD1, rotated 2]) (auto simp: not_less real_sgn_neg le_less n)\n  then have [simp]: \"\\<And>x. isCont ?f x\"\n    by (simp add: continuous_on_eq_continuous_at)\n\n  have \"isCont (root n) (?f (root n x))\"\n    by (rule isCont_inverse_function [where f=\"?f\" and d=1]) (auto simp: root_sgn_power n)\n  then show ?thesis\n    by (simp add: sgn_power_root n)\nqed (simp add: root_def[abs_def])\n\nlemma tendsto_real_root[tendsto_intros]:\n  \"(f ---> x) F \\<Longrightarrow> ((\\<lambda>x. root n (f x)) ---> root n x) F\"\n  using isCont_tendsto_compose[OF isCont_real_root, of f x F] .\n\nlemma continuous_real_root[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. root n (f x))\"\n  unfolding continuous_def by (rule tendsto_real_root)\n  \nlemma continuous_on_real_root[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. root n (f x))\"\n  unfolding continuous_on_def by (auto intro: tendsto_real_root)\n\nlemma DERIV_real_root:\n  assumes n: \"0 < n\"\n  assumes x: \"0 < x\"\n  shows \"DERIV (root n) x :> inverse (real n * root n x ^ (n - Suc 0))\"\nproof (rule DERIV_inverse_function)\n  show \"0 < x\" using x .\n  show \"x < x + 1\" by simp\n  show \"\\<forall>y. 0 < y \\<and> y < x + 1 \\<longrightarrow> root n y ^ n = y\"\n    using n by simp\n  show \"DERIV (\\<lambda>x. x ^ n) (root n x) :> real n * root n x ^ (n - Suc 0)\"\n    by (rule DERIV_pow)\n  show \"real n * root n x ^ (n - Suc 0) \\<noteq> 0\"\n    using n x by simp\nqed (rule isCont_real_root)\n\nlemma DERIV_odd_real_root:\n  assumes n: \"odd n\"\n  assumes x: \"x \\<noteq> 0\"\n  shows \"DERIV (root n) x :> inverse (real n * root n x ^ (n - Suc 0))\"\nproof (rule DERIV_inverse_function)\n  show \"x - 1 < x\" by simp\n  show \"x < x + 1\" by simp\n  show \"\\<forall>y. x - 1 < y \\<and> y < x + 1 \\<longrightarrow> root n y ^ n = y\"\n    using n by (simp add: odd_real_root_pow)\n  show \"DERIV (\\<lambda>x. x ^ n) (root n x) :> real n * root n x ^ (n - Suc 0)\"\n    by (rule DERIV_pow)\n  show \"real n * root n x ^ (n - Suc 0) \\<noteq> 0\"\n    using odd_pos [OF n] x by simp\nqed (rule isCont_real_root)\n\nlemma DERIV_even_real_root:\n  assumes n: \"0 < n\" and \"even n\"\n  assumes x: \"x < 0\"\n  shows \"DERIV (root n) x :> inverse (- real n * root n x ^ (n - Suc 0))\"\nproof (rule DERIV_inverse_function)\n  show \"x - 1 < x\" by simp\n  show \"x < 0\" using x .\nnext\n  show \"\\<forall>y. x - 1 < y \\<and> y < 0 \\<longrightarrow> - (root n y ^ n) = y\"\n  proof (rule allI, rule impI, erule conjE)\n    fix y assume \"x - 1 < y\" and \"y < 0\"\n    hence \"root n (-y) ^ n = -y\" using `0 < n` by simp\n    with real_root_minus and `even n`\n    show \"- (root n y ^ n) = y\" by simp\n  qed\nnext\n  show \"DERIV (\\<lambda>x. - (x ^ n)) (root n x) :> - real n * root n x ^ (n - Suc 0)\"\n    by  (auto intro!: derivative_eq_intros simp: real_of_nat_def)\n  show \"- real n * root n x ^ (n - Suc 0) \\<noteq> 0\"\n    using n x by simp\nqed (rule isCont_real_root)\n\nlemma DERIV_real_root_generic:\n  assumes \"0 < n\" and \"x \\<noteq> 0\"\n    and \"\\<lbrakk> even n ; 0 < x \\<rbrakk> \\<Longrightarrow> D = inverse (real n * root n x ^ (n - Suc 0))\"\n    and \"\\<lbrakk> even n ; x < 0 \\<rbrakk> \\<Longrightarrow> D = - inverse (real n * root n x ^ (n - Suc 0))\"\n    and \"odd n \\<Longrightarrow> D = inverse (real n * root n x ^ (n - Suc 0))\"\n  shows \"DERIV (root n) x :> D\"\nusing assms by (cases \"even n\", cases \"0 < x\",\n  auto intro: DERIV_real_root[THEN DERIV_cong]\n              DERIV_odd_real_root[THEN DERIV_cong]\n              DERIV_even_real_root[THEN DERIV_cong])\n\nsubsection {* Square Root *}\n\ndefinition sqrt :: \"real \\<Rightarrow> real\" where\n  \"sqrt = root 2\"\n\nlemma pos2: \"0 < (2::nat)\" by simp\n\nlemma real_sqrt_unique: \"\\<lbrakk>y\\<^sup>2 = x; 0 \\<le> y\\<rbrakk> \\<Longrightarrow> sqrt x = y\"\nunfolding sqrt_def by (rule real_root_pos_unique [OF pos2])\n\nlemma real_sqrt_abs [simp]: \"sqrt (x\\<^sup>2) = \\<bar>x\\<bar>\"\napply (rule real_sqrt_unique)\napply (rule power2_abs)\napply (rule abs_ge_zero)\ndone\n\nlemma real_sqrt_pow2 [simp]: \"0 \\<le> x \\<Longrightarrow> (sqrt x)\\<^sup>2 = x\"\nunfolding sqrt_def by (rule real_root_pow_pos2 [OF pos2])\n\nlemma real_sqrt_pow2_iff [simp]: \"((sqrt x)\\<^sup>2 = x) = (0 \\<le> x)\"\napply (rule iffI)\napply (erule subst)\napply (rule zero_le_power2)\napply (erule real_sqrt_pow2)\ndone\n\nlemma real_sqrt_zero [simp]: \"sqrt 0 = 0\"\nunfolding sqrt_def by (rule real_root_zero)\n\nlemma real_sqrt_one [simp]: \"sqrt 1 = 1\"\nunfolding sqrt_def by (rule real_root_one [OF pos2])\n\nlemma real_sqrt_four [simp]: \"sqrt 4 = 2\"\n  using real_sqrt_abs[of 2] by simp\n\nlemma real_sqrt_minus: \"sqrt (- x) = - sqrt x\"\nunfolding sqrt_def by (rule real_root_minus)\n\nlemma real_sqrt_mult: \"sqrt (x * y) = sqrt x * sqrt y\"\nunfolding sqrt_def by (rule real_root_mult)\n\nlemma real_sqrt_mult_self[simp]: \"sqrt a * sqrt a = \\<bar>a\\<bar>\"\n  using real_sqrt_abs[of a] unfolding power2_eq_square real_sqrt_mult .\n\nlemma real_sqrt_inverse: \"sqrt (inverse x) = inverse (sqrt x)\"\nunfolding sqrt_def by (rule real_root_inverse)\n\nlemma real_sqrt_divide: \"sqrt (x / y) = sqrt x / sqrt y\"\nunfolding sqrt_def by (rule real_root_divide)\n\nlemma real_sqrt_power: \"sqrt (x ^ k) = sqrt x ^ k\"\nunfolding sqrt_def by (rule real_root_power [OF pos2])\n\nlemma real_sqrt_gt_zero: \"0 < x \\<Longrightarrow> 0 < sqrt x\"\nunfolding sqrt_def by (rule real_root_gt_zero [OF pos2])\n\nlemma real_sqrt_ge_zero: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> sqrt x\"\nunfolding sqrt_def by (rule real_root_ge_zero)\n\nlemma real_sqrt_less_mono: \"x < y \\<Longrightarrow> sqrt x < sqrt y\"\nunfolding sqrt_def by (rule real_root_less_mono [OF pos2])\n\nlemma real_sqrt_le_mono: \"x \\<le> y \\<Longrightarrow> sqrt x \\<le> sqrt y\"\nunfolding sqrt_def by (rule real_root_le_mono [OF pos2])\n\nlemma real_sqrt_less_iff [simp]: \"(sqrt x < sqrt y) = (x < y)\"\nunfolding sqrt_def by (rule real_root_less_iff [OF pos2])\n\nlemma real_sqrt_le_iff [simp]: \"(sqrt x \\<le> sqrt y) = (x \\<le> y)\"\nunfolding sqrt_def by (rule real_root_le_iff [OF pos2])\n\nlemma real_sqrt_eq_iff [simp]: \"(sqrt x = sqrt y) = (x = y)\"\nunfolding sqrt_def by (rule real_root_eq_iff [OF pos2])\n\nlemma real_le_lsqrt: \"0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x \\<le> y\\<^sup>2 \\<Longrightarrow> sqrt x \\<le> y\"\n  using real_sqrt_le_iff[of x \"y\\<^sup>2\"] by simp\n\nlemma real_le_rsqrt: \"x\\<^sup>2 \\<le> y \\<Longrightarrow> x \\<le> sqrt y\"\n  using real_sqrt_le_mono[of \"x\\<^sup>2\" y] by simp\n\nlemma real_less_rsqrt: \"x\\<^sup>2 < y \\<Longrightarrow> x < sqrt y\"\n  using real_sqrt_less_mono[of \"x\\<^sup>2\" y] by simp\n\nlemma sqrt_even_pow2:\n  assumes n: \"even n\"\n  shows \"sqrt (2 ^ n) = 2 ^ (n div 2)\"\nproof -\n  from n obtain m where m: \"n = 2 * m\" ..\n  from m have \"sqrt (2 ^ n) = sqrt ((2 ^ m)\\<^sup>2)\"\n    by (simp only: power_mult[symmetric] mult.commute)\n  then show ?thesis\n    using m by simp\nqed\n\nlemmas real_sqrt_gt_0_iff [simp] = real_sqrt_less_iff [where x=0, unfolded real_sqrt_zero]\nlemmas real_sqrt_lt_0_iff [simp] = real_sqrt_less_iff [where y=0, unfolded real_sqrt_zero]\nlemmas real_sqrt_ge_0_iff [simp] = real_sqrt_le_iff [where x=0, unfolded real_sqrt_zero]\nlemmas real_sqrt_le_0_iff [simp] = real_sqrt_le_iff [where y=0, unfolded real_sqrt_zero]\nlemmas real_sqrt_eq_0_iff [simp] = real_sqrt_eq_iff [where y=0, unfolded real_sqrt_zero]\n\nlemmas real_sqrt_gt_1_iff [simp] = real_sqrt_less_iff [where x=1, unfolded real_sqrt_one]\nlemmas real_sqrt_lt_1_iff [simp] = real_sqrt_less_iff [where y=1, unfolded real_sqrt_one]\nlemmas real_sqrt_ge_1_iff [simp] = real_sqrt_le_iff [where x=1, unfolded real_sqrt_one]\nlemmas real_sqrt_le_1_iff [simp] = real_sqrt_le_iff [where y=1, unfolded real_sqrt_one]\nlemmas real_sqrt_eq_1_iff [simp] = real_sqrt_eq_iff [where y=1, unfolded real_sqrt_one]\n\nlemma isCont_real_sqrt: \"isCont sqrt x\"\nunfolding sqrt_def by (rule isCont_real_root)\n\nlemma tendsto_real_sqrt[tendsto_intros]:\n  \"(f ---> x) F \\<Longrightarrow> ((\\<lambda>x. sqrt (f x)) ---> sqrt x) F\"\n  unfolding sqrt_def by (rule tendsto_real_root)\n\nlemma continuous_real_sqrt[continuous_intros]:\n  \"continuous F f \\<Longrightarrow> continuous F (\\<lambda>x. sqrt (f x))\"\n  unfolding sqrt_def by (rule continuous_real_root)\n  \nlemma continuous_on_real_sqrt[continuous_intros]:\n  \"continuous_on s f \\<Longrightarrow> continuous_on s (\\<lambda>x. sqrt (f x))\"\n  unfolding sqrt_def by (rule continuous_on_real_root)\n\nlemma DERIV_real_sqrt_generic:\n  assumes \"x \\<noteq> 0\"\n  assumes \"x > 0 \\<Longrightarrow> D = inverse (sqrt x) / 2\"\n  assumes \"x < 0 \\<Longrightarrow> D = - inverse (sqrt x) / 2\"\n  shows \"DERIV sqrt x :> D\"\n  using assms unfolding sqrt_def\n  by (auto intro!: DERIV_real_root_generic)\n\nlemma DERIV_real_sqrt:\n  \"0 < x \\<Longrightarrow> DERIV sqrt x :> inverse (sqrt x) / 2\"\n  using DERIV_real_sqrt_generic by simp\n\ndeclare\n  DERIV_real_sqrt_generic[THEN DERIV_chain2, derivative_intros]\n  DERIV_real_root_generic[THEN DERIV_chain2, derivative_intros]\n\nlemma not_real_square_gt_zero [simp]: \"(~ (0::real) < x*x) = (x = 0)\"\napply auto\napply (cut_tac x = x and y = 0 in linorder_less_linear)\napply (simp add: zero_less_mult_iff)\ndone\n\nlemma real_sqrt_abs2 [simp]: \"sqrt(x*x) = \\<bar>x\\<bar>\"\napply (subst power2_eq_square [symmetric])\napply (rule real_sqrt_abs)\ndone\n\nlemma real_inv_sqrt_pow2: \"0 < x ==> (inverse (sqrt x))\\<^sup>2 = inverse x\"\nby (simp add: power_inverse [symmetric])\n\nlemma real_sqrt_eq_zero_cancel: \"[| 0 \\<le> x; sqrt(x) = 0|] ==> x = 0\"\nby simp\n\nlemma real_sqrt_ge_one: \"1 \\<le> x ==> 1 \\<le> sqrt x\"\nby simp\n\nlemma sqrt_divide_self_eq:\n  assumes nneg: \"0 \\<le> x\"\n  shows \"sqrt x / x = inverse (sqrt x)\"\nproof cases\n  assume \"x=0\" thus ?thesis by simp\nnext\n  assume nz: \"x\\<noteq>0\" \n  hence pos: \"0<x\" using nneg by arith\n  show ?thesis\n  proof (rule right_inverse_eq [THEN iffD1, THEN sym]) \n    show \"sqrt x / x \\<noteq> 0\" by (simp add: divide_inverse nneg nz) \n    show \"inverse (sqrt x) / (sqrt x / x) = 1\"\n      by (simp add: divide_inverse mult.assoc [symmetric] \n                  power2_eq_square [symmetric] real_inv_sqrt_pow2 pos nz) \n  qed\nqed\n\nlemma real_div_sqrt: \"0 \\<le> x \\<Longrightarrow> x / sqrt x = sqrt x\"\n  apply (cases \"x = 0\")\n  apply simp_all\n  using sqrt_divide_self_eq[of x]\n  apply (simp add: inverse_eq_divide field_simps)\n  done\n\nlemma real_divide_square_eq [simp]: \"(((r::real) * a) / (r * r)) = a / r\"\napply (simp add: divide_inverse)\napply (case_tac \"r=0\")\napply (auto simp add: ac_simps)\ndone\n\nlemma lemma_real_divide_sqrt_less: \"0 < u ==> u / sqrt 2 < u\"\nby (simp add: divide_less_eq)\n\nlemma four_x_squared: \n  fixes x::real\n  shows \"4 * x\\<^sup>2 = (2 * x)\\<^sup>2\"\nby (simp add: power2_eq_square)\n\nlemma sqrt_at_top: \"LIM x at_top. sqrt x :: real :> at_top\"\n  by (rule filterlim_at_top_at_top[where Q=\"\\<lambda>x. True\" and P=\"\\<lambda>x. 0 < x\" and g=\"power2\"])\n     (auto intro: eventually_gt_at_top)\n\nsubsection {* Square Root of Sum of Squares *}\n\nlemma sum_squares_bound: \n  fixes x:: \"'a::linordered_field\"\n  shows \"2*x*y \\<le> x^2 + y^2\"\nproof -\n  have \"(x-y)^2 = x*x - 2*x*y + y*y\"\n    by algebra\n  then have \"0 \\<le> x^2 - 2*x*y + y^2\"\n    by (metis sum_power2_ge_zero zero_le_double_add_iff_zero_le_single_add power2_eq_square)\n  then show ?thesis\n    by arith\nqed\n\nlemma arith_geo_mean: \n  fixes u:: \"'a::linordered_field\" assumes \"u\\<^sup>2 = x*y\" \"x\\<ge>0\" \"y\\<ge>0\" shows \"u \\<le> (x + y)/2\"\n    apply (rule power2_le_imp_le)\n    using sum_squares_bound assms\n    apply (auto simp: zero_le_mult_iff)\n    by (auto simp: algebra_simps power2_eq_square)\n\nlemma arith_geo_mean_sqrt: \n  fixes x::real assumes \"x\\<ge>0\" \"y\\<ge>0\" shows \"sqrt(x*y) \\<le> (x + y)/2\"\n  apply (rule arith_geo_mean)\n  using assms\n  apply (auto simp: zero_le_mult_iff)\n  done\n\nlemma real_sqrt_sum_squares_mult_ge_zero [simp]:\n     \"0 \\<le> sqrt ((x\\<^sup>2 + y\\<^sup>2)*(xa\\<^sup>2 + ya\\<^sup>2))\"\n  by (metis real_sqrt_ge_0_iff split_mult_pos_le sum_power2_ge_zero)\n\nlemma real_sqrt_sum_squares_mult_squared_eq [simp]:\n     \"(sqrt ((x\\<^sup>2 + y\\<^sup>2) * (xa\\<^sup>2 + ya\\<^sup>2)))\\<^sup>2 = (x\\<^sup>2 + y\\<^sup>2) * (xa\\<^sup>2 + ya\\<^sup>2)\"\n  by (simp add: zero_le_mult_iff)\n\nlemma real_sqrt_sum_squares_eq_cancel: \"sqrt (x\\<^sup>2 + y\\<^sup>2) = x \\<Longrightarrow> y = 0\"\nby (drule_tac f = \"%x. x\\<^sup>2\" in arg_cong, simp)\n\nlemma real_sqrt_sum_squares_eq_cancel2: \"sqrt (x\\<^sup>2 + y\\<^sup>2) = y \\<Longrightarrow> x = 0\"\nby (drule_tac f = \"%x. x\\<^sup>2\" in arg_cong, simp)\n\nlemma real_sqrt_sum_squares_ge1 [simp]: \"x \\<le> sqrt (x\\<^sup>2 + y\\<^sup>2)\"\nby (rule power2_le_imp_le, simp_all)\n\nlemma real_sqrt_sum_squares_ge2 [simp]: \"y \\<le> sqrt (x\\<^sup>2 + y\\<^sup>2)\"\nby (rule power2_le_imp_le, simp_all)\n\nlemma real_sqrt_ge_abs1 [simp]: \"\\<bar>x\\<bar> \\<le> sqrt (x\\<^sup>2 + y\\<^sup>2)\"\nby (rule power2_le_imp_le, simp_all)\n\nlemma real_sqrt_ge_abs2 [simp]: \"\\<bar>y\\<bar> \\<le> sqrt (x\\<^sup>2 + y\\<^sup>2)\"\nby (rule power2_le_imp_le, simp_all)\n\nlemma le_real_sqrt_sumsq [simp]: \"x \\<le> sqrt (x * x + y * y)\"\nby (simp add: power2_eq_square [symmetric])\n\nlemma real_sqrt_sum_squares_triangle_ineq:\n  \"sqrt ((a + c)\\<^sup>2 + (b + d)\\<^sup>2) \\<le> sqrt (a\\<^sup>2 + b\\<^sup>2) + sqrt (c\\<^sup>2 + d\\<^sup>2)\"\napply (rule power2_le_imp_le, simp)\napply (simp add: power2_sum)\napply (simp only: mult.assoc distrib_left [symmetric])\napply (rule mult_left_mono)\napply (rule power2_le_imp_le)\napply (simp add: power2_sum power_mult_distrib)\napply (simp add: ring_distribs)\napply (subgoal_tac \"0 \\<le> b\\<^sup>2 * c\\<^sup>2 + a\\<^sup>2 * d\\<^sup>2 - 2 * (a * c) * (b * d)\", simp)\napply (rule_tac b=\"(a * d - b * c)\\<^sup>2\" in ord_le_eq_trans)\napply (rule zero_le_power2)\napply (simp add: power2_diff power_mult_distrib)\napply (simp)\napply simp\napply (simp add: add_increasing)\ndone\n\nlemma real_sqrt_sum_squares_less:\n  \"\\<lbrakk>\\<bar>x\\<bar> < u / sqrt 2; \\<bar>y\\<bar> < u / sqrt 2\\<rbrakk> \\<Longrightarrow> sqrt (x\\<^sup>2 + y\\<^sup>2) < u\"\napply (rule power2_less_imp_less, simp)\napply (drule power_strict_mono [OF _ abs_ge_zero pos2])\napply (drule power_strict_mono [OF _ abs_ge_zero pos2])\napply (simp add: power_divide)\napply (drule order_le_less_trans [OF abs_ge_zero])\napply (simp add: zero_less_divide_iff)\ndone\n\ntext{*Needed for the infinitely close relation over the nonstandard\n    complex numbers*}\nlemma lemma_sqrt_hcomplex_capprox:\n     \"[| 0 < u; x < u/2; y < u/2; 0 \\<le> x; 0 \\<le> y |] ==> sqrt (x\\<^sup>2 + y\\<^sup>2) < u\"\napply (rule_tac y = \"u/sqrt 2\" in order_le_less_trans)\napply (erule_tac [2] lemma_real_divide_sqrt_less)\napply (rule power2_le_imp_le)\napply (auto simp add: zero_le_divide_iff power_divide)\napply (rule_tac t = \"u\\<^sup>2\" in real_sum_of_halves [THEN subst])\napply (rule add_mono)\napply (auto simp add: four_x_squared intro: power_mono)\ndone\n\ntext \"Legacy theorem names:\"\nlemmas real_root_pos2 = real_root_power_cancel\nlemmas real_root_pos_pos = real_root_gt_zero [THEN order_less_imp_le]\nlemmas real_root_pos_pos_le = real_root_ge_zero\nlemmas real_sqrt_mult_distrib = real_sqrt_mult\nlemmas real_sqrt_mult_distrib2 = real_sqrt_mult\nlemmas real_sqrt_eq_zero_cancel_iff = real_sqrt_eq_0_iff\n\n(* needed for CauchysMeanTheorem.het_base from AFP *)\nlemma real_root_pos: \"0 < x \\<Longrightarrow> root (Suc n) (x ^ (Suc n)) = x\"\nby (rule real_root_power_cancel [OF zero_less_Suc order_less_imp_le])\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/NthRoot.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.8652240860523328, "lm_q1q2_score": 0.7592140459366085}}
{"text": "section \\<open>Formalization using Axiomatic Type Classes\\<close>\n\ntheory Elliptic_Axclass\nimports \"HOL-Decision_Procs.Reflective_Field\"\nbegin\n\nsubsection \\<open>Affine Coordinates\\<close>\n\ndatatype 'a point = Infinity | Point 'a 'a\n\nclass ell_field = field +\n  assumes two_not_zero: \"2 \\<noteq> 0\"\nbegin\n\ndefinition nonsingular :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  \"nonsingular a b = (4 * a ^ 3 + 27 * b ^ 2 \\<noteq> 0)\"\n\ndefinition on_curve :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a point \\<Rightarrow> bool\" where\n  \"on_curve a b p = (case p of\n       Infinity \\<Rightarrow> True\n     | Point x y \\<Rightarrow> y ^ 2 = x ^ 3 + a * x + b)\"\n\ndefinition add :: \"'a \\<Rightarrow> 'a point \\<Rightarrow> 'a point \\<Rightarrow> 'a point\" where\n  \"add a p\\<^sub>1 p\\<^sub>2 = (case p\\<^sub>1 of\n       Infinity \\<Rightarrow> p\\<^sub>2\n     | Point x\\<^sub>1 y\\<^sub>1 \\<Rightarrow> (case p\\<^sub>2 of\n         Infinity \\<Rightarrow> p\\<^sub>1\n       | Point x\\<^sub>2 y\\<^sub>2 \\<Rightarrow>\n           if x\\<^sub>1 = x\\<^sub>2 then\n             if y\\<^sub>1 = - y\\<^sub>2 then Infinity\n             else\n               let\n                 l = (3 * x\\<^sub>1 ^ 2 + a) / (2 * y\\<^sub>1);\n                 x\\<^sub>3 = l ^ 2 - 2 * x\\<^sub>1\n               in\n                 Point x\\<^sub>3 (- y\\<^sub>1 - l * (x\\<^sub>3 - x\\<^sub>1))\n           else\n             let\n               l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1);\n               x\\<^sub>3 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\n             in\n               Point x\\<^sub>3 (- y\\<^sub>1 - l * (x\\<^sub>3 - x\\<^sub>1))))\"\n\ndefinition opp :: \"'a point \\<Rightarrow> 'a point\" where\n  \"opp p = (case p of\n       Infinity \\<Rightarrow> Infinity\n     | Point x y \\<Rightarrow> Point x (- y))\"\n\nend\n\nlemma on_curve_infinity [simp]: \"on_curve a b Infinity\"\n  by (simp add: on_curve_def)\n\nlemma opp_Infinity [simp]: \"opp Infinity = Infinity\"\n  by (simp add: opp_def)\n\nlemma opp_Point: \"opp (Point x y) = Point x (- y)\"\n  by (simp add: opp_def)\n\nlemma opp_opp: \"opp (opp p) = p\"\n  by (simp add: opp_def split: point.split)\n\nlemma opp_closed:\n  \"on_curve a b p \\<Longrightarrow> on_curve a b (opp p)\"\n  by (auto simp add: on_curve_def opp_def power2_eq_square\n    split: point.split)\n\nlemma curve_elt_opp:\n  assumes \"p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\"\n  and \"p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\"\n  and \"on_curve a b p\\<^sub>1\"\n  and \"on_curve a b p\\<^sub>2\"\n  and \"x\\<^sub>1 = x\\<^sub>2\"\n  shows \"p\\<^sub>1 = p\\<^sub>2 \\<or> p\\<^sub>1 = opp p\\<^sub>2\"\nproof -\n  from \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>1\\<close>\n  have \"y\\<^sub>1 ^ 2 = x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b\"\n    by (simp_all add: on_curve_def)\n  moreover from \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>x\\<^sub>1 = x\\<^sub>2\\<close>\n  have \"x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b = y\\<^sub>2 ^ 2\"\n    by (simp_all add: on_curve_def)\n  ultimately have \"y\\<^sub>1 = y\\<^sub>2 \\<or> y\\<^sub>1 = - y\\<^sub>2\"\n    by (simp add: square_eq_iff power2_eq_square)\n  with \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>x\\<^sub>1 = x\\<^sub>2\\<close> show ?thesis\n    by (auto simp add: opp_def)\nqed\n\n\n\nlemma add_case [consumes 2, case_names InfL InfR Opp Tan Gen]:\n  assumes p: \"on_curve a b p\"\n  and q: \"on_curve a b q\"\n  and R1: \"\\<And>p. P Infinity p p\"\n  and R2: \"\\<And>p. P p Infinity p\"\n  and R3: \"\\<And>p. on_curve a b p \\<Longrightarrow> P p (opp p) Infinity\"\n  and R4: \"\\<And>p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 l.\n    p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1 \\<Longrightarrow> p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2 \\<Longrightarrow>\n    p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1 \\<Longrightarrow> y\\<^sub>1 \\<noteq> 0 \\<Longrightarrow>\n    l = (3 * x\\<^sub>1 ^ 2 + a) / (2 * y\\<^sub>1) \\<Longrightarrow>\n    x\\<^sub>2 = l ^ 2 - 2 * x\\<^sub>1 \\<Longrightarrow>\n    y\\<^sub>2 = - y\\<^sub>1 - l * (x\\<^sub>2 - x\\<^sub>1) \\<Longrightarrow>\n    P p\\<^sub>1 p\\<^sub>1 p\\<^sub>2\"\n  and R5: \"\\<And>p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 l.\n    p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1 \\<Longrightarrow> p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2 \\<Longrightarrow> p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3 \\<Longrightarrow>\n    p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2 \\<Longrightarrow> x\\<^sub>1 \\<noteq> x\\<^sub>2 \\<Longrightarrow>\n    l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1) \\<Longrightarrow>\n    x\\<^sub>3 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2 \\<Longrightarrow>\n    y\\<^sub>3 = - y\\<^sub>1 - l * (x\\<^sub>3 - x\\<^sub>1) \\<Longrightarrow>\n    P p\\<^sub>1 p\\<^sub>2 p\\<^sub>3\"\n  shows \"P p q (add a p q)\"\nproof (cases p)\n  case Infinity\n  then show ?thesis\n    by (simp add: add_def R1)\nnext\n  case (Point x\\<^sub>1 y\\<^sub>1)\n  note Point' = this\n  show ?thesis\n  proof (cases q)\n    case Infinity\n    with Point show ?thesis\n      by (simp add: add_def R2)\n  next\n    case (Point x\\<^sub>2 y\\<^sub>2)\n    show ?thesis\n    proof (cases \"x\\<^sub>1 = x\\<^sub>2\")\n      case True\n      note True' = this\n      show ?thesis\n      proof (cases \"y\\<^sub>1 = - y\\<^sub>2\")\n        case True\n        with p Point Point' True' R3 [of p] show ?thesis\n          by (simp add: add_def opp_def)\n      next\n        case False\n        from True' Point Point' p q have \"(y\\<^sub>1 - y\\<^sub>2) * (y\\<^sub>1 + y\\<^sub>2) = 0\"\n          by (simp add: on_curve_def ring_distribs power2_eq_square)\n        with False have \"y\\<^sub>1 = y\\<^sub>2\"\n          by (simp add: eq_neg_iff_add_eq_0)\n        with False True' Point Point' show ?thesis\n          apply simp\n          apply (rule R4)\n          apply (auto simp add: add_def Let_def)\n          done\n      qed\n    next\n      case False\n      with Point Point' show ?thesis\n        apply -\n        apply (rule R5)\n        apply (auto simp add: add_def Let_def)\n        done\n    qed\n  qed\nqed\n\nlemma eq_opp_is_zero: \"((x::'a::ell_field) = - x) = (x = 0)\"\nproof\n  assume \"x = - x\"\n  have \"2 * x = x + x\" by simp\n  also from \\<open>x = - x\\<close>\n  have \"\\<dots> = - x + x\" by simp\n  also have \"\\<dots> = 0\" by simp\n  finally have \"2 * x = 0\" .\n  with two_not_zero [where 'a='a] show \"x = 0\"\n    by simp\nqed simp\n\nlemma add_casew [consumes 2, case_names InfL InfR Opp Gen]:\n  assumes p: \"on_curve a b p\"\n  and q: \"on_curve a b q\"\n  and R1: \"\\<And>p. P Infinity p p\"\n  and R2: \"\\<And>p. P p Infinity p\"\n  and R3: \"\\<And>p. on_curve a b p \\<Longrightarrow> P p (opp p) Infinity\"\n  and R4: \"\\<And>p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 l.\n    p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1 \\<Longrightarrow> p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2 \\<Longrightarrow> p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3 \\<Longrightarrow>\n    p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2 \\<Longrightarrow> p\\<^sub>1 \\<noteq> opp p\\<^sub>2 \\<Longrightarrow>\n    x\\<^sub>1 = x\\<^sub>2 \\<and> y\\<^sub>1 = y\\<^sub>2 \\<and> l = (3 * x\\<^sub>1 ^ 2 + a) / (2 * y\\<^sub>1) \\<or>\n    x\\<^sub>1 \\<noteq> x\\<^sub>2 \\<and> l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1) \\<Longrightarrow>\n    x\\<^sub>3 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2 \\<Longrightarrow>\n    y\\<^sub>3 = - y\\<^sub>1 - l * (x\\<^sub>3 - x\\<^sub>1) \\<Longrightarrow>\n    P p\\<^sub>1 p\\<^sub>2 p\\<^sub>3\"\n  shows \"P p q (add a p q)\"\n  using p q\n  apply (rule add_case)\n  apply (rule R1)\n  apply (rule R2)\n  apply (rule R3)\n  apply assumption\n  apply (rule R4)\n  apply assumption+\n  apply (simp add: opp_def eq_opp_is_zero)\n  apply simp\n  apply simp\n  apply simp\n  apply (rule R4)\n  apply assumption+\n  apply (simp add: opp_def)\n  apply simp\n  apply assumption+\n  done\n\ndefinition\n  \"is_tangent p q = (p \\<noteq> Infinity \\<and> p = q \\<and> p \\<noteq> opp q)\"\n\ndefinition\n  \"is_generic p q =\n     (p \\<noteq> Infinity \\<and> q \\<noteq> Infinity \\<and>\n      p \\<noteq> q \\<and> p \\<noteq> opp q)\"\n\nlemma diff_neq0:\n  \"(a::'a::ring) \\<noteq> b \\<Longrightarrow> a - b \\<noteq> 0\"\n  \"a \\<noteq> b \\<Longrightarrow> b - a \\<noteq> 0\"\n  by simp_all\n\nlemma minus2_not0: \"(-2::'a::ell_field) \\<noteq> 0\"\n  using two_not_zero [where 'a='a]\n  by simp\n\nlemmas [simp] = minus2_not0 [simplified]\n\ndeclare two_not_zero [simplified, simp add]\n\nlemma spec1_assoc:\n  assumes p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and p\\<^sub>3: \"on_curve a b p\\<^sub>3\"\n  and \"is_generic p\\<^sub>1 p\\<^sub>2\"\n  and \"is_generic p\\<^sub>2 p\\<^sub>3\"\n  and \"is_generic (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  and \"is_generic p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3)\"\n  shows \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3) = add a (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  using p\\<^sub>1 p\\<^sub>2 assms\nproof (induct rule: add_case)\n  case InfL\n  show ?case by (simp add: add_def)\nnext\n  case InfR\n  show ?case by (simp add: add_def)\nnext\n  case Opp\n  then show ?case by (simp add: is_generic_def)\nnext\n  case Tan\n  then show ?case by (simp add: is_generic_def)\nnext\n  case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>4 x\\<^sub>4 y\\<^sub>4 l)\n  with \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>3\\<close>\n  show ?case\n  proof (induct rule: add_case)\n    case InfL\n    then show ?case by (simp add: is_generic_def)\n  next\n    case InfR\n    then show ?case by (simp add: is_generic_def)\n  next\n    case Opp\n    then show ?case by (simp add: is_generic_def)\n  next\n    case Tan\n    then show ?case by (simp add: is_generic_def)\n  next\n    case (Gen p\\<^sub>2 x\\<^sub>2' y\\<^sub>2' p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 p\\<^sub>5 x\\<^sub>5 y\\<^sub>5 l\\<^sub>1)\n    from \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>3\\<close> \\<open>p\\<^sub>5 = add a p\\<^sub>2 p\\<^sub>3\\<close>\n    have \"on_curve a b p\\<^sub>5\" by (simp add: add_closed)\n    with \\<open>on_curve a b p\\<^sub>1\\<close> show ?case using Gen [simplified \\<open>p\\<^sub>2 = Point x\\<^sub>2' y\\<^sub>2'\\<close>]\n    proof (induct rule: add_case)\n      case InfL\n      then show ?case by (simp add: is_generic_def)\n    next\n      case InfR\n      then show ?case by (simp add: is_generic_def)\n    next\n      case (Opp p)\n      from \\<open>is_generic p (opp p)\\<close>\n      show ?case by (simp add: is_generic_def opp_opp)\n    next\n      case Tan\n      then show ?case by (simp add: is_generic_def)\n    next\n      case (Gen p\\<^sub>1 x\\<^sub>1' y\\<^sub>1' p\\<^sub>5' x\\<^sub>5' y\\<^sub>5' p\\<^sub>6 x\\<^sub>6 y\\<^sub>6 l\\<^sub>2)\n      from \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b (Point x\\<^sub>2' y\\<^sub>2')\\<close>\n        \\<open>p\\<^sub>4 = add a p\\<^sub>1 (Point x\\<^sub>2' y\\<^sub>2')\\<close>\n      have \"on_curve a b p\\<^sub>4\" by (simp add: add_closed)\n      then show ?case using \\<open>on_curve a b p\\<^sub>3\\<close> Gen\n      proof (induct rule: add_case)\n        case InfL\n        then show ?case by (simp add: is_generic_def)\n      next\n        case InfR\n        then show ?case by (simp add: is_generic_def)\n      next\n        case (Opp p)\n        from \\<open>is_generic p (opp p)\\<close>\n        show ?case by (simp add: is_generic_def opp_opp)\n      next\n        case Tan\n        then show ?case by (simp add: is_generic_def)\n      next\n        case (Gen p\\<^sub>4' x\\<^sub>4' y\\<^sub>4' p\\<^sub>3' x\\<^sub>3' y\\<^sub>3' p\\<^sub>7 x\\<^sub>7 y\\<^sub>7 l\\<^sub>3)\n        from \\<open>p\\<^sub>4' = Point x\\<^sub>4' y\\<^sub>4'\\<close> \\<open>p\\<^sub>4' = Point x\\<^sub>4 y\\<^sub>4\\<close>\n        have p\\<^sub>4: \"x\\<^sub>4' = x\\<^sub>4\" \"y\\<^sub>4' = y\\<^sub>4\" by simp_all\n        from \\<open>p\\<^sub>3' = Point x\\<^sub>3' y\\<^sub>3'\\<close> \\<open>p\\<^sub>3' = Point x\\<^sub>3 y\\<^sub>3\\<close>\n        have p\\<^sub>3: \"x\\<^sub>3' = x\\<^sub>3\" \"y\\<^sub>3' = y\\<^sub>3\" by simp_all\n        from \\<open>p\\<^sub>1 = Point x\\<^sub>1' y\\<^sub>1'\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n        have p\\<^sub>1: \"x\\<^sub>1' = x\\<^sub>1\" \"y\\<^sub>1' = y\\<^sub>1\" by simp_all\n        from \\<open>p\\<^sub>5' = Point x\\<^sub>5' y\\<^sub>5'\\<close> \\<open>p\\<^sub>5' = Point x\\<^sub>5 y\\<^sub>5\\<close>\n        have p\\<^sub>5: \"x\\<^sub>5' = x\\<^sub>5\" \"y\\<^sub>5' = y\\<^sub>5\" by simp_all\n        from \\<open>Point x\\<^sub>2' y\\<^sub>2' = Point x\\<^sub>2 y\\<^sub>2\\<close>\n        have p\\<^sub>2: \"x\\<^sub>2' = x\\<^sub>2\" \"y\\<^sub>2' = y\\<^sub>2\" by simp_all\n        note ps = p\\<^sub>1 p\\<^sub>2 p\\<^sub>3 p\\<^sub>4 p\\<^sub>5\n        note ps' =\n          \\<open>on_curve a b p\\<^sub>1\\<close> [simplified \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> on_curve_def, simplified]\n          \\<open>on_curve a b p\\<^sub>2\\<close> [simplified \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> on_curve_def, simplified]\n          \\<open>on_curve a b p\\<^sub>3\\<close> [simplified \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close> on_curve_def, simplified]\n        show ?case\n          apply (simp add: \\<open>p\\<^sub>6 = Point x\\<^sub>6 y\\<^sub>6\\<close> \\<open>p\\<^sub>7 = Point x\\<^sub>7 y\\<^sub>7\\<close>)\n          apply (simp only: ps\n            \\<open>x\\<^sub>6 = l\\<^sub>2\\<^sup>2 - x\\<^sub>1' - x\\<^sub>5'\\<close> \\<open>x\\<^sub>7 = l\\<^sub>3\\<^sup>2 - x\\<^sub>4' - x\\<^sub>3'\\<close>\n            \\<open>y\\<^sub>6 = - y\\<^sub>1' - l\\<^sub>2 * (x\\<^sub>6 - x\\<^sub>1')\\<close> \\<open>y\\<^sub>7 = - y\\<^sub>4' - l\\<^sub>3 * (x\\<^sub>7 - x\\<^sub>4')\\<close>\n            \\<open>l\\<^sub>2 = (y\\<^sub>5' - y\\<^sub>1') / (x\\<^sub>5' - x\\<^sub>1')\\<close> \\<open>l\\<^sub>3 = (y\\<^sub>3' - y\\<^sub>4') / (x\\<^sub>3' - x\\<^sub>4')\\<close>\n            \\<open>l\\<^sub>1 = (y\\<^sub>3 - y\\<^sub>2') / (x\\<^sub>3 - x\\<^sub>2')\\<close> \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>\n            \\<open>x\\<^sub>5 = l\\<^sub>1\\<^sup>2 - x\\<^sub>2' - x\\<^sub>3\\<close> \\<open>y\\<^sub>5 = - y\\<^sub>2' - l\\<^sub>1 * (x\\<^sub>5 - x\\<^sub>2')\\<close>\n            \\<open>x\\<^sub>4 = l\\<^sup>2 - x\\<^sub>1 - x\\<^sub>2\\<close> \\<open>y\\<^sub>4 = - y\\<^sub>1 - l * (x\\<^sub>4 - x\\<^sub>1)\\<close>)\n          apply (rule conjI)\n          apply (field ps')\n          apply (rule conjI)\n          apply (simp add: \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>, symmetric])\n          apply (rule conjI)\n          apply (rule notI)\n          apply (ring (prems) ps'(1-2))\n          apply (cut_tac \\<open>x\\<^sub>1' \\<noteq> x\\<^sub>5'\\<close> [simplified \\<open>x\\<^sub>5' = x\\<^sub>5\\<close> \\<open>x\\<^sub>1' = x\\<^sub>1\\<close> \\<open>x\\<^sub>5 = l\\<^sub>1\\<^sup>2 - x\\<^sub>2' - x\\<^sub>3\\<close>\n            \\<open>l\\<^sub>1 = (y\\<^sub>3 - y\\<^sub>2') / (x\\<^sub>3 - x\\<^sub>2')\\<close> \\<open>y\\<^sub>2' = y\\<^sub>2\\<close> \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>])\n          apply (erule notE)\n          apply (rule sym)\n          apply (field ps'(1-2))\n          apply (simp add: \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>, symmetric])\n          apply (rule conjI)\n          apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n          apply (rule notI)\n          apply (ring (prems) ps'(1-2))\n          apply (cut_tac \\<open>x\\<^sub>4' \\<noteq> x\\<^sub>3'\\<close> [simplified \\<open>x\\<^sub>4' = x\\<^sub>4\\<close> \\<open>x\\<^sub>3' = x\\<^sub>3\\<close> \\<open>x\\<^sub>4 = l\\<^sup>2 - x\\<^sub>1 - x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>])\n          apply (erule notE)\n          apply (rule sym)\n          apply (field ps'(1-2))\n          apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n          apply (field ps')\n          apply (rule conjI)\n          apply (rule notI)\n          apply (ring (prems) ps'(1-2))\n          apply (cut_tac \\<open>x\\<^sub>1' \\<noteq> x\\<^sub>5'\\<close> [simplified \\<open>x\\<^sub>5' = x\\<^sub>5\\<close> \\<open>x\\<^sub>1' = x\\<^sub>1\\<close> \\<open>x\\<^sub>5 = l\\<^sub>1\\<^sup>2 - x\\<^sub>2' - x\\<^sub>3\\<close>\n            \\<open>l\\<^sub>1 = (y\\<^sub>3 - y\\<^sub>2') / (x\\<^sub>3 - x\\<^sub>2')\\<close> \\<open>y\\<^sub>2' = y\\<^sub>2\\<close> \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>])\n          apply (erule notE)\n          apply (rule sym)\n          apply (field ps'(1-2))\n          apply (simp add: \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>, symmetric])\n          apply (rule conjI)\n          apply (simp add: \\<open>x\\<^sub>2' \\<noteq> x\\<^sub>3\\<close> [simplified \\<open>x\\<^sub>2' = x\\<^sub>2\\<close>, symmetric])\n          apply (rule conjI)\n          apply (rule notI)\n          apply (ring (prems) ps'(1-2))\n          apply (cut_tac \\<open>x\\<^sub>4' \\<noteq> x\\<^sub>3'\\<close> [simplified \\<open>x\\<^sub>4' = x\\<^sub>4\\<close> \\<open>x\\<^sub>3' = x\\<^sub>3\\<close> \\<open>x\\<^sub>4 = l\\<^sup>2 - x\\<^sub>1 - x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>])\n          apply (erule notE)\n          apply (rule sym)\n          apply (field ps'(1-2))\n          apply (simp_all add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n          done\n      qed\n    qed\n  qed\nqed\n\nlemma spec2_assoc:\n  assumes p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and p\\<^sub>3: \"on_curve a b p\\<^sub>3\"\n  and \"is_generic p\\<^sub>1 p\\<^sub>2\"\n  and \"is_tangent p\\<^sub>2 p\\<^sub>3\"\n  and \"is_generic (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  and \"is_generic p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3)\"\n  shows \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3) = add a (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  using p\\<^sub>1 p\\<^sub>2 assms\nproof (induct rule: add_case)\n  case InfL\n  show ?case by (simp add: add_def)\nnext\n  case InfR\n  show ?case by (simp add: add_def)\nnext\n  case Opp\n  then show ?case by (simp add: is_generic_def)\nnext\n  case Tan\n  then show ?case by (simp add: is_generic_def)\nnext\n  case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>4 x\\<^sub>4 y\\<^sub>4 l)\n  with \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>3\\<close>\n  show ?case\n  proof (induct rule: add_case)\n    case InfL\n    then show ?case by (simp add: is_generic_def)\n  next\n    case InfR\n    then show ?case by (simp add: is_generic_def)\n  next\n    case Opp\n    then show ?case by (simp add: is_generic_def)\n  next\n    case (Tan p\\<^sub>2 x\\<^sub>2' y\\<^sub>2' p\\<^sub>5 x\\<^sub>5 y\\<^sub>5 l\\<^sub>1)\n    from \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>5 = add a p\\<^sub>2 p\\<^sub>2\\<close>\n    have \"on_curve a b p\\<^sub>5\" by (simp add: add_closed)\n    with \\<open>on_curve a b p\\<^sub>1\\<close> show ?case using Tan\n    proof (induct rule: add_case)\n      case InfL\n      then show ?case by (simp add: is_generic_def)\n    next\n      case InfR\n      then show ?case by (simp add: is_generic_def)\n    next\n      case (Opp p)\n      from \\<open>is_generic p (opp p)\\<close> \\<open>on_curve a b p\\<close>\n      show ?case by (simp add: is_generic_def opp_opp)\n    next\n      case Tan\n      then show ?case by (simp add: is_generic_def)\n    next\n      case (Gen p\\<^sub>1 x\\<^sub>1' y\\<^sub>1' p\\<^sub>5' x\\<^sub>5' y\\<^sub>5' p\\<^sub>6 x\\<^sub>6 y\\<^sub>6 l\\<^sub>2)\n      from \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close>\n      have \"on_curve a b p\\<^sub>4\" by (simp add: add_closed)\n      then show ?case using \\<open>on_curve a b p\\<^sub>2\\<close> Gen\n      proof (induct rule: add_case)\n        case InfL\n        then show ?case by (simp add: is_generic_def)\n      next\n        case InfR\n        then show ?case by (simp add: is_generic_def)\n      next\n        case (Opp p)\n        from \\<open>is_generic p (opp p)\\<close>\n        show ?case by (simp add: is_generic_def opp_opp)\n      next\n        case Tan\n        then show ?case by (simp add: is_generic_def)\n      next\n        case (Gen p\\<^sub>4' x\\<^sub>4' y\\<^sub>4' p\\<^sub>3' x\\<^sub>3' y\\<^sub>3' p\\<^sub>7 x\\<^sub>7 y\\<^sub>7 l\\<^sub>3)\n        from\n          \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n          \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close>\n        have\n          y1: \"y\\<^sub>1 ^ 2 = x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b\" and\n          y2: \"y\\<^sub>2 ^ 2 = x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b\"\n          by (simp_all add: on_curve_def)\n        from\n          \\<open>p\\<^sub>5' = Point x\\<^sub>5' y\\<^sub>5'\\<close>\n          \\<open>p\\<^sub>5' = Point x\\<^sub>5 y\\<^sub>5\\<close>\n          \\<open>p\\<^sub>4' = Point x\\<^sub>4' y\\<^sub>4'\\<close>\n          \\<open>p\\<^sub>4' = Point x\\<^sub>4 y\\<^sub>4\\<close>\n          \\<open>p\\<^sub>3' = Point x\\<^sub>2' y\\<^sub>2'\\<close>\n          \\<open>p\\<^sub>3' = Point x\\<^sub>2 y\\<^sub>2\\<close>\n          \\<open>p\\<^sub>3' = Point x\\<^sub>3' y\\<^sub>3'\\<close>\n          \\<open>p\\<^sub>1 = Point x\\<^sub>1' y\\<^sub>1'\\<close>\n          \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n        have ps:\n          \"x\\<^sub>5' = x\\<^sub>5\" \"y\\<^sub>5' = y\\<^sub>5\"\n          \"x\\<^sub>4' = x\\<^sub>4\" \"y\\<^sub>4' = y\\<^sub>4\" \"x\\<^sub>3' = x\\<^sub>2\" \"y\\<^sub>3' = y\\<^sub>2\" \"x\\<^sub>2' = x\\<^sub>2\" \"y\\<^sub>2' = y\\<^sub>2\"\n          \"x\\<^sub>1' = x\\<^sub>1\" \"y\\<^sub>1' = y\\<^sub>1\"\n          by simp_all\n        show ?case\n          apply (simp add: \\<open>p\\<^sub>6 = Point x\\<^sub>6 y\\<^sub>6\\<close> \\<open>p\\<^sub>7 = Point x\\<^sub>7 y\\<^sub>7\\<close>)\n          apply (simp only: ps\n            \\<open>x\\<^sub>7 = l\\<^sub>3 ^ 2 - x\\<^sub>4' - x\\<^sub>3'\\<close>\n            \\<open>y\\<^sub>7 = - y\\<^sub>4' - l\\<^sub>3 * (x\\<^sub>7 - x\\<^sub>4')\\<close>\n            \\<open>l\\<^sub>3 = (y\\<^sub>3' - y\\<^sub>4') / (x\\<^sub>3' - x\\<^sub>4')\\<close>\n            \\<open>x\\<^sub>6 = l\\<^sub>2 ^ 2 - x\\<^sub>1' - x\\<^sub>5'\\<close>\n            \\<open>y\\<^sub>6 = - y\\<^sub>1' - l\\<^sub>2 * (x\\<^sub>6 - x\\<^sub>1')\\<close>\n            \\<open>l\\<^sub>2 = (y\\<^sub>5' - y\\<^sub>1') / (x\\<^sub>5' - x\\<^sub>1')\\<close>\n            \\<open>x\\<^sub>5 = l\\<^sub>1 ^ 2 - 2 * x\\<^sub>2'\\<close>\n            \\<open>y\\<^sub>5 = - y\\<^sub>2' - l\\<^sub>1 * (x\\<^sub>5 - x\\<^sub>2')\\<close>\n            \\<open>l\\<^sub>1 = (3 * x\\<^sub>2' ^ 2 + a) / (2 * y\\<^sub>2')\\<close>\n            \\<open>x\\<^sub>4 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close>\n            \\<open>y\\<^sub>4 = - y\\<^sub>1 - l * (x\\<^sub>4 - x\\<^sub>1)\\<close>\n            \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>)\n          apply (rule conjI)\n          apply (field y1 y2)\n          apply (intro conjI)\n          apply (simp add: \\<open>y\\<^sub>2' \\<noteq> 0\\<close> [simplified \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>])\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\n          apply (rule notE [OF \\<open>x\\<^sub>1' \\<noteq> x\\<^sub>5'\\<close> [simplified\n            \\<open>x\\<^sub>5 = l\\<^sub>1 ^ 2 - 2 * x\\<^sub>2'\\<close>\n            \\<open>l\\<^sub>1 = (3 * x\\<^sub>2' ^ 2 + a) / (2 * y\\<^sub>2')\\<close>\n            \\<open>x\\<^sub>1' = x\\<^sub>1\\<close> \\<open>x\\<^sub>2' = x\\<^sub>2\\<close> \\<open>y\\<^sub>2' = y\\<^sub>2\\<close> \\<open>x\\<^sub>5' = x\\<^sub>5\\<close>]])\n          apply (rule sym)\n          apply (field y1 y2)\n          apply (simp add: \\<open>y\\<^sub>2' \\<noteq> 0\\<close> [simplified \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>])\n          apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\n          apply (rule notE [OF \\<open>x\\<^sub>4' \\<noteq> x\\<^sub>3'\\<close> [simplified\n            \\<open>x\\<^sub>4 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>\n            \\<open>x\\<^sub>4' = x\\<^sub>4\\<close> \\<open>x\\<^sub>3' = x\\<^sub>2\\<close>]])\n          apply (rule sym)\n          apply (field y1 y2)\n          apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n          apply (field y1 y2)\n          apply (intro conjI)\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\n          apply (rule notE [OF \\<open>x\\<^sub>1' \\<noteq> x\\<^sub>5'\\<close> [simplified\n            \\<open>x\\<^sub>5 = l\\<^sub>1 ^ 2 - 2 * x\\<^sub>2'\\<close>\n            \\<open>l\\<^sub>1 = (3 * x\\<^sub>2' ^ 2 + a) / (2 * y\\<^sub>2')\\<close>\n            \\<open>x\\<^sub>1' = x\\<^sub>1\\<close> \\<open>x\\<^sub>2' = x\\<^sub>2\\<close> \\<open>y\\<^sub>2' = y\\<^sub>2\\<close> \\<open>x\\<^sub>5' = x\\<^sub>5\\<close>]])\n          apply (rule sym)\n          apply (field y1 y2)\n          apply (simp add: \\<open>y\\<^sub>2' \\<noteq> 0\\<close> [simplified \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>])\n          apply (simp add: \\<open>y\\<^sub>2' \\<noteq> 0\\<close> [simplified \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>])\n          apply (rule notI)\n          apply (ring (prems) y1 y2)\n          apply (rule notE [OF \\<open>x\\<^sub>4' \\<noteq> x\\<^sub>3'\\<close> [simplified\n            \\<open>x\\<^sub>4 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close>\n            \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>\n            \\<open>x\\<^sub>4' = x\\<^sub>4\\<close> \\<open>x\\<^sub>3' = x\\<^sub>2\\<close>]])\n          apply (rule sym)\n          apply (field y1 y2)\n          apply (simp_all add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n          done\n      qed\n    qed\n  next\n    case (Gen p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 p\\<^sub>5 x\\<^sub>5 y\\<^sub>5 p\\<^sub>6 x\\<^sub>6 y\\<^sub>6 l\\<^sub>1)\n    then show ?case by (simp add: is_tangent_def)\n  qed\nqed\n\nlemma spec3_assoc:\n  assumes p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and p\\<^sub>3: \"on_curve a b p\\<^sub>3\"\n  and \"is_generic p\\<^sub>1 p\\<^sub>2\"\n  and \"is_tangent p\\<^sub>2 p\\<^sub>3\"\n  and \"is_generic (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  and \"is_tangent p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3)\"\n  shows \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3) = add a (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  using p\\<^sub>1 p\\<^sub>2 assms\nproof (induct rule: add_case)\n  case InfL\n  then show ?case by (simp add: is_generic_def)\nnext\n  case InfR\n  then show ?case by (simp add: is_generic_def)\nnext\n  case Opp\n  then show ?case by (simp add: is_generic_def)\nnext\n  case Tan\n  then show ?case by (simp add: is_generic_def)\nnext\n  case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>4 x\\<^sub>4 y\\<^sub>4 l)\n  with \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>3\\<close>\n  show ?case\n  proof (induct rule: add_case)\n    case InfL\n    then show ?case by (simp add: is_generic_def)\n  next\n    case InfR\n    then show ?case by (simp add: is_generic_def)\n  next\n    case Opp\n    then show ?case by (simp add: is_tangent_def opp_opp)\n  next\n    case (Tan p\\<^sub>2 x\\<^sub>2' y\\<^sub>2' p\\<^sub>5 x\\<^sub>5 y\\<^sub>5 l\\<^sub>1)\n    from \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>5 = add a p\\<^sub>2 p\\<^sub>2\\<close>\n    have \"on_curve a b p\\<^sub>5\" by (simp add: add_closed)\n    with \\<open>on_curve a b p\\<^sub>1\\<close> show ?case using Tan\n    proof (induct rule: add_case)\n      case InfL\n      then show ?case by (simp add: is_generic_def)\n    next\n      case InfR\n      then show ?case by (simp add: is_generic_def)\n    next\n      case Opp\n      then show ?case by (simp add: is_tangent_def opp_opp)\n    next\n      case (Tan p\\<^sub>1 x\\<^sub>1' y\\<^sub>1' p\\<^sub>6 x\\<^sub>6 y\\<^sub>6 l\\<^sub>2)\n      from \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close>\n      have \"on_curve a b p\\<^sub>4\" by (simp add: add_closed)\n      then show ?case using \\<open>on_curve a b p\\<^sub>2\\<close> Tan\n      proof (induct rule: add_case)\n        case InfL\n        then show ?case by (simp add: is_generic_def)\n      next\n        case InfR\n        then show ?case by (simp add: is_generic_def)\n      next\n        case (Opp p)\n        from \\<open>is_generic p (opp p)\\<close>\n        show ?case by (simp add: is_generic_def opp_opp)\n      next\n        case Tan\n        then show ?case by (simp add: is_generic_def)\n      next\n        case (Gen p\\<^sub>4' x\\<^sub>4' y\\<^sub>4' p\\<^sub>2' x\\<^sub>2'' y\\<^sub>2'' p\\<^sub>7 x\\<^sub>7 y\\<^sub>7 l\\<^sub>3)\n        from\n          \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n          \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close>\n        have\n          y1: \"y\\<^sub>1 ^ 2 = x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b\" and\n          y2: \"y\\<^sub>2 ^ 2 = x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b\"\n          by (simp_all add: on_curve_def)\n        from\n          \\<open>p\\<^sub>4' = Point x\\<^sub>4' y\\<^sub>4'\\<close>\n          \\<open>p\\<^sub>4' = Point x\\<^sub>4 y\\<^sub>4\\<close>\n          \\<open>p\\<^sub>2' = Point x\\<^sub>2' y\\<^sub>2'\\<close>\n          \\<open>p\\<^sub>2' = Point x\\<^sub>2 y\\<^sub>2\\<close>\n          \\<open>p\\<^sub>2' = Point x\\<^sub>2'' y\\<^sub>2''\\<close>\n          \\<open>p\\<^sub>1 = Point x\\<^sub>1' y\\<^sub>1'\\<close>\n          \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n          \\<open>p\\<^sub>1 = Point x\\<^sub>5 y\\<^sub>5\\<close>\n        have ps:\n          \"x\\<^sub>4' = x\\<^sub>4\" \"y\\<^sub>4' = y\\<^sub>4\" \"x\\<^sub>2' = x\\<^sub>2\" \"y\\<^sub>2' = y\\<^sub>2\" \"x\\<^sub>2'' = x\\<^sub>2\" \"y\\<^sub>2'' = y\\<^sub>2\"\n          \"x\\<^sub>1' = x\\<^sub>5\" \"y\\<^sub>1' = y\\<^sub>5\" \"x\\<^sub>1 = x\\<^sub>5\" \"y\\<^sub>1 = y\\<^sub>5\"\n          by simp_all\n        note qs =\n          \\<open>x\\<^sub>7 = l\\<^sub>3 ^ 2 - x\\<^sub>4' - x\\<^sub>2''\\<close>\n          \\<open>y\\<^sub>7 = - y\\<^sub>4' - l\\<^sub>3 * (x\\<^sub>7 - x\\<^sub>4')\\<close>\n          \\<open>l\\<^sub>3 = (y\\<^sub>2'' - y\\<^sub>4') / (x\\<^sub>2'' - x\\<^sub>4')\\<close>\n          \\<open>x\\<^sub>6 = l\\<^sub>2 ^ 2 - 2 * x\\<^sub>1'\\<close>\n          \\<open>y\\<^sub>6 = - y\\<^sub>1' - l\\<^sub>2 * (x\\<^sub>6 - x\\<^sub>1')\\<close>\n          \\<open>x\\<^sub>5 = l\\<^sub>1 ^ 2 - 2 * x\\<^sub>2'\\<close>\n          \\<open>y\\<^sub>5 = - y\\<^sub>2' - l\\<^sub>1 * (x\\<^sub>5 - x\\<^sub>2')\\<close>\n          \\<open>l\\<^sub>1 = (3 * x\\<^sub>2' ^ 2 + a) / (2 * y\\<^sub>2')\\<close>\n          \\<open>l\\<^sub>2 = (3 * x\\<^sub>1' ^ 2 + a) / (2 * y\\<^sub>1')\\<close>\n          \\<open>x\\<^sub>4 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close>\n          \\<open>y\\<^sub>4 = - y\\<^sub>1 - l * (x\\<^sub>4 - x\\<^sub>1)\\<close>\n          \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>\n        from \\<open>y\\<^sub>2' \\<noteq> 0\\<close> \\<open>y\\<^sub>2' = y\\<^sub>2\\<close>\n        have \"2 * y\\<^sub>2 \\<noteq> 0\" by simp\n        show ?case\n          apply (simp add: \\<open>p\\<^sub>6 = Point x\\<^sub>6 y\\<^sub>6\\<close> \\<open>p\\<^sub>7 = Point x\\<^sub>7 y\\<^sub>7\\<close>)\n          apply (simp only: ps qs)\n          apply (rule conjI)\n          apply (field y2)\n          apply (intro conjI)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>y\\<^sub>1' \\<noteq> 0\\<close>])\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          apply (rule sym)\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>x\\<^sub>4' \\<noteq> x\\<^sub>2''\\<close>])\n          apply (rule sym)\n          apply (simp only: ps qs)\n          apply field\n          apply (intro conjI)\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (erule thin_rl)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          apply (rule sym)\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (field y2)\n          apply (intro conjI)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>y\\<^sub>1' \\<noteq> 0\\<close>])\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>x\\<^sub>4' \\<noteq> x\\<^sub>2''\\<close>])\n          apply (rule sym)\n          apply (simp only: ps qs)\n          apply field\n          apply (erule thin_rl)\n          apply (rule conjI)\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          apply (rule sym)\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          apply (rule notI)\n          apply (ring (prems))\n          apply (rule notE [OF \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>])\n          apply (rule sym)\n          apply (simp only: ps qs)\n          apply field\n          apply (rule \\<open>2 * y\\<^sub>2 \\<noteq> 0\\<close>)\n          done\n      qed\n    next\n      case Gen\n      then show ?case by (simp add: is_tangent_def)\n    qed\n  next\n    case Gen\n    then show ?case by (simp add: is_tangent_def)\n  qed\nqed\n\nlemma add_0_l: \"add a Infinity p = p\"\n  by (simp add: add_def)\n\nlemma add_0_r: \"add a p Infinity = p\"\n  by (simp add: add_def split: point.split)\n\nlemma add_opp: \"on_curve a b p \\<Longrightarrow> add a p (opp p) = Infinity\"\n  by (simp add: add_def opp_def on_curve_def split: point.split_asm)\n\nlemma add_comm:\n  assumes \"on_curve a b p\\<^sub>1\" \"on_curve a b p\\<^sub>2\"\n  shows \"add a p\\<^sub>1 p\\<^sub>2 = add a p\\<^sub>2 p\\<^sub>1\"\nproof (cases p\\<^sub>1)\n  case Infinity\n  then show ?thesis by (simp add: add_0_l add_0_r)\nnext\n  case (Point x\\<^sub>1 y\\<^sub>1)\n  note Point' = this\n  with \\<open>on_curve a b p\\<^sub>1\\<close>\n  have y1: \"y\\<^sub>1 ^ 2 = x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b\"\n    by (simp add: on_curve_def)\n  show ?thesis\n  proof (cases p\\<^sub>2)\n    case Infinity\n    then show ?thesis by (simp add: add_0_l add_0_r)\n  next\n    case (Point x\\<^sub>2 y\\<^sub>2)\n    with \\<open>on_curve a b p\\<^sub>2\\<close>\n    have y2: \"y\\<^sub>2 ^ 2 = x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b\"\n      by (simp add: on_curve_def)\n    show ?thesis\n    proof (cases \"x\\<^sub>1 = x\\<^sub>2\")\n      case True\n      show ?thesis\n      proof (cases \"y\\<^sub>1 = - y\\<^sub>2\")\n        case True\n        with Point Point' \\<open>x\\<^sub>1 = x\\<^sub>2\\<close> show ?thesis\n          by (simp add: add_def)\n      next\n        case False\n        with y1 y2 [symmetric] \\<open>x\\<^sub>1 = x\\<^sub>2\\<close> Point Point'\n        show ?thesis\n          by (simp add: power2_eq_square square_eq_iff)\n      qed\n    next\n      case False\n      with Point Point' show ?thesis\n        apply (simp add: add_def Let_def)\n        apply (rule conjI)\n        apply field\n        apply simp\n        apply field\n        apply simp\n        done\n    qed\n  qed\nqed\n\nlemma uniq_opp:\n  assumes \"add a p\\<^sub>1 p\\<^sub>2 = Infinity\"\n  shows \"p\\<^sub>2 = opp p\\<^sub>1\"\n  using assms\n  by (auto simp add: add_def opp_def Let_def\n    split: point.split_asm if_split_asm)\n\nlemma uniq_zero:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and add: \"add a p\\<^sub>1 p\\<^sub>2 = p\\<^sub>2\"\n  shows \"p\\<^sub>1 = Infinity\"\n  using p\\<^sub>1 p\\<^sub>2 assms\nproof (induct rule: add_case)\n  case InfL\n  show ?case ..\nnext\n  case InfR\n  then show ?case by simp\nnext\n  case Opp\n  then show ?case by (simp add: opp_def split: point.split_asm)\nnext\n  case (Tan p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 l)\n  from \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>p\\<^sub>2 = p\\<^sub>1\\<close>\n  have \"x\\<^sub>2 = x\\<^sub>1\" \"y\\<^sub>2 = y\\<^sub>1\" by simp_all\n  with \\<open>y\\<^sub>2 = - y\\<^sub>1 - l * (x\\<^sub>2 - x\\<^sub>1)\\<close> \\<open>y\\<^sub>1 \\<noteq> 0\\<close>\n  have \"- y\\<^sub>1 = y\\<^sub>1\" by simp\n  with \\<open>y\\<^sub>1 \\<noteq> 0\\<close>\n  show ?case by simp\nnext\n  case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 l)\n  then have y1: \"y\\<^sub>1 ^ 2 = x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b\"\n    and y2: \"y\\<^sub>2 ^ 2 = x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b\"\n    by (simp_all add: on_curve_def)\n  from \\<open>p\\<^sub>3 = p\\<^sub>2\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close>\n  have ps: \"x\\<^sub>3 = x\\<^sub>2\" \"y\\<^sub>3 = y\\<^sub>2\" by simp_all\n  with \\<open>y\\<^sub>3 = - y\\<^sub>1 - l * (x\\<^sub>3 - x\\<^sub>1)\\<close>\n  have \"y\\<^sub>2 = - y\\<^sub>1 - l * (x\\<^sub>2 - x\\<^sub>1)\" by simp\n  also from \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>\n  have \"l * (x\\<^sub>2 - x\\<^sub>1) = y\\<^sub>2 - y\\<^sub>1\"\n    by simp\n  also have \"- y\\<^sub>1 - (y\\<^sub>2 - y\\<^sub>1) = (- y\\<^sub>1 + y\\<^sub>1) + - y\\<^sub>2\"\n    by simp\n  finally have \"y\\<^sub>2 = 0\" by simp\n  with \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n  have x2: \"x\\<^sub>2 ^ 3 = - (a * x\\<^sub>2 + b)\"\n    by (simp add: on_curve_def eq_neg_iff_add_eq_0 add.assoc del: minus_add_distrib)\n  from \\<open>x\\<^sub>3 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close> \\<open>x\\<^sub>3 = x\\<^sub>2\\<close>\n  have \"l ^ 2 - x\\<^sub>1 - x\\<^sub>2 - x\\<^sub>2 = x\\<^sub>2 - x\\<^sub>2\" by simp\n  then have \"l ^ 2 - x\\<^sub>1 - 2 * x\\<^sub>2 = 0\" by simp\n  then have \"x\\<^sub>2 * (l ^ 2 - x\\<^sub>1 - 2 * x\\<^sub>2) = x\\<^sub>2 * 0\" by simp\n  then have \"(x\\<^sub>2 - x\\<^sub>1) * (2 * a * x\\<^sub>2 + 3 * b) = 0\"\n    apply (simp only: \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close> \\<open>y\\<^sub>2 = 0\\<close>)\n    apply (field (prems) y1 x2)\n    apply (ring y1 x2)\n    apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n    done\n  with \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> have \"2 * a * x\\<^sub>2 + 3 * b = 0\" by simp\n  then have \"2 * a * x\\<^sub>2 = - (3 * b)\"\n    by (simp add: eq_neg_iff_add_eq_0)\n  from y2 [symmetric] \\<open>y\\<^sub>2 = 0\\<close>\n  have \"(- (2 * a)) ^ 3 * (x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b) = 0\"\n    by simp\n  then have \"b * (4 * a ^ 3 + 27 * b ^ 2) = 0\"\n    apply (ring (prems) \\<open>2 * a * x\\<^sub>2 = - (3 * b)\\<close>)\n    apply (ring \\<open>2 * a * x\\<^sub>2 = - (3 * b)\\<close>)\n    done\n  with ab have \"b = 0\" by (simp add: nonsingular_def)\n  with \\<open>2 * a * x\\<^sub>2 + 3 * b = 0\\<close> ab\n  have \"x\\<^sub>2 = 0\" by (simp add: nonsingular_def)\n  from \\<open>l ^ 2 - x\\<^sub>1 - 2 * x\\<^sub>2 = 0\\<close>\n  show ?case\n    apply (simp add: \\<open>x\\<^sub>2 = 0\\<close> \\<open>y\\<^sub>2 = 0\\<close> \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>)\n    apply (field (prems) y1 \\<open>b = 0\\<close>)\n    apply (insert ab \\<open>b = 0\\<close> \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> \\<open>x\\<^sub>2 = 0\\<close>)\n    apply (simp add: nonsingular_def)\n    apply simp\n    done\nqed\n\nlemma opp_add:\n  assumes p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  shows \"opp (add a p\\<^sub>1 p\\<^sub>2) = add a (opp p\\<^sub>1) (opp p\\<^sub>2)\"\nproof (cases p\\<^sub>1)\n  case Infinity\n  then show ?thesis by (simp add: add_def opp_def)\nnext\n  case (Point x\\<^sub>1 y\\<^sub>1)\n  show ?thesis\n  proof (cases p\\<^sub>2)\n    case Infinity\n    with \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> show ?thesis\n      by (simp add: add_def opp_def)\n  next\n    case (Point x\\<^sub>2 y\\<^sub>2)\n    with \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> p\\<^sub>1 p\\<^sub>2\n    have \"x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b = y\\<^sub>1 ^ 2\"\n      \"x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b = y\\<^sub>2 ^ 2\"\n      by (simp_all add: on_curve_def)\n    with Point \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> show ?thesis\n      apply (cases \"x\\<^sub>1 = x\\<^sub>2\")\n      apply (cases \"y\\<^sub>1 = - y\\<^sub>2\")\n      apply (simp add: add_def opp_def Let_def)\n      apply (simp add: add_def opp_def Let_def trans [OF minus_equation_iff eq_commute])\n      apply (simp add: add_def opp_def Let_def)\n      apply (rule conjI)\n      apply field\n      apply simp\n      apply field\n      apply simp\n      done\n  qed\nqed\n\nlemma compat_add_opp:\n  assumes p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and \"add a p\\<^sub>1 p\\<^sub>2 = add a p\\<^sub>1 (opp p\\<^sub>2)\"\n  and \"p\\<^sub>1 \\<noteq> opp p\\<^sub>1\"\n  shows \"p\\<^sub>2 = opp p\\<^sub>2\"\n  using p\\<^sub>1 p\\<^sub>2 assms\nproof (induct rule: add_case)\n  case InfL\n  then show ?case by (simp add: add_0_l)\nnext\n  case InfR\n  then show ?case by (simp add: opp_def add_0_r)\nnext\n  case (Opp p)\n  then have \"add a p p = Infinity\" by (simp add: opp_opp)\n  then have \"p = opp p\" by (rule uniq_opp)\n  with \\<open>p \\<noteq> opp p\\<close> show ?case ..\nnext\n  case (Tan p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 l)\n  then have \"add a p\\<^sub>1 p\\<^sub>1 = Infinity\"\n    by (simp add: add_opp)\n  then have \"p\\<^sub>1 = opp p\\<^sub>1\" by (rule uniq_opp)\n  with \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>1\\<close> show ?case ..\nnext\n  case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 l)\n  have \"(2::'a) * 2 \\<noteq> 0\"\n    by (simp only: mult_eq_0_iff) simp\n  then have \"(4::'a) \\<noteq> 0\" by simp\n  from Gen have \"((- y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)) ^ 2 - x\\<^sub>1 - x\\<^sub>2 =\n    ((y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)) ^ 2 - x\\<^sub>1 - x\\<^sub>2\"\n    by (simp add: add_def opp_def Let_def)\n  then show ?case\n    apply (field (prems))\n    apply (insert \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>1\\<close>\n      \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>4 \\<noteq> 0\\<close>)[1]\n    apply (simp add: opp_def eq_neg_iff_add_eq_0)\n    apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n    done\nqed\n\n\n\nlemma add_opp_double_opp:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and \"add a p\\<^sub>1 p\\<^sub>2 = opp p\\<^sub>1\"\n  shows \"p\\<^sub>2 = add a (opp p\\<^sub>1) (opp p\\<^sub>1)\"\nproof (cases \"p\\<^sub>1 = opp p\\<^sub>1\")\n  case True\n  with assms have \"add a p\\<^sub>2 p\\<^sub>1 = p\\<^sub>1\" by (simp add: add_comm)\n  with ab p\\<^sub>2 p\\<^sub>1 have \"p\\<^sub>2 = Infinity\" by (rule uniq_zero)\n  also from \\<open>on_curve a b p\\<^sub>1\\<close> have \"\\<dots> = add a p\\<^sub>1 (opp p\\<^sub>1)\"\n    by (simp add: add_opp)\n  also from True have \"\\<dots> = add a (opp p\\<^sub>1) (opp p\\<^sub>1)\" by simp\n  finally show ?thesis .\nnext\n  case False\n  from p\\<^sub>1 p\\<^sub>2 False assms show ?thesis\n  proof (induct rule: add_case)\n    case InfL\n    then show ?case by simp\n  next\n    case InfR\n    then show ?case by simp\n  next\n    case Opp\n    then show ?case by (simp add: add_0_l)\n  next\n    case (Tan p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 l)\n    from \\<open>p\\<^sub>2 = opp p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>1\\<close>\n    have \"p\\<^sub>1 = opp p\\<^sub>2\" by (simp add: opp_opp)\n    also note \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close>\n    finally show ?case using \\<open>on_curve a b p\\<^sub>1\\<close>\n      by (simp add: opp_add)\n  next\n    case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 l)\n    from \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n    have y\\<^sub>1: \"y\\<^sub>1 ^ 2 = x\\<^sub>1 ^ 3 + a * x\\<^sub>1 + b\"\n      by (simp add: on_curve_def)\n    from \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close>\n    have y\\<^sub>2: \"y\\<^sub>2 ^ 2 = x\\<^sub>2 ^ 3 + a * x\\<^sub>2 + b\"\n      by (simp add: on_curve_def)\n    from \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>1\\<close>\n    have \"y\\<^sub>1 \\<noteq> 0\"\n      by (simp add: opp_Point)\n    from Gen have \"x\\<^sub>1 = ((y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)) ^ 2 - x\\<^sub>1 - x\\<^sub>2\"\n      by (simp add: opp_Point)\n    then have \"2 * y\\<^sub>2 * y\\<^sub>1 = a * x\\<^sub>2 + 3 * x\\<^sub>2 * x\\<^sub>1 ^ 2 + a * x\\<^sub>1 -\n      x\\<^sub>1 ^ 3 + 2 * b\"\n      apply (field (prems) y\\<^sub>1 y\\<^sub>2)\n      apply (field y\\<^sub>1 y\\<^sub>2)\n      apply simp\n      apply (simp add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n      done\n    then have \"(x\\<^sub>2 - (((3 * x\\<^sub>1 ^ 2 + a) / (2 * (- y\\<^sub>1))) ^ 2 -\n      2 * x\\<^sub>1)) * (x\\<^sub>2 - x\\<^sub>1) ^ 2 = 0\"\n      apply (drule_tac f=\"\\<lambda>x. x ^ 2\" in arg_cong)\n      apply (field (prems) y\\<^sub>1 y\\<^sub>2)\n      apply (field y\\<^sub>1 y\\<^sub>2)\n      apply (simp_all add: \\<open>y\\<^sub>1 \\<noteq> 0\\<close>)\n      done\n    with \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close>\n    have \"x\\<^sub>2 = ((3 * x\\<^sub>1 ^ 2 + a) / (2 * (- y\\<^sub>1))) ^ 2 - 2 * x\\<^sub>1\"\n      by simp\n    with \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> _ \\<open>on_curve a b p\\<^sub>2\\<close>\n      add_closed [OF\n        opp_closed [OF \\<open>on_curve a b p\\<^sub>1\\<close>] opp_closed [OF \\<open>on_curve a b p\\<^sub>1\\<close>]]\n    have \"p\\<^sub>2 = add a (opp p\\<^sub>1) (opp p\\<^sub>1) \\<or> p\\<^sub>2 = opp (add a (opp p\\<^sub>1) (opp p\\<^sub>1))\"\n      apply (rule curve_elt_opp)\n      apply (simp add: add_def opp_Point Let_def \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>y\\<^sub>1 \\<noteq> 0\\<close>)\n      done\n    then show ?case\n    proof\n      assume \"p\\<^sub>2 = opp (add a (opp p\\<^sub>1) (opp p\\<^sub>1))\"\n      with \\<open>on_curve a b p\\<^sub>1\\<close>\n      have \"p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\"\n        by (simp add: opp_add [of a b] opp_opp opp_closed)\n      show ?case\n      proof (cases \"add a p\\<^sub>1 p\\<^sub>1 = opp p\\<^sub>1\")\n        case True\n        from \\<open>on_curve a b p\\<^sub>1\\<close>\n        show ?thesis\n          apply (simp add: opp_add [symmetric] \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close> True)\n          apply (simp add: \\<open>p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2\\<close> [simplified \\<open>p\\<^sub>3 = opp p\\<^sub>1\\<close>])\n          apply (simp add: \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close> True add_opp)\n          done\n      next\n        case False\n        from \\<open>on_curve a b p\\<^sub>1\\<close>\n        have \"add a p\\<^sub>1 (opp p\\<^sub>2) = opp (add a (add a p\\<^sub>1 p\\<^sub>1) (opp p\\<^sub>1))\"\n          by (simp add: \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close>\n            opp_add [of a b] add_closed opp_closed opp_opp add_comm [of a b])\n        with ab \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>1\\<close> False\n        have \"add a p\\<^sub>1 (opp p\\<^sub>2) = opp p\\<^sub>1\"\n          by (simp add: compat_add_triple)\n        with \\<open>p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>p\\<^sub>3 = opp p\\<^sub>1\\<close>\n        have \"add a p\\<^sub>1 p\\<^sub>2 = add a p\\<^sub>1 (opp p\\<^sub>2)\" by simp\n        with \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n        have \"p\\<^sub>2 = opp p\\<^sub>2\" using \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>1\\<close>\n          by (rule compat_add_opp)\n        with \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close>\n        show ?thesis by (simp add: opp_add)\n      qed\n    qed\n  qed\nqed\n\nlemma cancel:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and p\\<^sub>3: \"on_curve a b p\\<^sub>3\"\n  and eq: \"add a p\\<^sub>1 p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>3\"\n  shows \"p\\<^sub>2 = p\\<^sub>3\"\n  using p\\<^sub>1 p\\<^sub>2 p\\<^sub>1 p\\<^sub>2 eq\nproof (induct rule: add_casew)\n  case InfL\n  then show ?case by (simp add: add_0_l)\nnext\n  case (InfR p)\n  with p\\<^sub>3 have \"add a p\\<^sub>3 p = p\" by (simp add: add_comm)\n  with ab p\\<^sub>3 \\<open>on_curve a b p\\<close>\n  show ?case by (rule uniq_zero [symmetric])\nnext\n  case (Opp p)\n  from \\<open>Infinity = add a p p\\<^sub>3\\<close> [symmetric]\n  show ?case by (rule uniq_opp [symmetric])\nnext\n  case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>4 x\\<^sub>4 y\\<^sub>4 l)\n  from \\<open>on_curve a b p\\<^sub>1\\<close> p\\<^sub>3 \\<open>on_curve a b p\\<^sub>1\\<close> p\\<^sub>3 \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n    \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>3\\<close> \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>2\\<close>\n  show ?case\n  proof (induct rule: add_casew)\n    case InfL\n    then show ?case by (simp add: add_0_l)\n  next\n    case (InfR p)\n    with \\<open>on_curve a b p\\<^sub>2\\<close>\n    have \"add a p\\<^sub>2 p = p\" by (simp add: add_comm)\n    with ab \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<close>\n    show ?case by (rule uniq_zero)\n  next\n    case (Opp p)\n    then have \"add a p p\\<^sub>2 = Infinity\" by simp\n    then show ?case by (rule uniq_opp)\n  next\n    case (Gen p\\<^sub>1 x\\<^sub>1' y\\<^sub>1' p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 p\\<^sub>5 x\\<^sub>5 y\\<^sub>5 l')\n    from \\<open>p\\<^sub>4 = p\\<^sub>5\\<close> \\<open>p\\<^sub>4 = Point x\\<^sub>4 y\\<^sub>4\\<close> \\<open>p\\<^sub>5 = Point x\\<^sub>5 y\\<^sub>5\\<close>\n      \\<open>p\\<^sub>1 = Point x\\<^sub>1' y\\<^sub>1'\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n      \\<open>y\\<^sub>4 = - y\\<^sub>1 - l * (x\\<^sub>4 - x\\<^sub>1)\\<close> \\<open>y\\<^sub>5 = - y\\<^sub>1' - l' * (x\\<^sub>5 - x\\<^sub>1')\\<close>\n    have \"0 = - y\\<^sub>1 - l * (x\\<^sub>4 - x\\<^sub>1) - (- y\\<^sub>1 - l' * (x\\<^sub>4 - x\\<^sub>1))\"\n      by auto\n    then have \"l' = l \\<or> x\\<^sub>4 = x\\<^sub>1\" by auto\n    then show ?case\n    proof\n      assume \"l' = l\"\n      with \\<open>p\\<^sub>4 = p\\<^sub>5\\<close> \\<open>p\\<^sub>4 = Point x\\<^sub>4 y\\<^sub>4\\<close> \\<open>p\\<^sub>5 = Point x\\<^sub>5 y\\<^sub>5\\<close>\n        \\<open>p\\<^sub>1 = Point x\\<^sub>1' y\\<^sub>1'\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n        \\<open>x\\<^sub>4 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close> \\<open>x\\<^sub>5 = l' ^ 2 - x\\<^sub>1' - x\\<^sub>3\\<close>\n      have \"0 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2 - (l ^ 2 - x\\<^sub>1 - x\\<^sub>3)\"\n        by simp\n      then have \"x\\<^sub>2 = x\\<^sub>3\" by simp\n      with \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close> \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>3\\<close>\n      have \"p\\<^sub>2 = p\\<^sub>3 \\<or> p\\<^sub>2 = opp p\\<^sub>3\" by (rule curve_elt_opp)\n      then show ?case\n      proof\n        assume \"p\\<^sub>2 = opp p\\<^sub>3\"\n        with \\<open>on_curve a b p\\<^sub>3\\<close> have \"opp p\\<^sub>2 = p\\<^sub>3\"\n          by (simp add: opp_opp)\n        with \\<open>p\\<^sub>4 = p\\<^sub>5\\<close> \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>p\\<^sub>5 = add a p\\<^sub>1 p\\<^sub>3\\<close>\n        have \"add a p\\<^sub>1 p\\<^sub>2 = add a p\\<^sub>1 (opp p\\<^sub>2)\" by simp\n        show ?case\n        proof (cases \"p\\<^sub>1 = opp p\\<^sub>1\")\n          case True\n          with \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>2\\<close> \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>3\\<close>\n          have \"p\\<^sub>1 \\<noteq> p\\<^sub>2\" \"p\\<^sub>1 \\<noteq> p\\<^sub>3\" by auto\n          with \\<open>l' = l\\<close> \\<open>x\\<^sub>1 = x\\<^sub>2 \\<and> _\\<or> _\\<close> \\<open>x\\<^sub>1' = x\\<^sub>3 \\<and> _ \\<or> _\\<close>\n            \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1' y\\<^sub>1'\\<close>\n            \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close>\n            \\<open>p\\<^sub>2 = opp p\\<^sub>3\\<close>\n          have eq: \"(y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1) = (y\\<^sub>3 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\" and \"x\\<^sub>1 \\<noteq> x\\<^sub>2\"\n            by (auto simp add: opp_Point)\n          from eq have \"y\\<^sub>2 = y\\<^sub>3\"\n            apply (field (prems))\n            apply (simp_all add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n            done\n          with \\<open>p\\<^sub>2 = opp p\\<^sub>3\\<close> \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>p\\<^sub>3 = Point x\\<^sub>3 y\\<^sub>3\\<close>\n          show ?thesis by (simp add: opp_Point)\n        next\n          case False\n          with \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n            \\<open>add a p\\<^sub>1 p\\<^sub>2 = add a p\\<^sub>1 (opp p\\<^sub>2)\\<close>\n          have \"p\\<^sub>2 = opp p\\<^sub>2\" by (rule compat_add_opp)\n          with \\<open>opp p\\<^sub>2 = p\\<^sub>3\\<close> show ?thesis by simp\n        qed\n      qed\n    next\n      assume \"x\\<^sub>4 = x\\<^sub>1\"\n      with \\<open>p\\<^sub>4 = Point x\\<^sub>4 y\\<^sub>4\\<close> [simplified \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close>]\n        \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n        add_closed [OF \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>]\n        \\<open>on_curve a b p\\<^sub>1\\<close>\n      have \"add a p\\<^sub>1 p\\<^sub>2 = p\\<^sub>1 \\<or> add a p\\<^sub>1 p\\<^sub>2 = opp p\\<^sub>1\" by (rule curve_elt_opp)\n      then show ?case\n      proof\n        assume \"add a p\\<^sub>1 p\\<^sub>2 = p\\<^sub>1\"\n        with \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n        have \"add a p\\<^sub>2 p\\<^sub>1 = p\\<^sub>1\" by (simp add: add_comm)\n        with ab \\<open>on_curve a b p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>1\\<close>\n        have \"p\\<^sub>2 = Infinity\" by (rule uniq_zero)\n        moreover from \\<open>add a p\\<^sub>1 p\\<^sub>2 = p\\<^sub>1\\<close>\n          \\<open>p\\<^sub>4 = p\\<^sub>5\\<close> \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>p\\<^sub>5 = add a p\\<^sub>1 p\\<^sub>3\\<close>\n          \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>3\\<close>\n        have \"add a p\\<^sub>3 p\\<^sub>1 = p\\<^sub>1\" by (simp add: add_comm)\n        with ab \\<open>on_curve a b p\\<^sub>3\\<close> \\<open>on_curve a b p\\<^sub>1\\<close>\n        have \"p\\<^sub>3 = Infinity\" by (rule uniq_zero)\n        ultimately show ?case by simp\n      next\n        assume \"add a p\\<^sub>1 p\\<^sub>2 = opp p\\<^sub>1\"\n        with ab \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n        have \"p\\<^sub>2 = add a (opp p\\<^sub>1) (opp p\\<^sub>1)\" by (rule add_opp_double_opp)\n        moreover from \\<open>add a p\\<^sub>1 p\\<^sub>2 = opp p\\<^sub>1\\<close>\n          \\<open>p\\<^sub>4 = p\\<^sub>5\\<close> \\<open>p\\<^sub>4 = add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>p\\<^sub>5 = add a p\\<^sub>1 p\\<^sub>3\\<close>\n        have \"add a p\\<^sub>1 p\\<^sub>3 = opp p\\<^sub>1\" by simp\n        with ab \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>3\\<close>\n        have \"p\\<^sub>3 = add a (opp p\\<^sub>1) (opp p\\<^sub>1)\" by (rule add_opp_double_opp)\n        ultimately show ?case by simp\n      qed\n    qed\n  qed\nqed\n\nlemma add_minus_id:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  shows \"add a (add a p\\<^sub>1 p\\<^sub>2) (opp p\\<^sub>2) = p\\<^sub>1\"\nproof (cases \"add a p\\<^sub>1 p\\<^sub>2 = opp p\\<^sub>2\")\n  case True\n  then have \"add a (add a p\\<^sub>1 p\\<^sub>2) (opp p\\<^sub>2) = add a (opp p\\<^sub>2) (opp p\\<^sub>2)\"\n    by simp\n  also from p\\<^sub>1 p\\<^sub>2 True have \"add a p\\<^sub>2 p\\<^sub>1 = opp p\\<^sub>2\"\n    by (simp add: add_comm)\n  with ab p\\<^sub>2 p\\<^sub>1 have \"add a (opp p\\<^sub>2) (opp p\\<^sub>2) = p\\<^sub>1\"\n    by (rule add_opp_double_opp [symmetric])\n  finally show ?thesis .\nnext\n  case False\n  from p\\<^sub>1 p\\<^sub>2 p\\<^sub>1 p\\<^sub>2 False show ?thesis\n  proof (induct rule: add_case)\n    case InfL\n    then show ?case by (simp add: add_opp)\n  next\n    case InfR\n    show ?case by (simp add: add_0_r)\n  next\n    case Opp\n    then show ?case by (simp add: opp_opp add_0_l)\n  next\n    case (Tan p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 l)\n    note ab \\<open>on_curve a b p\\<^sub>1\\<close>\n    moreover from \\<open>y\\<^sub>1 \\<noteq> 0\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n    have \"p\\<^sub>1 \\<noteq> opp p\\<^sub>1\" by (simp add: opp_Point)\n    moreover from \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close> \\<open>p\\<^sub>2 \\<noteq> opp p\\<^sub>1\\<close>\n    have \"add a p\\<^sub>1 p\\<^sub>1 \\<noteq> opp p\\<^sub>1\" by simp\n    ultimately have \"add a (add a p\\<^sub>1 p\\<^sub>1) (opp p\\<^sub>1) = p\\<^sub>1\"\n      by (rule compat_add_triple)\n    with \\<open>p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>1\\<close> show ?case by simp\n  next\n    case (Gen p\\<^sub>1 x\\<^sub>1 y\\<^sub>1 p\\<^sub>2 x\\<^sub>2 y\\<^sub>2 p\\<^sub>3 x\\<^sub>3 y\\<^sub>3 l)\n    from \\<open>p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>\n    have \"p\\<^sub>3 = add a p\\<^sub>1 (opp (opp p\\<^sub>2))\" by (simp add: opp_opp)\n    with\n      add_closed [OF \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<^sub>2\\<close>,\n        folded \\<open>p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2\\<close>]\n      opp_closed [OF \\<open>on_curve a b p\\<^sub>2\\<close>]\n      opp_closed [OF \\<open>on_curve a b p\\<^sub>2\\<close>]\n      opp_opp [of p\\<^sub>2]\n      Gen\n    show ?case\n    proof (induct rule: add_case)\n      case InfL\n      then show ?case by simp\n    next\n      case InfR\n      then show ?case by (simp add: add_0_r)\n    next\n      case (Opp p)\n      from \\<open>p = add a p\\<^sub>1 (opp (opp p))\\<close>\n      have \"add a p\\<^sub>1 p = p\" by (simp add: opp_opp)\n      with ab \\<open>on_curve a b p\\<^sub>1\\<close> \\<open>on_curve a b p\\<close>\n      show ?case by (rule uniq_zero [symmetric])\n    next\n      case Tan\n      then show ?case by simp\n    next\n      case (Gen p\\<^sub>4 x\\<^sub>4 y\\<^sub>4 p\\<^sub>5 x\\<^sub>5 y\\<^sub>5 p\\<^sub>6 x\\<^sub>6 y\\<^sub>6 l')\n      from \\<open>on_curve a b p\\<^sub>5\\<close> \\<open>opp p\\<^sub>5 = p\\<^sub>2\\<close>\n        \\<open>p\\<^sub>2 = Point x\\<^sub>2 y\\<^sub>2\\<close> \\<open>p\\<^sub>5 = Point x\\<^sub>5 y\\<^sub>5\\<close>\n      have \"y\\<^sub>5 = - y\\<^sub>2\" \"x\\<^sub>5 = x\\<^sub>2\"\n        by (auto simp add: opp_Point on_curve_def)\n      from \\<open>p\\<^sub>4 = Point x\\<^sub>3 y\\<^sub>3\\<close> \\<open>p\\<^sub>4 = Point x\\<^sub>4 y\\<^sub>4\\<close>\n      have \"x\\<^sub>4 = x\\<^sub>3\" \"y\\<^sub>4 = y\\<^sub>3\" by simp_all\n      from \\<open>x\\<^sub>4 \\<noteq> x\\<^sub>5\\<close> show ?case\n        apply (simp add:\n          \\<open>y\\<^sub>5 = - y\\<^sub>2\\<close> \\<open>x\\<^sub>5 = x\\<^sub>2\\<close>\n          \\<open>x\\<^sub>4 = x\\<^sub>3\\<close> \\<open>y\\<^sub>4 = y\\<^sub>3\\<close>\n          \\<open>p\\<^sub>6 = Point x\\<^sub>6 y\\<^sub>6\\<close> \\<open>p\\<^sub>1 = Point x\\<^sub>1 y\\<^sub>1\\<close>\n          \\<open>x\\<^sub>6 = l' ^ 2 - x\\<^sub>4 - x\\<^sub>5\\<close> \\<open>y\\<^sub>6 = - y\\<^sub>4 - l' * (x\\<^sub>6 - x\\<^sub>4)\\<close>\n          \\<open>l' = (y\\<^sub>5 - y\\<^sub>4) / (x\\<^sub>5 - x\\<^sub>4)\\<close>\n          \\<open>x\\<^sub>3 = l ^ 2 - x\\<^sub>1 - x\\<^sub>2\\<close> \\<open>y\\<^sub>3 = - y\\<^sub>1 - l * (x\\<^sub>3 - x\\<^sub>1)\\<close>\n          \\<open>l = (y\\<^sub>2 - y\\<^sub>1) / (x\\<^sub>2 - x\\<^sub>1)\\<close>)\n        apply (rule conjI)\n        apply field\n        apply (rule conjI)\n        apply (rule notI)\n        apply (erule notE)\n        apply (ring (prems))\n        apply (rule sym)\n        apply field\n        apply (simp_all add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n        apply field\n        apply (rule conjI)\n        apply (rule notI)\n        apply (erule notE)\n        apply (ring (prems))\n        apply (rule sym)\n        apply field\n        apply (simp_all add: \\<open>x\\<^sub>1 \\<noteq> x\\<^sub>2\\<close> [symmetric])\n        done\n    qed\n  qed\nqed\n\nlemma add_shift_minus:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and p\\<^sub>3: \"on_curve a b p\\<^sub>3\"\n  and eq: \"add a p\\<^sub>1 p\\<^sub>2 = p\\<^sub>3\"\n  shows \"p\\<^sub>1 = add a p\\<^sub>3 (opp p\\<^sub>2)\"\nproof -\n  note eq\n  also from add_minus_id [OF ab p\\<^sub>3 opp_closed [OF p\\<^sub>2]] p\\<^sub>2\n  have \"p\\<^sub>3 = add a (add a p\\<^sub>3 (opp p\\<^sub>2)) p\\<^sub>2\" by (simp add: opp_opp)\n  finally have \"add a p\\<^sub>2 p\\<^sub>1 = add a p\\<^sub>2 (add a p\\<^sub>3 (opp p\\<^sub>2))\"\n    using p\\<^sub>1 p\\<^sub>2 p\\<^sub>3\n    by (simp add: add_comm [of a b] add_closed opp_closed)\n  with ab p\\<^sub>2 p\\<^sub>1 add_closed [OF p\\<^sub>3 opp_closed [OF p\\<^sub>2]]\n  show ?thesis by (rule cancel)\nqed\n\nlemma degen_assoc:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  and p\\<^sub>3: \"on_curve a b p\\<^sub>3\"\n  and H:\n    \"(p\\<^sub>1 = Infinity \\<or> p\\<^sub>2 = Infinity \\<or> p\\<^sub>3 = Infinity) \\<or>\n     (p\\<^sub>1 = opp p\\<^sub>2 \\<or> p\\<^sub>2 = opp p\\<^sub>3) \\<or>\n     (opp p\\<^sub>1 = add a p\\<^sub>2 p\\<^sub>3 \\<or> opp p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2)\"\n  shows \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3) = add a (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>3\"\n  using H\nproof (elim disjE)\n  assume \"p\\<^sub>1 = Infinity\"\n  then show ?thesis by (simp add: add_0_l)\nnext\n  assume \"p\\<^sub>2 = Infinity\"\n  then show ?thesis by (simp add: add_0_l add_0_r)\nnext\n  assume \"p\\<^sub>3 = Infinity\"\n  then show ?thesis by (simp add: add_0_r)\nnext\n  assume \"p\\<^sub>1 = opp p\\<^sub>2\"\n  from p\\<^sub>2 p\\<^sub>3\n  have \"add a (opp p\\<^sub>2) (add a p\\<^sub>2 p\\<^sub>3) = add a (add a p\\<^sub>3 p\\<^sub>2) (opp p\\<^sub>2)\"\n    by (simp add: add_comm [of a b] add_closed opp_closed)\n  also from ab p\\<^sub>3 p\\<^sub>2 have \"\\<dots> = p\\<^sub>3\" by (rule add_minus_id)\n  also have \"\\<dots> = add a Infinity p\\<^sub>3\" by (simp add: add_0_l)\n  also from p\\<^sub>2 have \"\\<dots> = add a (add a p\\<^sub>2 (opp p\\<^sub>2)) p\\<^sub>3\"\n    by (simp add: add_opp)\n  also from p\\<^sub>2 have \"\\<dots> = add a (add a (opp p\\<^sub>2) p\\<^sub>2) p\\<^sub>3\"\n    by (simp add: add_comm [of a b] opp_closed)\n  finally show ?thesis using \\<open>p\\<^sub>1 = opp p\\<^sub>2\\<close> by simp\nnext\n  assume \"p\\<^sub>2 = opp p\\<^sub>3\"\n  from p\\<^sub>3\n  have \"add a p\\<^sub>1 (add a (opp p\\<^sub>3) p\\<^sub>3) = add a p\\<^sub>1 (add a p\\<^sub>3 (opp p\\<^sub>3))\"\n    by (simp add: add_comm [of a b] opp_closed)\n  also from ab p\\<^sub>1 p\\<^sub>3\n  have \"\\<dots> = add a (add a p\\<^sub>1 (opp p\\<^sub>3)) (opp (opp p\\<^sub>3))\"\n    by (simp add: add_opp add_minus_id add_0_r opp_closed)\n  finally show ?thesis using p\\<^sub>3 \\<open>p\\<^sub>2 = opp p\\<^sub>3\\<close>\n    by (simp add: opp_opp)\nnext\n  assume eq: \"opp p\\<^sub>1 = add a p\\<^sub>2 p\\<^sub>3\"\n  from eq [symmetric] p\\<^sub>1\n  have \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3) = Infinity\" by (simp add: add_opp)\n  also from p\\<^sub>3 have \"\\<dots> = add a p\\<^sub>3 (opp p\\<^sub>3)\" by (simp add: add_opp)\n  also from p\\<^sub>3 have \"\\<dots> = add a (opp p\\<^sub>3) p\\<^sub>3\"\n    by (simp add: add_comm [of a b] opp_closed)\n  also from ab p\\<^sub>2 p\\<^sub>3\n  have \"\\<dots> = add a (add a (add a (opp p\\<^sub>3) (opp p\\<^sub>2)) (opp (opp p\\<^sub>2))) p\\<^sub>3\"\n    by (simp add: add_minus_id opp_closed)\n  also from p\\<^sub>2 p\\<^sub>3\n  have \"\\<dots> = add a (add a (add a (opp p\\<^sub>2) (opp p\\<^sub>3)) p\\<^sub>2) p\\<^sub>3\"\n    by (simp add: add_comm [of a b] opp_opp opp_closed)\n  finally show ?thesis\n    using opp_add [OF p\\<^sub>2 p\\<^sub>3] eq [symmetric] p\\<^sub>1\n    by (simp add: opp_opp)\nnext\n  assume eq: \"opp p\\<^sub>3 = add a p\\<^sub>1 p\\<^sub>2\"\n  from opp_add [OF p\\<^sub>1 p\\<^sub>2] eq [symmetric] p\\<^sub>3\n  have \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>3) = add a p\\<^sub>1 (add a p\\<^sub>2 (add a (opp p\\<^sub>1) (opp p\\<^sub>2)))\"\n    by (simp add: opp_opp)\n  also from p\\<^sub>1 p\\<^sub>2\n  have \"\\<dots> = add a p\\<^sub>1 (add a (add a (opp p\\<^sub>1) (opp p\\<^sub>2)) (opp (opp p\\<^sub>2)))\"\n    by (simp add: add_comm [of a b] opp_opp add_closed opp_closed)\n  also from ab p\\<^sub>1 p\\<^sub>2 have \"\\<dots> = Infinity\"\n    by (simp add: add_minus_id add_opp opp_closed)\n  also from p\\<^sub>3 have \"\\<dots> = add a p\\<^sub>3 (opp p\\<^sub>3)\" by (simp add: add_opp)\n  also from p\\<^sub>3 have \"\\<dots> = add a (opp p\\<^sub>3) p\\<^sub>3\"\n    by (simp add: add_comm [of a b] opp_closed)\n  finally show ?thesis using eq [symmetric] by simp\nqed\n\nlemma spec4_assoc:\n  assumes ab: \"nonsingular a b\"\n  and p\\<^sub>1: \"on_curve a b p\\<^sub>1\"\n  and p\\<^sub>2: \"on_curve a b p\\<^sub>2\"\n  shows \"add a p\\<^sub>1 (add a p\\<^sub>2 p\\<^sub>2) = add a (add a p\\<^sub>1 p\\<^sub>2) p\\<^sub>2\"\nproof (cases \"p\\<^sub>1 = Infinity\")\n  case True\n  from ab p\\<^sub>1 p\\<^sub>2 p\\<^sub>2\n  show ?thesis by (rule degen_assoc) (simp add: True)\nnext\n  case False\n  show ?thesis\n  proof (cases \"p\\<^sub>2 = Infinity\")\n    case True\n    from ab p\\<^sub>1 p\\<^sub>2 p\\<^sub>2\n    show ?thesis by (rule degen_assoc) (simp add: True)\n  next\n    case False\n    show ?thesis\n    proof (cases \"p\\<^sub>2 = opp p\\<^sub>2\")\n      case True\n      from ab p\\<^sub>1 p\\<^sub>2 p\\<^sub>2\n      show ?thesis by (rule degen_assoc) (simp add: True [symmetric])\n    next\n      case False\n      show ?thesis\n      proof (cases \"p\\<^sub>1 = opp p\\<^sub>2\")\n        case True\n        from ab p\\<^sub>1 p\\<^sub>2 p\\<^sub>2\n        show ?thesis by (rule degen_assoc) (simp add: True)\n      next\n        case False\n        show ?thesis\n        proof (cases \"opp p\\<^sub>1 = add a p\\<^sub>2 p\\<^sub>2\")\n          case True\n          from ab p\\<^sub>1 p\\<^sub>2 p\\<^sub>2\n          show ?thesis by (rule degen_assoc) (simp add: True)\n        next\n          case False\n          show ?thesis\n          proof (cases \"opp p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>2\")\n            case True\n            from ab p\\<^sub>1 p\\<^sub>2 p\\<^sub>2\n            show ?thesis by (rule degen_assoc) (simp add: True)\n          next\n            case False\n            show ?thesis\n            proof (cases \"p\\<^sub>1 = add a p\\<^sub>2 p\\<^sub>2\")\n              case True\n              from p\\<^sub>1 p\\<^sub>2 \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>2\\<close> \\<open>p\\<^sub>2 \\<noteq> opp p\\<^sub>2\\<close>\n                \\<open>opp p\\<^sub>1 \\<noteq> add a p\\<^sub>2 p\\<^sub>2\\<close> \\<open>opp p\\<^sub>2 \\<noteq> add a p\\<^sub>1 p\\<^sub>2\\<close>\n                \\<open>p\\<^sub>1 \\<noteq> Infinity\\<close> \\<open>p\\<^sub>2 \\<noteq> Infinity\\<close>\n              show ?thesis\n                apply (simp add: True)\n                apply (rule spec3_assoc)\n                apply (simp_all add: is_generic_def is_tangent_def)\n                apply (rule notI)\n                apply (drule uniq_zero [OF ab p\\<^sub>2 p\\<^sub>2])\n                apply simp\n                apply (intro conjI notI)\n                apply (erule notE)\n                apply (rule uniq_opp [of a])\n                apply (simp add: add_comm [of a b] add_closed)\n                apply (erule notE)\n                apply (drule uniq_zero [OF ab add_closed [OF p\\<^sub>2 p\\<^sub>2] p\\<^sub>2])\n                apply simp\n                done\n            next\n              case False\n              show ?thesis\n              proof (cases \"p\\<^sub>2 = add a p\\<^sub>1 p\\<^sub>2\")\n                case True\n                from ab p\\<^sub>1 p\\<^sub>2 True [symmetric]\n                have \"p\\<^sub>1 = Infinity\" by (rule uniq_zero)\n                then show ?thesis by (simp add: add_0_l)\n              next\n                case False\n                show ?thesis\n                proof (cases \"p\\<^sub>1 = p\\<^sub>2\")\n                  case True\n                  with p\\<^sub>2 show ?thesis\n                    by (simp add: add_comm [of a b] add_closed)\n                next\n                  case False\n                  with p\\<^sub>1 p\\<^sub>2 \\<open>p\\<^sub>1 \\<noteq> Infinity\\<close> \\<open>p\\<^sub>2 \\<noteq> Infinity\\<close>\n                    \\<open>p\\<^sub>1 \\<noteq> opp p\\<^sub>2\\<close> \\<open>p\\<^sub>2 \\<noteq> opp p\\<^sub>2\\<close>\n                    \\<open>p\\<^sub>1 \\<noteq> add a p\\<^sub>2 p\\<^sub>2\\<close> \\<open>p\\<^sub>2 \\<noteq> add a p\\<^sub>1 p\\<^sub>2\\<close> \\<open>opp p\\<^sub>2 \\<noteq> add a p\\<^sub>1 p\\<^sub>2\\<close>\n                  show ?thesis\n                    apply (rule_tac spec2_assoc)\n                    apply (simp_all add: is_generic_def is_tangent_def)\n                    apply (rule notI)\n                    apply (erule notE [of \"p\\<^sub>1 = opp p\\<^sub>2\"])\n                    apply (rule uniq_opp [of a])\n                    apply (simp add: add_comm)\n                    apply (intro conjI notI)\n                    apply (erule notE [of \"p\\<^sub>2 = opp p\\<^sub>2\"])\n                    apply (rule uniq_opp)\n                    apply assumption+\n                    apply (rule notE [OF \\<open>opp p\\<^sub>1 \\<noteq> add a p\\<^sub>2 p\\<^sub>2\\<close>])\n                    apply (simp add: opp_opp)\n                    done\n                qed\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\nqed\n\n\n\n\nprimrec (in ell_field) point_mult :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a point \\<Rightarrow> 'a point\"\nwhere\n    \"point_mult a 0 p = Infinity\"\n  | \"point_mult a (Suc n) p = add a p (point_mult a n p)\"\n\nlemma point_mult_closed: \"on_curve a b p \\<Longrightarrow> on_curve a b (point_mult a n p)\"\n  by (induct n) (simp_all add: add_closed)\n\nlemma point_mult_add:\n  \"on_curve a b p \\<Longrightarrow> nonsingular a b \\<Longrightarrow>\n   point_mult a (m + n) p = add a (point_mult a m p) (point_mult a n p)\"\n  by (induct m) (simp_all add: add_assoc point_mult_closed add_0_l)\n\nlemma point_mult_mult:\n  \"on_curve a b p \\<Longrightarrow> nonsingular a b \\<Longrightarrow>\n   point_mult a (m * n) p = point_mult a n (point_mult a m p)\"\n   by (induct n) (simp_all add: point_mult_add)\n\nlemma point_mult2_eq_double:\n  \"point_mult a 2 p = add a p p\"\n  by (simp add: numeral_2_eq_2 add_0_r)\n\nsubsection \\<open>Projective Coordinates\\<close>\n\ntype_synonym 'a ppoint = \"'a \\<times> 'a \\<times> 'a\"\n\ncontext ell_field begin\n\ndefinition pdouble :: \"'a \\<Rightarrow> 'a ppoint \\<Rightarrow> 'a ppoint\" where\n  \"pdouble a p =\n     (let (x, y, z) = p\n      in\n        if z = 0 then p\n        else\n          let\n            l = 2 * y * z;\n            m = 3 * x ^ 2 + a * z ^ 2\n          in\n            (l * (m ^ 2 - 4 * x * y * l),\n             m * (6 * x * y * l - m ^ 2) -\n             2 * y ^ 2 * l ^ 2,\n             l ^ 3))\"\n\ndefinition padd :: \"'a \\<Rightarrow> 'a ppoint \\<Rightarrow> 'a ppoint \\<Rightarrow> 'a ppoint\" where\n  \"padd a p\\<^sub>1 p\\<^sub>2 =\n     (let\n        (x\\<^sub>1, y\\<^sub>1, z\\<^sub>1) = p\\<^sub>1;\n        (x\\<^sub>2, y\\<^sub>2, z\\<^sub>2) = p\\<^sub>2\n      in\n        if z\\<^sub>1 = 0 then p\\<^sub>2\n        else if z\\<^sub>2 = 0 then p\\<^sub>1\n        else\n          let\n            d\\<^sub>1 = x\\<^sub>2 * z\\<^sub>1;\n            d\\<^sub>2 = x\\<^sub>1 * z\\<^sub>2;\n            l = d\\<^sub>1 - d\\<^sub>2;\n            m = y\\<^sub>2 * z\\<^sub>1 - y\\<^sub>1 * z\\<^sub>2\n          in\n            if l = 0 then\n              if m = 0 then pdouble a p\\<^sub>1\n              else (0, 0, 0)\n            else\n              let h = m ^ 2 * z\\<^sub>1 * z\\<^sub>2 - (d\\<^sub>1 + d\\<^sub>2) * l ^ 2\n              in\n                (l * h,\n                 (d\\<^sub>2 * l ^ 2 - h) * m - l ^ 3 * y\\<^sub>1 * z\\<^sub>2,\n                 l ^ 3 * z\\<^sub>1 * z\\<^sub>2))\"\n\ndefinition make_affine :: \"'a ppoint \\<Rightarrow> 'a point\" where\n  \"make_affine p =\n     (let (x, y, z) = p\n      in if z = 0 then Infinity else Point (x / z) (y / z))\"\n\ndefinition on_curvep :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a ppoint \\<Rightarrow> bool\" where\n  \"on_curvep a b = (\\<lambda>(x, y, z). z \\<noteq> 0 \\<longrightarrow>\n     y ^ 2 * z = x ^ 3 + a * x * z ^ 2 + b * z ^ 3)\"\n\nend\n\nlemma on_curvep_infinity [simp]: \"on_curvep a b (x, y, 0)\"\n  by (simp add: on_curvep_def)\n\nlemma make_affine_infinity [simp]: \"make_affine (x, y, 0) = Infinity\"\n  by (simp add: make_affine_def)\n\nlemma on_curvep_iff_on_curve:\n  \"on_curvep a b p = on_curve a b (make_affine p)\"\nproof (induct p rule: prod_induct3)\n  case (fields x y z)\n  show \"on_curvep a b (x, y, z) = on_curve a b (make_affine (x, y, z))\"\n  proof\n    assume H: \"on_curvep a b (x, y, z)\"\n    then have yz: \"z \\<noteq> 0 \\<Longrightarrow> y ^ 2 * z = x ^ 3 + a * x * z ^ 2 + b * z ^ 3\"\n      by (simp_all add: on_curvep_def)\n    show \"on_curve a b (make_affine (x, y, z))\"\n    proof (cases \"z = 0\")\n      case True\n      then show ?thesis by (simp add: on_curve_def make_affine_def)\n    next\n      case False\n      then show ?thesis\n        apply (simp add: on_curve_def make_affine_def)\n        apply (field yz [OF False])\n        apply assumption\n        done\n    qed\n  next\n    assume H: \"on_curve a b (make_affine (x, y, z))\"\n    show \"on_curvep a b (x, y, z)\"\n    proof (cases \"z = 0\")\n      case True\n      then show ?thesis\n        by (simp add: on_curvep_def)\n    next\n      case False\n      from H show ?thesis\n        apply (simp add: on_curve_def on_curvep_def make_affine_def False)\n        apply (field (prems))\n        apply field\n        apply (simp_all add: False)\n        done\n    qed\n  qed\nqed\n\nlemma pdouble_infinity [simp]: \"pdouble a (x, y, 0) = (x, y, 0)\"\n  by (simp add: pdouble_def)\n\nlemma padd_infinity_l [simp]: \"padd a (x, y, 0) p = p\"\n  by (simp add: padd_def)\n\nlemma pdouble_correct:\n  \"make_affine (pdouble a p) = add a (make_affine p) (make_affine p)\"\nproof (induct p rule: prod_induct3)\n  case (fields x y z)\n  then show ?case\n    apply (auto simp add: add_def pdouble_def make_affine_def eq_opp_is_zero Let_def)\n    apply field\n    apply simp\n    apply field\n    apply simp\n    done\nqed\n\nlemma padd_correct:\n  assumes p\\<^sub>1: \"on_curvep a b p\\<^sub>1\" and p\\<^sub>2: \"on_curvep a b p\\<^sub>2\"\n  shows \"make_affine (padd a p\\<^sub>1 p\\<^sub>2) = add a (make_affine p\\<^sub>1) (make_affine p\\<^sub>2)\"\n  using p\\<^sub>1\nproof (induct p\\<^sub>1 rule: prod_induct3)\n  case (fields x\\<^sub>1 y\\<^sub>1 z\\<^sub>1)\n  note p\\<^sub>1' = fields\n  from p\\<^sub>2 show ?case\n  proof (induct p\\<^sub>2 rule: prod_induct3)\n    case (fields x\\<^sub>2 y\\<^sub>2 z\\<^sub>2)\n    then have\n      yz\\<^sub>2: \"z\\<^sub>2 \\<noteq> 0 \\<Longrightarrow> y\\<^sub>2 ^ 2 * z\\<^sub>2 * z\\<^sub>1 ^ 3 =\n        (x\\<^sub>2 ^ 3 + a * x\\<^sub>2 * z\\<^sub>2 ^ 2 + b * z\\<^sub>2 ^ 3) * z\\<^sub>1 ^ 3\"\n      by (simp_all add: on_curvep_def)\n    from p\\<^sub>1' have\n      yz\\<^sub>1: \"z\\<^sub>1 \\<noteq> 0 \\<Longrightarrow> y\\<^sub>1 ^ 2 * z\\<^sub>1 * z\\<^sub>2 ^ 3 =\n        (x\\<^sub>1 ^ 3 + a * x\\<^sub>1 * z\\<^sub>1 ^ 2 + b * z\\<^sub>1 ^ 3) * z\\<^sub>2 ^ 3\"\n      by (simp_all add: on_curvep_def)\n    show ?case\n    proof (cases \"z\\<^sub>1 = 0\")\n      case True\n      then show ?thesis\n        by (simp add: add_def padd_def make_affine_def)\n    next\n      case False\n      show ?thesis\n      proof (cases \"z\\<^sub>2 = 0\")\n        case True\n        then show ?thesis\n          by (simp add: add_def padd_def make_affine_def)\n      next\n        case False\n        show ?thesis\n        proof (cases \"x\\<^sub>2 * z\\<^sub>1 - x\\<^sub>1 * z\\<^sub>2 = 0\")\n          case True\n          note x = this\n          then have x': \"x\\<^sub>2 * z\\<^sub>1 = x\\<^sub>1 * z\\<^sub>2\" by simp\n          show ?thesis\n          proof (cases \"y\\<^sub>2 * z\\<^sub>1 - y\\<^sub>1 * z\\<^sub>2 = 0\")\n            case True\n            then have y: \"y\\<^sub>2 * z\\<^sub>1 = y\\<^sub>1 * z\\<^sub>2\" by simp\n            from \\<open>z\\<^sub>1 \\<noteq> 0\\<close> \\<open>z\\<^sub>2 \\<noteq> 0\\<close> x\n            have \"make_affine (x\\<^sub>2, y\\<^sub>2, z\\<^sub>2) = make_affine (x\\<^sub>1, y\\<^sub>1, z\\<^sub>1)\"\n              apply (simp add: make_affine_def)\n              apply (rule conjI)\n              apply (field x')\n              apply simp\n              apply (field y)\n              apply simp\n              done\n            with True x \\<open>z\\<^sub>1 \\<noteq> 0\\<close> \\<open>z\\<^sub>2 \\<noteq> 0\\<close> p\\<^sub>1' fields show ?thesis\n              by (simp add: padd_def pdouble_correct)\n          next\n            case False\n            have \"y\\<^sub>2 ^ 2 * z\\<^sub>1 ^ 3 * z\\<^sub>2 = y\\<^sub>1 ^ 2 * z\\<^sub>1 * z\\<^sub>2 ^ 3\"\n              by (ring yz\\<^sub>1 [OF \\<open>z\\<^sub>1 \\<noteq> 0\\<close>] yz\\<^sub>2 [OF \\<open>z\\<^sub>2 \\<noteq> 0\\<close>] x')\n            then have \"y\\<^sub>2 ^ 2 * z\\<^sub>1 ^ 3 * z\\<^sub>2 / z\\<^sub>1 / z\\<^sub>2 =\n              y\\<^sub>1 ^ 2 * z\\<^sub>1 * z\\<^sub>2 ^ 3 / z\\<^sub>1 / z\\<^sub>2\"\n              by simp\n            then have \"(y\\<^sub>2 * z\\<^sub>1) * (y\\<^sub>2 * z\\<^sub>1) = (y\\<^sub>1 * z\\<^sub>2) * (y\\<^sub>1 * z\\<^sub>2)\"\n              apply (field (prems))\n              apply (field)\n              apply (rule TrueI)\n              apply (simp add: \\<open>z\\<^sub>1 \\<noteq> 0\\<close> \\<open>z\\<^sub>2 \\<noteq> 0\\<close>)\n              done\n            with False\n            have y\\<^sub>2z\\<^sub>1: \"y\\<^sub>2 * z\\<^sub>1 = - (y\\<^sub>1 * z\\<^sub>2)\"\n              by (simp add: square_eq_iff)\n            from x False \\<open>z\\<^sub>1 \\<noteq> 0\\<close> \\<open>z\\<^sub>2 \\<noteq> 0\\<close> show ?thesis\n              apply (simp add: padd_def add_def make_affine_def Let_def)\n              apply (rule conjI)\n              apply (rule impI)\n              apply (field x')\n              apply simp\n              apply (field y\\<^sub>2z\\<^sub>1)\n              apply simp\n              done\n          qed\n        next\n          case False\n          then have \"x\\<^sub>1 / z\\<^sub>1 \\<noteq> x\\<^sub>2 / z\\<^sub>2\"\n            apply (rule_tac notI)\n            apply (erule notE)\n            apply (drule sym)\n            apply (field (prems))\n            apply ring\n            apply (simp add: \\<open>z\\<^sub>1 \\<noteq> 0\\<close> \\<open>z\\<^sub>2 \\<noteq> 0\\<close>)\n            done\n          with False \\<open>z\\<^sub>1 \\<noteq> 0\\<close> \\<open>z\\<^sub>2 \\<noteq> 0\\<close>\n          show ?thesis\n            apply (auto simp add: padd_def add_def make_affine_def Let_def)\n            apply field\n            apply simp\n            apply field\n            apply simp\n            done\n        qed\n      qed\n    qed\n  qed\nqed\n\nlemma pdouble_closed:\n  \"on_curvep a b p \\<Longrightarrow> on_curvep a b (pdouble a p)\"\n  by (simp add: on_curvep_iff_on_curve pdouble_correct add_closed)\n\nlemma padd_closed:\n  \"on_curvep a b p\\<^sub>1 \\<Longrightarrow> on_curvep a b p\\<^sub>2 \\<Longrightarrow> on_curvep a b (padd a p\\<^sub>1 p\\<^sub>2)\"\n  by (simp add: on_curvep_iff_on_curve padd_correct add_closed)\n\nprimrec (in ell_field) ppoint_mult :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a ppoint \\<Rightarrow> 'a ppoint\"\nwhere\n    \"ppoint_mult a 0 p = (0, 0, 0)\"\n  | \"ppoint_mult a (Suc n) p = padd a p (ppoint_mult a n p)\"\n\nlemma ppoint_mult_closed [simp]:\n  \"on_curvep a b p \\<Longrightarrow> on_curvep a b (ppoint_mult a n p)\"\n  by (induct n) (simp_all add: padd_closed)\n\nlemma ppoint_mult_correct: \"on_curvep a b p \\<Longrightarrow>\n  make_affine (ppoint_mult a n p) = point_mult a n (make_affine p)\"\n  by (induct n) (simp_all add: padd_correct)\n\ncontext ell_field begin\n\ndefinition proj_eq :: \"'a ppoint \\<Rightarrow> 'a ppoint \\<Rightarrow> bool\" where\n  \"proj_eq = (\\<lambda>(x\\<^sub>1, y\\<^sub>1, z\\<^sub>1) (x\\<^sub>2, y\\<^sub>2, z\\<^sub>2).\n     (z\\<^sub>1 = 0) = (z\\<^sub>2 = 0) \\<and> x\\<^sub>1 * z\\<^sub>2 = x\\<^sub>2 * z\\<^sub>1 \\<and> y\\<^sub>1 * z\\<^sub>2 = y\\<^sub>2 * z\\<^sub>1)\"\n\nend\n\nlemma proj_eq_refl: \"proj_eq p p\"\n  by (auto simp add: proj_eq_def)\n\nlemma proj_eq_sym: \"proj_eq p p' \\<Longrightarrow> proj_eq p' p\"\n  by (auto simp add: proj_eq_def)\n\nlemma proj_eq_trans:\n  \"in_carrierp p \\<Longrightarrow> in_carrierp p' \\<Longrightarrow> in_carrierp p'' \\<Longrightarrow>\n   proj_eq p p' \\<Longrightarrow> proj_eq p' p'' \\<Longrightarrow> proj_eq p p''\"\nproof (induct p rule: prod_induct3)\n  case (fields x y z)\n  then show ?case\n  proof (induct p' rule: prod_induct3)\n    case (fields x' y' z')\n    then show ?case\n    proof (induct p'' rule: prod_induct3)\n      case (fields x'' y'' z'')\n      then have\n        z: \"(z = 0) = (z' = 0)\" \"(z' = 0) = (z'' = 0)\" and\n        \"x * z' * z'' = x' * z * z''\"\n        \"y * z' * z'' = y' * z * z''\"\n        and xy:\n        \"x' * z'' = x'' * z'\"\n        \"y' * z'' = y'' * z'\"\n        by (simp_all add: proj_eq_def)\n      from \\<open>x * z' * z'' = x' * z * z''\\<close>\n      have \"(x * z'') * z' = (x'' * z) * z'\"\n        by (ring (prems) xy) (ring xy)\n      moreover from \\<open>y * z' * z'' = y' * z * z''\\<close>\n      have \"(y * z'') * z' = (y'' * z) * z'\"\n        by (ring (prems) xy) (ring xy)\n      ultimately show ?case using z\n        by (auto simp add: proj_eq_def)\n    qed\n  qed\nqed\n\nlemma make_affine_proj_eq_iff:\n  \"proj_eq p p' = (make_affine p = make_affine p')\"\nproof (induct p rule: prod_induct3)\n  case (fields x y z)\n  then show ?case\n  proof (induct p' rule: prod_induct3)\n    case (fields x' y' z')\n    show ?case\n    proof\n      assume \"proj_eq (x, y, z) (x', y', z')\"\n      then have \"(z = 0) = (z' = 0)\"\n        and xy: \"x * z' = x' * z\" \"y * z' = y' * z\"\n        by (simp_all add: proj_eq_def)\n      then show \"make_affine (x, y, z) = make_affine (x', y', z')\"\n        apply (auto simp add: make_affine_def)\n        apply (field xy)\n        apply simp\n        apply (field xy)\n        apply simp\n        done\n    next\n      assume H: \"make_affine (x, y, z) = make_affine (x', y', z')\"\n      show \"proj_eq (x, y, z) (x', y', z')\"\n      proof (cases \"z = 0\")\n        case True\n        with H have \"z' = 0\" by (simp add: make_affine_def split: if_split_asm)\n        with True show ?thesis by (simp add: proj_eq_def)\n      next\n        case False\n        with H have \"z' \\<noteq> 0\" \"x / z = x' / z'\" \"y / z = y' / z'\"\n          by (simp_all add: make_affine_def split: if_split_asm)\n        from \\<open>x / z = x' / z'\\<close>\n        have \"x * z' = x' * z\"\n          apply (field (prems))\n          apply field\n          apply (simp_all add: \\<open>z \\<noteq> 0\\<close> \\<open>z' \\<noteq> 0\\<close>)\n          done\n        moreover from \\<open>y / z = y' / z'\\<close>\n        have \"y * z' = y' * z\"\n          apply (field (prems))\n          apply field\n          apply (simp_all add: \\<open>z \\<noteq> 0\\<close> \\<open>z' \\<noteq> 0\\<close>)\n          done\n        ultimately show ?thesis\n          by (simp add: proj_eq_def \\<open>z \\<noteq> 0\\<close> \\<open>z' \\<noteq> 0\\<close>)\n      qed\n    qed\n  qed\nqed\n\nlemma pdouble_proj_eq_cong:\n  \"proj_eq p p' \\<Longrightarrow> proj_eq (pdouble a p) (pdouble a p')\"\n  by (simp add: make_affine_proj_eq_iff pdouble_correct)\n\nlemma padd_proj_eq_cong:\n  \"on_curvep a b p\\<^sub>1 \\<Longrightarrow> on_curvep a b p\\<^sub>1' \\<Longrightarrow> on_curvep a b p\\<^sub>2 \\<Longrightarrow> on_curvep a b p\\<^sub>2' \\<Longrightarrow>\n   proj_eq p\\<^sub>1 p\\<^sub>1' \\<Longrightarrow> proj_eq p\\<^sub>2 p\\<^sub>2' \\<Longrightarrow> proj_eq (padd a p\\<^sub>1 p\\<^sub>2) (padd a p\\<^sub>1' p\\<^sub>2')\"\n  by (simp add: make_affine_proj_eq_iff padd_correct)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Elliptic_Curves_Group_Law/Elliptic_Axclass.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7591560220297698}}
{"text": "theory Chapter1_PreciseProofs\n  imports Chapter0\nbegin\n\nsection \"1 Topology  Definition\"\n\n(* A topology on a set X is a collection T of subsets of X, \nincluding the empty set \\<emptyset> and X itself, \nin which T is closed under arbitrary union and finite intersection *)\n\ndefinition closed_topo :: \"('w \\<sigma> \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where \"closed_topo T \\<equiv> T \\<^bold>\\<top> \\<and> T \\<^bold>\\<bottom> \n                \\<and> supremum_closed T\n                \\<and> meet_closed T\"\n\ndefinition open_topo :: \"('w \\<sigma> \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where \"open_topo T \\<equiv> T \\<^bold>\\<top> \\<and> T \\<^bold>\\<bottom> \n                \\<and> infimum_closed T\n                \\<and> join_closed T\"\n\n\n\nsection \"2 Closure Operator Axioms\"\n\n(*\nAssociated with any topology T is the topological closure operator, \ndenoted Cl, which gives, for any subset A \\<subseteq> X, \nthe smallest closed set containing A. \n\nObviously, a set A is closed if and only if Cl(A) = A. \nTherefore, we can treat T as the collection of all fixed points of the Cl operator. \nHere and below, we call a set A \\<subseteq> X a fixed point of an operator Op \nif and only if Op(A) = A.\n*)\n\n(* fix point definition *)\ndefinition fixpoint_op::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('w \\<sigma> \\<Rightarrow> 'w \\<sigma>)\" (\"(_\\<^sup>f\\<^sup>p)\") \n  where \"\\<phi>\\<^sup>f\\<^sup>p  \\<equiv> \\<lambda>X. (\\<phi> X) \\<^bold>\\<leftrightarrow> X\"\ndefinition fixpoint_pred::\"('w \\<sigma> \\<Rightarrow> 'w \\<sigma>) \\<Rightarrow> ('w \\<sigma> \\<Rightarrow> bool)\" (\"fp\")\n  where \"fp \\<phi> \\<equiv> \\<lambda>X. \\<phi> X \\<^bold>\\<approx> X\"\n\n\n(*\nDenote P(X) as the powerset of X. \nThen Cl as defined above is viewed as an operator Cl : P(X) \\<rightarrow> P(X) \nthat satisfies the following properties (for any sets A, B \\<subseteq> X):\n[CO1] Cl(\\<emptyset>) = \\<emptyset>;\n[CO2] A \\<subseteq> Cl(A);\n[CO3] Cl(Cl(A)) = Cl(A);\n[CO4] Cl(A \\<union> B) = Cl(A) \\<union> Cl(B).\n*)\n\n(* Normality (NORM) *)\ndefinition CO1::\"'w cl \\<Rightarrow> bool\" (\"NORM\") \n  where \"CO1 Cl \\<equiv> (Cl \\<^bold>\\<bottom>) \\<^bold>\\<approx> \\<^bold>\\<bottom>\"\n(* Expansive (EXPN) *)\ndefinition CO2::\"'w cl \\<Rightarrow> bool\" (\"EXPN\") \n  where \"CO2 Cl \\<equiv> \\<forall>A. A \\<^bold>\\<preceq> Cl A\"\n(* Idempotent (IDEM) *)\ndefinition CO3::\"'w cl \\<Rightarrow> bool\" (\"IDEM\") \n  where \"CO3 Cl \\<equiv> \\<forall>A. (Cl A) \\<^bold>\\<approx> Cl(Cl A)\"\n(* Additivity (ADDI) *)\ndefinition CO4::\"'w cl \\<Rightarrow> bool\" (\"ADDI\") \n  where \"CO4 Cl \\<equiv> \\<forall>A B. Cl(A \\<^bold>\\<or> B) \\<^bold>\\<approx> (Cl A) \\<^bold>\\<or> (Cl B)\"\n\ndefinition closure_op :: \"'w cl \\<Rightarrow> bool\"\n  where \"closure_op \\<equiv> CO1 \\<^bold>\\<and> CO2 \\<^bold>\\<and> CO3 \\<^bold>\\<and> CO4\"\n\n(*\nnamed_theorems closure_def (*to group together order-related definitions*)\ndeclare \n  CO1_def[closure_def] \n  CO2_def[closure_def]\n  CO3_def[closure_def] \n  CO4_def[closure_def]\n*)\n\n(*\nIndeed, any operator Cl on P(X)\nthat satisfies the above four axioms (called Kuratowski Closure Axioms) \ndefines a topological closure operator. \nIts fixed points {A| Cl(A) = A} form a set system\nthat can be properly identified as a collection of closed sets \n*)\n\n\n\nsection \"1nd Topo-Condition for bottom-element\"\n\n\n(* sledgehammer proof *)\nlemma \n  assumes \"CO1 Cl\"\n  shows \"(fp Cl) \\<^bold>\\<bottom>\"\n  by (meson CO1_def assms fixpoint_pred_def)\n\n\nlemma \n  assumes 1: \"CO1 Cl\"\n  shows \"(fp Cl) \\<^bold>\\<bottom>\" \nproof (unfold bottom_def fixpoint_pred_def setequ_equ, rule)\n  fix w\n  have \"(Cl \\<^bold>\\<bottom>) \\<^bold>\\<approx> \\<^bold>\\<bottom>\" using CO1_def assms by auto\n  hence \"(Cl (\\<lambda>w. False)) w = (\\<lambda>w. False) w\" \n    using bottom_def setequ_def by (metis setequ_equ)\n  thus \"(Cl (\\<lambda>w. False)) w = False\" by (simp)\nqed\n\n\nsection \"2nd Topo-Condition for top-element\"\n\nlemma \n  assumes \"CO2 Cl\"\n  shows \"(fp Cl) \\<^bold>\\<top>\"\n  by (metis (mono_tags, lifting) \n        CO2_def assms \n        fixpoint_pred_def \n        setequ_def subset_def top_def)\n\n\nlemma \n  fixes Cl\n  assumes 1: \"CO2 Cl\"\n  shows \"(fp Cl) \\<^bold>\\<top>\" \n  apply (unfold top_def fixpoint_pred_def setequ_equ)\nproof (rule, rule iffI)\n  fix w\n  show l2r: \"Cl (\\<lambda>w. True) w \\<Longrightarrow> True\" by simp\nnext\n  fix w\n  show r2l: \"True \\<Longrightarrow> (Cl (\\<lambda>w. True)) w\"\n  proof -\n    have \"\\<forall>A. A \\<^bold>\\<preceq> Cl A\" using CO2_def assms by auto\n    hence \"(\\<lambda>w. True) \\<^bold>\\<preceq> Cl (\\<lambda>w. True)\" by simp\n    thus \"True \\<Longrightarrow> (Cl (\\<lambda>w. True)) w\" by (simp add: subset_def)\n  qed\nqed\n\n\n\nsection \"3rd topo-condition for infimum_closed (fp Cl)\"\n\n(* tbc *)\n\n\n\n\nsection \"4rd topo-condition for join_closed (fp Cl)\"\n\nlemma\n  fixes Cl\n  assumes co2: \"CO2 Cl\"\n  assumes co4: \"CO4 Cl\"\n  shows \"join_closed (fp Cl)\" \n  (*by (smt (verit) CO4_def assms fixpoint_pred_def join_closed_def setequ_equ)*)\n  apply (unfold join_closed_def fixpoint_pred_def setequ_equ join_def)\nproof (rule, rule, rule, rule)\n  fix X Y w\n  assume fixP: \"Cl X = X \\<and> Cl Y = Y\"\n  show \"Cl (\\<lambda>w. X w \\<or> Y w) w = (X w \\<or> Y w)\"\n  proof\n    assume clXY: \"Cl (\\<lambda>w. X w \\<or> Y w) w\"\n    show \"X w \\<or> Y w\" \n      (*by (metis CO4_def clXY co4 fixP join_def setequ_char setequ_equ)*)\n    proof -\n      from clXY have rw: \"Cl (\\<lambda>w. X w \\<or> Y w) \\<^bold>\\<approx> Cl(X \\<^bold>\\<or> Y)\" by (simp add: join_def setequ_equ)\n      have \"Cl(X \\<^bold>\\<or> Y) \\<^bold>\\<approx> (Cl X) \\<^bold>\\<or> (Cl Y)\" using assms CO4_def by auto\n      hence \"Cl(X \\<^bold>\\<or> Y) \\<^bold>\\<approx> (X \\<^bold>\\<or> Y)\" using fixP by simp\n      hence \"Cl (\\<lambda>w. (X w) \\<or> (Y w)) w \\<longleftrightarrow> (\\<lambda>w. (X w) \\<or> (Y w)) w\" using join_def setequ_def rw by metis\n      hence \"Cl (\\<lambda>w. (X w) \\<or> (Y w)) w \\<longrightarrow> (X w \\<or> Y w)\" by simp\n      thus ?thesis by (simp add: clXY)\n    qed\n  next\n    assume XY: \"X w \\<or> Y w\"\n    show \"Cl (\\<lambda>w. X w \\<or> Y w) w\" \n    proof -\n      have \"\\<forall>A. A \\<^bold>\\<preceq> Cl A\" using co2 CO2_def by auto\n      thus ?thesis by (metis XY subset_def)\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "jhln", "repo": "Bamberg", "sha": "73c62c87b4c3a5f39c211d4162f9915390f4cd64", "save_path": "github-repos/isabelle/jhln-Bamberg", "path": "github-repos/isabelle/jhln-Bamberg/Bamberg-73c62c87b4c3a5f39c211d4162f9915390f4cd64/Closure Systems/Chapter1_PreciseProofs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178969328286, "lm_q2_score": 0.8354835309589074, "lm_q1q2_score": 0.7591352888218962}}
{"text": "theory BST_Demo\nimports \"~~/src/HOL/Library/Tree\"\nbegin\n\n(* useful most of the time: *)\ndeclare Let_def [simp]\n\nsection \"BST Search and Insertion\"\n\nfun isin :: \"('a::linorder) tree \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"isin Leaf x = False\" |\n\"isin (Node l a r) x =\n  (if x < a then isin l x else\n   if x > a then isin r x\n   else True)\"\n\nfun ins :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"ins x Leaf = Node Leaf x Leaf\" |\n\"ins x (Node l a r) =\n  (if x < a then Node (ins x l) a r else\n   if x > a then Node l a (ins x r)\n   else Node l a r)\"\n\nsubsection \"Functional Correctness\"\n\nlemma set_tree_isin: \"bst t \\<Longrightarrow> isin t x = (x \\<in> set_tree t)\"\napply(induction t)\napply auto\ndone\n\nlemma set_tree_ins: \"set_tree (ins x t) = {x} \\<union> set_tree t\"\napply(induction t)\napply auto\ndone\n\nsubsection \"Preservation of Invariant\"\n\nlemma bst_ins: \"bst t \\<Longrightarrow> bst (ins x t)\"\napply(induction t)\napply (auto simp: set_tree_ins)\ndone\n\n\nsection \"BST Deletion\"\n\nfun split_min :: \"'a tree \\<Rightarrow> 'a * 'a tree\" where\n\"split_min (Node l a r) =\n  (if l = Leaf then (a,r)\n   else let (x,l') = split_min l\n        in (x, Node l' a r))\"\n\nfun delete :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"delete x Leaf = Leaf\" |\n\"delete x (Node l a r) =\n  (if x < a then Node (delete x l) a r else\n   if x > a then Node l a (delete x r)\n   else if r = Leaf then l else let (a',r') = split_min r in Node l a' r')\"\n\n(* A proof attempt *)\n\nlemma \"split_min t = (x,t') \\<Longrightarrow> set_tree t' = set_tree t - {x}\"\noops\n\n(* The final proof (needs more than auto!): *)\n\nlemma \"\\<lbrakk> split_min t = (x,t'); bst t; t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow>\n  set_tree t' = set_tree t - {x} \\<and> x \\<in> set_tree t\"\napply(induction t arbitrary: x t')\n apply simp\napply (force split: if_split_asm prod.splits)\ndone\n\nend\n", "meta": {"author": "amartyads", "repo": "functional-data-structures-HW", "sha": "df9edfd02bda931a0633f0e66bf8e32d7347902b", "save_path": "github-repos/isabelle/amartyads-functional-data-structures-HW", "path": "github-repos/isabelle/amartyads-functional-data-structures-HW/functional-data-structures-HW-df9edfd02bda931a0633f0e66bf8e32d7347902b/04/BST_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582997, "lm_q2_score": 0.8354835330070839, "lm_q1q2_score": 0.7591352886154779}}
{"text": "theory Free_Group\nimports Main \nbegin\n\ndatatype 'a gentype = C 'a | InvG 'a\n\nprimrec inverse :: \" 'a gentype ⇒ 'a gentype\"\n  where\n\"inverse (C x) = InvG x\"\n|\"inverse (InvG x) = C x\"\n\nprimrec genset :: \"('a gentype) list ⇒ ('a gentype) list\"\n  where\n\"genset [] = []\"\n|\"genset (x#xs) = (x#[inverse x]) @ (genset xs)\"\n\ntype_synonym 'a word = \"('a gentype) list\"\n\ninductive_set spanset :: \"('a gentype list) ⇒('a gentype ⇒ 'a gentype ⇒ 'a gentype) ⇒ ('a gentype) list\"\n  for S :: \"('a gentype) list\" and f :: \"('a gentype⇒ 'a gentype⇒ 'a gentype)\" \n  where\n\"x ∈ genset S ⟹ x ∈ spanset S f\"\n|\"x ∈ spanset S f ⟹ y ∈ spanset S f ⟹ (f x y) ∈ spanset S f\"\n\nfun is_inverse :: \"'a word ⇒ bool\"\n  where\n\"is_inverse [] = False\"\n|\"is_inverse (x#[]) = False\"\n|\"is_inverse (x#[y]) = (if x = inverse y then True else False)\"\n\n\nfun reduce :: \"'a word ⇒ 'a word\"\n  where\n\"reduce [] = []\"\n|\"reduce (x#[]) = (x#[])\"\n|\"reduce (x#(y#xys)) = (if is_inverse (x#[y]) then reduce xys else x#(reduce(y#xys)))\"\n\nfun is_reduced :: \"'a word ⇒ bool\"\n  where\n\"is_reduced [] = True\"\n|\"is_reduced (x#[]) = True\"\n|\"is_reduced (x#(y#xys)) = (if is_inverse (x#[y]) then False else is_reduced (y#xys))\"\n\n(*define reduced:: \"'a gentype set\" as a spanset S where ∄ x ∈ S. (y = inverse x) ∈ S\"\n and prove lemma empty_list_is_reduced and set with one element is reduced.*)\n\n(*lemma spanset_prop:\n  assumes \"x ∈ spanset n f \" \n  shows \"(∃ ls. length ls = n) \"\nproof-\n  using assms by (solve_direct: List.Ex_list_of_length)\nqed \n\nlemma spanset_prop1:\n  assumes \"x ∈ spanset n f \" \n  shows \"∃ ls. ls = x\"\nproof -\n  using assms by (solve_direct :  SMT.smt_arith_simplify(45))\nqed \n\n*)\n\n\n  \n \n\n\n  \n\n", "meta": {"author": "prathamesht-cs", "repo": "Groupabelle", "sha": "3b8369e3016b8e380eccd9c0033c60aa4a9755cf", "save_path": "github-repos/isabelle/prathamesht-cs-Groupabelle", "path": "github-repos/isabelle/prathamesht-cs-Groupabelle/Groupabelle-3b8369e3016b8e380eccd9c0033c60aa4a9755cf/Free_Group.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178870347122, "lm_q2_score": 0.8354835391516133, "lm_q1q2_score": 0.7591352879962222}}
{"text": "(*  Title:       Reachability implemented using while-loops\n    Authors:     Thomas Tuerk <tuerk@in.tum.de>\n*)\n\ntheory Accessible\nimports Main Workset\nbegin\n\n\nsubsection \\<open> accessible\\<close>\n\ntext \\<open> Let's define the set of value that are accessible/reachable from\n a given value using a binary relation. \\<close>\ndefinition accessible where\n  \"accessible R ws \\<equiv> R\\<^sup>* `` ws\"\n\nlemma accessible_empty [simp] :\n  \"accessible R {} = {}\" by (simp add: accessible_def)\n\nlemma accessible_union :\n  \"accessible R (ws \\<union> ws') = \n   accessible R ws \\<union> accessible R ws'\" \nunfolding accessible_def by (rule Image_Un)\n\nlemma accessible_Union :\n  \"accessible R (\\<Union> wss) = \\<Union> (accessible R ` wss)\" \nby (auto simp add: accessible_def)\n\nlemma accessible_insert :\n  \"accessible R (insert x ws) = \n   {y. (x, y) \\<in> R\\<^sup>*} \\<union> accessible R ws\" \nby (auto simp add: accessible_def)\n\nlemma accessible_eq_empty [simp] :\n   \"(accessible R ws = {}) \\<longleftrightarrow> (ws = {})\"\nunfolding accessible_def by auto\n\nlemma accessible_mono :\n  \"ws \\<subseteq> ws' \\<Longrightarrow> (accessible R ws \\<subseteq> accessible R ws')\"\nunfolding accessible_def by auto\n\nlemma accessible_subset_ws :\n  \"ws \\<subseteq> accessible R ws\"\nby (auto simp add: subset_iff accessible_def)\n\nlemma accessible_insert2 :\n  \"accessible R (insert x ws) = \n   insert x (accessible R (ws \\<union> {y. (x, y) \\<in> R}))\"\napply (auto simp add: accessible_def Image_iff Bex_def)\n  apply (metis converse_rtranclE)\napply (metis converse_rtrancl_into_rtrancl)\ndone\n\nlemma accessible_subset_R_ws_gen : \nassumes ws_S: \"ws \\<subseteq> S\"\n    and R_S: \"\\<And>x y. x \\<in> S \\<and> (x, y) \\<in> R \\<Longrightarrow> y \\<in> S\"\nshows \"accessible R ws \\<subseteq> S\"\nproof -\n  have \"\\<And>x y. \\<lbrakk>(x, y) \\<in> R\\<^sup>*; x \\<in> S\\<rbrakk> \\<Longrightarrow> y \\<in> S\"\n  proof -\n    fix x y\n    show \"\\<lbrakk>(x, y) \\<in> R\\<^sup>*; x \\<in> S\\<rbrakk> \\<Longrightarrow> y \\<in> S\"\n      apply (induct rule: converse_rtrancl_induct)\n      apply simp\n      apply (metis R_S)\n    done\n  qed\n  thus ?thesis\n    unfolding accessible_def\n    using ws_S\n    by auto\nqed\n\nlemma accessible_subset_R_ws: \"accessible R ws \\<subseteq> snd ` R \\<union> ws\"\nunfolding accessible_def\nby (auto simp add: image_iff Bex_def, metis rtranclE)\n\nlemma accessible_finite___args_finite :\nassumes fin_R: \"finite R\"\n    and fin_ws: \"finite ws\"\nshows \"finite (accessible R ws)\"\nproof -\n  have acc_subset: \"accessible R ws \\<subseteq> snd ` R \\<union> ws\" \n    by (simp add: accessible_subset_R_ws)\n  \n  have \"finite (snd ` R \\<union> ws)\" \n    by (simp add: fin_ws fin_R)\n  with acc_subset show ?thesis by (metis finite_subset) \nqed\n\nlemma accessible_accessible_idempot :\n   \"(accessible R (accessible R ws)) = accessible R ws\"\nby (auto simp add: accessible_def Image_iff Bex_def,\n    metis rtrancl_trans)\n\nlemma accessible_subset_accessible :\n   \"accessible R ws1 \\<subseteq> accessible R ws2 \\<longleftrightarrow>\n    ws1 \\<subseteq> accessible R ws2\"\nunfolding accessible_def\nby (auto simp add: accessible_def Image_iff Bex_def subset_iff,\n    metis rtrancl_trans)\n\ndefinition accessible_restrict where\n  \"accessible_restrict R rs ws \\<equiv> \n   rs \\<union> accessible (R - (rs \\<times> UNIV)) ws\"\n\nlemma accessible_restrict_empty :\n  \"accessible_restrict R {} ws = accessible R ws\"\n  by (simp add: accessible_restrict_def)\n\nlemma accessible_restrict_final [simp] :\n  \"accessible_restrict R rs {} = rs\"\n  by (simp add: accessible_restrict_def)\n\nlemma accessible_restrict_insert_in :\n  \"x \\<in> rs \\<Longrightarrow> \n   accessible_restrict R rs (insert x ws) = \n   accessible_restrict R rs ws\"\nunfolding accessible_restrict_def\nby (auto simp add: accessible_insert2)\n\nlemma accessible_restrict_diff_rs :\n  \"accessible_restrict R rs ws = \n   accessible_restrict R rs (ws - rs)\"\nproof -\n  { fix x y \n    have \"\\<lbrakk>(x, y) \\<in> (R - rs \\<times> UNIV)\\<^sup>*;y \\<notin> rs\\<rbrakk> \\<Longrightarrow> x \\<notin> rs\" \n    by (erule converse_rtranclE, simp_all)\n  }\n  thus ?thesis\n    unfolding accessible_def accessible_restrict_def Image_def Bex_def\n    by auto \nqed\n\nlemma accessible_restrict_insert_nin :\n  \"x \\<notin> rs \\<Longrightarrow> \n   accessible_restrict R rs (insert x ws) = \n   accessible_restrict R (insert x rs) (ws \\<union> {y. (x, y) \\<in> R})\"\nproof -\n  assume x_nin_rs: \"x \\<notin> rs\" \n  obtain R_res where R_res_def: \"R_res = (\\<lambda>rs. (R - (rs \\<times> UNIV)))\" \n    by blast\n   \n  have \"accessible (R_res (insert x rs)) (ws \\<union> {y. (x, y) \\<in> R}) =\n        accessible (R_res rs) (ws \\<union> {y. (x, y) \\<in> R})\"\n        (is \"?acc1 = ?acc2\")\n  proof (intro set_eqI iffI)\n    fix e\n    assume e_in_acc1: \"e \\<in> ?acc1\"\n\n    have \"R_res (insert x rs) \\<subseteq> R_res rs\" unfolding R_res_def by force\n    from rtrancl_mono[OF this] e_in_acc1 \n      show \"e \\<in> ?acc2\"\n      unfolding accessible_def\n      by auto\n  next \n    fix e\n    let ?ws' = \"ws \\<union> {y. (x, y) \\<in> R}\"\n\n    have ind_part: \"\\<And>y. \\<lbrakk>(y, e) \\<in> (R_res rs)\\<^sup>*; y \\<in> ?ws'\\<rbrakk> \\<Longrightarrow>\n                         \\<exists>y'. y' \\<in> ?ws' \\<and> (y', e) \\<in> (R_res (insert x rs))\\<^sup>*\"\n    proof -\n      fix y\n      show \"\\<lbrakk>(y, e) \\<in> (R_res rs)\\<^sup>*; y \\<in> ?ws'\\<rbrakk> \\<Longrightarrow>\n             \\<exists>y'. y' \\<in> ?ws' \\<and> (y', e) \\<in> (R_res (insert x rs))\\<^sup>*\"\n      proof (induct rule: rtrancl_induct)\n        case base thus ?case by auto\n      next\n        case (step y2 z)\n        note y2_z_in_R_res = step(2)\n        note ind_hyp = step(3)[OF step(4)]\n\n        show \"\\<exists>y'. y' \\<in> ?ws' \\<and> (y', z) \\<in> (R_res (insert x rs))\\<^sup>*\"\n        proof (cases \"(y2, z) \\<in> (R_res (insert x rs))\")\n          case True with ind_hyp show ?thesis by auto\n        next\n          case False\n          hence \"(x, z) \\<in> R\" using y2_z_in_R_res unfolding R_res_def\n            by simp\n          hence \"z \\<in> ?ws'\" by simp\n          thus ?thesis by auto\n        qed\n      qed\n    qed\n\n    assume e_in_acc2: \"e \\<in> ?acc2\"\n    with ind_part show \"e \\<in> ?acc1\"\n      by (auto simp add: accessible_def)\n  qed\n\n  with x_nin_rs show \n   \"accessible_restrict R rs (insert x ws) = \n    accessible_restrict R (insert x rs) (ws \\<union> {y. (x, y) \\<in> R})\"\n    unfolding accessible_restrict_def R_res_def\n    by (simp add: accessible_insert2)\nqed\n\n\nlemmas accessible_restrict_insert =\n       accessible_restrict_insert_nin accessible_restrict_insert_in\n\nlemma accessible_restrict_union :\n  \"accessible_restrict R rs (ws \\<union> ws') = \n   (accessible_restrict R rs ws) \\<union> (accessible_restrict R rs ws')\" \n  unfolding accessible_restrict_def\n  by (auto simp add: accessible_union)\n\nlemma accessible_restrict_Union :\n  \"wss \\<noteq> {} \\<Longrightarrow>\n   accessible_restrict R rs (\\<Union> wss) = (\\<Union>ws \\<in> wss. (accessible_restrict R rs ws))\" \n  unfolding accessible_restrict_def\n  by (simp add: accessible_Union)\n\nlemma accessible_restrict_subset_ws :\n  \"ws \\<subseteq> accessible_restrict R rs ws\"\nunfolding accessible_restrict_def\nusing accessible_subset_ws [of ws]\nby fast\n\nsubsection \\<open> Define a new order \\<close>\n\ndefinition bounded_superset_rel where\n  \"bounded_superset_rel S \\<equiv>\n   {(x, y). (y \\<subset> x \\<and> x \\<subseteq> S)}\"\n\nlemma wf_bounded_superset_rel [simp] :\nfixes S :: \"'a set\"\nassumes fin_S: \"finite S\"\nshows \"wf (bounded_superset_rel S)\"\nproof -\n  have \"bounded_superset_rel S \\<subseteq> measure (\\<lambda>s. card (S - s))\"\n  proof \n    fix xy :: \"'a set \\<times> 'a set\"\n    obtain x y where xy_eq: \"xy = (x, y)\" by (cases xy, blast)\n\n    assume \"xy \\<in> bounded_superset_rel S\"\n    hence \"y \\<subset> x \\<and> x \\<subseteq> S\" unfolding bounded_superset_rel_def xy_eq\n      by simp\n    hence \"S - x \\<subset> S - y\" by auto\n\n    hence \"card (S - x) < card (S - y)\"\n      using psubset_card_mono finite_Diff fin_S\n      by metis\n    thus \"xy \\<in> measure (\\<lambda>s. card (S - s))\"\n      using xy_eq\n      by simp\n  qed\n  thus ?thesis\n    using wf_measure wf_subset\n    by metis\nqed\n\n\n\nsubsection \\<open> Implementation of Accessible \\<close>\n\ntext \\<open> Now let's implement the algorithm using lists \\<close>\n\ndefinition accessible_worklist_invar where\n\"accessible_worklist_invar exit R rs S \\<equiv> (\\<lambda>s. \n(rs \\<subseteq> snd (fst s)) \\<and>\n(fst (fst s) = (\\<exists>e \\<in> (snd (fst s) - rs). exit e)) \\<and>\n(S = accessible_restrict R (snd (fst s)) (set (snd s))))\"\n\ndefinition accessible_worklist where\n  \"accessible_worklist exit R rs wl =\n   WORKLISTIT (accessible_worklist_invar exit R rs (accessible_restrict R rs (set wl))) \n    (\\<lambda>s. \\<not> (fst s))\n    (\\<lambda>s e. \n       if (e \\<in> snd s) then\n         (RETURN (s, []))\n       else                    \n         do {\n           N \\<leftarrow> SPEC (\\<lambda>wl. set wl = {y. (e,y) \\<in> R});\n           RETURN ((exit e, insert e (snd s)), N)\n         }\n     ) ((False, rs), wl)\"\n\nlemma accessible_worklist_thm :\nfixes R :: \"('e \\<times> 'e) set\" and rs wl\ndefines \"S \\<equiv> (accessible_restrict R rs (set wl))\"\nassumes fin_S: \"finite S\"\nshows \"accessible_worklist exit R rs wl \\<le>\n       SPEC (\\<lambda>((ex, rs'), wl'). \n            (accessible_restrict R rs' (set wl') = S) \\<and>\n            (ex \\<longleftrightarrow> (\\<exists>e \\<in> rs'-rs. exit e)) \\<and> (\\<not>ex \\<longrightarrow> wl' = []))\"\nunfolding accessible_worklist_def S_def[symmetric]\nproof (rule WORKLISTIT_rule [where R = \"inv_image (bounded_superset_rel S) snd\"])\n  show \"accessible_worklist_invar exit R rs S ((False, rs), wl)\"\n    unfolding accessible_worklist_invar_def S_def\n    by simp\nnext\n  show \"wf (inv_image (bounded_superset_rel S) snd)\"\n    using fin_S wf_bounded_superset_rel by simp\nnext\n  fix s\n  assume invar: \"accessible_worklist_invar exit R rs S (s, [])\"\n  obtain ex rs' where s_eq[simp]: \"s = (ex, rs')\" by fastforce\n\n  from invar\n  show \"(\\<lambda>((ex, rs'), wl').\n            accessible_restrict R rs' (set wl') = S \\<and>\n            ex = (\\<exists>e\\<in>rs' - rs. exit e) \\<and> (\\<not> ex \\<longrightarrow> wl' = []))\n         (s, [])\"\n    unfolding accessible_worklist_invar_def\n    by simp\nnext\n  fix s wl\n  assume invar: \"accessible_worklist_invar exit R rs S (s, wl)\"\n  assume \"\\<not> (\\<not> fst s)\"\n  obtain ex rs' where s_eq[simp]: \"s = (ex, rs')\" by fastforce\n\n  from `\\<not>(\\<not> fst s)` have \"ex = True\" by simp\n\n  with invar show \"(\\<lambda>((ex, rs'), wl').\n           accessible_restrict R rs' (set wl') = S \\<and>\n           ex = (\\<exists>e\\<in>rs' - rs. exit e) \\<and> (\\<not> ex \\<longrightarrow> wl' = []))\n        (s, wl)\" \n    unfolding accessible_worklist_invar_def\n    by simp\nnext\n  fix s wl e\n  assume invar: \"accessible_worklist_invar exit R rs S (s, e # wl)\"\n  assume \"(\\<not> fst s)\"\n  obtain ex rs' where s_eq[simp]: \"s = (ex, rs')\" by fastforce\n\n  from `\\<not>(fst s)` have not_ex: \"ex = False\" by simp\n\n  show \"(if e \\<in> snd s then RETURN (s, [])\n        else SPEC (\\<lambda>wl. set wl = {y. (e, y) \\<in> R}) \\<bind>\n             (\\<lambda>N. RETURN ((exit e, insert e (snd s)), N))) \\<le> SPEC\n          (\\<lambda>s'N.\n              accessible_worklist_invar exit R rs S\n               (fst s'N, snd s'N @ wl) \\<and>\n              ((fst s'N, s) \\<in> inv_image (bounded_superset_rel S) snd \\<or>\n               s'N = (s, [])))\"\n  proof (cases \"e \\<in> rs'\")\n    case True note e_in_rs' = this\n    with invar have\n      \"accessible_worklist_invar exit R rs S ((ex, rs'), wl)\" \n      unfolding accessible_worklist_invar_def workbag_update_def\n      by (simp add: accessible_restrict_insert_in)\n    with e_in_rs' show ?thesis by simp\n  next\n    case False note e_nin_rs' = this\n\n    have \"S = accessible_restrict R rs' (set (e # wl))\" using invar\n      unfolding accessible_worklist_invar_def by simp\n    moreover\n    have \"rs' \\<subset> insert e rs'\" using e_nin_rs' by auto\n    moreover\n    have \"rs' \\<subseteq> accessible_restrict R rs' (set (e # wl))\" by (simp add: accessible_restrict_def)\n    moreover\n    have \"e \\<in> accessible_restrict R rs' (set (e # wl))\"\n      using accessible_restrict_subset_ws [of \"set (e # wl)\" R rs'] \n      by (simp add: subset_iff)\n    ultimately have in_R: \"(insert e rs', rs') \\<in> bounded_superset_rel S\"\n      unfolding bounded_superset_rel_def\n      by simp\n\n    { fix N\n      assume N_eq: \"set N = {y. (e, y) \\<in> R}\"\n\n      with invar\n      have \"accessible_worklist_invar exit R rs S\n            ((exit e, insert e rs'), N @ wl)\" \n        unfolding accessible_worklist_invar_def workbag_update_def\n        apply (simp add: accessible_restrict_insert_nin e_nin_rs' Bex_def not_ex subset_iff)\n        apply (metis e_nin_rs' Un_commute)\n      done\n    } note invar' = this\n\n    from e_nin_rs' in_R invar'\n    show ?thesis \n      by (simp add: subset_iff image_iff pw_le_iff refine_pw_simps)\n  qed\nqed\n\nend\n", "meta": {"author": "VTrelat", "repo": "Hopcroft_verif", "sha": "ede77c3a2105fd6722cf96896a297db294edf269", "save_path": "github-repos/isabelle/VTrelat-Hopcroft_verif", "path": "github-repos/isabelle/VTrelat-Hopcroft_verif/Hopcroft_verif-ede77c3a2105fd6722cf96896a297db294edf269/Isabelle/Accessible.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7590479484710341}}
{"text": "(*  Title:      HOL/Computational_Algebra/Fraction_Field.thy\n    Author:     Amine Chaieb, University of Cambridge\n*)\n\nsection\\<open>A formalization of the fraction field of any integral domain;\n         generalization of theory Rat from int to any integral domain\\<close>\n\ntheory Fraction_Field\nimports Main\nbegin\n\nsubsection \\<open>General fractions construction\\<close>\n\nsubsubsection \\<open>Construction of the type of fractions\\<close>\n\ncontext idom begin\n\ndefinition fractrel :: \"'a \\<times> 'a \\<Rightarrow> 'a * 'a \\<Rightarrow> bool\" where\n  \"fractrel = (\\<lambda>x y. snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0 \\<and> fst x * snd y = fst y * snd x)\"\n\nlemma fractrel_iff [simp]:\n  \"fractrel x y \\<longleftrightarrow> snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0 \\<and> fst x * snd y = fst y * snd x\"\n  by (simp add: fractrel_def)\n\nlemma symp_fractrel: \"symp fractrel\"\n  by (simp add: symp_def)\n\nlemma transp_fractrel: \"transp fractrel\"\nproof (rule transpI, unfold split_paired_all)\n  fix a b a' b' a'' b'' :: 'a\n  assume A: \"fractrel (a, b) (a', b')\"\n  assume B: \"fractrel (a', b') (a'', b'')\"\n  have \"b' * (a * b'') = b'' * (a * b')\" by (simp add: ac_simps)\n  also from A have \"a * b' = a' * b\" by auto\n  also have \"b'' * (a' * b) = b * (a' * b'')\" by (simp add: ac_simps)\n  also from B have \"a' * b'' = a'' * b'\" by auto\n  also have \"b * (a'' * b') = b' * (a'' * b)\" by (simp add: ac_simps)\n  finally have \"b' * (a * b'') = b' * (a'' * b)\" .\n  moreover from B have \"b' \\<noteq> 0\" by auto\n  ultimately have \"a * b'' = a'' * b\" by simp\n  with A B show \"fractrel (a, b) (a'', b'')\" by auto\nqed\n\nlemma part_equivp_fractrel: \"part_equivp fractrel\"\nusing _ symp_fractrel transp_fractrel\nby(rule part_equivpI)(rule exI[where x=\"(0, 1)\"]; simp)\n\nend\n\nquotient_type (overloaded) 'a fract = \"'a :: idom \\<times> 'a\" / partial: \"fractrel\"\nby(rule part_equivp_fractrel)\n\nsubsubsection \\<open>Representation and basic operations\\<close>\n\nlift_definition Fract :: \"'a :: idom \\<Rightarrow> 'a \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>a b. if b = 0 then (0, 1) else (a, b)\"\n  by simp\n\nlemma Fract_cases [cases type: fract]:\n  obtains (Fract) a b where \"q = Fract a b\" \"b \\<noteq> 0\"\nby transfer simp\n\nlemma Fract_induct [case_names Fract, induct type: fract]:\n  \"(\\<And>a b. b \\<noteq> 0 \\<Longrightarrow> P (Fract a b)) \\<Longrightarrow> P q\"\n  by (cases q) simp\n\nlemma eq_fract:\n  shows \"\\<And>a b c d. b \\<noteq> 0 \\<Longrightarrow> d \\<noteq> 0 \\<Longrightarrow> Fract a b = Fract c d \\<longleftrightarrow> a * d = c * b\"\n    and \"\\<And>a. Fract a 0 = Fract 0 1\"\n    and \"\\<And>a c. Fract 0 a = Fract 0 c\"\nby(transfer; simp)+\n\ninstantiation fract :: (idom) comm_ring_1\nbegin\n\nlift_definition zero_fract :: \"'a fract\" is \"(0, 1)\" by simp\n\nlemma Zero_fract_def: \"0 = Fract 0 1\"\nby transfer simp\n\nlift_definition one_fract :: \"'a fract\" is \"(1, 1)\" by simp\n\nlemma One_fract_def: \"1 = Fract 1 1\"\nby transfer simp\n\nlift_definition plus_fract :: \"'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>q r. (fst q * snd r + fst r * snd q, snd q * snd r)\"\nby(auto simp add: algebra_simps)\n\nlemma add_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b + Fract c d = Fract (a * d + c * b) (b * d)\"\nby transfer simp\n\nlift_definition uminus_fract :: \"'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>x. (- fst x, snd x)\"\nby simp\n\nlemma minus_fract [simp]:\n  fixes a b :: \"'a::idom\"\n  shows \"- Fract a b = Fract (- a) b\"\nby transfer simp\n\nlemma minus_fract_cancel [simp]: \"Fract (- a) (- b) = Fract a b\"\n  by (cases \"b = 0\") (simp_all add: eq_fract)\n\ndefinition diff_fract_def: \"q - r = q + - (r::'a fract)\"\n\nlemma diff_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b - Fract c d = Fract (a * d - c * b) (b * d)\"\n  by (simp add: diff_fract_def)\n\nlift_definition times_fract :: \"'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>q r. (fst q * fst r, snd q * snd r)\"\nby(simp add: algebra_simps)\n\nlemma mult_fract [simp]: \"Fract (a::'a::idom) b * Fract c d = Fract (a * c) (b * d)\"\nby transfer simp\n\nlemma mult_fract_cancel:\n  \"c \\<noteq> 0 \\<Longrightarrow> Fract (c * a) (c * b) = Fract a b\"\nby transfer simp\n\ninstance\nproof\n  fix q r s :: \"'a fract\"\n  show \"(q * r) * s = q * (r * s)\"\n    by (cases q, cases r, cases s) (simp add: eq_fract algebra_simps)\n  show \"q * r = r * q\"\n    by (cases q, cases r) (simp add: eq_fract algebra_simps)\n  show \"1 * q = q\"\n    by (cases q) (simp add: One_fract_def eq_fract)\n  show \"(q + r) + s = q + (r + s)\"\n    by (cases q, cases r, cases s) (simp add: eq_fract algebra_simps)\n  show \"q + r = r + q\"\n    by (cases q, cases r) (simp add: eq_fract algebra_simps)\n  show \"0 + q = q\"\n    by (cases q) (simp add: Zero_fract_def eq_fract)\n  show \"- q + q = 0\"\n    by (cases q) (simp add: Zero_fract_def eq_fract)\n  show \"q - r = q + - r\"\n    by (cases q, cases r) (simp add: eq_fract)\n  show \"(q + r) * s = q * s + r * s\"\n    by (cases q, cases r, cases s) (simp add: eq_fract algebra_simps)\n  show \"(0::'a fract) \\<noteq> 1\"\n    by (simp add: Zero_fract_def One_fract_def eq_fract)\nqed\n\nend\n\nlemma of_nat_fract: \"of_nat k = Fract (of_nat k) 1\"\n  by (induct k) (simp_all add: Zero_fract_def One_fract_def)\n\nlemma Fract_of_nat_eq: \"Fract (of_nat k) 1 = of_nat k\"\n  by (rule of_nat_fract [symmetric])\n\nlemma fract_collapse:\n  \"Fract 0 k = 0\"\n  \"Fract 1 1 = 1\"\n  \"Fract k 0 = 0\"\nby(transfer; simp)+\n\nlemma fract_expand:\n  \"0 = Fract 0 1\"\n  \"1 = Fract 1 1\"\n  by (simp_all add: fract_collapse)\n\nlemma Fract_cases_nonzero:\n  obtains (Fract) a b where \"q = Fract a b\" and \"b \\<noteq> 0\" and \"a \\<noteq> 0\"\n    | (0) \"q = 0\"\nproof (cases \"q = 0\")\n  case True\n  then show thesis using 0 by auto\nnext\n  case False\n  then obtain a b where \"q = Fract a b\" and \"b \\<noteq> 0\" by (cases q) auto\n  with False have \"0 \\<noteq> Fract a b\" by simp\n  with \\<open>b \\<noteq> 0\\<close> have \"a \\<noteq> 0\" by (simp add: Zero_fract_def eq_fract)\n  with Fract \\<open>q = Fract a b\\<close> \\<open>b \\<noteq> 0\\<close> show thesis by auto\nqed\n\n\nsubsubsection \\<open>The field of rational numbers\\<close>\n\ncontext idom\nbegin\n\nsubclass ring_no_zero_divisors ..\n\nend\n\ninstantiation fract :: (idom) field\nbegin\n\nlift_definition inverse_fract :: \"'a fract \\<Rightarrow> 'a fract\"\n  is \"\\<lambda>x. if fst x = 0 then (0, 1) else (snd x, fst x)\"\nby(auto simp add: algebra_simps)\n\nlemma inverse_fract [simp]: \"inverse (Fract a b) = Fract (b::'a::idom) a\"\nby transfer simp\n\ndefinition divide_fract_def: \"q div r = q * inverse (r:: 'a fract)\"\n\nlemma divide_fract [simp]: \"Fract a b div Fract c d = Fract (a * d) (b * c)\"\n  by (simp add: divide_fract_def)\n\ninstance\nproof\n  fix q :: \"'a fract\"\n  assume \"q \\<noteq> 0\"\n  then show \"inverse q * q = 1\"\n    by (cases q rule: Fract_cases_nonzero)\n      (simp_all add: fract_expand eq_fract mult.commute)\nnext\n  fix q r :: \"'a fract\"\n  show \"q div r = q * inverse r\" by (simp add: divide_fract_def)\nnext\n  show \"inverse 0 = (0:: 'a fract)\"\n    by (simp add: fract_expand) (simp add: fract_collapse)\nqed\n\nend\n\n\nsubsubsection \\<open>The ordered field of fractions over an ordered idom\\<close>\n\ninstantiation fract :: (linordered_idom) linorder\nbegin\n\nlemma less_eq_fract_respect:\n  fixes a b a' b' c d c' d' :: 'a\n  assumes neq: \"b \\<noteq> 0\"  \"b' \\<noteq> 0\"  \"d \\<noteq> 0\"  \"d' \\<noteq> 0\"\n  assumes eq1: \"a * b' = a' * b\"\n  assumes eq2: \"c * d' = c' * d\"\n  shows \"((a * d) * (b * d) \\<le> (c * b) * (b * d)) \\<longleftrightarrow> ((a' * d') * (b' * d') \\<le> (c' * b') * (b' * d'))\"\nproof -\n  let ?le = \"\\<lambda>a b c d. ((a * d) * (b * d) \\<le> (c * b) * (b * d))\"\n  {\n    fix a b c d x :: 'a\n    assume x: \"x \\<noteq> 0\"\n    have \"?le a b c d = ?le (a * x) (b * x) c d\"\n    proof -\n      from x have \"0 < x * x\"\n        by (auto simp add: zero_less_mult_iff)\n      then have \"?le a b c d =\n          ((a * d) * (b * d) * (x * x) \\<le> (c * b) * (b * d) * (x * x))\"\n        by (simp add: mult_le_cancel_right)\n      also have \"... = ?le (a * x) (b * x) c d\"\n        by (simp add: ac_simps)\n      finally show ?thesis .\n    qed\n  } note le_factor = this\n\n  let ?D = \"b * d\" and ?D' = \"b' * d'\"\n  from neq have D: \"?D \\<noteq> 0\" by simp\n  from neq have \"?D' \\<noteq> 0\" by simp\n  then have \"?le a b c d = ?le (a * ?D') (b * ?D') c d\"\n    by (rule le_factor)\n  also have \"... = ((a * b') * ?D * ?D' * d * d' \\<le> (c * d') * ?D * ?D' * b * b')\"\n    by (simp add: ac_simps)\n  also have \"... = ((a' * b) * ?D * ?D' * d * d' \\<le> (c' * d) * ?D * ?D' * b * b')\"\n    by (simp only: eq1 eq2)\n  also have \"... = ?le (a' * ?D) (b' * ?D) c' d'\"\n    by (simp add: ac_simps)\n  also from D have \"... = ?le a' b' c' d'\"\n    by (rule le_factor [symmetric])\n  finally show \"?le a b c d = ?le a' b' c' d'\" .\nqed\n\nlift_definition less_eq_fract :: \"'a fract \\<Rightarrow> 'a fract \\<Rightarrow> bool\"\n  is \"\\<lambda>q r. (fst q * snd r) * (snd q * snd r) \\<le> (fst r * snd q) * (snd q * snd r)\"\nby (clarsimp simp add: less_eq_fract_respect)\n\ndefinition less_fract_def: \"z < (w::'a fract) \\<longleftrightarrow> z \\<le> w \\<and> \\<not> w \\<le> z\"\n\nlemma le_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b \\<le> Fract c d \\<longleftrightarrow> (a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n  by transfer simp\n\nlemma less_fract [simp]:\n  \"\\<lbrakk> b \\<noteq> 0; d \\<noteq> 0 \\<rbrakk> \\<Longrightarrow> Fract a b < Fract c d \\<longleftrightarrow> (a * d) * (b * d) < (c * b) * (b * d)\"\n  by (simp add: less_fract_def less_le_not_le ac_simps)\n\ninstance\nproof\n  fix q r s :: \"'a fract\"\n  assume \"q \\<le> r\" and \"r \\<le> s\"\n  then show \"q \\<le> s\"\n  proof (induct q, induct r, induct s)\n    fix a b c d e f :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\" \"f \\<noteq> 0\"\n    assume 1: \"Fract a b \\<le> Fract c d\"\n    assume 2: \"Fract c d \\<le> Fract e f\"\n    show \"Fract a b \\<le> Fract e f\"\n    proof -\n      from neq obtain bb: \"0 < b * b\" and dd: \"0 < d * d\" and ff: \"0 < f * f\"\n        by (auto simp add: zero_less_mult_iff linorder_neq_iff)\n      have \"(a * d) * (b * d) * (f * f) \\<le> (c * b) * (b * d) * (f * f)\"\n      proof -\n        from neq 1 have \"(a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n          by simp\n        with ff show ?thesis by (simp add: mult_le_cancel_right)\n      qed\n      also have \"... = (c * f) * (d * f) * (b * b)\"\n        by (simp only: ac_simps)\n      also have \"... \\<le> (e * d) * (d * f) * (b * b)\"\n      proof -\n        from neq 2 have \"(c * f) * (d * f) \\<le> (e * d) * (d * f)\"\n          by simp\n        with bb show ?thesis by (simp add: mult_le_cancel_right)\n      qed\n      finally have \"(a * f) * (b * f) * (d * d) \\<le> e * b * (b * f) * (d * d)\"\n        by (simp only: ac_simps)\n      with dd have \"(a * f) * (b * f) \\<le> (e * b) * (b * f)\"\n        by (simp add: mult_le_cancel_right)\n      with neq show ?thesis by simp\n    qed\n  qed\nnext\n  fix q r :: \"'a fract\"\n  assume \"q \\<le> r\" and \"r \\<le> q\"\n  then show \"q = r\"\n  proof (induct q, induct r)\n    fix a b c d :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\"\n    assume 1: \"Fract a b \\<le> Fract c d\"\n    assume 2: \"Fract c d \\<le> Fract a b\"\n    show \"Fract a b = Fract c d\"\n    proof -\n      from neq 1 have \"(a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n        by simp\n      also have \"... \\<le> (a * d) * (b * d)\"\n      proof -\n        from neq 2 have \"(c * b) * (d * b) \\<le> (a * d) * (d * b)\"\n          by simp\n        then show ?thesis by (simp only: ac_simps)\n      qed\n      finally have \"(a * d) * (b * d) = (c * b) * (b * d)\" .\n      moreover from neq have \"b * d \\<noteq> 0\" by simp\n      ultimately have \"a * d = c * b\" by simp\n      with neq show ?thesis by (simp add: eq_fract)\n    qed\n  qed\nnext\n  fix q r :: \"'a fract\"\n  show \"q \\<le> q\"\n    by (induct q) simp\n  show \"(q < r) = (q \\<le> r \\<and> \\<not> r \\<le> q)\"\n    by (simp only: less_fract_def)\n  show \"q \\<le> r \\<or> r \\<le> q\"\n    by (induct q, induct r)\n       (simp add: mult.commute, rule linorder_linear)\nqed\n\nend\n\ninstantiation fract :: (linordered_idom) linordered_field\nbegin\n\ndefinition abs_fract_def2:\n  \"\\<bar>q\\<bar> = (if q < 0 then -q else (q::'a fract))\"\n\ndefinition sgn_fract_def:\n  \"sgn (q::'a fract) = (if q = 0 then 0 else if 0 < q then 1 else - 1)\"\n\ntheorem abs_fract [simp]: \"\\<bar>Fract a b\\<bar> = Fract \\<bar>a\\<bar> \\<bar>b\\<bar>\"\n  unfolding abs_fract_def2 not_le [symmetric]\n  by transfer (auto simp add: zero_less_mult_iff le_less)\n\ninstance proof\n  fix q r s :: \"'a fract\"\n  assume \"q \\<le> r\"\n  then show \"s + q \\<le> s + r\"\n  proof (induct q, induct r, induct s)\n    fix a b c d e f :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\" \"f \\<noteq> 0\"\n    assume le: \"Fract a b \\<le> Fract c d\"\n    show \"Fract e f + Fract a b \\<le> Fract e f + Fract c d\"\n    proof -\n      let ?F = \"f * f\" from neq have F: \"0 < ?F\"\n        by (auto simp add: zero_less_mult_iff)\n      from neq le have \"(a * d) * (b * d) \\<le> (c * b) * (b * d)\"\n        by simp\n      with F have \"(a * d) * (b * d) * ?F * ?F \\<le> (c * b) * (b * d) * ?F * ?F\"\n        by (simp add: mult_le_cancel_right)\n      with neq show ?thesis by (simp add: field_simps)\n    qed\n  qed\nnext\n  fix q r s :: \"'a fract\"\n  assume \"q < r\" and \"0 < s\"\n  then show \"s * q < s * r\"\n  proof (induct q, induct r, induct s)\n    fix a b c d e f :: 'a\n    assume neq: \"b \\<noteq> 0\" \"d \\<noteq> 0\" \"f \\<noteq> 0\"\n    assume le: \"Fract a b < Fract c d\"\n    assume gt: \"0 < Fract e f\"\n    show \"Fract e f * Fract a b < Fract e f * Fract c d\"\n    proof -\n      let ?E = \"e * f\" and ?F = \"f * f\"\n      from neq gt have \"0 < ?E\"\n        by (auto simp add: Zero_fract_def order_less_le eq_fract)\n      moreover from neq have \"0 < ?F\"\n        by (auto simp add: zero_less_mult_iff)\n      moreover from neq le have \"(a * d) * (b * d) < (c * b) * (b * d)\"\n        by simp\n      ultimately have \"(a * d) * (b * d) * ?E * ?F < (c * b) * (b * d) * ?E * ?F\"\n        by (simp add: mult_less_cancel_right)\n      with neq show ?thesis\n        by (simp add: ac_simps)\n    qed\n  qed\nqed (fact sgn_fract_def abs_fract_def2)+\n\nend\n\ninstantiation fract :: (linordered_idom) distrib_lattice\nbegin\n\ndefinition inf_fract_def:\n  \"(inf :: 'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract) = min\"\n\ndefinition sup_fract_def:\n  \"(sup :: 'a fract \\<Rightarrow> 'a fract \\<Rightarrow> 'a fract) = max\"\n\ninstance\n  by standard (simp_all add: inf_fract_def sup_fract_def max_min_distrib2)\n  \nend\n\nlemma fract_induct_pos [case_names Fract]:\n  fixes P :: \"'a::linordered_idom fract \\<Rightarrow> bool\"\n  assumes step: \"\\<And>a b. 0 < b \\<Longrightarrow> P (Fract a b)\"\n  shows \"P q\"\nproof (cases q)\n  case (Fract a b)\n  {\n    fix a b :: 'a\n    assume b: \"b < 0\"\n    have \"P (Fract a b)\"\n    proof -\n      from b have \"0 < - b\" by simp\n      then have \"P (Fract (- a) (- b))\"\n        by (rule step)\n      then show \"P (Fract a b)\"\n        by (simp add: order_less_imp_not_eq [OF b])\n    qed\n  }\n  with Fract show \"P q\"\n    by (auto simp add: linorder_neq_iff step)\nqed\n\nlemma zero_less_Fract_iff: \"0 < b \\<Longrightarrow> 0 < Fract a b \\<longleftrightarrow> 0 < a\"\n  by (auto simp add: Zero_fract_def zero_less_mult_iff)\n\nlemma Fract_less_zero_iff: \"0 < b \\<Longrightarrow> Fract a b < 0 \\<longleftrightarrow> a < 0\"\n  by (auto simp add: Zero_fract_def mult_less_0_iff)\n\nlemma zero_le_Fract_iff: \"0 < b \\<Longrightarrow> 0 \\<le> Fract a b \\<longleftrightarrow> 0 \\<le> a\"\n  by (auto simp add: Zero_fract_def zero_le_mult_iff)\n\nlemma Fract_le_zero_iff: \"0 < b \\<Longrightarrow> Fract a b \\<le> 0 \\<longleftrightarrow> a \\<le> 0\"\n  by (auto simp add: Zero_fract_def mult_le_0_iff)\n\nlemma one_less_Fract_iff: \"0 < b \\<Longrightarrow> 1 < Fract a b \\<longleftrightarrow> b < a\"\n  by (auto simp add: One_fract_def mult_less_cancel_right_disj)\n\nlemma Fract_less_one_iff: \"0 < b \\<Longrightarrow> Fract a b < 1 \\<longleftrightarrow> a < b\"\n  by (auto simp add: One_fract_def mult_less_cancel_right_disj)\n\nlemma one_le_Fract_iff: \"0 < b \\<Longrightarrow> 1 \\<le> Fract a b \\<longleftrightarrow> b \\<le> a\"\n  by (auto simp add: One_fract_def mult_le_cancel_right)\n\nlemma Fract_le_one_iff: \"0 < b \\<Longrightarrow> Fract a b \\<le> 1 \\<longleftrightarrow> a \\<le> b\"\n  by (auto simp add: One_fract_def mult_le_cancel_right)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Computational_Algebra/Fraction_Field.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423873, "lm_q2_score": 0.8633916047011594, "lm_q1q2_score": 0.759047943835626}}
{"text": "(* Title:      Relation Algebra\n   Author:     Alasdair Armstrong, Simon Foster, Georg Struth, Tjark Weber\n   Maintainer: Georg Struth <g.struth at sheffield.ac.uk>\n               Tjark Weber <tjark.weber at it.uu.se>\n*)\n\nsection \\<open>(More) Boolean Algebra\\<close>\n\ntheory More_Boolean_Algebra\n  imports Main\nbegin\n\nsubsection \\<open>Laws of Boolean Algebra\\<close>\n\ntext \\<open>The following laws of Boolean algebra support relational proofs. We\nmight add laws for the binary minus since that would make certain theorems look\nmore nicely. These are currently not so well supported.\\<close>\n\ncontext boolean_algebra\nbegin\n\nno_notation\n  times (infixl \"\\<cdot>\" 70)\n  and plus (infixl \"+\" 65)\n  and Groups.zero_class.zero (\"0\")\n  and Groups.one_class.one (\"1\")\n\nnotation\n  inf (infixl \"\\<cdot>\" 70)\n  and sup (infixl \"+\" 65)\n  and bot (\"0\")\n  and top (\"1\")\n\nlemma meet_assoc: \"x \\<cdot> (y \\<cdot> z) = (x \\<cdot> y) \\<cdot> z\"\nby (metis inf_assoc)\n\nlemma aux4 [simp]: \"x \\<cdot> y + x \\<cdot> -y = x\"\nby (metis inf_sup_distrib1 inf_top_right sup_compl_top)\n\nlemma aux4_comm [simp]: \"x \\<cdot> -y + x \\<cdot> y = x\"\nby (metis aux4 sup.commute)\n\nlemma aux6 [simp]: \"(x + y) \\<cdot> -x = y \\<cdot> -x\"\nby (metis inf_compl_bot inf_sup_distrib2 sup_bot_left)\n\nlemma aux6_var [simp]: \"(-x + y) \\<cdot> x = x \\<cdot> y\"\nby (metis compl_inf_bot inf_commute inf_sup_distrib2 sup_bot_left)\n\nlemma aux9 [simp]: \"x + -x \\<cdot> y = x + y\"\nby (metis aux4 aux6 inf.commute inf_sup_absorb)\n\nlemma join_iso: \"x \\<le> y \\<Longrightarrow> x + z \\<le> y + z\"\nby (metis eq_refl sup_mono)\n\nlemma join_isol: \"x \\<le> y \\<Longrightarrow> z + x \\<le> z + y\"\nby (metis join_iso sup.commute)\n\nlemma join_double_iso: \"x \\<le> y \\<Longrightarrow> w + x + z \\<le> w + y + z\"\nby (metis le_iff_inf sup_inf_distrib1 sup_inf_distrib2)\n\nlemma comp_anti: \"x \\<le> y \\<longleftrightarrow> -y \\<le> -x\"\nby (metis compl_le_swap2 double_compl)\n\nlemma meet_iso: \"x \\<le> y \\<Longrightarrow> x \\<cdot> z \\<le> y \\<cdot> z\"\nby (metis eq_refl inf_mono)\n\nlemma meet_isor: \"x \\<le> y \\<Longrightarrow> z \\<cdot> x \\<le> z \\<cdot> y\"\nby (metis inf.commute meet_iso)\n\nlemma meet_double_iso: \"x \\<le> y \\<Longrightarrow> w \\<cdot> x \\<cdot> z \\<le> w \\<cdot> y \\<cdot> z\"\nby (metis meet_iso meet_isor)\n\nlemma de_morgan_3 [simp]: \"-(-x \\<cdot> -y) = x + y\"\nby (metis compl_sup double_compl)\n\nlemma subdist_2_var: \"x + y \\<cdot> z \\<le> x + y\"\nby (metis eq_refl inf_le1 sup_mono)\n\nlemma dist_alt: \"\\<lbrakk>x + z = y + z; x \\<cdot> z = y \\<cdot> z\\<rbrakk> \\<Longrightarrow> x = y\"\nby (metis aux4 aux6 sup.commute)\n\ntext \\<open>Finally we prove the Galois connections for complementation.\\<close>\n\nlemma galois_aux: \"x \\<cdot> y = 0 \\<longleftrightarrow> x \\<le> -y\"\nby (metis aux6 compl_sup double_compl inf.commute le_iff_inf sup_bot_right sup_compl_top)\n\nlemma galois_aux2: \"x \\<cdot> -y = 0 \\<longleftrightarrow> x \\<le> y\"\nby (metis double_compl galois_aux)\n\nlemma galois_1: \"x \\<cdot> -y \\<le> z \\<longleftrightarrow> x \\<le> y + z\"\napply (rule iffI)\n apply (metis inf_le2 join_iso le_iff_sup le_supE join_isol aux4)\napply (metis meet_iso aux6 le_infE)\ndone\n\n\n\nlemma galois_aux3: \"x + y = 1 \\<longleftrightarrow> -x \\<le> y\"\nby (metis galois_1 inf_top_left top_unique)\n\nlemma galois_aux4: \"-x + y = 1 \\<longleftrightarrow> x \\<le> y\"\nby (metis double_compl galois_aux3)\n\nsubsection \\<open>Boolean Algebras with Operators\\<close>\n\ntext \\<open>We follow J\\'onsson and Tarski to define pairs of conjugate functions\non Boolean algebras. We also consider material from Maddux's article. This\ngives rise to a Galois connection and the notion of Boolean algebras with\noperators.\n\nWe do not explicitly define families of functions over Boolean algebras as a\ntype class.\n\nThis development should certainly be expanded do deal with complete Boolean\nalgebras one the one hand and other lattices on the other hand.\n\nBoolean algebras with operators and their variants can be applied in various\nways. The prime example are relation algebras. The modular laws, for instance,\ncan be derived by instantiation. Other applications are antidomain semirings\nwhere modal operators satisfy conjugations and Galois connections, and algebras\nof predicate transformers.\\<close>\n\ntext\\<open>We define conjugation as a predicate which holds if a pair of functions\nare conjugates.\\<close>\n\ndefinition is_conjugation :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"is_conjugation f g \\<equiv> (\\<forall>x y . f x \\<cdot> y = 0 \\<longleftrightarrow> x \\<cdot> g y = 0)\"\n\ntext \\<open>We now prove the standard lemmas. First we show that conjugation is\nsymmetric and that conjugates are uniqely defined.\\<close>\n\nlemma is_conjugation_sym: \"is_conjugation f g \\<longleftrightarrow> is_conjugation g f\"\nby (metis inf.commute is_conjugation_def)\n\n\n\ntext \\<open>Next we show that conjugates give rise to adjoints in a Galois\nconnection.\\<close>\n\nlemma conj_galois_1:\n  assumes \"is_conjugation f g\"\n  shows \"f x \\<le> y \\<longleftrightarrow> x \\<le> -g (-y)\"\nby (metis assms is_conjugation_def double_compl galois_aux)\n\nlemma conj_galois_2:\n  assumes \"is_conjugation f g\"\n  shows \"g x \\<le> y \\<longleftrightarrow> x \\<le> -f (-y)\"\nby (metis assms is_conjugation_sym conj_galois_1)\n\ntext \\<open>Now we prove some of the standard properties of adjoints and\nconjugates. In fact, conjugate functions even distribute over all existing\nsuprema. We display the next proof in detail because it is elegant.\\<close>\n\nlemma f_pre_additive:\n  assumes \"is_conjugation f g\"\n  shows \"f (x + y) \\<le> z \\<longleftrightarrow> f x + f y \\<le> z\"\nproof -\n  have \"f (x + y) \\<le> z \\<longleftrightarrow> x + y \\<le> -g (-z)\"\n    by (metis assms conj_galois_1)\n  also have \"... \\<longleftrightarrow> x \\<le> -g (-z) \\<and> y \\<le> -g (-z)\"\n    by (metis le_sup_iff)\n  also have \"... \\<longleftrightarrow> f x \\<le> z \\<and> f y \\<le> z\"\n    by (metis assms conj_galois_1)\n  thus ?thesis\n    by (metis le_sup_iff calculation)\nqed\n\nlemma f_additive:\n  assumes \"is_conjugation f g\"\n  shows \"f (sup x y) = sup (f x) (f y)\"\nby (metis assms eq_iff f_pre_additive)\n\nlemma g_pre_additive:\n  assumes \"is_conjugation f g\"\n  shows \"g (sup x y) \\<le> z \\<longleftrightarrow> sup (g x) (g y) \\<le> z\"\nby (metis assms is_conjugation_sym f_pre_additive)\n\nlemma g_additive:\n  assumes \"is_conjugation f g\"\n  shows \"g (sup x y) = sup (g x) (g y)\"\nby (metis assms is_conjugation_sym f_additive)\n\ntext \\<open>Additivity of adjoints obviously implies their isotonicity.\\<close>\n\nlemma f_iso:\n  assumes \"is_conjugation f g\"\n  shows \"x \\<le> y \\<longrightarrow> f x \\<le> f y\"\nby (metis assms f_additive le_iff_sup)\n\nlemma g_iso:\n  assumes \"is_conjugation f g\"\n  shows \"x \\<le> y \\<longrightarrow> g x \\<le> g y\"\nby (metis assms is_conjugation_sym f_iso)\n\nlemma f_subdist:\n  assumes \"is_conjugation f g\"\n  shows \"f (x \\<cdot> y) \\<le> f x\"\nby (metis assms f_iso inf_le1)\n\nlemma g_subdist:\n  assumes \"is_conjugation f g\"\n  shows \"g (x \\<cdot> y) \\<le> g x\"\nby (metis assms g_iso inf_le1)\n\ntext \\<open>Next we prove cancellation and strictness laws.\\<close>\n\nlemma cancellation_1:\n  assumes \"is_conjugation f g\"\n  shows \"f (-g x) \\<le> -x\"\nby (metis assms conj_galois_1 double_compl eq_refl)\n\nlemma cancellation_2:\n  assumes \"is_conjugation f g\"\n  shows \"g (-f x) \\<le> -x\"\nby (metis assms is_conjugation_sym cancellation_1)\n\nlemma f_strict:\n  assumes \"is_conjugation f g\"\n  shows \"f 0 = 0\"\nby (metis assms inf.idem inf_bot_left is_conjugation_def)\n\nlemma g_strict:\n  assumes \"is_conjugation f g\"\n  shows \"g 0 = 0\"\nby (metis assms is_conjugation_sym f_strict)\n\ntext \\<open>The following variants of modular laws have more concrete counterparts\nin relation algebra.\\<close>\n\nlemma modular_1_aux:\n  assumes \"is_conjugation f g\"\n  shows \"f (x \\<cdot> -g y) \\<cdot> y = 0\"\nby (metis assms galois_aux inf_le2 is_conjugation_def)\n\nlemma modular_2_aux:\n  assumes \"is_conjugation f g\"\n  shows \"g (x \\<cdot> -f y) \\<cdot> y = 0\"\nby (metis assms is_conjugation_sym modular_1_aux)\n\nlemma modular_1:\n  assumes \"is_conjugation f g\"\n  shows \"f x \\<cdot> y = f (x \\<cdot> g y) \\<cdot> y\"\nproof -\n  have \"f x \\<cdot> y = f (x \\<cdot> g y + x \\<cdot> -g y) \\<cdot> y\"\n    by (metis aux4)\n  hence \"f x \\<cdot> y = (f (x \\<cdot> g y) + f (x \\<cdot> -g y)) \\<cdot> y\"\n    by (metis assms f_additive)\n  hence \"f x \\<cdot> y = f (x \\<cdot> g y) \\<cdot> y + f (x \\<cdot> -g y) \\<cdot> y\"\n    by (metis inf.commute inf_sup_distrib1)\n  thus ?thesis\n    by (metis assms modular_1_aux sup_bot_right)\nqed\n\nlemma modular_2:\n  assumes \"is_conjugation f g\"\n  shows \"g x \\<cdot> y = g (x \\<cdot> f y) \\<cdot> y\"\nby (metis assms is_conjugation_sym modular_1)\n\nlemma conjugate_eq_aux:\n  \"is_conjugation f g \\<Longrightarrow> f (x \\<cdot> -g y) \\<le> f x \\<cdot> -y\"\n  by (metis f_subdist galois_aux le_inf_iff modular_1_aux)\n\nlemma conjugate_eq:\n  \"is_conjugation f g \\<longleftrightarrow> (\\<forall>x y. f (x \\<cdot> -g y) \\<le> f x \\<cdot> -y \\<and> g (y \\<cdot> -f x) \\<le> g y \\<cdot> -x)\"\n    (is \"?l \\<longleftrightarrow> ?r\")\nproof\n  assume ?l thus ?r\n    by (metis is_conjugation_sym conjugate_eq_aux)\nnext\n  assume r: ?r\n  have \"\\<forall>x y. f x \\<cdot> y = 0 \\<longrightarrow> x \\<cdot> g y = 0\"\n    by (metis aux4 inf.left_commute inf_absorb1 inf_compl_bot inf_left_idem sup_bot_left r)\n  hence \"\\<forall>x y. x \\<cdot> g y = 0 \\<longleftrightarrow> f x \\<cdot> y = 0\"\n    by (metis aux4 inf.commute inf.left_commute inf_absorb1 inf_compl_bot sup_commute sup_inf_absorb r)\n  thus \"is_conjugation f g\"\n    by (metis is_conjugation_def)\nqed\n\nlemma conjugation_prop1: \"is_conjugation f g \\<Longrightarrow> f y \\<cdot> z \\<le> f (y \\<cdot> g z)\"\nby (metis le_infE modular_1 order_refl)\n\nlemma conjugation_prop2: \"is_conjugation f g \\<Longrightarrow> g z \\<cdot> y \\<le> g (z \\<cdot> f y)\"\nby (metis is_conjugation_sym conjugation_prop1)\n\nend (* boolean_algebra *)\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Relation_Algebra/More_Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8791467722591728, "lm_q1q2_score": 0.7590479409235559}}
{"text": "header {*  Predicate Transformers Semantics of Invariant Diagrams  *}\n\ntheory Diagram\nimports Hoare\nbegin\n\ntext {*\nThis theory introduces the concept of a transition diagram and proves\na number of Hoare total corectness rules for these diagrams. As before\nthe diagrams are introduced using their predicate transformer semantics.\n\nA transition diagram $D$ is a function from pairs of indexes to predicate\ntransformers: $D:I\\times I \\to (\\mathit{State}\\ \\mathit{set}\\to \\mathit{State}\\ \\mathit{set})$, or more\ngeneral $D:I\\times I \\to \\mathit{Ptran}$, where $\\mathit{Ptran}$ is a complete lattice. The elements\nof $I$ are called situations and intuitively a diagram is executed starting\nin a situation $i\\in I$ by choosing a transition $D (i,j)$ which is enabled\nand continuing similarly from $j$ if there are enabled trasitions. The \nexecution of a diagram stops when there are no more transitions enabled or\nwhen it fails.\n\nThe semantics of a transition diagram is an indexed predicate transformer \n($I\\to \\mathit{State}\\ \\mathit{set}$).\nIf $Q:I\\to \\mathit{State}\\ \\mathit{set}$ is an indexed predicate, then $p = \\mathit{pt}\\ D\\ Q\\ i$ is a\nweakest predicate such that if the executution of $D$ starts in a state\n$s\\in p$ from situation $i$, then it terminates, and if it terminates\nin situation $j$ and state $s'$, then $s'\\in Q \\  j$.\n\nWe introduce first the indexed predicate transformer $\\mathit{step}\\ D$ of executing\none step of diagram $D$. The predicate $step\\ D\\ Q\\ i$ is true for those\nstates $s$ from which the execution of one step of $D$ starting in situation \n$i$ ends in one of the situations $j$ such that $Q \\, j$ is true.\n\n*}\n\ndefinition\n  \"step D Q i = (INF j . D (i, j) (Q j) :: _ :: complete_lattice)\"\n\ndefinition\n  \"dmono D = (\\<forall> ij . mono (D ij))\"\n\nlemma dmono_mono [simp]: \"dmono D \\<Longrightarrow> mono (D ij)\"\n  by (simp add: dmono_def)\n\ntheorem mono_step [simp]:\n  \"dmono D \\<Longrightarrow> mono (step D)\"\n  apply (simp add: dmono_def mono_def le_fun_def step_def Inf_fun_def)\n  apply auto\n  apply (rule INF_greatest)\n  apply auto\n  apply (rule_tac y = \"D(xa, j) (x j)\" in order_trans)\n  apply auto\n  apply (rule INF_lower)\n  by auto\n\ntext {*\nThe indexed predicate transformer of a transition diagram is defined as the least\nfixpoint of the unfolding of the execution of the diagram. The indexed predicate\ntransformer $dgr\\ D\\ U$ is the choice between executing one step of $D$ follwed by\n$U$ ($(\\mathit{step}\\ D)\\circ U$) or skip if no transion of $D$ is enabled \n($\\mathit{assume}\\ \\neg \\mathit{grd} (\\mathit{step}\\ D)$).\n*}\n\ndefinition\n  \"dgr D U = ((step D) o U) \\<sqinter> [.-(grd (step D)).]\"\n\ntheorem mono_mono_dgr [simp]: \"dmono D \\<Longrightarrow> mono_mono (dgr D)\"\n  apply (simp add: mono_mono_def mono_def)\n  apply safe\n  apply (simp_all add: dgr_def)\n  apply (simp_all add: le_fun_def inf_fun_def)\n  apply safe\n  apply (rule_tac y = \"(step D (x xa) xb)\" in order_trans)\n  apply simp_all\n  apply (case_tac \"mono (step D)\")\n  apply (simp add: mono_def)\n  apply (simp add: le_fun_def)\n  apply simp\n  apply (rule_tac y = \"(step D (f x) xa)\" in order_trans)\n  apply simp_all\n  apply (case_tac \"mono (step D)\")\n  apply (simp add: mono_def)\n  apply (simp_all add: le_fun_def)\n  apply (rule_tac y = \"(assume (- grd (step D)) x xa)\" in order_trans)\n  apply simp_all\n  apply (case_tac \"mono (assume (- grd (step D)))\")\n  apply (simp add: mono_def le_fun_def)\n  by simp\n\ndefinition\n  \"pt D = lfp (dgr D)\"\n\ntext {*\nIf $U$ is an indexed predicate transformer and if $P, Q:I\\to \\mathit{State} \\ \\mathit{set}$\nare indexed predicates, then the meaning of the Hoare triple defined earlier,\n$\\models P \\{ | U | \\} Q$, is that if\nwe start $U$ in a state $s$ from a situation $i$ such that $s\\in P\\, i$,\nthen U terminates, and if it terminates in $s'$ and situation $j$, then\n$s'\\in Q\\ j$ is true.\n\nNext theorem shows that in a diagram all transitions are correct\nif and only if $\\mathit{step}\\ D$ is correct.\n*}\n\ntheorem hoare_step:\n  \"(\\<forall> i j . \\<Turnstile> (P i) {| D(i,j) |} (Q j) ) = (\\<Turnstile> P {| step D |} Q)\"\n  apply safe\n  apply (simp add: le_fun_def Hoare_def step_def)\n  apply safe\n  apply (rule INF_greatest)\n  apply auto\n  apply (simp add: le_fun_def Hoare_def step_def)\n  apply (erule_tac x = i in allE)\n  apply (rule_tac y = \"INF j. D(i, j) (Q j)\" in order_trans)\n  apply auto\n  apply (rule INF_lower)\n  by auto\n\ntext {*\nNext theorem provides the first proof rule for total correctnes of transition\ndiagrams. If all transitions are correct and if a global variant decreases \non every transition then the diagram is correct and it terminates. The variant\nmust decrease according to a well founded and transitive relation.\n*}\n\ntheorem hoare_diagram:\n  \"dmono D \\<Longrightarrow> (\\<forall> w i j . \\<Turnstile> X w i  {| D(i,j) |} Sup_less X w j) \\<Longrightarrow> \n    \\<Turnstile> (Sup (range X)) {| pt D |} (Sup(range X) \\<sqinter> -(grd (step D)))\"\n  apply (simp add: hoare_step pt_def del: Sup_image_eq)\n  apply (rule hoare_fixpoint)\n  apply auto\n  apply (simp add: dgr_def)\n  apply (simp add: hoare_choice)\n  apply safe\n  apply (simp add: hoare_sequential)\n  apply auto\n  apply (simp add: hoare_assume)\n  apply (rule le_infI1)\n  by (rule SUP_upper, auto)\n\ntext{*\nThis theorem is a more general form of the more familiar form with a variant $t$\nwhich must decrease. If we take $X\\ w\\ i = (Y \\ i \\land t\\ i = w)$, then the\nsecond hypothesis of the theorem above becomes\n$\\models Y \\ i \\land t\\ i = w \\{| D(i,j) |\\} Y \\ i \\land t \\ i < w$. However,\nthe more general form of the theorem is needed, because\nin data refinements, the form $Y\\ i \\land t\\ i = w$ cannot be preserved.\n*}\n\ntext {*\nThe drawback of this theorem is that the variant must be decreased on every\ntransitions which may be too cumbersome for practical applications. A similar \nsituation occur when introducing proof rules for mutually recursive procedures.\nThere the straightforward generalization of the proof rule of a recursive procedure\nto mutually recursive procedures suffers of a similar problem. We would need\nto prove that the variant decreases before every recursive call. Nipkow\n\\cite{nipkow:2002} has introduced a rule for mutually recursive procedures\nin which the variant is required to decrease only in a sequence of recursive\ncalls before calling again a procedure in this sequence. We introduce a\nsimilar proof rule in which the variant depends also on the situation\nindexes.\n*}\n\nlocale DiagramTermination =\n  fixes pair:: \"'a \\<Rightarrow> 'b \\<Rightarrow> ('c::well_founded_transitive)\"\nbegin\n\ndefinition\n  \"SUP_L_P X u i = (SUP v:{v. pair v i < u}. X v i :: _ :: complete_lattice)\" \n\ndefinition \n  \"SUP_LE_P X u i = (SUP v:{v. pair v i \\<le> u}. X v i :: _ :: complete_lattice)\"\n\nlemma SUP_L_P_upper:\n  \"pair v i < u \\<Longrightarrow> P v i \\<le> SUP_L_P P u i\"\n  by (auto simp add: SUP_L_P_def intro: SUP_upper)\n\nlemma SUP_L_P_least:\n  \"(!! v . pair v i < u \\<Longrightarrow> P v i \\<le> Q) \\<Longrightarrow> SUP_L_P P u i \\<le> Q\"\n  by (simp add: SUP_L_P_def, rule SUP_least, auto)\n\nlemma SUP_LE_P_upper:\n  \"pair v i \\<le> u \\<Longrightarrow> P v i \\<le> SUP_LE_P P u i\"\n  by (auto simp add: SUP_LE_P_def intro: SUP_upper)\n\nlemma SUP_LE_P_least:\n  \"(!! v . pair v i \\<le> u \\<Longrightarrow> P v i \\<le> Q) \\<Longrightarrow> SUP_LE_P P u i \\<le> Q\"\n  by (simp add: SUP_LE_P_def, rule SUP_least, auto)\n\nlemma SUP_SUP_L [simp]: \"Sup (range (SUP_LE_P X)) = Sup (range X)\"\n  apply (simp add: fun_eq_iff Sup_fun_def, clarify)\n  apply (rule antisym)\n  apply (rule SUP_least)\n  unfolding comp_def\n  apply (rule SUP_LE_P_least)\n  apply (rule SUP_upper, simp)\n  apply (rule SUP_least)\n  apply (rule_tac y = \"SUP_LE_P X (pair xa x) x\" in  order_trans)\n  apply (rule SUP_LE_P_upper, simp)\n  by (rule SUP_upper, simp)\n\nlemma SUP_L_SUP_LE_P [simp]: \"Sup_less (SUP_LE_P X) = SUP_L_P X\"\n  apply (rule antisym)\n  apply (subst le_fun_def, safe)\n  apply (rule Sup_less_least)\n  apply (subst le_fun_def, safe)\n  apply (rule SUP_LE_P_least)\n  apply (rule SUP_L_P_upper, simp)\n  apply (simp add: le_fun_def, safe)\n  apply (rule SUP_L_P_least)\n  apply (rule_tac y = \"SUP_LE_P X (pair v xa) xa\" in order_trans)\n  apply (rule SUP_LE_P_upper, simp)\n  apply (cut_tac P = \"SUP_LE_P X\" in Sup_less_upper)\n  by (simp, simp add: le_fun_def)\n  \nend\n    \ntheorem (in DiagramTermination) hoare_diagram2:\n  \"dmono D \\<Longrightarrow> (\\<forall> u i j . \\<Turnstile> X u i  {| D(i, j) |} SUP_L_P X (pair u i) j) \\<Longrightarrow> \n    \\<Turnstile> (Sup (range X)) {| pt D |} ((Sup (range  X)) \\<sqinter> (-(grd (step D))))\"\n  apply (frule_tac X = \"SUP_LE_P X\" in hoare_diagram)\n  apply (auto simp del: Sup_image_eq)\n  apply (simp add: SUP_LE_P_def)\n  apply (unfold SUP_def hoare_Sup [THEN sym])\n  apply auto\n  apply (rule_tac Q = \"SUP_L_P X (pair p i) j\" in hoare_mono)\n  apply auto\n  apply (rule SUP_L_P_least)\n  apply (rule SUP_L_P_upper)\n  apply (rule order_trans3)\n  by auto\n\nlemma mono_pt [simp]: \"dmono D \\<Longrightarrow> mono (pt D)\"\n  apply (drule mono_mono_dgr)\n  by (simp add: pt_def)\n\ntheorem (in DiagramTermination) hoare_diagram3:\n  \"dmono D \\<Longrightarrow> \n     (\\<forall> u i j . \\<Turnstile> X u i  {| D(i, j) |} SUP_L_P X (pair u i) j) \\<Longrightarrow> \n      P \\<le> Sup (range X) \\<Longrightarrow>  ((Sup (range X)) \\<sqinter> (-(grd (step D)))) \\<le> Q \\<Longrightarrow>\n      \\<Turnstile> P {| pt D |} Q\"\n  apply (rule hoare_mono)\n  apply auto\n  apply (rule hoare_pre)\n  apply (auto simp add: SUP_def simp del: Sup_image_eq)\n  apply (rule hoare_diagram2)\n  by auto\n\ntext{*\nThe following definition introduces the concept of correct Hoare triples for diagrams.\n*}\n\ndefinition (in DiagramTermination)\n  Hoare_dgr :: \"('b \\<Rightarrow> ('u::{complete_distrib_lattice, boolean_algebra})) \\<Rightarrow> ('b \\<times> 'b \\<Rightarrow> 'u \\<Rightarrow> 'u) \\<Rightarrow> ('b \\<Rightarrow> 'u) \\<Rightarrow> bool\" (\"\\<turnstile> (_){| _ |}(_) \" \n  [0,0,900] 900) where\n  \"\\<turnstile> P {| D |} Q \\<equiv> (\\<exists> X . (\\<forall> u i j . \\<Turnstile> X u i  {| D(i, j) |} SUP_L_P X (pair u i) j) \\<and> \n       P = Sup (range X) \\<and> Q = ((Sup (range  X)) \\<sqinter> (-(grd (step D)))))\"\n\ndefinition (in DiagramTermination)\n  Hoare_dgr1 :: \"('b \\<Rightarrow> ('u::{complete_distrib_lattice, boolean_algebra})) \\<Rightarrow> ('b \\<times> 'b \\<Rightarrow> 'u \\<Rightarrow> 'u) \\<Rightarrow> ('b \\<Rightarrow> 'u) \\<Rightarrow> bool\" (\"\\<turnstile>1 (_){| _ |}(_) \" \n  [0,0,900] 900) where\n  \"\\<turnstile>1 P {| D |} Q \\<equiv> (\\<exists> X . (\\<forall> u i j . \\<Turnstile> X u i  {| D(i, j) |} SUP_L_P X (pair u i) j) \\<and> \n      P \\<le> Sup (range X) \\<and> ((Sup (range X)) \\<sqinter> (-(grd (step D)))) \\<le> Q)\"\n\n\ntheorem (in DiagramTermination) hoare_dgr_correctness: \n  \"dmono D \\<Longrightarrow> (\\<turnstile> P {| D |} Q) \\<Longrightarrow> (\\<Turnstile> P {| pt D |} Q)\"\n  apply (simp add: Hoare_dgr_def)\n  apply safe\n  apply (rule hoare_diagram3)\n  by auto\n\ntheorem  (in DiagramTermination) hoare_dgr_correctness1:\n  \"dmono D \\<Longrightarrow> (\\<turnstile>1 P {| D |} Q) \\<Longrightarrow> (\\<Turnstile> P {| pt D |} Q)\"\n  apply (simp add: Hoare_dgr1_def)\n  apply safe\n  apply (rule hoare_diagram3)\n  by auto\n\ndefinition\n  \"dgr_demonic Q ij = [:Q ij:]\"\n\ntheorem dgr_demonic_mono[simp]:\n  \"dmono (dgr_demonic Q)\"\n  by (simp add: dmono_def dgr_demonic_def)\n\ndefinition\n  \"dangelic R Q i = angelic (R i) (Q i)\"\n\nlemma  grd_dgr:\n  \"((grd (step D) i)::('a::complete_boolean_algebra)) = \\<Squnion> {P . \\<exists> j . P = grd (D(i,j))}\"\n  apply (simp add: grd_def step_def)\n  apply (unfold step_def INF_def uminus_Inf)\n  apply (case_tac \"(uminus ` range (\\<lambda>j\\<Colon>'b. D (i, j) \\<bottom>)) = {P\\<Colon>'a. \\<exists>j\\<Colon>'b. P = - D (i, j) \\<bottom>}\")\n  apply auto\n  done\n\nlemma  grd_dgr_set:\n  \"((grd (step D) i)::('a set)) = Union {P . \\<exists> j . P = grd (D(i,j))}\"\n  by (simp add: grd_dgr)\n\nlemma not_grd_dgr [simp]: \"(a \\<in> (- grd (step D) i)) = (\\<forall> j . a \\<notin> grd (D(i,j)))\"\n apply (simp add: grd_dgr)\n  by auto\n\nlemma not_grd_dgr2 [simp]: \"a \\<notin> (grd (step D) i) = (\\<forall> j . a \\<notin> grd (D(i,j)))\"\n  apply (subst not_grd_dgr [THEN sym])\n  by simp\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/DataRefinementIBP/Diagram.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554476, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.7590433346809948}}
{"text": "theory ex2_02 imports Main\nbegin\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc (add m n)\"\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc m) = Suc (Suc (double m))\"\n\ntheorem add_assoc: \"add (add m n) p = add m (add n p)\"\napply(induction m)\napply auto\ndone\n\nlemma add_zero[simp]: \"add m 0 = m\"\napply(induction m)\napply auto\ndone\n\nlemma add_suc[simp]: \"add m (Suc n) = Suc(add m n)\"\napply(induction m)\napply auto\ndone\n\ntheorem add_comm: \"add m n = add n m\"\napply(induction m)\napply auto\ndone\n\ntheorem add_double: \"double m = add m m\"\napply (induction m)\napply auto\ndone\n\nend", "meta": {"author": "okaduki", "repo": "ConcreteSemantics", "sha": "74b593c16169bc47c5f2b58c6a204cabd8f185b7", "save_path": "github-repos/isabelle/okaduki-ConcreteSemantics", "path": "github-repos/isabelle/okaduki-ConcreteSemantics/ConcreteSemantics-74b593c16169bc47c5f2b58c6a204cabd8f185b7/chapter2/ex2_02.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9449947086083138, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.7589949854240373}}
{"text": "(*  Title:      HOL/Library/Boolean_Algebra.thy\n    Author:     Brian Huffman\n*)\n\nsection {* Boolean Algebras *}\n\ntheory Boolean_Algebra\nimports Main\nbegin\n\nlocale boolean =\n  fixes conj :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<sqinter>\" 70)\n  fixes disj :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<squnion>\" 65)\n  fixes compl :: \"'a \\<Rightarrow> 'a\" (\"\\<sim> _\" [81] 80)\n  fixes zero :: \"'a\" (\"\\<zero>\")\n  fixes one  :: \"'a\" (\"\\<one>\")\n  assumes conj_assoc: \"(x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n  assumes disj_assoc: \"(x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n  assumes conj_commute: \"x \\<sqinter> y = y \\<sqinter> x\"\n  assumes disj_commute: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes conj_disj_distrib: \"x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n  assumes disj_conj_distrib: \"x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n  assumes conj_one_right [simp]: \"x \\<sqinter> \\<one> = x\"\n  assumes disj_zero_right [simp]: \"x \\<squnion> \\<zero> = x\"\n  assumes conj_cancel_right [simp]: \"x \\<sqinter> \\<sim> x = \\<zero>\"\n  assumes disj_cancel_right [simp]: \"x \\<squnion> \\<sim> x = \\<one>\"\nbegin\n\nsublocale conj!: abel_semigroup conj proof\nqed (fact conj_assoc conj_commute)+\n\nsublocale disj!: abel_semigroup disj proof\nqed (fact disj_assoc disj_commute)+\n\nlemmas conj_left_commute = conj.left_commute\n\nlemmas disj_left_commute = disj.left_commute\n\nlemmas conj_ac = conj.assoc conj.commute conj.left_commute\nlemmas disj_ac = disj.assoc disj.commute disj.left_commute\n\nlemma dual: \"boolean disj conj compl one zero\"\napply (rule boolean.intro)\napply (rule disj_assoc)\napply (rule conj_assoc)\napply (rule disj_commute)\napply (rule conj_commute)\napply (rule disj_conj_distrib)\napply (rule conj_disj_distrib)\napply (rule disj_zero_right)\napply (rule conj_one_right)\napply (rule disj_cancel_right)\napply (rule conj_cancel_right)\ndone\n\nsubsection {* Complement *}\n\nlemma complement_unique:\n  assumes 1: \"a \\<sqinter> x = \\<zero>\"\n  assumes 2: \"a \\<squnion> x = \\<one>\"\n  assumes 3: \"a \\<sqinter> y = \\<zero>\"\n  assumes 4: \"a \\<squnion> y = \\<one>\"\n  shows \"x = y\"\nproof -\n  have \"(a \\<sqinter> x) \\<squnion> (x \\<sqinter> y) = (a \\<sqinter> y) \\<squnion> (x \\<sqinter> y)\" using 1 3 by simp\n  hence \"(x \\<sqinter> a) \\<squnion> (x \\<sqinter> y) = (y \\<sqinter> a) \\<squnion> (y \\<sqinter> x)\" using conj_commute by simp\n  hence \"x \\<sqinter> (a \\<squnion> y) = y \\<sqinter> (a \\<squnion> x)\" using conj_disj_distrib by simp\n  hence \"x \\<sqinter> \\<one> = y \\<sqinter> \\<one>\" using 2 4 by simp\n  thus \"x = y\" using conj_one_right by simp\nqed\n\nlemma compl_unique: \"\\<lbrakk>x \\<sqinter> y = \\<zero>; x \\<squnion> y = \\<one>\\<rbrakk> \\<Longrightarrow> \\<sim> x = y\"\nby (rule complement_unique [OF conj_cancel_right disj_cancel_right])\n\nlemma double_compl [simp]: \"\\<sim> (\\<sim> x) = x\"\nproof (rule compl_unique)\n  from conj_cancel_right show \"\\<sim> x \\<sqinter> x = \\<zero>\" by (simp only: conj_commute)\n  from disj_cancel_right show \"\\<sim> x \\<squnion> x = \\<one>\" by (simp only: disj_commute)\nqed\n\nlemma compl_eq_compl_iff [simp]: \"(\\<sim> x = \\<sim> y) = (x = y)\"\nby (rule inj_eq [OF inj_on_inverseI], rule double_compl)\n\nsubsection {* Conjunction *}\n\nlemma conj_absorb [simp]: \"x \\<sqinter> x = x\"\nproof -\n  have \"x \\<sqinter> x = (x \\<sqinter> x) \\<squnion> \\<zero>\" using disj_zero_right by simp\n  also have \"... = (x \\<sqinter> x) \\<squnion> (x \\<sqinter> \\<sim> x)\" using conj_cancel_right by simp\n  also have \"... = x \\<sqinter> (x \\<squnion> \\<sim> x)\" using conj_disj_distrib by (simp only:)\n  also have \"... = x \\<sqinter> \\<one>\" using disj_cancel_right by simp\n  also have \"... = x\" using conj_one_right by simp\n  finally show ?thesis .\nqed\n\nlemma conj_zero_right [simp]: \"x \\<sqinter> \\<zero> = \\<zero>\"\nproof -\n  have \"x \\<sqinter> \\<zero> = x \\<sqinter> (x \\<sqinter> \\<sim> x)\" using conj_cancel_right by simp\n  also have \"... = (x \\<sqinter> x) \\<sqinter> \\<sim> x\" using conj_assoc by (simp only:)\n  also have \"... = x \\<sqinter> \\<sim> x\" using conj_absorb by simp\n  also have \"... = \\<zero>\" using conj_cancel_right by simp\n  finally show ?thesis .\nqed\n\nlemma compl_one [simp]: \"\\<sim> \\<one> = \\<zero>\"\nby (rule compl_unique [OF conj_zero_right disj_zero_right])\n\nlemma conj_zero_left [simp]: \"\\<zero> \\<sqinter> x = \\<zero>\"\nby (subst conj_commute) (rule conj_zero_right)\n\nlemma conj_one_left [simp]: \"\\<one> \\<sqinter> x = x\"\nby (subst conj_commute) (rule conj_one_right)\n\nlemma conj_cancel_left [simp]: \"\\<sim> x \\<sqinter> x = \\<zero>\"\nby (subst conj_commute) (rule conj_cancel_right)\n\nlemma conj_left_absorb [simp]: \"x \\<sqinter> (x \\<sqinter> y) = x \\<sqinter> y\"\nby (simp only: conj_assoc [symmetric] conj_absorb)\n\nlemma conj_disj_distrib2:\n  \"(y \\<squnion> z) \\<sqinter> x = (y \\<sqinter> x) \\<squnion> (z \\<sqinter> x)\" \nby (simp only: conj_commute conj_disj_distrib)\n\nlemmas conj_disj_distribs =\n   conj_disj_distrib conj_disj_distrib2\n\nsubsection {* Disjunction *}\n\nlemma disj_absorb [simp]: \"x \\<squnion> x = x\"\nby (rule boolean.conj_absorb [OF dual])\n\nlemma disj_one_right [simp]: \"x \\<squnion> \\<one> = \\<one>\"\nby (rule boolean.conj_zero_right [OF dual])\n\nlemma compl_zero [simp]: \"\\<sim> \\<zero> = \\<one>\"\nby (rule boolean.compl_one [OF dual])\n\nlemma disj_zero_left [simp]: \"\\<zero> \\<squnion> x = x\"\nby (rule boolean.conj_one_left [OF dual])\n\nlemma disj_one_left [simp]: \"\\<one> \\<squnion> x = \\<one>\"\nby (rule boolean.conj_zero_left [OF dual])\n\nlemma disj_cancel_left [simp]: \"\\<sim> x \\<squnion> x = \\<one>\"\nby (rule boolean.conj_cancel_left [OF dual])\n\nlemma disj_left_absorb [simp]: \"x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\nby (rule boolean.conj_left_absorb [OF dual])\n\nlemma disj_conj_distrib2:\n  \"(y \\<sqinter> z) \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\nby (rule boolean.conj_disj_distrib2 [OF dual])\n\nlemmas disj_conj_distribs =\n   disj_conj_distrib disj_conj_distrib2\n\nsubsection {* De Morgan's Laws *}\n\nlemma de_Morgan_conj [simp]: \"\\<sim> (x \\<sqinter> y) = \\<sim> x \\<squnion> \\<sim> y\"\nproof (rule compl_unique)\n  have \"(x \\<sqinter> y) \\<sqinter> (\\<sim> x \\<squnion> \\<sim> y) = ((x \\<sqinter> y) \\<sqinter> \\<sim> x) \\<squnion> ((x \\<sqinter> y) \\<sqinter> \\<sim> y)\"\n    by (rule conj_disj_distrib)\n  also have \"... = (y \\<sqinter> (x \\<sqinter> \\<sim> x)) \\<squnion> (x \\<sqinter> (y \\<sqinter> \\<sim> y))\"\n    by (simp only: conj_ac)\n  finally show \"(x \\<sqinter> y) \\<sqinter> (\\<sim> x \\<squnion> \\<sim> y) = \\<zero>\"\n    by (simp only: conj_cancel_right conj_zero_right disj_zero_right)\nnext\n  have \"(x \\<sqinter> y) \\<squnion> (\\<sim> x \\<squnion> \\<sim> y) = (x \\<squnion> (\\<sim> x \\<squnion> \\<sim> y)) \\<sqinter> (y \\<squnion> (\\<sim> x \\<squnion> \\<sim> y))\"\n    by (rule disj_conj_distrib2)\n  also have \"... = (\\<sim> y \\<squnion> (x \\<squnion> \\<sim> x)) \\<sqinter> (\\<sim> x \\<squnion> (y \\<squnion> \\<sim> y))\"\n    by (simp only: disj_ac)\n  finally show \"(x \\<sqinter> y) \\<squnion> (\\<sim> x \\<squnion> \\<sim> y) = \\<one>\"\n    by (simp only: disj_cancel_right disj_one_right conj_one_right)\nqed\n\nlemma de_Morgan_disj [simp]: \"\\<sim> (x \\<squnion> y) = \\<sim> x \\<sqinter> \\<sim> y\"\nby (rule boolean.de_Morgan_conj [OF dual])\n\nend\n\nsubsection {* Symmetric Difference *}\n\nlocale boolean_xor = boolean +\n  fixes xor :: \"'a => 'a => 'a\"  (infixr \"\\<oplus>\" 65)\n  assumes xor_def: \"x \\<oplus> y = (x \\<sqinter> \\<sim> y) \\<squnion> (\\<sim> x \\<sqinter> y)\"\nbegin\n\nsublocale xor!: abel_semigroup xor proof\n  fix x y z :: 'a\n  let ?t = \"(x \\<sqinter> y \\<sqinter> z) \\<squnion> (x \\<sqinter> \\<sim> y \\<sqinter> \\<sim> z) \\<squnion>\n            (\\<sim> x \\<sqinter> y \\<sqinter> \\<sim> z) \\<squnion> (\\<sim> x \\<sqinter> \\<sim> y \\<sqinter> z)\"\n  have \"?t \\<squnion> (z \\<sqinter> x \\<sqinter> \\<sim> x) \\<squnion> (z \\<sqinter> y \\<sqinter> \\<sim> y) =\n        ?t \\<squnion> (x \\<sqinter> y \\<sqinter> \\<sim> y) \\<squnion> (x \\<sqinter> z \\<sqinter> \\<sim> z)\"\n    by (simp only: conj_cancel_right conj_zero_right)\n  thus \"(x \\<oplus> y) \\<oplus> z = x \\<oplus> (y \\<oplus> z)\"\n    apply (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\n    apply (simp only: conj_disj_distribs conj_ac disj_ac)\n    done\n  show \"x \\<oplus> y = y \\<oplus> x\"\n    by (simp only: xor_def conj_commute disj_commute)\nqed\n\nlemmas xor_assoc = xor.assoc\nlemmas xor_commute = xor.commute\nlemmas xor_left_commute = xor.left_commute\n\nlemmas xor_ac = xor.assoc xor.commute xor.left_commute\n\nlemma xor_def2:\n  \"x \\<oplus> y = (x \\<squnion> y) \\<sqinter> (\\<sim> x \\<squnion> \\<sim> y)\"\nby (simp only: xor_def conj_disj_distribs\n               disj_ac conj_ac conj_cancel_right disj_zero_left)\n\nlemma xor_zero_right [simp]: \"x \\<oplus> \\<zero> = x\"\nby (simp only: xor_def compl_zero conj_one_right conj_zero_right disj_zero_right)\n\nlemma xor_zero_left [simp]: \"\\<zero> \\<oplus> x = x\"\nby (subst xor_commute) (rule xor_zero_right)\n\nlemma xor_one_right [simp]: \"x \\<oplus> \\<one> = \\<sim> x\"\nby (simp only: xor_def compl_one conj_zero_right conj_one_right disj_zero_left)\n\nlemma xor_one_left [simp]: \"\\<one> \\<oplus> x = \\<sim> x\"\nby (subst xor_commute) (rule xor_one_right)\n\nlemma xor_self [simp]: \"x \\<oplus> x = \\<zero>\"\nby (simp only: xor_def conj_cancel_right conj_cancel_left disj_zero_right)\n\nlemma xor_left_self [simp]: \"x \\<oplus> (x \\<oplus> y) = y\"\nby (simp only: xor_assoc [symmetric] xor_self xor_zero_left)\n\nlemma xor_compl_left [simp]: \"\\<sim> x \\<oplus> y = \\<sim> (x \\<oplus> y)\"\napply (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\napply (simp only: conj_disj_distribs)\napply (simp only: conj_cancel_right conj_cancel_left)\napply (simp only: disj_zero_left disj_zero_right)\napply (simp only: disj_ac conj_ac)\ndone\n\nlemma xor_compl_right [simp]: \"x \\<oplus> \\<sim> y = \\<sim> (x \\<oplus> y)\"\napply (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\napply (simp only: conj_disj_distribs)\napply (simp only: conj_cancel_right conj_cancel_left)\napply (simp only: disj_zero_left disj_zero_right)\napply (simp only: disj_ac conj_ac)\ndone\n\nlemma xor_cancel_right: \"x \\<oplus> \\<sim> x = \\<one>\"\nby (simp only: xor_compl_right xor_self compl_zero)\n\nlemma xor_cancel_left: \"\\<sim> x \\<oplus> x = \\<one>\"\nby (simp only: xor_compl_left xor_self compl_zero)\n\nlemma conj_xor_distrib: \"x \\<sqinter> (y \\<oplus> z) = (x \\<sqinter> y) \\<oplus> (x \\<sqinter> z)\"\nproof -\n  have \"(x \\<sqinter> y \\<sqinter> \\<sim> z) \\<squnion> (x \\<sqinter> \\<sim> y \\<sqinter> z) =\n        (y \\<sqinter> x \\<sqinter> \\<sim> x) \\<squnion> (z \\<sqinter> x \\<sqinter> \\<sim> x) \\<squnion> (x \\<sqinter> y \\<sqinter> \\<sim> z) \\<squnion> (x \\<sqinter> \\<sim> y \\<sqinter> z)\"\n    by (simp only: conj_cancel_right conj_zero_right disj_zero_left)\n  thus \"x \\<sqinter> (y \\<oplus> z) = (x \\<sqinter> y) \\<oplus> (x \\<sqinter> z)\"\n    by (simp (no_asm_use) only:\n        xor_def de_Morgan_disj de_Morgan_conj double_compl\n        conj_disj_distribs conj_ac disj_ac)\nqed\n\nlemma conj_xor_distrib2:\n  \"(y \\<oplus> z) \\<sqinter> x = (y \\<sqinter> x) \\<oplus> (z \\<sqinter> x)\"\nproof -\n  have \"x \\<sqinter> (y \\<oplus> z) = (x \\<sqinter> y) \\<oplus> (x \\<sqinter> z)\"\n    by (rule conj_xor_distrib)\n  thus \"(y \\<oplus> z) \\<sqinter> x = (y \\<sqinter> x) \\<oplus> (z \\<sqinter> x)\"\n    by (simp only: conj_commute)\nqed\n\nlemmas conj_xor_distribs =\n   conj_xor_distrib conj_xor_distrib2\n\nend\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.853912747375134, "lm_q1q2_score": 0.7589224530408933}}
{"text": "theory VDMOrderExample\nimports VDMToolkit\nbegin\n\nrecord R = \n  x :: nat \n  y :: nat  \n\ndefinition \n  R_eq :: \"R \\<Rightarrow> R \\<Rightarrow> bool\" (infix \"=\\<^sub>R\" 50)\n  where\n  [simp]: \"r1 =\\<^sub>R r2 \\<equiv> (x r1) = (x r2)\"\n\ndefinition \n  R_ord :: \"R \\<Rightarrow> R \\<Rightarrow> bool\" (infix \"<\\<^sub>R\" 50)\n  where\n  [simp]: \"r1 <\\<^sub>R r2 \\<equiv> (x r1) < (x r2) \\<or> ((x r1) = (x r2) \\<and> (y r1) < (y r2))\"\n\ndefinition \n  R_tord :: \"R \\<Rightarrow> R \\<Rightarrow> bool\" (infix \"\\<le>\\<^sub>R\" 50)\n  where\n  [simp]: \"r1 \\<le>\\<^sub>R r2 \\<equiv> r1 <\\<^sub>R r2 \\<or> R_eq r1 r2\"\n\nlemma vdm_ord_irrefl: \"\\<forall> r . \\<not> r <\\<^sub>R r\"\n  by simp\n\nlemma vdm_ord_trans: \"\\<forall> r1 r2 r3 . r1 <\\<^sub>R r2 \\<and> r2 <\\<^sub>R r3 \\<longrightarrow> r1 <\\<^sub>R r3\"\n  by fastforce\n\nlemma vdm_ord_asym: \"\\<forall> x y . x <\\<^sub>R y \\<longrightarrow> \\<not> y <\\<^sub>R x\"\n  by simp\n\nlemma vdm_ord_implies_totality:\n  \"\\<forall> x y z . \\<not> x <\\<^sub>R x \\<and> (x <\\<^sub>R y \\<and> y <\\<^sub>R z \\<longrightarrow> x <\\<^sub>R z) \\<and> (x <\\<^sub>R y \\<longrightarrow> \\<not> y <\\<^sub>R x) \\<longrightarrow> x \\<le>\\<^sub>R y \\<or> y \\<le>\\<^sub>R x\"\n  by (safe, simp_all)\n\nlemma vdm_ord_total:\n  \"\\<forall> x y z . x \\<le>\\<^sub>R y \\<or> y \\<le>\\<^sub>R x\"\n  by (safe, simp_all)\n\nlemma PO2:\n  \"\\<forall> r . r =\\<^sub>R r\"\n  \"\\<forall> r1 r2 . r1 =\\<^sub>R r2 \\<longrightarrow> r2 =\\<^sub>R r1\" \n  \\<open>\\<forall> r1 r2 r3 . r1 =\\<^sub>R r2 \\<and> r2 =\\<^sub>R r3 \\<longrightarrow> r1 =\\<^sub>R r3\\<close>\n  by simp_all\n\nlemma PO4: \n  \\<open>\\<forall> r . \\<not> r <\\<^sub>R r\\<close>\n  \\<open>\\<forall> r1 r2 r3 . r1 <\\<^sub>R r2 \\<and> r2 <\\<^sub>R r3 \\<longrightarrow> r1 <\\<^sub>R r3\\<close>\n  by fastforce+\n\nlemma PO5: \n  \\<open>\\<forall> r1 r2 . r1 \\<le>\\<^sub>R r2 \\<or> r2 \\<le>\\<^sub>R r1\\<close>\n  by force\n\nend", "meta": {"author": "leouk", "repo": "VDM_Toolkit", "sha": "791013909961d45949fcd96d937ae18f0174c7ec", "save_path": "github-repos/isabelle/leouk-VDM_Toolkit", "path": "github-repos/isabelle/leouk-VDM_Toolkit/VDM_Toolkit-791013909961d45949fcd96d937ae18f0174c7ec/plugins/vdm2isa/src/main/resources/VDMOrderExample.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989810230102, "lm_q2_score": 0.8376199572530448, "lm_q1q2_score": 0.7588751461166323}}
{"text": "theory Logic\nimports Main\nbegin\n\n(* In Isabelle, Prop in Coq is just a type 'bool', then things are much easier *)\n\nsection {* Logic *}\nsubsection {* Propositions *}\n\nterm \"3 = 3\"\n  (* \\<Longrightarrow> \"3 = 3\" :: \"bool\" *)\nterm \"\\<forall>(n :: nat). n = 2\"\n  (* \\<Longrightarrow> \"\\<forall>n. n = 2\" :: \"bool\" *)\n\nsubsection {* Proofs and Evidence *}\n\nlemma silly: \"0 * 3 = (0 :: nat)\" by simp\nthm silly\n  (* \\<Longrightarrow> 0 * 3 = 0 *)\n\nsubsubsection {* Implications are functions *}\n\nlemma silly_implication: \"(1 + 1) = 2 \\<longrightarrow> 0 * 3 = (0 :: nat)\" by simp\nthm silly_implication\n  (* \\<Longrightarrow> 1 + 1 = 2 \\<longrightarrow> 0 * 3 = 0 *)\n\nsubsubsection {* Defining Propositions *}\n\nsubsection {* Conjunction (Logical \"and\") *}\n\n(*\nInductive and (P Q : Prop) : Prop :=\n  conj : P \\<rightarrow> Q \\<rightarrow> (and P Q).\n*)\n\nvalue \"\\<lambda>x y. x \\<and> y\"\n  (* \\<Longrightarrow> \"_\" :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" *)\n\nsubsubsection {* \"Introducing\" Conjuctions *}\n\ntheorem and_example: \"((0 :: nat) = 0) \\<and> ((4 :: nat) = 2 * 2)\" by simp\n\nsubsubsection {* \"Eliminating\" conjunctions *}\n\ntheorem proj1: \"\\<forall>p q. p \\<and> q \\<longrightarrow> p\" by simp\n\n(* Exercise: 1 star, optional (proj2) *)\n\ntheorem proj2: \"\\<forall>p q. p \\<and> q \\<longrightarrow> q\" by simp\ntheorem and_commut: \"\\<forall>p q. p \\<and> q \\<longrightarrow> q \\<and> p\" by simp\n\n(* Exercise: 2 stars (and_assoc) *)\n\ntheorem and_assoc: \"\\<forall>p q r. p \\<and> (q \\<and> r) \\<longrightarrow> (p \\<and> q) \\<and> r\" by simp\n\nsubsection {* Iff *}\n\nno_notation\n  iff (infixr \"\\<longleftrightarrow>\" 25)\n\nabbreviation iff (infixr \"\\<longleftrightarrow>\" 25) where\n  \"iff p q \\<equiv> (p \\<longrightarrow> q) \\<and> (q \\<longrightarrow> p)\"\n\ntheorem iff_implies: \"\\<forall>p q. (p \\<longleftrightarrow> q) \\<longrightarrow> p \\<longrightarrow> q\" by simp\ntheorem iff_sym: \"\\<forall>p q. (p \\<longleftrightarrow> q) \\<longrightarrow> (q \\<longleftrightarrow> p)\" by simp\n\n(* Exercise: 1 star, optional (iff_properties) *)\n\ntheorem iff_refl: \"\\<forall>p. p \\<longleftrightarrow> p\" by simp\ntheorem iff_trans: \"\\<forall>p q r. (p \\<longleftrightarrow> q) \\<longrightarrow> (q \\<longleftrightarrow> r) \\<longrightarrow> (p \\<longleftrightarrow> r)\" by fastforce\n\nsubsection {* Disjunction (Logical \"or\") *}\nsubsubsection {* Implementing Disjunction *}\n\n(*\nInductive or (P Q : Prop) : Prop :=\n  | or_introl : P -> or P Q\n  | or_intror : Q -> or P Q.\n*)\n\nthm \"disjI1\"\n  (* ?P \\<Longrightarrow> ?P \\<or> ?Q *)\nthm \"disjI2\"\n  (* ?Q \\<Longrightarrow> ?P \\<or> ?Q *)\n\ntheorem or_commut: \"\\<forall>p q. p \\<or> q \\<longrightarrow> q \\<or> p\" by simp\ntheorem or_distributes_over_and_1: \"\\<forall>p q r. p \\<or> (q \\<and> r) \\<longrightarrow> (p \\<or> q) \\<and> (p \\<or> r)\" by simp\n\n(* Exercise: 2 stars (or_distributes_over_and_2) *)\ntheorem or_distributes_over_and_2: \"\\<forall>p q r. (p \\<or> q) \\<and> (p \\<or> r) \\<longrightarrow> p \\<or> (q \\<and> r)\" by auto\n\n(* Exercise: 1 star, optional (or_distributes_over_and) *)\ntheorem or_distributes_over_and : \"\\<forall>P Q R. P \\<or> (Q \\<and> R) \\<longleftrightarrow> (P \\<or> Q) \\<and> (P \\<or> R)\" by auto\n\nsubsubsection {* Relating \\<and> and \\<or> with andb and orb (advanced) *}\n\ntheorem andb_prop: \"\\<forall>b c. b \\<and> c = True \\<longrightarrow> b = True \\<and> c = True\" by simp\ntheorem andb_true_intro: \"\\<forall>b c. b = True \\<and> c = True \\<longrightarrow> b \\<and> c\" by simp\n\n(* Exercise: 2 stars, optional (bool_prop) *)\ntheorem andb_false: \"\\<forall>b c. b \\<and> c = False \\<longrightarrow> b = False \\<or> c = False\" by simp\ntheorem orb_prop: \"\\<forall>b c. b \\<or> c = True \\<longrightarrow> b = True \\<or> c = True\" by simp\ntheorem orb_false_elim: \"\\<forall>b c. (b \\<or> c) = False \\<longrightarrow> b = False \\<and> c = False\" by simp\n\nsubsection {* Falsehood *}\n\n(* Inductive False : Prop := . *)\n\ntheorem False_implies_nonsense: \"False \\<longrightarrow> 2 + 2 = 5\" by simp\ntheorem ex_falso_quodlibet: \"\\<forall>p. False \\<longrightarrow> p\" by simp\n\nsubsubsection {* Truth *}\n\n(* Exercise: 2 stars, advanced (True) *)\n\nsubsection {* Negation *}\n\n(* Definition not (P:Prop) := P \\<rightarrow> False. *)\n\nterm \"\\<lambda>x. \\<not> x\"\n  (* \\<Longrightarrow> \"Not\" :: \"bool \\<Rightarrow> bool\" *)\n\ntheorem not_False: \"\\<not> False\" by simp\ntheorem contradiction_implies_anything: \"\\<forall>p q. (p \\<and> \\<not> p) \\<longrightarrow> q\" by simp\ntheorem double_neg: \"\\<forall>p. p \\<longrightarrow> ~~ p\" by simp\n\n(* Exercise: 2 stars, advanced (double_neg_inf) *)\n(* Exercise: 2 stars (contrapositive) *)\n\ntheorem contrapositive: \"\\<forall>p q. (p \\<longrightarrow> q) \\<longrightarrow> (\\<not> q \\<longrightarrow> \\<not> p)\" by auto\n\n(* Exercise: 1 star (not_both_true_and_false) *)\n\ntheorem \"\\<not> (p \\<and> \\<not> p)\" by simp\n\n(* Exercise: 1 star, advanced (informal_not_PNP) *)\n\nsubsubsection {* Constructive logic *}\n\ntheorem classis_double_neg: \"~~ p \\<longrightarrow> p\" by simp\n\n(* Exercise: 5 stars, advanced, optional (classical_axioms) *)\n\nabbreviation \"peirce \\<equiv> \\<forall>p q. ((p \\<longrightarrow> q) \\<longrightarrow> p) \\<longrightarrow> p\"\nabbreviation \"classic \\<equiv> \\<forall>p. ~~p \\<longrightarrow> p\"\nabbreviation \"excluded_middle \\<equiv> \\<forall>p. p \\<or> \\<not> p\"\nabbreviation \"de_morgan_not_and_not \\<equiv> \\<forall>p q. \\<not> (\\<not> p \\<and> \\<not> q) \\<longrightarrow> p \\<or> q\"\nabbreviation \"implies_to_or \\<equiv> \\<forall>p q. (p \\<longrightarrow> q) \\<longrightarrow> (\\<not> p \\<or> q)\"\n\n(* Exercise: 3 stars (excluded_middle_irrefutable) *)\n\ntheorem excluded_middle_irrefutable: \"\\<forall>p. \\<not> \\<not> (p \\<or> \\<not> p)\" by simp\n\nsubsubsection {* Inequality *}\n\ntheorem not_false_then_true: \"\\<forall>b. b \\<noteq> False \\<longrightarrow> b = True\" by simp\n\n(* Exercise: 2 stars (false_beq_nat) *)\n\ntheorem false_beq_nat: \"\\<forall>n m. n \\<noteq> m \\<longrightarrow> n = m = False\" by simp\n\n(* Exercise: 2 stars, optional (beq_nat_false) *)\n\ntheorem beq_nat_false: \"\\<forall>n m. n = m = False \\<longrightarrow> n \\<noteq> m\" by simp\n\nend\n", "meta": {"author": "myuon", "repo": "isabelle-software-foundations", "sha": "8dd28cd2628050549278a922ee72612459585de1", "save_path": "github-repos/isabelle/myuon-isabelle-software-foundations", "path": "github-repos/isabelle/myuon-isabelle-software-foundations/isabelle-software-foundations-8dd28cd2628050549278a922ee72612459585de1/src/Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615382165412809, "lm_q2_score": 0.8807970670261976, "lm_q1q2_score": 0.7588403342605414}}
{"text": "theory Chapter4\n  imports Main\nbegin\n\n(* Ex 4.1 *)\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n  \"set Tip = {}\"\n| \"set (Node l a r) = set l \\<union> {a} \\<union> set r\"\n\n(* fun ord :: \"int tree \\<Rightarrow> bool\" where\n  \"ord Tip = True\"\n| \"ord (Node l a r) = \n*) \n\nlemma \"\\<forall>x. \\<exists>y. x = y\"\n  by auto\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\n  by auto\n\nlemma \"\\<lbrakk> \\<forall>xs \\<in> A. \\<exists>ys. xs = ys @ ys; us \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists>n. length us = n + n\"\n  by fastforce\n\nlemma \"\\<lbrakk> \\<forall>x y. T x y \\<or> T y x;\n        \\<forall>x y. A x y \\<and> A y x \\<longrightarrow> x = y;\n        \\<forall>x y. T x y \\<longrightarrow> A x y \\<rbrakk>\n        \\<Longrightarrow> \\<forall>x y. A x y \\<longrightarrow> T x y\"\n  by blast\n\nlemma \"\\<lbrakk> xs @ ys = ys @ xs; length xs = length ys \\<rbrakk> \\<Longrightarrow> xs = ys\"\n  sledgehammer\n  using append_eq_append_conv by blast\n\nlemma \"\\<lbrakk> (a::nat) \\<le> x + b; 2 * x < c \\<rbrakk> \\<Longrightarrow> 2 * a + 1 \\<le> 2 * b + c\" \n  by arith\n\nlemma \"\\<lbrakk> (a::nat) \\<le> b; b \\<le> c; c \\<le> d; d \\<le> e \\<rbrakk> \\<Longrightarrow> a \\<le> e\"\n  by (blast intro: le_trans)\n\nthm conjI[OF refl[of \"a\"] refl[of \"b\"]]\n\nlemma \"Suc (Suc (Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\n  by (blast dest: Suc_leD)\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\n  ev0: \"ev 0\"\n| evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n  \"evn 0 = True\"\n| \"evn (Suc 0) = False\"\n| \"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev (Suc (Suc (Suc (Suc 0))))\"\n  apply (rule evSS)\n  apply (rule evSS)\n  apply (rule ev0)\n  done\n\nlemma \"ev m \\<Longrightarrow> evn m\"\n  apply (induction rule: ev.induct)\nby simp_all\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply (induction n rule: evn.induct)\n  apply (simp_all add: ev0 evSS)\ndone\n\ndeclare ev.intros[simp,intro]\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl: \"star r x x\"\n| step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n  apply assumption\n  apply (metis step)\ndone\n\n(* Ex 4.2 *)\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\n  emp: \"palindrome []\"\n| singleton: \"palindrome [a]\"\n| multi: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply (induction rule: palindrome.induct)\n  apply simp_all\ndone\n\n(* Ex 4.5 *)\ndatatype alpha = a | b\n\ninductive S  where\n  empty: \"S []\"\n| betw: \"S w \\<Longrightarrow> S (a # w @ [b])\"\n| conc : \"S w1 \\<Longrightarrow> S w2 \\<Longrightarrow> S (w1 @ w2)\"\n\ninductive T where\n  empty: \"T []\"\n| betw_conc: \"T w1 \\<Longrightarrow> T w2 \\<Longrightarrow> T (w1 @ a # w2 @ [b])\"\n\nlemma T_S:  \"T w \\<Longrightarrow> S w\"\n  apply (induct rule: T.induct)\n  apply (rule S.empty)\n  apply (metis S.conc S.betw)\ndone\n\naxiomatization where \nT_app: \"T w1 \\<Longrightarrow> T w2 \\<Longrightarrow> T (w1 @ w2)\"\n\n  \nlemma S_T: \"S w \\<Longrightarrow> T w\"\n  apply (induct rule: S.induct)\n  apply (rule T.empty)\n  using T.simps append.left_neutral apply blast\n  apply (simp add: T_app)\ndone\n\ntheorem S_T_eq: \"S w = T w\"\n  apply auto\n  apply (rule S_T, assumption)\n  apply (rule T_S, assumption)\ndone", "meta": {"author": "awazoooo", "repo": "concrete_semantics_with_isabelle_hol", "sha": "229e0674abf4788b76febf2e276e212c788a197f", "save_path": "github-repos/isabelle/awazoooo-concrete_semantics_with_isabelle_hol", "path": "github-repos/isabelle/awazoooo-concrete_semantics_with_isabelle_hol/concrete_semantics_with_isabelle_hol-229e0674abf4788b76febf2e276e212c788a197f/my_proof/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7587641182717209}}
{"text": "theory tut03\nimports Main \"~~/src/HOL/IMP/ASM\" \"~~/src/HOL/IMP/AExp\"\nbegin\n\ninductive odd :: \"nat \\<Rightarrow> bool\" where\nodd1:  \"odd 1\"\n | odd_add: \"odd n \\<Longrightarrow> odd (n+2)\"\n\nthm odd1 odd_add\n\n\ninductive is_aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n  N: \"is_aval (N n) s n\"\n| V: \"is_aval (V x) s (s x)\"\n| P: \"\\<lbrakk> is_aval a1 s v1; is_aval a2 s v2 \\<rbrakk> \n  \\<Longrightarrow> is_aval (Plus a1 a2) s (v1+v2)\"\n\nlemma \"is_aval (Plus (N 2) (Plus (V x) (N 3))) s (2+(s x + 3))\"\n  apply (rule N V P)\n  apply (rule N V P)\n  apply (rule N V P)\n  apply (rule N V P)\n  apply (rule N V P)\n  (* or apply (intro is_aval.intros) *)\n  (* or apply (rule is_aval.intros)+ *)\n  (* or apply (rule N V P)+ *)\n  done\n\nnotepad begin\n  fix a b c d e f g h :: int\n  assume \"a=b\"\n  also assume \"b < c+d+e+f+g+h\"\n  also assume \"... \\<le> d\"\n  also assume \"d = e\"\n  finally have \"a < e\" .\nend\n\n\nlemma \"is_aval a s v \\<longleftrightarrow> aval a s = v\"\nproof \n  assume \"is_aval a s v\"\n  (*thus \"aval a s = v\" by induction auto*)\n  \n  thus \"aval a s = v\" \n  proof induction\n    print_cases\n    case (N n s) show ?case by simp\n      thm aval.simps\n  next\n    case (V x s) show ?case by simp\n  next\n    case (P a1 s v1 a2 v2)\n    have \"aval (Plus a1 a2) s = aval a1 s + aval a2 s\" by simp\n    also from P.IH have \"\\<dots> = v1 + v2\" by simp\n    finally show ?case .\n  qed\nnext\n  assume \"aval a s = v\" thus \"is_aval a s v\"\n  proof (induction a arbitrary: v)\n    case (N v) thus ?case by (simp add: is_aval.N)\n  next\n    case (V x) thus ?case \n      by (auto simp add: is_aval.V)\n  next\n    case (Plus a1 a2)\n    from Plus.prems have 1: \"v = aval a1 s + aval a2 s\" \n      by simp\n    \n      thm Plus.IH\n    show ?case\n      unfolding 1\n      apply (rule is_aval.P)\n      thm Plus.IH\n      apply (rule Plus.IH, simp)\n      apply (rule Plus.IH, simp)\n      done\n  qed\n    (*by (induction a arbitrary: v) (auto intro: N V P)*)\nqed    \n\n\n\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec1 (LOADI n) _ stk  =  Some (n # stk)\" |\n\"exec1 (LOAD x) s stk  =  Some (s(x) # stk)\" |\n\"exec1  ADD _ (a#b#stk)  =  Some ((a+b)#stk)\" |\n\"exec1  ADD _ _  =  None\"\n\ntext_raw{*}%endsnip*}\n\ntext_raw{*\\snip{ASMexecdef}{1}{2}{% *}\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec [] _ stk = Some stk\" |\n\"exec (i#is) s stk = (\n  case exec1 i s stk of\n    Some stk \\<Rightarrow> exec is s stk\n  | None \\<Rightarrow> None)\"\n\nlemma exec_append:\n  \"exec (is1@is2) s stk = (\n    case exec is1 s stk of\n      Some stk \\<Rightarrow> exec is2 s stk\n    | None \\<Rightarrow> None)\"\napply(induction is1 arbitrary: stk)\napply (auto split: option.split)\ndone\n\n\nlemma \"exec (comp a) s stk = Some (aval a s # stk)\"\n  apply (induction a arbitrary: stk)\n  apply (auto simp add: exec_append)\n  done\n\nend\n\n", "meta": {"author": "glimonta", "repo": "Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "save_path": "github-repos/isabelle/glimonta-Semantics", "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise3/tut03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.8479677564567913, "lm_q1q2_score": 0.7587526089348947}}
{"text": "theory Exp\n  imports Main\nbegin\nsection \\<open>Aexp\\<close>\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V v) s = s v\" |\n\"aval (Plus e1 e2) s = aval e1 s + aval e2 s\"\n\nvalue \"aval (Plus (N 3) (V ''x'')) (\\<lambda>x. 0)\"\nvalue \"aval (Plus (V ''x'') (V ''y'')) ((\\<lambda>u. 0) (''x'' := 7, ''y'' := 3))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2 :: int))\"\n  by auto\n \nvalue \"aval (Plus (V ''x'') (V ''y'')) ((<> (''x'' := 7)) (''y'' := 3))\"\nvalue \"aval (Plus (V ''x'') (V ''y'')) <''x'' := 7, ''y'' := 3>\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V v) = V v\" |\n\"asimp_const (Plus e1 e2) = \n  (case (asimp_const e1, asimp_const e2) of\n    (N n1, N n2) \\<Rightarrow> N (n1 + n2) |\n    (x1, x2)     \\<Rightarrow> Plus x1 x2)\"\n\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply(induct a)\n  by (auto split: aexp.split)\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N n1) (N n2) = N (n1 + n2)\" |\n\"plus (N n1) e = (if n1=0 then e else Plus (N n1) e)\" |\n\"plus e (N n2) = (if n2=0 then e else Plus e (N n2))\" |\n\"plus e1 e2 = Plus e1 e2\"\n\nlemma aval_plus: \n  \"aval (plus e1 e2) s = aval e1 s + aval e2 s\"\n  apply(induction e1 e2 rule: plus.induct)\n  by simp_all\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V v) = V v\" |\n\"asimp (Plus e1 e2) = plus (asimp e1) (asimp e2)\"\n\nlemma aval_simp[simp]:\n  \"aval (asimp a) s = aval a s\"\n  apply (induct a)\n  apply simp_all\n  by (simp add: aval_plus)\n\nsection \\<open>Bexp\\<close>\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc c) s = c\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b1 b2) s = (bval b1 s \\<and> bval b2 s)\" |\n\"bval (Less a1 a2) s = (aval a1 s < aval a2 s)\"\n\ntext \\<open>some test of bexp\\<close>\nvalue \"bval (Bc True) (\\<lambda>x. 0)\"\nvalue \"bval (Not (Bc True)) (\\<lambda>x. 0)\"\nvalue \"bval (And (Bc True) (Bc False)) (\\<lambda>x. 0)\"\nvalue \"bval (And (Bc True) (Bc True)) (\\<lambda>x. 0)\"\nvalue \"bval (Less (N 1) (N 0)) (\\<lambda>x. 0)\"\nvalue \"bval (Less (N 0) (N 1)) (\\<lambda>x. 0)\"\n\nsubsection \\<open>Constant Folding\\<close>\nfun \"not\" :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\n\nlemma bval_not[simp]:\n  \"bval (not b) s = (\\<not> (bval b s))\"\n  apply (induct b)\n  by auto\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b1 b2 = And b1 b2\"\n\nlemma bval_and[simp]:\n  \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\n  apply (induction b1 b2 rule: and.induct)\n  by auto\n\nfun \"or\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"or (Bc True) b = Bc True\" |\n\"or b (Bc True) = Bc True\" |\n\"or (Bc False) b = b\" |\n\"or b (Bc False) = b\" |\n\"or b1 b2 = not (and (not b1) (not b2))\"\n\nlemma bval_or:\n  \"bval (or b1 b2) s = (bval b1 s \\<or> bval b2 s)\"\n  apply (induction b1 b2 rule: or.induct)\n  by auto\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n1) (N n2) = Bc (n1 < n2)\" |\n\"less a1 a2 = Less a1 a2\"\n\nlemma bval_less[simp]:\n  \"bval (less a1 a2) s = (aval a1 s < aval a2 s)\"\n  apply (induction a1 a2 rule: less.induct)\n  by auto\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc c) = Bc c\" |\n\"bsimp (Not b) = not (bsimp b)\" |\n\"bsimp (And b1 b2) = and (bsimp b1) (bsimp b2)\" |\n\"bsimp (Less a1 a2) = less (asimp a1) (asimp a2)\"\n\nlemma bsimp_eq:\n  \"bval (bsimp b) s = bval b s\"\n  apply (induct b rule: bsimp.induct)\n  by simp_all\n\n\nend", "meta": {"author": "3-F", "repo": "concrete-semanitcs", "sha": "0a35764f047d93b3069342ddea34a17dd0cbe414", "save_path": "github-repos/isabelle/3-F-concrete-semanitcs", "path": "github-repos/isabelle/3-F-concrete-semanitcs/concrete-semanitcs-0a35764f047d93b3069342ddea34a17dd0cbe414/My_IMP/Exp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8479677506936878, "lm_q1q2_score": 0.7587526085362959}}
{"text": "theory Chapter4\n  imports Main\nbegin\n\n-- \"Chapter 4\"\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume 0: \"surj f\"\n  from 0 have 1: \"\\<forall> A. \\<exists> a. A = f a\" by (simp add: surj_def)\n  from 1 have 2: \"\\<exists> a. {x. x \\<notin> f x} = f a\" by blast\n  from 2 show \"False\" by blast\nqed\n\nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  from this have \"\\<exists> a. {x. x \\<notin> f x} = f a\" by auto\n  from this show False by blast\nqed\n  \nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  hence \"\\<exists> a. {x. x \\<notin> f x} = f a\" by auto\n  thus False by blast\nqed\n  \nlemma\n  fixes f :: \"'a \\<Rightarrow> 'a set\"\n  assumes s: \"surj f\"\n  shows False\nproof -\n  have \"\\<exists> a. {x. x \\<notin> f x} = f a\" using s by auto\n  thus False by blast\nqed\n  \nlemma \"\\<not> surj(f :: 'a \\<Rightarrow> 'a set)\"\nproof\n  assume \"surj f\"\n  hence \"\\<exists> a. {x. x \\<notin> f x} = f a\" by auto\n  then obtain a where \"{x. x \\<notin> f x} = f a\" by blast\n  hence \"a \\<notin> f a \\<longleftrightarrow> a \\<in> f a\" by blast\n  thus False by blast\nqed\n  \n-- \"Exercise 4.1\"\n\nlemma\n  assumes T: \"\\<forall> x y. T x y \\<or> T y x\"\n  and A: \"\\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n  and TA: \"\\<forall> x y. T x y \\<longrightarrow> A x y\" and \"A x y\"\n  shows \"T x y\"\nproof (rule ccontr)\n  assume \"\\<not> T x y\"\n  from this T have \"T y x\" by blast\n  from this TA have \"A y x\" by blast\n  from A this `A x y` have \"x = y\" by blast\n  from this `T y x` have \"T x y\" by blast\n  from this `\\<not> T x y` show False by blast\nqed\n\nfind_theorems \"(EX x . _) \\<or> (EX y . _)\"\nfind_theorems \"(_ = _) \\<Longrightarrow> (_ = _)\"\nfind_theorems \"?a \\<Longrightarrow> ?a \\<or> ?b\"\nthm even_two_times_div_two\nthm length_drop\n  \nlemma\n  \"  (\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs)\n   \\<or> (\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs + 1)\"\nproof -\n  obtain zs where zs: \"zs = drop (length xs - length xs div 2) xs\" by simp\n  obtain ys where ys: \"ys = take (length xs - length xs div 2) xs\" by simp\n  show ?thesis proof cases\n    assume even: \"even (length xs)\"\n    from zs ys have concat: \"xs = ys @ zs\" by simp\n    from concat have sum: \"length xs = length ys + length zs\" by simp\n    from zs even sum have length: \"length ys = length zs\"\n      by (metis add_diff_cancel_right' even_two_times_div_two length_drop mult_2)\n    from concat length show ?thesis by auto\n  next\n    assume odd: \"odd (length xs)\"\n    from zs ys have concat: \"xs = ys @ zs\" by simp\n    from concat have sum: \"length xs = length ys + length zs\" by simp\n    from zs odd sum have length: \"length ys = length zs + 1\"\n      using odd_ex_decrement by fastforce\n    from concat length show ?thesis by auto\n  qed\nqed\n  \ninductive ev where\n  ev0: \"ev 0\" |\n  evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n  \nlemma \"~ ev (Suc (Suc (Suc 0)))\" (is \"\\<not> ?P\")\nproof\n  assume P: \"?P\"\n  hence \"ev (Suc 0)\" by cases\n  thus False by cases\nqed\n\nlemma assumes a: \"ev (Suc (Suc n))\" shows \"ev n\"\nproof -\n  from a show \"ev n\" by cases\nqed\n\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\"\n  thus False proof cases\n    case evSS\n    thus False proof cases qed\n  qed\nqed\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  star_refl: \"star r x x\" |\n  star_step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n  iter_refl: \"iter r 0 x x\" |\n  iter_step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case (iter_refl r x)\n  show \"star r x x\" by (rule star_refl)\nnext\n  case (iter_step r x y n z)\n  assume xy: \"r x y\"\n  assume yz: \"star r y z\"\n  show \"star r x z\" by (rule star_step[OF xy yz])\nqed\n  \nfun elems where\n  \"elems [] = {}\" |\n  \"elems (x # xs) = insert x (elems xs)\"\n\nlemma \"\\<exists> x. x = 1\" proof - show \"\\<exists> x. x = 1\" proof show \"1 = 1\" by rule qed qed\nthm exI\n\nlemma \"\\<exists> x. x = 1\" by (simp add: exI[of _ 1])\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\n  case Nil\n  assume \"x \\<in> elems []\"\n  then have False by simp\n  then show ?case by safe\nnext\n  case (Cons a xs)\n  assume ind: \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\n  assume elem: \"x \\<in> elems (a # xs)\"\n  show ?case proof cases\n    assume eq: \"x = a\"\n    obtain ys :: \"'a list\" where ys: \"ys = []\" by simp\n    obtain zs where zs: \"zs = xs\" by simp\n    have \"a # xs = ys @ x # zs \\<and> x \\<notin> elems ys\" by (simp add: ys zs eq)\n    thus ?case by auto\n  next\n    assume neq: \"x \\<noteq> a\"\n    with elem have \"x \\<in> elems xs\" by simp\n    with ind have \"\\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\" (is \"\\<exists> ys. ?P ys\") by simp\n    then obtain ys where \"?P ys\" by blast\n    with neq show \"\\<exists>ys zs. a # xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\n      using Cons_eq_appendI by force\n  qed\nqed\n\ndatatype alpha = a | b\n\nfunction balanced where\n  balanced_nil: \"balanced 0 [] = True\" |\n  balanced_a: \"balanced n (a # xs) = balanced (Suc n) xs\" |\n  balanced_b: \"balanced (Suc n) (b # xs) = balanced n xs\" |\n  unbalanced_a: \"balanced (Suc _) [] = False\" |\n  unbalanced_b: \"balanced 0 (b # _) = False\"\n  by (pat_completeness, auto)\ntermination by lexicographic_order\n\ninductive S where\n  S_empty: \"S []\" |\n  S_match: \"S x \\<Longrightarrow> S (a # x @ [b])\" |\n  S_concat: \"S x \\<Longrightarrow> S y \\<Longrightarrow> S (x @ y)\"\n\nlemma append_split: \"length cs < length as \\<Longrightarrow> as @ bs = cs @ ds \\<Longrightarrow> \\<exists>es. as = cs @ es\"\n  by (metis add_diff_inverse_nat append_Nil2 append_eq_append_conv_if\n            drop_all length_drop less_imp_not_less)\n\nlemma S_insert: \"S (x @ y) \\<Longrightarrow> S (x @ [a, b] @ y)\"\nproof (induction \"x @ y\" arbitrary: x y rule: S.induct)\n  fix x y :: \"alpha list\"\n  assume \"[] = x @ y\"\n  then have \"x = [] \\<and> y = []\" by simp\n  then show \"S (x @ [a, b] @ y)\" using S_empty S_match by force\nnext\n  fix z x y\n  assume IH: \"S z\" \"\\<And>x y. z = x @ y \\<Longrightarrow> S (x @ [a, b] @ y)\"\n  assume as: \"a # z @ [b] = x @ y\"\n  show \"S (x @ [a, b] @ y)\" proof (cases; cases)\n    assume \"x = []\" \"y = []\"\n    then show ?thesis using as by simp\n  next\n    assume \"x = []\" \"y \\<noteq> []\"\n    then show ?thesis using as IH by (metis S_concat S_empty S_match append_Nil)\n  next\n    assume \"x \\<noteq> []\" \"y = []\"\n    then show ?thesis using as IH by (metis S_concat S_empty S_match append_Nil append_Nil2)\n  next\n    assume not_empty: \"x \\<noteq> []\" \"y \\<noteq> []\"\n    obtain xx where xx: \"x = a # xx\" using not_empty as by (metis append_eq_Cons_conv)\n    obtain yy where yy: \"y = yy @ [b]\" using not_empty as\n      by (metis last.simps last_appendR snoc_eq_iff_butlast)\n    have \"S (xx @ [a, b] @ yy)\" using xx yy IH as by simp\n    then show ?thesis using xx yy by (metis S.simps append.assoc append_Cons)\n  qed\nnext\n  fix u v x y\n  assume IHu: \"S u\" \"\\<And>x y. u = x @ y \\<Longrightarrow> S (x @ [a, b] @ y)\"\n  assume IHv: \"S v\" \"\\<And>x y. v = x @ y \\<Longrightarrow> S (x @ [a, b] @ y)\"\n  assume as: \"u @ v = x @ y\"\n  show \"S (x @ [a, b] @ y)\" proof cases\n    assume \"length x < length u\"\n    then obtain w where w: \"u = x @ w\" using append_split as by blast\n    then have \"S (x @ [a, b] @ w)\" using IHu by blast\n    then have \"S ((x @ [a, b] @ w) @ v)\" using IHv S_concat by blast\n    then show \"S (x @ [a, b] @ y)\" using as w by simp\n  next\n    assume \"~ length x < length u\"\n    then obtain w where w: \"v = w @ y\" using as\n      by (metis append_eq_append_conv_if le_imp_less_Suc less_antisym)\n    then have \"S (w @ [a, b] @ y)\" using IHv by blast\n    then have \"S (u @ (w @ [a, b] @ y))\" using IHu S_concat by blast\n    then show \"S (x @ [a, b] @ y)\" using as w by force\n  qed\nqed\n\nlemma balanced_wrap: \"balanced n w \\<Longrightarrow> balanced (Suc n) (w @ [b])\"\n  by (induction n w rule: balanced.induct; simp)\n\nlemma balanced_concat: \"balanced n x \\<Longrightarrow> balanced 0 y \\<Longrightarrow> balanced n (x @ y)\"\n  by (induction n x rule: balanced.induct; simp)\n\nlemma replicate_split: \"m < n \\<Longrightarrow> replicate n x = replicate m x @ replicate (n - m) x\"\n  by (metis add_diff_inverse_nat less_imp_not_less replicate_add)\n\ntheorem \"balanced n w = S (replicate n a @ w)\" (is \"?L = ?R\")\nproof\n  show \"?L \\<Longrightarrow> ?R\" proof (induction n w rule: balanced.induct)\n    fix n xs\n    assume IH: \"balanced (Suc n) xs \\<Longrightarrow> S (replicate (Suc n) a @ xs)\"\n    assume \"balanced n (a # xs)\"\n    then show \"S (replicate n a @ a # xs)\" using IH\n      by (simp add: replicate_app_Cons_same)\n  next\n    fix n xs\n    assume IH: \"balanced n xs \\<Longrightarrow> S (replicate n a @ xs)\"\n    assume \"balanced (Suc n) (b # xs)\"\n    then show \"S (replicate (Suc n) a @ b # xs)\" using IH S_insert\n      by (metis balanced_b append.assoc append_Cons append_Nil2 append_eq_append_conv_if replicate_Suc replicate_append_same)\n  next\n    fix n\n    assume \"balanced (Suc n) []\"\n    then show \"S (replicate (Suc n) a @ [])\" by simp\n  next\n    fix xs\n    assume \"balanced 0 (b # xs)\"\n    then show \"S (replicate 0 a @ b # xs)\" by simp\n  next\n    show \"S (replicate 0 a @ [])\" using S_empty by simp\n  qed\nnext\n  show \"?R \\<Longrightarrow> ?L\"\n  proof (induction \"replicate n a @ w\" arbitrary: n w rule: S.induct)\n    fix n w\n    assume \"[] = replicate n a @ w\"\n    then have \"w = [] \\<and> n = 0\" by simp\n    then show \"balanced n w\" by simp\n  next\n    fix x n w\n    assume IH: \"S x\" \"\\<And>n w. x = replicate n a @ w \\<Longrightarrow> balanced n w\"\n    assume as: \"a # x @ [b] = replicate n a @ w\"\n    show \"balanced n w\" proof (cases n)\n      assume \"n = 0\"\n      have \"balanced 0 x\" using IH by simp\n      then show \"balanced n w\" using \\<open>n=0\\<close> balanced_wrap as by force\n    next\n      fix m\n      assume m: \"n = Suc m\"\n      then obtain y where y: \"y @ [b] = w\" using as\n        by (metis (mono_tags) alpha.distinct(1) append_butlast_last_id append_is_Nil_conv\n                  last_ConsR last_append last_snoc list.discI replicate_append_same)\n      then have \"x = replicate m a @ y\" using m as by force\n      then have \"balanced m y\" using IH by blast\n      then show \"balanced n w\" using m y balanced_wrap by blast\n    qed\n  next\n    fix n w x y\n    assume IHx: \"S x\" \"\\<And>n w. x = replicate n a @ w \\<Longrightarrow> balanced n w\"\n    assume IHy: \"S y\" \"\\<And>n w. y = replicate n a @ w \\<Longrightarrow> balanced n w\"\n    assume as: \"x @ y = replicate n a @ w\"\n    show \"balanced n w\" proof cases\n      assume \"x = []\"\n      then show \"balanced n w\" using IHy as by simp\n    next\n      assume x_not_nil: \"x \\<noteq> []\"\n      show \"balanced n w\" proof cases\n        assume \"n > length x\"\n        then have \"x @ y = replicate (length x) a @ replicate (n - length x) a @ w\"\n          using as replicate_split by simp\n        then have \"x = replicate (length x) a\" by simp\n        then have False using x_not_nil IHx\n          by (metis unbalanced_a Nitpick.size_list_simp(2) append_Nil2)\n        then show \"balanced n w\" by fast\n      next\n        assume small_n: \"\\<not> length x < n\"\n        then obtain z where z: \"x = replicate n a @ z\" using as append_split\n          by (metis append_Nil2 append_eq_append_conv_if length_replicate linorder_neqE_nat)\n        then have left: \"balanced n z\" using IHx by blast\n        have right: \"balanced 0 y\" using IHy by simp\n        have w: \"w = z @ y\" using z as by simp\n        from left right w show \"balanced n w\" using balanced_concat by simp\n      qed\n    qed\n  qed\nqed\n", "meta": {"author": "AtnNn", "repo": "isabelle-learn", "sha": "da71fb60bea0089fe473c104be16a4545e031be8", "save_path": "github-repos/isabelle/AtnNn-isabelle-learn", "path": "github-repos/isabelle/AtnNn-isabelle-learn/isabelle-learn-da71fb60bea0089fe473c104be16a4545e031be8/programming-and-proving/Chapter4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099168, "lm_q2_score": 0.8824278618165526, "lm_q1q2_score": 0.7585912452436643}}
{"text": "header{*Basics needed*}\n\ntheory PerfectBasics\nimports Main \"~~/src/HOL/Number_Theory/Primes\" \"~~/src/HOL/Algebra/Exponent\"\nbegin\n\nlemma setsum_mono2_nat: \"finite (B::nat set) \\<Longrightarrow> A <= B \\<Longrightarrow> \\<Sum> A <= \\<Sum> B\"\nby (auto simp add: setsum_mono2)\n\nlemma seteq_imp_setsumeq: \"A=B ==> \\<Sum> A = \\<Sum> B\" by simp\n\n\nlemma exp_is_max_div:\n   assumes m0:\"m>0\" and p: \"prime p\"\n   shows \"~ p dvd (m div (p^(exponent p m)))\"\nproof (rule ccontr)\n assume \"~ ~ p dvd (m div (p^(exponent p m)))\"\n hence a:\"p dvd (m div (p^(exponent p m)))\" by auto\n from m0 have \"p^(exponent p m) dvd m\" by (auto simp add: power_exponent_dvd)\n with a have \"p*(p^exponent p m) dvd m\"\n   by (metis (full_types) div_dvd_div div_mult_self2_is_id dvd_triv_right neq0_conv p \n      zero_less_prime_power)\n with p have \"m=0\" by (auto simp add: power_Suc_exponent_Not_dvd)\n with m0 show \"False\" by auto\nqed\n\nlemma coprime_exponent:\n  assumes p:\"prime p\" and m:\"m>0\"\n  shows \"coprime p (m div (p^(exponent p m)))\"\nproof (rule ccontr)\n  assume \" ~ coprime p (m div p ^ exponent p m)\"\n  hence \"EX q. prime q & q dvd p & q dvd (m div (p^(exponent p m)))\"\n    by (metis dvd.dual_order.refl p prime_imp_coprime_nat)\n  hence \"EX q. q = p & q dvd (m div (p^(exponent p m)))\"\n    by (metis one_not_prime_nat p prime_nat_def)\n  hence  \"EX q. p dvd (m div (p^(exponent p m)))\" by auto\n  hence \"p dvd (m div (p^(exponent p m)))\" by auto\n  with p m show \"False\" by (auto simp add: exp_is_max_div)\nqed\n\nlemma add_mult_distrib_three: \"(x::nat)*(a+b+c)=x*a+x*b+x*c\" \nproof -\n  have \"(x::nat)*(a+b+c) = x*((a+b)+c)\" by auto\n  hence \"x*(a+b+c) = x*(a+b)+x*c\" by (metis add_mult_distrib2 add.commute add.left_commute)\n  thus \"x*(a+b+c) = x*a+x*b+x*c\" by (metis add_mult_distrib2 add.commute add.left_commute) \nqed\n\nlemma nat_interval_minus_zero: \"{0..Suc n} = {0} Un {Suc 0..Suc n}\" by auto\nlemma nat_interval_minus_zero2:\n assumes \"n>0\"\n shows \"{0..n} = {0} Un {Suc 0..n}\" by (auto simp add: nat_interval_minus_zero)\n\ntheorem simplify_sum_of_powers: \"(x - 1::nat) * (\\<Sum>i=0 .. n . x^i)  = x^(n + 1) - 1\" (is \"?l = ?r\")\nproof (cases)\n  assume \"n = 0\"\n  thus \"?l = x^(n+1) - 1\" by auto\n  next\n  assume \"n~=0\"\n  hence n0: \"n>0\" by auto \n  have \"?l  = (x::nat)*(\\<Sum>i=0 .. n . x^i) - (\\<Sum>i=0 .. n . x^i)\"\n    by (metis diff_mult_distrib nat_mult_1)\n  also have \"... = (\\<Sum>i=0 .. n . x^(Suc i))    - (\\<Sum>i=0 .. n . x^i)\"\n    by (simp add: setsum_right_distrib)\n  also have \"... = (\\<Sum>i=Suc 0 .. Suc n . x^i)  - (\\<Sum>i=0 .. n . x^i)\"\n    by (metis setsum_shift_bounds_cl_Suc_ivl)\n  also with n0\n  have \"... = ((\\<Sum>i=Suc 0 .. n. x^i)+x^(Suc n)) - (x^0 + (\\<Sum>i=Suc 0 .. n. x^i))\"\n    by (auto simp add: setsum.union_disjoint nat_interval_minus_zero2)\n  finally show \"?thesis\" by auto\nqed\n\nend", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Perfect-Number-Thm/PerfectBasics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582497090322, "lm_q2_score": 0.8152324826183822, "lm_q1q2_score": 0.758539788883049}}
{"text": "theory properties\n  imports \"../TBAs/closure_algebra\"\nbegin\n\n(**We investigate some well known topological properties of sets drawing upon closure algebras.*)\n\n(**Sets with an empty interior are called boundary.*)\ndefinition boundary (\"boundary[_]\") \n  where \"boundary[\\<C>] A \\<equiv> \\<I>[\\<C>] A \\<approx> \\<^bold>\\<bottom>\"\n\n(**Boundary sets can be equivalently defined as the fixed points of the border operator.*)\nlemma boundary_def2: \"Cl_2 \\<C> \\<Longrightarrow> boundary[\\<C>] = Br[\\<C>]\" by (simp add: Br_Iempty boundary_def ext)\n\n(**Sets whose closure is the whole domain are called dense.*)\ndefinition dense (\"dense[_]\") \n  where \"dense[\\<C>] A \\<equiv> \\<C> A \\<approx> \\<^bold>\\<top>\"\n\n(**A set is dense iff its complement is boundary.*)\nlemma dense_def2: \"dense[\\<C>] A = boundary[\\<C>] (\\<^bold>\\<midarrow>A)\" unfolding dense_def boundary_def by (simp add: bottom_def compl_def op_dual_def setequ_char top_def)\n(**Dense sets can be equivalently defined as the fixed points of the dual-border operator.*)\nlemma dense_def3: \"Cl_2 \\<C> \\<Longrightarrow> dense[\\<C>] = fp (\\<B>[\\<C>])\\<^sup>d\" by (metis (full_types) boundary_def2 dense_def2 fp3 fp_d op_equal_equ setequ_char setequ_equ)\n\n\n(**Sets whose closure is a boundary set are called nowhere-dense.*)\ndefinition nowhereDense (\"nowhereDense[_]\") \n  where \"nowhereDense[\\<C>] A \\<equiv> boundary[\\<C>] (\\<C> A)\"\n\n(**For closed sets the properties of boundary and nowhere-dense collapse.*)\nlemma Cl_bnd_nwdn: \"\\<forall>A. Cl[\\<C>] A \\<longrightarrow> boundary[\\<C>] A = nowhereDense[\\<C>] A\" by (simp add: fixpoint_pred_def nowhereDense_def setequ_equ)\n\n(**Let us introduce a definition for the sets mentioned above (nowhere-dense and closed).*)\ndefinition nowhereDenseCl (\"nowhereDenseCl[_]\") \n  where \"nowhereDenseCl[\\<C>] A \\<equiv> nowhereDense[\\<C>] A \\<and> Cl[\\<C>] A\"\n\n(**A set is nowhere-dense and closed iff its complement is dense and open.*)\nlemma nowhereDenseCl_def2: \"nowhereDenseCl[\\<C>] A = (dense[\\<C>] (\\<^bold>\\<midarrow>A) \\<and> Op[\\<C>] (\\<^bold>\\<midarrow>A))\" by (metis BA_dn Cl_bnd_nwdn OpCldual dense_def2 nowhereDenseCl_def)\n(**Nowhere-dense closed sets can be equivalently defined as the fixed points of the frontier operator.*)\nlemma nowhereDenseCl_def3: \"Cl_2 \\<C> \\<Longrightarrow> nowhereDenseCl[\\<C>] = Fr[\\<C>]\" using Cl_bnd_nwdn Fr_ClBr boundary_def2 nowhereDenseCl_def by fastforce\n\nend", "meta": {"author": "davfuenmayor", "repo": "basic-topology", "sha": "45e6791becf6a2dfb174c9f8641b8c6816773529", "save_path": "github-repos/isabelle/davfuenmayor-basic-topology", "path": "github-repos/isabelle/davfuenmayor-basic-topology/basic-topology-45e6791becf6a2dfb174c9f8641b8c6816773529/Topology/properties.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.8397339716830605, "lm_q1q2_score": 0.7585268252353938}}
{"text": "(*<*)\ntheory Table\n  imports Main\nbegin\n(*>*)\n\nsection \\<open>Finite Tables\\<close>\n\nprimrec tabulate :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> 'a list\" where\n  \"tabulate f x 0 = []\"\n| \"tabulate f x (Suc n) = f x # tabulate f (Suc x) n\"\n\nlemma tabulate_alt: \"tabulate f x n = map f [x ..< x + n]\"\n  by (induct n arbitrary: x) (auto simp: not_le Suc_le_eq upt_rec)\n\nlemma length_tabulate[simp]: \"length (tabulate f x n) = n\"\n  by (induction n arbitrary: x) simp_all\n\nlemma map_tabulate[simp]: \"map f (tabulate g x n) = tabulate (\\<lambda>x. f (g x)) x n\"\n  by (induction n arbitrary: x) simp_all\n\nlemma nth_tabulate[simp]: \"k < n \\<Longrightarrow> tabulate f x n ! k = f (x + k)\"\nproof (induction n arbitrary: x k)\n  case (Suc n)\n  then show ?case by (cases k) simp_all\nqed simp\n\ntype_synonym 'a tuple = \"'a option list\"\ntype_synonym 'a table = \"'a tuple set\"\n\ndefinition wf_tuple :: \"nat \\<Rightarrow> nat set \\<Rightarrow> 'a tuple \\<Rightarrow> bool\" where\n  \"wf_tuple n V x \\<longleftrightarrow> length x = n \\<and> (\\<forall>i<n. x!i = None \\<longleftrightarrow> i \\<notin> V)\"\n\ndefinition table :: \"nat \\<Rightarrow> nat set \\<Rightarrow> 'a table \\<Rightarrow> bool\" where\n  \"table n V X \\<longleftrightarrow> (\\<forall>x\\<in>X. wf_tuple n V x)\"\n\ndefinition \"empty_table = {}\"\n\ndefinition \"unit_table n = {replicate n None}\"\n\ndefinition \"singleton_table n i x = {tabulate (\\<lambda>j. if i = j then Some x else None) 0 n}\"\n\nlemma in_empty_table[simp]: \"\\<not> x \\<in> empty_table\"\n  unfolding empty_table_def by simp\n\nlemma empty_table[simp]: \"table n V empty_table\"\n  unfolding table_def empty_table_def by simp\n\nlemma unit_table_wf_tuple[simp]: \"V = {} \\<Longrightarrow> x \\<in> unit_table n \\<Longrightarrow> wf_tuple n V x\"\n  unfolding unit_table_def wf_tuple_def by simp\n\nlemma unit_table[simp]: \"V = {} \\<Longrightarrow> table n V (unit_table n)\"\n  unfolding table_def by simp\n\nlemma in_unit_table: \"v \\<in> unit_table n \\<longleftrightarrow> wf_tuple n {} v\"\n  unfolding unit_table_def wf_tuple_def by (auto intro!: nth_equalityI)\n\nlemma singleton_table_wf_tuple[simp]: \"V = {i} \\<Longrightarrow> x \\<in> singleton_table n i z \\<Longrightarrow> wf_tuple n V x\"\n  unfolding singleton_table_def wf_tuple_def by simp\n\nlemma singleton_table[simp]: \"V = {i} \\<Longrightarrow> table n V (singleton_table n i z)\"\n  unfolding table_def by simp\n\nlemma table_Un[simp]: \"table n V X \\<Longrightarrow> table n V Y \\<Longrightarrow> table n V (X \\<union> Y)\"\n  unfolding table_def by auto\n\nlemma wf_tuple_length: \"wf_tuple n V x \\<Longrightarrow> length x = n\"\n  unfolding wf_tuple_def by simp\n\n\nfun join1 :: \"'a tuple \\<times> 'a tuple \\<Rightarrow> 'a tuple option\" where\n  \"join1 ([], []) = Some []\"\n| \"join1 (None # xs, None # ys) = map_option (Cons None) (join1 (xs, ys))\"\n| \"join1 (Some x # xs, None # ys) = map_option (Cons (Some x)) (join1 (xs, ys))\"\n| \"join1 (None # xs, Some y # ys) = map_option (Cons (Some y)) (join1 (xs, ys))\"\n| \"join1 (Some x # xs, Some y # ys) = (if x = y\n    then map_option (Cons (Some x)) (join1 (xs, ys))\n    else None)\"\n| \"join1 _ = None\"\n\ndefinition join :: \"'a table \\<Rightarrow> bool \\<Rightarrow> 'a table \\<Rightarrow> 'a table\" where\n  \"join A pos B = (if pos then Option.these (join1 ` (A \\<times> B))\n    else A - Option.these (join1 ` (A \\<times> B)))\"\n\nlemma join_True_code[code]: \"join A True B = (\\<Union>a \\<in> A. \\<Union>b \\<in> B. set_option (join1 (a, b)))\"\n  unfolding join_def by (force simp: Option.these_def image_iff)\n\nlemma join_False_alt: \"join X False Y = X - join X True Y\"\n  unfolding join_def by auto\n\n\n\nlemma join_False_code[code]: \"join A False B = {a \\<in> A. \\<forall>b \\<in> B. join1 (a, b) \\<noteq> Some a}\"\n  unfolding join_False_alt join_True_code\n  by (auto simp: Option.these_def image_iff dest: self_join1)\n\nlemma wf_tuple_Nil[simp]: \"wf_tuple n A [] = (n = 0)\"\n  unfolding wf_tuple_def by auto\n\nlemma Suc_pred': \"Suc (x - Suc 0) = (case x of 0 \\<Rightarrow> Suc 0 | _ \\<Rightarrow> x)\"\n  by (auto split: nat.splits)\n\nlemma wf_tuple_Cons[simp]:\n  \"wf_tuple n A (x # xs) \\<longleftrightarrow> ((if x = None then 0 \\<notin> A else 0 \\<in> A) \\<and>\n   (\\<exists>m. n = Suc m \\<and> wf_tuple m ((\\<lambda>x. x - 1) ` (A - {0})) xs))\"\n  unfolding wf_tuple_def\n  by (auto 0 3 simp: nth_Cons image_iff Ball_def gr0_conv_Suc Suc_pred' split: nat.splits)\n\nlemma join1_wf_tuple:\n  \"join1 (v1, v2) = Some v \\<Longrightarrow> wf_tuple n A v1 \\<Longrightarrow> wf_tuple n B v2 \\<Longrightarrow> wf_tuple n (A \\<union> B) v\"\n  by (induct \"(v1, v2)\" arbitrary: n v v1 v2 A B rule: join1.induct)\n    (auto simp: image_Un Un_Diff split: if_splits)\n\nlemma join_wf_tuple: \"x \\<in> join X b Y \\<Longrightarrow>\n  \\<forall>v \\<in> X. wf_tuple n A v \\<Longrightarrow> \\<forall>v \\<in> Y. wf_tuple n B v \\<Longrightarrow> (\\<not> b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow> A \\<union> B = C \\<Longrightarrow> wf_tuple n C x\"\n  unfolding join_def\n  by (fastforce simp: Option.these_def image_iff sup_absorb1 dest: join1_wf_tuple split: if_splits)\n\nlemma join_table: \"table n A X \\<Longrightarrow> table n B Y \\<Longrightarrow> (\\<not> b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow> A \\<union> B = C \\<Longrightarrow>\n  table n C (join X b Y)\"\n  unfolding table_def by (auto elim!: join_wf_tuple)\n\nlemma wf_tuple_Suc: \"wf_tuple (Suc m) A a \\<longleftrightarrow> a \\<noteq> [] \\<and>\n   wf_tuple m ((\\<lambda>x. x - 1) ` (A - {0})) (tl a) \\<and> (0 \\<in> A \\<longleftrightarrow> hd a \\<noteq> None)\"\n  by (cases a) (auto simp: nth_Cons image_iff split: nat.splits)\n\nlemma table_project: \"table (Suc n) A X \\<Longrightarrow> table n ((\\<lambda>x. x - Suc 0) ` (A - {0})) (tl ` X)\"\n  unfolding table_def\n  by (auto simp: wf_tuple_Suc)\n\ndefinition restrict where\n  \"restrict A v = map (\\<lambda>i. if i \\<in> A then v ! i else None) [0 ..< length v]\"\n\nlemma restrict_Nil[simp]: \"restrict A [] = []\"\n  unfolding restrict_def by auto\n\nlemma restrict_Cons[simp]: \"restrict A (x # xs) =\n  (if 0 \\<in> A then x # restrict ((\\<lambda>x. x - 1) ` (A - {0})) xs else None # restrict ((\\<lambda>x. x - 1) ` A) xs)\"\n  unfolding restrict_def\n  by (auto simp: map_upt_Suc image_iff Suc_pred' Ball_def simp del: upt_Suc split: nat.splits)\n\nlemma wf_tuple_restrict: \"wf_tuple n B v \\<Longrightarrow> A \\<inter> B = C \\<Longrightarrow> wf_tuple n C (restrict A v)\"\n  unfolding restrict_def wf_tuple_def by auto\n\nlemma wf_tuple_restrict_simple: \"wf_tuple n B v \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> wf_tuple n A (restrict A v)\"\n  unfolding restrict_def wf_tuple_def by auto\n\nlemma nth_restrict: \"i \\<in> A \\<Longrightarrow> i < length v \\<Longrightarrow> restrict A v ! i = v ! i\"\n  unfolding restrict_def by auto\n\nlemma restrict_eq_Nil[simp]: \"restrict A v = [] \\<longleftrightarrow> v = []\"\n  unfolding restrict_def by auto\n\nlemma length_restrict[simp]: \"length (restrict A v) = length v\"\n  unfolding restrict_def by auto\n\nlemma join1_Some_restrict:\n  fixes x y :: \"'a tuple\"\n  assumes \"wf_tuple n A x\" \"wf_tuple n B y\"\n  shows \"join1 (x, y) = Some z \\<longleftrightarrow> wf_tuple n (A \\<union> B) z \\<and> restrict A z = x \\<and> restrict B z = y\"\n  using assms\nproof (induct \"(x, y)\" arbitrary: n x y z A B rule: join1.induct)\n  case (2 xs ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nnext\n  case (3 x xs ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nnext\n  case (4 xs y ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nnext\n  case (5 x xs y ys)\n  then show ?case\n    by (cases z) (auto 4 0 simp: image_Un Un_Diff)+\nqed auto\n\nlemma restrict_idle: \"wf_tuple n A v \\<Longrightarrow> restrict A v = v\"\n  by (induct v arbitrary: n A) (auto split: if_splits)\n\nlemma map_the_restrict:\n  \"i \\<in> A \\<Longrightarrow> map the (restrict A v) ! i = map the v ! i\"\n  by (induct v arbitrary: A i) (auto simp: nth_Cons' gr0_conv_Suc split: option.splits)\n\n\n\nlemma join_restrict_table:\n  assumes \"table n A X\" \"table n B Y\" \"\\<not> b \\<Longrightarrow> B \\<subseteq> A\"\n  shows \"v \\<in> join X b Y \\<longleftrightarrow>\n    wf_tuple n (A \\<union> B) v \\<and> restrict A v \\<in> X \\<and> (if b then restrict B v \\<in> Y else restrict B v \\<notin> Y)\"\n  using assms unfolding table_def\n  by (simp add: join_restrict)\n\nlemma join_restrict_annotated:\n  fixes X Y :: \"'a tuple set\"\n  assumes \"\\<not> b =simp=> B \\<subseteq> A\"\n  shows \"join {v. wf_tuple n A v \\<and> P v} b {v. wf_tuple n B v \\<and> Q v} =\n    {v. wf_tuple n (A \\<union> B) v \\<and> P (restrict A v) \\<and> (if b then Q (restrict B v) else \\<not> Q (restrict B v))}\"\n  using assms\n  by (intro set_eqI, subst join_restrict) (auto simp: wf_tuple_restrict_simple simp_implies_def)\n\nlemma in_joinI: \"table n A X \\<Longrightarrow> table n B Y \\<Longrightarrow> (\\<not>b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow> wf_tuple n (A \\<union> B) v \\<Longrightarrow>\n  restrict A v \\<in> X \\<Longrightarrow> (b \\<Longrightarrow> restrict B v \\<in> Y) \\<Longrightarrow> (\\<not>b \\<Longrightarrow> restrict B v \\<notin> Y) \\<Longrightarrow> v \\<in> join X b Y\"\n  unfolding table_def\n  by (subst join_restrict) (auto)\n\nlemma in_joinE: \"v \\<in> join X b Y \\<Longrightarrow> table n A X \\<Longrightarrow> table n B Y \\<Longrightarrow> (\\<not> b \\<Longrightarrow> B \\<subseteq> A) \\<Longrightarrow>\n  (wf_tuple n (A \\<union> B) v \\<Longrightarrow> restrict A v \\<in> X \\<Longrightarrow> if b then restrict B v \\<in> Y else restrict B v \\<notin> Y \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding table_def\n  by (subst (asm) join_restrict) (auto)\n\ndefinition qtable :: \"nat \\<Rightarrow> nat set \\<Rightarrow> ('a tuple \\<Rightarrow> bool) \\<Rightarrow> ('a tuple \\<Rightarrow> bool) \\<Rightarrow>\n  'a table \\<Rightarrow> bool\" where\n  \"qtable n A P Q X \\<longleftrightarrow> table n A X \\<and> (\\<forall>x. (x \\<in> X \\<and> P x \\<longrightarrow> Q x) \\<and> (wf_tuple n A x \\<and> P x \\<and> Q x \\<longrightarrow> x \\<in> X))\"\n\nabbreviation wf_table where\n  \"wf_table n A Q X \\<equiv> qtable n A (\\<lambda>_. True) Q X\"\n\nlemma wf_table_iff: \"wf_table n A Q X \\<longleftrightarrow> (\\<forall>x. x \\<in> X \\<longleftrightarrow> (Q x \\<and> wf_tuple n A x))\"\n  unfolding qtable_def table_def by auto\n\nlemma table_wf_table: \"table n A X = wf_table n A (\\<lambda>v. v \\<in> X) X\"\n  unfolding table_def wf_table_iff by auto\n\nlemma qtableI: \"table n A X \\<Longrightarrow>\n  (\\<And>x. x \\<in> X \\<Longrightarrow> wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow>\n  (\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> x \\<in> X) \\<Longrightarrow>\n  qtable n A P Q X\"\n  unfolding qtable_def table_def by auto\n\nlemma in_qtableI: \"qtable n A P Q X \\<Longrightarrow> wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> x \\<in> X\"\n  unfolding qtable_def by blast\n\nlemma in_qtableE: \"qtable n A P Q X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> P x \\<Longrightarrow> (wf_tuple n A x \\<Longrightarrow> Q x \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  unfolding qtable_def table_def by blast\n\nlemma qtable_empty: \"(\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<Longrightarrow> False) \\<Longrightarrow> qtable n A P Q empty_table\"\n  unfolding qtable_def table_def empty_table_def by auto\n\nlemma qtable_empty_iff: \"qtable n A P Q empty_table = (\\<forall>x. wf_tuple n A x \\<longrightarrow> P x \\<longrightarrow> Q x \\<longrightarrow> False)\"\n  unfolding qtable_def table_def empty_table_def by auto\n\nlemma qtable_unit_table: \"(\\<And>x. wf_tuple n {} x \\<Longrightarrow> P x \\<Longrightarrow> Q x) \\<Longrightarrow> qtable n {} P Q (unit_table n)\"\n  unfolding qtable_def table_def in_unit_table by auto\n\nlemma qtable_union: \"qtable n A P Q1 X \\<Longrightarrow> qtable n A P Q2 Y \\<Longrightarrow>\n  (\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> Q1 x \\<or> Q2 x) \\<Longrightarrow> qtable n A P Q (X \\<union> Y)\"\n  unfolding qtable_def table_def by blast\n\nlemma qtable_Union: \"finite I \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> qtable n A P (Qi i) (Xi i)) \\<Longrightarrow>\n  (\\<And>x. wf_tuple n A x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> (\\<exists>i \\<in> I. Qi i x)) \\<Longrightarrow> qtable n A P Q (\\<Union>i \\<in> I. Xi i)\"\nproof (induct I arbitrary: Q rule: finite_induct)\n  case (insert i F)\n  then show ?case\n    by (auto intro!: qtable_union[where ?Q1.0 = \"Qi i\" and ?Q2.0 = \"\\<lambda>x. \\<exists>i\\<in>F. Qi i x\"])\nqed (auto intro!: qtable_empty[unfolded empty_table_def])\n\nlemma qtable_join: \n  assumes \"qtable n A P Q1 X\" \"qtable n B P Q2 Y\" \"\\<not> b \\<Longrightarrow> B \\<subseteq> A\" \"C = A \\<union> B\"\n  \"\\<And>x. wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> P (restrict A x) \\<and> P (restrict B x)\"\n  \"\\<And>x. b \\<Longrightarrow> wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> Q1 (restrict A x) \\<and> Q2 (restrict B x)\"\n  \"\\<And>x. \\<not> b \\<Longrightarrow> wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> Q x \\<longleftrightarrow> Q1 (restrict A x) \\<and> \\<not> Q2 (restrict B x)\"\n  shows \"qtable n C P Q (join X b Y)\"\nproof (rule qtableI)\n  from assms(1-4) show \"table n C (join X b Y)\" \n    unfolding qtable_def by (auto simp: join_table)\nnext\n  fix x assume \"x \\<in> join X b Y\" \"wf_tuple n C x\" \"P x\"\n  with assms(1-3) assms(5-7)[of x] show \"Q x\" unfolding qtable_def\n    by (auto 0 2 simp: wf_tuple_restrict_simple elim!: in_joinE split: if_splits)\nnext\n  fix x assume \"wf_tuple n C x\" \"P x\" \"Q x\"\n  with assms(1-4) assms(5-7)[of x] show \"x \\<in> join X b Y\" unfolding qtable_def\n    by (auto dest: wf_tuple_restrict_simple intro!: in_joinI[of n A X B Y])\nqed\n\nlemma qtable_join_fixed: \n  assumes \"qtable n A P Q1 X\" \"qtable n B P Q2 Y\" \"\\<not> b \\<Longrightarrow> B \\<subseteq> A\" \"C = A \\<union> B\"\n  \"\\<And>x. wf_tuple n C x \\<Longrightarrow> P x \\<Longrightarrow> P (restrict A x) \\<and> P (restrict B x)\"\n  shows \"qtable n C P (\\<lambda>x. Q1 (restrict A x) \\<and> (if b then Q2 (restrict B x) else \\<not> Q2 (restrict B x))) (join X b Y)\"\n  by (rule qtable_join[OF assms]) auto\n\nlemma wf_tuple_cong:\n  assumes \"wf_tuple n A v\" \"wf_tuple n A w\" \"\\<forall>x \\<in> A. map the v ! x = map the w ! x\"\n  shows \"v = w\"\nproof -\n  from assms(1,2) have \"length v = length w\" unfolding wf_tuple_def by simp\n  from this assms show \"v = w\"\n  proof (induct v w arbitrary: n A rule: list_induct2)\n    case (Cons x xs y ys)\n    let ?n = \"n - 1\" and ?A = \"(\\<lambda>x. x - 1) ` (A - {0})\"\n    have *: \"map the xs ! z = map the ys ! z\" if \"z \\<in> ?A\" for z\n      using that Cons(5)[THEN bspec, of \"Suc z\"]\n      by (cases z) (auto simp: le_Suc_eq split: if_splits)\n    from Cons(1,3-5) show ?case\n      by (auto intro!: Cons(2)[of ?n ?A] * split: if_splits)\n  qed simp\nqed\n\ndefinition mem_restr :: \"'a list set \\<Rightarrow> 'a tuple \\<Rightarrow> bool\" where\n  \"mem_restr A x \\<longleftrightarrow> (\\<exists>y\\<in>A. list_all2 (\\<lambda>a b. a \\<noteq> None \\<longrightarrow> a = Some b) x y)\"\n\nlemma mem_restrI: \"y \\<in> A \\<Longrightarrow> length y = n \\<Longrightarrow> wf_tuple n V x \\<Longrightarrow> \\<forall>i\\<in>V. x ! i = Some (y ! i) \\<Longrightarrow> mem_restr A x\"\n  unfolding mem_restr_def wf_tuple_def by (force simp add: list_all2_conv_all_nth)\n\nlemma mem_restrE: \"mem_restr A x \\<Longrightarrow> wf_tuple n V x \\<Longrightarrow> \\<forall>i\\<in>V. i < n \\<Longrightarrow>\n  (\\<And>y. y \\<in> A \\<Longrightarrow> \\<forall>i\\<in>V. x ! i = Some (y ! i) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  unfolding mem_restr_def wf_tuple_def by (fastforce simp add: list_all2_conv_all_nth)\n\nlemma mem_restr_IntD: \"mem_restr (A \\<inter> B) v \\<Longrightarrow> mem_restr A v \\<and> mem_restr B v\"\n  unfolding mem_restr_def by auto\n\nlemma mem_restr_Un_iff: \"mem_restr (A \\<union> B) x \\<longleftrightarrow> mem_restr A x \\<or> mem_restr B x\"\n  unfolding mem_restr_def by blast\n\nlemma mem_restr_UNIV [simp]: \"mem_restr UNIV x\"\n  unfolding mem_restr_def\n  by (auto simp add: list.rel_map intro!: exI[of _ \"map the x\"] list.rel_refl)\n\nlemma restrict_mem_restr[simp]: \"mem_restr A x \\<Longrightarrow> mem_restr A (restrict V x)\"\n  unfolding mem_restr_def restrict_def\n  by (auto simp: list_all2_conv_all_nth elim!: bexI[rotated])\n\ndefinition lift_envs :: \"'a list set \\<Rightarrow> 'a list set\" where\n  \"lift_envs R = (\\<lambda>(a,b). a # b) ` (UNIV \\<times> R)\"\n\nlemma lift_envs_mem_restr[simp]: \"mem_restr A x \\<Longrightarrow> mem_restr (lift_envs A) (a # x)\"\n  by (auto simp: mem_restr_def lift_envs_def)\n\nlemma qtable_project:\n  assumes \"qtable (Suc n) A (mem_restr (lift_envs R)) P X\"\n  shows \"qtable n ((\\<lambda>x. x - Suc 0) ` (A - {0})) (mem_restr R)\n      (\\<lambda>v. \\<exists>x. P ((if 0 \\<in> A then Some x else None) # v)) (tl ` X)\"\n      (is \"qtable n ?A (mem_restr R) ?P ?X\")\nproof ((rule qtableI; (elim exE)?), goal_cases table left right)\n  case table\n  with assms show ?case\n    unfolding qtable_def by (simp add: table_project) \nnext\n  case (left v)\n  from assms have \"[] \\<notin> X\"\n    unfolding qtable_def table_def by fastforce\n  with left(1) obtain x where \"x # v \\<in> X\"\n    by (metis (no_types, hide_lams) image_iff hd_Cons_tl)    \n  with assms show ?case\n    by (rule in_qtableE) (auto simp: left(3) split: if_splits)\nnext\n  case (right v x)\n  with assms have \"(if 0 \\<in> A then Some x else None) # v \\<in> X\"\n    by (elim in_qtableI) auto\n  then show ?case\n    by (auto simp: image_iff elim: bexI[rotated])\nqed\n\nlemma qtable_cong: \"qtable n A P Q X \\<Longrightarrow> A = B \\<Longrightarrow> (\\<And>v. P v \\<Longrightarrow> Q v \\<longleftrightarrow> Q' v) \\<Longrightarrow> qtable n B P Q' X\"\n  by (auto simp: qtable_def)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/MFOTL_Monitor/Table.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904956, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7585268176148486}}
{"text": "(*  Title:      ZF/AC/WO1_WO7.thy\n    Author:     Lawrence C Paulson, CU Computer Laboratory\n    Copyright   1998  University of Cambridge\n\nWO7 \\<longleftrightarrow> LEMMA \\<longleftrightarrow> WO1 (Rubin & Rubin p. 5)\nLEMMA is the sentence denoted by (**)\n\nAlso, WO1 \\<longleftrightarrow> WO8\n*)\n\ntheory WO1_WO7\nimports AC_Equiv\nbegin\n\ndefinition\n    \"LEMMA \\<equiv>\n     \\<forall>X. \\<not>Finite(X) \\<longrightarrow> (\\<exists>R. well_ord(X,R) \\<and> \\<not>well_ord(X,converse(R)))\"\n\n(* ********************************************************************** *)\n(* It is easy to see that WO7 is equivalent to (**)                       *)\n(* ********************************************************************** *)\n\nlemma WO7_iff_LEMMA: \"WO7 \\<longleftrightarrow> LEMMA\"\n  unfolding WO7_def LEMMA_def\napply (blast intro: Finite_well_ord_converse)\ndone\n\n(* ********************************************************************** *)\n(* It is also easy to show that LEMMA implies WO1.                        *)\n(* ********************************************************************** *)\n\nlemma LEMMA_imp_WO1: \"LEMMA \\<Longrightarrow> WO1\"\n  unfolding WO1_def LEMMA_def Finite_def eqpoll_def\napply (blast intro!: well_ord_rvimage [OF bij_is_inj nat_implies_well_ord])\ndone\n\n(* ********************************************************************** *)\n(* The Rubins' proof of the other implication is contained within the     *)\n(* following sentence \\<in>                                                   *)\n(* \"... each infinite ordinal is well ordered by < but not by >.\"         *)\n(* This statement can be proved by the following two theorems.            *)\n(* But moreover we need to show similar property for any well ordered     *)\n(* infinite set. It is not very difficult thanks to Isabelle order types  *)\n(* We show that if a set is well ordered by some relation and by its     *)\n(* converse, then apropriate order type is well ordered by the converse   *)\n(* of it's membership relation, which in connection with the previous     *)\n(* gives the conclusion.                                                  *)\n(* ********************************************************************** *)\n\nlemma converse_Memrel_not_wf_on: \n    \"\\<lbrakk>Ord(a); \\<not>Finite(a)\\<rbrakk> \\<Longrightarrow> \\<not>wf[a](converse(Memrel(a)))\"\n  unfolding wf_on_def wf_def\napply (drule nat_le_infinite_Ord [THEN le_imp_subset], assumption)\napply (rule notI)\napply (erule_tac x = nat in allE, blast)\ndone\n\nlemma converse_Memrel_not_well_ord: \n    \"\\<lbrakk>Ord(a); \\<not>Finite(a)\\<rbrakk> \\<Longrightarrow> \\<not>well_ord(a,converse(Memrel(a)))\"\n  unfolding well_ord_def\napply (blast dest: converse_Memrel_not_wf_on)\ndone\n\nlemma well_ord_rvimage_ordertype:\n     \"well_ord(A,r) \\<Longrightarrow>\n       rvimage (ordertype(A,r), converse(ordermap(A,r)),r) =\n       Memrel(ordertype(A,r))\" \nby (blast intro: ordertype_ord_iso [THEN ord_iso_sym] ord_iso_rvimage_eq\n             Memrel_type [THEN subset_Int_iff [THEN iffD1]] trans)\n\nlemma well_ord_converse_Memrel:\n     \"\\<lbrakk>well_ord(A,r); well_ord(A,converse(r))\\<rbrakk>   \n      \\<Longrightarrow> well_ord(ordertype(A,r), converse(Memrel(ordertype(A,r))))\" \napply (subst well_ord_rvimage_ordertype [symmetric], assumption) \napply (rule rvimage_converse [THEN subst])\napply (blast intro: ordertype_ord_iso ord_iso_sym ord_iso_is_bij\n                    bij_is_inj well_ord_rvimage)\ndone\n\nlemma WO1_imp_LEMMA: \"WO1 \\<Longrightarrow> LEMMA\"\napply (unfold WO1_def LEMMA_def, clarify) \napply (blast dest: well_ord_converse_Memrel\n                   Ord_ordertype [THEN converse_Memrel_not_well_ord]\n             intro: ordertype_ord_iso ord_iso_is_bij bij_is_inj lepoll_Finite\n                    lepoll_def [THEN def_imp_iff, THEN iffD2] )\ndone\n\nlemma WO1_iff_WO7: \"WO1 \\<longleftrightarrow> WO7\"\napply (simp add: WO7_iff_LEMMA)\napply (blast intro: LEMMA_imp_WO1 WO1_imp_LEMMA)\ndone\n\n\n\n(* ********************************************************************** *)\n(*            The proof of WO8 \\<longleftrightarrow> WO1 (Rubin & Rubin p. 6)               *)\n(* ********************************************************************** *)\n\nlemma WO1_WO8: \"WO1 \\<Longrightarrow> WO8\"\nby (unfold WO1_def WO8_def, fast)\n\n\n(* The implication \"WO8 \\<Longrightarrow> WO1\": a faithful image of Rubin & Rubin's proof*)\nlemma WO8_WO1: \"WO8 \\<Longrightarrow> WO1\"\n  unfolding WO1_def WO8_def\napply (rule allI)\napply (erule_tac x = \"{{x}. x \\<in> A}\" in allE)\napply (erule impE)\n apply (rule_tac x = \"\\<lambda>a \\<in> {{x}. x \\<in> A}. THE x. a={x}\" in exI)\n apply (force intro!: lam_type simp add: singleton_eq_iff the_equality)\napply (blast intro: lam_sing_bij bij_is_inj well_ord_rvimage)\ndone\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/ZF/AC/WO1_WO7.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.8519527982093666, "lm_q1q2_score": 0.7584886472548302}}
{"text": "theory Circlines_Angle\n  imports Oriented_Circlines Elementary_Complex_Geometry\nbegin\n\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Angle between circlines\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Angle between circlines can be defined in purely algebraic terms (following Schwerdtfeger\n\\cite{schwerdtfeger}) and using this definitions many properties can be easily proved.\\<close>\n\nfun mat_det_12 :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> complex\" where\n  \"mat_det_12 (A1, B1, C1, D1) (A2, B2, C2, D2) = A1*D2 + A2*D1 - B1*C2 - B2*C1\"\n\nlemma mat_det_12_mm_l [simp]:\n  shows \"mat_det_12 (M *\\<^sub>m\\<^sub>m A) (M *\\<^sub>m\\<^sub>m B) = mat_det M * mat_det_12 A B\"\n  by (cases M, cases A, cases B) (simp add: field_simps)\n\nlemma mat_det_12_mm_r [simp]:\n  shows \"mat_det_12 (A *\\<^sub>m\\<^sub>m M) (B *\\<^sub>m\\<^sub>m M) = mat_det M * mat_det_12 A B\"\n  by (cases M, cases A, cases B) (simp add: field_simps)\n\nlemma mat_det_12_sm_l [simp]:\n  shows \"mat_det_12 (k *\\<^sub>s\\<^sub>m A) B = k * mat_det_12 A B\"\n  by (cases A, cases B) (simp add: field_simps)\n\nlemma mat_det_12_sm_r [simp]:\n  shows \"mat_det_12 A (k *\\<^sub>s\\<^sub>m B) = k * mat_det_12 A B\"\n  by (cases A, cases B) (simp add: field_simps)\n\nlemma mat_det_12_congruence [simp]:\n  shows \"mat_det_12 (congruence M A) (congruence M B) = (cor ((cmod (mat_det M))\\<^sup>2)) * mat_det_12 A B\"\n  unfolding congruence_def\n  by ((subst mult_mm_assoc[symmetric])+, subst mat_det_12_mm_l, subst mat_det_12_mm_r, subst mat_det_adj) (auto simp add: field_simps complex_mult_cnj_cmod)\n\n\ndefinition cos_angle_cmat :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> real\" where\n  [simp]: \"cos_angle_cmat H1 H2 = - Re (mat_det_12 H1 H2) / (2 * (sqrt (Re (mat_det H1 * mat_det H2))))\"\n\nlift_definition cos_angle_clmat :: \"circline_mat \\<Rightarrow> circline_mat \\<Rightarrow> real\" is cos_angle_cmat\n  done\n\nlemma cos_angle_den_scale [simp]:\n  assumes \"k1 > 0\" and \"k2 > 0\"\n  shows \"sqrt (Re ((k1\\<^sup>2 * mat_det H1) * (k2\\<^sup>2 * mat_det H2))) =\n         k1 * k2 * sqrt (Re (mat_det H1 * mat_det H2))\"\nproof-\n  let ?lhs = \"(k1\\<^sup>2 * mat_det H1) * (k2\\<^sup>2 * mat_det H2)\"\n  let ?rhs = \"mat_det H1 * mat_det H2\"\n  have 1: \"?lhs = (k1\\<^sup>2*k2\\<^sup>2) * ?rhs\"\n    by simp\n  hence \"Re ?lhs = (k1\\<^sup>2*k2\\<^sup>2) * Re ?rhs\"\n    by (simp add: field_simps)\n  thus ?thesis\n    using assms\n    by (simp add: real_sqrt_mult)\nqed\n\nlift_definition cos_angle :: \"ocircline \\<Rightarrow> ocircline \\<Rightarrow> real\" is cos_angle_clmat\nproof transfer\n  fix H1 H2 H1' H2'\n  assume \"ocircline_eq_cmat H1 H1'\" \"ocircline_eq_cmat H2 H2'\"\n  then obtain k1 k2 :: real where\n  *:  \"k1 > 0\" \"H1' = cor k1 *\\<^sub>s\\<^sub>m H1\"\n      \"k2 > 0\" \"H2' = cor k2 *\\<^sub>s\\<^sub>m H2\"\n    by auto\n  thus \"cos_angle_cmat H1 H2 = cos_angle_cmat H1' H2'\"\n    unfolding cos_angle_cmat_def\n    apply (subst *)+\n    apply (subst mat_det_12_sm_l, subst mat_det_12_sm_r)\n    apply (subst mat_det_mult_sm)+\n    apply (subst power2_eq_square[symmetric])+\n    apply (subst cos_angle_den_scale, simp, simp)\n    apply simp\n    done\nqed\n\ntext \\<open>Möbius transformations are conformal, meaning that they preserve oriented angle between\noriented circlines.\\<close>\n\nlemma cos_angle_opposite1 [simp]: \n  shows \"cos_angle (opposite_ocircline H) H' = - cos_angle H H'\"\n  by (transfer, transfer, simp)\n\nlemma cos_angle_opposite2 [simp]: \n  shows \"cos_angle H (opposite_ocircline H') = - cos_angle H H'\"\n  by (transfer, transfer, simp)\n\n(* ----------------------------------------------------------------- *)\nsubsubsection \\<open>Connection with the elementary angle definition between circles\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext\\<open>We want to connect algebraic definition of an angle with a traditional one and \nto prove equivalency between these two definitions. For the traditional definition of \nan angle we follow the approach suggested by Needham \\cite{needham}.\\<close>\n\n\n\nlemma Re_mult_real3:\n  assumes \"is_real z1\" and \"is_real z2\" and \"is_real z3\"\n  shows \"Re (z1 * z2 * z3) = Re z1 * Re z2 * Re z3\"\n  using assms\n  by (metis Re_mult_real mult_reals)\n\nlemma sgn_sqrt [simp]: \n  shows \"sgn (sqrt x) = sgn x\"\n  by (simp add: sgn_root sqrt_def)\n\nlemma real_circle_sgn_r:\n  assumes \"is_circle H\" and \"(a, r) = euclidean_circle H\"\n  shows \"sgn r = - circline_type H\"\n  using assms\nproof (transfer, transfer)\n  fix H :: complex_mat and a r\n  assume hh: \"hermitean H \\<and> H \\<noteq> mat_zero\"\n  obtain A B C D where HH: \"H = (A, B, C, D)\"\n    by (cases H) auto\n  hence \"is_real A\" \"is_real D\"\n    using hermitean_elems hh\n    by auto\n  assume \"\\<not> circline_A0_cmat H\" \"(a, r) = euclidean_circle_cmat H\"\n  hence \"A \\<noteq> 0\"\n    using \\<open>\\<not> circline_A0_cmat H\\<close> HH\n    by simp\n  hence \"Re A * Re A > 0\"\n    using \\<open>is_real A\\<close>\n    using complex_eq_if_Re_eq not_real_square_gt_zero\n    by fastforce\n  thus \"sgn r = - circline_type_cmat H\"\n    using HH \\<open>(a, r) = euclidean_circle_cmat H\\<close> \\<open>is_real A\\<close> \\<open>is_real D\\<close> \\<open>A \\<noteq> 0\\<close>\n    by (simp add: Re_divide_real sgn_minus[symmetric])\nqed\n\ntext \\<open>The definition of an angle using algebraic terms is not intuitive, and we want to connect it to\nthe more common definition given earlier that defines an\nangle between circlines as the angle between tangent vectors in the point of the intersection of the\ncirclines.\\<close>\n\nlemma cos_angle_eq_cos_ang_circ:\n  assumes\n  \"is_circle (of_ocircline H1)\" and \"is_circle (of_ocircline H2)\" and\n  \"circline_type (of_ocircline H1) < 0\" and \"circline_type (of_ocircline H2) < 0\"\n  \"(a1, r1) = euclidean_circle (of_ocircline H1)\" and \"(a2, r2) = euclidean_circle (of_ocircline H2)\" and\n  \"of_complex E \\<in> ocircline_set H1 \\<inter> ocircline_set H2\"\n  shows \"cos_angle H1 H2 = cos (ang_circ E a1 a2 (pos_oriented H1) (pos_oriented H2))\"\nproof-\n  let ?p1 = \"pos_oriented H1\" and ?p2 = \"pos_oriented H2\"\n  have \"E \\<in> circle a1 r1\" \"E \\<in> circle a2 r2\"\n    using classic_circle[of \"of_ocircline H1\" a1 r1]  classic_circle[of \"of_ocircline H2\" a2 r2]\n    using assms of_complex_inj\n    by auto\n  hence *: \"cdist E a1 = r1\" \"cdist E a2 = r2\"\n    unfolding circle_def\n    by (simp_all add: norm_minus_commute)\n  have \"r1 > 0\" \"r2 > 0\"\n    using assms(1-6) real_circle_sgn_r[of \"of_ocircline H1\" a1 r1]  real_circle_sgn_r[of \"of_ocircline H2\" a2 r2]\n    using sgn_greater \n    by fastforce+\n  hence \"E \\<noteq> a1\" \"E \\<noteq> a2\"\n    using \\<open>cdist E a1 = r1\\<close> \\<open>cdist E a2 = r2\\<close>\n    by auto\n\n  let ?k = \"sgn_bool (?p1 = ?p2)\"\n  let ?xx = \"?k * (r1\\<^sup>2 + r2\\<^sup>2 - (cdist a2 a1)\\<^sup>2) / (2 * r1 * r2)\"\n\n  have \"cos (ang_circ E a1 a2 ?p1 ?p2) = ?xx\"\n    using law_of_cosines[of a2 a1 E] * \\<open>r1 > 0\\<close> \\<open>r2 > 0\\<close> cos_ang_circ_simp[OF \\<open>E \\<noteq> a1\\<close> \\<open>E \\<noteq> a2\\<close>]\n    by (subst (asm) ang_vec_opposite_opposite'[OF \\<open>E \\<noteq> a1\\<close>[symmetric] \\<open>E \\<noteq> a2\\<close>[symmetric], symmetric]) simp\n  moreover\n  have \"cos_angle H1 H2 = ?xx\"\n    using \\<open>r1 > 0\\<close> \\<open>r2 > 0\\<close>\n    using \\<open>(a1, r1) = euclidean_circle (of_ocircline H1)\\<close> \\<open>(a2, r2) = euclidean_circle (of_ocircline H2)\\<close>\n    using \\<open>is_circle (of_ocircline H1)\\<close> \\<open>is_circle (of_ocircline H2)\\<close>\n    using \\<open>circline_type (of_ocircline H1) < 0\\<close> \\<open>circline_type (of_ocircline H2) < 0\\<close>\n  proof (transfer, transfer)\n    fix a1 r1 H1 H2 a2 r2\n    assume hh: \"hermitean H1 \\<and> H1 \\<noteq> mat_zero\" \"hermitean H2 \\<and> H2 \\<noteq> mat_zero\"\n    obtain A1 B1 C1 D1 where HH1: \"H1 = (A1, B1, C1, D1)\"\n      by (cases H1) auto\n    obtain A2 B2 C2 D2 where HH2: \"H2 = (A2, B2, C2, D2)\"\n      by (cases H2) auto\n    have *: \"is_real A1\" \"is_real A2\" \"is_real D1\" \"is_real D2\" \"cnj B1 = C1\" \"cnj B2 = C2\"\n      using hh hermitean_elems[of A1 B1 C1 D1] hermitean_elems[of A2 B2 C2 D2] HH1 HH2\n      by auto\n    have \"cnj A1 = A1\" \"cnj A2 = A2\"\n      using \\<open>is_real A1\\<close> \\<open>is_real A2\\<close>\n      by (case_tac[!] A1, case_tac[!] A2, auto simp add: Complex_eq)\n\n    assume \"\\<not> circline_A0_cmat (id H1)\" \"\\<not> circline_A0_cmat (id H2)\"\n    hence \"A1 \\<noteq> 0\" \"A2 \\<noteq> 0\"\n      using HH1 HH2\n      by auto\n    hence \"Re A1 \\<noteq> 0\" \"Re A2 \\<noteq> 0\"\n      using \\<open>is_real A1\\<close> \\<open>is_real A2\\<close>\n      using complex.expand\n      by auto\n\n    assume \"circline_type_cmat (id H1) < 0\" \"circline_type_cmat (id H2) < 0\"\n    assume \"(a1, r1) = euclidean_circle_cmat (id H1)\" \"(a2, r2) = euclidean_circle_cmat (id H2)\"\n    assume \"r1 > 0\" \"r2 > 0\"\n\n    let ?D12 = \"mat_det_12 H1 H2\" and ?D1 = \"mat_det H1\" and ?D2 = \"mat_det H2\"\n    let ?x1 = \"(cdist a2 a1)\\<^sup>2 - r1\\<^sup>2 - r2\\<^sup>2\" and ?x2 = \"2*r1*r2\"\n    let ?x = \"?x1 / ?x2\"\n    have *:  \"Re (?D12) / (2 * (sqrt (Re (?D1 * ?D2)))) = Re (sgn A1) * Re (sgn A2) * ?x\"\n    proof-\n      let ?M1 = \"(A1, B1, C1, D1)\" and ?M2 = \"(A2, B2, C2, D2)\"\n      let ?d1 = \"B1 * C1 - A1 * D1\" and ?d2 = \"B2 * C2 - A2 * D2\"\n      have \"Re ?d1 > 0\" \"Re ?d2 > 0\"\n        using HH1 HH2 \\<open>circline_type_cmat (id H1) < 0\\<close>  \\<open>circline_type_cmat (id H2) < 0\\<close>\n        by auto\n      hence **: \"Re (?d1 / (A1 * A1)) > 0\" \"Re (?d2 / (A2 * A2)) > 0\"\n        using \\<open>is_real A1\\<close> \\<open>is_real A2\\<close> \\<open>A1 \\<noteq> 0\\<close> \\<open>A2 \\<noteq> 0\\<close>\n        by (subst Re_divide_real, simp_all add: complex_neq_0 power2_eq_square)+\n      have ***: \"is_real (?d1 / (A1 * A1)) \\<and> is_real (?d2 / (A2 * A2))\"\n        using \\<open>is_real A1\\<close>  \\<open>is_real A2\\<close> \\<open>A1 \\<noteq> 0\\<close> \\<open>A2 \\<noteq> 0\\<close> \\<open>cnj B1 = C1\\<close>[symmetric] \\<open>cnj B2 = C2\\<close>[symmetric] \\<open>is_real D1\\<close> \\<open>is_real D2\\<close>\n        by (subst div_reals, simp, simp, simp)+\n\n      have \"cor ?x = mat_det_12 ?M1 ?M2 / (2 * sgn A1 * sgn A2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))\"\n      proof-\n        have \"A1*A2*cor ?x1 = mat_det_12 ?M1 ?M2\"\n        proof-\n          have 1: \"A1*A2*(cor ((cdist a2 a1)\\<^sup>2)) = ((B2*A1 - A2*B1)*(C2*A1 - C1*A2)) / (A1*A2)\"\n            using \\<open>(a1, r1) = euclidean_circle_cmat (id H1)\\<close> \\<open>(a2, r2) = euclidean_circle_cmat (id H2)\\<close>\n            unfolding cdist_def cmod_square\n            using HH1 HH2 * \\<open>A1 \\<noteq> 0\\<close> \\<open>A2 \\<noteq> 0\\<close> \\<open>cnj A1 = A1\\<close> \\<open>cnj A2 = A2\\<close>\n            unfolding Let_def\n            apply (subst complex_of_real_Re)\n            apply (simp add: field_simps)\n            apply (simp add: complex_mult_cnj_cmod power2_eq_square)\n            apply (simp add: field_simps)\n            done\n          have 2: \"A1*A2*cor (-r1\\<^sup>2) = A2*D1 - B1*C1*A2/A1\"\n            using \\<open>(a1, r1) = euclidean_circle_cmat (id H1)\\<close>\n            using HH1 ** * *** \\<open>A1 \\<noteq> 0\\<close>\n            by (simp add: power2_eq_square field_simps)\n          have 3: \"A1*A2*cor (-r2\\<^sup>2) = A1*D2 - B2*C2*A1/A2\"\n            using \\<open>(a2, r2) = euclidean_circle_cmat (id H2)\\<close>\n            using HH2 ** * *** \\<open>A2 \\<noteq> 0\\<close>\n            by (simp add: power2_eq_square field_simps)\n          have \"A1*A2*cor((cdist a2 a1)\\<^sup>2) + A1*A2*cor(-r1\\<^sup>2) + A1*A2*cor(-r2\\<^sup>2) = mat_det_12 ?M1 ?M2\"\n            using \\<open>A1 \\<noteq> 0\\<close> \\<open>A2 \\<noteq> 0\\<close>\n            by (subst 1, subst 2, subst 3) (simp add: field_simps)\n          thus ?thesis\n            by (simp add: field_simps)\n        qed\n\n        moreover\n\n        have \"A1 * A2 * cor (?x2) = 2 * sgn A1 * sgn A2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2))\"\n        proof-\n          have 1: \"sqrt (Re (?d1/ (A1 * A1))) = sqrt (Re ?d1) / \\<bar>Re A1\\<bar>\"\n            using \\<open>A1 \\<noteq> 0\\<close> \\<open>is_real A1\\<close>\n            by (subst Re_divide_real, simp, simp, subst real_sqrt_divide, simp)\n\n          have 2: \"sqrt (Re (?d2/ (A2 * A2))) = sqrt (Re ?d2) / \\<bar>Re A2\\<bar>\"\n            using \\<open>A2 \\<noteq> 0\\<close> \\<open>is_real A2\\<close>\n            by (subst Re_divide_real, simp, simp, subst real_sqrt_divide, simp)\n          have \"sgn A1 = A1 / cor \\<bar>Re A1\\<bar>\"\n            using \\<open>is_real A1\\<close>\n            unfolding sgn_eq\n            by (simp add: cmod_eq_Re)\n          moreover\n          have \"sgn A2 = A2 / cor \\<bar>Re A2\\<bar>\"\n            using \\<open>is_real A2\\<close>\n            unfolding sgn_eq\n            by (simp add: cmod_eq_Re)\n          ultimately\n          show ?thesis\n            using \\<open>(a1, r1) = euclidean_circle_cmat (id H1)\\<close> \\<open>(a2, r2) = euclidean_circle_cmat (id H2)\\<close>  HH1 HH2\n            using *** \\<open>is_real A1\\<close> \\<open>is_real A2\\<close>\n            by simp (subst 1, subst 2, simp)\n        qed\n\n        ultimately\n\n        have \"(A1 * A2 * cor ?x1) / (A1 * A2 * (cor ?x2)) =\n               mat_det_12 ?M1 ?M2 / (2 * sgn A1 * sgn A2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))\"\n          by simp\n        thus ?thesis\n          using \\<open>A1 \\<noteq> 0\\<close> \\<open>A2 \\<noteq> 0\\<close>\n          by simp\n      qed\n      hence \"cor ?x * sgn A1 * sgn A2 = mat_det_12 ?M1 ?M2 / (2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))\"\n        using \\<open>A1 \\<noteq> 0\\<close> \\<open>A2 \\<noteq> 0\\<close>\n        by (simp add: sgn_zero_iff)\n      moreover\n      have \"Re (cor ?x * sgn A1 * sgn A2) = Re (sgn A1) * Re (sgn A2) * ?x\"\n      proof-\n        have \"is_real (cor ?x)\" \"is_real (sgn A1)\" \"is_real (sgn A2)\"\n          using \\<open>is_real A1\\<close> \\<open>is_real A2\\<close> Im_complex_of_real[of ?x]\n          by auto\n        thus ?thesis\n          using Re_complex_of_real[of ?x]\n          by (subst Re_mult_real3, auto simp add: field_simps)\n      qed\n      moreover\n      have *: \"sqrt (Re ?D1) * sqrt (Re ?D2) = sqrt (Re ?d1) * sqrt (Re ?d2)\"\n        using HH1 HH2\n        by (subst real_sqrt_mult[symmetric])+ (simp add: field_simps)\n      have \"2 * (sqrt (Re (?D1 * ?D2))) \\<noteq> 0\"\n        using \\<open>Re ?d1 > 0\\<close>  \\<open>Re ?d2 > 0\\<close> HH1 HH2 \\<open>is_real A1\\<close> \\<open>is_real A2\\<close>  \\<open>is_real D1\\<close> \\<open>is_real D2\\<close>\n        using hh mat_det_hermitean_real[of \"H1\"]\n        by (subst Re_mult_real, auto)\n      hence **: \"Re (?D12 / (2 * cor (sqrt (Re (?D1 * ?D2))))) = Re (?D12) / (2 * (sqrt (Re (?D1 * ?D2))))\"\n        using \\<open>Re ?d1 > 0\\<close>  \\<open>Re ?d2 > 0\\<close> HH1 HH2 \\<open>is_real A1\\<close> \\<open>is_real A2\\<close>  \\<open>is_real D1\\<close> \\<open>is_real D2\\<close>\n        by (subst Re_divide_real) auto\n      have \"Re (mat_det_12 ?M1 ?M2 / (2 * cor (sqrt (Re ?d1) * sqrt (Re ?d2)))) = Re (?D12) / (2 * (sqrt (Re (?D1 * ?D2))))\"\n        using HH1 HH2 hh mat_det_hermitean_real[of \"H1\"]\n        by (subst **[symmetric], subst Re_mult_real, simp, subst real_sqrt_mult, subst *, simp)\n      ultimately\n      show ?thesis\n        by simp\n    qed\n    have **: \"pos_oriented_cmat H1 \\<longleftrightarrow> Re A1 > 0\"  \"pos_oriented_cmat H2 \\<longleftrightarrow> Re A2 > 0\"\n      using \\<open>Re A1 \\<noteq> 0\\<close> HH1  \\<open>Re A2 \\<noteq> 0\\<close> HH2\n      by auto\n    show \"cos_angle_cmat H1 H2 = sgn_bool (pos_oriented_cmat H1 = pos_oriented_cmat H2) * (r1\\<^sup>2 + r2\\<^sup>2 - (cdist a2 a1)\\<^sup>2) /  (2 * r1 * r2)\"\n      unfolding Let_def\n      using \\<open>r1 > 0\\<close> \\<open>r2 > 0\\<close>\n      unfolding cos_angle_cmat_def\n      apply (subst divide_minus_left)\n      apply (subst *)\n      apply (subst Re_sgn[OF \\<open>is_real A1\\<close> \\<open>A1 \\<noteq> 0\\<close>], subst Re_sgn[OF \\<open>is_real A2\\<close> \\<open>A2 \\<noteq> 0\\<close>])\n      apply (subst **, subst **)\n      apply (simp add: field_simps)\n      done\n  qed\n  ultimately\n  show ?thesis\n    by simp\nqed\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Perpendicularity\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Two circlines are perpendicular if the intersect at right angle i.e., the angle with the cosine\n0.\\<close>\n\ndefinition perpendicular where\n  \"perpendicular H1 H2 \\<longleftrightarrow> cos_angle (of_circline H1) (of_circline H2) = 0\"\n\nlemma perpendicular_sym:\n  shows \"perpendicular H1 H2 \\<longleftrightarrow> perpendicular H2 H1\"\n  unfolding perpendicular_def\n  by (transfer, transfer, auto simp add: field_simps)\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Möbius transforms preserve angles and perpendicularity\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Möbius transformations are \\emph{conformal} i.e., they preserve angles between circlines.\\<close>\n\n\n\nlemma perpendicular_moebius [simp]:\n  assumes \"perpendicular H1 H2\"\n  shows \"perpendicular (moebius_circline M H1) (moebius_circline M H2)\"\n  using assms\n  unfolding perpendicular_def\n  using moebius_preserve_circline_angle[of M \"of_circline H1\" \"of_circline H2\"]\n  using moebius_ocircline_circline[of M \"of_circline H1\"]\n  using moebius_ocircline_circline[of M \"of_circline H2\"]\n  by (auto simp del: moebius_preserve_circline_angle)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/Circlines_Angle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577681013541611, "lm_q2_score": 0.8840392848011834, "lm_q1q2_score": 0.7583006988464016}}
{"text": "subsection \\<open>The Knapsack Problem\\<close>\n\ntheory Knapsack\n  imports\n    \"HOL-Library.Code_Target_Numeral\"\n    \"../state_monad/State_Main\" \n    \"../heap_monad/Heap_Default\"\n    Example_Misc\nbegin\n\nsubsubsection \\<open>Definitions\\<close>\n\ncontext (* Subset Sum *)\n  fixes w :: \"nat \\<Rightarrow> nat\"\nbegin\n\ncontext (* Knapsack *)\n  fixes v :: \"nat \\<Rightarrow> nat\"\nbegin\n\nfun knapsack :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"knapsack 0 W = 0\" |\n  \"knapsack (Suc i) W = (if W < w (Suc i)\n    then knapsack i W\n    else max (knapsack i W) (v (Suc i) + knapsack i (W - w (Suc i))))\"\n\nno_notation fun_app_lifted (infixl \".\" 999)\n\ntext \\<open>\n  The correctness proof closely follows Kleinberg \\<open>&\\<close> Tardos: \"Algorithm Design\",\n  chapter \"Dynamic Programming\" @{cite \"Kleinberg-Tardos\"}\n\\<close>\n\ndefinition\n  \"OPT n W = Max {\\<Sum> i \\<in> S. v i | S. S \\<subseteq> {1..n} \\<and> (\\<Sum> i \\<in> S. w i) \\<le> W}\"\n\nlemma OPT_0:\n  \"OPT 0 W = 0\"\n  unfolding OPT_def by simp\n\nsubsubsection \\<open>Functional Correctness\\<close>\n\nlemma Max_add_left:\n  \"(x :: nat) + Max S = Max (((+) x) ` S)\" (is \"?A = ?B\") if \"finite S\" \"S \\<noteq> {}\"\nproof -\n  have \"?A \\<le> ?B\"\n    using that by (force intro: Min.boundedI)\n  moreover have \"?B \\<le> ?A\"\n    using that by (force intro: Min.boundedI)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma OPT_Suc:\n  \"OPT (Suc i) W = (\n    if W < w (Suc i)\n    then OPT i W\n    else max(v (Suc i) + OPT i (W - w (Suc i))) (OPT i W)\n  )\" (is \"?lhs = ?rhs\")\nproof -\n  have OPT_in: \"OPT n W \\<in> {\\<Sum> i \\<in> S. v i | S. S \\<subseteq> {1..n} \\<and> (\\<Sum> i \\<in> S. w i) \\<le> W}\" for n W\n    unfolding OPT_def by - (rule Max_in; force)\n  from OPT_in[of \"Suc i\" W] obtain S where S:\n    \"S \\<subseteq> {1..Suc i}\" \"sum w S \\<le> W\" and [simp]: \"OPT (Suc i) W = sum v S\"\n    by auto\n\n  have \"OPT i W \\<le> OPT (Suc i) W\"\n    unfolding OPT_def by (force intro: Max_mono)\n  moreover have \"v (Suc i) + OPT i (W - w (Suc i)) \\<le> OPT (Suc i) W\" if \"w (Suc i) \\<le> W\"\n  proof -\n    have *: \"\n      v (Suc i) + sum v S = sum v (S \\<union> {Suc i}) \\<and> (S \\<union> {Suc i}) \\<subseteq> {1..Suc i}\n      \\<and> sum w (S \\<union> {Suc i}) \\<le> W\" if \"S \\<subseteq> {1..i}\" \"sum w S \\<le> W - w (Suc i)\" for S\n      using that \\<open>w (Suc i) \\<le> W\\<close>\n      by (subst sum.insert_if | auto intro: finite_subset[OF _ finite_atLeastAtMost])+\n    show ?thesis\n      unfolding OPT_def\n      by (subst Max_add_left;\n          fastforce intro: Max_mono finite_subset[OF _ finite_atLeastAtMost] dest: *\n         )\n  qed\n  ultimately have \"?lhs \\<ge> ?rhs\"\n    by auto\n\n  from S have *: \"sum v S \\<le> OPT i W\" if \"Suc i \\<notin> S\"\n    using that unfolding OPT_def by (auto simp: atLeastAtMostSuc_conv intro!: Max_ge)\n\n  have \"sum v S \\<le> OPT i W\" if \"W < w (Suc i)\"\n  proof (rule *, rule ccontr, simp)\n    assume \"Suc i \\<in> S\"\n    then have \"sum w S \\<ge> w (Suc i)\"\n      using S(1) by (subst sum.remove) (auto intro: finite_subset[OF _ finite_atLeastAtMost])\n    with \\<open>W < _\\<close> \\<open>_ \\<le> W\\<close> show False\n      by simp\n  qed\n  moreover have\n    \"OPT (Suc i) W \\<le> max(v (Suc i) + OPT i (W - w (Suc i))) (OPT i W)\" if \"w (Suc i) \\<le> W\"\n  proof (cases \"Suc i \\<in> S\")\n    case True\n    then have [simp]:\n      \"sum v S = v (Suc i) + sum v (S - {Suc i})\" \"sum w S = w (Suc i) + sum w (S - {Suc i})\"\n      using S(1) by (auto intro: finite_subset[OF _ finite_atLeastAtMost] sum.remove)\n    have \"OPT i (W - w (Suc i)) \\<ge> sum v (S - {Suc i})\"\n      unfolding OPT_def using S by (fastforce intro!: Max_ge)\n    then show ?thesis\n      by simp\n  next\n    case False\n    then show ?thesis\n      by (auto dest: *)\n  qed\n  ultimately have \"?lhs \\<le> ?rhs\"\n    by auto\n  with \\<open>?lhs \\<ge> ?rhs\\<close> show ?thesis\n    by simp\nqed\n\ntheorem knapsack_correct:\n  \"OPT n W = knapsack n W\"\n  by (induction n arbitrary: W; auto simp: OPT_0 OPT_Suc)\n\n\nsubsubsection \\<open>Functional Memoization\\<close>\n\nmemoize_fun knapsack\\<^sub>m: knapsack with_memory dp_consistency_mapping monadifies (state) knapsack.simps\n\ntext \\<open>Generated Definitions\\<close>\ncontext includes state_monad_syntax begin\nthm knapsack\\<^sub>m'.simps knapsack\\<^sub>m_def\nend\n\ntext \\<open>Correspondence Proof\\<close>\nmemoize_correct\n  by memoize_prover\nprint_theorems\nlemmas [code] = knapsack\\<^sub>m.memoized_correct\n\n\nsubsubsection \\<open>Imperative Memoization\\<close>\n\ncontext fixes\n  mem :: \"nat option array\"\n  and n W :: nat\nbegin\n\nmemoize_fun knapsack\\<^sub>T: knapsack\n  with_memory dp_consistency_heap_default where bound = \"Bound (0, 0) (n, W)\" and mem=\"mem\"\n  monadifies (heap) knapsack.simps\n\ncontext includes heap_monad_syntax begin\nthm knapsack\\<^sub>T'.simps knapsack\\<^sub>T_def\nend\n\nmemoize_correct\n  by memoize_prover\n\nlemmas memoized_empty = knapsack\\<^sub>T.memoized_empty\n\nend (* Fixed array *)\n\ntext \\<open>Adding Memory Initialization\\<close>\ncontext\n  includes heap_monad_syntax\n  notes [simp del] = knapsack\\<^sub>T'.simps\nbegin\n\ndefinition\n  \"knapsack\\<^sub>h \\<equiv> \\<lambda> i j. Heap_Monad.bind (mem_empty (i * j)) (\\<lambda> mem. knapsack\\<^sub>T' mem i j i j)\"\n\nlemmas memoized_empty' = memoized_empty[\n      of mem n W \"\\<lambda> m. \\<lambda>(i,j). knapsack\\<^sub>T' m n W i j\",\n      OF knapsack\\<^sub>T.crel[of mem n W], of \"(n, W)\" for mem n W\n    ]\n\nlemma knapsack_heap:\n  \"knapsack n W = result_of (knapsack\\<^sub>h n W) Heap.empty\"\n  unfolding knapsack\\<^sub>h_def using memoized_empty'[of _ n W] by (simp add: index_size_defs)\n\nend\n\nend (* Knapsack *)\n\nfun su :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"su 0 W = 0\" |\n  \"su (Suc i) W = (if W < w (Suc i)\n    then su i W\n    else max (su i W) (w (Suc i) + su i (W - w (Suc i))))\"\n\nlemma su_knapsack:\n  \"su n W = knapsack w n W\"\n  by (induction n arbitrary: W; simp)\n\nlemma su_correct:\n  \"Max {\\<Sum> i \\<in> S. w i | S. S \\<subseteq> {1..n} \\<and> (\\<Sum> i \\<in> S. w i) \\<le> W} = su n W\"\n  unfolding su_knapsack knapsack_correct[symmetric] OPT_def ..\n\nsubsubsection \\<open>Memoization\\<close>\n\nmemoize_fun su\\<^sub>m: su with_memory dp_consistency_mapping monadifies (state) su.simps\n\ntext \\<open>Generated Definitions\\<close>\ncontext includes state_monad_syntax begin\nthm su\\<^sub>m'.simps su\\<^sub>m_def\nend\n\ntext \\<open>Correspondence Proof\\<close>\nmemoize_correct\n  by memoize_prover\nprint_theorems\nlemmas [code] = su\\<^sub>m.memoized_correct\n\nend (* Subset Sum *)\n\n\nsubsubsection \\<open>Regression Test\\<close>\n\ndefinition\n  \"knapsack_test = (knapsack\\<^sub>h (\\<lambda> i. [2,3,4] ! (i - 1)) (\\<lambda> i. [2,3,4] ! (i - 1)) 3 8)\"\n\ncode_reflect Test functions knapsack_test\n\nML \\<open>Test.knapsack_test ()\\<close>\n\nend (* Theory *)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Monad_Memo_DP/example/Knapsack.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424450764199, "lm_q2_score": 0.8962513648201266, "lm_q1q2_score": 0.7581770709590163}}
{"text": "(*\n    Author:   Benedikt Seidl\n    License:  BSD\n*)\n\nsection \\<open>Equivalence Relations for LTL formulas\\<close>\n\ntheory Equivalence_Relations\nimports\n  LTL\nbegin\n\nsubsection \\<open>Language Equivalence\\<close>\n\ndefinition ltl_lang_equiv :: \"'a ltln \\<Rightarrow> 'a ltln \\<Rightarrow> bool\" (infix \"\\<sim>\\<^sub>L\" 75)\nwhere\n  \"\\<phi> \\<sim>\\<^sub>L \\<psi> \\<equiv> \\<forall>w. w \\<Turnstile>\\<^sub>n \\<phi> \\<longleftrightarrow> w \\<Turnstile>\\<^sub>n \\<psi>\"\n\nlemma ltl_lang_equiv_equivp:\n  \"equivp (\\<sim>\\<^sub>L)\"\n  unfolding ltl_lang_equiv_def\n  by (simp add: equivpI reflp_def symp_def transp_def)\n\n\n\nlemma ltl_lang_equiv_and_false[intro, simp]:\n  \"\\<phi>\\<^sub>1 \\<sim>\\<^sub>L false\\<^sub>n \\<Longrightarrow> \\<phi>\\<^sub>1 and\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>L false\\<^sub>n\"\n  \"\\<phi>\\<^sub>2 \\<sim>\\<^sub>L false\\<^sub>n \\<Longrightarrow> \\<phi>\\<^sub>1 and\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>L false\\<^sub>n\"\n  unfolding ltl_lang_equiv_def by auto\n\nlemma ltl_lang_equiv_or_false[simp]:\n  \"\\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>L false\\<^sub>n \\<longleftrightarrow> \\<phi>\\<^sub>1 \\<sim>\\<^sub>L false\\<^sub>n \\<and> \\<phi>\\<^sub>2 \\<sim>\\<^sub>L false\\<^sub>n\"\n  unfolding ltl_lang_equiv_def by auto\n\nlemma ltl_lang_equiv_or_const[intro, simp]:\n  \"\\<phi>\\<^sub>1 \\<sim>\\<^sub>L true\\<^sub>n \\<Longrightarrow> \\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>L true\\<^sub>n\"\n  \"\\<phi>\\<^sub>2 \\<sim>\\<^sub>L true\\<^sub>n \\<Longrightarrow> \\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>L true\\<^sub>n\"\n  unfolding ltl_lang_equiv_def by auto\n\n\nsubsection \\<open>Propositional Equivalence\\<close>\n\nfun ltl_prop_entailment :: \"'a ltln set \\<Rightarrow> 'a ltln \\<Rightarrow> bool\" (infix \"\\<Turnstile>\\<^sub>P\" 80)\nwhere\n  \"\\<A> \\<Turnstile>\\<^sub>P true\\<^sub>n = True\"\n| \"\\<A> \\<Turnstile>\\<^sub>P false\\<^sub>n = False\"\n| \"\\<A> \\<Turnstile>\\<^sub>P \\<phi> and\\<^sub>n \\<psi> = (\\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<and> \\<A> \\<Turnstile>\\<^sub>P \\<psi>)\"\n| \"\\<A> \\<Turnstile>\\<^sub>P \\<phi> or\\<^sub>n \\<psi> = (\\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<or> \\<A> \\<Turnstile>\\<^sub>P \\<psi>)\"\n| \"\\<A> \\<Turnstile>\\<^sub>P \\<phi> = (\\<phi> \\<in> \\<A>)\"\n\nlemma ltl_prop_entailment_monotonI[intro]:\n  \"S \\<Turnstile>\\<^sub>P \\<phi> \\<Longrightarrow> S \\<subseteq> S' \\<Longrightarrow> S' \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma ltl_models_equiv_prop_entailment:\n  \"w \\<Turnstile>\\<^sub>n \\<phi> \\<longleftrightarrow> {\\<psi>. w \\<Turnstile>\\<^sub>n \\<psi>} \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (induction \\<phi>) auto\n\ndefinition ltl_prop_equiv :: \"'a ltln \\<Rightarrow> 'a ltln \\<Rightarrow> bool\" (infix \"\\<sim>\\<^sub>P\" 75)\nwhere\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> \\<equiv> \\<forall>\\<A>. \\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<longleftrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi>\"\n\ndefinition ltl_prop_implies :: \"'a ltln \\<Rightarrow> 'a ltln \\<Rightarrow> bool\" (infix \"\\<longrightarrow>\\<^sub>P\" 75)\nwhere\n  \"\\<phi> \\<longrightarrow>\\<^sub>P \\<psi> \\<equiv> \\<forall>\\<A>. \\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<psi>\"\n\nlemma ltl_prop_implies_equiv:\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> \\<longleftrightarrow> (\\<phi> \\<longrightarrow>\\<^sub>P \\<psi> \\<and> \\<psi> \\<longrightarrow>\\<^sub>P \\<phi>)\"\n  unfolding ltl_prop_equiv_def ltl_prop_implies_def by meson\n\nlemma ltl_prop_equiv_equivp:\n  \"equivp (\\<sim>\\<^sub>P)\"\n  by (simp add: ltl_prop_equiv_def equivpI reflp_def symp_def transp_def)\n\nlemma ltl_prop_equiv_trans[trans]:\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> \\<Longrightarrow> \\<psi> \\<sim>\\<^sub>P \\<chi> \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>P \\<chi>\"\n  by (simp add: ltl_prop_equiv_def)\n\nlemma ltl_prop_equiv_true:\n  \"\\<phi> \\<sim>\\<^sub>P true\\<^sub>n \\<longleftrightarrow> {} \\<Turnstile>\\<^sub>P \\<phi>\"\n  using bot.extremum ltl_prop_entailment.simps(1) ltl_prop_equiv_def by blast\n\nlemma ltl_prop_equiv_false:\n  \"\\<phi> \\<sim>\\<^sub>P false\\<^sub>n \\<longleftrightarrow> \\<not> UNIV \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (meson ltl_prop_entailment.simps(2) ltl_prop_entailment_monotonI ltl_prop_equiv_def top_greatest)\n\nlemma ltl_prop_equiv_true_implies_true:\n  \"x \\<sim>\\<^sub>P true\\<^sub>n \\<Longrightarrow> x \\<longrightarrow>\\<^sub>P y \\<Longrightarrow> y \\<sim>\\<^sub>P true\\<^sub>n\"\n  by (simp add: ltl_prop_equiv_def ltl_prop_implies_def)\n\nlemma ltl_prop_equiv_false_implied_by_false:\n  \"y \\<sim>\\<^sub>P false\\<^sub>n \\<Longrightarrow> x \\<longrightarrow>\\<^sub>P y \\<Longrightarrow> x \\<sim>\\<^sub>P false\\<^sub>n\"\n  by (simp add: ltl_prop_equiv_def ltl_prop_implies_def)\n\nlemma ltl_prop_implication_implies_ltl_implication:\n  \"w \\<Turnstile>\\<^sub>n \\<phi> \\<Longrightarrow> \\<phi> \\<longrightarrow>\\<^sub>P \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<psi>\"\n  using ltl_models_equiv_prop_entailment ltl_prop_implies_def by blast\n\nlemma ltl_prop_equiv_implies_ltl_lang_equiv:\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>L \\<psi>\"\n  using ltl_lang_equiv_def ltl_prop_implication_implies_ltl_implication ltl_prop_implies_equiv by blast\n\nlemma ltl_prop_equiv_lt_ltl_lang_equiv[simp]:\n  \"(\\<sim>\\<^sub>P) \\<le> (\\<sim>\\<^sub>L)\"\n  using ltl_prop_equiv_implies_ltl_lang_equiv by blast\n\n\nsubsection \\<open>Constants Equivalence\\<close>\n\ndatatype tvl = Yes | No | Maybe\n\ndefinition eval_and :: \"tvl \\<Rightarrow> tvl \\<Rightarrow> tvl\"\nwhere\n  \"eval_and \\<phi> \\<psi> =\n    (case (\\<phi>, \\<psi>) of\n      (Yes, Yes) \\<Rightarrow> Yes\n    | (No, _) \\<Rightarrow> No\n    | (_, No) \\<Rightarrow> No\n    | _ \\<Rightarrow> Maybe)\"\n\ndefinition eval_or :: \"tvl \\<Rightarrow> tvl \\<Rightarrow> tvl\"\nwhere\n  \"eval_or \\<phi> \\<psi> =\n    (case (\\<phi>, \\<psi>) of\n      (No, No) \\<Rightarrow> No\n    | (Yes, _) \\<Rightarrow> Yes\n    | (_, Yes) \\<Rightarrow> Yes\n    | _ \\<Rightarrow> Maybe)\"\n\nfun eval :: \"'a ltln \\<Rightarrow> tvl\"\nwhere\n  \"eval true\\<^sub>n = Yes\"\n| \"eval false\\<^sub>n = No\"\n| \"eval (\\<phi> and\\<^sub>n \\<psi>) = eval_and (eval \\<phi>) (eval \\<psi>)\"\n| \"eval (\\<phi> or\\<^sub>n \\<psi>) = eval_or (eval \\<phi>) (eval \\<psi>)\"\n| \"eval \\<phi> = Maybe\"\n\nlemma eval_and_const[simp]:\n  \"eval_and \\<phi> \\<psi> = No \\<longleftrightarrow> \\<phi> = No \\<or> \\<psi> = No\"\n  \"eval_and \\<phi> \\<psi> = Yes \\<longleftrightarrow> \\<phi> = Yes \\<and> \\<psi> = Yes\"\n  unfolding eval_and_def\n  by (cases \\<phi>; cases \\<psi>, auto)+\n\nlemma eval_or_const[simp]:\n  \"eval_or \\<phi> \\<psi> = Yes \\<longleftrightarrow> \\<phi> = Yes \\<or> \\<psi> = Yes\"\n  \"eval_or \\<phi> \\<psi> = No \\<longleftrightarrow> \\<phi> = No \\<and> \\<psi> = No\"\n  unfolding eval_or_def\n  by (cases \\<phi>; cases \\<psi>, auto)+\n\nlemma eval_prop_entailment:\n  \"eval \\<phi> = Yes \\<longleftrightarrow> {} \\<Turnstile>\\<^sub>P \\<phi>\"\n  \"eval \\<phi> = No \\<longleftrightarrow> \\<not> UNIV \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (induction \\<phi>) auto\n\ndefinition ltl_const_equiv :: \"'a ltln \\<Rightarrow> 'a ltln \\<Rightarrow> bool\" (infix \"\\<sim>\\<^sub>C\" 75)\nwhere\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi> \\<equiv> \\<phi> = \\<psi> \\<or> (eval \\<phi> = eval \\<psi> \\<and> eval \\<psi> \\<noteq> Maybe)\"\n\nlemma ltl_const_equiv_equivp:\n  \"equivp (\\<sim>\\<^sub>C)\"\n  unfolding ltl_const_equiv_def\n  by (intro equivpI reflpI sympI transpI) auto\n\nlemma ltl_const_equiv_const:\n  \"\\<phi> \\<sim>\\<^sub>C true\\<^sub>n \\<longleftrightarrow> eval \\<phi> = Yes\"\n  \"\\<phi> \\<sim>\\<^sub>C false\\<^sub>n \\<longleftrightarrow> eval \\<phi> = No\"\n  unfolding ltl_const_equiv_def by force+\n\nlemma ltl_const_equiv_and_const[simp]:\n  \"\\<phi>\\<^sub>1 and\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>C true\\<^sub>n \\<longleftrightarrow> \\<phi>\\<^sub>1 \\<sim>\\<^sub>C true\\<^sub>n \\<and> \\<phi>\\<^sub>2 \\<sim>\\<^sub>C true\\<^sub>n\"\n  \"\\<phi>\\<^sub>1 and\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>C false\\<^sub>n \\<longleftrightarrow> \\<phi>\\<^sub>1 \\<sim>\\<^sub>C false\\<^sub>n \\<or> \\<phi>\\<^sub>2 \\<sim>\\<^sub>C false\\<^sub>n\"\n  unfolding ltl_const_equiv_const by force+\n\nlemma ltl_const_equiv_or_const[simp]:\n  \"\\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>C true\\<^sub>n \\<longleftrightarrow> \\<phi>\\<^sub>1 \\<sim>\\<^sub>C true\\<^sub>n \\<or> \\<phi>\\<^sub>2 \\<sim>\\<^sub>C true\\<^sub>n\"\n  \"\\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<sim>\\<^sub>C false\\<^sub>n \\<longleftrightarrow> \\<phi>\\<^sub>1 \\<sim>\\<^sub>C false\\<^sub>n \\<and> \\<phi>\\<^sub>2 \\<sim>\\<^sub>C false\\<^sub>n\"\n  unfolding ltl_const_equiv_const by force+\n\nlemma ltl_const_equiv_other[simp]:\n  \"\\<phi> \\<sim>\\<^sub>C prop\\<^sub>n(a) \\<longleftrightarrow> \\<phi> = prop\\<^sub>n(a)\"\n  \"\\<phi> \\<sim>\\<^sub>C nprop\\<^sub>n(a) \\<longleftrightarrow> \\<phi> = nprop\\<^sub>n(a)\"\n  \"\\<phi> \\<sim>\\<^sub>C X\\<^sub>n \\<psi> \\<longleftrightarrow> \\<phi> = X\\<^sub>n \\<psi>\"\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi>\\<^sub>1 U\\<^sub>n \\<psi>\\<^sub>2 \\<longleftrightarrow> \\<phi> = \\<psi>\\<^sub>1 U\\<^sub>n \\<psi>\\<^sub>2\"\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi>\\<^sub>1 R\\<^sub>n \\<psi>\\<^sub>2 \\<longleftrightarrow> \\<phi> = \\<psi>\\<^sub>1 R\\<^sub>n \\<psi>\\<^sub>2\"\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi>\\<^sub>1 W\\<^sub>n \\<psi>\\<^sub>2 \\<longleftrightarrow> \\<phi> = \\<psi>\\<^sub>1 W\\<^sub>n \\<psi>\\<^sub>2\"\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi>\\<^sub>1 M\\<^sub>n \\<psi>\\<^sub>2 \\<longleftrightarrow> \\<phi> = \\<psi>\\<^sub>1 M\\<^sub>n \\<psi>\\<^sub>2\"\n  using ltl_const_equiv_def by fastforce+\n\nlemma ltl_const_equiv_no_const_singleton:\n  \"eval \\<psi> = Maybe \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>C \\<psi> \\<Longrightarrow> \\<phi> = \\<psi>\"\n  unfolding ltl_const_equiv_def by fastforce\n\nlemma ltl_const_equiv_implies_prop_equiv:\n  \"\\<phi> \\<sim>\\<^sub>C true\\<^sub>n \\<longleftrightarrow> \\<phi> \\<sim>\\<^sub>P true\\<^sub>n\"\n  \"\\<phi> \\<sim>\\<^sub>C false\\<^sub>n \\<longleftrightarrow> \\<phi> \\<sim>\\<^sub>P false\\<^sub>n\"\n  unfolding ltl_const_equiv_const eval_prop_entailment ltl_prop_equiv_def\n  by auto\n\nlemma ltl_const_equiv_no_const_prop_equiv:\n  \"eval \\<psi> = Maybe \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>C \\<psi> \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>P \\<psi>\"\n  using ltl_const_equiv_no_const_singleton equivp_reflp[OF ltl_prop_equiv_equivp]\n  by blast\n\nlemma ltl_const_equiv_implies_ltl_prop_equiv:\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi> \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>P \\<psi>\"\nproof (induction \\<psi>)\n  case (And_ltln \\<psi>1 \\<psi>2)\n\n  show ?case\n  proof (cases \"eval (\\<psi>1 and\\<^sub>n \\<psi>2)\")\n    case Yes\n\n    then have \"\\<phi> \\<sim>\\<^sub>C true\\<^sub>n\"\n      by (meson And_ltln.prems equivp_transp ltl_const_equiv_const(1) ltl_const_equiv_equivp)\n    then show ?thesis\n      by (metis (full_types) Yes ltl_const_equiv_const(1) ltl_const_equiv_implies_prop_equiv(1) ltl_prop_equiv_trans ltl_prop_implies_equiv)\n  next\n    case No\n\n    then have \"\\<phi> \\<sim>\\<^sub>C false\\<^sub>n\"\n      by (meson And_ltln.prems equivp_transp ltl_const_equiv_const(2) ltl_const_equiv_equivp)\n    then show ?thesis\n      by (metis (full_types) No ltl_const_equiv_const(2) ltl_const_equiv_implies_prop_equiv(2) ltl_prop_equiv_trans ltl_prop_implies_equiv)\n  next\n    case Maybe\n\n    then show ?thesis\n      using And_ltln.prems ltl_const_equiv_no_const_prop_equiv by force\n  qed\nnext\n  case (Or_ltln \\<psi>1 \\<psi>2)\n\n  then show ?case\n  proof (cases \"eval (\\<psi>1 or\\<^sub>n \\<psi>2)\")\n    case Yes\n\n    then have \"\\<phi> \\<sim>\\<^sub>C true\\<^sub>n\"\n      by (meson Or_ltln.prems equivp_transp ltl_const_equiv_const(1) ltl_const_equiv_equivp)\n    then show ?thesis\n      by (metis (full_types) Yes ltl_const_equiv_const(1) ltl_const_equiv_implies_prop_equiv(1) ltl_prop_equiv_trans ltl_prop_implies_equiv)\n  next\n    case No\n\n    then have \"\\<phi> \\<sim>\\<^sub>C false\\<^sub>n\"\n      by (meson Or_ltln.prems equivp_transp ltl_const_equiv_const(2) ltl_const_equiv_equivp)\n    then show ?thesis\n      by (metis (full_types) No ltl_const_equiv_const(2) ltl_const_equiv_implies_prop_equiv(2) ltl_prop_equiv_trans ltl_prop_implies_equiv)\n  next\n    case Maybe\n\n    then show ?thesis\n      using Or_ltln.prems ltl_const_equiv_no_const_prop_equiv by force\n  qed\nqed (simp_all add: ltl_const_equiv_implies_prop_equiv equivp_reflp[OF ltl_prop_equiv_equivp])\n\nlemma ltl_const_equiv_lt_ltl_prop_equiv[simp]:\n  \"(\\<sim>\\<^sub>C) \\<le> (\\<sim>\\<^sub>P)\"\n  using ltl_const_equiv_implies_ltl_prop_equiv by blast\n\n\nsubsection \\<open>Quotient types\\<close>\n\nquotient_type 'a ltln\\<^sub>L = \"'a ltln\" / \"(\\<sim>\\<^sub>L)\"\n  by (rule ltl_lang_equiv_equivp)\n\ninstantiation ltln\\<^sub>L :: (type) equal\nbegin\n\nlift_definition ltln\\<^sub>L_eq_test :: \"'a ltln\\<^sub>L \\<Rightarrow> 'a ltln\\<^sub>L \\<Rightarrow> bool\" is \"\\<lambda>x y. x \\<sim>\\<^sub>L y\"\n  by (metis ltln\\<^sub>L.abs_eq_iff)\n\ndefinition\n  eq\\<^sub>L: \"equal_class.equal \\<equiv> ltln\\<^sub>L_eq_test\"\n\ninstance\n  by (standard; simp add: eq\\<^sub>L ltln\\<^sub>L_eq_test.rep_eq, metis Quotient_ltln\\<^sub>L Quotient_rel_rep)\n\nend\n\n\nquotient_type 'a ltln\\<^sub>P = \"'a ltln\" / \"(\\<sim>\\<^sub>P)\"\n  by (rule ltl_prop_equiv_equivp)\n\ninstantiation ltln\\<^sub>P :: (type) equal\nbegin\n\nlift_definition ltln\\<^sub>P_eq_test :: \"'a ltln\\<^sub>P \\<Rightarrow> 'a ltln\\<^sub>P \\<Rightarrow> bool\" is \"\\<lambda>x y. x \\<sim>\\<^sub>P y\"\n  by (metis ltln\\<^sub>P.abs_eq_iff)\n\ndefinition\n  eq\\<^sub>P: \"equal_class.equal \\<equiv> ltln\\<^sub>P_eq_test\"\n\ninstance\n  by (standard; simp add: eq\\<^sub>P ltln\\<^sub>P_eq_test.rep_eq, metis Quotient_ltln\\<^sub>P Quotient_rel_rep)\n\nend\n\n\nquotient_type 'a ltln\\<^sub>C = \"'a ltln\" / \"(\\<sim>\\<^sub>C)\"\n  by (rule ltl_const_equiv_equivp)\n\ninstantiation ltln\\<^sub>C :: (type) equal\nbegin\n\nlift_definition ltln\\<^sub>C_eq_test :: \"'a ltln\\<^sub>C \\<Rightarrow> 'a ltln\\<^sub>C \\<Rightarrow> bool\" is \"\\<lambda>x y. x \\<sim>\\<^sub>C y\"\n  by (metis ltln\\<^sub>C.abs_eq_iff)\n\ndefinition\n  eq\\<^sub>C: \"equal_class.equal \\<equiv> ltln\\<^sub>C_eq_test\"\n\ninstance\n  by (standard; simp add: eq\\<^sub>C ltln\\<^sub>C_eq_test.rep_eq, metis Quotient_ltln\\<^sub>C Quotient_rel_rep)\n\nend\n\n\n\nsubsection \\<open>Cardinality of propositional quotient sets\\<close>\n\ndefinition sat_models :: \"'a ltln\\<^sub>P \\<Rightarrow> 'a ltln set set\"\nwhere\n  \"sat_models \\<phi> = {\\<A>. \\<A> \\<Turnstile>\\<^sub>P rep_ltln\\<^sub>P \\<phi>}\"\n\nlemma Rep_Abs_prop_entailment[simp]:\n  \"\\<A> \\<Turnstile>\\<^sub>P rep_ltln\\<^sub>P (abs_ltln\\<^sub>P \\<phi>) = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (metis Quotient3_ltln\\<^sub>P Quotient3_rep_abs ltl_prop_equiv_def)\n\nlemma sat_models_Abs:\n  \"\\<A> \\<in> sat_models (abs_ltln\\<^sub>P \\<phi>) = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (simp add: sat_models_def)\n\nlemma sat_models_inj:\n  \"inj sat_models\"\nproof (rule injI)\n  fix \\<phi> \\<psi> :: \"'a ltln\\<^sub>P\"\n  assume \"sat_models \\<phi> = sat_models \\<psi>\"\n\n  then have \"rep_ltln\\<^sub>P \\<phi> \\<sim>\\<^sub>P rep_ltln\\<^sub>P \\<psi>\"\n    unfolding sat_models_def ltl_prop_equiv_def by force\n\n  then show \"\\<phi> = \\<psi>\"\n    by (meson Quotient3_ltln\\<^sub>P Quotient3_rel_rep)\nqed\n\n\nfun prop_atoms :: \"'a ltln \\<Rightarrow> 'a ltln set\"\nwhere\n  \"prop_atoms true\\<^sub>n = {}\"\n| \"prop_atoms false\\<^sub>n = {}\"\n| \"prop_atoms (\\<phi> and\\<^sub>n \\<psi>) = prop_atoms \\<phi> \\<union> prop_atoms \\<psi>\"\n| \"prop_atoms (\\<phi> or\\<^sub>n \\<psi>) = prop_atoms \\<phi> \\<union> prop_atoms \\<psi>\"\n| \"prop_atoms \\<phi> = {\\<phi>}\"\n\nfun nested_prop_atoms :: \"'a ltln \\<Rightarrow> 'a ltln set\"\nwhere\n  \"nested_prop_atoms true\\<^sub>n = {}\"\n| \"nested_prop_atoms false\\<^sub>n = {}\"\n| \"nested_prop_atoms (\\<phi> and\\<^sub>n \\<psi>) = nested_prop_atoms \\<phi> \\<union> nested_prop_atoms \\<psi>\"\n| \"nested_prop_atoms (\\<phi> or\\<^sub>n \\<psi>) = nested_prop_atoms \\<phi> \\<union> nested_prop_atoms \\<psi>\"\n| \"nested_prop_atoms (X\\<^sub>n \\<phi>) = {X\\<^sub>n \\<phi>} \\<union> nested_prop_atoms \\<phi>\"\n| \"nested_prop_atoms (\\<phi> U\\<^sub>n \\<psi>) = {\\<phi> U\\<^sub>n \\<psi>} \\<union> nested_prop_atoms \\<phi> \\<union> nested_prop_atoms \\<psi>\"\n| \"nested_prop_atoms (\\<phi> R\\<^sub>n \\<psi>) = {\\<phi> R\\<^sub>n \\<psi>} \\<union> nested_prop_atoms \\<phi> \\<union> nested_prop_atoms \\<psi>\"\n| \"nested_prop_atoms (\\<phi> W\\<^sub>n \\<psi>) = {\\<phi> W\\<^sub>n \\<psi>} \\<union> nested_prop_atoms \\<phi> \\<union> nested_prop_atoms \\<psi>\"\n| \"nested_prop_atoms (\\<phi> M\\<^sub>n \\<psi>) = {\\<phi> M\\<^sub>n \\<psi>} \\<union> nested_prop_atoms \\<phi> \\<union> nested_prop_atoms \\<psi>\"\n| \"nested_prop_atoms \\<phi> = {\\<phi>}\"\n\nlemma prop_atoms_nested_prop_atoms:\n  \"prop_atoms \\<phi> \\<subseteq> nested_prop_atoms \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma prop_atoms_subfrmlsn:\n  \"prop_atoms \\<phi> \\<subseteq> subfrmlsn \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma nested_prop_atoms_subfrmlsn:\n  \"nested_prop_atoms \\<phi> \\<subseteq> subfrmlsn \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma prop_atoms_notin[simp]:\n  \"true\\<^sub>n \\<notin> prop_atoms \\<phi>\"\n  \"false\\<^sub>n \\<notin> prop_atoms \\<phi>\"\n  \"\\<phi>\\<^sub>1 and\\<^sub>n \\<phi>\\<^sub>2 \\<notin> prop_atoms \\<phi>\"\n  \"\\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<notin> prop_atoms \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma nested_prop_atoms_notin[simp]:\n  \"true\\<^sub>n \\<notin> nested_prop_atoms \\<phi>\"\n  \"false\\<^sub>n \\<notin> nested_prop_atoms \\<phi>\"\n  \"\\<phi>\\<^sub>1 and\\<^sub>n \\<phi>\\<^sub>2 \\<notin> nested_prop_atoms \\<phi>\"\n  \"\\<phi>\\<^sub>1 or\\<^sub>n \\<phi>\\<^sub>2 \\<notin> nested_prop_atoms \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma prop_atoms_finite:\n  \"finite (prop_atoms \\<phi>)\"\n  by (induction \\<phi>) auto\n\nlemma nested_prop_atoms_finite:\n  \"finite (nested_prop_atoms \\<phi>)\"\n  by (induction \\<phi>) auto\n\nlemma prop_atoms_entailment_iff:\n  \"\\<phi> \\<in> prop_atoms \\<psi> \\<Longrightarrow> \\<A> \\<Turnstile>\\<^sub>P \\<phi> \\<longleftrightarrow> \\<phi> \\<in> \\<A>\"\n  by (induction \\<phi>) auto\n\nlemma prop_atoms_entailment_inter:\n  \"prop_atoms \\<phi> \\<subseteq> P \\<Longrightarrow> (\\<A> \\<inter> P) \\<Turnstile>\\<^sub>P \\<phi> = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma nested_prop_atoms_entailment_inter:\n  \"nested_prop_atoms \\<phi> \\<subseteq> P \\<Longrightarrow> (\\<A> \\<inter> P) \\<Turnstile>\\<^sub>P \\<phi> = \\<A> \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (induction \\<phi>) auto\n\nlemma sat_models_inter_inj_helper:\n  assumes\n    \"prop_atoms \\<phi> \\<subseteq> P\"\n  and\n    \"prop_atoms \\<psi> \\<subseteq> P\"\n  and\n    \"sat_models (abs_ltln\\<^sub>P \\<phi>) \\<inter> Pow P = sat_models (abs_ltln\\<^sub>P \\<psi>) \\<inter> Pow P\"\n  shows\n    \"\\<phi> \\<sim>\\<^sub>P \\<psi>\"\nproof -\n  from assms have \"\\<forall>\\<A>. (\\<A> \\<inter> P) \\<Turnstile>\\<^sub>P \\<phi> \\<longleftrightarrow> (\\<A> \\<inter> P) \\<Turnstile>\\<^sub>P \\<psi>\"\n    by (auto simp: sat_models_Abs)\n\n  with assms show \"\\<phi> \\<sim>\\<^sub>P \\<psi>\"\n    by (simp add: prop_atoms_entailment_inter ltl_prop_equiv_def)\nqed\n\nlemma sat_models_inter_inj:\n  \"inj_on (\\<lambda>\\<phi>. sat_models \\<phi> \\<inter> Pow P) {abs_ltln\\<^sub>P \\<phi> |\\<phi>. prop_atoms \\<phi> \\<subseteq> P}\"\n  by (auto simp: inj_on_def sat_models_inter_inj_helper ltln\\<^sub>P.abs_eq_iff)\n\nlemma sat_models_pow_pow:\n  \"{sat_models (abs_ltln\\<^sub>P \\<phi>) \\<inter> Pow P | \\<phi>. prop_atoms \\<phi> \\<subseteq> P} \\<subseteq> Pow (Pow P)\"\n  by (auto simp: sat_models_def)\n\nlemma sat_models_finite:\n  \"finite P \\<Longrightarrow> finite {sat_models (abs_ltln\\<^sub>P \\<phi>) \\<inter> Pow P | \\<phi>. prop_atoms \\<phi> \\<subseteq> P}\"\n  using sat_models_pow_pow finite_subset by fastforce\n\nlemma sat_models_card:\n  \"finite P \\<Longrightarrow> card ({sat_models (abs_ltln\\<^sub>P \\<phi>) \\<inter> Pow P | \\<phi>. prop_atoms \\<phi> \\<subseteq> P}) \\<le> 2 ^ 2 ^ card P\"\n  by (metis (mono_tags, lifting) sat_models_pow_pow Pow_def card_Pow card_mono finite_Collect_subsets)\n\n\nlemma image_filter:\n  \"f ` {g a | a. P a} = {f (g a) | a. P a}\"\n  by blast\n\nlemma prop_equiv_finite:\n  \"finite P \\<Longrightarrow> finite {abs_ltln\\<^sub>P \\<psi> | \\<psi>. prop_atoms \\<psi> \\<subseteq> P}\"\n  by (auto simp: image_filter sat_models_finite finite_imageD[OF _ sat_models_inter_inj])\n\nlemma prop_equiv_card:\n  \"finite P \\<Longrightarrow> card {abs_ltln\\<^sub>P \\<psi> | \\<psi>. prop_atoms \\<psi> \\<subseteq> P} \\<le> 2 ^ 2 ^ card P\"\n  by (auto simp: image_filter sat_models_card card_image[OF sat_models_inter_inj, symmetric])\n\n\nlemma prop_equiv_subset:\n  \"{abs_ltln\\<^sub>P \\<psi> |\\<psi>. nested_prop_atoms \\<psi> \\<subseteq> P} \\<subseteq> {abs_ltln\\<^sub>P \\<psi> |\\<psi>. prop_atoms \\<psi> \\<subseteq> P}\"\n  using prop_atoms_nested_prop_atoms by blast\n\nlemma prop_equiv_finite':\n  \"finite P \\<Longrightarrow> finite {abs_ltln\\<^sub>P \\<psi> | \\<psi>. nested_prop_atoms \\<psi> \\<subseteq> P}\"\n  using prop_equiv_finite prop_equiv_subset finite_subset by fast\n\nlemma prop_equiv_card':\n  \"finite P \\<Longrightarrow> card {abs_ltln\\<^sub>P \\<psi> | \\<psi>. nested_prop_atoms \\<psi> \\<subseteq> P} \\<le> 2 ^ 2 ^ card P\"\n  by (metis (mono_tags, lifting) prop_equiv_card prop_equiv_subset prop_equiv_finite card_mono le_trans)\n\n\n\nsubsection \\<open>Substitution\\<close>\n\nfun subst :: \"'a ltln \\<Rightarrow> ('a ltln \\<rightharpoonup> 'a ltln) \\<Rightarrow> 'a ltln\"\nwhere\n  \"subst true\\<^sub>n m = true\\<^sub>n\"\n| \"subst false\\<^sub>n m = false\\<^sub>n\"\n| \"subst (\\<phi> and\\<^sub>n \\<psi>) m = subst \\<phi> m and\\<^sub>n subst \\<psi> m\"\n| \"subst (\\<phi> or\\<^sub>n \\<psi>) m = subst \\<phi> m or\\<^sub>n subst \\<psi> m\"\n| \"subst \\<phi> m = (case m \\<phi> of Some \\<psi> \\<Rightarrow> \\<psi> | None \\<Rightarrow> \\<phi>)\"\n\ntext \\<open>Based on Uwe Schoening's Translation Lemma (Logic for CS, p. 54)\\<close>\n\nlemma ltl_prop_equiv_subst_S:\n  \"S \\<Turnstile>\\<^sub>P subst \\<phi> m = ((S - dom m) \\<union> {\\<chi> | \\<chi> \\<chi>'. \\<chi> \\<in> dom m \\<and> m \\<chi> = Some \\<chi>' \\<and> S \\<Turnstile>\\<^sub>P \\<chi>'}) \\<Turnstile>\\<^sub>P \\<phi>\"\n  by (induction \\<phi>) (auto split: option.split)\n\nlemma subst_respects_ltl_prop_entailment:\n  \"\\<phi> \\<longrightarrow>\\<^sub>P \\<psi> \\<Longrightarrow> subst \\<phi> m \\<longrightarrow>\\<^sub>P subst \\<psi> m\"\n  \"\\<phi> \\<sim>\\<^sub>P \\<psi> \\<Longrightarrow> subst \\<phi> m \\<sim>\\<^sub>P subst \\<psi> m\"\n  unfolding ltl_prop_equiv_def ltl_prop_implies_def ltl_prop_equiv_subst_S by blast+\n\n\nlemma eval_subst:\n  \"eval \\<phi> = Yes \\<Longrightarrow> eval (subst \\<phi> m) = Yes\"\n  \"eval \\<phi> = No \\<Longrightarrow> eval (subst \\<phi> m) = No\"\n  by (meson empty_subsetI eval_prop_entailment ltl_prop_entailment_monotonI ltl_prop_equiv_subst_S subset_UNIV)+\n\nlemma subst_respects_ltl_const_entailment:\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi> \\<Longrightarrow> subst \\<phi> m \\<sim>\\<^sub>C subst \\<psi> m\"\n  unfolding ltl_const_equiv_def\n  by (cases \"eval \\<psi>\") (metis eval_subst(1), metis eval_subst(2), blast)\n\n\n\nsubsection \\<open>Order of Equivalence Relations\\<close>\n\nlocale ltl_equivalence =\n  fixes\n    eq :: \"'a ltln \\<Rightarrow> 'a ltln \\<Rightarrow> bool\" (infix \"\\<sim>\" 75)\n  assumes\n    eq_equivp: \"equivp (\\<sim>)\"\n  and\n    ge_const_equiv: \"(\\<sim>\\<^sub>C) \\<le> (\\<sim>)\"\n  and\n    le_lang_equiv: \"(\\<sim>) \\<le> (\\<sim>\\<^sub>L)\"\nbegin\n\nlemma eq_implies_ltl_equiv:\n  \"\\<phi> \\<sim> \\<psi> \\<Longrightarrow> w \\<Turnstile>\\<^sub>n \\<phi> = w \\<Turnstile>\\<^sub>n \\<psi>\"\n  using le_lang_equiv ltl_lang_equiv_def by blast\n\nlemma const_implies_eq:\n  \"\\<phi> \\<sim>\\<^sub>C \\<psi> \\<Longrightarrow> \\<phi> \\<sim> \\<psi>\"\n  using ge_const_equiv by blast\n\nlemma eq_implies_lang:\n  \"\\<phi> \\<sim> \\<psi> \\<Longrightarrow> \\<phi> \\<sim>\\<^sub>L \\<psi>\"\n  using le_lang_equiv by blast\n\nlemma eq_refl[simp]:\n  \"\\<phi> \\<sim> \\<phi>\"\n  by (meson eq_equivp equivp_reflp)\n\nlemma eq_sym[sym]:\n  \"\\<phi> \\<sim> \\<psi> \\<Longrightarrow> \\<psi> \\<sim> \\<phi>\"\n  by (meson eq_equivp equivp_symp)\n\nlemma eq_trans[trans]:\n  \"\\<phi> \\<sim> \\<psi> \\<Longrightarrow> \\<psi> \\<sim> \\<chi> \\<Longrightarrow> \\<phi> \\<sim> \\<chi>\"\n  by (meson eq_equivp equivp_transp)\n\nend\n\ninterpretation ltl_lang_equivalence: ltl_equivalence \"(\\<sim>\\<^sub>L)\"\n  using ltl_lang_equiv_equivp ltl_const_equiv_lt_ltl_prop_equiv ltl_prop_equiv_lt_ltl_lang_equiv\n  by unfold_locales blast+\n\ninterpretation ltl_prop_equivalence: ltl_equivalence \"(\\<sim>\\<^sub>P)\"\n  using ltl_prop_equiv_equivp ltl_const_equiv_lt_ltl_prop_equiv ltl_prop_equiv_lt_ltl_lang_equiv\n  by unfold_locales blast+\n\ninterpretation ltl_const_equivalence: ltl_equivalence \"(\\<sim>\\<^sub>C)\"\n  using ltl_const_equiv_equivp ltl_const_equiv_lt_ltl_prop_equiv ltl_prop_equiv_lt_ltl_lang_equiv\n  by unfold_locales blast+\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/LTL/Equivalence_Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122288794595, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7580444283830783}}
{"text": "(*  Title:      HOL/Computational_Algebra/Normalized_Fraction.thy\n    Author:     Manuel Eberl\n*)\n\ntheory Normalized_Fraction\nimports \n  MainRLT\n  Euclidean_Algorithm\n  Fraction_Field\nbegin\n\ndefinition quot_to_fract :: \"'a :: {idom} \\<times> 'a \\<Rightarrow> 'a fract\" where\n  \"quot_to_fract = (\\<lambda>(a,b). Fraction_Field.Fract a b)\"\n\ndefinition normalize_quot :: \"'a :: {ring_gcd,idom_divide,semiring_gcd_mult_normalize} \\<times> 'a \\<Rightarrow> 'a \\<times> 'a\" where\n  \"normalize_quot = \n     (\\<lambda>(a,b). if b = 0 then (0,1) else let d = gcd a b * unit_factor b in (a div d, b div d))\" \n\nlemma normalize_quot_zero [simp]:\n  \"normalize_quot (a, 0) = (0, 1)\"\n  by (simp add: normalize_quot_def)\n\nlemma normalize_quot_proj:\n  \"fst (normalize_quot (a, b)) = a div (gcd a b * unit_factor b)\"\n  \"snd (normalize_quot (a, b)) = normalize b div gcd a b\" if \"b \\<noteq> 0\"\n  using that by (simp_all add: normalize_quot_def Let_def mult.commute [of _ \"unit_factor b\"] dvd_div_mult2_eq mult_unit_dvd_iff')\n\ndefinition normalized_fracts :: \"('a :: {ring_gcd,idom_divide} \\<times> 'a) set\" where\n  \"normalized_fracts = {(a,b). coprime a b \\<and> unit_factor b = 1}\"\n  \nlemma not_normalized_fracts_0_denom [simp]: \"(a, 0) \\<notin> normalized_fracts\"\n  by (auto simp: normalized_fracts_def)\n\nlemma unit_factor_snd_normalize_quot [simp]:\n  \"unit_factor (snd (normalize_quot x)) = 1\"\n  by (simp add: normalize_quot_def case_prod_unfold Let_def dvd_unit_factor_div\n                mult_unit_dvd_iff unit_factor_mult unit_factor_gcd)\n  \nlemma snd_normalize_quot_nonzero [simp]: \"snd (normalize_quot x) \\<noteq> 0\"\n  using unit_factor_snd_normalize_quot[of x] \n  by (auto simp del: unit_factor_snd_normalize_quot)\n  \nlemma normalize_quot_aux:\n  fixes a b\n  assumes \"b \\<noteq> 0\"\n  defines \"d \\<equiv> gcd a b * unit_factor b\"\n  shows   \"a = fst (normalize_quot (a,b)) * d\" \"b = snd (normalize_quot (a,b)) * d\"\n          \"d dvd a\" \"d dvd b\" \"d \\<noteq> 0\"\nproof -\n  from assms show \"d dvd a\" \"d dvd b\"\n    by (simp_all add: d_def mult_unit_dvd_iff)\n  thus \"a = fst (normalize_quot (a,b)) * d\" \"b = snd (normalize_quot (a,b)) * d\" \"d \\<noteq> 0\"\n    by (auto simp: normalize_quot_def Let_def d_def \\<open>b \\<noteq> 0\\<close>)\nqed\n\nlemma normalize_quotE:\n  assumes \"b \\<noteq> 0\"\n  obtains d where \"a = fst (normalize_quot (a,b)) * d\" \"b = snd (normalize_quot (a,b)) * d\"\n                  \"d dvd a\" \"d dvd b\" \"d \\<noteq> 0\"\n  using that[OF normalize_quot_aux[OF assms]] .\n  \nlemma normalize_quotE':\n  assumes \"snd x \\<noteq> 0\"\n  obtains d where \"fst x = fst (normalize_quot x) * d\" \"snd x = snd (normalize_quot x) * d\"\n                  \"d dvd fst x\" \"d dvd snd x\" \"d \\<noteq> 0\"\nproof -\n  from normalize_quotE[OF assms, of \"fst x\"] obtain d where\n    \"fst x = fst (normalize_quot (fst x, snd x)) * d\"\n    \"snd x = snd (normalize_quot (fst x, snd x)) * d\"\n    \"d dvd fst x\"\n    \"d dvd snd x\"\n    \"d \\<noteq> 0\" .\n  then show ?thesis unfolding prod.collapse by (intro that[of d])\nqed\n  \nlemma coprime_normalize_quot:\n  \"coprime (fst (normalize_quot x)) (snd (normalize_quot x))\"\n  by (simp add: normalize_quot_def case_prod_unfold div_mult_unit2)\n    (metis coprime_mult_self_right_iff div_gcd_coprime unit_div_mult_self unit_factor_is_unit)\n\nlemma normalize_quot_in_normalized_fracts [simp]: \"normalize_quot x \\<in> normalized_fracts\"\n  by (simp add: normalized_fracts_def coprime_normalize_quot case_prod_unfold)\n\nlemma normalize_quot_eq_iff:\n  assumes \"b \\<noteq> 0\" \"d \\<noteq> 0\"\n  shows   \"normalize_quot (a,b) = normalize_quot (c,d) \\<longleftrightarrow> a * d = b * c\"\nproof -\n  define x y where \"x = normalize_quot (a,b)\" and \"y = normalize_quot (c,d)\" \n  from normalize_quotE[OF assms(1), of a] normalize_quotE[OF assms(2), of c]\n    obtain d1 d2 \n      where \"a = fst x * d1\" \"b = snd x * d1\" \"c = fst y * d2\" \"d = snd y * d2\" \"d1 \\<noteq> 0\" \"d2 \\<noteq> 0\"\n    unfolding x_def y_def by metis\n  hence \"a * d = b * c \\<longleftrightarrow> fst x * snd y = snd x * fst y\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> fst x = fst y \\<and> snd x = snd y\"\n    by (intro coprime_crossproduct') (simp_all add: x_def y_def coprime_normalize_quot)\n  also have \"\\<dots> \\<longleftrightarrow> x = y\" using prod_eqI by blast\n  finally show \"x = y \\<longleftrightarrow> a * d = b * c\" ..\nqed\n\nlemma normalize_quot_eq_iff':\n  assumes \"snd x \\<noteq> 0\" \"snd y \\<noteq> 0\"\n  shows   \"normalize_quot x = normalize_quot y \\<longleftrightarrow> fst x * snd y = snd x * fst y\"\n  using assms by (cases x, cases y, hypsubst) (subst normalize_quot_eq_iff, simp_all)\n\nlemma normalize_quot_id: \"x \\<in> normalized_fracts \\<Longrightarrow> normalize_quot x = x\"\n  by (auto simp: normalized_fracts_def normalize_quot_def case_prod_unfold)\n\nlemma normalize_quot_idem [simp]: \"normalize_quot (normalize_quot x) = normalize_quot x\"\n  by (rule normalize_quot_id) simp_all\n\nlemma fractrel_iff_normalize_quot_eq:\n  \"fractrel x y \\<longleftrightarrow> normalize_quot x = normalize_quot y \\<and> snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0\"\n  by (cases x, cases y) (auto simp: fractrel_def normalize_quot_eq_iff)\n  \nlemma fractrel_normalize_quot_left:\n  assumes \"snd x \\<noteq> 0\"\n  shows   \"fractrel (normalize_quot x) y \\<longleftrightarrow> fractrel x y\"\n  using assms by (subst (1 2) fractrel_iff_normalize_quot_eq) auto\n\nlemma fractrel_normalize_quot_right:\n  assumes \"snd x \\<noteq> 0\"\n  shows   \"fractrel y (normalize_quot x) \\<longleftrightarrow> fractrel y x\"\n  using assms by (subst (1 2) fractrel_iff_normalize_quot_eq) auto\n\n  \nlift_definition quot_of_fract :: \n  \"'a :: {ring_gcd,idom_divide,semiring_gcd_mult_normalize} fract \\<Rightarrow> 'a \\<times> 'a\" \n    is normalize_quot\n  by (subst (asm) fractrel_iff_normalize_quot_eq) simp_all\n  \nlemma quot_to_fract_quot_of_fract [simp]: \"quot_to_fract (quot_of_fract x) = x\"\n  unfolding quot_to_fract_def\nproof transfer\n  fix x :: \"'a \\<times> 'a\" assume rel: \"fractrel x x\"\n  define x' where \"x' = normalize_quot x\"\n  obtain a b where [simp]: \"x = (a, b)\" by (cases x)\n  from rel have \"b \\<noteq> 0\" by simp\n  from normalize_quotE[OF this, of a] obtain d\n    where\n      \"a = fst (normalize_quot (a, b)) * d\"\n      \"b = snd (normalize_quot (a, b)) * d\"\n      \"d dvd a\"\n      \"d dvd b\"\n      \"d \\<noteq> 0\" .\n  hence \"a = fst x' * d\" \"b = snd x' * d\" \"d \\<noteq> 0\" \"snd x' \\<noteq> 0\" by (simp_all add: x'_def)\n  thus \"fractrel (case x' of (a, b) \\<Rightarrow> if b = 0 then (0, 1) else (a, b)) x\"\n    by (auto simp add: case_prod_unfold)\nqed\n\nlemma quot_of_fract_quot_to_fract: \"quot_of_fract (quot_to_fract x) = normalize_quot x\"\nproof (cases \"snd x = 0\")\n  case True\n  thus ?thesis unfolding quot_to_fract_def\n    by transfer (simp add: case_prod_unfold normalize_quot_def)\nnext\n  case False\n  thus ?thesis unfolding quot_to_fract_def by transfer (simp add: case_prod_unfold)\nqed\n\nlemma quot_of_fract_quot_to_fract': \n  \"x \\<in> normalized_fracts \\<Longrightarrow> quot_of_fract (quot_to_fract x) = x\"\n  unfolding quot_to_fract_def by transfer (auto simp: normalize_quot_id)\n\nlemma quot_of_fract_in_normalized_fracts [simp]: \"quot_of_fract x \\<in> normalized_fracts\"\n  by transfer simp\n\nlemma normalize_quotI:\n  assumes \"a * d = b * c\" \"b \\<noteq> 0\" \"(c, d) \\<in> normalized_fracts\"\n  shows   \"normalize_quot (a, b) = (c, d)\"\nproof -\n  from assms have \"normalize_quot (a, b) = normalize_quot (c, d)\"\n    by (subst normalize_quot_eq_iff) auto\n  also have \"\\<dots> = (c, d)\" by (intro normalize_quot_id) fact\n  finally show ?thesis .\nqed\n\nlemma td_normalized_fract:\n  \"type_definition quot_of_fract quot_to_fract normalized_fracts\"\n  by standard (simp_all add: quot_of_fract_quot_to_fract')\n\nlemma quot_of_fract_add_aux:\n  assumes \"snd x \\<noteq> 0\" \"snd y \\<noteq> 0\" \n  shows   \"(fst x * snd y + fst y * snd x) * (snd (normalize_quot x) * snd (normalize_quot y)) =\n             snd x * snd y * (fst (normalize_quot x) * snd (normalize_quot y) +\n             snd (normalize_quot x) * fst (normalize_quot y))\"\nproof -\n  from normalize_quotE'[OF assms(1)] obtain d\n    where d:\n      \"fst x = fst (normalize_quot x) * d\"\n      \"snd x = snd (normalize_quot x) * d\"\n      \"d dvd fst x\"\n      \"d dvd snd x\"\n      \"d \\<noteq> 0\" .\n  from normalize_quotE'[OF assms(2)] obtain e\n    where e:\n      \"fst y = fst (normalize_quot y) * e\"\n      \"snd y = snd (normalize_quot y) * e\"\n      \"e dvd fst y\"\n      \"e dvd snd y\"\n      \"e \\<noteq> 0\" .\n  show ?thesis by (simp_all add: d e algebra_simps)\nqed\n\n\nlocale fract_as_normalized_quot\nbegin\nsetup_lifting td_normalized_fract\nend\n\n\nlemma quot_of_fract_add:\n  \"quot_of_fract (x + y) = \n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y\n      in  normalize_quot (a * d + b * c, b * d))\"\n  by transfer (insert quot_of_fract_add_aux, \n               simp_all add: Let_def case_prod_unfold normalize_quot_eq_iff)\n\nlemma quot_of_fract_uminus:\n  \"quot_of_fract (-x) = (let (a,b) = quot_of_fract x in (-a, b))\"\n  by transfer (auto simp: case_prod_unfold Let_def normalize_quot_def dvd_neg_div mult_unit_dvd_iff)\n\nlemma quot_of_fract_diff:\n  \"quot_of_fract (x - y) = \n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y\n      in  normalize_quot (a * d - b * c, b * d))\" (is \"_ = ?rhs\")\nproof -\n  have \"x - y = x + -y\" by simp\n  also have \"quot_of_fract \\<dots> = ?rhs\"\n    by (simp only: quot_of_fract_add quot_of_fract_uminus Let_def case_prod_unfold) simp_all\n  finally show ?thesis .\nqed\n\nlemma normalize_quot_mult_coprime:\n  assumes \"coprime a b\" \"coprime c d\" \"unit_factor b = 1\" \"unit_factor d = 1\"\n  defines \"e \\<equiv> fst (normalize_quot (a, d))\" and \"f \\<equiv> snd (normalize_quot (a, d))\"\n     and  \"g \\<equiv> fst (normalize_quot (c, b))\" and \"h \\<equiv> snd (normalize_quot (c, b))\"\n  shows   \"normalize_quot (a * c, b * d) = (e * g, f * h)\"\nproof (rule normalize_quotI)\n  from assms have \"gcd a b = 1\" \"gcd c d = 1\"\n    by simp_all\n  from assms have \"b \\<noteq> 0\" \"d \\<noteq> 0\" by auto\n  with assms have \"normalize b = b\" \"normalize d = d\"\n    by (auto intro: normalize_unit_factor_eqI)\n  from normalize_quotE [OF \\<open>b \\<noteq> 0\\<close>, of c] obtain k\n    where\n      \"c = fst (normalize_quot (c, b)) * k\"\n      \"b = snd (normalize_quot (c, b)) * k\"\n      \"k dvd c\" \"k dvd b\" \"k \\<noteq> 0\" .\n  note k = this [folded \\<open>gcd a b = 1\\<close> \\<open>gcd c d = 1\\<close> assms(3) assms(4)]\n  from normalize_quotE [OF \\<open>d \\<noteq> 0\\<close>, of a] obtain l\n    where \"a = fst (normalize_quot (a, d)) * l\"\n      \"d = snd (normalize_quot (a, d)) * l\"\n      \"l dvd a\" \"l dvd d\" \"l \\<noteq> 0\" .\n  note l = this [folded \\<open>gcd a b = 1\\<close> \\<open>gcd c d = 1\\<close> assms(3) assms(4)]\n  from k l show \"a * c * (f * h) = b * d * (e * g)\"\n    by (metis e_def f_def g_def h_def mult.commute mult.left_commute)\n  from assms have [simp]: \"unit_factor f = 1\" \"unit_factor h = 1\"\n    by simp_all\n  from assms have \"coprime e f\" \"coprime g h\" by (simp_all add: coprime_normalize_quot)\n  with k l assms(1,2) \\<open>b \\<noteq> 0\\<close> \\<open>d \\<noteq> 0\\<close> \\<open>unit_factor b = 1\\<close> \\<open>unit_factor d = 1\\<close>\n    \\<open>normalize b = b\\<close> \\<open>normalize d = d\\<close>\n  show \"(e * g, f * h) \\<in> normalized_fracts\"\n    by (simp add: normalized_fracts_def unit_factor_mult e_def f_def g_def h_def\n      coprime_normalize_quot dvd_unit_factor_div unit_factor_gcd)\n      (metis coprime_mult_left_iff coprime_mult_right_iff)\nqed (insert assms(3,4), auto)\n\nlemma normalize_quot_mult:\n  assumes \"snd x \\<noteq> 0\" \"snd y \\<noteq> 0\"\n  shows   \"normalize_quot (fst x * fst y, snd x * snd y) = normalize_quot \n             (fst (normalize_quot x) * fst (normalize_quot y),\n              snd (normalize_quot x) * snd (normalize_quot y))\"\nproof -\n  from normalize_quotE'[OF assms(1)] obtain d where d:\n    \"fst x = fst (normalize_quot x) * d\"\n    \"snd x = snd (normalize_quot x) * d\"\n    \"d dvd fst x\"\n    \"d dvd snd x\"\n    \"d \\<noteq> 0\" .\n  from normalize_quotE'[OF assms(2)] obtain e where e:\n    \"fst y = fst (normalize_quot y) * e\"\n    \"snd y = snd (normalize_quot y) * e\"\n    \"e dvd fst y\"\n    \"e dvd snd y\"\n    \"e \\<noteq> 0\" .\n  show ?thesis by (simp_all add: d e algebra_simps normalize_quot_eq_iff)\nqed\n\nlemma quot_of_fract_mult:\n  \"quot_of_fract (x * y) = \n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y;\n          (e,f) = normalize_quot (a,d); (g,h) = normalize_quot (c,b)\n      in  (e*g, f*h))\"\n  by transfer\n     (simp add: split_def Let_def coprime_normalize_quot normalize_quot_mult normalize_quot_mult_coprime)\n  \nlemma normalize_quot_0 [simp]: \n    \"normalize_quot (0, x) = (0, 1)\" \"normalize_quot (x, 0) = (0, 1)\"\n  by (simp_all add: normalize_quot_def)\n  \nlemma normalize_quot_eq_0_iff [simp]: \"fst (normalize_quot x) = 0 \\<longleftrightarrow> fst x = 0 \\<or> snd x = 0\"\n  by (auto simp: normalize_quot_def case_prod_unfold Let_def div_mult_unit2 dvd_div_eq_0_iff)\n  \nlemma fst_quot_of_fract_0_imp: \"fst (quot_of_fract x) = 0 \\<Longrightarrow> snd (quot_of_fract x) = 1\"\n  by transfer auto\n\nlemma normalize_quot_swap:\n  assumes \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  defines \"a' \\<equiv> fst (normalize_quot (a, b))\" and \"b' \\<equiv> snd (normalize_quot (a, b))\"\n  shows   \"normalize_quot (b, a) = (b' div unit_factor a', a' div unit_factor a')\"\nproof (rule normalize_quotI)\n  from normalize_quotE[OF assms(2), of a] obtain d where\n    \"a = fst (normalize_quot (a, b)) * d\"\n    \"b = snd (normalize_quot (a, b)) * d\"\n    \"d dvd a\" \"d dvd b\" \"d \\<noteq> 0\" .\n  note d = this [folded assms(3,4)]\n  show \"b * (a' div unit_factor a') = a * (b' div unit_factor a')\"\n    using assms(1,2) d \n    by (simp add: div_unit_factor [symmetric] unit_div_mult_swap mult_ac del: div_unit_factor)\n  have \"coprime a' b'\" by (simp add: a'_def b'_def coprime_normalize_quot)\n  thus \"(b' div unit_factor a', a' div unit_factor a') \\<in> normalized_fracts\"\n    using assms(1,2) d\n    by (auto simp add: normalized_fracts_def ac_simps dvd_div_unit_iff elim: coprime_imp_coprime)\nqed fact+\n  \nlemma quot_of_fract_inverse:\n  \"quot_of_fract (inverse x) = \n     (let (a,b) = quot_of_fract x; d = unit_factor a \n      in  if d = 0 then (0, 1) else (b div d, a div d))\"\nproof (transfer, goal_cases)\n  case (1 x)\n  from normalize_quot_swap[of \"fst x\" \"snd x\"] show ?case\n    by (auto simp: Let_def case_prod_unfold)\nqed\n\nlemma normalize_quot_div_unit_left:\n  fixes x y u\n  assumes \"is_unit u\"\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (x div u, y) = (x' div u, y')\"\nproof (cases \"y = 0\")\n  case False\n  define v where \"v = 1 div u\"\n  with \\<open>is_unit u\\<close> have \"is_unit v\" and u: \"\\<And>a. a div u = a * v\"\n    by simp_all\n  from \\<open>is_unit v\\<close> have \"coprime v = top\"\n    by (simp add: fun_eq_iff is_unit_left_imp_coprime)\n  from normalize_quotE[OF False, of x] obtain d where\n    \"x = fst (normalize_quot (x, y)) * d\"\n    \"y = snd (normalize_quot (x, y)) * d\"\n    \"d dvd x\" \"d dvd y\" \"d \\<noteq> 0\" .\n  note d = this[folded assms(2,3)]\n  from assms have \"coprime x' y'\" \"unit_factor y' = 1\"\n    by (simp_all add: coprime_normalize_quot)\n  with d \\<open>coprime v = top\\<close> have \"normalize_quot (x * v, y) = (x' * v, y')\"\n    by (auto simp: normalized_fracts_def intro: normalize_quotI)\n  then show ?thesis\n    by (simp add: u)\nqed (simp_all add: assms)\n\nlemma normalize_quot_div_unit_right:\n  fixes x y u\n  assumes \"is_unit u\"\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (x, y div u) = (x' * u, y')\"\nproof (cases \"y = 0\")\n  case False\n  from normalize_quotE[OF this, of x]\n  obtain d where d:\n    \"x = fst (normalize_quot (x, y)) * d\"\n    \"y = snd (normalize_quot (x, y)) * d\"\n    \"d dvd x\" \"d dvd y\" \"d \\<noteq> 0\" .\n  note d = this[folded assms(2,3)]\n  from assms have \"coprime x' y'\" \"unit_factor y' = 1\" by (simp_all add: coprime_normalize_quot)\n  with d \\<open>is_unit u\\<close> show ?thesis\n    by (auto simp add: normalized_fracts_def is_unit_left_imp_coprime unit_div_eq_0_iff intro: normalize_quotI)\nqed (simp_all add: assms)\n\nlemma normalize_quot_normalize_left:\n  fixes x y u\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (normalize x, y) = (x' div unit_factor x, y')\"\n  using normalize_quot_div_unit_left[of \"unit_factor x\" x y]\n  by (cases \"x = 0\") (simp_all add: assms)\n  \nlemma normalize_quot_normalize_right:\n  fixes x y u\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (x, normalize y) = (x' * unit_factor y, y')\"\n  using normalize_quot_div_unit_right[of \"unit_factor y\" x y]\n  by (cases \"y = 0\") (simp_all add: assms)\n  \nlemma quot_of_fract_0 [simp]: \"quot_of_fract 0 = (0, 1)\"\n  by transfer auto\n\nlemma quot_of_fract_1 [simp]: \"quot_of_fract 1 = (1, 1)\"\n  by transfer (rule normalize_quotI, simp_all add: normalized_fracts_def)\n\nlemma quot_of_fract_divide:\n  \"quot_of_fract (x / y) = (if y = 0 then (0, 1) else\n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y;\n          (e,f) = normalize_quot (a,c); (g,h) = normalize_quot (d,b)\n      in  (e * g, f * h)))\" (is \"_ = ?rhs\")\nproof (cases \"y = 0\")\n  case False\n  hence A: \"fst (quot_of_fract y) \\<noteq> 0\" by transfer auto\n  have \"x / y = x * inverse y\" by (simp add: divide_inverse)\n  also from False A have \"quot_of_fract \\<dots> = ?rhs\"\n    by (simp only: quot_of_fract_mult quot_of_fract_inverse)\n       (simp_all add: Let_def case_prod_unfold fst_quot_of_fract_0_imp\n          normalize_quot_div_unit_left normalize_quot_div_unit_right \n          normalize_quot_normalize_right normalize_quot_normalize_left)\n  finally show ?thesis .\nqed simp_all\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Computational_Algebra/Normalized_Fraction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.849971181358171, "lm_q1q2_score": 0.7580136805069924}}
{"text": "section \"Arithmetic and Boolean Expressions\"\n\ntheory AExp imports Main begin\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext \\<open>The same state more concisely:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext \\<open>A little syntax magic to write larger states compactly:\\<close>\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext \\<open>We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\\<close>\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext \\<open>In the @{term \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\\<close>\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext \\<open>Note that this @{text\"<\\<dots>>\"} syntax works for any function space\n@{text\"\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\"} where @{text \"\\<tau>\\<^sub>2\"} has a @{text 0}.\\<close>\n\n\nsubsection \"Constant Folding\"\n\ntext \\<open>Evaluate constant subexpressions:\\<close>\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    )\"\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction )\napply (auto)\ndone\n\ntext \\<open>Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors:\\<close>\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus \"\n\nlemma aval_plus [simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply auto\ndone\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\n\ntext \\<open>Note that in @{const asimp_const} the optimized constructor was\ninlined. Making it a separate function @{const plus} improves modularity of\nthe code and the proofs.\\<close>\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply (auto)\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.8499711718571775, "lm_q1q2_score": 0.7580136769220017}}
{"text": "theory Llength_lappend\n  imports Main \"$HIPSTER_HOME/IsaHipster\"\nbegin\n  \nsetup Tactic_Data.set_coinduct_sledgehammer  \ncodatatype (lset: 'a) Llist =\n    lnull: LNil\n    | LCons (lhd: 'a) (ltl: \"'a Llist\")\nwhere\n \"ltl LNil = LNil\"\n\ncodatatype ENat = is_zero: EZ | ESuc (epred: ENat) \n\nprimcorec llength :: \"'a Llist \\<Rightarrow> ENat\" where\n\"llength xs = (if lnull xs then EZ else ESuc (llength (ltl xs)))\" \n\nprimcorec lappend :: \"'a Llist \\<Rightarrow> 'a Llist \\<Rightarrow> 'a Llist\" where\n\"lnull xs \\<Longrightarrow> lnull ys \\<Longrightarrow> lnull (lappend xs ys)\"\n| \"lhd (lappend xs ys) = lhd (if lnull xs then ys else xs)\"\n| \"ltl (lappend xs ys) = (if lnull xs then ltl ys else lappend (ltl xs) ys)\"\n\nprimcorec eplus :: \"ENat \\<Rightarrow> ENat \\<Rightarrow> ENat\" where\n\"eplus m n = (if is_zero m then n else ESuc (eplus (epred m) n))\"\n\n(*hipster llength lappend eplus*)\nlemma lemma_a [thy_expl]: \"eplus x EZ = x\"\n  apply (coinduction  arbitrary: x rule: Llength_lappend.ENat.coinduct_strong)\n  by simp\n    \nlemma lemma_aa [thy_expl]: \"eplus EZ x = x\"\napply (coinduction  arbitrary: x rule: Llength_lappend.ENat.coinduct_strong)\nby simp\n\nlemma lemma_ab [thy_expl]: \"eplus (ESuc x) y = eplus x (ESuc y)\"\napply (coinduction  arbitrary: x y rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby (metis ENat.collapse(2) eplus.code)\n\nlemma lemma_ac [thy_expl]: \"ESuc (eplus x y) = eplus x (ESuc y)\"\napply (coinduction  arbitrary: x y rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby (metis eplus.code)\n\nlemma lemma_ad [thy_expl]: \"eplus (eplus x y) z = eplus x (eplus y z)\"\napply (coinduction  arbitrary: x y z rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby auto\n\nlemma lemma_ae [thy_expl]: \"llength (LCons y z) = ESuc (llength z)\"\napply (coinduction  arbitrary: y z rule: Llength_lappend.ENat.coinduct_strong)\nby simp\n\nlemma lemma_af [thy_expl]: \"lappend y LNil = y\"\napply (coinduction  arbitrary: y rule: Llength_lappend.Llist.coinduct_strong)\nby simp\n\nlemma lemma_ag [thy_expl]: \"lappend LNil y = y\"\napply (coinduction  arbitrary: y rule: Llength_lappend.Llist.coinduct_strong)\nby simp\n\nlemma lemma_ah [thy_expl]: \"ltl (lappend y y) = lappend (ltl y) y\"\napply (coinduction  arbitrary: y rule: Llength_lappend.Llist.coinduct_strong)\napply simp\nby (smt Llist.collapse(1) Llist.sel(2) lappend.disc_iff(2) lappend.simps(3) lappend.simps(4))\n\nlemma lemma_ai [thy_expl]: \"lappend (LCons y z) x2 = LCons y (lappend z x2)\"\napply (coinduction  arbitrary: x2 y z rule: Llength_lappend.Llist.coinduct_strong)\nby simp\n\nlemma lemma_aj [thy_expl]: \"lappend (lappend y z) x2 = lappend y (lappend z x2)\"\napply (coinduction  arbitrary: x2 y z rule: Llength_lappend.Llist.coinduct_strong)\napply simp\nby blast\n\nlemma lemma_ak [thy_expl]: \"ltl (lappend y (ltl y)) = lappend (ltl y) (ltl y)\"\napply (coinduction  arbitrary: y rule: Llength_lappend.Llist.coinduct_strong)\napply simp\nby (fastforce Llist.collapse(1) lemma_af)\n\nlemma lemma_al [thy_expl]: \"eplus (llength y) (llength z) = llength (lappend y z)\"\napply (coinduction  arbitrary: y z rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby auto\n\nlemma lemma_am [thy_expl]: \"eplus y x = eplus x y\"\napply (coinduction  arbitrary: x y rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby (metis ENat.collapse(1) ENat.collapse(2) lemma_a lemma_ab)\n\nlemma lemma_an [thy_expl]: \"llength (lappend z y) = llength (lappend y z)\"\napply (coinduction  arbitrary: y z rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby (metis (no_types, lifting) Llength_lappend.lemma_af Llength_lappend.lemma_al Llist.collapse(1) lemma_ab llength.code)\n\nlemma lemma_ao [thy_expl]: \"llength (ltl (lappend z y)) = llength (ltl (lappend y z))\"\napply (coinduction  arbitrary: y z rule: Llength_lappend.ENat.coinduct_strong)\napply simp\nby (smt Llist.case_eq_if lemma_an llength.disc_iff(1) llength.sel ltl_def)\n    \ntheorem  llength_lappend: \"llength (lappend xs ys) = eplus (llength xs) (llength ys)\"\nby hipster_coinduct_sledgehammer\nend", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/benchmark/she/Coinductive_List/Llength_lappend.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9219218391455084, "lm_q2_score": 0.8221891327004132, "lm_q1q2_score": 0.7579941173446154}}
{"text": "(*  Title:      HOL/Library/FuncSet.thy\n    Author:     Florian Kammueller and Lawrence C Paulson, Lukas Bulwahn\n*)\n\nsection \\<open>Pi and Function Sets\\<close>\n\ntheory FuncSet\nimports Hilbert_Choice Main\nbegin\n\ndefinition Pi :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"\n  where \"Pi A B = {f. \\<forall>x. x \\<in> A \\<longrightarrow> f x \\<in> B x}\"\n\ndefinition extensional :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"\n  where \"extensional A = {f. \\<forall>x. x \\<notin> A \\<longrightarrow> f x = undefined}\"\n\ndefinition \"restrict\" :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'b\"\n  where \"restrict f A = (\\<lambda>x. if x \\<in> A then f x else undefined)\"\n\nabbreviation funcset :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (infixr \"->\" 60)\n  where \"A -> B \\<equiv> Pi A (\\<lambda>_. B)\"\n\nnotation (xsymbols)\n  funcset  (infixr \"\\<rightarrow>\" 60)\n\nsyntax\n  \"_Pi\"  :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3PI _:_./ _)\" 10)\n  \"_lam\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'b \\<Rightarrow> ('a \\<Rightarrow> 'b)\"  (\"(3%_:_./ _)\" [0,0,3] 3)\nsyntax (xsymbols)\n  \"_Pi\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3\\<Pi> _\\<in>_./ _)\"   10)\n  \"_lam\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b)\"  (\"(3\\<lambda>_\\<in>_./ _)\" [0,0,3] 3)\nsyntax (HTML output)\n  \"_Pi\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3\\<Pi> _\\<in>_./ _)\"   10)\n  \"_lam\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b)\"  (\"(3\\<lambda>_\\<in>_./ _)\" [0,0,3] 3)\ntranslations\n  \"\\<Pi> x\\<in>A. B\" \\<rightleftharpoons> \"CONST Pi A (\\<lambda>x. B)\"\n  \"\\<lambda>x\\<in>A. f\" \\<rightleftharpoons> \"CONST restrict (\\<lambda>x. f) A\"\n\ndefinition \"compose\" :: \"'a set \\<Rightarrow> ('b \\<Rightarrow> 'c) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'c)\"\n  where \"compose A g f = (\\<lambda>x\\<in>A. g (f x))\"\n\n\nsubsection \\<open>Basic Properties of @{term Pi}\\<close>\n\nlemma Pi_I[intro!]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> B x) \\<Longrightarrow> f \\<in> Pi A B\"\n  by (simp add: Pi_def)\n\nlemma Pi_I'[simp]: \"(\\<And>x. x \\<in> A \\<longrightarrow> f x \\<in> B x) \\<Longrightarrow> f \\<in> Pi A B\"\n  by (simp add:Pi_def)\n\nlemma funcsetI: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> B) \\<Longrightarrow> f \\<in> A \\<rightarrow> B\"\n  by (simp add: Pi_def)\n\nlemma Pi_mem: \"f \\<in> Pi A B \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f x \\<in> B x\"\n  by (simp add: Pi_def)\n\nlemma Pi_iff: \"f \\<in> Pi I X \\<longleftrightarrow> (\\<forall>i\\<in>I. f i \\<in> X i)\"\n  unfolding Pi_def by auto\n\nlemma PiE [elim]: \"f \\<in> Pi A B \\<Longrightarrow> (f x \\<in> B x \\<Longrightarrow> Q) \\<Longrightarrow> (x \\<notin> A \\<Longrightarrow> Q) \\<Longrightarrow> Q\"\n  by (auto simp: Pi_def)\n\nlemma Pi_cong: \"(\\<And>w. w \\<in> A \\<Longrightarrow> f w = g w) \\<Longrightarrow> f \\<in> Pi A B \\<longleftrightarrow> g \\<in> Pi A B\"\n  by (auto simp: Pi_def)\n\nlemma funcset_id [simp]: \"(\\<lambda>x. x) \\<in> A \\<rightarrow> A\"\n  by auto\n\nlemma funcset_mem: \"f \\<in> A \\<rightarrow> B \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f x \\<in> B\"\n  by (simp add: Pi_def)\n\nlemma funcset_image: \"f \\<in> A \\<rightarrow> B \\<Longrightarrow> f ` A \\<subseteq> B\"\n  by auto\n\nlemma image_subset_iff_funcset: \"F ` A \\<subseteq> B \\<longleftrightarrow> F \\<in> A \\<rightarrow> B\"\n  by auto\n\nlemma Pi_eq_empty[simp]: \"(\\<Pi> x \\<in> A. B x) = {} \\<longleftrightarrow> (\\<exists>x\\<in>A. B x = {})\"\n  apply (simp add: Pi_def)\n  apply auto\n  txt \\<open>Converse direction requires Axiom of Choice to exhibit a function\n  picking an element from each non-empty @{term \"B x\"}\\<close>\n  apply (drule_tac x = \"\\<lambda>u. SOME y. y \\<in> B u\" in spec)\n  apply auto\n  apply (cut_tac P = \"\\<lambda>y. y \\<in> B x\" in some_eq_ex)\n  apply auto\n  done\n\nlemma Pi_empty [simp]: \"Pi {} B = UNIV\"\n  by (simp add: Pi_def)\n\nlemma Pi_Int: \"Pi I E \\<inter> Pi I F = (\\<Pi> i\\<in>I. E i \\<inter> F i)\"\n  by auto\n\nlemma Pi_UN:\n  fixes A :: \"nat \\<Rightarrow> 'i \\<Rightarrow> 'a set\"\n  assumes \"finite I\"\n    and mono: \"\\<And>i n m. i \\<in> I \\<Longrightarrow> n \\<le> m \\<Longrightarrow> A n i \\<subseteq> A m i\"\n  shows \"(\\<Union>n. Pi I (A n)) = (\\<Pi> i\\<in>I. \\<Union>n. A n i)\"\nproof (intro set_eqI iffI)\n  fix f\n  assume \"f \\<in> (\\<Pi> i\\<in>I. \\<Union>n. A n i)\"\n  then have \"\\<forall>i\\<in>I. \\<exists>n. f i \\<in> A n i\"\n    by auto\n  from bchoice[OF this] obtain n where n: \"\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<in> (A (n i) i)\"\n    by auto\n  obtain k where k: \"\\<And>i. i \\<in> I \\<Longrightarrow> n i \\<le> k\"\n    using \\<open>finite I\\<close> finite_nat_set_iff_bounded_le[of \"n`I\"] by auto\n  have \"f \\<in> Pi I (A k)\"\n  proof (intro Pi_I)\n    fix i\n    assume \"i \\<in> I\"\n    from mono[OF this, of \"n i\" k] k[OF this] n[OF this]\n    show \"f i \\<in> A k i\" by auto\n  qed\n  then show \"f \\<in> (\\<Union>n. Pi I (A n))\"\n    by auto\nqed auto\n\nlemma Pi_UNIV [simp]: \"A \\<rightarrow> UNIV = UNIV\"\n  by (simp add: Pi_def)\n\ntext \\<open>Covariance of Pi-sets in their second argument\\<close>\nlemma Pi_mono: \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> C x) \\<Longrightarrow> Pi A B \\<subseteq> Pi A C\"\n  by auto\n\ntext \\<open>Contravariance of Pi-sets in their first argument\\<close>\nlemma Pi_anti_mono: \"A' \\<subseteq> A \\<Longrightarrow> Pi A B \\<subseteq> Pi A' B\"\n  by auto\n\nlemma prod_final:\n  assumes 1: \"fst \\<circ> f \\<in> Pi A B\"\n    and 2: \"snd \\<circ> f \\<in> Pi A C\"\n  shows \"f \\<in> (\\<Pi> z \\<in> A. B z \\<times> C z)\"\nproof (rule Pi_I)\n  fix z\n  assume z: \"z \\<in> A\"\n  have \"f z = (fst (f z), snd (f z))\"\n    by simp\n  also have \"\\<dots> \\<in> B z \\<times> C z\"\n    by (metis SigmaI PiE o_apply 1 2 z)\n  finally show \"f z \\<in> B z \\<times> C z\" .\nqed\n\nlemma Pi_split_domain[simp]: \"x \\<in> Pi (I \\<union> J) X \\<longleftrightarrow> x \\<in> Pi I X \\<and> x \\<in> Pi J X\"\n  by (auto simp: Pi_def)\n\nlemma Pi_split_insert_domain[simp]: \"x \\<in> Pi (insert i I) X \\<longleftrightarrow> x \\<in> Pi I X \\<and> x i \\<in> X i\"\n  by (auto simp: Pi_def)\n\nlemma Pi_cancel_fupd_range[simp]: \"i \\<notin> I \\<Longrightarrow> x \\<in> Pi I (B(i := b)) \\<longleftrightarrow> x \\<in> Pi I B\"\n  by (auto simp: Pi_def)\n\nlemma Pi_cancel_fupd[simp]: \"i \\<notin> I \\<Longrightarrow> x(i := a) \\<in> Pi I B \\<longleftrightarrow> x \\<in> Pi I B\"\n  by (auto simp: Pi_def)\n\nlemma Pi_fupd_iff: \"i \\<in> I \\<Longrightarrow> f \\<in> Pi I (B(i := A)) \\<longleftrightarrow> f \\<in> Pi (I - {i}) B \\<and> f i \\<in> A\"\n  apply auto\n  apply (drule_tac x=x in Pi_mem)\n  apply (simp_all split: split_if_asm)\n  apply (drule_tac x=i in Pi_mem)\n  apply (auto dest!: Pi_mem)\n  done\n\n\nsubsection \\<open>Composition With a Restricted Domain: @{term compose}\\<close>\n\nlemma funcset_compose: \"f \\<in> A \\<rightarrow> B \\<Longrightarrow> g \\<in> B \\<rightarrow> C \\<Longrightarrow> compose A g f \\<in> A \\<rightarrow> C\"\n  by (simp add: Pi_def compose_def restrict_def)\n\nlemma compose_assoc:\n  assumes \"f \\<in> A \\<rightarrow> B\"\n    and \"g \\<in> B \\<rightarrow> C\"\n    and \"h \\<in> C \\<rightarrow> D\"\n  shows \"compose A h (compose A g f) = compose A (compose B h g) f\"\n  using assms by (simp add: fun_eq_iff Pi_def compose_def restrict_def)\n\nlemma compose_eq: \"x \\<in> A \\<Longrightarrow> compose A g f x = g (f x)\"\n  by (simp add: compose_def restrict_def)\n\nlemma surj_compose: \"f ` A = B \\<Longrightarrow> g ` B = C \\<Longrightarrow> compose A g f ` A = C\"\n  by (auto simp add: image_def compose_eq)\n\n\nsubsection \\<open>Bounded Abstraction: @{term restrict}\\<close>\n\nlemma restrict_in_funcset: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> B) \\<Longrightarrow> (\\<lambda>x\\<in>A. f x) \\<in> A \\<rightarrow> B\"\n  by (simp add: Pi_def restrict_def)\n\nlemma restrictI[intro!]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> B x) \\<Longrightarrow> (\\<lambda>x\\<in>A. f x) \\<in> Pi A B\"\n  by (simp add: Pi_def restrict_def)\n\nlemma restrict_apply[simp]: \"(\\<lambda>y\\<in>A. f y) x = (if x \\<in> A then f x else undefined)\"\n  by (simp add: restrict_def)\n\nlemma restrict_apply': \"x \\<in> A \\<Longrightarrow> (\\<lambda>y\\<in>A. f y) x = f x\"\n  by simp\n\nlemma restrict_ext: \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x) \\<Longrightarrow> (\\<lambda>x\\<in>A. f x) = (\\<lambda>x\\<in>A. g x)\"\n  by (simp add: fun_eq_iff Pi_def restrict_def)\n\nlemma restrict_UNIV: \"restrict f UNIV = f\"\n  by (simp add: restrict_def)\n\nlemma inj_on_restrict_eq [simp]: \"inj_on (restrict f A) A = inj_on f A\"\n  by (simp add: inj_on_def restrict_def)\n\nlemma Id_compose: \"f \\<in> A \\<rightarrow> B \\<Longrightarrow> f \\<in> extensional A \\<Longrightarrow> compose A (\\<lambda>y\\<in>B. y) f = f\"\n  by (auto simp add: fun_eq_iff compose_def extensional_def Pi_def)\n\nlemma compose_Id: \"g \\<in> A \\<rightarrow> B \\<Longrightarrow> g \\<in> extensional A \\<Longrightarrow> compose A g (\\<lambda>x\\<in>A. x) = g\"\n  by (auto simp add: fun_eq_iff compose_def extensional_def Pi_def)\n\nlemma image_restrict_eq [simp]: \"(restrict f A) ` A = f ` A\"\n  by (auto simp add: restrict_def)\n\nlemma restrict_restrict[simp]: \"restrict (restrict f A) B = restrict f (A \\<inter> B)\"\n  unfolding restrict_def by (simp add: fun_eq_iff)\n\nlemma restrict_fupd[simp]: \"i \\<notin> I \\<Longrightarrow> restrict (f (i := x)) I = restrict f I\"\n  by (auto simp: restrict_def)\n\nlemma restrict_upd[simp]: \"i \\<notin> I \\<Longrightarrow> (restrict f I)(i := y) = restrict (f(i := y)) (insert i I)\"\n  by (auto simp: fun_eq_iff)\n\nlemma restrict_Pi_cancel: \"restrict x I \\<in> Pi I A \\<longleftrightarrow> x \\<in> Pi I A\"\n  by (auto simp: restrict_def Pi_def)\n\n\nsubsection \\<open>Bijections Between Sets\\<close>\n\ntext \\<open>The definition of @{const bij_betw} is in @{text \"Fun.thy\"}, but most of\nthe theorems belong here, or need at least @{term Hilbert_Choice}.\\<close>\n\nlemma bij_betwI:\n  assumes \"f \\<in> A \\<rightarrow> B\"\n    and \"g \\<in> B \\<rightarrow> A\"\n    and g_f: \"\\<And>x. x\\<in>A \\<Longrightarrow> g (f x) = x\"\n    and f_g: \"\\<And>y. y\\<in>B \\<Longrightarrow> f (g y) = y\"\n  shows \"bij_betw f A B\"\n  unfolding bij_betw_def\nproof\n  show \"inj_on f A\"\n    by (metis g_f inj_on_def)\n  have \"f ` A \\<subseteq> B\"\n    using \\<open>f \\<in> A \\<rightarrow> B\\<close> by auto\n  moreover\n  have \"B \\<subseteq> f ` A\"\n    by auto (metis Pi_mem \\<open>g \\<in> B \\<rightarrow> A\\<close> f_g image_iff)\n  ultimately show \"f ` A = B\"\n    by blast\nqed\n\nlemma bij_betw_imp_funcset: \"bij_betw f A B \\<Longrightarrow> f \\<in> A \\<rightarrow> B\"\n  by (auto simp add: bij_betw_def)\n\nlemma inj_on_compose: \"bij_betw f A B \\<Longrightarrow> inj_on g B \\<Longrightarrow> inj_on (compose A g f) A\"\n  by (auto simp add: bij_betw_def inj_on_def compose_eq)\n\nlemma bij_betw_compose: \"bij_betw f A B \\<Longrightarrow> bij_betw g B C \\<Longrightarrow> bij_betw (compose A g f) A C\"\n  apply (simp add: bij_betw_def compose_eq inj_on_compose)\n  apply (auto simp add: compose_def image_def)\n  done\n\nlemma bij_betw_restrict_eq [simp]: \"bij_betw (restrict f A) A B = bij_betw f A B\"\n  by (simp add: bij_betw_def)\n\n\nsubsection \\<open>Extensionality\\<close>\n\nlemma extensional_empty[simp]: \"extensional {} = {\\<lambda>x. undefined}\"\n  unfolding extensional_def by auto\n\nlemma extensional_arb: \"f \\<in> extensional A \\<Longrightarrow> x \\<notin> A \\<Longrightarrow> f x = undefined\"\n  by (simp add: extensional_def)\n\nlemma restrict_extensional [simp]: \"restrict f A \\<in> extensional A\"\n  by (simp add: restrict_def extensional_def)\n\nlemma compose_extensional [simp]: \"compose A f g \\<in> extensional A\"\n  by (simp add: compose_def)\n\nlemma extensionalityI:\n  assumes \"f \\<in> extensional A\"\n    and \"g \\<in> extensional A\"\n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> f x = g x\"\n  shows \"f = g\"\n  using assms by (force simp add: fun_eq_iff extensional_def)\n\nlemma extensional_restrict:  \"f \\<in> extensional A \\<Longrightarrow> restrict f A = f\"\n  by (rule extensionalityI[OF restrict_extensional]) auto\n\nlemma extensional_subset: \"f \\<in> extensional A \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f \\<in> extensional B\"\n  unfolding extensional_def by auto\n\nlemma inv_into_funcset: \"f ` A = B \\<Longrightarrow> (\\<lambda>x\\<in>B. inv_into A f x) \\<in> B \\<rightarrow> A\"\n  by (unfold inv_into_def) (fast intro: someI2)\n\nlemma compose_inv_into_id: \"bij_betw f A B \\<Longrightarrow> compose A (\\<lambda>y\\<in>B. inv_into A f y) f = (\\<lambda>x\\<in>A. x)\"\n  apply (simp add: bij_betw_def compose_def)\n  apply (rule restrict_ext, auto)\n  done\n\nlemma compose_id_inv_into: \"f ` A = B \\<Longrightarrow> compose B f (\\<lambda>y\\<in>B. inv_into A f y) = (\\<lambda>x\\<in>B. x)\"\n  apply (simp add: compose_def)\n  apply (rule restrict_ext)\n  apply (simp add: f_inv_into_f)\n  done\n\nlemma extensional_insert[intro, simp]:\n  assumes \"a \\<in> extensional (insert i I)\"\n  shows \"a(i := b) \\<in> extensional (insert i I)\"\n  using assms unfolding extensional_def by auto\n\nlemma extensional_Int[simp]: \"extensional I \\<inter> extensional I' = extensional (I \\<inter> I')\"\n  unfolding extensional_def by auto\n\nlemma extensional_UNIV[simp]: \"extensional UNIV = UNIV\"\n  by (auto simp: extensional_def)\n\nlemma restrict_extensional_sub[intro]: \"A \\<subseteq> B \\<Longrightarrow> restrict f A \\<in> extensional B\"\n  unfolding restrict_def extensional_def by auto\n\nlemma extensional_insert_undefined[intro, simp]:\n  \"a \\<in> extensional (insert i I) \\<Longrightarrow> a(i := undefined) \\<in> extensional I\"\n  unfolding extensional_def by auto\n\nlemma extensional_insert_cancel[intro, simp]:\n  \"a \\<in> extensional I \\<Longrightarrow> a \\<in> extensional (insert i I)\"\n  unfolding extensional_def by auto\n\n\nsubsection \\<open>Cardinality\\<close>\n\nlemma card_inj: \"f \\<in> A \\<rightarrow> B \\<Longrightarrow> inj_on f A \\<Longrightarrow> finite B \\<Longrightarrow> card A \\<le> card B\"\n  by (rule card_inj_on_le) auto\n\nlemma card_bij:\n  assumes \"f \\<in> A \\<rightarrow> B\" \"inj_on f A\"\n    and \"g \\<in> B \\<rightarrow> A\" \"inj_on g B\"\n    and \"finite A\" \"finite B\"\n  shows \"card A = card B\"\n  using assms by (blast intro: card_inj order_antisym)\n\n\nsubsection \\<open>Extensional Function Spaces\\<close>\n\ndefinition PiE :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"\n  where \"PiE S T = Pi S T \\<inter> extensional S\"\n\nabbreviation \"Pi\\<^sub>E A B \\<equiv> PiE A B\"\n\nsyntax\n  \"_PiE\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3PIE _:_./ _)\" 10)\nsyntax (xsymbols)\n  \"_PiE\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3\\<Pi>\\<^sub>E _\\<in>_./ _)\" 10)\nsyntax (HTML output)\n  \"_PiE\" :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\"  (\"(3\\<Pi>\\<^sub>E _\\<in>_./ _)\" 10)\ntranslations \"\\<Pi>\\<^sub>E x\\<in>A. B\" \\<rightleftharpoons> \"CONST Pi\\<^sub>E A (\\<lambda>x. B)\"\n\nabbreviation extensional_funcset :: \"'a set \\<Rightarrow> 'b set \\<Rightarrow> ('a \\<Rightarrow> 'b) set\" (infixr \"->\\<^sub>E\" 60)\n  where \"A ->\\<^sub>E B \\<equiv> (\\<Pi>\\<^sub>E i\\<in>A. B)\"\n\nnotation (xsymbols)\n  extensional_funcset  (infixr \"\\<rightarrow>\\<^sub>E\" 60)\n\nlemma extensional_funcset_def: \"extensional_funcset S T = (S \\<rightarrow> T) \\<inter> extensional S\"\n  by (simp add: PiE_def)\n\nlemma PiE_empty_domain[simp]: \"PiE {} T = {\\<lambda>x. undefined}\"\n  unfolding PiE_def by simp\n\nlemma PiE_UNIV_domain: \"PiE UNIV T = Pi UNIV T\"\n  unfolding PiE_def by simp\n\nlemma PiE_empty_range[simp]: \"i \\<in> I \\<Longrightarrow> F i = {} \\<Longrightarrow> (\\<Pi>\\<^sub>E i\\<in>I. F i) = {}\"\n  unfolding PiE_def by auto\n\nlemma PiE_eq_empty_iff: \"Pi\\<^sub>E I F = {} \\<longleftrightarrow> (\\<exists>i\\<in>I. F i = {})\"\nproof\n  assume \"Pi\\<^sub>E I F = {}\"\n  show \"\\<exists>i\\<in>I. F i = {}\"\n  proof (rule ccontr)\n    assume \"\\<not> ?thesis\"\n    then have \"\\<forall>i. \\<exists>y. (i \\<in> I \\<longrightarrow> y \\<in> F i) \\<and> (i \\<notin> I \\<longrightarrow> y = undefined)\"\n      by auto\n    from choice[OF this]\n    obtain f where \" \\<forall>x. (x \\<in> I \\<longrightarrow> f x \\<in> F x) \\<and> (x \\<notin> I \\<longrightarrow> f x = undefined)\" ..\n    then have \"f \\<in> Pi\\<^sub>E I F\"\n      by (auto simp: extensional_def PiE_def)\n    with \\<open>Pi\\<^sub>E I F = {}\\<close> show False\n      by auto\n  qed\nqed (auto simp: PiE_def)\n\nlemma PiE_arb: \"f \\<in> PiE S T \\<Longrightarrow> x \\<notin> S \\<Longrightarrow> f x = undefined\"\n  unfolding PiE_def by auto (auto dest!: extensional_arb)\n\nlemma PiE_mem: \"f \\<in> PiE S T \\<Longrightarrow> x \\<in> S \\<Longrightarrow> f x \\<in> T x\"\n  unfolding PiE_def by auto\n\nlemma PiE_fun_upd: \"y \\<in> T x \\<Longrightarrow> f \\<in> PiE S T \\<Longrightarrow> f(x := y) \\<in> PiE (insert x S) T\"\n  unfolding PiE_def extensional_def by auto\n\nlemma fun_upd_in_PiE: \"x \\<notin> S \\<Longrightarrow> f \\<in> PiE (insert x S) T \\<Longrightarrow> f(x := undefined) \\<in> PiE S T\"\n  unfolding PiE_def extensional_def by auto\n\nlemma PiE_insert_eq:\n  assumes \"x \\<notin> S\"\n  shows \"PiE (insert x S) T = (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> PiE S T)\"\nproof -\n  {\n    fix f assume \"f \\<in> PiE (insert x S) T\"\n    with assms have \"f \\<in> (\\<lambda>(y, g). g(x := y)) ` (T x \\<times> PiE S T)\"\n      by (auto intro!: image_eqI[where x=\"(f x, f(x := undefined))\"] intro: fun_upd_in_PiE PiE_mem)\n  }\n  then show ?thesis\n    using assms by (auto intro: PiE_fun_upd)\nqed\n\nlemma PiE_Int: \"Pi\\<^sub>E I A \\<inter> Pi\\<^sub>E I B = Pi\\<^sub>E I (\\<lambda>x. A x \\<inter> B x)\"\n  by (auto simp: PiE_def)\n\nlemma PiE_cong: \"(\\<And>i. i\\<in>I \\<Longrightarrow> A i = B i) \\<Longrightarrow> Pi\\<^sub>E I A = Pi\\<^sub>E I B\"\n  unfolding PiE_def by (auto simp: Pi_cong)\n\nlemma PiE_E [elim]:\n  assumes \"f \\<in> PiE A B\"\n  obtains \"x \\<in> A\" and \"f x \\<in> B x\"\n    | \"x \\<notin> A\" and \"f x = undefined\"\n  using assms by (auto simp: Pi_def PiE_def extensional_def)\n\nlemma PiE_I[intro!]:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<in> B x) \\<Longrightarrow> (\\<And>x. x \\<notin> A \\<Longrightarrow> f x = undefined) \\<Longrightarrow> f \\<in> PiE A B\"\n  by (simp add: PiE_def extensional_def)\n\nlemma PiE_mono: \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> C x) \\<Longrightarrow> PiE A B \\<subseteq> PiE A C\"\n  by auto\n\nlemma PiE_iff: \"f \\<in> PiE I X \\<longleftrightarrow> (\\<forall>i\\<in>I. f i \\<in> X i) \\<and> f \\<in> extensional I\"\n  by (simp add: PiE_def Pi_iff)\n\nlemma PiE_restrict[simp]:  \"f \\<in> PiE A B \\<Longrightarrow> restrict f A = f\"\n  by (simp add: extensional_restrict PiE_def)\n\nlemma restrict_PiE[simp]: \"restrict f I \\<in> PiE I S \\<longleftrightarrow> f \\<in> Pi I S\"\n  by (auto simp: PiE_iff)\n\nlemma PiE_eq_subset:\n  assumes ne: \"\\<And>i. i \\<in> I \\<Longrightarrow> F i \\<noteq> {}\" \"\\<And>i. i \\<in> I \\<Longrightarrow> F' i \\<noteq> {}\"\n    and eq: \"Pi\\<^sub>E I F = Pi\\<^sub>E I F'\"\n    and \"i \\<in> I\"\n  shows \"F i \\<subseteq> F' i\"\nproof\n  fix x\n  assume \"x \\<in> F i\"\n  with ne have \"\\<forall>j. \\<exists>y. (j \\<in> I \\<longrightarrow> y \\<in> F j \\<and> (i = j \\<longrightarrow> x = y)) \\<and> (j \\<notin> I \\<longrightarrow> y = undefined)\"\n    by auto\n  from choice[OF this] obtain f\n    where f: \" \\<forall>j. (j \\<in> I \\<longrightarrow> f j \\<in> F j \\<and> (i = j \\<longrightarrow> x = f j)) \\<and> (j \\<notin> I \\<longrightarrow> f j = undefined)\" ..\n  then have \"f \\<in> Pi\\<^sub>E I F\"\n    by (auto simp: extensional_def PiE_def)\n  then have \"f \\<in> Pi\\<^sub>E I F'\"\n    using assms by simp\n  then show \"x \\<in> F' i\"\n    using f \\<open>i \\<in> I\\<close> by (auto simp: PiE_def)\nqed\n\nlemma PiE_eq_iff_not_empty:\n  assumes ne: \"\\<And>i. i \\<in> I \\<Longrightarrow> F i \\<noteq> {}\" \"\\<And>i. i \\<in> I \\<Longrightarrow> F' i \\<noteq> {}\"\n  shows \"Pi\\<^sub>E I F = Pi\\<^sub>E I F' \\<longleftrightarrow> (\\<forall>i\\<in>I. F i = F' i)\"\nproof (intro iffI ballI)\n  fix i\n  assume eq: \"Pi\\<^sub>E I F = Pi\\<^sub>E I F'\"\n  assume i: \"i \\<in> I\"\n  show \"F i = F' i\"\n    using PiE_eq_subset[of I F F', OF ne eq i]\n    using PiE_eq_subset[of I F' F, OF ne(2,1) eq[symmetric] i]\n    by auto\nqed (auto simp: PiE_def)\n\nlemma PiE_eq_iff:\n  \"Pi\\<^sub>E I F = Pi\\<^sub>E I F' \\<longleftrightarrow> (\\<forall>i\\<in>I. F i = F' i) \\<or> ((\\<exists>i\\<in>I. F i = {}) \\<and> (\\<exists>i\\<in>I. F' i = {}))\"\nproof (intro iffI disjCI)\n  assume eq[simp]: \"Pi\\<^sub>E I F = Pi\\<^sub>E I F'\"\n  assume \"\\<not> ((\\<exists>i\\<in>I. F i = {}) \\<and> (\\<exists>i\\<in>I. F' i = {}))\"\n  then have \"(\\<forall>i\\<in>I. F i \\<noteq> {}) \\<and> (\\<forall>i\\<in>I. F' i \\<noteq> {})\"\n    using PiE_eq_empty_iff[of I F] PiE_eq_empty_iff[of I F'] by auto\n  with PiE_eq_iff_not_empty[of I F F'] show \"\\<forall>i\\<in>I. F i = F' i\"\n    by auto\nnext\n  assume \"(\\<forall>i\\<in>I. F i = F' i) \\<or> (\\<exists>i\\<in>I. F i = {}) \\<and> (\\<exists>i\\<in>I. F' i = {})\"\n  then show \"Pi\\<^sub>E I F = Pi\\<^sub>E I F'\"\n    using PiE_eq_empty_iff[of I F] PiE_eq_empty_iff[of I F'] by (auto simp: PiE_def)\nqed\n\nlemma extensional_funcset_fun_upd_restricts_rangeI:\n  \"\\<forall>y \\<in> S. f x \\<noteq> f y \\<Longrightarrow> f \\<in> (insert x S) \\<rightarrow>\\<^sub>E T \\<Longrightarrow> f(x := undefined) \\<in> S \\<rightarrow>\\<^sub>E (T - {f x})\"\n  unfolding extensional_funcset_def extensional_def\n  apply auto\n  apply (case_tac \"x = xa\")\n  apply auto\n  done\n\nlemma extensional_funcset_fun_upd_extends_rangeI:\n  assumes \"a \\<in> T\" \"f \\<in> S \\<rightarrow>\\<^sub>E (T - {a})\"\n  shows \"f(x := a) \\<in> insert x S \\<rightarrow>\\<^sub>E  T\"\n  using assms unfolding extensional_funcset_def extensional_def by auto\n\n\nsubsubsection \\<open>Injective Extensional Function Spaces\\<close>\n\nlemma extensional_funcset_fun_upd_inj_onI:\n  assumes \"f \\<in> S \\<rightarrow>\\<^sub>E (T - {a})\"\n    and \"inj_on f S\"\n  shows \"inj_on (f(x := a)) S\"\n  using assms\n  unfolding extensional_funcset_def by (auto intro!: inj_on_fun_updI)\n\nlemma extensional_funcset_extend_domain_inj_on_eq:\n  assumes \"x \\<notin> S\"\n  shows \"{f. f \\<in> (insert x S) \\<rightarrow>\\<^sub>E T \\<and> inj_on f (insert x S)} =\n    (\\<lambda>(y, g). g(x:=y)) ` {(y, g). y \\<in> T \\<and> g \\<in> S \\<rightarrow>\\<^sub>E (T - {y}) \\<and> inj_on g S}\"\n  using assms\n  apply (auto del: PiE_I PiE_E)\n  apply (auto intro: extensional_funcset_fun_upd_inj_onI\n    extensional_funcset_fun_upd_extends_rangeI del: PiE_I PiE_E)\n  apply (auto simp add: image_iff inj_on_def)\n  apply (rule_tac x=\"xa x\" in exI)\n  apply (auto intro: PiE_mem del: PiE_I PiE_E)\n  apply (rule_tac x=\"xa(x := undefined)\" in exI)\n  apply (auto intro!: extensional_funcset_fun_upd_restricts_rangeI)\n  apply (auto dest!: PiE_mem split: split_if_asm)\n  done\n\nlemma extensional_funcset_extend_domain_inj_onI:\n  assumes \"x \\<notin> S\"\n  shows \"inj_on (\\<lambda>(y, g). g(x := y)) {(y, g). y \\<in> T \\<and> g \\<in> S \\<rightarrow>\\<^sub>E (T - {y}) \\<and> inj_on g S}\"\n  using assms\n  apply (auto intro!: inj_onI)\n  apply (metis fun_upd_same)\n  apply (metis assms PiE_arb fun_upd_triv fun_upd_upd)\n  done\n\n\nsubsubsection \\<open>Cardinality\\<close>\n\nlemma finite_PiE: \"finite S \\<Longrightarrow> (\\<And>i. i \\<in> S \\<Longrightarrow> finite (T i)) \\<Longrightarrow> finite (\\<Pi>\\<^sub>E i \\<in> S. T i)\"\n  by (induct S arbitrary: T rule: finite_induct) (simp_all add: PiE_insert_eq)\n\nlemma inj_combinator: \"x \\<notin> S \\<Longrightarrow> inj_on (\\<lambda>(y, g). g(x := y)) (T x \\<times> Pi\\<^sub>E S T)\"\nproof (safe intro!: inj_onI ext)\n  fix f y g z\n  assume \"x \\<notin> S\"\n  assume fg: \"f \\<in> Pi\\<^sub>E S T\" \"g \\<in> Pi\\<^sub>E S T\"\n  assume \"f(x := y) = g(x := z)\"\n  then have *: \"\\<And>i. (f(x := y)) i = (g(x := z)) i\"\n    unfolding fun_eq_iff by auto\n  from this[of x] show \"y = z\" by simp\n  fix i from *[of i] \\<open>x \\<notin> S\\<close> fg show \"f i = g i\"\n    by (auto split: split_if_asm simp: PiE_def extensional_def)\nqed\n\nlemma card_PiE: \"finite S \\<Longrightarrow> card (\\<Pi>\\<^sub>E i \\<in> S. T i) = (\\<Prod> i\\<in>S. card (T i))\"\nproof (induct rule: finite_induct)\n  case empty\n  then show ?case by auto\nnext\n  case (insert x S)\n  then show ?case\n    by (simp add: PiE_insert_eq inj_combinator card_image card_cartesian_product)\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/FuncSet.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8705972667296309, "lm_q1q2_score": 0.7579396110675882}}
{"text": "(*  Title:      HOL/ex/PER.thy\n    Author:     Oscar Slotosch and Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Partial equivalence relations\\<close>\n\ntheory PER\nimports MainRLT\nbegin\n\ntext \\<open>\n  Higher-order quotients are defined over partial equivalence\n  relations (PERs) instead of total ones.  We provide axiomatic type\n  classes \\<open>equiv < partial_equiv\\<close> and a type constructor\n  \\<open>'a quot\\<close> with basic operations.  This development is based\n  on:\n\n  Oscar Slotosch: \\emph{Higher Order Quotients and their\n  Implementation in Isabelle HOL.}  Elsa L. Gunter and Amy Felty,\n  editors, Theorem Proving in Higher Order Logics: TPHOLs '97,\n  Springer LNCS 1275, 1997.\n\\<close>\n\n\nsubsection \\<open>Partial equivalence\\<close>\n\ntext \\<open>\n  Type class \\<open>partial_equiv\\<close> models partial equivalence\n  relations (PERs) using the polymorphic \\<open>\\<sim> :: 'a \\<Rightarrow> 'a \\<Rightarrow>\n  bool\\<close> relation, which is required to be symmetric and transitive,\n  but not necessarily reflexive.\n\\<close>\n\nclass partial_equiv =\n  fixes eqv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"    (infixl \"\\<sim>\" 50)\n  assumes partial_equiv_sym [elim?]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\"\n  assumes partial_equiv_trans [trans]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> x \\<sim> z\"\n\ntext \\<open>\n  \\medskip The domain of a partial equivalence relation is the set of\n  reflexive elements.  Due to symmetry and transitivity this\n  characterizes exactly those elements that are connected with\n  \\emph{any} other one.\n\\<close>\n\ndefinition\n  \"domain\" :: \"'a::partial_equiv set\" where\n  \"domain = {x. x \\<sim> x}\"\n\nlemma domainI [intro]: \"x \\<sim> x \\<Longrightarrow> x \\<in> domain\"\n  unfolding domain_def by blast\n\nlemma domainD [dest]: \"x \\<in> domain \\<Longrightarrow> x \\<sim> x\"\n  unfolding domain_def by blast\n\ntheorem domainI' [elim?]: \"x \\<sim> y \\<Longrightarrow> x \\<in> domain\"\nproof\n  assume xy: \"x \\<sim> y\"\n  also from xy have \"y \\<sim> x\" ..\n  finally show \"x \\<sim> x\" .\nqed\n\n\nsubsection \\<open>Equivalence on function spaces\\<close>\n\ntext \\<open>\n  The \\<open>\\<sim>\\<close> relation is lifted to function spaces.  It is\n  important to note that this is \\emph{not} the direct product, but a\n  structural one corresponding to the congruence property.\n\\<close>\n\ninstantiation \"fun\" :: (partial_equiv, partial_equiv) partial_equiv\nbegin\n\ndefinition \"f \\<sim> g \\<longleftrightarrow> (\\<forall>x \\<in> domain. \\<forall>y \\<in> domain. x \\<sim> y \\<longrightarrow> f x \\<sim> g y)\"\n\nlemma partial_equiv_funI [intro?]:\n    \"(\\<And>x y. x \\<in> domain \\<Longrightarrow> y \\<in> domain \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> f x \\<sim> g y) \\<Longrightarrow> f \\<sim> g\"\n  unfolding eqv_fun_def by blast\n\nlemma partial_equiv_funD [dest?]:\n    \"f \\<sim> g \\<Longrightarrow> x \\<in> domain \\<Longrightarrow> y \\<in> domain \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> f x \\<sim> g y\"\n  unfolding eqv_fun_def by blast\n\ntext \\<open>\n  The class of partial equivalence relations is closed under function\n  spaces (in \\emph{both} argument positions).\n\\<close>\n\ninstance proof\n  fix f g h :: \"'a::partial_equiv \\<Rightarrow> 'b::partial_equiv\"\n  assume fg: \"f \\<sim> g\"\n  show \"g \\<sim> f\"\n  proof\n    fix x y :: 'a\n    assume x: \"x \\<in> domain\" and y: \"y \\<in> domain\"\n    assume \"x \\<sim> y\" then have \"y \\<sim> x\" ..\n    with fg y x have \"f y \\<sim> g x\" ..\n    then show \"g x \\<sim> f y\" ..\n  qed\n  assume gh: \"g \\<sim> h\"\n  show \"f \\<sim> h\"\n  proof\n    fix x y :: 'a\n    assume x: \"x \\<in> domain\" and y: \"y \\<in> domain\" and \"x \\<sim> y\"\n    with fg have \"f x \\<sim> g y\" ..\n    also from y have \"y \\<sim> y\" ..\n    with gh y y have \"g y \\<sim> h y\" ..\n    finally show \"f x \\<sim> h y\" .\n  qed\nqed\n\nend\n\n\nsubsection \\<open>Total equivalence\\<close>\n\ntext \\<open>\n  The class of total equivalence relations on top of PERs.  It\n  coincides with the standard notion of equivalence, i.e.\\ \\<open>\\<sim>\n  :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close> is required to be reflexive, transitive and\n  symmetric.\n\\<close>\n\nclass equiv =\n  assumes eqv_refl [intro]: \"x \\<sim> x\"\n\ntext \\<open>\n  On total equivalences all elements are reflexive, and congruence\n  holds unconditionally.\n\\<close>\n\ntheorem equiv_domain [intro]: \"(x::'a::equiv) \\<in> domain\"\nproof\n  show \"x \\<sim> x\" ..\nqed\n\ntheorem equiv_cong [dest?]: \"f \\<sim> g \\<Longrightarrow> x \\<sim> y \\<Longrightarrow> f x \\<sim> g (y::'a::equiv)\"\nproof -\n  assume \"f \\<sim> g\"\n  moreover have \"x \\<in> domain\" ..\n  moreover have \"y \\<in> domain\" ..\n  moreover assume \"x \\<sim> y\"\n  ultimately show ?thesis ..\nqed\n\n\nsubsection \\<open>Quotient types\\<close>\n\ntext \\<open>\n  The quotient type \\<open>'a quot\\<close> consists of all\n  \\emph{equivalence classes} over elements of the base type \\<^typ>\\<open>'a\\<close>.\n\\<close>\n\ndefinition \"quot = {{x. a \\<sim> x}| a::'a::partial_equiv. True}\"\n\ntypedef (overloaded) 'a quot = \"quot :: 'a::partial_equiv set set\"\n  unfolding quot_def by blast\n\nlemma quotI [intro]: \"{x. a \\<sim> x} \\<in> quot\"\n  unfolding quot_def by blast\n\nlemma quotE [elim]: \"R \\<in> quot \\<Longrightarrow> (\\<And>a. R = {x. a \\<sim> x} \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  unfolding quot_def by blast\n\ntext \\<open>\n  \\medskip Abstracted equivalence classes are the canonical\n  representation of elements of a quotient type.\n\\<close>\n\ndefinition eqv_class :: \"('a::partial_equiv) \\<Rightarrow> 'a quot\"  (\"\\<lfloor>_\\<rfloor>\")\n  where \"\\<lfloor>a\\<rfloor> = Abs_quot {x. a \\<sim> x}\"\n\ntheorem quot_rep: \"\\<exists>a. A = \\<lfloor>a\\<rfloor>\"\nproof (cases A)\n  fix R assume R: \"A = Abs_quot R\"\n  assume \"R \\<in> quot\" then have \"\\<exists>a. R = {x. a \\<sim> x}\" by blast\n  with R have \"\\<exists>a. A = Abs_quot {x. a \\<sim> x}\" by blast\n  then show ?thesis by (unfold eqv_class_def)\nqed\n\nlemma quot_cases [cases type: quot]:\n  obtains (rep) a where \"A = \\<lfloor>a\\<rfloor>\"\n  using quot_rep by blast\n\n\nsubsection \\<open>Equality on quotients\\<close>\n\ntext \\<open>\n  Equality of canonical quotient elements corresponds to the original\n  relation as follows.\n\\<close>\n\ntheorem eqv_class_eqI [intro]: \"a \\<sim> b \\<Longrightarrow> \\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor>\"\nproof -\n  assume ab: \"a \\<sim> b\"\n  have \"{x. a \\<sim> x} = {x. b \\<sim> x}\"\n  proof (rule Collect_cong)\n    fix x show \"a \\<sim> x \\<longleftrightarrow> b \\<sim> x\"\n    proof\n      from ab have \"b \\<sim> a\" ..\n      also assume \"a \\<sim> x\"\n      finally show \"b \\<sim> x\" .\n    next\n      note ab\n      also assume \"b \\<sim> x\"\n      finally show \"a \\<sim> x\" .\n    qed\n  qed\n  then show ?thesis by (simp only: eqv_class_def)\nqed\n\ntheorem eqv_class_eqD' [dest?]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<Longrightarrow> a \\<in> domain \\<Longrightarrow> a \\<sim> b\"\nproof (unfold eqv_class_def)\n  assume \"Abs_quot {x. a \\<sim> x} = Abs_quot {x. b \\<sim> x}\"\n  then have \"{x. a \\<sim> x} = {x. b \\<sim> x}\" by (simp only: Abs_quot_inject quotI)\n  moreover assume \"a \\<in> domain\" then have \"a \\<sim> a\" ..\n  ultimately have \"a \\<in> {x. b \\<sim> x}\" by blast\n  then have \"b \\<sim> a\" by blast\n  then show \"a \\<sim> b\" ..\nqed\n\ntheorem eqv_class_eqD [dest?]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<Longrightarrow> a \\<sim> (b::'a::equiv)\"\nproof (rule eqv_class_eqD')\n  show \"a \\<in> domain\" ..\nqed\n\nlemma eqv_class_eq' [simp]: \"a \\<in> domain \\<Longrightarrow> \\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<longleftrightarrow> a \\<sim> b\"\n  using eqv_class_eqI eqv_class_eqD' by (blast del: eqv_refl)\n\nlemma eqv_class_eq [simp]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<longleftrightarrow> a \\<sim> (b::'a::equiv)\"\n  using eqv_class_eqI eqv_class_eqD by blast\n\n\nsubsection \\<open>Picking representing elements\\<close>\n\ndefinition pick :: \"'a::partial_equiv quot \\<Rightarrow> 'a\"\n  where \"pick A = (SOME a. A = \\<lfloor>a\\<rfloor>)\"\n\ntheorem pick_eqv' [intro?, simp]: \"a \\<in> domain \\<Longrightarrow> pick \\<lfloor>a\\<rfloor> \\<sim> a\"\nproof (unfold pick_def)\n  assume a: \"a \\<in> domain\"\n  show \"(SOME x. \\<lfloor>a\\<rfloor> = \\<lfloor>x\\<rfloor>) \\<sim> a\"\n  proof (rule someI2)\n    show \"\\<lfloor>a\\<rfloor> = \\<lfloor>a\\<rfloor>\" ..\n    fix x assume \"\\<lfloor>a\\<rfloor> = \\<lfloor>x\\<rfloor>\"\n    from this and a have \"a \\<sim> x\" ..\n    then show \"x \\<sim> a\" ..\n  qed\nqed\n\ntheorem pick_eqv [intro, simp]: \"pick \\<lfloor>a\\<rfloor> \\<sim> (a::'a::equiv)\"\nproof (rule pick_eqv')\n  show \"a \\<in> domain\" ..\nqed\n\ntheorem pick_inverse: \"\\<lfloor>pick A\\<rfloor> = (A::'a::equiv quot)\"\nproof (cases A)\n  fix a assume a: \"A = \\<lfloor>a\\<rfloor>\"\n  then have \"pick A \\<sim> a\" by simp\n  then have \"\\<lfloor>pick A\\<rfloor> = \\<lfloor>a\\<rfloor>\" by simp\n  with a show ?thesis by simp\nqed\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/ex/PER.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.757939603760099}}
{"text": "(*  Title:       Countable Ordinals\n\n    Author:      Brian Huffman, 2005\n    Maintainer:  Brian Huffman <brianh at cse.ogi.edu>\n*)\n\nheader {* Ordinal Induction *}\n\ntheory OrdinalInduct\nimports OrdinalDef\nbegin\n\nsubsection {* Zero and successor ordinals *}\n\ndefinition\n  oSuc :: \"ordinal \\<Rightarrow> ordinal\" where\n    \"oSuc x = oStrictLimit (\\<lambda>n. x)\"\n\nlemma less_oSuc[iff]: \"x < oSuc x\"\nby (unfold oSuc_def, rule oStrictLimit_ub)\n\nlemma oSuc_leI: \"x < y \\<Longrightarrow> oSuc x \\<le> y\"\nby (unfold oSuc_def, rule oStrictLimit_lub, simp)\n\ninstantiation ordinal :: \"{zero, one}\"\nbegin\n\ndefinition\n  ordinal_zero_def:       \"(0::ordinal) = oZero\"\n\ndefinition\n  ordinal_one_def [simp]: \"(1::ordinal) = oSuc 0\"\n\ninstance ..\n\nend\n\n\nsubsubsection {* Derived properties of 0 and oSuc *}\n\nlemma less_oSuc_eq_le: \"(x < oSuc y) = (x \\<le> y)\"\n apply (rule iffI)\n  apply (erule contrapos_pp, simp add: linorder_not_less linorder_not_le)\n  apply (erule oSuc_leI)\n apply (erule order_le_less_trans[OF _ less_oSuc])\ndone\n\nlemma ordinal_0_le [iff]: \"0 \\<le> (x::ordinal)\"\nby (unfold ordinal_zero_def, rule oZero_least)\n\nlemma ordinal_not_less_0 [iff]: \"\\<not> (x::ordinal) < 0\"\nby (simp add: linorder_not_less)\n\nlemma ordinal_le_0 [iff]: \"(x \\<le> 0) = (x = (0::ordinal))\"\nby (simp add: order_le_less)\n\nlemma ordinal_neq_0 [iff]: \"(x \\<noteq> 0) = (0 < (x::ordinal))\"\nby (simp add: order_less_le)\n\nlemma ordinal_not_0_less [iff]: \"(\\<not> 0 < x) = (x = (0::ordinal))\"\nby (simp add: linorder_not_less)\n\n\n\nlemma zero_less_oSuc [iff]: \"0 < oSuc x\"\nby (rule order_le_less_trans, rule ordinal_0_le, rule less_oSuc)\n\nlemma oSuc_not_0 [iff]: \"oSuc x \\<noteq> 0\"\nby simp\n\nlemma less_oSuc0 [iff]: \"(x < oSuc 0) = (x = 0)\"\nby (simp add: less_oSuc_eq_le)\n\nlemma oSuc_less_oSuc [iff]: \"(oSuc x < oSuc y) = (x < y)\"\n apply (rule iffI)\n  apply (simp add: less_oSuc_eq_le order_less_le_trans[OF less_oSuc])\n apply (erule order_le_less_trans[OF oSuc_leI less_oSuc])\ndone\n\nlemma oSuc_eq_oSuc [iff]: \"(oSuc x = oSuc y) = (x = y)\"\nby (safe, erule contrapos_pp, simp add: linorder_neq_iff)\n\nlemma oSuc_le_oSuc [iff]: \"(oSuc x \\<le> oSuc y) = (x \\<le> y)\"\nby (simp add: order_le_less)\n\nlemma le_oSucE: \n\"\\<lbrakk>x \\<le> oSuc y; x \\<le> y \\<Longrightarrow> R; x = oSuc y \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\nby (auto simp add: order_le_less less_oSuc_eq_le)\n\nlemma less_oSucE:\n\"\\<lbrakk>x < oSuc y; x < y \\<Longrightarrow> P; x = y \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (auto simp add: less_oSuc_eq_le order_le_less)\n\n\nsubsection {* Strict monotonicity *}\n\nlocale strict_mono =\n  fixes f\n  assumes strict_mono: \"A < B \\<Longrightarrow> f A < f B\"\n\nlemmas strict_monoI = strict_mono.intro\n   and strict_monoD = strict_mono.strict_mono\n\nlemma strict_mono_natI:\nfixes f :: \"nat \\<Rightarrow> 'a::order\"\nshows \"(\\<And>n. f n < f (Suc n)) \\<Longrightarrow> strict_mono f\"\n apply (rule strict_monoI)\n apply (drule Suc_leI)\n apply (drule le_add_diff_inverse)\n apply (subgoal_tac \"\\<forall>k. f A < f (Suc A + k)\")\n  apply (erule subst, erule spec)\n apply (rule allI, induct_tac k, simp)\n apply (erule order_less_trans, simp)\ndone\n\nlemma mono_natI:\nfixes f :: \"nat \\<Rightarrow> 'a::order\"\nshows \"(\\<And>n. f n \\<le> f (Suc n)) \\<Longrightarrow> mono f\"\n apply (rule monoI)\n apply (drule le_add_diff_inverse)\n apply (subgoal_tac \"\\<forall>k. f x \\<le> f (x + k)\")\n  apply (erule subst, erule spec)\n apply (rule allI, induct_tac k, simp)\n apply (erule order_trans, simp)\ndone\n\nlemma strict_mono_mono:\nfixes f :: \"'a::order \\<Rightarrow> 'b::order\"\nshows \"strict_mono f \\<Longrightarrow> mono f\"\nby (auto intro!: monoI simp add: order_le_less strict_monoD)\n\nlemma strict_mono_monoD:\nfixes f :: \"'a::order \\<Rightarrow> 'b::order\"\nshows \"\\<lbrakk>strict_mono f; A \\<le> B\\<rbrakk> \\<Longrightarrow> f A \\<le> f B\"\nby (rule monoD[OF strict_mono_mono])\n\nlemma strict_mono_cancel_eq:\nfixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\nshows \"strict_mono f \\<Longrightarrow> (f x = f y) = (x = y)\"\n apply safe\n apply (rule_tac x=x and y=y in linorder_cases)\n   apply (drule strict_monoD, assumption, simp)\n  apply assumption\n apply (drule strict_monoD, assumption, simp)\ndone\n\nlemma strict_mono_cancel_less: \nfixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\nshows \"strict_mono f \\<Longrightarrow> (f x < f y) = (x < y)\"\n apply safe\n  apply (rule_tac x=x and y=y in linorder_cases)\n    apply assumption\n   apply simp\n  apply (drule strict_monoD, assumption, simp)\n apply (simp add: strict_monoD)\ndone\n\nlemma strict_mono_cancel_le:\nfixes f :: \"'a::linorder \\<Rightarrow> 'b::linorder\"\nshows \"strict_mono f \\<Longrightarrow> (f x \\<le> f y) = (x \\<le> y)\"\n apply (auto simp add: order_le_less)\n   apply (simp add: strict_mono_cancel_less)\n  apply (simp add: strict_mono_cancel_eq)\n apply (simp add: strict_monoD)\ndone\n\n\nsubsection {* Limit ordinals *}\n\ndefinition\n  oLimit :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> ordinal\" where\n  \"oLimit f = (LEAST k. \\<forall>n. f n \\<le> k)\"\n\nlemma oLimit_leI: \"\\<forall>n. f n \\<le> x \\<Longrightarrow> oLimit f \\<le> x\"\n apply (unfold oLimit_def)\n apply (erule Least_le)\ndone\n\nlemma le_oLimit [iff]: \"f n \\<le> oLimit f\"\n apply (unfold oLimit_def)\n apply (rule_tac x=n in spec)\n apply (rule_tac k=\"oStrictLimit f\" in LeastI)\n apply (clarify, rule order_less_imp_le)\n apply (rule oStrictLimit_ub)\ndone\n\nlemma le_oLimitI: \"x \\<le> f n \\<Longrightarrow> x \\<le> oLimit f\"\nby (erule order_trans, rule le_oLimit)\n\nlemma less_oLimitI: \"x < f n \\<Longrightarrow> x < oLimit f\"\nby (erule order_less_le_trans, rule le_oLimit)\n\nlemma less_oLimitD: \"x < oLimit f \\<Longrightarrow> \\<exists>n. x < f n\"\n apply (unfold oLimit_def)\n apply (drule not_less_Least)\n apply (simp add: linorder_not_le)\ndone\n\nlemma less_oLimitE:\n\"\\<lbrakk>x < oLimit f; \\<And>n. x < f n \\<Longrightarrow> P\\<rbrakk> \\<Longrightarrow> P\"\nby (auto dest: less_oLimitD)\n\nlemma le_oLimitE:\n\"\\<lbrakk>x \\<le> oLimit f; \\<And>n. x \\<le> f n \\<Longrightarrow> R; x = oLimit f \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\nby (auto simp add: order_le_less dest: less_oLimitD)\n\nlemma oLimit_const [simp]: \"oLimit (\\<lambda>n. x) = x\"\n apply (rule order_antisym[OF _ le_oLimit])\n apply (rule oLimit_leI, simp)\ndone\n\nlemma strict_mono_less_oLimit:\n\"strict_mono f \\<Longrightarrow> f n < oLimit f\"\n apply (rule order_less_le_trans)\n  apply (erule strict_monoD, rule lessI)\n apply (rule le_oLimit)\ndone\n\nlemma oLimit_eqI:\n\"\\<lbrakk>\\<And>n. \\<exists>m. f n \\<le> g m; \\<And>n. \\<exists>m. g n \\<le> f m\\<rbrakk> \\<Longrightarrow> oLimit f = oLimit g\"\n apply atomize\n apply (rule order_antisym)\n  apply (rule oLimit_leI, clarify)\n  apply (drule spec, erule exE, erule le_oLimitI)\n apply (rule oLimit_leI, clarify)\n apply (drule spec, erule exE, erule le_oLimitI)\ndone\n\nlemma oLimit_Suc:\n\"f 0 < oLimit f \\<Longrightarrow> oLimit (\\<lambda>n. f (Suc n)) = oLimit f\"\n apply (rule oLimit_eqI)\n  apply (rule exI, rule order_refl)\n apply (case_tac n)\n  apply (drule less_oLimitD, clarify, rename_tac m)\n  apply (case_tac m, simp)\n  apply (rule_tac x=nat in exI)\n  apply (simp add: order_less_imp_le)\n apply (rule_tac x=nat in exI, simp)\ndone\n\nlemma oLimit_shift:\n\"\\<forall>n. f n < oLimit f \\<Longrightarrow> oLimit (\\<lambda>n. f (n + k)) = oLimit f\"\n apply (induct_tac k, simp, rename_tac k)\n apply (simp only: add_Suc_right add_Suc[symmetric])\n apply (rule trans[OF oLimit_Suc], simp_all)\ndone\n\nlemma oLimit_shift_mono:\n\"mono f \\<Longrightarrow> oLimit (\\<lambda>n. f (n + k)) = oLimit f\"\n apply (rule oLimit_eqI)\n  apply (rule exI, rule order_refl)\n apply (rule_tac x=n in exI)\n apply (erule monoD, simp)\ndone\n\n\ntext \"limit ordinal predicate\"\n\ndefinition\n  limit_ordinal :: \"ordinal \\<Rightarrow> bool\" where\n  \"limit_ordinal x \\<longleftrightarrow> (x \\<noteq> 0) \\<and> (\\<forall>y. x \\<noteq> oSuc y)\"\n\nlemma limit_ordinal_not_0 [simp]: \"\\<not> limit_ordinal 0\"\nby (simp add: limit_ordinal_def)\n\nlemma zero_less_limit_ordinal [simp]: \"limit_ordinal x \\<Longrightarrow> 0 < x\"\nby (simp add: limit_ordinal_def)\n\nlemma limit_ordinal_not_oSuc [simp]: \"\\<not> limit_ordinal (oSuc p)\"\nby (simp add: limit_ordinal_def)\n\nlemma oSuc_less_limit_ordinal:\n\"limit_ordinal x \\<Longrightarrow> (oSuc w < x) = (w < x)\"\n apply (rule iffI)\n  apply (erule order_less_trans[OF less_oSuc])\n apply (simp add: linorder_not_le[symmetric])\n apply (erule contrapos_nn)\n apply (auto simp add: order_le_less less_oSuc_eq_le)\ndone\n\nlemma limit_ordinal_oLimitI:\n\"\\<forall>n. f n < oLimit f \\<Longrightarrow> limit_ordinal (oLimit f)\"\n apply (unfold limit_ordinal_def, simp)\n apply (rule conjI)\n  apply (rule order_le_less_trans[OF ordinal_0_le])\n  apply (erule spec)\n apply (clarsimp simp add: less_oSuc_eq_le)\n apply (drule oLimit_leI)\n apply (simp add: linorder_not_less[symmetric])\ndone\n\nlemma strict_mono_limit_ordinal:\n\"strict_mono f \\<Longrightarrow> limit_ordinal (oLimit f)\"\n apply (rule limit_ordinal_oLimitI)\n apply (simp add: strict_mono_less_oLimit)\ndone\n\nlemma limit_ordinalI:\n\"\\<lbrakk>0 < z; \\<forall>x<z. oSuc x < z\\<rbrakk> \\<Longrightarrow> limit_ordinal z\"\n apply (erule contrapos_pp)\n apply (unfold limit_ordinal_def, clarsimp)\n apply (drule_tac x=y in spec, clarsimp)\ndone\n\n\nsubsubsection {* Making strict monotonic sequences *}\n\nprimrec make_mono :: \"(nat \\<Rightarrow> ordinal) \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"make_mono f 0       = 0\"\n| \"make_mono f (Suc n) = (LEAST x. f (make_mono f n) < f x)\"\n\n\n\nlemma strict_mono_f_make_mono:\n\"\\<forall>n. f n < oLimit f \\<Longrightarrow> strict_mono (\\<lambda>n. f (make_mono f n))\"\nby (rule strict_mono_natI, erule f_make_mono_less)\n\nlemma le_f_make_mono:\n\"\\<lbrakk>\\<forall>n. f n < oLimit f; m \\<le> make_mono f n\\<rbrakk> \\<Longrightarrow> f m \\<le> f (make_mono f n)\"\n apply (auto simp add: order_le_less)\n apply (case_tac n, simp_all)\n apply (drule not_less_Least)\n apply (simp add: linorder_not_less)\n apply (erule order_le_less_trans)\n apply (rule LeastI)\n apply (erule f_make_mono_less)\ndone\n\nlemma make_mono_less:\n\"\\<forall>n. f n < oLimit f \\<Longrightarrow> make_mono f n < make_mono f (Suc n)\"\n apply (frule_tac n=n in f_make_mono_less)\n apply (rule ccontr, simp only: linorder_not_less)\n apply (drule le_f_make_mono, assumption)\n apply (simp add: linorder_not_less[symmetric])\ndone\n\ndeclare make_mono.simps [simp del]\n\nlemma oLimit_make_mono_eq:\n\"\\<forall>n. f n < oLimit f \\<Longrightarrow> oLimit (\\<lambda>n. f (make_mono f n)) = oLimit f\"\n apply (rule oLimit_eqI, force)\n apply (rule_tac x=n in exI)\n apply (rule le_f_make_mono, assumption)\n apply (induct_tac n, simp)\n apply (rule Suc_leI)\n apply (erule order_le_less_trans)\n apply (erule make_mono_less)\ndone\n\n\nsubsection {* Induction principle for ordinals *}\n\nlemma oLimit_le_oStrictLimit: \"oLimit f \\<le> oStrictLimit f\"\n apply (rule oLimit_leI, clarify)\n apply (rule order_less_imp_le)\n apply (rule oStrictLimit_ub)\ndone\n\nlemma oLimit_induct:\nassumes zero: \"P 0\"\n    and suc:  \"\\<And>x. P x \\<Longrightarrow> P (oSuc x)\"\n    and lim:  \"\\<And>f. \\<lbrakk>strict_mono f; \\<forall>n. P (f n)\\<rbrakk> \\<Longrightarrow> P (oLimit f)\"\nshows \"P a\"\n apply (rule oStrictLimit_induct)\n  apply (rule zero[unfolded ordinal_zero_def])\n apply (cut_tac f=f in oLimit_le_oStrictLimit)\n apply (simp add: order_le_less, erule disjE)\n  apply (drule less_oStrictLimitD, clarify)\n  apply (subgoal_tac \"oStrictLimit f = oSuc (f n)\", simp add: suc)\n  apply (rule order_antisym)\n   apply (rule oStrictLimit_lub, clarify)\n   apply (simp add: less_oSuc_eq_le)\n   apply (erule order_trans[OF le_oLimit])\n  apply (rule oSuc_leI, rule oStrictLimit_ub)\n apply (subgoal_tac \"\\<forall>n. f n < oLimit f\")\n  apply (subgoal_tac \"P (oLimit (\\<lambda>n. f (make_mono f n)))\")\n   apply (simp add: oLimit_make_mono_eq)\n  apply (rule lim)\n   apply (erule strict_mono_f_make_mono)\n  apply simp\n apply (simp add: oStrictLimit_ub)\ndone\n\nlemma ordinal_cases:\nassumes zero: \"a = 0 \\<Longrightarrow> P\"\n    and suc:  \"\\<And>x. a = oSuc x \\<Longrightarrow> P\"\n    and lim:  \"\\<And>f. \\<lbrakk>strict_mono f; a = oLimit f\\<rbrakk> \\<Longrightarrow> P\"\nshows \"P\"\n apply (subgoal_tac \"\\<forall>x. a = x \\<longrightarrow> P\", force)\n apply (rule allI)\n apply (rule_tac a=x in oLimit_induct)\n   apply (rule impI, erule zero)\n  apply (rule impI, erule suc)\n apply (rule impI, erule lim, assumption)\ndone\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Ordinal/OrdinalInduct.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9046505453836383, "lm_q2_score": 0.8376199714402812, "lm_q1q2_score": 0.757753363987678}}
{"text": "theory Mult\n  imports Main Add\nbegin\n\nthm nat.induct\nprint_statement nat.induct\n\n(*  mult: \\<nat> \\<times> \\<nat> \\<rightarrow> \\<nat>  *)\n(*  requer \\<top>  *)\n(*  garante mult(x, y) = x \\<^emph> y  *)\n(*  mult (x, y) = 0, se y = 0  *)\n(*  mult (x, y) = x + mult (x, y − 1), se y > 0  *)\n\nprimrec mult::\"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  mult01: \"mult x 0 = 0\"|\n  mult02: \"mult x (Suc y) = add x (mult x y)\"\n\nvalue \"mult 2 2\"\nvalue \"mult 1 2\"\nvalue \"mult 2 0\"\nvalue \"mult 0 1\"\n\n(*  \\<forall>x \\<in> \\<nat>. \\<forall>y \\<in> \\<nat>: mult(x, y) = x \\<^emph> y  *)\ntheorem multT1:\"\\<forall>x. mult x y = x * y\"\nproof(induct y)\n  show \"\\<forall>x. mult x 0 = x * 0\"\n  proof (rule allI)\n    fix x0::nat\n    have \"mult x0 0 = 0\" by (simp only:mult01)\n    also have \"... = x0 * 0\" by (simp only:algebra)\n    finally show \"mult x0 0 = x0 * 0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HIP:\"\\<forall>x. mult x y0 = x * y0\"\n  show \"\\<forall>x. mult x (Suc y0) = x * (Suc y0)\"\n  proof (rule allI)\n    fix x0::nat\n    have \"mult x0 (Suc y0) = add x0 (mult x0 y0)\" by (simp only:mult02)\n    also have \"... = x0 + (mult x0 y0)\" by (simp only:addT1)\n    also have \"... = x0 + x0 * y0\" by (simp only:HIP)\n    also have \"... = x0 * (y0 + 1)\" by algebra\n    also have \"... = x0 * (Suc y0)\" by simp\n    finally show \"mult x0 (Suc y0) = x0 * (Suc y0)\" by simp\n  qed\nqed\n\n(*  \\<forall>x \\<in> \\<nat>. \\<forall>y \\<in> \\<nat>: mult(x, y) = mult(y, x)  *)\ntheorem multT2:\"\\<forall>x. mult x y = mult y x\"\nproof(induct y)\n  show \"\\<forall>x. mult x 0 = mult 0 x\"\n  proof (rule allI)\n    fix x0::nat\n    have \"mult x0 0 = 0\" by (simp only:mult01)\n    also have \"... = 0 * x0\" by (simp only:algebra)\n    also have \"... = mult 0 x0\" by (simp only:multT1)\n    finally show \"mult x0 0 = mult 0 x0\" by simp\n  qed\nnext\n  fix y0::nat\n  assume HIP:\"\\<forall>x. mult x y0 = mult y0 x\"\n  show \"\\<forall>x. mult x (Suc y0) = mult (Suc y0) x\"\n  proof (rule allI)\n    fix x0::nat\n    have \"mult x0 (Suc y0) = add x0 (mult x0 y0)\" by (simp only:mult02)\n    also have \"... = x0 + (mult x0 y0)\" by (simp only:addT1)\n    also have \"... = x0 + x0 * y0\" by (simp only:multT1)\n    also have \"... = x0 * (y0 + 1)\" by algebra\n    also have \"... = x0 * (Suc y0)\" by simp\n    also have \"... = (Suc y0) * x0\" by simp\n    also have \"... = mult (Suc y0) x0\" by (simp only:multT1)\n    finally show \"mult x0 (Suc y0) = mult (Suc y0) x0\" by simp\n  qed\nqed\n\n(*  \\<forall>x \\<in> \\<nat>: mult(1, x) = x  *)\ntheorem multT4:\"mult 1 x = x\"\nproof(induct x)\n  show \"mult 1 0 = 0\"\n  proof -\n    show \"mult 1 0 = 0\" by (simp only:mult01) \n  qed\nnext\n  fix x0::nat\n  assume HIP:\"mult 1 x0 = x0\"\n  show \"mult 1 (Suc x0) = Suc x0\"\n  proof -\n    have \"mult 1 (Suc x0) = add 1 (mult 1  x0)\" by (simp only:mult02)\n    also have \"... = add 1 x0\" by (simp only:HIP)\n    also have \"... = Suc x0\" by (simp only:addT0)\n    finally show \"mult 1 (Suc x0) = Suc x0\" by simp\n  qed\nqed\n\n(*  \\<forall>x \\<in> \\<nat>: mult(x, 1) = x  *)\ntheorem multT3:\"mult x 1 = x\"\nproof(induct x)\n  show \"mult 0 1 = 0\"\n  proof -\n    have \"mult 0 1 = 0 * 1\" by (simp only:multT1)\n    also have \"... = 0\" by arith\n    finally show \"mult 0 1 = 0\" by simp\n  qed\nnext\n  fix x0::nat\n  assume HIP:\"mult x0 1 = x0\"\n  show \"mult (Suc x0) 1 = Suc x0\"\n  proof -\n    have \"mult (Suc x0) 1 = mult 1 (Suc x0)\" by (simp only:multT2)\n    also have \"... = Suc x0\" by (simp only:multT4)\n    finally show \"mult (Suc x0) 1 = Suc x0\" by simp\n  qed\nqed\n\n(*  \\<forall>x \\<in> \\<nat>. \\<forall>y \\<in> \\<nat>. \\<forall>z \\<in> \\<nat>: mult(x, mult(y, z)) = mult(mult(x, y), z)  *)\ntheorem multT5:\"\\<forall>x. \\<forall>y. mult x (mult y z) = mult (mult x y) z\"\nproof(induction z)\n  show \"\\<forall>x. \\<forall>y. mult x (mult y 0) = mult (mult x y) 0\"\n  proof(rule allI, rule allI)\n    fix x0::nat and y0::nat\n    have \"mult x0 (mult y0 0) = mult x0 0\" by (simp only:mult01)\n    also have \"... = mult (mult x0 y0) 0\" by (simp only:mult01)\n    finally show \"mult x0 (mult y0 0) = mult (mult x0 y0) 0\" by simp\n  qed\nnext\n  fix z0::nat\n  assume HI:\"\\<forall>x y. mult x (mult y z0) = mult (mult x y) z0\"\n  show \"\\<forall>x y. mult x (mult y (Suc z0)) = mult (mult x y) (Suc z0)\"\n  proof(rule allI, rule allI)\n    fix x0::nat and y0::nat\n    have \"mult x0 (mult y0 (Suc z0)) = x0 * (mult y0 (Suc z0))\" by (simp only:multT1)\n    also have \"... = x0 * y0 * (Suc z0)\" by (simp only:multT1)\n    also have \"... = mult x0 y0 * (Suc z0)\" by (simp only:multT1)\n    also have \"... = mult (mult x0 y0) (Suc z0)\" by (simp only:multT1)\n    finally show \"mult x0 (mult y0 (Suc z0)) = mult (mult x0 y0) (Suc z0)\" by simp\n  qed\nqed", "meta": {"author": "Jean-Lucca", "repo": "PUCRS-metodos-formais-t2", "sha": "dd05f7ccffc49b58d26af2a007257f2ba18b4790", "save_path": "github-repos/isabelle/Jean-Lucca-PUCRS-metodos-formais-t2", "path": "github-repos/isabelle/Jean-Lucca-PUCRS-metodos-formais-t2/PUCRS-metodos-formais-t2-dd05f7ccffc49b58d26af2a007257f2ba18b4790/Mult.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.8376199653600372, "lm_q1q2_score": 0.7577533541806646}}
{"text": "theory BExp imports AExp begin\n\nsubsection \"Boolean Expressions\"\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\"|\n\"less n\\<^sub>1 n\\<^sub>2 = Less n\\<^sub>1 n\\<^sub>2\"\n\n\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and n\\<^sub>1 n\\<^sub>2 = And n\\<^sub>1 n\\<^sub>2\"\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply auto\ndone\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc v) = Bc(\\<not> v)\" |\n\"not b = Not b\"\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction )\napply auto\ndone\n\ntext \\<open>Now the overall optimizer:\\<close>\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply auto\n  done\n\nend\n", "meta": {"author": "oguri257", "repo": "isabelle", "sha": "master", "save_path": "github-repos/isabelle/oguri257-isabelle", "path": "github-repos/isabelle/oguri257-isabelle/isabelle-main/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505376715775, "lm_q2_score": 0.8376199613065411, "lm_q1q2_score": 0.7577533483604084}}
{"text": "theory Baby\nimports Main\n\nbegin\n\n (* fun conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n\"conj True True = True\" |\n\"conj _ _ = False\"\n\n fun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\nlemma add_02: \"add m 0 = m\"\napply(induction m)\napply(auto)\ndone \n\nlemma add_03 [simp]: \"add 0 m = m\"\n(* apply(induction m) *)\napply(auto)\ndone\n\n(* double function *)\n(* fun double :: \"nat => nat\" where \n\"double 0 = 0\" | \n\"double (Suc m) = Suc(m) + Suc(m)\"\n\nlemma double_2 [simp]: \"double m = add m m\"\napply(induction m)\napply (auto)\ndone *)\n\n\n(* we can now compute it *)\nvalue \"add 5 0\"\n\n\nthm add_02 \n\n(* datatype 'a list = Nil | Cons 'a \" 'a list\" *)\n\nfun app :: \"'a list => 'a list => 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun rev :: \"'a list => 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\n\nlemma app_Nil2: \"app xs Nil = xs\"\napply(induction xs)\napply(auto)\ndone\n\n\nlemma app_assoc [simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply(induction xs)\napply(auto)\ndone\n\nfun map :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\" where\n\"map f Nil = Nil\" |\n\"map f (Cons x xs) = Cons (f x ) (map f xs)\"\n\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n\nfun count :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"count [] _ = 0\" |\n  \"count (x#xs) x' = (if x = x' then Suc (count xs x') else count xs x')\"\n\nvalue \"count [(1::nat), 1, 1] 1\"\n\n\ntheorem \"count xs x \\<le> length xs\"\n  apply(induct xs)\n   apply auto\n  done\n\nfun sum_upto :: \"nat \\<Rightarrow> nat \" where\n\"sum_upto 0 = 0\" | \n\"sum_upto n = n + sum_upto (n - 1)\"\n\nvalue \"sum_upto 4\"\n\nlemma sum_up_to: \"sum_upto n = (n * (n+1)) div 2 \"\napply(induction n)\napply(auto)\ndone\n\nthm sum_up_to\n\n(*  tree/mirror *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \" 'a tree\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n    \"mirror Tip = Tip\" |\n    \"mirror (Node l a r ) = Node (mirror r ) a (mirror l)\"\n\nlemma \"mirror (mirror t) = t\"\napply(induction t)\napply(auto)\ndone\n\ndatatype 'a option = None | Some 'a *)\n\nfun lookup :: \"('a * 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup [] x = None\" |\n\"lookup ((a,b) # ps) x = (if a = x then Some b else lookup ps x )\"\n\n\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0 = 0\" |\n\"div2 (Suc 0) = 0\" |\n\"div2 (Suc(Suc n)) = Suc(div2 n)\"\n\nvalue \"div2 2\"\n\n\nlemma \"div2 n = n div 2\"\napply(induction n rule: div2.induct)\napply(auto)\ndone\n\n\nfun intersperse:: \"'a => 'a list => 'a list\" where\n    \"intersperse a [] = []\" | \n    \"intersperse _ [x] = [x]\" | \n    \"intersperse a (x#xs) = x#a#(intersperse a xs)\"\n(* it works too: `\"intersperse a (Cons x xs) = [x,a]@(intersperse a xs)\"` *)\n\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\napply(induction xs rule: intersperse.induct)\napply(auto)\ndone\n\n\nvalue \"intersperse 9 [1::nat,2,3,4,5]\"\n\nend", "meta": {"author": "redbeardster", "repo": "isabelle", "sha": "b4e9605249a204a9439d2bcc23cddac3c9ec07f7", "save_path": "github-repos/isabelle/redbeardster-isabelle", "path": "github-repos/isabelle/redbeardster-isabelle/isabelle-b4e9605249a204a9439d2bcc23cddac3c9ec07f7/Baby.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.8757869981319863, "lm_q1q2_score": 0.7577520111224907}}
{"text": "theory Projection\nimports Main\nbegin\n\n(* Projection of an event list onto a subset of the events *)\ndefinition projection:: \"'e list \\<Rightarrow> 'e set \\<Rightarrow> 'e list\" (infixl \"\\<upharpoonleft>\" 100)\nwhere\n\"l \\<upharpoonleft> E \\<equiv> filter (\\<lambda>x . x \\<in> E) l\"\n\n(* If projecting on Y yields the empty sequence, then projecting\n  on X \\<union> Y yields the projection on X. *)\nlemma projection_on_union: \n  \"l \\<upharpoonleft> Y = [] \\<Longrightarrow> l \\<upharpoonleft> (X \\<union> Y) = l \\<upharpoonleft> X\"\nproof (induct l)\n  case Nil show ?case by (simp add: projection_def)\nnext\n  case (Cons a b) show ?case\n  proof (cases \"a \\<in> Y\")\n    case True from Cons show \"a \\<in> Y \\<Longrightarrow> (a # b) \\<upharpoonleft> (X \\<union> Y) = (a # b) \\<upharpoonleft> X\" \n      by (simp add: projection_def)\n  next\n    case False from Cons show \"a \\<notin> Y \\<Longrightarrow> (a # b) \\<upharpoonleft> (X \\<union> Y) = (a # b) \\<upharpoonleft> X\" \n      by (simp add: projection_def)\n  qed\nqed\n\n(*projection on the empty trace yields the empty trace*)\nlemma projection_on_empty_trace: \"[] \\<upharpoonleft> X =[]\" by (simp add: projection_def)\n\n(*projection to the empty set yields the empty trace*)\nlemma projection_to_emptyset_is_empty_trace: \"l \\<upharpoonleft>{} = []\" by (simp add: projection_def)\n\n(*projection is idempotent*)\nlemma projection_idempotent: \"l \\<upharpoonleft> X= (l \\<upharpoonleft>X) \\<upharpoonleft>X\" by (simp add: projection_def) \n\n(*empty projection implies that the trace contains no events of the set the trace is projected to*)\nlemma projection_empty_implies_absence_of_events: \"l \\<upharpoonleft> X = [] \\<Longrightarrow>  X \\<inter> (set l) = {}\" \n by (metis empty_set inter_set_filter projection_def)\n\n(*subsequently projecting to two disjoint sets yields the empty trace*)\nlemma disjoint_projection: \"X \\<inter> Y = {} \\<Longrightarrow> (l \\<upharpoonleft> X) \\<upharpoonleft> Y = []\" \nproof -\n  assume X_Y_disjoint: \"X \\<inter> Y = {}\"\n  show \"(l \\<upharpoonleft> X) \\<upharpoonleft> Y = []\" unfolding projection_def \n  proof (induct l)\n    case Nil show ?case by simp\n  next\n    case (Cons x xs) show ?case\n    proof (cases \"x \\<in> X\")\n      case True\n      with X_Y_disjoint have \"x \\<notin> Y\" by auto\n      thus \"[x\\<leftarrow>[x\\<leftarrow>x # xs . x \\<in> X] . x \\<in> Y] = []\" using Cons.hyps by auto\n    next\n      case False show \"[x\\<leftarrow>[x\\<leftarrow>x # xs . x \\<in> X] . x \\<in> Y] = []\" using Cons.hyps False by auto\n    qed\n  qed  \nqed      \n\n(* auxiliary lemmas for projection *)\nlemma projection_concatenation_commute:\n  \"(l1 @ l2) \\<upharpoonleft> X = (l1 \\<upharpoonleft> X) @ (l2 \\<upharpoonleft> X)\"\n  by (unfold projection_def, auto)\n\n(* Lists that are equal under projection on a set will remain \nequal under projection on a subset. *)\nlemma projection_subset_eq_from_superset_eq: \n\"((xs \\<upharpoonleft> (X \\<union> Y)) = (ys \\<upharpoonleft> (X \\<union> Y))) \\<Longrightarrow> ((xs \\<upharpoonleft> X) = (ys \\<upharpoonleft> X))\"\n(is \"(?L1 = ?L2) \\<Longrightarrow> (?L3 = ?L4)\")\nproof -\n  assume prem: \"?L1 = ?L2\"  \n  have \"?L1 \\<upharpoonleft> X = ?L3 \\<and> ?L2 \\<upharpoonleft> X = ?L4\"\n  proof -\n    have \"\\<And> a. ((a \\<in> X \\<or> a \\<in> Y) \\<and> a \\<in> X) = (a \\<in> X)\" \n      by auto\n    thus ?thesis\n      by (simp add: projection_def)\n  qed   \n  with prem show ?thesis\n    by auto\nqed\n\n(* All elements of a list l are in a set X if and only if\n the projection of l onto X yields l. *)\nlemma list_subset_iff_projection_neutral: \"(set l \\<subseteq> X) = ((l \\<upharpoonleft> X) = l)\"\n(is \"?A = ?B\")\nproof -\n  have \"?A \\<Longrightarrow> ?B\"\n    proof -\n      assume \"?A\"\n      hence \"\\<And>x. x \\<in> (set l) \\<Longrightarrow> x \\<in> X\"\n        by auto\n      thus ?thesis\n        by (simp add: projection_def)\n    qed\n  moreover \n  have \"?B \\<Longrightarrow> ?A\"\n    proof -\n      assume \"?B\"\n      hence \"(set (l \\<upharpoonleft> X)) = set l\"\n        by (simp add: projection_def)\n      thus ?thesis\n        by (simp add: projection_def, auto)\n    qed\n  ultimately show ?thesis ..\nqed\n\n(* If the projection of \\<tau> onto a set X is not the empty trace, then \nthere is x \\<in> X that is the last occurrence of all elements of X in \\<tau>. \n\\<tau> can then be split around x.\n\nExpressing non-emptiness in terms of list length is quite useful\nfor inductive proofs. *)\nlemma projection_split_last: \"Suc n = length (\\<tau> \\<upharpoonleft> X) \\<Longrightarrow> \n\\<exists> \\<beta> x \\<alpha>. (x \\<in> X \\<and> \\<tau> = \\<beta> @ [x] @ \\<alpha> \\<and> \\<alpha> \\<upharpoonleft> X = [] \\<and> n = length ((\\<beta> @ \\<alpha>) \\<upharpoonleft> X))\"\nproof -\n  assume Suc_n_is_len_\\<tau>X: \"Suc n = length (\\<tau> \\<upharpoonleft> X)\"\n\n  let ?L = \"\\<tau> \\<upharpoonleft> X\"\n  let ?RL = \"filter (\\<lambda>x . x \\<in> X) (rev \\<tau>)\"\n\n  have \"Suc n = length ?RL\"\n  proof -\n    have \"rev ?L = ?RL\"\n      by (simp add: projection_def, rule rev_filter)\n    hence \"rev (rev ?L) = rev ?RL\" ..\n    hence \"?L = rev ?RL\"\n      by auto\n    with Suc_n_is_len_\\<tau>X show ?thesis\n      by auto\n  qed\n  with Suc_length_conv[of n ?RL] obtain x xs\n    where \"?RL = x # xs\"\n    by auto\n  hence \"x # xs = ?RL\" \n    by auto\n  \n  from Cons_eq_filterD[OF this] obtain rev\\<alpha> rev\\<beta>\n    where \"(rev \\<tau>) = rev\\<alpha> @ x # rev\\<beta>\"\n    and rev\\<alpha>_no_x: \"\\<forall>a \\<in> set rev\\<alpha>. a \\<notin> X\"\n    and x_in_X: \"x \\<in> X\"\n    by auto\n  hence \"rev (rev \\<tau>) = rev (rev\\<alpha> @ x # rev\\<beta>)\"\n    by auto\n  hence \"\\<tau> = (rev rev\\<beta>) @ [x] @ (rev rev\\<alpha>)\"\n    by auto\n  then obtain \\<beta> \\<alpha>\n    where \\<tau>_is_\\<beta>x\\<alpha>: \"\\<tau> = \\<beta> @ [x] @ \\<alpha>\"\n    and \\<alpha>_is_revrev\\<alpha>: \"\\<alpha> = (rev rev\\<alpha>)\"\n    and \\<beta>_is_revrev\\<beta>: \"\\<beta> = (rev rev\\<beta>)\"\n    by auto\n  hence \\<alpha>_no_x: \"\\<alpha> \\<upharpoonleft> X = []\"\n  proof -\n    from \\<alpha>_is_revrev\\<alpha> rev\\<alpha>_no_x have \"\\<forall>a \\<in> set \\<alpha>. a \\<notin> X\"\n      by auto\n    thus ?thesis \n      by (simp add: projection_def)\n  qed\n\n  have \"n = length ((\\<beta> @ \\<alpha>) \\<upharpoonleft> X)\"\n  proof -\n    from \\<alpha>_no_x have \\<alpha>X_zero_len: \"length (\\<alpha> \\<upharpoonleft> X) = 0\"\n      by auto\n\n    from x_in_X have xX_one_len: \"length ([x] \\<upharpoonleft> X) = 1\"\n      by (simp add: projection_def)\n\n    from \\<tau>_is_\\<beta>x\\<alpha> have \"length ?L = length (\\<beta> \\<upharpoonleft> X) + length ([x] \\<upharpoonleft> X) + length (\\<alpha> \\<upharpoonleft> X)\"\n      by (simp add: projection_def)            \n    with \\<alpha>X_zero_len have \"length ?L = length (\\<beta> \\<upharpoonleft> X) + length ([x] \\<upharpoonleft> X)\"\n      by auto\n    with xX_one_len Suc_n_is_len_\\<tau>X have \"n = length (\\<beta> \\<upharpoonleft> X)\"\n      by auto\n    with \\<alpha>X_zero_len show ?thesis\n      by (simp add: projection_def)\n  qed\n  with x_in_X \\<tau>_is_\\<beta>x\\<alpha> \\<alpha>_no_x show ?thesis\n    by auto\nqed\n\nlemma projection_rev_commute:\n  \"rev (l \\<upharpoonleft> X) = (rev l) \\<upharpoonleft> X\"\n  by (induct l, simp add: projection_def, simp add: projection_def)\n\n(* Same as the previous lemma except that we split around the FIRST\n    occurrence.\n\n    Note that we do not express non-emptiness via the length function\n    simply because there is no need for it in the theories relying on\n    this lemma. *)\n\n\n  from rev\\<tau>_is_\\<beta>'x'\\<alpha>' have \"rev (rev \\<tau>) = rev (\\<beta>' @ [x'] @ \\<alpha>')\" ..\n  hence \\<tau>_is_rev\\<alpha>'_x'_rev\\<beta>':\"\\<tau> = rev \\<alpha>' @ [x'] @ rev \\<beta>'\"\n    by auto\n  moreover\n  from \\<alpha>'X_empty have rev\\<alpha>'X_empty: \"rev \\<alpha>' \\<upharpoonleft> X = []\"\n    by (metis projection_rev_commute rev_is_Nil_conv)\n  moreover\n  note x'_in_X\n  ultimately have \"(\\<tau> \\<upharpoonleft> X) = x' # ((rev \\<beta>') \\<upharpoonleft> X)\"\n    by (simp only: projection_concatenation_commute projection_def, auto)\n  with \\<tau>X_is_x_xs have \"x = x'\"\n    by auto\n  with \\<tau>_is_rev\\<alpha>'_x'_rev\\<beta>' have \\<tau>_is_rev\\<alpha>'_x_rev\\<beta>': \"\\<tau> = rev \\<alpha>' @ [x] @ rev \\<beta>'\"\n    by auto\n  with rev\\<alpha>'X_empty show ?thesis\n    by auto\nqed\n\n(* this lemma extends the previous lemma by also concluding that the suffix of the splitted trace\n   projected is equal to the projection of the initial trace without the first element *)\nlemma projection_split_first_with_suffix: \n  \"\\<lbrakk> (\\<tau> \\<upharpoonleft> X) = x # xs \\<rbrakk> \\<Longrightarrow> \\<exists> \\<alpha> \\<beta>. (\\<tau> = \\<alpha> @ [x] @ \\<beta> \\<and> \\<alpha> \\<upharpoonleft> X = [] \\<and> \\<beta> \\<upharpoonleft> X = xs)\" \nproof -\n  assume tau_proj_X: \"(\\<tau> \\<upharpoonleft> X) = x # xs\"\n  show ?thesis\n  proof - \n    from   tau_proj_X have x_in_X: \"x \\<in> X\"\n      by (metis IntE inter_set_filter list.set_intros(1) projection_def)\n    from  tau_proj_X have  \"\\<exists> \\<alpha> \\<beta>. \\<tau> = \\<alpha> @ [x] @ \\<beta> \\<and> \\<alpha> \\<upharpoonleft> X = []\"\n      using projection_split_first by auto\n    then obtain \\<alpha> \\<beta> where tau_split: \"\\<tau> = \\<alpha> @ [x] @ \\<beta>\"\n                      and X_empty_prefix:\"\\<alpha> \\<upharpoonleft> X = []\"\n      by auto\n    from tau_split tau_proj_X  have  \"(\\<alpha> @ [x] @ \\<beta>) \\<upharpoonleft> X =x # xs\"\n      by auto\n    with  X_empty_prefix have  \"([x] @ \\<beta>) \\<upharpoonleft> X =x # xs\"\n      by (simp add: projection_concatenation_commute)   \n    hence \"(x # \\<beta>) \\<upharpoonleft> X =x # xs\"\n      by auto\n    with  x_in_X have \"\\<beta> \\<upharpoonleft> X = xs\"\n      unfolding projection_def by simp\n    with  tau_split X_empty_prefix show ?thesis\n      by auto\n  qed   \nqed\n\n\n\n\nlemma projection_split_arbitrary_element: \n  \"\\<lbrakk>\\<tau> \\<upharpoonleft> X = (\\<alpha> @ [x] @ \\<beta>) \\<upharpoonleft> X; x \\<in> X \\<rbrakk> \n      \\<Longrightarrow> \\<exists> \\<alpha>' \\<beta>'. (\\<tau> = \\<alpha>' @ [x] @ \\<beta>' \\<and> \\<alpha>' \\<upharpoonleft> X = \\<alpha> \\<upharpoonleft> X \\<and> \\<beta>' \\<upharpoonleft> X = \\<beta> \\<upharpoonleft> X)\" \nproof -\n  assume \"\\<tau> \\<upharpoonleft> X = (\\<alpha> @ [x] @ \\<beta>) \\<upharpoonleft> X\"\n  and  \" x \\<in> X\"\n  { \n    fix n\n    have \"\\<lbrakk>\\<tau> \\<upharpoonleft> X = (\\<alpha> @ [x] @ \\<beta>) \\<upharpoonleft> X; x \\<in> X; n = length(\\<alpha>\\<upharpoonleft>X) \\<rbrakk>\n          \\<Longrightarrow> \\<exists> \\<alpha>' \\<beta>'. (\\<tau> = \\<alpha>' @ [x] @ \\<beta>' \\<and> \\<alpha>' \\<upharpoonleft> X = \\<alpha> \\<upharpoonleft> X \\<and> \\<beta>' \\<upharpoonleft> X = \\<beta> \\<upharpoonleft> X)\"\n    proof (induct n arbitrary: \\<tau> \\<alpha> )\n      case 0\n      hence \"\\<alpha>\\<upharpoonleft>X = []\"\n        unfolding projection_def by simp\n      with \"0.prems\"(1) \"0.prems\"(2) have \"\\<tau>\\<upharpoonleft>X = x # \\<beta>\\<upharpoonleft>X\"\n        unfolding projection_def by simp\n      with \\<open>\\<alpha>\\<upharpoonleft>X = []\\<close> show ?case\n        using projection_split_first_with_suffix by fastforce\n    next\n      case (Suc n)\n      from \"Suc.prems\"(1) have \"\\<tau>\\<upharpoonleft>X=\\<alpha>\\<upharpoonleft>X @ ([x] @ \\<beta>) \\<upharpoonleft>X\"\n        using projection_concatenation_commute by auto\n      from \"Suc.prems\"(3) obtain x' xs' where \"\\<alpha> \\<upharpoonleft>X= x' #xs'\"\n                                            and \"x' \\<in> X\" \n        by (metis filter_eq_ConsD length_Suc_conv projection_def)\n      then obtain a\\<^sub>1 a\\<^sub>2 where \"\\<alpha> = a\\<^sub>1 @ [x'] @ a\\<^sub>2\" \n                         and \"a\\<^sub>1\\<upharpoonleft>X = []\"\n                         and \"a\\<^sub>2\\<upharpoonleft>X = xs'\" \n        using projection_split_first_with_suffix by metis\n      with \\<open>x' \\<in> X\\<close> \"Suc.prems\"(1) have \"\\<tau>\\<upharpoonleft>X= x' #  (a\\<^sub>2 @ [x] @ \\<beta>) \\<upharpoonleft>X\" \n        unfolding projection_def by simp \n      then obtain t\\<^sub>1 t\\<^sub>2 where \"\\<tau>= t\\<^sub>1 @ [x'] @ t\\<^sub>2\"\n                         and \"t\\<^sub>1\\<upharpoonleft>X = []\"\n                         and \"t\\<^sub>2\\<upharpoonleft>X = (a\\<^sub>2 @ [x] @ \\<beta>) \\<upharpoonleft>X\"\n        using projection_split_first_with_suffix by metis\n      from Suc.prems(3) \\<open>\\<alpha> \\<upharpoonleft>X= x' # xs'\\<close> \\<open>\\<alpha> = a\\<^sub>1 @ [x'] @ a\\<^sub>2\\<close> \\<open>a\\<^sub>1\\<upharpoonleft>X = []\\<close> \\<open>a\\<^sub>2\\<upharpoonleft>X = xs'\\<close>\n      have \"n=length(a\\<^sub>2\\<upharpoonleft>X)\"\n        by auto               \n      with \"Suc.hyps\"(1) \"Suc.prems\"(2) \\<open>t\\<^sub>2\\<upharpoonleft>X = (a\\<^sub>2 @ [x] @ \\<beta>) \\<upharpoonleft>X\\<close> \n        obtain t\\<^sub>2' t\\<^sub>3' where \"t\\<^sub>2=t\\<^sub>2' @ [x] @ t\\<^sub>3'\"\n                         and \"t\\<^sub>2'\\<upharpoonleft>X = a\\<^sub>2\\<upharpoonleft>X\"\n                         and \"t\\<^sub>3'\\<upharpoonleft>X = \\<beta>\\<upharpoonleft>X\"\n          using projection_concatenation_commute by blast\n      \n      let ?\\<alpha>'=\"t\\<^sub>1 @ [x'] @ t\\<^sub>2'\" and ?\\<beta>'=\"t\\<^sub>3'\"\n      from \\<open>\\<tau>= t\\<^sub>1 @ [x'] @ t\\<^sub>2\\<close> \\<open>t\\<^sub>2=t\\<^sub>2' @ [x] @ t\\<^sub>3'\\<close> have \"\\<tau>=?\\<alpha>'@[x]@?\\<beta>'\"\n        by auto\n      moreover\n      from  \\<open>\\<alpha> \\<upharpoonleft>X= x' # xs'\\<close>  \\<open>t\\<^sub>1\\<upharpoonleft>X = []\\<close> \\<open>x' \\<in> X\\<close> \\<open>t\\<^sub>2'\\<upharpoonleft>X = a\\<^sub>2\\<upharpoonleft>X\\<close> \\<open>a\\<^sub>2\\<upharpoonleft>X = xs'\\<close>\n      have \"?\\<alpha>'\\<upharpoonleft>X = \\<alpha>\\<upharpoonleft>X\"\n        using projection_concatenation_commute unfolding projection_def by simp \n      ultimately\n      show ?case using \\<open>t\\<^sub>3'\\<upharpoonleft>X = \\<beta>\\<upharpoonleft>X\\<close>\n        by blast\n    qed    \n  }\n  with \\<open>\\<tau> \\<upharpoonleft> X = (\\<alpha> @ [x] @ \\<beta>) \\<upharpoonleft> X\\<close> \\<open> x \\<in> X\\<close> show ?thesis\n    by simp\nqed\n        \n(* If the projection of a list l onto a set X is empty, it\n    will remain empty when projecting further. *)\nlemma projection_on_intersection: \"l \\<upharpoonleft> X = [] \\<Longrightarrow> l \\<upharpoonleft> (X \\<inter> Y) = []\"\n(is \"?L1 = [] \\<Longrightarrow> ?L2 = []\")\nproof -\n  assume \"?L1 = []\"\n  hence \"set ?L1 = {}\" \n    by simp\n  moreover\n  have \"set ?L2 \\<subseteq> set ?L1\"\n    by (simp add: projection_def, auto)\n  ultimately have \"set ?L2 = {}\"\n    by auto\n  thus ?thesis\n    by auto\nqed\n\n(* The previous lemma expressed with subsets. *)\nlemma projection_on_subset: \"\\<lbrakk> Y \\<subseteq> X; l \\<upharpoonleft> X = [] \\<rbrakk> \\<Longrightarrow> l \\<upharpoonleft> Y = []\"\nproof -\n  assume subset: \"Y \\<subseteq> X\"\n  assume proj_empty: \"l \\<upharpoonleft> X = []\"\n  hence \"l \\<upharpoonleft> (X \\<inter> Y) = []\"\n    by (rule projection_on_intersection)\n  moreover\n  from subset have \"X \\<inter> Y = Y\"\n    by auto\n  ultimately show ?thesis\n    by auto\nqed\n\n(* Another variant that is used in proofs of BSP compositionality theorems. *)\nlemma projection_on_subset2: \"\\<lbrakk> set l \\<subseteq> L; l \\<upharpoonleft> X' = []; X \\<inter> L \\<subseteq> X' \\<rbrakk> \\<Longrightarrow> l \\<upharpoonleft> X = []\"\nproof -\n  assume setl_subset_L: \"set l \\<subseteq> L\"\n  assume l_no_X': \"l \\<upharpoonleft> X' = []\"\n  assume X_inter_L_subset_X': \"X \\<inter> L \\<subseteq> X'\"\n\n  from X_inter_L_subset_X' l_no_X' have \"l \\<upharpoonleft> (X \\<inter> L) = []\"\n    by (rule projection_on_subset)\n  moreover\n  have \"l \\<upharpoonleft> (X \\<inter> L) = (l \\<upharpoonleft> L) \\<upharpoonleft> X\"\n    by (simp add: Int_commute projection_def)\n  moreover\n  note setl_subset_L\n  ultimately show ?thesis\n    by (simp add: list_subset_iff_projection_neutral)\nqed  \n\n(*If the projection of two lists l1 and l2  onto a set Y is equal then its also equal for all X \\<subseteq> Y*)\nlemma non_empty_projection_on_subset: \"X \\<subseteq> Y \\<and> l\\<^sub>1 \\<upharpoonleft> Y = l\\<^sub>2 \\<upharpoonleft> Y \\<Longrightarrow>  l\\<^sub>1 \\<upharpoonleft> X = l\\<^sub>2 \\<upharpoonleft> X\" \n  by (metis projection_subset_eq_from_superset_eq subset_Un_eq)\n\n(* Intersecting a projection set with a list's elements does not change the result\n    of the projection. *)\nlemma projection_intersection_neutral: \"(set l \\<subseteq> X) \\<Longrightarrow> (l \\<upharpoonleft> (X \\<inter> Y) = l \\<upharpoonleft> Y)\"\nproof -\n  assume \"set l \\<subseteq> X\"\n  hence \"(l \\<upharpoonleft> X) = l\"\n    by (simp add: list_subset_iff_projection_neutral)\n  hence \"(l \\<upharpoonleft> X) \\<upharpoonleft> Y = l \\<upharpoonleft> Y\"\n    by simp\n  moreover\n  have \"(l \\<upharpoonleft> X) \\<upharpoonleft> Y = l \\<upharpoonleft> (X \\<inter> Y)\"\n    by (simp add: projection_def)\n  ultimately show ?thesis\n    by simp\nqed\n\nlemma projection_commute:\n  \"(l \\<upharpoonleft> X) \\<upharpoonleft> Y = (l \\<upharpoonleft> Y) \\<upharpoonleft> X\"\n  by (simp add: projection_def conj_commute)\n\n\nlemma projection_subset_elim: \"Y \\<subseteq> X \\<Longrightarrow> (l \\<upharpoonleft> X) \\<upharpoonleft> Y = l \\<upharpoonleft> Y\"\nby (simp only: projection_def, metis Diff_subset list_subset_iff_projection_neutral\n    minus_coset_filter order_trans projection_commute projection_def)\n\n\nlemma projection_sequence: \"(xs \\<upharpoonleft> X) \\<upharpoonleft> Y = (xs \\<upharpoonleft> (X \\<inter> Y))\"\nby (metis Int_absorb inf_sup_ord(1) list_subset_iff_projection_neutral\n    projection_intersection_neutral projection_subset_elim)\n\n\n(* This function yields a possible interleaving for given \n  traces t1 and t2.\n  The set A (B) shall denote the the set of events for t1 (t2).\n  Non-synchronization events in trace t1 are prioritized. *)\nfun merge :: \"'e set \\<Rightarrow> 'e set \\<Rightarrow> 'e list \\<Rightarrow> 'e list \\<Rightarrow> 'e list\"\nwhere\n\"merge A B [] t2 = t2\" |\n\"merge A B t1 [] = t1\" |\n\"merge A B (e1 # t1') (e2 # t2') = (if e1 = e2 then \n                                          e1 # (merge A B t1' t2')\n                                        else (if e1 \\<in> (A \\<inter> B) then\n                                               e2 # (merge A B (e1 # t1') t2')\n                                             else e1 # (merge A B t1' (e2 # t2'))))\"\n\n(* If two traces can be interleaved, then merge yields such an interleaving  *)\nlemma merge_property: \"\\<lbrakk>set t1 \\<subseteq> A; set t2 \\<subseteq> B; t1 \\<upharpoonleft> B = t2 \\<upharpoonleft> A \\<rbrakk> \n  \\<Longrightarrow> let t = (merge A B t1 t2) in (t \\<upharpoonleft> A = t1 \\<and> t \\<upharpoonleft> B = t2 \\<and> set t \\<subseteq> ((set t1) \\<union> (set t2)))\"\nunfolding Let_def\nproof (induct A B t1 t2 rule: merge.induct)\n  case (1 A B t2) thus ?case\n    by (metis Un_empty_left empty_subsetI list_subset_iff_projection_neutral \n      merge.simps(1) set_empty subset_iff_psubset_eq)\nnext\n  case (2 A B t1) thus ?case\n    by (metis Un_empty_right empty_subsetI list_subset_iff_projection_neutral \n      merge.simps(2) set_empty subset_refl)\nnext\n  case (3 A B e1 t1' e2 t2') thus ?case\n  proof (cases)\n    assume e1_is_e2: \"e1 = e2\"\n    \n    note e1_is_e2 \n    moreover\n    from 3(4) have \"set t1' \\<subseteq> A\"\n      by auto\n    moreover\n    from 3(5) have \"set t2' \\<subseteq> B\"\n      by auto\n    moreover\n    from e1_is_e2 3(4-6) have \"t1' \\<upharpoonleft> B = t2' \\<upharpoonleft> A\"\n      by (simp add: projection_def)\n    moreover\n    note 3(1)\n    ultimately have ind1: \"merge A B t1' t2' \\<upharpoonleft> A = t1'\"\n      and ind2: \"merge A B t1' t2' \\<upharpoonleft> B = t2'\"\n      and ind3: \"set (merge A B t1' t2') \\<subseteq> (set t1') \\<union> (set t2')\"\n      by auto\n    \n    from e1_is_e2 have merge_eq: \n      \"merge A B (e1 # t1') (e2 # t2') = e1 # (merge A B t1' t2')\"\n      by auto\n\n    from 3(4) ind1 have goal1: \n      \"merge A B (e1 # t1') (e2 # t2') \\<upharpoonleft> A = e1 # t1'\"\n      by (simp only: merge_eq projection_def, auto)\n    moreover\n    from e1_is_e2 3(5) ind2 have goal2: \n      \"merge A B (e1 # t1') (e2 # t2') \\<upharpoonleft> B = e2 # t2'\"\n      by (simp only: merge_eq projection_def, auto)\n    moreover\n    from ind3 have goal3: \n      \"set (merge A B (e1 # t1') (e2 # t2')) \\<subseteq> set (e1 # t1') \\<union> set (e2 # t2')\"\n      by (simp only: merge_eq, auto)\n    ultimately show ?thesis\n      by auto (* case (3 e1 t1' e2 t2') for e1 = e2 *)\n  next\n    assume e1_isnot_e2: \"e1 \\<noteq> e2\"\n    show ?thesis\n    proof (cases)\n      assume e1_in_A_inter_B: \"e1 \\<in> A \\<inter> B\"\n      \n      from 3(6) e1_isnot_e2 e1_in_A_inter_B have e2_notin_A: \"e2 \\<notin> A\"\n        by (simp add: projection_def, auto)\n      \n      note e1_isnot_e2 e1_in_A_inter_B 3(4)\n      moreover\n      from 3(5) have \"set t2' \\<subseteq> B\"\n        by auto\n      moreover\n      from 3(6) e1_isnot_e2 e1_in_A_inter_B have \"(e1 # t1') \\<upharpoonleft> B = t2' \\<upharpoonleft> A\"\n        by (simp add: projection_def, auto)\n      moreover\n      note 3(2)\n      ultimately have ind1: \"merge A B (e1 # t1') t2' \\<upharpoonleft> A = (e1 # t1')\"\n        and ind2: \"merge A B (e1 # t1') t2' \\<upharpoonleft> B = t2'\"\n        and ind3: \"set (merge A B (e1 # t1') t2') \\<subseteq> set (e1 # t1') \\<union> set t2'\"\n        by auto\n      \n      from e1_isnot_e2 e1_in_A_inter_B \n      have merge_eq: \n        \"merge A B (e1 # t1') (e2 # t2') = e2 # (merge A B (e1 # t1') t2')\"\n        by auto\n \n      from e1_isnot_e2 ind1 e2_notin_A have goal1: \n        \"merge A B (e1 # t1') (e2 # t2') \\<upharpoonleft> A = e1 # t1'\"\n        by (simp only: merge_eq projection_def, auto)\n      moreover\n      from 3(5) ind2 have goal2: \"merge A B (e1 # t1') (e2 # t2') \\<upharpoonleft> B = e2 # t2'\"\n        by (simp only: merge_eq projection_def, auto)\n      moreover\n      from 3(5) ind3 have goal3: \n        \"set (merge A B (e1 # t1') (e2 # t2')) \\<subseteq> set (e1 # t1') \\<union> set (e2 # t2')\"\n        by (simp only: merge_eq, auto)\n      ultimately show ?thesis\n        by auto (* case (3 e1 t1' e2 t2') for e1 \\<noteq> e2 e1 \\<in> A \\<inter> B *)\n    next\n      assume e1_notin_A_inter_B: \"e1 \\<notin> A \\<inter> B\"\n      \n      from 3(4) e1_notin_A_inter_B have e1_notin_B: \"e1 \\<notin> B\"\n        by auto\n      \n      note e1_isnot_e2 e1_notin_A_inter_B\n      moreover\n      from 3(4) have \"set t1' \\<subseteq> A\"\n        by auto\n      moreover\n      note 3(5)\n      moreover\n      from 3(6) e1_notin_B have \"t1' \\<upharpoonleft> B = (e2 # t2') \\<upharpoonleft> A\"\n        by (simp add: projection_def)\n      moreover\n      note 3(3)\n      ultimately have ind1: \"merge A B t1' (e2 # t2') \\<upharpoonleft> A = t1'\"\n        and ind2: \"merge A B t1' (e2 # t2') \\<upharpoonleft> B = (e2 # t2')\"\n        and ind3: \"set (merge A B t1' (e2 # t2')) \\<subseteq> set t1' \\<union> set (e2 # t2')\"\n        by auto\n      \n      from e1_isnot_e2 e1_notin_A_inter_B \n      have merge_eq: \"merge A B (e1 # t1') (e2 # t2') = e1 # (merge A B t1' (e2 # t2'))\"\n        by auto\n      \n      from 3(4) ind1 have goal1: \"merge A B (e1 # t1') (e2 # t2') \\<upharpoonleft> A = e1 # t1'\"\n        by (simp only: merge_eq projection_def, auto)\n      moreover\n      from ind2 e1_notin_B have goal2: \n        \"merge A B (e1 # t1') (e2 # t2') \\<upharpoonleft> B = e2 # t2'\"\n        by (simp only: merge_eq projection_def, auto)\n      moreover\n      from 3(4) ind3 have goal3: \n        \"set (merge A B (e1 # t1') (e2 # t2')) \\<subseteq> set (e1 # t1') \\<union> set (e2 # t2')\"\n        by (simp only: merge_eq, auto)\n      ultimately show ?thesis\n        by auto (* case (3 e1 t1' e2 t2') for e1 \\<noteq> e2 e1 \\<notin> A \\<inter> B *)\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Modular_Assembly_Kit_Security/Basics/Projection.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.8652240686758841, "lm_q1q2_score": 0.7577519898171962}}
{"text": "theory de_morgan imports Main begin \n\ntext {*\n  Proving De Morgan's Laws in zeroth and first order logic\n*}\n\nlemma \"(\\<not>(P\\<or>Q)) = (\\<not>P\\<and>\\<not>Q)\" \n  apply (rule iffI)\n   apply(rule conjI)\n    apply(rule classical)\n    apply(erule notE)\n    apply(rule disjI1)\n    apply(rule classical)\n    apply(erule notE)\n    apply assumption\n   apply(rule classical)\n   apply(erule notE)\n   apply(rule disjI2)\n   apply(rule classical)\n   apply(erule notE)\n   apply assumption\n  apply(erule conjE)\n  apply (rule notI)\n  apply(erule notE)\n  apply(rule classical)\n  apply(erule notE)\n  apply(erule disjE)\n   apply(erule notE)\n   apply assumption\n  apply assumption\n  done\n\nlemma \"(\\<not>(P\\<and>Q)) = (\\<not>P\\<or>\\<not>Q)\" \n    apply (rule iffI)\n   apply (rule classical)\n   apply (erule notE)\n   apply (rule conjI)\n    apply (rule classical)\n    apply (erule notE)\n    apply (rule disjI1)\n    apply assumption\n   apply (rule classical)\n   apply (erule notE)\n  apply (rule disjI2)\n  apply assumption\n\n  apply (rule notI)\n  apply (erule conjE)\n  apply (erule disjE)\n  apply (erule notE,  assumption)+\n  done\nlemma \"(\\<not> (\\<forall> x. P x)) = (\\<exists> x. \\<not> P x)\"\n  apply(rule iffI)\n   apply(rule classical)\n   apply(erule notE)\n   apply(rule allI)\n   apply(rule classical)\n   apply(erule notE)\n  apply(rule exI)\n   apply assumption\n\n  apply(erule exE)\n  apply(rule notI)\n  apply(erule allE)\n  apply(erule notE)\n  apply assumption\n  done\nlemma \"(\\<not> (\\<exists> x. P x)) = (\\<forall> x. \\<not> P x)\"\n  apply(rule iffI)\n   apply(rule allI)\n   apply(rule classical)\n   apply (erule notE)\n   apply(rule exI)\n   apply(rule classical)\n   apply(erule notE)\n   apply assumption\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule allE)\n  apply (erule notE)\n  apply assumption\n  done\n  \n \n  \n  \n\n\n", "meta": {"author": "hei411", "repo": "Isabelle", "sha": "9126e84b3e39af28336f25e3b7563a01f70625fa", "save_path": "github-repos/isabelle/hei411-Isabelle", "path": "github-repos/isabelle/hei411-Isabelle/Isabelle-9126e84b3e39af28336f25e3b7563a01f70625fa/Fun_attempts/de_morgan.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294403979493139, "lm_q2_score": 0.8152324938410784, "lm_q1q2_score": 0.7577100134968635}}
{"text": "(*  Title:      HOL/Examples/Ackermann.thy\n    Author:     Larry Paulson\n*)\n\nsection \\<open>A Tail-Recursive, Stack-Based Ackermann's Function\\<close>\n\ntheory Ackermann imports MainRLT\n\nbegin\n\ntext\\<open>This theory investigates a stack-based implementation of Ackermann's function.\nLet's recall the traditional definition,\nas modified by R{\\'o}zsa P\\'eter and Raphael Robinson.\\<close>\n\nfun ack :: \"[nat,nat] \\<Rightarrow> nat\" where\n  \"ack 0 n             = Suc n\"\n| \"ack (Suc m) 0       = ack m 1\"\n| \"ack (Suc m) (Suc n) = ack m (ack (Suc m) n)\"\n\ntext\\<open>Here is the stack-based version, which uses lists.\\<close>\n\nfunction (domintros) ackloop :: \"nat list \\<Rightarrow> nat\" where\n  \"ackloop (n # 0 # l)         = ackloop (Suc n # l)\"\n| \"ackloop (0 # Suc m # l)     = ackloop (1 # m # l)\"\n| \"ackloop (Suc n # Suc m # l) = ackloop (n # Suc m # m # l)\"\n| \"ackloop [m] = m\"\n| \"ackloop [] =  0\"\n  by pat_completeness auto\n\ntext\\<open>\nThe key task is to prove termination. In the first recursive call, the head of the list gets bigger\nwhile the list gets shorter, suggesting that the length of the list should be the primary\ntermination criterion. But in the third recursive call, the list gets longer. The idea of trying\na multiset-based termination argument is frustrated by the second recursive call when m = 0:\nthe list elements are simply permuted.\n\nFortunately, the function definition package allows us to define a function and only later identify its domain of termination.\nInstead, it makes all the recursion equations conditional on satisfying\nthe function's domain predicate. Here we shall eventually be able\nto show that the predicate is always satisfied.\\<close>\n\ntext\\<open>@{thm [display] ackloop.domintros[no_vars]}\\<close>\ndeclare ackloop.domintros [simp]\n\ntext \\<open>Termination is trivial if the length of the list is less then two.\nThe following lemma is the key to proving termination for longer lists.\\<close>\nlemma \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\nproof (induction m arbitrary: n l)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (Suc m)\n  show ?case\n    using Suc.prems\n    by (induction n arbitrary: l) (simp_all add: Suc)\nqed\n\ntext \\<open>The proof above (which actually is unused) can be expressed concisely as follows.\\<close>\nlemma ackloop_dom_longer:\n  \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\nlemma \"ackloop_dom (ack m n # l) \\<Longrightarrow> ackloop_dom (n # m # l)\"\n  by (induction m n arbitrary: l rule: ack.induct) auto\n\ntext\\<open>This function codifies what @{term ackloop} is designed to do.\nProving the two functions equivalent also shows that @{term ackloop} can be used\nto compute Ackermann's function.\\<close>\nfun acklist :: \"nat list \\<Rightarrow> nat\" where\n  \"acklist (n#m#l) = acklist (ack m n # l)\"\n| \"acklist [m] = m\"\n| \"acklist [] =  0\"\n\ntext\\<open>The induction rule for @{term acklist} is @{thm [display] acklist.induct[no_vars]}.\\<close>\n\nlemma ackloop_dom: \"ackloop_dom l\"\n  by (induction l rule: acklist.induct) (auto simp: ackloop_dom_longer)\n\ntermination ackloop\n  by (simp add: ackloop_dom)\n\ntext\\<open>This result is trivial even by inspection of the function definitions\n(which faithfully follow the definition of Ackermann's function).\nAll that we needed was termination.\\<close>\nlemma ackloop_acklist: \"ackloop l = acklist l\"\n  by (induction l rule: ackloop.induct) auto\n\ntheorem ack: \"ack m n = ackloop [n,m]\"\n  by (simp add: ackloop_acklist)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Examples/Ackermann.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888614, "lm_q2_score": 0.8774767922879693, "lm_q1q2_score": 0.7576061034925403}}
{"text": "(*  Title:      HOL/Library/Sublist.thy\n    Author:     Tobias Nipkow and Markus Wenzel, TU Muenchen\n    Author:     Christian Sternagel, JAIST\n*)\n\nsection {* List prefixes, suffixes, and homeomorphic embedding *}\n\ntheory Sublist\nimports Main\nbegin\n\nsubsection {* Prefix order on lists *}\n\ndefinition prefixeq :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"prefixeq xs ys \\<longleftrightarrow> (\\<exists>zs. ys = xs @ zs)\"\n\ndefinition prefix :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"prefix xs ys \\<longleftrightarrow> prefixeq xs ys \\<and> xs \\<noteq> ys\"\n\ninterpretation prefix_order: order prefixeq prefix\n  by default (auto simp: prefixeq_def prefix_def)\n\ninterpretation prefix_bot: order_bot Nil prefixeq prefix\n  by default (simp add: prefixeq_def)\n\nlemma prefixeqI [intro?]: \"ys = xs @ zs \\<Longrightarrow> prefixeq xs ys\"\n  unfolding prefixeq_def by blast\n\nlemma prefixeqE [elim?]:\n  assumes \"prefixeq xs ys\"\n  obtains zs where \"ys = xs @ zs\"\n  using assms unfolding prefixeq_def by blast\n\nlemma prefixI' [intro?]: \"ys = xs @ z # zs \\<Longrightarrow> prefix xs ys\"\n  unfolding prefix_def prefixeq_def by blast\n\nlemma prefixE' [elim?]:\n  assumes \"prefix xs ys\"\n  obtains z zs where \"ys = xs @ z # zs\"\nproof -\n  from `prefix xs ys` obtain us where \"ys = xs @ us\" and \"xs \\<noteq> ys\"\n    unfolding prefix_def prefixeq_def by blast\n  with that show ?thesis by (auto simp add: neq_Nil_conv)\nqed\n\nlemma prefixI [intro?]: \"prefixeq xs ys \\<Longrightarrow> xs \\<noteq> ys \\<Longrightarrow> prefix xs ys\"\n  unfolding prefix_def by blast\n\nlemma prefixE [elim?]:\n  fixes xs ys :: \"'a list\"\n  assumes \"prefix xs ys\"\n  obtains \"prefixeq xs ys\" and \"xs \\<noteq> ys\"\n  using assms unfolding prefix_def by blast\n\n\nsubsection {* Basic properties of prefixes *}\n\ntheorem Nil_prefixeq [iff]: \"prefixeq [] xs\"\n  by (simp add: prefixeq_def)\n\ntheorem prefixeq_Nil [simp]: \"(prefixeq xs []) = (xs = [])\"\n  by (induct xs) (simp_all add: prefixeq_def)\n\nlemma prefixeq_snoc [simp]: \"prefixeq xs (ys @ [y]) \\<longleftrightarrow> xs = ys @ [y] \\<or> prefixeq xs ys\"\nproof\n  assume \"prefixeq xs (ys @ [y])\"\n  then obtain zs where zs: \"ys @ [y] = xs @ zs\" ..\n  show \"xs = ys @ [y] \\<or> prefixeq xs ys\"\n    by (metis append_Nil2 butlast_append butlast_snoc prefixeqI zs)\nnext\n  assume \"xs = ys @ [y] \\<or> prefixeq xs ys\"\n  then show \"prefixeq xs (ys @ [y])\"\n    by (metis prefix_order.eq_iff prefix_order.order_trans prefixeqI)\nqed\n\nlemma Cons_prefixeq_Cons [simp]: \"prefixeq (x # xs) (y # ys) = (x = y \\<and> prefixeq xs ys)\"\n  by (auto simp add: prefixeq_def)\n\nlemma prefixeq_code [code]:\n  \"prefixeq [] xs \\<longleftrightarrow> True\"\n  \"prefixeq (x # xs) [] \\<longleftrightarrow> False\"\n  \"prefixeq (x # xs) (y # ys) \\<longleftrightarrow> x = y \\<and> prefixeq xs ys\"\n  by simp_all\n\nlemma same_prefixeq_prefixeq [simp]: \"prefixeq (xs @ ys) (xs @ zs) = prefixeq ys zs\"\n  by (induct xs) simp_all\n\nlemma same_prefixeq_nil [iff]: \"prefixeq (xs @ ys) xs = (ys = [])\"\n  by (metis append_Nil2 append_self_conv prefix_order.eq_iff prefixeqI)\n\nlemma prefixeq_prefixeq [simp]: \"prefixeq xs ys \\<Longrightarrow> prefixeq xs (ys @ zs)\"\n  by (metis prefix_order.le_less_trans prefixeqI prefixE prefixI)\n\nlemma append_prefixeqD: \"prefixeq (xs @ ys) zs \\<Longrightarrow> prefixeq xs zs\"\n  by (auto simp add: prefixeq_def)\n\ntheorem prefixeq_Cons: \"prefixeq xs (y # ys) = (xs = [] \\<or> (\\<exists>zs. xs = y # zs \\<and> prefixeq zs ys))\"\n  by (cases xs) (auto simp add: prefixeq_def)\n\ntheorem prefixeq_append:\n  \"prefixeq xs (ys @ zs) = (prefixeq xs ys \\<or> (\\<exists>us. xs = ys @ us \\<and> prefixeq us zs))\"\n  apply (induct zs rule: rev_induct)\n   apply force\n  apply (simp del: append_assoc add: append_assoc [symmetric])\n  apply (metis append_eq_appendI)\n  done\n\nlemma append_one_prefixeq:\n  \"prefixeq xs ys \\<Longrightarrow> length xs < length ys \\<Longrightarrow> prefixeq (xs @ [ys ! length xs]) ys\"\n  proof (unfold prefixeq_def)\n    assume a1: \"\\<exists>zs. ys = xs @ zs\"\n    then obtain sk :: \"'a list\" where sk: \"ys = xs @ sk\" by fastforce\n    assume a2: \"length xs < length ys\"\n    have f1: \"\\<And>v. ([]\\<Colon>'a list) @ v = v\" using append_Nil2 by simp\n    have \"[] \\<noteq> sk\" using a1 a2 sk less_not_refl by force\n    hence \"\\<exists>v. xs @ hd sk # v = ys\" using sk by (metis hd_Cons_tl)\n    thus \"\\<exists>zs. ys = (xs @ [ys ! length xs]) @ zs\" using f1 by fastforce\n  qed\n\ntheorem prefixeq_length_le: \"prefixeq xs ys \\<Longrightarrow> length xs \\<le> length ys\"\n  by (auto simp add: prefixeq_def)\n\nlemma prefixeq_same_cases:\n  \"prefixeq (xs\\<^sub>1::'a list) ys \\<Longrightarrow> prefixeq xs\\<^sub>2 ys \\<Longrightarrow> prefixeq xs\\<^sub>1 xs\\<^sub>2 \\<or> prefixeq xs\\<^sub>2 xs\\<^sub>1\"\n  unfolding prefixeq_def by (force simp: append_eq_append_conv2)\n\nlemma set_mono_prefixeq: \"prefixeq xs ys \\<Longrightarrow> set xs \\<subseteq> set ys\"\n  by (auto simp add: prefixeq_def)\n\nlemma take_is_prefixeq: \"prefixeq (take n xs) xs\"\n  unfolding prefixeq_def by (metis append_take_drop_id)\n\nlemma map_prefixeqI: \"prefixeq xs ys \\<Longrightarrow> prefixeq (map f xs) (map f ys)\"\n  by (auto simp: prefixeq_def)\n\nlemma prefixeq_length_less: \"prefix xs ys \\<Longrightarrow> length xs < length ys\"\n  by (auto simp: prefix_def prefixeq_def)\n\nlemma prefix_simps [simp, code]:\n  \"prefix xs [] \\<longleftrightarrow> False\"\n  \"prefix [] (x # xs) \\<longleftrightarrow> True\"\n  \"prefix (x # xs) (y # ys) \\<longleftrightarrow> x = y \\<and> prefix xs ys\"\n  by (simp_all add: prefix_def cong: conj_cong)\n\nlemma take_prefix: \"prefix xs ys \\<Longrightarrow> prefix (take n xs) ys\"\n  apply (induct n arbitrary: xs ys)\n   apply (case_tac ys, simp_all)[1]\n  apply (metis prefix_order.less_trans prefixI take_is_prefixeq)\n  done\n\nlemma not_prefixeq_cases:\n  assumes pfx: \"\\<not> prefixeq ps ls\"\n  obtains\n    (c1) \"ps \\<noteq> []\" and \"ls = []\"\n  | (c2) a as x xs where \"ps = a#as\" and \"ls = x#xs\" and \"x = a\" and \"\\<not> prefixeq as xs\"\n  | (c3) a as x xs where \"ps = a#as\" and \"ls = x#xs\" and \"x \\<noteq> a\"\nproof (cases ps)\n  case Nil\n  then show ?thesis using pfx by simp\nnext\n  case (Cons a as)\n  note c = `ps = a#as`\n  show ?thesis\n  proof (cases ls)\n    case Nil then show ?thesis by (metis append_Nil2 pfx c1 same_prefixeq_nil)\n  next\n    case (Cons x xs)\n    show ?thesis\n    proof (cases \"x = a\")\n      case True\n      have \"\\<not> prefixeq as xs\" using pfx c Cons True by simp\n      with c Cons True show ?thesis by (rule c2)\n    next\n      case False\n      with c Cons show ?thesis by (rule c3)\n    qed\n  qed\nqed\n\nlemma not_prefixeq_induct [consumes 1, case_names Nil Neq Eq]:\n  assumes np: \"\\<not> prefixeq ps ls\"\n    and base: \"\\<And>x xs. P (x#xs) []\"\n    and r1: \"\\<And>x xs y ys. x \\<noteq> y \\<Longrightarrow> P (x#xs) (y#ys)\"\n    and r2: \"\\<And>x xs y ys. \\<lbrakk> x = y; \\<not> prefixeq xs ys; P xs ys \\<rbrakk> \\<Longrightarrow> P (x#xs) (y#ys)\"\n  shows \"P ps ls\" using np\nproof (induct ls arbitrary: ps)\n  case Nil then show ?case\n    by (auto simp: neq_Nil_conv elim!: not_prefixeq_cases intro!: base)\nnext\n  case (Cons y ys)\n  then have npfx: \"\\<not> prefixeq ps (y # ys)\" by simp\n  then obtain x xs where pv: \"ps = x # xs\"\n    by (rule not_prefixeq_cases) auto\n  show ?case by (metis Cons.hyps Cons_prefixeq_Cons npfx pv r1 r2)\nqed\n\n\nsubsection {* Parallel lists *}\n\ndefinition parallel :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"  (infixl \"\\<parallel>\" 50)\n  where \"(xs \\<parallel> ys) = (\\<not> prefixeq xs ys \\<and> \\<not> prefixeq ys xs)\"\n\nlemma parallelI [intro]: \"\\<not> prefixeq xs ys \\<Longrightarrow> \\<not> prefixeq ys xs \\<Longrightarrow> xs \\<parallel> ys\"\n  unfolding parallel_def by blast\n\nlemma parallelE [elim]:\n  assumes \"xs \\<parallel> ys\"\n  obtains \"\\<not> prefixeq xs ys \\<and> \\<not> prefixeq ys xs\"\n  using assms unfolding parallel_def by blast\n\ntheorem prefixeq_cases:\n  obtains \"prefixeq xs ys\" | \"prefix ys xs\" | \"xs \\<parallel> ys\"\n  unfolding parallel_def prefix_def by blast\n\ntheorem parallel_decomp:\n  \"xs \\<parallel> ys \\<Longrightarrow> \\<exists>as b bs c cs. b \\<noteq> c \\<and> xs = as @ b # bs \\<and> ys = as @ c # cs\"\nproof (induct xs rule: rev_induct)\n  case Nil\n  then have False by auto\n  then show ?case ..\nnext\n  case (snoc x xs)\n  show ?case\n  proof (rule prefixeq_cases)\n    assume le: \"prefixeq xs ys\"\n    then obtain ys' where ys: \"ys = xs @ ys'\" ..\n    show ?thesis\n    proof (cases ys')\n      assume \"ys' = []\"\n      then show ?thesis by (metis append_Nil2 parallelE prefixeqI snoc.prems ys)\n    next\n      fix c cs assume ys': \"ys' = c # cs\"\n      have \"x \\<noteq> c\" using snoc.prems ys ys' by fastforce\n      thus \"\\<exists>as b bs c cs. b \\<noteq> c \\<and> xs @ [x] = as @ b # bs \\<and> ys = as @ c # cs\"\n        using ys ys' by blast\n    qed\n  next\n    assume \"prefix ys xs\"\n    then have \"prefixeq ys (xs @ [x])\" by (simp add: prefix_def)\n    with snoc have False by blast\n    then show ?thesis ..\n  next\n    assume \"xs \\<parallel> ys\"\n    with snoc obtain as b bs c cs where neq: \"(b::'a) \\<noteq> c\"\n      and xs: \"xs = as @ b # bs\" and ys: \"ys = as @ c # cs\"\n      by blast\n    from xs have \"xs @ [x] = as @ b # (bs @ [x])\" by simp\n    with neq ys show ?thesis by blast\n  qed\nqed\n\nlemma parallel_append: \"a \\<parallel> b \\<Longrightarrow> a @ c \\<parallel> b @ d\"\n  apply (rule parallelI)\n    apply (erule parallelE, erule conjE,\n      induct rule: not_prefixeq_induct, simp+)+\n  done\n\nlemma parallel_appendI: \"xs \\<parallel> ys \\<Longrightarrow> x = xs @ xs' \\<Longrightarrow> y = ys @ ys' \\<Longrightarrow> x \\<parallel> y\"\n  by (simp add: parallel_append)\n\nlemma parallel_commute: \"a \\<parallel> b \\<longleftrightarrow> b \\<parallel> a\"\n  unfolding parallel_def by auto\n\n\nsubsection {* Suffix order on lists *}\n\ndefinition suffixeq :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"suffixeq xs ys = (\\<exists>zs. ys = zs @ xs)\"\n\ndefinition suffix :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"suffix xs ys \\<longleftrightarrow> (\\<exists>us. ys = us @ xs \\<and> us \\<noteq> [])\"\n\nlemma suffix_imp_suffixeq:\n  \"suffix xs ys \\<Longrightarrow> suffixeq xs ys\"\n  by (auto simp: suffixeq_def suffix_def)\n\nlemma suffixeqI [intro?]: \"ys = zs @ xs \\<Longrightarrow> suffixeq xs ys\"\n  unfolding suffixeq_def by blast\n\nlemma suffixeqE [elim?]:\n  assumes \"suffixeq xs ys\"\n  obtains zs where \"ys = zs @ xs\"\n  using assms unfolding suffixeq_def by blast\n\nlemma suffixeq_refl [iff]: \"suffixeq xs xs\"\n  by (auto simp add: suffixeq_def)\nlemma suffix_trans:\n  \"suffix xs ys \\<Longrightarrow> suffix ys zs \\<Longrightarrow> suffix xs zs\"\n  by (auto simp: suffix_def)\nlemma suffixeq_trans: \"\\<lbrakk>suffixeq xs ys; suffixeq ys zs\\<rbrakk> \\<Longrightarrow> suffixeq xs zs\"\n  by (auto simp add: suffixeq_def)\nlemma suffixeq_antisym: \"\\<lbrakk>suffixeq xs ys; suffixeq ys xs\\<rbrakk> \\<Longrightarrow> xs = ys\"\n  by (auto simp add: suffixeq_def)\n\nlemma suffixeq_tl [simp]: \"suffixeq (tl xs) xs\"\n  by (induct xs) (auto simp: suffixeq_def)\n\nlemma suffix_tl [simp]: \"xs \\<noteq> [] \\<Longrightarrow> suffix (tl xs) xs\"\n  by (induct xs) (auto simp: suffix_def)\n\nlemma Nil_suffixeq [iff]: \"suffixeq [] xs\"\n  by (simp add: suffixeq_def)\nlemma suffixeq_Nil [simp]: \"(suffixeq xs []) = (xs = [])\"\n  by (auto simp add: suffixeq_def)\n\nlemma suffixeq_ConsI: \"suffixeq xs ys \\<Longrightarrow> suffixeq xs (y # ys)\"\n  by (auto simp add: suffixeq_def)\nlemma suffixeq_ConsD: \"suffixeq (x # xs) ys \\<Longrightarrow> suffixeq xs ys\"\n  by (auto simp add: suffixeq_def)\n\nlemma suffixeq_appendI: \"suffixeq xs ys \\<Longrightarrow> suffixeq xs (zs @ ys)\"\n  by (auto simp add: suffixeq_def)\nlemma suffixeq_appendD: \"suffixeq (zs @ xs) ys \\<Longrightarrow> suffixeq xs ys\"\n  by (auto simp add: suffixeq_def)\n\nlemma suffix_set_subset:\n  \"suffix xs ys \\<Longrightarrow> set xs \\<subseteq> set ys\" by (auto simp: suffix_def)\n\nlemma suffixeq_set_subset:\n  \"suffixeq xs ys \\<Longrightarrow> set xs \\<subseteq> set ys\" by (auto simp: suffixeq_def)\n\nlemma suffixeq_ConsD2: \"suffixeq (x # xs) (y # ys) \\<Longrightarrow> suffixeq xs ys\"\nproof -\n  assume \"suffixeq (x # xs) (y # ys)\"\n  then obtain zs where \"y # ys = zs @ x # xs\" ..\n  then show ?thesis\n    by (induct zs) (auto intro!: suffixeq_appendI suffixeq_ConsI)\nqed\n\nlemma suffixeq_to_prefixeq [code]: \"suffixeq xs ys \\<longleftrightarrow> prefixeq (rev xs) (rev ys)\"\nproof\n  assume \"suffixeq xs ys\"\n  then obtain zs where \"ys = zs @ xs\" ..\n  then have \"rev ys = rev xs @ rev zs\" by simp\n  then show \"prefixeq (rev xs) (rev ys)\" ..\nnext\n  assume \"prefixeq (rev xs) (rev ys)\"\n  then obtain zs where \"rev ys = rev xs @ zs\" ..\n  then have \"rev (rev ys) = rev zs @ rev (rev xs)\" by simp\n  then have \"ys = rev zs @ xs\" by simp\n  then show \"suffixeq xs ys\" ..\nqed\n\nlemma distinct_suffixeq: \"distinct ys \\<Longrightarrow> suffixeq xs ys \\<Longrightarrow> distinct xs\"\n  by (clarsimp elim!: suffixeqE)\n\nlemma suffixeq_map: \"suffixeq xs ys \\<Longrightarrow> suffixeq (map f xs) (map f ys)\"\n  by (auto elim!: suffixeqE intro: suffixeqI)\n\nlemma suffixeq_drop: \"suffixeq (drop n as) as\"\n  unfolding suffixeq_def\n  apply (rule exI [where x = \"take n as\"])\n  apply simp\n  done\n\nlemma suffixeq_take: \"suffixeq xs ys \\<Longrightarrow> ys = take (length ys - length xs) ys @ xs\"\n  by (auto elim!: suffixeqE)\n\nlemma suffixeq_suffix_reflclp_conv: \"suffixeq = suffix\\<^sup>=\\<^sup>=\"\nproof (intro ext iffI)\n  fix xs ys :: \"'a list\"\n  assume \"suffixeq xs ys\"\n  show \"suffix\\<^sup>=\\<^sup>= xs ys\"\n  proof\n    assume \"xs \\<noteq> ys\"\n    with `suffixeq xs ys` show \"suffix xs ys\"\n      by (auto simp: suffixeq_def suffix_def)\n  qed\nnext\n  fix xs ys :: \"'a list\"\n  assume \"suffix\\<^sup>=\\<^sup>= xs ys\"\n  then show \"suffixeq xs ys\"\n  proof\n    assume \"suffix xs ys\" then show \"suffixeq xs ys\"\n      by (rule suffix_imp_suffixeq)\n  next\n    assume \"xs = ys\" then show \"suffixeq xs ys\"\n      by (auto simp: suffixeq_def)\n  qed\nqed\n\nlemma parallelD1: \"x \\<parallel> y \\<Longrightarrow> \\<not> prefixeq x y\"\n  by blast\n\nlemma parallelD2: \"x \\<parallel> y \\<Longrightarrow> \\<not> prefixeq y x\"\n  by blast\n\nlemma parallel_Nil1 [simp]: \"\\<not> x \\<parallel> []\"\n  unfolding parallel_def by simp\n\nlemma parallel_Nil2 [simp]: \"\\<not> [] \\<parallel> x\"\n  unfolding parallel_def by simp\n\nlemma Cons_parallelI1: \"a \\<noteq> b \\<Longrightarrow> a # as \\<parallel> b # bs\"\n  by auto\n\nlemma Cons_parallelI2: \"\\<lbrakk> a = b; as \\<parallel> bs \\<rbrakk> \\<Longrightarrow> a # as \\<parallel> b # bs\"\n  by (metis Cons_prefixeq_Cons parallelE parallelI)\n\nlemma not_equal_is_parallel:\n  assumes neq: \"xs \\<noteq> ys\"\n    and len: \"length xs = length ys\"\n  shows \"xs \\<parallel> ys\"\n  using len neq\nproof (induct rule: list_induct2)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a as b bs)\n  have ih: \"as \\<noteq> bs \\<Longrightarrow> as \\<parallel> bs\" by fact\n  show ?case\n  proof (cases \"a = b\")\n    case True\n    then have \"as \\<noteq> bs\" using Cons by simp\n    then show ?thesis by (rule Cons_parallelI2 [OF True ih])\n  next\n    case False\n    then show ?thesis by (rule Cons_parallelI1)\n  qed\nqed\n\nlemma suffix_reflclp_conv: \"suffix\\<^sup>=\\<^sup>= = suffixeq\"\n  by (intro ext) (auto simp: suffixeq_def suffix_def)\n\nlemma suffix_lists: \"suffix xs ys \\<Longrightarrow> ys \\<in> lists A \\<Longrightarrow> xs \\<in> lists A\"\n  unfolding suffix_def by auto\n\n\nsubsection {* Homeomorphic embedding on lists *}\n\ninductive list_emb :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  for P :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool)\"\nwhere\n  list_emb_Nil [intro, simp]: \"list_emb P [] ys\"\n| list_emb_Cons [intro] : \"list_emb P xs ys \\<Longrightarrow> list_emb P xs (y#ys)\"\n| list_emb_Cons2 [intro]: \"P x y \\<Longrightarrow> list_emb P xs ys \\<Longrightarrow> list_emb P (x#xs) (y#ys)\"\n\nlemma list_emb_mono:                         \n  assumes \"\\<And>x y. P x y \\<longrightarrow> Q x y\"\n  shows \"list_emb P xs ys \\<longrightarrow> list_emb Q xs ys\"\nproof                                        \n  assume \"list_emb P xs ys\"                    \n  then show \"list_emb Q xs ys\" by (induct) (auto simp: assms)\nqed \n\nlemma list_emb_Nil2 [simp]:\n  assumes \"list_emb P xs []\" shows \"xs = []\"\n  using assms by (cases rule: list_emb.cases) auto\n\nlemma list_emb_refl:\n  assumes \"\\<And>x. x \\<in> set xs \\<Longrightarrow> P x x\"\n  shows \"list_emb P xs xs\"\n  using assms by (induct xs) auto\n\nlemma list_emb_Cons_Nil [simp]: \"list_emb P (x#xs) [] = False\"\nproof -\n  { assume \"list_emb P (x#xs) []\"\n    from list_emb_Nil2 [OF this] have False by simp\n  } moreover {\n    assume False\n    then have \"list_emb P (x#xs) []\" by simp\n  } ultimately show ?thesis by blast\nqed\n\nlemma list_emb_append2 [intro]: \"list_emb P xs ys \\<Longrightarrow> list_emb P xs (zs @ ys)\"\n  by (induct zs) auto\n\nlemma list_emb_prefix [intro]:\n  assumes \"list_emb P xs ys\" shows \"list_emb P xs (ys @ zs)\"\n  using assms\n  by (induct arbitrary: zs) auto\n\nlemma list_emb_ConsD:\n  assumes \"list_emb P (x#xs) ys\"\n  shows \"\\<exists>us v vs. ys = us @ v # vs \\<and> P x v \\<and> list_emb P xs vs\"\nusing assms\nproof (induct x \\<equiv> \"x # xs\" ys arbitrary: x xs)\n  case list_emb_Cons\n  then show ?case by (metis append_Cons)\nnext\n  case (list_emb_Cons2 x y xs ys)\n  then show ?case by blast\nqed\n\nlemma list_emb_appendD:\n  assumes \"list_emb P (xs @ ys) zs\"\n  shows \"\\<exists>us vs. zs = us @ vs \\<and> list_emb P xs us \\<and> list_emb P ys vs\"\nusing assms\nproof (induction xs arbitrary: ys zs)\n  case Nil then show ?case by auto\nnext\n  case (Cons x xs)\n  then obtain us v vs where\n    zs: \"zs = us @ v # vs\" and p: \"P x v\" and lh: \"list_emb P (xs @ ys) vs\"\n    by (auto dest: list_emb_ConsD)\n  obtain sk\\<^sub>0 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" and sk\\<^sub>1 :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n    sk: \"\\<forall>x\\<^sub>0 x\\<^sub>1. \\<not> list_emb P (xs @ x\\<^sub>0) x\\<^sub>1 \\<or> sk\\<^sub>0 x\\<^sub>0 x\\<^sub>1 @ sk\\<^sub>1 x\\<^sub>0 x\\<^sub>1 = x\\<^sub>1 \\<and> list_emb P xs (sk\\<^sub>0 x\\<^sub>0 x\\<^sub>1) \\<and> list_emb P x\\<^sub>0 (sk\\<^sub>1 x\\<^sub>0 x\\<^sub>1)\"\n    using Cons(1) by (metis (no_types))\n  hence \"\\<forall>x\\<^sub>2. list_emb P (x # xs) (x\\<^sub>2 @ v # sk\\<^sub>0 ys vs)\" using p lh by auto\n  thus ?case using lh zs sk by (metis (no_types) append_Cons append_assoc)\nqed\n\nlemma list_emb_suffix:\n  assumes \"list_emb P xs ys\" and \"suffix ys zs\"\n  shows \"list_emb P xs zs\"\n  using assms(2) and list_emb_append2 [OF assms(1)] by (auto simp: suffix_def)\n\nlemma list_emb_suffixeq:\n  assumes \"list_emb P xs ys\" and \"suffixeq ys zs\"\n  shows \"list_emb P xs zs\"\n  using assms and list_emb_suffix unfolding suffixeq_suffix_reflclp_conv by auto\n\nlemma list_emb_length: \"list_emb P xs ys \\<Longrightarrow> length xs \\<le> length ys\"\n  by (induct rule: list_emb.induct) auto\n\nlemma list_emb_trans:\n  assumes \"\\<And>x y z. \\<lbrakk>x \\<in> set xs; y \\<in> set ys; z \\<in> set zs; P x y; P y z\\<rbrakk> \\<Longrightarrow> P x z\"\n  shows \"\\<lbrakk>list_emb P xs ys; list_emb P ys zs\\<rbrakk> \\<Longrightarrow> list_emb P xs zs\"\nproof -\n  assume \"list_emb P xs ys\" and \"list_emb P ys zs\"\n  then show \"list_emb P xs zs\" using assms\n  proof (induction arbitrary: zs)\n    case list_emb_Nil show ?case by blast\n  next\n    case (list_emb_Cons xs ys y)\n    from list_emb_ConsD [OF `list_emb P (y#ys) zs`] obtain us v vs\n      where zs: \"zs = us @ v # vs\" and \"P\\<^sup>=\\<^sup>= y v\" and \"list_emb P ys vs\" by blast\n    then have \"list_emb P ys (v#vs)\" by blast\n    then have \"list_emb P ys zs\" unfolding zs by (rule list_emb_append2)\n    from list_emb_Cons.IH [OF this] and list_emb_Cons.prems show ?case by auto\n  next\n    case (list_emb_Cons2 x y xs ys)\n    from list_emb_ConsD [OF `list_emb P (y#ys) zs`] obtain us v vs\n      where zs: \"zs = us @ v # vs\" and \"P y v\" and \"list_emb P ys vs\" by blast\n    with list_emb_Cons2 have \"list_emb P xs vs\" by auto\n    moreover have \"P x v\"\n    proof -\n      from zs have \"v \\<in> set zs\" by auto\n      moreover have \"x \\<in> set (x#xs)\" and \"y \\<in> set (y#ys)\" by simp_all\n      ultimately show ?thesis\n        using `P x y` and `P y v` and list_emb_Cons2\n        by blast\n    qed\n    ultimately have \"list_emb P (x#xs) (v#vs)\" by blast\n    then show ?case unfolding zs by (rule list_emb_append2)\n  qed\nqed\n\nlemma list_emb_set:\n  assumes \"list_emb P xs ys\" and \"x \\<in> set xs\"\n  obtains y where \"y \\<in> set ys\" and \"P x y\"\n  using assms by (induct) auto\n\n\nsubsection {* Sublists (special case of homeomorphic embedding) *}\n\nabbreviation sublisteq :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  where \"sublisteq xs ys \\<equiv> list_emb (op =) xs ys\"\n\nlemma sublisteq_Cons2: \"sublisteq xs ys \\<Longrightarrow> sublisteq (x#xs) (x#ys)\" by auto\n\nlemma sublisteq_same_length:\n  assumes \"sublisteq xs ys\" and \"length xs = length ys\" shows \"xs = ys\"\n  using assms by (induct) (auto dest: list_emb_length)\n\nlemma not_sublisteq_length [simp]: \"length ys < length xs \\<Longrightarrow> \\<not> sublisteq xs ys\"\n  by (metis list_emb_length linorder_not_less)\n\n\n\nlemma sublisteq_Cons': \"sublisteq (x#xs) ys \\<Longrightarrow> sublisteq xs ys\"\n  by (induct xs, simp, blast dest: list_emb_ConsD)\n\nlemma sublisteq_Cons2':\n  assumes \"sublisteq (x#xs) (x#ys)\" shows \"sublisteq xs ys\"\n  using assms by (cases) (rule sublisteq_Cons')\n\nlemma sublisteq_Cons2_neq:\n  assumes \"sublisteq (x#xs) (y#ys)\"\n  shows \"x \\<noteq> y \\<Longrightarrow> sublisteq (x#xs) ys\"\n  using assms by (cases) auto\n\nlemma sublisteq_Cons2_iff [simp, code]:\n  \"sublisteq (x#xs) (y#ys) = (if x = y then sublisteq xs ys else sublisteq (x#xs) ys)\"\n  by (metis list_emb_Cons sublisteq_Cons2 sublisteq_Cons2' sublisteq_Cons2_neq)\n\nlemma sublisteq_append': \"sublisteq (zs @ xs) (zs @ ys) \\<longleftrightarrow> sublisteq xs ys\"\n  by (induct zs) simp_all\n\nlemma sublisteq_refl [simp, intro!]: \"sublisteq xs xs\" by (induct xs) simp_all\n\nlemma sublisteq_antisym:\n  assumes \"sublisteq xs ys\" and \"sublisteq ys xs\"\n  shows \"xs = ys\"\nusing assms\nproof (induct)\n  case list_emb_Nil\n  from list_emb_Nil2 [OF this] show ?case by simp\nnext\n  case list_emb_Cons2\n  thus ?case by simp\nnext\n  case list_emb_Cons\n  hence False using sublisteq_Cons' by fastforce\n  thus ?case ..\nqed\n\nlemma sublisteq_trans: \"sublisteq xs ys \\<Longrightarrow> sublisteq ys zs \\<Longrightarrow> sublisteq xs zs\"\n  by (rule list_emb_trans [of _ _ _ \"op =\"]) auto\n\nlemma sublisteq_append_le_same_iff: \"sublisteq (xs @ ys) ys \\<longleftrightarrow> xs = []\"\n  by (auto dest: list_emb_length)\n\nlemma list_emb_append_mono:\n  \"\\<lbrakk> list_emb P xs xs'; list_emb P ys ys' \\<rbrakk> \\<Longrightarrow> list_emb P (xs@ys) (xs'@ys')\"\n  apply (induct rule: list_emb.induct)\n    apply (metis eq_Nil_appendI list_emb_append2)\n   apply (metis append_Cons list_emb_Cons)\n  apply (metis append_Cons list_emb_Cons2)\n  done\n\n\nsubsection {* Appending elements *}\n\nlemma sublisteq_append [simp]:\n  \"sublisteq (xs @ zs) (ys @ zs) \\<longleftrightarrow> sublisteq xs ys\" (is \"?l = ?r\")\nproof\n  { fix xs' ys' xs ys zs :: \"'a list\" assume \"sublisteq xs' ys'\"\n    then have \"xs' = xs @ zs & ys' = ys @ zs \\<longrightarrow> sublisteq xs ys\"\n    proof (induct arbitrary: xs ys zs)\n      case list_emb_Nil show ?case by simp\n    next\n      case (list_emb_Cons xs' ys' x)\n      { assume \"ys=[]\" then have ?case using list_emb_Cons(1) by auto }\n      moreover\n      { fix us assume \"ys = x#us\"\n        then have ?case using list_emb_Cons(2) by(simp add: list_emb.list_emb_Cons) }\n      ultimately show ?case by (auto simp:Cons_eq_append_conv)\n    next\n      case (list_emb_Cons2 x y xs' ys')\n      { assume \"xs=[]\" then have ?case using list_emb_Cons2(1) by auto }\n      moreover\n      { fix us vs assume \"xs=x#us\" \"ys=x#vs\" then have ?case using list_emb_Cons2 by auto}\n      moreover\n      { fix us assume \"xs=x#us\" \"ys=[]\" then have ?case using list_emb_Cons2(2) by bestsimp }\n      ultimately show ?case using `op = x y` by (auto simp: Cons_eq_append_conv)\n    qed }\n  moreover assume ?l\n  ultimately show ?r by blast\nnext\n  assume ?r then show ?l by (metis list_emb_append_mono sublisteq_refl)\nqed\n\nlemma sublisteq_drop_many: \"sublisteq xs ys \\<Longrightarrow> sublisteq xs (zs @ ys)\"\n  by (induct zs) auto\n\nlemma sublisteq_rev_drop_many: \"sublisteq xs ys \\<Longrightarrow> sublisteq xs (ys @ zs)\"\n  by (metis append_Nil2 list_emb_Nil list_emb_append_mono)\n\n\nsubsection {* Relation to standard list operations *}\n\nlemma sublisteq_map:\n  assumes \"sublisteq xs ys\" shows \"sublisteq (map f xs) (map f ys)\"\n  using assms by (induct) auto\n\nlemma sublisteq_filter_left [simp]: \"sublisteq (filter P xs) xs\"\n  by (induct xs) auto\n\nlemma sublisteq_filter [simp]:\n  assumes \"sublisteq xs ys\" shows \"sublisteq (filter P xs) (filter P ys)\"\n  using assms by induct auto\n\nlemma \"sublisteq xs ys \\<longleftrightarrow> (\\<exists>N. xs = sublist ys N)\" (is \"?L = ?R\")\nproof\n  assume ?L\n  then show ?R\n  proof (induct)\n    case list_emb_Nil show ?case by (metis sublist_empty)\n  next\n    case (list_emb_Cons xs ys x)\n    then obtain N where \"xs = sublist ys N\" by blast\n    then have \"xs = sublist (x#ys) (Suc ` N)\"\n      by (clarsimp simp add:sublist_Cons inj_image_mem_iff)\n    then show ?case by blast\n  next\n    case (list_emb_Cons2 x y xs ys)\n    then obtain N where \"xs = sublist ys N\" by blast\n    then have \"x#xs = sublist (x#ys) (insert 0 (Suc ` N))\"\n      by (clarsimp simp add:sublist_Cons inj_image_mem_iff)\n    moreover from list_emb_Cons2 have \"x = y\" by simp\n    ultimately show ?case by blast\n  qed\nnext\n  assume ?R\n  then obtain N where \"xs = sublist ys N\" ..\n  moreover have \"sublisteq (sublist ys N) ys\"\n  proof (induct ys arbitrary: N)\n    case Nil show ?case by simp\n  next\n    case Cons then show ?case by (auto simp: sublist_Cons)\n  qed\n  ultimately show ?L by simp\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Sublist.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.8774767970940974, "lm_q1q2_score": 0.7576060983889055}}
{"text": "(* Property from Case-Analysis for Rippling and Inductive Proof, \n   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. \n   This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n   Some proofs were added by Yutaka Nagashima.*)\ntheory TIP_prop_58\n  imports \"../../Test_Base\"\nbegin\n\ndatatype ('a, 'b) pair = pair2 \"'a\" \"'b\"\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun zip :: \"'a list => 'b list => (('a, 'b) pair) list\" where\n  \"zip (nil2) y = nil2\"\n| \"zip (cons2 z x2) (nil2) = nil2\"\n| \"zip (cons2 z x2) (cons2 x3 x4) = cons2 (pair2 z x3) (zip x2 x4)\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n  \"drop (Z) y = y\"\n| \"drop (S z) (nil2) = nil2\"\n| \"drop (S z) (cons2 x2 x3) = drop z x3\"\n\ntheorem property0 :\n  \"((drop n (zip xs ys)) = (zip (drop n xs) (drop n ys)))\"\n  apply(induct n arbitrary: xs ys)\n   apply fastforce\n    (*Why \"case_tac xs\"?\n    Because of \"drop (S n) xs\" and \"drop\"'s pattern-matching.*)\n  apply(case_tac xs)\n   apply fastforce\n  apply clarsimp\n    (*Why \"case_tac ys\"?\n    Because of \"zip (cons2 x21 x22) ys\" and \"drop (S n) ys\" and\n    the pattern-matching of \"zip\" and \"drop\".*)\n  apply(case_tac ys)\n   apply clarsimp\n    (*Why \"case_tac \"(TIP_prop_58.drop n x22)\"?\n     \"zip (TIP_prop_58.drop n x22) nil2\"*)\n   apply(case_tac \"(TIP_prop_58.drop n x22)\")(*\"case_tac\" instead of \"cases\" because \"\\<And>n x2.\" *)\n    apply fastforce+\n  done\n\ntheorem property0':\n  \"((drop n (zip xs ys)) = (zip (drop n xs) (drop n ys)))\"\n  apply(induct n arbitrary: xs ys)\n   apply fastforce\n  apply(induct_tac xs)\n   apply fastforce\n  apply clarsimp\n  apply(case_tac ys)\n   apply clarsimp\n   apply(case_tac \"(TIP_prop_58.drop n x2)\")(*\"case_tac\" instead of \"cases\" because \"\\<And>n x2.\" *)\n    apply fastforce+\n  done\n\ntheorem property0'' :(*alternative proof with sledgehammer.*)\n  \"((drop n (zip xs ys)) = (zip (drop n xs) (drop n ys)))\"\n  apply(induct n arbitrary: xs ys)\n   apply fastforce\n  apply(induct_tac xs)\n   apply fastforce\n  apply clarsimp\n  apply(case_tac ys)\n   apply clarsimp\n   apply (metis TIP_prop_58.list.distinct(1) zip.elims)\n  apply fastforce+\n  done\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/Isaplanner/Isaplanner/TIP_prop_58.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7576060962585676}}
{"text": "(*<*)\n(*\n * Knowledge-based programs.\n * (C)opyright 2011, Peter Gammie, peteg42 at gmail.com.\n * License: BSD\n *\n * Based on Florian Haftmann's DList.thy and Tobias Nipkow's msort proofs.\n *)\n\ntheory ODList\nimports\n  \"~~/src/HOL/Library/Multiset\"\n  List_local\nbegin\n(*>*)\n\ntext{*\n\nDefine a type of ordered distinct lists, intended to represent sets.\n\nThe advantage of this representation is that it is isomorphic to the\nset of finite sets. Conversely it requires the carrier type to be a\nlinear order.  Note that this representation does not arise from a\nquotient on lists: all the unsorted lists are junk.\n\n*}\n\ncontext linorder\nbegin\n\ntext{*\n\n\"Absorbing\" msort, a variant of Tobias Nipkow's proofs from 1992.\n\n*}\n\nfun\n  merge :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"merge [] ys = ys\"\n| \"merge xs [] = xs\"\n| \"merge (x#xs) (y#ys) =\n    (if x = y then merge xs (y#ys)\n             else if x < y then x # merge xs (y#ys)\n                           else y # merge (x#xs) ys)\"\n\n(*<*)\nlemma set_merge[simp]:\n  \"set (merge xs ys) = set (xs @ ys)\"\n  by (induct xs ys rule: merge.induct) auto\n\nlemma distinct_sorted_merge[simp]:\n  \"\\<lbrakk> distinct xs; distinct ys; sorted xs; sorted ys \\<rbrakk>\n     \\<Longrightarrow> distinct (merge xs ys) \\<and> sorted (merge xs ys)\"\n  by (induct xs ys rule: merge.induct) (auto iff: sorted_Cons)\n\nlemma multiset_of_merge [simp]:\n  \"\\<lbrakk> distinct (xs @ ys) \\<rbrakk> \\<Longrightarrow> multiset_of (merge xs ys) = multiset_of xs + multiset_of ys\"\n  by (induct xs ys rule: merge.induct) (simp_all add: ac_simps)\n(*>*)\n\ntext{* The \"absorbing\" sort itself. *}\n\nfun msort :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  \"msort [] = []\"\n| \"msort [x] = [x]\"\n| \"msort xs = merge (msort (take (size xs div 2) xs))\n                    (msort (drop (size xs div 2) xs))\"\n\n(*<*)\nlemma msort_distinct_sorted[simp]:\n  \"distinct (msort xs) \\<and> sorted (msort xs)\"\n  by (induct xs rule: msort.induct) simp_all\n\n\n\nlemma msort_remdups[simp]:\n  \"remdups (msort xs) = msort xs\"\n  by simp\n\nlemma msort_idle[simp]:\n  \"\\<lbrakk> distinct xs; sorted xs \\<rbrakk> \\<Longrightarrow> msort xs = xs\"\n  by (rule map_sorted_distinct_set_unique[where f=id]) (auto simp: map.id)\n\nlemma multiset_of_msort[simp]:\n  \"distinct xs \\<Longrightarrow> multiset_of (msort xs) = multiset_of xs\"\n  by (rule iffD1[OF set_eq_iff_multiset_of_eq_distinct]) simp_all\n\nlemma msort_sort[simp]:\n  \"distinct xs \\<Longrightarrow> sort xs = msort xs\"\n  by (simp add: properties_for_sort)\n(*>*)\n\nend (* context linorder *)\n\n\nsection {* The @{term \"odlist\"} type *}\n\ntypedef ('a :: linorder) odlist = \"{ x::'a list . sorted x \\<and> distinct x }\"\n  morphisms toList odlist_Abs by auto\n\nlemma distinct_toList[simp]: \"distinct (toList xs)\"\n  using toList by auto\n\nlemma sorted_toList[simp]: \"sorted (toList xs)\"\n  using toList by auto\n\ntext{*\n\nCode generator voodoo: this is the constructor for the abstract type.\n\n*}\n\ndefinition\n  ODList :: \"('a :: linorder) list \\<Rightarrow> 'a odlist\"\nwhere\n  \"ODList \\<equiv> odlist_Abs \\<circ> msort\"\n\nlemma toList_ODList:\n  \"toList (ODList xs) = msort xs\"\n  unfolding ODList_def\n  by (simp add: odlist_Abs_inverse)\n\nlemma ODList_toList[simp, code abstype]:\n  \"ODList (toList xs) = xs\"\n  unfolding ODList_def\n  by (cases xs) (simp add: odlist_Abs_inverse)\n\ntext{*\n\nRuntime cast from @{typ \"'a list\"} into @{typ \"'a odlist\"}. This is\njust a renaming of @{term \"ODList\"} -- names are significant to the\ncode generator's abstract type machinery.\n\n*}\n\ndefinition\n  fromList :: \"('a :: linorder) list \\<Rightarrow> 'a odlist\"\nwhere\n  \"fromList \\<equiv> ODList\"\n\nlemma toList_fromList[code abstract]:\n  \"toList (fromList xs) = msort xs\"\n  unfolding fromList_def\n  by (simp add: toList_ODList)\n\nsubsection{* Basic properties: equality, finiteness *}\n\n(*<*)\ndeclare toList_inject[iff]\n(*>*)\n\ninstantiation odlist :: (linorder) equal\n(*<*)\nbegin\n\ndefinition [code]:\n  \"HOL.equal A B \\<longleftrightarrow> odlist_equal (toList A) (toList B)\"\n\ninstance\n  by default (simp add: equal_odlist_def)\n\nend\n(*>*)\n\ninstance odlist :: (\"{finite, linorder}\") finite\n(*<*)\nproof\n  let ?ol = \"UNIV :: 'a odlist set\"\n  let ?s = \"UNIV :: 'a set set\"\n  have \"finite ?s\" by simp\n  moreover\n  have \"?ol \\<subseteq> range (odlist_Abs \\<circ> sorted_list_of_set)\"\n  proof\n    fix x show \"x \\<in> range (odlist_Abs \\<circ> sorted_list_of_set)\"\n      apply (cases x)\n      apply (rule range_eqI[where x=\"set (toList x)\"])\n      apply (clarsimp simp: odlist_Abs_inject sorted_list_of_set_sort_remdups odlist_Abs_inverse distinct_remdups_id)\n      done\n  qed\n  ultimately show \"finite ?ol\" by (blast intro: finite_surj)\nqed\n(*>*)\n\nsubsection{* Constants *}\n\ndefinition\n  empty :: \"('a :: linorder) odlist\"\nwhere\n  \"empty \\<equiv> ODList []\"\n\nlemma toList_empty[simp, code abstract]:\n  \"toList empty = []\"\n  unfolding empty_def by (simp add: toList_ODList)\n\nsubsection{* Operations *}\n\nsubsubsection{* toSet *}\n\ndefinition\n  toSet :: \"('a :: linorder) odlist \\<Rightarrow> 'a set\"\nwhere\n  \"toSet X = set (toList X)\"\n\nlemma toSet_empty[simp]:\n  \"toSet empty = {}\"\n  unfolding toSet_def empty_def by (simp add: toList_ODList)\n\nlemma toSet_ODList[simp]:\n  \"\\<lbrakk> distinct xs; sorted xs \\<rbrakk> \\<Longrightarrow> toSet (ODList xs) = set xs\"\n  unfolding toSet_def by (simp add: toList_ODList)\n\nlemma toSet_fromList_set[simp]:\n  \"toSet (fromList xs) = set xs\"\n  unfolding toSet_def fromList_def\n  by (simp add: toList_ODList)\n\nlemma toSet_inj[intro, simp]: \"inj toSet\"\n  apply (rule injI)\n  unfolding toSet_def\n  apply (case_tac x)\n  apply (case_tac y)\n  apply (auto iff: odlist_Abs_inject odlist_Abs_inverse sorted_distinct_set_unique)\n  done\n\nlemma toSet_eq_iff:\n  \"X = Y \\<longleftrightarrow> toSet X = toSet Y\"\n  by (blast dest: injD[OF toSet_inj])\n\nsubsubsection{* head *}\n\ndefinition\n  hd :: \"('a :: linorder) odlist \\<Rightarrow> 'a\"\nwhere\n  [code]: \"hd \\<equiv> List.hd \\<circ> toList\"\n\nlemma hd_toList: \"toList xs = y # ys \\<Longrightarrow> ODList.hd xs = y\"\n  unfolding hd_def by simp\n\nsubsubsection{* member *}\n\ndefinition\n  member :: \"('a :: linorder) odlist \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  [code]: \"member xs x \\<equiv> List.member (toList xs) x\"\n\nlemma member_toSet[iff]:\n  \"member xs x \\<longleftrightarrow>x \\<in> toSet xs\"\n  unfolding member_def toSet_def by (simp add: in_set_member)\n\nsubsubsection{* Filter *}\n\ndefinition\n  filter :: \"(('a :: linorder) \\<Rightarrow> bool) \\<Rightarrow> 'a odlist \\<Rightarrow> 'a odlist\"\nwhere\n  \"filter P xs \\<equiv> ODList (List.filter P (toList xs))\"\n\nlemma toList_filter[simp, code abstract]:\n  \"toList (filter P xs) = List.filter P (toList xs)\"\n  unfolding filter_def by (simp add: toList_ODList)\n\nlemma toSet_filter[simp]:\n  \"toSet (filter P xs) = { x \\<in> toSet xs . P x }\"\n  unfolding filter_def\n  apply simp\n  apply (simp add: toSet_def)\n  done\n\nsubsubsection{* All *}\n\ndefinition\n  odlist_all :: \"('a :: linorder \\<Rightarrow> bool) \\<Rightarrow> 'a odlist \\<Rightarrow> bool\"\nwhere\n  [code]: \"odlist_all P xs \\<equiv> list_all P (toList xs)\"\n\n\n\nlemma odlist_all_cong [fundef_cong]:\n  \"xs = ys \\<Longrightarrow> (\\<And>x. x \\<in> toSet ys \\<Longrightarrow> f x = g x) \\<Longrightarrow> odlist_all f xs = odlist_all g ys\"\n  by (simp add: odlist_all_iff)\n\nsubsubsection{* Difference *}\n\ndefinition\n  difference :: \"('a :: linorder) odlist \\<Rightarrow> 'a odlist \\<Rightarrow> 'a odlist\"\nwhere\n  \"difference xs ys = ODList (List_local.difference (toList xs) (toList ys))\"\n\nlemma toList_difference[simp, code abstract]:\n  \"toList (difference xs ys) = List_local.difference (toList xs) (toList ys)\"\n  unfolding difference_def by (simp add: toList_ODList)\n\nlemma toSet_difference[simp]:\n  \"toSet (difference xs ys) = toSet xs - toSet ys\"\n  unfolding difference_def\n  apply simp\n  apply (simp add: toSet_def)\n  done\n\nsubsubsection{* Intersection *}\n\ndefinition\n  intersect :: \"('a :: linorder) odlist \\<Rightarrow> 'a odlist \\<Rightarrow> 'a odlist\"\nwhere\n  \"intersect xs ys = ODList (List_local.intersection (toList xs) (toList ys))\"\n\nlemma toList_intersect[simp, code abstract]:\n  \"toList (intersect xs ys) = List_local.intersection (toList xs) (toList ys)\"\n  unfolding intersect_def by (simp add: toList_ODList)\n\n\n\nsubsubsection{* Union *}\n\ndefinition\n  union :: \"('a :: linorder) odlist \\<Rightarrow> 'a odlist \\<Rightarrow> 'a odlist\"\nwhere\n  \"union xs ys = ODList (merge (toList xs) (toList ys))\"\n\nlemma toList_union[simp, code abstract]:\n  \"toList (union xs ys) = merge (toList xs) (toList ys)\"\n  unfolding union_def by (simp add: toList_ODList)\n\nlemma toSet_union[simp]:\n  \"toSet (union xs ys) = toSet xs \\<union> toSet ys\"\n  unfolding union_def\n  apply simp\n  apply (simp add: toSet_def)\n  done\n\ndefinition\n  big_union :: \"('b \\<Rightarrow> ('a :: linorder) odlist) \\<Rightarrow> 'b list \\<Rightarrow> 'a odlist\"\nwhere\n  [code]: \"big_union f X \\<equiv> foldr (\\<lambda>a A. ODList.union (f a) A) X ODList.empty\"\n\nlemma toSet_big_union[simp]:\n  \"toSet (big_union f X) = (\\<Union>x \\<in> set X. toSet (f x))\"\nproof -\n  { fix X Y\n    have \"toSet (foldr (\\<lambda>x A. ODList.union (f x) A) X Y) = toSet Y \\<union> (\\<Union>x \\<in> set X. toSet (f x))\"\n      by (induct X arbitrary: Y) auto }\n   thus ?thesis\n     unfolding big_union_def by simp\nqed\n\nsubsubsection{* Case distinctions *}\n\ntext{*\n\nWe construct ODLists out of lists, so talk in terms of those, not a\none-step constructor we don't use.\n\n*}\n\nlemma distinct_sorted_induct [consumes 2, case_names Nil insert]:\n  assumes \"distinct xs\"\n  assumes \"sorted xs\"\n  assumes base: \"P []\"\n  assumes step: \"\\<And>x xs. \\<lbrakk> distinct (x # xs); sorted (x # xs); P xs \\<rbrakk> \\<Longrightarrow> P (x # xs)\"\n  shows \"P xs\"\nusing `distinct xs` `sorted xs` proof (induct xs)\n  case Nil from `P []` show ?case .\nnext\n  case (Cons x xs)\n  then have \"distinct (x # xs)\" and \"sorted (x # xs)\" and \"P xs\" by (simp_all add: sorted_Cons)\n  with step show \"P (x # xs)\" .\nqed\n\nlemma odlist_induct [case_names empty insert, cases type: odlist]:\n  assumes empty: \"\\<And>dxs. dxs = empty \\<Longrightarrow> P dxs\"\n  assumes insrt: \"\\<And>dxs x xs. \\<lbrakk> dxs = fromList (x # xs); distinct (x # xs); sorted (x # xs); P (fromList xs) \\<rbrakk>\n                            \\<Longrightarrow> P dxs\"\n  shows \"P dxs\"\nproof (cases dxs)\n  case (odlist_Abs xs)\n  then have dxs: \"dxs = ODList xs\" and distinct: \"distinct xs\" and sorted: \"sorted xs\"\n    by (simp_all add: ODList_def)\n  from `distinct xs` and `sorted xs` have \"P (ODList xs)\"\n  proof (induct xs rule: distinct_sorted_induct)\n    case Nil from empty show ?case by (simp add: empty_def)\n  next\n    case (insert x xs) thus ?case\n      apply -\n      apply (rule insrt)\n      apply (auto iff: sorted_Cons fromList_def)\n      done\n  qed\n  with dxs show \"P dxs\" by simp\nqed\n\nlemma odlist_cases [case_names empty insert, cases type: odlist]:\n  assumes empty: \"dxs = empty \\<Longrightarrow> P\"\n  assumes insert: \"\\<And>x xs. \\<lbrakk> dxs = fromList (x # xs); distinct (x # xs); sorted (x # xs) \\<rbrakk>\n                            \\<Longrightarrow> P\"\n  shows P\nproof (cases dxs)\n  case (odlist_Abs xs)\n  then have dxs: \"dxs = ODList xs\" and distinct: \"distinct xs\" and sorted: \"sorted xs\"\n    by (simp_all add: ODList_def)\n  show P proof (cases xs)\n    case Nil with dxs have \"dxs = empty\" by (simp add: empty_def)\n    with empty show P .\n  next\n    case (Cons y ys)\n    with dxs distinct sorted insert\n    show P by (simp add: fromList_def)\n  qed\nqed\n\nsubsubsection{* Relations *}\n\ntext{*\n\nRelations, represented as a list of pairs.\n\n*}\n\ntype_synonym 'a odrelation = \"('a \\<times> 'a) odlist\"\n\nsubsubsection{* Image *}\n\ntext{*\n\nThe output of @{term \"List_local.image\"} is not guaranteed to be\nordered or distinct. Also the relation need not be monomorphic.\n\n*}\n\ndefinition\n  image :: \"('a :: linorder \\<times> 'b :: linorder) odlist \\<Rightarrow> 'a odlist \\<Rightarrow> 'b odlist\"\nwhere\n  \"image R xs = ODList (List_local.image (toList R) (toList xs))\"\n\nlemma toList_image[simp, code abstract]:\n  \"toList (image R xs) = msort (List_local.image (toList R) (toList xs))\"\n  unfolding image_def by (simp add: toList_ODList)\n\nlemma toSet_image[simp]:\n  \"toSet (image R xs) = toSet R `` toSet xs\"\n  unfolding image_def by (simp add: toSet_def toList_ODList)\n\nsubsubsection{* Linear order *}\n\ntext{*\n\nLexicographic ordering on lists. Executable, unlike in List.thy.\n\n*}\n\ninstantiation odlist :: (linorder) linorder\nbegin\nprint_context\nfun\n  less_eq_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n  \"less_eq_list [] ys = True\"\n| \"less_eq_list xs [] = False\"\n| \"less_eq_list (x # xs) (y # ys) = (x < y \\<or> (x = y \\<and> less_eq_list xs ys))\"\n\nlemma less_eq_list_nil_inv:\n  fixes xs :: \"'a list\"\n  shows \"less_eq_list xs [] \\<Longrightarrow> xs = []\"\n  by (cases xs) simp_all\n\nlemma less_eq_list_cons_inv:\n  fixes x :: 'a\n  shows \"less_eq_list (x # xs) yys \\<Longrightarrow> \\<exists>y ys. yys = y # ys \\<and> (x < y \\<or> (x = y \\<and> less_eq_list xs ys))\"\n  by (cases yys) auto\n\nlemma less_eq_list_refl:\n  fixes xs :: \"'a list\"\n  shows \"less_eq_list xs xs\"\n  by (induct xs) simp_all\n\nlemma less_eq_list_trans:\n  fixes xs ys zs :: \"'a list\"\n  shows \"\\<lbrakk> less_eq_list xs ys; less_eq_list ys zs \\<rbrakk> \\<Longrightarrow> less_eq_list xs zs\"\n  apply (induct xs ys arbitrary: zs rule: less_eq_list.induct)\n    apply simp\n   apply simp\n  apply clarsimp\n  apply (erule disjE)\n   apply (drule less_eq_list_cons_inv)\n   apply clarsimp\n   apply (erule disjE)\n    apply auto[1]\n   apply auto[1]\n  apply (auto dest: less_eq_list_cons_inv)\n  done\n\nlemma less_eq_list_antisym:\n  fixes xs ys :: \"'a list\"\n  shows \"\\<lbrakk> less_eq_list xs ys; less_eq_list ys xs \\<rbrakk> \\<Longrightarrow> xs = ys\"\n  by (induct xs ys rule: less_eq_list.induct) (auto dest: less_eq_list_nil_inv)\n\nlemma less_eq_list_linear:\n  fixes xs ys :: \"'a list\"\n  shows \"less_eq_list xs ys \\<or> less_eq_list ys xs\"\n  by (induct xs ys rule: less_eq_list.induct) auto\n\ndefinition\n  less_eq_odlist :: \"'a odlist \\<Rightarrow> 'a odlist \\<Rightarrow> bool\"\nwhere\n  \"xs \\<le> ys \\<equiv> less_eq_list (toList xs) (toList ys)\"\n\nfun\n  less_list :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n  \"less_list [] [] = False\"\n| \"less_list [] ys = True\"\n| \"less_list xs [] = False\"\n| \"less_list (x # xs) (y # ys) = (x < y \\<or> (x = y \\<and> less_list xs ys))\"\n\ndefinition\n  less_odlist :: \"'a odlist \\<Rightarrow> 'a odlist \\<Rightarrow> bool\"\nwhere\n  \"xs < ys \\<equiv> less_list (toList xs) (toList ys)\"\n\nlemma less_eq_list_not_le:\n  fixes xs ys :: \"'a list\"\n  shows \"(less_list xs ys) = (less_eq_list xs ys \\<and> \\<not> less_eq_list ys xs)\"\n  by (induct xs ys rule: less_list.induct) auto\n\ninstance\n  apply intro_classes\n  unfolding less_eq_odlist_def less_odlist_def\n  using less_eq_list_not_le less_eq_list_refl less_eq_list_trans less_eq_list_antisym\n  apply blast\n  using less_eq_list_not_le less_eq_list_refl less_eq_list_trans less_eq_list_antisym\n  apply blast\n  using less_eq_list_not_le less_eq_list_refl less_eq_list_trans less_eq_list_antisym\n  apply blast\n  using less_eq_list_not_le less_eq_list_refl less_eq_list_trans less_eq_list_antisym\n  apply blast\n  apply (rule less_eq_list_linear)\n  done\n\nend\n\nsubsubsection{* Finite maps *}\n\ntext{*\n\nA few operations on finite maps.\n\nUnlike the AssocList theory, ODLists give us canonical\nrepresentations, so we can order them. Our tabulate has the wrong type\n(we want to take an odlist, not a list) so we can't use that\npart of the framework.\n\n*}\n\ndefinition\n  lookup :: \"('a :: linorder \\<times> 'b :: linorder) odlist \\<Rightarrow> ('a \\<rightharpoonup> 'b)\"\nwhere\n  [code]: \"lookup = map_of \\<circ> toList\"\n\ntext{* Specific to ODLists. *}\n\ndefinition\n  tabulate :: \"('a :: linorder) odlist \\<Rightarrow> ('a \\<Rightarrow> 'b :: linorder) \\<Rightarrow> ('a \\<times> 'b) odlist\"\nwhere\n  \"tabulate ks f = ODList (List.map (\\<lambda>k. (k, f k)) (toList ks))\"\n\ndefinition (in order) mono_on :: \"('a \\<Rightarrow> 'b\\<Colon>order) \\<Rightarrow> 'a set \\<Rightarrow> bool\" where\n  \"mono_on f X \\<longleftrightarrow> (\\<forall>x\\<in>X. \\<forall>y\\<in>X. x \\<le> y \\<longrightarrow> f x \\<le> f y)\"\n\nlemma (in order) mono_onI [intro?]:\n  fixes f :: \"'a \\<Rightarrow> 'b\\<Colon>order\"\n  shows \"(\\<And>x y. x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y) \\<Longrightarrow> mono_on f X\"\n  unfolding mono_on_def by simp\n\nlemma (in order) mono_onD [dest?]:\n  fixes f :: \"'a \\<Rightarrow> 'b\\<Colon>order\"\n  shows \"mono_on f X \\<Longrightarrow> x \\<in> X \\<Longrightarrow> y \\<in> X \\<Longrightarrow> x \\<le> y \\<Longrightarrow> f x \\<le> f y\"\n  unfolding mono_on_def by simp\n\nlemma (in order) mono_on_subset:\n  fixes f :: \"'a \\<Rightarrow> 'b\\<Colon>order\"\n  shows \"mono_on f X \\<Longrightarrow> Y \\<subseteq> X \\<Longrightarrow> mono_on f Y\"\n  unfolding mono_on_def by auto\n\nlemma sorted_mono_map:\n  \"\\<lbrakk> sorted xs; mono_on f (set xs) \\<rbrakk> \\<Longrightarrow> sorted (List.map f xs)\"\n  apply (induct xs)\n   apply simp\n  apply (simp add: sorted_Cons)\n  apply (cut_tac X=\"insert a (set xs)\" and Y=\"set xs\" in mono_on_subset)\n  apply (auto dest: mono_onD)\n  done\n\nlemma msort_map:\n  \"\\<lbrakk> distinct xs; sorted xs; inj_on f (set xs); mono_on f (set xs) \\<rbrakk> \\<Longrightarrow> msort (List.map f xs) = List.map f xs\"\n  apply (rule msort_idle)\n   apply (simp add: distinct_map)\n  apply (simp add: sorted_mono_map)\n  done\n\nlemma tabulate_toList[simp, code abstract]:\n  \"toList (tabulate ks f) = List.map (\\<lambda>k. (k, f k)) (toList ks)\"\n  unfolding tabulate_def\n  apply (simp add: toList_ODList)\n  apply (subst msort_map)\n  apply simp_all\n   apply (rule inj_onI)\n   apply simp\n  apply (rule mono_onI)\n  apply (simp add: less_eq_prod_def less_le)\n  done\n\nlemma lookup_tabulate[simp]:\n  \"lookup (tabulate ks f) = (Some o f) |` toSet ks\"\nproof(induct ks rule: odlist_induct)\n  case (empty dxs) thus ?case unfolding tabulate_def lookup_def by (simp add: toList_ODList)\nnext\n  case (insert dxs x xs)\n  from insert have \"map_of (List.map (\\<lambda>k. (k, f k)) xs) = map_of (msort (List.map (\\<lambda>k. (k, f k)) xs))\"\n    apply (subst msort_map)\n    apply (auto intro: inj_onI simp: sorted_Cons)\n    apply (rule mono_onI)\n    apply (simp add: less_eq_prod_def less_le)\n    done\n  also from insert have \"... = lookup (tabulate (fromList xs) f)\"\n    unfolding tabulate_def lookup_def\n    by (simp add: toList_ODList toList_fromList sorted_Cons)\n  also from insert have \"... = (Some \\<circ> f) |` toSet (fromList xs)\"\n    by (simp only: toSet_fromList_set)\n  finally have IH: \"map_of (List.map (\\<lambda>k. (k, f k)) xs) = (Some \\<circ> f) |` toSet (fromList xs)\" .\n  from insert have \"lookup (tabulate dxs f) = map_of (toList (ODList (List.map (\\<lambda>k. (k, f k)) (x # xs))))\"\n    unfolding tabulate_def lookup_def by (simp add: toList_fromList)\n  also have \"... = map_of (msort (List.map (\\<lambda>k. (k, f k)) (x # xs)))\"\n    by (simp only: toList_ODList)\n  also from insert have \"... = map_of (List.map (\\<lambda>k. (k, f k)) (x # xs))\"\n    apply (subst msort_map)\n    apply (auto intro: inj_onI)\n    apply (rule mono_onI)\n    apply (simp add: less_eq_prod_def less_le)\n    done\n  also with insert IH have \"... = (Some \\<circ> f) |` toSet dxs\"\n    by (auto simp add: restrict_map_def fun_eq_iff)\n  finally show ?case .\nqed\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/KBPs/ODList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.8774767810736693, "lm_q1q2_score": 0.757606090725806}}
{"text": "(*\n  File:     Periodic_Arithmetic.thy\n  Authors:  Rodrigo Raya, EPFL; Manuel Eberl, TUM\n\n  Periodic arithmetic functions\n*)\nsection \\<open>Periodic arithmetic functions\\<close>\ntheory Periodic_Arithmetic\nimports\n  Complex_Main\n  \"HOL-Number_Theory.Cong\"\nbegin\n\ndefinition \n  \"periodic_arithmetic f k = (\\<forall>n. f (n+k) = f n)\" \n  for n :: int and k :: nat and f :: \"nat \\<Rightarrow> complex\"\n\nlemma const_periodic_arithmetic: \"periodic_arithmetic (\\<lambda>x. y) k\"\n  unfolding periodic_arithmetic_def by blast\n\nlemma add_periodic_arithmetic:\n  fixes f g :: \"nat \\<Rightarrow> complex\"\n  assumes \"periodic_arithmetic f k\"\n  assumes \"periodic_arithmetic g k\"\n  shows \"periodic_arithmetic (\\<lambda>n. f n + g n) k\"\n  using assms unfolding periodic_arithmetic_def by simp\n\nlemma mult_periodic_arithmetic:\n  fixes f g :: \"nat \\<Rightarrow> complex\"\n  assumes \"periodic_arithmetic f k\"\n  assumes \"periodic_arithmetic g k\"\n  shows \"periodic_arithmetic (\\<lambda>n. f n * g n) k\"\n  using assms unfolding periodic_arithmetic_def  by simp\n\nlemma scalar_mult_periodic_arithmetic:\n  fixes f :: \"nat \\<Rightarrow> complex\" and a :: complex\n  assumes \"periodic_arithmetic f k\"\n  shows \"periodic_arithmetic (\\<lambda>n. a * f n) k\"\n  using mult_periodic_arithmetic[OF const_periodic_arithmetic[of a k] assms(1)] by simp\n\nlemma fin_sum_periodic_arithmetic_set:\n  fixes f g :: \"nat \\<Rightarrow> complex\" \n  assumes \"\\<forall>i\\<in>A. periodic_arithmetic (h i) k\"\n  shows \"periodic_arithmetic (\\<lambda>n. \\<Sum>i \\<in> A. h i n) k\"\n  using assms by (simp add: periodic_arithmetic_def)\n\nlemma mult_period:\n  assumes \"periodic_arithmetic g k\"\n  shows \"periodic_arithmetic g (k*q)\"\n  using assms\nproof (induction q)\n  case 0 then show ?case unfolding periodic_arithmetic_def by simp\nnext\n  case (Suc m)\n  then show ?case \n    unfolding periodic_arithmetic_def \n  proof -\n   { fix n \n     have \"g (n + k * Suc m) = g (n + k +  k * m)\"\n       by (simp add: algebra_simps)\n     also have \"\\<dots> = g(n)\" \n       using Suc.IH[OF Suc.prems] assms\n       unfolding periodic_arithmetic_def by simp\n     finally have \"g (n + k * Suc m) = g(n)\" by blast\n   }\n    then show \"\\<forall>n. g (n + k * Suc m) = g n\" by auto\n  qed   \nqed\n\nlemma unique_periodic_arithmetic_extension:\n  assumes \"k > 0\"\n  assumes \"\\<forall>j<k. g j = h j\"\n  assumes \"periodic_arithmetic g k\" and \"periodic_arithmetic h k\"\n  shows \"g i = h i\"\nproof (cases \"i < k\")\n  case True then show ?thesis using assms by simp\nnext\n  case False then show ?thesis \n  proof -\n    have \"k * (i div k) + (i mod k) = i \\<and> (i mod k) < k\" \n      by (simp add: assms(1) algebra_simps)\n    then obtain q r where euclid_div: \"k*q + r = i \\<and> r < k\"\n      using mult.commute by blast\n    from assms(3) assms(4) \n    have  \"periodic_arithmetic g (k*q)\" \"periodic_arithmetic h (k*q)\" \n      using mult_period by simp+\n    have \"g(k*q+r) = g(r)\" \n      using \\<open>periodic_arithmetic g (k*q)\\<close> unfolding periodic_arithmetic_def \n      using add.commute[of \"k*q\" r] by presburger\n    also have \"\\<dots> = h(r)\" \n      using euclid_div assms(2) by simp\n    also have \"\\<dots> = h(k*q+r)\"\n      using \\<open>periodic_arithmetic h (k*q)\\<close> add.commute[of \"k*q\" r]\n      unfolding periodic_arithmetic_def by presburger\n    also have \"\\<dots> = h(i)\" using euclid_div by simp\n    finally show \"g(i) = h(i)\" using euclid_div by simp\n  qed\nqed\n                  \nlemma periodic_arithmetic_sum_periodic_arithmetic:\n  assumes \"periodic_arithmetic f k\"\n  shows \"(\\<Sum>l \\<in> {m..n}. f l) = (\\<Sum>l \\<in> {m+k..n+k}. f l)\"\n  using periodic_arithmetic_def assms \n  by (intro sum.reindex_bij_witness\n         [of \"{m..n}\" \"\\<lambda>l. l-k\" \"\\<lambda>l. l+k\" \"{m+k..n+k}\" f f])\n      auto\n\nlemma mod_periodic_arithmetic:\n  fixes n m :: nat\n  assumes \"periodic_arithmetic f k\"\n  assumes \"n mod k = m mod k\"\n  shows \"f n = f m\"\nproof -\n  obtain q where 1: \"n = q*k+(n mod k)\"   \n     using div_mult_mod_eq[of n k,symmetric] by blast \n  obtain q' where 2: \"m = q'*k+(m mod k)\"\n     using div_mult_mod_eq[of m k,symmetric] by blast\n  from 1 have \"f n = f (q*k+(n mod k))\" by auto\n  also have \"\\<dots> = f (n mod k)\"\n    using mult_period[of f k q] assms(1) periodic_arithmetic_def[of f \"k*q\"]\n    by (simp add: algebra_simps,subst add.commute,blast)\n  also have \"\\<dots> = f (m mod k)\" using assms(2) by auto\n  also have \"\\<dots> = f (q'*k+(m mod k))\"\n    using mult_period[of f k q'] assms(1) periodic_arithmetic_def[of f \"k*q'\"]\n    by (simp add: algebra_simps,subst add.commute,presburger)\n  also have \"\\<dots> = f m\" using 2 by auto\n  finally show \"f n = f m\" by simp\nqed\n\nlemma cong_periodic_arithmetic:\n  assumes \"periodic_arithmetic f k\" \"[a = b] (mod k)\"\n  shows   \"f a = f b\"\n  using assms mod_periodic_arithmetic[of f k a b] by (auto simp: cong_def)\n\nlemma cong_nat_imp_eq:\n  fixes m :: nat\n  assumes \"m > 0\" \"x \\<in> {a..<a+m}\" \"y \\<in> {a..<a+m}\" \"[x = y] (mod m)\"\n  shows   \"x = y\"\n  using assms\nproof (induction x y rule: linorder_wlog)\n  case (le x y)\n  have \"[y - x = 0] (mod m)\"\n    using cong_diff_iff_cong_0_nat cong_sym le by blast\n  thus \"x = y\"\n    using le by (auto simp: cong_def)\nqed (auto simp: cong_sym)\n\nlemma inj_on_mod_nat:\n  fixes m :: nat\n  assumes \"m > 0\"\n  shows   \"inj_on (\\<lambda>x. x mod m) {a..<a+m}\"\nproof\n  fix x y assume xy: \"x \\<in> {a..<a+m}\" \"y \\<in> {a..<a+m}\" and eq: \"x mod m = y mod m\"\n  from \\<open>m > 0\\<close> and xy show \"x = y\"\n    by (rule cong_nat_imp_eq) (use eq in \\<open>simp_all add: cong_def\\<close>)\nqed\n\nlemma bij_betw_mod_nat_atLeastLessThan:\n  fixes k d :: nat\n  assumes \"k > 0\"\n  defines \"g \\<equiv> (\\<lambda>i. nat ((int i - int d) mod int k) + d)\"\n  shows   \"bij_betw (\\<lambda>i. i mod k) {d..<d+k} {..<k}\"\n  unfolding bij_betw_def\nproof\n  show inj: \"inj_on (\\<lambda>i. i mod k) {d..<d + k}\"\n    by (rule inj_on_mod_nat) fact+\n  have \"(\\<lambda>i. i mod k) ` {d..<d + k} \\<subseteq> {..<k}\"\n    by auto\n  moreover have \"card ((\\<lambda>i. i mod k) ` {d..<d + k}) = card {..<k}\"\n    using inj by (subst card_image) auto\n  ultimately show \"(\\<lambda>i. i mod k) ` {d..<d + k} = {..<k}\"\n    by (intro card_subset_eq) auto\nqed\n\nlemma periodic_arithmetic_sum_periodic_arithmetic_shift:\n  fixes k d :: nat\n  assumes \"periodic_arithmetic f k\" \"k > 0\" \"d > 0\"\n  shows \"(\\<Sum>l \\<in> {0..k-1}. f l) = (\\<Sum>l \\<in> {d..d+k-1}. f l)\"\nproof -\n  have \"(\\<Sum>l \\<in> {0..k-1}. f l) = (\\<Sum>l \\<in> {0..<k}. f l)\"\n    using assms(2) by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>l \\<in> {d..<d+k}. f (l mod k))\"\n    using assms(2) \n    by (simp add: sum.reindex_bij_betw[OF bij_betw_mod_nat_atLeastLessThan[of k d]] \n                  lessThan_atLeast0)\n  also have \"\\<dots> = (\\<Sum>l \\<in> {d..<d+k}. f l)\"\n    using mod_periodic_arithmetic[of f k] assms(1) sum.cong\n    by (meson mod_mod_trivial)\n  also have \"\\<dots> = (\\<Sum>l \\<in> {d..d+k-1}. f l)\"\n    using assms(2,3) by (intro sum.cong) auto\n  finally show ?thesis by auto\nqed\n\nlemma self_bij_0_k:\n  fixes a k :: nat\n  assumes \"coprime a k\" \"[a*i = 1] (mod k)\" \"k > 0\" \n  shows \"bij_betw (\\<lambda>r. r*a mod k) {0..k-1} {0..k-1}\"\n  unfolding bij_betw_def\nproof\n  show \"inj_on (\\<lambda>r. r*a mod k) {0..k-1}\"\n  proof -\n    {fix r1 r2\n    assume in_k: \"r1 \\<in> {0..k-1}\" \"r2 \\<in> {0..k-1}\"\n    assume as: \"[r1*a = r2*a] (mod k)\"\n    then have \"[r1*a*i = r2*a*i] (mod k)\" \n      using cong_scalar_right by blast\n    then have \"[r1 = r2] (mod k)\" \n      using cong_mult_rcancel_nat as assms(1) by simp\n    then have \"r1 = r2\" using in_k\n      using assms(3) cong_less_modulus_unique_nat by auto}\n    note eq = this\n    show ?thesis unfolding inj_on_def \n      by (safe, simp add: eq cong_def)\n  qed\n  define f where \"f = (\\<lambda>r. r * a mod k)\"\n  show \"f ` {0..k - 1} = {0..k - 1} \"\n    unfolding image_def\n  proof (standard)\n    show \"{y. \\<exists>x\\<in>{0..k - 1}. y = f x} \\<subseteq> {0..k - 1}\" \n    proof -\n      {fix y\n      assume \"y \\<in> {y. \\<exists>x\\<in>{0..k - 1}. y = f x}\" \n      then obtain x where \"y = f x\" by blast\n      then have \"y \\<in> {0..k-1}\"\n        unfolding f_def\n        using Suc_pred assms(3) lessThan_Suc_atMost by fastforce}\n      then show ?thesis by blast\n    qed\n    show \"{0..k - 1} \\<subseteq> {y. \\<exists>x\\<in>{0..k - 1}. y = f x}\"\n    proof -\n      { fix x \n        assume ass: \"x \\<in> {0..k-1}\"\n        then have \"x * i mod k \\<in> {0..k-1}\"\n        proof -\n          have \"x * i mod k \\<in> {0..<k}\" by (simp add: assms(3))\n          have \"{0..<k} = {0..k-1}\" using Suc_diff_1 assms(3) by auto\n          show ?thesis using \\<open>x * i mod k \\<in> {0..<k}\\<close> \\<open>{0..<k} = {0..k-1}\\<close> by blast\n        qed          \n        then have \"f (x * i mod k) = x\"\n        proof -\n          have \"f (x * i mod k) = (x * i mod k) * a mod k\"\n            unfolding f_def by blast\n          also have \"\\<dots> = (x*i*a) mod k\" \n            by (simp add: mod_mult_left_eq) \n          also have \"\\<dots> = (x*1) mod k\" \n            using assms(2) \n            unfolding cong_def \n            by (subst mult.assoc, subst (2) mult.commute,\n               subst mod_mult_right_eq[symmetric],simp) \n          also have \"\\<dots> = x\" using ass assms(3) by auto\n          finally show ?thesis .\n        qed\n        then have \"x \\<in> {y. \\<exists>x\\<in>{0..k - 1}. y = f x}\" \n          using \\<open>x * i mod k \\<in> {0..k-1}\\<close> by force\n      }\n      then show ?thesis by blast \n    qed\n  qed\nqed\n\nlemma periodic_arithmetic_homothecy:\n  assumes \"periodic_arithmetic f k\"\n  shows   \"periodic_arithmetic (\\<lambda>l. f (l*a)) k\"\n  unfolding periodic_arithmetic_def\nproof \n  fix n\n  have \"f ((n + k) * a) = f(n*a+k*a)\" by (simp add: algebra_simps)\n  also have \"\\<dots> = f(n*a)\" \n    using mult_period[OF assms] unfolding periodic_arithmetic_def by simp\n  finally show \"f ((n + k) * a) = f (n * a)\" by simp\nqed\n\ntheorem periodic_arithmetic_remove_homothecy:\n  assumes \"coprime a k\" \"periodic_arithmetic f k\" \"k > 0\" \n  shows \"(\\<Sum>l=1..k. f l) = (\\<Sum>l=1..k. f (l*a))\" \nproof -\n  obtain i where inv: \"[a*i = 1] (mod k)\"\n    using assms(1) coprime_iff_invertible_nat[of a k] by auto\n  from this self_bij_0_k assms\n  have bij: \"bij_betw (\\<lambda>r. r * a mod k) {0..k - 1} {0..k - 1}\" by blast\n  \n  have \"(\\<Sum>l = 1..k. f(l)) = (\\<Sum>l = 0..k-1. f(l))\"\n    using periodic_arithmetic_sum_periodic_arithmetic_shift[of f k 1] assms by simp\n  also have \"\\<dots> = (\\<Sum>l = 0..k-1. f(l*a mod k))\"\n    using sum.reindex_bij_betw[OF bij,symmetric] by blast\n  also have \"\\<dots> = (\\<Sum>l = 0..k-1. f(l*a))\"\n    by (intro sum.cong refl) (use mod_periodic_arithmetic[OF assms(2)] mod_mod_trivial in blast)\n  also have \"\\<dots> = (\\<Sum>l = 1..k. f(l*a))\"\n    using periodic_arithmetic_sum_periodic_arithmetic_shift[of \"(\\<lambda>l. f(l*a))\" k 1]\n          periodic_arithmetic_homothecy[OF assms(2)] assms(3) by fastforce  \n  finally show ?thesis by blast     \nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Gauss_Sums/Periodic_Arithmetic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.8539127492339907, "lm_q1q2_score": 0.7575953239408237}}
{"text": "theory \"chapter3\"\n  imports Main\nbegin\n\ntype_synonym vname = string\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n  \"aval (N n) s = n\" |\n  \"aval (V x) s = s x\" |\n  \"aval (Plus a1 a2) s = aval a1 s + aval a2 s\"\n\nvalue \"aval (Plus (N 3) (V ''x'')) (\\<lambda>x. 0)\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n  \"asimp_const (N n) = N n\" |\n  \"asimp_const (V x) = V x\" |\n  \"asimp_const (Plus a1 a2) =\n    (case (asimp_const a1, asimp_const a2) of\n      (N n1, N n2) \\<Rightarrow> N (n1 + n2) |\n      (b1, b2) \\<Rightarrow> Plus b1 b2)\"\n\n(* asimp_const preserves evaluation *)\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply (induction a)\n  apply (auto split: aexp.split)\n  done\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  \"plus (N n1) (N n2) = N (n1 + n2)\" |\n  \"plus (N n) a = (if n = 0 then a else Plus (N n) a)\" |\n  \"plus a (N n) = (if n = 0 then a else Plus a (N n))\" |\n  \"plus a1 a2 = Plus a1 a2\"\n\nlemma aval_plus: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction a1 rule: plus.induct)\n  apply (induction a2 rule: plus.induct)\n  apply auto\n  done\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n  \"asimp (N n) = N n\" |\n  \"asimp (V x) = V x\" |\n  \"asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)\"\n\n(* asimp preserves evaluation *)\nlemma \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n  apply (auto simp: aval_plus)\n  done\n\n(* 3.1 *)\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n  \"optimal (N n) = True\" |\n  \"optimal (V x) = True\" |\n  \"optimal (Plus (N n1) (N n2)) = False\" |\n  \"optimal (Plus a1 a2) = ((optimal a1) \\<and> (optimal a2))\"\n\ntheorem asimp_const_optimal: \"optimal (asimp_const a)\"\n  apply (induction a)\n  apply (auto split: aexp.split)\n  done\n\n(* 3.2 *)\nfun var_aexp :: \"aexp \\<Rightarrow> aexp option\" where\n  \"var_aexp (N n) = None\" |\n  \"var_aexp (V x) = Some (V x)\" |\n  \"var_aexp (Plus a1 a2) =\n    (case (var_aexp a1, var_aexp a2) of\n      (None, None) \\<Rightarrow> None |\n      (Some b1, None) \\<Rightarrow> Some b1 |\n      (None, Some b2) \\<Rightarrow> Some b2 |\n      (Some b1, Some b2) \\<Rightarrow> Some (Plus b1 b2))\"\n\nfun fold_consts :: \"aexp \\<Rightarrow> aexp option\" where\n  \"fold_consts (N n) = Some (N n)\" |\n  \"fold_consts (V x) = None\" |\n  \"fold_consts (Plus a1 a2) = \n    (case (fold_consts a1, fold_consts a2) of\n      (None, None) \\<Rightarrow> None |\n      (Some (N n1), None) \\<Rightarrow> Some (N n1) |\n      (None, Some (N n2)) \\<Rightarrow> Some (N n2) |\n      (Some (N n1), Some (N n2)) \\<Rightarrow> Some (N (n1 + n2)))\"\n\nlemma \"var_aexp a = None \\<Longrightarrow> fold_consts a \\<noteq> None\"\n  apply (induction a)\n  apply auto\n  apply (case_tac \"var_aexp a1\", case_tac \"var_aexp a2\")\n  apply auto\n  oops\n\n(*\nproof (prove)\ngoal (2 subgoals):\n 1. \\<And>a1 a2 y ya.\n       var_aexp a1 = None \\<Longrightarrow>\n       var_aexp a2 = None \\<Longrightarrow>\n       fold_consts a1 = Some y \\<Longrightarrow>\n       fold_consts a2 = Some ya \\<Longrightarrow>\n       \\<exists>ya. (case y of\n             N n1 \\<Rightarrow>\n               case fold_consts a2 of None \\<Rightarrow> Some (N n1)\n               | Some (N n2) \\<Rightarrow> Some (N (n1 + n2))) =\n            Some ya\n 2. \\<And>a1 a2 a.\n       (var_aexp a2 = None \\<Longrightarrow> \\<exists>y. fold_consts a2 = Some y) \\<Longrightarrow>\n       (case var_aexp a2 of None \\<Rightarrow> Some a | Some b2 \\<Rightarrow> Some (Plus a b2)) = None \\<Longrightarrow>\n       var_aexp a1 = Some a \\<Longrightarrow>\n       \\<exists>y. (case fold_consts a1 of\n            None \\<Rightarrow> case fold_consts a2 of None \\<Rightarrow> None | Some (N n2) \\<Rightarrow> Some (N n2)\n            | Some (N n1) \\<Rightarrow>\n                case fold_consts a2 of None \\<Rightarrow> Some (N n1)\n                | Some (N n2) \\<Rightarrow> Some (N (n1 + n2))) =\n           Some y\n*)\n\nlemma \"fold_consts a = None \\<Longrightarrow> var_aexp a \\<noteq> None\"\n  oops\n\nlemma \"var_aexp a = None \\<Longrightarrow> fold_consts a = None \\<Longrightarrow> False\"\n  apply (induction a)\n  oops\n\n(* Acts like Plus but handles optional aexps *)\nfun merge_aexps :: \"aexp option \\<Rightarrow> aexp option \\<Rightarrow> aexp\" where\n  \"merge_aexps None None = (N 0)\" |\n  \"merge_aexps None (Some n) = n\" |\n  \"merge_aexps (Some a) None = a\" |\n  \"merge_aexps (Some a) (Some n) = Plus a n\"\n\nlemma \"aval a s = aval (merge_aexps (var_aexp a) (fold_consts a)) s\"\n  apply (induction a)\n  apply auto\n  oops\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n  \"full_asimp (N n) = N n\" |\n  \"full_asimp (V x) = V x\" |\n  \"full_asimp (Plus a1 a2) = merge_aexps (var_aexp (Plus a1 a2)) (fold_consts (Plus a1 a2))\"\n\nlemma \"aval (full_asimp a) s = aval a s\"\n  apply (induction a)\n  apply (auto split: aexp.split)\n  oops\n\n(*\nfun full_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n  (* Ways to combine two constants *)\n  \"full_plus (N n1) (N n2) = N (n1 + n2)\" |\n  \"full_plus (Plus (N n1) a) (N n2) = Plus a (N (n1 + n2))\" |\n  \"full_plus (Plus a (N n1)) (N n2) = Plus a (N (n1 + n2))\" |\n  \"full_plus (N n1) (Plus (N n2) a) = Plus a (N (n1 + n2))\" |\n  \"full_plus (N n1) (Plus a (N n2)) = Plus a (N (n1 + n2))\" |\n  (* Ways to shift constants right *)\n  \"full_plus (Plus a1 (N n1)) a2 = Plus (Plus a1 a2) (N n1)\" |\n  \"full_plus a1 (Plus a2 (N n1)) = Plus (Plus a1 a2) (N n1)\" |\n  \"full_plus (Plus (N n1) a1) (Plus (N n2) a2) = Plus (Plus a1 a2) (N (n1 + n2))\" |\n  (* Everything else *)\n  \"full_plus a1 a2 = Plus a1 a2\"\n\nlemma aval_full_plus: \"aval (full_plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction rule: full_plus.induct)\n  apply auto\n  done\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n  \"full_asimp (N n) = N n\" |\n  \"full_asimp (V x) = V x\" |\n  \"full_asimp (Plus a1 a2) = full_plus (full_asimp a1) (full_asimp a2)\"\n\nvalue \"full_asimp (Plus (N 1) (Plus (V ''x'') (N 2)))\"\nvalue \"full_asimp (Plus (N (- 2)) (Plus (N (- 1)) (V [])))\"\n\nlemma \"aval (full_asimp a) s = aval a s\"\n  apply (induction a)\n  apply (auto simp: aval_full_plus)\n  done\n*)\n\n(* Great, we preserved that it doesn't change evaluation, but can we\n  prove that it's also optimal?  *)\n\nfun count_n :: \"aexp \\<Rightarrow> int\" where\n  \"count_n (N n) = 1\" |\n  \"count_n (V x) = 0\" |\n  \"count_n (Plus a1 a2) = (count_n a1) + (count_n a2)\"\n\n(* Adding more cases to full_plus is making the evaluation take awhile. There has\n  to be a better way to write the simplification rules for full_plus. *)\ntheorem full_asimp_optimal: \"count_n (full_asimp a) \\<le> 1\"\n  oops\n\nend", "meta": {"author": "nnooney", "repo": "isabelle-theories", "sha": "194126c8eaca0c87e9e714bf7be7e0b1b9a448be", "save_path": "github-repos/isabelle/nnooney-isabelle-theories", "path": "github-repos/isabelle/nnooney-isabelle-theories/isabelle-theories-194126c8eaca0c87e9e714bf7be7e0b1b9a448be/concrete-semantics/chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183444, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7575606710492708}}
{"text": "(*  Title:      HOL/Word/Bits_Int.thy\n    Author:     Jeremy Dawson and Gerwin Klein, NICTA\n\nDefinitions and basic theorems for bit-wise logical operations\nfor integers expressed using Pls, Min, BIT,\nand converting them to and from lists of bools.\n*)\n\nsection \\<open>Bitwise Operations on integers\\<close>\n\ntheory Bits_Int\n  imports Bits Misc_Auxiliary\nbegin\n\nsubsection \\<open>Implicit bit representation of \\<^typ>\\<open>int\\<close>\\<close>\n\ndefinition Bit :: \"int \\<Rightarrow> bool \\<Rightarrow> int\"  (infixl \"BIT\" 90)\n  where \"k BIT b = (if b then 1 else 0) + k + k\"\n\nlemma Bit_B0: \"k BIT False = k + k\"\n   by (simp add: Bit_def)\n\nlemma Bit_B1: \"k BIT True = k + k + 1\"\n   by (simp add: Bit_def)\n\nlemma Bit_B0_2t: \"k BIT False = 2 * k\"\n  by (rule trans, rule Bit_B0) simp\n\nlemma Bit_B1_2t: \"k BIT True = 2 * k + 1\"\n  by (rule trans, rule Bit_B1) simp\n\nlemma uminus_Bit_eq:\n  \"- k BIT b = (- k - of_bool b) BIT b\"\n  by (cases b) (simp_all add: Bit_def)\n\nlemma power_BIT: \"2 ^ Suc n - 1 = (2 ^ n - 1) BIT True\"\n  by (simp add: Bit_B1)\n\ndefinition bin_last :: \"int \\<Rightarrow> bool\"\n  where \"bin_last w \\<longleftrightarrow> w mod 2 = 1\"\n\nlemma bin_last_odd: \"bin_last = odd\"\n  by (rule ext) (simp add: bin_last_def even_iff_mod_2_eq_zero)\n\ndefinition bin_rest :: \"int \\<Rightarrow> int\"\n  where \"bin_rest w = w div 2\"\n\nlemma bin_rl_simp [simp]: \"bin_rest w BIT bin_last w = w\"\n  unfolding bin_rest_def bin_last_def Bit_def\n  by (cases \"w mod 2 = 0\") (use div_mult_mod_eq [of w 2] in simp_all)\n\nlemma bin_rest_BIT [simp]: \"bin_rest (x BIT b) = x\"\n  unfolding bin_rest_def Bit_def\n  by (cases b) simp_all\n\nlemma bin_last_BIT [simp]: \"bin_last (x BIT b) = b\"\n  unfolding bin_last_def Bit_def\n  by (cases b) simp_all\n\nlemma BIT_eq_iff [iff]: \"u BIT b = v BIT c \\<longleftrightarrow> u = v \\<and> b = c\"\n  by (auto simp: Bit_def) arith+\n\nlemma BIT_bin_simps [simp]:\n  \"numeral k BIT False = numeral (Num.Bit0 k)\"\n  \"numeral k BIT True = numeral (Num.Bit1 k)\"\n  \"(- numeral k) BIT False = - numeral (Num.Bit0 k)\"\n  \"(- numeral k) BIT True = - numeral (Num.BitM k)\"\n  unfolding numeral.simps numeral_BitM\n  by (simp_all add: Bit_def del: arith_simps add_numeral_special diff_numeral_special)\n\nlemma BIT_special_simps [simp]:\n  shows \"0 BIT False = 0\"\n    and \"0 BIT True = 1\"\n    and \"1 BIT False = 2\"\n    and \"1 BIT True = 3\"\n    and \"(- 1) BIT False = - 2\"\n    and \"(- 1) BIT True = - 1\"\n  by (simp_all add: Bit_def)\n\nlemma Bit_eq_0_iff: \"w BIT b = 0 \\<longleftrightarrow> w = 0 \\<and> \\<not> b\"\n  by (auto simp: Bit_def) arith\n\nlemma Bit_eq_m1_iff: \"w BIT b = -1 \\<longleftrightarrow> w = -1 \\<and> b\"\n  by (auto simp: Bit_def) arith\n\nlemma BitM_inc: \"Num.BitM (Num.inc w) = Num.Bit1 w\"\n  by (induct w) simp_all\n\nlemma expand_BIT:\n  \"numeral (Num.Bit0 w) = numeral w BIT False\"\n  \"numeral (Num.Bit1 w) = numeral w BIT True\"\n  \"- numeral (Num.Bit0 w) = (- numeral w) BIT False\"\n  \"- numeral (Num.Bit1 w) = (- numeral (w + Num.One)) BIT True\"\n  by (simp_all add: add_One BitM_inc)\n\nlemma bin_last_numeral_simps [simp]:\n  \"\\<not> bin_last 0\"\n  \"bin_last 1\"\n  \"bin_last (- 1)\"\n  \"bin_last Numeral1\"\n  \"\\<not> bin_last (numeral (Num.Bit0 w))\"\n  \"bin_last (numeral (Num.Bit1 w))\"\n  \"\\<not> bin_last (- numeral (Num.Bit0 w))\"\n  \"bin_last (- numeral (Num.Bit1 w))\"\n  by (simp_all add: bin_last_def zmod_zminus1_eq_if)\n\nlemma bin_rest_numeral_simps [simp]:\n  \"bin_rest 0 = 0\"\n  \"bin_rest 1 = 0\"\n  \"bin_rest (- 1) = - 1\"\n  \"bin_rest Numeral1 = 0\"\n  \"bin_rest (numeral (Num.Bit0 w)) = numeral w\"\n  \"bin_rest (numeral (Num.Bit1 w)) = numeral w\"\n  \"bin_rest (- numeral (Num.Bit0 w)) = - numeral w\"\n  \"bin_rest (- numeral (Num.Bit1 w)) = - numeral (w + Num.One)\"\n  by (simp_all add: bin_rest_def zdiv_zminus1_eq_if)\n\nlemma less_Bits: \"v BIT b < w BIT c \\<longleftrightarrow> v < w \\<or> v \\<le> w \\<and> \\<not> b \\<and> c\"\n  by (auto simp: Bit_def)\n\nlemma le_Bits: \"v BIT b \\<le> w BIT c \\<longleftrightarrow> v < w \\<or> v \\<le> w \\<and> (\\<not> b \\<or> c)\"\n  by (auto simp: Bit_def)\n\nlemma pred_BIT_simps [simp]:\n  \"x BIT False - 1 = (x - 1) BIT True\"\n  \"x BIT True - 1 = x BIT False\"\n  by (simp_all add: Bit_B0_2t Bit_B1_2t)\n\nlemma succ_BIT_simps [simp]:\n  \"x BIT False + 1 = x BIT True\"\n  \"x BIT True + 1 = (x + 1) BIT False\"\n  by (simp_all add: Bit_B0_2t Bit_B1_2t)\n\nlemma add_BIT_simps [simp]:\n  \"x BIT False + y BIT False = (x + y) BIT False\"\n  \"x BIT False + y BIT True = (x + y) BIT True\"\n  \"x BIT True + y BIT False = (x + y) BIT True\"\n  \"x BIT True + y BIT True = (x + y + 1) BIT False\"\n  by (simp_all add: Bit_B0_2t Bit_B1_2t)\n\nlemma mult_BIT_simps [simp]:\n  \"x BIT False * y = (x * y) BIT False\"\n  \"x * y BIT False = (x * y) BIT False\"\n  \"x BIT True * y = (x * y) BIT False + y\"\n  by (simp_all add: Bit_B0_2t Bit_B1_2t algebra_simps)\n\nlemma B_mod_2': \"X = 2 \\<Longrightarrow> (w BIT True) mod X = 1 \\<and> (w BIT False) mod X = 0\"\n  by (simp add: Bit_B0 Bit_B1)\n\nlemma bin_ex_rl: \"\\<exists>w b. w BIT b = bin\"\n  by (metis bin_rl_simp)\n\nlemma bin_exhaust: \"(\\<And>x b. bin = x BIT b \\<Longrightarrow> Q) \\<Longrightarrow> Q\"\nby (metis bin_ex_rl)\n\nlemma bin_abs_lem: \"bin = (w BIT b) \\<Longrightarrow> bin \\<noteq> -1 \\<longrightarrow> bin \\<noteq> 0 \\<longrightarrow> nat \\<bar>w\\<bar> < nat \\<bar>bin\\<bar>\"\n  apply clarsimp\n  apply (unfold Bit_def)\n  apply (cases b)\n   apply (clarsimp, arith)\n  apply (clarsimp, arith)\n  done\n\nlemma bin_induct:\n  assumes PPls: \"P 0\"\n    and PMin: \"P (- 1)\"\n    and PBit: \"\\<And>bin bit. P bin \\<Longrightarrow> P (bin BIT bit)\"\n  shows \"P bin\"\n  apply (rule_tac P=P and a=bin and f1=\"nat \\<circ> abs\" in wf_measure [THEN wf_induct])\n  apply (simp add: measure_def inv_image_def)\n  apply (case_tac x rule: bin_exhaust)\n  apply (frule bin_abs_lem)\n  apply (auto simp add : PPls PMin PBit)\n  done\n\nlemma Bit_div2 [simp]: \"(w BIT b) div 2 = w\"\n  unfolding bin_rest_def [symmetric] by (rule bin_rest_BIT)\n\nlemma bin_rl_eqI: \"\\<lbrakk>bin_rest x = bin_rest y; bin_last x = bin_last y\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (metis (mono_tags) BIT_eq_iff bin_ex_rl bin_last_BIT bin_rest_BIT)\n\nlemma twice_conv_BIT: \"2 * x = x BIT False\"\n  by (rule bin_rl_eqI) (simp_all, simp_all add: bin_rest_def bin_last_def)\n\nlemma BIT_lt0 [simp]: \"x BIT b < 0 \\<longleftrightarrow> x < 0\"\nby(cases b)(auto simp add: Bit_def)\n\nlemma BIT_ge0 [simp]: \"x BIT b \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0\"\nby(cases b)(auto simp add: Bit_def)\n\n\n\nlemma bin_rest_gt_0 [simp]: \"bin_rest x > 0 \\<longleftrightarrow> x > 1\"\nby(simp add: bin_rest_def add1_zle_eq pos_imp_zdiv_pos_iff) (metis add1_zle_eq one_add_one)\n\n\nsubsection \\<open>Explicit bit representation of \\<^typ>\\<open>int\\<close>\\<close>\n\nprimrec bl_to_bin_aux :: \"bool list \\<Rightarrow> int \\<Rightarrow> int\"\n  where\n    Nil: \"bl_to_bin_aux [] w = w\"\n  | Cons: \"bl_to_bin_aux (b # bs) w = bl_to_bin_aux bs (w BIT b)\"\n\ndefinition bl_to_bin :: \"bool list \\<Rightarrow> int\"\n  where \"bl_to_bin bs = bl_to_bin_aux bs 0\"\n\nprimrec bin_to_bl_aux :: \"nat \\<Rightarrow> int \\<Rightarrow> bool list \\<Rightarrow> bool list\"\n  where\n    Z: \"bin_to_bl_aux 0 w bl = bl\"\n  | Suc: \"bin_to_bl_aux (Suc n) w bl = bin_to_bl_aux n (bin_rest w) ((bin_last w) # bl)\"\n\ndefinition bin_to_bl :: \"nat \\<Rightarrow> int \\<Rightarrow> bool list\"\n  where \"bin_to_bl n w = bin_to_bl_aux n w []\"\n\nlemma bin_to_bl_aux_zero_minus_simp [simp]:\n  \"0 < n \\<Longrightarrow> bin_to_bl_aux n 0 bl = bin_to_bl_aux (n - 1) 0 (False # bl)\"\n  by (cases n) auto\n\nlemma bin_to_bl_aux_minus1_minus_simp [simp]:\n  \"0 < n \\<Longrightarrow> bin_to_bl_aux n (- 1) bl = bin_to_bl_aux (n - 1) (- 1) (True # bl)\"\n  by (cases n) auto\n\nlemma bin_to_bl_aux_one_minus_simp [simp]:\n  \"0 < n \\<Longrightarrow> bin_to_bl_aux n 1 bl = bin_to_bl_aux (n - 1) 0 (True # bl)\"\n  by (cases n) auto\n\nlemma bin_to_bl_aux_Bit_minus_simp [simp]:\n  \"0 < n \\<Longrightarrow> bin_to_bl_aux n (w BIT b) bl = bin_to_bl_aux (n - 1) w (b # bl)\"\n  by (cases n) auto\n\nlemma bin_to_bl_aux_Bit0_minus_simp [simp]:\n  \"0 < n \\<Longrightarrow>\n    bin_to_bl_aux n (numeral (Num.Bit0 w)) bl = bin_to_bl_aux (n - 1) (numeral w) (False # bl)\"\n  by (cases n) auto\n\nlemma bin_to_bl_aux_Bit1_minus_simp [simp]:\n  \"0 < n \\<Longrightarrow>\n    bin_to_bl_aux n (numeral (Num.Bit1 w)) bl = bin_to_bl_aux (n - 1) (numeral w) (True # bl)\"\n  by (cases n) auto\n\nlemma bl_to_bin_aux_append: \"bl_to_bin_aux (bs @ cs) w = bl_to_bin_aux cs (bl_to_bin_aux bs w)\"\n  by (induct bs arbitrary: w) auto\n\nlemma bin_to_bl_aux_append: \"bin_to_bl_aux n w bs @ cs = bin_to_bl_aux n w (bs @ cs)\"\n  by (induct n arbitrary: w bs) auto\n\nlemma bl_to_bin_append: \"bl_to_bin (bs @ cs) = bl_to_bin_aux cs (bl_to_bin bs)\"\n  unfolding bl_to_bin_def by (rule bl_to_bin_aux_append)\n\nlemma bin_to_bl_aux_alt: \"bin_to_bl_aux n w bs = bin_to_bl n w @ bs\"\n  by (simp add: bin_to_bl_def bin_to_bl_aux_append)\n\nlemma bin_to_bl_0 [simp]: \"bin_to_bl 0 bs = []\"\n  by (auto simp: bin_to_bl_def)\n\nlemma size_bin_to_bl_aux: \"length (bin_to_bl_aux n w bs) = n + length bs\"\n  by (induct n arbitrary: w bs) auto\n\nlemma size_bin_to_bl [simp]: \"length (bin_to_bl n w) = n\"\n  by (simp add: bin_to_bl_def size_bin_to_bl_aux)\n\nlemma bl_bin_bl': \"bin_to_bl (n + length bs) (bl_to_bin_aux bs w) = bin_to_bl_aux n w bs\"\n  apply (induct bs arbitrary: w n)\n   apply auto\n    apply (simp_all only: add_Suc [symmetric])\n    apply (auto simp add: bin_to_bl_def)\n  done\n\nlemma bl_bin_bl [simp]: \"bin_to_bl (length bs) (bl_to_bin bs) = bs\"\n  unfolding bl_to_bin_def\n  apply (rule box_equals)\n    apply (rule bl_bin_bl')\n   prefer 2\n   apply (rule bin_to_bl_aux.Z)\n  apply simp\n  done\n\nlemma bl_to_bin_inj: \"bl_to_bin bs = bl_to_bin cs \\<Longrightarrow> length bs = length cs \\<Longrightarrow> bs = cs\"\n  apply (rule_tac box_equals)\n    defer\n    apply (rule bl_bin_bl)\n   apply (rule bl_bin_bl)\n  apply simp\n  done\n\nlemma bl_to_bin_False [simp]: \"bl_to_bin (False # bl) = bl_to_bin bl\"\n  by (auto simp: bl_to_bin_def)\n\nlemma bl_to_bin_Nil [simp]: \"bl_to_bin [] = 0\"\n  by (auto simp: bl_to_bin_def)\n\nlemma bin_to_bl_zero_aux: \"bin_to_bl_aux n 0 bl = replicate n False @ bl\"\n  by (induct n arbitrary: bl) (auto simp: replicate_app_Cons_same)\n\nlemma bin_to_bl_zero: \"bin_to_bl n 0 = replicate n False\"\n  by (simp add: bin_to_bl_def bin_to_bl_zero_aux)\n\nlemma bin_to_bl_minus1_aux: \"bin_to_bl_aux n (- 1) bl = replicate n True @ bl\"\n  by (induct n arbitrary: bl) (auto simp: replicate_app_Cons_same)\n\nlemma bin_to_bl_minus1: \"bin_to_bl n (- 1) = replicate n True\"\n  by (simp add: bin_to_bl_def bin_to_bl_minus1_aux)\n\nlemma bl_to_bin_BIT:\n  \"bl_to_bin bs BIT b = bl_to_bin (bs @ [b])\"\n  by (simp add: bl_to_bin_append)\n\n\nsubsection \\<open>Bit projection\\<close>\n\nprimrec bin_nth :: \"int \\<Rightarrow> nat \\<Rightarrow> bool\"\n  where\n    Z: \"bin_nth w 0 \\<longleftrightarrow> bin_last w\"\n  | Suc: \"bin_nth w (Suc n) \\<longleftrightarrow> bin_nth (bin_rest w) n\"\n\nlemma bin_nth_eq_mod:\n  \"bin_nth w n \\<longleftrightarrow> odd (w div 2 ^ n)\"\n  by (induction n arbitrary: w) (simp_all add: bin_last_def bin_rest_def odd_iff_mod_2_eq_one zdiv_zmult2_eq)\n\nlemma bin_nth_eq_iff: \"bin_nth x = bin_nth y \\<longleftrightarrow> x = y\"\nproof -\n  have bin_nth_lem [rule_format]: \"\\<forall>y. bin_nth x = bin_nth y \\<longrightarrow> x = y\"\n    apply (induct x rule: bin_induct)\n      apply safe\n      apply (erule rev_mp)\n      apply (induct_tac y rule: bin_induct)\n        apply safe\n        apply (drule_tac x=0 in fun_cong, force)\n       apply (erule notE, rule ext, drule_tac x=\"Suc x\" in fun_cong, force)\n      apply (drule_tac x=0 in fun_cong, force)\n     apply (erule rev_mp)\n     apply (induct_tac y rule: bin_induct)\n       apply safe\n       apply (drule_tac x=0 in fun_cong, force)\n      apply (erule notE, rule ext, drule_tac x=\"Suc x\" in fun_cong, force)\n     apply (metis Bit_eq_m1_iff Z bin_last_BIT)\n    apply (case_tac y rule: bin_exhaust)\n    apply clarify\n    apply (erule allE)\n    apply (erule impE)\n     prefer 2\n     apply (erule conjI)\n     apply (drule_tac x=0 in fun_cong, force)\n    apply (rule ext)\n    apply (drule_tac x=\"Suc x\" for x in fun_cong, force)\n    done\n  show ?thesis\n    by (auto elim: bin_nth_lem)\nqed\n\nlemma bin_eqI:\n  \"x = y\" if \"\\<And>n. bin_nth x n \\<longleftrightarrow> bin_nth y n\"\n  using that bin_nth_eq_iff [of x y] by (simp add: fun_eq_iff)\n\nlemma bin_eq_iff: \"x = y \\<longleftrightarrow> (\\<forall>n. bin_nth x n = bin_nth y n)\"\n  using bin_nth_eq_iff by auto\n\nlemma bin_nth_zero [simp]: \"\\<not> bin_nth 0 n\"\n  by (induct n) auto\n\nlemma bin_nth_1 [simp]: \"bin_nth 1 n \\<longleftrightarrow> n = 0\"\n  by (cases n) simp_all\n\nlemma bin_nth_minus1 [simp]: \"bin_nth (- 1) n\"\n  by (induct n) auto\n\nlemma bin_nth_0_BIT: \"bin_nth (w BIT b) 0 \\<longleftrightarrow> b\"\n  by auto\n\nlemma bin_nth_Suc_BIT: \"bin_nth (w BIT b) (Suc n) = bin_nth w n\"\n  by auto\n\nlemma bin_nth_minus [simp]: \"0 < n \\<Longrightarrow> bin_nth (w BIT b) n = bin_nth w (n - 1)\"\n  by (cases n) auto\n\nlemma bin_nth_numeral: \"bin_rest x = y \\<Longrightarrow> bin_nth x (numeral n) = bin_nth y (pred_numeral n)\"\n  by (simp add: numeral_eq_Suc)\n\nlemmas bin_nth_numeral_simps [simp] =\n  bin_nth_numeral [OF bin_rest_numeral_simps(2)]\n  bin_nth_numeral [OF bin_rest_numeral_simps(5)]\n  bin_nth_numeral [OF bin_rest_numeral_simps(6)]\n  bin_nth_numeral [OF bin_rest_numeral_simps(7)]\n  bin_nth_numeral [OF bin_rest_numeral_simps(8)]\n\nlemmas bin_nth_simps =\n  bin_nth.Z bin_nth.Suc bin_nth_zero bin_nth_minus1\n  bin_nth_numeral_simps\n\nlemma nth_2p_bin: \"bin_nth (2 ^ n) m = (m = n)\" \\<comment> \\<open>for use when simplifying with \\<open>bin_nth_Bit\\<close>\\<close>\n  apply (induct n arbitrary: m)\n   apply clarsimp\n   apply safe\n   apply (case_tac m)\n    apply (auto simp: Bit_B0_2t [symmetric])\n  done \n\nlemma nth_rest_power_bin: \"bin_nth ((bin_rest ^^ k) w) n = bin_nth w (n + k)\"\n  apply (induct k arbitrary: n)\n   apply clarsimp\n  apply clarsimp\n  apply (simp only: bin_nth.Suc [symmetric] add_Suc)\n  done\n\nlemma bin_nth_numeral_unfold:\n  \"bin_nth (numeral (num.Bit0 x)) n \\<longleftrightarrow> n > 0 \\<and> bin_nth (numeral x) (n - 1)\"\n  \"bin_nth (numeral (num.Bit1 x)) n \\<longleftrightarrow> (n > 0 \\<longrightarrow> bin_nth (numeral x) (n - 1))\"\nby(case_tac [!] n) simp_all\n\n\nsubsection \\<open>Truncating\\<close>\n\ndefinition bin_sign :: \"int \\<Rightarrow> int\"\n  where \"bin_sign k = (if k \\<ge> 0 then 0 else - 1)\"\n\nlemma bin_sign_simps [simp]:\n  \"bin_sign 0 = 0\"\n  \"bin_sign 1 = 0\"\n  \"bin_sign (- 1) = - 1\"\n  \"bin_sign (numeral k) = 0\"\n  \"bin_sign (- numeral k) = -1\"\n  \"bin_sign (w BIT b) = bin_sign w\"\n  by (simp_all add: bin_sign_def Bit_def)\n\nlemma bin_sign_rest [simp]: \"bin_sign (bin_rest w) = bin_sign w\"\n  by (cases w rule: bin_exhaust) auto\n\nprimrec bintrunc :: \"nat \\<Rightarrow> int \\<Rightarrow> int\"\n  where\n    Z : \"bintrunc 0 bin = 0\"\n  | Suc : \"bintrunc (Suc n) bin = bintrunc n (bin_rest bin) BIT (bin_last bin)\"\n\nprimrec sbintrunc :: \"nat \\<Rightarrow> int \\<Rightarrow> int\"\n  where\n    Z : \"sbintrunc 0 bin = (if bin_last bin then -1 else 0)\"\n  | Suc : \"sbintrunc (Suc n) bin = sbintrunc n (bin_rest bin) BIT (bin_last bin)\"\n\nlemma bintrunc_mod2p: \"bintrunc n w = w mod 2 ^ n\"\n  by (induct n arbitrary: w) (auto simp add: bin_last_def bin_rest_def Bit_def zmod_zmult2_eq)\n\nlemma sbintrunc_mod2p: \"sbintrunc n w = (w + 2 ^ n) mod 2 ^ Suc n - 2 ^ n\"\nproof (induction n arbitrary: w)\n  case 0\n  then show ?case\n    by (auto simp add: bin_last_odd odd_iff_mod_2_eq_one)\nnext\n  case (Suc n)\n  moreover have \"((bin_rest w + 2 ^ n) mod (2 * 2 ^ n) - 2 ^ n) BIT bin_last w =\n    (w + 2 * 2 ^ n) mod (4 * 2 ^ n) - 2 * 2 ^ n\"\n  proof (cases w rule: parity_cases)\n    case even\n    then show ?thesis\n      by (simp add: bin_last_odd bin_rest_def Bit_B0_2t mult_mod_right)\n  next\n    case odd\n    then have \"2 * (w div 2) = w - 1\"\n      using minus_mod_eq_mult_div [of w 2] by simp\n    moreover have \"(2 * 2 ^ n + w - 1) mod (2 * 2 * 2 ^ n) + 1 = (2 * 2 ^ n + w) mod (2 * 2 * 2 ^ n)\"\n      using odd emep1 [of \"2 * 2 ^ n + w - 1\" \"2 * 2 * 2 ^ n\"] by simp\n    ultimately show ?thesis \n      using odd by (simp add: bin_last_odd bin_rest_def Bit_B1_2t mult_mod_right) (simp add: algebra_simps)\n  qed\n  ultimately show ?case\n    by simp\nqed\n\nlemma sign_bintr: \"bin_sign (bintrunc n w) = 0\"\n  by (simp add: bintrunc_mod2p bin_sign_def)\n\nlemma bintrunc_n_0 [simp]: \"bintrunc n 0 = 0\"\n  by (simp add: bintrunc_mod2p)\n\nlemma sbintrunc_n_0 [simp]: \"sbintrunc n 0 = 0\"\n  by (simp add: sbintrunc_mod2p)\n\nlemma sbintrunc_n_minus1 [simp]: \"sbintrunc n (- 1) = -1\"\n  by (induct n) auto\n\nlemma bintrunc_Suc_numeral:\n  \"bintrunc (Suc n) 1 = 1\"\n  \"bintrunc (Suc n) (- 1) = bintrunc n (- 1) BIT True\"\n  \"bintrunc (Suc n) (numeral (Num.Bit0 w)) = bintrunc n (numeral w) BIT False\"\n  \"bintrunc (Suc n) (numeral (Num.Bit1 w)) = bintrunc n (numeral w) BIT True\"\n  \"bintrunc (Suc n) (- numeral (Num.Bit0 w)) = bintrunc n (- numeral w) BIT False\"\n  \"bintrunc (Suc n) (- numeral (Num.Bit1 w)) = bintrunc n (- numeral (w + Num.One)) BIT True\"\n  by simp_all\n\nlemma sbintrunc_0_numeral [simp]:\n  \"sbintrunc 0 1 = -1\"\n  \"sbintrunc 0 (numeral (Num.Bit0 w)) = 0\"\n  \"sbintrunc 0 (numeral (Num.Bit1 w)) = -1\"\n  \"sbintrunc 0 (- numeral (Num.Bit0 w)) = 0\"\n  \"sbintrunc 0 (- numeral (Num.Bit1 w)) = -1\"\n  by simp_all\n\nlemma sbintrunc_Suc_numeral:\n  \"sbintrunc (Suc n) 1 = 1\"\n  \"sbintrunc (Suc n) (numeral (Num.Bit0 w)) = sbintrunc n (numeral w) BIT False\"\n  \"sbintrunc (Suc n) (numeral (Num.Bit1 w)) = sbintrunc n (numeral w) BIT True\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit0 w)) = sbintrunc n (- numeral w) BIT False\"\n  \"sbintrunc (Suc n) (- numeral (Num.Bit1 w)) = sbintrunc n (- numeral (w + Num.One)) BIT True\"\n  by simp_all\n\nlemma bin_sign_lem: \"(bin_sign (sbintrunc n bin) = -1) = bin_nth bin n\"\n  apply (induct n arbitrary: bin)\n  apply (case_tac bin rule: bin_exhaust, case_tac b, auto)\n  done\n\nlemma nth_bintr: \"bin_nth (bintrunc m w) n \\<longleftrightarrow> n < m \\<and> bin_nth w n\"\n  apply (induct n arbitrary: w m)\n   apply (case_tac m, auto)[1]\n  apply (case_tac m, auto)[1]\n  done\n\nlemma nth_sbintr: \"bin_nth (sbintrunc m w) n = (if n < m then bin_nth w n else bin_nth w m)\"\n  apply (induct n arbitrary: w m)\n   apply (case_tac m)\n    apply simp_all\n  apply (case_tac m)\n   apply simp_all\n  done\n\nlemma bin_nth_Bit: \"bin_nth (w BIT b) n \\<longleftrightarrow> n = 0 \\<and> b \\<or> (\\<exists>m. n = Suc m \\<and> bin_nth w m)\"\n  by (cases n) auto\n\nlemma bin_nth_Bit0:\n  \"bin_nth (numeral (Num.Bit0 w)) n \\<longleftrightarrow>\n    (\\<exists>m. n = Suc m \\<and> bin_nth (numeral w) m)\"\n  using bin_nth_Bit [where w=\"numeral w\" and b=\"False\"] by simp\n\nlemma bin_nth_Bit1:\n  \"bin_nth (numeral (Num.Bit1 w)) n \\<longleftrightarrow>\n    n = 0 \\<or> (\\<exists>m. n = Suc m \\<and> bin_nth (numeral w) m)\"\n  using bin_nth_Bit [where w=\"numeral w\" and b=\"True\"] by simp\n\nlemma bintrunc_bintrunc_l: \"n \\<le> m \\<Longrightarrow> bintrunc m (bintrunc n w) = bintrunc n w\"\n  by (rule bin_eqI) (auto simp: nth_bintr)\n\nlemma sbintrunc_sbintrunc_l: \"n \\<le> m \\<Longrightarrow> sbintrunc m (sbintrunc n w) = sbintrunc n w\"\n  by (rule bin_eqI) (auto simp: nth_sbintr)\n\nlemma bintrunc_bintrunc_ge: \"n \\<le> m \\<Longrightarrow> bintrunc n (bintrunc m w) = bintrunc n w\"\n  by (rule bin_eqI) (auto simp: nth_bintr)\n\nlemma bintrunc_bintrunc_min [simp]: \"bintrunc m (bintrunc n w) = bintrunc (min m n) w\"\n  by (rule bin_eqI) (auto simp: nth_bintr)\n\nlemma sbintrunc_sbintrunc_min [simp]: \"sbintrunc m (sbintrunc n w) = sbintrunc (min m n) w\"\n  by (rule bin_eqI) (auto simp: nth_sbintr min.absorb1 min.absorb2)\n\nlemmas bintrunc_Pls =\n  bintrunc.Suc [where bin=\"0\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas bintrunc_Min [simp] =\n  bintrunc.Suc [where bin=\"-1\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas bintrunc_BIT  [simp] =\n  bintrunc.Suc [where bin=\"w BIT b\", simplified bin_last_BIT bin_rest_BIT] for w b\n\nlemmas bintrunc_Sucs = bintrunc_Pls bintrunc_Min bintrunc_BIT\n  bintrunc_Suc_numeral\n\nlemmas sbintrunc_Suc_Pls =\n  sbintrunc.Suc [where bin=\"0\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Suc_Min =\n  sbintrunc.Suc [where bin=\"-1\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Suc_BIT [simp] =\n  sbintrunc.Suc [where bin=\"w BIT b\", simplified bin_last_BIT bin_rest_BIT] for w b\n\nlemmas sbintrunc_Sucs = sbintrunc_Suc_Pls sbintrunc_Suc_Min sbintrunc_Suc_BIT\n  sbintrunc_Suc_numeral\n\nlemmas sbintrunc_Pls =\n  sbintrunc.Z [where bin=\"0\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_Min =\n  sbintrunc.Z [where bin=\"-1\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n\nlemmas sbintrunc_0_BIT_B0 [simp] =\n  sbintrunc.Z [where bin=\"w BIT False\", simplified bin_last_numeral_simps bin_rest_numeral_simps]\n  for w\n\nlemmas sbintrunc_0_BIT_B1 [simp] =\n  sbintrunc.Z [where bin=\"w BIT True\", simplified bin_last_BIT bin_rest_numeral_simps]\n  for w\n\nlemmas sbintrunc_0_simps =\n  sbintrunc_Pls sbintrunc_Min sbintrunc_0_BIT_B0 sbintrunc_0_BIT_B1\n\nlemmas bintrunc_simps = bintrunc.Z bintrunc_Sucs\nlemmas sbintrunc_simps = sbintrunc_0_simps sbintrunc_Sucs\n\nlemma bintrunc_minus: \"0 < n \\<Longrightarrow> bintrunc (Suc (n - 1)) w = bintrunc n w\"\n  by auto\n\nlemma sbintrunc_minus: \"0 < n \\<Longrightarrow> sbintrunc (Suc (n - 1)) w = sbintrunc n w\"\n  by auto\n\nlemmas bintrunc_minus_simps =\n  bintrunc_Sucs [THEN [2] bintrunc_minus [symmetric, THEN trans]]\nlemmas sbintrunc_minus_simps =\n  sbintrunc_Sucs [THEN [2] sbintrunc_minus [symmetric, THEN trans]]\n\nlemmas thobini1 = arg_cong [where f = \"\\<lambda>w. w BIT b\"] for b\n\nlemmas bintrunc_BIT_I = trans [OF bintrunc_BIT thobini1]\nlemmas bintrunc_Min_I = trans [OF bintrunc_Min thobini1]\n\nlemmas bmsts = bintrunc_minus_simps(1-3) [THEN thobini1 [THEN [2] trans]]\nlemmas bintrunc_Pls_minus_I = bmsts(1)\nlemmas bintrunc_Min_minus_I = bmsts(2)\nlemmas bintrunc_BIT_minus_I = bmsts(3)\n\nlemma bintrunc_Suc_lem: \"bintrunc (Suc n) x = y \\<Longrightarrow> m = Suc n \\<Longrightarrow> bintrunc m x = y\"\n  by auto\n\nlemmas bintrunc_Suc_Ialts =\n  bintrunc_Min_I [THEN bintrunc_Suc_lem]\n  bintrunc_BIT_I [THEN bintrunc_Suc_lem]\n\nlemmas sbintrunc_BIT_I = trans [OF sbintrunc_Suc_BIT thobini1]\n\nlemmas sbintrunc_Suc_Is =\n  sbintrunc_Sucs(1-3) [THEN thobini1 [THEN [2] trans]]\n\nlemmas sbintrunc_Suc_minus_Is =\n  sbintrunc_minus_simps(1-3) [THEN thobini1 [THEN [2] trans]]\n\nlemma sbintrunc_Suc_lem: \"sbintrunc (Suc n) x = y \\<Longrightarrow> m = Suc n \\<Longrightarrow> sbintrunc m x = y\"\n  by auto\n\nlemmas sbintrunc_Suc_Ialts =\n  sbintrunc_Suc_Is [THEN sbintrunc_Suc_lem]\n\nlemma sbintrunc_bintrunc_lt: \"m > n \\<Longrightarrow> sbintrunc n (bintrunc m w) = sbintrunc n w\"\n  by (rule bin_eqI) (auto simp: nth_sbintr nth_bintr)\n\nlemma bintrunc_sbintrunc_le: \"m \\<le> Suc n \\<Longrightarrow> bintrunc m (sbintrunc n w) = bintrunc m w\"\n  apply (rule bin_eqI)\n  using le_Suc_eq less_Suc_eq_le apply (auto simp: nth_sbintr nth_bintr)\n  done\n\nlemmas bintrunc_sbintrunc [simp] = order_refl [THEN bintrunc_sbintrunc_le]\nlemmas sbintrunc_bintrunc [simp] = lessI [THEN sbintrunc_bintrunc_lt]\nlemmas bintrunc_bintrunc [simp] = order_refl [THEN bintrunc_bintrunc_l]\nlemmas sbintrunc_sbintrunc [simp] = order_refl [THEN sbintrunc_sbintrunc_l]\n\nlemma bintrunc_sbintrunc' [simp]: \"0 < n \\<Longrightarrow> bintrunc n (sbintrunc (n - 1) w) = bintrunc n w\"\n  by (cases n) (auto simp del: bintrunc.Suc)\n\nlemma sbintrunc_bintrunc' [simp]: \"0 < n \\<Longrightarrow> sbintrunc (n - 1) (bintrunc n w) = sbintrunc (n - 1) w\"\n  by (cases n) (auto simp del: bintrunc.Suc)\n\nlemma bin_sbin_eq_iff: \"bintrunc (Suc n) x = bintrunc (Suc n) y \\<longleftrightarrow> sbintrunc n x = sbintrunc n y\"\n  apply (rule iffI)\n   apply (rule box_equals [OF _ sbintrunc_bintrunc sbintrunc_bintrunc])\n   apply simp\n  apply (rule box_equals [OF _ bintrunc_sbintrunc bintrunc_sbintrunc])\n  apply simp\n  done\n\nlemma bin_sbin_eq_iff':\n  \"0 < n \\<Longrightarrow> bintrunc n x = bintrunc n y \\<longleftrightarrow> sbintrunc (n - 1) x = sbintrunc (n - 1) y\"\n  by (cases n) (simp_all add: bin_sbin_eq_iff del: bintrunc.Suc)\n\nlemmas bintrunc_sbintruncS0 [simp] = bintrunc_sbintrunc' [unfolded One_nat_def]\nlemmas sbintrunc_bintruncS0 [simp] = sbintrunc_bintrunc' [unfolded One_nat_def]\n\nlemmas bintrunc_bintrunc_l' = le_add1 [THEN bintrunc_bintrunc_l]\nlemmas sbintrunc_sbintrunc_l' = le_add1 [THEN sbintrunc_sbintrunc_l]\n\n(* although bintrunc_minus_simps, if added to default simpset,\n  tends to get applied where it's not wanted in developing the theories,\n  we get a version for when the word length is given literally *)\n\nlemmas nat_non0_gr =\n  trans [OF iszero_def [THEN Not_eq_iff [THEN iffD2]] refl]\n\nlemma bintrunc_numeral:\n  \"bintrunc (numeral k) x = bintrunc (pred_numeral k) (bin_rest x) BIT bin_last x\"\n  by (simp add: numeral_eq_Suc)\n\nlemma sbintrunc_numeral:\n  \"sbintrunc (numeral k) x = sbintrunc (pred_numeral k) (bin_rest x) BIT bin_last x\"\n  by (simp add: numeral_eq_Suc)\n\nlemma bintrunc_numeral_simps [simp]:\n  \"bintrunc (numeral k) (numeral (Num.Bit0 w)) = bintrunc (pred_numeral k) (numeral w) BIT False\"\n  \"bintrunc (numeral k) (numeral (Num.Bit1 w)) = bintrunc (pred_numeral k) (numeral w) BIT True\"\n  \"bintrunc (numeral k) (- numeral (Num.Bit0 w)) = bintrunc (pred_numeral k) (- numeral w) BIT False\"\n  \"bintrunc (numeral k) (- numeral (Num.Bit1 w)) =\n    bintrunc (pred_numeral k) (- numeral (w + Num.One)) BIT True\"\n  \"bintrunc (numeral k) 1 = 1\"\n  by (simp_all add: bintrunc_numeral)\n\nlemma sbintrunc_numeral_simps [simp]:\n  \"sbintrunc (numeral k) (numeral (Num.Bit0 w)) = sbintrunc (pred_numeral k) (numeral w) BIT False\"\n  \"sbintrunc (numeral k) (numeral (Num.Bit1 w)) = sbintrunc (pred_numeral k) (numeral w) BIT True\"\n  \"sbintrunc (numeral k) (- numeral (Num.Bit0 w)) =\n    sbintrunc (pred_numeral k) (- numeral w) BIT False\"\n  \"sbintrunc (numeral k) (- numeral (Num.Bit1 w)) =\n    sbintrunc (pred_numeral k) (- numeral (w + Num.One)) BIT True\"\n  \"sbintrunc (numeral k) 1 = 1\"\n  by (simp_all add: sbintrunc_numeral)\n\nlemma no_bintr_alt1: \"bintrunc n = (\\<lambda>w. w mod 2 ^ n :: int)\"\n  by (rule ext) (rule bintrunc_mod2p)\n\nlemma range_bintrunc: \"range (bintrunc n) = {i. 0 \\<le> i \\<and> i < 2 ^ n}\"\n  apply (unfold no_bintr_alt1)\n  apply (auto simp add: image_iff)\n  apply (rule exI)\n  apply (rule sym)\n  using int_mod_lem [symmetric, of \"2 ^ n\"]\n  apply auto\n  done\n\nlemma no_sbintr_alt2: \"sbintrunc n = (\\<lambda>w. (w + 2 ^ n) mod 2 ^ Suc n - 2 ^ n :: int)\"\n  by (rule ext) (simp add : sbintrunc_mod2p)\n\nlemma range_sbintrunc: \"range (sbintrunc n) = {i. - (2 ^ n) \\<le> i \\<and> i < 2 ^ n}\"\n  apply (unfold no_sbintr_alt2)\n  apply (auto simp add: image_iff eq_diff_eq)\n\n  apply (rule exI)\n  apply (auto intro: int_mod_lem [THEN iffD1, symmetric])\n  done\n\nlemma sb_inc_lem: \"a + 2^k < 0 \\<Longrightarrow> a + 2^k + 2^(Suc k) \\<le> (a + 2^k) mod 2^(Suc k)\"\n  for a :: int\n  using int_mod_ge' [where n = \"2 ^ (Suc k)\" and b = \"a + 2 ^ k\"]\n  by simp\n\nlemma sb_inc_lem': \"a < - (2^k) \\<Longrightarrow> a + 2^k + 2^(Suc k) \\<le> (a + 2^k) mod 2^(Suc k)\"\n  for a :: int\n  by (rule sb_inc_lem) simp\n\nlemma sbintrunc_inc: \"x < - (2^n) \\<Longrightarrow> x + 2^(Suc n) \\<le> sbintrunc n x\"\n  unfolding no_sbintr_alt2 by (drule sb_inc_lem') simp\n\nlemma sb_dec_lem: \"0 \\<le> - (2 ^ k) + a \\<Longrightarrow> (a + 2 ^ k) mod (2 * 2 ^ k) \\<le> - (2 ^ k) + a\"\n  for a :: int\n  using int_mod_le'[where n = \"2 ^ (Suc k)\" and b = \"a + 2 ^ k\"] by simp\n\nlemma sb_dec_lem': \"2 ^ k \\<le> a \\<Longrightarrow> (a + 2 ^ k) mod (2 * 2 ^ k) \\<le> - (2 ^ k) + a\"\n  for a :: int\n  by (rule sb_dec_lem) simp\n\nlemma sbintrunc_dec: \"x \\<ge> (2 ^ n) \\<Longrightarrow> x - 2 ^ (Suc n) >= sbintrunc n x\"\n  unfolding no_sbintr_alt2 by (drule sb_dec_lem') simp\n\nlemma bintr_ge0: \"0 \\<le> bintrunc n w\"\n  by (simp add: bintrunc_mod2p)\n\nlemma bintr_lt2p: \"bintrunc n w < 2 ^ n\"\n  by (simp add: bintrunc_mod2p)\n\nlemma bintr_Min: \"bintrunc n (- 1) = 2 ^ n - 1\"\n  by (simp add: bintrunc_mod2p m1mod2k)\n\nlemma sbintr_ge: \"- (2 ^ n) \\<le> sbintrunc n w\"\n  by (simp add: sbintrunc_mod2p)\n\nlemma sbintr_lt: \"sbintrunc n w < 2 ^ n\"\n  by (simp add: sbintrunc_mod2p)\n\nlemma sign_Pls_ge_0: \"bin_sign bin = 0 \\<longleftrightarrow> bin \\<ge> 0\"\n  for bin :: int\n  by (simp add: bin_sign_def)\n\nlemma sign_Min_lt_0: \"bin_sign bin = -1 \\<longleftrightarrow> bin < 0\"\n  for bin :: int\n  by (simp add: bin_sign_def)\n\nlemma bin_rest_trunc: \"bin_rest (bintrunc n bin) = bintrunc (n - 1) (bin_rest bin)\"\n  by (induct n arbitrary: bin) auto\n\nlemma bin_rest_power_trunc:\n  \"(bin_rest ^^ k) (bintrunc n bin) = bintrunc (n - k) ((bin_rest ^^ k) bin)\"\n  by (induct k) (auto simp: bin_rest_trunc)\n\nlemma bin_rest_trunc_i: \"bintrunc n (bin_rest bin) = bin_rest (bintrunc (Suc n) bin)\"\n  by auto\n\nlemma bin_rest_strunc: \"bin_rest (sbintrunc (Suc n) bin) = sbintrunc n (bin_rest bin)\"\n  by (induct n arbitrary: bin) auto\n\nlemma bintrunc_rest [simp]: \"bintrunc n (bin_rest (bintrunc n bin)) = bin_rest (bintrunc n bin)\"\n  apply (induct n arbitrary: bin)\n   apply simp\n  apply (case_tac bin rule: bin_exhaust)\n  apply (auto simp: bintrunc_bintrunc_l)\n  done\n\nlemma sbintrunc_rest [simp]: \"sbintrunc n (bin_rest (sbintrunc n bin)) = bin_rest (sbintrunc n bin)\"\n  apply (induct n arbitrary: bin)\n   apply simp\n  apply (case_tac bin rule: bin_exhaust)\n  apply (auto simp: bintrunc_bintrunc_l split: bool.splits)\n  done\n\nlemma bintrunc_rest': \"bintrunc n \\<circ> bin_rest \\<circ> bintrunc n = bin_rest \\<circ> bintrunc n\"\n  by (rule ext) auto\n\nlemma sbintrunc_rest': \"sbintrunc n \\<circ> bin_rest \\<circ> sbintrunc n = bin_rest \\<circ> sbintrunc n\"\n  by (rule ext) auto\n\nlemma rco_lem: \"f \\<circ> g \\<circ> f = g \\<circ> f \\<Longrightarrow> f \\<circ> (g \\<circ> f) ^^ n = g ^^ n \\<circ> f\"\n  apply (rule ext)\n  apply (induct_tac n)\n   apply (simp_all (no_asm))\n  apply (drule fun_cong)\n  apply (unfold o_def)\n  apply (erule trans)\n  apply simp\n  done\n\nlemmas rco_bintr = bintrunc_rest'\n  [THEN rco_lem [THEN fun_cong], unfolded o_def]\nlemmas rco_sbintr = sbintrunc_rest'\n  [THEN rco_lem [THEN fun_cong], unfolded o_def]\n\n\nsubsection \\<open>Splitting and concatenation\\<close>\n\nprimrec bin_split :: \"nat \\<Rightarrow> int \\<Rightarrow> int \\<times> int\"\n  where\n    Z: \"bin_split 0 w = (w, 0)\"\n  | Suc: \"bin_split (Suc n) w =\n      (let (w1, w2) = bin_split n (bin_rest w)\n       in (w1, w2 BIT bin_last w))\"\n\n\n\nprimrec bin_cat :: \"int \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> int\"\n  where\n    Z: \"bin_cat w 0 v = w\"\n  | Suc: \"bin_cat w (Suc n) v = bin_cat w n (bin_rest v) BIT bin_last v\"\n\nlemma bin_sign_cat: \"bin_sign (bin_cat x n y) = bin_sign x\"\n  by (induct n arbitrary: y) auto\n\nlemma bin_cat_Suc_Bit: \"bin_cat w (Suc n) (v BIT b) = bin_cat w n v BIT b\"\n  by auto\n\nlemma bin_cat_assoc: \"bin_cat (bin_cat x m y) n z = bin_cat x (m + n) (bin_cat y n z)\"\n  by (induct n arbitrary: z) auto\n\nlemma bin_cat_assoc_sym: \"bin_cat x m (bin_cat y n z) = bin_cat (bin_cat x (m - n) y) (min m n) z\"\n  apply (induct n arbitrary: z m)\n   apply clarsimp\n  apply (case_tac m, auto)\n  done\n\ndefinition bin_rcat :: \"nat \\<Rightarrow> int list \\<Rightarrow> int\"\n  where \"bin_rcat n = foldl (\\<lambda>u v. bin_cat u n v) 0\"\n\nfun bin_rsplit_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> int list \\<Rightarrow> int list\"\n  where \"bin_rsplit_aux n m c bs =\n    (if m = 0 \\<or> n = 0 then bs\n     else\n      let (a, b) = bin_split n c\n      in bin_rsplit_aux n (m - n) a (b # bs))\"\n\ndefinition bin_rsplit :: \"nat \\<Rightarrow> nat \\<times> int \\<Rightarrow> int list\"\n  where \"bin_rsplit n w = bin_rsplit_aux n (fst w) (snd w) []\"\n\nfun bin_rsplitl_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> int \\<Rightarrow> int list \\<Rightarrow> int list\"\n  where \"bin_rsplitl_aux n m c bs =\n    (if m = 0 \\<or> n = 0 then bs\n     else\n      let (a, b) = bin_split (min m n) c\n      in bin_rsplitl_aux n (m - n) a (b # bs))\"\n\ndefinition bin_rsplitl :: \"nat \\<Rightarrow> nat \\<times> int \\<Rightarrow> int list\"\n  where \"bin_rsplitl n w = bin_rsplitl_aux n (fst w) (snd w) []\"\n\ndeclare bin_rsplit_aux.simps [simp del]\ndeclare bin_rsplitl_aux.simps [simp del]\n\nlemma bin_nth_cat:\n  \"bin_nth (bin_cat x k y) n =\n    (if n < k then bin_nth y n else bin_nth x (n - k))\"\n  apply (induct k arbitrary: n y)\n   apply clarsimp\n  apply (case_tac n, auto)\n  done\n\nlemma bin_nth_split:\n  \"bin_split n c = (a, b) \\<Longrightarrow>\n    (\\<forall>k. bin_nth a k = bin_nth c (n + k)) \\<and>\n    (\\<forall>k. bin_nth b k = (k < n \\<and> bin_nth c k))\"\n  apply (induct n arbitrary: b c)\n   apply clarsimp\n  apply (clarsimp simp: Let_def split: prod.split_asm)\n  apply (case_tac k)\n  apply auto\n  done\n\nlemma bin_cat_zero [simp]: \"bin_cat 0 n w = bintrunc n w\"\n  by (induct n arbitrary: w) auto\n\nlemma bintr_cat1: \"bintrunc (k + n) (bin_cat a n b) = bin_cat (bintrunc k a) n b\"\n  by (induct n arbitrary: b) auto\n\nlemma bintr_cat: \"bintrunc m (bin_cat a n b) =\n    bin_cat (bintrunc (m - n) a) n (bintrunc (min m n) b)\"\n  by (rule bin_eqI) (auto simp: bin_nth_cat nth_bintr)\n\nlemma bintr_cat_same [simp]: \"bintrunc n (bin_cat a n b) = bintrunc n b\"\n  by (auto simp add : bintr_cat)\n\nlemma cat_bintr [simp]: \"bin_cat a n (bintrunc n b) = bin_cat a n b\"\n  by (induct n arbitrary: b) auto\n\nlemma split_bintrunc: \"bin_split n c = (a, b) \\<Longrightarrow> b = bintrunc n c\"\n  by (induct n arbitrary: b c) (auto simp: Let_def split: prod.split_asm)\n\nlemma bin_cat_split: \"bin_split n w = (u, v) \\<Longrightarrow> w = bin_cat u n v\"\n  by (induct n arbitrary: v w) (auto simp: Let_def split: prod.split_asm)\n\nlemma bin_split_cat: \"bin_split n (bin_cat v n w) = (v, bintrunc n w)\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_split_zero [simp]: \"bin_split n 0 = (0, 0)\"\n  by (induct n) auto\n\nlemma bin_split_minus1 [simp]:\n  \"bin_split n (- 1) = (- 1, bintrunc n (- 1))\"\n  by (induct n) auto\n\nlemma bin_split_trunc:\n  \"bin_split (min m n) c = (a, b) \\<Longrightarrow>\n    bin_split n (bintrunc m c) = (bintrunc (m - n) a, b)\"\n  apply (induct n arbitrary: m b c, clarsimp)\n  apply (simp add: bin_rest_trunc Let_def split: prod.split_asm)\n  apply (case_tac m)\n   apply (auto simp: Let_def split: prod.split_asm)\n  done\n\nlemma bin_split_trunc1:\n  \"bin_split n c = (a, b) \\<Longrightarrow>\n    bin_split n (bintrunc m c) = (bintrunc (m - n) a, bintrunc m b)\"\n  apply (induct n arbitrary: m b c, clarsimp)\n  apply (simp add: bin_rest_trunc Let_def split: prod.split_asm)\n  apply (case_tac m)\n   apply (auto simp: Let_def split: prod.split_asm)\n  done\n\nlemma bin_cat_num: \"bin_cat a n b = a * 2 ^ n + bintrunc n b\"\n  apply (induct n arbitrary: b)\n   apply clarsimp\n  apply (simp add: Bit_def)\n  done\n\nlemma bin_split_num: \"bin_split n b = (b div 2 ^ n, b mod 2 ^ n)\"\n  apply (induct n arbitrary: b)\n   apply simp\n  apply (simp add: bin_rest_def zdiv_zmult2_eq)\n  apply (case_tac b rule: bin_exhaust)\n  apply simp\n  apply (simp add: Bit_def mod_mult_mult1 pos_zmod_mult_2 add.commute)\n  done\n\nlemmas bin_rsplit_aux_simps = bin_rsplit_aux.simps bin_rsplitl_aux.simps\nlemmas rsplit_aux_simps = bin_rsplit_aux_simps\n\nlemmas th_if_simp1 = if_split [where P = \"(=) l\", THEN iffD1, THEN conjunct1, THEN mp] for l\nlemmas th_if_simp2 = if_split [where P = \"(=) l\", THEN iffD1, THEN conjunct2, THEN mp] for l\n\nlemmas rsplit_aux_simp1s = rsplit_aux_simps [THEN th_if_simp1]\n\nlemmas rsplit_aux_simp2ls = rsplit_aux_simps [THEN th_if_simp2]\n\\<comment> \\<open>these safe to \\<open>[simp add]\\<close> as require calculating \\<open>m - n\\<close>\\<close>\nlemmas bin_rsplit_aux_simp2s [simp] = rsplit_aux_simp2ls [unfolded Let_def]\nlemmas rbscl = bin_rsplit_aux_simp2s (2)\n\nlemmas rsplit_aux_0_simps [simp] =\n  rsplit_aux_simp1s [OF disjI1] rsplit_aux_simp1s [OF disjI2]\n\nlemma bin_rsplit_aux_append: \"bin_rsplit_aux n m c (bs @ cs) = bin_rsplit_aux n m c bs @ cs\"\n  apply (induct n m c bs rule: bin_rsplit_aux.induct)\n  apply (subst bin_rsplit_aux.simps)\n  apply (subst bin_rsplit_aux.simps)\n  apply (clarsimp split: prod.split)\n  done\n\nlemma bin_rsplitl_aux_append: \"bin_rsplitl_aux n m c (bs @ cs) = bin_rsplitl_aux n m c bs @ cs\"\n  apply (induct n m c bs rule: bin_rsplitl_aux.induct)\n  apply (subst bin_rsplitl_aux.simps)\n  apply (subst bin_rsplitl_aux.simps)\n  apply (clarsimp split: prod.split)\n  done\n\nlemmas rsplit_aux_apps [where bs = \"[]\"] =\n  bin_rsplit_aux_append bin_rsplitl_aux_append\n\nlemmas rsplit_def_auxs = bin_rsplit_def bin_rsplitl_def\n\nlemmas rsplit_aux_alts = rsplit_aux_apps\n  [unfolded append_Nil rsplit_def_auxs [symmetric]]\n\nlemma bin_split_minus: \"0 < n \\<Longrightarrow> bin_split (Suc (n - 1)) w = bin_split n w\"\n  by auto\n\nlemmas bin_split_minus_simp =\n  bin_split.Suc [THEN [2] bin_split_minus [symmetric, THEN trans]]\n\nlemma bin_split_pred_simp [simp]:\n  \"(0::nat) < numeral bin \\<Longrightarrow>\n    bin_split (numeral bin) w =\n      (let (w1, w2) = bin_split (numeral bin - 1) (bin_rest w)\n       in (w1, w2 BIT bin_last w))\"\n  by (simp only: bin_split_minus_simp)\n\nlemma bin_rsplit_aux_simp_alt:\n  \"bin_rsplit_aux n m c bs =\n    (if m = 0 \\<or> n = 0 then bs\n     else let (a, b) = bin_split n c in bin_rsplit n (m - n, a) @ b # bs)\"\n  apply (simp add: bin_rsplit_aux.simps [of n m c bs])\n  apply (subst rsplit_aux_alts)\n  apply (simp add: bin_rsplit_def)\n  done\n\nlemmas bin_rsplit_simp_alt =\n  trans [OF bin_rsplit_def bin_rsplit_aux_simp_alt]\n\nlemmas bthrs = bin_rsplit_simp_alt [THEN [2] trans]\n\nlemma bin_rsplit_size_sign' [rule_format]:\n  \"n > 0 \\<Longrightarrow> rev sw = bin_rsplit n (nw, w) \\<Longrightarrow> \\<forall>v\\<in>set sw. bintrunc n v = v\"\n  apply (induct sw arbitrary: nw w)\n   apply clarsimp\n  apply clarsimp\n  apply (drule bthrs)\n  apply (simp (no_asm_use) add: Let_def split: prod.split_asm if_split_asm)\n  apply clarify\n  apply (drule split_bintrunc)\n  apply simp\n  done\n\nlemmas bin_rsplit_size_sign = bin_rsplit_size_sign' [OF asm_rl\n  rev_rev_ident [THEN trans] set_rev [THEN equalityD2 [THEN subsetD]]]\n\nlemma bin_nth_rsplit [rule_format] :\n  \"n > 0 \\<Longrightarrow> m < n \\<Longrightarrow>\n    \\<forall>w k nw.\n      rev sw = bin_rsplit n (nw, w) \\<longrightarrow>\n      k < size sw \\<longrightarrow> bin_nth (sw ! k) m = bin_nth w (k * n + m)\"\n  apply (induct sw)\n   apply clarsimp\n  apply clarsimp\n  apply (drule bthrs)\n  apply (simp (no_asm_use) add: Let_def split: prod.split_asm if_split_asm)\n  apply clarify\n  apply (erule allE, erule impE, erule exI)\n  apply (case_tac k)\n   apply clarsimp\n   prefer 2\n   apply clarsimp\n   apply (erule allE)\n   apply (erule (1) impE)\n   apply (drule bin_nth_split, erule conjE, erule allE, erule trans, simp add: ac_simps)+\n  done\n\nlemma bin_rsplit_all: \"0 < nw \\<Longrightarrow> nw \\<le> n \\<Longrightarrow> bin_rsplit n (nw, w) = [bintrunc n w]\"\n  by (auto simp: bin_rsplit_def rsplit_aux_simp2ls split: prod.split dest!: split_bintrunc)\n\nlemma bin_rsplit_l [rule_format]:\n  \"\\<forall>bin. bin_rsplitl n (m, bin) = bin_rsplit n (m, bintrunc m bin)\"\n  apply (rule_tac a = \"m\" in wf_less_than [THEN wf_induct])\n  apply (simp (no_asm) add: bin_rsplitl_def bin_rsplit_def)\n  apply (rule allI)\n  apply (subst bin_rsplitl_aux.simps)\n  apply (subst bin_rsplit_aux.simps)\n  apply (clarsimp simp: Let_def split: prod.split)\n  apply (drule bin_split_trunc)\n  apply (drule sym [THEN trans], assumption)\n  apply (subst rsplit_aux_alts(1))\n  apply (subst rsplit_aux_alts(2))\n  apply clarsimp\n  unfolding bin_rsplit_def bin_rsplitl_def\n  apply simp\n  done\n\nlemma bin_rsplit_rcat [rule_format]:\n  \"n > 0 \\<longrightarrow> bin_rsplit n (n * size ws, bin_rcat n ws) = map (bintrunc n) ws\"\n  apply (unfold bin_rsplit_def bin_rcat_def)\n  apply (rule_tac xs = ws in rev_induct)\n   apply clarsimp\n  apply clarsimp\n  apply (subst rsplit_aux_alts)\n  unfolding bin_split_cat\n  apply simp\n  done\n\nlemma bin_rsplit_aux_len_le [rule_format] :\n  \"\\<forall>ws m. n \\<noteq> 0 \\<longrightarrow> ws = bin_rsplit_aux n nw w bs \\<longrightarrow>\n    length ws \\<le> m \\<longleftrightarrow> nw + length bs * n \\<le> m * n\"\nproof -\n  have *: R\n    if d: \"i \\<le> j \\<or> m < j'\"\n    and R1: \"i * k \\<le> j * k \\<Longrightarrow> R\"\n    and R2: \"Suc m * k' \\<le> j' * k' \\<Longrightarrow> R\"\n    for i j j' k k' m :: nat and R\n    using d\n    apply safe\n    apply (rule R1, erule mult_le_mono1)\n    apply (rule R2, erule Suc_le_eq [THEN iffD2 [THEN mult_le_mono1]])\n    done\n  have **: \"0 < sc \\<Longrightarrow> sc - n + (n + lb * n) \\<le> m * n \\<longleftrightarrow> sc + lb * n \\<le> m * n\"\n    for sc m n lb :: nat\n    apply safe\n     apply arith\n    apply (case_tac \"sc \\<ge> n\")\n     apply arith\n    apply (insert linorder_le_less_linear [of m lb])\n    apply (erule_tac k=n and k'=n in *)\n     apply arith\n    apply simp\n    done\n  show ?thesis\n    apply (induct n nw w bs rule: bin_rsplit_aux.induct)\n    apply (subst bin_rsplit_aux.simps)\n    apply (simp add: ** Let_def split: prod.split)\n    done\nqed\n\nlemma bin_rsplit_len_le: \"n \\<noteq> 0 \\<longrightarrow> ws = bin_rsplit n (nw, w) \\<longrightarrow> length ws \\<le> m \\<longleftrightarrow> nw \\<le> m * n\"\n  by (auto simp: bin_rsplit_def bin_rsplit_aux_len_le)\n\nlemma bin_rsplit_aux_len:\n  \"n \\<noteq> 0 \\<Longrightarrow> length (bin_rsplit_aux n nw w cs) = (nw + n - 1) div n + length cs\"\n  apply (induct n nw w cs rule: bin_rsplit_aux.induct)\n  apply (subst bin_rsplit_aux.simps)\n  apply (clarsimp simp: Let_def split: prod.split)\n  apply (erule thin_rl)\n  apply (case_tac m)\n   apply simp\n  apply (case_tac \"m \\<le> n\")\n   apply (auto simp add: div_add_self2)\n  done\n\nlemma bin_rsplit_len: \"n \\<noteq> 0 \\<Longrightarrow> length (bin_rsplit n (nw, w)) = (nw + n - 1) div n\"\n  by (auto simp: bin_rsplit_def bin_rsplit_aux_len)\n\nlemma bin_rsplit_aux_len_indep:\n  \"n \\<noteq> 0 \\<Longrightarrow> length bs = length cs \\<Longrightarrow>\n    length (bin_rsplit_aux n nw v bs) =\n    length (bin_rsplit_aux n nw w cs)\"\nproof (induct n nw w cs arbitrary: v bs rule: bin_rsplit_aux.induct)\n  case (1 n m w cs v bs)\n  show ?case\n  proof (cases \"m = 0\")\n    case True\n    with \\<open>length bs = length cs\\<close> show ?thesis by simp\n  next\n    case False\n    from \"1.hyps\" \\<open>m \\<noteq> 0\\<close> \\<open>n \\<noteq> 0\\<close>\n    have hyp: \"\\<And>v bs. length bs = Suc (length cs) \\<Longrightarrow>\n      length (bin_rsplit_aux n (m - n) v bs) =\n      length (bin_rsplit_aux n (m - n) (fst (bin_split n w)) (snd (bin_split n w) # cs))\"\n      by auto\n    from \\<open>length bs = length cs\\<close> \\<open>n \\<noteq> 0\\<close> show ?thesis\n      by (auto simp add: bin_rsplit_aux_simp_alt Let_def bin_rsplit_len split: prod.split)\n  qed\nqed\n\nlemma bin_rsplit_len_indep:\n  \"n \\<noteq> 0 \\<Longrightarrow> length (bin_rsplit n (nw, v)) = length (bin_rsplit n (nw, w))\"\n  apply (unfold bin_rsplit_def)\n  apply (simp (no_asm))\n  apply (erule bin_rsplit_aux_len_indep)\n  apply (rule refl)\n  done\n\n\nsubsection \\<open>Logical operations\\<close>\n\nprimrec bin_sc :: \"nat \\<Rightarrow> bool \\<Rightarrow> int \\<Rightarrow> int\"\n  where\n    Z: \"bin_sc 0 b w = bin_rest w BIT b\"\n  | Suc: \"bin_sc (Suc n) b w = bin_sc n b (bin_rest w) BIT bin_last w\"\n\nlemma bin_nth_sc [simp]: \"bin_nth (bin_sc n b w) n \\<longleftrightarrow> b\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sc_sc_same [simp]: \"bin_sc n c (bin_sc n b w) = bin_sc n c w\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sc_sc_diff: \"m \\<noteq> n \\<Longrightarrow> bin_sc m c (bin_sc n b w) = bin_sc n b (bin_sc m c w)\"\n  apply (induct n arbitrary: w m)\n   apply (case_tac [!] m)\n     apply auto\n  done\n\nlemma bin_nth_sc_gen: \"bin_nth (bin_sc n b w) m = (if m = n then b else bin_nth w m)\"\n  by (induct n arbitrary: w m) (case_tac [!] m, auto)\n\nlemma bin_sc_nth [simp]: \"bin_sc n (bin_nth w n) w = w\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sign_sc [simp]: \"bin_sign (bin_sc n b w) = bin_sign w\"\n  by (induct n arbitrary: w) auto\n\nlemma bin_sc_bintr [simp]: \"bintrunc m (bin_sc n x (bintrunc m (w))) = bintrunc m (bin_sc n x w)\"\n  apply (induct n arbitrary: w m)\n   apply (case_tac [!] w rule: bin_exhaust)\n   apply (case_tac [!] m, auto)\n  done\n\nlemma bin_clr_le: \"bin_sc n False w \\<le> w\"\n  apply (induct n arbitrary: w)\n   apply (case_tac [!] w rule: bin_exhaust)\n   apply (auto simp: le_Bits)\n  done\n\nlemma bin_set_ge: \"bin_sc n True w \\<ge> w\"\n  apply (induct n arbitrary: w)\n   apply (case_tac [!] w rule: bin_exhaust)\n   apply (auto simp: le_Bits)\n  done\n\nlemma bintr_bin_clr_le: \"bintrunc n (bin_sc m False w) \\<le> bintrunc n w\"\n  apply (induct n arbitrary: w m)\n   apply simp\n  apply (case_tac w rule: bin_exhaust)\n  apply (case_tac m)\n   apply (auto simp: le_Bits)\n  done\n\nlemma bintr_bin_set_ge: \"bintrunc n (bin_sc m True w) \\<ge> bintrunc n w\"\n  apply (induct n arbitrary: w m)\n   apply simp\n  apply (case_tac w rule: bin_exhaust)\n  apply (case_tac m)\n   apply (auto simp: le_Bits)\n  done\n\nlemma bin_sc_FP [simp]: \"bin_sc n False 0 = 0\"\n  by (induct n) auto\n\nlemma bin_sc_TM [simp]: \"bin_sc n True (- 1) = - 1\"\n  by (induct n) auto\n\nlemmas bin_sc_simps = bin_sc.Z bin_sc.Suc bin_sc_TM bin_sc_FP\n\nlemma bin_sc_minus: \"0 < n \\<Longrightarrow> bin_sc (Suc (n - 1)) b w = bin_sc n b w\"\n  by auto\n\nlemmas bin_sc_Suc_minus =\n  trans [OF bin_sc_minus [symmetric] bin_sc.Suc]\n\nlemma bin_sc_numeral [simp]:\n  \"bin_sc (numeral k) b w =\n    bin_sc (pred_numeral k) b (bin_rest w) BIT bin_last w\"\n  by (simp add: numeral_eq_Suc)\n\ninstantiation int :: bit_operations\nbegin\n\ndefinition int_not_def: \"NOT = (\\<lambda>x::int. - x - 1)\"\n\nfunction bitAND_int\n  where \"bitAND_int x y =\n    (if x = 0 then 0 else if x = -1 then y\n     else (bin_rest x AND bin_rest y) BIT (bin_last x \\<and> bin_last y))\"\n  by pat_completeness simp\n\ntermination\n  by (relation \"measure (nat \\<circ> abs \\<circ> fst)\", simp_all add: bin_rest_def)\n\ndeclare bitAND_int.simps [simp del]\n\ndefinition int_or_def: \"(OR) = (\\<lambda>x y::int. NOT (NOT x AND NOT y))\"\n\ndefinition int_xor_def: \"(XOR) = (\\<lambda>x y::int. (x AND NOT y) OR (NOT x AND y))\"\n\ndefinition [iff]: \"i !! n \\<longleftrightarrow> bin_nth i n\"\n\ndefinition \"lsb i = i !! 0\" for i :: int\n\ndefinition \"set_bit i n b = bin_sc n b i\"\n\ndefinition \"shiftl x n = x * 2 ^ n\" for x :: int\n\ndefinition \"shiftr x n = x div 2 ^ n\" for x :: int\n\ndefinition \"msb x \\<longleftrightarrow> x < 0\" for x :: int\n\ninstance ..\n\nend\n\n\nsubsubsection \\<open>Basic simplification rules\\<close>\n\nlemma int_not_BIT [simp]: \"NOT (w BIT b) = (NOT w) BIT (\\<not> b)\"\n  by (cases b) (simp_all add: int_not_def Bit_def)\n\nlemma int_not_simps [simp]:\n  \"NOT (0::int) = -1\"\n  \"NOT (1::int) = -2\"\n  \"NOT (- 1::int) = 0\"\n  \"NOT (numeral w::int) = - numeral (w + Num.One)\"\n  \"NOT (- numeral (Num.Bit0 w)::int) = numeral (Num.BitM w)\"\n  \"NOT (- numeral (Num.Bit1 w)::int) = numeral (Num.Bit0 w)\"\n  unfolding int_not_def by simp_all\n\nlemma int_not_not [simp]: \"NOT (NOT x) = x\"\n  for x :: int\n  unfolding int_not_def by simp\n\nlemma int_and_0 [simp]: \"0 AND x = 0\"\n  for x :: int\n  by (simp add: bitAND_int.simps)\n\nlemma int_and_m1 [simp]: \"-1 AND x = x\"\n  for x :: int\n  by (simp add: bitAND_int.simps)\n\nlemma int_and_Bits [simp]: \"(x BIT b) AND (y BIT c) = (x AND y) BIT (b \\<and> c)\"\n  by (subst bitAND_int.simps) (simp add: Bit_eq_0_iff Bit_eq_m1_iff)\n\nlemma int_or_zero [simp]: \"0 OR x = x\"\n  for x :: int\n  by (simp add: int_or_def)\n\nlemma int_or_minus1 [simp]: \"-1 OR x = -1\"\n  for x :: int\n  by (simp add: int_or_def)\n\nlemma int_or_Bits [simp]: \"(x BIT b) OR (y BIT c) = (x OR y) BIT (b \\<or> c)\"\n  by (simp add: int_or_def)\n\nlemma int_xor_zero [simp]: \"0 XOR x = x\"\n  for x :: int\n  by (simp add: int_xor_def)\n\nlemma int_xor_Bits [simp]: \"(x BIT b) XOR (y BIT c) = (x XOR y) BIT ((b \\<or> c) \\<and> \\<not> (b \\<and> c))\"\n  unfolding int_xor_def by auto\n\n\nsubsubsection \\<open>Binary destructors\\<close>\n\nlemma bin_rest_NOT [simp]: \"bin_rest (NOT x) = NOT (bin_rest x)\"\n  by (cases x rule: bin_exhaust) simp\n\nlemma bin_last_NOT [simp]: \"bin_last (NOT x) \\<longleftrightarrow> \\<not> bin_last x\"\n  by (cases x rule: bin_exhaust) simp\n\nlemma bin_rest_AND [simp]: \"bin_rest (x AND y) = bin_rest x AND bin_rest y\"\n  by (cases x rule: bin_exhaust, cases y rule: bin_exhaust) simp\n\nlemma bin_last_AND [simp]: \"bin_last (x AND y) \\<longleftrightarrow> bin_last x \\<and> bin_last y\"\n  by (cases x rule: bin_exhaust, cases y rule: bin_exhaust) simp\n\nlemma bin_rest_OR [simp]: \"bin_rest (x OR y) = bin_rest x OR bin_rest y\"\n  by (cases x rule: bin_exhaust, cases y rule: bin_exhaust) simp\n\nlemma bin_last_OR [simp]: \"bin_last (x OR y) \\<longleftrightarrow> bin_last x \\<or> bin_last y\"\n  by (cases x rule: bin_exhaust, cases y rule: bin_exhaust) simp\n\nlemma bin_rest_XOR [simp]: \"bin_rest (x XOR y) = bin_rest x XOR bin_rest y\"\n  by (cases x rule: bin_exhaust, cases y rule: bin_exhaust) simp\n\nlemma bin_last_XOR [simp]:\n  \"bin_last (x XOR y) \\<longleftrightarrow> (bin_last x \\<or> bin_last y) \\<and> \\<not> (bin_last x \\<and> bin_last y)\"\n  by (cases x rule: bin_exhaust, cases y rule: bin_exhaust) simp\n\nlemma bin_nth_ops:\n  \"\\<And>x y. bin_nth (x AND y) n \\<longleftrightarrow> bin_nth x n \\<and> bin_nth y n\"\n  \"\\<And>x y. bin_nth (x OR y) n \\<longleftrightarrow> bin_nth x n \\<or> bin_nth y n\"\n  \"\\<And>x y. bin_nth (x XOR y) n \\<longleftrightarrow> bin_nth x n \\<noteq> bin_nth y n\"\n  \"\\<And>x. bin_nth (NOT x) n \\<longleftrightarrow> \\<not> bin_nth x n\"\n  by (induct n) auto\n\n\nsubsubsection \\<open>Derived properties\\<close>\n\nlemma int_xor_minus1 [simp]: \"-1 XOR x = NOT x\"\n  for x :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_xor_extra_simps [simp]:\n  \"w XOR 0 = w\"\n  \"w XOR -1 = NOT w\"\n  for w :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_or_extra_simps [simp]:\n  \"w OR 0 = w\"\n  \"w OR -1 = -1\"\n  for w :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_and_extra_simps [simp]:\n  \"w AND 0 = 0\"\n  \"w AND -1 = w\"\n  for w :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\ntext \\<open>Commutativity of the above.\\<close>\nlemma bin_ops_comm:\n  fixes x y :: int\n  shows int_and_comm: \"x AND y = y AND x\"\n    and int_or_comm:  \"x OR y = y OR x\"\n    and int_xor_comm: \"x XOR y = y XOR x\"\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bin_ops_same [simp]:\n  \"x AND x = x\"\n  \"x OR x = x\"\n  \"x XOR x = 0\"\n  for x :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemmas bin_log_esimps =\n  int_and_extra_simps  int_or_extra_simps  int_xor_extra_simps\n  int_and_0 int_and_m1 int_or_zero int_or_minus1 int_xor_zero int_xor_minus1\n\n\nsubsubsection \\<open>Basic properties of logical (bit-wise) operations\\<close>\n\nlemma bbw_ao_absorb: \"x AND (y OR x) = x \\<and> x OR (y AND x) = x\"\n  for x y :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_ao_absorbs_other:\n  \"x AND (x OR y) = x \\<and> (y AND x) OR x = x\"\n  \"(y OR x) AND x = x \\<and> x OR (x AND y) = x\"\n  \"(x OR y) AND x = x \\<and> (x AND y) OR x = x\"\n  for x y :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemmas bbw_ao_absorbs [simp] = bbw_ao_absorb bbw_ao_absorbs_other\n\nlemma int_xor_not: \"(NOT x) XOR y = NOT (x XOR y) \\<and> x XOR (NOT y) = NOT (x XOR y)\"\n  for x y :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_and_assoc: \"(x AND y) AND z = x AND (y AND z)\"\n  for x y z :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_or_assoc: \"(x OR y) OR z = x OR (y OR z)\"\n  for x y z :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma int_xor_assoc: \"(x XOR y) XOR z = x XOR (y XOR z)\"\n  for x y z :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemmas bbw_assocs = int_and_assoc int_or_assoc int_xor_assoc\n\n(* BH: Why are these declared as simp rules??? *)\nlemma bbw_lcs [simp]:\n  \"y AND (x AND z) = x AND (y AND z)\"\n  \"y OR (x OR z) = x OR (y OR z)\"\n  \"y XOR (x XOR z) = x XOR (y XOR z)\"\n  for x y :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_not_dist:\n  \"NOT (x OR y) = (NOT x) AND (NOT y)\"\n  \"NOT (x AND y) = (NOT x) OR (NOT y)\"\n  for x y :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_oa_dist: \"(x AND y) OR z = (x OR z) AND (y OR z)\"\n  for x y z :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\nlemma bbw_ao_dist: \"(x OR y) AND z = (x AND z) OR (y AND z)\"\n  for x y z :: int\n  by (auto simp add: bin_eq_iff bin_nth_ops)\n\n(*\nWhy were these declared simp???\ndeclare bin_ops_comm [simp] bbw_assocs [simp]\n*)\n\n\nsubsubsection \\<open>Simplification with numerals\\<close>\n\ntext \\<open>Cases for \\<open>0\\<close> and \\<open>-1\\<close> are already covered by other simp rules.\\<close>\n\nlemma bin_rest_neg_numeral_BitM [simp]:\n  \"bin_rest (- numeral (Num.BitM w)) = - numeral w\"\n  by (simp only: BIT_bin_simps [symmetric] bin_rest_BIT)\n\nlemma bin_last_neg_numeral_BitM [simp]:\n  \"bin_last (- numeral (Num.BitM w))\"\n  by (simp only: BIT_bin_simps [symmetric] bin_last_BIT)\n\n(* FIXME: The rule sets below are very large (24 rules for each\n  operator). Is there a simpler way to do this? *)\n\nlemma int_and_numerals [simp]:\n  \"numeral (Num.Bit0 x) AND numeral (Num.Bit0 y) = (numeral x AND numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) AND numeral (Num.Bit1 y) = (numeral x AND numeral y) BIT False\"\n  \"numeral (Num.Bit1 x) AND numeral (Num.Bit0 y) = (numeral x AND numeral y) BIT False\"\n  \"numeral (Num.Bit1 x) AND numeral (Num.Bit1 y) = (numeral x AND numeral y) BIT True\"\n  \"numeral (Num.Bit0 x) AND - numeral (Num.Bit0 y) = (numeral x AND - numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) AND - numeral (Num.Bit1 y) = (numeral x AND - numeral (y + Num.One)) BIT False\"\n  \"numeral (Num.Bit1 x) AND - numeral (Num.Bit0 y) = (numeral x AND - numeral y) BIT False\"\n  \"numeral (Num.Bit1 x) AND - numeral (Num.Bit1 y) = (numeral x AND - numeral (y + Num.One)) BIT True\"\n  \"- numeral (Num.Bit0 x) AND numeral (Num.Bit0 y) = (- numeral x AND numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) AND numeral (Num.Bit1 y) = (- numeral x AND numeral y) BIT False\"\n  \"- numeral (Num.Bit1 x) AND numeral (Num.Bit0 y) = (- numeral (x + Num.One) AND numeral y) BIT False\"\n  \"- numeral (Num.Bit1 x) AND numeral (Num.Bit1 y) = (- numeral (x + Num.One) AND numeral y) BIT True\"\n  \"- numeral (Num.Bit0 x) AND - numeral (Num.Bit0 y) = (- numeral x AND - numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) AND - numeral (Num.Bit1 y) = (- numeral x AND - numeral (y + Num.One)) BIT False\"\n  \"- numeral (Num.Bit1 x) AND - numeral (Num.Bit0 y) = (- numeral (x + Num.One) AND - numeral y) BIT False\"\n  \"- numeral (Num.Bit1 x) AND - numeral (Num.Bit1 y) = (- numeral (x + Num.One) AND - numeral (y + Num.One)) BIT True\"\n  \"(1::int) AND numeral (Num.Bit0 y) = 0\"\n  \"(1::int) AND numeral (Num.Bit1 y) = 1\"\n  \"(1::int) AND - numeral (Num.Bit0 y) = 0\"\n  \"(1::int) AND - numeral (Num.Bit1 y) = 1\"\n  \"numeral (Num.Bit0 x) AND (1::int) = 0\"\n  \"numeral (Num.Bit1 x) AND (1::int) = 1\"\n  \"- numeral (Num.Bit0 x) AND (1::int) = 0\"\n  \"- numeral (Num.Bit1 x) AND (1::int) = 1\"\n  by (rule bin_rl_eqI; simp)+\n\nlemma int_or_numerals [simp]:\n  \"numeral (Num.Bit0 x) OR numeral (Num.Bit0 y) = (numeral x OR numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) OR numeral (Num.Bit1 y) = (numeral x OR numeral y) BIT True\"\n  \"numeral (Num.Bit1 x) OR numeral (Num.Bit0 y) = (numeral x OR numeral y) BIT True\"\n  \"numeral (Num.Bit1 x) OR numeral (Num.Bit1 y) = (numeral x OR numeral y) BIT True\"\n  \"numeral (Num.Bit0 x) OR - numeral (Num.Bit0 y) = (numeral x OR - numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) OR - numeral (Num.Bit1 y) = (numeral x OR - numeral (y + Num.One)) BIT True\"\n  \"numeral (Num.Bit1 x) OR - numeral (Num.Bit0 y) = (numeral x OR - numeral y) BIT True\"\n  \"numeral (Num.Bit1 x) OR - numeral (Num.Bit1 y) = (numeral x OR - numeral (y + Num.One)) BIT True\"\n  \"- numeral (Num.Bit0 x) OR numeral (Num.Bit0 y) = (- numeral x OR numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) OR numeral (Num.Bit1 y) = (- numeral x OR numeral y) BIT True\"\n  \"- numeral (Num.Bit1 x) OR numeral (Num.Bit0 y) = (- numeral (x + Num.One) OR numeral y) BIT True\"\n  \"- numeral (Num.Bit1 x) OR numeral (Num.Bit1 y) = (- numeral (x + Num.One) OR numeral y) BIT True\"\n  \"- numeral (Num.Bit0 x) OR - numeral (Num.Bit0 y) = (- numeral x OR - numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) OR - numeral (Num.Bit1 y) = (- numeral x OR - numeral (y + Num.One)) BIT True\"\n  \"- numeral (Num.Bit1 x) OR - numeral (Num.Bit0 y) = (- numeral (x + Num.One) OR - numeral y) BIT True\"\n  \"- numeral (Num.Bit1 x) OR - numeral (Num.Bit1 y) = (- numeral (x + Num.One) OR - numeral (y + Num.One)) BIT True\"\n  \"(1::int) OR numeral (Num.Bit0 y) = numeral (Num.Bit1 y)\"\n  \"(1::int) OR numeral (Num.Bit1 y) = numeral (Num.Bit1 y)\"\n  \"(1::int) OR - numeral (Num.Bit0 y) = - numeral (Num.BitM y)\"\n  \"(1::int) OR - numeral (Num.Bit1 y) = - numeral (Num.Bit1 y)\"\n  \"numeral (Num.Bit0 x) OR (1::int) = numeral (Num.Bit1 x)\"\n  \"numeral (Num.Bit1 x) OR (1::int) = numeral (Num.Bit1 x)\"\n  \"- numeral (Num.Bit0 x) OR (1::int) = - numeral (Num.BitM x)\"\n  \"- numeral (Num.Bit1 x) OR (1::int) = - numeral (Num.Bit1 x)\"\n  by (rule bin_rl_eqI; simp)+\n\nlemma int_xor_numerals [simp]:\n  \"numeral (Num.Bit0 x) XOR numeral (Num.Bit0 y) = (numeral x XOR numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) XOR numeral (Num.Bit1 y) = (numeral x XOR numeral y) BIT True\"\n  \"numeral (Num.Bit1 x) XOR numeral (Num.Bit0 y) = (numeral x XOR numeral y) BIT True\"\n  \"numeral (Num.Bit1 x) XOR numeral (Num.Bit1 y) = (numeral x XOR numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) XOR - numeral (Num.Bit0 y) = (numeral x XOR - numeral y) BIT False\"\n  \"numeral (Num.Bit0 x) XOR - numeral (Num.Bit1 y) = (numeral x XOR - numeral (y + Num.One)) BIT True\"\n  \"numeral (Num.Bit1 x) XOR - numeral (Num.Bit0 y) = (numeral x XOR - numeral y) BIT True\"\n  \"numeral (Num.Bit1 x) XOR - numeral (Num.Bit1 y) = (numeral x XOR - numeral (y + Num.One)) BIT False\"\n  \"- numeral (Num.Bit0 x) XOR numeral (Num.Bit0 y) = (- numeral x XOR numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) XOR numeral (Num.Bit1 y) = (- numeral x XOR numeral y) BIT True\"\n  \"- numeral (Num.Bit1 x) XOR numeral (Num.Bit0 y) = (- numeral (x + Num.One) XOR numeral y) BIT True\"\n  \"- numeral (Num.Bit1 x) XOR numeral (Num.Bit1 y) = (- numeral (x + Num.One) XOR numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) XOR - numeral (Num.Bit0 y) = (- numeral x XOR - numeral y) BIT False\"\n  \"- numeral (Num.Bit0 x) XOR - numeral (Num.Bit1 y) = (- numeral x XOR - numeral (y + Num.One)) BIT True\"\n  \"- numeral (Num.Bit1 x) XOR - numeral (Num.Bit0 y) = (- numeral (x + Num.One) XOR - numeral y) BIT True\"\n  \"- numeral (Num.Bit1 x) XOR - numeral (Num.Bit1 y) = (- numeral (x + Num.One) XOR - numeral (y + Num.One)) BIT False\"\n  \"(1::int) XOR numeral (Num.Bit0 y) = numeral (Num.Bit1 y)\"\n  \"(1::int) XOR numeral (Num.Bit1 y) = numeral (Num.Bit0 y)\"\n  \"(1::int) XOR - numeral (Num.Bit0 y) = - numeral (Num.BitM y)\"\n  \"(1::int) XOR - numeral (Num.Bit1 y) = - numeral (Num.Bit0 (y + Num.One))\"\n  \"numeral (Num.Bit0 x) XOR (1::int) = numeral (Num.Bit1 x)\"\n  \"numeral (Num.Bit1 x) XOR (1::int) = numeral (Num.Bit0 x)\"\n  \"- numeral (Num.Bit0 x) XOR (1::int) = - numeral (Num.BitM x)\"\n  \"- numeral (Num.Bit1 x) XOR (1::int) = - numeral (Num.Bit0 (x + Num.One))\"\n  by (rule bin_rl_eqI; simp)+\n\n\nsubsubsection \\<open>Interactions with arithmetic\\<close>\n\nlemma plus_and_or [rule_format]: \"\\<forall>y::int. (x AND y) + (x OR y) = x + y\"\n  apply (induct x rule: bin_induct)\n    apply clarsimp\n   apply clarsimp\n  apply clarsimp\n  apply (case_tac y rule: bin_exhaust)\n  apply clarsimp\n  apply (unfold Bit_def)\n  apply clarsimp\n  apply (erule_tac x = \"x\" in allE)\n  apply simp\n  done\n\nlemma le_int_or: \"bin_sign y = 0 \\<Longrightarrow> x \\<le> x OR y\"\n  for x y :: int\n  apply (induct y arbitrary: x rule: bin_induct)\n    apply clarsimp\n   apply clarsimp\n  apply (case_tac x rule: bin_exhaust)\n  apply (case_tac b)\n   apply (case_tac [!] bit)\n     apply (auto simp: le_Bits)\n  done\n\nlemmas int_and_le =\n  xtrans(3) [OF bbw_ao_absorbs (2) [THEN conjunct2, symmetric] le_int_or]\n\ntext \\<open>Interaction between bit-wise and arithmetic: good example of \\<open>bin_induction\\<close>.\\<close>\nlemma bin_add_not: \"x + NOT x = (-1::int)\"\n  apply (induct x rule: bin_induct)\n    apply clarsimp\n   apply clarsimp\n  apply (case_tac bit, auto)\n  done\n\nlemma mod_BIT:\n  \"bin BIT bit mod 2 ^ Suc n = (bin mod 2 ^ n) BIT bit\" for bit\nproof -\n  have \"2 * (bin mod 2 ^ n) + 1 = (2 * bin mod 2 ^ Suc n) + 1\"\n    by (simp add: mod_mult_mult1)\n  also have \"\\<dots> = ((2 * bin mod 2 ^ Suc n) + 1) mod 2 ^ Suc n\"\n    by (simp add: ac_simps pos_zmod_mult_2)\n  also have \"\\<dots> = (2 * bin + 1) mod 2 ^ Suc n\"\n    by (simp only: mod_simps)\n  finally show ?thesis\n    by (auto simp add: Bit_def)\nqed\n\nlemma AND_mod: \"x AND 2 ^ n - 1 = x mod 2 ^ n\"\n  for x :: int\nproof (induct x arbitrary: n rule: bin_induct)\n  case 1\n  then show ?case\n    by simp\nnext\n  case 2\n  then show ?case\n    by (simp, simp add: m1mod2k)\nnext\n  case (3 bin bit)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis by simp\n  next\n    case (Suc m)\n    with 3 show ?thesis\n      by (simp only: power_BIT mod_BIT int_and_Bits) simp\n  qed\nqed\n\n\nsubsubsection \\<open>Comparison\\<close>\n\nlemma AND_lower [simp]: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> x\"\n  shows \"0 \\<le> x AND y\"\n  using assms\nproof (induct x arbitrary: y rule: bin_induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by (simp only: Min_def)\nnext\n  case (3 bin bit)\n  show ?case\n  proof (cases y rule: bin_exhaust)\n    case (1 bin' bit')\n    from 3 have \"0 \\<le> bin\"\n      by (cases bit) (simp_all add: Bit_def)\n    then have \"0 \\<le> bin AND bin'\" by (rule 3)\n    with 1 show ?thesis\n      by simp\n  qed\nqed\n\nlemma OR_lower [simp]: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> x\" \"0 \\<le> y\"\n  shows \"0 \\<le> x OR y\"\n  using assms\nproof (induct x arbitrary: y rule: bin_induct)\n  case (3 bin bit)\n  show ?case\n  proof (cases y rule: bin_exhaust)\n    case (1 bin' bit')\n    from 3 have \"0 \\<le> bin\"\n      by (cases bit) (simp_all add: Bit_def)\n    moreover from 1 3 have \"0 \\<le> bin'\"\n      by (cases bit') (simp_all add: Bit_def)\n    ultimately have \"0 \\<le> bin OR bin'\" by (rule 3)\n    with 1 show ?thesis\n      by simp\n  qed\nqed simp_all\n\nlemma XOR_lower [simp]: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> x\" \"0 \\<le> y\"\n  shows \"0 \\<le> x XOR y\"\n  using assms\nproof (induct x arbitrary: y rule: bin_induct)\n  case (3 bin bit)\n  show ?case\n  proof (cases y rule: bin_exhaust)\n    case (1 bin' bit')\n    from 3 have \"0 \\<le> bin\"\n      by (cases bit) (simp_all add: Bit_def)\n    moreover from 1 3 have \"0 \\<le> bin'\"\n      by (cases bit') (simp_all add: Bit_def)\n    ultimately have \"0 \\<le> bin XOR bin'\" by (rule 3)\n    with 1 show ?thesis\n      by simp\n  qed\nnext\n  case 2\n  then show ?case by (simp only: Min_def)\nqed simp\n\nlemma AND_upper1 [simp]: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> x\"\n  shows \"x AND y \\<le> x\"\n  using assms\nproof (induct x arbitrary: y rule: bin_induct)\n  case (3 bin bit)\n  show ?case\n  proof (cases y rule: bin_exhaust)\n    case (1 bin' bit')\n    from 3 have \"0 \\<le> bin\"\n      by (cases bit) (simp_all add: Bit_def)\n    then have \"bin AND bin' \\<le> bin\" by (rule 3)\n    with 1 show ?thesis\n      by simp (simp add: Bit_def)\n  qed\nnext\n  case 2\n  then show ?case by (simp only: Min_def)\nqed simp\n\nlemmas AND_upper1' [simp] = order_trans [OF AND_upper1] \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\nlemmas AND_upper1'' [simp] = order_le_less_trans [OF AND_upper1] \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n\nlemma AND_upper2 [simp]: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> y\"\n  shows \"x AND y \\<le> y\"\n  using assms\nproof (induct y arbitrary: x rule: bin_induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by (simp only: Min_def)\nnext\n  case (3 bin bit)\n  show ?case\n  proof (cases x rule: bin_exhaust)\n    case (1 bin' bit')\n    from 3 have \"0 \\<le> bin\"\n      by (cases bit) (simp_all add: Bit_def)\n    then have \"bin' AND bin \\<le> bin\" by (rule 3)\n    with 1 show ?thesis\n      by simp (simp add: Bit_def)\n  qed\nqed\n\nlemmas AND_upper2' [simp] = order_trans [OF AND_upper2] \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\nlemmas AND_upper2'' [simp] = order_le_less_trans [OF AND_upper2] \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n\nlemma OR_upper: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> x\" \"x < 2 ^ n\" \"y < 2 ^ n\"\n  shows \"x OR y < 2 ^ n\"\n  using assms\nproof (induct x arbitrary: y n rule: bin_induct)\n  case (3 bin bit)\n  show ?case\n  proof (cases y rule: bin_exhaust)\n    case (1 bin' bit')\n    show ?thesis\n    proof (cases n)\n      case 0\n      with 3 have \"bin BIT bit = 0\"\n        by (simp add: Bit_def)\n      then have \"bin = 0\" and \"\\<not> bit\"\n        by (auto simp add: Bit_def split: if_splits) arith\n      then show ?thesis using 0 1 \\<open>y < 2 ^ n\\<close>\n        by simp\n    next\n      case (Suc m)\n      from 3 have \"0 \\<le> bin\"\n        by (cases bit) (simp_all add: Bit_def)\n      moreover from 3 Suc have \"bin < 2 ^ m\"\n        by (cases bit) (simp_all add: Bit_def)\n      moreover from 1 3 Suc have \"bin' < 2 ^ m\"\n        by (cases bit') (simp_all add: Bit_def)\n      ultimately have \"bin OR bin' < 2 ^ m\" by (rule 3)\n      with 1 Suc show ?thesis\n        by simp (simp add: Bit_def)\n    qed\n  qed\nqed simp_all\n\nlemma XOR_upper: \\<^marker>\\<open>contributor \\<open>Stefan Berghofer\\<close>\\<close>\n  fixes x y :: int\n  assumes \"0 \\<le> x\" \"x < 2 ^ n\" \"y < 2 ^ n\"\n  shows \"x XOR y < 2 ^ n\"\n  using assms\nproof (induct x arbitrary: y n rule: bin_induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by (simp only: Min_def)\nnext\n  case (3 bin bit)\n  show ?case\n  proof (cases y rule: bin_exhaust)\n    case (1 bin' bit')\n    show ?thesis\n    proof (cases n)\n      case 0\n      with 3 have \"bin BIT bit = 0\"\n        by (simp add: Bit_def)\n      then have \"bin = 0\" and \"\\<not> bit\"\n        by (auto simp add: Bit_def split: if_splits) arith\n      then show ?thesis using 0 1 \\<open>y < 2 ^ n\\<close>\n        by simp\n    next\n      case (Suc m)\n      from 3 have \"0 \\<le> bin\"\n        by (cases bit) (simp_all add: Bit_def)\n      moreover from 3 Suc have \"bin < 2 ^ m\"\n        by (cases bit) (simp_all add: Bit_def)\n      moreover from 1 3 Suc have \"bin' < 2 ^ m\"\n        by (cases bit') (simp_all add: Bit_def)\n      ultimately have \"bin XOR bin' < 2 ^ m\" by (rule 3)\n      with 1 Suc show ?thesis\n        by simp (simp add: Bit_def)\n    qed\n  qed\nqed\n\n\n\nsubsubsection \\<open>Truncating results of bit-wise operations\\<close>\n\nlemma bin_trunc_ao:\n  \"bintrunc n x AND bintrunc n y = bintrunc n (x AND y)\"\n  \"bintrunc n x OR bintrunc n y = bintrunc n (x OR y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\nlemma bin_trunc_xor: \"bintrunc n (bintrunc n x XOR bintrunc n y) = bintrunc n (x XOR y)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\nlemma bin_trunc_not: \"bintrunc n (NOT (bintrunc n x)) = bintrunc n (NOT x)\"\n  by (auto simp add: bin_eq_iff bin_nth_ops nth_bintr)\n\ntext \\<open>Want theorems of the form of \\<open>bin_trunc_xor\\<close>.\\<close>\nlemma bintr_bintr_i: \"x = bintrunc n y \\<Longrightarrow> bintrunc n x = bintrunc n y\"\n  by auto\n\nlemmas bin_trunc_and = bin_trunc_ao(1) [THEN bintr_bintr_i]\nlemmas bin_trunc_or = bin_trunc_ao(2) [THEN bintr_bintr_i]\n\n\nsubsubsection \\<open>More lemmas\\<close>\n\nlemma not_int_cmp_0 [simp]:\n  fixes i :: int shows\n  \"0 < NOT i \\<longleftrightarrow> i < -1\"\n  \"0 \\<le> NOT i \\<longleftrightarrow> i < 0\"\n  \"NOT i < 0 \\<longleftrightarrow> i \\<ge> 0\"\n  \"NOT i \\<le> 0 \\<longleftrightarrow> i \\<ge> -1\"\nby(simp_all add: int_not_def) arith+\n\nlemma bbw_ao_dist2: \"(x :: int) AND (y OR z) = x AND y OR x AND z\"\nby(metis int_and_comm bbw_ao_dist)\n\nlemmas int_and_ac = bbw_lcs(1) int_and_comm int_and_assoc\n\nlemma int_nand_same [simp]: fixes x :: int shows \"x AND NOT x = 0\"\nby(induct x y\\<equiv>\"NOT x\" rule: bitAND_int.induct)(subst bitAND_int.simps, clarsimp)\n\nlemma int_nand_same_middle: fixes x :: int shows \"x AND y AND NOT x = 0\"\nby (metis bbw_lcs(1) int_and_0 int_nand_same)\n\nlemma and_xor_dist: fixes x :: int shows\n  \"x AND (y XOR z) = (x AND y) XOR (x AND z)\"\nby(simp add: int_xor_def bbw_ao_dist2 bbw_not_dist int_and_ac int_nand_same_middle)\n\nlemma int_and_lt0 [simp]: fixes x y :: int shows\n  \"x AND y < 0 \\<longleftrightarrow> x < 0 \\<and> y < 0\"\nby(induct x y rule: bitAND_int.induct)(subst bitAND_int.simps, simp)\n\nlemma int_and_ge0 [simp]: fixes x y :: int shows \n  \"x AND y \\<ge> 0 \\<longleftrightarrow> x \\<ge> 0 \\<or> y \\<ge> 0\"\nby (metis int_and_lt0 linorder_not_less)\n\nlemma int_and_1: fixes x :: int shows \"x AND 1 = x mod 2\"\nby(subst bitAND_int.simps)(simp add: Bit_def bin_last_def zmod_minus1)\n\nlemma int_1_and: fixes x :: int shows \"1 AND x = x mod 2\"\nby(subst int_and_comm)(simp add: int_and_1)\n\nlemma int_or_lt0 [simp]: fixes x y :: int shows \n  \"x OR y < 0 \\<longleftrightarrow> x < 0 \\<or> y < 0\"\nby(simp add: int_or_def)\n\nlemma int_xor_lt0 [simp]: fixes x y :: int shows\n  \"x XOR y < 0 \\<longleftrightarrow> ((x < 0) \\<noteq> (y < 0))\"\nby(auto simp add: int_xor_def)\n\nlemma int_xor_ge0 [simp]: fixes x y :: int shows\n  \"x XOR y \\<ge> 0 \\<longleftrightarrow> ((x \\<ge> 0) \\<longleftrightarrow> (y \\<ge> 0))\"\nby (metis int_xor_lt0 linorder_not_le)\n\nlemma bin_last_conv_AND:\n  \"bin_last i \\<longleftrightarrow> i AND 1 \\<noteq> 0\"\nproof -\n  obtain x b where \"i = x BIT b\" by(cases i rule: bin_exhaust)\n  hence \"i AND 1 = 0 BIT b\"\n    by(simp add: BIT_special_simps(2)[symmetric] del: BIT_special_simps(2))\n  thus ?thesis using \\<open>i = x BIT b\\<close> by(cases b) simp_all\nqed\n\nlemma bitval_bin_last:\n  \"of_bool (bin_last i) = i AND 1\"\nproof -\n  obtain x b where \"i = x BIT b\" by(cases i rule: bin_exhaust)\n  hence \"i AND 1 = 0 BIT b\"\n    by(simp add: BIT_special_simps(2)[symmetric] del: BIT_special_simps(2))\n  thus ?thesis by(cases b)(simp_all add: bin_last_conv_AND)\nqed\n\nlemma bin_sign_and:\n  \"bin_sign (i AND j) = - (bin_sign i * bin_sign j)\"\nby(simp add: bin_sign_def)\n\nlemma minus_BIT_0: fixes x y :: int shows \"x BIT b - y BIT False = (x - y) BIT b\"\nby(simp add: Bit_def)\n\nlemma int_not_neg_numeral: \"NOT (- numeral n) = (Num.sub n num.One :: int)\"\nby(simp add: int_not_def)\n\nlemma int_neg_numeral_pOne_conv_not: \"- numeral (n + num.One) = (NOT (numeral n) :: int)\"\nby(simp add: int_not_def)\n\n\nsubsection \\<open>Setting and clearing bits\\<close>\n\n\n\nlemma int_lsb_BIT [simp]: fixes x :: int shows\n  \"lsb (x BIT b) \\<longleftrightarrow> b\"\nby(simp add: lsb_int_def)\n\nlemma bin_last_conv_lsb: \"bin_last = lsb\"\nby(clarsimp simp add: lsb_int_def fun_eq_iff)\n\nlemma int_lsb_numeral [simp]:\n  \"lsb (0 :: int) = False\"\n  \"lsb (1 :: int) = True\"\n  \"lsb (Numeral1 :: int) = True\"\n  \"lsb (- 1 :: int) = True\"\n  \"lsb (- Numeral1 :: int) = True\"\n  \"lsb (numeral (num.Bit0 w) :: int) = False\"\n  \"lsb (numeral (num.Bit1 w) :: int) = True\"\n  \"lsb (- numeral (num.Bit0 w) :: int) = False\"\n  \"lsb (- numeral (num.Bit1 w) :: int) = True\"\nby(simp_all add: lsb_int_def)\n\nlemma int_set_bit_0 [simp]: fixes x :: int shows\n  \"set_bit x 0 b = bin_rest x BIT b\"\nby(auto simp add: set_bit_int_def intro: bin_rl_eqI)\n\nlemma int_set_bit_Suc: fixes x :: int shows\n  \"set_bit x (Suc n) b = set_bit (bin_rest x) n b BIT bin_last x\"\nby(auto simp add: set_bit_int_def twice_conv_BIT intro: bin_rl_eqI)\n\nlemma bin_last_set_bit:\n  \"bin_last (set_bit x n b) = (if n > 0 then bin_last x else b)\"\nby(cases n)(simp_all add: int_set_bit_Suc)\n\nlemma bin_rest_set_bit: \n  \"bin_rest (set_bit x n b) = (if n > 0 then set_bit (bin_rest x) (n - 1) b else bin_rest x)\"\nby(cases n)(simp_all add: int_set_bit_Suc)\n\nlemma int_set_bit_numeral: fixes x :: int shows\n  \"set_bit x (numeral w) b = set_bit (bin_rest x) (pred_numeral w) b BIT bin_last x\"\nby(simp add: set_bit_int_def)\n\nlemmas int_set_bit_numerals [simp] =\n  int_set_bit_numeral[where x=\"numeral w'\"] \n  int_set_bit_numeral[where x=\"- numeral w'\"]\n  int_set_bit_numeral[where x=\"Numeral1\"]\n  int_set_bit_numeral[where x=\"1\"]\n  int_set_bit_numeral[where x=\"0\"]\n  int_set_bit_Suc[where x=\"numeral w'\"]\n  int_set_bit_Suc[where x=\"- numeral w'\"]\n  int_set_bit_Suc[where x=\"Numeral1\"]\n  int_set_bit_Suc[where x=\"1\"]\n  int_set_bit_Suc[where x=\"0\"]\n  for w'\n\nlemma int_shiftl_BIT: fixes x :: int\n  shows int_shiftl0 [simp]: \"x << 0 = x\"\n  and int_shiftl_Suc [simp]: \"x << Suc n = (x << n) BIT False\"\nby(auto simp add: shiftl_int_def Bit_def)\n\nlemma int_0_shiftl [simp]: \"0 << n = (0 :: int)\"\nby(induct n) simp_all\n\nlemma bin_last_shiftl: \"bin_last (x << n) \\<longleftrightarrow> n = 0 \\<and> bin_last x\"\nby(cases n)(simp_all)\n\nlemma bin_rest_shiftl: \"bin_rest (x << n) = (if n > 0 then x << (n - 1) else bin_rest x)\"\nby(cases n)(simp_all)\n\nlemma bin_nth_shiftl [simp]: \"bin_nth (x << n) m \\<longleftrightarrow> n \\<le> m \\<and> bin_nth x (m - n)\"\nproof(induct n arbitrary: x m)\n  case (Suc n)\n  thus ?case by(cases m) simp_all\nqed simp\n\nlemma int_shiftr_BIT [simp]: fixes x :: int\n  shows int_shiftr0: \"x >> 0 = x\"\n  and int_shiftr_Suc: \"x BIT b >> Suc n = x >> n\"\nproof -\n  show \"x >> 0 = x\" by (simp add: shiftr_int_def)\n  show \"x BIT b >> Suc n = x >> n\" by (cases b)\n   (simp_all add: shiftr_int_def Bit_def add.commute pos_zdiv_mult_2)\nqed\n\nlemma bin_last_shiftr: \"bin_last (x >> n) \\<longleftrightarrow> x !! n\"\nproof(induct n arbitrary: x)\n  case 0 thus ?case by simp\nnext\n  case (Suc n)\n  thus ?case by(cases x rule: bin_exhaust) simp\nqed\n\nlemma bin_rest_shiftr [simp]: \"bin_rest (x >> n) = x >> Suc n\"\nproof(induct n arbitrary: x)\n  case 0\n  thus ?case by(cases x rule: bin_exhaust) auto\nnext\n  case (Suc n)\n  thus ?case by(cases x rule: bin_exhaust) auto\nqed\n\nlemma bin_nth_shiftr [simp]: \"bin_nth (x >> n) m = bin_nth x (n + m)\"\nproof(induct n arbitrary: x m)\n  case (Suc n)\n  thus ?case by(cases x rule: bin_exhaust) simp_all\nqed simp\n\nlemma bin_nth_conv_AND:\n  fixes x :: int shows \n  \"bin_nth x n \\<longleftrightarrow> x AND (1 << n) \\<noteq> 0\"\nproof(induct n arbitrary: x)\n  case 0 \n  thus ?case by(simp add: int_and_1 bin_last_def)\nnext\n  case (Suc n)\n  thus ?case by(cases x rule: bin_exhaust)(simp_all add: bin_nth_ops Bit_eq_0_iff)\nqed\n\nlemma int_shiftl_numeral [simp]: \n  \"(numeral w :: int) << numeral w' = numeral (num.Bit0 w) << pred_numeral w'\"\n  \"(- numeral w :: int) << numeral w' = - numeral (num.Bit0 w) << pred_numeral w'\"\nby(simp_all add: numeral_eq_Suc Bit_def shiftl_int_def)\n  (metis add_One mult_inc semiring_norm(11) semiring_norm(13) semiring_norm(2) semiring_norm(6) semiring_norm(87))+\n\nlemma int_shiftl_One_numeral [simp]: \"(1 :: int) << numeral w = 2 << pred_numeral w\"\nby(metis int_shiftl_numeral numeral_One)\n\nlemma shiftl_ge_0 [simp]: fixes i :: int shows \"i << n \\<ge> 0 \\<longleftrightarrow> i \\<ge> 0\"\nby(induct n) simp_all\n\nlemma shiftl_lt_0 [simp]: fixes i :: int shows \"i << n < 0 \\<longleftrightarrow> i < 0\"\nby (metis not_le shiftl_ge_0)\n\nlemma int_shiftl_test_bit: \"(n << i :: int) !! m \\<longleftrightarrow> m \\<ge> i \\<and> n !! (m - i)\"\nproof(induction i)\n  case (Suc n)\n  thus ?case by(cases m) simp_all\nqed simp\n\nlemma int_0shiftr [simp]: \"(0 :: int) >> x = 0\"\nby(simp add: shiftr_int_def)\n\nlemma int_minus1_shiftr [simp]: \"(-1 :: int) >> x = -1\"\nby(simp add: shiftr_int_def div_eq_minus1)\n\nlemma int_shiftr_ge_0 [simp]: fixes i :: int shows \"i >> n \\<ge> 0 \\<longleftrightarrow> i \\<ge> 0\"\nproof(induct n arbitrary: i)\n  case (Suc n)\n  thus ?case by(cases i rule: bin_exhaust) simp_all\nqed simp\n\nlemma int_shiftr_lt_0 [simp]: fixes i :: int shows \"i >> n < 0 \\<longleftrightarrow> i < 0\"\nby (metis int_shiftr_ge_0 not_less)\n\nlemma int_shiftr_numeral [simp]:\n  \"(1 :: int) >> numeral w' = 0\"\n  \"(numeral num.One :: int) >> numeral w' = 0\"\n  \"(numeral (num.Bit0 w) :: int) >> numeral w' = numeral w >> pred_numeral w'\"\n  \"(numeral (num.Bit1 w) :: int) >> numeral w' = numeral w >> pred_numeral w'\"\n  \"(- numeral (num.Bit0 w) :: int) >> numeral w' = - numeral w >> pred_numeral w'\"\n  \"(- numeral (num.Bit1 w) :: int) >> numeral w' = - numeral (Num.inc w) >> pred_numeral w'\"\n  by (simp_all only: numeral_One expand_BIT numeral_eq_Suc int_shiftr_Suc BIT_special_simps(2)[symmetric] int_0shiftr add_One uminus_Bit_eq)\n    (simp_all add: add_One)\n\nlemma int_shiftr_numeral_Suc0 [simp]:\n  \"(1 :: int) >> Suc 0 = 0\"\n  \"(numeral num.One :: int) >> Suc 0 = 0\"\n  \"(numeral (num.Bit0 w) :: int) >> Suc 0 = numeral w\"\n  \"(numeral (num.Bit1 w) :: int) >> Suc 0 = numeral w\"\n  \"(- numeral (num.Bit0 w) :: int) >> Suc 0 = - numeral w\"\n  \"(- numeral (num.Bit1 w) :: int) >> Suc 0 = - numeral (Num.inc w)\"\nby(simp_all only: One_nat_def[symmetric] numeral_One[symmetric] int_shiftr_numeral pred_numeral_simps int_shiftr0)\n\nlemma bin_nth_minus_p2:\n  assumes sign: \"bin_sign x = 0\"\n  and y: \"y = 1 << n\"\n  and m: \"m < n\"\n  and x: \"x < y\"\n  shows \"bin_nth (x - y) m = bin_nth x m\"\nusing sign m x unfolding y\nproof(induction m arbitrary: x y n)\n  case 0\n  thus ?case\n    by(simp add: bin_last_def shiftl_int_def) (metis (hide_lams, no_types) mod_diff_right_eq mod_self neq0_conv numeral_One power_eq_0_iff power_mod diff_zero zero_neq_numeral)\nnext\n  case (Suc m)\n  from \\<open>Suc m < n\\<close> obtain n' where [simp]: \"n = Suc n'\" by(cases n) auto\n  obtain x' b where [simp]: \"x = x' BIT b\" by(cases x rule: bin_exhaust)\n  from \\<open>bin_sign x = 0\\<close> have \"bin_sign x' = 0\" by simp\n  moreover from \\<open>x < 1 << n\\<close> have \"x' < 1 << n'\"\n    by(cases b)(simp_all add: Bit_def shiftl_int_def)\n  moreover have \"(2 * x' + of_bool b - 2 * 2 ^ n') div 2 = x' + (- (2 ^ n') + of_bool b div 2)\"\n    by(simp only: add_diff_eq[symmetric] add.commute div_mult_self2[OF zero_neq_numeral[symmetric]])\n  ultimately show ?case using Suc.IH[of x' n'] Suc.prems\n    by(cases b)(simp_all add: Bit_def bin_rest_def shiftl_int_def)\nqed\n\nlemma bin_clr_conv_NAND:\n  \"bin_sc n False i = i AND NOT (1 << n)\"\nby(induct n arbitrary: i)(auto intro: bin_rl_eqI)\n\nlemma bin_set_conv_OR:\n  \"bin_sc n True i = i OR (1 << n)\"\nby(induct n arbitrary: i)(auto intro: bin_rl_eqI)\n\nlemma msb_conv_bin_sign: \"msb x \\<longleftrightarrow> bin_sign x = -1\"\nby(simp add: bin_sign_def not_le msb_int_def)\n\nlemma msb_BIT [simp]: \"msb (x BIT b) = msb x\"\nby(simp add: msb_int_def)\n\nlemma msb_bin_rest [simp]: \"msb (bin_rest x) = msb x\"\nby(simp add: msb_int_def)\n\nlemma int_msb_and [simp]: \"msb ((x :: int) AND y) \\<longleftrightarrow> msb x \\<and> msb y\"\nby(simp add: msb_int_def)\n\nlemma int_msb_or [simp]: \"msb ((x :: int) OR y) \\<longleftrightarrow> msb x \\<or> msb y\"\nby(simp add: msb_int_def)\n\nlemma int_msb_xor [simp]: \"msb ((x :: int) XOR y) \\<longleftrightarrow> msb x \\<noteq> msb y\"\nby(simp add: msb_int_def)\n\nlemma int_msb_not [simp]: \"msb (NOT (x :: int)) \\<longleftrightarrow> \\<not> msb x\"\nby(simp add: msb_int_def not_less)\n\nlemma msb_shiftl [simp]: \"msb ((x :: int) << n) \\<longleftrightarrow> msb x\"\nby(simp add: msb_int_def)\n\nlemma msb_shiftr [simp]: \"msb ((x :: int) >> r) \\<longleftrightarrow> msb x\"\nby(simp add: msb_int_def)\n\nlemma msb_bin_sc [simp]: \"msb (bin_sc n b x) \\<longleftrightarrow> msb x\"\nby(simp add: msb_conv_bin_sign)\n\nlemma msb_set_bit [simp]: \"msb (set_bit (x :: int) n b) \\<longleftrightarrow> msb x\"\nby(simp add: msb_conv_bin_sign set_bit_int_def)\n\nlemma msb_0 [simp]: \"msb (0 :: int) = False\"\nby(simp add: msb_int_def)\n\nlemma msb_1 [simp]: \"msb (1 :: int) = False\"\nby(simp add: msb_int_def)\n\nlemma msb_numeral [simp]:\n  \"msb (numeral n :: int) = False\"\n  \"msb (- numeral n :: int) = True\"\nby(simp_all add: msb_int_def)\n\n\nsubsection \\<open>Semantic interpretation of \\<^typ>\\<open>bool list\\<close> as \\<^typ>\\<open>int\\<close>\\<close>\n\nlemma bin_bl_bin': \"bl_to_bin (bin_to_bl_aux n w bs) = bl_to_bin_aux bs (bintrunc n w)\"\n  by (induct n arbitrary: w bs) (auto simp: bl_to_bin_def)\n\nlemma bin_bl_bin [simp]: \"bl_to_bin (bin_to_bl n w) = bintrunc n w\"\n  by (auto simp: bin_to_bl_def bin_bl_bin')\n\nlemma bl_to_bin_rep_F: \"bl_to_bin (replicate n False @ bl) = bl_to_bin bl\"\n  by (simp add: bin_to_bl_zero_aux [symmetric] bin_bl_bin') (simp add: bl_to_bin_def)\n\nlemma bin_to_bl_trunc [simp]: \"n \\<le> m \\<Longrightarrow> bin_to_bl n (bintrunc m w) = bin_to_bl n w\"\n  by (auto intro: bl_to_bin_inj)\n\nlemma bin_to_bl_aux_bintr:\n  \"bin_to_bl_aux n (bintrunc m bin) bl =\n    replicate (n - m) False @ bin_to_bl_aux (min n m) bin bl\"\n  apply (induct n arbitrary: m bin bl)\n   apply clarsimp\n  apply clarsimp\n  apply (case_tac \"m\")\n   apply (clarsimp simp: bin_to_bl_zero_aux)\n   apply (erule thin_rl)\n   apply (induct_tac n)\n    apply auto\n  done\n\nlemma bin_to_bl_bintr:\n  \"bin_to_bl n (bintrunc m bin) = replicate (n - m) False @ bin_to_bl (min n m) bin\"\n  unfolding bin_to_bl_def by (rule bin_to_bl_aux_bintr)\n\nlemma bl_to_bin_rep_False: \"bl_to_bin (replicate n False) = 0\"\n  by (induct n) auto\n\nlemma len_bin_to_bl_aux: \"length (bin_to_bl_aux n w bs) = n + length bs\"\n  by (fact size_bin_to_bl_aux)\n\nlemma len_bin_to_bl: \"length (bin_to_bl n w) = n\"\n  by (fact size_bin_to_bl) (* FIXME: duplicate *)\n\nlemma sign_bl_bin': \"bin_sign (bl_to_bin_aux bs w) = bin_sign w\"\n  by (induct bs arbitrary: w) auto\n\nlemma sign_bl_bin: \"bin_sign (bl_to_bin bs) = 0\"\n  by (simp add: bl_to_bin_def sign_bl_bin')\n\nlemma bl_sbin_sign_aux: \"hd (bin_to_bl_aux (Suc n) w bs) = (bin_sign (sbintrunc n w) = -1)\"\n  apply (induct n arbitrary: w bs)\n   apply clarsimp\n   apply (cases w rule: bin_exhaust)\n   apply simp\n  done\n\nlemma bl_sbin_sign: \"hd (bin_to_bl (Suc n) w) = (bin_sign (sbintrunc n w) = -1)\"\n  unfolding bin_to_bl_def by (rule bl_sbin_sign_aux)\n\nlemma bin_nth_of_bl_aux:\n  \"bin_nth (bl_to_bin_aux bl w) n =\n    (n < size bl \\<and> rev bl ! n \\<or> n \\<ge> length bl \\<and> bin_nth w (n - size bl))\"\n  apply (induct bl arbitrary: w)\n   apply clarsimp\n  apply clarsimp\n  apply (cut_tac x=n and y=\"size bl\" in linorder_less_linear)\n  apply (erule disjE, simp add: nth_append)+\n  apply auto\n  done\n\nlemma bin_nth_of_bl: \"bin_nth (bl_to_bin bl) n = (n < length bl \\<and> rev bl ! n)\"\n  by (simp add: bl_to_bin_def bin_nth_of_bl_aux)\n\nlemma bin_nth_bl: \"n < m \\<Longrightarrow> bin_nth w n = nth (rev (bin_to_bl m w)) n\"\n  apply (induct n arbitrary: m w)\n   apply clarsimp\n   apply (case_tac m, clarsimp)\n   apply (clarsimp simp: bin_to_bl_def)\n   apply (simp add: bin_to_bl_aux_alt)\n  apply clarsimp\n  apply (case_tac m, clarsimp)\n  apply (clarsimp simp: bin_to_bl_def)\n  apply (simp add: bin_to_bl_aux_alt)\n  done\n\nlemma nth_bin_to_bl_aux:\n  \"n < m + length bl \\<Longrightarrow> (bin_to_bl_aux m w bl) ! n =\n    (if n < m then bin_nth w (m - 1 - n) else bl ! (n - m))\"\n  apply (induct m arbitrary: w n bl)\n   apply clarsimp\n  apply clarsimp\n  apply (case_tac w rule: bin_exhaust)\n  apply simp\n  done\n\nlemma nth_bin_to_bl: \"n < m \\<Longrightarrow> (bin_to_bl m w) ! n = bin_nth w (m - Suc n)\"\n  by (simp add: bin_to_bl_def nth_bin_to_bl_aux)\n\nlemma bl_to_bin_lt2p_aux: \"bl_to_bin_aux bs w < (w + 1) * (2 ^ length bs)\"\n  apply (induct bs arbitrary: w)\n   apply clarsimp\n  apply clarsimp\n  apply (drule meta_spec, erule xtrans(8) [rotated], simp add: Bit_def)+\n  done\n\nlemma bl_to_bin_lt2p_drop: \"bl_to_bin bs < 2 ^ length (dropWhile Not bs)\"\nproof (induct bs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons b bs)\n  with bl_to_bin_lt2p_aux[where w=1] show ?case\n    by (simp add: bl_to_bin_def)\nqed\n\nlemma bl_to_bin_lt2p: \"bl_to_bin bs < 2 ^ length bs\"\n  by (metis bin_bl_bin bintr_lt2p bl_bin_bl)\n\nlemma bl_to_bin_ge2p_aux: \"bl_to_bin_aux bs w \\<ge> w * (2 ^ length bs)\"\n  apply (induct bs arbitrary: w)\n   apply clarsimp\n  apply clarsimp\n   apply (drule meta_spec, erule order_trans [rotated],\n          simp add: Bit_B0_2t Bit_B1_2t algebra_simps)+\n   apply (simp add: Bit_def)\n  done\n\nlemma bl_to_bin_ge0: \"bl_to_bin bs \\<ge> 0\"\n  apply (unfold bl_to_bin_def)\n  apply (rule xtrans(4))\n   apply (rule bl_to_bin_ge2p_aux)\n  apply simp\n  done\n\nlemma butlast_rest_bin: \"butlast (bin_to_bl n w) = bin_to_bl (n - 1) (bin_rest w)\"\n  apply (unfold bin_to_bl_def)\n  apply (cases w rule: bin_exhaust)\n  apply (cases n, clarsimp)\n  apply clarsimp\n  apply (auto simp add: bin_to_bl_aux_alt)\n  done\n\nlemma butlast_bin_rest: \"butlast bl = bin_to_bl (length bl - Suc 0) (bin_rest (bl_to_bin bl))\"\n  using butlast_rest_bin [where w=\"bl_to_bin bl\" and n=\"length bl\"] by simp\n\nlemma butlast_rest_bl2bin_aux:\n  \"bl \\<noteq> [] \\<Longrightarrow> bl_to_bin_aux (butlast bl) w = bin_rest (bl_to_bin_aux bl w)\"\n  by (induct bl arbitrary: w) auto\n\nlemma butlast_rest_bl2bin: \"bl_to_bin (butlast bl) = bin_rest (bl_to_bin bl)\"\n  by (cases bl) (auto simp: bl_to_bin_def butlast_rest_bl2bin_aux)\n\nlemma trunc_bl2bin_aux:\n  \"bintrunc m (bl_to_bin_aux bl w) =\n    bl_to_bin_aux (drop (length bl - m) bl) (bintrunc (m - length bl) w)\"\nproof (induct bl arbitrary: w)\n  case Nil\n  show ?case by simp\nnext\n  case (Cons b bl)\n  show ?case\n  proof (cases \"m - length bl\")\n    case 0\n    then have \"Suc (length bl) - m = Suc (length bl - m)\" by simp\n    with Cons show ?thesis by simp\n  next\n    case (Suc n)\n    then have \"m - Suc (length bl) = n\" by simp\n    with Cons Suc show ?thesis by simp\n  qed\nqed\n\nlemma trunc_bl2bin: \"bintrunc m (bl_to_bin bl) = bl_to_bin (drop (length bl - m) bl)\"\n  by (simp add: bl_to_bin_def trunc_bl2bin_aux)\n\nlemma trunc_bl2bin_len [simp]: \"bintrunc (length bl) (bl_to_bin bl) = bl_to_bin bl\"\n  by (simp add: trunc_bl2bin)\n\nlemma bl2bin_drop: \"bl_to_bin (drop k bl) = bintrunc (length bl - k) (bl_to_bin bl)\"\n  apply (rule trans)\n   prefer 2\n   apply (rule trunc_bl2bin [symmetric])\n  apply (cases \"k \\<le> length bl\")\n   apply auto\n  done\n\nlemma take_rest_power_bin: \"m \\<le> n \\<Longrightarrow> take m (bin_to_bl n w) = bin_to_bl m ((bin_rest ^^ (n - m)) w)\"\n  apply (rule nth_equalityI)\n   apply simp\n  apply (clarsimp simp add: nth_bin_to_bl nth_rest_power_bin)\n  done\n\nlemma last_bin_last': \"size xs > 0 \\<Longrightarrow> last xs \\<longleftrightarrow> bin_last (bl_to_bin_aux xs w)\"\n  by (induct xs arbitrary: w) auto\n\nlemma last_bin_last: \"size xs > 0 \\<Longrightarrow> last xs \\<longleftrightarrow> bin_last (bl_to_bin xs)\"\n  unfolding bl_to_bin_def by (erule last_bin_last')\n\nlemma bin_last_last: \"bin_last w \\<longleftrightarrow> last (bin_to_bl (Suc n) w)\"\n  by (simp add: bin_to_bl_def) (auto simp: bin_to_bl_aux_alt)\n\nlemma drop_bin2bl_aux:\n  \"drop m (bin_to_bl_aux n bin bs) =\n    bin_to_bl_aux (n - m) bin (drop (m - n) bs)\"\n  apply (induct n arbitrary: m bin bs, clarsimp)\n  apply clarsimp\n  apply (case_tac bin rule: bin_exhaust)\n  apply (case_tac \"m \\<le> n\", simp)\n  apply (case_tac \"m - n\", simp)\n  apply simp\n  apply (rule_tac f = \"\\<lambda>nat. drop nat bs\" in arg_cong)\n  apply simp\n  done\n\nlemma drop_bin2bl: \"drop m (bin_to_bl n bin) = bin_to_bl (n - m) bin\"\n  by (simp add: bin_to_bl_def drop_bin2bl_aux)\n\nlemma take_bin2bl_lem1: \"take m (bin_to_bl_aux m w bs) = bin_to_bl m w\"\n  apply (induct m arbitrary: w bs)\n   apply clarsimp\n  apply clarsimp\n  apply (simp add: bin_to_bl_aux_alt)\n  apply (simp add: bin_to_bl_def)\n  apply (simp add: bin_to_bl_aux_alt)\n  done\n\nlemma take_bin2bl_lem: \"take m (bin_to_bl_aux (m + n) w bs) = take m (bin_to_bl (m + n) w)\"\n  by (induct n arbitrary: w bs) (simp_all (no_asm) add: bin_to_bl_def take_bin2bl_lem1, simp)\n\nlemma bin_split_take: \"bin_split n c = (a, b) \\<Longrightarrow> bin_to_bl m a = take m (bin_to_bl (m + n) c)\"\n  apply (induct n arbitrary: b c)\n   apply clarsimp\n  apply (clarsimp simp: Let_def split: prod.split_asm)\n  apply (simp add: bin_to_bl_def)\n  apply (simp add: take_bin2bl_lem)\n  done\n\nlemma bin_split_take1:\n  \"k = m + n \\<Longrightarrow> bin_split n c = (a, b) \\<Longrightarrow> bin_to_bl m a = take m (bin_to_bl k c)\"\n  by (auto elim: bin_split_take)\n\nlemma takefill_bintrunc: \"takefill False n bl = rev (bin_to_bl n (bl_to_bin (rev bl)))\"\n  apply (rule nth_equalityI)\n   apply simp\n  apply (clarsimp simp: nth_takefill nth_rev nth_bin_to_bl bin_nth_of_bl)\n  done\n\nlemma bl_bin_bl_rtf: \"bin_to_bl n (bl_to_bin bl) = rev (takefill False n (rev bl))\"\n  by (simp add: takefill_bintrunc)\n\nlemma bl_bin_bl_rep_drop:\n  \"bin_to_bl n (bl_to_bin bl) =\n    replicate (n - length bl) False @ drop (length bl - n) bl\"\n  by (simp add: bl_bin_bl_rtf takefill_alt rev_take)\n\nlemma bl_to_bin_aux_cat:\n  \"\\<And>nv v. bl_to_bin_aux bs (bin_cat w nv v) =\n    bin_cat w (nv + length bs) (bl_to_bin_aux bs v)\"\n  by (induct bs) (simp, simp add: bin_cat_Suc_Bit [symmetric] del: bin_cat.simps)\n\nlemma bin_to_bl_aux_cat:\n  \"\\<And>w bs. bin_to_bl_aux (nv + nw) (bin_cat v nw w) bs =\n    bin_to_bl_aux nv v (bin_to_bl_aux nw w bs)\"\n  by (induct nw) auto\n\nlemma bl_to_bin_aux_alt: \"bl_to_bin_aux bs w = bin_cat w (length bs) (bl_to_bin bs)\"\n  using bl_to_bin_aux_cat [where nv = \"0\" and v = \"0\"]\n  by (simp add: bl_to_bin_def [symmetric])\n\nlemma bin_to_bl_cat:\n  \"bin_to_bl (nv + nw) (bin_cat v nw w) =\n    bin_to_bl_aux nv v (bin_to_bl nw w)\"\n  by (simp add: bin_to_bl_def bin_to_bl_aux_cat)\n\nlemmas bl_to_bin_aux_app_cat =\n  trans [OF bl_to_bin_aux_append bl_to_bin_aux_alt]\n\nlemmas bin_to_bl_aux_cat_app =\n  trans [OF bin_to_bl_aux_cat bin_to_bl_aux_alt]\n\nlemma bl_to_bin_app_cat:\n  \"bl_to_bin (bsa @ bs) = bin_cat (bl_to_bin bsa) (length bs) (bl_to_bin bs)\"\n  by (simp only: bl_to_bin_aux_app_cat bl_to_bin_def)\n\nlemma bin_to_bl_cat_app:\n  \"bin_to_bl (n + nw) (bin_cat w nw wa) = bin_to_bl n w @ bin_to_bl nw wa\"\n  by (simp only: bin_to_bl_def bin_to_bl_aux_cat_app)\n\ntext \\<open>\\<open>bl_to_bin_app_cat_alt\\<close> and \\<open>bl_to_bin_app_cat\\<close> are easily interderivable.\\<close>\nlemma bl_to_bin_app_cat_alt: \"bin_cat (bl_to_bin cs) n w = bl_to_bin (cs @ bin_to_bl n w)\"\n  by (simp add: bl_to_bin_app_cat)\n\nlemma mask_lem: \"(bl_to_bin (True # replicate n False)) = bl_to_bin (replicate n True) + 1\"\n  apply (unfold bl_to_bin_def)\n  apply (induct n)\n   apply simp\n  apply (simp only: Suc_eq_plus1 replicate_add append_Cons [symmetric] bl_to_bin_aux_append)\n  apply (simp add: Bit_B0_2t Bit_B1_2t)\n  done\n\nprimrec rbl_succ :: \"bool list \\<Rightarrow> bool list\"\n  where\n    Nil: \"rbl_succ Nil = Nil\"\n  | Cons: \"rbl_succ (x # xs) = (if x then False # rbl_succ xs else True # xs)\"\n\nprimrec rbl_pred :: \"bool list \\<Rightarrow> bool list\"\n  where\n    Nil: \"rbl_pred Nil = Nil\"\n  | Cons: \"rbl_pred (x # xs) = (if x then False # xs else True # rbl_pred xs)\"\n\nprimrec rbl_add :: \"bool list \\<Rightarrow> bool list \\<Rightarrow> bool list\"\n  where \\<comment> \\<open>result is length of first arg, second arg may be longer\\<close>\n    Nil: \"rbl_add Nil x = Nil\"\n  | Cons: \"rbl_add (y # ys) x =\n      (let ws = rbl_add ys (tl x)\n       in (y \\<noteq> hd x) # (if hd x \\<and> y then rbl_succ ws else ws))\"\n\nprimrec rbl_mult :: \"bool list \\<Rightarrow> bool list \\<Rightarrow> bool list\"\n  where \\<comment> \\<open>result is length of first arg, second arg may be longer\\<close>\n    Nil: \"rbl_mult Nil x = Nil\"\n  | Cons: \"rbl_mult (y # ys) x =\n      (let ws = False # rbl_mult ys x\n       in if y then rbl_add ws x else ws)\"\n\nlemma size_rbl_pred: \"length (rbl_pred bl) = length bl\"\n  by (induct bl) auto\n\nlemma size_rbl_succ: \"length (rbl_succ bl) = length bl\"\n  by (induct bl) auto\n\nlemma size_rbl_add: \"length (rbl_add bl cl) = length bl\"\n  by (induct bl arbitrary: cl) (auto simp: Let_def size_rbl_succ)\n\nlemma size_rbl_mult: \"length (rbl_mult bl cl) = length bl\"\n  by (induct bl arbitrary: cl) (auto simp add: Let_def size_rbl_add)\n\nlemmas rbl_sizes [simp] =\n  size_rbl_pred size_rbl_succ size_rbl_add size_rbl_mult\n\nlemmas rbl_Nils =\n  rbl_pred.Nil rbl_succ.Nil rbl_add.Nil rbl_mult.Nil\n\nlemma rbl_add_app2: \"length blb \\<ge> length bla \\<Longrightarrow> rbl_add bla (blb @ blc) = rbl_add bla blb\"\n  apply (induct bla arbitrary: blb)\n   apply simp\n  apply clarsimp\n  apply (case_tac blb, clarsimp)\n  apply (clarsimp simp: Let_def)\n  done\n\nlemma rbl_add_take2:\n  \"length blb \\<ge> length bla \\<Longrightarrow> rbl_add bla (take (length bla) blb) = rbl_add bla blb\"\n  apply (induct bla arbitrary: blb)\n   apply simp\n  apply clarsimp\n  apply (case_tac blb, clarsimp)\n  apply (clarsimp simp: Let_def)\n  done\n\nlemma rbl_mult_app2: \"length blb \\<ge> length bla \\<Longrightarrow> rbl_mult bla (blb @ blc) = rbl_mult bla blb\"\n  apply (induct bla arbitrary: blb)\n   apply simp\n  apply clarsimp\n  apply (case_tac blb, clarsimp)\n  apply (clarsimp simp: Let_def rbl_add_app2)\n  done\n\nlemma rbl_mult_take2:\n  \"length blb \\<ge> length bla \\<Longrightarrow> rbl_mult bla (take (length bla) blb) = rbl_mult bla blb\"\n  apply (rule trans)\n   apply (rule rbl_mult_app2 [symmetric])\n   apply simp\n  apply (rule_tac f = \"rbl_mult bla\" in arg_cong)\n  apply (rule append_take_drop_id)\n  done\n\nlemma rbl_add_split:\n  \"P (rbl_add (y # ys) (x # xs)) =\n    (\\<forall>ws. length ws = length ys \\<longrightarrow> ws = rbl_add ys xs \\<longrightarrow>\n      (y \\<longrightarrow> ((x \\<longrightarrow> P (False # rbl_succ ws)) \\<and> (\\<not> x \\<longrightarrow> P (True # ws)))) \\<and>\n      (\\<not> y \\<longrightarrow> P (x # ws)))\"\n  by (cases y) (auto simp: Let_def)\n\nlemma rbl_mult_split:\n  \"P (rbl_mult (y # ys) xs) =\n    (\\<forall>ws. length ws = Suc (length ys) \\<longrightarrow> ws = False # rbl_mult ys xs \\<longrightarrow>\n      (y \\<longrightarrow> P (rbl_add ws xs)) \\<and> (\\<not> y \\<longrightarrow> P ws))\"\n  by (auto simp: Let_def)\n\nlemma rbl_pred: \"rbl_pred (rev (bin_to_bl n bin)) = rev (bin_to_bl n (bin - 1))\"\n  apply (unfold bin_to_bl_def)\n  apply (induct n arbitrary: bin)\n   apply simp\n  apply clarsimp\n  apply (case_tac bin rule: bin_exhaust)\n  apply (case_tac b)\n   apply (clarsimp simp: bin_to_bl_aux_alt)+\n  done\n\nlemma rbl_succ: \"rbl_succ (rev (bin_to_bl n bin)) = rev (bin_to_bl n (bin + 1))\"\n  apply (unfold bin_to_bl_def)\n  apply (induct n arbitrary: bin)\n   apply simp\n  apply clarsimp\n  apply (case_tac bin rule: bin_exhaust)\n  apply (case_tac b)\n   apply (clarsimp simp: bin_to_bl_aux_alt)+\n  done\n\nlemma rbl_add:\n  \"\\<And>bina binb. rbl_add (rev (bin_to_bl n bina)) (rev (bin_to_bl n binb)) =\n    rev (bin_to_bl n (bina + binb))\"\n  apply (unfold bin_to_bl_def)\n  apply (induct n)\n   apply simp\n  apply clarsimp\n  apply (case_tac bina rule: bin_exhaust)\n  apply (case_tac binb rule: bin_exhaust)\n  apply (case_tac b)\n   apply (case_tac [!] \"ba\")\n     apply (auto simp: rbl_succ bin_to_bl_aux_alt Let_def ac_simps)\n  done\n\nlemma rbl_add_long:\n  \"m \\<ge> n \\<Longrightarrow> rbl_add (rev (bin_to_bl n bina)) (rev (bin_to_bl m binb)) =\n    rev (bin_to_bl n (bina + binb))\"\n  apply (rule box_equals [OF _ rbl_add_take2 rbl_add])\n   apply (rule_tac f = \"rbl_add (rev (bin_to_bl n bina))\" in arg_cong)\n   apply (rule rev_swap [THEN iffD1])\n   apply (simp add: rev_take drop_bin2bl)\n  apply simp\n  done\n\nlemma rbl_mult_gt1:\n  \"m \\<ge> length bl \\<Longrightarrow>\n    rbl_mult bl (rev (bin_to_bl m binb)) =\n    rbl_mult bl (rev (bin_to_bl (length bl) binb))\"\n  apply (rule trans)\n   apply (rule rbl_mult_take2 [symmetric])\n   apply simp_all\n  apply (rule_tac f = \"rbl_mult bl\" in arg_cong)\n  apply (rule rev_swap [THEN iffD1])\n  apply (simp add: rev_take drop_bin2bl)\n  done\n\nlemma rbl_mult_gt:\n  \"m > n \\<Longrightarrow>\n    rbl_mult (rev (bin_to_bl n bina)) (rev (bin_to_bl m binb)) =\n    rbl_mult (rev (bin_to_bl n bina)) (rev (bin_to_bl n binb))\"\n  by (auto intro: trans [OF rbl_mult_gt1])\n\nlemmas rbl_mult_Suc = lessI [THEN rbl_mult_gt]\n\nlemma rbbl_Cons: \"b # rev (bin_to_bl n x) = rev (bin_to_bl (Suc n) (x BIT b))\"\n  by (simp add: bin_to_bl_def) (simp add: bin_to_bl_aux_alt)\n\nlemma rbl_mult:\n  \"rbl_mult (rev (bin_to_bl n bina)) (rev (bin_to_bl n binb)) =\n    rev (bin_to_bl n (bina * binb))\"\n  apply (induct n arbitrary: bina binb)\n   apply simp\n  apply (unfold bin_to_bl_def)\n  apply clarsimp\n  apply (case_tac bina rule: bin_exhaust)\n  apply (case_tac binb rule: bin_exhaust)\n  apply (case_tac b)\n   apply (case_tac [!] \"ba\")\n     apply (auto simp: bin_to_bl_aux_alt Let_def)\n     apply (auto simp: rbbl_Cons rbl_mult_Suc rbl_add)\n  done\n\nlemma sclem: \"size (concat (map (bin_to_bl n) xs)) = length xs * n\"\n  by (induct xs) auto\n\nlemma bin_cat_foldl_lem:\n  \"foldl (\\<lambda>u. bin_cat u n) x xs =\n    bin_cat x (size xs * n) (foldl (\\<lambda>u. bin_cat u n) y xs)\"\n  apply (induct xs arbitrary: x)\n   apply simp\n  apply (simp (no_asm))\n  apply (frule asm_rl)\n  apply (drule meta_spec)\n  apply (erule trans)\n  apply (drule_tac x = \"bin_cat y n a\" in meta_spec)\n  apply (simp add: bin_cat_assoc_sym min.absorb2)\n  done\n\nlemma bin_rcat_bl: \"bin_rcat n wl = bl_to_bin (concat (map (bin_to_bl n) wl))\"\n  apply (unfold bin_rcat_def)\n  apply (rule sym)\n  apply (induct wl)\n   apply (auto simp add: bl_to_bin_append)\n  apply (simp add: bl_to_bin_aux_alt sclem)\n  apply (simp add: bin_cat_foldl_lem [symmetric])\n  done\n\nlemma bin_last_bl_to_bin: \"bin_last (bl_to_bin bs) \\<longleftrightarrow> bs \\<noteq> [] \\<and> last bs\"\nby(cases \"bs = []\")(auto simp add: bl_to_bin_def last_bin_last'[where w=0])\n\nlemma bin_rest_bl_to_bin: \"bin_rest (bl_to_bin bs) = bl_to_bin (butlast bs)\"\nby(cases \"bs = []\")(simp_all add: bl_to_bin_def butlast_rest_bl2bin_aux)\n\nlemma bl_xor_aux_bin:\n  \"map2 (\\<lambda>x y. x \\<noteq> y) (bin_to_bl_aux n v bs) (bin_to_bl_aux n w cs) =\n    bin_to_bl_aux n (v XOR w) (map2 (\\<lambda>x y. x \\<noteq> y) bs cs)\"\n  apply (induct n arbitrary: v w bs cs)\n   apply simp\n  apply (case_tac v rule: bin_exhaust)\n  apply (case_tac w rule: bin_exhaust)\n  apply clarsimp\n  apply (case_tac b)\n   apply auto\n  done\n\nlemma bl_or_aux_bin:\n  \"map2 (\\<or>) (bin_to_bl_aux n v bs) (bin_to_bl_aux n w cs) =\n    bin_to_bl_aux n (v OR w) (map2 (\\<or>) bs cs)\"\n  apply (induct n arbitrary: v w bs cs)\n   apply simp\n  apply (case_tac v rule: bin_exhaust)\n  apply (case_tac w rule: bin_exhaust)\n  apply clarsimp\n  done\n\nlemma bl_and_aux_bin:\n  \"map2 (\\<and>) (bin_to_bl_aux n v bs) (bin_to_bl_aux n w cs) =\n    bin_to_bl_aux n (v AND w) (map2 (\\<and>) bs cs)\"\n  apply (induct n arbitrary: v w bs cs)\n   apply simp\n  apply (case_tac v rule: bin_exhaust)\n  apply (case_tac w rule: bin_exhaust)\n  apply clarsimp\n  done\n\nlemma bl_not_aux_bin: \"map Not (bin_to_bl_aux n w cs) = bin_to_bl_aux n (NOT w) (map Not cs)\"\n  by (induct n arbitrary: w cs) auto\n\nlemma bl_not_bin: \"map Not (bin_to_bl n w) = bin_to_bl n (NOT w)\"\n  by (simp add: bin_to_bl_def bl_not_aux_bin)\n\nlemma bl_and_bin: \"map2 (\\<and>) (bin_to_bl n v) (bin_to_bl n w) = bin_to_bl n (v AND w)\"\n  by (simp add: bin_to_bl_def bl_and_aux_bin)\n\nlemma bl_or_bin: \"map2 (\\<or>) (bin_to_bl n v) (bin_to_bl n w) = bin_to_bl n (v OR w)\"\n  by (simp add: bin_to_bl_def bl_or_aux_bin)\n\nlemma bl_xor_bin: \"map2 (\\<noteq>) (bin_to_bl n v) (bin_to_bl n w) = bin_to_bl n (v XOR w)\"\n  using bl_xor_aux_bin by (simp add: bin_to_bl_def)\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Word/Bits_Int.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7574185381310287}}
{"text": "theory Ex2_5\n  imports Main \nbegin \n  \ndatatype form = T | Var nat | And form form | Xor form form\n  \ndefinition xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"xor x y= ((x \\<and> \\<not>y) \\<or> (\\<not>x \\<and> y))\"\n  \nnotation \n  xor (infixr \"<**>\" 50)\n  \ndeclare xor_def [simp]  \n  \nprimrec evalf :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\" where \n  \"evalf _ T = True\"|\n  \"evalf p (Var n) = p n\"|\n  \"evalf p (And f1 f2) = (evalf p f1 \\<and> evalf p f2)\"|\n  \"evalf p (Xor f1 f2) = (evalf p f1 <**>  evalf p f2)\"\n  \nprimrec evalm :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat list \\<Rightarrow> bool\" where \n  \"evalm P [] = True\"|\n  \"evalm P (x#xs) = (P x \\<and> evalm P xs)\"\n  \n  \nprimrec evalp :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat list list \\<Rightarrow> bool\" where\n  \"evalp P [] = False\"|\n  \"evalp P (x#xs) = (evalm P x <**> evalp P xs)\"\n  \nlemma \"((a <**> b)  \\<and> (c <**> d)) = ((a \\<and> c) <**> (a \\<and> d) <**> (b \\<and> c) <**> (b \\<and> d))\" by auto\n  \nprimrec mulpp :: \"nat list list \\<Rightarrow> nat list list \\<Rightarrow> nat list list \" where \n  \"mulpp [] _ = [] \"|\n  \"mulpp (x#xs) ys = (map (op @ x) ys) @ mulpp xs ys\"\n  \nprimrec poly :: \"form \\<Rightarrow> nat list list\" where\n  \"poly T = [[]]\"|\n  \"poly (Var i)= [[i]]\"|\n  \"poly (And f1 f2) = mulpp (poly f1) (poly f2)\"|\n  \"poly (Xor f1 f2) = poly f1 @ poly f2\"\n\nlemma helper1 : \"evalp e (xs @ ys) = (evalp e xs <**> evalp e ys)\"  by (induction xs ; auto)\n    \nlemma helper2 : \"evalp e (map (op @ a) f2) = (evalp e [a] \\<and> evalp e f2)\" \nproof (induction f2)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons aa f2)\n  assume hyp:\"evalp e (map (op @ a) f2) = (evalp e [a] \\<and> evalp e f2)\"\n  have \"evalp e (map (op @ a) (aa # f2)) = evalp e ((a @ aa) # map (op @ a) f2)\" by simp\n  also have \"\\<dots> = (evalm e (a @ aa) <**> evalp e (map (op @ a) f2))\" by simp\n  also have \"\\<dots> =  (evalm e (a @ aa) <**> (evalp e [a] \\<and> evalp e f2))\" using hyp by simp\n  finally have tmp:\"evalp e (map (op @ a) (aa # f2)) = (evalm e (a @ aa) <**> (evalp e [a] \\<and> evalp e f2))\" by assumption\n      \n  have tmp2:\"evalm e (a @ aa) = (evalm e a \\<and> evalm e aa)\" by (induction a ; simp)\n      \n  have \"(evalp e [a] \\<and> evalp e (aa # f2)) = (evalm e a \\<and> evalp e (aa # f2))\" by simp\n  also have \"\\<dots> = (evalm e a \\<and> (evalm e aa <**> evalp e  f2))\" by simp\n  also have \"\\<dots> = ((evalm e a \\<and> evalm e aa) <**> (evalm e a  \\<and> evalp e  f2))\" by auto\n  also have \"\\<dots> = ((evalm e (a@aa)) <**> (evalm e a  \\<and> evalp e  f2))\" using tmp2 by simp\n  also have \"\\<dots> = ((evalm e (a@aa)) <**> (evalp e [a]  \\<and> evalp e  f2))\" by simp\n  finally  show ?case using tmp by simp\nqed\n  \nlemma helper3: \"evalp e (mulpp f1 f2) = (evalp e f1 \\<and> evalp e f2)\"  \nproof (induction f1)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a f1)\n  assume hyp:\"evalp e (mulpp f1 f2) = (evalp e f1 \\<and> evalp e f2)\"\n    \n  have \"evalp e (mulpp (a # f1) f2) = evalp e (map (op @ a) f2 @ mulpp f1 f2)\" by simp\n  also have \"\\<dots> = (evalp e (map (op @ a) f2) <**> evalp e (mulpp f1 f2))\" using helper1 by simp\n  also have \"\\<dots> = (evalp e (map (op @ a) f2) <**> ((evalp e f1 \\<and> evalp e f2)))\" using hyp by simp\n  finally have tmp1:\"evalp e (mulpp (a # f1) f2) = (evalp e (map (op @ a) f2) <**> (evalp e f1 \\<and> evalp e f2))\" by assumption\n      \n  have \"(evalp e (a # f1) \\<and> evalp e f2) = ((evalm e a <**> evalp e f1) \\<and> evalp e f2)\" by simp\n  also have \"\\<dots> = ((evalm e a \\<and> evalp e f2 ) <**> (evalp e f1 \\<and> evalp e f2))\" by auto\n  also have \"\\<dots> = (evalp e (map (op @ a) f2) <**> (evalp e f1 \\<and> evalp e f2))\" using helper2 by simp\n  finally show \"evalp e (mulpp (a # f1) f2) = (evalp e (a # f1) \\<and> evalp e f2)\" using tmp1 by simp\nqed\n  \n  \ntheorem poly_correct : \"evalf e f = evalp e (poly f)\" \nproof (induction f)\n  case T\n  then show ?case by simp\nnext\n  case (Var x)\n  then show ?case by simp\nnext\n  case (And f1 f2)\n  then show ?case using helper3 by simp\nnext\n  case (Xor f1 f2)\n  then show ?case by (simp add: helper1)\nqed\n  ", "meta": {"author": "SvenWille", "repo": "ExerciseSolutions_New", "sha": "b8243e7a669846c64e2f5520dae88ff41265d233", "save_path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New", "path": "github-repos/isabelle/SvenWille-ExerciseSolutions_New/ExerciseSolutions_New-b8243e7a669846c64e2f5520dae88ff41265d233/Isabelle/2. Trees and other inductive data types/Ex2_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.839733963661418, "lm_q1q2_score": 0.7573734179689494}}
{"text": "theory ex3_2\nimports Main begin\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N (i\\<^sub>1+i\\<^sub>2)\"|\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\"|\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\"|\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\nfun sum_n :: \"aexp \\<Rightarrow> int\" where\n\"sum_n (N a) = a\" |\n\"sum_n (Plus a b) = (sum_n a) + (sum_n b)\" |\n\"sum_n (V x) = 0\"\n\nfun sum_v :: \"aexp \\<Rightarrow> aexp\" where \n\"sum_v  (N a) = N 0\" |\n\"sum_v  (Plus a b) = Plus (sum_v a) (sum_v b)\" |\n\"sum_v  (V x) = V x\"\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = asimp (Plus (sum_v a) (N (sum_n a)))\"\n\nlemma aval_plus [simp]:\"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply(auto)\ndone\n\nlemma \"aval (full_asimp a) s = aval a s\"\napply(induction a)\napply(auto)\ndone\n\nvalue \"full_asimp (Plus (Plus (N 0) (N 7)) (Plus (V x) (N 8)))\"\n\nend\n", "meta": {"author": "oguri257", "repo": "isabelle", "sha": "master", "save_path": "github-repos/isabelle/oguri257-isabelle", "path": "github-repos/isabelle/oguri257-isabelle/isabelle-main/ex3_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802395624257, "lm_q2_score": 0.8244619263765707, "lm_q1q2_score": 0.7572519876484517}}
{"text": "(*  Author:      Christian Sternagel\n    Maintainer:  Christian Sternagel\n*)\n\ntheory Efficient_Sort\nimports \"~~/src/HOL/Library/Multiset\"\nbegin\n\ntext {*\nA high-level overview of this formalization as well as some experimental data is\nto be found in \\cite{Sternagel2012}.\n*}\n\nsection {* Chaining Lists by Predicates *}\n\ntext {*\nMake sure that some binary predicate @{text P} is satisfied between\nevery two consecutive elements of a list. We call such a list a\n\\emph{chain} in the following.\n*}\ninductive\n  linked :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  for P::\"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nwhere\n  Nil[iff]: \"linked P []\"\n| singleton[iff]: \"linked P [x]\"\n| many: \"P x y \\<Longrightarrow> linked P (y#ys) \\<Longrightarrow> linked P (x#y#ys)\"\n\ndeclare eqTrueI[OF Nil, code] eqTrueI[OF singleton, code]\n\nlemma linked_many_eq[simp, code]:\n  \"linked P (x#y#zs) \\<longleftrightarrow> P x y \\<and> linked P (y#zs)\"\n  by (blast intro: linked.many elim: linked.cases)\n\ntext {* Take the longest prefix of a list that forms a chain. *}\nfun take_chain :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"take_chain a P [] = []\"\n| \"take_chain a P (x#xs) = (if P a x\n    then x # take_chain x P xs\n    else [])\"\n\ntext {* Drop the longest prefix of a list that forms a chain. *}\nfun drop_chain :: \"'a \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"drop_chain a P [] = []\"\n| \"drop_chain a P (x#xs) = (if P a x\n    then drop_chain x P xs\n    else x#xs)\"\n\nlemma take_chain_drop_chain_id[simp]:\n  \"take_chain a P xs @ drop_chain a P xs = xs\"\n  by (induct xs arbitrary: a) simp_all\n\nlemma linked_take_chain:\n  \"linked P (x # take_chain x P xs)\"\n  by (induct xs arbitrary: x) simp_all\n\nlemma linked_rev_take_chain_append:\n  \"linked P (x#ys) \\<Longrightarrow> linked P (rev (take_chain x (\\<lambda>x y. P y x) xs) @ x#ys)\"\n  by (induct xs arbitrary: x ys) simp_all\n\nlemma linked_rev_take_chain:\n  \"linked P (rev (take_chain x (\\<lambda>x y. P y x) xs) @ [x])\"\n  using linked_rev_take_chain_append[of P x \"[]\" xs] by simp\n\nlemma linked_append:\n  \"linked P (xs@ys) \\<longleftrightarrow> linked P xs \\<and> linked P ys\n    \\<and> (if xs \\<noteq> [] \\<and> ys \\<noteq> [] then P (last xs) (hd ys) else True)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume \"?lhs\" thus \"?rhs\"\n  proof (induct xs)\n    case (Cons x xs) thus ?case by (cases xs, simp_all) (cases ys, auto)\n  qed simp\nnext\n  assume \"?rhs\" thus \"?lhs\"\n  proof (induct xs)\n    case (Cons x xs) thus ?case by (cases ys, auto) (cases xs, auto)\n  qed simp\nqed\n\nlemma length_drop_chain[termination_simp]:\n  \"length (drop_chain b P xs) \\<le> length xs\" (is \"?P b xs\")\nproof (induct xs arbitrary: b rule: length_induct)\n  fix xs::\"'a list\" and b\n  assume IH: \"\\<forall>ys. length ys < length xs \\<longrightarrow> (\\<forall>x. ?P x ys)\"\n  show \"?P b xs\"\n  proof (cases xs)\n    case (Cons y ys) with IH[rule_format, of ys y] show ?thesis by simp\n  qed simp\nqed\n\nlemma take_chain_map[simp]:\n  \"take_chain (f x) P (map f xs) = map f (take_chain x (\\<lambda>x y. P (f x) (f y)) xs)\"\n  by (induct xs arbitrary: x) simp_all\n\n\nsubsection {* Sorted is a Special Case of Linked *}\n\nlemma (in linorder) linked_le_sorted_conv[simp]:\n  \"linked (op \\<le>) xs = sorted xs\"\nproof\n  assume \"sorted xs\" thus \"linked (op \\<le>) xs\"\n  proof (induct xs rule: sorted.induct)\n    case (Cons xs x) thus ?case by (cases xs) simp_all\n  qed simp\nqed (induct xs rule: linked.induct, simp_all)\n\nlemma (in linorder) linked_less_imp_sorted:\n  \"linked (op <) xs \\<Longrightarrow> sorted xs\"\n  by (induct xs rule: linked.induct) simp_all\n\nabbreviation (in linorder) (input) lt :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> 'b \\<Rightarrow> bool\" where\n  \"lt key x y \\<equiv> key x < key y\"\n\nabbreviation (in linorder) (input) le :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> 'b \\<Rightarrow> bool\" where\n  \"le key x y \\<equiv> key x \\<le> key y\"\n\nabbreviation (in linorder) (input) gt :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> 'b \\<Rightarrow> bool\" where\n  \"gt key x y \\<equiv> key x > key y\"\n\nabbreviation (in linorder) (input) ge :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> 'b \\<Rightarrow> bool\" where\n  \"ge key x y \\<equiv> key x \\<ge> key y\"\n\nlemma (in linorder) sorted_take_chain_le[simp]:\n  \"sorted (key x # map key (take_chain x (le key) xs))\"\n  using linked_take_chain[of \"op \\<le>\", of \"key x\" \"map key xs\"] by simp\n\nlemma (in linorder) sorted_rev_take_chain_gt_append:\n  assumes \"linked (op <) (key x # map key ys)\"\n  shows \"sorted (map key (rev (take_chain x (gt key) xs)) @ key x # map key ys)\"\n  using linked_less_imp_sorted[OF linked_rev_take_chain_append[OF assms, of \"map key xs\"]]\n    by (simp add: rev_map)\n\nlemma multiset_of_take_chain_drop_chain[simp]:\n  \"multiset_of (take_chain x P xs) + multiset_of (drop_chain x P xs) = multiset_of xs\"\n  by (induct xs arbitrary: x) (simp_all add: ac_simps)\n\nlemma multiset_of_drop_chain_take_chain[simp]:\n  \"multiset_of (drop_chain x P xs) + multiset_of (take_chain x P xs) = multiset_of xs\"\n  by (induct xs arbitrary: x) (simp_all add: ac_simps)\n\n\nsection {* GHC Version of Mergesort *}\n\ntext {*\nIn the following we show that the mergesort implementation\nused in GHC (see @{url \"http://haskell.org/ghc/docs/7.0-latest/html/libraries/base-4.3.1.0/src/Data-List.html#sort\"})\nis a correct and stable sorting algorithm. Furthermore, experimental\ndata suggests that generated code for this implementation is much more\nefficient than for the implementation provided by @{theory Multiset}.\n*}\ncontext linorder\nbegin\n\ntext {*\nSplit a list into chunks of ascending and descending parts, where\ndescending parts are reversed. Hence, the result is a list of\nsorted lists.\n*}\nfun sequences :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b list \\<Rightarrow> 'b list list\"\n  and asc :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> ('b list \\<Rightarrow> 'b list) \\<Rightarrow> 'b list \\<Rightarrow> 'b list list\"\n  and desc :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b \\<Rightarrow> 'b list \\<Rightarrow> 'b list \\<Rightarrow> 'b list list\"\nwhere\n  \"sequences key (a#b#xs) =\n    (if key a > key b then desc key b [a] xs else asc key b (op # a) xs)\"\n| \"sequences key xs = [xs]\"\n| \"asc key a f (b#bs) = (if \\<not> key a > key b\n    then asc key b (f \\<circ> op # a) bs\n    else f [a] # sequences key (b#bs))\"\n| \"asc key a f bs = f [a] # sequences key bs\"\n| \"desc key a as (b#bs) = (if key a > key b\n    then desc key b (a#as) bs\n    else (a#as) # sequences key (b#bs))\"\n| \"desc key a as bs = (a#as) # sequences key bs\"\n\nfun merge :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b list \\<Rightarrow> 'b list \\<Rightarrow> 'b list\" where\n  \"merge key (a#as) (b#bs) = (if key a > key b\n    then b # merge key (a#as) bs\n    else a # merge key as (b#bs))\"\n| \"merge key [] bs = bs\"\n| \"merge key as [] = as\"\n\nfun merge_pairs :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b list list \\<Rightarrow> 'b list list\" where\n  \"merge_pairs key (a#b#xs) = merge key a b # merge_pairs key xs\"\n| \"merge_pairs key xs = xs\"\n\nlemma merge_Nil2[simp]: \"merge key as [] = as\" by (cases as) simp_all\n\nlemma length_merge[simp]:\n  \"length (merge key xs ys) = length xs + length ys\"\n  by (induct xs ys rule: merge.induct) simp_all\n\nlemma merge_pairs_length[termination_simp]:\n  \"length (merge_pairs key xs) \\<le> length xs\"\n  by (induct xs rule: merge_pairs.induct) simp_all\n\nfun merge_all :: \"('b \\<Rightarrow> 'a) \\<Rightarrow> 'b list list \\<Rightarrow> 'b list\" where\n  \"merge_all key [] = []\"\n| \"merge_all key [x] = x\"\n| \"merge_all key xs = merge_all key (merge_pairs key xs)\"\n\nlemma multiset_of_merge[simp]:\n  \"multiset_of (merge key xs ys) = multiset_of xs + multiset_of ys\"\n  by (induct xs ys rule: merge.induct) (simp_all add: ac_simps)\n\nlemma set_merge[simp]:\n  \"set (merge key xs ys) = set xs \\<union> set ys\"\n  unfolding set_of_multiset_of[symmetric] by simp\n\nlemma multiset_of_concat_merge_pairs[simp]:\n  \"multiset_of (concat (merge_pairs key xs)) = multiset_of (concat xs)\"\n  by (induct xs rule: merge_pairs.induct) (auto simp: ac_simps)\n\nlemma set_concat_merge_pairs[simp]:\n  \"set (concat (merge_pairs key xs)) = set (concat xs)\"\n  unfolding set_of_multiset_of[symmetric] by simp\n\nlemma multiset_of_merge_all[simp]:\n  \"multiset_of (merge_all key xs) = multiset_of (concat xs)\"\n  by (induct xs rule: merge_all.induct) (simp_all add: ac_simps)\n\nlemma set_merge_all[simp]:\n  \"set (merge_all key xs) = set (concat xs)\"\n  unfolding set_of_multiset_of[symmetric] by simp\n\nlemma sorted_merge[simp]:\n  assumes \"sorted (map key xs)\" and \"sorted (map key ys)\"\n  shows \"sorted (map key (merge key xs ys))\"\n  using assms by (induct xs ys rule: merge.induct) (auto simp: sorted_Cons)\n\nlemma sorted_merge_pairs[simp]:\n  assumes \"\\<forall>x\\<in>set xs. sorted (map key x)\"\n  shows \"\\<forall>x\\<in>set (merge_pairs key xs). sorted (map key x)\"\n  using assms by (induct xs rule: merge_pairs.induct) simp_all\n\nlemma sorted_merge_all:\n  assumes \"\\<forall>x\\<in>set xs. sorted (map key x)\"\n  shows \"sorted (map key (merge_all key xs))\"\n  using assms by (induct xs rule: merge_all.induct) simp_all\n\nlemma desc_take_chain_drop_chain_conv[simp]:\n  \"desc key a bs xs\n    = (rev (take_chain a (gt key) xs) @ a # bs) # sequences key (drop_chain a (gt key) xs)\"\nproof (induct xs arbitrary: a bs)\n  case (Cons x xs) thus ?case by (cases \"key a < key x\") simp_all\nqed simp\n\nlemma asc_take_chain_drop_chain_conv_append:\n  assumes \"\\<And>xs ys. f (xs@ys) = f xs @ ys\"\n  shows \"asc key a (f \\<circ> op @ as) xs\n    = (f as @ a # take_chain a (le key) xs) # sequences key (drop_chain a (le key) xs)\"\nusing assms\nproof (induct xs arbitrary: as a)\n  case (Cons x xs)\n  show ?case\n  proof (cases \"le key a x\")\n    case False with Cons show ?thesis by auto\n  next\n    case True\n    with Cons(1)[of \"x\" \"as@[a]\"] and Cons(2)\n      show ?thesis by (simp add: o_def)\n  qed\nqed simp\n\nlemma asc_take_chain_drop_chain_conv[simp]:\n  \"asc key b (op # a) xs\n    = (a # b # take_chain b (le key) xs) # sequences key (drop_chain b (le key) xs)\"\nproof -\n  let ?f = \"op # a\"\n  have \"\\<And>xs ys. (op # a) (xs@ys) = (op # a) xs @ ys\" by simp\n  from asc_take_chain_drop_chain_conv_append[of ?f key b \"[]\" xs, OF this]\n    show ?thesis by (simp add: o_def)\nqed\n\nlemma sequences_induct[case_names Nil singleton many]:\n  assumes \"\\<And>key. P key []\" and \"\\<And>key x. P key [x]\"\n    and \"\\<And>key a b xs.\n    (le key a b \\<Longrightarrow> P key (drop_chain b (le key) xs))\n    \\<Longrightarrow> (\\<not> le key a b \\<Longrightarrow> P key (drop_chain b (gt key) xs))\n    \\<Longrightarrow> P key (a#b#xs)\"\n  shows \"P key xs\"\n  using assms by (induction_schema) (pat_completeness, lexicographic_order)\n\nlemma sorted_sequences:\n  \"\\<forall>x\\<in>set (sequences key xs). sorted (map key x)\"\nproof (induct key xs rule: sequences_induct)\n  case (many key a b xs)\n  thus ?case using sorted_rev_take_chain_gt_append[of key b \"[a]\" xs]\n    by (cases \"le key a b\") auto\nqed simp_all\n\nlemma multiset_of_sequences[simp]:\n  \"multiset_of (concat (sequences key xs)) = multiset_of xs\"\n  by (induct key xs rule: sequences_induct) (simp_all add: ac_simps)\n\nlemma filter_by_key_drop_chain_gt[simp]:\n  assumes \"key b \\<le> key a\"\n  shows \"[y\\<leftarrow>drop_chain b (gt key) xs. key a = key y] = [y\\<leftarrow>xs. key a = key y]\"\n  using assms by (induct xs arbitrary: b) auto\n\nlemma filter_by_key_take_chain_gt[simp]:\n  assumes \"key b \\<le> key a\"\n  shows \"[y\\<leftarrow>take_chain b (gt key) xs. key a = key y] = []\"\n  using assms by (induct xs arbitrary: b) auto\n\nlemma filter_take_chain_drop_chain[simp]:\n  \"filter P (take_chain x Q xs) @ filter P (drop_chain x Q xs) = filter P xs\"\n  by (simp add: filter_append[symmetric])\n\nlemma filter_by_key_rev_take_chain_gt_conv[simp]:\n  \"[y\\<leftarrow>rev (take_chain b (gt key) xs). key x = key y]\n    = [y\\<leftarrow>take_chain b (gt key) xs. key x = key y]\"\n  by (induct xs arbitrary: b) auto\n\nlemma filter_by_key_sequences[simp]:\n  \"[y\\<leftarrow>concat (sequences key xs). key x = key y]\n    = [y\\<leftarrow>xs. key x = key y]\" (is ?P)\n  by (induct key xs rule: sequences_induct) auto\n\nlemma merge_simp[simp]:\n  assumes \"sorted (map key xs)\"\n  shows \"merge key xs (y#ys)\n    = takeWhile (ge key y) xs @ y # merge key (dropWhile (ge key y) xs) ys\"\n  using assms by (induct xs arbitrary: y ys) (auto simp: sorted_Cons)\n\nlemma sorted_map_dropWhile[simp]:\n  assumes \"sorted (map key xs)\"\n  shows \"sorted (map key (dropWhile (ge key y) xs))\"\n  using sorted_dropWhile[OF assms] by (simp add: dropWhile_map o_def)\n\nlemma sorted_merge_induct[consumes 1, case_names Nil IH]:\n  assumes \"sorted (map key xs)\"\n    and \"\\<And>xs. P xs []\"\n    and \"\\<And>xs y ys. sorted (map key xs) \\<Longrightarrow> P (dropWhile (ge key y) xs) ys\n      \\<Longrightarrow> P xs (y#ys)\"\n  shows \"P xs ys\"\n  using assms(2-) assms(1)\n  by (induction_schema) (case_tac ys, simp_all, lexicographic_order)\n \nlemma filter_by_key_dropWhile[simp]:\n  assumes \"sorted (map key xs)\"\n  shows \"[y\\<leftarrow>dropWhile (\\<lambda>x. key x \\<le> key z) xs. key z = key y] = []\"\n    (is \"[y\\<leftarrow>dropWhile ?P xs. key z = key y] = []\")\nusing assms\nproof (induct xs rule: rev_induct)\n  case Nil thus ?case by simp\nnext\n  case (snoc x xs)\n  hence IH: \"[y\\<leftarrow>dropWhile ?P xs. key z = key y] = []\"\n    by (auto simp: sorted_append)\n  show ?case\n  proof (cases \"\\<forall>z\\<in>set xs. ?P z\")\n    case True\n    show ?thesis\n      using dropWhile_append2[of xs ?P \"[x]\"] and True by simp\n  next\n    case False\n    then obtain a where a: \"a \\<in> set xs\" \"\\<not> ?P a\" by auto\n    show ?thesis\n      unfolding dropWhile_append1[of a xs ?P, OF a]\n      using snoc and False by (auto simp: IH sorted_append)\n  qed\nqed\n\nlemma filter_by_key_takeWhile[simp]:\n  assumes \"sorted (map key xs)\"\n  shows \"[y\\<leftarrow>takeWhile (\\<lambda>x. key x \\<le> key z) xs. key z = key y]\n    = [y\\<leftarrow>xs. key z = key y]\"\n    (is \"[y\\<leftarrow>takeWhile ?P xs. key z = key y] = _\")\nusing assms\nproof (induct xs rule: rev_induct)\n  case Nil thus ?case by simp\nnext\n  case (snoc x xs)\n  hence IH: \"[y\\<leftarrow>takeWhile ?P xs. key z = key y] = [y\\<leftarrow>xs. key z = key y]\"\n    by (auto simp: sorted_append)\n  show ?case\n  proof (cases \"\\<forall>z\\<in>set xs. ?P z\")\n    case True\n    show ?thesis\n      using takeWhile_append2[of xs ?P \"[x]\"] and True by simp\n  next\n    case False\n    then obtain a where a: \"a \\<in> set xs\" \"\\<not> ?P a\" by auto\n    show ?thesis\n      unfolding takeWhile_append1[of a xs ?P, OF a]\n      using snoc and False by (auto simp: IH sorted_append)\n  qed\nqed\n \nlemma filter_takeWhile_dropWhile_id[simp]:\n  \"filter P (takeWhile Q xs) @ filter P (dropWhile Q xs) = filter P xs\"\n  by (simp add: filter_append[symmetric])\n\nlemma filter_by_key_merge_is_append[simp]:\n  assumes \"sorted (map key xs)\"\n  shows \"[y\\<leftarrow>merge key xs ys. key x = key y]\n    = [y\\<leftarrow>xs. key x = key y] @ [y\\<leftarrow>ys. key x = key y]\"\n  using assms by (induct xs ys rule: sorted_merge_induct) auto\n\nlemma filter_by_key_merge_pairs[simp]:\n  assumes \"\\<forall>xs\\<in>set xss. sorted (map key xs)\"\n  shows \"[y\\<leftarrow>concat (merge_pairs key xss). key x = key y]\n    = [y\\<leftarrow>concat xss. key x = key y]\"\n  using assms by (induct xss rule: merge_pairs.induct) simp_all\n\nlemma filter_by_key_merge_all[simp]:\n  assumes \"\\<forall>xs\\<in>set xss. sorted (map key xs)\"\n  shows \"[y\\<leftarrow>merge_all key xss. key x = key y]\n    = [y\\<leftarrow>concat xss. key x = key y]\"\n  using assms by (induct xss rule: merge_all.induct) simp_all\n\nlemma filter_by_key_merge_all_sequences[simp]:\n  \"[x\\<leftarrow>merge_all key (sequences key xs) . key y = key x]\n    = [x\\<leftarrow>xs . key y = key x]\"\n  using sorted_sequences[of key xs] by simp\n\nlemma sort_key_merge_all_sequences:\n  \"sort_key key = merge_all key \\<circ> sequences key\"\n  by (intro ext properties_for_sort_key)\n     (simp_all add: sorted_merge_all[OF sorted_sequences])\n\ntext {*\nReplace existing code equations for @{const sort_key} by\n@{term \"merge_all key \\<circ> sequences key\"}.\n*}\ndeclare sort_key_merge_all_sequences[code]\n\nend\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Efficient-Mergesort/Efficient_Sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.757189333419202}}
{"text": "(*\nIsabelle/HOL source for lectures of Set Theory\ncreated by Yongwang ZHAO\nSchool of Computer Science and Engineering, Beihang University, China\nzhaoyw@buaa.edu.cn\n*)\n\ntheory SetFoundation\nimports Main \n\nbegin\n\n(*\ntypedecl Student\n\nconsts InRoom :: \"Student \\<Rightarrow> bool\"\n\ndefinition students_in_room :: \"Student set\"\n  where \"students_in_room \\<equiv> {x. InRoom(x)}\"\n\n\ntypedef nat1 = \"{x::nat. x > 0}\"\n  proof -\n    have \"(2::nat) \\<in> {x::nat. x>0}\" by force\n    then show ?thesis by blast\n  qed\n*)\n\nchapter {* chapter 5. Set and Operation *}\n\nsection {* section 5.1: sets and elements *}\n\nsubsection {* example 5.1 *}\n\n\ndefinition \"A0 \\<equiv> {''a'',''e'',''i'',''w'',''u''}\"\n\nlemma \"''a'' \\<in> A0\" \n  by (simp add: A0_def)\n\nlemma \"''e'' \\<in> A0\" \n  by (simp add: A0_def)\n\nlemma \"''i'' \\<in> A0\" \n  by (simp add: A0_def)\n\nlemma \"''b'' \\<notin> A0\" \n  by (simp add: A0_def)\n\nlemma \"''c'' \\<notin> A0\"\n  by (simp add: A0_def)\n\nsubsection {*example 5.2*}\n\ndefinition \"B0 \\<equiv> {x::int. x > 0}\"\n\nsubsection {* predicates and sets *}\n\nlemma \"a\\<in>{x. P(x)} \\<longleftrightarrow> P a\" by auto\n\nlemma \"b\\<notin>{x. P(x)} \\<longleftrightarrow> \\<not> (P b)\" by auto\n\nsubsection {*example 5.3*}\n\ndefinition \"S\\<^sub>1 \\<equiv> {x::int. x > 0 \\<and> x mod 2 = 1}\"\n\ndefinition \"S\\<^sub>3 \\<equiv> {x::int. x^3 + x^2 + 2 = 0}\"\n\n\ndefinition \"S\\<^sub>5 \\<equiv> {x::int. x =  8 \\<or> x = -2 \\<or> x = 75}\"\n\nlemma \"S\\<^sub>5 = {8, -2 ,75}\" \n  proof(rule subset_antisym)\n    show \"S\\<^sub>5 \\<subseteq> {8, -2, 75}\" using S\\<^sub>5_def by auto \n    show \"{8, -2, 75} \\<subseteq> S\\<^sub>5\" using S\\<^sub>5_def by auto \n  qed\n\nsubsection {* definition 5.1 *}\n\nconsts P :: \"'t \\<Rightarrow> bool\"\n\ndefinition \"A1 \\<equiv> {x. P(x)}\"\n\nlemma \"\\<forall>x. (P(x) \\<longleftrightarrow> x\\<in>A1)\" \n  by (simp add: A1_def) \n\ndefinition A2 :: \"('t \\<Rightarrow> bool) \\<Rightarrow> 't set\" \n  where aa2: \"A2(Q) = {x. Q(x)}\"\n\nlemma \"\\<forall>x. (Q(x) \\<longleftrightarrow> x\\<in>A2(Q))\" \n  by (simp add: aa2) \n\nsection {* section 5.2: equivalence and containment *}\n\nsubsection {* example 5.4 *}\n\nlemma \"{1,2,3,4} = {(x::int). x > 0 \\<and> x \\<le> 4}\" \n  by auto\n\nlemma \"{1,2,3,4} = {(x::int). 0 < x \\<and> x < 6 \\<and> (\\<exists>y. x * y = 12)}\" \napply auto apply(subgoal_tac \"x = 1 \\<or> x = 2 \\<or> x = 3 \\<or> x = 4 \\<or> x = 5\") \n  prefer 2 apply simp apply auto\n  by presburger \n\nsubsection {* definition 5.2 *}\n\n (*definition of set equal*)\nlemma \"(A = B) = (\\<forall>x. (x \\<in> A) \\<longleftrightarrow> (x \\<in> B))\" \n  using Set.set_eq_iff by fastforce\n\nsubsection {* example 5.5 *}\n\nlemma \"{1,2,3} = {3,1,2}\" \n  by auto\n\nlemma \"{''a'',''b'',''a''} = {''a'',''a'',''b'',''b'',''a''}\" \n  by auto\n\nlemma \"{''a'',''b'',''a''} = {''a'',''b''}\" \n  by auto\n\nsubsection {* example 5.6 *}\n\nconsts d :: \"int set\"\nconsts p :: \"int set\"\nconsts q :: \"int\"\n\ndefinition \"B1 \\<equiv> {d, {1,2},p,{q}}\"\n\nlemma \"{q} \\<in> B1\" \n  by (simp add: B1_def)\n\n(*lemma \"q \\<notin> B1\" *)\n\nsubsection {* definition 5.3 *}\n\n(*definition of \\<subseteq>*)\nlemma \"(A \\<subseteq> B) = (\\<forall>t. t \\<in> A \\<longrightarrow> t \\<in> B)\"\n  using subset_iff by auto\n\nsubsection {* definition 5.4 *}\n\n(*definition of \\<subseteq>*)\nlemma \"(A \\<subseteq> B) = (\\<forall>x\\<in>A. x \\<in> B)\"\n  using subset_eq by auto\n\n(*definition of \\<subset>*)\nlemma \"A \\<subset> B = ((\\<forall>x. x\\<in>A \\<longrightarrow> x\\<in>B) \\<and> (\\<exists>x. x\\<in>B \\<and> x\\<notin>A))\" \n  by auto\n\nsubsection {* example 5.8 *}\n\ndefinition \"A3 \\<equiv> {1,3,4,5,7}\"\n\ndefinition \"B2 \\<equiv> {1,3,4}\"\n\ndefinition \"C1 \\<equiv> {4}\"\n\nlemma \"C1 \\<subseteq> B2\" \n  by (simp add:B2_def C1_def)\n\nlemma \"B2 \\<subseteq> A3\"\n  by (simp add:B2_def A3_def)\n\nsubsection {* theorem 5.1 *}\n\nlemma \"(A = B) = (A \\<subseteq> B \\<and> B \\<subseteq> A)\"\n  using set_eq_iff by auto\n\nlemma \"A \\<subseteq> A\" by simp\n\nsubsection {* theorem 5.2 *}\nlemma \"A \\<subseteq> B \\<and> B \\<subseteq> C \\<Longrightarrow> A \\<subseteq> C\"\n  by auto\n\nsubsection {* definition 5.5 *}\n\nlemma \"UNIV = {x. True}\"\n using UNIV_def by auto  (* {x. P(x) \\<or> \\<not>P(x)}, is esentially equal to {x. True} *)\n\nlemma \"\\<forall>x. x\\<in>UNIV\" by auto\n\nsubsection {* definition 5.6 *}\n\nlemma \"{} = {x. False}\"\n  using empty_def by auto\n\nlemma \"\\<forall>x. x\\<notin>{}\" by auto\n\nsubsection {* theorem 5.3 *}\n\nlemma \"\\<forall>P. {} \\<subseteq> P\" \n  by simp\n\nsection {* section 5.3: power set*}\n\nsubsection {* definition 5.7 *}\n\nthm Pow_def (* definition of power set*)\n\nlemma \"Pow A = {X. (\\<forall>t\\<in>X. t\\<in>A)}\" \n  using Pow_def[of A] by blast \n\nlemma \"Pow {} = {{}}\" \n  by simp\n\nlemma \"Pow {a} = {{},{a}}\"\n  by auto\n\nlemma \"Pow {a,b} = {{},{a},{b},{a,b}}\"\n  by auto\n\nlemma \"B \\<subseteq> A \\<Longrightarrow> B \\<in> Pow A\"\n  by simp\n\nlemma \"a\\<in>A \\<Longrightarrow> {a}\\<subseteq>A \\<and> {a}\\<in>Pow A\"\n  by simp\n\nlemma \"a\\<in>A \\<and> b\\<in>A \\<Longrightarrow> {a,b}\\<subseteq>A \\<and> {a,b}\\<in>Pow A\"\n  by simp\n\nsubsection {* differences between subset and belong *}\nlemma \"B \\<subseteq> A \\<Longrightarrow> B \\<in> Pow A\"\n  by auto\n\nlemma \"a\\<in>A \\<Longrightarrow> {a} \\<subseteq> A \\<and> {a}\\<in>Pow A\"\n  by auto\n\nlemma \"a\\<in>A \\<and> b\\<in>A \\<Longrightarrow> {a,b}\\<subseteq>A \\<and> {a,b}\\<in>Pow A\"\n  by auto\n\n\nsubsection {* definition 5.8 *}\n\nthm card_def (* definition of card of set *)\n\nlemma \"finite A \\<Longrightarrow> finite (Pow A)\"\n  by simp\n\nlemma \"\\<not> (finite A) \\<Longrightarrow> \\<not> (finite (Pow A))\"\n  by simp\n\nsubsection {* theorem 5.5 *}\n\nlemma \"finite A \\<Longrightarrow> card (Pow A) = 2 ^ card A\"\n  using Power.card_Pow by auto\n\nlemma \"infinite A \\<Longrightarrow> card A = 0\"\n  using Finite_Set.card.infinite by auto\n\nsubsection {* example 5.9 *}\n\nvalue \"Pow {''a'',''b'',''c''}\"\n  \nsection {* section 5.4: set operations *}\n\nsubsection {* definition 5.9 *}\n\n(* definition of intersection*)\nlemma \"A \\<inter> B = {x. x\\<in>A \\<and> x\\<in>B}\"\n  using Int_def by auto\n\n(* definition of union*)\nlemma  \"A \\<union> B = {x. x \\<in> A \\<or> x \\<in> B}\" \n  using Un_def by auto\n\n(* definition of difference*)\nlemma \"A - B = {x. x \\<in> A \\<and> x \\<notin> B}\"\n  using \"set_diff_eq\" by auto\n\nsubsection {* example 5.10 *}\n\ndefinition \"A4 \\<equiv> {1::int,2,3,4}\"\n\ndefinition \"B4 \\<equiv> {3,4,5,6}\"\n\nvalue \"A4 \\<union> B4\" \n\nvalue \"A4 \\<inter> B4\"\n\nvalue \"A4 - B4\"\n\nvalue \"B4 - A4\"\n\nsubsection {* definition 5.12 *}\n\n(* definition of complement *)\nlemma \"-A = (UNIV - A)\"\n  using Compl_eq_Diff_UNIV by auto\n\nlemma \"- A = {x. x\\<notin>A}\" by auto\n\nsubsection {* example 5.11 *}\n\ndatatype univ = a | b | c | d\n\nlemma univ_lm: \"UNIV = {a, b, c, d}\" \n  proof (rule UNIV_eq_I)\n    fix x show \"x \\<in> {a, b, c, d}\" by (cases x) simp_all\n  qed\n\ndefinition \"A7 \\<equiv> {a, b}\"\n\nvalue \"- A7\"\n\nlemma \"- A7 = {c, d}\" \n  using univ_lm A7_def Compl_eq_Diff_UNIV Diff_eq_empty_iff insertE \n    insertI1 insert_Diff_if insert_commute singletonD subset_insertI \n    univ.distinct(3) univ.distinct(5) univ.distinct(7) univ.distinct(9) by blast\n\ndefinition \"A5 \\<equiv> {x::nat. x > 0}\"\n\nlemma \"- A5 = {x::nat. x = 0}\" \n  proof -\n    have \"\\<forall>x::nat. x > 0 \\<or> x = 0\" by auto\n    have \"\\<forall>x::nat. x\\<in>{x. x = 0} = (x \\<notin> {x. x > 0})\" by simp\n    have \"- A5 = UNIV - A5\" by auto\n    then have \"- A5 = {x::nat \\<in> UNIV. x \\<notin> {x::nat. x > 0}}\" using set_diff_eq A5_def by auto\n    then have \"- A5 = {x::nat \\<in> UNIV. x \\<in> {x::nat. x = 0}}\" by auto\n    then show ?thesis by auto\n  qed\n  \nsubsection {* example 5.12 *}\n\nlemma \"A - B = A \\<inter> (-B)\"\n  using Set.Diff_eq by auto\n\nsubsection {* example 5.13 *}\n\nlemma \"A - (A \\<inter> B) = A - B\" \n  by auto\n\nsubsection {* definition 5.13 *}\n\ndefinition plus :: \"'t set \\<Rightarrow> 't set \\<Rightarrow> 't set\" (infix \"\\<oplus>\" 70)\n  where \"plus A B \\<equiv> (A - B) \\<union> (B - A)\" \n\ndefinition \"A6 \\<equiv> {''a'',''b'',''c'',''d''}\"\n\ndefinition \"B6 \\<equiv> {''a'',''c'',''e''}\"\n\nvalue \"A6 - B6\"\nvalue \"B6 - A6\"\nvalue \"A6 \\<oplus> B6\" \n\nsubsection {* theorem 5.6 *}\n\nthm Set.Un_absorb\nlemma \"A \\<union> A = A\" \n  proof -\n    have \"(\\<forall>x. (x \\<in> (A \\<union> A))) = (\\<forall>x. x\\<in>{x. x \\<in> A \\<or> x \\<in> A})\" using Un_def by simp\n    then have \"(\\<forall>x. (x \\<in> (A \\<union> A))) = (\\<forall>x. x\\<in>{x. x \\<in> A})\" by simp\n    then show ?thesis using Un_def by simp \n  qed\n\nlemma \"A \\<inter> A = A\"\n  by auto\nthm Set.Int_absorb\n\nlemma \"A \\<union> B = B \\<union> A\"\n  by auto\nthm Set.Un_ac(3)\n\nlemma \"A \\<inter> B = B \\<inter> A\"\n  by auto\nthm Set.Int_ac(3)\n\nlemma \"A \\<union> (B \\<union> C) = (A \\<union> B) \\<union> C\" \n  by auto\n\nlemma \"A \\<inter> (B \\<inter> C) = (A \\<inter> B) \\<inter> C\" \n  by auto\n\nlemma \"A \\<union> (B \\<inter> C) = (A \\<union> B) \\<inter> (A \\<union> C)\"\n  using Set.Un_Int_distrib by auto\n\nlemma \"A \\<inter> (B \\<union> C) = (A \\<inter> B) \\<union> (A \\<inter> C)\"\n  using Set.Int_Un_distrib by auto\n\nsubsection {* theorem 5.7 *}\n\nlemma \"A \\<union> {} = A\"\n  using Set.Un_empty_right by auto\n\nlemma \"A \\<inter> UNIV = A\"\n  using Set.Int_UNIV_right by auto\n\nsubsection {* theorem 5.8 *}\n\nlemma \"A \\<union> -A = UNIV\"\n  using Set.Compl_partition by auto\n\nlemma \"A \\<inter> -A = {}\"\n  using Set.Compl_disjoint by auto\n\nsubsection {* theorem 5.9 *}\n\nlemma \"(B = - A) \\<longleftrightarrow> (A \\<union> B = UNIV \\<and> A \\<inter> B = {})\" by auto\n  \nsubsection {* theorem 5.10 *}\n\nlemma \"-(A \\<union> B) = (-A) \\<inter> (-B)\"\n  using Set.Compl_Un by auto\n\nlemma \"-(A \\<inter> B) = (-A) \\<union> (-B)\"\n  using Set.Compl_Int by auto\n\nsubsection {* theorem 5.11 *}\n\nlemma \"A \\<subseteq> B \\<Longrightarrow> A \\<union> B = B\"\n  using Set.Un_absorb1 by auto\n\nlemma \"A \\<union> B = B \\<Longrightarrow> A \\<inter> B = A\" \n  by auto\n\nlemma \"A \\<inter> B = A \\<Longrightarrow> A - B = {}\" \n  by auto\n\nlemma \"A - B = {} \\<Longrightarrow> A \\<subseteq> B\" \n  by auto\n\nsubsection {* definition 5.14 *}\n\nlemma \"\\<Union>A = {x. \\<exists>B \\<in> A. x \\<in> B}\"\n  using Union_eq by auto\n\nlemma \"\\<Inter>A = {x. \\<forall>B \\<in> A. x \\<in> B}\"\n  using Inter_eq by auto\n\nlemma \"\\<Inter>{} = UNIV\" by auto\n\nlemma \"\\<Union>{} = {}\" by auto\n\nsubsection {* example 5.14 *}\n\ndefinition \"C4 \\<equiv> {{0::int},{0,1},{0,1,2}}\"\n\nvalue \"\\<Union>C4\" \n\ndefinition \"A8 \\<equiv> {{0::int,1,2},{4,5,6},{2}}\"\n\nvalue \"\\<Union>A8\"\nvalue \"\\<Inter>A8\"\n\nsection {* section 5.5 counting *}\n\nlemma \"finite A \\<and> finite B \\<and> A \\<inter> B = {} \\<Longrightarrow> card (A \\<union> B) = card A + card B\"\n  using card_Un_disjoint by auto\n\nlemma \"finite A \\<and> finite B \\<Longrightarrow> card A + card B = card (A \\<union> B) + card (A \\<inter> B)\"\n  using card_Un_Int by auto\n\nlemma card_un_int: \"finite A \\<and> finite B \\<Longrightarrow> card (A \\<union> B) = card A + card B - card (A \\<inter> B)\" \n  using card_Un_Int by fastforce\n\n\nsection {* section 5.6 inductive set *}\n\nsubsection {* example 5.16 *}\ninductive_set even :: \"int set\" \n  where \"0 \\<in> even\" |\n        \"n \\<in> even \\<Longrightarrow> n + 2 \\<in> even\"\n\nsubsection {* example 5.17 *}\ninductive_set set3 :: \"int set\"\n  where \"3 \\<in> set3\" |\n        \"\\<lbrakk>x \\<in> set3; y \\<in> set3\\<rbrakk> \\<Longrightarrow> x + y \\<in> set3\"\n\nsubsection {* string set \\<Sigma>* and its caculus *}\n\ntype_synonym \\<Sigma> = \"char\"\n(* type_synonym string = \"\\<Sigma> list\" *)\ntype_synonym string = \"\\<Sigma> list\" \n\nsubsection {* definition 5.16 *}\ninductive_set sigma_set :: \"string set\" (\"\\<Sigma>\\<^sup>*\" 80)\n  where nil_str: \"Nil \\<in> sigma_set\" |\n        cons_str: \"\\<lbrakk>chr\\<in>\\<Sigma>; x\\<in>sigma_set\\<rbrakk> \\<Longrightarrow>chr#x\\<in>sigma_set\"\n\nsubsection {* definition 5.17 *}\nprimrec str_n :: \"\\<Sigma> \\<Rightarrow> nat \\<Rightarrow> string\"\n  where zero_str: \"str_n x 0 = Nil\" |\n        sucn_str: \"str_n x (Suc n) = x#(str_n x n)\"\n\nsubsection {* definition 5.18 *}\ntype_synonym Lang = \"string set\"\n\nlemma \"\\<forall>l::Lang. l \\<subseteq> \\<Sigma>\\<^sup>*\"\n  proof -\n    {\n      fix x\n      have \"\\<forall>l::Lang. x\\<in>l \\<longrightarrow> x\\<in>\\<Sigma>\\<^sup>*\"\n        apply(induct x)\n        using nil_str apply blast\n        using cons_str by blast\n    }\n    then show ?thesis by auto\n  qed\n\nsubsection {* definition 5.19 *}\n\ndefinition multi :: \"Lang \\<Rightarrow> Lang \\<Rightarrow> Lang\" (infixl \"\\<^emph>\" 85) (*(\"_\\<^emph>_\")*)\n  where \"A \\<^emph> B \\<equiv> {z. \\<exists>x y. x\\<in>A \\<and> y\\<in>B \\<and> z = x@y}\"\n\nsubsection {* example 5.18 *}\n\nvalue \"{Nil, ''a'',''ab''} \\<^emph> {''a'',''bb''}\"\n\nvalue \"{''a'',''bb''} \\<^emph> {Nil, ''a'',''ab''}\"\n\nvalue \"{''a'',''ab''} \\<^emph> {''a'',''bb''}\"\n\nsubsection {* theorem 5.13 *}\n\nlemma \"(A \\<^emph> {}) = ({} \\<^emph> A)\" by (simp add: multi_def) \n\nlemma \"(A \\<^emph> {Nil}) = ({Nil} \\<^emph> A)\" \n  proof -\n    have \"\\<forall>x\\<in>(A \\<^emph> {Nil}). x\\<in>({Nil} \\<^emph> A)\"\n      proof\n        fix x\n        assume \"x \\<in> A\\<^emph>{Nil}\"\n        then have \"\\<exists>x1 y1. x1\\<in>A \\<and> y1\\<in>{Nil} \\<and> x = x1@y1\" by (simp add:multi_def)\n        then show \"x\\<in>({Nil} \\<^emph> A)\" using multi_def by auto \n      qed\n    moreover\n    have \"\\<forall>x\\<in>({Nil} \\<^emph> A). x\\<in>(A \\<^emph> {Nil})\"\n      proof\n        fix x\n        assume \"x\\<in>({Nil} \\<^emph> A)\"\n        then have \"\\<exists>x1 y1. x1\\<in>{Nil} \\<and> y1\\<in>A \\<and> x = x1@y1\" by (simp add:multi_def)\n        then show \"x\\<in>(A \\<^emph> {Nil})\" using multi_def by auto \n      qed\n    ultimately show ?thesis by auto\n  qed\n\nlemma comm_lm: \"((A \\<^emph> B) \\<^emph> C) = (A \\<^emph> (B \\<^emph> C))\"\n  proof -\n    have \"\\<forall>x\\<in>((A \\<^emph> B) \\<^emph> C). x\\<in>(A \\<^emph> (B \\<^emph> C))\"\n      proof\n        fix x\n        assume \"x\\<in>((A \\<^emph> B) \\<^emph> C)\"\n        then have \"\\<exists>x1 y1. x1\\<in>(A \\<^emph> B) \\<and> y1\\<in>C \\<and> x = x1@y1\" by (simp add:multi_def)\n        then have \"\\<exists>x1 y1 x2 y2. x2\\<in>A \\<and> y2\\<in>B \\<and> x1 = x2@y2 \\<and> y1\\<in>C \\<and> x = x1@y1\"\n          using multi_def by auto \n        then have \"\\<exists>x1 y1 x2 y2. x2\\<in>A \\<and> y2\\<in>B \\<and> x1 = y2@y1 \\<and> y1\\<in>C \\<and> x = x2@x1\"\n          using append_assoc by blast \n        then show \"x\\<in>(A \\<^emph> (B \\<^emph> C))\" using multi_def by auto \n      qed\n    moreover\n    have \"\\<forall>x\\<in>(A \\<^emph> (B \\<^emph> C)). x\\<in>((A \\<^emph> B) \\<^emph> C)\" sorry (* similar to above *)\n    ultimately show ?thesis by auto\n  qed\n\nlemma \"A \\<subseteq> B \\<and> C \\<subseteq> D \\<Longrightarrow> (A \\<^emph> C) \\<subseteq> (B \\<^emph> D)\"\n  proof -\n    assume p: \"A \\<subseteq> B \\<and> C \\<subseteq> D\"\n    have \"\\<forall>x\\<in>(A \\<^emph> C). x\\<in>(B \\<^emph> D)\"\n      proof\n        fix x\n        assume \"x\\<in>(A \\<^emph> C)\"\n        with p show \"x\\<in>(B \\<^emph> D)\"\n          using mem_Collect_eq multi_def set_rev_mp by fastforce\n      qed\n    then show \"(A \\<^emph> C) \\<subseteq> (B \\<^emph> D)\" by auto\n  qed\n\nlemma \"(A \\<^emph> (B \\<union> C)) = (A \\<^emph> B) \\<union> (A \\<^emph> C)\"\n  proof -\n    have \"\\<forall>x\\<in>(A \\<^emph> (B \\<union> C)). x\\<in>(A \\<^emph> B) \\<union> (A \\<^emph> C)\"\n      proof\n        fix x\n        assume \"x\\<in>(A \\<^emph> (B \\<union> C))\"\n        then have \"\\<exists>y z. y\\<in>A \\<and> z\\<in>B \\<union> C \\<and> x = y@z\" by (simp add:multi_def)\n        then have \"\\<exists>y z. y\\<in>A \\<and> (z\\<in>B \\<or> z\\<in>C) \\<and> x = y@z\" by simp\n        then have \"\\<exists>y z. (y\\<in>A \\<and> z\\<in>B \\<and> x = y@z) \\<or> (y\\<in>A \\<and> z\\<in>C \\<and> x = y@z)\" by auto\n        then have \"(\\<exists>y z. (y\\<in>A \\<and> z\\<in>B \\<and> x = y@z)) \\<or> (\\<exists>y z. (y\\<in>A \\<and> z\\<in>C \\<and> x = y@z))\" by auto\n        then have \"x\\<in>(A \\<^emph> B) \\<or> x\\<in>(A \\<^emph> C)\" by (simp add:multi_def)\n        then show \"x\\<in>(A \\<^emph> B) \\<union> (A \\<^emph> C)\" by simp\n      qed\n    moreover\n    have \"\\<forall>x\\<in>(A \\<^emph> B) \\<union> (A \\<^emph> C). x\\<in>(A \\<^emph> (B \\<union> C))\" sorry (* similar to the above formula*)\n    ultimately show ?thesis by auto\n  qed\n\nlemma \"((B \\<union> C) \\<^emph> A) = ((B \\<^emph> A) \\<union> (C \\<^emph> A))\"\n  sorry (*similar to the above lemma*)\n\nlemma \"(A \\<^emph> (B \\<inter> C)) \\<subseteq> (A \\<^emph> B) \\<inter> (A \\<^emph> C)\"\n  proof -\n  {\n    fix x\n    assume \"x\\<in>(A \\<^emph> (B \\<inter> C))\"\n    then have \"\\<exists>y z. y\\<in>A \\<and> z\\<in>B \\<inter> C \\<and> x = y@z\" by (simp add:multi_def)\n    then have \"\\<exists>y z. y\\<in>A \\<and> (z\\<in>B \\<and> z\\<in>C) \\<and> x = y@z\" by simp\n    then have \"\\<exists>y z. (y\\<in>A \\<and> z\\<in>B \\<and> x = y@z) \\<and> (y\\<in>A \\<and> z\\<in>C \\<and> x = y@z)\" by auto\n    then have \"(\\<exists>y z. (y\\<in>A \\<and> z\\<in>B \\<and> x = y@z)) \\<and> (\\<exists>y z. (y\\<in>A \\<and> z\\<in>C \\<and> x = y@z))\" by auto\n    then have \"x\\<in>(A \\<^emph> B) \\<and> x\\<in>(A \\<^emph> C)\" by (simp add:multi_def)\n    then have \"x\\<in>(A \\<^emph> B) \\<inter> (A \\<^emph> C)\" by simp\n  }\n  then show ?thesis by auto\n  qed\n\nlemma \"((B \\<inter> C) \\<^emph> A) \\<subseteq> ((B \\<^emph> A) \\<inter> (C \\<^emph> A))\"\n  sorry (*similar to the above lemma*)\n\nsubsection {* definition 5.20 *}\n\nprimrec A_n :: \"Lang \\<Rightarrow> nat \\<Rightarrow> Lang\" (\"_\\<^sup>_\" [81] 80)\n  where a_n_nil: \"(A\\<^sup>0) = {Nil}\" |\n        a_n_cons: \"A_n A (Suc n) = (A \\<^emph> (A\\<^sup>n))\"\n\nsubsection {* example 5.19 *}\n\nvalue \"A_n ({Nil, ''a'', ''ab''}) 0\"\n\nvalue \"A_n ({Nil, ''a'', ''ab''}) 1\"\n\nvalue \"A_n ({Nil, ''a'', ''ab''}) 2\"\n\nsubsection {* theorem 5.14 *}\n\nlemma A_n_plus: \"\\<forall>A m n. ((A\\<^sup>m) \\<^emph> (A\\<^sup>n)) = (A_n A (m+n))\"\n  proof -\n  {\n    fix m A\n    have \"\\<forall>n. ((A\\<^sup>m) \\<^emph> (A\\<^sup>n)) = (A_n A (m+n))\"\n      proof(induct m)\n        case 0\n        show ?case\n          proof\n            fix n\n            have \"\\<forall>x\\<in>((A\\<^sup>0) \\<^emph> (A\\<^sup>n)). x\\<in>(A_n A (0 + n))\"\n              proof\n                fix x\n                assume \"x\\<in>((A\\<^sup>0) \\<^emph> (A\\<^sup>n))\"\n                then have \"x\\<in>({Nil} \\<^emph> (A\\<^sup>n))\" using a_n_nil by simp\n                then have \"\\<exists>y z. y\\<in>{Nil} \\<and> z\\<in>(A\\<^sup>n) \\<and> x = y@z\" by (simp add:multi_def)\n                then have \"x\\<in>(A\\<^sup>n)\" by (simp add:multi_def)\n                then show \"x\\<in>(A_n A (0 + n))\" by simp\n              qed\n            moreover\n            have \"\\<forall>x\\<in>(A_n A (0 + n)). x\\<in>((A\\<^sup>0) \\<^emph> (A\\<^sup>n))\"\n              proof\n                fix x\n                assume \"x\\<in>(A_n A (0 + n))\"\n                then have \"x\\<in>(A\\<^sup>n)\" by simp\n                then have \"\\<exists>y z. y\\<in>{Nil} \\<and> z\\<in>(A\\<^sup>n) \\<and> x = y@z\" by (simp add:multi_def)\n                then show \"x\\<in>((A\\<^sup>0) \\<^emph> (A\\<^sup>n))\" by (simp add:multi_def)\n              qed\n            ultimately show \"((A\\<^sup>0) \\<^emph> (A\\<^sup>n)) = (A_n A (0 + n))\" by auto\n          qed\n      next\n        case (Suc m)\n        assume p: \"\\<forall> n. ((A\\<^sup>m) \\<^emph> (A\\<^sup>n)) = (A_n A (m + n))\"\n        show ?case\n          proof\n            fix n\n            from p have \"((A\\<^sup>m) \\<^emph> (A\\<^sup>n)) = (A_n A (m + n))\" by simp\n            moreover\n            have \"(A_n A (Suc m)) \\<^emph> (A\\<^sup>n) = (A \\<^emph> (A\\<^sup>m)) \\<^emph> (A\\<^sup>n)\"\n              using a_n_cons by simp\n            moreover\n            have \"(A_n A (Suc m + n)) = (A \\<^emph> A_n A (m + n))\" \n              using a_n_cons by simp\n\n            ultimately show \"((A_n A (Suc m)) \\<^emph> (A\\<^sup>n)) = (A_n A (Suc m + n))\"\n              by (simp add: comm_lm) \n          qed\n      qed\n  }\n  then show ?thesis by simp\n  qed\n\nlemma \"\\<forall>A m n. A_n (A\\<^sup>m) n = A_n A (m*n)\" \n  proof -\n  {\n    fix A m\n    have \"\\<forall>n. A_n (A\\<^sup>m) n = A_n A (m*n)\"\n      proof(induct m)\n        case 0\n        show ?case \n          proof\n            fix n\n            have \"A_n (A\\<^sup>0) n = (A\\<^sup>0)\" \n              proof(induct n)\n                case 0\n                show ?case using a_n_nil by auto\n              next\n                case (Suc k)\n                assume \"A_n (A\\<^sup>0) k = (A\\<^sup>0)\"\n                then have \"A_n (A\\<^sup>0) (Suc k) = (A\\<^sup>0) \\<^emph> (A\\<^sup>0)\"\n                  using a_n_cons by auto\n                then show ?case by (simp add:multi_def)\n              qed\n            then show \"A_n (A\\<^sup>0) n = A_n A (0 * n)\" by simp\n          qed\n      next\n        case (Suc k)\n        assume p: \"\\<forall>n. A_n (A\\<^sup>k) n = A_n A (k * n)\"\n        show ?case\n          proof \n            fix n\n            show \"A_n (A_n A (Suc k)) n = A_n A (Suc k * n)\"\n              proof(induct n)\n                case 0\n                show ?case using a_n_nil by auto\n              next\n                case (Suc l)\n                assume a0: \"A_n (A_n A (Suc k)) l = A_n A (Suc k * l)\"\n                \n                have \"A_n (A_n A (Suc k)) l = A_n (A \\<^emph> (A_n A k)) l\" \n                  using a_n_nil by auto\n                then have a1: \"A_n (A_n A (Suc k)) (Suc l) = ((A_n A (Suc k)) \\<^emph> (A_n (A_n A (Suc k)) l))\"\n                  using a_n_nil by auto\n                with a0 have \"A_n (A_n A (Suc k)) (Suc l) = ((A_n A (Suc k)) \\<^emph> (A_n A (Suc k * l)))\"\n                  by simp\n                then have \"A_n (A_n A (Suc k)) (Suc l) = ((A \\<^emph> (A_n A k)) \\<^emph> (A_n A (Suc k * l)))\"\n                  using a_n_cons by auto\n                then show ?case \n                  using A_n_plus by (metis a1 a0 mult.commute mult_Suc) \n              qed\n          qed\n      qed\n  }\n  then show ?thesis by auto\n  qed\n\nlemma \"A \\<subseteq> B \\<Longrightarrow> (A\\<^sup>n) \\<subseteq> (B\\<^sup>n)\" sorry\n  (* please prove it by youself *)\n\nsubsection {* definition 5.21 *}\ndefinition A_star :: \"Lang \\<Rightarrow> Lang\" (\"(_\\<^sup>\\<star>)\" [1000] 999)\n  where \"A\\<^sup>\\<star> \\<equiv> (\\<Union>n. A\\<^sup>n)\"\n\ndefinition A_star1 :: \"Lang \\<Rightarrow> Lang\" (\"(_\\<^sup>+)\" [1000] 999)\n  where \"A\\<^sup>+ \\<equiv> (\\<Union>n\\<in>{0<..}. A\\<^sup>n)\"\n\nlemma A_star1_lm: \"(x\\<in>A\\<^sup>+) = (\\<exists>n::nat>0. x\\<in>A\\<^sup>n)\"\n  proof -\n    have \"(x\\<in>A\\<^sup>+) \\<longrightarrow> (\\<exists>n::nat>0. x\\<in>A\\<^sup>n)\" using A_star1_def by blast\n    moreover\n    have \"(\\<exists>n::nat>0. x\\<in>A\\<^sup>n) \\<longrightarrow> (x\\<in>A\\<^sup>+)\" using A_star1_def by blast\n    ultimately show ?thesis by auto\n  qed\n\nlemma A_star_lm: \"(x\\<in>A\\<^sup>\\<star>) = (\\<exists>n::nat. x\\<in>A\\<^sup>n)\"\n  proof -\n    have \"(x\\<in>A\\<^sup>\\<star>) \\<longrightarrow> (\\<exists>n::nat. x\\<in>A\\<^sup>n)\" using A_star_def by blast\n    moreover\n    have \"(\\<exists>n::nat. x\\<in>A\\<^sup>n) \\<longrightarrow> (x\\<in>A\\<^sup>\\<star>)\" using A_star_def by blast\n    ultimately show ?thesis by auto\n  qed\n\n\nsubsection{* example 5.20 *}\n\nlemma \"{''a''}\\<^sup>+ = (\\<Union>n\\<in>{0<..}. {''a''}\\<^sup>n)\"\n  unfolding A_star1_def using a_n_cons by blast\n\nlemma \"{''a''}\\<^sup>\\<star> = (\\<Union>n. {''a''}\\<^sup>n)\"\n  unfolding A_star_def using a_n_cons by blast\n\n\nsubsection{* theorem 5.15 *}\n\nlemma A_star_lm2: \"A\\<^sup>\\<star> = A\\<^sup>+ \\<union> A\\<^sup>0\" \n  proof -\n  {\n    fix x\n    have \"(x \\<in> A\\<^sup>\\<star>) \\<longrightarrow> (x = [] \\<or> x \\<in> A\\<^sup>+)\"\n      using A_star_lm A_star1_lm by (metis a_n_nil gr0I singletonD) \n    moreover\n    have \"(x = [] \\<or> x \\<in> A\\<^sup>+) \\<longrightarrow> (x \\<in> A\\<^sup>\\<star>)\"\n      using A_star_lm A_star1_lm by (metis a_n_nil insert_iff) \n    ultimately have \"(x \\<in> A\\<^sup>\\<star>) = (x = [] \\<or> x \\<in> A\\<^sup>+)\" by auto\n  }\n  then show ?thesis by (simp add:set_eq_iff)\n  qed\n\nlemma \"A\\<^sup>n \\<subseteq> A\\<^sup>\\<star>\" \n  using A_star_lm by auto\n\nlemma \"n > 0 \\<Longrightarrow> A\\<^sup>n \\<subseteq> A\\<^sup>+\" \n  using A_star1_lm by auto\n\nlemma \"A \\<subseteq> (A \\<^emph> (B\\<^sup>\\<star>))\"\n  sorry\n\nlemma \"A \\<subseteq> ((B\\<^sup>\\<star>) \\<^emph> A)\"\n  sorry\n\nlemma \"A \\<subseteq> B \\<Longrightarrow> A\\<^sup>\\<star> \\<subseteq> B\\<^sup>\\<star>\"\n  sorry\n\nlemma \"A \\<subseteq> B \\<Longrightarrow> (A_star1 A) \\<subseteq> (A_star1 B)\"\n  sorry\n\nlemma \"A \\<^emph> (A\\<^sup>\\<star>) = (A\\<^sup>\\<star>) \\<^emph> A\"\n  sorry\n\nlemma \"Nil\\<in>A \\<Longrightarrow> A\\<^sup>\\<star> = A\\<^sup>+\"\n  sorry\n\nlemma \"(A\\<^sup>\\<star>)\\<^sup>\\<star> = (A\\<^sup>\\<star>) \\<^emph> (A\\<^sup>\\<star>)\"\n  sorry\n\nlemma \"(A\\<^sup>\\<star>)\\<^sup>\\<star> = (A\\<^sup>+)\\<^sup>\\<star>\"\n  sorry\n\nlemma \"A_star1 (A_star1 A) = A_star1 A\"\n  sorry\n\nsection {* section 5.7 pair and product *}\n\nsubsection {* definition 5.22*}\n\nvalue \"(x,y)\"\n\nvalue \"fst (x,y)\"\n\nvalue \"snd (x,y)\"\n\nlemma \"x \\<noteq> y \\<Longrightarrow> (x,y)\\<noteq>(y,x)\" by auto\n\nlemma \"(x,y) \\<noteq> (y,x)\" nitpick sorry (*it is not correct*)\n\nlemma \"{x,y} = {y,x}\" by auto\n\nlemma \"{x,x} = {x}\" by auto\n\nsubsection {* theorem 5.16*}\n\nlemma \"(x,y) = (u,v) \\<longleftrightarrow> u = x \\<and> v = y\" by auto\n\nsubsection {* definition 5.23*}\n\nvalue \"(x1,x2,x3,x4)\"\n\nlemma \"(x1,x2,x3,x4) = (x1,(x2,(x3,x4)))\" by auto\n\n(* lemma \"(x1,x2,x3,x4) = (((x1,x2),x3),x4)\" *)\n(* syntax error*)\n\nlemma \"(x1,x2,x3,x4) = (y1,y2,y3,y4) \\<longleftrightarrow> x1 = y1 \\<and> x2 = y2 \\<and> x3 = y3 \\<and> x4 = y4\"\n  by auto\n\nsubsection {* definition 5.24*}\n\n(* thm Times_Un_distrib1 *)\n\nthm Sigma_def\n\nlemma \"A \\<times> B = {(x,y). x\\<in>A \\<and> y\\<in>B}\" by auto\n\nsubsection {* example 5.21 *}\n\ndefinition \"A9 \\<equiv> {''a'',''b''}\"\n\ndefinition \"B9 \\<equiv> {1::int,2,3}\"\n\nvalue \"A9 \\<times> B9\"\n\nvalue \"B9 \\<times> A9\"\n\nvalue \"A9 \\<times> A9\"\n\nvalue \"B9 \\<times> B9\"\n\n(*  value \"(A9 \\<times> B9) \\<inter> (B9 \\<times> A9)\"  *)\n\nsubsection {* example 5.22 *}\n\nvalue \"({}:: int set) \\<times> {1::int,2,3}\"\n\nvalue \"{1::int,2,3} \\<times> ({}:: int set)\"\n\nsection {* exercise *}\n\nlemma \"{{}} \\<subseteq> {{}, {{}}}\" by auto\n\n\nend\n", "meta": {"author": "LVPGroup", "repo": "FLAT", "sha": "674c932d9a2f178cb870e28bd63407ad797199e8", "save_path": "github-repos/isabelle/LVPGroup-FLAT", "path": "github-repos/isabelle/LVPGroup-FLAT/FLAT-674c932d9a2f178cb870e28bd63407ad797199e8/Section1_Foundation/SetFoundation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.8887587949656841, "lm_q1q2_score": 0.7571805556673766}}
{"text": "section \\<open>A Hilbert Proof Calculus for Propositional Logic (PL)\\<close>\n\n(*<*)\ntheory Hilbert\nimports Main\n\nbegin\n(*>*)\n\nsubsection \\<open>Logical Connectives for PL\\<close>\n\nsubsubsection \\<open>Primitive Connectives\\<close>\n\nconsts impl :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<rightarrow>\" 49)\nconsts not :: \"bool \\<Rightarrow> bool\" (\"\\<^bold>\\<not>\")\n\ntext \\<open>In philosophy, we often assume that the only two logical connectives\n  are the implication @{const impl} and the negation @{const not}.\n  This is handy, since it simplifies proofs to only consider these two\n  cases.\n\\<close>\n\nsubsubsection \\<open>Further Defined Connectives\\<close>\n\ntext \\<open>We can of course add further connectives that are to be\n  understood as abbreviations that are defined in terms of the primitive\n  connectives above.\\<close>\n\nabbreviation disj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<or>\"50) where\n  \"A \\<^bold>\\<or> B \\<equiv> \\<^bold>\\<not>A \\<^bold>\\<rightarrow> B\"\nabbreviation conj :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" (infixr \"\\<^bold>\\<and>\"51) where\n  \"A \\<^bold>\\<and> B \\<equiv> \\<^bold>\\<not>(A \\<^bold>\\<rightarrow> \\<^bold>\\<not>B)\"\n\nsubsection \\<open>Hilbert Axioms for PL\\<close>\n\nsubsubsection \\<open>Axiom Schemes\\<close>\n\naxiomatization where\n  (* A1: \"(A \\<^bold>\\<rightarrow> A)\" and*)\n  A2: \"A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> A)\" and\n  A3: \"(A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> C)) \\<^bold>\\<rightarrow> ((A \\<^bold>\\<rightarrow> B) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> C))\" and\n  A4: \"(\\<^bold>\\<not>A \\<^bold>\\<rightarrow> \\<^bold>\\<not>B) \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> A)\"\n\nsubsubsection \\<open>Inference Rules\\<close>\n\naxiomatization where\n  ModusPonens: \"(A \\<^bold>\\<rightarrow> B) \\<Longrightarrow> A \\<Longrightarrow> B\"\n\n(* Test soundness of axiomatizaion *)\nlemma True nitpick [satisfy, user_axioms, expect = genuine] oops\n\nsubsection \\<open>A Proof\\<close>\n\n(* just playing around *)\nthm A3[where A = \"A\" and B = \"(B \\<^bold>\\<rightarrow> A)\" and C = \"A\"]\nthm A3[of \"A\" \"(B \\<^bold>\\<rightarrow> A)\" \"A\"]\n\ntext \\<open>We show that A1 is redundant\\<close>\n\ntheorem A1Redundant:\n  shows \"A \\<^bold>\\<rightarrow> A\"\nproof -\n  have 1: \"(A \\<^bold>\\<rightarrow> ((B \\<^bold>\\<rightarrow> A) \\<^bold>\\<rightarrow> A)) \\<^bold>\\<rightarrow> ((A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> A)) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> A))\" by (rule A3[where B = \"(B \\<^bold>\\<rightarrow> A)\" and C = \"A\"])\n  have 2: \"A \\<^bold>\\<rightarrow> ((B \\<^bold>\\<rightarrow> A) \\<^bold>\\<rightarrow> A)\"  by (rule A2[where B = \"B \\<^bold>\\<rightarrow> A\"])\n  from 1 2 have 3: \"(A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> A)) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> A)\" by (rule ModusPonens)\n  have 4: \"(A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> A))\" by (rule A2)\n  from 3 4 have 5: \"A \\<^bold>\\<rightarrow> A\" by (rule ModusPonens)\n  thus ?thesis .\nqed\n\n\ntheorem \n  shows \"A \\<^bold>\\<rightarrow> A\"\n  by (metis (full_types) A2 ModusPonens) -- \"Sledgehammer even finds a proof without using A3\"\n\nsubsection \\<open>Exercise 3\\<close>\n\ntheorem transitivity:\n  assumes 1: \"A \\<^bold>\\<rightarrow> B\" and\n  2: \"B \\<^bold>\\<rightarrow> C\"\n  shows \"A \\<^bold>\\<rightarrow> C\"\n  proof -\n    have 3: \"(A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> C)) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> B) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> C)\" by (rule A3)\n    have 4: \"(B \\<^bold>\\<rightarrow> C) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> C))\" by (rule A2)\n    from 4 2 have 5: \"A \\<^bold>\\<rightarrow> (B \\<^bold>\\<rightarrow> C)\" by (rule ModusPonens)\n    from 3 5 have 6: \"(A \\<^bold>\\<rightarrow> B) \\<^bold>\\<rightarrow> (A \\<^bold>\\<rightarrow> C)\" by (rule ModusPonens)\n    from 6 1 have 7: \"A \\<^bold>\\<rightarrow> C\" by (rule ModusPonens)\n    thus ?thesis .\nqed\n(*<*)\nend\n(*>*)\n", "meta": {"author": "MrChico", "repo": "CompMeta", "sha": "6ea156d26df6feaac10d652a3743252f7112655a", "save_path": "github-repos/isabelle/MrChico-CompMeta", "path": "github-repos/isabelle/MrChico-CompMeta/CompMeta-6ea156d26df6feaac10d652a3743252f7112655a/as02/Hilbert.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7569403846723487}}
{"text": "theory theory29 imports Main begin\n\ndeclare [[names_short]]\n\n(* 3.1 *)\n\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N a) s = a\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a b) s = aval a s + aval b s\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N a) = N a\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus p q) = \n (case (asimp_const p, asimp_const q) of \n  (N a, N b) \\<Rightarrow> N (a+b) |\n  (x, y) \\<Rightarrow> Plus x y)\"\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N a) (N b) = N (a+b)\" |\n\"plus p (N i) = (if i = 0 then p else Plus p (N i))\" |\n\"plus (N i) p = (if i = 0 then p else Plus (N i) p)\" |\n\"plus p q = (Plus p q)\"\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N a) = N a\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus p q) = plus (asimp p) (asimp q)\"\n\nlemma plus_correct: \"aval (plus e1 e2) s = aval e1 s + aval e2 s\"\n  apply(induction rule:plus.induct)\n  apply(auto)\n  done\n\ntheorem asimp_correct: \"aval (asimp e) s = aval e s\"\n  apply (induction e)\n  apply (auto simp add: plus_correct)\n  done  \n\n(* 3.2 *)\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And a b) s = (bval a s \\<and> bval b s)\" |\n\"bval (Less a b) s = (aval a s < aval b s)\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n) (N m) = Bc(n < m)\" |\n\"less a b = Less a b\"\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and a b = And a b\"\n\nlemma and_0: \"bval (and a1 a2) s = (bval a1 s \\<and> bval a2 s)\"\n  apply (induction rule: and.induct)\n  apply (auto)\n  done\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And a b) = and (bsimp a) (bsimp b)\" |\n\"bsimp (Less a b) = less (asimp a) (asimp b)\"\n\n(* 3.3  *)\n\ndatatype instr = LOADI val | LOAD vname | ADD\n\ntype_synonym stack = \"val list\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec1 (LOADI n) _ stk = n # stk\" |\n\"exec1 (LOAD x) s stk = s(x) # stk\" |\n\"exec1 ADD _ (x # y # stk) = (x+y) # stk\"  \n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i#is) s stk = exec is s (exec1 i s stk)\" \n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\nlemma exec_append: \"exec (is1 @ is2) s stk = exec is2 s (exec is1 s stk)\"\napply (induction is1 arbitrary:stk)\napply (auto)\ndone\n\nlemma \"exec (comp a) s stk = aval a s # stk\"\napply (induction a arbitrary:stk)\napply (auto  simp add: exec_append)\ndone\n\n", "meta": {"author": "kolya-vasiliev", "repo": "isabelle_sc", "sha": "843c848dff833dcb956fcace6afa95a08543044f", "save_path": "github-repos/isabelle/kolya-vasiliev-isabelle_sc", "path": "github-repos/isabelle/kolya-vasiliev-isabelle_sc/isabelle_sc-843c848dff833dcb956fcace6afa95a08543044f/theory29.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.8354835391516132, "lm_q1q2_score": 0.7569395815692807}}
{"text": "header {* Log Upper and Lower Bounds *}\n\ntheory Log_CF_Bounds\nimports Bounds_Lemmas\n\nbegin\n\ntheorem ln_upper_1: \"0<x \\<Longrightarrow> ln(x) \\<le> x - 1\"\nby (rule ln_le_minus_one)\n\ndefinition ln_lower_1 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_1 \\<equiv> \\<lambda>x. 1 - (inverse x)\"\n\ncorollary ln_lower_1: \"0<x \\<Longrightarrow> ln_lower_1 x \\<le> ln x\"\n  unfolding ln_lower_1_def\n  by (metis ln_inverse ln_le_minus_one positive_imp_inverse_positive minus_diff_eq minus_le_iff)\n\ntheorem ln_lower_1_eq: \"0<x \\<Longrightarrow> ln_lower_1 x = (x - 1)/x\"\n  by (auto simp: ln_lower_1_def divide_simps)\n\nsection {*Upper Bound 3*}\n\ndefinition ln_upper_3 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_3 \\<equiv> \\<lambda>x. (x + 5)*(x - 1) / (2*(2*x + 1))\"\n\ndefinition diff_delta_ln_upper_3 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_3 \\<equiv> \\<lambda>x. (x - 1)^3 / ((2*x + 1)^2 * x)\"\n\nlemma d_delta_ln_upper_3: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_3 x - ln x) has_field_derivative diff_delta_ln_upper_3 x) (at x)\"\nunfolding ln_upper_3_def diff_delta_ln_upper_3_def\napply (intro derivative_eq_intros | simp)+\napply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\ndone\n\ntext{*Strict inequalities also possible*}\nlemma ln_upper_3_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_3 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_3])\napply (auto simp: diff_delta_ln_upper_3_def ln_upper_3_def)\ndone\n\nlemma ln_upper_3_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_3 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_3])\nusing assms\napply (auto simp: diff_delta_ln_upper_3_def divide_simps ln_upper_3_def)\ndone\n\ntheorem ln_upper_3: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_3 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_3_neg ln_upper_3_pos)\n\ndefinition ln_lower_3 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_3 \\<equiv> \\<lambda>x. - ln_upper_3 (inverse x)\"\n\ncorollary ln_lower_3: \"0<x \\<Longrightarrow> ln_lower_3 x \\<le> ln x\"\n  unfolding ln_lower_3_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_3)\n\ntheorem ln_lower_3_eq: \"0<x \\<Longrightarrow> ln_lower_3 x = (1/2)*(1 + 5*x)*(x - 1) / (x*(2 + x))\"\n  unfolding ln_lower_3_def ln_upper_3_def\n  by (simp add: divide_simps) algebra\n\n\nsection {*Upper Bound 5*}\n\ndefinition ln_upper_5 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_5 x \\<equiv> (x^2 + 19*x + 10)*(x - 1) / (3*(3*x^2 + 6*x + 1))\"\n\ndefinition diff_delta_ln_upper_5 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_5 \\<equiv> \\<lambda>x. (x - 1)^5 / ((3*x^2 + 6*x + 1)^2*x)\"\n\nlemma d_delta_ln_upper_5: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_5 x - ln x) has_field_derivative diff_delta_ln_upper_5 x) (at x)\"\n  unfolding ln_upper_5_def diff_delta_ln_upper_5_def\n  apply (intro derivative_eq_intros | simp add: add_nonneg_eq_0_iff)+\n  apply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\n  done\n\nlemma ln_upper_5_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_5 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_5])\napply (auto simp: diff_delta_ln_upper_5_def ln_upper_5_def)\ndone\n\nlemma ln_upper_5_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_5 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_5])\nusing assms\napply (auto simp: diff_delta_ln_upper_5_def divide_simps ln_upper_5_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_5: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_5 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_5_neg ln_upper_5_pos)\n\ndefinition ln_lower_5 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_5 \\<equiv> \\<lambda>x. - ln_upper_5 (inverse x)\"\n\ncorollary ln_lower_5: \"0<x \\<Longrightarrow> ln_lower_5 x \\<le> ln x\"\n  unfolding ln_lower_5_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_5)\n\ntheorem ln_lower_5_eq: \"0<x \\<Longrightarrow>\n    ln_lower_5 x = (1/3)*(10*x^2 + 19*x + 1)*(x - 1) / (x*(x^2 + 6*x + 3))\"\n  unfolding ln_lower_5_def ln_upper_5_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection {*Upper Bound 7*}\n\ndefinition ln_upper_7 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_7 x \\<equiv> (3*x^3 + 131*x^2 + 239*x + 47)*(x - 1) / (12*(4*x^3 + 18*x^2 + 12*x + 1))\"\n\ndefinition diff_delta_ln_upper_7 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_7 \\<equiv> \\<lambda>x. (x - 1)^7 / ((4*x^3 + 18*x^2 + 12*x + 1)^2 * x)\"\n\nlemma d_delta_ln_upper_7: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_7 x - ln x) has_field_derivative diff_delta_ln_upper_7 x) (at x)\"\nunfolding ln_upper_7_def diff_delta_ln_upper_7_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_7_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_7 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_7])\napply (auto simp: diff_delta_ln_upper_7_def ln_upper_7_def)\ndone\n\nlemma ln_upper_7_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_7 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_7])\nusing assms\napply (auto simp: diff_delta_ln_upper_7_def divide_simps ln_upper_7_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_7: \"0 < x \\<Longrightarrow> ln(x) \\<le> ln_upper_7 x\"\n  by (metis le_less_linear less_eq_real_def ln_upper_7_neg ln_upper_7_pos)\n\ndefinition ln_lower_7 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_7 \\<equiv> \\<lambda>x. - ln_upper_7 (inverse x)\"\n\ncorollary ln_lower_7: \"0 < x \\<Longrightarrow> ln_lower_7 x \\<le> ln x\"\n  unfolding ln_lower_7_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_7)\n\ntheorem ln_lower_7_eq: \"0 < x \\<Longrightarrow>\n  ln_lower_7 x = (1/12)*(47*x^3 + 239*x^2 + 131*x + 3)*(x - 1) / (x*(x^3 + 12*x^2 + 18*x + 4))\"\n  unfolding ln_lower_7_def ln_upper_7_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection {*Upper Bound 9*}\n\ndefinition ln_upper_9 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_9 x \\<equiv> (6*x^4 + 481*x^3 + 1881*x^2 + 1281*x + 131)*(x - 1) /\n                         (30 * (5*x^4 + 40*x^3 + 60*x^2 + 20*x + 1))\"\n\ndefinition diff_delta_ln_upper_9 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_9 \\<equiv> \\<lambda>x. (x - 1)^9 / (((5*x^4 + 40*x^3 + 60*x^2 + 20*x + 1)^2) * x)\"\n\nlemma d_delta_ln_upper_9: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_9 x - ln x) has_field_derivative diff_delta_ln_upper_9 x) (at x)\"\nunfolding ln_upper_9_def diff_delta_ln_upper_9_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_9_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_9 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_9])\napply (auto simp: diff_delta_ln_upper_9_def ln_upper_9_def)\ndone\n\nlemma ln_upper_9_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_9 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_9])\nusing assms\napply (auto simp: diff_delta_ln_upper_9_def divide_simps ln_upper_9_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_9: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_9 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_9_neg ln_upper_9_pos)\n\n\ndefinition ln_lower_9 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_9 \\<equiv> \\<lambda>x. - ln_upper_9 (inverse x)\"\n\ncorollary ln_lower_9: \"0 < x \\<Longrightarrow> ln_lower_9 x \\<le> ln x\"\n  unfolding ln_lower_9_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_9)\n\ntheorem ln_lower_9_eq: \"0 < x \\<Longrightarrow>\n      ln_lower_9 x = (1/30)*(6 + 481*x + 1881*x^2 + 1281*x^3 + 131*x^4)*(x - 1) /\n                     (x*(5 + 40*x + 60*x^2 + 20*x^3 + x^4))\"\n  unfolding ln_lower_9_def ln_upper_9_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection {*Upper Bound 11*}\n\ntext{*Extended bounds start here*}\n\ndefinition ln_upper_11 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_11 x \\<equiv>\n           (5*x^5 + 647*x^4 + 4397*x^3 + 6397*x^2 + 2272*x + 142) * (x - 1) /\n           (30*(6*x^5 + 75*x^4 + 200*x^3 + 150*x^2 + 30*x + 1))\"\n\ndefinition diff_delta_ln_upper_11 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_11 \\<equiv> \\<lambda>x. (x - 1)^11 / ((6*x^5 + 75*x^4 + 200*x^3 + 150*x^2 + 30*x + 1)^2 * x)\"\n\nlemma d_delta_ln_upper_11: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_11 x - ln x) has_field_derivative diff_delta_ln_upper_11 x) (at x)\"\nunfolding ln_upper_11_def diff_delta_ln_upper_11_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_11_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_11 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_11])\napply (auto simp: diff_delta_ln_upper_11_def ln_upper_11_def)\ndone\n\nlemma ln_upper_11_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_11 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_11])\nusing assms\napply (auto simp: diff_delta_ln_upper_11_def divide_simps ln_upper_11_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_11: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_11 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_11_neg ln_upper_11_pos)\n\ndefinition ln_lower_11 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_11 \\<equiv> \\<lambda>x. - ln_upper_11 (inverse x)\"\n\ncorollary ln_lower_11: \"0<x \\<Longrightarrow> ln_lower_11 x \\<le> ln x\"\n  unfolding ln_lower_11_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_11)\n\ntheorem ln_lower_11_eq: \"0<x \\<Longrightarrow>\n    ln_lower_11 x = (1/30)*(142*x^5 + 2272*x^4 + 6397*x^3 + 4397*x^2 + 647*x + 5)*(x - 1) /\n                    (x*(x^5 + 30*x^4 + 150*x^3 + 200*x^2 + 75*x + 6))\"\n  unfolding ln_lower_11_def ln_upper_11_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection {*Upper Bound 13*}\n\ndefinition ln_upper_13 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_13 x \\<equiv> (353 + 8389*x + 20149*x^4 + 50774*x^3 + 38524*x^2 + 1921*x^5 + 10*x^6) * (x - 1)\n                          / (70*(1 + 42*x + 525*x^4 + 700*x^3 + 315*x^2 + 126*x^5 + 7*x^6))\"\n\ndefinition diff_delta_ln_upper_13 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_13 \\<equiv> \\<lambda>x. (x - 1)^13 /\n                     ((1 + 42*x + 525*x^4 + 700*x^3 + 315*x^2 + 126*x^5 + 7*x^6)^2*x)\"\n\nlemma d_delta_ln_upper_13: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_13 x - ln x) has_field_derivative diff_delta_ln_upper_13 x) (at x)\"\nunfolding ln_upper_13_def diff_delta_ln_upper_13_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_13_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_13 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_13])\napply (auto simp: diff_delta_ln_upper_13_def ln_upper_13_def)\ndone\n\nlemma ln_upper_13_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_13 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_13])\nusing assms\napply (auto simp: diff_delta_ln_upper_13_def divide_simps ln_upper_13_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_13: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_13 x\"\n  by (metis le_less_linear less_eq_real_def ln_upper_13_neg ln_upper_13_pos)\n\ndefinition ln_lower_13 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_13 \\<equiv> \\<lambda>x. - ln_upper_13 (inverse x)\"\n\ncorollary ln_lower_13: \"0<x \\<Longrightarrow> ln_lower_13 x \\<le> ln x\"\n  unfolding ln_lower_13_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_13)\n\ntheorem ln_lower_13_eq: \"0<x \\<Longrightarrow>\n    ln_lower_13 x = (1/70)*(10 + 1921*x + 20149*x^2 + 50774*x^3 + 38524*x^4 + 8389*x^5 + 353*x^6)*(x - 1) /\n                    (x*(7 + 126*x + 525*x^2 + 700*x^3 + 315*x^4 + 42*x^5 + x^6))\"\n  unfolding ln_lower_13_def ln_upper_13_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection {*Upper Bound 15*}\n\ndefinition ln_upper_15 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_15 x \\<equiv>\n           (1487 + 49199*x + 547235*x^4 + 718735*x^3 + 334575*x^2 + 141123*x^5 + 35*x^7 + 9411*x^6)*(x - 1) /\n           (280*(1 + 56*x + 2450*x^4 + 1960*x^3 + 588*x^2 + 1176*x^5 + 8*x^7 + 196*x^6))\"\n\ndefinition diff_delta_ln_upper_15 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_15\n         \\<equiv> \\<lambda>x. (x - 1)^15 / ((1+56*x+2450*x^4+1960*x^3+588*x^2+8*x^7+196*x^6+1176*x^5)^2 * x)\"\n\nlemma d_delta_ln_upper_15: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_15 x - ln x) has_field_derivative diff_delta_ln_upper_15 x) (at x)\"\nunfolding ln_upper_15_def diff_delta_ln_upper_15_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_15_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_15 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_15])\napply (auto simp: diff_delta_ln_upper_15_def ln_upper_15_def)\ndone\n\nlemma ln_upper_15_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_15 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_15])\nusing assms\napply (auto simp: diff_delta_ln_upper_15_def divide_simps ln_upper_15_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_15: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_15 x\"\n  by (metis le_less_linear less_eq_real_def ln_upper_15_neg ln_upper_15_pos)\n\n\ndefinition ln_lower_15 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_15 \\<equiv> \\<lambda>x. - ln_upper_15 (inverse x)\"\n\ncorollary ln_lower_15: \"0<x \\<Longrightarrow> ln_lower_15 x \\<le> ln x\"\n  unfolding ln_lower_15_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_15)\n\ntheorem ln_lower_15_eq: \"0<x \\<Longrightarrow>\n    ln_lower_15 x = (1/280)*(35 + 9411*x + 141123*x^2 + 547235*x^3 + 718735*x^4 + 334575*x^5 + 49199*x^6 + 1487*x^7)*(x - 1) /\n                    (x*(8 + 196*x + 1176*x^2 + 2450*x^3 + 1960*x^4 + 588*x^5 + 56*x^6 + x^7))\"\n  unfolding ln_lower_15_def ln_upper_15_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq\n              divide_simps) algebra\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Special_Function_Bounds/Log_CF_Bounds.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898127684335, "lm_q2_score": 0.8354835411997897, "lm_q1q2_score": 0.7569395770627053}}
{"text": "\nsection \\<open>Operations on sorted lists\\<close>\n\ntheory Sorted_List_Operations2\nimports Sorted_Less2\nbegin \n\ntext\\<open>The definition and the inter\\_sorted\\_correct lemma in this theory are the same as those\n     in Collections \\<^cite>\\<open>\"OpsOnSortedLists-AFP\"\\<close>. \n     except the former is for a descending list while the latter is for an ascending one.\\<close>\n\nfun inter_sorted_rev :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"inter_sorted_rev [] l2 = []\"\n | \"inter_sorted_rev l1 [] = []\"\n | \"inter_sorted_rev (x1 # l1) (x2 # l2) =\n    (if (x1 > x2) then (inter_sorted_rev l1 (x2 # l2)) else \n      (if (x1 = x2) then x1 # (inter_sorted_rev l1 l2) else inter_sorted_rev (x1 # l1) l2))\"\n\nlemma inter_sorted_correct :\n  assumes l1_OK: \"sorted (rev l1)\"\n  assumes l2_OK: \"sorted (rev l2)\"\n    shows \"sorted (rev (inter_sorted_rev l1 l2)) \\<and> set (inter_sorted_rev l1 l2) = set l1 \\<inter> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"sorted (rev l1)\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_gt: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 > x\"\n    by (auto simp add: Ball_def sorted_wrt_append)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)  (* sorted (rev (x2 # l2))*)\n    from x2_l2_props have l2_props: \"sorted (rev l2)\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_gt: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 > x\"\n    by (auto simp  add: Ball_def sorted_wrt_append )\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 > x2\")\n      case True note x1_gt_x2 = this\n      have \"set l1 \\<inter> set (x2 # l2) = set (x1 # l1)\\<inter> set (x2 # l2)\" \n        using x1_gt_x2 x1_nin_l1 x2_nin_l2 x1_gt x2_gt \n        by fastforce\n      then show ?thesis using ind_hyp_l1[OF x2_l2_props]  using x1_gt_x2 x1_nin_l1 x2_nin_l2 x1_gt x2_gt \n        by (auto simp add:Ball_def sorted_wrt_append)\n    next\n      case False note x2_ge_x1 = this      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this        \n        then show ?thesis using ind_hyp_l1[OF l2_props]  \n          using x1_eq_x2  x1_nin_l1 x2_nin_l2 x1_gt x2_gt by (auto simp add:Ball_def sorted_wrt_append)\n      next\n        case False note x1_neq_x2 = this\n        with x2_ge_x1 have x2_gt_x1 : \"x2 > x1\" by auto\n        from ind_hyp_l2 x2_ge_x1 x1_neq_x2 x2_gt x2_nin_l2 x1_gt \n        show ?thesis by auto         \n      qed\n    qed\n  qed\nqed\n\nlemma inter_sorted_rev_refl: \"inter_sorted_rev xs xs = xs\" \n  by (induct xs) auto\n\nlemma  inter_sorted_correct_col: \n  assumes \"sorted (rev xs)\"\n      and \"sorted (rev ys)\"\n    shows \"(inter_sorted_rev xs ys) = rev (sorted_list_of_set (set xs \\<inter> set ys))\"\n  using assms\nproof-\n  from assms have 1: \"sorted (rev (inter_sorted_rev xs ys)) \" \n              and 2: \"set (inter_sorted_rev xs ys) = set xs \\<inter> set ys\" using inter_sorted_correct by auto\n  have \"sorted (rev (rev (sorted_list_of_set (set xs \\<inter> set ys))))\" by ( simp add:sorted_less_sorted_list_of_set)\n  with 1 2 show ?thesis by (auto intro:sorted_less_rev_set_unique)\nqed\n\nlemma cons_set_eq: \"set (x # xs) \\<inter> set xs = set xs\"  \n  by auto\n\nlemma inter_sorted_cons: \"sorted (rev (x # xs)) \\<Longrightarrow> inter_sorted_rev (x # xs) xs = xs\" \nproof-\n  assume ass: \"sorted (rev (x # xs))\" \n  then have sorted_xs: \"sorted (rev xs)\" by (auto simp add:sorted_wrt_append)\n  with ass have \"inter_sorted_rev (x # xs) xs = rev (sorted_list_of_set (set (x # xs) \\<inter> set xs))\" \n    by (simp add:inter_sorted_correct_col)\n  then have \"inter_sorted_rev (x # xs) xs = rev (rev xs)\"using  sorted_xs by (simp only:cons_set_eq sorted_less_rev_set_eq)\n  then show ?thesis using sorted_xs by auto\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Dominance_CHK/Sorted_List_Operations2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223265, "lm_q2_score": 0.8577681049901036, "lm_q1q2_score": 0.7569184894078638}}
{"text": "theory Munkres\n imports \"HOL-Analysis.Analysis\"\nbegin\n\n(*\nproblem_number:13_1\nnatural language statement:\nLet $X$ be a topological space; let $A$ be a subset of $X$. Suppose that for each $x \\in A$ there is an open set $U$ containing $x$ such that $U \\subset A$. Show that $A$ is open in $X$.\nlean statement:\ntheorem exercise_13_1 (X : Type* ) [topological_space X] (A : set X)\n  (h1 : \\<forall> x \\<in> A, \\<exists> U : set X, x \\<in> U \\<and> is_open U \\<and> U \\<subseteq> A) :\n  is_open A :=\nbegin\n  have : A = \\<Union> x, \\<Union> h : x \\<in> A, (classical.some (h1 x h)),\n  { ext x, simp, split,\n  { intro xA,\n  use [x, xA],\n  exact (classical.some_spec (h1 x xA)).1},\n  { rintros \\<langle>y, yA, yspec\\<rangle>,\n  have h := classical.some_spec (h1 y yA),\n  exact h.2.2 yspec }, },\n  rw this,\n  apply is_open_Union,\n  intro x,\n  apply is_open_Union,\n  intro xA,\n  have h := classical.some_spec (h1 x xA),\n  exact h.2.1\nend\n\ncodex statement:\ntheorem subset_of_open_subset_is_open:\n  fixes T::\"'a topology\" and A::\"'a set\"\n  assumes \"A \\<subseteq> topspace T\" \"\\<forall>x\\<in>A. \\<exists> U \\<subseteq> topspace T. openin T U \\<and> x\\<in>U \\<and> U \\<subseteq> A\"\n  shows \"openin T A\"\nOur comment on the codex statement: very good!\n *)\ntheorem exercise_13_1:  (*FIRST ASSUMPTION NOT NECESSARY*)\n  fixes T::\"'a topology\" and A::\"'a set\"\n  assumes \"A \\<subseteq> topspace T\" \"\\<forall>x\\<in>A. \\<exists>U. openin T U \\<and> x\\<in>U \\<and> U \\<subseteq> A\"\n  shows \"openin T A\"\n  using assms(2) openin_subopen by fastforce\n\n\n(*\nproblem_number:13_5a\nnatural language statement:\nShow that if $\\mathcal{A}$ is a basis for a topology on $X$, then the topology generated by $\\mathcal{A}$ equals the intersection of all topologies on $X$ that contain $\\mathcal{A}$.\nlean statement:\ntheorem exercise_13_5a {X : Type*}\n  [topological_space X] (A : set (set X)) (hA : is_topological_basis A) :\n  generate_from A = generate_from (sInter {T | is_topology X T \\<and> A \\<subseteq> T}) :=\n\ncodex statement:\ntheorem topology_generated_by_basis_eq_intersection_of_topologies_containing_basis:\n  fixes X::\"'a set\" and A::\"'a set set\"\n  assumes \"topological_basis A\"\n  shows \"topology_generated_by A = \\<Inter>T. topological_space T \\<and> A \\<subseteq> sets T\"\nOur comment on the codex statement: \"basis of a topology\" is not directly available\n *)\n\ntheorem exercise_13_5a: undefined oops\n\n(*\nproblem_number:13_5b\nnatural language statement:\nShow that if $\\mathcal{A}$ is a subbasis for a topology on $X$, then the topology generated by $\\mathcal{A}$ equals the intersection of all topologies on $X$ that contain $\\mathcal{A}$.\nlean statement:\ntheorem exercise_13_5b {X : Type*}\n  [t : topological_space X] (A : set (set X)) (hA : t = generate_from A) :\n  generate_from A = generate_from (sInter {T | is_topology X T \\<and> A \\<subseteq> T}) :=\n\ncodex statement:\ntheorem topology_generated_by_subbasis_eq_intersection_of_topologies_containing_subbasis:\n  fixes X::\"'a set\" and A::\"'a set set\"\n  assumes \"subbasis A X\"\n  shows \"topology_generated_by A = \\<Inter>T. topology T \\<and> A \\<subseteq> T\"\nOur comment on the codex statement:  mostly wrong. This was very tricky to get right, and I proved it to check\n *)\ntheorem exercise_13_5b: (*\"subbasis of a topology\" is not directly available*)\n  shows \"topology_generated_by \\<A> = topology(\\<lambda>S. \\<forall>T \\<in> {T::'a topology. \\<A> \\<subseteq> {S. openin T S}}. openin T S)\"\nproof -\n  have istop: \"istopology (\\<lambda>S. \\<forall>T. \\<A> \\<subseteq> Collect (openin T) \\<longrightarrow> openin T S)\"\n    by (simp add: istopology_def openin_Int openin_Union)\n  show ?thesis\n  apply (simp add: topology_eq openin_topology_generated_by_iff topology_inverse' [OF istop])\n    by (metis Ball_Collect Basis generate_topology_on_coarsest istopology_generate_topology_on istopology_openin topology_inverse')\nqed\n\n\n(*\nproblem_number:16_1\nnatural language statement:\nShow that if $Y$ is a subspace of $X$, and $A$ is a subset of $Y$, then the topology $A$ inherits as a subspace of $Y$ is the same as the topology it inherits as a subspace of $X$.\nlean statement:\ntheorem exercise_16_1 {X : Type*} [topological_space X]\n  (Y : set X)\n  (A : set Y)\n  :\n  \\<forall> U : set A, is_open U \\<longleftrightarrow> is_open (subtype.val '' U) :=\n\ncodex statement:\ntheorem subspace_topology_of_subspace_eq_subspace_topology_of_superspace:\n  fixes X::\"'a::topological_space set\" and Y::\"'a::topological_space set\" and A::\"'a::topological_space set\"\n  assumes \"subspace Y\" \"A \\<subseteq> Y\"\n  shows \"subtopology (subspace_topology Y A) (subspace_topology X A)\"\nOur comment on the codex statement: Wrong and in particular it keeps wanting to use the typeclass-based versions\n *)\ntheorem exercise_16_1: \n  assumes \"Y = subtopology X S\" \"A \\<subseteq> topspace Y\"\n  shows \"subtopology X A = subtopology Y A\"\n  by (metis assms inf.absorb2 le_inf_iff subtopology_subtopology topspace_subtopology)\n\n\n(*\nproblem_number:16_4\nnatural language statement:\nA map $f: X \\rightarrow Y$ is said to be an open map if for every open set $U$ of $X$, the set $f(U)$ is open in $Y$. Show that $\\pi_{1}: X \\times Y \\rightarrow X$ and $\\pi_{2}: X \\times Y \\rightarrow Y$ are open maps.\nlean statement:\ntheorem exercise_16_4 {X Y : Type*} [topological_space X] [topological_space Y]\n  (\\<pi>_1 : X \\<times> Y \\<rightarrow> X)\n  (\\<pi>_2 : X \\<times> Y \\<rightarrow> Y)\n  (h_1 : \\<pi>_1 = prod.fst)\n  (h_2 : \\<pi>_2 = prod.snd) :\n  is_open_map \\<pi>_1 \\<and> is_open_map \\<pi>_2 :=\n\ncodex statement:\ntheorem open_map_of_prod_space:\n  fixes X Y::\"'a::topological_space\"\n  shows \"open_map (prod_topology X Y) (X \\<times> Y) (\\<lambda>x. fst x)\" \"open_map (prod_topology X Y) (X \\<times> Y) (\\<lambda>x. snd x)\"\nOur comment on the codex statement:  partly right. Again used the typeclass version\n *)\ntheorem exercise_16_4: \n    fixes X Y::\"'a topology\"\n  shows \"open_map (prod_topology X Y) X fst\" \"open_map (prod_topology X Y) Y snd\"\n  by (auto simp: open_map_fst open_map_snd)\n\n\n(*\nproblem_number:16_6\nnatural language statement:\nShow that the countable collection \\[\\{(a, b) \\times (c, d) | a < b \\text{ and } c < d, \\text{ and } a, b, c, d \\text{ are rational}\\}\\] is a basis for $\\mathbb{R}^2$.\nlean statement:\ntheorem exercise_16_6\n  (S : set (set (\\<real> \\<times> \\<real>)))\n  (hS : \\<forall> s, s \\<in> S \\<rightarrow> \\<exists> a b c d, (rational a \\<and> rational b \\<and> rational c \\<and> rational d\n  \\<and> s = {x | \\<exists> x_1 x_2, x = (x_1, x_2) \\<and> a < x_1 \\<and> x_1 < b \\<and> c < x_2 \\<and> x_2 < d})) :\n  is_topological_basis S :=\n\ncodex statement:\ntheorem basis_of_rational_interval:\n  fixes a b c d::rat\n  assumes \"a < b\" \"c < d\"\n  shows \"openin (subtopology euclidean_space (UNIV::real^2 set)) ((a, b) \\<times> (c, d))\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_16_6: \n  defines \"\\<B> \\<equiv> { {a<..<b::real} \\<times> {c<..<d::real} | a b c d. a \\<in> \\<rat> \\<and> b \\<in> \\<rat> \\<and> c \\<in> \\<rat> \\<and> d \\<in> \\<rat> \\<and> a<b \\<and> c<d }\"\n  shows \"topology_generated_by \\<B> = euclidean\"\n  oops\n\n\n(*\nproblem_number:16_9\nnatural language statement:\nShow that the dictionary order topology on the set $\\mathbb{R} \\times \\mathbb{R}$ is the same as the product topology $\\mathbb{R}_d \\times \\mathbb{R}$, where $\\mathbb{R}_d$ denotes $\\mathbb{R}$ in the discrete topology.\nlean statement:\n\ncodex statement:\ntheorem dictionary_order_topology_eq_product_topology:\n  shows \"dictionary_order_topology = product_topology (discrete_topology::'a::linorder_topology topology) (discrete_topology::'b::linorder_topology topology)\"\nOur comment on the codex statement:  wrong, but this was difficult\n *)\n\ndefinition\n  \"dictless x y \\<equiv> fst x < fst y \\<or> fst x \\<le> fst y \\<and> snd x < snd y\"\n\ndefinition\n  \"dict_basis \\<equiv> range (\\<lambda>a. {x. dictless x a}) \\<union> range (\\<lambda>a. {x. dictless a x})\"\n\ntheorem exercise_16_9: \n  shows \"topology_generated_by dict_basis = prod_topology (discrete_topology (UNIV::real set)) euclidean\"\n  oops\n\n\n(*\nproblem_number:17_2\nnatural language statement:\nShow that if $A$ is closed in $Y$ and $Y$ is closed in $X$, then $A$ is closed in $X$.\nlean statement:\n\ncodex statement:\ntheorem closed_of_closed_subset:\n  fixes A::\"'a::topological_space set\" and X::\"'b::topological_space set\"\n  assumes \"closed_in (subtopology (top_of_set X) Y) A\" \"closed_in (top_of_set X) Y\"\n  shows \"closed_in (top_of_set X) A\"\nOur comment on the codex statement:  not bad but again the typeclass issue\n *)\ntheorem exercise_17_2: \n  assumes \"closedin (subtopology X Y) A\" \"closedin X Y\"\n  shows \"closedin X A\"\n  using assms closedin_closed_subtopology by blast\n\n\n(*\nproblem_number:17_3\nnatural language statement:\nShow that if $A$ is closed in $X$ and $B$ is closed in $Y$, then $A \\times B$ is closed in $X \\times Y$.\nlean statement:\n\ncodex statement:\ntheorem closed_of_closed_times_closed:\n  fixes A::\"'a::topological_space set\" and B::\"'b::topological_space set\"\n  assumes \"closedin (top_of_set (UNIV::'a set)) A\" \"closedin (top_of_set (UNIV::'b set)) B\"\n  shows \"closedin (top_of_set (UNIV::('a\\<times>'b) set)) (A\\<times>B)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_17_3: \n  assumes \"closedin X A\" \"closedin Y B\"\n  shows \"closedin (prod_topology X Y) (A\\<times>B)\"\n  by (simp add: assms closedin_prod_Times_iff)\n\n\n\n(*\nproblem_number:17_4\nnatural language statement:\nShow that if $U$ is open in $X$ and $A$ is closed in $X$, then $U-A$ is open in $X$, and $A-U$ is closed in $X$.\nlean statement:\ntheorem exercise_17_4 {X : Type*} [topological_space X]\n  (U A : set X) (hU : is_open U) (hA : is_closed A) :\n  is_open (U \\ A) \\<and> is_closed (A \\ U) :=\n\ncodex statement:\ntheorem open_of_open_diff_closed:\n  fixes U A::\"'a::topological_space set\"\n  assumes \"open U\" \"closed A\"\n  shows \"open (U - A)\"\nOur comment on the codex statement: Not bad but it is the type class version\n *)\ntheorem exercise_17_4: \n  assumes \"openin X U\" \"closedin X A\"\n  shows \"openin X (U - A) \\<and> closedin X (A - U)\"\n  by (simp add: assms closedin_diff openin_diff)\n\n\n(*\nproblem_number:18_8a\nnatural language statement:\nLet $Y$ be an ordered set in the order topology. Let $f, g: X \\rightarrow Y$ be continuous. Show that the set $\\{x \\mid f(x) \\leq g(x)\\}$ is closed in $X$.\nlean statement:\ntheorem exercise_18_8a {X Y : Type*} [topological_space X] [topological_space Y]\n  [linear_order Y] [order_topology Y] {f g : X \\<rightarrow> Y}\n  (hf : continuous f) (hg : continuous g) :\n  is_closed {x | f x \\<le> g x} :=\n\ncodex statement:\ntheorem closed_of_continuous_leq:\n  fixes f g::\"'a::topological_space \\<Rightarrow> 'b::order_topology\"\n  assumes \"continuous_on UNIV f\" \"continuous_on UNIV g\"\n  shows \"closed {x. f x \\<le> g x}\"\nOur comment on the codex statement:  perfect except it is for type classes\n *)\n\ndefinition \"order_topology \\<equiv> topology_generated_by (range (\\<lambda>a. {..<a}) \\<union> range (\\<lambda>a::'a::linorder. {a<..}))\" \n\ntheorem exercise_18_8a: \n  fixes A :: \"'a::linorder set\"\n  defines \"X \\<equiv> order_topology\"\n  defines \"Y \\<equiv> subtopology X A\"\n  assumes \"continuous_map X Y f\" \"continuous_map X Y g\"\n  shows \"closedin Y {x. f x \\<le> g x}\"\n  oops\n\ntheorem closed_of_continuous_leq:\n  fixes f g::\"'a::topological_space \\<Rightarrow> 'b::order_topology\"\n  assumes \"continuous_on UNIV f\" \"continuous_on UNIV g\"\n  shows \"closed {x. f x \\<le> g x}\"\n  oops\n\n(*\nproblem_number:18_8b\nnatural language statement:\nLet $Y$ be an ordered set in the order topology. Let $f, g: X \\rightarrow Y$ be continuous. Let $h: X \\rightarrow Y$ be the function $h(x)=\\min \\{f(x), g(x)\\}.$ Show that $h$ is continuous.\nlean statement:\ntheorem exercise_18_8b {X Y : Type*} [topological_space X] [topological_space Y]\n  [linear_order Y] [order_topology Y] {f g : X \\<rightarrow> Y}\n  (hf : continuous f) (hg : continuous g) :\n  continuous (\\<lambda> x, min (f x) (g x)) :=\n\ncodex statement:\ntheorem continuous_of_continuous_min:\n  fixes f g::\"'a::topological_space \\<Rightarrow> 'b::order_topology\"\n  assumes \"continuous_on UNIV f\" \"continuous_on UNIV g\"\n  shows \"continuous_on UNIV (\\<lambda>x. min (f x) (g x))\"\nOur comment on the codex statement: type classes\n *)\ntheorem exercise_18_8b: \n  fixes A :: \"'a::linorder set\"\n  defines \"X \\<equiv> order_topology\"\n  defines \"Y \\<equiv> subtopology X A\"\n  assumes \"continuous_map X Y f\" \"continuous_map X Y g\"\n  defines \"h \\<equiv> \\<lambda>x. min (f x) (g x)\"\n  shows \"continuous_map X Y h\"\n  oops\n\n\n\n(*\nproblem_number:18_13\nnatural language statement:\nLet $A \\subset X$; let $f: A \\rightarrow Y$ be continuous; let $Y$ be Hausdorff. Show that if $f$ may be extended to a continuous function $g: \\bar{A} \\rightarrow Y$, then $g$ is uniquely determined by $f$.\nlean statement:\ntheorem exercise_18_13\n  {X : Type*} [topological_space X] {Y : Type*} [topological_space Y]\n  [t2_space Y] {A : set X} {f : A \\<rightarrow> Y} (hf : continuous f)\n  (g : closure A \\<rightarrow> Y)\n  (g_con : continuous g) :\n  \\<forall> (g' : closure A \\<rightarrow> Y), continuous g' \\<rightarrow>  (\\<forall> (x : closure A), g x = g' x) :=\n\ncodex statement:\ntheorem unique_continuous_extension_of_continuous_on_closure:\n  fixes f::\"'a::t1_space \\<Rightarrow> 'b::t2_space\" and g::\"'a::t1_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"continuous_on A f\" \"continuous_on (closure A) g\" \"g|`A = f\"\n  shows \"g = f\"\nOur comment on the codex statement:  it went wrong and it is the type class version\n *)\ntheorem exercise_18_13: \n  fixes A :: \"'a set\" and X :: \"'a topology\"\n  defines \"A' \\<equiv> subtopology X (X closure_of A)\"\n  assumes \"A \\<subseteq> topspace X\" \"Hausdorff_space Y\" \"continuous_map (subtopology X A) Y f\"\n    and \"continuous_map A' Y g1\" \"restrict g1 A = f\"\n    and \"continuous_map A' Y g2\" \"restrict g2 A = f\"\n  shows \"g1 = g2\"\n  oops\n\n\n(*\nproblem_number:19_4\nnatural language statement:\nShow that $(X_1 \\times  \\cdots \\times X_{n-1}) \\times X_n$ is homeomorphic with $X_1 \\times  \\cdots \\times X_n$.\nlean statement:\n\ncodex statement:\ntheorem homeomorphic_of_prod_prod_prod:\n  fixes X::\"'a::topological_space set\" and Y::\"'b::topological_space set\" and Z::\"'c::topological_space set\"\n  assumes \"topological_space X\" \"topological_space Y\" \"topological_space Z\"\n  shows \"X \\<times> Y \\<times> Z \\<cong> (X \\<times> Y) \\<times> Z\"\nOur comment on the codex statement:  kind of model with kind of muddled with the type class setup\n *)\ntheorem exercise_19_4:  (*only for n=3: trickery is needed to express the general case, \n                          cf DirProd_list in Algebra/Weak_Morphisms*)\n  shows \"prod_topology (prod_topology X1 X2) X3 homeomorphic_space prod_topology X1 (prod_topology X2 X3)\"\n  oops\n\n(*\nproblem_number:19_6a\nnatural language statement:\nLet $\\mathbf{x}_1, \\mathbf{x}_2, \\ldots$ be a sequence of the points of the product space $\\prod X_\\alpha$.  Show that this sequence converges to the point $\\mathbf{x}$ if and only if the sequence $\\pi_\\alpha(\\mathbf{x}_i)$ converges to $\\pi_\\alpha(\\mathbf{x})$ for each $\\alpha$.\nlean statement:\ntheorem exercise_19_6a\n  {n : \\<nat>}\n  {f : fin n \\<rightarrow> Type*} {x : \\<nat> \\<rightarrow> \\<pi>a, f a}\n  (y : \\<pi>i, f i)\n  [\\<pi>a, topological_space (f a)] :\n  tendsto x at_top (\\<N> y) \\<longleftrightarrow> \\<forall> i, tendsto (\\<lambda> j, (x j) i) at_top (\\<N> (y i)) :=\n\ncodex statement:\ntheorem convergent_of_prod_convergent:\n  fixes X::\"('a::metric_space) set\" and f::\"nat \\<Rightarrow> 'a\"\n  assumes \"\\<forall>n. f n \\<in> X\" \"\\<forall>n. (\\<forall>x\\<in>X. (f n x) = (f (n+1) x)) \\<longrightarrow> (f n = f (n+1))\"\n  shows \"convergent f\"\nOur comment on the codex statement: just no.\n *)\ntheorem exercise_19_6a: \n  \"limitin (product_topology X I) x a sequentially  \\<longleftrightarrow> (\\<forall>i\\<in>I. limitin (X i) (x i) (a i) sequentially)\"\n  oops\n\n\n(*\nproblem_number:19_9\nnatural language statement:\nShow that the choice axiom is equivalent to the statement that for any indexed family of nonempty sets, $\\{A_\\alpha\\}_{\\alpha \\in J}$ with $J \\neq 0$, the cartesian product \\[\\prod_{\\alpha \\in J} A_\\alpha\\] is not empty.\nlean statement:\n\ncodex statement:\ntheorem choice_iff_cartesian_product_not_empty:\n  fixes J::\"'a set\" and A::\"'a \\<Rightarrow> 'b set\"\n  assumes \"J \\<noteq> \\<emptyset>\"\n  shows \"\\<exists>f. \\<forall>x\\<in>J. f x \\<in> A x \\<Longleftrightarrow> (\\<exists>f. \\<forall>x\\<in>J. f x \\<in> A x)\"\nOur comment on the codex statement: not really\n *)\ntheorem exercise_19_9: (* not expressible in full because AC is included in Isabelle/HOL*)\n  assumes \"J \\<noteq> {}\" \"\\<And>j. j \\<in> J \\<Longrightarrow> A j \\<noteq> {}\"\n  shows \"Pi J A \\<noteq> {}\"\n  by (simp add: assms(2))\n\n\n(*\nproblem_number:20_2\nnatural language statement:\nShow that $\\mathbb{R} \\times \\mathbb{R}$ in the dictionary order topology is metrizable.\nlean statement:\ntheorem exercise_20_2\n  [topological_space (\\<real> \\<times>ₗ \\<real>)] [order_topology (\\<real> \\<times>ₗ \\<real>)]\n  : metrizable_space (\\<real> \\<times>ₗ \\<real>) :=\n\ncodex statement:\ntheorem metrizable_of_dictionary_order_topology:\n  fixes X::\"real set\"\n  assumes \"X = UNIV\"\n  shows \"metrizable_space (order_topology (dictionary_order X))\"\nOur comment on the codex statement:  it kind of assumes we have everything\n *)\ntheorem exercise_20_2: undefined oops\n  (*\n  shows \"topology_generated_by dict_basis = XXX\"\n NOT POSSIBLE until we get an abstract formalisation of metric spaces*)\n\n\n(*\nproblem_number:20_5\nnatural language statement:\nLet $\\mathbb{R}^\\infty$ be the subset of $\\mathbb{R}^\\omega$ consisting of all sequences that are eventually zero.  What is the closure of $\\mathbb{R}^\\infty$ in $\\mathbb{R}^\\omega$ in the uniform topology? Justify your answer.\nlean statement:\n\ncodex statement:\ntheorem closure_of_eventually_zero_seq_is_all_seq:\n  fixes f::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"\\<forall>n. \\<exists>m. \\<forall>k. m \\<le> k \\<longrightarrow> f k = 0\"\n  shows \"closure {f. \\<forall>n. \\<exists>m. \\<forall>k. m \\<le> k \\<longrightarrow> f k = 0} = UNIV\"\nOur comment on the codex statement:  nonsense\n *)\ntheorem exercise_20_5: undefined oops (* this is a \"WHAT-IS\" exercise with no actual theorem statement*)\n\n\n(*\nproblem_number:21_6a\nnatural language statement:\nDefine $f_{n}:[0,1] \\rightarrow \\mathbb{R}$ by the equation $f_{n}(x)=x^{n}$. Show that the sequence $\\left(f_{n}(x)\\right)$ converges for each $x \\in[0,1]$.\nlean statement:\ntheorem exercise_21_6a\n  (f : \\<nat> \\<rightarrow> I \\<rightarrow> \\<real> )\n  (h : \\<forall> x n, f n x = x ^ n) :\n  \\<forall> x, \\<exists> y, tendsto (\\<lambda> n, f n x) at_top (\\<N> y) :=\n\ncodex statement:\ntheorem converges_of_power_seq:\n  fixes x::real\n  assumes \"0 \\<le> x \\<and> x \\<le> 1\"\n  shows \"convergent (\\<lambda>n. x^n)\"\nOur comment on the codex statement:  perfect!\n *)                                              \ntheorem exercise_21_6a: \n  fixes x::real\n  assumes \"0 \\<le> x \\<and> x \\<le> 1\"\n  shows \"convergent (\\<lambda>n. x^n)\"\n  using assms convergent_realpow by presburger\n\n\n(*\nproblem_number:21_6b\nnatural language statement:\nDefine $f_{n}:[0,1] \\rightarrow \\mathbb{R}$ by the equation $f_{n}(x)=x^{n}$. Show that the sequence $\\left(f_{n}\\right)$ does not converge uniformly.\nlean statement:\ntheorem exercise_21_6b\n  (f : \\<nat> \\<rightarrow> I \\<rightarrow> \\<real> )\n  (h : \\<forall> x n, f n x = x ^ n) :\n  \\<not> \\<exists> f₀, tendsto_uniformly f f₀ at_top :=\n\ncodex statement:\ntheorem not_uniformly_convergent_of_power_function:\n  fixes n::nat\n  shows \"\\<forall>\\<epsilon>>0. \\<exists>x. \\<forall>n. dist (x^n) (x^(n+1)) > \\<epsilon>\"\nOur comment on the codex statement:  Interesting\n *)\ntheorem exercise_21_6b: \n  shows \"\\<not> uniformly_convergent_on {0..1} (\\<lambda>x n. x^n)\" \n  oops\n\n\n(*\nproblem_number:21_8\nnatural language statement:\nLet $X$ be a topological space and let $Y$ be a metric space. Let $f_{n}: X \\rightarrow Y$ be a sequence of continuous functions. Let $x_{n}$ be a sequence of points of $X$ converging to $x$. Show that if the sequence $\\left(f_{n}\\right)$ converges uniformly to $f$, then $\\left(f_{n}\\left(x_{n}\\right)\\right)$ converges to $f(x)$.\nlean statement:\ntheorem exercise_21_8\n  {X : Type*} [topological_space X] {Y : Type*} [metric_space Y]\n  {f : \\<nat> \\<rightarrow> X \\<rightarrow> Y} {x : \\<nat> \\<rightarrow> X}\n  (hf : \\<forall> n, continuous (f n))\n  (x₀ : X)\n  (hx : tendsto x at_top (\\<N> x₀))\n  (f₀ : X \\<rightarrow> Y)\n  (hh : tendsto_uniformly f f₀ at_top) :\n  tendsto (\\<lambda> n, f n (x n)) at_top (\\<N> (f₀ x₀)) :=\n\ncodex statement:\ntheorem converges_of_uniformly_converges_and_converges:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::metric_space\" and X::\"'a set\" and Y::\"'b set\"\n  assumes \"compact X\" \"continuous_on X f\" \"uniformly_convergent_on X (f \\<circ> g)\" \"convergent g\"\n  shows \"convergent (f \\<circ> g)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_21_8: undefined oops\n(*NOT POSSIBLE until we get an abstract formalisation of metric spaces*)\n\n(*\nproblem_number:22_2a\nnatural language statement:\nLet $p: X \\rightarrow Y$ be a continuous map. Show that if there is a continuous map $f: Y \\rightarrow X$ such that $p \\circ f$ equals the identity map of $Y$, then $p$ is a quotient map.\nlean statement:\ntheorem exercise_22_2a {X Y : Type*} [topological_space X]\n  [topological_space Y] (p : X \\<rightarrow> Y) (h : continuous p) :\n  quotient_map p \\<longleftrightarrow> \\<exists> (f : Y \\<rightarrow> X), continuous f \\<and> p \\<circ> f = id :=\n\ncodex statement:\ntheorem quotient_map_of_continuous_map_and_continuous_map_comp_id:\n  fixes p::\"'a::topological_space \\<Rightarrow> 'b::topological_space\" and f::\"'b::topological_space \\<Rightarrow> 'a::topological_space\"\n  assumes \"continuous_on UNIV p\" \"continuous_on UNIV f\" \"\\<forall>x. p (f x) = x\"\n  shows \"quotient_map p\"\nOur comment on the codex statement:  it is the type class version and it is scrambled\n *)\ntheorem exercise_22_2a: \n  assumes \"continuous_map X Y p\"  \"continuous_map Y X f\" \n    and \"\\<And>y. y \\<in> topspace Y \\<Longrightarrow> p (f y) = y\"\n  shows \"quotient_map X Y p\"\n  by (smt (verit) assms comp_apply continuous_map_compose continuous_open_imp_quotient_map \n      homeomorphic_eq_everything_map homeomorphic_map_involution quotient_map_from_composition)\n\n(*\nproblem_number:22_2b\nnatural language statement:\nIf $A \\subset X$, a retraction of $X$ onto $A$ is a continuous map $r: X \\rightarrow A$ such that $r(a)=a$ for each $a \\in A$. Show that a retraction is a quotient map.\nlean statement:\ntheorem exercise_22_2b {X : Type*} [topological_space X]\n  {A : set X} (r : X \\<rightarrow> A) (hr : continuous r) (h : \\<forall> x : A, r x = x) :\n  quotient_map r :=\n\ncodex statement:\ntheorem retraction_is_quotient_map:\n  fixes X::\"'a::topological_space topology\" and A::\"'a set\" and r::\"'a \\<Rightarrow> 'a\"\n  assumes \"continuous_on (carrier X) r\" \"r ` (carrier X) \\<subseteq> A\" \"\\<forall>x\\<in>A. r x = x\"\n  shows \"quotient_map X (subtopology X A) r\"\nOur comment on the codex statement:  partly right\n *)\ntheorem exercise_22_2b: \n  assumes \"A \\<subseteq> topspace X\" \"continuous_map X (subtopology X A) r\"   \n    and \"\\<And>x. x \\<in> A \\<Longrightarrow> r x = x\"\n  shows \"quotient_map X (subtopology X A) r\"\n  by (metis assms continuous_map_from_subtopology continuous_map_into_fulltopology exercise_22_2a topspace_subtopology_subset)\n\n\n(*\nproblem_number:22_5\nnatural language statement:\nLet $p \\colon X \\rightarrow Y$ be an open map. Show that if $A$ is open in $X$, then the map $q \\colon A \\rightarrow p(A)$ obtained by restricting $p$ is an open map.\nlean statement:\ntheorem exercise_22_5 {X Y : Type*} [topological_space X]\n  [topological_space Y] (p : X \\<rightarrow> Y) (hp : is_open_map p)\n  (A : set X) (hA : is_open A) : is_open_map (p \\<circ> subtype.val : A \\<rightarrow> Y) :=\n\ncodex statement:\ntheorem open_map_of_open_subset:\n  fixes p::\"'a::topological_space \\<Rightarrow> 'b::topological_space\"\n  assumes \"open_map p\" \"openin (top_of_set (UNIV::'a set)) A\"\n  shows \"open_map (p|A)\"\nOur comment on the codex statement:  type class primitives, and scrambled\n *)\ntheorem exercise_22_5: \n  assumes \"open_map X Y p\" \"openin X A\"\n  shows \"open_map (subtopology X A) (subtopology Y (p ` A)) (restrict p A)\"\n  oops\n\n\n(*\nproblem_number:23_2\nnatural language statement:\nLet $\\left\\{A_{n}\\right\\}$ be a sequence of connected subspaces of $X$, such that $A_{n} \\cap A_{n+1} \\neq \\varnothing$ for all $n$. Show that $\\bigcup A_{n}$ is connected.\nlean statement:\ntheorem exercise_23_2 {X : Type*}\n  [topological_space X] {A : \\<nat> \\<rightarrow> set X} (hA : \\<forall> n, is_connected (A n))\n  (hAn : \\<forall> n, A n \\<inter> A (n + 1) \\<noteq> \\<emptyset>) :\n  is_connected (\\<Union> n, A n) :=\n\ncodex statement:\ntheorem connected_of_connected_inter_nonempty:\n  fixes X::\"'a::topological_space set\" and A::\"nat \\<Rightarrow> 'a set\"\n  assumes \"\\<forall>n. connected (A n)\" \"\\<forall>n. A n \\<inter> A (n+1) \\<noteq> {}\"\n  shows \"connected (\\<Union>i. A i)\"\nOur comment on the codex statement:  very good but uses type classes\n *)\ntheorem exercise_23_2:\n  assumes \"\\<And>n. connectedin X (A n)\" \"\\<And>n. A n \\<inter> A (Suc n) \\<noteq> {}\"\n  shows \"connectedin X (\\<Union>i. A i)\"\n  oops\n\n\n(*\nproblem_number:23_3\nnatural language statement:\nLet $\\left\\{A_{\\alpha}\\right\\}$ be a collection of connected subspaces of $X$; let $A$ be a connectea eubsen of $X$ Show that if $A \\cap A_{\\alpha} \\neq \\varnothing$ for all $\\alpha$, then $A \\cup\\left(\\bigcup A_{\\alpha}\\right)$ is connected.\nlean statement:\ntheorem exercise_23_3 {X : Type*} [topological_space X]\n  [topological_space X] {A : \\<nat> \\<rightarrow> set X}\n  (hAn : \\<forall> n, is_connected (A n))\n  (A₀ : set X)\n  (hA : is_connected A₀)\n  (h : \\<forall> n, A₀ \\<inter> A n \\<noteq> \\<emptyset>) :\n  is_connected (A₀ \\<union> (\\<Union> n, A n)) :=\n\ncodex statement:\ntheorem connected_of_connected_inter_nonempty:\n  fixes X::\"'a::topological_space set\" and A::\"'a set\" and A\\<alpha>::\"'a set\"\n  assumes \"\\<forall>\\<alpha>. connected (A\\<alpha> \\<alpha>)\" \"connected A\" \"\\<forall>\\<alpha>. A \\<inter> A\\<alpha> \\<alpha> \\<noteq> {}\"\n  shows \"connected (A \\<union> (\\<Union>\\<alpha>. A\\<alpha> \\<alpha>))\"\nOur comment on the codex statement: very good but uses type classes\n *)\ntheorem exercise_23_3: \n  assumes \"\\<And>\\<alpha>. connectedin X (\\<A> \\<alpha>)\" \"\\<And>n. \\<A> n \\<inter> \\<A> (Suc n) \\<noteq> {}\"\n          \"A \\<subseteq> topspace X\" \"connectedin X A\"\n  shows \"connectedin X (A \\<union> (\\<Union>i. \\<A> i))\"\n  oops\n\n\n(*\nproblem_number:23_4\nnatural language statement:\nShow that if $X$ is an infinite set, it is connected in the finite complement topology.\nlean statement:\ntheorem exercise_23_4 {X : Type*} [topological_space X] [cofinite_topology X]\n  (s : set X) : set.infinite s \\<rightarrow> is_connected s :=\n\ncodex statement:\ntheorem connected_of_infinite_set:\n  fixes X::\"'a set\"\n  assumes \"infinite X\"\n  shows \"connected_space (subtopology (discrete_topology X) X)\"\nOur comment on the codex statement: not about discrete topology; uses type classes\n *)\ntheorem exercise_23_4: \n  assumes \"infinite A\"\n  shows \"connectedin (topology (\\<lambda>U. finite (-U))) A\"\n  oops\n\n\n(*\nproblem_number:23_6\nnatural language statement:\nLet $A \\subset X$. Show that if $C$ is a connected subspace of $X$ that intersects both $A$ and $X-A$, then $C$ intersects $\\operatorname{Bd} A$.\nlean statement:\ntheorem exercise_23_6 {X : Type*}\n  [topological_space X] {A C : set X} (hc : is_connected C)\n  (hCA : C \\<inter> A \\<noteq> \\<emptyset>) (hCXA : C \\<inter> Aᶜ \\<noteq> \\<emptyset>) :\n  C \\<inter> (frontier A) \\<noteq> \\<emptyset> :=\n\ncodex statement:\ntheorem connected_intersect_of_subset_intersect_diff_subset_intersect_boundary:\n  fixes A::\"'a::topological_space set\" and C::\"'a set\"\n  assumes \"connected C\" \"C \\<inter> A \\<noteq> {}\" \"C \\<inter> (UNIV - A) \\<noteq> {}\"\n  shows \"C \\<inter> (boundary A) \\<noteq> {}\"\nOur comment on the codex statement: very good but uses type classes; it's frontier not boundary\n *)\ntheorem exercise_23_6: \n  assumes \"connectedin X C\" \"C \\<inter> A \\<noteq> {}\" \"C \\<inter> (-A) \\<noteq> {}\"\n  shows \"C \\<inter> (frontier A) \\<noteq> {}\"  \n  oops\n\n\n(*\nproblem_number:23_9\nnatural language statement:\nLet $A$ be a proper subset of $X$, and let $B$ be a proper subset of $Y$. If $X$ and $Y$ are connected, show that $(X \\times Y)-(A \\times B)$ is connected.\nlean statement:\ntheorem exercise_23_9 {X Y : Type*}\n  [topological_space X] [topological_space Y]\n  (A_1 A_2 : set X)\n  (B_1 B_2 : set Y)\n  (hA : A_1 \\<subset> A_2)\n  (hB : B_1 \\<subset> B_2)\n  (hA : is_connected A_2)\n  (hB : is_connected B_2) :\n  is_connected ({x | \\<exists> a b, x = (a, b) \\<and> a \\<in> A_2 \\<and> b \\<in> B_2} \\\n      {x | \\<exists> a b, x = (a, b) \\<and> a \\<in> A_1 \\<and> b \\<in> B_1}) :=\n\ncodex statement:\ntheorem connected_of_connected_times_connected_minus_proper_subset:\n  fixes X Y::\"'a::topological_space set\"\n  assumes \"connected X\" \"connected Y\" \"A \\<subset> X\" \"B \\<subset> Y\"\n  shows \"connected ((X \\<inter> Y) - (A \\<inter> B))\"\nOur comment on the codex statement:  where did those intersections come from?\n *)\ntheorem exercise_23_9: \n  assumes \"connected_space X\" \"connected_space Y\" \"A \\<subset> topspace X\" \"B \\<subset> topspace Y\"\n  shows \"connectedin (prod_topology X Y) ((topspace X \\<times> topspace Y) - (A \\<times> B))\"\noops\n\n\n(*\nproblem_number:23_11\nnatural language statement:\nLet $p: X \\rightarrow Y$ be a quotient map. Show that if each set $p^{-1}(\\{y\\})$ is connected, and if $Y$ is connected, then $X$ is connected.\nlean statement:\ntheorem exercise_23_11 {X Y : Type*} [topological_space X] [topological_space Y]\n  (p : X \\<rightarrow> Y) (hq : quotient_map p)\n  (hY : connected_space Y) (hX : \\<forall> y : Y, is_connected (p ⁻¹' {y})) :\n  connected_space X :=\n\ncodex statement:\ntheorem connected_of_connected_quotient_map:\n  fixes X::\"'a topology\" and Y::\"'b topology\"\n  assumes \"continuous_map X Y p\" \"\\<forall>y\\<in>Y. connected (p -` {y})\" \"connected Y\"\n  shows \"connected X\"\nOur comment on the codex statement: very good but uses type classes\n *)\ntheorem exercise_23_11: \n  assumes \"quotient_map X Y p\" \"\\<forall>y \\<in> topspace Y. connectedin X (p -` {y})\" \"connected_space Y\"\n  shows \"connected_space X\"\noops\n\n\n(*\nproblem_number:23_12\nnatural language statement:\nLet $Y \\subset X$; let $X$ and $Y$ be connected. Show that if $A$ and $B$ form a separation of $X-Y$, then $Y \\cup A$ and $Y \\cup B$ are connected.\nlean statement:\n\ncodex statement:\ntheorem connected_of_connected_of_separation:\n  fixes X Y::\"'a::topological_space set\"\n  assumes \"connected X\" \"connected Y\" \"Y \\<subseteq> X\" \"separation_set (X - Y) A B\"\n  shows \"connected (Y \\<union> A)\" \"connected (Y \\<union> B)\"\nOur comment on the codex statement: very good but uses type classes\n *)\ntheorem exercise_23_12: \n  assumes \"connected_space X\" \"connectedin X Y\" \n  assumes \"openin X A\" \"A \\<noteq> {}\" \"openin X B\" \"B \\<noteq> {}\" \"A \\<inter> B = {}\" \"A \\<union> B = topspace X - Y\"\n  shows \"connectedin X (Y \\<union> A)\" \"connectedin X (Y \\<union> B)\" \noops\n\n(*\nproblem_number:24_2\nnatural language statement:\nLet $f: S^{1} \\rightarrow \\mathbb{R}$ be a continuous map. Show there exists a point $x$ of $S^{1}$ such that $f(x)=f(-x)$.\nlean statement:\ntheorem exercise_24_2 {f : (metric.sphere 0 1 : set \\<real>) \\<rightarrow> \\<real>}\n  (hf : continuous f) : \\<exists> x, f x = f (-x) :=\n\ncodex statement:\ntheorem exists_eq_of_continuous_map:\n  fixes f::\"complex \\<Rightarrow> real\"\n  assumes \"continuous_on (sphere 1) f\"\n  shows \"\\<exists>x. f x = f (-x)\"\nOur comment on the codex statement: Uses type classes and overlooks that x must lie on the sphere\n *)\ntheorem exercise_24_2: \n  fixes f::\"complex \\<Rightarrow> real\"\n  assumes \"continuous_map (top_of_set (sphere 0 1)) euclidean f\"\n  shows \"\\<exists>x \\<in> sphere 0 1. f x = f (-x)\"\nproof -\n  have \"continuous_on (sphere 0 1) f\"\n    using assms continuous_map_iff_continuous by blast\n  then show ?thesis\n  oops\n\n\n(*\nproblem_number:24_3a\nnatural language statement:\nLet $f \\colon X \\rightarrow X$ be continuous. Show that if $X = [0, 1]$, there is a point $x$ such that $f(x) = x$. (The point $x$ is called a fixed point of $f$.)\nlean statement:\ntheorem exercise_24_3a [topological_space I]\n  (f : I \\<rightarrow> I) (hf : continuous f) :\n  \\<exists> (x : I), f x = x :=\n\ncodex statement:\ntheorem exists_fixed_point_of_continuous_on_closed_interval:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'a\"\n  assumes \"continuous_on {0..1} f\"\n  shows \"\\<exists>x. f x = x\"\nOur comment on the codex statement: very good but uses type classes\n *)\ntheorem exercise_24_3a: \n  fixes f::\"real \\<Rightarrow> real\"\n  defines \"X \\<equiv> top_of_set {0..1}\"\n  assumes \"continuous_map X X f\"\n  shows \"\\<exists>x \\<in> {0..1}. f x = x\"\noops\n\n\n(*\nproblem_number:24_4\nnatural language statement:\nLet $X$ be an ordered set in the order topology. Show that if $X$ is connected, then $X$ is a linear continuum.\nlean statement:\n\ncodex statement:\ntheorem connected_of_linear_continuum:\n  fixes X::\"'a::linorder_topology\"\n  assumes \"connected X\"\n  shows \"linear_continuum X\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_24_4: undefined oops (* NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:24_6\nnatural language statement:\nShow that if $X$ is a well-ordered set, then $X \\times [0, 1)$ in the dictionary order is a linear continuum.\nlean statement:\n\ncodex statement:\ntheorem linear_continuum_of_well_order:\n  fixes X::\"'a::wellorder set\"\n  assumes \"well_order X\"\n  shows \"linear_continuum (X \\<times> {0..<1})\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_24_6: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:25_4\nnatural language statement:\nLet $X$ be locally path connected. Show that every connected open set in $X$ is path connected.\nlean statement:\ntheorem exercise_25_4 {X : Type*} [topological_space X]\n  [loc_path_connected_space X] (U : set X) (hU : is_open U)\n  (hcU : is_connected U) : is_path_connected U :=\n\ncodex statement:\ntheorem connected_open_is_path_connected:\n  fixes X::\"'a::topological_space topology\"\n  assumes \"locally path_connected X\" \"openin X U\" \"connected U\"\n  shows \"path_connected U\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_25_4: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:25_9\nnatural language statement:\nLet $G$ be a topological group; let $C$ be the component of $G$ containing the identity element $e$. Show that $C$ is a normal subgroup of $G$.\nlean statement:\ntheorem exercise_25_9 {G : Type*} [topological_space G] [group G]\n  [topological_group G] (C : set G) (h : C = connected_component 1) :\n  is_normal_subgroup C :=\n\ncodex statement:\ntheorem component_of_topological_group_is_normal:\n  fixes G::\"('a, 'b) topological_group_scheme\"\n  assumes \"topological_group G\"\n  shows \"normal_subgroup (component_of G (\\<one> G)) G\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_25_9: undefined oops (* no idea what this is about*)\n\n\n(*\nproblem_number:26_9\nnatural language statement:\nLet $A$ and $B$ be subspaces of $X$ and $Y$, respectively; let $N$ be an open set in $X \\times Y$ containing $A \\times B$. If $A$ and $B$ are compact, then there exist open sets $U$ and $V$ in $X$ and $Y$, respectively, such that $A \\times B \\subset U \\times V \\subset N .$\nlean statement:\n\ncodex statement:\ntheorem exists_open_subset_of_compact_subset_in_open_set:\n  fixes A B::\"'a::euclidean_space set\" and N::\"'a set \\<times> 'a set\"\n  assumes \"compact A\" \"compact B\" \"open N\" \"A \\<times> B \\<subseteq> N\"\n  shows \"\\<exists>U V. open U \\<and> open V \\<and> A \\<times> B \\<subseteq> U \\<times> V \\<and> U \\<times> V \\<subseteq> N\"\nOur comment on the codex statement: very good but uses type classes\n *)\ntheorem exercise_26_9: \n  assumes \"A \\<subseteq> topspace X\" \"B \\<subseteq> topspace Y\" \"openin (prod_topology X Y) N\" \"A \\<times> B \\<subseteq> N\"\n  assumes \"compact A\" \"compact B\"\n  shows \"\\<exists>U V. openin X U \\<and> openin Y V \\<and> A \\<times> B \\<subseteq> U \\<times> V \\<and> U \\<times> V \\<subseteq> N\"\n  oops\n\n\n(*\nproblem_number:26_11\nnatural language statement:\nLet $X$ be a compact Hausdorff space. Let $\\mathcal{A}$ be a collection of closed connected subsets of $X$ that is simply ordered by proper inclusion. Then $Y=\\bigcap_{A \\in \\mathcal{A}} A$ is connected.\nlean statement:\ntheorem exercise_26_11\n  {X : Type*} [topological_space X] [compact_space X] [t2_space X]\n  (A : set (set X)) (hA : \\<forall> (a b : set X), a \\<in> A \\<rightarrow> b \\<in> A \\<rightarrow> a \\<subseteq> b \\<or> b \\<subseteq> a)\n  (hA' : \\<forall> a \\<in> A, is_closed a) (hA'' : \\<forall> a \\<in> A, is_connected a) :\n  is_connected (\\<Inter>₀ A) :=\n\ncodex statement:\ntheorem connected_of_compact_hausdorff_simply_ordered_closed_connected_subsets:\n  fixes X::\"'a::t2_space set\" and A::\"'a set set\"\n  assumes \"compact X\" \"hausdorff X\" \"\\<forall>A B. A \\<in> A \\<and> B \\<in> A \\<longrightarrow> A \\<subseteq> B \\<or> B \\<subseteq> A\" \"\\<forall>A\\<in>A. closedin (subtopology X UNIV) A \\<and> connected A\"\n  shows \"connected (\\<Inter>A\\<in>A. A)\"\nOur comment on the codex statement: very good but uses type classes\n *)\ntheorem exercise_26_11: \n  assumes \"compact_space X\" \"Hausdorff_space X\" \"\\<Union>\\<A> \\<subseteq> topspace X\"\n    \"\\<forall>A\\<in>\\<A>. closedin X A \\<and> connectedin X A\"\n    \"\\<forall>A\\<in>\\<A>. \\<forall>B\\<in>\\<A>. A \\<subseteq> B \\<or> B \\<subseteq> A\"\n  shows \"connectedin X (\\<Inter>A\\<in>A. A)\"\noops\n\n\n(*\nproblem_number:26_12\nnatural language statement:\nLet $p: X \\rightarrow Y$ be a closed continuous surjective map such that $p^{-1}(\\{y\\})$ is compact, for each $y \\in Y$. (Such a map is called a perfect map.) Show that if $Y$ is compact, then $X$ is compact.\nlean statement:\ntheorem exercise_26_12 {X Y : Type*} [topological_space X] [topological_space Y]\n  (p : X \\<rightarrow> Y) (h : function.surjective p) (hc : continuous p) (hp : \\<forall> y, is_compact (p ⁻¹' {y}))\n  (hY : compact_space Y) : compact_space X :=\n\ncodex statement:\ntheorem compact_of_perfect_map_compact:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::metric_space\"\n  assumes \"compact (UNIV::'b set)\" \"continuous_on UNIV f\" \"surj f\" \"\\<forall>y\\<in>UNIV. compact (f -` {y})\"\n  shows \"compact (UNIV::'a set)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_26_12: \n  assumes \"closed_map X Y p\" \"continuous_map X Y p\" \"p ` topspace X = topspace Y\"\n  assumes \"\\<forall>y \\<in> topspace Y. compactin X (f -` {y})\" \"compact_space Y\" \n  shows \"compact_space X\"\noops\n\n\n(*\nproblem_number:27_1\nnatural language statement:\nProve that if $X$ is an ordered set in which every closed interval is compact, then $X$ has the least upper bound property.\nlean statement:\n\ncodex statement:\ntheorem least_upper_bound_of_compact_closed_interval:\n  fixes X::\"'a::{order_topology, linorder_topology} set\"\n  assumes \"compact {a..b}\"\n  shows \"\\<exists>c. is_lub {a..b} c\"\nOur comment on the codex statement:  many quantification issues\n *)\ntheorem exercise_27_1:  (*this version assumes type classes*)\n  fixes A::\"'a::linorder_topology set\"\n  assumes \"\\<And>a b. a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> compact {a..b}\"\n  assumes \"A' \\<subseteq> A\" \"bdd_above A'\"\n  shows \"\\<exists>x \\<in> A. A' \\<subseteq> {..x}\"\n  oops\n\n\n(*\nproblem_number:27_4\nnatural language statement:\nShow that a connected metric space having more than one point is uncountable.\nlean statement:\ntheorem exercise_27_4\n  {X : Type*} [metric_space X] [connected_space X] (hX : \\<exists> x y : X, x \\<noteq> y) :\n  \\<not> countable (univ : set X) :=\n\ncodex statement:\ntheorem connected_metric_space_of_more_than_one_point_is_uncountable:\n  fixes X::\"'a::metric_space set\"\n  assumes \"connected X\" \"card X > 1\"\n  shows \"uncountable X\"\nOur comment on the codex statement:  perfect, because for this one we have to use type classes ATM\n *)\ntheorem exercise_27_4: (*this version assumes type classes*)\n  fixes X::\"'a::metric_space set\"\n  assumes \"connected X\" \"card X > 1\"\n  shows \"uncountable X\"\n  using assms connected_finite_iff_sing by fastforce\n\n\n(*\nproblem_number:28_4\nnatural language statement:\nA space $X$ is said to be countably compact if every countable open covering of $X$ contains a finite subcollection that covers $X$. Show that for a $T_1$ space $X$, countable compactness is equivalent to limit point compactness.\nlean statement:\ntheorem exercise_28_4 {X : Type*}\n  [topological_space X] (hT1 : t1_space X) :\n  countably_compact X \\<longleftrightarrow> limit_point_compact X :=\n\ncodex statement:\ntheorem countably_compact_of_limit_point_compact:\n  fixes X::\"'a::t1_space topological_space\"\n  assumes \"limit_point_compact X\"\n  shows \"countably_compact X\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_28_4: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:28_5\nnatural language statement:\nShow that X is countably compact if and only if every nested sequence $C_1 \\supset C_2 \\supset \\cdots$ of closed nonempty sets of X has a nonempty intersection.\nlean statement:\ntheorem exercise_28_5\n  (X : Type* ) [topological_space X] :\n  countably_compact X \\<longleftrightarrow> \\<forall> (C : \\<nat> \\<rightarrow> set X), (\\<forall> n, is_closed (C n)) \\<and>\n  (\\<forall> n, C n \\<noteq> \\<emptyset>) \\<and> (\\<forall> n, C n \\<subseteq> C (n + 1)) \\<rightarrow> \\<exists> x, \\<forall> n, x \\<in> C n :=\n\ncodex statement:\ntheorem countably_compact_of_nested_closed_nonempty_has_nonempty_intersection:\n  fixes X::\"'a::t2_space set\"\n  assumes \"\\<forall>n. closed (C n)\" \"\\<forall>n. C n \\<noteq> {}\" \"\\<forall>n. C n \\<subseteq> C (n+1)\"\n  shows \"\\<exists>x. x\\<in>\\<Inter>n. C n\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_28_5: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:28_6\nnatural language statement:\nLet $(X, d)$ be a metric space. If $f: X \\rightarrow X$ satisfies the condition $d(f(x), f(y))=d(x, y)$ for all $x, y \\in X$, then $f$ is called an isometry of $X$. Show that if $f$ is an isometry and $X$ is compact, then $f$ is bijective and hence a homeomorphism.\nlean statement:\ntheorem exercise_28_6 {X : Type*} [metric_space X]\n  [compact_space X] {f : X \\<rightarrow> X} (hf : isometry f) :\n  function.bijective f :=\n\ncodex statement:\ntheorem isometry_of_compact_is_homeomorphism:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'a\"\n  assumes \"compact (UNIV::'a set)\" \"\\<forall>x y. dist (f x) (f y) = dist x y\"\n  shows \"homeomorphism (UNIV::'a set) (UNIV::'a set) f\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_28_6: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:29_1\nnatural language statement:\nShow that the rationals $\\mathbb{Q}$ are not locally compact.\nlean statement:\ntheorem exercise_29_1 : \\<not> locally_compact_space \\<rat> :=\n\ncodex statement:\ntheorem not_locally_compact_of_Q:\n  shows \"\\<forall>x\\<in>UNIV. \\<exists>U. open U \\<and> x\\<in>U \\<and> (\\<forall>V. open V \\<and> x\\<in>V \\<longrightarrow> \\<exists>y\\<in>V. y\\<notin>U)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_29_1: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:29_4\nnatural language statement:\nShow that $[0, 1]^\\omega$ is not locally compact in the uniform topology.\nlean statement:\ntheorem exercise_29_4 [topological_space (\\<nat> \\<rightarrow> I)] :\n  \\<not> locally_compact_space (\\<nat> \\<rightarrow> I) :=\n\ncodex statement:\ntheorem not_locally_compact_of_uniform_topology:\n  fixes X::\"nat \\<Rightarrow> real\"\n  assumes \"\\<forall>n. 0 \\<le> X n \\<and> X n \\<le> 1\"\n  shows \"\\<forall>U. openin (uniform_topology (product_topology real UNIV)) U \\<longrightarrow> \\<exists>V. openin (uniform_topology (product_topology real UNIV)) V \\<and> compact V \\<and> X \\<in> V \\<and> V \\<subseteq> U\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_29_4: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:29_5\nnatural language statement:\nIf $f \\colon X_1 \\rightarrow X_2$ is a homeomorphism of locally compact Hausdorff spaces, show that $f$ extends to a homeomorphism of their one-point compactifications.\nlean statement:\n\ncodex statement:\ntheorem homeomorphism_of_one_point_compactification:\n  fixes f::\"'a::t2_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"homeomorphism X1 X2 f\" \"locally compact X1\" \"locally compact X2\" \"compact_space X1\" \"compact_space X2\"\n  shows \"homeomorphism (one_point_compactification X1) (one_point_compactification X2) (extend_map f)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_29_5: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:29_6\nnatural language statement:\nShow that the one-point compactification of $\\mathbb{R}$ is homeomorphic with the circle $S^1$.\nlean statement:\n\ncodex statement:\ntheorem homeomorphic_of_one_point_compactification_of_real_is_circle:\n  shows \"one_point_compactification \\<real> homeomorphic (sphere (1::real) 0)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_29_6: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:29_10\nnatural language statement:\nShow that if $X$ is a Hausdorff space that is locally compact at the point $x$, then for each neighborhood $U$ of $x$, there is a neighborhood $V$ of $x$ such that $\\bar{V}$ is compact and $\\bar{V} \\subset U$.\nlean statement:\ntheorem exercise_29_10 {X : Type*}\n  [topological_space X] [t2_space X] (x : X)\n  (hx : \\<exists> U : set X, x \\<in> U \\<and> is_open U \\<and> (\\<exists> K : set X, U \\<subset> K \\<and> is_compact K))\n  (U : set X) (hU : is_open U) (hxU : x \\<in> U) :\n  \\<exists> (V : set X), is_open V \\<and> x \\<in> V \\<and> is_compact (closure V) \\<and> closure V \\<subseteq> U :=\n\ncodex statement:\ntheorem exists_compact_subset_of_neighborhood:\n  fixes X::\"'a::metric_space topology\" and x::'a\n  assumes \"x\\<in>topspace X\" \"t1_space X\" \"locally_compact_space X\" \"\\<exists>U. openin X U \\<and> x\\<in>U\"\n  shows \"\\<exists>V. openin X V \\<and> x\\<in>V \\<and> compact (closure V) \\<and> closure V \\<subseteq> U\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_29_10: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:30_10\nnatural language statement:\nShow that if $X$ is a countable product of spaces having countable dense subsets, then $X$ has a countable dense subset.\nlean statement:\ntheorem exercise_30_10\n  {X : \\<nat> \\<rightarrow> Type*} [\\<forall> i, topological_space (X i)]\n  (h : \\<forall> i, \\<exists> (s : set (X i)), countable s \\<and> dense s) :\n  \\<exists> (s : set (\\<pi> i, X i)), countable s \\<and> dense s :=\n\ncodex statement:\ntheorem countable_dense_subset_of_countable_product_of_countable_dense_subset:\n  fixes X::\"'a::{second_countable_topology, t2_space} set\"\n  assumes \"countable X\" \"\\<forall>x\\<in>X. \\<exists>D. countable D \\<and> dense_in (top_of_set X) D\"\n  shows \"\\<exists>D. countable D \\<and> dense_in (top_of_set X) D\"\nOur comment on the codex statement: plausible\n *)\ntheorem exercise_30_10: \n  fixes Y :: \"'a \\<Rightarrow> 'b topology\"\n  assumes \"countable I\" \"\\<forall>i\\<in>I. \\<exists>D. countable D \\<and> D \\<subseteq> topspace (Y i) \\<and> Y i closure_of D = topspace (Y i)\"\n  defines \"X \\<equiv> product_topology Y I\"\n  shows \"\\<exists>D. countable D \\<and> D \\<subseteq> topspace X \\<and> X closure_of D = topspace X\"\noops\n\n\n(*\nproblem_number:30_13\nnatural language statement:\nShow that if $X$ has a countable dense subset, every collection of disjoint open sets in $X$ is countable.\nlean statement:\ntheorem exercise_30_13 {X : Type*} [topological_space X]\n  (h : \\<exists> (s : set X), countable s \\<and> dense s) (U : set (set X))\n  (hU : \\<forall> (x y : set X), x \\<in> U \\<rightarrow> y \\<in> U \\<rightarrow> x \\<noteq> y \\<rightarrow> x \\<inter> y = \\<emptyset>) :\n  countable U :=\n\ncodex statement:\ntheorem countable_of_dense_countable:\n  fixes X::\"'a::metric_space set\"\n  assumes \"countable (UNIV::'a set)\" \"\\<forall>x\\<in>X. \\<exists>U. open U \\<and> x\\<in>U \\<and> U \\<subseteq> X\"\n  shows \"countable X\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_30_13: \n  assumes \"countable D\" \"D \\<subseteq> topspace X\" \"X closure_of D = topspace X\"\n    \"\\<forall>A\\<in>\\<A>. openin X A\" \"disjoint \\<A>\"\n  shows \"countable \\<A>\"\n  oops\n\n\n(*\nproblem_number:31_1\nnatural language statement:\nShow that if $X$ is regular, every pair of points of $X$ have neighborhoods whose closures are disjoint.\nlean statement:\ntheorem exercise_31_1 {X : Type*} [topological_space X]\n  (hX : regular_space X) (x y : X) :\n  \\<exists> (U V : set X), is_open U \\<and> is_open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> closure U \\<inter> closure V = \\<emptyset> :=\n\ncodex statement:\ntheorem regular_implies_disjoint_closure_of_neighborhoods:\n  fixes X::\"'a::t1_space topology\"\n  assumes \"regular_space X\"\n  shows \"\\<forall>x y. x \\<in> topspace X \\<and> y \\<in> topspace X \\<longrightarrow> \\<exists>U V. openin X U \\<and> openin X V \\<and> x\\<in>U \\<and> y\\<in>V \\<and> closure U \\<inter> closure V = {}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_31_1: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:31_2\nnatural language statement:\nShow that if $X$ is normal, every pair of disjoint closed sets have neighborhoods whose closures are disjoint.\nlean statement:\ntheorem exercise_31_2 {X : Type*}\n  [topological_space X] [normal_space X] {A B : set X}\n  (hA : is_closed A) (hB : is_closed B) (hAB : disjoint A B) :\n  \\<exists> (U V : set X), is_open U \\<and> is_open V \\<and> A \\<subseteq> U \\<and> B \\<subseteq> V \\<and> closure U \\<inter> closure V = \\<emptyset> :=\n\ncodex statement:\ntheorem disjoint_closed_sets_have_disjoint_neighborhoods:\n  fixes X::\"'a::t2_space topology\" and A B::\"'a set\"\n  assumes \"normal_space X\" \"closedin X A\" \"closedin X B\" \"A \\<inter> B = {}\"\n  shows \"\\<exists>U V. openin X U \\<and> openin X V \\<and> A \\<subseteq> U \\<and> B \\<subseteq> V \\<and> closure U \\<inter> closure V = {}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_31_2: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:31_3\nnatural language statement:\nShow that every order topology is regular.\nlean statement:\ntheorem exercise_31_3 {\\<alpha> : Type*} [partial_order \\<alpha>]\n  [topological_space \\<alpha>] (h : order_topology \\<alpha>) : regular_space \\<alpha> :=\n\ncodex statement:\ntheorem regular_of_order_topology:\n  fixes T::\"'a::order topology\"\n  shows \"regular_space T\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_31_3: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:32_1\nnatural language statement:\nShow that a closed subspace of a normal space is normal.\nlean statement:\ntheorem exercise_32_1 {X : Type*} [topological_space X]\n  (hX : normal_space X) (A : set X) (hA : is_closed A) :\n  normal_space {x // x \\<in> A} :=\n\ncodex statement:\ntheorem closed_subspace_of_normal_is_normal:\n  fixes X::\"'a::t2_space set\" and Y::\"'b::t2_space set\"\n  assumes \"closed_in (subtopology euclidean X) Y\" \"normal_space X\"\n  shows \"normal_space Y\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_32_1: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:32_2\nnatural language statement:\nShow that if $\\prod X_\\alpha$ is Hausdorff, or regular, or normal, then so is $X_\\alpha$. Assume that each $X_\\alpha$ is nonempty.\nlean statement:\ntheorem exercise_32_2a\n  {\\<iota> : Type*} {X : \\<iota> \\<rightarrow> Type*} [\\<forall> i, topological_space (X i)]\n  (h : \\<forall> i, nonempty (X i)) (h2 : t2_space (\\<pi> i, X i)) :\n  \\<forall> i, t2_space (X i) :=\n\ncodex statement:\ntheorem prod_topology_of_topology_is_topology:\n  fixes \\<alpha>::\"'a\" and X::\"'a \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<forall>\\<alpha>. x \\<in> X \\<alpha>\"\n  shows \"\\<forall>\\<alpha>. openin (prod_topology (\\<alpha>::'a) X) {x} \\<longrightarrow> openin (X \\<alpha>) {x \\<alpha>}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_32_2: \n    fixes X :: \"'a \\<Rightarrow> 'b topology\"\n  assumes \"\\<forall>i\\<in>I. topspace (X i) \\<noteq> {}\" \"Hausdorff_space (product_topology X I)\" \"i \\<in> I\"\n  shows \"Hausdorff_space (X i)\"\noops\n\n\n(*\nproblem_number:32_2\nnatural language statement:\nShow that every locally compact Hausdorff space is regular.\nlean statement:\ntheorem exercise_32_2a\n  {\\<iota> : Type*} {X : \\<iota> \\<rightarrow> Type*} [\\<forall> i, topological_space (X i)]\n  (h : \\<forall> i, nonempty (X i)) (h2 : t2_space (\\<pi> i, X i)) :\n  \\<forall> i, t2_space (X i) :=\n\ncodex statement:\ntheorem regular_of_locally_compact_hausdorff:\n  fixes X::\"'a::metric_space topology\"\n  assumes \"locally_compact_space X\" \"hausdorff_space X\"\n  shows \"regular_space X\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_32_2: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:33_7\nnatural language statement:\nShow that every locally compact Hausdorff space is completely regular.\nlean statement:\ntheorem exercise_33_7 {X : Type*} [topological_space X]\n  (hX : locally_compact_space X) (hX' : t2_space X) :\n  \\<forall> x A, is_closed A \\<and> \\<not> x \\<in> A \\<rightarrow>\n  \\<exists> (f : X \\<rightarrow> I), continuous f \\<and> f x = 1 \\<and> f '' A = {0}\n  :=\n\ncodex statement:\ntheorem locally_compact_hausdorff_is_completely_regular:\n  fixes T::\"'a::metric_space topology\"\n  assumes \"locally_compact T\" \"T_2_space T\"\n  shows \"completely_regular_space T\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_33_7: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:33_8\nnatural language statement:\nLet $X$ be completely regular, let $A$ and $B$ be disjoint closed subsets of $X$. Show that if $A$ is compact, there is a continuous function $f \\colon X \\rightarrow [0, 1]$ such that $f(A) = \\{0\\}$ and $f(B) = \\{1\\}$.\nlean statement:\ntheorem exercise_33_8\n  (X : Type* ) [topological_space X] [regular_space X]\n  (h : \\<forall> x A, is_closed A \\<and> \\<not> x \\<in> A \\<rightarrow>\n  \\<exists> (f : X \\<rightarrow> I), continuous f \\<and> f x = (1 : I) \\<and> f '' A = {0})\n  (A B : set X) (hA : is_closed A) (hB : is_closed B)\n  (hAB : disjoint A B)\n  (hAc : is_compact A) :\n  \\<exists> (f : X \\<rightarrow> I), continuous f \\<and> f '' A = {0} \\<and> f '' B = {1} :=\n\ncodex statement:\ntheorem exists_continuous_function_of_disjoint_compact_closed_sets:\n  fixes X::\"'a::t2_space\" and A B::\"'a set\"\n  assumes \"compact A\" \"closed A\" \"closed B\" \"A \\<inter> B = \\<emptyset>\"\n  shows \"\\<exists>f. continuous_on X f \\<and> f ` X \\<subseteq> {0..1} \\<and> f ` A = {0} \\<and> f ` B = {1}\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_33_8: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:34_9\nnatural language statement:\nLet $X$ be a compact Hausdorif space that is the union of the closed subspaces $X_1$ and $X_2$. If $X_1$ and $X_2$ are metrizable, show that $X$ is metrizable.\nlean statement:\ntheorem exercise_34_9\n  (X : Type* ) [topological_space X] [compact_space X]\n  (X1 X2 : set X) (hX1 : is_closed X1) (hX2 : is_closed X2)\n  (hX : X1 \\<union> X2 = univ) (hX1m : metrizable_space X1)\n  (hX2m : metrizable_space X2) : metrizable_space X :=\n\ncodex statement:\ntheorem metrizable_of_compact_union_of_metrizable:\n  fixes X::\"'a::metric_space set\" and X1 X2::\"'a set\"\n  assumes \"compact X\" \"closed X1\" \"closed X2\" \"X = X1 \\<union> X2\" \"metrizable X1\" \"metrizable X2\"\n  shows \"metrizable X\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_34_9: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:37_2\nnatural language statement:\nA collection $\\mathcal{A}$ of subsets of $X$ has the countable intersection property if every countable intersection of elements of $\\mathcal{A}$ is nonempty. Show that $X$ is a Lindelöf space if and only if for every collection $\\mathcal{A}$ of subsets of $X$ having the countable intersection property, $\\bigcap_{A \\in \\mathcal{A}} \\bar{A}$ is nonempty.\nlean statement:\n\ncodex statement:\ntheorem lindelof_iff_countable_intersection_property:\n  fixes X::\"'a::metric_space topology\"\n  assumes \"countable_basis X\"\n  shows \"Lindelöf_space X \\<longleftrightarrow> (\\<forall>A. (\\<forall>a\\<in>A. openin X a) \\<longrightarrow> (\\<exists>b. openin X b \\<and> \\<forall>a\\<in>A. a \\<subseteq> b) \\<longrightarrow> (\\<exists>x. \\<forall>a\\<in>A. x\\<in>a))\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_37_2: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:38_4\nnatural language statement:\nLet $Y$ be an arbitrary compactification of $X$; let $\\beta(X)$ be the Stone-Čech compactification. Show there is a continuous surjective closed map $g \\colon \\beta(X)\\rightarrow Y$ that equals the identity on $X$.\nlean statement:\n\ncodex statement:\ntheorem exists_continuous_surjective_closed_map_of_compactification:\n  fixes X::\"'a::t1_space set\" and Y::\"'b::t1_space set\"\n  assumes \"compactification X Y\"\n  shows \"\\<exists>g. continuous_on (UNIV::'b set) g \\<and> g ` (UNIV::'b set) = UNIV \\<and> closed_in (subtopology (top_of_set (UNIV::'b set)) (UNIV::'b set)) (g -` (UNIV::'a set)) \\<and> g ` (UNIV::'a set) = (UNIV::'a set)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_38_4: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:38_6\nnatural language statement:\nLet $X$ be completely regular. Show that $X$ is connected if and only if $\\beta(X)$ is connected.\nlean statement:\ntheorem exercise_38_6 {X : Type*}\n  (X : Type* ) [topological_space X] [regular_space X]\n  (h : \\<forall> x A, is_closed A \\<and> \\<not> x \\<in> A \\<rightarrow>\n  \\<exists> (f : X \\<rightarrow> I), continuous f \\<and> f x = (1 : I) \\<and> f '' A = {0}) :\n  is_connected (univ : set X) \\<longleftrightarrow> is_connected (univ : set (stone_cech X)) :=\n\ncodex statement:\ntheorem connected_of_completely_regular_iff_connected_beta:\n  fixes X::\"'a::t2_space topology\"\n  assumes \"completely_regular_space X\"\n  shows \"connected X \\<longleftrightarrow> connected (\\<beta> X)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_38_6: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:39_5\nnatural language statement:\nShow that if X has a countable basis, a collection $\\mathcal{A}$ of subsets of $X$ is countably locally finite if and only if it is countable.\nlean statement:\n\ncodex statement:\ntheorem countable_of_countably_locally_finite:\n  fixes X::\"'a::metric_space set\" and A::\"'a set set\"\n  assumes \"countable_basis X\" \"countably_locally_finite A\"\n  shows \"countable A\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_39_5: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:43_2\nnatural language statement:\nLet $(X, d_X)$ and $(Y, d_Y)$ be metric spaces; let $Y$ be complete. Let $A \\subset X$. Show that if $f \\colon A \\rightarrow Y$ is uniformly continuous, then $f$ can be uniquely extended to a continuous function $g \\colon \\bar{A} \\rightarrow Y$, and $g$ is uniformly continuous.\nlean statement:\ntheorem exercise_43_2 {X : Type*} [metric_space X]\n  {Y : Type*} [metric_space Y] [complete_space Y] (A : set X)\n  (f : X \\<rightarrow> Y) (hf : uniform_continuous_on f A) :\n  \\<exists>! (g : X \\<rightarrow> Y), continuous_on g (closure A) \\<and>\n  uniform_continuous_on g (closure A) \\<and> \\<forall> (x : A), g x = f x :=\n\ncodex statement:\ntheorem uniformly_continuous_extends_to_continuous_uniformly_continuous:\n  fixes f::\"'a::metric_space \\<Rightarrow> 'b::complete_space\"\n  assumes \"uniformly_continuous_on A f\"\n  shows \"\\<exists>g. continuous_on (closure A) g \\<and> g|`A = f \\<and> uniformly_continuous_on (closure A) g\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_43_2: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n(*\nproblem_number:43_7\nnatural language statement:\nShow that the set of all sequences $(x_1, x_2, \\ldots)$ such that $\\sum x_i^2$ converges is complete in $l^2$-metric.\nlean statement:\n\ncodex statement:\ntheorem complete_of_sum_square_converges:\n  fixes X::\"nat \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"\\<forall>n. norm (X n) < \\<infinity>\"\n  shows \"\\<exists>l. (\\<forall>n. norm (X n - l) < e) \\<longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. norm (X n - l) < e)\"\nOur comment on the codex statement: <YOU CAN LEAVE YOUR COMMENT HERE>\n *)\ntheorem exercise_43_7: undefined oops (*NOT EASILY EXPRESSIBLE using our primitives*)\n\n\n\n\nend\n", "meta": {"author": "Wenda302", "repo": "ProofNet_Isabelle", "sha": "eb3374445d74b257368dc62907fbb901b7daef73", "save_path": "github-repos/isabelle/Wenda302-ProofNet_Isabelle", "path": "github-repos/isabelle/Wenda302-ProofNet_Isabelle/ProofNet_Isabelle-eb3374445d74b257368dc62907fbb901b7daef73/isabelle_formal/Munkres.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.8824278788223264, "lm_q1q2_score": 0.7569184829909497}}
{"text": "theory Part_2 imports Main\n\nbegin\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS: \"ev n \\<Longrightarrow> ev(Suc(Suc n))\"\n\n(* 5.3 *)\n\nlemma assumes a: \"ev(Suc(Suc n))\" shows \"ev n\"\nproof -\n  show ?thesis using a\n  proof cases\n    case evSS thus ?thesis by auto\n  qed\nqed\n\n(* 5.4 *)\n\nlemma \"\\<not> ev(Suc(Suc(Suc 0)))\" (is \"\\<not> ?P\")\nproof\n  assume \"?P\"\n  hence \"ev (Suc 0)\" using ev.cases by blast\n  thus \"False\" using ev.cases by blast\nqed\n\n(* 5.5 *)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\nit0: \"iter r 0 x x\" |\nit_SS: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case it0\n    show ?case by (simp add: star.refl)\nnext\n  case it_SS\n  thus ?case by (meson star.step)\nqed\n\n(* 5.6 *)\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (x#xs) = {x} \\<union> elems xs\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\n  case Nil\n  thus ?case by auto\nnext\n  case (Cons a xs)\n  show ?case\n  proof cases\n    assume \"a = x\"\n    obtain ys where ys:\"(ys::'a list) = []\" by auto\n    obtain zs where \"zs = xs\" by auto\n    have \"a \\<notin> elems ys\" by (simp add: ys)\n    thus ?thesis using ys using \\<open>a = x\\<close> by blast\n  next\n    assume \"a \\<noteq> x\"\n    hence \"x \\<in> elems xs\" using Cons.prems by auto\n    obtain ys where ys:\"ys = [a]\" by auto\n    obtain zs where zs:\"zs = xs\" by auto\n    thus ?thesis using ys zs \n      by (metis Cons.IH Cons_eq_appendI Un_iff \\<open>a \\<noteq> x\\<close> \\<open>x \\<in> elems xs\\<close> elems.simps(2) ex_in_conv insert_iff)\n  qed\nqed\n\n(* 5.7 *)\n\ndatatype alpha = a | b (* a == '(', b == ')' *)\n\n(* \nGrammar for balanced parentheses S\n  S \\<rightarrow> \\<epsilon> | aSb | SS\n*)\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS0: \"S []\" |\nS1: \"S w \\<Longrightarrow> S (a # w @ [b])\" (*S [a,b,a,b] \\<rightarrow> S [a,b] \\<rightarrow> S [] \\<rightarrow> true *) |\nS2: \"S w \\<Longrightarrow> S x \\<Longrightarrow> S (w @ x)\" (* S [a,b,a,b] \\<rightarrow> S [a,b] \\<and> S [a,b] \\<rightarrow> true *)\n\n(* \nSecond grammar for balanced parentheses T\n  T \\<rightarrow> \\<epsilon> | TaTb \n*)\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nT0: \"T []\" |\nT1: \"T w \\<Longrightarrow> T x \\<Longrightarrow> T (w @ [a] @ x @ [b])\"\n\nlemma TS : \"T w \\<Longrightarrow> S w\"\n  apply(induction rule: T.induct)\n   apply(auto intro: S0 S1 S2)\n  done\n\nlemma ST : \"S w \\<Longrightarrow> T w\"\nproof (induction rule: S.induct)\n  case S0\n  thus ?case by (simp add: T0)\nnext\n  case S1\n  thus ?case using T1 by blast\nnext\n  case S2\n  thus ?case using T1 by blast\nqed\n\ncorollary SeqT: \"S w \\<longleftrightarrow> T w\"\n  apply(auto intro: ST TS)\n  done\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n\"balanced 0 w = S w\" |\n\"balanced n w = balanced (n - 1) (a # w)\"\n\ncorollary \"balanced n w \\<longleftrightarrow> S (replicate n a @ w)\" (is \"?P \\<longleftrightarrow> ?Q\")\nproof\n  assume \"?P\"\n  from this show \"?Q\"\n  proof (induction n)\n    case 0\n    thus ?case by simp\n  next\n    case (Suc m)\n    thus ?case using S0 and S2 by blast\n  qed\nnext\n  assume \"?Q\"\n  from this show \"?P\"\n  proof (induction n)\n    case 0\n    thus ?case by auto\n  next\n    case (Suc m)\n    thus ?case using S0 and S1 and S2 by blast\n  qed\nqed\n\nend", "meta": {"author": "joshua-morris", "repo": "concrete-semantics", "sha": "a6621e2d7b55b7a6965ed17a21befc93cd9dd298", "save_path": "github-repos/isabelle/joshua-morris-concrete-semantics", "path": "github-repos/isabelle/joshua-morris-concrete-semantics/concrete-semantics-a6621e2d7b55b7a6965ed17a21befc93cd9dd298/chapter-5/Part_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8577681013541611, "lm_q1q2_score": 0.7569184729384884}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_nat_HSortSorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Heap = Node \"Heap\" \"Nat\" \"Heap\" | Nil\n\nfun toHeap :: \"Nat list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun ordered :: \"Nat list => bool\" where\n  \"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if le x2 x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else\n      Node (hmerge (Node z x2 x3) x6) x5 x4)\"\n| \"hmerge (Node z x2 x3) (Nil) = Node z x2 x3\"\n| \"hmerge (Nil) y = y\"\n\nfun hpairwise :: \"Heap list => Heap list\" where\n  \"hpairwise (nil2) = nil2\"\n| \"hpairwise (cons2 q (nil2)) = cons2 q (nil2)\"\n| \"hpairwise (cons2 q (cons2 r qs)) =\n     cons2 (hmerge q r) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 q (nil2)) = q\"\n| \"hmerging (cons2 q (cons2 z x2)) =\n     hmerging (hpairwise (cons2 q (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"Nat list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => Nat list\" where\n  \"toList (Node q y r) = cons2 y (toList (hmerge q r))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"Nat list => Nat list\" where\n  \"hsort x = toList (toHeap2 x)\"\n\ntheorem property0 :\n  \"ordered (hsort xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_nat_HSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7566172602984752}}
{"text": "(*  Title:       Defintion and basics facts about Cantor pairing function\n    Author:      Michael Nedzelsky <MichaelNedzelsky at yandex.ru>, 2008\n    Maintainer:  Michael Nedzelsky <MichaelNedzelsky at yandex.ru>\n*)\n\nsection \\<open>Cantor pairing function\\<close>\n\ntheory CPair\nimports Main\nbegin\n\ntext \\<open>\n  We introduce a particular coding \\<open>c_pair\\<close> from ordered pairs\n  of natural numbers to natural numbers.  See \\cite{Rogers} and the\n  Isabelle documentation for more information.\n\\<close>\n\nsubsection \\<open>Pairing function\\<close>\n\ndefinition\n  sf :: \"nat \\<Rightarrow> nat\" where\n  sf_def: \"sf x = x * (x+1) div 2\"\n\ndefinition\n  c_pair :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"c_pair x y = sf (x+y) + x\"\n\nlemma sf_at_0: \"sf 0 = 0\" by (simp add: sf_def)\n\nlemma sf_at_1: \"sf 1 = 1\" by (simp add: sf_def)\n\nlemma sf_at_Suc: \"sf (x+1) = sf x + x + 1\"\nproof -\n  have S1: \"sf(x+1) = ((x+1)*(x+2)) div 2\" by (simp add: sf_def)\n  have S2: \"(x+1)*(x+2) = x*(x+1) + 2*(x+1)\" by (auto)\n  have S2_1: \"\\<And> x y. x=y \\<Longrightarrow> x div 2 = y div 2\" by auto\n  from S2 have S3: \"(x+1)*(x+2) div 2 = (x*(x+1) + 2*(x+1)) div 2\" by (rule S2_1)\n  have S4: \"(0::nat) < 2\" by (auto)\n  from S4 have S5: \"(x*(x+1) + 2*(x+1)) div 2 = (x+1) + x*(x+1) div 2\" by simp\n  from S1 S3 S5 show ?thesis by (simp add: sf_def)\nqed\n\nlemma arg_le_sf: \"x \\<le> sf x\"\nproof -\n  have \"x + x \\<le> x*(x + 1)\" by simp\n  hence \"(x + x) div 2 \\<le> x*(x+1) div 2\" by (rule div_le_mono)\n  hence \"x \\<le> x*(x+1) div 2\" by simp\n  thus ?thesis by (simp add: sf_def)\nqed\n\nlemma sf_mono: \"x \\<le> y \\<Longrightarrow> sf x \\<le> sf y\"\nproof -\n  assume A1: \"x \\<le> y\"\n  then have \"x+1 \\<le> y+1\" by (auto)\n  with A1 have \"x*(x+1) \\<le> y*(y+1)\" by (rule mult_le_mono)\n  then have \"x*(x+1) div 2 \\<le> y*(y+1) div 2\" by (rule div_le_mono)\n  thus ?thesis by (simp add: sf_def)\nqed\n\nlemma sf_strict_mono: \"x < y \\<Longrightarrow> sf x < sf y\"\nproof -\n  assume A1: \"x < y\"\n  from A1 have S1: \"x+1 \\<le> y\" by simp\n  from S1 sf_mono have S2: \"sf (x+1) \\<le> sf y\" by (auto)\n  from sf_at_Suc have S3: \"sf x < sf (x+1)\" by (auto)\n  from S2 S3 show ?thesis by (auto)\nqed\n\nlemma sf_posI: \"x > 0 \\<Longrightarrow> sf(x) > 0\"\nproof -\n  assume A1: \"x > 0\"\n  then have \"sf(0) < sf(x)\" by (rule sf_strict_mono)\n  then show ?thesis by simp\nqed\n\nlemma arg_less_sf: \"x > 1 \\<Longrightarrow> x < sf(x)\"\nproof -\n  assume A1: \"x > 1\"\n  let ?y = \"x-(1::nat)\"\n  from A1 have S1: \"x = ?y+1\" by simp\n  from A1 have \"?y > 0\" by simp\n  then have S2: \"sf(?y) > 0\" by (rule sf_posI)\n  have \"sf(?y+1) = sf(?y) + ?y + 1\" by (rule sf_at_Suc)\n  with S1 have \"sf(x) = sf(?y) + x\" by simp\n  with S2  show ?thesis by simp\nqed\n\nlemma sf_eq_arg: \"sf x = x \\<Longrightarrow> x \\<le> 1\"\nproof -\n  assume \"sf(x) = x\"\n  then have \"\\<not> (x < sf(x))\" by simp\n  then have \"(\\<not> (x > 1))\" by (auto simp add: arg_less_sf)\n  then show ?thesis by simp\nqed\n\nlemma sf_le_sfD: \"sf x \\<le> sf y \\<Longrightarrow> x \\<le> y\"\nproof -\n  assume A1: \"sf x \\<le> sf y\"\n  have S1: \"y < x \\<Longrightarrow> sf y < sf x\" by (rule sf_strict_mono)\n  have S2: \"y < x \\<or> x \\<le> y\" by (auto)\n  from A1 S1 S2 show ?thesis by (auto)\nqed\n\nlemma sf_less_sfD: \"sf x < sf y \\<Longrightarrow> x < y\"\nproof -\n  assume A1: \"sf x < sf y\"\n  have S1: \"y \\<le> x \\<Longrightarrow> sf y \\<le> sf x\" by (rule sf_mono)\n  have S2: \"y \\<le> x \\<or> x < y\" by (auto)\n  from A1 S1 S2 show ?thesis by (auto)\nqed\n\nlemma sf_inj: \"sf x = sf y \\<Longrightarrow> x = y\"\nproof -\n  assume A1: \"sf x = sf y\"\n  have S1: \"sf x \\<le> sf y \\<Longrightarrow> x \\<le> y\" by (rule sf_le_sfD)\n  have S2: \"sf y \\<le> sf x \\<Longrightarrow> y \\<le> x\" by (rule sf_le_sfD)\n  from A1 have S3: \"sf x \\<le> sf y \\<and> sf y \\<le> sf x\" by (auto)\n  from S3 S1 S2 have S4: \"x \\<le> y \\<and> y \\<le> x\" by (auto)\n  from S4 show ?thesis by (auto)\nqed\n\ntext \\<open>Auxiliary lemmas\\<close>\n\nlemma sf_aux1: \"x + y < z \\<Longrightarrow> sf(x+y) + x < sf(z)\"\nproof -\n  assume A1: \"x+y < z\"\n  from A1 have S1: \"x+y+1 \\<le> z\" by (auto)\n  from S1 have S2: \"sf(x+y+1) \\<le> sf(z)\" by (rule sf_mono)\n  have S3: \"sf(x+y+1) = sf(x+y) + (x+y)+1\" by (rule sf_at_Suc)\n  from S3 S2 have S4: \"sf(x+y) + (x+y) + 1 \\<le> sf(z)\" by (auto)\n  from S4 show ?thesis by (auto)\nqed\n\nlemma sf_aux2: \"sf(z) \\<le> sf(x+y) + x \\<Longrightarrow> z \\<le> x+y\"\nproof -\n  assume A1: \"sf(z) \\<le> sf(x+y) + x\"\n  from A1 have S1: \"\\<not> sf(x+y) +x < sf(z)\" by (auto)\n  from S1 sf_aux1 have S2: \"\\<not> x+y < z\" by (auto)\n  from S2 show ?thesis by (auto)\nqed\n\nlemma sf_aux3: \"sf(z) + m < sf(z+1) \\<Longrightarrow> m \\<le> z\"\nproof -\n  assume A1: \"sf(z) + m < sf(z+1)\"\n  have S1: \"sf(z+1) = sf(z) + z + 1\" by (rule sf_at_Suc)\n  from A1 S1 have S2: \"sf(z) + m < sf(z) + z + 1\" by (auto)\n  from S2 have S3: \"m < z + 1\" by (auto)\n  from S3 show ?thesis by (auto)\nqed\n\nlemma sf_aux4: \"(s::nat) < t \\<Longrightarrow> (sf s) + s < sf t\"\nproof -\n  assume A1: \"(s::nat) < t\"\n  have \"s*(s + 1) + 2*(s+1) \\<le> t*(t+1)\"\n  proof -\n    from A1 have S1: \"(s::nat) + 1 \\<le> t\" by (auto)\n    from A1 have \"(s::nat) + 2 \\<le> t+1\" by (auto)\n    with S1 have \"((s::nat)+1)*(s+2) \\<le> t*(t+1)\" by (rule mult_le_mono)\n    thus ?thesis by (auto)\n  qed\n  then have S1: \"(s*(s+1) + 2*(s+1)) div 2 \\<le>  t*(t+1) div 2\" by (rule div_le_mono)\n  have \"(0::nat) < 2\" by (auto)\n  then have \"(s*(s+1) + 2*(s+1)) div 2 = (s+1) + (s*(s+1)) div 2\" by simp\n  with S1 have \"(s*(s+1)) div 2 + (s+1) \\<le> t*(t+1) div 2\" by (auto)\n  then have \"(s*(s+1)) div 2 + s < t*(t+1) div 2\" by (auto)\n  thus ?thesis by (simp add: sf_def)  \nqed\n\ntext \\<open>Basic properties of c\\_pair function\\<close>\n\nlemma sum_le_c_pair: \"x + y \\<le> c_pair x y\"\nproof -\n  have \"x+y \\<le> sf(x+y)\" by (rule arg_le_sf)\n  thus ?thesis by (simp add: c_pair_def)\nqed\n\nlemma arg1_le_c_pair: \"x \\<le> c_pair x y\"\nproof -\n  have \"(x::nat) \\<le> x + y\" by (simp)\n  moreover have \"x + y \\<le> c_pair x y\" by (rule sum_le_c_pair)\n  ultimately show ?thesis by (simp)\nqed\n\nlemma arg2_le_c_pair: \"y \\<le> c_pair x y\"\nproof -\n  have \"(y::nat) \\<le> x + y\" by (simp)\n  moreover have \"x + y \\<le> c_pair x y\" by (rule sum_le_c_pair)\n  ultimately show ?thesis by (simp)\nqed\n\nlemma c_pair_sum_mono: \"(x1::nat) + y1 < x2 + y2 \\<Longrightarrow> c_pair x1 y1 < c_pair x2 y2\"\nproof -\n  assume \"(x1::nat) + y1 < x2 + y2\"\n  hence \"sf (x1+y1) + (x1+y1) < sf(x2+y2)\" by (rule sf_aux4)\n  hence \"sf (x1+y1) + x1 < sf(x2+y2) + x2\" by (auto)\n  thus ?thesis by (simp add: c_pair_def)\nqed\n\nlemma c_pair_sum_inj: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> x1 + y1 = x2 + y2\"\nproof -\n  assume A1: \"c_pair x1 y1 = c_pair x2 y2\"\n  have S1: \"(x1::nat) + y1 < x2 + y2 \\<Longrightarrow> c_pair x1 y1 \\<noteq> c_pair x2 y2\" by (rule less_not_refl3, rule c_pair_sum_mono, auto)\n  have S2: \"(x2::nat) + y2 < x1 + y1 \\<Longrightarrow> c_pair x1 y1 \\<noteq> c_pair x2 y2\" by (rule less_not_refl2, rule c_pair_sum_mono, auto)\n  from S1 S2 have \"(x1::nat) + y1 \\<noteq> x2 + y2 \\<Longrightarrow> c_pair x1 y1 \\<noteq> c_pair x2 y2\" by (arith)\n  with A1 show ?thesis by (auto)\nqed\n\nlemma c_pair_inj: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> x1 = x2 \\<and> y1 = y2\"\nproof -\n  assume A1: \"c_pair x1 y1 = c_pair x2 y2\"\n  from A1 have S1: \"x1 + y1 = x2 + y2\" by (rule c_pair_sum_inj)\n  from A1 have S2: \"sf (x1+y1) + x1 = sf (x2+y2) + x2\" by (unfold c_pair_def)\n  from S1 S2 have S3: \"x1 = x2\" by (simp)\n  from S1 S3 have S4: \"y1 = y2\" by (simp)\n  from S3 S4 show ?thesis by (auto)\nqed\n\nlemma c_pair_inj1: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> x1 = x2\" by (frule c_pair_inj, drule conjunct1)\n\nlemma c_pair_inj2: \"c_pair x1 y1 = c_pair x2 y2 \\<Longrightarrow> y1 = y2\" by (frule c_pair_inj, drule conjunct2)\n\nlemma c_pair_strict_mono1: \"x1 < x2 \\<Longrightarrow> c_pair x1 y < c_pair x2 y\"\nproof -\n  assume \"x1 < x2\"\n  then have \"x1 + y < x2 + y\" by simp\n  then show ?thesis by (rule c_pair_sum_mono)\nqed\n\nlemma c_pair_mono1: \"x1 \\<le> x2 \\<Longrightarrow> c_pair x1 y \\<le> c_pair x2 y\"\nproof -\n  assume A1: \"x1 \\<le> x2\"\n  show ?thesis\n  proof cases\n    assume \"x1 < x2\"\n    then have \"c_pair x1 y < c_pair x2 y\" by (rule c_pair_strict_mono1)\n    then show ?thesis by simp\n  next\n    assume \"\\<not> x1 < x2\"\n    with A1 have \"x1 = x2\" by simp\n    then show ?thesis by simp\n  qed\nqed\n\nlemma c_pair_strict_mono2: \"y1 < y2 \\<Longrightarrow> c_pair x y1 < c_pair x y2\"\nproof -\n  assume A1: \"y1 < y2\"\n  from A1 have S1: \"x + y1 < x + y2\" by simp\n  then show ?thesis by (rule c_pair_sum_mono)\nqed\n\nlemma c_pair_mono2: \"y1 \\<le> y2 \\<Longrightarrow> c_pair x y1 \\<le> c_pair x y2\"\nproof -\n  assume A1: \"y1 \\<le> y2\"\n  show ?thesis\n  proof cases\n    assume \"y1 < y2\"\n    then have \"c_pair x y1 < c_pair x y2\" by (rule c_pair_strict_mono2)\n    then show ?thesis by simp\n  next\n    assume \"\\<not> y1 < y2\"\n    with A1 have \"y1 = y2\" by simp\n    then show ?thesis by simp\n  qed\nqed\n\nsubsection \\<open>Inverse mapping\\<close>\n\ntext \\<open>\n  \\<open>c_fst\\<close> and \\<open>c_snd\\<close> are the functions which yield\n  the inverse mapping to \\<open>c_pair\\<close>.\n\\<close>\n\ndefinition\n  c_sum :: \"nat \\<Rightarrow> nat\" where\n  \"c_sum u = (LEAST z. u < sf (z+1))\"\n\ndefinition\n  c_fst :: \"nat \\<Rightarrow> nat\" where\n  \"c_fst u = u - sf (c_sum u)\"\n\ndefinition\n  c_snd :: \"nat \\<Rightarrow> nat\" where\n  \"c_snd u = c_sum u - c_fst u\"\n\nlemma arg_less_sf_at_Suc_of_c_sum: \"u < sf ((c_sum u) + 1)\"\nproof -\n  have \"u+1 \\<le> sf(u+1)\" by (rule arg_le_sf)\n  hence \"u < sf(u+1)\" by simp\n  thus ?thesis by (unfold c_sum_def, rule LeastI)\nqed\n\nlemma arg_less_sf_imp_c_sum_less_arg: \"u < sf(x) \\<Longrightarrow> c_sum u < x\"\nproof -\n  assume A1: \"u < sf(x)\"\n  then show ?thesis\n  proof (cases x)\n    assume \"x=0\"\n    with A1 show ?thesis by (simp add: sf_def)\n  next\n    fix y\n    assume A2: \"x = Suc y\"\n    show ?thesis\n    proof -\n      from A1 A2 have \"u < sf(y+1)\" by simp\n      hence \"(Least (%z. u < sf (z+1))) \\<le> y\" by (rule Least_le)\n      hence \"c_sum u \\<le> y\" by (fold c_sum_def)\n      with A2 show ?thesis by simp\n    qed\n  qed\nqed\n\nlemma sf_c_sum_le_arg: \"u \\<ge> sf (c_sum u)\"\nproof -\n  let ?z = \"c_sum u\"\n  from arg_less_sf_at_Suc_of_c_sum have S1: \"u < sf (?z+1)\" by (auto)\n  have S2: \"\\<not> c_sum u < c_sum u\" by (auto)\n  from arg_less_sf_imp_c_sum_less_arg S2 have S3: \"\\<not> u < sf (c_sum u) \" by (auto)\n  from S3 show ?thesis by (auto)\nqed\n\nlemma c_sum_le_arg: \"c_sum u \\<le> u\"\nproof -\n  have \"c_sum u \\<le> sf (c_sum u)\" by (rule arg_le_sf)\n  moreover have \"sf(c_sum u) \\<le> u\" by (rule sf_c_sum_le_arg)\n  ultimately show ?thesis by simp\nqed\n\nlemma c_sum_of_c_pair [simp]: \"c_sum (c_pair x y) = x + y\"\nproof -\n  let ?u = \"c_pair x y\"\n  let ?z = \"c_sum ?u\"\n  have S1: \"?u < sf(?z+1)\" by (rule arg_less_sf_at_Suc_of_c_sum)\n  have S2: \"sf(?z) \\<le> ?u\" by (rule sf_c_sum_le_arg)\n  from S1 have S3: \"sf(x+y)+x < sf(?z+1)\" by (simp add: c_pair_def)\n  from S2 have S4: \"sf(?z) \\<le> sf(x+y) + x\" by (simp add: c_pair_def)\n  from S3 have S5: \"sf(x+y) < sf(?z+1)\" by (auto)\n  from S5 have S6: \"x+y < ?z+1\" by (rule sf_less_sfD)\n  from S6 have S7: \"x+y \\<le> ?z\" by (auto)\n  from S4 have S8: \"?z \\<le> x+y\" by (rule sf_aux2)\n  from S7 S8 have S9: \"?z = x+y\" by (auto)\n  from S9 show ?thesis by (simp)\nqed\n\nlemma c_fst_of_c_pair[simp]: \"c_fst (c_pair x y) = x\"\nproof -\n  let ?u = \"c_pair x y\"\n  have \"c_sum ?u = x + y\" by simp\n  hence \"c_fst ?u = ?u - sf(x+y)\" by (simp add: c_fst_def)\n  moreover have \"?u = sf(x+y) + x\" by (simp add: c_pair_def)\n  ultimately show ?thesis by (simp)\nqed\n\nlemma c_snd_of_c_pair[simp]: \"c_snd (c_pair x y) = y\"\nproof -\n  let ?u = \"c_pair x y\"\n  have \"c_sum ?u = x + y\" by simp\n  moreover have \"c_fst ?u = x\" by simp\n  ultimately show ?thesis by (simp add: c_snd_def)\nqed\n\nlemma c_pair_at_0: \"c_pair 0 0 = 0\" by (simp add: sf_def c_pair_def)\n\nlemma c_fst_at_0: \"c_fst 0 = 0\"\nproof -\n  have \"c_pair 0 0 = 0\" by (rule c_pair_at_0)\n  hence \"c_fst 0 = c_fst (c_pair 0 0)\" by simp\n  thus ?thesis by simp\nqed\n\nlemma c_snd_at_0: \"c_snd 0 = 0\"\nproof -\n  have \"c_pair 0 0 = 0\" by (rule c_pair_at_0)\n  hence \"c_snd 0 = c_snd (c_pair 0 0)\" by simp\n  thus ?thesis by simp\nqed\n\nlemma sf_c_sum_plus_c_fst: \"sf(c_sum u) + c_fst u = u\"\nproof -\n  have S1: \"sf(c_sum u) \\<le> u\" by (rule sf_c_sum_le_arg)\n  have S2: \"c_fst u = u - sf(c_sum u)\" by (simp add: c_fst_def)\n  from S1 S2 show ?thesis by (auto)\nqed\n\nlemma c_fst_le_c_sum: \"c_fst u \\<le> c_sum u\"\nproof -\n  have S1: \"sf(c_sum u) + c_fst u = u\" by (rule sf_c_sum_plus_c_fst)\n  have S2: \"u < sf((c_sum u) + 1)\" by (rule arg_less_sf_at_Suc_of_c_sum)\n  from S1 S2 sf_aux3 show ?thesis by (auto)\nqed\n\nlemma c_snd_le_c_sum: \"c_snd u \\<le> c_sum u\" by (simp add: c_snd_def)\n\nlemma c_fst_le_arg: \"c_fst u \\<le> u\"\nproof -\n  have \"c_fst u \\<le> c_sum u\" by (rule c_fst_le_c_sum)\n  moreover have \"c_sum u \\<le> u\" by (rule c_sum_le_arg)\n  ultimately show ?thesis by simp\nqed\n\nlemma c_snd_le_arg: \"c_snd u \\<le> u\"\nproof -\n  have \"c_snd u \\<le> c_sum u\" by (rule c_snd_le_c_sum)\n  moreover have \"c_sum u \\<le> u\" by (rule c_sum_le_arg)\n  ultimately show ?thesis by simp\nqed\n\nlemma c_sum_is_sum: \"c_sum u = c_fst u + c_snd u\" by (simp add: c_snd_def c_fst_le_c_sum)\n \nlemma proj_eq_imp_arg_eq: \"\\<lbrakk> c_fst u = c_fst v; c_snd u = c_snd v\\<rbrakk> \\<Longrightarrow> u = v\"\nproof -\n  assume A1: \"c_fst u = c_fst v\"\n  assume A2: \"c_snd u = c_snd v\"\n  from A1 A2 c_sum_is_sum have S1: \"c_sum u = c_sum v\" by (auto)\n  have S2: \"sf(c_sum u) + c_fst u = u\" by (rule sf_c_sum_plus_c_fst)\n  from A1 S1 S2 have S3: \"sf(c_sum v) + c_fst v = u\" by (auto)\n  from S3 sf_c_sum_plus_c_fst show ?thesis by (auto)\nqed\n\nlemma c_pair_of_c_fst_c_snd[simp]: \"c_pair (c_fst u) (c_snd u) = u\"\nproof -\n  let ?x = \"c_fst u\"\n  let ?y = \"c_snd u\"\n  have S1: \"c_pair ?x ?y = sf(?x + ?y) + ?x\" by (simp add: c_pair_def)\n  have S2: \"c_sum u = ?x + ?y\" by (rule c_sum_is_sum)\n  from S1 S2 have \"c_pair ?x ?y = sf(c_sum u) + c_fst u\" by (auto)\n  thus ?thesis by (simp add: sf_c_sum_plus_c_fst)\nqed\n\nlemma c_sum_eq_arg: \"c_sum x = x \\<Longrightarrow> x \\<le> 1\"\nproof -\n  assume A1: \"c_sum x = x\"\n  have S1: \"sf(c_sum x) + c_fst x = x\" by (rule sf_c_sum_plus_c_fst)\n  from A1 S1 have S2: \"sf x + c_fst x = x\" by simp\n  have S3: \"x \\<le> sf x\" by (rule arg_le_sf)\n  from S2 S3 have \"sf(x)=x\" by simp\n  thus ?thesis by (rule sf_eq_arg)\nqed\n\nlemma c_sum_eq_arg_2: \"c_sum x = x \\<Longrightarrow> c_fst x = 0\"\nproof -\n  assume A1: \"c_sum x = x\"\n  have S1: \"sf(c_sum x) + c_fst x = x\" by (rule sf_c_sum_plus_c_fst)\n  from A1 S1 have S2: \"sf x + c_fst x = x\" by simp\n  have S3: \"x \\<le> sf x\" by (rule arg_le_sf)\n  from S2 S3 show ?thesis by simp\nqed\n\nlemma c_fst_eq_arg: \"c_fst x = x \\<Longrightarrow> x = 0\"\nproof -\n  assume A1: \"c_fst x = x\"\n  have S1: \"c_fst x \\<le> c_sum x\" by (rule c_fst_le_c_sum)\n  have S2: \"c_sum x \\<le> x\" by (rule c_sum_le_arg)\n  from A1 S1 S2 have \"c_sum x = x\" by simp\n  then have \"c_fst x = 0\" by (rule c_sum_eq_arg_2)\n  with A1 show ?thesis by simp\nqed\n\n\n\nlemma c_snd_eq_arg: \"c_snd x = x \\<Longrightarrow> x \\<le> 1\"\nproof -\n  assume A1: \"c_snd x = x\"\n  have S1: \"c_snd x \\<le> c_sum x\" by (rule c_snd_le_c_sum)\n  have S2: \"c_sum x \\<le> x\" by (rule c_sum_le_arg)\n  from A1 S1 S2 have \"c_sum x = x\" by simp  \n  then show ?thesis by (rule c_sum_eq_arg)\nqed\n\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Recursion-Theory-I/CPair.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7566060319752476}}
{"text": "(*<*)theory AB imports Main begin(*>*)\n\nsection{*Case Study: A Context Free Grammar*}\n\ntext{*\\label{sec:CFG}\n\\index{grammars!defining inductively|(}%\nGrammars are nothing but shorthands for inductive definitions of nonterminals\nwhich represent sets of strings. For example, the production\n$A \\to B c$ is short for\n\\[ w \\in B \\Longrightarrow wc \\in A \\]\nThis section demonstrates this idea with an example\ndue to Hopcroft and Ullman, a grammar for generating all words with an\nequal number of $a$'s and~$b$'s:\n\\begin{eqnarray}\nS &\\to& \\epsilon \\mid b A \\mid a B \\nonumber\\\\\nA &\\to& a S \\mid b A A \\nonumber\\\\\nB &\\to& b S \\mid a B B \\nonumber\n\\end{eqnarray}\nAt the end we say a few words about the relationship between\nthe original proof @{cite \\<open>p.\\ts81\\<close> HopcroftUllman} and our formal version.\n\nWe start by fixing the alphabet, which consists only of @{term a}'s\nand~@{term b}'s:\n*}\n\ndatatype alfa = a | b\n\ntext{*\\noindent\nFor convenience we include the following easy lemmas as simplification rules:\n*}\n\n\n\ntext{*\\noindent\nWords over this alphabet are of type @{typ\"alfa list\"}, and\nthe three nonterminals are declared as sets of such words.\nThe productions above are recast as a \\emph{mutual} inductive\ndefinition\\index{inductive definition!simultaneous}\nof @{term S}, @{term A} and~@{term B}:\n*}\n\ninductive_set\n  S :: \"alfa list set\" and\n  A :: \"alfa list set\" and\n  B :: \"alfa list set\"\nwhere\n  \"[] \\<in> S\"\n| \"w \\<in> A \\<Longrightarrow> b#w \\<in> S\"\n| \"w \\<in> B \\<Longrightarrow> a#w \\<in> S\"\n\n| \"w \\<in> S        \\<Longrightarrow> a#w   \\<in> A\"\n| \"\\<lbrakk> v\\<in>A; w\\<in>A \\<rbrakk> \\<Longrightarrow> b#v@w \\<in> A\"\n\n| \"w \\<in> S            \\<Longrightarrow> b#w   \\<in> B\"\n| \"\\<lbrakk> v \\<in> B; w \\<in> B \\<rbrakk> \\<Longrightarrow> a#v@w \\<in> B\"\n\ntext{*\\noindent\nFirst we show that all words in @{term S} contain the same number of @{term\na}'s and @{term b}'s. Since the definition of @{term S} is by mutual\ninduction, so is the proof: we show at the same time that all words in\n@{term A} contain one more @{term a} than @{term b} and all words in @{term\nB} contain one more @{term b} than @{term a}.\n*}\n\nlemma correctness:\n  \"(w \\<in> S \\<longrightarrow> size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b])     \\<and>\n   (w \\<in> A \\<longrightarrow> size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b] + 1) \\<and>\n   (w \\<in> B \\<longrightarrow> size[x\\<leftarrow>w. x=b] = size[x\\<leftarrow>w. x=a] + 1)\"\n\ntxt{*\\noindent\nThese propositions are expressed with the help of the predefined @{term\nfilter} function on lists, which has the convenient syntax @{text\"[x\\<leftarrow>xs. P\nx]\"}, the list of all elements @{term x} in @{term xs} such that @{prop\"P x\"}\nholds. Remember that on lists @{text size} and @{text length} are synonymous.\n\nThe proof itself is by rule induction and afterwards automatic:\n*}\n\nby (rule S_A_B.induct, auto)\n\ntext{*\\noindent\nThis may seem surprising at first, and is indeed an indication of the power\nof inductive definitions. But it is also quite straightforward. For example,\nconsider the production $A \\to b A A$: if $v,w \\in A$ and the elements of $A$\ncontain one more $a$ than~$b$'s, then $bvw$ must again contain one more $a$\nthan~$b$'s.\n\nAs usual, the correctness of syntactic descriptions is easy, but completeness\nis hard: does @{term S} contain \\emph{all} words with an equal number of\n@{term a}'s and @{term b}'s? It turns out that this proof requires the\nfollowing lemma: every string with two more @{term a}'s than @{term\nb}'s can be cut somewhere such that each half has one more @{term a} than\n@{term b}. This is best seen by imagining counting the difference between the\nnumber of @{term a}'s and @{term b}'s starting at the left end of the\nword. We start with 0 and end (at the right end) with 2. Since each move to the\nright increases or decreases the difference by 1, we must have passed through\n1 on our way from 0 to 2. Formally, we appeal to the following discrete\nintermediate value theorem @{thm[source]nat0_intermed_int_val}\n@{thm[display,margin=60]nat0_intermed_int_val[no_vars]}\nwhere @{term f} is of type @{typ\"nat \\<Rightarrow> int\"}, @{typ int} are the integers,\n@{text\"\\<bar>.\\<bar>\"} is the absolute value function\\footnote{See\nTable~\\ref{tab:ascii} in the Appendix for the correct \\textsc{ascii}\nsyntax.}, and @{term\"1::int\"} is the integer 1 (see \\S\\ref{sec:numbers}).\n\nFirst we show that our specific function, the difference between the\nnumbers of @{term a}'s and @{term b}'s, does indeed only change by 1 in every\nmove to the right. At this point we also start generalizing from @{term a}'s\nand @{term b}'s to an arbitrary property @{term P}. Otherwise we would have\nto prove the desired lemma twice, once as stated above and once with the\nroles of @{term a}'s and @{term b}'s interchanged.\n*}\n\nlemma step1: \"\\<forall>i < size w.\n  \\<bar>(int(size[x\\<leftarrow>take (i+1) w. P x])-int(size[x\\<leftarrow>take (i+1) w. \\<not>P x]))\n   - (int(size[x\\<leftarrow>take i w. P x])-int(size[x\\<leftarrow>take i w. \\<not>P x]))\\<bar> \\<le> 1\"\n\ntxt{*\\noindent\nThe lemma is a bit hard to read because of the coercion function\n@{text\"int :: nat \\<Rightarrow> int\"}. It is required because @{term size} returns\na natural number, but subtraction on type~@{typ nat} will do the wrong thing.\nFunction @{term take} is predefined and @{term\"take i xs\"} is the prefix of\nlength @{term i} of @{term xs}; below we also need @{term\"drop i xs\"}, which\nis what remains after that prefix has been dropped from @{term xs}.\n\nThe proof is by induction on @{term w}, with a trivial base case, and a not\nso trivial induction step. Since it is essentially just arithmetic, we do not\ndiscuss it.\n*}\n\napply(induct_tac w)\napply(auto simp add: abs_if take_Cons split: nat.split)\ndone\n\ntext{*\nFinally we come to the above-mentioned lemma about cutting in half a word with two more elements of one sort than of the other sort:\n*}\n\nlemma part1:\n \"size[x\\<leftarrow>w. P x] = size[x\\<leftarrow>w. \\<not>P x]+2 \\<Longrightarrow>\n  \\<exists>i\\<le>size w. size[x\\<leftarrow>take i w. P x] = size[x\\<leftarrow>take i w. \\<not>P x]+1\"\n\ntxt{*\\noindent\nThis is proved by @{text force} with the help of the intermediate value theorem,\ninstantiated appropriately and with its first premise disposed of by lemma\n@{thm[source]step1}:\n*}\n\napply(insert nat0_intermed_int_val[OF step1, of \"P\" \"w\" \"1\"])\nby force\n\ntext{*\\noindent\n\nLemma @{thm[source]part1} tells us only about the prefix @{term\"take i w\"}.\nAn easy lemma deals with the suffix @{term\"drop i w\"}:\n*}\n\n\nlemma part2:\n  \"\\<lbrakk>size[x\\<leftarrow>take i w @ drop i w. P x] =\n    size[x\\<leftarrow>take i w @ drop i w. \\<not>P x]+2;\n    size[x\\<leftarrow>take i w. P x] = size[x\\<leftarrow>take i w. \\<not>P x]+1\\<rbrakk>\n   \\<Longrightarrow> size[x\\<leftarrow>drop i w. P x] = size[x\\<leftarrow>drop i w. \\<not>P x]+1\"\nby(simp del: append_take_drop_id)\n\ntext{*\\noindent\nIn the proof we have disabled the normally useful lemma\n\\begin{isabelle}\n@{thm append_take_drop_id[no_vars]}\n\\rulename{append_take_drop_id}\n\\end{isabelle}\nto allow the simplifier to apply the following lemma instead:\n@{text[display]\"[x\\<in>xs@ys. P x] = [x\\<in>xs. P x] @ [x\\<in>ys. P x]\"}\n\nTo dispose of trivial cases automatically, the rules of the inductive\ndefinition are declared simplification rules:\n*}\n\ndeclare S_A_B.intros[simp]\n\ntext{*\\noindent\nThis could have been done earlier but was not necessary so far.\n\nThe completeness theorem tells us that if a word has the same number of\n@{term a}'s and @{term b}'s, then it is in @{term S}, and similarly \nfor @{term A} and @{term B}:\n*}\n\ntheorem completeness:\n  \"(size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b]     \\<longrightarrow> w \\<in> S) \\<and>\n   (size[x\\<leftarrow>w. x=a] = size[x\\<leftarrow>w. x=b] + 1 \\<longrightarrow> w \\<in> A) \\<and>\n   (size[x\\<leftarrow>w. x=b] = size[x\\<leftarrow>w. x=a] + 1 \\<longrightarrow> w \\<in> B)\"\n\ntxt{*\\noindent\nThe proof is by induction on @{term w}. Structural induction would fail here\nbecause, as we can see from the grammar, we need to make bigger steps than\nmerely appending a single letter at the front. Hence we induct on the length\nof @{term w}, using the induction rule @{thm[source]length_induct}:\n*}\n\napply(induct_tac w rule: length_induct)\napply(rename_tac w)\n\ntxt{*\\noindent\nThe @{text rule} parameter tells @{text induct_tac} explicitly which induction\nrule to use. For details see \\S\\ref{sec:complete-ind} below.\nIn this case the result is that we may assume the lemma already\nholds for all words shorter than @{term w}. Because the induction step renames\nthe induction variable we rename it back to @{text w}.\n\nThe proof continues with a case distinction on @{term w},\non whether @{term w} is empty or not.\n*}\n\napply(case_tac w)\n apply(simp_all)\n(*<*)apply(rename_tac x v)(*>*)\n\ntxt{*\\noindent\nSimplification disposes of the base case and leaves only a conjunction\nof two step cases to be proved:\nif @{prop\"w = a#v\"} and @{prop[display]\"size[x\\<in>v. x=a] = size[x\\<in>v. x=b]+2\"} then\n@{prop\"b#v \\<in> A\"}, and similarly for @{prop\"w = b#v\"}.\nWe only consider the first case in detail.\n\nAfter breaking the conjunction up into two cases, we can apply\n@{thm[source]part1} to the assumption that @{term w} contains two more @{term\na}'s than @{term b}'s.\n*}\n\napply(rule conjI)\n apply(clarify)\n apply(frule part1[of \"\\<lambda>x. x=a\", simplified])\n apply(clarify)\ntxt{*\\noindent\nThis yields an index @{prop\"i \\<le> length v\"} such that\n@{prop[display]\"length [x\\<leftarrow>take i v . x = a] = length [x\\<leftarrow>take i v . x = b] + 1\"}\nWith the help of @{thm[source]part2} it follows that\n@{prop[display]\"length [x\\<leftarrow>drop i v . x = a] = length [x\\<leftarrow>drop i v . x = b] + 1\"}\n*}\n\n apply(drule part2[of \"\\<lambda>x. x=a\", simplified])\n  apply(assumption)\n\ntxt{*\\noindent\nNow it is time to decompose @{term v} in the conclusion @{prop\"b#v \\<in> A\"}\ninto @{term\"take i v @ drop i v\"},\n*}\n\n apply(rule_tac n1=i and t=v in subst[OF append_take_drop_id])\n\ntxt{*\\noindent\n(the variables @{term n1} and @{term t} are the result of composing the\ntheorems @{thm[source]subst} and @{thm[source]append_take_drop_id})\nafter which the appropriate rule of the grammar reduces the goal\nto the two subgoals @{prop\"take i v \\<in> A\"} and @{prop\"drop i v \\<in> A\"}:\n*}\n\n apply(rule S_A_B.intros)\n\ntxt{*\nBoth subgoals follow from the induction hypothesis because both @{term\"take i\nv\"} and @{term\"drop i v\"} are shorter than @{term w}:\n*}\n\n  apply(force simp add: min_less_iff_disj)\n apply(force split: nat_diff_split)\n\ntxt{*\nThe case @{prop\"w = b#v\"} is proved analogously:\n*}\n\napply(clarify)\napply(frule part1[of \"\\<lambda>x. x=b\", simplified])\napply(clarify)\napply(drule part2[of \"\\<lambda>x. x=b\", simplified])\n apply(assumption)\napply(rule_tac n1=i and t=v in subst[OF append_take_drop_id])\napply(rule S_A_B.intros)\n apply(force simp add: min_less_iff_disj)\nby(force simp add: min_less_iff_disj split: nat_diff_split)\n\ntext{*\nWe conclude this section with a comparison of our proof with \nHopcroft\\index{Hopcroft, J. E.} and Ullman's\\index{Ullman, J. D.}\n@{cite \\<open>p.\\ts81\\<close> HopcroftUllman}.\nFor a start, the textbook\ngrammar, for no good reason, excludes the empty word, thus complicating\nmatters just a little bit: they have 8 instead of our 7 productions.\n\nMore importantly, the proof itself is different: rather than\nseparating the two directions, they perform one induction on the\nlength of a word. This deprives them of the beauty of rule induction,\nand in the easy direction (correctness) their reasoning is more\ndetailed than our @{text auto}. For the hard part (completeness), they\nconsider just one of the cases that our @{text simp_all} disposes of\nautomatically. Then they conclude the proof by saying about the\nremaining cases: ``We do this in a manner similar to our method of\nproof for part (1); this part is left to the reader''. But this is\nprecisely the part that requires the intermediate value theorem and\nthus is not at all similar to the other cases (which are automatic in\nIsabelle). The authors are at least cavalier about this point and may\neven have overlooked the slight difficulty lurking in the omitted\ncases.  Such errors are found in many pen-and-paper proofs when they\nare scrutinized formally.%\n\\index{grammars!defining inductively|)}\n*}\n\n(*<*)end(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/Inductive/AB.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.855851135937125, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.7566060248027596}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_MSortTDSorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun minus :: \"Nat => Nat => Nat\" where\n  \"minus (Z) y = Z\"\n| \"minus (S z) (S y2) = minus z y2\"\n\nfun lt :: \"Nat => Nat => bool\" where\n  \"lt x (Z) = False\"\n| \"lt (Z) (S z) = True\"\n| \"lt (S n) (S z) = lt n z\"\n\nfun length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 y l) = plus (S Z) (length l)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun ordered :: \"Nat list => bool\" where\n  \"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun take :: \"Nat => 'a list => 'a list\" where\n  \"take x y =\n   (if le x Z then nil2 else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs => (case x of S x2 => cons2 z (take x2 xs))))\"\n\n(*fun did not finish the proof*)\nfunction idiv :: \"Nat => Nat => Nat\" where\n  \"idiv x y = (if lt x y then Z else S (idiv (minus x y) y))\"\n  by pat_completeness auto\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n  \"drop x y =\n   (if le x Z then y else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs1 => (case x of S x2 => drop x2 xs1)))\"\n\n(*fun did not finish the proof*)\nfunction msorttd :: \"Nat list => Nat list\" where\n  \"msorttd (nil2) = nil2\"\n| \"msorttd (cons2 y (nil2)) = cons2 y (nil2)\"\n| \"msorttd (cons2 y (cons2 x2 x3)) =\n     (let k :: Nat = idiv (length (cons2 y (cons2 x2 x3))) (S (S Z))\n     in lmerge\n          (msorttd (take k (cons2 y (cons2 x2 x3))))\n          (msorttd (drop k (cons2 y (cons2 x2 x3)))))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"ordered (msorttd xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_MSortTDSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248174286373, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7565086125995151}}
{"text": "theory HSV_tasks_2021_solutions imports Complex_Main begin\n\nsection \\<open>Task 1: Factorising circuits.\\<close>\n\n(* Datatype for representing simple circuits. *)\ndatatype \"circuit\" = \n  NOT \"circuit\"\n| AND \"circuit\" \"circuit\"\n| OR \"circuit\" \"circuit\"\n| TRUE\n| FALSE\n| INPUT \"int\"\n\n(* Simulates a circuit given a valuation for each input wire. *)\nfun simulate where\n  \"simulate (AND c1 c2) \\<rho> = ((simulate c1 \\<rho>) \\<and> (simulate c2 \\<rho>))\"\n| \"simulate (OR c1 c2) \\<rho> = ((simulate c1 \\<rho>) \\<or> (simulate c2 \\<rho>))\"\n| \"simulate (NOT c) \\<rho> = (\\<not> (simulate c \\<rho>))\"\n| \"simulate TRUE \\<rho> = True\"\n| \"simulate FALSE \\<rho> = False\"\n| \"simulate (INPUT i) \\<rho> = \\<rho> i\"\n\n(* Equivalence between circuits. *)\nfun circuits_equiv (infix \"\\<sim>\" 50) (* the \"50\" indicates the operator precedence *) where\n  \"c1 \\<sim> c2 = (\\<forall>\\<rho>. simulate c1 \\<rho> = simulate c2 \\<rho>)\"\n\n(* An optimisation that exploits the following Boolean identities:\n  `(a | b) & (a | c) = a | (b & c)`\n  `(a | b) & (c | a) = a | (b & c)`\n  `(a | b) & (b | c) = b | (a & c)`\n  `(a | b) & (c | b) = b | (a & c)`\n *)\nfun factorise where\n  \"factorise (NOT c) = NOT (factorise c)\"\n| \"factorise (AND (OR c1 c2) (OR c3 c4)) = (\n    let c1' = factorise c1; c2' = factorise c2; c3' = factorise c3; c4' = factorise c4 in\n    if c1' = c3' then OR c1' (AND c2' c4') \n    else if c1' = c4' then OR c1' (AND c2' c3') \n    else if c2' = c3' then OR c2' (AND c1' c4') \n    else if c2' = c4' then OR c2' (AND c1' c3') \n    else AND (OR c1' c2') (OR c3' c4'))\"\n| \"factorise (AND c1 c2) = AND (factorise c1) (factorise c2)\"\n| \"factorise (OR c1 c2) = OR (factorise c1) (factorise c2)\"\n| \"factorise TRUE = TRUE\"\n| \"factorise FALSE = FALSE\"\n| \"factorise (INPUT i) = INPUT i\"\n\nlemma (* test case *)\n \"factorise (AND TRUE TRUE) = AND TRUE TRUE\"\n  by eval\nlemma (* test case *)\n  \"factorise (AND (OR (INPUT 1) FALSE) (OR TRUE (INPUT 1))) = \n  OR (INPUT 1) (AND FALSE TRUE)\"\n  by eval\nlemma (* test case *)\n  \"factorise (NOT (AND (OR FALSE (INPUT 2)) (OR TRUE (INPUT 2)))) =\n  NOT (OR (INPUT 2) (AND FALSE TRUE))\"\n  by eval\n\ntheorem factorise_is_sound: \"factorise c \\<sim> c\"\nproof (induct rule: factorise.induct)\n  case (2 c1 c2 c3 c4)\n  let ?c1' = \"factorise c1\"\n  let ?c2' = \"factorise c2\"\n  let ?c3' = \"factorise c3\"\n  let ?c4' = \"factorise c4\"\n  from 2 have IH: \"?c1' \\<sim> c1\" \"?c2' \\<sim> c2\" \"?c3' \\<sim> c3\" \"?c4' \\<sim> c4\" by auto\n  have \"factorise (AND (OR c1 c2) (OR c3 c4)) = (\n        if ?c1' = ?c3' then OR ?c1' (AND ?c2' ?c4')\n        else if ?c1' = ?c4' then OR ?c1' (AND ?c2' ?c3')\n        else if ?c2' = ?c3' then OR ?c2' (AND ?c1' ?c4')\n        else if ?c2' = ?c4' then OR ?c2' (AND ?c1' ?c3') \n        else AND (OR ?c1' ?c2') (OR ?c3' ?c4'))\"\n    by auto\n  also have \"... \\<sim> AND (OR c1 c2) (OR c3 c4)\" using IH by auto\n  finally show ?case by auto\nqed(simp_all)\n\nfun factorise2 where\n  \"factorise2 (NOT c) = NOT (factorise2 c)\"\n| \"factorise2 (AND (OR c1 c2) (OR c3 c4)) = (\n    let c1' = factorise2 c1; c2' = factorise2 c2; c3' = factorise2 c3; c4' = factorise2 c4 in\n    if c1' = c3' then OR c1' (AND c2' c4') \n    else if c1' = c4' then OR c1' (AND c2' c3') \n    else if c2' = c3' then OR c2' (AND c1' c4') \n    else if c2' = c4' then OR c2' (AND c1' c3') \n    else AND (OR c1' c2') (OR c3' c4'))\"\n| \"factorise2 (OR (AND c1 c2) (AND c3 c4)) = (\n    let c1' = factorise2 c1; c2' = factorise2 c2; c3' = factorise2 c3; c4' = factorise2 c4 in\n    if c1' = c3' then AND c1' (OR c2' c4') \n    else if c1' = c4' then AND c1' (OR c2' c3') \n    else if c2' = c3' then AND c2' (OR c1' c4') \n    else if c2' = c4' then AND c2' (OR c1' c3') \n    else OR (AND c1' c2') (AND c3' c4'))\"\n| \"factorise2 (AND c1 c2) = AND (factorise2 c1) (factorise2 c2)\"\n| \"factorise2 (OR c1 c2) = OR (factorise2 c1) (factorise2 c2)\"\n| \"factorise2 TRUE = TRUE\"\n| \"factorise2 FALSE = FALSE\"\n| \"factorise2 (INPUT i) = INPUT i\"\n\nlemma (* test case *)\n  \"factorise2 (OR (AND (INPUT 1) (INPUT 2)) (AND TRUE (INPUT 1))) = \n  AND (INPUT 1) (OR (INPUT 2) TRUE)\"\n  by eval\n\ntheorem factorise2_is_sound: \"factorise2 c \\<sim> c\"\nproof (induct rule: factorise2.induct)\n  case (2 c1 c2 c3 c4)\n  let ?c1' = \"factorise2 c1\"\n  let ?c2' = \"factorise2 c2\"\n  let ?c3' = \"factorise2 c3\"\n  let ?c4' = \"factorise2 c4\"\n  from 2 have IH: \"?c1' \\<sim> c1\" \"?c2' \\<sim> c2\" \"?c3' \\<sim> c3\" \"?c4' \\<sim> c4\" by auto\n  have \"factorise2 (AND (OR c1 c2) (OR c3 c4)) = (\n        if ?c1' = ?c3' then OR ?c1' (AND ?c2' ?c4')\n        else if ?c1' = ?c4' then OR ?c1' (AND ?c2' ?c3')\n        else if ?c2' = ?c3' then OR ?c2' (AND ?c1' ?c4')\n        else if ?c2' = ?c4' then OR ?c2' (AND ?c1' ?c3') \n        else AND (OR ?c1' ?c2') (OR ?c3' ?c4'))\"\n    by auto\n  also have \"... \\<sim> AND (OR c1 c2) (OR c3 c4)\" using IH by auto\n  finally show ?case by auto\nnext\n  case (3 c1 c2 c3 c4)\n  let ?c1' = \"factorise2 c1\"\n  let ?c2' = \"factorise2 c2\"\n  let ?c3' = \"factorise2 c3\"\n  let ?c4' = \"factorise2 c4\"\n  from 3 have IH: \"?c1' \\<sim> c1\" \"?c2' \\<sim> c2\" \"?c3' \\<sim> c3\" \"?c4' \\<sim> c4\" by auto\n  have \"factorise2 (OR (AND c1 c2) (AND c3 c4)) = (\n        if ?c1' = ?c3' then AND ?c1' (OR ?c2' ?c4')\n        else if ?c1' = ?c4' then AND ?c1' (OR ?c2' ?c3')\n        else if ?c2' = ?c3' then AND ?c2' (OR ?c1' ?c4')\n        else if ?c2' = ?c4' then AND ?c2' (OR ?c1' ?c3') \n        else OR (AND ?c1' ?c2') (AND ?c3' ?c4'))\"\n    by auto\n  also have \"... \\<sim> OR (AND c1 c2) (AND c3 c4)\" using IH by auto\n  finally show ?case by auto\nqed(simp_all)\n\nsection \\<open>Task 2: A theorem about divisibility.\\<close>\n\ntheorem plus_dvd_odd_power:\n  \"(a::int) + b dvd a ^ (2 * n + 1) + b ^ (2 * n + 1)\"\nproof (induct n)\n  case 0 \n  thus ?case by auto\nnext\n  case (Suc n)\n  then obtain k::int where \"a ^ (2 * n + 1) + b ^ (2 * n + 1) = (a + b) * k\" \n    unfolding dvd_class.dvd_def by auto\n  hence IH: \"a ^ (2 * n + 1) = (a + b) * k - b ^ (2 * n + 1)\" by auto\n\n  have \"a ^ (2 * Suc n + 1) + b ^ (2 * Suc n + 1) = a ^ (2 * n + 2 + 1) + b ^ (2 * n + 2 + 1)\"\n    by simp\n  also have \"... = a\\<^sup>2 * a ^ (2 * n + 1) + b\\<^sup>2 * b ^ (2 * n + 1)\"\n    by (metis (no_types, lifting) add.commute add_Suc_right plus_1_eq_Suc power_add)\n  also have \"... = a\\<^sup>2 * ((a + b) * k - b ^ (2 * n + 1)) + b\\<^sup>2 * b ^ (2 * n + 1)\" \n    unfolding IH by auto\n  also have \"... = a\\<^sup>2 * (a + b) * k - a\\<^sup>2 * b ^ (2 * n + 1) + b\\<^sup>2 * b ^ (2 * n + 1)\"\n    by algebra\n  also have \"... = a\\<^sup>2 * (a + b) * k - ((a\\<^sup>2 - b\\<^sup>2) * b ^ (2 * n + 1))\"\n    by algebra\n  also have \"... = a\\<^sup>2 * (a + b) * k - ((a + b) * (a - b) * b ^ (2 * n + 1))\"\n    by algebra\n  also have \"... = (a + b) * (a\\<^sup>2 * k - ((a - b) * b ^ (2 * n + 1)))\"\n    by algebra\n  finally have \"a ^ (2 * Suc n + 1) + b ^ (2 * Suc n + 1) = \n    (a + b) * (a ^ 2 * k - ((a - b) * b ^ (2 * n + 1)))\" .\n  thus ?case by simp\nqed\n\ntheorem plus_dvd_power:\n  \"(a::int) + b dvd a ^ (2 * n + 2) + b ^ (2 * n + 2)\"\n  oops\n\nsection \\<open>Task 3: Proving that the shift-and-add-3 algorithm is correct.\\<close>\n\nsubsection \\<open>Binary and its conversion to nat\\<close>\n\ntype_synonym bit = \"bool\"\n\nabbreviation B0 where \"B0 == False\"\nabbreviation B1 where \"B1 == True\"\n\n(* The following lemma says that if I want to prove a property of \nall 5-bit binary numbers, it suffices to just consider all 32 bit patterns. *)\nlemma cases_b5:\n  fixes v w x y z :: \"bit\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B0, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B0, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B0, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B0, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B1, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B1, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B1, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B0, B1, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B0, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B0, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B0, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B0, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B1, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B1, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B1, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B0, B1, B1, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B0, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B0, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B0, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B0, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B1, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B1, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B1, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B0, B1, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B0, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B0, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B0, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B0, B1, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B1, B0, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B1, B0, B1) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B1, B1, B0) \\<Longrightarrow> P v w x y z\"\n  assumes \"(v, w, x, y, z) = (B1, B1, B1, B1, B1) \\<Longrightarrow> P v w x y z\"\n  shows \"P v w x y z\"\n  using assms\n  apply (cases v)\n   apply (cases w)\n    apply (cases x)\n     apply (cases y)\n      apply (cases z)\n       apply auto[2]\n     apply (cases z)\n      apply auto[2]\n    apply (cases y)\n     apply (cases z)\n      apply auto[2]\n    apply (cases z)\n     apply auto[2]\n   apply (cases x)\n    apply (cases y)\n     apply (cases z)\n      apply auto[2]\n    apply (cases z)\n     apply auto[2]\n   apply (cases y)\n    apply (cases z)\n     apply auto[2]\n   apply (cases z)\n    apply auto[2]\n  apply (cases w)\n   apply (cases x)\n    apply (cases y)\n     apply (cases z)\n      apply auto[2]\n    apply (cases z)\n     apply auto[2]\n   apply (cases y)\n    apply (cases z)\n     apply auto[2]\n   apply (cases z)\n    apply auto[2]\n  apply (cases x)\n   apply (cases y)\n    apply (cases z)\n     apply auto[2]\n   apply (cases z)\n    apply auto[2]\n  apply (cases y)\n   apply (cases z)\n    apply auto[2]\n  apply (cases z)\n  apply auto[2]\n  done\n\nfun binary_to_nat :: \"bit list \\<Rightarrow> nat\"\nwhere\n  \"binary_to_nat [] = 0\"\n| \"binary_to_nat (b # bs) = (if b then 2 ^ length bs else 0) + binary_to_nat bs\"\n\n\nlemma (* test case *) \"binary_to_nat [B0, B1, B0, B1] = 5\" by eval\nlemma (* test case *) \"binary_to_nat [B0, B0, B1, B0, B1] = 5\" by eval\nlemma (* test case *) \"binary_to_nat [B1] = 1\" by eval\nlemma (* test case *) \"binary_to_nat [B0] = 0\" by eval\n\nsubsection \\<open>BCD and its conversion to nat\\<close>\n\ntype_synonym nibble = \"bit * bit * bit * bit\"\n\nfun nibble_to_nat :: \"nibble \\<Rightarrow> nat\"\nwhere\n  \"nibble_to_nat (B0,B0,B0,B0) = 0\"\n| \"nibble_to_nat (B0,B0,B0,B1) = 1\"\n| \"nibble_to_nat (B0,B0,B1,B0) = 2\"\n| \"nibble_to_nat (B0,B0,B1,B1) = 3\"\n| \"nibble_to_nat (B0,B1,B0,B0) = 4\"\n| \"nibble_to_nat (B0,B1,B0,B1) = 5\"\n| \"nibble_to_nat (B0,B1,B1,B0) = 6\"\n| \"nibble_to_nat (B0,B1,B1,B1) = 7\"\n| \"nibble_to_nat (B1,B0,B0,B0) = 8\"\n| \"nibble_to_nat (B1,B0,B0,B1) = 9\"\n| \"nibble_to_nat (B1,B0,B1,B0) = 10\"\n| \"nibble_to_nat (B1,B0,B1,B1) = 11\"\n| \"nibble_to_nat (B1,B1,B0,B0) = 12\"\n| \"nibble_to_nat (B1,B1,B0,B1) = 13\"\n| \"nibble_to_nat (B1,B1,B1,B0) = 14\"\n| \"nibble_to_nat (B1,B1,B1,B1) = 15\"\n\nfun bcd_to_nat :: \"nibble list \\<Rightarrow> nat\"\nwhere\n  \"bcd_to_nat [] = 0\"\n| \"bcd_to_nat (n # ns) = bcd_to_nat ns + nibble_to_nat n * 10 ^ length ns\"\n\nlemma (* test case *) \"bcd_to_nat [(B0,B1,B1,B0)] = 6\" by eval\nlemma (* test case *) \"bcd_to_nat [(B0,B1,B1,B0),(B1,B0,B0,B1)] = 69\" by eval\nlemma (* test case *) \"bcd_to_nat [(B0,B0,B0,B0),(B1,B0,B0,B1)] = 9\" by eval\nlemma (* test case *) \"bcd_to_nat [(B0,B0,B1,B1),(B0,B0,B0,B0)] = 30\" by eval\n\n\nsubsection \\<open>Left-shifting BCD numbers\\<close>\n\n(*\n\"Add-three-and-shift\"\n                                                   bcd_part  bin_part         combined\n    ([                   ], [1,0,1,0,1,0,1])              0        85      0 + 85 = 85\n\\<longrightarrow> ([          (0,0,0,1)], [0,1,0,1,0,1])                1        21   1*64 + 21 = 85\n\\<longrightarrow> ([          (0,0,1,0)], [1,0,1,0,1])                  2        21   2*32 + 21 = 85\n\\<longrightarrow> ([          (0,1,0,1)], [0,1,0,1])                    5         5    5*16 + 5 = 85\n\\<longrightarrow> ([(0,0,0,1),(0,0,0,0)], [1,0,1])                     10         5    10*8 + 5 = 85\n\\<longrightarrow> ([(0,0,1,0),(0,0,0,1)], [0,1])                       21         1    21*4 + 1 = 85\n\\<longrightarrow> ([(0,1,0,0),(0,0,1,0)], [1])                         42         1    42*2 + 1 = 85\n\\<longrightarrow> ([(1,0,0,0),(0,1,0,1)], [])                          85         0      85 + 0 = 85\n\\<longrightarrow> done\n*)\n\nfun shift_helper :: \"nibble list \\<Rightarrow> bit \\<Rightarrow> (bit * nibble list)\"\n  where\n  \"shift_helper [] b = (b, [])\"\n| \"shift_helper ((b1, b2, b3, b4) # ns) b = (\n    let (c, ns') = shift_helper ns b in \n    (b1, (b2,b3,b4,c) # ns'))\"\n\nfun shift :: \"nibble list \\<Rightarrow> bit \\<Rightarrow> nibble list\"\nwhere\n  \"shift ns b = (let (c,ns') = shift_helper ns b in \n                 if c = B1 then (B0,B0,B0,c) # ns' else ns')\"\n\nlemma (* test case *)\n  \"shift [(B0, B1, B0, B1), (B1, B0, B1, B0)] B0\n       = [(B1, B0, B1, B1), (B0, B1, B0, B0)]\" \nby eval\n\nlemma (* test case *)\n  \"shift [(B1, B1, B0, B1), (B1, B0, B1, B0)] B0\n       = [(B0, B0, B0, B1), (B1, B0, B1, B1), (B0, B1, B0, B0)]\" \nby eval\n\nlemma (* test case *)\n  \"shift [] B1\n       = [(B0, B0, B0, B1)]\" \nby eval\n\nsubsection \\<open>Functions for adding 3 to BCD digits\\<close>\n\n(* Even though this function is only used on nibbles 0 to 9, I've\n   defined it as a total, bijective function so that it is invertible;\n   this seems to make the proof easier later on. *)\nfun maybe_add3 :: \"nibble \\<Rightarrow> nibble\"\nwhere\n  \"maybe_add3 (B0,B0,B0,B0) = (B0,B0,B0,B0)\" (* 0 \\<rightarrow> 0 *)\n| \"maybe_add3 (B0,B0,B0,B1) = (B0,B0,B0,B1)\" (* 1 \\<rightarrow> 1 *)\n| \"maybe_add3 (B0,B0,B1,B0) = (B0,B0,B1,B0)\" (* 2 \\<rightarrow> 2 *)\n| \"maybe_add3 (B0,B0,B1,B1) = (B0,B0,B1,B1)\" (* 3 \\<rightarrow> 3 *)\n| \"maybe_add3 (B0,B1,B0,B0) = (B0,B1,B0,B0)\" (* 4 \\<rightarrow> 4 *)\n| \"maybe_add3 (B0,B1,B0,B1) = (B1,B0,B0,B0)\" (* 5 \\<rightarrow> 8 *)\n| \"maybe_add3 (B0,B1,B1,B0) = (B1,B0,B0,B1)\" (* 6 \\<rightarrow> 9 *)\n| \"maybe_add3 (B0,B1,B1,B1) = (B1,B0,B1,B0)\" (* 7 \\<rightarrow> 10 *)\n| \"maybe_add3 (B1,B0,B0,B0) = (B1,B0,B1,B1)\" (* 8 \\<rightarrow> 11 *)\n| \"maybe_add3 (B1,B0,B0,B1) = (B1,B1,B0,B0)\" (* 9 \\<rightarrow> 12 *)\n| \"maybe_add3 (B1,B0,B1,B0) = (B1,B1,B0,B1)\" (* 10 \\<rightarrow> 13 *)\n| \"maybe_add3 (B1,B0,B1,B1) = (B1,B1,B1,B0)\" (* 11 \\<rightarrow> 14 *)\n| \"maybe_add3 (B1,B1,B0,B0) = (B1,B1,B1,B1)\" (* 12 \\<rightarrow> 15 *)\n| \"maybe_add3 (B1,B1,B0,B1) = (B0,B1,B0,B1)\" (* 13 \\<rightarrow> 5 *)\n| \"maybe_add3 (B1,B1,B1,B0) = (B0,B1,B1,B0)\" (* 14 \\<rightarrow> 6 *)\n| \"maybe_add3 (B1,B1,B1,B1) = (B0,B1,B1,B1)\" (* 15 \\<rightarrow> 7 *)\n\nfun maybe_add3_inv :: \"nibble \\<Rightarrow> nibble\"\n(* It's sometimes handy to be able to run the `maybe_add3` function backwards *)\nwhere\n  \"maybe_add3_inv (B0,B0,B0,B0) = (B0,B0,B0,B0)\"\n| \"maybe_add3_inv (B0,B0,B0,B1) = (B0,B0,B0,B1)\"\n| \"maybe_add3_inv (B0,B0,B1,B0) = (B0,B0,B1,B0)\"\n| \"maybe_add3_inv (B0,B0,B1,B1) = (B0,B0,B1,B1)\"\n| \"maybe_add3_inv (B0,B1,B0,B0) = (B0,B1,B0,B0)\"\n| \"maybe_add3_inv (B1,B0,B0,B0) = (B0,B1,B0,B1)\"\n| \"maybe_add3_inv (B1,B0,B0,B1) = (B0,B1,B1,B0)\"\n| \"maybe_add3_inv (B1,B0,B1,B0) = (B0,B1,B1,B1)\"\n| \"maybe_add3_inv (B1,B0,B1,B1) = (B1,B0,B0,B0)\"\n| \"maybe_add3_inv (B1,B1,B0,B0) = (B1,B0,B0,B1)\"\n| \"maybe_add3_inv (B1,B1,B0,B1) = (B1,B0,B1,B0)\"\n| \"maybe_add3_inv (B1,B1,B1,B0) = (B1,B0,B1,B1)\"\n| \"maybe_add3_inv (B1,B1,B1,B1) = (B1,B1,B0,B0)\"\n| \"maybe_add3_inv (B0,B1,B0,B1) = (B1,B1,B0,B1)\"\n| \"maybe_add3_inv (B0,B1,B1,B0) = (B1,B1,B1,B0)\"\n| \"maybe_add3_inv (B0,B1,B1,B1) = (B1,B1,B1,B1)\"\n\nlemma maybe_add3_inv1: \n  \"maybe_add3_inv (maybe_add3 n) = n\"\nby (cases n, metis (full_types) maybe_add3.simps maybe_add3_inv.simps)\n\nlemma maybe_add3_inv2: \n  \"maybe_add3 (maybe_add3_inv n) = n\"\nby (cases n, metis (full_types) maybe_add3.simps maybe_add3_inv.simps)\n\n\nsubsection \\<open>Converting binary to BCD\\<close>\n\nfun binary_to_bcd_helper :: \"nibble list \\<Rightarrow> bit list \\<Rightarrow> nibble list\"\nwhere \n  \"binary_to_bcd_helper ns [] = ns\"\n| \"binary_to_bcd_helper ns (b # bs) = binary_to_bcd_helper (shift (map maybe_add3 ns) b) bs\"\n\nfun binary_to_bcd :: \"bit list \\<Rightarrow> nibble list\"\nwhere\n  \"binary_to_bcd bs = binary_to_bcd_helper [] bs\"  \n\nlemma (* test case *)\n  \"binary_to_bcd [B1,B0,B1,B0,B1,B0,B1] = [(B1,B0,B0,B0), (B0,B1,B0,B1)]\" \n  by eval\n\n(* more test cases *)\nlemma \"binary_to_bcd [B1,B1,B1] = [(B0,B1,B1,B1)]\" by eval \nlemma \"binary_to_bcd [B1,B0,B0,B0,B0,B0,B0,B0] = [(B0,B0,B0,B1),(B0,B0,B1,B0),(B1,B0,B0,B0)]\" by eval\nlemma \"binary_to_bcd [B0,B0,B0,B0,B0,B1] = [(B0,B0,B0,B1)]\" by eval\nlemma \"binary_to_bcd [B1,B1,B0,B0,B0,B0,B0] = [(B1,B0,B0,B1),(B0,B1,B1,B0)]\" by eval\n\nsubsection \\<open>Checking that nibbles correspond to valid BCD digits\\<close>\n\nfun valid_nibble :: \"nibble \\<Rightarrow> bool\"\nwhere\n  \"valid_nibble (B0,B0,B0,B0) = True\"\n| \"valid_nibble (B0,B0,B0,B1) = True\"\n| \"valid_nibble (B0,B0,B1,B0) = True\"\n| \"valid_nibble (B0,B0,B1,B1) = True\"\n| \"valid_nibble (B0,B1,B0,B0) = True\"\n| \"valid_nibble (B0,B1,B0,B1) = True\"\n| \"valid_nibble (B0,B1,B1,B0) = True\"\n| \"valid_nibble (B0,B1,B1,B1) = True\"\n| \"valid_nibble (B1,B0,B0,B0) = True\"\n| \"valid_nibble (B1,B0,B0,B1) = True\"\n| \"valid_nibble (B1,B0,B1,B0) = False\"\n| \"valid_nibble (B1,B0,B1,B1) = False\"\n| \"valid_nibble (B1,B1,B0,B0) = False\"\n| \"valid_nibble (B1,B1,B0,B1) = False\"\n| \"valid_nibble (B1,B1,B1,B0) = False\"\n| \"valid_nibble (B1,B1,B1,B1) = False\"\n\nlemma shift_helper_valid:\n  \"list_all valid_nibble ns \\<Longrightarrow> \n  list_all valid_nibble (snd (shift_helper (map maybe_add3 ns) b))\"\nproof (induct ns)\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons n ns)\n  thus ?case\n    apply auto\n    apply (cases \"maybe_add3 n\")\n    apply auto\n    apply (split prod.split)\n    apply auto\n    apply (cases n)\n    apply (smt (z3) maybe_add3.simps valid_nibble.simps prod.inject)\n    done\nqed\n\nlemma binary_to_bcd_helper_step_valid:\n  assumes \"list_all valid_nibble ns\"\n  shows \"list_all valid_nibble (shift (map maybe_add3 ns) b)\"\nusing assms\napply auto\napply (split prod.split)\napply (smt (z3) list_all_simps(1) shift_helper_valid snd_conv valid_nibble.simps(2))\ndone\n\nlemma binary_to_bcd_helper_valid:\n  \"list_all valid_nibble ns \\<Longrightarrow> \n  list_all valid_nibble (binary_to_bcd_helper ns bs)\"\nproof (induct bs arbitrary: ns)\n  case Nil\n  thus ?case by auto\nnext\n  case (Cons b bs)\n  thus ?case using binary_to_bcd_helper_step_valid by auto\nqed\n\ntheorem binary_to_bcd_valid:\n  \"list_all valid_nibble (binary_to_bcd bs)\"\nusing binary_to_bcd_helper_valid by auto\n  \nsubsection \\<open>Proof that the binary_to_bcd translation is correct.\\<close>\n\n(* `shift_helper` doesn't change the length of its list *)\nlemma length_shift_helper:\n  \"length ns = length (snd (shift_helper ns b))\"\nproof (induct ns)\n  case Nil\n  thus ?case by auto\nnext\n  case (Cons a ns)\n  show ?case   \n    apply auto\n    apply (cases a)\n    apply auto\n    apply (cases \"shift_helper ns b\")\n    apply (auto simp add: Cons)\n    done\nqed\n\nlemma shift_helper:\n  \"list_all valid_nibble ns \\<Longrightarrow> \n  shift_helper (map maybe_add3 ns) b = (c, ns') \\<Longrightarrow>\n  bcd_to_nat ((B0,B0,B0,c) # ns') = bcd_to_nat ns * 2 + (if b then 1 else 0)\"\nproof (induct ns arbitrary: c ns')\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons n ns)\n\n  obtain c' ns'' where *: \"shift_helper (map maybe_add3 ns) b = (c', ns'')\" by fastforce\n  with Cons have IH: \n    \"bcd_to_nat ((B0, B0, B0, c') # ns'') = bcd_to_nat ns * 2 + (if b then 1 else 0)\" by simp\n\n  obtain b1 b2 b3 b4 where maybe_add3_n: \"maybe_add3 n = (b1, b2, b3, b4)\" \n    by (cases rule: prod_cases4) \n  hence \"maybe_add3_inv (maybe_add3 n) = maybe_add3_inv (b1, b2, b3, b4)\" by auto\n  with maybe_add3_inv1 have n_def: \"n = maybe_add3_inv (b1, b2, b3, b4)\" by auto\n\n  have \"c = b1\" and ns'_def: \"ns' = (b2, b3, b4, c') # ns''\" using maybe_add3_n * Cons by auto\n\n  have \"length ns'' = length ns\" \n    by (metis * length_map length_shift_helper snd_conv)\n\n  have \"nibble_to_nat (b2, b3, b4, c') * 10 ^ length ns +\n    nibble_to_nat (B0, B0, B0, b1) * 10 * 10 ^ length ns =\n    nibble_to_nat (B0, B0, B0, c') * 10 ^ length ns + \n    nibble_to_nat n * 10 ^ length ns * 2\"\n    apply (rule cases_b5[of b1 b2 b3 b4 c'])\n    using Cons apply (auto simp add: n_def)\n    done\n  thus ?case using ns'_def IH `length ns'' = length ns` `c = b1` by auto\nqed\n\n(* Determines the \"current state\" of a translation-in-progress. See examples below. *)\nfun bcd_binary_to_nat :: \"nibble list \\<Rightarrow> bit list \\<Rightarrow> nat\"\nwhere\n  \"bcd_binary_to_nat ns bs = bcd_to_nat ns * 2 ^ length bs + binary_to_nat bs\"\n\nlemma \"bcd_binary_to_nat                             [] [B1,B0,B1,B0,B1,B0,B1] = 85\" by eval\nlemma \"bcd_binary_to_nat                [(B0,B0,B0,B1)] [B0,B1,B0,B1,B0,B1]    = 85\" by eval\nlemma \"bcd_binary_to_nat                [(B0,B0,B1,B0)] [B1,B0,B1,B0,B1]       = 85\" by eval\nlemma \"bcd_binary_to_nat                [(B0,B1,B0,B1)] [B0,B1,B0,B1]          = 85\" by eval\nlemma \"bcd_binary_to_nat [(B0,B0,B0,B1), (B0,B0,B0,B0)] [B1,B0,B1]             = 85\" by eval\nlemma \"bcd_binary_to_nat [(B0,B0,B1,B0), (B0,B0,B0,B1)] [B0,B1]                = 85\" by eval\nlemma \"bcd_binary_to_nat [(B0,B1,B0,B0), (B0,B0,B1,B0)] [B1]                   = 85\" by eval\nlemma \"bcd_binary_to_nat [(B1,B0,B0,B0), (B0,B1,B0,B1)] []                     = 85\" by eval\n\nlemma binary_to_bcd_helper_step_correct:\n  assumes \"list_all valid_nibble ns\"\n  shows \"bcd_binary_to_nat ns (b # bs) =\n         bcd_binary_to_nat (shift (map maybe_add3 ns) b) bs\"\nproof -\n  have \"bcd_to_nat (shift (map maybe_add3 ns) B0) = bcd_to_nat ns * 2\"\n    apply (auto simp del: bcd_to_nat.simps)\n    apply (split prod.split)\n    apply (auto simp del: bcd_to_nat.simps)\n    using assms shift_helper apply presburger\n    apply (smt (z3) assms shift_helper add.right_neutral bcd_to_nat.simps(2)\n     mult_zero_left nibble_to_nat.simps(1))\n    done\n  moreover\n  have \"bcd_to_nat (shift (map maybe_add3 ns) B1) = bcd_to_nat ns * 2 + 1\"\n    apply (auto simp del: bcd_to_nat.simps)\n    apply (split prod.split)\n    apply (auto simp del: bcd_to_nat.simps)\n     using assms shift_helper apply presburger\n    apply (smt (z3) One_nat_def add_Suc_shift add_right_imp_eq assms bcd_to_nat.simps(2) \n       mult_zero_left nibble_to_nat.simps(1) shift_helper)\n    done\n  ultimately show ?thesis using assms by auto\nqed\n\nlemma binary_to_bcd_helper_correct:\n  \"list_all valid_nibble ns \\<Longrightarrow> \n  bcd_to_nat (binary_to_bcd_helper ns bs) = bcd_binary_to_nat ns bs\"\nproof (induct bs arbitrary: ns)\n  case Nil\n  thus ?case by simp\nnext\n  case Cons\n  thus ?case \n    using binary_to_bcd_helper_step_correct and binary_to_bcd_helper_step_valid \n    by auto\nqed\n\ntheorem binary_to_bcd_correct:\n  \"bcd_to_nat (binary_to_bcd bs) = binary_to_nat bs\"\nusing binary_to_bcd_helper_correct by auto\n\nsection \\<open> Alternative implementation of binary_to_bcd that converts to nat and then to bcd \\<close>\n\nlemma mod10_induct [case_names 0 1 2 3 4 5 6 7 8 9]:\n  fixes n :: nat\n  assumes \"P 0\" \"P 1\" \"P 2\" \"P 3\" \"P 4\" \"P 5\" \"P 6\" \"P 7\" \"P 8\" \"P 9\"\n  shows \"P (n mod 10)\"\nproof -\n  have \"n mod 10 \\<in> {..<10}\"\n    by simp\n  also have \"{..<10} = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 :: nat}\"\n    by (simp add: lessThan_nat_numeral lessThan_Suc insert_commute)\n  finally show ?thesis using assms\n    by fastforce\nqed\n  \nfun nat_to_nibble :: \"nat \\<Rightarrow> nibble\"\nwhere\n  \"nat_to_nibble n = (\n     if n = 0 then (B0,B0,B0,B0) else\n     if n = 1 then (B0,B0,B0,B1) else\n     if n = 2 then (B0,B0,B1,B0) else\n     if n = 3 then (B0,B0,B1,B1) else\n     if n = 4 then (B0,B1,B0,B0) else\n     if n = 5 then (B0,B1,B0,B1) else\n     if n = 6 then (B0,B1,B1,B0) else\n     if n = 7 then (B0,B1,B1,B1) else\n     if n = 8 then (B1,B0,B0,B0) else\n     if n = 9 then (B1,B0,B0,B1) else \n                   (B1,B1,B1,B1))\" (* unreachable *)\n\nfun nat_to_bcd :: \"nat \\<Rightarrow> nibble list\"\nwhere\n  \"nat_to_bcd n = (if n = 0 then [] else\n     nat_to_bcd (n div 10) @ [nat_to_nibble (n mod 10)])\"\n\nvalue \"nat_to_bcd 420\"\nvalue \"nat_to_bcd 42\"\nvalue \"nat_to_bcd 4\"\nvalue \"nat_to_bcd 0\"\n\nfun binary_to_bcd2 :: \"bit list \\<Rightarrow> nibble list\"\nwhere\n  \"binary_to_bcd2 bs = nat_to_bcd (binary_to_nat bs)\" \n\nlemma nat_to_nibble_valid:\n  \"valid_nibble (nat_to_nibble (n mod 10))\"\nby (induct rule: mod10_induct, auto)\n\nlemma nat_to_bcd_valid:\n  \"list_all valid_nibble (nat_to_bcd n)\"\n  using nat_to_nibble_valid \n  by (induct rule: nat_to_bcd.induct, simp)\n\ntheorem binary_to_bcd2_valid:\n \"list_all valid_nibble (binary_to_bcd2 bs)\"\nusing nat_to_bcd_valid by auto\n\nlemma bcd_to_nat_snoc:\n  \"bcd_to_nat (ns @ [n]) = bcd_to_nat ns * 10 + bcd_to_nat [n]\"\n  by (induct ns, auto)\n\nlemma bcd_to_nat_nibble:\n  \"bcd_to_nat [nat_to_nibble (n mod 10)] = n mod 10\"\n  by (induct rule: mod10_induct, auto)\n\nlemma bcd_to_nat_inv:\n  \"bcd_to_nat (nat_to_bcd n) = n\"\n  apply (induct rule: nat_to_bcd.induct)\n  apply (subst nat_to_bcd.simps)\n  apply (case_tac \"n=0\")\n   apply simp\n  apply (simp del: nat_to_bcd.simps nat_to_nibble.simps)\n  apply (subst bcd_to_nat_snoc)\n  apply (subst bcd_to_nat_nibble)\n  apply simp\n  done\n\ntheorem binary_to_bcd2_correct:\n  \"bcd_to_nat (binary_to_bcd2 bs) = binary_to_nat bs\"\n  using bcd_to_nat_inv by auto\n\nend", "meta": {"author": "johnwickerson", "repo": "HSV", "sha": "54be339e0fac44ee7af8ebba9dab10d778164ea3", "save_path": "github-repos/isabelle/johnwickerson-HSV", "path": "github-repos/isabelle/johnwickerson-HSV/HSV-54be339e0fac44ee7af8ebba9dab10d778164ea3/isabelle/2021/HSV_tasks_2021_solutions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8705972583359806, "lm_q1q2_score": 0.7563982152757763}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection \\<open>List Insertion and Deletion\\<close>\n\ntheory List_Ins_Del\nimports Sorted_Less\nbegin\n\nsubsection \\<open>Elements in a list\\<close>\n\nlemma sorted_Cons_iff:\n  \"sorted(x # xs) = ((\\<forall>y \\<in> set xs. x < y) \\<and> sorted xs)\"\nby(simp add: sorted_wrt_Cons)\n\nlemma sorted_snoc_iff:\n  \"sorted(xs @ [x]) = (sorted xs \\<and> (\\<forall>y \\<in> set xs. y < x))\"\nby(simp add: sorted_wrt_append)\n(*\ntext\\<open>The above two rules introduce quantifiers. It turns out\nthat in practice this is not a problem because of the simplicity of\nthe \"isin\" functions that implement @{const set}. Nevertheless\nit is possible to avoid the quantifiers with the help of some rewrite rules:\\<close>\n\nlemma sorted_ConsD: \"sorted (y # xs) \\<Longrightarrow> x \\<le> y \\<Longrightarrow> x \\<notin> set xs\"\nby (auto simp: sorted_Cons_iff)\n\nlemma sorted_snocD: \"sorted (xs @ [y]) \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x \\<notin> set xs\"\nby (auto simp: sorted_snoc_iff)\n\nlemmas isin_simps2 = sorted_lems sorted_ConsD sorted_snocD\n*)\n\nlemmas isin_simps = sorted_mid_iff' sorted_Cons_iff sorted_snoc_iff\n\n\nsubsection \\<open>Inserting into an ordered list without duplicates:\\<close>\n\nfun ins_list :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"ins_list x [] = [x]\" |\n\"ins_list x (a#xs) =\n  (if x < a then x#a#xs else if x=a then a#xs else a # ins_list x xs)\"\n\nlemma set_ins_list: \"set (ins_list x xs) = set xs \\<union> {x}\"\nby(induction xs) auto\n\nlemma sorted_ins_list: \"sorted xs \\<Longrightarrow> sorted(ins_list x xs)\"\nby(induction xs rule: induct_list012) auto\n\nlemma ins_list_sorted: \"sorted (xs @ [a]) \\<Longrightarrow>\n  ins_list x (xs @ a # ys) =\n  (if x < a then ins_list x xs @ (a#ys) else xs @ ins_list x (a#ys))\"\nby(induction xs) (auto simp: sorted_lems)\n\ntext\\<open>In principle, @{thm ins_list_sorted} suffices, but the following two\ncorollaries speed up proofs.\\<close>\n\ncorollary ins_list_sorted1: \"sorted (xs @ [a]) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  ins_list x (xs @ a # ys) = xs @ ins_list x (a#ys)\"\nby(auto simp add: ins_list_sorted)\n\ncorollary ins_list_sorted2: \"sorted (xs @ [a]) \\<Longrightarrow> x < a \\<Longrightarrow>\n  ins_list x (xs @ a # ys) = ins_list x xs @ (a#ys)\"\nby(auto simp: ins_list_sorted)\n\nlemmas ins_list_simps = sorted_lems ins_list_sorted1 ins_list_sorted2\n\ntext\\<open>Splay trees need two additional \\<^const>\\<open>ins_list\\<close> lemmas:\\<close>\n\nlemma ins_list_Cons: \"sorted (x # xs) \\<Longrightarrow> ins_list x xs = x # xs\"\nby (induction xs) auto\n\nlemma ins_list_snoc: \"sorted (xs @ [x]) \\<Longrightarrow> ins_list x xs = xs @ [x]\"\nby(induction xs) (auto simp add: sorted_mid_iff2)\n\n\nsubsection \\<open>Delete one occurrence of an element from a list:\\<close>\n\nfun del_list :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"del_list x [] = []\" |\n\"del_list x (a#xs) = (if x=a then xs else a # del_list x xs)\"\n\nlemma del_list_idem: \"x \\<notin> set xs \\<Longrightarrow> del_list x xs = xs\"\nby (induct xs) simp_all\n\nlemma set_del_list:\n  \"sorted xs \\<Longrightarrow> set (del_list x xs) = set xs - {x}\"\nby(induct xs) (auto simp: sorted_Cons_iff)\n\nlemma sorted_del_list: \"sorted xs \\<Longrightarrow> sorted(del_list x xs)\"\napply(induction xs rule: induct_list012)\napply auto\nby (meson order.strict_trans sorted_Cons_iff)\n\nlemma del_list_sorted: \"sorted (xs @ a # ys) \\<Longrightarrow>\n  del_list x (xs @ a # ys) = (if x < a then del_list x xs @ a # ys else xs @ del_list x (a # ys))\"\nby(induction xs)\n  (fastforce simp: sorted_lems sorted_Cons_iff intro!: del_list_idem)+\n\ntext\\<open>In principle, @{thm del_list_sorted} suffices, but the following\ncorollaries speed up proofs.\\<close>\n\ncorollary del_list_sorted1: \"sorted (xs @ a # ys) \\<Longrightarrow> a \\<le> x \\<Longrightarrow>\n  del_list x (xs @ a # ys) = xs @ del_list x (a # ys)\"\nby (auto simp: del_list_sorted)\n\ncorollary del_list_sorted2: \"sorted (xs @ a # ys) \\<Longrightarrow> x < a \\<Longrightarrow>\n  del_list x (xs @ a # ys) = del_list x xs @ a # ys\"\nby (auto simp: del_list_sorted)\n\ncorollary del_list_sorted3:\n  \"sorted (xs @ a # ys @ b # zs) \\<Longrightarrow> x < b \\<Longrightarrow>\n  del_list x (xs @ a # ys @ b # zs) = del_list x (xs @ a # ys) @ b # zs\"\nby (auto simp: del_list_sorted sorted_lems)\n\ncorollary del_list_sorted4:\n  \"sorted (xs @ a # ys @ b # zs @ c # us) \\<Longrightarrow> x < c \\<Longrightarrow>\n  del_list x (xs @ a # ys @ b # zs @ c # us) = del_list x (xs @ a # ys @ b # zs) @ c # us\"\nby (auto simp: del_list_sorted sorted_lems)\n\ncorollary del_list_sorted5:\n  \"sorted (xs @ a # ys @ b # zs @ c # us @ d # vs) \\<Longrightarrow> x < d \\<Longrightarrow>\n   del_list x (xs @ a # ys @ b # zs @ c # us @ d # vs) =\n   del_list x (xs @ a # ys @ b # zs @ c # us) @ d # vs\" \nby (auto simp: del_list_sorted sorted_lems)\n\nlemmas del_list_simps = sorted_lems\n  del_list_sorted1\n  del_list_sorted2\n  del_list_sorted3\n  del_list_sorted4\n  del_list_sorted5\n\ntext\\<open>Splay trees need two additional \\<^const>\\<open>del_list\\<close> lemmas:\\<close>\n\nlemma del_list_notin_Cons: \"sorted (x # xs) \\<Longrightarrow> del_list x xs = xs\"\nby(induction xs)(fastforce simp: sorted_Cons_iff)+\n\nlemma del_list_sorted_app:\n  \"sorted(xs @ [x]) \\<Longrightarrow> del_list x (xs @ ys) = xs @ del_list x ys\"\nby (induction xs) (auto simp: sorted_mid_iff2)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/List_Ins_Del.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357563664175, "lm_q2_score": 0.8723473796562744, "lm_q1q2_score": 0.7563563701345403}}
{"text": "theory Majorities\nimports Main\nbegin\n\nsection \\<open>Utility Lemmas About Majorities\\<close>\n\ntext \\<open>\n  Consensus algorithms usually ensure that a majority of processes\n  proposes the same value before taking a decision,\n  and we provide a few utility lemmas for reasoning about majorities.\n\\<close>\n\ntext \\<open>\n  Any two subsets \\<open>S\\<close> and \\<open>T\\<close> of a finite  set \\<open>E\\<close> such that\n  the sum of their cardinalities is larger than the size of \\<open>E\\<close> have a\n  non-empty intersection.\n\\<close>\nlemma abs_majorities_intersect:\n    assumes crd: \"card E < card S + card T\"\n        and s: \"S \\<subseteq> E\" and t: \"T \\<subseteq> E\" and e: \"finite E\"\n    shows \"S \\<inter> T \\<noteq> {}\"\nproof (clarify)\n  assume contra: \"S \\<inter> T = {}\"\n  from s t e have \"finite S\" and \"finite T\" by (auto simp: finite_subset)\n  with crd contra have \"card E < card (S \\<union> T)\" by (auto simp add: card_Un_Int)\n  moreover\n  from s t e have \"card (S \\<union> T) \\<le> card E\" by (simp add: card_mono)\n  ultimately\n  show \"False\" by simp\nqed\n\nlemma abs_majoritiesE:\n  assumes crd: \"card E < card S + card T\"\n      and s: \"S \\<subseteq> E\" and t: \"T \\<subseteq> E\" and e: \"finite E\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nproof -\n  from assms have \"S \\<inter> T \\<noteq> {}\" by (rule abs_majorities_intersect)\n  then obtain p where \"p \\<in> S \\<inter> T\" by blast\n  with that show ?thesis by auto\nqed\n\ntext \\<open>Special case: both sets \\<open>S\\<close> and \\<open>T\\<close> are majorities.\\<close>\n\nlemma abs_majoritiesE':\n  assumes Smaj: \"card S > (card E) div 2\" and Tmaj: \"card T > (card E) div 2\"\n      and s: \"S \\<subseteq> E\" and t: \"T \\<subseteq> E\" and e: \"finite E\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nproof (rule abs_majoritiesE[OF _ s t e])\n  from Smaj Tmaj show \"card E < card S + card T\" by auto\nqed\n\ntext \\<open>\n  We restate the above theorems for the case where the base type\n  is finite (taking \\<open>E\\<close> as the universal set).\n\\<close>\n\nlemma majorities_intersect:\n  assumes crd: \"card (UNIV::('a::finite) set) < card (S::'a set) + card T\"\n  shows \"S \\<inter> T \\<noteq> {}\"\n  by (rule abs_majorities_intersect[OF crd]) auto\n\nlemma majoritiesE:\n  assumes crd: \"card (UNIV::('a::finite) set) < card (S::'a set) + card (T::'a set)\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nusing crd majorities_intersect by blast\n\nlemma majoritiesE':\n  assumes S: \"card (S::('a::finite) set) > (card (UNIV::'a set)) div 2\"\n  and T: \"card (T::'a set) > (card (UNIV::'a set)) div 2\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nby (rule abs_majoritiesE'[OF S T]) auto\n\nend (* theory Majorities *)\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Heard_Of/Majorities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.8438951025545426, "lm_q1q2_score": 0.7563421514609622}}
{"text": "(*  Author:     Tobias Nipkow, TU München\n\nA theory of types extended with a greatest and a least element.\nOriented towards numeric types, hence \"\\<infinity>\" and \"-\\<infinity>\".\n*)\n\ntheory Extended\nimports\n  Main\n  \"~~/src/HOL/Library/Simps_Case_Conv\"\nbegin\n\ndatatype 'a extended = Fin 'a | Pinf (\"\\<infinity>\") | Minf (\"-\\<infinity>\")\n\n\ninstantiation extended :: (order)order\nbegin\n\nfun less_eq_extended :: \"'a extended \\<Rightarrow> 'a extended \\<Rightarrow> bool\" where\n\"Fin x \\<le> Fin y = (x \\<le> y)\" |\n\"_     \\<le> Pinf  = True\" |\n\"Minf  \\<le> _     = True\" |\n\"(_::'a extended) \\<le> _     = False\"\n\ncase_of_simps less_eq_extended_case: less_eq_extended.simps\n\ndefinition less_extended :: \"'a extended \\<Rightarrow> 'a extended \\<Rightarrow> bool\" where\n\"((x::'a extended) < y) = (x \\<le> y & \\<not> y \\<le> x)\"\n\ninstance\n  by intro_classes (auto simp: less_extended_def less_eq_extended_case split: extended.splits)\n\nend\n\ninstance extended :: (linorder)linorder\n  by intro_classes (auto simp: less_eq_extended_case split:extended.splits)\n\nlemma Minf_le[simp]: \"Minf \\<le> y\"\nby(cases y) auto\nlemma le_Pinf[simp]: \"x \\<le> Pinf\"\nby(cases x) auto\nlemma le_Minf[simp]: \"x \\<le> Minf \\<longleftrightarrow> x = Minf\"\nby(cases x) auto\nlemma Pinf_le[simp]: \"Pinf \\<le> x \\<longleftrightarrow> x = Pinf\"\nby(cases x) auto\n\nlemma less_extended_simps[simp]:\n  \"Fin x < Fin y = (x < y)\"\n  \"Fin x < Pinf  = True\"\n  \"Fin x < Minf  = False\"\n  \"Pinf < h      = False\"\n  \"Minf < Fin x  = True\"\n  \"Minf < Pinf   = True\"\n  \"l    < Minf   = False\"\nby (auto simp add: less_extended_def)\n\nlemma min_extended_simps[simp]:\n  \"min (Fin x) (Fin y) = Fin(min x y)\"\n  \"min xx      Pinf    = xx\"\n  \"min xx      Minf    = Minf\"\n  \"min Pinf    yy      = yy\"\n  \"min Minf    yy      = Minf\"\nby (auto simp add: min_def)\n\nlemma max_extended_simps[simp]:\n  \"max (Fin x) (Fin y) = Fin(max x y)\"\n  \"max xx      Pinf    = Pinf\"\n  \"max xx      Minf    = xx\"\n  \"max Pinf    yy      = Pinf\"\n  \"max Minf    yy      = yy\"\nby (auto simp add: max_def)\n\n\ninstantiation extended :: (zero)zero\nbegin\ndefinition \"0 = Fin(0::'a)\"\ninstance ..\nend\n\ndeclare zero_extended_def[symmetric, code_post]\n\ninstantiation extended :: (one)one\nbegin\ndefinition \"1 = Fin(1::'a)\"\ninstance ..\nend\n\ndeclare one_extended_def[symmetric, code_post]\n\ninstantiation extended :: (plus)plus\nbegin\n\ntext \\<open>The following definition of of addition is totalized\nto make it asociative and commutative. Normally the sum of plus and minus infinity is undefined.\\<close>\n\nfun plus_extended where\n\"Fin x + Fin y = Fin(x+y)\" |\n\"Fin x + Pinf  = Pinf\" |\n\"Pinf  + Fin x = Pinf\" |\n\"Pinf  + Pinf  = Pinf\" |\n\"Minf  + Fin y = Minf\" |\n\"Fin x + Minf  = Minf\" |\n\"Minf  + Minf  = Minf\" |\n\"Minf  + Pinf  = Pinf\" |\n\"Pinf  + Minf  = Pinf\"\n\ncase_of_simps plus_case: plus_extended.simps\n\ninstance ..\n\nend\n\n\n\ninstance extended :: (ab_semigroup_add)ab_semigroup_add\n  by intro_classes (simp_all add: ac_simps plus_case split: extended.splits)\n\ninstance extended :: (ordered_ab_semigroup_add)ordered_ab_semigroup_add\n  by intro_classes (auto simp: add_left_mono plus_case split: extended.splits)\n\ninstance extended :: (comm_monoid_add)comm_monoid_add\nproof\n  fix x :: \"'a extended\" show \"0 + x = x\" unfolding zero_extended_def by(cases x)auto\nqed\n\ninstantiation extended :: (uminus)uminus\nbegin\n\nfun uminus_extended where\n\"- (Fin x) = Fin (- x)\" |\n\"- Pinf    = Minf\" |\n\"- Minf    = Pinf\"\n\ninstance ..\n\nend\n\n\ninstantiation extended :: (ab_group_add)minus\nbegin\ndefinition \"x - y = x + -(y::'a extended)\"\ninstance ..\nend\n\nlemma minus_extended_simps[simp]:\n  \"Fin x - Fin y = Fin(x - y)\"\n  \"Fin x - Pinf  = Minf\"\n  \"Fin x - Minf  = Pinf\"\n  \"Pinf  - Fin y = Pinf\"\n  \"Pinf  - Minf  = Pinf\"\n  \"Minf  - Fin y = Minf\"\n  \"Minf  - Pinf  = Minf\"\n  \"Minf  - Minf  = Pinf\"\n  \"Pinf  - Pinf  = Pinf\"\nby (simp_all add: minus_extended_def)\n\n\ntext\\<open>Numerals:\\<close>\n\ninstance extended :: (\"{ab_semigroup_add,one}\")numeral ..\n\nlemma Fin_numeral[code_post]: \"Fin(numeral w) = numeral w\"\n  apply (induct w rule: num_induct)\n  apply (simp only: numeral_One one_extended_def)\n  apply (simp only: numeral_inc one_extended_def plus_extended.simps(1)[symmetric])\n  done\n\nlemma Fin_neg_numeral[code_post]: \"Fin (- numeral w) = - numeral w\"\nby (simp only: Fin_numeral uminus_extended.simps[symmetric])\n\n\ninstantiation extended :: (lattice)bounded_lattice\nbegin\n\ndefinition \"bot = Minf\"\ndefinition \"top = Pinf\"\n\nfun inf_extended :: \"'a extended \\<Rightarrow> 'a extended \\<Rightarrow> 'a extended\" where\n\"inf_extended (Fin i) (Fin j) = Fin (inf i j)\" |\n\"inf_extended a Minf = Minf\" |\n\"inf_extended Minf a = Minf\" |\n\"inf_extended Pinf a = a\" |\n\"inf_extended a Pinf = a\"\n\nfun sup_extended :: \"'a extended \\<Rightarrow> 'a extended \\<Rightarrow> 'a extended\" where\n\"sup_extended (Fin i) (Fin j) = Fin (sup i j)\" |\n\"sup_extended a Pinf = Pinf\" |\n\"sup_extended Pinf a = Pinf\" |\n\"sup_extended Minf a = a\" |\n\"sup_extended a Minf = a\"\n\ncase_of_simps inf_extended_case: inf_extended.simps\ncase_of_simps sup_extended_case: sup_extended.simps\n\ninstance\n  by (intro_classes) (auto simp: inf_extended_case sup_extended_case less_eq_extended_case\n    bot_extended_def top_extended_def split: extended.splits)\nend\n\nend\n\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/Extended.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7563421473847567}}
{"text": "theory example\n  imports Main\n\nbegin\n\ndeclare [[names_short]]\ndatatype 'a list = Empty | Cons 'a \"'a list\"\n\nfun length :: \"'a list \\<Rightarrow> nat\"\n  where\n  \"length Empty = 0\"\n| \"length (Cons x xs) = 1 + length xs\"\n\n(* Found termination order: \"size <*mlex*> {}\" *)\n\nfun concat :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where\n  \"concat Empty xs = xs\"\n| \"concat (Cons x xs) ys =  Cons x (concat xs ys)\"\n\n(* Found termination order: \"(\\<lambda>p. size (fst p)) <*mlex*> {}\" *)\n\nfun add_tl :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where\n  \"add_tl x Empty = Cons x Empty\"\n| \"add_tl x (Cons y ys) = Cons y (add_tl x ys)\"\n\n(* Found termination order: \"(\\<lambda>p. size (snd p)) <*mlex*> {}\" *)\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\"\n  where\n  \"reverse Empty = Empty\"\n| \"reverse (Cons x xs) = concat (reverse xs) (Cons x Empty)\"\n\n(* Found termination order: \"size <*mlex*> {}\" *)\n\nlemma concat_empty [simp]: \"concat xs Empty = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\nlemma concat_assoc [simp]: \"concat (concat xs ys) zs = concat xs (concat ys zs)\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma reverse_concat [simp]: \"reverse (concat xs ys) = concat (reverse ys) (reverse xs)\"\n  apply(induction xs)\n(*  1. reverse (concat Empty ys) = concat (reverse ys) (reverse Empty)\n    2. \\<And>x1 xs.\n          reverse (concat xs ys) = concat (reverse ys) (reverse xs) \\<Longrightarrow>\n          reverse (concat (Cons x1 xs) ys) = concat (reverse ys) (reverse (Cons x1 xs)) *)\n(* after reverse_empty :\n 1. \\<And>x1 xs.\n       reverse (concat xs ys) = concat (reverse ys) (reverse xs) \\<Longrightarrow>\n       concat (concat (reverse ys) (reverse xs)) (Cons x1 Empty) =\n       concat (reverse ys) (concat (reverse xs) (Cons x1 Empty))\n*)\n  apply(auto)\n  done\n(*\n 1. reverse ys = concat (reverse ys) Empty\n 2. \\<And>x1 xs.\n       reverse (concat xs ys) = concat (reverse ys) (reverse xs) \\<Longrightarrow>\n       concat (concat (reverse ys) (reverse xs)) (Cons x1 Empty) =\n       concat (reverse ys) (concat (reverse xs) (Cons x1 Empty))\n*)\n\ntheorem reverse_reverse [simp]: \"reverse(reverse(x)) = x\"\n  apply(induction x)\n  apply(auto)\n  done\n\n (* 1. \\<And>x1 x. reverse (reverse x) = x \\<Longrightarrow> reverse (concat (reverse x) (Cons x1 Empty)) = Cons x1 x *)\n (* assoc *)\nend", "meta": {"author": "VTrelat", "repo": "Tarjan", "sha": "33564d34be43189a76b2e6e4ffbcd6fe540c4ed2", "save_path": "github-repos/isabelle/VTrelat-Tarjan", "path": "github-repos/isabelle/VTrelat-Tarjan/Tarjan-33564d34be43189a76b2e6e4ffbcd6fe540c4ed2/Isabelle/example.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7563421415057352}}
{"text": "(* < *)\ntheory mp2_sol\n  imports Main\nbegin\n(* > *)\nsection{*Boolean Expressions, Evaluation and Substitution*}\n\ntext{*\nThe following is a slightly revised version of the type of boolean\nexpressions presented in class.\n*}\ndatatype 'a boolexp =\n   TRUE | FALSE |Atom 'a | Not \"'a boolexp\"\n  | And \"'a boolexp\" \"'a boolexp\"\n  | Or \"'a boolexp\" \"'a boolexp\"\n  | Implies \"'a boolexp\" \"'a boolexp\"\n\ntext{* And the following is an implementation of the Standard\nInterpretation function defined on page 4 0f\n\\texttt{02\\_prop\\_log\\_model.pdf}. *}\n\nfun boolexp_eval \nwhere\n   \"boolexp_eval v TRUE = True\"\n | \"boolexp_eval v FALSE = False\"\n | \"boolexp_eval v (Atom x) = v x\"\n | \"boolexp_eval v (Not b) = (\\<not> (boolexp_eval v b))\"\n | \"boolexp_eval v (And a b) =\n    ((boolexp_eval v a) \\<and> (boolexp_eval v b))\"\n | \"boolexp_eval v (Or a b) =\n    ((boolexp_eval v a) \\<or> (boolexp_eval v b))\"\n | \"boolexp_eval v (Implies a b) =\n    ((\\<not> (boolexp_eval v a))\\<or> (boolexp_eval v b))\"\n\nsection{* Problems *}\n\ntext{*\nBelow you are asked to define substitution and the set of variables\noccurring in a proposition.  You are additionally asked to prove a few\nsimple properties about these two functions.\n\n\\begin{problem} (7 pts)\nDefine @{term \"boolexp_subst\"} that, given a propositional atom (@{term \"x :: 'a\"}), and two\nboolexps, creates a third boolexp that is the result of replacing all\noccurrences of the propositional atom in the second boolexp with the first\nboolexp.\n\nYou will likely find it helpful to use something like\n@{term \"(if x = y then result1 else result2)\"}\n\\end{problem}\n*}\nfun boolexp_subst :: \"'a \\<Rightarrow> 'a boolexp \\<Rightarrow> 'a boolexp \\<Rightarrow> 'a boolexp\" where\n  \"boolexp_subst x b TRUE = TRUE\"\n| \"boolexp_subst x b FALSE = FALSE\"\n| \"boolexp_subst x b (Atom y) = (if x = y then b else (Atom y))\"\n| \"boolexp_subst x b (Not b1) = Not (boolexp_subst x b b1)\"\n| \"boolexp_subst x b (And b1 b2) = And (boolexp_subst x b b1) (boolexp_subst x b b2)\"\n| \"boolexp_subst x b (Or b1 b2) = Or (boolexp_subst x b b1) (boolexp_subst x b b2)\"\n| \"boolexp_subst x b (Implies b1 b2) = Implies (boolexp_subst x b b1) (boolexp_subst x b b2)\"\n\ntext{* If you have done your work right, the following should give a result of\n@{term \"And (Atom ''b'') (Implies (Atom ''b'') TRUE) :: char list boolexp\"}\n*}\n\nvalue \"boolexp_subst ''a'' (Implies (Atom ''b'') TRUE) (And (Atom ''b'') (Atom ''a''))\"\n\ntext{*\n\\begin{problem} (3 pts)\nProve that if you evaluate with a valuation @{term \"v\"} a boolexp that is the\nresult of substituting all occurences of a propositional atom @{term \"x\"} by\nthe proposition @{const \"TRUE\"}, the result is the same as if you had evaluated the\noriginal boolexp using the valuation @{term \"(\\<lambda> y. if y = x then TRUE else v y)\"}\n\\end{problem}\n*}\n\nlemma subst_to_eval: \n\"boolexp_eval v (boolexp_subst x TRUE b) = \n boolexp_eval (\\<lambda> y. if y = x then True else v y) b\"\n  by (induct \"b\", simp_all)\n\ntext{*\n\\begin{problem} (6 pts)\nDefine a function @{term \"atoms_of_boolexp :: 'a boolexp \\<Rightarrow>\n'a list\"} that returns a list containing exactly the propositional\natoms that occur in the input boolexp.  Duplicates are allowed in the\nlist.  There is no required order.  The empty list is represented by\n@{term \"[]\"}.  To insert an element @{term \"x\"} at the front of a list\n@{term \"lst\"} use @{term \"(x # lst)\"}.  To append list @{term \"l2\"}\nonto list @{term \"l1\"} use @{term \"(l1 @ l2)\"}.\n\\end{problem}\n*}\n\nfun  atoms_of_boolexp :: \"'a boolexp \\<Rightarrow> 'a list\" where\n  \"atoms_of_boolexp TRUE = []\"\n| \"atoms_of_boolexp FALSE = []\"\n| \"atoms_of_boolexp (Atom x) = [x]\"\n| \"atoms_of_boolexp (Not b) = atoms_of_boolexp b\"\n| \"atoms_of_boolexp (And b1 b2) = (atoms_of_boolexp b1) @ (atoms_of_boolexp b2)\"\n| \"atoms_of_boolexp (Or b1 b2) = (atoms_of_boolexp b1) @ (atoms_of_boolexp b2)\"\n| \"atoms_of_boolexp (Implies b1 b2) = (atoms_of_boolexp b1) @ (atoms_of_boolexp b2)\"\n\ntext{*\nIf your definition in Problem 3 is correct, the following lemma should\ncomplete, producing a theorem\n*}\n\nlemma test_problem3:\n\"set (atoms_of_boolexp (Or (Implies (Atom ''b'') TRUE) (And (Atom ''b'') (Atom ''a'')))) =\n {''a'', ''b''}\"\nby (simp, blast)\n\ntext{*\n\\begin{problem} (3 pts)\nProve that if two valuations are the same on the propositional atoms in a\nboolexp, then they will give the same result when used to evaluate the boolexp.\n*}\n\nlemma same_on_atoms_same_value:\n\"(\\<forall> x. x : set (atoms_of_boolexp b) \\<longrightarrow> v1 x = v2 x) \\<longrightarrow>\n  (boolexp_eval v1 b = boolexp_eval v2 b)\"\nby (induct b, simp_all)\n\ntext{*\n\\begin{problem} (3 pts)\nProve that substituting for an atom that is not in a boolexp yields\nthe same boolexp.\n*}\n\nlemma subst_nonexistant_atom:\n\"x \\<notin> set(atoms_of_boolexp b) \\<longrightarrow> (boolexp_subst x b' b = b)\"\nby (induct \"b\", simp_all)\n\n\nend\n", "meta": {"author": "YunyiZheng", "repo": "mpref", "sha": "1f2da32043114eaf8480c249ac163d72dcc91b9f", "save_path": "github-repos/isabelle/YunyiZheng-mpref", "path": "github-repos/isabelle/YunyiZheng-mpref/mpref-1f2da32043114eaf8480c249ac163d72dcc91b9f/mp2_sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.896251377290367, "lm_q1q2_score": 0.7563421409156604}}
{"text": "(*  Title:      FOL/ex/Quantifiers_Cla.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n*)\n\nsection \\<open>First-Order Logic: quantifier examples (classical version)\\<close>\n\ntheory Quantifiers_Cla\nimports FOL\nbegin\n\nlemma \"(\\<forall>x y. P(x,y)) \\<longrightarrow> (\\<forall>y x. P(x,y))\"\n  by fast\n\nlemma \"(\\<exists>x y. P(x,y)) \\<longrightarrow> (\\<exists>y x. P(x,y))\"\n  by fast\n\n\ntext \\<open>Converse is false.\\<close>\nlemma \"(\\<forall>x. P(x)) \\<or> (\\<forall>x. Q(x)) \\<longrightarrow> (\\<forall>x. P(x) \\<or> Q(x))\"\n  by fast\n\nlemma \"(\\<forall>x. P \\<longrightarrow> Q(x)) \\<longleftrightarrow> (P \\<longrightarrow> (\\<forall>x. Q(x)))\"\n  by fast\n\n\nlemma \"(\\<forall>x. P(x) \\<longrightarrow> Q) \\<longleftrightarrow> ((\\<exists>x. P(x)) \\<longrightarrow> Q)\"\n  by fast\n\n\ntext \\<open>Some harder ones.\\<close>\n\nlemma \"(\\<exists>x. P(x) \\<or> Q(x)) \\<longleftrightarrow> (\\<exists>x. P(x)) \\<or> (\\<exists>x. Q(x))\"\n  by fast\n\n\\<comment> \\<open>Converse is false.\\<close>\nlemma \"(\\<exists>x. P(x) \\<and> Q(x)) \\<longrightarrow> (\\<exists>x. P(x)) \\<and> (\\<exists>x. Q(x))\"\n  by fast\n\n\ntext \\<open>Basic test of quantifier reasoning.\\<close>\n\n\\<comment> \\<open>TRUE\\<close>\nlemma \"(\\<exists>y. \\<forall>x. Q(x,y)) \\<longrightarrow> (\\<forall>x. \\<exists>y. Q(x,y))\"\n  by fast\n\nlemma \"(\\<forall>x. Q(x)) \\<longrightarrow> (\\<exists>x. Q(x))\"\n  by fast\n\n\ntext \\<open>The following should fail, as they are false!\\<close>\n\nlemma \"(\\<forall>x. \\<exists>y. Q(x,y)) \\<longrightarrow> (\\<exists>y. \\<forall>x. Q(x,y))\"\n  apply fast?\n  oops\n\nlemma \"(\\<exists>x. Q(x)) \\<longrightarrow> (\\<forall>x. Q(x))\"\n  apply fast?\n  oops\n\nschematic_goal \"P(?a) \\<longrightarrow> (\\<forall>x. P(x))\"\n  apply fast?\n  oops\n\nschematic_goal \"(P(?a) \\<longrightarrow> (\\<forall>x. Q(x))) \\<longrightarrow> (\\<forall>x. P(x) \\<longrightarrow> Q(x))\"\n  apply fast?\n  oops\n\n\ntext \\<open>Back to things that are provable \\dots\\<close>\n\nlemma \"(\\<forall>x. P(x) \\<longrightarrow> Q(x)) \\<and> (\\<exists>x. P(x)) \\<longrightarrow> (\\<exists>x. Q(x))\"\n  by fast\n\ntext \\<open>An example of why \\<open>exI\\<close> should be delayed as long as possible.\\<close>\nlemma \"(P \\<longrightarrow> (\\<exists>x. Q(x))) \\<and> P \\<longrightarrow> (\\<exists>x. Q(x))\"\n  by fast\n\nschematic_goal \"(\\<forall>x. P(x) \\<longrightarrow> Q(f(x))) \\<and> (\\<forall>x. Q(x) \\<longrightarrow> R(g(x))) \\<and> P(d) \\<longrightarrow> R(?a)\"\n  by fast\n\nlemma \"(\\<forall>x. Q(x)) \\<longrightarrow> (\\<exists>x. Q(x))\"\n  by fast\n\n\ntext \\<open>Some slow ones\\<close>\n\ntext \\<open>Principia Mathematica *11.53\\<close>\nlemma \"(\\<forall>x y. P(x) \\<longrightarrow> Q(y)) \\<longleftrightarrow> ((\\<exists>x. P(x)) \\<longrightarrow> (\\<forall>y. Q(y)))\"\n  by fast\n\n(*Principia Mathematica *11.55  *)\nlemma \"(\\<exists>x y. P(x) \\<and> Q(x,y)) \\<longleftrightarrow> (\\<exists>x. P(x) \\<and> (\\<exists>y. Q(x,y)))\"\n  by fast\n\n(*Principia Mathematica *11.61  *)\nlemma \"(\\<exists>y. \\<forall>x. P(x) \\<longrightarrow> Q(x,y)) \\<longrightarrow> (\\<forall>x. P(x) \\<longrightarrow> (\\<exists>y. Q(x,y)))\"\n  by fast\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/FOL/ex/Quantifiers_Cla.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582516374121, "lm_q2_score": 0.8128673178375735, "lm_q1q2_score": 0.7563391033683412}}
{"text": "theory prog_01\n  imports Main\nbegin\n\nvalue \"1 + 2::nat\"\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 m = m\" | \n\"add (Suc m) n = Suc (add m n)\"\n\nfun fib :: \"nat \\<Rightarrow> nat\" where\n\"fib 0 = 0\" |\n\"fib (Suc 0) = 1\" |\n\"fib (Suc(Suc x)) = fib x + fib (Suc x)\"\n\nvalue \"fib(8)\"\nfun gcd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"gcd m n = (if n=0 then m then gcd n (m mod n))\"\n\n\n(*associative*)\ntheorem add_assoc: \"add x (add y z) = add (add x y) z\"\n  apply (induction x)\n  apply (auto)\n  done\n\nlemma Lemma0[simp]: \"add m 0 = m\"\n  by (induct m) simp_all\nlemma Lemma2 [simp]: \"add m (Suc n) = Suc (add m n)\"\n  by (induct m) simp_all\n\ntheorem Commu: \"add m k = add k m\"\n  apply (induction k)\n  apply (auto)\n  done\n\ntheorem add_community: \"add k m = add m k\"  \n  apply(induction k)\n   apply(subst Lemma0)\n   apply (subst add.simps(1))\n   apply(rule refl)\n  apply (subst add.simps(2))\n  apply(erule ssubst)\napply (subst Lemma2)\napply (rule refl)\n  done\nend", "meta": {"author": "TrinhLK", "repo": "Isabelle-Code", "sha": "6eb41d730967df6b4dca606376a6825d16968c20", "save_path": "github-repos/isabelle/TrinhLK-Isabelle-Code", "path": "github-repos/isabelle/TrinhLK-Isabelle-Code/Isabelle-Code-6eb41d730967df6b4dca606376a6825d16968c20/prog_01.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.8031738057795403, "lm_q1q2_score": 0.7563119549240499}}
{"text": "theory Coin imports \"~~/src/HOL/Library/Multiset\" begin\n\n\nsection \"Fundamental Lemmas\"\nsubsection \"nat\"\n\n\ntheorem \"\\<lbrakk> v1 dvd v2; v = v1 * c1 + v2 * c2; c2 \\<ge> c2' \\<rbrakk> \\<Longrightarrow> \\<exists>c1'. v = v1 * (c1 + c1') + v2 * (c2 - c2')\" for v :: nat\n  apply(rule_tac x=\"(v2 div v1) * c2'\" in exI)\n  apply(auto simp add: add_mult_distrib2 diff_mult_distrib2)\n  done\n\n\nlemma le_div_plus_mod[rule_format]: \"\\<forall>x. x \\<ge> y \\<longrightarrow> y > 1 \\<longrightarrow> x > x div y + x mod y\" for x :: nat and y :: nat\n  apply(induct y)\n  apply(force)\n  apply(auto)\n  by (metis Suc_mono div_greater_zero_iff less_diff_conv minus_mod_eq_div_mult n_less_n_mult_m zero_less_Suc)\n\n\nlemma plus_minus_assoc: \"b \\<ge> c \\<Longrightarrow> a + b - c = a + (b - c)\" for a :: nat\n  by auto\n\n\nlemma a_minus_b_plus_c_plus_d_le_a: \"a \\<ge> b \\<Longrightarrow> a - b + c + d < a \\<longleftrightarrow> b > c + d\" for a :: nat\n  by auto\n\n\nlemma a_eq_a_minus_b_plus_c_plus_d_is_b_eq_c_plus_d: \"a \\<ge> b \\<Longrightarrow> a = a - b + c + d \\<longleftrightarrow> b = c + d\"  for a :: nat\n  by auto\n\n\nlemma a_eq_b_plus_a_minus_b: \"a \\<ge> b \\<Longrightarrow> a = b + (a - b)\" for a :: nat\n  by auto\n\n\nlemma a_plus_b_eq_b_plus_c_minus_d: \"c \\<ge> d \\<Longrightarrow> a + b = b + c - d \\<longleftrightarrow> a = c - d\" for a :: nat\n  by auto\n\n\nlemma a_plus_b_minus_c_le_a: \"c \\<ge> b \\<Longrightarrow> a + b - c \\<le> a\" for a :: nat\n  apply(simp)\n  done\n\n\nlemma le_1_is_lt_2: \"x \\<le> Suc 0 \\<Longrightarrow> x < 2\" for x :: nat\n  by auto\n\n\nlemma le_4_is_lt_5: \"x \\<le> 4 \\<Longrightarrow> x < 5\" for x :: nat\n  by auto\n\n\nlemma le_Suc_flip_le: \"\\<lbrakk> x \\<le> Suc y; y < x \\<rbrakk> \\<Longrightarrow> Suc y = x\"\n  apply(simp)\n  done\n\n\nlemma neq_le_SucD: \"\\<lbrakk> x \\<noteq> z; x < y; y = z + 1 \\<rbrakk> \\<Longrightarrow> x < z\" for x :: nat\n  apply(auto)\n  done\n\n\nlemma n_eq_div_plus_mod: \"v2 = m * v1 \\<Longrightarrow> n * v1 = n div m * v2 + n mod m * v1\" for n :: nat\n  by (metis distrib_right div_mult_mod_eq mult.assoc)\n\n\nlemma le_minus[rule_format]: \"x \\<le> x - y \\<longrightarrow> x \\<le> y \\<or> y = 0\"  for x :: nat\n  apply(induct x arbitrary: y)\n  apply(auto)\n  done\n\n\nsubsection \"multiset\"\nlemma (in comm_monoid_diff) fold_mset_empty: \"fold_mset (+) x {#} = x\"\n  by auto\n\n\nlemma (in comm_monoid_diff) abc_bac: \"a + (b + c) = b + (a + c)\"\n  by (rule local.add.left_commute)\n\n\nlemma (in comm_monoid_diff) comm_monoid_add_comp_fun_commute: \"comp_fun_commute (+)\"\n  by (auto simp add: comp_fun_commute_def abc_bac intro: local.add.left_commute)\n\n\nlemma (in comm_monoid_diff) fold_mset_add: \"fold_mset (+) y (add_mset x M) = x + (fold_mset (+) y M)\"\n  by (auto simp add: comp_fun_commute.fold_mset_add_mset comm_monoid_add_comp_fun_commute)\n\n\nlemma (in comm_monoid_diff) fold_mset_plus: \"fold_mset (+) (x + y) M = y + fold_mset (+) x M\"\n  apply(induct M)\n  apply(subst (1 2) fold_mset_empty)\n  apply(rule add_commute)\n  apply(subst (1 2) fold_mset_add)\n  apply(erule ssubst)\n  apply(subst (1 2) add_assoc[symmetric])\n  apply(subst add_commute)\n  apply(rule refl)\n  done\n\n\nlemma replicate_mset_subseteq: \"replicate_mset (count C c) c \\<subseteq># C\"\n  using count_le_replicate_mset_subset_eq by fastforce\n\n\nlemma count_le_size: \"count C x \\<le> size C\"\n  using replicate_mset_subseteq size_mset_mono by fastforce\n\n\nlemma count_add_mset_eq_count: \"\\<lbrakk> xa \\<noteq> x \\<rbrakk> \\<Longrightarrow> count (add_mset xa M) x = count M x\"\n  by auto\n\n\nlemma count_eq_replicate_mset_subset_eq: \"count M x = n \\<Longrightarrow> replicate_mset n x \\<subseteq># M\"\n  using count_le_replicate_mset_subset_eq by fastforce\n\n\nlemma subset_add_weak: \"A \\<subseteq># B \\<Longrightarrow> A \\<subseteq># add_mset x B\"\n  using subset_mset.order.trans by fastforce\n\n\nlemma subset_plus_weak: \"A \\<subseteq># B \\<Longrightarrow> A \\<subseteq># B + C\"\n  by (simp add: subset_mset.add_increasing2)\n\n\nlemma count_size_FalseE: \"\\<lbrakk>count M x = n; size M < n\\<rbrakk> \\<Longrightarrow> False\"\n  by (meson count_le_size not_le)\n\n\nlemma image_mset_diff_nat: \"B \\<subseteq># A \\<Longrightarrow> image_mset f (A - B) = image_mset f A - image_mset f B\"  for f :: \"'a \\<Rightarrow> nat\"\n  apply(unfold image_mset_def)\n  by (metis image_mset_Diff image_mset_def)\n\n\nsection \"Coins\"\nsubsection \"Coin Definitions\"\ndatatype Coin = One | Five | Ten | Fifty | Hundred | FiveHundred\n\n\nsubsection \"Value of Coins\"\ntype_alias val_unit = nat\n\n\nfun val_yen_unit :: \"Coin \\<Rightarrow> val_unit\" where\n  \"val_yen_unit One = 1\" |\n  \"val_yen_unit Five = 5\" |\n  \"val_yen_unit Ten = 10\" |\n  \"val_yen_unit Fifty = 50\" |\n  \"val_yen_unit Hundred = 100\" |\n  \"val_yen_unit FiveHundred = 500\"\n\n\ntheorem inj_val_yen_unit: \"inj val_yen_unit\"\n  apply(unfold inj_def)\n  apply(intro allI)\n  apply(case_tac x)\n  apply(case_tac y)\n  apply(auto)\n  apply(case_tac y)\n  apply(auto)\n  apply(case_tac y)\n  apply(auto)\n  apply(case_tac y)\n  apply(auto)\n  apply(case_tac y)\n  apply(auto)\n  apply(case_tac y)\n  apply(auto)\n  done\n\n\ntheorem range_val_yen_unit: \"range val_yen_unit = {1, 5, 10, 50, 100, 500}\"\n  apply(subst full_SetCompr_eq[symmetric])\n  apply(auto)\n  apply(case_tac xa)\n  apply(auto)\n  apply(rule_tac x=One in exI)\n  apply(force)\n  apply(rule_tac x=Five in exI)\n  apply(force)\n  apply(rule_tac x=Ten in exI)\n  apply(force)\n  apply(rule_tac x=Fifty in exI)\n  apply(force)\n  apply(rule_tac x=Hundred in exI)\n  apply(force)\n  apply(rule_tac x=FiveHundred in exI)\n  apply(force)\n  done\n\n\nlemma val_yen_unit_gt_0: \"val_yen_unit x > 0\"\n  apply(case_tac x)\n  apply(auto)\n  done\n\n\nlemma val_yen_unit_eq_0E: \"val_yen_unit x = 0 \\<Longrightarrow> P\"\n  apply(insert val_yen_unit_gt_0)\n  apply(subst (asm) zero_less_iff_neq_zero)\n  apply(drule_tac x=x in meta_spec)\n  apply(erule notE)\n  apply(assumption)\n  done\n\n\ndefinition val :: \"Coin multiset \\<Rightarrow> nat\" where\n  \"val M = sum_mset (image_mset val_yen_unit M)\"\n\n\nlemma val_empty: \"val {#} = 0\"\n  apply(auto simp add: val_def)\n  done\n\n\nlemma val_singleton: \"val {#c#} = val_yen_unit c\"\n  apply(unfold val_def)\n  apply(auto)\n  done\n\n\nlemma val_add: \"val (add_mset x M) = val_yen_unit x + val M\"\n  apply(induct M)\n  apply(auto simp add: val_def)\n  done\n\n\nlemma val_plus: \"val (A + B) = val A + val B\"\n  apply(auto simp add: val_def)\n  done\n\n\nlemma val_diff: \"B \\<subseteq># A \\<Longrightarrow> val (A - B) = val A - val B\"\n  apply(auto simp add: val_def)\n  apply(subst image_mset_diff_nat)\n  apply(assumption)\n  apply(rule ordered_cancel_comm_monoid_diff_class.sum_mset_diff)\n  apply(erule image_mset_subseteq_mono)\n  done\n\n\ntheorem val_aribitrary: \"\\<exists>C1 C2. C1 \\<noteq> C2 \\<and> val C1 = val C2\"\n  apply(rule_tac x=\"{# Five #}\" in exI)\n  apply(rule_tac x=\"{# One, One, One, One, One #}\" in exI)\n  apply(auto simp add: val_add)\n  done\n\n\nlemma val_0: \"val C = 0 \\<longleftrightarrow> C = {#}\"\n  apply(case_tac C)\n  apply(auto simp add: val_empty val_add val_yen_unit_gt_0)\n  done\n\n\nlemma val_add_gt_0: \"val (add_mset c C) > 0\"\n  apply(subst val_add)\n  apply(rule trans_less_add1)\n  apply(rule val_yen_unit_gt_0)\n  done\n\n\nlemma val_gt_0_eq_not_empty: \"val C > 0 \\<longleftrightarrow> C \\<noteq> {#}\"\n  apply(rule iffI)\n  apply(case_tac C)\n  apply(clarify)\n  apply(subst (asm) val_empty)\n  apply(subst (asm) less_nat_zero_code)\n  apply(erule FalseE)\n  apply(erule ssubst)\n  apply(subst neq_commute)\n  apply(rule empty_not_add_mset)\n  apply(drule multi_nonempty_split)\n  apply(elim exE)\n  apply(erule ssubst)\n  apply(rule val_add_gt_0)\n  done\n\n\nlemma val_replicate_mset_count: \"val (replicate_mset n x) = n * val_yen_unit x\"\n  apply(induct n)\n  apply(auto simp add: val_empty val_add)\n  done\n\n\nlemma count_le_val: \"count C x * val_yen_unit x \\<le> val C\"\n  apply(induct C)\n  apply(auto simp add: val_add)\n  done\n\n\nlemma same_val_singleton_size_le[rule_format]: \"val {#c#} = val C \\<longrightarrow> size {#c#} \\<le> size C\"\n  apply(case_tac C)\n  apply(erule ssubst)\n  apply(rule impI)\n  apply(subst (asm) val_add)\n  apply(subst (asm) (1 2) val_empty)\n  apply(subst (asm) add_0_right)\n  apply(erule val_yen_unit_eq_0E)\n  apply(case_tac x)\n  apply(auto)\n  done\n\n\ndefinition dvd_coins :: \"val_unit set \\<Rightarrow> bool\" where\n  \"dvd_coins V \\<equiv> \\<forall>v1 \\<in> V. \\<forall>v2 \\<in> V. v1 < v2 \\<longrightarrow> v1 dvd v2\"\n\n\ntheorem dvd_coins_yen: \"dvd_coins (range val_yen_unit)\"\n  apply(unfold dvd_coins_def range_val_yen_unit)\n  apply(auto)\n  done\n\n\n\ndefinition next_Coin :: \"Coin \\<Rightarrow> Coin \\<Rightarrow> bool\" where\n  \"next_Coin c1 c3 \\<equiv> \\<nexists>c2. val_unit c1 < val_unit c2 \\<and> val_unit c2 < val_unit c3\"\n\n\nfun next_Coin :: \"Coin \\<Rightarrow> Coin option\"where\n  \"next_Coin One = Some Five\" |\n  \"next_Coin Five = Some Ten\" |\n  \"next_Coin Ten = Some Fifty\" |\n  \"next_Coin Fifty = Some Hundred\" |\n  \"next_Coin Hundred = Some FiveHundred\" |\n  \"next_Coin FiveHundred = None\"\n\n\nfun redundant_since :: \"Coin \\<Rightarrow> nat option\"where\n  \"redundant_since One = Some 5\" |\n  \"redundant_since Five = Some 2\" |\n  \"redundant_since Ten = Some 5\" |\n  \"redundant_since Fifty = Some 2\" |\n  \"redundant_since Hundred = Some 5\" |\n  \"redundant_since FiveHundred = None\"\n\n\nlemma redundant_sinceD: \"redundant_since c = Some m \\<Longrightarrow> \\<exists>c'. next_Coin c = Some c'\"\n  apply(case_tac c)\n  apply(auto)\n  done\n\n\nlemma redundant_since_gtD: \"redundant_since x = Some m \\<Longrightarrow> m > 1\"\n  apply(case_tac x)\n  apply(auto)\n  done\n\n\nlemma all_redundant_since_imp: \"(\\<forall>c m. redundant_since c = Some m \\<longrightarrow> P c m) \\<longleftrightarrow>\n    (P One 5 \\<and> P Five 2 \\<and> P Ten 5 \\<and> P Fifty 2 \\<and> P Hundred 5)\"\n  apply(auto)\n  apply(case_tac c)\n  apply(auto)\n  done\n\n\nlemma val_yen_unit_next_Coin: \"\\<lbrakk> redundant_since c = Some m; next_Coin c = Some c'\\<rbrakk> \\<Longrightarrow> val_yen_unit c' = m * val_yen_unit c\"\n  apply(case_tac c)\n  apply(auto)\n  done\n\n\nsubsection \"Normal form\"\ndefinition normal :: \"Coin multiset \\<Rightarrow> bool\" where\n  \"normal C \\<equiv> \\<forall>C'. val C = val C' \\<longrightarrow> size C \\<le> size C'\"  \n\n\nlemma normal_empty: \"normal {#}\"\n  apply(unfold normal_def)\n  apply(auto)\n  done\n\n\nlemma normal_singleton: \"normal {# c #}\"\n  apply(unfold normal_def)\n  apply(clarify)\n  apply(erule same_val_singleton_size_le)\n  done\n\n\nlemma not_normal_singletonE: \"\\<not>normal {# c #} \\<Longrightarrow> P\"\n  apply(erule notE)\n  apply(rule normal_singleton)\n  done\n\n\nlemma normal_add_imp_normal: \"normal (add_mset c C) \\<Longrightarrow> normal C\"\n  apply(unfold normal_def)\n  apply(auto)\n  apply(drule_tac x=\"add_mset c C'\" in spec)\n  apply(drule mp)\n  apply(subst (1 2) val_add)\n  apply(auto)\n  done\n\n\nlemma normal_add_add_imp_normal: \"normal (add_mset c1 (add_mset c2 C)) \\<Longrightarrow> normal C \\<and> normal (add_mset c1 C) \\<and> normal (add_mset c2 C)\"\n  apply(intro conjI)\n  apply(drule normal_add_imp_normal)\n  apply(erule normal_add_imp_normal)\n  apply(subst (asm) add_mset_commute)\n  apply(erule normal_add_imp_normal)\n  apply(erule normal_add_imp_normal)\n  done\n\n\ntheorem not_normal_if_redundant: \"\\<lbrakk> redundant_since c = Some m; count C c = m \\<rbrakk> \\<Longrightarrow> \\<not> normal C\"\n  apply(unfold normal_def)\n  apply(subst not_all)\n  apply(frule redundant_sinceD)\n  apply(clarify)\n  apply(rule_tac x=\"C + {# c' #} - replicate_mset m c\" in exI)\n  apply(clarify)\n  apply(subst (asm) size_Diff_submset)\n  apply(rule subset_plus_weak)\n  apply(force intro: count_eq_replicate_mset_subset_eq)\n  apply(clarsimp)\n  apply(drule mp)\n  apply(subst val_diff)\n  apply(rule subset_add_weak)\n  apply(force intro: count_eq_replicate_mset_subset_eq)\n  apply(subst val_replicate_mset_count)\n  apply(subst val_add)\n  apply(case_tac c)\n  apply(auto)\n  apply(case_tac c)\n  apply(auto dest!: le_minus le_1_is_lt_2 le_4_is_lt_5 elim: count_size_FalseE)\n  done\n\n\ndefinition no_redundant :: \"Coin multiset \\<Rightarrow> bool\" where\n  \"no_redundant C \\<equiv> \\<forall>c n. redundant_since c = Some n \\<longrightarrow> count C c < n\"\n\n\nlemma no_redundant_empty: \"no_redundant {#}\"\n  apply(unfold no_redundant_def)\n  apply(auto)\n  apply(case_tac c)\n  apply(auto)\n  done\n\n\nlemma no_redundant_singleton: \"no_redundant {#c#}\"\n  apply(unfold no_redundant_def)\n  apply(rule allI)\n  apply(case_tac ca)\n  apply(auto)\n  done\n\n\nlemma no_redundant_add_imp_no_redundant[rule_format]: \"no_redundant (add_mset c C) \\<longrightarrow> no_redundant C\"\n  apply(auto simp add: no_redundant_def)\n  done\n\n\nlemma no_redundant_not_no_redundant_addD: \"\\<lbrakk> no_redundant C; \\<not> no_redundant (add_mset c C) \\<rbrakk> \\<Longrightarrow> redundant_since c = Some (Suc (count C c))\"\n  apply(unfold no_redundant_def not_all not_imp not_less)\n  apply(elim exE conjE)\n  apply(drule_tac x=x in spec)\n  apply(drule_tac x=xa in spec)\n  apply(drule mp)\n  apply(assumption)\n  apply(subst (asm) count_add_mset)\n  apply(case_tac \"c=x\")\n  apply(subst (asm) if_P)\n  apply(assumption)\n  apply(drule le_Suc_flip_le)\n  apply(assumption)\n  apply(clarify)\n  apply(subst (asm) if_not_P)\n  apply(assumption)\n  apply(subst (asm) not_less[symmetric])\n  apply(erule notE)\n  apply(assumption)\n  done\n\n\nlemma redundant_since_eq_Some_SucD: \"\\<lbrakk> redundant_since c = Some (Suc (count C c)); next_Coin c = Some c' \\<rbrakk> \\<Longrightarrow> val (replicate_mset (count C c) c) \\<le> val {#c'#}\"\n  apply(subst val_replicate_mset_count)\n  apply(subst val_singleton)\n  apply(case_tac c)\n  apply(auto)\n  done\n\n\nlemma not_no_redundant_imp_not_normal[rule_format]: \"\\<not>no_redundant C \\<longrightarrow> \\<not>normal C\"\n  apply(induct C)\n  apply(rule impI)\n  apply(erule notE)\n  apply(rule no_redundant_empty)\n\n  apply(rule impI)\n  apply(case_tac \"\\<not>no_redundant C\")\n  apply(drule mp)\n  apply(assumption)\n  apply(erule_tac Q=\"normal C\" in contrapos_nn)\n  apply(erule normal_add_imp_normal)\n\n  apply(subst (asm) not_not)\n  apply(drule no_redundant_not_no_redundant_addD)\n  apply(assumption)\n  apply(subst normal_def)\n  apply(unfold not_all not_imp size_add_mset not_le less_Suc_eq_le)\n  apply(frule redundant_sinceD)\n  apply(elim exE)\n  apply(rule_tac x=\"C + {#c'#} - replicate_mset (count C x) x\" in exI)\n  apply(rule conjI)\n  apply(subst val_add)\n  apply(subst val_diff)\n  apply(rule subset_plus_weak)\n  apply(rule replicate_mset_subseteq)\n  apply(subst val_plus)\n  apply(subst a_plus_b_eq_b_plus_c_minus_d)\n  apply(erule redundant_since_eq_Some_SucD)\n  apply(assumption)\n  apply(subst val_replicate_mset_count)\n  apply(drule_tac val_yen_unit_next_Coin)\n  apply(assumption)\n  apply(subst val_singleton)\n  apply(erule_tac t=\"val_yen_unit c'\" in ssubst)\n  apply(subst mult_Suc)\n  apply(subst diff_add_inverse2)\n  apply(rule refl)\n\n  apply(subst size_Diff_submset)\n  apply(rule subset_plus_weak)\n  apply(rule replicate_mset_subseteq)\n  apply(subst size_union)\n  apply(subst size_single)\n  apply(subst size_replicate_mset)\n  apply(drule redundant_since_gtD)\n  apply(subst (asm) less_Suc_eq_le)\n  apply(rule a_plus_b_minus_c_le_a)\n  apply(assumption)\n  done\n\n\ntheorem normal_imp_no_redundant: \"normal C \\<Longrightarrow> no_redundant C\"\n  apply(erule contrapos_pp)\n  apply(erule not_no_redundant_imp_not_normal)\n  done\n\n\nlemma x[rule_format]: \"no_redundant C \\<longrightarrow> val C = val C' \\<longrightarrow> size C \\<le> size C' \\<longrightarrow>\n       no_redundant (add_mset x C) \\<longrightarrow> val (add_mset x C) = val C' \\<longrightarrow> size (add_mset x C) \\<le> size C'\"\n  apply(induct C')\n  apply(force simp add: val_empty val_0)\n\n  apply(clarsimp simp add: val_add)\n  apply(case_tac x)\n  apply(auto)\n  done\n\n\nlemma \"no_redundant C \\<longrightarrow> val C = val C' \\<longrightarrow> size C \\<le> size C'\"\n  apply(induct C)\n  apply(intro impI)\n  apply(subst size_empty)\n  apply(rule le0)\n  apply(clarify)\n  oops\n\n\ntheorem no_redundant_imp_normal[rule_format]: \"no_redundant C \\<longrightarrow> normal C\"\n  apply(unfold no_redundant_def normal_def)\n  oops\n\n\ntheorem normal_uniq: \"\\<lbrakk> normal C1; normal C2; val C1 = val C2 \\<rbrakk> \\<Longrightarrow> C1 = C2\"\n  apply(auto simp add: normal_def)\n  oops\n\n\ntheorem normal_total: \"\\<forall>v. \\<exists>C. v = val C \\<and> normal C\"\n  apply(unfold normal_def)\n  oops\n\n\ntheorem \"\\<lbrakk> normal C0; normal C2 \\<rbrakk> \\<Longrightarrow> \\<exists>C1. C1 \\<subseteq># C0 \\<and> normal (C0 - C1 + C2)\"\n  oops\n\n\nsubsection \"Normalize\"\ndefinition normalize1 :: \"Coin \\<Rightarrow> Coin multiset \\<Rightarrow> Coin multiset\" where\n  \"normalize1 c C \\<equiv> case (next_Coin c, redundant_since c) of\n    (Some c', Some n) \\<Rightarrow>\n      C - (replicate_mset (count C c) c)\n      + (replicate_mset ((count C c) div n) c')\n      + (replicate_mset ((count C c) mod n) c) |\n    _ \\<Rightarrow> C\"\n\n\nlemma redundant_since_normnalize1_D: \"\\<lbrakk> redundant_since c = Some n; C' = normalize1 c C; next_Coin c = Some c' \\<rbrakk> \\<Longrightarrow>\n    C' = C - (replicate_mset (count C c) c)\n       + (replicate_mset ((count C c) div n) c')\n       + (replicate_mset ((count C c) mod n) c)\"\n  apply(unfold normalize1_def)\n  apply(auto)\n  done\n\n\ntheorem same_val_size_leI: \"\\<lbrakk> redundant_since c = Some m; count C c \\<ge> m; C' = normalize1 c C \\<rbrakk> \\<Longrightarrow> val C = val C' \\<and> size C' < size C\"\n  apply(frule redundant_sinceD)\n  apply(elim exE)\n  apply(frule redundant_since_normnalize1_D)\n  apply(assumption)\n  apply(assumption)\n  apply(erule_tac s=\" C - replicate_mset (count C c) c + replicate_mset (count C c div m) c' + replicate_mset (count C c mod m) c\" in ssubst)\n  apply(auto simp add: val_plus val_replicate_mset_count)\n  apply(subst val_diff)\n  apply(rule replicate_mset_subseteq)\n  apply(subst val_replicate_mset_count)\n  apply(subst a_eq_a_minus_b_plus_c_plus_d_is_b_eq_c_plus_d)\n  apply(rule count_le_val)\n  apply(rule n_eq_div_plus_mod)\n  apply(force intro: val_yen_unit_next_Coin)\n  apply(subst size_Diff_submset)\n  apply(rule replicate_mset_subseteq)\n  apply(subst size_replicate_mset)\n  apply(subst a_minus_b_plus_c_plus_d_le_a)\n  apply(rule count_le_size)\n  apply(rule le_div_plus_mod)\n  apply(assumption)\n  apply(case_tac c)\n  apply(auto)\n  done\n\n\nend\n", "meta": {"author": "Kuniwak", "repo": "isabelle-coin", "sha": "381178e18de50f0301ce90e251927477e13dda1b", "save_path": "github-repos/isabelle/Kuniwak-isabelle-coin", "path": "github-repos/isabelle/Kuniwak-isabelle-coin/isabelle-coin-381178e18de50f0301ce90e251927477e13dda1b/Coin.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8244619306896955, "lm_q1q2_score": 0.7562811198849256}}
{"text": "section \\<open>Helpers\\<close>\n\ntheory Helpers imports Main begin\n\ntext \\<open>\n  First, we will prove a few lemmas unrelated to graphs or Menger's Theorem.  These lemmas\n  will simplify some of the other proof steps.\n\\<close>\n\ntext \\<open>\n  If two finite sets have different cardinality, then there exists an element in the larger set\n  that is not in the smaller set.\n\\<close>\nlemma card_finite_less_ex:\n  assumes finite_A: \"finite A\"\n      and finite_B: \"finite B\"\n      and card_AB: \"card A < card B\"\n  shows \"\\<exists>b \\<in> B. b \\<notin> A\"\nproof-\n  have \"card (B - A) > 0\" using finite_A finite_B card_AB\n    by (meson Diff_eq_empty_iff card_eq_0_iff card_mono finite_Diff gr0I leD)\n  then show ?thesis using finite_B\n    by (metis Diff_eq_empty_iff card_0_eq finite_Diff neq_iff subsetI)\nqed\n\ntext \\<open>\n  The cardinality of the union of two disjoint finite sets is the sum of their cardinalities\n  even if we intersect everything with a fixed set @{term X}.\n\\<close>\nlemma card_intersect_sum_disjoint:\n  assumes \"finite B\" \"finite C\" \"A = B \\<union> C\" \"B \\<inter> C = {}\"\n    shows \"card (A \\<inter> X) = card (B \\<inter> X) + card (C \\<inter> X)\"\n  by (metis (no_types, lifting) Un_Diff_Int assms card_Un_disjoint finite_Int inf.commute\n      inf_sup_distrib2 sup_eq_bot_iff)\n\ntext \\<open>\n  If @{term x} is in a list @{term xs} but is not its last element, then it is also in\n  @{term \"butlast xs\"}.\n\\<close>\nlemma set_butlast: \"\\<lbrakk> x \\<in> set xs; x \\<noteq> last xs \\<rbrakk> \\<Longrightarrow> x \\<in> set (butlast xs)\"\n  by (metis butlast.simps(2) in_set_butlast_appendI last.simps last_appendR\n      list.set_intros(1) split_list_first)\n\ntext \\<open>\n  If a property @{term P} is satisfiable and if we have a weight measure mapping into the natural\n  numbers, then there exists an element of minimum weight satisfying @{term P} because the\n  natural numbers are well-ordered.\n\\<close>\nlemma arg_min_ex:\n  fixes P :: \"'a \\<Rightarrow> bool\" and weight :: \"'a \\<Rightarrow> nat\"\n  assumes \"\\<exists>x. P x\"\n  obtains x where \"P x\" \"\\<And>y. P y \\<Longrightarrow> weight x \\<le> weight y\"\nproof (cases \"\\<exists>x. P x \\<and> weight x = 0\")\n  case True then show ?thesis using that by auto\nnext\n  case False then show ?thesis\n    using that ex_least_nat_le[of \"\\<lambda>n. \\<exists>x. P x \\<and> weight x = n\"] assms by (metis not_le_imp_less)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Menger/Helpers.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.8652240930029117, "lm_q1q2_score": 0.7562726886862816}}
{"text": "theory List_util\n  imports Main\nbegin\n\ninductive same_length :: \"'a list \\<Rightarrow> 'b list \\<Rightarrow> bool\" where\n  same_length_Nil: \"same_length [] []\" |\n  same_length_Cons: \"same_length xs ys \\<Longrightarrow> same_length (x # xs) (y # ys)\"\n\ncode_pred same_length .\n\nlemma same_length_iff_eq_lengths: \"same_length xs ys \\<longleftrightarrow> length xs = length ys\"\nproof\n  assume \"same_length xs ys\"\n  then show \"length xs = length ys\"\n    by (induction xs ys rule: same_length.induct) simp_all\nnext\n  assume \"length xs = length ys\"\n  then show \"same_length xs ys\"\n  proof (induction xs arbitrary: ys)\n    case Nil\n    then show ?case\n      by (simp add: same_length_Nil)\n  next\n    case (Cons x xs)\n    then show ?case\n      by (metis length_Suc_conv same_length_Cons)\n  qed\nqed\n\nlemma same_length_Cons:\n  \"same_length (x # xs) ys \\<Longrightarrow> \\<exists>y ys'. ys = y # ys'\"\n  \"same_length xs (y # ys) \\<Longrightarrow> \\<exists>x xs'. xs = x # xs'\"\nproof -\n  assume \"same_length (x # xs) ys\"\n  then show \"\\<exists>y ys'. ys = y # ys'\"\n    by (induction \"x # xs\" ys rule: same_length.induct) simp\nnext\n  assume \"same_length xs (y # ys)\"\n  then show \"\\<exists>x xs'. xs = x # xs'\"\n    by (induction xs \"y # ys\" rule: same_length.induct) simp\nqed\n\n\nsection \\<open>nth\\_opt\\<close>\n\nfun nth_opt where\n  \"nth_opt (x # _) 0 = Some x\" |\n  \"nth_opt (_ # xs) (Suc n) = nth_opt xs n\" |\n  \"nth_opt _ _ = None\"\n\nlemma nth_opt_eq_Some_conv: \"nth_opt xs n = Some x \\<longleftrightarrow> n < length xs \\<and> xs ! n = x\"\n  by (induction xs n rule: nth_opt.induct; simp)\n\nlemmas nth_opt_eq_SomeD[dest] = nth_opt_eq_Some_conv[THEN iffD1]\n\n\nsection \\<open>Generic lemmas\\<close>\n\nlemma list_rel_imp_pred1:\n  assumes\n    \"list_all2 R xs ys\" and\n    \"\\<And>x y. (x, y) \\<in> set (zip xs ys) \\<Longrightarrow> R x y \\<Longrightarrow> P x\"\n  shows \"list_all P xs\"\n  using assms\n  by (induction xs ys rule: list.rel_induct) auto\n\nlemma list_rel_imp_pred2:\n  assumes\n    \"list_all2 R xs ys\" and\n    \"\\<And>x y. (x, y) \\<in> set (zip xs ys) \\<Longrightarrow> R x y \\<Longrightarrow> P y\"\n  shows \"list_all P ys\"\n  using assms\n  by (induction xs ys rule: list.rel_induct) auto\n\nlemma eq_append_conv_conj: \"(zs = xs @ ys) = (xs = take (length xs) zs \\<and> ys = drop (length xs) zs)\"\n  by (metis append_eq_conv_conj)\n\nlemma list_all_list_updateI: \"list_all P xs \\<Longrightarrow> P x \\<Longrightarrow> list_all P (list_update xs n x)\"\n  by (induction xs arbitrary: n) (auto simp add: nat.split_sels(2))\n\nlemmas list_all2_update1_cong = list_all2_update_cong[of _ _ ys _ \"ys ! i\" i for ys i, simplified]\nlemmas list_all2_update2_cong = list_all2_update_cong[of _ xs _ \"xs ! i\" _ i for xs i, simplified]\n\nlemma map_list_update_id:\n  \"f (xs ! pc) = f instr \\<Longrightarrow> map f (xs[pc := instr]) = map f xs\"\n  using list_update_id map_update by metis\n\nlemma list_all_eq_const_imp_replicate:\n  assumes \"list_all (\\<lambda>x. x = y) xs\"\n  shows \"xs = replicate (length xs) y\"\n  using assms\n  by (induction xs; simp)\n\nlemma list_all_eq_const_imp_replicate':\n  assumes \"list_all ((=) y) xs\"\n  shows \"xs = replicate (length xs) y\"\n  using assms\n  by (induction xs; simp)\n\nlemma list_all_eq_const_replicate_lhs[intro]:\n  \"list_all (\\<lambda>x. y = x) (replicate n y)\"\n  by (simp add: list_all_length)\n\nlemma list_all_eq_const_replicate_rhs[intro]:\n  \"list_all (\\<lambda>x. x = y) (replicate n y)\"\n  by (simp add: list_all_length)\n\nlemma list_all_eq_const_replicate[simp]: \"list_all ((=) c) (replicate n c)\"\n  by (simp add: list_all_length)\n\nlemma replicate_eq_map:\n  assumes \"n = length xs\" and \"\\<And>y. y \\<in> set xs \\<Longrightarrow> f y = x\"\n  shows \"replicate n x = map f xs\"\n  using assms\nproof (induction xs arbitrary: n)\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons x xs)\n  thus ?case by (cases n; auto)\nqed\n\nlemma replicate_eq_impl_Ball_eq:\n  shows \"replicate n c = xs \\<Longrightarrow> (\\<forall>x \\<in> set xs. x = c)\"\n  by (meson in_set_replicate)\n\nlemma rel_option_map_of:\n  assumes \"list_all2 (rel_prod (=) R) xs ys\"\n  shows \"rel_option R (map_of xs l) (map_of ys l)\"\n  using assms\nproof (induction xs ys rule: list.rel_induct)\n  case Nil\n  thus ?case by simp\nnext\n  case (Cons x xs y ys)\n  from Cons.hyps have \"fst x = fst y\" and \"R (snd x) (snd y)\"\n    by (simp_all add: rel_prod_sel)\n  show ?case\n  proof (cases \"l = fst y\")\n    case True\n    then show ?thesis\n      by (simp add: \\<open>fst x = fst y\\<close> \\<open>R (snd x) (snd y)\\<close>)\n  next\n    case False\n    then show ?thesis\n      using Cons.IH\n      by (simp add: \\<open>fst x = fst y\\<close> )\n  qed\nqed\n\nlemma list_all2_rel_prod_nth:\n  assumes \"list_all2 (rel_prod R1 R2) xs ys\" and \"n < length xs\"\n  shows \"R1 (fst (xs ! n)) (fst (ys ! n)) \\<and> R2 (snd (xs ! n)) (snd (ys ! n))\"\n  using assms\nproof (induction n arbitrary: xs ys)\n  case 0\n  then show ?case\n    using assms(1,2)\n    by (auto elim: list.rel_cases)\nnext\n  case (Suc n)\n  then obtain x xs' y ys' where xs_def[simp]: \"xs = x # xs'\" and ys_def[simp]: \"ys = y # ys'\"\n    by (auto elim: list.rel_cases)\n  show ?case\n    using Suc.prems Suc.IH[of xs' ys']\n    by force\nqed\n\nlemma list_all2_rel_prod_fst_hd:\n  assumes \"list_all2 (rel_prod R1 R2) xs ys\" and \"xs \\<noteq> [] \\<or> ys \\<noteq> []\"\n  shows \"R1 (fst (hd xs)) (fst (hd ys)) \\<and> R2 (snd (hd xs)) (snd (hd ys))\"\n  using assms\n  by (auto simp: rel_prod_sel elim: list.rel_cases)\n\nlemma list_all2_rel_prod_fst_last:\n  assumes \"list_all2 (rel_prod R1 R2) xs ys\" and \"xs \\<noteq> [] \\<or> ys \\<noteq> []\"\n  shows \"R1 (fst (last xs)) (fst (last ys)) \\<and> R2 (snd (last xs)) (snd (last ys))\"\nproof -\n  have \"xs \\<noteq> []\" and \"ys \\<noteq> []\"\n    using assms by (auto elim: list.rel_cases)\n  moreover have \"length xs = length ys\"\n    by (rule assms(1)[THEN list_all2_lengthD])\n  ultimately show ?thesis\n    using list_all2_rel_prod_nth[OF assms(1)]\n    by (simp add: last_conv_nth)\nqed\n\nlemma list_all_nthD[intro]: \"list_all P xs \\<Longrightarrow> n < length xs \\<Longrightarrow> P (xs ! n)\"\n  by (simp add: list_all_length)\n\nlemma \"list_all P xs \\<Longrightarrow> \\<forall>x\\<in> set xs. P x\"\n  using list_all_iff list.pred_set\n  by (simp add: list_all_iff)\n\n\nlemma list_all_map_of_SomeD:\n  assumes \"list_all P kvs\" and \"map_of kvs k = Some v\"\n  shows \"P (k, v)\"\n  using assms\n  unfolding list.pred_set\n  by (auto dest: map_of_SomeD)\n\nlemma list_all_not_nthD:\"list_all P xs \\<Longrightarrow> \\<not> P (xs ! n) \\<Longrightarrow> length xs \\<le> n\"\nproof (induction xs arbitrary: n)\n  case Nil\n  then show ?case\n    by simp\nnext\n  case (Cons x xs)\n  then show ?case\n    by (cases n) simp_all\nqed\n\nlemma list_all_butlast_not_nthD: \"list_all P (butlast xs) \\<Longrightarrow> \\<not> P (xs ! n) \\<Longrightarrow> length xs \\<le> Suc n\"\n  using list_all_not_nthD[of _ \"butlast xs\" for xs, simplified]\n  by (smt (z3) One_nat_def Suc_pred le_Suc_eq length_butlast length_greater_0_conv less_Suc_eq list.pred_inject(1) list_all_not_nthD not_le nth_butlast)\n\nlemma list_all_replicateI[intro]: \"P x \\<Longrightarrow> list_all P (replicate n x)\"\n  unfolding list.pred_set\n  by simp\n\nlemma map_eq_append_replicate_conv:\n  assumes \"map f xs = replicate n x @ ys\"\n  shows \"map f (take n xs) = replicate n x\"\n  using assms\n  by (metis append_eq_conv_conj length_replicate take_map)\n\nlemma map_eq_replicate_imp_list_all_const:\n  \"map f xs = replicate n x \\<Longrightarrow> n = length xs \\<Longrightarrow> list_all (\\<lambda>y. f y = x) xs\"\n  by (induction xs arbitrary: n) simp_all\n\nlemma map_eq_replicateI: \"length xs = n \\<Longrightarrow> (\\<And>x. x \\<in> set xs \\<Longrightarrow> f x = c) \\<Longrightarrow> map f xs = replicate n c\"\n  by (induction xs arbitrary: n) auto\n\nlemma list_all_dropI[intro]: \"list_all P xs \\<Longrightarrow> list_all P (drop n xs)\"\n  by (metis append_take_drop_id list_all_append)\n\n\nsection \\<open>Non-empty list\\<close>\n\ntype_synonym 'a nlist = \"'a \\<times> 'a list\"\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Interpreter_Optimizations/List_util.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.8652240912652671, "lm_q1q2_score": 0.7562726814911799}}
{"text": "(*  Title:      Sigma_Algebra.thy\n\n    Author:     Stefan Richter, Markus Wenzel, TU Muenchen\n    License:    LGPL\n\nChanges for Accordance to Joe Hurd's conventions\nand additions by Stefan Richter 2002\n*)\n\nheader {* Sigma algebras *}\n\ntheory Sigma_Algebra imports Main begin\n\ntext {* The $\\isacommand {theory}$ command commences a formal document and enumerates the\n  theories it depends on. With the @{text Main} theory, a standard\n  selection of useful HOL theories excluding the real\n  numbers is loaded. This theory includes and builds upon a tiny theory of the\n  same name by Markus Wenzel. This theory as well as @{text Measure}\n  in \\ref{sec:measure-spaces} is heavily\n  influenced by Joe Hurd's thesis \\cite{hurd2002} and has been designed to keep the terminology as\n  consistent as possible with that work.\n\n  Sigma algebras are an elementary concept in measure\n  theory. To measure --- that is to integrate --- functions, we first have\n  to measure sets. Unfortunately, when dealing with a large universe,\n  it is often not possible to consistently assign a measure to every\n  subset. Therefore it is necessary to define the set of measurable\n  subsets of the universe. A sigma algebra is such a set that has\n  three very natural and desirable properties. *}\n\ndefinition\n  sigma_algebra:: \"'a set set \\<Rightarrow> bool\" where\n  \"sigma_algebra A \\<longleftrightarrow>\n  {} \\<in> A \\<and> (\\<forall>a. a \\<in> A \\<longrightarrow> -a \\<in> A) \\<and>\n  (\\<forall>a. (\\<forall> i::nat. a i \\<in> A) \\<longrightarrow> (\\<Union>i. a i) \\<in> A)\"\n\ntext {*\n  The $\\isacommand {definition}$ command defines new constants, which\n  are just named functions in HOL. Mind that the third condition\n  expresses the fact that the union of countably many sets in $A$ is\n  again a set in $A$ without explicitly defining the notion of\n  countability.\n\n  Sigma algebras can naturally be created as the closure of any set of\n  sets with regard to the properties just postulated. Markus Wenzel\n  wrote the following\n  inductive definition of the $\\isa {sigma}$ operator.  *}\n\n\ninductive_set\n  sigma :: \"'a set set \\<Rightarrow> 'a set set\"\n  for A :: \"'a set set\"\n  where\n    basic: \"a \\<in> A \\<Longrightarrow> a \\<in> sigma A\"\n  | empty: \"{} \\<in> sigma A\"\n  | complement: \"a \\<in> sigma A \\<Longrightarrow> -a \\<in> sigma A\"\n  | Union: \"(\\<And>i::nat. a i \\<in> sigma A) \\<Longrightarrow> (\\<Union>i. a i) \\<in> sigma A\"\n\n\ntext {* He also proved the following basic facts. The easy proofs are omitted.\n*}\n\ntheorem sigma_UNIV: \"UNIV \\<in> sigma A\"\n(*<*)proof -\n  have \"{} \\<in> sigma A\" by (rule sigma.empty)\n  hence \"-{} \\<in> sigma A\" by (rule sigma.complement)\n  also have \"-{} = UNIV\" by simp\n  finally show ?thesis .\nqed(*>*)\n\n\ntheorem sigma_Inter:\n  \"(\\<And>i::nat. a i \\<in> sigma A) \\<Longrightarrow> (\\<Inter>i. a i) \\<in> sigma A\"\n(*<*) proof -\n  assume \"\\<And>i::nat. a i \\<in> sigma A\"\n  hence \"\\<And>i::nat. -(a i) \\<in> sigma A\" by (rule sigma.complement)\n  hence \"(\\<Union>i. -(a i)) \\<in> sigma A\" by (rule sigma.Union)\n  hence \"-(\\<Union>i. -(a i)) \\<in> sigma A\" by (rule sigma.complement)\n  also have \"-(\\<Union>i. -(a i)) = (\\<Inter>i. a i)\" by simp\n  finally show ?thesis .\nqed(*>*)\n\ntext {*It is trivial to show the connection between our first\n  definitions. We use the opportunity to introduce the proof syntax.*}\n\n\ntheorem assumes sa: \"sigma_algebra A\"\n  -- \"Named premises are introduced like this.\"\n\n  shows sigma_sigma_algebra: \"sigma A = A\"\nproof\n\n  txt {*The $\\isacommand {proof}$ command alone invokes a single standard rule to\n    simplify the goal. Here the following two subgoals emerge.*}\n\n  show \"A \\<subseteq> sigma A\"\n    -- {*The $\\isacommand {show}$ command starts the proof of a subgoal.*}\n\n    by (auto simp add: sigma.basic)\n\n  txt {* This is easy enough to be solved by an automatic step,\n    indicated by the keyword $\\isacommand {by}$. The method $\\isacommand {auto}$ is stated in parentheses, with attributes to it following.  In\n    this case, the first introduction rule for the $\\isacommand {sigma}$\n    operator is given as an extra simplification rule. *}\n\n  show \"sigma A \\<subseteq> A\"\n  proof\n\n    txt {*Because this goal is not quite as trivial, another proof is\n      invoked, delimiting a block as in a programming language.*}\n\n    fix x\n    -- \"A new named variable is introduced.\"\n\n    assume \"x \\<in> sigma A\"\n\n    txt {*An assumption is made that must be justified by the current proof\n      context. In this case the corresponding fact had been generated\n      by a rule automatically invoked by the inner $\\isacommand {proof}$\n      command.*}\n\n    from this sa show \"x \\<in> A\"\n\n      txt {* Named facts can explicitly be given to the proof methods using\n        $\\isacommand {from}$. A special name is @{text this}, which denotes\n        current facts generated by the last command. Usually $\\isacommand\n        {from}$ @{text \"this sa\"} --- remember that @{text sa} is an assumption from above\n        --- is abbreviated to $\\isacommand {with}$ @{text \"sa\"}, but in this case the order of\n        facts is relevant for the following method and $\\isacommand\n        {with}$\n        would have put the current facts last. *}\n\n      by (induct rule: sigma.induct) (auto simp add: sigma_algebra_def)\n\n    txt {*Two methods may be carried out at $\\isacommand {by}$. The first\n      one applies induction here via the canonical rule generated by the\n      inductive definition above, while the latter solves the\n      resulting subgoals by an automatic step involving\n      simplification.*}\n\n  qed\nqed\n\ntext \"These two steps finish their respective proofs, checking\n  that all subgoals have been proven.\"\n\ntext {* To end this theory we prove a special case of the @{text\n  sigma_Inter} theorem above. It seems trivial that\n  the fact holds for two sets as well as for countably many.\n  We get a first taste of the cost of formal reasoning here, however. The\n  idea must be made precise by exhibiting a concrete sequence of\n  sets. *}\n\nprimrec trivial_series:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> (nat \\<Rightarrow> 'a set)\"\nwhere\n  \"trivial_series a b 0 = a\"\n| \"trivial_series a b (Suc n) = b\"\n\ntext {*Using $\\isacommand {primrec}$, primitive recursive functions over\n  inductively defined data types --- the natural numbers in this case ---\n  may be constructed.*}\n\n\ntheorem assumes s: \"sigma_algebra A\" and a: \"a \\<in> A\" and b: \"b \\<in> A\"\n  shows sigma_algebra_inter: \"a \\<inter> b \\<in> A\"\nproof -\n    -- {*This form of $\\isacommand {proof}$ foregoes the application of a rule.*}\n\n  have \"a \\<inter> b = (\\<Inter>i::nat. trivial_series a b i)\"\n\n    txt {*Intermediate facts that do not solve any subgoals yet are established this way.*}\n\n  proof (rule set_eqI)\n\n    txt {*The  $\\isacommand {proof}$ command may also take one explicit method\n      as an argument like the single rule application in this instance.*}\n\n    fix x\n\n    {\n      fix i\n      assume \"x \\<in> a \\<inter> b\"\n      hence \"x \\<in> trivial_series a b i\" by (cases i) auto\n        -- {*This is just an abbreviation for $\\isacommand {\"from this have\"}$.*}\n    }\n\n    txt {*Curly braces can be used to explicitly delimit\n      blocks. In conjunction with $\\isacommand {fix}$, universal\n      quantification over the fixed variable $i$ is achieved\n      for the last statement in the block, which is exported to the\n      enclosing block.*}\n\n    hence \"x \\<in> a \\<inter> b \\<Longrightarrow> \\<forall>i. x \\<in> trivial_series a b i\"\n      by fast\n    also\n\n    txt {*The statement $\\isacommand {also}$ introduces calculational\n      reasoning. This basically amounts to collecting facts. With\n      $\\isacommand {also}$, the current fact is added to a special list of\n      theorems called the calculation and\n      an automatically selected transitivity rule\n      is additionally applied from the second collected fact on.*}\n\n    { assume \"\\<And>i. x \\<in> trivial_series a b i\"\n      hence \"x \\<in> trivial_series a b 0\" and \"x \\<in> trivial_series a b 1\"\n        by this+\n      hence \"x \\<in> a \\<inter> b\"\n        by simp\n    }\n    hence \"\\<forall>i. x \\<in> trivial_series a b i \\<Longrightarrow> x \\<in> a \\<inter> b\"\n      by blast\n\n    ultimately have \"x \\<in> a \\<inter> b = (\\<forall>i::nat. x \\<in> trivial_series a b i)\" ..\n\n    txt {*The accumulated calculational facts including the current one\n      are exposed to the next statement by  $\\isacommand {ultimately}$ and\n      the calculation list is then erased. The two dots after the\n      statement here indicate proof by a single automatically\n      selected rule.*}\n\n    also have \"\\<dots> =  (x \\<in> (\\<Inter>i::nat. trivial_series a b i))\"\n      by simp\n    finally show \"x \\<in> a \\<inter> b = (x \\<in> (\\<Inter>i::nat. trivial_series a b i))\" .\n\n    txt {*The $\\isacommand {finally}$ directive behaves like $\\isacommand {ultimately}$\n      with the addition of a further transitivity rule application. A\n      single dot stands for proof by assumption.*}\n\n  qed\n\n  moreover have \"(\\<Inter>i::nat. trivial_series a b i) \\<in> A\"\n  proof -\n    { fix i\n      from a b have \"trivial_series a b i \\<in> A\"\n        by (cases i) auto\n    }\n    hence \"\\<And>i. trivial_series a b i \\<in> sigma A\"\n      by (simp only: sigma.basic)\n    hence \"(\\<Inter>i::nat. trivial_series a b i) \\<in> sigma A\"\n      by (simp only: sigma_Inter)\n    with s show ?thesis\n      by (simp only: sigma_sigma_algebra)\n  qed\n\n  ultimately show ?thesis by simp\nqed\n\ntext {* Of course, a like theorem holds for union instead of\n  intersection.  But as we will not need it in what follows, the\n  theory is finished with the following easy properties instead.\n  Note that the former is a kind of generalization of the last result and\n  could be used to  shorten its proof. Unfortunately, this one was needed ---\n  and therefore found --- only late in the development.\n  *}\n\ntheorem sigma_INTER:\n  assumes a:\"(\\<And>i::nat. i \\<in> S \\<Longrightarrow> a i \\<in> sigma A)\"\n  shows \"(\\<Inter>i\\<in>S. a i) \\<in> sigma A\"(*<*)\nproof -\n  from a have \"\\<And>i. (if i\\<in>S then {} else UNIV) \\<union> a i \\<in> sigma A\"\n    by (simp add: sigma.intros sigma_UNIV)\n  hence \"(\\<Inter>i. (if i\\<in>S then {} else UNIV) \\<union> a i) \\<in> sigma A\"\n    by (rule sigma_Inter)\n  also have \"(\\<Inter>i. (if i\\<in>S then {} else UNIV) \\<union> a i) = (\\<Inter>i\\<in>S. a i)\"\n    by force\n  finally show ?thesis .\nqed(*>*)\n\n\nlemma assumes s: \"sigma_algebra a\" shows sigma_algebra_UNIV: \"UNIV \\<in> a\"(*<*)\nproof -\n  from s have \"{}\\<in>a\" by (unfold sigma_algebra_def) blast\n  with s show ?thesis by (unfold sigma_algebra_def) auto\nqed(*>*)\n\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Integration/Sigma_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.8652240930029118, "lm_q1q2_score": 0.756272677333749}}
{"text": "(*  Title:      HOL/Lattice/CompleteLattice.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection {* Complete lattices *}\n\ntheory CompleteLattice imports Lattice begin\n\nsubsection {* Complete lattice operations *}\n\ntext {*\n  A \\emph{complete lattice} is a partial order with general\n  (infinitary) infimum of any set of elements.  General supremum\n  exists as well, as a consequence of the connection of infinitary\n  bounds (see \\S\\ref{sec:connect-bounds}).\n*}\n\nclass complete_lattice =\n  assumes ex_Inf: \"\\<exists>inf. is_Inf A inf\"\n\ntheorem ex_Sup: \"\\<exists>sup::'a::complete_lattice. is_Sup A sup\"\nproof -\n  from ex_Inf obtain sup where \"is_Inf {b. \\<forall>a\\<in>A. a \\<sqsubseteq> b} sup\" by blast\n  then have \"is_Sup A sup\" by (rule Inf_Sup)\n  then show ?thesis ..\nqed\n\ntext {*\n  The general @{text \\<Sqinter>} (meet) and @{text \\<Squnion>} (join) operations select\n  such infimum and supremum elements.\n*}\n\ndefinition\n  Meet :: \"'a::complete_lattice set \\<Rightarrow> 'a\" where\n  \"Meet A = (THE inf. is_Inf A inf)\"\ndefinition\n  Join :: \"'a::complete_lattice set \\<Rightarrow> 'a\" where\n  \"Join A = (THE sup. is_Sup A sup)\"\n\nnotation (xsymbols)\n  Meet  (\"\\<Sqinter>_\" [90] 90) and\n  Join  (\"\\<Squnion>_\" [90] 90)\n\ntext {*\n  Due to unique existence of bounds, the complete lattice operations\n  may be exhibited as follows.\n*}\n\nlemma Meet_equality [elim?]: \"is_Inf A inf \\<Longrightarrow> \\<Sqinter>A = inf\"\nproof (unfold Meet_def)\n  assume \"is_Inf A inf\"\n  then show \"(THE inf. is_Inf A inf) = inf\"\n    by (rule the_equality) (rule is_Inf_uniq [OF _ `is_Inf A inf`])\nqed\n\nlemma MeetI [intro?]:\n  \"(\\<And>a. a \\<in> A \\<Longrightarrow> inf \\<sqsubseteq> a) \\<Longrightarrow>\n    (\\<And>b. \\<forall>a \\<in> A. b \\<sqsubseteq> a \\<Longrightarrow> b \\<sqsubseteq> inf) \\<Longrightarrow>\n    \\<Sqinter>A = inf\"\n  by (rule Meet_equality, rule is_InfI) blast+\n\nlemma Join_equality [elim?]: \"is_Sup A sup \\<Longrightarrow> \\<Squnion>A = sup\"\nproof (unfold Join_def)\n  assume \"is_Sup A sup\"\n  then show \"(THE sup. is_Sup A sup) = sup\"\n    by (rule the_equality) (rule is_Sup_uniq [OF _ `is_Sup A sup`])\nqed\n\nlemma JoinI [intro?]:\n  \"(\\<And>a. a \\<in> A \\<Longrightarrow> a \\<sqsubseteq> sup) \\<Longrightarrow>\n    (\\<And>b. \\<forall>a \\<in> A. a \\<sqsubseteq> b \\<Longrightarrow> sup \\<sqsubseteq> b) \\<Longrightarrow>\n    \\<Squnion>A = sup\"\n  by (rule Join_equality, rule is_SupI) blast+\n\n\ntext {*\n  \\medskip The @{text \\<Sqinter>} and @{text \\<Squnion>} operations indeed determine\n  bounds on a complete lattice structure.\n*}\n\nlemma is_Inf_Meet [intro?]: \"is_Inf A (\\<Sqinter>A)\"\nproof (unfold Meet_def)\n  from ex_Inf obtain inf where \"is_Inf A inf\" ..\n  then show \"is_Inf A (THE inf. is_Inf A inf)\"\n    by (rule theI) (rule is_Inf_uniq [OF _ `is_Inf A inf`])\nqed\n\nlemma Meet_greatest [intro?]: \"(\\<And>a. a \\<in> A \\<Longrightarrow> x \\<sqsubseteq> a) \\<Longrightarrow> x \\<sqsubseteq> \\<Sqinter>A\"\n  by (rule is_Inf_greatest, rule is_Inf_Meet) blast\n\nlemma Meet_lower [intro?]: \"a \\<in> A \\<Longrightarrow> \\<Sqinter>A \\<sqsubseteq> a\"\n  by (rule is_Inf_lower) (rule is_Inf_Meet)\n\n\nlemma is_Sup_Join [intro?]: \"is_Sup A (\\<Squnion>A)\"\nproof (unfold Join_def)\n  from ex_Sup obtain sup where \"is_Sup A sup\" ..\n  then show \"is_Sup A (THE sup. is_Sup A sup)\"\n    by (rule theI) (rule is_Sup_uniq [OF _ `is_Sup A sup`])\nqed\n\nlemma Join_least [intro?]: \"(\\<And>a. a \\<in> A \\<Longrightarrow> a \\<sqsubseteq> x) \\<Longrightarrow> \\<Squnion>A \\<sqsubseteq> x\"\n  by (rule is_Sup_least, rule is_Sup_Join) blast\nlemma Join_lower [intro?]: \"a \\<in> A \\<Longrightarrow> a \\<sqsubseteq> \\<Squnion>A\"\n  by (rule is_Sup_upper) (rule is_Sup_Join)\n\n\nsubsection {* The Knaster-Tarski Theorem *}\n\ntext {*\n  The Knaster-Tarski Theorem (in its simplest formulation) states that\n  any monotone function on a complete lattice has a least fixed-point\n  (see @{cite \\<open>pages 93--94\\<close> \"Davey-Priestley:1990\"} for example).  This\n  is a consequence of the basic boundary properties of the complete\n  lattice operations.\n*}\n\ntheorem Knaster_Tarski:\n  assumes mono: \"\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\"\n  obtains a :: \"'a::complete_lattice\" where\n    \"f a = a\" and \"\\<And>a'. f a' = a' \\<Longrightarrow> a \\<sqsubseteq> a'\"\nproof\n  let ?H = \"{u. f u \\<sqsubseteq> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof -\n    have ge: \"f ?a \\<sqsubseteq> ?a\"\n    proof\n      fix x assume x: \"x \\<in> ?H\"\n      then have \"?a \\<sqsubseteq> x\" ..\n      then have \"f ?a \\<sqsubseteq> f x\" by (rule mono)\n      also from x have \"... \\<sqsubseteq> x\" ..\n      finally show \"f ?a \\<sqsubseteq> x\" .\n    qed\n    also have \"?a \\<sqsubseteq> f ?a\"\n    proof\n      from ge have \"f (f ?a) \\<sqsubseteq> f ?a\" by (rule mono)\n      then show \"f ?a \\<in> ?H\" ..\n    qed\n    finally show ?thesis .\n  qed\n\n  fix a'\n  assume \"f a' = a'\"\n  then have \"f a' \\<sqsubseteq> a'\" by (simp only: leq_refl)\n  then have \"a' \\<in> ?H\" ..\n  then show \"?a \\<sqsubseteq> a'\" ..\nqed\n\ntheorem Knaster_Tarski_dual:\n  assumes mono: \"\\<And>x y. x \\<sqsubseteq> y \\<Longrightarrow> f x \\<sqsubseteq> f y\"\n  obtains a :: \"'a::complete_lattice\" where\n    \"f a = a\" and \"\\<And>a'. f a' = a' \\<Longrightarrow> a' \\<sqsubseteq> a\"\nproof\n  let ?H = \"{u. u \\<sqsubseteq> f u}\"\n  let ?a = \"\\<Squnion>?H\"\n  show \"f ?a = ?a\"\n  proof -\n    have le: \"?a \\<sqsubseteq> f ?a\"\n    proof\n      fix x assume x: \"x \\<in> ?H\"\n      then have \"x \\<sqsubseteq> f x\" ..\n      also from x have \"x \\<sqsubseteq> ?a\" ..\n      then have \"f x \\<sqsubseteq> f ?a\" by (rule mono)\n      finally show \"x \\<sqsubseteq> f ?a\" .\n    qed\n    have \"f ?a \\<sqsubseteq> ?a\"\n    proof\n      from le have \"f ?a \\<sqsubseteq> f (f ?a)\" by (rule mono)\n      then show \"f ?a \\<in> ?H\" ..\n    qed\n    from this and le show ?thesis by (rule leq_antisym)\n  qed\n\n  fix a'\n  assume \"f a' = a'\"\n  then have \"a' \\<sqsubseteq> f a'\" by (simp only: leq_refl)\n  then have \"a' \\<in> ?H\" ..\n  then show \"a' \\<sqsubseteq> ?a\" ..\nqed\n\n\nsubsection {* Bottom and top elements *}\n\ntext {*\n  With general bounds available, complete lattices also have least and\n  greatest elements.\n*}\n\ndefinition\n  bottom :: \"'a::complete_lattice\"  (\"\\<bottom>\") where\n  \"\\<bottom> = \\<Sqinter>UNIV\"\n\ndefinition\n  top :: \"'a::complete_lattice\"  (\"\\<top>\") where\n  \"\\<top> = \\<Squnion>UNIV\"\n\nlemma bottom_least [intro?]: \"\\<bottom> \\<sqsubseteq> x\"\nproof (unfold bottom_def)\n  have \"x \\<in> UNIV\" ..\n  then show \"\\<Sqinter>UNIV \\<sqsubseteq> x\" ..\nqed\n\nlemma bottomI [intro?]: \"(\\<And>a. x \\<sqsubseteq> a) \\<Longrightarrow> \\<bottom> = x\"\nproof (unfold bottom_def)\n  assume \"\\<And>a. x \\<sqsubseteq> a\"\n  show \"\\<Sqinter>UNIV = x\"\n  proof\n    fix a show \"x \\<sqsubseteq> a\" by fact\n  next\n    fix b :: \"'a::complete_lattice\"\n    assume b: \"\\<forall>a \\<in> UNIV. b \\<sqsubseteq> a\"\n    have \"x \\<in> UNIV\" ..\n    with b show \"b \\<sqsubseteq> x\" ..\n  qed\nqed\n\nlemma top_greatest [intro?]: \"x \\<sqsubseteq> \\<top>\"\nproof (unfold top_def)\n  have \"x \\<in> UNIV\" ..\n  then show \"x \\<sqsubseteq> \\<Squnion>UNIV\" ..\nqed\n\nlemma topI [intro?]: \"(\\<And>a. a \\<sqsubseteq> x) \\<Longrightarrow> \\<top> = x\"\nproof (unfold top_def)\n  assume \"\\<And>a. a \\<sqsubseteq> x\"\n  show \"\\<Squnion>UNIV = x\"\n  proof\n    fix a show \"a \\<sqsubseteq> x\" by fact\n  next\n    fix b :: \"'a::complete_lattice\"\n    assume b: \"\\<forall>a \\<in> UNIV. a \\<sqsubseteq> b\"\n    have \"x \\<in> UNIV\" ..\n    with b show \"x \\<sqsubseteq> b\" ..\n  qed\nqed\n\n\nsubsection {* Duality *}\n\ntext {*\n  The class of complete lattices is closed under formation of dual\n  structures.\n*}\n\ninstance dual :: (complete_lattice) complete_lattice\nproof\n  fix A' :: \"'a::complete_lattice dual set\"\n  show \"\\<exists>inf'. is_Inf A' inf'\"\n  proof -\n    have \"\\<exists>sup. is_Sup (undual ` A') sup\" by (rule ex_Sup)\n    then have \"\\<exists>sup. is_Inf (dual ` undual ` A') (dual sup)\" by (simp only: dual_Inf)\n    then show ?thesis by (simp add: dual_ex [symmetric] image_comp)\n  qed\nqed\n\ntext {*\n  Apparently, the @{text \\<Sqinter>} and @{text \\<Squnion>} operations are dual to each\n  other.\n*}\n\ntheorem dual_Meet [intro?]: \"dual (\\<Sqinter>A) = \\<Squnion>(dual ` A)\"\nproof -\n  from is_Inf_Meet have \"is_Sup (dual ` A) (dual (\\<Sqinter>A))\" ..\n  then have \"\\<Squnion>(dual ` A) = dual (\\<Sqinter>A)\" ..\n  then show ?thesis ..\nqed\n\ntheorem dual_Join [intro?]: \"dual (\\<Squnion>A) = \\<Sqinter>(dual ` A)\"\nproof -\n  from is_Sup_Join have \"is_Inf (dual ` A) (dual (\\<Squnion>A))\" ..\n  then have \"\\<Sqinter>(dual ` A) = dual (\\<Squnion>A)\" ..\n  then show ?thesis ..\nqed\n\ntext {*\n  Likewise are @{text \\<bottom>} and @{text \\<top>} duals of each other.\n*}\n\ntheorem dual_bottom [intro?]: \"dual \\<bottom> = \\<top>\"\nproof -\n  have \"\\<top> = dual \\<bottom>\"\n  proof\n    fix a' have \"\\<bottom> \\<sqsubseteq> undual a'\" ..\n    then have \"dual (undual a') \\<sqsubseteq> dual \\<bottom>\" ..\n    then show \"a' \\<sqsubseteq> dual \\<bottom>\" by simp\n  qed\n  then show ?thesis ..\nqed\n\ntheorem dual_top [intro?]: \"dual \\<top> = \\<bottom>\"\nproof -\n  have \"\\<bottom> = dual \\<top>\"\n  proof\n    fix a' have \"undual a' \\<sqsubseteq> \\<top>\" ..\n    then have \"dual \\<top> \\<sqsubseteq> dual (undual a')\" ..\n    then show \"dual \\<top> \\<sqsubseteq> a'\" by simp\n  qed\n  then show ?thesis ..\nqed\n\n\nsubsection {* Complete lattices are lattices *}\n\ntext {*\n  Complete lattices (with general bounds available) are indeed plain\n  lattices as well.  This holds due to the connection of general\n  versus binary bounds that has been formally established in\n  \\S\\ref{sec:gen-bin-bounds}.\n*}\n\nlemma is_inf_binary: \"is_inf x y (\\<Sqinter>{x, y})\"\nproof -\n  have \"is_Inf {x, y} (\\<Sqinter>{x, y})\" ..\n  then show ?thesis by (simp only: is_Inf_binary)\nqed\n\nlemma is_sup_binary: \"is_sup x y (\\<Squnion>{x, y})\"\nproof -\n  have \"is_Sup {x, y} (\\<Squnion>{x, y})\" ..\n  then show ?thesis by (simp only: is_Sup_binary)\nqed\n\ninstance complete_lattice \\<subseteq> lattice\nproof\n  fix x y :: \"'a::complete_lattice\"\n  from is_inf_binary show \"\\<exists>inf. is_inf x y inf\" ..\n  from is_sup_binary show \"\\<exists>sup. is_sup x y sup\" ..\nqed\n\ntheorem meet_binary: \"x \\<sqinter> y = \\<Sqinter>{x, y}\"\n  by (rule meet_equality) (rule is_inf_binary)\n\ntheorem join_binary: \"x \\<squnion> y = \\<Squnion>{x, y}\"\n  by (rule join_equality) (rule is_sup_binary)\n\n\nsubsection {* Complete lattices and set-theory operations *}\n\ntext {*\n  The complete lattice operations are (anti) monotone wrt.\\ set\n  inclusion.\n*}\n\ntheorem Meet_subset_antimono: \"A \\<subseteq> B \\<Longrightarrow> \\<Sqinter>B \\<sqsubseteq> \\<Sqinter>A\"\nproof (rule Meet_greatest)\n  fix a assume \"a \\<in> A\"\n  also assume \"A \\<subseteq> B\"\n  finally have \"a \\<in> B\" .\n  then show \"\\<Sqinter>B \\<sqsubseteq> a\" ..\nqed\n\ntheorem Join_subset_mono: \"A \\<subseteq> B \\<Longrightarrow> \\<Squnion>A \\<sqsubseteq> \\<Squnion>B\"\nproof -\n  assume \"A \\<subseteq> B\"\n  then have \"dual ` A \\<subseteq> dual ` B\" by blast\n  then have \"\\<Sqinter>(dual ` B) \\<sqsubseteq> \\<Sqinter>(dual ` A)\" by (rule Meet_subset_antimono)\n  then have \"dual (\\<Squnion>B) \\<sqsubseteq> dual (\\<Squnion>A)\" by (simp only: dual_Join)\n  then show ?thesis by (simp only: dual_leq)\nqed\n\ntext {*\n  Bounds over unions of sets may be obtained separately.\n*}\n\ntheorem Meet_Un: \"\\<Sqinter>(A \\<union> B) = \\<Sqinter>A \\<sqinter> \\<Sqinter>B\"\nproof\n  fix a assume \"a \\<in> A \\<union> B\"\n  then show \"\\<Sqinter>A \\<sqinter> \\<Sqinter>B \\<sqsubseteq> a\"\n  proof\n    assume a: \"a \\<in> A\"\n    have \"\\<Sqinter>A \\<sqinter> \\<Sqinter>B \\<sqsubseteq> \\<Sqinter>A\" ..\n    also from a have \"\\<dots> \\<sqsubseteq> a\" ..\n    finally show ?thesis .\n  next\n    assume a: \"a \\<in> B\"\n    have \"\\<Sqinter>A \\<sqinter> \\<Sqinter>B \\<sqsubseteq> \\<Sqinter>B\" ..\n    also from a have \"\\<dots> \\<sqsubseteq> a\" ..\n    finally show ?thesis .\n  qed\nnext\n  fix b assume b: \"\\<forall>a \\<in> A \\<union> B. b \\<sqsubseteq> a\"\n  show \"b \\<sqsubseteq> \\<Sqinter>A \\<sqinter> \\<Sqinter>B\"\n  proof\n    show \"b \\<sqsubseteq> \\<Sqinter>A\"\n    proof\n      fix a assume \"a \\<in> A\"\n      then have \"a \\<in>  A \\<union> B\" ..\n      with b show \"b \\<sqsubseteq> a\" ..\n    qed\n    show \"b \\<sqsubseteq> \\<Sqinter>B\"\n    proof\n      fix a assume \"a \\<in> B\"\n      then have \"a \\<in>  A \\<union> B\" ..\n      with b show \"b \\<sqsubseteq> a\" ..\n    qed\n  qed\nqed\n\ntheorem Join_Un: \"\\<Squnion>(A \\<union> B) = \\<Squnion>A \\<squnion> \\<Squnion>B\"\nproof -\n  have \"dual (\\<Squnion>(A \\<union> B)) = \\<Sqinter>(dual ` A \\<union> dual ` B)\"\n    by (simp only: dual_Join image_Un)\n  also have \"\\<dots> = \\<Sqinter>(dual ` A) \\<sqinter> \\<Sqinter>(dual ` B)\"\n    by (rule Meet_Un)\n  also have \"\\<dots> = dual (\\<Squnion>A \\<squnion> \\<Squnion>B)\"\n    by (simp only: dual_join dual_Join)\n  finally show ?thesis ..\nqed\n\ntext {*\n  Bounds over singleton sets are trivial.\n*}\n\ntheorem Meet_singleton: \"\\<Sqinter>{x} = x\"\nproof\n  fix a assume \"a \\<in> {x}\"\n  then have \"a = x\" by simp\n  then show \"x \\<sqsubseteq> a\" by (simp only: leq_refl)\nnext\n  fix b assume \"\\<forall>a \\<in> {x}. b \\<sqsubseteq> a\"\n  then show \"b \\<sqsubseteq> x\" by simp\nqed\n\ntheorem Join_singleton: \"\\<Squnion>{x} = x\"\nproof -\n  have \"dual (\\<Squnion>{x}) = \\<Sqinter>{dual x}\" by (simp add: dual_Join)\n  also have \"\\<dots> = dual x\" by (rule Meet_singleton)\n  finally show ?thesis ..\nqed\n\ntext {*\n  Bounds over the empty and universal set correspond to each other.\n*}\n\ntheorem Meet_empty: \"\\<Sqinter>{} = \\<Squnion>UNIV\"\nproof\n  fix a :: \"'a::complete_lattice\"\n  assume \"a \\<in> {}\"\n  then have False by simp\n  then show \"\\<Squnion>UNIV \\<sqsubseteq> a\" ..\nnext\n  fix b :: \"'a::complete_lattice\"\n  have \"b \\<in> UNIV\" ..\n  then show \"b \\<sqsubseteq> \\<Squnion>UNIV\" ..\nqed\n\ntheorem Join_empty: \"\\<Squnion>{} = \\<Sqinter>UNIV\"\nproof -\n  have \"dual (\\<Squnion>{}) = \\<Sqinter>{}\" by (simp add: dual_Join)\n  also have \"\\<dots> = \\<Squnion>UNIV\" by (rule Meet_empty)\n  also have \"\\<dots> = dual (\\<Sqinter>UNIV)\" by (simp add: dual_Meet)\n  finally show ?thesis ..\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Lattice/CompleteLattice.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8740772253241802, "lm_q2_score": 0.8652240704135291, "lm_q1q2_score": 0.7562726547507507}}
{"text": "(*  Title:      HOL/Binomial.thy\n    Author:     Jacques D. Fleuriot\n    Author:     Lawrence C Paulson\n    Author:     Jeremy Avigad\n    Author:     Chaitanya Mangla\n    Author:     Manuel Eberl\n*)\n\nsection \\<open>Binomial Coefficients and Binomial Theorem\\<close>\n\ntheory Binomial\n  imports Presburger Factorial\nbegin\n\nsubsection \\<open>Binomial coefficients\\<close>\n\ntext \\<open>This development is based on the work of Andy Gordon and Florian Kammueller.\\<close>\n\ntext \\<open>Combinatorial definition\\<close>\n\ndefinition binomial :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"  (infixl \"choose\" 65)\n  where \"n choose k = card {K\\<in>Pow {0..<n}. card K = k}\"\n\ntheorem n_subsets:\n  assumes \"finite A\"\n  shows \"card {B. B \\<subseteq> A \\<and> card B = k} = card A choose k\"\nproof -\n  from assms obtain f where bij: \"bij_betw f {0..<card A} A\"\n    by (blast dest: ex_bij_betw_nat_finite)\n  then have [simp]: \"card (f ` C) = card C\" if \"C \\<subseteq> {0..<card A}\" for C\n    by (meson bij_betw_imp_inj_on bij_betw_subset card_image that)\n  from bij have \"bij_betw (image f) (Pow {0..<card A}) (Pow A)\"\n    by (rule bij_betw_Pow)\n  then have \"inj_on (image f) (Pow {0..<card A})\"\n    by (rule bij_betw_imp_inj_on)\n  moreover have \"{K. K \\<subseteq> {0..<card A} \\<and> card K = k} \\<subseteq> Pow {0..<card A}\"\n    by auto\n  ultimately have \"inj_on (image f) {K. K \\<subseteq> {0..<card A} \\<and> card K = k}\"\n    by (rule inj_on_subset)\n  then have \"card {K. K \\<subseteq> {0..<card A} \\<and> card K = k} =\n      card (image f ` {K. K \\<subseteq> {0..<card A} \\<and> card K = k})\" (is \"_ = card ?C\")\n    by (simp add: card_image)\n  also have \"?C = {K. K \\<subseteq> f ` {0..<card A} \\<and> card K = k}\"\n    by (auto elim!: subset_imageE)\n  also have \"f ` {0..<card A} = A\"\n    by (meson bij bij_betw_def)\n  finally show ?thesis\n    by (simp add: binomial_def)\nqed\n\ntext \\<open>Recursive characterization\\<close>\n\nlemma binomial_n_0 [simp]: \"n choose 0 = 1\"\nproof -\n  have \"{K \\<in> Pow {0..<n}. card K = 0} = {{}}\"\n    by (auto dest: finite_subset)\n  then show ?thesis\n    by (simp add: binomial_def)\nqed\n\nlemma binomial_0_Suc [simp]: \"0 choose Suc k = 0\"\n  by (simp add: binomial_def)\n\nlemma binomial_Suc_Suc [simp]: \"Suc n choose Suc k = (n choose k) + (n choose Suc k)\"\nproof -\n  let ?P = \"\\<lambda>n k. {K. K \\<subseteq> {0..<n} \\<and> card K = k}\"\n  let ?Q = \"?P (Suc n) (Suc k)\"\n  have inj: \"inj_on (insert n) (?P n k)\"\n    by rule (auto; metis atLeastLessThan_iff insert_iff less_irrefl subsetCE)\n  have disjoint: \"insert n ` ?P n k \\<inter> ?P n (Suc k) = {}\"\n    by auto\n  have \"?Q = {K\\<in>?Q. n \\<in> K} \\<union> {K\\<in>?Q. n \\<notin> K}\"\n    by auto\n  also have \"{K\\<in>?Q. n \\<in> K} = insert n ` ?P n k\" (is \"?A = ?B\")\n  proof (rule set_eqI)\n    fix K\n    have K_finite: \"finite K\" if \"K \\<subseteq> insert n {0..<n}\"\n      using that by (rule finite_subset) simp_all\n    have Suc_card_K: \"Suc (card K - Suc 0) = card K\" if \"n \\<in> K\"\n      and \"finite K\"\n    proof -\n      from \\<open>n \\<in> K\\<close> obtain L where \"K = insert n L\" and \"n \\<notin> L\"\n        by (blast elim: Set.set_insert)\n      with that show ?thesis by (simp add: card.insert_remove)\n    qed\n    show \"K \\<in> ?A \\<longleftrightarrow> K \\<in> ?B\"\n      by (subst in_image_insert_iff)\n        (auto simp add: card.insert_remove subset_eq_atLeast0_lessThan_finite\n          Diff_subset_conv K_finite Suc_card_K)\n  qed\n  also have \"{K\\<in>?Q. n \\<notin> K} = ?P n (Suc k)\"\n    by (auto simp add: atLeast0_lessThan_Suc)\n  finally show ?thesis using inj disjoint\n    by (simp add: binomial_def card_Un_disjoint card_image)\nqed\n\nlemma binomial_eq_0: \"n < k \\<Longrightarrow> n choose k = 0\"\n  by (auto simp add: binomial_def dest: subset_eq_atLeast0_lessThan_card)\n\nlemma zero_less_binomial: \"k \\<le> n \\<Longrightarrow> n choose k > 0\"\n  by (induct n k rule: diff_induct) simp_all\n\nlemma binomial_eq_0_iff [simp]: \"n choose k = 0 \\<longleftrightarrow> n < k\"\n  by (metis binomial_eq_0 less_numeral_extra(3) not_less zero_less_binomial)\n\nlemma zero_less_binomial_iff [simp]: \"n choose k > 0 \\<longleftrightarrow> k \\<le> n\"\n  by (metis binomial_eq_0_iff not_less0 not_less zero_less_binomial)\n\nlemma binomial_n_n [simp]: \"n choose n = 1\"\n  by (induct n) (simp_all add: binomial_eq_0)\n\nlemma binomial_Suc_n [simp]: \"Suc n choose n = Suc n\"\n  by (induct n) simp_all\n\nlemma binomial_1 [simp]: \"n choose Suc 0 = n\"\n  by (induct n) simp_all\n\nlemma choose_reduce_nat:\n  \"0 < n \\<Longrightarrow> 0 < k \\<Longrightarrow>\n    n choose k = ((n - 1) choose (k - 1)) + ((n - 1) choose k)\"\n  using binomial_Suc_Suc [of \"n - 1\" \"k - 1\"] by simp\n\nlemma Suc_times_binomial_eq: \"Suc n * (n choose k) = (Suc n choose Suc k) * Suc k\"\nproof (induction n arbitrary: k)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (Suc n)\n  show ?case \n  proof (cases k)\n    case (Suc k')\n    then show ?thesis\n      using Suc.IH\n      by (auto simp add: add_mult_distrib add_mult_distrib2 le_Suc_eq binomial_eq_0)\n  qed auto\nqed\n\nlemma binomial_le_pow2: \"n choose k \\<le> 2^n\"\nproof (induction n arbitrary: k)\n  case 0\n  then show ?case\n    using le_less less_le_trans by fastforce\nnext\n  case (Suc n)\n  show ?case\n  proof (cases k)\n    case (Suc k')\n    then show ?thesis\n      using Suc.IH by (simp add: add_le_mono mult_2)\n  qed auto\nqed\n\ntext \\<open>The absorption property.\\<close>\nlemma Suc_times_binomial: \"Suc k * (Suc n choose Suc k) = Suc n * (n choose k)\"\n  using Suc_times_binomial_eq by auto\n\ntext \\<open>This is the well-known version of absorption, but it's harder to use\n  because of the need to reason about division.\\<close>\nlemma binomial_Suc_Suc_eq_times: \"(Suc n choose Suc k) = (Suc n * (n choose k)) div Suc k\"\n  by (simp add: Suc_times_binomial_eq del: mult_Suc mult_Suc_right)\n\ntext \\<open>Another version of absorption, with \\<open>-1\\<close> instead of \\<open>Suc\\<close>.\\<close>\nlemma times_binomial_minus1_eq: \"0 < k \\<Longrightarrow> k * (n choose k) = n * ((n - 1) choose (k - 1))\"\n  using Suc_times_binomial_eq [where n = \"n - 1\" and k = \"k - 1\"]\n  by (auto split: nat_diff_split)\n\n\nsubsection \\<open>The binomial theorem (courtesy of Tobias Nipkow):\\<close>\n\ntext \\<open>Avigad's version, generalized to any commutative ring\\<close>\ntheorem binomial_ring: \"(a + b :: 'a::comm_semiring_1)^n =\n  (\\<Sum>k\\<le>n. (of_nat (n choose k)) * a^k * b^(n-k))\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have decomp: \"{0..n+1} = {0} \\<union> {n + 1} \\<union> {1..n}\"\n    by auto\n  have decomp2: \"{0..n} = {0} \\<union> {1..n}\"\n    by auto\n  have \"(a + b)^(n+1) = (a + b) * (\\<Sum>k\\<le>n. of_nat (n choose k) * a^k * b^(n - k))\"\n    using Suc.hyps by simp\n  also have \"\\<dots> = a * (\\<Sum>k\\<le>n. of_nat (n choose k) * a^k * b^(n-k)) +\n      b * (\\<Sum>k\\<le>n. of_nat (n choose k) * a^k * b^(n-k))\"\n    by (rule distrib_right)\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. of_nat (n choose k) * a^(k+1) * b^(n-k)) +\n      (\\<Sum>k\\<le>n. of_nat (n choose k) * a^k * b^(n - k + 1))\"\n    by (auto simp add: sum_distrib_left ac_simps)\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. of_nat (n choose k) * a^k * b^(n + 1 - k)) +\n      (\\<Sum>k=1..n+1. of_nat (n choose (k - 1)) * a^k * b^(n + 1 - k))\"\n    by (simp add: atMost_atLeast0 sum.shift_bounds_cl_Suc_ivl Suc_diff_le field_simps del: sum.cl_ivl_Suc)\n  also have \"\\<dots> = b^(n + 1) +\n      (\\<Sum>k=1..n. of_nat (n choose k) * a^k * b^(n + 1 - k)) + (a^(n + 1) +\n      (\\<Sum>k=1..n. of_nat (n choose (k - 1)) * a^k * b^(n + 1 - k)))\"\n      using sum.nat_ivl_Suc' [of 1 n \"\\<lambda>k. of_nat (n choose (k-1)) * a ^ k * b ^ (n + 1 - k)\"]\n    by (simp add: sum.atLeast_Suc_atMost atMost_atLeast0)\n  also have \"\\<dots> = a^(n + 1) + b^(n + 1) +\n      (\\<Sum>k=1..n. of_nat (n + 1 choose k) * a^k * b^(n + 1 - k))\"\n    by (auto simp add: field_simps sum.distrib [symmetric] choose_reduce_nat)\n  also have \"\\<dots> = (\\<Sum>k\\<le>n+1. of_nat (n + 1 choose k) * a^k * b^(n + 1 - k))\"\n    using decomp by (simp add: atMost_atLeast0 field_simps)\n  finally show ?case\n    by simp\nqed\n\ntext \\<open>Original version for the naturals.\\<close>\ncorollary binomial: \"(a + b :: nat)^n = (\\<Sum>k\\<le>n. (of_nat (n choose k)) * a^k * b^(n - k))\"\n  using binomial_ring [of \"int a\" \"int b\" n]\n  by (simp only: of_nat_add [symmetric] of_nat_mult [symmetric] of_nat_power [symmetric]\n      of_nat_sum [symmetric] of_nat_eq_iff of_nat_id)\n\nlemma binomial_fact_lemma: \"k \\<le> n \\<Longrightarrow> fact k * fact (n - k) * (n choose k) = fact n\"\nproof (induct n arbitrary: k rule: nat_less_induct)\n  fix n k\n  assume H: \"\\<forall>m<n. \\<forall>x\\<le>m. fact x * fact (m - x) * (m choose x) = fact m\"\n  assume kn: \"k \\<le> n\"\n  let ?ths = \"fact k * fact (n - k) * (n choose k) = fact n\"\n  consider \"n = 0 \\<or> k = 0 \\<or> n = k\" | m h where \"n = Suc m\" \"k = Suc h\" \"h < m\"\n    using kn by atomize_elim presburger\n  then show \"fact k * fact (n - k) * (n choose k) = fact n\"\n  proof cases\n    case 1\n    with kn show ?thesis by auto\n  next\n    case 2\n    note n = \\<open>n = Suc m\\<close>\n    note k = \\<open>k = Suc h\\<close>\n    note hm = \\<open>h < m\\<close>\n    have mn: \"m < n\"\n      using n by arith\n    have hm': \"h \\<le> m\"\n      using hm by arith\n    have km: \"k \\<le> m\"\n      using hm k n kn by arith\n    have \"m - h = Suc (m - Suc h)\"\n      using  k km hm by arith\n    with km k have \"fact (m - h) = (m - h) * fact (m - k)\"\n      by simp\n    with n k have \"fact k * fact (n - k) * (n choose k) =\n        k * (fact h * fact (m - h) * (m choose h)) +\n        (m - h) * (fact k * fact (m - k) * (m choose k))\"\n      by (simp add: field_simps)\n    also have \"\\<dots> = (k + (m - h)) * fact m\"\n      using H[rule_format, OF mn hm'] H[rule_format, OF mn km]\n      by (simp add: field_simps)\n    finally show ?thesis\n      using k n km by simp\n  qed\nqed\n\nlemma binomial_fact':\n  assumes \"k \\<le> n\"\n  shows \"n choose k = fact n div (fact k * fact (n - k))\"\n  using binomial_fact_lemma [OF assms]\n  by (metis fact_nonzero mult_eq_0_iff nonzero_mult_div_cancel_left)\n\nlemma binomial_fact:\n  assumes kn: \"k \\<le> n\"\n  shows \"(of_nat (n choose k) :: 'a::field_char_0) = fact n / (fact k * fact (n - k))\"\n  using binomial_fact_lemma[OF kn]\n  by (metis (mono_tags, lifting) fact_nonzero mult_eq_0_iff nonzero_mult_div_cancel_left of_nat_fact of_nat_mult)\n\nlemma fact_binomial:\n  assumes \"k \\<le> n\"\n  shows \"fact k * of_nat (n choose k) = (fact n / fact (n - k) :: 'a::field_char_0)\"\n  unfolding binomial_fact [OF assms] by (simp add: field_simps)\n\nlemma choose_two: \"n choose 2 = n * (n - 1) div 2\"\nproof (cases \"n \\<ge> 2\")\n  case False\n  then have \"n = 0 \\<or> n = 1\"\n    by auto\n  then show ?thesis by auto\nnext\n  case True\n  define m where \"m = n - 2\"\n  with True have \"n = m + 2\"\n    by simp\n  then have \"fact n = n * (n - 1) * fact (n - 2)\"\n    by (simp add: fact_prod_Suc atLeast0_lessThan_Suc algebra_simps)\n  with True show ?thesis\n    by (simp add: binomial_fact')\nqed\n\nlemma choose_row_sum: \"(\\<Sum>k\\<le>n. n choose k) = 2^n\"\n  using binomial [of 1 \"1\" n] by (simp add: numeral_2_eq_2)\n\nlemma sum_choose_lower: \"(\\<Sum>k\\<le>n. (r+k) choose k) = Suc (r+n) choose n\"\n  by (induct n) auto\n\nlemma sum_choose_upper: \"(\\<Sum>k\\<le>n. k choose m) = Suc n choose Suc m\"\n  by (induct n) auto\n\nlemma choose_alternating_sum:\n  \"n > 0 \\<Longrightarrow> (\\<Sum>i\\<le>n. (-1)^i * of_nat (n choose i)) = (0 :: 'a::comm_ring_1)\"\n  using binomial_ring[of \"-1 :: 'a\" 1 n]\n  by (simp add: atLeast0AtMost mult_of_nat_commute zero_power)\n\nlemma choose_even_sum:\n  assumes \"n > 0\"\n  shows \"2 * (\\<Sum>i\\<le>n. if even i then of_nat (n choose i) else 0) = (2 ^ n :: 'a::comm_ring_1)\"\nproof -\n  have \"2 ^ n = (\\<Sum>i\\<le>n. of_nat (n choose i)) + (\\<Sum>i\\<le>n. (-1) ^ i * of_nat (n choose i) :: 'a)\"\n    using choose_row_sum[of n]\n    by (simp add: choose_alternating_sum assms atLeast0AtMost of_nat_sum[symmetric])\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. of_nat (n choose i) + (-1) ^ i * of_nat (n choose i))\"\n    by (simp add: sum.distrib)\n  also have \"\\<dots> = 2 * (\\<Sum>i\\<le>n. if even i then of_nat (n choose i) else 0)\"\n    by (subst sum_distrib_left, intro sum.cong) simp_all\n  finally show ?thesis ..\nqed\n\nlemma choose_odd_sum:\n  assumes \"n > 0\"\n  shows \"2 * (\\<Sum>i\\<le>n. if odd i then of_nat (n choose i) else 0) = (2 ^ n :: 'a::comm_ring_1)\"\nproof -\n  have \"2 ^ n = (\\<Sum>i\\<le>n. of_nat (n choose i)) - (\\<Sum>i\\<le>n. (-1) ^ i * of_nat (n choose i) :: 'a)\"\n    using choose_row_sum[of n]\n    by (simp add: choose_alternating_sum assms atLeast0AtMost of_nat_sum[symmetric])\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. of_nat (n choose i) - (-1) ^ i * of_nat (n choose i))\"\n    by (simp add: sum_subtractf)\n  also have \"\\<dots> = 2 * (\\<Sum>i\\<le>n. if odd i then of_nat (n choose i) else 0)\"\n    by (subst sum_distrib_left, intro sum.cong) simp_all\n  finally show ?thesis ..\nqed\n\ntext\\<open>NW diagonal sum property\\<close>\nlemma sum_choose_diagonal:\n  assumes \"m \\<le> n\"\n  shows \"(\\<Sum>k\\<le>m. (n - k) choose (m - k)) = Suc n choose m\"\nproof -\n  have \"(\\<Sum>k\\<le>m. (n-k) choose (m - k)) = (\\<Sum>k\\<le>m. (n - m + k) choose k)\"\n    using sum.atLeastAtMost_rev [of \"\\<lambda>k. (n - k) choose (m - k)\" 0 m] assms\n    by (simp add: atMost_atLeast0)\n  also have \"\\<dots> = Suc (n - m + m) choose m\"\n    by (rule sum_choose_lower)\n  also have \"\\<dots> = Suc n choose m\"\n    using assms by simp\n  finally show ?thesis .\nqed\n\n\nsubsection \\<open>Generalized binomial coefficients\\<close>\n\ndefinition gbinomial :: \"'a::{semidom_divide,semiring_char_0} \\<Rightarrow> nat \\<Rightarrow> 'a\"  (infixl \"gchoose\" 65)\n  where gbinomial_prod_rev: \"a gchoose k = prod (\\<lambda>i. a - of_nat i) {0..<k} div fact k\"\n\nlemma gbinomial_0 [simp]:\n  \"a gchoose 0 = 1\"\n  \"0 gchoose (Suc k) = 0\"\n  by (simp_all add: gbinomial_prod_rev prod.atLeast0_lessThan_Suc_shift del: prod.op_ivl_Suc)\n\nlemma gbinomial_Suc: \"a gchoose (Suc k) = prod (\\<lambda>i. a - of_nat i) {0..k} div fact (Suc k)\"\n  by (simp add: gbinomial_prod_rev atLeastLessThanSuc_atLeastAtMost)\n\nlemma gbinomial_1 [simp]: \"a gchoose 1 = a\"\n  by (simp add: gbinomial_prod_rev lessThan_Suc)\n\nlemma gbinomial_Suc0 [simp]: \"a gchoose Suc 0 = a\"\n  by (simp add: gbinomial_prod_rev lessThan_Suc)\n\nlemma gbinomial_mult_fact: \"fact k * (a gchoose k) = (\\<Prod>i = 0..<k. a - of_nat i)\"\n  for a :: \"'a::field_char_0\"\n  by (simp_all add: gbinomial_prod_rev field_simps)\n\nlemma gbinomial_mult_fact': \"(a gchoose k) * fact k = (\\<Prod>i = 0..<k. a - of_nat i)\"\n  for a :: \"'a::field_char_0\"\n  using gbinomial_mult_fact [of k a] by (simp add: ac_simps)\n\nlemma gbinomial_pochhammer: \"a gchoose k = (- 1) ^ k * pochhammer (- a) k / fact k\"\n  for a :: \"'a::field_char_0\"\nproof (cases k)\n  case (Suc k')\n  then have \"a gchoose k = pochhammer (a - of_nat k') (Suc k') / ((1 + of_nat k') * fact k')\"\n    by (simp add: gbinomial_prod_rev pochhammer_prod_rev atLeastLessThanSuc_atLeastAtMost\n        prod.atLeast_Suc_atMost_Suc_shift of_nat_diff flip: power_mult_distrib prod.cl_ivl_Suc)\n  then show ?thesis\n    by (simp add: pochhammer_minus Suc)\nqed auto\n\nlemma gbinomial_pochhammer': \"a gchoose k = pochhammer (a - of_nat k + 1) k / fact k\"\n  for a :: \"'a::field_char_0\"\nproof -\n  have \"a gchoose k = ((-1)^k * (-1)^k) * pochhammer (a - of_nat k + 1) k / fact k\"\n    by (simp add: gbinomial_pochhammer pochhammer_minus mult_ac)\n  also have \"(-1 :: 'a)^k * (-1)^k = 1\"\n    by (subst power_add [symmetric]) simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma gbinomial_binomial: \"n gchoose k = n choose k\"\nproof (cases \"k \\<le> n\")\n  case False\n  then have \"n < k\"\n    by (simp add: not_le)\n  then have \"0 \\<in> ((-) n) ` {0..<k}\"\n    by auto\n  then have \"prod ((-) n) {0..<k} = 0\"\n    by (auto intro: prod_zero)\n  with \\<open>n < k\\<close> show ?thesis\n    by (simp add: binomial_eq_0 gbinomial_prod_rev prod_zero)\nnext\n  case True\n  from True have *: \"prod ((-) n) {0..<k} = \\<Prod>{Suc (n - k)..n}\"\n    by (intro prod.reindex_bij_witness[of _ \"\\<lambda>i. n - i\" \"\\<lambda>i. n - i\"]) auto\n  from True have \"n choose k = fact n div (fact k * fact (n - k))\"\n    by (rule binomial_fact')\n  with * show ?thesis\n    by (simp add: gbinomial_prod_rev mult.commute [of \"fact k\"] div_mult2_eq fact_div_fact)\nqed\n\nlemma of_nat_gbinomial: \"of_nat (n gchoose k) = (of_nat n gchoose k :: 'a::field_char_0)\"\nproof (cases \"k \\<le> n\")\n  case False\n  then show ?thesis\n    by (simp add: not_le gbinomial_binomial binomial_eq_0 gbinomial_prod_rev)\nnext\n  case True\n  define m where \"m = n - k\"\n  with True have n: \"n = m + k\"\n    by arith\n  from n have \"fact n = ((\\<Prod>i = 0..<m + k. of_nat (m + k - i) ):: 'a)\"\n    by (simp add: fact_prod_rev)\n  also have \"\\<dots> = ((\\<Prod>i\\<in>{0..<k} \\<union> {k..<m + k}. of_nat (m + k - i)) :: 'a)\"\n    by (simp add: ivl_disj_un)\n  finally have \"fact n = (fact m * (\\<Prod>i = 0..<k. of_nat m + of_nat k - of_nat i) :: 'a)\"\n    using prod.shift_bounds_nat_ivl [of \"\\<lambda>i. of_nat (m + k - i) :: 'a\" 0 k m]\n    by (simp add: fact_prod_rev [of m] prod.union_disjoint of_nat_diff)\n  then have \"fact n / fact (n - k) = ((\\<Prod>i = 0..<k. of_nat n - of_nat i) :: 'a)\"\n    by (simp add: n)\n  with True have \"fact k * of_nat (n gchoose k) = (fact k * (of_nat n gchoose k) :: 'a)\"\n    by (simp only: gbinomial_mult_fact [of k \"of_nat n\"] gbinomial_binomial [of n k] fact_binomial)\n  then show ?thesis\n    by simp\nqed\n\nlemma binomial_gbinomial: \"of_nat (n choose k) = (of_nat n gchoose k :: 'a::field_char_0)\"\n  by (simp add: gbinomial_binomial [symmetric] of_nat_gbinomial)\n\nsetup\n  \\<open>Sign.add_const_constraint (\\<^const_name>\\<open>gbinomial\\<close>, SOME \\<^typ>\\<open>'a::field_char_0 \\<Rightarrow> nat \\<Rightarrow> 'a\\<close>)\\<close>\n\nlemma gbinomial_mult_1:\n  fixes a :: \"'a::field_char_0\"\n  shows \"a * (a gchoose k) = of_nat k * (a gchoose k) + of_nat (Suc k) * (a gchoose (Suc k))\"\n  (is \"?l = ?r\")\nproof -\n  have \"?r = ((- 1) ^k * pochhammer (- a) k / fact k) * (of_nat k - (- a + of_nat k))\"\n    unfolding gbinomial_pochhammer pochhammer_Suc right_diff_distrib power_Suc\n    by (auto simp add: field_simps simp del: of_nat_Suc)\n  also have \"\\<dots> = ?l\"\n    by (simp add: field_simps gbinomial_pochhammer)\n  finally show ?thesis ..\nqed\n\nlemma gbinomial_mult_1':\n  \"(a gchoose k) * a = of_nat k * (a gchoose k) + of_nat (Suc k) * (a gchoose (Suc k))\"\n  for a :: \"'a::field_char_0\"\n  by (simp add: mult.commute gbinomial_mult_1)\n\nlemma gbinomial_Suc_Suc: \"(a + 1) gchoose (Suc k) = a gchoose k + (a gchoose (Suc k))\"\n  for a :: \"'a::field_char_0\"\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc h)\n  have eq0: \"(\\<Prod>i\\<in>{1..k}. (a + 1) - of_nat i) = (\\<Prod>i\\<in>{0..h}. a - of_nat i)\"\n  proof (rule prod.reindex_cong)\n    show \"{1..k} = Suc ` {0..h}\"\n      using Suc by (auto simp add: image_Suc_atMost)\n  qed auto\n  have \"fact (Suc k) * (a gchoose k + (a gchoose (Suc k))) =\n      (a gchoose Suc h) * (fact (Suc (Suc h))) +\n      (a gchoose Suc (Suc h)) * (fact (Suc (Suc h)))\"\n    by (simp add: Suc field_simps del: fact_Suc)\n  also have \"\\<dots> =\n    (a gchoose Suc h) * of_nat (Suc (Suc h) * fact (Suc h)) + (\\<Prod>i=0..Suc h. a - of_nat i)\"\n    apply (simp only: gbinomial_mult_fact field_simps mult.left_commute [of _ \"2\"])\n    apply (simp del: fact_Suc add: fact_Suc [of \"Suc h\"] field_simps gbinomial_mult_fact\n      mult.left_commute [of _ \"2\"] atLeastLessThanSuc_atLeastAtMost)\n    done\n  also have \"\\<dots> =\n    (fact (Suc h) * (a gchoose Suc h)) * of_nat (Suc (Suc h)) + (\\<Prod>i=0..Suc h. a - of_nat i)\"\n    by (simp only: fact_Suc mult.commute mult.left_commute of_nat_fact of_nat_id of_nat_mult)\n  also have \"\\<dots> =\n    of_nat (Suc (Suc h)) * (\\<Prod>i=0..h. a - of_nat i) + (\\<Prod>i=0..Suc h. a - of_nat i)\"\n    unfolding gbinomial_mult_fact atLeastLessThanSuc_atLeastAtMost by auto\n  also have \"\\<dots> =\n    (\\<Prod>i=0..Suc h. a - of_nat i) + (of_nat h * (\\<Prod>i=0..h. a - of_nat i) + 2 * (\\<Prod>i=0..h. a - of_nat i))\"\n    by (simp add: field_simps)\n  also have \"\\<dots> =\n    ((a gchoose Suc h) * (fact (Suc h)) * of_nat (Suc k)) + (\\<Prod>i\\<in>{0..Suc h}. a - of_nat i)\"\n    unfolding gbinomial_mult_fact'\n    by (simp add: comm_semiring_class.distrib field_simps Suc atLeastLessThanSuc_atLeastAtMost)\n  also have \"\\<dots> = (\\<Prod>i\\<in>{0..h}. a - of_nat i) * (a + 1)\"\n    unfolding gbinomial_mult_fact' atLeast0_atMost_Suc\n    by (simp add: field_simps Suc atLeastLessThanSuc_atLeastAtMost)\n  also have \"\\<dots> = (\\<Prod>i\\<in>{0..k}. (a + 1) - of_nat i)\"\n    using eq0\n    by (simp add: Suc prod.atLeast0_atMost_Suc_shift del: prod.cl_ivl_Suc)\n  also have \"\\<dots> = (fact (Suc k)) * ((a + 1) gchoose (Suc k))\"\n    by (simp only: gbinomial_mult_fact atLeastLessThanSuc_atLeastAtMost)\n  finally show ?thesis\n    using fact_nonzero [of \"Suc k\"] by auto\nqed\n\nlemma gbinomial_reduce_nat: \"0 < k \\<Longrightarrow> a gchoose k = (a - 1) gchoose (k - 1) + ((a - 1) gchoose k)\"\n  for a :: \"'a::field_char_0\"\n  by (metis Suc_pred' diff_add_cancel gbinomial_Suc_Suc)\n\nlemma gchoose_row_sum_weighted:\n  \"(\\<Sum>k = 0..m. (r gchoose k) * (r/2 - of_nat k)) = of_nat(Suc m) / 2 * (r gchoose (Suc m))\"\n  for r :: \"'a::field_char_0\"\n  by (induct m) (simp_all add: field_simps distrib gbinomial_mult_1)\n\nlemma binomial_symmetric:\n  assumes kn: \"k \\<le> n\"\n  shows \"n choose k = n choose (n - k)\"\nproof -\n  have kn': \"n - k \\<le> n\"\n    using kn by arith\n  from binomial_fact_lemma[OF kn] binomial_fact_lemma[OF kn']\n  have \"fact k * fact (n - k) * (n choose k) = fact (n - k) * fact (n - (n - k)) * (n choose (n - k))\"\n    by simp\n  then show ?thesis\n    using kn by simp\nqed\n\nlemma choose_rising_sum:\n  \"(\\<Sum>j\\<le>m. ((n + j) choose n)) = ((n + m + 1) choose (n + 1))\"\n  \"(\\<Sum>j\\<le>m. ((n + j) choose n)) = ((n + m + 1) choose m)\"\nproof -\n  show \"(\\<Sum>j\\<le>m. ((n + j) choose n)) = ((n + m + 1) choose (n + 1))\"\n    by (induct m) simp_all\n  also have \"\\<dots> = (n + m + 1) choose m\"\n    by (subst binomial_symmetric) simp_all\n  finally show \"(\\<Sum>j\\<le>m. ((n + j) choose n)) = (n + m + 1) choose m\" .\nqed\n\nlemma choose_linear_sum: \"(\\<Sum>i\\<le>n. i * (n choose i)) = n * 2 ^ (n - 1)\"\nproof (cases n)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc m)\n  have \"(\\<Sum>i\\<le>n. i * (n choose i)) = (\\<Sum>i\\<le>Suc m. i * (Suc m choose i))\"\n    by (simp add: Suc)\n  also have \"\\<dots> = Suc m * 2 ^ m\"\n    unfolding sum.atMost_Suc_shift Suc_times_binomial sum_distrib_left[symmetric]\n    by (simp add: choose_row_sum)\n  finally show ?thesis\n    using Suc by simp\nqed\n\nlemma choose_alternating_linear_sum:\n  assumes \"n \\<noteq> 1\"\n  shows \"(\\<Sum>i\\<le>n. (-1)^i * of_nat i * of_nat (n choose i) :: 'a::comm_ring_1) = 0\"\nproof (cases n)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc m)\n  with assms have \"m > 0\"\n    by simp\n  have \"(\\<Sum>i\\<le>n. (-1) ^ i * of_nat i * of_nat (n choose i) :: 'a) =\n      (\\<Sum>i\\<le>Suc m. (-1) ^ i * of_nat i * of_nat (Suc m choose i))\"\n    by (simp add: Suc)\n  also have \"\\<dots> = (\\<Sum>i\\<le>m. (-1) ^ (Suc i) * of_nat (Suc i * (Suc m choose Suc i)))\"\n    by (simp only: sum.atMost_Suc_shift sum_distrib_left[symmetric] mult_ac of_nat_mult) simp\n  also have \"\\<dots> = - of_nat (Suc m) * (\\<Sum>i\\<le>m. (-1) ^ i * of_nat (m choose i))\"\n    by (subst sum_distrib_left, rule sum.cong[OF refl], subst Suc_times_binomial)\n       (simp add: algebra_simps)\n  also have \"(\\<Sum>i\\<le>m. (-1 :: 'a) ^ i * of_nat ((m choose i))) = 0\"\n    using choose_alternating_sum[OF \\<open>m > 0\\<close>] by simp\n  finally show ?thesis\n    by simp\nqed\n\nlemma vandermonde: \"(\\<Sum>k\\<le>r. (m choose k) * (n choose (r - k))) = (m + n) choose r\"\nproof (induct n arbitrary: r)\n  case 0\n  have \"(\\<Sum>k\\<le>r. (m choose k) * (0 choose (r - k))) = (\\<Sum>k\\<le>r. if k = r then (m choose k) else 0)\"\n    by (intro sum.cong) simp_all\n  also have \"\\<dots> = m choose r\"\n    by simp\n  finally show ?case\n    by simp\nnext\n  case (Suc n r)\n  show ?case\n    by (cases r) (simp_all add: Suc [symmetric] algebra_simps sum.distrib Suc_diff_le)\nqed\n\nlemma choose_square_sum: \"(\\<Sum>k\\<le>n. (n choose k)^2) = ((2*n) choose n)\"\n  using vandermonde[of n n n]\n  by (simp add: power2_eq_square mult_2 binomial_symmetric [symmetric])\n\nlemma pochhammer_binomial_sum:\n  fixes a b :: \"'a::comm_ring_1\"\n  shows \"pochhammer (a + b) n = (\\<Sum>k\\<le>n. of_nat (n choose k) * pochhammer a k * pochhammer b (n - k))\"\nproof (induction n arbitrary: a b)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n a b)\n  have \"(\\<Sum>k\\<le>Suc n. of_nat (Suc n choose k) * pochhammer a k * pochhammer b (Suc n - k)) =\n      (\\<Sum>i\\<le>n. of_nat (n choose i) * pochhammer a (Suc i) * pochhammer b (n - i)) +\n      ((\\<Sum>i\\<le>n. of_nat (n choose Suc i) * pochhammer a (Suc i) * pochhammer b (n - i)) +\n      pochhammer b (Suc n))\"\n    by (subst sum.atMost_Suc_shift) (simp add: ring_distribs sum.distrib)\n  also have \"(\\<Sum>i\\<le>n. of_nat (n choose i) * pochhammer a (Suc i) * pochhammer b (n - i)) =\n      a * pochhammer ((a + 1) + b) n\"\n    by (subst Suc) (simp add: sum_distrib_left pochhammer_rec mult_ac)\n  also have \"(\\<Sum>i\\<le>n. of_nat (n choose Suc i) * pochhammer a (Suc i) * pochhammer b (n - i)) +\n        pochhammer b (Suc n) =\n      (\\<Sum>i=0..Suc n. of_nat (n choose i) * pochhammer a i * pochhammer b (Suc n - i))\"\n    apply (subst sum.atLeast_Suc_atMost, simp)\n    apply (simp add: sum.shift_bounds_cl_Suc_ivl atLeast0AtMost del: sum.cl_ivl_Suc)\n    done\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. of_nat (n choose i) * pochhammer a i * pochhammer b (Suc n - i))\"\n    using Suc by (intro sum.mono_neutral_right) (auto simp: not_le binomial_eq_0)\n  also have \"\\<dots> = (\\<Sum>i\\<le>n. of_nat (n choose i) * pochhammer a i * pochhammer b (Suc (n - i)))\"\n    by (intro sum.cong) (simp_all add: Suc_diff_le)\n  also have \"\\<dots> = b * pochhammer (a + (b + 1)) n\"\n    by (subst Suc) (simp add: sum_distrib_left mult_ac pochhammer_rec)\n  also have \"a * pochhammer ((a + 1) + b) n + b * pochhammer (a + (b + 1)) n =\n      pochhammer (a + b) (Suc n)\"\n    by (simp add: pochhammer_rec algebra_simps)\n  finally show ?case ..\nqed\n\ntext \\<open>Contributed by Manuel Eberl, generalised by LCP.\n  Alternative definition of the binomial coefficient as \\<^term>\\<open>\\<Prod>i<k. (n - i) / (k - i)\\<close>.\\<close>\nlemma gbinomial_altdef_of_nat: \"a gchoose k = (\\<Prod>i = 0..<k. (a - of_nat i) / of_nat (k - i) :: 'a)\"\n  for k :: nat and a :: \"'a::field_char_0\"\n  by (simp add: prod_dividef gbinomial_prod_rev fact_prod_rev)\n\nlemma gbinomial_ge_n_over_k_pow_k:\n  fixes k :: nat\n    and a :: \"'a::linordered_field\"\n  assumes \"of_nat k \\<le> a\"\n  shows \"(a / of_nat k :: 'a) ^ k \\<le> a gchoose k\"\nproof -\n  have x: \"0 \\<le> a\"\n    using assms of_nat_0_le_iff order_trans by blast\n  have \"(a / of_nat k :: 'a) ^ k = (\\<Prod>i = 0..<k. a / of_nat k :: 'a)\"\n    by simp\n  also have \"\\<dots> \\<le> a gchoose k\"\n  proof -\n    have \"\\<And>i. i < k \\<Longrightarrow> 0 \\<le> a / of_nat k\"\n      by (simp add: x zero_le_divide_iff)\n    moreover have \"a / of_nat k \\<le> (a - of_nat i) / of_nat (k - i)\" if \"i < k\" for i\n    proof -\n      from assms have \"a * of_nat i \\<ge> of_nat (i * k)\"\n        by (metis mult.commute mult_le_cancel_right of_nat_less_0_iff of_nat_mult)\n      then have \"a * of_nat k - a * of_nat i \\<le> a * of_nat k - of_nat (i * k)\"\n        by arith\n      then have \"a * of_nat (k - i) \\<le> (a - of_nat i) * of_nat k\"\n        using \\<open>i < k\\<close> by (simp add: algebra_simps zero_less_mult_iff of_nat_diff)\n      then have \"a * of_nat (k - i) \\<le> (a - of_nat i) * (of_nat k :: 'a)\"\n        by blast\n      with assms show ?thesis\n        using \\<open>i < k\\<close> by (simp add: field_simps)\n    qed\n    ultimately show ?thesis\n      unfolding gbinomial_altdef_of_nat\n      by (intro prod_mono) auto\n  qed\n  finally show ?thesis .\nqed\n\nlemma gbinomial_negated_upper: \"(a gchoose k) = (-1) ^ k * ((of_nat k - a - 1) gchoose k)\"\n  by (simp add: gbinomial_pochhammer pochhammer_minus algebra_simps)\n\nlemma gbinomial_minus: \"((-a) gchoose k) = (-1) ^ k * ((a + of_nat k - 1) gchoose k)\"\n  by (subst gbinomial_negated_upper) (simp add: add_ac)\n\nlemma Suc_times_gbinomial: \"of_nat (Suc k) * ((a + 1) gchoose (Suc k)) = (a + 1) * (a gchoose k)\"\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc b)\n  then have \"((a + 1) gchoose (Suc (Suc b))) = (\\<Prod>i = 0..Suc b. a + (1 - of_nat i)) / fact (b + 2)\"\n    by (simp add: field_simps gbinomial_prod_rev atLeastLessThanSuc_atLeastAtMost)\n  also have \"(\\<Prod>i = 0..Suc b. a + (1 - of_nat i)) = (a + 1) * (\\<Prod>i = 0..b. a - of_nat i)\"\n    by (simp add: prod.atLeast0_atMost_Suc_shift del: prod.cl_ivl_Suc)\n  also have \"\\<dots> / fact (b + 2) = (a + 1) / of_nat (Suc (Suc b)) * (a gchoose Suc b)\"\n    by (simp_all add: gbinomial_prod_rev atLeastLessThanSuc_atLeastAtMost)\n  finally show ?thesis by (simp add: Suc field_simps del: of_nat_Suc)\nqed\n\nlemma gbinomial_factors: \"((a + 1) gchoose (Suc k)) = (a + 1) / of_nat (Suc k) * (a gchoose k)\"\nproof (cases k)\n  case 0\n  then show ?thesis by simp\nnext\n  case (Suc b)\n  then have \"((a + 1) gchoose (Suc (Suc b))) = (\\<Prod>i = 0 .. Suc b. a + (1 - of_nat i)) / fact (b + 2)\"\n    by (simp add: field_simps gbinomial_prod_rev atLeastLessThanSuc_atLeastAtMost)\n  also have \"(\\<Prod>i = 0 .. Suc b. a + (1 - of_nat i)) = (a + 1) * (\\<Prod>i = 0..b. a - of_nat i)\"\n    by (simp add: prod.atLeast0_atMost_Suc_shift del: prod.cl_ivl_Suc)\n  also have \"\\<dots> / fact (b + 2) = (a + 1) / of_nat (Suc (Suc b)) * (a gchoose Suc b)\"\n    by (simp_all add: gbinomial_prod_rev atLeastLessThanSuc_atLeastAtMost atLeast0AtMost)\n  finally show ?thesis\n    by (simp add: Suc)\nqed\n\nlemma gbinomial_rec: \"((a + 1) gchoose (Suc k)) = (a gchoose k) * ((a + 1) / of_nat (Suc k))\"\n  using gbinomial_mult_1[of a k]\n  by (subst gbinomial_Suc_Suc) (simp add: field_simps del: of_nat_Suc, simp add: algebra_simps)\n\nlemma gbinomial_of_nat_symmetric: \"k \\<le> n \\<Longrightarrow> (of_nat n) gchoose k = (of_nat n) gchoose (n - k)\"\n  using binomial_symmetric[of k n] by (simp add: binomial_gbinomial [symmetric])\n\n\ntext \\<open>The absorption identity (equation 5.5 \\<^cite>\\<open>\\<open>p.~157\\<close> in GKP_CM\\<close>):\n\\[\n{r \\choose k} = \\frac{r}{k}{r - 1 \\choose k - 1},\\quad \\textnormal{integer } k \\neq 0.\n\\]\\<close>\nlemma gbinomial_absorption': \"k > 0 \\<Longrightarrow> a gchoose k = (a / of_nat k) * (a - 1 gchoose (k - 1))\"\n  using gbinomial_rec[of \"a - 1\" \"k - 1\"]\n  by (simp_all add: gbinomial_rec field_simps del: of_nat_Suc)\n\ntext \\<open>The absorption identity is written in the following form to avoid\ndivision by $k$ (the lower index) and therefore remove the $k \\neq 0$\nrestriction \\<^cite>\\<open>\\<open>p.~157\\<close> in GKP_CM\\<close>:\n\\[\nk{r \\choose k} = r{r - 1 \\choose k - 1}, \\quad \\textnormal{integer } k.\n\\]\\<close>\nlemma gbinomial_absorption: \"of_nat (Suc k) * (a gchoose Suc k) = a * ((a - 1) gchoose k)\"\n  using gbinomial_absorption'[of \"Suc k\" a] by (simp add: field_simps del: of_nat_Suc)\n\ntext \\<open>The absorption identity for natural number binomial coefficients:\\<close>\nlemma binomial_absorption: \"Suc k * (n choose Suc k) = n * ((n - 1) choose k)\"\n  by (cases n) (simp_all add: binomial_eq_0 Suc_times_binomial del: binomial_Suc_Suc mult_Suc)\n\ntext \\<open>The absorption companion identity for natural number coefficients,\n  following the proof by GKP \\<^cite>\\<open>\\<open>p.~157\\<close> in GKP_CM\\<close>:\\<close>\nlemma binomial_absorb_comp: \"(n - k) * (n choose k) = n * ((n - 1) choose k)\"\n  (is \"?lhs = ?rhs\")\nproof (cases \"n \\<le> k\")\n  case True\n  then show ?thesis by auto\nnext\n  case False\n  then have \"?rhs = Suc ((n - 1) - k) * (n choose Suc ((n - 1) - k))\"\n    using binomial_symmetric[of k \"n - 1\"] binomial_absorption[of \"(n - 1) - k\" n]\n    by simp\n  also have \"Suc ((n - 1) - k) = n - k\"\n    using False by simp\n  also have \"n choose \\<dots> = n choose k\"\n    using False by (intro binomial_symmetric [symmetric]) simp_all\n  finally show ?thesis ..\nqed\n\ntext \\<open>The generalised absorption companion identity:\\<close>\nlemma gbinomial_absorb_comp: \"(a - of_nat k) * (a gchoose k) = a * ((a - 1) gchoose k)\"\n  using pochhammer_absorb_comp[of a k] by (simp add: gbinomial_pochhammer)\n\nlemma gbinomial_addition_formula:\n  \"a gchoose (Suc k) = ((a - 1) gchoose (Suc k)) + ((a - 1) gchoose k)\"\n  using gbinomial_Suc_Suc[of \"a - 1\" k] by (simp add: algebra_simps)\n\nlemma binomial_addition_formula:\n  \"0 < n \\<Longrightarrow> n choose (Suc k) = ((n - 1) choose (Suc k)) + ((n - 1) choose k)\"\n  by (subst choose_reduce_nat) simp_all\n\ntext \\<open>\n  Equation 5.9 of the reference material \\<^cite>\\<open>\\<open>p.~159\\<close> in GKP_CM\\<close> is a useful\n  summation formula, operating on both indices:\n  \\[\n   \\sum\\limits_{k \\leq n}{r + k \\choose k} = {r + n + 1 \\choose n},\n   \\quad \\textnormal{integer } n.\n  \\]\n\\<close>\nlemma gbinomial_parallel_sum: \"(\\<Sum>k\\<le>n. (a + of_nat k) gchoose k) = (a + of_nat n + 1) gchoose n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc m)\n  then show ?case\n    using gbinomial_Suc_Suc[of \"(a + of_nat m + 1)\" m]\n    by (simp add: add_ac)\nqed\n\n\nsubsubsection \\<open>Summation on the upper index\\<close>\n\ntext \\<open>\n  Another summation formula is equation 5.10 of the reference material \\<^cite>\\<open>\\<open>p.~160\\<close> in GKP_CM\\<close>,\n  aptly named \\emph{summation on the upper index}:\\[\\sum_{0 \\leq k \\leq n} {k \\choose m} =\n  {n + 1 \\choose m + 1}, \\quad \\textnormal{integers } m, n \\geq 0.\\]\n\\<close>\nlemma gbinomial_sum_up_index:\n  \"(\\<Sum>j = 0..n. (of_nat j gchoose k) :: 'a::field_char_0) = (of_nat n + 1) gchoose (k + 1)\"\nproof (induct n)\n  case 0\n  show ?case\n    using gbinomial_Suc_Suc[of 0 k]\n    by (cases k) auto\nnext\n  case (Suc n)\n  then show ?case\n    using gbinomial_Suc_Suc[of \"of_nat (Suc n) :: 'a\" k]\n    by (simp add: add_ac)\nqed\n\nlemma gbinomial_index_swap:\n  \"((-1) ^ k) * ((- (of_nat n) - 1) gchoose k) = ((-1) ^ n) * ((- (of_nat k) - 1) gchoose n)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = (of_nat (k + n) gchoose k)\"\n    by (subst gbinomial_negated_upper) (simp add: power_mult_distrib [symmetric])\n  also have \"\\<dots> = (of_nat (k + n) gchoose n)\"\n    by (subst gbinomial_of_nat_symmetric) simp_all\n  also have \"\\<dots> = ?rhs\"\n    by (subst gbinomial_negated_upper) simp\n  finally show ?thesis .\nqed\n\nlemma gbinomial_sum_lower_neg: \"(\\<Sum>k\\<le>m. (a gchoose k) * (- 1) ^ k) = (- 1) ^ m * (a - 1 gchoose m)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = (\\<Sum>k\\<le>m. -(a + 1) + of_nat k gchoose k)\"\n    by (intro sum.cong[OF refl]) (subst gbinomial_negated_upper, simp add: power_mult_distrib)\n  also have \"\\<dots>  = - a + of_nat m gchoose m\"\n    by (subst gbinomial_parallel_sum) simp\n  also have \"\\<dots> = ?rhs\"\n    by (subst gbinomial_negated_upper) (simp add: power_mult_distrib)\n  finally show ?thesis .\nqed\n\nlemma gbinomial_partial_row_sum:\n  \"(\\<Sum>k\\<le>m. (a gchoose k) * ((a / 2) - of_nat k)) = ((of_nat m + 1)/2) * (a gchoose (m + 1))\"\nproof (induct m)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc mm)\n  then have \"(\\<Sum>k\\<le>Suc mm. (a gchoose k) * (a / 2 - of_nat k)) =\n      (a - of_nat (Suc mm)) * (a gchoose Suc mm) / 2\"\n    by (simp add: field_simps)\n  also have \"\\<dots> = a * (a - 1 gchoose Suc mm) / 2\"\n    by (subst gbinomial_absorb_comp) (rule refl)\n  also have \"\\<dots> = (of_nat (Suc mm) + 1) / 2 * (a gchoose (Suc mm + 1))\"\n    by (subst gbinomial_absorption [symmetric]) simp\n  finally show ?case .\nqed\n\nlemma sum_bounds_lt_plus1: \"(\\<Sum>k<mm. f (Suc k)) = (\\<Sum>k=1..mm. f k)\"\n  by (induct mm) simp_all\n\nlemma gbinomial_partial_sum_poly:\n  \"(\\<Sum>k\\<le>m. (of_nat m + a gchoose k) * x^k * y^(m-k)) =\n    (\\<Sum>k\\<le>m. (-a gchoose k) * (-x)^k * (x + y)^(m-k))\"\n  (is \"?lhs m = ?rhs m\")\nproof (induction m)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc mm)\n  define G where \"G i k = (of_nat i + a gchoose k) * x^k * y^(i - k)\" for i k\n  define S where \"S = ?lhs\"\n  have SG_def: \"S = (\\<lambda>i. (\\<Sum>k\\<le>i. (G i k)))\"\n    unfolding S_def G_def ..\n\n  have \"S (Suc mm) = G (Suc mm) 0 + (\\<Sum>k=Suc 0..Suc mm. G (Suc mm) k)\"\n    using SG_def by (simp add: sum.atLeast_Suc_atMost atLeast0AtMost [symmetric])\n  also have \"(\\<Sum>k=Suc 0..Suc mm. G (Suc mm) k) = (\\<Sum>k=0..mm. G (Suc mm) (Suc k))\"\n    by (subst sum.shift_bounds_cl_Suc_ivl) simp\n  also have \"\\<dots> = (\\<Sum>k=0..mm. ((of_nat mm + a gchoose (Suc k)) +\n      (of_nat mm + a gchoose k)) * x^(Suc k) * y^(mm - k))\"\n    unfolding G_def by (subst gbinomial_addition_formula) simp\n  also have \"\\<dots> = (\\<Sum>k=0..mm. (of_nat mm + a gchoose (Suc k)) * x^(Suc k) * y^(mm - k)) +\n      (\\<Sum>k=0..mm. (of_nat mm + a gchoose k) * x^(Suc k) * y^(mm - k))\"\n    by (subst sum.distrib [symmetric]) (simp add: algebra_simps)\n  also have \"(\\<Sum>k=0..mm. (of_nat mm + a gchoose (Suc k)) * x^(Suc k) * y^(mm - k)) =\n      (\\<Sum>k<Suc mm. (of_nat mm + a gchoose (Suc k)) * x^(Suc k) * y^(mm - k))\"\n    by (simp only: atLeast0AtMost lessThan_Suc_atMost)\n  also have \"\\<dots> = (\\<Sum>k<mm. (of_nat mm + a gchoose Suc k) * x^(Suc k) * y^(mm-k)) +\n      (of_nat mm + a gchoose (Suc mm)) * x^(Suc mm)\"\n    (is \"_ = ?A + ?B\")\n    by (subst sum.lessThan_Suc) simp\n  also have \"?A = (\\<Sum>k=1..mm. (of_nat mm + a gchoose k) * x^k * y^(mm - k + 1))\"\n  proof (subst sum_bounds_lt_plus1 [symmetric], intro sum.cong[OF refl], clarify)\n    fix k\n    assume \"k < mm\"\n    then have \"mm - k = mm - Suc k + 1\"\n      by linarith\n    then show \"(of_nat mm + a gchoose Suc k) * x ^ Suc k * y ^ (mm - k) =\n        (of_nat mm + a gchoose Suc k) * x ^ Suc k * y ^ (mm - Suc k + 1)\"\n      by (simp only:)\n  qed\n  also have \"\\<dots> + ?B = y * (\\<Sum>k=1..mm. (G mm k)) + (of_nat mm + a gchoose (Suc mm)) * x^(Suc mm)\"\n    unfolding G_def by (subst sum_distrib_left) (simp add: algebra_simps)\n  also have \"(\\<Sum>k=0..mm. (of_nat mm + a gchoose k) * x^(Suc k) * y^(mm - k)) = x * (S mm)\"\n    unfolding S_def by (subst sum_distrib_left) (simp add: atLeast0AtMost algebra_simps)\n  also have \"(G (Suc mm) 0) = y * (G mm 0)\"\n    by (simp add: G_def)\n  finally have \"S (Suc mm) =\n      y * (G mm 0 + (\\<Sum>k=1..mm. (G mm k))) + (of_nat mm + a gchoose (Suc mm)) * x^(Suc mm) + x * (S mm)\"\n    by (simp add: ring_distribs)\n  also have \"G mm 0 + (\\<Sum>k=1..mm. (G mm k)) = S mm\"\n    by (simp add: sum.atLeast_Suc_atMost[symmetric] SG_def atLeast0AtMost)\n  finally have \"S (Suc mm) = (x + y) * (S mm) + (of_nat mm + a gchoose (Suc mm)) * x^(Suc mm)\"\n    by (simp add: algebra_simps)\n  also have \"(of_nat mm + a gchoose (Suc mm)) = (-1) ^ (Suc mm) * (- a gchoose (Suc mm))\"\n    by (subst gbinomial_negated_upper) simp\n  also have \"(-1) ^ Suc mm * (- a gchoose Suc mm) * x ^ Suc mm =\n      (- a gchoose (Suc mm)) * (-x) ^ Suc mm\"\n    by (simp add: power_minus[of x])\n  also have \"(x + y) * S mm + \\<dots> = (x + y) * ?rhs mm + (- a gchoose (Suc mm)) * (- x)^Suc mm\"\n    unfolding S_def by (subst Suc.IH) simp\n  also have \"(x + y) * ?rhs mm = (\\<Sum>n\\<le>mm. ((- a gchoose n) * (- x) ^ n * (x + y) ^ (Suc mm - n)))\"\n    by (subst sum_distrib_left, rule sum.cong) (simp_all add: Suc_diff_le)\n  also have \"\\<dots> + (-a gchoose (Suc mm)) * (-x)^Suc mm =\n      (\\<Sum>n\\<le>Suc mm. (- a gchoose n) * (- x) ^ n * (x + y) ^ (Suc mm - n))\"\n    by simp\n  finally show ?case\n    by (simp only: S_def)\nqed\n\nlemma gbinomial_partial_sum_poly_xpos:\n    \"(\\<Sum>k\\<le>m. (of_nat m + a gchoose k) * x^k * y^(m-k)) =\n     (\\<Sum>k\\<le>m. (of_nat k + a - 1 gchoose k) * x^k * (x + y)^(m-k))\" (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = (\\<Sum>k\\<le>m. (- a gchoose k) * (- x) ^ k * (x + y) ^ (m - k))\"\n    by (simp add: gbinomial_partial_sum_poly)\n  also have \"... = (\\<Sum>k\\<le>m. (-1) ^ k * (of_nat k - - a - 1 gchoose k) * (- x) ^ k * (x + y) ^ (m - k))\"\n    by (metis (no_types, opaque_lifting) gbinomial_negated_upper)\n  also have \"... = ?rhs\"\n    by (intro sum.cong) (auto simp flip: power_mult_distrib)\n  finally show ?thesis .\nqed\n\nlemma binomial_r_part_sum: \"(\\<Sum>k\\<le>m. (2 * m + 1 choose k)) = 2 ^ (2 * m)\"\nproof -\n  have \"2 * 2^(2*m) = (\\<Sum>k = 0..(2 * m + 1). (2 * m + 1 choose k))\"\n    using choose_row_sum[where n=\"2 * m + 1\"]  by (simp add: atMost_atLeast0)\n  also have \"(\\<Sum>k = 0..(2 * m + 1). (2 * m + 1 choose k)) =\n      (\\<Sum>k = 0..m. (2 * m + 1 choose k)) +\n      (\\<Sum>k = m+1..2*m+1. (2 * m + 1 choose k))\"\n    using sum.ub_add_nat[of 0 m \"\\<lambda>k. 2 * m + 1 choose k\" \"m+1\"]\n    by (simp add: mult_2)\n  also have \"(\\<Sum>k = m+1..2*m+1. (2 * m + 1 choose k)) =\n      (\\<Sum>k = 0..m. (2 * m + 1 choose (k + (m + 1))))\"\n    by (subst sum.shift_bounds_cl_nat_ivl [symmetric]) (simp add: mult_2)\n  also have \"\\<dots> = (\\<Sum>k = 0..m. (2 * m + 1 choose (m - k)))\"\n    by (intro sum.cong[OF refl], subst binomial_symmetric) simp_all\n  also have \"\\<dots> = (\\<Sum>k = 0..m. (2 * m + 1 choose k))\"\n    using sum.atLeastAtMost_rev [of \"\\<lambda>k. 2 * m + 1 choose (m - k)\" 0 m]\n    by simp\n  also have \"\\<dots> + \\<dots> = 2 * \\<dots>\"\n    by simp\n  finally show ?thesis\n    by (subst (asm) mult_cancel1) (simp add: atLeast0AtMost)\nqed\n\nlemma gbinomial_r_part_sum: \"(\\<Sum>k\\<le>m. (2 * (of_nat m) + 1 gchoose k)) = 2 ^ (2 * m)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs = of_nat (\\<Sum>k\\<le>m. (2 * m + 1) choose k)\"\n    by (simp add: binomial_gbinomial add_ac)\n  also have \"\\<dots> = of_nat (2 ^ (2 * m))\"\n    by (subst binomial_r_part_sum) (rule refl)\n  finally show ?thesis by simp\nqed\n\nlemma gbinomial_sum_nat_pow2:\n  \"(\\<Sum>k\\<le>m. (of_nat (m + k) gchoose k :: 'a::field_char_0) / 2 ^ k) = 2 ^ m\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"2 ^ m * 2 ^ m = (2 ^ (2*m) :: 'a)\"\n    by (induct m) simp_all\n  also have \"\\<dots> = (\\<Sum>k\\<le>m. (2 * (of_nat m) + 1 gchoose k))\"\n    using gbinomial_r_part_sum ..\n  also have \"\\<dots> = (\\<Sum>k\\<le>m. (of_nat (m + k) gchoose k) * 2 ^ (m - k))\"\n    using gbinomial_partial_sum_poly_xpos[where x=\"1\" and y=\"1\" and a=\"of_nat m + 1\" and m=\"m\"]\n    by (simp add: add_ac)\n  also have \"\\<dots> = 2 ^ m * (\\<Sum>k\\<le>m. (of_nat (m + k) gchoose k) / 2 ^ k)\"\n    by (subst sum_distrib_left) (simp add: algebra_simps power_diff)\n  finally show ?thesis\n    by (subst (asm) mult_left_cancel) simp_all\nqed\n\nlemma gbinomial_trinomial_revision:\n  assumes \"k \\<le> m\"\n  shows \"(a gchoose m) * (of_nat m gchoose k) = (a gchoose k) * (a - of_nat k gchoose (m - k))\"\nproof -\n  have \"(a gchoose m) * (of_nat m gchoose k) = (a gchoose m) * fact m / (fact k * fact (m - k))\"\n    using assms by (simp add: binomial_gbinomial [symmetric] binomial_fact)\n  also have \"\\<dots> = (a gchoose k) * (a - of_nat k gchoose (m - k))\"\n    using assms by (simp add: gbinomial_pochhammer power_diff pochhammer_product)\n  finally show ?thesis .\nqed\n\ntext \\<open>Versions of the theorems above for the natural-number version of \"choose\"\\<close>\nlemma binomial_altdef_of_nat:\n  \"k \\<le> n \\<Longrightarrow> of_nat (n choose k) = (\\<Prod>i = 0..<k. of_nat (n - i) / of_nat (k - i) :: 'a)\"\n  for n k :: nat and x :: \"'a::field_char_0\"\n  by (simp add: gbinomial_altdef_of_nat binomial_gbinomial of_nat_diff)\n\nlemma binomial_ge_n_over_k_pow_k: \"k \\<le> n \\<Longrightarrow> (of_nat n / of_nat k :: 'a) ^ k \\<le> of_nat (n choose k)\"\n  for k n :: nat and x :: \"'a::linordered_field\"\n  by (simp add: gbinomial_ge_n_over_k_pow_k binomial_gbinomial of_nat_diff)\n\nlemma binomial_le_pow:\n  assumes \"r \\<le> n\"\n  shows \"n choose r \\<le> n ^ r\"\nproof -\n  have \"n choose r \\<le> fact n div fact (n - r)\"\n    using assms by (subst binomial_fact_lemma[symmetric]) auto\n  with fact_div_fact_le_pow [OF assms] show ?thesis\n    by auto\nqed\n\nlemma binomial_altdef_nat: \"k \\<le> n \\<Longrightarrow> n choose k = fact n div (fact k * fact (n - k))\"\n  for k n :: nat\n  by (subst binomial_fact_lemma [symmetric]) auto\n\nlemma choose_dvd:\n  assumes \"k \\<le> n\" shows \"fact k * fact (n - k) dvd (fact n :: 'a::linordered_semidom)\"\n  unfolding dvd_def\nproof\n  show \"fact n = fact k * fact (n - k) * of_nat (n choose k)\"\n    by (metis assms binomial_fact_lemma of_nat_fact of_nat_mult) \nqed\n\nlemma fact_fact_dvd_fact:\n  \"fact k * fact n dvd (fact (k + n) :: 'a::linordered_semidom)\"\n  by (metis add.commute add_diff_cancel_left' choose_dvd le_add2)\n\nlemma choose_mult_lemma:\n  \"((m + r + k) choose (m + k)) * ((m + k) choose k) = ((m + r + k) choose k) * ((m + r) choose m)\"\n  (is \"?lhs = _\")\nproof -\n  have \"?lhs =\n      fact (m + r + k) div (fact (m + k) * fact (m + r - m)) * (fact (m + k) div (fact k * fact m))\"\n    by (simp add: binomial_altdef_nat)\n  also have \"... = fact (m + r + k) * fact (m + k) div\n                 (fact (m + k) * fact (m + r - m) * (fact k * fact m))\"\n    by (metis add_implies_diff add_le_mono1 choose_dvd diff_cancel2 div_mult_div_if_dvd le_add1 le_add2)\n  also have \"\\<dots> = fact (m + r + k) div (fact r * (fact k * fact m))\"\n    by (auto simp: algebra_simps fact_fact_dvd_fact)\n  also have \"\\<dots> = (fact (m + r + k) * fact (m + r)) div (fact r * (fact k * fact m) * fact (m + r))\"\n    by simp\n  also have \"\\<dots> =\n      (fact (m + r + k) div (fact k * fact (m + r)) * (fact (m + r) div (fact r * fact m)))\"\n    by (auto simp: div_mult_div_if_dvd fact_fact_dvd_fact algebra_simps)\n  finally show ?thesis\n    by (simp add: binomial_altdef_nat mult.commute)\nqed\n\ntext \\<open>The \"Subset of a Subset\" identity.\\<close>\nlemma choose_mult:\n  \"k \\<le> m \\<Longrightarrow> m \\<le> n \\<Longrightarrow> (n choose m) * (m choose k) = (n choose k) * ((n - k) choose (m - k))\"\n  using choose_mult_lemma [of \"m-k\" \"n-m\" k] by simp\n\nlemma of_nat_binomial_eq_mult_binomial_Suc:\n  assumes \"k \\<le> n\"\n  shows \"(of_nat :: (nat \\<Rightarrow> ('a :: field_char_0))) (n choose k) = of_nat (n + 1 - k) / of_nat (n + 1) * of_nat (Suc n choose k)\"\nproof (cases k)\n  case 0 then show ?thesis\n    using of_nat_neq_0 by auto\nnext\n  case (Suc l)\n  have \"of_nat (n + 1) * (\\<Prod>i=0..<k. of_nat (n - i)) = (of_nat :: (nat \\<Rightarrow> 'a)) (n + 1 - k) * (\\<Prod>i=0..<k. of_nat (Suc n - i))\"\n    using prod.atLeast0_lessThan_Suc [where ?'a = 'a, symmetric, of \"\\<lambda>i. of_nat (Suc n - i)\" k]\n    by (simp add: ac_simps prod.atLeast0_lessThan_Suc_shift del: prod.op_ivl_Suc)\n  also have \"... = (of_nat :: (nat \\<Rightarrow> 'a)) (Suc n - k) * (\\<Prod>i=0..<k. of_nat (Suc n - i))\"\n    by (simp add: Suc atLeast0_atMost_Suc atLeastLessThanSuc_atLeastAtMost)\n  also have \"... = (of_nat :: (nat \\<Rightarrow> 'a)) (n + 1 - k) * (\\<Prod>i=0..<k. of_nat (Suc n - i))\"\n    by (simp only: Suc_eq_plus1)\n  finally have \"(\\<Prod>i=0..<k. of_nat (n - i)) = (of_nat :: (nat \\<Rightarrow> 'a)) (n + 1 - k) / of_nat (n + 1) * (\\<Prod>i=0..<k. of_nat (Suc n - i))\"\n    using of_nat_neq_0 by (auto simp: mult.commute divide_simps)\n  with assms show ?thesis\n    by (simp add: binomial_altdef_of_nat prod_dividef)\nqed\n\n\nsubsection \\<open>More on Binomial Coefficients\\<close>\n\nlemma choose_one: \"n choose 1 = n\" for n :: nat\n  by simp\n\ntext \\<open>The famous inclusion-exclusion formula for the cardinality of a union\\<close>\nlemma int_card_UNION:\n  assumes \"finite A\"\n    and \"\\<forall>k \\<in> A. finite k\"\n  shows \"int (card (\\<Union>A)) = (\\<Sum>I | I \\<subseteq> A \\<and> I \\<noteq> {}. (- 1) ^ (card I + 1) * int (card (\\<Inter>I)))\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?rhs = (\\<Sum>I | I \\<subseteq> A \\<and> I \\<noteq> {}. (- 1) ^ (card I + 1) * (\\<Sum>_\\<in>\\<Inter>I. 1))\"\n    by simp\n  also have \"\\<dots> = (\\<Sum>I | I \\<subseteq> A \\<and> I \\<noteq> {}. (\\<Sum>_\\<in>\\<Inter>I. (- 1) ^ (card I + 1)))\"\n    by (subst sum_distrib_left) simp\n  also have \"\\<dots> = (\\<Sum>(I, _)\\<in>Sigma {I. I \\<subseteq> A \\<and> I \\<noteq> {}} Inter. (- 1) ^ (card I + 1))\"\n    using assms by (subst sum.Sigma) auto\n  also have \"\\<dots> = (\\<Sum>(x, I)\\<in>(SIGMA x:UNIV. {I. I \\<subseteq> A \\<and> I \\<noteq> {} \\<and> x \\<in> \\<Inter>I}). (- 1) ^ (card I + 1))\"\n    by (rule sum.reindex_cong [where l = \"\\<lambda>(x, y). (y, x)\"]) (auto intro: inj_onI)\n  also have \"\\<dots> = (\\<Sum>(x, I)\\<in>(SIGMA x:\\<Union>A. {I. I \\<subseteq> A \\<and> I \\<noteq> {} \\<and> x \\<in> \\<Inter>I}). (- 1) ^ (card I + 1))\"\n    using assms\n    by (auto intro!: sum.mono_neutral_cong_right finite_SigmaI2 intro: finite_subset[where B=\"\\<Union>A\"])\n  also have \"\\<dots> = (\\<Sum>x\\<in>\\<Union>A. (\\<Sum>I|I \\<subseteq> A \\<and> I \\<noteq> {} \\<and> x \\<in> \\<Inter>I. (- 1) ^ (card I + 1)))\"\n    using assms by (subst sum.Sigma) auto\n  also have \"\\<dots> = (\\<Sum>_\\<in>\\<Union>A. 1)\" (is \"sum ?lhs _ = _\")\n  proof (rule sum.cong[OF refl])\n    fix x\n    assume x: \"x \\<in> \\<Union>A\"\n    define K where \"K = {X \\<in> A. x \\<in> X}\"\n    with \\<open>finite A\\<close> have K: \"finite K\"\n      by auto\n    let ?I = \"\\<lambda>i. {I. I \\<subseteq> A \\<and> card I = i \\<and> x \\<in> \\<Inter>I}\"\n    have \"inj_on snd (SIGMA i:{1..card A}. ?I i)\"\n      using assms by (auto intro!: inj_onI)\n    moreover have [symmetric]: \"snd ` (SIGMA i:{1..card A}. ?I i) = {I. I \\<subseteq> A \\<and> I \\<noteq> {} \\<and> x \\<in> \\<Inter>I}\"\n      using assms\n      by (auto intro!: rev_image_eqI[where x=\"(card a, a)\" for a]\n        simp add: card_gt_0_iff[folded Suc_le_eq]\n        dest: finite_subset intro: card_mono)\n    ultimately have \"?lhs x = (\\<Sum>(i, I)\\<in>(SIGMA i:{1..card A}. ?I i). (- 1) ^ (i + 1))\"\n      by (rule sum.reindex_cong [where l = snd]) fastforce\n    also have \"\\<dots> = (\\<Sum>i=1..card A. (\\<Sum>I|I \\<subseteq> A \\<and> card I = i \\<and> x \\<in> \\<Inter>I. (- 1) ^ (i + 1)))\"\n      using assms by (subst sum.Sigma) auto\n    also have \"\\<dots> = (\\<Sum>i=1..card A. (- 1) ^ (i + 1) * (\\<Sum>I|I \\<subseteq> A \\<and> card I = i \\<and> x \\<in> \\<Inter>I. 1))\"\n      by (subst sum_distrib_left) simp\n    also have \"\\<dots> = (\\<Sum>i=1..card K. (- 1) ^ (i + 1) * (\\<Sum>I|I \\<subseteq> K \\<and> card I = i. 1))\"\n      (is \"_ = ?rhs\")\n    proof (rule sum.mono_neutral_cong_right[rule_format])\n      show \"finite {1..card A}\"\n        by simp\n      show \"{1..card K} \\<subseteq> {1..card A}\"\n        using \\<open>finite A\\<close> by (auto simp add: K_def intro: card_mono)\n    next\n      fix i\n      assume \"i \\<in> {1..card A} - {1..card K}\"\n      then have i: \"i \\<le> card A\" \"card K < i\"\n        by auto\n      have \"{I. I \\<subseteq> A \\<and> card I = i \\<and> x \\<in> \\<Inter>I} = {I. I \\<subseteq> K \\<and> card I = i}\"\n        by (auto simp add: K_def)\n      also have \"\\<dots> = {}\"\n        using \\<open>finite A\\<close> i by (auto simp add: K_def dest: card_mono[rotated 1])\n      finally show \"(- 1) ^ (i + 1) * (\\<Sum>I | I \\<subseteq> A \\<and> card I = i \\<and> x \\<in> \\<Inter>I. 1 :: int) = 0\"\n        by (metis mult_zero_right sum.empty)\n    next\n      fix i\n      have \"(\\<Sum>I | I \\<subseteq> A \\<and> card I = i \\<and> x \\<in> \\<Inter>I. 1) = (\\<Sum>I | I \\<subseteq> K \\<and> card I = i. 1 :: int)\"\n        (is \"?lhs = ?rhs\")\n        by (rule sum.cong) (auto simp add: K_def)\n      then show \"(- 1) ^ (i + 1) * ?lhs = (- 1) ^ (i + 1) * ?rhs\"\n        by simp\n    qed\n    also have \"{I. I \\<subseteq> K \\<and> card I = 0} = {{}}\"\n      using assms by (auto simp add: card_eq_0_iff K_def dest: finite_subset)\n    then have \"?rhs = (\\<Sum>i = 0..card K. (- 1) ^ (i + 1) * (\\<Sum>I | I \\<subseteq> K \\<and> card I = i. 1 :: int)) + 1\"\n      by (subst (2) sum.atLeast_Suc_atMost) simp_all\n    also have \"\\<dots> = (\\<Sum>i = 0..card K. (- 1) * ((- 1) ^ i * int (card K choose i))) + 1\"\n      using K by (subst n_subsets[symmetric]) simp_all\n    also have \"\\<dots> = - (\\<Sum>i = 0..card K. (- 1) ^ i * int (card K choose i)) + 1\"\n      by (subst sum_distrib_left[symmetric]) simp\n    also have \"\\<dots> =  - ((-1 + 1) ^ card K) + 1\"\n      by (subst binomial_ring) (simp add: ac_simps atMost_atLeast0)\n    also have \"\\<dots> = 1\"\n      using x K by (auto simp add: K_def card_gt_0_iff)\n    finally show \"?lhs x = 1\" .\n  qed\n  also have \"\\<dots> = int (card (\\<Union>A))\"\n    by simp\n  finally show ?thesis ..\nqed\n\nlemma card_UNION:\n  assumes \"finite A\"\n    and \"\\<forall>k \\<in> A. finite k\"\n  shows \"card (\\<Union>A) = nat (\\<Sum>I | I \\<subseteq> A \\<and> I \\<noteq> {}. (- 1) ^ (card I + 1) * int (card (\\<Inter>I)))\"\n  by (simp only: flip: int_card_UNION [OF assms])\n\nlemma card_UNION_nonneg:\n  assumes \"finite A\"\n    and \"\\<forall>k \\<in> A. finite k\"\n  shows \"(\\<Sum>I | I \\<subseteq> A \\<and> I \\<noteq> {}. (- 1) ^ (card I + 1) * int (card (\\<Inter>I))) \\<ge> 0\"\n  using int_card_UNION [OF assms] by presburger\n\ntext \\<open>The number of nat lists of length \\<open>m\\<close> summing to \\<open>N\\<close> is \\<^term>\\<open>(N + m - 1) choose N\\<close>:\\<close>\nlemma card_length_sum_list_rec:\n  assumes \"m \\<ge> 1\"\n  shows \"card {l::nat list. length l = m \\<and> sum_list l = N} =\n      card {l. length l = (m - 1) \\<and> sum_list l = N} +\n      card {l. length l = m \\<and> sum_list l + 1 = N}\"\n    (is \"card ?C = card ?A + card ?B\")\nproof -\n  let ?A' = \"{l. length l = m \\<and> sum_list l = N \\<and> hd l = 0}\"\n  let ?B' = \"{l. length l = m \\<and> sum_list l = N \\<and> hd l \\<noteq> 0}\"\n  let ?f = \"\\<lambda>l. 0 # l\"\n  let ?g = \"\\<lambda>l. (hd l + 1) # tl l\"\n  have 1: \"xs \\<noteq> [] \\<Longrightarrow> x = hd xs \\<Longrightarrow> x # tl xs = xs\" for x :: nat and xs\n    by simp\n  have 2: \"xs \\<noteq> [] \\<Longrightarrow> sum_list(tl xs) = sum_list xs - hd xs\" for xs :: \"nat list\"\n    by (auto simp add: neq_Nil_conv)\n  have f: \"bij_betw ?f ?A ?A'\"\n    by (rule bij_betw_byWitness[where f' = tl]) (use assms in \\<open>auto simp: 2 1 simp flip: length_0_conv\\<close>)\n  have 3: \"xs \\<noteq> [] \\<Longrightarrow> hd xs + (sum_list xs - hd xs) = sum_list xs\" for xs :: \"nat list\"\n    by (metis 1 sum_list_simps(2) 2)\n  have g: \"bij_betw ?g ?B ?B'\"\n    apply (rule bij_betw_byWitness[where f' = \"\\<lambda>l. (hd l - 1) # tl l\"])\n    using assms\n    by (auto simp: 2 simp flip: length_0_conv intro!: 3)\n  have fin: \"finite {xs. size xs = M \\<and> set xs \\<subseteq> {0..<N}}\" for M N :: nat\n    using finite_lists_length_eq[OF finite_atLeastLessThan] conj_commute by auto\n  have fin_A: \"finite ?A\" using fin[of _ \"N+1\"]\n    by (intro finite_subset[where ?A = \"?A\" and ?B = \"{xs. size xs = m - 1 \\<and> set xs \\<subseteq> {0..<N+1}}\"])\n      (auto simp: member_le_sum_list less_Suc_eq_le)\n  have fin_B: \"finite ?B\"\n    by (intro finite_subset[where ?A = \"?B\" and ?B = \"{xs. size xs = m \\<and> set xs \\<subseteq> {0..<N}}\"])\n      (auto simp: member_le_sum_list less_Suc_eq_le fin)\n  have uni: \"?C = ?A' \\<union> ?B'\"\n    by auto\n  have disj: \"?A' \\<inter> ?B' = {}\" by blast\n  have \"card ?C = card(?A' \\<union> ?B')\"\n    using uni by simp\n  also have \"\\<dots> = card ?A + card ?B\"\n    using card_Un_disjoint[OF _ _ disj] bij_betw_finite[OF f] bij_betw_finite[OF g]\n      bij_betw_same_card[OF f] bij_betw_same_card[OF g] fin_A fin_B\n    by presburger\n  finally show ?thesis .\nqed\n\nlemma card_length_sum_list: \"card {l::nat list. size l = m \\<and> sum_list l = N} = (N + m - 1) choose N\"\n  \\<comment> \\<open>by Holden Lee, tidied by Tobias Nipkow\\<close>\nproof (cases m)\n  case 0\n  then show ?thesis\n    by (cases N) (auto cong: conj_cong)\nnext\n  case (Suc m')\n  have m: \"m \\<ge> 1\"\n    by (simp add: Suc)\n  then show ?thesis\n  proof (induct \"N + m - 1\" arbitrary: N m)\n    case 0  \\<comment> \\<open>In the base case, the only solution is [0].\\<close>\n    have [simp]: \"{l::nat list. length l = Suc 0 \\<and> (\\<forall>n\\<in>set l. n = 0)} = {[0]}\"\n      by (auto simp: length_Suc_conv)\n    have \"m = 1 \\<and> N = 0\"\n      using 0 by linarith\n    then show ?case\n      by simp\n  next\n    case (Suc k)\n    have c1: \"card {l::nat list. size l = (m - 1) \\<and> sum_list l =  N} = (N + (m - 1) - 1) choose N\"\n    proof (cases \"m = 1\")\n      case True\n      with Suc.hyps have \"N \\<ge> 1\"\n        by auto\n      with True show ?thesis\n        by (simp add: binomial_eq_0)\n    next\n      case False\n      then show ?thesis\n        using Suc by fastforce\n    qed\n    from Suc have c2: \"card {l::nat list. size l = m \\<and> sum_list l + 1 = N} =\n      (if N > 0 then ((N - 1) + m - 1) choose (N - 1) else 0)\"\n    proof -\n      have *: \"n > 0 \\<Longrightarrow> Suc m = n \\<longleftrightarrow> m = n - 1\" for m n\n        by arith\n      from Suc have \"N > 0 \\<Longrightarrow>\n        card {l::nat list. size l = m \\<and> sum_list l + 1 = N} =\n          ((N - 1) + m - 1) choose (N - 1)\"\n        by (simp add: *)\n      then show ?thesis\n        by auto\n    qed\n    from Suc.prems have \"(card {l::nat list. size l = (m - 1) \\<and> sum_list l = N} +\n          card {l::nat list. size l = m \\<and> sum_list l + 1 = N}) = (N + m - 1) choose N\"\n      by (auto simp: c1 c2 choose_reduce_nat[of \"N + m - 1\" N] simp del: One_nat_def)\n    then show ?case\n      using card_length_sum_list_rec[OF Suc.prems] by auto\n  qed\nqed\n\nlemma card_disjoint_shuffles:\n  assumes \"set xs \\<inter> set ys = {}\"\n  shows   \"card (shuffles xs ys) = (length xs + length ys) choose length xs\"\nusing assms\nproof (induction xs ys rule: shuffles.induct)\n  case (3 x xs y ys)\n  have \"shuffles (x # xs) (y # ys) = (#) x ` shuffles xs (y # ys) \\<union> (#) y ` shuffles (x # xs) ys\"\n    by (rule shuffles.simps)\n  also have \"card \\<dots> = card ((#) x ` shuffles xs (y # ys)) + card ((#) y ` shuffles (x # xs) ys)\"\n    by (rule card_Un_disjoint) (insert \"3.prems\", auto)\n  also have \"card ((#) x ` shuffles xs (y # ys)) = card (shuffles xs (y # ys))\"\n    by (rule card_image) auto\n  also have \"\\<dots> = (length xs + length (y # ys)) choose length xs\"\n    using \"3.prems\" by (intro \"3.IH\") auto\n  also have \"card ((#) y ` shuffles (x # xs) ys) = card (shuffles (x # xs) ys)\"\n    by (rule card_image) auto\n  also have \"\\<dots> = (length (x # xs) + length ys) choose length (x # xs)\"\n    using \"3.prems\" by (intro \"3.IH\") auto\n  also have \"length xs + length (y # ys) choose length xs + \\<dots> =\n               (length (x # xs) + length (y # ys)) choose length (x # xs)\" by simp\n  finally show ?case .\nqed auto\n\nlemma Suc_times_binomial_add: \"Suc a * (Suc (a + b) choose Suc a) = Suc b * (Suc (a + b) choose a)\"\n  \\<comment> \\<open>by Lukas Bulwahn\\<close>\nproof -\n  have dvd: \"Suc a * (fact a * fact b) dvd fact (Suc (a + b))\" for a b\n    using fact_fact_dvd_fact[of \"Suc a\" \"b\", where 'a=nat]\n    by (simp only: fact_Suc add_Suc[symmetric] of_nat_id mult.assoc)\n  have \"Suc a * (fact (Suc (a + b)) div (Suc a * fact a * fact b)) =\n      Suc a * fact (Suc (a + b)) div (Suc a * (fact a * fact b))\"\n    by (subst div_mult_swap[symmetric]; simp only: mult.assoc dvd)\n  also have \"\\<dots> = Suc b * fact (Suc (a + b)) div (Suc b * (fact a * fact b))\"\n    by (simp only: div_mult_mult1)\n  also have \"\\<dots> = Suc b * (fact (Suc (a + b)) div (Suc b * (fact a * fact b)))\"\n    using dvd[of b a] by (subst div_mult_swap[symmetric]; simp only: ac_simps dvd)\n  finally show ?thesis\n    by (subst (1 2) binomial_altdef_nat)\n      (simp_all only: ac_simps diff_Suc_Suc Suc_diff_le diff_add_inverse fact_Suc of_nat_id)\nqed\n\n\nsubsection \\<open>Executable code\\<close>\n\nlemma gbinomial_code [code]:\n  \"a gchoose k =\n    (if k = 0 then 1\n     else fold_atLeastAtMost_nat (\\<lambda>k acc. (a - of_nat k) * acc) 0 (k - 1) 1 / fact k)\"\n  by (cases k)\n    (simp_all add: gbinomial_prod_rev prod_atLeastAtMost_code [symmetric]\n      atLeastLessThanSuc_atLeastAtMost)\n\nlemma binomial_code [code]:\n  \"n choose k =\n      (if k > n then 0\n       else if 2 * k > n then n choose (n - k)\n       else (fold_atLeastAtMost_nat (*) (n - k + 1) n 1 div fact k))\"\nproof -\n  {\n    assume \"k \\<le> n\"\n    then have \"{1..n} = {1..n-k} \\<union> {n-k+1..n}\" by auto\n    then have \"(fact n :: nat) = fact (n-k) * \\<Prod>{n-k+1..n}\"\n      by (simp add: prod.union_disjoint fact_prod)\n  }\n  then show ?thesis by (auto simp: binomial_altdef_nat mult_ac prod_atLeastAtMost_code)\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Binomial.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.8856314768368161, "lm_q1q2_score": 0.7562520026088366}}
{"text": "(*\n    $Id: ex.thy,v 1.4 2011/06/28 18:11:39 webertj Exp $\n    Author: Farhad Mehta, Tobias Nipkow\n*)\n\nheader {* Optimising Compilation for a Register Machine *}\n\n(*<*) theory ex imports Main begin (*>*)\n\ntext {*\nSection 3.3 of the Isabelle/HOL tutorial describes an expression compiler for a stack machine. In this exercise we will build and verify an optimising expression compiler for a register machine.\n*}\n\ntext {*\\subsubsection*{The Source Language: Expressions}*}\n\ntext {*\nThe arithmetic expressions we will work with consist of variables, constants, and an arbitrary binary operator @{text \"oper\"}.\n*}\n\nconsts oper :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n\ntype_synonym var = string\n\ndatatype exp = \n    Const nat \n  | Var var\n  | Op exp exp\n\ntext {*\nThe state in which an expression is evaluated is modelled by an {\\em environment} function that maps variables to constants.\n*}\n\ntype_synonym env = \"var \\<Rightarrow> nat\"\n\ntext {*\nDefine a function @{text \"value\"} that evaluates an expression in a given environment.\n*}\n\nconsts \"value\" :: \"exp \\<Rightarrow> env \\<Rightarrow> nat\"\n\ntext {*\\subsubsection*{The Register Machine}*}\n\ntext {*\nAs the name suggests, a register machine uses a collection of registers to store intermediate results. There exists a special register, called the accumulator, that serves as an implicit argument to each instruction. The rest of the registers make up the register file, and can be randomly accessed using an index. \n*}\n\ntype_synonym regIndex = nat\n\ndatatype cell = \n    Acc\n  | Reg regIndex\n\ntext {*\nThe state of the register machine is denoted by a function that maps storage cells to constants.\n*}\n\ntype_synonym state = \"cell \\<Rightarrow> nat\"\n\ntext {*\nThe instruction set for the register machine is defined as follows:\n*}\n\ndatatype instr = \n  LI nat        \n  -- \"Load Immediate: loads a constant into the accumulator.\" \n| LOAD regIndex \n  -- \"Loads the contents of a register into the accumulator.\"\n| STORE regIndex \n  -- \"Saves the contents of the accumulator in a register.\" \n| OPER regIndex \n  -- {* Performs the binary operation @{text \"oper\"}.*}\n    -- \"The first argument is taken from a register.\"\n    -- \"The second argument is taken from the accumulator.\" \n    -- \"The result of the computation is stored in the accumulator.\"\n\ntext {*\nA program is a list of such instructions. The result of running a program is a change of state of the register machine. Define a function @{text \"exec\"} that models this.\n*}\n\nconsts exec :: \"state \\<Rightarrow> instr list \\<Rightarrow> state\"\n\ntext {*\\subsubsection*{Compilation}*}\n\ntext {*\nThe task now is to translate an expression into a sequence of instructions that computes it. At the end of execution, the result should be stored in the accumulator.\n\nBefore execution, the values of each variable need to be stored somewhere in the register file. A {\\it mapping} function maps variables to positions in the register file.\n*}\n\ntype_synonym map = \"var \\<Rightarrow> regIndex\"\n\ntext {*\nDefine a function @{text \"cmp\"} that compiles an expression into a sequence of instructions. The evaluation should proceed in a bottom-up depth-first manner.\n\nState and prove a theorem expressing the correctness of @{text \"cmp\"}.\n\nHints:\n\\begin{itemize}\n  \\item The compilation function is dependent on the mapping function.\n  \\item The compilation function needs some way of storing intermediate results. It should be clever enough to reuse registers it no longer needs.\n  \\item It may be helpful to assume that at each recursive call, compilation is only allowed to use registers with indices greater than a given value to store intermediate results.\n\\end{itemize}\n*}\n\ntext {*\\subsubsection*{Compiler Optimisation: Common Subexpressions}*}\n\ntext {*\nIn the previous section, the compiler @{text \"cmp\"} was allowed to evaluate a subexpression every time it occurred. In situations where arithmetic operations are costly, one may want to compute commonly occurring subexpressions only once.\n\nFor example, to compute @{text \"(a op b) op (a op b)\"}, @{text \"cmp\"} was allowed three calls to @{text \"oper\"}, when only two were needed.\n\nDevelop an optimised compiler @{text \"optCmp\"}, that evaluates every commonly occurring subexpression only once. Prove its correctness.\n*}\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/isabelle.in.tum.de/exercises/proj/optComp/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.8918110562208682, "lm_q1q2_score": 0.7562270222401708}}
{"text": "theory Unify imports\n  Main \"HOL-Library.Adhoc_Overloading\"\nbegin\n\n(*\n--------------------------------------------------\nAssignment 1\n--------------------------------------------------\n*)\n\ndatatype ('f , 'v) \"term\" = Var 'v | Fun 'f \"('f, 'v) term list\"\n\nfun fv :: \"('f , 'v) term \\<Rightarrow> 'v set\" where\n  \"fv (Var x) = {x}\"\n| \"fv (Fun f l) = (\\<Union>x\\<in>(set l).(fv x))\"\n\nlemma equi_def_fv:\n  \"fv (Fun f l) = fold (\\<union>) (map fv l) {}\"\n  by (metis Sup_set_fold fv.simps(2) set_map)\n\nvalue \"fv (Fun (1 :: nat) [Var (0 :: nat), Var 1, Fun 2 [Var 2, Fun 3 [Var 5]]])\"\n\ntype_synonym ('f, 'v) subst = \"'v \\<Rightarrow> ('f, 'v) term\"\n\nconsts\n  SAPPLY_SYMBOL :: \"('f, 'v) subst \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<cdot>\" 67)\n\nfun sapply :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) term \\<Rightarrow> ('f, 'v) term\"\n  where\n  \"sapply s (Fun f l) = Fun f (map (sapply s) l)\"\n| \"sapply s (Var x) = s x\"\nadhoc_overloading SAPPLY_SYMBOL sapply\n\nlemma fv_sapply[simp]: \"fv (\\<sigma> \\<cdot> t) = (\\<Union> x \\<in> (fv t). fv (\\<sigma> x))\"\nproof (induction t)\n  case (Var y)\n  have \"fv (\\<sigma> \\<cdot> (Var y)) = fv (\\<sigma> y)\" by simp\n  also have \"... = (\\<Union>x \\<in> fv (Var y) .fv (\\<sigma> x))\" by simp\n  then show ?case by simp\nnext\n  case (Fun x1a x2)\n  have \"fv (\\<sigma> \\<cdot> Fun x1a x2) = (\\<Union>y\\<in>(set x2).((fv \\<circ> (sapply \\<sigma>)) y))\" by simp\n  also have \"... =  (\\<Union>y\\<in>(set x2). (\\<Union>yy\\<in>fv y. fv (\\<sigma> yy)))\" using Fun.IH by simp\n  also have \"... = (\\<Union>x\\<in>fv (Fun x1a x2). fv (\\<sigma> x))\"\n    by (metis Sup_set_fold UN_UN_flatten fv.simps(2) set_map)\n  also have \"fv (\\<sigma> \\<cdot> Fun x1a x2) = (\\<Union>x\\<in>fv (Fun x1a x2). fv (\\<sigma> x))\"\n    using calculation by blast\n  then show ?case by simp\nqed\n\nlemma sapply_cong:\n  assumes \"\\<And>x. x \\<in> fv t \\<Longrightarrow> \\<sigma> x = \\<tau> x\"\n  shows \"\\<sigma> \\<cdot> t = \\<tau> \\<cdot> t\"\n  using assms\nproof (induction t)\n  case (Var x)\n  then show ?case by simp\nnext\n  case (Fun x1a x2)\n  then show ?case by auto\nqed\n\nfun scomp :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> ('f, 'v) subst\" (infixl \"\\<circ>s\" 75)\n  where\n  \"scomp \\<sigma> \\<tau> = (\\<lambda> x. \\<sigma> \\<cdot> \\<tau>(x))\"\n\nlemma scomp_sapply[simp]: \"(\\<sigma> \\<circ>s \\<tau> ) x = \\<sigma> \\<cdot>(\\<tau> x)\"\n  by simp\n\nlemma sapply_scomp_distrib[simp]: \"(\\<sigma> \\<circ>s \\<tau> ) \\<cdot> t = \\<sigma> \\<cdot> (\\<tau> \\<cdot> t)\"\nproof (induction t)\n  case (Var x)\n  then show ?case by simp\nnext\n  case (Fun x1a x2)\n  then show ?case by simp\nqed\n\nlemma scomp_assoc[simp]: \"(\\<sigma> \\<circ>s \\<tau> ) \\<circ>s q = \\<sigma> \\<circ>s (\\<tau> \\<circ>s q)\"\nproof (rule ext)\n  show \"(\\<sigma> \\<circ>s \\<tau> \\<circ>s q) x = (\\<sigma> \\<circ>s (\\<tau> \\<circ>s q)) x\" for x\n    using sapply_scomp_distrib by simp\nqed\n\nlemma scomp_Var [simp]: \"\\<sigma> \\<circ>s Var = \\<sigma>\"\nproof (rule ext)\n  show \"(\\<sigma> \\<circ>s Var) x = \\<sigma> x\" for x\n    by simp\nqed\n\nlemma Var_id: \"Var \\<cdot> t = t\"\nproof (induction t)\n  case (Var x)\nthen show ?case by simp\nnext\n  case (Fun x1a x2)\n  then show ?case\n    by (simp add: map_idI)\nqed\n\nlemma Var_scomp [simp]: \"Var \\<circ>s \\<sigma> = \\<sigma>\"\n  by (simp add: Var_id)\n\n(* 1. (d) *)\n\nfun sdom :: \"('f , 'v) subst \\<Rightarrow> 'v set\"\n  where\n  \"sdom \\<sigma> = {x. \\<sigma> x \\<noteq> Var x}\"\n\nfun sran :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) term set\"\n  where\n\"sran \\<sigma> = (\\<Union>x\\<in>sdom \\<sigma>. {\\<sigma> x})\"\n\nfun svran:: \"('f , 'v) subst \\<Rightarrow> 'v set\"\n  where\n\"svran \\<sigma> = (\\<Union>t\\<in>(sran \\<sigma>).(fv t))\"\n\nlemma sdom_Var [simp]: \"sdom Var = {}\"\n  by simp\n\nlemma svran_Var [simp]: \"svran Var = {}\"\n  by simp\n\nlemma svran_single_non_trivial [simp]:\n  assumes \"t \\<noteq> Var x\"\n  shows \"svran (Var(x:=t)) = fv t\"\n  using assms by simp\n\nlemma fold_union_map[intro]:\n  \"\\<lbrakk> x \\<in> (fold (\\<union>) (map f l) {}) \\<rbrakk> \\<Longrightarrow> x \\<in> (\\<Union>y\\<in>(set l).f y)\"\n  by (metis Sup_set_fold set_map)\n\nlemma fv_fun[simp]: \"fv (Fun f l) = (\\<Union> x \\<in> (set l). fv x)\" by simp\n\nlemma fv_sapply_sdom_svran[simp]:\n  assumes \"x \\<in> fv (\\<sigma> \\<cdot> t)\"\n  shows \"x \\<in> (fv t - sdom \\<sigma>) \\<union> svran \\<sigma>\"\n  using assms\nproof (induction t)\n  case (Var y)\n  then show ?case\n  proof (cases \"y \\<in> sdom \\<sigma>\")\n    case True\n    then have \"\\<sigma> y \\<in> sran \\<sigma>\" by auto\n    then have \"fv (\\<sigma> y) \\<subseteq> svran \\<sigma>\" by auto\n    then have \"fv (\\<sigma> \\<cdot> (Var y)) \\<subseteq> svran \\<sigma>\" by simp\n    then show ?thesis using Var.prems by blast\n  next\n    case False\n    then show ?thesis using Var.prems by auto\n  qed\nnext\n  case (Fun x1a x2)\n  have \"x \\<in> (\\<Union>x2a \\<in> (set x2). fv (\\<sigma> \\<cdot> x2a))\"\n    by (metis (no_types, lifting) Fun.prems SUP_UNION Sup.SUP_cong fv_fun fv_sapply)\n  also obtain x2a where \"x2a \\<in> (set x2) \\<and> x \\<in> fv (\\<sigma> \\<cdot> x2a)\"\n    using calculation by blast\n  then show ?case\n    by (metis Diff_iff Fun.IH UN_I UnE UnI1 UnI2 fv_fun)\nqed\n\nlemma sdom_scomp[simp]: \"sdom (\\<sigma> \\<circ>s \\<tau> ) \\<subseteq> sdom \\<sigma> \\<union> sdom \\<tau>\"\n  by auto\n\nthm singleton_iff\n\nlemma svran_scomp[simp]: \"svran (\\<sigma> \\<circ>s \\<tau> ) \\<subseteq> svran \\<sigma> \\<union> svran \\<tau>\"\nproof -\n  have \"\\<And>x xa xb. \\<lbrakk>xb \\<in> fv (\\<tau> xa); x \\<in> fv (\\<sigma> xb); \\<forall>xa. \\<tau> xa = Var xa \\<or> x \\<notin> fv (\\<tau> xa); \\<sigma> \\<cdot> \\<tau> xa \\<noteq> Var xa\\<rbrakk> \\<Longrightarrow> \\<exists>xa. \\<sigma> xa \\<noteq> Var xa \\<and> x \\<in> fv (\\<sigma> xa)\"\n    by (metis fv.simps(1) sapply.simps(2) singletonD)\n  then show ?thesis by (auto simp add: singleton_iff)\nqed\n\n(*\n--------------------------------------------------\nAssignment 2\n--------------------------------------------------\n*)\n\ntype_synonym ('f, 'v) equation = \"('f, 'v) term \\<times> ('f, 'v) term\"\ntype_synonym ('f, 'v) equations = \"('f, 'v) equation list\"\n\nfun fv_eq :: \"('f , 'v) equation \\<Rightarrow> 'v set\" where\n  \"fv_eq eq = (fv (fst eq)) \\<union> (fv (snd eq))\"\n\nfun fv_eq_system :: \"('f, 'v) equations \\<Rightarrow> 'v set\" where\n  \"fv_eq_system l = fold (\\<union>) (map fv_eq l) {}\"\n\nlemma fv_eq_system_def_equiv_1:\n  \"fv_eq_system l = (\\<Union>x\\<in>(set l). fv_eq x)\"\n  by (metis Sup_set_fold fv_eq_system.elims set_map)\n\nlemma fv_eq_system_def_equiv:\n  \"fv_eq_system (eq # U) = (fv_eq eq) \\<union> (fv_eq_system U)\"\n  by (metis UN_insert fv_eq_system_def_equiv_1 list.simps(15))\n\nfun sapply_eq :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> ('f, 'v) equation\"\n  where\n  \"sapply_eq \\<sigma> eq = (sapply \\<sigma> (fst eq), sapply \\<sigma> (snd eq))\"\nadhoc_overloading SAPPLY_SYMBOL sapply_eq\n\nfun sapply_eq_system :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> ('f, 'v) equations\"\n  where\n\"sapply_eq_system \\<sigma> l = map (sapply_eq \\<sigma>) l\"\nadhoc_overloading SAPPLY_SYMBOL sapply_eq_system\n\nlemma sapply_eq_system_equiv_def:\n  \"sapply_eq_system \\<sigma> (eq # U) = (sapply_eq \\<sigma> eq) # (sapply_eq_system \\<sigma> U)\" by simp\n\nlemma fv_sapply_eq[simp]: \"fv_eq (\\<sigma> \\<cdot> eq) = (\\<Union> x \\<in> (fv_eq eq). fv (\\<sigma> x))\"\n  by simp\n\nlemma fv_sapply_eq_system[simp]: \"fv_eq_system (\\<sigma> \\<cdot> s) = (\\<Union> x \\<in> (fv_eq_system s). fv (\\<sigma> x))\"\nproof (induction s)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons eq s)\n  have \"fv_eq_system (\\<sigma> \\<cdot> (eq # s)) = fold (\\<union>) (map fv_eq (\\<sigma> \\<cdot> (eq # s))) {}\" by simp\n  also have \"... = (\\<Union>y\\<in>(set (\\<sigma> \\<cdot> (eq # s))). fv_eq y)\" by (metis Sup_set_fold set_map)\n  also have \"... = (\\<Union>y\\<in>(set (\\<sigma> \\<cdot> s)). fv_eq y) \\<union> (\\<Union>y\\<in>(set (\\<sigma> \\<cdot> [eq])). fv_eq y)\" by (simp add: inf_sup_aci(5))\n  have \"(\\<Union>y\\<in>(set (\\<sigma> \\<cdot> s)). fv_eq y) = fv_eq_system (\\<sigma> \\<cdot> s)\"\n    by (metis Sup_set_fold fv_eq_system.elims set_map)\n  have \"... = (\\<Union> x \\<in> (fv_eq_system s). fv (\\<sigma> x))\" using Cons.IH by blast\n  have \"(\\<Union>y\\<in>(set (\\<sigma> \\<cdot> [eq])). fv_eq y) =  (\\<Union>x\\<in>(fv_eq_system [eq]). fv (\\<sigma> x))\"\n    by auto\n  have \"fv_eq_system (\\<sigma> \\<cdot> (eq # s)) =\n             (\\<Union> x \\<in> (fv_eq_system s). fv (\\<sigma> x)) \\<union> (\\<Union>x\\<in>(fv_eq_system [eq]). fv (\\<sigma> x))\"\n    using Cons.IH \\<open>(\\<Union>y\\<in>set (\\<sigma> \\<cdot> s). fv_eq y) = fv_eq_system (\\<sigma> \\<cdot> s)\\<close> calculation by auto\n  also have \"... = (\\<Union> x \\<in> (fv_eq_system (eq # s)). fv (\\<sigma> x))\"\n    by (metis (no_types, lifting) Sup_set_fold UN_Un UN_insert Union_image_empty empty_set fv_eq_system.elims inf_sup_aci(5) list.simps(15) set_map)\n  then show ?case\n    using \\<open>fv_eq_system (\\<sigma> \\<cdot> (eq # s)) = (\\<Union>x\\<in>fv_eq_system s. fv (\\<sigma> x)) \\<union> (\\<Union>x\\<in>fv_eq_system [eq]. fv (\\<sigma> x))\\<close> by auto\nqed\n\nlemma sapply_scomp_distrib_eq[simp]: \"(\\<sigma> \\<circ>s \\<tau>) \\<cdot> (eq :: ('f, 'v) equation) = \\<sigma> \\<cdot> (\\<tau> \\<cdot> eq)\"\n  using sapply_scomp_distrib by force+\n\nlemma sapply_scomp_distrib_eq_system[simp]: \"(\\<sigma> \\<circ>s \\<tau>) \\<cdot> (s :: ('f, 'v) equations) = \\<sigma> \\<cdot> (\\<tau> \\<cdot> s)\"\n  using sapply_scomp_distrib by force+\n\n(* 2. (b) *)\n\ninductive unifies :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> bool\" where\n  unifies_eq: \"(\\<sigma> \\<cdot> u = \\<sigma> \\<cdot> t) \\<Longrightarrow> unifies \\<sigma> (u, t)\"\n\ninductive unifiess :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  unifiess_empty: \"unifiess \\<sigma> []\"\n| unifiess_rec:   \"(unifiess \\<sigma> s) \\<and> (unifies \\<sigma> eq) \\<Longrightarrow> unifiess \\<sigma> (eq # s)\"\n\nfun is_mgu :: \"('f, 'v) subst \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"is_mgu \\<sigma> U = (\\<forall>\\<tau>. unifiess \\<tau> U \\<longrightarrow> (\\<exists>\\<rho> . \\<tau> = \\<rho> \\<circ>s \\<sigma>))\"\n\n(* 2. (c) *)\n\nlemma unifies_sapply_eq[simp]: \"unifies \\<sigma> (sapply_eq \\<tau> eq) \\<longleftrightarrow> unifies (\\<sigma> \\<circ>s \\<tau> ) eq\"\nproof -\n  have \"unifies \\<sigma> (sapply_eq \\<tau> eq) \\<longleftrightarrow> \\<sigma> \\<cdot> (fst (sapply_eq \\<tau> eq)) = \\<sigma> \\<cdot> (snd (sapply_eq \\<tau> eq))\"\n    by (simp add: unifies.simps)\n  also have \"... \\<longleftrightarrow> \\<sigma> \\<cdot> (\\<tau>  \\<cdot> (fst eq)) = \\<sigma> \\<cdot> (\\<tau>  \\<cdot> (snd eq))\" by simp\n  also have \"... \\<longleftrightarrow> (\\<sigma> \\<circ>s \\<tau>)  \\<cdot> (fst eq) = (\\<sigma> \\<circ>s \\<tau>)  \\<cdot> (snd eq)\" by (metis sapply_scomp_distrib)\n  also have \"... \\<longleftrightarrow> unifies (\\<sigma> \\<circ>s \\<tau> ) eq\" using unifies.simps by force\n  then show ?thesis using calculation by blast\nqed\n\nlemma unifies_sapply_eq_sys: \"unifiess \\<sigma> (sapply_eq_system \\<tau> U) \\<longleftrightarrow> unifiess (\\<sigma> \\<circ>s \\<tau> ) U\"\n\nproof (induction U)\n  case Nil\n  then show ?case by (simp add: unifiess_empty)\nnext\n  case (Cons a U)\n  have \"\\<And>a b U. \\<lbrakk>unifiess \\<sigma> (map ((\\<cdot>) \\<tau>) U); unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) U; unifiess \\<sigma> ((\\<tau> \\<cdot> a, \\<tau> \\<cdot> b) # map ((\\<cdot>) \\<tau>) U)\\<rbrakk> \\<Longrightarrow> unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) ((a, b) # U)\"\n    by (metis (no_types, lifting) list.discI list.sel(1) prod.sel(1) prod.sel(2) sapply_cong sapply_scomp_distrib scomp.simps unifies.simps unifiess.simps)\n  moreover have \"\\<And>a b U. \\<lbrakk>unifiess \\<sigma> (map ((\\<cdot>) \\<tau>) U); unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) U; unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) ((a, b) # U)\\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> ((\\<tau> \\<cdot> a, \\<tau> \\<cdot> b) # map ((\\<cdot>) \\<tau>) U)\"\n    by (metis (no_types, lifting) list.discI list.sel(1) prod.sel(1) prod.sel(2) sapply_cong sapply_scomp_distrib scomp.simps unifies.simps unifiess.simps)\n  moreover have \"\\<And>a b U. \\<lbrakk>\\<not> unifiess \\<sigma> (map ((\\<cdot>) \\<tau>) U); \\<not> unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) U; unifiess \\<sigma> ((\\<tau> \\<cdot> a, \\<tau> \\<cdot> b) # map ((\\<cdot>) \\<tau>) U)\\<rbrakk> \\<Longrightarrow> unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) ((a, b) # U)\"\n    using induct_rulify_fallback(2) unifiess.simps by auto\n  moreover have \"\\<And>a b U. \\<lbrakk>\\<not> unifiess \\<sigma> (map ((\\<cdot>) \\<tau>) U); \\<not> unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) U; unifiess (\\<lambda>a. \\<sigma> \\<cdot> \\<tau> a) ((a, b) # U)\\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> ((\\<tau> \\<cdot> a, \\<tau> \\<cdot> b) # map ((\\<cdot>) \\<tau>) U)\"\n    using induct_rulify_fallback(2) unifiess.simps by auto\n  then show ?case\n    by (metis Cons.IH list.discI list.sel(3) nth_Cons_0 sapply_eq_system_equiv_def unifies_sapply_eq unifiess.simps)\nqed\n\n(*\n--------------------------------------------------\nAssignment 3\n--------------------------------------------------\n*)\n\nfun lifted_comp :: \"('f, 'v) subst option \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> ('f, 'v) subst option\"\n  where\n  \"lifted_comp None \\<tau> = None\"\n| \"lifted_comp (Some \\<sigma>) \\<tau> = Some (\\<sigma> \\<circ>s \\<tau>)\"\n\nfun get_equations :: \"('f, 'v) term list \\<Rightarrow> ('f, 'v) term list \\<Rightarrow> ('f, 'v) equations\"\n  where\n  \"get_equations [] v = []\"\n| \"get_equations u [] = []\"\n| \"get_equations (h1 # q1) (h2 # q2) = (h1, h2) # (get_equations q1 q2)\"\n\nfun size_term :: \"('f, 'v) term \\<Rightarrow> nat\" where\n  \"size_term (Var x) = 0\"\n| \"size_term (Fun f l) = fold (+) (map size_term l) 1\"\n\nlemma size_term_sound: \"size_term (Fun f l) > fold (+) (map size_term l) 0\"\n  by (simp add: fold_plus_sum_list_rev)\n\n\n\nfun k2 :: \"('f, 'v) equations \\<Rightarrow> nat\" where\n  \"k2 [] = 0\"\n| \"k2 (eq # U) = size_term (fst eq) + k2 U\"\n\nlemma k2_def: \"k2 U = fold (+) (map (size_term \\<circ> fst) U) 0\"\nproof (induction U)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a U)\n  then show ?case by (simp add: fold_plus_sum_list_rev)\nqed\n\nlemma fold_union_basic: \"fold (\\<union>) l s = (fold (\\<union>) l {}) \\<union> s\"\nproof -\n  have \"fold (\\<union>) l s = (\\<Union>x\\<in>(set l).x) \\<union> s\"\n    by (metis Sup_insert Sup_set_fold fold_simps(2) image_ident list.simps(15) sup_bot.right_neutral sup_commute)\n  also have \"... = (fold (\\<union>) l {}) \\<union> s\" by (simp add: Sup_set_fold)\n  then show ?thesis by (simp add: calculation)\nqed\n\nlemma finite_fv: \"finite (fv t)\"\nproof (induction t)\n  case (Var x)\n  then show ?case by auto\nnext\n  case (Fun x1a x2)\n  have \"fv (Fun x1a x2) = (\\<Union>x2a\\<in>(set x2). fv x2a)\" by (meson fv_fun)\n  then show ?case by (simp add: Fun.IH)\nqed\n\nlemma finite_fv_eq: \"finite (fv_eq eq)\"\n  by (simp add: finite_fv)\n\nlemma finite_fold_fv:\n  assumes \"finite s\" \n  shows \"finite (fold (\\<union>) (map fv_eq U) s)\"\n  using assms\nproof (induction U)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a U)\n  then show ?case\n    by (metis Sup_set_fold UN_insert Un_infinite finite_UnI finite_fv_eq fold_union_basic list.set(2) set_map)\nqed\n\nlemma prelim_unify_equations:\n  assumes \"x \\<notin> fv t\"\n  shows \"x \\<notin> fv_eq_system (sapply_eq_system (Var(x := t)) U)\"\nproof (induction U)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a U)\n  have \"fv_eq_system (Var(x := t) \\<cdot> (a # U)) = (fv_eq_system (Var(x := t) \\<cdot> U)) \\<union> (fv_eq (Var(x := t) \\<cdot> a))\"\n    by (metis fold_simps(2) fold_union_basic fv_eq_system.elims list.simps(9) sapply_eq_system.elims sup_bot.right_neutral)\n  moreover have \"x \\<notin> fv_eq_system (Var(x := t) \\<cdot> U)\"\n    using Cons.IH by blast\n  moreover have \"x \\<notin> (fv_eq (Var(x := t) \\<cdot> a))\" by (simp add: assms)\n  then show ?case by (metis Cons.IH UnE calculation(1))\nqed\n\nlemma prelim_prelim_unify:\n  assumes \"y \\<in> fv_eq (Var(x := t) \\<cdot> a)\"\n  shows \"y \\<in> fold (\\<union>) (map fv_eq (a # U)) (insert x (fv t))\"\n  using assms\nproof -\n  have \"\\<And>xa. \\<lbrakk>xa \\<in> fv (fst a); y \\<in> fv (if xa = x then t else Var xa)\\<rbrakk> \\<Longrightarrow> y \\<in> fold (\\<union>) (map fv_eq U) (insert x (fv (fst a) \\<union> fv (snd a) \\<union> fv t))\"\n    by (metis (mono_tags, hide_lams) Sup_set_fold Un_iff Un_insert_right fold_union_basic fv.simps(1) fv_eq.simps inf_sup_aci(5) insert_iff singleton_iff)+\n  moreover have \"\\<And>xa. \\<lbrakk>xa \\<in> fv (snd a); y \\<in> fv (if xa = x then t else Var xa)\\<rbrakk> \\<Longrightarrow> y \\<in> fold (\\<union>) (map fv_eq U) (insert x (fv (fst a) \\<union> fv (snd a) \\<union> fv t))\"\n    by (metis (mono_tags, hide_lams) Sup_set_fold Un_iff Un_insert_right fold_union_basic fv.simps(1) fv_eq.simps inf_sup_aci(5) insert_iff singleton_iff)+\n  then show ?thesis using assms calculation by auto\nqed\n\nlemma prelim_unify_2:\n  assumes \"x \\<notin> fv t\"\n  shows \"(fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) (Var(x := t))) U) {}) \\<subseteq> (fold (\\<union>) (map fv_eq U) (insert x (fv t)))\"\nproof (rule subsetI)\n  fix y\n  assume \"y \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) (Var(x := t))) U) {}\"\n  thus \"y \\<in> fold (\\<union>) (map fv_eq U) (insert x (fv t))\"\n  proof (induction U)\n    case Nil\n    then show ?case by simp\n  next\n    case (Cons a U)\n    then show ?case\n    proof (cases \"y \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) (Var(x := t))) (U)) {}\")\n      case True\n      then show ?thesis\n        by (metis (no_types, lifting) Cons.IH UnCI UnE fold_map fold_simps(2) fold_union_basic)\n    next\n      case False\n      have \"y \\<in> fv_eq (sapply_eq (Var(x := t)) a)\"\n      proof -\n        have \"\\<forall>ps p f. fold (\\<union>) (map f ps) (f (p::('b, 'a) Unify.term \\<times> ('b, 'a) Unify.term)) = fold (\\<union>) (map f (p # ps)) ({}::'a set)\"\n          by simp\n        then show ?thesis\n          by (metis Cons.prems False UnE comp_apply fold_union_basic)\n      qed\n      then show ?thesis by (meson prelim_prelim_unify)\n    qed\n  qed\nqed\n\nlemma measure_unify:\n  assumes \"x \\<notin> fv t\"\n  shows \"card (fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) (Var(x := t))) U) {})\n       < card (fold (\\<union>) (map fv_eq U) (insert x (fv t)))\"\n  (is \"card (?s1) < card (?s2)\")\n  using assms\nproof -\n  have \"?s1 \\<subseteq> ?s2\"\n    by (simp add: assms prelim_unify_2)\n  moreover have \"x \\<notin> ?s1\"\n    using assms prelim_unify_equations by fastforce\n  moreover have \"x \\<in> ?s2\"\n    using fold_union_basic by fastforce\n  have \"?s1 \\<subset> ?s2\"\n    using \\<open>x \\<in> fold (\\<union>) (map fv_eq U) (insert x (fv t))\\<close> calculation(1) calculation(2) by blast\n  moreover have \"finite ?s2\" by (simp add: finite_fold_fv finite_fv)\n  then show ?thesis by (simp add: calculation(3) psubset_card_mono)\nqed\n\nlemma measure_simp:\n  assumes \"x \\<in> fv t\" and \"Var x = t\"\n  shows \"card (fold (\\<union>) (map fv_eq U) {}) < card (fold (\\<union>) (map fv_eq U) (fv t)) \\<or>\n           card (fold (\\<union>) (map fv_eq U) {}) = card (fold (\\<union>) (map fv_eq U) (fv t))\"\n  using assms\n  by (metis card.insert card_eq_0_iff card_mono empty_iff finite_Un fold_union_basic fv.simps(1) le_neq_trans nat.simps(3) sup_ge1)\n\nlemma zip_fst:\n  assumes \"length u = length v\"\n  shows \"(\\<Union>x\\<in>(set (zip u v)). (fv (fst x))) =  (\\<Union>x\\<in>(set u). (fv x))\"\nproof -\n  have \"(\\<Union>x\\<in>(set (zip u v)). (fv (fst x))) = fold (\\<union>) (map (fv \\<circ> fst) (zip u v)) {}\"\n    by (metis (mono_tags, lifting) Sup.SUP_cong Sup_set_fold comp_apply set_map)\n  also have \"... = fold (\\<union>) (map fv (map fst (zip u v))) {}\" by simp\n  also have \"... = fold (\\<union>) (map fv u) {}\" by (simp add: assms)\n  then show ?thesis by (metis Sup_set_fold calculation set_map)\nqed\n\nlemma zip_snd:\n  assumes \"length u = length v\"\n  shows \"(\\<Union>x\\<in>(set (zip u v)). (fv (snd x))) =  (\\<Union>x\\<in>(set v). (fv x))\"\nproof -\n  have \"(\\<Union>x\\<in>(set (zip u v)). (fv (snd x))) = fold (\\<union>) (map (fv \\<circ> snd) (zip u v)) {}\"\n    by (metis (mono_tags, lifting) Sup.SUP_cong Sup_set_fold comp_apply set_map)\n  also have \"... = fold (\\<union>) (map fv (map snd (zip u v))) {}\" by simp\n  also have \"... = fold (\\<union>) (map fv v) {}\" by (simp add: assms)\n  then show ?thesis by (metis Sup_set_fold calculation set_map)\nqed\n\nlemma measure_fun:\n  assumes \"f = g\" and \"length u = length v\"\n  shows \"card (fold (\\<union>) (map fv_eq U) (fold (\\<union>) (map fv_eq (zip u v)) {}))\n       = card (fold (\\<union>) (map fv_eq U) (fold (\\<union>) (map fv u) {} \\<union> fold (\\<union>) (map fv v) {})) \\<and>\n       k2 (zip u v @ U) < fold (+) (map Unify.size_term u) (Suc 0) + k2 U\"\n  using assms\nproof -\n  have \"fold (\\<union>) (map fv_eq (zip u v)) {} = (\\<Union>x\\<in>(set (zip u v)). (fv_eq x))\"\n    by (metis Sup_set_fold set_map)\n  also have \"... = (\\<Union>x\\<in>(set (zip u v)). (fv (fst x) \\<union> fv (snd x)))\" by auto\n  also have \"... = (\\<Union>x\\<in>(set (zip u v)). (fv (fst x))) \\<union>\n                   (\\<Union>x\\<in>(set (zip u v)). (fv (snd x)))\" by blast\n  also have \"... = (\\<Union>x\\<in>(set u). (fv x)) \\<union> (\\<Union>x\\<in>(set v). (fv x))\"\n    by (simp add: assms(2) zip_fst zip_snd)\n  also have \"... = fold (\\<union>) (map fv u) {} \\<union> fold (\\<union>) (map fv v) {}\"\n    by (metis Sup_set_fold image_set)\n  have \"card (fold (\\<union>) (map fv_eq U) (fold (\\<union>) (map fv_eq (zip u v)) {}))\n       = card (fold (\\<union>) (map fv_eq U) (fold (\\<union>) (map fv u) {} \\<union> fold (\\<union>) (map fv v) {}))\"\n    by (simp add: \\<open>(\\<Union>x\\<in>set u. fv x) \\<union> (\\<Union>x\\<in>set v. fv x) = fold (\\<union>) (map fv u) {} \\<union> fold (\\<union>) (map fv v) {}\\<close> calculation)\n  moreover have \"k2 (zip u v @ U) = (fold (+) (map (size_term \\<circ> fst) (zip u v)) 0) + k2 U\"\n    by (simp add: fold_plus_sum_list_rev k2_def)\n  have \"... = (fold (+) (map size_term u) 0) + k2 U\"\n    by (metis assms(2) map_fst_zip map_map)\n  then show ?thesis\n    by (simp add: \\<open>k2 (zip u v @ U) = fold (+) (map (Unify.size_term \\<circ> fst) (zip u v)) 0 + k2 U\\<close>\n        calculation(2) fold_plus_sum_list_rev)\nqed\n\nfunction (sequential) unify :: \"('f, 'v) equations \\<Rightarrow> ('f, 'v) subst option\"\n  where\n  \"unify [] = Some Var\"\n| \"unify ((Var x, t) # U) = (\n  if (x \\<notin> fv t) then\n    lifted_comp (unify((Var(x := t)) \\<cdot> U)) (Var(x := t))\n   else (\n     if Var x = t then unify(U) else None\n    )\n  )\"\n| \"unify ((u, Var y) # U) = unify ((Var y, u) # U)\"\n| \"unify ((Fun f u, Fun g v) # U) =\n  (if (f = g \\<and> length u = length v) then\n    unify(append (zip u v) U)\n  else\n    None)\"\n  by pat_completeness auto\ntermination\n  apply(relation \"measures [\\<lambda>U. card (fv_eq_system U), k2, length]\")\n      apply (simp add: measure_unify measure_simp)+\n   apply (simp add: fold_plus_sum_list_rev measure_fun)\n  apply (simp add: measure_fun)\n  by (metis (mono_tags, lifting) Sup_set_fold list.set_map)\n\n(* 3. (b) *)\n\nlemma alternative_definition_unifiess:\n \"unifiess \\<tau> U \\<longleftrightarrow> (\\<forall>eq\\<in>(set U). unifies \\<tau> eq)\"\nproof (induction U)\n  case Nil\n  then show ?case using unifiess_empty by auto\nnext\n  case (Cons a U)\n  have \"unifiess \\<tau> (a # U) \\<longleftrightarrow> (\\<forall>eq\\<in>set (a # U). unifies \\<tau> eq)\"\n  proof (rule iffI)\n    assume \"unifiess \\<tau> (a # U)\"\n    show \"\\<forall>eq\\<in>set (a # U). unifies \\<tau> eq\"\n      by (metis Cons.IH \\<open>unifiess \\<tau> (a # U)\\<close> list.discI list.sel(3) set_ConsD unifiess.simps)\n  next\n    assume \"\\<forall>eq\\<in>set (a # U). unifies \\<tau> eq\"\n    show  \"unifiess \\<tau> (a # U)\"\n      by (simp add: Cons.IH \\<open>\\<forall>eq\\<in>set (a # U). unifies \\<tau> eq\\<close> unifiess_rec)\n  qed\n  then show ?case by blast\nqed\n\nlemma separate_unifiess:\n  \"unifiess \\<tau> (U @ V) \\<longleftrightarrow> (unifiess \\<tau> U) \\<and> (unifiess \\<tau> V)\"\nproof (rule iffI)\n  assume \"unifiess \\<tau> (U @ V)\"\n  show \"(unifiess \\<tau> U) \\<and> (unifiess \\<tau> V)\"\n  proof -\n    have \"unifiess \\<tau> (U @ V) = (\\<forall>eq\\<in>set (U @ V). unifies \\<tau> eq)\"\n    by (simp add: alternative_definition_unifiess)\n  also have \"... = (\\<forall>eq\\<in>set U. unifies \\<tau> eq) \\<and> (\\<forall>eq\\<in>set V. unifies \\<tau> eq)\"\n    using \\<open>unifiess \\<tau> (U @ V)\\<close> calculation by auto\n  also have \"... = (unifiess \\<tau> U) \\<and> (unifiess \\<tau> V)\"\n    using \\<open>unifiess \\<tau> (U @ V)\\<close> alternative_definition_unifiess calculation by blast\n  then show ?thesis\n    using alternative_definition_unifiess calculation by blast\nqed\nnext\n  assume \"(unifiess \\<tau> U) \\<and> (unifiess \\<tau> V)\"\n  show \"unifiess \\<tau> (U @ V)\"\n  proof -\n    have \"unifiess \\<tau> (U @ V) = (\\<forall>eq\\<in>set (U @ V). unifies \\<tau> eq)\"\n    by (simp add: alternative_definition_unifiess)\n  also have \"... = (\\<forall>eq\\<in>set U. unifies \\<tau> eq) \\<and> (\\<forall>eq\\<in>set V. unifies \\<tau> eq)\"\n    using \\<open>unifiess \\<tau> U \\<and> unifiess \\<tau> V\\<close> alternative_definition_unifiess by fastforce\n  also have \"... = (unifiess \\<tau> U) \\<and> (unifiess \\<tau> V)\"\n    using \\<open>unifiess \\<tau> U \\<and> unifiess \\<tau> V\\<close> alternative_definition_unifiess by blast\n  then show ?thesis\n    using alternative_definition_unifiess calculation by blast\nqed\nqed\n\nlemma case_unify:\n  assumes h1: \"\\<And>\\<sigma>. \\<lbrakk>x \\<notin> fv t; unify (Var(x := t) \\<cdot> U) = Some \\<sigma>\\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> (Var(x := t) \\<cdot> U)\"\n    and h2: \"\\<And>\\<sigma>. \\<lbrakk>\\<not> x \\<notin> fv t; Var x = t; unify U = Some \\<sigma>\\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> U\"\n    and h3: \"unify ((Var x, t) # U) = Some \\<sigma>\"\n  shows \"unifiess \\<sigma> ((Var x, t) # U)\"\n  using assms\nproof (cases \"x \\<in> fv t\")\n  case True\n  then show ?thesis\n    by (metis assms(2) assms(3) option.discI unifies_eq unifiess_rec unify.simps(2))\nnext\n  case False\n  obtain \\<tau> where \"Some \\<tau> = lifted_comp (unify (Var(x := t) \\<cdot> U)) (Var(x := t))\"\n    using False h3 by auto\n  also obtain \\<sigma> where \"(Some \\<sigma>) = (unify (Var(x := t) \\<cdot> U))\"\n    by (metis calculation lifted_comp.elims)\n  have \"\\<tau> =  \\<sigma> \\<circ>s (Var(x := t))\"\n    by (metis \\<open>Some \\<sigma> = unify (Var(x := t) \\<cdot> U)\\<close> calculation lifted_comp.simps(2) map_upd_eqD1)\n  have \"\\<tau> \\<cdot> (Var x) = (\\<sigma> \\<circ>s (Var(x := t))) \\<cdot> (Var x)\"\n    by (simp add: \\<open>\\<tau> = \\<sigma> \\<circ>s Var(x := t)\\<close>)\n  have \"... = \\<sigma> \\<cdot> t\"\n    by simp\n  moreover have \"... = (\\<sigma> \\<circ>s (Var(x := t))) \\<cdot> t\"\n    by (metis (mono_tags, lifting) False fun_upd_other sapply_cong scomp.elims scomp_Var)\n  moreover have \"... = \\<tau> \\<cdot> t\"\n    by (simp add: \\<open>\\<tau> = \\<sigma> \\<circ>s Var(x := t)\\<close>)\n  then show ?thesis\n    by (metis False \\<open>Some \\<sigma> = unify (Var(x := t) \\<cdot> U)\\<close> \\<open>\\<sigma> \\<circ>s Var(x := t) \\<cdot> Var x = \\<sigma> \\<cdot> t\\<close> \\<open>\\<sigma> \\<cdot> t = \\<sigma> \\<circ>s Var(x := t) \\<cdot> t\\<close> \\<open>\\<tau> = \\<sigma> \\<circ>s Var(x := t)\\<close> calculation h1 h3 option.inject unifies_eq unifies_sapply_eq_sys unifiess_rec unify.simps(2))\nqed\n\nlemma unifiess_zip_simple_2:\n  assumes \"unifiess \\<sigma> (zip u v @ U)\"\n  and \"length u = length v\"\n  shows \"unifiess \\<sigma> U\"\n  using assms\nproof (induction u arbitrary: v)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a u)\n  obtain b and vv where \"v = b # vv\"\n    by (metis Cons.prems(2) Suc_length_conv)\n  then show ?case\n    using Cons.IH Cons.prems(1) Cons.prems(2) unifiess.simps by auto\nqed\n\nlemma unifiess_zip_simple_4:\n  assumes \"unifiess \\<sigma> (U @ V)\"\n  shows \"unifiess \\<sigma> U\"\n  using assms\nproof (induction U)\n  case Nil\n  then show ?case\n  by (simp add: unifiess_empty)\nnext\n  case (Cons a U)\n  then show ?case\n    by (metis (no_types, lifting) append_is_Nil_conv hd_append2 list.sel(1) list.sel(3) tl_append2 unifiess.simps)\nqed\n\nlemma test:\n  assumes \"unifiess \\<sigma> u\"\n  shows \"map (sapply \\<sigma>) (map fst u) = map (sapply \\<sigma>) (map snd u)\"\n  using assms\nproof (induction u)\n  case (unifiess_empty \\<sigma>)\n  then show ?case\n    by simp\nnext\n  case (unifiess_rec \\<sigma> s eq)\n  then show ?case\n    using unifies.simps by force\nqed\n  \nlemma case_fun:\n  assumes \" \\<lbrakk>f = g \\<and> length u = length v; unify (zip u v @ U) = Some \\<sigma>\\<rbrakk> \\<Longrightarrow> unifiess \\<sigma> (zip u v @ U)\"\nand \"unify ((Fun f u, Fun g v) # U) = Some \\<sigma>\"\nshows \"unifiess \\<sigma> ((Fun f u, Fun g v) # U)\"\n  using assms\nproof -\n  obtain \"f = g\" and \"length u = length v\"\n    using assms(2) option.discI by fastforce\n  have \"unify (zip u v @ U) = Some \\<sigma>\"\n    using \\<open>f = g\\<close> \\<open>length u = length v\\<close> assms(2) by auto\n  have \"unifiess \\<sigma> (zip u v @ U)\"\n    by (simp add: \\<open>f = g\\<close> \\<open>length u = length v\\<close> \\<open>unify (zip u v @ U) = Some \\<sigma>\\<close> assms(1))\n  have \"unifiess \\<sigma> U\"\n    using \\<open>length u = length v\\<close> \\<open>unifiess \\<sigma> (zip u v @ U)\\<close> unifiess_zip_simple_2 by blast\n  have \"unifiess \\<sigma> (zip u v)\"\n    using \\<open>unifiess \\<sigma> (zip u v @ U)\\<close> unifiess_zip_simple_4 by blast\n  have \"unifies \\<sigma> (Fun f u, Fun g v)\"\n    by (metis \\<open>f = g\\<close> \\<open>length u = length v\\<close> \\<open>unifiess \\<sigma> (zip u v)\\<close> map_fst_zip map_snd_zip sapply.simps(1) test unifies_eq)\n  then show ?thesis\n    by (simp add: \\<open>unifiess \\<sigma> U\\<close> unifiess_rec)\nqed\n\ntheorem soundness1:\n  assumes \"unify U = Some \\<sigma>\"\n  shows \"unifiess \\<sigma> U\"\n  using assms\nproof (induction arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case by (simp add: unifiess_empty)\nnext\n  case (2 x t U)\n  then show ?case by (meson case_unify)\nnext\n  case (3 v va y U)\n  then show ?case\n    by (metis list.discI list.sel(1) list.sel(3) prod.sel(1) prod.sel(2) unifies.simps unifiess.simps unify.simps(3))\nnext\n  case (4 f u g v U)\n  then show ?case by (simp add: case_fun)\nqed\n\n(*\n\nHint: Split the proof into two parts and prove them separately by computational induction.\n(i) If unify returns a substitution, it is a unifier.\n(ii) If unify returns a substitution \\<sigma> and there is another unifier \\<tau> , then\n\\<tau> = \\<rho> ◦s \\<sigma> for some \\<rho>.\n\n*)\n\nlemma unifies_fv_same:\n  assumes \"\\<tau> \\<cdot> Var x = \\<tau> \\<cdot> t\"\n  and \"x \\<notin> fv t\"\n  shows \"sapply (\\<tau> \\<circ>s (Var(x := t))) = sapply \\<tau>\"\nproof (rule ext)\n  show \"sapply (\\<tau> \\<circ>s Var(x := t)) xa = sapply \\<tau> xa\" for xa\n  proof (induction xa rule: term.induct)\n    case (Var y)\n    then show ?case\n      using assms(1) by auto\n  next\n    case (Fun x1a x2)\n    then show ?case by auto\n  qed\nqed\n\nlemma unifies_equal_sapply:\n  assumes \"unifiess \\<sigma> U\"\n  and \"sapply \\<sigma> = sapply \\<tau>\"\nshows \"unifiess \\<tau> U\"\n  by (metis alternative_definition_unifiess assms(1) assms(2) unifies.simps)\n\nlemma sapply_equal:\n  assumes \"sapply \\<sigma> = sapply \\<tau>\"\n  shows \"\\<sigma> = \\<tau>\"\nproof (rule ext)\n  show \"\\<sigma> x = \\<tau> x\" for x\n  proof -\n    have \"\\<sigma> x = sapply \\<sigma> (Var x)\" by (metis sapply.simps(2))\n    also have \"... = sapply \\<tau> (Var x)\" by (simp add: assms)\n    also have \"... = \\<tau> x\" by simp\n    then show ?thesis by (simp add: calculation)\n  qed\nqed\n\nlemma case_mgu_unify:\n  fixes \\<sigma>\n  assumes \"\\<And>\\<sigma>2 \\<tau>. \\<lbrakk>x \\<notin> fv t; unify (Var(x := t) \\<cdot> U) = Some \\<sigma>2; unifiess \\<tau> (Var(x := t) \\<cdot> U)\\<rbrakk> \\<Longrightarrow> \\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>2\"\nand \"\\<And>\\<sigma>2 \\<tau>. \\<lbrakk>\\<not> x \\<notin> fv t; Var x = t; unify U = Some \\<sigma>2; unifiess \\<tau> U\\<rbrakk> \\<Longrightarrow> \\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>2\"\nand \"unify ((Var x, t) # U) = Some \\<sigma>\"\nand \"unifiess \\<tau> ((Var x, t) # U)\"\nshows \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\"\nproof (cases \"x \\<in> fv t\")\n  case True\n  then show ?thesis\n    by (metis assms(2) assms(3) assms(4) list.discI list.sel(3) option.discI unifiess.simps unify.simps(2))\nnext\n  case False\n  obtain \\<sigma>2 where \"unify (Var(x := t) \\<cdot> U) = Some \\<sigma>2\"\n    using False assms(3) by fastforce\n  also have \"\\<sigma> = \\<sigma>2 \\<circ>s (Var(x := t))\"\n    using False assms(3) calculation by auto\n  have \"\\<tau> \\<cdot> (Var x) = \\<tau> \\<cdot> t\"\n    by (metis assms(4) list.discI list.sel(1) prod.sel(1) prod.sel(2) unifies.simps unifiess.simps)\n  have \"\\<forall>(u,w)\\<in>(set U). \\<tau> \\<cdot> u = \\<tau> \\<cdot> w\"\n    by (metis (mono_tags, lifting) alternative_definition_unifiess assms(4) case_prodI2 insert_iff list.set(2) prod.sel(1) prod.sel(2) unifies.simps)\n  have \"unifiess \\<tau> (Var(x := t) \\<cdot> U)\"\n    by (metis False \\<open>\\<tau> \\<cdot> Var x = \\<tau> \\<cdot> t\\<close> assms(4) list.discI list.sel(3) unifies_equal_sapply unifies_fv_same unifies_sapply_eq_sys unifiess.simps)\n  obtain \\<rho> where \"\\<tau> = \\<rho> \\<circ>s \\<sigma>2\"\n    using False \\<open>unifiess \\<tau> (Var(x := t) \\<cdot> U)\\<close> assms(1) calculation by auto\n  moreover have \"sapply (\\<tau> \\<circ>s (Var(x := t))) = sapply \\<tau>\"\n    by (meson False \\<open>\\<tau> \\<cdot> Var x = \\<tau> \\<cdot> t\\<close> unifies_fv_same)\n  moreover have \"\\<tau> = \\<rho> \\<circ>s \\<sigma>\" by (metis \\<open>sapply (\\<tau> \\<circ>s Var(x := t)) = (\\<cdot>) \\<tau>\\<close> \\<open>\\<sigma> = \\<sigma>2 \\<circ>s Var(x := t)\\<close> calculation(2) sapply_equal scomp_assoc)\n  then show ?thesis\n    by blast\nqed\n\nlemma useful_1:\n  assumes \"unifies \\<tau> (Fun f (map fst (a # u)), Fun g (map snd (a # u)))\"\n  shows \"unifies \\<tau> (Fun f (map fst u), Fun g (map snd u))\"\nproof -\n  have \"map (sapply \\<tau>) (map fst (a # u)) = map (sapply \\<tau>) (map snd (a # u))\"\n    by (metis assms prod.sel(1) prod.sel(2) sapply.simps(1) term.inject(2) unifies.simps)\n  also have \"map (sapply \\<tau>) ((fst a) # (map fst u)) = map (sapply \\<tau>) ((snd a) # (map snd u))\"\n    using calculation by auto\n  moreover have \"map (sapply \\<tau>) (map fst u) = map (sapply \\<tau>) (map snd u)\"\n    using \\<open>map ((\\<cdot>) \\<tau>) (fst a # map fst u) = map ((\\<cdot>) \\<tau>) (snd a # map snd u)\\<close> by auto\n  then show ?thesis\n    by (metis (no_types, lifting) assms prod.sel(1) prod.sel(2) sapply.simps(1) term.inject(2) unifies.simps)\nqed\n\nlemma useful_2:\n  assumes \"unifies \\<tau> (Fun f (map fst (a # u)), Fun g (map snd (a # u)))\"\n  shows \"unifies \\<tau> (fst a, snd a)\"\nproof -\n  have \"map (sapply \\<tau>) (map fst (a # u)) = map (sapply \\<tau>) (map snd (a # u))\"\n    by (metis assms prod.sel(1) prod.sel(2) sapply.simps(1) term.inject(2) unifies.simps)\n  moreover have \"map (sapply \\<tau>) ((fst a) # (map fst u)) = map (sapply \\<tau>) ((snd a) # (map snd u))\"\n    using calculation by auto\n  moreover have \"map (sapply \\<tau>) [fst a] = map (sapply \\<tau>) [snd a]\"\n    using \\<open>map ((\\<cdot>) \\<tau>) (fst a # map fst u) = map ((\\<cdot>) \\<tau>) (snd a # map snd u)\\<close> by auto\n  then show ?thesis\n    using unifies_eq by fastforce\nqed\n\nlemma unifies_fun_args:\n  assumes \"unifies \\<tau> (Fun f (map fst u), Fun g (map snd u))\"\n  shows \"unifiess \\<tau> u\"\n  using assms\nproof (induction u)\n  case Nil\n  then show ?case\n    by (simp add: unifiess_empty)\nnext\n  case (Cons a u)\n  then show ?case\n    by (metis prod.collapse unifiess_rec useful_1 useful_2)\nqed\n\nlemma case_mgu_fun:\n  assumes \" \\<lbrakk>f = g \\<and> length u = length v; unify (zip u v @ U) = Some \\<sigma>; unifiess \\<tau> (zip u v @ U)\\<rbrakk>\n        \\<Longrightarrow> \\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\"\nand \"unify ((Fun f u, Fun g v) # U) = Some \\<sigma>\"\nand \"unifiess \\<tau> ((Fun f u, Fun g v) # U)\"\nshows \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\"\n  using assms\nproof -\n  obtain \"f = g\" and \"length u = length v\"\n    using assms(2) by fastforce\n  moreover have \"unify (zip u v @ U) = Some \\<sigma>\"\n    using \\<open>f = g\\<close> \\<open>length u = length v\\<close> assms(2) by auto\n  moreover have \"unifiess \\<tau> (zip u v @ U)\"\n  proof -\n    have \"unifiess \\<tau> U\"\n      by (metis assms(3) list.discI list.sel(3) unifiess.simps)\n    moreover have \"unifies \\<tau> (Fun f u, Fun g v)\"\n      by (metis assms(3) list.discI list.sel(1) unifiess.simps)\n    moreover have \"unifiess \\<tau> (zip u v)\"\n      by (metis \\<open>\\<And>thesis. (\\<lbrakk>f = g; length u = length v\\<rbrakk> \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> \\<open>unifies \\<tau> (Fun f u, Fun g v)\\<close> map_fst_zip map_snd_zip unifies_fun_args)\n    then show ?thesis\n      by (simp add: calculation separate_unifiess)\n  qed\n  then show ?thesis\n    using assms(1) calculation(1) calculation(2) calculation(3) by blast\nqed\n\ntheorem soundness2:\n  assumes \"unify U = Some \\<sigma>\"\n  and \"unifiess \\<tau> U\"\nshows \"\\<exists>\\<rho>. \\<tau> = \\<rho> \\<circ>s \\<sigma>\"\n  using assms\nproof (induction arbitrary: \\<sigma> \\<tau> rule: unify.induct)\n  case 1\n  then show ?case by simp\nnext\n  case (2 x t U)\n  then show ?case\n    by (metis (no_types, lifting) case_mgu_unify)\nnext\n  case (3 v va y U)\n  then show ?case\n    by (metis list.discI list.sel(1) list.sel(3) prod.sel(1) prod.sel(2) unifies.simps unifiess.simps unify.simps(3))\nnext\n  case (4 f u g v U)\nthen show ?case\n  by (meson case_mgu_fun)\nqed\n\ntheorem soundness:\n  \"unify U = Some \\<sigma> \\<Longrightarrow> is_mgu \\<sigma> U\"\n  using is_mgu.simps soundness2 by blast\n\n\n\n\n\n(* (c). Formalize theorem 3 *)\n\nlemma increasing_sum_liste:\n \"xa \\<in> (set x2) \\<Longrightarrow> sum_list (map size_term (map (sapply \\<tau>) x2))  \\<ge>\nsum_list (map size_term (map (sapply \\<tau>) [xa]))\"\nproof (induction x2)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a x2)\n  then show ?case using list.simps(8) set_ConsD by auto\nqed\n\nlemma size_term_fun:\n  assumes \"xa \\<in> (set x2)\"\n  shows \"size_term (sapply \\<tau> xa) \\<le> size_term (sapply \\<tau> (Fun x1a x2))\"\n  using assms\nproof -\n\n(* Basically\nsize_term (Fun x1a (map (sapply \\<tau>) x2)) \\<ge> sum_list (map size_term (map (sapply \\<tau>) x2))\n    \\<ge> size_term (sapply \\<tau> xa)\"\n*)\n\n  have \"sapply \\<tau> (Fun x1a x2) = Fun x1a (map (sapply \\<tau>) x2)\" by simp\n  also have \"size_term (Fun x1a (map (sapply \\<tau>) x2)) \\<ge>\n            fold (+) (map size_term (map (sapply \\<tau>) x2)) 0\"\n    by (meson less_imp_le_nat size_term_sound)\n  also have \"fold (+) (map size_term (map (sapply \\<tau>) x2)) (0 :: nat) = sum_list (map size_term (map (sapply \\<tau>) x2))\"\n    by (simp add: fold_plus_sum_list_rev)\n  also have \"... \\<ge> sum_list (map size_term (map (sapply \\<tau>) [xa]))\"\n    using assms increasing_sum_liste by auto\n  have \"sum_list (map size_term (map (sapply \\<tau>) [xa])) = size_term (sapply \\<tau> xa)\" by simp\n  then show ?thesis\n    using \\<open>sum_list (map Unify.size_term (map ((\\<cdot>) \\<tau>) [xa])) \\<le> sum_list (map Unify.size_term (map ((\\<cdot>) \\<tau>) x2))\\<close> calculation by linarith\nqed\n\nlemma size_term_subterm_prelim:\n  \"x \\<in> fv t \\<Longrightarrow> size_term (\\<tau> \\<cdot> (Var x)) \\<le> size_term (\\<tau> \\<cdot> t)\"\nproof (induction t)\n  case (Var y)\n  then show ?case\n    by simp\nnext\n  case (Fun x1a x2)\n\n(* We go deeper *)\n  obtain xa where \"xa \\<in> (set x2)\" and \"x \\<in> fv xa\"\n    by (metis Fun.prems UN_E fv_fun)\n\n(* Induction hypothesis *)\n  also have \"size_term (sapply \\<tau> (Var x)) \\<le> size_term (sapply \\<tau> xa)\"\n    using Fun.IH calculation by auto\n  have \"size_term (sapply \\<tau> xa) \\<le> size_term (sapply \\<tau> (Fun x1a x2))\"\n    using calculation(1) size_term_fun by auto\n  then show ?case\n    using \\<open>Unify.size_term (\\<tau> \\<cdot> Var x) \\<le> Unify.size_term (\\<tau> \\<cdot> xa)\\<close> dual_order.trans by blast\nqed\n\nlemma size_term_subset:\n  \"xa \\<in> (set l) \\<Longrightarrow> size_term (\\<tau> \\<cdot> (Fun f l)) \\<ge> 1 + size_term (\\<tau> \\<cdot> xa)\"\nproof (induction l)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a ll)\n  then show ?case\n  proof (cases \"xa = a\")\n    case True\n    have \"size_term (sapply \\<tau> (Fun f (xa # ll))) =\n          size_term ((sapply \\<tau>) xa) + (size_term (sapply \\<tau> (Fun f ll)))\"\n      by (simp add: fold_plus_sum_list_rev)\n    then show ?thesis\n      by (simp add: True fold_plus_sum_list_rev)\n  next\n    case False\n    have \"xa \\<in> (set ll)\" using Cons.prems False by auto\n    also have \"size_term (sapply \\<tau> (Fun f ll)) \\<ge> 1 + size_term (sapply \\<tau> xa)\"\n      using Cons.IH calculation by auto\n    have \"size_term (\\<tau> \\<cdot> Fun f (a # ll)) = size_term (Fun f (map (sapply \\<tau>) (a # ll)))\"\n      by simp\n    have \"... = size_term ((sapply \\<tau>) a) + size_term (Fun f (map (sapply \\<tau>) ll))\"\n      by (simp add: fold_plus_sum_list_rev)\n    then show ?thesis\n      using \\<open>1 + Unify.size_term (\\<tau> \\<cdot> xa) \\<le> Unify.size_term (\\<tau> \\<cdot> Fun f ll)\\<close> by auto\n  qed\nqed\n\nlemma size_term_subterm:\n  assumes \"x \\<in> fv t\"\n  and \"\\<not> (Var x = t)\"\nshows \"size_term (sapply \\<tau> (Var x)) < size_term (sapply \\<tau> t)\"\nproof -\n\n(* t is necessarily a function *)\n  obtain f and l where \"t = Fun f l\"\n    by (metis (full_types) Unify.term.simps(17) assms(1) assms(2) fv.elims term.set_cases(2))\n\n(* we go deeper and find xa in t *)\n  also obtain xa where \"(xa \\<in> (set l)) \\<and> x \\<in> fv xa\"\n    by (metis UN_E assms(1) calculation fv_fun)\n\n(* we get the inequality for xa using size_term_subterm_prelim *)\n  have \"size_term (sapply \\<tau> (Var x)) \\<le> size_term (sapply \\<tau> xa)\"\n    by (meson \\<open>xa \\<in> set l \\<and> x \\<in> fv xa\\<close> size_term_subterm_prelim)\n\n(* we transform this inequality into a strict one for t *)\n  moreover have \"size_term (sapply \\<tau> t) > size_term (sapply \\<tau> xa)\"\n    by (metis (no_types, lifting) \\<open>xa \\<in> set l \\<and> x \\<in> fv xa\\<close> calculation(1) le_less_trans lessI linorder_neqE_nat order.asym plus_1_eq_Suc size_term_subset)\n\n  then show ?thesis\n    using calculation(2) le_less_trans by blast\nqed\n\nlemma lemma2:\n  assumes \"\\<exists>\\<tau>. unifiess \\<tau> U\"\n  shows \"\\<not>(unify U = None)\"\n  using assms\nproof (induction rule: unify.induct)\n  case 1\n\n(* BASE case *)\n\n  then show ?case by simp\nnext\n  case (2 x t U)\n  then show ?case\n  proof (cases \"x \\<in> fv t\")\n    case True\n   \n    (* OCCURS case *)\n    \n    have \"Var x = t\"\n    proof (rule ccontr)\n      assume \"\\<not> (Var x = t)\"\n      show \"False\"\n      proof -\n        obtain \\<tau> where \"unifiess \\<tau> ((Var x, t) # U)\"\n          using \"2.prems\" by blast\n        also have \"sapply \\<tau> (Var x) = sapply \\<tau> t\"\n          by (metis calculation list.discI list.sel(1) prod.sel(1) prod.sel(2) unifies.simps unifiess.simps)\n        have \"size_term (\\<tau> \\<cdot> (Var x)) = size_term (\\<tau> \\<cdot> t)\"\n          using \\<open>\\<tau> \\<cdot> Var x = \\<tau> \\<cdot> t\\<close> by auto\n        have \"size_term (\\<tau> \\<cdot> (Var x)) < size_term (\\<tau> \\<cdot> t)\"\n          by (meson True \\<open>Var x \\<noteq> t\\<close> size_term_subterm)\n        then show ?thesis\n          using \\<open>Unify.size_term (\\<tau> \\<cdot> Var x) = Unify.size_term (\\<tau> \\<cdot> t)\\<close> nat_neq_iff by blast\n      qed\n    qed\n\n    (* SIMP case *)\n  \n    then show ?thesis\n      by (metis \"2.IH\"(2) \"2.prems\" fv.simps(1) insert_iff list.discI list.sel(3) unifiess.simps unify.simps(2))\n  next\n    case False\n    (* UNIFY case *)\n    obtain \\<tau> where \"unifiess \\<tau> ((Var x, t) # U)\"\n      using \"2.prems\" by blast\n    also have \"\\<tau> \\<cdot> (Var x) = \\<tau> \\<cdot> t\"\n      by (metis calculation list.discI list.sel(1) prod.sel(1) prod.sel(2) unifies.simps unifiess.simps)\n    have \"sapply (\\<tau> \\<circ>s (Var(x := t))) = sapply \\<tau>\"\n      by (meson False \\<open>\\<tau> \\<cdot> Var x = \\<tau> \\<cdot> t\\<close> unifies_fv_same)\n    have \"unifiess (\\<tau> \\<circ>s (Var(x := t))) U\"\n      by (metis \\<open>sapply (\\<tau> \\<circ>s Var(x := t)) = sapply \\<tau>\\<close> calculation list.distinct(1) list.sel(3) unifies_equal_sapply unifiess.cases)\n    then show ?thesis\n      using \"2.IH\"(1) False unifies_sapply_eq_sys by fastforce\n  qed\nnext\n  case (3 v va y U)\n(* SWAP case *)\n  then show ?case\n  by (metis list.discI list.sel(1) list.sel(3) prod.sel(1) prod.sel(2) unifies.simps unifiess.simps unify.simps(3))\nnext\n  case (4 f u g v U)\n(* FAIL not possible *)\n(* FUN case *)\n  obtain \"f = g\" and \"length u = length v\"\n    by (metis (no_types, lifting) \"4.prems\" length_map list.discI list.sel(1) prod.sel(1) prod.sel(2) sapply.simps(1) term.inject(2) unifies.simps unifiess.simps)\n  then show ?case\n    by (metis (no_types, lifting) \"4.IH\" \"4.prems\" list.discI list.sel(1) list.sel(3) map_fst_zip map_snd_zip separate_unifiess unifies_fun_args unifiess.simps unify.simps(4))\nqed\n\ntheorem completeness:\n  assumes \"\\<exists>\\<tau>. unifiess \\<tau> U\"\n  shows \"\\<exists>\\<sigma>. unify U = Some \\<sigma> \\<and> unifiess \\<sigma> U\"\n  using assms lemma2 soundness1 by fastforce\n\n\n\n\n\n\n\n\n\n\n\n\n(* (d). Lemma 3 *)\n\nlemma simple_fv_eq_system_double_var:\n  \"fv_eq_system ((Var x, Var y) # U) = (fv_eq_system U) \\<union> {x, y}\" (is \"?A = ?B\")\nproof -\n  have \"?A \\<subseteq> ?B\"\n  proof (rule subsetI)\n    fix xa assume \"xa \\<in> ?A\" then show \"xa \\<in> ?B\"\n    proof (cases \"xa \\<in> fv_eq_system U\")\n      case True then show ?thesis by simp\n    next\n      case False\n      have \"xa = x \\<or> xa = y\"\n        by (metis (no_types, lifting) False Sup_set_fold UN_insert UnE UnI2 \\<open>xa \\<in> fv_eq_system ((Var x, Var y) # U)\\<close> fold_union_basic fv.simps(1) fv_eq.elims fv_eq_system.elims insert_iff list.simps(15) prod.sel(1) prod.sel(2) set_map)\n      then show ?thesis by blast\n    qed\n  qed\n  moreover have \"?B \\<subseteq> ?A\"\n  proof (rule subsetI)\n    fix xa assume \"xa \\<in> ?B\" then show \"xa \\<in> ?A\"\n    proof (cases \"xa \\<in> {x, y}\")\n      case True\n      then show ?thesis\n        by (metis (no_types, lifting) Sup_set_fold UN_insert \\<open>xa \\<in> fv_eq_system U \\<union> {x, y}\\<close> fv.simps(1) fv_eq.elims fv_eq_system.elims inf_sup_aci(5) insert_is_Un list.simps(15) prod.sel(1) prod.sel(2) set_map)\n    next\n      case False\n      then show ?thesis\n        by (metis (no_types, lifting) Sup_set_fold UN_insert \\<open>xa \\<in> fv_eq_system U \\<union> {x, y}\\<close> fv.simps(1) fv_eq.elims fv_eq_system.elims inf_sup_aci(5) insert_is_Un list.simps(15) prod.sel(1) prod.sel(2) set_map)\n    qed\n  qed\n  then show ?thesis using calculation by blast\nqed\n\nlemma simple_fv_apply:\n  \"fv_eq_system (\\<sigma> \\<cdot> ((Var x, Var y) # U)) = fv (\\<sigma> x) \\<union> fv (\\<sigma> y) \\<union> fv_eq_system (\\<sigma> \\<cdot> U)\"\nproof -\n  have \"\\<And>xa. \\<lbrakk>xa \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) \\<sigma>) U) (fv (\\<sigma> x) \\<union> fv (\\<sigma> y)); xa \\<notin> fv (\\<sigma> x); xa \\<notin> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) \\<sigma>) U) {}\\<rbrakk> \\<Longrightarrow> xa \\<in> fv (\\<sigma> y)\"\n    by (metis UnE fold_union_basic)\n  moreover have \"\\<And>xa. xa \\<in> fv (\\<sigma> x) \\<Longrightarrow> xa \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) \\<sigma>) U) (fv (\\<sigma> x) \\<union> fv (\\<sigma> y))\"\n    using fold_union_basic by fastforce\n  moreover have \"\\<And>xa. xa \\<in> fv (\\<sigma> y) \\<Longrightarrow> xa \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) \\<sigma>) U) (fv (\\<sigma> x) \\<union> fv (\\<sigma> y))\"\n    using fold_union_basic by force\n  moreover have \"\\<And>xa. xa \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) \\<sigma>) U) {} \\<Longrightarrow> xa \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) \\<sigma>) U) (fv (\\<sigma> x) \\<union> fv (\\<sigma> y))\"\n    using fold_union_basic by fastforce\n  then show ?thesis using calculation by (auto simp add: SUP_union simple_fv_eq_system_double_var sup_assoc sup_left_commute)\nqed\n\nlemma simple_fold_map_first_elem:\n  \"fold (\\<union>) (map f (t # q)) {} = (f t) \\<union> fold (\\<union>) (map f q) {}\"\n  by (metis Sup_set_fold UN_insert list.simps(15) set_map)\n\nlemma fv_fun_simple:\n  \"fv_eq (Fun f (map fst U), Fun g (map snd U)) = fv_eq_system U\"\nproof (induction U)\n  case Nil\n  have \"fv_eq (Fun f (map fst []), Fun g (map snd [])) = fv_eq (Fun f [], Fun g [])\" by auto\n  also have \"... = (fold (\\<union>) (map fv []) {}) \\<union> (fold (\\<union>) (map fv []) {})\" by simp\n  have \"(fold (\\<union>) (map fv []) {}) = {}\" by simp\n  have \"fv_eq_system [] = {}\" by auto\n  then show ?case by simp\nnext\n  case (Cons a U)\n  have \"fv_eq (Fun f ((fst a) # (map fst U)), Fun g ((snd a) # (map snd U))) = (fv (fst a)) \\<union> (fold (\\<union>) (map fv (map fst U)) {}) \\<union> (fv (snd a)) \\<union> (fold (\\<union>) (map fv (map snd U)) {})\"\n    by (metis (no_types, lifting) equi_def_fv fst_conv fv_eq.elims simple_fold_map_first_elem snd_conv sup_assoc)\n  also have \"... = (fv_eq a) \\<union> (fold (\\<union>) (map fv (map fst U)) {}) \\<union> (fold (\\<union>) (map fv (map snd U)) {})\" by auto\n  have \"(fold (\\<union>) (map fv (map fst U)) {}) \\<union> (fold (\\<union>) (map fv (map snd U)) {}) = fv_eq (Fun f (map fst U), Fun g (map snd U))\"\n    by (metis equi_def_fv fst_conv fv_eq.elims snd_conv)\n  have \"fv_eq (Fun f (map fst U), Fun g (map snd U)) = fv_eq_system U\" using Cons.IH by blast\n  then show ?case\n    by (metis \\<open>fold (\\<union>) (map fv (map fst U)) {} \\<union> fold (\\<union>) (map fv (map snd U)) {} = fv_eq (Fun f (map fst U), Fun g (map snd U))\\<close> \\<open>fv (fst a) \\<union> fold (\\<union>) (map fv (map fst U)) {} \\<union> fv (snd a) \\<union> fold (\\<union>) (map fv (map snd U)) {} = fv_eq a \\<union> fold (\\<union>) (map fv (map fst U)) {} \\<union> fold (\\<union>) (map fv (map snd U)) {}\\<close> calculation fv_eq_system.elims list.simps(9) simple_fold_map_first_elem sup_assoc)\nqed\n\nlemma fv_fun_simple_alternative:\n  assumes \"length u = length v\"\n  shows \"fv_eq (Fun f u, Fun g v) = fv_eq_system (zip u v)\"\n  by (metis assms fv_fun_simple map_fst_zip map_snd_zip)\n\nlemma fv_union:\n  \"(fv_eq_system U) \\<union> (fv_eq_system V) = fv_eq_system (U @ V)\"\nproof (induction U)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a U)\n  then show ?case\n    by (metis (no_types, lifting) append_Cons fv_eq_system.elims inf_sup_aci(5) simple_fold_map_first_elem sup_left_commute)\nqed\n\nlemma fv_eq_fun_lists:\n  assumes \"length u = length v\"\n  shows \"fv_eq_system (zip u v @ U) = fv_eq_system ((Fun f u, Fun g v) # U)\"\nproof -\n  have \"fv_eq_system ((Fun f u, Fun g v) # U) = (fv_eq (Fun f u, Fun g v)) \\<union> (fv_eq_system U)\"\n    by (metis (no_types, lifting) Sup_set_fold UN_insert fv_eq_system.elims list.simps(15) set_map)\n  have \"fv_eq (Fun f u, Fun g v) = fv_eq_system (zip u v)\" using assms fv_fun_simple_alternative by fastforce\n  also have \"fv_eq_system (zip u v) \\<union> (fv_eq_system U) = fv_eq_system (zip u v @ U)\" by (meson fv_union)\n  then show ?thesis\n    using \\<open>fv_eq_system ((Fun f u, Fun g v) # U) = fv_eq (Fun f u, Fun g v) \\<union> fv_eq_system U\\<close> calculation by blast\nqed\n\nlemma fv_subst_term:\n  \"fv (Var(x := t) \\<cdot> tt) \\<subseteq> fv t \\<union> fv tt\"\nproof -\n  have \"\\<And>xa xaa. \\<lbrakk>xaa \\<in> fv tt; xa \\<in> fv (if xaa = x then t else Var xaa); xa \\<notin> fv tt\\<rbrakk> \\<Longrightarrow> xa \\<in> fv t\"\n    by (metis (full_types) fv.simps(1) singletonD)\n  then show ?thesis by auto\nqed\n\nlemma fv_subst_eq:\n  \"fv_eq (Var(x := t) \\<cdot> eq) \\<subseteq> fv t \\<union> fv_eq eq\"\nproof -\n  have \"\\<And>xa xaa. \\<lbrakk>xaa \\<in> fv (fst eq); xa \\<in> fv (if xaa = x then t else Var xaa); xa \\<notin> fv t; xa \\<notin> fv (snd eq)\\<rbrakk> \\<Longrightarrow> xa \\<in> fv (fst eq)\"\n    by (metis (full_types) fv.simps(1) singletonD)\n  moreover have \"\\<And>xa xaa. \\<lbrakk>xaa \\<in> fv (snd eq); xa \\<in> fv (if xaa = x then t else Var xaa); xa \\<notin> fv t; xa \\<notin> fv (snd eq)\\<rbrakk> \\<Longrightarrow> xa \\<in> fv (fst eq)\"\n    by (metis (full_types) fv.simps(1) singletonD)\n  then show ?thesis using calculation by (auto simp add: fv_eq.elims fv_subst_term le_supI1 le_supI2 sup_assoc sup_left_commute)\nqed\n\nlemma fv_subst_eqs:\n  \"fv_eq_system (Var(x := t) \\<cdot> U) \\<subseteq> fv t \\<union> fv_eq_system U\"\nproof (induction U)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a U)\n  have \"fv_eq_system (Var(x := t) \\<cdot> (a # U)) = fv_eq (Var(x := t) \\<cdot> a) \\<union> fv_eq_system (Var(x := t) \\<cdot> U)\"\n    by (metis fv_eq_system.elims list.simps(9) sapply_eq_system.elims simple_fold_map_first_elem)\n  also have \"... \\<subseteq> fv t \\<union> fv_eq a \\<union> fv t \\<union> fv_eq_system U\"\n  proof -\n    have \"\\<And>xa. \\<lbrakk>xa \\<in> fold (\\<union>) (map (fv_eq \\<circ> (\\<cdot>) (Var(x := t))) U) {}; xa \\<notin> fold (\\<union>) (map fv_eq U) {}; xa \\<notin> fv t; xa \\<notin> fv (snd a)\\<rbrakk> \\<Longrightarrow> xa \\<in> fv (fst a)\"\n      by (metis Cons.IH UnE fv_eq_system.simps map_map sapply_eq_system.elims subsetCE)\n    moreover have \"\\<And>xa xaa. \\<lbrakk>xaa \\<in> fv (fst a); xa \\<in> fv (if xaa = x then t else Var xaa); xa \\<notin> fold (\\<union>) (map fv_eq U) {}; xa \\<notin> fv t; xa \\<notin> fv (snd a)\\<rbrakk> \\<Longrightarrow> xa \\<in> fv (fst a)\"\n      by (metis (full_types) fv.simps(1) singletonD)\n    moreover have \"\\<And>xa xaa. \\<lbrakk>xaa \\<in> fv (snd a); xa \\<in> fv (if xaa = x then t else Var xaa); xa \\<notin> fold (\\<union>) (map fv_eq U) {}; xa \\<notin> fv t; xa \\<notin> fv (snd a)\\<rbrakk> \\<Longrightarrow> xa \\<in> fv (fst a)\"\n      by (metis (full_types) fv.simps(1) singletonD)\n    then show ?thesis using calculation by (auto simp add: Cons.IH Un_upper1 fv_subst_eq inf_sup_aci(5) subset_trans)\n  qed\n  then show ?case\n    by (metis (no_types, lifting) calculation fv_eq_system.elims inf_sup_aci(5) simple_fold_map_first_elem sup_assoc sup_left_idem)\nqed\n\nlemma lemma_3_i_iii:\n  \"unify U = Some \\<sigma> \\<Longrightarrow> fv_eq_system (\\<sigma> \\<cdot> U) \\<subseteq> fv_eq_system U \\<and> sdom \\<sigma> \\<subseteq> fv_eq_system U \\<and> svran \\<sigma> \\<subseteq> fv_eq_system U\"\nproof (induction arbitrary: \\<sigma> rule: unify.induct)\n  case 1\n  then show ?case\n    by (metis empty_iff list.simps(8) option.inject sapply_eq_system.elims sdom_Var subsetI svran_Var unify.simps(1))\nnext\n  case (2 x t U)\n  then show ?case\n  proof (cases \"x \\<in> fv t\")\n    case True\n    have \"Var x = t\"\n    proof (rule ccontr)\n      assume \"\\<not> (Var x = t)\"\n      show \"False\"\n      proof -\n        show ?thesis using \"2\"(3) True \\<open>Var x \\<noteq> t\\<close> by simp\n      qed\n    qed\n\n  (* SIMP CASE *)\n\n    have \"unify U = unify ((Var x, t) # U)\" using \\<open>Var x = t\\<close> by auto\n    have \"fv_eq_system (\\<sigma> \\<cdot> U) \\<subseteq> fv_eq_system U \\<and> sdom \\<sigma> \\<subseteq> fv_eq_system U \\<and> svran \\<sigma> \\<subseteq> fv_eq_system U\"\n      using \"2\"(2) \"2.prems\" True \\<open>Var x = t\\<close> \\<open>unify U = unify ((Var x, t) # U)\\<close> by auto\n    also have \"fv_eq_system ((Var x, t) # U) = (fv_eq_system U) \\<union> {x}\"\n      by (metis \\<open>Var x = t\\<close> insert_absorb2 simple_fv_eq_system_double_var)\n    moreover have \"fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) = fv (\\<sigma> x) \\<union> fv_eq_system (\\<sigma> \\<cdot> U)\"\n      using \\<open>Var x = t\\<close> simple_fv_apply by fastforce\n    have \"fv (\\<sigma> x) \\<subseteq> {x} \\<union> fv_eq_system ((Var x, t) # U)\"\n    proof -\n      have \"fv (\\<sigma> x) \\<subseteq> (fv (Var x) - sdom \\<sigma>) \\<union> svran \\<sigma>\"\n        by (metis fv.simps(1) fv_sapply_sdom_svran sapply.simps(2) subsetI)\n      have \"(fv (Var x) - sdom \\<sigma>) \\<union> svran \\<sigma> \\<subseteq> (fv (Var x) - sdom \\<sigma>) \\<union> fv_eq_system U\"\n        using calculation(1) by fastforce\n      moreover have \"(fv (Var x) - sdom \\<sigma>) \\<subseteq> {x} \\<union> fv_eq ((Var x, t))\" by auto\n      also have \"fv_eq ((Var x, t)) \\<subseteq> fv_eq_system ((Var x, t) # U)\"\n        using \\<open>Var x = t\\<close> \\<open>fv_eq_system ((Var x, t) # U) = fv_eq_system U \\<union> {x}\\<close> fv_eq.elims by auto\n      moreover have \"fv_eq_system U \\<subseteq> fv_eq_system ((Var x, t) # U)\"\n        using \\<open>fv_eq_system ((Var x, t) # U) = fv_eq_system U \\<union> {x}\\<close> by auto\n      then show ?thesis\n        using \\<open>Var x = t\\<close> \\<open>fv (\\<sigma> x) \\<subseteq> fv (Var x) - sdom \\<sigma> \\<union> svran \\<sigma>\\<close> calculation(1) by fastforce\n    qed\n    moreover have \"sdom \\<sigma> \\<subseteq> fv_eq_system ((Var x, t) # U)\"\n      using calculation(1) calculation(2) by blast\n    moreover have \"svran \\<sigma> \\<subseteq> fv_eq_system ((Var x, t) # U)\"\n      using calculation(1) calculation(2) by blast\n    then show ?thesis\n      using \\<open>fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) = fv (\\<sigma> x) \\<union> fv_eq_system (\\<sigma> \\<cdot> U)\\<close> calculation(1) calculation(2) calculation(3) by auto\n  next\n    case False\n\n(* CASE UNIFY *)\n\n    obtain \\<tau> where \"unify (Var(x := t) \\<cdot> U) = Some \\<tau>\"\n      using \"2.prems\" False by force\n    also obtain \"fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U) \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U)\"\n      and \"sdom \\<tau> \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U)\"\n      and \"svran \\<tau> \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U)\"\n      using \"2.IH\"(1) False calculation by blast\n    have \"\\<sigma> = \\<tau> \\<circ>s (Var(x := t))\"\n      using \"2.prems\" False calculation by auto\n    have \"fv_eq_system ((Var(x := t)) \\<cdot> U) \\<subseteq> fv t \\<union> fv_eq_system U\" by (meson fv_subst_eqs)\n    obtain \"fv_eq_system (\\<tau> \\<cdot> (Var(x := t) \\<cdot> U)) \\<subseteq> fv t \\<union> fv_eq_system U\"\n      and \"sdom \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\"\n      and \"svran \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\"\n      using \\<open>\\<And>thesis. (\\<lbrakk>fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U) \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U); sdom \\<tau> \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U); svran \\<tau> \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U)\\<rbrakk> \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> \\<open>fv_eq_system (Var(x := t) \\<cdot> U) \\<subseteq> fv t \\<union> fv_eq_system U\\<close> subset_trans by auto\n    have \"fv_eq_system ((Var x, t) # U) = fv t \\<union> fv_eq_system U \\<union> {x}\"\n      by (metis (no_types, lifting) fv.simps(1) fv_eq.elims fv_eq_system.elims inf_sup_aci(5) prod.sel(1) prod.sel(2) simple_fold_map_first_elem sup_assoc)\n    have \"fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) = fv_eq_system ((\\<tau> \\<circ>s Var(x := t)) \\<cdot> ((Var x, t) # U))\"\n      using \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> by blast\n    have \"... = fv_eq ((\\<tau> \\<circ>s Var(x := t)) \\<cdot> (Var x, t)) \\<union> fv_eq_system ((\\<tau> \\<circ>s Var(x := t)) \\<cdot> U)\"\n      by (metis SUP_union fv_eq_system.elims fv_sapply_eq fv_sapply_eq_system simple_fold_map_first_elem)\n    have \"... = fv_eq (\\<tau> \\<cdot> (Var(x := t) \\<cdot> (Var x, t))) \\<union> fv_eq_system (\\<tau> \\<cdot> (Var(x := t) \\<cdot> U))\"\n      by (metis sapply_scomp_distrib_eq sapply_scomp_distrib_eq_system)\n    have \"... = fv (\\<tau> \\<cdot> t) \\<union> fv_eq_system (\\<tau> \\<cdot> (Var(x := t) \\<cdot> U))\"\n      using fv_subst_term by fastforce\n    have \"sdom \\<sigma> \\<subseteq> fv_eq_system ((Var x, t) # U)\"\n      using \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> \\<open>fv_eq_system ((Var x, t) # U) = fv t \\<union> fv_eq_system U \\<union> {x}\\<close> \\<open>sdom \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\\<close> by auto\n    have \"svran \\<sigma> \\<subseteq> fv_eq_system ((Var x, t) # U)\"\n      by (metis (no_types, lifting) False Un_assoc \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> \\<open>fv_eq_system ((Var x, t) # U) = fv t \\<union> fv_eq_system U \\<union> {x}\\<close> \\<open>svran \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\\<close> fv.simps(1) singletonI subset_Un_eq svran_scomp svran_single_non_trivial)\n\n    have \"fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) = fv (\\<tau> \\<cdot> t) \\<union> fv_eq_system (\\<tau> \\<cdot> (Var(x := t) \\<cdot> U))\"\n      using \\<open>fv_eq (\\<tau> \\<cdot> Var(x := t) \\<cdot> (Var x, t)) \\<union> fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U) = fv (\\<tau> \\<cdot> t) \\<union> fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U)\\<close> \\<open>fv_eq (\\<tau> \\<circ>s Var(x := t) \\<cdot> (Var x, t)) \\<union> fv_eq_system (\\<tau> \\<circ>s Var(x := t) \\<cdot> U) = fv_eq (\\<tau> \\<cdot> Var(x := t) \\<cdot> (Var x, t)) \\<union> fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U)\\<close> \\<open>fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) = fv_eq_system (\\<tau> \\<circ>s Var(x := t) \\<cdot> ((Var x, t) # U))\\<close> \\<open>fv_eq_system (\\<tau> \\<circ>s Var(x := t) \\<cdot> ((Var x, t) # U)) = fv_eq (\\<tau> \\<circ>s Var(x := t) \\<cdot> (Var x, t)) \\<union> fv_eq_system (\\<tau> \\<circ>s Var(x := t) \\<cdot> U)\\<close> by blast\n    have \"fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) \\<subseteq> fv (\\<tau> \\<cdot> t) \\<union> fv t \\<union> fv_eq_system U\"\n      using \\<open>fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) = fv (\\<tau> \\<cdot> t) \\<union> fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U)\\<close> \\<open>fv_eq_system (\\<tau> \\<cdot> Var(x := t) \\<cdot> U) \\<subseteq> fv t \\<union> fv_eq_system U\\<close> by auto\n    have \"fv (\\<tau> \\<cdot> t) \\<subseteq> (fv t - sdom \\<tau>) \\<union> svran \\<tau>\"\n      by (meson fv_sapply_sdom_svran subsetI)\n    have \"svran \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\"\n      using \\<open>svran \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\\<close> by linarith\n    have \"fv (\\<tau> \\<cdot> t) \\<subseteq> (fv t - sdom \\<tau>) \\<union> fv t \\<union> fv_eq_system U\"\n      using \\<open>fv (\\<tau> \\<cdot> t) \\<subseteq> fv t - sdom \\<tau> \\<union> svran \\<tau>\\<close> \\<open>svran \\<tau> \\<subseteq> fv t \\<union> fv_eq_system U\\<close> by blast\n    have \"fv (\\<tau> \\<cdot> t) \\<subseteq>  fv t \\<union> fv_eq_system U\"\n      using \\<open>fv (\\<tau> \\<cdot> t) \\<subseteq> fv t - sdom \\<tau> \\<union> fv t \\<union> fv_eq_system U\\<close> by auto\n    then show ?thesis\n      using \\<open>fv_eq_system ((Var x, t) # U) = fv t \\<union> fv_eq_system U \\<union> {x}\\<close> \\<open>fv_eq_system (\\<sigma> \\<cdot> ((Var x, t) # U)) \\<subseteq> fv (\\<tau> \\<cdot> t) \\<union> fv t \\<union> fv_eq_system U\\<close> \\<open>sdom \\<sigma> \\<subseteq> fv_eq_system ((Var x, t) # U)\\<close> \\<open>svran \\<sigma> \\<subseteq> fv_eq_system ((Var x, t) # U)\\<close> by blast\n  qed\nnext\n  case (3 v va y U)\n  then show ?case by (simp add: inf_sup_aci(5))\nnext\n  case (4 f u g v U)\n  have \"f = g \\<and> length u = length v\" using \"4.prems\" option.discI by (metis unify.simps(4))\n  have \"unify (zip u v @ U) = Some \\<sigma>\" using \"4.prems\" \\<open>f = g \\<and> length u = length v\\<close> by auto\n  obtain \"fv_eq_system (\\<sigma> \\<cdot> (zip u v @ U)) \\<subseteq> fv_eq_system (zip u v @ U)\"\n    and \"sdom \\<sigma> \\<subseteq> fv_eq_system (zip u v @ U)\"\n    and \"svran \\<sigma> \\<subseteq> fv_eq_system (zip u v @ U)\"\n    using \"4.IH\" \\<open>f = g \\<and> length u = length v\\<close> \\<open>unify (zip u v @ U) = Some \\<sigma>\\<close> \"4.prems\" by blast\n  have \"svran \\<sigma> \\<subseteq> fv_eq_system ((Fun f u, Fun g v) # U)\"\n    using \\<open>f = g \\<and> length u = length v\\<close> \\<open>svran \\<sigma> \\<subseteq> fv_eq_system (zip u v @ U)\\<close> fv_eq_fun_lists by fastforce\n  moreover have \"sdom \\<sigma> \\<subseteq> fv_eq_system ((Fun f u, Fun g v) # U)\"\n    using \\<open>f = g \\<and> length u = length v\\<close> \\<open>sdom \\<sigma> \\<subseteq> fv_eq_system (zip u v @ U)\\<close> fv_eq_fun_lists by fastforce\n  moreover have \"fv_eq_system (\\<sigma> \\<cdot> ((Fun f u, Fun g v) # U)) \\<subseteq> fv_eq_system ((Fun f u, Fun g v) # U)\"\n    by (metis \\<open>f = g \\<and> length u = length v\\<close> \\<open>fv_eq_system (\\<sigma> \\<cdot> (zip u v @ U)) \\<subseteq> fv_eq_system (zip u v @ U)\\<close> fv_eq_fun_lists fv_sapply_eq_system)\n  then show ?case using calculation(1) calculation(2) by blast\nqed\n\nlemma lemma_3_iv:\n  \"unify U = Some \\<sigma> \\<Longrightarrow> sdom \\<sigma> \\<inter> svran \\<sigma> = {}\"\nproof (induction arbitrary: \\<sigma> rule: unify.induct)\ncase 1\n  then show ?case\n    by (metis inf_bot_right option.inject svran_Var unify.simps(1))\nnext\n  case (2 x t U)\n  then show ?case\n  proof (cases \"x \\<in> fv t\")\n    case True\n    then show ?thesis\n      by (metis \"2.IH\"(2) \"2.prems\" option.discI unify.simps(2))\n  next\n\n  (* CASE UNIFY *)\n\n  case False\n    obtain \\<tau> where \"unify (Var(x := t) \\<cdot> U) = Some \\<tau>\"\n      by (metis (no_types, hide_lams) \"2.prems\" False lifted_comp.elims option.discI unify.simps(2))\n    have \"\\<sigma> = \\<tau> \\<circ>s (Var(x := t))\"\n      using \"2.prems\" False \\<open>unify (Var(x := t) \\<cdot> U) = Some \\<tau>\\<close> by auto\n    have \"sdom \\<tau> \\<inter> svran \\<tau> = {}\"\n      using \"2\"(1) False \\<open>unify (Var(x := t) \\<cdot> U) = Some \\<tau>\\<close> by blast\n    have \"svran \\<tau> \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U)\"\n      using \\<open>unify (Var(x := t) \\<cdot> U) = Some \\<tau>\\<close> lemma_3_i_iii by blast\n    have \"x \\<notin> svran \\<tau>\"\n      by (meson False \\<open>svran \\<tau> \\<subseteq> fv_eq_system (Var(x := t) \\<cdot> U)\\<close> prelim_unify_equations subsetCE)\n    have \"sdom \\<sigma> \\<inter> svran \\<sigma> = {}\"\n    proof (rule ccontr)\n      assume \"\\<not> (sdom \\<sigma> \\<inter> svran \\<sigma> = {})\"\n      show \"False\"\n      proof -\n        obtain z where \"z \\<in> sdom \\<sigma>\" and \"z \\<in> svran \\<sigma>\"\n          using \\<open>sdom \\<sigma> \\<inter> svran \\<sigma> \\<noteq> {}\\<close> by blast\n        have \"z \\<in> sdom \\<tau> \\<union> {x}\"\n          using \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> \\<open>z \\<in> sdom \\<sigma>\\<close> sdom_scomp by auto\n        have \"z \\<in> svran \\<tau> \\<union> fv t\"\n          by (metis False \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> \\<open>z \\<in> svran \\<sigma>\\<close> fv.simps(1) singletonI subsetCE svran_scomp svran_single_non_trivial)\n        have \"z \\<in> sdom \\<tau>\"\n          using False \\<open>x \\<notin> svran \\<tau>\\<close> \\<open>z \\<in> sdom \\<tau> \\<union> {x}\\<close> \\<open>z \\<in> svran \\<tau> \\<union> fv t\\<close> by blast\n        have \"\\<exists>y. y \\<in> sdom \\<sigma> \\<and> z \\<in> fv (\\<sigma> \\<cdot> (Var y))\"\n        proof -\n          have \"z \\<in> (\\<Union>t\\<in>(sran \\<sigma>).(fv t))\" using \\<open>z \\<in> svran \\<sigma>\\<close> by auto\n          then obtain t where \"t \\<in> sran \\<sigma>\" and \"z \\<in> fv t\" by blast\n          then obtain y where \"y \\<in> sdom \\<sigma>\" and \"t = \\<sigma> y\" by auto\n          then have \"z \\<in> fv (\\<sigma> \\<cdot> (Var y))\" using \\<open>z \\<in> fv t\\<close> by auto\n          then have \"y \\<in> sdom \\<sigma> \\<and> z \\<in> fv (\\<sigma> \\<cdot> (Var y))\" using \\<open>y \\<in> sdom \\<sigma>\\<close> by blast\n          show ?thesis using \\<open>y \\<in> sdom \\<sigma>\\<close> \\<open>z \\<in> fv (\\<sigma> \\<cdot> Var y)\\<close> by auto\n        qed\n        then obtain y where \"y \\<in> sdom \\<sigma>\" and \"z \\<in> fv (\\<sigma> \\<cdot> (Var y))\" by blast\n        then show ?thesis\n        proof (cases \"y = x\")\n          case True\n          have \"\\<sigma> \\<cdot> (Var y) = \\<tau> \\<cdot> t\"\n            by (simp add: True \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close>)\n          have \"z \\<in> fv (\\<tau> \\<cdot> t)\" using \\<open>\\<sigma> \\<cdot> Var y = \\<tau> \\<cdot> t\\<close> \\<open>z \\<in> fv (\\<sigma> \\<cdot> Var y)\\<close> by auto\n          then show ?thesis\n            by (meson Diff_disjoint UnE \\<open>sdom \\<tau> \\<inter> svran \\<tau> = {}\\<close> \\<open>z \\<in> sdom \\<tau>\\<close> disjoint_iff_not_equal fv_sapply_sdom_svran)\n        next\n          case False\n          have \"\\<sigma> \\<cdot> (Var y) = \\<tau> \\<cdot> (Var y)\" by (simp add: False \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close>)\n          have \"z \\<in> svran \\<tau>\"\n            by (metis (mono_tags, hide_lams) Diff_iff UnE \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> \\<open>z \\<in> fv (\\<sigma> \\<cdot> Var y)\\<close> \\<open>z \\<in> sdom \\<tau>\\<close> fv_sapply_sdom_svran sapply_scomp_distrib)\n          then show ?thesis using \\<open>sdom \\<tau> \\<inter> svran \\<tau> = {}\\<close> \\<open>z \\<in> sdom \\<tau>\\<close> by blast\n        qed\n      qed\n    qed\n    then show ?thesis by blast\n  qed\nnext\ncase (3 v va y U)\n  then show ?case\n    by simp\nnext\n  case (4 f u g v U)\n  then show ?case\n    by (metis option.discI unify.simps(4))\nqed\n\n\n\n\n\n(*\n--------------------------------------------------\nAssignment 4\n--------------------------------------------------\n*)\n\n(* 4. (a) *)\n\ninductive wf_term :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) term \\<Rightarrow> bool\" where\n  \"wf_term ar (Var x)\"\n| \"(length l = ar f) \\<and> (\\<forall>t\\<in>(set l). wf_term ar t) \\<Longrightarrow> wf_term ar (Fun f l)\"\n\ndefinition wf_subst :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) subst \\<Rightarrow> bool\" where\n  \"wf_subst ar \\<sigma> = (\\<forall>x. wf_term ar (\\<sigma> x))\"\n\ndefinition wf_eq :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) equation \\<Rightarrow> bool\" where\n  \"wf_eq ar eq \\<equiv> (wf_term ar (fst eq)) \\<and> (wf_term ar (snd eq))\"\n\ninductive wf_eqs :: \"('f \\<Rightarrow> nat) \\<Rightarrow> ('f, 'v) equations \\<Rightarrow> bool\" where\n  \"wf_eqs ar []\"\n| \"(wf_eqs ar U) \\<and> (wf_eq ar eq) \\<Longrightarrow> wf_eqs ar (eq # U)\"\n\n(* 4. (b) *)\n\nlemma wf_term_sapply[simp]:\n\"\\<lbrakk> wf_term arity t; wf_subst arity \\<sigma> \\<rbrakk> \\<Longrightarrow> wf_term arity (\\<sigma> \\<cdot> t)\"\nproof (induction t)\ncase (Var x)\n  then show ?case by (simp add: wf_subst_def)\nnext\n  case (Fun x1a x2)\n  have \"length x2 = arity x1a\" using Fun.prems(1) wf_term.simps by fastforce\n  moreover have \"\\<forall>t\\<in>(set x2). wf_term arity t\" using Fun.prems(1) wf_term.cases by auto\n  then show ?case by (simp add: Fun.IH Fun.prems(2) calculation wf_term.intros(2))\nqed\n\nlemma wf_subst_scomp[simp]:\n\"\\<lbrakk> wf_subst arity \\<sigma>; wf_subst arity \\<tau> \\<rbrakk> \\<Longrightarrow> wf_subst arity (\\<sigma> \\<circ>s \\<tau> )\"\n  by (simp add: wf_subst_def)\n\nlemma for_all_wf_eqs:\n  \"\\<forall>(x, y)\\<in>(set u). wf_eq ar (x, y) \\<Longrightarrow> wf_eqs ar u\"\nproof (induction u)\n  case Nil\n  then show ?case using wf_eqs.intros(1) by blast\nnext\n  case (Cons a u)\n  then show ?case\n    by (metis case_prodD list.set_intros(1) list.set_intros(2) prod.collapse wf_eqs.intros(2))\nqed\n\nlemma wf_fun_zip:\n  \"wf_eq ar (Fun f (map fst u), Fun g (map snd u)) \\<Longrightarrow> wf_eqs ar u\"\nproof (induction u)\n  case Nil\n  then show ?case by (simp add: wf_eqs.intros(1))\nnext\n  case (Cons a u)\n  obtain \"wf_term ar (Fun f (map fst (a # u)))\" and \"wf_term ar (Fun g (map snd (a # u)))\"\n    using Cons.prems wf_eq_def by fastforce\n  have \"(\\<forall>t\\<in>(set (map fst (a # u))). wf_term ar t)\"\n    by (metis \\<open>wf_term ar (Fun f (map fst (a # u)))\\<close> term.distinct(1) term.inject(2) wf_term.cases)\n  obtain \"wf_term ar (fst a)\" and \"\\<forall>x\\<in>(set (map fst u)). wf_term ar x\"\n    by (simp add: \\<open>(\\<forall>t\\<in>set (map fst (a # u)). wf_term ar t)\\<close>)\n  have \"(\\<forall>t\\<in>(set (map snd (a # u))). wf_term ar t)\"\n    by (metis \\<open>wf_term ar (Fun g (map snd (a # u)))\\<close> term.distinct(1) term.inject(2) wf_term.cases)\n  obtain \"wf_term ar (snd a)\" and \"\\<forall>x\\<in>(set (map snd u)). wf_term ar x\"\n    by (simp add: \\<open>(\\<forall>t\\<in>set (map snd (a # u)). wf_term ar t)\\<close>)\n  have \"\\<forall>(x, y)\\<in>(set u). wf_eq ar (x, y)\"\n    using \\<open>\\<forall>x\\<in>set (map fst u). wf_term ar x\\<close> \\<open>\\<forall>x\\<in>set (map snd u). wf_term ar x\\<close> wf_eq_def by fastforce\n  also have \"wf_eqs ar u\" using calculation for_all_wf_eqs by blast\n  have \"wf_eq ar a\"\n    by (simp add: \\<open>wf_term ar (fst a)\\<close> \\<open>wf_term ar (snd a)\\<close> wf_eq_def)\n  then show ?case by (simp add: \\<open>wf_eqs ar u\\<close> wf_eqs.intros(2))\nqed\n\nlemma wf_eqs_two_parts:\n  \"wf_eqs ar U \\<and> wf_eqs ar V \\<Longrightarrow> wf_eqs ar (U @ V)\"\nproof (induction U)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a U)\n  then show ?case\n    by (metis (no_types, lifting) append_Cons list.sel(3) self_append_conv2 wf_eqs.cases wf_eqs.intros(2))\nqed\n\nlemma wf_eqs_subst:\n  \"wf_subst ar \\<sigma> \\<and> wf_eqs ar U \\<Longrightarrow> wf_eqs ar (\\<sigma> \\<cdot> U)\"\nproof (induction U)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a U)\n  have \"wf_eqs ar (\\<sigma> \\<cdot> U)\" using Cons.IH Cons.prems wf_eqs.cases by fastforce\n  moreover have \"wf_eq ar (\\<sigma> \\<cdot> a)\" by (metis Cons.prems fst_conv list.discI list.sel(1) sapply_eq.simps snd_conv wf_eq_def wf_eqs.cases wf_term_sapply)\n  then show ?case using calculation wf_eqs.simps by fastforce\nqed\n\nlemma wf_subst_unify:\n  \"unify U = Some \\<sigma> \\<and> wf_eqs arity U \\<Longrightarrow> wf_subst arity \\<sigma>\"\nproof (induction U arbitrary: \\<sigma> rule: unify.induct)\n  case 1\nthen show ?case\n  by (metis option.inject unify.simps(1) wf_subst_def wf_term.intros(1))\nnext\n  case (2 x t U)\n  then show ?case\n  proof (cases \"x \\<in> fv t\")\n    case True\n    then show ?thesis\n      by (metis \"2.IH\"(2) \"2.prems\" list.discI list.sel(3) option.discI unify.simps(2) wf_eqs.cases)\n  next\n    case False\n    obtain \\<tau> where \"unify (Var(x := t) \\<cdot> U) = Some \\<tau>\"\n      by (metis (no_types, hide_lams) \"2.prems\" False lifted_comp.elims option.discI unify.simps(2))\n    have \"\\<sigma> = \\<tau> \\<circ>s (Var(x := t))\"\n      using \"2.prems\" False \\<open>unify (Var(x := t) \\<cdot> U) = Some \\<tau>\\<close> by auto\n    have \"wf_eq arity (Var x, t)\" using \"2.prems\" wf_eqs.cases by fastforce\n    moreover have \"wf_eqs arity U\" using \"2.prems\" wf_eqs.cases by fastforce\n    then have \"wf_subst arity (Var(x := t))\" using calculation wf_eq_def wf_subst_def wf_term.intros(1) by fastforce\n    then have \"wf_eqs arity (Var(x := t) \\<cdot> U)\" using \\<open>wf_eqs arity U\\<close> wf_eqs_subst by blast\n    then have \"wf_subst arity \\<tau>\" using \"2.IH\"(1) False \\<open>unify (Var(x := t) \\<cdot> U) = Some \\<tau>\\<close> by blast\n    then show ?thesis using \\<open>\\<sigma> = \\<tau> \\<circ>s Var(x := t)\\<close> \\<open>wf_subst arity (Var(x := t))\\<close> wf_subst_scomp by blast\n  qed\nnext\n  case (3 v va y U)\n  obtain \"wf_eqs arity U\" and \"wf_eq arity (Fun v va, Var y)\"\n    using \"3.prems\" wf_eqs.cases by fastforce\n  also have \"wf_eq arity (Var y, Fun v va)\" using calculation(2) prod.sel(2) wf_eq_def by fastforce\n  have \"wf_eqs arity ((Var y, Fun v va) # U)\"\n    by (simp add: \\<open>wf_eq arity (Var y, Fun v va)\\<close> calculation(1) wf_eqs.intros(2))\n  then show ?case using \"3.IH\" \"3.prems\"(1) by auto\nnext\n  case (4 f u g v U)\n  obtain \"f = g\" and \"length u = length v\" using \"4.prems\"(1) by fastforce\n  obtain \\<tau> where \"unify (zip u v @ U) = Some \\<tau>\"\n    using \"4.prems\"(1) \\<open>f = g\\<close> \\<open>length u = length v\\<close> by auto\n  have \"wf_eqs arity (zip u v)\"\n    by (metis (no_types, lifting) \"4.prems\" \\<open>length u = length v\\<close> list.discI list.sel(1) map_fst_zip map_snd_zip wf_eqs.cases wf_fun_zip)\n  also have \"wf_eqs arity U\" using \"4.prems\" wf_eqs.cases by fastforce\n  then show ?case using \"4.IH\" \"4.prems\"(1) \\<open>f = g\\<close> \\<open>length u = length v\\<close> calculation wf_eqs_two_parts by auto\nqed\n\nend", "meta": {"author": "tdardinier", "repo": "camr", "sha": "d8a4f774285bb185b1431b9c7e9325e5cc4eb1c4", "save_path": "github-repos/isabelle/tdardinier-camr", "path": "github-repos/isabelle/tdardinier-camr/camr-d8a4f774285bb185b1431b9c7e9325e5cc4eb1c4/Unify.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.8397339736884712, "lm_q1q2_score": 0.7562054534798791}}
{"text": "(*\n  File:     Furstenberg_Topology.thy\n  Author:   Manuel Eberl, TU München\n*)\nsection \\<open>Furstenberg's topology and his proof of the infinitude of primes\\<close>\ntheory Furstenberg_Topology\n  imports \n    \"HOL-Real_Asymp.Real_Asymp\" \n    \"HOL-Analysis.Analysis\" \n    \"HOL-Number_Theory.Number_Theory\"\nbegin\n\ntext \\<open>\n  This article gives a formal version of Furstenberg's topological proof of the infinitude of\n  primes~\\<^cite>\\<open>\"furstenberg\"\\<close>. He defines a topology on the integers based on arithmetic progressions\n  (or, equivalently, residue classes).\n\n  Apart from yielding a short proof of the infinitude of primes, this topology is also fairly\n  `nice' in general: it is second countable, metrizable, and perfect. All of these (well-known)\n  facts will be formally proven below.\n\\<close>\n\nsubsection \\<open>Arithmetic progressions of integers\\<close>\n\ntext \\<open>\n  We first define `bidirectional infinite arithmetic progressions' on \\<open>\\<int>\\<close> in the sense that \n  to an integer \\<open>a\\<close> and a positive integer \\<open>b\\<close>, we associate all the integers \\<open>x\\<close> such that\n  $x \\equiv a\\ (\\text{mod}\\ b)$, or, equivalently, $\\{a + nb\\mid n\\in\\mathbb{Z}\\}$.\n\\<close>\n\ndefinition arith_prog :: \"int \\<Rightarrow> nat \\<Rightarrow> int set\" where\n  \"arith_prog a b = {x. [x = a] (mod int b)}\"\n\nlemma arith_prog_0_right [simp]: \"arith_prog a 0 = {a}\"\n  by (simp add: arith_prog_def)\n\nlemma arith_prog_Suc_0_right [simp]: \"arith_prog a (Suc 0) = UNIV\"\n  by (auto simp: arith_prog_def)\n\nlemma in_arith_progI [intro]: \"[x = a] (mod b) \\<Longrightarrow> x \\<in> arith_prog a b\"\n  by (auto simp: arith_prog_def)\n\ntext \\<open>\n  Two arithmetic progressions with the same period and noncongruent starting points are\n  disjoint.\n\\<close>\nlemma arith_prog_disjoint:\n  assumes \"[a \\<noteq> a'] (mod int b)\" and \"b > 0\"\n  shows   \"arith_prog a b \\<inter> arith_prog a' b = {}\"\n  using assms by (auto simp: arith_prog_def cong_def)\n\ntext \\<open>\n  Multiplying the period gives us a subset of the original progression.\n\\<close>\nlemma arith_prog_dvd_mono: \"b dvd b' \\<Longrightarrow> arith_prog a b' \\<subseteq> arith_prog a b\"\n  by (auto simp: arith_prog_def cong_dvd_modulus)\n\ntext \\<open>\n  The following proves the alternative definition mentioned above.\n\\<close>\nlemma bij_betw_arith_prog:\n  assumes \"b > 0\"\n  shows   \"bij_betw (\\<lambda>n. a + int b * n) UNIV (arith_prog a b)\"\nproof (rule bij_betwI[of _ _ _ \"\\<lambda>x. (x - a) div int b\"], goal_cases)\n  case 1\n  thus ?case \n    by (auto simp: arith_prog_def cong_add_lcancel_0 cong_mult_self_right mult_of_nat_commute)\nnext\n  case 4\n  thus ?case\n    by (auto simp: arith_prog_def cong_iff_lin)\nqed (use \\<open>b > 0\\<close> in \\<open>auto simp: arith_prog_def\\<close>)\n\nlemma arith_prog_altdef: \"arith_prog a b = range (\\<lambda>n. a + int b * n)\"\nproof (cases \"b = 0\")\n  case False\n  thus ?thesis\n    using bij_betw_arith_prog[of b] by (auto simp: bij_betw_def)\nqed auto\n\ntext \\<open>\n  A simple corollary from this is also that any such arithmetic progression is infinite.\n\\<close>\nlemma infinite_arith_prog: \"b > 0 \\<Longrightarrow> infinite (arith_prog a b)\"\n  using bij_betw_finite[OF bij_betw_arith_prog[of b]] by simp\n\n\nsubsection \\<open>The Furstenberg topology on \\<open>\\<int>\\<close>\\<close>\n\ntext \\<open>\n  The typeclass-based topology is somewhat nicer to use in Isabelle/HOL, but the integers, \n  of course, already have a topology associated to them. We therefore need to introduce a type\n  copy of the integers and furnish them with the new topology. We can easily convert between\n  them and the `proper' integers using Lifting and Transfer.\n\\<close>\ntypedef fbint = \"UNIV :: int set\"\n  morphisms int_of_fbint fbint ..\n\nsetup_lifting type_definition_fbint\n\nlift_definition arith_prog_fb :: \"int \\<Rightarrow> nat \\<Rightarrow> fbint set\" is \"arith_prog\" .\n\ninstantiation fbint :: topological_space\nbegin\n\ntext \\<open>\n  Furstenberg defined the topology as the one generated by all arithmetic progressions.\n  We use a slightly more explicit equivalent formulation that exploits the fact that\n  the intersection of two arithmetic progressions is again an arithmetic progression (or empty).\n\\<close>\nlift_definition open_fbint :: \"fbint set \\<Rightarrow> bool\" is\n  \"\\<lambda>U. (\\<forall>x\\<in>U. \\<exists>b>0. arith_prog x b \\<subseteq> U)\" .\n\ntext \\<open>\n  We now prove that this indeed forms a topology.\n\\<close>\ninstance proof\n  show \"open (UNIV :: fbint set)\"\n    by transfer auto\nnext\n  fix U V :: \"fbint set\"\n  assume \"open U\" and \"open V\"\n  show \"open (U \\<inter> V)\"\n  proof (use \\<open>open U\\<close> \\<open>open V\\<close> in transfer, safe)\n    fix U V :: \"int set\" and x :: int\n    assume U: \"\\<forall>x\\<in>U. \\<exists>b>0. arith_prog x b \\<subseteq> U\" and V: \"\\<forall>x\\<in>V. \\<exists>b>0. arith_prog x b \\<subseteq> V\"\n    assume x: \"x \\<in> U\" \"x \\<in> V\"\n    from U x obtain b1 where b1: \"b1 > 0\" \"arith_prog x b1 \\<subseteq> U\" by auto\n    from V x obtain b2 where b2: \"b2 > 0\" \"arith_prog x b2 \\<subseteq> V\" by auto\n    from b1 b2 have \"lcm b1 b2 > 0\" \"arith_prog x (lcm b1 b2) \\<subseteq> U \\<inter> V\"\n      using arith_prog_dvd_mono[of b1 \"lcm b1 b2\" x] arith_prog_dvd_mono[of b2 \"lcm b1 b2\" x]\n      by (auto simp: lcm_pos_nat)\n    thus \"\\<exists>b>0. arith_prog x b \\<subseteq> U \\<inter> V\" by blast\n  qed\nnext\n  fix F :: \"fbint set set\"\n  assume *: \"\\<forall>U\\<in>F. open U\"\n  show \"open (\\<Union>F)\"\n  proof (use * in transfer, safe)\n    fix F :: \"int set set\" and U :: \"int set\" and x :: int\n    assume F: \"\\<forall>U\\<in>F. \\<forall>x\\<in>U. \\<exists>b>0. arith_prog x b \\<subseteq> U\"\n    assume \"x \\<in> U\" \"U \\<in> F\"\n    with F obtain b where b: \"b > 0\" \"arith_prog x b \\<subseteq> U\" by blast\n    with \\<open>U \\<in> F\\<close> show \"\\<exists>b>0. arith_prog x b \\<subseteq> \\<Union>F\"\n      by blast\n  qed\nqed\n\nend\n\ntext \\<open>\n  Since any non-empty open set contains an arithmetic progression and arithmetic progressions\n  are infinite, we obtain that all nonempty open sets are infinite.\n\\<close>\nlemma open_fbint_imp_infinite:\n  fixes U :: \"fbint set\"\n  assumes \"open U\" and \"U \\<noteq> {}\"\n  shows   \"infinite U\"\n  using assms\nproof transfer\n  fix U :: \"int set\"\n  assume *: \"\\<forall>x\\<in>U. \\<exists>b>0. arith_prog x b \\<subseteq> U\" and \"U \\<noteq> {}\"\n  from \\<open>U \\<noteq> {}\\<close> obtain x where \"x \\<in> U\" by auto\n  with * obtain b where b: \"b > 0\" \"arith_prog x b \\<subseteq> U\" by auto\n  from b have \"infinite (arith_prog x b)\"\n    using infinite_arith_prog by blast\n  with b show \"infinite U\"\n    using finite_subset by blast\nqed\n\nlemma not_open_finite_fbint [simp]:\n  assumes \"finite (U :: fbint set)\" \"U \\<noteq> {}\"\n  shows   \"\\<not>open U\"\n  using open_fbint_imp_infinite assms by blast\n\ntext \\<open>\n  More or less by definition, any arithmetic progression is open.\n\\<close>\nlemma open_arith_prog_fb [intro]:\n  assumes \"b > 0\"\n  shows   \"open (arith_prog_fb a b)\"\n  using assms\nproof transfer\n  fix a :: int and b :: nat\n  assume \"b > 0\"\n  show \"\\<forall>x\\<in>arith_prog a b. \\<exists>b'>0. arith_prog x b' \\<subseteq> arith_prog a b\"\n  proof (intro ballI exI[of _ b] conjI)\n    fix x assume \"x \\<in> arith_prog a b\"\n    thus \"arith_prog x b \\<subseteq> arith_prog a b\"\n      using cong_trans by (auto simp: arith_prog_def )\n  qed (use \\<open>b > 0\\<close> in auto)\nqed\n\ntext \\<open>\n  Slightly less obviously, any arithmetic progression is also closed.\n  This can be seen by realising that for a period \\<open>b\\<close>, we can partition the integers\n  into \\<open>b\\<close> congruence classes and then the complement of each congruence class is the \n  union of the other \\<open>b - 1\\<close> classes, and unions of open sets are open.\n\\<close>\nlemma closed_arith_prog_fb [intro]:\n  assumes \"b > 0\"\n  shows   \"closed (arith_prog_fb a b)\"\nproof -\n  have \"open (-arith_prog_fb a b)\"\n  proof -\n    have \"-arith_prog_fb a b = (\\<Union>i\\<in>{1..<b}. arith_prog_fb (a+i) b)\"\n    proof (transfer fixing: b)\n      fix a :: int\n      have disjoint: \"x \\<notin> arith_prog a b\" if \"x \\<in> arith_prog (a + int i) b\" \"i \\<in> {1..<b}\" for x i\n      proof -\n        have \"[a \\<noteq> a + int i] (mod int b)\"\n        proof\n          assume \"[a = a + int i] (mod int b)\"\n          hence \"[a + 0 = a + int i] (mod int b)\" by simp\n          hence \"[0 = int i] (mod int b)\" by (subst (asm) cong_add_lcancel) auto\n          with that show False by (auto simp: cong_def)\n        qed\n        thus ?thesis using arith_prog_disjoint[of a \"a + int i\" b] \\<open>b > 0\\<close> that by auto\n      qed\n\n      have covering: \"x \\<in> arith_prog a b \\<or> x \\<in> (\\<Union>i\\<in>{1..<b}. arith_prog (a + int i) b)\" for x\n      proof -\n        define i where \"i = nat ((x - a) mod (int b))\"\n        have \"[a + int i = a + (x - a) mod int b] (mod int b)\"\n          unfolding i_def using \\<open>b > 0\\<close> by simp\n        also have \"[a + (x - a) mod int b = a + (x - a)] (mod int b)\"\n          by (intro cong_add) auto\n        finally have \"[x = a + int i] (mod int b)\"\n          by (simp add: cong_sym_eq)\n        hence \"x \\<in> arith_prog (a + int i) b\"\n          using \\<open>b > 0\\<close> by (auto simp: arith_prog_def)\n        moreover have \"i < b\" using \\<open>b > 0\\<close> \n          by (auto simp: i_def nat_less_iff)\n        ultimately show ?thesis using \\<open>b > 0\\<close>\n          by (cases \"i = 0\") auto\n      qed\n\n      from disjoint and covering show \"- arith_prog a b = (\\<Union>i\\<in>{1..<b}. arith_prog (a + int i) b)\"\n        by blast\n    qed \n    also from \\<open>b > 0\\<close> have \"open \\<dots>\"\n      by auto\n    finally show ?thesis .\n  qed\n  thus ?thesis by (simp add: closed_def)\nqed\n\nsubsection \\<open>The infinitude of primes\\<close>\n\ntext \\<open>\n  The infinite of the primes now follows quite obviously: The multiples of any prime form a\n  closed set, so if there were only finitely many primes, the union of all of these would also\n  be open. However, since any number other than \\<open>\\<plusminus>1\\<close> has a prime divisor, the union of all these\n  sets is simply \\<open>\\<int>\\<setminus>{\\<plusminus>1}\\<close>, which is obviously \\<^emph>\\<open>not\\<close> closed since the finite set \\<open>{\\<plusminus>1}\\<close> is not\n  open.\n\\<close>\ntheorem \"infinite {p::nat. prime p}\"\nproof  \n  assume fin: \"finite {p::nat. prime p}\"\n  define A where \"A = (\\<Union>p\\<in>{p::nat. prime p}. arith_prog_fb 0 p)\"\n  have \"closed A\"\n    unfolding A_def using fin by (intro closed_Union) (auto simp: prime_gt_0_nat)\n  hence \"open (-A)\"\n    by (simp add: closed_def)\n  also have \"A = -{fbint 1, fbint (-1)}\"\n    unfolding A_def\n  proof transfer\n    show \"(\\<Union>p\\<in>{p::nat. prime p}. arith_prog 0 p) = - {1, - 1}\"\n    proof (intro equalityI subsetI)\n      fix x :: int assume x: \"x \\<in> -{1, -1}\"\n      hence \"\\<bar>x\\<bar> \\<noteq> 1\" by auto\n      show \"x \\<in> (\\<Union>p\\<in>{p::nat. prime p}. arith_prog 0 p)\"\n      proof (cases \"x = 0\")\n        case True\n        thus ?thesis\n          by (auto simp: A_def intro!: exI[of _ 2])\n      next\n        case [simp]: False\n        obtain p where p: \"prime p\" \"p dvd x\"\n          using prime_divisor_exists[of x] and \\<open>\\<bar>x\\<bar> \\<noteq> 1\\<close> by auto\n        hence \"x \\<in> arith_prog 0 (nat p)\" using prime_gt_0_int[of p]\n          by (auto simp: arith_prog_def cong_0_iff)\n        thus ?thesis using p\n          by (auto simp: A_def intro!: exI[of _ \"nat p\"])\n      qed\n    qed (auto simp: A_def arith_prog_def cong_0_iff)\n  qed\n  also have \"-(-{fbint 1, fbint (-1)}) = {fbint 1, fbint (-1)}\"\n    by simp\n  finally have \"open {fbint 1, fbint (-1)}\" .\n  thus False by simp\nqed\n\n\n\n\nsubsection \\<open>Additional topological properties\\<close>\n\ntext \\<open>\n  Just for fun, let us also show a few more properties of Furstenberg's topology.\n  First, we show the equivalence to the above to Furstenberg's original definition\n  (the topology generated by all arithmetic progressions).\n\\<close>\n\n\n\n\ntext \\<open>\n  From this, we can immediately see that it is second countable:\n\\<close>\ninstance fbint :: second_countable_topology\nproof\n  have \"countable ((\\<lambda>(a,b). arith_prog_fb a b) ` (UNIV \\<times> {b. b > 0}))\"\n    by (intro countable_image) auto\n  also have \"\\<dots> = {arith_prog_fb a b |a b. b > 0}\"\n    by auto\n  ultimately show \"\\<exists>B::fbint set set. countable B \\<and> open = generate_topology B\"\n    unfolding open_fbint_altdef by auto\nqed\n\ntext \\<open>\n  A trivial consequence of the fact that nonempty open sets in this topology are infinite\n  is that it is a perfect space:\n\\<close>\ninstance fbint :: perfect_space\n  by standard auto\n\n\ntext \\<open>\n  It is also Hausdorff, since given any two distinct integers, we can easily\n  construct two non-overlapping arithmetic progressions that each contain one of them.\n  We do not \\<^emph>\\<open>really\\<close> have to prove this since we will get it for free later on when we\n  show that it is a metric space, but here is the proof anyway:\n\\<close>\ninstance fbint :: t2_space\nproof\n  fix x y :: fbint\n  assume \"x \\<noteq> y\"\n  define d where \"d = nat \\<bar>int_of_fbint x - int_of_fbint y\\<bar> + 1\"\n  from \\<open>x \\<noteq> y\\<close> have \"d > 0\"\n    unfolding d_def by transfer auto\n  define U where \"U = arith_prog_fb (int_of_fbint x) d\"\n  define V where \"V = arith_prog_fb (int_of_fbint y) d\"\n\n  have \"U \\<inter> V = {}\" unfolding U_def V_def d_def\n  proof (use \\<open>x \\<noteq> y\\<close> in transfer, rule arith_prog_disjoint)\n    fix x y :: int\n    assume \"x \\<noteq> y\"\n    show \"[x \\<noteq> y] (mod int (nat \\<bar>x - y\\<bar> + 1))\"\n    proof\n      assume \"[x = y] (mod int (nat \\<bar>x - y\\<bar> + 1))\"\n      hence \"\\<bar>x - y\\<bar> + 1 dvd \\<bar>x - y\\<bar>\"\n        by (auto simp: cong_iff_dvd_diff algebra_simps)\n      hence \"\\<bar>x - y\\<bar> + 1 \\<le> \\<bar>x - y\\<bar>\"\n        by (rule zdvd_imp_le) (use \\<open>x \\<noteq> y\\<close> in auto)\n      thus False by simp\n    qed\n  qed auto\n  moreover have \"x \\<in> U\" \"y \\<in> V\"\n    unfolding U_def V_def by (use \\<open>d > 0\\<close> in transfer, fastforce)+\n  moreover have \"open U\" \"open V\"\n    using \\<open>d > 0\\<close> by (auto simp: U_def V_def)\n  ultimately show \"\\<exists>U V. open U \\<and> open V \\<and> x \\<in> U \\<and> y \\<in> V \\<and> U \\<inter> V = {}\" by blast\nqed\n\n(* TODO Move? *)\ntext \\<open>\n  Next, we need a small lemma: Given an additional assumption, a $T_2$ space is also $T_3$:\n\\<close>\nlemma t2_space_t3_spaceI:\n  assumes \"\\<And>(x :: 'a :: t2_space) U. x \\<in> U \\<Longrightarrow> open U \\<Longrightarrow>\n             \\<exists>V. x \\<in> V \\<and> open V \\<and> closure V \\<subseteq> U\"\n  shows   \"OFCLASS('a, t3_space_class)\"\nproof\n  fix X :: \"'a set\" and z :: 'a\n  assume X: \"closed X\" \"z \\<notin> X\"\n  with assms[of z \"-X\"] obtain V where V: \"z \\<in> V\" \"open V\" \"closure V \\<subseteq> -X\"\n    by auto\n  show \"\\<exists>U V. open U \\<and> open V \\<and> z \\<in> U \\<and> X \\<subseteq> V \\<and> U \\<inter> V = {}\"\n    by (rule exI[of _ V], rule exI[of _ \"-closure V\"])\n       (use X V closure_subset[of V] in auto)\nqed  \n\ntext \\<open>\n  Since the Furstenberg topology is $T_2$ and every arithmetic progression is also closed,\n  we can now easily show that it is also $T_3$ (i.\\,e.\\ regular). \n  Again, we do not really need this proof, but here it is:\n\\<close>\ninstance fbint :: t3_space\nproof (rule t2_space_t3_spaceI)\n  fix x :: fbint and U :: \"fbint set\"\n  assume \"x \\<in> U\" and \"open U\"\n  then obtain b where b: \"b > 0\" \"arith_prog_fb (int_of_fbint x) b \\<subseteq> U\"\n    by transfer blast\n  define V where \"V = arith_prog_fb (int_of_fbint x) b\"\n  have \"x \\<in> V\"\n    unfolding V_def by transfer auto\n  moreover have \"open V\" \"closed V\"\n    using \\<open>b > 0\\<close> by (auto simp: V_def)\n  ultimately show \"\\<exists>V. x \\<in> V \\<and> open V \\<and> closure V \\<subseteq> U\"\n    using b by (intro exI[of _ V]) (auto simp: V_def)\nqed\n\n\nsubsection \\<open>Metrizability\\<close>\n\ntext \\<open>\n  The metrizability of Furstenberg's topology (i.\\,e.\\ that it is induced by some metric) can\n  be shown from the fact that it is second countable and $T_3$ using Urysohn's Metrization Theorem, \n  but this is not available in Isabelle yet. Let us therefore give an \\<^emph>\\<open>explicit\\<close> metric, \n  as described by Zulfeqarr~\\<^cite>\\<open>\"zulfeqarr\"\\<close>. We follow the exposition by Dirmeier~\\<^cite>\\<open>\"dirmeier\"\\<close>.\n\n  First, we define a kind of norm on the integers. The norm depends on a real parameter \\<open>q > 1\\<close>.\n  The value of \\<open>q\\<close> does not matter in the sense that all values induce the same topology\n  (which we will show). For the final definition, we then simply pick \\<open>q = 2\\<close>.\n\\<close>\n\nlocale fbnorm =\n  fixes q :: \"real\"\n  assumes q_gt_1: \"q > 1\"\nbegin\n\ndefinition N :: \"int \\<Rightarrow> real\" where\n  \"N n = (\\<Sum>k. if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k)\"\n\nlemma N_summable: \"summable (\\<lambda>k. if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k)\"\n  by (rule summable_comparison_test[OF _ summable_geometric[of \"1/q\"]])\n     (use q_gt_1 in \\<open>auto intro!: exI[of _ 0] simp: power_divide\\<close>)\n\nlemma N_sums: \"(\\<lambda>k. if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k) sums N n\"\n  using N_summable unfolding N_def by (rule summable_sums)\n\nlemma N_nonneg: \"N n \\<ge> 0\"\n  by (rule sums_le[OF _ sums_zero N_sums]) (use q_gt_1 in auto)\n\nlemma N_uminus [simp]: \"N (-n) = N n\"\n  by (simp add: N_def)\n\nlemma N_minus_commute: \"N (x - y) = N (y - x)\"\n  using N_uminus[of \"x - y\"] by (simp del: N_uminus)\n\nlemma N_zero [simp]: \"N 0 = 0\"\n  by (simp add: N_def)\n\nlemma not_dvd_imp_N_ge:\n  assumes \"\\<not>n dvd a\" \"n > 0\"\n  shows   \"N a \\<ge> 1 / q ^ n\"\n  by (rule sums_le[OF _ sums_single[of n] N_sums]) (use q_gt_1 assms in auto)\n\nlemma N_lt_imp_dvd:\n  assumes \"N a < 1 / q ^ n\" and \"n > 0\"\n  shows   \"n dvd a\"\n  using not_dvd_imp_N_ge[of n a] assms by auto\n\nlemma N_pos:\n  assumes \"n \\<noteq> 0\"\n  shows   \"N n > 0\"\nproof -\n  have \"0 < 1 / q ^ (nat \\<bar>n\\<bar>+1)\"\n    using q_gt_1 by simp\n  also have \"\\<not>1 + \\<bar>n\\<bar> dvd \\<bar>n\\<bar>\"\n    using zdvd_imp_le[of \"1 + \\<bar>n\\<bar>\" \"\\<bar>n\\<bar>\"] assms by auto\n  hence \"1 / q ^ (nat \\<bar>n\\<bar>+1) \\<le> N n\"\n    by (intro not_dvd_imp_N_ge) (use assms in auto)\n  finally show ?thesis .\nqed\n\nlemma N_zero_iff [simp]: \"N n = 0 \\<longleftrightarrow> n = 0\"\n  using N_pos[of n] by (cases \"n = 0\") auto\n\nlemma N_triangle_ineq: \"N (n + m) \\<le> N n + N m\"\nproof (rule sums_le)\n  let ?I = \"\\<lambda>n k. if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k\"\n  show \"?I (n + m) sums N (n + m)\"\n    by (rule N_sums)\n  show \"(\\<lambda>k. ?I n k + ?I m k) sums (N n + N m)\"\n    by (intro sums_add N_sums)\nqed (use q_gt_1 in auto)\n\nlemma N_1: \"N 1 = 1 / (q * (q - 1))\"\nproof (rule sums_unique2)\n  have \"(\\<lambda>k. if k = 0 \\<or> int k dvd 1 then 0 else 1 / q ^ k) sums N 1\"\n    by (rule N_sums)\n  also have \"(\\<lambda>k. if k = 0 \\<or> int k dvd 1 then 0 else 1 / q ^ k) =\n               (\\<lambda>k. if k \\<in> {0, 1} then 0 else (1 / q) ^ k)\"\n    by (simp add: power_divide cong: if_cong)\n  finally show \"(\\<lambda>k. if k \\<in> {0, 1} then 0 else (1 / q) ^ k) sums N 1\" .\n\n  have \"(\\<lambda>k. if k \\<in> {0, 1} then 0 else (1 / q) ^ k) sums\n                 (1 / (1 - 1 / q) + (- (1 / q) - 1))\"\n    by (rule sums_If_finite_set'[OF geometric_sums]) (use q_gt_1 in auto)\n  also have \"\\<dots> = 1 / (q * (q - 1))\"\n    using q_gt_1 by (simp add: field_simps)\n  finally show \"(\\<lambda>k. if k \\<in> {0, 1} then 0 else (1 / q) ^ k) sums \\<dots>\" .\nqed\n\ntext \\<open>\n  It follows directly from the definition that norms fulfil a kind of monotonicity property\n  with respect to divisibility: the norm of a number is at most as large as the norm of any of\n  its factors:\n\\<close>\nlemma N_dvd_mono:\n  assumes \"m dvd n\"\n  shows   \"N n \\<le> N m\"\nproof (rule sums_le[OF _ N_sums N_sums])\n  fix k :: nat\n  show \"(if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k) \\<le>\n        (if k = 0 \\<or> int k dvd m then 0 else 1 / q ^ k)\"\n    using q_gt_1 assms by auto\nqed\n\ntext \\<open>\n  In particular, this means that 1 and -1 have the greatest norm.\n\\<close>\nlemma N_le_N_1: \"N n \\<le> N 1\"\n  by (rule N_dvd_mono) auto\n\ntext \\<open>\n  Primes have relatively large norms, almost reaching the norm of 1:\n\\<close>\nlemma N_prime:\n  assumes \"prime p\"\n  shows   \"N p = N 1 - 1 / q ^ nat p\"\nproof (rule sums_unique2)\n  define p' where \"p' = nat p\"\n  have p: \"p = int p'\"\n    using assms by (auto simp: p'_def prime_ge_0_int)\n  have \"prime p'\"\n    using assms by (simp add: p)\n\n  have \"(\\<lambda>k. if k = 0 \\<or> int k dvd p then 0 else 1 / q ^ k) sums N p\"\n    by (rule N_sums)\n  also have \"int k dvd p \\<longleftrightarrow> k \\<in> {1, p'}\" for k\n    using assms by (auto simp: p prime_nat_iff)\n  hence \"(\\<lambda>k. if k = 0 \\<or> int k dvd p then 0 else 1 / q ^ k) =\n         (\\<lambda>k. if k \\<in> {0, 1, p'} then 0 else (1 / q) ^ k)\"\n    using assms q_gt_1 by (simp add: power_divide cong: if_cong)\n  finally show \"\\<dots> sums N p\" .\n\n  have \"(\\<lambda>k. if k \\<in> {0, 1, p'} then 0 else (1 / q) ^ k) sums\n                 (1 / (1 - 1 / q) + (- (1 / q) - (1 / q) ^ p' - 1))\"\n    by (rule sums_If_finite_set'[OF geometric_sums])\n       (use \\<open>prime p'\\<close> q_gt_1 prime_gt_Suc_0_nat[of p'] in \\<open>auto simp: \\<close>)\n  also have \"\\<dots> = N 1 - 1 / q ^ p'\"\n    using q_gt_1 by (simp add: field_simps N_1)\n  finally show \"(\\<lambda>k. if k \\<in> {0, 1, p'} then 0 else (1 / q) ^ k) sums \\<dots>\" .\nqed\n\nlemma N_2: \"N 2 = 1 / (q ^ 2 * (q - 1))\"\n  using q_gt_1 by (auto simp: N_prime N_1 field_simps power2_eq_square)\n\nlemma N_less_N_1:\n  assumes \"n \\<noteq> 1\" \"n \\<noteq> -1\"\n  shows   \"N n < N 1\"\nproof (cases \"n = 0\")\n  case False\n  then obtain p where p: \"prime p\" \"p dvd n\"\n    using prime_divisor_exists[of n] assms by force\n  hence \"N n \\<le> N p\" by (intro N_dvd_mono)\n  also from p have \"N p < N 1\"\n    using q_gt_1 by (simp add: N_prime)\n  finally show ?thesis .\nqed (use q_gt_1 in \\<open>auto simp: N_1\\<close>)\n\ntext \\<open>\n  Composites, on the other hand, do not achieve this:\n\\<close>\nlemma nonprime_imp_N_lt:\n  assumes \"\\<not>prime_elem n\" \"\\<bar>n\\<bar> \\<noteq> 1\" \"n \\<noteq> 0\"\n  shows   \"N n < N 1 - 1 / q ^ nat \\<bar>n\\<bar>\"\nproof -\n  obtain p where p: \"prime p\" \"p dvd n\"\n    using prime_divisor_exists[of n] assms by auto\n  define p' where \"p' = nat p\"\n  have p': \"p = int p'\"\n    using p by (auto simp: p'_def prime_ge_0_int)\n  have \"prime p'\"\n    using p by (simp add: p')\n\n  define n' where \"n' = nat \\<bar>n\\<bar>\"\n  have \"n' > 1\"\n    using assms by (auto simp: n'_def)\n\n  have \"N n \\<le> 1 / (q * (q - 1)) - 1 / q ^ p' - 1 / q ^ n'\"\n  proof (rule sums_le)\n    show \"(\\<lambda>k. if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k) sums N n\"\n      by (rule N_sums)\n  next\n    from assms p have \"n' \\<noteq> p'\"\n      by (auto simp: n'_def p'_def nat_eq_iff)\n    hence \"(\\<lambda>k. if k \\<in> {0, 1, p', n'} then 0 else (1 / q) ^ k) sums\n                   (1 / (1 - 1 / q) + (- (1 / q) - (1 / q) ^ p' - (1 / q) ^ n' - 1))\"\n      by (intro sums_If_finite_set'[OF geometric_sums])\n         (use \\<open>prime p'\\<close> q_gt_1 prime_gt_Suc_0_nat[of p'] \\<open>n' > 1\\<close> in \\<open>auto simp: \\<close>)\n    also have \"\\<dots> = 1 / (q * (q - 1)) - 1 / q ^ p' - 1 / q ^ n'\"\n      using q_gt_1 by (simp add: field_simps)\n    finally show \"(\\<lambda>k. if k \\<in> {0, 1, p', n'} then 0 else (1 / q) ^ k) sums \\<dots>\" .\n  next\n    show \"\\<And>k. (if k = 0 \\<or> int k dvd n then 0 else 1 / q ^ k)\n         \\<le> (if k \\<in> {0, 1, p', n'} then 0 else (1 / q) ^ k)\"\n      using q_gt_1 p by (auto simp: p'_def n'_def power_divide)\n  qed\n  also have \"\\<dots> < 1 / (q * (q - 1)) - 1 / q ^ n'\"\n    using q_gt_1 by simp\n  finally show ?thesis by (simp add: n'_def N_1)\nqed\n\ntext \\<open>\n  This implies that one can use the norm as a primality test:\n\\<close>\nlemma prime_iff_N_eq:\n  assumes \"n \\<noteq> 0\"\n  shows   \"prime_elem n \\<longleftrightarrow> N n = N 1 - 1 / q ^ nat \\<bar>n\\<bar>\"\nproof -\n  have *: \"prime_elem n \\<longleftrightarrow> N n = N 1 - 1 / q ^ nat \\<bar>n\\<bar>\" if \"n > 0\" for n\n  proof -\n    consider \"n = 1\" | \"prime n\" | \"\\<not>prime n\" \"n > 1\"\n      using \\<open>n > 0\\<close> by force\n    thus ?thesis\n    proof cases\n      assume \"n = 1\"\n      thus ?thesis using q_gt_1\n        by (auto simp: N_1)\n    next\n      assume n: \"\\<not>prime n\" \"n > 1\"\n      with nonprime_imp_N_lt[of n] show ?thesis by simp\n    qed (auto simp: N_prime prime_ge_0_int)\n  qed\n\n  show ?thesis\n  proof (cases \"n > 0\")\n    case True\n    with * show ?thesis by blast\n  next\n    case False\n    with *[of \"-n\"] assms show ?thesis by simp\n  qed\nqed\n\ntext \\<open>\n  Factorials, on the other hand, have very small norms:\n\\<close>\nlemma N_fact_le: \"N (fact m) \\<le> 1 / (q - 1) * 1 / q ^ m\"\nproof (rule sums_le[OF _ N_sums])\n  have \"(\\<lambda>k. 1 / q ^ k / q ^ Suc m) sums (q / (q - 1) / q ^ Suc m)\"\n    using geometric_sums[of \"1 / q\"] q_gt_1 \n    by (intro sums_divide) (auto simp: field_simps)\n  also have \"(q / (q - 1) / q ^ Suc m) = 1 / (q - 1) * 1 / q ^ m\"\n    using q_gt_1 by (simp add: field_simps)\n  also have \"(\\<lambda>k. 1 / q ^ k / q ^ Suc m) = (\\<lambda>k. 1 / q ^ (k + Suc m))\"\n    using q_gt_1 by (simp add: field_simps power_add)\n  also have \"\\<dots> = (\\<lambda>k. if k + Suc m \\<le> m then 0 else 1 / q ^ (k + Suc m))\"\n    by auto\n  finally have \"\\<dots> sums (1 / (q - 1) * 1 / q ^ m)\" .\n  also have \"?this \\<longleftrightarrow> (\\<lambda>k. if k \\<le> m then 0 else 1 / q ^ k) sums (1 / (q - 1) * 1 / q ^ m)\"\n    by (rule sums_zero_iff_shift) auto\n  finally show \\<dots> .\nnext\n  fix k :: nat\n  have \"int k dvd fact m\" if \"k > 0\" \"k \\<le> m\"\n  proof -\n    have \"int k dvd int (fact m)\"\n      unfolding int_dvd_int_iff using that by (simp add: dvd_fact)\n    thus \"int k dvd fact m\"\n      unfolding of_nat_fact by simp\n  qed  \n  thus \"(if k = 0 \\<or> int k dvd fact m then 0 else 1 / q ^ k) \\<le>\n        (if k \\<le> m then 0 else 1 / q ^ k)\" using q_gt_1 by auto\nqed\n\nlemma N_prime_mono:\n  assumes \"prime p\" \"prime p'\" \"p \\<le> p'\"\n  shows   \"N p \\<le> N p'\"\n  using assms q_gt_1 by (auto simp add: N_prime field_simps nat_le_iff prime_ge_0_int)\n\nlemma N_prime_ge:\n  assumes \"prime p\"\n  shows   \"N p \\<ge> 1 / (q\\<^sup>2 * (q - 1))\"\nproof -\n  have \"1 / (q ^ 2 * (q - 1)) = N 2\"\n    using q_gt_1 by (auto simp: N_prime N_1 field_simps power2_eq_square)\n  also have \"\\<dots> \\<le> N p\"\n    using assms by (intro N_prime_mono) (auto simp: prime_ge_2_int)\n  finally show ?thesis .\nqed\n\nlemma N_prime_elem_ge:\n  assumes \"prime_elem p\"\n  shows   \"N p \\<ge> 1 / (q\\<^sup>2 * (q - 1))\"\nproof (cases \"p \\<ge> 0\")\n  case True\n  with assms N_prime_ge show ?thesis by auto\nnext\n  case False\n  with assms N_prime_ge[of \"-p\"] show ?thesis by auto\nqed\n\n\ntext \\<open>\n  Next, we use this norm to derive a metric:\n\\<close>\n\nlift_definition dist :: \"fbint \\<Rightarrow> fbint \\<Rightarrow> real\" is\n  \"\\<lambda>x y. N (x - y)\" .\n\nlemma dist_self [simp]: \"dist x x = 0\"\n  by transfer simp\n\nlemma dist_sym [simp]: \"dist x y = dist y x\"\n  by transfer (simp add: N_minus_commute)\n\nlemma dist_pos: \"x \\<noteq> y \\<Longrightarrow> dist x y > 0\"\n  by transfer (use N_pos in simp)\n\nlemma dist_eq_0_iff [simp]: \"dist x y = 0 \\<longleftrightarrow> x = y\"\n  using dist_pos[of x y] by (cases \"x = y\") auto\n\nlemma dist_triangle_ineq: \"dist x z \\<le> dist x y + dist y z\"\nproof transfer\n  fix x y z :: int\n  show \"N (x - z) \\<le> N (x - y) + N (y - z)\"\n    using N_triangle_ineq[of \"x - y\" \"y - z\"] by simp\nqed\n\n\ntext \\<open>\n  Lastly, we show that the metric we defined indeed induces the Furstenberg topology.\n\\<close>\ntheorem dist_induces_open:\n  \"open U \\<longleftrightarrow> (\\<forall>x\\<in>U. \\<exists>e>0. \\<forall>y. dist x y < e \\<longrightarrow> y \\<in> U)\"\nproof (transfer, safe)\n  fix U :: \"int set\" and x :: int\n  assume *: \"\\<forall>x\\<in>U. \\<exists>b>0. arith_prog x b \\<subseteq> U\"\n  assume \"x \\<in> U\"\n  with * obtain b where b: \"b > 0\" \"arith_prog x b \\<subseteq> U\" by blast\n  define e where \"e = 1 / q ^ b\"\n\n  show \"\\<exists>e>0. \\<forall>y. N (x - y) < e \\<longrightarrow> y \\<in> U\"\n  proof (rule exI; safe?)\n    show \"e > 0\" using q_gt_1 by (simp add: e_def)\n  next\n    fix y assume \"N (x - y) < e\"\n    also have \"\\<dots> = 1 / q ^ b\" by fact\n    finally have \"b dvd (x - y)\"\n      by (rule N_lt_imp_dvd) fact\n    hence \"y \\<in> arith_prog x b\"\n      by (auto simp: arith_prog_def cong_iff_dvd_diff dvd_diff_commute)\n    with b show \"y \\<in> U\" by blast\n  qed\n\nnext\n\n  fix U :: \"int set\" and x :: int\n  assume *: \"\\<forall>x\\<in>U. \\<exists>e>0. \\<forall>y. N (x - y) < e \\<longrightarrow> y \\<in> U\"\n  assume \"x \\<in> U\"\n  with * obtain e where e: \"e > 0\" \"\\<forall>y. N (x - y) < e \\<longrightarrow> y \\<in> U\" by blast\n  have \"eventually (\\<lambda>N. 1 / (q - 1) * 1 / q ^ N < e) at_top\"\n    using q_gt_1 \\<open>e > 0\\<close> by real_asymp\n  then obtain m where m: \"1 / (q - 1) * 1 / q ^ m < e\"\n    by (auto simp: eventually_at_top_linorder)\n  define b :: nat where \"b = fact m\"\n\n  have \"arith_prog x b \\<subseteq> U\"\n  proof\n    fix y assume \"y \\<in> arith_prog x b\"\n    show \"y \\<in> U\"\n    proof (cases \"y = x\")\n      case False\n      from \\<open>y \\<in> arith_prog x b\\<close> obtain n where y: \"y = x + int b * n\"\n        by (auto simp: arith_prog_altdef)\n      from y and \\<open>y \\<noteq> x\\<close> have [simp]: \"n \\<noteq> 0\" by auto\n      have \"N (x - y) = N (int b * n)\" by (simp add: y)\n      also have \"\\<dots> \\<le> N (int b)\"\n        by (rule N_dvd_mono) auto\n      also have \"\\<dots> \\<le> 1 / (q - 1) * 1 / q ^ m\"\n        using N_fact_le by (simp add: b_def)\n      also have \"\\<dots> < e\" by fact\n      finally show \"y \\<in> U\" using e by auto\n    qed (use \\<open>x \\<in> U\\<close> in auto)\n  qed\n  moreover have \"b > 0\" by (auto simp: b_def)\n  ultimately show \"\\<exists>b>0. arith_prog x b \\<subseteq> U\"\n    by blast\nqed\n  \nend\n\n\ntext \\<open>\n  We now show that the Furstenberg space is a metric space with this metric (with \\<open>q = 2\\<close>),\n  which essentially only amounts to plugging together all the results from above.\n\\<close>\n\ninterpretation fb: fbnorm 2\n  by standard auto\n\n\ninstantiation fbint :: dist\nbegin\n\ndefinition dist_fbint where \"dist_fbint = fb.dist\"\n\ninstance ..\n\nend\n\n\ninstantiation fbint :: uniformity_dist\nbegin\n\ndefinition uniformity_fbint :: \"(fbint \\<times> fbint) filter\" where\n  \"uniformity_fbint = (INF e\\<in>{0 <..}. principal {(x, y). dist x y < e})\"\n\ninstance by standard (simp add: uniformity_fbint_def)\n\nend\n\n\ninstance fbint :: open_uniformity\nproof\n  fix U :: \"fbint set\"\n  show \"open U = (\\<forall>x\\<in>U. eventually (\\<lambda>(x',y). x' = x \\<longrightarrow> y \\<in> U) uniformity)\"\n    unfolding eventually_uniformity_metric dist_fbint_def\n    using fb.dist_induces_open by simp\nqed\n\n\ninstance fbint :: metric_space\n  by standard (use fb.dist_triangle_ineq in \\<open>auto simp: dist_fbint_def\\<close>)\n\ntext \\<open>\n  In particular, we can now show that the sequence \\<open>n!\\<close> tends to 0 in the Furstenberg topology:\n\\<close>\nlemma tendsto_fbint_fact: \"(\\<lambda>n. fbint (fact n)) \\<longlonglongrightarrow> fbint 0\"\nproof -\n  have \"(\\<lambda>n. dist (fbint (fact n)) (fbint 0)) \\<longlonglongrightarrow> 0\"\n  proof (rule tendsto_sandwich[OF always_eventually always_eventually]; safe?)\n    fix n :: nat\n    show \"dist (fbint (fact n)) (fbint 0) \\<le> 1 / 2 ^ n\"\n      unfolding dist_fbint_def by (transfer fixing: n) (use fb.N_fact_le[of n] in simp)\n    show \"dist (fbint (fact n)) (fbint 0) \\<ge> 0\"\n      by simp\n    show \"(\\<lambda>n. 1 / 2 ^ n :: real) \\<longlonglongrightarrow> 0\"\n      by real_asymp\n  qed simp_all\n  thus ?thesis\n    using tendsto_dist_iff by metis\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Furstenberg_Topology/Furstenberg_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.8757869819218865, "lm_q1q2_score": 0.7561471446294633}}
{"text": "(*  Title:      HOL/Lattice/Orders.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Orders\\<close>\n\ntheory Orders imports Main begin\n\nsubsection \\<open>Ordered structures\\<close>\n\ntext \\<open>\n  We define several classes of ordered structures over some type @{typ\n  'a} with relation \\<open>\\<sqsubseteq> :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>.  For a\n  \\emph{quasi-order} that relation is required to be reflexive and\n  transitive, for a \\emph{partial order} it also has to be\n  anti-symmetric, while for a \\emph{linear order} all elements are\n  required to be related (in either direction).\n\\<close>\n\nclass leq =\n  fixes leq :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infixl \"\\<sqsubseteq>\" 50)\n\nclass quasi_order = leq +\n  assumes leq_refl [intro?]: \"x \\<sqsubseteq> x\"\n  assumes leq_trans [trans]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n\nclass partial_order = quasi_order +\n  assumes leq_antisym [trans]: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\n\nclass linear_order = partial_order +\n  assumes leq_linear: \"x \\<sqsubseteq> y \\<or> y \\<sqsubseteq> x\"\n\nlemma linear_order_cases:\n    \"((x::'a::linear_order) \\<sqsubseteq> y \\<Longrightarrow> C) \\<Longrightarrow> (y \\<sqsubseteq> x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (insert leq_linear) blast\n\n\nsubsection \\<open>Duality\\<close>\n\ntext \\<open>\n  The \\emph{dual} of an ordered structure is an isomorphic copy of the\n  underlying type, with the \\<open>\\<sqsubseteq>\\<close> relation defined as the inverse\n  of the original one.\n\\<close>\n\ndatatype 'a dual = dual 'a\n\nprimrec undual :: \"'a dual \\<Rightarrow> 'a\" where\n  undual_dual: \"undual (dual x) = x\"\n\ninstantiation dual :: (leq) leq\nbegin\n\ndefinition\n  leq_dual_def: \"x' \\<sqsubseteq> y' \\<equiv> undual y' \\<sqsubseteq> undual x'\"\n\ninstance ..\n\nend\n\nlemma undual_leq [iff?]: \"(undual x' \\<sqsubseteq> undual y') = (y' \\<sqsubseteq> x')\"\n  by (simp add: leq_dual_def)\n\nlemma dual_leq [iff?]: \"(dual x \\<sqsubseteq> dual y) = (y \\<sqsubseteq> x)\"\n  by (simp add: leq_dual_def)\n\ntext \\<open>\n  \\medskip Functions @{term dual} and @{term undual} are inverse to\n  each other; this entails the following fundamental properties.\n\\<close>\n\nlemma dual_undual [simp]: \"dual (undual x') = x'\"\n  by (cases x') simp\n\nlemma undual_dual_id [simp]: \"undual o dual = id\"\n  by (rule ext) simp\n\nlemma dual_undual_id [simp]: \"dual o undual = id\"\n  by (rule ext) simp\n\ntext \\<open>\n  \\medskip Since @{term dual} (and @{term undual}) are both injective\n  and surjective, the basic logical connectives (equality,\n  quantification etc.) are transferred as follows.\n\\<close>\n\nlemma undual_equality [iff?]: \"(undual x' = undual y') = (x' = y')\"\n  by (cases x', cases y') simp\n\nlemma dual_equality [iff?]: \"(dual x = dual y) = (x = y)\"\n  by simp\n\nlemma dual_ball [iff?]: \"(\\<forall>x \\<in> A. P (dual x)) = (\\<forall>x' \\<in> dual ` A. P x')\"\nproof\n  assume a: \"\\<forall>x \\<in> A. P (dual x)\"\n  show \"\\<forall>x' \\<in> dual ` A. P x'\"\n  proof\n    fix x' assume x': \"x' \\<in> dual ` A\"\n    have \"undual x' \\<in> A\"\n    proof -\n      from x' have \"undual x' \\<in> undual ` dual ` A\" by simp\n      thus \"undual x' \\<in> A\" by (simp add: image_comp)\n    qed\n    with a have \"P (dual (undual x'))\" ..\n    also have \"\\<dots> = x'\" by simp\n    finally show \"P x'\" .\n  qed\nnext\n  assume a: \"\\<forall>x' \\<in> dual ` A. P x'\"\n  show \"\\<forall>x \\<in> A. P (dual x)\"\n  proof\n    fix x assume \"x \\<in> A\"\n    hence \"dual x \\<in> dual ` A\" by simp\n    with a show \"P (dual x)\" ..\n  qed\nqed\n\nlemma range_dual [simp]: \"surj dual\"\nproof -\n  have \"\\<And>x'. dual (undual x') = x'\" by simp\n  thus \"surj dual\" by (rule surjI)\nqed\n\nlemma dual_all [iff?]: \"(\\<forall>x. P (dual x)) = (\\<forall>x'. P x')\"\nproof -\n  have \"(\\<forall>x \\<in> UNIV. P (dual x)) = (\\<forall>x' \\<in> dual ` UNIV. P x')\"\n    by (rule dual_ball)\n  thus ?thesis by simp\nqed\n\nlemma dual_ex: \"(\\<exists>x. P (dual x)) = (\\<exists>x'. P x')\"\nproof -\n  have \"(\\<forall>x. \\<not> P (dual x)) = (\\<forall>x'. \\<not> P x')\"\n    by (rule dual_all)\n  thus ?thesis by blast\nqed\n\nlemma dual_Collect: \"{dual x| x. P (dual x)} = {x'. P x'}\"\nproof -\n  have \"{dual x| x. P (dual x)} = {x'. \\<exists>x''. x' = x'' \\<and> P x''}\"\n    by (simp only: dual_ex [symmetric])\n  thus ?thesis by blast\nqed\n\n\nsubsection \\<open>Transforming orders\\<close>\n\nsubsubsection \\<open>Duals\\<close>\n\ntext \\<open>\n  The classes of quasi, partial, and linear orders are all closed\n  under formation of dual structures.\n\\<close>\n\ninstance dual :: (quasi_order) quasi_order\nproof\n  fix x' y' z' :: \"'a::quasi_order dual\"\n  have \"undual x' \\<sqsubseteq> undual x'\" .. thus \"x' \\<sqsubseteq> x'\" ..\n  assume \"y' \\<sqsubseteq> z'\" hence \"undual z' \\<sqsubseteq> undual y'\" ..\n  also assume \"x' \\<sqsubseteq> y'\" hence \"undual y' \\<sqsubseteq> undual x'\" ..\n  finally show \"x' \\<sqsubseteq> z'\" ..\nqed\n\ninstance dual :: (partial_order) partial_order\nproof\n  fix x' y' :: \"'a::partial_order dual\"\n  assume \"y' \\<sqsubseteq> x'\" hence \"undual x' \\<sqsubseteq> undual y'\" ..\n  also assume \"x' \\<sqsubseteq> y'\" hence \"undual y' \\<sqsubseteq> undual x'\" ..\n  finally show \"x' = y'\" ..\nqed\n\ninstance dual :: (linear_order) linear_order\nproof\n  fix x' y' :: \"'a::linear_order dual\"\n  show \"x' \\<sqsubseteq> y' \\<or> y' \\<sqsubseteq> x'\"\n  proof (rule linear_order_cases)\n    assume \"undual y' \\<sqsubseteq> undual x'\"\n    hence \"x' \\<sqsubseteq> y'\" .. thus ?thesis ..\n  next\n    assume \"undual x' \\<sqsubseteq> undual y'\"\n    hence \"y' \\<sqsubseteq> x'\" .. thus ?thesis ..\n  qed\nqed\n\n\nsubsubsection \\<open>Binary products \\label{sec:prod-order}\\<close>\n\ntext \\<open>\n  The classes of quasi and partial orders are closed under binary\n  products.  Note that the direct product of linear orders need\n  \\emph{not} be linear in general.\n\\<close>\n\ninstantiation prod :: (leq, leq) leq\nbegin\n\ndefinition\n  leq_prod_def: \"p \\<sqsubseteq> q \\<equiv> fst p \\<sqsubseteq> fst q \\<and> snd p \\<sqsubseteq> snd q\"\n\ninstance ..\n\nend\n\nlemma leq_prodI [intro?]:\n    \"fst p \\<sqsubseteq> fst q \\<Longrightarrow> snd p \\<sqsubseteq> snd q \\<Longrightarrow> p \\<sqsubseteq> q\"\n  by (unfold leq_prod_def) blast\n\nlemma leq_prodE [elim?]:\n    \"p \\<sqsubseteq> q \\<Longrightarrow> (fst p \\<sqsubseteq> fst q \\<Longrightarrow> snd p \\<sqsubseteq> snd q \\<Longrightarrow> C) \\<Longrightarrow> C\"\n  by (unfold leq_prod_def) blast\n\ninstance prod :: (quasi_order, quasi_order) quasi_order\nproof\n  fix p q r :: \"'a::quasi_order \\<times> 'b::quasi_order\"\n  show \"p \\<sqsubseteq> p\"\n  proof\n    show \"fst p \\<sqsubseteq> fst p\" ..\n    show \"snd p \\<sqsubseteq> snd p\" ..\n  qed\n  assume pq: \"p \\<sqsubseteq> q\" and qr: \"q \\<sqsubseteq> r\"\n  show \"p \\<sqsubseteq> r\"\n  proof\n    from pq have \"fst p \\<sqsubseteq> fst q\" ..\n    also from qr have \"\\<dots> \\<sqsubseteq> fst r\" ..\n    finally show \"fst p \\<sqsubseteq> fst r\" .\n    from pq have \"snd p \\<sqsubseteq> snd q\" ..\n    also from qr have \"\\<dots> \\<sqsubseteq> snd r\" ..\n    finally show \"snd p \\<sqsubseteq> snd r\" .\n  qed\nqed\n\ninstance prod :: (partial_order, partial_order) partial_order\nproof\n  fix p q :: \"'a::partial_order \\<times> 'b::partial_order\"\n  assume pq: \"p \\<sqsubseteq> q\" and qp: \"q \\<sqsubseteq> p\"\n  show \"p = q\"\n  proof\n    from pq have \"fst p \\<sqsubseteq> fst q\" ..\n    also from qp have \"\\<dots> \\<sqsubseteq> fst p\" ..\n    finally show \"fst p = fst q\" .\n    from pq have \"snd p \\<sqsubseteq> snd q\" ..\n    also from qp have \"\\<dots> \\<sqsubseteq> snd p\" ..\n    finally show \"snd p = snd q\" .\n  qed\nqed\n\n\nsubsubsection \\<open>General products \\label{sec:fun-order}\\<close>\n\ntext \\<open>\n  The classes of quasi and partial orders are closed under general\n  products (function spaces).  Note that the direct product of linear\n  orders need \\emph{not} be linear in general.\n\\<close>\n\ninstantiation \"fun\" :: (type, leq) leq\nbegin\n\ndefinition\n  leq_fun_def: \"f \\<sqsubseteq> g \\<equiv> \\<forall>x. f x \\<sqsubseteq> g x\"\n\ninstance ..\n\nend\n\nlemma leq_funI [intro?]: \"(\\<And>x. f x \\<sqsubseteq> g x) \\<Longrightarrow> f \\<sqsubseteq> g\"\n  by (unfold leq_fun_def) blast\n\nlemma leq_funD [dest?]: \"f \\<sqsubseteq> g \\<Longrightarrow> f x \\<sqsubseteq> g x\"\n  by (unfold leq_fun_def) blast\n\ninstance \"fun\" :: (type, quasi_order) quasi_order\nproof\n  fix f g h :: \"'a \\<Rightarrow> 'b::quasi_order\"\n  show \"f \\<sqsubseteq> f\"\n  proof\n    fix x show \"f x \\<sqsubseteq> f x\" ..\n  qed\n  assume fg: \"f \\<sqsubseteq> g\" and gh: \"g \\<sqsubseteq> h\"\n  show \"f \\<sqsubseteq> h\"\n  proof\n    fix x from fg have \"f x \\<sqsubseteq> g x\" ..\n    also from gh have \"\\<dots> \\<sqsubseteq> h x\" ..\n    finally show \"f x \\<sqsubseteq> h x\" .\n  qed\nqed\n\ninstance \"fun\" :: (type, partial_order) partial_order\nproof\n  fix f g :: \"'a \\<Rightarrow> 'b::partial_order\"\n  assume fg: \"f \\<sqsubseteq> g\" and gf: \"g \\<sqsubseteq> f\"\n  show \"f = g\"\n  proof\n    fix x from fg have \"f x \\<sqsubseteq> g x\" ..\n    also from gf have \"\\<dots> \\<sqsubseteq> f x\" ..\n    finally show \"f x = g x\" .\n  qed\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Lattice/Orders.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757870046160257, "lm_q2_score": 0.863391599428538, "lm_q1q2_score": 0.7561471426741588}}
{"text": "theory Practical\nimports Main\nbegin\n\n(***************************First-order logic*************************************)\n\n(*1 mark*)\nlemma \"A\\<or>A \\<longrightarrow> A\"\n  apply (rule impI)\n  apply (erule disjE)\n   apply assumption+\n  done\n\n(*1 mark*)\nlemma \"(P\\<longrightarrow>R)\\<longrightarrow>(\\<not>P\\<or>R)\"\n  apply (rule impI)\n  apply (rule ccontr)\n  apply (erule impE)\n   apply (rule ccontr)\n   apply (erule notE)\n   apply (rule disjI1)\n   apply assumption\n  apply (erule notE)\n  apply (rule disjI2)\n  apply assumption\n  done\n\n(*1 mark*)\nlemma \"(P\\<and>Q\\<longrightarrow>R)\\<longrightarrow>P\\<longrightarrow>Q\\<longrightarrow>R\"\n  apply (rule impI)+\n  apply (erule impE)\n   apply (rule conjI)\n    apply assumption+\n  done\n\n(*3 marks*)\nlemma \"\\<not>\\<not>P \\<or> \\<not>P\"\n  apply (rule classical)\n  apply (rule disjI2)\n  apply (rule classical)\n  apply (erule notE)\n  apply (rule disjI1)\n  apply assumption\n  done\n\n(*4 marks*)\nlemma \"(P\\<or>R)\\<longleftrightarrow>(\\<not>(\\<not>P\\<and> \\<not>R))\"\n  apply (rule iffI)\n   apply (rule notI)\n   apply (erule disjE)\n    apply (erule conjE)\n    apply (erule notE)\n    apply assumption\n   apply (erule conjE)\n   apply (erule_tac P = \"R\" in notE)\n   apply assumption\n  apply (rule ccontr)\n  apply (erule notE)\n  apply (rule conjI)\n   apply (rule notI)\n   apply (erule notE)\n   apply (rule disjI1)\n   apply assumption\n  apply (rule notI)\n  apply (erule notE)\n  apply (rule disjI2)\n  apply assumption\n  done\n\n(*1 mark*)\n(* First version theory file lemma *)\nlemma \"(\\<forall> x . F x \\<longrightarrow> G x ) \\<longrightarrow> \\<not> (\\<exists> x . F x \\<and> \\<not> G x )\"\n  apply (rule impI)\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule allE)\n  apply (erule impE)\n   apply (erule conjE)\n   apply assumption\n  apply (erule conjE)\n  apply (erule notE)\n  apply assumption\n  done\n\n(* Updated lemma in handout *)\nlemma \"(\\<forall> x . F x) \\<and> (\\<forall> x . G x ) \\<longrightarrow> (\\<forall> x . F x \\<and> G x )\"\n  apply (rule impI)\n  apply (rule allI)\n  apply (erule conjE)\n  apply (rule conjI)\n   apply (erule allE, assumption)+\n  done\n\n(*1 mark*)\nlemma \"(\\<forall> x y. R x y) \\<longrightarrow> (\\<forall> x . R x x )\"\n  apply (rule impI)\n  apply (rule allI)\n  apply (erule allE)+\n  apply assumption\n  done\n\n(*3 marks*)\nlemma \"(\\<forall>x. P x)\\<or>(\\<exists>x.\\<not>P x)\"\n  apply (rule classical)\n  apply (rule disjI1)\n  apply (rule allI)\n  apply (rule classical)\n  apply (erule notE)\n  apply (rule disjI2)\n  apply (rule exI)\n  apply assumption\n  done\n\n(*3 marks*)\nlemma \"(\\<forall>x. \\<not> (P x \\<longrightarrow> Q x)) \\<longrightarrow> \\<not>(\\<exists>x. \\<not>P x \\<and> Q x)\"\n  apply (rule impI)\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule allE)\n  apply (erule notE)\n  apply (rule impI)\n  apply (erule conjE)\n  apply assumption\n  done\n\n(*3 marks*)\nlemma \"\\<exists>Bob. (drunk Bob \\<longrightarrow> (\\<forall>y. drunk y))\"\n apply (rule classical)\n  apply (rule exI)\n  apply (rule impI)\n  apply (rule allI)\n  apply (erule notE)\n  apply (rule classical)\n  apply (rule exI)\n  apply (rule impI)\n  apply (rule allI)\n  apply (rule classical)\n  apply (erule notE)\n  apply (rule exI)\n  apply (rule impI)\n  apply (rule allI)\n  apply (erule notE)\n  apply assumption\n  done\n\n(*4 marks*)\nlemma \"\\<not> (\\<exists> barber . man barber \\<and> (\\<forall> x . man x \\<and> \\<not>shaves x x \\<longleftrightarrow> shaves barber x ))\"\n  apply (rule notI)\n  apply (erule exE)\n  apply (erule conjE)\n  apply (erule allE)\n  apply (erule iffE)\n  apply (erule impE)\n   apply (rule conjI)\n    apply assumption\n   apply (rule notI)\n   apply (erule impE, assumption, erule conjE, erule notE, assumption)+\n  done\n\nlocale incidence =\n  fixes incidence_points_on_sections :: \"'point \\<Rightarrow> 'section \\<Rightarrow> bool\" (infix \" \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t \" 80)\n  fixes region_to_section :: \"'region \\<Rightarrow> 'section\" \n(*Write here your axiom stating that every section has a point incident to it*) (*2 marks*)\n  assumes section_nonempty: \"\\<forall>s. \\<exists>P. P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t s\"\n(*Write here your axiom stating that two sections are the same if the same points are\nincident to each*) (*2 marks*)\n  and section_uniqueness: \"\\<forall>s1 s2. (\\<forall>P. (P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t s1 \\<longleftrightarrow> P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t s2)) \\<longrightarrow> s1 = s2\"\n\nbegin\n\ndefinition isPartOf ::\"'section \\<Rightarrow> 'section \\<Rightarrow> bool\" (infix \"isPartOf\" 80) where \n(*write your formalisation of definition D1 here*) (*1 mark*)\n\"s1 isPartOf s2 \\<equiv> \\<forall>P. (P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t s1 \\<longrightarrow> P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t s2)\"\n\ndefinition inclusion ::\"'region \\<Rightarrow> 'section \\<Rightarrow> bool\"(infix \"isIncludedIn\" 80) where\n(*write your formalisation of definition D2 here*) (*1 mark*)\n\"R isIncludedIn s \\<equiv> (region_to_section R) isPartOf s\"\n\ndefinition overlaps ::\"'region \\<Rightarrow> 'section \\<Rightarrow> bool\"(infix \"overlaps\" 80) where\n(*write your formalisation of definition D3 here*) (*1 mark*)\n\" R overlaps s \\<equiv> \\<exists>P. P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t (region_to_section R) \\<and> P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t s\"\n\nlemma region_overlaps_itself: \"R overlaps (region_to_section R)\"\n(*Write your structured proof here*) (*2 marks*)\nproof (unfold overlaps_def)\n  have incidence: \"\\<exists>P. P \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t region_to_section R\"\n    by (simp add: section_nonempty)\n  show \"\\<exists>P. P  \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t  region_to_section R \\<and> P  \\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t  region_to_section R\" using incidence\n    by auto\nqed \n\n(*Formalise and prove that isPartOf is reflexive, transitive and antisymmetric*) (*3 marks*)\nlemma isPartOf_reflexive: \"s isPartOf s\"\n(*Formalise and prove that isPartOf is reflexive here*)\n  by (simp add: isPartOf_def)\n\nlemma isPartOf_transitive: \"(s1 isPartOf s2 \\<and> s2 isPartOf s3) \\<longrightarrow> s1 isPartOf s3\"\n(*Formalise and prove that isPartOf is transitive here*)\n  by (simp add: isPartOf_def)\n\nlemma isPartOf_antisymmetric: \"(s1 isPartOf s2 \\<and> s2 isPartOf s1) \\<longrightarrow> s1 = s2\"\n(*Formalise and prove that isPartOf is antisymmetric here*)\n  using isPartOf_def section_uniqueness by blast\nend\n\n\nlocale section_bundles =  incidence incidence_points_on_sections region_to_section \n  for  incidence_points_on_sections :: \"'point \\<Rightarrow> 'section \\<Rightarrow> bool\" \n  and region_to_section :: \"'region \\<Rightarrow> 'section\" +\n  fixes crossing :: \"'region \\<Rightarrow> 'section \\<Rightarrow> bool\" \n  and incidence_sections_on_bundles :: \"'section \\<Rightarrow> 'bundle \\<Rightarrow> bool\" (infix \"\\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n\" 80) \n(*Write your formalisation of Axiom SC1 here*) (*1 mark*)\n  assumes SC1: \"\\<forall>s R. (crossing R s) \\<longrightarrow> (R overlaps s)\"\n(*Write your formalisation of Axiom SI1 here*)     (*1 mark*)\n and SI1: \"\\<forall>s b1 b2. (s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b1 \\<longleftrightarrow> s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b2) \\<longrightarrow> (b1 = b2)\"\n\nbegin\n\ndefinition atLeastAsRestrictiveAs :: \"'section \\<Rightarrow> 'bundle \\<Rightarrow> 'section \\<Rightarrow> bool\" where \n(*Write your formalisation of atLeastAsRestrictiveAs here*) (*1 mark*)\n\"atLeastAsRestrictiveAs s1 b s2 \\<equiv> (s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> s2 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> s1 isPartOf s2)\"\n\nnotation \n  atLeastAsRestrictiveAs (\"_ \\<le>\\<^sub>_ _\" [80, 80, 80] 80)\n\n\n(*Formalise and prove that isPartOf is reflexive, transitive and antisymmetric*) (*2 marks*)\n\n(*Kulik and Eschenbach say 'The relation \\<ge> is reflexive, transitive and antisymmetric for a given \nsector bundle.' So, do they mean, given that the sections under consideration are in the bundle?\nThis is what we assume for reflexivity.*)\nlemma atLeastAsRestrictiveAs_reflexive: \n  assumes \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"  shows \"s \\<le>\\<^sub>b s\"\n(*Add your proof here*)\n  by (simp add: assms atLeastAsRestrictiveAs_def isPartOf_reflexive)\n\nlemma atLeastAsRestrictiveAs_transitive: \n(*Formalise and prove that atLeastAsRestrictiveAs is transitive*)\n  assumes \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" shows \"(s1 \\<le>\\<^sub>b s2 \\<and> s2 \\<le>\\<^sub>b s3) \\<longrightarrow> (s1 \\<le>\\<^sub>b s3)\"\n  using atLeastAsRestrictiveAs_def isPartOf_transitive by blast\n\nlemma atLeastAsRestrictiveAs_antisymmetric: \n(*Formalise and prove that atLeastAsRestrictiveAs is antisymmetric*)\n  assumes \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" shows \"(s1 \\<le>\\<^sub>b s2 \\<and> s2 \\<le>\\<^sub>b s1) \\<longrightarrow> (s1 = s2)\"\n  by (simp add: atLeastAsRestrictiveAs_def isPartOf_antisymmetric)\n\nend\n\n\nlocale comparison = section_bundles incidence_points_on_sections region_to_section \n crossing incidence_sections_on_bundles\n  for  incidence_points_on_sections :: \"'point \\<Rightarrow> 'section \\<Rightarrow> bool\" (infix \"\\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t\" 80) \n  and region_to_section :: \"'region \\<Rightarrow> 'section\" \n  and crossing :: \"'region \\<Rightarrow> 'section \\<Rightarrow> bool\" (infix \"crosses\" 80) \n  and incidence_sections_on_bundles :: \"'section \\<Rightarrow> 'bundle \\<Rightarrow> bool\" (infix \"\\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n\" 80)+\n(*Write your formalisation of Axiom SB2 here*) (*1 mark*)\nassumes SB2: \"\\<forall>b s1 s2. (s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> s2 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b) \\<longrightarrow> (s1 \\<le>\\<^sub>b s2 \\<or> s2 \\<le>\\<^sub>b s1)\"\n\nbegin\n\n(*Write your formalisation and proof of Theorem T1 here*) (*1 mark*)\nlemma T1: \"\\<forall>b s1 R. (R overlaps s1) \\<longrightarrow> (\\<forall>s2. (s1 \\<le>\\<^sub>b s2) \\<longrightarrow> (R overlaps s2))\"\n  using atLeastAsRestrictiveAs_def isPartOf_def overlaps_def by auto\n\n(*Write your formalisation and proof of Theorem T2 here*) (*1 mark*)\nlemma T2: \"\\<forall>b s1 R. (R isIncludedIn s1) \\<longrightarrow> (\\<forall>s2. (s1 \\<le>\\<^sub>b s2) \\<longrightarrow> (R isIncludedIn s2))\"\n  using atLeastAsRestrictiveAs_def inclusion_def isPartOf_transitive by blast\n\ndefinition isCore (infix \"isCoreOf\" 80) where\n\"s isCoreOf b = (s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> (\\<forall>s'. s' \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> s \\<le>\\<^sub>b s'))\"\n\n(*Write your definition of hull here*) (*1 mark*)\ndefinition isHull (infix \"isHull\" 80) where\n\"s isHull b = (s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> (\\<forall>s'. s' \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> s' \\<le>\\<^sub>b s))\"\n\nend\n\n\nlocale crossing_sector = comparison incidence_points_on_sections \n          region_to_section crossing incidence_sections_on_bundles\n          for incidence_points_on_sections :: \"'point \\<Rightarrow> 'section \\<Rightarrow> bool\" (infix \"\\<iota>\\<^sub>p\\<^sub>o\\<^sub>i\\<^sub>n\\<^sub>t\" 80) \nand region_to_section :: \"'region \\<Rightarrow> 'section\" \nand crossing :: \"'region \\<Rightarrow> 'section \\<Rightarrow> bool\" (infix \"crosses\" 80)  \nand incidence_sections_on_bundles :: \"'section \\<Rightarrow> 'bundle \\<Rightarrow> bool\" (infix \"\\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n\" 80) +\n(*Write your formalisation of Axiom SC2 here*) (*1 mark*)\nassumes SC2: \"\\<forall>b s1 R. (R crosses s1) \\<longrightarrow> (\\<forall>s2. (s2 \\<le>\\<^sub>b s1) \\<longrightarrow> (R crosses s2))\"\nbegin\n\n(****************************)\n(*Write your formalisation and structured proof of the remark 'If a region \noverlaps the core of a section bundle then it overlaps every section of the section bundle'*) \n(*4 marks*)\nlemma overlaps_core:\n  assumes core: \"s1 isCoreOf b\" and overlap: \"R overlaps s1\"\n  shows \"\\<forall>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> R overlaps s\"\nproof (rule allI, rule impI)\n  fix s\n  assume \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n  then have \"s1 \\<le>\\<^sub>b s\"\n    using core isCore_def by blast\n  then show \"R overlaps s\"\n    using overlap T1 by blast\nqed\n\n(*\nWe have that section s is core of bundle b, and region R overlaps s.\nWe showed that s is a section of b, by the definition of core (which says that this section contains\nall sections in the bundle.\nWe need to show that for all sections of the bundle (part of the bundle), we have that R overlaps\nall these sections from the theorems we proved previously (core_region)\n *)\n\n\n(*Write your formalisation and structured proof of the remark `If a region \ncrosses the hull of a section bundle then it crosses every sector of the section bundle'*) \n(*4 marks*)\nlemma crosses_hull:\n  assumes hull: \"s1 isHull b\" and cross: \"R crosses s1\"\n  shows \"\\<forall>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> R crosses s\"\nproof (rule allI, rule impI)\n  fix s\n  assume \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n  then have \"s \\<le>\\<^sub>b s1\"\n    using hull isHull_def by blast\n  then show \"R crosses s\"\n    using cross SC2 by blast\nqed\n\n\n(*Write your formalisation and structured proof of the remark `If a region \ndoes not overlap the hull of a section bundle, it does not overlap any of its sections'*) \n(*4 marks*)\nlemma not_overlap_hull:\n  assumes hull: \"s1 isHull b\" and not_overlaps: \"\\<not>(R overlaps s1)\" and section_bundle: \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n  shows \"(\\<not>(R overlaps s))\"\nproof (insert not_overlaps, rule contrapos_nn, assumption)\n  assume all_overlaps: \"R overlaps s\"\n  then have \"s \\<le>\\<^sub>b s1\"\n    using hull isHull_def section_bundle by blast\n  then show \"R overlaps s1\"\n    using not_overlaps all_overlaps T1 by blast\nqed\n\n\ndefinition overlapsAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\"  where \n\"overlapsAsMuchAs R b R' == (\\<forall>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> R' overlaps s \\<longrightarrow> R overlaps s)\"\n\nnotation \n  overlapsAsMuchAs (\"_ \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>_ _\" [80, 80, 80] 80)\n\ndefinition eq_overlapsAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\"  where \n\"eq_overlapsAsMuchAs R b R' == R \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R' \\<and> R' \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R\"\n\nnotation \n  eq_overlapsAsMuchAs (\"_ \\<cong>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>_ _\" [80, 80, 80] 80)\n\nabbreviation\nrev_overlapsAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\"  (\"_ \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>_ _\" [80, 80, 80] 80)\nwhere\"rev_overlapsAsMuchAs R b R' == overlapsAsMuchAs R' b R\"\n\ndefinition more_overlapsAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\"  where \n\"more_overlapsAsMuchAs R b R' == R \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R' \\<and> \\<not>(R' \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R)\"\n\nnotation \n  more_overlapsAsMuchAs (\"_ >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>_ _\" [80, 80, 80] 80)\n\nabbreviation\nless_overlapsAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\"  (\"_ <\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>_ _\" [80, 80, 80] 80)\nwhere\"less_overlapsAsMuchAs R b R' == more_overlapsAsMuchAs R' b R\"\n\n(*Formalise and prove that overlapsAsMuchAs is reflexive and transitive*) (*2 marks*)\n\nlemma overlapsAsMuchAs_reflexive:\n(*Write your formalisation and proof that overlapsAsMuchAs is reflexive here*) \n  assumes \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" shows \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1\"\n  by (simp add: overlapsAsMuchAs_def)\n\nlemma overlapsAsMuchAs_transitive:\n(*Write your formalisation and proof that overlapsAsMuchAs is transitive here*)\n  assumes \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" shows \"(R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2 \\<and> R2 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R3) \\<longrightarrow> (R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R3)\"\n  by (simp add: overlapsAsMuchAs_def)\n\n\n(*Write your formalisation and structured proof of Theorem T3 here. You must attempt to \nformalise Kulik et al.'s reasoning*) (*11 marks*)\nlemma T3: \"\\<forall>b R1 R2. (R1 >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<longleftrightarrow> (\\<exists>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> R1 overlaps s \\<and> \\<not>(R2 overlaps s))\"\nproof ((rule allI)+, rule iffI)\n  fix b R1 R2\n(*Left-to-right \\<Rightarrow>*)\n  assume moreThan: \"R1 >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n  then have asMuchAs: \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    by (simp add: more_overlapsAsMuchAs_def)\n  then have not_asMuchAs: \"\\<not>(R2 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1)\"\n    using more_overlapsAsMuchAs_def moreThan by blast\n(*overlaps as much as definition*)\n  obtain s where ov_def: \"s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> R2 overlaps s \\<longrightarrow> R1 overlaps s\"\n                and not_ov_def: \"\\<not>(s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> R1 overlaps s \\<longrightarrow> R2 overlaps s)\"\n    using not_asMuchAs overlapsAsMuchAs_def by blast\n  then have overlaps: \"R1 overlaps s\"\n    by blast\n  then have not_overlaps: \"\\<not>(R2 overlaps s)\"\n    using not_ov_def by blast\n  then have \"(\\<not>(s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b) \\<or> R1 overlaps s) \\<and> \\<not>(R2 overlaps s)\" (*Equivalent to not_ov_def*)\n    using not_ov_def by blast\n  then show \"\\<exists>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> R1 overlaps s \\<and> \\<not>(R2 overlaps s)\"\n    using not_ov_def by blast\nnext\n(*Right-to-left \\<Leftarrow>*)\n  fix b R1 R2\n  assume \"(\\<exists>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> R1 overlaps s \\<and> \\<not>(R2 overlaps s))\"\n  then obtain s1 where section_bundle1: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" and overlaps1: \"R1 overlaps s1\"\n                       and not_overlaps1: \"\\<not>(R2 overlaps s1)\"\n    by blast\n  then obtain s2 where section_bundle2: \"s2 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" \n    by blast\n  then have \"(s1 \\<le>\\<^sub>b s2 \\<or> s2 \\<le>\\<^sub>b s1)\"\n    using SB2 section_bundle1 by auto\n  then have restrictive: \"s1 \\<le>\\<^sub>b s2 \\<or> s2 \\<le>\\<^sub>b s1\"\n    using section_bundle1 section_bundle2 by blast\n (* then have part_of: \"(s1 isPartOf s2) \\<or> (s2 isPartOf s1)\"\n    using atLeastAsRestrictiveAs_def by blast*)\n  (*Proof by cases*)\n  from restrictive consider \"s1 \\<le>\\<^sub>b s2\" | \"s2 \\<le>\\<^sub>b s1\" by auto\n  then have asMuchAs: \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n  proof (cases)\n    assume res1: \"s1 \\<le>\\<^sub>b s2\"\n    then have \"(R1 overlaps s1) \\<longrightarrow> (s1 \\<le>\\<^sub>b s2) \\<longrightarrow> (R1 overlaps s2)\"\n      using T1 by blast\n    then have overlaps2: \"R1 overlaps s2\"\n      using overlaps1 res1 by blast\n    then show \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n      using SB2 T1 not_overlaps1 overlaps1 overlapsAsMuchAs_def section_bundle1 by blast\n  next\n    assume res2: \"s2 \\<le>\\<^sub>b s1\"\n    then have expanded_t1: \"(\\<not>(R2 overlaps s1) \\<or> (s2 \\<le>\\<^sub>b s1)) \\<and> \\<not>(R2 overlaps s2)\"\n      using T1 not_overlaps1 by blast\n    then have not_overlaps2: \"\\<not>(R2 overlaps s2)\"\n      by blast\n    then show \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n      using SB2 T1 not_overlaps1 overlaps1 overlapsAsMuchAs_def section_bundle1 by blast\n  qed\n  have not_asMuchAs: \"\\<not>(R2 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1)\"\n    using section_bundle1 overlaps1 not_overlaps1 overlapsAsMuchAs_def by blast\n  then have \"R1 >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    by (simp add: asMuchAs more_overlapsAsMuchAs_def not_asMuchAs)\n  then show \"R1 >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    by blast\nqed\n\n(*In under 200 words, compare and contrast the mechanical proof that you produced with the \npen-and-paper proof by Kulik et al.\\. In particular, indicate any reasoning, proof parts, and/or \nuseful lemmas that you had to make explicit during the mechanisation but may have been glossed over\n or assumed by the pen-and-paper proof. Also highlight any inaccuracies in their language or \nnotation. Note any parts where you had to diverge from their reasoning, and why.\nWrite your answer in a comment here.*) (*4 marks*)\n\n(*\nLEFT-TO-RIGHT \\<Rightarrow>\nIn my paper proof, I just assumed I had an 's' and didn't consider having to get a specific 's' for\nthe \\<exists>s in the conclusion. So, my paper proof was very simple, where I expanded R1 > R2 by the\ndefinition of more_overlapsAsMuchAs in order to obtain R1 \\<ge> R2 and \\<not>(R2 \\<ge> R1). Then, I expanded\nboth of these expressions using the definition of overlapsAsMuchAs to get 'R1 overlaps s' and\n'\\<not>(R2 overlaps s)' respectively, both of which are in the conclusion.\nHowever, for my Isabelle proof, I had to explicitly obtain section 's' using the constraints imposed\nby the definition of overlapsAsMuchAs in order to prove the conclusion. I had to make explicit the \nthe definition of overlapsAsMuchAS to get 'R1 overlaps s' and '\\<not>(R2 overlaps s)'.\n\nRIGHT-TO-LEFT \\<Leftarrow>\nFor this proof I followed Kulik et al.'s reasoning. One of the incaccuracies is that they mentioned\ngetting 's1 isPartOf s2 \\<or> s2 isPartOf s1' using SB2, but these expressions didn't help me in the\nproof. Instead, I used atLeastAsRestrictiveAs in order to obtain the regions overlapping the sections\nusing T1. That is, I had to do a proof by cases using 's1 \\<le>\\<^sub>b s2' and 's2 \\<le>\\<^sub>b s1' separately.\nFor proving 'R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2', I had to explicitly indicate that I was using lemma T1 and\naxiom SB2, not only T1 as stated by Kulik. In my mechanical proof, I also had to make explicit that\nI had '\\<not>(R2 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1)' from '\\<not>(R2 overlaps s)' to obtain the conclusion.\n*)\n\n(*Write your formalisation and proof of Theorem T4 here*) (*1 mark*)\nlemma T4: \"\\<forall>b R1 R2. (R1  >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<cong>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 <\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\n  using T3 eq_overlapsAsMuchAs_def overlapsAsMuchAs_def by auto\n\n(*Write your formalisation and structured proof of Theorem T5 here. \nYou must show it follows from T4*) (*3 marks*)\nlemma T5: \"\\<forall>b R1 R2. (R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\nproof ((rule allI)+)\n  fix b R1 R2\n  have \"(R1 >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<cong>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 <\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\n    by (simp add: T4)\n  from this consider \"(R1  >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\" | \"(R1 \\<cong>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\" | \"(R1 <\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\" by auto\n  then have concl: \"(R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\n  proof (cases)\n    assume \"R1 >\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    then have \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2 \\<and> \\<not>(R2 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1)\"\n      using more_overlapsAsMuchAs_def by blast\n    then have \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n      by simp\n    then show \"(R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\n      by simp\n  next\n    assume \"R1 \\<cong>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    then have \"R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2 \\<and> R2 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1\"\n      using eq_overlapsAsMuchAs_def by blast\n    then show \"(R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\n      by blast\n  next\n    assume \"R1 <\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    then have \"R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2 \\<and> \\<not>(R2 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1)\"\n      using more_overlapsAsMuchAs_def by blast\n    then show \"(R1 \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2) \\<or> (R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2)\"\n      by blast\n  qed\n  then show \"R2 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1 \\<or> R1 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R2\"\n    by simp\nqed\n\n\n(********************Challenge problem****************************************)\n\n(*Write your definition of the relation ci here. \nKulik et al. say `If a region crosses or is included in a section we write ci'.*) (*2 marks*)\ndefinition crosses_isIncludedIn :: \"'region \\<Rightarrow> 'section \\<Rightarrow> bool\"  where\n\"crosses_isIncludedIn R s \\<equiv> R crosses s \\<or> R isIncludedIn s\"\n\nnotation \n  crosses_isIncludedIn (\"_ ci _\" 80)\n\n(*Write your definition of `crosses or is included in as much as' here*) (*2 marks*)\ndefinition crosses_isIncludedInAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n\"crosses_isIncludedInAsMuchAs R b R' \\<equiv> (\\<forall>s. s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> (R crosses s \\<or> (R' isIncludedIn s \\<longrightarrow> R isIncludedIn s)))\" \n\nnotation \n  crosses_isIncludedInAsMuchAs (\"_ \\<ge>\\<^sub>c\\<^sub>i \\<^sub>_ _\" [80, 80, 80] 80)\n\n(*Write your definition of `belongs as much as here: definition D8 in the paper.*) (*2 marks*)\ndefinition belongsAsMuchAs :: \"'region \\<Rightarrow> 'bundle \\<Rightarrow> 'region \\<Rightarrow> bool\" where\n\"belongsAsMuchAs R b R' \\<equiv>  (R \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R') \\<and> (R \\<ge>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R')\"\n\nnotation \n  belongsAsMuchAs (\"_ \\<ge> \\<^sub>_ _\" [80, 80, 80] 80)\n\n(*Formalise and write structured proofs of Theorems T6-T8 for both crossesIncludedInAsMuchAs and\nbelongsAsMuchAs*) (*14 marks*)\n\nlemma T6_crosses_isIncludedInAsMuchAs: \"\\<forall>b R1. (\\<exists>s. s isHull b \\<and> \\<not>(R1 overlaps s)) \\<longrightarrow> (\\<forall>R2. R2 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R1)\"\nproof ((rule allI)+, rule impI, rule allI)\n  fix b R1 R2 \n  assume \"\\<exists>s. s isHull b \\<and> \\<not>(R1 overlaps s)\"\n  then obtain s1 where hull: \"s1 isHull b\" and not_overlaps: \"\\<not>(R1 overlaps s1)\"\n    by blast\n  then have hull_def: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<and> (\\<forall>s2. s2 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<longrightarrow> s2 \\<le>\\<^sub>b s1)\"\n    using hull isHull_def by blast\n  then have section_bundle: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n    by blast\n  then show \"R2 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R1\"\n    by (meson crosses_isIncludedInAsMuchAs_def hull inclusion_def isPartOf_def not_overlap_hull\n        not_overlaps overlaps_def region_overlaps_itself)\nqed\n(*\n  assume \"s2 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n  then have res: \"s2 \\<le>\\<^sub>b s1\"\n    using hull_def by blast\n  then have \"s2 isPartOf s1\"\n    by (simp add: atLeastAsRestrictiveAs_def)\n  then have part: \"(region_to_section R2) isPartOf s1\" (*s2 = region_to_section R2*)\n    by (simp add: eq)\n  then have inclusion1: \"R2 isIncludedIn s1\"\n    by (simp add: inclusion_def)\n  then have not_crosses: \"\\<not>(R1 crosses s1)\" (*\\<^sub>c\\<^sub>iconclusion of \\<ge>\\<^sub>c\\<^sub>i: R1 crosses s1 \\<or> (R2 isIncludedIn s1 \\<longrightarrow> R1 isIncludedIn s1)*)\n    using SC1 not_overlaps by blast\n*)\n\n(*\nWe can show \"R2 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R1\" by its definition.\nSince we have obtained \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\" from isHull_def, we can get\n\"R1 crosses s1 \\<or> (R2 isIncludedIn s1 \\<longrightarrow> R1 isIncludedIn s1)\". \nBut we have the assumption that \"\\<not>(R1 overlaps s1)\", so we have that \"\\<not>(R1 crosses s1)\" by\nthe definition of overlaps.\nThus, we know that in the disjunction above, it must be the case that \"(R2 isIncludedIn s1 \\<longrightarrow> R1 isIncludedIn s1)\".\nWe have that \"R2 isIncludedIn s1\" if we assume that \"region_to_section R2\" gives us s2.\nWe obtained that \"s2 isPartOF s1\" from the atLeastAsRestrictiveAs_def \"s2 \\<le>\\<^sub>b s1\" (obtained from hull definition)\nTherefore, from the intermediate proofs above, we can show that \"R2 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R1\"\n*)\n\nlemma T6_belongsAsMuchAs: \"\\<forall>b R1. (\\<exists>s. s isHull b \\<and> \\<not>(R1 overlaps s)) \\<longrightarrow> (\\<forall>R2. R2 \\<ge> \\<^sub>b R1)\"\nproof ((rule allI)+, rule impI, rule allI)\n  fix b R1 R2\n  assume \"\\<exists>s. s isHull b \\<and> \\<not>(R1 overlaps s)\"\n  then obtain s1 where hull: \"s1 isHull b\" and not_overlaps: \"\\<not>(R1 overlaps s1)\"\n    by blast\n  then have section_bundle: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n    using isHull_def by blast\n  then show \"R2 \\<ge> \\<^sub>b R1\"\n  proof -\n    have overlaps: \"\\<forall>R3 b R4. \\<exists>s. (R3 overlaps s \\<or> R3 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R4) \\<and> (s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<or> R3 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R4)\"\n      using overlapsAsMuchAs_def by blast\n    then show \"R2 \\<ge> \\<^sub>b R1\"\n      by (meson T1 T6_crosses_isIncludedInAsMuchAs belongsAsMuchAs_def hull isHull_def not_overlaps)\n  qed\nqed\n\nlemma T7_crosses_isIncludedInAsMuchAs: \"\\<forall>b R1. (\\<exists>s. s isCoreOf b \\<and> R1 isIncludedIn s) \\<longrightarrow> (\\<forall>R2. R1 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R2)\"\nproof ((rule allI)+, rule impI, rule allI)\n  fix b R1 R2\n  fix s2\n  assume \"\\<exists>s. s isCoreOf b \\<and> R1 isIncludedIn s\"\n  then obtain s1 where core: \"s1 isCoreOf b\" and inclusion1: \"R1 isIncludedIn s1\"\n    by blast\n  then have section_bundle1: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n    by (simp add: isCore_def)\n  then show \"R1 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R2\"\n    using T2 core crosses_isIncludedInAsMuchAs_def inclusion1 isCore_def by blast\nqed\n\nlemma T7_belongsAsMuchAs: \"\\<forall>b R1. (\\<exists>s. s isCoreOf b \\<and> R1 isIncludedIn s) \\<longrightarrow> (\\<forall>R2. R1 \\<ge> \\<^sub>b R2)\"\nproof ((rule allI)+, rule impI, rule allI)\n  fix b R1 R2\n  assume \"\\<exists>s. s isCoreOf b \\<and> R1 isIncludedIn s\"\n  then obtain s1 where core: \"s1 isCoreOf b\" and inclusion1: \"R1 isIncludedIn s1\"\n    by blast\n  then have section_bundle1: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n    by (simp add: isCore_def)\n  then show \"R1 \\<ge> \\<^sub>b R2\"\n  proof -\n    have \"\\<forall>s. R1 overlaps s \\<or> \\<not> s1 isPartOf s\"\n      by (meson inclusion1 inclusion_def isPartOf_def overlaps_def section_nonempty)\n    then show \"R1 \\<ge> \\<^sub>b R2\"\n      using T7_crosses_isIncludedInAsMuchAs atLeastAsRestrictiveAs_def belongsAsMuchAs_def core\n            inclusion1 isCore_def overlapsAsMuchAs_def by auto\n  qed\nqed\n\nlemma T8_crosses_isIncludedInAsMuchAs: \"\\<forall>b R1. (\\<exists>s. s isHull b \\<and> (R1 crosses s)) \\<longrightarrow> (\\<forall>R2. R1 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R2)\"\nproof ((rule allI)+, rule impI, rule allI)\n  fix b R1 R2\n  assume \"\\<exists>s. s isHull b \\<and> (R1 crosses s)\"\n  then obtain s1 where hull: \"s1 isHull b\" and cross: \"R1 crosses s1\"\n    by blast\n  then have section_bundle1: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n    using isHull_def by blast\n  then show \"R1 \\<ge>\\<^sub>c\\<^sub>i \\<^sub>b R2\"\n    using cross crosses_hull crosses_isIncludedInAsMuchAs_def hull by blast\nqed\n\nlemma T8_belongsAsMuchAs: \"\\<forall>b R1. (\\<exists>s. s isHull b \\<and> (R1 crosses s)) \\<longrightarrow> (\\<forall>R2. R1 \\<ge> \\<^sub>b R2)\"\nproof ((rule allI)+, rule impI, rule allI)\n  fix b R1 R2\n  assume \"\\<exists>s. s isHull b \\<and> (R1 crosses s)\"\n  then obtain s1 where hull: \"s1 isHull b\" and cross: \"R1 crosses s1\"\n    by blast\n  then have section_bundle1: \"s1 \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b\"\n    using isHull_def by blast\n  then show \"R1 \\<ge> \\<^sub>b R2\"\n  proof -\n    have \"\\<forall>s. \\<not> s \\<iota>\\<^sub>s\\<^sub>e\\<^sub>c\\<^sub>t\\<^sub>i\\<^sub>o\\<^sub>n b \\<or> R1 crosses s\"\n      using cross crosses_hull hull by blast\n    then have overlaps1: \"R2 \\<le>\\<^sub>o\\<^sub>v\\<^sub>e\\<^sub>r\\<^sub>l\\<^sub>a\\<^sub>p\\<^sub>s \\<^sub>b R1\"\n      by (simp add: SC1 overlapsAsMuchAs_def)\n    then show \"R1 \\<ge> \\<^sub>b R2\"\n      using T8_crosses_isIncludedInAsMuchAs belongsAsMuchAs_def cross hull by blast\n  qed\nqed\n\nend\n\nend", "meta": {"author": "celinadongye", "repo": "Geometry-of-Sections", "sha": "8ebddd7b66249cb4ad576c5df6ddaf905786790c", "save_path": "github-repos/isabelle/celinadongye-Geometry-of-Sections", "path": "github-repos/isabelle/celinadongye-Geometry-of-Sections/Geometry-of-Sections-8ebddd7b66249cb4ad576c5df6ddaf905786790c/Practical.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.7560855934427094}}
{"text": "(* Title: Dual_Systems.thy\n   Author: Chelsea Edmonds\n*)\n\nsection \\<open> Dual Systems \\<close>\ntext \\<open>The concept of a dual incidence system \\<^cite>\\<open>\"colbournHandbookCombinatorialDesigns2007\"\\<close>\n is an important property in design theory. It enables us to reason on the existence of several \ndifferent types of design constructs through dual properties \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>\\<close>\n\ntheory Dual_Systems imports Incidence_Matrices\nbegin\n\nsubsection \\<open>Dual Blocks \\<close>\ntext \\<open>A dual design of $(\\mathcal{V}, \\mathcal{B})$, is the design where each block in $\\mathcal{B}$\nrepresents a point $x$, and a block in a dual design is a set of blocks which $x$ is in from the original design. \nIt is important to note that if a block repeats in $\\mathcal{B}$, each instance of the block is a distinct point. \nAs such the definition below uses each block's list index as its identifier. The list of points would simply be the \nindices $0..<$length $Bs$ \\<close>   \n\ndefinition dual_blocks :: \"'a set \\<Rightarrow> 'a set list \\<Rightarrow> nat set multiset\" where\n\"dual_blocks \\<V> \\<B>s \\<equiv> {# {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y} . x \\<in># (mset_set \\<V>)#}\"\n\nlemma dual_blocks_wf: \"b \\<in># dual_blocks V Bs \\<Longrightarrow> b \\<subseteq> {0..<length Bs}\"\n  by (auto simp add: dual_blocks_def)\n\ncontext ordered_incidence_system\nbegin\n\ndefinition dual_blocks_ordered :: \"nat set list\" (\"\\<B>s*\") where\n\"dual_blocks_ordered \\<equiv> map (\\<lambda> x . {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y}) \\<V>s\"\n\nlemma dual_blocks_ordered_eq: \"dual_blocks \\<V> \\<B>s= mset (\\<B>s*)\"\n  by (auto simp add: distinct dual_blocks_def dual_blocks_ordered_def mset_set_set)\n\nlemma dual_blocks_len: \"length \\<B>s* = length \\<V>s\"\n  by (simp add: dual_blocks_ordered_def)\n\ntext \\<open>A dual system is an incidence system \\<close>\nsublocale dual_sys: finite_incidence_system \"{0..<length \\<B>s}\" \"dual_blocks \\<V> \\<B>s\"\n  using dual_blocks_wf by(unfold_locales) (auto)\n\nlemma dual_is_ordered_inc_sys: \"ordered_incidence_system [0..<length \\<B>s] \\<B>s*\"\n  using inc_sys_orderedI dual_blocks_ordered_eq\n  by (metis atLeastLessThan_upt distinct_upt dual_sys.incidence_system_axioms)\n\ninterpretation ordered_dual_sys: ordered_incidence_system \"[0..<length \\<B>s]\" \"\\<B>s*\"\n  using dual_is_ordered_inc_sys by simp \n\nsubsection \\<open>Basic Dual Properties\\<close>\nlemma ord_dual_blocks_b: \"ordered_dual_sys.\\<b> = \\<v>\"\n  using dual_blocks_len by (simp add: points_list_length) \n\nlemma dual_blocks_b: \"dual_sys.\\<b> = \\<v>\"\n  using points_list_length\n  by (simp add: dual_blocks_len dual_blocks_ordered_eq) \n\nlemma dual_blocks_v: \"dual_sys.\\<v> = \\<b>\"\n  by fastforce\n\nlemma ord_dual_blocks_v: \"ordered_dual_sys.\\<v> = \\<b>\"\n  by fastforce\n\nlemma dual_point_block: \"i < \\<v> \\<Longrightarrow> \\<B>s* ! i = {y. y < length \\<B>s \\<and> (\\<V>s ! i) \\<in> \\<B>s ! y}\"\n  by (simp add: dual_blocks_ordered_def points_list_length)\n\nlemma dual_incidence_iff: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> \\<B>s ! j = bl \\<Longrightarrow> \\<V>s ! i = x \\<Longrightarrow> (x \\<in> bl \\<longleftrightarrow> j \\<in> \\<B>s* ! i)\"\n  using dual_point_block by (intro iffI)(simp_all)\n\nlemma dual_incidence_iff2: \"i < \\<v> \\<Longrightarrow> j < \\<b> \\<Longrightarrow> (\\<V>s ! i \\<in> \\<B>s ! j  \\<longleftrightarrow> j \\<in> \\<B>s* ! i)\"\n  using dual_incidence_iff by simp\n\nlemma dual_blocks_point_exists: \"bl \\<in># dual_blocks \\<V> \\<B>s \\<Longrightarrow> \n    \\<exists> x. x \\<in> \\<V> \\<and> bl = {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y}\"\n  by (auto simp add: dual_blocks_def)\n\nlemma dual_blocks_ne_index_ne:  \"j1 < length \\<B>s* \\<Longrightarrow> j2 < length \\<B>s* \\<Longrightarrow> \\<B>s* ! j1 \\<noteq> \\<B>s* ! j2 \\<Longrightarrow> j1 \\<noteq> j2\"\n  by auto\n\nlemma dual_blocks_list_index_img: \"image_mset (\\<lambda>x . \\<B>s* ! x) (mset_set {0..<length \\<B>s*}) = mset \\<B>s*\"\n  using lessThan_atLeast0 ordered_dual_sys.blocks_list_length ordered_dual_sys.blocks_mset_image \n  by presburger\n\nlemma dual_blocks_elem_iff:\n  assumes \"j < \\<v>\"\n  shows \"x \\<in> (\\<B>s* ! j) \\<longleftrightarrow> \\<V>s ! j \\<in> \\<B>s ! x \\<and> x < \\<b>\"\nproof (intro iffI conjI)\n  show \"x \\<in> \\<B>s* ! j \\<Longrightarrow> \\<V>s ! j \\<in> \\<B>s ! x\"\n    using assms ordered_incidence_system.dual_point_block ordered_incidence_system_axioms \n    by fastforce\n  show \"x \\<in> \\<B>s* ! j \\<Longrightarrow> x < \\<b>\"\n    using assms dual_blocks_ordered_def dual_point_block by fastforce\n  show \"\\<V>s ! j \\<in> \\<B>s ! x \\<and> x < \\<b> \\<Longrightarrow> x \\<in> \\<B>s* ! j\"\n    by (metis (full_types) assms blocks_list_length dual_incidence_iff)\nqed\n\ntext \\<open>The incidence matrix of the dual of a design is just the transpose \\<close>\nlemma dual_incidence_mat_eq_trans: \"ordered_dual_sys.N = N\\<^sup>T\"\nproof (intro eq_matI)\n  show dimr: \"dim_row ordered_dual_sys.N = dim_row N\\<^sup>T\" using dual_blocks_v by (simp) \n  show dimc: \"dim_col ordered_dual_sys.N = dim_col N\\<^sup>T\" using ord_dual_blocks_b by (simp)\n  show \"\\<And>i j. i < dim_row N\\<^sup>T \\<Longrightarrow> j < dim_col N\\<^sup>T \\<Longrightarrow> ordered_dual_sys.N $$ (i, j) = N\\<^sup>T $$ (i, j)\" \n  proof -\n    fix i j assume ilt: \"i < dim_row N\\<^sup>T\" assume jlt: \"j < dim_col N\\<^sup>T\"\n    then have ilt2: \"i < length \\<B>s\"using dimr\n      using blocks_list_length ord_dual_blocks_v ilt ordered_dual_sys.dim_row_is_v by linarith\n    then have ilt3: \"i < \\<b>\" by simp\n    have jlt2: \"j < \\<v>\" using jlt\n      using dim_row_is_v by fastforce \n    have \"ordered_dual_sys.N $$ (i, j) =  (if ([0..<length \\<B>s] ! i) \\<in> (\\<B>s* ! j) then 1 else 0)\"\n      using dimr dual_blocks_len ilt jlt inc_matrix_elems_one_zero\n      by (metis  inc_mat_dim_row inc_matrix_point_in_block_iff index_transpose_mat(3) )\n    then have \"ordered_dual_sys.N $$ (i, j) = (if \\<V>s ! j \\<in> \\<B>s ! i then 1 else 0)\" \n      using ilt3 jlt2 dual_incidence_iff2 by simp \n    thus \"ordered_dual_sys.N $$ (i, j) = N\\<^sup>T $$ (i, j)\" \n      using ilt3 jlt2 dim_row_is_v dim_col_is_b N_trans_index_val by simp\n  qed\nqed\n\nlemma dual_incidence_mat_eq_trans_rev: \"(ordered_dual_sys.N)\\<^sup>T = N\"\n  using dual_incidence_mat_eq_trans by simp \n\nsubsection \\<open>Incidence System Dual Properties\\<close>\ntext \\<open>Many common design properties have a dual in the dual design which enables extensive reasoning\nUsing incidence matrices and the transpose property these are easy to prove. We leave examples of \ncounting proofs (commented out), to demonstrate how incidence matrices can significantly simplify \nreasoning \\<close>\n\nlemma dual_blocks_nempty:\n  assumes \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\"\n  assumes \"bl \\<in># dual_blocks \\<V> \\<B>s\"\n  shows \"bl \\<noteq> {}\"\nproof -\n  have \"bl \\<in># {# {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y} . x \\<in># (mset_set \\<V>)#}\" \n    using assms dual_blocks_def by metis \n  then obtain x where \"x \\<in># (mset_set \\<V>)\" and blval: \"bl = {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y}\"\n    by blast \n  then obtain bl' where \"bl' \\<in># \\<B>\" and xin: \"x \\<in> bl'\" using assms(1)\n    using point_in_block_rep_min_iff by auto \n  then obtain y where \"y < length \\<B>s\" and \"\\<B>s ! y = bl'\"\n    using valid_blocks_index_cons by auto \n  then have \"y \\<in> bl\"\n    by (simp add: xin blval) \n  thus ?thesis by blast\nqed\n\nlemma dual_blocks_size_is_rep: \"j < length \\<B>s* \\<Longrightarrow> card (\\<B>s* ! j) = \\<B> rep (\\<V>s ! j)\"\n  using dual_incidence_mat_eq_trans trans_mat_rep_block_size_sym(2)\n  by (metis dual_blocks_len dual_is_ordered_inc_sys inc_mat_dim_row mat_rep_num_N_row \n      ordered_incidence_system.mat_block_size_N_col points_list_length size_mset) \n\n(* Old Counting proof \nproof -\n  have 1: \"card (\\<B>s* ! j) = card {y . y < length \\<B>s \\<and> (\\<V>s ! j) \\<in> \\<B>s ! y}\"\n    using assms dual_blocks_len dual_point_block points_list_length by force\n  also have 2: \"... = card {y \\<in> {0..<length \\<B>s} . (\\<V>s ! j) \\<in> \\<B>s ! y}\" by simp\n  also have \"... = size (mset_set {y \\<in> {0..<length \\<B>s} . (\\<V>s ! j) \\<in> \\<B>s ! y})\" by simp\n  also have \"... = size {# y \\<in># mset_set {0..< length \\<B>s} . (\\<V>s ! j) \\<in> \\<B>s ! y #}\" \n    using filter_mset_mset_set by simp \n  finally have \"card (\\<B>s* ! j) = size {# bl \\<in># \\<B> . (\\<V>s ! j) \\<in> bl #}\"\n    by (metis 1 2 filter_size_blocks_eq_card_indexes lessThan_atLeast0 size_mset) \n  thus ?thesis by (simp add: point_replication_number_def)\nqed\n*)\n\nlemma dual_blocks_size_is_rep_obtain: \n  assumes \"bl \\<in># dual_blocks \\<V> \\<B>s\"\n  obtains x where \"x \\<in> \\<V>\" and \"card bl = \\<B> rep x\"\nproof -\n  obtain j where jlt1: \"j < length \\<B>s*\" and bleq: \"\\<B>s* ! j = bl\"\n    by (metis assms dual_blocks_ordered_eq in_mset_conv_nth) \n  then have jlt: \"j < \\<v>\"\n    by (simp add: dual_blocks_len points_list_length) \n  let ?x = \"\\<V>s ! j\"\n  have xin: \"?x \\<in> \\<V>\" using jlt\n    by (simp add: valid_points_index) \n  have \"card bl = \\<B> rep ?x\" using dual_blocks_size_is_rep jlt1 bleq by auto\n  thus ?thesis using xin that by auto \nqed\n\nlemma dual_blocks_rep_is_size:\n  assumes \"i < length \\<B>s\"\n  shows \"(mset \\<B>s*) rep i = card (\\<B>s ! i)\"\nproof -\n  have \"[0..<length \\<B>s] ! i = i\" using assms by simp\n  then have \"(mset \\<B>s*) rep i = mat_rep_num ordered_dual_sys.N i\" \n    using ordered_dual_sys.mat_rep_num_N_row assms length_upt minus_nat.diff_0 \n      ordered_dual_sys.points_list_length by presburger \n  also have \"... = mat_block_size (ordered_dual_sys.N)\\<^sup>T i\" using dual_incidence_mat_eq_trans \n    trans_mat_rep_block_size_sym(2) by (metis assms inc_mat_dim_col index_transpose_mat(2))\n  finally show ?thesis using dual_incidence_mat_eq_trans_rev\n    by (metis assms blocks_list_length mat_block_size_N_col)\nqed\n\n(* Counting Proof\nproof -\n  have \"(mset \\<B>s* ) rep i = size {# bl \\<in># (mset \\<B>s* ) . i \\<in> bl #}\" \n    by (simp add: point_replication_number_def)\n  also have 1: \"... = size {# bl \\<in># {# {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y} . x \\<in># (mset_set \\<V>)#} . i \\<in> bl #}\" \n    using dual_blocks_ordered_eq dual_blocks_def by metis \n  also have \"... = size (filter_mset (\\<lambda> bl . i \\<in> bl) \n      (image_mset (\\<lambda> x . {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y}) (mset_set \\<V>)))\" by simp\n  finally have \"(mset \\<B>s* ) rep i = size (image_mset (\\<lambda> x . {y . y < length \\<B>s \\<and> x \\<in> \\<B>s ! y}) \n      (filter_mset (\\<lambda> bl . i \\<in> {y . y < length \\<B>s \\<and> bl \\<in> \\<B>s ! y}) (mset_set \\<V>)))\"\n    using filter_mset_image_mset by (metis 1 ordered_dual_sys.point_rep_number_alt_def) \n  then have \"(mset \\<B>s* ) rep i = size (filter_mset (\\<lambda> bl . i \\<in> {y . y < length \\<B>s \\<and> bl \\<in> \\<B>s ! y}) \n      (mset_set \\<V>))\"\n    by fastforce\n  then have \"(mset \\<B>s* ) rep i = size (filter_mset (\\<lambda> bl . bl \\<in> \\<B>s ! i) (mset_set \\<V>))\" \n    using assms by simp\n  then have \"(mset \\<B>s* ) rep i =  card {x \\<in> \\<V> . x \\<in> (\\<B>s ! i)}\" by simp\n  thus ?thesis using assms block_size_alt by auto\nqed\n*)\n\nlemma dual_blocks_inter_index: \n  assumes \"j1 < length \\<B>s*\" \"j2 < length \\<B>s*\"\n  shows \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = points_index \\<B> {\\<V>s ! j1, \\<V>s ! j2}\"\nproof -\n  have assms2: \"j1 < \\<v>\" \"j2 < \\<v>\" using assms\n    by (simp_all add: dual_blocks_len points_list_length) \n  have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = mat_inter_num (ordered_dual_sys.N) j1 j2\"\n    by (simp add: assms(1) assms(2) ordered_dual_sys.mat_inter_num_conv)\n  also have \"... = mat_point_index N {j1, j2}\" using dual_incidence_mat_eq_trans_rev trans_mat_point_index_inter_sym(2)\n    by (metis assms inc_mat_dim_col)\n  finally show ?thesis using assms2 incidence_mat_two_index\n    by presburger\nqed\n(* Counting Proof \n  have fin: \"finite {0..<length \\<B>s}\"\n    by auto \n  have j1lt: \"j1 < \\<v>\" using assms\n    using dual_blocks_len points_list_length by auto \n  have j2lt: \"j2 < \\<v>\" using assms dual_blocks_len points_list_length by auto\n  have iff: \"\\<And> x. (x \\<in>(\\<B>s* ! j1) \\<and> x \\<in> (\\<B>s* ! j2)) \\<longleftrightarrow> (\\<V>s ! j1 \\<in> \\<B>s ! x \\<and> x < \\<b> \\<and> \\<V>s ! j2 \\<in> \\<B>s ! x)\" \n    by (auto simp add: dual_blocks_elem_iff j1lt j2lt)\n  have pi: \"points_index \\<B> {\\<V>s ! j1, \\<V>s ! j2} = size {# bl \\<in># \\<B> . \\<V>s !j1 \\<in> bl \\<and> \\<V>s ! j2 \\<in> bl#}\" \n    by (auto simp add: points_index_def)\n  have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = card ({x . x <length \\<B>s \\<and> x \\<in> (\\<B>s* ! j1) \\<and> x \\<in> (\\<B>s* ! j2)})\"\n    apply (auto simp add: intersection_number_def)\n    by (smt (verit) Collect_cong Int_Collect blocks_list_length dual_blocks_elem_iff inf.idem inf_set_def j2lt mem_Collect_eq)\n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = card ({x . x <length \\<B>s \\<and> \\<V>s ! j1 \\<in> \\<B>s ! x \\<and> \\<V>s ! j2 \\<in> \\<B>s ! x})\" using iff\n    size_mset by (smt (verit, best) Collect_cong) \n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = size (mset_set {x \\<in> {0..<length \\<B>s}. \\<V>s ! j1 \\<in> \\<B>s ! x \\<and> \\<V>s ! j2 \\<in> \\<B>s ! x})\" by simp\n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = size ({#x \\<in># mset_set {0..<length \\<B>s}. \\<V>s ! j1 \\<in> \\<B>s ! x \\<and> \\<V>s ! j2 \\<in> \\<B>s ! x#})\" using fin by simp\n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = size (filter_mset (\\<lambda> x . \\<V>s ! j1 \\<in> \\<B>s ! x \\<and> \\<V>s ! j2 \\<in> \\<B>s ! x) (mset_set {0..<length \\<B>s}))\" by simp\n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = size (image_mset (\\<lambda> i. \\<B>s ! i) (filter_mset (\\<lambda> x . \\<V>s ! j1 \\<in> \\<B>s ! x \\<and> \\<V>s ! j2 \\<in> \\<B>s ! x) (mset_set {0..<length \\<B>s})))\"\n    by simp\n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = size (filter_mset (\\<lambda> x . \\<V>s ! j1 \\<in> x \\<and> \\<V>s ! j2 \\<in> x) (image_mset (\\<lambda> i. \\<B>s ! i) (mset_set {0..<length \\<B>s})))\"\n    by (simp add: filter_mset_image_mset)\n  then have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = size {# bl \\<in># \\<B> . \\<V>s !j1 \\<in> bl \\<and> \\<V>s ! j2 \\<in> bl#}\"\n    by (metis blocks_list_length blocks_mset_image lessThan_atLeast0) \n  thus ?thesis using pi by simp\nqed\n*)\n\nlemma dual_blocks_points_index_inter: \n  assumes \"i1 < \\<b>\" \"i2 < \\<b>\"\n  shows \"(mset \\<B>s*) index {i1, i2} = (\\<B>s ! i1) |\\<inter>| (\\<B>s ! i2)\"\nproof -\n  have \"(mset \\<B>s*) index {i1, i2} = mat_point_index (ordered_dual_sys.N) {i1, i2}\"\n    using assms(1) assms(2) blocks_list_length ord_dual_blocks_v ordered_dual_sys.dim_row_is_v \n      ordered_dual_sys.incidence_mat_two_index ordered_dual_sys.mat_ord_inc_sys_point by presburger \n  also have \"... = mat_inter_num N i1 i2\" using dual_incidence_mat_eq_trans trans_mat_point_index_inter_sym(1)\n    by (metis assms(1) assms(2) dual_incidence_mat_eq_trans_rev ord_dual_blocks_v ordered_dual_sys.dim_row_is_v) \n  finally show ?thesis using mat_inter_num_conv\n    using assms(1) assms(2) by auto \nqed\n\n(* Counting Proof \nproof - \n  have \"\\<And> j . j \\<in># mset_set {0..<length \\<B>s*} \\<Longrightarrow> j < \\<v>\"\n    by (metis atLeastLessThan_iff atLeastLessThan_upt dual_blocks_len mset_upt points_list_length set_mset_mset) \n  then have iff: \"\\<And> j i. j \\<in># mset_set {0..<length \\<B>s*} \\<Longrightarrow> i < \\<b> \\<Longrightarrow> i \\<in> (\\<B>s* ! j) \\<longleftrightarrow> (\\<V>s ! j) \\<in> (\\<B>s ! i)\" \n    using assms dual_incidence_iff2 by simp \n  then have iff2: \"\\<And> j . j \\<in># mset_set {0..<length \\<B>s*} \\<Longrightarrow> i1 \\<in> (\\<B>s* ! j) \\<and> i2 \\<in> (\\<B>s* ! j) \\<longleftrightarrow> (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)\"\n    using assms by auto\n  have ss2: \"(\\<B>s ! i2) \\<subseteq> \\<V>\" using wellformed assms by auto\n  then have ss: \"{x . x \\<in> (\\<B>s ! i1) \\<and> x \\<in> (\\<B>s ! i2)} \\<subseteq> \\<V>\"\n    by auto \n  then have inter:  \"(\\<B>s ! i1) |\\<inter>| (\\<B>s ! i2) = card {x \\<in> \\<V>. x \\<in> (\\<B>s ! i1) \\<and> x \\<in> (\\<B>s ! i2)}\"\n    using intersection_number_def by (metis Collect_conj_eq Collect_mem_eq Int_absorb1)\n  have inj: \"inj_on (\\<lambda> j. \\<V>s ! j) {j \\<in> {0..<length \\<V>s} . (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)}\"\n    by (simp add: inj_on_nth distinct) \n  have init: \"(mset \\<B>s* ) index {i1, i2} = size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#}\"\n    by (simp add: points_index_def)\n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = size {#j \\<in># mset_set {0..<length \\<B>s*} . i1 \\<in> (\\<B>s* ! j) \\<and> i2 \\<in> (\\<B>s* ! j)#}\"\n  proof - \n    have \"size {#j \\<in># mset_set {0..<length \\<B>s*} . i1 \\<in> (\\<B>s* ! j) \\<and> i2 \\<in> (\\<B>s* ! j)#} \n      = size (filter_mset (\\<lambda> j. i1 \\<in> (\\<B>s* ! j) \\<and> i2 \\<in> (\\<B>s* ! j)) (mset_set {0..<length \\<B>s*})) \" by simp\n    also have s1: \"... = size (image_mset (\\<lambda>x . \\<B>s* ! x) (filter_mset (\\<lambda> j. i1 \\<in> (\\<B>s* ! j) \\<and> i2 \\<in> (\\<B>s* ! j)) (mset_set {0..<length \\<B>s*})))\" by fastforce\n    also have s2: \"... = size (filter_mset (\\<lambda> j. i1 \\<in> j \\<and> i2 \\<in> j) (image_mset (\\<lambda>x . \\<B>s* ! x) (mset_set {0..<length \\<B>s*})))\"\n      by (simp add: filter_mset_image_mset) \n    finally have \"size {#j \\<in># mset_set {0..<length \\<B>s*} . i1 \\<in> (\\<B>s* ! j) \\<and> i2 \\<in> (\\<B>s* ! j)#} = size (filter_mset (\\<lambda> j. i1 \\<in> j \\<and> i2 \\<in> j) (mset \\<B>s* ))\"\n      using dual_blocks_list_index_img s2 s1 by presburger \n    thus ?thesis by simp\n  qed\n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = size {#j \\<in># mset_set {0..<length \\<B>s*} . (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)#}\" using iff2\n    by (smt (verit, ccfv_SIG) filter_mset_cong) \n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = \n    card ({j \\<in> {0..<length \\<B>s*} . (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)})\" by simp\n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = \n    card ({j \\<in> {0..<length \\<V>s} . (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)})\" using dual_blocks_len by presburger \n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = \n    card (image (\\<lambda> j. \\<V>s ! j) {j \\<in> {0..<length \\<V>s} . (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)})\"  \n    using inj card_image[of \"(\\<lambda> j. \\<V>s ! j)\" \"{j \\<in> {0..<length \\<V>s} . (\\<V>s ! j) \\<in> (\\<B>s ! i1) \\<and> (\\<V>s ! j) \\<in> (\\<B>s ! i2)}\"] by simp\n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = \n    card {j \\<in> image (\\<lambda> j. \\<V>s ! j) {0..<length \\<V>s}. j \\<in> (\\<B>s ! i1) \\<and> j \\<in> (\\<B>s ! i2)}\" \n    using Compr_image_eq[of \"(\\<lambda> j. \\<V>s ! j)\" \"{0..<length \\<V>s}\" \"(\\<lambda> j . j \\<in> (\\<B>s ! i1) \\<and> j \\<in> (\\<B>s ! i2))\"] by simp\n  then have \"size {#bl \\<in># (mset \\<B>s* ) . i1 \\<in> bl \\<and> i2 \\<in> bl#} = \n    card {j \\<in> \\<V>. j \\<in> (\\<B>s ! i1) \\<and> j \\<in> (\\<B>s ! i2)}\"\n    using lessThan_atLeast0 points_list_length points_set_index_img by presburger \n  thus ?thesis using init inter by simp\nqed*)\nend \n\nsubsection \\<open>Dual Properties for Design sub types \\<close>\ncontext ordered_design\nbegin\n\nlemma dual_is_design: \n  assumes \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\" \\<comment> \\<open> Required to ensure no blocks are empty \\<close>\n  shows \"design {0..<length \\<B>s} (dual_blocks \\<V> \\<B>s)\"\n  using dual_blocks_nempty assms by (unfold_locales) (simp) \nend\n\ncontext ordered_proper_design\nbegin\n\nlemma dual_sys_b_non_zero: \"dual_sys.\\<b> \\<noteq> 0\"\n  using v_non_zero dual_blocks_b by auto\n\nlemma dual_is_proper_design: \n  assumes \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\"  \\<comment> \\<open> Required to ensure no blocks are empty \\<close>\n  shows \"proper_design {0..<length \\<B>s} (dual_blocks \\<V> \\<B>s)\"\n  using dual_blocks_nempty dual_sys_b_non_zero assms by (unfold_locales) (simp_all)\n\nend\n\ncontext ordered_block_design \nbegin\n\nlemma dual_blocks_const_rep: \"i \\<in> {0..<length \\<B>s} \\<Longrightarrow> (mset \\<B>s*) rep i = \\<k>\"\n  using dual_blocks_rep_is_size uniform by (metis atLeastLessThan_iff nth_mem_mset) \n\nlemma dual_blocks_constant_rep_design:\n  assumes \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\"\n  shows \"constant_rep_design {0..<length \\<B>s} (dual_blocks \\<V> \\<B>s) \\<k>\"\nproof -\n  interpret des: proper_design \"{0..<length \\<B>s}\" \"(dual_blocks \\<V> \\<B>s)\"\n    using dual_is_proper_design assms by simp\n  show ?thesis using dual_blocks_const_rep dual_blocks_ordered_eq by (unfold_locales) (simp)\nqed\n\n\nend\n\ncontext ordered_constant_rep\nbegin\n\nlemma dual_blocks_const_size:  \"j < length \\<B>s* \\<Longrightarrow> card (\\<B>s* ! j) = \\<r>\"\n  using dual_blocks_rep_is_size dual_blocks_len dual_blocks_size_is_rep by fastforce \n\nlemma dual_is_block_design: \"block_design {0..<length \\<B>s} (dual_blocks \\<V> \\<B>s) \\<r>\"\nproof -\n  have \"\\<r> > 0\" by (simp add: r_gzero)\n  then have \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\" using rep_number by simp\n  then interpret pdes: proper_design \"{0..<length \\<B>s}\" \"(dual_blocks \\<V> \\<B>s)\" \n    using dual_is_proper_design by simp\n  have \"\\<And> bl. bl \\<in># dual_blocks \\<V> \\<B>s \\<Longrightarrow> card bl = \\<r>\" \n    using dual_blocks_const_size \n    by (metis dual_blocks_ordered_eq in_set_conv_nth set_mset_mset)\n  thus ?thesis by (unfold_locales) (simp)\nqed\n\nend\n\ncontext ordered_pairwise_balance \nbegin\n\nlemma dual_blocks_const_intersect: \n  assumes \"j1 < length \\<B>s*\" \"j2 < length \\<B>s*\"\n  assumes \"j1 \\<noteq> j2\"\n  shows \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = \\<Lambda>\"\nproof -\n  have \"\\<V>s ! j1 \\<noteq> \\<V>s ! j2\" using assms(3)\n    using assms(1) assms(2) distinct dual_blocks_len nth_eq_iff_index_eq by auto \n  then have c: \"card {\\<V>s ! j1, \\<V>s ! j2} = 2\"\n    using card_2_iff by blast \n  have ss: \"{\\<V>s ! j1, \\<V>s ! j2} \\<subseteq> \\<V>\" using assms points_list_length\n    using dual_blocks_len by auto \n  have \"(\\<B>s* ! j1) |\\<inter>| (\\<B>s* ! j2) = points_index \\<B> {\\<V>s ! j1, \\<V>s ! j2}\"\n    using dual_blocks_inter_index assms by simp\n  thus ?thesis using ss c balanced\n    by blast \nqed\n\nlemma dual_is_const_intersect_des: \n  assumes \"\\<Lambda> > 0\"\n  shows \"const_intersect_design {0..<(length \\<B>s)} (dual_blocks \\<V> \\<B>s) \\<Lambda>\"\nproof -\n  have \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x \\<ge> \\<Lambda>)\" using const_index_lt_rep by simp\n  then have \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\" using assms\n    by (metis gr_zeroI le_zero_eq) \n  then interpret pd: proper_design \"{0..<(length \\<B>s)}\" \"(dual_blocks \\<V> \\<B>s)\" \n    using dual_is_proper_design by (simp) \n  show ?thesis proof (unfold_locales)\n    fix b1 b2\n    assume b1in: \"b1 \\<in># dual_blocks \\<V> \\<B>s\"\n    assume b2in:  \"b2 \\<in># remove1_mset b1 (dual_blocks \\<V> \\<B>s)\"\n    obtain j1 where b1eq: \"b1 = \\<B>s* ! j1\" and j1lt: \"j1 < length \\<B>s*\" using b1in\n      by (metis dual_blocks_ordered_eq in_set_conv_nth set_mset_mset) \n    obtain j2 where b2eq: \"b2 = \\<B>s* ! j2\" and j2lt: \"j2 < length \\<B>s*\" and \"j1 \\<noteq> j2\" \n      using b2in index_remove1_mset_ne\n      by (metis (mono_tags) b1eq dual_blocks_ordered_eq j1lt nth_mem set_mset_mset) \n    then show \"b1 |\\<inter>| b2 = \\<Lambda>\" \n      using dual_blocks_const_intersect b1eq b2eq j1lt j2lt by simp \n  qed\nqed\n\n\nlemma dual_is_simp_const_inter_des: \n  assumes \"\\<Lambda> > 0\"\n  assumes \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> incomplete_block bl\"  \n  shows \"simple_const_intersect_design {0..<(length \\<B>s)} (dual_blocks \\<V> \\<B>s) \\<Lambda>\"\nproof -\n  interpret d: const_intersect_design \"{0..<(length \\<B>s)}\" \"(dual_blocks \\<V> \\<B>s)\"  \"\\<Lambda>\"\n    using assms dual_is_const_intersect_des by simp\n  \\<comment> \\<open> Show that m < block size for all blocks \\<close>\n  have \"\\<And> x. x \\<in> \\<V> \\<Longrightarrow> \\<Lambda> < \\<B> rep x\" using assms incomplete_index_strict_lt_rep\n    by blast \n  then have \"\\<And> bl. bl \\<in># (dual_blocks \\<V> \\<B>s) \\<Longrightarrow> \\<Lambda> < card bl\"\n    by (metis dual_blocks_size_is_rep_obtain) \n  then interpret s: simple_design \"{0..<(length \\<B>s)}\" \"(dual_blocks \\<V> \\<B>s)\" \n    using d.simple_const_inter_block_size by simp\n  show ?thesis by (unfold_locales)\nqed\nend\n\ncontext ordered_const_intersect_design\nbegin\n\nlemma dual_is_balanced: \n  assumes \"ps \\<subseteq> {0..<length \\<B>s}\"\n  assumes \"card ps = 2\"\n  shows \"(dual_blocks \\<V> \\<B>s) index ps = \\<m>\"\nproof -\n  obtain i1 i2 where psin: \"ps = {i1, i2}\" and neq: \"i1 \\<noteq> i2\" using assms\n    by (meson card_2_iff) \n  then have lt: \"i1 < \\<b>\" using assms \n    by (metis atLeastLessThan_iff blocks_list_length insert_subset) \n  have lt2: \"i2 < \\<b>\" using assms psin\n    by (metis atLeastLessThan_iff blocks_list_length insert_subset) \n  then have inter: \"(dual_blocks \\<V> \\<B>s) index ps = (\\<B>s ! i1) |\\<inter>| (\\<B>s ! i2)\" using dual_blocks_points_index_inter neq lt\n    using dual_blocks_ordered_eq psin by presburger\n  have inb1: \"(\\<B>s ! i1) \\<in># \\<B>\"\n    using lt by auto \n  have inb2: \"(\\<B>s ! i2) \\<in># (\\<B> - {#(\\<B>s ! i1)#})\" using lt2 neq blocks_index_ne_belong\n    by (metis blocks_list_length lt) \n  thus ?thesis using const_intersect inb1 inb2 inter by blast \nqed\n\nlemma dual_is_pbd: \n  assumes \"(\\<And> x . x \\<in> \\<V> \\<Longrightarrow> \\<B> rep x > 0)\"\n  assumes \"\\<b> \\<ge> 2\"\n  shows \"pairwise_balance {0..<(length \\<B>s)} (dual_blocks \\<V> \\<B>s) \\<m>\"\nproof -\n  interpret pd: proper_design \"{0..<(length \\<B>s)}\" \"(dual_blocks \\<V> \\<B>s)\" \n    using dual_is_proper_design\n    by (simp add: assms) \n  show ?thesis proof (unfold_locales)\n    show \"(1 ::nat) \\<le> 2\" by simp\n    then show \"2 \\<le> dual_sys.\\<v>\" using  assms(2)\n      by fastforce \n    show \"\\<And>ps. ps \\<subseteq> {0..<length \\<B>s} \\<Longrightarrow> card ps = 2 \\<Longrightarrow> dual_blocks \\<V> \\<B>s index ps = \\<m>\"\n      using dual_is_balanced by simp\n  qed\nqed\n\nend\n\ncontext ordered_sym_bibd\nbegin\n\nlemma dual_is_balanced: \n  assumes \"ps \\<subseteq> {0..<length \\<B>s}\"\n  assumes \"card ps = 2\"\n  shows \"(dual_blocks \\<V> \\<B>s) index ps = \\<Lambda>\"\nproof -\n  obtain i1 i2 where psin: \"ps = {i1, i2}\" and neq: \"i1 \\<noteq> i2\" \n    using assms by (meson card_2_iff) \n  then have lt: \"i1 < \\<b>\" using assms \n    by (metis atLeastLessThan_iff blocks_list_length insert_subset) \n  have lt2: \"i2 < \\<b>\" using assms psin\n    by (metis atLeastLessThan_iff blocks_list_length insert_subset) \n  then have inter: \"(dual_blocks \\<V> \\<B>s) index ps = (\\<B>s ! i1) |\\<inter>| (\\<B>s ! i2)\" \n    using dual_blocks_points_index_inter neq lt dual_blocks_ordered_eq psin by presburger\n  have inb1: \"(\\<B>s ! i1) \\<in># \\<B>\"\n    using lt by auto \n  have inb2: \"(\\<B>s ! i2) \\<in># (\\<B> - {#(\\<B>s ! i1)#})\" using lt2 neq blocks_index_simp_unique\n    by (metis blocks_list_length in_remove1_mset_neq lt valid_blocks_index) \n  thus ?thesis using sym_block_intersections_index inb1 inter by blast\nqed\n\nlemma dual_bibd: \"bibd {0..<(length \\<B>s)} (dual_blocks \\<V> \\<B>s) \\<r> \\<Lambda>\"\nproof -\n  interpret block: block_design \"{0..<(length \\<B>s)}\" \"(dual_blocks \\<V> \\<B>s)\" \\<r> \n    using dual_is_block_design by simp\n  show ?thesis proof (unfold_locales)\n    show \"\\<r> < dual_sys.\\<v>\"\n      using dual_blocks_v incomplete symmetric_condition_1 symmetric_condition_2 by presburger \n    show \"(1 ::nat) \\<le> 2\" by simp\n    have \"\\<v> \\<ge> 2\"\n      by (simp add: t_lt_order) \n    then have \"\\<b> \\<ge> 2\" using local.symmetric by auto \n    then show \"2 \\<le> dual_sys.\\<v>\" by simp\n    show \"\\<And>ps. ps \\<subseteq> {0..<length \\<B>s} \\<Longrightarrow> card ps = 2 \\<Longrightarrow> dual_blocks \\<V> \\<B>s index ps = \\<Lambda>\"\n      using dual_is_balanced by simp\n    show \"2 \\<le> \\<r>\" using r_ge_two by blast \n  qed\nqed\n\ntext \\<open>The dual of a BIBD must by symmetric \\<close>\n\nlemma dual_bibd_symmetric: \"symmetric_bibd {0..<(length \\<B>s)} (dual_blocks \\<V> \\<B>s) \\<r> \\<Lambda>\"\nproof -\n  interpret bibd: bibd \"{0..<(length \\<B>s)}\" \"(dual_blocks \\<V> \\<B>s)\" \\<r> \\<Lambda>\n    using dual_bibd by simp\n  show ?thesis using dual_blocks_b local.symmetric by (unfold_locales) (simp)\nqed\n\nend\n\nsubsection \\<open>Generalise Dual Concept \\<close>\ntext \\<open>The above formalisation relies on one translation of a dual design. However, any design \nwith an ordering of points and blocks such that the matrix is the transpose of the original is \na dual. The definition below encapsulates this concept. Additionally, we prove an isomorphism\nexists between the generated dual from @{term \"dual_blocks\"} and any design satisfying the is dual\ndefinition\\<close>\n\ncontext ordered_incidence_system \nbegin\n\ndefinition is_dual:: \"'b list \\<Rightarrow> 'b set list \\<Rightarrow> bool\" where\n\"is_dual Vs' Bs' \\<equiv> ordered_incidence_system Vs' Bs' \\<and> (inc_mat_of Vs' Bs' = N\\<^sup>T)\"\n\nlemma is_dualI: \n  assumes \"ordered_incidence_system Vs' Bs'\"\n  assumes \"(inc_mat_of Vs' Bs' = N\\<^sup>T)\"\n  shows \"is_dual Vs' Bs'\"\n  by (auto simp add: is_dual_def assms)\n\nlemma is_dualD1: \n  assumes \"is_dual Vs' Bs'\"\n  shows  \"(inc_mat_of Vs' Bs' = N\\<^sup>T)\"\n  using is_dual_def assms\n  by auto \n\nlemma is_dualD2: \n  assumes \"is_dual Vs' Bs'\"\n  shows  \"ordered_incidence_system Vs' Bs'\"\n  using is_dual_def assms\n  by auto \n\nlemma generated_is_dual: \"is_dual [0..<(length \\<B>s)] \\<B>s*\"\nproof -\n  interpret osys: ordered_incidence_system \"[0..<(length \\<B>s)]\" \"\\<B>s*\" using dual_is_ordered_inc_sys by simp \n  show ?thesis using is_dual_def\n    by (simp add: is_dual_def dual_incidence_mat_eq_trans osys.ordered_incidence_system_axioms) \nqed\n\nlemma is_dual_isomorphism_generated: \n  assumes \"is_dual Vs' Bs'\"\n  shows \"\\<exists> \\<pi>. incidence_system_isomorphism (set Vs') (mset Bs') ({0..<(length \\<B>s)}) (dual_blocks \\<V> \\<B>s) \\<pi>\"\nproof -\n  interpret os2: ordered_incidence_system \"([0..<(length \\<B>s)])\" \"(\\<B>s*)\"\n    by (simp add: dual_is_ordered_inc_sys) \n  interpret os1: ordered_incidence_system Vs' Bs' using assms\n    by (simp add: is_dualD2) \n  interpret tos: two_ordered_sys Vs' Bs' \"([0..<(length \\<B>s)])\" \"(\\<B>s*)\" \n     using assms  ordered_incidence_system_axioms two_ordered_sys.intro\n     by (simp add: is_dualD2 two_ordered_sys.intro dual_is_ordered_inc_sys)\n  have os2V: \"os2.\\<V> = {0..<(length \\<B>s)}\"\n    by auto \n  have os2B: \"os2.\\<B> = dual_blocks \\<V> \\<B>s\"\n    by (simp add: dual_blocks_ordered_eq) \n  have \"os1.N = inc_mat_of Vs' Bs'\" by simp\n  then have \"os2.N = os1.N\"\n    using assms is_dualD1 dual_incidence_mat_eq_trans by fastforce \n  thus ?thesis using tos.equal_inc_mat_isomorphism_ex os2V os2B by auto\nqed\n\ninterpretation ordered_dual_sys: ordered_incidence_system \"[0..<length \\<B>s]\" \"\\<B>s*\"\n  using dual_is_ordered_inc_sys by simp \n\ntext \\<open>Original system is dual of the dual \\<close>\nlemma is_dual_rev: \"ordered_dual_sys.is_dual \\<V>s \\<B>s\"\n  by (simp add: dual_incidence_mat_eq_trans_rev ordered_dual_sys.is_dualI ordered_incidence_system_axioms)\n\nend\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Fishers_Inequality/Dual_Systems.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8774767986961403, "lm_q1q2_score": 0.7559797837268745}}
{"text": "theory Quasi_Order\nimports Main\nbegin\n\nlocale quasi_order =\nfixes qle :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"\\<preceq>\" 60)\nassumes qle_refl[iff]: \"x \\<preceq> x\"\nand qle_trans: \"x \\<preceq> y \\<Longrightarrow> y \\<preceq> z \\<Longrightarrow> x \\<preceq> z\"\nbegin\n\ndefinition in_qle :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infix \"\\<in>\\<^sub>\\<preceq>\" 60) where\n \"x \\<in>\\<^sub>\\<preceq> M \\<equiv> \\<exists>y \\<in> M. x \\<preceq> y\"\n\ndefinition subseteq_qle :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infix \"\\<subseteq>\\<^sub>\\<preceq>\" 60) where\n \"M \\<subseteq>\\<^sub>\\<preceq> N \\<equiv> \\<forall>x \\<in> M. x \\<in>\\<^sub>\\<preceq> N\"\n\ndefinition seteq_qle :: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> bool\" (infix \"=\\<^sub>\\<preceq>\" 60) where\n \"M =\\<^sub>\\<preceq> N  \\<equiv>  M \\<subseteq>\\<^sub>\\<preceq> N \\<and> N \\<subseteq>\\<^sub>\\<preceq> M\"\n\nlemmas \"defs\" = in_qle_def subseteq_qle_def seteq_qle_def\n\nlemma subseteq_qle_refl[simp]: \"M \\<subseteq>\\<^sub>\\<preceq> M\"\nby(auto simp add: subseteq_qle_def in_qle_def)\n\nlemma subseteq_qle_trans: \"A \\<subseteq>\\<^sub>\\<preceq> B \\<Longrightarrow> B \\<subseteq>\\<^sub>\\<preceq> C \\<Longrightarrow> A \\<subseteq>\\<^sub>\\<preceq> C\"\nby (simp add: subseteq_qle_def in_qle_def) (metis qle_trans)\n\nlemma empty_subseteq_qle[simp]: \"{} \\<subseteq>\\<^sub>\\<preceq> A\"\nby (simp add: subseteq_qle_def)\n\nlemma subseteq_qleI2: \"(\\<And>x. x \\<in> M \\<Longrightarrow> \\<exists>y \\<in> N. x \\<preceq> y) \\<Longrightarrow> M \\<subseteq>\\<^sub>\\<preceq> N\"\nby (auto simp add: subseteq_qle_def in_qle_def)\n\nlemma subseteq_qleD2: \"M \\<subseteq>\\<^sub>\\<preceq> N \\<Longrightarrow> x \\<in> M \\<Longrightarrow> \\<exists>y \\<in> N. x \\<preceq> y\"\nby (auto simp add: subseteq_qle_def in_qle_def)\n\nlemma seteq_qle_refl[iff]: \"A =\\<^sub>\\<preceq> A\"\nby (simp add: seteq_qle_def)\n\nlemma seteq_qle_trans: \"A =\\<^sub>\\<preceq> B \\<Longrightarrow> B =\\<^sub>\\<preceq> C \\<Longrightarrow> A =\\<^sub>\\<preceq> C\"\nby (simp add: seteq_qle_def) (metis subseteq_qle_trans)\n\nend\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Flyspeck-Tame/Quasi_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.861538211208597, "lm_q1q2_score": 0.7559797818641714}}
{"text": "(*\n  File:    Pochhammer_Polynomials.thy\n  Author:  Manuel Eberl, TU München\n*)\nsection \\<open>Falling factorial as a polynomial\\<close>\ntheory Pochhammer_Polynomials\nimports\n  Complex_Main\n  \"HOL-Library.Stirling\" \n  \"HOL-Computational_Algebra.Polynomial\" \nbegin\n\ndefinition pochhammer_poly :: \"nat \\<Rightarrow> 'a :: {comm_semiring_1} poly\" where\n  \"pochhammer_poly n = Poly [of_nat (stirling n k). k \\<leftarrow> [0..<Suc n]]\"\n\nlemma pochhammer_poly_code [code abstract]:\n  \"coeffs (pochhammer_poly n) = map of_nat (stirling_row n)\"\n  by (simp add: pochhammer_poly_def stirling_row_def Let_def)\n\nlemma coeff_pochhammer_poly: \"coeff (pochhammer_poly n) k = of_nat (stirling n k)\"\n  by (simp add: pochhammer_poly_def nth_default_def del: upt_Suc)\n\nlemma degree_pochhammer_poly [simp]: \"degree (pochhammer_poly n) = n\"\n  by (simp add: degree_eq_length_coeffs pochhammer_poly_def)\n\nlemma pochhammer_poly_0 [simp]: \"pochhammer_poly 0 = 1\"\n  by (simp add: pochhammer_poly_def)\n\nlemma pochhammer_poly_Suc: \"pochhammer_poly (Suc n) = [:of_nat n,1:] * pochhammer_poly n\"\n  by (cases \"n = 0\") (simp_all add: poly_eq_iff coeff_pochhammer_poly coeff_pCons split: nat.split)\n\nlemma pochhammer_poly_altdef: \"pochhammer_poly n = (\\<Prod>i<n. [:of_nat i,1:])\"\n  by (induction n) (simp_all add: pochhammer_poly_Suc)\n\nlemma eval_pochhammer_poly: \"poly (pochhammer_poly n) k = pochhammer k n\"\n  by (cases n) (auto simp add: pochhammer_poly_altdef poly_prod add_ac lessThan_Suc_atMost \n                               pochhammer_Suc_prod atLeast0AtMost)\n\nlemma pochhammer_poly_Suc':\n    \"pochhammer_poly (Suc n) = pCons 0 (pcompose (pochhammer_poly n) [:1,1:])\"\n  by (simp add: pochhammer_poly_altdef prod.lessThan_Suc_shift pcompose_prod pcompose_pCons add_ac del: prod.lessThan_Suc)\n \nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Linear_Recurrences/Pochhammer_Polynomials.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767778695834, "lm_q2_score": 0.86153820232079, "lm_q1q2_score": 0.7559797657840002}}
{"text": "section \\<open>ListUtilities\\<close>\n\ntext \\<open>\n  \\file{ListUtilities} defines a (proper) prefix relation for lists, and proves some\n  additional lemmata, mostly about lists.\n\\<close>\n\ntheory ListUtilities\nimports Main\nbegin\n\nsubsection \\<open>List Prefixes\\<close>\n\ninductive prefixList ::\n  \"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere\n  \"prefixList [] (x # xs)\"\n| \"prefixList xa xb \\<Longrightarrow> prefixList (x # xa) (x # xb)\"\n\nlemma PrefixListHasTail:\nfixes \n  l1 :: \"'a list\" and\n  l2 :: \"'a list\"\nassumes\n  \"prefixList l1 l2\"\nshows\n  \"\\<exists> l . l2 = l1 @ l \\<and> l \\<noteq> []\"\nusing assms by (induct rule: prefixList.induct, auto)\n\nlemma PrefixListMonotonicity:\nfixes \n  l1 :: \"'a list\" and\n  l2 :: \"'a list\"\nassumes\n  \"prefixList l1 l2\"\nshows\n  \"length l1 < length l2\"\nusing assms by (induct rule: prefixList.induct, auto)\n\nlemma TailIsPrefixList : \nfixes \n  l1 :: \"'a list\" and\n  tail :: \"'a list\"\nassumes \"tail \\<noteq> []\"\nshows \"prefixList l1 (l1 @ tail)\"\nusing assms\nproof (induct l1, auto)\n  have \"\\<exists> x xs . tail = x # xs\"\n    using assms by (metis neq_Nil_conv)\n  thus \"prefixList [] tail\"\n    using assms  by (metis prefixList.intros(1))\nnext\n  fix a l1\n  assume \"prefixList l1 (l1 @ tail)\"\n  thus \"prefixList (a # l1) (a # l1 @ tail)\"\n    by (metis prefixList.intros(2))\nqed\n\nlemma PrefixListTransitive:\nfixes \n  l1 :: \"'a list\" and\n  l2 :: \"'a list\" and\n  l3 :: \"'a list\"\nassumes\n  \"prefixList l1 l2\"\n  \"prefixList l2 l3\"\nshows\n  \"prefixList l1 l3\"\nusing assms\nproof -\n  from assms(1) have \"\\<exists> l12 . l2 = l1 @ l12 \\<and> l12 \\<noteq> []\" \n    using PrefixListHasTail by auto\n  then obtain l12 where Extend1: \"l2 = l1 @ l12 \\<and> l12 \\<noteq> []\" by blast\n  from assms(2) have Extend2: \"\\<exists> l23 . l3 = l2 @ l23 \\<and> l23 \\<noteq> []\" \n    using PrefixListHasTail by auto\n  then obtain l23 where Extend2: \"l3 = l2 @ l23 \\<and> l23 \\<noteq> []\" by blast\n  have \"l3 = l1 @ (l12 @ l23) \\<and> (l12 @ l23) \\<noteq> []\" \n    using Extend1 Extend2 by simp\n  hence \"\\<exists> l . l3 = l1 @ l \\<and> l \\<noteq> []\" by blast\n  thus \"prefixList l1 l3\" using TailIsPrefixList by auto  \nqed\n\nsubsection \\<open>Lemmas for lists and nat predicates\\<close>\n\nlemma NatPredicateTippingPoint:\nfixes \n  n2 Pr\nassumes\n  Min:     \"0 < n2\" and\n  Pr0:     \"Pr 0\" and\n  NotPrN2: \"\\<not>Pr n2\"\nshows\n  \"\\<exists>n<n2. Pr n \\<and> \\<not>Pr (Suc n)\"                       \nproof (rule classical, simp)\n  assume Asm: \"\\<forall>n. Pr n \\<longrightarrow> n < n2 \\<longrightarrow> Pr (Suc n)\"\n  have \"\\<And>n. n < n2 \\<Longrightarrow> Pr n\"\n  proof-\n    fix n\n    show \"n < n2 \\<Longrightarrow> Pr n\"\n    by (induct n, auto simp add: Pr0 Asm)\n  qed\n  hence False\n    using Asm[rule_format, of \"n2 - 1\"] Min NotPrN2 by auto\n  thus ?thesis by auto\nqed\n\nlemma MinPredicate:\nfixes \n  P::\"nat \\<Rightarrow> bool\"\nassumes\n  \"\\<exists> n . P n\"\nshows \n  \"(\\<exists> n0 . (P n0) \\<and> (\\<forall> n' . (P n') \\<longrightarrow> (n' \\<ge> n0)))\"\nusing assms\nby (metis LeastI2_wellorder Suc_n_not_le_n)\n\ntext \\<open>\n  The lemma \\isb{MinPredicate2} describes one case of \\isb{MinPredicate}\n  where the aforementioned smallest element is zero.\n\\<close>\n\nlemma MinPredicate2:\nfixes\n  P::\"nat \\<Rightarrow> bool\"\nassumes\n \"\\<exists> n . P n\"\nshows\n  \"\\<exists> n0 . (P n0) \\<and> (n0 = 0 \\<or> \\<not> P (n0 - 1))\"\nusing assms MinPredicate\nby (metis add_diff_cancel_right' diff_is_0_eq diff_mult_distrib mult_eq_if)\n\ntext \\<open>\n  \\isb{PredicatePairFunction} allows to obtain functions mapping two arguments\n  to pairs from 4-ary predicates which are left-total on their first\n  two arguments.\n\\<close>\n\nlemma PredicatePairFunction: \nfixes\n  P::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\nassumes\n  A1: \"\\<forall>x1 x2 . \\<exists>y1 y2 . (P x1 x2 y1 y2)\"\nshows \n  \"\\<exists>f . \\<forall>x1 x2 . \\<exists>y1 y2 .\n    (f x1 x2) = (y1, y2) \n    \\<and> (P x1 x2 (fst (f x1 x2)) (snd (f x1 x2)))\"\nproof -\n  define P' where \"P' x y = P (fst x) (snd x) (fst y) (snd y)\" for x y\n  hence \"\\<forall>x. \\<exists>y. P' x  y\" using A1 by auto\n  hence \"\\<exists>f. \\<forall>x. P' x (f x)\" by metis\n  then obtain f where \"\\<forall>x. P' x (f x)\" by blast\n  moreover define f' where \"f' x1 x2 = f (x1, x2)\" for x1 x2\n  ultimately have \"\\<forall>x. P' x (f' (fst x) (snd x))\" by auto\n  hence \"\\<exists>f'. \\<forall>x. P' x (f' (fst x) (snd x))\" by blast\n  thus ?thesis using P'_def by auto\nqed           \n\nlemma PredicatePairFunctions2: \nfixes\n  P::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\nassumes\n  A1: \"\\<forall>x1 x2 . \\<exists>y1 y2 . (P x1 x2 y1 y2)\"\nobtains f1 f2  where\n  \"\\<forall>x1 x2 . \\<exists>y1 y2 .\n    (f1 x1 x2) = y1 \\<and> (f2 x1 x2) = y2 \n    \\<and> (P x1 x2 (f1 x1 x2) (f2 x1 x2))\"\nproof (cases thesis, auto)\n  assume ass: \"\\<And>f1 f2. \\<forall>x1 x2. P x1 x2 (f1 x1 x2) (f2 x1 x2) \\<Longrightarrow> False\"\n  obtain f where F: \"\\<forall>x1 x2. \\<exists>y1 y2. f x1 x2 = (y1, y2) \\<and> P x1 x2 (fst (f x1 x2)) (snd (f x1 x2))\"\n    using PredicatePairFunction[OF A1] by blast\n  define f1 where \"f1 x1 x2 = fst (f x1 x2)\" for x1 x2\n  define f2 where \"f2 x1 x2 = snd (f x1 x2)\" for x1 x2\n  show False\n    using ass[of f1 f2] F unfolding f1_def f2_def by auto\nqed\n\nlemma PredicatePairFunctions2Inv: \nfixes\n  P::\"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> bool\"\nassumes\n  A1: \"\\<forall>x1 x2 . \\<exists>y1 y2 . (P x1 x2 y1 y2)\"\nobtains f1 f2  where\n  \"\\<forall>x1 x2 . (P x1 x2 (f1 x1 x2) (f2 x1 x2))\"\nusing PredicatePairFunctions2[OF A1] by auto\n\nlemma SmallerMultipleStepsWithLimit:\nfixes\n  k A limit\nassumes\n  \"\\<forall> n \\<ge> limit . (A (Suc n)) < (A n)\"\nshows\n  \"\\<forall> n \\<ge> limit . (A (n + k)) \\<le> (A n) - k\"\nproof(induct k,auto)\n  fix n k\n  assume IH: \"\\<forall>n\\<ge>limit. A (n + k) \\<le> A n - k\" \"limit \\<le> n\"\n  hence \"A (Suc (n + k)) < A (n + k)\" using assms by simp \n  hence \"A (Suc (n + k)) < A n - k\" using IH by auto\n  thus \"A (Suc (n + k)) \\<le> A n - Suc k\" \n    by (metis Suc_lessI add_Suc_right add_diff_cancel_left' \n       less_diff_conv less_or_eq_imp_le add.commute)\nqed\n\nlemma PrefixSameOnLow:\nfixes\n  l1 l2\nassumes\n  \"prefixList l1 l2\"\nshows\n  \"\\<forall> index < length l1 . l1 ! index = l2 ! index\"\nusing assms\nproof(induct rule: prefixList.induct, auto)\n  fix xa xb ::\"'a list\" and x index\n  assume AssumpProof: \"prefixList xa xb\" \n        \"\\<forall>index < length xa. xa ! index = xb ! index\"\n        \"prefixList l1 l2\" \"index < Suc (length xa)\"\n  show \"(x # xa) ! index = (x # xb) ! index\" using AssumpProof\n  proof(cases \"index = 0\", auto)\n  qed\nqed\n\nlemma KeepProperty:\nfixes\n  P Q low\nassumes\n  \"\\<forall> i \\<ge> low . P i \\<longrightarrow> (P (Suc i) \\<and> Q i)\" \"P low\"\nshows\n  \"\\<forall> i \\<ge> low . Q i\"\nusing assms\nproof(clarify)\n  fix i\n  assume Assump:\n    \"\\<forall>i\\<ge>low. P i \\<longrightarrow> P (Suc i) \\<and> Q i\"\n    \"P low\"\n    \"low \\<le> i\"\n  hence \"\\<forall>i\\<ge>low. P i \\<longrightarrow> P (Suc i)\" by blast\n  hence \"\\<forall> i \\<ge> low . P i\" using Assump(2) by (metis dec_induct)\n  hence \"P i\" using Assump(3) by blast\n  thus \"Q i\" using Assump by blast\nqed\n\nlemma ListLenDrop: \nfixes\n  i la lb\nassumes\n  \"i < length lb\"\n  \"i \\<ge> la\"\nshows\n  \"lb ! i \\<in> set (drop la lb)\" \nusing assms\nby (metis Cons_nth_drop_Suc in_set_member member_rec(1) \n       set_drop_subset_set_drop rev_subsetD)\n\nlemma DropToShift:\nfixes\n  l i list\nassumes\n  \"l + i < length list\"\nshows\n  \"(drop l list) ! i = list ! (l + i)\"\nusing assms\nby (induct l, auto)\n\nlemma SetToIndex:\nfixes\n  a and liste::\"'a list\"\nassumes\n  AssumpSetToIndex: \"a \\<in> set liste\"\nshows\n  \"\\<exists> index < length liste . a = liste ! index\"\nproof -\n  have LenInduct:\n    \"\\<And>xs. \\<forall>ys. length ys < length xs \\<longrightarrow> a \\<in> set ys \n          \\<longrightarrow> (\\<exists>index<length ys. a = ys ! index) \n          \\<Longrightarrow> a \\<in> set xs \\<longrightarrow> (\\<exists>index<length xs. a = xs ! index)\" \n  proof(auto)\n    fix xs\n    assume AssumpLengthInduction: \n      \"\\<forall>ys. length ys < length xs \\<longrightarrow> a \\<in> set ys \n      \\<longrightarrow> (\\<exists>index<length ys. a = ys ! index)\" \"a \\<in> set xs\"\n    have \"\\<exists> x xs' . xs = x#xs'\" using AssumpLengthInduction(2) \n      by (metis ListMem.cases ListMem_iff)\n    then obtain x xs' where XSSplit: \"xs = x#xs'\" by blast\n    hence \"a \\<in> insert x (set xs')\" using set_simps AssumpLengthInduction \n      by simp\n    hence \"a = x \\<or> a \\<in> set xs'\" by simp\n    thus \"\\<exists>index<length xs. a = xs ! index\"\n    proof(cases \"a = x\",auto)\n      show \"\\<exists>index<length xs. x = xs ! index\" using XSSplit by auto\n    next\n      assume AssumpCases: \"a \\<in> set xs'\" \"a \\<noteq> x\"\n      have \"length xs' < length xs\" using XSSplit by simp\n      hence \"\\<exists>index<length xs'. a = xs' ! index\" \n        using AssumpLengthInduction(1) AssumpCases(1) by simp\n      thus \"\\<exists>index<length xs. a = xs ! index\" using XSSplit by auto\n    qed\n  qed\n  thus \"\\<exists> index < length liste . a = liste ! index\" \n    using length_induct[of \n      \"\\<lambda>l. a \\<in> set l \\<longrightarrow> (\\<exists> index < length l . a = l ! index)\" \"liste\"] \n    AssumpSetToIndex by blast\nqed\n\nlemma DropToIndex:\nfixes\n  a::\"'a\" and l liste \nassumes\n  AssumpDropToIndex: \"a \\<in> set (drop l liste)\"\nshows\n  \"\\<exists> i \\<ge> l . i < length liste \\<and> a = liste ! i\"\nproof-\n  have \"\\<exists> index < length (drop l liste) . a = (drop l liste) ! index\"\n    using AssumpDropToIndex SetToIndex[of \"a\" \"drop l liste\"] by blast\n  then obtain index where Index: \"index < length (drop l liste)\" \n    \"a = (drop l liste) ! index\" by blast\n  have \"l + index < length liste\" using Index(1) \n    by (metis length_drop less_diff_conv add.commute)\n  hence \"a = liste ! (l + index)\" \n    using DropToShift[of \"l\" \"index\"] Index(2) by blast\n  thus \"\\<exists>i\\<ge>l. i < length liste \\<and> a = liste ! i\" \n    by (metis \\<open>l + index < length liste\\<close> le_add1)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/FLP/ListUtilities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872046026642944, "lm_q2_score": 0.8519528076067262, "lm_q1q2_score": 0.7558564521614556}}
{"text": "theory ex_sort\n  imports Main\nbegin\n  \nvalue \"[1::nat, 3,2]\"\n\n(*\nfun my_sort::\"nat list \\<Rightarrow> nat list\" where\n  \"my_sort [] = []\"|\n  \"my_sort [x] = [x]\"|\n  \"my_sort [x1,x2] = (if (x1 < x2) then ([x1,x2]) else ([x2,x1]))\"|\n  \"my_sort (x1#x2#xs) = (if (x1 < x2) then (x1#(my_sort (x2#xs))) else (my_sort (x2#x1#xs)))\"\n*)\n    \nfun myInsert::\"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\" where\n  \"myInsert x [] = [x]\"|\n  \"myInsert x (y#ys) = (if (x\\<le>y) then (x#y#ys) else (y#(myInsert x ys)))\"\n  \nfun mySort::\"nat list \\<Rightarrow> nat list\" where\n  \"mySort [] = []\"|\n  \"mySort (x#xs) = myInsert x (mySort xs)\"\n  \nvalue \"mySort [3,2,1]\"\n  \nlemma ms: \"\\<forall>i j. i<j \\<longrightarrow> j<length xs \\<longrightarrow> \\<not>(mySort xs) ! 1 > (mySort xs) ! 1\"\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by blast\nqed\n  \nlemma subls: \"Suc (length xs) = length (myInsert a xs)\"\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by simp\nqed\n  \nlemma ls: \"length xs = length (mySort xs)\"\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case by (simp add:subls)\nqed\n    \n(*export_code mySort in OCaml*)\n\n  \nend\n  ", "meta": {"author": "Caterpie-poke", "repo": "Isabelle", "sha": "cf7507d94ac3b7b4bd8f2c0d26045259d77fc6f6", "save_path": "github-repos/isabelle/Caterpie-poke-Isabelle", "path": "github-repos/isabelle/Caterpie-poke-Isabelle/Isabelle-cf7507d94ac3b7b4bd8f2c0d26045259d77fc6f6/2018-summer/ex_sort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.8354835330070838, "lm_q1q2_score": 0.7558206187595404}}
{"text": "(*  Title:      HOL/Computational_Algebra/Normalized_Fraction.thy\n    Author:     Manuel Eberl\n*)\n\ntheory Normalized_Fraction\nimports \n  Main \n  Euclidean_Algorithm\n  Fraction_Field\nbegin\n\ndefinition quot_to_fract :: \"'a :: {idom} \\<times> 'a \\<Rightarrow> 'a fract\" where\n  \"quot_to_fract = (\\<lambda>(a,b). Fraction_Field.Fract a b)\"\n\ndefinition normalize_quot :: \"'a :: {ring_gcd,idom_divide,semiring_gcd_mult_normalize} \\<times> 'a \\<Rightarrow> 'a \\<times> 'a\" where\n  \"normalize_quot = \n     (\\<lambda>(a,b). if b = 0 then (0,1) else let d = gcd a b * unit_factor b in (a div d, b div d))\" \n\nlemma normalize_quot_zero [simp]:\n  \"normalize_quot (a, 0) = (0, 1)\"\n  by (simp add: normalize_quot_def)\n\nlemma normalize_quot_proj:\n  \"fst (normalize_quot (a, b)) = a div (gcd a b * unit_factor b)\"\n  \"snd (normalize_quot (a, b)) = normalize b div gcd a b\" if \"b \\<noteq> 0\"\n  using that by (simp_all add: normalize_quot_def Let_def mult.commute [of _ \"unit_factor b\"] dvd_div_mult2_eq mult_unit_dvd_iff')\n\ndefinition normalized_fracts :: \"('a :: {ring_gcd,idom_divide} \\<times> 'a) set\" where\n  \"normalized_fracts = {(a,b). coprime a b \\<and> unit_factor b = 1}\"\n  \nlemma not_normalized_fracts_0_denom [simp]: \"(a, 0) \\<notin> normalized_fracts\"\n  by (auto simp: normalized_fracts_def)\n\nlemma unit_factor_snd_normalize_quot [simp]:\n  \"unit_factor (snd (normalize_quot x)) = 1\"\n  by (simp add: normalize_quot_def case_prod_unfold Let_def dvd_unit_factor_div\n                mult_unit_dvd_iff unit_factor_mult unit_factor_gcd)\n  \nlemma snd_normalize_quot_nonzero [simp]: \"snd (normalize_quot x) \\<noteq> 0\"\n  using unit_factor_snd_normalize_quot[of x] \n  by (auto simp del: unit_factor_snd_normalize_quot)\n  \nlemma normalize_quot_aux:\n  fixes a b\n  assumes \"b \\<noteq> 0\"\n  defines \"d \\<equiv> gcd a b * unit_factor b\"\n  shows   \"a = fst (normalize_quot (a,b)) * d\" \"b = snd (normalize_quot (a,b)) * d\"\n          \"d dvd a\" \"d dvd b\" \"d \\<noteq> 0\"\nproof -\n  from assms show \"d dvd a\" \"d dvd b\"\n    by (simp_all add: d_def mult_unit_dvd_iff)\n  thus \"a = fst (normalize_quot (a,b)) * d\" \"b = snd (normalize_quot (a,b)) * d\" \"d \\<noteq> 0\"\n    by (auto simp: normalize_quot_def Let_def d_def \\<open>b \\<noteq> 0\\<close>)\nqed\n\nlemma normalize_quotE:\n  assumes \"b \\<noteq> 0\"\n  obtains d where \"a = fst (normalize_quot (a,b)) * d\" \"b = snd (normalize_quot (a,b)) * d\"\n                  \"d dvd a\" \"d dvd b\" \"d \\<noteq> 0\"\n  using that[OF normalize_quot_aux[OF assms]] .\n  \nlemma normalize_quotE':\n  assumes \"snd x \\<noteq> 0\"\n  obtains d where \"fst x = fst (normalize_quot x) * d\" \"snd x = snd (normalize_quot x) * d\"\n                  \"d dvd fst x\" \"d dvd snd x\" \"d \\<noteq> 0\"\nproof -\n  from normalize_quotE[OF assms, of \"fst x\"] guess d .\n  from this show ?thesis unfolding prod.collapse by (intro that[of d])\nqed\n  \nlemma coprime_normalize_quot:\n  \"coprime (fst (normalize_quot x)) (snd (normalize_quot x))\"\n  by (simp add: normalize_quot_def case_prod_unfold div_mult_unit2)\n    (metis coprime_mult_self_right_iff div_gcd_coprime unit_div_mult_self unit_factor_is_unit)\n\nlemma normalize_quot_in_normalized_fracts [simp]: \"normalize_quot x \\<in> normalized_fracts\"\n  by (simp add: normalized_fracts_def coprime_normalize_quot case_prod_unfold)\n\nlemma normalize_quot_eq_iff:\n  assumes \"b \\<noteq> 0\" \"d \\<noteq> 0\"\n  shows   \"normalize_quot (a,b) = normalize_quot (c,d) \\<longleftrightarrow> a * d = b * c\"\nproof -\n  define x y where \"x = normalize_quot (a,b)\" and \"y = normalize_quot (c,d)\" \n  from normalize_quotE[OF assms(1), of a] normalize_quotE[OF assms(2), of c]\n    obtain d1 d2 \n      where \"a = fst x * d1\" \"b = snd x * d1\" \"c = fst y * d2\" \"d = snd y * d2\" \"d1 \\<noteq> 0\" \"d2 \\<noteq> 0\"\n    unfolding x_def y_def by metis\n  hence \"a * d = b * c \\<longleftrightarrow> fst x * snd y = snd x * fst y\" by simp\n  also have \"\\<dots> \\<longleftrightarrow> fst x = fst y \\<and> snd x = snd y\"\n    by (intro coprime_crossproduct') (simp_all add: x_def y_def coprime_normalize_quot)\n  also have \"\\<dots> \\<longleftrightarrow> x = y\" using prod_eqI by blast\n  finally show \"x = y \\<longleftrightarrow> a * d = b * c\" ..\nqed\n\nlemma normalize_quot_eq_iff':\n  assumes \"snd x \\<noteq> 0\" \"snd y \\<noteq> 0\"\n  shows   \"normalize_quot x = normalize_quot y \\<longleftrightarrow> fst x * snd y = snd x * fst y\"\n  using assms by (cases x, cases y, hypsubst) (subst normalize_quot_eq_iff, simp_all)\n\nlemma normalize_quot_id: \"x \\<in> normalized_fracts \\<Longrightarrow> normalize_quot x = x\"\n  by (auto simp: normalized_fracts_def normalize_quot_def case_prod_unfold)\n\nlemma normalize_quot_idem [simp]: \"normalize_quot (normalize_quot x) = normalize_quot x\"\n  by (rule normalize_quot_id) simp_all\n\nlemma fractrel_iff_normalize_quot_eq:\n  \"fractrel x y \\<longleftrightarrow> normalize_quot x = normalize_quot y \\<and> snd x \\<noteq> 0 \\<and> snd y \\<noteq> 0\"\n  by (cases x, cases y) (auto simp: fractrel_def normalize_quot_eq_iff)\n  \nlemma fractrel_normalize_quot_left:\n  assumes \"snd x \\<noteq> 0\"\n  shows   \"fractrel (normalize_quot x) y \\<longleftrightarrow> fractrel x y\"\n  using assms by (subst (1 2) fractrel_iff_normalize_quot_eq) auto\n\nlemma fractrel_normalize_quot_right:\n  assumes \"snd x \\<noteq> 0\"\n  shows   \"fractrel y (normalize_quot x) \\<longleftrightarrow> fractrel y x\"\n  using assms by (subst (1 2) fractrel_iff_normalize_quot_eq) auto\n\n  \nlift_definition quot_of_fract :: \n  \"'a :: {ring_gcd,idom_divide,semiring_gcd_mult_normalize} fract \\<Rightarrow> 'a \\<times> 'a\" \n    is normalize_quot\n  by (subst (asm) fractrel_iff_normalize_quot_eq) simp_all\n  \nlemma quot_to_fract_quot_of_fract [simp]: \"quot_to_fract (quot_of_fract x) = x\"\n  unfolding quot_to_fract_def\nproof transfer\n  fix x :: \"'a \\<times> 'a\" assume rel: \"fractrel x x\"\n  define x' where \"x' = normalize_quot x\"\n  obtain a b where [simp]: \"x = (a, b)\" by (cases x)\n  from rel have \"b \\<noteq> 0\" by simp\n  from normalize_quotE[OF this, of a] guess d .\n  hence \"a = fst x' * d\" \"b = snd x' * d\" \"d \\<noteq> 0\" \"snd x' \\<noteq> 0\" by (simp_all add: x'_def)\n  thus \"fractrel (case x' of (a, b) \\<Rightarrow> if b = 0 then (0, 1) else (a, b)) x\"\n    by (auto simp add: case_prod_unfold)\nqed\n\nlemma quot_of_fract_quot_to_fract: \"quot_of_fract (quot_to_fract x) = normalize_quot x\"\nproof (cases \"snd x = 0\")\n  case True\n  thus ?thesis unfolding quot_to_fract_def\n    by transfer (simp add: case_prod_unfold normalize_quot_def)\nnext\n  case False\n  thus ?thesis unfolding quot_to_fract_def by transfer (simp add: case_prod_unfold)\nqed\n\nlemma quot_of_fract_quot_to_fract': \n  \"x \\<in> normalized_fracts \\<Longrightarrow> quot_of_fract (quot_to_fract x) = x\"\n  unfolding quot_to_fract_def by transfer (auto simp: normalize_quot_id)\n\nlemma quot_of_fract_in_normalized_fracts [simp]: \"quot_of_fract x \\<in> normalized_fracts\"\n  by transfer simp\n\nlemma normalize_quotI:\n  assumes \"a * d = b * c\" \"b \\<noteq> 0\" \"(c, d) \\<in> normalized_fracts\"\n  shows   \"normalize_quot (a, b) = (c, d)\"\nproof -\n  from assms have \"normalize_quot (a, b) = normalize_quot (c, d)\"\n    by (subst normalize_quot_eq_iff) auto\n  also have \"\\<dots> = (c, d)\" by (intro normalize_quot_id) fact\n  finally show ?thesis .\nqed\n\nlemma td_normalized_fract:\n  \"type_definition quot_of_fract quot_to_fract normalized_fracts\"\n  by standard (simp_all add: quot_of_fract_quot_to_fract')\n\nlemma quot_of_fract_add_aux:\n  assumes \"snd x \\<noteq> 0\" \"snd y \\<noteq> 0\" \n  shows   \"(fst x * snd y + fst y * snd x) * (snd (normalize_quot x) * snd (normalize_quot y)) =\n             snd x * snd y * (fst (normalize_quot x) * snd (normalize_quot y) +\n             snd (normalize_quot x) * fst (normalize_quot y))\"\nproof -\n  from normalize_quotE'[OF assms(1)] guess d . note d = this\n  from normalize_quotE'[OF assms(2)] guess e . note e = this\n  show ?thesis by (simp_all add: d e algebra_simps)\nqed\n\n\nlocale fract_as_normalized_quot\nbegin\nsetup_lifting td_normalized_fract\nend\n\n\nlemma quot_of_fract_add:\n  \"quot_of_fract (x + y) = \n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y\n      in  normalize_quot (a * d + b * c, b * d))\"\n  by transfer (insert quot_of_fract_add_aux, \n               simp_all add: Let_def case_prod_unfold normalize_quot_eq_iff)\n\nlemma quot_of_fract_uminus:\n  \"quot_of_fract (-x) = (let (a,b) = quot_of_fract x in (-a, b))\"\n  by transfer (auto simp: case_prod_unfold Let_def normalize_quot_def dvd_neg_div mult_unit_dvd_iff)\n\nlemma quot_of_fract_diff:\n  \"quot_of_fract (x - y) = \n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y\n      in  normalize_quot (a * d - b * c, b * d))\" (is \"_ = ?rhs\")\nproof -\n  have \"x - y = x + -y\" by simp\n  also have \"quot_of_fract \\<dots> = ?rhs\"\n    by (simp only: quot_of_fract_add quot_of_fract_uminus Let_def case_prod_unfold) simp_all\n  finally show ?thesis .\nqed\n\nlemma normalize_quot_mult_coprime:\n  assumes \"coprime a b\" \"coprime c d\" \"unit_factor b = 1\" \"unit_factor d = 1\"\n  defines \"e \\<equiv> fst (normalize_quot (a, d))\" and \"f \\<equiv> snd (normalize_quot (a, d))\"\n     and  \"g \\<equiv> fst (normalize_quot (c, b))\" and \"h \\<equiv> snd (normalize_quot (c, b))\"\n  shows   \"normalize_quot (a * c, b * d) = (e * g, f * h)\"\nproof (rule normalize_quotI)\n  from assms have \"gcd a b = 1\" \"gcd c d = 1\"\n    by simp_all\n  from assms have \"b \\<noteq> 0\" \"d \\<noteq> 0\" by auto\n  with assms have \"normalize b = b\" \"normalize d = d\"\n    by (auto intro: normalize_unit_factor_eqI)\n  from normalize_quotE [OF \\<open>b \\<noteq> 0\\<close>, of c] guess k .\n  note k = this [folded \\<open>gcd a b = 1\\<close> \\<open>gcd c d = 1\\<close> assms(3) assms(4)]\n  from normalize_quotE [OF \\<open>d \\<noteq> 0\\<close>, of a] guess l .\n  note l = this [folded \\<open>gcd a b = 1\\<close> \\<open>gcd c d = 1\\<close> assms(3) assms(4)]\n  from k l show \"a * c * (f * h) = b * d * (e * g)\"\n    by (metis e_def f_def g_def h_def mult.commute mult.left_commute)\n  from assms have [simp]: \"unit_factor f = 1\" \"unit_factor h = 1\"\n    by simp_all\n  from assms have \"coprime e f\" \"coprime g h\" by (simp_all add: coprime_normalize_quot)\n  with k l assms(1,2) \\<open>b \\<noteq> 0\\<close> \\<open>d \\<noteq> 0\\<close> \\<open>unit_factor b = 1\\<close> \\<open>unit_factor d = 1\\<close>\n    \\<open>normalize b = b\\<close> \\<open>normalize d = d\\<close>\n  show \"(e * g, f * h) \\<in> normalized_fracts\"\n    by (simp add: normalized_fracts_def unit_factor_mult e_def f_def g_def h_def\n      coprime_normalize_quot dvd_unit_factor_div unit_factor_gcd)\n      (metis coprime_mult_left_iff coprime_mult_right_iff)\nqed (insert assms(3,4), auto)\n\nlemma normalize_quot_mult:\n  assumes \"snd x \\<noteq> 0\" \"snd y \\<noteq> 0\"\n  shows   \"normalize_quot (fst x * fst y, snd x * snd y) = normalize_quot \n             (fst (normalize_quot x) * fst (normalize_quot y),\n              snd (normalize_quot x) * snd (normalize_quot y))\"\nproof -\n  from normalize_quotE'[OF assms(1)] guess d . note d = this\n  from normalize_quotE'[OF assms(2)] guess e . note e = this\n  show ?thesis by (simp_all add: d e algebra_simps normalize_quot_eq_iff)\nqed\n\nlemma quot_of_fract_mult:\n  \"quot_of_fract (x * y) = \n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y;\n          (e,f) = normalize_quot (a,d); (g,h) = normalize_quot (c,b)\n      in  (e*g, f*h))\"\n  by transfer\n     (simp add: split_def Let_def coprime_normalize_quot normalize_quot_mult normalize_quot_mult_coprime)\n  \nlemma normalize_quot_0 [simp]: \n    \"normalize_quot (0, x) = (0, 1)\" \"normalize_quot (x, 0) = (0, 1)\"\n  by (simp_all add: normalize_quot_def)\n  \nlemma normalize_quot_eq_0_iff [simp]: \"fst (normalize_quot x) = 0 \\<longleftrightarrow> fst x = 0 \\<or> snd x = 0\"\n  by (auto simp: normalize_quot_def case_prod_unfold Let_def div_mult_unit2 dvd_div_eq_0_iff)\n  \nlemma fst_quot_of_fract_0_imp: \"fst (quot_of_fract x) = 0 \\<Longrightarrow> snd (quot_of_fract x) = 1\"\n  by transfer auto\n\nlemma normalize_quot_swap:\n  assumes \"a \\<noteq> 0\" \"b \\<noteq> 0\"\n  defines \"a' \\<equiv> fst (normalize_quot (a, b))\" and \"b' \\<equiv> snd (normalize_quot (a, b))\"\n  shows   \"normalize_quot (b, a) = (b' div unit_factor a', a' div unit_factor a')\"\nproof (rule normalize_quotI)\n  from normalize_quotE[OF assms(2), of a] guess d . note d = this [folded assms(3,4)]\n  show \"b * (a' div unit_factor a') = a * (b' div unit_factor a')\"\n    using assms(1,2) d \n    by (simp add: div_unit_factor [symmetric] unit_div_mult_swap mult_ac del: div_unit_factor)\n  have \"coprime a' b'\" by (simp add: a'_def b'_def coprime_normalize_quot)\n  thus \"(b' div unit_factor a', a' div unit_factor a') \\<in> normalized_fracts\"\n    using assms(1,2) d\n    by (auto simp add: normalized_fracts_def ac_simps dvd_div_unit_iff elim: coprime_imp_coprime)\nqed fact+\n  \nlemma quot_of_fract_inverse:\n  \"quot_of_fract (inverse x) = \n     (let (a,b) = quot_of_fract x; d = unit_factor a \n      in  if d = 0 then (0, 1) else (b div d, a div d))\"\nproof (transfer, goal_cases)\n  case (1 x)\n  from normalize_quot_swap[of \"fst x\" \"snd x\"] show ?case\n    by (auto simp: Let_def case_prod_unfold)\nqed\n\nlemma normalize_quot_div_unit_left:\n  fixes x y u\n  assumes \"is_unit u\"\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (x div u, y) = (x' div u, y')\"\nproof (cases \"y = 0\")\n  case False\n  define v where \"v = 1 div u\"\n  with \\<open>is_unit u\\<close> have \"is_unit v\" and u: \"\\<And>a. a div u = a * v\"\n    by simp_all\n  from \\<open>is_unit v\\<close> have \"coprime v = top\"\n    by (simp add: fun_eq_iff is_unit_left_imp_coprime)\n  from normalize_quotE[OF False, of x] guess d .\n  note d = this[folded assms(2,3)]\n  from assms have \"coprime x' y'\" \"unit_factor y' = 1\"\n    by (simp_all add: coprime_normalize_quot)\n  with d \\<open>coprime v = top\\<close> have \"normalize_quot (x * v, y) = (x' * v, y')\"\n    by (auto simp: normalized_fracts_def intro: normalize_quotI)\n  then show ?thesis\n    by (simp add: u)\nqed (simp_all add: assms)\n\nlemma normalize_quot_div_unit_right:\n  fixes x y u\n  assumes \"is_unit u\"\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (x, y div u) = (x' * u, y')\"\nproof (cases \"y = 0\")\n  case False\n  from normalize_quotE[OF this, of x] guess d . note d = this[folded assms(2,3)]\n  from assms have \"coprime x' y'\" \"unit_factor y' = 1\" by (simp_all add: coprime_normalize_quot)\n  with d \\<open>is_unit u\\<close> show ?thesis\n    by (auto simp add: normalized_fracts_def is_unit_left_imp_coprime unit_div_eq_0_iff intro: normalize_quotI)\nqed (simp_all add: assms)\n\nlemma normalize_quot_normalize_left:\n  fixes x y u\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (normalize x, y) = (x' div unit_factor x, y')\"\n  using normalize_quot_div_unit_left[of \"unit_factor x\" x y]\n  by (cases \"x = 0\") (simp_all add: assms)\n  \nlemma normalize_quot_normalize_right:\n  fixes x y u\n  defines \"x' \\<equiv> fst (normalize_quot (x, y))\" and \"y' \\<equiv> snd (normalize_quot (x, y))\"\n  shows \"normalize_quot (x, normalize y) = (x' * unit_factor y, y')\"\n  using normalize_quot_div_unit_right[of \"unit_factor y\" x y]\n  by (cases \"y = 0\") (simp_all add: assms)\n  \nlemma quot_of_fract_0 [simp]: \"quot_of_fract 0 = (0, 1)\"\n  by transfer auto\n\nlemma quot_of_fract_1 [simp]: \"quot_of_fract 1 = (1, 1)\"\n  by transfer (rule normalize_quotI, simp_all add: normalized_fracts_def)\n\nlemma quot_of_fract_divide:\n  \"quot_of_fract (x / y) = (if y = 0 then (0, 1) else\n     (let (a,b) = quot_of_fract x; (c,d) = quot_of_fract y;\n          (e,f) = normalize_quot (a,c); (g,h) = normalize_quot (d,b)\n      in  (e * g, f * h)))\" (is \"_ = ?rhs\")\nproof (cases \"y = 0\")\n  case False\n  hence A: \"fst (quot_of_fract y) \\<noteq> 0\" by transfer auto\n  have \"x / y = x * inverse y\" by (simp add: divide_inverse)\n  also from False A have \"quot_of_fract \\<dots> = ?rhs\"\n    by (simp only: quot_of_fract_mult quot_of_fract_inverse)\n       (simp_all add: Let_def case_prod_unfold fst_quot_of_fract_0_imp\n          normalize_quot_div_unit_left normalize_quot_div_unit_right \n          normalize_quot_normalize_right normalize_quot_normalize_left)\n  finally show ?thesis .\nqed simp_all\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Computational_Algebra/Normalized_Fraction.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8596637523076225, "lm_q1q2_score": 0.7557706144304875}}
{"text": "(*  Author:     Amine Chaieb\n    Author:     Florian Haftmann\n    Author:     Lukas Bulwahn\n    Author:     Manuel Eberl\n*)\n\nsection \\<open>Stirling numbers of first and second kind\\<close>\n\ntheory Stirling\nimports MainRLT\nbegin\n\nsubsection \\<open>Stirling numbers of the second kind\\<close>\n\nfun Stirling :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"Stirling 0 0 = 1\"\n  | \"Stirling 0 (Suc k) = 0\"\n  | \"Stirling (Suc n) 0 = 0\"\n  | \"Stirling (Suc n) (Suc k) = Suc k * Stirling n (Suc k) + Stirling n k\"\n\nlemma Stirling_1 [simp]: \"Stirling (Suc n) (Suc 0) = 1\"\n  by (induct n) simp_all\n\nlemma Stirling_less [simp]: \"n < k \\<Longrightarrow> Stirling n k = 0\"\n  by (induct n k rule: Stirling.induct) simp_all\n\nlemma Stirling_same [simp]: \"Stirling n n = 1\"\n  by (induct n) simp_all\n\nlemma Stirling_2_2: \"Stirling (Suc (Suc n)) (Suc (Suc 0)) = 2 ^ Suc n - 1\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"Stirling (Suc (Suc (Suc n))) (Suc (Suc 0)) =\n      2 * Stirling (Suc (Suc n)) (Suc (Suc 0)) + Stirling (Suc (Suc n)) (Suc 0)\"\n    by simp\n  also have \"\\<dots> = 2 * (2 ^ Suc n - 1) + 1\"\n    by (simp only: Suc Stirling_1)\n  also have \"\\<dots> = 2 ^ Suc (Suc n) - 1\"\n  proof -\n    have \"(2::nat) ^ Suc n - 1 > 0\"\n      by (induct n) simp_all\n    then have \"2 * ((2::nat) ^ Suc n - 1) > 0\"\n      by simp\n    then have \"2 \\<le> 2 * ((2::nat) ^ Suc n)\"\n      by simp\n    with add_diff_assoc2 [of 2 \"2 * 2 ^ Suc n\" 1]\n    have \"2 * 2 ^ Suc n - 2 + (1::nat) = 2 * 2 ^ Suc n + 1 - 2\" .\n    then show ?thesis\n      by (simp add: nat_distrib)\n  qed\n  finally show ?case by simp\nqed\n\nlemma Stirling_2: \"Stirling (Suc n) (Suc (Suc 0)) = 2 ^ n - 1\"\n  using Stirling_2_2 by (cases n) simp_all\n\n\nsubsection \\<open>Stirling numbers of the first kind\\<close>\n\nfun stirling :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where\n    \"stirling 0 0 = 1\"\n  | \"stirling 0 (Suc k) = 0\"\n  | \"stirling (Suc n) 0 = 0\"\n  | \"stirling (Suc n) (Suc k) = n * stirling n (Suc k) + stirling n k\"\n\nlemma stirling_0 [simp]: \"n > 0 \\<Longrightarrow> stirling n 0 = 0\"\n  by (cases n) simp_all\n\nlemma stirling_less [simp]: \"n < k \\<Longrightarrow> stirling n k = 0\"\n  by (induct n k rule: stirling.induct) simp_all\n\nlemma stirling_same [simp]: \"stirling n n = 1\"\n  by (induct n) simp_all\n\nlemma stirling_Suc_n_1: \"stirling (Suc n) (Suc 0) = fact n\"\n  by (induct n) auto\n\nlemma stirling_Suc_n_n: \"stirling (Suc n) n = Suc n choose 2\"\n  by (induct n) (auto simp add: numerals(2))\n\nlemma stirling_Suc_n_2:\n  assumes \"n \\<ge> Suc 0\"\n  shows \"stirling (Suc n) 2 = (\\<Sum>k=1..n. fact n div k)\"\n  using assms\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by (simp add: numerals(2))\n  next\n    case Suc\n    then have geq1: \"Suc 0 \\<le> n\"\n      by simp\n    have \"stirling (Suc (Suc n)) 2 = Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0)\"\n      by (simp only: stirling.simps(4)[of \"Suc n\"] numerals(2))\n    also have \"\\<dots> = Suc n * (\\<Sum>k=1..n. fact n div k) + fact n\"\n      using Suc.hyps[OF geq1]\n      by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)\n    also have \"\\<dots> = Suc n * (\\<Sum>k=1..n. fact n div k) + Suc n * fact n div Suc n\"\n      by (metis nat.distinct(1) nonzero_mult_div_cancel_left)\n    also have \"\\<dots> = (\\<Sum>k=1..n. fact (Suc n) div k) + fact (Suc n) div Suc n\"\n      by (simp add: sum_distrib_left div_mult_swap dvd_fact)\n    also have \"\\<dots> = (\\<Sum>k=1..Suc n. fact (Suc n) div k)\"\n      by simp\n    finally show ?thesis .\n  qed\nqed\n\nlemma of_nat_stirling_Suc_n_2:\n  assumes \"n \\<ge> Suc 0\"\n  shows \"(of_nat (stirling (Suc n) 2)::'a::field_char_0) = fact n * (\\<Sum>k=1..n. (1 / of_nat k))\"\n  using assms\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  show ?case\n  proof (cases n)\n    case 0\n    then show ?thesis\n      by (auto simp add: numerals(2))\n  next\n    case Suc\n    then have geq1: \"Suc 0 \\<le> n\"\n      by simp\n    have \"(of_nat (stirling (Suc (Suc n)) 2)::'a) =\n        of_nat (Suc n * stirling (Suc n) 2 + stirling (Suc n) (Suc 0))\"\n      by (simp only: stirling.simps(4)[of \"Suc n\"] numerals(2))\n    also have \"\\<dots> = of_nat (Suc n) * (fact n * (\\<Sum>k = 1..n. 1 / of_nat k)) + fact n\"\n      using Suc.hyps[OF geq1]\n      by (simp only: stirling_Suc_n_1 of_nat_fact of_nat_add of_nat_mult)\n    also have \"\\<dots> = fact (Suc n) * (\\<Sum>k = 1..n. 1 / of_nat k) + fact (Suc n) * (1 / of_nat (Suc n))\"\n      using of_nat_neq_0 by auto\n    also have \"\\<dots> = fact (Suc n) * (\\<Sum>k = 1..Suc n. 1 / of_nat k)\"\n      by (simp add: distrib_left)\n    finally show ?thesis .\n  qed\nqed\n\nlemma sum_stirling: \"(\\<Sum>k\\<le>n. stirling n k) = fact n\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"(\\<Sum>k\\<le>Suc n. stirling (Suc n) k) = stirling (Suc n) 0 + (\\<Sum>k\\<le>n. stirling (Suc n) (Suc k))\"\n    by (simp only: sum.atMost_Suc_shift)\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. stirling (Suc n) (Suc k))\"\n    by simp\n  also have \"\\<dots> = (\\<Sum>k\\<le>n. n * stirling n (Suc k) + stirling n k)\"\n    by simp\n  also have \"\\<dots> = n * (\\<Sum>k\\<le>n. stirling n (Suc k)) + (\\<Sum>k\\<le>n. stirling n k)\"\n    by (simp add: sum.distrib sum_distrib_left)\n  also have \"\\<dots> = n * fact n + fact n\"\n  proof -\n    have \"n * (\\<Sum>k\\<le>n. stirling n (Suc k)) = n * ((\\<Sum>k\\<le>Suc n. stirling n k) - stirling n 0)\"\n      by (metis add_diff_cancel_left' sum.atMost_Suc_shift)\n    also have \"\\<dots> = n * (\\<Sum>k\\<le>n. stirling n k)\"\n      by (cases n) simp_all\n    also have \"\\<dots> = n * fact n\"\n      using Suc.hyps by simp\n    finally have \"n * (\\<Sum>k\\<le>n. stirling n (Suc k)) = n * fact n\" .\n    moreover have \"(\\<Sum>k\\<le>n. stirling n k) = fact n\"\n      using Suc.hyps .\n    ultimately show ?thesis by simp\n  qed\n  also have \"\\<dots> = fact (Suc n)\" by simp\n  finally show ?case .\nqed\n\nlemma stirling_pochhammer:\n  \"(\\<Sum>k\\<le>n. of_nat (stirling n k) * x ^ k) = (pochhammer x n :: 'a::comm_semiring_1)\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"of_nat (n * stirling n 0) = (0 :: 'a)\" by (cases n) simp_all\n  then have \"(\\<Sum>k\\<le>Suc n. of_nat (stirling (Suc n) k) * x ^ k) =\n      (of_nat (n * stirling n 0) * x ^ 0 +\n      (\\<Sum>i\\<le>n. of_nat (n * stirling n (Suc i)) * (x ^ Suc i))) +\n      (\\<Sum>i\\<le>n. of_nat (stirling n i) * (x ^ Suc i))\"\n    by (subst sum.atMost_Suc_shift) (simp add: sum.distrib ring_distribs)\n  also have \"\\<dots> = pochhammer x (Suc n)\"\n    by (subst sum.atMost_Suc_shift [symmetric])\n      (simp add: algebra_simps sum.distrib sum_distrib_left pochhammer_Suc flip: Suc)\n  finally show ?case .\nqed\n\n\ntext \\<open>A row of the Stirling number triangle\\<close>\n\ndefinition stirling_row :: \"nat \\<Rightarrow> nat list\"\n  where \"stirling_row n = [stirling n k. k \\<leftarrow> [0..<Suc n]]\"\n\nlemma nth_stirling_row: \"k \\<le> n \\<Longrightarrow> stirling_row n ! k = stirling n k\"\n  by (simp add: stirling_row_def del: upt_Suc)\n\nlemma length_stirling_row [simp]: \"length (stirling_row n) = Suc n\"\n  by (simp add: stirling_row_def)\n\nlemma stirling_row_nonempty [simp]: \"stirling_row n \\<noteq> []\"\n  using length_stirling_row[of n] by (auto simp del: length_stirling_row)\n\n\nsubsubsection \\<open>Efficient code\\<close>\n\ntext \\<open>\n  Naively using the defining equations of the Stirling numbers of the first\n  kind to compute them leads to exponential run time due to repeated\n  computations. We can use memoisation to compute them row by row without\n  repeating computations, at the cost of computing a few unneeded values.\n\n  As a bonus, this is very efficient for applications where an entire row of\n  Stirling numbers is needed.\n\\<close>\n\ndefinition zip_with_prev :: \"('a \\<Rightarrow> 'a \\<Rightarrow> 'b) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'b list\"\n  where \"zip_with_prev f x xs = map2 f (x # xs) xs\"\n\nlemma zip_with_prev_altdef:\n  \"zip_with_prev f x xs =\n    (if xs = [] then [] else f x (hd xs) # [f (xs!i) (xs!(i+1)). i \\<leftarrow> [0..<length xs - 1]])\"\nproof (cases xs)\n  case Nil\n  then show ?thesis\n    by (simp add: zip_with_prev_def)\nnext\n  case (Cons y ys)\n  then have \"zip_with_prev f x xs = f x (hd xs) # zip_with_prev f y ys\"\n    by (simp add: zip_with_prev_def)\n  also have \"zip_with_prev f y ys = map (\\<lambda>i. f (xs ! i) (xs ! (i + 1))) [0..<length xs - 1]\"\n    unfolding Cons\n    by (induct ys arbitrary: y)\n      (simp_all add: zip_with_prev_def upt_conv_Cons flip: map_Suc_upt del: upt_Suc)\n  finally show ?thesis\n    using Cons by simp\nqed\n\n\nprimrec stirling_row_aux\n  where\n    \"stirling_row_aux n y [] = [1]\"\n  | \"stirling_row_aux n y (x#xs) = (y + n * x) # stirling_row_aux n x xs\"\n\nlemma stirling_row_aux_correct:\n  \"stirling_row_aux n y xs = zip_with_prev (\\<lambda>a b. a + n * b) y xs @ [1]\"\n  by (induct xs arbitrary: y) (simp_all add: zip_with_prev_def)\n\nlemma stirling_row_code [code]:\n  \"stirling_row 0 = [1]\"\n  \"stirling_row (Suc n) = stirling_row_aux n 0 (stirling_row n)\"\nproof goal_cases\n  case 1\n  show ?case by (simp add: stirling_row_def)\nnext\n  case 2\n  have \"stirling_row (Suc n) =\n    0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \\<leftarrow> [0..<n]] @ [1]\"\n  proof (rule nth_equalityI, goal_cases length nth)\n    case (nth i)\n    from nth have \"i \\<le> Suc n\"\n      by simp\n    then consider \"i = 0 \\<or> i = Suc n\" | \"i > 0\" \"i \\<le> n\"\n      by linarith\n    then show ?case\n    proof cases\n      case 1\n      then show ?thesis\n        by (auto simp: nth_stirling_row nth_append)\n    next\n      case 2\n      then show ?thesis\n        by (cases i) (simp_all add: nth_append nth_stirling_row)\n    qed\n  next\n    case length\n    then show ?case by simp\n  qed\n  also have \"0 # [stirling_row n ! i + stirling_row n ! (i+1) * n. i \\<leftarrow> [0..<n]] @ [1] =\n      zip_with_prev (\\<lambda>a b. a + n * b) 0 (stirling_row n) @ [1]\"\n    by (cases n) (auto simp add: zip_with_prev_altdef stirling_row_def hd_map simp del: upt_Suc)\n  also have \"\\<dots> = stirling_row_aux n 0 (stirling_row n)\"\n    by (simp add: stirling_row_aux_correct)\n  finally show ?case .\nqed\n\nlemma stirling_code [code]:\n  \"stirling n k =\n    (if k = 0 then (if n = 0 then 1 else 0)\n     else if k > n then 0\n     else if k = n then 1\n     else stirling_row n ! k)\"\n  by (simp add: nth_stirling_row)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Combinatorics/Stirling.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.8596637541053281, "lm_q1q2_score": 0.7557706132888704}}
{"text": "(*\nTitle: A relationship between the Erdos-Nicolas function and the odd divisors\nAuthor: Jose Manuel Rodriguez Caballero\n\nThe Erdos-Nicolas function is defined as follows:\n\ndefinition ErdosNicolasSet :: \\<open> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<close> \n  where \\<open>ErdosNicolasSet \\<equiv> \\<lambda> n :: nat. \\<lambda> d :: nat.\n {e | e :: nat. e dvd n \\<and> e \\<le> d \\<and> d < 2*e}\\<close>\n\ndefinition ErdosNicolas :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where \\<open>ErdosNicolas \\<equiv> \\<lambda> n :: nat. Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n}\\<close>\n\nWe prove the following characterization of this function, involving only odd divisors:\n\ntheorem ErdosNicolasOddDivSetOdd:\n  fixes n k m :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> \n  shows \\<open>ErdosNicolas n = Max { card (ErdosNicolasSetOdd n k d) | d :: nat. d dvd n \\<and> odd d}\\<close>\n\nwhere \n\ndefinition ErdosNicolasSetOdd :: \\<open> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<close> \n  where \\<open>ErdosNicolasSetOdd \\<equiv> \\<lambda> n :: nat. \\<lambda> k::nat. \\<lambda> d :: nat.\n {e | e :: nat. e dvd n \\<and> odd e \\<and> e \\<le> d \\<and> d < 2^(k+1)*e}\\<close>\n\n\nReferences:\n\n@article{caballero2017symmetric,\n  title={Symmetric Dyck Paths and Hooley’s ∆-function},\n  author={Caballero, Jos{\\'e} Manuel Rodr{\\i}guez},\n  journal={Combinatorics on Words. Springer International Publishing AG},\n  year={2017}\n}\n\n@article{caballero2018function,\n  title={On a function introduced by Erd{\\\"o}s and Nicolas},\n  author={Caballero, Jos{\\'e} Manuel Rodr{\\'i}guez},\n  journal={Journal of Number Theory},\n  year={2018},\n  publisher={Elsevier}\n}\n\n@article{erdos1976methodes,\n  title={M{\\'e}thodes probabilistes et combinatoires en th{\\'e}orie des nombres},\n  author={Erdos, Paul and Nicolas, Jean-Louis},\n  journal={Bull. Sci. Math},\n  volume={2},\n  number={100},\n  pages={301--320},\n  year={1976}\n}\n\n(This code  was verified in Isabelle2018)\n\n*)\n\n\ntheory ErdosNicolasOdd\n\nimports Complex_Main  PowOfTwo\n\n\nbegin\n\ndefinition ErdosNicolasSet :: \\<open> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<close> \n  where \\<open>ErdosNicolasSet \\<equiv> \\<lambda> n :: nat. \\<lambda> d :: nat.\n {e | e :: nat. e dvd n \\<and> e \\<le> d \\<and> d < 2*e}\\<close>\n\ndefinition ErdosNicolas :: \\<open>nat \\<Rightarrow> nat\\<close>\n  where \\<open>ErdosNicolas \\<equiv> \\<lambda> n :: nat. Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n}\\<close>\n\ndefinition ErdosNicolasSetOdd :: \\<open> nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat set \\<close> \n  where \\<open>ErdosNicolasSetOdd \\<equiv> \\<lambda> n :: nat. \\<lambda> k::nat. \\<lambda> d :: nat.\n {e | e :: nat. e dvd n \\<and> odd e \\<and> e \\<le> d \\<and> d < 2^(k+1)*e}\\<close>\n\n\nsection {* Auxiliary Results *}\n\n\ndefinition OddDivSet :: \\<open>nat \\<Rightarrow> real \\<Rightarrow> nat set\\<close> where\n  \\<open>OddDivSet \\<equiv> \\<lambda> n::nat. \\<lambda> x::real.  {d | d :: nat. d dvd n \\<and> odd d \\<and> d \\<le> x }\\<close>\n\n\n\n\nlemma ErdosNicolasOdd7AXAL:\n  fixes n d:: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close>\n  shows \\<open> \\<exists> e :: nat. e dvd n \\<and> e \\<le> d \\<and> d < 2*e \\<close>\n  by (metis One_nat_def arith_special(3) assms(1) assms(2) dvd_pos_nat lessI less_le_trans n_less_m_mult_n nat_le_linear plus_1_eq_Suc)\n\nlemma ErdosNicolasOdd7AXA:\n  fixes n d:: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close>\n  shows \\<open> d \\<in> (ErdosNicolasSet n d)\\<close>\n  using assms ErdosNicolasOdd7AXAL \n  by (smt ErdosNicolasSet_def dvd_def dvd_refl le_neq_implies_less mem_Collect_eq mult.commute mult_le_mono nat_le_linear not_le)\n\nlemma ErdosNicolasOdd7AXB:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open> d \\<notin> (ErdosNicolasSet n e)\\<close>\nproof-\n  have \\<open>\\<forall> j. j \\<in> (ErdosNicolasSet n e) \\<longrightarrow> j \\<le> e\\<close> \n    by (simp add: ErdosNicolasSet_def)\n  hence  \\<open>\\<forall> j. j \\<in> (ErdosNicolasSet n e) \\<longrightarrow> j \\<noteq> d\\<close> \n    using  \\<open>e < d\\<close> \n      less_le_trans by blast\n  thus ?thesis \n    by blast\nqed\n\nlemma ErdosNicolasOdd7AX:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open> d \\<in> (ErdosNicolasSet n d) - (ErdosNicolasSet n e)\\<close>\n  using  assms ErdosNicolasOdd7AXA ErdosNicolasOdd7AXB\n  by blast\n\nlemma ErdosNicolasOdd7AY:\n  fixes n d dd e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n    and \\<open> d \\<in> (ErdosNicolasSet n d) - (ErdosNicolasSet n e)\\<close>\n    and \\<open> dd \\<in> (ErdosNicolasSet n d) - (ErdosNicolasSet n e)\\<close>\n  shows \\<open>d = dd\\<close> \n  by (metis (no_types, lifting) CollectD CollectI DiffE ErdosNicolasSet_def assms(5) assms(6) assms(8) dual_order.strict_iff_order less_le_trans)\n\nlemma singletonSplit:\n  assumes \\<open>x \\<in> S\\<close> and \\<open>\\<forall> y. (y \\<in> S \\<longrightarrow> x = y)\\<close>\n  shows \\<open>{x} = S\\<close>\n  using assms(1) assms(2) by fastforce\n\nlemma ErdosNicolasOdd7A:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open> (ErdosNicolasSet n d) - (ErdosNicolasSet n e) = {d}\\<close>\n  using assms ErdosNicolasOdd7AX ErdosNicolasOdd7AY singletonSplit\n  by metis\n\nlemma ErdosNicolasOdd7BXAL:\n  fixes n d e:: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open> (d div 2) dvd n \\<and> (d div 2) \\<le> e \\<and> e < 2*(d div 2)\\<close>\n  using Suc_le_lessD assms(1) assms(2) assms(3) assms(5) assms(6) by fastforce\n\nlemma ErdosNicolasOdd7BX:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open>d div 2 \\<in> (ErdosNicolasSet n e)\\<close>\n  using assms ErdosNicolasOdd7BXAL \n  by (metis (no_types, lifting) CollectI ErdosNicolasSet_def dvd_mult_div_cancel)\n\n\nlemma ErdosNicolasOdd7BY:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open>d div 2 \\<notin> (ErdosNicolasSet n d)\\<close>\n  by (simp add: ErdosNicolasSet_def leD)\n\n\nlemma ErdosNicolasOdd7BXYFusion:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open>d div 2 \\<in> (ErdosNicolasSet n e) - (ErdosNicolasSet n d)\\<close>\n  using ErdosNicolasOdd7BX ErdosNicolasOdd7BY assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) by auto\n\n\nlemma ErdosNicolasOdd7B:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open>card((ErdosNicolasSet n e) - (ErdosNicolasSet n d)) \\<ge> 1\\<close>\nproof-\n  have \\<open>finite (ErdosNicolasSet n e)\\<close> \n    by (metis (mono_tags, lifting) CollectD ErdosNicolasSet_def assms(5)  finite_nat_set_iff_bounded less_le_trans  not_le)\n  hence \\<open>finite((ErdosNicolasSet n e) - (ErdosNicolasSet n d))\\<close>\n    by blast\n  have \\<open>d div 2 \\<in> (ErdosNicolasSet n e) - (ErdosNicolasSet n d)\\<close> \n    using ErdosNicolasOdd7BXYFusion assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) by blast\n  thus ?thesis \n    using \\<open>finite (ErdosNicolasSet n e - ErdosNicolasSet n d)\\<close> card_Suc_Diff1 by fastforce  \nqed\n\nlemma SymDiffThisProblem:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open>card((ErdosNicolasSet n d) - (ErdosNicolasSet n e)) \\<le> card((ErdosNicolasSet n e) - (ErdosNicolasSet n d)) \\<close>\n  by (metis ErdosNicolasOdd7A ErdosNicolasOdd7B One_nat_def assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) card.empty card_insert_if empty_iff finite.emptyI)\n\nlemma SymDiff:\n  assumes \\<open>finite A\\<close> and \\<open>finite B\\<close> and \\<open>card (A - B) \\<le> card (B - A)\\<close>\n  shows \\<open>card A \\<le> card B\\<close>\nproof-\n  have \\<open>card A = card (A - B) + card (A \\<inter> B)\\<close> \n    by (metis Diff_Diff_Int Diff_disjoint Un_Diff_Int assms(1) card_Un_disjoint finite_Diff)\n  have \\<open>card B = card (B - A) + card (A \\<inter> B)\\<close> \n    by (metis Diff_Diff_Int Diff_disjoint Un_Diff_Int assms(2) card_Un_disjoint finite_Diff inf_commute)\n  show ?thesis \n    by (simp add: \\<open>card A = card (A - B) + card (A \\<inter> B)\\<close> \\<open>card B = card (B - A) + card (A \\<inter> B)\\<close> assms(3))\nqed\n\nlemma ErdosNicolasOdd6:\n  fixes n d e :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close> and \\<open>e dvd n\\<close> and \\<open>e < d\\<close>\n    and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n  shows \\<open> card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e)\\<close>\nproof-\n  have \\<open>finite (ErdosNicolasSet n d)\\<close> \n    by (metis (no_types, lifting) CollectD ErdosNicolasSet_def  finite_nat_set_iff_bounded_le  )\n  have \\<open>finite (ErdosNicolasSet n e)\\<close> \n    by (metis (no_types, lifting) CollectD ErdosNicolasSet_def bounded_nat_set_is_finite  less_le_trans  not_less)\n  hence \\<open>card((ErdosNicolasSet n d) - (ErdosNicolasSet n e)) \\<le> card((ErdosNicolasSet n e) - (ErdosNicolasSet n d)) \\<close>\n    using SymDiffThisProblem assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) by blast\n  show ?thesis \n    by (simp add: SymDiff \\<open>card (ErdosNicolasSet n d - ErdosNicolasSet n e) \\<le> card (ErdosNicolasSet n e - ErdosNicolasSet n d)\\<close> \\<open>finite (ErdosNicolasSet n d)\\<close> \\<open>finite (ErdosNicolasSet n e)\\<close>)\nqed\n\nlemma ErdosNicolasOdd5:\n  fixes n d :: nat\n  assumes \\<open>n \\<ge> 1\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close>\n  shows \\<open> \\<exists> e. e dvd n \\<and> e < d \\<and> (\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e)\\<close>\nproof-\n  obtain k::nat where \\<open>d = 2*k\\<close> using \\<open>even d\\<close> \n    by blast\n  have \\<open>k \\<in> {e | e :: nat.  e dvd n \\<and> e < d }\\<close> \n    by (metis CollectI Groups.mult_ac(2) One_nat_def Suc_le_lessD \\<open>d = 2 * k\\<close> assms(1) assms(2) dual_order.strict_iff_order dvd_imp_le dvd_pos_nat dvd_triv_right gcd_nat.trans nat_mult_1 nonzero_mult_div_cancel_left odd_one)\n  have \\<open>finite {e | e :: nat.  e dvd n \\<and> e < d }\\<close> \n    using finite_nat_set_iff_bounded by blast\n  obtain e ::nat where \\<open>e = Max  {e | e :: nat.  e dvd n \\<and> e < d }\\<close>\n    by simp\n  from  \\<open>e = Max  {e | e :: nat.  e dvd n \\<and> e < d }\\<close> \n  have \\<open>e dvd n\\<close> \n    using Max_in \\<open>finite {e |e. e dvd n \\<and> e < d}\\<close> \\<open>k \\<in> {e |e. e dvd n \\<and> e < d}\\<close> mem_Collect_eq by blast\n  from  \\<open>e = Max  {e | e :: nat.  e dvd n \\<and> e < d }\\<close> \n  have \\<open>e < d\\<close> \n    using Max_in \\<open>finite {e |e. e dvd n \\<and> e < d}\\<close> \\<open>k \\<in> {e |e. e dvd n \\<and> e < d}\\<close> mem_Collect_eq by blast\n  from  \\<open>e = Max  {e | e :: nat.  e dvd n \\<and> e < d }\\<close> \n  have \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close> \n    by simp\n  show ?thesis \n    using \\<open>\\<forall>ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close> \\<open>e < d\\<close> \\<open>e dvd n\\<close> by blast\nqed\n\nlemma ErdosNicolasOdd4:\n  assumes  \\<open>n \\<ge> 1\\<close> and \\<open>d \\<le> Suc k\\<close> and \\<open>d dvd n\\<close> and \\<open>even d\\<close>\n  shows \\<open>\\<exists> e. e dvd n \\<and> e \\<le> k \\<and> card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e)\\<close>\nproof-\n  obtain k where \\<open>2*k = d\\<close> \n    using assms(4) by blast\n  obtain e where \\<open>e dvd n\\<close> and \\<open>e < d\\<close> and \\<open>\\<forall> ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close>\n    using ErdosNicolasOdd5 assms(1) assms(3) \\<open>even d\\<close> by blast\n  have \\<open>card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e)\\<close> \n    using ErdosNicolasOdd6 \\<open>\\<forall>ee. ee dvd n \\<and> ee < d \\<longrightarrow> ee \\<le> e\\<close> \\<open>e < d\\<close> \\<open>e dvd n\\<close> assms(1) assms(3) assms(4) by blast\n  thus ?thesis \n    using \\<open>e < d\\<close> \\<open>e dvd n\\<close> assms(2) less_le_trans by auto\nqed\n\nlemma ErdosNicolasOdd3:\n  assumes \\<open>\\<forall> n d.  n \\<ge> 1 \\<and> d \\<le> k  \\<and> d dvd n  \\<longrightarrow> ( \\<exists> e. e dvd n \\<and> odd e \\<and> card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e) )\\<close>\n    and \\<open>n \\<ge> 1\\<close> and \\<open>d \\<le> Suc k\\<close>  and \\<open>d dvd n\\<close>\n  shows \\<open>\\<exists> e. e dvd n \\<and> odd e \\<and> card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e)\\<close>\nproof(induction k)\n  case 0\n  thus ?case \n    by (smt ErdosNicolasOdd4 assms(1) assms(2) assms(3) assms(4) order_refl order_trans)\nnext\n  case (Suc k)\n  thus ?case using ErdosNicolasOdd4 \n    by blast\nqed\n\n\nlemma ErdosNicolasOdd2:\n  \\<open>\\<forall> n d.  n \\<ge> 1 \\<and> d \\<le> k  \\<and> d dvd n  \\<longrightarrow> ( \\<exists> e. e dvd n \\<and> odd e \\<and> card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e) )\\<close>\nproof(induction k)\n  case 0\n  thus ?case \n    by auto\nnext\n  case (Suc k)\n  thus ?case using ErdosNicolasOdd3 by blast\nqed\n\nlemma ErdosNicolasOdd1:\n  \\<open>n \\<ge> 1 \\<Longrightarrow> d dvd n  \\<Longrightarrow> \\<exists> e. e dvd n \\<and> odd e \\<and> card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e) \\<close>\n  using ErdosNicolasOdd2 \n  by (metis   Suc_n_not_le_n dual_order.trans    nat_le_linear  )\n\n\nproposition ErdosNicolasOdd:\n  \\<open>n \\<ge> 1 \\<Longrightarrow> ErdosNicolas n = Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d}\\<close>\nproof-\n  assume \\<open>n \\<ge> 1\\<close>\n  have \\<open>{ card (ErdosNicolasSet n d) | d :: nat. d dvd n} \\<noteq> {}\\<close>\n    by blast\n  have \\<open>\\<forall> d. d dvd n \\<longrightarrow> d \\<le> n\\<close> \n    using \\<open>1 \\<le> n\\<close> by auto\n  hence \\<open>{ card (ErdosNicolasSet n d) | d :: nat. d dvd n} = { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> d \\<le> n}\\<close>\n    by blast\n  have \\<open>finite { d | d :: nat. d dvd n \\<and> d \\<le> n}\\<close>\n    using finite_nat_set_iff_bounded_le by blast\n  hence \\<open>finite { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> d \\<le> n}\\<close>\n    by auto\n  hence \\<open>finite { card (ErdosNicolasSet n d) | d :: nat. d dvd n}\\<close>\n    using  \\<open>{ card (ErdosNicolasSet n d) | d :: nat. d dvd n} = { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> d \\<le> n}\\<close>\n    by auto\n  have \\<open>{ card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d} \\<subseteq> { card (ErdosNicolasSet n d) | d :: nat. d dvd n}\\<close>\n    by blast\n  hence  \\<open>Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d} \\<le> Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n}\\<close>\n  proof -\n    have \"\\<exists>na nb. na = card (ErdosNicolasSet n nb) \\<and> nb dvd n \\<and> odd nb\"\n      by (meson odd_one one_dvd)\n    thus ?thesis\n      by (simp add: Max.subset_imp \\<open>finite {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> \\<open>{card (ErdosNicolasSet n d) |d. d dvd n \\<and> odd d} \\<subseteq> {card (ErdosNicolasSet n d) |d. d dvd n}\\<close>)\n  qed\n\n  obtain d::nat where \\<open>card (ErdosNicolasSet n d)  = Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n}\\<close>\n  proof -\n    assume a1: \"\\<And>d. card (ErdosNicolasSet n d) = Max {card (ErdosNicolasSet n d) |d. d dvd n} \\<Longrightarrow> thesis\"\n    have \"\\<exists>na. Max {card (ErdosNicolasSet n na) |na. na dvd n} = card (ErdosNicolasSet n na)\"\n      using Max_in \\<open>finite {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> by auto\n    thus ?thesis\n      using a1 by force\n  qed\n\n  obtain e :: nat where \\<open>card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e)\\<close> and \\<open>e dvd n\\<close> and \\<open>odd e\\<close>\n    by (smt CollectD ErdosNicolasOdd1 Max_in \\<open>1 \\<le> n\\<close> \\<open>card (ErdosNicolasSet n d) = Max {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> \\<open>finite {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> \\<open>{card (ErdosNicolasSet n d) |d. d dvd n} \\<noteq> {}\\<close>)\n\n  have \\<open>card (ErdosNicolasSet n e) \\<in> {card (ErdosNicolasSet n d) |d. d dvd n \\<and> odd d}\\<close>\n    using \\<open>e dvd n\\<close> \\<open>odd e\\<close> by blast\n  hence \\<open>card (ErdosNicolasSet n e) \\<le> Max {card (ErdosNicolasSet n d) |d. d dvd n \\<and> odd d}\\<close>\n    by (metis (mono_tags, lifting) Max_ge \\<open>finite {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> \\<open>{card (ErdosNicolasSet n d) |d. d dvd n \\<and> odd d} \\<subseteq> {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> finite_subset)\n  hence  \\<open> Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n} \\<le> Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d}\\<close>\n    using \\<open>card (ErdosNicolasSet n d) = Max {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> \\<open>card (ErdosNicolasSet n d) \\<le> card (ErdosNicolasSet n e)\\<close> le_trans subset_refl by linarith\n  hence \\<open>Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n} = Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d}\\<close>\n    using \\<open>Max {card (ErdosNicolasSet n d) |d. d dvd n \\<and> odd d} \\<le> Max {card (ErdosNicolasSet n d) |d. d dvd n}\\<close> le_antisym by blast\n  show ?thesis \n    using ErdosNicolas_def \\<open>Max {card (ErdosNicolasSet n d) |d. d dvd n} = Max {card (ErdosNicolasSet n d) |d. d dvd n \\<and> odd d}\\<close> by presburger\nqed\n\n\n\n\nlemma ErdosNicolasSetOddDivSetLInter:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open> (ErdosNicolasSet n d) \\<inter> (OddDivSet n ((d::real)/(2::real)^(k+1))) = {}\\<close>\nproof(rule classical)\n  assume \\<open>\\<not> (  (ErdosNicolasSet n d) \\<inter> (OddDivSet n ((d::real)/(2::real)^(k+1))) = {} )\\<close>\n  hence  \\<open>(ErdosNicolasSet n d) \\<inter> (OddDivSet n ((d::real)/(2::real)^(k+1))) \\<noteq> {}\\<close>\n    by simp\n  then obtain x where \\<open>x \\<in> (ErdosNicolasSet n d) \\<inter> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    by blast\n  hence \\<open>x \\<in> ErdosNicolasSet n d\\<close>\n    by blast\n  from  \\<open>x \\<in> (ErdosNicolasSet n d) \\<inter> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n  have \\<open>x \\<in> OddDivSet n ((d::real)/(2::real)^(k+1))\\<close> \n    by blast\n  from  \\<open>x \\<in> ErdosNicolasSet n d\\<close> have \\<open>(d::real)/(2::real) < x\\<close> \n    using CollectD ErdosNicolasSet_def by fastforce\n  from \\<open>x \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close> have \\<open>x \\<le> (d::real)/(2::real)^(k+1)\\<close>\n    using CollectD OddDivSet_def by fastforce\n  have \\<open>(2::real)^1 \\<le> (2::real)^(k+1)\\<close> \n    by simp\n  hence \\<open> (d::real)/(2::real)^(k+1) \\<le>  (d::real)/(2::real)\\<close>  \n    by (smt frac_le neq0_conv of_nat_0_less_iff power_one_right semiring_1_class.of_nat_simps(1))\n  hence \\<open>x < x\\<close> using \\<open>(d::real)/(2::real) < x\\<close>  \\<open>x \\<le> (d::real)/(2::real)^(k+1)\\<close>\n    by linarith\n  thus ?thesis \n    by blast\nqed\n\n\nlemma WLGOddPartShortIntervalX:\n  fixes x y i j :: nat\n  assumes \\<open>OddPart x = OddPart y\\<close> and \\<open>y < 2*x\\<close> and \\<open>x \\<le> y\\<close>\n    and \\<open>x = (2::nat)^i*(OddPart x)\\<close> and \\<open>y = (2::nat)^j*(OddPart y)\\<close>\n    and \\<open>i \\<le> j\\<close>\n  shows \\<open>x = y\\<close>\nproof-\n  have \\<open>OddPart x > 0\\<close> \n    using Exp2OddPartChar assms(4) by fastforce\n  hence \\<open>(OddPart x)/(OddPart x) = 1\\<close>\n    by simp\n  have \\<open>(2::nat)^j*(OddPart y) < (2::nat)*((2::nat)^i*(OddPart x))\\<close>\n    using \\<open>y < (2::nat)*x\\<close>  \\<open>x = (2::nat)^i*(OddPart x)\\<close>  \\<open>y = (2::nat)^j*(OddPart y)\\<close>\n    by auto\n  hence \\<open>(2::nat)^j*(OddPart y) < (2::nat)^(i+1)*(OddPart x)\\<close>\n    by simp\n  hence \\<open>(2::nat)^j*(OddPart x) < (2::nat)^(i+1)*(OddPart x)\\<close>\n    using  \\<open>OddPart x = OddPart y\\<close> by simp\n  hence  \\<open>(2::nat)^j < (2::nat)^(i+1)\\<close>\n    using  \\<open>(OddPart x)/(OddPart x) = 1\\<close> \n    by simp   \n  hence \\<open>j < i+1\\<close> \n    using nat_power_less_imp_less pos2 by blast\n  have \\<open>j = i\\<close> \n    using \\<open>j < i + 1\\<close> assms(6) by linarith\n  show ?thesis \n    using \\<open>j = i\\<close> assms(1) assms(4) assms(5) by auto\nqed\n\nlemma OddPartShortIntervalX:\n  fixes x y :: nat\n  assumes \\<open>OddPart x = OddPart y\\<close> and \\<open>y < 2*x\\<close> and \\<open>x \\<le> y\\<close>\n    and \\<open>x = 2^i*(OddPart x)\\<close> and \\<open>y = 2^j*(OddPart y)\\<close>\n  shows \\<open>x = y\\<close>\n  by (metis WLGOddPartShortIntervalX antisym assms(1) assms(2) assms(3) assms(4) assms(5) linear mult_le_mono1 one_less_numeral_iff power_increasing_iff semiring_norm(76))\n\nlemma OddPartShortInterval:\n  fixes x y :: nat\n  assumes \\<open>OddPart x = OddPart y\\<close> and \\<open>y < 2*x\\<close> and \\<open>x \\<le> y\\<close>\n  shows \\<open>x = y\\<close>\nproof-\n  obtain i where \\<open>x = 2^i*(OddPart x)\\<close> \n    by (metis One_nat_def Suc_leI assms(2) assms(3) mult_0_right neq0_conv not_le preExp2OddPartChar2)\n  obtain j where \\<open>y = 2^j*(OddPart y)\\<close> \n    by (metis One_nat_def Suc_leI \\<open>x = 2 ^ i * OddPart x\\<close> assms(3) linorder_not_le neq0_conv preExp2OddPartChar2)\n  show ?thesis \n    using OddPartShortIntervalX \\<open>x = 2 ^ i * OddPart x\\<close> \\<open>y = 2 ^ j * OddPart y\\<close> assms(1) assms(2) assms(3) by blast\nqed\n\nlemma WLOGErdosNicolasSetOddDivSetInjOnSCaseA:\n  fixes n k m d x y :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close>\n    and  \\<open>x \\<in>  (ErdosNicolasSet n d)\\<close>\n    and  \\<open>y \\<in>  (ErdosNicolasSet n d)\\<close>\n    and \\<open>OddPart x = OddPart y\\<close> and \\<open>x \\<le> y\\<close>\n  shows \\<open>x = y\\<close>\nproof-\n  from  \\<open>x \\<in>  (ErdosNicolasSet n d)\\<close>\n  have \\<open>d < 2*x\\<close> \n    using CollectD ErdosNicolasSet_def by fastforce\n  from  \\<open>y \\<in>  (ErdosNicolasSet n d)\\<close>\n  have \\<open>y \\<le> d\\<close> \n    by (simp add: ErdosNicolasSet_def)\n  have \\<open>y < 2*x\\<close> \n    using \\<open>d < 2 * x\\<close> \\<open>y \\<le> d\\<close> le_less_trans by blast\n  show ?thesis using OddPartShortInterval \\<open>x \\<le> y\\<close> \\<open>y < 2*x\\<close>  \\<open>OddPart x = OddPart y\\<close> \n    by simp\nqed\n\n\nlemma ErdosNicolasSetOddDivSetInjOnSCaseA:\n  fixes n k m d x y :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close>\n    and  \\<open>x \\<in>  (ErdosNicolasSet n d)\\<close>\n    and  \\<open>y \\<in>  (ErdosNicolasSet n d)\\<close>\n    and \\<open>OddPart x = OddPart y\\<close>\n  shows \\<open>x = y\\<close>\n  using WLOGErdosNicolasSetOddDivSetInjOnSCaseA assms \n  by (metis nat_le_linear)\n\nlemma OddPartBoundDiv:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close>\n  shows \\<open>OddPart d \\<ge> d/(2::real)^k\\<close>\nproof-\n  obtain j where \\<open>(2::nat)^j*(OddPart d) = d\\<close>\n    by (metis assms(1) assms(2) assms(3) dvd_0_left_iff even_mult_iff even_numeral less_one linorder_not_le   mult_eq_0_iff  preExp2OddPartChar2X2)\n  from  \\<open>(2::nat)^j*(OddPart d) = d\\<close> \\<open>d dvd n\\<close> \n  have \\<open>(2::nat)^j dvd n\\<close> \n    by (metis dvd_mult_left)\n  hence \\<open>(2::nat)^j dvd (2::nat)^k*m\\<close>  \n    using  \\<open>n = (2::nat)^k*m\\<close> \n    by blast\n  have \\<open>gcd ((2::nat)^j) m = 1\\<close> \n    by (meson OddDivPow2 assms(2) dvd_trans gcd_unique_nat one_le_numeral one_le_power)\n  hence  \\<open>(2::nat)^j dvd (2::nat)^k\\<close>\n    using \\<open>(2::nat)^j dvd (2::nat)^k*m\\<close>\n    by (metis dvd_triv_right gcd_greatest gcd_mult_distrib_nat semiring_normalization_rules(12))\n  hence \\<open>(2::nat)^j \\<le> (2::nat)^k\\<close>\n    by (simp add: dvd_imp_le)\n  hence \\<open>(2::nat)^k*(OddPart d) \\<ge> d\\<close> using  \\<open>(2::nat)^j*(OddPart d) = d\\<close> \n    by (metis mult_le_mono1)\n  hence \\<open>(2::real)^k*(OddPart d) \\<ge> d\\<close> \n    by (metis  numeral_power_eq_of_nat_cancel_iff of_nat_le_iff of_nat_mult )\n  have \\<open>(2::real)^k > 0\\<close> \n    by simp\n  then  show ?thesis using  \\<open>(2::real)^k*(OddPart d) \\<ge> d\\<close>\n    by (smt divide_strict_right_mono nonzero_mult_div_cancel_left)\nqed\n\n\nlemma ImpoErdosNicolasSetOddDivSetInjOnSCaseB:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close>\n    and  \\<open>x \\<in>  (ErdosNicolasSet n d)\\<close>\n    and  \\<open>y \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n  shows \\<open>OddPart x \\<noteq> OddPart y\\<close>\nproof-\n  have \\<open>odd y\\<close> \n    using CollectD OddDivSet_def assms(6) by fastforce\n  hence \\<open>OddPart y = y\\<close> \n    by (metis One_nat_def Suc_leI odd_pos preExp2OddPartChar1 preExp2OddPartChar2 preUniqnessOddEven_OddPartOneSide)\n  have \\<open>y \\<le> ((d::real)/(2::real)^(k+1))\\<close> \n    using CollectD OddDivSet_def assms(6) by fastforce\n  have \\<open>x dvd n\\<close> \n    using CollectD ErdosNicolasSet_def assms(5) by fastforce\n  hence \\<open>OddPart x \\<ge> x / (2::real)^k\\<close> \n    using OddPartBoundDiv assms(1) assms(2) by blast\n  from  \\<open>x \\<in>  (ErdosNicolasSet n d)\\<close> \n  have \\<open>2*x > d\\<close> \n    using CollectD ErdosNicolasSet_def by fastforce \n  hence \\<open>x > (d::real)/(2::real)\\<close>\n    by linarith\n  hence \\<open> x / (2::real)^k  > ((d::real)/(2::real))/(2::real)^k\\<close>\n    by (smt divide_strict_right_mono zero_less_power)\n  hence \\<open> x / (2::real)^k  > (d::real)/((2::real)*(2::real)^k)\\<close>\n    by simp\n  hence \\<open> x / (2::real)^k  > (d::real)/((2::real)^(k+1))\\<close>\n    by simp\n  hence \\<open>OddPart x > (d::real)/((2::real)^(k+1))\\<close> \n    using \\<open>real x / 2 ^ k \\<le> real (OddPart x)\\<close> by linarith\n  hence \\<open>OddPart x > y\\<close> \n    using \\<open>real y \\<le> real d / 2 ^ (k + 1)\\<close> by linarith \n  thus ?thesis \n    using \\<open>OddPart y = y\\<close> by linarith\nqed\n\nlemma ErdosNicolasSetOddDivSetInjOnSCaseB:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close>\n    and  \\<open>x \\<in>  (ErdosNicolasSet n d)\\<close>\n    and  \\<open> y \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    and \\<open>OddPart x = OddPart y\\<close>\n  shows \\<open>x = y\\<close>\n  using assms ImpoErdosNicolasSetOddDivSetInjOnSCaseB \n  by blast\n\n\nlemma ErdosNicolasSetOddDivSetInjOnSCaseC:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close>\n    and  \\<open> x \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    and  \\<open>y \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    and \\<open>OddPart x = OddPart y\\<close>\n  shows \\<open>x = y\\<close>\nproof-\n  have \\<open>odd x\\<close> \n    by (metis (no_types, lifting) OddDivSet_def One_nat_def add.right_neutral add_Suc_right assms(5) mem_Collect_eq)\n  hence \\<open>OddPart x = x\\<close> \n    by (metis One_nat_def Suc_leI odd_pos preExp2OddPartChar1 preExp2OddPartChar2 preUniqnessOddEven_OddPartOneSide)\n  have \\<open>odd y\\<close> \n    using CollectD OddDivSet_def assms(6) by fastforce\n  hence \\<open>OddPart y = y\\<close>\n    by (metis One_nat_def Suc_leI odd_pos preExp2OddPartChar1 preExp2OddPartChar2 preUniqnessOddEven_OddPartOneSide)\n  show ?thesis \n    using \\<open>OddPart x = x\\<close> \\<open>OddPart y = y\\<close> assms(7) by linarith\nqed\n\n\nlemma ErdosNicolasSetOddDivSetInjOnS:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close>\n    and  \\<open>x \\<in>  (ErdosNicolasSet n d) \\<or> x \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    and  \\<open>y \\<in>  (ErdosNicolasSet n d) \\<or> y \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    and \\<open>OddPart x = OddPart y\\<close>\n  shows \\<open>x = y\\<close>\n  using assms ErdosNicolasSetOddDivSetInjOnSCaseA ErdosNicolasSetOddDivSetInjOnSCaseB\n    ErdosNicolasSetOddDivSetInjOnSCaseC \n  by metis\n\nlemma ErdosNicolasSetOddDivSetInjOn:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open> inj_on OddPart ((ErdosNicolasSet n d) \\<union> (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\n  using ErdosNicolasSetOddDivSetInjOnS inj_on_def assms \n  by (smt UnE)\n\nlemma OddPartErdosNicolasSet:\n  \\<open> OddPart ` ((ErdosNicolasSet n d) \\<union> (OddDivSet n ((d::real)/(2::real)^(k+1)))) = (OddPart ` ((ErdosNicolasSet n d))) \\<union> (OddPart ` (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\n  by (simp add: image_Un)\n\nlemma ErdosNicolasSetOddDivSetSurjAIS:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n    and \\<open>x \\<in> ((ErdosNicolasSet n d))\\<close> \n  shows \\<open>OddPart x \\<in> (OddDivSet n (d::real))\\<close>\nproof-\n  from  \\<open>x \\<in> ((ErdosNicolasSet n d))\\<close> \n  have \\<open>x dvd n\\<close> \n    using CollectD ErdosNicolasSet_def by fastforce\n  from  \\<open>x \\<in> ((ErdosNicolasSet n d))\\<close> \n  have \\<open>x \\<le> d\\<close> \n    using CollectD ErdosNicolasSet_def by fastforce\n  have \\<open>OddPart x dvd n\\<close> \n    by (metis OddPartL1 \\<open>x dvd n\\<close> dvd_0_right dvd_imp_le gcd_nat.trans one_dvd order.order_iff_strict zero_order(1)) \n  have \\<open>OddPart x \\<le> d\\<close> \n    by (metis OddPartL1 One_nat_def Suc_leI \\<open>x \\<le> d\\<close> \\<open>x dvd n\\<close> assms(1) assms(2) dual_order.trans dvd_imp_le dvd_pos_nat nat_0_less_mult_iff odd_pos pos2 zero_less_power)\n  have \\<open>OddPart x \\<ge> 1\\<close> \n    by (metis One_nat_def Suc_leI \\<open>OddPart x dvd n\\<close> assms(1) assms(2) dvd_pos_nat nat_0_less_mult_iff odd_pos pos2 zero_less_power)\n  hence \\<open>odd (OddPart x)\\<close>\n    by (metis One_nat_def Suc_leI \\<open>x dvd n\\<close> assms(1) assms(2) dvd_pos_nat nat_0_less_mult_iff odd_pos pos2 preExp2OddPartChar1 zero_less_power)\n  show ?thesis \n    by (simp add: OddDivSet_def \\<open>OddPart x \\<le> d\\<close> \\<open>OddPart x dvd n\\<close> \\<open>odd (OddPart x)\\<close>)\nqed\n\n\nlemma ErdosNicolasSetOddDivSetSurjAI:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>  (OddPart ` ((ErdosNicolasSet n d))) \\<subseteq> (OddDivSet n (d::real))\\<close>\n  using ErdosNicolasSetOddDivSetSurjAIS assms(1) assms(2) assms(3) assms(4) by blast\n\nlemma ErdosNicolasSetOddDivSetSurjAIIX:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n    and \\<open>x \\<in> (OddPart ` (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\n  shows \\<open> x \\<in> (OddDivSet n (d::real))\\<close>\nproof-\n  obtain y::nat where \\<open>x = OddPart y\\<close> and \\<open>y \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    using assms(5) by blast\n  from  \\<open>y \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n  have \\<open>odd y\\<close> \n    by (metis (mono_tags, lifting) CollectD OddDivSet_def One_nat_def add.right_neutral add_Suc_right  one_add_one)\n  hence \\<open>y \\<ge> 1\\<close> \n    by (simp add: dvd_imp_le odd_pos)\n  hence \\<open>y = OddPart y\\<close> using  \\<open>odd y\\<close>\n    by (meson OddPartL1 OddPartL1X1 antisym dvd_refl linorder_neqE_nat nat_dvd_not_less odd_pos order_less_imp_le)\n  have \\<open>y \\<le> ((d::real)/(2::real)^(k+1))\\<close> \n    using CollectD OddDivSet_def \\<open>y \\<in> OddDivSet n (real d / 2 ^ (k + 1))\\<close> by fastforce\n  have \\<open>(1::real) \\<le> (2::real)^(k+1)\\<close> \n    using two_realpow_ge_one by blast \n  have \\<open> ((d::real)/(2::real)^(k+1)) \\<le> (d::real)/(1::real)\\<close> \n    by (smt \\<open>1 \\<le> 2 ^ (k + 1)\\<close> frac_le neq0_conv of_nat_0 of_nat_0_less_iff)    \n  then  have \\<open> ((d::real)/(2::real)^(k+1)) \\<le> (d::real)\\<close> \n    by linarith\n  then  have \\<open>y \\<le> (d::real)\\<close> \n    using \\<open>real y \\<le> real d / 2 ^ (k + 1)\\<close> by linarith\n  hence \\<open>x \\<le> d\\<close> \n    using \\<open>x = OddPart y\\<close> \\<open>y = OddPart y\\<close> by linarith\n  have \\<open>odd x\\<close> \n    using \\<open>odd y\\<close> \\<open>x = OddPart y\\<close> \\<open>y = OddPart y\\<close> by auto\n  have \\<open>x dvd n\\<close> \n    using CollectD OddDivSet_def \\<open>x = OddPart y\\<close> \\<open>y = OddPart y\\<close> \\<open>y \\<in> OddDivSet n (real d / 2 ^ (k + 1))\\<close> by fastforce\n  show ?thesis \n    by (simp add: OddDivSet_def \\<open>odd x\\<close> \\<open>x \\<le> d\\<close> \\<open>x dvd n\\<close>)\nqed\n\n\nlemma ErdosNicolasSetOddDivSetSurjAII:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>  (OddPart ` (OddDivSet n ((d::real)/(2::real)^(k+1)))) \\<subseteq> (OddDivSet n (d::real))\\<close>\n  using assms ErdosNicolasSetOddDivSetSurjAIIX by blast\n\nlemma ErdosNicolasSetOddDivSetSurjA:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>  (OddPart ` ((ErdosNicolasSet n d))) \\<union> (OddPart ` (OddDivSet n ((d::real)/(2::real)^(k+1)))) \\<subseteq> (OddDivSet n (d::real))\\<close>\n  using assms ErdosNicolasSetOddDivSetSurjAI ErdosNicolasSetOddDivSetSurjAII \n  by simp\n\nlemma ErdosNicolasSetOddDivSetSurjBI:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n    and \\<open>x \\<in> (OddDivSet n (d::real))\\<close>\n    and \\<open>x \\<le> ((d::real)/(2::real)^(k+1))\\<close>\n  shows \\<open>x \\<in> (OddPart ` (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\nproof-\n  from \\<open>x \\<in> (OddDivSet n (d::real))\\<close>\n  have \\<open>x dvd n\\<close> \n    using CollectD OddDivSet_def by fastforce\n  from  \\<open>x \\<in> (OddDivSet n (d::real))\\<close>\n  have \\<open>odd x\\<close> using OddDivSet_def \n    using CollectD by fastforce\n  have \\<open>x \\<ge> 1\\<close> \n    by (simp add: Suc_leI \\<open>odd x\\<close> odd_pos)\n  have \\<open>x = OddPart x\\<close> \n    using \\<open>1 \\<le> x\\<close> \\<open>odd x\\<close> preExp2OddPartChar1 preExp2OddPartChar2 preUniqnessOddEven_OddPartOneSide by blast\n  have \\<open>x \\<in> (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close>\n    by (metis (mono_tags) OddDivSet_def Suc_eq_plus1 \\<open>odd x\\<close> \\<open>x dvd n\\<close> assms(6) mem_Collect_eq )\n  thus ?thesis \n    using \\<open>x = OddPart x\\<close> by blast\nqed\n\n\nlemma ErdosNicolasSetOddDivSetSurjBII:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n    and \\<open>x \\<in> (OddDivSet n (d::real))\\<close>\n    and \\<open>x > ((d::real)/(2::real)^(k+1))\\<close>\n  shows \\<open>x \\<in> (OddPart ` ((ErdosNicolasSet n d)))\\<close>\nproof-\n  from  \\<open>x \\<in> (OddDivSet n (d::real))\\<close>\n  have \\<open>x dvd n\\<close> \n    using CollectD OddDivSet_def by fastforce\n  from  \\<open>x \\<in> (OddDivSet n (d::real))\\<close>\n  have \\<open>odd x\\<close> \n    using CollectD OddDivSet_def by fastforce\n  hence \\<open>x \\<ge> 1\\<close> \n    by (simp add: dvd_imp_le odd_pos)\n  hence \\<open>OddPart x = x\\<close>\n    using  \\<open>odd x\\<close> \n    by (meson OddPartL1 OddPartL1X1 antisym dvd_refl linorder_neqE_nat nat_dvd_not_less odd_pos order_less_imp_le)\n  from \\<open>x > ((d::real)/(2::real)^(k+1))\\<close>\n  have \\<open>2^k*x > 2^k*((d::real)/(2::real)^(k+1))\\<close>\n    by (smt mult_le_cancel_left_pos of_nat_1 of_nat_add of_nat_mult of_nat_power one_add_one zero_less_power)\n  hence \\<open>2^k*x > (d::real)/(2::real)\\<close>\n    by simp\n  hence \\<open>k \\<in> {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close>\n    by blast\n  hence \\<open>{i | i :: nat. 2^i*x > (d::real)/(2::real)} \\<noteq> {}\\<close>\n    by blast\n  then obtain j::nat where \\<open>j = Inf {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close>\n    by blast\n  from \\<open>k \\<in> {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close> \n  have \\<open>k \\<ge> Inf {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close>\n    using cInf_lower\n    by (metis \\<open>j = Inf {i |i. real d / 2 < real (2 ^ i * x)}\\<close> bdd_above_bot)\n  hence \\<open>k \\<ge> j\\<close> \n    using \\<open>j = Inf {i |i. real d / 2 < real (2 ^ i * x)}\\<close> by blast\n  hence \\<open>2^j dvd n\\<close> \n    using assms(1) dvd_triv_left power_le_dvd by blast\n  hence \\<open>gcd x (2^j) = 1\\<close> \n    by (meson OddDivPow2 \\<open>odd x\\<close> dvd_trans gcd_unique_nat one_le_numeral one_le_power)\n  hence \\<open>2^j*x dvd n\\<close> using  \\<open>2^j dvd n\\<close> \\<open>x dvd n\\<close> \n    by (smt TrapezoidalNumbersNec2_5 \\<open>j \\<le> k\\<close> \\<open>odd x\\<close> assms(1) division_decomp dvd_mult le_imp_power_dvd mult_dvd_mono preUniqnessOddEven_OddPartOneSide)\n  from  \\<open>j = Inf {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close> \\<open> {i | i :: nat. 2^i*x > (d::real)/(2::real)} \\<noteq> {}\\<close>\n  have \\<open>j \\<in> {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close>\n    using Inf_nat_def1\n    by presburger\n  hence \\<open>2^j*x > (d::real)/(2::real)\\<close>\n    by blast\n  have \\<open>d \\<ge> x\\<close> \n    by (metis (no_types, lifting) CollectD OddDivSet_def assms(5) of_nat_le_iff)\n  have \\<open>d \\<ge> 2^j*x\\<close>\n  proof(cases \\<open>j = 0\\<close>)\n    case True\n    thus ?thesis using \\<open>d \\<ge> x\\<close> \\<open>j = 0\\<close> by simp\n  next\n    case False\n    hence \\<open>j \\<noteq> 0\\<close> by blast\n    then obtain p::nat where \\<open>Suc p = j\\<close> \n      by (metis lessI less_Suc_eq_0_disj)\n    have \\<open>d \\<ge> 2^j*x\\<close>\n    proof(rule classical)\n      assume \\<open>\\<not>(d \\<ge> 2^j*x)\\<close>\n      hence \\<open>2^(Suc p)*x > d\\<close> using \\<open>Suc p = j\\<close> by auto\n      hence \\<open>2*(2^p*x) > d\\<close> \n        by auto\n      hence \\<open>2^p*x > (d::real)/(2::real)\\<close> \n        by linarith\n      hence \\<open>p \\<in> {i | i :: nat. 2^i*x > (d::real)/(2::real)}\\<close>\n        by blast\n      have \\<open>p < j\\<close> \n        using \\<open>Suc p = j\\<close> by blast\n      have \\<open>p \\<ge> j\\<close> \n        by (metis \\<open>j = Inf {i |i. real d / 2 < real (2 ^ i * x)}\\<close> \\<open>p \\<in> {i |i. real d / 2 < real (2 ^ i * x)}\\<close> bdd_above_bot cInf_lower)\n      show ?thesis using  \\<open>p < j\\<close> \\<open>p \\<ge> j\\<close>  by auto\n    qed\n    thus ?thesis by blast\n  qed\n  from \\<open>2^j*x > (d::real)/(2::real)\\<close>\n  have \\<open>2^j*x > d/2\\<close>\n    by simp\n  hence \\<open>2*(2^j*x) > 2*(d/2)\\<close> by simp\n  hence  \\<open>2*(2^j*x) > d*((2::nat)/2)\\<close> by simp\n  hence  \\<open>2*(2^j*x) > d*(1::nat)\\<close> \n    by (simp add: of_nat_less_imp_less)\n  hence  \\<open>2*(2^j*x) > d\\<close> \n    by linarith \n  have \\<open>2^j*x \\<in> ((ErdosNicolasSet n d))\\<close>\n    using \\<open>d \\<ge> 2^j*x\\<close> \\<open>2*(2^j*x) > d\\<close>  \\<open>x dvd n\\<close> ErdosNicolasSet_def \n    by (simp add: \\<open>ErdosNicolasSet \\<equiv> \\<lambda>n d. {e |e. e dvd n \\<and> e \\<le> d \\<and> d < 2 * e}\\<close> \\<open>2 ^ j * x dvd n\\<close>)\n  have \\<open>OddPart (2^j*x) = x\\<close> using \\<open>odd x\\<close> \\<open>x \\<ge> 1\\<close> UniqnessOddEven\n    by (smt dvd_mult_unit_iff' le_eq_less_or_eq less_1_mult nat_dvd_1_iff_1 one_le_numeral one_le_power preExp2OddPartChar1 preExp2OddPartChar2 preUniqnessOddEven_OddPartOneSide semiring_normalization_rules(12))\n  from  \\<open>2^j*x \\<in> (ErdosNicolasSet n d)\\<close> \\<open>OddPart (2^j*x) = x\\<close>\n  have \\<open>x \\<in> OddPart ` (ErdosNicolasSet n d)\\<close> \n    by (metis image_eqI)\n  thus ?thesis by blast\nqed\n\nlemma ErdosNicolasSetOddDivSetSurjB:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>(OddDivSet n (d::real)) \\<subseteq>  (OddPart ` ((ErdosNicolasSet n d))) \\<union> (OddPart ` (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\n  by (smt ErdosNicolasSetOddDivSetSurjBI ErdosNicolasSetOddDivSetSurjBII UnCI assms(1) assms(2) assms(3) assms(4) subsetI)\n\nlemma ErdosNicolasSetOddDivSetSurj:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open> OddPart ` ((ErdosNicolasSet n d) \\<union> (OddDivSet n ((d::real)/(2::real)^(k+1)))) = (OddDivSet n (d::real))\\<close>\n  using assms ErdosNicolasSetOddDivSetSurjA ErdosNicolasSetOddDivSetSurjB OddPartErdosNicolasSet\n  by (simp add: subset_antisym)\n\n\nlemma ErdosNicolasSetOddDivSetBij:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open> bij_betw OddPart ((ErdosNicolasSet n d) \\<union> (OddDivSet n ((d::real)/(2::real)^(k+1)))) (OddDivSet n (d::real))\\<close>\n  using assms ErdosNicolasSetOddDivSetInjOn ErdosNicolasSetOddDivSetSurj \n  by (simp add: bij_betw_def)\n\nlemma ErdosNicolasSetOddDivSetL:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>card (ErdosNicolasSet n d) + (card (OddDivSet n ((d::real)/(2::real)^(k+1)))) = (card (OddDivSet n (d::real)))\\<close>\nproof-\n  have \\<open>finite (ErdosNicolasSet n d)\\<close> \n    by (metis (no_types, lifting) CollectD ErdosNicolasSet_def finite_nat_set_iff_bounded_le )\n\n  have \\<open>finite (OddDivSet n (d::real))\\<close> using OddDivSet_def \n    by (metis (no_types, lifting) assms(1) assms(2) dvd_0_right dvd_imp_le finite_nat_set_iff_bounded_le mem_Collect_eq mult_eq_0_iff neq0_conv pos2 zero_less_power)\n\n  have \\<open>finite (OddDivSet n ((d::real)/(2::real)^(k+1)))\\<close> using OddDivSet_def\n    by (metis (no_types, lifting) assms(1) assms(2) dvd_0_right dvd_imp_le finite_nat_set_iff_bounded_le mem_Collect_eq mult_eq_0_iff neq0_conv pos2 zero_less_power)\n\n  have \\<open>card ((ErdosNicolasSet n d) \\<union> (OddDivSet n ((d::real)/(2::real)^(k+1)))) = card (OddDivSet n (d::real))\\<close>\n    using ErdosNicolasSetOddDivSetBij \n    by (meson assms(1) assms(2) assms(3) assms(4) bij_betw_same_card)\n\n  have \\<open> (ErdosNicolasSet n d) \\<inter> (OddDivSet n ((d::real)/(2::real)^(k+1))) = {}\\<close>\n    using ErdosNicolasSetOddDivSetLInter \n    using assms(1) assms(2) assms(3) assms(4) by blast\n  show ?thesis \n    using \\<open>ErdosNicolasSet n d \\<inter> OddDivSet n (real d / 2 ^ (k + 1)) = {}\\<close> \\<open>card (ErdosNicolasSet n d \\<union> OddDivSet n (real d / 2 ^ (k + 1))) = card (OddDivSet n (real d))\\<close> \\<open>finite (ErdosNicolasSet n d)\\<close> \\<open>finite (OddDivSet n (real d / 2 ^ (k + 1)))\\<close> card_Un_disjoint by fastforce\nqed\n\nlemma ErdosNicolasSetOddDivSetLL:\n  fixes n k m d :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>card (ErdosNicolasSet n d) = (card (OddDivSet n (d::real))) - (card (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\n  using ErdosNicolasSetOddDivSetL assms \n  by (metis diff_add_inverse2)\n\n\nproposition ErdosNicolasOddDivSet:\n  fixes n k m :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> \n  shows \\<open>ErdosNicolas n\n   = Max{ (card (OddDivSet n (real d))) - (card (OddDivSet n ((real d)/(2::real)^(k+1)))) \n          |d :: nat. d dvd n \\<and> odd d}\\<close>\nproof-\n  have \\<open>n \\<ge> 1\\<close> \n    by (simp add: Suc_leI assms(1) assms(2) odd_pos)\n  hence \\<open>ErdosNicolas n = Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d}\\<close>\n    using ErdosNicolasOdd by auto\n  have \\<open>\\<forall> d::nat. d dvd n \\<and> odd d \\<longrightarrow> card (ErdosNicolasSet n d) = (card (OddDivSet n (d::real))) - (card (OddDivSet n ((d::real)/(2::real)^(k+1))))\\<close>\n    using ErdosNicolasSetOddDivSetLL assms(1) assms(2) by blast\n  thus ?thesis using  \\<open>ErdosNicolas n = Max { card (ErdosNicolasSet n d) | d :: nat. d dvd n \\<and> odd d}\\<close>\n    by (smt Collect_cong)\nqed\n\n\n\nlemma preErdosNicolasSetDiffIncl:\n  fixes n k m :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) \\<subseteq> (OddDivSet n (real d))\\<close>\nproof-\n  have \\<open>(OddDivSet n (real d)) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> (real d)}\\<close> \n    using OddDivSet_def by presburger\n  have \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> (real d)/(2::real)^(k+1)}\\<close> \n    using OddDivSet_def by presburger\n  have \\<open>(real d)/(2::real)^(k+1) \\<le> (real d)\\<close> \n    by (smt assms(4) div_by_1 frac_le odd_pos of_nat_0_less_iff one_le_power)\n  hence \\<open>\\<forall> e :: nat. e \\<le> (real d)/(2::real)^(k+1) \\<longrightarrow> e \\<le> (real d)\\<close> \n    using order_trans by blast\n  show ?thesis using  \\<open>\\<forall> e :: nat. e \\<le> (real d)/(2::real)^(k+1) \\<longrightarrow> e \\<le> (real d)\\<close>\n      \\<open>(OddDivSet n (real d)) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> (real d)}\\<close> \n      \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> (real d)/(2::real)^(k+1)}\\<close> \n    by blast\nqed\n\n\nlemma preErdosNicolasSetDiff:\n  fixes n k m :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>ErdosNicolasSetOdd n k d  = (OddDivSet n (real d)) - (OddDivSet n ((real d)/(2::real)^(k+1)))\\<close>\nproof-\n  have \\<open>(OddDivSet n (real d)) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> (real d)}\\<close> \n    using OddDivSet_def by presburger\n  hence \\<open>(OddDivSet n (real d)) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le>  d}\\<close> \n    by auto\n  have \\<open>(2::nat)^(k+1) > 0\\<close> \n    by simp\n  have \\<open>\\<forall> e :: nat.  e \\<le> (real d)/(2::real)^(k+1) \\<longleftrightarrow> e \\<le> d/(2::nat)^(k+1)\\<close>\n    by simp\n  hence \\<open>\\<forall> e :: nat.  e \\<le> (real d)/(2::real)^(k+1) \\<longleftrightarrow> e*(2::nat)^(k+1) \\<le> (d/(2::nat)^(k+1))*(2::nat)^(k+1)\\<close>\n    using  \\<open>(2::nat)^(k+1) > 0\\<close>  \n    by (smt of_nat_0_less_iff of_nat_mult real_mult_less_iff1)\n  hence \\<open>\\<forall> e :: nat.  e \\<le> (real d)/(2::real)^(k+1) \\<longleftrightarrow> e*(2::nat)^(k+1) \\<le> d*((2::nat)^(k+1)/(2::nat)^(k+1))\\<close>\n    by simp\n  hence  \\<open>\\<forall> e :: nat.  e \\<le> (real d)/(2::real)^(k+1) \\<longleftrightarrow> e*(2::nat)^(k+1) \\<le> d*1\\<close>\n    by simp\n  hence  \\<open>\\<forall> e :: nat.  e \\<le> (real d)/(2::real)^(k+1) \\<longleftrightarrow> e*(2::nat)^(k+1) \\<le> d\\<close>\n    by simp\n  have \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> (real d)/(2::real)^(k+1)}\\<close>\n    using OddDivSet_def by presburger\n  hence  \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. e dvd n \\<and> odd e \\<and> e*(2::nat)^(k+1) \\<le> d }\\<close>\n    using  \\<open>\\<forall> e :: nat.  e \\<le> (real d)/(2::real)^(k+1) \\<longleftrightarrow> e*(2::nat)^(k+1) \\<le> d\\<close> \n    by (smt Collect_cong of_nat_le_iff of_nat_mult) \n  from  \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. e dvd n \\<and> odd e \\<and> e*(2::nat)^(k+1) \\<le> d }\\<close>\n  have \\<open> - (OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. \\<not>(e dvd n \\<and> odd e \\<and> e*(2::nat)^(k+1) \\<le> d) }\\<close>\n    by auto\n  from  \\<open>(OddDivSet n (real d)) = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> d}\\<close>\n    \\<open> - (OddDivSet n ((real d)/(2::real)^(k+1))) = {e | e::nat. \\<not>(e dvd n \\<and> odd e \\<and> e*(2::nat)^(k+1) \\<le> d) }\\<close>\n  have \\<open>(OddDivSet n (real d)) - (OddDivSet n ((real d)/(2::real)^(k+1)))\n        = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> d} \\<inter> {e | e::nat. \\<not>(e dvd n \\<and> odd e \\<and> e*(2::nat)^(k+1) \\<le> d) }\\<close>\n    by auto    \n  hence  \\<open>(OddDivSet n (real d)) - (OddDivSet n ((real d)/(2::real)^(k+1)))\n        = {e | e::nat. (e dvd n \\<and> odd e \\<and> e \\<le> d) \\<and>  \\<not>(e dvd n \\<and> odd e \\<and> e*(2::nat)^(k+1) \\<le> d) }\\<close>\n    by blast\n  hence   \\<open>(OddDivSet n (real d)) - (OddDivSet n ((real d)/(2::real)^(k+1)))\n        = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> d \\<and>  \\<not>( e*(2::nat)^(k+1) \\<le> d) }\\<close>\n    by auto\n  hence   \\<open>(OddDivSet n (real d)) - (OddDivSet n ((real d)/(2::real)^(k+1)))\n        = {e | e::nat. e dvd n \\<and> odd e \\<and> e \\<le> d \\<and>  d < 2^(k+1)*e }\\<close>\n    by (smt Collect_cong Groups.mult_ac(2) linorder_not_le)\n  have \\<open>ErdosNicolasSetOdd n k d = {e | e::nat. e dvd n \\<and> odd e \\<and>  e \\<le> d \\<and> d < 2^(k+1)*e}\\<close>\n    using ErdosNicolasSetOdd_def by presburger\n  show ?thesis \n    using \\<open>ErdosNicolasSetOdd n k d = {e |e. e dvd n \\<and> odd e \\<and> e \\<le> d \\<and> d < 2 ^ (k + 1) * e}\\<close> \\<open>OddDivSet n (real d) - OddDivSet n (real d / 2 ^ (k + 1)) = {e |e. e dvd n \\<and> odd e \\<and> e \\<le> d \\<and> d < 2 ^ (k + 1) * e}\\<close> by auto\nqed\n\nlemma ErdosNicolasSetDiff:\n  fixes n k m :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> and \\<open>d dvd n\\<close> and \\<open>odd d\\<close> \n  shows \\<open>card (ErdosNicolasSetOdd n k d) = (card (OddDivSet n (real d))) - (card (OddDivSet n ((real d)/(2::real)^(k+1))))\\<close>\nproof-\n  have \\<open>finite (ErdosNicolasSetOdd n k d)\\<close> \n    by (metis (no_types, lifting) CollectD ErdosNicolasSetOdd_def finite_nat_set_iff_bounded_le   )\n  have \\<open>finite (OddDivSet n (real d))\\<close> \n    by (metis (no_types, lifting) CollectD OddDivSet_def finite_nat_set_iff_bounded_le of_nat_le_iff) \n  have \\<open>(OddDivSet n ((real d)/(2::real)^(k+1))) \\<subseteq> (OddDivSet n (real d))\\<close> \n    using assms(1) assms(2) assms(3) assms(4) preErdosNicolasSetDiffIncl by blast\n  hence \\<open>finite (OddDivSet n ((real d)/(2::real)^(k+1)))\\<close> using \\<open>finite (OddDivSet n (real d))\\<close> \n    by (meson finite_nat_set_iff_bounded_le subsetCE)\n  have  \\<open>ErdosNicolasSetOdd n k d  = (OddDivSet n (real d)) - (OddDivSet n ((real d)/(2::real)^(k+1)))\\<close>\n    using assms(1) assms(2) assms(3) assms(4) preErdosNicolasSetDiff by blast\n  show ?thesis \n    using \\<open>ErdosNicolasSetOdd n k d = OddDivSet n (real d) - OddDivSet n (real d / 2 ^ (k + 1))\\<close> \\<open>OddDivSet n (real d / 2 ^ (k + 1)) \\<subseteq> OddDivSet n (real d)\\<close> \\<open>finite (OddDivSet n (real d / 2 ^ (k + 1)))\\<close> card_Diff_subset by auto\nqed\n\nsection {* Main Result *}\n\ntheorem ErdosNicolasOddDivSetOdd:\n  fixes n k m :: nat\n  assumes \\<open>n = (2::nat)^k*m\\<close> and \\<open>odd m\\<close> \n  shows \\<open>ErdosNicolas n = Max { card (ErdosNicolasSetOdd n k d) | d :: nat. d dvd n \\<and> odd d}\\<close>\nproof-\n  have \\<open>ErdosNicolas n\n   = Max{ (card (OddDivSet n (real d))) - (card (OddDivSet n ((real d)/(2::real)^(k+1)))) \n          |d :: nat. d dvd n \\<and> odd d}\\<close> \n    using ErdosNicolasOddDivSet assms(1) assms(2) by auto\n  have \\<open>\\<forall> d :: nat. d dvd n \\<and> odd d \\<longrightarrow> card (ErdosNicolasSetOdd n k d)  = (card (OddDivSet n (real d))) - (card (OddDivSet n ((real d)/(2::real)^(k+1))))\\<close>\n    using ErdosNicolasSetDiff assms(1) assms(2) by blast\n  show ?thesis  using  \\<open>ErdosNicolas n\n   = Max{ (card (OddDivSet n (real d))) - (card (OddDivSet n ((real d)/(2::real)^(k+1)))) \n          |d :: nat. d dvd n \\<and> odd d}\\<close> \n      \\<open>\\<forall> d :: nat. d dvd n \\<and> odd d \\<longrightarrow> card (ErdosNicolasSetOdd n k d)  = (card (OddDivSet n (real d))) - (card (OddDivSet n ((real d)/(2::real)^(k+1))))\\<close>\n    by (smt Collect_cong)\nqed\n\nend\n\n", "meta": {"author": "josephcmac", "repo": "Folklore-and-miscellaneous-results-in-number-theory", "sha": "e7385a025637dbf07b4f9172c0691e46cf6c9664", "save_path": "github-repos/isabelle/josephcmac-Folklore-and-miscellaneous-results-in-number-theory", "path": "github-repos/isabelle/josephcmac-Folklore-and-miscellaneous-results-in-number-theory/Folklore-and-miscellaneous-results-in-number-theory-e7385a025637dbf07b4f9172c0691e46cf6c9664/ErdosNicolasOdd.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.8596637487122111, "lm_q1q2_score": 0.7557706112695931}}
{"text": "theory Ex4_6\nimports\n  \"~~/src/HOL/IMP/AExp\"\nbegin\n\n(*\nBy: Vadim Zaliva <vzaliva@cmu.edu>\nFrom: T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL. Springer, 2014.\nExercise 4.6:\n*)\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n  n: \"aval_rel (N n) s n\" |\n  v: \"aval_rel (V x) s (s x)\" |\n  p: \"\\<lbrakk>aval_rel a\\<^sub>1 s v\\<^sub>1; aval_rel a\\<^sub>2 s v\\<^sub>2\\<rbrakk> \\<Longrightarrow> aval_rel (Plus a\\<^sub>1 a\\<^sub>2) s (v\\<^sub>1 + v\\<^sub>2)\"\n\nlemma aeq1: \"aval_rel a s v \\<Longrightarrow> (aval a s = v)\"\n  apply(induction rule: aval_rel.induct)\n  apply(auto)\ndone\n\nlemma aeq2: \"((aval a s) = v) \\<Longrightarrow> (aval_rel a s v)\"\n  apply(induction a arbitrary: s v)\n  apply(simp_all)\n  apply(auto)\n  apply(rule aval_rel.n)\n  apply(rule aval_rel.v)\n  apply(rule aval_rel.p)\n  apply(auto)\ndone\n\ntheorem \"((aval a s) = v) = (aval_rel a s v)\"\n  apply(auto)\n  apply(rule aeq2)\n  apply(simp)\n  apply(rule aeq1)\n  apply(simp)\ndone\n", "meta": {"author": "vzaliva", "repo": "isabelle-semantics-ex", "sha": "4e1acf1c9850f17057dd98454e42262d01301670", "save_path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex", "path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex/isabelle-semantics-ex-4e1acf1c9850f17057dd98454e42262d01301670/Ex4_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8418256532040708, "lm_q1q2_score": 0.7557029302646388}}
{"text": "(*<*)theory Even imports \"../Setup\" begin(*>*)\n\nsection\\<open>The Set of Even Numbers\\<close>\n\ntext \\<open>\n\\index{even numbers!defining inductively|(}%\nThe set of even numbers can be inductively defined as the least set\ncontaining 0 and closed under the operation $+2$.  Obviously,\n\\emph{even} can also be expressed using the divides relation (\\<open>dvd\\<close>). \nWe shall prove below that the two formulations coincide.  On the way we\nshall examine the primary means of reasoning about inductively defined\nsets: rule induction.\n\\<close>\n\nsubsection\\<open>Making an Inductive Definition\\<close>\n\ntext \\<open>\nUsing \\commdx{inductive\\protect\\_set}, we declare the constant \\<open>even\\<close> to be\na set of natural numbers with the desired properties.\n\\<close>\n\ninductive_set even :: \"nat set\" where\nzero[intro!]: \"0 \\<in> even\" |\nstep[intro!]: \"n \\<in> even \\<Longrightarrow> (Suc (Suc n)) \\<in> even\"\n\ntext \\<open>\nAn inductive definition consists of introduction rules.  The first one\nabove states that 0 is even; the second states that if $n$ is even, then so\nis~$n+2$.  Given this declaration, Isabelle generates a fixed point\ndefinition for \\<^term>\\<open>even\\<close> and proves theorems about it,\nthus following the definitional approach (see {\\S}\\ref{sec:definitional}).\nThese theorems\ninclude the introduction rules specified in the declaration, an elimination\nrule for case analysis and an induction rule.  We can refer to these\ntheorems by automatically-generated names.  Here are two examples:\n@{named_thms[display,indent=0] even.zero[no_vars] (even.zero) even.step[no_vars] (even.step)}\n\nThe introduction rules can be given attributes.  Here\nboth rules are specified as \\isa{intro!},%\n\\index{intro\"!@\\isa {intro\"!} (attribute)}\ndirecting the classical reasoner to \napply them aggressively. Obviously, regarding 0 as even is safe.  The\n\\<open>step\\<close> rule is also safe because $n+2$ is even if and only if $n$ is\neven.  We prove this equivalence later.\n\\<close>\n\nsubsection\\<open>Using Introduction Rules\\<close>\n\ntext \\<open>\nOur first lemma states that numbers of the form $2\\times k$ are even.\nIntroduction rules are used to show that specific values belong to the\ninductive set.  Such proofs typically involve \ninduction, perhaps over some other inductive set.\n\\<close>\n\nlemma two_times_even[intro!]: \"2*k \\<in> even\"\napply (induct_tac k)\n apply auto\ndone\n(*<*)\nlemma \"2*k \\<in> even\"\napply (induct_tac k)\n(*>*)\ntxt \\<open>\n\\noindent\nThe first step is induction on the natural number \\<open>k\\<close>, which leaves\ntwo subgoals:\n@{subgoals[display,indent=0,margin=65]}\nHere \\<open>auto\\<close> simplifies both subgoals so that they match the introduction\nrules, which are then applied automatically.\n\nOur ultimate goal is to prove the equivalence between the traditional\ndefinition of \\<open>even\\<close> (using the divides relation) and our inductive\ndefinition.  One direction of this equivalence is immediate by the lemma\njust proved, whose \\<open>intro!\\<close> attribute ensures it is applied automatically.\n\\<close>\n(*<*)oops(*>*)\nlemma dvd_imp_even: \"2 dvd n \\<Longrightarrow> n \\<in> even\"\nby (auto simp add: dvd_def)\n\nsubsection\\<open>Rule Induction \\label{sec:rule-induction}\\<close>\n\ntext \\<open>\n\\index{rule induction|(}%\nFrom the definition of the set\n\\<^term>\\<open>even\\<close>, Isabelle has\ngenerated an induction rule:\n@{named_thms [display,indent=0,margin=40] even.induct [no_vars] (even.induct)}\nA property \\<^term>\\<open>P\\<close> holds for every even number provided it\nholds for~\\<open>0\\<close> and is closed under the operation\n\\isa{Suc(Suc \\(\\cdot\\))}.  Then \\<^term>\\<open>P\\<close> is closed under the introduction\nrules for \\<^term>\\<open>even\\<close>, which is the least set closed under those rules. \nThis type of inductive argument is called \\textbf{rule induction}. \n\nApart from the double application of \\<^term>\\<open>Suc\\<close>, the induction rule above\nresembles the familiar mathematical induction, which indeed is an instance\nof rule induction; the natural numbers can be defined inductively to be\nthe least set containing \\<open>0\\<close> and closed under~\\<^term>\\<open>Suc\\<close>.\n\nInduction is the usual way of proving a property of the elements of an\ninductively defined set.  Let us prove that all members of the set\n\\<^term>\\<open>even\\<close> are multiples of two.\n\\<close>\n\nlemma even_imp_dvd: \"n \\<in> even \\<Longrightarrow> 2 dvd n\"\ntxt \\<open>\nWe begin by applying induction.  Note that \\<open>even.induct\\<close> has the form\nof an elimination rule, so we use the method \\<open>erule\\<close>.  We get two\nsubgoals:\n\\<close>\napply (erule even.induct)\ntxt \\<open>\n@{subgoals[display,indent=0]}\nWe unfold the definition of \\<open>dvd\\<close> in both subgoals, proving the first\none and simplifying the second:\n\\<close>\napply (simp_all add: dvd_def)\ntxt \\<open>\n@{subgoals[display,indent=0]}\nThe next command eliminates the existential quantifier from the assumption\nand replaces \\<open>n\\<close> by \\<open>2 * k\\<close>.\n\\<close>\napply clarify\ntxt \\<open>\n@{subgoals[display,indent=0]}\nTo conclude, we tell Isabelle that the desired value is\n\\<^term>\\<open>Suc k\\<close>.  With this hint, the subgoal falls to \\<open>simp\\<close>.\n\\<close>\napply (rule_tac x = \"Suc k\" in exI, simp)\n(*<*)done(*>*)\n\ntext \\<open>\nCombining the previous two results yields our objective, the\nequivalence relating \\<^term>\\<open>even\\<close> and \\<open>dvd\\<close>. \n%\n%we don't want [iff]: discuss?\n\\<close>\n\ntheorem even_iff_dvd: \"(n \\<in> even) = (2 dvd n)\"\nby (blast intro: dvd_imp_even even_imp_dvd)\n\n\nsubsection\\<open>Generalization and Rule Induction \\label{sec:gen-rule-induction}\\<close>\n\ntext \\<open>\n\\index{generalizing for induction}%\nBefore applying induction, we typically must generalize\nthe induction formula.  With rule induction, the required generalization\ncan be hard to find and sometimes requires a complete reformulation of the\nproblem.  In this  example, our first attempt uses the obvious statement of\nthe result.  It fails:\n\\<close>\n\nlemma \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\napply (erule even.induct)\noops\n(*<*)\nlemma \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\napply (erule even.induct)\n(*>*)\ntxt \\<open>\nRule induction finds no occurrences of \\<^term>\\<open>Suc(Suc n)\\<close> in the\nconclusion, which it therefore leaves unchanged.  (Look at\n\\<open>even.induct\\<close> to see why this happens.)  We have these subgoals:\n@{subgoals[display,indent=0]}\nThe first one is hopeless.  Rule induction on\na non-variable term discards information, and usually fails.\nHow to deal with such situations\nin general is described in {\\S}\\ref{sec:ind-var-in-prems} below.\nIn the current case the solution is easy because\nwe have the necessary inverse, subtraction:\n\\<close>\n(*<*)oops(*>*)\nlemma even_imp_even_minus_2: \"n \\<in> even \\<Longrightarrow> n - 2 \\<in> even\"\napply (erule even.induct)\n apply auto\ndone\n(*<*)\nlemma \"n \\<in>  even \\<Longrightarrow> n - 2 \\<in> even\"\napply (erule even.induct)\n(*>*)\ntxt \\<open>\nThis lemma is trivially inductive.  Here are the subgoals:\n@{subgoals[display,indent=0]}\nThe first is trivial because \\<open>0 - 2\\<close> simplifies to \\<open>0\\<close>, which is\neven.  The second is trivial too: \\<^term>\\<open>Suc (Suc n) - 2\\<close> simplifies to\n\\<^term>\\<open>n\\<close>, matching the assumption.%\n\\index{rule induction|)}  %the sequel isn't really about induction\n\n\\medskip\nUsing our lemma, we can easily prove the result we originally wanted:\n\\<close>\n(*<*)oops(*>*)\nlemma Suc_Suc_even_imp_even: \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"\nby (drule even_imp_even_minus_2, simp)\n\ntext \\<open>\nWe have just proved the converse of the introduction rule \\<open>even.step\\<close>.\nThis suggests proving the following equivalence.  We give it the\n\\attrdx{iff} attribute because of its obvious value for simplification.\n\\<close>\n\n\n\n\nsubsection\\<open>Rule Inversion \\label{sec:rule-inversion}\\<close>\n\ntext \\<open>\n\\index{rule inversion|(}%\nCase analysis on an inductive definition is called \\textbf{rule\ninversion}.  It is frequently used in proofs about operational\nsemantics.  It can be highly effective when it is applied\nautomatically.  Let us look at how rule inversion is done in\nIsabelle/HOL\\@.\n\nRecall that \\<^term>\\<open>even\\<close> is the minimal set closed under these two rules:\n@{thm [display,indent=0] even.intros [no_vars]}\nMinimality means that \\<^term>\\<open>even\\<close> contains only the elements that these\nrules force it to contain.  If we are told that \\<^term>\\<open>a\\<close>\nbelongs to\n\\<^term>\\<open>even\\<close> then there are only two possibilities.  Either \\<^term>\\<open>a\\<close> is \\<open>0\\<close>\nor else \\<^term>\\<open>a\\<close> has the form \\<^term>\\<open>Suc(Suc n)\\<close>, for some suitable \\<^term>\\<open>n\\<close>\nthat belongs to\n\\<^term>\\<open>even\\<close>.  That is the gist of the \\<^term>\\<open>cases\\<close> rule, which Isabelle proves\nfor us when it accepts an inductive definition:\n@{named_thms [display,indent=0,margin=40] even.cases [no_vars] (even.cases)}\nThis general rule is less useful than instances of it for\nspecific patterns.  For example, if \\<^term>\\<open>a\\<close> has the form\n\\<^term>\\<open>Suc(Suc n)\\<close> then the first case becomes irrelevant, while the second\ncase tells us that \\<^term>\\<open>n\\<close> belongs to \\<^term>\\<open>even\\<close>.  Isabelle will generate\nthis instance for us:\n\\<close>\n\ninductive_cases Suc_Suc_cases [elim!]: \"Suc(Suc n) \\<in> even\"\n\ntext \\<open>\nThe \\commdx{inductive\\protect\\_cases} command generates an instance of\nthe \\<open>cases\\<close> rule for the supplied pattern and gives it the supplied name:\n@{named_thms [display,indent=0] Suc_Suc_cases [no_vars] (Suc_Suc_cases)}\nApplying this as an elimination rule yields one case where \\<open>even.cases\\<close>\nwould yield two.  Rule inversion works well when the conclusions of the\nintroduction rules involve datatype constructors like \\<^term>\\<open>Suc\\<close> and \\<open>#\\<close>\n(list ``cons''); freeness reasoning discards all but one or two cases.\n\nIn the \\isacommand{inductive\\_cases} command we supplied an\nattribute, \\<open>elim!\\<close>,\n\\index{elim\"!@\\isa {elim\"!} (attribute)}%\nindicating that this elimination rule can be\napplied aggressively.  The original\n\\<^term>\\<open>cases\\<close> rule would loop if used in that manner because the\npattern~\\<^term>\\<open>a\\<close> matches everything.\n\nThe rule \\<open>Suc_Suc_cases\\<close> is equivalent to the following implication:\n@{term [display,indent=0] \"Suc (Suc n) \\<in> even \\<Longrightarrow> n \\<in> even\"}\nJust above we devoted some effort to reaching precisely\nthis result.  Yet we could have obtained it by a one-line declaration,\ndispensing with the lemma \\<open>even_imp_even_minus_2\\<close>. \nThis example also justifies the terminology\n\\textbf{rule inversion}: the new rule inverts the introduction rule\n\\<open>even.step\\<close>.  In general, a rule can be inverted when the set of elements\nit introduces is disjoint from those of the other introduction rules.\n\nFor one-off applications of rule inversion, use the \\methdx{ind_cases} method. \nHere is an example:\n\\<close>\n\n(*<*)lemma \"Suc(Suc n) \\<in> even \\<Longrightarrow> P\"(*>*)\napply (ind_cases \"Suc(Suc n) \\<in> even\")\n(*<*)oops(*>*)\n\ntext \\<open>\nThe specified instance of the \\<open>cases\\<close> rule is generated, then applied\nas an elimination rule.\n\nTo summarize, every inductive definition produces a \\<open>cases\\<close> rule.  The\n\\commdx{inductive\\protect\\_cases} command stores an instance of the\n\\<open>cases\\<close> rule for a given pattern.  Within a proof, the\n\\<open>ind_cases\\<close> method applies an instance of the \\<open>cases\\<close>\nrule.\n\nThe even numbers example has shown how inductive definitions can be\nused.  Later examples will show that they are actually worth using.%\n\\index{rule inversion|)}%\n\\index{even numbers!defining inductively|)}\n\\<close>\n\n(*<*)end(*>*)\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Doc/Tutorial/Inductive/Even.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7557029128778258}}
{"text": "theory Chapter5\n  imports \"~~/src/HOL/IMP/ASM\"\nbegin\n\n(* Exercise 5.1. Give a readable, structured proof of the following lemma: *)\n\nlemma assumes T : \"\\<forall> x y. T x y \\<or> T y x\"\nand A: \"\\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\nand TA: \"\\<forall> x y. T x y \\<longrightarrow> A x y\"\nand \"A x y\"\nshows \"T x y\"\nproof (rule ccontr)\n  assume \"\\<not> T x y\"\n  from this and T have \"T y x\" by blast\n  from this and TA have \"A y x\" by simp\n  from this and `A x y` and A have \"x = y\" by simp\n  from this and `T y x` have \"T x y\" by simp\n  from this and `\\<not> T x y` show \"False\" by simp\nqed\n\n(*\nExercise 5.2. Give a readable, structured proof of the following lemma:\n\nlemma \"\\<exists> ys zs. xs = ys @ zs \\<and> (length ys = length zs \\<or> length ys = length zs + 1)\"\n\nHint: There are predefined functions take :: nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list and drop\n:: nat \\<Rightarrow> 'a list \\<Rightarrow> 'a list such that take k [x 1,. . .] = [x 1 ,. . .,x k ] and drop k\n[x 1 ,. . .] = [x k +1 ,. . .]. Let sledgehammer find and apply the relevant take and\ndrop lemmas for you.\n*)\n\nlemma \"(\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs) \\<or>\n (\\<exists> ys zs. xs = ys @ zs \\<and> length ys = length zs + 1)\" (is \"?P \\<or> ?Q\")\nproof cases\n  assume \"even (length xs)\" \n  then obtain k where lxs: \"(length xs) = 2*k\" by auto\n  obtain ys where ys: \"ys = take k xs\" by simp\n  obtain zs where zs: \"zs = drop k xs\" by simp\n  from ys and lxs have lys: \"length ys = k\" by simp\n  from zs and lxs have lzs: \"length zs = k\" by simp\n  from ys and zs have \"xs = ys @ zs\" by simp\n  moreover from lys and lzs have \"length ys = length zs\" by simp\n  ultimately show ?thesis by blast\nnext\n  assume \"odd (length xs)\"\n  then obtain k where lxs: \"(length xs) = 2*k + 1\" using oddE by blast\n  obtain ys where ys: \"ys = take (Suc k) xs\" by simp\n  obtain zs where zs: \"zs = drop (Suc k) xs\" by simp\n  from ys and lxs have lys: \"length ys = (Suc k)\" by simp\n  from zs and lxs have lzs: \"length zs = k\" by simp\n  from ys and zs have \"xs = ys @ zs\" by simp\n  moreover from lys and lzs have \"length ys = length zs + 1\" by simp\n  ultimately show ?thesis by blast\nqed\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS : \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\n(* Simple exercise from 5.4.5 *)\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\"\nproof\n  assume \"ev (Suc (Suc (Suc 0)))\" then show False using ev.cases nat.distinct(1) by auto\nqed\n\n(* Exercise 5.4. Give a structured proof of \\<not> ev (Suc (Suc (Suc 0))) by rule\ninversions. If there are no cases to be proved you can close a proof immediately\nwith qed. *)\nlemma \"\\<not> ev (Suc (Suc (Suc 0)))\" (is \"\\<not> ?P\")\nproof\n  assume \"?P\"\n  hence \"ev (Suc 0)\" by cases\n  thus False by cases\nqed\n\n(* Exercise 5.5. Recall predicate star from Section 4.5.2 and iter from Exer-\ncise 4.4. Prove iter r n x y =\\<Rightarrow> star r x y in a structured style; do not just\nsledgehammer each case of the required induction. *)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl : \"star r x x\" |\nstep : \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nit0 : \"iter r 0 x x\" |\nitSS : \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma \"iter r n x y \\<Longrightarrow> star r x y\" (is \"?P \\<Longrightarrow> ?Q\")\nproof (induction rule: iter.induct)\n  case (it0 x)\n  then show ?case by (rule star.refl) \nnext\n  case (itSS x)\n  then show ?case by (simp add: star.step)\nqed\n\n(* Exercise 5.6. Define a recursive function elems :: 'a list \\<Rightarrow> 'a set and prove\nx \\<in> elems xs =\\<Rightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<in>/ elems ys. *)\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n\"elems [] = {}\" |\n\"elems (x # xs) = {x} \\<union> elems xs\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists> ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"\nproof (induction xs)\n  case Nil\n  then show ?case by simp\nnext\n  case (Cons a xs)\n  then show ?case\n  proof cases\n    assume \"a = x\"\n    then show ?thesis by fastforce\n  next\n    assume \"a \\<noteq> x\"\n    moreover obtain ys zs where\n    \"ys = []\" \"zs = xs\" by simp \n    ultimately show ?thesis by (metis Cons.prems Un_iff append.simps(2) elems.simps(2) empty_iff insert_iff local.Cons(1))\n  qed\nqed\n\n(* Exercise 5.7. Extend Exercise 4.5 with a function that checks if some\nalpha list is a balanced string of parentheses. More precisely, define a recursive\nfunction balanced :: nat \\<Rightarrow> alpha list \\<Rightarrow> bool such that balanced n w is true\niff (informally) S (a n @ w ). Formally, prove that balanced n w = S (replicate\nn a @ w ) where replicate :: nat \\<Rightarrow> 'a \\<Rightarrow> 'a list is predefined and replicate\nn x yields the list [x , . . ., x ] of length n. *)\n\ndatatype alpha = ay | be | ce | de | ee | ef | ge \n\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS0 : \"S []\" |\nSw : \"S w \\<Longrightarrow> S (a # w @ [b])\" |\nSc : \"S w1 \\<Longrightarrow> S w2 \\<Longrightarrow> S (w1 @ w2)\"\n\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nT0 : \"T []\" |\nTw : \"T w \\<Longrightarrow> T x \\<Longrightarrow> T (w @ [a] @ x @ [b])\"\n\nlemma T_comm: \"T w \\<Longrightarrow> T x \\<Longrightarrow> T (x @ w)\"\n  apply(induction rule: T.induct)\n   apply(simp)\n  apply(metis Tw append_assoc)\n  done\n\nlemma T_implies_S: \"T w \\<Longrightarrow> S w\"\n  apply(induction rule: T.induct)\n   apply(metis S0)\n  apply(simp add: Sw Sc)\n  done\n\nlemma S_implies_T: \"S w \\<Longrightarrow> T w\"\n  apply(induction rule: S.induct)\n    apply(metis T0)\n   apply (metis Cons_eq_appendI T.simps self_append_conv2)\n  apply(simp add: T_comm)\n  done\n\ntheorem S_eq_T: \"S w = T w\"\n  apply(auto simp add: T_implies_S S_implies_T)\n  done\n\nfun replicate :: \"nat \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"replicate 0 _ = []\" |\n\"replicate n x = [x] @ (replicate (n - 1) x)\"\n\nfun balanced :: \"nat \\<Rightarrow> alpha list \\<Rightarrow> bool\" where\n(* not sure how to define this yet *)\n\nlemma \"balanced n w \\<Longrightarrow> S (replicate n a @ w)\"\n", "meta": {"author": "rasheedja", "repo": "concrete-semantics", "sha": "65997b65adccf690f076a79291aa643e2d1a9d43", "save_path": "github-repos/isabelle/rasheedja-concrete-semantics", "path": "github-repos/isabelle/rasheedja-concrete-semantics/concrete-semantics-65997b65adccf690f076a79291aa643e2d1a9d43/Chapter5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.8933094046341532, "lm_q1q2_score": 0.755688345435548}}
{"text": "theory Chapt2\n\nimports Main\n\nbegin\n\n(* Exercise 2.1 *)\n\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\n\n\n(* Exercise 2.2 *)\n\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double 0 = 0\" |\n\"double (Suc m) = Suc (Suc (double m))\"\n\nlemma add_01[simp]: \"add m (Suc n) = Suc (add m n)\"\n  apply(induction m)\n   apply(auto)\n  done\n        \nlemma add_02[simp]: \"add m 0 = m\"\n  apply(induction m)\n   apply(auto)\n  done\n\nlemma add_commutative[simp]: \"add m n = add n m\"\n  apply(induction m)\n   apply(auto)\n  done\n\nlemma add_associative[simp]: \"add x (add y z) = add (add x y) z\"\n  apply(induction x)\n   apply(auto)\n  done\n\nlemma add_double[simp]: \"double m = add m m\"\n  apply(induction m)\n   apply(auto)\n  done\n\n\n(* Exercise 2.3 *)\n\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count x Nil = 0\" |\n\"count y (x # xs) = (if x = y then Suc(count y xs) else count y xs)\"\n\nlemma count_inequality[simp]: \"count x xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n\n(* Exercise 2.4 *)\nfun snoc :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc [] x = [x]\" |\n\"snoc (x # xs) y = x # (snoc xs y)\"\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\" |\n\"reverse (x # xs) = snoc (reverse xs) x\"\n\nlemma reverse_01[simp] : \"reverse (snoc xs x) = x # reverse xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\nlemma double_reverse[simp] : \"reverse(reverse xs) = xs\"\n  apply(induction xs)\n   apply(auto)\n  done\n\n\n(* Exercise 2.5 *)\nfun sum_opto :: \"nat \\<Rightarrow> nat\" where\n\"sum_opto 0 = 0\" |\n\"sum_opto (Suc n) = (sum_opto n) + (Suc n)\"\n\nlemma formula_sum[simp] : \"sum_opto n = n * (n + 1) div 2\"\n  apply(induction n)\n   apply(auto)\n  done\n\nend", "meta": {"author": "nicolasAmat", "repo": "Concrete-Semantics", "sha": "c29ea48456f4edc9af80438521e1297a273a7553", "save_path": "github-repos/isabelle/nicolasAmat-Concrete-Semantics", "path": "github-repos/isabelle/nicolasAmat-Concrete-Semantics/Concrete-Semantics-c29ea48456f4edc9af80438521e1297a273a7553/Chapt2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.755688329019815}}
{"text": "theory Algebra1 \nimports Complex\nbegin \n\n\nlemma \"( (n::nat) +1 )^2 = n^2  + 2*n + 1^2\" \nproof -\n  show ?thesis by (simp only : power2_sum) \nqed \n\nlemma \"( Suc(n::nat)  )^2 = n^2  + 2*n + 1^2\" \nproof -\n  have \"( Suc(n::nat)  )^2 = ((n::nat)+1  )^2\" by auto\n  also have \"\\<dots> = n^2  + 2*n + 1^2\" unfolding power2_sum by auto\n  finally show ?thesis by auto \nqed \n\n\n\n\n", "meta": {"author": "SvenWille", "repo": "ProvingStuff", "sha": "ffc7914d23ffa7353406f7baf839d83383ad8787", "save_path": "github-repos/isabelle/SvenWille-ProvingStuff", "path": "github-repos/isabelle/SvenWille-ProvingStuff/ProvingStuff-ffc7914d23ffa7353406f7baf839d83383ad8787/Isabelle/Algebra/Algebra1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.8031738010682209, "lm_q1q2_score": 0.7556176775847746}}
{"text": "theory Chapter9_2\nimports \"HOL-IMP.Sec_Typing\" \"Short_Theory\"\nbegin\n\ntext{*\n\\exercise\nReformulate the inductive predicate @{const sec_type}\nas a recursive function and prove the equivalence of the two formulations:\n*}\n\nfun ok :: \"level \\<Rightarrow> com \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntheorem \"(l \\<turnstile> c) = ok l c\"\n(* your definition/proof here *)\n\ntext{*\nTry to reformulate the bottom-up system @{prop \"\\<turnstile> c : l\"}\nas a function that computes @{text l} from @{text c}. What difficulty do you face?\n\\endexercise\n\n\\exercise\nDefine a bottom-up termination insensitive security type system\n@{text\"\\<turnstile>' c : l\"} with subsumption rule:\n*}\n\ninductive sec_type2' :: \"com \\<Rightarrow> level \\<Rightarrow> bool\" (\"(\\<turnstile>'' _ : _)\" [0,0] 50) where\n(* your definition/proof here *)\n\ntext{*\nProve equivalence with the bottom-up system @{prop \"\\<turnstile> c : l\"}\nwithout subsumption rule:\n*}\n\nlemma \"\\<turnstile> c : l \\<Longrightarrow> \\<turnstile>' c : l\"\n(* your definition/proof here *)\n\nlemma \"\\<turnstile>' c : l \\<Longrightarrow> \\<exists>l' \\<ge> l. \\<turnstile> c : l'\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a function that erases those parts of a command that\ncontain variables above some security level: *}\n\nfun erase :: \"level \\<Rightarrow> com \\<Rightarrow> com\" where\n(* your definition/proof here *)\n\ntext{*\nFunction @{term \"erase l\"} should replace all assignments to variables with\nsecurity level @{text\"\\<ge> l\"} by @{const SKIP}.\nIt should also erase certain @{text IF}s and @{text WHILE}s,\ndepending on the security level of the boolean condition. Now show\nthat @{text c} and @{term \"erase l c\"} behave the same on the variables up\nto level @{text l}: *}\n\ntheorem \"\\<lbrakk> (c,s) \\<Rightarrow> s';  (erase l c,t) \\<Rightarrow> t';  0 \\<turnstile> c;  s = t (< l) \\<rbrakk>\n   \\<Longrightarrow> s' = t' (< l)\"\n(* your definition/proof here *)\n\ntext{* This theorem looks remarkably like the noninterference lemma from\ntheory \\mbox{@{short_theory \"Sec_Typing\"}} (although @{text\"\\<le>\"} has been replaced by @{text\"<\"}).\nYou may want to start with that proof and modify it.\nThe structure should remain the same. You may also need one or\ntwo simple additional lemmas.\n\nIn the theorem above we assume that both @{term\"(c,s)\"}\nand @{term \"(erase l c,t)\"} terminate. How about the following two properties: *}\n\nlemma \"\\<lbrakk> (c,s) \\<Rightarrow> s';  0 \\<turnstile> c;  s = t (< l) \\<rbrakk>\n  \\<Longrightarrow> \\<exists>t'. (erase l c, t) \\<Rightarrow> t' \\<and> s' = t' (< l)\"\n(* your definition/proof here *)\n\n\nlemma \"\\<lbrakk> (erase l c,s) \\<Rightarrow> s';  0 \\<turnstile> c;  s = t (< l) \\<rbrakk>\n  \\<Longrightarrow> \\<exists>t'. (c,t) \\<Rightarrow> t' \\<and> s' = t' (< l)\"\n(* your definition/proof here *)\n\ntext{* Give proofs or counterexamples.\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "brando90", "repo": "isabelle-gym", "sha": "f4d231cb9f625422e873aa2c9c2c6f22b7da4b27", "save_path": "github-repos/isabelle/brando90-isabelle-gym", "path": "github-repos/isabelle/brando90-isabelle-gym/isabelle-gym-f4d231cb9f625422e873aa2c9c2c6f22b7da4b27/isar_brandos_resources/templates/Chapter9_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206738932334, "lm_q2_score": 0.8376199633332891, "lm_q1q2_score": 0.7554667617959856}}
{"text": "(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Library Additions for Complex Numbers\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Some additional lemmas about complex numbers.\\<close>\n\ntheory More_Complex\n  imports Complex_Main More_Transcendental Canonical_Angle\nbegin\n\ntext \\<open>Conjugation and @{term cis}\\<close>\n          \ndeclare cis_cnj[simp] \n\nlemma rcis_cnj: \n  shows \"cnj a = rcis (cmod a) (- arg a)\"\n  by (subst rcis_cmod_arg[of a, symmetric]) (simp add: rcis_def)\n\nlemmas complex_cnj = complex_cnj_diff complex_cnj_mult complex_cnj_add complex_cnj_divide complex_cnj_minus\n\ntext \\<open>Some properties for @{term complex_of_real}. Also, since it is often used in our\nformalization we abbreviate it to @{term cor}.\\<close>\n\nabbreviation cor :: \"real \\<Rightarrow> complex\" where\n  \"cor \\<equiv> complex_of_real\"\n\nlemma cmod_cis [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"cor (cmod a) * cis (arg a) = a\"\n  using assms\n  by (metis rcis_cmod_arg rcis_def)\n\nlemma cis_cmod [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"cis (arg a) * cor (cmod a) = a\"\n  using assms cmod_cis[of a]\n  by (simp add: field_simps)\n\nlemma cor_squared:\n  shows \"(cor x)\\<^sup>2 = cor (x\\<^sup>2)\"\n  by (simp add: power2_eq_square)\n\nlemma cor_sqrt_mult_cor_sqrt [simp]:\n  shows \"cor (sqrt A) * cor (sqrt A) = cor \\<bar>A\\<bar>\"\n  by (metis of_real_mult real_sqrt_mult_self)\n\nlemma cor_eq_0: \"cor x + \\<i> * cor y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n by (metis Complex_eq Im_complex_of_real Im_i_times Re_complex_of_real add_cancel_left_left of_real_eq_0_iff plus_complex.sel(2) zero_complex.code)\n\nlemma one_plus_square_neq_zero [simp]:\n  shows \"1 + (cor x)\\<^sup>2 \\<noteq> 0\"\n  by (metis (hide_lams, no_types) of_real_1 of_real_add of_real_eq_0_iff of_real_power power_one sum_power2_eq_zero_iff zero_neq_one)\n\ntext \\<open>Additional lemmas about @{term Complex} constructor. Following newer versions of Isabelle,\nthese should be deprecated.\\<close>\n\nlemma complex_real_two [simp]:\n  shows \"Complex 2 0 = 2\"\n  by (simp add: Complex_eq)\n\nlemma complex_double [simp]:\n  shows \"(Complex a b) * 2 = Complex (2*a) (2*b)\"\n  by (simp add: Complex_eq)\n\nlemma complex_half [simp]: \n  shows \"(Complex a b) / 2 = Complex (a/2) (b/2)\"\n  by (subst complex_eq_iff) auto\n\nlemma Complex_scale1:\n  shows \"Complex (a * b) (a * c) = cor a * Complex b c\"\n  unfolding complex_of_real_def\n  unfolding Complex_eq\n  by (auto simp add: field_simps)\n\nlemma Complex_scale2: \n  shows \"Complex (a * c) (b * c) = Complex a b * cor c\"\n  unfolding complex_of_real_def\n  unfolding Complex_eq\n  by (auto simp add: field_simps)\n\nlemma Complex_scale3: \n  shows \"Complex (a / b) (a / c) = cor a * Complex (1 / b) (1 / c)\"\n  unfolding complex_of_real_def\n  unfolding Complex_eq\n  by (auto simp add: field_simps)\n\n\n\nlemma Complex_Re_express_cnj:\n  shows \"Complex (Re z) 0 = (z + cnj z) / 2\"\n  by (cases z) (simp add: Complex_eq)\n\nlemma Complex_Im_express_cnj:\n  shows \"Complex 0 (Im z) = (z - cnj z)/2\"\n  by (cases z) (simp add: Complex_eq)\n\ntext \\<open>Additional properties of @{term cmod}.\\<close>\n\nlemma complex_mult_cnj_cmod:\n  shows \"z * cnj z = cor ((cmod z)\\<^sup>2)\"\n  using complex_norm_square\n  by auto\n\nlemma cmod_square: \n  shows \"(cmod z)\\<^sup>2 = Re (z * cnj z)\"\n  using complex_mult_cnj_cmod[of z]\n  by (simp add: power2_eq_square)\n\nlemma cor_cmod_power_4 [simp]:\n  shows \"cor (cmod z) ^ 4 = (z * cnj z)\\<^sup>2\"\n  by (simp add: complex_mult_cnj_cmod)\n\nlemma cnjE:\n  assumes \"x \\<noteq> 0\"\n  shows \"cnj x = cor ((cmod x)\\<^sup>2) / x\"\n  using complex_mult_cnj_cmod[of x] assms\n  by (auto simp add: field_simps)\n\nlemma cmod_cor_divide [simp]:\n  shows \"cmod (z / cor k) = cmod z / \\<bar>k\\<bar>\"\n  by (simp add: norm_divide)\n\nlemma cmod_mult_minus_left_distrib [simp]:\n  shows \"cmod (z*z1 - z*z2) = cmod z * cmod(z1 - z2)\"\n  by (metis norm_mult right_diff_distrib)\n\nlemma cmod_eqI:\n  assumes \"z1 * cnj z1 = z2 * cnj z2\"\n  shows \"cmod z1 = cmod z2\"\n  using assms\n  by (subst complex_mod_sqrt_Re_mult_cnj)+ auto\n\n\n\nlemma cmod_eq_one [simp]:\n  shows \"cmod a = 1 \\<longleftrightarrow> a*cnj a = 1\"\n  by (metis cmod_eqE cmod_eqI complex_cnj_one monoid_mult_class.mult.left_neutral norm_one)\n\ntext \\<open>We introduce @{term is_real} (the imaginary part of complex number is zero) and @{term is_imag}\n(real part of complex number is zero) operators and prove some of their properties.\\<close>\n\nabbreviation is_real where\n  \"is_real z \\<equiv> Im z = 0\"\n\nabbreviation is_imag where\n  \"is_imag z \\<equiv> Re z = 0\"\n\n\n\nlemma complex_eq_if_Re_eq:\n  assumes \"is_real z1\" and \"is_real z2\"\n  shows \"z1 = z2 \\<longleftrightarrow> Re z1 = Re z2\"\n  using assms\n  by (cases z1, cases z2) auto\n\nlemma mult_reals [simp]:\n  assumes \"is_real a\" and \"is_real b\"\n  shows \"is_real (a * b)\"\n  using assms\n  by auto\n\nlemma div_reals [simp]:\n  assumes \"is_real a\" and \"is_real b\"\n  shows \"is_real (a / b)\"\n  using assms\n  by (simp add: complex_is_Real_iff)\n\nlemma complex_of_real_Re [simp]:\n  assumes \"is_real k\"\n  shows \"cor (Re k) = k\"\n  using assms\n  by (cases k) (auto simp add: complex_of_real_def)\n\nlemma cor_cmod_real:\n  assumes \"is_real a\"\n  shows \"cor (cmod a) = a \\<or> cor (cmod a) = -a\"\n  using assms\n  unfolding cmod_def\n  by (cases \"Re a > 0\") auto\n\nlemma eq_cnj_iff_real:\n  shows \"cnj z = z \\<longleftrightarrow> is_real z\"\n  by (cases z) (simp add: Complex_eq)\n\nlemma eq_minus_cnj_iff_imag:\n  shows \"cnj z = -z \\<longleftrightarrow> is_imag z\"\n  by (cases z) (simp add: Complex_eq)\n\nlemma Re_divide_real:\n  assumes \"is_real b\" and \"b \\<noteq> 0\"\n  shows \"Re (a / b) = (Re a) / (Re b)\"\n  using assms\n  by (simp add: complex_is_Real_iff)\n\nlemma Re_mult_real:\n  assumes \"is_real a\"\n  shows \"Re (a * b) = (Re a) * (Re b)\"\n  using assms\n  by simp\n\nlemma Im_mult_real:\n  assumes \"is_real a\"\n  shows \"Im (a * b) = (Re a) * (Im b)\"\n  using assms\n  by simp\n\nlemma Im_divide_real:\n  assumes \"is_real b\" and \"b \\<noteq> 0\"\n  shows \"Im (a / b) = (Im a) / (Re b)\"\n  using assms\n  by (simp add: complex_is_Real_iff)\n\n\n\nlemma is_real_div:\n  assumes \"b \\<noteq> 0\"\n  shows \"is_real (a / b) \\<longleftrightarrow> a*cnj b = b*cnj a\"\n  using assms\n  by (metis complex_cnj_divide complex_cnj_zero_iff eq_cnj_iff_real frac_eq_eq mult.commute)\n\nlemma is_real_mult_real:\n  assumes \"is_real a\" and \"a \\<noteq> 0\"\n  shows \"is_real b \\<longleftrightarrow> is_real (a * b)\"\n  using assms\n  by (cases a, auto simp add: Complex_eq)\n\nlemma Im_express_cnj:\n  shows \"Im z = (z - cnj z) / (2 * \\<i>)\"\n  by (simp add: complex_diff_cnj field_simps)\n\nlemma Re_express_cnj: \n  shows \"Re z = (z + cnj z) / 2\"\n  by (simp add: complex_add_cnj)\n\ntext \\<open>Rotation of complex number for 90 degrees in the positive direction.\\<close>\n\nabbreviation rot90 where\n  \"rot90 z \\<equiv> Complex (-Im z) (Re z)\"\n\nlemma rot90_ii: \n  shows \"rot90 z = z * \\<i>\"\n  by (metis Complex_mult_i complex_surj)\n\ntext \\<open>With @{term cnj_mix} we introduce scalar product between complex vectors. This operation shows\nto be useful to succinctly express some conditions.\\<close>\n\nabbreviation cnj_mix where\n  \"cnj_mix z1 z2 \\<equiv> cnj z1 * z2 + z1 * cnj z2\"\n\nabbreviation scalprod where\n  \"scalprod z1 z2 \\<equiv> cnj_mix z1 z2 / 2\"\n\nlemma cnj_mix_minus:\n  shows \"cnj z1*z2 - z1*cnj z2 = \\<i> * cnj_mix (rot90 z1) z2\"\n  by (cases z1, cases z2) (simp add: Complex_eq field_simps)\n\nlemma cnj_mix_minus':\n  shows \"cnj z1*z2 - z1*cnj z2 = rot90 (cnj_mix (rot90 z1) z2)\"\n  by (cases z1, cases z2) (simp add: Complex_eq field_simps)\n\nlemma cnj_mix_real [simp]:\n  shows \"is_real (cnj_mix z1 z2)\"\n  by (cases z1, cases z2) simp\n\nlemma scalprod_real [simp]:\n  shows \"is_real (scalprod z1 z2)\"\n  using cnj_mix_real\n  by simp\n\ntext \\<open>Additional properties of @{term cis} function.\\<close>\n\nlemma cis_minus_pi2 [simp]:\n  shows \"cis (-pi/2) = -\\<i>\"\n  by (simp add: cis_inverse[symmetric])\n\nlemma cis_pi2_minus_x [simp]:\n  shows \"cis (pi/2 - x) = \\<i> * cis(-x)\"\n  using cis_divide[of \"pi/2\" x, symmetric]\n  using cis_divide[of 0 x, symmetric]\n  by simp\n\nlemma cis_pm_pi [simp]: \n  shows \"cis (x - pi) = - cis x\" and  \"cis (x + pi) = - cis x\"\n  by (simp add: cis.ctr complex_minus)+\n\n\nlemma cis_times_cis_opposite [simp]: \n  shows \"cis \\<phi> * cis (- \\<phi>) = 1\"\n  by (simp add: cis_mult)\n\ntext \\<open>@{term cis} repeats only after $2k\\pi$\\<close>\nlemma cis_eq:\n  assumes \"cis a = cis b\"\n  shows \"\\<exists> k::int. a - b = 2 * k * pi\"\n  using assms sin_cos_eq[of a b]\n  using cis.sel[of a] cis.sel[of b]\n  by (cases \"cis a\", cases \"cis b\") auto\n\ntext \\<open>@{term cis} is injective on $(-\\pi, \\pi]$.\\<close>\nlemma cis_inj:\n  assumes \"-pi < \\<alpha>\" and \"\\<alpha> \\<le> pi\" and \"-pi < \\<alpha>'\" and \"\\<alpha>' \\<le> pi\"\n  assumes \"cis \\<alpha> = cis \\<alpha>'\"\n  shows \"\\<alpha> = \\<alpha>'\"\n  using assms\n  by (metis arg_unique sgn_cis)\n\ntext \\<open>@{term cis} of an angle combined with @{term cis} of the opposite angle\\<close>\n\nlemma cis_diff_cis_opposite [simp]: \n  shows \"cis \\<phi> - cis (- \\<phi>) = 2 * \\<i> * sin \\<phi>\"\n  using Im_express_cnj[of \"cis \\<phi>\"]\n  by simp\n\nlemma cis_opposite_diff_cis [simp]:\n  shows \"cis (-\\<phi>) - cis (\\<phi>) = - 2 * \\<i> * sin \\<phi>\"\n  using cis_diff_cis_opposite[of \"-\\<phi>\"]\n  by simp\n\nlemma cis_add_cis_opposite [simp]: \n  shows \"cis \\<phi> + cis (-\\<phi>) = 2 * cos \\<phi>\"\n  by (metis cis.sel(1) cis_cnj complex_add_cnj)\n\ntext \\<open>@{term cis} equal to 1 or -1\\<close>\nlemma cis_one [simp]:\n  assumes \"sin \\<phi> = 0\" and \"cos \\<phi> = 1\"\n  shows \"cis \\<phi> = 1\"\n  using assms\n  by (auto simp add: cis.ctr one_complex.code)\n\nlemma cis_minus_one [simp]:\n  assumes \"sin \\<phi> = 0\" and \"cos \\<phi> = -1\"\n  shows \"cis \\<phi> = -1\"\n  using assms\n  by (auto simp add: cis.ctr Complex_eq_neg_1)\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Additional properties of complex number argument\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>@{term arg} of real numbers\\<close>\n\nlemma is_real_arg1:\n  assumes \"arg z = 0 \\<or> arg z = pi\"\n  shows \"is_real z\"\n  using assms\n  using rcis_cmod_arg[of z] Im_rcis[of \"cmod z\" \"arg z\"]\n  by auto\n\nlemma is_real_arg2:\n  assumes \"is_real z\"\n  shows \"arg z = 0 \\<or> arg z = pi\"\nproof (cases \"z = 0\")\n  case False\n  thus ?thesis\n    using arg_bounded[of z]\n    by (smt (verit, best) Im_sgn assms cis.simps(2) cis_arg div_0 sin_zero_pi_iff)\nqed (auto simp add: arg_zero)\n\nlemma arg_complex_of_real_positive [simp]:\n  assumes \"k > 0\"\n  shows \"arg (cor k) = 0\"\nproof-\n  have \"cos (arg (Complex k 0)) > 0\"\n    using assms\n    using rcis_cmod_arg[of \"Complex k 0\"] Re_rcis[of \"cmod (Complex k 0)\" \"arg (Complex k 0)\"]\n    using cmod_eq_Re by force\n  thus ?thesis\n    using assms is_real_arg2[of \"cor k\"]\n    unfolding complex_of_real_def\n    by auto\nqed\n\nlemma arg_complex_of_real_negative [simp]:\n  assumes \"k < 0\"\n  shows \"arg (cor k) = pi\"\nproof-\n  have \"cos (arg (Complex k 0)) < 0\"\n    using \\<open>k < 0\\<close> rcis_cmod_arg[of \"Complex k 0\"] Re_rcis[of \"cmod (Complex k 0)\" \"arg (Complex k 0)\"]\n    by (metis complex.sel(1) mult_less_0_iff norm_not_less_zero)\n  thus ?thesis\n    using assms is_real_arg2[of \"cor k\"]\n    unfolding complex_of_real_def\n    by auto\nqed\n\nlemma arg_0_iff:\n  shows \"z \\<noteq> 0 \\<and> arg z = 0 \\<longleftrightarrow> is_real z \\<and> Re z > 0\"\n  by (smt arg_complex_of_real_negative arg_complex_of_real_positive arg_zero complex_of_real_Re is_real_arg1 pi_gt_zero zero_complex.simps)\n\nlemma arg_pi_iff:\n  shows \"arg z = pi \\<longleftrightarrow> is_real z \\<and> Re z < 0\"\n  by (smt arg_complex_of_real_negative arg_complex_of_real_positive arg_zero complex_of_real_Re is_real_arg1 pi_gt_zero zero_complex.simps)\n\n\ntext \\<open>@{term arg} of imaginary numbers\\<close>\n\nlemma is_imag_arg1:\n  assumes \"arg z = pi/2 \\<or> arg z = -pi/2\"\n  shows \"is_imag z\"\n  using assms\n  using rcis_cmod_arg[of z] Re_rcis[of \"cmod z\" \"arg z\"]\n  by (metis cos_minus cos_pi_half minus_divide_left mult_eq_0_iff)\n\nlemma is_imag_arg2:\n  assumes \"is_imag z\" and \"z \\<noteq> 0\"\n  shows \"arg z = pi/2 \\<or> arg z = -pi/2\"\n  using arg_bounded assms cos_0_iff_canon cos_arg_i_mult_zero by presburger\n\nlemma arg_complex_of_real_times_i_positive [simp]:\n  assumes \"k > 0\"\n  shows \"arg (cor k * \\<i>) = pi / 2\"\nproof-\n  have \"sin (arg (Complex 0 k)) > 0\"\n    using \\<open>k > 0\\<close> rcis_cmod_arg[of \"Complex 0 k\"] Im_rcis[of \"cmod (Complex 0 k)\" \"arg (Complex 0 k)\"]\n    by (smt complex.sel(2) mult_nonneg_nonpos norm_ge_zero)\n  thus ?thesis\n    using assms is_imag_arg2[of \"cor k * \\<i>\"]\n    using arg_zero complex_of_real_i\n    by force\nqed\n\nlemma arg_complex_of_real_times_i_negative [simp]:\n  assumes \"k < 0\"\n  shows \"arg (cor k * \\<i>) = - pi / 2\"\nproof-\n  have \"sin (arg (Complex 0 k)) < 0\"\n    using \\<open>k < 0\\<close> rcis_cmod_arg[of \"Complex 0 k\"] Im_rcis[of \"cmod (Complex 0 k)\" \"arg (Complex 0 k)\"]\n    by (metis complex.sel(2) mult_less_0_iff norm_not_less_zero)\n  thus ?thesis\n    using assms is_imag_arg2[of \"cor k * \\<i>\"]\n    using arg_zero complex_of_real_i[of k]\n    by (smt complex.sel(1) sin_pi_half sin_zero)\nqed\n\nlemma arg_pi2_iff:\n  shows \"z \\<noteq> 0 \\<and> arg z = pi / 2 \\<longleftrightarrow> is_imag z \\<and> Im z > 0\"\n  by (smt Im_rcis Re_i_times Re_rcis arcsin_minus_1 cos_pi_half divide_minus_left mult.commute mult_cancel_right1 rcis_cmod_arg is_imag_arg2 sin_arcsin sin_pi_half zero_less_mult_pos zero_less_norm_iff)\n\nlemma arg_minus_pi2_iff:\n  shows \"z \\<noteq> 0 \\<and> arg z = - pi / 2 \\<longleftrightarrow> is_imag z \\<and> Im z < 0\"\n  by (smt arg_pi2_iff complex.expand divide_cancel_right pi_neq_zero is_imag_arg1 is_imag_arg2 zero_complex.simps(1) zero_complex.simps(2))\n\n\n\nlemma arg_minus_ii [simp]: \n  shows \"arg (-\\<i>) = -pi/2\"\nproof-\n  have \"-\\<i> = cis (arg (- \\<i>))\"\n    using rcis_cmod_arg[of \"-\\<i>\"]\n    by (simp add: rcis_def)\n  hence \"cos (arg (-\\<i>)) = 0\" \"sin (arg (-\\<i>)) = -1\"\n    using cis.simps[of \"arg (-\\<i>)\"]\n    by auto\n  thus ?thesis\n    using cos_0_iff_canon[of \"arg (-\\<i>)\"] arg_bounded[of \"-\\<i>\"]\n    by fastforce\nqed\n\ntext \\<open>Argument is a canonical angle\\<close>\n\nlemma canon_ang_arg:\n  shows \"\\<downharpoonright>arg z\\<downharpoonleft> = arg z\"\n  using canon_ang_id[of \"arg z\"] arg_bounded\n  by simp\n\nlemma arg_cis:\n  shows \"arg (cis \\<phi>) = \\<downharpoonright>\\<phi>\\<downharpoonleft>\"\n  using arg_unique canon_ang canon_ang_cos canon_ang_sin cis.ctr sgn_cis by presburger\n\ntext \\<open>Cosine and sine of @{term arg}\\<close>\n\nlemma cos_arg:\n  assumes \"z \\<noteq> 0\"\n  shows \"cos (arg z) = Re z / cmod z\"\n  by (metis Complex.Re_sgn cis.simps(1) assms cis_arg)\n\nlemma sin_arg:\n  assumes \"z \\<noteq> 0\"\n  shows \"sin (arg z) = Im z / cmod z\"\n  by (metis Complex.Im_sgn cis.simps(2) assms cis_arg)\n\ntext \\<open>Argument of product\\<close>\n\nlemma cis_arg_mult:\n  assumes \"z1 * z2 \\<noteq> 0\"\n  shows \"cis (arg (z1 * z2)) = cis (arg z1 + arg z2)\"\n  by (metis assms cis_arg cis_mult mult_eq_0_iff sgn_mult)\n\nlemma arg_mult_2kpi:\n  assumes \"z1 * z2 \\<noteq> 0\"\n  shows \"\\<exists> k::int. arg (z1 * z2) = arg z1 + arg z2 + 2*k*pi\"\nproof-\n  have \"cis (arg (z1*z2)) = cis (arg z1 + arg z2)\"\n    by (rule cis_arg_mult[OF assms])\n  thus ?thesis\n    using cis_eq[of \"arg (z1*z2)\" \"arg z1 + arg z2\"]\n    by (auto simp add: field_simps)\nqed\n\nlemma arg_mult:\n  assumes \"z1 * z2 \\<noteq> 0\"\n  shows \"arg(z1 * z2) = \\<downharpoonright>arg z1 + arg z2\\<downharpoonleft>\"\nproof-\n  obtain k::int where \"arg(z1 * z2) = arg z1 + arg z2 + 2*k*pi\"\n    using arg_mult_2kpi[of z1 z2]\n    using assms\n    by auto\n  hence \"\\<downharpoonright>arg(z1 * z2)\\<downharpoonleft> = \\<downharpoonright>arg z1 + arg z2\\<downharpoonleft>\"\n    using canon_ang_eq\n    by(simp add:field_simps)\n  thus ?thesis\n    using canon_ang_arg[of \"z1*z2\"]\n    by auto\nqed\n\nlemma arg_mult_real_positive [simp]:\n  assumes \"k > 0\"\n  shows \"arg (cor k * z) = arg z\"\nproof (cases \"z = 0\")\n  case False\n  thus ?thesis\n    using arg_mult assms canon_ang_arg by force\nqed (auto simp: arg_zero)\n\nlemma arg_mult_real_negative [simp]:\n  assumes \"k < 0\"\n  shows \"arg (cor k * z) = arg (-z)\"\nproof (cases \"z = 0\")\n  case False\n  thus ?thesis\n    using assms\n    by (metis arg_mult_real_positive minus_mult_commute neg_0_less_iff_less of_real_minus minus_minus)\nqed (auto simp: arg_zero)\n\nlemma arg_div_real_positive [simp]:\n  assumes \"k > 0\"\n  shows \"arg (z / cor k) = arg z\"\nproof(cases \"z = 0\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  thus ?thesis\n    using assms\n    using arg_mult_real_positive[of \"1/k\" z]\n    by auto\nqed\n\nlemma arg_div_real_negative [simp]:\n  assumes \"k < 0\"\n  shows \"arg (z / cor k) = arg (-z)\"\nproof(cases \"z = 0\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  thus ?thesis\n    using assms\n    using arg_mult_real_negative[of \"1/k\" z]\n    by auto\nqed\n\nlemma arg_mult_eq:\n  assumes \"z * z1 \\<noteq> 0\" and \"z * z2 \\<noteq> 0\"\n  assumes \"arg (z * z1) = arg (z * z2)\"\n  shows \"arg z1 = arg z2\"\n  by (metis (no_types, lifting) arg_cis assms canon_ang_arg cis_arg mult_eq_0_iff nonzero_mult_div_cancel_left sgn_divide)\n\ntext \\<open>Argument of conjugate\\<close>\n\nlemma arg_cnj_pi:\n  assumes \"arg z = pi\"\n  shows \"arg (cnj z) = pi\"\n  using arg_pi_iff assms by auto\n\nlemma arg_cnj_not_pi:\n  assumes \"arg z \\<noteq> pi\"\n  shows \"arg (cnj z) = -arg z\"\nproof(cases \"arg z = 0\")\n  case True\n  thus ?thesis\n    using eq_cnj_iff_real[of z] is_real_arg1[of z] by force\nnext\n  case False\n  have \"arg (cnj z) = arg z \\<or> arg(cnj z) = -arg z\"\n    using arg_bounded[of z] arg_bounded[of \"cnj z\"]\n    by (smt (verit, best) arccos_cos arccos_cos2 cnj.sel(1) complex_cnj_zero_iff complex_mod_cnj cos_arg)\n  moreover\n  have \"arg (cnj z) \\<noteq> arg z\"\n    using sin_0_iff_canon[of \"arg (cnj z)\"] arg_bounded False assms\n    by (metis complex_mod_cnj eq_cnj_iff_real is_real_arg2 rcis_cmod_arg)\n  ultimately\n  show ?thesis\n    by auto\nqed\n\ntext \\<open>Argument of reciprocal\\<close>\n\nlemma arg_inv_not_pi:\n  assumes \"z \\<noteq> 0\" and \"arg z \\<noteq> pi\"\n  shows \"arg (1 / z) = - arg z\"\nproof-\n  have \"1/z = cnj z / cor ((cmod z)\\<^sup>2 )\"\n    using \\<open>z \\<noteq> 0\\<close> complex_mult_cnj_cmod[of z]\n    by (auto simp add:field_simps)\n  thus ?thesis\n    using arg_div_real_positive[of \"(cmod z)\\<^sup>2\" \"cnj z\"] \\<open>z \\<noteq> 0\\<close>\n    using arg_cnj_not_pi[of z] \\<open>arg z \\<noteq> pi\\<close>\n    by auto\nqed\n\nlemma arg_inv_pi:\n  assumes \"z \\<noteq> 0\" and \"arg z = pi\"\n  shows \"arg (1 / z) = pi\"\nproof-\n  have \"1/z = cnj z / cor ((cmod z)\\<^sup>2 )\"\n    using \\<open>z \\<noteq> 0\\<close> complex_mult_cnj_cmod[of z]\n    by (auto simp add:field_simps)\n  thus ?thesis\n    using arg_div_real_positive[of \"(cmod z)\\<^sup>2\" \"cnj z\"] \\<open>z \\<noteq> 0\\<close>\n    using arg_cnj_pi[of z] \\<open>arg z = pi\\<close>\n    by auto\nqed\n\nlemma arg_inv_2kpi:\n  assumes \"z \\<noteq> 0\"\n  shows \"\\<exists> k::int. arg (1 / z) = - arg z + 2*k*pi\"\n  using arg_inv_pi[OF assms]\n  using arg_inv_not_pi[OF assms]\n  by (cases \"arg z = pi\") (rule_tac x=\"1\" in exI, simp, rule_tac x=\"0\" in exI, simp)\n\nlemma arg_inv:\n  assumes \"z \\<noteq> 0\"\n  shows \"arg (1 / z) = \\<downharpoonright>- arg z\\<downharpoonleft>\"\n  by (metis arg_inv_not_pi arg_inv_pi assms canon_ang_arg canon_ang_uminus_pi)\n\ntext \\<open>Argument of quotient\\<close>\n\nlemma arg_div_2kpi:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"\\<exists> k::int. arg (z1 / z2) = arg z1 - arg z2 + 2*k*pi\"\nproof-\n  obtain x1 where \"arg (z1 * (1 / z2)) = arg z1 + arg (1 / z2) + 2 * real_of_int x1 * pi\"\n    using assms arg_mult_2kpi[of z1 \"1/z2\"]\n    by auto\n  moreover\n  obtain x2 where \"arg (1 / z2) = - arg z2 + 2 * real_of_int x2 * pi\"\n    using assms arg_inv_2kpi[of z2]\n    by auto\n  ultimately\n  show ?thesis\n    by (rule_tac x=\"x1 + x2\" in exI, simp add: field_simps)\nqed\n\nlemma arg_div:\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"arg(z1 / z2) = \\<downharpoonright>arg z1 - arg z2\\<downharpoonleft>\"\nproof-\n  obtain k::int where \"arg(z1 / z2) = arg z1 - arg z2 + 2*k*pi\"\n    using arg_div_2kpi[of z1 z2]\n    using assms\n    by auto\n  hence \"canon_ang(arg(z1 / z2)) = canon_ang(arg z1 - arg z2)\"\n    using canon_ang_eq\n    by(simp add:field_simps)\n  thus ?thesis\n    using canon_ang_arg[of \"z1/z2\"]\n    by auto\nqed\n\ntext \\<open>Argument of opposite\\<close>\n\nlemma arg_uminus:\n  assumes \"z \\<noteq> 0\"\n  shows \"arg (-z) = \\<downharpoonright>arg z + pi\\<downharpoonleft>\"\n  using assms\n  using arg_mult[of \"-1\" z]\n  using arg_complex_of_real_negative[of \"-1\"]\n  by (auto simp add: field_simps)\n\nlemma arg_uminus_opposite_sign:\n  assumes \"z \\<noteq> 0\"\n  shows \"arg z > 0 \\<longleftrightarrow> \\<not> arg (-z) > 0\"\nproof (cases \"arg z = 0\")\n  case True\n  thus ?thesis\n    using assms\n    by (simp add: arg_uminus)\nnext\n  case False\n  show ?thesis\n  proof (cases \"arg z > 0\")\n    case True\n    thus ?thesis\n      using assms\n      using arg_bounded[of z]\n      using canon_ang_plus_pi1[of \"arg z\"]\n      by (simp add: arg_uminus)\n  next\n    case False\n    thus ?thesis\n      using \\<open>arg z \\<noteq> 0\\<close>\n      using assms\n      using arg_bounded[of z]\n      using canon_ang_plus_pi2[of \"arg z\"]\n      by (simp add: arg_uminus)\n  qed\nqed\n\ntext \\<open>Sign of argument is the same as the sign of the Imaginary part\\<close>\n\nlemma arg_Im_sgn:\n  assumes \"\\<not> is_real z\"\n  shows \"sgn (arg z) = sgn (Im z)\"\nproof-\n  have \"z \\<noteq> 0\"\n    using assms\n    by auto\n  then obtain r \\<phi> where polar: \"z = cor r * cis \\<phi>\" \"\\<phi> = arg z\" \"r > 0\"\n    by (smt cmod_cis mult_eq_0_iff norm_ge_zero of_real_0)\n  hence \"Im z = r * sin \\<phi>\"\n    by (metis Im_mult_real Re_complex_of_real cis.simps(2) Im_complex_of_real)\n  hence  \"Im z > 0 \\<longleftrightarrow> sin \\<phi> > 0\" \"Im z < 0 \\<longleftrightarrow> sin \\<phi> < 0\"\n    using \\<open>r > 0\\<close>\n    using mult_pos_pos mult_nonneg_nonneg zero_less_mult_pos mult_less_cancel_left\n    by smt+\n  moreover\n  have \"\\<phi> \\<noteq> pi\" \"\\<phi> \\<noteq> 0\"\n    using \\<open>\\<not> is_real z\\<close> polar cis_pi\n    by force+\n  hence \"sin \\<phi> > 0 \\<longleftrightarrow> \\<phi> > 0\" \"\\<phi> < 0 \\<longleftrightarrow> sin \\<phi> < 0\"\n    using \\<open>\\<phi> = arg z\\<close> \\<open>\\<phi> \\<noteq> 0\\<close> \\<open>\\<phi> \\<noteq> pi\\<close>\n    using arg_bounded[of z]\n    by (smt sin_gt_zero sin_le_zero sin_pi_minus sin_0_iff_canon sin_ge_zero)+\n  ultimately\n  show ?thesis\n    using \\<open>\\<phi> = arg z\\<close>\n    by auto\nqed\n\n\nsubsubsection \\<open>Complex square root\\<close>\n\ndefinition\n  \"ccsqrt z = rcis (sqrt (cmod z)) (arg z / 2)\"\n\nlemma square_ccsqrt [simp]:\n  shows \"(ccsqrt x)\\<^sup>2 = x\"\n  unfolding ccsqrt_def\n  by (subst DeMoivre2) (simp add: rcis_cmod_arg)\n\nlemma ex_complex_sqrt:\n  shows \"\\<exists> s::complex. s*s = z\"\n  unfolding power2_eq_square[symmetric]\n  by (rule_tac x=\"csqrt z\" in exI) simp\n\nlemma ccsqrt:\n  assumes \"s * s = z\"\n  shows \"s = ccsqrt z \\<or> s = -ccsqrt z\"\nproof (cases \"s = 0\")\n  case True\n  thus ?thesis\n    using assms\n    unfolding ccsqrt_def\n    by simp\nnext\n  case False\n  then obtain k::int where \"cmod s * cmod s = cmod z\" \"2 * arg s - arg z = 2*k*pi\"\n    using assms\n    using rcis_cmod_arg[of z] rcis_cmod_arg[of s]\n    using arg_mult[of s s]\n    using canon_ang(3)[of \"2*arg s\"]\n    by (auto simp add: norm_mult arg_mult)\n  have *: \"sqrt (cmod z) = cmod s\"\n    using \\<open>cmod s * cmod s = cmod z\\<close>\n    by (smt norm_not_less_zero real_sqrt_abs2)\n\n  have **: \"arg z / 2 = arg s - k*pi\"\n    using \\<open>2 * arg s - arg z = 2*k*pi\\<close>\n    by simp\n\n  have \"cis (arg s - k*pi) = cis (arg s) \\<or> cis (arg s - k*pi) = -cis (arg s)\"\n  proof (cases \"even k\")\n    case True\n    hence \"cis (arg s - k*pi) = cis (arg s)\"\n      by (simp add: cis_def complex.corec cos_diff sin_diff)\n    thus ?thesis\n      by simp\n  next\n    case False\n    hence \"cis (arg s - k*pi) = -cis (arg s)\"\n      by (simp add: cis_def complex.corec Complex_eq cos_diff sin_diff)\n    thus ?thesis\n      by simp\n  qed\n  thus ?thesis\n  proof\n    assume ***: \"cis (arg s - k * pi) = cis (arg s)\"\n    hence \"s = ccsqrt z\"\n      using rcis_cmod_arg[of s]\n      unfolding ccsqrt_def rcis_def\n      by (subst *, subst **, subst ***, simp)\n    thus ?thesis\n      by simp\n  next\n    assume ***: \"cis (arg s - k * pi) = -cis (arg s)\"\n    hence \"s = - ccsqrt z\"\n      using rcis_cmod_arg[of s]\n      unfolding ccsqrt_def rcis_def\n      by (subst *, subst **, subst ***, simp)\n    thus ?thesis\n      by simp\n  qed\nqed\n\nlemma null_ccsqrt [simp]:\n  shows \"ccsqrt x = 0 \\<longleftrightarrow> x = 0\"\n  unfolding ccsqrt_def\n  by auto\n\nlemma ccsqrt_mult:\n  shows \"ccsqrt (a * b) = ccsqrt a * ccsqrt b \\<or>\n         ccsqrt (a * b) = - ccsqrt a * ccsqrt b\"\nproof (cases \"a = 0 \\<or> b = 0\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  obtain k::int where \"arg a + arg b - \\<downharpoonright>arg a + arg b\\<downharpoonleft> = 2 * real_of_int k * pi\"\n    using canon_ang(3)[of \"arg a + arg b\"]\n    by auto\n  hence *: \"\\<downharpoonright>arg a + arg b\\<downharpoonleft> = arg a + arg b - 2 * (real_of_int k) * pi\"\n    by (auto simp add: field_simps)\n\n  have \"cis (\\<downharpoonright>arg a + arg b\\<downharpoonleft> / 2) = cis (arg a / 2 + arg b / 2) \\<or> cis (\\<downharpoonright>arg a + arg b\\<downharpoonleft> / 2) = - cis (arg a / 2 + arg b / 2)\"\n    using cos_even_kpi[of k] cos_odd_kpi[of k]\n    by ((subst *)+, (subst diff_divide_distrib)+, (subst add_divide_distrib)+)\n       (cases \"even k\", auto simp add: cis_def complex.corec Complex_eq cos_diff sin_diff)\n  thus ?thesis\n    using False\n    unfolding ccsqrt_def\n    by (smt (verit, best) arg_mult mult_minus_left mult_minus_right no_zero_divisors norm_mult rcis_def rcis_mult real_sqrt_mult)\nqed\n\nlemma csqrt_real:\n  assumes \"is_real x\"\n  shows \"(Re x \\<ge> 0 \\<and> ccsqrt x = cor (sqrt (Re x))) \\<or>\n         (Re x < 0 \\<and> ccsqrt x = \\<i> * cor (sqrt (- (Re x))))\"\nproof (cases \"x = 0\")\n  case True\n  thus ?thesis\n    by auto\nnext\n  case False\n  show ?thesis\n  proof (cases \"Re x > 0\")\n    case True\n    hence \"arg x = 0\"\n      using \\<open>is_real x\\<close>\n      by (metis arg_complex_of_real_positive complex_of_real_Re)\n    thus ?thesis\n      using \\<open>Re x > 0\\<close> \\<open>is_real x\\<close>\n      unfolding ccsqrt_def\n      by (simp add: cmod_eq_Re)\n  next\n    case False\n    hence \"Re x < 0\"\n      using \\<open>x \\<noteq> 0\\<close> \\<open>is_real x\\<close>\n      using complex_eq_if_Re_eq by auto\n    hence \"arg x = pi\"\n      using \\<open>is_real x\\<close>\n      by (metis arg_complex_of_real_negative complex_of_real_Re)\n    thus ?thesis\n      using \\<open>Re x < 0\\<close> \\<open>is_real x\\<close>\n      unfolding ccsqrt_def rcis_def\n      by (simp add: cis_def complex.corec Complex_eq cmod_eq_Re)\n  qed\nqed\n\n\ntext \\<open>Rotation of complex vector to x-axis.\\<close>\n\nlemma is_real_rot_to_x_axis:\n  assumes \"z \\<noteq> 0\"\n  shows \"is_real (cis (-arg z) * z)\"\nproof (cases \"arg z = pi\")\n  case True\n  thus ?thesis\n    using is_real_arg1[of z]\n    by auto\nnext\n  case False\n  hence \"\\<downharpoonright>- arg z\\<downharpoonleft> = - arg z\"\n    using canon_ang_eqI[of \"- arg z\" \"-arg z\"]\n    using arg_bounded[of z]\n    by (auto simp add: field_simps)\n  hence \"arg (cis (- (arg z)) * z) = 0\"\n    using arg_mult[of \"cis (- (arg z))\" z] \\<open>z \\<noteq> 0\\<close>\n    using arg_cis[of \"- arg z\"]\n    by simp\n  thus ?thesis\n    using is_real_arg1[of \"cis (- arg z) * z\"]\n    by auto\nqed\n\nlemma positive_rot_to_x_axis:\n  assumes \"z \\<noteq> 0\"\n  shows \"Re (cis (-arg z) * z) > 0\"\n  using assms\n  by (smt Re_complex_of_real cis_rcis_eq mult_cancel_right1 rcis_cmod_arg rcis_mult rcis_zero_arg zero_less_norm_iff)\n\ntext \\<open>Inequalities involving @{term cmod}.\\<close>\n\nlemma cmod_1_plus_mult_le:\n  shows \"cmod (1 + z*w) \\<le> sqrt((1 + (cmod z)\\<^sup>2) * (1 + (cmod w)\\<^sup>2))\"\nproof-\n  have \"Re ((1+z*w)*(1+cnj z*cnj w)) \\<le> Re (1+z*cnj z)* Re (1+w*cnj w)\"\n  proof-\n    have \"Re ((w - cnj z)*cnj(w - cnj z)) \\<ge> 0\"\n      by (subst complex_mult_cnj_cmod) (simp add: power2_eq_square)\n    hence \"Re (z*w + cnj z * cnj w) \\<le> Re (w*cnj w) + Re(z*cnj z)\"\n      by (simp add: field_simps)\n    thus ?thesis\n      by (simp add: field_simps)\n  qed\n  hence \"(cmod (1 + z * w))\\<^sup>2 \\<le> (1 + (cmod z)\\<^sup>2) * (1 + (cmod w)\\<^sup>2)\"\n    by (subst cmod_square)+ simp\n  thus ?thesis\n    by (metis abs_norm_cancel real_sqrt_abs real_sqrt_le_iff)\nqed\n\nlemma cmod_diff_ge: \n  shows \"cmod (b - c) \\<ge> sqrt (1 + (cmod b)\\<^sup>2) - sqrt (1 + (cmod c)\\<^sup>2)\"\nproof-\n  have \"(cmod (b - c))\\<^sup>2 + (1/2*Im(b*cnj c - c*cnj b))\\<^sup>2 \\<ge> 0\"\n    by simp\n  hence \"(cmod (b - c))\\<^sup>2 \\<ge> - (1/2*Im(b*cnj c - c*cnj b))\\<^sup>2\"\n    by simp\n  hence \"(cmod (b - c))\\<^sup>2 \\<ge> (1/2*Re(b*cnj c + c*cnj b))\\<^sup>2 - Re(b*cnj b*c*cnj c) \"\n    by (auto simp add: power2_eq_square field_simps)\n  hence \"Re ((b - c)*(cnj b - cnj c)) \\<ge> (1/2*Re(b*cnj c + c*cnj b))\\<^sup>2 - Re(b*cnj b*c*cnj c)\"\n    by (subst (asm) cmod_square) simp\n  moreover\n  have \"(1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2) = 1 + Re(b*cnj b) + Re(c*cnj c) + Re(b*cnj b*c*cnj c)\"\n    by (subst cmod_square)+ (simp add: field_simps power2_eq_square)\n  moreover\n  have \"(1 + Re (scalprod b c))\\<^sup>2 = 1 + 2*Re(scalprod b c) + ((Re (scalprod b c))\\<^sup>2)\"\n    by (subst power2_sum) simp\n  hence \"(1 + Re (scalprod b c))\\<^sup>2 = 1 + Re(b*cnj c + c*cnj b) + (1/2 * Re (b*cnj c + c*cnj b))\\<^sup>2\"\n    by simp\n  ultimately\n  have \"(1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2) \\<ge> (1 + Re (scalprod b c))\\<^sup>2\"\n    by (simp add: field_simps)\n  moreover\n  have \"sqrt((1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2)) \\<ge> 0\"\n    by (metis one_power2 real_sqrt_sum_squares_mult_ge_zero)\n  ultimately\n  have \"sqrt((1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2)) \\<ge> 1 + Re (scalprod b c)\"\n    by (metis power2_le_imp_le real_sqrt_ge_0_iff real_sqrt_pow2_iff)\n  hence \"Re ((b - c) * (cnj b - cnj c)) \\<ge> 1 + Re (c*cnj c) + 1 + Re (b*cnj b) - 2*sqrt((1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2))\"\n    by (simp add: field_simps)\n  hence *: \"(cmod (b - c))\\<^sup>2 \\<ge> (sqrt (1 + (cmod b)\\<^sup>2) - sqrt (1 + (cmod c)\\<^sup>2))\\<^sup>2\"\n    apply (subst cmod_square)+\n    apply (subst (asm) cmod_square)+\n    apply (subst power2_diff)\n    apply (subst real_sqrt_pow2, simp)\n    apply (subst real_sqrt_pow2, simp)\n    apply (simp add: real_sqrt_mult)\n    done\n  thus ?thesis\n  proof (cases \"sqrt (1 + (cmod b)\\<^sup>2) - sqrt (1 + (cmod c)\\<^sup>2) > 0\")\n    case True\n    thus ?thesis\n      using power2_le_imp_le[OF *]\n      by simp\n  next\n    case False\n    hence \"0 \\<ge> sqrt (1 + (cmod b)\\<^sup>2) - sqrt (1 + (cmod c)\\<^sup>2)\"\n      by (metis less_eq_real_def linorder_neqE_linordered_idom)\n    moreover\n    have \"cmod (b - c) \\<ge> 0\"\n      by simp\n    ultimately\n    show ?thesis\n      by (metis add_increasing monoid_add_class.add.right_neutral)\n  qed\nqed\n\nlemma cmod_diff_le:\n  shows \"cmod (b - c) \\<le> sqrt (1 + (cmod b)\\<^sup>2) + sqrt (1 + (cmod c)\\<^sup>2)\"\nproof-\n  have \"(cmod (b + c))\\<^sup>2 + (1/2*Im(b*cnj c - c*cnj b))\\<^sup>2 \\<ge> 0\"\n    by simp\n  hence \"(cmod (b + c))\\<^sup>2 \\<ge> - (1/2*Im(b*cnj c - c*cnj b))\\<^sup>2\"\n    by simp\n  hence \"(cmod (b + c))\\<^sup>2 \\<ge> (1/2*Re(b*cnj c + c*cnj b))\\<^sup>2 - Re(b*cnj b*c*cnj c) \"\n    by (auto simp add: power2_eq_square field_simps)\n  hence \"Re ((b + c)*(cnj b + cnj c)) \\<ge> (1/2*Re(b*cnj c + c*cnj b))\\<^sup>2 - Re(b*cnj b*c*cnj c)\"\n    by (subst (asm) cmod_square) simp\n  moreover\n  have \"(1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2) = 1 + Re(b*cnj b) + Re(c*cnj c) + Re(b*cnj b*c*cnj c)\"\n    by (subst cmod_square)+ (simp add: field_simps power2_eq_square)\n  moreover\n  have ++: \"2*Re(scalprod b c) = Re(b*cnj c + c*cnj b)\"\n    by simp\n  have \"(1 - Re (scalprod b c))\\<^sup>2 = 1 - 2*Re(scalprod b c) + ((Re (scalprod b c))\\<^sup>2)\"\n    by (subst power2_diff) simp\n  hence \"(1 - Re (scalprod b c))\\<^sup>2 = 1 - Re(b*cnj c + c*cnj b) + (1/2 * Re (b*cnj c + c*cnj b))\\<^sup>2\"\n    by (subst ++[symmetric]) simp\n  ultimately\n  have \"(1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2) \\<ge> (1 - Re (scalprod b c))\\<^sup>2\"\n    by (simp add: field_simps)\n  moreover\n  have \"sqrt((1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2)) \\<ge> 0\"\n    by (metis one_power2 real_sqrt_sum_squares_mult_ge_zero)\n  ultimately\n  have \"sqrt((1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2)) \\<ge> 1 - Re (scalprod b c)\"\n    by (metis power2_le_imp_le real_sqrt_ge_0_iff real_sqrt_pow2_iff)\n  hence \"Re ((b - c) * (cnj b - cnj c)) \\<le> 1 + Re (c*cnj c) + 1 + Re (b*cnj b) + 2*sqrt((1 + (cmod b)\\<^sup>2) * (1 + (cmod c)\\<^sup>2))\"\n    by (simp add: field_simps)\n  hence *: \"(cmod (b - c))\\<^sup>2 \\<le> (sqrt (1 + (cmod b)\\<^sup>2) + sqrt (1 + (cmod c)\\<^sup>2))\\<^sup>2\"\n    apply (subst cmod_square)+\n    apply (subst (asm) cmod_square)+\n    apply (subst power2_sum)\n    apply (subst real_sqrt_pow2, simp)\n    apply (subst real_sqrt_pow2, simp)\n    apply (simp add: real_sqrt_mult)\n    done\n  thus ?thesis\n    using power2_le_imp_le[OF *]\n    by simp\nqed\n\n\ntext \\<open>Definition of Euclidean distance between two complex numbers.\\<close>\n\ndefinition cdist where\n  [simp]: \"cdist z1 z2 \\<equiv> cmod (z2 - z1)\"\n\ntext \\<open>Misc. properties of complex numbers.\\<close>\n\nlemma ex_complex_to_complex [simp]:\n  fixes z1 z2 :: complex\n  assumes \"z1 \\<noteq> 0\" and \"z2 \\<noteq> 0\"\n  shows \"\\<exists>k. k \\<noteq> 0 \\<and> z2 = k * z1\"\n  using assms\n  by (rule_tac x=\"z2/z1\" in exI) simp\n\nlemma ex_complex_to_one [simp]:\n  fixes z::complex\n  assumes \"z \\<noteq> 0\"\n  shows \"\\<exists>k. k \\<noteq> 0 \\<and> k * z = 1\"\n  using assms\n  by (rule_tac x=\"1/z\" in exI) simp\n\nlemma ex_complex_to_complex2 [simp]:\n  fixes z::complex\n  shows \"\\<exists>k. k \\<noteq> 0 \\<and> k * z = z\"\n  by (rule_tac x=\"1\" in exI) simp\n\nlemma complex_sqrt_1:\n  fixes z::complex\n  assumes \"z \\<noteq> 0\"\n  shows \"z = 1 / z \\<longleftrightarrow> z = 1 \\<or> z = -1\"\n  using assms\n  using nonzero_eq_divide_eq square_eq_iff\n  by fastforce\n\nend\n", "meta": {"author": "zabihullah331", "repo": "barakzai", "sha": "793257c1d71ec75a299fc6b5843af756ead2afb0", "save_path": "github-repos/isabelle/zabihullah331-barakzai", "path": "github-repos/isabelle/zabihullah331-barakzai/barakzai-793257c1d71ec75a299fc6b5843af756ead2afb0/thys/Complex_Geometry/More_Complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8499711756575749, "lm_q1q2_score": 0.7554193615895938}}
{"text": "theory BST_Demo\nimports \"HOL-Library.Tree\"\nbegin\n\n(* useful most of the time: *)\ndeclare Let_def [simp]\n\nsection \"BST Search and Insertion\"\n\nfun isin :: \"('a::linorder) tree \\<Rightarrow> 'a \\<Rightarrow> bool\" where\n\"isin Leaf x = False\" |\n\"isin (Node l a r) x =\n  (if x < a then isin l x else\n   if x > a then isin r x\n   else True)\"\n\nfun ins :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"ins x Leaf = Node Leaf x Leaf\" |\n\"ins x (Node l a r) =\n  (if x < a then Node (ins x l) a r else\n   if x > a then Node l a (ins x r)\n   else Node l a r)\"\n\nsubsection \"Functional Correctness\"\n\nlemma set_tree_isin: \"bst t \\<Longrightarrow> isin t x = (x \\<in> set_tree t)\"\napply(induction t)\napply auto\ndone\n\nlemma set_tree_ins: \"set_tree (ins x t) = {x} \\<union> set_tree t\"\napply(induction t)\napply auto\ndone\n\nsubsection \"Preservation of Invariant\"\n\nlemma bst_ins: \"bst t \\<Longrightarrow> bst (ins x t)\"\napply(induction t)\napply (auto simp: set_tree_ins)\ndone\n\n\nsection \"BST Deletion\"\n\nfun split_min :: \"'a tree \\<Rightarrow> 'a * 'a tree\" where\n\"split_min (Node l a r) =\n  (if l = Leaf then (a,r)\n   else let (x,l') = split_min l\n        in (x, Node l' a r))\"\n\nfun delete :: \"'a::linorder \\<Rightarrow> 'a tree \\<Rightarrow> 'a tree\" where\n\"delete x Leaf = Leaf\" |\n\"delete x (Node l a r) =\n  (if x < a then Node (delete x l) a r else\n   if x > a then Node l a (delete x r)\n   else if r = Leaf then l else let (a',r') = split_min r in Node l a' r')\"\n\n(* A proof attempt *)\n\nlemma \"split_min t = (x,t') \\<Longrightarrow> set_tree t' = set_tree t - {x}\"\noops\n\n(* The final proof (needs more than auto!): *)\n\nlemma \"\\<lbrakk> split_min t = (x,t'); bst t; t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow>\n  set_tree t' = set_tree t - {x} \\<and> x \\<in> set_tree t\"\napply(induction t arbitrary: x t')\n apply simp\napply (force split: if_split_asm prod.splits)\ndone\n\nend\n", "meta": {"author": "nipkow", "repo": "fds_ss20", "sha": "daae0f92277b0df86f34ec747c7b3f1c5f0a725c", "save_path": "github-repos/isabelle/nipkow-fds_ss20", "path": "github-repos/isabelle/nipkow-fds_ss20/fds_ss20-daae0f92277b0df86f34ec747c7b3f1c5f0a725c/Demos/BST_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.913676530465412, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7553471676022371}}
{"text": "section\\<open>Boolean functions\\<close>\ntheory Bool_Func\nimports Main\nbegin\ntext\\<open>\n  The end result of our implementation is verified against these functions:\n\\<close>\ntype_synonym 'a boolfunc = \"('a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n\ntext\\<open>if-then-else on boolean functions.\\<close>\ndefinition \"bf_ite i t e \\<equiv> (\\<lambda>l. if i l then t l else e l)\"\ntext\\<open>if-then-else is interesting because we can, together with constant true and false, represent all binary boolean functions using maximally two applications of it.\\<close>\nabbreviation \"bf_True \\<equiv> (\\<lambda>l. True)\"\nabbreviation \"bf_False \\<equiv> (\\<lambda>l. False)\"\ntext\\<open>A quick demonstration:\\<close>\ndefinition \"bf_and a b \\<equiv> bf_ite a b bf_False\"\nlemma \"(bf_and a b) as \\<longleftrightarrow> a as \\<and> b as\" unfolding bf_and_def  bf_ite_def  by meson \ndefinition \"bf_not b \\<equiv> bf_ite b bf_False bf_True\"\nlemma bf_not_alt: \"bf_not a as \\<longleftrightarrow> \\<not>a as\" unfolding bf_not_def bf_ite_def by meson\ntext\\<open>For convenience, we want a few functions more:\\<close>\ndefinition \"bf_or a b \\<equiv> bf_ite a bf_True b\"\ndefinition \"bf_lit v \\<equiv> (\\<lambda>l. l v)\"\ndefinition \"bf_if v t e \\<equiv> bf_ite (bf_lit v) t e\"\nlemma bf_if_alt: \"bf_if v t e = (\\<lambda>l. if l v then t l else e l)\" unfolding bf_if_def bf_ite_def bf_lit_def ..\ndefinition \"bf_nand a b = bf_not (bf_and a b)\"\ndefinition \"bf_nor a b = bf_not (bf_or a b)\"\ndefinition \"bf_biimp a b = (bf_ite a b (bf_not b))\"\nlemma bf_biimp_alt: \"bf_biimp a b = (\\<lambda>l. a l \\<longleftrightarrow> b l)\" unfolding bf_biimp_def bf_not_def bf_ite_def by(simp add: fun_eq_iff)\ndefinition \"bf_xor a b = bf_not (bf_biimp a b)\"\nlemma bf_xor_alt: \"bf_xor a b = (bf_ite a (bf_not b) b)\" (* two application version *) \n  unfolding bf_xor_def bf_biimp_def bf_not_def\n  unfolding bf_ite_def\n  by simp\ntext\\<open>All of these are implemented and had their implementation verified.\\<close>\n\ndefinition \"bf_imp a b = bf_ite a b bf_True\"\nlemma bf_imp_alt: \"bf_imp a b = bf_or (bf_not a) b\" unfolding bf_or_def bf_not_def bf_imp_def unfolding bf_ite_def unfolding fun_eq_iff by simp\n\nlemma [dest!,elim!]: \"bf_False = bf_True \\<Longrightarrow> False\" \"bf_True = bf_False \\<Longrightarrow> False\" unfolding fun_eq_iff by simp_all (* Occurs here and there as goal for sep_auto *)\n\nlemmas [simp] = bf_and_def bf_or_def bf_nand_def bf_biimp_def bf_xor_alt bf_nor_def bf_not_def \n\nsubsection\\<open>Shannon decomposition\\<close>\ntext\\<open>\n  A restriction of a boolean function on a variable is creating the boolean function that evaluates as if that variable was set to a fixed value:\n\\<close>\ndefinition \"bf_restrict (i::'a) (val::bool) (f::'a boolfunc) \\<equiv> (\\<lambda>v. f (v(i:=val)))\"\n\ntext \\<open>\n  Restrictions are useful, because they remove variables from the set of significant variables:\n\\<close>\ndefinition \"bf_vars bf = {v. \\<exists>as. bf_restrict v True bf as \\<noteq> bf_restrict v False bf as}\"\nlemma \"var \\<notin> bf_vars (bf_restrict var val ex)\"\nunfolding bf_vars_def bf_restrict_def by(simp)\n\ntext\\<open>\n  We can decompose calculating if-then-else into computing if-then-else of two triples of functions with one variable restricted to true / false.\n  Given that the functions have finite arity, we can use this to construct a recursive definition.\n\\<close>\nlemma brace90shannon: \"bf_ite F G H ass =\n  bf_ite (\\<lambda>l. l i) \n         (bf_ite (bf_restrict i True F) (bf_restrict i True G) (bf_restrict i True H))\n         (bf_ite (bf_restrict i False F) (bf_restrict i False G) (bf_restrict i False H)) ass\"\nunfolding bf_ite_def bf_restrict_def by (auto simp add: fun_upd_idem)\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/ROBDD/Bool_Func.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.7553122191332549}}
{"text": "(*<*)\ntheory Two_Steps\nimports Consensus_Misc\nbegin\n(*>*)\nsubsection \\<open>Step definitions for 2-step algorithms\\<close>\n\ndefinition two_phase where \"two_phase (r::nat) \\<equiv> r div 2\"\n\ndefinition two_step where \"two_step (r::nat) \\<equiv> r mod 2\"\n\nlemma two_phase_zero [simp]: \"two_phase 0 = 0\"\nby (simp add: two_phase_def)\n\nlemma two_step_zero [simp]: \"two_step 0 = 0\"\nby (simp add: two_step_def)\n\nlemma two_phase_step: \"(two_phase r * 2) + two_step r = r\"\n  by (auto simp add: two_phase_def two_step_def)\n\nlemma two_step_phase_Suc:\n  \"two_step r = 0 \\<Longrightarrow> two_phase (Suc r) = two_phase r\"\n  \"two_step r = 0 \\<Longrightarrow> two_step (Suc r) = 1\"\n  \"two_step r = 0 \\<Longrightarrow> two_phase (Suc (Suc r)) = Suc (two_phase r)\"\n  \"two_step r = (Suc 0) \\<Longrightarrow> two_phase (Suc r) = Suc (two_phase r)\"\n  \"two_step r = (Suc 0) \\<Longrightarrow> two_step (Suc r) = 0\"\n  by(simp_all add: two_step_def two_phase_def mod_Suc div_Suc)\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Consensus_Refined/Two_Steps.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.755226906913461}}
{"text": "(*\nAuthors: \n\n  Anthony Bordg, University of Cambridge, apdb3@cam.ac.uk\n  Yijun He, University of Cambridge, yh403@cam.ac.uk\n  with contributions by Hanna Lachnitt\n*)\n\nsection \\<open>Qubits and Quantum Gates\\<close>\n\ntheory Quantum\nimports\n  Jordan_Normal_Form.Matrix\n  \"HOL-Library.Nonpos_Ints\"\n  Basics\n  Binary_Nat\nbegin\n\n\nsubsection \\<open>Qubits\\<close>\n\ntext\\<open>In this theory @{text cpx} stands for @{text complex}.\\<close>\n\ndefinition cpx_vec_length :: \"complex vec \\<Rightarrow> real\" (\"\\<parallel>_\\<parallel>\") where\n\"cpx_vec_length v \\<equiv> sqrt(\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2)\"\n\nlemma cpx_length_of_vec_of_list [simp]:\n  \"\\<parallel>vec_of_list l\\<parallel> = sqrt(\\<Sum>i<length l. (cmod (l ! i))\\<^sup>2)\"\n  by (auto simp: cpx_vec_length_def vec_of_list_def vec_of_list_index)\n    (metis (no_types, lifting) dim_vec_of_list sum.cong vec_of_list.abs_eq vec_of_list_index)\n\nlemma norm_vec_index_unit_vec_is_0 [simp]:\n  assumes \"j < n\" and \"j \\<noteq> i\"\n  shows \"cmod ((unit_vec n i) $ j) = 0\"\n  using assms by (simp add: unit_vec_def)\n\nlemma norm_vec_index_unit_vec_is_1 [simp]:\n  assumes \"j < n\" and \"j = i\"\n  shows \"cmod ((unit_vec n i) $ j) = 1\"\nproof -\n  have f:\"(unit_vec n i) $ j = 1\"\n    using assms by simp\n  thus ?thesis\n    by (simp add: f cmod_def) \nqed\n\nlemma unit_cpx_vec_length [simp]:\n  assumes \"i < n\"\n  shows \"\\<parallel>unit_vec n i\\<parallel> = 1\"\nproof -\n  have \"(\\<Sum>j<n. (cmod((unit_vec n i) $ j))\\<^sup>2) = (\\<Sum>j<n. if j = i then 1 else 0)\"\n    using norm_vec_index_unit_vec_is_0 norm_vec_index_unit_vec_is_1\n    by (smt lessThan_iff one_power2 sum.cong zero_power2) \n  also have \"\\<dots> = 1\"\n    using assms by simp\n  finally have \"sqrt (\\<Sum>j<n. (cmod((unit_vec n i) $ j))\\<^sup>2) = 1\" \n    by simp\n  thus ?thesis\n    using cpx_vec_length_def by simp\nqed\n\nlemma smult_vec_length [simp]:\n  assumes \"x \\<ge> 0\"\n  shows \"\\<parallel>complex_of_real(x) \\<cdot>\\<^sub>v v\\<parallel> = x * \\<parallel>v\\<parallel>\"\nproof-\n  have \"(\\<lambda>i::nat.(cmod (complex_of_real x * v $ i))\\<^sup>2) = (\\<lambda>i::nat. (cmod (v $ i))\\<^sup>2 * x\\<^sup>2)\" \n    by (auto simp: norm_mult power_mult_distrib)\n  then have \"(\\<Sum>i<dim_vec v. (cmod (complex_of_real x * v $ i))\\<^sup>2) = \n             (\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2 * x\\<^sup>2)\" by meson\n  moreover have \"(\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2 * x\\<^sup>2) = x\\<^sup>2 * (\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2)\"\n    by (metis (no_types) mult.commute sum_distrib_right)\n  moreover have \"sqrt(x\\<^sup>2 * (\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2)) = \n                 sqrt(x\\<^sup>2) * sqrt (\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2)\" \n    using real_sqrt_mult by blast\n  ultimately show ?thesis\n    by(simp add: cpx_vec_length_def assms)\nqed\n\nlocale state =\n  fixes n:: nat and v:: \"complex mat\"\n  assumes is_column [simp]: \"dim_col v = 1\"\n    and dim_row [simp]: \"dim_row v = 2^n\"\n    and is_normal [simp]: \"\\<parallel>col v 0\\<parallel> = 1\"\n\ntext\\<open> \nBelow the natural number n codes for the dimension of the complex vector space whose elements of norm\n1 we call states. \n\\<close>\n\nlemma unit_vec_of_right_length_is_state [simp]:\n  assumes \"i < 2^n\"\n  shows \"unit_vec (2^n) i \\<in> {v| n v::complex vec. dim_vec v = 2^n \\<and> \\<parallel>v\\<parallel> = 1}\"\nproof-\n  have \"dim_vec (unit_vec (2^n) i) = 2^n\" \n    by simp\n  moreover have \"\\<parallel>unit_vec (2^n) i\\<parallel> = 1\"\n    using assms by simp\n  ultimately show ?thesis \n    by simp\nqed\n\ndefinition state_qbit :: \"nat \\<Rightarrow> complex vec set\" where\n\"state_qbit n \\<equiv> {v| v:: complex vec. dim_vec v = 2^n \\<and> \\<parallel>v\\<parallel> = 1}\"\n\nlemma (in state) state_to_state_qbit [simp]:\n  shows \"col v 0 \\<in> state_qbit n\"\n  using state_def state_qbit_def by simp\n\nsubsection \"The Hermitian Conjugation\"\n\ntext \\<open>The Hermitian conjugate of a complex matrix is the complex conjugate of its transpose. \\<close>\n\ndefinition dagger :: \"complex mat \\<Rightarrow> complex mat\" (\"_\\<^sup>\\<dagger>\") where\n  \"M\\<^sup>\\<dagger> \\<equiv> mat (dim_col M) (dim_row M) (\\<lambda>(i,j). cnj(M $$ (j,i)))\"\n\ntext \\<open>We introduce the type of complex square matrices.\\<close>\n\ntypedef cpx_sqr_mat = \"{M | M::complex mat. square_mat M}\"\nproof-\n  have \"square_mat (1\\<^sub>m n)\" for n\n    using one_mat_def by simp\n  thus ?thesis by blast\nqed\n\ndefinition cpx_sqr_mat_to_cpx_mat :: \"cpx_sqr_mat => complex mat\" where\n\"cpx_sqr_mat_to_cpx_mat M \\<equiv> Rep_cpx_sqr_mat M\"\n\ntext \\<open>\nWe introduce a coercion from the type of complex square matrices to the type of complex \nmatrices.\n\\<close>\n\ndeclare [[coercion cpx_sqr_mat_to_cpx_mat]]\n\nlemma dim_row_of_dagger [simp]:\n  \"dim_row (M\\<^sup>\\<dagger>) = dim_col M\"\n  using dagger_def by simp\n\nlemma dim_col_of_dagger [simp]:\n  \"dim_col (M\\<^sup>\\<dagger>) = dim_row M\"\n  using dagger_def by simp\n\nlemma col_of_dagger [simp]:\n  assumes \"j < dim_row M\"\n  shows \"col (M\\<^sup>\\<dagger>) j = vec (dim_col M) (\\<lambda>i. cnj (M $$ (j,i)))\"\n  using assms col_def dagger_def by simp\n\nlemma row_of_dagger [simp]:\n  assumes \"i < dim_col M\"\n  shows \"row (M\\<^sup>\\<dagger>) i = vec (dim_row M) (\\<lambda>j. cnj (M $$ (j,i)))\"\n  using assms row_def dagger_def by simp\n\nlemma dagger_of_dagger_is_id:\n  fixes M :: \"complex Matrix.mat\"\n  shows \"(M\\<^sup>\\<dagger>)\\<^sup>\\<dagger> = M\"\nproof\n  show \"dim_row ((M\\<^sup>\\<dagger>)\\<^sup>\\<dagger>) = dim_row M\" by simp\n  show \"dim_col ((M\\<^sup>\\<dagger>)\\<^sup>\\<dagger>) = dim_col M\" by simp\n  fix i j assume a0:\"i < dim_row M\" and a1:\"j < dim_col M\"\n  then show \"(M\\<^sup>\\<dagger>)\\<^sup>\\<dagger> $$ (i,j) = M $$ (i,j)\"\n  proof-\n    show ?thesis\n      using dagger_def a0 a1 by auto\n  qed\nqed\n\nlemma dagger_of_sqr_is_sqr [simp]:\n  \"square_mat ((M::cpx_sqr_mat)\\<^sup>\\<dagger>)\"\nproof-\n  have \"square_mat M\"\n    using cpx_sqr_mat_to_cpx_mat_def Rep_cpx_sqr_mat by simp\n  then have \"dim_row M = dim_col M\" by simp\n  then have \"dim_col (M\\<^sup>\\<dagger>) = dim_row (M\\<^sup>\\<dagger>)\" by simp\n  thus \"square_mat (M\\<^sup>\\<dagger>)\" by simp\nqed\n\nlemma dagger_of_id_is_id [simp]:\n  \"(1\\<^sub>m n)\\<^sup>\\<dagger> = 1\\<^sub>m n\"\n  using dagger_def one_mat_def by auto\n\nsubsection \"Unitary Matrices and Quantum Gates\"\n\ndefinition unitary :: \"complex mat \\<Rightarrow> bool\" where\n\"unitary M \\<equiv> (M\\<^sup>\\<dagger>) * M = 1\\<^sub>m (dim_col M) \\<and> M * (M\\<^sup>\\<dagger>) = 1\\<^sub>m (dim_row M)\"\n\nlemma id_is_unitary [simp]:\n  \"unitary (1\\<^sub>m n)\"\n  by (simp add: unitary_def)\n\nlocale gate =\n  fixes n:: nat and A:: \"complex mat\"\n  assumes dim_row [simp]: \"dim_row A = 2^n\"\n    and square_mat [simp]: \"square_mat A\"\n    and unitary [simp]: \"unitary A\"\n\ntext \\<open>\nWe prove that a quantum gate is invertible and its inverse is given by its Hermitian conjugate.\n\\<close>\n\nlemma mat_unitary_mat [intro]:\n  assumes \"unitary M\"\n  shows \"inverts_mat M (M\\<^sup>\\<dagger>)\"\n  using assms by (simp add: unitary_def inverts_mat_def)\n\nlemma unitary_mat_mat [intro]:\n  assumes \"unitary M\"\n  shows \"inverts_mat (M\\<^sup>\\<dagger>) M\"\n  using assms by (simp add: unitary_def inverts_mat_def)\n\nlemma (in gate) gate_is_inv:\n  \"invertible_mat A\"\n  using square_mat unitary invertible_mat_def by blast\n\nsubsection \"Relations Between Complex Conjugation, Hermitian Conjugation, Transposition and Unitarity\"\n\nnotation transpose_mat (\"(_\\<^sup>t)\")\n\nlemma col_tranpose [simp]:\n  assumes \"dim_row M = n\" and \"i < n\"\n  shows \"col (M\\<^sup>t) i = row M i\"\nproof\n  show \"dim_vec (col (M\\<^sup>t) i) = dim_vec (row M i)\"\n    by (simp add: row_def col_def transpose_mat_def)\nnext\n  show \"\\<And>j. j < dim_vec (row M i) \\<Longrightarrow> col M\\<^sup>t i $ j = row M i $ j\"\n    using assms by (simp add: transpose_mat_def)\nqed\n\nlemma row_transpose [simp]:\n  assumes \"dim_col M = n\" and \"i < n\"\n  shows \"row (M\\<^sup>t) i = col M i\"\n  using assms by simp\n\ndefinition cpx_mat_cnj :: \"complex mat \\<Rightarrow> complex mat\" (\"(_\\<^sup>\\<star>)\") where\n\"cpx_mat_cnj M \\<equiv> mat (dim_row M) (dim_col M) (\\<lambda>(i,j). cnj (M $$ (i,j)))\"\n\nlemma cpx_mat_cnj_id [simp]:\n  \"(1\\<^sub>m n)\\<^sup>\\<star> = 1\\<^sub>m n\" \n  by (auto simp: cpx_mat_cnj_def)\n\nlemma cpx_mat_cnj_cnj [simp]:\n  \"(M\\<^sup>\\<star>)\\<^sup>\\<star> = M\"\n  by (auto simp: cpx_mat_cnj_def)\n\nlemma dim_row_of_cjn_prod [simp]: \n  \"dim_row ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>)) = dim_row M\"\n  by (simp add: cpx_mat_cnj_def)\n\nlemma dim_col_of_cjn_prod [simp]: \n  \"dim_col ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>)) = dim_col N\"\n  by (simp add: cpx_mat_cnj_def)\n\nlemma cpx_mat_cnj_prod:\n  assumes \"dim_col M = dim_row N\"\n  shows \"(M * N)\\<^sup>\\<star> = (M\\<^sup>\\<star>) * (N\\<^sup>\\<star>)\"\nproof\n  show \"dim_row (M * N)\\<^sup>\\<star> = dim_row ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>))\" \n    by (simp add: cpx_mat_cnj_def)\nnext\n  show \"dim_col ((M * N)\\<^sup>\\<star>) = dim_col ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>))\" \n    by (simp add: cpx_mat_cnj_def)\nnext \n  fix i j::nat\n  assume a1:\"i < dim_row ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>))\" and a2:\"j < dim_col ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>))\"\n  then have \"(M * N)\\<^sup>\\<star> $$ (i,j) = cnj (\\<Sum>k<(dim_row N). M $$ (i,k) * N $$ (k,j))\"\n    using assms cpx_mat_cnj_def index_mat times_mat_def scalar_prod_def row_def col_def \ndim_row_of_cjn_prod dim_col_of_cjn_prod\n    by (smt case_prod_conv dim_col index_mult_mat(2) index_mult_mat(3) index_vec lessThan_atLeast0 \n        lessThan_iff sum.cong)\n  also have \"\\<dots> = (\\<Sum>k<(dim_row N). cnj(M $$ (i,k)) * cnj(N $$ (k,j)))\" by simp\n  also have \"((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>)) $$ (i,j) = \n    (\\<Sum>k<(dim_row N). cnj(M $$ (i,k)) * cnj(N $$ (k,j)))\"\n    using assms a1 a2 cpx_mat_cnj_def index_mat times_mat_def scalar_prod_def row_def col_def\n    by (smt case_prod_conv dim_col dim_col_mat(1) dim_row_mat(1) index_vec lessThan_atLeast0 \n        lessThan_iff sum.cong)\n  finally show \"(M * N)\\<^sup>\\<star> $$ (i, j) = ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>)) $$ (i, j)\" by simp\nqed\n\nlemma transpose_of_prod:\n  fixes M N::\"complex Matrix.mat\"\n  assumes \"dim_col M = dim_row N\"\n  shows \"(M * N)\\<^sup>t = N\\<^sup>t * (M\\<^sup>t)\"\nproof\n  fix i j::nat\n  assume a0: \"i < dim_row (N\\<^sup>t * (M\\<^sup>t))\" and a1: \"j < dim_col (N\\<^sup>t * (M\\<^sup>t))\"  \n  then have \"(M * N)\\<^sup>t $$ (i,j) = (M * N) $$ (j,i)\" by auto\n  also have \"... = (\\<Sum>k<dim_row M\\<^sup>t.  M $$ (j,k) * N $$ (k,i))\"\n    using assms a0 a1 by auto\n  also have \"... = (\\<Sum>k<dim_row M\\<^sup>t. N $$ (k,i) * M $$ (j,k))\"\n   by (simp add: semiring_normalization_rules(7))\n  also have \"... = (\\<Sum>k<dim_row M\\<^sup>t. ((N\\<^sup>t) $$ (i,k)) * (M\\<^sup>t) $$ (k,j))\" \n    using assms a0 a1 by auto\n  finally show \"((M * N)\\<^sup>t) $$ (i,j) = (N\\<^sup>t * (M\\<^sup>t)) $$ (i,j)\" \n    using assms a0 a1 by auto\nnext\n  show \"dim_row ((M * N)\\<^sup>t) = dim_row (N\\<^sup>t * (M\\<^sup>t))\" by auto\nnext\n  show \"dim_col ((M * N)\\<^sup>t) = dim_col (N\\<^sup>t * (M\\<^sup>t))\" by auto\nqed\n\nlemma transpose_cnj_is_dagger [simp]:\n  \"(M\\<^sup>t)\\<^sup>\\<star> = (M\\<^sup>\\<dagger>)\"\nproof\n  show f1:\"dim_row ((M\\<^sup>t)\\<^sup>\\<star>) = dim_row (M\\<^sup>\\<dagger>)\"\n    by (simp add: cpx_mat_cnj_def transpose_mat_def dagger_def)\nnext\n  show f2:\"dim_col ((M\\<^sup>t)\\<^sup>\\<star>) = dim_col (M\\<^sup>\\<dagger>)\" \n    by (simp add: cpx_mat_cnj_def transpose_mat_def dagger_def)\nnext\n  fix i j::nat\n  assume \"i < dim_row M\\<^sup>\\<dagger>\" and \"j < dim_col M\\<^sup>\\<dagger>\"\n  then show \"M\\<^sup>t\\<^sup>\\<star> $$ (i, j) = M\\<^sup>\\<dagger> $$ (i, j)\" \n    by (simp add: cpx_mat_cnj_def transpose_mat_def dagger_def)\nqed\n\nlemma cnj_transpose_is_dagger [simp]:\n  \"(M\\<^sup>\\<star>)\\<^sup>t = (M\\<^sup>\\<dagger>)\"\nproof\n  show \"dim_row ((M\\<^sup>\\<star>)\\<^sup>t) = dim_row (M\\<^sup>\\<dagger>)\" \n    by (simp add: transpose_mat_def cpx_mat_cnj_def dagger_def)\nnext\n  show \"dim_col ((M\\<^sup>\\<star>)\\<^sup>t) = dim_col (M\\<^sup>\\<dagger>)\" \n    by (simp add: transpose_mat_def cpx_mat_cnj_def dagger_def)\nnext\n  fix i j::nat\n  assume \"i < dim_row M\\<^sup>\\<dagger>\" and \"j < dim_col M\\<^sup>\\<dagger>\"\n  then show \"M\\<^sup>\\<star>\\<^sup>t $$ (i, j) = M\\<^sup>\\<dagger> $$ (i, j)\" \n    by (simp add: transpose_mat_def cpx_mat_cnj_def dagger_def)\nqed\n\nlemma dagger_of_transpose_is_cnj [simp]:\n  \"(M\\<^sup>t)\\<^sup>\\<dagger> = (M\\<^sup>\\<star>)\"\n  by (metis transpose_transpose transpose_cnj_is_dagger)\n\nlemma dagger_of_prod:\n  fixes M N::\"complex Matrix.mat\"\n  assumes \"dim_col M = dim_row N\"\n  shows \"(M * N)\\<^sup>\\<dagger> = N\\<^sup>\\<dagger> * (M\\<^sup>\\<dagger>)\"\nproof-\n  have \"(M * N)\\<^sup>\\<dagger> = ((M * N)\\<^sup>\\<star>)\\<^sup>t\" by auto\n  also have \"... = ((M\\<^sup>\\<star>) * (N\\<^sup>\\<star>))\\<^sup>t\" using assms cpx_mat_cnj_prod by auto\n  also have \"... = (N\\<^sup>\\<star>)\\<^sup>t * ((M\\<^sup>\\<star>)\\<^sup>t)\" using assms transpose_of_prod \n    by (metis cnj_transpose_is_dagger dim_col_of_dagger dim_row_of_dagger index_transpose_mat(2) index_transpose_mat(3))\n  finally show \"(M * N)\\<^sup>\\<dagger> = N\\<^sup>\\<dagger> * (M\\<^sup>\\<dagger>)\" by auto\nqed\n\ntext \\<open>The product of two quantum gates is a quantum gate.\\<close>\n\nlemma prod_of_gate_is_gate: \n  assumes \"gate n G1\" and \"gate n G2\"\n  shows \"gate n (G1 * G2)\"\nproof\n  show \"dim_row (G1 * G2) = 2^n\" using assms by (simp add: gate_def)\nnext\n  show \"square_mat (G1 * G2)\" \n    using assms gate.dim_row gate.square_mat by simp\nnext\n  show \"unitary (G1 * G2)\" \n  proof-\n    have \"((G1 * G2)\\<^sup>\\<dagger>) * (G1 * G2) = 1\\<^sub>m (dim_col (G1 * G2))\" \n    proof-\n      have f0: \"G1 \\<in> carrier_mat (2^n) (2^n) \\<and> G2 \\<in> carrier_mat (2^n) (2^n)\n              \\<and> G1\\<^sup>\\<dagger> \\<in> carrier_mat (2^n) (2^n) \\<and> G2\\<^sup>\\<dagger> \\<in> carrier_mat (2^n) (2^n)\n              \\<and> G1 * G2 \\<in> carrier_mat (2^n) (2^n)\" \n        using assms gate.dim_row gate.square_mat by auto\n      have \"((G1 * G2)\\<^sup>\\<dagger>) * (G1 * G2) = ((G2\\<^sup>\\<dagger>) * (G1\\<^sup>\\<dagger>)) * (G1 * G2)\" \n        using assms dagger_of_prod gate.dim_row gate.square_mat by simp\n      also have \"... = (G2\\<^sup>\\<dagger>) * ((G1\\<^sup>\\<dagger>) * (G1 * G2))\" \n        using assms f0 by auto\n      also have \"... = (G2\\<^sup>\\<dagger>) * (((G1\\<^sup>\\<dagger>) * G1) * G2)\" \n        using assms f0 f0 by auto\n      also have \"... = (G2\\<^sup>\\<dagger>) * ((1\\<^sub>m (dim_col G1)) * G2)\" \n        using gate.unitary[of n G1] assms unitary_def[of G1] by simp\n      also have \"... = (G2\\<^sup>\\<dagger>) * ((1\\<^sub>m (dim_col G2)) * G2)\" \n        using assms f0 by (metis carrier_matD(2))\n      also have \"... = (G2\\<^sup>\\<dagger>) * G2\" \n        using f0 by (metis carrier_matD(2) left_mult_one_mat)\n      finally show \"((G1 * G2)\\<^sup>\\<dagger>) * (G1 * G2) = 1\\<^sub>m (dim_col (G1 * G2))\" \n        using assms gate.unitary unitary_def by simp\n    qed\n    moreover have \"(G1 * G2) * ((G1 * G2)\\<^sup>\\<dagger>) = 1\\<^sub>m (dim_row (G1 * G2))\"\n      using assms calculation\n      by (smt carrier_matI dim_col_of_dagger dim_row_of_dagger gate.dim_row gate.square_mat index_mult_mat(2) index_mult_mat(3) \n          mat_mult_left_right_inverse square_mat.elims(2))\n    ultimately show ?thesis using unitary_def by simp\n  qed\nqed\n\nlemma left_inv_of_unitary_transpose [simp]:\n  assumes \"unitary U\"\n  shows \"(U\\<^sup>t)\\<^sup>\\<dagger> * (U\\<^sup>t) =  1\\<^sub>m(dim_row U)\"\nproof -\n  have \"dim_col U = dim_row ((U\\<^sup>t)\\<^sup>\\<star>)\" by simp\n  then have \"(U * ((U\\<^sup>t)\\<^sup>\\<star>))\\<^sup>\\<star> = (U\\<^sup>\\<star>) * (U\\<^sup>t)\"\n    using cpx_mat_cnj_prod cpx_mat_cnj_cnj by presburger\n  also have \"\\<dots> = (U\\<^sup>t)\\<^sup>\\<dagger> * (U\\<^sup>t)\" by simp\n  finally show ?thesis \n    using assms by (metis transpose_cnj_is_dagger cpx_mat_cnj_id unitary_def)\nqed\n\nlemma right_inv_of_unitary_transpose [simp]:\n  assumes \"unitary U\"\n  shows \"U\\<^sup>t * ((U\\<^sup>t)\\<^sup>\\<dagger>) = 1\\<^sub>m(dim_col U)\"\nproof -\n  have \"dim_col ((U\\<^sup>t)\\<^sup>\\<star>) = dim_row U\" by simp\n  then have \"U\\<^sup>t * ((U\\<^sup>t)\\<^sup>\\<dagger>) = (((U\\<^sup>t)\\<^sup>\\<star> * U)\\<^sup>\\<star>)\"\n    using cpx_mat_cnj_cnj cpx_mat_cnj_prod dagger_of_transpose_is_cnj by presburger\n  also have \"\\<dots> = (U\\<^sup>\\<dagger> * U)\\<^sup>\\<star>\" by simp\n  finally show ?thesis\n    using assms by (metis cpx_mat_cnj_id unitary_def)\nqed\n\nlemma transpose_of_unitary_is_unitary [simp]:\n  assumes \"unitary U\"\n  shows \"unitary (U\\<^sup>t)\" \n  using unitary_def assms left_inv_of_unitary_transpose right_inv_of_unitary_transpose by simp\n\n\nsubsection \"The Inner Product\"\n\ntext \\<open>We introduce a coercion between complex vectors and (column) complex matrices.\\<close>\n\ndefinition ket_vec :: \"complex vec \\<Rightarrow> complex mat\" (\"|_\\<rangle>\") where\n\"|v\\<rangle> \\<equiv> mat (dim_vec v) 1 (\\<lambda>(i,j). v $ i)\"\n\nlemma ket_vec_index [simp]:\n  assumes \"i < dim_vec v\"\n  shows \"|v\\<rangle> $$ (i,0) = v $ i\"\n  using assms ket_vec_def by simp\n\nlemma ket_vec_col [simp]:\n  \"col |v\\<rangle> 0 = v\"\n  by (auto simp: col_def ket_vec_def)\n\nlemma smult_ket_vec [simp]:\n  \"|x \\<cdot>\\<^sub>v v\\<rangle> = x \\<cdot>\\<^sub>m |v\\<rangle>\"\n  by (auto simp: ket_vec_def)\n\nlemma smult_vec_length_bis [simp]:\n  assumes \"x \\<ge> 0\"\n  shows \"\\<parallel>col (complex_of_real(x) \\<cdot>\\<^sub>m |v\\<rangle>) 0\\<parallel> = x * \\<parallel>v\\<parallel>\"\n  using assms smult_ket_vec smult_vec_length ket_vec_col by metis\n\ndeclare [[coercion ket_vec]]\n\ndefinition row_vec :: \"complex vec \\<Rightarrow> complex mat\" where\n\"row_vec v \\<equiv> mat 1 (dim_vec v) (\\<lambda>(i,j). v $ j)\" \n\ndefinition bra_vec :: \"complex vec \\<Rightarrow> complex mat\" where\n\"bra_vec v \\<equiv> (row_vec v)\\<^sup>\\<star>\"\n\nlemma row_bra_vec [simp]:\n  \"row (bra_vec v) 0 = vec (dim_vec v) (\\<lambda>i. cnj(v $ i))\"\n  by (auto simp: row_def bra_vec_def cpx_mat_cnj_def row_vec_def)\n\ntext \\<open>We introduce a definition called @{term \"bra\"} to see a vector as a column matrix.\\<close>\n\ndefinition bra :: \"complex mat \\<Rightarrow> complex mat\" (\"\\<langle>_|\") where\n\"\\<langle>v| \\<equiv> mat 1 (dim_row v) (\\<lambda>(i,j). cnj(v $$ (j,i)))\"\n\ntext \\<open>The relation between @{term \"bra\"}, @{term \"bra_vec\"} and @{term \"ket_vec\"} is given as follows.\\<close>\n\nlemma bra_bra_vec [simp]:\n  \"bra (ket_vec v) = bra_vec v\"\n  by (auto simp: bra_def ket_vec_def bra_vec_def cpx_mat_cnj_def row_vec_def)\n\nlemma row_bra [simp]:\n  fixes v::\"complex vec\"\n  shows \"row \\<langle>v| 0 = vec (dim_vec v) (\\<lambda>i. cnj (v $ i))\" by simp\n\ntext \\<open>We introduce the inner product of two complex vectors in @{text \"\\<complex>\\<^sup>n\"}.\\<close>\n\ndefinition inner_prod :: \"complex vec \\<Rightarrow> complex vec \\<Rightarrow> complex\" (\"\\<langle>_|_\\<rangle>\") where\n\"inner_prod u v \\<equiv> \\<Sum> i \\<in> {0..< dim_vec v}. cnj(u $ i) * (v $ i)\"\n\nlemma inner_prod_with_row_bra_vec [simp]:\n  assumes \"dim_vec u = dim_vec v\"\n  shows \"\\<langle>u|v\\<rangle> = row (bra_vec u) 0 \\<bullet> v\"\n  using assms inner_prod_def scalar_prod_def row_bra_vec index_vec\n  by (smt lessThan_atLeast0 lessThan_iff sum.cong)\n\nlemma inner_prod_with_row_bra_vec_col_ket_vec [simp]:\n  assumes \"dim_vec u = dim_vec v\"\n  shows \"\\<langle>u|v\\<rangle> = (row \\<langle>u| 0) \\<bullet> (col |v\\<rangle> 0)\"\n  using assms by (simp add: inner_prod_def scalar_prod_def)\n\nlemma inner_prod_with_times_mat [simp]:\n  assumes \"dim_vec u = dim_vec v\"\n  shows \"\\<langle>u|v\\<rangle> = (\\<langle>u| * |v\\<rangle>) $$ (0,0)\"\n  using assms inner_prod_with_row_bra_vec_col_ket_vec \n  by (simp add: inner_prod_def times_mat_def ket_vec_def bra_def)\n\nlemma orthogonal_unit_vec [simp]:\n  assumes \"i < n\" and \"j < n\" and \"i \\<noteq> j\"\n  shows \"\\<langle>unit_vec n i|unit_vec n j\\<rangle> = 0\"\nproof-\n  have \"\\<langle>unit_vec n i|unit_vec n j\\<rangle> = unit_vec n i \\<bullet> unit_vec n j\"\n    using assms unit_vec_def inner_prod_def scalar_prod_def\n    by (smt complex_cnj_zero index_unit_vec(3) index_vec inner_prod_with_row_bra_vec row_bra_vec \n        scalar_prod_right_unit)\n  thus ?thesis\n    using assms scalar_prod_def unit_vec_def by simp \nqed\n\ntext \\<open>We prove that our inner product is linear in its second argument.\\<close>\n\n\n\nlemma inner_prod_is_linear [simp]:\n  fixes u::\"complex vec\" and v::\"nat \\<Rightarrow> complex vec\" and l::\"nat \\<Rightarrow> complex\"\n  assumes \"\\<forall>i\\<in>{0, 1}. dim_vec u = dim_vec (v i)\"\n  shows \"\\<langle>u|l 0 \\<cdot>\\<^sub>v v 0 + l 1 \\<cdot>\\<^sub>v v 1\\<rangle> = (\\<Sum>i\\<le>1. l i * \\<langle>u|v i\\<rangle>)\"\nproof -\n  have f1:\"dim_vec (l 0 \\<cdot>\\<^sub>v v 0 + l 1 \\<cdot>\\<^sub>v v 1) = dim_vec u\"\n    using assms by simp\n  then have \"\\<langle>u|l 0 \\<cdot>\\<^sub>v v 0 + l 1 \\<cdot>\\<^sub>v v 1\\<rangle> = (\\<Sum>i\\<in>{0 ..< dim_vec u}. cnj (u $ i) * ((l 0 \\<cdot>\\<^sub>v v 0 + l 1 \\<cdot>\\<^sub>v v 1) $ i))\"\n    by (simp add: inner_prod_def)\n  also have \"\\<dots> = (\\<Sum>i\\<in>{0 ..< dim_vec u}. cnj (u $ i) * (l 0 * v 0 $ i + l 1 * v 1 $ i))\"\n    using assms by simp\n  also have \"\\<dots> = l 0 * (\\<Sum>i\\<in>{0 ..< dim_vec u}. cnj(u $ i) * (v 0 $ i)) + l 1 * (\\<Sum>i\\<in>{0 ..< dim_vec u}. cnj(u $ i) * (v 1 $ i))\"\n    by (auto simp: algebra_simps)\n      (simp add: sum.distrib sum_distrib_left)\n  also have \"\\<dots> = l 0 * \\<langle>u|v 0\\<rangle> + l 1 * \\<langle>u|v 1\\<rangle>\"\n    using assms inner_prod_def by auto\n  finally show ?thesis by simp\nqed\n\nlemma inner_prod_cnj:\n  assumes \"dim_vec u = dim_vec v\"\n  shows \"\\<langle>v|u\\<rangle> = cnj (\\<langle>u|v\\<rangle>)\"\n  by (simp add: assms inner_prod_def algebra_simps)\n\nlemma inner_prod_with_itself_Im [simp]:\n  \"Im (\\<langle>u|u\\<rangle>) = 0\"\n  using inner_prod_cnj by (metis Reals_cnj_iff complex_is_Real_iff)\n\nlemma inner_prod_with_itself_real [simp]:\n  \"\\<langle>u|u\\<rangle> \\<in> \\<real>\"\n  using inner_prod_with_itself_Im by (simp add: complex_is_Real_iff)\n\nlemma inner_prod_with_itself_eq0 [simp]:\n  assumes \"u = 0\\<^sub>v (dim_vec u)\"\n  shows \"\\<langle>u|u\\<rangle> = 0\"\n  using assms inner_prod_def zero_vec_def\n  by (smt atLeastLessThan_iff complex_cnj_zero index_zero_vec(1) mult_zero_left sum.neutral)\n\nlemma inner_prod_with_itself_Re:\n  \"Re (\\<langle>u|u\\<rangle>) \\<ge> 0\"\nproof -\n  have \"Re (\\<langle>u|u\\<rangle>) = (\\<Sum>i<dim_vec u. Re (cnj(u $ i) * (u $ i)))\"\n    by (simp add: inner_prod_def lessThan_atLeast0)\n  moreover have \"\\<dots> = (\\<Sum>i<dim_vec u. (Re (u $ i))\\<^sup>2 + (Im (u $ i))\\<^sup>2)\"\n    using complex_mult_cnj\n    by (metis (no_types, lifting) Re_complex_of_real semiring_normalization_rules(7))\n  ultimately show \"Re (\\<langle>u|u\\<rangle>) \\<ge> 0\" by (simp add: sum_nonneg)\nqed\n\nlemma inner_prod_with_itself_nonneg_reals:\n  fixes u::\"complex vec\"\n  shows \"\\<langle>u|u\\<rangle> \\<in> nonneg_Reals\"\n  using inner_prod_with_itself_real inner_prod_with_itself_Re complex_nonneg_Reals_iff \ninner_prod_with_itself_Im by auto\n\nlemma inner_prod_with_itself_Re_non0:\n  assumes \"u \\<noteq> 0\\<^sub>v (dim_vec u)\"\n  shows \"Re (\\<langle>u|u\\<rangle>) > 0\"\nproof -\n  obtain i where a1:\"i < dim_vec u\" and \"u $ i \\<noteq> 0\"\n    using assms zero_vec_def by (metis dim_vec eq_vecI index_zero_vec(1))\n  then have f1:\"Re (cnj (u $ i) * (u $ i)) > 0\"\n    by (metis Re_complex_of_real complex_mult_cnj complex_neq_0 mult.commute)\n  moreover have f2:\"Re (\\<langle>u|u\\<rangle>) = (\\<Sum>i<dim_vec u. Re (cnj(u $ i) * (u $ i)))\"\n    using inner_prod_def by (simp add: lessThan_atLeast0)\n  moreover have f3:\"\\<forall>i<dim_vec u. Re (cnj(u $ i) * (u $ i)) \\<ge> 0\"\n    using complex_mult_cnj by simp\n  ultimately show ?thesis\n    using a1 inner_prod_def lessThan_iff\n    by (metis (no_types, lifting) finite_lessThan sum_pos2)\nqed\n\nlemma inner_prod_with_itself_nonneg_reals_non0:\n  assumes \"u \\<noteq> 0\\<^sub>v (dim_vec u)\"\n  shows \"\\<langle>u|u\\<rangle> \\<noteq> 0\"\n  using assms inner_prod_with_itself_Re_non0 by fastforce\n\nlemma cpx_vec_length_inner_prod [simp]:\n  \"\\<parallel>v\\<parallel>\\<^sup>2 = \\<langle>v|v\\<rangle>\"\nproof -\n  have \"\\<parallel>v\\<parallel>\\<^sup>2 = (\\<Sum>i<dim_vec v. (cmod (v $ i))\\<^sup>2)\"\n    using cpx_vec_length_def complex_of_real_def\n    by (metis (no_types, lifting) real_sqrt_power real_sqrt_unique sum_nonneg zero_le_power2)\n  also have \"\\<dots> = (\\<Sum>i<dim_vec v. cnj (v $ i) * (v $ i))\"\n    using complex_norm_square mult.commute by (smt of_real_sum sum.cong)\n  finally show ?thesis\n    using inner_prod_def by (simp add: lessThan_atLeast0)\nqed\n\nlemma inner_prod_csqrt [simp]:\n  \"csqrt \\<langle>v|v\\<rangle> = \\<parallel>v\\<parallel>\"\n  using inner_prod_with_itself_Re inner_prod_with_itself_Im csqrt_of_real_nonneg cpx_vec_length_def\n  by (metis (no_types, lifting) Re_complex_of_real cpx_vec_length_inner_prod real_sqrt_ge_0_iff \n      real_sqrt_unique sum_nonneg zero_le_power2)\n\n\nsubsection \"Unitary Matrices and Length-Preservation\"\n\nsubsubsection \"Unitary Matrices are Length-Preserving\"\n\ntext \\<open>The bra-vector @{text \"\\<langle>A * v|\"} is given by @{text \"\\<langle>v| * A\\<^sup>\\<dagger>\"}\\<close>\n\nlemma dagger_of_ket_is_bra:\n  fixes v:: \"complex vec\"\n  shows \"( |v\\<rangle> )\\<^sup>\\<dagger> = \\<langle>v|\"\n  by (simp add: bra_def dagger_def ket_vec_def)\n\nlemma bra_mat_on_vec:\n  fixes v::\"complex vec\" and A::\"complex mat\"\n  assumes \"dim_col A = dim_vec v\"\n  shows \"\\<langle>A * v| = \\<langle>v| * (A\\<^sup>\\<dagger>)\"\nproof\n  show \"dim_row \\<langle>A * v| = dim_row (\\<langle>v| * (A\\<^sup>\\<dagger>))\"\n    by (simp add: bra_def times_mat_def)\nnext\n  show \"dim_col \\<langle>A * v| = dim_col (\\<langle>v| * (A\\<^sup>\\<dagger>))\"\n    by (simp add: bra_def times_mat_def)\nnext\n  fix i j::nat\n  assume a1:\"i < dim_row (\\<langle>v| * (A\\<^sup>\\<dagger>))\" and a2:\"j < dim_col (\\<langle>v| * (A\\<^sup>\\<dagger>))\" \n  then have \"cnj((A * v) $$ (j,0)) = cnj (row A j \\<bullet> v)\"\n    using bra_def times_mat_def ket_vec_col ket_vec_def by simp\n  also have f7:\"\\<dots>= (\\<Sum>i\\<in>{0 ..< dim_vec v}. cnj(v $ i) * cnj(A $$ (j,i)))\"\n    using row_def scalar_prod_def cnj_sum complex_cnj_mult mult.commute\n    by (smt assms index_vec lessThan_atLeast0 lessThan_iff sum.cong)\n  moreover have f8:\"(row \\<langle>v| 0) \\<bullet> (col (A\\<^sup>\\<dagger>) j) = \n    vec (dim_vec v) (\\<lambda>i. cnj (v $ i)) \\<bullet> vec (dim_col A) (\\<lambda>i. cnj (A $$ (j,i)))\"\n    using a2 by simp \n  ultimately have \"cnj((A * v) $$ (j,0)) = (row \\<langle>v| 0) \\<bullet> (col (A\\<^sup>\\<dagger>) j)\"\n    using assms scalar_prod_def\n    by (smt dim_vec index_vec lessThan_atLeast0 lessThan_iff sum.cong)\n  then have \"\\<langle>A * v| $$ (0,j) = (\\<langle>v| * (A\\<^sup>\\<dagger>)) $$ (0,j)\"\n    using bra_def times_mat_def a2 by simp\n  thus \"\\<langle>A * |v\\<rangle>| $$ (i, j) = (\\<langle>v| * (A\\<^sup>\\<dagger>)) $$ (i, j)\" \n    using a1 by (simp add: times_mat_def bra_def)\nqed\n\nlemma mat_on_ket:\n  fixes v:: \"complex vec\" and A:: \"complex mat\"\n  assumes \"dim_col A = dim_vec v\"\n  shows \"A * |v\\<rangle> = |col (A * v) 0\\<rangle>\"\n  using assms ket_vec_def by auto\n\nlemma dagger_of_mat_on_ket:\n  fixes v:: \"complex vec\" and A :: \"complex mat\"\n  assumes \"dim_col A = dim_vec v\"\n  shows \"(A * |v\\<rangle> )\\<^sup>\\<dagger> = \\<langle>v| * (A\\<^sup>\\<dagger>)\"\n  using assms by (metis bra_mat_on_vec dagger_of_ket_is_bra mat_on_ket)\n\ndefinition col_fst :: \"'a mat \\<Rightarrow> 'a vec\" where \n  \"col_fst A = vec (dim_row A) (\\<lambda> i. A $$ (i,0))\"\n\nlemma col_fst_is_col [simp]:\n  \"col_fst M = col M 0\"\n  by (simp add: col_def col_fst_def)\n\ntext \\<open>\nWe need to declare @{term \"col_fst\"} as a coercion from matrices to vectors in order to see a column \nmatrix as a vector. \n\\<close>\n\ndeclare \n  [[coercion_delete ket_vec]]\n  [[coercion col_fst]]\n\nlemma unit_vec_to_col:\n  assumes \"dim_col A = n\" and \"i < n\"\n  shows \"col A i = A * |unit_vec n i\\<rangle>\"\nproof\n  show \"dim_vec (col A i) = dim_vec (A * |unit_vec n i\\<rangle>)\"\n    using col_def times_mat_def by simp\nnext\n  fix j::nat\n  assume \"j < dim_vec (col_fst (A * |unit_vec n i\\<rangle>))\"\n  then show \"col A i $ j = (A * |unit_vec n i\\<rangle>) $ j\"\n    using assms times_mat_def ket_vec_def\n    by (smt col_fst_is_col dim_col dim_col_mat(1) index_col index_mult_mat(1) index_mult_mat(2) \nindex_row(1) ket_vec_col less_numeral_extra(1) scalar_prod_right_unit)\nqed\n\nlemma mult_ket_vec_is_ket_vec_of_mult:\n  fixes A::\"complex mat\" and v::\"complex vec\"\n  assumes \"dim_col A = dim_vec v\"\n  shows \"|A * |v\\<rangle> \\<rangle> = A * |v\\<rangle>\"\n  using assms ket_vec_def\n  by (metis One_nat_def col_fst_is_col dim_col dim_col_mat(1) index_mult_mat(3) ket_vec_col less_Suc0 \nmat_col_eqI)\n\nlemma unitary_is_sq_length_preserving [simp]:\n  assumes \"unitary U\" and \"dim_vec v = dim_col U\"\n  shows \"\\<parallel>U * |v\\<rangle>\\<parallel>\\<^sup>2 = \\<parallel>v\\<parallel>\\<^sup>2\"\nproof -\n  have \"\\<langle>U * |v\\<rangle>|U * |v\\<rangle> \\<rangle> = (\\<langle>|v\\<rangle>| * (U\\<^sup>\\<dagger>) * |U * |v\\<rangle>\\<rangle>) $$ (0,0)\"\n    using assms(2) bra_mat_on_vec\n    by (metis inner_prod_with_times_mat mult_ket_vec_is_ket_vec_of_mult)\n  then have \"\\<langle>U * |v\\<rangle>|U * |v\\<rangle> \\<rangle> = (\\<langle>|v\\<rangle>| * (U\\<^sup>\\<dagger>) * (U * |v\\<rangle>)) $$ (0,0)\"\n    using assms(2) mult_ket_vec_is_ket_vec_of_mult by simp\n  moreover have f1:\"dim_col \\<langle>|v\\<rangle>| = dim_vec v\"\n    using ket_vec_def bra_def by simp\n  moreover have \"dim_row (U\\<^sup>\\<dagger>) = dim_vec v\"\n    using assms(2) by simp\n  ultimately have \"\\<langle>U * |v\\<rangle>|U * |v\\<rangle> \\<rangle> = (\\<langle>|v\\<rangle>| * ((U\\<^sup>\\<dagger>) * U) * |v\\<rangle>) $$ (0,0)\"\n    using assoc_mult_mat\n    by(smt carrier_mat_triv dim_row_mat(1) dagger_def ket_vec_def mat_carrier times_mat_def)\n  then have \"\\<langle>U * |v\\<rangle>|U * |v\\<rangle> \\<rangle> = (\\<langle>|v\\<rangle>| * |v\\<rangle>) $$ (0,0)\"\n    using assms f1 unitary_def by simp\n  thus ?thesis\n    using cpx_vec_length_inner_prod by(metis Re_complex_of_real inner_prod_with_times_mat)\nqed\n\nlemma col_ket_vec [simp]:\n  assumes \"dim_col M = 1\"\n  shows \"|col M 0\\<rangle> = M\"\n  using eq_matI assms ket_vec_def by auto\n\nlemma state_col_ket_vec:\n  assumes \"state 1 v\"\n  shows \"state 1 |col v 0\\<rangle>\"\n  using assms by (simp add: state_def)\n\nlemma col_ket_vec_index [simp]:\n  assumes \"i < dim_row v\"\n  shows \"|col v 0\\<rangle> $$ (i,0) = v $$ (i,0)\"\n  using assms ket_vec_def by (simp add: col_def)\n\nlemma col_index_of_mat_col [simp]:\n  assumes \"dim_col v = 1\" and \"i < dim_row v\"\n  shows \"col v 0 $ i = v $$ (i,0)\"\n  using assms by simp\n\nlemma unitary_is_sq_length_preserving_bis [simp]:\n  assumes \"unitary U\" and \"dim_row v = dim_col U\" and \"dim_col v = 1\"\n  shows \"\\<parallel>col (U * v) 0\\<parallel>\\<^sup>2 = \\<parallel>col v 0\\<parallel>\\<^sup>2\"\nproof -\n  have \"dim_vec (col v 0) = dim_col U\"\n    using assms(2) by simp\n  then have \"\\<parallel>col_fst (U * |col v 0\\<rangle>)\\<parallel>\\<^sup>2 = \\<parallel>col v 0\\<parallel>\\<^sup>2\"\n    using unitary_is_sq_length_preserving[of \"U\" \"col v 0\"] assms(1) by simp\n  thus ?thesis\n    using assms(3) by simp\nqed\n\ntext \\<open> \nA unitary matrix is length-preserving, i.e. it acts on a vector to produce another vector of the \nsame length. \n\\<close>\n\nlemma unitary_is_length_preserving_bis [simp]:\n  fixes U::\"complex mat\" and v::\"complex mat\"\n  assumes \"unitary U\" and \"dim_row v = dim_col U\" and \"dim_col v = 1\"\n  shows \"\\<parallel>col (U * v) 0\\<parallel> = \\<parallel>col v 0\\<parallel>\"\n  using assms unitary_is_sq_length_preserving_bis\n  by (metis cpx_vec_length_inner_prod inner_prod_csqrt of_real_hom.injectivity)\n\nlemma unitary_is_length_preserving [simp]:\n  fixes U:: \"complex mat\" and v:: \"complex vec\"\n  assumes \"unitary U\" and \"dim_vec v = dim_col U\"\n  shows \"\\<parallel>U * |v\\<rangle>\\<parallel> = \\<parallel>v\\<parallel>\"\n  using assms unitary_is_sq_length_preserving\n  by (metis cpx_vec_length_inner_prod inner_prod_csqrt of_real_hom.injectivity)\n\n\nsubsubsection \"Length-Preserving Matrices are Unitary\"\n\nlemma inverts_mat_sym:\n  fixes A B:: \"complex mat\"\n  assumes \"inverts_mat A B\" and \"dim_row B = dim_col A\" and \"square_mat B\"\n  shows \"inverts_mat B A\"\nproof-\n  define n where d0:\"n = dim_row B\"\n  have \"A * B = 1\\<^sub>m (dim_row A)\" using assms(1) inverts_mat_def by auto\n  moreover have \"dim_col B = dim_col (A * B)\" using times_mat_def by simp\n  ultimately have \"dim_col B = dim_row A\" by simp\n  then have c0:\"A \\<in> carrier_mat n n\" using assms(2,3) d0 by auto\n  have c1:\"B \\<in> carrier_mat n n\" using assms(3) d0 by auto\n  have f0:\"A * B = 1\\<^sub>m n\" using inverts_mat_def c0 c1 assms(1) by auto\n  have f1:\"det B \\<noteq> 0\"\n  proof\n    assume \"det B = 0\"\n    then have \"\\<exists>v. v \\<in> carrier_vec n \\<and> v \\<noteq> 0\\<^sub>v n \\<and> B *\\<^sub>v v = 0\\<^sub>v n\"\n      using det_0_iff_vec_prod_zero assms(3) c1 by blast\n    then obtain v where d1:\"v \\<in> carrier_vec n \\<and> v \\<noteq> 0\\<^sub>v n \\<and> B *\\<^sub>v v = 0\\<^sub>v n\" by auto\n    then have d2:\"dim_vec v = n\" by simp\n    have \"B * |v\\<rangle> = |0\\<^sub>v n\\<rangle>\"\n    proof\n      show \"dim_row (B * |v\\<rangle>) = dim_row |0\\<^sub>v n\\<rangle>\" using ket_vec_def d0 by simp\n    next\n      show \"dim_col (B * |v\\<rangle>) = dim_col |0\\<^sub>v n\\<rangle>\" using ket_vec_def d0 by simp\n    next\n      fix i j assume \"i < dim_row |0\\<^sub>v n\\<rangle>\" and \"j < dim_col |0\\<^sub>v n\\<rangle>\"\n      then have f2:\"i < n \\<and> j = 0\" using ket_vec_def by simp\n      moreover have \"vec (dim_row B) (($) v) = v\" using d0 d1 by auto\n      moreover have \"(B *\\<^sub>v v) $ i = (\\<Sum>ia = 0..<dim_row B. row B i $ ia * v $ ia)\"\n        using d0 d2 f2 by (auto simp add: scalar_prod_def)\n      ultimately show \"(B * |v\\<rangle>) $$ (i, j) = |0\\<^sub>v n\\<rangle> $$ (i, j)\"\n        using ket_vec_def d0 d1 times_mat_def mult_mat_vec_def by (auto simp add: scalar_prod_def)\n    qed\n    moreover have \"|v\\<rangle> \\<in> carrier_mat n 1\" using d2 ket_vec_def by simp\n    ultimately have \"(A * B) * |v\\<rangle> = A * |0\\<^sub>v n\\<rangle>\" using c0 c1 by simp\n    then have f3:\"|v\\<rangle> = A * |0\\<^sub>v n\\<rangle>\" using d2 f0 ket_vec_def by auto\n    have \"v = 0\\<^sub>v n\"\n    proof\n      show \"dim_vec v = dim_vec (0\\<^sub>v n)\" using d2 by simp\n    next\n      fix i assume f4:\"i < dim_vec (0\\<^sub>v n)\"\n      then have \"|v\\<rangle> $$ (i,0) = v $ i\" using d2 ket_vec_def by simp\n      moreover have \"(A * |0\\<^sub>v n\\<rangle>) $$ (i, 0) = 0\"\n        using ket_vec_def times_mat_def scalar_prod_def f4 c0 by auto\n      ultimately show \"v $ i = 0\\<^sub>v n $ i\" using f3 f4 by simp\n    qed\n    then show False using d1 by simp\n  qed\n  have f5:\"adj_mat B \\<in> carrier_mat n n \\<and> B * adj_mat B = det B \\<cdot>\\<^sub>m 1\\<^sub>m n\" using c1 adj_mat by auto\n  then have c2:\"((1/det B) \\<cdot>\\<^sub>m adj_mat B) \\<in> carrier_mat n n\" by simp\n  have f6:\"B * ((1/det B) \\<cdot>\\<^sub>m adj_mat B) = 1\\<^sub>m n\" using c1 f1 f5 mult_smult_distrib[of \"B\"] by auto\n  then have \"A = (A * B) * ((1/det B) \\<cdot>\\<^sub>m adj_mat B)\" using c0 c1 c2 by simp\n  then have \"A = (1/det B) \\<cdot>\\<^sub>m adj_mat B\" using f0 c2 by auto\n  then show ?thesis using c0 c1 f6 inverts_mat_def by auto\nqed\n\nlemma sum_of_unit_vec_length:\n  fixes i j n:: nat and c:: complex\n  assumes \"i < n\" and \"j < n\" and \"i \\<noteq> j\"\n  shows \"\\<parallel>unit_vec n i + c \\<cdot>\\<^sub>v unit_vec n j\\<parallel>\\<^sup>2 = 1 + cnj(c) * c\"\nproof-\n  define v where d0:\"v = unit_vec n i + c \\<cdot>\\<^sub>v unit_vec n j\"\n  have \"\\<forall>k<n. v $ k = (if k = i then 1 else (if k = j then c else 0))\"\n    using d0 assms(1,2,3) by auto\n  then have \"\\<forall>k<n. cnj (v $ k) * v $ k = (if k = i then 1 else 0) + (if k = j then cnj(c) * c else 0)\"\n    using assms(3) by auto\n  moreover have \"\\<parallel>v\\<parallel>\\<^sup>2 = (\\<Sum>k = 0..<n. cnj (v $ k) * v $ k)\"\n    using d0 assms cpx_vec_length_inner_prod inner_prod_def by simp\n  ultimately show ?thesis\n    using d0 assms by (auto simp add: sum.distrib)\nqed\n\nlemma sum_of_unit_vec_to_col:\n  assumes \"dim_col A = n\" and \"i < n\" and \"j < n\"\n  shows \"col A i + c \\<cdot>\\<^sub>v col A j = A * |unit_vec n i + c \\<cdot>\\<^sub>v unit_vec n j\\<rangle>\"\nproof\n  show \"dim_vec (col A i + c \\<cdot>\\<^sub>v col A j) = dim_vec (col_fst (A * |unit_vec n i + c \\<cdot>\\<^sub>v unit_vec n j\\<rangle>))\"\n    using assms(1) by auto\nnext\n  fix k assume \"k < dim_vec (col_fst (A * |unit_vec n i + c \\<cdot>\\<^sub>v unit_vec n j\\<rangle>))\"\n  then have f0:\"k < dim_row A\" using assms(1) by auto\n  have \"(col A i + c \\<cdot>\\<^sub>v col A j) $ k = A $$ (k, i) + c * A $$ (k, j)\"\n    using f0 assms(1-3) by auto\n  moreover have \"(\\<Sum>x<n. A $$ (k, x) * ((if x = i then 1 else 0) + c * (if x = j then 1 else 0))) = \n                 (\\<Sum>x<n. A $$ (k, x) * (if x = i then 1 else 0)) + \n                 (\\<Sum>x<n. A $$ (k, x) * c * (if x = j then 1 else 0))\"\n    by (auto simp add: sum.distrib algebra_simps)\n  moreover have \"\\<forall>x<n. A $$ (k, x) * (if x = i then 1 else 0) = (if x = i then A $$ (k, x) else 0)\"\n    by simp\n  moreover have \"\\<forall>x<n. A $$ (k, x) * c * (if x = j then 1 else 0) = (if x = j then A $$ (k, x) * c else 0)\"\n    by simp\n  ultimately show \"(col A i + c \\<cdot>\\<^sub>v col A j) $ k = col_fst (A * |unit_vec n i + c \\<cdot>\\<^sub>v unit_vec n j\\<rangle>) $ k\"\n    using f0 assms(1-3) times_mat_def scalar_prod_def ket_vec_def by auto\nqed\n\nlemma inner_prod_is_sesquilinear:\n  fixes u1 u2 v1 v2:: \"complex vec\" and c1 c2 c3 c4:: complex and n:: nat\n  assumes \"dim_vec u1 = n\" and \"dim_vec u2 = n\" and \"dim_vec v1 = n\" and \"dim_vec v2 = n\"\n  shows \"\\<langle>c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2|c3 \\<cdot>\\<^sub>v v1 + c4 \\<cdot>\\<^sub>v v2\\<rangle> = cnj (c1) * c3 * \\<langle>u1|v1\\<rangle> + cnj (c2) * c3 * \\<langle>u2|v1\\<rangle> + \n                                                 cnj (c1) * c4 * \\<langle>u1|v2\\<rangle> + cnj (c2) * c4 * \\<langle>u2|v2\\<rangle>\"\nproof-\n  have \"\\<langle>c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2|c3 \\<cdot>\\<^sub>v v1 + c4 \\<cdot>\\<^sub>v v2\\<rangle> = c3 * \\<langle>c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2|v1\\<rangle> + c4 * \\<langle>c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2|v2\\<rangle>\"\n    using inner_prod_is_linear[of \"c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2\" \"\\<lambda>i. if i = 0 then v1 else v2\" \n                                  \"\\<lambda>i. if i = 0 then c3 else c4\"] assms\n    by simp\n  also have \"... = c3 * cnj(\\<langle>v1|c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2\\<rangle>) + c4 * cnj(\\<langle>v2|c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2\\<rangle>)\"\n    using assms inner_prod_cnj[of \"v1\" \"c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2\"] inner_prod_cnj[of \"v2\" \"c1 \\<cdot>\\<^sub>v u1 + c2 \\<cdot>\\<^sub>v u2\"] \n    by simp\n  also have \"... = c3 * cnj(c1 * \\<langle>v1|u1\\<rangle> + c2 * \\<langle>v1|u2\\<rangle>) + c4 * cnj(c1 * \\<langle>v2|u1\\<rangle> + c2 * \\<langle>v2|u2\\<rangle>)\"\n    using inner_prod_is_linear[of \"v1\" \"\\<lambda>i. if i = 0 then u1 else u2\" \"\\<lambda>i. if i = 0 then c1 else c2\"] \n          inner_prod_is_linear[of \"v2\" \"\\<lambda>i. if i = 0 then u1 else u2\" \"\\<lambda>i. if i = 0 then c1 else c2\"] assms\n    by simp\n  also have \"... = c3 * (cnj(c1) * \\<langle>u1|v1\\<rangle> + cnj(c2) * \\<langle>u2|v1\\<rangle>) + \n                   c4 * (cnj(c1) * \\<langle>u1|v2\\<rangle> + cnj(c2) * \\<langle>u2|v2\\<rangle>)\"\n    using inner_prod_cnj[of \"v1\" \"u1\"] inner_prod_cnj[of \"v1\" \"u2\"] \n          inner_prod_cnj[of \"v2\" \"u1\"] inner_prod_cnj[of \"v2\" \"u2\"] assms\n    by simp\n  finally show ?thesis\n    by (auto simp add: algebra_simps)\nqed\n\ntext \\<open>\nA length-preserving matrix is unitary. So, unitary matrices are exactly the length-preserving\nmatrices.\n\\<close>\n\nlemma length_preserving_is_unitary:\n  fixes U:: \"complex mat\"\n  assumes \"square_mat U\" and \"\\<forall>v::complex vec. dim_vec v = dim_col U \\<longrightarrow> \\<parallel>U * |v\\<rangle>\\<parallel> = \\<parallel>v\\<parallel>\"\n  shows \"unitary U\"\nproof-\n  define n where \"n = dim_col U\"\n  then have c0:\"U \\<in> carrier_mat n n\" using assms(1) by auto\n  then have c1:\"U\\<^sup>\\<dagger> \\<in> carrier_mat n n\" using assms(1) dagger_def by auto\n  have f0:\"(U\\<^sup>\\<dagger>) * U = 1\\<^sub>m (dim_col U)\"\n  proof\n    show \"dim_row (U\\<^sup>\\<dagger> * U) = dim_row (1\\<^sub>m (dim_col U))\" using c0 by simp\n  next\n    show \"dim_col (U\\<^sup>\\<dagger> * U) = dim_col (1\\<^sub>m (dim_col U))\" using c0 by simp\n  next\n    fix i j assume \"i < dim_row (1\\<^sub>m (dim_col U))\" and \"j < dim_col (1\\<^sub>m (dim_col U))\"\n    then have a0:\"i < n \\<and> j < n\" using c0 by simp\n    have f1:\"\\<And>l. l<n \\<longrightarrow> (\\<Sum>k<n. cnj (U $$ (k, l)) * U $$ (k, l)) = 1\"\n    proof\n      fix l assume a1:\"l<n\"\n      define v::\"complex vec\" where d1:\"v = unit_vec n l\"\n      have \"\\<parallel>col U l\\<parallel>\\<^sup>2 = (\\<Sum>k<n. cnj (U $$ (k, l)) * U $$ (k, l))\"\n        using c0 a1 cpx_vec_length_inner_prod inner_prod_def lessThan_atLeast0 by simp\n      moreover have \"\\<parallel>col U l\\<parallel>\\<^sup>2 = \\<parallel>v\\<parallel>\\<^sup>2\" using c0 d1 a1 assms(2) unit_vec_to_col by simp\n      moreover have \"\\<parallel>v\\<parallel>\\<^sup>2 = 1\" using d1 a1 cpx_vec_length_inner_prod by simp\n      ultimately show \"(\\<Sum>k<n. cnj (U $$ (k, l)) * U $$ (k, l)) = 1\" by simp\n    qed\n    moreover have \"i \\<noteq> j \\<longrightarrow> (\\<Sum>k<n. cnj (U $$ (k, i)) * U $$ (k, j)) = 0\"\n    proof\n      assume a2:\"i \\<noteq> j\"\n      define v1::\"complex vec\" where d1:\"v1 = unit_vec n i + 1 \\<cdot>\\<^sub>v unit_vec n j\"\n      define v2::\"complex vec\" where d2:\"v2 = unit_vec n i + \\<i> \\<cdot>\\<^sub>v unit_vec n j\"\n      have \"\\<parallel>v1\\<parallel>\\<^sup>2 = 1 + cnj 1 * 1\" using d1 a0 a2 sum_of_unit_vec_length by blast\n      then have \"\\<parallel>v1\\<parallel>\\<^sup>2 = 2\"\n        by (metis complex_cnj_one cpx_vec_length_inner_prod mult.left_neutral of_real_eq_iff \n            of_real_numeral one_add_one)\n      then have \"\\<parallel>U * |v1\\<rangle>\\<parallel>\\<^sup>2 = 2\" using c0 d1 assms(2) unit_vec_to_col by simp\n      moreover have \"col U i + 1 \\<cdot>\\<^sub>v col U j = U * |v1\\<rangle>\"\n        using c0 d1 a0 sum_of_unit_vec_to_col by blast\n      moreover have \"col U i + 1 \\<cdot>\\<^sub>v col U j = col U i + col U j\" by simp\n      ultimately have \"\\<langle>col U i + col U j|col U i + col U j\\<rangle> = 2\"\n        using cpx_vec_length_inner_prod by (metis of_real_numeral)\n      moreover have \"\\<langle>col U i + col U j|col U i + col U j\\<rangle> = \n               \\<langle>col U i|col U i\\<rangle> + \\<langle>col U j|col U i\\<rangle> + \\<langle>col U i|col U j\\<rangle> + \\<langle>col U j|col U j\\<rangle>\"\n        using inner_prod_is_sesquilinear[of \"col U i\" \"dim_row U\" \"col U j\" \"col U i\" \"col U j\" \"1\" \"1\" \"1\" \"1\"]\n        by simp\n      ultimately have f2:\"\\<langle>col U j|col U i\\<rangle> + \\<langle>col U i|col U j\\<rangle> = 0\"\n        using c0 a0 f1 inner_prod_def lessThan_atLeast0 by simp\n\n      have \"\\<parallel>v2\\<parallel>\\<^sup>2 = 1 + cnj \\<i> * \\<i>\" using a0 a2 d2 sum_of_unit_vec_length by simp\n      then have \"\\<parallel>v2\\<parallel>\\<^sup>2 = 2\"\n        by (metis Re_complex_of_real complex_norm_square mult.commute norm_ii numeral_Bit0 \n            numeral_One numeral_eq_one_iff of_real_numeral one_power2)\n      moreover have \"\\<parallel>U * |v2\\<rangle>\\<parallel>\\<^sup>2 = \\<parallel>v2\\<parallel>\\<^sup>2\" using c0 d2 assms(2) unit_vec_to_col by simp\n      moreover have \"\\<langle>col U i + \\<i> \\<cdot>\\<^sub>v col U j|col U i + \\<i> \\<cdot>\\<^sub>v col U j\\<rangle> = \\<parallel>U * |v2\\<rangle>\\<parallel>\\<^sup>2\"\n        using c0 a0 d2 sum_of_unit_vec_to_col cpx_vec_length_inner_prod by auto\n      moreover have \"\\<langle>col U i + \\<i> \\<cdot>\\<^sub>v col U j|col U i + \\<i> \\<cdot>\\<^sub>v col U j\\<rangle> = \n                     \\<langle>col U i|col U i\\<rangle> + (-\\<i>) * \\<langle>col U j|col U i\\<rangle> + \\<i> * \\<langle>col U i|col U j\\<rangle> + \\<langle>col U j|col U j\\<rangle>\"\n        using inner_prod_is_sesquilinear[of \"col U i\" \"dim_row U\" \"col U j\" \"col U i\" \"col U j\" \"1\" \"\\<i>\" \"1\" \"\\<i>\"]\n        by simp\n      ultimately have \"\\<langle>col U j|col U i\\<rangle> - \\<langle>col U i|col U j\\<rangle> = 0\"\n        using c0 a0 f1 inner_prod_def lessThan_atLeast0 by auto\n      then show \"(\\<Sum>k<n. cnj (U $$ (k, i)) * U $$ (k, j)) = 0\"\n        using c0 a0 f2 lessThan_atLeast0 inner_prod_def by auto\n    qed\n    ultimately show \"(U\\<^sup>\\<dagger> * U) $$ (i, j) = 1\\<^sub>m (dim_col U) $$ (i, j)\"\n      using c0 assms(1) a0 one_mat_def dagger_def by auto\nqed\n  then have \"(U\\<^sup>\\<dagger>) * U = 1\\<^sub>m n\" using c0 by simp\n  then have \"inverts_mat (U\\<^sup>\\<dagger>) U\" using c1 inverts_mat_def by auto\n  then have \"inverts_mat U (U\\<^sup>\\<dagger>)\" using c0 c1 inverts_mat_sym by simp\n  then have \"U * (U\\<^sup>\\<dagger>) = 1\\<^sub>m (dim_row U)\" using c0 inverts_mat_def by auto\n  then show ?thesis using f0 unitary_def by simp\nqed\n\nlemma inner_prod_with_unitary_mat [simp]:\n  assumes \"unitary U\" and \"dim_vec u = dim_col U\" and \"dim_vec v = dim_col U\"\n  shows \"\\<langle>U * |u\\<rangle>|U * |v\\<rangle>\\<rangle> = \\<langle>u|v\\<rangle>\"\nproof -\n  have f1:\"\\<langle>U * |u\\<rangle>|U * |v\\<rangle>\\<rangle> = (\\<langle>|u\\<rangle>| * (U\\<^sup>\\<dagger>) * U * |v\\<rangle>) $$ (0,0)\"\n    using assms(2-3) bra_mat_on_vec mult_ket_vec_is_ket_vec_of_mult\n    by (smt assoc_mult_mat carrier_mat_triv col_fst_def dim_vec dim_col_of_dagger index_mult_mat(2) \n        index_mult_mat(3) inner_prod_with_times_mat ket_vec_def mat_carrier)\n  moreover have f2:\"\\<langle>|u\\<rangle>| \\<in> carrier_mat 1 (dim_vec v)\"\n    using bra_def ket_vec_def assms(2-3) by simp\n  moreover have f3:\"U\\<^sup>\\<dagger> \\<in> carrier_mat (dim_col U) (dim_row U)\"\n    using dagger_def by simp\n  ultimately have \"\\<langle>U * |u\\<rangle>|U * |v\\<rangle>\\<rangle> = (\\<langle>|u\\<rangle>| * (U\\<^sup>\\<dagger> * U) * |v\\<rangle>) $$ (0,0)\"\n    using assms(3) assoc_mult_mat by (metis carrier_mat_triv)\n  also have \"\\<dots> = (\\<langle>|u\\<rangle>| * |v\\<rangle>) $$ (0,0)\"\n    using assms(1) unitary_def\n    by (simp add: assms(2) bra_def ket_vec_def)\n  finally show ?thesis\n    using assms(2-3) inner_prod_with_times_mat by presburger\nqed\n\ntext \\<open>As a consequence we prove that columns and rows of a unitary matrix are orthonormal vectors.\\<close>\n\nlemma unitary_unit_col [simp]:\n  assumes \"unitary U\" and \"dim_col U = n\" and \"i < n\"\n  shows \"\\<parallel>col U i\\<parallel> = 1\"\n  using assms unit_vec_to_col unitary_is_length_preserving by simp\n\nlemma unitary_unit_row [simp]:\n  assumes \"unitary U\" and \"dim_row U = n\" and \"i < n\"\n  shows \"\\<parallel>row U i\\<parallel> = 1\"\nproof -\n  have \"row U i = col (U\\<^sup>t) i\"\n    using  assms(2-3) by simp\n  thus ?thesis\n    using assms transpose_of_unitary_is_unitary unitary_unit_col\n    by (metis index_transpose_mat(3))\nqed\n\nlemma orthogonal_col_of_unitary [simp]:\n  assumes \"unitary U\" and \"dim_col U = n\" and \"i < n\" and \"j < n\" and \"i \\<noteq> j\"\n  shows \"\\<langle>col U i|col U j\\<rangle> = 0\"\nproof -\n  have \"\\<langle>col U i|col U j\\<rangle> = \\<langle>U * |unit_vec n i\\<rangle>| U * |unit_vec n j\\<rangle>\\<rangle>\"\n    using assms(2-4) unit_vec_to_col by simp\n  also have \"\\<dots> = \\<langle>unit_vec n i |unit_vec n j\\<rangle>\"\n    using assms(1-2) inner_prod_with_unitary_mat index_unit_vec(3) by simp\n  finally show ?thesis\n    using assms(3-5) by simp\nqed\n\nlemma orthogonal_row_of_unitary [simp]:\n  fixes U::\"complex mat\"\n  assumes \"unitary U\" and \"dim_row U = n\" and \"i < n\" and \"j < n\" and \"i \\<noteq> j\"\n  shows \"\\<langle>row U i|row U j\\<rangle> = 0\"\n  using assms orthogonal_col_of_unitary transpose_of_unitary_is_unitary col_transpose\n  by (metis index_transpose_mat(3))\n\n\ntext\\<open>\nAs a consequence, we prove that a quantum gate acting on a state of a system of n qubits give \nanother state of that same system.\n\\<close>\n\nlemma gate_on_state_is_state [intro, simp]:\n  assumes a1:\"gate n A\" and a2:\"state n v\"\n  shows \"state n (A * v)\"\nproof\n  show \"dim_row (A * v) = 2^n\"\n    using gate_def state_def a1 by simp\nnext\n  show \"dim_col (A * v) = 1\"\n    using state_def a2 by simp\nnext\n  have \"square_mat A\"\n    using a1 gate_def by simp\n  then have \"dim_col A = 2^n\"\n    using a1 gate.dim_row by simp\n  then have \"dim_col A = dim_row v\"\n    using a2 state.dim_row by simp\n  then have \"\\<parallel>col (A * v) 0\\<parallel> = \\<parallel>col v 0\\<parallel>\"\n    using unitary_is_length_preserving_bis assms gate_def state_def by simp\n  thus\"\\<parallel>col (A * v) 0\\<parallel> = 1\"\n    using a2 state.is_normal by simp\nqed\n\n\nsubsection \\<open>A Few Well-known Quantum Gates\\<close>\n\ntext \\<open>\nAny unitary operation on n qubits can be implemented exactly by composing single qubits and\nCNOT-gates (controlled-NOT gates). However, no straightforward method is known to implement these \ngates in a fashion which is resistant to errors. But, the Hadamard gate, the phase gate, the \nCNOT-gate and the @{text \"\\<pi>/8\"} gate are also universal for quantum computations, i.e. any quantum circuit on \nn qubits can be approximated to an arbitrary accuracy by using only these gates, and these gates can \nbe implemented in a fault-tolerant way. \n\\<close>\n\ntext \\<open>We introduce a coercion from real matrices to complex matrices.\\<close>\n\ndefinition real_to_cpx_mat:: \"real mat \\<Rightarrow> complex mat\" where\n\"real_to_cpx_mat A \\<equiv> mat (dim_row A) (dim_col A) (\\<lambda>(i,j). A $$ (i,j))\"\n\ntext \\<open>Our first quantum gate: the identity matrix! Arguably, not a very interesting one though!\\<close>\n\ndefinition Id :: \"nat \\<Rightarrow> complex mat\" where\n\"Id n \\<equiv> 1\\<^sub>m (2^n)\"\n\nlemma id_is_gate [simp]:\n  \"gate n (Id n)\"\nproof\n  show \"dim_row (Id n) = 2^n\"\n    using Id_def by simp\nnext\n  show \"square_mat (Id n)\"\n    using Id_def by simp\nnext\n  show \"unitary (Id n)\" \n    by (simp add: Id_def)\nqed\n\ntext \\<open>More interesting: the Pauli matrices.\\<close>\n\ndefinition X ::\"complex mat\" where\n\"X \\<equiv> mat 2 2 (\\<lambda>(i,j). if i=j then 0 else 1)\"\n\ntext\\<open> \nBe aware that @{text \"gate n A\"} means that the matrix A has dimension @{text \"2^n * 2^n\"}. \nFor instance, with this convention a 2 X 2 matrix A which is unitary satisfies @{text \"gate 1 A\"}\n but not @{text \"gate 2 A\"} as one might have been expected.\n\\<close>\n\nlemma dagger_of_X [simp]:\n  \"X\\<^sup>\\<dagger> = X\"\n  using dagger_def by (simp add: X_def cong_mat)\n\nlemma X_inv [simp]:\n  \"X * X = 1\\<^sub>m 2\"\n  apply(simp add: X_def times_mat_def one_mat_def)\n  apply(rule cong_mat)\n  by(auto simp: scalar_prod_def)\n\nlemma X_is_gate [simp]:\n  \"gate 1 X\"\n  by (simp add: gate_def unitary_def)\n    (simp add: X_def)\n\ndefinition Y ::\"complex mat\" where\n\"Y \\<equiv> mat 2 2 (\\<lambda>(i,j). if i=j then 0 else (if i=0 then -\\<i> else \\<i>))\"\n\nlemma dagger_of_Y [simp]:\n  \"Y\\<^sup>\\<dagger> = Y\"\n  using dagger_def by (simp add: Y_def cong_mat)\n\nlemma Y_inv [simp]:\n  \"Y * Y = 1\\<^sub>m 2\"\n  apply(simp add: Y_def times_mat_def one_mat_def)\n  apply(rule cong_mat)\n  by(auto simp: scalar_prod_def)\n\nlemma Y_is_gate [simp]:\n  \"gate 1 Y\"\n  by (simp add: gate_def unitary_def)\n    (simp add: Y_def)\n\ndefinition Z ::\"complex mat\" where\n\"Z \\<equiv> mat 2 2 (\\<lambda>(i,j). if i\\<noteq>j then 0 else (if i=0 then 1 else -1))\"\n\nlemma dagger_of_Z [simp]:\n  \"Z\\<^sup>\\<dagger> = Z\"\n  using dagger_def by (simp add: Z_def cong_mat)\n\nlemma Z_inv [simp]:\n  \"Z * Z = 1\\<^sub>m 2\"\n  apply(simp add: Z_def times_mat_def one_mat_def)\n  apply(rule cong_mat)\n  by(auto simp: scalar_prod_def)\n\nlemma Z_is_gate [simp]:\n  \"gate 1 Z\"\n  by (simp add: gate_def unitary_def)\n    (simp add: Z_def)\n\ntext \\<open>The Hadamard gate\\<close>\n\ndefinition H ::\"complex mat\" where\n\"H \\<equiv> 1/sqrt(2) \\<cdot>\\<^sub>m (mat 2 2 (\\<lambda>(i,j). if i\\<noteq>j then 1 else (if i=0 then 1 else -1)))\"\n\nlemma H_without_scalar_prod:\n  \"H = mat 2 2 (\\<lambda>(i,j). if i\\<noteq>j then 1/sqrt(2) else (if i=0 then 1/sqrt(2) else -(1/sqrt(2))))\"\n  using cong_mat by (auto simp: H_def)\n\nlemma dagger_of_H [simp]:\n  \"H\\<^sup>\\<dagger> = H\"\n  using dagger_def by (auto simp: H_def cong_mat)\n\nlemma H_inv [simp]:\n  \"H * H = 1\\<^sub>m 2\"\n  apply(simp add: H_def times_mat_def one_mat_def)\n  apply(rule cong_mat)\n  by(auto simp: scalar_prod_def complex_eqI)\n\nlemma H_is_gate [simp]:\n  \"gate 1 H\"\n  by (simp add: gate_def unitary_def)\n    (simp add: H_def)\n\nlemma H_values:\n  fixes i j:: nat\n  assumes \"i < dim_row H\" and \"j < dim_col H\" and \"i \\<noteq> 1 \\<or> j \\<noteq> 1\" \n  shows \"H $$ (i,j) = 1/sqrt 2\"\nproof-\n  have \"i < 2\"\n    using assms(1) by (simp add: H_without_scalar_prod less_2_cases)\n  moreover have \"j < 2\"\n    using assms(2) by (simp add: H_without_scalar_prod less_2_cases)\n  ultimately show ?thesis \n    using assms(3) H_without_scalar_prod by(smt One_nat_def index_mat(1) less_2_cases old.prod.case)\nqed\n\nlemma H_values_right_bottom:\n  fixes i j:: nat\n  assumes \"i = 1 \\<and> j = 1\"\n  shows \"H $$ (i,j) = - 1/sqrt 2\"     \n  using assms by (simp add: H_without_scalar_prod)\n\ntext \\<open>The controlled-NOT gate\\<close>\n\ndefinition CNOT ::\"complex mat\" where\n\"CNOT \\<equiv> mat 4 4 \n  (\\<lambda>(i,j). if i=0 \\<and> j=0 then 1 else \n    (if i=1 \\<and> j=1 then 1 else \n      (if i=2 \\<and> j=3 then 1 else \n        (if i=3 \\<and> j=2 then 1 else 0))))\"\n\nlemma dagger_of_CNOT [simp]:\n  \"CNOT\\<^sup>\\<dagger> = CNOT\"\n  using dagger_def by (simp add: CNOT_def cong_mat)\n\nlemma CNOT_inv [simp]:\n  \"CNOT * CNOT = 1\\<^sub>m 4\"\n  apply(simp add: CNOT_def times_mat_def one_mat_def)\n  apply(rule cong_mat)\n  by(auto simp: scalar_prod_def)\n\nlemma CNOT_is_gate [simp]:\n  \"gate 2 CNOT\"\n  by (simp add: gate_def unitary_def)\n    (simp add: CNOT_def)\n\ntext \\<open>The phase gate, also known as the S-gate\\<close>\n\ndefinition S ::\"complex mat\" where\n\"S \\<equiv> mat 2 2 (\\<lambda>(i,j). if i=0 \\<and> j=0 then 1 else (if i=1 \\<and> j=1 then \\<i> else 0))\"\n\ntext \\<open>The @{text \"\\<pi>/8\"} gate, also known as the T-gate\\<close>\n\ndefinition T ::\"complex mat\" where\n\"T \\<equiv> mat 2 2 (\\<lambda>(i,j). if i=0 \\<and> j=0 then 1 else (if i=1 \\<and> j=1 then exp(\\<i>*(pi/4)) else 0))\"\n\ntext \\<open>A few relations between the Hadamard gate and the Pauli matrices\\<close>\n\nlemma HXH_is_Z [simp]:\n  \"H * X * H = Z\" \n  apply(simp add: X_def Z_def H_def times_mat_def)\n  apply(rule cong_mat)\n  by(auto simp add: scalar_prod_def complex_eqI)\n\nlemma HYH_is_minusY [simp]:\n  \"H * Y * H = - Y\" \n  apply(simp add: Y_def H_def times_mat_def)\n  apply(rule eq_matI)\n  by(auto simp add: scalar_prod_def complex_eqI)\n\nlemma HZH_is_X [simp]:\n  shows \"H * Z * H = X\"  \n  apply(simp add: X_def Z_def H_def times_mat_def)\n  apply(rule cong_mat)\n  by(auto simp add: scalar_prod_def complex_eqI)\n\n\nsubsection \\<open>The Bell States\\<close>\n\ntext \\<open>\nWe introduce below the so-called Bell states, also known as EPR pairs (EPR stands for Einstein,\nPodolsky and Rosen).\n\\<close>\n\ndefinition bell00 ::\"complex mat\" (\"|\\<beta>\\<^sub>0\\<^sub>0\\<rangle>\") where\n\"bell00 \\<equiv> 1/sqrt(2) \\<cdot>\\<^sub>m |vec 4 (\\<lambda>i. if i=0 \\<or> i=3 then 1 else 0)\\<rangle>\"\n\ndefinition bell01 ::\"complex mat\" (\"|\\<beta>\\<^sub>0\\<^sub>1\\<rangle>\") where\n\"bell01 \\<equiv> 1/sqrt(2) \\<cdot>\\<^sub>m |vec 4 (\\<lambda>i. if i=1 \\<or> i=2 then 1 else 0)\\<rangle>\"\n\ndefinition bell10 ::\"complex mat\" (\"|\\<beta>\\<^sub>1\\<^sub>0\\<rangle>\") where\n\"bell10 \\<equiv> 1/sqrt(2) \\<cdot>\\<^sub>m |vec 4 (\\<lambda>i. if i=0 then 1 else if i=3 then -1 else 0)\\<rangle>\"\n\ndefinition bell11 ::\"complex mat\" (\"|\\<beta>\\<^sub>1\\<^sub>1\\<rangle>\") where\n\"bell11 \\<equiv> 1/sqrt(2) \\<cdot>\\<^sub>m |vec 4 (\\<lambda>i. if i=1 then 1 else if i=2 then -1 else 0)\\<rangle>\"\n\nlemma\n  shows bell00_is_state [simp]:\"state 2 |\\<beta>\\<^sub>0\\<^sub>0\\<rangle>\" and bell01_is_state [simp]:\"state 2 |\\<beta>\\<^sub>0\\<^sub>1\\<rangle>\" and \n    bell10_is_state [simp]:\"state 2 |\\<beta>\\<^sub>1\\<^sub>0\\<rangle>\" and bell11_is_state [simp]:\"state 2 |\\<beta>\\<^sub>1\\<^sub>1\\<rangle>\"\n  by (auto simp: state_def bell00_def bell01_def bell10_def bell11_def ket_vec_def)\n    (auto simp: cpx_vec_length_def Set_Interval.lessThan_atLeast0 cmod_def power2_eq_square) \n\nlemma bell00_index [simp]:\n  shows \"|\\<beta>\\<^sub>0\\<^sub>0\\<rangle> $$ (0,0) = 1/sqrt 2\" and \"|\\<beta>\\<^sub>0\\<^sub>0\\<rangle> $$ (1,0) = 0\" and \"|\\<beta>\\<^sub>0\\<^sub>0\\<rangle> $$ (2,0) = 0\" and \n    \"|\\<beta>\\<^sub>0\\<^sub>0\\<rangle> $$ (3,0) = 1/sqrt 2\"\n  by (auto simp: bell00_def ket_vec_def)\n\nlemma bell01_index [simp]:\n  shows \"|\\<beta>\\<^sub>0\\<^sub>1\\<rangle> $$ (0,0) = 0\" and \"|\\<beta>\\<^sub>0\\<^sub>1\\<rangle> $$ (1,0) = 1/sqrt 2\" and \"|\\<beta>\\<^sub>0\\<^sub>1\\<rangle> $$ (2,0) = 1/sqrt 2\" and \n    \"|\\<beta>\\<^sub>0\\<^sub>1\\<rangle> $$ (3,0) = 0\"\n  by (auto simp: bell01_def ket_vec_def)\n\nlemma bell10_index [simp]:\n  shows \"|\\<beta>\\<^sub>1\\<^sub>0\\<rangle> $$ (0,0) = 1/sqrt 2\" and \"|\\<beta>\\<^sub>1\\<^sub>0\\<rangle> $$ (1,0) = 0\" and \"|\\<beta>\\<^sub>1\\<^sub>0\\<rangle> $$ (2,0) = 0\" and \n    \"|\\<beta>\\<^sub>1\\<^sub>0\\<rangle> $$ (3,0) = - 1/sqrt 2\"\n  by (auto simp: bell10_def ket_vec_def)\n\nlemma bell_11_index [simp]:\n  shows \"|\\<beta>\\<^sub>1\\<^sub>1\\<rangle> $$ (0,0) = 0\" and \"|\\<beta>\\<^sub>1\\<^sub>1\\<rangle> $$ (1,0) = 1/sqrt 2\" and \"|\\<beta>\\<^sub>1\\<^sub>1\\<rangle> $$ (2,0) = - 1/sqrt 2\" and \n    \"|\\<beta>\\<^sub>1\\<^sub>1\\<rangle> $$ (3,0) = 0\"\n  by (auto simp: bell11_def ket_vec_def)\n\n\nsubsection \\<open>The Bitwise Inner Product\\<close>\n\ndefinition bitwise_inner_prod:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where \n\"bitwise_inner_prod n i j = (\\<Sum>k\\<in>{0..<n}. (bin_rep n i) ! k * (bin_rep n j) ! k)\"\n\nabbreviation bip:: \"nat \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" (\"_ \\<cdot>\\<^bsub>_\\<^esub>  _\") where\n\"bip i n j \\<equiv> bitwise_inner_prod n i j\"\n\nlemma bitwise_inner_prod_fst_el_0: \n  assumes \"i < 2^n \\<or> j < 2^n\" \n  shows \"(i \\<cdot>\\<^bsub>Suc n\\<^esub> j) = (i mod 2^n) \\<cdot>\\<^bsub>n\\<^esub> (j mod 2^n)\" \nproof-\n  have \"bip i (Suc n) j = (\\<Sum>k\\<in>{0..<(Suc n)}. (bin_rep (Suc n) i) ! k * (bin_rep (Suc n) j) ! k)\" \n    using bitwise_inner_prod_def by simp\n  also have \"... = bin_rep (Suc n) i ! 0 * bin_rep (Suc n) j ! 0 + \n             (\\<Sum>k\\<in>{1..<(Suc n)}. bin_rep (Suc n) i ! k * bin_rep (Suc n) j ! k)\"\n    by (simp add: sum.atLeast_Suc_lessThan)\n  also have \"... = (\\<Sum>k\\<in>{1..<(Suc n)}. bin_rep (Suc n) i ! k * bin_rep (Suc n) j ! k)\"\n    using bin_rep_index_0[of i n] bin_rep_index_0[of j n] assms by auto\n  also have \"... = (\\<Sum>k\\<in>{0..<n}. bin_rep (Suc n) i !(k+1) * bin_rep (Suc n) j ! (k+1))\" \n     using sum.shift_bounds_Suc_ivl[of \"\\<lambda>k. bin_rep (Suc n) i ! k * bin_rep (Suc n) j ! k\" \"0\" \"n\"] \n     by (metis (no_types, lifting) One_nat_def add.commute plus_1_eq_Suc sum.cong)\n  finally have \"bip i (Suc n) j = (\\<Sum>k\\<in>{0..<n}. bin_rep (Suc n) i ! (k+1) * bin_rep (Suc n) j ! (k+1))\" \n    by simp\n  moreover have \"k\\<in>{0..n} \\<longrightarrow> bin_rep (Suc n) i ! (k+1) = bin_rep n (i mod 2^n) ! k\" for k\n    using bin_rep_def by (simp add: bin_rep_aux_neq_nil)\n  moreover have \"k\\<in>{0..n} \\<longrightarrow> bin_rep (Suc n) j !(k+1) = bin_rep n (j mod 2^n) ! k\" for k \n    using bin_rep_def by (simp add: bin_rep_aux_neq_nil)\n  ultimately show ?thesis\n    using assms bin_rep_index_0 bitwise_inner_prod_def by simp\nqed\n\nlemma bitwise_inner_prod_fst_el_is_1:\n  fixes n i j:: nat\n  assumes \"i \\<ge> 2^n \\<and> j \\<ge> 2^n\" and \"i < 2^(n+1) \\<and> j < 2^(n+1)\"\n  shows \"(i \\<cdot>\\<^bsub>(n+1)\\<^esub> j) = 1 + ((i mod 2^n) \\<cdot>\\<^bsub>n\\<^esub> (j mod 2^n))\" \nproof-\n  have \"bip i (Suc n) j = (\\<Sum>k\\<in>{0..<(Suc n)}. bin_rep (Suc n) i ! k * bin_rep (Suc n) j ! k)\" \n    using bitwise_inner_prod_def by simp\n  also have \"... = bin_rep (Suc n) i ! 0 * bin_rep (Suc n) j ! 0 + \n            (\\<Sum>k\\<in>{1..<(Suc n)}. bin_rep (Suc n) i ! k * bin_rep (Suc n) j ! k)\"\n    by (simp add: sum.atLeast_Suc_lessThan)\n  also have \"... = 1 + (\\<Sum>k\\<in>{1..<(Suc n)}. bin_rep (Suc n) i ! k * bin_rep (Suc n) j ! k)\"\n    using bin_rep_index_0_geq[of n i] bin_rep_index_0_geq[of n j] assms by simp\n  also have \"... = 1 + (\\<Sum>k \\<in> {0..<n}. bin_rep (Suc n) i ! (k+1) * bin_rep (Suc n) j ! (k+1))\" \n    using sum.shift_bounds_Suc_ivl[of \"\\<lambda>k. (bin_rep (Suc n) i)!k * (bin_rep (Suc n) j)!k\" \"0\" \"n\"] \n    by (metis (no_types, lifting) One_nat_def Suc_eq_plus1 sum.cong)\n  finally have f0:\"bip i (Suc n) j = 1 + (\\<Sum>k\\<in>{0..<n}. bin_rep (Suc n) i ! (k+1) * bin_rep (Suc n) j ! (k+1))\"\n    by simp\n  moreover have \"k\\<in>{0..n} \\<longrightarrow> bin_rep (Suc n) i ! (k+1) = bin_rep n (i mod 2^n) ! k\n\\<and> bin_rep (Suc n) j ! (k+1) = bin_rep n (j mod 2^n) ! k\" for k\n    using bin_rep_def by(metis Suc_eq_plus1 bin_rep_aux.simps(2) bin_rep_aux_neq_nil butlast.simps(2) nth_Cons_Suc)\n  ultimately show ?thesis\n    using bitwise_inner_prod_def by simp\nqed\n\nlemma bitwise_inner_prod_with_zero:\n  assumes \"m < 2^n\"\n  shows \"(0 \\<cdot>\\<^bsub>n\\<^esub>  m) = 0\" \nproof-\n  have \"(0 \\<cdot>\\<^bsub>n\\<^esub>  m) = (\\<Sum>j\\<in>{0..<n}. bin_rep n 0 ! j * bin_rep n m ! j)\" \n    using bitwise_inner_prod_def by simp\n  moreover have \"(\\<Sum>j\\<in>{0..<n}. bin_rep n 0 ! j * bin_rep n m ! j) \n               = (\\<Sum>j\\<in>{0..<n}. 0 * (bin_rep n m) ! j)\"\n    by (simp add: bin_rep_index)\n  ultimately show \"?thesis\" \n    by simp\nqed\n\n(*\nBiblio:\n\n@book{MikeandIke,\n  author = {Nielsen, Michael A. and Chuang, Isaac L.},\n  publisher = {Cambridge University Press},\n  title = {Quantum Computation and Quantum Information},\n  year = 2010\n}\n*)\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Isabelle_Marries_Dirac/Quantum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7552269005969076}}
{"text": "theory ATC\nimports \"../FSM/FSM\"\nbegin\n\nsection {* Adaptive test cases *}\n\ntext \\<open>\nAdaptive test cases (ATCs) are tree-like structures that label nodes with inputs and edges with\noutputs such that applying an ATC to some FSM is performed by applying the label of its root node\nand then applying the ATC connected to the root node by an edge labeled with the observed output of\nthe FSM. The result of such an application is here called an ATC-reaction.\n\nATCs are here modelled to have edges for every possible output from each non-leaf node. This is not\na restriction on the definition of ATCs by Hierons @{cite \"hierons\"} as a missing edge can be \nexpressed by an edge to a leaf.\n\\<close>\n\n\ndatatype ('in, 'out) ATC = Leaf | Node 'in \"'out \\<Rightarrow> ('in, 'out) ATC\"\n\ninductive atc_reaction :: \"('in, 'out, 'state) FSM \\<Rightarrow> 'state \\<Rightarrow> ('in, 'out) ATC \n                            \\<Rightarrow> ('in \\<times> 'out) list \\<Rightarrow> bool\" \n  where\n  leaf[intro!]: \"atc_reaction M q1 Leaf []\" |\n  node[intro!]: \"q2 \\<in> succ M (x,y) q1 \n                  \\<Longrightarrow> atc_reaction M q2 (f y) io \n                  \\<Longrightarrow> atc_reaction M q1 (Node x f) ((x,y)#io)\"\n\ninductive_cases leaf_elim[elim!] : \"atc_reaction M q1 Leaf []\"\ninductive_cases node_elim[elim!] : \"atc_reaction M q1 (Node x f) ((x,y)#io)\"\n\n\n\n\nsubsection {* Properties of ATC-reactions *}\n\nlemma atc_reaction_empty[simp] :\n  assumes \"atc_reaction M q t []\"\n  shows \"t = Leaf\"\nusing assms atc_reaction.simps by force \n\nlemma atc_reaction_nonempty_no_leaf :\n  assumes \"atc_reaction M q t (Cons a io)\"\n  shows \"t \\<noteq> Leaf\"\nusing assms\nproof -\n  have \"\\<And>f c a ps. \\<not> atc_reaction f (c::'c) (a::('a, 'b) ATC) ps \\<or> a \\<noteq> Leaf \\<or> a \\<noteq> Leaf \\<or> ps = []\"\n    using atc_reaction.simps by fastforce\n  then show ?thesis\n    using assms by blast\nqed  \n\nlemma atc_reaction_nonempty[elim] :\n  assumes \"atc_reaction M q1 t (Cons (x,y) io)\"\n  obtains q2 f \n  where \"t = Node x f\" \"q2 \\<in> succ M (x,y) q1\"  \"atc_reaction M q2 (f y) io\"\nproof -\n  obtain x2 f where \"t = Node x2 f\"  \n    using assms by (metis ATC.exhaust atc_reaction_nonempty_no_leaf) \n  moreover have \"x = x2\" \n    using assms calculation atc_reaction.cases by fastforce \n  ultimately show ?thesis \n    using assms using that by blast \nqed\n\nlemma atc_reaction_path_ex : \n  assumes \"atc_reaction M q1 t io\"\n  shows \"\\<exists> tr . path M (io || tr) q1 \\<and> length io = length tr\"\nusing assms proof (induction io arbitrary: q1 t rule: list.induct)\n  case Nil\n  then show ?case by (simp add: FSM.nil) \nnext\n  case (Cons io_hd io_tl)\n  then obtain x y where io_hd_def : \"io_hd = (x,y)\" \n    by (meson surj_pair)\n  then obtain f where f_def : \"t = (Node x f)\" \n    using Cons atc_reaction_nonempty by metis\n  then obtain q2 where q2_def : \"q2 \\<in> succ M (x,y) q1\" \"atc_reaction M q2 (f y) io_tl\" \n    using Cons io_hd_def atc_reaction_nonempty by auto\n  then obtain tr_tl where tr_tl_def :  \"path M (io_tl || tr_tl) q2\" \"length io_tl = length tr_tl\" \n    using Cons.IH[of q2 \"f y\"] by blast\n  then have \"path M (io_hd # io_tl || q2 # tr_tl) q1\" \n    using Cons q2_def by (simp add: FSM.path.intros(2) io_hd_def)\n  then show ?case using tr_tl_def by fastforce   \nqed\n\nlemma atc_reaction_path[elim] : \n  assumes \"atc_reaction M q1 t io\"\nobtains tr\n  where \"path M (io || tr) q1\" \"length io = length tr\"\nby (meson assms atc_reaction_path_ex) \n\n\n\nsubsection {* Applicability *}\n\ntext \\<open> \nAn ATC can be applied to an FSM if each node-label is contained in the input alphabet of the FSM.\n\\<close>\n\ninductive subtest :: \"('in, 'out) ATC \\<Rightarrow> ('in, 'out) ATC \\<Rightarrow> bool\" where\n  \"t \\<in> range f \\<Longrightarrow> subtest t (Node x f)\"\n\nlemma accp_subtest : \"Wellfounded.accp subtest t\"\nproof (induction t)\n  case Leaf\n  then show ?case by (meson ATC.distinct(1) accp.simps subtest.cases)\nnext\n  case (Node x f)\n  have IH: \"Wellfounded.accp subtest t\" if \"t \\<in> range f\" for \"t\"\n    using Node[of t] and that by (auto simp: eq_commute)\n  show ?case by (rule accpI) (auto intro: IH elim!: subtest.cases)\nqed\n\ndefinition subtest_rel where \"subtest_rel = {(t, Node x f) |f x t. t \\<in> range f}\"\n\nlemma subtest_rel_altdef: \"subtest_rel = {(s, t) |s t. subtest s t}\"\n  by (auto simp: subtest_rel_def subtest.simps)\n\nlemma subtest_relI [intro]: \"t \\<in> range f \\<Longrightarrow> (t, Node x f) \\<in> subtest_rel\"\n  by (simp add: subtest_rel_def)\n\nlemma subtest_relI' [intro]: \"t = f y \\<Longrightarrow> (t, Node x f) \\<in> subtest_rel\"\n  by (auto simp: subtest_rel_def ran_def)\n\nlemma wf_subtest_rel [simp, intro]: \"wf subtest_rel\" \n  using accp_subtest unfolding subtest_rel_altdef accp_eq_acc wf_acc_iff\n  by auto\n\n\n\nfunction inputs_atc :: \"('a,'b) ATC \\<Rightarrow> 'a set\" where\n  \"inputs_atc Leaf = {}\" |\n  \"inputs_atc (Node x f) = insert x (\\<Union> (image inputs_atc (range f)))\"\nby pat_completeness auto\ntermination by (relation subtest_rel) auto\n\nfun applicable :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in, 'out) ATC \\<Rightarrow> bool\" where\n  \"applicable M t = (inputs_atc t \\<subseteq> inputs M)\"\n\nfun applicable_set :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in, 'out) ATC set \\<Rightarrow> bool\" where\n  \"applicable_set M \\<Omega> = (\\<forall> t \\<in> \\<Omega> . applicable M t)\"\n\nlemma applicable_subtest :\n  assumes \"applicable M (Node x f)\"\nshows \"applicable M (f y)\"\nusing assms inputs_atc.simps\n  by (simp add: Sup_le_iff)\n\n\n\nsubsection {* Application function IO *}\n\ntext \\<open>\nFunction @{verbatim IO} collects all ATC-reactions of some FSM to some ATC.\n\\<close>\n\nfun IO :: \"('in, 'out, 'state) FSM \\<Rightarrow> 'state \\<Rightarrow> ('in, 'out) ATC \\<Rightarrow> ('in \\<times> 'out) list set\" where\n  \"IO M q t = { tr . atc_reaction M q t tr }\"\n\nfun IO_set :: \"('in, 'out, 'state) FSM \\<Rightarrow> 'state \\<Rightarrow> ('in, 'out) ATC set \\<Rightarrow> ('in \\<times> 'out) list set\" \n  where\n  \"IO_set M q \\<Omega> = \\<Union> {IO M q t | t . t \\<in> \\<Omega>}\"\n\nlemma IO_language : \"IO M q t \\<subseteq> language_state M q\"\n  by (metis atc_reaction_path IO.elims language_state mem_Collect_eq subsetI) \n\nlemma IO_leaf[simp] : \"IO M q Leaf = {[]}\"\nproof   \n  show \"IO M q Leaf \\<subseteq> {[]}\" \n  proof (rule ccontr)\n    assume assm : \"\\<not> IO M q Leaf \\<subseteq> {[]}\"\n    then obtain io_hd io_tl where elem_ex : \"Cons io_hd io_tl \\<in> IO M q Leaf\" \n      by (metis (no_types, hide_lams) insertI1 neq_Nil_conv subset_eq) \n    then show \"False\" \n      using atc_reaction_nonempty_no_leaf assm by (metis IO.simps mem_Collect_eq)\n  qed  \nnext\n  show \"{[]} \\<subseteq> IO M q Leaf\" by auto \nqed\n\n\nlemma IO_applicable_nonempty :\n  assumes \"applicable M t\"\n  and     \"completely_specified M\"\n  and     \"q1 \\<in> nodes M\"\n  shows \"IO M q1 t \\<noteq> {}\"\nusing assms proof (induction t arbitrary: q1)\n  case Leaf\n  then show ?case by auto\nnext\n  case (Node x f)\n  then have \"x \\<in> inputs M\" by auto\n  then obtain y q2  where x_appl : \"q2 \\<in> succ M (x, y) q1\" \n    using Node unfolding completely_specified.simps by blast\n  then have \"applicable M (f y)\" \n    using applicable_subtest Node by metis\n  moreover have \"q2 \\<in> nodes M\" \n    using Node(4) \\<open>q2 \\<in> succ M (x, y) q1\\<close> FSM.nodes.intros(2)[of q1 M \"((x,y),q2)\"] by auto\n  ultimately have \"IO M q2 (f y) \\<noteq> {}\" \n    using Node by auto\n  then show ?case unfolding IO.simps \n    using x_appl by blast  \nqed\n\n\nlemma IO_in_language :\n  \"IO M q t \\<subseteq> LS M q\"\n  unfolding IO.simps by blast\n\nlemma IO_set_in_language :\n  \"IO_set M q \\<Omega> \\<subseteq> LS M q\"\n  using IO_in_language[of M q] unfolding IO_set.simps by blast\n\n\nsubsection {* R-distinguishability *}\n\ntext \\<open>\nA non-empty ATC r-distinguishes two states of some FSM if there exists no shared ATC-reaction.\n\\<close>\n\nfun r_dist :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in, 'out) ATC \\<Rightarrow> 'state \\<Rightarrow> 'state \\<Rightarrow> bool\" where\n\"r_dist M t s1 s2 = (t \\<noteq> Leaf \\<and> IO M s1 t \\<inter> IO M s2 t = {})\"\n\nfun r_dist_set :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in, 'out) ATC set \\<Rightarrow> 'state \\<Rightarrow> 'state \\<Rightarrow> bool\" where\n\"r_dist_set M T s1 s2 = (\\<exists> t \\<in> T . r_dist M t s1 s2)\"\n\n\nlemma r_dist_dist :\n  assumes \"applicable M t\"\n  and     \"completely_specified M\"\n  and     \"r_dist M t q1 q2\"\n  and     \"q1 \\<in> nodes M\"\nshows   \"q1 \\<noteq> q2\"\nproof (rule ccontr)\n  assume \"\\<not>(q1 \\<noteq> q2)\" \n  then have \"q1 = q2\" \n    by simp\n  then have \"IO M q1 t = {}\" \n    using assms by simp\n  moreover have \"IO M q1 t \\<noteq> {}\" \n    using assms IO_applicable_nonempty by auto\n  ultimately show \"False\" \n    by simp\nqed\n\nlemma r_dist_set_dist :\n  assumes \"applicable_set M \\<Omega>\"\n  and     \"completely_specified M\"\n  and     \"r_dist_set M \\<Omega> q1 q2\"\n  and     \"q1 \\<in> nodes M\"\nshows   \"q1 \\<noteq> q2\"\nusing assms r_dist_dist by (metis applicable_set.elims(2) r_dist_set.elims(2))  \n\nlemma r_dist_set_dist_disjoint :\n  assumes \"applicable_set M \\<Omega>\"\n  and     \"completely_specified M\"\n  and     \"\\<forall> t1 \\<in> T1 . \\<forall> t2 \\<in> T2 . r_dist_set M \\<Omega> t1 t2\"\n  and     \"T1 \\<subseteq> nodes M\"\nshows \"T1 \\<inter> T2 = {}\"\n  by (metis assms disjoint_iff_not_equal r_dist_set_dist subsetCE)\n  \n\n\n\n\nsubsection {* Response sets *}\n\ntext \\<open>\nThe following functions calculate the sets of all ATC-reactions observed by applying some set of \nATCs on every state reached in some FSM using a given set of IO-sequences.\n\\<close>\n\n\nfun B :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in * 'out) list \\<Rightarrow> ('in, 'out) ATC set \n          \\<Rightarrow> ('in * 'out) list set\" where\n  \"B M io \\<Omega> = \\<Union> (image (\\<lambda> s . IO_set M s \\<Omega>) (io_targets M (initial M) io))\"\n\n\nfun D :: \"('in, 'out, 'state) FSM \\<Rightarrow> 'in list set \\<Rightarrow> ('in, 'out) ATC set\n          \\<Rightarrow> ('in * 'out) list set set\" where\n  \"D M ISeqs \\<Omega> = image (\\<lambda> io . B M io \\<Omega>) (LS\\<^sub>i\\<^sub>n M (initial M) ISeqs)\"\n\nfun append_io_B :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in * 'out) list \\<Rightarrow> ('in, 'out) ATC set \n                    \\<Rightarrow> ('in * 'out) list set\" where\n  \"append_io_B M io \\<Omega> = { io@res | res . res \\<in> B M io \\<Omega> }\"\n\n\n\n\nlemma B_dist' :\n  assumes df: \"B M io1 \\<Omega> \\<noteq> B M io2 \\<Omega>\"\n  shows   \"(io_targets M (initial M) io1) \\<noteq> (io_targets M (initial M) io2)\"\n  using assms by force \n\nlemma B_dist :\n  assumes \"io_targets M (initial M) io1 = {q1}\"\n  and     \"io_targets M (initial M) io2 = {q2}\"\n  and     \"B M io1 \\<Omega> \\<noteq> B M io2 \\<Omega>\"\nshows   \"q1 \\<noteq> q2\"\n  using assms by force\n\n\nlemma D_bound :\n  assumes wf: \"well_formed M\"\n  and     ob: \"observable M\"\n  and     fi: \"finite ISeqs\"\n  shows \"finite (D M ISeqs \\<Omega>)\" \"card (D M ISeqs \\<Omega>) \\<le> card (nodes M)\" \nproof -\n  have \"D M ISeqs \\<Omega> \\<subseteq> image (\\<lambda> s . IO_set M s \\<Omega>) (nodes M)\"\n  proof \n    fix RS assume RS_def : \"RS \\<in> D M ISeqs \\<Omega>\"\n    then obtain xs ys where RS_tr : \"RS = B M (xs || ys) \\<Omega>\" \n                                    \"(xs \\<in> ISeqs \\<and> length xs = length ys \n                                        \\<and> (xs || ys) \\<in> language_state M (initial M))\" \n      by auto\n    then obtain qx where qx_def : \"io_targets M (initial M) (xs || ys) = { qx }\" \n      by (meson io_targets_observable_singleton_ex ob)  \n    then have \"RS = IO_set M qx \\<Omega>\" \n      using RS_tr by auto\n    moreover have \"qx \\<in> nodes M\" \n      by (metis FSM.nodes.initial io_targets_nodes qx_def singletonI) \n    ultimately show \"RS \\<in> image (\\<lambda> s . IO_set M s \\<Omega>) (nodes M)\" \n      by auto\n  qed\n  moreover have \"finite (nodes M)\" \n    using assms by auto\n  ultimately show \"finite (D M ISeqs \\<Omega>)\" \"card (D M ISeqs \\<Omega>) \\<le> card (nodes M)\" \n    by (meson  finite_imageI infinite_super surj_card_le)+\nqed\n\n\nlemma append_io_B_in_language :\n  \"append_io_B M io \\<Omega> \\<subseteq> L M\"\nproof\n  fix x assume \"x \\<in> append_io_B M io \\<Omega>\"\n  then obtain res where \"x = io@res\" \"res \\<in> B M io \\<Omega>\"\n    unfolding append_io_B.simps by blast\n  then obtain q where \"q \\<in> io_targets M (initial M) io\"  \"res \\<in> IO_set M q \\<Omega>\"\n    unfolding B.simps by blast\n  then have \"res \\<in> LS M q\" \n    using IO_set_in_language[of M q \\<Omega>] by blast\n\n  obtain pIO where \"path M (io || pIO) (initial M)\" \n                   \"length pIO = length io\" \"target (io || pIO) (initial M) = q\"\n    using \\<open>q \\<in> io_targets M (initial M) io\\<close> by auto\n  moreover obtain pRes where \"path M (res || pRes) q\" \"length pRes = length res\" \n    using \\<open>res \\<in> LS M q\\<close> by auto\n  ultimately have \"io@res \\<in> L M\" \n    using FSM.path_append[of M \"io||pIO\" \"initial M\" \"res||pRes\"]\n    by (metis language_state length_append zip_append) \n  then show \"x \\<in> L M\"\n    using \\<open>x = io@res\\<close> by blast\nqed\n\n\nlemma append_io_B_nonempty :\n  assumes \"applicable_set M \\<Omega>\"\n  and     \"completely_specified M\"\n  and     \"io \\<in> language_state M (initial M)\"\n  and     \"\\<Omega> \\<noteq> {}\"\nshows \"append_io_B M io \\<Omega> \\<noteq> {}\"\nproof -\n  obtain t where \"t \\<in> \\<Omega>\" \n    using assms(4) by blast\n  then have \"applicable M t\" \n    using assms(1) by simp\n  moreover obtain tr where \"path M (io || tr) (initial M) \\<and> length tr = length io\" \n    using assms(3) by auto\n  moreover have \"target (io || tr) (initial M) \\<in> nodes M\"\n    using calculation(2) by blast\n  ultimately have \"IO M (target (io || tr) (initial M)) t \\<noteq> {}\" \n    using assms(2) IO_applicable_nonempty by simp\n  then obtain io' where \"io' \\<in> IO M (target (io || tr) (initial M)) t\" \n    by blast\n  then have \"io' \\<in> IO_set M (target (io || tr) (initial M)) \\<Omega>\" \n    using \\<open>t \\<in> \\<Omega>\\<close> unfolding IO_set.simps by blast\n  moreover have \"(target (io || tr) (initial M)) \\<in> io_targets M (initial M) io\" \n    using \\<open>path M (io || tr) (initial M) \\<and> length tr = length io\\<close> by auto \n  ultimately have \"io' \\<in> B M io \\<Omega>\" \n    unfolding B.simps by blast\n  then have \"io@io' \\<in> append_io_B M io \\<Omega>\" \n    unfolding append_io_B.simps by blast\n  then show ?thesis by blast\nqed\n  \n\nlemma append_io_B_prefix_in_language :\n  assumes \"append_io_B M io \\<Omega> \\<noteq> {}\"\n  shows \"io \\<in> L M\"\nproof -\n  obtain res where \"io @ res \\<in> append_io_B M io \\<Omega> \\<and> res \\<in> B M io \\<Omega>\" \n    using assms by auto \n  then have \"io_targets M (initial M) io \\<noteq> {}\" \n    by auto\n  then obtain q where \"q \\<in> io_targets M (initial M) io\" \n    by blast\n  then obtain tr where \"target (io || tr) (initial M) = q \\<and> path M (io || tr) (initial M) \n                          \\<and> length tr = length io\" by auto \n  then show ?thesis by auto\nqed\n\n\n\n\n\nsubsection {* Characterizing sets *}\n\ntext \\<open>\nA set of ATCs is a characterizing set for some FSM if for every pair of r-distinguishable states it\ncontains an ATC that r-distinguishes them.\n\\<close>\n\nfun characterizing_atc_set :: \"('in, 'out, 'state) FSM \\<Rightarrow> ('in, 'out) ATC set \\<Rightarrow> bool\" where\n\"characterizing_atc_set M \\<Omega> = (applicable_set M \\<Omega> \\<and> (\\<forall> s1 \\<in> (nodes M) . \\<forall> s2 \\<in> (nodes M) . \n    (\\<exists> td . r_dist M td s1 s2) \\<longrightarrow> (\\<exists> tt \\<in> \\<Omega> . r_dist M tt s1 s2)))\"\n\n\nsubsection {* Reduction over ATCs *}\n\ntext \\<open>\nSome state is a an ATC-reduction of another over some set of ATCs if for every contained ATC every \nATC-reaction to it of the former state is also an ATC-reaction of the latter state.\n\\<close>\n\n\nfun atc_reduction :: \"('in, 'out, 'state) FSM \\<Rightarrow> 'state \\<Rightarrow> ('in, 'out, 'state) FSM \\<Rightarrow> 'state \n                      \\<Rightarrow> ('in, 'out) ATC set \\<Rightarrow> bool\" where\n  \"atc_reduction M2 s2 M1 s1 \\<Omega> = (\\<forall> t \\<in> \\<Omega> . IO M2 s2 t \\<subseteq> IO M1 s1 t)\"\n\n\n\n\\<comment> \\<open>r-distinguishability holds for atc-reductions\\<close>\nlemma atc_rdist_dist[intro] :\n  assumes wf2   : \"well_formed M2\"\n  and     cs2   : \"completely_specified M2\"\n  and     ap2   : \"applicable_set M2 \\<Omega>\"\n  and     el_t1 : \"t1 \\<in> nodes M2\"\n  and     red1  : \"atc_reduction M2 t1 M1 s1 \\<Omega>\"\n  and     red2  : \"atc_reduction M2 t2 M1 s2 \\<Omega>\"\n  and     rdist : \"r_dist_set M1 \\<Omega> s1 s2\"\n  and             \"t1 \\<in> nodes M2\"\nshows \"r_dist_set M2 \\<Omega> t1 t2\"\nproof -\n  obtain td where td_def : \"td \\<in> \\<Omega> \\<and> r_dist M1 td s1 s2\" \n    using rdist by auto\n  then have \"IO M1 s1 td \\<inter> IO M1 s2 td = {}\" \n    using td_def by simp\n  moreover have \"IO M2 t1 td \\<subseteq> IO M1 s1 td\" \n    using red1 td_def by auto\n  moreover have \"IO M2 t2 td \\<subseteq> IO M1 s2 td\" \n    using red2 td_def by auto\n  ultimately have no_inter : \"IO M2 t1 td \\<inter> IO M2 t2 td = {}\" \n    by blast\n  \n  then have \"td \\<noteq> Leaf\" \n    by auto\n  then have \"IO M2 t1 td \\<noteq> {}\" \n    by (meson ap2 IO_applicable_nonempty applicable_set.elims(2) cs2 td_def assms(8)) \n  then have \"IO M2 t1 td \\<noteq> IO M2 t2 td\" \n    using no_inter by auto \n  then show ?thesis \n    using no_inter td_def by auto \nqed\n\n\n\n\nsubsection {* Reduction over ATCs applied after input sequences *}\n\ntext \\<open>\nThe following functions check whether some FSM is a reduction of another over a given set of input\nsequences while furthermore the response sets obtained by applying a set of ATCs after every input\nsequence to the first FSM are subsets of the analogously constructed response sets of the second\nFSM.\n\\<close>\n\nfun atc_io_reduction_on :: \"('in, 'out, 'state1) FSM \\<Rightarrow> ('in, 'out, 'state2) FSM \\<Rightarrow> 'in list \n                            \\<Rightarrow> ('in, 'out) ATC set \\<Rightarrow> bool\" where\n  \"atc_io_reduction_on M1 M2 iseq \\<Omega> = (L\\<^sub>i\\<^sub>n M1 {iseq} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {iseq} \n    \\<and> (\\<forall> io \\<in> L\\<^sub>i\\<^sub>n M1 {iseq} . B M1 io \\<Omega> \\<subseteq> B M2 io \\<Omega>))\"\n\nfun atc_io_reduction_on_sets :: \"('in, 'out, 'state1) FSM \\<Rightarrow> 'in list set \\<Rightarrow> ('in, 'out) ATC set \n                                  \\<Rightarrow> ('in, 'out, 'state2) FSM \\<Rightarrow> bool\" where\n  \"atc_io_reduction_on_sets M1 TS \\<Omega> M2 = (\\<forall> iseq \\<in> TS . atc_io_reduction_on M1 M2 iseq \\<Omega>)\"\n\nnotation \n  atc_io_reduction_on_sets (\"(_ \\<preceq>\\<lbrakk>_._\\<rbrakk> _)\" [1000,1000,1000,1000])\n\n\n\nlemma io_reduction_from_atc_io_reduction :\n  assumes \"atc_io_reduction_on_sets M1 T \\<Omega> M2\"\n  and     \"finite T\"\n  shows \"io_reduction_on M1 T M2\" \nusing assms(2,1) proof (induction T)\n  case empty\n  then show ?case by auto\nnext\n  case (insert t T)\n  then have \"atc_io_reduction_on M1 M2 t \\<Omega>\"\n    by auto\n  then have \"L\\<^sub>i\\<^sub>n M1 {t} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {t}\"\n    using atc_io_reduction_on.simps by blast\n\n  have \"L\\<^sub>i\\<^sub>n M1 T \\<subseteq> L\\<^sub>i\\<^sub>n M2 T\" \n    using insert.IH\n  proof -\n    have \"atc_io_reduction_on_sets M1 T \\<Omega> M2\"\n      by (meson contra_subsetD insert.prems atc_io_reduction_on_sets.simps subset_insertI)\n    then show ?thesis\n      using insert.IH by blast\n  qed\n  then have \"L\\<^sub>i\\<^sub>n M1 T \\<subseteq> L\\<^sub>i\\<^sub>n M2 (insert t T)\"\n    by (meson insert_iff language_state_for_inputs_in_language_state \n        language_state_for_inputs_map_fst language_state_for_inputs_map_fst_contained \n        subsetCE subsetI) \n  moreover have \"L\\<^sub>i\\<^sub>n M1 {t} \\<subseteq> L\\<^sub>i\\<^sub>n M2 (insert t T)\"\n  proof -\n    obtain pps :: \"('a \\<times> 'b) list set \\<Rightarrow> ('a \\<times> 'b) list set \\<Rightarrow> ('a \\<times> 'b) list\" where\n      \"\\<forall>x0 x1. (\\<exists>v2. v2 \\<in> x1 \\<and> v2 \\<notin> x0) = (pps x0 x1 \\<in> x1 \\<and> pps x0 x1 \\<notin> x0)\"\n      by moura\n    then have \"\\<forall>P Pa. pps Pa P \\<in> P \\<and> pps Pa P \\<notin> Pa \\<or> P \\<subseteq> Pa\"\n      by blast\n    moreover\n    { assume \"map fst (pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 {t})) \\<notin> insert t T\"\n      then have \"pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 {t}) \\<notin> L\\<^sub>i\\<^sub>n M1 {t} \n                      \\<or> pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 {t}) \\<in> L\\<^sub>i\\<^sub>n M2 (insert t T)\"\n        by (metis (no_types) insertI1 language_state_for_inputs_map_fst_contained singletonD) }\n    ultimately show ?thesis\n      by (meson \\<open>L\\<^sub>i\\<^sub>n M1 {t} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {t}\\<close> language_state_for_inputs_in_language_state \n          language_state_for_inputs_map_fst set_rev_mp)\n  qed\n        \n     \n  ultimately show ?case\n  proof -\n    have f1: \"\\<forall>ps P Pa. (ps::('a \\<times> 'b) list) \\<notin> P \\<or> \\<not> P \\<subseteq> Pa \\<or> ps \\<in> Pa\"\n      by blast\n    obtain pps :: \"('a \\<times> 'b) list set \\<Rightarrow> ('a \\<times> 'b) list set \\<Rightarrow> ('a \\<times> 'b) list\" where\n      \"\\<forall>x0 x1. (\\<exists>v2. v2 \\<in> x1 \\<and> v2 \\<notin> x0) = (pps x0 x1 \\<in> x1 \\<and> pps x0 x1 \\<notin> x0)\"\n      by moura\n    moreover\n    { assume \"pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 (insert t T)) \n              \\<notin> L\\<^sub>i\\<^sub>n M1 {t}\"\n      moreover\n      { assume \"map fst (pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 (insert t T))) \n                \\<notin> {t}\"\n        then have \"map fst (pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) \n                      (L\\<^sub>i\\<^sub>n M1 (insert t T))) \\<noteq> t\"\n          by blast\n        then have \"pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 (insert t T)) \n                        \\<notin> L\\<^sub>i\\<^sub>n M1 (insert t T) \n                    \\<or> pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 (insert t T)) \n                          \\<in> L\\<^sub>i\\<^sub>n M2 (insert t T)\"\n          using f1 by (meson \\<open>L\\<^sub>i\\<^sub>n M1 T \\<subseteq> L\\<^sub>i\\<^sub>n M2 (insert t T)\\<close> \n                       insertE language_state_for_inputs_in_language_state \n                       language_state_for_inputs_map_fst \n                       language_state_for_inputs_map_fst_contained) }\n      ultimately have \"io_reduction_on M1 (insert t T) M2 \n                        \\<or> pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 (insert t T)) \n                            \\<notin> L\\<^sub>i\\<^sub>n M1 (insert t T) \n                        \\<or> pps (L\\<^sub>i\\<^sub>n M2 (insert t T)) (L\\<^sub>i\\<^sub>n M1 (insert t T)) \n                            \\<in> L\\<^sub>i\\<^sub>n M2 (insert t T)\"\n        using f1 by (meson language_state_for_inputs_in_language_state \n                     language_state_for_inputs_map_fst) }\n      ultimately show ?thesis\n        using f1 by (meson \\<open>L\\<^sub>i\\<^sub>n M1 {t} \\<subseteq> L\\<^sub>i\\<^sub>n M2 (insert t T)\\<close> subsetI)\n  qed \nqed\n    \nlemma atc_io_reduction_on_subset :\n  assumes \"atc_io_reduction_on_sets M1 T \\<Omega> M2\"\n  and     \"T' \\<subseteq> T\"\nshows \"atc_io_reduction_on_sets M1 T' \\<Omega> M2\"\n  using assms unfolding atc_io_reduction_on_sets.simps by blast\n\n\nlemma atc_reaction_reduction[intro] :\n  assumes ls : \"language_state M1 q1 \\<subseteq> language_state M2 q2\"\n  and     el1 : \"q1 \\<in> nodes M1\"\n  and     el2 : \"q2 \\<in> nodes M2\"\n  and     rct : \"atc_reaction M1 q1 t io\"\n  and     ob2 : \"observable M2\"\n  and     ob1 : \"observable M1\"\nshows \"atc_reaction M2 q2 t io\"\nusing assms proof (induction t arbitrary: io q1 q2)\n  case Leaf\n  then have \"io = []\" \n    by (metis atc_reaction_nonempty_no_leaf list.exhaust) \n  then show ?case \n    by (simp add: leaf)  \nnext\n  case (Node x f)\n  then obtain io_hd io_tl where io_split : \"io = io_hd # io_tl\" \n    by (metis ATC.distinct(1) atc_reaction_empty list.exhaust) \n  moreover obtain y where y_def : \"io_hd = (x,y)\" \n    using Node calculation by (metis ATC.inject atc_reaction_nonempty surj_pair) \n  ultimately  obtain q1x where q1x_def : \"q1x \\<in> succ M1 (x,y) q1\" \"atc_reaction M1 q1x (f y) io_tl\" \n    using Node.prems(4) by blast \n\n  then have pt1 : \"path M1 ([(x,y)] || [q1x]) q1\" \n    by auto\n  then have ls1 : \"[(x,y)] \\<in> language_state M1 q1\" \n    unfolding language_state_def path_def using list.simps(9) by force\n  moreover have \"q1x \\<in> io_targets M1 q1 [(x,y)]\" \n    unfolding io_targets.simps\n  proof -\n    have f1: \"length [(x, y)] = length [q1x]\"\n      by simp\n    have \"q1x = target ([(x, y)] || [q1x]) q1\"\n      by simp\n    then show \"q1x \\<in> {target ([(x, y)] || cs) q1 |cs. path M1 ([(x, y)] || cs) q1 \n                                                      \\<and> length [(x, y)] = length cs}\"\n      using f1 pt1 by blast\n  qed \n  ultimately have tgt1 : \"io_targets M1 q1 [(x,y)] = {q1x}\" \n    using Node.prems io_targets_observable_singleton_ex q1x_def \n    by (metis (no_types, lifting) singletonD) \n\n  \n  then have ls2 : \"[(x,y)] \\<in> language_state M2 q2\" \n    using Node.prems(1) ls1 by auto\n  then obtain q2x where q2x_def : \"q2x \\<in> succ M2 (x,y) q2\" \n    unfolding language_state_def path_def \n    using transition_system.path.cases by fastforce \n  then have pt2 : \"path M2 ([(x,y)] || [q2x]) q2\" \n    by auto\n  then have \"q2x \\<in> io_targets M2 q2 [(x,y)]\" \n    using ls2 unfolding io_targets.simps \n  proof -\n    have f1: \"length [(x, y)] = length [q2x]\"\n      by simp\n    have \"q2x = target ([(x, y)] || [q2x]) q2\"\n      by simp\n    then show \"q2x \\<in> {target ([(x, y)] || cs) q2 |cs. path M2 ([(x, y)] || cs) q2 \n                                                        \\<and> length [(x, y)] = length cs}\"\n      using f1 pt2 by blast\n  qed\n\n  then have tgt2 : \"io_targets M2 q2 [(x,y)] = {q2x}\" \n    using Node.prems io_targets_observable_singleton_ex ls2 q2x_def \n    by (metis (no_types, lifting) singletonD) \n\n\n  then have \"language_state M1 q1x \\<subseteq> language_state M2 q2x\" \n    using language_state_inclusion_of_state_reached_by_same_sequence\n          [of M1 q1 M2 q2 \"[(x,y)]\" q1x q2x] \n          tgt1 tgt2 Node.prems by auto\n  moreover have \"q1x \\<in> nodes M1\" \n    using q1x_def(1) Node.prems(2) by (metis insertI1 io_targets_nodes tgt1)\n  moreover have \"q2x \\<in> nodes M2\" \n    using q2x_def(1) Node.prems(3) by (metis insertI1 io_targets_nodes tgt2)\n  ultimately have \"q2x \\<in> succ M2 (x,y) q2 \\<and> atc_reaction M2 q2x (f y) io_tl\" \n    using Node.IH[of \"f y\" q1x q2x io_tl] ob1 ob2 q1x_def(2) q2x_def by blast \n \n\n  then show \"atc_reaction M2 q2 (Node x f) io\" using io_split y_def by blast \nqed\n\n\nlemma IO_reduction :\n  assumes ls : \"language_state M1 q1 \\<subseteq> language_state M2 q2\"\n  and     el1 : \"q1 \\<in> nodes M1\"\n  and     el2 : \"q2 \\<in> nodes M2\"\n  and     ob1 : \"observable M1\"\n  and     ob2 : \"observable M2\"\nshows \"IO M1 q1 t \\<subseteq> IO M2 q2 t\"\n  using assms atc_reaction_reduction unfolding IO.simps by auto\n\nlemma IO_set_reduction :\n  assumes ls : \"language_state M1 q1 \\<subseteq> language_state M2 q2\"\n  and     el1 : \"q1 \\<in> nodes M1\"\n  and     el2 : \"q2 \\<in> nodes M2\"\n  and     ob1 : \"observable M1\"\n  and     ob2 : \"observable M2\"\nshows \"IO_set M1 q1 \\<Omega> \\<subseteq> IO_set M2 q2 \\<Omega>\"\nproof -\n  have \"\\<forall> t \\<in> \\<Omega> . IO M1 q1 t \\<subseteq> IO M2 q2 t\" \n    using assms IO_reduction by metis \n  then show ?thesis \n    unfolding IO_set.simps by blast\nqed\n\nlemma B_reduction :\n  assumes red : \"M1 \\<preceq> M2\"\n  and     ob1 : \"observable M1\"\n  and     ob2 : \"observable M2\"\nshows \"B M1 io \\<Omega> \\<subseteq> B M2 io \\<Omega>\"\nproof \n  fix xy assume xy_assm : \"xy \\<in> B M1 io \\<Omega>\"\n  then obtain q1x where q1x_def : \"q1x \\<in> (io_targets M1 (initial M1) io) \\<and> xy \\<in> IO_set M1 q1x \\<Omega>\" \n    unfolding B.simps by auto\n  then obtain tr1 where tr1_def : \"path M1 (io || tr1) (initial M1) \\<and> length io = length tr1\" \n    by auto\n\n  then have q1x_ob : \"io_targets M1 (initial M1) io = {q1x}\" \n    using assms\n    by (metis io_targets_observable_singleton_ex language_state q1x_def singleton_iff) \n  \n  then have ls1 : \"io \\<in> language_state M1 (initial M1)\" \n    by auto \n  then have ls2 : \"io \\<in> language_state M2 (initial M2)\" \n    using red by auto\n\n  then obtain tr2 where tr2_def : \"path M2 (io || tr2) (initial M2) \\<and> length io = length tr2\" \n    by auto\n  then obtain q2x where q2x_def : \"q2x \\<in> (io_targets M2 (initial M2) io)\" \n    by auto\n\n  then have q2x_ob : \"io_targets M2 (initial M2) io = {q2x}\" \n    using tr2_def assms\n    by (metis io_targets_observable_singleton_ex language_state singleton_iff) \n\n  then have \"language_state M1 q1x \\<subseteq> language_state M2 q2x\" \n    using q1x_ob assms unfolding io_reduction.simps \n    by (simp add: language_state_inclusion_of_state_reached_by_same_sequence) \n  then have \"IO_set M1 q1x \\<Omega> \\<subseteq> IO_set M2 q2x \\<Omega>\" \n    using assms IO_set_reduction by (metis FSM.nodes.initial io_targets_nodes q1x_def q2x_def) \n  moreover have \"B M1 io \\<Omega> = IO_set M1 q1x \\<Omega>\" \n    using q1x_ob by auto\n  moreover have \"B M2 io \\<Omega> = IO_set M2 q2x \\<Omega>\" \n    using q2x_ob by auto\n  ultimately have \"B M1 io \\<Omega> \\<subseteq> B M2 io \\<Omega>\" \n    by simp\n  then show \"xy \\<in> B M2 io \\<Omega>\" using xy_assm \n    by blast\nqed\n\n\nlemma append_io_B_reduction :\n  assumes red : \"M1 \\<preceq> M2\"\n  and     ob1 : \"observable M1\"\n  and     ob2 : \"observable M2\"\nshows \"append_io_B M1 io \\<Omega> \\<subseteq> append_io_B M2 io \\<Omega>\"\nproof \n  fix ioR assume ioR_assm : \"ioR \\<in> append_io_B M1 io \\<Omega>\" \n  then obtain res where res_def : \"ioR = io @ res\" \"res \\<in> B M1 io \\<Omega>\" \n    by auto\n  then have \"res \\<in> B M2 io \\<Omega>\" \n    using assms B_reduction by (metis (no_types, hide_lams) subset_iff)\n  then show \"ioR \\<in> append_io_B M2 io \\<Omega>\" \n    using ioR_assm res_def by auto\nqed \n\n\n\nlemma atc_io_reduction_on_reduction[intro] :\n  assumes red : \"M1 \\<preceq> M2\"\n  and     ob1 : \"observable M1\"\n  and     ob2 : \"observable M2\"\nshows \"atc_io_reduction_on M1 M2 iseq \\<Omega>\"\nunfolding atc_io_reduction_on.simps proof \n  show \"L\\<^sub>i\\<^sub>n M1 {iseq} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {iseq}\" \n    using red by auto \nnext\n  show \"\\<forall>io\\<in>L\\<^sub>i\\<^sub>n M1 {iseq}. B M1 io \\<Omega> \\<subseteq> B M2 io \\<Omega>\" \n    using  B_reduction assms by blast\nqed\n    \n\nlemma atc_io_reduction_on_sets_reduction[intro] :\n  assumes red : \"M1 \\<preceq> M2\"\n  and     ob1 : \"observable M1\"\n  and     ob2 : \"observable M2\"\nshows \"atc_io_reduction_on_sets M1 TS \\<Omega> M2\"\n  using assms atc_io_reduction_on_reduction by (metis atc_io_reduction_on_sets.elims(3)) \n\nlemma atc_io_reduction_on_sets_via_LS\\<^sub>i\\<^sub>n : \n  assumes \"atc_io_reduction_on_sets M1 TS \\<Omega> M2\"\n  shows \"(L\\<^sub>i\\<^sub>n M1 TS \\<union> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 TS. B M1 io \\<Omega>)) \n          \\<subseteq> (L\\<^sub>i\\<^sub>n M2 TS \\<union> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 TS. B M2 io \\<Omega>))\"\nproof -\n  have \"\\<forall> iseq \\<in> TS . (L\\<^sub>i\\<^sub>n M1 {iseq} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {iseq} \n                        \\<and> (\\<forall> io \\<in> L\\<^sub>i\\<^sub>n M1 {iseq} . B M1 io \\<Omega> \\<subseteq> B M2 io \\<Omega>))\" \n    using assms by auto\n  then have \"\\<forall> iseq \\<in> TS . (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 {iseq}. B M1 io \\<Omega>) \n                            \\<subseteq> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 {iseq}. B M2 io \\<Omega>)\"\n    by blast\n  moreover have \"\\<forall> iseq \\<in> TS . (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 {iseq}. B M2 io \\<Omega>) \n                                \\<subseteq> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 TS. B M2 io \\<Omega>)\"\n    unfolding language_state_for_inputs.simps by blast\n  ultimately have elem_subset : \"\\<forall> iseq \\<in> TS . \n                                  (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 {iseq}. B M1 io \\<Omega>) \n                                    \\<subseteq> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 TS. B M2 io \\<Omega>)\" \n    by blast\n  \n  show ?thesis\n  proof \n    fix x assume \"x \\<in> L\\<^sub>i\\<^sub>n M1 TS \\<union> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 TS. B M1 io \\<Omega>)\"\n    then show \"x \\<in> L\\<^sub>i\\<^sub>n M2 TS \\<union> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 TS. B M2 io \\<Omega>)\"\n    proof (cases \"x \\<in> L\\<^sub>i\\<^sub>n M1 TS\")\n      case True\n      then obtain iseq where \"iseq \\<in> TS\" \"x\\<in> L\\<^sub>i\\<^sub>n M1 {iseq}\"\n        unfolding language_state_for_inputs.simps by blast \n      then have \"atc_io_reduction_on M1 M2 iseq \\<Omega>\" \n        using assms by auto\n      then have \"L\\<^sub>i\\<^sub>n M1 {iseq} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {iseq}\" \n        by auto\n      then have \"x \\<in> L\\<^sub>i\\<^sub>n M2 TS\"\n        by (metis (no_types, lifting) UN_I \n            \\<open>\\<And>thesis. (\\<And>iseq. \\<lbrakk>iseq \\<in> TS; x \\<in> L\\<^sub>i\\<^sub>n M1 {iseq}\\<rbrakk> \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\\<close> \n            \\<open>\\<forall>iseq\\<in>TS. L\\<^sub>i\\<^sub>n M1 {iseq} \\<subseteq> L\\<^sub>i\\<^sub>n M2 {iseq} \\<and> (\\<forall>io\\<in>L\\<^sub>i\\<^sub>n M1 {iseq}. B M1 io \\<Omega> \\<subseteq> B M2 io \\<Omega>)\\<close> \n            language_state_for_input_alt_def language_state_for_inputs_alt_def set_rev_mp) \n      then show ?thesis \n        by blast\n    next\n      case False\n      then have \"x \\<in> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 TS. B M1 io \\<Omega>)\"\n        using \\<open>x \\<in> L\\<^sub>i\\<^sub>n M1 TS \\<union> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 TS. B M1 io \\<Omega>)\\<close> by blast\n      then obtain io where \"io \\<in> L\\<^sub>i\\<^sub>n M1 TS\" \"x \\<in> B M1 io \\<Omega>\"\n        by blast\n      then obtain iseq where \"iseq \\<in> TS\" \"io\\<in>L\\<^sub>i\\<^sub>n M1 {iseq}\"\n        unfolding language_state_for_inputs.simps by blast\n      have \"x \\<in> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M1 {iseq}. B M1 io \\<Omega>)\"\n        using \\<open>io \\<in> L\\<^sub>i\\<^sub>n M1 {iseq}\\<close> \\<open>x \\<in> B M1 io \\<Omega>\\<close> by blast\n      then have \"x \\<in> (\\<Union>io\\<in>L\\<^sub>i\\<^sub>n M2 TS. B M2 io \\<Omega>)\"\n        using \\<open>iseq \\<in> TS\\<close> elem_subset by blast\n      then show ?thesis \n        by blast\n    qed\n  qed\nqed\n\n\n\n\nend\n", "meta": {"author": "RobertSachtleben", "repo": "Refined-Adaptive-State-Counting", "sha": "3691de6f16cec5ec74282465495c12e6a40133aa", "save_path": "github-repos/isabelle/RobertSachtleben-Refined-Adaptive-State-Counting", "path": "github-repos/isabelle/RobertSachtleben-Refined-Adaptive-State-Counting/Refined-Adaptive-State-Counting-3691de6f16cec5ec74282465495c12e6a40133aa/Adaptive_State_Counting/ATC/ATC.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.8558511414521922, "lm_q1q2_score": 0.755226896754299}}
{"text": "section\\<open>Perfect Number Theorem\\<close>\n\ntheory Perfect\nimports Sigma\nbegin\n\ndefinition  perfect :: \"nat => bool\" where\n\"perfect m == m>0 & 2*m = sigma m\"\n\ntheorem perfect_number_theorem:\n  assumes even: \"even m\" and perfect: \"perfect m\"\n  shows \"\\<exists> n . m = 2^n*(2^(n+1) - 1) \\<and> prime ((2::nat)^(n+1) - 1)\"\nproof                                         \n  from perfect have m0: \"m>0\" by (auto simp add: perfect_def)\n\n  let ?n = \"multiplicity 2 m\" \n  let ?A = \"m div 2^?n\"\n  let ?np = \"(2::nat)^(?n+1) - 1\"\n\n  from even m0 have n1: \"?n >= 1 \" by (simp add: multiplicity_geI)\n\n  have  \"2^?n dvd m\" by (rule multiplicity_dvd)\n  hence \"m = 2^?n*?A\" by (simp only: dvd_mult_div_cancel) \n  with m0 have mdef: \"m=2^?n*?A & coprime 2 ?A\"\n    using multiplicity_decompose [of m 2] by simp\n  moreover with m0 have a0: \"?A>0\" by (metis nat_0_less_mult_iff)\n  moreover\n  { from perfect have \"2*m=sigma(m)\" by (simp add: perfect_def)\n    with mdef have \"2^(?n+1)*?A=sigma(2^?n*?A)\" by auto\n  } ultimately have \"2^(?n+1)*?A=sigma(2^?n)*sigma(?A)\"\n    by (simp add: sigma_semimultiplicative)\n  hence formula: \"2^(?n+1)*?A=(?np)*sigma(?A)\"\n    by (simp only: sigma_prime_power_two)\n\n  from n1 have \"(2::nat)^(?n+1) >= 2^2\" by (simp only: power_increasing)\n  hence nplarger: \"?np>= 3\" by auto\n\n  let ?B = \"?A div ?np\"\n\n  from formula have \"?np dvd ?A * 2^(?n+1)\"\n    by (auto simp add: ac_simps)\n  then have \"?np dvd ?A\"\n    using coprime_diff_one_left_nat [of \"2 ^ (multiplicity 2 m + 1)\"]\n    by (auto simp add: coprime_dvd_mult_left_iff)\n  then have bdef: \"?np*?B = ?A\"\n    by simp\n  with a0 have  b0: \"?B>0\" by (metis gr0I mult_is_0)\n\n  from nplarger a0 have bsmallera: \"?B < ?A\" by auto\n\n  have \"?B = 1\"\n  proof (rule ccontr)\n    assume \"~?B = 1\"\n    with b0 bsmallera have \"1<?B\" \"?B<?A\" by auto\n    moreover from bdef have \"?B : divisors ?A\" by (rule mult_divisors2)\n    ultimately have \"1+?B+?A <= sigma ?A\" by (rule sigma_third_divisor)\n    with nplarger have \"?np*(1+?A+?B) <= ?np*(sigma ?A)\"\n      by (auto simp only: nat_mult_le_cancel1)\n    with bdef have \"?np+?A*?np + ?A*1 <= ?np*(sigma ?A)\"\n      by (simp only: add_mult_distrib_three mult.commute)\n    hence \"?np+?A*(?np + 1) <= ?np*(sigma ?A)\" by (simp only:add_mult_distrib2)\n    with nplarger have \"2^(?n+1)*?A < ?np*(sigma ?A)\" by(simp add:mult.commute)\n    with formula show \"False\" by auto\n  qed\n\n  with bdef have adef: \"?A=?np\" by auto\n  with formula have \"?np*2^(?n+1) =(?np)*sigma(?A)\" by auto\n  with nplarger adef have \"?A + 1=sigma(?A)\" by auto\n  with a0 have \"prime ?A\" by (simp add: sigma_imp_prime)\n  with mdef adef show \"m = 2^?n*(?np) & prime ?np\" by simp\nqed\n\ntheorem Euclid_book9_prop36:\n  assumes p: \"prime (2^(n+1) - (1::nat))\"\n  shows \"perfect ((2^n)*(2^(n+1) - 1))\"\nproof (unfold perfect_def, auto)\n  from assms show \"(2::nat)*2^n > Suc 0\" by (auto simp add: prime_nat_iff)\nnext\n  have \"2 ~= ((2::nat)^(n+1) - 1)\" by simp arith\n  then have \"coprime (2::nat) (2^(n+1) - 1)\"\n    by (metis p primes_coprime_nat two_is_prime_nat) \n  moreover with p have \"2^(n+1) - 1 > (0::nat)\"\n    by (auto simp add: prime_nat_iff)\n  ultimately have  \"sigma (2^n*(2^(n+1) - 1)) = (sigma(2^n))*(sigma(2^(n+1) - 1))\"\n    by (metis sigma_semimultiplicative two_is_prime_nat)\n  also from assms have \"... = (sigma(2^(n)))*(2^(n+1))\"\n    by (auto simp add: prime_imp_sigma)\n  also have \"... = (2^(n+1) - 1)*(2^(n+1))\" by(simp add: sigma_prime_power_two)\n  finally show \"2*(2^n * (2*2^n - Suc 0)) = sigma(2^n*(2*2^n - Suc 0))\" by auto\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Perfect-Number-Thm/Perfect.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818864, "lm_q2_score": 0.8311430499496095, "lm_q1q2_score": 0.7551914542089261}}
{"text": "theory Why3_Number\nimports\n  Why3_Int\n  \"HOL-Computational_Algebra.Primes\"\nbegin\n\nsection {* Parity properties *}\n\nwhy3_open \"number/Parity.xml\"\n\nwhy3_vc evenqtdef by arith\n\nwhy3_vc oddqtdef by arith\n\nwhy3_vc even_or_odd by auto\n\nwhy3_vc even_not_odd using assms by simp\n\nwhy3_vc odd_not_even using assms by simp\n\nwhy3_vc even_odd using assms by simp\n\nwhy3_vc odd_even using assms by simp\n\nwhy3_vc even_even using assms by simp\n\nwhy3_vc odd_odd using assms by simp\n\nwhy3_vc even_2k by simp\n\nwhy3_vc odd_2k1 by simp\n\nwhy3_vc even_mod2\n  by (auto simp add: evenqtdef cmod_def sgn_if minus_equation_iff [of n])\n\nwhy3_end\n\n\nsection {* Divisibility *}\n\nwhy3_open \"number/Divisibility.xml\"\n\nwhy3_vc dividesqtdef\n  by (auto simp add: cmod_def sgn_if minus_equation_iff [of n])\n\nwhy3_vc divides_refl by simp\n\nwhy3_vc divides_1_n by simp\n\nwhy3_vc divides_0 by simp\n\nwhy3_vc divides_left using assms by simp\n\nwhy3_vc divides_right using assms by simp\n\nwhy3_vc divides_oppr using assms by simp\n\nwhy3_vc divides_oppl using assms by simp\n\nwhy3_vc divides_oppr_rev using assms by simp\n\nwhy3_vc divides_oppl_rev using assms by simp\n\nwhy3_vc divides_plusr using assms by simp\n\nwhy3_vc divides_minusr using assms by simp\n\nwhy3_vc divides_multl using assms by simp\n\nwhy3_vc divides_multr using assms by simp\n\nwhy3_vc divides_factorl by simp\n\nwhy3_vc divides_factorr by simp\n\nwhy3_vc divides_n_1 using assms by auto\n\nwhy3_vc divides_antisym\n  using assms\n  by (auto dest: zdvd_antisym_abs)\n\nwhy3_vc divides_trans using assms by (rule dvd_trans)\n\nwhy3_vc divides_bounds using assms by (simp add: dvd_imp_le_int)\n\nwhy3_vc mod_divides_euclidean\n  using assms\n  by (auto simp add: emod_def split: if_split_asm)\n\nwhy3_vc divides_mod_euclidean\n  using assms\n  by (simp add: emod_def dvd_eq_mod_eq_0 zabs_def zmod_zminus2_eq_if)\n\nwhy3_vc mod_divides_computer\n  using assms\n  by (auto simp add: cmod_def zabs_def sgn_0_0 zmod_zminus1_eq_if\n    not_sym [OF less_imp_neq [OF pos_mod_bound]]\n    split: if_split_asm)\n\nwhy3_vc divides_mod_computer\n  using assms\n  by (simp add: cmod_def dvd_eq_mod_eq_0 zabs_def\n    zmod_zminus1_eq_if zmod_zminus2_eq_if)\n\nwhy3_vc even_divides ..\n\nwhy3_vc odd_divides ..\n\nwhy3_vc dividesqtspec\n  by (simp add: dvd_def mult.commute)\n\nwhy3_end\n\n\nsection {* Greatest Common Divisor *}\n\nwhy3_open \"number/Gcd.xml\"\n\nwhy3_vc gcd_nonneg by simp\n\nwhy3_vc gcd_def1 by simp\n\nwhy3_vc gcd_def2 by simp\n\nwhy3_vc gcd_def3 using assms by (rule gcd_greatest)\n\nwhy3_vc gcd_unique using assms\n  by (simp add: gcd_unique_int [symmetric])\n\nwhy3_vc Comm by (rule gcd.commute)\n\nwhy3_vc Assoc by (rule gcd.assoc)\n\nwhy3_vc gcd_0_pos using assms by simp\n\nwhy3_vc gcd_0_neg using assms by simp\n\nwhy3_vc gcd_opp by simp\n\nwhy3_vc gcd_euclid\n  using gcd_add_mult [of a \"- q\" b]\n  by (simp add: algebra_simps)\n\nwhy3_vc Gcd_computer_mod\n  using assms gcd_add_mult [of b \"- 1\" \"a mod b\"]\n  by (simp add: cmod_def zabs_def gcd_red_int [symmetric] sgn_if algebra_simps del: gcd_mod_right)\n    (simp add: zmod_zminus2_eq_if gcd_red_int [of a b] del: gcd_mod_right)\n\nwhy3_vc Gcd_euclidean_mod\n  using assms gcd_add_mult [of b \"- 1\" \"a mod b\"]\n  by (simp add: emod_def zabs_def gcd_red_int [symmetric] algebra_simps del: gcd_mod_right)\n    (simp add: zmod_zminus2_eq_if gcd_red_int [of a b] del: gcd_mod_right)\n\nwhy3_vc gcd_mult using assms\n  by (simp add: gcd_mult_distrib_int [symmetric])\n\nwhy3_end\n\n\nsection {* Prime numbers *}\n\nwhy3_open \"number/Prime.xml\"\n\nwhy3_vc primeqtdef\n  by (auto simp add: prime_int_iff')\n\nwhy3_vc not_prime_1 by simp\n\nwhy3_vc prime_2 by simp\n\nwhy3_vc prime_3 by simp\n\nwhy3_vc prime_divisors\n  using assms\n  by (auto simp add: prime_int_altdef dest: spec [of _ \"\\<bar>d\\<bar>\"])\n\nlemma small_divisors_aux:\n  \"1 < (n::nat) \\<Longrightarrow> n < p \\<Longrightarrow> n dvd p \\<Longrightarrow> \\<exists>d. prime d \\<and> d * d \\<le> p \\<and> d dvd p\"\nproof (induct n rule: less_induct)\n  case (less n)\n  then obtain m where \"p = n * m\" by (auto simp add: dvd_def)\n  show ?case\n  proof (cases \"prime n\")\n    case True\n    show ?thesis\n    proof (cases \"n \\<le> m\")\n      case True\n      with `p = n * m` `prime n`\n      show ?thesis by auto\n    next\n      case False\n      then have \"m < n\" by simp\n      moreover from `n < p` `p = n * m` have \"1 < m\" by simp\n      moreover from `1 < n` `n < p` `p = n * m` have \"m < p\" by simp\n      moreover from `p = n * m` have \"m dvd p\" by simp\n      ultimately show ?thesis by (rule less)\n    qed\n  next\n    case False\n    with `1 < n` obtain k where \"k dvd n\" \"k \\<noteq> 1\" \"k \\<noteq> n\"\n      by (auto simp add: prime_nat_iff)\n    with `1 < n` have \"k \\<le> n\" by (simp add: dvd_imp_le)\n    with `k \\<noteq> n` have \"k < n\" by simp\n    moreover from `k dvd n` `1 < n` have \"k \\<noteq> 0\" by (rule_tac notI) simp\n    with `k \\<noteq> 1` have \"1 < k\" by simp\n    moreover from `k < n` `n < p` have \"k < p\" by simp\n    moreover from `k dvd n` `n dvd p` have \"k dvd p\" by (rule dvd_trans)\n    ultimately show ?thesis by (rule less)\n  qed\nqed\n\nwhy3_vc small_divisors\n  unfolding primeqtdef\nproof\n  show \"2 \\<le> p\" by fact\n\n  show \"\\<forall>n. 1 < n \\<and> n < p \\<longrightarrow> \\<not> n dvd p\"\n  proof (intro strip)\n    fix n\n    assume \"1 < n \\<and> n < p\"\n    show \"\\<not> n dvd p\"\n    proof\n      assume \"n dvd p\"\n      with `1 < n \\<and> n < p`\n      have \"1 < nat n\" \"nat n < nat p\" \"nat n dvd nat p\"\n        by (simp_all add: nat_dvd_iff)\n      then have \"\\<exists>d. prime d \\<and> d * d \\<le> nat p \\<and> d dvd (nat p)\"\n        by (rule small_divisors_aux)\n      with `2 \\<le> p` obtain d\n        where d: \"prime (int d)\" \"int d * int d \\<le> p\" \"int d dvd p\"\n        by (auto simp add: int_dvd_int_iff [symmetric] le_nat_iff)\n      from `prime (int d)` have \"2 \\<le> int d\" by (simp add: prime_ge_2_int)\n      then have \"2 \\<le> int d\" by simp\n      with `2 \\<le> int d` have \"2 * 2 \\<le> int d * int d\"\n        by (rule mult_mono) simp_all\n      with d assms `2 \\<le> int d` show False by auto\n    qed\n  qed\nqed\n\nwhy3_vc even_prime\nproof -\n  from `prime p` have \"0 \\<le> p\" by (simp add: primeqtdef)\n  from `prime p` have \"2 \\<le> p\" by (simp add: prime_ge_2_int)\n  with `prime p` `even p` `0 \\<le> p` show ?thesis\n    by (auto simp add: order_le_less prime_odd_int)\nqed\n\nwhy3_vc odd_prime\nproof -\n  from `prime p` have \"2 \\<le> p\" by (simp add: prime_ge_2_int)\n  with `prime p` `3 \\<le> p` show ?thesis\n    by (auto simp add: order_le_less prime_odd_int)\nqed\n\nwhy3_end\n\n\nsection {* Coprime numbers *}\n\nwhy3_open \"number/Coprime.xml\"\n\nwhy3_vc coprimeqtdef by (rule coprime_iff_gcd_eq_1)\n\nwhy3_vc prime_coprime\nproof -\n  have \"(\\<forall>n. 1 < n \\<and> n < p \\<longrightarrow> \\<not> n dvd p) =\n    (\\<forall>n. 1 \\<le> n \\<and> n < p \\<longrightarrow> coprime n p)\"\n  proof\n    assume H: \"\\<forall>n. 1 < n \\<and> n < p \\<longrightarrow> \\<not> n dvd p\"\n    show \"\\<forall>n. 1 \\<le> n \\<and> n < p \\<longrightarrow> coprime n p\"\n    proof (intro strip)\n      fix n\n      assume H': \"1 \\<le> n \\<and> n < p\"\n      {\n        fix d\n        assume \"0 \\<le> d\" \"d dvd n\" \"d dvd p\"\n        with H' have \"d \\<noteq> 0\" by auto\n        have \"d = 1\"\n        proof (rule ccontr)\n          assume \"d \\<noteq> 1\"\n          with `0 \\<le> d` `d \\<noteq> 0` have \"1 < d\" by simp\n          moreover from `d dvd p` H' have \"d \\<le> p\" by (auto dest: zdvd_imp_le)\n          moreover from `d dvd n` H' have \"d \\<noteq> p\" by (auto dest: zdvd_imp_le)\n          ultimately show False using `d dvd p` H by auto\n        qed\n      }\n      then show \"coprime n p\"\n        by (auto simp add: coprime_iff_gcd_eq_1)\n    qed\n  next\n    assume H: \"\\<forall>n. 1 \\<le> n \\<and> n < p \\<longrightarrow> coprime n p\"\n    show \"\\<forall>n. 1 < n \\<and> n < p \\<longrightarrow> \\<not> n dvd p\"\n    proof (intro strip notI)\n      fix n\n      assume H': \"1 < n \\<and> n < p\" \"n dvd p\"\n      then have \"1 \\<le> n \\<and> n < p\" by simp\n      with H have \"coprime n p\" by simp\n      with H' show False by (simp add: coprime_iff_gcd_eq_1)\n    qed\n  qed\n  then show ?thesis by (simp add: primeqtdef)\nqed\n\nwhy3_vc Gauss\nproof -\n  from assms\n  have \"coprime a b\" \"a dvd c * b\" by (simp_all add: mult.commute)\n  then show ?thesis by (simp add: coprime_dvd_mult_left_iff)\nqed\n\nwhy3_vc Euclid\n  using assms\n  by (simp add: prime_dvd_multD)\n\nwhy3_vc gcd_coprime\nproof -\n  have \"gcd a (b * c) = gcd (b * c) a\" by (simp add: gcd.commute)\n  also from assms have \"coprime a b\" by (simp add: gcd.commute coprime_iff_gcd_eq_1)\n  then have \"gcd (b * c) a = gcd c a\" by (simp add: gcd_mult_left_left_cancel)\n  finally show ?thesis by (simp add: gcd.commute)\nqed\n\nwhy3_end\n\nend\n", "meta": {"author": "Frederic-Boulanger-UPS", "repo": "docker-3asem", "sha": "e30e0134e5336e2da635c5f28731dce1a8fa207d", "save_path": "github-repos/isabelle/Frederic-Boulanger-UPS-docker-3asem", "path": "github-repos/isabelle/Frederic-Boulanger-UPS-docker-3asem/docker-3asem-e30e0134e5336e2da635c5f28731dce1a8fa207d/resources/why3/lib/isabelle/Why3_Number.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178994073576, "lm_q2_score": 0.8311430436757312, "lm_q1q2_score": 0.7551914464516806}}
{"text": "theory Exercise5p6\nimports Main \nbegin\n\nfun elems :: \"'a list \\<Rightarrow> 'a set\" where\n    \"elems [] = {}\"\n  | \"elems (x#xs) = {x} \\<union> elems xs\"\n\nvalue \"elems [1,2,3,3,2,4]\"\n\nlemma \"x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys\"  \nproof (induction xs)\n  case Nil\n  then show ?case by auto\nnext\n  case (Cons a xs)\n  then show ?case\n  proof cases\n    assume \"a = x\"\n    obtain ys where ys: \"(ys:: 'a list) = []\" by auto\n    obtain zs where zs: \"zs = xs\" by auto\n    then have \"x \\<notin> elems ys\" using `a = x` ys by auto\n    thus ?case using ys zs `a = x` by blast\n  next\n    (* \\<exists>ys zs. a # xs = ys @ x # zs \\<and> x \\<notin> elems ys *)\n    assume prems: \"x \\<in> elems (a # xs)\"\n    assume IH: \"(x \\<in> elems xs \\<Longrightarrow> \\<exists>ys zs. xs = ys @ x # zs \\<and> x \\<notin> elems ys)\"\n    assume \"a \\<noteq> x\"\n    then have \"x \\<in> elems xs\" using prems by auto\n    then obtain ys old_ys zs where \n      \"ys = a # old_ys\"\n      \"xs = old_ys @ x # zs\"\n      \"x \\<notin> elems old_ys\" \n      using IH by auto\n    then have \"a # xs = ys @ x # zs \\<and> x \\<notin> elems ys\" using `a \\<noteq> x` by auto\n    thus ?case by auto\n  qed\nqed   \n  \nend", "meta": {"author": "sseefried", "repo": "concrete-semantics-solutions", "sha": "ca562994bc36b2d9c9e6047bf481056e0be7bbcd", "save_path": "github-repos/isabelle/sseefried-concrete-semantics-solutions", "path": "github-repos/isabelle/sseefried-concrete-semantics-solutions/concrete-semantics-solutions-ca562994bc36b2d9c9e6047bf481056e0be7bbcd/Exercise5p6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.831143045767024, "lm_q1q2_score": 0.7551914462951792}}
{"text": "theory \"Denotational_Semantics\" \nimports\n  Ordinary_Differential_Equations.ODE_Analysis\n  \"./Lib\"\n  \"./Syntax\"\nbegin\nsubsection \\<open>Denotational Semantics\\<close>\ntext \\<open>\n  The canonical dynamic semantics of dL are given as a denotational semantics.\n  The important definitions for the denotational semantics are states $\\nu$,\n  interpretations I and the semantic functions $[[\\psi]]I$, $[[\\theta]]I\\nu$,\n  $[[\\alpha]]I$, which are represented by the Isabelle functions \\verb|fml_sem|,\n  \\verb|dterm_sem| and \\verb|prog_sem|, respectively.\n  \\<close>\nsubsection \\<open>States\\<close>\ntext \\<open>We formalize a state S as a pair $(S_V, S_V') : R^n \\times R^n $, where $S_V$ assigns\n  values to the program variables and $S_V$' assigns values to their\n  differentials. Function constants are also formalized as having a fixed arity\n  m \\verb|(Rvec_dim)| which may differ from n. If a function does not need to\n  have m arguments, any remaining arguments can be uniformly set to 0,\n  which simulates the affect of having functions of less arguments.\n  \n  Most semantic proofs need to reason about states agreeing on variables.\n  We say Vagree A B V if states A and B have the same values on all variables in V,\n  similarly with VSagree A B V for simple states A and B and Iagree I J V for interpretations\n  I and J.\n  \\<close>\n\n(* Vector of reals of length 'a *)\ntype_synonym Rvec = \"real^ident\"\n(* A state specifies one vector of values for unprimed variables x and a second vector for x'*)\ntype_synonym state = \"Rvec \\<times> Rvec\"\n(* 'a simple_state is half a state - either the xs or the x's *)\ntype_synonym simple_state = \"Rvec\"\n\ndefinition Vagree :: \"state \\<Rightarrow> state \\<Rightarrow> (ident + ident) set \\<Rightarrow> bool\"\nwhere \"Vagree \\<nu> \\<nu>' V \\<equiv>\n   (\\<forall>i. Inl i \\<in> V \\<longrightarrow> fst \\<nu> $ i = fst \\<nu>' $ i)\n \\<and> (\\<forall>i. Inr i \\<in> V \\<longrightarrow> snd \\<nu> $ i = snd \\<nu>' $ i)\"\n\ndefinition VSagree :: \"simple_state \\<Rightarrow> simple_state \\<Rightarrow> ident set \\<Rightarrow> bool\"\nwhere \"VSagree \\<nu> \\<nu>' V \\<longleftrightarrow> (\\<forall>i \\<in> V. (\\<nu> $ i) = (\\<nu>' $ i))\"\n\n(* Agreement lemmas *)\nlemma agree_nil:\"Vagree \\<nu> \\<omega> {}\"\n  by (auto simp add: Vagree_def)\n\nlemma agree_supset:\"A \\<supseteq> B \\<Longrightarrow> Vagree \\<nu> \\<nu>' A \\<Longrightarrow> Vagree \\<nu> \\<nu>' B\"\n  by (auto simp add: Vagree_def)\n\nlemma VSagree_nil:\"VSagree \\<nu> \\<omega> {}\"\n  by (auto simp add: VSagree_def)\n\nlemma VSagree_supset:\"A \\<supseteq> B \\<Longrightarrow> VSagree \\<nu> \\<nu>' A \\<Longrightarrow> VSagree \\<nu> \\<nu>' B\"\n  by (auto simp add: VSagree_def)\n\nlemma VSagree_UNIV_eq:\"VSagree A B UNIV \\<Longrightarrow> A = B\"\n  unfolding VSagree_def by (auto simp add: vec_eq_iff)\n\nlemma agree_comm:\"\\<And>A B V. Vagree A B V \\<Longrightarrow> Vagree B A V\" unfolding Vagree_def by auto\n\nlemma agree_eq:\"\\<And>A B V. A = B \\<Longrightarrow> Vagree A B V\" unfolding Vagree_def by auto\n\nlemma agree_sub:\"\\<And>\\<nu> \\<omega> A B . A \\<subseteq> B \\<Longrightarrow> Vagree \\<nu> \\<omega> B \\<Longrightarrow> Vagree \\<nu> \\<omega> A\"\n  unfolding Vagree_def by auto\n\nlemma agree_UNIV_eq:\"\\<And>\\<nu> \\<omega>. Vagree \\<nu> \\<omega> UNIV \\<Longrightarrow> \\<nu> = \\<omega>\"\n  unfolding Vagree_def by (auto simp add: vec_eq_iff)\n\nlemma agree_UNIV_fst:\"\\<And>\\<nu> \\<omega>. Vagree \\<nu> \\<omega> (Inl ` UNIV) \\<Longrightarrow> (fst \\<nu>) = (fst \\<omega>)\"\n  unfolding Vagree_def by (auto simp add: vec_eq_iff)\n\n\n\nlemma Vagree_univ:\"\\<And>a b c d. Vagree (a,b) (c,d) UNIV \\<Longrightarrow> a = c \\<and> b = d\"\n  by (auto simp add: Vagree_def vec_eq_iff)\n\nlemma agree_union:\"\\<And>\\<nu> \\<omega> A B. Vagree \\<nu> \\<omega> A \\<Longrightarrow> Vagree \\<nu> \\<omega> B \\<Longrightarrow> Vagree \\<nu> \\<omega> (A \\<union> B)\"\n  unfolding Vagree_def by (auto simp add: vec_eq_iff)\n\n\n\nlemma agree_refl:\"Vagree \\<nu> \\<nu> A\"\n  by (auto simp add: Vagree_def)\n\nlemma VSagree_sub:\"\\<And>\\<nu> \\<omega> A B . A \\<subseteq> B \\<Longrightarrow> VSagree \\<nu> \\<omega> B \\<Longrightarrow> VSagree \\<nu> \\<omega> A\"\n  unfolding VSagree_def by auto\n\nlemma VSagree_refl:\"VSagree \\<nu> \\<nu> A\"\n  by (auto simp add: VSagree_def)\n\nsubsection Interpretations\ntext\\<open>\n    For convenience we pretend interpretations contain an extra field called\n  FunctionFrechet specifying the Frechet derivative \\verb|(FunctionFrechet f \\<nu>)| : $R^m \\rightarrow R$ \n  for every function in every state. The proposition \\verb|(is_interp I)| says that such a\n  derivative actually exists and is continuous (i.e. all functions are C1-continuous)\n  without saying what the exact derivative is.\n  \n  The type parameters 'a, 'b, 'c are finite types whose cardinalities indicate the maximum number \n  of functions, contexts, and <everything else defined by the interpretation>, respectively.\n\\<close>\nrecord interp =\n  Functions       :: \"ident \\<Rightarrow> Rvec \\<Rightarrow> real\"\n  Funls           :: \"ident \\<Rightarrow> state \\<Rightarrow> real\"\n  Predicates      :: \"ident \\<Rightarrow> Rvec \\<Rightarrow> bool\"\n  Contexts        :: \"ident \\<Rightarrow> state set \\<Rightarrow> state set\"\n  Programs        :: \"ident \\<Rightarrow> (state * state) set\"\n  ODEs            :: \"ident \\<Rightarrow> space \\<Rightarrow> simple_state \\<Rightarrow> simple_state\"\n  ODEBV           :: \"ident \\<Rightarrow> space \\<Rightarrow> ident set\"\n\nfun FunctionFrechet :: \"interp \\<Rightarrow> ident \\<Rightarrow> Rvec \\<Rightarrow> Rvec \\<Rightarrow> real\"\n  where \"FunctionFrechet I i = (THE f'. \\<forall> x. (Functions I i has_derivative f' x) (at x))\"\n\n(* For an interpretation to be valid, all functions must be differentiable everywhere.*)\ndefinition is_interp :: \"interp \\<Rightarrow> bool\"\n  where \"is_interp I \\<equiv>\n   (\\<forall>x. \\<forall>i.  ((FDERIV (Functions I i) x :> (FunctionFrechet I i x)) \\<and> continuous_on UNIV (\\<lambda>x. Blinfun (FunctionFrechet I i x))))\n\\<and>  (\\<forall> ode. \\<forall> x. ODEBV I ode (NB x) \\<subseteq> -{x})\"\n\nlemma is_interpD:\"is_interp I \\<Longrightarrow> \\<forall>x. \\<forall>i. (FDERIV (Functions I i) x :> (FunctionFrechet I i x))\"\n  unfolding is_interp_def by auto\n  \n(* Agreement between interpretations. *)\ndefinition Iagree :: \"interp \\<Rightarrow> interp \\<Rightarrow> (ident + ident + ident) set \\<Rightarrow> bool\"\nwhere \"Iagree I J V \\<equiv>\n  (\\<forall>i\\<in>V.\n    (\\<forall>x. i = Inl x \\<longrightarrow> Functions I x = Functions J x) \\<and>\n\\<^cancel>\\<open>    (\\<forall>x. i = Inl x \\<longrightarrow> DFunls I x = DFunls J x) \\<and>\\<close>\n    (\\<forall>x. i = Inl x \\<longrightarrow> Funls I x = Funls J x) \\<and>\n    (\\<forall>x. i = Inr (Inl x) \\<longrightarrow> Contexts I x = Contexts J x) \\<and>\n    (\\<forall>x. i = Inr (Inr x) \\<longrightarrow> Predicates I x = Predicates J x) \\<and>\n    (\\<forall>x. i = Inr (Inr x) \\<longrightarrow> Programs I x = Programs J x) \\<and>\n    (\\<forall>x. i = Inr (Inr x) \\<longrightarrow> ODEs I x = ODEs J x) \\<and>\n    (\\<forall>x. i = Inr (Inr x) \\<longrightarrow> ODEBV I x = ODEBV J x))\"\n\nlemma Iagree_Func:\"Iagree I J V \\<Longrightarrow> Inl f \\<in> V \\<Longrightarrow> Functions I f = Functions J f\"\n  unfolding Iagree_def by auto\n\n(*lemma Iagree_DFunl:\"Iagree I J V \\<Longrightarrow> Inl f \\<in> V \\<Longrightarrow> DFunls I f = DFunls J f\"\n  unfolding Iagree_def by auto*)\n\nlemma Iagree_Funl:\"Iagree I J V \\<Longrightarrow> Inl f \\<in> V \\<Longrightarrow> Funls I f = Funls J f\"\n  unfolding Iagree_def by auto\n\nlemma Iagree_Contexts:\"Iagree I J V \\<Longrightarrow> Inr (Inl C) \\<in> V \\<Longrightarrow> Contexts I C = Contexts J C\"\n  unfolding Iagree_def by auto\n\nlemma Iagree_Pred:\"Iagree I J V \\<Longrightarrow> Inr (Inr p) \\<in> V \\<Longrightarrow> Predicates I p = Predicates J p\"\n  unfolding Iagree_def by auto\n\nlemma Iagree_Prog:\"Iagree I J V \\<Longrightarrow> Inr (Inr a) \\<in> V \\<Longrightarrow> Programs I a = Programs J a\"\n  unfolding Iagree_def by auto\n\nlemma Iagree_ODE:\"Iagree I J V \\<Longrightarrow> Inr (Inr a) \\<in> V \\<Longrightarrow> ODEs I a = ODEs J a\"\n  unfolding Iagree_def by auto  \n\nlemma Iagree_ODEBV:\"Iagree I J V \\<Longrightarrow> Inr (Inr a) \\<in> V \\<Longrightarrow> ODEBV I a = ODEBV J a\"\n  unfolding Iagree_def by auto  \n\nlemma Iagree_comm:\"\\<And>A B V. Iagree A B V \\<Longrightarrow> Iagree B A V\" \n  unfolding Iagree_def by auto\n\nlemma Iagree_sub:\"\\<And>I J A B . A \\<subseteq> B \\<Longrightarrow> Iagree I J B \\<Longrightarrow> Iagree I J A\"\n  unfolding Iagree_def by auto\n\nlemma Iagree_refl:\"Iagree I I A\"\n  by (auto simp add: Iagree_def)\n\n(* Semantics for differential-free terms. Because there are no differentials, depends only on the \"x\" variables\n * and not the \"x'\" variables. *)\nprimrec sterm_sem :: \"interp \\<Rightarrow> trm \\<Rightarrow> simple_state \\<Rightarrow> real\"\nwhere\n  ssem_Var:\"sterm_sem I (Var x) v = v $ x\"\n| ssem_Fun:\"sterm_sem I (Function f args) v = Functions I f (\\<chi> i. sterm_sem I (args i) v)\"\n| ssem_Neg:\"sterm_sem I (Neg t) v = - sterm_sem I t v\"\n| ssem_Plus:\"sterm_sem I (Plus t1 t2) v = sterm_sem I t1 v + sterm_sem I t2 v\"\n| ssem_Times:\"sterm_sem I (Times t1 t2) v = sterm_sem I t1 v * sterm_sem I t2 v\"\n| ssem_Const:\"sterm_sem I (Const b) v = sint (Rep_bword b)\"\n| ssem_DiffVar:\"sterm_sem I ($' c) v = undefined\"\n| ssem_Funl:\"sterm_sem I ($$F f) v = undefined\"\n| ssem_Diff:\"sterm_sem I (Differential d) v = undefined\"\n| ssem_Max:\"sterm_sem I (Max _ _ ) v = undefined\"\n| ssem_Min:\"sterm_sem I (Min _ _ ) v = undefined\"\n| ssem_Abs:\"sterm_sem I (Abs _) v = undefined\"\n| ssem_Div:\"sterm_sem I (Div t1 t2) v = undefined\"\n  \n(* frechet I \\<theta> \\<nu> syntactically computes the frechet derivative of the term \\<theta> in the interpretation\n * I at state \\<nu> (containing only the unprimed variables). The frechet derivative is a\n * linear map from the differential state \\<nu> to reals.\n *)\nprimrec frechet :: \"interp \\<Rightarrow> trm \\<Rightarrow> simple_state \\<Rightarrow> simple_state \\<Rightarrow> real\"\nwhere\n  Frechet_Var:\"frechet I (Var x) v = (\\<lambda>v'. v' \\<bullet> axis x 1)\"\n| Frechet_Fun:\"frechet I (Function f args) v =\n    (\\<lambda>v'. FunctionFrechet I f (\\<chi> i. sterm_sem I (args i) v) (\\<chi> i. frechet I (args i) v v'))\"\n| Frechet_Neg:\"frechet I (Neg t) v = (\\<lambda>v'. - frechet I t v v')\"\n| Frechet_Plus:\"frechet I (Plus t1 t2) v = (\\<lambda>v'. frechet I t1 v v' + frechet I t2 v v')\"\n| Frechet_Times:\"frechet I (Times t1 t2) v =\n    (\\<lambda>v'. sterm_sem I t1 v * frechet I t2 v v' + frechet I t1 v v' * sterm_sem I t2 v)\"\n| Frechet_Const:\"frechet I (Const r) v = (\\<lambda>v'. 0)\"\n(*| \"frechet I ($$F' f) v = DFunls I f v\"*)\n| Frechet_DiffVar:\"frechet I ($' c) v = undefined\"\n| Frechet_Diff:\"frechet I (Differential d) v = undefined\"\n| Frechet_Funl:\"frechet I ($$F f) v = undefined\"\n\nlemma Frechet_Zero[simp]: \"frechet I \\<^bold>0 v = (\\<lambda>_. 0)\"\n  by (simp add: Zero_def)\n\ndefinition directional_derivative :: \"interp \\<Rightarrow> trm \\<Rightarrow> state \\<Rightarrow> real\"\nwhere \"directional_derivative I t = (\\<lambda>v. frechet I t (fst v) (snd v))\"\n\n(* Sem for terms that are allowed to contain differentials.\n * Note there is some duplication with sterm_sem.*)\nprimrec dterm_sem :: \"interp \\<Rightarrow> trm \\<Rightarrow> state \\<Rightarrow> real\"\nwhere\n  \"dterm_sem I (Var x) = (\\<lambda>v. fst v $ x)\"\n| \"dterm_sem I (DiffVar x) = (\\<lambda>v. snd v $ x)\"\n| \"dterm_sem I (Function f args) = (\\<lambda>v. Functions I f (\\<chi> i. dterm_sem I (args i) v))\"\n| \"dterm_sem I (Neg t) = (\\<lambda>v. - (dterm_sem I t v) )\"\n| \"dterm_sem I (Plus t1 t2) = (\\<lambda>v. (dterm_sem I t1 v) + (dterm_sem I t2 v))\"\n| \"dterm_sem I (Times t1 t2) = (\\<lambda>v. (dterm_sem I t1 v) * (dterm_sem I t2 v))\"\n| \"dterm_sem I (Div t1 t2) = (\\<lambda>v. (dterm_sem I t1 v) / (dterm_sem I t2 v))\"\n| \"dterm_sem I (Differential t) = (\\<lambda>v. directional_derivative I t v)\"\n| \"dterm_sem I ($$F f) = (\\<lambda>v. Funls I f v)\"\n| \"dterm_sem I (Const b) = (\\<lambda>v. sint (Rep_bword b))\"\n| \"dterm_sem I (Max t1 t2) = (\\<lambda>v. max (dterm_sem I t1 v) (dterm_sem I t2 v))\"\n| \"dterm_sem I (Min t1 t2) = (\\<lambda>v. min (dterm_sem I t1 v) (dterm_sem I t2 v))\"\n| \"dterm_sem I (Abs t1) = (\\<lambda>v. abs (dterm_sem I t1 v))\"\n\ntext\\<open> The semantics of an ODE is the vector field at a given point. ODE's are all time-independent\n  so no time variable is necessary. Terms on the RHS of an ODE must be differential-free, so\n  depends only on the xs.\n\n  The safety predicate \\texttt{osafe} ensures the domains of ODE1 and ODE2 are disjoint, so vector addition\n  is equivalent to saying \"take things defined from ODE1 from ODE1, take things defined\n  by ODE2 from ODE2\"\\<close>\nfun ODE_sem:: \"interp \\<Rightarrow> ODE \\<Rightarrow> Rvec \\<Rightarrow> Rvec\"\n  where\n  ODE_sem_OVar:\"ODE_sem I (OVar x sp) = (\\<lambda>\\<nu>. (\\<chi> i. if i \\<in> ODEBV I x sp then ODEs I x sp  \\<nu> $ i else 0))\"\n| ODE_sem_OSing:\"ODE_sem I (OSing x \\<theta>) =  (\\<lambda>\\<nu>. (\\<chi> i. if i = x then sterm_sem I \\<theta> \\<nu> else 0))\"\n(* Note: Could define using SOME operator in a way that more closely matches above description,\n * but that gets complicated in the OVar case because not all variables are bound by the OVar *)\n| ODE_sem_OProd:\"ODE_sem I (OProd ODE1 ODE2) = (\\<lambda>\\<nu>. ODE_sem I ODE1 \\<nu> + ODE_sem I ODE2 \\<nu>)\"\n\nlemma ODE_sem_assoc:\"ODE_sem I (oprod ODE1 ODE2) = ODE_sem I (OProd ODE1 ODE2)\"\n  apply(induction ODE1 arbitrary:ODE2)\n  by(auto)\n\n(* The bound variables of an ODE *)\nfun ODE_vars :: \"interp \\<Rightarrow> ODE \\<Rightarrow> ident set\"\n  where \n  \"ODE_vars I (OVar c sp) = ODEBV I c sp\"\n| \"ODE_vars I (OSing x \\<theta>) = {x}\"\n| \"ODE_vars I (OProd ODE1 ODE2) = ODE_vars I ODE1 \\<union> ODE_vars I ODE2\"\n\nlemma ODE_vars_assoc:\"ODE_vars I (oprod ODE1 ODE2) = ODE_vars I (OProd ODE1 ODE2)\"\n  apply(induction ODE1 arbitrary:ODE2)\n  by(auto)\n\nfun semBV ::\"interp \\<Rightarrow> ODE \\<Rightarrow> (ident + ident) set\"\n  where \"semBV I ODE = Inl ` (ODE_vars I ODE) \\<union> Inr ` (ODE_vars I ODE)\"\n\nlemma ODE_vars_lr:\n  fixes x::\"ident\" and ODE::\"ODE\" and I::\"interp\"\n  shows \"Inl x \\<in> semBV I ODE \\<longleftrightarrow> Inr x \\<in> semBV I ODE\"\n  by (induction \"ODE\", auto)\n\nfun mk_xode::\"interp \\<Rightarrow> ODE \\<Rightarrow>  simple_state \\<Rightarrow> state\"\nwhere \"mk_xode I ODE sol = (sol, ODE_sem I ODE sol)\"\n \ntext\\<open> Given an initial state $\\nu$ and solution to an ODE at some point, construct the resulting state $\\omega$.\n  This is defined using the SOME operator because the concrete definition is unwieldy. \\<close>\ndefinition mk_v::\"interp \\<Rightarrow> ODE \\<Rightarrow> state \\<Rightarrow> simple_state \\<Rightarrow> state\"\nwhere \"mk_v I ODE \\<nu> sol = (THE \\<omega>. \n  Vagree \\<omega> \\<nu> (- semBV I ODE) \n\\<and> Vagree \\<omega> (mk_xode I ODE sol) (semBV I ODE))\"\n\n(* repv \\<nu> x r replaces the value of (unprimed) variable x in the state \\<nu> with r *)\nfun repv :: \"state \\<Rightarrow> ident \\<Rightarrow> real \\<Rightarrow> state\"\nwhere \"repv v x r = ((\\<chi> y. if x = y then r else vec_nth (fst v) y), snd v)\"\n\n(* repd \\<nu> x' r replaces the value of (primed) variable x' in the state \\<nu> with r *)\nfun repd :: \"state \\<Rightarrow> ident \\<Rightarrow> real \\<Rightarrow> state\"\nwhere \"repd v x r = (fst v, (\\<chi> y. if x = y then r else vec_nth (snd v) y))\"  \n  \n(* Semantics for formulas, differential formulas, programs. *)\nfun fml_sem  :: \"interp \\<Rightarrow> formula \\<Rightarrow> state set\" and\n  prog_sem :: \"interp \\<Rightarrow>  hp \\<Rightarrow> (state * state) set\"\nwhere\n  \"fml_sem I (Geq t1 t2) = {v. dterm_sem I t1 v \\<ge> dterm_sem I t2 v}\"\n| \"fml_sem I (Prop P terms) = {\\<nu>. Predicates I P (\\<chi> i. dterm_sem I (terms i) \\<nu>)}\"\n| \"fml_sem I (Not \\<phi>) = {v. v \\<notin> fml_sem I \\<phi>}\"\n| \"fml_sem I (And \\<phi> \\<psi>) = fml_sem I \\<phi> \\<inter> fml_sem I \\<psi>\"\n| \"fml_sem I (Exists x \\<phi>) = {v | v r. (repv v x r) \\<in> fml_sem I \\<phi>}\"\n| \"fml_sem I (Diamond \\<alpha> \\<phi>) = {\\<nu> | \\<nu> \\<omega>. (\\<nu>, \\<omega>) \\<in> prog_sem I \\<alpha> \\<and> \\<omega> \\<in> fml_sem I \\<phi>}\"\n| \"fml_sem I (InContext c \\<phi>) = Contexts I c (fml_sem I \\<phi>)\"\n\n| \"prog_sem I (Pvar p) = Programs I p\"\n| \"prog_sem I (Assign x t) = {(\\<nu>, \\<omega>). \\<omega> = repv \\<nu> x (dterm_sem I t \\<nu>)}\"\n| \"prog_sem I (AssignAny x) = {(\\<nu>, \\<omega>) | \\<omega> \\<nu> r. \\<omega> = repv \\<nu> x r}\"\n| \"prog_sem I (DiffAssign x t) = {(\\<nu>, \\<omega>). \\<omega> = repd \\<nu> x (dterm_sem I t \\<nu>)}\"\n| \"prog_sem I (Test \\<phi>) = {(\\<nu>, \\<nu>) | \\<nu>. \\<nu> \\<in> fml_sem I \\<phi>}\"\n| \"prog_sem I (Choice \\<alpha> \\<beta>) = prog_sem I \\<alpha> \\<union> prog_sem I \\<beta>\"\n| \"prog_sem I (Sequence \\<alpha> \\<beta>) = prog_sem I \\<alpha> O prog_sem I \\<beta>\"\n| \"prog_sem I (Loop \\<alpha>) = (prog_sem I \\<alpha>)\\<^sup>*\"\n| \"prog_sem I (EvolveODE ODE \\<phi>) =\n  ({(\\<nu>, mk_v I ODE \\<nu> (sol t)) | \\<nu> sol t.\n      t \\<ge> 0 \\<and>\n      (sol solves_ode (\\<lambda>_. ODE_sem I ODE)) {0..t} {x. mk_v I ODE \\<nu> x \\<in> fml_sem I \\<phi>} \\<and>\n      sol 0 = fst \\<nu>})\"\n\ndefinition valid :: \"formula \\<Rightarrow> bool\"\nwhere \"valid \\<phi> \\<equiv> (\\<forall> I. \\<forall> \\<nu>. is_interp I \\<longrightarrow> \\<nu> \\<in> fml_sem I \\<phi>)\"\n\ntext\\<open> Because mk\\_v is defined with the SOME operator, need to construct a state that satisfies\n    ${\\tt Vagree} \\omega \\nu (- {\\tt ODE\\_vars\\ ODE}) \n     \\wedge {\\tt Vagree} \\omega {\\tt (mk\\_xode\\ I\\ ODE\\ sol)\\ (ODE\\_vars\\ ODE)})$\n    to do anything useful \\<close>\nfun concrete_v::\"interp \\<Rightarrow> ODE \\<Rightarrow> state \\<Rightarrow> simple_state \\<Rightarrow> state\"\nwhere \"concrete_v I ODE \\<nu> sol =\n((\\<chi> i. (if Inl i \\<in> semBV I ODE then sol else (fst \\<nu>)) $ i),\n (\\<chi> i. (if Inr i \\<in> semBV I ODE then ODE_sem I ODE sol else (snd \\<nu>)) $ i))\"\n\nlemma mk_v_exists:\"\\<exists>\\<omega>. Vagree \\<omega> \\<nu> (- semBV I ODE) \n\\<and> Vagree \\<omega> (mk_xode I ODE sol) (semBV I ODE)\"\n  by(rule exI[where x=\"(concrete_v I ODE \\<nu> sol)\"], auto simp add: Vagree_def)\n    \nlemma mk_v_agree:\"Vagree (mk_v I ODE \\<nu> sol) \\<nu> (- semBV I ODE) \n\\<and> Vagree (mk_v I ODE \\<nu> sol) (mk_xode I ODE sol) (semBV I ODE)\"\n  unfolding mk_v_def \n  apply(rule theI[where a= \"((\\<chi> i. (if Inl i \\<in> semBV I ODE then sol else (fst \\<nu>)) $ i),\n  (\\<chi> i. (if Inr i \\<in> semBV I ODE then ODE_sem I ODE sol else (snd \\<nu>)) $ i))\"])\n   using exE[OF mk_v_exists, of \\<nu> I ODE sol]\n   by (auto simp add: Vagree_def vec_eq_iff)\n\nlemma mk_v_concrete:\"mk_v I ODE \\<nu> sol = ((\\<chi> i. (if Inl i \\<in> semBV I ODE then sol else (fst \\<nu>)) $ i),\n  (\\<chi> i. (if Inr i \\<in> semBV I ODE then ODE_sem I ODE sol else (snd \\<nu>)) $ i))\"\n  apply(rule agree_UNIV_eq)\n  using mk_v_agree[of I ODE \\<nu> sol]\n  unfolding Vagree_def by auto\n\nsubsection \\<open>Trivial Simplification Lemmas\\<close>\ntext \\<open>\n We often want to pretend the definitions in the semantics are written slightly\n differently than they are. Since the simplifier has some trouble guessing that\n these are the right simplifications to do, we write them all out explicitly as\n lemmas, even though they prove trivially.\n\\<close>\n\nlemma svar_case:\n  \"sterm_sem I (Var x) = (\\<lambda>v. v $ x)\"\n  by auto\n\nlemma sconst_case:\n  \"sterm_sem I (Const b) = (\\<lambda>v. sint (Rep_bword b))\"\n  by auto\n\nlemma sfunction_case:\n  \"sterm_sem I (Function f args) = (\\<lambda>v. Functions I f (\\<chi> i. sterm_sem I (args i) v))\"\n  by auto\n\nlemma splus_case:\n  \"sterm_sem I (Plus t1 t2) = (\\<lambda>v. (sterm_sem I t1 v) + (sterm_sem I t2 v))\"\n  by auto\n\nlemma stimes_case:\n  \"sterm_sem I (Times t1 t2) = (\\<lambda>v. (sterm_sem I t1 v) * (sterm_sem I t2 v))\"\n  by auto  \n\nlemma or_sem [simp]:\n  \"fml_sem I (Or \\<phi> \\<psi>) = fml_sem I \\<phi> \\<union> fml_sem I \\<psi>\"\n  by (auto simp add: Or_def)\n\nlemma iff_sem [simp]: \"(\\<nu> \\<in> fml_sem I (A \\<leftrightarrow> B))\n  \\<longleftrightarrow> ((\\<nu> \\<in> fml_sem I A) \\<longleftrightarrow> (\\<nu> \\<in> fml_sem I B))\"\n  by (auto simp add: Equiv_def)\n\nlemma box_sem [simp]:\"fml_sem I (Box \\<alpha> \\<phi>) = {\\<nu>. \\<forall> \\<omega>. (\\<nu>, \\<omega>) \\<in> prog_sem I \\<alpha> \\<longrightarrow> \\<omega> \\<in> fml_sem I \\<phi>}\"\n  unfolding Box_def fml_sem.simps\n  using Collect_cong by (auto)\n  \nlemma forall_sem [simp]:\"fml_sem I (Forall x \\<phi>) = {v. \\<forall>r. (repv v x r) \\<in> fml_sem I \\<phi>}\"\n  unfolding Forall_def fml_sem.simps\n  using Collect_cong by (auto)\n\nlemma greater_sem[simp]:\"fml_sem I (Greater \\<theta> \\<theta>') = {v. dterm_sem I \\<theta> v > dterm_sem I \\<theta>' v}\"\n  unfolding Greater_def by auto\n\nlemma sterm_sem_zero[simp]: \"sterm_sem I \\<^bold>0 \\<nu> = 0\"\n  by (auto simp: Zero_def bword_zero.rep_eq)\n\nlemma dterm_sem_zero[simp]: \"dterm_sem I \\<^bold>0 = (\\<lambda>_. 0)\"\n  by (auto simp: Zero_def bword_zero.rep_eq)\n\nlemma sterm_sem_one[simp]: \"sterm_sem I \\<^bold>1 \\<nu> = 1\"\n  by (auto simp: One_def bword_one.rep_eq)\n\nlemma dterm_sem_one[simp]: \"dterm_sem I \\<^bold>1 = (\\<lambda>_. 1)\"\n  by (auto simp: One_def bword_one.rep_eq)\n\nlemma loop_sem:\"prog_sem I (Loop \\<alpha>) = (prog_sem I \\<alpha>)\\<^sup>*\"\n  by (auto)\n\nlemma impl_sem [simp]: \"(\\<nu> \\<in> fml_sem I (A \\<rightarrow> B))\n  = ((\\<nu> \\<in> fml_sem I A) \\<longrightarrow> (\\<nu> \\<in> fml_sem I B))\"\n  by (auto simp add: Implies_def)\n\nlemma equals_sem [simp]: \"(\\<nu> \\<in> fml_sem I (Equals \\<theta> \\<theta>'))\n  = (dterm_sem I \\<theta> \\<nu> = dterm_sem I \\<theta>' \\<nu>)\"\n  by (auto simp add: Equals_def)\n\nlemma diamond_sem [simp]: \"fml_sem I (Diamond \\<alpha> \\<phi>)\n  = {\\<nu>. \\<exists> \\<omega>. (\\<nu>, \\<omega>) \\<in> prog_sem I \\<alpha> \\<and> \\<omega> \\<in> fml_sem I \\<phi>}\"\n  by auto\n\nlemma tt_sem [simp]:\"fml_sem I TT = UNIV\" unfolding TT_def by auto\nlemma ff_sem [simp]:\"fml_sem I FF = {}\" \n  using Abs_bword_inverse[of 0] Abs_bword_inverse[of 1]  \n  unfolding FF_def POS_INF_def NEG_INF_def bword_zero_def bword_one_def by (auto)\n\nlemma iff_to_impl: \"((\\<nu> \\<in> fml_sem I A) \\<longleftrightarrow> (\\<nu> \\<in> fml_sem I B))\n  \\<longleftrightarrow> (((\\<nu> \\<in> fml_sem I A) \\<longrightarrow> (\\<nu> \\<in> fml_sem I B))\n     \\<and> ((\\<nu> \\<in> fml_sem I B) \\<longrightarrow> (\\<nu> \\<in> fml_sem I A)))\"\n  by (auto) \n    \n    fun seq2fml :: \"sequent \\<Rightarrow> formula\"\nwhere\n  \"seq2fml (ante,succ) = Implies (foldr And ante TT) (foldr Or succ FF)\"\n  \nfun seq_sem ::\"interp \\<Rightarrow> sequent \\<Rightarrow> state set\"\nwhere \"seq_sem I S = fml_sem I (seq2fml S)\"\n\nlemma and_foldl_sem:\"\\<nu> \\<in> fml_sem I (foldr And \\<Gamma> TT) \\<Longrightarrow> (\\<And>\\<phi>. List.member \\<Gamma> \\<phi> \\<Longrightarrow> \\<nu> \\<in> fml_sem I \\<phi>)\"\n  by(induction \\<Gamma>, auto simp add: member_rec)\n\nlemma and_foldl_sem_conv:\"(\\<And>\\<phi>. List.member \\<Gamma> \\<phi> \\<Longrightarrow> \\<nu> \\<in> fml_sem I \\<phi>) \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr And \\<Gamma> TT)\"\n  by(induction \\<Gamma>, auto simp add: member_rec)\n\nlemma or_foldl_sem:\"List.member \\<Gamma> \\<phi> \\<Longrightarrow> \\<nu> \\<in> fml_sem I \\<phi> \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr Or \\<Gamma> FF)\"\n  by(induction \\<Gamma>, auto simp add: member_rec)\n\nlemma or_foldl_sem_conv:\"\\<nu> \\<in> fml_sem I (foldr Or \\<Gamma> FF) \\<Longrightarrow> \\<exists> \\<phi>. \\<nu> \\<in> fml_sem I \\<phi> \\<and> List.member \\<Gamma> \\<phi>\"\n  by(induction \\<Gamma>, auto simp add: member_rec)\n\n\n\nlemma seq_sem_UNIV_I:\"(\\<And>\\<nu>. \\<nu> \\<in> fml_sem I (foldr And \\<Gamma> TT) \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr Or \\<Delta> FF)) \\<Longrightarrow> seq_sem I (\\<Gamma>,\\<Delta>) = UNIV\"\n  by auto \n\nlemma seq_semD':\"\\<And>P. \\<nu> \\<in> seq_sem I (\\<Gamma>,\\<Delta>) \\<Longrightarrow> ((\\<nu> \\<in> fml_sem I (foldr And \\<Gamma> TT) \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr Or \\<Delta> FF)) \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  by simp\n\ndefinition sublist::\"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\"\nwhere \"sublist A B \\<equiv> (\\<forall>x. List.member A x \\<longrightarrow> List.member B x)\"\n\nlemma sublistI:\"(\\<And>x. List.member A x \\<Longrightarrow> List.member B x) \\<Longrightarrow> sublist A B\"\n  unfolding sublist_def by auto\n\nlemma \\<Gamma>_sub_sem:\"sublist \\<Gamma>1 \\<Gamma>2 \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr And \\<Gamma>2 TT) \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr And \\<Gamma>1 TT)\"\n  unfolding sublist_def \n  by (metis and_foldl_sem and_foldl_sem_conv)\n\nlemma seq_semI:\"List.member \\<Delta> \\<psi> \\<Longrightarrow>((\\<And>\\<phi>. List.member \\<Gamma> \\<phi> \\<Longrightarrow> \\<nu> \\<in> fml_sem I \\<phi>) \\<Longrightarrow> \\<nu> \\<in> fml_sem I \\<psi>) \\<Longrightarrow> \\<nu> \\<in> seq_sem I (\\<Gamma>,\\<Delta>)\"\n  apply(rule seq_semI')\n  using and_foldl_sem[of \\<nu> I \\<Gamma>] or_foldl_sem by blast\n\nlemma seq_semD:\"\\<nu> \\<in> seq_sem I (\\<Gamma>,\\<Delta>) \\<Longrightarrow> (\\<And>\\<phi>. List.member \\<Gamma> \\<phi> \\<Longrightarrow> \\<nu> \\<in> fml_sem I \\<phi>) \\<Longrightarrow> \\<exists>\\<phi>. (List.member \\<Delta> \\<phi>) \\<and>\\<nu> \\<in> fml_sem I \\<phi> \"\n  apply(rule seq_semD')\n  using and_foldl_sem_conv or_foldl_sem_conv\n  by blast+\n\nlemma seq_MP:\"\\<nu> \\<in> seq_sem I (\\<Gamma>,\\<Delta>) \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr And \\<Gamma> TT) \\<Longrightarrow> \\<nu> \\<in> fml_sem I (foldr Or \\<Delta> FF)\"\n  by(induction \\<Delta>, auto)\n\ndefinition seq_valid\nwhere \"seq_valid S \\<equiv> \\<forall>I. is_interp I \\<longrightarrow> seq_sem I S = UNIV\"  \n\n\ntext\\<open> Soundness for derived rules is local soundness, i.e. if the premisses are all true in the same interpretation,\n  then the conclusion is also true in that same interpretation. \\<close>\ndefinition sound :: \"rule \\<Rightarrow> bool\"\nwhere \"sound R \\<longleftrightarrow> (\\<forall>I. is_interp I \\<longrightarrow> (\\<forall>i. i \\<ge> 0 \\<longrightarrow> i < length (fst R) \\<longrightarrow> seq_sem I (nth (fst R) i) = UNIV) \\<longrightarrow> seq_sem I (snd R) = UNIV)\"\n\nlemma soundI:\"(\\<And>I. is_interp I \\<Longrightarrow> (\\<And>i. i \\<ge> 0 \\<Longrightarrow> i < length SG \\<Longrightarrow> seq_sem I (nth SG i) = UNIV) \\<Longrightarrow> seq_sem I G = UNIV) \\<Longrightarrow> sound (SG,G)\"\n  unfolding sound_def by auto\n\nlemma soundI':\"(\\<And>I \\<nu>. is_interp I \\<Longrightarrow> (\\<And>i . i \\<ge> 0 \\<Longrightarrow> i < length SG \\<Longrightarrow> \\<nu> \\<in> seq_sem I (nth SG i)) \\<Longrightarrow> \\<nu> \\<in> seq_sem I G) \\<Longrightarrow> sound (SG,G)\"\n  unfolding sound_def by auto\n    \nlemma soundI_mem:\"(\\<And>I. is_interp I \\<Longrightarrow> (\\<And>\\<phi>. List.member SG \\<phi> \\<Longrightarrow> seq_sem I \\<phi> = UNIV) \\<Longrightarrow> seq_sem I C = UNIV) \\<Longrightarrow> sound (SG,C)\"\n  apply (auto simp add: sound_def)\n  by (metis in_set_conv_nth in_set_member iso_tuple_UNIV_I seq2fml.simps)\n\nlemma soundI_memv:\"(\\<And>I. is_interp I \\<Longrightarrow> (\\<And>\\<phi> \\<nu>. List.member SG \\<phi> \\<Longrightarrow> \\<nu> \\<in> seq_sem I \\<phi>) \\<Longrightarrow> (\\<And>\\<nu>. \\<nu> \\<in> seq_sem I C)) \\<Longrightarrow> sound (SG,C)\"\n  apply(rule soundI_mem)\n  using impl_sem by blast\n\nlemma soundI_memv':\"(\\<And>I. is_interp I \\<Longrightarrow> (\\<And>\\<phi> \\<nu>. List.member SG \\<phi> \\<Longrightarrow> \\<nu> \\<in> seq_sem I \\<phi>) \\<Longrightarrow> (\\<And>\\<nu>. \\<nu> \\<in> seq_sem I C)) \\<Longrightarrow> R = (SG,C) \\<Longrightarrow> sound R\"\n  using  soundI_mem\n  using impl_sem by blast\n\nlemma soundD_mem:\"sound (SG,C) \\<Longrightarrow> (\\<And>I. is_interp I \\<Longrightarrow> (\\<And>\\<phi>. List.member SG \\<phi> \\<Longrightarrow> seq_sem I \\<phi> = UNIV) \\<Longrightarrow> seq_sem I C = UNIV)\"\n  apply (auto simp add: sound_def)\n  using in_set_conv_nth in_set_member iso_tuple_UNIV_I seq2fml.simps\n  by (metis seq2fml.elims)\n\nlemma soundD_memv:\"sound (SG,C) \\<Longrightarrow> (\\<And>I. is_interp I \\<Longrightarrow> (\\<And>\\<phi> \\<nu>. List.member SG \\<phi> \\<Longrightarrow> \\<nu> \\<in> seq_sem I \\<phi>) \\<Longrightarrow> (\\<And>\\<nu>. \\<nu> \\<in> seq_sem I C))\"\n  using soundD_mem\n  by (metis UNIV_I UNIV_eq_I)\n\nend", "meta": {"author": "LS-Lab", "repo": "Isabelle-dL", "sha": "97770ed9ca8d6a633c59d11d799247f44cc62dc2", "save_path": "github-repos/isabelle/LS-Lab-Isabelle-dL", "path": "github-repos/isabelle/LS-Lab-Isabelle-dL/Isabelle-dL-97770ed9ca8d6a633c59d11d799247f44cc62dc2/Denotational_Semantics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086178895092415, "lm_q2_score": 0.8311430478583168, "lm_q1q2_score": 0.7551914420253023}}
{"text": "chapter \\<open>Log Upper and Lower Bounds\\<close>\n\ntheory Log_CF_Bounds\nimports Bounds_Lemmas\n\nbegin\n\ntheorem ln_upper_1: \"0<x \\<Longrightarrow> ln(x::real) \\<le> x - 1\"\nby (rule ln_le_minus_one)\n\ndefinition ln_lower_1 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_1 \\<equiv> \\<lambda>x. 1 - (inverse x)\"\n\ncorollary ln_lower_1: \"0<x \\<Longrightarrow> ln_lower_1 x \\<le> ln x\"\n  unfolding ln_lower_1_def\n  by (metis ln_inverse ln_le_minus_one positive_imp_inverse_positive minus_diff_eq minus_le_iff)\n\ntheorem ln_lower_1_eq: \"0<x \\<Longrightarrow> ln_lower_1 x = (x - 1)/x\"\n  by (auto simp: ln_lower_1_def divide_simps)\n\nsection \\<open>Upper Bound 3\\<close>\n\ndefinition ln_upper_3 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_3 \\<equiv> \\<lambda>x. (x + 5)*(x - 1) / (2*(2*x + 1))\"\n\ndefinition diff_delta_ln_upper_3 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_3 \\<equiv> \\<lambda>x. (x - 1)^3 / ((2*x + 1)^2 * x)\"\n\nlemma d_delta_ln_upper_3: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_3 x - ln x) has_field_derivative diff_delta_ln_upper_3 x) (at x)\"\nunfolding ln_upper_3_def diff_delta_ln_upper_3_def\napply (intro derivative_eq_intros | simp)+\napply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\ndone\n\ntext\\<open>Strict inequalities also possible\\<close>\nlemma ln_upper_3_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_3 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_3])\napply (auto simp: diff_delta_ln_upper_3_def ln_upper_3_def)\ndone\n\nlemma ln_upper_3_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_3 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_3])\nusing assms\napply (auto simp: diff_delta_ln_upper_3_def divide_simps ln_upper_3_def)\ndone\n\ntheorem ln_upper_3: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_3 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_3_neg ln_upper_3_pos)\n\ndefinition ln_lower_3 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_3 \\<equiv> \\<lambda>x. - ln_upper_3 (inverse x)\"\n\ncorollary ln_lower_3: \"0<x \\<Longrightarrow> ln_lower_3 x \\<le> ln x\"\n  unfolding ln_lower_3_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_3)\n\ntheorem ln_lower_3_eq: \"0<x \\<Longrightarrow> ln_lower_3 x = (1/2)*(1 + 5*x)*(x - 1) / (x*(2 + x))\"\n  unfolding ln_lower_3_def ln_upper_3_def\n  by (simp add: divide_simps) algebra\n\n\nsection \\<open>Upper Bound 5\\<close>\n\ndefinition ln_upper_5 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_5 x \\<equiv> (x^2 + 19*x + 10)*(x - 1) / (3*(3*x^2 + 6*x + 1))\"\n\ndefinition diff_delta_ln_upper_5 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_5 \\<equiv> \\<lambda>x. (x - 1)^5 / ((3*x^2 + 6*x + 1)^2*x)\"\n\nlemma d_delta_ln_upper_5: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_5 x - ln x) has_field_derivative diff_delta_ln_upper_5 x) (at x)\"\n  unfolding ln_upper_5_def diff_delta_ln_upper_5_def\n  apply (intro derivative_eq_intros | simp add: add_nonneg_eq_0_iff)+\n  apply (simp add: divide_simps add_nonneg_eq_0_iff, algebra)\n  done\n\nlemma ln_upper_5_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_5 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_5])\napply (auto simp: diff_delta_ln_upper_5_def ln_upper_5_def)\ndone\n\nlemma ln_upper_5_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_5 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_5])\nusing assms\napply (auto simp: diff_delta_ln_upper_5_def divide_simps ln_upper_5_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_5: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_5 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_5_neg ln_upper_5_pos)\n\ndefinition ln_lower_5 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_5 \\<equiv> \\<lambda>x. - ln_upper_5 (inverse x)\"\n\ncorollary ln_lower_5: \"0<x \\<Longrightarrow> ln_lower_5 x \\<le> ln x\"\n  unfolding ln_lower_5_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_5)\n\ntheorem ln_lower_5_eq: \"0<x \\<Longrightarrow>\n    ln_lower_5 x = (1/3)*(10*x^2 + 19*x + 1)*(x - 1) / (x*(x^2 + 6*x + 3))\"\n  unfolding ln_lower_5_def ln_upper_5_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection \\<open>Upper Bound 7\\<close>\n\ndefinition ln_upper_7 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_7 x \\<equiv> (3*x^3 + 131*x^2 + 239*x + 47)*(x - 1) / (12*(4*x^3 + 18*x^2 + 12*x + 1))\"\n\ndefinition diff_delta_ln_upper_7 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_7 \\<equiv> \\<lambda>x. (x - 1)^7 / ((4*x^3 + 18*x^2 + 12*x + 1)^2 * x)\"\n\nlemma d_delta_ln_upper_7: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_7 x - ln x) has_field_derivative diff_delta_ln_upper_7 x) (at x)\"\nunfolding ln_upper_7_def diff_delta_ln_upper_7_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_7_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_7 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_7])\napply (auto simp: diff_delta_ln_upper_7_def ln_upper_7_def)\ndone\n\nlemma ln_upper_7_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_7 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_7])\nusing assms\napply (auto simp: diff_delta_ln_upper_7_def divide_simps ln_upper_7_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_7: \"0 < x \\<Longrightarrow> ln(x) \\<le> ln_upper_7 x\"\n  by (metis le_less_linear less_eq_real_def ln_upper_7_neg ln_upper_7_pos)\n\ndefinition ln_lower_7 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_7 \\<equiv> \\<lambda>x. - ln_upper_7 (inverse x)\"\n\ncorollary ln_lower_7: \"0 < x \\<Longrightarrow> ln_lower_7 x \\<le> ln x\"\n  unfolding ln_lower_7_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_7)\n\ntheorem ln_lower_7_eq: \"0 < x \\<Longrightarrow>\n  ln_lower_7 x = (1/12)*(47*x^3 + 239*x^2 + 131*x + 3)*(x - 1) / (x*(x^3 + 12*x^2 + 18*x + 4))\"\n  unfolding ln_lower_7_def ln_upper_7_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection \\<open>Upper Bound 9\\<close>\n\ndefinition ln_upper_9 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_9 x \\<equiv> (6*x^4 + 481*x^3 + 1881*x^2 + 1281*x + 131)*(x - 1) /\n                         (30 * (5*x^4 + 40*x^3 + 60*x^2 + 20*x + 1))\"\n\ndefinition diff_delta_ln_upper_9 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_9 \\<equiv> \\<lambda>x. (x - 1)^9 / (((5*x^4 + 40*x^3 + 60*x^2 + 20*x + 1)^2) * x)\"\n\nlemma d_delta_ln_upper_9: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_9 x - ln x) has_field_derivative diff_delta_ln_upper_9 x) (at x)\"\nunfolding ln_upper_9_def diff_delta_ln_upper_9_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_9_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_9 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_9])\napply (auto simp: diff_delta_ln_upper_9_def ln_upper_9_def)\ndone\n\nlemma ln_upper_9_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_9 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_9])\nusing assms\napply (auto simp: diff_delta_ln_upper_9_def divide_simps ln_upper_9_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_9: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_9 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_9_neg ln_upper_9_pos)\n\n\ndefinition ln_lower_9 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_9 \\<equiv> \\<lambda>x. - ln_upper_9 (inverse x)\"\n\ncorollary ln_lower_9: \"0 < x \\<Longrightarrow> ln_lower_9 x \\<le> ln x\"\n  unfolding ln_lower_9_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_9)\n\ntheorem ln_lower_9_eq: \"0 < x \\<Longrightarrow>\n      ln_lower_9 x = (1/30)*(6 + 481*x + 1881*x^2 + 1281*x^3 + 131*x^4)*(x - 1) /\n                     (x*(5 + 40*x + 60*x^2 + 20*x^3 + x^4))\"\n  unfolding ln_lower_9_def ln_upper_9_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection \\<open>Upper Bound 11\\<close>\n\ntext\\<open>Extended bounds start here\\<close>\n\ndefinition ln_upper_11 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_11 x \\<equiv>\n           (5*x^5 + 647*x^4 + 4397*x^3 + 6397*x^2 + 2272*x + 142) * (x - 1) /\n           (30*(6*x^5 + 75*x^4 + 200*x^3 + 150*x^2 + 30*x + 1))\"\n\ndefinition diff_delta_ln_upper_11 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_11 \\<equiv> \\<lambda>x. (x - 1)^11 / ((6*x^5 + 75*x^4 + 200*x^3 + 150*x^2 + 30*x + 1)^2 * x)\"\n\nlemma d_delta_ln_upper_11: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_11 x - ln x) has_field_derivative diff_delta_ln_upper_11 x) (at x)\"\nunfolding ln_upper_11_def diff_delta_ln_upper_11_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_11_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_11 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_11])\napply (auto simp: diff_delta_ln_upper_11_def ln_upper_11_def)\ndone\n\nlemma ln_upper_11_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_11 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_11])\nusing assms\napply (auto simp: diff_delta_ln_upper_11_def divide_simps ln_upper_11_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_11: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_11 x\"\nby (metis le_less_linear less_eq_real_def ln_upper_11_neg ln_upper_11_pos)\n\ndefinition ln_lower_11 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_11 \\<equiv> \\<lambda>x. - ln_upper_11 (inverse x)\"\n\ncorollary ln_lower_11: \"0<x \\<Longrightarrow> ln_lower_11 x \\<le> ln x\"\n  unfolding ln_lower_11_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_11)\n\ntheorem ln_lower_11_eq: \"0<x \\<Longrightarrow>\n    ln_lower_11 x = (1/30)*(142*x^5 + 2272*x^4 + 6397*x^3 + 4397*x^2 + 647*x + 5)*(x - 1) /\n                    (x*(x^5 + 30*x^4 + 150*x^3 + 200*x^2 + 75*x + 6))\"\n  unfolding ln_lower_11_def ln_upper_11_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection \\<open>Upper Bound 13\\<close>\n\ndefinition ln_upper_13 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_13 x \\<equiv> (353 + 8389*x + 20149*x^4 + 50774*x^3 + 38524*x^2 + 1921*x^5 + 10*x^6) * (x - 1)\n                          / (70*(1 + 42*x + 525*x^4 + 700*x^3 + 315*x^2 + 126*x^5 + 7*x^6))\"\n\ndefinition diff_delta_ln_upper_13 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_13 \\<equiv> \\<lambda>x. (x - 1)^13 /\n                     ((1 + 42*x + 525*x^4 + 700*x^3 + 315*x^2 + 126*x^5 + 7*x^6)^2*x)\"\n\nlemma d_delta_ln_upper_13: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_13 x - ln x) has_field_derivative diff_delta_ln_upper_13 x) (at x)\"\nunfolding ln_upper_13_def diff_delta_ln_upper_13_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_13_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_13 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_13])\napply (auto simp: diff_delta_ln_upper_13_def ln_upper_13_def)\ndone\n\nlemma ln_upper_13_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_13 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_13])\nusing assms\napply (auto simp: diff_delta_ln_upper_13_def divide_simps ln_upper_13_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_13: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_13 x\"\n  by (metis le_less_linear less_eq_real_def ln_upper_13_neg ln_upper_13_pos)\n\ndefinition ln_lower_13 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_13 \\<equiv> \\<lambda>x. - ln_upper_13 (inverse x)\"\n\ncorollary ln_lower_13: \"0<x \\<Longrightarrow> ln_lower_13 x \\<le> ln x\"\n  unfolding ln_lower_13_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_13)\n\ntheorem ln_lower_13_eq: \"0<x \\<Longrightarrow>\n    ln_lower_13 x = (1/70)*(10 + 1921*x + 20149*x^2 + 50774*x^3 + 38524*x^4 + 8389*x^5 + 353*x^6)*(x - 1) /\n                    (x*(7 + 126*x + 525*x^2 + 700*x^3 + 315*x^4 + 42*x^5 + x^6))\"\n  unfolding ln_lower_13_def ln_upper_13_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq divide_simps)\n     algebra\n\n\nsection \\<open>Upper Bound 15\\<close>\n\ndefinition ln_upper_15 :: \"real \\<Rightarrow> real\"\n  where \"ln_upper_15 x \\<equiv>\n           (1487 + 49199*x + 547235*x^4 + 718735*x^3 + 334575*x^2 + 141123*x^5 + 35*x^7 + 9411*x^6)*(x - 1) /\n           (280*(1 + 56*x + 2450*x^4 + 1960*x^3 + 588*x^2 + 1176*x^5 + 8*x^7 + 196*x^6))\"\n\ndefinition diff_delta_ln_upper_15 :: \"real \\<Rightarrow> real\"\n  where \"diff_delta_ln_upper_15\n         \\<equiv> \\<lambda>x. (x - 1)^15 / ((1+56*x+2450*x^4+1960*x^3+588*x^2+8*x^7+196*x^6+1176*x^5)^2 * x)\"\n\nlemma d_delta_ln_upper_15: \"x > 0 \\<Longrightarrow>\n    ((\\<lambda>x. ln_upper_15 x - ln x) has_field_derivative diff_delta_ln_upper_15 x) (at x)\"\nunfolding ln_upper_15_def diff_delta_ln_upper_15_def\napply (intro derivative_eq_intros | simp)+\napply auto\napply (auto simp: add_pos_pos dual_order.strict_implies_not_eq divide_simps, algebra)\ndone\n\nlemma ln_upper_15_pos:\n  assumes \"1 \\<le> x\" shows \"ln(x) \\<le> ln_upper_15 x\"\napply (rule gen_upper_bound_increasing [OF assms d_delta_ln_upper_15])\napply (auto simp: diff_delta_ln_upper_15_def ln_upper_15_def)\ndone\n\nlemma ln_upper_15_neg:\n  assumes \"0 < x\" and x1: \"x \\<le> 1\" shows \"ln(x) \\<le> ln_upper_15 x\"\napply (rule gen_upper_bound_decreasing [OF x1 d_delta_ln_upper_15])\nusing assms\napply (auto simp: diff_delta_ln_upper_15_def divide_simps ln_upper_15_def mult_less_0_iff)\ndone\n\ntheorem ln_upper_15: \"0<x \\<Longrightarrow> ln(x) \\<le> ln_upper_15 x\"\n  by (metis le_less_linear less_eq_real_def ln_upper_15_neg ln_upper_15_pos)\n\n\ndefinition ln_lower_15 :: \"real \\<Rightarrow> real\"\n  where \"ln_lower_15 \\<equiv> \\<lambda>x. - ln_upper_15 (inverse x)\"\n\ncorollary ln_lower_15: \"0<x \\<Longrightarrow> ln_lower_15 x \\<le> ln x\"\n  unfolding ln_lower_15_def\n  by (metis ln_inverse inverse_positive_iff_positive minus_le_iff ln_upper_15)\n\ntheorem ln_lower_15_eq: \"0<x \\<Longrightarrow>\n    ln_lower_15 x = (1/280)*(35 + 9411*x + 141123*x^2 + 547235*x^3 + 718735*x^4 + 334575*x^5 + 49199*x^6 + 1487*x^7)*(x - 1) /\n                    (x*(8 + 196*x + 1176*x^2 + 2450*x^3 + 1960*x^4 + 588*x^5 + 56*x^6 + x^7))\"\n  unfolding ln_lower_15_def ln_upper_15_def\n  by (simp add: zero_less_mult_iff add_pos_pos dual_order.strict_implies_not_eq\n              divide_simps) algebra\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Special_Function_Bounds/Log_CF_Bounds.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037282594921, "lm_q2_score": 0.815232489352, "lm_q1q2_score": 0.7551528942850243}}
{"text": "theory ex211\n  imports Main\nbegin\ndatatype exp = Var | Const \"int\" | Add \"exp\" \"exp\" | Mult \"exp\" \"exp\"\n  \nvalue \"Const 2\"\nvalue \"Add (Var) (Const 3)\"\n  \nfun eval::\"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"eval Var n = n\"|\n  \"eval (Const i) n = i\"|\n  \"eval (Add l r) n = (eval l n) + (eval r n)\"|\n  \"eval (Mult l r) n = (eval l n) * (eval r n)\"\n  \nvalue \"eval (Var) 2\"\nvalue \"eval (Const 1) 3\"\nvalue \"eval (Add Var (Mult Var (Const 2))) 4\"\n  \nfun evalp::\"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"evalp [] n = 0\"|\n  \"evalp [x] n = x\"|\n  \"evalp (x#xs) n = x + n * (evalp xs n)\"\n  \nvalue \"evalp [1,2,3] 2\"\n  \nfun adlist::\"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"adlist [] [] = []\"|\n  \"adlist [] (y#ys) = (y#ys)\"|\n  \"adlist (x#xs) [] = (x#xs)\"|\n  \"adlist [x] [y] = [x+y]\"|\n  \"adlist [x] (y#ys) = ((x+y)#ys)\"|\n  \"adlist (x#xs) [y] = ((x+y)#xs)\"|\n  \"adlist (x#xs) (y#ys) = ((x+y)#(adlist xs ys))\"\n  \nvalue \"adlist [0,1,2] [3,4,5]\"\n  \nfun lm::\"int list \\<Rightarrow> int \\<Rightarrow> int list\" where\n  \"lm [] n = []\"|\n  \"lm (x#xs) n = (x*n)#(lm xs n)\"\n  \nvalue \"lm [1,2,3] 2\"\n  \nfun mllist::\"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where\n  \"mllist [] [] = []\"|\n  \"mllist [] y = []\"|\n  \"mllist x [] = []\"|  \n  \"mllist x (y#ys) = adlist (lm x y)(mllist (0#x)(ys))\"\n  \nvalue \"mllist [1,2,1][3,1]\"\n  \nfun coeffs::\"exp \\<Rightarrow> int list\" where\n  \"coeffs (Const i) = [i]\"|\n  \"coeffs Var = [0,1]\"|\n  \"coeffs (Add l r) = adlist (coeffs l) (coeffs r)\"|\n  \"coeffs (Mult l r) = mllist (coeffs l) (coeffs r)\"\n  \nvalue \"evalp (coeffs (Add Var (Mult Var (Const 2)))) 6\"\nvalue \"eval (Add Var (Mult Var (Const 2))) 6\"\n  \nlemma ex210: \"evalp (coeffs e) x = eval e x\"\n  apply(induction x arbitrary: e)\n   apply(auto simp add: algebra_simps)\n    sorry\n    \n    \n  \nend\n  ", "meta": {"author": "Caterpie-poke", "repo": "Isabelle", "sha": "cf7507d94ac3b7b4bd8f2c0d26045259d77fc6f6", "save_path": "github-repos/isabelle/Caterpie-poke-Isabelle", "path": "github-repos/isabelle/Caterpie-poke-Isabelle/Isabelle-cf7507d94ac3b7b4bd8f2c0d26045259d77fc6f6/2018-summer/ex211.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951661947456, "lm_q2_score": 0.8080672227971211, "lm_q1q2_score": 0.7550541069420424}}
{"text": "\nsection \\<open>Three-Way Comparison\\<close>\n\ntheory Cmp\nimports Main\nbegin\n\ndatatype cmp_val = LT | EQ | GT\n\ndefinition cmp :: \"'a:: linorder \\<Rightarrow> 'a \\<Rightarrow> cmp_val\" where\n\"cmp x y = (if x < y then LT else if x=y then EQ else GT)\"\n\nlemma \n    LT[simp]: \"cmp x y = LT \\<longleftrightarrow> x < y\"\nand EQ[simp]: \"cmp x y = EQ \\<longleftrightarrow> x = y\"\nand GT[simp]: \"cmp x y = GT \\<longleftrightarrow> x > y\"\nby (auto simp: cmp_def)\n\nlemma case_cmp_if[simp]: \"(case c of EQ \\<Rightarrow> e | LT \\<Rightarrow> l | GT \\<Rightarrow> g) =\n  (if c = LT then l else if c = GT then g else e)\"\nby(simp split: cmp_val.split)\n\nend", "meta": {"author": "Criank", "repo": "LLRB_PROOF_NEW", "sha": "2991cfdeee0ef0ce6b2992c393ab61443885781b", "save_path": "github-repos/isabelle/Criank-LLRB_PROOF_NEW", "path": "github-repos/isabelle/Criank-LLRB_PROOF_NEW/LLRB_PROOF_NEW-2991cfdeee0ef0ce6b2992c393ab61443885781b/Cmp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.8333245932423308, "lm_q1q2_score": 0.7549836048984737}}
{"text": "theory Ex5_2\n  imports Main\nbegin\n\n(*\nBy: Vadim Zaliva <vzaliva@cmu.edu>\nFrom: T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL. Springer, 2014.\nExercise 5.2:\n*)\n\nlemma  \"\n  (\\<exists> ys zs . xs=ys@zs \\<and> length ys = length zs) \\<or>\n  (\\<exists> ys zs . xs=ys@zs \\<and> length ys = length zs +1)\" (is \"?C1 \\<or> ?C2\")\nproof -\n  {\n    fix n assume A1: \"length xs=n+n\"\n    hence ?C1 proof -\n      obtain ys zs where \"ys = take n xs \\<and> zs = drop n xs\" by blast\n      hence \"xs=ys@zs \\<and> length ys = length zs\" by (metis A1 add_diff_cancel_right' append_take_drop_id length_append length_drop length_splice)\n      thus ?thesis by blast\n    qed\n  }\n  note g1 = this\n\n  {\n    fix n assume A2:\"length xs=(Suc n)+n\"\n    hence ?C2 proof -\n      obtain ys zs where \"ys = take (Suc n) xs \\<and> zs = drop (Suc n) xs\" by blast\n      hence \"xs=ys@zs \\<and> length ys = length zs+1\" \n        by (metis A2 Suc_eq_plus1_left ab_semigroup_add_class.add_ac(1) add_diff_cancel_right' append_take_drop_id comm_monoid_diff_class.add_diff_cancel_left length_append length_drop)\n      thus ?thesis by blast\n    qed\n  }\n  note g2 = this\n\n  have \"\\<exists> b . (length xs=(b+b)) \\<or> (length xs=((Suc b)+b))\" by presburger\n  then obtain b where \"(length xs=(b+b)) \\<or> (length xs=((Suc b)+b))\" by blast\n  from this g1 g2 show ?thesis by auto\nqed\n\nend\n", "meta": {"author": "vzaliva", "repo": "isabelle-semantics-ex", "sha": "4e1acf1c9850f17057dd98454e42262d01301670", "save_path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex", "path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex/isabelle-semantics-ex-4e1acf1c9850f17057dd98454e42262d01301670/Ex5_2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8333245891029457, "lm_q1q2_score": 0.7549835926872176}}
{"text": "section \\<open>Addition and Multiplication of Sets\\<close>\n\ntheory Kirby\n  imports ZFC_Cardinals\n\nbegin\n\nsubsection \\<open>Generalised Addition\\<close>\n\ntext \\<open>Source: Laurence Kirby, Addition and multiplication of sets\n      Math. Log. Quart. 53, No. 1, 52-65 (2007) / DOI 10.1002/malq.200610026\n      @{url \"http://faculty.baruch.cuny.edu/lkirby/mlqarticlejan2007.pdf\"}\\<close>\n\nsubsubsection \\<open>Addition is a monoid\\<close>\n\ninstantiation V :: plus\nbegin\n\ntext\\<open>This definition is credited to Tarski\\<close>\ndefinition plus_V :: \"V \\<Rightarrow> V \\<Rightarrow> V\"\n  where \"plus_V x \\<equiv> transrec (\\<lambda>f z. x \\<squnion> set (f ` elts z))\"\n\ninstance ..\nend\n\ndefinition lift :: \"V \\<Rightarrow> V \\<Rightarrow> V\"\n  where \"lift x y \\<equiv> set (plus x ` elts y)\"\n\nlemma plus: \"x + y = x \\<squnion> set ((+)x ` elts y)\"\n  unfolding plus_V_def  by (subst transrec) auto\n\nlemma plus_eq_lift: \"x + y = x \\<squnion> lift x y\"\n  unfolding lift_def  using plus by blast\n\ntext\\<open>Lemma 3.2\\<close>\nlemma lift_sup_distrib: \"lift x (a \\<squnion> b) = lift x a \\<squnion> lift x b\"\n  by (simp add: image_Un lift_def sup_V_def)\n\nlemma lift_Sup_distrib: \"small Y \\<Longrightarrow> lift x (\\<Squnion> Y) = \\<Squnion> (lift x ` Y)\"\n  by (auto simp: lift_def Sup_V_def image_Union)\n\nlemma add_Sup_distrib:\n  fixes x::V shows \"y \\<noteq> 0 \\<Longrightarrow> x + (SUP z\\<in>elts y. f z) = (SUP z\\<in>elts y. x + f z)\"\n  by (auto simp: plus_eq_lift SUP_sup_distrib lift_Sup_distrib image_image)\n\nlemma Limit_add_Sup_distrib:\n  fixes x::V shows \"Limit \\<alpha> \\<Longrightarrow> x + (SUP z\\<in>elts \\<alpha>. f z) = (SUP z\\<in>elts \\<alpha>. x + f z)\"\n  using add_Sup_distrib by force\n\ntext\\<open>Proposition 3.3(ii)\\<close>\ninstantiation V :: monoid_add\nbegin\ninstance\nproof\n  show \"a + b + c = a + (b + c)\" for a b c :: V\n  proof (induction c rule: eps_induct)\n    case (step c)\n    have \"(a+b) + c = a + b \\<squnion> set ((+) (a + b) ` elts c)\"\n      by (metis plus)\n    also have \"\\<dots> = a \\<squnion> lift a b \\<squnion> set ((\\<lambda>u. a + (b+u)) ` elts c)\"\n      using plus_eq_lift step.IH by auto\n    also have \"\\<dots> = a \\<squnion> lift a (b + c)\"\n    proof -\n      have \"lift a b \\<squnion> set ((\\<lambda>u. a + (b + u)) ` elts c) = lift a (b + c)\"\n        unfolding lift_def\n        by (metis elts_of_set image_image lift_def lift_sup_distrib plus_eq_lift replacement small_elts)\n      then show ?thesis\n        by (simp add: sup_assoc)\n    qed\n    also have \"\\<dots> = a + (b + c)\"\n      using plus_eq_lift by auto\n    finally show ?case .\n  qed\n  show \"0 + x = x\" for x :: V\n  proof (induction rule: eps_induct)\n    case (step x)\n    then show ?case\n      by (subst plus) auto\n  qed\n  show \"x + 0 = x\" for x :: V\n    by (subst plus) auto\nqed\nend\n\nlemma lift_0 [simp]: \"lift 0 x = x\"\n  by (simp add: lift_def)\n\nlemma lift_by0 [simp]: \"lift x 0 = 0\"\n  by (simp add: lift_def)\n\nlemma lift_by1 [simp]: \"lift x 1 = set{x}\"\n  by (simp add: lift_def)\n\nlemma add_eq_0_iff [simp]:\n  fixes x y::V\n  shows \"x+y = 0 \\<longleftrightarrow> x=0 \\<and> y=0\"\n  proof safe\n  show \"x = 0\" if \"x + y = 0\"\n    by (metis that le_imp_less_or_eq not_less_0 plus sup_ge1)\n  then show \"y = 0\" if \"x + y = 0\"\n    using that by auto\nqed auto\n\nlemma plus_vinsert: \"x + vinsert z y = vinsert (x+z) (x + y)\"\nproof -\n  have f1: \"elts (x + y) = elts x \\<union> (+) x ` elts y\"\n    by (metis elts_of_set lift_def plus_eq_lift replacement small_Un small_elts sup_V_def)\n  moreover have \"lift x (vinsert z y) = set ((+) x ` elts (set (insert z (elts y))))\"\n    using vinsert_def lift_def by presburger\n  ultimately show ?thesis\n    by (simp add: vinsert_def plus_eq_lift sup_V_def)\nqed\n\nlemma plus_V_succ_right: \"x + succ y = succ (x + y)\"\n  by (metis plus_vinsert succ_def)\n\nlemma succ_eq_add1: \"succ x = x + 1\"\n  by (simp add: plus_V_succ_right one_V_def)\n\nlemma ord_of_nat_add: \"ord_of_nat (m+n) = ord_of_nat m + ord_of_nat n\"\n  by (induction n) (auto simp: plus_V_succ_right)\n\nlemma succ_0_plus_eq [simp]:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \n  shows \"succ 0 + \\<alpha> = succ \\<alpha>\"\nproof -\n  obtain n where \"\\<alpha> = ord_of_nat n\"\n    using assms elts_\\<omega> by blast\n  then show ?thesis\n    by (metis One_nat_def ord_of_nat.simps ord_of_nat_add plus_1_eq_Suc)\nqed\n\nlemma omega_closed_add [intro]:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \"\\<beta> \\<in> elts \\<omega>\" shows \"\\<alpha>+\\<beta> \\<in> elts \\<omega>\"\nproof -\n  obtain m n where \"\\<alpha> = ord_of_nat m\" \"\\<beta> = ord_of_nat n\"\n    using assms elts_\\<omega> by auto\n  then have \"\\<alpha>+\\<beta> = ord_of_nat (m+n)\"\n    using ord_of_nat_add by auto\n  then show ?thesis\n    by (simp add: \\<omega>_def)\nqed\n\nlemma mem_plus_V_E:\n  assumes l: \"l \\<in> elts (x + y)\"\n  obtains \"l \\<in> elts x\" | z where \"z \\<in> elts y\" \"l = x + z\"\n  using l by (auto simp: plus [of x y] split: if_split_asm)\n\nlemma not_add_less_right: assumes \"Ord y\" shows \"\\<not> (x + y < x)\"\n  using assms\nproof (induction rule: Ord_induct)\n  case (step i)\n  then show ?case\n    by (metis less_le_not_le plus sup_ge1)\nqed\n\nlemma not_add_mem_right: \"\\<not> (x + y \\<in> elts x)\"\n  by (metis sup_ge1 mem_not_refl plus vsubsetD)\n\ntext\\<open>Proposition 3.3(iii)\\<close>\nlemma add_not_less_TC_self: \"\\<not> x + y \\<sqsubset> x\"\nproof (induction y arbitrary: x rule: eps_induct)\n  case (step y)\n  then show ?case\n    using less_TC_imp_not_le plus_eq_lift by fastforce\nqed\n\nlemma TC_sup_lift: \"TC x \\<sqinter> lift x y = 0\"\nproof -\n  have \"elts (TC x) \\<inter> elts (set ((+) x ` elts y)) = {}\"\n    using add_not_less_TC_self by (auto simp: less_TC_def)\n  then have \"TC x \\<sqinter> set ((+) x ` elts y) = set {}\"\n    by (metis inf_V_def)\n  then show ?thesis\n    using lift_def by auto\nqed\n\nlemma lift_lift: \"lift x (lift y z) = lift (x+y) z\"\n  using add.assoc  by (auto simp: lift_def)\n\nlemma lift_self_disjoint: \"x \\<sqinter> lift x u = 0\"\n  by (metis TC_sup_lift arg_subset_TC inf.absorb_iff2 inf_assoc inf_sup_aci(3) lift_0)\n\nlemma sup_lift_eq_lift:\n  assumes \"x \\<squnion> lift x u = x \\<squnion> lift x v\"\n  shows \"lift x u = lift x v\"\n  by (metis (no_types) assms inf_sup_absorb inf_sup_distrib2 lift_self_disjoint sup_commute sup_inf_absorb)\n\nsubsubsection \\<open>Deeper properties of addition\\<close>\n\ntext\\<open>Proposition 3.4(i)\\<close>\nproposition lift_eq_lift: \"lift x y = lift x z \\<Longrightarrow> y = z\"\nproof (induction y arbitrary: z rule: eps_induct)\n  case (step y)\n  show ?case\n  proof (intro vsubsetI order_antisym)\n    show \"u \\<in> elts z\" if \"u \\<in> elts y\" for u\n    proof -\n      have \"x+u \\<in> elts (lift x z)\"\n        using lift_def step.prems that by fastforce\n      then obtain v where \"v \\<in> elts z\" \"x+u = x+v\"\n        using lift_def by auto\n      then have \"lift x u = lift x v\"\n        using sup_lift_eq_lift by (simp add: plus_eq_lift)\n      then have \"u=v\"\n        using step.IH that by blast\n      then show ?thesis\n        using \\<open>v \\<in> elts z\\<close> by blast\n    qed\n    show \"u \\<in> elts y\" if \"u \\<in> elts z\" for u\n    proof -\n      have \"x+u \\<in> elts (lift x y)\"\n        using lift_def step.prems that by fastforce\n      then obtain v where \"v \\<in> elts y\" \"x+u = x+v\"\n        using lift_def by auto\n      then have \"lift x u = lift x v\"\n        using sup_lift_eq_lift by (simp add: plus_eq_lift)\n      then have \"u=v\"\n        using step.IH by (metis \\<open>v \\<in> elts y\\<close>)\n      then show ?thesis\n        using \\<open>v \\<in> elts y\\<close> by auto\n    qed\n  qed\nqed\n\ncorollary inj_lift: \"inj_on (lift x) A\"\n  by (auto simp: inj_on_def dest: lift_eq_lift)\n\ncorollary add_right_cancel [iff]:\n  fixes x y z::V shows \"x+y = x+z \\<longleftrightarrow> y=z\"\n  by (metis lift_eq_lift plus_eq_lift sup_lift_eq_lift)\n\ncorollary add_mem_right_cancel [iff]:\n  fixes x y z::V shows \"x+y \\<in> elts (x+z) \\<longleftrightarrow> y \\<in> elts z\"\n  apply safe\n   apply (metis mem_plus_V_E not_add_mem_right add_right_cancel)\n  by (metis ZFC_in_HOL.ext dual_order.antisym elts_vinsert insert_subset order_refl plus_vinsert)\n\ncorollary add_le_cancel_left [iff]:\n  fixes x y z::V shows \"x+y \\<le> x+z \\<longleftrightarrow> y\\<le>z\"\n  by auto (metis add_mem_right_cancel mem_plus_V_E plus sup_ge1 vsubsetD)\n\ncorollary add_less_cancel_left [iff]:\n  fixes x y z::V shows \"x+y < x+z \\<longleftrightarrow> y<z\"\n  by (simp add: less_le_not_le)\n\ncorollary lift_le_self [simp]: \"lift x y \\<le> x \\<longleftrightarrow> y = 0\"\n  by (auto simp: inf.absorb_iff2 lift_eq_lift lift_self_disjoint)\n\nlemma succ_less_\\<omega>_imp: \"succ x < \\<omega> \\<Longrightarrow> x < \\<omega>\"\n  by (metis add_le_cancel_left add.right_neutral le_0 le_less_trans succ_eq_add1)\n\ntext\\<open>Proposition 3.5\\<close>\nlemma card_lift: \"vcard (lift x y) = vcard y\"\nproof (rule cardinal_cong)\n  have \"bij_betw ((+)x) (elts y) (elts (lift x y))\"\n    unfolding bij_betw_def\n    by (simp add: inj_on_def lift_def)\n  then show \"elts (lift x y) \\<approx> elts y\"\n    using eqpoll_def eqpoll_sym by blast\nqed\n\nlemma eqpoll_lift: \"elts (lift x y) \\<approx> elts y\"\n  by (metis card_lift cardinal_eqpoll eqpoll_sym eqpoll_trans)\n\n\n\nlemma countable_add:\n  assumes \"countable (elts A)\" \"countable (elts B)\"\n  shows \"countable (elts (A+B))\"\nproof -\n  have \"vcard A \\<le> \\<aleph>0\" \"vcard B \\<le> \\<aleph>0\"\n    using assms countable_iff_le_Aleph0 by blast+\n  then have \"vcard (A+B) \\<le> \\<aleph>0\"\n    unfolding vcard_add\n    by (metis Aleph_0 Card_\\<omega> InfCard_cdouble_eq InfCard_def cadd_le_mono order_refl)\n  then show ?thesis\n    by (simp add: countable_iff_le_Aleph0)\nqed\n\ntext\\<open>Proposition 3.6\\<close>\nproposition TC_add: \"TC (x + y) = TC x \\<squnion> lift x (TC y)\"\nproof (induction y rule: eps_induct)\n  case (step y)\n  have *: \"\\<Squnion> (TC ` (+) x ` elts y) = TC x \\<squnion> (SUP u\\<in>elts y. TC (set ((+) x ` elts u)))\"\n    if \"elts y \\<noteq> {}\"\n  proof -\n    obtain w where \"w \\<in> elts y\"\n      using \\<open>elts y \\<noteq> {}\\<close> by blast\n    then have \"TC x \\<le> TC (x + w)\"\n      by (simp add: step.IH)\n    then have \\<dagger>: \"TC x \\<le> (SUP w\\<in>elts y. TC (x + w))\"\n      using \\<open>w \\<in> elts y\\<close> by blast\n    show ?thesis\n      using that\n      apply (intro conjI ballI impI order_antisym; clarsimp simp add: image_comp \\<dagger>)\n       apply(metis TC_sup_distrib Un_iff elts_sup_iff plus)\n      by (metis TC_least Transset_TC arg_subset_TC le_sup_iff plus vsubsetD)\n  qed\n  have \"TC (x + y) = (x + y) \\<squnion> \\<Squnion> (TC ` elts (x + y))\"\n    using TC by blast\n  also have \"\\<dots> = x \\<squnion> lift x y \\<squnion> \\<Squnion> (TC ` elts x) \\<squnion> \\<Squnion> ((\\<lambda>u. TC (x+u)) ` elts y)\"\n    apply (simp add: plus_eq_lift image_Un Sup_Un_distrib sup.left_commute sup_assoc TC_sup_distrib SUP_sup_distrib)\n    apply (simp add: lift_def sup.commute sup_aci *)\n    done\n  also have \"\\<dots> = x \\<squnion> \\<Squnion> (TC ` elts x) \\<squnion> lift x y \\<squnion> \\<Squnion> ((\\<lambda>u. TC x \\<squnion> lift x (TC u)) ` elts y)\"\n    by (simp add: sup_aci step.IH)\n  also have \"\\<dots> = TC x \\<squnion> lift x y \\<squnion> \\<Squnion> ((\\<lambda>u. lift x (TC u)) ` elts y)\"\n    by (simp add: sup_aci SUP_sup_distrib flip: TC [of x])\n  also have \"\\<dots> = TC x \\<squnion> lift x (y \\<squnion> \\<Squnion> (TC ` elts y))\"\n    by (metis (no_types) elts_of_set lift_Sup_distrib image_image lift_sup_distrib replacement small_elts sup_assoc)\n  also have \"\\<dots> = TC x \\<squnion> lift x (TC y)\"\n    by (simp add: TC [of y])\n  finally show ?case .\nqed\n\ncorollary TC_add': \"z \\<sqsubset> x + y \\<longleftrightarrow> z \\<sqsubset> x \\<or> (\\<exists>v. v \\<sqsubset> y \\<and> z = x + v)\"\n  using TC_add by (force simp: less_TC_def lift_def)\n\ntext\\<open>Corollary 3.7\\<close>\ncorollary vcard_TC_add: \"vcard (TC (x+y)) = vcard (TC x) \\<oplus> vcard (TC y)\"\n  by (simp add: TC_add TC_sup_lift card_lift vcard_disjoint_sup)\n\ntext\\<open>Corollary 3.8\\<close>\ncorollary TC_lift:\n  assumes \"y \\<noteq> 0\"\n  shows \"TC (lift x y) = TC x \\<squnion> lift x (TC y)\"\nproof -\n  have \"TC (lift x y) = lift x y \\<squnion> \\<Squnion> ((\\<lambda>u. TC(x+u)) ` elts y)\"\n    unfolding TC [of \"lift x y\"]  by (simp add: lift_def image_image)\n  also have \"\\<dots> = lift x y \\<squnion> (SUP u\\<in>elts y. TC x \\<squnion> lift x (TC u))\"\n    by (simp add: TC_add)\n  also have \"\\<dots> = lift x y \\<squnion> TC x \\<squnion> (SUP u\\<in>elts y. lift x (TC u))\"\n    using assms by (auto simp: SUP_sup_distrib)\n  also have \"\\<dots> = TC x \\<squnion> lift x (TC y)\"\n    by (simp add: TC [of y] sup_aci image_image lift_sup_distrib lift_Sup_distrib)\n  finally show ?thesis .\nqed\n\nproposition rank_add_distrib: \"rank (x+y) = rank x + rank y\"\nproof (induction y rule: eps_induct)\n  case (step y)\n  show ?case\n  proof (cases \"y=0\")\n    case False\n    then obtain e where e: \"e \\<in> elts y\"\n      by fastforce\n    have \"rank (x+y) = (SUP u\\<in>elts (x \\<squnion> ZFC_in_HOL.set ((+) x ` elts y)). succ (rank u))\"\n      by (metis plus rank_Sup)\n    also have \"\\<dots> = (SUP x\\<in>elts x. succ (rank x)) \\<squnion> (SUP z\\<in>elts y. succ (rank x + rank z))\"\n      apply (simp add: Sup_Un_distrib image_Un image_image)\n      apply (simp add: step cong: SUP_cong_simp)\n      done\n    also have \"\\<dots> = (SUP z \\<in> elts y. rank x + succ (rank z))\"\n    proof -\n      have \"rank x \\<le> (SUP z\\<in>elts y. ZFC_in_HOL.succ (rank x + rank z))\"\n        using \\<open>y \\<noteq> 0\\<close>\n        by (auto simp: plus_eq_lift intro: order_trans [OF _ cSUP_upper [OF e]])\n      then show ?thesis\n        by (force simp: plus_V_succ_right simp flip: rank_Sup [of x] intro!: order_antisym)\n    qed\n    also have \"\\<dots> = rank x + (SUP z \\<in> elts y. succ (rank z))\"\n      by (simp add: add_Sup_distrib False)\n    also have \"\\<dots> = rank x + rank y\"\n      by (simp add: rank_Sup [of y])\n    finally show ?thesis .\n  qed auto\nqed\n\nlemma Ord_add [simp]: \"\\<lbrakk>Ord x; Ord y\\<rbrakk> \\<Longrightarrow> Ord (x+y)\"\nproof (induction y rule: eps_induct)\n  case (step y)\n  then show ?case\n    by (metis Ord_rank rank_add_distrib rank_of_Ord)\nqed\n\nlemma add_Sup_distrib_id: \"A \\<noteq> 0 \\<Longrightarrow> x + \\<Squnion>(elts A) = (SUP z\\<in>elts A. x + z)\"\n  by (metis add_Sup_distrib image_ident image_image)\n\n\n\nlemma add_le_left:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" shows \"\\<beta> \\<le> \\<alpha>+\\<beta>\"\n  using \\<open>Ord \\<beta>\\<close>\nproof (induction rule: Ord_induct3)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (succ \\<alpha>)\n  then show ?case\n    by (auto simp: plus_V_succ_right Ord_mem_iff_lt assms(1))\nnext\n  case (Limit \\<mu>)\n  then have k: \"\\<mu> = (SUP \\<beta> \\<in> elts \\<mu>. \\<beta>)\"\n    by (simp add: Limit_eq_Sup_self)\n  also have \"\\<dots>  \\<le> (SUP \\<beta> \\<in> elts \\<mu>. \\<alpha> + \\<beta>)\"\n    using Limit.IH by auto\n  also have \"\\<dots> = \\<alpha> + (SUP \\<beta> \\<in> elts \\<mu>. \\<beta>)\"\n    using Limit.hyps Limit_add_Sup_distrib by presburger\n  finally show ?case\n    using k by simp\nqed\n\nlemma plus_\\<omega>_equals_\\<omega>:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\"  shows \"\\<alpha> + \\<omega> = \\<omega>\"\nproof (rule antisym)\n  show \"\\<alpha> + \\<omega> \\<le> \\<omega>\"\n    using Ord_trans assms by (auto simp: elim!: mem_plus_V_E)\n  show \"\\<omega> \\<le> \\<alpha> + \\<omega>\"\n    by (simp add: add_le_left assms)\nqed\n\nlemma one_plus_\\<omega>_equals_\\<omega> [simp]: \"1 + \\<omega> = \\<omega>\"\n  by (simp add: one_V_def plus_\\<omega>_equals_\\<omega>)\n\nsubsubsection \\<open>Cancellation / set subtraction\\<close>\n\ndefinition vle :: \"V \\<Rightarrow> V \\<Rightarrow> bool\" (infix \"\\<unlhd>\" 50)\n  where \"x \\<unlhd> y \\<equiv> \\<exists>z::V. x+z = y\"\n\nlemma vle_refl [iff]: \"x \\<unlhd> x\"\n  by (metis (no_types) add.right_neutral vle_def)\n\nlemma vle_antisym: \"\\<lbrakk>x \\<unlhd> y; y \\<unlhd> x\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (metis V_equalityI plus_eq_lift sup_ge1 vle_def vsubsetD)\n\nlemma vle_trans [trans]: \"\\<lbrakk>x \\<unlhd> y; y \\<unlhd> z\\<rbrakk> \\<Longrightarrow> x \\<unlhd> z\"\n  by (metis add.assoc vle_def)\n\ndefinition vle_comparable :: \"V \\<Rightarrow> V \\<Rightarrow> bool\"\n  where \"vle_comparable x y \\<equiv> x \\<unlhd> y \\<or> y \\<unlhd> x\"\n\ntext\\<open>Lemma 3.13\\<close>\nlemma comparable:\n  assumes \"a+b = c+d\"\n  shows \"vle_comparable a c\"\nunfolding vle_comparable_def\nproof (rule ccontr)\n  assume non: \"\\<not> (a \\<unlhd> c \\<or> c \\<unlhd> a)\"\n  let ?\\<phi> = \"\\<lambda>x. \\<forall>z. a+x \\<noteq> c+z\"\n  have \"?\\<phi> x\" for x\n  proof (induction x rule: eps_induct)\n    case (step x)\n    show ?case\n    proof (cases \"x=0\")\n      case True\n      with non nonzero_less_TC show ?thesis\n        using vle_def by auto\n    next\n      case False\n      then obtain v where \"v \\<in> elts x\"\n        using trad_foundation by blast\n      show ?thesis\n      proof clarsimp\n        fix z\n        assume eq: \"a + x = c + z\"\n        then have \"z \\<noteq> 0\"\n          using vle_def non by auto\n        have av: \"a+v \\<in> elts (a+x)\"\n          by (simp add: \\<open>v \\<in> elts x\\<close>)\n        moreover have \"a+x = c \\<squnion> lift c z\"\n          using eq plus_eq_lift by fastforce\n        ultimately have \"a+v \\<in> elts (c \\<squnion> lift c z)\"\n          by simp\n        moreover\n        define u where \"u \\<equiv> set (elts x - {v})\"\n        have u: \"v \\<notin> elts u\" and xeq: \"x = vinsert v u\"\n          using \\<open>v \\<in> elts x\\<close> by (auto simp: u_def intro: order_antisym)\n        have case1: \"a+v \\<notin> elts c\"\n        proof\n          assume avc: \"a + v \\<in> elts c\"\n          then have \"a \\<le> c\"\n            by clarify (metis Un_iff elts_sup_iff eq mem_not_sym mem_plus_V_E plus_eq_lift)\n          moreover have \"a \\<squnion> lift a x = c \\<squnion> lift c z\"\n            using eq by (simp add: plus_eq_lift)\n          ultimately have \"lift c z \\<le> lift a x\"\n            by (metis inf.absorb_iff2 inf_commute inf_sup_absorb inf_sup_distrib2 lift_self_disjoint sup.commute)\n          also have \"\\<dots> = vinsert (a+v) (lift a u)\"\n            by (simp add: lift_def vinsert_def xeq)\n          finally have *: \"lift c z \\<le> vinsert (a + v) (lift a u)\" .\n          have \"lift c z \\<le> lift a u\"\n          proof -\n            have \"a + v \\<notin> elts (lift c z)\"\n              using lift_self_disjoint [of c z] avc V_disjoint_iff by auto\n            then show ?thesis\n              using * less_eq_V_def by auto\n          qed\n          { fix e\n            assume \"e \\<in> elts z\"\n            then have \"c+e \\<in> elts (lift c z)\"\n              by (simp add: lift_def)\n            then have \"c+e \\<in> elts (lift a u)\"\n              using \\<open>lift c z \\<le> lift a u\\<close> by blast\n            then obtain y where \"y \\<in> elts u\" \"c+e = a+y\"\n              using lift_def by auto\n            then have False\n              by (metis elts_vinsert insert_iff step.IH xeq)\n          }\n          then show False\n            using \\<open>z \\<noteq> 0\\<close> by fastforce\n        qed\n        ultimately show False\n          by (metis (no_types) \\<open>v \\<in> elts x\\<close> av case1 eq mem_plus_V_E step.IH)\n      qed\n    qed\n  qed\n  then show False\n    using assms by blast\nqed\n\nlemma vle1: \"x \\<unlhd> y \\<Longrightarrow> x \\<le> y\"\n  using vle_def plus_eq_lift by auto\n\nlemma vle2: \"x \\<unlhd> y \\<Longrightarrow> x \\<sqsubseteq> y\"\n  by (metis (full_types) TC_add' add.right_neutral le_TC_def vle_def nonzero_less_TC)\n\nlemma vle_iff_le_Ord:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\"\n  shows \"\\<alpha> \\<unlhd> \\<beta> \\<longleftrightarrow> \\<alpha> \\<le> \\<beta>\"\nproof\n  show \"\\<alpha> \\<le> \\<beta>\" if \"\\<alpha> \\<unlhd> \\<beta>\"\n    using that by (simp add: vle1)\n  show \"\\<alpha> \\<unlhd> \\<beta>\" if \"\\<alpha> \\<le> \\<beta>\"\n    using \\<open>Ord \\<alpha>\\<close> \\<open>Ord \\<beta>\\<close> that\n  proof (induction \\<alpha> arbitrary: \\<beta> rule: Ord_induct)\n    case (step \\<gamma>)\n    then show ?case\n      unfolding vle_def\n      by (metis Ord_add Ord_linear add_le_left mem_not_refl mem_plus_V_E vsubsetD)\n  qed\nqed\n\nlemma add_le_cancel_left0 [iff]:\n  fixes x::V shows \"x \\<le> x+z\"\n  by (simp add: vle1 vle_def)\n\nlemma add_less_cancel_left0 [iff]:\n  fixes x::V shows \"x < x+z \\<longleftrightarrow> 0<z\"\n  by (metis add_less_cancel_left add.right_neutral)\n\nlemma le_Ord_diff:\n  assumes \"\\<alpha> \\<le> \\<beta>\" \"Ord \\<alpha>\" \"Ord \\<beta>\"\n  obtains \\<gamma> where \"\\<alpha>+\\<gamma> = \\<beta>\" \"\\<gamma> \\<le> \\<beta>\" \"Ord \\<gamma>\"\nproof -\n  obtain \\<gamma> where \\<gamma>: \"\\<alpha>+\\<gamma> = \\<beta>\" \"\\<gamma> \\<le> \\<beta>\"\n    by (metis add_le_cancel_left add_le_left assms vle_def vle_iff_le_Ord)\n  then have \"Ord \\<gamma>\"\n    using Ord_def Transset_def \\<open>Ord \\<beta>\\<close> by force\n  with \\<gamma> that show thesis by blast\nqed\n\nlemma plus_Ord_le:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \"Ord \\<beta>\" shows \"\\<alpha>+\\<beta> \\<le> \\<beta>+\\<alpha>\"\nproof (cases \"\\<beta> \\<in> elts \\<omega>\")\n  case True\n  with assms have \"\\<alpha>+\\<beta> = \\<beta>+\\<alpha>\"\n    by (auto simp: elts_\\<omega> add.commute ord_of_nat_add [symmetric])\n  then show ?thesis by simp\nnext\n  case False\n  then have \"\\<omega> \\<le> \\<beta>\" \n    using Ord_linear2 Ord_mem_iff_lt \\<open>Ord \\<beta>\\<close> by auto\n  then obtain \\<gamma> where \"\\<omega>+\\<gamma> = \\<beta>\" \"\\<gamma> \\<le> \\<beta>\" \"Ord \\<gamma>\"\n    using \\<open>Ord \\<beta>\\<close> le_Ord_diff by auto\n  then have \"\\<alpha>+\\<beta> = \\<beta>\"\n    by (metis add.assoc assms(1) plus_\\<omega>_equals_\\<omega>)\n  then show ?thesis\n    by simp\nqed\n\nlemma add_right_mono: \"\\<lbrakk>\\<alpha> \\<le> \\<beta>; Ord \\<alpha>; Ord \\<beta>; Ord \\<gamma>\\<rbrakk> \\<Longrightarrow> \\<alpha>+\\<gamma> \\<le> \\<beta>+\\<gamma>\"\n  by (metis add_le_cancel_left add.assoc add_le_left le_Ord_diff)\n\nlemma add_strict_mono: \"\\<lbrakk>\\<alpha> < \\<beta>; \\<gamma> < \\<delta>; Ord \\<alpha>; Ord \\<beta>; Ord \\<gamma>; Ord \\<delta>\\<rbrakk> \\<Longrightarrow> \\<alpha>+\\<gamma> < \\<beta>+\\<delta>\"\n  by (metis order.strict_implies_order add_less_cancel_left add_right_mono le_less_trans)\n\nlemma add_right_strict_mono: \"\\<lbrakk>\\<alpha> \\<le> \\<beta>; \\<gamma> < \\<delta>; Ord \\<alpha>; Ord \\<beta>; Ord \\<gamma>; Ord \\<delta>\\<rbrakk> \\<Longrightarrow> \\<alpha>+\\<gamma> < \\<beta>+\\<delta>\"\n  using add_strict_mono le_imp_less_or_eq by blast\n\nlemma Limit_add_Limit [simp]:\n  assumes \"Limit \\<mu>\" \"Ord \\<beta>\" shows \"Limit (\\<beta> + \\<mu>)\"\n  unfolding Limit_def\n  proof (intro conjI allI impI)\n  show \"Ord (\\<beta> + \\<mu>)\"\n    using Limit_def assms by auto\n  show \"0 \\<in> elts (\\<beta> + \\<mu>)\"\n    using Limit_def add_le_left assms by auto\nnext\n  fix \\<gamma>\n  assume \"\\<gamma> \\<in> elts (\\<beta> + \\<mu>)\"\n  then consider \"\\<gamma> \\<in> elts \\<beta>\" | \\<xi> where \"\\<xi> \\<in> elts \\<mu>\" \"\\<gamma> = \\<beta> + \\<xi>\"\n    using mem_plus_V_E by blast\n  then show \"succ \\<gamma> \\<in> elts (\\<beta> + \\<mu>)\"\n  proof cases\n    case 1\n    then show ?thesis\n      by (metis Kirby.add_strict_mono Limit_def Ord_add Ord_in_Ord Ord_mem_iff_lt assms one_V_def succ_eq_add1)\n  next\n    case 2\n    then show ?thesis\n      by (metis Limit_def add_mem_right_cancel assms(1) plus_V_succ_right)\n  qed\nqed\n\n\nsubsection \\<open>Generalised Difference\\<close>\n\ndefinition odiff where \"odiff y x \\<equiv> THE z::V. (x+z = y) \\<or> (z=0 \\<and> \\<not> x \\<unlhd> y)\"\n\nlemma vle_imp_odiff_eq: \"x \\<unlhd> y \\<Longrightarrow> x + (odiff y x) = y\"\n  by (auto simp: vle_def odiff_def)\n\nlemma not_vle_imp_odiff_0: \"\\<not> x \\<unlhd> y \\<Longrightarrow> (odiff y x) = 0\"\n  by (auto simp: vle_def odiff_def)\n\nlemma Ord_odiff_eq:\n  assumes \"\\<alpha> \\<le> \\<beta>\" \"Ord \\<alpha>\" \"Ord \\<beta>\"\n  shows \"\\<alpha> + odiff \\<beta> \\<alpha> = \\<beta>\"\n  by (simp add: assms vle_iff_le_Ord vle_imp_odiff_eq)\n\nlemma Ord_odiff:\n  assumes \"Ord \\<alpha>\" \"Ord \\<beta>\" shows \"Ord (odiff \\<beta> \\<alpha>)\"\nproof (cases \"\\<alpha> \\<unlhd> \\<beta>\")\n  case True\n  then show ?thesis\n    by (metis add_right_cancel assms le_Ord_diff vle1 vle_imp_odiff_eq)\nnext\n  case False\n  then show ?thesis\n    by (simp add: odiff_def vle_def)\nqed\n\nlemma Ord_odiff_le:\n  assumes  \"Ord \\<alpha>\" \"Ord \\<beta>\" shows \"odiff \\<beta> \\<alpha> \\<le> \\<beta>\"\nproof (cases \"\\<alpha> \\<unlhd> \\<beta>\")\n  case True\n  then show ?thesis\n    by (metis add_right_cancel assms le_Ord_diff vle1 vle_imp_odiff_eq)\nnext\n  case False\n  then show ?thesis \n    by (simp add: odiff_def vle_def)\nqed\n\n\nlemma odiff_0_right [simp]: \"odiff x 0 = x\"\n  by (metis add.left_neutral vle_def vle_imp_odiff_eq)\n\nlemma odiff_succ: \"y \\<unlhd> x \\<Longrightarrow> odiff (succ x) y = succ (odiff x y)\"\n  unfolding odiff_def\n  by (metis add_right_cancel odiff_def plus_V_succ_right vle_def vle_imp_odiff_eq)\n\nlemma odiff_eq_iff: \"z \\<unlhd> x \\<Longrightarrow> odiff x z = y \\<longleftrightarrow> x = z + y\"\n  by (auto simp: odiff_def vle_def)\n\nlemma odiff_le_iff: \"z \\<unlhd> x \\<Longrightarrow> odiff x z \\<le> y \\<longleftrightarrow> x \\<le> z + y\"\n  by (auto simp: odiff_def vle_def)\n\nlemma odiff_less_iff: \"z \\<unlhd> x \\<Longrightarrow> odiff x z < y \\<longleftrightarrow> x < z + y\"\n  by (auto simp: odiff_def vle_def)\n\nlemma odiff_ge_iff: \"z \\<unlhd> x \\<Longrightarrow> odiff x z \\<ge> y \\<longleftrightarrow> x \\<ge> z + y\"\n  by (auto simp: odiff_def vle_def)\n\nlemma Ord_odiff_le_iff: \"\\<lbrakk>\\<alpha> \\<le> x; Ord x; Ord \\<alpha>\\<rbrakk> \\<Longrightarrow> odiff x \\<alpha> \\<le> y \\<longleftrightarrow> x \\<le> \\<alpha> + y\"\n  by (simp add: odiff_le_iff vle_iff_le_Ord)\n\nlemma odiff_le_odiff:\n  assumes \"x \\<unlhd> y\" shows \"odiff x z \\<le> odiff y z\"\nproof (cases \"z \\<unlhd> x\")\n  case True\n  then show ?thesis\n    using assms odiff_le_iff vle1 vle_imp_odiff_eq vle_trans by presburger\nnext\n  case False\n  then show ?thesis\n    by (simp add: not_vle_imp_odiff_0)\nqed\n\nlemma Ord_odiff_le_odiff: \"\\<lbrakk>x \\<le> y; Ord x; Ord y\\<rbrakk> \\<Longrightarrow> odiff x \\<alpha> \\<le> odiff y \\<alpha>\"\n  by (simp add: odiff_le_odiff vle_iff_le_Ord)\n\n\n\nlemma Ord_odiff_less_imp_less: \"\\<lbrakk>odiff x \\<alpha> < odiff y \\<alpha>; Ord x; Ord y\\<rbrakk> \\<Longrightarrow> x < y\"\n  by (meson Ord_linear2 leD odiff_le_odiff vle_iff_le_Ord)\n\nlemma odiff_add_cancel [simp]: \"odiff (x + y) x = y\"\n  by (simp add: odiff_eq_iff vle_def)\n\nlemma odiff_add_cancel_0 [simp]: \"odiff x x = 0\"\n  by (simp add: odiff_eq_iff)\n\nlemma odiff_add_cancel_both [simp]: \"odiff (x + y) (x + z) = odiff y z\"\n  by (simp add: add.assoc odiff_def vle_def)\n\n\nsubsection \\<open>Generalised Multiplication\\<close>\n\ntext \\<open>Credited to Dana Scott\\<close>\n\ninstantiation V :: times\nbegin\n\ntext\\<open>This definition is credited to Tarski\\<close>\ndefinition times_V :: \"V \\<Rightarrow> V \\<Rightarrow> V\"\n  where \"times_V x \\<equiv> transrec (\\<lambda>f y. \\<Squnion> ((\\<lambda>u. lift (f u) x) ` elts y))\"\n\ninstance ..\nend\n\nlemma mult: \"x * y = (SUP u\\<in>elts y. lift (x * u) x)\"\n  unfolding times_V_def  by (subst transrec) (force simp:)\n\ntext \\<open>Lemma 4.2\\<close>\n\nlemma mult_zero_right [simp]:\n  fixes x::V shows \"x * 0 = 0\"\n  by (metis ZFC_in_HOL.Sup_empty elts_0 image_empty mult)\n\nlemma mult_insert: \"x * (vinsert y z) = x*z \\<squnion> lift (x*y) x\"\n  by (metis (no_types, lifting) elts_vinsert image_insert replacement small_elts sup_commute mult Sup_V_insert)\n\nlemma mult_succ: \"x * succ y = x*y + x\"\n  by (simp add: mult_insert plus_eq_lift succ_def)\n\nlemma ord_of_nat_mult: \"ord_of_nat (m*n) = ord_of_nat m * ord_of_nat n\"\nproof (induction n)\n  case (Suc n)\n  then show ?case\n    by (simp add: add.commute [of m]) (simp add: ord_of_nat_add mult_succ)\nqed auto\n\nlemma omega_closed_mult [intro]:\n  assumes \"\\<alpha> \\<in> elts \\<omega>\" \"\\<beta> \\<in> elts \\<omega>\" shows \"\\<alpha>*\\<beta> \\<in> elts \\<omega>\"\nproof -\n  obtain m n where \"\\<alpha> = ord_of_nat m\" \"\\<beta> = ord_of_nat n\"\n    using assms elts_\\<omega> by auto\n  then have \"\\<alpha>*\\<beta> = ord_of_nat (m*n)\"\n    by (simp add: ord_of_nat_mult)\n  then show ?thesis\n    by (simp add: \\<omega>_def)\nqed\n\nlemma zero_imp_le_mult: \"0 \\<in> elts y \\<Longrightarrow> x \\<le> x*y\"\n  by (auto simp: mult [of x y])\n  \nsubsubsection\\<open>Proposition 4.3\\<close>\n\nlemma mult_zero_left [simp]:\n  fixes x::V shows \"0 * x = 0\"\nproof (induction x rule: eps_induct)\n  case (step x)\n  then show ?case\n    by (subst mult) auto\nqed\n\nlemma mult_sup_distrib:\n  fixes x::V shows \"x * (y \\<squnion> z) = x*y \\<squnion> x*z\"\n  unfolding mult [of x \"y \\<squnion> z\"] mult [of x y] mult [of x z]\n  by (simp add: Sup_Un_distrib image_Un)\n\nlemma mult_Sup_distrib: \"small Y \\<Longrightarrow> x * (\\<Squnion>Y) = \\<Squnion> ((*) x ` Y)\" for Y:: \"V set\"\n  unfolding mult [of x \"\\<Squnion>Y\"]\n  by (simp add: cSUP_UNION) (metis mult)\n\nlemma mult_lift_imp_distrib: \"x * (lift y z) = lift (x*y) (x*z) \\<Longrightarrow> x * (y+z) = x*y + x*z\"\n  by (simp add: mult_sup_distrib plus_eq_lift)\n\nlemma mult_lift: \"x * (lift y z) = lift (x*y) (x*z)\"\nproof (induction z rule: eps_induct)\n  case (step z)\n  have \"x * lift y z = (SUP u\\<in>elts (lift y z). lift (x * u) x)\"\n    using mult by blast\n  also have \"\\<dots> = (SUP v\\<in>elts z. lift (x * (y + v)) x)\"\n    using lift_def by auto\n  also have \"\\<dots> = (SUP v\\<in>elts z. lift (x * y + x * v) x)\"\n    using mult_lift_imp_distrib step.IH by auto\n  also have \"\\<dots> = (SUP v\\<in>elts z. lift (x * y) (lift (x * v) x))\"\n    by (simp add: lift_lift)\n  also have \"\\<dots> = lift (x * y) (SUP v\\<in>elts z. lift (x * v) x)\"\n    by (simp add: image_image lift_Sup_distrib)\n  also have \"\\<dots> = lift (x*y) (x*z)\"\n    by (metis mult)\n  finally show ?case .\nqed\n\nlemma mult_Limit: \"Limit \\<gamma> \\<Longrightarrow> x * \\<gamma> = \\<Squnion> ((*) x ` elts \\<gamma>)\"\n  by (metis Limit_eq_Sup_self mult_Sup_distrib small_elts)\n\nlemma add_mult_distrib: \"x * (y+z) = x*y + x*z\" for x::V\n  by (simp add: mult_lift mult_lift_imp_distrib)\n\ninstantiation V :: monoid_mult\nbegin\ninstance\nproof\n  show \"1 * x = x\" for x :: V\n  proof (induction x rule: eps_induct)\n    case (step x)\n    then show ?case\n      by (subst mult) auto\n  qed\n  show \"x * 1 = x\" for x :: V\n    by (subst mult) auto\n  show \"(x * y) * z = x * (y * z)\" for x y z::V\n  proof (induction z rule: eps_induct)\n    case (step z)\n    have \"(x * y) * z = (SUP u\\<in>elts z. lift (x * y * u) (x * y))\"\n      using mult by blast\n    also have \"\\<dots> = (SUP u\\<in>elts z. lift (x * (y * u)) (x * y))\"\n      using step.IH by auto\n    also have \"\\<dots> = (SUP u\\<in>elts z. x * lift (y * u) y)\"\n      using mult_lift by auto\n    also have \"\\<dots> = x * (SUP u\\<in>elts z. lift (y * u) y)\"\n      by (simp add: image_image mult_Sup_distrib)\n    also have \"\\<dots> = x * (y * z)\"\n      by (metis mult)\n    finally show ?case .\n  qed\nqed\n\nend\n\nlemma le_mult:\n  assumes \"Ord \\<beta>\" \"\\<beta> \\<noteq> 0\" shows \"\\<alpha> \\<le> \\<alpha> * \\<beta>\"\n  using assms\nproof (induction rule: Ord_induct3)\n  case (succ \\<alpha>)\n  then show ?case\n    using mult_insert succ_def by fastforce\nnext\n  case (Limit \\<mu>)\n  have \"\\<alpha> \\<in> (*) \\<alpha> ` elts \\<mu>\"\n    using Limit.hyps Limit_def one_V_def by (metis imageI mult.right_neutral)\n  then have \"\\<alpha> \\<le> \\<Squnion> ((*) \\<alpha> ` elts \\<mu>)\"\n    by auto\n  then show ?case\n    by (simp add: Limit.hyps mult_Limit)\nqed auto\n\nlemma mult_sing_1 [simp]:\n  fixes x::V shows \"x * set{1} = lift x x\"\n  by (subst mult) auto\n\nlemma mult_2_right [simp]:\n  fixes x::V shows \"x * set{0,1} = x+x\"\n  by (subst mult) (auto simp: Sup_V_insert plus_eq_lift)\n\nlemma Ord_mult [simp]: \"\\<lbrakk>Ord y; Ord x\\<rbrakk> \\<Longrightarrow> Ord (x*y)\"\nproof (induction y rule: Ord_induct3)\n  case 0\n  then show ?case\n    by auto\nnext\n  case (succ k)\n  then show ?case\n    by (simp add: mult_succ)\nnext\n  case (Limit k)\n  then have \"Ord (x * \\<Squnion> (elts k))\"\n    by (metis Ord_Sup imageE mult_Sup_distrib small_elts)\n  then show ?case\n    using Limit.hyps Limit_eq_Sup_self by auto\nqed\n\n\nsubsubsection \\<open>Proposition 4.4-5\\<close>\nproposition rank_mult_distrib: \"rank (x*y) = rank x * rank y\"\nproof (induction y rule: eps_induct)\n  case (step y)\n  have \"rank (x*y) = (SUP y\\<in>elts (SUP u\\<in>elts y. lift (x * u) x). succ (rank y))\"\n    by (metis rank_Sup mult)\n  also have \"\\<dots> = (SUP u\\<in>elts y. SUP r\\<in>elts x. succ (rank (x * u + r)))\"\n    apply (simp add: lift_def image_image image_UN)\n    apply (simp add: Sup_V_def)\n    done\n  also have \"\\<dots> = (SUP u\\<in>elts y. SUP r\\<in>elts x. succ (rank (x * u) + rank r))\"\n    using rank_add_distrib by auto\n  also have \"\\<dots> = (SUP u\\<in>elts y. SUP r\\<in>elts x. succ (rank x * rank u + rank r))\"\n    using step arg_cong [where f = Sup] by auto\n  also have \"\\<dots> = (SUP u\\<in>elts y. rank x * rank u + rank x)\"\n  proof (rule SUP_cong)\n    show \"(SUP r\\<in>elts x. succ (rank x * rank u + rank r)) = rank x * rank u + rank x\"\n      if \"u \\<in> elts y\" for u\n    proof (cases \"x=0\")\n      case False\n      have \"(SUP r\\<in>elts x. succ (rank x * rank u + rank r)) = rank x * rank u + (SUP y\\<in>elts x. succ (rank y))\"\n      proof (rule order_antisym)\n        show \"(SUP r\\<in>elts x. succ (rank x * rank u + rank r)) \\<le> rank x * rank u + (SUP y\\<in>elts x. succ (rank y))\"\n          by (auto simp: Sup_le_iff simp flip: plus_V_succ_right)\n        have \"rank x * rank u + (SUP y\\<in>elts x. succ (rank y)) = (SUP y\\<in>elts x. rank x * rank u + succ (rank y))\"\n          by (simp add: add_Sup_distrib False)\n        also have \"\\<dots> \\<le> (SUP r\\<in>elts x. succ (rank x * rank u + rank r))\"\n          using plus_V_succ_right by auto\n        finally show \"rank x * rank u + (SUP y\\<in>elts x. succ (rank y)) \\<le> (SUP r\\<in>elts x. succ (rank x * rank u + rank r))\" .\n      qed\n      also have \"\\<dots> = rank x * rank u + rank x\"\n        by (metis rank_Sup)\n      finally show ?thesis .\n    qed auto\n  qed auto\n  also have \"\\<dots> = rank x * rank y\"\n    by (simp add: rank_Sup [of y] mult_Sup_distrib mult_succ image_image)\n  finally show ?case .\nqed\n\nlemma mult_le1:\n  fixes y::V assumes \"y \\<noteq> 0\" shows \"x \\<sqsubseteq> x * y\"\nproof (cases \"x = 0\")\n  case False\n  then obtain r where r: \"r \\<in> elts x\"\n    by fastforce\n  from \\<open>y \\<noteq> 0\\<close> show ?thesis\n  proof (induction y rule: eps_induct)\n    case (step y)\n    show ?case\n    proof (cases \"y = 1\")\n      case False\n      with \\<open>y \\<noteq> 0\\<close> obtain p where p: \"p \\<in> elts y\" \"p \\<noteq> 0\"\n        by (metis V_equalityI elts_1 insertI1 singletonD trad_foundation)\n      then have \"x*p + r \\<in> elts (lift (x*p) x)\"\n        by (simp add: lift_def r)\n      moreover have \"lift (x*p) x \\<le> x*y\"\n        by (metis bdd_above_iff_small cSUP_upper2 order_refl \\<open>p \\<in> elts y\\<close> replacement small_elts mult)\n      ultimately have \"x*p + r \\<in> elts (x*y)\"\n        by blast\n      moreover have \"x*p \\<sqsubseteq> x*p + r\"\n        by (metis TC_add' V_equalityI add.right_neutral eps_induct le_TC_refl less_TC_iff less_imp_le_TC)\n      ultimately show ?thesis\n        using step.IH [OF p] le_TC_trans less_TC_iff by blast\n    qed auto\n  qed\nqed auto\n\nlemma mult_eq_0_iff [simp]:\n  fixes y::V shows \"x * y = 0 \\<longleftrightarrow> x=0 \\<or> y=0\"\nproof\n  show \"x = 0 \\<or> y = 0\" if \"x * y = 0\"\n    by (metis le_0 le_TC_def less_TC_imp_not_le mult_le1 that)\nqed auto\n\nlemma lift_lemma:\n  assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\"  shows \"\\<not> lift (x * y) x \\<le> x\"\n  using assms mult_le1 [of concl: x y]\n  by (auto simp: le_TC_def TC_lift less_TC_def less_TC_imp_not_le)\n\nlemma mult_le2:\n  fixes y::V assumes \"x \\<noteq> 0\" \"y \\<noteq> 0\" \"y \\<noteq> 1\" shows \"x \\<sqsubset> x * y\"\nproof -\n  obtain v where v: \"v \\<in> elts y\" \"v \\<noteq> 0\"\n    using assms by fastforce\n  have \"x \\<noteq> x * y\"\n    using lift_lemma [of x v]\n    by (metis \\<open>x \\<noteq> 0\\<close> bdd_above_iff_small cSUP_upper2 order_refl replacement small_elts mult v)\n  then show ?thesis\n  using assms mult_le1 [of y x]\n    by (auto simp: le_TC_def)\nqed\n\nlemma elts_mult_\\<omega>E:\n  assumes \"x \\<in> elts (y * \\<omega>)\"\n  obtains n where \"n \\<noteq> 0\" \"x \\<in> elts (y * ord_of_nat n)\" \"\\<And>m. m < n \\<Longrightarrow> x \\<notin> elts (y * ord_of_nat m)\"\nproof -\n  obtain k where k:  \"k \\<noteq> 0 \\<and> x \\<in> elts (y * ord_of_nat k)\"\n    using assms\n    apply (simp add: mult_Limit elts_\\<omega>)\n    by (metis mult_eq_0_iff elts_0 ex_in_conv ord_of_eq_0_iff that)\n  define n where \"n \\<equiv> (LEAST k. k \\<noteq> 0 \\<and> x \\<in> elts (y * ord_of_nat k))\"\n  show thesis\n  proof\n    show \"n \\<noteq> 0\" \"x \\<in> elts (y * ord_of_nat n)\"\n      unfolding n_def by (metis (mono_tags, lifting) LeastI_ex k)+\n    show \"\\<And>m. m < n \\<Longrightarrow> x \\<notin> elts (y * ord_of_nat m)\"\n      by (metis (mono_tags, lifting) mult_eq_0_iff elts_0 empty_iff n_def not_less_Least ord_of_eq_0_iff)\n  qed\nqed\n\n\nsubsubsection\\<open>Theorem 4.6\\<close>\n\ntheorem mult_eq_imp_0:\n  assumes \"a*x = a*y + b\" \"b \\<sqsubset> a\"\n  shows \"b=0\"\nproof (cases \"a=0 \\<or> x=0\")\n  case True\n  with assms show ?thesis\n    by (metis add_le_cancel_left mult_eq_0_iff eq_iff le_0)\nnext\n  case False\n  then have \"a\\<noteq>0\" \"x\\<noteq>0\"\n    by auto\n  then show ?thesis\n  proof (cases \"y=0\")\n    case True\n    then show ?thesis\n      using assms less_asym_TC mult_le2 by force\n  next\n    case False\n    have \"b=0\" if \"Ord \\<alpha>\" \"x \\<in> elts (Vset \\<alpha>)\" \"y \\<in> elts (Vset \\<alpha>)\" for \\<alpha>\n      using that assms\n    proof (induction \\<alpha> arbitrary: x y b rule: Ord_induct3)\n      case 0\n      then show ?case by auto\n    next\n      case (succ k)\n      define \\<Phi> where \"\\<Phi> \\<equiv> \\<lambda>x y. \\<exists>r. 0 \\<sqsubset> r \\<and> r \\<sqsubset> a \\<and> a*x = a*y + r\"\n      show ?case\n      proof (rule ccontr)\n        assume \"b \\<noteq> 0\"\n        then have \"0 \\<sqsubset> b\"\n          by (metis nonzero_less_TC)\n        then have \"\\<Phi> x y\"\n          unfolding \\<Phi>_def using succ.prems by blast\n        then obtain x' where \"\\<Phi> x' y\" \"x' \\<sqsubseteq> x\" and min: \"\\<And>x''. x'' \\<sqsubset> x' \\<Longrightarrow> \\<not> \\<Phi> x'' y\"\n          using less_TC_minimal [of \"\\<lambda>x. \\<Phi> x y\" x] by blast\n        then obtain b' where \"0 \\<sqsubset> b'\" \"b' \\<sqsubset> a\" and eq: \"a*x' = a*y + b'\"\n          using \\<Phi>_def by blast\n        have \"a*y \\<sqsubset> a*x'\"\n          using TC_add' \\<open>0 \\<sqsubset> b'\\<close> eq by auto\n        then obtain p where \"p \\<in> elts (a * x')\" \"a * y \\<sqsubseteq> p\"\n          using less_TC_iff by blast\n        then have \"p \\<notin> elts (a * y)\"\n          using less_TC_iff less_irrefl_TC by blast\n        then have \"p \\<in> \\<Union> (elts ` (\\<lambda>v. lift (a * v) a) ` elts x')\"\n          by (metis \\<open>p \\<in> elts (a * x')\\<close> elts_Sup replacement small_elts mult)\n        then obtain u c where \"u \\<in> elts x'\" \"c \\<in> elts a\" \"p = a*u + c\"\n          using lift_def by auto\n        then have \"p \\<in> elts (lift (a*y) b')\"\n          using \\<open>p \\<in> elts (a * x')\\<close> \\<open>p \\<notin> elts (a * y)\\<close> eq plus_eq_lift by auto\n        then obtain d where d: \"d \\<in> elts b'\" \"p = a*y + d\" \"p = a*u + c\"\n          by (metis \\<open>p = a * u + c\\<close> \\<open>p \\<in> elts (a * x')\\<close> \\<open>p \\<notin> elts (a * y)\\<close> eq mem_plus_V_E)\n        have noteq: \"a*y \\<noteq> a*u\"\n        proof\n          assume \"a*y = a*u\"\n          then have \"lift (a*y) a = lift (a*u) a\"\n            by metis\n          also have \"\\<dots> \\<le> a*x'\"\n            unfolding mult [of _ x'] using \\<open>u \\<in> elts x'\\<close> by (auto intro: cSUP_upper)\n          also have \"\\<dots> = a*y \\<squnion> lift (a*y) b'\"\n            by (simp add: eq plus_eq_lift)\n          finally have \"lift (a*y) a \\<le> a*y \\<squnion> lift (a*y) b'\" .\n          then have \"lift (a*y) a \\<le> lift (a*y) b'\"\n            using add_le_cancel_left less_TC_imp_not_le plus_eq_lift \\<open>b' \\<sqsubset> a\\<close> by auto\n          then have \"a \\<le> b'\"\n            by (simp add: le_iff_sup lift_eq_lift lift_sup_distrib)\n          then show False\n            using \\<open>b' \\<sqsubset> a\\<close> less_TC_imp_not_le by auto\n        qed\n        consider \"a*y \\<unlhd> a*u\" | \"a*u \\<unlhd> a*y\"\n          using d comparable vle_comparable_def by auto\n        then show False\n        proof cases\n          case 1\n          then obtain e where e: \"a*u = a*y + e\" \"e \\<noteq> 0\"\n            by (metis add.right_neutral noteq vle_def)\n          moreover have \"e + c = d\"\n            by (metis e add_right_cancel \\<open>p = a * u + c\\<close> \\<open>p = a * y + d\\<close> add.assoc)\n          with \\<open>d \\<in> elts b'\\<close> \\<open>b' \\<sqsubset> a\\<close> have \"e \\<sqsubset> a\"\n            by (meson less_TC_iff less_TC_trans vle2 vle_def)\n          ultimately show False\n            \\<comment>\\<open>contradicts minimality of @{term x'}\\<close>\n            using min unfolding \\<Phi>_def by (meson \\<open>u \\<in> elts x'\\<close> le_TC_def less_TC_iff nonzero_less_TC)\n        next\n          case 2\n          then obtain e where e: \"a*y = a*u + e\" \"e \\<noteq> 0\"\n            by (metis add.right_neutral noteq vle_def)\n          moreover have \"e + d = c\"\n            by (metis e add_right_cancel \\<open>p = a * u + c\\<close> \\<open>p = a * y + d\\<close> add.assoc)\n          with \\<open>d \\<in> elts b'\\<close> \\<open>b' \\<sqsubset> a\\<close> have \"e \\<sqsubset> a\"\n            by (metis \\<open>c \\<in> elts a\\<close> less_TC_iff vle2 vle_def)\n          ultimately have \"\\<Phi> y u\"\n            unfolding \\<Phi>_def using nonzero_less_TC by blast\n          then obtain y' where \"\\<Phi> y' u\" \"y' \\<sqsubseteq> y\" and min: \"\\<And>x''. x'' \\<sqsubset> y' \\<Longrightarrow> \\<not> \\<Phi> x'' u\"\n            using less_TC_minimal [of \"\\<lambda>x. \\<Phi> x u\" y] by blast\n          then obtain b' where \"0 \\<sqsubset> b'\" \"b' \\<sqsubset> a\" and eq: \"a*y' = a*u + b'\"\n            using \\<Phi>_def by blast\n          have u_k: \"u \\<in> elts (Vset k)\"\n            using \\<open>u \\<in> elts x'\\<close> \\<open>x' \\<sqsubseteq> x\\<close> succ Vset_succ_TC less_TC_iff less_le_TC_trans by blast\n          have \"a*u \\<sqsubset> a*y'\"\n            using TC_add' \\<open>0 \\<sqsubset> b'\\<close> eq by auto\n          then obtain p where \"p \\<in> elts (a * y')\" \"a * u \\<sqsubseteq> p\"\n            using less_TC_iff by blast\n          then have \"p \\<notin> elts (a * u)\"\n            using less_TC_iff less_irrefl_TC by blast\n          then have \"p \\<in> \\<Union> (elts ` (\\<lambda>v. lift (a * v) a) ` elts y')\"\n            by (metis \\<open>p \\<in> elts (a * y')\\<close> elts_Sup replacement small_elts mult)\n          then obtain v c where \"v \\<in> elts y'\" \"c \\<in> elts a\" \"p = a*v + c\"\n            using lift_def by auto\n          then have \"p \\<in> elts (lift (a*u) b')\"\n            using \\<open>p \\<in> elts (a * y')\\<close> \\<open>p \\<notin> elts (a * u)\\<close> eq plus_eq_lift by auto\n          then obtain d where d: \"d \\<in> elts b'\" \"p = a*u + d\" \"p = a*v + c\"\n            by (metis \\<open>p = a * v + c\\<close> \\<open>p \\<in> elts (a * y')\\<close> \\<open>p \\<notin> elts (a * u)\\<close> eq mem_plus_V_E)\n          have v_k: \"v \\<in> elts (Vset k)\"\n            using Vset_succ_TC \\<open>v \\<in> elts y'\\<close> \\<open>y' \\<sqsubseteq> y\\<close> less_TC_iff less_le_TC_trans succ.hyps succ.prems(2) by blast\n          have noteq: \"a*u \\<noteq> a*v\"\n            proof\n              assume \"a*u = a*v\"\n              then have \"lift (a*v) a \\<le> a*y'\"\n                unfolding mult [of _ y'] using \\<open>v \\<in> elts y'\\<close> by (auto intro: cSUP_upper)\n              also have \"\\<dots> = a*u \\<squnion> lift (a*u) b'\"\n                by (simp add: eq plus_eq_lift)\n              finally have \"lift (a*v) a \\<le> a*u \\<squnion> lift (a*u) b'\" .\n              then have \"lift (a*u) a \\<le> lift (a*u) b'\"\n                by (metis \\<open>a * u = a * v\\<close> le_iff_sup lift_sup_distrib sup_left_commute sup_lift_eq_lift)\n              then have \"a \\<le> b'\"\n                by (simp add: le_iff_sup lift_eq_lift lift_sup_distrib)\n              then show False\n                using \\<open>b' \\<sqsubset> a\\<close> less_TC_imp_not_le by auto\n            qed\n          consider \"a*u \\<unlhd> a*v\" | \"a*v \\<unlhd> a*u\"\n            using d comparable vle_comparable_def by auto\n          then show False\n          proof cases\n            case 1\n            then obtain e where e: \"a*v = a*u + e\" \"e \\<noteq> 0\"\n              by (metis add.right_neutral noteq vle_def)\n            moreover have \"e + c = d\"\n              by (metis add_right_cancel \\<open>p = a * u + d\\<close> \\<open>p = a * v + c\\<close> add.assoc e)\n            with \\<open>d \\<in> elts b'\\<close> \\<open>b' \\<sqsubset> a\\<close> have \"e \\<sqsubset> a\"\n              by (meson less_TC_iff less_TC_trans vle2 vle_def)\n            ultimately show False\n              using succ.IH u_k v_k by blast\n          next\n            case 2\n            then obtain e where e: \"a*u = a*v + e\" \"e \\<noteq> 0\"\n              by (metis add.right_neutral noteq vle_def)\n            moreover have \"e + d = c\"\n              by (metis add_right_cancel add.assoc d e)\n            with \\<open>d \\<in> elts b'\\<close> \\<open>b' \\<sqsubset> a\\<close> have \"e \\<sqsubset> a\"\n              by (metis \\<open>c \\<in> elts a\\<close> less_TC_iff vle2 vle_def)\n           ultimately show False\n             using succ.IH u_k v_k by blast\n          qed\n        qed\n      qed\n    next\n      case (Limit k)\n      obtain i j where k: \"i \\<in> elts k\" \"j \\<in> elts k\"\n        and x: \"x \\<in> elts (Vset i)\"\n        and y: \"y \\<in> elts (Vset j)\"\n        using that Limit by (auto simp: Limit_Vfrom_eq)\n      show ?case\n      proof (rule Limit.IH [of \"i \\<squnion> j\"])\n        show \"i \\<squnion> j \\<in> elts k\"\n          by (meson k x y Limit.hyps Limit_def Ord_in_Ord Ord_mem_iff_lt Ord_sup union_less_iff)\n        show \"x \\<in> elts (Vset (i \\<squnion> j))\" \"y \\<in> elts (Vset (i \\<squnion> j))\"\n          using x y by (auto simp: Vfrom_sup)\n      qed (use Limit.prems in auto)\n    qed\n    then show ?thesis\n      by (metis two_in_Vset Ord_rank Ord_VsetI rank_lt)\n  qed\nqed\n\nsubsubsection\\<open>Theorem 4.7\\<close>\n\nlemma mult_cancellation_half:\n  assumes \"a*x + r = a*y + s\" \"r \\<sqsubset> a\" \"s \\<sqsubset> a\"\n  shows \"x \\<le> y\"\nproof -\n  have \"x \\<le> y\" if \"Ord \\<alpha>\" \"x \\<in> elts (Vset \\<alpha>)\" \"y \\<in> elts (Vset \\<alpha>)\" for \\<alpha>\n    using that assms\n  proof (induction \\<alpha> arbitrary: x y r s rule: Ord_induct3)\n    case 0\n    then show ?case\n      by auto\n  next\n    case (succ k)\n    show ?case\n    proof\n      fix u\n      assume u: \"u \\<in> elts x\"\n      have u_k: \"u \\<in> elts (Vset k)\"\n        using Vset_succ succ.hyps succ.prems(1) u by auto\n      obtain r' where \"r' \\<in> elts a\" \"r \\<sqsubseteq> r'\"\n        using less_TC_iff succ.prems(4) by blast\n      have \"a*u + r' \\<in> elts (lift (a*u) a)\"\n        by (simp add: \\<open>r' \\<in> elts a\\<close> lift_def)\n      also have \"\\<dots> \\<le> elts (a*x)\"\n        using u by (force simp: mult [of _ x])\n      also have \"\\<dots> \\<le> elts (a*y + s)\"\n        by (metis less_eq_V_def plus_eq_lift succ.prems(3) sup_ge1)\n      also have \"\\<dots> = elts (a*y) \\<union> elts (lift (a*y) s)\"\n        by (simp add: plus_eq_lift)\n      finally have \"a * u + r' \\<in> elts (a * y) \\<union> elts (lift (a * y) s)\" .\n      then show \"u \\<in> elts y\"\n      proof\n        assume *: \"a * u + r' \\<in> elts (a * y)\"\n        show \"u \\<in> elts y\"\n        proof -\n          obtain v e where v: \"v \\<in> elts y\" \"e \\<in> elts a\" \"a * u + r' = a * v + e\"\n            using * by (auto simp: mult [of _ y] lift_def)\n          then have v_k: \"v \\<in> elts (Vset k)\"\n            using Vset_succ_TC less_TC_iff succ.prems(2) by blast\n          then have \"u = v\"\n            by (metis succ.IH u_k V_equalityI \\<open>r' \\<in> elts a\\<close> le_TC_refl less_TC_iff v(2) v(3) vsubsetD)\n          then show ?thesis\n            using \\<open>v \\<in> elts y\\<close> by blast\n        qed\n      next\n        assume \"a * u + r' \\<in> elts (lift (a * y) s)\"\n        then obtain t where \"t \\<in> elts s\" and t: \"a * u + r' = a * y + t\"\n          using lift_def by auto\n        have noteq: \"a*y \\<noteq> a*u\"\n        proof\n          assume \"a*y = a*u\"\n          then have \"lift (a*y) a = lift (a*u) a\"\n            by metis\n          also have \"\\<dots> \\<le> a*x\"\n            unfolding mult [of _ x] using \\<open>u \\<in> elts x\\<close> by (auto intro: cSUP_upper)\n          also have \"\\<dots> \\<le> a*y \\<squnion> lift (a*y) s\"\n            using \\<open>elts (a * x) \\<subseteq> elts (a * y + s)\\<close> plus_eq_lift by auto\n          finally have \"lift (a*y) a \\<le> a*y \\<squnion> lift (a*y) s\" .\n          then have \"lift (a*y) a \\<le> lift (a*y) s\"\n            using add_le_cancel_left less_TC_imp_not_le plus_eq_lift \\<open>s \\<sqsubset> a\\<close> by auto\n          then have \"a \\<le> s\"\n            by (simp add: le_iff_sup lift_eq_lift lift_sup_distrib)\n          then show False\n            using \\<open>s \\<sqsubset> a\\<close> less_TC_imp_not_le by auto\n        qed\n        consider \"a * u \\<unlhd> a * y\" | \"a * y \\<unlhd> a * u\"\n          using t comparable vle_comparable_def by blast\n        then have \"False\"\n        proof cases\n          case 1\n          then obtain c where \"a*y = a*u + c\"\n            by (metis vle_def)\n          then have \"c+t = r'\"\n            by (metis add_right_cancel add.assoc t)\n          then have \"c \\<sqsubset> a\"\n            using \\<open>r' \\<in> elts a\\<close> less_TC_iff vle2 vle_def by force\n          moreover have \"c \\<noteq> 0\"\n            using \\<open>a * y = a * u + c\\<close> noteq by auto\n          ultimately show ?thesis\n            using \\<open>a * y = a * u + c\\<close> mult_eq_imp_0 by blast\n        next\n          case 2\n          then obtain c where \"a*u = a*y + c\"\n            by (metis vle_def)\n          then have \"c+r' = t\"\n            by (metis add_right_cancel add.assoc t)\n          then have \"c \\<sqsubset> a\"\n            by (metis \\<open>t \\<in> elts s\\<close> less_TC_iff less_TC_trans \\<open>s \\<sqsubset> a\\<close> vle2 vle_def)\n          moreover have \"c \\<noteq> 0\"\n            using \\<open>a * u = a * y + c\\<close> noteq by auto\n          ultimately show ?thesis\n            using \\<open>a * u = a * y + c\\<close> mult_eq_imp_0 by blast\n        qed\n        then show \"u \\<in> elts y\" ..\n      qed\n    qed\n  next\n    case (Limit k)\n    obtain i j where k: \"i \\<in> elts k\" \"j \\<in> elts k\"\n      and x: \"x \\<in> elts (Vset i)\" and y: \"y \\<in> elts (Vset j)\"\n      using that Limit by (auto simp: Limit_Vfrom_eq)\n    show ?case\n    proof (rule Limit.IH [of \"i \\<squnion> j\"])\n      show \"i \\<squnion> j \\<in> elts k\"\n        by (meson k x y Limit.hyps Limit_def Ord_in_Ord Ord_mem_iff_lt Ord_sup union_less_iff)\n      show \"x \\<in> elts (Vset (i \\<squnion> j))\" \"y \\<in> elts (Vset (i \\<squnion> j))\"\n        using x y by (auto simp: Vfrom_sup)\n      thm Limit.prems\n    qed (auto intro: Limit.prems)\n  qed\n  then show ?thesis\n    by (metis two_in_Vset Ord_rank Ord_VsetI rank_lt)\nqed\n\n\ntheorem mult_cancellation_lemma:\n  assumes \"a*x + r = a*y + s\" \"r \\<sqsubset> a\" \"s \\<sqsubset> a\"\n  shows \"x=y \\<and> r=s\"\n  by (metis add_right_cancel mult_cancellation_half antisym assms)\n\ncorollary mult_cancellation [simp]:\n  fixes a::V\n  assumes \"a \\<noteq> 0\"\n  shows \"a*x = a*y \\<longleftrightarrow> x=y\"\n  by (metis assms nonzero_less_TC mult_cancellation_lemma)\n\ncorollary lift_mult_TC_disjoint:\n  fixes x::V\n  assumes \"x \\<noteq> y\"\n  shows \"lift (a*x) (TC a) \\<sqinter> lift (a*y) (TC a) = 0\"\n  apply (rule V_equalityI)\n  using assms\n  by (auto simp: less_TC_def inf_V_def lift_def image_iff dest: mult_cancellation_lemma)\n\ncorollary lift_mult_disjoint:\n  fixes x::V\n  assumes \"x \\<noteq> y\"\n  shows \"lift (a*x) a \\<sqinter> lift (a*y) a = 0\"\nproof -\n  have \"lift (a*x) a \\<sqinter> lift (a*y) a \\<le> lift (a*x) (TC a) \\<sqinter> lift (a*y) (TC a)\"\n    by (metis TC' inf_mono lift_sup_distrib sup_ge1)\n  then show ?thesis\n    using assms lift_mult_TC_disjoint by auto\nqed\n\nlemma mult_add_mem:\n  assumes \"a*x + r \\<in> elts (a*y)\" \"r \\<sqsubset> a\"\n  shows \"x \\<in> elts y\" \"r \\<in> elts a\"\nproof -\n  obtain v s where v: \"a * x + r = a * v + s\" \"v \\<in> elts y\" \"s \\<in> elts a\"\n    using assms unfolding mult [of a y] lift_def by auto\n  then show \"x \\<in> elts y\"\n    by (metis arg_subset_TC assms(2) less_TC_def mult_cancellation_lemma vsubsetD)\n  show \"r \\<in> elts a\"\n    by (metis arg_subset_TC assms(2) less_TC_def mult_cancellation_lemma v(1) v(3) vsubsetD)\nqed\n\n\n\nlemma zero_mem_mult_iff: \"0 \\<in> elts (x*y) \\<longleftrightarrow> 0 \\<in> elts x \\<and> 0 \\<in> elts y\" \n  by (metis Kirby.mult_zero_right mult_add_mem_0)\n\nlemma zero_less_mult_iff [simp]: \"0 < x*y \\<longleftrightarrow> 0 < x \\<and> 0 < y\" if \"Ord x\" \n  using Kirby.mult_eq_0_iff ZFC_in_HOL.neq0_conv by blast\n\nlemma mult_cancel_less_iff [simp]:\n  \"\\<lbrakk>Ord \\<alpha>; Ord \\<beta>; Ord \\<gamma>\\<rbrakk> \\<Longrightarrow> \\<alpha>*\\<beta> < \\<alpha>*\\<gamma> \\<longleftrightarrow> \\<beta> < \\<gamma> \\<and> 0 < \\<alpha>\"\n  using mult_add_mem_0 [of \\<alpha> \\<beta> \\<gamma>]\n  by (meson Ord_0 Ord_mem_iff_lt Ord_mult)\n\nlemma mult_cancel_le_iff [simp]:\n  \"\\<lbrakk>Ord \\<alpha>; Ord \\<beta>; Ord \\<gamma>\\<rbrakk> \\<Longrightarrow> \\<alpha>*\\<beta> \\<le> \\<alpha>*\\<gamma> \\<longleftrightarrow> \\<beta> \\<le> \\<gamma> \\<or> \\<alpha>=0\"\n  by (metis Ord_linear2 Ord_mult eq_iff leD mult_cancel_less_iff mult_cancellation)\n\nlemma mult_Suc_add_less: \"\\<lbrakk>\\<alpha> < \\<gamma>; \\<beta> < \\<gamma>; Ord \\<alpha>; Ord \\<beta>; Ord \\<gamma>\\<rbrakk>  \\<Longrightarrow> \\<gamma> * ord_of_nat m + \\<alpha> < \\<gamma> * ord_of_nat (Suc m) + \\<beta>\"\n  apply (simp add: mult_succ add.assoc)\n  by (meson Ord_add Ord_linear2 le_less_trans not_add_less_right)\n\nlemma mult_nat_less_add_less:\n  assumes \"m < n\" \"\\<alpha> < \\<gamma>\" \"\\<beta> < \\<gamma>\" and ord: \"Ord \\<alpha>\" \"Ord \\<beta>\" \"Ord \\<gamma>\"\n    shows \"\\<gamma> * ord_of_nat m + \\<alpha> < \\<gamma> * ord_of_nat n + \\<beta>\"\nproof -\n  have \"Suc m \\<le> n\"\n    using \\<open>m < n\\<close> by auto\n  have \"\\<gamma> * ord_of_nat m + \\<alpha> < \\<gamma> * ord_of_nat (Suc m) + \\<beta>\"\n    using assms mult_Suc_add_less by blast\n  also have \"\\<dots> \\<le> \\<gamma> * ord_of_nat n + \\<beta>\"\n    using Ord_mult Ord_ord_of_nat add_right_mono \\<open>Suc m \\<le> n\\<close> ord mult_cancel_le_iff ord_of_nat_mono_iff by presburger\n  finally show ?thesis .\nqed\n\nlemma add_mult_less_add_mult:\n  assumes \"x < y\" \"x \\<in> elts \\<beta>\" \"y \\<in> elts \\<beta>\" \"\\<mu> \\<in> elts \\<alpha>\" \"\\<nu> \\<in> elts \\<alpha>\" \"Ord \\<alpha>\" \"Ord \\<beta>\"\n    shows \"\\<alpha>*x + \\<mu> < \\<alpha>*y + \\<nu>\"\nproof -\n  obtain \"Ord x\" \"Ord y\"\n    using Ord_in_Ord assms by blast\n  then obtain \\<delta> where \"0 \\<in> elts \\<delta>\" \"y = x + \\<delta>\"\n    by (metis add.right_neutral \\<open>x < y\\<close> le_Ord_diff less_V_def mem_0_Ord)\n  then show ?thesis\n    apply (simp add: add_mult_distrib add.assoc)\n    by (meson OrdmemD add_le_cancel_left0 \\<open>\\<mu> \\<in> elts \\<alpha>\\<close> \\<open>Ord \\<alpha>\\<close> less_le_trans zero_imp_le_mult)\nqed\n\nlemma add_mult_less:\n  assumes \"\\<gamma> \\<in> elts \\<alpha>\" \"\\<nu> \\<in> elts \\<beta>\" \"Ord \\<alpha>\" \"Ord \\<beta>\"\n    shows \"\\<alpha> * \\<nu> + \\<gamma> \\<in> elts (\\<alpha> * \\<beta>)\"\nproof -\n  have \"Ord \\<nu>\" \n    using Ord_in_Ord assms by blast\n  with assms show ?thesis\n    by (metis Ord_mem_iff_lt Ord_succ add_mem_right_cancel mult_cancel_le_iff mult_succ succ_le_iff vsubsetD)\nqed\n\nlemma vcard_mult: \"vcard (x * y) = vcard x \\<otimes> vcard y\"\nproof -\n  have 1: \"elts (lift (x * u) x) \\<approx> elts x\" if \"u \\<in> elts y\" for u\n    by (metis cardinal_eqpoll eqpoll_sym eqpoll_trans card_lift)\n  have 2: \"pairwise (\\<lambda>u u'. disjnt (elts (lift (x * u) x)) (elts (lift (x * u') x)))  (elts y)\"\n    by (simp add: pairwise_def disjnt_def) (metis V_disjoint_iff lift_mult_disjoint)\n  have \"x * y = (SUP u\\<in>elts y. lift (x * u) x)\"\n    using mult by blast\n  then have \"elts (x * y) \\<approx> (\\<Union>u\\<in>elts y. elts (lift (x * u) x))\"\n    by simp\n  also have \"\\<dots> \\<approx> elts y \\<times> elts x\"\n    using Union_eqpoll_Times [OF 1 2] .\n  also have \"\\<dots> \\<approx> elts x \\<times> elts y\"\n    by (simp add: times_commute_eqpoll)\n  also have \"\\<dots> \\<approx> elts (vcard x) \\<times> elts (vcard y)\"\n    using cardinal_eqpoll eqpoll_sym times_eqpoll_cong by blast\n  also have \"\\<dots> \\<approx> elts (vcard x \\<otimes> vcard y)\"\n    by (simp add: cmult_def elts_vcard_VSigma_eqpoll eqpoll_sym)\n  finally have \"elts (x * y) \\<approx> elts (vcard x \\<otimes> vcard y)\" .\n  then show ?thesis\n    by (metis cadd_cmult_distrib cadd_def cardinal_cong cardinal_idem vsum_0_eqpoll)\nqed\n\nproposition TC_mult: \"TC(x * y) = (SUP r \\<in> elts (TC x). SUP u \\<in> elts (TC y). set{x * u + r})\"\nproof (cases \"x = 0\")\n  case False\n  have *: \"TC(x * y) = (SUP u \\<in> elts (TC y). lift (x * u) (TC x))\" for y\n  proof (induction y rule: eps_induct)\n    case (step y)\n    have \"TC(x * y) = (SUP u \\<in> elts y. TC (lift (x * u) x))\"\n      by (simp add: mult [of x y] TC_Sup_distrib image_image)\n    also have \"\\<dots> = (SUP u \\<in> elts y. TC(x * u) \\<squnion> lift (x * u) (TC x))\"\n      by (simp add: TC_lift False)\n    also have \"\\<dots> = (SUP u \\<in> elts y. (SUP z \\<in> elts (TC u). lift (x * z) (TC x)) \\<squnion> lift (x * u) (TC x))\"\n      by (simp add: step)\n    also have \"\\<dots> = (SUP u \\<in> elts (TC y). lift (x * u) (TC x))\"\n      by (auto simp: TC' [of y] image_Un Sup_Un_distrib TC_Sup_distrib cSUP_UNION SUP_sup_distrib)\n    finally show ?case .\n  qed\n  show ?thesis\n    by (force simp: * lift_def)\nqed auto\n\n\ncorollary vcard_TC_mult: \"vcard (TC(x * y)) = vcard (TC x) \\<otimes> vcard (TC y)\"\nproof -\n  have \"(\\<Union>u\\<in>elts (TC x). \\<Union>v\\<in>elts (TC y). {x * v + u}) = (\\<Union>u\\<in>elts (TC x). (\\<lambda>v. x * v + u) ` elts (TC y))\"\n    by (simp add: UNION_singleton_eq_range)\n  also have \"\\<dots> \\<approx> (\\<Union>x\\<in>elts (TC x). elts (lift (TC y * x) (TC y)))\"\n  proof (rule UN_eqpoll_UN)\n    show \"(\\<lambda>v. x * v + u) ` elts (TC y) \\<approx> elts (lift (TC y * u) (TC y))\"\n      if \"u \\<in> elts (TC x)\" for u\n    proof -\n      have \"inj_on (\\<lambda>v. x * v + u) (elts (TC y))\"\n        by (meson inj_onI less_TC_def mult_cancellation_lemma that)\n      then have \"(\\<lambda>v. x * v + u) ` elts (TC y) \\<approx> elts (TC y)\"\n        by (rule inj_on_image_eqpoll_self)\n      also have \"\\<dots> \\<approx> elts (lift (TC y * u) (TC y))\"\n        by (simp add: eqpoll_lift eqpoll_sym)\n      finally show ?thesis .\n    qed\n    show \"pairwise (\\<lambda>u ya. disjnt ((\\<lambda>v. x * v + u) ` elts (TC y)) ((\\<lambda>v. x * v + ya) ` elts (TC y))) (elts (TC x))\"\n      apply (auto simp: pairwise_def disjnt_def)\n      using less_TC_def mult_cancellation_lemma by blast\n    show \"pairwise (\\<lambda>u ya. disjnt (elts (lift (TC y * u) (TC y))) (elts (lift (TC y * ya) (TC y)))) (elts (TC x))\"\n      apply (auto simp: pairwise_def disjnt_def)\n      by (metis Int_iff V_disjoint_iff empty_iff lift_mult_disjoint)\n  qed\n  also have \"\\<dots> = elts (TC y * TC x)\"\n    by (metis elts_Sup image_image mult replacement small_elts)\n  finally have \"(\\<Union>u\\<in>elts (TC x). \\<Union>v\\<in>elts (TC y). {x * v + u}) \\<approx> elts (TC y * TC x)\" .\n  then show ?thesis\n    apply (subst cmult_commute)\n    by (simp add: TC_mult cardinal_cong flip: vcard_mult)\nqed\n\nlemma countable_mult:\n  assumes \"countable (elts A)\" \"countable (elts B)\"\n  shows \"countable (elts (A*B))\"\nproof -\n  have \"vcard A \\<le> \\<aleph>0\" \"vcard B \\<le> \\<aleph>0\"\n    using assms countable_iff_le_Aleph0 by blast+\n  then have \"vcard (A*B) \\<le> \\<aleph>0\"\n    unfolding vcard_mult\n    by (metis InfCard_csquare_eq cmult_le_mono Aleph_0 Card_\\<omega> InfCard_def order_refl)\n  then show ?thesis\n    by (simp add: countable_iff_le_Aleph0)\nqed\n\nsubsection \\<open>Ordertype properties\\<close>\n\nlemma ordertype_image_plus:\n  assumes \"Ord \\<alpha>\"\n  shows \"ordertype ((+) u ` elts \\<alpha>) VWF = \\<alpha>\"\nproof (subst ordertype_VWF_eq_iff)\n    have 1: \"(u + x, u + y) \\<in> VWF\" if \"x \\<in> elts \\<alpha>\" \"y \\<in> elts \\<alpha>\" \"x < y\" for x y\n      using that\n      by (meson Ord_in_Ord Ord_mem_iff_lt add_mem_right_cancel assms mem_imp_VWF)\n  then have 2: \"x < y\"\n    if \"x \\<in> elts \\<alpha>\" \"y \\<in> elts \\<alpha>\" \"(u + x, u + y) \\<in> VWF\" for x y\n    using that by (metis Ord_in_Ord Ord_linear_lt VWF_asym assms)\n  show \"\\<exists>f. bij_betw f ((+) u ` elts \\<alpha>) (elts \\<alpha>) \\<and> (\\<forall>x\\<in>(+) u ` elts \\<alpha>. \\<forall>y\\<in>(+) u ` elts \\<alpha>. (f x < f y) = ((x, y) \\<in> VWF))\"\n    using 1 2 unfolding bij_betw_def inj_on_def\n    by (rule_tac x=\"\\<lambda>x. odiff x u\" in exI) (auto simp: image_iff)\nqed (use assms in auto)\n\nlemma ordertype_diff:\n  assumes \"\\<beta> + \\<delta> = \\<alpha>\" and \\<alpha>: \"\\<delta> \\<in> elts \\<alpha>\" \"Ord \\<alpha>\"\n  shows \"ordertype (elts \\<alpha> - elts \\<beta>) VWF = \\<delta>\"\nproof -\n  have *: \"elts \\<alpha> - elts \\<beta> = ((+)\\<beta>) ` elts \\<delta>\"\n  proof\n    show \"elts \\<alpha> - elts \\<beta> \\<subseteq> (+) \\<beta> ` elts \\<delta>\"\n      by clarsimp (metis assms(1) image_iff mem_plus_V_E)\n    show \"(+) \\<beta> ` elts \\<delta> \\<subseteq> elts \\<alpha> - elts \\<beta>\"\n      using assms(1) not_add_mem_right by force\n  qed\n  have \"ordertype ((+) \\<beta> ` elts \\<delta>) VWF = \\<delta>\"\n  proof (subst ordertype_VWF_inc_eq)\n    show \"elts \\<delta> \\<subseteq> ON\" \"ordertype (elts \\<delta>) VWF = \\<delta>\"\n      using \\<alpha> elts_subset_ON ordertype_eq_Ord by blast+\n  qed (use \"*\" assms elts_subset_ON in auto)\n  then show ?thesis\n    by (simp add: *)\nqed\n\nlemma ordertype_interval_eq:\n  assumes \\<alpha>: \"Ord \\<alpha>\" and \\<beta>: \"Ord \\<beta>\"\n  shows \"ordertype ({\\<alpha> ..< \\<alpha>+\\<beta>} \\<inter> ON) VWF = \\<beta>\"\nproof -\n  have ON: \"(+) \\<alpha> ` elts \\<beta> \\<subseteq> ON\"\n    using assms Ord_add Ord_in_Ord by blast\n  have \"({\\<alpha> ..< \\<alpha>+\\<beta>} \\<inter> ON) = (+) \\<alpha> ` elts \\<beta>\"\n    using assms\n    apply (simp add: image_def set_eq_iff)\n    by (metis add_less_cancel_left Ord_add Ord_in_Ord Ord_linear2 Ord_mem_iff_lt le_Ord_diff not_add_less_right)\n  moreover have \"ordertype (elts \\<beta>) VWF = ordertype ((+) \\<alpha> ` elts \\<beta>) VWF\"\n    using ON \\<beta> elts_subset_ON ordertype_VWF_inc_eq by auto\n  ultimately show ?thesis\n    using \\<beta> by auto\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/ZFC_in_HOL/Kirby.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942290328345, "lm_q2_score": 0.8479677583778258, "lm_q1q2_score": 0.7549408016896872}}
{"text": "section \"Algebraic Classes\"\n\ntheory Derive_Algebra\nimports Main \"../Derive\" Derive_Datatypes\nbegin\n\nclass semigroup = \n  fixes mult :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixl \"\\<otimes>\" 70)\n(*  assumes assoc: \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\" *)\n    \nclass monoidl = semigroup +\nfixes neutral :: 'a (\"\\<one>\")\n(* assumes neutl : \"\\<one> \\<otimes> x = x\" *)    \n  \nclass group = monoidl +\n  fixes inverse :: \"'a \\<Rightarrow> 'a\"\n(* assumes invl: \"x\\<div> \\<otimes> x = \\<one>\" *)\n    \n(* Manual instances for nat, unit, prod, and sum *)    \ninstantiation nat and unit:: semigroup\nbegin  \n  definition mult_nat : \"mult (x::nat) y = x + y\"\n  definition mult_unit_def: \"mult (x::unit) y = x\"\n  instance ..\nend \ninstantiation nat and unit:: monoidl\nbegin  \n  definition neutral_nat : \"neutral = (0::nat)\"\n  definition neutral_unit_def: \"neutral = ()\"\n  instance ..\nend   \n  \ninstantiation nat and unit:: group\nbegin  \n  definition inverse_nat : \"inverse (i::nat) = \\<one> - i\"\n  definition inverse_unit_def: \"inverse u = ()\"\n  instance ..\nend   \n\ninstantiation prod and sum :: (semigroup, semigroup) semigroup\nbegin\n  definition mult_prod_def: \"x \\<otimes> y = (fst x \\<otimes> fst y, snd x \\<otimes> snd y)\"\n  definition mult_sum_def: \"x \\<otimes> y = (case x of Inl a \\<Rightarrow> (case y of Inl b \\<Rightarrow> Inl (a \\<otimes> b) | Inr b \\<Rightarrow> Inl a)\n                                             | Inr a \\<Rightarrow> (case y of Inl b \\<Rightarrow> Inr a | Inr b \\<Rightarrow> Inr (a \\<otimes> b)))\"\n  instance ..\nend\n  \ninstantiation prod and sum :: (monoidl, monoidl) monoidl\nbegin\n  definition neutral_prod_def: \"neutral = (neutral,neutral)\"\n  definition neutral_sum_def: \"neutral = Inl neutral\"\n  instance ..\nend \n  \ninstantiation prod and sum :: (group, group) group\nbegin\n  definition inverse_prod_def: \"inverse p = (inverse (fst p), inverse (snd p))\"\n  definition inverse_sum_def: \"inverse x = (case x of Inl a \\<Rightarrow> (Inl (inverse a)) \n                                                    | Inr b \\<Rightarrow> Inr (inverse b))\"\n  instance ..\nend    \n    \n(* Simple test *)  \n  \nderive_generic semigroup simple .\nderive_generic monoidl simple .\nderive_generic group simple .\n  \nlemma \"(B \\<one> 6) \\<otimes> (B 4 5) = B 4 11\" by eval\nlemma \"(A 2) \\<otimes> (A 3) = A 5\" by eval\nlemma \"(B \\<one> 6) \\<otimes> \\<one> = B 0 6\" by eval\n  \n(* type with parameter *)\n  \nderive_generic group either .  \n\nlemma \"(L 3) \\<otimes> ((L 4)::(nat,nat) either) = L 7\" by eval\nlemma \"(R (2::nat)) \\<otimes> (L (3::nat)) = R 2\" by eval\n  \n(* recursive types *) \n\nderive_generic semigroup list .\nderive_generic monoidl list .\nderive_generic group list .\nderive_generic semigroup tree .\nderive_generic monoidl tree .\nderive_generic group tree .\n  \nlemma \"[1,2,3,4::nat] \\<otimes> [1,2,3] = [2,4,6,4]\" by eval\nlemma \"inverse [1,2,3::nat] = [0,0,0]\" by eval\n\n(* mutually recursive types *)\n\nderive_generic semigroup even_nat .\nderive_generic monoidl even_nat .\nderive_generic group even_nat .\nderive_generic semigroup exp .\n\n(* instantiate monoidl manually *)  \ninstantiation exp and trm and fct  :: (monoidl,monoidl) monoidl \nbegin  \n  definition neutral_fct where \"neutral_fct = Const neutral\"\n  definition neutral_trm where \"neutral_trm = Factor neutral\"\n  definition neutral_exp where \"neutral_exp = Term neutral\"\n  instance ..\nend     \n\n(* Manually defined instances need to be added to the theory context *)\nsetup \\<open>\n(Derive.add_inst_info \\<^class>\\<open>monoidl\\<close> \\<^type_name>\\<open>fct\\<close> [@{thm neutral_fct_def}]) #>\n(Derive.add_inst_info \\<^class>\\<open>monoidl\\<close> \\<^type_name>\\<open>trm\\<close> [@{thm neutral_trm_def}]) #>\n(Derive.add_inst_info \\<^class>\\<open>monoidl\\<close> \\<^type_name>\\<open>exp\\<close> [@{thm neutral_exp_def}])\n\\<close>\n\nderive_generic group exp .\n   \nlemma \"(Odd_Succ (Even_Succ (Odd_Succ Even_Zero))) \\<otimes> (Odd_Succ Even_Zero) \n       = Odd_Succ (Even_Succ (Odd_Succ Even_Zero))\" by eval\nlemma \"inverse (Odd_Succ Even_Zero) = Odd_Succ Even_Zero\" by eval\nlemma \"(Term (Prod ((Const 1)::(nat, nat) fct) (Factor (Const (2::nat))))) \n    \\<otimes> (Term (Prod (Const (2::nat)) (Factor ((Const 2)::(nat, nat) fct))))\n    = Term (Prod (Const 3) (Factor (Const 4)))\" by eval   \n\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Generic_Deriving/tests/Derive_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942173896131, "lm_q2_score": 0.8479677583778257, "lm_q1q2_score": 0.7549407918166109}}
{"text": "theory ArithVeri\n  imports Main\nbegin\n\ndatatype Arith = Num nat\n  | Plus Arith Arith\n  | Minus Arith Arith\n  | Times Arith Arith\n\ndatatype StackOp = SNum nat\n  | SPlus\n  | SMinus\n  | STimes\n\nfun eval :: \"nat list \\<Rightarrow> StackOp list \\<Rightarrow> nat\" where\n\"eval (n # _) [] = n\" |\n\"eval ns (SNum n # xs) = eval (n # ns) xs\" |\n\"eval (n1 # n2 # ns) (SPlus # xs) = eval ((n1+n2) # ns) xs\" |\n\"eval (n1 # n2 # ns) (SMinus # xs) = eval ((n1-n2) # ns) xs\" |\n\"eval (n1 # n2 # ns) (STimes # xs) = eval ((n1*n2) # ns) xs\"\n\nvalue \"eval [] [SNum 1, SNum 2, SNum 4, STimes, SPlus]\"\n\nfun compile :: \"Arith \\<Rightarrow> StackOp list\" where\n\"compile (Num n) = [SNum n]\" |\n\"compile (Plus a1 a2) = compile a2 @ compile a1 @ [SPlus]\" |\n\"compile (Minus a1 a2) = compile a2 @ compile a1 @ [SMinus]\" |\n\"compile (Times a1 a2) = compile a2 @ compile a1 @ [STimes]\"\n\nvalue \"compile (Plus (Num 1) (Times (Num 2) (Num 4)))\"\n\nfun eval' :: \"Arith \\<Rightarrow> nat\" where\n\"eval' (Num n) = n\" |\n\"eval' (Plus a1 a2) = (eval' a1) + (eval' a2)\" |\n\"eval' (Minus a1 a2) = (eval' a1) - (eval' a2)\" |\n\"eval' (Times a1 a2) = (eval' a1) * (eval' a2)\"\n\nvalue \"eval' (Plus (Num 1) (Times (Num 2) (Num 4)))\"\n\ntheorem compiler_correctness: \"eval [] (compile a) = (eval' a)\"\n  sorry\n\nend\n", "meta": {"author": "waynee95", "repo": "isabelle-hol-playground", "sha": "6ed735e98e99b475088e59932d0bae43dbd314d8", "save_path": "github-repos/isabelle/waynee95-isabelle-hol-playground", "path": "github-repos/isabelle/waynee95-isabelle-hol-playground/isabelle-hol-playground-6ed735e98e99b475088e59932d0bae43dbd314d8/ArithVeri.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.939913354875362, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.7549137774817961}}
{"text": "theory prog_prov_ch03\nimports Main\nbegin\n\ntext{*\n  Section 3: Logic and Proof Beyond Equality\n*}\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set:: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\"\n| \"set (Node l e r) = (set l) \\<union> {e} \\<union> (set r)\"\n\nfun ord:: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\" |\n\"ord (Node l e r) = ((ord l) \\<and> (ord r) \\<and> (\\<forall>x\\<in> (set l). x<e) \\<and> (\\<forall>x\\<in>(set r). e<x))\"\n\nfun ins:: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins a Tip = (Node Tip a Tip)\"\n| \"ins a (Node l e r) = (if a < e then Node (ins a l) e r else if a=e then Node l e r else Node l e (ins a r))\"\n\nlemma ins_union: \"set (ins x t) = {x} \\<union> (set t)\"\napply(induction t rule:ins.induct)\napply(auto)\ndone\n\nlemma ins_ord: \"ord t \\<Longrightarrow> ord (ins x t)\"\napply(induction t)\napply(auto simp add:ins_union)\ndone\n\nlemma \"\\<forall> x. \\<exists> y. x = y\" by auto\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\" by auto\n\nlemma \"A \\<and> B \\<Longrightarrow> B \\<and> A\"\napply (rule conjI)\napply simp_all\ndone\n\nlemma \"\\<lbrakk>\\<forall> xs \\<in> A. \\<exists> ys. xs = ys @ ys; us \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists> n. List.length us = n + n\"\n  by fastforce\n    \nlemma \"\\<lbrakk>\\<forall> x y. T x y \\<or> T y x; \\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y; \\<forall> x y. T x y \\<longrightarrow> A x y \\<rbrakk> \\<Longrightarrow> \n\\<forall> x y. A x y \\<longrightarrow> T x y\" by blast\n\nlemma \"\\<lbrakk> xs @ ys = ys @ xs; length xs = length ys \\<rbrakk> \\<Longrightarrow> xs = ys\"\nby (metis append_eq_conv_conj)\n\nlemma \"\\<lbrakk> (a::nat)\\<le>x+b; 2*x < c\\<rbrakk> \\<Longrightarrow> 2*a +1 \\<le> 2*b +c \" by arith\n\nlemma \"\\<lbrakk> (a::nat) \\<le> b; b\\<le>c; c\\<le>d; d\\<le>e\\<rbrakk> \\<Longrightarrow> a\\<le>e\"\napply (blast intro:le_trans)\ndone\n\nthm conjI[OF refl[of \"a\"] refl[of \"b\"]]\n\nlemma \"Suc (Suc (Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\" by (blast dest:Suc_leD)\n\ninductive ev :: \"nat\\<Rightarrow>bool\" where \nev0 : \"ev 0\"\n| evSS : \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nfun evn:: \"nat\\<Rightarrow>bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev (Suc (Suc (Suc (Suc 0))))\"\napply (rule evSS)\napply (rule evSS)\napply (rule ev0)\ndone\n\nlemma \"ev n \\<Longrightarrow> evn n\"\napply(induction rule:ev.induct)\napply(auto)\ndone\n\nlemma \"evn n \\<Longrightarrow> ev n\"\napply(induction n rule: evn.induct)\napply(simp_all)\napply(rule ev0)\napply(rule evSS)\napply(simp)\ndone\n\ninductive star:: \"('a\\<Rightarrow>'a\\<Rightarrow>bool)\\<Rightarrow>'a\\<Rightarrow>'a\\<Rightarrow>bool\" for r where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\napply(induction rule:star.induct)\napply(assumption)\napply(metis step)\ndone\n\nlemma star_rev: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\napply(induction rule:star.induct)\napply(rule step)\napply(simp_all)\napply(rule refl)\napply(rule step)\napply(simp_all)\ndone\n\n(* exercise 3.2 *)\n\ninductive palindrome:: \"'a list \\<Rightarrow> bool\" where\nempty_p: \"palindrome []\" |\nsingle_p: \"palindrome [x]\" |\nstep_p: \"palindrome xs \\<Longrightarrow> palindrome (a # (xs@[a]))\"\n\n(* exercise 3.3 *)\ninductive star':: \"('a\\<Rightarrow>'a\\<Rightarrow>bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\nrefl': \"star' r x x\" |\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\napply(induction rule:star'.induct)\napply(rule refl)\napply(simp add:star_rev)\ndone\n\nlemma star'_rev : \"star' r y z  \\<Longrightarrow>  r x y  \\<Longrightarrow>  star' r x z\"\napply(induction rule: star'.induct)\napply(auto intro: step' refl')\ndone\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\napply(induction rule:star.induct)\napply(rule refl')\napply(auto simp add:star'_rev)\ndone\n\n(* exercise 3.4 TODO *)\n(* inductive iter:: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where *)\n\n(* exercise 3.5 TODO *)\n\nend", "meta": {"author": "The-Wallfacer-Plan", "repo": "yes-isabelle", "sha": "0ead6c036a3e6f0e06c46d8fbbd7ea802af1db8f", "save_path": "github-repos/isabelle/The-Wallfacer-Plan-yes-isabelle", "path": "github-repos/isabelle/The-Wallfacer-Plan-yes-isabelle/yes-isabelle-0ead6c036a3e6f0e06c46d8fbbd7ea802af1db8f/tutorials/prog_prov_ch03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127603871312, "lm_q2_score": 0.8840392924390585, "lm_q1q2_score": 0.7548924324973227}}
{"text": "(*<*)\ntheory tmpl05\n  imports\n    Complex_Main\n    \"HOL-Library.Tree\"\nbegin\n(*>*)\n\n\ntext {* \\ExerciseSheet{5}{11.~5.~2017} *}\n\ntext \\<open>\n  \\<^item> Import \\<open>Complex_Main\\<close> and \\<open>HOL-Library.Tree\\<close>\n  \\<^item> For this exercise sheet (and Homework 1), you are not allowed to use sledgehammer!\n    Proofs using the \\<open>smt, metis, meson, or moura\\<close> methods are forbidden!\n\\<close>\n\ntext \\<open>\n  \\Exercise{Bounding power-of-two by factorial}\n  Prove that, for all natural numbers $n>3$, we have $2^n < n!$.\n  We have already prepared the proof skeleton for you.\n\\<close>\nlemma exp_fact_estimate: \"n>3 \\<Longrightarrow> (2::nat)^n < fact n\"\nproof (induction n)\n  case 0 then show ?case by auto\nnext\n  case (Suc n)\n  assume IH: \"3 < n \\<Longrightarrow> (2::nat) ^ n < fact n\"\n  assume PREM: \"3 < Suc n\"\n  show \"(2::nat) ^ Suc n < fact (Suc n)\"\n    text \\<open>Fill in a proof here. Hint: Start with a case distinction\n      whether \\<open>n>3\\<close> or \\<open>n=3\\<close>. \\<close>\n    sorry\nqed\n\ntext \\<open>\n  \\vspace{1em}\n  {\\bfseries Warning!}\n  Make sure that your numerals have the right type, otherwise\n  proofs will not work! To check the type of a numeral, hover the mouse over\n  it with pressed CTRL (Mac: CMD) key. Example:\n\\<close>\nlemma \"2^n \\<le> 2^Suc n\"\n  apply auto oops -- \\<open>Leaves the subgoal \\<open>2 ^ n \\<le> 2 * 2 ^ n\\<close>\\<close>\n  text \\<open>You will find out that the numeral \\<open>2\\<close> has type @{typ 'a},\n    for which you do not have any ordering laws. So you have to\n    manually restrict the numeral's type to, e.g., @{typ nat}.\\<close>\nlemma \"(2::nat)^n \\<le> 2^Suc n\" by simp -- \\<open>Note: Type inference will\n  infer \\<open>nat\\<close> for the unannotated numeral, too. Use CTRL+hover to double check!\\<close>\n\ntext \\<open>\n  \\vspace{1em}\n\\<close>\n\ntext \\<open>\\Exercise{Sum Squared is Sum of Cubes}\n  \\<^item> Define a recursive function $sumto~f~n = \\sum_{i=0\\ldots n} f(i)$.\n  \\<^item> Show that $\\left(\\sum_{i=0\\ldots n}i\\right)^2 = \\sum_{i=0\\ldots n} i^3$.\n\\<close>\n\n\nfun sumto :: \"(nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n\"sumto f 0 = 0\"\n\ntext \\<open>You may need the following lemma:\\<close>\nlemma sum_of_naturals: \"2 * sumto (\\<lambda>x. x) n = n * Suc n\"\n  (*by (induction n) auto*) oops\n\nlemma \"sumto (\\<lambda>x. x) n ^ 2 = sumto (\\<lambda>x. x^3) n\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n)\n  assume IH: \"(sumto (\\<lambda>x. x) n)\\<^sup>2 = sumto (\\<lambda>x. x ^ 3) n\"\n  note [simp] = algebra_simps -- \\<open>Extend the simpset only in this block\\<close>\n  show \"(sumto (\\<lambda>x. x) (Suc n))\\<^sup>2 = sumto (\\<lambda>x. x ^ 3) (Suc n)\"\n  text \\<open>Insert a proof here\\<close>\n    sorry\nqed\n\ntext \\<open>\n  \\Exercise{Paths in Graphs}\n  A graph is described by its adjacency matrix, i.e., \\<open>G :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>.\n\n  Define a predicate \\<open>path G u p v\\<close> that is true if \\<open>p\\<close> is a path from\n  \\<open>u\\<close> to \\<open>v\\<close>, i.e., \\<open>p\\<close> is a list of nodes, not including \\<open>u\\<close>, such that\n  the nodes on the path are connected with edges.\n  In other words, \\<open>path G u (p\\<^sub>1\\<dots>p\\<^sub>n) v\\<close>, iff \\<open>G u p\\<^sub>1\\<close>, \\<open>G p\\<^sub>i p\\<^sub>i\\<^sub>+\\<^sub>1\\<close>,\n  and \\<open>p\\<^sub>n = v\\<close>. For the empty path (\\<open>n=0\\<close>), we have \\<open>u=v\\<close>.\n\\<close>\n\nfun path :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a list \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  where\n  \"path _ _ _ _ \\<longleftrightarrow> False\"\n\ntext \\<open>Test cases\\<close>\ndefinition \"nat_graph x y \\<longleftrightarrow> y=Suc x\"\nvalue \\<open>path nat_graph 2 [] 2\\<close>\nvalue \\<open>path nat_graph 2 [3,4,5] 5\\<close>\nvalue \\<open>\\<not> path nat_graph 3 [3,4,5] 6\\<close>\nvalue \\<open>\\<not> path nat_graph 2 [3,4,5] 6\\<close>\n\ntext \\<open>Show the following lemma, that decomposes paths. Register it as simp-lemma.\\<close>\nlemma path_append[simp]: \"path G u (p1@p2) v \\<longleftrightarrow> (\\<exists>w. path G u p1 w \\<and> path G w p2 v)\"\n  oops\n\ntext \\<open>\n  Show that, for a non-distinct path from \\<open>u\\<close> to \\<open>v\\<close>,\n  we find a longer non-distinct path from \\<open>u\\<close> to \\<open>v\\<close>.\n  Note: This can be seen as a simple pumping-lemma,\n  allowing to pump the length of the path.\n\n  Hint: Theorem @{thm [source] not_distinct_decomp}.\n\\<close>\nlemma pump_nondistinct_path:\n  assumes P: \"path G u p v\"\n  assumes ND: \"\\<not>distinct p\"\n  shows \"\\<exists>p'. length p' > length p \\<and> \\<not>distinct p' \\<and> path G u p' v\"\n  oops\n\n\ntext \\<open>\n  \\NumHomework{Split Lists}{May 18}\n  Recall: Use Isar where appropriate, proofs using\n    \\<open>metis, smt, meson, or moura\\<close> (as generated by sledgehammer) are forbidden!\n\n  Show that every list can be split into a prefix and a suffix,\n  such that the length of the prefix is \\<open>1/n\\<close> of the original lists's length.\n\n\\<close>\n\nlemma\n  assumes \"n\\<ge>0\" -- \\<open>Note: This assumption is actually not needed,\n    as @{lemma \"n div 0 = 0\" by auto}, so don't be puzzled if you do\n    not use it at all in your proof.\\<close>\n  shows \"\\<exists>ys zs. length ys = length xs div n \\<and> xs=ys@zs\"\n  oops\n\ntext \\<open>\n  \\NumHomework{Estimate Recursion Equation}{May 18}\n\n  (Sledgehammer allowed again)\n\n  Show that the function defined by \\<open>a 0 = 0\\<close> and \\<open>a (n+1) = (a n)\\<^sup>2 + 1\\<close>\n  is bounded by the double-exponential function \\<open>2^(2^n)\\<close>\n\\<close>\n\nfun a :: \"nat \\<Rightarrow> int\" where\n\"a 0 = 0\" |\n\"a (Suc n) = a n ^ 2 + 1\"\n\ntext \\<open>\n  We have given you a proof skeleton, setting up the induction.\n  To complete your proof, you should come up with a chain of inequations.\n  You may try to solve the intermediate steps with sledgehammer.\n\n  Hint: It is a bit tricky to get the approximation right.\n    We strongly recommend to sketch the inequations on paper first.\n\n  Hint: Have a look at the lemma @{thm [source] power_mono}, in particular its\n  instance for squares:\n\\<close>\n\nthm power_mono[where n=2]\n\nlemma \"a n \\<le> 2 ^ (2 ^ n) - 1\"\nproof(induction n)\n  case 0 thus ?case by simp\nnext\n  case (Suc n)\n  assume IH: \"a n \\<le> 2 ^ 2 ^ n - 1\"\n    -- \\<open>Refer to the induction hypothesis by name \\<open>IH\\<close> or \\<open>Suc.IH\\<close>\\<close>\n  show \"a (Suc n) \\<le> 2 ^ 2 ^ Suc n - 1\"\n  proof -\n    text \\<open>Insert your proof here\\<close>\n    show ?thesis sorry\n  qed\nqed\n\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "amartyads", "repo": "functional-data-structures-HW", "sha": "df9edfd02bda931a0633f0e66bf8e32d7347902b", "save_path": "github-repos/isabelle/amartyads-functional-data-structures-HW", "path": "github-repos/isabelle/amartyads-functional-data-structures-HW/functional-data-structures-HW-df9edfd02bda931a0633f0e66bf8e32d7347902b/05/tmpl05.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267864276107, "lm_q2_score": 0.8688267830311354, "lm_q1q2_score": 0.7548599818631803}}
{"text": "(*  \n    Author:      René Thiemann \n    License:     BSD\n*)\nsubsection \\<open>Fundamental Theorem of Algebra for Factorizations\\<close>\n\ntext \\<open>Via the existing formulation of the fundamental theorem of algebra,\n  we prove that we always get a linear factorization of a complex polynomial.\n  Using this factorization we show that root-square-freeness of complex polynomial\n  is identical to the statement that the cardinality of the set of all roots \n  is equal to the degree of the polynomial.\\<close>\n\ntheory Fundamental_Theorem_Algebra_Factorized\nimports \n  Order_Polynomial\n  \"HOL-Computational_Algebra.Fundamental_Theorem_Algebra\"\nbegin\n\nlemma fundamental_theorem_algebra_factorized: fixes p :: \"complex poly\"\n  shows \"\\<exists> as. smult (coeff p (degree p)) (\\<Prod> a \\<leftarrow> as. [:- a, 1:]) = p \\<and> length as = degree p\"\nproof -\n  define n where \"n = degree p\"\n  have \"degree p = n\" unfolding n_def by simp\n  thus ?thesis\n  proof (induct n arbitrary: p)\n    case (0 p)\n    hence \"\\<exists> c. p = [: c :]\" by (cases p, auto split: if_splits)\n    thus ?case by (intro exI[of _ Nil], auto)\n  next\n    case (Suc n p)\n    have dp: \"degree p = Suc n\" by fact\n    hence \"\\<not> constant (poly p)\" by (simp add: constant_degree)\n    from fundamental_theorem_of_algebra[OF this] obtain c where rt: \"poly p c = 0\" by auto\n    hence \"[:-c,1 :] dvd p\" by (simp add: dvd_iff_poly_eq_0)\n    then obtain q where p: \"p = q * [: -c,1 :]\" by (metis dvd_def mult.commute)\n    from \\<open>degree p = Suc n\\<close> have dq: \"degree q = n\" using p\n      by simp (metis add.right_neutral degree_synthetic_div diff_Suc_1 mult.commute mult_left_cancel p pCons_eq_0_iff rt synthetic_div_correct' zero_neq_one) \n    from Suc(1)[OF this] obtain as where q: \"[:coeff q (degree q):] * (\\<Prod>a\\<leftarrow>as. [:- a, 1:]) = q\"\n      and deg: \"length as = degree q\" by auto\n    have dc: \"degree p = degree q + degree [: -c, 1 :]\" unfolding dq dp by simp\n    have cq: \"coeff q (degree q) = coeff p (degree p)\" unfolding dc unfolding p coeff_mult_degree_sum unfolding dq by simp\n    show ?case using p[unfolded q[unfolded cq, symmetric]] \n      by (intro exI[of _ \"c # as\"], auto simp: ac_simps, insert deg dc, auto)\n  qed\nqed\n\nlemma rsquarefree_card_degree: assumes p0: \"(p :: complex poly) \\<noteq> 0\"\n  shows \"rsquarefree p = (card {x. poly p x = 0} = degree p)\"\nproof -\n  from fundamental_theorem_algebra_factorized[of p] obtain c as\n    where p: \"p = smult c (\\<Prod> a \\<leftarrow> as. [:- a, 1:])\" and pas: \"degree p = length as\"\n    and c: \"c = coeff p (degree p)\" by metis\n  let ?prod = \"(\\<Prod>a\\<leftarrow>as. [:- a, 1:])\"\n  from p0 have c: \"c \\<noteq> 0\" unfolding c by auto\n  have roots: \"{x. poly p x = 0} = set as\" unfolding p poly_smult_zero_iff poly_prod_list prod_list_zero_iff\n    using c by auto\n  have idr: \"(card {x. poly p x = 0} = degree p) = distinct as\" unfolding roots pas\n    using card_distinct distinct_card by blast\n  have id: \"\\<And> q. (p \\<noteq> 0 \\<and> q) = q\" using p0 by simp\n  have dist: \"distinct as = (\\<forall>a. (\\<Sum>x\\<leftarrow>as. if x = a then 1 else 0) \\<le> Suc 0)\" (is \"?l = (\\<forall> a. ?r a)\")\n  proof (cases \"distinct as\")\n    case False\n    from not_distinct_decomp[OF this] obtain xs ys zs a where \"as = xs @ [a] @ ys @ [a] @ zs\" by auto\n    hence \"\\<not> ?r a\" by auto\n    thus ?thesis using False by auto\n  next\n    case True\n    {\n      fix a\n      from True have \"?r a\"\n      proof (induct as)\n        case (Cons b bs)\n        show ?case\n        proof (cases \"a = b\")\n          case False\n          with Cons show ?thesis by auto\n        next\n          case True\n          with Cons(2) have \"a \\<notin> set bs\" by auto\n          hence \"(\\<Sum>x\\<leftarrow> bs. if x = a then 1 else 0) = (0 :: nat)\" by (induct bs, auto)\n          thus ?thesis unfolding True by auto\n        qed\n      qed simp\n    }\n    thus ?thesis using True by auto\n  qed\n  have \"rsquarefree p = distinct as\" unfolding rsquarefree_def' id unfolding p order_smult[OF c]\n    by (subst order_prod_list, auto simp: o_def order_linear' dist)\n  thus ?thesis unfolding idr by simp\nqed\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Polynomial_Factorization/Fundamental_Theorem_Algebra_Factorized.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267728417087, "lm_q2_score": 0.8688267864276108, "lm_q1q2_score": 0.7548599730103336}}
{"text": "theory Homework5_1sol\nimports Main\nbegin\n\n  (*\n    ISSUED: Wednesday, October 18\n    DUE: Wednesday, October 25, 11:59pm\n    POINTS: 5\n  *)\n\n  (*\n    Recall the LTS formalization from the tutorial. \n    I copied the important parts here:\n  *)\n  \nsection \\<open>Parts of LTS from Tutorial\\<close>  \ntype_synonym ('q,'a) lts = \"'q \\<Rightarrow> 'a \\<Rightarrow> 'q \\<Rightarrow> bool\"\n\n\ninductive word :: \"('q,'a) lts \\<Rightarrow> 'q \\<Rightarrow> 'a list \\<Rightarrow> 'q \\<Rightarrow> bool\" \n  where\n    empty: \"word L q [] q\"\n  | cons: \"\\<lbrakk> L p a q; word L q as r \\<rbrakk> \\<Longrightarrow> word L p (a#as) r\"\n\nlemma word_Nil_conv: \"word L p [] q \\<longleftrightarrow> p=q\"\n  by (auto elim: word.cases intro: word.intros)\n  \nlemma word_Cons_conv: \"word L p (a#bs) r \\<longleftrightarrow> (\\<exists>q. L p a q \\<and> word L q bs r)\"\n  by (auto elim: word.cases intro: word.intros)\n  \nlemma word_append_conv: \"word L p (as@bs) r \\<longleftrightarrow> (\\<exists>q. word L p as q \\<and> word L q bs r)\"\n  (* Slightly changed proof compared to tutorial *)\n  by (induction as arbitrary: p) (auto simp: word_Nil_conv word_Cons_conv)\n\nsection \\<open>Product Construction\\<close>  \n(* Here starts the homework assignment *)  \n  \n(*\n  For a labeled transition system, we define the language\n  from state p to state q as the set of all words from p to q. \n*)\ndefinition \"lang L p q = {w. word L p w q}\"  \n\n\n(*\n  The product \"prod L1 L2\" of two labeled transition systems L1 :: ('p,'a) lts \n  and L2 :: ('q,'a) lts is a labeled transition system over states of\n  type 'p\\<times>'q. We define (prod L1 L2) (p1,q1) a (p2,q2) iff \n  L1 p1 a p2 and L2 q1 a q2.\n*)\ndefinition L_prod :: \"('p,'a) lts \\<Rightarrow> ('q,'a) lts \\<Rightarrow> ('p\\<times>'q,'a) lts\" where\n  \"L_prod L1 L2 \\<equiv> \\<lambda>(p1,p2) l (q1,q2). L1 p1 l q1 \\<and> L2 p2 l q2\"\n\n(*\n  Intuitively, a transition of the product corresponds to a transition \n  of both components, with the same label.\n*)  \n\n(*\n  Show that the language of the product LTS corresponds to the \n  intersection of the languages of the component LTSs.\n  \n  Proof sketch:\n    assume we have a word w in the product language.\n    hence, we have \"word (L_prod L1 L2) (p1, p2) w (q1, q2)\"\n    by induction on w, we get word L1 p1 w q1 and word L2 p2 w q2\n    from which, by definition of lang, we get the proposition.\n  \n    the proof of the other direction is symmetric.\n    \n  Use an Isar proof! Note: There is no notion of \"symmetric\" in Isar, so \n    you will have to actually prove both directions.\n    \n  Hint: In the induction proofs, use the structural equations  \n     word_Cons_conv word_Nil_conv as simp rules, rather than \n     the word.intros and word.cases rules. \n     Don't forget to generalize over some variables!\n    \n*)\n\n  lemma \"lang (L_prod L1 L2) (p1,p2) (q1,q2) = (lang L1 p1 q1 \\<inter> lang L2 p2 q2)\"\n  proof (intro equalityI subsetI)  \n    fix w\n    assume \"w \\<in> lang (L_prod L1 L2) (p1, p2) (q1, q2)\" \n    hence \"word (L_prod L1 L2) (p1, p2) w (q1, q2)\" by (auto simp: lang_def)\n    hence \"word L1 p1 w q1 \\<and> word L2 p2 w q2\"\n      by (induction w arbitrary: p1 p2) (auto simp: word_Cons_conv word_Nil_conv L_prod_def)\n    thus \"w \\<in> lang L1 p1 q1 \\<inter> lang L2 p2 q2\"\n      by (auto simp: lang_def)\n  next\n    fix w\n    assume \"w \\<in> lang L1 p1 q1 \\<inter> lang L2 p2 q2\"\n    hence \"word L1 p1 w q1\" \"word L2 p2 w q2\" by (auto simp: lang_def)\n    hence \"word (L_prod L1 L2) (p1, p2) w (q1, q2)\"\n      by (induction w arbitrary: p1 p2) (auto simp: word_Cons_conv word_Nil_conv L_prod_def)\n    thus \"w \\<in> lang (L_prod L1 L2) (p1, p2) (q1, q2)\" by (auto simp: lang_def) \n  qed\n\nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/Homeworks/Homework5_1sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972717658209, "lm_q2_score": 0.8670357598021707, "lm_q1q2_score": 0.7548389670071755}}
{"text": "theory AExp\nimports Main\nbegin\n\nsubsection \"Arithmetic Expressions\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ntext_raw{*\\snip{AExpaexpdef}{2}{1}{% *}\ndatatype aexp = N int | V vname | Plus aexp aexp\ntext_raw{*}%endsnip*}\n\ntext_raw{*\\snip{AExpavaldef}{1}{2}{% *}\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\ntext_raw{*}%endsnip*}\n\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\ntext {* The same state more concisely: *}\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext {* A little syntax magic to write larger states compactly: *}\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\n*}\nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\n\ntext {* In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n*}\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext{* Note that this @{text\"<\\<dots>>\"} syntax works for any function space\n@{text\"\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\"} where @{text \"\\<tau>\\<^sub>2\"} has a @{text 0}. *}\n\n\nsubsection \"Constant Folding\"\n\ntext{* Evaluate constant subsexpressions: *}\n\ntext_raw{*\\snip{AExpasimpconstdef}{0}{2}{% *}\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a\\<^sub>1 a\\<^sub>2) =\n  (case (asimp_const a\\<^sub>1, asimp_const a\\<^sub>2) of\n    (N n\\<^sub>1, N n\\<^sub>2) \\<Rightarrow> N(n\\<^sub>1+n\\<^sub>2) |\n    (b\\<^sub>1,b\\<^sub>2) \\<Rightarrow> Plus b\\<^sub>1 b\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntheorem aval_asimp_const:\n  \"aval (asimp_const a) s = aval a s\"\napply(induction a)\napply (auto split: aexp.split)\ndone\n\ntext{* Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors: *}\n\ntext_raw{*\\snip{AExpplusdef}{0}{2}{% *}\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\ntext_raw{*}%endsnip*}\n\nlemma aval_plus[simp]:\n  \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\napply(induction a1 a2 rule: plus.induct)\napply simp_all (* just for a change from auto *)\ndone\n\ntext_raw{*\\snip{AExpasimpdef}{2}{0}{% *}\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw{*}%endsnip*}\n\ntext{* Note that in @{const asimp_const} the optimized constructor was\ninlined. Making it a separate function @{const plus} improves modularity of\nthe code and the proofs. *}\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]:\n  \"aval (asimp a) s = aval a s\"\napply(induction a)\napply simp_all\ndone\n\nend", "meta": {"author": "sseefried", "repo": "concrete-semantics-solutions", "sha": "ca562994bc36b2d9c9e6047bf481056e0be7bbcd", "save_path": "github-repos/isabelle/sseefried-concrete-semantics-solutions", "path": "github-repos/isabelle/sseefried-concrete-semantics-solutions/concrete-semantics-solutions-ca562994bc36b2d9c9e6047bf481056e0be7bbcd/AExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8723473779969194, "lm_q1q2_score": 0.7547759628475335}}
{"text": "(* Title: Group_Divisible_Designs.thy\n   Author: Chelsea Edmonds\n*)\n\nsection \\<open>Group Divisible Designs\\<close>\ntext \\<open>Definitions in this section taken from the handbook \\<^cite>\\<open>\"colbournHandbookCombinatorialDesigns2007\"\\<close>\nand Stinson \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>\\<close>\ntheory Group_Divisible_Designs imports Resolvable_Designs\nbegin\n\nsubsection \\<open>Group design\\<close>\ntext \\<open>We define a group design to have an additional paramater $G$ which is a partition on the point \nset $V$. This is not defined in the handbook, but is a precursor to GDD's without index constraints\\<close>\n\nlocale group_design = proper_design + \n  fixes groups :: \"'a set set\" (\"\\<G>\")\n  assumes group_partitions: \"partition_on \\<V> \\<G>\"\n  assumes groups_size: \"card \\<G> > 1\" \nbegin\n\nlemma groups_not_empty: \"\\<G> \\<noteq> {}\"\n  using groups_size by auto\n\nlemma num_groups_lt_points: \"card \\<G> \\<le> \\<v>\"\n  by (simp add: partition_on_le_set_elements finite_sets group_partitions) \n\nlemma groups_disjoint: \"disjoint \\<G>\"\n  using group_partitions partition_onD2 by auto\n\nlemma groups_disjoint_pairwise: \"G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> disjnt G1 G2\"\n  using group_partitions partition_onD2 pairwiseD by fastforce \n\nlemma point_in_one_group: \"x \\<in> G1 \\<Longrightarrow> G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> x \\<notin> G2\"\n  using groups_disjoint_pairwise by (simp add: disjnt_iff) \n\nlemma point_has_unique_group: \"x \\<in> \\<V> \\<Longrightarrow> \\<exists>!G. x \\<in> G \\<and> G \\<in> \\<G>\"\n  using partition_on_partition_on_unique group_partitions\n  by fastforce \n\nlemma rep_number_point_group_one: \n  assumes \"x \\<in> \\<V>\"\n  shows  \"card {g \\<in> \\<G> . x \\<in> g} = 1\" \nproof -\n  obtain g' where \"g' \\<in> \\<G>\" and \"x \\<in> g'\"\n    using assms point_has_unique_group by blast \n  then have \"{g \\<in> \\<G> . x \\<in> g} = {g'}\"\n    using  group_partitions partition_onD4 by force \n  thus ?thesis\n    by simp \nqed\n\nlemma point_in_group: \"G \\<in> \\<G> \\<Longrightarrow> x \\<in> G \\<Longrightarrow> x \\<in> \\<V>\"\n  using group_partitions partition_onD1 by auto \n\nlemma point_subset_in_group: \"G \\<in> \\<G> \\<Longrightarrow> ps \\<subseteq> G \\<Longrightarrow> ps \\<subseteq> \\<V>\"\n  using point_in_group by auto\n\nlemma group_subset_point_subset: \"G \\<in> \\<G> \\<Longrightarrow> G' \\<subseteq> G \\<Longrightarrow> ps \\<subseteq> G' \\<Longrightarrow> ps \\<subseteq> \\<V>\"\n  using point_subset_in_group by auto\n\nlemma groups_finite: \"finite \\<G>\"\n  using finite_elements finite_sets group_partitions by auto\n\nlemma group_elements_finite: \"G \\<in> \\<G> \\<Longrightarrow> finite G\"\n  using groups_finite finite_sets group_partitions\n  by (meson finite_subset point_in_group subset_iff)\n\nlemma v_equals_sum_group_sizes: \"\\<v> = (\\<Sum>G \\<in> \\<G>. card G)\"\n  using group_partitions groups_disjoint partition_onD1 card_Union_disjoint group_elements_finite \n  by fastforce \n\nlemma gdd_min_v: \"\\<v> \\<ge> 2\"\nproof - \n  have assm: \"card \\<G> \\<ge> 2\" using groups_size by simp\n  then have \"\\<And> G . G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}\" using partition_onD3 group_partitions by auto\n  then have \"\\<And> G . G \\<in> \\<G> \\<Longrightarrow> card G \\<ge> 1\"\n    using group_elements_finite card_0_eq by fastforce \n  then have \" (\\<Sum>G \\<in> \\<G>. card G) \\<ge> 2\" using assm\n    using sum_mono by force \n  thus ?thesis using v_equals_sum_group_sizes\n    by linarith \nqed\n\nlemma min_group_size: \"G \\<in> \\<G> \\<Longrightarrow> card G \\<ge> 1\"\n  using partition_onD3 group_partitions\n  using group_elements_finite not_le_imp_less by fastforce  \n\nlemma group_size_lt_v: \n  assumes \"G \\<in> \\<G>\"\n  shows \"card G < \\<v>\"\nproof - \n  have \"(\\<Sum>G' \\<in> \\<G>. card G') = \\<v>\" using gdd_min_v v_equals_sum_group_sizes\n    by linarith \n  then have split_sum: \"card G + (\\<Sum>G' \\<in> (\\<G> - {G}). card G') = \\<v>\" using assms sum.remove\n    by (metis groups_finite v_equals_sum_group_sizes) \n  have \"card (\\<G> - {G}) \\<ge> 1\" using groups_size\n    by (simp add: assms groups_finite)\n  then obtain G' where gin: \"G' \\<in> (\\<G> - {G})\"\n    by (meson elem_exists_non_empty_set less_le_trans less_numeral_extra(1)) \n  then have \"card G' \\<ge> 1\" using min_group_size by auto \n  then have \"(\\<Sum>G' \\<in> (\\<G> - {G}). card G') \\<ge> 1\"\n    by (metis gin finite_Diff groups_finite leI less_one sum_eq_0_iff) \n  thus ?thesis using split_sum\n    by linarith\nqed\n\nsubsubsection \\<open>Group Type\\<close>\n\ntext \\<open>GDD's have a \"type\", which is defined by a sequence of group sizes $g_i$, and the number \nof groups of that size $a_i$: $g_1^{a_1}g2^{a_2}...g_n^{a_n}$\\<close>\ndefinition group_sizes :: \"nat set\" where\n\"group_sizes \\<equiv> {card G | G . G \\<in> \\<G>}\"\n\ndefinition groups_of_size :: \"nat \\<Rightarrow> nat\" where\n\"groups_of_size g \\<equiv> card { G \\<in> \\<G> . card G = g }\"\n\ndefinition group_type :: \"(nat \\<times> nat) set\" where\n\"group_type \\<equiv> {(g, groups_of_size g) | g . g \\<in> group_sizes }\"\n\nlemma group_sizes_min: \"x \\<in> group_sizes \\<Longrightarrow> x \\<ge> 1 \" \n  unfolding group_sizes_def using min_group_size group_size_lt_v by auto \n\nlemma group_sizes_max: \"x \\<in> group_sizes \\<Longrightarrow> x < \\<v> \" \n  unfolding group_sizes_def using min_group_size group_size_lt_v by auto \n\nlemma group_size_implies_group_existance: \"x \\<in> group_sizes \\<Longrightarrow> \\<exists>G. G \\<in> \\<G> \\<and> card G = x\"\n  unfolding group_sizes_def by auto\n\nlemma groups_of_size_zero: \"groups_of_size 0 = 0\"\nproof -\n  have empty: \"{G \\<in> \\<G> . card G = 0} = {}\" using min_group_size\n    by fastforce \n  thus ?thesis unfolding groups_of_size_def\n    by (simp add: empty) \nqed\n\nlemma groups_of_size_max: \n  assumes \"g \\<ge> \\<v>\"\n  shows \"groups_of_size g = 0\"\nproof -\n  have \"{G \\<in> \\<G> . card G = g} = {}\" using group_size_lt_v assms by fastforce \n  thus ?thesis unfolding groups_of_size_def\n    by (simp add: \\<open>{G \\<in> \\<G>. card G = g} = {}\\<close>) \nqed\n\nlemma group_type_contained_sizes: \"(g, a) \\<in> group_type \\<Longrightarrow> g \\<in> group_sizes\" \n  unfolding group_type_def by simp\n\nlemma group_type_contained_count: \"(g, a) \\<in> group_type \\<Longrightarrow> card {G \\<in> \\<G> . card G = g} = a\"\n  unfolding group_type_def groups_of_size_def by simp\n\nlemma group_card_in_sizes: \"g \\<in> \\<G> \\<Longrightarrow> card g \\<in> group_sizes\"\n  unfolding group_sizes_def by auto\n\nlemma group_card_non_zero_groups_of_size_min: \n  assumes \"g \\<in> \\<G>\"\n  assumes \"card g = a\"\n  shows \"groups_of_size a \\<ge> 1\"\nproof - \n  have \"g \\<in> {G \\<in> \\<G> . card G = a}\" using assms by simp\n  then have \"{G \\<in> \\<G> . card G = a} \\<noteq> {}\" by auto\n  then have \"card {G \\<in> \\<G> . card G = a} \\<noteq> 0\"\n    by (simp add: groups_finite) \n  thus ?thesis unfolding groups_of_size_def by simp \nqed\n\nlemma elem_in_group_sizes_min_of_size: \n  assumes \"a \\<in> group_sizes\"\n  shows \"groups_of_size a \\<ge> 1\"\n  using assms group_card_non_zero_groups_of_size_min group_size_implies_group_existance by blast\n\nlemma group_card_non_zero_groups_of_size_max: \n  shows \"groups_of_size a \\<le> \\<v>\"\nproof -\n  have \"{G \\<in> \\<G> . card G = a} \\<subseteq> \\<G>\" by simp\n  then have \"card {G \\<in> \\<G> . card G = a} \\<le> card \\<G>\"\n    by (simp add: card_mono groups_finite)\n  thus ?thesis\n    using groups_of_size_def num_groups_lt_points by auto \nqed\n\nlemma group_card_in_type: \"g \\<in> \\<G> \\<Longrightarrow> \\<exists> x . (card g, x) \\<in> group_type \\<and> x \\<ge> 1\"\n  unfolding group_type_def using group_card_non_zero_groups_of_size_min\n  by (simp add: group_card_in_sizes)\n\nlemma partition_groups_on_size: \"partition_on \\<G> {{ G \\<in> \\<G> . card G = g } | g . g \\<in> group_sizes}\"\nproof (intro partition_onI, auto)\n  fix g\n  assume a1: \"g \\<in> group_sizes\"\n  assume \" \\<forall>x. x \\<in> \\<G> \\<longrightarrow> card x \\<noteq> g\"\n  then show False using a1 group_size_implies_group_existance by auto \nnext\n  fix x\n  assume \"x \\<in> \\<G>\"\n  then show \"\\<exists>xa. (\\<exists>g. xa = {G \\<in> \\<G>. card G = g} \\<and> g \\<in> group_sizes) \\<and> x \\<in> xa\"\n    using  group_card_in_sizes by auto \nqed\n\nlemma group_size_partition_covers_points: \"\\<Union>(\\<Union>{{ G \\<in> \\<G> . card G = g } | g . g \\<in> group_sizes}) = \\<V>\"\n  by (metis (no_types, lifting) group_partitions partition_groups_on_size partition_onD1)\n\nlemma groups_of_size_alt_def_count: \"groups_of_size g = count {# card G . G \\<in># mset_set \\<G> #} g\" \nproof -\n  have a: \"groups_of_size g =  card { G \\<in> \\<G> . card G = g }\" unfolding groups_of_size_def by simp\n  then have \"groups_of_size g =  size {# G \\<in># (mset_set \\<G>) . card G = g #}\"\n    using groups_finite by auto \n  then have size_repr: \"groups_of_size g =  size {# x \\<in># {# card G . G \\<in># mset_set \\<G> #} . x = g #}\"\n    using groups_finite by (simp add: filter_mset_image_mset)\n  have \"group_sizes = set_mset ({# card G . G \\<in># mset_set \\<G> #})\" \n    using group_sizes_def groups_finite by auto \n  thus ?thesis using size_repr by (simp add: count_size_set_repr) \nqed\n\nlemma v_sum_type_rep: \"\\<v> = (\\<Sum> g \\<in> group_sizes . g * (groups_of_size g))\"\nproof -\n  have gs: \"set_mset {# card G . G \\<in># mset_set \\<G> #} = group_sizes\" \n    unfolding group_sizes_def using groups_finite by auto \n  have \"\\<v> = card (\\<Union>(\\<Union>{{ G \\<in> \\<G> . card G = g } | g . g \\<in> group_sizes}))\"\n    using group_size_partition_covers_points by simp\n  have v1: \"\\<v> = (\\<Sum>x \\<in># {# card G . G \\<in># mset_set \\<G> #}. x)\"\n    by (simp add: sum_unfold_sum_mset v_equals_sum_group_sizes)\n  then have \"\\<v> = (\\<Sum>x \\<in> set_mset {# card G . G \\<in># mset_set \\<G> #} . x * (count {# card G . G \\<in># mset_set \\<G> #} x))\" \n    using mset_set_size_card_count by (simp add: v1)\n  thus ?thesis using gs groups_of_size_alt_def_count by auto \nqed\n\nend\n\nsubsubsection \\<open>Uniform Group designs\\<close>\ntext \\<open>A group design requiring all groups are the same size\\<close>\nlocale uniform_group_design = group_design + \n  fixes u_group_size :: nat (\"\\<m>\")\n  assumes uniform_groups: \"G \\<in> \\<G> \\<Longrightarrow> card G = \\<m>\"\n\nbegin\n\nlemma m_positive: \"\\<m> \\<ge> 1\"\nproof -\n  obtain G where \"G \\<in> \\<G>\" using groups_size elem_exists_non_empty_set gr_implies_not_zero by blast \n  thus ?thesis using uniform_groups min_group_size by fastforce\nqed\n\nlemma uniform_groups_alt: \" \\<forall> G \\<in> \\<G> . card G = \\<m>\"\n  using uniform_groups by blast \n\nlemma uniform_groups_group_sizes: \"group_sizes = {\\<m>}\"\n  using design_points_nempty group_card_in_sizes group_size_implies_group_existance \n    point_has_unique_group uniform_groups_alt by force\n\nlemma uniform_groups_group_size_singleton: \"is_singleton (group_sizes)\"\n  using uniform_groups_group_sizes by auto\n\nlemma set_filter_eq_P_forall:\"\\<forall> x \\<in> X . P x \\<Longrightarrow> Set.filter P X = X\"\n  by (simp add: Collect_conj_eq Int_absorb2 Set.filter_def subsetI)\n\nlemma uniform_groups_groups_of_size_m: \"groups_of_size \\<m> = card \\<G>\"\nproof(simp add: groups_of_size_def)\n  have \"{G \\<in> \\<G>. card G = \\<m>} = \\<G>\" using uniform_groups_alt set_filter_eq_P_forall by auto\n  thus \"card {G \\<in> \\<G>. card G = \\<m>} = card \\<G>\" by simp\nqed\n\nlemma uniform_groups_of_size_not_m: \"x \\<noteq> \\<m> \\<Longrightarrow> groups_of_size x = 0\"\n  by (simp add: groups_of_size_def card_eq_0_iff uniform_groups)\n\nend\n\nsubsection \\<open>GDD\\<close>\ntext \\<open>A GDD extends a group design with an additional index parameter.\nEach pair of elements must occur either \\Lambda times if in diff groups, or 0 times if in the same \ngroup\\<close>\n\nlocale GDD = group_design + \n  fixes index :: int (\"\\<Lambda>\")\n  assumes index_ge_1: \"\\<Lambda> \\<ge> 1\"\n  assumes index_together: \"G \\<in> \\<G> \\<Longrightarrow> x \\<in> G \\<Longrightarrow> y \\<in> G \\<Longrightarrow> x \\<noteq> y \\<Longrightarrow> \\<B> index {x, y} = 0\"\n  assumes index_distinct: \"G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> x \\<in> G1 \\<Longrightarrow> y \\<in> G2 \\<Longrightarrow> \n    \\<B> index {x, y} = \\<Lambda>\"\nbegin\n\nlemma points_sep_groups_ne: \"G1 \\<in> \\<G> \\<Longrightarrow> G2 \\<in> \\<G> \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> x \\<in> G1 \\<Longrightarrow> y \\<in> G2 \\<Longrightarrow> x \\<noteq> y\"\n  by (meson point_in_one_group)\n\nlemma index_together_alt_ss: \"ps \\<subseteq> G \\<Longrightarrow> G \\<in> \\<G> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0\"\n  using index_together by (metis card_2_iff insert_subset) \n\nlemma index_distinct_alt_ss: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> (\\<And> G . G \\<in> \\<G> \\<Longrightarrow> \\<not> ps \\<subseteq> G) \\<Longrightarrow> \n    \\<B> index ps = \\<Lambda>\"\n  using index_distinct by (metis card_2_iff empty_subsetI insert_subset point_has_unique_group) \n\nlemma gdd_index_options: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0 \\<or> \\<B> index ps = \\<Lambda>\"\n  using index_distinct_alt_ss index_together_alt_ss by blast\n\nlemma index_zero_implies_same_group: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0 \\<Longrightarrow> \n    \\<exists> G \\<in> \\<G> . ps \\<subseteq> G\" using index_distinct_alt_ss gr_implies_not_zero\n  by (metis index_ge_1 less_one of_nat_0 of_nat_1 of_nat_le_0_iff)\n\nlemma index_zero_implies_same_group_unique: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 0 \\<Longrightarrow> \n    \\<exists>! G \\<in> \\<G> . ps \\<subseteq> G\" \n  by (meson GDD.index_zero_implies_same_group GDD_axioms card_2_iff' group_design.point_in_one_group \n      group_design_axioms in_mono)\n\nlemma index_not_zero_impl_diff_group: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = \\<Lambda> \\<Longrightarrow>  \n    (\\<And> G . G \\<in> \\<G> \\<Longrightarrow> \\<not> ps \\<subseteq> G)\"\n  using index_ge_1 index_together_alt_ss by auto\n\nlemma index_zero_implies_one_group: \n  assumes \"ps \\<subseteq> \\<V>\" \n  and \"card ps = 2\" \n  and \"\\<B> index ps = 0\" \n  shows \"size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 1\"\nproof -\n  obtain G where ging: \"G \\<in> \\<G>\" and psin: \"ps \\<subseteq> G\" \n    using index_zero_implies_same_group groups_size assms by blast\n  then have unique: \"\\<And> G2 . G2 \\<in> \\<G> \\<Longrightarrow> G \\<noteq> G2 \\<Longrightarrow> \\<not> ps \\<subseteq> G2\" \n    using index_zero_implies_same_group_unique by (metis assms) \n  have \"\\<And> G'. G' \\<in> \\<G> \\<longleftrightarrow> G' \\<in># mset_set \\<G>\"\n    by (simp add: groups_finite) \n  then have eq_mset: \"{#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = mset_set {b \\<in> \\<G> . ps \\<subseteq> b}\"\n    using filter_mset_mset_set groups_finite by blast \n  then have \"{b \\<in> \\<G> . ps \\<subseteq> b} = {G}\" using unique psin\n    by (smt Collect_cong ging singleton_conv)\n  thus ?thesis by (simp add: eq_mset) \nqed\n\nlemma index_distinct_group_num_alt_def: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \n    size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 0 \\<Longrightarrow> \\<B> index ps = \\<Lambda>\"\n  by (metis gdd_index_options index_zero_implies_one_group numeral_One zero_neq_numeral)\n\nlemma index_non_zero_implies_no_group: \n  assumes \"ps \\<subseteq> \\<V>\" \n    and  \"card ps = 2\" \n    and \"\\<B> index ps = \\<Lambda>\" \n  shows \"size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 0\"\nproof -\n  have \"\\<And> G . G \\<in> \\<G> \\<Longrightarrow>  \\<not> ps \\<subseteq> G\" using index_not_zero_impl_diff_group assms by simp\n  then have \"{#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = {#}\"\n    using filter_mset_empty_if_finite_and_filter_set_empty by force\n  thus ?thesis by simp\nqed\n\nlemma gdd_index_non_zero_iff: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \n    \\<B> index ps = \\<Lambda> \\<longleftrightarrow> size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 0\"\n  using index_non_zero_implies_no_group index_distinct_group_num_alt_def by auto\n\nlemma gdd_index_zero_iff: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \n    \\<B> index ps = 0 \\<longleftrightarrow> size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 1\"\n  apply (auto simp add: index_zero_implies_one_group)\n  by (metis GDD.gdd_index_options GDD_axioms index_non_zero_implies_no_group old.nat.distinct(2))\n\nlemma points_index_upper_bound: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps \\<le> \\<Lambda>\"\n  using gdd_index_options index_ge_1\n  by (metis int_one_le_iff_zero_less le_refl of_nat_0 of_nat_0_le_iff of_nat_le_iff zero_less_imp_eq_int) \n\nlemma index_1_imp_mult_1: \n  assumes \"\\<Lambda> = 1\"\n  assumes \"bl \\<in># \\<B>\"\n  assumes \"card bl \\<ge> 2\"\n  shows \"multiplicity bl = 1\"\nproof (rule ccontr)\n  assume \"\\<not> (multiplicity bl = 1)\"\n  then have \"multiplicity bl \\<noteq> 1\" and \"multiplicity bl \\<noteq> 0\" using assms by simp_all \n  then have m: \"multiplicity bl \\<ge> 2\" by linarith\n  obtain ps where ps: \"ps \\<subseteq> bl \\<and> card ps = 2\"\n    using nat_int_comparison(3) obtain_subset_with_card_n by (metis assms(3))  \n  then have \"\\<B> index ps \\<ge> 2\"\n    using m points_index_count_min ps by blast\n  then show False using assms index_distinct ps antisym_conv2 not_numeral_less_zero \n      numeral_le_one_iff points_index_ps_nin semiring_norm(69) zero_neq_numeral\n    by (metis gdd_index_options int_int_eq int_ops(2))\nqed\n\nlemma simple_if_block_size_gt_2:\n  assumes \"\\<And> bl . card bl \\<ge> 2\"\n  assumes \"\\<Lambda> = 1\"\n  shows \"simple_design \\<V> \\<B>\"\n  using index_1_imp_mult_1 assms apply (unfold_locales)\n  by (metis card.empty not_numeral_le_zero) \n\nend\n\nsubsubsection \\<open>Sub types of GDD's\\<close>\n\ntext \\<open>In literature, a GDD is usually defined in a number of different ways, \nincluding factors such as block size limitations\\<close>\nlocale K_\\<Lambda>_GDD = K_block_design + GDD\n\nlocale k_\\<Lambda>_GDD = block_design + GDD\n\nsublocale k_\\<Lambda>_GDD \\<subseteq> K_\\<Lambda>_GDD \\<V> \\<B> \"{\\<k>}\" \\<G> \\<Lambda>\n  by (unfold_locales)\n\nlocale K_GDD = K_\\<Lambda>_GDD \\<V> \\<B> \\<K> \\<G> 1 \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and sizes (\"\\<K>\") and groups (\"\\<G>\")\n\nlocale k_GDD = k_\\<Lambda>_GDD \\<V> \\<B> \\<k> \\<G> 1 \n  for point_set (\"\\<V>\") and block_collection (\"\\<B>\") and u_block_size (\"\\<k>\") and groups (\"\\<G>\")\n\nsublocale k_GDD \\<subseteq> K_GDD \\<V> \\<B> \"{\\<k>}\" \\<G>\n  by (unfold_locales)\n\nlemma (in K_GDD) multiplicity_1:  \"bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2 \\<Longrightarrow> multiplicity bl = 1\"\n  using index_1_imp_mult_1 by simp\n\nlocale RGDD = GDD + resolvable_design\n\nsubsection \\<open>GDD and PBD Constructions\\<close>\ntext \\<open>GDD's are commonly studied alongside PBD's (pairwise balanced designs). Many constructions\nhave been developed for designs to create a GDD from a PBD and vice versa. In particular, \nWilsons Construction is a well known construction, which is formalised in this section. It\nshould be noted that many of the more basic constructions in this section are often stated without\nproof/all the necessary assumptions in textbooks/course notes.\\<close>\n\ncontext GDD\nbegin\n\nsubsubsection \\<open>GDD Delete Point construction\\<close>\nlemma delete_point_index_zero: \n  assumes \"G \\<in> {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\n  and \"y \\<in> G\" and \"z \\<in> G\" and \"z\\<noteq> y\"\nshows \"(del_point_blocks x) index {y, z} = 0\"\nproof -\n  have \"y \\<noteq> x\" using assms(1) assms(2) by blast \n  have \"z \\<noteq> x\" using assms(1) assms(3) by blast \n  obtain G' where ing: \"G' \\<in> \\<G>\" and ss: \"G \\<subseteq> G'\"\n    using assms(1) by auto\n  have \"{y, z} \\<subseteq> G\" by (simp add: assms(2) assms(3)) \n  then have \"{y, z} \\<subseteq> \\<V>\"\n    by (meson ss ing group_subset_point_subset) \n  then have \"{y, z} \\<subseteq> (del_point x)\"\n    using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> del_point_def by fastforce \n  thus ?thesis using delete_point_index_eq index_together\n    by (metis assms(2) assms(3) assms(4) in_mono ing ss) \nqed\n\nlemma delete_point_index: \n  assumes \"G1 \\<in> {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\n  assumes \"G2 \\<in> {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\n  assumes \"G1 \\<noteq> G2\" and \"y \\<in> G1\" and \"z \\<in> G2\"\n  shows \"del_point_blocks x index {y, z} = \\<Lambda>\"\nproof -\n  have \"y \\<noteq> x\" using assms by blast \n  have \"z \\<noteq> x\" using assms by blast \n  obtain G1' where ing1: \"G1' \\<in> \\<G>\" and t1: \"G1 = G1' - {x}\"\n    using assms(1) by auto\n  obtain G2' where ing2: \"G2' \\<in> \\<G>\" and t2: \"G2 = G2' - {x}\"\n    using assms(2) by auto\n  then have ss1: \"G1 \\<subseteq> G1'\" and ss2: \"G2 \\<subseteq> G2'\" using t1 by auto\n  then have \"{y, z} \\<subseteq> \\<V>\" using ing1 ing2 ss1 ss2 assms(4) assms(5)\n    by (metis empty_subsetI insert_absorb insert_subset point_in_group) \n  then have \"{y, z} \\<subseteq> del_point x\"\n    using \\<open>y \\<noteq> x\\<close> \\<open>z \\<noteq> x\\<close> del_point_def by auto \n  then have indx: \"del_point_blocks x index {y, z} = \\<B> index {y, z}\" \n    using delete_point_index_eq by auto\n  have \"G1' \\<noteq> G2'\" using assms t1 t2 by fastforce \n  thus ?thesis using index_distinct\n    using indx assms(4) assms(5) ing1 ing2 t1 t2 by auto \nqed\n\nlemma delete_point_group_size: \n  assumes \"{x} \\<in> \\<G> \\<Longrightarrow> card \\<G> > 2\" \n  shows \"1 < card {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}}\"\nproof (cases \"{x} \\<in> \\<G>\")\n  case True\n  then have \"\\<And> g . g \\<in> (\\<G> - {{x}}) \\<Longrightarrow> x \\<notin> g\"\n    by (meson disjnt_insert1 groups_disjoint pairwise_alt)\n  then have simpg: \"\\<And> g . g \\<in> (\\<G> - {{x}}) \\<Longrightarrow> g - {x} = g\"\n    by simp \n  have \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = {g - {x} |g. (g \\<in> \\<G> - {{x}})}\" using True\n    by force \n  then have \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = {g |g. (g \\<in> \\<G> - {{x}})}\" using simpg \n    by (smt (verit) Collect_cong)\n  then have eq: \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} =  \\<G> - {{x}}\" using set_self_img_compr by blast\n  have \"card (\\<G> - {{x}}) = card \\<G> - 1\" using True\n    by (simp add: groups_finite) \n  then show ?thesis using True assms eq diff_is_0_eq' by force \nnext\n  case False\n  then have \"\\<And>g' y. {x} \\<notin> \\<G> \\<Longrightarrow> g' \\<in> \\<G> \\<Longrightarrow> y \\<in> \\<G> \\<Longrightarrow> g' - {x} = y - {x} \\<Longrightarrow> g' = y\" \n    by (metis all_not_in_conv insert_Diff_single insert_absorb insert_iff points_sep_groups_ne)\n  then have inj: \"inj_on (\\<lambda> g . g - {x}) \\<G>\" by (simp add: inj_onI False) \n  have \"{g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = {g - {x} |g. g \\<in> \\<G>}\" using False by auto\n  then have \"card {g - {x} |g. g \\<in> \\<G> \\<and> g \\<noteq> {x}} = card \\<G>\" using inj groups_finite card_image\n    by (auto simp add: card_image setcompr_eq_image) \n  then show ?thesis using groups_size by presburger \nqed\n\nlemma GDD_by_deleting_point: \n  assumes \"\\<And>bl. bl \\<in># \\<B> \\<Longrightarrow> x \\<in> bl \\<Longrightarrow> 2 \\<le> card bl\"\n  assumes \"{x} \\<in> \\<G> \\<Longrightarrow> card \\<G> > 2\"\n  shows \"GDD (del_point x) (del_point_blocks x) {g - {x} | g . g \\<in> \\<G> \\<and> g \\<noteq> {x}} \\<Lambda>\"\nproof -\n  interpret pd: proper_design \"del_point x\" \"del_point_blocks x\"\n    using delete_point_proper assms by blast\n  show ?thesis using delete_point_index_zero delete_point_index assms delete_point_group_size\n    by(unfold_locales) (simp_all add: partition_on_remove_pt group_partitions index_ge_1 del_point_def)\nqed\n\nend\n\ncontext K_GDD begin \n\nsubsubsection \\<open>PBD construction from GDD\\<close>\ntext \\<open>Two well known PBD constructions involve taking a GDD and either combining the groups and\nblocks to form a new block collection, or by adjoining a point\\<close>\n\ntext \\<open>First prove that combining the groups and block set results in a constant index\\<close>\nlemma kgdd1_points_index_group_block: \n  assumes \"ps \\<subseteq> \\<V>\"\n  and \"card ps = 2\"\n  shows \"(\\<B> + mset_set \\<G>) index ps = 1\"\nproof -\n  have index1: \"(\\<And> G . G \\<in> \\<G> \\<Longrightarrow> \\<not> ps \\<subseteq> G) \\<Longrightarrow> \\<B> index ps = 1\"\n    using index_distinct_alt_ss assms by fastforce \n  have groups1: \"\\<B> index ps = 0 \\<Longrightarrow> size {#b \\<in>#  mset_set \\<G> . ps \\<subseteq> b#} = 1\"  \n    using index_zero_implies_one_group assms by simp \n  then have \"(\\<B> + mset_set \\<G>) index ps = size (filter_mset ((\\<subseteq>) ps) (\\<B> + mset_set \\<G>))\" \n    by (simp add: points_index_def)\n  thus ?thesis using index1 groups1 gdd_index_non_zero_iff gdd_index_zero_iff assms \n      gdd_index_options points_index_def filter_union_mset union_commute\n    by (smt (z3) empty_neutral(1) less_irrefl_nat nonempty_has_size of_nat_1_eq_iff) \nqed\n\ntext \\<open>Combining blocks and the group set forms a PBD\\<close>\nlemma combine_block_groups_pairwise: \"pairwise_balance \\<V> (\\<B> + mset_set \\<G>) 1\"\nproof -\n  let ?B = \"\\<B> + mset_set \\<G>\"\n  have ss: \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> G \\<subseteq> \\<V>\"\n    by (simp add: point_in_group subsetI)\n  have \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}\" using group_partitions\n    using partition_onD3 by auto \n  then interpret inc: design \\<V> ?B \n  proof (unfold_locales)\n    show \"\\<And>b. (\\<And>G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}) \\<Longrightarrow> b \\<in># \\<B> + mset_set \\<G> \\<Longrightarrow> b \\<subseteq> \\<V>\"\n      by (metis finite_set_mset_mset_set groups_finite ss union_iff wellformed)\n    show \"(\\<And>G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}) \\<Longrightarrow> finite \\<V>\" by (simp add: finite_sets)\n    show \"\\<And>bl. (\\<And>G. G \\<in> \\<G> \\<Longrightarrow> G \\<noteq> {}) \\<Longrightarrow> bl \\<in># \\<B> + mset_set \\<G> \\<Longrightarrow> bl \\<noteq> {}\"\n      using blocks_nempty groups_finite by auto\n  qed\n  show ?thesis proof (unfold_locales)\n    show \"inc.\\<b> \\<noteq> 0\" using b_positive by auto\n    show \"(1 ::nat) \\<le> 2\" by simp\n    show \"2 \\<le> inc.\\<v>\" by (simp add: gdd_min_v)\n    then show \"\\<And>ps. ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> (\\<B> + mset_set \\<G>) index ps = 1\" \n      using kgdd1_points_index_group_block by simp\n  qed\nqed\n\nlemma combine_block_groups_PBD:\n  assumes \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> card G \\<in> \\<K>\"\n  assumes \"\\<And> k . k \\<in> \\<K> \\<Longrightarrow> k \\<ge> 2\"\n  shows \"PBD \\<V> (\\<B> + mset_set \\<G>) \\<K>\"\nproof -\n  let ?B = \"\\<B> + mset_set \\<G>\"\n  interpret inc: pairwise_balance \\<V> ?B 1 using combine_block_groups_pairwise by simp\n  show ?thesis using assms block_sizes groups_finite positive_ints \n    by (unfold_locales) auto\nqed\n\ntext \\<open>Prove adjoining a point to each group set results in a constant points index\\<close>\nlemma kgdd1_index_adjoin_group_block:\n  assumes \"x \\<notin> \\<V>\"\n  assumes \"ps \\<subseteq> insert x \\<V>\"\n  assumes \"card ps = 2\"\n  shows \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = 1\"\nproof -\n  have \"inj_on ((insert) x) \\<G>\"\n    by (meson assms(1) inj_onI insert_ident point_in_group) \n  then have eq: \"mset_set {insert x g |g. g \\<in> \\<G>} = {# insert x g . g \\<in># mset_set \\<G>#}\"\n    by (simp add: image_mset_mset_set setcompr_eq_image)\n  thus ?thesis \n  proof (cases \"x \\<in> ps\")\n    case True\n    then obtain y where y_ps: \"ps = {x, y}\" using assms(3)\n      by (metis card_2_iff doubleton_eq_iff insertE singletonD)\n    then have ynex: \"y \\<noteq> x\" using assms by fastforce \n    have yinv: \"y \\<in> \\<V>\"\n      using assms(2) y_ps ynex by auto \n    have all_g: \"\\<And> g. g \\<in># (mset_set {insert x g |g. g \\<in> \\<G>}) \\<Longrightarrow> x \\<in> g\"\n      using eq by force\n    have iff: \"\\<And> g . g \\<in> \\<G> \\<Longrightarrow> y \\<in> (insert x g) \\<longleftrightarrow> y \\<in> g\" using ynex by simp \n    have b: \"\\<B> index ps = 0\"\n      using True assms(1) points_index_ps_nin by fastforce \n    then have \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = \n        (mset_set {insert x g |g. g \\<in> \\<G>}) index ps\"\n      using eq by (simp add: point_index_distrib)\n    also have  \"... = (mset_set {insert x g |g. g \\<in> \\<G>}) rep y\" using points_index_pair_rep_num\n      by (metis (no_types, lifting) all_g y_ps) \n    also have 0: \"... = card {b \\<in> {insert x g |g. g \\<in> \\<G>} . y \\<in> b}\" \n      by (simp add: groups_finite rep_number_on_set_def)\n    also have 1: \"... = card {insert x g |g. g \\<in> \\<G> \\<and> y \\<in> insert x g}\"\n      by (smt (verit) Collect_cong mem_Collect_eq)\n    also have 2: \" ... = card {insert x g |g. g \\<in> \\<G> \\<and> y \\<in> g}\" \n      using iff by metis \n    also have \"... = card {g \\<in> \\<G> . y \\<in> g}\" using 1 2 0 empty_iff eq groups_finite ynex insert_iff\n      by (metis points_index_block_image_add_eq points_index_single_rep_num rep_number_on_set_def)  \n    finally have \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = 1\" \n      using rep_number_point_group_one yinv by simp \n    then show ?thesis\n      by simp \n  next\n    case False\n    then have v: \"ps \\<subseteq> \\<V>\" using assms(2) by auto \n    then have \"(\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = (\\<B> + mset_set \\<G>) index ps\"\n      using eq by (simp add: points_index_block_image_add_eq False point_index_distrib) \n    then show ?thesis using v assms kgdd1_points_index_group_block by simp\n  qed\nqed\n\nlemma pairwise_by_adjoining_point: \n  assumes \"x \\<notin> \\<V>\"\n  shows \"pairwise_balance (add_point x) (\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}) 1\"\nproof -\n  let ?B = \"\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}\"\n  let ?V = \"add_point x\"\n  have vdef: \"?V = \\<V> \\<union> {x}\" using add_point_def by simp\n  show ?thesis unfolding add_point_def using finite_sets design_blocks_nempty \n  proof (unfold_locales, simp_all)\n    have \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> insert x G \\<subseteq> ?V\"\n      by (simp add: point_in_group subsetI vdef)\n    then have \"\\<And> G. G \\<in># (mset_set { insert x g | g. g \\<in> \\<G>}) \\<Longrightarrow> G \\<subseteq> ?V\"\n      by (smt (verit, del_insts) elem_mset_set empty_iff infinite_set_mset_mset_set mem_Collect_eq)\n    then show \"\\<And>b. b \\<in># \\<B> \\<or> b \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> b \\<subseteq> insert x \\<V>\" \n      using wellformed add_point_def by fastforce\n  next \n    have \"\\<And> G. G \\<in> \\<G> \\<Longrightarrow> insert x G \\<noteq> {}\" using group_partitions\n      using partition_onD3 by auto \n    then have gnempty: \"\\<And> G. G \\<in># (mset_set { insert x g | g. g \\<in> \\<G>}) \\<Longrightarrow> G \\<noteq> {}\"\n      by (smt (verit, del_insts) elem_mset_set empty_iff infinite_set_mset_mset_set mem_Collect_eq)\n    then show \"\\<And>bl. bl \\<in># \\<B> \\<or> bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> bl \\<noteq> {}\" \n      using blocks_nempty by auto\n  next\n    have \"card \\<V> \\<ge> 2\" using gdd_min_v by simp \n    then have \"card (insert x \\<V>) \\<ge> 2\"\n      by (meson card_insert_le dual_order.trans finite_sets) \n    then show \"2 \\<le> card (insert x \\<V>)\" by auto\n  next\n    show \"\\<And>ps. ps \\<subseteq> insert x \\<V> \\<Longrightarrow>\n          card ps = 2 \\<Longrightarrow> (\\<B> + mset_set {insert x g |g. g \\<in> \\<G>}) index ps = Suc 0\" \n      using kgdd1_index_adjoin_group_block by (simp add: assms) \n  qed\nqed\n\nlemma PBD_by_adjoining_point: \n  assumes \"x \\<notin> \\<V>\"\n  assumes \"\\<And> k . k \\<in> \\<K> \\<Longrightarrow> k \\<ge> 2\"\n  shows \"PBD (add_point x) (\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}) (\\<K> \\<union> {(card g) + 1 | g . g \\<in> \\<G>})\"\nproof -\n  let ?B = \"\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}\"\n  let ?V = \"(add_point x)\"\n  interpret inc: pairwise_balance ?V ?B 1 using pairwise_by_adjoining_point assms by auto \n  show ?thesis using  block_sizes positive_ints proof (unfold_locales)\n    have xg: \"\\<And> g. g \\<in> \\<G> \\<Longrightarrow> x \\<notin> g\"\n      using assms point_in_group by auto \n    have \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> card bl \\<in> \\<K>\" by (simp add: block_sizes) \n    have \"\\<And> bl . bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> bl \\<in> {insert x g | g . g \\<in> \\<G>}\"\n      by (simp add: groups_finite) \n    then have \"\\<And> bl . bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> \n      card bl \\<in>  {card g + 1 |g. g \\<in> \\<G>}\" \n    proof -\n      fix bl \n      assume \"bl \\<in># mset_set {insert x g |g. g \\<in> \\<G>}\"\n      then have \"bl \\<in> {insert x g | g . g \\<in> \\<G>}\" by (simp add: groups_finite)\n      then obtain g where gin: \"g \\<in> \\<G>\" and i: \"bl = insert x g\" by auto \n      thus \"card bl \\<in>  {(card g + 1) |g. g \\<in> \\<G>}\"\n        using gin group_elements_finite i xg by auto\n    qed\n    then show \"\\<And>bl. bl \\<in># \\<B> + mset_set {insert x g |g. g \\<in> \\<G>} \\<Longrightarrow> \n        (card bl) \\<in> \\<K> \\<union> {(card g + 1) |g. g \\<in> \\<G>}\"\n      using UnI1 UnI2 block_sizes union_iff by (smt (z3) mem_Collect_eq)\n    show \"\\<And>x. x \\<in> \\<K> \\<union> {card g + 1 |g. g \\<in> \\<G>} \\<Longrightarrow> 0 < x\" \n      using min_group_size positive_ints by auto\n    show \"\\<And>k.  k \\<in> \\<K> \\<union> {card g + 1 |g. g \\<in> \\<G>} \\<Longrightarrow> 2 \\<le> k\" \n      using min_group_size positive_ints assms by fastforce\n  qed\nqed\n\nsubsubsection \\<open>Wilson's Construction\\<close>\ntext \\<open>Wilson's construction involves the combination of multiple k-GDD's. This proof was\nbased of Stinson \\<^cite>\\<open>\"stinsonCombinatorialDesignsConstructions2004\"\\<close>\\<close>\n\nlemma wilsons_construction_proper: \n  assumes \"card I = w\"\n  assumes \"w > 0\"\n  assumes \"\\<And> n. n \\<in> \\<K>' \\<Longrightarrow> n \\<ge> 2\"\n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  shows \"proper_design (\\<V> \\<times> I) (\\<Sum>B \\<in># \\<B>. (f B))\" (is \"proper_design ?Y ?B\")\nproof (unfold_locales, simp_all)\n  show \"\\<And>b. \\<exists>x\\<in>#\\<B>. b \\<in># f x \\<Longrightarrow> b \\<subseteq> \\<V> \\<times> I\"\n  proof -\n    fix b\n    assume \"\\<exists>x\\<in>#\\<B>. b \\<in># f x\"\n    then obtain B where \"B \\<in># \\<B>\" and \"b \\<in># (f B)\" by auto\n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by auto\n    show \"b \\<subseteq> \\<V> \\<times> I\" using kgdd.wellformed\n      using \\<open>B \\<in># \\<B>\\<close> \\<open>b \\<in># f B\\<close> wellformed by fastforce \n  qed\n  show \"finite (\\<V> \\<times> I)\" using finite_sets assms bot_nat_0.not_eq_extremum card.infinite by blast \n  show \"\\<And>bl. \\<exists>x\\<in>#\\<B>. bl \\<in># f x \\<Longrightarrow> bl \\<noteq> {}\"\n  proof -\n    fix bl\n    assume \"\\<exists>x\\<in>#\\<B>. bl \\<in># f x\"\n    then obtain B where \"B \\<in># \\<B>\" and \"bl \\<in># (f B)\" by auto\n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by auto\n    show \"bl \\<noteq> {}\" using kgdd.blocks_nempty by (simp add: \\<open>bl \\<in># f B\\<close>) \n  qed\n  show \"\\<exists>i\\<in>#\\<B>. f i \\<noteq> {#}\"\n  proof -\n    obtain B where \"B \\<in># \\<B>\"\n      using design_blocks_nempty by auto \n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by auto\n    have \"f B \\<noteq> {#}\" using kgdd.design_blocks_nempty by simp \n    then show \"\\<exists>i\\<in>#\\<B>. f i \\<noteq> {#}\" using \\<open>B \\<in># \\<B>\\<close> by auto \n  qed\nqed\n\nlemma pair_construction_block_sizes: \n  assumes \"K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  assumes \"B \\<in># \\<B>\"\n  assumes \"b \\<in># (f B)\"\n  shows \"card b \\<in> \\<K>'\"\nproof -\n  interpret bkgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\"\n    using assms by simp\n  show \"card b \\<in> \\<K>'\" using bkgdd.block_sizes by (simp add:assms) \nqed\n\nlemma wilsons_construction_index_0: \n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  assumes \"G \\<in> {GG \\<times> I |GG. GG \\<in> \\<G>}\"\n  assumes \"X \\<in> G\" \n  assumes \"Y \\<in> G\" \n  assumes \"X \\<noteq> Y\"\n  shows \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y} = 0\"\nproof -\n  obtain G' where gi: \"G = G' \\<times> I\" and ging: \"G' \\<in> \\<G>\" using assms by auto\n  obtain x y ix iy where xpair: \"X = (x, ix)\" and ypair: \"Y = (y, iy)\" using assms by auto\n  then have ixin: \"ix \\<in> I\" and xing: \"x \\<in> G'\" using assms gi by auto \n  have iyin: \"iy \\<in> I\" and ying: \"y \\<in> G'\" using assms ypair gi by auto\n  have ne_index_0: \"x \\<noteq> y \\<Longrightarrow> \\<B> index {x, y} = 0\" \n    using ying xing index_together ging by simp\n  have \"\\<And> B. B \\<in># \\<B> \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\" \n  proof -\n    fix B\n    assume assm: \"B \\<in># \\<B>\"\n    then interpret kgdd: K_GDD \"(B \\<times> I)\" \"(f B)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> B }\" using assms by simp\n    have not_ss_0: \"\\<not> ({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I)) \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\"\n      by (metis kgdd.points_index_ps_nin) \n    have \"x \\<noteq> y \\<Longrightarrow> \\<not> {x, y} \\<subseteq> B\" using ne_index_0 assm points_index_0_left_imp by auto \n    then have \"x \\<noteq> y \\<Longrightarrow> \\<not> ({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I))\" using assms\n      by (meson empty_subsetI insert_subset mem_Sigma_iff)\n    then have nexy: \"x \\<noteq> y \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\" using not_ss_0 by simp\n    have \"x = y \\<Longrightarrow> ({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I)) \\<Longrightarrow> (f B) index {(x, ix), (y, iy)} = 0\"\n    proof -\n      assume eq: \"x = y\"\n      assume \"({(x, ix), (y, iy)} \\<subseteq> (B \\<times> I))\"\n      then obtain g where \"g \\<in> {{x} \\<times> I |x . x \\<in> B }\" and \"(x, ix) \\<in> g\" and \"(y, ix) \\<in> g\"\n        using eq  by auto \n      then show ?thesis using kgdd.index_together\n        by (smt (verit, best) SigmaD1 SigmaD2 SigmaI assms(4) assms(5) gi mem_Collect_eq xpair ypair)\n    qed\n    then show \"(f B) index {(x, ix), (y, iy)} = 0\" using not_ss_0 nexy by auto\n  qed\n  then have \"\\<And> B. B \\<in># (image_mset f \\<B>) \\<Longrightarrow> B index {(x, ix), (y, iy)} = 0\" by auto\n  then show \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y} = 0\" \n    by (simp add: points_index_sum xpair ypair)\nqed\n\nlemma wilsons_construction_index_1: \n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  assumes \"G1 \\<in> {G \\<times> I |G. G \\<in> \\<G>}\"\n  assumes \"G2 \\<in> {G \\<times> I |G. G \\<in> \\<G>}\"\n  assumes \"G1 \\<noteq> G2\"\n  and \"(x, ix) \\<in> G1\" and \"(y, iy) \\<in> G2\" \n  shows \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {(x, ix), (y, iy)} = (1 ::int)\"\nproof -\n  obtain G1' where gi1: \"G1 = G1' \\<times> I\" and ging1: \"G1' \\<in> \\<G>\" using assms by auto\n  obtain G2' where gi2: \"G2 = G2' \\<times> I\" and ging2: \"G2' \\<in> \\<G>\" using assms by auto\n  have xing: \"x \\<in> G1'\" using assms gi1 by simp\n  have ying: \"y \\<in> G2'\" using assms gi2 by simp\n  have gne: \"G1' \\<noteq> G2'\" using assms gi1 gi2 by auto\n  then have xyne: \"x \\<noteq> y\" using xing ying ging1 ging2 point_in_one_group by blast\n  have \"\\<exists>! bl . bl \\<in># \\<B> \\<and> {x, y} \\<subseteq> bl\" using index_distinct points_index_one_unique_block\n    by (metis ging1 ging2 gne of_nat_1_eq_iff xing ying) \n  then obtain bl where blinb:\"bl \\<in># \\<B>\" and xyblss: \"{x, y} \\<subseteq> bl\" by auto \n  then have \"\\<And> b . b \\<in># \\<B> - {#bl#} \\<Longrightarrow> \\<not> {x, y} \\<subseteq> b\" using points_index_one_not_unique_block\n    by (metis ging1 ging2 gne index_distinct int_ops(2) nat_int_comparison(1) xing ying) \n  then have not_ss: \"\\<And> b . b \\<in># \\<B> - {#bl#} \\<Longrightarrow> \\<not> ({(x, ix), (y, iy)} \\<subseteq> (b \\<times> I))\" using assms\n    by (meson SigmaD1 empty_subsetI insert_subset)\n  then have pi0: \"\\<And> b . b \\<in># \\<B> - {#bl#} \\<Longrightarrow> (f b) index {(x, ix), (y, iy)}  = 0\"\n  proof -\n    fix b\n    assume assm: \"b \\<in># \\<B> - {#bl#}\"\n    then have \"b \\<in># \\<B>\" by (meson in_diffD) \n    then interpret kgdd: K_GDD \"(b \\<times> I)\" \"(f b)\" \\<K>' \"{{x} \\<times> I |x . x \\<in> b }\" using assms by simp\n    show \"(f b) index {(x, ix), (y, iy)} = 0\"\n      using assm not_ss by (metis kgdd.points_index_ps_nin) \n  qed\n  let ?G = \"{{x} \\<times> I |x . x \\<in> bl }\"\n  interpret bkgdd: K_GDD \"(bl \\<times> I)\" \"(f bl)\" \\<K>' ?G using assms blinb by simp\n  obtain g1 g2 where xing1: \"(x, ix) \\<in> g1\" and ying2: \"(y, iy) \\<in> g2\" and g1g: \"g1 \\<in> ?G\" \n      and g2g: \"g2 \\<in> ?G\" using assms(5) assms(6) gi1 gi2\n    by (metis (no_types, lifting) bkgdd.point_has_unique_group insert_subset mem_Sigma_iff xyblss) \n  then have \"g1 \\<noteq> g2\" using xyne by blast \n  then have pi1: \"(f bl) index {(x, ix), (y, iy)} = 1\" \n    using bkgdd.index_distinct xing1 ying2 g1g g2g by simp\n  have \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {(x, ix), (y, iy)} = \n      (\\<Sum>B \\<in># \\<B>. (f B) index {(x, ix), (y, iy)} )\" \n    by (simp add: points_index_sum)\n  then have \"(\\<Sum>\\<^sub># (image_mset f \\<B>)) index {(x, ix), (y, iy)} = \n      (\\<Sum>B \\<in># (\\<B> - {#bl#}). (f B) index {(x, ix), (y, iy)}) + (f bl) index {(x, ix), (y, iy)}\"\n    by (metis (no_types, lifting) add.commute blinb insert_DiffM sum_mset.insert) \n  thus ?thesis using pi0 pi1 by simp\nqed\n\ntheorem Wilsons_Construction:\n  assumes \"card I = w\"\n  assumes \"w > 0\"\n  assumes \"\\<And> n. n \\<in> \\<K>' \\<Longrightarrow> n \\<ge> 2\"\n  assumes \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\"\n  shows \"K_GDD (\\<V> \\<times> I) (\\<Sum>B \\<in># \\<B>. (f B)) \\<K>' {G \\<times> I | G . G \\<in> \\<G>}\"\nproof -\n  let ?Y = \"\\<V> \\<times> I\" and ?H = \"{G \\<times> I | G . G \\<in> \\<G>}\" and ?B = \"\\<Sum>B \\<in># \\<B>. (f B)\"\n  interpret pd: proper_design ?Y ?B using wilsons_construction_proper assms by auto\n  have \"\\<And> bl . bl \\<in># (\\<Sum>B \\<in># \\<B>. (f B)) \\<Longrightarrow> card bl \\<in> \\<K>'\"  \n    using assms pair_construction_block_sizes by blast \n  then interpret kdes: K_block_design ?Y ?B \\<K>' \n    using assms(3) by (unfold_locales) (simp_all,fastforce)\n  interpret gdd: GDD ?Y ?B ?H \"1:: int\" \n  proof (unfold_locales)\n    show \"partition_on (\\<V> \\<times> I) {G \\<times> I |G. G \\<in> \\<G>}\" \n      using assms groups_not_empty design_points_nempty group_partitions\n      by (simp add: partition_on_cart_prod) \n    have \"inj_on (\\<lambda> G. G \\<times> I) \\<G>\"\n      using inj_on_def pd.design_points_nempty by auto \n    then have \"card {G \\<times> I |G. G \\<in> \\<G>} = card \\<G>\" using card_image by (simp add: Setcompr_eq_image) \n    then show \"1 < card {G \\<times> I |G. G \\<in> \\<G>}\" using groups_size by linarith \n    show \"(1::int) \\<le> 1\" by simp\n    have gdd_fact: \"\\<And> B . B \\<in># \\<B> \\<Longrightarrow> K_GDD (B \\<times> I) (f B) \\<K>' {{x} \\<times> I |x . x \\<in> B }\" \n      using assms by simp\n    show \"\\<And>G X Y. G \\<in> {GG \\<times> I |GG. GG \\<in> \\<G>} \\<Longrightarrow> X \\<in> G \\<Longrightarrow> Y \\<in> G \\<Longrightarrow> X \\<noteq> Y \n        \\<Longrightarrow> (\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y} = 0\"\n      using wilsons_construction_index_0[OF assms(4)] by auto\n    show \"\\<And>G1 G2 X Y. G1 \\<in> {G \\<times> I |G. G \\<in> \\<G>} \\<Longrightarrow> G2 \\<in> {G \\<times> I |G. G \\<in> \\<G>} \n      \\<Longrightarrow> G1 \\<noteq> G2 \\<Longrightarrow> X \\<in> G1 \\<Longrightarrow> Y \\<in> G2 \\<Longrightarrow> ((\\<Sum>\\<^sub># (image_mset f \\<B>)) index {X, Y}) = (1 ::int)\"\n      using wilsons_construction_index_1[OF assms(4)] by blast \n  qed\n  show ?thesis by (unfold_locales)\nqed\n\nend\n\ncontext pairwise_balance\nbegin\n\nlemma PBD_by_deleting_point: \n  assumes \"\\<v> > 2\"\n  assumes \"\\<And> bl . bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2\"\n  shows \"pairwise_balance (del_point x) (del_point_blocks x) \\<Lambda>\"\nproof (cases \"x \\<in> \\<V>\")\n  case True\n  interpret des: design \"del_point x\" \"del_point_blocks x\"\n    using delete_point_design assms by blast \n  show ?thesis using assms design_blocks_nempty del_point_def del_point_blocks_def\n  proof (unfold_locales, simp_all)\n    show \"2 < \\<v> \\<Longrightarrow> (\\<And>bl. bl \\<in># \\<B> \\<Longrightarrow> 2 \\<le> card bl) \\<Longrightarrow> 2 \\<le> (card (\\<V> - {x}))\"\n      using card_Diff_singleton_if diff_diff_cancel diff_le_mono2 finite_sets less_one\n      by (metis diff_is_0_eq neq0_conv t_lt_order zero_less_diff) \n    have \"\\<And> ps . ps  \\<subseteq> \\<V> - {x} \\<Longrightarrow> ps \\<subseteq> \\<V>\" by auto\n    then show \"\\<And>ps. ps \\<subseteq> \\<V> - {x} \\<Longrightarrow> card ps = 2  \\<Longrightarrow> {#bl - {x}. bl \\<in># \\<B>#} index ps = \\<Lambda>\"\n      using delete_point_index_eq del_point_def del_point_blocks_def by simp\n  qed\nnext\n  case False\n  then show ?thesis\n    by (simp add: del_invalid_point del_invalid_point_blocks pairwise_balance_axioms)\nqed\nend\n\ncontext k_GDD\nbegin\n\nlemma bibd_from_kGDD:\n  assumes \"\\<k> > 1\"\n  assumes \"\\<And> g. g \\<in> \\<G> \\<Longrightarrow> card g = \\<k> - 1\"\n  assumes \" x \\<notin> \\<V>\"\n  shows \"bibd (add_point x) (\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}) (\\<k>) 1\"\nproof - \n  have \"\\<And> k . k\\<in> {\\<k>} \\<Longrightarrow> k = \\<k>\" by blast \n  then have kge: \"\\<And> k . k\\<in> {\\<k>} \\<Longrightarrow> k \\<ge> 2\" using assms(1) by simp\n  have \"\\<And> g . g \\<in> \\<G> \\<Longrightarrow> card g + 1 = \\<k>\" using assms k_non_zero by auto \n  then have s: \"({\\<k>} \\<union> {(card g) + 1 | g . g \\<in> \\<G>}) = {\\<k>}\" by auto\n  then interpret pbd: PBD \"(add_point x)\" \"\\<B> + mset_set { insert x g | g. g \\<in> \\<G>}\" \"{\\<k>}\"\n    using PBD_by_adjoining_point[of \"x\"] kge assms by (smt (z3) Collect_cong)\n  show ?thesis using assms pbd.block_sizes block_size_lt_v finite_sets add_point_def\n    by (unfold_locales) (simp_all)\nqed\n\nend\n\ncontext PBD \nbegin\n\nlemma pbd_points_index1: \"ps \\<subseteq> \\<V> \\<Longrightarrow> card ps = 2 \\<Longrightarrow> \\<B> index ps = 1\"\n  using balanced by simp \n\nlemma pbd_index1_points_imply_unique_block: \n  assumes \"b1 \\<in># \\<B>\" and \"b2 \\<in># \\<B>\" and \"b1 \\<noteq> b2\"\n  assumes \"x \\<noteq> y\" and \"{x, y} \\<subseteq> b1\" and \"x \\<in> b2\" \n  shows \"y \\<notin> b2\"\nproof (rule ccontr)\n  let ?ps = \"{# b \\<in># \\<B> . {x, y} \\<subseteq> b#}\"\n  assume \"\\<not> y \\<notin> b2\"\n  then have a: \"y \\<in> b2\" by linarith\n  then have \"{x, y} \\<subseteq> b2\"\n    by (simp add: assms(6)) \n  then have \"b1 \\<in># ?ps\" and \"b2 \\<in># ?ps\" using assms by auto\n  then have ss: \"{#b1, b2#} \\<subseteq># ?ps\" using assms\n    by (metis insert_noteq_member mset_add mset_subset_eq_add_mset_cancel single_subset_iff) \n  have \"size {#b1, b2#} = 2\" using assms by auto\n  then have ge2: \"size ?ps \\<ge> 2\" using assms ss by (metis size_mset_mono) \n  have pair: \"card {x, y} = 2\" using assms by auto\n  have \"{x, y} \\<subseteq> \\<V>\" using assms wellformed by auto\n  then have \"\\<B> index {x, y} = 1\" using pbd_points_index1 pair by simp\n  then show False using points_index_def ge2\n    by (metis numeral_le_one_iff semiring_norm(69)) \nqed\n\nlemma strong_delete_point_groups_index_zero: \n  assumes \"G \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n  assumes \"xa \\<in> G\" and \"y \\<in> G\" and \"xa \\<noteq> y\"\n  shows \"(str_del_point_blocks x) index {xa, y} = 0\"\nproof (auto simp add: points_index_0_iff str_del_point_blocks_def)\n  fix b\n  assume a1: \"b \\<in># \\<B>\" and a2: \"x \\<notin> b\" and a3: \"xa \\<in> b\" and a4: \"y \\<in> b\"\n  obtain b' where \"G = b' - {x}\" and \"b' \\<in># \\<B>\" and  \"x \\<in> b'\" using assms by blast\n  then show False using a1 a2 a3 a4 assms pbd_index1_points_imply_unique_block\n    by fastforce \nqed\n\nlemma strong_delete_point_groups_index_one: \n  assumes \"G1 \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n  assumes \"G2 \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n  assumes \"G1 \\<noteq> G2\" and \"xa \\<in> G1\" and \"y \\<in> G2\"\n  shows  \"(str_del_point_blocks x) index {xa, y} = 1\"\nproof -\n  obtain b1 where gb1: \"G1 = b1 - {x}\" and b1in: \"b1 \\<in># \\<B>\" and xin1: \"x \\<in> b1\" using assms by blast\n  obtain b2 where gb2: \"G2 = b2 - {x}\" and b2in: \"b2 \\<in># \\<B>\" and xin2:\"x \\<in> b2\" using assms by blast\n  have bneq: \"b1 \\<noteq> b2 \" using assms(3) gb1 gb2 by auto\n  have \"xa \\<noteq> y\" using gb1 b1in xin1 gb2 b2in xin2 assms(3) assms(4) assms(5) insert_subset\n    by (smt (verit, best) Diff_eq_empty_iff Diff_iff empty_Diff insertCI pbd_index1_points_imply_unique_block) \n  then have pair: \"card {xa, y} = 2\" by simp \n  have inv: \"{xa, y} \\<subseteq> \\<V>\" using gb1 b1in gb2 b2in assms(4) assms(5)\n    by (metis Diff_cancel Diff_subset insert_Diff insert_subset wellformed) \n  have \"{# bl \\<in># \\<B> . x \\<in> bl#} index {xa, y} = 0\"\n  proof (auto simp add: points_index_0_iff)\n    fix b assume a1: \"b \\<in># \\<B>\" and a2: \"x \\<in> b\" and a3: \"xa \\<in> b\" and a4: \"y \\<in> b\"\n    then have yxss: \"{y, x} \\<subseteq> b2\"\n      using assms(5) gb2 xin2 by blast \n    have \"{xa, x} \\<subseteq> b1\"\n      using assms(4) gb1 xin1 by auto \n    then have \"xa \\<notin> b2\" using pbd_index1_points_imply_unique_block\n      by (metis DiffE assms(4) b1in b2in bneq gb1 singletonI xin2) \n    then have \"b2 \\<noteq> b\" using a3 by auto \n    then show False using pbd_index1_points_imply_unique_block\n      by (metis DiffD2 yxss a1 a2 a4 assms(5) b2in gb2 insertI1) \n  qed\n  then have \"(str_del_point_blocks x) index {xa, y} = \\<B> index {xa, y}\" \n    by (metis multiset_partition plus_nat.add_0 point_index_distrib str_del_point_blocks_def) \n  thus ?thesis using pbd_points_index1 pair inv by fastforce\nqed\n\nlemma blocks_with_x_partition: \n  assumes \"x \\<in> \\<V>\"\n  shows \"partition_on (\\<V> - {x}) {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\nproof (intro partition_onI )\n  have gtt: \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2\" using block_size_gt_t\n    by (simp add: block_sizes nat_int_comparison(3)) \n  show \"\\<And>p. p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} \\<Longrightarrow> p \\<noteq> {}\"\n  proof -\n    fix p assume \"p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n    then obtain b where ptx: \"p = b - {x}\" and \"b \\<in># \\<B>\" and xinb: \"x \\<in> b\" by blast\n    then have ge2: \"card b \\<ge> 2\" using gtt by (simp add: nat_int_comparison(3)) \n    then have \"finite b\" by (metis card.infinite not_numeral_le_zero) \n    then have \"card p = card b - 1\" using xinb ptx by simp\n    then have \"card p \\<ge> 1\" using ge2 by linarith\n    thus \"p \\<noteq> {}\" by auto\n  qed\n  show \"\\<Union> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} = \\<V> - {x}\"\n  proof (intro subset_antisym subsetI)\n    fix xa\n    assume \"xa \\<in> \\<Union> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" \n    then obtain b where \"xa \\<in> b\" and \"b \\<in># \\<B>\" and \"x \\<in> b\" and \"xa \\<noteq> x\" by auto\n    then show \"xa \\<in> \\<V> - {x}\" using wf_invalid_point by blast \n  next \n    fix xa\n    assume a: \"xa \\<in> \\<V> - {x}\"\n    then have nex: \"xa \\<noteq> x\" by simp\n    then have pair: \"card {xa, x} = 2\" by simp \n    have \"{xa, x} \\<subseteq> \\<V>\" using a assms by auto \n    then have \"card {b \\<in> design_support . {xa, x} \\<subseteq> b} = 1\" \n      using balanced points_index_simple_def pbd_points_index1 assms by (metis pair) \n    then obtain b where des: \"b \\<in> design_support\" and ss: \"{xa, x} \\<subseteq> b\"\n      by (metis (no_types, lifting) card_1_singletonE mem_Collect_eq singletonI)\n    then show \"xa \\<in> \\<Union> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\"\n      using des ss nex design_support_def by auto\n  qed\n  show \"\\<And>p p'. p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} \\<Longrightarrow> p' \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} \\<Longrightarrow> \n    p \\<noteq> p' \\<Longrightarrow> p \\<inter> p' = {}\" \n  proof -\n    fix p p'\n    assume p1: \"p \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" and p2: \"p' \\<in> {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" \n      and pne: \"p \\<noteq> p'\"\n    then obtain b where b1: \"p = b - {x}\" and b1in:\"b \\<in># \\<B>\" and xinb1:\"x \\<in> b\" by blast \n    then obtain b' where b2: \"p' = b' - {x}\" and b2in: \"b' \\<in># \\<B>\" and xinb2: \"x \\<in> b'\"\n      using p2 by blast\n    then have \"b \\<noteq> b'\" using pne b1 by auto\n    then have \"\\<And> y. y \\<in> b \\<Longrightarrow> y \\<noteq> x \\<Longrightarrow> y \\<notin> b'\" \n      using b1in b2in xinb1 xinb2 pbd_index1_points_imply_unique_block\n      by (meson empty_subsetI insert_subset) \n    then have \"\\<And> y. y \\<in> p \\<Longrightarrow> y \\<notin> p'\"\n      by (metis Diff_iff b1 b2 insertI1) \n    then show \"p \\<inter> p' = {}\" using disjoint_iff by auto\n  qed\nqed\n\nlemma KGDD_by_deleting_point:\n  assumes \"x \\<in> \\<V>\"\n  assumes \"\\<B> rep x < \\<b>\"\n  assumes \"\\<B> rep x > 1\" \n  shows \"K_GDD (del_point x) (str_del_point_blocks x) \\<K> { b - {x} | b . b \\<in># \\<B> \\<and> x \\<in> b}\"\nproof -\n  have \"\\<And> bl. bl \\<in># \\<B> \\<Longrightarrow> card bl \\<ge> 2\" using block_size_gt_t \n    by (simp add: block_sizes nat_int_comparison(3))\n  then interpret des: proper_design \"(del_point x)\" \"(str_del_point_blocks x)\" \n    using strong_delete_point_proper assms by blast\n  show ?thesis using blocks_with_x_partition strong_delete_point_groups_index_zero \n      strong_delete_point_groups_index_one str_del_point_blocks_def del_point_def\n  proof (unfold_locales, simp_all add: block_sizes positive_ints assms) \n    have ge1: \"card {b . b \\<in># \\<B> \\<and> x \\<in> b} > 1\" \n      using assms(3) replication_num_simple_def design_support_def by auto\n    have fin: \"finite {b . b \\<in># \\<B> \\<and> x \\<in> b}\" by simp \n    have inj: \"inj_on (\\<lambda> b . b - {x}) {b . b \\<in># \\<B> \\<and> x \\<in> b}\" \n      using assms(2) inj_on_def mem_Collect_eq by auto \n    then have \"card {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b} = card {b . b \\<in># \\<B> \\<and> x \\<in> b}\" \n      using card_image fin by (simp add: inj card_image setcompr_eq_image)\n    then show \"Suc 0 < card {b - {x} |b. b \\<in># \\<B> \\<and> x \\<in> b}\" using ge1\n      by presburger \n  qed\nqed\n\nlemma card_singletons_eq: \"card {{a} | a . a \\<in> A} = card A\"\n  by (simp add: card_image Setcompr_eq_image)\n\nlemma KGDD_from_PBD: \"K_GDD \\<V> \\<B> \\<K> {{x} | x . x \\<in> \\<V>}\"\nproof (unfold_locales,auto simp add: Setcompr_eq_image partition_on_singletons)\n  have \"card ((\\<lambda>x. {x}) ` \\<V>) \\<ge> 2\" using t_lt_order card_singletons_eq\n    by (metis Collect_mem_eq setcompr_eq_image) \n  then show \"Suc 0 < card ((\\<lambda>x. {x}) ` \\<V>)\" by linarith\n  show \"\\<And>xa xb. xa \\<in> \\<V> \\<Longrightarrow> xb \\<in> \\<V> \\<Longrightarrow> \\<B> index {xa, xb} \\<noteq> Suc 0 \\<Longrightarrow> xa = xb\"\n  proof (rule ccontr)\n    fix xa xb\n    assume ain: \"xa \\<in> \\<V>\" and bin: \"xb \\<in> \\<V>\" and ne1: \"\\<B> index {xa, xb} \\<noteq> Suc 0\"\n    assume \"xa \\<noteq> xb\"\n    then have \"card {xa, xb} = 2\" by auto\n    then have \"\\<B> index {xa, xb} = 1\"\n      by (simp add: ain bin) \n    thus False using ne1 by linarith\n  qed \nqed\n\nend\n\ncontext bibd\nbegin\nlemma kGDD_from_bibd:\n  assumes \"\\<Lambda> = 1\"\n  assumes \"x \\<in> \\<V>\"\n  shows \"k_GDD (del_point x) (str_del_point_blocks x) \\<k> { b - {x} | b . b \\<in># \\<B> \\<and> x \\<in> b}\"\nproof -\n  interpret pbd: PBD \\<V> \\<B> \"{\\<k>}\" using assms\n    using PBD.intro \\<Lambda>_PBD_axioms by auto \n  have lt: \"\\<B> rep x < \\<b>\" using block_num_gt_rep\n    by (simp add: assms(2)) \n  have \"\\<B> rep x > 1\" using r_ge_two assms by simp\n  then interpret kgdd: K_GDD \"(del_point x)\" \"str_del_point_blocks x\" \n    \"{\\<k>}\" \"{ b - {x} | b . b \\<in># \\<B> \\<and> x \\<in> b}\"\n    using pbd.KGDD_by_deleting_point lt assms by blast \n  show ?thesis using del_point_def str_del_point_blocks_def by (unfold_locales) (simp_all)\nqed\n\nend\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Design_Theory/Group_Divisible_Designs.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8652240825770432, "lm_q1q2_score": 0.7547759626873015}}
{"text": "(* Author: Tobias Nipkow *)\n\nsection {* Binary Tree *}\n\ntheory Tree\nimports Main\nbegin\n\ndatatype 'a tree =\n  Leaf (\"\\<langle>\\<rangle>\") |\n  Node (left: \"'a tree\") (val: 'a) (right: \"'a tree\") (\"\\<langle>_, _, _\\<rangle>\")\n  where\n    \"left Leaf = Leaf\"\n  | \"right Leaf = Leaf\"\ndatatype_compat tree\n\ntext{* Can be seen as counting the number of leaves rather than nodes: *}\n\ndefinition size1 :: \"'a tree \\<Rightarrow> nat\" where\n\"size1 t = size t + 1\"\n\nlemma size1_simps[simp]:\n  \"size1 \\<langle>\\<rangle> = 1\"\n  \"size1 \\<langle>l, x, r\\<rangle> = size1 l + size1 r\"\nby (simp_all add: size1_def)\n\nlemma neq_Leaf_iff: \"(t \\<noteq> \\<langle>\\<rangle>) = (\\<exists>l a r. t = \\<langle>l, a, r\\<rangle>)\"\nby (cases t) auto\n\nlemma finite_set_tree[simp]: \"finite(set_tree t)\"\nby(induction t) auto\n\n\nsubsection \"The set of subtrees\"\n\nfun subtrees :: \"'a tree \\<Rightarrow> 'a tree set\" where\n  \"subtrees \\<langle>\\<rangle> = {\\<langle>\\<rangle>}\" |\n  \"subtrees (\\<langle>l, a, r\\<rangle>) = insert \\<langle>l, a, r\\<rangle> (subtrees l \\<union> subtrees r)\"\n\nlemma set_treeE: \"a \\<in> set_tree t \\<Longrightarrow> \\<exists>l r. \\<langle>l, a, r\\<rangle> \\<in> subtrees t\"\nby (induction t)(auto)\n\nlemma Node_notin_subtrees_if[simp]: \"a \\<notin> set_tree t \\<Longrightarrow> Node l a r \\<notin> subtrees t\"\nby (induction t) auto\n\nlemma in_set_tree_if: \"\\<langle>l, a, r\\<rangle> \\<in> subtrees t \\<Longrightarrow> a \\<in> set_tree t\"\nby (metis Node_notin_subtrees_if)\n\n\nsubsection \"Inorder list of entries\"\n\nfun inorder :: \"'a tree \\<Rightarrow> 'a list\" where\n\"inorder \\<langle>\\<rangle> = []\" |\n\"inorder \\<langle>l, x, r\\<rangle> = inorder l @ [x] @ inorder r\"\n\nlemma set_inorder[simp]: \"set (inorder t) = set_tree t\"\nby (induction t) auto\n\n\nsubsection {* Binary Search Tree predicate *}\n\nfun (in linorder) bst :: \"'a tree \\<Rightarrow> bool\" where\n\"bst \\<langle>\\<rangle> \\<longleftrightarrow> True\" |\n\"bst \\<langle>l, a, r\\<rangle> \\<longleftrightarrow> bst l \\<and> bst r \\<and> (\\<forall>x\\<in>set_tree l. x < a) \\<and> (\\<forall>x\\<in>set_tree r. a < x)\"\n\nlemma (in linorder) bst_imp_sorted: \"bst t \\<Longrightarrow> sorted (inorder t)\"\nby (induction t) (auto simp: sorted_append sorted_Cons intro: less_imp_le less_trans)\n\n\nsubsection \"Deletion of the rightmost entry\"\n\nfun del_rightmost :: \"'a tree \\<Rightarrow> 'a tree * 'a\" where\n\"del_rightmost \\<langle>l, a, \\<langle>\\<rangle>\\<rangle> = (l,a)\" |\n\"del_rightmost \\<langle>l, a, r\\<rangle> = (let (r',x) = del_rightmost r in (\\<langle>l, a, r'\\<rangle>, x))\"\n\nlemma del_rightmost_set_tree_if_bst:\n  \"\\<lbrakk> del_rightmost t = (t',x); bst t; t \\<noteq> Leaf \\<rbrakk>\n  \\<Longrightarrow> x \\<in> set_tree t \\<and> set_tree t' = set_tree t - {x}\"\napply(induction t arbitrary: t' rule: del_rightmost.induct)\n  apply (fastforce simp: ball_Un split: prod.splits)+\ndone\n\nlemma del_rightmost_set_tree:\n  \"\\<lbrakk> del_rightmost t = (t',x);  t \\<noteq> \\<langle>\\<rangle> \\<rbrakk> \\<Longrightarrow> set_tree t = insert x (set_tree t')\"\napply(induction t arbitrary: t' rule: del_rightmost.induct)\nby (auto split: prod.splits) auto\n\nlemma del_rightmost_bst:\n  \"\\<lbrakk> del_rightmost t = (t',x);  bst t;  t \\<noteq> \\<langle>\\<rangle> \\<rbrakk> \\<Longrightarrow> bst t'\"\nproof(induction t arbitrary: t' rule: del_rightmost.induct)\n  case (2 l a rl b rr)\n  let ?r = \"Node rl b rr\"\n  from \"2.prems\"(1) obtain r' where 1: \"del_rightmost ?r = (r',x)\" and [simp]: \"t' = Node l a r'\"\n    by(simp split: prod.splits)\n  from \"2.prems\"(2) 1 del_rightmost_set_tree[OF 1] show ?case by(auto)(simp add: \"2.IH\")\nqed auto\n\n\nlemma del_rightmost_greater: \"\\<lbrakk> del_rightmost t = (t',x);  bst t;  t \\<noteq> \\<langle>\\<rangle> \\<rbrakk>\n  \\<Longrightarrow> \\<forall>a\\<in>set_tree t'. a < x\"\nproof(induction t arbitrary: t' rule: del_rightmost.induct)\n  case (2 l a rl b rr)\n  from \"2.prems\"(1) obtain r'\n  where dm: \"del_rightmost (Node rl b rr) = (r',x)\" and [simp]: \"t' = Node l a r'\"\n    by(simp split: prod.splits)\n  show ?case using \"2.prems\"(2) \"2.IH\"[OF dm] del_rightmost_set_tree_if_bst[OF dm]\n    by (fastforce simp add: ball_Un)\nqed simp_all\n\nlemma del_rightmost_Max:\n  \"\\<lbrakk> del_rightmost t = (t',x);  bst t;  t \\<noteq> \\<langle>\\<rangle> \\<rbrakk> \\<Longrightarrow> x = Max(set_tree t)\"\nby (metis Max_insert2 del_rightmost_greater del_rightmost_set_tree finite_set_tree less_le_not_le)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8652240704135291, "lm_q1q2_score": 0.7547759549479196}}
{"text": "section \\<open>Minimum Weight Basis\\<close>\n\ntheory MinWeightBasis\n  imports \"Refine_Monadic.Refine_Monadic\" Matroids.Matroid    \nbegin\n  \ntext \\<open>For a matroid together with a weight function, assigning each element\n  of the carrier set an weight, we construct a greedy algorithm that determines\n  a minimum weight basis.\\<close>\n\n(* TODO: consider greedoids instead of matroids as a more\n   general class of structures that allow a greedy min weight algorithm *)\n\nlocale weighted_matroid = matroid carrier indep for carrier::\"'a set\" and indep  +\n  fixes weight :: \"'a \\<Rightarrow> 'b::{linorder, ordered_comm_monoid_add}\"\nbegin\n    \ndefinition minBasis where\n  \"minBasis B \\<equiv> basis B \\<and> (\\<forall>B'. basis B' \\<longrightarrow> sum weight B \\<le> sum weight B')\"\n\n                             \nsubsection \\<open>Preparations\\<close>\n     \nfun in_sort_edge where\n   \"in_sort_edge x [] = [x]\" \n | \"in_sort_edge x (y#ys) = (if weight x \\<le> weight y then x#y#ys else y# in_sort_edge x ys)\"  \n\n\n\nlemma in_sort_edge: \"sorted_wrt (\\<lambda>e1 e2. weight e1 \\<le> weight e2) L\n         \\<Longrightarrow> sorted_wrt (\\<lambda>e1 e2. weight e1 \\<le> weight e2) (in_sort_edge x L)\"\n  by (induct L, auto)\n   \nlemma in_sort_edge_distinct: \"x \\<notin> set L \\<Longrightarrow> distinct L \\<Longrightarrow> distinct (in_sort_edge x L)\"    \n  by (induct L, auto) \n    \nlemma finite_sorted_edge_distinct:\n  assumes \"finite S\" \n  obtains L where \"distinct L\" \"sorted_wrt (\\<lambda>e1 e2. weight e1 \\<le> weight e2) L\" \"S = set L\"\nproof -\n  {\n    have \"\\<exists>L.  distinct L \\<and> sorted_wrt (\\<lambda>e1 e2. weight e1 \\<le> weight e2) L \\<and> S = set L\"\n      using assms\n      apply(induct S)\n       apply(clarsimp)\n      apply(clarsimp) \n      subgoal for x L apply(rule exI[where x=\"in_sort_edge x L\"])\n        by (auto simp: in_sort_edge in_sort_edge_distinct)\n      done\n  }\n  with that show ?thesis by blast\nqed    \n    \nabbreviation \"wsorted == sorted_wrt (\\<lambda>e1 e2. weight e1 \\<le> weight e2)\"\n \nlemma sum_list_map_cons:\n  \"sum_list (map weight (y # ys)) = weight y + sum_list (map weight ys)\" \n  by auto\n     \nlemma exists_greater:\n  assumes  len: \"length F = length F'\"\n      and sum: \"sum_list (map weight F) > sum_list (map weight F')\"\n    shows \"\\<exists>i<length F. weight (F ! i) > weight (F' ! i)\"\nusing len sum    \nproof (induct rule: list_induct2) \n  case (Cons x xs y ys)    \n  from Cons(3)\n  have *: \"~ weight y < weight x \\<Longrightarrow> sum_list (map weight ys) < sum_list (map weight xs)\" \n    by (metis add_mono not_less sum_list_map_cons)\n  show ?case              \n    using Cons * \n    by (cases \"weight y < weight x\", auto)\nqed simp\n  \n  \nlemma wsorted_nth_mono: assumes \"wsorted L\" \"i\\<le>j\" \"j<length L\"\n  shows \"weight (L!i) \\<le> weight (L!j)\"\n  using assms by (induct L arbitrary: i j rule: list.induct, auto simp: nth_Cons') \n\n    \nsubsubsection \\<open>Weight restricted set\\<close>\n\ntext \\<open>limi T g is the set T restricted  \n     to elements only with weight\n    strictly smaller than g.\\<close>\n\ndefinition \"limi T g == {e. e\\<in>T \\<and> weight e < g}\"\n  \nlemma limi_subset: \"limi T g \\<subseteq> T\" by (auto simp: limi_def)  \n  \nlemma limi_mono: \"A \\<subseteq> B \\<Longrightarrow> limi A g \\<subseteq> limi B g\"  by (auto simp: limi_def) \n\nsubsubsection \\<open>The greedy idea\\<close>\n\ndefinition \"no_smallest_element_skipped E F\n   = (\\<forall>e\\<in>carrier - E. \\<forall>g>weight e. indep (insert e (limi F g)) \\<longrightarrow> (e \\<in> limi F g))\"\n\ntext  \\<open>let @{term F} be a set of elements\n  @{term \\<open>limi F g\\<close>} is @{term F} restricted to elements with weight smaller than @{term g}\n  let @{term E} be a set of elements we want to exclude.\n    \n  @{term \\<open>no_smallest_element_skipped E F\\<close>} expresses,\n     that going greedily over @{term \\<open>carrier-E\\<close>}, every element that did not\n     render the accumulated set dependent, was added to the set @{term F}.\\<close>\n\n\nlemma no_smallest_element_skipped_empty[simp]: \"no_smallest_element_skipped carrier {}\"\n  by(auto simp: no_smallest_element_skipped_def)\n\n\n\nlemma no_smallest_element_skipped_skip: \n  assumes createsCycle: \"\\<not> indep (insert e F)\"\n       and    I: \"no_smallest_element_skipped (E\\<union>{e}) F\"\n       and    sorted: \"(\\<forall>x\\<in>F.\\<forall>y\\<in>(E\\<union>{e}). weight x \\<le> weight y)\"\n     shows \"no_smallest_element_skipped E F\"\n  unfolding no_smallest_element_skipped_def\nproof (clarsimp)\n  fix x g\n  assume x: \"x \\<in> carrier\"  \"x \\<notin> E\"  \"weight x < g\"\n  assume f: \"indep (insert x (limi F g))\" \n  show \"(x \\<in> limi F g)\"  \n  proof (cases \"x=e\")\n    case True \n    from True have \"limi F g = F\"\n      unfolding limi_def using \\<open>weight x < g\\<close> sorted by fastforce  \n    with createsCycle f True have \"False\" by auto  \n    then show ?thesis by simp\n  next\n    case False\n    show ?thesis \n    apply(rule I[THEN no_smallest_element_skippedD, OF _ \\<open>weight x < g\\<close>])\n    using x f False\n    by auto\n  qed\nqed\n  \nlemma no_smallest_element_skipped_add:\n  assumes I: \"no_smallest_element_skipped (E\\<union>{e}) F\"\n  shows \"no_smallest_element_skipped E (insert e F)\"\n  unfolding no_smallest_element_skipped_def\nproof (clarsimp)\n  fix x g\n  assume xc: \"x \\<in> carrier\"\n  assume x: \"x \\<notin> E\"\n  assume wx: \"weight x < g\"\n  assume f: \"indep (insert x (limi (insert e F) g))\"\n  show \"(x \\<in> limi (insert e F) g)\"\n  proof(cases \"x=e\")\n    case True   \n    then show ?thesis unfolding limi_def\n      using wx by blast \n  next\n    case False\n    have ind: \"indep (insert x (limi F g))\"\n      apply(rule indep_subset[OF f]) using limi_mono by blast  \n    have \"indep (insert x (limi F g)) \\<Longrightarrow> x \\<in> limi F g\" \n      apply(rule I[THEN no_smallest_element_skippedD]) using False xc wx x by auto\n    with ind show ?thesis using limi_mono by blast\n  qed      \nqed  \n\n\nsubsection \\<open>Minimum Weight Basis algorithm\\<close>\n\n\ndefinition \"obtain_sorted_carrier \\<equiv> SPEC (\\<lambda>L. wsorted L \\<and> set L = carrier)\"\n\nabbreviation \"empty_basis \\<equiv> {}\"\n\ntext \\<open>To compute a minimum weight basis one obtains a list of the carrier set sorted ascendingly\n  by the weight function. Then one iterates over the list and adds an elements greedily to \n  the independent set if it does not render the set dependet.\\<close>\n\ndefinition minWeightBasis where \n  \"minWeightBasis \\<equiv> do {\n        l \\<leftarrow> obtain_sorted_carrier;\n        ASSERT (set l = carrier);\n        T \\<leftarrow> nfoldli l (\\<lambda>_. True) \n        (\\<lambda>e T. do { \n            ASSERT (indep T \\<and> e\\<in>carrier \\<and> T\\<subseteq>carrier);\n            if indep (insert e T) then\n              RETURN (insert e T)\n            else \n              RETURN T\n        }) empty_basis;\n        RETURN T\n      }\"\n\n \nsubsection \\<open>The heart of the argument\\<close>\n\ntext \\<open>The algorithmic idea above is correct, as an independent set, which\n  is inclusion maximal and has not skipped any smaller element, is a minimum weight basis. \\<close>\n\nlemma greedy_approach_leads_to_minBasis: assumes indep: \"indep F\"\n  and inclmax: \"\\<forall>e\\<in>carrier - F. \\<not> indep (insert e F)\"\n  and \"no_smallest_element_skipped {} F\"\n  shows \"minBasis F\"\nproof (rule ccontr)\n  \\<comment> \\<open>from our assumptions we have that F is a basis\\<close>  \n  from indep inclmax have bF: \"basis F\" using indep_not_basis by blast\n  \\<comment> \\<open>towards a contradiction, assume F is not a minimum Basis\\<close>\n  assume notmin: \"\\<not> minBasis F\"    \n  \\<comment> \\<open>then we can get a smaller Basis B\\<close>\n  from bF notmin[unfolded minBasis_def] obtain B\n    where bB: \"basis B\" and sum: \"sum weight B < sum weight F\"\n    by force\n  \\<comment> \\<open>lets us obtain two sorted lists for the bases F and B\\<close>\n  from bF basis_finite finite_sorted_edge_distinct\n  obtain FL where dF[simp]: \"distinct FL\" and wF[simp]: \"wsorted FL\" \n    and sF[simp]: \"F = set FL\"\n    by blast\n  from bB basis_finite finite_sorted_edge_distinct\n  obtain BL where dB[simp]: \"distinct BL\" and wB[simp]: \"wsorted BL\"\n    and sB[simp]: \"B = set BL\"\n      by blast\n  \\<comment> \\<open>as basis F has more total weight than basis B (and the basis have the same length) ...\\<close>\n  from sum have suml: \"sum_list (map weight BL) < sum_list (map weight FL)\"\n    by(simp add: sum.distinct_set_conv_list[symmetric]) \n  from bB bF have \"card B = card F\" using basis_card by blast \n  then have l: \"length FL = length BL\" by (simp add: distinct_card) \n  \\<comment> \\<open>... there exists an index i such that the ith element of the BL is strictly smaller \n      than the ith element of FL \\<close>\n  from exists_greater[OF l suml] obtain i where i: \"i<length FL\"\n    and gr: \"weight (BL ! i) < weight (FL ! i)\"\n    by auto\n  let ?FL_restricted = \"limi (set FL) (weight (FL ! i))\"\n\n  \\<comment> \\<open>now let us look at the two independent sets X and Y:\n        let X and Y be the set if we take the first i-1 elements of BL\n         and the first i elements of FL respectively. \n      We want to use the augment property of Matroids in order to show that we must have skipped\n      and optimal element, which then contradicts our assumption. \\<close>\n  let ?X = \"take i FL\"\n  have X_size: \"card (set ?X) = i\" using i\n    by (simp add: distinct_card)\n  have X_indep: \"indep (set ?X)\" using bF\n    using indep_iff_subset_basis set_take_subset by force\n\n  let ?Y = \"take (Suc i) BL\"\n  have Y_size: \"card (set ?Y) = Suc i\" using i l\n    by (simp add: distinct_card)\n  have Y_indep: \"indep (set ?Y)\" using bB\n    using indep_iff_subset_basis set_take_subset by force \n\n  have \"card (set ?X) < card (set ?Y)\" using X_size Y_size by simp\n\n  \\<comment> \\<open>X and Y are independent and X is smaller than Y, thus we can augment X with some element x\\<close>\n  with Y_indep X_indep                                 \n  obtain x where x: \"x\\<in>set (take (Suc i) BL) - set ?X\"\n    and indepX: \"indep (insert x (set ?X))\"\n      using augment by auto\n\n  \\<comment> \\<open>we know many things about x now, i.e. x weights strictly less than the ith element of FL ...\\<close>\n  have \"x\\<in>carrier\"  using indepX indep_subset_carrier by blast     \n  from x have xs: \"x\\<in>set (take (Suc i) BL)\" and xnX: \"x \\<notin> set ?X\" by auto\n  from xs obtain j where \"x=(take (Suc i) BL)!j\" and ij: \"j\\<le>i\"  \n    by (metis i in_set_conv_nth l length_take less_Suc_eq_le min_Suc_gt(2))\n  then have x: \"x=BL!j\" by auto\n  have il: \"i < length BL\" using i l by simp\n  have \"weight x \\<le> weight (BL ! i)\" \n    unfolding x apply(rule wsorted_nth_mono) by fact+\n  then have k: \"weight x < weight (FL ! i)\" using gr by auto\n\n  \\<comment> \\<open>... and that adding x to X gives us an independent set\\<close>\n  have \"?FL_restricted \\<subseteq> set ?X\"\n    unfolding  limi_def apply safe\n    by (metis (no_types, lifting) i in_set_conv_nth length_take\n              min_simps(2) not_less nth_take wF wsorted_nth_mono) \n  have z': \"insert x ?FL_restricted \\<subseteq> insert x (set ?X)\"\n    using xnX \\<open>?FL_restricted \\<subseteq> set (take i FL)\\<close> by auto \n  from indep_subset[OF indepX z'] have add_x_stay_indep: \"indep (insert x ?FL_restricted)\" .\n\n  \\<comment> \\<open>... finally this means that we must have taken the element during our greedy algorithm\\<close>\n  from \\<open>no_smallest_element_skipped {} F\\<close>\n      \\<open>x\\<in>carrier\\<close> \\<open>weight x < weight (FL ! i)\\<close> add_x_stay_indep\n    have \"x \\<in> ?FL_restricted\"  by (auto dest: no_smallest_element_skippedD)\n  with \\<open>?FL_restricted \\<subseteq> set ?X\\<close> have \"x \\<in> set ?X\"  by auto\n\n  \\<comment> \\<open>... but we actually didn't. This finishes our proof by contradiction.\\<close>  \n  with xnX show \"False\" by auto              \nqed\n\n\nsubsection \"The Invariant\"\n\ntext \\<open>The following predicate is invariant during the execution of the \n  minimum weight basis algorithm, and implies that its result is a minimum weight basis.\\<close>\n\ndefinition I_minWeightBasis where\n  \"I_minWeightBasis == \\<lambda>(T,E). indep T \n                \\<and> T \\<subseteq> carrier\n                 \\<and> E \\<subseteq> carrier  \n                 \\<and> (\\<forall>x\\<in>T.\\<forall>y\\<in>E. weight x \\<le> weight y)\n                \\<and> (\\<forall>e\\<in>carrier-E-T. ~indep (insert e T))\n                 \\<and> no_smallest_element_skipped E T\"\n\nlemma I_minWeightBasisD: \n  assumes \n   \"I_minWeightBasis (T,E)\"\n shows\"indep T\" \"\\<And>e. e\\<in>carrier-E-T \\<Longrightarrow> ~indep (insert e T)\"\n    \"E \\<subseteq> carrier\" \"\\<And>x y. x\\<in>T \\<Longrightarrow> y\\<in>E \\<Longrightarrow> weight x \\<le> weight y\"  \"T \\<subseteq> carrier\"\n    \"no_smallest_element_skipped E T\"\n  using assms by(auto simp: no_smallest_element_skipped_def I_minWeightBasis_def)\n\nlemma I_minWeightBasisI:\n  assumes \"indep T\" \"\\<And>e. e\\<in>carrier-E-T \\<Longrightarrow> ~indep (insert e T)\"\n    \"E \\<subseteq> carrier\" \"\\<And>x y. x\\<in>T \\<Longrightarrow> y\\<in>E \\<Longrightarrow> weight x \\<le> weight y\"  \"T \\<subseteq> carrier\"\n    \"no_smallest_element_skipped E T\"\n  shows \"I_minWeightBasis (T,E)\"\n  using assms by(auto simp: no_smallest_element_skipped_def I_minWeightBasis_def)\n\nlemma I_minWeightBasisG: \"I_minWeightBasis (T,E) \\<Longrightarrow> no_smallest_element_skipped E T\"\n  by(auto simp: I_minWeightBasis_def)\n\nlemma I_minWeightBasis_sorted: \"I_minWeightBasis (T,E) \\<Longrightarrow> (\\<forall>x\\<in>T.\\<forall>y\\<in>E. weight x \\<le> weight y)\"\n  by(auto simp: I_minWeightBasis_def)\n\n\nsubsection \\<open>Invariant proofs\\<close>\n\nlemma I_minWeightBasis_empty: \"I_minWeightBasis ({}, carrier)\"\n  by (auto simp: I_minWeightBasis_def)\n\nlemma I_minWeightBasis_final: \"I_minWeightBasis (T, {}) \\<Longrightarrow> minBasis T\"\n  by(auto simp: greedy_approach_leads_to_minBasis I_minWeightBasis_def)\n\nlemma indep_aux:       \n  assumes \"e \\<in> E\" \"\\<forall>e\\<in>carrier - E - F. \\<not> indep (insert e F)\"        \n    and \"x\\<in>carrier - (E - {e}) - insert e F\"\n    shows  \"\\<not> indep (insert x (insert e F))\"\n  using assms indep_iff_subset_basis by auto \n\nlemma preservation_if: \"wsorted x \\<Longrightarrow>   set x = carrier \\<Longrightarrow>\n    x = l1 @ xa # l2 \\<Longrightarrow> I_minWeightBasis (\\<sigma>, set (xa # l2))  \\<Longrightarrow> indep \\<sigma>\n   \\<Longrightarrow> xa \\<in> carrier \\<Longrightarrow> indep (insert xa \\<sigma>) \\<Longrightarrow> I_minWeightBasis (insert xa \\<sigma>, set l2)\"\n  apply(rule I_minWeightBasisI)\n  subgoal by simp      \n  subgoal unfolding I_minWeightBasis_def apply(rule indep_aux[where E=\"set (xa # l2)\"]) \n    by simp_all \n  subgoal by auto        \n  subgoal by (metis insert_iff list.set(2) I_minWeightBasis_sorted\n        sorted_wrt_append sorted_wrt.simps(2))  \n  subgoal by(auto simp: I_minWeightBasis_def)  \n  subgoal apply (rule no_smallest_element_skipped_add)\n    by(auto intro!:  simp: I_minWeightBasis_def)  \n  done\n\nlemma preservation_else: \"set x = carrier \\<Longrightarrow>\n    x = l1 @ xa # l2 \\<Longrightarrow> I_minWeightBasis (\\<sigma>, set (xa # l2))\n     \\<Longrightarrow> indep \\<sigma>   \\<Longrightarrow> \\<not> indep (insert xa \\<sigma>) \\<Longrightarrow> I_minWeightBasis (\\<sigma>, set l2)\"\n  apply(rule I_minWeightBasisI)\n  subgoal by simp\n  subgoal by (auto simp: DiffD2 I_minWeightBasis_def)   \n  subgoal by auto \n  subgoal by(auto simp: I_minWeightBasis_def)   \n  subgoal by(auto simp: I_minWeightBasis_def)  \n  subgoal apply (rule no_smallest_element_skipped_skip)\n    by(auto intro!:  simp: I_minWeightBasis_def)  \n  done\n\n\nsubsection \\<open>The refinement lemma\\<close>\n\ntheorem minWeightBasis_refine: \"(minWeightBasis, SPEC minBasis)\\<in>\\<langle>Id\\<rangle>nres_rel\"\n  unfolding minWeightBasis_def obtain_sorted_carrier_def\n  apply(refine_vcg nfoldli_rule[where I=\"\\<lambda>l1 l2 s. I_minWeightBasis (s,set l2)\"])\n  subgoal by auto\n  subgoal by (auto simp: I_minWeightBasis_empty)\n      \\<comment> \\<open>asserts\\<close>\n  subgoal by (auto simp: I_minWeightBasis_def)  \n  subgoal by (auto simp: I_minWeightBasis_def) \n  subgoal by (auto simp: I_minWeightBasis_def)   \n      \\<comment> \\<open>branches\\<close>\n  subgoal apply(rule preservation_if) by auto\n  subgoal apply(rule preservation_else) by auto  \n      \\<comment> \\<open>final\\<close>\n  subgoal by auto\n  subgoal by (auto simp: I_minWeightBasis_final)  \n  done\n\nend \\<comment> \\<open>locale minWeightBasis\\<close>\n  \nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Kruskal/MinWeightBasis.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.8723473663814338, "lm_q1q2_score": 0.7547759406708964}}
{"text": "(* author: wzh *)\n\ntheory Exercise3\n  imports Main\n\nbegin\n\ntype_synonym vname = string\ntype_synonym val = int\n\ndatatype aexp = N val | V vname | Plus aexp aexp\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N a) s = a\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a b) s = aval a s + aval b s\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (V v) = V v\" |\n\"asimp_const (N n) = N n\" |\n\"asimp_const (Plus a1 a2) = \n(\ncase (asimp_const a1, asimp_const a2) of\n  (N n1, N n2) \\<Rightarrow> N (n1 + n2) |\n(b1, b2) \\<Rightarrow> Plus b1 b2\n)\"\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N a) (N b) = N (a+b)\" |\n\"plus p (N i) = (if i = 0 then p else Plus p (N i))\" |\n\"plus (N i) p = (if i = 0 then p else Plus (N i) p)\" |\n\"plus p q = (Plus p q)\"\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N a) = N a\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus p q) = plus (asimp p) (asimp q)\"\n\n\n(* Exer 3.1 *)\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (V v) = True\" |\n\"optimal (N n) = True\" |\n\"optimal (Plus (N n1) (N n2)) = False\" |\n\"optimal (Plus a1 a2) = ((optimal a1) \\<and> (optimal a2))\"\n\ntheorem \"optimal (asimp_const x)\"\n  apply(induction x)\n    apply(auto split: aexp.split)\n  done\n\n(* Exer 3.2 *)\n(* we make together the variable terms and constant terms *)\nfun make_const :: \"aexp \\<Rightarrow> int\" where\n\"make_const (N n) = n\" |\n\"make_const (V v) = 0\" |\n\"make_const (Plus a1 a2) = (make_const a1) + (make_const a2)\"\n\nfun make_var :: \"aexp \\<Rightarrow> aexp\" where\n\"make_var (V v) = V v\" |\n\"make_var (N n) = N 0\" |\n\"make_var (Plus a1 a2) = Plus (make_var a1) (make_var a2) \"\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = Plus (make_var a) (N (make_const a))\"\n\nvalue \"full_asimp (Plus (N 12) (Plus (V a) (Plus (V b) (N 123))))\"\n\ntheorem \"aval (full_asimp a) s = aval a s\"\n  apply(induction a)\n    apply(auto)\n  done\n\n(* Exer 3.3 *)\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst name a (N n) = N n\" |\n\"subst name a (V v) = (if v = name then a else V v)\" |\n\"subst name a (Plus a1 a2) = Plus (subst name a a1) (subst name a a2)\"\n\nvalue \"subst ''x'' (N 10) (N 20)\"\nvalue \"subst ''x'' (N 10) (V ''y'')\"\nvalue \"subst ''x'' (N 10) (V ''x'')\"\nvalue \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y''))\"\n\n(* this theorem should be set simp for future proofs in 3.6 *)\ntheorem [simp]: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply(induction e)\n    apply(auto)\n  done\n\n(* \\<Longrightarrow> is a  \\<Longrightarrow> *)\ntheorem [simp]: \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply(induction e)\n    apply(auto)\n  done\n\n(* Exer 3.4 *)\ndatatype aexp2 = N2 int | V2 vname | Plus2 aexp2 aexp2 | Times2 aexp2 aexp2\n\nfun aval2 :: \"aexp2 \\<Rightarrow> state \\<Rightarrow> int\" where\n\"aval2 (N2 n) s = n\" |\n\"aval2 (V2 v) s = s v\" |\n\"aval2 (Plus2 a1 a2) s = (aval2 a1 s) + (aval2 a2 s)\" |\n\"aval2 (Times2 a1 a2) s = (aval2 a1 s) * (aval2 a2 s)\"\n\nfun asimp2 :: \"aexp2 \\<Rightarrow> aexp2\" where\n\"asimp2 (N2 n) = N2 n\" |\n\"asimp2 (V2 v) = V2 v\" |\n\"asimp2 (Plus2 a1 a2) = (\ncase (asimp2 a1, asimp2 a2) of\n(N2 n1, N2 n2) \\<Rightarrow> N2 (n1+n2) |\n(b1, b2) \\<Rightarrow> Plus2 b1 b2\n)\" |\n\"asimp2 (Times2 a1 a2) = (\ncase (asimp2 a1, asimp2 a2) of\n(N2 n1, N2 n2) \\<Rightarrow> N2 (n1*n2) |\n(N2 n1, b2) \\<Rightarrow> (if n1 = 0 then N2 0 else (if n1 = 1 then b2 else Times2 (N2 n1) b2)) |\n(b1, N2 n2) \\<Rightarrow> (if n2 = 0 then N2 0 else (if n2 = 0 then b1 else Times2 b1 (N2 n2))) |\n(b1, b2) \\<Rightarrow> Times2 b1 b2\n)\"\n\ntheorem \"aval2 (asimp2 a) s = aval2 a s\"\n  apply(induction a)\n     apply(auto split: aexp2.split)\n  done\n\n(* Exer 3.5 *)\ndatatype aexp3 = N3 int | V3 vname | Plus3 aexp3 aexp3 | Times3 aexp3 aexp3 | Post3 vname | Div3 aexp3 aexp3\n\nfun aval3 :: \"aexp3 \\<Rightarrow> state \\<Rightarrow> (val* state)\" where\n\"aval3 (N3 n) s = (n, s)\"\n| \"aval3 (V3 v) s = (s v, s)\"\n| \"aval3 (Post3 v) s = (s v, s(v := s v + 1))\"\n| \"aval3 (Plus3 a1 a2) s = (fst (aval3 a1 s) + fst (aval3 a2 (snd (aval3 a1 s))), snd (aval3 a2 (snd (aval3 a1 s))))\"\n| \"aval3 (Times3 a1 a2) s = (fst (aval3 a1 s) * fst (aval3 a2 (snd (aval3 a1 s))), snd (aval3 a2 (snd (aval3 a1 s))))\"\n| \"aval3 (Div3 a1 a2) s = (fst (aval3 a1 s) div fst (aval3 a2 (snd (aval3 a1 s))), snd (aval3 a2 (snd (aval3 a1 s))))\"\n\nvalue \"aval3 (Div3 (N3 9) (V3 y))  (\\<lambda> x. 3) \"\nvalue \"aval3 (Post3 v)  (\\<lambda> x. 12) \"\n\nfun aval3_2 :: \"aexp3 \\<Rightarrow> state \\<Rightarrow> (val * state) option\" where\n\"aval3_2 (N3 n) s = Some (n, s)\"\n| \"aval3_2 (V3 v) s = Some (s v, s)\"\n| \"aval3_2 (Post3 v) s = Some (s v, s(v := s v + 1))\"\n| \"aval3_2 (Plus3 a1 a2) s = (\n   case (aval3_2 a1 s) of\n   None \\<Rightarrow> None\n   | Some (v1, s1) \\<Rightarrow>\n     (case (aval3_2 a2 s1) of\n      None \\<Rightarrow> None\n      | Some (v2, s2) \\<Rightarrow> Some (v1 + v2, s2)))\"\n| \"aval3_2 (Times3 a1 a2) s = (\n   case (aval3_2 a1 s) of\n   None \\<Rightarrow> None \n   | Some (v1, s1) \\<Rightarrow>\n     (case (aval3_2 a2 s1) of\n      None \\<Rightarrow> None\n      | Some (v2, s2) \\<Rightarrow> Some (v1*v2, s2)))\"\n| \"aval3_2 (Div3 a1 a2) s = (\n   case (aval3_2 a1 s) of\n   None \\<Rightarrow> None\n   | Some (v1, s1) \\<Rightarrow>\n     (case (aval3_2 a2 s1) of\n      None \\<Rightarrow> None\n      | Some (v2, s2) \\<Rightarrow> (if v2 = 0 then None else Some (v1 div v2, s2))))\"\n\nvalue \"aval3_2 (Plus3 (Post3 x) (Post3 x)) (\\<lambda> x. 0)\"\nvalue \"aval3_2 (Div3 (Post3 x) (N3 1))  (\\<lambda> x. 3) \"\nvalue \"aval3_2 (Div3 (N3 9) (V3 y))  (\\<lambda> x. 3) \"\nvalue \"aval3_2 (Div3 (N3 9) (V3 y))  (\\<lambda> x. 0) \"\nvalue \"aval3_2 (Post3 v)  (\\<lambda> x. 12) \"\nvalue \"aval3_2 (Plus3 (Post3 v) (Post3 v))  (\\<lambda> x. 12) \"\nvalue \"aval3_2 (Times3 (Post3 v) (Post3 v))  (\\<lambda> x. 12) \"\nvalue \"aval3_2 (Times3 (N3 9) (Div3 (V3 t) (N3 0)))  (\\<lambda> x. 10) \"\nvalue \"aval3_2 (Times3 (N3 9) (Div3 (Post3 t) (Post3 z)))  (\\<lambda> x. 10) \"\nvalue \"aval3_2 (Times3 (Div3 (V3 z) (N3 0)) (Div3 (V3 t) (N3 0)))  (\\<lambda> x. 10) \"\n\n(* Exer 3.6 *)\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\nfun lval :: \"lexp \\<Rightarrow> state \\<Rightarrow> int\" where\n\"lval (Nl a) s = a\" |\n\"lval (Vl x) s = s x\" |\n\"lval (Plusl p q) s = lval p s + lval q s\" |\n\"lval (LET x a e) s = lval e (s(x:=lval a s))\"\n\nfun inline :: \"lexp \\<Rightarrow> aexp\" where\n\"inline (Nl a) = (N a)\" |\n\"inline (Vl x) = (V x)\" |\n\"inline (Plusl p q) = Plus (inline p) (inline q)\" |\n\"inline (LET x a e) = subst x (inline a) (inline e)\"  \n\ntheorem \"aval (inline e) s = lval e s\"\napply (induction e arbitrary: s)\napply (auto)\ndone\n\n\n(* Exer 3.7 *)\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a1 a2 = Not (Less a2 a1)\"\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a1 a2 = And (Not (Less a1 a2)) (Not (Less a2 a1))\"\n\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc b) s = b\"\n| \"bval (Not b) s = (\\<not> (bval b s))\"\n| \"bval (And b1 b2) s = ((bval b1 s) \\<and> (bval b2 s))\"\n| \"bval (Less a1 a2) s = (aval a1 s < aval a2 s)\"\n\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\"\n| \"not (Bc False) = Bc True\"\n| \"not b = Not b\"\n\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\"\n| \"and b (Bc True) = b\"\n| \"and (Bc False) b = (Bc False)\"\n| \"and b (Bc False) = (Bc False)\"\n| \"and b1 b2 = And b1 b2\"\n\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n1) (N n2) = Bc (n1 < n2)\"\n| \"less a1 a2 = Less a1 a2\"\n\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc b) = Bc b\"\n| \"bsimp (Not b) = Not (bsimp b)\"\n| \"bsimp (And b1 b2) = And (bsimp b1) (bsimp b2)\"\n| \"bsimp (Less a1 a2) = less (asimp a1) (asimp a2)\"\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n  apply (auto simp add: Eq_def)\n  done  \n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n  apply (auto simp add: Le_def)\n  done \n\n(* Exer 3.8 *)\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 c) s = c\"\n| \"ifval (Less2 a1 a2) s = (aval a1 s < aval a2 s)\"\n| \"ifval (If if1 if2 if3) s = (if (ifval if1 s) then (ifval if2 s) else (ifval if3 s))\"\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc b) = Bc2 b\"\n| \"b2ifexp (Less a1 a2) = Less2 a1 a2\"\n| \"b2ifexp (Not b) = (If (b2ifexp b) (Bc2 False) (Bc2 True))\"\n| \"b2ifexp (And b1 b2) = If (b2ifexp b1) (b2ifexp b2) (Bc2 False)\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 c) = Bc c\"\n| \"if2bexp (Less2 a1 a2) = Less a1 a2\"\n| \"if2bexp (If if1 if2 if3) = Not (And (Not (And (if2bexp if1) (if2bexp if2))) (Not (And (Not (if2bexp if1)) (if2bexp if3))))\"\n(* (a&b) \\<or> (\\<not>a&c) = \\<not>(\\<not>(a&b) \\<and> \\<not>(\\<not>a&c)) *)\n\ntheorem \"bval b s = ifval (b2ifexp b) s\"\n  apply(induction b)\n     apply(auto)\n  done\n\ntheorem \"bval (if2bexp f) s = ifval f s\"\n  apply(induction f)\n     apply(auto)\n  done\n\n(* Exer 3.9 *)\ndatatype pbexp = VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\"  \n| \"pbval (NOT b) s = (\\<not> (pbval b s))\"\n| \"pbval (AND b1 b2) s = ((pbval b1 s) \\<and> (pbval b2 s))\" \n| \"pbval (OR b1 b2) s = ((pbval b1 s) \\<or> (pbval b2 s))\"\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR v) = True\"\n| \"is_nnf (NOT (VAR v)) = True\"\n| \"is_nnf (NOT p) = False\"\n| \"is_nnf (AND p1 p2) = ((is_nnf p1) \\<and> (is_nnf p2))\"\n| \"is_nnf (OR p1 p2) = ((is_nnf p1) \\<and> (is_nnf p2))\"\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR v) = VAR v\"\n| \"nnf (NOT (VAR v)) = NOT (VAR v)\"\n| \"nnf (AND p1 p2) = AND (nnf p1) (nnf p2)\"\n| \"nnf (OR p1 p2) = OR (nnf p1) (nnf p2)\"\n| \"nnf (NOT (NOT p)) = nnf p\"\n| \"nnf (NOT (AND p1 p2)) = OR (nnf (NOT p1)) (nnf (NOT p2))\"\n| \"nnf (NOT (OR p1 p2)) = AND (nnf (NOT p1)) (nnf (NOT p2))\"\n\n\n\ntheorem \"pbval (nnf p) s = pbval p s\"                                  \n  apply(induction p)\n     apply(auto)\n  done\n\ntheorem \"is_nnf (nnf p)\"\n  apply(induction p rule: nnf.induct)\n     apply(auto)\n  done\n\n(* Exer 3.10 *)\ndatatype instr = LOADI val | LOAD vname | ADD\ntype_synonym stack = \"val list\"\n\nfun exec1_modi :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec1_modi (LOADI v) s stk = Some (v#stk)\"\n| \"exec1_modi (LOAD v) s stk = Some (s v # stk)\"\n| \"exec1_modi ADD s (x#y#stk) = Some ((x+y)#stk)\"\n| \"exec1_modi ADD s stk = None\"\n\nfun exec_modi :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" where\n\"exec_modi [] s stk = Some stk\"\n| \"exec_modi (x#xs) s stk = (\n     case (exec1_modi x s stk) of\n        None \\<Rightarrow> None\n        | Some stk2 \\<Rightarrow> exec_modi xs s stk2)\"\n\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\"\n| \"comp (V x) = [LOAD x]\"\n| \"comp (Plus e1 e2) = comp e1 @ comp e2 @ [ADD]\"\n\nlemma [simp]: \"exec_modi s1 s stk = Some stk1 \\<Longrightarrow> exec_modi (s1@s2) s stk = exec_modi s2 s stk1\"\n  apply(induction s1 arbitrary: stk)\n   apply(auto split: option.split)\n  done\n\ntheorem \"exec_modi (comp a) s stk = Some ((aval a s) # stk)\"\n  apply(induction a arbitrary: stk)\n    apply(auto)\n  done\n\n(* Exer 3.11 *)\ntype_synonym reg = nat\ndatatype instr2 = LDI int reg | LD vname reg | ADD reg reg\n\nfun exec1 :: \"instr2 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec1 (LDI n r) s1 s2 = s2(r := n)\"\n| \"exec1 (LD n r) s1 s2 = s2(r := s1 n)\"\n| \"exec1 (ADD r1 r2) s1 s2 = s2(r1 := s2 r1 + s2 r2)\"\n\nfun exec :: \"instr2 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n\"exec [] s1 s2 = s2\"\n| \"exec (x#xs) s1 s2 = exec xs s1 (exec1 x s1 s2)\"\n\nfun compiler :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr2 list\" where\n\"compiler (N n) r = [LDI n r]\"\n| \"compiler (V v) r = [LD v r]\"\n| \"compiler (Plus a1 a2) r = (compiler a1 r) @ (compiler a2 (r+1)) @ [ADD r (r+1)]\"\n\nlemma [simp]: \"exec (a@b) s1 s2 = exec b s1 (exec a s1 s2)\"\n  apply(induction a arbitrary: s2)\n   apply(auto)\n  done\n\n\n(* Meaning: compiler a q only affects those larger or equal to q, because in compiler we only mention q and q+1.\n   Thus, we do not change the key_value pair for those less than q in rs.\n *)\n\nlemma [simp]: \"q > r \\<Longrightarrow> exec (compiler a q) s rs r = rs r\"\n  apply(induction a arbitrary: r rs q)\n    apply(auto)\n  done\n\ntheorem \"exec (compiler a r) s rs r = aval a s\"\n  apply(induction a arbitrary: r rs)\n   apply(auto)\n  done\n\n(* Exer 3.12 *)\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\nfun exec1_0 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> val) \\<Rightarrow> reg \\<Rightarrow> val\" where\n\"exec1_0 (LDI0 v) s rs = rs(0 := v)\"\n| \"exec1_0 (LD0 v) s rs = rs(0 := s v)\"\n| \"exec1_0 (MV0 r) s rs = rs(r := rs 0)\"\n| \"exec1_0 (ADD0 r1) s rs = rs(0 := rs 0 + rs r1)\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> val) \\<Rightarrow> reg \\<Rightarrow> val\" where\n\"exec0 [] s rs = rs \"\n| \"exec0 (x#xs) s rs = exec0 xs s (exec1_0 x s rs)\"\n\nfun compiler0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"compiler0 (N n) r = [LDI0 n]\"\n| \"compiler0 (V v) r = [LD0 v]\"\n| \"compiler0 (Plus a1 a2) r = (compiler0 a1 (r+1)) @ [MV0 (r+1)] @ (compiler0 a2 (r+2)) @ [ADD0 (r+1)]\"\n(* Note that: r may be 0. \n In this case, first put result a1 into 0\n Second do nothing.\n Third put result a2 into 0. Then data in 0 will be overwritten.\n *)\n\nlemma [simp]: \"exec0 (a@b) s rs = exec0 b s (exec0 a s rs)\"\n  apply(induction a arbitrary: s rs b)\n   apply(auto)\n  done\n\n(* Meaning: compiler a q only affects those larger or equal to q, because in compiler we only mention q and q+1.\n   Thus, we do not change the key_value pair for those less than q in rs unless r is 0.\n *)\nlemma [simp]: \"r > 0 \\<Longrightarrow> q > r \\<Longrightarrow> exec0 (compiler0 a q) s rs r = rs r\"\n  apply(induction a arbitrary: q s rs r)\n    apply(auto)\n  done\n\ntheorem \"exec0 (compiler0 a r) s rs 0 = aval a s\"\n  apply(induction a arbitrary: r s rs)\n    apply(auto)\n  done\n\nend", "meta": {"author": "yogurt-shadow", "repo": "Isar_Exercise", "sha": "27658bff434e0845a23aeb310eeb971e4fc20b98", "save_path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise", "path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise/Isar_Exercise-27658bff434e0845a23aeb310eeb971e4fc20b98/Exercise3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971872, "lm_q2_score": 0.8354835350552603, "lm_q1q2_score": 0.7546874326617885}}
{"text": "(*  Author:     L C Paulson, University of Cambridge\n    Author:     Amine Chaieb, University of Cambridge\n    Author:     Robert Himmelmann, TU Muenchen\n    Author:     Brian Huffman, Portland State University\n*)\n\nchapter \\<open>Topology\\<close>\n\ntheory Elementary_Topology\nimports\n  \"HOL-Library.Set_Idioms\"\n  \"HOL-Library.Disjoint_Sets\"\n  Product_Vector\nbegin\n\nsection \\<open>Elementary Topology\\<close>\n\n\nsubsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Affine transformations of intervals\\<close>\n\nlemma real_affinity_le: \"0 < m \\<Longrightarrow> m * x + c \\<le> y \\<longleftrightarrow> x \\<le> inverse m * y + - (c / m)\"\n  for m :: \"'a::linordered_field\"\n  by (simp add: field_simps)\n\nlemma real_le_affinity: \"0 < m \\<Longrightarrow> y \\<le> m * x + c \\<longleftrightarrow> inverse m * y + - (c / m) \\<le> x\"\n  for m :: \"'a::linordered_field\"\n  by (simp add: field_simps)\n\nlemma real_affinity_lt: \"0 < m \\<Longrightarrow> m * x + c < y \\<longleftrightarrow> x < inverse m * y + - (c / m)\"\n  for m :: \"'a::linordered_field\"\n  by (simp add: field_simps)\n\nlemma real_lt_affinity: \"0 < m \\<Longrightarrow> y < m * x + c \\<longleftrightarrow> inverse m * y + - (c / m) < x\"\n  for m :: \"'a::linordered_field\"\n  by (simp add: field_simps)\n\nlemma real_affinity_eq: \"m \\<noteq> 0 \\<Longrightarrow> m * x + c = y \\<longleftrightarrow> x = inverse m * y + - (c / m)\"\n  for m :: \"'a::linordered_field\"\n  by (simp add: field_simps)\n\nlemma real_eq_affinity: \"m \\<noteq> 0 \\<Longrightarrow> y = m * x + c  \\<longleftrightarrow> inverse m * y + - (c / m) = x\"\n  for m :: \"'a::linordered_field\"\n  by (simp add: field_simps)\n\n\nsubsection \\<open>Topological Basis\\<close>\n\ncontext topological_space\nbegin\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"topological_basis B \\<longleftrightarrow>\n  (\\<forall>b\\<in>B. open b) \\<and> (\\<forall>x. open x \\<longrightarrow> (\\<exists>B'. B' \\<subseteq> B \\<and> \\<Union>B' = x))\"\n\nlemma topological_basis:\n  \"topological_basis B \\<longleftrightarrow> (\\<forall>x. open x \\<longleftrightarrow> (\\<exists>B'. B' \\<subseteq> B \\<and> \\<Union>B' = x))\"\n  unfolding topological_basis_def\n  apply safe\n     apply fastforce\n    apply fastforce\n   apply (erule_tac x=x in allE, simp)\n   apply (rule_tac x=\"{x}\" in exI, auto)\n  done\n\nlemma topological_basis_iff:\n  assumes \"\\<And>B'. B' \\<in> B \\<Longrightarrow> open B'\"\n  shows \"topological_basis B \\<longleftrightarrow> (\\<forall>O'. open O' \\<longrightarrow> (\\<forall>x\\<in>O'. \\<exists>B'\\<in>B. x \\<in> B' \\<and> B' \\<subseteq> O'))\"\n    (is \"_ \\<longleftrightarrow> ?rhs\")\nproof safe\n  fix O' and x::'a\n  assume H: \"topological_basis B\" \"open O'\" \"x \\<in> O'\"\n  then have \"(\\<exists>B'\\<subseteq>B. \\<Union>B' = O')\" by (simp add: topological_basis_def)\n  then obtain B' where \"B' \\<subseteq> B\" \"O' = \\<Union>B'\" by auto\n  then show \"\\<exists>B'\\<in>B. x \\<in> B' \\<and> B' \\<subseteq> O'\" using H by auto\nnext\n  assume H: ?rhs\n  show \"topological_basis B\"\n    using assms unfolding topological_basis_def\n  proof safe\n    fix O' :: \"'a set\"\n    assume \"open O'\"\n    with H obtain f where \"\\<forall>x\\<in>O'. f x \\<in> B \\<and> x \\<in> f x \\<and> f x \\<subseteq> O'\"\n      by (force intro: bchoice simp: Bex_def)\n    then show \"\\<exists>B'\\<subseteq>B. \\<Union>B' = O'\"\n      by (auto intro: exI[where x=\"{f x |x. x \\<in> O'}\"])\n  qed\nqed\n\nlemma topological_basisI:\n  assumes \"\\<And>B'. B' \\<in> B \\<Longrightarrow> open B'\"\n    and \"\\<And>O' x. open O' \\<Longrightarrow> x \\<in> O' \\<Longrightarrow> \\<exists>B'\\<in>B. x \\<in> B' \\<and> B' \\<subseteq> O'\"\n  shows \"topological_basis B\"\n  using assms by (subst topological_basis_iff) auto\n\nlemma topological_basisE:\n  fixes O'\n  assumes \"topological_basis B\"\n    and \"open O'\"\n    and \"x \\<in> O'\"\n  obtains B' where \"B' \\<in> B\" \"x \\<in> B'\" \"B' \\<subseteq> O'\"\nproof atomize_elim\n  from assms have \"\\<And>B'. B'\\<in>B \\<Longrightarrow> open B'\"\n    by (simp add: topological_basis_def)\n  with topological_basis_iff assms\n  show  \"\\<exists>B'. B' \\<in> B \\<and> x \\<in> B' \\<and> B' \\<subseteq> O'\"\n    using assms by (simp add: Bex_def)\nqed\n\nlemma topological_basis_open:\n  assumes \"topological_basis B\"\n    and \"X \\<in> B\"\n  shows \"open X\"\n  using assms by (simp add: topological_basis_def)\n\nlemma topological_basis_imp_subbasis:\n  assumes B: \"topological_basis B\"\n  shows \"open = generate_topology B\"\nproof (intro ext iffI)\n  fix S :: \"'a set\"\n  assume \"open S\"\n  with B obtain B' where \"B' \\<subseteq> B\" \"S = \\<Union>B'\"\n    unfolding topological_basis_def by blast\n  then show \"generate_topology B S\"\n    by (auto intro: generate_topology.intros dest: topological_basis_open)\nnext\n  fix S :: \"'a set\"\n  assume \"generate_topology B S\"\n  then show \"open S\"\n    by induct (auto dest: topological_basis_open[OF B])\nqed\n\nlemma basis_dense:\n  fixes B :: \"'a set set\"\n    and f :: \"'a set \\<Rightarrow> 'a\"\n  assumes \"topological_basis B\"\n    and choosefrom_basis: \"\\<And>B'. B' \\<noteq> {} \\<Longrightarrow> f B' \\<in> B'\"\n  shows \"\\<forall>X. open X \\<longrightarrow> X \\<noteq> {} \\<longrightarrow> (\\<exists>B' \\<in> B. f B' \\<in> X)\"\nproof (intro allI impI)\n  fix X :: \"'a set\"\n  assume \"open X\" and \"X \\<noteq> {}\"\n  from topological_basisE[OF \\<open>topological_basis B\\<close> \\<open>open X\\<close> choosefrom_basis[OF \\<open>X \\<noteq> {}\\<close>]]\n  obtain B' where \"B' \\<in> B\" \"f X \\<in> B'\" \"B' \\<subseteq> X\" .\n  then show \"\\<exists>B'\\<in>B. f B' \\<in> X\"\n    by (auto intro!: choosefrom_basis)\nqed\n\nend\n\nlemma topological_basis_prod:\n  assumes A: \"topological_basis A\"\n    and B: \"topological_basis B\"\n  shows \"topological_basis ((\\<lambda>(a, b). a \\<times> b) ` (A \\<times> B))\"\n  unfolding topological_basis_def\nproof (safe, simp_all del: ex_simps add: subset_image_iff ex_simps(1)[symmetric])\n  fix S :: \"('a \\<times> 'b) set\"\n  assume \"open S\"\n  then show \"\\<exists>X\\<subseteq>A \\<times> B. (\\<Union>(a,b)\\<in>X. a \\<times> b) = S\"\n  proof (safe intro!: exI[of _ \"{x\\<in>A \\<times> B. fst x \\<times> snd x \\<subseteq> S}\"])\n    fix x y\n    assume \"(x, y) \\<in> S\"\n    from open_prod_elim[OF \\<open>open S\\<close> this]\n    obtain a b where a: \"open a\"\"x \\<in> a\" and b: \"open b\" \"y \\<in> b\" and \"a \\<times> b \\<subseteq> S\"\n      by (metis mem_Sigma_iff)\n    moreover\n    from A a obtain A0 where \"A0 \\<in> A\" \"x \\<in> A0\" \"A0 \\<subseteq> a\"\n      by (rule topological_basisE)\n    moreover\n    from B b obtain B0 where \"B0 \\<in> B\" \"y \\<in> B0\" \"B0 \\<subseteq> b\"\n      by (rule topological_basisE)\n    ultimately show \"(x, y) \\<in> (\\<Union>(a, b)\\<in>{X \\<in> A \\<times> B. fst X \\<times> snd X \\<subseteq> S}. a \\<times> b)\"\n      by (intro UN_I[of \"(A0, B0)\"]) auto\n  qed auto\nqed (metis A B topological_basis_open open_Times)\n\n\nsubsection \\<open>Countable Basis\\<close>\n\nlocale\\<^marker>\\<open>tag important\\<close> countable_basis = topological_space p for p::\"'a set \\<Rightarrow> bool\" +\n  fixes B :: \"'a set set\"\n  assumes is_basis: \"topological_basis B\"\n    and countable_basis: \"countable B\"\nbegin\n\nlemma open_countable_basis_ex:\n  assumes \"p X\"\n  shows \"\\<exists>B' \\<subseteq> B. X = \\<Union>B'\"\n  using assms countable_basis is_basis\n  unfolding topological_basis_def by blast\n\nlemma open_countable_basisE:\n  assumes \"p X\"\n  obtains B' where \"B' \\<subseteq> B\" \"X = \\<Union>B'\"\n  using assms open_countable_basis_ex\n  by atomize_elim simp\n\nlemma countable_dense_exists:\n  \"\\<exists>D::'a set. countable D \\<and> (\\<forall>X. p X \\<longrightarrow> X \\<noteq> {} \\<longrightarrow> (\\<exists>d \\<in> D. d \\<in> X))\"\nproof -\n  let ?f = \"(\\<lambda>B'. SOME x. x \\<in> B')\"\n  have \"countable (?f ` B)\" using countable_basis by simp\n  with basis_dense[OF is_basis, of ?f] show ?thesis\n    by (intro exI[where x=\"?f ` B\"]) (metis (mono_tags) all_not_in_conv imageI someI)\nqed\n\nlemma countable_dense_setE:\n  obtains D :: \"'a set\"\n  where \"countable D\" \"\\<And>X. p X \\<Longrightarrow> X \\<noteq> {} \\<Longrightarrow> \\<exists>d \\<in> D. d \\<in> X\"\n  using countable_dense_exists by blast\n\nend\n\nlemma countable_basis_openI: \"countable_basis open B\"\n  if \"countable B\" \"topological_basis B\"\n  using that\n  by unfold_locales\n    (simp_all add: topological_basis topological_space.topological_basis topological_space_axioms)\n\nlemma (in first_countable_topology) first_countable_basisE:\n  fixes x :: 'a\n  obtains \\<A> where \"countable \\<A>\" \"\\<And>A. A \\<in> \\<A> \\<Longrightarrow> x \\<in> A\" \"\\<And>A. A \\<in> \\<A> \\<Longrightarrow> open A\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> (\\<exists>A\\<in>\\<A>. A \\<subseteq> S)\"\nproof -\n  obtain \\<A> where \\<A>: \"(\\<forall>i::nat. x \\<in> \\<A> i \\<and> open (\\<A> i))\" \"(\\<forall>S. open S \\<and> x \\<in> S \\<longrightarrow> (\\<exists>i. \\<A> i \\<subseteq> S))\"\n    using first_countable_basis[of x] by metis\n  show thesis\n  proof \n    show \"countable (range \\<A>)\"\n      by simp\n  qed (use \\<A> in auto)\nqed\n\nlemma (in first_countable_topology) first_countable_basis_Int_stableE:\n  obtains \\<A> where \"countable \\<A>\" \"\\<And>A. A \\<in> \\<A> \\<Longrightarrow> x \\<in> A\" \"\\<And>A. A \\<in> \\<A> \\<Longrightarrow> open A\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> (\\<exists>A\\<in>\\<A>. A \\<subseteq> S)\"\n    \"\\<And>A B. A \\<in> \\<A> \\<Longrightarrow> B \\<in> \\<A> \\<Longrightarrow> A \\<inter> B \\<in> \\<A>\"\nproof atomize_elim\n  obtain \\<B> where \\<B>:\n    \"countable \\<B>\"\n    \"\\<And>B. B \\<in> \\<B> \\<Longrightarrow> x \\<in> B\"\n    \"\\<And>B. B \\<in> \\<B> \\<Longrightarrow> open B\"\n    \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>B\\<in>\\<B>. B \\<subseteq> S\"\n    by (rule first_countable_basisE) blast\n  define \\<A> where [abs_def]:\n    \"\\<A> = (\\<lambda>N. \\<Inter>((\\<lambda>n. from_nat_into \\<B> n) ` N)) ` (Collect finite::nat set set)\"\n  then show \"\\<exists>\\<A>. countable \\<A> \\<and> (\\<forall>A. A \\<in> \\<A> \\<longrightarrow> x \\<in> A) \\<and> (\\<forall>A. A \\<in> \\<A> \\<longrightarrow> open A) \\<and>\n        (\\<forall>S. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> (\\<exists>A\\<in>\\<A>. A \\<subseteq> S)) \\<and> (\\<forall>A B. A \\<in> \\<A> \\<longrightarrow> B \\<in> \\<A> \\<longrightarrow> A \\<inter> B \\<in> \\<A>)\"\n  proof (safe intro!: exI[where x=\\<A>])\n    show \"countable \\<A>\"\n      unfolding \\<A>_def by (intro countable_image countable_Collect_finite)\n    fix A\n    assume \"A \\<in> \\<A>\"\n    then show \"x \\<in> A\" \"open A\"\n      using \\<B>(4)[OF open_UNIV] by (auto simp: \\<A>_def intro: \\<B> from_nat_into)\n  next\n    let ?int = \"\\<lambda>N. \\<Inter>(from_nat_into \\<B> ` N)\"\n    fix A B\n    assume \"A \\<in> \\<A>\" \"B \\<in> \\<A>\"\n    then obtain N M where \"A = ?int N\" \"B = ?int M\" \"finite (N \\<union> M)\"\n      by (auto simp: \\<A>_def)\n    then show \"A \\<inter> B \\<in> \\<A>\"\n      by (auto simp: \\<A>_def intro!: image_eqI[where x=\"N \\<union> M\"])\n  next\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    then obtain a where a: \"a\\<in>\\<B>\" \"a \\<subseteq> S\" using \\<B> by blast\n    then show \"\\<exists>a\\<in>\\<A>. a \\<subseteq> S\" using a \\<B>\n      by (intro bexI[where x=a]) (auto simp: \\<A>_def intro: image_eqI[where x=\"{to_nat_on \\<B> a}\"])\n  qed\nqed\n\nlemma (in topological_space) first_countableI:\n  assumes \"countable \\<A>\"\n    and 1: \"\\<And>A. A \\<in> \\<A> \\<Longrightarrow> x \\<in> A\" \"\\<And>A. A \\<in> \\<A> \\<Longrightarrow> open A\"\n    and 2: \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> \\<exists>A\\<in>\\<A>. A \\<subseteq> S\"\n  shows \"\\<exists>\\<A>::nat \\<Rightarrow> 'a set. (\\<forall>i. x \\<in> \\<A> i \\<and> open (\\<A> i)) \\<and> (\\<forall>S. open S \\<and> x \\<in> S \\<longrightarrow> (\\<exists>i. \\<A> i \\<subseteq> S))\"\nproof (safe intro!: exI[of _ \"from_nat_into \\<A>\"])\n  fix i\n  have \"\\<A> \\<noteq> {}\" using 2[of UNIV] by auto\n  show \"x \\<in> from_nat_into \\<A> i\" \"open (from_nat_into \\<A> i)\"\n    using range_from_nat_into_subset[OF \\<open>\\<A> \\<noteq> {}\\<close>] 1 by auto\nnext\n  fix S\n  assume \"open S\" \"x\\<in>S\" from 2[OF this]\n  show \"\\<exists>i. from_nat_into \\<A> i \\<subseteq> S\"\n    using subset_range_from_nat_into[OF \\<open>countable \\<A>\\<close>] by auto\nqed\n\ninstance prod :: (first_countable_topology, first_countable_topology) first_countable_topology\nproof\n  fix x :: \"'a \\<times> 'b\"\n  obtain \\<A> where \\<A>:\n      \"countable \\<A>\"\n      \"\\<And>a. a \\<in> \\<A> \\<Longrightarrow> fst x \\<in> a\"\n      \"\\<And>a. a \\<in> \\<A> \\<Longrightarrow> open a\"\n      \"\\<And>S. open S \\<Longrightarrow> fst x \\<in> S \\<Longrightarrow> \\<exists>a\\<in>\\<A>. a \\<subseteq> S\"\n    by (rule first_countable_basisE[of \"fst x\"]) blast\n  obtain B where B:\n      \"countable B\"\n      \"\\<And>a. a \\<in> B \\<Longrightarrow> snd x \\<in> a\"\n      \"\\<And>a. a \\<in> B \\<Longrightarrow> open a\"\n      \"\\<And>S. open S \\<Longrightarrow> snd x \\<in> S \\<Longrightarrow> \\<exists>a\\<in>B. a \\<subseteq> S\"\n    by (rule first_countable_basisE[of \"snd x\"]) blast\n  show \"\\<exists>\\<A>::nat \\<Rightarrow> ('a \\<times> 'b) set.\n    (\\<forall>i. x \\<in> \\<A> i \\<and> open (\\<A> i)) \\<and> (\\<forall>S. open S \\<and> x \\<in> S \\<longrightarrow> (\\<exists>i. \\<A> i \\<subseteq> S))\"\n  proof (rule first_countableI[of \"(\\<lambda>(a, b). a \\<times> b) ` (\\<A> \\<times> B)\"], safe)\n    fix a b\n    assume x: \"a \\<in> \\<A>\" \"b \\<in> B\"\n    show \"x \\<in> a \\<times> b\" \n      by (simp add: \\<A>(2) B(2) mem_Times_iff x)\n    show \"open (a \\<times> b)\"\n      by (simp add: \\<A>(3) B(3) open_Times x)\n  next\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    then obtain a' b' where a'b': \"open a'\" \"open b'\" \"x \\<in> a' \\<times> b'\" \"a' \\<times> b' \\<subseteq> S\"\n      by (rule open_prod_elim)\n    moreover\n    from a'b' \\<A>(4)[of a'] B(4)[of b']\n    obtain a b where \"a \\<in> \\<A>\" \"a \\<subseteq> a'\" \"b \\<in> B\" \"b \\<subseteq> b'\"\n      by auto\n    ultimately\n    show \"\\<exists>a\\<in>(\\<lambda>(a, b). a \\<times> b) ` (\\<A> \\<times> B). a \\<subseteq> S\"\n      by (auto intro!: bexI[of _ \"a \\<times> b\"] bexI[of _ a] bexI[of _ b])\n  qed (simp add: \\<A> B)\nqed\n\nclass second_countable_topology = topological_space +\n  assumes ex_countable_subbasis:\n    \"\\<exists>B::'a set set. countable B \\<and> open = generate_topology B\"\nbegin\n\nlemma ex_countable_basis: \"\\<exists>B::'a set set. countable B \\<and> topological_basis B\"\nproof -\n  from ex_countable_subbasis obtain B where B: \"countable B\" \"open = generate_topology B\"\n    by blast\n  let ?B = \"Inter ` {b. finite b \\<and> b \\<subseteq> B }\"\n\n  show ?thesis\n  proof (intro exI conjI)\n    show \"countable ?B\"\n      by (intro countable_image countable_Collect_finite_subset B)\n    {\n      fix S\n      assume \"open S\"\n      then have \"\\<exists>B'\\<subseteq>{b. finite b \\<and> b \\<subseteq> B}. (\\<Union>b\\<in>B'. \\<Inter>b) = S\"\n        unfolding B\n      proof induct\n        case UNIV\n        show ?case by (intro exI[of _ \"{{}}\"]) simp\n      next\n        case (Int a b)\n        then obtain x y where x: \"a = \\<Union>(Inter ` x)\" \"\\<And>i. i \\<in> x \\<Longrightarrow> finite i \\<and> i \\<subseteq> B\"\n          and y: \"b = \\<Union>(Inter ` y)\" \"\\<And>i. i \\<in> y \\<Longrightarrow> finite i \\<and> i \\<subseteq> B\"\n          by blast\n        show ?case\n          unfolding x y Int_UN_distrib2\n          by (intro exI[of _ \"{i \\<union> j| i j.  i \\<in> x \\<and> j \\<in> y}\"]) (auto dest: x(2) y(2))\n      next\n        case (UN K)\n        then have \"\\<forall>k\\<in>K. \\<exists>B'\\<subseteq>{b. finite b \\<and> b \\<subseteq> B}. \\<Union> (Inter ` B') = k\" by auto\n        then obtain k where\n            \"\\<forall>ka\\<in>K. k ka \\<subseteq> {b. finite b \\<and> b \\<subseteq> B} \\<and> \\<Union>(Inter ` (k ka)) = ka\"\n          unfolding bchoice_iff ..\n        then show \"\\<exists>B'\\<subseteq>{b. finite b \\<and> b \\<subseteq> B}. \\<Union> (Inter ` B') = \\<Union>K\"\n          by (intro exI[of _ \"\\<Union>(k ` K)\"]) auto\n      next\n        case (Basis S)\n        then show ?case\n          by (intro exI[of _ \"{{S}}\"]) auto\n      qed\n      then have \"(\\<exists>B'\\<subseteq>Inter ` {b. finite b \\<and> b \\<subseteq> B}. \\<Union>B' = S)\"\n        unfolding subset_image_iff by blast }\n    then show \"topological_basis ?B\"\n      unfolding topological_basis_def\n      by (safe intro!: open_Inter)\n         (simp_all add: B generate_topology.Basis subset_eq)\n  qed\nqed\n\n\nend\n\nlemma univ_second_countable:\n  obtains \\<B> :: \"'a::second_countable_topology set set\"\n  where \"countable \\<B>\" \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> open C\"\n       \"\\<And>S. open S \\<Longrightarrow> \\<exists>U. U \\<subseteq> \\<B> \\<and> S = \\<Union>U\"\nby (metis ex_countable_basis topological_basis_def)\n\nproposition Lindelof:\n  fixes \\<F> :: \"'a::second_countable_topology set set\"\n  assumes \\<F>: \"\\<And>S. S \\<in> \\<F> \\<Longrightarrow> open S\"\n  obtains \\<F>' where \"\\<F>' \\<subseteq> \\<F>\" \"countable \\<F>'\" \"\\<Union>\\<F>' = \\<Union>\\<F>\"\nproof -\n  obtain \\<B> :: \"'a set set\"\n    where \"countable \\<B>\" \"\\<And>C. C \\<in> \\<B> \\<Longrightarrow> open C\"\n      and \\<B>: \"\\<And>S. open S \\<Longrightarrow> \\<exists>U. U \\<subseteq> \\<B> \\<and> S = \\<Union>U\"\n    using univ_second_countable by blast\n  define \\<D> where \"\\<D> \\<equiv> {S. S \\<in> \\<B> \\<and> (\\<exists>U. U \\<in> \\<F> \\<and> S \\<subseteq> U)}\"\n  have \"countable \\<D>\"\n    apply (rule countable_subset [OF _ \\<open>countable \\<B>\\<close>])\n    apply (force simp: \\<D>_def)\n    done\n  have \"\\<And>S. \\<exists>U. S \\<in> \\<D> \\<longrightarrow> U \\<in> \\<F> \\<and> S \\<subseteq> U\"\n    by (simp add: \\<D>_def)\n  then obtain G where G: \"\\<And>S. S \\<in> \\<D> \\<longrightarrow> G S \\<in> \\<F> \\<and> S \\<subseteq> G S\"\n    by metis\n  have \"\\<Union>\\<F> \\<subseteq> \\<Union>\\<D>\"\n    unfolding \\<D>_def by (blast dest: \\<F> \\<B>)\n  moreover have \"\\<Union>\\<D> \\<subseteq> \\<Union>\\<F>\"\n    using \\<D>_def by blast\n  ultimately have eq1: \"\\<Union>\\<F> = \\<Union>\\<D>\" ..\n  have eq2: \"\\<Union>\\<D> = \\<Union> (G ` \\<D>)\"\n    using G eq1 by auto\n  show ?thesis\n    apply (rule_tac \\<F>' = \"G ` \\<D>\" in that)\n    using G \\<open>countable \\<D>\\<close>\n    by (auto simp: eq1 eq2)\nqed\n\nlemma countable_disjoint_open_subsets:\n  fixes \\<F> :: \"'a::second_countable_topology set set\"\n  assumes \"\\<And>S. S \\<in> \\<F> \\<Longrightarrow> open S\" and pw: \"pairwise disjnt \\<F>\"\n    shows \"countable \\<F>\"\nproof -\n  obtain \\<F>' where \"\\<F>' \\<subseteq> \\<F>\" \"countable \\<F>'\" \"\\<Union>\\<F>' = \\<Union>\\<F>\"\n    by (meson assms Lindelof)\n  with pw have \"\\<F> \\<subseteq> insert {} \\<F>'\"\n    by (fastforce simp add: pairwise_def disjnt_iff)\n  then show ?thesis\n    by (simp add: \\<open>countable \\<F>'\\<close> countable_subset)\nqed\n\nsublocale second_countable_topology <\n  countable_basis \"open\" \"SOME B. countable B \\<and> topological_basis B\"\n  using someI_ex[OF ex_countable_basis]\n  by unfold_locales safe\n\n\ninstance prod :: (second_countable_topology, second_countable_topology) second_countable_topology\nproof\n  obtain A :: \"'a set set\" where \"countable A\" \"topological_basis A\"\n    using ex_countable_basis by auto\n  moreover\n  obtain B :: \"'b set set\" where \"countable B\" \"topological_basis B\"\n    using ex_countable_basis by auto\n  ultimately show \"\\<exists>B::('a \\<times> 'b) set set. countable B \\<and> open = generate_topology B\"\n    by (auto intro!: exI[of _ \"(\\<lambda>(a, b). a \\<times> b) ` (A \\<times> B)\"] topological_basis_prod\n      topological_basis_imp_subbasis)\nqed\n\ninstance second_countable_topology \\<subseteq> first_countable_topology\nproof\n  fix x :: 'a\n  define B :: \"'a set set\" where \"B = (SOME B. countable B \\<and> topological_basis B)\"\n  then have B: \"countable B\" \"topological_basis B\"\n    using countable_basis is_basis\n    by (auto simp: countable_basis is_basis)\n  then show \"\\<exists>A::nat \\<Rightarrow> 'a set.\n    (\\<forall>i. x \\<in> A i \\<and> open (A i)) \\<and> (\\<forall>S. open S \\<and> x \\<in> S \\<longrightarrow> (\\<exists>i. A i \\<subseteq> S))\"\n    by (intro first_countableI[of \"{b\\<in>B. x \\<in> b}\"])\n       (fastforce simp: topological_space_class.topological_basis_def)+\nqed\n\ninstance nat :: second_countable_topology\nproof\n  show \"\\<exists>B::nat set set. countable B \\<and> open = generate_topology B\"\n    by (intro exI[of _ \"range lessThan \\<union> range greaterThan\"]) (auto simp: open_nat_def)\nqed\n\nlemma countable_separating_set_linorder1:\n  shows \"\\<exists>B::('a::{linorder_topology, second_countable_topology} set). countable B \\<and> (\\<forall>x y. x < y \\<longrightarrow> (\\<exists>b \\<in> B. x < b \\<and> b \\<le> y))\"\nproof -\n  obtain A::\"'a set set\" where \"countable A\" \"topological_basis A\" using ex_countable_basis by auto\n  define B1 where \"B1 = {(LEAST x. x \\<in> U)| U. U \\<in> A}\"\n  then have \"countable B1\" using \\<open>countable A\\<close> by (simp add: Setcompr_eq_image)\n  define B2 where \"B2 = {(SOME x. x \\<in> U)| U. U \\<in> A}\"\n  then have \"countable B2\" using \\<open>countable A\\<close> by (simp add: Setcompr_eq_image)\n  have \"\\<exists>b \\<in> B1 \\<union> B2. x < b \\<and> b \\<le> y\" if \"x < y\" for x y\n  proof (cases)\n    assume \"\\<exists>z. x < z \\<and> z < y\"\n    then obtain z where z: \"x < z \\<and> z < y\" by auto\n    define U where \"U = {x<..<y}\"\n    then have \"open U\" by simp\n    moreover have \"z \\<in> U\" using z U_def by simp\n    ultimately obtain V where \"V \\<in> A\" \"z \\<in> V\" \"V \\<subseteq> U\" \n      using topological_basisE[OF \\<open>topological_basis A\\<close>] by auto\n    define w where \"w = (SOME x. x \\<in> V)\"\n    then have \"w \\<in> V\" using \\<open>z \\<in> V\\<close> by (metis someI2)\n    then have \"x < w \\<and> w \\<le> y\" using \\<open>w \\<in> V\\<close> \\<open>V \\<subseteq> U\\<close> U_def by fastforce\n    moreover have \"w \\<in> B1 \\<union> B2\" using w_def B2_def \\<open>V \\<in> A\\<close> by auto\n    ultimately show ?thesis by auto\n  next\n    assume \"\\<not>(\\<exists>z. x < z \\<and> z < y)\"\n    then have *: \"\\<And>z. z > x \\<Longrightarrow> z \\<ge> y\" by auto\n    define U where \"U = {x<..}\"\n    then have \"open U\" by simp\n    moreover have \"y \\<in> U\" using \\<open>x < y\\<close> U_def by simp\n    ultimately obtain \"V\" where \"V \\<in> A\" \"y \\<in> V\" \"V \\<subseteq> U\" \n      using topological_basisE[OF \\<open>topological_basis A\\<close>] by auto\n    have \"U = {y..}\" unfolding U_def using * \\<open>x < y\\<close> by auto\n    then have \"V \\<subseteq> {y..}\" using \\<open>V \\<subseteq> U\\<close> by simp\n    then have \"(LEAST w. w \\<in> V) = y\" using \\<open>y \\<in> V\\<close> by (meson Least_equality atLeast_iff subsetCE)\n    then have \"y \\<in> B1 \\<union> B2\" using \\<open>V \\<in> A\\<close> B1_def by auto\n    moreover have \"x < y \\<and> y \\<le> y\" using \\<open>x < y\\<close> by simp\n    ultimately show ?thesis by auto\n  qed\n  moreover have \"countable (B1 \\<union> B2)\" using \\<open>countable B1\\<close> \\<open>countable B2\\<close> by simp\n  ultimately show ?thesis by auto\nqed\n\nlemma countable_separating_set_linorder2:\n  shows \"\\<exists>B::('a::{linorder_topology, second_countable_topology} set). countable B \\<and> (\\<forall>x y. x < y \\<longrightarrow> (\\<exists>b \\<in> B. x \\<le> b \\<and> b < y))\"\nproof -\n  obtain A::\"'a set set\" where \"countable A\" \"topological_basis A\" using ex_countable_basis by auto\n  define B1 where \"B1 = {(GREATEST x. x \\<in> U) | U. U \\<in> A}\"\n  then have \"countable B1\" using \\<open>countable A\\<close> by (simp add: Setcompr_eq_image)\n  define B2 where \"B2 = {(SOME x. x \\<in> U)| U. U \\<in> A}\"\n  then have \"countable B2\" using \\<open>countable A\\<close> by (simp add: Setcompr_eq_image)\n  have \"\\<exists>b \\<in> B1 \\<union> B2. x \\<le> b \\<and> b < y\" if \"x < y\" for x y\n  proof (cases)\n    assume \"\\<exists>z. x < z \\<and> z < y\"\n    then obtain z where z: \"x < z \\<and> z < y\" by auto\n    define U where \"U = {x<..<y}\"\n    then have \"open U\" by simp\n    moreover have \"z \\<in> U\" using z U_def by simp\n    ultimately obtain \"V\" where \"V \\<in> A\" \"z \\<in> V\" \"V \\<subseteq> U\" \n      using topological_basisE[OF \\<open>topological_basis A\\<close>] by auto\n    define w where \"w = (SOME x. x \\<in> V)\"\n    then have \"w \\<in> V\" using \\<open>z \\<in> V\\<close> by (metis someI2)\n    then have \"x \\<le> w \\<and> w < y\" using \\<open>w \\<in> V\\<close> \\<open>V \\<subseteq> U\\<close> U_def by fastforce\n    moreover have \"w \\<in> B1 \\<union> B2\" using w_def B2_def \\<open>V \\<in> A\\<close> by auto\n    ultimately show ?thesis by auto\n  next\n    assume \"\\<not>(\\<exists>z. x < z \\<and> z < y)\"\n    then have *: \"\\<And>z. z < y \\<Longrightarrow> z \\<le> x\" using leI by blast\n    define U where \"U = {..<y}\"\n    then have \"open U\" by simp\n    moreover have \"x \\<in> U\" using \\<open>x < y\\<close> U_def by simp\n    ultimately obtain \"V\" where \"V \\<in> A\" \"x \\<in> V\" \"V \\<subseteq> U\" \n      using topological_basisE[OF \\<open>topological_basis A\\<close>] by auto\n    have \"U = {..x}\" unfolding U_def using * \\<open>x < y\\<close> by auto\n    then have \"V \\<subseteq> {..x}\" using \\<open>V \\<subseteq> U\\<close> by simp\n    then have \"(GREATEST x. x \\<in> V) = x\" using \\<open>x \\<in> V\\<close> by (meson Greatest_equality atMost_iff subsetCE)\n    then have \"x \\<in> B1 \\<union> B2\" using \\<open>V \\<in> A\\<close> B1_def by auto\n    moreover have \"x \\<le> x \\<and> x < y\" using \\<open>x < y\\<close> by simp\n    ultimately show ?thesis by auto\n  qed\n  moreover have \"countable (B1 \\<union> B2)\" using \\<open>countable B1\\<close> \\<open>countable B2\\<close> by simp\n  ultimately show ?thesis by auto\nqed\n\nlemma countable_separating_set_dense_linorder:\n  shows \"\\<exists>B::('a::{linorder_topology, dense_linorder, second_countable_topology} set). countable B \\<and> (\\<forall>x y. x < y \\<longrightarrow> (\\<exists>b \\<in> B. x < b \\<and> b < y))\"\nproof -\n  obtain B::\"'a set\" where B: \"countable B\" \"\\<And>x y. x < y \\<Longrightarrow> (\\<exists>b \\<in> B. x < b \\<and> b \\<le> y)\"\n    using countable_separating_set_linorder1 by auto\n  have \"\\<exists>b \\<in> B. x < b \\<and> b < y\" if \"x < y\" for x y\n  proof -\n    obtain z where \"x < z\" \"z < y\" using \\<open>x < y\\<close> dense by blast\n    then obtain b where \"b \\<in> B\" \"x < b \\<and> b \\<le> z\" using B(2) by auto\n    then have \"x < b \\<and> b < y\" using \\<open>z < y\\<close> by auto\n    then show ?thesis using \\<open>b \\<in> B\\<close> by auto\n  qed\n  then show ?thesis using B(1) by auto\nqed\n\n\nsubsection \\<open>Polish spaces\\<close>\n\ntext \\<open>Textbooks define Polish spaces as completely metrizable.\n  We assume the topology to be complete for a given metric.\\<close>\n\nclass polish_space = complete_space + second_countable_topology\n\n\nsubsection \\<open>Limit Points\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> (in topological_space) islimpt:: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infixr \"islimpt\" 60)\n  where \"x islimpt S \\<longleftrightarrow> (\\<forall>T. x\\<in>T \\<longrightarrow> open T \\<longrightarrow> (\\<exists>y\\<in>S. y\\<in>T \\<and> y\\<noteq>x))\"\n\nlemma islimptI:\n  assumes \"\\<And>T. x \\<in> T \\<Longrightarrow> open T \\<Longrightarrow> \\<exists>y\\<in>S. y \\<in> T \\<and> y \\<noteq> x\"\n  shows \"x islimpt S\"\n  using assms unfolding islimpt_def by auto\n\nlemma islimptE:\n  assumes \"x islimpt S\" and \"x \\<in> T\" and \"open T\"\n  obtains y where \"y \\<in> S\" and \"y \\<in> T\" and \"y \\<noteq> x\"\n  using assms unfolding islimpt_def by auto\n\nlemma islimpt_iff_eventually: \"x islimpt S \\<longleftrightarrow> \\<not> eventually (\\<lambda>y. y \\<notin> S) (at x)\"\n  unfolding islimpt_def eventually_at_topological by auto\n\nlemma islimpt_subset: \"x islimpt S \\<Longrightarrow> S \\<subseteq> T \\<Longrightarrow> x islimpt T\"\n  unfolding islimpt_def by fast\n\nlemma islimpt_UNIV_iff: \"x islimpt UNIV \\<longleftrightarrow> \\<not> open {x}\"\n  unfolding islimpt_def by (safe, fast, case_tac \"T = {x}\", fast, fast)\n\nlemma islimpt_punctured: \"x islimpt S = x islimpt (S-{x})\"\n  unfolding islimpt_def by blast\n\ntext \\<open>A perfect space has no isolated points.\\<close>\n\nlemma islimpt_UNIV [simp, intro]: \"x islimpt UNIV\"\n  for x :: \"'a::perfect_space\"\n  unfolding islimpt_UNIV_iff by (rule not_open_singleton)\n\nlemma closed_limpt: \"closed S \\<longleftrightarrow> (\\<forall>x. x islimpt S \\<longrightarrow> x \\<in> S)\"\n  unfolding closed_def\n  apply (subst open_subopen)\n  apply (simp add: islimpt_def subset_eq)\n  apply (metis ComplE ComplI)\n  done\n\nlemma islimpt_EMPTY[simp]: \"\\<not> x islimpt {}\"\n  by (auto simp: islimpt_def)\n\nlemma islimpt_Un: \"x islimpt (S \\<union> T) \\<longleftrightarrow> x islimpt S \\<or> x islimpt T\"\n  by (simp add: islimpt_iff_eventually eventually_conj_iff)\n\nlemma islimpt_finite_union_iff:\n  assumes \"finite A\"\n  shows   \"z islimpt (\\<Union>x\\<in>A. B x) \\<longleftrightarrow> (\\<exists>x\\<in>A. z islimpt B x)\"\n  using assms by (induction rule: finite_induct) (simp_all add: islimpt_Un)\n\nlemma islimpt_insert:\n  fixes x :: \"'a::t1_space\"\n  shows \"x islimpt (insert a s) \\<longleftrightarrow> x islimpt s\"\nproof\n  assume \"x islimpt (insert a s)\"\n  then show \"x islimpt s\"\n    by (metis closed_limpt closed_singleton empty_iff insert_iff insert_is_Un islimpt_Un islimpt_def)\nnext\n  assume \"x islimpt s\"\n  then show \"x islimpt (insert a s)\"\n    by (rule islimpt_subset) auto\nqed\n\nlemma islimpt_finite:\n  fixes x :: \"'a::t1_space\"\n  shows \"finite s \\<Longrightarrow> \\<not> x islimpt s\"\n  by (induct set: finite) (simp_all add: islimpt_insert)\n\nlemma islimpt_Un_finite:\n  fixes x :: \"'a::t1_space\"\n  shows \"finite s \\<Longrightarrow> x islimpt (s \\<union> t) \\<longleftrightarrow> x islimpt t\"\n  by (simp add: islimpt_Un islimpt_finite)\n\nlemma islimpt_eq_acc_point:\n  fixes l :: \"'a :: t1_space\"\n  shows \"l islimpt S \\<longleftrightarrow> (\\<forall>U. l\\<in>U \\<longrightarrow> open U \\<longrightarrow> infinite (U \\<inter> S))\"\nproof (safe intro!: islimptI)\n  fix U\n  assume \"l islimpt S\" \"l \\<in> U\" \"open U\" \"finite (U \\<inter> S)\"\n  then have \"l islimpt S\" \"l \\<in> (U - (U \\<inter> S - {l}))\" \"open (U - (U \\<inter> S - {l}))\"\n    by (auto intro: finite_imp_closed)\n  then show False\n    by (rule islimptE) auto\nnext\n  fix T\n  assume *: \"\\<forall>U. l\\<in>U \\<longrightarrow> open U \\<longrightarrow> infinite (U \\<inter> S)\" \"l \\<in> T\" \"open T\"\n  then have \"infinite (T \\<inter> S - {l})\"\n    by auto\n  then have \"\\<exists>x. x \\<in> (T \\<inter> S - {l})\"\n    unfolding ex_in_conv by (intro notI) simp\n  then show \"\\<exists>y\\<in>S. y \\<in> T \\<and> y \\<noteq> l\"\n    by auto\nqed\n\nlemma acc_point_range_imp_convergent_subsequence:\n  fixes l :: \"'a :: first_countable_topology\"\n  assumes l: \"\\<forall>U. l\\<in>U \\<longrightarrow> open U \\<longrightarrow> infinite (U \\<inter> range f)\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\nproof -\n  from countable_basis_at_decseq[of l]\n  obtain A where A:\n      \"\\<And>i. open (A i)\"\n      \"\\<And>i. l \\<in> A i\"\n      \"\\<And>S. open S \\<Longrightarrow> l \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\n    by blast\n  define s where \"s n i = (SOME j. i < j \\<and> f j \\<in> A (Suc n))\" for n i\n  {\n    fix n i\n    have \"infinite (A (Suc n) \\<inter> range f - f`{.. i})\"\n      using l A by auto\n    then have \"\\<exists>x. x \\<in> A (Suc n) \\<inter> range f - f`{.. i}\"\n      unfolding ex_in_conv by (intro notI) simp\n    then have \"\\<exists>j. f j \\<in> A (Suc n) \\<and> j \\<notin> {.. i}\"\n      by auto\n    then have \"\\<exists>a. i < a \\<and> f a \\<in> A (Suc n)\"\n      by (auto simp: not_le)\n    then have \"i < s n i\" \"f (s n i) \\<in> A (Suc n)\"\n      unfolding s_def by (auto intro: someI2_ex)\n  }\n  note s = this\n  define r where \"r = rec_nat (s 0 0) s\"\n  have \"strict_mono r\"\n    by (auto simp: r_def s strict_mono_Suc_iff)\n  moreover\n  have \"(\\<lambda>n. f (r n)) \\<longlonglongrightarrow> l\"\n  proof (rule topological_tendstoI)\n    fix S\n    assume \"open S\" \"l \\<in> S\"\n    with A(3) have \"eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\n      by auto\n    moreover\n    {\n      fix i\n      assume \"Suc 0 \\<le> i\"\n      then have \"f (r i) \\<in> A i\"\n        by (cases i) (simp_all add: r_def s)\n    }\n    then have \"eventually (\\<lambda>i. f (r i) \\<in> A i) sequentially\"\n      by (auto simp: eventually_sequentially)\n    ultimately show \"eventually (\\<lambda>i. f (r i) \\<in> S) sequentially\"\n      by eventually_elim auto\n  qed\n  ultimately show \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n    by (auto simp: convergent_def comp_def)\nqed\n\nlemma islimpt_range_imp_convergent_subsequence:\n  fixes l :: \"'a :: {t1_space, first_countable_topology}\"\n  assumes l: \"l islimpt (range f)\"\n  shows \"\\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n  using l unfolding islimpt_eq_acc_point\n  by (rule acc_point_range_imp_convergent_subsequence)\n\nlemma sequence_unique_limpt:\n  fixes f :: \"nat \\<Rightarrow> 'a::t2_space\"\n  assumes \"(f \\<longlongrightarrow> l) sequentially\"\n    and \"l' islimpt (range f)\"\n  shows \"l' = l\"\nproof (rule ccontr)\n  assume \"l' \\<noteq> l\"\n  obtain s t where \"open s\" \"open t\" \"l' \\<in> s\" \"l \\<in> t\" \"s \\<inter> t = {}\"\n    using hausdorff [OF \\<open>l' \\<noteq> l\\<close>] by auto\n  have \"eventually (\\<lambda>n. f n \\<in> t) sequentially\"\n    using assms(1) \\<open>open t\\<close> \\<open>l \\<in> t\\<close> by (rule topological_tendstoD)\n  then obtain N where \"\\<forall>n\\<ge>N. f n \\<in> t\"\n    unfolding eventually_sequentially by auto\n\n  have \"UNIV = {..<N} \\<union> {N..}\"\n    by auto\n  then have \"l' islimpt (f ` ({..<N} \\<union> {N..}))\"\n    using assms(2) by simp\n  then have \"l' islimpt (f ` {..<N} \\<union> f ` {N..})\"\n    by (simp add: image_Un)\n  then have \"l' islimpt (f ` {N..})\"\n    by (simp add: islimpt_Un_finite)\n  then obtain y where \"y \\<in> f ` {N..}\" \"y \\<in> s\" \"y \\<noteq> l'\"\n    using \\<open>l' \\<in> s\\<close> \\<open>open s\\<close> by (rule islimptE)\n  then obtain n where \"N \\<le> n\" \"f n \\<in> s\" \"f n \\<noteq> l'\"\n    by auto\n  with \\<open>\\<forall>n\\<ge>N. f n \\<in> t\\<close> have \"f n \\<in> s \\<inter> t\"\n    by simp\n  with \\<open>s \\<inter> t = {}\\<close> show False\n    by simp\nqed\n\n(*could prove directly from islimpt_sequential_inj, but only for metric spaces*)\nlemma islimpt_sequential:\n  fixes x :: \"'a::first_countable_topology\"\n  shows \"x islimpt S \\<longleftrightarrow> (\\<exists>f. (\\<forall>n::nat. f n \\<in> S - {x}) \\<and> (f \\<longlongrightarrow> x) sequentially)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  from countable_basis_at_decseq[of x] obtain A where A:\n      \"\\<And>i. open (A i)\"\n      \"\\<And>i. x \\<in> A i\"\n      \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\n    by blast\n  define f where \"f n = (SOME y. y \\<in> S \\<and> y \\<in> A n \\<and> x \\<noteq> y)\" for n\n  {\n    fix n\n    from \\<open>?lhs\\<close> have \"\\<exists>y. y \\<in> S \\<and> y \\<in> A n \\<and> x \\<noteq> y\"\n      unfolding islimpt_def using A(1,2)[of n] by auto\n    then have \"f n \\<in> S \\<and> f n \\<in> A n \\<and> x \\<noteq> f n\"\n      unfolding f_def by (rule someI_ex)\n    then have \"f n \\<in> S\" \"f n \\<in> A n\" \"x \\<noteq> f n\" by auto\n  }\n  then have \"\\<forall>n. f n \\<in> S - {x}\" by auto\n  moreover have \"(\\<lambda>n. f n) \\<longlonglongrightarrow> x\"\n  proof (rule topological_tendstoI)\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    from A(3)[OF this] \\<open>\\<And>n. f n \\<in> A n\\<close>\n    show \"eventually (\\<lambda>x. f x \\<in> S) sequentially\"\n      by (auto elim!: eventually_mono)\n  qed\n  ultimately show ?rhs by fast\nnext\n  assume ?rhs\n  then obtain f :: \"nat \\<Rightarrow> 'a\" where f: \"\\<And>n. f n \\<in> S - {x}\" and lim: \"f \\<longlonglongrightarrow> x\"\n    by auto\n  show ?lhs\n    unfolding islimpt_def\n  proof safe\n    fix T\n    assume \"open T\" \"x \\<in> T\"\n    from lim[THEN topological_tendstoD, OF this] f\n    show \"\\<exists>y\\<in>S. y \\<in> T \\<and> y \\<noteq> x\"\n      unfolding eventually_sequentially by auto\n  qed\nqed\n\nlemma islimpt_isCont_image:\n  fixes f :: \"'a :: {first_countable_topology, t2_space} \\<Rightarrow> 'b :: {first_countable_topology, t2_space}\"\n  assumes \"x islimpt A\" and \"isCont f x\" and ev: \"eventually (\\<lambda>y. f y \\<noteq> f x) (at x)\"\n  shows   \"f x islimpt f ` A\"\nproof -\n  from assms(1) obtain g where g: \"g \\<longlonglongrightarrow> x\" \"range g \\<subseteq> A - {x}\"\n    unfolding islimpt_sequential by blast\n  have \"filterlim g (at x) sequentially\"\n    using g by (auto simp: filterlim_at intro!: always_eventually)\n  then obtain N where N: \"\\<And>n. n \\<ge> N \\<Longrightarrow> f (g n) \\<noteq> f x\"\n    by (metis (mono_tags, lifting) ev eventually_at_top_linorder filterlim_iff)\n  have \"(\\<lambda>x. g (x + N)) \\<longlonglongrightarrow> x\"\n    using g(1) by (rule LIMSEQ_ignore_initial_segment)\n  hence \"(\\<lambda>x. f (g (x + N))) \\<longlonglongrightarrow> f x\"\n    using assms(2) isCont_tendsto_compose by blast\n  moreover have \"range (\\<lambda>x. f (g (x + N))) \\<subseteq> f ` A - {f x}\"\n    using g(2) N by auto\n  ultimately show ?thesis\n    unfolding islimpt_sequential by (intro exI[of _ \"\\<lambda>x. f (g (x + N))\"]) auto\nqed\n\nlemma islimpt_image:\n  assumes \"z islimpt g -` A \\<inter> B\" \"g z \\<notin> A\" \"z \\<in> B\" \"open B\" \"continuous_on B g\"\n  shows   \"g z islimpt A\"\n  unfolding islimpt_def\nproof clarify\n  fix T assume T: \"g z \\<in> T\" \"open T\"\n  have \"z \\<in> g -` T \\<inter> B\"\n    using T assms by auto\n  moreover have \"open (g -` T \\<inter> B)\"\n    using T continuous_on_open_vimage assms by blast\n  ultimately show \"\\<exists>y\\<in>A. y \\<in> T \\<and> y \\<noteq> g z\"\n    using assms by (metis (mono_tags, lifting) IntD1 islimptE vimageE)\nqed\n  \n\nsubsection \\<open>Interior of a Set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> interior :: \"('a::topological_space) set \\<Rightarrow> 'a set\" where\n\"interior S = \\<Union>{T. open T \\<and> T \\<subseteq> S}\"\n\nlemma interiorI [intro?]:\n  assumes \"open T\" and \"x \\<in> T\" and \"T \\<subseteq> S\"\n  shows \"x \\<in> interior S\"\n  using assms unfolding interior_def by fast\n\nlemma interiorE [elim?]:\n  assumes \"x \\<in> interior S\"\n  obtains T where \"open T\" and \"x \\<in> T\" and \"T \\<subseteq> S\"\n  using assms unfolding interior_def by fast\n\nlemma open_interior [simp, intro]: \"open (interior S)\"\n  by (simp add: interior_def open_Union)\n\nlemma interior_subset: \"interior S \\<subseteq> S\"\n  by (auto simp: interior_def)\n\nlemma interior_maximal: \"T \\<subseteq> S \\<Longrightarrow> open T \\<Longrightarrow> T \\<subseteq> interior S\"\n  by (auto simp: interior_def)\n\nlemma interior_open: \"open S \\<Longrightarrow> interior S = S\"\n  by (intro equalityI interior_subset interior_maximal subset_refl)\n\nlemma interior_eq: \"interior S = S \\<longleftrightarrow> open S\"\n  by (metis open_interior interior_open)\n\nlemma open_subset_interior: \"open S \\<Longrightarrow> S \\<subseteq> interior T \\<longleftrightarrow> S \\<subseteq> T\"\n  by (metis interior_maximal interior_subset subset_trans)\n\nlemma interior_empty [simp]: \"interior {} = {}\"\n  using open_empty by (rule interior_open)\n\nlemma interior_UNIV [simp]: \"interior UNIV = UNIV\"\n  using open_UNIV by (rule interior_open)\n\nlemma interior_interior [simp]: \"interior (interior S) = interior S\"\n  using open_interior by (rule interior_open)\n\nlemma interior_mono: \"S \\<subseteq> T \\<Longrightarrow> interior S \\<subseteq> interior T\"\n  by (auto simp: interior_def)\n\nlemma interior_unique:\n  assumes \"T \\<subseteq> S\" and \"open T\"\n  assumes \"\\<And>T'. T' \\<subseteq> S \\<Longrightarrow> open T' \\<Longrightarrow> T' \\<subseteq> T\"\n  shows \"interior S = T\"\n  by (intro equalityI assms interior_subset open_interior interior_maximal)\n\nlemma interior_singleton [simp]: \"interior {a} = {}\"\n  for a :: \"'a::perfect_space\"\n  by (meson interior_eq interior_subset not_open_singleton subset_singletonD)\n\nlemma interior_Int [simp]: \"interior (S \\<inter> T) = interior S \\<inter> interior T\"\n  by (meson Int_mono Int_subset_iff antisym_conv interior_maximal interior_subset open_Int open_interior)\n\nlemma eventually_nhds_in_nhd: \"x \\<in> interior s \\<Longrightarrow> eventually (\\<lambda>y. y \\<in> s) (nhds x)\"\n  using interior_subset[of s] by (subst eventually_nhds) blast\n\nlemma interior_limit_point [intro]:\n  fixes x :: \"'a::perfect_space\"\n  assumes x: \"x \\<in> interior S\"\n  shows \"x islimpt S\"\n  using x islimpt_UNIV [of x]\n  unfolding interior_def islimpt_def\n  apply (clarsimp, rename_tac T T')\n  apply (drule_tac x=\"T \\<inter> T'\" in spec)\n  apply (auto simp: open_Int)\n  done\n\nlemma open_imp_islimpt:\n  fixes x::\"'a:: perfect_space\"\n  assumes \"open S\" \"x\\<in>S\"\n  shows \"x islimpt S\"\n  using assms interior_eq interior_limit_point by auto\n\nlemma islimpt_Int_eventually:\n  assumes \"x islimpt A\" \"eventually (\\<lambda>y. y \\<in> B) (at x)\"\n  shows   \"x islimpt A \\<inter> B\"\n  using assms unfolding islimpt_def eventually_at_filter eventually_nhds\n  by (metis Int_iff UNIV_I open_Int)\n\nlemma islimpt_conv_frequently_at:\n  \"x islimpt A \\<longleftrightarrow> frequently (\\<lambda>y. y \\<in> A) (at x)\"\n  by (simp add: frequently_def islimpt_iff_eventually)\n\nlemma frequently_at_imp_islimpt:\n  assumes \"frequently (\\<lambda>y. y \\<in> A) (at x)\"\n  shows   \"x islimpt A\"\n  by (simp add: assms islimpt_conv_frequently_at)  \n\nlemma interior_closed_Un_empty_interior:\n  assumes cS: \"closed S\"\n    and iT: \"interior T = {}\"\n  shows \"interior (S \\<union> T) = interior S\"\nproof\n  show \"interior S \\<subseteq> interior (S \\<union> T)\"\n    by (rule interior_mono) (rule Un_upper1)\n  show \"interior (S \\<union> T) \\<subseteq> interior S\"\n  proof\n    fix x\n    assume \"x \\<in> interior (S \\<union> T)\"\n    then obtain R where \"open R\" \"x \\<in> R\" \"R \\<subseteq> S \\<union> T\" ..\n    show \"x \\<in> interior S\"\n    proof (rule ccontr)\n      assume \"x \\<notin> interior S\"\n      with \\<open>x \\<in> R\\<close> \\<open>open R\\<close> obtain y where \"y \\<in> R - S\"\n        unfolding interior_def by fast\n      from \\<open>open R\\<close> \\<open>closed S\\<close> have \"open (R - S)\"\n        by (rule open_Diff)\n      from \\<open>R \\<subseteq> S \\<union> T\\<close> have \"R - S \\<subseteq> T\"\n        by fast\n      from \\<open>y \\<in> R - S\\<close> \\<open>open (R - S)\\<close> \\<open>R - S \\<subseteq> T\\<close> \\<open>interior T = {}\\<close> show False\n        unfolding interior_def by fast\n    qed\n  qed\nqed\n\nlemma interior_Times: \"interior (A \\<times> B) = interior A \\<times> interior B\"\nproof (rule interior_unique)\n  show \"interior A \\<times> interior B \\<subseteq> A \\<times> B\"\n    by (intro Sigma_mono interior_subset)\n  show \"open (interior A \\<times> interior B)\"\n    by (intro open_Times open_interior)\n  fix T\n  assume \"T \\<subseteq> A \\<times> B\" and \"open T\"\n  then show \"T \\<subseteq> interior A \\<times> interior B\"\n  proof safe\n    fix x y\n    assume \"(x, y) \\<in> T\"\n    then obtain C D where \"open C\" \"open D\" \"C \\<times> D \\<subseteq> T\" \"x \\<in> C\" \"y \\<in> D\"\n      using \\<open>open T\\<close> unfolding open_prod_def by fast\n    then have \"open C\" \"open D\" \"C \\<subseteq> A\" \"D \\<subseteq> B\" \"x \\<in> C\" \"y \\<in> D\"\n      using \\<open>T \\<subseteq> A \\<times> B\\<close> by auto\n    then show \"x \\<in> interior A\" and \"y \\<in> interior B\"\n      by (auto intro: interiorI)\n  qed\nqed\n\nlemma interior_Ici:\n  fixes x :: \"'a :: {dense_linorder,linorder_topology}\"\n  assumes \"b < x\"\n  shows \"interior {x ..} = {x <..}\"\nproof (rule interior_unique)\n  fix T\n  assume \"T \\<subseteq> {x ..}\" \"open T\"\n  moreover have \"x \\<notin> T\"\n  proof\n    assume \"x \\<in> T\"\n    obtain y where \"y < x\" \"{y <.. x} \\<subseteq> T\"\n      using open_left[OF \\<open>open T\\<close> \\<open>x \\<in> T\\<close> \\<open>b < x\\<close>] by auto\n    with dense[OF \\<open>y < x\\<close>] obtain z where \"z \\<in> T\" \"z < x\"\n      by (auto simp: subset_eq Ball_def)\n    with \\<open>T \\<subseteq> {x ..}\\<close> show False by auto\n  qed\n  ultimately show \"T \\<subseteq> {x <..}\"\n    by (auto simp: subset_eq less_le)\nqed auto\n\nlemma interior_Iic:\n  fixes x :: \"'a ::{dense_linorder,linorder_topology}\"\n  assumes \"x < b\"\n  shows \"interior {.. x} = {..< x}\"\nproof (rule interior_unique)\n  fix T\n  assume \"T \\<subseteq> {.. x}\" \"open T\"\n  moreover have \"x \\<notin> T\"\n  proof\n    assume \"x \\<in> T\"\n    obtain y where \"x < y\" \"{x ..< y} \\<subseteq> T\"\n      using open_right[OF \\<open>open T\\<close> \\<open>x \\<in> T\\<close> \\<open>x < b\\<close>] by auto\n    with dense[OF \\<open>x < y\\<close>] obtain z where \"z \\<in> T\" \"x < z\"\n      by (auto simp: subset_eq Ball_def less_le)\n    with \\<open>T \\<subseteq> {.. x}\\<close> show False by auto\n  qed\n  ultimately show \"T \\<subseteq> {..< x}\"\n    by (auto simp: subset_eq less_le)\nqed auto\n\nlemma countable_disjoint_nonempty_interior_subsets:\n  fixes \\<F> :: \"'a::second_countable_topology set set\"\n  assumes pw: \"pairwise disjnt \\<F>\" and int: \"\\<And>S. \\<lbrakk>S \\<in> \\<F>; interior S = {}\\<rbrakk> \\<Longrightarrow> S = {}\"\n  shows \"countable \\<F>\"\nproof (rule countable_image_inj_on)\n  have \"disjoint (interior ` \\<F>)\"\n    using pw by (simp add: disjoint_image_subset interior_subset)\n  then show \"countable (interior ` \\<F>)\"\n    by (auto intro: countable_disjoint_open_subsets)\n  show \"inj_on interior \\<F>\"\n    using pw apply (clarsimp simp: inj_on_def pairwise_def)\n    apply (metis disjnt_def disjnt_subset1 inf.orderE int interior_subset)\n    done\nqed\n\nsubsection \\<open>Closure of a Set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> closure :: \"('a::topological_space) set \\<Rightarrow> 'a set\" where\n\"closure S = S \\<union> {x . x islimpt S}\"\n\nlemma interior_closure: \"interior S = - (closure (- S))\"\n  by (auto simp: interior_def closure_def islimpt_def)\n\nlemma closure_interior: \"closure S = - interior (- S)\"\n  by (simp add: interior_closure)\n\nlemma closed_closure[simp, intro]: \"closed (closure S)\"\n  by (simp add: closure_interior closed_Compl)\n\nlemma closure_subset: \"S \\<subseteq> closure S\"\n  by (simp add: closure_def)\n\nlemma closure_hull: \"closure S = closed hull S\"\n  by (auto simp: hull_def closure_interior interior_def)\n\nlemma closure_eq: \"closure S = S \\<longleftrightarrow> closed S\"\n  unfolding closure_hull using closed_Inter by (rule hull_eq)\n\nlemma closure_closed [simp]: \"closed S \\<Longrightarrow> closure S = S\"\n  by (simp only: closure_eq)\n\nlemma closure_closure [simp]: \"closure (closure S) = closure S\"\n  unfolding closure_hull by (rule hull_hull)\n\nlemma closure_mono: \"S \\<subseteq> T \\<Longrightarrow> closure S \\<subseteq> closure T\"\n  unfolding closure_hull by (rule hull_mono)\n\nlemma closure_minimal: \"S \\<subseteq> T \\<Longrightarrow> closed T \\<Longrightarrow> closure S \\<subseteq> T\"\n  unfolding closure_hull by (rule hull_minimal)\n\nlemma closure_unique:\n  assumes \"S \\<subseteq> T\"\n    and \"closed T\"\n    and \"\\<And>T'. S \\<subseteq> T' \\<Longrightarrow> closed T' \\<Longrightarrow> T \\<subseteq> T'\"\n  shows \"closure S = T\"\n  using assms unfolding closure_hull by (rule hull_unique)\n\nlemma closure_empty [simp]: \"closure {} = {}\"\n  using closed_empty by (rule closure_closed)\n\nlemma closure_UNIV [simp]: \"closure UNIV = UNIV\"\n  using closed_UNIV by (rule closure_closed)\n\nlemma closure_Un [simp]: \"closure (S \\<union> T) = closure S \\<union> closure T\"\n  by (simp add: closure_interior)\n\nlemma closure_eq_empty [iff]: \"closure S = {} \\<longleftrightarrow> S = {}\"\n  using closure_empty closure_subset[of S] by blast\n\nlemma closure_subset_eq: \"closure S \\<subseteq> S \\<longleftrightarrow> closed S\"\n  using closure_eq[of S] closure_subset[of S] by simp\n\nlemma open_Int_closure_eq_empty: \"open S \\<Longrightarrow> (S \\<inter> closure T) = {} \\<longleftrightarrow> S \\<inter> T = {}\"\n  using open_subset_interior[of S \"- T\"]\n  using interior_subset[of \"- T\"]\n  by (auto simp: closure_interior)\n\nlemma open_Int_closure_subset: \"open S \\<Longrightarrow> S \\<inter> closure T \\<subseteq> closure (S \\<inter> T)\"\nproof\n  fix x\n  assume *: \"open S\" \"x \\<in> S \\<inter> closure T\"\n  have \"x islimpt (S \\<inter> T)\" if **: \"x islimpt T\"\n  proof (rule islimptI)\n    fix A\n    assume \"x \\<in> A\" \"open A\"\n    with * have \"x \\<in> A \\<inter> S\" \"open (A \\<inter> S)\"\n      by (simp_all add: open_Int)\n    with ** obtain y where \"y \\<in> T\" \"y \\<in> A \\<inter> S\" \"y \\<noteq> x\"\n      by (rule islimptE)\n    then have \"y \\<in> S \\<inter> T\" \"y \\<in> A \\<and> y \\<noteq> x\"\n      by simp_all\n    then show \"\\<exists>y\\<in>(S \\<inter> T). y \\<in> A \\<and> y \\<noteq> x\" ..\n  qed\n  with * show \"x \\<in> closure (S \\<inter> T)\"\n    unfolding closure_def by blast\nqed\n\nlemma closure_complement: \"closure (- S) = - interior S\"\n  by (simp add: closure_interior)\n\nlemma interior_complement: \"interior (- S) = - closure S\"\n  by (simp add: closure_interior)\n\nlemma interior_diff: \"interior(S - T) = interior S - closure T\"\n  by (simp add: Diff_eq interior_complement)\n\nlemma closure_Times: \"closure (A \\<times> B) = closure A \\<times> closure B\"\nproof (rule closure_unique)\n  show \"A \\<times> B \\<subseteq> closure A \\<times> closure B\"\n    by (intro Sigma_mono closure_subset)\n  show \"closed (closure A \\<times> closure B)\"\n    by (intro closed_Times closed_closure)\n  fix T\n  assume \"A \\<times> B \\<subseteq> T\" and \"closed T\"\n  then show \"closure A \\<times> closure B \\<subseteq> T\"\n    apply (simp add: closed_def open_prod_def, clarify)\n    apply (rule ccontr)\n    apply (drule_tac x=\"(a, b)\" in bspec, simp, clarify, rename_tac C D)\n    apply (simp add: closure_interior interior_def)\n    apply (drule_tac x=C in spec)\n    apply (drule_tac x=D in spec, auto)\n    done\nqed\n\nlemma closure_open_Int_superset:\n  assumes \"open S\" \"S \\<subseteq> closure T\"\n  shows \"closure(S \\<inter> T) = closure S\"\nproof -\n  have \"closure S \\<subseteq> closure(S \\<inter> T)\"\n    by (metis assms closed_closure closure_minimal inf.orderE open_Int_closure_subset)\n  then show ?thesis\n    by (simp add: closure_mono dual_order.antisym)\nqed\n\nlemma closure_Int: \"closure (\\<Inter>I) \\<le> \\<Inter>{closure S |S. S \\<in> I}\"\nproof -\n  {\n    fix y\n    assume \"y \\<in> \\<Inter>I\"\n    then have y: \"\\<forall>S \\<in> I. y \\<in> S\" by auto\n    {\n      fix S\n      assume \"S \\<in> I\"\n      then have \"y \\<in> closure S\"\n        using closure_subset y by auto\n    }\n    then have \"y \\<in> \\<Inter>{closure S |S. S \\<in> I}\"\n      by auto\n  }\n  then have \"\\<Inter>I \\<subseteq> \\<Inter>{closure S |S. S \\<in> I}\"\n    by auto\n  moreover have \"closed (\\<Inter>{closure S |S. S \\<in> I})\"\n    unfolding closed_Inter closed_closure by auto\n  ultimately show ?thesis using closure_hull[of \"\\<Inter>I\"]\n    hull_minimal[of \"\\<Inter>I\" \"\\<Inter>{closure S |S. S \\<in> I}\" \"closed\"] by auto\nqed\n\nlemma islimpt_in_closure: \"(x islimpt S) = (x\\<in>closure(S-{x}))\"\n  unfolding closure_def using islimpt_punctured by blast\n\nlemma connected_imp_connected_closure: \"connected S \\<Longrightarrow> connected (closure S)\"\n  by (rule connectedI) (meson closure_subset open_Int open_Int_closure_eq_empty subset_trans connectedD)\n\nlemma bdd_below_closure:\n  fixes A :: \"real set\"\n  assumes \"bdd_below A\"\n  shows \"bdd_below (closure A)\"\nproof -\n  from assms obtain m where \"\\<And>x. x \\<in> A \\<Longrightarrow> m \\<le> x\"\n    by (auto simp: bdd_below_def)\n  then have \"A \\<subseteq> {m..}\" by auto\n  then have \"closure A \\<subseteq> {m..}\"\n    using closed_real_atLeast by (rule closure_minimal)\n  then show ?thesis\n    by (auto simp: bdd_below_def)\nqed\n\n\nsubsection \\<open>Frontier (also known as boundary)\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> frontier :: \"('a::topological_space) set \\<Rightarrow> 'a set\" where\n\"frontier S = closure S - interior S\"\n\nlemma frontier_closed [iff]: \"closed (frontier S)\"\n  by (simp add: frontier_def closed_Diff)\n\nlemma frontier_closures: \"frontier S = closure S \\<inter> closure (- S)\"\n  by (auto simp: frontier_def interior_closure)\n\nlemma frontier_Int: \"frontier(S \\<inter> T) = closure(S \\<inter> T) \\<inter> (frontier S \\<union> frontier T)\"\nproof -\n  have \"closure (S \\<inter> T) \\<subseteq> closure S\" \"closure (S \\<inter> T) \\<subseteq> closure T\"\n    by (simp_all add: closure_mono)\n  then show ?thesis\n    by (auto simp: frontier_closures)\nqed\n\nlemma frontier_Int_subset: \"frontier(S \\<inter> T) \\<subseteq> frontier S \\<union> frontier T\"\n  by (auto simp: frontier_Int)\n\nlemma frontier_Int_closed:\n  assumes \"closed S\" \"closed T\"\n  shows \"frontier(S \\<inter> T) = (frontier S \\<inter> T) \\<union> (S \\<inter> frontier T)\"\nproof -\n  have \"closure (S \\<inter> T) = T \\<inter> S\"\n    using assms by (simp add: Int_commute closed_Int)\n  moreover have \"T \\<inter> (closure S \\<inter> closure (- S)) = frontier S \\<inter> T\"\n    by (simp add: Int_commute frontier_closures)\n  ultimately show ?thesis\n    by (simp add: Int_Un_distrib Int_assoc Int_left_commute assms frontier_closures)\nqed\n\nlemma frontier_subset_closed: \"closed S \\<Longrightarrow> frontier S \\<subseteq> S\"\n  by (metis frontier_def closure_closed Diff_subset)\n\nlemma frontier_empty [simp]: \"frontier {} = {}\"\n  by (simp add: frontier_def)\n\nlemma frontier_subset_eq: \"frontier S \\<subseteq> S \\<longleftrightarrow> closed S\"\nproof -\n  {\n    assume \"frontier S \\<subseteq> S\"\n    then have \"closure S \\<subseteq> S\"\n      using interior_subset unfolding frontier_def by auto\n    then have \"closed S\"\n      using closure_subset_eq by auto\n  }\n  then show ?thesis using frontier_subset_closed[of S] ..\nqed\n\nlemma frontier_complement [simp]: \"frontier (- S) = frontier S\"\n  by (auto simp: frontier_def closure_complement interior_complement)\n\nlemma frontier_Un_subset: \"frontier(S \\<union> T) \\<subseteq> frontier S \\<union> frontier T\"\n  by (metis compl_sup frontier_Int_subset frontier_complement)\n\nlemma frontier_disjoint_eq: \"frontier S \\<inter> S = {} \\<longleftrightarrow> open S\"\n  using frontier_complement frontier_subset_eq[of \"- S\"]\n  unfolding open_closed by auto\n\nlemma frontier_UNIV [simp]: \"frontier UNIV = {}\"\n  using frontier_complement frontier_empty by fastforce\n\nlemma frontier_interiors: \"frontier s = - interior(s) - interior(-s)\"\n  by (simp add: Int_commute frontier_def interior_closure)\n\nlemma frontier_interior_subset: \"frontier(interior S) \\<subseteq> frontier S\"\n  by (simp add: Diff_mono frontier_interiors interior_mono interior_subset)\n\nlemma closure_Un_frontier: \"closure S = S \\<union> frontier S\"\nproof -\n  have \"S \\<union> interior S = S\"\n    using interior_subset by auto\n  then show ?thesis\n    using closure_subset by (auto simp: frontier_def)\nqed\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Filters and the ``eventually true'' quantifier\\<close>\n\ntext \\<open>Identify Trivial limits, where we can't approach arbitrarily closely.\\<close>\n\nlemma trivial_limit_within: \"trivial_limit (at a within S) \\<longleftrightarrow> \\<not> a islimpt S\"\nproof\n  assume \"trivial_limit (at a within S)\"\n  then show \"\\<not> a islimpt S\"\n    unfolding trivial_limit_def\n    unfolding eventually_at_topological\n    unfolding islimpt_def\n    apply (clarsimp simp add: set_eq_iff)\n    apply (rename_tac T, rule_tac x=T in exI)\n    apply (clarsimp, drule_tac x=y in bspec, simp_all)\n    done\nnext\n  assume \"\\<not> a islimpt S\"\n  then show \"trivial_limit (at a within S)\"\n    unfolding trivial_limit_def eventually_at_topological islimpt_def\n    by metis\nqed\n\nlemma trivial_limit_at_iff: \"trivial_limit (at a) \\<longleftrightarrow> \\<not> a islimpt UNIV\"\n  using trivial_limit_within [of a UNIV] by simp\n\nlemma trivial_limit_at: \"\\<not> trivial_limit (at a)\"\n  for a :: \"'a::perfect_space\"\n  by (rule at_neq_bot)\n\nlemma not_trivial_limit_within: \"\\<not> trivial_limit (at x within S) = (x \\<in> closure (S - {x}))\"\n  using islimpt_in_closure by (metis trivial_limit_within)\n\nlemma not_in_closure_trivial_limitI:\n  \"x \\<notin> closure s \\<Longrightarrow> trivial_limit (at x within s)\"\n  using not_trivial_limit_within[of x s]\n  by safe (metis Diff_empty Diff_insert0 closure_subset contra_subsetD)\n\nlemma filterlim_at_within_closure_implies_filterlim: \"filterlim f l (at x within s)\"\n  if \"x \\<in> closure s \\<Longrightarrow> filterlim f l (at x within s)\"\n  by (metis bot.extremum filterlim_filtercomap filterlim_mono not_in_closure_trivial_limitI that)\n\nlemma at_within_eq_bot_iff: \"at c within A = bot \\<longleftrightarrow> c \\<notin> closure (A - {c})\"\n  using not_trivial_limit_within[of c A] by blast\n\ntext \\<open>Some property holds \"sufficiently close\" to the limit point.\\<close>\n\nlemma trivial_limit_eventually: \"trivial_limit net \\<Longrightarrow> eventually P net\"\n  by simp\n\nlemma trivial_limit_eq: \"trivial_limit net \\<longleftrightarrow> (\\<forall>P. eventually P net)\"\n  by (simp add: filter_eq_iff)\n\nlemma Lim_topological:\n  \"(f \\<longlongrightarrow> l) net \\<longleftrightarrow>\n    trivial_limit net \\<or> (\\<forall>S. open S \\<longrightarrow> l \\<in> S \\<longrightarrow> eventually (\\<lambda>x. f x \\<in> S) net)\"\n  unfolding tendsto_def trivial_limit_eq by auto\n\nlemma eventually_within_Un:\n  \"eventually P (at x within (s \\<union> t)) \\<longleftrightarrow>\n    eventually P (at x within s) \\<and> eventually P (at x within t)\"\n  unfolding eventually_at_filter\n  by (auto elim!: eventually_rev_mp)\n\nlemma Lim_within_union:\n \"(f \\<longlongrightarrow> l) (at x within (s \\<union> t)) \\<longleftrightarrow>\n  (f \\<longlongrightarrow> l) (at x within s) \\<and> (f \\<longlongrightarrow> l) (at x within t)\"\n  unfolding tendsto_def\n  by (auto simp: eventually_within_Un)\n\n\nsubsection \\<open>Limits\\<close>\n\ntext \\<open>The expected monotonicity property.\\<close>\n\nlemma Lim_Un:\n  assumes \"(f \\<longlongrightarrow> l) (at x within S)\" \"(f \\<longlongrightarrow> l) (at x within T)\"\n  shows \"(f \\<longlongrightarrow> l) (at x within (S \\<union> T))\"\n  using assms unfolding at_within_union by (rule filterlim_sup)\n\nlemma Lim_Un_univ:\n  \"(f \\<longlongrightarrow> l) (at x within S) \\<Longrightarrow> (f \\<longlongrightarrow> l) (at x within T) \\<Longrightarrow>\n    S \\<union> T = UNIV \\<Longrightarrow> (f \\<longlongrightarrow> l) (at x)\"\n  by (metis Lim_Un)\n\ntext \\<open>Interrelations between restricted and unrestricted limits.\\<close>\n\nlemma Lim_at_imp_Lim_at_within: \"(f \\<longlongrightarrow> l) (at x) \\<Longrightarrow> (f \\<longlongrightarrow> l) (at x within S)\"\n  by (metis order_refl filterlim_mono subset_UNIV at_le)\n\nlemma eventually_within_interior:\n  assumes \"x \\<in> interior S\"\n  shows \"eventually P (at x within S) \\<longleftrightarrow> eventually P (at x)\"\n  (is \"?lhs = ?rhs\")\nproof\n  from assms obtain T where T: \"open T\" \"x \\<in> T\" \"T \\<subseteq> S\" ..\n  {\n    assume ?lhs\n    then obtain A where \"open A\" and \"x \\<in> A\" and \"\\<forall>y\\<in>A. y \\<noteq> x \\<longrightarrow> y \\<in> S \\<longrightarrow> P y\"\n      by (auto simp: eventually_at_topological)\n    with T have \"open (A \\<inter> T)\" and \"x \\<in> A \\<inter> T\" and \"\\<forall>y \\<in> A \\<inter> T. y \\<noteq> x \\<longrightarrow> P y\"\n      by auto\n    then show ?rhs\n      by (auto simp: eventually_at_topological)\n  next\n    assume ?rhs\n    then show ?lhs\n      by (auto elim: eventually_mono simp: eventually_at_filter)\n  }\nqed\n\nlemma at_within_interior: \"x \\<in> interior S \\<Longrightarrow> at x within S = at x\"\n  unfolding filter_eq_iff by (intro allI eventually_within_interior)\n\nlemma Lim_within_LIMSEQ:\n  fixes a :: \"'a::first_countable_topology\"\n  assumes \"\\<forall>S. (\\<forall>n. S n \\<noteq> a \\<and> S n \\<in> T) \\<and> S \\<longlonglongrightarrow> a \\<longrightarrow> (\\<lambda>n. X (S n)) \\<longlonglongrightarrow> L\"\n  shows \"(X \\<longlongrightarrow> L) (at a within T)\"\n  using assms unfolding tendsto_def [where l=L]\n  by (simp add: sequentially_imp_eventually_within)\n\nlemma Lim_right_bound:\n  fixes f :: \"'a :: {linorder_topology, conditionally_complete_linorder, no_top} \\<Rightarrow>\n    'b::{linorder_topology, conditionally_complete_linorder}\"\n  assumes mono: \"\\<And>a b. a \\<in> I \\<Longrightarrow> b \\<in> I \\<Longrightarrow> x < a \\<Longrightarrow> a \\<le> b \\<Longrightarrow> f a \\<le> f b\"\n    and bnd: \"\\<And>a. a \\<in> I \\<Longrightarrow> x < a \\<Longrightarrow> K \\<le> f a\"\n  shows \"(f \\<longlongrightarrow> Inf (f ` ({x<..} \\<inter> I))) (at x within ({x<..} \\<inter> I))\"\nproof (cases \"{x<..} \\<inter> I = {}\")\n  case True\n  then show ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof (rule order_tendstoI)\n    fix a\n    assume a: \"a < Inf (f ` ({x<..} \\<inter> I))\"\n    {\n      fix y\n      assume \"y \\<in> {x<..} \\<inter> I\"\n      with False bnd have \"Inf (f ` ({x<..} \\<inter> I)) \\<le> f y\"\n        by (auto intro!: cInf_lower bdd_belowI2)\n      with a have \"a < f y\"\n        by (blast intro: less_le_trans)\n    }\n    then show \"eventually (\\<lambda>x. a < f x) (at x within ({x<..} \\<inter> I))\"\n      by (auto simp: eventually_at_filter intro: exI[of _ 1] zero_less_one)\n  next\n    fix a\n    assume \"Inf (f ` ({x<..} \\<inter> I)) < a\"\n    from cInf_lessD[OF _ this] False obtain y where y: \"x < y\" \"y \\<in> I\" \"f y < a\"\n      by auto\n    then have \"eventually (\\<lambda>x. x \\<in> I \\<longrightarrow> f x < a) (at_right x)\"\n      unfolding eventually_at_right[OF \\<open>x < y\\<close>] by (metis less_imp_le le_less_trans mono)\n    then show \"eventually (\\<lambda>x. f x < a) (at x within ({x<..} \\<inter> I))\"\n      unfolding eventually_at_filter by eventually_elim simp\n  qed\nqed\n\ntext\\<open>These are special for limits out of the same topological space.\\<close>\n\nlemma Lim_within_id: \"(id \\<longlongrightarrow> a) (at a within s)\"\n  unfolding id_def by (rule tendsto_ident_at)\n\nlemma Lim_at_id: \"(id \\<longlongrightarrow> a) (at a)\"\n  unfolding id_def by (rule tendsto_ident_at)\n\ntext\\<open>It's also sometimes useful to extract the limit point from the filter.\\<close>\n\nabbreviation netlimit :: \"'a::t2_space filter \\<Rightarrow> 'a\"\n  where \"netlimit F \\<equiv> Lim F (\\<lambda>x. x)\"\n\nlemma netlimit_at [simp]:\n  fixes a :: \"'a::{perfect_space,t2_space}\"\n  shows \"netlimit (at a) = a\"\n  using Lim_ident_at [of a UNIV] by simp\n\nlemma lim_within_interior:\n  \"x \\<in> interior S \\<Longrightarrow> (f \\<longlongrightarrow> l) (at x within S) \\<longleftrightarrow> (f \\<longlongrightarrow> l) (at x)\"\n  by (metis at_within_interior)\n\nlemma netlimit_within_interior:\n  fixes x :: \"'a::{t2_space,perfect_space}\"\n  assumes \"x \\<in> interior S\"\n  shows \"netlimit (at x within S) = x\"\n  using assms by (metis at_within_interior netlimit_at)\n\ntext\\<open>Useful lemmas on closure and set of possible sequential limits.\\<close>\n\nlemma closure_sequential:\n  fixes l :: \"'a::first_countable_topology\"\n  shows \"l \\<in> closure S \\<longleftrightarrow> (\\<exists>x. (\\<forall>n. x n \\<in> S) \\<and> (x \\<longlongrightarrow> l) sequentially)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume \"?lhs\"\n  moreover\n  {\n    assume \"l \\<in> S\"\n    then have \"?rhs\" using tendsto_const[of l sequentially] by auto\n  }\n  moreover\n  {\n    assume \"l islimpt S\"\n    then have \"?rhs\" unfolding islimpt_sequential by auto\n  }\n  ultimately show \"?rhs\"\n    unfolding closure_def by auto\nnext\n  assume \"?rhs\"\n  then show \"?lhs\" unfolding closure_def islimpt_sequential by auto\nqed\n\nlemma closed_sequential_limits:\n  fixes S :: \"'a::first_countable_topology set\"\n  shows \"closed S \\<longleftrightarrow> (\\<forall>x l. (\\<forall>n. x n \\<in> S) \\<and> (x \\<longlongrightarrow> l) sequentially \\<longrightarrow> l \\<in> S)\"\nby (metis closure_sequential closure_subset_eq subset_iff)\n\nlemma tendsto_If_within_closures:\n  assumes f: \"x \\<in> s \\<union> (closure s \\<inter> closure t) \\<Longrightarrow>\n      (f \\<longlongrightarrow> l x) (at x within s \\<union> (closure s \\<inter> closure t))\"\n  assumes g: \"x \\<in> t \\<union> (closure s \\<inter> closure t) \\<Longrightarrow>\n      (g \\<longlongrightarrow> l x) (at x within t \\<union> (closure s \\<inter> closure t))\"\n  assumes \"x \\<in> s \\<union> t\"\n  shows \"((\\<lambda>x. if x \\<in> s then f x else g x) \\<longlongrightarrow> l x) (at x within s \\<union> t)\"\nproof -\n  have *: \"(s \\<union> t) \\<inter> {x. x \\<in> s} = s\" \"(s \\<union> t) \\<inter> {x. x \\<notin> s} = t - s\"\n    by auto\n  have \"(f \\<longlongrightarrow> l x) (at x within s)\"\n    by (rule filterlim_at_within_closure_implies_filterlim)\n       (use \\<open>x \\<in> _\\<close> in \\<open>auto simp: inf_commute closure_def intro: tendsto_within_subset[OF f]\\<close>)\n  moreover\n  have \"(g \\<longlongrightarrow> l x) (at x within t - s)\"\n    by (rule filterlim_at_within_closure_implies_filterlim)\n      (use \\<open>x \\<in> _\\<close> in\n        \\<open>auto intro!: tendsto_within_subset[OF g] simp: closure_def intro: islimpt_subset\\<close>)\n  ultimately show ?thesis\n    by (intro filterlim_at_within_If) (simp_all only: *)\nqed\n\n\nsubsection \\<open>Compactness\\<close>\n\nlemma brouwer_compactness_lemma:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::real_normed_vector\"\n  assumes \"compact s\"\n    and \"continuous_on s f\"\n    and \"\\<not> (\\<exists>x\\<in>s. f x = 0)\"\n  obtains d where \"0 < d\" and \"\\<forall>x\\<in>s. d \\<le> norm (f x)\"\nproof (cases \"s = {}\")\n  case True\n  show thesis\n    by (rule that [of 1]) (auto simp: True)\nnext\n  case False\n  have \"continuous_on s (norm \\<circ> f)\"\n    by (rule continuous_intros continuous_on_norm assms(2))+\n  with False obtain x where x: \"x \\<in> s\" \"\\<forall>y\\<in>s. (norm \\<circ> f) x \\<le> (norm \\<circ> f) y\"\n    using continuous_attains_inf[OF assms(1), of \"norm \\<circ> f\"]\n    unfolding o_def\n    by auto\n  have \"(norm \\<circ> f) x > 0\"\n    using assms(3) and x(1)\n    by auto\n  then show ?thesis\n    by (rule that) (insert x(2), auto simp: o_def)\nqed\n\nsubsubsection \\<open>Bolzano-Weierstrass property\\<close>\n\nproposition Heine_Borel_imp_Bolzano_Weierstrass:\n  assumes \"compact s\"\n    and \"infinite t\"\n    and \"t \\<subseteq> s\"\n  shows \"\\<exists>x \\<in> s. x islimpt t\"\nproof (rule ccontr)\n  assume \"\\<not> (\\<exists>x \\<in> s. x islimpt t)\"\n  then obtain f where f: \"\\<forall>x\\<in>s. x \\<in> f x \\<and> open (f x) \\<and> (\\<forall>y\\<in>t. y \\<in> f x \\<longrightarrow> y = x)\"\n    unfolding islimpt_def\n    using bchoice[of s \"\\<lambda> x T. x \\<in> T \\<and> open T \\<and> (\\<forall>y\\<in>t. y \\<in> T \\<longrightarrow> y = x)\"]\n    by auto\n  obtain g where g: \"g \\<subseteq> {t. \\<exists>x. x \\<in> s \\<and> t = f x}\" \"finite g\" \"s \\<subseteq> \\<Union>g\"\n    using assms(1)[unfolded compact_eq_Heine_Borel, THEN spec[where x=\"{t. \\<exists>x. x\\<in>s \\<and> t = f x}\"]]\n    using f by auto\n  from g(1,3) have g':\"\\<forall>x\\<in>g. \\<exists>xa \\<in> s. x = f xa\"\n    by auto\n  {\n    fix x y\n    assume \"x \\<in> t\" \"y \\<in> t\" \"f x = f y\"\n    then have \"x \\<in> f x\"  \"y \\<in> f x \\<longrightarrow> y = x\"\n      using f[THEN bspec[where x=x]] and \\<open>t \\<subseteq> s\\<close> by auto\n    then have \"x = y\"\n      using \\<open>f x = f y\\<close> and f[THEN bspec[where x=y]] and \\<open>y \\<in> t\\<close> and \\<open>t \\<subseteq> s\\<close>\n      by auto\n  }\n  then have \"inj_on f t\"\n    unfolding inj_on_def by simp\n  then have \"infinite (f ` t)\"\n    using assms(2) using finite_imageD by auto\n  moreover\n  {\n    fix x\n    assume \"x \\<in> t\" \"f x \\<notin> g\"\n    from g(3) assms(3) \\<open>x \\<in> t\\<close> obtain h where \"h \\<in> g\" and \"x \\<in> h\"\n      by auto\n    then obtain y where \"y \\<in> s\" \"h = f y\"\n      using g'[THEN bspec[where x=h]] by auto\n    then have \"y = x\"\n      using f[THEN bspec[where x=y]] and \\<open>x\\<in>t\\<close> and \\<open>x\\<in>h\\<close>[unfolded \\<open>h = f y\\<close>]\n      by auto\n    then have False\n      using \\<open>f x \\<notin> g\\<close> \\<open>h \\<in> g\\<close> unfolding \\<open>h = f y\\<close>\n      by auto\n  }\n  then have \"f ` t \\<subseteq> g\" by auto\n  ultimately show False\n    using g(2) using finite_subset by auto\nqed\n\nlemma sequence_infinite_lemma:\n  fixes f :: \"nat \\<Rightarrow> 'a::t1_space\"\n  assumes \"\\<forall>n. f n \\<noteq> l\"\n    and \"(f \\<longlongrightarrow> l) sequentially\"\n  shows \"infinite (range f)\"\nproof\n  assume \"finite (range f)\"\n  then have \"l \\<notin> range f \\<and> closed (range f)\"\n    using \\<open>finite (range f)\\<close> assms(1) finite_imp_closed by blast\n  then have \"eventually (\\<lambda>n. f n \\<in> - range f) sequentially\"\n    by (metis Compl_iff assms(2) open_Compl topological_tendstoD)\n  then show False\n    unfolding eventually_sequentially by auto\nqed\n\nlemma Bolzano_Weierstrass_imp_closed:\n  fixes s :: \"'a::{first_countable_topology,t2_space} set\"\n  assumes \"\\<forall>t. infinite t \\<and> t \\<subseteq> s --> (\\<exists>x \\<in> s. x islimpt t)\"\n  shows \"closed s\"\nproof -\n  {\n    fix x l\n    assume as: \"\\<forall>n::nat. x n \\<in> s\" \"(x \\<longlongrightarrow> l) sequentially\"\n    then have \"l \\<in> s\"\n    proof (cases \"\\<forall>n. x n \\<noteq> l\")\n      case False\n      then show \"l\\<in>s\" using as(1) by auto\n    next\n      case True note cas = this\n      with as(2) have \"infinite (range x)\"\n        using sequence_infinite_lemma[of x l] by auto\n      then obtain l' where \"l'\\<in>s\" \"l' islimpt (range x)\"\n        using assms[THEN spec[where x=\"range x\"]] as(1) by auto\n      then show \"l\\<in>s\" using sequence_unique_limpt[of x l l']\n        using as cas by auto\n    qed\n  }\n  then show ?thesis\n    unfolding closed_sequential_limits by fast\nqed\n\nlemma closure_insert:\n  fixes x :: \"'a::t1_space\"\n  shows \"closure (insert x s) = insert x (closure s)\"\n  by (meson closed_closure closed_insert closure_minimal closure_subset dual_order.antisym insert_mono insert_subset)\n\nlemma finite_not_islimpt_in_compact:\n  assumes \"compact A\" \"\\<And>z. z \\<in> A \\<Longrightarrow> \\<not>z islimpt B\"\n  shows   \"finite (A \\<inter> B)\"\nproof (rule ccontr)\n  assume \"infinite (A \\<inter> B)\"\n  have \"\\<exists>z\\<in>A. z islimpt A \\<inter> B\"\n    by (rule Heine_Borel_imp_Bolzano_Weierstrass) (use assms \\<open>infinite _\\<close> in auto)\n  hence \"\\<exists>z\\<in>A. z islimpt B\"\n    using islimpt_subset by blast\n  thus False using assms(2)\n    by simp\nqed\n\n\ntext\\<open>In particular, some common special cases.\\<close>\n\nlemma compact_Un [intro]:\n  assumes \"compact s\"\n    and \"compact t\"\n  shows \" compact (s \\<union> t)\"\nproof (rule compactI)\n  fix f\n  assume *: \"Ball f open\" \"s \\<union> t \\<subseteq> \\<Union>f\"\n  from * \\<open>compact s\\<close> obtain s' where \"s' \\<subseteq> f \\<and> finite s' \\<and> s \\<subseteq> \\<Union>s'\"\n    unfolding compact_eq_Heine_Borel by (auto elim!: allE[of _ f])\n  moreover\n  from * \\<open>compact t\\<close> obtain t' where \"t' \\<subseteq> f \\<and> finite t' \\<and> t \\<subseteq> \\<Union>t'\"\n    unfolding compact_eq_Heine_Borel by (auto elim!: allE[of _ f])\n  ultimately show \"\\<exists>f'\\<subseteq>f. finite f' \\<and> s \\<union> t \\<subseteq> \\<Union>f'\"\n    by (auto intro!: exI[of _ \"s' \\<union> t'\"])\nqed\n\nlemma compact_Union [intro]: \"finite S \\<Longrightarrow> (\\<And>T. T \\<in> S \\<Longrightarrow> compact T) \\<Longrightarrow> compact (\\<Union>S)\"\n  by (induct set: finite) auto\n\nlemma compact_UN [intro]:\n  \"finite A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> compact (B x)) \\<Longrightarrow> compact (\\<Union>x\\<in>A. B x)\"\n  by (rule compact_Union) auto\n\nlemma closed_Int_compact [intro]:\n  assumes \"closed s\"\n    and \"compact t\"\n  shows \"compact (s \\<inter> t)\"\n  using compact_Int_closed [of t s] assms\n  by (simp add: Int_commute)\n\nlemma compact_Int [intro]:\n  fixes s t :: \"'a :: t2_space set\"\n  assumes \"compact s\"\n    and \"compact t\"\n  shows \"compact (s \\<inter> t)\"\n  using assms by (intro compact_Int_closed compact_imp_closed)\n\nlemma compact_sing [simp]: \"compact {a}\"\n  unfolding compact_eq_Heine_Borel by auto\n\nlemma compact_insert [simp]:\n  assumes \"compact s\"\n  shows \"compact (insert x s)\"\nproof -\n  have \"compact ({x} \\<union> s)\"\n    using compact_sing assms by (rule compact_Un)\n  then show ?thesis by simp\nqed\n\nlemma finite_imp_compact: \"finite s \\<Longrightarrow> compact s\"\n  by (induct set: finite) simp_all\n\nlemma open_delete:\n  fixes s :: \"'a::t1_space set\"\n  shows \"open s \\<Longrightarrow> open (s - {x})\"\n  by (simp add: open_Diff)\n\n\ntext\\<open>Compactness expressed with filters\\<close>\n\nlemma closure_iff_nhds_not_empty:\n  \"x \\<in> closure X \\<longleftrightarrow> (\\<forall>A. \\<forall>S\\<subseteq>A. open S \\<longrightarrow> x \\<in> S \\<longrightarrow> X \\<inter> A \\<noteq> {})\"\nproof safe\n  assume x: \"x \\<in> closure X\"\n  fix S A\n  assume \"open S\" \"x \\<in> S\" \"X \\<inter> A = {}\" \"S \\<subseteq> A\"\n  then have \"x \\<notin> closure (-S)\"\n    by (auto simp: closure_complement subset_eq[symmetric] intro: interiorI)\n  with x have \"x \\<in> closure X - closure (-S)\"\n    by auto\n  also have \"\\<dots> \\<subseteq> closure (X \\<inter> S)\"\n    using \\<open>open S\\<close> open_Int_closure_subset[of S X] by (simp add: closed_Compl ac_simps)\n  finally have \"X \\<inter> S \\<noteq> {}\" by auto\n  then show False using \\<open>X \\<inter> A = {}\\<close> \\<open>S \\<subseteq> A\\<close> by auto\nnext\n  assume \"\\<forall>A S. S \\<subseteq> A \\<longrightarrow> open S \\<longrightarrow> x \\<in> S \\<longrightarrow> X \\<inter> A \\<noteq> {}\"\n  from this[THEN spec, of \"- X\", THEN spec, of \"- closure X\"]\n  show \"x \\<in> closure X\"\n    by (simp add: closure_subset open_Compl)\nqed\n\nlemma compact_filter:\n  \"compact U \\<longleftrightarrow> (\\<forall>F. F \\<noteq> bot \\<longrightarrow> eventually (\\<lambda>x. x \\<in> U) F \\<longrightarrow> (\\<exists>x\\<in>U. inf (nhds x) F \\<noteq> bot))\"\nproof (intro allI iffI impI compact_fip[THEN iffD2] notI)\n  fix F\n  assume \"compact U\"\n  assume F: \"F \\<noteq> bot\" \"eventually (\\<lambda>x. x \\<in> U) F\"\n  then have \"U \\<noteq> {}\"\n    by (auto simp: eventually_False)\n\n  define Z where \"Z = closure ` {A. eventually (\\<lambda>x. x \\<in> A) F}\"\n  then have \"\\<forall>z\\<in>Z. closed z\"\n    by auto\n  moreover\n  have ev_Z: \"\\<And>z. z \\<in> Z \\<Longrightarrow> eventually (\\<lambda>x. x \\<in> z) F\"\n    unfolding Z_def by (auto elim: eventually_mono intro: subsetD[OF closure_subset])\n  have \"(\\<forall>B \\<subseteq> Z. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {})\"\n  proof (intro allI impI)\n    fix B assume \"finite B\" \"B \\<subseteq> Z\"\n    with \\<open>finite B\\<close> ev_Z F(2) have \"eventually (\\<lambda>x. x \\<in> U \\<inter> (\\<Inter>B)) F\"\n      by (auto simp: eventually_ball_finite_distrib eventually_conj_iff)\n    with F show \"U \\<inter> \\<Inter>B \\<noteq> {}\"\n      by (intro notI) (simp add: eventually_False)\n  qed\n  ultimately have \"U \\<inter> \\<Inter>Z \\<noteq> {}\"\n    using \\<open>compact U\\<close> unfolding compact_fip by blast\n  then obtain x where \"x \\<in> U\" and x: \"\\<And>z. z \\<in> Z \\<Longrightarrow> x \\<in> z\"\n    by auto\n\n  have \"\\<And>P. eventually P (inf (nhds x) F) \\<Longrightarrow> P \\<noteq> bot\"\n    unfolding eventually_inf eventually_nhds\n  proof safe\n    fix P Q R S\n    assume \"eventually R F\" \"open S\" \"x \\<in> S\"\n    with open_Int_closure_eq_empty[of S \"{x. R x}\"] x[of \"closure {x. R x}\"]\n    have \"S \\<inter> {x. R x} \\<noteq> {}\" by (auto simp: Z_def)\n    moreover assume \"Ball S Q\" \"\\<forall>x. Q x \\<and> R x \\<longrightarrow> bot x\"\n    ultimately show False by (auto simp: set_eq_iff)\n  qed\n  with \\<open>x \\<in> U\\<close> show \"\\<exists>x\\<in>U. inf (nhds x) F \\<noteq> bot\"\n    by (metis eventually_bot)\nnext\n  fix A\n  assume A: \"\\<forall>a\\<in>A. closed a\" \"\\<forall>B\\<subseteq>A. finite B \\<longrightarrow> U \\<inter> \\<Inter>B \\<noteq> {}\" \"U \\<inter> \\<Inter>A = {}\"\n  define F where \"F = (INF a\\<in>insert U A. principal a)\"\n  have \"F \\<noteq> bot\"\n    unfolding F_def\n  proof (rule INF_filter_not_bot)\n    fix X\n    assume X: \"X \\<subseteq> insert U A\" \"finite X\"\n    with A(2)[THEN spec, of \"X - {U}\"] have \"U \\<inter> \\<Inter>(X - {U}) \\<noteq> {}\"\n      by auto\n    with X show \"(INF a\\<in>X. principal a) \\<noteq> bot\"\n      by (auto simp: INF_principal_finite principal_eq_bot_iff)\n  qed\n  moreover\n  have \"F \\<le> principal U\"\n    unfolding F_def by auto\n  then have \"eventually (\\<lambda>x. x \\<in> U) F\"\n    by (auto simp: le_filter_def eventually_principal)\n  moreover\n  assume \"\\<forall>F. F \\<noteq> bot \\<longrightarrow> eventually (\\<lambda>x. x \\<in> U) F \\<longrightarrow> (\\<exists>x\\<in>U. inf (nhds x) F \\<noteq> bot)\"\n  ultimately obtain x where \"x \\<in> U\" and x: \"inf (nhds x) F \\<noteq> bot\"\n    by auto\n\n  { fix V assume \"V \\<in> A\"\n    then have \"F \\<le> principal V\"\n      unfolding F_def by (intro INF_lower2[of V]) auto\n    then have V: \"eventually (\\<lambda>x. x \\<in> V) F\"\n      by (auto simp: le_filter_def eventually_principal)\n    have \"x \\<in> closure V\"\n      unfolding closure_iff_nhds_not_empty\n    proof (intro impI allI)\n      fix S A\n      assume \"open S\" \"x \\<in> S\" \"S \\<subseteq> A\"\n      then have \"eventually (\\<lambda>x. x \\<in> A) (nhds x)\"\n        by (auto simp: eventually_nhds)\n      with V have \"eventually (\\<lambda>x. x \\<in> V \\<inter> A) (inf (nhds x) F)\"\n        by (auto simp: eventually_inf)\n      with x show \"V \\<inter> A \\<noteq> {}\"\n        by (auto simp del: Int_iff simp add: trivial_limit_def)\n    qed\n    then have \"x \\<in> V\"\n      using \\<open>V \\<in> A\\<close> A(1) by simp\n  }\n  with \\<open>x\\<in>U\\<close> have \"x \\<in> U \\<inter> \\<Inter>A\" by auto\n  with \\<open>U \\<inter> \\<Inter>A = {}\\<close> show False by auto\nqed\n\ndefinition\\<^marker>\\<open>tag important\\<close> countably_compact :: \"('a::topological_space) set \\<Rightarrow> bool\" where\n\"countably_compact U \\<longleftrightarrow>\n  (\\<forall>A. countable A \\<longrightarrow> (\\<forall>a\\<in>A. open a) \\<longrightarrow> U \\<subseteq> \\<Union>A\n     \\<longrightarrow> (\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T))\"\n\nlemma countably_compactE:\n  assumes \"countably_compact s\" and \"\\<forall>t\\<in>C. open t\" and \"s \\<subseteq> \\<Union>C\" \"countable C\"\n  obtains C' where \"C' \\<subseteq> C\" and \"finite C'\" and \"s \\<subseteq> \\<Union>C'\"\n  using assms unfolding countably_compact_def by metis\n\nlemma countably_compactI:\n  assumes \"\\<And>C. \\<forall>t\\<in>C. open t \\<Longrightarrow> s \\<subseteq> \\<Union>C \\<Longrightarrow> countable C \\<Longrightarrow> (\\<exists>C'\\<subseteq>C. finite C' \\<and> s \\<subseteq> \\<Union>C')\"\n  shows \"countably_compact s\"\n  using assms unfolding countably_compact_def by metis\n\nlemma compact_imp_countably_compact: \"compact U \\<Longrightarrow> countably_compact U\"\n  by (auto simp: compact_eq_Heine_Borel countably_compact_def)\n\nlemma countably_compact_imp_compact:\n  assumes \"countably_compact U\"\n    and ccover: \"countable B\" \"\\<forall>b\\<in>B. open b\"\n    and basis: \"\\<And>T x. open T \\<Longrightarrow> x \\<in> T \\<Longrightarrow> x \\<in> U \\<Longrightarrow> \\<exists>b\\<in>B. x \\<in> b \\<and> b \\<inter> U \\<subseteq> T\"\n  shows \"compact U\"\n  using \\<open>countably_compact U\\<close>\n  unfolding compact_eq_Heine_Borel countably_compact_def\nproof safe\n  fix A\n  assume A: \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\"\n  assume *: \"\\<forall>A. countable A \\<longrightarrow> (\\<forall>a\\<in>A. open a) \\<longrightarrow> U \\<subseteq> \\<Union>A \\<longrightarrow> (\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T)\"\n  moreover define C where \"C = {b\\<in>B. \\<exists>a\\<in>A. b \\<inter> U \\<subseteq> a}\"\n  ultimately have \"countable C\" \"\\<forall>a\\<in>C. open a\"\n    unfolding C_def using ccover by auto\n  moreover\n  have \"\\<Union>A \\<inter> U \\<subseteq> \\<Union>C\"\n  proof safe\n    fix x a\n    assume \"x \\<in> U\" \"x \\<in> a\" \"a \\<in> A\"\n    with basis[of a x] A obtain b where \"b \\<in> B\" \"x \\<in> b\" \"b \\<inter> U \\<subseteq> a\"\n      by blast\n    with \\<open>a \\<in> A\\<close> show \"x \\<in> \\<Union>C\"\n      unfolding C_def by auto\n  qed\n  then have \"U \\<subseteq> \\<Union>C\" using \\<open>U \\<subseteq> \\<Union>A\\<close> by auto\n  ultimately obtain T where T: \"T\\<subseteq>C\" \"finite T\" \"U \\<subseteq> \\<Union>T\"\n    using * by metis\n  then have \"\\<forall>t\\<in>T. \\<exists>a\\<in>A. t \\<inter> U \\<subseteq> a\"\n    by (auto simp: C_def)\n  then obtain f where \"\\<forall>t\\<in>T. f t \\<in> A \\<and> t \\<inter> U \\<subseteq> f t\"\n    unfolding bchoice_iff Bex_def ..\n  with T show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n    unfolding C_def by (intro exI[of _ \"f`T\"]) fastforce\nqed\n\nproposition countably_compact_imp_compact_second_countable:\n  \"countably_compact U \\<Longrightarrow> compact (U :: 'a :: second_countable_topology set)\"\nproof (rule countably_compact_imp_compact)\n  fix T and x :: 'a\n  assume \"open T\" \"x \\<in> T\"\n  from topological_basisE[OF is_basis this] obtain b where\n    \"b \\<in> (SOME B. countable B \\<and> topological_basis B)\" \"x \\<in> b\" \"b \\<subseteq> T\" .\n  then show \"\\<exists>b\\<in>SOME B. countable B \\<and> topological_basis B. x \\<in> b \\<and> b \\<inter> U \\<subseteq> T\"\n    by blast\nqed (insert countable_basis topological_basis_open[OF is_basis], auto)\n\nlemma countably_compact_eq_compact:\n  \"countably_compact U \\<longleftrightarrow> compact (U :: 'a :: second_countable_topology set)\"\n  using countably_compact_imp_compact_second_countable compact_imp_countably_compact by blast\n\nsubsubsection\\<open>Sequential compactness\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> seq_compact :: \"'a::topological_space set \\<Rightarrow> bool\" where\n\"seq_compact S \\<longleftrightarrow>\n  (\\<forall>f. (\\<forall>n. f n \\<in> S)\n    \\<longrightarrow> (\\<exists>l\\<in>S. \\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially))\"\n\nlemma seq_compactI:\n  assumes \"\\<And>f. \\<forall>n. f n \\<in> S \\<Longrightarrow> \\<exists>l\\<in>S. \\<exists>r::nat\\<Rightarrow>nat. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n  shows \"seq_compact S\"\n  unfolding seq_compact_def using assms by fast\n\nlemma seq_compactE:\n  assumes \"seq_compact S\" \"\\<forall>n. f n \\<in> S\"\n  obtains l r where \"l \\<in> S\" \"strict_mono (r :: nat \\<Rightarrow> nat)\" \"((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n  using assms unfolding seq_compact_def by fast\n\nlemma closed_sequentially: (* TODO: move upwards *)\n  assumes \"closed s\" and \"\\<forall>n. f n \\<in> s\" and \"f \\<longlonglongrightarrow> l\"\n  shows \"l \\<in> s\"\nproof (rule ccontr)\n  assume \"l \\<notin> s\"\n  with \\<open>closed s\\<close> and \\<open>f \\<longlonglongrightarrow> l\\<close> have \"eventually (\\<lambda>n. f n \\<in> - s) sequentially\"\n    by (fast intro: topological_tendstoD)\n  with \\<open>\\<forall>n. f n \\<in> s\\<close> show \"False\"\n    by simp\nqed\n\nlemma seq_compact_Int_closed:\n  assumes \"seq_compact s\" and \"closed t\"\n  shows \"seq_compact (s \\<inter> t)\"\nproof (rule seq_compactI)\n  fix f assume \"\\<forall>n::nat. f n \\<in> s \\<inter> t\"\n  hence \"\\<forall>n. f n \\<in> s\" and \"\\<forall>n. f n \\<in> t\"\n    by simp_all\n  from \\<open>seq_compact s\\<close> and \\<open>\\<forall>n. f n \\<in> s\\<close>\n  obtain l r where \"l \\<in> s\" and r: \"strict_mono r\" and l: \"(f \\<circ> r) \\<longlonglongrightarrow> l\"\n    by (rule seq_compactE)\n  from \\<open>\\<forall>n. f n \\<in> t\\<close> have \"\\<forall>n. (f \\<circ> r) n \\<in> t\"\n    by simp\n  from \\<open>closed t\\<close> and this and l have \"l \\<in> t\"\n    by (rule closed_sequentially)\n  with \\<open>l \\<in> s\\<close> and r and l show \"\\<exists>l\\<in>s \\<inter> t. \\<exists>r. strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n    by fast\nqed\n\nlemma seq_compact_closed_subset:\n  assumes \"closed s\" and \"s \\<subseteq> t\" and \"seq_compact t\"\n  shows \"seq_compact s\"\n  using assms seq_compact_Int_closed [of t s] by (simp add: Int_absorb1)\n\nlemma seq_compact_imp_countably_compact:\n  fixes U :: \"'a :: first_countable_topology set\"\n  assumes \"seq_compact U\"\n  shows \"countably_compact U\"\nproof (safe intro!: countably_compactI)\n  fix A\n  assume A: \"\\<forall>a\\<in>A. open a\" \"U \\<subseteq> \\<Union>A\" \"countable A\"\n  have subseq: \"\\<And>X. range X \\<subseteq> U \\<Longrightarrow> \\<exists>r x. x \\<in> U \\<and> strict_mono (r :: nat \\<Rightarrow> nat) \\<and> (X \\<circ> r) \\<longlonglongrightarrow> x\"\n    using \\<open>seq_compact U\\<close> by (fastforce simp: seq_compact_def subset_eq)\n  show \"\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T\"\n  proof cases\n    assume \"finite A\"\n    with A show ?thesis by auto\n  next\n    assume \"infinite A\"\n    then have \"A \\<noteq> {}\" by auto\n    show ?thesis\n    proof (rule ccontr)\n      assume \"\\<not> (\\<exists>T\\<subseteq>A. finite T \\<and> U \\<subseteq> \\<Union>T)\"\n      then have \"\\<forall>T. \\<exists>x. T \\<subseteq> A \\<and> finite T \\<longrightarrow> (x \\<in> U - \\<Union>T)\"\n        by auto\n      then obtain X' where T: \"\\<And>T. T \\<subseteq> A \\<Longrightarrow> finite T \\<Longrightarrow> X' T \\<in> U - \\<Union>T\"\n        by metis\n      define X where \"X n = X' (from_nat_into A ` {.. n})\" for n\n      have X: \"\\<And>n. X n \\<in> U - (\\<Union>i\\<le>n. from_nat_into A i)\"\n        using \\<open>A \\<noteq> {}\\<close> unfolding X_def by (intro T) (auto intro: from_nat_into)\n      then have \"range X \\<subseteq> U\"\n        by auto\n      with subseq[of X] obtain r x where \"x \\<in> U\" and r: \"strict_mono r\" \"(X \\<circ> r) \\<longlonglongrightarrow> x\"\n        by auto\n      from \\<open>x\\<in>U\\<close> \\<open>U \\<subseteq> \\<Union>A\\<close> from_nat_into_surj[OF \\<open>countable A\\<close>]\n      obtain n where \"x \\<in> from_nat_into A n\" by auto\n      with r(2) A(1) from_nat_into[OF \\<open>A \\<noteq> {}\\<close>, of n]\n      have \"eventually (\\<lambda>i. X (r i) \\<in> from_nat_into A n) sequentially\"\n        unfolding tendsto_def by (auto simp: comp_def)\n      then obtain N where \"\\<And>i. N \\<le> i \\<Longrightarrow> X (r i) \\<in> from_nat_into A n\"\n        by (auto simp: eventually_sequentially)\n      moreover from X have \"\\<And>i. n \\<le> r i \\<Longrightarrow> X (r i) \\<notin> from_nat_into A n\"\n        by auto\n      moreover from \\<open>strict_mono r\\<close>[THEN seq_suble, of \"max n N\"] have \"\\<exists>i. n \\<le> r i \\<and> N \\<le> i\"\n        by (auto intro!: exI[of _ \"max n N\"])\n      ultimately show False\n        by auto\n    qed\n  qed\nqed\n\nlemma compact_imp_seq_compact:\n  fixes U :: \"'a :: first_countable_topology set\"\n  assumes \"compact U\"\n  shows \"seq_compact U\"\n  unfolding seq_compact_def\nproof safe\n  fix X :: \"nat \\<Rightarrow> 'a\"\n  assume \"\\<forall>n. X n \\<in> U\"\n  then have \"eventually (\\<lambda>x. x \\<in> U) (filtermap X sequentially)\"\n    by (auto simp: eventually_filtermap)\n  moreover\n  have \"filtermap X sequentially \\<noteq> bot\"\n    by (simp add: trivial_limit_def eventually_filtermap)\n  ultimately\n  obtain x where \"x \\<in> U\" and x: \"inf (nhds x) (filtermap X sequentially) \\<noteq> bot\" (is \"?F \\<noteq> _\")\n    using \\<open>compact U\\<close> by (auto simp: compact_filter)\n\n  from countable_basis_at_decseq[of x]\n  obtain A where A:\n      \"\\<And>i. open (A i)\"\n      \"\\<And>i. x \\<in> A i\"\n      \"\\<And>S. open S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\n    by blast\n  define s where \"s n i = (SOME j. i < j \\<and> X j \\<in> A (Suc n))\" for n i\n  {\n    fix n i\n    have \"\\<exists>a. i < a \\<and> X a \\<in> A (Suc n)\"\n    proof (rule ccontr)\n      assume \"\\<not> (\\<exists>a>i. X a \\<in> A (Suc n))\"\n      then have \"\\<And>a. Suc i \\<le> a \\<Longrightarrow> X a \\<notin> A (Suc n)\"\n        by auto\n      then have \"eventually (\\<lambda>x. x \\<notin> A (Suc n)) (filtermap X sequentially)\"\n        by (auto simp: eventually_filtermap eventually_sequentially)\n      moreover have \"eventually (\\<lambda>x. x \\<in> A (Suc n)) (nhds x)\"\n        using A(1,2)[of \"Suc n\"] by (auto simp: eventually_nhds)\n      ultimately have \"eventually (\\<lambda>x. False) ?F\"\n        by (auto simp: eventually_inf)\n      with x show False\n        by (simp add: eventually_False)\n    qed\n    then have \"i < s n i\" \"X (s n i) \\<in> A (Suc n)\"\n      unfolding s_def by (auto intro: someI2_ex)\n  }\n  note s = this\n  define r where \"r = rec_nat (s 0 0) s\"\n  have \"strict_mono r\"\n    by (auto simp: r_def s strict_mono_Suc_iff)\n  moreover\n  have \"(\\<lambda>n. X (r n)) \\<longlonglongrightarrow> x\"\n  proof (rule topological_tendstoI)\n    fix S\n    assume \"open S\" \"x \\<in> S\"\n    with A(3) have \"eventually (\\<lambda>i. A i \\<subseteq> S) sequentially\"\n      by auto\n    moreover\n    {\n      fix i\n      assume \"Suc 0 \\<le> i\"\n      then have \"X (r i) \\<in> A i\"\n        by (cases i) (simp_all add: r_def s)\n    }\n    then have \"eventually (\\<lambda>i. X (r i) \\<in> A i) sequentially\"\n      by (auto simp: eventually_sequentially)\n    ultimately show \"eventually (\\<lambda>i. X (r i) \\<in> S) sequentially\"\n      by eventually_elim auto\n  qed\n  ultimately show \"\\<exists>x \\<in> U. \\<exists>r. strict_mono r \\<and> (X \\<circ> r) \\<longlonglongrightarrow> x\"\n    using \\<open>x \\<in> U\\<close> by (auto simp: convergent_def comp_def)\nqed\n\nlemma countably_compact_imp_acc_point:\n  assumes \"countably_compact s\"\n    and \"countable t\"\n    and \"infinite t\"\n    and \"t \\<subseteq> s\"\n  shows \"\\<exists>x\\<in>s. \\<forall>U. x\\<in>U \\<and> open U \\<longrightarrow> infinite (U \\<inter> t)\"\nproof (rule ccontr)\n  define C where \"C = (\\<lambda>F. interior (F \\<union> (- t))) ` {F. finite F \\<and> F \\<subseteq> t }\"\n  note \\<open>countably_compact s\\<close>\n  moreover have \"\\<forall>t\\<in>C. open t\"\n    by (auto simp: C_def)\n  moreover\n  assume \"\\<not> (\\<exists>x\\<in>s. \\<forall>U. x\\<in>U \\<and> open U \\<longrightarrow> infinite (U \\<inter> t))\"\n  then have s: \"\\<And>x. x \\<in> s \\<Longrightarrow> \\<exists>U. x\\<in>U \\<and> open U \\<and> finite (U \\<inter> t)\" by metis\n  have \"s \\<subseteq> \\<Union>C\"\n    using \\<open>t \\<subseteq> s\\<close>\n    unfolding C_def\n    apply (safe dest!: s)\n    apply (rule_tac a=\"U \\<inter> t\" in UN_I)\n    apply (auto intro!: interiorI simp add: finite_subset)\n    done\n  moreover\n  from \\<open>countable t\\<close> have \"countable C\"\n    unfolding C_def by (auto intro: countable_Collect_finite_subset)\n  ultimately\n  obtain D where \"D \\<subseteq> C\" \"finite D\" \"s \\<subseteq> \\<Union>D\"\n    by (rule countably_compactE)\n  then obtain E where E: \"E \\<subseteq> {F. finite F \\<and> F \\<subseteq> t }\" \"finite E\"\n    and s: \"s \\<subseteq> (\\<Union>F\\<in>E. interior (F \\<union> (- t)))\"\n    by (metis (lifting) finite_subset_image C_def)\n  from s \\<open>t \\<subseteq> s\\<close> have \"t \\<subseteq> \\<Union>E\"\n    using interior_subset by blast\n  moreover have \"finite (\\<Union>E)\"\n    using E by auto\n  ultimately show False using \\<open>infinite t\\<close>\n    by (auto simp: finite_subset)\nqed\n\nlemma countable_acc_point_imp_seq_compact:\n  fixes s :: \"'a::first_countable_topology set\"\n  assumes \"\\<forall>t. infinite t \\<and> countable t \\<and> t \\<subseteq> s \\<longrightarrow>\n    (\\<exists>x\\<in>s. \\<forall>U. x\\<in>U \\<and> open U \\<longrightarrow> infinite (U \\<inter> t))\"\n  shows \"seq_compact s\"\nproof -\n  {\n    fix f :: \"nat \\<Rightarrow> 'a\"\n    assume f: \"\\<forall>n. f n \\<in> s\"\n    have \"\\<exists>l\\<in>s. \\<exists>r. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n    proof (cases \"finite (range f)\")\n      case True\n      obtain l where \"infinite {n. f n = f l}\"\n        using pigeonhole_infinite[OF _ True] by auto\n      then obtain r :: \"nat \\<Rightarrow> nat\" where \"strict_mono  r\" and fr: \"\\<forall>n. f (r n) = f l\"\n        using infinite_enumerate by blast\n      then have \"strict_mono r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> f l\"\n        by (simp add: fr o_def)\n      with f show \"\\<exists>l\\<in>s. \\<exists>r. strict_mono  r \\<and> (f \\<circ> r) \\<longlonglongrightarrow> l\"\n        by auto\n    next\n      case False\n      with f assms have \"\\<exists>x\\<in>s. \\<forall>U. x\\<in>U \\<and> open U \\<longrightarrow> infinite (U \\<inter> range f)\"\n        by auto\n      then obtain l where \"l \\<in> s\" \"\\<forall>U. l\\<in>U \\<and> open U \\<longrightarrow> infinite (U \\<inter> range f)\" ..\n      from this(2) have \"\\<exists>r. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\"\n        using acc_point_range_imp_convergent_subsequence[of l f] by auto\n      with \\<open>l \\<in> s\\<close> show \"\\<exists>l\\<in>s. \\<exists>r. strict_mono r \\<and> ((f \\<circ> r) \\<longlongrightarrow> l) sequentially\" ..\n    qed\n  }\n  then show ?thesis\n    unfolding seq_compact_def by auto\nqed\n\nlemma seq_compact_eq_countably_compact:\n  fixes U :: \"'a :: first_countable_topology set\"\n  shows \"seq_compact U \\<longleftrightarrow> countably_compact U\"\n  using\n    countable_acc_point_imp_seq_compact\n    countably_compact_imp_acc_point\n    seq_compact_imp_countably_compact\n  by metis\n\nlemma seq_compact_eq_acc_point:\n  fixes s :: \"'a :: first_countable_topology set\"\n  shows \"seq_compact s \\<longleftrightarrow>\n    (\\<forall>t. infinite t \\<and> countable t \\<and> t \\<subseteq> s --> (\\<exists>x\\<in>s. \\<forall>U. x\\<in>U \\<and> open U \\<longrightarrow> infinite (U \\<inter> t)))\"\n  using\n    countable_acc_point_imp_seq_compact[of s]\n    countably_compact_imp_acc_point[of s]\n    seq_compact_imp_countably_compact[of s]\n  by metis\n\nlemma seq_compact_eq_compact:\n  fixes U :: \"'a :: second_countable_topology set\"\n  shows \"seq_compact U \\<longleftrightarrow> compact U\"\n  using seq_compact_eq_countably_compact countably_compact_eq_compact by blast\n\nproposition Bolzano_Weierstrass_imp_seq_compact:\n  fixes s :: \"'a::{t1_space, first_countable_topology} set\"\n  shows \"\\<forall>t. infinite t \\<and> t \\<subseteq> s \\<longrightarrow> (\\<exists>x \\<in> s. x islimpt t) \\<Longrightarrow> seq_compact s\"\n  by (rule countable_acc_point_imp_seq_compact) (metis islimpt_eq_acc_point)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Cartesian products\\<close>\n\nlemma seq_compact_Times: \"seq_compact s \\<Longrightarrow> seq_compact t \\<Longrightarrow> seq_compact (s \\<times> t)\"\n  unfolding seq_compact_def\n  apply clarify\n  apply (drule_tac x=\"fst \\<circ> f\" in spec)\n  apply (drule mp, simp add: mem_Times_iff)\n  apply (clarify, rename_tac l1 r1)\n  apply (drule_tac x=\"snd \\<circ> f \\<circ> r1\" in spec)\n  apply (drule mp, simp add: mem_Times_iff)\n  apply (clarify, rename_tac l2 r2)\n  apply (rule_tac x=\"(l1, l2)\" in rev_bexI, simp)\n  apply (rule_tac x=\"r1 \\<circ> r2\" in exI)\n  apply (rule conjI, simp add: strict_mono_def)\n  apply (drule_tac f=r2 in LIMSEQ_subseq_LIMSEQ, assumption)\n  apply (drule (1) tendsto_Pair) back\n  apply (simp add: o_def)\n  done\n\nlemma compact_Times:\n  assumes \"compact s\" \"compact t\"\n  shows \"compact (s \\<times> t)\"\nproof (rule compactI)\n  fix C\n  assume C: \"\\<forall>t\\<in>C. open t\" \"s \\<times> t \\<subseteq> \\<Union>C\"\n  have \"\\<forall>x\\<in>s. \\<exists>a. open a \\<and> x \\<in> a \\<and> (\\<exists>d\\<subseteq>C. finite d \\<and> a \\<times> t \\<subseteq> \\<Union>d)\"\n  proof\n    fix x\n    assume \"x \\<in> s\"\n    have \"\\<forall>y\\<in>t. \\<exists>a b c. c \\<in> C \\<and> open a \\<and> open b \\<and> x \\<in> a \\<and> y \\<in> b \\<and> a \\<times> b \\<subseteq> c\" (is \"\\<forall>y\\<in>t. ?P y\")\n    proof\n      fix y\n      assume \"y \\<in> t\"\n      with \\<open>x \\<in> s\\<close> C obtain c where \"c \\<in> C\" \"(x, y) \\<in> c\" \"open c\" by auto\n      then show \"?P y\" by (auto elim!: open_prod_elim)\n    qed\n    then obtain a b c where b: \"\\<And>y. y \\<in> t \\<Longrightarrow> open (b y)\"\n      and c: \"\\<And>y. y \\<in> t \\<Longrightarrow> c y \\<in> C \\<and> open (a y) \\<and> open (b y) \\<and> x \\<in> a y \\<and> y \\<in> b y \\<and> a y \\<times> b y \\<subseteq> c y\"\n      by metis\n    then have \"\\<forall>y\\<in>t. open (b y)\" \"t \\<subseteq> (\\<Union>y\\<in>t. b y)\" by auto\n    with compactE_image[OF \\<open>compact t\\<close>] obtain D where D: \"D \\<subseteq> t\" \"finite D\" \"t \\<subseteq> (\\<Union>y\\<in>D. b y)\"\n      by metis\n    moreover from D c have \"(\\<Inter>y\\<in>D. a y) \\<times> t \\<subseteq> (\\<Union>y\\<in>D. c y)\"\n      by (fastforce simp: subset_eq)\n    ultimately show \"\\<exists>a. open a \\<and> x \\<in> a \\<and> (\\<exists>d\\<subseteq>C. finite d \\<and> a \\<times> t \\<subseteq> \\<Union>d)\"\n      using c by (intro exI[of _ \"c`D\"] exI[of _ \"\\<Inter>(a`D)\"] conjI) (auto intro!: open_INT)\n  qed\n  then obtain a d where a: \"\\<And>x. x\\<in>s \\<Longrightarrow> open (a x)\" \"s \\<subseteq> (\\<Union>x\\<in>s. a x)\"\n    and d: \"\\<And>x. x \\<in> s \\<Longrightarrow> d x \\<subseteq> C \\<and> finite (d x) \\<and> a x \\<times> t \\<subseteq> \\<Union>(d x)\"\n    unfolding subset_eq UN_iff by metis\n  moreover\n  from compactE_image[OF \\<open>compact s\\<close> a]\n  obtain e where e: \"e \\<subseteq> s\" \"finite e\" and s: \"s \\<subseteq> (\\<Union>x\\<in>e. a x)\"\n    by auto\n  moreover\n  {\n    from s have \"s \\<times> t \\<subseteq> (\\<Union>x\\<in>e. a x \\<times> t)\"\n      by auto\n    also have \"\\<dots> \\<subseteq> (\\<Union>x\\<in>e. \\<Union>(d x))\"\n      using d \\<open>e \\<subseteq> s\\<close> by (intro UN_mono) auto\n    finally have \"s \\<times> t \\<subseteq> (\\<Union>x\\<in>e. \\<Union>(d x))\" .\n  }\n  ultimately show \"\\<exists>C'\\<subseteq>C. finite C' \\<and> s \\<times> t \\<subseteq> \\<Union>C'\"\n    by (intro exI[of _ \"(\\<Union>x\\<in>e. d x)\"]) (auto simp: subset_eq)\nqed\n\n\nlemma tube_lemma:\n  assumes \"compact K\"\n  assumes \"open W\"\n  assumes \"{x0} \\<times> K \\<subseteq> W\"\n  shows \"\\<exists>X0. x0 \\<in> X0 \\<and> open X0 \\<and> X0 \\<times> K \\<subseteq> W\"\nproof -\n  {\n    fix y assume \"y \\<in> K\"\n    then have \"(x0, y) \\<in> W\" using assms by auto\n    with \\<open>open W\\<close>\n    have \"\\<exists>X0 Y. open X0 \\<and> open Y \\<and> x0 \\<in> X0 \\<and> y \\<in> Y \\<and> X0 \\<times> Y \\<subseteq> W\"\n      by (rule open_prod_elim) blast\n  }\n  then obtain X0 Y where\n    *: \"\\<forall>y \\<in> K. open (X0 y) \\<and> open (Y y) \\<and> x0 \\<in> X0 y \\<and> y \\<in> Y y \\<and> X0 y \\<times> Y y \\<subseteq> W\"\n    by metis\n  from * have \"\\<forall>t\\<in>Y ` K. open t\" \"K \\<subseteq> \\<Union>(Y ` K)\" by auto\n  with \\<open>compact K\\<close> obtain CC where CC: \"CC \\<subseteq> Y ` K\" \"finite CC\" \"K \\<subseteq> \\<Union>CC\"\n    by (meson compactE)\n  then obtain c where c: \"\\<And>C. C \\<in> CC \\<Longrightarrow> c C \\<in> K \\<and> C = Y (c C)\"\n    by (force intro!: choice)\n  with * CC show ?thesis\n    by (force intro!: exI[where x=\"\\<Inter>C\\<in>CC. X0 (c C)\"]) (* SLOW *)\nqed\n\nlemma continuous_on_prod_compactE:\n  fixes fx::\"'a::topological_space \\<times> 'b::topological_space \\<Rightarrow> 'c::metric_space\"\n    and e::real\n  assumes cont_fx: \"continuous_on (U \\<times> C) fx\"\n  assumes \"compact C\"\n  assumes [intro]: \"x0 \\<in> U\"\n  notes [continuous_intros] = continuous_on_compose2[OF cont_fx]\n  assumes \"e > 0\"\n  obtains X0 where \"x0 \\<in> X0\" \"open X0\"\n    \"\\<forall>x\\<in>X0 \\<inter> U. \\<forall>t \\<in> C. dist (fx (x, t)) (fx (x0, t)) \\<le> e\"\nproof -\n  define psi where \"psi = (\\<lambda>(x, t). dist (fx (x, t)) (fx (x0, t)))\"\n  define W0 where \"W0 = {(x, t) \\<in> U \\<times> C. psi (x, t) < e}\"\n  have W0_eq: \"W0 = psi -` {..<e} \\<inter> U \\<times> C\"\n    by (auto simp: vimage_def W0_def)\n  have \"open {..<e}\" by simp\n  have \"continuous_on (U \\<times> C) psi\"\n    by (auto intro!: continuous_intros simp: psi_def split_beta')\n  from this[unfolded continuous_on_open_invariant, rule_format, OF \\<open>open {..<e}\\<close>]\n  obtain W where W: \"open W\" \"W \\<inter> U \\<times> C = W0 \\<inter> U \\<times> C\"\n    unfolding W0_eq by blast\n  have \"{x0} \\<times> C \\<subseteq> W \\<inter> U \\<times> C\"\n    unfolding W\n    by (auto simp: W0_def psi_def \\<open>0 < e\\<close>)\n  then have \"{x0} \\<times> C \\<subseteq> W\" by blast\n  from tube_lemma[OF \\<open>compact C\\<close> \\<open>open W\\<close> this]\n  obtain X0 where X0: \"x0 \\<in> X0\" \"open X0\" \"X0 \\<times> C \\<subseteq> W\"\n    by blast\n\n  have \"\\<forall>x\\<in>X0 \\<inter> U. \\<forall>t \\<in> C. dist (fx (x, t)) (fx (x0, t)) \\<le> e\"\n  proof safe\n    fix x assume x: \"x \\<in> X0\" \"x \\<in> U\"\n    fix t assume t: \"t \\<in> C\"\n    have \"dist (fx (x, t)) (fx (x0, t)) = psi (x, t)\"\n      by (auto simp: psi_def)\n    also\n    {\n      have \"(x, t) \\<in> X0 \\<times> C\"\n        using t x\n        by auto\n      also note \\<open>\\<dots> \\<subseteq> W\\<close>\n      finally have \"(x, t) \\<in> W\" .\n      with t x have \"(x, t) \\<in> W \\<inter> U \\<times> C\"\n        by blast\n      also note \\<open>W \\<inter> U \\<times> C = W0 \\<inter> U \\<times> C\\<close>\n      finally  have \"psi (x, t) < e\"\n        by (auto simp: W0_def)\n    }\n    finally show \"dist (fx (x, t)) (fx (x0, t)) \\<le> e\" by simp\n  qed\n  from X0(1,2) this show ?thesis ..\nqed\n\n\nsubsection \\<open>Continuity\\<close>\n\nlemma continuous_at_imp_continuous_within:\n  \"continuous (at x) f \\<Longrightarrow> continuous (at x within s) f\"\n  unfolding continuous_within continuous_at using Lim_at_imp_Lim_at_within by auto\n\nlemma Lim_trivial_limit: \"trivial_limit net \\<Longrightarrow> (f \\<longlongrightarrow> l) net\"\n  by simp\n\nlemmas continuous_on = continuous_on_def \\<comment> \\<open>legacy theorem name\\<close>\n\nlemma continuous_within_subset:\n  \"continuous (at x within s) f \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> continuous (at x within t) f\"\n  unfolding continuous_within by(metis tendsto_within_subset)\n\nlemma continuous_on_interior:\n  \"continuous_on s f \\<Longrightarrow> x \\<in> interior s \\<Longrightarrow> continuous (at x) f\"\n  by (metis continuous_on_eq_continuous_at continuous_on_subset interiorE)\n\nlemma continuous_on_eq:\n  \"\\<lbrakk>continuous_on s f; \\<And>x. x \\<in> s \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> continuous_on s g\"\n  unfolding continuous_on_def tendsto_def eventually_at_topological\n  by simp\n\ntext \\<open>Characterization of various kinds of continuity in terms of sequences.\\<close>\n\nlemma continuous_within_sequentiallyI:\n  fixes f :: \"'a::{first_countable_topology, t2_space} \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<And>u::nat \\<Rightarrow> 'a. u \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<forall>n. u n \\<in> s) \\<Longrightarrow> (\\<lambda>n. f (u n)) \\<longlonglongrightarrow> f a\"\n  shows \"continuous (at a within s) f\"\n  using assms unfolding continuous_within tendsto_def[where l = \"f a\"]\n  by (auto intro!: sequentially_imp_eventually_within)\n\nlemma continuous_within_tendsto_compose:\n  fixes f::\"'a::t2_space \\<Rightarrow> 'b::topological_space\"\n  assumes \"continuous (at a within s) f\"\n          \"eventually (\\<lambda>n. x n \\<in> s) F\"\n          \"(x \\<longlongrightarrow> a) F \"\n  shows \"((\\<lambda>n. f (x n)) \\<longlongrightarrow> f a) F\"\nproof -\n  have *: \"filterlim x (inf (nhds a) (principal s)) F\"\n    using assms(2) assms(3) unfolding at_within_def filterlim_inf by (auto simp: filterlim_principal eventually_mono)\n  show ?thesis\n    by (auto simp: assms(1) continuous_within[symmetric] tendsto_at_within_iff_tendsto_nhds[symmetric] intro!: filterlim_compose[OF _ *])\nqed\n\nlemma continuous_within_tendsto_compose':\n  fixes f::\"'a::t2_space \\<Rightarrow> 'b::topological_space\"\n  assumes \"continuous (at a within s) f\"\n    \"\\<And>n. x n \\<in> s\"\n    \"(x \\<longlongrightarrow> a) F \"\n  shows \"((\\<lambda>n. f (x n)) \\<longlongrightarrow> f a) F\"\n  by (auto intro!: continuous_within_tendsto_compose[OF assms(1)] simp add: assms)\n\nlemma continuous_within_sequentially:\n  fixes f :: \"'a::{first_countable_topology, t2_space} \\<Rightarrow> 'b::topological_space\"\n  shows \"continuous (at a within s) f \\<longleftrightarrow>\n    (\\<forall>x. (\\<forall>n::nat. x n \\<in> s) \\<and> (x \\<longlongrightarrow> a) sequentially\n         \\<longrightarrow> ((f \\<circ> x) \\<longlongrightarrow> f a) sequentially)\"\n  using continuous_within_tendsto_compose'[of a s f _ sequentially]\n    continuous_within_sequentiallyI[of a s f]\n  by (auto simp: o_def)\n\nlemma continuous_at_sequentiallyI:\n  fixes f :: \"'a::{first_countable_topology, t2_space} \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<And>u. u \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<lambda>n. f (u n)) \\<longlonglongrightarrow> f a\"\n  shows \"continuous (at a) f\"\n  using continuous_within_sequentiallyI[of a UNIV f] assms by auto\n\nlemma continuous_at_sequentially:\n  fixes f :: \"'a::metric_space \\<Rightarrow> 'b::topological_space\"\n  shows \"continuous (at a) f \\<longleftrightarrow>\n    (\\<forall>x. (x \\<longlongrightarrow> a) sequentially --> ((f \\<circ> x) \\<longlongrightarrow> f a) sequentially)\"\n  using continuous_within_sequentially[of a UNIV f] by simp\n\nlemma continuous_on_sequentiallyI:\n  fixes f :: \"'a::{first_countable_topology, t2_space} \\<Rightarrow> 'b::topological_space\"\n  assumes \"\\<And>u a. (\\<forall>n. u n \\<in> s) \\<Longrightarrow> a \\<in> s \\<Longrightarrow> u \\<longlonglongrightarrow> a \\<Longrightarrow> (\\<lambda>n. f (u n)) \\<longlonglongrightarrow> f a\"\n  shows \"continuous_on s f\"\n  using assms unfolding continuous_on_eq_continuous_within\n  using continuous_within_sequentiallyI[of _ s f] by auto\n\nlemma continuous_on_sequentially:\n  fixes f :: \"'a::{first_countable_topology, t2_space} \\<Rightarrow> 'b::topological_space\"\n  shows \"continuous_on s f \\<longleftrightarrow>\n    (\\<forall>x. \\<forall>a \\<in> s. (\\<forall>n. x(n) \\<in> s) \\<and> (x \\<longlongrightarrow> a) sequentially\n      --> ((f \\<circ> x) \\<longlongrightarrow> f a) sequentially)\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?rhs\n  then show ?lhs\n    using continuous_within_sequentially[of _ s f]\n    unfolding continuous_on_eq_continuous_within\n    by auto\nnext\n  assume ?lhs\n  then show ?rhs\n    unfolding continuous_on_eq_continuous_within\n    using continuous_within_sequentially[of _ s f]\n    by auto\nqed\n\ntext \\<open>Continuity in terms of open preimages.\\<close>\n\nlemma continuous_at_open:\n  \"continuous (at x) f \\<longleftrightarrow> (\\<forall>t. open t \\<and> f x \\<in> t --> (\\<exists>s. open s \\<and> x \\<in> s \\<and> (\\<forall>x' \\<in> s. (f x') \\<in> t)))\"\n  unfolding continuous_within_topological [of x UNIV f]\n  unfolding imp_conjL\n  by (intro all_cong imp_cong ex_cong conj_cong refl) auto\n\nlemma continuous_imp_tendsto:\n  assumes \"continuous (at x0) f\"\n    and \"x \\<longlonglongrightarrow> x0\"\n  shows \"(f \\<circ> x) \\<longlonglongrightarrow> (f x0)\"\nproof (rule topological_tendstoI)\n  fix S\n  assume \"open S\" \"f x0 \\<in> S\"\n  then obtain T where T_def: \"open T\" \"x0 \\<in> T\" \"\\<forall>x\\<in>T. f x \\<in> S\"\n     using assms continuous_at_open by metis\n  then have \"eventually (\\<lambda>n. x n \\<in> T) sequentially\"\n    using assms T_def by (auto simp: tendsto_def)\n  then show \"eventually (\\<lambda>n. (f \\<circ> x) n \\<in> S) sequentially\"\n    using T_def by (auto elim!: eventually_mono)\nqed\n\nsubsection \\<open>Homeomorphisms\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> \"homeomorphism s t f g \\<longleftrightarrow>\n  (\\<forall>x\\<in>s. (g(f x) = x)) \\<and> (f ` s = t) \\<and> continuous_on s f \\<and>\n  (\\<forall>y\\<in>t. (f(g y) = y)) \\<and> (g ` t = s) \\<and> continuous_on t g\"\n\nlemma homeomorphismI [intro?]:\n  assumes \"continuous_on S f\" \"continuous_on T g\"\n          \"f ` S \\<subseteq> T\" \"g ` T \\<subseteq> S\" \"\\<And>x. x \\<in> S \\<Longrightarrow> g(f x) = x\" \"\\<And>y. y \\<in> T \\<Longrightarrow> f(g y) = y\"\n    shows \"homeomorphism S T f g\"\n  using assms by (force simp: homeomorphism_def)\n\nlemma homeomorphism_translation:\n  fixes a :: \"'a :: real_normed_vector\"\n  shows \"homeomorphism ((+) a ` S) S ((+) (- a)) ((+) a)\"\nunfolding homeomorphism_def by (auto simp: algebra_simps continuous_intros)\n\nlemma homeomorphism_ident: \"homeomorphism T T (\\<lambda>a. a) (\\<lambda>a. a)\"\n  by (rule homeomorphismI) auto\n\nlemma homeomorphism_compose:\n  assumes \"homeomorphism S T f g\" \"homeomorphism T U h k\"\n    shows \"homeomorphism S U (h o f) (g o k)\"\n  using assms\n  unfolding homeomorphism_def\n  by (intro conjI ballI continuous_on_compose) (auto simp: image_iff)\n\nlemma homeomorphism_cong:\n  \"homeomorphism X' Y' f' g'\"\n    if \"homeomorphism X Y f g\" \"X' = X\" \"Y' = Y\" \"\\<And>x. x \\<in> X \\<Longrightarrow> f' x = f x\" \"\\<And>y. y \\<in> Y \\<Longrightarrow> g' y = g y\"\n  using that by (auto simp add: homeomorphism_def)\n\nlemma homeomorphism_empty [simp]:\n  \"homeomorphism {} {} f g\"\n  unfolding homeomorphism_def by auto\n\nlemma homeomorphism_symD: \"homeomorphism S t f g \\<Longrightarrow> homeomorphism t S g f\"\n  by (simp add: homeomorphism_def)\n\nlemma homeomorphism_sym: \"homeomorphism S t f g = homeomorphism t S g f\"\n  by (force simp: homeomorphism_def)\n\nlemma continuous_on_translation_eq:\n  fixes g :: \"'a :: real_normed_vector \\<Rightarrow> 'b :: real_normed_vector\"\n  shows \"continuous_on A ((+) a \\<circ> g) = continuous_on A g\"\nproof -\n  have g: \"g = (\\<lambda>x. -a + x) \\<circ> ((\\<lambda>x. a + x) \\<circ> g)\"\n    by (rule ext) simp\n  show ?thesis\n    by (metis (no_types, opaque_lifting) g continuous_on_compose homeomorphism_def homeomorphism_translation)\nqed\n\ndefinition\\<^marker>\\<open>tag important\\<close> homeomorphic :: \"'a::topological_space set \\<Rightarrow> 'b::topological_space set \\<Rightarrow> bool\"\n    (infixr \"homeomorphic\" 60)\n  where \"s homeomorphic t \\<equiv> (\\<exists>f g. homeomorphism s t f g)\"\n\nlemma homeomorphic_empty [iff]:\n     \"S homeomorphic {} \\<longleftrightarrow> S = {}\" \"{} homeomorphic S \\<longleftrightarrow> S = {}\"\n  by (auto simp: homeomorphic_def homeomorphism_def)\n\nlemma homeomorphic_refl: \"s homeomorphic s\"\n  unfolding homeomorphic_def homeomorphism_def\n  using continuous_on_id\n  apply (rule_tac x = \"(\\<lambda>x. x)\" in exI)\n  apply (rule_tac x = \"(\\<lambda>x. x)\" in exI)\n  apply blast\n  done\n\nlemma homeomorphic_sym: \"s homeomorphic t \\<longleftrightarrow> t homeomorphic s\"\n  unfolding homeomorphic_def homeomorphism_def\n  by blast\n\nlemma homeomorphic_trans [trans]:\n  assumes \"S homeomorphic T\"\n      and \"T homeomorphic U\"\n    shows \"S homeomorphic U\"\n  using assms\n  unfolding homeomorphic_def\nby (metis homeomorphism_compose)\n\nlemma homeomorphic_minimal:\n  \"s homeomorphic t \\<longleftrightarrow>\n    (\\<exists>f g. (\\<forall>x\\<in>s. f(x) \\<in> t \\<and> (g(f(x)) = x)) \\<and>\n           (\\<forall>y\\<in>t. g(y) \\<in> s \\<and> (f(g(y)) = y)) \\<and>\n           continuous_on s f \\<and> continuous_on t g)\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (fastforce simp: homeomorphic_def homeomorphism_def)\nnext\n  assume ?rhs\n  then show ?lhs\n    apply clarify\n    unfolding homeomorphic_def homeomorphism_def\n    by (metis equalityI image_subset_iff subsetI)\n qed\n\nlemma homeomorphicI [intro?]:\n   \"\\<lbrakk>f ` S = T; g ` T = S;\n     continuous_on S f; continuous_on T g;\n     \\<And>x. x \\<in> S \\<Longrightarrow> g(f(x)) = x;\n     \\<And>y. y \\<in> T \\<Longrightarrow> f(g(y)) = y\\<rbrakk> \\<Longrightarrow> S homeomorphic T\"\nunfolding homeomorphic_def homeomorphism_def by metis\n\nlemma homeomorphism_of_subsets:\n   \"\\<lbrakk>homeomorphism S T f g; S' \\<subseteq> S; T'' \\<subseteq> T; f ` S' = T'\\<rbrakk>\n    \\<Longrightarrow> homeomorphism S' T' f g\"\napply (auto simp: homeomorphism_def elim!: continuous_on_subset)\nby (metis subsetD imageI)\n\nlemma homeomorphism_apply1: \"\\<lbrakk>homeomorphism S T f g; x \\<in> S\\<rbrakk> \\<Longrightarrow> g(f x) = x\"\n  by (simp add: homeomorphism_def)\n\nlemma homeomorphism_apply2: \"\\<lbrakk>homeomorphism S T f g; x \\<in> T\\<rbrakk> \\<Longrightarrow> f(g x) = x\"\n  by (simp add: homeomorphism_def)\n\nlemma homeomorphism_image1: \"homeomorphism S T f g \\<Longrightarrow> f ` S = T\"\n  by (simp add: homeomorphism_def)\n\nlemma homeomorphism_image2: \"homeomorphism S T f g \\<Longrightarrow> g ` T = S\"\n  by (simp add: homeomorphism_def)\n\nlemma homeomorphism_cont1: \"homeomorphism S T f g \\<Longrightarrow> continuous_on S f\"\n  by (simp add: homeomorphism_def)\n\nlemma homeomorphism_cont2: \"homeomorphism S T f g \\<Longrightarrow> continuous_on T g\"\n  by (simp add: homeomorphism_def)\n\nlemma continuous_on_no_limpt:\n   \"(\\<And>x. \\<not> x islimpt S) \\<Longrightarrow> continuous_on S f\"\n  unfolding continuous_on_def\n  by (metis UNIV_I empty_iff eventually_at_topological islimptE open_UNIV tendsto_def trivial_limit_within)\n\nlemma continuous_on_finite:\n  fixes S :: \"'a::t1_space set\"\n  shows \"finite S \\<Longrightarrow> continuous_on S f\"\nby (metis continuous_on_no_limpt islimpt_finite)\n\nlemma homeomorphic_finite:\n  fixes S :: \"'a::t1_space set\" and T :: \"'b::t1_space set\"\n  assumes \"finite T\"\n  shows \"S homeomorphic T \\<longleftrightarrow> finite S \\<and> finite T \\<and> card S = card T\" (is \"?lhs = ?rhs\")\nproof\n  assume \"S homeomorphic T\"\n  with assms show ?rhs\n    apply (auto simp: homeomorphic_def homeomorphism_def)\n     apply (metis finite_imageI)\n    by (metis card_image_le finite_imageI le_antisym)\nnext\n  assume R: ?rhs\n  with finite_same_card_bij obtain h where \"bij_betw h S T\"\n    by auto\n  with R show ?lhs\n    apply (auto simp: homeomorphic_def homeomorphism_def continuous_on_finite)\n    apply (rule_tac x=h in exI)\n    apply (rule_tac x=\"inv_into S h\" in exI)\n    apply (auto simp:  bij_betw_inv_into_left bij_betw_inv_into_right bij_betw_imp_surj_on inv_into_into bij_betwE)\n    apply (metis bij_betw_def bij_betw_inv_into)\n    done\nqed\n\ntext \\<open>Relatively weak hypotheses if a set is compact.\\<close>\n\nlemma homeomorphism_compact:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  assumes \"compact s\" \"continuous_on s f\"  \"f ` s = t\"  \"inj_on f s\"\n  shows \"\\<exists>g. homeomorphism s t f g\"\nproof -\n  define g where \"g x = (SOME y. y\\<in>s \\<and> f y = x)\" for x\n  have g: \"\\<forall>x\\<in>s. g (f x) = x\"\n    using assms(3) assms(4)[unfolded inj_on_def] unfolding g_def by auto\n  {\n    fix y\n    assume \"y \\<in> t\"\n    then obtain x where x:\"f x = y\" \"x\\<in>s\"\n      using assms(3) by auto\n    then have \"g (f x) = x\" using g by auto\n    then have \"f (g y) = y\" unfolding x(1)[symmetric] by auto\n  }\n  then have g':\"\\<forall>x\\<in>t. f (g x) = x\" by auto\n  moreover\n  {\n    fix x\n    have \"x\\<in>s \\<Longrightarrow> x \\<in> g ` t\"\n      using g[THEN bspec[where x=x]]\n      unfolding image_iff\n      using assms(3)\n      by (auto intro!: bexI[where x=\"f x\"])\n    moreover\n    {\n      assume \"x\\<in>g ` t\"\n      then obtain y where y:\"y\\<in>t\" \"g y = x\" by auto\n      then obtain x' where x':\"x'\\<in>s\" \"f x' = y\"\n        using assms(3) by auto\n      then have \"x \\<in> s\"\n        unfolding g_def\n        using someI2[of \"\\<lambda>b. b\\<in>s \\<and> f b = y\" x' \"\\<lambda>x. x\\<in>s\"]\n        unfolding y(2)[symmetric] and g_def\n        by auto\n    }\n    ultimately have \"x\\<in>s \\<longleftrightarrow> x \\<in> g ` t\" ..\n  }\n  then have \"g ` t = s\" by auto\n  ultimately show ?thesis\n    unfolding homeomorphism_def homeomorphic_def\n    using assms continuous_on_inv by fastforce\nqed\n\nlemma homeomorphic_compact:\n  fixes f :: \"'a::topological_space \\<Rightarrow> 'b::t2_space\"\n  shows \"compact s \\<Longrightarrow> continuous_on s f \\<Longrightarrow> (f ` s = t) \\<Longrightarrow> inj_on f s \\<Longrightarrow> s homeomorphic t\"\n  unfolding homeomorphic_def by (metis homeomorphism_compact)\n\ntext\\<open>Preservation of topological properties.\\<close>\n\nlemma homeomorphic_compactness: \"s homeomorphic t \\<Longrightarrow> (compact s \\<longleftrightarrow> compact t)\"\n  unfolding homeomorphic_def homeomorphism_def\n  by (metis compact_continuous_image)\n\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>On Linorder Topologies\\<close>\n\nlemma islimpt_greaterThanLessThan1:\n  fixes a b::\"'a::{linorder_topology, dense_order}\"\n  assumes \"a < b\"\n  shows  \"a islimpt {a<..<b}\"\nproof (rule islimptI)\n  fix T\n  assume \"open T\" \"a \\<in> T\"\n  from open_right[OF this \\<open>a < b\\<close>]\n  obtain c where c: \"a < c\" \"{a..<c} \\<subseteq> T\" by auto\n  with assms dense[of a \"min c b\"]\n  show \"\\<exists>y\\<in>{a<..<b}. y \\<in> T \\<and> y \\<noteq> a\"\n    by (metis atLeastLessThan_iff greaterThanLessThan_iff min_less_iff_conj\n      not_le order.strict_implies_order subset_eq)\nqed\n\nlemma islimpt_greaterThanLessThan2:\n  fixes a b::\"'a::{linorder_topology, dense_order}\"\n  assumes \"a < b\"\n  shows  \"b islimpt {a<..<b}\"\nproof (rule islimptI)\n  fix T\n  assume \"open T\" \"b \\<in> T\"\n  from open_left[OF this \\<open>a < b\\<close>]\n  obtain c where c: \"c < b\" \"{c<..b} \\<subseteq> T\" by auto\n  with assms dense[of \"max a c\" b]\n  show \"\\<exists>y\\<in>{a<..<b}. y \\<in> T \\<and> y \\<noteq> b\"\n    by (metis greaterThanAtMost_iff greaterThanLessThan_iff max_less_iff_conj\n      not_le order.strict_implies_order subset_eq)\nqed\n\nlemma closure_greaterThanLessThan[simp]:\n  fixes a b::\"'a::{linorder_topology, dense_order}\"\n  shows \"a < b \\<Longrightarrow> closure {a <..< b} = {a .. b}\" (is \"_ \\<Longrightarrow> ?l = ?r\")\nproof\n  have \"?l \\<subseteq> closure ?r\"\n    by (rule closure_mono) auto\n  thus \"closure {a<..<b} \\<subseteq> {a..b}\" by simp\nqed (auto simp: closure_def order.order_iff_strict islimpt_greaterThanLessThan1\n  islimpt_greaterThanLessThan2)\n\nlemma closure_greaterThan[simp]:\n  fixes a b::\"'a::{no_top, linorder_topology, dense_order}\"\n  shows \"closure {a<..} = {a..}\"\nproof -\n  from gt_ex obtain b where \"a < b\" by auto\n  hence \"{a<..} = {a<..<b} \\<union> {b..}\" by auto\n  also have \"closure \\<dots> = {a..}\" using \\<open>a < b\\<close> unfolding closure_Un\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closure_lessThan[simp]:\n  fixes b::\"'a::{no_bot, linorder_topology, dense_order}\"\n  shows \"closure {..<b} = {..b}\"\nproof -\n  from lt_ex obtain a where \"a < b\" by auto\n  hence \"{..<b} = {a<..<b} \\<union> {..a}\" by auto\n  also have \"closure \\<dots> = {..b}\" using \\<open>a < b\\<close> unfolding closure_Un\n    by auto\n  finally show ?thesis .\nqed\n\nlemma closure_atLeastLessThan[simp]:\n  fixes a b::\"'a::{linorder_topology, dense_order}\"\n  assumes \"a < b\"\n  shows \"closure {a ..< b} = {a .. b}\"\nproof -\n  from assms have \"{a ..< b} = {a} \\<union> {a <..< b}\" by auto\n  also have \"closure \\<dots> = {a .. b}\" unfolding closure_Un\n    by (auto simp: assms less_imp_le)\n  finally show ?thesis .\nqed\n\nlemma closure_greaterThanAtMost[simp]:\n  fixes a b::\"'a::{linorder_topology, dense_order}\"\n  assumes \"a < b\"\n  shows \"closure {a <.. b} = {a .. b}\"\nproof -\n  from assms have \"{a <.. b} = {b} \\<union> {a <..< b}\" by auto\n  also have \"closure \\<dots> = {a .. b}\" unfolding closure_Un\n    by (auto simp: assms less_imp_le)\n  finally show ?thesis .\nqed\n\nend", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/Elementary_Topology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.874077222043951, "lm_q1q2_score": 0.754670927692128}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_bin_plus\nimports \"../../Test_Base\"\nbegin\n\ndatatype Bin = One | ZeroAnd \"Bin\" | OneAnd \"Bin\"\n\nfun toNat :: \"Bin => int\" where\n\"toNat (One) = 1\"\n| \"toNat (ZeroAnd xs) = (toNat xs) + (toNat xs)\"\n| \"toNat (OneAnd ys) = (1 + (toNat ys)) + (toNat ys)\"\n\nfun s :: \"Bin => Bin\" where\n\"s (One) = ZeroAnd One\"\n| \"s (ZeroAnd xs) = OneAnd xs\"\n| \"s (OneAnd ys) = ZeroAnd (s ys)\"\n\nfun plus :: \"Bin => Bin => Bin\" where\n\"plus (One) y = s y\"\n| \"plus (ZeroAnd z) (One) = s (ZeroAnd z)\"\n| \"plus (ZeroAnd z) (ZeroAnd ys) = ZeroAnd (plus z ys)\"\n| \"plus (ZeroAnd z) (OneAnd xs) = OneAnd (plus z xs)\"\n| \"plus (OneAnd x2) (One) = s (OneAnd x2)\"\n| \"plus (OneAnd x2) (ZeroAnd zs) = OneAnd (plus x2 zs)\"\n| \"plus (OneAnd x2) (OneAnd ys2) = ZeroAnd (s (plus x2 ys2))\"\n\ntheorem property0 :\n  \"((toNat (plus x y)) = ((toNat x) + (toNat y)))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_bin_plus.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391643039739, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.7546532592106268}}
{"text": "theory Ex024 \n  imports Main \nbegin \n  \n\n  \n  \nlemma \"(A \\<longleftrightarrow> B) \\<longleftrightarrow> (\\<not>A \\<longleftrightarrow> \\<not>B)\"\nproof -\n  {\n    assume a:\"A \\<longleftrightarrow> B\"\n    hence b:\"A \\<longrightarrow> B\" by (rule iffE)\n    from a have c:\"B \\<longrightarrow> A\" by (rule iffE)\n    {\n      assume d:\"\\<not>A\"\n      {\n        assume B\n        with c have A by (rule mp)\n        with d have False by contradiction\n      }\n      hence \"\\<not>B\" by (rule notI)\n    }\n    moreover\n    {\n      assume e:\"\\<not>B\"\n      {\n        assume A\n        with b have B by (rule mp)\n        with e have False by contradiction\n      }\n      hence \"\\<not>A\" by (rule notI)\n    }\n    ultimately have \"\\<not>A \\<longleftrightarrow> \\<not>B\" by (rule iffI)\n  }\n  moreover\n  {\n    assume f:\"\\<not>A \\<longleftrightarrow> \\<not>B\"\n    hence g:\"\\<not>A \\<longrightarrow> \\<not>B\" by (rule iffE)\n    from f have h:\"\\<not>B \\<longrightarrow> \\<not>A\" by (rule iffE)\n    {\n      assume i:A \n      {\n        assume \"\\<not>B\"\n        with h have \"\\<not>A\" by (rule mp)\n        with i have False by contradiction\n      }\n      hence \"\\<not>\\<not>B\" by (rule notI)\n      hence B by (rule notnotD)\n    }\n    moreover\n    {\n      assume j:B\n      {\n        assume \"\\<not>A\"\n        with g have \"\\<not>B\" by (rule mp)\n        with j have False by contradiction\n      }\n      hence \"\\<not>\\<not>A\" by (rule notI)\n      hence A by (rule notnotD)\n    }\n    ultimately have \"A \\<longleftrightarrow> B\" by (rule iffI)\n  }\n  ultimately show ?thesis by (rule iffI)\nqed\n  \n          \n     \n          ", "meta": {"author": "SvenWille", "repo": "LogicForwardProofs", "sha": "b03c110b073eb7c34a561fce94b860b14cde75f7", "save_path": "github-repos/isabelle/SvenWille-LogicForwardProofs", "path": "github-repos/isabelle/SvenWille-LogicForwardProofs/LogicForwardProofs-b03c110b073eb7c34a561fce94b860b14cde75f7/src/propLogic/Ex024.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.8175744695262775, "lm_q1q2_score": 0.7546532499151553}}
{"text": "(*  Title:      HOL/ex/HarmonicSeries.thy\n    Author:     Benjamin Porter, 2006\n*)\n\nsection \\<open>Divergence of the Harmonic Series\\<close>\n\ntheory HarmonicSeries\nimports Complex_Main\nbegin\n\nsubsection \\<open>Abstract\\<close>\n\ntext \\<open>The following document presents a proof of the Divergence of\nHarmonic Series theorem formalised in the Isabelle/Isar theorem\nproving system.\n\n{\\em Theorem:} The series $\\sum_{n=1}^{\\infty} \\frac{1}{n}$ does not\nconverge to any number.\n\n{\\em Informal Proof:}\n  The informal proof is based on the following auxillary lemmas:\n  \\begin{itemize}\n  \\item{aux: $\\sum_{n=2^m-1}^{2^m} \\frac{1}{n} \\geq \\frac{1}{2}$}\n  \\item{aux2: $\\sum_{n=1}^{2^M} \\frac{1}{n} = 1 + \\sum_{m=1}^{M} \\sum_{n=2^m-1}^{2^m} \\frac{1}{n}$}\n  \\end{itemize}\n\n  From {\\em aux} and {\\em aux2} we can deduce that $\\sum_{n=1}^{2^M}\n  \\frac{1}{n} \\geq 1 + \\frac{M}{2}$ for all $M$.\n  Now for contradiction, assume that $\\sum_{n=1}^{\\infty} \\frac{1}{n}\n  = s$ for some $s$. Because $\\forall n. \\frac{1}{n} > 0$ all the\n  partial sums in the series must be less than $s$. However with our\n  deduction above we can choose $N > 2*s - 2$ and thus\n  $\\sum_{n=1}^{2^N} \\frac{1}{n} > s$. This leads to a contradiction\n  and hence $\\sum_{n=1}^{\\infty} \\frac{1}{n}$ is not summable.\n  QED.\n\\<close>\n\nsubsection \\<open>Formal Proof\\<close>\n\nlemma two_pow_sub:\n  \"0 < m \\<Longrightarrow> (2::nat)^m - 2^(m - 1) = 2^(m - 1)\"\n  by (induct m) auto\n\ntext \\<open>We first prove the following auxillary lemma. This lemma\nsimply states that the finite sums: $\\frac{1}{2}$, $\\frac{1}{3} +\n\\frac{1}{4}$, $\\frac{1}{5} + \\frac{1}{6} + \\frac{1}{7} + \\frac{1}{8}$\netc. are all greater than or equal to $\\frac{1}{2}$. We do this by\nobserving that each term in the sum is greater than or equal to the\nlast term, e.g. $\\frac{1}{3} > \\frac{1}{4}$ and thus $\\frac{1}{3} +\n\\frac{1}{4} > \\frac{1}{4} + \\frac{1}{4} = \\frac{1}{2}$.\\<close>\n\nlemma harmonic_aux:\n  \"\\<forall>m>0. (\\<Sum>n\\<in>{(2::nat)^(m - 1)+1..2^m}. 1/real n) \\<ge> 1/2\"\n  (is \"\\<forall>m>0. (\\<Sum>n\\<in>(?S m). 1/real n) \\<ge> 1/2\")\nproof\n  fix m::nat\n  obtain tm where tmdef: \"tm = (2::nat)^m\" by simp\n  {\n    assume mgt0: \"0 < m\"\n    have \"\\<And>x. x\\<in>(?S m) \\<Longrightarrow> 1/(real x) \\<ge> 1/(real tm)\"\n    proof -\n      fix x::nat\n      assume xs: \"x\\<in>(?S m)\"\n      have xgt0: \"x>0\"\n      proof -\n        from xs have\n          \"x \\<ge> 2^(m - 1) + 1\" by auto\n        moreover from mgt0 have\n          \"2^(m - 1) + 1 \\<ge> (1::nat)\" by auto\n        ultimately have\n          \"x \\<ge> 1\" by (rule xtrans)\n        thus ?thesis by simp\n      qed\n      moreover from xs have \"x \\<le> 2^m\" by auto\n      ultimately have \"inverse (real x) \\<ge> inverse (real ((2::nat)^m))\" by simp\n      moreover\n      from xgt0 have \"real x \\<noteq> 0\" by simp\n      then have\n        \"inverse (real x) = 1 / (real x)\"\n        by (rule nonzero_inverse_eq_divide)\n      moreover from mgt0 have \"real tm \\<noteq> 0\" by (simp add: tmdef)\n      then have\n        \"inverse (real tm) = 1 / (real tm)\"\n        by (rule nonzero_inverse_eq_divide)\n      ultimately show\n        \"1/(real x) \\<ge> 1/(real tm)\" by (auto simp add: tmdef)\n    qed\n    then have\n      \"(\\<Sum>n\\<in>(?S m). 1 / real n) \\<ge> (\\<Sum>n\\<in>(?S m). 1/(real tm))\"\n      by (rule sum_mono)\n    moreover have\n      \"(\\<Sum>n\\<in>(?S m). 1/(real tm)) = 1/2\"\n    proof -\n      have\n        \"(\\<Sum>n\\<in>(?S m). 1/(real tm)) =\n         (1/(real tm))*(\\<Sum>n\\<in>(?S m). 1)\"\n        by simp\n      also have\n        \"\\<dots> = ((1/(real tm)) * real (card (?S m)))\"\n        by (simp add: real_of_card)\n      also have\n        \"\\<dots> = ((1/(real tm)) * real (tm - (2^(m - 1))))\"\n        by (simp add: tmdef)\n      also from mgt0 have\n        \"\\<dots> = ((1/(real tm)) * real ((2::nat)^(m - 1)))\"\n        by (auto simp: tmdef dest: two_pow_sub)\n      also have\n        \"\\<dots> = (real (2::nat))^(m - 1) / (real (2::nat))^m\"\n        by (simp add: tmdef)\n      also from mgt0 have\n        \"\\<dots> = (real (2::nat))^(m - 1) / (real (2::nat))^((m - 1) + 1)\"\n        by auto\n      also have \"\\<dots> = 1/2\" by simp\n      finally show ?thesis .\n    qed\n    ultimately have\n      \"(\\<Sum>n\\<in>(?S m). 1 / real n) \\<ge> 1/2\"\n      by - (erule subst)\n  }\n  thus \"0 < m \\<longrightarrow> 1 / 2 \\<le> (\\<Sum>n\\<in>(?S m). 1 / real n)\" by simp\nqed\n\ntext \\<open>We then show that the sum of a finite number of terms from the\nharmonic series can be regrouped in increasing powers of 2. For\nexample: $1 + \\frac{1}{2} + \\frac{1}{3} + \\frac{1}{4} + \\frac{1}{5} +\n\\frac{1}{6} + \\frac{1}{7} + \\frac{1}{8} = 1 + (\\frac{1}{2}) +\n(\\frac{1}{3} + \\frac{1}{4}) + (\\frac{1}{5} + \\frac{1}{6} + \\frac{1}{7}\n+ \\frac{1}{8})$.\\<close>\n\nlemma harmonic_aux2 [rule_format]:\n  \"0<M \\<Longrightarrow> (\\<Sum>n\\<in>{1..(2::nat)^M}. 1/real n) =\n   (1 + (\\<Sum>m\\<in>{1..M}. \\<Sum>n\\<in>{(2::nat)^(m - 1)+1..2^m}. 1/real n))\"\n  (is \"0<M \\<Longrightarrow> ?LHS M = ?RHS M\")\nproof (induct M)\n  case 0 show ?case by simp\nnext\n  case (Suc M)\n  have ant: \"0 < Suc M\" by fact\n  {\n    have suc: \"?LHS (Suc M) = ?RHS (Suc M)\"\n    proof cases \\<comment> \\<open>show that LHS = c and RHS = c, and thus LHS = RHS\\<close>\n      assume mz: \"M=0\"\n      {\n        then have\n          \"?LHS (Suc M) = ?LHS 1\" by simp\n        also have\n          \"\\<dots> = (\\<Sum>n\\<in>{(1::nat)..2}. 1/real n)\" by simp\n        also have\n          \"\\<dots> = ((\\<Sum>n\\<in>{Suc 1..2}. 1/real n) + 1/(real (1::nat)))\"\n          by (subst sum.head)\n             (auto simp: atLeastSucAtMost_greaterThanAtMost)\n        also have\n          \"\\<dots> = ((\\<Sum>n\\<in>{2..2::nat}. 1/real n) + 1/(real (1::nat)))\"\n          by (simp add: eval_nat_numeral)\n        also have\n          \"\\<dots> =  1/(real (2::nat)) + 1/(real (1::nat))\" by simp\n        finally have\n          \"?LHS (Suc M) = 1/2 + 1\" by simp\n      }\n      moreover\n      {\n        from mz have\n          \"?RHS (Suc M) = ?RHS 1\" by simp\n        also have\n          \"\\<dots> = (\\<Sum>n\\<in>{((2::nat)^0)+1..2^1}. 1/real n) + 1\"\n          by simp\n        also have\n          \"\\<dots> = (\\<Sum>n\\<in>{2::nat..2}. 1/real n) + 1\"\n          by (auto simp: atLeastAtMost_singleton')\n        also have\n          \"\\<dots> = 1/2 + 1\"\n          by simp\n        finally have\n          \"?RHS (Suc M) = 1/2 + 1\" by simp\n      }\n      ultimately show \"?LHS (Suc M) = ?RHS (Suc M)\" by simp\n    next\n      assume mnz: \"M\\<noteq>0\"\n      then have mgtz: \"M>0\" by simp\n      with Suc have suc:\n        \"(?LHS M) = (?RHS M)\" by blast\n      have\n        \"(?LHS (Suc M)) =\n         ((?LHS M) + (\\<Sum>n\\<in>{(2::nat)^M+1..2^(Suc M)}. 1 / real n))\"\n      proof -\n        have\n          \"{1..(2::nat)^(Suc M)} =\n           {1..(2::nat)^M}\\<union>{(2::nat)^M+1..(2::nat)^(Suc M)}\"\n          by auto\n        moreover have\n          \"{1..(2::nat)^M}\\<inter>{(2::nat)^M+1..(2::nat)^(Suc M)} = {}\"\n          by auto\n        moreover have\n          \"finite {1..(2::nat)^M}\" and \"finite {(2::nat)^M+1..(2::nat)^(Suc M)}\"\n          by auto\n        ultimately show ?thesis\n          by (auto intro: sum.union_disjoint)\n      qed\n      moreover\n      {\n        have\n          \"(?RHS (Suc M)) =\n           (1 + (\\<Sum>m\\<in>{1..M}.  \\<Sum>n\\<in>{(2::nat)^(m - 1)+1..2^m}. 1/real n) +\n           (\\<Sum>n\\<in>{(2::nat)^(Suc M - 1)+1..2^(Suc M)}. 1/real n))\" by simp\n        also have\n          \"\\<dots> = (?RHS M) + (\\<Sum>n\\<in>{(2::nat)^M+1..2^(Suc M)}. 1/real n)\"\n          by simp\n        also from suc have\n          \"\\<dots> = (?LHS M) +  (\\<Sum>n\\<in>{(2::nat)^M+1..2^(Suc M)}. 1/real n)\"\n          by simp\n        finally have\n          \"(?RHS (Suc M)) = \\<dots>\" by simp\n      }\n      ultimately show \"?LHS (Suc M) = ?RHS (Suc M)\" by simp\n    qed\n  }\n  thus ?case by simp\nqed\n\ntext \\<open>Using @{thm [source] harmonic_aux} and @{thm [source] harmonic_aux2} we now show\nthat each group sum is greater than or equal to $\\frac{1}{2}$ and thus\nthe finite sum is bounded below by a value proportional to the number\nof elements we choose.\\<close>\n\nlemma harmonic_aux3 [rule_format]:\n  shows \"\\<forall>(M::nat). (\\<Sum>n\\<in>{1..(2::nat)^M}. 1 / real n) \\<ge> 1 + (real M)/2\"\n  (is \"\\<forall>M. ?P M \\<ge> _\")\nproof (rule allI, cases)\n  fix M::nat\n  assume \"M=0\"\n  then show \"?P M \\<ge> 1 + (real M)/2\" by simp\nnext\n  fix M::nat\n  assume \"M\\<noteq>0\"\n  then have \"M > 0\" by simp\n  then have\n    \"(?P M) =\n     (1 + (\\<Sum>m\\<in>{1..M}. \\<Sum>n\\<in>{(2::nat)^(m - 1)+1..2^m}. 1/real n))\"\n    by (rule harmonic_aux2)\n  also have\n    \"\\<dots> \\<ge> (1 + (\\<Sum>m\\<in>{1..M}. 1/2))\"\n  proof -\n    let ?f = \"(\\<lambda>x. 1/2)\"\n    let ?g = \"(\\<lambda>x. (\\<Sum>n\\<in>{(2::nat)^(x - 1)+1..2^x}. 1/real n))\"\n    from harmonic_aux have \"\\<And>x. x\\<in>{1..M} \\<Longrightarrow> ?f x \\<le> ?g x\" by simp\n    then have \"(\\<Sum>m\\<in>{1..M}. ?g m) \\<ge> (\\<Sum>m\\<in>{1..M}. ?f m)\" by (rule sum_mono)\n    thus ?thesis by simp\n  qed\n  finally have \"(?P M) \\<ge> (1 + (\\<Sum>m\\<in>{1..M}. 1/2))\" .\n  moreover\n  {\n    have\n      \"(\\<Sum>m\\<in>{1..M}. (1::real)/2) = 1/2 * (\\<Sum>m\\<in>{1..M}. 1)\"\n      by auto\n    also have\n      \"\\<dots> = 1/2*(real (card {1..M}))\"\n      by (simp only: real_of_card[symmetric])\n    also have\n      \"\\<dots> = 1/2*(real M)\" by simp\n    also have\n      \"\\<dots> = (real M)/2\" by simp\n    finally have \"(\\<Sum>m\\<in>{1..M}. (1::real)/2) = (real M)/2\" .\n  }\n  ultimately show \"(?P M) \\<ge> (1 + (real M)/2)\" by simp\nqed\n\ntext \\<open>The final theorem shows that as we take more and more elements\n(see @{thm [source] harmonic_aux3}) we get an ever increasing sum. By assuming\nthe sum converges, the lemma @{thm [source] sum_less_suminf} ( @{thm\nsum_less_suminf} ) states that each sum is bounded above by the\nseries' limit. This contradicts our first statement and thus we prove\nthat the harmonic series is divergent.\\<close>\n\ntheorem DivergenceOfHarmonicSeries:\n  shows \"\\<not>summable (\\<lambda>n. 1/real (Suc n))\"\n  (is \"\\<not>summable ?f\")\nproof \\<comment> \\<open>by contradiction\\<close>\n  let ?s = \"suminf ?f\" \\<comment> \\<open>let ?s equal the sum of the harmonic series\\<close>\n  assume sf: \"summable ?f\"\n  then obtain n::nat where ndef: \"n = nat \\<lceil>2 * ?s\\<rceil>\" by simp\n  then have ngt: \"1 + real n/2 > ?s\" by linarith\n  define j where \"j = (2::nat)^n\"\n  have \"(\\<Sum>i<j. ?f i) < ?s\" \n    using sf by (simp add: sum_less_suminf)\n  then have \"(\\<Sum>i\\<in>{Suc 0..<Suc j}. 1/(real i)) < ?s\"\n    unfolding sum.shift_bounds_Suc_ivl by (simp add: atLeast0LessThan)\n  with j_def have\n    \"(\\<Sum>i\\<in>{1..< Suc ((2::nat)^n)}. 1 / (real i)) < ?s\" by simp\n  then have\n    \"(\\<Sum>i\\<in>{1..(2::nat)^n}. 1 / (real i)) < ?s\"\n    by (simp only: atLeastLessThanSuc_atLeastAtMost)\n  moreover from harmonic_aux3 have\n    \"(\\<Sum>i\\<in>{1..(2::nat)^n}. 1 / (real i)) \\<ge> 1 + real n/2\" by simp\n  moreover from ngt have \"1 + real n/2 > ?s\" by simp\n  ultimately show False by simp\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/ex/HarmonicSeries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040853, "lm_q2_score": 0.8856314753275019, "lm_q1q2_score": 0.7545162302327493}}
{"text": "theory Chap4\nimports Main Chap3_1 Chap3_3\nbegin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\"\n| \"set (Node l a r) = {a} \\<union> set l \\<union> set r\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\"\n| \"ord (Node l a r) = (ord l \\<and> ord r \\<and> (\\<forall>x\\<in>set l. x \\<le> a) \\<and> (\\<forall>x\\<in>set r. a \\<le> x))\"\n\nfun ins :: \"int \\<Rightarrow> int tree \\<Rightarrow> int tree\" where\n\"ins a Tip = Node Tip a Tip\"\n| \"ins a (Node l b r) = (\n  if a < b then Node (ins a l) b r \n  else if a = b then Node l b r \n  else Node l b (ins a r))\"\n\nlemma ins_set: \"set (ins a t) = {a} \\<union> set t\"\n  apply (induction t)\n  by auto\nlemma \"ord t \\<Longrightarrow> ord (ins a t)\"\n  apply (induction t rule: ins.induct)\n  using ins_set by auto\n\nlemma \"\\<forall>x. \\<exists>y. x = y\"\n  by auto\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\n  by auto\n\nlemma \"\\<lbrakk> \\<forall>xs \\<in> A. \\<exists>ys. xs = ys@ys; us \\<in> A \\<rbrakk> \\<Longrightarrow> \\<exists>n. length us = n+n\"\n  (* apply auto *)\n  by fastforce\n\nlemma \n  assumes a1: \"\\<forall>x y. T x y \\<or> T y x\"\n  assumes a2: \"\\<forall>x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n  assumes a3: \"\\<forall>x y. T x y \\<longrightarrow> A x y\"\n  shows \"\\<forall>x y. A x y \\<longrightarrow> T x y\"\n  apply (rule allI; rule allI)\n  apply (rule impI)\n  using a1 apply (erule_tac x=x in allE)\n  apply (erule_tac x=y in allE)\n  apply (erule disjE)\n   apply assumption\n  using a3 apply (erule_tac x=y in allE)\n  apply (erule_tac x=x in allE)\n  apply (erule impE)\n   apply assumption\n  using a2 apply (erule_tac x=x in allE)\n  apply (erule_tac x=y in allE)\n  apply (erule impE)\n   apply (rule conjI)\n    apply assumption+\n  apply (rule_tac a=x and b=y in forw_subst)\n   apply assumption\n  apply (drule_tac a=x and b=y in back_subst)\n   apply assumption\n  apply (drule_tac P=\"T y\" and s=x in subst)\n  by assumption+\n\nlemma \n  assumes a1: \"\\<forall>x y. T x y \\<or> T y x\"\n  assumes a2: \"\\<forall>x y. A x y \\<and> A y x \\<longrightarrow> x = y\"\n  assumes a3: \"\\<forall>x y. T x y \\<longrightarrow> A x y\"\n  shows \"\\<forall>x y. A x y \\<longrightarrow> T x y\"\n  using a1 a2 a3 \n  (* apply simp *)\n  (* apply auto *)\n  (* by fastforce *)\n  by blast\n\nlemma \"\\<lbrakk> xs @ ys = ys @ xs; length xs = length ys \\<rbrakk> \\<Longrightarrow> xs = ys\"\n  (* using append_eq_conv_conj *)\n  (* apply simp *)\n  (* apply auto *)\n  (* apply fastforce *)\n  (* apply blast *)\n  text \\<open>using sledgehammer\\<close>\n  (* using append_eq_append_conv by blast *)\n  by (metis append_eq_conv_conj)\n\nthm conjI[of \"a=b\" \"False\"]\nthm conjI[of _ \"False\"]\nthm conjI[where ?P=\"a=b\" and ?Q=\"False\"]\n\nlemma \"\\<lbrakk> (a::nat) \\<le> b; b \\<le> c; c \\<le> d; d \\<le> e \\<rbrakk> \\<Longrightarrow> a \\<le> e\"\n  by (blast intro: le_trans)\n\nthm conjI[OF refl[of \"a\"] refl[of \"b\"]]\nthm refl[of \"a\"]\nthm conjI\n\nlemma \"Suc (Suc (Suc a)) \\<le> b \\<Longrightarrow> a \\<le> b\"\n  thm Suc_leD\n  by (blast dest: Suc_leD)\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\"\n| evSS: \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\"\n| \"evn (Suc 0) = False\"\n| \"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev m \\<Longrightarrow> evn m\"\n  apply (induction rule: ev.induct)\n  by auto\n\nlemma \"ev m \\<Longrightarrow> ev (m-2)\"\n  apply (induction rule: ev.induct)\n  using ev0 apply simp\n  by simp\n\nthm evSS[OF evSS[OF ev0]]\n\nlemma \"ev (Suc (Suc (Suc (Suc 0))))\"\n  apply (rule evSS)\n  apply (rule evSS)\n  apply (rule ev0)\n  done\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply (induction n rule: evn.induct)\n  by (simp_all add: ev0 evSS)\n\ndeclare ev.intros[simp,intro]\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\"\n| step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n   apply assumption\n  by (metis step)\n\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\nempty: \"palindrome []\"\n| singleton: \"palindrome [x]\"\n| extend: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma \"palindrome xs \\<Longrightarrow> rev xs = xs\"\n  apply (induction rule: palindrome.induct)\n  by auto\n\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\"\n| step': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma f1: \"star' r y z \\<Longrightarrow> r x y \\<Longrightarrow> star' r x z\"\n  apply (induction rule: star'.induct)\n  by (auto intro: star'.intros)\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n   apply (simp add: refl')\n  using f1 by force\n\nlemma f2: \"star r x y \\<Longrightarrow> r y z \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n  by (auto intro: star.intros)\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: star'.induct)\n   apply (simp add: refl)\n  using f2 by force\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n\"iter r 0 x x\"\n| \"iter r n y z \\<Longrightarrow> r x y \\<Longrightarrow> iter r (n+1) x z\"\n\nlemma \"star r x y \\<Longrightarrow> \\<exists>n. iter r n x y\"\n  apply (induction rule: star.induct)\n  using iter.intros(1) apply force\n  apply clarsimp\n  using iter.intros(2) by force\n\ndatatype alphabet = a | b\n\ninductive S :: \"alphabet list \\<Rightarrow> bool\" where\n\"S []\"\n| \"S w \\<Longrightarrow> S (a#w@[b])\"\n| \"S v \\<Longrightarrow> S w \\<Longrightarrow> S (v@w)\"\n\ninductive T :: \"alphabet list \\<Rightarrow> bool\" where\n\"T []\"\n| \"T v \\<Longrightarrow> T w \\<Longrightarrow> T (v@[a]@w@[b])\"\n\nlemma stinduct1:\n  assumes \"\\<And>v. T v \\<Longrightarrow> T (v @ u')\"\nshows \"T u' \\<Longrightarrow> T v' \\<Longrightarrow> T w' \\<Longrightarrow> T ((w' @ u') @ [a] @ v' @ [b])\"\n  using T.intros(2) assms by presburger\n\nlemma stinduct: \"T w \\<Longrightarrow> T v \\<Longrightarrow> T (v @ w)\"\n  apply (induction w arbitrary: v rule: T.induct)\n   apply simp_all\n  using stinduct1 by auto\n\nlemma st: \"S w \\<Longrightarrow> T w\"\n  apply (induction rule: S.induct)\n  using T.intros apply force+\n  using stinduct by auto\n\nlemma ts: \"T w \\<Longrightarrow> S w\"\n  apply (induction rule: T.induct)\n  using S.intros apply force\n  by (simp add: S.intros(2) S.intros(3))\n\nlemma \"S w = T w\"\n  using st ts by auto\n\ninductive aval_rel :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n\"aval_rel (N n) s n\"\n| \"aval_rel (V v) s (s v)\"\n| \"aval_rel e1 s x1 \\<Longrightarrow> aval_rel e2 s x2 \\<Longrightarrow> aval_rel (Plus e1 e2) s (x1 + x2)\"\n\nlemma relfn1:\n\"(\\<And>x. Chap4.aval_rel e1 s x \\<Longrightarrow> aval e1 s = x) \\<Longrightarrow>\n       (\\<And>x. Chap4.aval_rel e2 s x \\<Longrightarrow> aval e2 s = x) \\<Longrightarrow>\n       Chap4.aval_rel (Plus e1 e2) s x \\<Longrightarrow> aval (Plus e1 e2) s = x\"\n  apply (cases \"Plus e1 e2\" s x rule: aval_rel.cases)\n  by auto\n\nlemma relfn: \"aval_rel e s x \\<Longrightarrow> aval e s = x\"\n  apply (induction e arbitrary: x)\n  using Chap4.aval_rel.cases apply auto[2]\n  using relfn1 by blast\n\nlemma fnrel: \"aval e s = x \\<Longrightarrow> aval_rel e s x\"\n  apply (induction e arbitrary: x)\n  using Chap4.aval_rel.intros by auto\n\nlemma \"aval e s = x \\<longleftrightarrow> aval_rel e s x\"\n  using relfn fnrel by blast\n\ninductive ok :: \"nat \\<Rightarrow> instr list \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"ok n [] n\"\n| \"ok (Suc m) is n \\<Longrightarrow> ok m (LOADI k#is) n\"\n| \"ok (Suc m) is n \\<Longrightarrow> ok m (LOAD x#is) n\"\n| \"ok (Suc m) is n \\<Longrightarrow> ok (Suc (Suc m)) (ADD#is) n\"\n\nlemma \"ok n is n' \\<Longrightarrow> length stk = n \\<Longrightarrow> length (exec is s stk) = n'\"\n  apply (induction arbitrary: stk rule: ok.induct)\n     apply simp_all\n  apply (subgoal_tac \"\\<exists>i j stk'. stk = i#j#stk'\")\n   apply force\n  by (metis Suc_length_conv)\n\nend", "meta": {"author": "1000teslas", "repo": "concrete_semantics", "sha": "690bb968718a3162b1c4ada4ef40370a4ff99c9c", "save_path": "github-repos/isabelle/1000teslas-concrete_semantics", "path": "github-repos/isabelle/1000teslas-concrete_semantics/concrete_semantics-690bb968718a3162b1c4ada4ef40370a4ff99c9c/Chap4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.8418256412990658, "lm_q1q2_score": 0.7544873822877035}}
{"text": "theory SetCombinators\n  imports SetComprehension UPair \nbegin\n\ncontext GZF begin\n\nsubsection \\<open>Intersection of a set of sets\\<close>\n\ndefinition Int :: \"'a \\<Rightarrow> 'a\" (\\<open>\\<Inter> _\\<close> [90] 90)\n  where \"\\<Inter> x \\<equiv> { b \\<in> \\<Union> x | \\<forall>y \\<in> x. b \\<in> y }\"\n\nlemma Int_typ : \"Int : SetOf Set \\<rightarrow> Set\" \n  unfolding Int_def \n  by (rule funI, rule collect_set[OF union_set], assumption)\n\nlemmas Int_set = funE[OF Int_typ]\n\nlemma Int_iff: \n  assumes \"x : SetOf Set\"\n  shows \"a \\<in> \\<Inter> x \\<longleftrightarrow> (ball x (\\<lambda>y. a \\<in> y)) \\<and> x \\<noteq> \\<emptyset> \"\nproof\n  assume \"a \\<in> \\<Inter> x\" hence \"a \\<in> \\<Union> x\" \"ball x (\\<lambda>y. a \\<in> y)\" unfolding Int_def\n    using collectE[OF funE[OF Union_typ \\<open>x : SetOf Set\\<close>]] by auto\n  thus \"ball x (\\<lambda>y. a \\<in> y) \\<and> x \\<noteq> \\<emptyset>\" using union_emp[OF assms] by auto\nnext\n  assume \"ball x (\\<lambda>y. a \\<in> y) \\<and> x \\<noteq> \\<emptyset>\" \n  hence ball:\"ball x (\\<lambda>y. a \\<in> y)\" and \"x \\<noteq> \\<emptyset>\" by simp_all\n  have \"a \\<in> \\<Union> x\"\n  proof (rule not_emptyE[OF subtypE[OF setof_set_subtyp assms] \\<open>x \\<noteq> \\<emptyset>\\<close>])\n    fix y assume \"y \\<in> x\" thus \"a \\<in> \\<Union> x\" \n      using ball unionI[OF assms] unfolding ball_def rall_def by auto\n  qed\n  thus \"a \\<in> \\<Inter> x\" unfolding Int_def using ball collectI[OF funE[OF Union_typ assms]] by auto\nqed\n\nlemma IntI : \n  assumes \"x : SetOf Set\" \n  shows \"\\<lbrakk> \\<And>y. y \\<in> x \\<Longrightarrow> a \\<in> y ; x \\<noteq> \\<emptyset> \\<rbrakk> \\<Longrightarrow> a \\<in> \\<Inter> x\"\n  using Int_iff[OF assms] by auto\n\nlemma IntD : \n  assumes \"x : SetOf Set\" \n  shows \"\\<lbrakk> a \\<in> \\<Inter> x ; y \\<in> x \\<rbrakk> \\<Longrightarrow> a \\<in> y\"\n  using Int_iff[OF assms] by auto\n\nlemma IntE : \n  assumes \"x : SetOf Set\" \n  shows \"\\<lbrakk> a \\<in> \\<Inter> x ; y \\<notin> x \\<Longrightarrow> R; a \\<in> y \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  using Int_iff[OF assms] by auto\n\nsubsection \\<open>Set difference\\<close>\n\ndefinition diff :: \"['a, 'a] \\<Rightarrow> 'a\" (infixl \\<open>-\\<close> 65) \n  where \"x - y \\<equiv> { b \\<in> x | b \\<notin> y }\"\n(*   *)\n(*Diff will return a set even if its second argument (y above) is not a set*)\nlemma diff_typ : \"diff : Set \\<rightarrow> Set \\<rightarrow> Set\" unfolding diff_def\n  by (rule funI, rule funI, use collect_set in auto)\n\nlemmas diff_set = funE[OF funE[OF diff_typ]]\n\nlemma diff_iff : \n  assumes \"x : Set\" \n    shows \"a \\<in> x - y \\<longleftrightarrow> a \\<in> x \\<and> a \\<notin> y\"\n  unfolding diff_def using collect_iff[OF assms] by simp\n\nlemma diffI : \n  assumes \"x : Set\" \n    shows \"\\<lbrakk> a \\<in> x ; a \\<notin> y \\<rbrakk> \\<Longrightarrow> a \\<in> x - y\"\n  using diff_iff[OF assms] by simp\n\nlemma diffD1 : \n  assumes \"x : Set\" \n    shows \"a \\<in> x - y \\<Longrightarrow> a \\<in> x\" \n  using diff_iff[OF assms] by simp\n\nlemma diffD2 : \n  assumes \"x : Set\" \n    shows \"a \\<in> x - y \\<Longrightarrow> a \\<notin> y\" \n  using diff_iff[OF assms] by simp\n\nlemma diffE : \n  assumes \"x : Set\" \n    shows \"\\<lbrakk> a \\<in> x - y ; \\<lbrakk> a \\<in> x ; a \\<notin> y\\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  using diff_iff[OF assms] by simp\n\nlemma diff_sub : \n  assumes \"x : Set\" \"y : Set\" \"z : Set\" \n    shows \"x \\<subseteq> y \\<Longrightarrow> x - z \\<subseteq> y - z\"\n  using subset_iff diff_iff diff_set assms by auto\n\nlemma diff_subset1 : \n  assumes \"x : Set\" \"y : Set\" \"z : Set\" \"a : Set\"\n    shows \"x \\<subseteq> y \\<Longrightarrow> a \\<subseteq> (x - z) \\<Longrightarrow> a \\<subseteq> (y - z)\"\n  using subset_iff diff_iff funE[OF funE[OF diff_typ _] _] assms by auto\n\nlemma diff_subset2 : \n  assumes \"x : Set\" \"y : Set\" \"z : Set\" \n    shows \"x \\<subseteq> (y - z) \\<Longrightarrow> x \\<subseteq> y\"\n  using subset_iff diff_iff[OF \\<open>y : Set\\<close>] diff_set assms by auto\n\nlemma diff_emp : \n  assumes \"x : Set\" \n    shows \"\\<emptyset> - x = \\<emptyset>\"\nproof -\n  have \"\\<emptyset> - x : Set\" by (rule diff_set[OF emp_set assms])\n  show ?thesis using diff_iff[OF emp_set] equals0I[OF \\<open>\\<emptyset> - x : Set\\<close>] by auto\nqed\n\n\nsubsection \\<open>Binary union and intersection\\<close>\n\ndefinition un :: \"['a,'a] \\<Rightarrow> 'a\" (infixl \\<open>\\<union>\\<close> 90) where\n  \"x \\<union> y \\<equiv> \\<Union> upair x y\"\n\nlemma upair_setof : \"x : Set \\<Longrightarrow> y : Set \\<Longrightarrow> upair x y : SetOf Set\"\nproof (rule setofI, rule upair_set)\n  fix x y assume xy: \"x : Set\" \"y : Set\"\n  thus \"x : SetMem\" \"y : SetMem\" by (simp_all only: set_setmem)\n  moreover fix b assume \"b \\<in> upair x y\"\n  ultimately show \"b : Set\" using upair_iff xy by auto\nqed\n\nlemma un_typ : \"(\\<union>) : Set \\<rightarrow> Set \\<rightarrow> Set\" unfolding un_def \n  by (rule funI, rule funI, simp only: union_set[OF upair_setof])\n\nlemmas un_set = funE[OF funE[OF un_typ]]\n\nlemma un_iff :\n  assumes \"x : Set\" \"y : Set\" \n  shows \"a \\<in> x \\<union> y \\<longleftrightarrow> (a \\<in> x \\<or> a \\<in> y)\"\n  unfolding un_def\n  by (simp add: union_iff[OF upair_setof[OF assms]],\n      use upair_iff set_setmem assms in auto)\n\nlemma unI1 : \n  assumes \"x : Set\" \"y : Set\" \n  shows\"a \\<in> x \\<Longrightarrow> a \\<in> x \\<union> y\" by (simp add: un_iff assms)\nlemma unI2 : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"b \\<in> y \\<Longrightarrow> b \\<in> x \\<union> y\" by (simp add: un_iff assms)\n\nlemma un_subset1 : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"x \\<subseteq> x \\<union> y\" \n  using subsetI unI1[OF assms] by simp\n\nlemma un_subset2 : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"y \\<subseteq> x \\<union> y\" \n  using subsetI unI2[OF assms] by simp\n                                                                               \nlemma unE : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"\\<lbrakk> a \\<in> x \\<union> y ; a \\<in> x \\<Longrightarrow> P ; a \\<in> y \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (simp add: un_iff[OF assms], blast)\n\nlemma unE' : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"\\<lbrakk> a \\<in> x \\<union> y ; a \\<in> x \\<Longrightarrow> P ; \\<lbrakk> a \\<in> y ; a \\<notin> x \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (simp add: un_iff[OF assms], blast)\n\nlemma unCI :\n  assumes \"x : Set\" \"y : Set\" \n  shows \"(a \\<notin> y \\<Longrightarrow> a \\<in> x) \\<Longrightarrow> a \\<in> x \\<union> y\"\n  by (simp add: un_iff[OF assms], blast)\n\n\nsubsection \\<open>Rules for binary intersection\\<close>\n\ndefinition inter :: \"['a,'a] \\<Rightarrow> 'a\" (infixl \\<open>\\<inter>\\<close> 90) where\n  \"x \\<inter> y \\<equiv> \\<Inter> upair x y\"\n\nlemma inter_typ : \"(\\<inter>) : Set \\<rightarrow> Set \\<rightarrow> Set\"\n  unfolding inter_def\n  by (rule funI, rule funI, rule Int_set[OF upair_setof])\n\nlemmas inter_set = funE[OF funE[OF inter_typ]]\n\nlemma inter_iff : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"a \\<in> x \\<inter> y \\<longleftrightarrow> (a \\<in> x \\<and> a \\<in> y)\"\n  unfolding inter_def \n  by (simp add: Int_iff[OF upair_setof[OF assms]], \n      use upair_iff set_setmem assms in auto)\n\nlemma interI : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"\\<lbrakk> a \\<in> x ; a \\<in> y \\<rbrakk> \\<Longrightarrow> a \\<in> x \\<inter> y\"\n  by (simp add: inter_iff[OF assms])\n\nlemma interD1 : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"a \\<in> x \\<inter> y \\<Longrightarrow> a \\<in> x\" \n  by (simp add: inter_iff assms)  \n\nlemma interD2 :\n  assumes \"x : Set\" \"y : Set\" \n  shows \"a \\<in> x \\<inter> y \\<Longrightarrow> a \\<in> y\" \n  by (simp add: inter_iff assms)\n\nlemma interE : \n  assumes \"x : Set\" \"y : Set\" \n  shows \"\\<lbrakk> a \\<in> x \\<inter> y ; \\<lbrakk> a \\<in> x ; a \\<in> y \\<rbrakk> \\<Longrightarrow> P \\<rbrakk> \\<Longrightarrow> P\"\n  by (simp add: inter_iff assms)\nend\n\nsubsection \\<open>Binders for union and intersection\\<close>\n\nsyntax\n  \"_Union\" :: \"[pttrn, 'a, 'a] \\<Rightarrow> 'a\"  (\\<open>(3\\<Union>_\\<in>_./ _)\\<close> 10)\n  \"_Inter\" :: \"[pttrn, 'a, 'a] \\<Rightarrow> 'a\"  (\\<open>(3\\<Inter>_\\<in>_./ _)\\<close> 10)\ntranslations\n  \"\\<Union>b\\<in>x. B\" == \"CONST Union {B | b \\<in> x}\"\n  \"\\<Inter>b\\<in>x. B\" == \"CONST Int {B | b \\<in> x}\"\n\nend", "meta": {"author": "ultra-group", "repo": "isabelle-gst", "sha": "e0ccdde0105eac05f3f4bbccdd58a9860e642eca", "save_path": "github-repos/isabelle/ultra-group-isabelle-gst", "path": "github-repos/isabelle/ultra-group-isabelle-gst/isabelle-gst-e0ccdde0105eac05f3f4bbccdd58a9860e642eca/src/GZF/SetCombinators.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.8459424334245617, "lm_q1q2_score": 0.7544208107975954}}
{"text": "(*\n    $Id: sol.thy,v 1.2 2004/11/23 15:14:35 webertj Exp $\n*)\n\nheader {* A Riddle: Rich Grandfather *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {*\n  First prove the following formula, which is valid in classical predicate\n  logic, informally with pen and paper.  Use case distinctions and/or proof by\n  contradiction.\n\n  {\\it  If every poor man has a rich father,\\\\\n   then there is a rich man who has a rich grandfather.}\n*}\n\ntheorem\n  \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x) \\<Longrightarrow>\n  \\<exists>x. rich (father (father x)) \\<and> rich x\" (*<*) oops (*>*)\n\ntext {*\n\\begin{tabbing}\n{\\bf Proof} \\\\\n(1)\\ \\= We first show: @{term \"\\<exists>x. rich x\"}. \\\\\nProof by contradiction. \\\\\n    \\> {\\bf Assume} \\=  @{term \"\\<not> (\\<exists>x. rich x)\"}. \\\\\n    \\>               \\> Then @{term \"\\<forall>x. \\<not> rich x\"}. \\\\\n    \\>               \\> We consider an arbitrary @{term \"y\"} with\n                          @{term \"\\<not> rich y\"}. \\\\\n    \\>               \\> Then @{term \"rich (father y)\"}. \\\\\n(2) \\> Now we show the theorem. \\\\\nProof by cases. \\\\\n    \\> {\\bf Case 1:} \\> @{term \"rich (father (father x))\"}. \\\\\n    \\>               \\> We are done. \\\\ \n    \\> {\\bf Case 2:} \\> @{term \"\\<not> rich (father (father x))\"}. \\\\  \n    \\>               \\> Then @{term \"rich (father (father (father x)))\"}. \\\\\n    \\>               \\> Also @{term \"rich (father x)\"}, \\\\\n    \\>               \\> because otherwise @{term \"rich (father (father x))\"}. \\\\\n{\\bf qed} \\\\\n\\end{tabbing}\n*}\n\ntext {*\n  Now prove the formula in Isabelle using a sequence of rule applications (i.e.\\\n  only using the methods @{term rule}, @{term erule} and @{term assumption}).\n*}\n\ntheorem\n  \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x) \\<Longrightarrow>\n  \\<exists>x. rich (father (father x)) \\<and> rich x\"\napply (rule classical)\napply (rule exI)\napply (rule conjI)\n  \n  apply (rule classical)\n  apply (rule allE) apply assumption\n  apply (erule impE) apply assumption\n  apply (erule notE) \n  apply (rule exI)\n  apply (rule conjI) apply assumption\n  apply (rule classical)\n  apply (erule allE)\n  apply (erule notE)\n  apply (erule impE) apply assumption\n  apply assumption\n\napply (rule classical)\napply (rule allE) apply assumption\napply (erule impE) apply assumption\napply (erule notE)\napply (rule exI)\napply (rule conjI) apply assumption\napply (rule classical)\napply (erule allE)\napply (erule notE)\napply (erule impE) apply assumption\napply assumption\ndone\n\ntext {*\n  Here is a proof in Isar that resembles the informal reasoning above:\n*}\n\ntheorem rich_grandfather: \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x) \\<Longrightarrow> \n  \\<exists>x. rich x \\<and> rich (father (father x))\"\nproof -\n  assume a: \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x)\"\n  txt {* (1) *} have \"\\<exists>x. rich x\"\n  proof (rule classical)\n    fix y \n    assume \"\\<not> (\\<exists>x. rich x)\"\n    then have \"\\<forall>x. \\<not> rich x\" by simp \n    then have \"\\<not> rich y\" by simp\n    with a have \"rich (father y)\" by simp\n    then show ?thesis by rule \n  qed\n  then obtain x where x: \"rich x\" by auto\n  txt {* (2) *} show ?thesis\n  proof cases\n    assume \"rich (father (father x))\"\n    with x show ?thesis by auto\n  next\n    assume b: \"\\<not> rich (father (father x))\"\n    with a have \"rich (father (father (father x)))\" by simp\n    moreover have \"rich (father x)\" \n    proof (rule classical)\n      assume \"\\<not> rich (father x)\" \n      with a have \"rich (father (father x))\" by simp\n      with b show ?thesis by contradiction \n    qed\n    ultimately show ?thesis by auto\n  qed\nqed\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/logic/grandfather/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115783, "lm_q2_score": 0.8459424431344437, "lm_q1q2_score": 0.7544208072946478}}
{"text": "(*  Title:      HOL/Library/Set_Algebras.thy\n    Author:     Jeremy Avigad\n    Author:     Kevin Donnelly\n    Author:     Florian Haftmann, TUM\n*)\n\nsection \\<open>Algebraic operations on sets\\<close>\n\ntheory Set_Algebras\n  imports MainRLT\nbegin\n\ntext \\<open>\n  This library lifts operations like addition and multiplication to sets. It\n  was designed to support asymptotic calculations. See the comments at the top\n  of \\<^file>\\<open>BigO.thy\\<close>.\n\\<close>\n\ninstantiation set :: (plus) plus\nbegin\n\ndefinition plus_set :: \"'a::plus set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where set_plus_def: \"A + B = {c. \\<exists>a\\<in>A. \\<exists>b\\<in>B. c = a + b}\"\n\ninstance ..\n\nend\n\ninstantiation set :: (times) times\nbegin\n\ndefinition times_set :: \"'a::times set \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n  where set_times_def: \"A * B = {c. \\<exists>a\\<in>A. \\<exists>b\\<in>B. c = a * b}\"\n\ninstance ..\n\nend\n\ninstantiation set :: (zero) zero\nbegin\n\ndefinition set_zero[simp]: \"(0::'a::zero set) = {0}\"\n\ninstance ..\n\nend\n\ninstantiation set :: (one) one\nbegin\n\ndefinition set_one[simp]: \"(1::'a::one set) = {1}\"\n\ninstance ..\n\nend\n\ndefinition elt_set_plus :: \"'a::plus \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (infixl \"+o\" 70)\n  where \"a +o B = {c. \\<exists>b\\<in>B. c = a + b}\"\n\ndefinition elt_set_times :: \"'a::times \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"  (infixl \"*o\" 80)\n  where \"a *o B = {c. \\<exists>b\\<in>B. c = a * b}\"\n\nabbreviation (input) elt_set_eq :: \"'a \\<Rightarrow> 'a set \\<Rightarrow> bool\"  (infix \"=o\" 50)\n  where \"x =o A \\<equiv> x \\<in> A\"\n\ninstance set :: (semigroup_add) semigroup_add\n  by standard (force simp add: set_plus_def add.assoc)\n\ninstance set :: (ab_semigroup_add) ab_semigroup_add\n  by standard (force simp add: set_plus_def add.commute)\n\ninstance set :: (monoid_add) monoid_add\n  by standard (simp_all add: set_plus_def)\n\ninstance set :: (comm_monoid_add) comm_monoid_add\n  by standard (simp_all add: set_plus_def)\n\ninstance set :: (semigroup_mult) semigroup_mult\n  by standard (force simp add: set_times_def mult.assoc)\n\ninstance set :: (ab_semigroup_mult) ab_semigroup_mult\n  by standard (force simp add: set_times_def mult.commute)\n\ninstance set :: (monoid_mult) monoid_mult\n  by standard (simp_all add: set_times_def)\n\ninstance set :: (comm_monoid_mult) comm_monoid_mult\n  by standard (simp_all add: set_times_def)\n\nlemma set_plus_intro [intro]: \"a \\<in> C \\<Longrightarrow> b \\<in> D \\<Longrightarrow> a + b \\<in> C + D\"\n  by (auto simp add: set_plus_def)\n\nlemma set_plus_elim:\n  assumes \"x \\<in> A + B\"\n  obtains a b where \"x = a + b\" and \"a \\<in> A\" and \"b \\<in> B\"\n  using assms unfolding set_plus_def by fast\n\nlemma set_plus_intro2 [intro]: \"b \\<in> C \\<Longrightarrow> a + b \\<in> a +o C\"\n  by (auto simp add: elt_set_plus_def)\n\nlemma set_plus_rearrange: \"(a +o C) + (b +o D) = (a + b) +o (C + D)\"\n  for a b :: \"'a::comm_monoid_add\"\n  apply (auto simp add: elt_set_plus_def set_plus_def ac_simps)\n   apply (rule_tac x = \"ba + bb\" in exI)\n   apply (auto simp add: ac_simps)\n  apply (rule_tac x = \"aa + a\" in exI)\n  apply (auto simp add: ac_simps)\n  done\n\nlemma set_plus_rearrange2: \"a +o (b +o C) = (a + b) +o C\"\n  for a b :: \"'a::semigroup_add\"\n  by (auto simp add: elt_set_plus_def add.assoc)\n\nlemma set_plus_rearrange3: \"(a +o B) + C = a +o (B + C)\"\n  for a :: \"'a::semigroup_add\"\n  apply (auto simp add: elt_set_plus_def set_plus_def)\n   apply (blast intro: ac_simps)\n  apply (rule_tac x = \"a + aa\" in exI)\n  apply (rule conjI)\n   apply (rule_tac x = \"aa\" in bexI)\n    apply auto\n  apply (rule_tac x = \"ba\" in bexI)\n   apply (auto simp add: ac_simps)\n  done\n\ntheorem set_plus_rearrange4: \"C + (a +o D) = a +o (C + D)\"\n  for a :: \"'a::comm_monoid_add\"\n  apply (auto simp add: elt_set_plus_def set_plus_def ac_simps)\n   apply (rule_tac x = \"aa + ba\" in exI)\n   apply (auto simp add: ac_simps)\n  done\n\nlemmas set_plus_rearranges = set_plus_rearrange set_plus_rearrange2\n  set_plus_rearrange3 set_plus_rearrange4\n\nlemma set_plus_mono [intro!]: \"C \\<subseteq> D \\<Longrightarrow> a +o C \\<subseteq> a +o D\"\n  by (auto simp add: elt_set_plus_def)\n\nlemma set_plus_mono2 [intro]: \"C \\<subseteq> D \\<Longrightarrow> E \\<subseteq> F \\<Longrightarrow> C + E \\<subseteq> D + F\"\n  for C D E F :: \"'a::plus set\"\n  by (auto simp add: set_plus_def)\n\nlemma set_plus_mono3 [intro]: \"a \\<in> C \\<Longrightarrow> a +o D \\<subseteq> C + D\"\n  by (auto simp add: elt_set_plus_def set_plus_def)\n\nlemma set_plus_mono4 [intro]: \"a \\<in> C \\<Longrightarrow> a +o D \\<subseteq> D + C\"\n  for a :: \"'a::comm_monoid_add\"\n  by (auto simp add: elt_set_plus_def set_plus_def ac_simps)\n\nlemma set_plus_mono5: \"a \\<in> C \\<Longrightarrow> B \\<subseteq> D \\<Longrightarrow> a +o B \\<subseteq> C + D\"\n  apply (subgoal_tac \"a +o B \\<subseteq> a +o D\")\n   apply (erule order_trans)\n   apply (erule set_plus_mono3)\n  apply (erule set_plus_mono)\n  done\n\nlemma set_plus_mono_b: \"C \\<subseteq> D \\<Longrightarrow> x \\<in> a +o C \\<Longrightarrow> x \\<in> a +o D\"\n  apply (frule set_plus_mono)\n  apply auto\n  done\n\nlemma set_plus_mono2_b: \"C \\<subseteq> D \\<Longrightarrow> E \\<subseteq> F \\<Longrightarrow> x \\<in> C + E \\<Longrightarrow> x \\<in> D + F\"\n  apply (frule set_plus_mono2)\n   prefer 2\n   apply force\n  apply assumption\n  done\n\nlemma set_plus_mono3_b: \"a \\<in> C \\<Longrightarrow> x \\<in> a +o D \\<Longrightarrow> x \\<in> C + D\"\n  apply (frule set_plus_mono3)\n  apply auto\n  done\n\nlemma set_plus_mono4_b: \"a \\<in> C \\<Longrightarrow> x \\<in> a +o D \\<Longrightarrow> x \\<in> D + C\"\n  for a x :: \"'a::comm_monoid_add\"\n  apply (frule set_plus_mono4)\n  apply auto\n  done\n\nlemma set_zero_plus [simp]: \"0 +o C = C\"\n  for C :: \"'a::comm_monoid_add set\"\n  by (auto simp add: elt_set_plus_def)\n\nlemma set_zero_plus2: \"0 \\<in> A \\<Longrightarrow> B \\<subseteq> A + B\"\n  for A B :: \"'a::comm_monoid_add set\"\n  apply (auto simp add: set_plus_def)\n  apply (rule_tac x = 0 in bexI)\n   apply (rule_tac x = x in bexI)\n    apply (auto simp add: ac_simps)\n  done\n\nlemma set_plus_imp_minus: \"a \\<in> b +o C \\<Longrightarrow> a - b \\<in> C\"\n  for a b :: \"'a::ab_group_add\"\n  by (auto simp add: elt_set_plus_def ac_simps)\n\nlemma set_minus_imp_plus: \"a - b \\<in> C \\<Longrightarrow> a \\<in> b +o C\"\n  for a b :: \"'a::ab_group_add\"\n  apply (auto simp add: elt_set_plus_def ac_simps)\n  apply (subgoal_tac \"a = (a + - b) + b\")\n   apply (rule bexI)\n    apply assumption\n   apply (auto simp add: ac_simps)\n  done\n\nlemma set_minus_plus: \"a - b \\<in> C \\<longleftrightarrow> a \\<in> b +o C\"\n  for a b :: \"'a::ab_group_add\"\n  apply (rule iffI)\n   apply (rule set_minus_imp_plus)\n   apply assumption\n  apply (rule set_plus_imp_minus)\n  apply assumption\n  done\n\nlemma set_times_intro [intro]: \"a \\<in> C \\<Longrightarrow> b \\<in> D \\<Longrightarrow> a * b \\<in> C * D\"\n  by (auto simp add: set_times_def)\n\nlemma set_times_elim:\n  assumes \"x \\<in> A * B\"\n  obtains a b where \"x = a * b\" and \"a \\<in> A\" and \"b \\<in> B\"\n  using assms unfolding set_times_def by fast\n\nlemma set_times_intro2 [intro!]: \"b \\<in> C \\<Longrightarrow> a * b \\<in> a *o C\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_times_rearrange: \"(a *o C) * (b *o D) = (a * b) *o (C * D)\"\n  for a b :: \"'a::comm_monoid_mult\"\n  apply (auto simp add: elt_set_times_def set_times_def)\n   apply (rule_tac x = \"ba * bb\" in exI)\n   apply (auto simp add: ac_simps)\n  apply (rule_tac x = \"aa * a\" in exI)\n  apply (auto simp add: ac_simps)\n  done\n\nlemma set_times_rearrange2: \"a *o (b *o C) = (a * b) *o C\"\n  for a b :: \"'a::semigroup_mult\"\n  by (auto simp add: elt_set_times_def mult.assoc)\n\nlemma set_times_rearrange3: \"(a *o B) * C = a *o (B * C)\"\n  for a :: \"'a::semigroup_mult\"\n  apply (auto simp add: elt_set_times_def set_times_def)\n   apply (blast intro: ac_simps)\n  apply (rule_tac x = \"a * aa\" in exI)\n  apply (rule conjI)\n   apply (rule_tac x = \"aa\" in bexI)\n    apply auto\n  apply (rule_tac x = \"ba\" in bexI)\n   apply (auto simp add: ac_simps)\n  done\n\ntheorem set_times_rearrange4: \"C * (a *o D) = a *o (C * D)\"\n  for a :: \"'a::comm_monoid_mult\"\n  apply (auto simp add: elt_set_times_def set_times_def ac_simps)\n   apply (rule_tac x = \"aa * ba\" in exI)\n   apply (auto simp add: ac_simps)\n  done\n\nlemmas set_times_rearranges = set_times_rearrange set_times_rearrange2\n  set_times_rearrange3 set_times_rearrange4\n\nlemma set_times_mono [intro]: \"C \\<subseteq> D \\<Longrightarrow> a *o C \\<subseteq> a *o D\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_times_mono2 [intro]: \"C \\<subseteq> D \\<Longrightarrow> E \\<subseteq> F \\<Longrightarrow> C * E \\<subseteq> D * F\"\n  for C D E F :: \"'a::times set\"\n  by (auto simp add: set_times_def)\n\nlemma set_times_mono3 [intro]: \"a \\<in> C \\<Longrightarrow> a *o D \\<subseteq> C * D\"\n  by (auto simp add: elt_set_times_def set_times_def)\n\nlemma set_times_mono4 [intro]: \"a \\<in> C \\<Longrightarrow> a *o D \\<subseteq> D * C\"\n  for a :: \"'a::comm_monoid_mult\"\n  by (auto simp add: elt_set_times_def set_times_def ac_simps)\n\nlemma set_times_mono5: \"a \\<in> C \\<Longrightarrow> B \\<subseteq> D \\<Longrightarrow> a *o B \\<subseteq> C * D\"\n  apply (subgoal_tac \"a *o B \\<subseteq> a *o D\")\n   apply (erule order_trans)\n   apply (erule set_times_mono3)\n  apply (erule set_times_mono)\n  done\n\nlemma set_times_mono_b: \"C \\<subseteq> D \\<Longrightarrow> x \\<in> a *o C \\<Longrightarrow> x \\<in> a *o D\"\n  apply (frule set_times_mono)\n  apply auto\n  done\n\nlemma set_times_mono2_b: \"C \\<subseteq> D \\<Longrightarrow> E \\<subseteq> F \\<Longrightarrow> x \\<in> C * E \\<Longrightarrow> x \\<in> D * F\"\n  apply (frule set_times_mono2)\n   prefer 2\n   apply force\n  apply assumption\n  done\n\nlemma set_times_mono3_b: \"a \\<in> C \\<Longrightarrow> x \\<in> a *o D \\<Longrightarrow> x \\<in> C * D\"\n  apply (frule set_times_mono3)\n  apply auto\n  done\n\nlemma set_times_mono4_b: \"a \\<in> C \\<Longrightarrow> x \\<in> a *o D \\<Longrightarrow> x \\<in> D * C\"\n  for a x :: \"'a::comm_monoid_mult\"\n  apply (frule set_times_mono4)\n  apply auto\n  done\n\nlemma set_one_times [simp]: \"1 *o C = C\"\n  for C :: \"'a::comm_monoid_mult set\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_times_plus_distrib: \"a *o (b +o C) = (a * b) +o (a *o C)\"\n  for a b :: \"'a::semiring\"\n  by (auto simp add: elt_set_plus_def elt_set_times_def ring_distribs)\n\nlemma set_times_plus_distrib2: \"a *o (B + C) = (a *o B) + (a *o C)\"\n  for a :: \"'a::semiring\"\n  apply (auto simp add: set_plus_def elt_set_times_def ring_distribs)\n   apply blast\n  apply (rule_tac x = \"b + bb\" in exI)\n  apply (auto simp add: ring_distribs)\n  done\n\nlemma set_times_plus_distrib3: \"(a +o C) * D \\<subseteq> a *o D + C * D\"\n  for a :: \"'a::semiring\"\n  apply (auto simp: elt_set_plus_def elt_set_times_def set_times_def set_plus_def ring_distribs)\n  apply auto\n  done\n\nlemmas set_times_plus_distribs =\n  set_times_plus_distrib\n  set_times_plus_distrib2\n\nlemma set_neg_intro: \"a \\<in> (- 1) *o C \\<Longrightarrow> - a \\<in> C\"\n  for a :: \"'a::ring_1\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_neg_intro2: \"a \\<in> C \\<Longrightarrow> - a \\<in> (- 1) *o C\"\n  for a :: \"'a::ring_1\"\n  by (auto simp add: elt_set_times_def)\n\nlemma set_plus_image: \"S + T = (\\<lambda>(x, y). x + y) ` (S \\<times> T)\"\n  by (fastforce simp: set_plus_def image_iff)\n\nlemma set_times_image: \"S * T = (\\<lambda>(x, y). x * y) ` (S \\<times> T)\"\n  by (fastforce simp: set_times_def image_iff)\n\nlemma finite_set_plus: \"finite s \\<Longrightarrow> finite t \\<Longrightarrow> finite (s + t)\"\n  by (simp add: set_plus_image)\n\nlemma finite_set_times: \"finite s \\<Longrightarrow> finite t \\<Longrightarrow> finite (s * t)\"\n  by (simp add: set_times_image)\n\nlemma set_sum_alt:\n  assumes fin: \"finite I\"\n  shows \"sum S I = {sum s I |s. \\<forall>i\\<in>I. s i \\<in> S i}\"\n    (is \"_ = ?sum I\")\n  using fin\nproof induct\n  case empty\n  then show ?case by simp\nnext\n  case (insert x F)\n  have \"sum S (insert x F) = S x + ?sum F\"\n    using insert.hyps by auto\n  also have \"\\<dots> = {s x + sum s F |s. \\<forall> i\\<in>insert x F. s i \\<in> S i}\"\n    unfolding set_plus_def\n  proof safe\n    fix y s\n    assume \"y \\<in> S x\" \"\\<forall>i\\<in>F. s i \\<in> S i\"\n    then show \"\\<exists>s'. y + sum s F = s' x + sum s' F \\<and> (\\<forall>i\\<in>insert x F. s' i \\<in> S i)\"\n      using insert.hyps\n      by (intro exI[of _ \"\\<lambda>i. if i \\<in> F then s i else y\"]) (auto simp add: set_plus_def)\n  qed auto\n  finally show ?case\n    using insert.hyps by auto\nqed\n\nlemma sum_set_cond_linear:\n  fixes f :: \"'a::comm_monoid_add set \\<Rightarrow> 'b::comm_monoid_add set\"\n  assumes [intro!]: \"\\<And>A B. P A  \\<Longrightarrow> P B  \\<Longrightarrow> P (A + B)\" \"P {0}\"\n    and f: \"\\<And>A B. P A  \\<Longrightarrow> P B \\<Longrightarrow> f (A + B) = f A + f B\" \"f {0} = {0}\"\n  assumes all: \"\\<And>i. i \\<in> I \\<Longrightarrow> P (S i)\"\n  shows \"f (sum S I) = sum (f \\<circ> S) I\"\nproof (cases \"finite I\")\n  case True\n  from this all show ?thesis\n  proof induct\n    case empty\n    then show ?case by (auto intro!: f)\n  next\n    case (insert x F)\n    from \\<open>finite F\\<close> \\<open>\\<And>i. i \\<in> insert x F \\<Longrightarrow> P (S i)\\<close> have \"P (sum S F)\"\n      by induct auto\n    with insert show ?case\n      by (simp, subst f) auto\n  qed\nnext\n  case False\n  then show ?thesis by (auto intro!: f)\nqed\n\nlemma sum_set_linear:\n  fixes f :: \"'a::comm_monoid_add set \\<Rightarrow> 'b::comm_monoid_add set\"\n  assumes \"\\<And>A B. f(A) + f(B) = f(A + B)\" \"f {0} = {0}\"\n  shows \"f (sum S I) = sum (f \\<circ> S) I\"\n  using sum_set_cond_linear[of \"\\<lambda>x. True\" f I S] assms by auto\n\nlemma set_times_Un_distrib:\n  \"A * (B \\<union> C) = A * B \\<union> A * C\"\n  \"(A \\<union> B) * C = A * C \\<union> B * C\"\n  by (auto simp: set_times_def)\n\nlemma set_times_UNION_distrib:\n  \"A * \\<Union>(M ` I) = (\\<Union>i\\<in>I. A * M i)\"\n  \"\\<Union>(M ` I) * A = (\\<Union>i\\<in>I. M i * A)\"\n  by (auto simp: set_times_def)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Set_Algebras.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110396870287, "lm_q2_score": 0.8459424295406088, "lm_q1q2_score": 0.7544207976039814}}
{"text": "theory Chapter3\nimports Main\nbegin\ntype_synonym vname = string\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval::\"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a1 a2) s = aval a1 s + aval a2 s\"\n\nvalue \"aval (Plus (N 3) (V ''x'')) (((\\<lambda>x.0) (''x'' := 7))(''y'' := 3))\"\n\nvalue \"aval (Plus (N 3) (V ''x'')) \"\n\nfun asimp_const::\"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a1 a2) =\n(case (asimp_const a1, asimp_const a2) of\n  (N n1, N n2) \\<Rightarrow> N(n1 + n2) |\n  (b1, b2) \\<Rightarrow> Plus b1 b2)\"\n\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply (induction a)\n    apply (auto split: aexp.split) (*split by the definition of the aexp type*)\n  done\n\nfun plus:: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"plus (N i1) (N i2) = N(i1 + i2)\" |\n\"plus (N i) a = (if i = 0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i = 0 then a else Plus a (N i))\" |\n\"plus a1 a2 = Plus a1 a2\"\n\nlemma aval_plus: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply (induction rule: plus.induct)\n  apply (auto)\n  done\n\nfun asimp::\"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)\"\n\nlemma aval_asimp: \"aval (asimp a) s = aval a s\"\n  apply (induction a)\n    apply (auto split: aexp.split)\n  apply (simp add: aval_plus)\n  done\n\nfun optimal::\"aexp \\<Rightarrow> bool\" where\n\"optimal (N i) = True\" |\n\"optimal (V x) = True\" |\n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (Plus b1 b2) = (optimal b1 \\<and> optimal b2)\"\n\nlemma asimp_const_opt: \"optimal (asimp_const a)\"\n  apply (induction a)\n    apply (auto split: aexp.split)\n  done\n\nfun sum_vals::\"aexp \\<Rightarrow> int\" where\n\"sum_vals (N i) = i\" |\n\"sum_vals (V x) = 0\" |\n\"sum_vals (Plus a1 a2) = (sum_vals a1) + (sum_vals a2)\"\n\nlemma sum_vals_plus: \"sum_vals (plus e1 e2) = sum_vals e1 + sum_vals e2\"\n  apply (induction rule: plus.induct)\n  apply (auto)\n  done\n\nlemma sum_vals_asimp: \"sum_vals (asimp e) = sum_vals e\"\n  apply (induction e)\n    apply (auto simp add: sum_vals_plus)\n  done\n\nfun sum_vars::\"aexp \\<Rightarrow> aexp\" where\n\"sum_vars (N i) = N 0\" |\n\"sum_vars (V x) = V x\" |\n\"sum_vars (Plus a1 a2) = Plus (sum_vars a1) (sum_vars a2)\"\n\n\nlemma sum_vars_asimp: \"aval (asimp (sum_vars e)) s = aval (sum_vars e) s\"\n  apply (induction e)\n    apply (auto simp add: aval_plus)\n  done\n\nfun full_asimp::\"aexp \\<Rightarrow> aexp\" where\n\"full_asimp e = asimp (Plus (sum_vars e) (N (sum_vals e)))\"\n\nlemma full_asimp: \"aval (full_asimp a) s = aval a s\"\n  apply (induction a)\n    apply (auto simp add: aval_plus sum_vars_asimp sum_vals_asimp)\n  done\n\nfun subst::\"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where \n\"subst x y (V n) = (if x = n then y else (V n))\" |\n\"subst x y (N n) = N n\" |\n\"subst x y (Plus a1 a2) = Plus (subst x y a1) (subst x y a2)\"\n\nlemma substitution_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply (induction e)\n  apply (auto split: if_splits)\n  done\n\nlemma subst_eq: \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply (induction a1 arbitrary: a2)\n  apply (auto simp add: substitution_lemma)\n  done\n\nend", "meta": {"author": "david-wang-0", "repo": "concrete-semantics", "sha": "master", "save_path": "github-repos/isabelle/david-wang-0-concrete-semantics", "path": "github-repos/isabelle/david-wang-0-concrete-semantics/concrete-semantics-main/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.7542572392917595}}
{"text": "theory Exercise_2_6\nimports Main\nbegin\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"contents Tip = []\" |\n  \"contents (Node l a r) = (contents l)@(a#(contents r))\"\n\nfun treesum :: \"nat tree \\<Rightarrow> nat\" where\n  \"treesum Tip = 0\" |\n  \"treesum (Node l a r) = (treesum l) + a + (treesum r)\"\n\nfun listsum :: \"nat list \\<Rightarrow> nat\" where\n  \"listsum [] = 0\" |\n  \"listsum (x#xs) = x + (listsum xs)\"\n  \nlemma listsum_app[simp]: \"listsum (x@y) = (listsum x) + (listsum y)\"\n  apply(induction x)\n  apply(auto)\n  done\n  \nlemma treelist_sum: \"treesum t = listsum(contents t)\"\n  apply(induction t)\n  apply(auto)\n  done\n", "meta": {"author": "AlexeyAkhunov", "repo": "isabelle", "sha": "3a46e94f04c64b12f806fe50750a5463786593d9", "save_path": "github-repos/isabelle/AlexeyAkhunov-isabelle", "path": "github-repos/isabelle/AlexeyAkhunov-isabelle/isabelle-3a46e94f04c64b12f806fe50750a5463786593d9/Exercise_2_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7542572370614812}}
{"text": "section \\<open> Cardinality of the continuum \\<close>\n\ntheory Continuum\n  imports\n    Lightweight_Cardinals\n    Finite_Bijection\n    HOL.Transcendental\n    Real_Bit\n    \"Z_Toolkit.Countable_Set_Extra\"\n    \"Z_Toolkit.Positive\"\nbegin\n\nsubsection \\<open> Cardinality $\\mathfrak{c}$ \\<close>\n\ntext \\<open> This theory introduces definitions and type class that group Isabelle types that have\n        cardinality of up to the cardinality of the continuum (i.e. $|\\mathbb{R}| = \\mathfrak{c}$). We can\n        then use the type class to exhibit injections into a universe of types of up to cardinality\n        $\\mathfrak{c}$, which we can then can then be used to introduce deeply encoded types into the UTP model.\n        Though restricting ourselves to types of cardinality $\\mathfrak{c}$ may seem limiting, this seems\n        to be a decently large universe that even for instance includes countable sets of real numbers.\n\n        Countable types in HOL are specified using the @{term countable} predicate, which includes both\n        types that are finite, and also countably infinite. Effectively then, the @{term countable} predicate\n        characterises types with cardinality up to $\\aleph_0$. We will create an analogous constant called\n        \\emph{continuum} that characterises types up to cardinality $\\mathfrak{c}$.\n        Since we don't have the continuum hypothesis in HOL, we explicitly require that types of up to cardinality $\\mathfrak{c}$\n        either exhibit an injection into the natural numbers (for types of finite or $\\aleph_0$ cardinality)\n        or a bijection with the set of natural numbers ($\\mathbb{P}\\,\\mathbb{N}$). With informal justification by\n        the continuum hypothesis there should be no types in between these two possibilities. \\<close>\n\ndefinition continuum :: \"'a set \\<Rightarrow> bool\" where\n\"continuum A \\<longleftrightarrow> (\\<exists> to_nat :: 'a \\<Rightarrow> nat. inj_on to_nat A) \\<or> (\\<exists> to_nat_set :: 'a \\<Rightarrow> nat set. bij_betw to_nat_set A UNIV)\"\n\nabbreviation \"\\<N> \\<equiv> UNIV :: nat set\"\nabbreviation \"\\<P>\\<N> \\<equiv> UNIV :: nat set set\"\n\ntext \\<open> The continuum can be equivalently characterised using HOL cardinals as types whose cardinality\n        is less than or equal to $\\aleph_0$, or else with cardinality equal to $\\mathfrak{c}$. \\<close>\n\nlemma continuum_as_card:\n  \"continuum A \\<longleftrightarrow> |A| \\<le>o |\\<N>| \\<or> |A| =o |\\<P>\\<N>|\"\n  by (simp add: continuum_def card_of_ordIso[THEN sym] card_of_ordLeq[THEN sym])\n\ntext \\<open> We now prove that certain sets are within the continuum; firstly empty sets. \\<close>\n\nlemma continuum_empty [simp]:\n  \"continuum {}\"\n  by (simp add: continuum_def)\n\nlemma countable_continuum:\n  \"countable A \\<Longrightarrow> continuum A\"\n  by (simp add: continuum_def countable_def)\n\nlemma continuum_bij_betw:\n  \"\\<lbrakk> continuum A; bij_betw f A B \\<rbrakk> \\<Longrightarrow> continuum B\"\n  by (simp add: continuum_as_card, meson bij_betw_inv_into card_of_ordIsoI ordIso_ordLeq_trans ordIso_transitive)\n\nlemma continuum_prod_lemma:\n  assumes \"A \\<noteq> {}\" \"|A| \\<le>o |\\<N>|\" \"|B| =o |\\<P>\\<N>|\"\n  shows \"|A \\<times> B| =o |\\<P>\\<N>|\"\nproof -\n  have \"|A| \\<le>o |B|\"\n  proof -\n    have \"|\\<N>| <o |\\<P>\\<N>|\"\n      by (rule card_of_set_type)\n    with assms(2) have \"|A| <o |\\<P>\\<N>|\"\n      using ordIso_ordLess_trans ordLess_lemma ordLess_transitive by blast\n    with assms(3)[THEN ordIso_symmetric] have \"|A| <o |B|\"\n      using ordLess_ordIso_trans by blast\n    thus ?thesis\n      using ordLess_imp_ordLeq by blast\n  qed\n  moreover from assms(3) have \"infinite B\"\n    using Finite_Set.finite_set card_of_ordIso_finite by blast\n  ultimately have \"|A \\<times> B| =o |B|\"\n    using assms(1) card_of_Times_infinite\n      by (auto)\n  with assms(3) show ?thesis\n    using ordIso_transitive by (blast)\nqed\n\ntext \\<open> The product of two types, both of whose cardinality is up to $\\mathfrak{c}$, is again $\\mathfrak{c}$ \\<close>\n\nlemma continuum_prod:\n  assumes \"continuum A\" \"continuum B\"\n  shows \"continuum (A \\<times> B)\"\nproof (cases \"A = {} \\<or> B = {}\")\n  case True\n  thus ?thesis by (auto)\nnext\n  case False\n  hence nemp: \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n    by (auto)\n\n  with nemp have \"|A| \\<le>o |\\<N>| \\<Longrightarrow> |B| =o |\\<P>\\<N>| \\<Longrightarrow> |A \\<times> B| =o |\\<P>\\<N>|\"\n    by (auto intro: continuum_prod_lemma)\n\n  moreover have \"|A| =o |\\<P>\\<N>| \\<Longrightarrow> |B| \\<le>o |\\<N>| \\<Longrightarrow> |A \\<times> B| =o |\\<P>\\<N>|\"\n  proof -\n    assume as: \"|A| =o |\\<P>\\<N>|\" \"|B| \\<le>o |\\<N>|\"\n    have \"|A \\<times> B| =o |B \\<times> A|\"\n      using card_of_Times_commute by fastforce\n    with as show ?thesis\n      using nemp continuum_prod_lemma[of B A] ordIso_transitive\n      by (auto)\n  qed\n\n  moreover have \"|A| =o |\\<P>\\<N>| \\<Longrightarrow> |B| =o |\\<P>\\<N>| \\<Longrightarrow> |A \\<times> B| =o |\\<P>\\<N>|\"\n  proof -\n    assume as: \"|A| =o |\\<P>\\<N>|\" \"|B| =o |\\<P>\\<N>|\"\n    have \"|\\<P>\\<N> \\<times> \\<P>\\<N>| =o |\\<P>\\<N>|\"\n      using card_of_Times_same_infinite\n      by force\n    moreover from as have \"|A \\<times> B| =o |\\<P>\\<N> \\<times> \\<P>\\<N>|\"\n      by (rule card_of_Times_cong)\n    ultimately show ?thesis\n      using ordIso_transitive by blast\n  qed\n\n  ultimately show ?thesis using assms\n    apply (simp add: continuum_as_card)\n    apply (erule disjE; erule disjE)\n    apply (blast intro: card_of_Times_ordLeq_infinite)\n    apply (rule disjI2)\n    apply (simp_all)\n  done\nqed\n\ntext \\<open> A list of continuum sets is in the continuum \\<close>\n\nlemma continuum_lists:\n  assumes \"continuum A\"\n  shows \"continuum (lists A)\"\n  by (meson assms bij_betw_inv continuum_bij_betw countable_continuum countable_lists lists_infinite_bij_betw uncountable_infinite)\n\ntext \\<open> A countable set over a type of cardinality up to $\\mathfrak{c}$ has cardinality up to $\\mathfrak{c}$. \\<close>\n\nlemma continuum_csets:\n  assumes \"continuum A\"\n  shows \"continuum (csets A)\"\nproof (cases \"countable A\")\n  case True note count = this\n  thus ?thesis\n  proof (cases \"finite A\")\n    case True\n    hence \"finite (csets A)\"\n      by (simp add: csets_def)\n    thus ?thesis\n      using countable_continuum uncountable_infinite by blast\n  next\n    case False\n    with count obtain to_nat where \"bij_betw to_nat A \\<N>\"\n      by blast\n    moreover hence \"bij_betw (\\<lambda> B. to_nat ` B) (Pow A) \\<P>\\<N>\"\n      using bij_betw_image_Pow by force\n    moreover have \"rcset ` csets A \\<subseteq> Pow A\"\n      by (auto simp add: csets_def)\n    ultimately have \"bij_betw (\\<lambda> B. to_nat ` B) (rcset ` csets A) \\<P>\\<N>\"\n      by (metis (no_types, lifting) Collect_mono Pow_def count countable_subset csets.rep_eq subset_antisym)\n    moreover have \"bij_betw rcset (csets A) (rcset ` csets A)\"\n      by (auto intro: bij_betwI' simp add: rcset_inject)\n    ultimately have \"bij_betw ((\\<lambda> B. to_nat ` B) \\<circ> rcset) (csets A) \\<P>\\<N>\"\n      by (simp add: bij_betw_def comp_inj_on image_comp)\n    thus ?thesis\n      by (auto simp add: continuum_def)\n  qed\nnext\n  case False\n  then obtain to_nat_set :: \"'a \\<Rightarrow> nat set\" where \"bij_betw to_nat_set A \\<P>\\<N>\"\n    using assms continuum_def countableI by blast\n  hence \"bij_betw (\\<lambda> B. to_nat_set `\\<^sub>c B) (csets A) UNIV\"\n    by (metis bij_betw_image_csets csets_UNIV)\n    thm bij_betw_trans\n  hence \"bij_betw (nat_set_cset_bij \\<circ> (\\<lambda> B. to_nat_set `\\<^sub>c B)) (csets A) \\<P>\\<N>\"\n    using bij_betw_trans bij_nat_set_cset_bij by blast\n  thus ?thesis\n    by (auto simp add: continuum_def)\nqed\n\nsubsection \\<open> Continuum class \\<close>\n\nclass continuum =\n  assumes ex_continuum_inj: \"(\\<exists> to_nat :: 'a \\<Rightarrow> nat. inj to_nat) \\<or> (\\<exists> to_nat_set :: 'a \\<Rightarrow> nat set. bij to_nat_set)\"\nbegin\n  lemma continuum: \"continuum (UNIV :: 'a set)\"\n    by (simp add: continuum_def ex_continuum_inj)\nend\n\nlemma continuum_classI: \"continuum (UNIV :: 'a set) \\<Longrightarrow> OFCLASS('a, continuum_class)\"\n  by (intro_classes, simp add: continuum_def)\n\nlemma uncountable_continuum:\n  \"uncountable (UNIV :: 'a::continuum set) \\<Longrightarrow> (\\<exists> to_nat_set :: 'a \\<Rightarrow> nat set. bij to_nat_set)\"\n  using countableI ex_continuum_inj by blast\n\ndefinition to_nat_set :: \"'a::continuum \\<Rightarrow> nat set\" where\n  \"to_nat_set = (if (countable (UNIV::'a set)) then (SOME f. inj f) else (SOME f. bij f))\"\n\ndefinition from_nat_set :: \"nat set \\<Rightarrow> 'a::continuum\" where\n  \"from_nat_set = inv (to_nat_set :: 'a \\<Rightarrow> nat set)\"\n\nlemma to_nat_set_inj [simp]: \"inj to_nat_set\"\nproof (cases \"countable (UNIV :: 'a set)\")\n  case False\n  then obtain to_nat_set :: \"'a \\<Rightarrow> nat set\" where \"bij to_nat_set\"\n    using uncountable_continuum by auto\n  thus ?thesis\n    by (simp add: to_nat_set_def, metis bij_betw_imp_inj_on someI_ex)\nnext\n  case True\n  hence \"(\\<exists> to_nat :: 'a \\<Rightarrow> nat. inj to_nat)\"\n    using ex_continuum_inj by blast\n  then obtain to_nat :: \"'a \\<Rightarrow> nat\" where \"inj to_nat\"\n    by auto\n  hence \"inj (\\<lambda> x. {to_nat x})\"\n    by (meson injD injI singleton_inject)\n  thus ?thesis using True\n    by (auto simp add: to_nat_set_def, metis someI_ex)\nqed\n\nlemma to_nat_set_bij:\n  assumes \"uncountable (UNIV :: 'a::continuum set)\"\n  shows \"bij (to_nat_set :: 'a \\<Rightarrow> nat set)\"\nproof -\n  obtain to_nat_set :: \"'a \\<Rightarrow> nat set\" where \"bij to_nat_set\"\n    using assms uncountable_continuum by blast\n  thus ?thesis\n    by (auto simp add: to_nat_set_def assms, metis someI_ex)\nqed\n\nlemma inj_on_to_nat_set[simp, intro]: \"inj_on to_nat_set S\"\n  using to_nat_set_inj by (auto simp: inj_on_def)\n\nlemma surj_from_nat_set [simp]: \"surj from_nat_set\"\n  unfolding from_nat_set_def by (simp add: inj_imp_surj_inv)\n\nlemma to_nat_set_split [simp]: \"to_nat_set x = to_nat_set y \\<longleftrightarrow> x = y\"\n  using injD [OF to_nat_set_inj] by auto\n\nlemma from_nat_set_to_nat_set [simp]:\n  \"from_nat_set (to_nat_set x) = x\"\n  by (simp add: from_nat_set_def)\n\ntext \\<open> Every countable type is within the continuum \\<close>\n\ninstance countable \\<subseteq> continuum\n  by (intro_classes, simp add: countable_infinite_type_inj_ex)\n\ntext \\<open> We construct bijective versions of @{const to_nat_set} and @{const from_nat_set} \\<close>\n\ndefinition to_nat_set_bij :: \"'a::{continuum, infinite} \\<Rightarrow> nat set\" where\n\"to_nat_set_bij = (SOME f. bij f)\"\n\nlemma to_nat_set_bij:\n  \"bij to_nat_set_bij\"\n  apply (auto simp add: bij_def)\n  oops\n\ntext \\<open> The real numbers are in the continuum -- this requires a proof that $|\\mathbb{P}\\,\\mathbb{N}| = |\\mathbb{R}|$\n that we have proved elsewhere. \\<close>\n\ninstance real :: continuum\n  using real_nats_bij by (intro_classes, blast)\n\ntext \\<open> Any set over a countable type is within the continuum \\<close>\n\ninstance set :: (countable) continuum\nproof\n  show \"(\\<exists>to_nat :: 'a set \\<Rightarrow> nat. inj to_nat) \\<or> (\\<exists>to_nat_set :: 'a set \\<Rightarrow> nat set. bij to_nat_set)\"\n  proof (cases \"finite (UNIV :: 'a set)\")\n    case True\n    hence \"countable (UNIV :: 'a set set)\"\n      by (simp add: Finite_Set.finite_set countable_finite)\n    then obtain to_nat :: \"'a set \\<Rightarrow> nat\" where \"inj to_nat\"\n      by auto\n    thus ?thesis\n      by (auto)\n  next\n    case False\n    then obtain to_nat :: \"'a \\<Rightarrow> nat\" where bij_to_nat: \"bij to_nat\"\n      using to_nat_on_infinite[of \"UNIV :: 'a set\"] by auto\n\n    let ?f = \"(\\<lambda> A. to_nat ` A) :: 'a set \\<Rightarrow> nat set\"\n\n    from bij_to_nat have \"bij ?f\"\n    proof -\n      have \"inj ?f\"\n        by (meson bij_betw_imp_inj_on bij_to_nat injI inj_image_eq_iff)\n      moreover have \"surj ?f\"\n      proof (clarsimp simp add: surj_def)\n        fix y :: \"nat set\"\n        have \"y = to_nat ` inv to_nat ` y\"\n          by (simp add: bij_is_surj bij_to_nat image_f_inv_f)\n        thus \"\\<exists>x::'a set. y = to_nat ` x\"\n          by (auto)\n      qed\n      ultimately show ?thesis\n        by (simp add: bij_betw_def)\n    qed\n    thus ?thesis\n      by (auto)\n  qed\nqed\n\ntext \\<open> A product of two continuum types is within the continuum \\<close>\n\ninstance prod :: (continuum, continuum) continuum\nproof\n  have \"continuum (UNIV :: 'a set)\" \"continuum (UNIV :: 'b set)\"\n    by (simp_all add: continuum)\n  hence \"continuum ((UNIV :: 'a set) \\<times> (UNIV :: 'b set))\"\n    by (rule continuum_prod)\n  hence \"continuum (UNIV :: ('a \\<times> 'b) set)\"\n    by simp\n  thus \"(\\<exists>to_nat :: ('a\\<times>'b) \\<Rightarrow> nat. inj to_nat) \\<or> (\\<exists>to_nat_set :: ('a\\<times>'b) \\<Rightarrow> nat set. bij to_nat_set)\"\n    by (simp add: continuum_def)\nqed\n\ntext \\<open> A list over a continuum type is within the continuum \\<close>\n\ninstance list :: (continuum) continuum\nproof\n  have \"continuum (UNIV :: 'a set)\"\n    by (simp_all add: continuum)\n  hence \"continuum (lists (UNIV :: 'a set))\"\n    using continuum_lists by blast\n  thus \"(\\<exists>to_nat::'a list \\<Rightarrow> nat. inj to_nat) \\<or> (\\<exists>to_nat_set::'a list \\<Rightarrow> nat set. bij to_nat_set)\"\n    by (simp add: continuum_def)\nqed\n\ntext \\<open> A countable set over a continuum type is within the continuum \\<close>\n\ninstance cset :: (continuum) continuum\nproof\n  have \"continuum (UNIV :: 'a cset set)\"\n    by (metis continuum continuum_csets csets_UNIV)\n  thus \"(\\<exists>to_nat :: 'a cset \\<Rightarrow> nat. inj to_nat) \\<or> (\\<exists>to_nat_set :: 'a cset \\<Rightarrow> nat set. bij to_nat_set)\"\n    by (simp add: continuum_def)\nqed\n\ntext \\<open> A positive number over a continuum type is within the continuum \\<close>\n\nlemma ge_num_infinite_if_no_top:\n  \"infinite {x::'a::{linorder, no_top}. n \\<le> x}\"\n  apply (clarsimp)\n  \\<comment> \\<open> From the assumption that the set is finite. \\<close>\n  apply (subgoal_tac \"\\<exists>y::'a. Max {x. n \\<le> x} < y\")\n   apply (clarsimp)\n   apply (metis Max_ge leD mem_Collect_eq order.strict_implies_order order_refl order_trans)\n  using gt_ex apply (blast)\ndone\n\nlemma less_zero_ordLeq_ge_zero:\n  \"|{x::'a::{ordered_ab_group_add}. x < 0}| \\<le>o |{x::'a. 0 \\<le> x}|\"\n  apply (rule_tac f = \"uminus\" in surj_imp_ordLeq)\n  apply (simp add: image_def)\n  apply (clarsimp)\n  apply (rule_tac x = \"- x\" in exI)\n  apply (simp)\ndone\n\ninstance pos :: (\"{zero, linorder, no_top}\") two ..\n\ntext \\<open> The next theorem is not entirely trivial to prove! \\<close>\n\ninstance pos :: (\"{linordered_ab_group_add, no_top, continuum}\") continuum\n  apply (intro_classes)\n  apply (case_tac \"countable (UNIV :: 'a set)\")\n    \\<comment> \\<open> Subgoal 1 (Easy Case) \\<close>\n   apply (rule disjI1)\n   apply (subgoal_tac \"\\<exists>to_nat::'a \\<Rightarrow> nat. inj to_nat\")\n    \\<comment> \\<open> Subgoal 1.1 \\<close>\n    apply (clarsimp)\n    apply (thin_tac \"countable UNIV\")\n    apply (rule_tac x = \"to_nat o Rep_pos\" in exI)\n    apply (rule inj_compose)\n     apply (assumption)\n    apply (meson Rep_pos_inject injI)\n    \\<comment> \\<open> Subgoal 1.2 \\<close>\n   apply (blast)\n    \\<comment> \\<open> Subgoal 2 \\<close>\n  apply (rule disjI2)\n  apply (subst sym [OF equal_card_bij_betw])\n  apply (rule equal_card_intro)\n  apply (subgoal_tac \"|UNIV::'a pos set| =o |{x::'a. 0 \\<le> x}|\")\n    \\<comment> \\<open> Subgoal 2.1 \\<close>\n   apply (erule ordIso_transitive)\n   apply (rule ordIso_symmetric)\n   apply (subgoal_tac \"|UNIV::nat set set| =o |UNIV::'a set|\")\n    \\<comment> \\<open> Subgoal 2.1.1 \\<close>\n    apply (erule ordIso_transitive)\n    apply (subgoal_tac \"(UNIV::'a set) = {x.0 \\<le> x} \\<union> {x. x < 0}\")\n    \\<comment> \\<open> Subgoal 2.1.1.1 \\<close>\n     apply (erule ssubst)\n     apply (rule card_of_Un_infinite_simps(1))\n      apply (rule ge_num_infinite_if_no_top)\n     apply (rule less_zero_ordLeq_ge_zero)\n    \\<comment> \\<open> Subgoal 2.1.1.2 \\<close>\n    apply (auto)\n    \\<comment> \\<open> Subgoal 2.1.2 \\<close>\n   apply (rule_tac f = \"from_nat_set\" in card_of_ordIsoI)\n   apply (rule_tac bij_betwI'; clarsimp?)\n    \\<comment> \\<open> This is the only place where @{term \"countable UNIV\"} is needed. \\<close>\n    apply (metis bij_betw_imp_surj from_nat_set_def surj_f_inv_f to_nat_set_bij)\n   apply (rule_tac x = \"to_nat_set y\" in exI)\n   apply (clarsimp)\n    \\<comment> \\<open> Subgoal 2.2 \\<close>\n  apply (rule_tac f = \"Rep_pos\" in card_of_ordIsoI)\n  apply (rule_tac bij_betwI'; clarsimp?)\n    apply (simp add: Rep_pos_inject)\n  using Rep_pos apply (blast)\n  apply (rule_tac x = \"Abs_pos y\" in exI)\n  apply (simp add: Abs_pos_inverse)\ndone\n\nend", "meta": {"author": "isabelle-utp", "repo": "utp-main", "sha": "27bdf3aee6d4fc00c8fe4d53283d0101857e0d41", "save_path": "github-repos/isabelle/isabelle-utp-utp-main", "path": "github-repos/isabelle/isabelle-utp-utp-main/utp-main-27bdf3aee6d4fc00c8fe4d53283d0101857e0d41/continuum/Continuum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.82893881677331, "lm_q1q2_score": 0.7542572369589248}}
{"text": "section \\<open>Baby examples\\<close>\n\ntheory Baby \n  imports \"HOL-Library.Sum_of_Squares\" \n          \"HOL-Decision_Procs.Approximation\"\n          \"HOL-Analysis.Analysis\"\n\nbegin\n\ntext \\<open>a simplification rule for powers\\<close>\nthm power_Suc\n\ntext \\<open>Kevin Buzzard's examples\\<close>\nlemma\n  fixes x::real\n  shows \"(x+y)*(x+2*y)*(x+3*y) = x^3 + 6*x^2*y + 11*x*y^2 + 6*y^3\"\n  by (simp add: algebra_simps eval_nat_numeral)\n\nlemma \"sqrt 2 + sqrt 3 < sqrt 10\"\nproof -\n  have \"(sqrt 2 + sqrt 3)^2 < (sqrt 10)^2\"\n  proof (simp add: algebra_simps eval_nat_numeral)\n    have \"(2 * (sqrt 2 * sqrt 3))^2 < 5 ^ 2\"\n      by (simp add: algebra_simps eval_nat_numeral)\n    then show \"2 * (sqrt 2 * sqrt 3) < 5\"\n      by (smt (verit, best) power_mono)\n  qed\n  then show ?thesis\n    by (simp add: real_less_rsqrt)\nqed\n\nlemma \"sqrt 2 + sqrt 3 < sqrt 10\"\n  by (approximation 10)\n\nlemma \"x \\<in> {0.999..1.001} \\<Longrightarrow> \\<bar>pi - 4 * arctan x\\<bar> < 0.0021\"\n  by (approximation 20)\n\nlemma \"3.141592635389 < pi\"\n  by (approximation 30)\n\nlemma\n  fixes a::real\n  shows \"(a*b + b * c + c*a)^3 \\<le> (a^2 + a * b + b^2) * (b^2 + b * c + c^2) * (c^2 + c*a + a^2)\"\n  by sos\n\nlemma \"sqrt 2 \\<notin> \\<rat>\"\nproof\n  assume \"sqrt 2 \\<in> \\<rat>\"\n  then obtain q::rat where \"sqrt 2 = of_rat q\"\n    using Rats_cases by blast\n  then have \"q^2 = 2\"\n    by (metis abs_numeral of_rat_eq_iff of_rat_numeral_eq of_rat_power power2_eq_square \n              real_sqrt_mult_self)\n  then obtain m n where \"coprime m n\" \"q = of_int m / of_int n\"\n    by (metis Fract_of_int_quotient Rat_cases)\n  then have \"of_int m ^ 2 / of_int n ^ 2 = (2::rat)\"\n    by (metis \\<open>q\\<^sup>2 = 2\\<close> power_divide)\n  then have 2: \"of_int m ^ 2 = (2::rat) * of_int n ^ 2\"\n    by (metis division_ring_divide_zero double_eq_0_iff mult_2_right mult_zero_right \n              nonzero_divide_eq_eq)\n  then have \"2 dvd m\"\n    by (metis (mono_tags, lifting) even_mult_iff even_numeral of_int_eq_iff of_int_mult \n              of_int_numeral power2_eq_square)\n  then obtain r where \"m = 2*r\"\n    by blast\n  then have \"2 dvd n\"\n    by (smt (verit) \"2\" \\<open>even m\\<close> dvdE even_mult_iff mult.left_commute mult_cancel_left of_int_1 \n            of_int_add of_int_eq_iff of_int_mult one_add_one power2_eq_square)\n  then show False\n    using \\<open>coprime m n\\<close> \\<open>m = 2 * r\\<close> by simp\nqed\n\nsubsection \\<open>Material for a later post, about descriptions\\<close>\n\n\nlemma \n  fixes \\<B> :: \"'a::metric_space set set\" and L :: \"nat list set\"\n  assumes \"\\<S> \\<subseteq> {ball x r | x r. r>0}\" and \"L \\<noteq> {}\"\n  shows \"P \\<S> L\"\nproof -\n  have \"\\<And>B. B \\<in> \\<S> \\<Longrightarrow> \\<exists>x. \\<exists>r>0. B = ball x r\"\n    using assms by blast\n  then obtain centre rad where rad: \"\\<And>B. B \\<in> \\<S> \\<Longrightarrow> rad B > 0\" \n                         and centre: \"\\<And>B. B \\<in> \\<S> \\<Longrightarrow> B = ball (centre B) (rad B)\"\n    by metis\n  define infrad where \"infrad \\<equiv> Inf (rad ` \\<S>)\"\n  have \"infrad \\<le> rad B\" if \"B \\<in> \\<S>\" for B\n    by (smt (verit, best) bdd_below.I cINF_lower image_iff infrad_def rad that)\n\n  have \"\\<exists>B \\<in> \\<S>. rad B = infrad\" if \"finite \\<S>\" \"\\<S> \\<noteq> {}\"\n    by (smt (verit) empty_is_image finite_imageI finite_less_Inf_iff imageE infrad_def that)\n\n  define minl where \"minl = Inf (length ` L)\"\n  obtain l0 where  \"l0 \\<in> L\" \"length l0 = minl\"\n    by (metis Inf_nat_def1 empty_is_image imageE minl_def \\<open>L \\<noteq> {}\\<close>)\n  then have \"length l0 \\<le> length l\" if \"l \\<in> L\" for l\n    by (simp add: cINF_lower minl_def that)\n\n  show ?thesis \n    sorry\nqed\n\n\n\n\nend\n", "meta": {"author": "lawrencecpaulson", "repo": "lawrencecpaulson.github.io", "sha": "325aed7ca359736ebed88a820f88763d248cd2c8", "save_path": "github-repos/isabelle/lawrencecpaulson-lawrencecpaulson.github.io", "path": "github-repos/isabelle/lawrencecpaulson-lawrencecpaulson.github.io/lawrencecpaulson.github.io-325aed7ca359736ebed88a820f88763d248cd2c8/Isabelle-Examples/Baby.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.822189121808099, "lm_q1q2_score": 0.7541962662582454}}
{"text": "theory Exe4p5\n  imports Main\nbegin\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0: \"ev 0\" |\nevSS : \"ev n \\<Longrightarrow> ev (Suc(Suc n))\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\" |\n\"evn (Suc 0) = False\" |\n\"evn (Suc(Suc n)) = evn n\"\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\nrefl: \"star r x x\" |\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" where\niter_refl: \"iter r 0 x x\" |\niter_step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma fixes r n x y\n  assumes s: \"iter r n x y\"\n  shows \"star r x y\"\nproof -\n  have \"iter r n x y \\<Longrightarrow> star r x y\"\n  proof (induction rule: iter.induct)\n    case (iter_refl r x)\n    then show ?case by (simp add: star.refl)\n  next\n    case (iter_step r x y n z)\n    then show ?case by (simp add: star.step)\n  qed\n  thus ?thesis using s by simp\nqed\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/prog-prove/Exe4p5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582477806521, "lm_q2_score": 0.8104789040926008, "lm_q1q2_score": 0.7541167809651845}}
{"text": "(*  Author:     Tobias Nipkow, Lawrence C Paulson and Markus Wenzel; Florian Haftmann, TU Muenchen *)\n\nsection {* Complete lattices *}\n\ntheory Complete_Lattices\nimports Fun\nbegin\n\nnotation\n  less_eq (infix \"\\<sqsubseteq>\" 50) and\n  less (infix \"\\<sqsubset>\" 50)\n\n\nsubsection {* Syntactic infimum and supremum operations *}\n\nclass Inf =\n  fixes Inf :: \"'a set \\<Rightarrow> 'a\" (\"\\<Sqinter>_\" [900] 900)\nbegin\n\ndefinition INFIMUM :: \"'b set \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  INF_def: \"INFIMUM A f = \\<Sqinter>(f ` A)\"\n\nlemma Inf_image_eq [simp]:\n  \"\\<Sqinter>(f ` A) = INFIMUM A f\"\n  by (simp add: INF_def)\n\nlemma INF_image [simp]:\n  \"INFIMUM (f ` A) g = INFIMUM A (g \\<circ> f)\"\n  by (simp only: INF_def image_comp)\n\nlemma INF_identity_eq [simp]:\n  \"INFIMUM A (\\<lambda>x. x) = \\<Sqinter>A\"\n  by (simp add: INF_def)\n\nlemma INF_id_eq [simp]:\n  \"INFIMUM A id = \\<Sqinter>A\"\n  by (simp add: id_def)\n\nlemma INF_cong:\n  \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> C x = D x) \\<Longrightarrow> INFIMUM A C = INFIMUM B D\"\n  by (simp add: INF_def image_def)\n\nlemma strong_INF_cong [cong]:\n  \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B =simp=> C x = D x) \\<Longrightarrow> INFIMUM A C = INFIMUM B D\"\n  unfolding simp_implies_def by (fact INF_cong)\n\nend\n\nclass Sup =\n  fixes Sup :: \"'a set \\<Rightarrow> 'a\" (\"\\<Squnion>_\" [900] 900)\nbegin\n\ndefinition SUPREMUM :: \"'b set \\<Rightarrow> ('b \\<Rightarrow> 'a) \\<Rightarrow> 'a\" where\n  SUP_def: \"SUPREMUM A f = \\<Squnion>(f ` A)\"\n\nlemma Sup_image_eq [simp]:\n  \"\\<Squnion>(f ` A) = SUPREMUM A f\"\n  by (simp add: SUP_def)\n\nlemma SUP_image [simp]:\n  \"SUPREMUM (f ` A) g = SUPREMUM A (g \\<circ> f)\"\n  by (simp only: SUP_def image_comp)\n\nlemma SUP_identity_eq [simp]:\n  \"SUPREMUM A (\\<lambda>x. x) = \\<Squnion>A\"\n  by (simp add: SUP_def)\n\nlemma SUP_id_eq [simp]:\n  \"SUPREMUM A id = \\<Squnion>A\"\n  by (simp add: id_def)\n\nlemma SUP_cong:\n  \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> C x = D x) \\<Longrightarrow> SUPREMUM A C = SUPREMUM B D\"\n  by (simp add: SUP_def image_def)\n\nlemma strong_SUP_cong [cong]:\n  \"A = B \\<Longrightarrow> (\\<And>x. x \\<in> B =simp=> C x = D x) \\<Longrightarrow> SUPREMUM A C = SUPREMUM B D\"\n  unfolding simp_implies_def by (fact SUP_cong)\n\nend\n\ntext {*\n  Note: must use names @{const INFIMUM} and @{const SUPREMUM} here instead of\n  @{text INF} and @{text SUP} to allow the following syntax coexist\n  with the plain constant names.\n*}\n\nsyntax\n  \"_INF1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3INF _./ _)\" [0, 10] 10)\n  \"_INF\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3INF _:_./ _)\" [0, 0, 10] 10)\n  \"_SUP1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3SUP _./ _)\" [0, 10] 10)\n  \"_SUP\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3SUP _:_./ _)\" [0, 0, 10] 10)\n\nsyntax (xsymbols)\n  \"_INF1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3\\<Sqinter>_./ _)\" [0, 10] 10)\n  \"_INF\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3\\<Sqinter>_\\<in>_./ _)\" [0, 0, 10] 10)\n  \"_SUP1\"     :: \"pttrns \\<Rightarrow> 'b \\<Rightarrow> 'b\"           (\"(3\\<Squnion>_./ _)\" [0, 10] 10)\n  \"_SUP\"      :: \"pttrn \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> 'b\"  (\"(3\\<Squnion>_\\<in>_./ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"INF x y. B\"   == \"INF x. INF y. B\"\n  \"INF x. B\"     == \"CONST INFIMUM CONST UNIV (%x. B)\"\n  \"INF x. B\"     == \"INF x:CONST UNIV. B\"\n  \"INF x:A. B\"   == \"CONST INFIMUM A (%x. B)\"\n  \"SUP x y. B\"   == \"SUP x. SUP y. B\"\n  \"SUP x. B\"     == \"CONST SUPREMUM CONST UNIV (%x. B)\"\n  \"SUP x. B\"     == \"SUP x:CONST UNIV. B\"\n  \"SUP x:A. B\"   == \"CONST SUPREMUM A (%x. B)\"\n\nprint_translation {*\n  [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax INFIMUM} @{syntax_const \"_INF\"},\n    Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax SUPREMUM} @{syntax_const \"_SUP\"}]\n*} -- {* to avoid eta-contraction of body *}\n\nsubsection {* Abstract complete lattices *}\n\ntext {* A complete lattice always has a bottom and a top,\nso we include them into the following type class,\nalong with assumptions that define bottom and top\nin terms of infimum and supremum. *}\n\nclass complete_lattice = lattice + Inf + Sup + bot + top +\n  assumes Inf_lower: \"x \\<in> A \\<Longrightarrow> \\<Sqinter>A \\<sqsubseteq> x\"\n     and Inf_greatest: \"(\\<And>x. x \\<in> A \\<Longrightarrow> z \\<sqsubseteq> x) \\<Longrightarrow> z \\<sqsubseteq> \\<Sqinter>A\"\n  assumes Sup_upper: \"x \\<in> A \\<Longrightarrow> x \\<sqsubseteq> \\<Squnion>A\"\n     and Sup_least: \"(\\<And>x. x \\<in> A \\<Longrightarrow> x \\<sqsubseteq> z) \\<Longrightarrow> \\<Squnion>A \\<sqsubseteq> z\"\n  assumes Inf_empty [simp]: \"\\<Sqinter>{} = \\<top>\"\n  assumes Sup_empty [simp]: \"\\<Squnion>{} = \\<bottom>\"\nbegin\n\nsubclass bounded_lattice\nproof\n  fix a\n  show \"\\<bottom> \\<le> a\" by (auto intro: Sup_least simp only: Sup_empty [symmetric])\n  show \"a \\<le> \\<top>\" by (auto intro: Inf_greatest simp only: Inf_empty [symmetric])\nqed\n\nlemma dual_complete_lattice:\n  \"class.complete_lattice Sup Inf sup (op \\<ge>) (op >) inf \\<top> \\<bottom>\"\n  by (auto intro!: class.complete_lattice.intro dual_lattice)\n    (unfold_locales, (fact Inf_empty Sup_empty\n        Sup_upper Sup_least Inf_lower Inf_greatest)+)\n\nend\n\ncontext complete_lattice\nbegin\n\nlemma INF_foundation_dual:\n  \"Sup.SUPREMUM Inf = INFIMUM\"\n  by (simp add: fun_eq_iff Sup.SUP_def)\n\nlemma SUP_foundation_dual:\n  \"Inf.INFIMUM Sup = SUPREMUM\"\n  by (simp add: fun_eq_iff Inf.INF_def)\n\nlemma Sup_eqI:\n  \"(\\<And>y. y \\<in> A \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> (\\<And>y. (\\<And>z. z \\<in> A \\<Longrightarrow> z \\<le> y) \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> \\<Squnion>A = x\"\n  by (blast intro: antisym Sup_least Sup_upper)\n\nlemma Inf_eqI:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> x \\<le> i) \\<Longrightarrow> (\\<And>y. (\\<And>i. i \\<in> A \\<Longrightarrow> y \\<le> i) \\<Longrightarrow> y \\<le> x) \\<Longrightarrow> \\<Sqinter>A = x\"\n  by (blast intro: antisym Inf_greatest Inf_lower)\n\nlemma SUP_eqI:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<le> x) \\<Longrightarrow> (\\<And>y. (\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<le> y) \\<Longrightarrow> x \\<le> y) \\<Longrightarrow> (\\<Squnion>i\\<in>A. f i) = x\"\n  using Sup_eqI [of \"f ` A\" x] by auto\n\nlemma INF_eqI:\n  \"(\\<And>i. i \\<in> A \\<Longrightarrow> x \\<le> f i) \\<Longrightarrow> (\\<And>y. (\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<ge> y) \\<Longrightarrow> x \\<ge> y) \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) = x\"\n  using Inf_eqI [of \"f ` A\" x] by auto\n\nlemma INF_lower: \"i \\<in> A \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) \\<sqsubseteq> f i\"\n  using Inf_lower [of _ \"f ` A\"] by simp\n\nlemma INF_greatest: \"(\\<And>i. i \\<in> A \\<Longrightarrow> u \\<sqsubseteq> f i) \\<Longrightarrow> u \\<sqsubseteq> (\\<Sqinter>i\\<in>A. f i)\"\n  using Inf_greatest [of \"f ` A\"] by auto\n\nlemma SUP_upper: \"i \\<in> A \\<Longrightarrow> f i \\<sqsubseteq> (\\<Squnion>i\\<in>A. f i)\"\n  using Sup_upper [of _ \"f ` A\"] by simp\n\nlemma SUP_least: \"(\\<And>i. i \\<in> A \\<Longrightarrow> f i \\<sqsubseteq> u) \\<Longrightarrow> (\\<Squnion>i\\<in>A. f i) \\<sqsubseteq> u\"\n  using Sup_least [of \"f ` A\"] by auto\n\nlemma Inf_lower2: \"u \\<in> A \\<Longrightarrow> u \\<sqsubseteq> v \\<Longrightarrow> \\<Sqinter>A \\<sqsubseteq> v\"\n  using Inf_lower [of u A] by auto\n\nlemma INF_lower2: \"i \\<in> A \\<Longrightarrow> f i \\<sqsubseteq> u \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f i) \\<sqsubseteq> u\"\n  using INF_lower [of i A f] by auto\n\nlemma Sup_upper2: \"u \\<in> A \\<Longrightarrow> v \\<sqsubseteq> u \\<Longrightarrow> v \\<sqsubseteq> \\<Squnion>A\"\n  using Sup_upper [of u A] by auto\n\nlemma SUP_upper2: \"i \\<in> A \\<Longrightarrow> u \\<sqsubseteq> f i \\<Longrightarrow> u \\<sqsubseteq> (\\<Squnion>i\\<in>A. f i)\"\n  using SUP_upper [of i A f] by auto\n\nlemma le_Inf_iff: \"b \\<sqsubseteq> \\<Sqinter>A \\<longleftrightarrow> (\\<forall>a\\<in>A. b \\<sqsubseteq> a)\"\n  by (auto intro: Inf_greatest dest: Inf_lower)\n\nlemma le_INF_iff: \"u \\<sqsubseteq> (\\<Sqinter>i\\<in>A. f i) \\<longleftrightarrow> (\\<forall>i\\<in>A. u \\<sqsubseteq> f i)\"\n  using le_Inf_iff [of _ \"f ` A\"] by simp\n\nlemma Sup_le_iff: \"\\<Squnion>A \\<sqsubseteq> b \\<longleftrightarrow> (\\<forall>a\\<in>A. a \\<sqsubseteq> b)\"\n  by (auto intro: Sup_least dest: Sup_upper)\n\nlemma SUP_le_iff: \"(\\<Squnion>i\\<in>A. f i) \\<sqsubseteq> u \\<longleftrightarrow> (\\<forall>i\\<in>A. f i \\<sqsubseteq> u)\"\n  using Sup_le_iff [of \"f ` A\"] by simp\n\nlemma Inf_insert [simp]: \"\\<Sqinter>insert a A = a \\<sqinter> \\<Sqinter>A\"\n  by (auto intro: le_infI le_infI1 le_infI2 antisym Inf_greatest Inf_lower)\n\nlemma INF_insert [simp]: \"(\\<Sqinter>x\\<in>insert a A. f x) = f a \\<sqinter> INFIMUM A f\"\n  unfolding INF_def Inf_insert by simp\n\nlemma Sup_insert [simp]: \"\\<Squnion>insert a A = a \\<squnion> \\<Squnion>A\"\n  by (auto intro: le_supI le_supI1 le_supI2 antisym Sup_least Sup_upper)\n\nlemma SUP_insert [simp]: \"(\\<Squnion>x\\<in>insert a A. f x) = f a \\<squnion> SUPREMUM A f\"\n  unfolding SUP_def Sup_insert by simp\n\nlemma INF_empty [simp]: \"(\\<Sqinter>x\\<in>{}. f x) = \\<top>\"\n  by (simp add: INF_def)\n\nlemma SUP_empty [simp]: \"(\\<Squnion>x\\<in>{}. f x) = \\<bottom>\"\n  by (simp add: SUP_def)\n\nlemma Inf_UNIV [simp]:\n  \"\\<Sqinter>UNIV = \\<bottom>\"\n  by (auto intro!: antisym Inf_lower)\n\nlemma Sup_UNIV [simp]:\n  \"\\<Squnion>UNIV = \\<top>\"\n  by (auto intro!: antisym Sup_upper)\n\nlemma Inf_Sup: \"\\<Sqinter>A = \\<Squnion>{b. \\<forall>a \\<in> A. b \\<sqsubseteq> a}\"\n  by (auto intro: antisym Inf_lower Inf_greatest Sup_upper Sup_least)\n\nlemma Sup_Inf:  \"\\<Squnion>A = \\<Sqinter>{b. \\<forall>a \\<in> A. a \\<sqsubseteq> b}\"\n  by (auto intro: antisym Inf_lower Inf_greatest Sup_upper Sup_least)\n\nlemma Inf_superset_mono: \"B \\<subseteq> A \\<Longrightarrow> \\<Sqinter>A \\<sqsubseteq> \\<Sqinter>B\"\n  by (auto intro: Inf_greatest Inf_lower)\n\nlemma Sup_subset_mono: \"A \\<subseteq> B \\<Longrightarrow> \\<Squnion>A \\<sqsubseteq> \\<Squnion>B\"\n  by (auto intro: Sup_least Sup_upper)\n\nlemma Inf_mono:\n  assumes \"\\<And>b. b \\<in> B \\<Longrightarrow> \\<exists>a\\<in>A. a \\<sqsubseteq> b\"\n  shows \"\\<Sqinter>A \\<sqsubseteq> \\<Sqinter>B\"\nproof (rule Inf_greatest)\n  fix b assume \"b \\<in> B\"\n  with assms obtain a where \"a \\<in> A\" and \"a \\<sqsubseteq> b\" by blast\n  from `a \\<in> A` have \"\\<Sqinter>A \\<sqsubseteq> a\" by (rule Inf_lower)\n  with `a \\<sqsubseteq> b` show \"\\<Sqinter>A \\<sqsubseteq> b\" by auto\nqed\n\nlemma INF_mono:\n  \"(\\<And>m. m \\<in> B \\<Longrightarrow> \\<exists>n\\<in>A. f n \\<sqsubseteq> g m) \\<Longrightarrow> (\\<Sqinter>n\\<in>A. f n) \\<sqsubseteq> (\\<Sqinter>n\\<in>B. g n)\"\n  using Inf_mono [of \"g ` B\" \"f ` A\"] by auto\n\nlemma Sup_mono:\n  assumes \"\\<And>a. a \\<in> A \\<Longrightarrow> \\<exists>b\\<in>B. a \\<sqsubseteq> b\"\n  shows \"\\<Squnion>A \\<sqsubseteq> \\<Squnion>B\"\nproof (rule Sup_least)\n  fix a assume \"a \\<in> A\"\n  with assms obtain b where \"b \\<in> B\" and \"a \\<sqsubseteq> b\" by blast\n  from `b \\<in> B` have \"b \\<sqsubseteq> \\<Squnion>B\" by (rule Sup_upper)\n  with `a \\<sqsubseteq> b` show \"a \\<sqsubseteq> \\<Squnion>B\" by auto\nqed\n\nlemma SUP_mono:\n  \"(\\<And>n. n \\<in> A \\<Longrightarrow> \\<exists>m\\<in>B. f n \\<sqsubseteq> g m) \\<Longrightarrow> (\\<Squnion>n\\<in>A. f n) \\<sqsubseteq> (\\<Squnion>n\\<in>B. g n)\"\n  using Sup_mono [of \"f ` A\" \"g ` B\"] by auto\n\nlemma INF_superset_mono:\n  \"B \\<subseteq> A \\<Longrightarrow> (\\<And>x. x \\<in> B \\<Longrightarrow> f x \\<sqsubseteq> g x) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. f x) \\<sqsubseteq> (\\<Sqinter>x\\<in>B. g x)\"\n  -- {* The last inclusion is POSITIVE! *}\n  by (blast intro: INF_mono dest: subsetD)\n\nlemma SUP_subset_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<sqsubseteq> g x) \\<Longrightarrow> (\\<Squnion>x\\<in>A. f x) \\<sqsubseteq> (\\<Squnion>x\\<in>B. g x)\"\n  by (blast intro: SUP_mono dest: subsetD)\n\nlemma Inf_less_eq:\n  assumes \"\\<And>v. v \\<in> A \\<Longrightarrow> v \\<sqsubseteq> u\"\n    and \"A \\<noteq> {}\"\n  shows \"\\<Sqinter>A \\<sqsubseteq> u\"\nproof -\n  from `A \\<noteq> {}` obtain v where \"v \\<in> A\" by blast\n  moreover from `v \\<in> A` assms(1) have \"v \\<sqsubseteq> u\" by blast\n  ultimately show ?thesis by (rule Inf_lower2)\nqed\n\nlemma less_eq_Sup:\n  assumes \"\\<And>v. v \\<in> A \\<Longrightarrow> u \\<sqsubseteq> v\"\n    and \"A \\<noteq> {}\"\n  shows \"u \\<sqsubseteq> \\<Squnion>A\"\nproof -\n  from `A \\<noteq> {}` obtain v where \"v \\<in> A\" by blast\n  moreover from `v \\<in> A` assms(1) have \"u \\<sqsubseteq> v\" by blast\n  ultimately show ?thesis by (rule Sup_upper2)\nqed\n\nlemma SUP_eq:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> \\<exists>j\\<in>B. f i \\<le> g j\"\n  assumes \"\\<And>j. j \\<in> B \\<Longrightarrow> \\<exists>i\\<in>A. g j \\<le> f i\"\n  shows \"(\\<Squnion>i\\<in>A. f i) = (\\<Squnion>j\\<in>B. g j)\"\n  by (intro antisym SUP_least) (blast intro: SUP_upper2 dest: assms)+\n\nlemma INF_eq:\n  assumes \"\\<And>i. i \\<in> A \\<Longrightarrow> \\<exists>j\\<in>B. f i \\<ge> g j\"\n  assumes \"\\<And>j. j \\<in> B \\<Longrightarrow> \\<exists>i\\<in>A. g j \\<ge> f i\"\n  shows \"(\\<Sqinter>i\\<in>A. f i) = (\\<Sqinter>j\\<in>B. g j)\"\n  by (intro antisym INF_greatest) (blast intro: INF_lower2 dest: assms)+\n\nlemma less_eq_Inf_inter: \"\\<Sqinter>A \\<squnion> \\<Sqinter>B \\<sqsubseteq> \\<Sqinter>(A \\<inter> B)\"\n  by (auto intro: Inf_greatest Inf_lower)\n\nlemma Sup_inter_less_eq: \"\\<Squnion>(A \\<inter> B) \\<sqsubseteq> \\<Squnion>A \\<sqinter> \\<Squnion>B \"\n  by (auto intro: Sup_least Sup_upper)\n\nlemma Inf_union_distrib: \"\\<Sqinter>(A \\<union> B) = \\<Sqinter>A \\<sqinter> \\<Sqinter>B\"\n  by (rule antisym) (auto intro: Inf_greatest Inf_lower le_infI1 le_infI2)\n\nlemma INF_union:\n  \"(\\<Sqinter>i \\<in> A \\<union> B. M i) = (\\<Sqinter>i \\<in> A. M i) \\<sqinter> (\\<Sqinter>i\\<in>B. M i)\"\n  by (auto intro!: antisym INF_mono intro: le_infI1 le_infI2 INF_greatest INF_lower)\n\nlemma Sup_union_distrib: \"\\<Squnion>(A \\<union> B) = \\<Squnion>A \\<squnion> \\<Squnion>B\"\n  by (rule antisym) (auto intro: Sup_least Sup_upper le_supI1 le_supI2)\n\nlemma SUP_union:\n  \"(\\<Squnion>i \\<in> A \\<union> B. M i) = (\\<Squnion>i \\<in> A. M i) \\<squnion> (\\<Squnion>i\\<in>B. M i)\"\n  by (auto intro!: antisym SUP_mono intro: le_supI1 le_supI2 SUP_least SUP_upper)\n\nlemma INF_inf_distrib: \"(\\<Sqinter>a\\<in>A. f a) \\<sqinter> (\\<Sqinter>a\\<in>A. g a) = (\\<Sqinter>a\\<in>A. f a \\<sqinter> g a)\"\n  by (rule antisym) (rule INF_greatest, auto intro: le_infI1 le_infI2 INF_lower INF_mono)\n\nlemma SUP_sup_distrib: \"(\\<Squnion>a\\<in>A. f a) \\<squnion> (\\<Squnion>a\\<in>A. g a) = (\\<Squnion>a\\<in>A. f a \\<squnion> g a)\" (is \"?L = ?R\")\nproof (rule antisym)\n  show \"?L \\<le> ?R\" by (auto intro: le_supI1 le_supI2 SUP_upper SUP_mono)\nnext\n  show \"?R \\<le> ?L\" by (rule SUP_least) (auto intro: le_supI1 le_supI2 SUP_upper)\nqed\n\nlemma Inf_top_conv [simp]:\n  \"\\<Sqinter>A = \\<top> \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\"\n  \"\\<top> = \\<Sqinter>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\"\nproof -\n  show \"\\<Sqinter>A = \\<top> \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\"\n  proof\n    assume \"\\<forall>x\\<in>A. x = \\<top>\"\n    then have \"A = {} \\<or> A = {\\<top>}\" by auto\n    then show \"\\<Sqinter>A = \\<top>\" by auto\n  next\n    assume \"\\<Sqinter>A = \\<top>\"\n    show \"\\<forall>x\\<in>A. x = \\<top>\"\n    proof (rule ccontr)\n      assume \"\\<not> (\\<forall>x\\<in>A. x = \\<top>)\"\n      then obtain x where \"x \\<in> A\" and \"x \\<noteq> \\<top>\" by blast\n      then obtain B where \"A = insert x B\" by blast\n      with `\\<Sqinter>A = \\<top>` `x \\<noteq> \\<top>` show False by simp\n    qed\n  qed\n  then show \"\\<top> = \\<Sqinter>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<top>)\" by auto\nqed\n\nlemma INF_top_conv [simp]:\n  \"(\\<Sqinter>x\\<in>A. B x) = \\<top> \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<top>)\"\n  \"\\<top> = (\\<Sqinter>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<top>)\"\n  using Inf_top_conv [of \"B ` A\"] by simp_all\n\nlemma Sup_bot_conv [simp]:\n  \"\\<Squnion>A = \\<bottom> \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<bottom>)\" (is ?P)\n  \"\\<bottom> = \\<Squnion>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = \\<bottom>)\" (is ?Q)\n  using dual_complete_lattice\n  by (rule complete_lattice.Inf_top_conv)+\n\nlemma SUP_bot_conv [simp]:\n \"(\\<Squnion>x\\<in>A. B x) = \\<bottom> \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<bottom>)\"\n \"\\<bottom> = (\\<Squnion>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = \\<bottom>)\"\n  using Sup_bot_conv [of \"B ` A\"] by simp_all\n\nlemma INF_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Sqinter>i\\<in>A. f) = f\"\n  by (auto intro: antisym INF_lower INF_greatest)\n\nlemma SUP_const [simp]: \"A \\<noteq> {} \\<Longrightarrow> (\\<Squnion>i\\<in>A. f) = f\"\n  by (auto intro: antisym SUP_upper SUP_least)\n\nlemma INF_top [simp]: \"(\\<Sqinter>x\\<in>A. \\<top>) = \\<top>\"\n  by (cases \"A = {}\") simp_all\n\nlemma SUP_bot [simp]: \"(\\<Squnion>x\\<in>A. \\<bottom>) = \\<bottom>\"\n  by (cases \"A = {}\") simp_all\n\nlemma INF_commute: \"(\\<Sqinter>i\\<in>A. \\<Sqinter>j\\<in>B. f i j) = (\\<Sqinter>j\\<in>B. \\<Sqinter>i\\<in>A. f i j)\"\n  by (iprover intro: INF_lower INF_greatest order_trans antisym)\n\nlemma SUP_commute: \"(\\<Squnion>i\\<in>A. \\<Squnion>j\\<in>B. f i j) = (\\<Squnion>j\\<in>B. \\<Squnion>i\\<in>A. f i j)\"\n  by (iprover intro: SUP_upper SUP_least order_trans antisym)\n\nlemma INF_absorb:\n  assumes \"k \\<in> I\"\n  shows \"A k \\<sqinter> (\\<Sqinter>i\\<in>I. A i) = (\\<Sqinter>i\\<in>I. A i)\"\nproof -\n  from assms obtain J where \"I = insert k J\" by blast\n  then show ?thesis by simp\nqed\n\nlemma SUP_absorb:\n  assumes \"k \\<in> I\"\n  shows \"A k \\<squnion> (\\<Squnion>i\\<in>I. A i) = (\\<Squnion>i\\<in>I. A i)\"\nproof -\n  from assms obtain J where \"I = insert k J\" by blast\n  then show ?thesis by simp\nqed\n\nlemma INF_inf_const1:\n  \"I \\<noteq> {} \\<Longrightarrow> (INF i:I. inf x (f i)) = inf x (INF i:I. f i)\"\n  by (intro antisym INF_greatest inf_mono order_refl INF_lower)\n     (auto intro: INF_lower2 le_infI2 intro!: INF_mono)\n\nlemma INF_inf_const2:\n  \"I \\<noteq> {} \\<Longrightarrow> (INF i:I. inf (f i) x) = inf (INF i:I. f i) x\"\n  using INF_inf_const1[of I x f] by (simp add: inf_commute)\n\nlemma INF_constant:\n  \"(\\<Sqinter>y\\<in>A. c) = (if A = {} then \\<top> else c)\"\n  by simp\n\nlemma SUP_constant:\n  \"(\\<Squnion>y\\<in>A. c) = (if A = {} then \\<bottom> else c)\"\n  by simp\n\nlemma less_INF_D:\n  assumes \"y < (\\<Sqinter>i\\<in>A. f i)\" \"i \\<in> A\" shows \"y < f i\"\nproof -\n  note `y < (\\<Sqinter>i\\<in>A. f i)`\n  also have \"(\\<Sqinter>i\\<in>A. f i) \\<le> f i\" using `i \\<in> A`\n    by (rule INF_lower)\n  finally show \"y < f i\" .\nqed\n\nlemma SUP_lessD:\n  assumes \"(\\<Squnion>i\\<in>A. f i) < y\" \"i \\<in> A\" shows \"f i < y\"\nproof -\n  have \"f i \\<le> (\\<Squnion>i\\<in>A. f i)\" using `i \\<in> A`\n    by (rule SUP_upper)\n  also note `(\\<Squnion>i\\<in>A. f i) < y`\n  finally show \"f i < y\" .\nqed\n\nlemma INF_UNIV_bool_expand:\n  \"(\\<Sqinter>b. A b) = A True \\<sqinter> A False\"\n  by (simp add: UNIV_bool inf_commute)\n\nlemma SUP_UNIV_bool_expand:\n  \"(\\<Squnion>b. A b) = A True \\<squnion> A False\"\n  by (simp add: UNIV_bool sup_commute)\n\nlemma Inf_le_Sup: \"A \\<noteq> {} \\<Longrightarrow> Inf A \\<le> Sup A\"\n  by (blast intro: Sup_upper2 Inf_lower ex_in_conv)\n\nlemma INF_le_SUP: \"A \\<noteq> {} \\<Longrightarrow> INFIMUM A f \\<le> SUPREMUM A f\"\n  using Inf_le_Sup [of \"f ` A\"] by simp\n\nlemma INF_eq_const:\n  \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i = x) \\<Longrightarrow> INFIMUM I f = x\"\n  by (auto intro: INF_eqI)\n\nlemma SUP_eq_const:\n  \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i = x) \\<Longrightarrow> SUPREMUM I f = x\"\n  by (auto intro: SUP_eqI)\n\nlemma INF_eq_iff:\n  \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> f i \\<le> c) \\<Longrightarrow> (INFIMUM I f = c) \\<longleftrightarrow> (\\<forall>i\\<in>I. f i = c)\"\n  using INF_eq_const [of I f c] INF_lower [of _ I f]\n  by (auto intro: antisym cong del: strong_INF_cong)\n\nlemma SUP_eq_iff:\n  \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> c \\<le> f i) \\<Longrightarrow> (SUPREMUM I f = c) \\<longleftrightarrow> (\\<forall>i\\<in>I. f i = c)\"\n  using SUP_eq_const [of I f c] SUP_upper [of _ I f]\n  by (auto intro: antisym cong del: strong_SUP_cong)\n\nend\n\nclass complete_distrib_lattice = complete_lattice +\n  assumes sup_Inf: \"a \\<squnion> \\<Sqinter>B = (\\<Sqinter>b\\<in>B. a \\<squnion> b)\"\n  assumes inf_Sup: \"a \\<sqinter> \\<Squnion>B = (\\<Squnion>b\\<in>B. a \\<sqinter> b)\"\nbegin\n\nlemma sup_INF:\n  \"a \\<squnion> (\\<Sqinter>b\\<in>B. f b) = (\\<Sqinter>b\\<in>B. a \\<squnion> f b)\"\n  by (simp only: INF_def sup_Inf image_image)\n\nlemma inf_SUP:\n  \"a \\<sqinter> (\\<Squnion>b\\<in>B. f b) = (\\<Squnion>b\\<in>B. a \\<sqinter> f b)\"\n  by (simp only: SUP_def inf_Sup image_image)\n\nlemma dual_complete_distrib_lattice:\n  \"class.complete_distrib_lattice Sup Inf sup (op \\<ge>) (op >) inf \\<top> \\<bottom>\"\n  apply (rule class.complete_distrib_lattice.intro)\n  apply (fact dual_complete_lattice)\n  apply (rule class.complete_distrib_lattice_axioms.intro)\n  apply (simp_all only: INF_foundation_dual SUP_foundation_dual inf_Sup sup_Inf)\n  done\n\nsubclass distrib_lattice proof\n  fix a b c\n  from sup_Inf have \"a \\<squnion> \\<Sqinter>{b, c} = (\\<Sqinter>d\\<in>{b, c}. a \\<squnion> d)\" .\n  then show \"a \\<squnion> b \\<sqinter> c = (a \\<squnion> b) \\<sqinter> (a \\<squnion> c)\" by (simp add: INF_def)\nqed\n\nlemma Inf_sup:\n  \"\\<Sqinter>B \\<squnion> a = (\\<Sqinter>b\\<in>B. b \\<squnion> a)\"\n  by (simp add: sup_Inf sup_commute)\n\nlemma Sup_inf:\n  \"\\<Squnion>B \\<sqinter> a = (\\<Squnion>b\\<in>B. b \\<sqinter> a)\"\n  by (simp add: inf_Sup inf_commute)\n\nlemma INF_sup: \n  \"(\\<Sqinter>b\\<in>B. f b) \\<squnion> a = (\\<Sqinter>b\\<in>B. f b \\<squnion> a)\"\n  by (simp add: sup_INF sup_commute)\n\nlemma SUP_inf:\n  \"(\\<Squnion>b\\<in>B. f b) \\<sqinter> a = (\\<Squnion>b\\<in>B. f b \\<sqinter> a)\"\n  by (simp add: inf_SUP inf_commute)\n\nlemma Inf_sup_eq_top_iff:\n  \"(\\<Sqinter>B \\<squnion> a = \\<top>) \\<longleftrightarrow> (\\<forall>b\\<in>B. b \\<squnion> a = \\<top>)\"\n  by (simp only: Inf_sup INF_top_conv)\n\nlemma Sup_inf_eq_bot_iff:\n  \"(\\<Squnion>B \\<sqinter> a = \\<bottom>) \\<longleftrightarrow> (\\<forall>b\\<in>B. b \\<sqinter> a = \\<bottom>)\"\n  by (simp only: Sup_inf SUP_bot_conv)\n\nlemma INF_sup_distrib2:\n  \"(\\<Sqinter>a\\<in>A. f a) \\<squnion> (\\<Sqinter>b\\<in>B. g b) = (\\<Sqinter>a\\<in>A. \\<Sqinter>b\\<in>B. f a \\<squnion> g b)\"\n  by (subst INF_commute) (simp add: sup_INF INF_sup)\n\nlemma SUP_inf_distrib2:\n  \"(\\<Squnion>a\\<in>A. f a) \\<sqinter> (\\<Squnion>b\\<in>B. g b) = (\\<Squnion>a\\<in>A. \\<Squnion>b\\<in>B. f a \\<sqinter> g b)\"\n  by (subst SUP_commute) (simp add: inf_SUP SUP_inf)\n\ncontext\n  fixes f :: \"'a \\<Rightarrow> 'b::complete_lattice\"\n  assumes \"mono f\"\nbegin\n\nlemma mono_Inf:\n  shows \"f (\\<Sqinter>A) \\<le> (\\<Sqinter>x\\<in>A. f x)\"\n  using `mono f` by (auto intro: complete_lattice_class.INF_greatest Inf_lower dest: monoD)\n\nlemma mono_Sup:\n  shows \"(\\<Squnion>x\\<in>A. f x) \\<le> f (\\<Squnion>A)\"\n  using `mono f` by (auto intro: complete_lattice_class.SUP_least Sup_upper dest: monoD)\n\nend\n\nend\n\nclass complete_boolean_algebra = boolean_algebra + complete_distrib_lattice\nbegin\n\nlemma dual_complete_boolean_algebra:\n  \"class.complete_boolean_algebra Sup Inf sup (op \\<ge>) (op >) inf \\<top> \\<bottom> (\\<lambda>x y. x \\<squnion> - y) uminus\"\n  by (rule class.complete_boolean_algebra.intro, rule dual_complete_distrib_lattice, rule dual_boolean_algebra)\n\nlemma uminus_Inf:\n  \"- (\\<Sqinter>A) = \\<Squnion>(uminus ` A)\"\nproof (rule antisym)\n  show \"- \\<Sqinter>A \\<le> \\<Squnion>(uminus ` A)\"\n    by (rule compl_le_swap2, rule Inf_greatest, rule compl_le_swap2, rule Sup_upper) simp\n  show \"\\<Squnion>(uminus ` A) \\<le> - \\<Sqinter>A\"\n    by (rule Sup_least, rule compl_le_swap1, rule Inf_lower) auto\nqed\n\nlemma uminus_INF: \"- (\\<Sqinter>x\\<in>A. B x) = (\\<Squnion>x\\<in>A. - B x)\"\n  by (simp only: INF_def SUP_def uminus_Inf image_image)\n\nlemma uminus_Sup:\n  \"- (\\<Squnion>A) = \\<Sqinter>(uminus ` A)\"\nproof -\n  have \"\\<Squnion>A = - \\<Sqinter>(uminus ` A)\" by (simp add: image_image uminus_INF)\n  then show ?thesis by simp\nqed\n  \nlemma uminus_SUP: \"- (\\<Squnion>x\\<in>A. B x) = (\\<Sqinter>x\\<in>A. - B x)\"\n  by (simp only: INF_def SUP_def uminus_Sup image_image)\n\nend\n\nclass complete_linorder = linorder + complete_lattice\nbegin\n\nlemma dual_complete_linorder:\n  \"class.complete_linorder Sup Inf sup (op \\<ge>) (op >) inf \\<top> \\<bottom>\"\n  by (rule class.complete_linorder.intro, rule dual_complete_lattice, rule dual_linorder)\n\nlemma complete_linorder_inf_min: \"inf = min\"\n  by (auto intro: antisym simp add: min_def fun_eq_iff)\n\nlemma complete_linorder_sup_max: \"sup = max\"\n  by (auto intro: antisym simp add: max_def fun_eq_iff)\n\nlemma Inf_less_iff:\n  \"\\<Sqinter>S \\<sqsubset> a \\<longleftrightarrow> (\\<exists>x\\<in>S. x \\<sqsubset> a)\"\n  unfolding not_le [symmetric] le_Inf_iff by auto\n\nlemma INF_less_iff:\n  \"(\\<Sqinter>i\\<in>A. f i) \\<sqsubset> a \\<longleftrightarrow> (\\<exists>x\\<in>A. f x \\<sqsubset> a)\"\n  using Inf_less_iff [of \"f ` A\"] by simp\n\nlemma less_Sup_iff:\n  \"a \\<sqsubset> \\<Squnion>S \\<longleftrightarrow> (\\<exists>x\\<in>S. a \\<sqsubset> x)\"\n  unfolding not_le [symmetric] Sup_le_iff by auto\n\nlemma less_SUP_iff:\n  \"a \\<sqsubset> (\\<Squnion>i\\<in>A. f i) \\<longleftrightarrow> (\\<exists>x\\<in>A. a \\<sqsubset> f x)\"\n  using less_Sup_iff [of _ \"f ` A\"] by simp\n\nlemma Sup_eq_top_iff [simp]:\n  \"\\<Squnion>A = \\<top> \\<longleftrightarrow> (\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < i)\"\nproof\n  assume *: \"\\<Squnion>A = \\<top>\"\n  show \"(\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < i)\" unfolding * [symmetric]\n  proof (intro allI impI)\n    fix x assume \"x < \\<Squnion>A\" then show \"\\<exists>i\\<in>A. x < i\"\n      unfolding less_Sup_iff by auto\n  qed\nnext\n  assume *: \"\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < i\"\n  show \"\\<Squnion>A = \\<top>\"\n  proof (rule ccontr)\n    assume \"\\<Squnion>A \\<noteq> \\<top>\"\n    with top_greatest [of \"\\<Squnion>A\"]\n    have \"\\<Squnion>A < \\<top>\" unfolding le_less by auto\n    then have \"\\<Squnion>A < \\<Squnion>A\"\n      using * unfolding less_Sup_iff by auto\n    then show False by auto\n  qed\nqed\n\nlemma SUP_eq_top_iff [simp]:\n  \"(\\<Squnion>i\\<in>A. f i) = \\<top> \\<longleftrightarrow> (\\<forall>x<\\<top>. \\<exists>i\\<in>A. x < f i)\"\n  using Sup_eq_top_iff [of \"f ` A\"] by simp\n\nlemma Inf_eq_bot_iff [simp]:\n  \"\\<Sqinter>A = \\<bottom> \\<longleftrightarrow> (\\<forall>x>\\<bottom>. \\<exists>i\\<in>A. i < x)\"\n  using dual_complete_linorder\n  by (rule complete_linorder.Sup_eq_top_iff)\n\nlemma INF_eq_bot_iff [simp]:\n  \"(\\<Sqinter>i\\<in>A. f i) = \\<bottom> \\<longleftrightarrow> (\\<forall>x>\\<bottom>. \\<exists>i\\<in>A. f i < x)\"\n  using Inf_eq_bot_iff [of \"f ` A\"] by simp\n\nlemma Inf_le_iff: \"\\<Sqinter>A \\<le> x \\<longleftrightarrow> (\\<forall>y>x. \\<exists>a\\<in>A. y > a)\"\nproof safe\n  fix y assume \"x \\<ge> \\<Sqinter>A\" \"y > x\"\n  then have \"y > \\<Sqinter>A\" by auto\n  then show \"\\<exists>a\\<in>A. y > a\"\n    unfolding Inf_less_iff .\nqed (auto elim!: allE[of _ \"\\<Sqinter>A\"] simp add: not_le[symmetric] Inf_lower)\n\nlemma INF_le_iff:\n  \"INFIMUM A f \\<le> x \\<longleftrightarrow> (\\<forall>y>x. \\<exists>i\\<in>A. y > f i)\"\n  using Inf_le_iff [of \"f ` A\"] by simp\n\nlemma le_Sup_iff: \"x \\<le> \\<Squnion>A \\<longleftrightarrow> (\\<forall>y<x. \\<exists>a\\<in>A. y < a)\"\nproof safe\n  fix y assume \"x \\<le> \\<Squnion>A\" \"y < x\"\n  then have \"y < \\<Squnion>A\" by auto\n  then show \"\\<exists>a\\<in>A. y < a\"\n    unfolding less_Sup_iff .\nqed (auto elim!: allE[of _ \"\\<Squnion>A\"] simp add: not_le[symmetric] Sup_upper)\n\nlemma le_SUP_iff: \"x \\<le> SUPREMUM A f \\<longleftrightarrow> (\\<forall>y<x. \\<exists>i\\<in>A. y < f i)\"\n  using le_Sup_iff [of _ \"f ` A\"] by simp\n\nsubclass complete_distrib_lattice\nproof\n  fix a and B\n  show \"a \\<squnion> \\<Sqinter>B = (\\<Sqinter>b\\<in>B. a \\<squnion> b)\" and \"a \\<sqinter> \\<Squnion>B = (\\<Squnion>b\\<in>B. a \\<sqinter> b)\"\n    by (safe intro!: INF_eqI [symmetric] sup_mono Inf_lower SUP_eqI [symmetric] inf_mono Sup_upper)\n      (auto simp: not_less [symmetric] Inf_less_iff less_Sup_iff\n        le_max_iff_disj complete_linorder_sup_max min_le_iff_disj complete_linorder_inf_min)\nqed\n\nend\n\n\nsubsection {* Complete lattice on @{typ bool} *}\n\ninstantiation bool :: complete_lattice\nbegin\n\ndefinition\n  [simp, code]: \"\\<Sqinter>A \\<longleftrightarrow> False \\<notin> A\"\n\ndefinition\n  [simp, code]: \"\\<Squnion>A \\<longleftrightarrow> True \\<in> A\"\n\ninstance proof\nqed (auto intro: bool_induct)\n\nend\n\nlemma not_False_in_image_Ball [simp]:\n  \"False \\<notin> P ` A \\<longleftrightarrow> Ball A P\"\n  by auto\n\nlemma True_in_image_Bex [simp]:\n  \"True \\<in> P ` A \\<longleftrightarrow> Bex A P\"\n  by auto\n\nlemma INF_bool_eq [simp]:\n  \"INFIMUM = Ball\"\n  by (simp add: fun_eq_iff INF_def)\n\nlemma SUP_bool_eq [simp]:\n  \"SUPREMUM = Bex\"\n  by (simp add: fun_eq_iff SUP_def)\n\ninstance bool :: complete_boolean_algebra proof\nqed (auto intro: bool_induct)\n\n\nsubsection {* Complete lattice on @{typ \"_ \\<Rightarrow> _\"} *}\n\ninstantiation \"fun\" :: (type, Inf) Inf\nbegin\n\ndefinition\n  \"\\<Sqinter>A = (\\<lambda>x. \\<Sqinter>f\\<in>A. f x)\"\n\nlemma Inf_apply [simp, code]:\n  \"(\\<Sqinter>A) x = (\\<Sqinter>f\\<in>A. f x)\"\n  by (simp add: Inf_fun_def)\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, Sup) Sup\nbegin\n\ndefinition\n  \"\\<Squnion>A = (\\<lambda>x. \\<Squnion>f\\<in>A. f x)\"\n\nlemma Sup_apply [simp, code]:\n  \"(\\<Squnion>A) x = (\\<Squnion>f\\<in>A. f x)\"\n  by (simp add: Sup_fun_def)\n\ninstance ..\n\nend\n\ninstantiation \"fun\" :: (type, complete_lattice) complete_lattice\nbegin\n\ninstance proof\nqed (auto simp add: le_fun_def intro: INF_lower INF_greatest SUP_upper SUP_least)\n\nend\n\nlemma INF_apply [simp]:\n  \"(\\<Sqinter>y\\<in>A. f y) x = (\\<Sqinter>y\\<in>A. f y x)\"\n  using Inf_apply [of \"f ` A\"] by (simp add: comp_def)\n\nlemma SUP_apply [simp]:\n  \"(\\<Squnion>y\\<in>A. f y) x = (\\<Squnion>y\\<in>A. f y x)\"\n  using Sup_apply [of \"f ` A\"] by (simp add: comp_def)\n\ninstance \"fun\" :: (type, complete_distrib_lattice) complete_distrib_lattice proof\nqed (auto simp add: INF_def SUP_def inf_Sup sup_Inf fun_eq_iff image_image\n  simp del: Inf_image_eq Sup_image_eq)\n\ninstance \"fun\" :: (type, complete_boolean_algebra) complete_boolean_algebra ..\n\n\nsubsection {* Complete lattice on unary and binary predicates *}\n\nlemma Inf1_I: \n  \"(\\<And>P. P \\<in> A \\<Longrightarrow> P a) \\<Longrightarrow> (\\<Sqinter>A) a\"\n  by auto\n\nlemma INF1_I:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x b) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. B x) b\"\n  by simp\n\nlemma INF2_I:\n  \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x b c) \\<Longrightarrow> (\\<Sqinter>x\\<in>A. B x) b c\"\n  by simp\n\nlemma Inf2_I: \n  \"(\\<And>r. r \\<in> A \\<Longrightarrow> r a b) \\<Longrightarrow> (\\<Sqinter>A) a b\"\n  by auto\n\nlemma Inf1_D:\n  \"(\\<Sqinter>A) a \\<Longrightarrow> P \\<in> A \\<Longrightarrow> P a\"\n  by auto\n\nlemma INF1_D:\n  \"(\\<Sqinter>x\\<in>A. B x) b \\<Longrightarrow> a \\<in> A \\<Longrightarrow> B a b\"\n  by simp\n\nlemma Inf2_D:\n  \"(\\<Sqinter>A) a b \\<Longrightarrow> r \\<in> A \\<Longrightarrow> r a b\"\n  by auto\n\nlemma INF2_D:\n  \"(\\<Sqinter>x\\<in>A. B x) b c \\<Longrightarrow> a \\<in> A \\<Longrightarrow> B a b c\"\n  by simp\n\nlemma Inf1_E:\n  assumes \"(\\<Sqinter>A) a\"\n  obtains \"P a\" | \"P \\<notin> A\"\n  using assms by auto\n\nlemma INF1_E:\n  assumes \"(\\<Sqinter>x\\<in>A. B x) b\"\n  obtains \"B a b\" | \"a \\<notin> A\"\n  using assms by auto\n\nlemma Inf2_E:\n  assumes \"(\\<Sqinter>A) a b\"\n  obtains \"r a b\" | \"r \\<notin> A\"\n  using assms by auto\n\nlemma INF2_E:\n  assumes \"(\\<Sqinter>x\\<in>A. B x) b c\"\n  obtains \"B a b c\" | \"a \\<notin> A\"\n  using assms by auto\n\nlemma Sup1_I:\n  \"P \\<in> A \\<Longrightarrow> P a \\<Longrightarrow> (\\<Squnion>A) a\"\n  by auto\n\nlemma SUP1_I:\n  \"a \\<in> A \\<Longrightarrow> B a b \\<Longrightarrow> (\\<Squnion>x\\<in>A. B x) b\"\n  by auto\n\nlemma Sup2_I:\n  \"r \\<in> A \\<Longrightarrow> r a b \\<Longrightarrow> (\\<Squnion>A) a b\"\n  by auto\n\nlemma SUP2_I:\n  \"a \\<in> A \\<Longrightarrow> B a b c \\<Longrightarrow> (\\<Squnion>x\\<in>A. B x) b c\"\n  by auto\n\nlemma Sup1_E:\n  assumes \"(\\<Squnion>A) a\"\n  obtains P where \"P \\<in> A\" and \"P a\"\n  using assms by auto\n\nlemma SUP1_E:\n  assumes \"(\\<Squnion>x\\<in>A. B x) b\"\n  obtains x where \"x \\<in> A\" and \"B x b\"\n  using assms by auto\n\nlemma Sup2_E:\n  assumes \"(\\<Squnion>A) a b\"\n  obtains r where \"r \\<in> A\" \"r a b\"\n  using assms by auto\n\nlemma SUP2_E:\n  assumes \"(\\<Squnion>x\\<in>A. B x) b c\"\n  obtains x where \"x \\<in> A\" \"B x b c\"\n  using assms by auto\n\n\nsubsection {* Complete lattice on @{typ \"_ set\"} *}\n\ninstantiation \"set\" :: (type) complete_lattice\nbegin\n\ndefinition\n  \"\\<Sqinter>A = {x. \\<Sqinter>((\\<lambda>B. x \\<in> B) ` A)}\"\n\ndefinition\n  \"\\<Squnion>A = {x. \\<Squnion>((\\<lambda>B. x \\<in> B) ` A)}\"\n\ninstance proof\nqed (auto simp add: less_eq_set_def Inf_set_def Sup_set_def le_fun_def)\n\nend\n\ninstance \"set\" :: (type) complete_boolean_algebra\nproof\nqed (auto simp add: INF_def SUP_def Inf_set_def Sup_set_def image_def)\n  \n\nsubsubsection {* Inter *}\n\nabbreviation Inter :: \"'a set set \\<Rightarrow> 'a set\" where\n  \"Inter S \\<equiv> \\<Sqinter>S\"\n  \nnotation (xsymbols)\n  Inter  (\"\\<Inter>_\" [900] 900)\n\nlemma Inter_eq:\n  \"\\<Inter>A = {x. \\<forall>B \\<in> A. x \\<in> B}\"\nproof (rule set_eqI)\n  fix x\n  have \"(\\<forall>Q\\<in>{P. \\<exists>B\\<in>A. P \\<longleftrightarrow> x \\<in> B}. Q) \\<longleftrightarrow> (\\<forall>B\\<in>A. x \\<in> B)\"\n    by auto\n  then show \"x \\<in> \\<Inter>A \\<longleftrightarrow> x \\<in> {x. \\<forall>B \\<in> A. x \\<in> B}\"\n    by (simp add: Inf_set_def image_def)\nqed\n\nlemma Inter_iff [simp]: \"A \\<in> \\<Inter>C \\<longleftrightarrow> (\\<forall>X\\<in>C. A \\<in> X)\"\n  by (unfold Inter_eq) blast\n\nlemma InterI [intro!]: \"(\\<And>X. X \\<in> C \\<Longrightarrow> A \\<in> X) \\<Longrightarrow> A \\<in> \\<Inter>C\"\n  by (simp add: Inter_eq)\n\ntext {*\n  \\medskip A ``destruct'' rule -- every @{term X} in @{term C}\n  contains @{term A} as an element, but @{prop \"A \\<in> X\"} can hold when\n  @{prop \"X \\<in> C\"} does not!  This rule is analogous to @{text spec}.\n*}\n\nlemma InterD [elim, Pure.elim]: \"A \\<in> \\<Inter>C \\<Longrightarrow> X \\<in> C \\<Longrightarrow> A \\<in> X\"\n  by auto\n\nlemma InterE [elim]: \"A \\<in> \\<Inter>C \\<Longrightarrow> (X \\<notin> C \\<Longrightarrow> R) \\<Longrightarrow> (A \\<in> X \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  -- {* ``Classical'' elimination rule -- does not require proving\n    @{prop \"X \\<in> C\"}. *}\n  by (unfold Inter_eq) blast\n\nlemma Inter_lower: \"B \\<in> A \\<Longrightarrow> \\<Inter>A \\<subseteq> B\"\n  by (fact Inf_lower)\n\nlemma Inter_subset:\n  \"(\\<And>X. X \\<in> A \\<Longrightarrow> X \\<subseteq> B) \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \\<Inter>A \\<subseteq> B\"\n  by (fact Inf_less_eq)\n\nlemma Inter_greatest: \"(\\<And>X. X \\<in> A \\<Longrightarrow> C \\<subseteq> X) \\<Longrightarrow> C \\<subseteq> Inter A\"\n  by (fact Inf_greatest)\n\nlemma Inter_empty: \"\\<Inter>{} = UNIV\"\n  by (fact Inf_empty) (* already simp *)\n\nlemma Inter_UNIV: \"\\<Inter>UNIV = {}\"\n  by (fact Inf_UNIV) (* already simp *)\n\nlemma Inter_insert: \"\\<Inter>(insert a B) = a \\<inter> \\<Inter>B\"\n  by (fact Inf_insert) (* already simp *)\n\nlemma Inter_Un_subset: \"\\<Inter>A \\<union> \\<Inter>B \\<subseteq> \\<Inter>(A \\<inter> B)\"\n  by (fact less_eq_Inf_inter)\n\nlemma Inter_Un_distrib: \"\\<Inter>(A \\<union> B) = \\<Inter>A \\<inter> \\<Inter>B\"\n  by (fact Inf_union_distrib)\n\nlemma Inter_UNIV_conv [simp]:\n  \"\\<Inter>A = UNIV \\<longleftrightarrow> (\\<forall>x\\<in>A. x = UNIV)\"\n  \"UNIV = \\<Inter>A \\<longleftrightarrow> (\\<forall>x\\<in>A. x = UNIV)\"\n  by (fact Inf_top_conv)+\n\nlemma Inter_anti_mono: \"B \\<subseteq> A \\<Longrightarrow> \\<Inter>A \\<subseteq> \\<Inter>B\"\n  by (fact Inf_superset_mono)\n\n\nsubsubsection {* Intersections of families *}\n\nabbreviation INTER :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b set\" where\n  \"INTER \\<equiv> INFIMUM\"\n\ntext {*\n  Note: must use name @{const INTER} here instead of @{text INT}\n  to allow the following syntax coexist with the plain constant name.\n*}\n\nsyntax\n  \"_INTER1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3INT _./ _)\" [0, 10] 10)\n  \"_INTER\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3INT _:_./ _)\" [0, 0, 10] 10)\n\nsyntax (xsymbols)\n  \"_INTER1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3\\<Inter>_./ _)\" [0, 10] 10)\n  \"_INTER\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3\\<Inter>_\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax (latex output)\n  \"_INTER1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3\\<Inter>(00\\<^bsub>_\\<^esub>)/ _)\" [0, 10] 10)\n  \"_INTER\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3\\<Inter>(00\\<^bsub>_\\<in>_\\<^esub>)/ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"INT x y. B\"  == \"INT x. INT y. B\"\n  \"INT x. B\"    == \"CONST INTER CONST UNIV (%x. B)\"\n  \"INT x. B\"    == \"INT x:CONST UNIV. B\"\n  \"INT x:A. B\"  == \"CONST INTER A (%x. B)\"\n\nprint_translation {*\n  [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax INTER} @{syntax_const \"_INTER\"}]\n*} -- {* to avoid eta-contraction of body *}\n\nlemma INTER_eq:\n  \"(\\<Inter>x\\<in>A. B x) = {y. \\<forall>x\\<in>A. y \\<in> B x}\"\n  by (auto intro!: INF_eqI)\n\nlemma Inter_image_eq:\n  \"\\<Inter>(B ` A) = (\\<Inter>x\\<in>A. B x)\"\n  by (fact Inf_image_eq)\n\nlemma INT_iff [simp]: \"b \\<in> (\\<Inter>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. b \\<in> B x)\"\n  using Inter_iff [of _ \"B ` A\"] by simp\n\nlemma INT_I [intro!]: \"(\\<And>x. x \\<in> A \\<Longrightarrow> b \\<in> B x) \\<Longrightarrow> b \\<in> (\\<Inter>x\\<in>A. B x)\"\n  by (auto simp add: INF_def image_def)\n\nlemma INT_D [elim, Pure.elim]: \"b \\<in> (\\<Inter>x\\<in>A. B x) \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> B a\"\n  by auto\n\nlemma INT_E [elim]: \"b \\<in> (\\<Inter>x\\<in>A. B x) \\<Longrightarrow> (b \\<in> B a \\<Longrightarrow> R) \\<Longrightarrow> (a \\<notin> A \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  -- {* \"Classical\" elimination -- by the Excluded Middle on @{prop \"a\\<in>A\"}. *}\n  by (auto simp add: INF_def image_def)\n\nlemma Collect_ball_eq: \"{x. \\<forall>y\\<in>A. P x y} = (\\<Inter>y\\<in>A. {x. P x y})\"\n  by blast\n\nlemma Collect_all_eq: \"{x. \\<forall>y. P x y} = (\\<Inter>y. {x. P x y})\"\n  by blast\n\nlemma INT_lower: \"a \\<in> A \\<Longrightarrow> (\\<Inter>x\\<in>A. B x) \\<subseteq> B a\"\n  by (fact INF_lower)\n\nlemma INT_greatest: \"(\\<And>x. x \\<in> A \\<Longrightarrow> C \\<subseteq> B x) \\<Longrightarrow> C \\<subseteq> (\\<Inter>x\\<in>A. B x)\"\n  by (fact INF_greatest)\n\nlemma INT_empty: \"(\\<Inter>x\\<in>{}. B x) = UNIV\"\n  by (fact INF_empty)\n\nlemma INT_absorb: \"k \\<in> I \\<Longrightarrow> A k \\<inter> (\\<Inter>i\\<in>I. A i) = (\\<Inter>i\\<in>I. A i)\"\n  by (fact INF_absorb)\n\nlemma INT_subset_iff: \"B \\<subseteq> (\\<Inter>i\\<in>I. A i) \\<longleftrightarrow> (\\<forall>i\\<in>I. B \\<subseteq> A i)\"\n  by (fact le_INF_iff)\n\nlemma INT_insert [simp]: \"(\\<Inter>x \\<in> insert a A. B x) = B a \\<inter> INTER A B\"\n  by (fact INF_insert)\n\nlemma INT_Un: \"(\\<Inter>i \\<in> A \\<union> B. M i) = (\\<Inter>i \\<in> A. M i) \\<inter> (\\<Inter>i\\<in>B. M i)\"\n  by (fact INF_union)\n\nlemma INT_insert_distrib:\n  \"u \\<in> A \\<Longrightarrow> (\\<Inter>x\\<in>A. insert a (B x)) = insert a (\\<Inter>x\\<in>A. B x)\"\n  by blast\n\nlemma INT_constant [simp]: \"(\\<Inter>y\\<in>A. c) = (if A = {} then UNIV else c)\"\n  by (fact INF_constant)\n\nlemma INTER_UNIV_conv:\n \"(UNIV = (\\<Inter>x\\<in>A. B x)) = (\\<forall>x\\<in>A. B x = UNIV)\"\n \"((\\<Inter>x\\<in>A. B x) = UNIV) = (\\<forall>x\\<in>A. B x = UNIV)\"\n  by (fact INF_top_conv)+ (* already simp *)\n\nlemma INT_bool_eq: \"(\\<Inter>b. A b) = A True \\<inter> A False\"\n  by (fact INF_UNIV_bool_expand)\n\nlemma INT_anti_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<subseteq> g x) \\<Longrightarrow> (\\<Inter>x\\<in>B. f x) \\<subseteq> (\\<Inter>x\\<in>A. g x)\"\n  -- {* The last inclusion is POSITIVE! *}\n  by (fact INF_superset_mono)\n\nlemma Pow_INT_eq: \"Pow (\\<Inter>x\\<in>A. B x) = (\\<Inter>x\\<in>A. Pow (B x))\"\n  by blast\n\nlemma vimage_INT: \"f -` (\\<Inter>x\\<in>A. B x) = (\\<Inter>x\\<in>A. f -` B x)\"\n  by blast\n\n\nsubsubsection {* Union *}\n\nabbreviation Union :: \"'a set set \\<Rightarrow> 'a set\" where\n  \"Union S \\<equiv> \\<Squnion>S\"\n\nnotation (xsymbols)\n  Union  (\"\\<Union>_\" [900] 900)\n\nlemma Union_eq:\n  \"\\<Union>A = {x. \\<exists>B \\<in> A. x \\<in> B}\"\nproof (rule set_eqI)\n  fix x\n  have \"(\\<exists>Q\\<in>{P. \\<exists>B\\<in>A. P \\<longleftrightarrow> x \\<in> B}. Q) \\<longleftrightarrow> (\\<exists>B\\<in>A. x \\<in> B)\"\n    by auto\n  then show \"x \\<in> \\<Union>A \\<longleftrightarrow> x \\<in> {x. \\<exists>B\\<in>A. x \\<in> B}\"\n    by (simp add: Sup_set_def image_def)\nqed\n\nlemma Union_iff [simp]:\n  \"A \\<in> \\<Union>C \\<longleftrightarrow> (\\<exists>X\\<in>C. A\\<in>X)\"\n  by (unfold Union_eq) blast\n\nlemma UnionI [intro]:\n  \"X \\<in> C \\<Longrightarrow> A \\<in> X \\<Longrightarrow> A \\<in> \\<Union>C\"\n  -- {* The order of the premises presupposes that @{term C} is rigid;\n    @{term A} may be flexible. *}\n  by auto\n\nlemma UnionE [elim!]:\n  \"A \\<in> \\<Union>C \\<Longrightarrow> (\\<And>X. A \\<in> X \\<Longrightarrow> X \\<in> C \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by auto\n\nlemma Union_upper: \"B \\<in> A \\<Longrightarrow> B \\<subseteq> \\<Union>A\"\n  by (fact Sup_upper)\n\nlemma Union_least: \"(\\<And>X. X \\<in> A \\<Longrightarrow> X \\<subseteq> C) \\<Longrightarrow> \\<Union>A \\<subseteq> C\"\n  by (fact Sup_least)\n\nlemma Union_empty: \"\\<Union>{} = {}\"\n  by (fact Sup_empty) (* already simp *)\n\nlemma Union_UNIV: \"\\<Union>UNIV = UNIV\"\n  by (fact Sup_UNIV) (* already simp *)\n\nlemma Union_insert: \"\\<Union>insert a B = a \\<union> \\<Union>B\"\n  by (fact Sup_insert) (* already simp *)\n\nlemma Union_Un_distrib [simp]: \"\\<Union>(A \\<union> B) = \\<Union>A \\<union> \\<Union>B\"\n  by (fact Sup_union_distrib)\n\nlemma Union_Int_subset: \"\\<Union>(A \\<inter> B) \\<subseteq> \\<Union>A \\<inter> \\<Union>B\"\n  by (fact Sup_inter_less_eq)\n\nlemma Union_empty_conv: \"(\\<Union>A = {}) \\<longleftrightarrow> (\\<forall>x\\<in>A. x = {})\"\n  by (fact Sup_bot_conv) (* already simp *)\n\nlemma empty_Union_conv: \"({} = \\<Union>A) \\<longleftrightarrow> (\\<forall>x\\<in>A. x = {})\"\n  by (fact Sup_bot_conv) (* already simp *)\n\nlemma subset_Pow_Union: \"A \\<subseteq> Pow (\\<Union>A)\"\n  by blast\n\nlemma Union_Pow_eq [simp]: \"\\<Union>(Pow A) = A\"\n  by blast\n\nlemma Union_mono: \"A \\<subseteq> B \\<Longrightarrow> \\<Union>A \\<subseteq> \\<Union>B\"\n  by (fact Sup_subset_mono)\n\n\nsubsubsection {* Unions of families *}\n\nabbreviation UNION :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'b set) \\<Rightarrow> 'b set\" where\n  \"UNION \\<equiv> SUPREMUM\"\n\ntext {*\n  Note: must use name @{const UNION} here instead of @{text UN}\n  to allow the following syntax coexist with the plain constant name.\n*}\n\nsyntax\n  \"_UNION1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3UN _./ _)\" [0, 10] 10)\n  \"_UNION\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3UN _:_./ _)\" [0, 0, 10] 10)\n\nsyntax (xsymbols)\n  \"_UNION1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3\\<Union>_./ _)\" [0, 10] 10)\n  \"_UNION\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3\\<Union>_\\<in>_./ _)\" [0, 0, 10] 10)\n\nsyntax (latex output)\n  \"_UNION1\"     :: \"pttrns => 'b set => 'b set\"           (\"(3\\<Union>(00\\<^bsub>_\\<^esub>)/ _)\" [0, 10] 10)\n  \"_UNION\"      :: \"pttrn => 'a set => 'b set => 'b set\"  (\"(3\\<Union>(00\\<^bsub>_\\<in>_\\<^esub>)/ _)\" [0, 0, 10] 10)\n\ntranslations\n  \"UN x y. B\"   == \"UN x. UN y. B\"\n  \"UN x. B\"     == \"CONST UNION CONST UNIV (%x. B)\"\n  \"UN x. B\"     == \"UN x:CONST UNIV. B\"\n  \"UN x:A. B\"   == \"CONST UNION A (%x. B)\"\n\ntext {*\n  Note the difference between ordinary xsymbol syntax of indexed\n  unions and intersections (e.g.\\ @{text\"\\<Union>a\\<^sub>1\\<in>A\\<^sub>1. B\"})\n  and their \\LaTeX\\ rendition: @{term\"\\<Union>a\\<^sub>1\\<in>A\\<^sub>1. B\"}. The\n  former does not make the index expression a subscript of the\n  union/intersection symbol because this leads to problems with nested\n  subscripts in Proof General.\n*}\n\nprint_translation {*\n  [Syntax_Trans.preserve_binder_abs2_tr' @{const_syntax UNION} @{syntax_const \"_UNION\"}]\n*} -- {* to avoid eta-contraction of body *}\n\nlemma UNION_eq:\n  \"(\\<Union>x\\<in>A. B x) = {y. \\<exists>x\\<in>A. y \\<in> B x}\"\n  by (auto intro!: SUP_eqI)\n\nlemma bind_UNION [code]:\n  \"Set.bind A f = UNION A f\"\n  by (simp add: bind_def UNION_eq)\n\nlemma member_bind [simp]:\n  \"x \\<in> Set.bind P f \\<longleftrightarrow> x \\<in> UNION P f \"\n  by (simp add: bind_UNION)\n\nlemma Union_image_eq:\n  \"\\<Union>(B ` A) = (\\<Union>x\\<in>A. B x)\"\n  by (fact Sup_image_eq)\n\nlemma UN_iff [simp]: \"b \\<in> (\\<Union>x\\<in>A. B x) \\<longleftrightarrow> (\\<exists>x\\<in>A. b \\<in> B x)\"\n  using Union_iff [of _ \"B ` A\"] by simp\n\nlemma UN_I [intro]: \"a \\<in> A \\<Longrightarrow> b \\<in> B a \\<Longrightarrow> b \\<in> (\\<Union>x\\<in>A. B x)\"\n  -- {* The order of the premises presupposes that @{term A} is rigid;\n    @{term b} may be flexible. *}\n  by auto\n\nlemma UN_E [elim!]: \"b \\<in> (\\<Union>x\\<in>A. B x) \\<Longrightarrow> (\\<And>x. x\\<in>A \\<Longrightarrow> b \\<in> B x \\<Longrightarrow> R) \\<Longrightarrow> R\"\n  by (auto simp add: SUP_def image_def)\n\nlemma image_eq_UN: \"f ` A = (\\<Union>x\\<in>A. {f x})\"\n  by blast\n\nlemma UN_upper: \"a \\<in> A \\<Longrightarrow> B a \\<subseteq> (\\<Union>x\\<in>A. B x)\"\n  by (fact SUP_upper)\n\nlemma UN_least: \"(\\<And>x. x \\<in> A \\<Longrightarrow> B x \\<subseteq> C) \\<Longrightarrow> (\\<Union>x\\<in>A. B x) \\<subseteq> C\"\n  by (fact SUP_least)\n\nlemma Collect_bex_eq: \"{x. \\<exists>y\\<in>A. P x y} = (\\<Union>y\\<in>A. {x. P x y})\"\n  by blast\n\nlemma UN_insert_distrib: \"u \\<in> A \\<Longrightarrow> (\\<Union>x\\<in>A. insert a (B x)) = insert a (\\<Union>x\\<in>A. B x)\"\n  by blast\n\nlemma UN_empty: \"(\\<Union>x\\<in>{}. B x) = {}\"\n  by (fact SUP_empty)\n\nlemma UN_empty2: \"(\\<Union>x\\<in>A. {}) = {}\"\n  by (fact SUP_bot) (* already simp *)\n\nlemma UN_absorb: \"k \\<in> I \\<Longrightarrow> A k \\<union> (\\<Union>i\\<in>I. A i) = (\\<Union>i\\<in>I. A i)\"\n  by (fact SUP_absorb)\n\nlemma UN_insert [simp]: \"(\\<Union>x\\<in>insert a A. B x) = B a \\<union> UNION A B\"\n  by (fact SUP_insert)\n\nlemma UN_Un [simp]: \"(\\<Union>i \\<in> A \\<union> B. M i) = (\\<Union>i\\<in>A. M i) \\<union> (\\<Union>i\\<in>B. M i)\"\n  by (fact SUP_union)\n\nlemma UN_UN_flatten: \"(\\<Union>x \\<in> (\\<Union>y\\<in>A. B y). C x) = (\\<Union>y\\<in>A. \\<Union>x\\<in>B y. C x)\"\n  by blast\n\nlemma UN_subset_iff: \"((\\<Union>i\\<in>I. A i) \\<subseteq> B) = (\\<forall>i\\<in>I. A i \\<subseteq> B)\"\n  by (fact SUP_le_iff)\n\nlemma UN_constant [simp]: \"(\\<Union>y\\<in>A. c) = (if A = {} then {} else c)\"\n  by (fact SUP_constant)\n\nlemma image_Union: \"f ` \\<Union>S = (\\<Union>x\\<in>S. f ` x)\"\n  by blast\n\nlemma UNION_empty_conv:\n  \"{} = (\\<Union>x\\<in>A. B x) \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = {})\"\n  \"(\\<Union>x\\<in>A. B x) = {} \\<longleftrightarrow> (\\<forall>x\\<in>A. B x = {})\"\n  by (fact SUP_bot_conv)+ (* already simp *)\n\nlemma Collect_ex_eq: \"{x. \\<exists>y. P x y} = (\\<Union>y. {x. P x y})\"\n  by blast\n\nlemma ball_UN: \"(\\<forall>z \\<in> UNION A B. P z) \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>z \\<in> B x. P z)\"\n  by blast\n\nlemma bex_UN: \"(\\<exists>z \\<in> UNION A B. P z) \\<longleftrightarrow> (\\<exists>x\\<in>A. \\<exists>z\\<in>B x. P z)\"\n  by blast\n\nlemma Un_eq_UN: \"A \\<union> B = (\\<Union>b. if b then A else B)\"\n  by (auto simp add: split_if_mem2)\n\nlemma UN_bool_eq: \"(\\<Union>b. A b) = (A True \\<union> A False)\"\n  by (fact SUP_UNIV_bool_expand)\n\nlemma UN_Pow_subset: \"(\\<Union>x\\<in>A. Pow (B x)) \\<subseteq> Pow (\\<Union>x\\<in>A. B x)\"\n  by blast\n\nlemma UN_mono:\n  \"A \\<subseteq> B \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> f x \\<subseteq> g x) \\<Longrightarrow>\n    (\\<Union>x\\<in>A. f x) \\<subseteq> (\\<Union>x\\<in>B. g x)\"\n  by (fact SUP_subset_mono)\n\nlemma vimage_Union: \"f -` (\\<Union>A) = (\\<Union>X\\<in>A. f -` X)\"\n  by blast\n\nlemma vimage_UN: \"f -` (\\<Union>x\\<in>A. B x) = (\\<Union>x\\<in>A. f -` B x)\"\n  by blast\n\nlemma vimage_eq_UN: \"f -` B = (\\<Union>y\\<in>B. f -` {y})\"\n  -- {* NOT suitable for rewriting *}\n  by blast\n\nlemma image_UN: \"f ` UNION A B = (\\<Union>x\\<in>A. f ` B x)\"\n  by blast\n\nlemma UN_singleton [simp]: \"(\\<Union>x\\<in>A. {x}) = A\"\n  by blast\n\n\nsubsubsection {* Distributive laws *}\n\nlemma Int_Union: \"A \\<inter> \\<Union>B = (\\<Union>C\\<in>B. A \\<inter> C)\"\n  by (fact inf_Sup)\n\nlemma Un_Inter: \"A \\<union> \\<Inter>B = (\\<Inter>C\\<in>B. A \\<union> C)\"\n  by (fact sup_Inf)\n\nlemma Int_Union2: \"\\<Union>B \\<inter> A = (\\<Union>C\\<in>B. C \\<inter> A)\"\n  by (fact Sup_inf)\n\nlemma INT_Int_distrib: \"(\\<Inter>i\\<in>I. A i \\<inter> B i) = (\\<Inter>i\\<in>I. A i) \\<inter> (\\<Inter>i\\<in>I. B i)\"\n  by (rule sym) (rule INF_inf_distrib)\n\nlemma UN_Un_distrib: \"(\\<Union>i\\<in>I. A i \\<union> B i) = (\\<Union>i\\<in>I. A i) \\<union> (\\<Union>i\\<in>I. B i)\"\n  by (rule sym) (rule SUP_sup_distrib)\n\nlemma Int_Inter_image: \"(\\<Inter>x\\<in>C. A x \\<inter> B x) = \\<Inter>(A ` C) \\<inter> \\<Inter>(B ` C)\" -- {* FIXME drop *}\n  by (simp add: INT_Int_distrib)\n\nlemma Un_Union_image: \"(\\<Union>x\\<in>C. A x \\<union> B x) = \\<Union>(A ` C) \\<union> \\<Union>(B ` C)\" -- {* FIXME drop *}\n  -- {* Devlin, Fundamentals of Contemporary Set Theory, page 12, exercise 5: *}\n  -- {* Union of a family of unions *}\n  by (simp add: UN_Un_distrib)\n\nlemma Un_INT_distrib: \"B \\<union> (\\<Inter>i\\<in>I. A i) = (\\<Inter>i\\<in>I. B \\<union> A i)\"\n  by (fact sup_INF)\n\nlemma Int_UN_distrib: \"B \\<inter> (\\<Union>i\\<in>I. A i) = (\\<Union>i\\<in>I. B \\<inter> A i)\"\n  -- {* Halmos, Naive Set Theory, page 35. *}\n  by (fact inf_SUP)\n\nlemma Int_UN_distrib2: \"(\\<Union>i\\<in>I. A i) \\<inter> (\\<Union>j\\<in>J. B j) = (\\<Union>i\\<in>I. \\<Union>j\\<in>J. A i \\<inter> B j)\"\n  by (fact SUP_inf_distrib2)\n\nlemma Un_INT_distrib2: \"(\\<Inter>i\\<in>I. A i) \\<union> (\\<Inter>j\\<in>J. B j) = (\\<Inter>i\\<in>I. \\<Inter>j\\<in>J. A i \\<union> B j)\"\n  by (fact INF_sup_distrib2)\n\nlemma Union_disjoint: \"(\\<Union>C \\<inter> A = {}) \\<longleftrightarrow> (\\<forall>B\\<in>C. B \\<inter> A = {})\"\n  by (fact Sup_inf_eq_bot_iff)\n\n\nsubsection {* Injections and bijections *}\n\nlemma inj_on_Inter:\n  \"S \\<noteq> {} \\<Longrightarrow> (\\<And>A. A \\<in> S \\<Longrightarrow> inj_on f A) \\<Longrightarrow> inj_on f (\\<Inter>S)\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_INTER:\n  \"I \\<noteq> {} \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> inj_on f (A i)) \\<Longrightarrow> inj_on f (\\<Inter>i \\<in> I. A i)\"\n  unfolding inj_on_def by blast\n\nlemma inj_on_UNION_chain:\n  assumes CH: \"\\<And> i j. \\<lbrakk>i \\<in> I; j \\<in> I\\<rbrakk> \\<Longrightarrow> A i \\<le> A j \\<or> A j \\<le> A i\" and\n         INJ: \"\\<And> i. i \\<in> I \\<Longrightarrow> inj_on f (A i)\"\n  shows \"inj_on f (\\<Union> i \\<in> I. A i)\"\nproof -\n  {\n    fix i j x y\n    assume *: \"i \\<in> I\" \"j \\<in> I\" and **: \"x \\<in> A i\" \"y \\<in> A j\"\n      and ***: \"f x = f y\"\n    have \"x = y\"\n    proof -\n      {\n        assume \"A i \\<le> A j\"\n        with ** have \"x \\<in> A j\" by auto\n        with INJ * ** *** have ?thesis\n        by(auto simp add: inj_on_def)\n      }\n      moreover\n      {\n        assume \"A j \\<le> A i\"\n        with ** have \"y \\<in> A i\" by auto\n        with INJ * ** *** have ?thesis\n        by(auto simp add: inj_on_def)\n      }\n      ultimately show ?thesis using CH * by blast\n    qed\n  }\n  then show ?thesis by (unfold inj_on_def UNION_eq) auto\nqed\n\nlemma bij_betw_UNION_chain:\n  assumes CH: \"\\<And> i j. \\<lbrakk>i \\<in> I; j \\<in> I\\<rbrakk> \\<Longrightarrow> A i \\<le> A j \\<or> A j \\<le> A i\" and\n         BIJ: \"\\<And> i. i \\<in> I \\<Longrightarrow> bij_betw f (A i) (A' i)\"\n  shows \"bij_betw f (\\<Union> i \\<in> I. A i) (\\<Union> i \\<in> I. A' i)\"\nproof (unfold bij_betw_def, auto)\n  have \"\\<And> i. i \\<in> I \\<Longrightarrow> inj_on f (A i)\"\n  using BIJ bij_betw_def[of f] by auto\n  thus \"inj_on f (\\<Union> i \\<in> I. A i)\"\n  using CH inj_on_UNION_chain[of I A f] by auto\nnext\n  fix i x\n  assume *: \"i \\<in> I\" \"x \\<in> A i\"\n  hence \"f x \\<in> A' i\" using BIJ bij_betw_def[of f] by auto\n  thus \"\\<exists>j \\<in> I. f x \\<in> A' j\" using * by blast\nnext\n  fix i x'\n  assume *: \"i \\<in> I\" \"x' \\<in> A' i\"\n  hence \"\\<exists>x \\<in> A i. x' = f x\" using BIJ bij_betw_def[of f] by blast\n  then have \"\\<exists>j \\<in> I. \\<exists>x \\<in> A j. x' = f x\"\n    using * by blast\n  then show \"x' \\<in> f ` (\\<Union>x\\<in>I. A x)\" by blast\nqed\n\n(*injectivity's required.  Left-to-right inclusion holds even if A is empty*)\nlemma image_INT:\n   \"[| inj_on f C;  ALL x:A. B x <= C;  j:A |]\n    ==> f ` (INTER A B) = (INT x:A. f ` B x)\"\napply (simp add: inj_on_def, blast)\ndone\n\n(*Compare with image_INT: no use of inj_on, and if f is surjective then\n  it doesn't matter whether A is empty*)\nlemma bij_image_INT: \"bij f ==> f ` (INTER A B) = (INT x:A. f ` B x)\"\napply (simp add: bij_def)\napply (simp add: inj_on_def surj_def, blast)\ndone\n\nlemma UNION_fun_upd:\n  \"UNION J (A(i:=B)) = (UNION (J-{i}) A \\<union> (if i\\<in>J then B else {}))\"\nby (auto split: if_splits)\n\n\nsubsubsection {* Complement *}\n\nlemma Compl_INT [simp]: \"- (\\<Inter>x\\<in>A. B x) = (\\<Union>x\\<in>A. -B x)\"\n  by (fact uminus_INF)\n\nlemma Compl_UN [simp]: \"- (\\<Union>x\\<in>A. B x) = (\\<Inter>x\\<in>A. -B x)\"\n  by (fact uminus_SUP)\n\n\nsubsubsection {* Miniscoping and maxiscoping *}\n\ntext {* \\medskip Miniscoping: pushing in quantifiers and big Unions\n           and Intersections. *}\n\nlemma UN_simps [simp]:\n  \"\\<And>a B C. (\\<Union>x\\<in>C. insert a (B x)) = (if C={} then {} else insert a (\\<Union>x\\<in>C. B x))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x \\<union> B) = ((if C={} then {} else (\\<Union>x\\<in>C. A x) \\<union> B))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A \\<union> B x) = ((if C={} then {} else A \\<union> (\\<Union>x\\<in>C. B x)))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x \\<inter> B) = ((\\<Union>x\\<in>C. A x) \\<inter> B)\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A \\<inter> B x) = (A \\<inter>(\\<Union>x\\<in>C. B x))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x - B) = ((\\<Union>x\\<in>C. A x) - B)\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A - B x) = (A - (\\<Inter>x\\<in>C. B x))\"\n  \"\\<And>A B. (\\<Union>x\\<in>\\<Union>A. B x) = (\\<Union>y\\<in>A. \\<Union>x\\<in>y. B x)\"\n  \"\\<And>A B C. (\\<Union>z\\<in>UNION A B. C z) = (\\<Union>x\\<in>A. \\<Union>z\\<in>B x. C z)\"\n  \"\\<And>A B f. (\\<Union>x\\<in>f`A. B x) = (\\<Union>a\\<in>A. B (f a))\"\n  by auto\n\nlemma INT_simps [simp]:\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x \\<inter> B) = (if C={} then UNIV else (\\<Inter>x\\<in>C. A x) \\<inter> B)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A \\<inter> B x) = (if C={} then UNIV else A \\<inter>(\\<Inter>x\\<in>C. B x))\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x - B) = (if C={} then UNIV else (\\<Inter>x\\<in>C. A x) - B)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A - B x) = (if C={} then UNIV else A - (\\<Union>x\\<in>C. B x))\"\n  \"\\<And>a B C. (\\<Inter>x\\<in>C. insert a (B x)) = insert a (\\<Inter>x\\<in>C. B x)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x \\<union> B) = ((\\<Inter>x\\<in>C. A x) \\<union> B)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A \\<union> B x) = (A \\<union> (\\<Inter>x\\<in>C. B x))\"\n  \"\\<And>A B. (\\<Inter>x\\<in>\\<Union>A. B x) = (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B x)\"\n  \"\\<And>A B C. (\\<Inter>z\\<in>UNION A B. C z) = (\\<Inter>x\\<in>A. \\<Inter>z\\<in>B x. C z)\"\n  \"\\<And>A B f. (\\<Inter>x\\<in>f`A. B x) = (\\<Inter>a\\<in>A. B (f a))\"\n  by auto\n\nlemma UN_ball_bex_simps [simp]:\n  \"\\<And>A P. (\\<forall>x\\<in>\\<Union>A. P x) \\<longleftrightarrow> (\\<forall>y\\<in>A. \\<forall>x\\<in>y. P x)\"\n  \"\\<And>A B P. (\\<forall>x\\<in>UNION A B. P x) = (\\<forall>a\\<in>A. \\<forall>x\\<in> B a. P x)\"\n  \"\\<And>A P. (\\<exists>x\\<in>\\<Union>A. P x) \\<longleftrightarrow> (\\<exists>y\\<in>A. \\<exists>x\\<in>y. P x)\"\n  \"\\<And>A B P. (\\<exists>x\\<in>UNION A B. P x) \\<longleftrightarrow> (\\<exists>a\\<in>A. \\<exists>x\\<in>B a. P x)\"\n  by auto\n\n\ntext {* \\medskip Maxiscoping: pulling out big Unions and Intersections. *}\n\nlemma UN_extend_simps:\n  \"\\<And>a B C. insert a (\\<Union>x\\<in>C. B x) = (if C={} then {a} else (\\<Union>x\\<in>C. insert a (B x)))\"\n  \"\\<And>A B C. (\\<Union>x\\<in>C. A x) \\<union> B = (if C={} then B else (\\<Union>x\\<in>C. A x \\<union> B))\"\n  \"\\<And>A B C. A \\<union> (\\<Union>x\\<in>C. B x) = (if C={} then A else (\\<Union>x\\<in>C. A \\<union> B x))\"\n  \"\\<And>A B C. ((\\<Union>x\\<in>C. A x) \\<inter> B) = (\\<Union>x\\<in>C. A x \\<inter> B)\"\n  \"\\<And>A B C. (A \\<inter> (\\<Union>x\\<in>C. B x)) = (\\<Union>x\\<in>C. A \\<inter> B x)\"\n  \"\\<And>A B C. ((\\<Union>x\\<in>C. A x) - B) = (\\<Union>x\\<in>C. A x - B)\"\n  \"\\<And>A B C. (A - (\\<Inter>x\\<in>C. B x)) = (\\<Union>x\\<in>C. A - B x)\"\n  \"\\<And>A B. (\\<Union>y\\<in>A. \\<Union>x\\<in>y. B x) = (\\<Union>x\\<in>\\<Union>A. B x)\"\n  \"\\<And>A B C. (\\<Union>x\\<in>A. \\<Union>z\\<in>B x. C z) = (\\<Union>z\\<in>UNION A B. C z)\"\n  \"\\<And>A B f. (\\<Union>a\\<in>A. B (f a)) = (\\<Union>x\\<in>f`A. B x)\"\n  by auto\n\nlemma INT_extend_simps:\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x) \\<inter> B = (if C={} then B else (\\<Inter>x\\<in>C. A x \\<inter> B))\"\n  \"\\<And>A B C. A \\<inter> (\\<Inter>x\\<in>C. B x) = (if C={} then A else (\\<Inter>x\\<in>C. A \\<inter> B x))\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>C. A x) - B = (if C={} then UNIV - B else (\\<Inter>x\\<in>C. A x - B))\"\n  \"\\<And>A B C. A - (\\<Union>x\\<in>C. B x) = (if C={} then A else (\\<Inter>x\\<in>C. A - B x))\"\n  \"\\<And>a B C. insert a (\\<Inter>x\\<in>C. B x) = (\\<Inter>x\\<in>C. insert a (B x))\"\n  \"\\<And>A B C. ((\\<Inter>x\\<in>C. A x) \\<union> B) = (\\<Inter>x\\<in>C. A x \\<union> B)\"\n  \"\\<And>A B C. A \\<union> (\\<Inter>x\\<in>C. B x) = (\\<Inter>x\\<in>C. A \\<union> B x)\"\n  \"\\<And>A B. (\\<Inter>y\\<in>A. \\<Inter>x\\<in>y. B x) = (\\<Inter>x\\<in>\\<Union>A. B x)\"\n  \"\\<And>A B C. (\\<Inter>x\\<in>A. \\<Inter>z\\<in>B x. C z) = (\\<Inter>z\\<in>UNION A B. C z)\"\n  \"\\<And>A B f. (\\<Inter>a\\<in>A. B (f a)) = (\\<Inter>x\\<in>f`A. B x)\"\n  by auto\n\ntext {* Finally *}\n\nno_notation\n  less_eq (infix \"\\<sqsubseteq>\" 50) and\n  less (infix \"\\<sqsubset>\" 50)\n\nlemmas mem_simps =\n  insert_iff empty_iff Un_iff Int_iff Compl_iff Diff_iff\n  mem_Collect_eq UN_iff Union_iff INT_iff Inter_iff\n  -- {* Each of these has ALREADY been added @{text \"[simp]\"} above. *}\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Complete_Lattices.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979306, "lm_q2_score": 0.8791467738423873, "lm_q1q2_score": 0.7541040717965286}}
{"text": "(* Author: Florian Haftmann, TU Muenchen *)  \n\nsection {* Common discrete functions *}\n\ntheory Discrete\nimports Main\nbegin\n\nsubsection {* Discrete logarithm *}\n\nfun log :: \"nat \\<Rightarrow> nat\" where\n  [simp del]: \"log n = (if n < 2 then 0 else Suc (log (n div 2)))\"\n\nlemma log_zero [simp]:\n  \"log 0 = 0\"\n  by (simp add: log.simps)\n\nlemma log_one [simp]:\n  \"log 1 = 0\"\n  by (simp add: log.simps)\n\nlemma log_Suc_zero [simp]:\n  \"log (Suc 0) = 0\"\n  using log_one by simp\n\nlemma log_rec:\n  \"n \\<ge> 2 \\<Longrightarrow> log n = Suc (log (n div 2))\"\n  by (simp add: log.simps)\n\nlemma log_twice [simp]:\n  \"n \\<noteq> 0 \\<Longrightarrow> log (2 * n) = Suc (log n)\"\n  by (simp add: log_rec)\n\nlemma log_half [simp]:\n  \"log (n div 2) = log n - 1\"\nproof (cases \"n < 2\")\n  case True\n  then have \"n = 0 \\<or> n = 1\" by arith\n  then show ?thesis by (auto simp del: One_nat_def)\nnext\n  case False then show ?thesis by (simp add: log_rec)\nqed\n\nlemma log_exp [simp]:\n  \"log (2 ^ n) = n\"\n  by (induct n) simp_all\n\nlemma log_mono:\n  \"mono log\"\nproof\n  fix m n :: nat\n  assume \"m \\<le> n\"\n  then show \"log m \\<le> log n\"\n  proof (induct m arbitrary: n rule: log.induct)\n    case (1 m)\n    then have mn2: \"m div 2 \\<le> n div 2\" by arith\n    show \"log m \\<le> log n\"\n    proof (cases \"m < 2\")\n      case True\n      then have \"m = 0 \\<or> m = 1\" by arith\n      then show ?thesis by (auto simp del: One_nat_def)\n    next\n      case False\n      with mn2 have \"m \\<ge> 2\" and \"n \\<ge> 2\" by auto arith\n      from False have m2_0: \"m div 2 \\<noteq> 0\" by arith\n      with mn2 have n2_0: \"n div 2 \\<noteq> 0\" by arith\n      from False \"1.hyps\" mn2 have \"log (m div 2) \\<le> log (n div 2)\" by blast\n      with m2_0 n2_0 have \"log (2 * (m div 2)) \\<le> log (2 * (n div 2))\" by simp\n      with m2_0 n2_0 `m \\<ge> 2` `n \\<ge> 2` show ?thesis by (simp only: log_rec [of m] log_rec [of n]) simp\n    qed\n  qed\nqed\n\n\nsubsection {* Discrete square root *}\n\ndefinition sqrt :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"sqrt n = Max {m. m\\<^sup>2 \\<le> n}\"\n\nlemma sqrt_aux:\n  fixes n :: nat\n  shows \"finite {m. m\\<^sup>2 \\<le> n}\" and \"{m. m\\<^sup>2 \\<le> n} \\<noteq> {}\"\nproof -\n  { fix m\n    assume \"m\\<^sup>2 \\<le> n\"\n    then have \"m \\<le> n\"\n      by (cases m) (simp_all add: power2_eq_square)\n  } note ** = this\n  then have \"{m. m\\<^sup>2 \\<le> n} \\<subseteq> {m. m \\<le> n}\" by auto\n  then show \"finite {m. m\\<^sup>2 \\<le> n}\" by (rule finite_subset) rule\n  have \"0\\<^sup>2 \\<le> n\" by simp\n  then show *: \"{m. m\\<^sup>2 \\<le> n} \\<noteq> {}\" by blast\nqed\n\n\n\nlemma sqrt_inverse_power2 [simp]:\n  \"sqrt (n\\<^sup>2) = n\"\nproof -\n  have \"{m. m \\<le> n} \\<noteq> {}\" by auto\n  then have \"Max {m. m \\<le> n} \\<le> n\" by auto\n  then show ?thesis\n    by (auto simp add: sqrt_def power2_nat_le_eq_le intro: antisym)\nqed\n\nlemma sqrt_zero [simp]:\n  \"sqrt 0 = 0\"\n  using sqrt_inverse_power2 [of 0] by simp\n\nlemma sqrt_one [simp]:\n  \"sqrt 1 = 1\"\n  using sqrt_inverse_power2 [of 1] by simp\n\nlemma mono_sqrt:\n  \"mono sqrt\"\nproof\n  fix m n :: nat\n  have *: \"0 * 0 \\<le> m\" by simp\n  assume \"m \\<le> n\"\n  then show \"sqrt m \\<le> sqrt n\"\n    by (auto intro!: Max_mono `0 * 0 \\<le> m` finite_less_ub simp add: power2_eq_square sqrt_def)\nqed\n\nlemma sqrt_greater_zero_iff [simp]:\n  \"sqrt n > 0 \\<longleftrightarrow> n > 0\"\nproof -\n  have *: \"0 < Max {m. m\\<^sup>2 \\<le> n} \\<longleftrightarrow> (\\<exists>a\\<in>{m. m\\<^sup>2 \\<le> n}. 0 < a)\"\n    by (rule Max_gr_iff) (fact sqrt_aux)+\n  show ?thesis\n  proof\n    assume \"0 < sqrt n\"\n    then have \"0 < Max {m. m\\<^sup>2 \\<le> n}\" by (simp add: sqrt_def)\n    with * show \"0 < n\" by (auto dest: power2_nat_le_imp_le)\n  next\n    assume \"0 < n\"\n    then have \"1\\<^sup>2 \\<le> n \\<and> 0 < (1::nat)\" by simp\n    then have \"\\<exists>q. q\\<^sup>2 \\<le> n \\<and> 0 < q\" ..\n    with * have \"0 < Max {m. m\\<^sup>2 \\<le> n}\" by blast\n    then show \"0 < sqrt n\" by  (simp add: sqrt_def)\n  qed\nqed\n\nlemma sqrt_power2_le [simp]: (* FIXME tune proof *)\n  \"(sqrt n)\\<^sup>2 \\<le> n\"\nproof (cases \"n > 0\")\n  case False then show ?thesis by simp\nnext\n  case True then have \"sqrt n > 0\" by simp\n  then have \"mono (times (Max {m. m\\<^sup>2 \\<le> n}))\" by (auto intro: mono_times_nat simp add: sqrt_def)\n  then have *: \"Max {m. m\\<^sup>2 \\<le> n} * Max {m. m\\<^sup>2 \\<le> n} = Max (times (Max {m. m\\<^sup>2 \\<le> n}) ` {m. m\\<^sup>2 \\<le> n})\"\n    using sqrt_aux [of n] by (rule mono_Max_commute)\n  have \"Max (op * (Max {m. m * m \\<le> n}) ` {m. m * m \\<le> n}) \\<le> n\"\n    apply (subst Max_le_iff)\n    apply (metis (mono_tags) finite_imageI finite_less_ub le_square)\n    apply simp\n    apply (metis le0 mult_0_right)\n    apply auto\n    proof -\n      fix q\n      assume \"q * q \\<le> n\"\n      show \"Max {m. m * m \\<le> n} * q \\<le> n\"\n      proof (cases \"q > 0\")\n        case False then show ?thesis by simp\n      next\n        case True then have \"mono (times q)\" by (rule mono_times_nat)\n        then have \"q * Max {m. m * m \\<le> n} = Max (times q ` {m. m * m \\<le> n})\"\n          using sqrt_aux [of n] by (auto simp add: power2_eq_square intro: mono_Max_commute)\n        then have \"Max {m. m * m \\<le> n} * q = Max (times q ` {m. m * m \\<le> n})\" by (simp add: ac_simps)\n        then show ?thesis apply simp\n          apply (subst Max_le_iff)\n          apply auto\n          apply (metis (mono_tags) finite_imageI finite_less_ub le_square)\n          apply (metis `q * q \\<le> n`)\n          using `q * q \\<le> n` by (metis le_cases mult_le_mono1 mult_le_mono2 order_trans)\n      qed\n    qed\n  with * show ?thesis by (simp add: sqrt_def power2_eq_square)\nqed\n\nlemma sqrt_le:\n  \"sqrt n \\<le> n\"\n  using sqrt_aux [of n] by (auto simp add: sqrt_def intro: power2_nat_le_imp_le)\n\nhide_const (open) log sqrt\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Library/Discrete.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.8577681086260461, "lm_q1q2_score": 0.7541040708355983}}
{"text": "section \"Derivatives of regular expressions\"\n\n(* Author: Christian Urban *)\n\ntheory Derivatives\nimports Regular_Exp\nbegin\n\ntext\\<open>This theory is based on work by Brozowski \\<^cite>\\<open>\"Brzozowski64\"\\<close> and Antimirov \\<^cite>\\<open>\"Antimirov95\"\\<close>.\\<close>\n\nsubsection \\<open>Brzozowski's derivatives of regular expressions\\<close>\n\nfun\n  deriv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"deriv c (Zero) = Zero\"\n| \"deriv c (One) = Zero\"\n| \"deriv c (Atom c') = (if c = c' then One else Zero)\"\n| \"deriv c (Plus r1 r2) = Plus (deriv c r1) (deriv c r2)\"\n| \"deriv c (Times r1 r2) = \n    (if nullable r1 then Plus (Times (deriv c r1) r2) (deriv c r2) else Times (deriv c r1) r2)\"\n| \"deriv c (Star r) = Times (deriv c r) (Star r)\"\n\nfun \n  derivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp\"\nwhere\n  \"derivs [] r = r\"\n| \"derivs (c # s) r = derivs s (deriv c r)\"\n\n\nlemma atoms_deriv_subset: \"atoms (deriv x r) \\<subseteq> atoms r\"\nby (induction r) (auto)\n\nlemma atoms_derivs_subset: \"atoms (derivs w r) \\<subseteq> atoms r\"\nby (induction w arbitrary: r) (auto dest: atoms_deriv_subset[THEN subsetD])\n\nlemma lang_deriv: \"lang (deriv c r) = Deriv c (lang r)\"\nby (induct r) (simp_all add: nullable_iff)\n\nlemma lang_derivs: \"lang (derivs s r) = Derivs s (lang r)\"\nby (induct s arbitrary: r) (simp_all add: lang_deriv)\n\ntext \\<open>A regular expression matcher:\\<close>\n\ndefinition matcher :: \"'a rexp \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"matcher r s = nullable (derivs s r)\"\n\nlemma matcher_correctness: \"matcher r s \\<longleftrightarrow> s \\<in> lang r\"\nby (induct s arbitrary: r)\n   (simp_all add: nullable_iff lang_deriv matcher_def Deriv_def)\n\n\nsubsection \\<open>Antimirov's partial derivatives\\<close>\n\nabbreviation\n  \"Timess rs r \\<equiv> (\\<Union>r' \\<in> rs. {Times r' r})\"\n\nlemma Timess_eq_image:\n  \"Timess rs r = (\\<lambda>r'. Times r' r) ` rs\"\n  by auto\n\nprimrec\n  pderiv :: \"'a \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderiv c Zero = {}\"\n| \"pderiv c One = {}\"\n| \"pderiv c (Atom c') = (if c = c' then {One} else {})\"\n| \"pderiv c (Plus r1 r2) = (pderiv c r1) \\<union> (pderiv c r2)\"\n| \"pderiv c (Times r1 r2) = \n    (if nullable r1 then Timess (pderiv c r1) r2 \\<union> pderiv c r2 else Timess (pderiv c r1) r2)\"\n| \"pderiv c (Star r) = Timess (pderiv c r) (Star r)\"\n\nprimrec\n  pderivs :: \"'a list \\<Rightarrow> 'a rexp \\<Rightarrow> ('a rexp) set\"\nwhere\n  \"pderivs [] r = {r}\"\n| \"pderivs (c # s) r = \\<Union> (pderivs s ` pderiv c r)\"\n\nabbreviation\n pderiv_set :: \"'a \\<Rightarrow> 'a rexp set \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderiv_set c rs \\<equiv> \\<Union> (pderiv c ` rs)\"\n\nabbreviation\n  pderivs_set :: \"'a list \\<Rightarrow> 'a rexp set \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderivs_set s rs \\<equiv> \\<Union> (pderivs s ` rs)\"\n\nlemma pderivs_append:\n  \"pderivs (s1 @ s2) r = \\<Union> (pderivs s2 ` pderivs s1 r)\"\nby (induct s1 arbitrary: r) (simp_all)\n\nlemma pderivs_snoc:\n  shows \"pderivs (s @ [c]) r = pderiv_set c (pderivs s r)\"\nby (simp add: pderivs_append)\n\nlemma pderivs_simps [simp]:\n  shows \"pderivs s Zero = (if s = [] then {Zero} else {})\"\n  and   \"pderivs s One = (if s = [] then {One} else {})\"\n  and   \"pderivs s (Plus r1 r2) = (if s = [] then {Plus r1 r2} else (pderivs s r1) \\<union> (pderivs s r2))\"\nby (induct s) (simp_all)\n\nlemma pderivs_Atom:\n  shows \"pderivs s (Atom c) \\<subseteq> {Atom c, One}\"\nby (induct s) (simp_all)\n\nsubsection \\<open>Relating left-quotients and partial derivatives\\<close>\n\nlemma Deriv_pderiv:\n  shows \"Deriv c (lang r) = \\<Union> (lang ` pderiv c r)\"\nby (induct r) (auto simp add: nullable_iff conc_UNION_distrib)\n\nlemma Derivs_pderivs:\n  shows \"Derivs s (lang r) = \\<Union> (lang ` pderivs s r)\"\nproof (induct s arbitrary: r)\n  case (Cons c s)\n  have ih: \"\\<And>r. Derivs s (lang r) = \\<Union> (lang ` pderivs s r)\" by fact\n  have \"Derivs (c # s) (lang r) = Derivs s (Deriv c (lang r))\" by simp\n  also have \"\\<dots> = Derivs s (\\<Union> (lang ` pderiv c r))\" by (simp add: Deriv_pderiv)\n  also have \"\\<dots> = Derivss s (lang ` (pderiv c r))\"\n    by (auto simp add:  Derivs_def)\n  also have \"\\<dots> = \\<Union> (lang ` (pderivs_set s (pderiv c r)))\"\n    using ih by auto\n  also have \"\\<dots> = \\<Union> (lang ` (pderivs (c # s) r))\" by simp\n  finally show \"Derivs (c # s) (lang r) = \\<Union> (lang ` pderivs (c # s) r)\" .\nqed (simp add: Derivs_def)\n\nsubsection \\<open>Relating derivatives and partial derivatives\\<close>\n\nlemma deriv_pderiv:\n  shows \"\\<Union> (lang ` (pderiv c r)) = lang (deriv c r)\"\nunfolding lang_deriv Deriv_pderiv by simp\n\nlemma derivs_pderivs:\n  shows \"\\<Union> (lang ` (pderivs s r)) = lang (derivs s r)\"\nunfolding lang_derivs Derivs_pderivs by simp\n\n\nsubsection \\<open>Finiteness property of partial derivatives\\<close>\n\ndefinition\n  pderivs_lang :: \"'a lang \\<Rightarrow> 'a rexp \\<Rightarrow> 'a rexp set\"\nwhere\n  \"pderivs_lang A r \\<equiv> \\<Union>x \\<in> A. pderivs x r\"\n\nlemma pderivs_lang_subsetI:\n  assumes \"\\<And>s. s \\<in> A \\<Longrightarrow> pderivs s r \\<subseteq> C\"\n  shows \"pderivs_lang A r \\<subseteq> C\"\nusing assms unfolding pderivs_lang_def by (rule UN_least)\n\nlemma pderivs_lang_union:\n  shows \"pderivs_lang (A \\<union> B) r = (pderivs_lang A r \\<union> pderivs_lang B r)\"\nby (simp add: pderivs_lang_def)\n\nlemma pderivs_lang_subset:\n  shows \"A \\<subseteq> B \\<Longrightarrow> pderivs_lang A r \\<subseteq> pderivs_lang B r\"\nby (auto simp add: pderivs_lang_def)\n\ndefinition\n  \"UNIV1 \\<equiv> UNIV - {[]}\"\n\nlemma pderivs_lang_Zero [simp]:\n  shows \"pderivs_lang UNIV1 Zero = {}\"\nunfolding UNIV1_def pderivs_lang_def by auto\n\nlemma pderivs_lang_One [simp]:\n  shows \"pderivs_lang UNIV1 One = {}\"\nunfolding UNIV1_def pderivs_lang_def by (auto split: if_splits)\n\nlemma pderivs_lang_Atom [simp]:\n  shows \"pderivs_lang UNIV1 (Atom c) = {One}\"\nunfolding UNIV1_def pderivs_lang_def \napply(auto)\napply(frule rev_subsetD)\napply(rule pderivs_Atom)\napply(simp)\napply(case_tac xa)\napply(auto split: if_splits)\ndone\n\nlemma pderivs_lang_Plus [simp]:\n  shows \"pderivs_lang UNIV1 (Plus r1 r2) = pderivs_lang UNIV1 r1 \\<union> pderivs_lang UNIV1 r2\"\nunfolding UNIV1_def pderivs_lang_def by auto\n\n\ntext \\<open>Non-empty suffixes of a string (needed for the cases of @{const Times} and @{const Star} below)\\<close>\n\ndefinition\n  \"PSuf s \\<equiv> {v. v \\<noteq> [] \\<and> (\\<exists>u. u @ v = s)}\"\n\nlemma PSuf_snoc:\n  shows \"PSuf (s @ [c]) = (PSuf s) @@ {[c]} \\<union> {[c]}\"\nunfolding PSuf_def conc_def\nby (auto simp add: append_eq_append_conv2 append_eq_Cons_conv)\n\nlemma PSuf_Union:\n  shows \"(\\<Union>v \\<in> PSuf s @@ {[c]}. f v) = (\\<Union>v \\<in> PSuf s. f (v @ [c]))\"\nby (auto simp add: conc_def)\n\nlemma pderivs_lang_snoc:\n  shows \"pderivs_lang (PSuf s @@ {[c]}) r = (pderiv_set c (pderivs_lang (PSuf s) r))\"\nunfolding pderivs_lang_def\nby (simp add: PSuf_Union pderivs_snoc)\n\nlemma pderivs_Times:\n  shows \"pderivs s (Times r1 r2) \\<subseteq> Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2)\"\nproof (induct s rule: rev_induct)\n  case (snoc c s)\n  have ih: \"pderivs s (Times r1 r2) \\<subseteq> Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2)\" \n    by fact\n  have \"pderivs (s @ [c]) (Times r1 r2) = pderiv_set c (pderivs s (Times r1 r2))\" \n    by (simp add: pderivs_snoc)\n  also have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs s r1) r2 \\<union> (pderivs_lang (PSuf s) r2))\"\n    using ih by fastforce\n  also have \"\\<dots> = pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderiv_set c (pderivs_lang (PSuf s) r2)\"\n    by (simp)\n  also have \"\\<dots> = pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (simp add: pderivs_lang_snoc)\n  also \n  have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs s r1) r2) \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by auto\n  also \n  have \"\\<dots> \\<subseteq> Timess (pderiv_set c (pderivs s r1)) r2 \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (auto simp add: if_splits)\n  also have \"\\<dots> = Timess (pderivs (s @ [c]) r1) r2 \\<union> pderiv c r2 \\<union> pderivs_lang (PSuf s @@ {[c]}) r2\"\n    by (simp add: pderivs_snoc)\n  also have \"\\<dots> \\<subseteq> Timess (pderivs (s @ [c]) r1) r2 \\<union> pderivs_lang (PSuf (s @ [c])) r2\"\n    unfolding pderivs_lang_def by (auto simp add: PSuf_snoc)  \n  finally show ?case .\nqed (simp) \n\nlemma pderivs_lang_Times_aux1:\n  assumes a: \"s \\<in> UNIV1\"\n  shows \"pderivs_lang (PSuf s) r \\<subseteq> pderivs_lang UNIV1 r\"\nusing a unfolding UNIV1_def PSuf_def pderivs_lang_def by auto\n\n\n\nlemma pderivs_lang_Times:\n  shows \"pderivs_lang UNIV1 (Times r1 r2) \\<subseteq> Timess (pderivs_lang UNIV1 r1) r2 \\<union> pderivs_lang UNIV1 r2\"\napply(rule pderivs_lang_subsetI)\napply(rule subset_trans)\napply(rule pderivs_Times)\nusing pderivs_lang_Times_aux1 pderivs_lang_Times_aux2\napply auto\napply blast\ndone\n\nlemma pderivs_Star:\n  assumes a: \"s \\<noteq> []\"\n  shows \"pderivs s (Star r) \\<subseteq> Timess (pderivs_lang (PSuf s) r) (Star r)\"\nusing a\nproof (induct s rule: rev_induct)\n  case (snoc c s)\n  have ih: \"s \\<noteq> [] \\<Longrightarrow> pderivs s (Star r) \\<subseteq> Timess (pderivs_lang (PSuf s) r) (Star r)\" by fact\n  { assume asm: \"s \\<noteq> []\"\n    have \"pderivs (s @ [c]) (Star r) = pderiv_set c (pderivs s (Star r))\" by (simp add: pderivs_snoc)\n    also have \"\\<dots> \\<subseteq> pderiv_set c (Timess (pderivs_lang (PSuf s) r) (Star r))\"\n      using ih[OF asm] by fast\n    also have \"\\<dots> \\<subseteq> Timess (pderiv_set c (pderivs_lang (PSuf s) r)) (Star r) \\<union> pderiv c (Star r)\"\n      by (auto split: if_splits)\n    also have \"\\<dots> \\<subseteq> Timess (pderivs_lang (PSuf (s @ [c])) r) (Star r) \\<union> (Timess (pderiv c r) (Star r))\"\n      by (simp only: PSuf_snoc pderivs_lang_snoc pderivs_lang_union)\n         (auto simp add: pderivs_lang_def)\n    also have \"\\<dots> = Timess (pderivs_lang (PSuf (s @ [c])) r) (Star r)\"\n      by (auto simp add: PSuf_snoc PSuf_Union pderivs_snoc pderivs_lang_def)\n    finally have ?case .\n  }\n  moreover\n  { assume asm: \"s = []\"\n    then have ?case by (auto simp add: pderivs_lang_def pderivs_snoc PSuf_def)\n  }\n  ultimately show ?case by blast\nqed (simp)\n\nlemma pderivs_lang_Star:\n  shows \"pderivs_lang UNIV1 (Star r) \\<subseteq> Timess (pderivs_lang UNIV1 r) (Star r)\"\napply(rule pderivs_lang_subsetI)\napply(rule subset_trans)\napply(rule pderivs_Star)\napply(simp add: UNIV1_def)\napply(simp add: UNIV1_def PSuf_def)\napply(auto simp add: pderivs_lang_def)\ndone\n\nlemma finite_Timess [simp]:\n  assumes a: \"finite A\"\n  shows \"finite (Timess A r)\"\nusing a by auto\n\nlemma finite_pderivs_lang_UNIV1:\n  shows \"finite (pderivs_lang UNIV1 r)\"\napply(induct r)\napply(simp_all add: \n  finite_subset[OF pderivs_lang_Times]\n  finite_subset[OF pderivs_lang_Star])\ndone\n    \nlemma pderivs_lang_UNIV:\n  shows \"pderivs_lang UNIV r = pderivs [] r \\<union> pderivs_lang UNIV1 r\"\nunfolding UNIV1_def pderivs_lang_def\nby blast\n\nlemma finite_pderivs_lang_UNIV:\n  shows \"finite (pderivs_lang UNIV r)\"\nunfolding pderivs_lang_UNIV\nby (simp add: finite_pderivs_lang_UNIV1)\n\nlemma finite_pderivs_lang:\n  shows \"finite (pderivs_lang A r)\"\nby (metis finite_pderivs_lang_UNIV pderivs_lang_subset rev_finite_subset subset_UNIV)\n\n\ntext\\<open>The following relationship between the alphabetic width of regular expressions\n(called \\<open>awidth\\<close> below) and the number of partial derivatives was proved\nby Antimirov~\\<^cite>\\<open>\"Antimirov95\"\\<close> and formalized by Max Haslbeck.\\<close>\n\nfun awidth :: \"'a rexp \\<Rightarrow> nat\" where\n\"awidth Zero = 0\" |\n\"awidth One = 0\" |\n\"awidth (Atom a) = 1\" |\n\"awidth (Plus r1 r2) = awidth r1 + awidth r2\" |\n\"awidth (Times r1 r2) = awidth r1 + awidth r2\" |\n\"awidth (Star r1) = awidth r1\"\n\nlemma card_Timess_pderivs_lang_le:\n  \"card (Timess (pderivs_lang A r) s) \\<le> card (pderivs_lang A r)\"\n  using finite_pderivs_lang unfolding Timess_eq_image by (rule card_image_le)\n\nlemma card_pderivs_lang_UNIV1_le_awidth: \"card (pderivs_lang UNIV1 r) \\<le> awidth r\"\nproof (induction r)\n  case (Plus r1 r2)\n  have \"card (pderivs_lang UNIV1 (Plus r1 r2)) = card (pderivs_lang UNIV1 r1 \\<union> pderivs_lang UNIV1 r2)\" by simp\n  also have \"\\<dots> \\<le> card (pderivs_lang UNIV1 r1) + card (pderivs_lang UNIV1 r2)\"\n    by(simp add: card_Un_le)\n  also have \"\\<dots> \\<le> awidth (Plus r1 r2)\" using Plus.IH by simp\n  finally show ?case .\nnext\n  case (Times r1 r2)\n  have \"card (pderivs_lang UNIV1 (Times r1 r2)) \\<le> card (Timess (pderivs_lang UNIV1 r1) r2 \\<union> pderivs_lang UNIV1 r2)\"\n    by (simp add: card_mono finite_pderivs_lang pderivs_lang_Times)\n  also have \"\\<dots> \\<le> card (Timess (pderivs_lang UNIV1 r1) r2) + card (pderivs_lang UNIV1 r2)\"\n    by (simp add: card_Un_le)\n  also have \"\\<dots> \\<le> card (pderivs_lang UNIV1 r1) + card (pderivs_lang UNIV1 r2)\"\n    by (simp add: card_Timess_pderivs_lang_le)\n  also have \"\\<dots> \\<le> awidth (Times r1 r2)\" using Times.IH by simp\n  finally show ?case .\nnext\n  case (Star r)\n  have \"card (pderivs_lang UNIV1 (Star r)) \\<le> card (Timess (pderivs_lang UNIV1 r) (Star r))\"\n    by (simp add: card_mono finite_pderivs_lang pderivs_lang_Star)\n  also have \"\\<dots> \\<le> card (pderivs_lang UNIV1 r)\" by (rule card_Timess_pderivs_lang_le)\n  also have \"\\<dots> \\<le> awidth (Star r)\" by (simp add: Star.IH)\n  finally show ?case .\nqed (auto)\n\ntext\\<open>Antimirov's Theorem 3.4:\\<close>\ntheorem card_pderivs_lang_UNIV_le_awidth: \"card (pderivs_lang UNIV r) \\<le> awidth r + 1\"\nproof -\n  have \"card (insert r (pderivs_lang UNIV1 r)) \\<le> Suc (card (pderivs_lang UNIV1 r))\"\n    by(auto simp: card_insert_if[OF finite_pderivs_lang_UNIV1])\n  also have \"\\<dots> \\<le> Suc (awidth r)\" by(simp add: card_pderivs_lang_UNIV1_le_awidth)\n  finally show ?thesis by(simp add: pderivs_lang_UNIV)\nqed \n\ntext\\<open>Antimirov's Corollary 3.5:\\<close>\ncorollary card_pderivs_lang_le_awidth: \"card (pderivs_lang A r) \\<le> awidth r + 1\"\nby(rule order_trans[OF\n  card_mono[OF finite_pderivs_lang_UNIV pderivs_lang_subset[OF subset_UNIV]]\n  card_pderivs_lang_UNIV_le_awidth])\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Regular-Sets/Derivatives.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7541040604518162}}
{"text": "section \\<open>Specification\\<close>\n\ntheory Goodstein_Lambda\n  imports Main \"Eval_Base.Eval_Base\"\nbegin\n\nsubsection \\<open>Hereditary base representation\\<close>\n\ntext \\<open>We define a data type of trees and an evaluation function that sums siblings and\n  exponentiates with respect to the given base on nesting.\\<close>\n\ndatatype C = C (unC: \"C list\")\n\nfun evalC where\n  \"evalC b (C []) = 0\"\n| \"evalC b (C (x # xs)) = b^evalC b x + evalC b (C xs)\"\n\nvalue \"evalC 2 (C [])\" \\<comment> \\<open>$0$\\<close>\nvalue \"evalC 2 (C [C []])\" \\<comment> \\<open>$2^0 = 1$\\<close>\nvalue \"evalC 2 (C [C [C []]])\" \\<comment> \\<open>$2^1 = 2$\\<close>\nvalue \"evalC 2 (C [C [], C []])\" \\<comment> \\<open>$2^0 + 2^0 = 2^0 \\cdot 2 = 2$; not in hereditary base $2$\\<close>\n\ntext \\<open>The hereditary base representation is characterized as trees (i.e., nested lists) whose\n  lists have monotonically increasing evaluations, with fewer than @{term \"b\"} repetitions for\n  each value. We will show later that this representation is unique.\\<close>\n\ninductive_set hbase for b where\n  \"C [] \\<in> hbase b\"\n| \"i \\<noteq> 0 \\<Longrightarrow> i < b \\<Longrightarrow> n \\<in> hbase b \\<Longrightarrow>\n   C ms \\<in> hbase b \\<Longrightarrow> (\\<And>m'. m' \\<in> set ms \\<Longrightarrow> evalC b n < evalC b m') \\<Longrightarrow>\n   C (replicate i n @ ms) \\<in> hbase b\"\n\ntext \\<open>We can convert to and from natural numbers as follows.\\<close>\n\ndefinition H2N where\n  \"H2N b n = evalC b n\"\n\ntext \\<open>As we will show later, @{term \"H2N b\"} restricted to @{term \"hbase n\"} is bijective\n  if @{prop \"b \\<ge> (2 :: nat)\"}, so we can convert from natural numbers by taking the inverse.\\<close>\n\ndefinition N2H where\n  \"N2H b n = inv_into (hbase b) (H2N b) n\"\n\nsubsection \\<open>The Goodstein function\\<close>\n\ntext \\<open>We define a function that computes the length of the Goodstein sequence whose $c$-th element\n  is $g_c = n$. Termination will be shown later, thereby establishing Goodstein's theorem.\\<close>\n\nfunction (sequential) goodstein :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"goodstein 0 n = 0\"\n  \\<comment> \\<open>we start counting at 1; also note that the initial base is @{term \"c+1 :: nat\"} and\\<close>\n  \\<comment> \\<open>hereditary base 1 makes no sense, so we have to avoid this case\\<close>\n| \"goodstein c 0 = c\"\n| \"goodstein c n = goodstein (c+1) (H2N (c+2) (N2H (c+1) n) - 1)\"\n  by pat_completeness auto\n\nabbreviation \\<G> where\n  \"\\<G> n \\<equiv> goodstein (Suc 0) n\"\n\nsection \\<open>Ordinals\\<close>\n\ntext \\<open>The following type contains countable ordinals, by the usual case distinction into 0,\n  successor ordinal, or limit ordinal; limit ordinals are given by their fundamental sequence.\n  Hereditary base @{term \"b\"} representations carry over to such ordinals by replacing each\n  occurrence of the base by @{term \"\\<omega>\"}.\\<close>\n\ndatatype Ord = Z | S Ord | L \"nat \\<Rightarrow> Ord\"\n\ntext \\<open>Note that the following arithmetic operations are not correct for all ordinals. However, they\n  will only be used in cases where they actually correspond to the ordinal arithmetic operations.\\<close>\n\nprimrec addO where\n  \"addO n Z = n\"\n| \"addO n (S m) = S (addO n m)\"\n| \"addO n (L f) = L (\\<lambda>i. addO n (f i))\"\n\nprimrec mulO where\n  \"mulO n Z = Z\"\n| \"mulO n (S m) = addO (mulO n m) n\"\n| \"mulO n (L f) = L (\\<lambda>i. mulO n (f i))\"\n\ndefinition \\<omega> where\n  \"\\<omega> = L (\\<lambda>n. (S ^^ n) Z)\"\n\nprimrec exp\\<omega> where\n  \"exp\\<omega> Z = S Z\"\n| \"exp\\<omega> (S n) = mulO (exp\\<omega> n) \\<omega>\"\n| \"exp\\<omega> (L f) = L (\\<lambda>i. exp\\<omega> (f i))\"\n\nsubsection \\<open>Evaluation\\<close>\n\ntext \\<open>Evaluating an ordinal number at base $b$ is accomplished by taking the $b$-th element of\n  all fundamental sequences and interpreting zero and successor over the natural numbers.\\<close>\n\nprimrec evalO where\n  \"evalO b Z = 0\"\n| \"evalO b (S n) = Suc (evalO b n)\"\n| \"evalO b (L f) = evalO b (f b)\"\n\nsubsection \\<open>Goodstein function and sequence\\<close>\n\ntext \\<open>We can define the Goodstein function very easily, but proving correctness will take a while.\\<close>\n\nprimrec goodsteinO where\n  \"goodsteinO c Z = c\"\n| \"goodsteinO c (S n) = goodsteinO (c+1) n\"\n| \"goodsteinO c (L f) = goodsteinO c (f (c+2))\"\n\nprimrec stepO where\n  \"stepO c Z = Z\"\n| \"stepO c (S n) = n\"\n| \"stepO c (L f) = stepO c (f (c+2))\"\n\ntext \\<open>We can compute a few values of the Goodstein sequence starting at $4$.\\<close>\n\ndefinition g4O where\n  \"g4O n = fold stepO [1..<Suc n] ((exp\\<omega> ^^ 3) Z)\"\n\nvalue \"map (\\<lambda>n. evalO (n+2) (g4O n)) [0..<10]\"\n\\<comment> \\<open>@{value \"[4, 26, 41, 60, 83, 109, 139, 173, 211, 253] :: nat list\"}\\<close>\n\nsubsection \\<open>Properties of evaluation\\<close>\n\nlemma evalO_addO [simp]:\n  \"evalO b (addO n m) = evalO b n + evalO b m\"\n  apply2 (induct m) by auto\n\nlemma evalO_mulO [simp]:\n  \"evalO b (mulO n m) = evalO b n * evalO b m\"\n  apply2 (induct m) by auto\n\nlemma evalO_n [simp]:\n  \"evalO b ((S ^^ n) Z) = n\"\n  apply2 (induct n) by auto\n\nlemma evalO_\\<omega> [simp]:\n  \"evalO b \\<omega> = b\"\n  by (auto simp: \\<omega>_def)\n\nlemma evalO_exp\\<omega> [simp]:\n  \"evalO b (exp\\<omega> n) = b^(evalO b n)\"\n  apply2 (induct n) by auto\n\ntext \\<open>Note that evaluation is useful for proving that @{type \"Ord\"} values are distinct:\\<close>\nnotepad begin\n  have \"addO n (exp\\<omega> m) \\<noteq> n\" for n m by (auto dest: arg_cong[of _ _ \"evalO 1\"])\nend\n\nsubsection \\<open>Arithmetic properties\\<close>\n\nlemma addO_Z [simp]:\n  \"addO Z n = n\"\n  apply2 (induct n) by auto\n\nlemma addO_assoc [simp]:\n  \"addO n (addO m p) = addO (addO n m) p\"\n  apply2 (induct p) by auto\n\nlemma mul0_distrib [simp]:\n  \"mulO n (addO p q) = addO (mulO n p) (mulO n q)\"\n  apply2 (induct q) by auto\n\nlemma mulO_assoc [simp]:\n  \"mulO n (mulO m p) = mulO (mulO n m) p\"\n  apply2 (induct p) by auto\n\n\n\n\nsection \\<open>Cantor normal form\\<close>\n\ntext \\<open>The previously introduced tree type @{type C} can be used to represent Cantor normal forms;\n  they are trees (evaluated at base @{term \\<omega>}) such that siblings are in non-decreasing order.\n  One can think of this as hereditary base @{term \\<omega>}. The plan is to mirror selected operations on\n  ordinals in Cantor normal forms.\\<close>\n\nsubsection \\<open>Conversion to and from the ordinal type @{type Ord}\\<close>\n\nfun C2O where\n  \"C2O (C []) = Z\"\n| \"C2O (C (n # ns)) = addO (C2O (C ns)) (exp\\<omega> (C2O n))\"\n\ndefinition O2C where\n  \"O2C = inv C2O\"\n\ntext \\<open>We show that @{term C2O} is injective, meaning the inverse is unique.\\<close>\n\nlemma addO_exp\\<omega>_inj:\n  assumes \"addO n (exp\\<omega> m) = addO n' (exp\\<omega> m')\"\n  shows \"n = n'\" and \"m = m'\"\nproof -\n  have \"addO n (exp\\<omega> m) = addO n' (exp\\<omega> m') \\<Longrightarrow> n = n'\"\n    apply2 (induct m arbitrary: m') by(case_tac m';\n      force simp: \\<omega>_def dest!: fun_cong[of _ _ 1])+\n  moreover have \"addO n (exp\\<omega> m) = addO n (exp\\<omega> m') \\<Longrightarrow> m = m'\"\n    apply2 (induct m arbitrary: n m'; case_tac m')\n    apply (auto 0 3 simp: \\<omega>_def intro: rangeI\n      dest: arg_cong[of _ _ \"evalO 1\"] fun_cong[of _ _ 0] fun_cong[of _ _ 1])[8] (* 1 left *)\n    by simp (meson ext rangeI)\n  ultimately show \"n = n'\" and \"m = m'\" using assms by simp_all\nqed\n\nlemma C2O_inj:\n  \"C2O n = C2O m \\<Longrightarrow> n = m\"\n  apply2 (induct n arbitrary: m rule: C2O.induct; case_tac m rule: C2O.cases)\n    by (auto dest: addO_exp\\<omega>_inj arg_cong[of _ _ \"evalO 1\"])\n\nlemma O2C_C2O [simp]:\n  \"O2C (C2O n) = n\"\n  by (auto intro!: inv_f_f simp: O2C_def inj_def C2O_inj)\n\nlemma O2C_Z [simp]:\n  \"O2C Z = C []\"\n  using O2C_C2O[of \"C []\", unfolded C2O.simps] .\n\nlemma C2O_replicate:\n  \"C2O (C (replicate i n)) = mulO (exp\\<omega> (C2O n)) ((S ^^ i) Z)\"\n  apply2 (induct i) by auto\n\nlemma C2O_app:\n  \"C2O (C (xs @ ys)) = addO (C2O (C ys)) (C2O (C xs))\"\n  apply2 (induct xs arbitrary: ys) by auto\n\nsubsection \\<open>Evaluation\\<close>\n\nlemma evalC_def':\n  \"evalC b n = evalO b (C2O n)\"\n  apply2 (induct n rule: C2O.induct) by auto\n\nlemma evalC_app [simp]:\n  \"evalC b (C (ns @ ms)) = evalC b (C ns) + evalC b (C ms)\"\n  apply2 (induct ns) by auto\n\nlemma evalC_replicate [simp]:\n  \"evalC b (C (replicate c n)) = c * evalC b (C [n])\"\n  apply2 (induct c) by auto\n\nsubsection \\<open>Transfer of the @{type Ord} induction principle to @{type C}\\<close>\n\nfun funC where \\<comment> \\<open>@{term funC} computes the fundamental sequence on @{type C}\\<close>\n  \"funC (C []) = (\\<lambda>i. [C []])\"\n| \"funC (C (C [] # ns)) = (\\<lambda>i. replicate i (C ns))\"\n| \"funC (C (n # ns)) = (\\<lambda>i. [C (funC n i @ ns)])\"\n\nlemma C2O_cons:\n  \"C2O (C (n # ns)) =\n    (if n = C [] then S (C2O (C ns)) else L (\\<lambda>i. C2O (C (funC n i @ ns))))\"\n  apply2 (induct n arbitrary: ns rule: funC.induct)\n  by (simp_all add: \\<omega>_def C2O_replicate C2O_app flip: exp\\<omega>_addO)\n\nlemma C_Ord_induct:\n  assumes \"P (C [])\"\n  and \"\\<And>ns. P (C ns) \\<Longrightarrow> P (C (C [] # ns))\"\n  and \"\\<And>n ns ms. (\\<And>i. P (C (funC (C (n # ns)) i @ ms))) \\<Longrightarrow>\n    P (C (C (n # ns) # ms))\"\n  shows \"P n\"\nproof -\n  have \"\\<forall>n. C2O n = m \\<longrightarrow> P n\" for m\n    apply2 (induct m; intro allI; case_tac n rule: funC.cases)\n  by (auto simp: C2O_cons simp del: C2O.simps(2) intro: assms)\n  then show ?thesis by simp\nqed\n\nsubsection \\<open>Goodstein function and sequence on @{type C}\\<close>\n\nfunction (domintros) goodsteinC where\n  \"goodsteinC c (C []) = c\"\n| \"goodsteinC c (C (C [] # ns)) = goodsteinC (c+1) (C ns)\"\n| \"goodsteinC c (C (C (n # ns) # ms)) =\n    goodsteinC c (C (funC (C (n # ns)) (c+2) @ ms))\"\n  by pat_completeness auto\n\ntermination\nproof -\n  have \"goodsteinC_dom (c, n)\" for c n\n    apply2 (induct n arbitrary: c rule: C_Ord_induct) by(auto intro: goodsteinC.domintros)\n  then show ?thesis by simp\nqed\n\nlemma goodsteinC_def':\n  \"goodsteinC c n = goodsteinO c (C2O n)\"\n  apply2 (induct c n rule: goodsteinC.induct) by(simp_all add: C2O_cons del: C2O.simps(2))\n\nfunction (domintros) stepC where\n  \"stepC c (C []) = C []\"\n| \"stepC c (C (C [] # ns)) = C ns\"\n| \"stepC c (C (C (n # ns) # ms)) =\n    stepC c (C (funC (C (n # ns)) (Suc (Suc c)) @ ms))\"\n  by pat_completeness auto\n\ntermination\nproof -\n  have \"stepC_dom (c, n)\" for c n\n    apply2 (induct n arbitrary: c rule: C_Ord_induct) by(auto intro: stepC.domintros)\n  then show ?thesis by simp\nqed\n\ndefinition g4C where\n  \"g4C n = fold stepC [1..<Suc n] (C [C [C [C []]]])\"\n\nvalue \"map (\\<lambda>n. evalC (n+2) (g4C n)) [0..<10]\"\n\\<comment> \\<open>@{value \"[4, 26, 41, 60, 83, 109, 139, 173, 211, 253] :: nat list\"}\\<close>\n\nsubsection \\<open>Properties\\<close>\n\nlemma stepC_def':\n  \"stepC c n = O2C (stepO c (C2O n))\"\n  apply2 (induct c n rule: stepC.induct) by(simp_all add: C2O_cons del: C2O.simps(2))\n\nlemma funC_ne [simp]:\n  \"funC m (Suc n) \\<noteq> []\"\n  by (cases m rule: funC.cases) simp_all\n\nlemma evalC_funC [simp]:\n  \"evalC b (C (funC n b)) = evalC b (C [n])\"\n  apply2 (induct n rule: funC.induct) by simp_all\n\nlemma stepC_app [simp]:\n  \"n \\<noteq> C [] \\<Longrightarrow> stepC c (C (unC n @ ns)) = C (unC (stepC c n) @ ns)\"\n  apply2 (induct n arbitrary: ns rule: stepC.induct) by simp_all\n\nlemma stepC_cons [simp]:\n  \"ns \\<noteq> [] \\<Longrightarrow> stepC c (C (n # ns)) = C (unC (stepC c (C [n])) @ ns)\"\n  using stepC_app[of \"C[n]\" c ns] by simp\n\nlemma stepC_dec:\n  \"n \\<noteq> C [] \\<Longrightarrow> Suc (evalC (Suc (Suc c)) (stepC c n)) = evalC (Suc (Suc c)) n\"\n  apply2 (induct c n rule: stepC.induct) by simp_all\n\nlemma stepC_dec':\n  \"n \\<noteq> C [] \\<Longrightarrow> evalC (c+3) (stepC c n) < evalC (c+3) n\"\nproof2 (induct c n rule: stepC.induct)\n  case (3 c n ns ms)\n  have \"evalC (c+3) (C (funC (C (n # ns)) (Suc (Suc c)))) \\<le>\n      (c+3) ^ ((c+3) ^ evalC (c+3) n + evalC (c+3) (C ns))\"\n    apply2 (induct n rule: funC.induct) by(simp_all add: distrib_right)\n  then show ?case using 3 by simp\nqed simp_all\n\n\nsection \\<open>Hereditary base @{term b} representation\\<close>\n\ntext \\<open>We now turn to properties of the @{term \"hbase b\"} subset of trees.\\<close>\n\nsubsection \\<open>Uniqueness\\<close>\n\ntext \\<open>We show uniqueness of the hereditary base representation by showing that @{term \"evalC b\"}\n  restricted to @{term \"hbase b\"} is injective.\\<close>\n\nlemma hbaseI2:\n  \"i < b \\<Longrightarrow> n \\<in> hbase b \\<Longrightarrow> C m \\<in> hbase b \\<Longrightarrow>\n    (\\<And>m'. m' \\<in> set m \\<Longrightarrow> evalC b n < evalC b m') \\<Longrightarrow>\n    C (replicate i n @ m) \\<in> hbase b\"\n  by (cases i) (auto intro: hbase.intros simp del: replicate.simps(2))\n\nlemmas hbase_singletonI =\n  hbase.intros(2)[of 1 \"Suc (Suc b)\" for b, OF _ _ _ hbase.intros(1), simplified]\n\nlemma hbase_hd:\n  \"C ns \\<in> hbase b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> hd ns \\<in> hbase b\"\n  by (cases rule: hbase.cases) auto\n\nlemmas hbase_hd' [dest] = hbase_hd[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_tl:\n  \"C ns \\<in> hbase b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> C (tl ns) \\<in> hbase b\"\n  by (cases \"C ns\" b rule: hbase.cases) (auto intro: hbaseI2)\n\nlemmas hbase_tl' [dest] = hbase_tl[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_elt [dest]:\n  \"C ns \\<in> hbase b \\<Longrightarrow> n \\<in> set ns \\<Longrightarrow> n \\<in> hbase b\"\n  apply2 (induct ns) by auto\n\nlemma evalC_sum_list:\n  \"evalC b (C ns) = sum_list (map (\\<lambda>n. b^evalC b n) ns)\"\n  apply2 (induct ns) by auto\n\nlemma sum_list_replicate:\n  \"sum_list (replicate n x) = n * x\"\n  apply2 (induct n) by auto\n\nlemma base_red:\n  fixes b :: nat\n  assumes n: \"\\<And>n'. n' \\<in> set ns \\<Longrightarrow> n < n'\" \"i < b\" \"i \\<noteq> 0\"\n  and m: \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> m < m'\" \"j < b\" \"j \\<noteq> 0\"\n  and s: \"i * b^n + sum_list (map (\\<lambda>n. b^n) ns) = j * b^m + sum_list (map (\\<lambda>n. b^n) ms)\"\n  shows \"i = j \\<and> n = m\"\n  using n(1) m(1) s\nproof2 (induct n arbitrary: m ns ms)\n  { fix ns ms :: \"nat list\" and i j m :: nat\n    assume n': \"\\<And>n'. n' \\<in> set ns \\<Longrightarrow> 0 < n'\" \"i < b\" \"i \\<noteq> 0\"\n    assume m': \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> m < m'\" \"j < b\" \"j \\<noteq> 0\"\n    assume s': \"i * b^0 + sum_list (map (\\<lambda>n. b^n) ns) = j * b^m + sum_list (map (\\<lambda>n. b^n) ms)\"\n    obtain x where [simp]: \"sum_list (map ((^) b) ns) = x*b\"\n      using n'(1)\n      by (intro that[of \"sum_list (map (\\<lambda>n. b^(n-1)) ns)\"])\n        (simp add: ac_simps flip: sum_list_const_mult power_Suc cong: map_cong)\n    obtain y where [simp]: \"sum_list (map ((^) b) ms) = y*b\"\n      using order.strict_trans1[OF le0 m'(1)]\n      by (intro that[of \"sum_list (map (\\<lambda>n. b^(n-1)) ms)\"])\n        (simp add: ac_simps flip: sum_list_const_mult power_Suc cong: map_cong)\n    have [simp]: \"m = 0\"\n      using s' n'(2,3)\n      by (cases m, simp_all)\n        (metis Groups.mult_ac(2) Groups.mult_ac(3) Suc_pred div_less mod_div_mult_eq\n          mod_mult_self2 mod_mult_self2_is_0 mult_zero_right nat.simps(3))\n    have \"i = j \\<and> 0 = m\" using s' n'(2,3) m'(2,3)\n      by simp (metis div_less mod_div_mult_eq mod_mult_self1)\n  } note BASE = this\n  {\n    case 0 show ?case by (rule BASE; fact)\n  next\n    case (Suc n m')\n    have \"j = i \\<and> 0 = Suc n\" if \"m' = 0\" using Suc(2-4)\n      by (intro BASE[of ms j ns \"Suc n\" i]) (simp_all add: ac_simps that n(2,3) m(2,3))\n    then obtain m where m' [simp]: \"m' = Suc m\"\n      by (cases m') auto\n    obtain ns' where [simp]: \"ns = map Suc ns'\" \"\\<And>n'. n' \\<in> set ns' \\<Longrightarrow> n < n'\"\n      using Suc(2) less_trans[OF zero_less_Suc Suc(2)]\n      by (intro that[of \"map (\\<lambda>n. n-1) ns\"]; force cong: map_cong)\n    obtain ms' where [simp]: \"ms = map Suc ms'\" \"\\<And>m'. m' \\<in> set ms' \\<Longrightarrow> m < m'\"\n      using Suc(3)[unfolded m'] less_trans[OF zero_less_Suc Suc(3)[unfolded m']]\n      by (intro that[of \"map (\\<lambda>n. n-1) ms\"]; force cong: map_cong)\n    have *: \"b * x = b * y \\<Longrightarrow> x = y\" for x y using n(2) by simp\n    have \"i = j \\<and> n = m\"\n    proof (rule Suc(1)[of \"map (\\<lambda>n. n-1) ns\" \"map (\\<lambda>n. n-1) ms\" m, OF _ _ *], goal_cases)\n      case 3 show ?case using Suc(4) unfolding add_mult_distrib2\n        by (simp add: comp_def ac_simps flip: sum_list_const_mult)\n    qed simp_all\n    then show ?case by simp\n  }\nqed\n\nlemma evalC_inj_on_hbase:\n  \"n \\<in> hbase b \\<Longrightarrow> m \\<in> hbase b \\<Longrightarrow> evalC b n = evalC b m \\<Longrightarrow> n = m\"\nproof2 (induct n arbitrary: m rule: hbase.induct)\n  case 1\n  then show ?case by (cases m rule: hbase.cases) simp_all\nnext\n  case (2 i n ns m')\n  obtain j m ms where [simp]: \"m' = C (replicate j m @ ms)\" and\n    m: \"j \\<noteq> 0\" \"j < b\" \"m \\<in> hbase b\" \"C ms \\<in> hbase b\" \"\\<And>m'. m' \\<in> set ms \\<Longrightarrow> evalC b m < evalC b m'\"\n    using 2(8,1,2,9) by (cases m' rule: hbase.cases) simp_all\n  have \"i = j \\<and> evalC b n = evalC b m\" using 2(1,2,7,9) m(1,2,5)\n    by (intro base_red[of \"map (evalC b) ns\" _ _ b \"map (evalC b) ms\"])\n      (auto simp: comp_def evalC_sum_list sum_list_replicate)\n  then show ?case\n    using 2(4)[OF m(3)] 2(6)[OF m(4)] 2(9) by simp\nqed\n\nsubsection \\<open>Correctness of @{const stepC}\\<close>\n\ntext \\<open>We show that @{term \"stepC c\"} preserves hereditary base @{term \"c + 2 :: nat\"}\n  representations. In order to cover intermediate results produced by @{const stepC}, we extend\n  the hereditary base representation to allow the least significant digit to be equal to @{term b},\n  which essentially means that we may have an extra sibling in front on every level.\\<close>\n\ninductive_set hbase_ext for b where\n  \"n \\<in> hbase b \\<Longrightarrow> n \\<in> hbase_ext b\"\n| \"n \\<in> hbase_ext b \\<Longrightarrow>\n   C m \\<in> hbase b \\<Longrightarrow> (\\<And>m'. m' \\<in> set m \\<Longrightarrow> evalC b n \\<le> evalC b m') \\<Longrightarrow>\n   C (n # m) \\<in> hbase_ext b\"\n\nlemma hbase_ext_hd' [dest]:\n  \"C (n # ns) \\<in> hbase_ext b \\<Longrightarrow> n \\<in> hbase_ext b\"\n  by (cases rule: hbase_ext.cases) (auto intro: hbase_ext.intros(1))\n\nlemma hbase_ext_tl:\n  \"C ns \\<in> hbase_ext b \\<Longrightarrow> ns \\<noteq> [] \\<Longrightarrow> C (tl ns) \\<in> hbase b\"\n  by (cases \"C ns\" b rule: hbase_ext.cases; cases ns) (simp_all add: hbase_tl')\n\nlemmas hbase_ext_tl' [dest] = hbase_ext_tl[of \"n # ns\" for n ns, simplified]\n\nlemma hbase_funC:\n  \"c \\<noteq> 0 \\<Longrightarrow> C (n # ns) \\<in> hbase_ext (Suc c) \\<Longrightarrow>\n    C (funC n (Suc c) @ ns) \\<in> hbase_ext (Suc c)\"\nproof2 (induct n arbitrary: ns rule: funC.induct)\n  case (2 ms)\n  have [simp]: \"evalC (Suc c) (C ms) < evalC (Suc c) m'\" if \"m' \\<in> set ns\" for m'\n    using 2(2)\n  proof (cases rule: hbase_ext.cases)\n    case 1 then show ?thesis using that\n      by (cases rule: hbase.cases, case_tac i) (auto intro: Suc_lessD)\n  qed (auto simp: Suc_le_eq that)\n  show ?case using 2\n    by (auto 0 4 intro: hbase_ext.intros hbase.intros(2) order.strict_implies_order)\nnext\n  case (3 m ms ms')\n  show ?case\n    unfolding funC.simps append_Cons append_Nil\n  proof (rule hbase_ext.intros(2), goal_cases 31 32 33)\n    case (33 m')\n    show ?case using 3(3)\n    proof (cases rule: hbase_ext.cases)\n      case 1 show ?thesis using 1 3(1,2) 33\n        by (cases rule: hbase.cases, case_tac i) (auto intro: less_or_eq_imp_le)\n    qed (insert 33, simp)\n  qed (insert 3, blast+)\nqed auto\n\nlemma stepC_sound:\n  \"n \\<in> hbase_ext (Suc (Suc c)) \\<Longrightarrow> stepC c n \\<in> hbase (Suc (Suc c))\"\nproof2 (induct c n rule: stepC.induct)\n  case (3 c n ns ms)\n  show ?case using 3(2,1)\n    by (cases rule: hbase_ext.cases; unfold stepC.simps) (auto intro: hbase_funC)\nqed (auto intro: hbase.intros)\n\nsubsection \\<open>Surjectivity of @{const evalC}\\<close>\n\ntext \\<open>Note that the base must be at least @{term \"2 :: nat\"}.\\<close>\n\nlemma evalC_surjective:\n  \"\\<exists>n' \\<in> hbase (Suc (Suc b)). evalC (Suc (Suc b)) n' = n\"\nproof2 (induct n)\n  case 0 then show ?case by (auto intro: bexI[of _ \"C []\"] hbase.intros)\nnext\n  have [simp]: \"Suc x \\<le> Suc (Suc b)^x\" for x apply2 (induct x) by auto\n  case (Suc n)\n  then guess n' by (rule bexE)\n  then obtain n' j where n': \"Suc n \\<le> j\" \"j = evalC (Suc (Suc b)) n'\" \"n' \\<in> hbase (Suc (Suc b))\"\n    by (intro that[of _ \"C [n']\"])\n      (auto intro!: intro: hbase.intros(1) dest!: hbaseI2[of 1 \"b+2\" n' \"[]\", simplified])\n  then show ?case\n  proof2 (induct rule: inc_induct)\n    case (step m)\n    guess n' using step(3)[OF step(4,5)] by (rule bexE)\n    then show ?case using stepC_dec[of n' \"b\"]\n      by (cases n' rule: C2O.cases) (auto intro: stepC_sound hbase_ext.intros(1))\n  qed blast\nqed\n\nsubsection \\<open>Monotonicity of @{const hbase}\\<close>\n\ntext \\<open>Here we show that every hereditary base @{term \"b :: nat\"} number is also a valid hereditary\n  base @{term \"b+1 :: nat\"} number. This is not immediate because we have to show that monotonicity\n  of siblings is preserved.\\<close>\n\nlemma hbase_evalC_mono:\n  assumes \"n \\<in> hbase b\" \"m \\<in> hbase b\" \"evalC b n < evalC b m\"\n  shows \"evalC (Suc b) n < evalC (Suc b) m\"\nproof (cases \"b < 2\")\n  case True show ?thesis using assms(2,3) True by (cases rule: hbase.cases) simp_all\nnext\n  case False\n  then obtain b' where [simp]: \"b = Suc (Suc b')\"\n    by (auto simp: numeral_2_eq_2 not_less_eq dest: less_imp_Suc_add)\n  show ?thesis using assms(3,1,2)\n  proof2 (induct \"evalC b n\" \"evalC b m\" arbitrary: n m rule: less_Suc_induct)\n    case 1 then show ?case using stepC_sound[of m b', OF hbase_ext.intros(1)]\n      stepC_dec[of m b'] stepC_dec'[of m b'] evalC_inj_on_hbase\n      by (cases m rule: C2O.cases) (fastforce simp: eval_nat_numeral)+\n  next\n    case (2 j) then show ?case\n      using evalC_surjective[of b' j] less_trans by fastforce\n  qed\nqed\n\nlemma hbase_mono:\n  \"n \\<in> hbase b \\<Longrightarrow> n \\<in> hbase (Suc b)\"\n  apply2 (induct n rule: hbase.induct) by(auto 0 3 intro: hbase.intros hbase_evalC_mono)\n\nsubsection \\<open>Conversion to and from @{type nat}\\<close>\n\ntext \\<open>We have previously defined @{term \"H2N b = evalC b\"} and @{term \"N2H b\"} as its inverse.\n  So we can use the injectivity and surjectivity of @{term \"evalC b\"} for simplification.\\<close>\n\nlemma N2H_inv:\n  \"n \\<in> hbase b \\<Longrightarrow> N2H b (H2N b n) = n\"\n  using evalC_inj_on_hbase\n  by (auto simp: N2H_def H2N_def[abs_def] inj_on_def intro!: inv_into_f_f)\n\n\n\nlemma N2H_eqI:\n  \"n \\<in> hbase (Suc (Suc b)) \\<Longrightarrow>\n   H2N (Suc (Suc b)) n = m \\<Longrightarrow> N2H (Suc (Suc b)) m = n\"\n  using N2H_inv by blast\n\nlemma N2H_neI:\n  \"n \\<in> hbase (Suc (Suc b)) \\<Longrightarrow>\n   H2N (Suc (Suc b)) n \\<noteq> m \\<Longrightarrow> N2H (Suc (Suc b)) m \\<noteq> n\"\n  using H2N_inv by blast\n\nlemma N2H_0 [simp]:\n  \"N2H (Suc (Suc c)) 0 = C []\"\n  using H2N_def N2H_inv hbase.intros(1) by fastforce\n\nlemma N2H_nz [simp]:\n  \"0 < n \\<Longrightarrow> N2H (Suc (Suc c)) n \\<noteq> C []\"\n  by (metis N2H_0 H2N_inv neq0_conv)\n\n\nsection \\<open>The Goodstein function revisited\\<close>\n\ntext \\<open>We are now ready to prove termination of the Goodstein function @{const goodstein} as well\n  as its relation to @{const goodsteinC} and @{const goodsteinO}.\\<close>\n\nlemma goodstein_aux:\n  \"goodsteinC (Suc c) (N2H (Suc (Suc c)) (Suc n)) =\n    goodsteinC (c+2) (N2H (c+3) (H2N (c+3) (N2H (c+2) (n+1)) - 1))\"\nproof -\n  have [simp]: \"n \\<noteq> C [] \\<Longrightarrow> goodsteinC c n = goodsteinC (c+1) (stepC c n)\" for c n\n    apply2 (induct c n rule: stepC.induct) by simp_all\n  have [simp]: \"stepC (Suc c) (N2H (Suc (Suc c)) (Suc n)) \\<in> hbase (Suc (Suc (Suc c)))\"\n    by (metis H2N_def N2H_inv evalC_surjective hbase_ext.intros(1) hbase_mono stepC_sound)\n  show ?thesis\n    using arg_cong[OF stepC_dec[of \"N2H (c+2) (n+1)\" \"c+1\", folded H2N_def], of \"\\<lambda>n. N2H (c+3) (n-1)\"]\n    by (simp add: eval_nat_numeral N2H_inv)\nqed\n\ntermination goodstein\nproof (relation \"measure (\\<lambda>(c, n). goodsteinC c (N2H (c+1) n) - c)\", goal_cases _ 1)\n  case (1 c n)\n  have *: \"goodsteinC c n \\<ge> c\" for c n\n    apply2 (induct c n rule: goodsteinC.induct) by simp_all\n  show ?case by (simp add: goodstein_aux eval_nat_numeral) (meson Suc_le_eq diff_less_mono2 lessI *)\nqed simp\n\nlemma goodstein_def':\n  \"c \\<noteq> 0 \\<Longrightarrow> goodstein c n = goodsteinC c (N2H (c+1) n)\"\n  apply2 (induct c n rule: goodstein.induct) by(simp_all add: goodstein_aux eval_nat_numeral)\n\nlemma goodstein_impl:\n  \"c \\<noteq> 0 \\<Longrightarrow> goodstein c n = goodsteinO c (C2O (N2H (c+1) n))\"\n  \\<comment> \\<open>but note that @{term N2H} is not executable as currently defined\\<close>\n  using goodstein_def'[unfolded goodsteinC_def'] .\n\nlemma goodstein_16:\n  \"\\<G> 16 = goodsteinO 1 (exp\\<omega> (exp\\<omega> (exp\\<omega> (exp\\<omega> Z))))\"\nproof -\n  have \"N2H (Suc (Suc 0)) 16 = C [C [C [C [C []]]]]\"\n    by (auto simp: H2N_def intro!: N2H_eqI hbase_singletonI hbase.intros(1))\n  then show ?thesis by (simp add: goodstein_impl)\nqed\n\n\nsection \\<open>Translation to $\\lambda$-calculus\\<close>\n\ntext \\<open>We define Church encodings for @{type nat} and @{type Ord}. Note that we are basically in a\n  Hindley-Milner type system, so we cannot use a proper polymorphic type. We can still express\n  Church encodings as folds over values of the original type.\\<close>\n\nabbreviation Z\\<^sub>N where \"Z\\<^sub>N \\<equiv> (\\<lambda>s z. z)\"\nabbreviation S\\<^sub>N where \"S\\<^sub>N \\<equiv> (\\<lambda>n s z. s (n s z))\"\n\nprimrec fold_nat (\"\\<langle>_\\<rangle>\\<^sub>N\") where\n  \"\\<langle>0\\<rangle>\\<^sub>N = Z\\<^sub>N\"\n| \"\\<langle>Suc n\\<rangle>\\<^sub>N = S\\<^sub>N \\<langle>n\\<rangle>\\<^sub>N\"\n\nlemma one\\<^sub>N:\n  \"\\<langle>1\\<rangle>\\<^sub>N = (\\<lambda>x. x)\"\n  by simp\n\nabbreviation Z\\<^sub>O where \"Z\\<^sub>O \\<equiv> (\\<lambda>z s l. z)\"\nabbreviation S\\<^sub>O where \"S\\<^sub>O \\<equiv> (\\<lambda>n z s l. s (n z s l))\"\nabbreviation L\\<^sub>O where \"L\\<^sub>O \\<equiv> (\\<lambda>f z s l. l (\\<lambda>i. f i z s l))\"\n\nprimrec fold_Ord (\"\\<langle>_\\<rangle>\\<^sub>O\") where\n  \"\\<langle>Z\\<rangle>\\<^sub>O = Z\\<^sub>O\"\n| \"\\<langle>S n\\<rangle>\\<^sub>O = S\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\n| \"\\<langle>L f\\<rangle>\\<^sub>O = L\\<^sub>O (\\<lambda>i. \\<langle>f i\\<rangle>\\<^sub>O)\"\n\ntext \\<open>The following abbreviations and lemmas show how to implement the arithmetic functions and\n  the Goodstein function on a Church-encoded @{type Ord} in lambda calculus.\\<close>\n\nabbreviation (input) add\\<^sub>O where\n  \"add\\<^sub>O n m \\<equiv> (\\<lambda>z s l. m (n z s l) s l)\"\n\nlemma add\\<^sub>O:\n  \"\\<langle>addO n m\\<rangle>\\<^sub>O = add\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\n  apply2 (induct m) by simp_all\n\nabbreviation (input) mul\\<^sub>O where\n  \"mul\\<^sub>O n m \\<equiv> (\\<lambda>z s l. m z (\\<lambda>m. n m s l) l)\"\n\nlemma mul\\<^sub>O:\n  \"\\<langle>mulO n m\\<rangle>\\<^sub>O = mul\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\n  apply2 (induct m) by(simp_all add: add\\<^sub>O)\n\nabbreviation (input) \\<omega>\\<^sub>O where\n  \"\\<omega>\\<^sub>O \\<equiv> (\\<lambda>z s l. l (\\<lambda>n. \\<langle>n\\<rangle>\\<^sub>N s z))\"\n\nlemma \\<omega>\\<^sub>O:\n  \"\\<langle>\\<omega>\\<rangle>\\<^sub>O = \\<omega>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>(S ^^ i) Z\\<rangle>\\<^sub>O z s l = \\<langle>i\\<rangle>\\<^sub>N s z\" for i z s l apply2 (induct i) by simp_all\n  show ?thesis by (simp add: \\<omega>_def)\nqed\n\nabbreviation (input) exp\\<omega>\\<^sub>O where\n  \"exp\\<omega>\\<^sub>O n \\<equiv> (\\<lambda>z s l. n s (\\<lambda>x z. l (\\<lambda>n. \\<langle>n\\<rangle>\\<^sub>N x z)) (\\<lambda>f z. l (\\<lambda>n. f n z)) z)\"\n\nlemma exp\\<omega>\\<^sub>O:\n  \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = exp\\<omega>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\n  apply2 (induct n) by (simp_all add: mul\\<^sub>O \\<omega>\\<^sub>O)\n\nabbreviation (input) goodstein\\<^sub>O where\n  \"goodstein\\<^sub>O \\<equiv> (\\<lambda>c n. n (\\<lambda>x. x) (\\<lambda>n m. n (m + 1)) (\\<lambda>f m. f (m + 2) m) c)\"\n\nlemma goodstein\\<^sub>O:\n  \"goodsteinO c n = goodstein\\<^sub>O c \\<langle>n\\<rangle>\\<^sub>O\"\n  apply2 (induct n arbitrary: c) by simp_all\n\ntext \\<open>Note that modeling Church encodings with folds is still limited. For example, the meaningful\n  expression @{text \"\\<langle>n\\<rangle>\\<^sub>N exp\\<omega>\\<^sub>O Z\\<^sub>O\"} cannot be typed in Isabelle/HOL, as that would require rank-2\n  polymorphism.\\<close>\n\nsubsection \\<open>Alternative: free theorems\\<close>\n\ntext \\<open>The following is essentially the free theorem for Church-encoded @{type Ord} values.\\<close>\n\nlemma freeOrd:\n  assumes \"\\<And>n. h (s n) = s' (h n)\" and \"\\<And>f. h (l f) = l' (\\<lambda>i. h (f i))\"\n  shows \"h (\\<langle>n\\<rangle>\\<^sub>O z s l) = \\<langle>n\\<rangle>\\<^sub>O (h z) s' l'\"\n  apply2 (induct n) by(simp_all add: assms)\n\ntext \\<open>Each of the following proofs first states a naive definition of the corresponding function\n  (which is proved correct by induction), from which we then derive the optimized version using\n  the free theorem, by (conditional) rewriting (without induction).\\<close>\n\nlemma add\\<^sub>O':\n  \"\\<langle>addO n m\\<rangle>\\<^sub>O = add\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>addO n m\\<rangle>\\<^sub>O = \\<langle>m\\<rangle>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O S\\<^sub>O L\\<^sub>O\"\n    apply2 (induct m) by simp_all\n  show ?thesis\n    by (intro ext) (simp add: freeOrd[where h = \"\\<lambda>n. n _ _ _\"])\nqed\n\nlemma mul\\<^sub>O':\n  \"\\<langle>mulO n m\\<rangle>\\<^sub>O = mul\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O \\<langle>m\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>mulO n m\\<rangle>\\<^sub>O = \\<langle>m\\<rangle>\\<^sub>O Z\\<^sub>O (\\<lambda>m. add\\<^sub>O m \\<langle>n\\<rangle>\\<^sub>O) L\\<^sub>O\"\n    apply2 (induct m) by(simp_all add: add\\<^sub>O)\n  show ?thesis\n    by (intro ext) (simp add: freeOrd[where h = \"\\<lambda>n. n _ _ _\"])\nqed\n\nlemma exp\\<omega>\\<^sub>O':\n  \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = exp\\<omega>\\<^sub>O \\<langle>n\\<rangle>\\<^sub>O\"\nproof -\n  have [simp]: \"\\<langle>exp\\<omega> n\\<rangle>\\<^sub>O = \\<langle>n\\<rangle>\\<^sub>O (S\\<^sub>O Z\\<^sub>O) (\\<lambda>m. mul\\<^sub>O m \\<omega>\\<^sub>O) L\\<^sub>O\"\n    apply2 (induct n) by(simp_all add: mul\\<^sub>O \\<omega>\\<^sub>O)\n  show ?thesis\n    by (intro ext) (simp add: fun_cong[OF freeOrd[where h = \"\\<lambda>n z. n z _ _\"]])\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Goodstein_Lambda/Goodstein_Lambda.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.8577681122619883, "lm_q1q2_score": 0.7541040523036301}}
{"text": "(*  Gauss-Jordan elimination for matrices represented as functions\n    Author: Tobias Nipkow\n*)\nsection \\<open>Gauss-Jordan elimination algorithm\\<close>\ntheory Gauss_Jordan_Elim_Fun\nimports Main\nbegin\n\ntext\\<open>Matrices are functions:\\<close>\n\ntype_synonym 'a matrix = \"nat \\<Rightarrow> nat \\<Rightarrow> 'a\"\n\ntext\\<open>In order to restrict to finite matrices, a matrix is usually combined\nwith one or two natural numbers indicating the maximal row and column of the\nmatrix.\n\nGauss-Jordan elimination is parameterized with a natural number \\<open>n\\<close>. It indicates that the matrix \\<open>A\\<close> has \\<open>n\\<close> rows and columns.\nIn fact, \\<open>A\\<close> is the augmented matrix with \\<open>n+1\\<close> columns. Column\n\\<open>n\\<close> is the ``right-hand side'', i.e.\\ the constant vector \\<open>b\\<close>. The result is the unit matrix augmented with the solution in column\n\\<open>n\\<close>; see the correctness theorem below.\\<close>\n\nfun gauss_jordan :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> ('a)matrix option\" where\n\"gauss_jordan A 0 = Some(A)\" |\n\"gauss_jordan A (Suc m) =\n (case dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] of\n   [] \\<Rightarrow> None |\n   p # _ \\<Rightarrow>\n    (let Ap' = (\\<lambda>j. A p j / A p m);\n         A' = (\\<lambda>i. if i=p then Ap' else (\\<lambda>j. A i j - A i m * Ap' j))\n     in gauss_jordan (Fun.swap p m A') m))\"\n\ntext\\<open>Some auxiliary functions:\\<close>\n\ndefinition solution :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n\"solution A n x = (\\<forall>i<n. (\\<Sum> j=0..<n. A i j * x j) = A i n)\"\n\ndefinition unit :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> bool\" where\n\"unit A m n =\n (\\<forall>i j::nat. m\\<le>j \\<longrightarrow> j<n \\<longrightarrow> A i j = (if i=j then 1 else 0))\"\n\nlemma solution_swap:\nassumes \"p1 < n\" \"p2 < n\"\nshows \"solution (Fun.swap p1 p2 A) n x = solution A n x\" (is \"?L = ?R\")\nproof(cases \"p1=p2\")\n  case True thus ?thesis by simp\nnext\n  case False\n  show ?thesis\n  proof\n    assume ?R thus ?L using assms False by(simp add: solution_def Fun.swap_def)\n  next\n   assume ?L\n   show ?R\n   proof(auto simp: solution_def)\n     fix i assume \"i<n\"\n     show \"(\\<Sum>j = 0..<n. A i j * x j) = A i n\"\n     proof cases\n       assume \"i=p1\"\n       with \\<open>?L\\<close> assms False show ?thesis\n         by(fastforce simp add: solution_def Fun.swap_def)\n     next\n       assume \"i\\<noteq>p1\"\n       show ?thesis\n       proof cases\n         assume \"i=p2\"\n         with \\<open>?L\\<close> assms False show ?thesis\n           by(fastforce simp add: solution_def Fun.swap_def)\n       next\n         assume \"i\\<noteq>p2\"\n         with \\<open>i\\<noteq>p1\\<close> \\<open>?L\\<close> \\<open>i<n\\<close> assms False show ?thesis\n           by(fastforce simp add: solution_def Fun.swap_def)\n       qed\n     qed\n   qed\n qed\nqed\n\n(* Converting these apply scripts makes them blow up - see above *)\n\nlemma solution_upd1:\n  \"c \\<noteq> 0 \\<Longrightarrow> solution (A(p:=(\\<lambda>j. A p j / c))) n x = solution A n x\"\napply(cases \"p<n\")\n prefer 2\n apply(simp add: solution_def)\napply(clarsimp simp add: solution_def)\napply rule\n apply clarsimp\n apply(case_tac \"i=p\")\n  apply (simp add: sum_divide_distrib[symmetric] eq_divide_eq field_simps)\n apply simp\napply (simp add: sum_divide_distrib[symmetric] eq_divide_eq field_simps)\ndone\n\nlemma solution_upd_but1: \"\\<lbrakk> ap = A p; \\<forall>i j. i\\<noteq>p \\<longrightarrow> a i j = A i j; p<n \\<rbrakk> \\<Longrightarrow>\n solution (\\<lambda>i. if i=p then ap else (\\<lambda>j. a i j - c i * ap j)) n x =\n solution A n x\"\napply(clarsimp simp add: solution_def)\napply rule\n prefer 2\n apply (simp add: field_simps sum_subtractf sum_distrib_left[symmetric])\napply(clarsimp)\napply(case_tac \"i=p\")\n apply simp\napply (auto simp add: field_simps sum_subtractf sum_distrib_left[symmetric] all_conj_distrib)\ndone\n\nsubsection\\<open>Correctness\\<close>\n\ntext\\<open>The correctness proof:\\<close>\n\nlemma gauss_jordan_lemma: \"m\\<le>n \\<Longrightarrow> unit A m n \\<Longrightarrow> gauss_jordan A m = Some B \\<Longrightarrow>\n  unit B 0 n \\<and> solution A n (\\<lambda>j. B j n)\"\nproof(induct m arbitrary: A B)\n  case 0\n  { fix a and b c d :: \"'a\"\n    have \"(if a then b else c) * d = (if a then b*d else c*d)\" by simp\n  } with 0 show ?case by(simp add: unit_def solution_def sum.If_cases)\nnext\n  case (Suc m)\n  let \"?Ap' p\" = \"(\\<lambda>j. A p j / A p m)\"\n  let \"?A' p\" = \"(\\<lambda>i. if i=p then ?Ap' p else (\\<lambda>j. A i j - A i m * ?Ap' p j))\"\n  from \\<open>gauss_jordan A (Suc m) = Some B\\<close>\n  obtain p ks where \"dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] = p#ks\" and\n    rec: \"gauss_jordan (Fun.swap p m (?A' p)) m = Some B\"\n    by (auto split: list.splits)\n  from this have p: \"p\\<le>m\" \"A p m \\<noteq> 0\"\n    apply(simp_all add: dropWhile_eq_Cons_conv del:upt_Suc)\n    by (metis set_upt atLeast0AtMost atLeastLessThanSuc_atLeastAtMost atMost_iff in_set_conv_decomp)\n  have \"m\\<le>n\" \"m<n\" using \\<open>Suc m \\<le> n\\<close> by arith+\n  have \"unit (Fun.swap p m (?A' p)) m n\" using Suc.prems(2) p\n    unfolding unit_def Fun.swap_def Suc_le_eq by (auto simp: le_less)\n  from Suc.hyps[OF \\<open>m\\<le>n\\<close> this rec] \\<open>m<n\\<close> p\n  show ?case\n    by(simp add: solution_swap solution_upd1 solution_upd_but1[where A = \"A(p := ?Ap' p)\"])\nqed\n\ntheorem gauss_jordan_correct:\n  \"gauss_jordan A n = Some B \\<Longrightarrow> solution A n (\\<lambda>j. B j n)\"\nby(simp add:gauss_jordan_lemma[of n n] unit_def  field_simps)\n\ndefinition solution2 :: \"('a::field)matrix \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\nwhere \"solution2 A m n x = (\\<forall>i<m. (\\<Sum> j=0..<m. A i j * x j) = A i n)\"\n\ndefinition \"usolution A m n x \\<longleftrightarrow>\n  solution2 A m n x \\<and> (\\<forall>y. solution2 A m n y \\<longrightarrow> (\\<forall>j<m. y j = x j))\"\n\nlemma non_null_if_pivot:\n  assumes \"usolution A m n x\" and \"q < m\" shows \"\\<exists>p<m. A p q \\<noteq> 0\"\nproof(rule ccontr)\n  assume \"\\<not>(\\<exists>p<m. A p q \\<noteq> 0)\"\n  hence 1: \"\\<And>p. p<m \\<Longrightarrow> A p q = 0\" by simp\n  { fix y assume 2: \"\\<forall>j. j\\<noteq>q \\<longrightarrow> y j = x j\"\n    { fix i assume \"i<m\"\n      with assms(1) have \"A i n = (\\<Sum>j = 0..<m. A i j * x j)\"\n        by (auto simp: solution2_def usolution_def)\n      with 1[OF \\<open>i<m\\<close>] 2\n      have \"(\\<Sum>j = 0..<m. A i j * y j) = A i n\"\n        by (auto intro!: sum.cong)\n    }\n    hence \"solution2 A m n y\" by(simp add: solution2_def)\n  }\n  hence \"solution2 A m n (x(q:=0))\" and \"solution2 A m n (x(q:=1))\" by auto\n  with assms(1) zero_neq_one \\<open>q < m\\<close>\n  show False\n    by (simp add: usolution_def)\n       (metis fun_upd_same zero_neq_one)\nqed\n\nlemma lem1:\n  fixes f :: \"'a \\<Rightarrow> 'b::field\"\n  shows \"(\\<Sum>x\\<in>A. f x * (a * g x)) = a * (\\<Sum>x\\<in>A. f x * g x)\"\n  by (simp add: sum_distrib_left field_simps)\n\n\n\nsubsection\\<open>Complete\\<close>\n\nlemma gauss_jordan_complete:\n  \"m \\<le> n \\<Longrightarrow> usolution A m n x \\<Longrightarrow> \\<exists>B. gauss_jordan A m = Some B\"\nproof(induction m arbitrary: A)\n  case 0 show ?case by simp\nnext\n  case (Suc m A)\n  from \\<open>Suc m \\<le> n\\<close> have \"m\\<le>n\" and \"m<Suc m\" by arith+\n  from non_null_if_pivot[OF Suc.prems(2) \\<open>m<Suc m\\<close>]\n  obtain p' where \"p'<Suc m\" and \"A p' m \\<noteq> 0\" by blast\n  hence \"dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] \\<noteq> []\"\n    by (simp add: atLeast0LessThan) (metis lessThan_iff linorder_neqE_nat not_less_eq)\n  then obtain p xs where 1: \"dropWhile (\\<lambda>i. A i m = 0) [0..<Suc m] = p#xs\"\n    by (metis list.exhaust)\n  from this have \"p\\<le>m\" \"A p m \\<noteq> 0\"\n    by (simp_all add: dropWhile_eq_Cons_conv del: upt_Suc)\n       (metis set_upt atLeast0AtMost atLeastLessThanSuc_atLeastAtMost atMost_iff in_set_conv_decomp)\n  then have p: \"p < Suc m\" \"A p m \\<noteq> 0\"\n    by auto\n  let ?Ap' = \"(\\<lambda>j. A p j / A p m)\"\n  let ?A' = \"(\\<lambda>i. if i=p then ?Ap' else (\\<lambda>j. A i j - A i m * ?Ap' j))\"\n  let ?A = \"Fun.swap p m ?A'\"\n  have A: \"solution2 A (Suc m) n x\" using Suc.prems(2) by(simp add: usolution_def)\n  { fix i assume le_m: \"p < Suc m\" \"i < Suc m\" \"A p m \\<noteq> 0\"\n    have \"(\\<Sum>j = 0..<m. (A i j - A i m * A p j / A p m) * x j) =\n      ((\\<Sum>j = 0..<Suc m. A i j * x j) - A i m * x m) -\n      ((\\<Sum>j = 0..<Suc m. A p j * x j) - A p m * x m) * A i m / A p m\"\n      by (simp add: field_simps sum_subtractf sum_divide_distrib\n                    sum_distrib_left)\n    also have \"\\<dots> = A i n - A p n * A i m / A p m\"\n      using A le_m\n      by (simp add: solution2_def field_simps del: sum.op_ivl_Suc)\n    finally have \"(\\<Sum>j = 0..<m. (A i j - A i m * A p j / A p m) * x j) =\n      A i n - A p n * A i m / A p m\" . }\n  then have \"solution2 ?A m n x\" using p\n    by (auto simp add: solution2_def Fun.swap_def field_simps)\n  moreover\n  { fix y assume a: \"solution2 ?A m n y\"\n    let ?y = \"y(m := A p n / A p m - (\\<Sum>j = 0..<m. A p j * y j) / A p m)\"\n    have \"solution2 A (Suc m) n ?y\" unfolding solution2_def\n    proof safe\n      fix i assume \"i < Suc m\"\n      show \"(\\<Sum>j=0..<Suc m. A i j * ?y j) = A i n\"\n      proof (cases \"i = p\")\n        assume \"i = p\" with p show ?thesis by (simp add: field_simps)\n      next\n        assume \"i \\<noteq> p\"\n        show ?thesis\n        proof (cases \"i = m\")\n          assume \"i = m\"\n          with p \\<open>i \\<noteq> p\\<close> have \"p < m\" by simp\n          with a[unfolded solution2_def, THEN spec, of p] p(2)\n          have \"A p m * (A m m * A p n + A p m * (\\<Sum>j = 0..<m. y j * A m j)) = A p m * (A m n * A p m + A m m * (\\<Sum>j = 0..<m. y j * A p j))\"\n            by (simp add: Fun.swap_def field_simps sum_subtractf lem1 lem2 sum_divide_distrib[symmetric]\n                     split: if_splits)\n          with \\<open>A p m \\<noteq> 0\\<close> show ?thesis unfolding \\<open>i = m\\<close>\n            by simp (simp add: field_simps)\n        next\n          assume \"i \\<noteq> m\"\n          then have \"i < m\" using \\<open>i < Suc m\\<close> by simp\n          with a[unfolded solution2_def, THEN spec, of i] p(2)\n          have \"A p m * (A i m * A p n + A p m * (\\<Sum>j = 0..<m. y j * A i j)) = A p m * (A i n * A p m + A i m * (\\<Sum>j = 0..<m. y j * A p j))\"\n            by (simp add: Fun.swap_def split: if_splits)\n              (simp add: field_simps sum_subtractf lem1 lem2 sum_divide_distrib [symmetric])\n          with \\<open>A p m \\<noteq> 0\\<close> show ?thesis\n            by simp (simp add: field_simps)\n        qed\n      qed\n    qed\n    with \\<open>usolution A (Suc m) n x\\<close>\n    have \"\\<forall>j<Suc m. ?y j = x j\" by (simp add: usolution_def)\n    hence \"\\<forall>j<m. y j = x j\"\n      by simp (metis less_SucI nat_neq_iff)\n  } ultimately have \"usolution ?A m n x\" by(simp add: usolution_def)\n  from Suc.IH[OF \\<open>m\\<le>n\\<close> this] 1 show ?case by(simp)\nqed\n\ntext\\<open>Future work: extend the proof to matrix inversion.\\<close>\n\nhide_const (open) unit\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Gauss-Jordan-Elim-Fun/Gauss_Jordan_Elim_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.7540983307214447}}
{"text": "theory ConstOn\nimports Main\nbegin\n\ndefinition const_on :: \"('a \\<Rightarrow> 'b) \\<Rightarrow> 'a set \\<Rightarrow> 'b \\<Rightarrow> bool\"\n  where \"const_on f S x = (\\<forall> y \\<in> S . f y = x)\"\n\nlemma const_onI[intro]: \"(\\<And>y. y \\<in> S \\<Longrightarrow> f y = x) \\<Longrightarrow> const_on f S x\"\n  by (simp add: const_on_def)\n\n\n\n(*\nlemma const_onE[elim]: \"const_on f S r ==> x : S ==> r = r' ==> f x = r'\" \n*)\n\nlemma const_on_insert[simp]: \"const_on f (insert x S) y \\<longleftrightarrow> const_on f S y \\<and> f x = y\"\n   by auto\n\nlemma const_on_union[simp]: \"const_on f (S \\<union> S') y \\<longleftrightarrow> const_on f S y \\<and> const_on f S' y\"\n  by auto\n\nlemma const_on_subset[elim]: \"const_on f S y \\<Longrightarrow> S' \\<subseteq> S \\<Longrightarrow> const_on f S' y\"\n  by auto\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Call_Arity/ConstOn.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7540087791238691}}
{"text": "theory Exe2p6 \n  imports Main\nbegin\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l n r) = n # (contents l) @ (contents r)\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l n r) = n + sum_tree l + sum_tree r\"\n\nlemma sum_tree_lemma_1 : \"sum_tree t = sum_list (contents t)\"\n  apply(induction t rule: sum_tree.induct)\n   apply(auto)\n  done\n\nend\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/prog-prove/Exe2p6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.8198933293122506, "lm_q1q2_score": 0.7540087766645058}}
{"text": "section \\<open>Regular Expressions as Homogeneous Binary Relations\\<close>\n\ntheory Relation_Interpretation\nimports Regular_Exp\nbegin\n\nprimrec rel :: \"('a \\<Rightarrow> ('b * 'b) set) \\<Rightarrow> 'a rexp \\<Rightarrow> ('b * 'b) set\"\nwhere\n  \"rel v Zero = {}\" |\n  \"rel v One = Id\" |\n  \"rel v (Atom a) = v a\" |\n  \"rel v (Plus r s) = rel v r \\<union> rel v s\" |\n  \"rel v (Times r s) = rel v r O rel v s\" |\n  \"rel v (Star r) = (rel v r)^*\"\n\nprimrec word_rel :: \"('a \\<Rightarrow> ('b * 'b) set) \\<Rightarrow> 'a list \\<Rightarrow> ('b * 'b) set\"\nwhere\n  \"word_rel v [] = Id\"\n| \"word_rel v (a#as) = v a O word_rel v as\"\n\nlemma word_rel_append: \n  \"word_rel v w O word_rel v w' = word_rel v (w @ w')\"\nby (rule sym) (induct w, auto)\n\nlemma rel_word_rel: \"rel v r = (\\<Union>w\\<in>lang r. word_rel v w)\"\nproof (induct r)\n  case Times thus ?case \n    by (auto simp: rel_def word_rel_append conc_def relcomp_UNION_distrib relcomp_UNION_distrib2)\nnext\n  case (Star r)\n  { fix n\n    have \"(rel v r) ^^ n = (\\<Union>w \\<in> lang r ^^ n. word_rel v w)\"\n    proof (induct n)\n      case 0 show ?case by simp\n    next\n      case (Suc n) thus ?case\n        unfolding relpow.simps relpow_commute[symmetric]\n        by (auto simp add: Star conc_def word_rel_append\n          relcomp_UNION_distrib relcomp_UNION_distrib2)\n    qed }\n\n  thus ?case unfolding rel.simps\n    by (force simp: rtrancl_power star_def)\nqed auto\n\n\ntext \\<open>Soundness:\\<close>\n\n\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Regular-Sets/Relation_Interpretation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.7540087714651941}}
{"text": "theory IMPExpMult\n\nimports Main\n\nbegin\n\ntype_synonym vname = string\n\ndatatype aexp = N int | V vname | Plus aexp aexp\n\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a1 a2) s = aval a1 s + aval a2 s\"\n\ndefinition exp :: \"aexp\" where \"exp = (Plus (N 5) (V ''x''))\"\n\nvalue \"aval exp ((\\<lambda> x. 0)(''x'' := 1))\"\n\nfun asimp_const :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp_const (N n) = N n\" |\n\"asimp_const (V x) = V x\" |\n\"asimp_const (Plus a1 a2) = \n  (case (asimp_const a1, asimp_const a2) of\n    (N n1, N n2) \\<Rightarrow> N(n1 + n2) |\n    (b1, b2) \\<Rightarrow> Plus b1 b2)\"\n\nlemma \"aval (asimp_const a) s = aval a s\"\n  apply(induction a)\n    apply(auto split: aexp.split)\n  done\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow>  aexp\" where\n\"plus (N i1) (N i2) = N(i1 + i2)\" |\n\"plus (N i) a = (if i=0 then a else Plus (N i) a)\" |\n\"plus a (N i) = (if i=0 then a else Plus a (N i))\" |\n\"plus a1 a2 = Plus a1 a2\"\n\nlemma aval_plus: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply(induction rule: plus.induct)\n    apply(auto)\n  done\n\nfun asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"asimp (N n) = N n\" |\n\"asimp (V x) = V x\" |\n\"asimp (Plus a1 a2) = plus (asimp a1) (asimp a2)\"\n\nlemma \"aval (asimp a) s = aval a s\"\n  apply(induction a)\n    apply(auto simp add: aval_plus)\n  done\n\nfun optimal_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bool\" where\n\"optimal_plus (N _) (N _) = False\" |\n\"optimal_plus a1 a2 = True\"\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N _) = True\" |\n\"optimal (V _) = True\" |\n\"optimal (Plus a1 a2) = ((optimal a1) \\<and> (optimal a2) \\<and> (optimal_plus a1 a2))\"\n\ntheorem \"optimal(asimp_const a)\"\n  apply(induction a)\n    apply(auto split: aexp.split)\n  done\n\nfun full_plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"full_plus (N n1) (N n2) = N (n1 + n2)\" |\n\"full_plus (N n1) (Plus a (N n2)) = (Plus a (N (n1 + n2)))\" |\n\"full_plus (Plus a (N n1)) (N n2) = (Plus a (N (n1 + n2)))\" |\n\"full_plus a1 a2 = (Plus a1 a2)\"\n\nlemma full_plus_aval: \"aval (full_plus a1 a2) s = aval a1 s + aval a2 s\"\n  apply(induction rule: full_plus.induct)\n    apply(auto)\n  done\n\nfun full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp (N n) = N n\" |\n\"full_asimp (V x) = V x\" |\n\"full_asimp (Plus a1 a2) = full_plus (full_asimp a1) (full_asimp a2)\"\n\nvalue \"full_asimp (Plus (N 1) (Plus (V ''x'') (N 2)))\"\n    \ntheorem \"aval (full_asimp a) s = aval a s\"\n  apply(induction a arbitrary: s)\n    apply(auto simp add: full_plus_aval)\n  done\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst v e (V x) = (if v = x then e else (V x))\" |\n\"subst v e (Plus a1 a2) = (Plus (subst v e a1) (subst v e a2))\" |\n\"subst v e a = a\"\n\nvalue \"subst ''x''  (N 2) (Plus (V ''x'') (N 1))\"\n\nlemma subst_preserves_semantics: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n  apply(induction e)\n    apply(auto)\n  done\n\ntheorem \"aval a1 s = aval a2 s \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n  apply(simp add: subst_preserves_semantics)\n  done\n\nend", "meta": {"author": "amw-zero", "repo": "concrete_semantics", "sha": "b486ec4950cdb8ee83d222e9b8abff4663021e77", "save_path": "github-repos/isabelle/amw-zero-concrete_semantics", "path": "github-repos/isabelle/amw-zero-concrete_semantics/concrete_semantics-b486ec4950cdb8ee83d222e9b8abff4663021e77/IMPExpMult.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7538594435333201}}
{"text": "theory GabrielaLimonta2\nimports Main \"Repeat_Big_Step\" \"~~/src/HOL/IMP/Star\" \nbegin\nsubsection \"List setup\"\n\n(** Score: 5/5\n*)\n\ntext {* \n  In the following, we use the length of lists as integers \n  instead of natural numbers. Instead of converting @{typ nat}\n  to @{typ int} explicitly, we tell Isabelle to coerce @{typ nat}\n  automatically when necessary.\n*}\ndeclare [[coercion_enabled]] \ndeclare [[coercion \"int :: nat \\<Rightarrow> int\"]]\n\ntext {* \n  Similarly, we will want to access the ith element of a list, \n  where @{term i} is an @{typ int}.\n*}\nfun inth :: \"'a list \\<Rightarrow> int \\<Rightarrow> 'a\" (infixl \"!!\" 100) where\n\"(x # xs) !! i = (if i = 0 then x else xs !! (i - 1))\"\n\ntext {*\n  The only additional lemma we need about this function \n  is indexing over append:\n*}\nlemma inth_append [simp]:\n  \"0 \\<le> i \\<Longrightarrow>\n  (xs @ ys) !! i = (if i < size xs then xs !! i else ys !! (i - size xs))\"\nby (induction xs arbitrary: i) (auto simp: algebra_simps)\n\ntext{* We hide coercion @{const int} applied to @{const length}: *}\n\nabbreviation (output)\n  \"isize xs == int (length xs)\"\n\nnotation isize (\"size\")\n\n\nsubsection \"Instructions and Stack Machine\"\n\ntext_raw{*\\snip{instrdef}{0}{1}{% *}\ndatatype instr = \n  LOADI int | LOAD vname | ADD | STORE vname |\n  JMP int | JMPLESS int | JMPGE int\ntext_raw{*}%endsnip*}\n\ntype_synonym stack = \"val list\"\ntype_synonym config = \"int \\<times> state \\<times> stack\"\n\nabbreviation \"hd2 xs == hd(tl xs)\"\nabbreviation \"tl2 xs == tl(tl xs)\"\n\nfun iexec :: \"instr \\<Rightarrow> config \\<Rightarrow> config\" where\n\"iexec instr (i,s,stk) = (case instr of\n  LOADI n \\<Rightarrow> (i+1,s, n#stk) |\n  LOAD x \\<Rightarrow> (i+1,s, s x # stk) |\n  ADD \\<Rightarrow> (i+1,s, (hd2 stk + hd stk) # tl2 stk) |\n  STORE x \\<Rightarrow> (i+1,s(x := hd stk),tl stk) |\n  JMP n \\<Rightarrow>  (i+1+n,s,stk) |\n  JMPLESS n \\<Rightarrow> (if hd2 stk < hd stk then i+1+n else i+1,s,tl2 stk) |\n  JMPGE n \\<Rightarrow> (if hd2 stk >= hd stk then i+1+n else i+1,s,tl2 stk))\"\n\ndefinition\n  exec1 :: \"instr list \\<Rightarrow> config \\<Rightarrow> config \\<Rightarrow> bool\"\n     (\"(_/ \\<turnstile> (_ \\<rightarrow>/ _))\" [59,0,59] 60) \nwhere\n  \"P \\<turnstile> c \\<rightarrow> c' = \n  (\\<exists>i s stk. c = (i,s,stk) \\<and> c' = iexec(P!!i) (i,s,stk) \\<and> 0 \\<le> i \\<and> i < size P)\"\n\nlemma exec1I [intro, code_pred_intro]:\n  \"c' = iexec (P!!i) (i,s,stk) \\<Longrightarrow> 0 \\<le> i \\<Longrightarrow> i < size P\n  \\<Longrightarrow> P \\<turnstile> (i,s,stk) \\<rightarrow> c'\"\nby (simp add: exec1_def)\n\nabbreviation \n  exec :: \"instr list \\<Rightarrow> config \\<Rightarrow> config \\<Rightarrow> bool\" (\"(_/ \\<turnstile> (_ \\<rightarrow>*/ _))\" 50)\nwhere\n  \"exec P \\<equiv> star (exec1 P)\"\n\ndeclare star.step[intro]\n\nlemmas exec_induct = star.induct [of \"exec1 P\", split_format(complete)]\n\ncode_pred exec1 by (metis exec1_def)\n\nvalues\n  \"{(i,map t [''x'',''y''],stk) | i t stk.\n    [LOAD ''y'', STORE ''x''] \\<turnstile>\n    (0, <''x'' := 3, ''y'' := 4>, []) \\<rightarrow>* (i,t,stk)}\"\n\n\nsubsection{* Verification infrastructure *}\n\ntext{* Below we need to argue about the execution of code that is embedded in\nlarger programs. For this purpose we show that execution is preserved by\nappending code to the left or right of a program. *}\n\nlemma iexec_shift [simp]: \n  \"((n+i',s',stk') = iexec x (n+i,s,stk)) = ((i',s',stk') = iexec x (i,s,stk))\"\nby(auto split:instr.split)\n\nlemma exec1_appendR: \"P \\<turnstile> c \\<rightarrow> c' \\<Longrightarrow> P@P' \\<turnstile> c \\<rightarrow> c'\"\nby (auto simp: exec1_def)\n\nlemma exec_appendR: \"P \\<turnstile> c \\<rightarrow>* c' \\<Longrightarrow> P@P' \\<turnstile> c \\<rightarrow>* c'\"\nby (induction rule: star.induct) (fastforce intro: exec1_appendR)+\n\nlemma exec1_appendL:\n  fixes i i' :: int \n  shows\n  \"P \\<turnstile> (i,s,stk) \\<rightarrow> (i',s',stk') \\<Longrightarrow>\n   P' @ P \\<turnstile> (size(P')+i,s,stk) \\<rightarrow> (size(P')+i',s',stk')\"\n  unfolding exec1_def\n  by (auto simp del: iexec.simps)\n\nlemma exec_appendL:\n  fixes i i' :: int \n  shows\n \"P \\<turnstile> (i,s,stk) \\<rightarrow>* (i',s',stk')  \\<Longrightarrow>\n  P' @ P \\<turnstile> (size(P')+i,s,stk) \\<rightarrow>* (size(P')+i',s',stk')\"\n  by (induction rule: exec_induct) (blast intro!: exec1_appendL)+\n\ntext{* Now we specialise the above lemmas to enable automatic proofs of\n@{prop \"P \\<turnstile> c \\<rightarrow>* c'\"} where @{text P} is a mixture of concrete instructions and\npieces of code that we already know how they execute (by induction), combined\nby @{text \"@\"} and @{text \"#\"}. Backward jumps are not supported.\nThe details should be skipped on a first reading.\n\nIf we have just executed the first instruction of the program, drop it: *}\n\nlemma exec_Cons_1 [intro]:\n  \"P \\<turnstile> (0,s,stk) \\<rightarrow>* (j,t,stk') \\<Longrightarrow>\n  instr#P \\<turnstile> (1,s,stk) \\<rightarrow>* (1+j,t,stk')\"\nby (drule exec_appendL[where P'=\"[instr]\"]) simp\n\nlemma exec_appendL_if[intro]:\n  fixes i i' j :: int\n  shows\n  \"size P' <= i\n   \\<Longrightarrow> P \\<turnstile> (i - size P',s,stk) \\<rightarrow>* (j,s',stk')\n   \\<Longrightarrow> i' = size P' + j\n   \\<Longrightarrow> P' @ P \\<turnstile> (i,s,stk) \\<rightarrow>* (i',s',stk')\"\nby (drule exec_appendL[where P'=P']) simp\n\ntext{* Split the execution of a compound program up into the excution of its\nparts: *}\n\nlemma exec_append_trans[intro]:\n  fixes i' i'' j'' :: int\n  shows\n\"P \\<turnstile> (0,s,stk) \\<rightarrow>* (i',s',stk') \\<Longrightarrow>\n size P \\<le> i' \\<Longrightarrow>\n P' \\<turnstile>  (i' - size P,s',stk') \\<rightarrow>* (i'',s'',stk'') \\<Longrightarrow>\n j'' = size P + i''\n \\<Longrightarrow>\n P @ P' \\<turnstile> (0,s,stk) \\<rightarrow>* (j'',s'',stk'')\"\nby(metis star_trans[OF exec_appendR exec_appendL_if])\n\n\ndeclare Let_def[simp]\n\n\nsubsection \"Compilation\"\n\nfun acomp :: \"aexp \\<Rightarrow> instr list\" where\n\"acomp (N n) = [LOADI n]\" |\n\"acomp (V x) = [LOAD x]\" |\n\"acomp (Plus a1 a2) = acomp a1 @ acomp a2 @ [ADD]\"\n\nlemma acomp_correct[intro]:\n  \"acomp a \\<turnstile> (0,s,stk) \\<rightarrow>* (size(acomp a),s,aval a s#stk)\"\nby (induction a arbitrary: stk) fastforce+\n\nfun bcomp :: \"bexp \\<Rightarrow> bool \\<Rightarrow> int \\<Rightarrow> instr list\" where\n\"bcomp (Bc v) f n = (if v=f then [JMP n] else [])\" |\n\"bcomp (Not b) f n = bcomp b (\\<not>f) n\" |\n\"bcomp (And b1 b2) f n =\n (let cb2 = bcomp b2 f n;\n        m = (if f then size cb2 else (size cb2::int)+n);\n      cb1 = bcomp b1 False m\n  in cb1 @ cb2)\" |\n\"bcomp (Less a1 a2) f n =\n acomp a1 @ acomp a2 @ (if f then [JMPLESS n] else [JMPGE n])\"\n\nvalue\n  \"bcomp (And (Less (V ''x'') (V ''y'')) (Not(Less (V ''u'') (V ''v''))))\n     False 3\"\n\nlemma bcomp_correct[intro]:\n  fixes n :: int\n  shows\n  \"0 \\<le> n \\<Longrightarrow>\n  bcomp b f n \\<turnstile>\n (0,s,stk)  \\<rightarrow>*  (size(bcomp b f n) + (if f = bval b s then n else 0),s,stk)\"\nproof(induction b arbitrary: f n)\n  case Not\n  from Not(1)[where f=\"~f\"] Not(2) show ?case by fastforce\nnext\n  case (And b1 b2)\n  from And(1)[of \"if f then size(bcomp b2 f n) else size(bcomp b2 f n) + n\" \n                 \"False\"] \n       And(2)[of n f] And(3) \n  show ?case by fastforce\nqed fastforce+\n\nfun ccomp :: \"com \\<Rightarrow> instr list\" where\n\"ccomp SKIP = []\" |\n\"ccomp (x ::= a) = acomp a @ [STORE x]\" |\n\"ccomp (c\\<^sub>1;;c\\<^sub>2) = ccomp c\\<^sub>1 @ ccomp c\\<^sub>2\" |\n\"ccomp (IF b THEN c\\<^sub>1 ELSE c\\<^sub>2) =\n  (let cc\\<^sub>1 = ccomp c\\<^sub>1; cc\\<^sub>2 = ccomp c\\<^sub>2; cb = bcomp b False (size cc\\<^sub>1 + 1)\n   in cb @ cc\\<^sub>1 @ JMP (size cc\\<^sub>2) # cc\\<^sub>2)\" |\n\"ccomp (WHILE b DO c) =\n (let cc = ccomp c; cb = bcomp b False (size cc + 1)\n  in cb @ cc @ [JMP (-(size cb + size cc + 1))])\" |\n(* begin mod *)\n\"ccomp (REPEAT c UNTIL b) =\n  (let cc = ccomp c; cb = bcomp b True 1\n    in cc @ cb @ [JMP (-(size cb + size cc + 1))])\"\n(* end mod *)\n\nvalue \"ccomp (REPEAT ''u'' ::= Plus (V ''u'') (N 1) UNTIL Less (N 0) (V ''u''))\"\n\n\nsubsection \"Preservation of semantics\"\n\nlemma ccomp_bigstep:\n  \"(c,s) \\<Rightarrow> t \\<Longrightarrow> ccomp c \\<turnstile> (0,s,stk) \\<rightarrow>* (size(ccomp c),t,stk)\"\nproof(induction arbitrary: stk rule: big_step_induct)\n  case (Assign x a s)\n  show ?case by (fastforce simp:fun_upd_def cong: if_cong)\nnext\n  case (Seq c1 s1 s2 c2 s3)\n  let ?cc1 = \"ccomp c1\"  let ?cc2 = \"ccomp c2\"\n  have \"?cc1 @ ?cc2 \\<turnstile> (0,s1,stk) \\<rightarrow>* (size ?cc1,s2,stk)\"\n    using Seq.IH(1) by fastforce\n  moreover\n  have \"?cc1 @ ?cc2 \\<turnstile> (size ?cc1,s2,stk) \\<rightarrow>* (size(?cc1 @ ?cc2),s3,stk)\"\n    using Seq.IH(2) by fastforce\n  ultimately show ?case by simp (blast intro: star_trans)\nnext\n  case (WhileTrue b s1 c s2 s3)\n  let ?cc = \"ccomp c\"\n  let ?cb = \"bcomp b False (size ?cc + 1)\"\n  let ?cw = \"ccomp(WHILE b DO c)\"\n  have \"?cw \\<turnstile> (0,s1,stk) \\<rightarrow>* (size ?cb,s1,stk)\"\n    using `bval b s1` by fastforce\n  moreover\n  have \"?cw \\<turnstile> (size ?cb,s1,stk) \\<rightarrow>* (size ?cb + size ?cc,s2,stk)\"\n    using WhileTrue.IH(1) by fastforce\n  moreover\n  have \"?cw \\<turnstile> (size ?cb + size ?cc,s2,stk) \\<rightarrow>* (0,s2,stk)\"\n    by fastforce\n  moreover\n  have \"?cw \\<turnstile> (0,s2,stk) \\<rightarrow>* (size ?cw,s3,stk)\" by(rule WhileTrue.IH(2))\n  ultimately show ?case by(blast intro: star_trans)\nnext\n  case (RepeatTrue c s1 s2 b)\n  let ?cc = \"ccomp c\"\n  let ?cb = \"bcomp b True 1\"\n  let ?cr = \"ccomp(REPEAT c UNTIL b)\"\n  have \"?cr \\<turnstile> (0, s1, stk) \\<rightarrow>* (size ?cc, s2, stk)\"\n    using RepeatTrue.IH and ccomp.simps(6) by fastforce\n  moreover\n  have \"?cr \\<turnstile> (size ?cc, s2, stk) \\<rightarrow>* (size ?cr, s2, stk)\" \n    using `bval b s2` by fastforce\n  ultimately\n  show ?case by(blast intro: star_trans)\nnext\n  case (RepeatFalse c s1 s2 b s3)\n  let ?cc = \"ccomp c\"\n  let ?cb = \"bcomp b True 1\"\n  let ?cr = \"ccomp(REPEAT c UNTIL b)\"\n  have \"?cr \\<turnstile> (0, s1, stk) \\<rightarrow>* (size ?cc, s2, stk)\"\n    using RepeatFalse.IH by fastforce\n  moreover\n  have \"?cr \\<turnstile> (size ?cc, s2, stk) \\<rightarrow>* (size ?cc + size ?cb, s2, stk)\"\n    using `\\<not>bval b s2` by fastforce\n  moreover\n  have \"?cr \\<turnstile> (size ?cc + size ?cb, s2, stk) \\<rightarrow>* (0, s2, stk)\"\n    using RepeatFalse.IH by fastforce\n  moreover\n  have \"?cr \\<turnstile> (0, s2, stk) \\<rightarrow>* (size ?cr, s3, stk)\"\n    using RepeatFalse.IH by fastforce\n  ultimately\n  show ?case by(blast intro: star_trans)\nqed fastforce+\n\nend\n", "meta": {"author": "glimonta", "repo": "Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "save_path": "github-repos/isabelle/glimonta-Semantics", "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise7/GabrielaLimontaFeedback2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094117351309, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7538594358755706}}
{"text": "(*:maxLineLen=78:*)\n\nsection \\<open>Example: First-Order Logic\\<close>\n\ntheory %visible First_Order_Logic\nimports Base  (* FIXME Pure!? *)\nbegin\n\ntext \\<open>\n  In order to commence a new object-logic within Isabelle/Pure we introduce\n  abstract syntactic categories \\<open>i\\<close> for individuals and \\<open>o\\<close> for\n  object-propositions. The latter is embedded into the language of Pure\n  propositions by means of a separate judgment.\n\\<close>\n\ntypedecl i\ntypedecl o\n\njudgment Trueprop :: \"o \\<Rightarrow> prop\"    (\"_\" 5)\n\ntext \\<open>\n  Note that the object-logic judgment is implicit in the syntax: writing\n  @{prop A} produces @{term \"Trueprop A\"} internally. From the Pure\n  perspective this means ``@{prop A} is derivable in the object-logic''.\n\\<close>\n\n\nsubsection \\<open>Equational reasoning \\label{sec:framework-ex-equal}\\<close>\n\ntext \\<open>\n  Equality is axiomatized as a binary predicate on individuals, with\n  reflexivity as introduction, and substitution as elimination principle. Note\n  that the latter is particularly convenient in a framework like Isabelle,\n  because syntactic congruences are implicitly produced by unification of\n  \\<open>B x\\<close> against expressions containing occurrences of \\<open>x\\<close>.\n\\<close>\n\naxiomatization equal :: \"i \\<Rightarrow> i \\<Rightarrow> o\"  (infix \"=\" 50)\n  where refl [intro]: \"x = x\"\n    and subst [elim]: \"x = y \\<Longrightarrow> B x \\<Longrightarrow> B y\"\n\ntext \\<open>\n  Substitution is very powerful, but also hard to control in full generality.\n  We derive some common symmetry~/ transitivity schemes of @{term equal} as\n  particular consequences.\n\\<close>\n\ntheorem sym [sym]:\n  assumes \"x = y\"\n  shows \"y = x\"\nproof -\n  have \"x = x\" ..\n  with \\<open>x = y\\<close> show \"y = x\" ..\nqed\n\ntheorem forw_subst [trans]:\n  assumes \"y = x\" and \"B x\"\n  shows \"B y\"\nproof -\n  from \\<open>y = x\\<close> have \"x = y\" ..\n  from this and \\<open>B x\\<close> show \"B y\" ..\nqed\n\ntheorem back_subst [trans]:\n  assumes \"B x\" and \"x = y\"\n  shows \"B y\"\nproof -\n  from \\<open>x = y\\<close> and \\<open>B x\\<close>\n  show \"B y\" ..\nqed\n\ntheorem trans [trans]:\n  assumes \"x = y\" and \"y = z\"\n  shows \"x = z\"\nproof -\n  from \\<open>y = z\\<close> and \\<open>x = y\\<close>\n  show \"x = z\" ..\nqed\n\n\nsubsection \\<open>Basic group theory\\<close>\n\ntext \\<open>\n  As an example for equational reasoning we consider some bits of group\n  theory. The subsequent locale definition postulates group operations and\n  axioms; we also derive some consequences of this specification.\n\\<close>\n\nlocale group =\n  fixes prod :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infix \"\\<circ>\" 70)\n    and inv :: \"i \\<Rightarrow> i\"  (\"(_\\<inverse>)\" [1000] 999)\n    and unit :: i  (\"1\")\n  assumes assoc: \"(x \\<circ> y) \\<circ> z = x \\<circ> (y \\<circ> z)\"\n    and left_unit:  \"1 \\<circ> x = x\"\n    and left_inv: \"x\\<inverse> \\<circ> x = 1\"\nbegin\n\ntheorem right_inv: \"x \\<circ> x\\<inverse> = 1\"\nproof -\n  have \"x \\<circ> x\\<inverse> = 1 \\<circ> (x \\<circ> x\\<inverse>)\" by (rule left_unit [symmetric])\n  also have \"\\<dots> = (1 \\<circ> x) \\<circ> x\\<inverse>\" by (rule assoc [symmetric])\n  also have \"1 = (x\\<inverse>)\\<inverse> \\<circ> x\\<inverse>\" by (rule left_inv [symmetric])\n  also have \"\\<dots> \\<circ> x = (x\\<inverse>)\\<inverse> \\<circ> (x\\<inverse> \\<circ> x)\" by (rule assoc)\n  also have \"x\\<inverse> \\<circ> x = 1\" by (rule left_inv)\n  also have \"((x\\<inverse>)\\<inverse> \\<circ> \\<dots>) \\<circ> x\\<inverse> = (x\\<inverse>)\\<inverse> \\<circ> (1 \\<circ> x\\<inverse>)\" by (rule assoc)\n  also have \"1 \\<circ> x\\<inverse> = x\\<inverse>\" by (rule left_unit)\n  also have \"(x\\<inverse>)\\<inverse> \\<circ> \\<dots> = 1\" by (rule left_inv)\n  finally show \"x \\<circ> x\\<inverse> = 1\" .\nqed\n\ntheorem right_unit: \"x \\<circ> 1 = x\"\nproof -\n  have \"1 = x\\<inverse> \\<circ> x\" by (rule left_inv [symmetric])\n  also have \"x \\<circ> \\<dots> = (x \\<circ> x\\<inverse>) \\<circ> x\" by (rule assoc [symmetric])\n  also have \"x \\<circ> x\\<inverse> = 1\" by (rule right_inv)\n  also have \"\\<dots> \\<circ> x = x\" by (rule left_unit)\n  finally show \"x \\<circ> 1 = x\" .\nqed\n\ntext \\<open>\n  Reasoning from basic axioms is often tedious. Our proofs work by producing\n  various instances of the given rules (potentially the symmetric form) using\n  the pattern ``\\<^theory_text>\\<open>have eq by (rule r)\\<close>'' and composing the chain of results\n  via \\<^theory_text>\\<open>also\\<close>/\\<^theory_text>\\<open>finally\\<close>. These steps may involve any of the transitivity\n  rules declared in \\secref{sec:framework-ex-equal}, namely @{thm trans} in\n  combining the first two results in @{thm right_inv} and in the final steps\n  of both proofs, @{thm forw_subst} in the first combination of @{thm\n  right_unit}, and @{thm back_subst} in all other calculational steps.\n\n  Occasional substitutions in calculations are adequate, but should not be\n  over-emphasized. The other extreme is to compose a chain by plain\n  transitivity only, with replacements occurring always in topmost position.\n  For example:\n\\<close>\n\n(*<*)\ntheorem \"\\<And>A. PROP A \\<Longrightarrow> PROP A\"\nproof -\n  assume [symmetric, defn]: \"\\<And>x y. (x \\<equiv> y) \\<equiv> Trueprop (x = y)\"\n  fix x\n(*>*)\n  have \"x \\<circ> 1 = x \\<circ> (x\\<inverse> \\<circ> x)\" unfolding left_inv ..\n  also have \"\\<dots> = (x \\<circ> x\\<inverse>) \\<circ> x\" unfolding assoc ..\n  also have \"\\<dots> = 1 \\<circ> x\" unfolding right_inv ..\n  also have \"\\<dots> = x\" unfolding left_unit ..\n  finally have \"x \\<circ> 1 = x\" .\n(*<*)\nqed\n(*>*)\n\ntext \\<open>\n  Here we have re-used the built-in mechanism for unfolding definitions in\n  order to normalize each equational problem. A more realistic object-logic\n  would include proper setup for the Simplifier (\\secref{sec:simplifier}), the\n  main automated tool for equational reasoning in Isabelle. Then ``\\<^theory_text>\\<open>unfolding\n  left_inv ..\\<close>'' would become ``\\<^theory_text>\\<open>by (simp only: left_inv)\\<close>'' etc.\n\\<close>\n\nend\n\n\nsubsection \\<open>Propositional logic \\label{sec:framework-ex-prop}\\<close>\n\ntext \\<open>\n  We axiomatize basic connectives of propositional logic: implication,\n  disjunction, and conjunction. The associated rules are modeled after\n  Gentzen's system of Natural Deduction @{cite \"Gentzen:1935\"}.\n\\<close>\n\naxiomatization imp :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<longrightarrow>\" 25)\n  where impI [intro]: \"(A \\<Longrightarrow> B) \\<Longrightarrow> A \\<longrightarrow> B\"\n    and impD [dest]: \"(A \\<longrightarrow> B) \\<Longrightarrow> A \\<Longrightarrow> B\"\n\naxiomatization disj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<or>\" 30)\n  where disjI\\<^sub>1 [intro]: \"A \\<Longrightarrow> A \\<or> B\"\n    and disjI\\<^sub>2 [intro]: \"B \\<Longrightarrow> A \\<or> B\"\n    and disjE [elim]: \"A \\<or> B \\<Longrightarrow> (A \\<Longrightarrow> C) \\<Longrightarrow> (B \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\naxiomatization conj :: \"o \\<Rightarrow> o \\<Rightarrow> o\"  (infixr \"\\<and>\" 35)\n  where conjI [intro]: \"A \\<Longrightarrow> B \\<Longrightarrow> A \\<and> B\"\n    and conjD\\<^sub>1: \"A \\<and> B \\<Longrightarrow> A\"\n    and conjD\\<^sub>2: \"A \\<and> B \\<Longrightarrow> B\"\n\ntext \\<open>\n  The conjunctive destructions have the disadvantage that decomposing @{prop\n  \"A \\<and> B\"} involves an immediate decision which component should be projected.\n  The more convenient simultaneous elimination @{prop \"A \\<and> B \\<Longrightarrow> (A \\<Longrightarrow> B \\<Longrightarrow> C) \\<Longrightarrow>\n  C\"} can be derived as follows:\n\\<close>\n\ntheorem conjE [elim]:\n  assumes \"A \\<and> B\"\n  obtains A and B\nproof\n  from \\<open>A \\<and> B\\<close> show A by (rule conjD\\<^sub>1)\n  from \\<open>A \\<and> B\\<close> show B by (rule conjD\\<^sub>2)\nqed\n\ntext \\<open>\n  Here is an example of swapping conjuncts with a single intermediate\n  elimination step:\n\\<close>\n\n(*<*)\nlemma \"\\<And>A. PROP A \\<Longrightarrow> PROP A\"\nproof -\n  fix A B\n(*>*)\n  assume \"A \\<and> B\"\n  then obtain B and A ..\n  then have \"B \\<and> A\" ..\n(*<*)\nqed\n(*>*)\n\ntext \\<open>\n  Note that the analogous elimination rule for disjunction ``\\<^theory_text>\\<open>assumes \"A \\<or> B\"\n  obtains A \\<BBAR> B\\<close>'' coincides with the original axiomatization of @{thm\n  disjE}.\n\n  \\<^medskip>\n  We continue propositional logic by introducing absurdity with its\n  characteristic elimination. Plain truth may then be defined as a proposition\n  that is trivially true.\n\\<close>\n\naxiomatization false :: o  (\"\\<bottom>\")\n  where falseE [elim]: \"\\<bottom> \\<Longrightarrow> A\"\n\ndefinition true :: o  (\"\\<top>\")\n  where \"\\<top> \\<equiv> \\<bottom> \\<longrightarrow> \\<bottom>\"\n\ntheorem trueI [intro]: \\<top>\n  unfolding true_def ..\n\ntext \\<open>\n  \\<^medskip>\n  Now negation represents an implication towards absurdity:\n\\<close>\n\ndefinition not :: \"o \\<Rightarrow> o\"  (\"\\<not> _\" [40] 40)\n  where \"\\<not> A \\<equiv> A \\<longrightarrow> \\<bottom>\"\n\ntheorem notI [intro]:\n  assumes \"A \\<Longrightarrow> \\<bottom>\"\n  shows \"\\<not> A\"\nunfolding not_def\nproof\n  assume A\n  then show \\<bottom> by (rule \\<open>A \\<Longrightarrow> \\<bottom>\\<close>)\nqed\n\ntheorem notE [elim]:\n  assumes \"\\<not> A\" and A\n  shows B\nproof -\n  from \\<open>\\<not> A\\<close> have \"A \\<longrightarrow> \\<bottom>\" unfolding not_def .\n  from \\<open>A \\<longrightarrow> \\<bottom>\\<close> and \\<open>A\\<close> have \\<bottom> ..\n  then show B ..\nqed\n\n\nsubsection \\<open>Classical logic\\<close>\n\ntext \\<open>\n  Subsequently we state the principle of classical contradiction as a local\n  assumption. Thus we refrain from forcing the object-logic into the classical\n  perspective. Within that context, we may derive well-known consequences of\n  the classical principle.\n\\<close>\n\nlocale classical =\n  assumes classical: \"(\\<not> C \\<Longrightarrow> C) \\<Longrightarrow> C\"\nbegin\n\ntheorem double_negation:\n  assumes \"\\<not> \\<not> C\"\n  shows C\nproof (rule classical)\n  assume \"\\<not> C\"\n  with \\<open>\\<not> \\<not> C\\<close> show C ..\nqed\n\ntheorem tertium_non_datur: \"C \\<or> \\<not> C\"\nproof (rule double_negation)\n  show \"\\<not> \\<not> (C \\<or> \\<not> C)\"\n  proof\n    assume \"\\<not> (C \\<or> \\<not> C)\"\n    have \"\\<not> C\"\n    proof\n      assume C then have \"C \\<or> \\<not> C\" ..\n      with \\<open>\\<not> (C \\<or> \\<not> C)\\<close> show \\<bottom> ..\n    qed\n    then have \"C \\<or> \\<not> C\" ..\n    with \\<open>\\<not> (C \\<or> \\<not> C)\\<close> show \\<bottom> ..\n  qed\nqed\n\ntext \\<open>\n  These examples illustrate both classical reasoning and non-trivial\n  propositional proofs in general. All three rules characterize classical\n  logic independently, but the original rule is already the most convenient to\n  use, because it leaves the conclusion unchanged. Note that @{prop \"(\\<not> C \\<Longrightarrow> C)\n  \\<Longrightarrow> C\"} fits again into our format for eliminations, despite the additional\n  twist that the context refers to the main conclusion. So we may write @{thm\n  classical} as the Isar statement ``\\<^theory_text>\\<open>obtains \\<not> thesis\\<close>''. This also explains\n  nicely how classical reasoning really works: whatever the main \\<open>thesis\\<close>\n  might be, we may always assume its negation!\n\\<close>\n\nend\n\n\nsubsection \\<open>Quantifiers \\label{sec:framework-ex-quant}\\<close>\n\ntext \\<open>\n  Representing quantifiers is easy, thanks to the higher-order nature of the\n  underlying framework. According to the well-known technique introduced by\n  Church @{cite \"church40\"}, quantifiers are operators on predicates, which\n  are syntactically represented as \\<open>\\<lambda>\\<close>-terms of type @{typ \"i \\<Rightarrow> o\"}. Binder\n  notation turns \\<open>All (\\<lambda>x. B x)\\<close> into \\<open>\\<forall>x. B x\\<close> etc.\n\\<close>\n\naxiomatization All :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<forall>\" 10)\n  where allI [intro]: \"(\\<And>x. B x) \\<Longrightarrow> \\<forall>x. B x\"\n    and allD [dest]: \"(\\<forall>x. B x) \\<Longrightarrow> B a\"\n\naxiomatization Ex :: \"(i \\<Rightarrow> o) \\<Rightarrow> o\"  (binder \"\\<exists>\" 10)\n  where exI [intro]: \"B a \\<Longrightarrow> (\\<exists>x. B x)\"\n    and exE [elim]: \"(\\<exists>x. B x) \\<Longrightarrow> (\\<And>x. B x \\<Longrightarrow> C) \\<Longrightarrow> C\"\n\ntext \\<open>\n  The statement of @{thm exE} corresponds to ``\\<^theory_text>\\<open>assumes \"\\<exists>x. B x\" obtains x\n  where \"B x\"\\<close>'' in Isar. In the subsequent example we illustrate quantifier\n  reasoning involving all four rules:\n\\<close>\n\ntheorem\n  assumes \"\\<exists>x. \\<forall>y. R x y\"\n  shows \"\\<forall>y. \\<exists>x. R x y\"\nproof    \\<comment> \\<open>\\<open>\\<forall>\\<close> introduction\\<close>\n  obtain x where \"\\<forall>y. R x y\" using \\<open>\\<exists>x. \\<forall>y. R x y\\<close> ..    \\<comment> \\<open>\\<open>\\<exists>\\<close> elimination\\<close>\n  fix y have \"R x y\" using \\<open>\\<forall>y. R x y\\<close> ..    \\<comment> \\<open>\\<open>\\<forall>\\<close> destruction\\<close>\n  then show \"\\<exists>x. R x y\" ..    \\<comment> \\<open>\\<open>\\<exists>\\<close> introduction\\<close>\nqed\n\n\nsubsection \\<open>Canonical reasoning patterns\\<close>\n\ntext \\<open>\n  The main rules of first-order predicate logic from\n  \\secref{sec:framework-ex-prop} and \\secref{sec:framework-ex-quant} can now\n  be summarized as follows, using the native Isar statement format of\n  \\secref{sec:framework-stmt}.\n\n  \\<^medskip>\n  \\begin{tabular}{l}\n  \\<^theory_text>\\<open>impI: assumes \"A \\<Longrightarrow> B\" shows \"A \\<longrightarrow> B\"\\<close> \\\\\n  \\<^theory_text>\\<open>impD: assumes \"A \\<longrightarrow> B\" and A shows B\\<close> \\\\[1ex]\n\n  \\<^theory_text>\\<open>disjI\\<^sub>1: assumes A shows \"A \\<or> B\"\\<close> \\\\\n  \\<^theory_text>\\<open>disjI\\<^sub>2: assumes B shows \"A \\<or> B\"\\<close> \\\\\n  \\<^theory_text>\\<open>disjE: assumes \"A \\<or> B\" obtains A \\<BBAR> B\\<close> \\\\[1ex]\n\n  \\<^theory_text>\\<open>conjI: assumes A and B shows A \\<and> B\\<close> \\\\\n  \\<^theory_text>\\<open>conjE: assumes \"A \\<and> B\" obtains A and B\\<close> \\\\[1ex]\n\n  \\<^theory_text>\\<open>falseE: assumes \\<bottom> shows A\\<close> \\\\\n  \\<^theory_text>\\<open>trueI: shows \\<top>\\<close> \\\\[1ex]\n\n  \\<^theory_text>\\<open>notI: assumes \"A \\<Longrightarrow> \\<bottom>\" shows \"\\<not> A\"\\<close> \\\\\n  \\<^theory_text>\\<open>notE: assumes \"\\<not> A\" and A shows B\\<close> \\\\[1ex]\n\n  \\<^theory_text>\\<open>allI: assumes \"\\<And>x. B x\" shows \"\\<forall>x. B x\"\\<close> \\\\\n  \\<^theory_text>\\<open>allE: assumes \"\\<forall>x. B x\" shows \"B a\"\\<close> \\\\[1ex]\n\n  \\<^theory_text>\\<open>exI: assumes \"B a\" shows \"\\<exists>x. B x\"\\<close> \\\\\n  \\<^theory_text>\\<open>exE: assumes \"\\<exists>x. B x\" obtains a where \"B a\"\\<close>\n  \\end{tabular}\n  \\<^medskip>\n\n  This essentially provides a declarative reading of Pure rules as Isar\n  reasoning patterns: the rule statements tells how a canonical proof outline\n  shall look like. Since the above rules have already been declared as\n  @{attribute (Pure) intro}, @{attribute (Pure) elim}, @{attribute (Pure)\n  dest} --- each according to its particular shape --- we can immediately\n  write Isar proof texts as follows:\n\\<close>\n\n(*<*)\ntheorem \"\\<And>A. PROP A \\<Longrightarrow> PROP A\"\nproof -\n(*>*)\n\n  text_raw \\<open>\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"A \\<longrightarrow> B\"\n  proof\n    assume A\n    show B \\<proof>\n  qed\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"A \\<longrightarrow> B\" and A \\<proof>\n  then have B ..\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have A \\<proof>\n  then have \"A \\<or> B\" ..\n\n  have B \\<proof>\n  then have \"A \\<or> B\" ..\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"A \\<or> B\" \\<proof>\n  then have C\n  proof\n    assume A\n    then show C \\<proof>\n  next\n    assume B\n    then show C \\<proof>\n  qed\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have A and B \\<proof>\n  then have \"A \\<and> B\" ..\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"A \\<and> B\" \\<proof>\n  then obtain A and B ..\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<bottom>\" \\<proof>\n  then have A ..\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<top>\" ..\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<not> A\"\n  proof\n    assume A\n    then show \"\\<bottom>\" \\<proof>\n  qed\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<not> A\" and A \\<proof>\n  then have B ..\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<forall>x. B x\"\n  proof\n    fix x\n    show \"B x\" \\<proof>\n  qed\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<forall>x. B x\" \\<proof>\n  then have \"B a\" ..\n\n  text_raw \\<open>\\end{minipage}\\\\[3ex]\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<exists>x. B x\"\n  proof\n    show \"B a\" \\<proof>\n  qed\n\n  text_raw \\<open>\\end{minipage}\\qquad\\begin{minipage}[t]{0.4\\textwidth}\\<close>(*<*)next(*>*)\n\n  have \"\\<exists>x. B x\" \\<proof>\n  then obtain a where \"B a\" ..\n\n  text_raw \\<open>\\end{minipage}\\<close>\n\n(*<*)\nqed\n(*>*)\n\ntext \\<open>\n  \\<^bigskip>\n  Of course, these proofs are merely examples. As sketched in\n  \\secref{sec:framework-subproof}, there is a fair amount of flexibility in\n  expressing Pure deductions in Isar. Here the user is asked to express\n  himself adequately, aiming at proof texts of literary quality.\n\\<close>\n\nend %visible\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Isar_Ref/First_Order_Logic.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.8558511396138365, "lm_q1q2_score": 0.7538311883119144}}
{"text": "(*  Title:      HOL/Isar_Examples/Mutilated_Checkerboard.thy\n    Author:     Markus Wenzel, TU Muenchen (Isar document)\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory (original scripts)\n*)\n\nsection \\<open>The Mutilated Checker Board Problem\\<close>\n\ntheory Mutilated_Checkerboard\n  imports Main\nbegin\n\ntext \\<open>\n  The Mutilated Checker Board Problem, formalized inductively. See @{cite\n  \"paulson-mutilated-board\"} for the original tactic script version.\n\\<close>\n\nsubsection \\<open>Tilings\\<close>\n\ninductive_set tiling :: \"'a set set \\<Rightarrow> 'a set set\" for A :: \"'a set set\"\n  where\n    empty: \"{} \\<in> tiling A\"\n  | Un: \"a \\<union> t \\<in> tiling A\" if \"a \\<in> A\" and \"t \\<in> tiling A\" and \"a \\<subseteq> - t\"\n\n\ntext \\<open>The union of two disjoint tilings is a tiling.\\<close>\n\nlemma tiling_Un:\n  assumes \"t \\<in> tiling A\"\n    and \"u \\<in> tiling A\"\n    and \"t \\<inter> u = {}\"\n  shows \"t \\<union> u \\<in> tiling A\"\nproof -\n  let ?T = \"tiling A\"\n  from \\<open>t \\<in> ?T\\<close> and \\<open>t \\<inter> u = {}\\<close>\n  show \"t \\<union> u \\<in> ?T\"\n  proof (induct t)\n    case empty\n    with \\<open>u \\<in> ?T\\<close> show \"{} \\<union> u \\<in> ?T\" by simp\n  next\n    case (Un a t)\n    show \"(a \\<union> t) \\<union> u \\<in> ?T\"\n    proof -\n      have \"a \\<union> (t \\<union> u) \\<in> ?T\"\n        using \\<open>a \\<in> A\\<close>\n      proof (rule tiling.Un)\n        from \\<open>(a \\<union> t) \\<inter> u = {}\\<close> have \"t \\<inter> u = {}\" by blast\n        then show \"t \\<union> u \\<in> ?T\" by (rule Un)\n        from \\<open>a \\<subseteq> - t\\<close> and \\<open>(a \\<union> t) \\<inter> u = {}\\<close>\n        show \"a \\<subseteq> - (t \\<union> u)\" by blast\n      qed\n      also have \"a \\<union> (t \\<union> u) = (a \\<union> t) \\<union> u\"\n        by (simp only: Un_assoc)\n      finally show ?thesis .\n    qed\n  qed\nqed\n\n\nsubsection \\<open>Basic properties of ``below''\\<close>\n\ndefinition below :: \"nat \\<Rightarrow> nat set\"\n  where \"below n = {i. i < n}\"\n\nlemma below_less_iff [iff]: \"i \\<in> below k \\<longleftrightarrow> i < k\"\n  by (simp add: below_def)\n\nlemma below_0: \"below 0 = {}\"\n  by (simp add: below_def)\n\nlemma Sigma_Suc1: \"m = n + 1 \\<Longrightarrow> below m \\<times> B = ({n} \\<times> B) \\<union> (below n \\<times> B)\"\n  by (simp add: below_def less_Suc_eq) blast\n\nlemma Sigma_Suc2:\n  \"m = n + 2 \\<Longrightarrow>\n    A \\<times> below m = (A \\<times> {n}) \\<union> (A \\<times> {n + 1}) \\<union> (A \\<times> below n)\"\n  by (auto simp add: below_def)\n\nlemmas Sigma_Suc = Sigma_Suc1 Sigma_Suc2\n\n\nsubsection \\<open>Basic properties of ``evnodd''\\<close>\n\ndefinition evnodd :: \"(nat \\<times> nat) set \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"evnodd A b = A \\<inter> {(i, j). (i + j) mod 2 = b}\"\n\nlemma evnodd_iff: \"(i, j) \\<in> evnodd A b \\<longleftrightarrow> (i, j) \\<in> A  \\<and> (i + j) mod 2 = b\"\n  by (simp add: evnodd_def)\n\nlemma evnodd_subset: \"evnodd A b \\<subseteq> A\"\n  unfolding evnodd_def by (rule Int_lower1)\n\nlemma evnoddD: \"x \\<in> evnodd A b \\<Longrightarrow> x \\<in> A\"\n  by (rule subsetD) (rule evnodd_subset)\n\nlemma evnodd_finite: \"finite A \\<Longrightarrow> finite (evnodd A b)\"\n  by (rule finite_subset) (rule evnodd_subset)\n\nlemma evnodd_Un: \"evnodd (A \\<union> B) b = evnodd A b \\<union> evnodd B b\"\n  unfolding evnodd_def by blast\n\nlemma evnodd_Diff: \"evnodd (A - B) b = evnodd A b - evnodd B b\"\n  unfolding evnodd_def by blast\n\nlemma evnodd_empty: \"evnodd {} b = {}\"\n  by (simp add: evnodd_def)\n\nlemma evnodd_insert: \"evnodd (insert (i, j) C) b =\n    (if (i + j) mod 2 = b\n      then insert (i, j) (evnodd C b) else evnodd C b)\"\n  by (simp add: evnodd_def)\n\n\nsubsection \\<open>Dominoes\\<close>\n\ninductive_set domino :: \"(nat \\<times> nat) set set\"\n  where\n    horiz: \"{(i, j), (i, j + 1)} \\<in> domino\"\n  | vertl: \"{(i, j), (i + 1, j)} \\<in> domino\"\n\nlemma dominoes_tile_row:\n  \"{i} \\<times> below (2 * n) \\<in> tiling domino\"\n  (is \"?B n \\<in> ?T\")\nproof (induct n)\n  case 0\n  show ?case by (simp add: below_0 tiling.empty)\nnext\n  case (Suc n)\n  let ?a = \"{i} \\<times> {2 * n + 1} \\<union> {i} \\<times> {2 * n}\"\n  have \"?B (Suc n) = ?a \\<union> ?B n\"\n    by (auto simp add: Sigma_Suc Un_assoc)\n  also have \"\\<dots> \\<in> ?T\"\n  proof (rule tiling.Un)\n    have \"{(i, 2 * n), (i, 2 * n + 1)} \\<in> domino\"\n      by (rule domino.horiz)\n    also have \"{(i, 2 * n), (i, 2 * n + 1)} = ?a\" by blast\n    finally show \"\\<dots> \\<in> domino\" .\n    show \"?B n \\<in> ?T\" by (rule Suc)\n    show \"?a \\<subseteq> - ?B n\" by blast\n  qed\n  finally show ?case .\nqed\n\nlemma dominoes_tile_matrix:\n  \"below m \\<times> below (2 * n) \\<in> tiling domino\"\n  (is \"?B m \\<in> ?T\")\nproof (induct m)\n  case 0\n  show ?case by (simp add: below_0 tiling.empty)\nnext\n  case (Suc m)\n  let ?t = \"{m} \\<times> below (2 * n)\"\n  have \"?B (Suc m) = ?t \\<union> ?B m\" by (simp add: Sigma_Suc)\n  also have \"\\<dots> \\<in> ?T\"\n  proof (rule tiling_Un)\n    show \"?t \\<in> ?T\" by (rule dominoes_tile_row)\n    show \"?B m \\<in> ?T\" by (rule Suc)\n    show \"?t \\<inter> ?B m = {}\" by blast\n  qed\n  finally show ?case .\nqed\n\nlemma domino_singleton:\n  assumes \"d \\<in> domino\"\n    and \"b < 2\"\n  shows \"\\<exists>i j. evnodd d b = {(i, j)}\"  (is \"?P d\")\n  using assms\nproof induct\n  from \\<open>b < 2\\<close> have b_cases: \"b = 0 \\<or> b = 1\" by arith\n  fix i j\n  note [simp] = evnodd_empty evnodd_insert mod_Suc\n  from b_cases show \"?P {(i, j), (i, j + 1)}\" by rule auto\n  from b_cases show \"?P {(i, j), (i + 1, j)}\" by rule auto\nqed\n\nlemma domino_finite:\n  assumes \"d \\<in> domino\"\n  shows \"finite d\"\n  using assms\nproof induct\n  fix i j :: nat\n  show \"finite {(i, j), (i, j + 1)}\" by (intro finite.intros)\n  show \"finite {(i, j), (i + 1, j)}\" by (intro finite.intros)\nqed\n\n\nsubsection \\<open>Tilings of dominoes\\<close>\n\nlemma tiling_domino_finite:\n  assumes t: \"t \\<in> tiling domino\"  (is \"t \\<in> ?T\")\n  shows \"finite t\"  (is \"?F t\")\n  using t\nproof induct\n  show \"?F {}\" by (rule finite.emptyI)\n  fix a t assume \"?F t\"\n  assume \"a \\<in> domino\"\n  then have \"?F a\" by (rule domino_finite)\n  from this and \\<open>?F t\\<close> show \"?F (a \\<union> t)\" by (rule finite_UnI)\nqed\n\nlemma tiling_domino_01:\n  assumes t: \"t \\<in> tiling domino\"  (is \"t \\<in> ?T\")\n  shows \"card (evnodd t 0) = card (evnodd t 1)\"\n  using t\nproof induct\n  case empty\n  show ?case by (simp add: evnodd_def)\nnext\n  case (Un a t)\n  let ?e = evnodd\n  note hyp = \\<open>card (?e t 0) = card (?e t 1)\\<close>\n    and at = \\<open>a \\<subseteq> - t\\<close>\n  have card_suc: \"card (?e (a \\<union> t) b) = Suc (card (?e t b))\" if \"b < 2\" for b :: nat\n  proof -\n    have \"?e (a \\<union> t) b = ?e a b \\<union> ?e t b\" by (rule evnodd_Un)\n    also obtain i j where e: \"?e a b = {(i, j)}\"\n    proof -\n      from \\<open>a \\<in> domino\\<close> and \\<open>b < 2\\<close>\n      have \"\\<exists>i j. ?e a b = {(i, j)}\" by (rule domino_singleton)\n      then show ?thesis by (blast intro: that)\n    qed\n    also have \"\\<dots> \\<union> ?e t b = insert (i, j) (?e t b)\" by simp\n    also have \"card \\<dots> = Suc (card (?e t b))\"\n    proof (rule card_insert_disjoint)\n      from \\<open>t \\<in> tiling domino\\<close> have \"finite t\"\n        by (rule tiling_domino_finite)\n      then show \"finite (?e t b)\"\n        by (rule evnodd_finite)\n      from e have \"(i, j) \\<in> ?e a b\" by simp\n      with at show \"(i, j) \\<notin> ?e t b\" by (blast dest: evnoddD)\n    qed\n    finally show ?thesis .\n  qed\n  then have \"card (?e (a \\<union> t) 0) = Suc (card (?e t 0))\" by simp\n  also from hyp have \"card (?e t 0) = card (?e t 1)\" .\n  also from card_suc have \"Suc \\<dots> = card (?e (a \\<union> t) 1)\"\n    by simp\n  finally show ?case .\nqed\n\n\nsubsection \\<open>Main theorem\\<close>\n\ndefinition mutilated_board :: \"nat \\<Rightarrow> nat \\<Rightarrow> (nat \\<times> nat) set\"\n  where \"mutilated_board m n =\n    below (2 * (m + 1)) \\<times> below (2 * (n + 1)) - {(0, 0)} - {(2 * m + 1, 2 * n + 1)}\"\n\ntheorem mutil_not_tiling: \"mutilated_board m n \\<notin> tiling domino\"\nproof (unfold mutilated_board_def)\n  let ?T = \"tiling domino\"\n  let ?t = \"below (2 * (m + 1)) \\<times> below (2 * (n + 1))\"\n  let ?t' = \"?t - {(0, 0)}\"\n  let ?t'' = \"?t' - {(2 * m + 1, 2 * n + 1)}\"\n\n  show \"?t'' \\<notin> ?T\"\n  proof\n    have t: \"?t \\<in> ?T\" by (rule dominoes_tile_matrix)\n    assume t'': \"?t'' \\<in> ?T\"\n\n    let ?e = evnodd\n    have fin: \"finite (?e ?t 0)\"\n      by (rule evnodd_finite, rule tiling_domino_finite, rule t)\n\n    note [simp] = evnodd_iff evnodd_empty evnodd_insert evnodd_Diff\n    have \"card (?e ?t'' 0) < card (?e ?t' 0)\"\n    proof -\n      have \"card (?e ?t' 0 - {(2 * m + 1, 2 * n + 1)})\n        < card (?e ?t' 0)\"\n      proof (rule card_Diff1_less)\n        from _ fin show \"finite (?e ?t' 0)\"\n          by (rule finite_subset) auto\n        show \"(2 * m + 1, 2 * n + 1) \\<in> ?e ?t' 0\" by simp\n      qed\n      then show ?thesis by simp\n    qed\n    also have \"\\<dots> < card (?e ?t 0)\"\n    proof -\n      have \"(0, 0) \\<in> ?e ?t 0\" by simp\n      with fin have \"card (?e ?t 0 - {(0, 0)}) < card (?e ?t 0)\"\n        by (rule card_Diff1_less)\n      then show ?thesis by simp\n    qed\n    also from t have \"\\<dots> = card (?e ?t 1)\"\n      by (rule tiling_domino_01)\n    also have \"?e ?t 1 = ?e ?t'' 1\" by simp\n    also from t'' have \"card \\<dots> = card (?e ?t'' 0)\"\n      by (rule tiling_domino_01 [symmetric])\n    finally have \"\\<dots> < \\<dots>\" . then show False ..\n  qed\nqed\n\nend\n", "meta": {"author": "m-fleury", "repo": "isabelle-emacs", "sha": "756c662195e138a1941d22d4dd7ff759cbf6b6b9", "save_path": "github-repos/isabelle/m-fleury-isabelle-emacs", "path": "github-repos/isabelle/m-fleury-isabelle-emacs/isabelle-emacs-756c662195e138a1941d22d4dd7ff759cbf6b6b9/src/HOL/Isar_Examples/Mutilated_Checkerboard.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797068590724, "lm_q2_score": 0.8558511506439708, "lm_q1q2_score": 0.7538311846372077}}
{"text": "(*  \n    Author:      René Thiemann \n                 Akihisa Yamada\n    License:     BSD\n*)\nsection \\<open>Lagrange Interpolation\\<close>\n\ntext \\<open>We formalized the Lagrange interpolation, i.e., a method to interpolate a polynomial $p$\n  from a list of points $(x_1,p(x_1)), (x_2, p(x_2)), \\ldots$. The interpolation algorithm is proven\n  to be sound and complete.\\<close>\n\ntheory Lagrange_Interpolation\nimports \n  Missing_Polynomial\nbegin\n\ndefinition lagrange_basis_poly :: \"'a :: field list \\<Rightarrow> 'a \\<Rightarrow> 'a poly\" where\n  \"lagrange_basis_poly xs xj \\<equiv> let ys = filter (\\<lambda> x. x \\<noteq> xj) xs\n    in prod_list (map (\\<lambda> xi. smult (inverse (xj - xi)) [: - xi, 1 :]) ys)\"\n\ndefinition lagrange_interpolation_poly :: \"('a :: field \\<times> 'a)list \\<Rightarrow> 'a poly\" where\n  \"lagrange_interpolation_poly xs_ys \\<equiv> let \n    xs = map fst xs_ys\n    in sum_list (map (\\<lambda> (xj,yj). smult yj (lagrange_basis_poly xs xj)) xs_ys)\"\n\n\n\nlemma degree_lagrange_basis_poly: \"degree (lagrange_basis_poly xs xj) \\<le> length (filter (\\<lambda> x. x \\<noteq> xj) xs)\"\n  unfolding lagrange_basis_poly_def Let_def\n  by (rule order.trans[OF degree_prod_list_le], rule order_trans[OF sum_list_mono[of _ _ \"\\<lambda> _. 1\"]], \n  auto simp: o_def, induct xs, auto)\n\nlemma degree_lagrange_interpolation_poly:  \n  shows \"degree (lagrange_interpolation_poly xs_ys) \\<le> length xs_ys - 1\"\nproof -\n  {\n    fix a b\n    assume ab: \"(a,b) \\<in> set xs_ys\" \n    let ?xs = \"filter (\\<lambda>x. x\\<noteq>a) (map fst xs_ys)\"\n    from ab have \"a \\<in> set (map fst xs_ys)\" by force\n    hence \"Suc (length ?xs) \\<le> length xs_ys\"\n      by (induct xs_ys, auto)\n    hence \"length ?xs \\<le> length xs_ys - 1\" by auto\n  } note main = this\n  show ?thesis\n    unfolding lagrange_interpolation_poly_def Let_def\n    by (rule degree_sum_list_le, auto, rule order_trans[OF degree_lagrange_basis_poly], insert main, auto)\nqed\n\nlemma lagrange_basis_poly_1: \n  \"poly (lagrange_basis_poly (map fst xs_ys) x) x = 1\"\n  unfolding lagrange_basis_poly_def Let_def poly_prod_list\n  by (rule prod_list_neutral, auto)\n  (metis field_class.field_inverse mult.commute right_diff_distrib right_minus_eq)\n\nlemma lagrange_basis_poly_0: assumes \"x' \\<in> set (map fst xs_ys)\" and \"x' \\<noteq> x\" \n  shows \"poly (lagrange_basis_poly (map fst xs_ys) x) x' = 0\"\nproof -\n  let ?f = \"\\<lambda>xi. smult (inverse (x - xi)) [:- xi, 1:]\"\n  let ?xs = \"filter (\\<lambda>c. c\\<noteq>x) (map fst xs_ys)\"\n  have mem: \"?f x' \\<in> set (map ?f ?xs)\" using assms by auto\n  show ?thesis\n    unfolding lagrange_basis_poly_def Let_def poly_prod_list prod_list_map_remove1[OF mem]\n    by simp\nqed\n\nlemma lagrange_interpolation_poly: assumes dist: \"distinct (map fst xs_ys)\"\n  and p: \"p = lagrange_interpolation_poly xs_ys\"\n  shows \"\\<And> x y. (x,y) \\<in> set xs_ys \\<Longrightarrow> poly p x = y\"\nproof -\n  let ?xs = \"map fst xs_ys\"\n  {\n    fix x y\n    assume xy: \"(x,y) \\<in> set xs_ys\"\n    show \"poly p x = y\" unfolding p lagrange_interpolation_poly_def Let_def poly_sum_list map_map o_def\n    proof (subst sum_list_map_remove1[OF xy], unfold split poly_smult lagrange_basis_poly_1,\n      subst sum_list_neutral)\n      fix v\n      assume \"v \\<in> set (map (\\<lambda>xa. poly (case xa of (xj, yj) \\<Rightarrow> smult yj (lagrange_basis_poly ?xs xj))\n                               x)\n                 (remove1 (x, y) xs_ys))\" (is \"_ \\<in> set (map ?f ?xy)\")\n      then obtain xy' where mem: \"xy' \\<in> set ?xy\" and v: \"v = ?f xy'\" by auto\n      obtain x' y' where xy': \"xy' = (x',y')\" by force\n      from v[unfolded this split] have v: \"v = poly (smult y' (lagrange_basis_poly ?xs x')) x\" .\n      have neq: \"x' \\<noteq> x\"\n      proof\n        assume \"x' = x\"\n        with mem[unfolded xy'] have mem: \"(x,y') \\<in> set (remove1 (x,y) xs_ys)\" by auto\n        hence mem': \"(x,y') \\<in> set xs_ys\" by (meson notin_set_remove1)\n        from dist[unfolded distinct_map] have inj: \"inj_on fst (set xs_ys)\" by auto\n        with mem' xy have y': \"y' = y\" unfolding inj_on_def by force\n        from dist have \"distinct xs_ys\" using distinct_map by blast\n        hence \"(x,y) \\<notin> set (remove1 (x,y) xs_ys)\" by simp\n        with mem[unfolded y']         \n        show False by auto\n      qed\n      have \"poly (lagrange_basis_poly ?xs x') x = 0\"\n        by (rule lagrange_basis_poly_0, insert xy mem[unfolded xy'] dist neq, force+) \n      thus \"v = 0\" unfolding v by simp\n    qed simp\n  } note sound = this\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Polynomial_Interpolation/Lagrange_Interpolation.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333484, "lm_q2_score": 0.8397339696776499, "lm_q1q2_score": 0.7538252266055374}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_BubSortSorts\nimports \"../../Test_Base\"\nbegin\n\ndatatype ('a, 'b) pair = pair2 \"'a\" \"'b\"\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\nfun ordered :: \"int list => bool\" where\n\"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((y <= y2) & (ordered (cons2 y2 xs)))\"\n\nfun bubble :: \"int list => (bool, (int list)) pair\" where\n\"bubble (nil2) = pair2 False (nil2)\"\n| \"bubble (cons2 y (nil2)) = pair2 False (cons2 y (nil2))\"\n| \"bubble (cons2 y (cons2 y2 xs)) =\n     (if y <= y2 then\n        (case bubble (cons2 y2 xs) of\n           pair2 b22 ys22 => pair2 b22 (cons2 y ys22))\n        else\n        (case bubble (cons2 y xs) of\n           pair2 b2 ys2 => pair2 True (cons2 y2 ys2)))\"\n\n(*fun did not finish the proof*)\nfunction bubsort :: \"int list => int list\" where\n\"bubsort x =\n   (case bubble x of pair2 b1 ys => (if b1 then bubsort ys else x))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"ordered (bubsort xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_BubSortSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.7536388002740556}}
{"text": "theory Majorities\nimports Main\nbegin\n\nsection {* Utility Lemmas About Majorities *}\n\ntext {*\n  Consensus algorithms usually ensure that a majority of processes\n  proposes the same value before taking a decision,\n  and we provide a few utility lemmas for reasoning about majorities.\n*}\n\ntext {*\n  Any two subsets @{text S} and @{text T} of a finite  set @{text E} such that\n  the sum of their cardinalities is larger than the size of @{text E} have a\n  non-empty intersection.\n*}\nlemma abs_majorities_intersect:\n    assumes crd: \"card E < card S + card T\"\n        and s: \"S \\<subseteq> E\" and t: \"T \\<subseteq> E\" and e: \"finite E\"\n    shows \"S \\<inter> T \\<noteq> {}\"\nproof (clarify)\n  assume contra: \"S \\<inter> T = {}\"\n  from s t e have \"finite S\" and \"finite T\" by (auto simp: finite_subset)\n  with crd contra have \"card E < card (S \\<union> T)\" by (auto simp add: card_Un_Int)\n  moreover\n  from s t e have \"card (S \\<union> T) \\<le> card E\" by (simp add: card_mono)\n  ultimately\n  show \"False\" by simp\nqed\n\nlemma abs_majoritiesE:\n  assumes crd: \"card E < card S + card T\"\n      and s: \"S \\<subseteq> E\" and t: \"T \\<subseteq> E\" and e: \"finite E\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nproof -\n  from assms have \"S \\<inter> T \\<noteq> {}\" by (rule abs_majorities_intersect)\n  then obtain p where \"p \\<in> S \\<inter> T\" by blast\n  with that show ?thesis by auto\nqed\n\ntext {* Special case: both sets @{text S} and @{text T} are majorities. *}\n\nlemma abs_majoritiesE':\n  assumes Smaj: \"card S > (card E) div 2\" and Tmaj: \"card T > (card E) div 2\"\n      and s: \"S \\<subseteq> E\" and t: \"T \\<subseteq> E\" and e: \"finite E\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nproof (rule abs_majoritiesE[OF _ s t e])\n  from Smaj Tmaj show \"card E < card S + card T\" by auto\nqed\n\ntext {*\n  We restate the above theorems for the case where the base type\n  is finite (taking @{text E} as the universal set).\n*}\n\nlemma majorities_intersect:\n  assumes crd: \"card (UNIV::('a::finite) set) < card (S::'a set) + card T\"\n  shows \"S \\<inter> T \\<noteq> {}\"\n  by (rule abs_majorities_intersect[OF crd]) auto\n\nlemma majoritiesE:\n  assumes crd: \"card (UNIV::('a::finite) set) < card (S::'a set) + card (T::'a set)\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nusing crd majorities_intersect by blast\n\nlemma majoritiesE':\n  assumes S: \"card (S::('a::finite) set) > (card (UNIV::'a set)) div 2\"\n  and T: \"card (T::'a set) > (card (UNIV::'a set)) div 2\"\n  obtains p where \"p \\<in> S\" and \"p \\<in> T\"\nby (rule abs_majoritiesE'[OF S T]) auto\n\nend (* theory Majorities *)\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Heard_Of/Majorities.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7535164172865936}}
{"text": "chapter \\<open>Addition, Sequences and their Concatenation\\<close>\n\ntheory OrdArith imports Rank\nbegin\n\nsection \\<open>Generalised Addition --- Also for Ordinals\\<close>\ntext \\<open>Source: Laurence Kirby, Addition and multiplication of sets\n      Math. Log. Quart. 53, No. 1, 52-65 (2007) / DOI 10.1002/malq.200610026\n      @{url \"http://faculty.baruch.cuny.edu/lkirby/mlqarticlejan2007.pdf\"}\\<close>\n\ndefinition\n  hadd      :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"           (infixl \"@+\" 65)  where\n    \"hadd x \\<equiv> hmemrec (\\<lambda>f z. x \\<squnion> RepFun z f)\"\n\nlemma hadd: \"x @+ y = x \\<squnion> RepFun y (\\<lambda>z. x @+ z)\"\n  by (metis def_hmemrec RepFun_ecut hadd_def order_refl)\n\nlemma hmem_hadd_E:\n  assumes l: \"l \\<^bold>\\<in> x @+ y\"\n  obtains \"l \\<^bold>\\<in> x\" | z where \"z \\<^bold>\\<in> y\" \"l = x @+ z\"\n  using l by (auto simp: hadd [of x y])\n\nlemma hadd_0_right [simp]: \"x @+ 0 = x\"\n  by (subst hadd) simp\n\nlemma hadd_hinsert_right: \"x @+ hinsert y z = hinsert (x @+ y) (x @+ z)\"\n  by (metis hadd hunion_hinsert_right RepFun_hinsert)\n\nlemma hadd_succ_right [simp]: \"x @+ succ y = succ (x @+ y)\"\n  by (metis hadd_hinsert_right succ_def)\n\nlemma not_add_less_right: \"\\<not> (x @+ y < x)\"\nproof (induction y)\n  case (2 y1 y2)\n  then show ?case\n    using hadd less_supI1 order_less_le by blast\nqed auto\n\nlemma not_add_mem_right: \"\\<not> (x @+ y \\<^bold>\\<in> x)\"\n  by (metis hadd hmem_not_refl hunion_iff)\n\nlemma hadd_0_left [simp]: \"0 @+ x = x\"\n  by (induct x) (auto simp: hadd_hinsert_right)\n\nlemma hadd_succ_left [simp]: \"Ord y \\<Longrightarrow> succ x @+ y = succ (x @+ y)\"\n  by (induct y rule: Ord_induct2) auto\n\nlemma hadd_assoc: \"(x @+ y) @+ z = x @+ (y @+ z)\"\n  by (induct z) (auto simp: hadd_hinsert_right)\n\nlemma RepFun_hadd_disjoint: \"x \\<sqinter> RepFun y ((@+) x) = 0\"\n  by (metis hf_equalityI RepFun_iff hinter_iff not_add_mem_right hmem_hempty)\n\n\nsubsection \\<open>Cancellation laws for addition\\<close>\n\nlemma Rep_le_Cancel: \"x \\<squnion> RepFun y ((@+) x) \\<le> x \\<squnion> RepFun z ((@+) x)\n                      \\<Longrightarrow> RepFun y ((@+) x) \\<le> RepFun z ((@+) x)\"\n  by (auto simp add: not_add_mem_right)\n\nlemma hadd_cancel_right [simp]: \"x @+ y = x @+ z \\<longleftrightarrow> y=z\"\nproof (induct y arbitrary: z rule: hmem_induct)\n  case (step y z) show ?case\n  proof auto\n    assume eq: \"x @+ y = x @+ z\"\n    hence  \"RepFun y ((@+) x) = RepFun z ((@+) x)\"\n      by (metis hadd Rep_le_Cancel order_antisym order_refl)\n    thus  \"y = z\"\n      by (metis hf_equalityI RepFun_iff step)\n  qed\nqed\n\nlemma RepFun_hadd_cancel: \"RepFun y (\\<lambda>z. x @+ z) = RepFun z (\\<lambda>z. x @+ z) \\<longleftrightarrow> y=z\"\n  by (metis hadd hadd_cancel_right)\n\nlemma hadd_hmem_cancel [simp]: \"x @+ y \\<^bold>\\<in> x @+ z \\<longleftrightarrow> y \\<^bold>\\<in> z\"\n  by (metis RepFun_iff hadd hadd_cancel_right hunion_iff not_add_mem_right)\n\nlemma ord_of_add: \"ord_of (i+j) = ord_of i @+ ord_of j\"\n  by (induct j) auto\n\nlemma Ord_hadd: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> Ord (x @+ y)\"\n  by (induct x rule: Ord_induct2) auto\n\nlemma hmem_self_hadd [simp]: \"k1 \\<^bold>\\<in> k1 @+ k2 \\<longleftrightarrow> 0 \\<^bold>\\<in> k2\"\n  by (metis hadd_0_right hadd_hmem_cancel)\n\nlemma hadd_commute: \"Ord x \\<Longrightarrow> Ord y \\<Longrightarrow> x @+ y = y @+ x\"\n  by (induct x rule: Ord_induct2) auto\n\nlemma hadd_cancel_left [simp]: \"Ord x \\<Longrightarrow> y @+ x = z @+ x \\<longleftrightarrow> y=z\"\n  by (induct x rule: Ord_induct2) auto\n\n\nsubsection \\<open>The predecessor function\\<close>\n\ndefinition pred :: \"hf \\<Rightarrow> hf\"\n  where \"pred x \\<equiv> (THE y. succ y = x \\<or> x=0 \\<and> y=0)\"\n\nlemma pred_succ [simp]: \"pred (succ x) = x\"\n  by (simp add: pred_def)\n\nlemma pred_0 [simp]: \"pred 0 = 0\"\n  by (simp add: pred_def)\n\nlemma succ_pred [simp]: \"Ord x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> succ (pred x) = x\"\n  by (metis Ord_cases pred_succ)\n\nlemma pred_mem [simp]: \"Ord x \\<Longrightarrow> x \\<noteq> 0 \\<Longrightarrow> pred x \\<^bold>\\<in> x\"\n  by (metis succ_iff succ_pred)\n\nlemma Ord_pred [simp]: \"Ord x \\<Longrightarrow> Ord (pred x)\"\n  by (metis Ord_in_Ord pred_0 pred_mem)\n\nlemma hadd_pred_right: \"Ord y \\<Longrightarrow> y \\<noteq> 0 \\<Longrightarrow> x @+ pred y = pred (x @+ y)\"\n  by (metis hadd_succ_right pred_succ succ_pred)\n\nlemma Ord_pred_HUnion: \"Ord(k) \\<Longrightarrow> pred k = \\<Squnion>k\"\n  by (metis HUnion_hempty Ordinal.Ord_pred pred_0 pred_succ)\n\n\nsection \\<open>A Concatentation Operation for Sequences\\<close>\n\ndefinition shift :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"shift f delta = \\<lbrace>v . u \\<^bold>\\<in> f, \\<exists>n y. u = \\<langle>n, y\\<rangle> \\<and> v = \\<langle>delta @+ n, y\\<rangle>\\<rbrace>\"\n\nlemma shiftD: \"x \\<^bold>\\<in> shift f delta \\<Longrightarrow> \\<exists>u. u \\<^bold>\\<in> f \\<and> x = \\<langle>delta @+ hfst u, hsnd u\\<rangle>\"\n  by (auto simp: shift_def hsplit_def)\n\nlemma hmem_shift_iff: \"\\<langle>m, y\\<rangle> \\<^bold>\\<in> shift f delta \\<longleftrightarrow> (\\<exists>n. m = delta @+ n \\<and> \\<langle>n, y\\<rangle> \\<^bold>\\<in> f)\"\n  by (auto simp: shift_def hrelation_def is_hpair_def)\n\nlemma hmem_shift_add_iff [simp]: \"\\<langle>delta @+ n, y\\<rangle> \\<^bold>\\<in> shift f delta \\<longleftrightarrow> \\<langle>n, y\\<rangle> \\<^bold>\\<in> f\"\n  by (metis hadd_cancel_right hmem_shift_iff)\n\nlemma hrelation_shift [simp]: \"hrelation (shift f delta)\"\n  by (auto simp: shift_def hrelation_def hsplit_def)\n\nlemma app_shift [simp]: \"app (shift f k) (k @+ j) = app f j\"\n  by (simp add: app_def)\n\nlemma hfunction_shift_iff [simp]: \"hfunction (shift f delta) = hfunction f\"\n  by (auto simp: hfunction_def hmem_shift_iff)\n\nlemma hdomain_shift_add: \"hdomain (shift f delta) = \\<lbrace>delta @+ n . n \\<^bold>\\<in> hdomain f\\<rbrace>\"\n  by  (rule hf_equalityI) (force simp add: hdomain_def hmem_shift_iff)\n\n\n\ndefinition seq_append :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf\"\n  where \"seq_append k f g \\<equiv> hrestrict f k \\<squnion> shift g k\"\n\nlemma hrelation_seq_append [simp]: \"hrelation (seq_append k f g)\"\n  by (simp add: seq_append_def)\n\nlemma Seq_append:\n  assumes \"Seq s1 k1\" \"Seq s2 k2\"\n  shows \"Seq (seq_append k1 s1 s2) (k1 @+ k2)\"\nproof -\n  have \"hfunction (hrestrict s1 k1 \\<squnion> shift s2 k1)\"\n    using assms\n    by (simp add: Ordinal.Seq_def hdomain_shift_disjoint hfunction_hunion hfunction_restr inf.absorb2)\n  moreover \n  have \"\\<And>x. \\<lbrakk>x \\<^bold>\\<in> k1 @+ k2; x \\<^bold>\\<notin> hdomain (shift s2 k1)\\<rbrakk> \\<Longrightarrow> x \\<^bold>\\<in> hdomain s1 \\<and> x \\<^bold>\\<in> k1\"\n    by (metis Ordinal.Seq_def RepFun_iff assms hdomain_shift_add hmem_hadd_E hsubsetCE)\n  ultimately show ?thesis\n    by (auto simp: Seq_def seq_append_def)\nqed\n\nlemma app_hunion1: \"x \\<^bold>\\<notin> hdomain g \\<Longrightarrow> app (f \\<squnion> g) x = app f x\"\n  by (auto simp: app_def) (metis hdomainI)\n\nlemma app_hunion2: \"x \\<^bold>\\<notin> hdomain f \\<Longrightarrow> app (f \\<squnion> g) x = app g x\"\n  by (auto simp: app_def) (metis hdomainI)\n\nlemma Seq_append_app1: \"Seq s k \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> app (seq_append k s s') l = app s l\"\n  by (metis app_hrestrict app_hunion1 hdomain_shift_disjoint hemptyE hinter_iff seq_append_def)\n\nlemma Seq_append_app2: \"Seq s1 k1 \\<Longrightarrow> Seq s2 k2 \\<Longrightarrow> l = k1 @+ j \\<Longrightarrow> app (seq_append k1 s1 s2) l = app s2 j\"\n  by (metis seq_append_def app_hunion2 app_shift hdomain_restr hinter_iff not_add_mem_right)\n\n\nsection \\<open>Nonempty sequences indexed by ordinals\\<close>\n\ndefinition OrdDom where\n \"OrdDom r \\<equiv> \\<forall>x y. \\<langle>x,y\\<rangle> \\<^bold>\\<in> r \\<longrightarrow> Ord x\"\n\nlemma OrdDom_insf: \"\\<lbrakk>OrdDom s; Ord k\\<rbrakk> \\<Longrightarrow> OrdDom (insf s (succ k) y)\"\n  by (auto simp: insf_def OrdDom_def)\n\nlemma OrdDom_hunion [simp]: \"OrdDom (s1 \\<squnion> s2) \\<longleftrightarrow> OrdDom s1 \\<and> OrdDom s2\"\n  by (auto simp: OrdDom_def)\n\nlemma OrdDom_hrestrict: \"OrdDom s \\<Longrightarrow> OrdDom (hrestrict s A)\"\n  by (auto simp: OrdDom_def)\n\nlemma OrdDom_shift: \"\\<lbrakk>OrdDom s; Ord k\\<rbrakk> \\<Longrightarrow> OrdDom (shift s k)\"\n  by (auto simp: OrdDom_def shift_def Ord_hadd)\n\n\ntext \\<open>A sequence of positive length ending with @{term y}\\<close>\ndefinition LstSeq :: \"hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"LstSeq s k y \\<equiv> Seq s (succ k) \\<and> Ord k \\<and> \\<langle>k,y\\<rangle> \\<^bold>\\<in> s \\<and> OrdDom s\"\n\n\n\nlemma LstSeq_imp_Seq_same: \"LstSeq s k y \\<Longrightarrow> Seq s k\"\n  by (metis LstSeq_imp_Seq_succ Seq_succ_D)\n\nlemma LstSeq_imp_Ord: \"LstSeq s k y \\<Longrightarrow> Ord k\"\n  by (metis LstSeq_def)\n\nlemma LstSeq_trunc: \"LstSeq s k y \\<Longrightarrow> l \\<^bold>\\<in> k \\<Longrightarrow> LstSeq s l (app s l)\"\n  by (meson LstSeq_def Ord_in_Ord Seq_Ord_D Seq_iff_app Seq_succ_iff)\n\nlemma LstSeq_insf: \"LstSeq s k z \\<Longrightarrow> LstSeq (insf s (succ k) y) (succ k) y\"\n  using LstSeq_def OrdDom_insf Seq_insf insf_def by force\n\nlemma app_insf_LstSeq: \"LstSeq s k z \\<Longrightarrow> app (insf s (succ k) y) (succ k) = y\"\n  by (metis LstSeq_imp_Seq_succ app_insf_Seq)\n\nlemma app_insf2_LstSeq: \"LstSeq s k z \\<Longrightarrow> k' \\<noteq> succ k \\<Longrightarrow> app (insf s (succ k) y) k' = app s k'\"\n  by (metis LstSeq_imp_Seq_succ app_insf2_Seq)\n\nlemma app_insf_LstSeq_if: \"LstSeq s k z \\<Longrightarrow> app (insf s (succ k) y) k' = (if k' = succ k then y else app s k')\"\n  by (metis app_insf2_LstSeq app_insf_LstSeq)\n\nlemma LstSeq_append_app1:\n  \"LstSeq s k y \\<Longrightarrow> l \\<^bold>\\<in> succ k \\<Longrightarrow> app (seq_append (succ k) s s') l = app s l\"\n  by (metis LstSeq_imp_Seq_succ Seq_append_app1)\n\nlemma LstSeq_append_app2:\n  \"\\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2; l = succ k1 @+ j\\<rbrakk>\n   \\<Longrightarrow> app (seq_append (succ k1) s1 s2) l = app s2 j\"\n   by (metis LstSeq_imp_Seq_succ Seq_append_app2)\n\nlemma Seq_append_pair:\n  \"\\<lbrakk>Seq s1 k1; Seq s2 (succ n);  \\<langle>n, y\\<rangle> \\<^bold>\\<in> s2; Ord n\\<rbrakk> \\<Longrightarrow> \\<langle>k1 @+ n, y\\<rangle> \\<^bold>\\<in> (seq_append k1 s1 s2)\"\n  by (metis hmem_shift_add_iff hunion_iff seq_append_def)\n\nlemma Seq_append_OrdDom: \"\\<lbrakk>Ord k; OrdDom s1; OrdDom s2\\<rbrakk> \\<Longrightarrow> OrdDom (seq_append k s1 s2)\"\n  by (auto simp: seq_append_def OrdDom_hrestrict OrdDom_shift)\n\nlemma LstSeq_append:\n  \"\\<lbrakk>LstSeq s1 k1 y1; LstSeq s2 k2 y2\\<rbrakk> \\<Longrightarrow> LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n  using LstSeq_def Ord_hadd Seq_append Seq_append_OrdDom Seq_append_pair by fastforce\n\nlemma LstSeq_app [simp]: \"LstSeq s k y \\<Longrightarrow> app s k = y\"\n  by (metis LstSeq_def Seq_imp_eq_app)\n\n\nsubsection \\<open>Sequence-building operators\\<close>\n\ndefinition Builds :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"Builds B C s l \\<equiv> B (app s l) \\<or> (\\<exists>m \\<^bold>\\<in> l. \\<exists>n \\<^bold>\\<in> l. C (app s l) (app s m) (app s n))\"\n\ndefinition BuildSeq :: \"(hf \\<Rightarrow> bool) \\<Rightarrow> (hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool) \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> hf \\<Rightarrow> bool\"\n  where \"BuildSeq B C s k y \\<equiv> LstSeq s k y \\<and> (\\<forall>l \\<^bold>\\<in> succ k. Builds B C s l)\"\n\nlemma BuildSeqI: \"LstSeq s k y \\<Longrightarrow> (\\<And>l. l \\<^bold>\\<in> succ k \\<Longrightarrow> Builds B C s l) \\<Longrightarrow> BuildSeq B C s k y\"\n  by (simp add: BuildSeq_def)\n\nlemma BuildSeq_imp_LstSeq: \"BuildSeq B C s k y \\<Longrightarrow> LstSeq s k y\"\n  by (metis BuildSeq_def)\n\nlemma BuildSeq_imp_Seq: \"BuildSeq B C s k y \\<Longrightarrow> Seq s (succ k)\"\n  by (metis LstSeq_imp_Seq_succ BuildSeq_imp_LstSeq)\n\nlemma BuildSeq_conj_distrib:\n \"BuildSeq (\\<lambda>x. B x \\<and> P x) (\\<lambda>x y z. C x y z \\<and> P x) s k y \\<longleftrightarrow>\n  BuildSeq B C s k y \\<and> (\\<forall>l \\<^bold>\\<in> succ k. P (app s l))\"\n  by (auto simp: BuildSeq_def Builds_def)\n\nlemma BuildSeq_mono:\n  assumes y: \"BuildSeq B C s k y\"\n      and B: \"\\<And>x. B x \\<Longrightarrow> B' x\" and C: \"\\<And>x y z. C x y z \\<Longrightarrow> C' x y z\"\n  shows \"BuildSeq B' C' s k y\"\nusing y\n  by (auto simp: BuildSeq_def Builds_def intro!: B C)\n\nlemma BuildSeq_trunc:\n  assumes b: \"BuildSeq B C s k y\"\n      and l: \"l \\<^bold>\\<in> k\"\n  shows \"BuildSeq B C s l (app s l)\"\n  by (smt (verit) BuildSeqI BuildSeq_def LstSeq_def LstSeq_trunc Ord_trans b hballE l succ_iff)\n\n\nsubsection \\<open>Showing that Sequences can be Constructed\\<close>\n\nlemma Builds_insf: \"Builds B C s l \\<Longrightarrow> LstSeq s k z \\<Longrightarrow> l \\<^bold>\\<in> succ k \\<Longrightarrow> Builds B C (insf s (succ k) y) l\"\nby (auto simp: HBall_def hmem_not_refl Builds_def app_insf_LstSeq_if simp del: succ_iff)\n   (metis hmem_not_sym)\n\nlemma BuildSeq_insf:\n  assumes b: \"BuildSeq B C s k z\"\n      and m: \"m \\<^bold>\\<in> succ k\"\n      and n: \"n \\<^bold>\\<in> succ k\"\n      and y: \"B y \\<or> C y (app s m) (app s n)\"\nshows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\nproof (rule BuildSeqI)\n  show \"LstSeq (insf s (succ k) y) (succ k) y\"\n  by (metis BuildSeq_imp_LstSeq LstSeq_insf b)\nnext\n  fix l\n  assume l: \"l \\<^bold>\\<in> succ (succ k)\"\n  thus \"Builds B C (insf s (succ k) y) l\"\n  proof\n    assume l: \"l = succ k\"\n    have \"B (app (insf s l y) l) \\<or> C (app (insf s l y) l) (app (insf s l y) m) (app (insf s l y) n)\"\n      by (metis BuildSeq_imp_Seq app_insf_Seq_if b hmem_not_refl l m n y)\n    thus \"Builds B C (insf s (succ k) y) l\" using m n\n      by (auto simp: Builds_def l)\n  next\n    assume l: \"l \\<^bold>\\<in> succ k\"\n    thus \"Builds B C (insf s (succ k) y) l\" using b l\n      by (metis hballE Builds_insf BuildSeq_def)\n  qed\nqed\n\nlemma BuildSeq_insf1:\n  assumes b: \"BuildSeq B C s k z\"\n      and y: \"B y\"\n  shows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\nby (metis BuildSeq_insf b succ_iff y)\n\nlemma BuildSeq_insf2:\n  assumes b: \"BuildSeq B C s k z\"\n      and m: \"m \\<^bold>\\<in> k\"\n      and n: \"n \\<^bold>\\<in> k\"\n      and y: \"C y (app s m) (app s n)\"\n  shows \"BuildSeq B C (insf s (succ k) y) (succ k) y\"\n  by (metis BuildSeq_insf b m n succ_iff y)\n\nlemma BuildSeq_append:\n  assumes s1: \"BuildSeq B C s1 k1 y1\" and s2: \"BuildSeq B C s2 k2 y2\"\n  shows \"BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\nproof (rule BuildSeqI)\n  show \"LstSeq (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n    using assms\n    by (metis BuildSeq_imp_LstSeq LstSeq_append)\nnext\n  fix l\n  have s1L: \"LstSeq s1 k1 y1\"\n   and s1BC: \"\\<And>l. l \\<^bold>\\<in> succ k1 \\<Longrightarrow> Builds B C s1 l\"\n   and s2L: \"LstSeq s2 k2 y2\"\n   and s2BC: \"\\<And>l. l \\<^bold>\\<in> succ k2 \\<Longrightarrow> Builds B C s2 l\"\n    using s1 s2 by (auto simp: BuildSeq_def)\n  assume l: \"l \\<^bold>\\<in> succ (succ (k1 @+ k2))\"\n  hence  \"l \\<^bold>\\<in> succ k1 @+ succ k2\"\n    by (metis LstSeq_imp_Ord hadd_succ_left hadd_succ_right s2L)\n  thus \"Builds B C (seq_append (succ k1) s1 s2) l\"\n  proof (rule hmem_hadd_E)\n    assume l1: \"l \\<^bold>\\<in> succ k1\"\n    hence \"B (app s1 l) \\<or> (\\<exists>m\\<^bold>\\<in>l. \\<exists>n\\<^bold>\\<in>l. C (app s1 l) (app s1 m) (app s1 n))\" using s1BC\n      by (simp add: Builds_def)\n    thus ?thesis\n    proof\n      assume \"B (app s1 l)\"\n      thus ?thesis\n        by (metis Builds_def LstSeq_append_app1 l1 s1L)\n    next\n      assume \"\\<exists>m\\<^bold>\\<in>l. \\<exists>n\\<^bold>\\<in>l. C (app s1 l) (app s1 m) (app s1 n)\"\n      then obtain m n where mn: \"m \\<^bold>\\<in> l\" \"n \\<^bold>\\<in> l\" and C: \"C (app s1 l) (app s1 m) (app s1 n)\"\n        by blast\n      moreover have \"m \\<^bold>\\<in> succ k1\" \"n \\<^bold>\\<in> succ k1\"\n        by (metis LstSeq_def Ord_trans l1 mn s1L succ_iff)+\n      ultimately have \"C (app (seq_append (succ k1) s1 s2) l)\n                         (app (seq_append (succ k1) s1 s2) m)\n                         (app (seq_append (succ k1) s1 s2) n)\"\n        using s1L l1\n        by (simp add: LstSeq_append_app1)\n      thus \"Builds B C (seq_append (succ k1) s1 s2) l\" using mn\n        by (auto simp: Builds_def)\n    qed\n  next\n    fix z\n    assume z: \"z \\<^bold>\\<in> succ k2\" and l2: \"l = succ k1 @+ z\"\n    hence \"B (app s2 z) \\<or> (\\<exists>m\\<^bold>\\<in>z. \\<exists>n\\<^bold>\\<in>z. C (app s2 z) (app s2 m) (app s2 n))\" using s2BC\n      by (simp add: Builds_def)\n    thus ?thesis\n    proof\n      assume \"B (app s2 z)\"\n      thus ?thesis\n        by (metis Builds_def LstSeq_append_app2 l2 s1L s2L)\n    next\n      assume \"\\<exists>m\\<^bold>\\<in>z. \\<exists>n\\<^bold>\\<in>z. C (app s2 z) (app s2 m) (app s2 n)\"\n      then obtain m n where mn: \"m \\<^bold>\\<in> z\" \"n \\<^bold>\\<in> z\" and C: \"C (app s2 z) (app s2 m) (app s2 n)\"\n        by blast\n      also have \"m \\<^bold>\\<in> succ k2\" \"n \\<^bold>\\<in> succ k2\" using mn\n        by (metis LstSeq_def Ord_trans z s2L succ_iff)+\n      ultimately have \"C (app (seq_append (succ k1) s1 s2) l)\n                         (app (seq_append (succ k1) s1 s2) (succ k1 @+ m))\n                         (app (seq_append (succ k1) s1 s2) (succ k1 @+ n))\"\n        using s1L s2L l2 z\n        by (simp add: LstSeq_append_app2)\n      thus \"Builds B C (seq_append (succ k1) s1 s2) l\" using mn l2\n        by (auto simp: Builds_def HBall_def)\n    qed\n  qed\nqed\n\nlemma BuildSeq_combine:\n  assumes b1: \"BuildSeq B C s1 k1 y1\" and b2: \"BuildSeq B C s2 k2 y2\"\n      and y: \"C y y1 y2\"\n  shows \"BuildSeq B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) y) (succ (succ (k1 @+ k2))) y\"\nproof -\n  have k2: \"Ord k2\"  using b2\n    by (auto simp: BuildSeq_def LstSeq_def)\n  show ?thesis\n  proof (rule BuildSeq_insf [where m=k1 and n=\"succ(k1@+k2)\"])\n    show \"BuildSeq B C (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) y2\"\n      by (rule BuildSeq_append [OF b1 b2])\n  next\n    show \"k1 \\<^bold>\\<in> succ (succ (k1 @+ k2))\" using k2\n      by (metis hadd_0_right hmem_0_Ord hmem_self_hadd succ_iff)\n  next\n    show \"succ (k1 @+ k2) \\<^bold>\\<in> succ (succ (k1 @+ k2))\"\n      by (metis succ_iff)\n  next\n    have [simp]: \"app (seq_append (succ k1) s1 s2) k1 = y1\"\n      by (metis b1 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app1 succ_iff)\n    have [simp]: \"app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)) = y2\"\n      by (metis b1 b2 k2 BuildSeq_imp_LstSeq LstSeq_app LstSeq_append_app2 hadd_succ_left)\n    show \"B y \\<or>\n          C y (app (seq_append (succ k1) s1 s2) k1)\n              (app (seq_append (succ k1) s1 s2) (succ (k1 @+ k2)))\"\n      using y by simp\n  qed\nqed\n\nlemma LstSeq_1: \"LstSeq \\<lbrace>\\<langle>0, y\\<rangle>\\<rbrace> 0 y\"\n by (auto simp: LstSeq_def One_hf_eq_succ Seq_ins OrdDom_def)\n\nlemma BuildSeq_1: \"B y \\<Longrightarrow> BuildSeq B C \\<lbrace>\\<langle>0, y\\<rangle>\\<rbrace> 0 y\"\n  by (auto simp: BuildSeq_def Builds_def LstSeq_1)\n\nlemma BuildSeq_exI: \"B t \\<Longrightarrow> \\<exists>s k. BuildSeq B C s k t\"\n  by (metis BuildSeq_1)\n\n\nsubsection \\<open>Proving Properties of Given Sequences\\<close>\n\n\n\nlemma BuildSeq_induct [consumes 1, case_names B C]:\n  assumes major: \"BuildSeq B C s k a\"\n      and B: \"\\<And>x. B x \\<Longrightarrow> P x\"\n      and C: \"\\<And>x y z. C x y z \\<Longrightarrow> P y \\<Longrightarrow> P z \\<Longrightarrow> P x\"\n  shows \"P a\"\nproof -\n  have \"Ord k\" using assms\n    by (auto simp: BuildSeq_def LstSeq_def)\n  hence \"\\<And>a s. BuildSeq B C s k a \\<Longrightarrow> P a\"\n    by (induction k rule: Ord_induct) (metis BuildSeq_trunc BuildSeq_succ_E B C)\n  thus ?thesis\n    by (metis major)\nqed\n\ndefinition BuildSeq2 :: \"[[hf,hf] \\<Rightarrow> bool, [hf,hf,hf,hf,hf,hf] \\<Rightarrow> bool, hf, hf, hf, hf] \\<Rightarrow> bool\"\n  where \"BuildSeq2 B C s k y y' \\<equiv>\n         BuildSeq (\\<lambda>p. \\<exists>x x'. p = \\<langle>x,x'\\<rangle> \\<and> B x x')\n                  (\\<lambda>p q r. \\<exists>x x' y y' z z'. p = \\<langle>x,x'\\<rangle> \\<and> q = \\<langle>y,y'\\<rangle> \\<and> r = \\<langle>z,z'\\<rangle> \\<and> C x x' y y' z z')\n                  s k \\<langle>y,y'\\<rangle>\"\n\nlemma BuildSeq2_combine:\n  assumes b1: \"BuildSeq2 B C s1 k1 y1 y1'\" and b2: \"BuildSeq2 B C s2 k2 y2 y2'\"\n      and y: \"C y y' y1 y1' y2 y2'\"\n  shows \"BuildSeq2 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \\<langle>y, y'\\<rangle>)\n                       (succ (succ (k1 @+ k2))) y y'\"\n  using BuildSeq2_def BuildSeq_combine b1 b2 y by force\n\nlemma BuildSeq2_1: \"B y y' \\<Longrightarrow> BuildSeq2 B C \\<lbrace>\\<langle>0, y, y'\\<rangle>\\<rbrace> 0 y y'\"\n  by (auto simp: BuildSeq2_def BuildSeq_1)\n\n\n\nlemma BuildSeq2_induct [consumes 1, case_names B C]:\n  assumes \"BuildSeq2 B C s k a a'\"\n    and B: \"\\<And>x x'. B x x' \\<Longrightarrow> P x x'\"\n    and C: \"\\<And>x x' y y' z z'. C x x' y y' z z' \\<Longrightarrow> P y y' \\<Longrightarrow> P z z' \\<Longrightarrow> P x x'\"\n  shows \"P a a'\"\n  using assms BuildSeq_induct [where P = \"\\<lambda>\\<langle>x,x'\\<rangle>. P x x'\"]\n  by (smt (verit, del_insts) BuildSeq2_def hsplit)\n\ndefinition BuildSeq3\n   :: \"[[hf,hf,hf] \\<Rightarrow> bool, [hf,hf,hf,hf,hf,hf,hf,hf,hf] \\<Rightarrow> bool, hf, hf, hf, hf, hf] \\<Rightarrow> bool\"\n  where \"BuildSeq3 B C s k y y' y'' \\<equiv>\n         BuildSeq (\\<lambda>p. \\<exists>x x' x''. p = \\<langle>x,x',x''\\<rangle> \\<and> B x x' x'')\n                  (\\<lambda>p q r. \\<exists>x x' x'' y y' y'' z z' z''.\n                           p = \\<langle>x,x',x''\\<rangle> \\<and> q = \\<langle>y,y',y''\\<rangle> \\<and> r = \\<langle>z,z',z''\\<rangle> \\<and>\n                           C x x' x'' y y' y'' z z' z'')\n                  s k \\<langle>y,y',y''\\<rangle>\"\n\nlemma BuildSeq3_combine:\n  assumes b1: \"BuildSeq3 B C s1 k1 y1 y1' y1''\" and b2: \"BuildSeq3 B C s2 k2 y2 y2' y2''\"\n      and y: \"C y y' y'' y1 y1' y1'' y2 y2' y2''\"\n  shows \"BuildSeq3 B C (insf (seq_append (succ k1) s1 s2) (succ (succ (k1 @+ k2))) \\<langle>y, y', y''\\<rangle>)\n                       (succ (succ (k1 @+ k2))) y y' y''\"\n  using assms\n  unfolding BuildSeq3_def by (blast intro: BuildSeq_combine)\n\nlemma BuildSeq3_1: \"B y y' y'' \\<Longrightarrow> BuildSeq3 B C \\<lbrace>\\<langle>0, y, y', y''\\<rangle>\\<rbrace> 0 y y' y''\"\n  by (auto simp: BuildSeq3_def BuildSeq_1)\n\nlemma BuildSeq3_exI: \"B t t' t'' \\<Longrightarrow> \\<exists>s k. BuildSeq3 B C s k t t' t''\"\n  by (metis BuildSeq3_1)\n\nlemma BuildSeq3_induct [consumes 1, case_names B C]:\n  assumes \"BuildSeq3 B C s k a a' a''\"\n    and B: \"\\<And>x x' x''. B x x' x'' \\<Longrightarrow> P x x' x''\"\n    and C: \"\\<And>x x' x'' y y' y'' z z' z''. C x x' x'' y y' y'' z z' z'' \\<Longrightarrow> P y y' y'' \\<Longrightarrow> P z z' z'' \\<Longrightarrow> P x x' x''\"\n  shows \"P a a' a''\"\n  using assms BuildSeq_induct [where P = \"\\<lambda>\\<langle>x,x',x''\\<rangle>. P x x' x''\"]\n  by (smt (verit, del_insts) BuildSeq3_def hsplit)\n\n\nsection \\<open>A Unique Predecessor for every non-empty set\\<close>\n\nlemma Rep_hf_0 [simp]: \"Rep_hf 0 = 0\"\n  by (metis Abs_hf_inverse HF.HF_def UNIV_I Zero_hf_def image_empty set_encode_empty)\n\nlemma hmem_imp_less: \"x \\<^bold>\\<in> y \\<Longrightarrow> Rep_hf x < Rep_hf y\"\n  unfolding hmem_def hfset_def image_iff \n  apply (clarsimp simp: hmem_def hfset_def set_decode_def Abs_hf_inverse)\n  apply (metis div_less even_zero le_less_trans less_exp not_less)\n  done\n\nlemma hsubset_imp_le: \n  assumes \"x \\<le> y\" shows \"Rep_hf x \\<le> Rep_hf y\"\nproof -\n  have \"\\<And>u v. \\<lbrakk>\\<forall>x. x \\<in> Abs_hf ` set_decode (Rep_hf (Abs_hf u)) \\<longrightarrow>\n                   x \\<in> Abs_hf ` set_decode (Rep_hf (Abs_hf v))\\<rbrakk>\n              \\<Longrightarrow> u \\<le> v\"\n    by (metis Abs_hf_inverse UNIV_I imageE image_eqI subsetI subset_decode_imp_le)\n  then show ?thesis\n    by (metis Rep_hf_inverse assms hfset_def hmem_def hsubsetCE)\nqed\n\nlemma diff_hmem_imp_less: assumes \"x \\<^bold>\\<in> y\" shows \"Rep_hf (y - \\<lbrace>x\\<rbrace>) < Rep_hf y\"\nproof -\n  have  \"Rep_hf (y - \\<lbrace>x\\<rbrace>) \\<le> Rep_hf y\"\n    by (metis hdiff_iff hsubsetI hsubset_imp_le)\n  moreover\n  have \"Rep_hf (y - \\<lbrace>x\\<rbrace>) \\<noteq> Rep_hf y\" using assms\n    by (metis Rep_hf_inject hdiff_iff hinsert_iff)\n  ultimately show ?thesis\n    by (metis le_neq_implies_less)\nqed\n\ndefinition least :: \"hf \\<Rightarrow> hf\"\n  where \"least a \\<equiv> (THE x. x \\<^bold>\\<in> a \\<and> (\\<forall>y. y \\<^bold>\\<in> a \\<longrightarrow> Rep_hf x \\<le> Rep_hf y))\"\n\nlemma least_equality:\n  assumes \"x \\<^bold>\\<in> a\" and \"\\<And>y. y \\<^bold>\\<in> a \\<Longrightarrow> Rep_hf x \\<le> Rep_hf y\"\n  shows \"least a = x\"\n  unfolding least_def\n  using Rep_hf_inject assms order_antisym_conv by blast\n\n\n\nlemma nonempty_imp_ex_least: \"a \\<noteq> 0 \\<Longrightarrow> \\<exists>x. x \\<^bold>\\<in> a \\<and> (\\<forall>y. y \\<^bold>\\<in> a \\<longrightarrow> Rep_hf x \\<le> Rep_hf y)\"\nproof (induction a rule: hf_induct)\n  case 0 thus ?case by simp\nnext\n  case (hinsert u v)\n  show ?case\n    proof (cases \"v=0\")\n     case True thus ?thesis\n       by (rule_tac x=u in exI, simp)\n    next\n      case False\n      thus ?thesis\n        by (metis order.trans hinsert.IH(2) hmem_hinsert linorder_le_cases)\n    qed\nqed\n\nlemma least_hmem: \"a \\<noteq> 0 \\<Longrightarrow> least a \\<^bold>\\<in> a\"\n  by (metis least_equality nonempty_imp_ex_least)\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/HereditarilyFinite/OrdArith.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.8539127566694177, "lm_q1q2_score": 0.7535164172865936}}
{"text": "(* Property from Case-Analysis for Rippling and Inductive Proof, \n   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. \n   This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n   Some proofs were added by Yutaka Nagashima.*)\ntheory TIP_prop_41\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun take :: \"Nat => 'a list => 'a list\" where\n  \"take (Z) y = nil2\"\n| \"take (S z) (nil2) = nil2\"\n| \"take (S z) (cons2 x2 x3) = cons2 x2 (take z x3)\"\n\nfun map :: \"('a => 'b) => 'a list => 'b list\" where\n  \"map x (nil2) = nil2\"\n| \"map x (cons2 z xs) = cons2 (x z) (map x xs)\"\n\ntheorem property0 :(*Probably the best proof*)\n  \"((take n (map f xs)) = (map f (take n xs)))\"\n  find_proof DInd\n    (*specifying \"xs\" is necessary.*)\n  apply (induct xs rule: TIP_prop_41.take.induct)\n    (*Why \"rule:take.induct\" instead of \"rule:map.induct\"?*)\n    (*Because \"take\"'s pattern-matching is complete on the first parameter and \n    both first arguments (\"n\" and \"n\") are variables here, while\n    \"map\"'s pattern-matching is complete on the second parameter and \n    \"map\"'s second arguments are \"xs\" and \"take n xs\" in this case (?)*)\n    apply auto\n  done \n\ntheorem property0' :\n  \"((take n (map f xs)) = (map f (take n xs)))\"\n  apply (induct n xs rule: TIP_prop_41.take.induct)(*equivalent to \"(induct xs rule: TIP_prop_41.take.induct)\"*)\n    apply auto\n  done\n\ntheorem property0'' :(*sub-optimal proof*)\n  \"((take n (map f xs)) = (map f (take n xs)))\"\n  apply (induct n arbitrary: xs) (*This \"arbitrary: xs\" is necessary.*)\n   apply fastforce\n  apply(induct_tac xs)\n   apply auto\n  done\n\ntheorem property0''' :(*sub-optimal proof*)\n  \"((take n (map f xs)) = (map f (take n xs)))\"\n  (*Why does \"induct n arbitrary:xs\" lead to a shorter proof.\n    Because \"induct xs arbitrary:n\" cannot process the right-hand side (\"map f (take n xs)\") \n    very well. *)\n  apply (induct xs arbitrary: n) (*This \"arbitrary: xs\" is necessary.*)\n   apply(induct_tac n)\n    apply fastforce+\n  apply(induct_tac n)\n   apply auto\n  done\n\ntheorem property0''' :\n  \"((take n (map f xs)) = (map f (take n xs)))\"\n  apply (induct rule: TIP_prop_41.take.induct)\n  nitpick\n  oops\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/Isaplanner/Isaplanner/TIP_prop_41.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267796346599, "lm_q2_score": 0.8670357477770336, "lm_q1q2_score": 0.7533038765692494}}
{"text": "section \\<open>Tries via Functions\\<close>\n\ntheory Trie_Fun\nimports\n  Set_Specs\nbegin\n\ntext \\<open>A trie where each node maps a key to sub-tries via a function.\nNice abstract model. Not efficient because of the function space.\\<close>\n\ndatatype 'a trie = Nd bool \"'a \\<Rightarrow> 'a trie option\"\n\ndefinition empty :: \"'a trie\" where\n[simp]: \"empty = Nd False (\\<lambda>_. None)\"\n\nfun isin :: \"'a trie \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n\"isin (Nd b m) [] = b\" |\n\"isin (Nd b m) (k # xs) = (case m k of None \\<Rightarrow> False | Some t \\<Rightarrow> isin t xs)\"\n\nfun insert :: \"('a::linorder) list \\<Rightarrow> 'a trie \\<Rightarrow> 'a trie\" where\n\"insert [] (Nd b m) = Nd True m\" |\n\"insert (x#xs) (Nd b m) =\n   Nd b (m(x := Some(insert xs (case m x of None \\<Rightarrow> empty | Some t \\<Rightarrow> t))))\"\n\nfun delete :: \"('a::linorder) list \\<Rightarrow> 'a trie \\<Rightarrow> 'a trie\" where\n\"delete [] (Nd b m) = Nd False m\" |\n\"delete (x#xs) (Nd b m) = Nd b\n   (case m x of\n      None \\<Rightarrow> m |\n      Some t \\<Rightarrow> m(x := Some(delete xs t)))\"\n\ntext \\<open>The actual definition of \\<open>set\\<close> is a bit cryptic but canonical, to enable\nprimrec to prove termination:\\<close>\n\nprimrec set :: \"'a trie \\<Rightarrow> 'a list set\" where\n\"set (Nd b m) = (if b then {[]} else {}) \\<union>\n    (\\<Union>a. case (map_option set o m) a of None \\<Rightarrow> {} | Some t \\<Rightarrow> (#) a ` t)\"\n\ntext \\<open>This is the more human-readable version:\\<close>\n\nlemma set_Nd:\n  \"set (Nd b m) =\n     (if b then {[]} else {}) \\<union>\n     (\\<Union>a. case m a of None \\<Rightarrow> {} | Some t \\<Rightarrow> (#) a ` set t)\"\nby (auto simp: split: option.splits)\n\nlemma isin_set: \"isin t xs = (xs \\<in> set t)\"\napply(induction t xs rule: isin.induct)\napply (auto split: option.split)\ndone\n\nlemma set_insert: \"set (insert xs t) = set t \\<union> {xs}\"\nproof(induction xs t rule: insert.induct)\n  case 1 thus ?case by simp\nnext\n  case 2\n  thus ?case\n    apply(simp)\n    apply(subst set_eq_iff)\n    apply(auto split!: if_splits option.splits)\n     apply fastforce\n    by (metis imageI option.sel)\nqed\n\nlemma set_delete: \"set (delete xs t) = set t - {xs}\"\nproof(induction xs t rule: delete.induct)\n  case 1 thus ?case by (force split: option.splits)\nnext\n  case 2\n  thus ?case\n    apply (auto simp add: image_iff split!: if_splits option.splits)\n       apply blast\n      apply (metis insertE insertI2 insert_Diff_single option.inject)\n     apply blast\n    by (metis insertE insertI2 insert_Diff_single option.inject)\nqed\n\ninterpretation S: Set\nwhere empty = empty and isin = isin and insert = insert and delete = delete\nand set = set and invar = \"\\<lambda>_. True\"\nproof (standard, goal_cases)\n  case 1 show ?case by (simp)\nnext\n  case 2 thus ?case by(simp add: isin_set)\nnext\n  case 3 thus ?case by(simp add: set_insert)\nnext\n  case 4 thus ?case by(simp add: set_delete)\nqed (rule TrueI)+\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Data_Structures/Trie_Fun.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765304654121, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7532915143629756}}
{"text": "(* Title:      Boolean Semirings\n   Author:     Walter Guttmann\n   Maintainer: Walter Guttmann <walter.guttmann at canterbury.ac.nz>\n*)\n\nsection \\<open>Boolean Semirings\\<close>\n\ntheory Boolean_Semirings\n\nimports Stone_Algebras.P_Algebras Lattice_Ordered_Semirings\n\nbegin\n\nclass complemented_distributive_lattice = bounded_distrib_lattice + uminus +\n  assumes inf_complement: \"x \\<sqinter> (-x) = bot\"\n  assumes sup_complement: \"x \\<squnion> (-x) = top\"\nbegin\n\nsublocale boolean_algebra where minus = \"\\<lambda>x y . x \\<sqinter> (-y)\" and inf = inf and sup = sup and bot = bot and top = top\n  apply unfold_locales\n  apply (simp add: inf_complement)\n  apply (simp add: sup_complement)\n  by simp\n\nend\n\ntext \\<open>M0-algebra\\<close>\n\ncontext lattice_ordered_pre_left_semiring\nbegin\n\ntext \\<open>Section 7\\<close>\n\nlemma vector_1:\n  \"vector x \\<longleftrightarrow> x * top \\<le> x\"\n  by (simp add: antisym_conv top_right_mult_increasing)\n\ndefinition zero_vector :: \"'a \\<Rightarrow> bool\" where \"zero_vector x \\<equiv> x \\<le> x * bot\"\ndefinition one_vector :: \"'a \\<Rightarrow> bool\" where \"one_vector x \\<equiv> x * bot \\<le> x\"\n\nlemma zero_vector_left_zero:\n  assumes \"zero_vector x\"\n    shows \"x * y = x * bot\"\nproof -\n  have \"x * y \\<le> x * bot\"\n    by (metis assms mult_isotone top.extremum vector_mult_closed zero_vector zero_vector_def)\n  thus ?thesis\n    by (simp add: order.antisym mult_right_isotone)\nqed\n\nlemma zero_vector_1:\n  \"zero_vector x \\<longleftrightarrow> (\\<forall>y . x * y = x * bot)\"\n  by (metis top_right_mult_increasing zero_vector_def zero_vector_left_zero)\n\nlemma zero_vector_2:\n  \"zero_vector x \\<longleftrightarrow> (\\<forall>y . x * y \\<le> x * bot)\"\n  by (metis eq_refl order_trans top_right_mult_increasing zero_vector_def zero_vector_left_zero)\n\nlemma zero_vector_3:\n  \"zero_vector x \\<longleftrightarrow> x * 1 = x * bot\"\n  by (metis mult_sub_right_one zero_vector_def zero_vector_left_zero)\n\nlemma zero_vector_4:\n  \"zero_vector x \\<longleftrightarrow> x * 1 \\<le> x * bot\"\n  using order.antisym mult_right_isotone zero_vector_3 by auto\n\nlemma zero_vector_5:\n  \"zero_vector x \\<longleftrightarrow> x * top = x * bot\"\n  by (metis top_right_mult_increasing zero_vector_def zero_vector_left_zero)\n\nlemma zero_vector_6:\n  \"zero_vector x \\<longleftrightarrow> x * top \\<le> x * bot\"\n  by (meson mult_right_isotone order_trans top.extremum zero_vector_2)\n\nlemma zero_vector_7:\n  \"zero_vector x \\<longleftrightarrow> (\\<forall>y . x * top = x * y)\"\n  by (metis zero_vector_1)\n\nlemma zero_vector_8:\n  \"zero_vector x \\<longleftrightarrow> (\\<forall>y . x * top \\<le> x * y)\"\n  by (metis zero_vector_6 zero_vector_left_zero)\n\nlemma zero_vector_9:\n  \"zero_vector x \\<longleftrightarrow> (\\<forall>y . x * 1 = x * y)\"\n  by (metis zero_vector_1)\n\nlemma zero_vector_0:\n  \"zero_vector x \\<longleftrightarrow> (\\<forall>y z . x * y = x * z)\"\n  by (metis zero_vector_5 zero_vector_left_zero)\n\ntext \\<open>Theorem 6 / Figure 2: relations between properties\\<close>\n\nlemma co_vector_zero_vector_one_vector:\n  \"co_vector x \\<longleftrightarrow> zero_vector x \\<and> one_vector x\"\n  using co_vector_def one_vector_def zero_vector_def by auto\n\nlemma up_closed_one_vector:\n  \"up_closed x \\<Longrightarrow> one_vector x\"\n  by (metis bot_least mult_right_isotone up_closed_def one_vector_def)\n\nlemma zero_vector_dense:\n  \"zero_vector x \\<Longrightarrow> dense_rel x\"\n  by (metis zero_vector_0 zero_vector_def)\n\nlemma zero_vector_sup_distributive:\n  \"zero_vector x \\<Longrightarrow> sup_distributive x\"\n  by (metis sup_distributive_def sup_idem zero_vector_0)\n\nlemma zero_vector_inf_distributive:\n  \"zero_vector x \\<Longrightarrow> inf_distributive x\"\n  by (metis inf_idem inf_distributive_def zero_vector_0)\n\nlemma up_closed_zero_vector_vector:\n  \"up_closed x \\<Longrightarrow> zero_vector x \\<Longrightarrow> vector x\"\n  by (metis up_closed_def zero_vector_0)\n\nlemma zero_vector_one_vector_vector:\n  \"zero_vector x \\<Longrightarrow> one_vector x \\<Longrightarrow> vector x\"\n  by (metis one_vector_def vector_1 zero_vector_0)\n\nlemma co_vector_vector:\n  \"co_vector x \\<Longrightarrow> vector x\"\n  by (simp add: co_vector_zero_vector_one_vector zero_vector_one_vector_vector)\n\ntext \\<open>Theorem 10 / Figure 3: closure properties\\<close>\n\ntext \\<open>zero-vector\\<close>\n\nlemma zero_zero_vector:\n  \"zero_vector bot\"\n  by (simp add: zero_vector_def)\n\nlemma sup_zero_vector:\n  \"zero_vector x \\<Longrightarrow> zero_vector y \\<Longrightarrow> zero_vector (x \\<squnion> y)\"\n  by (simp add: mult_right_dist_sup zero_vector_3)\n\nlemma comp_zero_vector:\n  \"zero_vector x \\<Longrightarrow> zero_vector y \\<Longrightarrow> zero_vector (x * y)\"\n  by (metis mult_one_associative zero_vector_0)\n\ntext \\<open>one-vector\\<close>\n\nlemma zero_one_vector:\n  \"one_vector bot\"\n  by (simp add: one_vector_def)\n\nlemma one_one_vector:\n  \"one_vector 1\"\n  by (simp add: one_up_closed up_closed_one_vector)\n\nlemma top_one_vector:\n  \"one_vector top\"\n  by (simp add: one_vector_def)\n\nlemma sup_one_vector:\n  \"one_vector x \\<Longrightarrow> one_vector y \\<Longrightarrow> one_vector (x \\<squnion> y)\"\n  by (simp add: mult_right_dist_sup order_trans one_vector_def)\n\nlemma inf_one_vector:\n  \"one_vector x \\<Longrightarrow> one_vector y \\<Longrightarrow> one_vector (x \\<sqinter> y)\"\n  by (meson order.trans inf.boundedI mult_right_sub_dist_inf_left mult_right_sub_dist_inf_right one_vector_def)\n\nlemma comp_one_vector:\n  \"one_vector x \\<Longrightarrow> one_vector y \\<Longrightarrow> one_vector (x * y)\"\n  using mult_isotone mult_semi_associative order_lesseq_imp one_vector_def by blast\n\nend\n\ncontext multirelation_algebra_1\nbegin\n\ntext \\<open>Theorem 10 / Figure 3: closure properties\\<close>\n\ntext \\<open>zero-vector\\<close>\n\nlemma top_zero_vector:\n   \"zero_vector top\"\n  by (simp add: mult_left_top zero_vector_def)\n\nend\n\ntext \\<open>M1-algebra\\<close>\n\ncontext multirelation_algebra_2\nbegin\n\ntext \\<open>Section 7\\<close>\n\nlemma zero_vector_10:\n  \"zero_vector x \\<longleftrightarrow> x * top = x * 1\"\n  by (metis mult_one_associative mult_top_associative zero_vector_7)\n\nlemma zero_vector_11:\n  \"zero_vector x \\<longleftrightarrow> x * top \\<le> x * 1\"\n  using order.antisym mult_right_isotone zero_vector_10 by fastforce\n\ntext \\<open>Theorem 6 / Figure 2: relations between properties\\<close>\n\nlemma vector_zero_vector:\n  \"vector x \\<Longrightarrow> zero_vector x\"\n  by (simp add: zero_vector_def vector_left_annihilator)\n\nlemma vector_up_closed_zero_vector:\n  \"vector x \\<longleftrightarrow> up_closed x \\<and> zero_vector x\"\n  using up_closed_zero_vector_vector vector_up_closed vector_zero_vector by blast\n\nlemma vector_zero_vector_one_vector:\n  \"vector x \\<longleftrightarrow> zero_vector x \\<and> one_vector x\"\n  by (simp add: co_vector_zero_vector_one_vector vector_co_vector)\n\nproposition \"(x * bot \\<sqinter> y) * 1 = x * bot \\<sqinter> y * 1\" nitpick [expect=genuine,card=7] oops\n\nend\n\ntext \\<open>M3-algebra\\<close>\n\ncontext up_closed_multirelation_algebra\nbegin\n\nlemma up_closed:\n  \"up_closed x\"\n  by (simp add: up_closed_def)\n\nlemma dedekind_1_left:\n  \"x * 1 \\<sqinter> y \\<le> (x \\<sqinter> y * 1) * 1\"\n  by simp\n\ntext \\<open>Theorem 10 / Figure 3: closure properties\\<close>\n\ntext \\<open>zero-vector\\<close>\n\nlemma zero_vector_dual:\n  \"zero_vector x \\<longleftrightarrow> zero_vector (x\\<^sup>d)\"\n  using up_closed_zero_vector_vector vector_dual vector_zero_vector up_closed by blast\n\nend\n\ntext \\<open>complemented M0-algebra\\<close>\n\nclass lattice_ordered_pre_left_semiring_b = lattice_ordered_pre_left_semiring + complemented_distributive_lattice\nbegin\n\ndefinition down_closed :: \"'a \\<Rightarrow> bool\" where \"down_closed x \\<equiv> -x * 1 \\<le> -x\"\n\ntext \\<open>Theorem 10 / Figure 3: closure properties\\<close>\n\ntext \\<open>down-closed\\<close>\n\nlemma zero_down_closed:\n  \"down_closed bot\"\n  by (simp add: down_closed_def)\n\nlemma top_down_closed:\n  \"down_closed top\"\n  by (simp add: down_closed_def)\n\nlemma complement_down_closed_up_closed:\n  \"down_closed x \\<longleftrightarrow> up_closed (-x)\"\n  using down_closed_def order.antisym mult_sub_right_one up_closed_def by auto\n\nlemma sup_down_closed:\n  \"down_closed x \\<Longrightarrow> down_closed y \\<Longrightarrow> down_closed (x \\<squnion> y)\"\n  by (simp add: complement_down_closed_up_closed inf_up_closed)\n\nlemma inf_down_closed:\n  \"down_closed x \\<Longrightarrow> down_closed y \\<Longrightarrow> down_closed (x \\<sqinter> y)\"\n  by (simp add: complement_down_closed_up_closed sup_up_closed)\n\nend\n\nclass multirelation_algebra_1b = multirelation_algebra_1 + complemented_distributive_lattice\nbegin\n\nsubclass lattice_ordered_pre_left_semiring_b ..\n\ntext \\<open>Theorem 7.1\\<close>\n\nlemma complement_mult_zero_sub:\n  \"-(x * bot) \\<le> -x * bot\"\nproof -\n  have \"top = -x * bot \\<squnion> x * bot\"\n    by (metis compl_sup_top mult_left_top mult_right_dist_sup)\n  thus ?thesis\n    by (simp add: heyting.implies_order sup.commute)\nqed\n\ntext \\<open>Theorem 7.2\\<close>\n\nlemma transitive_zero_vector_complement:\n  \"transitive x \\<Longrightarrow> zero_vector (-x)\"\n  by (meson complement_mult_zero_sub compl_mono mult_right_isotone order_trans zero_vector_def bot_least)\n\nlemma transitive_dense_complement:\n  \"transitive x \\<Longrightarrow> dense_rel (-x)\"\n  by (simp add: zero_vector_dense transitive_zero_vector_complement)\n\nlemma transitive_sup_distributive_complement:\n  \"transitive x \\<Longrightarrow> sup_distributive (-x)\"\n  by (simp add: zero_vector_sup_distributive transitive_zero_vector_complement)\n\nlemma transitive_inf_distributive_complement:\n  \"transitive x \\<Longrightarrow> inf_distributive (-x)\"\n  by (simp add: zero_vector_inf_distributive transitive_zero_vector_complement)\n\nlemma up_closed_zero_vector_complement:\n  \"up_closed x \\<Longrightarrow> zero_vector (-x)\"\n  by (meson complement_mult_zero_sub compl_le_swap2 one_vector_def order_trans up_closed_one_vector zero_vector_def)\n\nlemma up_closed_dense_complement:\n  \"up_closed x \\<Longrightarrow> dense_rel (-x)\"\n  by (simp add: zero_vector_dense up_closed_zero_vector_complement)\n\nlemma up_closed_sup_distributive_complement:\n  \"up_closed x \\<Longrightarrow> sup_distributive (-x)\"\n  by (simp add: zero_vector_sup_distributive up_closed_zero_vector_complement)\n\nlemma up_closed_inf_distributive_complement:\n  \"up_closed x \\<Longrightarrow> inf_distributive (-x)\"\n  by (simp add: zero_vector_inf_distributive up_closed_zero_vector_complement)\n\ntext \\<open>Theorem 10 / Figure 3: closure properties\\<close>\n\ntext \\<open>closure under complement\\<close>\n\nlemma co_total_total:\n  \"co_total x \\<Longrightarrow> total (-x)\"\n  by (metis complement_mult_zero_sub co_total_def compl_bot_eq mult_left_sub_dist_sup_right sup_bot_right top_le)\n\nlemma complement_one_vector_zero_vector:\n  \"one_vector x \\<Longrightarrow> zero_vector (-x)\"\n  using compl_mono complement_mult_zero_sub one_vector_def order_trans zero_vector_def by blast\n\ntext \\<open>Theorem 6 / Figure 2: relations between properties\\<close>\n\nlemma down_closed_zero_vector:\n  \"down_closed x \\<Longrightarrow> zero_vector x\"\n  using complement_down_closed_up_closed up_closed_zero_vector_complement by force\n\nlemma down_closed_one_vector_vector:\n  \"down_closed x \\<Longrightarrow> one_vector x \\<Longrightarrow> vector x\"\n  by (simp add: down_closed_zero_vector zero_vector_one_vector_vector)\n\nproposition complement_vector: \"vector x \\<longrightarrow> vector (-x)\" nitpick [expect=genuine,card=8] oops\n\nend\n\nclass multirelation_algebra_1c = multirelation_algebra_1b +\n  assumes dedekind_top_left: \"x * top \\<sqinter> y \\<le> (x \\<sqinter> y * top) * top\"\n  assumes comp_zero_inf: \"(x * bot \\<sqinter> y) * bot \\<le> (x \\<sqinter> y) * bot\"\nbegin\n\ntext \\<open>Theorem 7.3\\<close>\n\nlemma schroeder_top_sub:\n  \"-(x * top) * top \\<le> -x\"\nproof -\n  have \"-(x * top) * top \\<sqinter> x \\<le> bot\"\n    by (metis dedekind_top_left p_inf zero_vector)\n  thus ?thesis\n    by (simp add: shunting_1)\nqed\n\ntext \\<open>Theorem 7.4\\<close>\n\nlemma schroeder_top:\n  \"x * top \\<le> y \\<longleftrightarrow> -y * top \\<le> -x\"\n  apply (rule iffI)\n  using compl_mono inf.order_trans mult_left_isotone schroeder_top_sub apply blast\n  by (metis compl_mono double_compl mult_left_isotone order_trans schroeder_top_sub)\n\ntext \\<open>Theorem 7.5\\<close>\n\nlemma schroeder_top_eq:\n  \"-(x * top) * top = -(x * top)\"\n  using vector_1 vector_mult_closed vector_top_closed schroeder_top by auto\n\nlemma schroeder_one_eq:\n  \"-(x * top) * 1 = -(x * top)\"\n  by (metis top_mult_right_one schroeder_top_eq)\n\ntext \\<open>Theorem 7.6\\<close>\n\nlemma vector_inf_comp:\n  \"x * top \\<sqinter> y * z = (x * top \\<sqinter> y) * z\"\nproof (rule order.antisym)\n  have \"x * top \\<sqinter> y * z = x * top \\<sqinter> ((x * top \\<sqinter> y) \\<squnion> (-(x * top) \\<sqinter> y)) * z\"\n    by (simp add: inf_commute)\n  also have \"... = x * top \\<sqinter> ((x * top \\<sqinter> y) * z \\<squnion> (-(x * top) \\<sqinter> y) * z)\"\n    by (simp add: inf_sup_distrib2 mult_right_dist_sup)\n  also have \"... = (x * top \\<sqinter> (x * top \\<sqinter> y) * z) \\<squnion> (x * top \\<sqinter> (-(x * top) \\<sqinter> y) * z)\"\n    by (simp add: inf_sup_distrib1)\n  also have \"... \\<le> (x * top \\<sqinter> y) * z \\<squnion> (x * top \\<sqinter> (-(x * top) \\<sqinter> y) * z)\"\n    by (simp add: le_infI2)\n  also have \"... \\<le> (x * top \\<sqinter> y) * z \\<squnion> (x * top \\<sqinter> -(x * top) * z)\"\n    by (metis inf.sup_left_isotone inf_commute mult_right_sub_dist_inf_left sup_right_isotone)\n  also have \"... \\<le> (x * top \\<sqinter> y) * z \\<squnion> (x * top \\<sqinter> -(x * top) * top)\"\n    using inf.sup_right_isotone mult_right_isotone sup_right_isotone by auto\n  also have \"... = (x * top \\<sqinter> y) * z\"\n    by (simp add: schroeder_top_eq)\n  finally show \"x * top \\<sqinter> y * z \\<le> (x * top \\<sqinter> y) * z\"\n    .\nnext\n  show \"(x * top \\<sqinter> y) * z \\<le> x * top \\<sqinter> y * z\"\n    by (metis inf.bounded_iff mult_left_top mult_right_sub_dist_inf_left mult_right_sub_dist_inf_right mult_semi_associative order_lesseq_imp)\nqed\n\n(* The following proof is based on \\<open>vector_inf_comp\\<close>, so the latter could serve as axiom instead. *)\nlemma dedekind_top_left_var:\n  \"x * top \\<sqinter> y \\<le> (x \\<sqinter> y * top) * top\"\n  by (metis inf.commute top_right_mult_increasing vector_inf_comp)\n\ntext \\<open>Theorem 7.7\\<close>\n\nlemma vector_zero_inf_comp:\n  \"(x * bot \\<sqinter> y) * z = x * bot \\<sqinter> y * z\"\n  by (metis vector_inf_comp vector_mult_closed zero_vector)\n\nlemma vector_zero_inf_comp_2:\n  \"(x * bot \\<sqinter> y) * z = (x * bot \\<sqinter> y * 1) * z\"\n  by (simp add: vector_zero_inf_comp)\n\ntext \\<open>Theorem 7.8\\<close>\n\nlemma comp_zero_inf_2:\n  \"x * bot \\<sqinter> y * bot = (x \\<sqinter> y) * bot\"\n  using order.antisym mult_right_sub_dist_inf comp_zero_inf vector_zero_inf_comp by auto\n\nlemma comp_zero_inf_3:\n  \"x * bot \\<sqinter> y * bot = (x * bot \\<sqinter> y) * bot\"\n  by (simp add: vector_zero_inf_comp)\n\nlemma comp_zero_inf_4:\n  \"x * bot \\<sqinter> y * bot = (x * bot \\<sqinter> y * bot) * bot\"\n  by (metis comp_zero_inf_2 inf.commute vector_zero_inf_comp)\n\nlemma comp_zero_inf_5:\n  \"x * bot \\<sqinter> y * bot = (x * 1 \\<sqinter> y * 1) * bot\"\n  by (metis comp_zero_inf_2 mult_one_associative)\n\nlemma comp_zero_inf_6:\n  \"x * bot \\<sqinter> y * bot = (x * 1 \\<sqinter> y * bot) * bot\"\n  using inf.sup_monoid.add_commute vector_zero_inf_comp by fastforce\n\nlemma comp_zero_inf_7:\n  \"x * bot \\<sqinter> y * bot = (x * 1 \\<sqinter> y) * bot\"\n  by (metis comp_zero_inf_2 mult_one_associative)\n\ntext \\<open>Theorem 10 / Figure 3: closure properties\\<close>\n\ntext \\<open>zero-vector\\<close>\n\nlemma inf_zero_vector:\n  \"zero_vector x \\<Longrightarrow> zero_vector y \\<Longrightarrow> zero_vector (x \\<sqinter> y)\"\n  by (metis comp_zero_inf_2 inf.sup_mono zero_vector_def)\n\ntext \\<open>down-closed\\<close>\n\nlemma comp_down_closed:\n  \"down_closed x \\<Longrightarrow> down_closed y \\<Longrightarrow> down_closed (x * y)\"\n  by (metis complement_down_closed_up_closed down_closed_zero_vector up_closed_def zero_vector_0 schroeder_one_eq)\n\ntext \\<open>closure under complement\\<close>\n\nlemma complement_vector:\n  \"vector x \\<longleftrightarrow> vector (-x)\"\n  using vector_1 schroeder_top by blast\n\nlemma complement_zero_vector_one_vector:\n  \"zero_vector x \\<Longrightarrow> one_vector (-x)\"\n  by (metis comp_zero_inf_2 order.antisym complement_mult_zero_sub double_compl inf.sup_monoid.add_commute mult_left_zero one_vector_def order.refl pseudo_complement top_right_mult_increasing zero_vector_0)\n\nlemma complement_zero_vector_one_vector_iff:\n  \"zero_vector x \\<longleftrightarrow> one_vector (-x)\"\n  using complement_zero_vector_one_vector complement_one_vector_zero_vector by force\n\nlemma complement_one_vector_zero_vector_iff:\n  \"one_vector x \\<longleftrightarrow> zero_vector (-x)\"\n  using complement_zero_vector_one_vector complement_one_vector_zero_vector by force\n\ntext \\<open>Theorem 6 / Figure 2: relations between properties\\<close>\n\nlemma vector_down_closed:\n  \"vector x \\<Longrightarrow> down_closed x\"\n  using complement_vector complement_down_closed_up_closed vector_up_closed by blast\n\nlemma co_vector_down_closed:\n  \"co_vector x \\<Longrightarrow> down_closed x\"\n  by (simp add: co_vector_vector vector_down_closed)\n\nlemma vector_down_closed_one_vector:\n  \"vector x \\<longleftrightarrow> down_closed x \\<and> one_vector x\"\n  using down_closed_one_vector_vector up_closed_one_vector vector_up_closed vector_down_closed by blast\n\nlemma vector_up_closed_down_closed:\n  \"vector x \\<longleftrightarrow> up_closed x \\<and> down_closed x\"\n  using down_closed_zero_vector up_closed_zero_vector_vector vector_up_closed vector_down_closed by blast\n\ntext \\<open>Section 7\\<close>\n\nlemma vector_b1:\n  \"vector x \\<longleftrightarrow> -x * top = -x\"\n  using complement_vector by auto\n\nlemma vector_b2:\n  \"vector x \\<longleftrightarrow> -x * bot = -x\"\n  by (metis down_closed_zero_vector vector_mult_closed zero_vector zero_vector_left_zero vector_b1 vector_down_closed)\n\nlemma covector_b1:\n  \"co_vector x \\<longleftrightarrow> -x * top = -x\"\n  using co_vector_def co_vector_vector vector_b1 vector_b2 by force\n\nlemma covector_b2:\n  \"co_vector x \\<longleftrightarrow> -x * bot = -x\"\n  using covector_b1 vector_b1 vector_b2 by auto\n\nlemma vector_co_vector_iff:\n  \"vector x \\<longleftrightarrow> co_vector x\"\n  by (simp add: covector_b2 vector_b2)\n\nlemma zero_vector_b:\n  \"zero_vector x \\<longleftrightarrow> -x * bot \\<le> -x\"\n  by (simp add: complement_zero_vector_one_vector_iff one_vector_def)\n\nlemma one_vector_b1:\n  \"one_vector x \\<longleftrightarrow> -x \\<le> -x * bot\"\n  by (simp add: complement_one_vector_zero_vector_iff zero_vector_def)\n\nlemma one_vector_b0:\n  \"one_vector x \\<longleftrightarrow> (\\<forall>y z . -x * y = -x * z)\"\n  by (simp add: complement_one_vector_zero_vector_iff zero_vector_0)\n\nproposition schroeder_one: \"x * -1 \\<le> y \\<longleftrightarrow> -y * -1 \\<le> -x\" nitpick [expect=genuine,card=8] oops\n\nend\n\nclass multirelation_algebra_2b = multirelation_algebra_2 + complemented_distributive_lattice\nbegin\n\nsubclass multirelation_algebra_1b ..\n\nproposition \"-x * bot \\<le> -(x * bot)\" nitpick [expect=genuine,card=8] oops\n\nend\n\ntext \\<open>complemented M1-algebra\\<close>\n\nclass multirelation_algebra_2c = multirelation_algebra_2b + multirelation_algebra_1c\n\nclass multirelation_algebra_3b = multirelation_algebra_3 + complemented_distributive_lattice\nbegin\n\nsubclass lattice_ordered_pre_left_semiring_b ..\n\nlemma dual_complement_commute:\n  \"-(x\\<^sup>d) = (-x)\\<^sup>d\"\n  by (metis compl_unique dual_dist_sup dual_dist_inf dual_top dual_zero inf_complement sup_compl_top)\n\nend\n\ntext \\<open>complemented M2-algebra\\<close>\n\nclass multirelation_algebra_5b = multirelation_algebra_5 + complemented_distributive_lattice\nbegin\n\nsubclass multirelation_algebra_2b ..\n\nsubclass multirelation_algebra_3b ..\n\nlemma dual_down_closed:\n  \"down_closed x \\<longleftrightarrow> down_closed (x\\<^sup>d)\"\n  using complement_down_closed_up_closed dual_complement_commute dual_up_closed by auto\n\nend\n\nclass multirelation_algebra_5c = multirelation_algebra_5b + multirelation_algebra_1c\nbegin\n\nlemma complement_mult_zero_below:\n  \"-x * bot \\<le> -(x * bot)\"\n  by (simp add: comp_zero_inf_2 shunting_1)\n\nproposition \"x * 1 \\<sqinter> y * 1 \\<le> (x \\<sqinter> y) * 1\" nitpick [expect=genuine,card=4] oops\nproposition \"x * 1 \\<sqinter> (y * 1) \\<le> (x * 1 \\<sqinter> y) * 1\" nitpick [expect=genuine,card=4] oops\n\nend\n\nclass up_closed_multirelation_algebra_b = up_closed_multirelation_algebra + complemented_distributive_lattice\nbegin\n\nsubclass multirelation_algebra_5c\n  apply unfold_locales\n  apply (metis inf.sup_monoid.add_commute top_right_mult_increasing vector_inf_comp)\n  using mult_right_dist_inf vector_zero_inf_comp by auto\n\nlemma complement_zero_vector:\n  \"zero_vector x \\<longleftrightarrow> zero_vector (-x)\"\n  by (simp add: zero_right_mult_decreasing zero_vector_b)\n\nlemma down_closed:\n  \"down_closed x\"\n  by (simp add: down_closed_def)\n\nlemma vector:\n  \"vector x\"\n  by (simp add: down_closed up_closed_def vector_up_closed_down_closed)\n\nend\n\nend\n\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Correctness_Algebras/Boolean_Semirings.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765257642905, "lm_q2_score": 0.8244619242200082, "lm_q1q2_score": 0.7532915065462789}}
{"text": "theory Infinite\n  imports Main\nbegin\n\nclass infinite =\n  assumes infinite_UNIV: \"infinite (UNIV :: 'a set)\"\nbegin\n\nlemma arb_element: \"finite Y \\<Longrightarrow> \\<exists>x :: 'a. x \\<notin> Y\"\n  using ex_new_if_finite infinite_UNIV\n  by blast\n\nlemma arb_finite_subset: \"finite Y \\<Longrightarrow> \\<exists>X :: 'a set. Y \\<inter> X = {} \\<and> finite X \\<and> n \\<le> card X\"\nproof -\n  assume fin: \"finite Y\"\n  then obtain X where \"X \\<subseteq> UNIV - Y\" \"finite X\" \"n \\<le> card X\"\n    using infinite_UNIV\n    by (metis Compl_eq_Diff_UNIV finite_compl infinite_arbitrarily_large order_refl)\n  then show ?thesis\n    by auto\nqed\n\nlemma arb_countable_map: \"finite Y \\<Longrightarrow> \\<exists>f :: (nat \\<Rightarrow> 'a). inj f \\<and> range f \\<subseteq> UNIV - Y\"\n  using infinite_UNIV\n  by (auto simp: infinite_countable_subset)\n\nend\n\ninstance nat :: infinite\n  by standard auto\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Eval_FO/Infinite.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9136765187126078, "lm_q2_score": 0.8244619177503205, "lm_q1q2_score": 0.7532914948212333}}
{"text": "(*  Title:       HOL/Complex.thy\n    Author:      Jacques D. Fleuriot\n    Copyright:   2001 University of Edinburgh\n    Conversion to Isar and new proofs by Lawrence C Paulson, 2003/4\n*)\n\nsection {* Complex Numbers: Rectangular and Polar Representations *}\n\ntheory Complex\nimports Transcendental\nbegin\n\ntext {*\nWe use the @{text codatatype} command to define the type of complex numbers. This allows us to use\n@{text primcorec} to define complex functions by defining their real and imaginary result\nseparately.\n*}\n\ncodatatype complex = Complex (Re: real) (Im: real)\n\nlemma complex_surj: \"Complex (Re z) (Im z) = z\"\n  by (rule complex.collapse)\n\nlemma complex_eqI [intro?]: \"\\<lbrakk>Re x = Re y; Im x = Im y\\<rbrakk> \\<Longrightarrow> x = y\"\n  by (rule complex.expand) simp\n\nlemma complex_eq_iff: \"x = y \\<longleftrightarrow> Re x = Re y \\<and> Im x = Im y\"\n  by (auto intro: complex.expand)\n\nsubsection {* Addition and Subtraction *}\n\ninstantiation complex :: ab_group_add\nbegin\n\nprimcorec zero_complex where\n  \"Re 0 = 0\"\n| \"Im 0 = 0\"\n\nprimcorec plus_complex where\n  \"Re (x + y) = Re x + Re y\"\n| \"Im (x + y) = Im x + Im y\"\n\nprimcorec uminus_complex where\n  \"Re (- x) = - Re x\"\n| \"Im (- x) = - Im x\"\n\nprimcorec minus_complex where\n  \"Re (x - y) = Re x - Re y\"\n| \"Im (x - y) = Im x - Im y\"\n\ninstance\n  by intro_classes (simp_all add: complex_eq_iff)\n\nend\n\nsubsection {* Multiplication and Division *}\n\ninstantiation complex :: field_inverse_zero\nbegin\n\nprimcorec one_complex where\n  \"Re 1 = 1\"\n| \"Im 1 = 0\"\n\nprimcorec times_complex where\n  \"Re (x * y) = Re x * Re y - Im x * Im y\"\n| \"Im (x * y) = Re x * Im y + Im x * Re y\"\n\nprimcorec inverse_complex where\n  \"Re (inverse x) = Re x / ((Re x)\\<^sup>2 + (Im x)\\<^sup>2)\"\n| \"Im (inverse x) = - Im x / ((Re x)\\<^sup>2 + (Im x)\\<^sup>2)\"\n\ndefinition \"x / (y\\<Colon>complex) = x * inverse y\"\n\ninstance\n  by intro_classes \n     (simp_all add: complex_eq_iff divide_complex_def\n      distrib_left distrib_right right_diff_distrib left_diff_distrib\n      power2_eq_square add_divide_distrib [symmetric])\n\nend\n\nlemma Re_divide: \"Re (x / y) = (Re x * Re y + Im x * Im y) / ((Re y)\\<^sup>2 + (Im y)\\<^sup>2)\"\n  unfolding divide_complex_def by (simp add: add_divide_distrib)\n\nlemma Im_divide: \"Im (x / y) = (Im x * Re y - Re x * Im y) / ((Re y)\\<^sup>2 + (Im y)\\<^sup>2)\"\n  unfolding divide_complex_def times_complex.sel inverse_complex.sel\n  by (simp_all add: divide_simps)\n\nlemma Re_power2: \"Re (x ^ 2) = (Re x)^2 - (Im x)^2\"\n  by (simp add: power2_eq_square)\n\nlemma Im_power2: \"Im (x ^ 2) = 2 * Re x * Im x\"\n  by (simp add: power2_eq_square)\n\nlemma Re_power_real: \"Im x = 0 \\<Longrightarrow> Re (x ^ n) = Re x ^ n \"\n  by (induct n) simp_all\n\nlemma Im_power_real: \"Im x = 0 \\<Longrightarrow> Im (x ^ n) = 0\"\n  by (induct n) simp_all\n\nsubsection {* Scalar Multiplication *}\n\ninstantiation complex :: real_field\nbegin\n\nprimcorec scaleR_complex where\n  \"Re (scaleR r x) = r * Re x\"\n| \"Im (scaleR r x) = r * Im x\"\n\ninstance\nproof\n  fix a b :: real and x y :: complex\n  show \"scaleR a (x + y) = scaleR a x + scaleR a y\"\n    by (simp add: complex_eq_iff distrib_left)\n  show \"scaleR (a + b) x = scaleR a x + scaleR b x\"\n    by (simp add: complex_eq_iff distrib_right)\n  show \"scaleR a (scaleR b x) = scaleR (a * b) x\"\n    by (simp add: complex_eq_iff mult.assoc)\n  show \"scaleR 1 x = x\"\n    by (simp add: complex_eq_iff)\n  show \"scaleR a x * y = scaleR a (x * y)\"\n    by (simp add: complex_eq_iff algebra_simps)\n  show \"x * scaleR a y = scaleR a (x * y)\"\n    by (simp add: complex_eq_iff algebra_simps)\nqed\n\nend\n\nsubsection {* Numerals, Arithmetic, and Embedding from Reals *}\n\nabbreviation complex_of_real :: \"real \\<Rightarrow> complex\"\n  where \"complex_of_real \\<equiv> of_real\"\n\ndeclare [[coercion \"of_real :: real \\<Rightarrow> complex\"]]\ndeclare [[coercion \"of_rat :: rat \\<Rightarrow> complex\"]]\ndeclare [[coercion \"of_int :: int \\<Rightarrow> complex\"]]\ndeclare [[coercion \"of_nat :: nat \\<Rightarrow> complex\"]]\n\nlemma complex_Re_of_nat [simp]: \"Re (of_nat n) = of_nat n\"\n  by (induct n) simp_all\n\nlemma complex_Im_of_nat [simp]: \"Im (of_nat n) = 0\"\n  by (induct n) simp_all\n\nlemma complex_Re_of_int [simp]: \"Re (of_int z) = of_int z\"\n  by (cases z rule: int_diff_cases) simp\n\nlemma complex_Im_of_int [simp]: \"Im (of_int z) = 0\"\n  by (cases z rule: int_diff_cases) simp\n\nlemma complex_Re_numeral [simp]: \"Re (numeral v) = numeral v\"\n  using complex_Re_of_int [of \"numeral v\"] by simp\n\nlemma complex_Im_numeral [simp]: \"Im (numeral v) = 0\"\n  using complex_Im_of_int [of \"numeral v\"] by simp\n\nlemma Re_complex_of_real [simp]: \"Re (complex_of_real z) = z\"\n  by (simp add: of_real_def)\n\nlemma Im_complex_of_real [simp]: \"Im (complex_of_real z) = 0\"\n  by (simp add: of_real_def)\n\nsubsection {* The Complex Number $i$ *}\n\nprimcorec \"ii\" :: complex  (\"\\<i>\") where\n  \"Re ii = 0\"\n| \"Im ii = 1\"\n\nlemma Complex_eq[simp]: \"Complex a b = a + \\<i> * b\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_eq: \"a = Re a + \\<i> * Im a\"\n  by (simp add: complex_eq_iff)\n\nlemma fun_complex_eq: \"f = (\\<lambda>x. Re (f x) + \\<i> * Im (f x))\"\n  by (simp add: fun_eq_iff complex_eq)\n\nlemma i_squared [simp]: \"ii * ii = -1\"\n  by (simp add: complex_eq_iff)\n\nlemma power2_i [simp]: \"ii\\<^sup>2 = -1\"\n  by (simp add: power2_eq_square)\n\nlemma inverse_i [simp]: \"inverse ii = - ii\"\n  by (rule inverse_unique) simp\n\nlemma divide_i [simp]: \"x / ii = - ii * x\"\n  by (simp add: divide_complex_def)\n\nlemma complex_i_mult_minus [simp]: \"ii * (ii * x) = - x\"\n  by (simp add: mult.assoc [symmetric])\n\nlemma complex_i_not_zero [simp]: \"ii \\<noteq> 0\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_i_not_one [simp]: \"ii \\<noteq> 1\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_i_not_numeral [simp]: \"ii \\<noteq> numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_i_not_neg_numeral [simp]: \"ii \\<noteq> - numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_split_polar: \"\\<exists>r a. z = complex_of_real r * (cos a + \\<i> * sin a)\"\n  by (simp add: complex_eq_iff polar_Ex)\n\nsubsection {* Vector Norm *}\n\ninstantiation complex :: real_normed_field\nbegin\n\ndefinition \"norm z = sqrt ((Re z)\\<^sup>2 + (Im z)\\<^sup>2)\"\n\nabbreviation cmod :: \"complex \\<Rightarrow> real\"\n  where \"cmod \\<equiv> norm\"\n\ndefinition complex_sgn_def:\n  \"sgn x = x /\\<^sub>R cmod x\"\n\ndefinition dist_complex_def:\n  \"dist x y = cmod (x - y)\"\n\ndefinition open_complex_def:\n  \"open (S :: complex set) \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<exists>e>0. \\<forall>y. dist y x < e \\<longrightarrow> y \\<in> S)\"\n\ninstance proof\n  fix r :: real and x y :: complex and S :: \"complex set\"\n  show \"(norm x = 0) = (x = 0)\"\n    by (simp add: norm_complex_def complex_eq_iff)\n  show \"norm (x + y) \\<le> norm x + norm y\"\n    by (simp add: norm_complex_def complex_eq_iff real_sqrt_sum_squares_triangle_ineq)\n  show \"norm (scaleR r x) = \\<bar>r\\<bar> * norm x\"\n    by (simp add: norm_complex_def complex_eq_iff power_mult_distrib distrib_left [symmetric] real_sqrt_mult)\n  show \"norm (x * y) = norm x * norm y\"\n    by (simp add: norm_complex_def complex_eq_iff real_sqrt_mult [symmetric] power2_eq_square algebra_simps)\nqed (rule complex_sgn_def dist_complex_def open_complex_def)+\n\nend\n\nlemma norm_ii [simp]: \"norm ii = 1\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_unit_one: \"cmod (cos a + \\<i> * sin a) = 1\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_complex_polar: \"cmod (r * (cos a + \\<i> * sin a)) = \\<bar>r\\<bar>\"\n  by (simp add: norm_mult cmod_unit_one)\n\nlemma complex_Re_le_cmod: \"Re x \\<le> cmod x\"\n  unfolding norm_complex_def\n  by (rule real_sqrt_sum_squares_ge1)\n\nlemma complex_mod_minus_le_complex_mod: \"- cmod x \\<le> cmod x\"\n  by (rule order_trans [OF _ norm_ge_zero]) simp\n\nlemma complex_mod_triangle_ineq2: \"cmod (b + a) - cmod b \\<le> cmod a\"\n  by (rule ord_le_eq_trans [OF norm_triangle_ineq2]) simp\n\nlemma abs_Re_le_cmod: \"\\<bar>Re x\\<bar> \\<le> cmod x\"\n  by (simp add: norm_complex_def)\n\nlemma abs_Im_le_cmod: \"\\<bar>Im x\\<bar> \\<le> cmod x\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_le: \"cmod z \\<le> \\<bar>Re z\\<bar> + \\<bar>Im z\\<bar>\"\n  apply (subst complex_eq)\n  apply (rule order_trans)\n  apply (rule norm_triangle_ineq)\n  apply (simp add: norm_mult)\n  done\n\nlemma cmod_eq_Re: \"Im z = 0 \\<Longrightarrow> cmod z = \\<bar>Re z\\<bar>\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_eq_Im: \"Re z = 0 \\<Longrightarrow> cmod z = \\<bar>Im z\\<bar>\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_power2: \"cmod z ^ 2 = (Re z)^2 + (Im z)^2\"\n  by (simp add: norm_complex_def)\n\nlemma cmod_plus_Re_le_0_iff: \"cmod z + Re z \\<le> 0 \\<longleftrightarrow> Re z = - cmod z\"\n  using abs_Re_le_cmod[of z] by auto\n\nlemma Im_eq_0: \"\\<bar>Re z\\<bar> = cmod z \\<Longrightarrow> Im z = 0\"\n  by (subst (asm) power_eq_iff_eq_base[symmetric, where n=2])\n     (auto simp add: norm_complex_def)\n\nlemma abs_sqrt_wlog:\n  fixes x::\"'a::linordered_idom\"\n  assumes \"\\<And>x::'a. x \\<ge> 0 \\<Longrightarrow> P x (x\\<^sup>2)\" shows \"P \\<bar>x\\<bar> (x\\<^sup>2)\"\nby (metis abs_ge_zero assms power2_abs)\n\nlemma complex_abs_le_norm: \"\\<bar>Re z\\<bar> + \\<bar>Im z\\<bar> \\<le> sqrt 2 * norm z\"\n  unfolding norm_complex_def\n  apply (rule abs_sqrt_wlog [where x=\"Re z\"])\n  apply (rule abs_sqrt_wlog [where x=\"Im z\"])\n  apply (rule power2_le_imp_le)\n  apply (simp_all add: power2_sum add.commute sum_squares_bound real_sqrt_mult [symmetric])\n  done\n\n\ntext {* Properties of complex signum. *}\n\nlemma sgn_eq: \"sgn z = z / complex_of_real (cmod z)\"\n  by (simp add: sgn_div_norm divide_inverse scaleR_conv_of_real mult.commute)\n\nlemma Re_sgn [simp]: \"Re(sgn z) = Re(z)/cmod z\"\n  by (simp add: complex_sgn_def divide_inverse)\n\nlemma Im_sgn [simp]: \"Im(sgn z) = Im(z)/cmod z\"\n  by (simp add: complex_sgn_def divide_inverse)\n\n\nsubsection {* Completeness of the Complexes *}\n\nlemma bounded_linear_Re: \"bounded_linear Re\"\n  by (rule bounded_linear_intro [where K=1], simp_all add: norm_complex_def)\n\nlemma bounded_linear_Im: \"bounded_linear Im\"\n  by (rule bounded_linear_intro [where K=1], simp_all add: norm_complex_def)\n\nlemmas Cauchy_Re = bounded_linear.Cauchy [OF bounded_linear_Re]\nlemmas Cauchy_Im = bounded_linear.Cauchy [OF bounded_linear_Im]\nlemmas tendsto_Re [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Re]\nlemmas tendsto_Im [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_Im]\nlemmas isCont_Re [simp] = bounded_linear.isCont [OF bounded_linear_Re]\nlemmas isCont_Im [simp] = bounded_linear.isCont [OF bounded_linear_Im]\nlemmas continuous_Re [simp] = bounded_linear.continuous [OF bounded_linear_Re]\nlemmas continuous_Im [simp] = bounded_linear.continuous [OF bounded_linear_Im]\nlemmas continuous_on_Re [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Re]\nlemmas continuous_on_Im [continuous_intros] = bounded_linear.continuous_on[OF bounded_linear_Im]\nlemmas has_derivative_Re [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Re]\nlemmas has_derivative_Im [derivative_intros] = bounded_linear.has_derivative[OF bounded_linear_Im]\nlemmas sums_Re = bounded_linear.sums [OF bounded_linear_Re]\nlemmas sums_Im = bounded_linear.sums [OF bounded_linear_Im]\n\nlemma tendsto_Complex [tendsto_intros]:\n  \"(f ---> a) F \\<Longrightarrow> (g ---> b) F \\<Longrightarrow> ((\\<lambda>x. Complex (f x) (g x)) ---> Complex a b) F\"\n  by (auto intro!: tendsto_intros)\n\nlemma tendsto_complex_iff:\n  \"(f ---> x) F \\<longleftrightarrow> (((\\<lambda>x. Re (f x)) ---> Re x) F \\<and> ((\\<lambda>x. Im (f x)) ---> Im x) F)\"\nproof safe\n  assume \"((\\<lambda>x. Re (f x)) ---> Re x) F\" \"((\\<lambda>x. Im (f x)) ---> Im x) F\"\n  from tendsto_Complex[OF this] show \"(f ---> x) F\"\n    unfolding complex.collapse .\nqed (auto intro: tendsto_intros)\n\nlemma continuous_complex_iff: \"continuous F f \\<longleftrightarrow>\n    continuous F (\\<lambda>x. Re (f x)) \\<and> continuous F (\\<lambda>x. Im (f x))\"\n  unfolding continuous_def tendsto_complex_iff ..\n\nlemma has_vector_derivative_complex_iff: \"(f has_vector_derivative x) F \\<longleftrightarrow>\n    ((\\<lambda>x. Re (f x)) has_field_derivative (Re x)) F \\<and>\n    ((\\<lambda>x. Im (f x)) has_field_derivative (Im x)) F\"\n  unfolding has_vector_derivative_def has_field_derivative_def has_derivative_def tendsto_complex_iff\n  by (simp add: field_simps bounded_linear_scaleR_left bounded_linear_mult_right)\n\nlemma has_field_derivative_Re[derivative_intros]:\n  \"(f has_vector_derivative D) F \\<Longrightarrow> ((\\<lambda>x. Re (f x)) has_field_derivative (Re D)) F\"\n  unfolding has_vector_derivative_complex_iff by safe\n\nlemma has_field_derivative_Im[derivative_intros]:\n  \"(f has_vector_derivative D) F \\<Longrightarrow> ((\\<lambda>x. Im (f x)) has_field_derivative (Im D)) F\"\n  unfolding has_vector_derivative_complex_iff by safe\n\ninstance complex :: banach\nproof\n  fix X :: \"nat \\<Rightarrow> complex\"\n  assume X: \"Cauchy X\"\n  then have \"(\\<lambda>n. Complex (Re (X n)) (Im (X n))) ----> Complex (lim (\\<lambda>n. Re (X n))) (lim (\\<lambda>n. Im (X n)))\"\n    by (intro tendsto_Complex convergent_LIMSEQ_iff[THEN iffD1] Cauchy_convergent_iff[THEN iffD1] Cauchy_Re Cauchy_Im)\n  then show \"convergent X\"\n    unfolding complex.collapse by (rule convergentI)\nqed\n\ndeclare\n  DERIV_power[where 'a=complex, unfolded of_nat_def[symmetric], derivative_intros]\n\nsubsection {* Complex Conjugation *}\n\nprimcorec cnj :: \"complex \\<Rightarrow> complex\" where\n  \"Re (cnj z) = Re z\"\n| \"Im (cnj z) = - Im z\"\n\nlemma complex_cnj_cancel_iff [simp]: \"(cnj x = cnj y) = (x = y)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_cnj [simp]: \"cnj (cnj z) = z\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_zero [simp]: \"cnj 0 = 0\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_zero_iff [iff]: \"(cnj z = 0) = (z = 0)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_add [simp]: \"cnj (x + y) = cnj x + cnj y\"\n  by (simp add: complex_eq_iff)\n\nlemma cnj_setsum [simp]: \"cnj (setsum f s) = (\\<Sum>x\\<in>s. cnj (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma complex_cnj_diff [simp]: \"cnj (x - y) = cnj x - cnj y\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_minus [simp]: \"cnj (- x) = - cnj x\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_one [simp]: \"cnj 1 = 1\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_mult [simp]: \"cnj (x * y) = cnj x * cnj y\"\n  by (simp add: complex_eq_iff)\n\nlemma cnj_setprod [simp]: \"cnj (setprod f s) = (\\<Prod>x\\<in>s. cnj (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma complex_cnj_inverse [simp]: \"cnj (inverse x) = inverse (cnj x)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_divide [simp]: \"cnj (x / y) = cnj x / cnj y\"\n  by (simp add: divide_complex_def)\n\nlemma complex_cnj_power [simp]: \"cnj (x ^ n) = cnj x ^ n\"\n  by (induct n) simp_all\n\nlemma complex_cnj_of_nat [simp]: \"cnj (of_nat n) = of_nat n\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_of_int [simp]: \"cnj (of_int z) = of_int z\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_numeral [simp]: \"cnj (numeral w) = numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_neg_numeral [simp]: \"cnj (- numeral w) = - numeral w\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_scaleR [simp]: \"cnj (scaleR r x) = scaleR r (cnj x)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_mod_cnj [simp]: \"cmod (cnj z) = cmod z\"\n  by (simp add: norm_complex_def)\n\nlemma complex_cnj_complex_of_real [simp]: \"cnj (of_real x) = of_real x\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_cnj_i [simp]: \"cnj ii = - ii\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_add_cnj: \"z + cnj z = complex_of_real (2 * Re z)\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_diff_cnj: \"z - cnj z = complex_of_real (2 * Im z) * ii\"\n  by (simp add: complex_eq_iff)\n\nlemma complex_mult_cnj: \"z * cnj z = complex_of_real ((Re z)\\<^sup>2 + (Im z)\\<^sup>2)\"\n  by (simp add: complex_eq_iff power2_eq_square)\n\nlemma complex_mod_mult_cnj: \"cmod (z * cnj z) = (cmod z)\\<^sup>2\"\n  by (simp add: norm_mult power2_eq_square)\n\nlemma complex_mod_sqrt_Re_mult_cnj: \"cmod z = sqrt (Re (z * cnj z))\"\n  by (simp add: norm_complex_def power2_eq_square)\n\nlemma complex_In_mult_cnj_zero [simp]: \"Im (z * cnj z) = 0\"\n  by simp\n\nlemma bounded_linear_cnj: \"bounded_linear cnj\"\n  using complex_cnj_add complex_cnj_scaleR\n  by (rule bounded_linear_intro [where K=1], simp)\n\nlemmas tendsto_cnj [tendsto_intros] = bounded_linear.tendsto [OF bounded_linear_cnj]\nlemmas isCont_cnj [simp] = bounded_linear.isCont [OF bounded_linear_cnj]\nlemmas continuous_cnj [simp, continuous_intros] = bounded_linear.continuous [OF bounded_linear_cnj]\nlemmas continuous_on_cnj [simp, continuous_intros] = bounded_linear.continuous_on [OF bounded_linear_cnj]\nlemmas has_derivative_cnj [simp, derivative_intros] = bounded_linear.has_derivative [OF bounded_linear_cnj]\n\nlemma lim_cnj: \"((\\<lambda>x. cnj(f x)) ---> cnj l) F \\<longleftrightarrow> (f ---> l) F\"\n  by (simp add: tendsto_iff dist_complex_def complex_cnj_diff [symmetric] del: complex_cnj_diff)\n\nlemma sums_cnj: \"((\\<lambda>x. cnj(f x)) sums cnj l) \\<longleftrightarrow> (f sums l)\"\n  by (simp add: sums_def lim_cnj cnj_setsum [symmetric] del: cnj_setsum)\n\n\nsubsection{*Basic Lemmas*}\n\nlemma complex_eq_0: \"z=0 \\<longleftrightarrow> (Re z)\\<^sup>2 + (Im z)\\<^sup>2 = 0\"\n  by (metis zero_complex.sel complex_eqI sum_power2_eq_zero_iff)\n\nlemma complex_neq_0: \"z\\<noteq>0 \\<longleftrightarrow> (Re z)\\<^sup>2 + (Im z)\\<^sup>2 > 0\"\n  by (metis complex_eq_0 less_numeral_extra(3) sum_power2_gt_zero_iff)\n\nlemma complex_norm_square: \"of_real ((norm z)\\<^sup>2) = z * cnj z\"\nby (cases z)\n   (auto simp: complex_eq_iff norm_complex_def power2_eq_square[symmetric] of_real_power[symmetric]\n         simp del: of_real_power)\n\nlemma re_complex_div_eq_0: \"Re (a / b) = 0 \\<longleftrightarrow> Re (a * cnj b) = 0\"\n  by (auto simp add: Re_divide)\n  \nlemma im_complex_div_eq_0: \"Im (a / b) = 0 \\<longleftrightarrow> Im (a * cnj b) = 0\"\n  by (auto simp add: Im_divide)\n\nlemma complex_div_gt_0: \n  \"(Re (a / b) > 0 \\<longleftrightarrow> Re (a * cnj b) > 0) \\<and> (Im (a / b) > 0 \\<longleftrightarrow> Im (a * cnj b) > 0)\"\nproof cases\n  assume \"b = 0\" then show ?thesis by auto\nnext\n  assume \"b \\<noteq> 0\"\n  then have \"0 < (Re b)\\<^sup>2 + (Im b)\\<^sup>2\"\n    by (simp add: complex_eq_iff sum_power2_gt_zero_iff)\n  then show ?thesis\n    by (simp add: Re_divide Im_divide zero_less_divide_iff)\nqed\n\nlemma re_complex_div_gt_0: \"Re (a / b) > 0 \\<longleftrightarrow> Re (a * cnj b) > 0\"\n  and im_complex_div_gt_0: \"Im (a / b) > 0 \\<longleftrightarrow> Im (a * cnj b) > 0\"\n  using complex_div_gt_0 by auto\n\nlemma re_complex_div_ge_0: \"Re(a / b) \\<ge> 0 \\<longleftrightarrow> Re(a * cnj b) \\<ge> 0\"\n  by (metis le_less re_complex_div_eq_0 re_complex_div_gt_0)\n\nlemma im_complex_div_ge_0: \"Im(a / b) \\<ge> 0 \\<longleftrightarrow> Im(a * cnj b) \\<ge> 0\"\n  by (metis im_complex_div_eq_0 im_complex_div_gt_0 le_less)\n\nlemma re_complex_div_lt_0: \"Re(a / b) < 0 \\<longleftrightarrow> Re(a * cnj b) < 0\"\n  by (metis less_asym neq_iff re_complex_div_eq_0 re_complex_div_gt_0)\n\nlemma im_complex_div_lt_0: \"Im(a / b) < 0 \\<longleftrightarrow> Im(a * cnj b) < 0\"\n  by (metis im_complex_div_eq_0 im_complex_div_gt_0 less_asym neq_iff)\n\nlemma re_complex_div_le_0: \"Re(a / b) \\<le> 0 \\<longleftrightarrow> Re(a * cnj b) \\<le> 0\"\n  by (metis not_le re_complex_div_gt_0)\n\nlemma im_complex_div_le_0: \"Im(a / b) \\<le> 0 \\<longleftrightarrow> Im(a * cnj b) \\<le> 0\"\n  by (metis im_complex_div_gt_0 not_le)\n\nlemma Re_setsum[simp]: \"Re (setsum f s) = (\\<Sum>x\\<in>s. Re (f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma Im_setsum[simp]: \"Im (setsum f s) = (\\<Sum>x\\<in>s. Im(f x))\"\n  by (induct s rule: infinite_finite_induct) auto\n\nlemma sums_complex_iff: \"f sums x \\<longleftrightarrow> ((\\<lambda>x. Re (f x)) sums Re x) \\<and> ((\\<lambda>x. Im (f x)) sums Im x)\"\n  unfolding sums_def tendsto_complex_iff Im_setsum Re_setsum ..\n  \nlemma summable_complex_iff: \"summable f \\<longleftrightarrow> summable (\\<lambda>x. Re (f x)) \\<and>  summable (\\<lambda>x. Im (f x))\"\n  unfolding summable_def sums_complex_iff[abs_def] by (metis complex.sel)\n\nlemma summable_complex_of_real [simp]: \"summable (\\<lambda>n. complex_of_real (f n)) \\<longleftrightarrow> summable f\"\n  unfolding summable_complex_iff by simp\n\nlemma summable_Re: \"summable f \\<Longrightarrow> summable (\\<lambda>x. Re (f x))\"\n  unfolding summable_complex_iff by blast\n\nlemma summable_Im: \"summable f \\<Longrightarrow> summable (\\<lambda>x. Im (f x))\"\n  unfolding summable_complex_iff by blast\n\nlemma complex_is_Real_iff: \"z \\<in> \\<real> \\<longleftrightarrow> Im z = 0\"\n  by (auto simp: Reals_def complex_eq_iff)\n\nlemma Reals_cnj_iff: \"z \\<in> \\<real> \\<longleftrightarrow> cnj z = z\"\n  by (auto simp: complex_is_Real_iff complex_eq_iff)\n\nlemma in_Reals_norm: \"z \\<in> \\<real> \\<Longrightarrow> norm(z) = abs(Re z)\"\n  by (simp add: complex_is_Real_iff norm_complex_def)\n\nlemma series_comparison_complex:\n  fixes f:: \"nat \\<Rightarrow> 'a::banach\"\n  assumes sg: \"summable g\"\n     and \"\\<And>n. g n \\<in> \\<real>\" \"\\<And>n. Re (g n) \\<ge> 0\"\n     and fg: \"\\<And>n. n \\<ge> N \\<Longrightarrow> norm(f n) \\<le> norm(g n)\"\n  shows \"summable f\"\nproof -\n  have g: \"\\<And>n. cmod (g n) = Re (g n)\" using assms\n    by (metis abs_of_nonneg in_Reals_norm)\n  show ?thesis\n    apply (rule summable_comparison_test' [where g = \"\\<lambda>n. norm (g n)\" and N=N])\n    using sg\n    apply (auto simp: summable_def)\n    apply (rule_tac x=\"Re s\" in exI)\n    apply (auto simp: g sums_Re)\n    apply (metis fg g)\n    done\nqed\n\nsubsection{*Finally! Polar Form for Complex Numbers*}\n\nsubsubsection {* $\\cos \\theta + i \\sin \\theta$ *}\n\nprimcorec cis :: \"real \\<Rightarrow> complex\" where\n  \"Re (cis a) = cos a\"\n| \"Im (cis a) = sin a\"\n\nlemma cis_zero [simp]: \"cis 0 = 1\"\n  by (simp add: complex_eq_iff)\n\nlemma norm_cis [simp]: \"norm (cis a) = 1\"\n  by (simp add: norm_complex_def)\n\nlemma sgn_cis [simp]: \"sgn (cis a) = cis a\"\n  by (simp add: sgn_div_norm)\n\nlemma cis_neq_zero [simp]: \"cis a \\<noteq> 0\"\n  by (metis norm_cis norm_zero zero_neq_one)\n\nlemma cis_mult: \"cis a * cis b = cis (a + b)\"\n  by (simp add: complex_eq_iff cos_add sin_add)\n\nlemma DeMoivre: \"(cis a) ^ n = cis (real n * a)\"\n  by (induct n, simp_all add: real_of_nat_Suc algebra_simps cis_mult)\n\nlemma cis_inverse [simp]: \"inverse(cis a) = cis (-a)\"\n  by (simp add: complex_eq_iff)\n\nlemma cis_divide: \"cis a / cis b = cis (a - b)\"\n  by (simp add: divide_complex_def cis_mult)\n\nlemma cos_n_Re_cis_pow_n: \"cos (real n * a) = Re(cis a ^ n)\"\n  by (auto simp add: DeMoivre)\n\nlemma sin_n_Im_cis_pow_n: \"sin (real n * a) = Im(cis a ^ n)\"\n  by (auto simp add: DeMoivre)\n\nlemma cis_pi: \"cis pi = -1\"\n  by (simp add: complex_eq_iff)\n\nsubsubsection {* $r(\\cos \\theta + i \\sin \\theta)$ *}\n\ndefinition rcis :: \"real \\<Rightarrow> real \\<Rightarrow> complex\" where\n  \"rcis r a = complex_of_real r * cis a\"\n\nlemma Re_rcis [simp]: \"Re(rcis r a) = r * cos a\"\n  by (simp add: rcis_def)\n\nlemma Im_rcis [simp]: \"Im(rcis r a) = r * sin a\"\n  by (simp add: rcis_def)\n\nlemma rcis_Ex: \"\\<exists>r a. z = rcis r a\"\n  by (simp add: complex_eq_iff polar_Ex)\n\nlemma complex_mod_rcis [simp]: \"cmod(rcis r a) = abs r\"\n  by (simp add: rcis_def norm_mult)\n\nlemma cis_rcis_eq: \"cis a = rcis 1 a\"\n  by (simp add: rcis_def)\n\nlemma rcis_mult: \"rcis r1 a * rcis r2 b = rcis (r1*r2) (a + b)\"\n  by (simp add: rcis_def cis_mult)\n\nlemma rcis_zero_mod [simp]: \"rcis 0 a = 0\"\n  by (simp add: rcis_def)\n\nlemma rcis_zero_arg [simp]: \"rcis r 0 = complex_of_real r\"\n  by (simp add: rcis_def)\n\nlemma rcis_eq_zero_iff [simp]: \"rcis r a = 0 \\<longleftrightarrow> r = 0\"\n  by (simp add: rcis_def)\n\nlemma DeMoivre2: \"(rcis r a) ^ n = rcis (r ^ n) (real n * a)\"\n  by (simp add: rcis_def power_mult_distrib DeMoivre)\n\nlemma rcis_inverse: \"inverse(rcis r a) = rcis (1/r) (-a)\"\n  by (simp add: divide_inverse rcis_def)\n\nlemma rcis_divide: \"rcis r1 a / rcis r2 b = rcis (r1/r2) (a - b)\"\n  by (simp add: rcis_def cis_divide [symmetric])\n\nsubsubsection {* Complex exponential *}\n\nabbreviation expi :: \"complex \\<Rightarrow> complex\"\n  where \"expi \\<equiv> exp\"\n\nlemma cis_conv_exp: \"cis b = exp (\\<i> * b)\"\nproof -\n  { fix n :: nat\n    have \"\\<i> ^ n = fact n *\\<^sub>R (cos_coeff n + \\<i> * sin_coeff n)\"\n      by (induct n)\n         (simp_all add: sin_coeff_Suc cos_coeff_Suc complex_eq_iff Re_divide Im_divide field_simps\n                        power2_eq_square real_of_nat_Suc add_nonneg_eq_0_iff\n                        real_of_nat_def[symmetric])\n    then have \"(\\<i> * complex_of_real b) ^ n /\\<^sub>R fact n =\n        of_real (cos_coeff n * b^n) + \\<i> * of_real (sin_coeff n * b^n)\"\n      by (simp add: field_simps) }\n  then show ?thesis\n    by (auto simp add: cis.ctr exp_def simp del: of_real_mult\n             intro!: sums_unique sums_add sums_mult sums_of_real sin_converges cos_converges)\nqed\n\nlemma expi_def: \"expi z = exp (Re z) * cis (Im z)\"\n  unfolding cis_conv_exp exp_of_real [symmetric] mult_exp_exp by (cases z) simp\n\nlemma Re_exp: \"Re (exp z) = exp (Re z) * cos (Im z)\"\n  unfolding expi_def by simp\n\nlemma Im_exp: \"Im (exp z) = exp (Re z) * sin (Im z)\"\n  unfolding expi_def by simp\n\nlemma complex_expi_Ex: \"\\<exists>a r. z = complex_of_real r * expi a\"\napply (insert rcis_Ex [of z])\napply (auto simp add: expi_def rcis_def mult.assoc [symmetric])\napply (rule_tac x = \"ii * complex_of_real a\" in exI, auto)\ndone\n\nlemma expi_two_pi_i [simp]: \"expi((2::complex) * complex_of_real pi * ii) = 1\"\n  by (simp add: expi_def complex_eq_iff)\n\nsubsubsection {* Complex argument *}\n\ndefinition arg :: \"complex \\<Rightarrow> real\" where\n  \"arg z = (if z = 0 then 0 else (SOME a. sgn z = cis a \\<and> -pi < a \\<and> a \\<le> pi))\"\n\nlemma arg_zero: \"arg 0 = 0\"\n  by (simp add: arg_def)\n\nlemma arg_unique:\n  assumes \"sgn z = cis x\" and \"-pi < x\" and \"x \\<le> pi\"\n  shows \"arg z = x\"\nproof -\n  from assms have \"z \\<noteq> 0\" by auto\n  have \"(SOME a. sgn z = cis a \\<and> -pi < a \\<and> a \\<le> pi) = x\"\n  proof\n    fix a def d \\<equiv> \"a - x\"\n    assume a: \"sgn z = cis a \\<and> - pi < a \\<and> a \\<le> pi\"\n    from a assms have \"- (2*pi) < d \\<and> d < 2*pi\"\n      unfolding d_def by simp\n    moreover from a assms have \"cos a = cos x\" and \"sin a = sin x\"\n      by (simp_all add: complex_eq_iff)\n    hence cos: \"cos d = 1\" unfolding d_def cos_diff by simp\n    moreover from cos have \"sin d = 0\" by (rule cos_one_sin_zero)\n    ultimately have \"d = 0\"\n      unfolding sin_zero_iff\n      by (auto elim!: evenE dest!: less_2_cases)\n    thus \"a = x\" unfolding d_def by simp\n  qed (simp add: assms del: Re_sgn Im_sgn)\n  with `z \\<noteq> 0` show \"arg z = x\"\n    unfolding arg_def by simp\nqed\n\nlemma arg_correct:\n  assumes \"z \\<noteq> 0\" shows \"sgn z = cis (arg z) \\<and> -pi < arg z \\<and> arg z \\<le> pi\"\nproof (simp add: arg_def assms, rule someI_ex)\n  obtain r a where z: \"z = rcis r a\" using rcis_Ex by fast\n  with assms have \"r \\<noteq> 0\" by auto\n  def b \\<equiv> \"if 0 < r then a else a + pi\"\n  have b: \"sgn z = cis b\"\n    unfolding z b_def rcis_def using `r \\<noteq> 0`\n    by (simp add: of_real_def sgn_scaleR sgn_if complex_eq_iff)\n  have cis_2pi_nat: \"\\<And>n. cis (2 * pi * real_of_nat n) = 1\"\n    by (induct_tac n) (simp_all add: distrib_left cis_mult [symmetric] complex_eq_iff)\n  have cis_2pi_int: \"\\<And>x. cis (2 * pi * real_of_int x) = 1\"\n    by (case_tac x rule: int_diff_cases)\n       (simp add: right_diff_distrib cis_divide [symmetric] cis_2pi_nat)\n  def c \\<equiv> \"b - 2*pi * of_int \\<lceil>(b - pi) / (2*pi)\\<rceil>\"\n  have \"sgn z = cis c\"\n    unfolding b c_def\n    by (simp add: cis_divide [symmetric] cis_2pi_int)\n  moreover have \"- pi < c \\<and> c \\<le> pi\"\n    using ceiling_correct [of \"(b - pi) / (2*pi)\"]\n    by (simp add: c_def less_divide_eq divide_le_eq algebra_simps)\n  ultimately show \"\\<exists>a. sgn z = cis a \\<and> -pi < a \\<and> a \\<le> pi\" by fast\nqed\n\nlemma arg_bounded: \"- pi < arg z \\<and> arg z \\<le> pi\"\n  by (cases \"z = 0\") (simp_all add: arg_zero arg_correct)\n\nlemma cis_arg: \"z \\<noteq> 0 \\<Longrightarrow> cis (arg z) = sgn z\"\n  by (simp add: arg_correct)\n\nlemma rcis_cmod_arg: \"rcis (cmod z) (arg z) = z\"\n  by (cases \"z = 0\") (simp_all add: rcis_def cis_arg sgn_div_norm of_real_def)\n\nlemma cos_arg_i_mult_zero [simp]: \"y \\<noteq> 0 \\<Longrightarrow> Re y = 0 \\<Longrightarrow> cos (arg y) = 0\"\n  using cis_arg [of y] by (simp add: complex_eq_iff)\n\nsubsection {* Square root of complex numbers *}\n\nprimcorec csqrt :: \"complex \\<Rightarrow> complex\" where\n  \"Re (csqrt z) = sqrt ((cmod z + Re z) / 2)\"\n| \"Im (csqrt z) = (if Im z = 0 then 1 else sgn (Im z)) * sqrt ((cmod z - Re z) / 2)\"\n\nlemma csqrt_of_real_nonneg [simp]: \"Im x = 0 \\<Longrightarrow> Re x \\<ge> 0 \\<Longrightarrow> csqrt x = sqrt (Re x)\"\n  by (simp add: complex_eq_iff norm_complex_def)\n\nlemma csqrt_of_real_nonpos [simp]: \"Im x = 0 \\<Longrightarrow> Re x \\<le> 0 \\<Longrightarrow> csqrt x = \\<i> * sqrt \\<bar>Re x\\<bar>\"\n  by (simp add: complex_eq_iff norm_complex_def)\n\nlemma csqrt_0 [simp]: \"csqrt 0 = 0\"\n  by simp\n\nlemma csqrt_1 [simp]: \"csqrt 1 = 1\"\n  by simp\n\nlemma csqrt_ii [simp]: \"csqrt \\<i> = (1 + \\<i>) / sqrt 2\"\n  by (simp add: complex_eq_iff Re_divide Im_divide real_sqrt_divide real_div_sqrt)\n\nlemma power2_csqrt[algebra]: \"(csqrt z)\\<^sup>2 = z\"\nproof cases\n  assume \"Im z = 0\" then show ?thesis\n    using real_sqrt_pow2[of \"Re z\"] real_sqrt_pow2[of \"- Re z\"]\n    by (cases \"0::real\" \"Re z\" rule: linorder_cases)\n       (simp_all add: complex_eq_iff Re_power2 Im_power2 power2_eq_square cmod_eq_Re)\nnext\n  assume \"Im z \\<noteq> 0\"\n  moreover\n  have \"cmod z * cmod z - Re z * Re z = Im z * Im z\"\n    by (simp add: norm_complex_def power2_eq_square)\n  moreover\n  have \"\\<bar>Re z\\<bar> \\<le> cmod z\"\n    by (simp add: norm_complex_def)\n  ultimately show ?thesis\n    by (simp add: Re_power2 Im_power2 complex_eq_iff real_sgn_eq\n                  field_simps real_sqrt_mult[symmetric] real_sqrt_divide)\nqed\n\nlemma csqrt_eq_0 [simp]: \"csqrt z = 0 \\<longleftrightarrow> z = 0\"\n  by auto (metis power2_csqrt power_eq_0_iff)\n\nlemma csqrt_eq_1 [simp]: \"csqrt z = 1 \\<longleftrightarrow> z = 1\"\n  by auto (metis power2_csqrt power2_eq_1_iff)\n\nlemma csqrt_principal: \"0 < Re (csqrt z) \\<or> Re (csqrt z) = 0 \\<and> 0 \\<le> Im (csqrt z)\"\n  by (auto simp add: not_less cmod_plus_Re_le_0_iff Im_eq_0)\n\nlemma Re_csqrt: \"0 \\<le> Re (csqrt z)\"\n  by (metis csqrt_principal le_less)\n\nlemma csqrt_square:\n  assumes \"0 < Re b \\<or> (Re b = 0 \\<and> 0 \\<le> Im b)\"\n  shows \"csqrt (b^2) = b\"\nproof -\n  have \"csqrt (b^2) = b \\<or> csqrt (b^2) = - b\"\n    unfolding power2_eq_iff[symmetric] by (simp add: power2_csqrt)\n  moreover have \"csqrt (b^2) \\<noteq> -b \\<or> b = 0\"\n    using csqrt_principal[of \"b ^ 2\"] assms by (intro disjCI notI) (auto simp: complex_eq_iff)\n  ultimately show ?thesis\n    by auto\nqed\n\nlemma csqrt_minus [simp]: \n  assumes \"Im x < 0 \\<or> (Im x = 0 \\<and> 0 \\<le> Re x)\"\n  shows \"csqrt (- x) = \\<i> * csqrt x\"\nproof -\n  have \"csqrt ((\\<i> * csqrt x)^2) = \\<i> * csqrt x\"\n  proof (rule csqrt_square)\n    have \"Im (csqrt x) \\<le> 0\"\n      using assms by (auto simp add: cmod_eq_Re mult_le_0_iff field_simps complex_Re_le_cmod)\n    then show \"0 < Re (\\<i> * csqrt x) \\<or> Re (\\<i> * csqrt x) = 0 \\<and> 0 \\<le> Im (\\<i> * csqrt x)\"\n      by (auto simp add: Re_csqrt simp del: csqrt.simps)\n  qed\n  also have \"(\\<i> * csqrt x)^2 = - x\"\n    by (simp add: power2_csqrt power_mult_distrib)\n  finally show ?thesis .\nqed\n\ntext {* Legacy theorem names *}\n\nlemmas expand_complex_eq = complex_eq_iff\nlemmas complex_Re_Im_cancel_iff = complex_eq_iff\nlemmas complex_equality = complex_eqI\nlemmas cmod_def = norm_complex_def\nlemmas complex_norm_def = norm_complex_def\nlemmas complex_divide_def = divide_complex_def\n\nlemma legacy_Complex_simps:\n  shows Complex_eq_0: \"Complex a b = 0 \\<longleftrightarrow> a = 0 \\<and> b = 0\"\n    and complex_add: \"Complex a b + Complex c d = Complex (a + c) (b + d)\"\n    and complex_minus: \"- (Complex a b) = Complex (- a) (- b)\"\n    and complex_diff: \"Complex a b - Complex c d = Complex (a - c) (b - d)\"\n    and Complex_eq_1: \"Complex a b = 1 \\<longleftrightarrow> a = 1 \\<and> b = 0\"\n    and Complex_eq_neg_1: \"Complex a b = - 1 \\<longleftrightarrow> a = - 1 \\<and> b = 0\"\n    and complex_mult: \"Complex a b * Complex c d = Complex (a * c - b * d) (a * d + b * c)\"\n    and complex_inverse: \"inverse (Complex a b) = Complex (a / (a\\<^sup>2 + b\\<^sup>2)) (- b / (a\\<^sup>2 + b\\<^sup>2))\"\n    and Complex_eq_numeral: \"Complex a b = numeral w \\<longleftrightarrow> a = numeral w \\<and> b = 0\"\n    and Complex_eq_neg_numeral: \"Complex a b = - numeral w \\<longleftrightarrow> a = - numeral w \\<and> b = 0\"\n    and complex_scaleR: \"scaleR r (Complex a b) = Complex (r * a) (r * b)\"\n    and Complex_eq_i: \"(Complex x y = ii) = (x = 0 \\<and> y = 1)\"\n    and i_mult_Complex: \"ii * Complex a b = Complex (- b) a\"\n    and Complex_mult_i: \"Complex a b * ii = Complex (- b) a\"\n    and i_complex_of_real: \"ii * complex_of_real r = Complex 0 r\"\n    and complex_of_real_i: \"complex_of_real r * ii = Complex 0 r\"\n    and Complex_add_complex_of_real: \"Complex x y + complex_of_real r = Complex (x+r) y\"\n    and complex_of_real_add_Complex: \"complex_of_real r + Complex x y = Complex (r+x) y\"\n    and Complex_mult_complex_of_real: \"Complex x y * complex_of_real r = Complex (x*r) (y*r)\"\n    and complex_of_real_mult_Complex: \"complex_of_real r * Complex x y = Complex (r*x) (r*y)\"\n    and complex_eq_cancel_iff2: \"(Complex x y = complex_of_real xa) = (x = xa & y = 0)\"\n    and complex_cn: \"cnj (Complex a b) = Complex a (- b)\"\n    and Complex_setsum': \"setsum (%x. Complex (f x) 0) s = Complex (setsum f s) 0\"\n    and Complex_setsum: \"Complex (setsum f s) 0 = setsum (%x. Complex (f x) 0) s\"\n    and complex_of_real_def: \"complex_of_real r = Complex r 0\"\n    and complex_norm: \"cmod (Complex x y) = sqrt (x\\<^sup>2 + y\\<^sup>2)\"\n  by (simp_all add: norm_complex_def field_simps complex_eq_iff Re_divide Im_divide del: Complex_eq)\n\nlemma Complex_in_Reals: \"Complex x 0 \\<in> \\<real>\"\n  by (metis Reals_of_real complex_of_real_def)\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Complex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7532617301754031}}
{"text": "(*  Title:      HOL/HOLCF/Porder.thy\n    Author:     Franz Regensburger and Brian Huffman\n*)\n\nsection \\<open>Partial orders\\<close>\n\ntheory Porder\nimports Main\nbegin\n\ndeclare [[typedef_overloaded]]\n\n\nsubsection \\<open>Type class for partial orders\\<close>\n\nclass below =\n  fixes below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation (ASCII)\n  below (infix \"<<\" 50)\n\nnotation\n  below (infix \"\\<sqsubseteq>\" 50)\n\nabbreviation\n  not_below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infix \"\\<notsqsubseteq>\" 50)\n  where \"not_below x y \\<equiv> \\<not> below x y\"\n\nnotation (ASCII)\n  not_below  (infix \"~<<\" 50)\n\nlemma below_eq_trans: \"\\<lbrakk>a \\<sqsubseteq> b; b = c\\<rbrakk> \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule subst)\n\nlemma eq_below_trans: \"\\<lbrakk>a = b; b \\<sqsubseteq> c\\<rbrakk> \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule ssubst)\n\nend\n\nclass po = below +\n  assumes below_refl [iff]: \"x \\<sqsubseteq> x\"\n  assumes below_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  assumes below_antisym: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma eq_imp_below: \"x = y \\<Longrightarrow> x \\<sqsubseteq> y\"\n  by simp\n\nlemma box_below: \"a \\<sqsubseteq> b \\<Longrightarrow> c \\<sqsubseteq> a \\<Longrightarrow> b \\<sqsubseteq> d \\<Longrightarrow> c \\<sqsubseteq> d\"\n  by (rule below_trans [OF below_trans])\n\nlemma po_eq_conv: \"x = y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\n  by (fast intro!: below_antisym)\n\nlemma rev_below_trans: \"y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> y \\<Longrightarrow> x \\<sqsubseteq> z\"\n  by (rule below_trans)\n\nlemma not_below2not_eq: \"x \\<notsqsubseteq> y \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nend\n\nlemmas HOLCF_trans_rules [trans] =\n  below_trans\n  below_antisym\n  below_eq_trans\n  eq_below_trans\n\ncontext po\nbegin\n\nsubsection \\<open>Upper bounds\\<close>\n\ndefinition is_ub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<|\" 55) where\n  \"S <| x \\<longleftrightarrow> (\\<forall>y\\<in>S. y \\<sqsubseteq> x)\"\n\nlemma is_ubI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> x \\<sqsubseteq> u) \\<Longrightarrow> S <| u\"\n  by (simp add: is_ub_def)\n\nlemma is_ubD: \"\\<lbrakk>S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  by (simp add: is_ub_def)\n\nlemma ub_imageI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<sqsubseteq> u) \\<Longrightarrow> (\\<lambda>x. f x) ` S <| u\"\n  unfolding is_ub_def by fast\n\nlemma ub_imageD: \"\\<lbrakk>f ` S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq> u\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeI: \"(\\<And>i. S i \\<sqsubseteq> x) \\<Longrightarrow> range S <| x\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeD: \"range S <| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_empty [simp]: \"{} <| u\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_insert [simp]: \"(insert x A) <| y = (x \\<sqsubseteq> y \\<and> A <| y)\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_upward: \"\\<lbrakk>S <| x; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> S <| y\"\n  unfolding is_ub_def by (fast intro: below_trans)\n\nsubsection \\<open>Least upper bounds\\<close>\n\ndefinition is_lub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<<|\" 55) where\n  \"S <<| x \\<longleftrightarrow> S <| x \\<and> (\\<forall>u. S <| u \\<longrightarrow> x \\<sqsubseteq> u)\"\n\ndefinition lub :: \"'a set \\<Rightarrow> 'a\" where\n  \"lub S = (THE x. S <<| x)\"\n\nend\n\nsyntax (ASCII)\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3LUB _:_./ _)\" [0,0, 10] 10)\n\nsyntax\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3\\<Squnion>_\\<in>_./ _)\" [0,0, 10] 10)\n\ntranslations\n  \"LUB x:A. t\" == \"CONST lub ((%x. t) ` A)\"\n\ncontext po\nbegin\n\nabbreviation\n  Lub  (binder \"\\<Squnion>\" 10) where\n  \"\\<Squnion>n. t n == lub (range t)\"\n\nnotation (ASCII)\n  Lub  (binder \"LUB \" 10)\n\ntext \\<open>access to some definition as inference rule\\<close>\n\nlemma is_lubD1: \"S <<| x \\<Longrightarrow> S <| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lubD2: \"\\<lbrakk>S <<| x; S <| u\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  unfolding is_lub_def by fast\n\nlemma is_lubI: \"\\<lbrakk>S <| x; \\<And>u. S <| u \\<Longrightarrow> x \\<sqsubseteq> u\\<rbrakk> \\<Longrightarrow> S <<| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lub_below_iff: \"S <<| x \\<Longrightarrow> x \\<sqsubseteq> u \\<longleftrightarrow> S <| u\"\n  unfolding is_lub_def is_ub_def by (metis below_trans)\n\ntext \\<open>lubs are unique\\<close>\n\nlemma is_lub_unique: \"\\<lbrakk>S <<| x; S <<| y\\<rbrakk> \\<Longrightarrow> x = y\"\n  unfolding is_lub_def is_ub_def by (blast intro: below_antisym)\n\ntext \\<open>technical lemmas about @{term lub} and @{term is_lub}\\<close>\n\nlemma is_lub_lub: \"M <<| x \\<Longrightarrow> M <<| lub M\"\n  unfolding lub_def by (rule theI [OF _ is_lub_unique])\n\nlemma lub_eqI: \"M <<| l \\<Longrightarrow> lub M = l\"\n  by (rule is_lub_unique [OF is_lub_lub])\n\nlemma is_lub_singleton: \"{x} <<| x\"\n  by (simp add: is_lub_def)\n\nlemma lub_singleton [simp]: \"lub {x} = x\"\n  by (rule is_lub_singleton [THEN lub_eqI])\n\nlemma is_lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> {x, y} <<| y\"\n  by (simp add: is_lub_def)\n\nlemma lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> lub {x, y} = y\"\n  by (rule is_lub_bin [THEN lub_eqI])\n\nlemma is_lub_maximal: \"\\<lbrakk>S <| x; x \\<in> S\\<rbrakk> \\<Longrightarrow> S <<| x\"\n  by (erule is_lubI, erule (1) is_ubD)\n\nlemma lub_maximal: \"\\<lbrakk>S <| x; x \\<in> S\\<rbrakk> \\<Longrightarrow> lub S = x\"\n  by (rule is_lub_maximal [THEN lub_eqI])\n\nsubsection \\<open>Countable chains\\<close>\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \\<comment> \\<open>Here we use countable chains and I prefer to code them as functions!\\<close>\n  \"chain Y = (\\<forall>i. Y i \\<sqsubseteq> Y (Suc i))\"\n\nlemma chainI: \"(\\<And>i. Y i \\<sqsubseteq> Y (Suc i)) \\<Longrightarrow> chain Y\"\n  unfolding chain_def by fast\n\nlemma chainE: \"chain Y \\<Longrightarrow> Y i \\<sqsubseteq> Y (Suc i)\"\n  unfolding chain_def by fast\n\ntext \\<open>chains are monotone functions\\<close>\n\nlemma chain_mono_less: \"\\<lbrakk>chain Y; i < j\\<rbrakk> \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (erule less_Suc_induct, erule chainE, erule below_trans)\n\nlemma chain_mono: \"\\<lbrakk>chain Y; i \\<le> j\\<rbrakk> \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (cases \"i = j\", simp, simp add: chain_mono_less)\n\nlemma chain_shift: \"chain Y \\<Longrightarrow> chain (\\<lambda>i. Y (i + j))\"\n  by (rule chainI, simp, erule chainE)\n\ntext \\<open>technical lemmas about (least) upper bounds of chains\\<close>\n\nlemma is_lub_rangeD1: \"range S <<| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  by (rule is_lubD1 [THEN ub_rangeD])\n\nlemma is_ub_range_shift:\n  \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <| x = range S <| x\"\napply (rule iffI)\napply (rule ub_rangeI)\napply (rule_tac y=\"S (i + j)\" in below_trans)\napply (erule chain_mono)\napply (rule le_add1)\napply (erule ub_rangeD)\napply (rule ub_rangeI)\napply (erule ub_rangeD)\ndone\n\nlemma is_lub_range_shift:\n  \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <<| x = range S <<| x\"\n  by (simp add: is_lub_def is_ub_range_shift)\n\ntext \\<open>the lub of a constant chain is the constant\\<close>\n\nlemma chain_const [simp]: \"chain (\\<lambda>i. c)\"\n  by (simp add: chainI)\n\nlemma is_lub_const: \"range (\\<lambda>x. c) <<| c\"\nby (blast dest: ub_rangeD intro: is_lubI ub_rangeI)\n\nlemma lub_const [simp]: \"(\\<Squnion>i. c) = c\"\n  by (rule is_lub_const [THEN lub_eqI])\n\nsubsection \\<open>Finite chains\\<close>\n\ndefinition max_in_chain :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \\<comment> \\<open>finite chains, needed for monotony of continuous functions\\<close>\n  \"max_in_chain i C \\<longleftrightarrow> (\\<forall>j. i \\<le> j \\<longrightarrow> C i = C j)\"\n\ndefinition finite_chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\" where\n  \"finite_chain C = (chain C \\<and> (\\<exists>i. max_in_chain i C))\"\n\ntext \\<open>results about finite chains\\<close>\n\nlemma max_in_chainI: \"(\\<And>j. i \\<le> j \\<Longrightarrow> Y i = Y j) \\<Longrightarrow> max_in_chain i Y\"\n  unfolding max_in_chain_def by fast\n\nlemma max_in_chainD: \"\\<lbrakk>max_in_chain i Y; i \\<le> j\\<rbrakk> \\<Longrightarrow> Y i = Y j\"\n  unfolding max_in_chain_def by fast\n\nlemma finite_chainI:\n  \"\\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> finite_chain C\"\n  unfolding finite_chain_def by fast\n\nlemma finite_chainE:\n  \"\\<lbrakk>finite_chain C; \\<And>i. \\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  unfolding finite_chain_def by fast\n\nlemma lub_finch1: \"\\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> range C <<| C i\"\napply (rule is_lubI)\napply (rule ub_rangeI, rename_tac j)\napply (rule_tac x=i and y=j in linorder_le_cases)\napply (drule (1) max_in_chainD, simp)\napply (erule (1) chain_mono)\napply (erule ub_rangeD)\ndone\n\nlemma lub_finch2:\n  \"finite_chain C \\<Longrightarrow> range C <<| C (LEAST i. max_in_chain i C)\"\napply (erule finite_chainE)\napply (erule LeastI2 [where Q=\"\\<lambda>i. range C <<| C i\"])\napply (erule (1) lub_finch1)\ndone\n\nlemma finch_imp_finite_range: \"finite_chain Y \\<Longrightarrow> finite (range Y)\"\n apply (erule finite_chainE)\n apply (rule_tac B=\"Y ` {..i}\" in finite_subset)\n  apply (rule subsetI)\n  apply (erule rangeE, rename_tac j)\n  apply (rule_tac x=i and y=j in linorder_le_cases)\n   apply (subgoal_tac \"Y j = Y i\", simp)\n   apply (simp add: max_in_chain_def)\n  apply simp\n apply simp\ndone\n\nlemma finite_range_has_max:\n  fixes f :: \"nat \\<Rightarrow> 'a\" and r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes mono: \"\\<And>i j. i \\<le> j \\<Longrightarrow> r (f i) (f j)\"\n  assumes finite_range: \"finite (range f)\"\n  shows \"\\<exists>k. \\<forall>i. r (f i) (f k)\"\nproof (intro exI allI)\n  fix i :: nat\n  let ?j = \"LEAST k. f k = f i\"\n  let ?k = \"Max ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n  have \"?j \\<le> ?k\"\n  proof (rule Max_ge)\n    show \"finite ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n      using finite_range by (rule finite_imageI)\n    show \"?j \\<in> (\\<lambda>x. LEAST k. f k = x) ` range f\"\n      by (intro imageI rangeI)\n  qed\n  hence \"r (f ?j) (f ?k)\"\n    by (rule mono)\n  also have \"f ?j = f i\"\n    by (rule LeastI, rule refl)\n  finally show \"r (f i) (f ?k)\" .\nqed\n\nlemma finite_range_imp_finch:\n  \"\\<lbrakk>chain Y; finite (range Y)\\<rbrakk> \\<Longrightarrow> finite_chain Y\"\n apply (subgoal_tac \"\\<exists>k. \\<forall>i. Y i \\<sqsubseteq> Y k\")\n  apply (erule exE)\n  apply (rule finite_chainI, assumption)\n  apply (rule max_in_chainI)\n  apply (rule below_antisym)\n   apply (erule (1) chain_mono)\n  apply (erule spec)\n apply (rule finite_range_has_max)\n  apply (erule (1) chain_mono)\n apply assumption\ndone\n\nlemma bin_chain: \"x \\<sqsubseteq> y \\<Longrightarrow> chain (\\<lambda>i. if i=0 then x else y)\"\n  by (rule chainI, simp)\n\nlemma bin_chainmax:\n  \"x \\<sqsubseteq> y \\<Longrightarrow> max_in_chain (Suc 0) (\\<lambda>i. if i=0 then x else y)\"\n  unfolding max_in_chain_def by simp\n\nlemma is_lub_bin_chain:\n  \"x \\<sqsubseteq> y \\<Longrightarrow> range (\\<lambda>i::nat. if i=0 then x else y) <<| y\"\napply (frule bin_chain)\napply (drule bin_chainmax)\napply (drule (1) lub_finch1)\napply simp\ndone\n\ntext \\<open>the maximal element in a chain is its lub\\<close>\n\nlemma lub_chain_maxelem: \"\\<lbrakk>Y i = c; \\<forall>i. Y i \\<sqsubseteq> c\\<rbrakk> \\<Longrightarrow> lub (range Y) = c\"\n  by (blast dest: ub_rangeD intro: lub_eqI is_lubI ub_rangeI)\n\nend\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/HOLCF/Porder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8705972650509008, "lm_q2_score": 0.865224084314688, "lm_q1q2_score": 0.7532617214605374}}
{"text": "(*  Title:      HOL/HOLCF/Porder.thy\n    Author:     Franz Regensburger and Brian Huffman\n*)\n\nsection \\<open>Partial orders\\<close>\n\ntheory Porder\n  imports Main\nbegin\n\ndeclare [[typedef_overloaded]]\n\n\nsubsection \\<open>Type class for partial orders\\<close>\n\nclass below =\n  fixes below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\nbegin\n\nnotation (ASCII)\n  below (infix \"<<\" 50)\n\nnotation\n  below (infix \"\\<sqsubseteq>\" 50)\n\nabbreviation not_below :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infix \"\\<notsqsubseteq>\" 50)\n  where \"not_below x y \\<equiv> \\<not> below x y\"\n\nnotation (ASCII)\n  not_below  (infix \"~<<\" 50)\n\nlemma below_eq_trans: \"a \\<sqsubseteq> b \\<Longrightarrow> b = c \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule subst)\n\nlemma eq_below_trans: \"a = b \\<Longrightarrow> b \\<sqsubseteq> c \\<Longrightarrow> a \\<sqsubseteq> c\"\n  by (rule ssubst)\n\nend\n\nclass po = below +\n  assumes below_refl [iff]: \"x \\<sqsubseteq> x\"\n  assumes below_trans: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> z\"\n  assumes below_antisym: \"x \\<sqsubseteq> y \\<Longrightarrow> y \\<sqsubseteq> x \\<Longrightarrow> x = y\"\nbegin\n\nlemma eq_imp_below: \"x = y \\<Longrightarrow> x \\<sqsubseteq> y\"\n  by simp\n\nlemma box_below: \"a \\<sqsubseteq> b \\<Longrightarrow> c \\<sqsubseteq> a \\<Longrightarrow> b \\<sqsubseteq> d \\<Longrightarrow> c \\<sqsubseteq> d\"\n  by (rule below_trans [OF below_trans])\n\nlemma po_eq_conv: \"x = y \\<longleftrightarrow> x \\<sqsubseteq> y \\<and> y \\<sqsubseteq> x\"\n  by (fast intro!: below_antisym)\n\nlemma rev_below_trans: \"y \\<sqsubseteq> z \\<Longrightarrow> x \\<sqsubseteq> y \\<Longrightarrow> x \\<sqsubseteq> z\"\n  by (rule below_trans)\n\nlemma not_below2not_eq: \"x \\<notsqsubseteq> y \\<Longrightarrow> x \\<noteq> y\"\n  by auto\n\nend\n\nlemmas HOLCF_trans_rules [trans] =\n  below_trans\n  below_antisym\n  below_eq_trans\n  eq_below_trans\n\ncontext po\nbegin\n\nsubsection \\<open>Upper bounds\\<close>\n\ndefinition is_ub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<|\" 55)\n  where \"S <| x \\<longleftrightarrow> (\\<forall>y\\<in>S. y \\<sqsubseteq> x)\"\n\nlemma is_ubI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> x \\<sqsubseteq> u) \\<Longrightarrow> S <| u\"\n  by (simp add: is_ub_def)\n\nlemma is_ubD: \"\\<lbrakk>S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  by (simp add: is_ub_def)\n\nlemma ub_imageI: \"(\\<And>x. x \\<in> S \\<Longrightarrow> f x \\<sqsubseteq> u) \\<Longrightarrow> (\\<lambda>x. f x) ` S <| u\"\n  unfolding is_ub_def by fast\n\nlemma ub_imageD: \"\\<lbrakk>f ` S <| u; x \\<in> S\\<rbrakk> \\<Longrightarrow> f x \\<sqsubseteq> u\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeI: \"(\\<And>i. S i \\<sqsubseteq> x) \\<Longrightarrow> range S <| x\"\n  unfolding is_ub_def by fast\n\nlemma ub_rangeD: \"range S <| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_empty [simp]: \"{} <| u\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_insert [simp]: \"(insert x A) <| y = (x \\<sqsubseteq> y \\<and> A <| y)\"\n  unfolding is_ub_def by fast\n\nlemma is_ub_upward: \"\\<lbrakk>S <| x; x \\<sqsubseteq> y\\<rbrakk> \\<Longrightarrow> S <| y\"\n  unfolding is_ub_def by (fast intro: below_trans)\n\n\nsubsection \\<open>Least upper bounds\\<close>\n\ndefinition is_lub :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> bool\" (infix \"<<|\" 55)\n  where \"S <<| x \\<longleftrightarrow> S <| x \\<and> (\\<forall>u. S <| u \\<longrightarrow> x \\<sqsubseteq> u)\"\n\ndefinition lub :: \"'a set \\<Rightarrow> 'a\"\n  where \"lub S = (THE x. S <<| x)\"\n\nend\n\nsyntax (ASCII)\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3LUB _:_./ _)\" [0,0, 10] 10)\n\nsyntax\n  \"_BLub\" :: \"[pttrn, 'a set, 'b] \\<Rightarrow> 'b\" (\"(3\\<Squnion>_\\<in>_./ _)\" [0,0, 10] 10)\n\ntranslations\n  \"LUB x:A. t\" \\<rightleftharpoons> \"CONST lub ((\\<lambda>x. t) ` A)\"\n\ncontext po\nbegin\n\nabbreviation Lub  (binder \"\\<Squnion>\" 10)\n  where \"\\<Squnion>n. t n \\<equiv> lub (range t)\"\n\nnotation (ASCII)\n  Lub  (binder \"LUB \" 10)\n\ntext \\<open>access to some definition as inference rule\\<close>\n\nlemma is_lubD1: \"S <<| x \\<Longrightarrow> S <| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lubD2: \"\\<lbrakk>S <<| x; S <| u\\<rbrakk> \\<Longrightarrow> x \\<sqsubseteq> u\"\n  unfolding is_lub_def by fast\n\nlemma is_lubI: \"\\<lbrakk>S <| x; \\<And>u. S <| u \\<Longrightarrow> x \\<sqsubseteq> u\\<rbrakk> \\<Longrightarrow> S <<| x\"\n  unfolding is_lub_def by fast\n\nlemma is_lub_below_iff: \"S <<| x \\<Longrightarrow> x \\<sqsubseteq> u \\<longleftrightarrow> S <| u\"\n  unfolding is_lub_def is_ub_def by (metis below_trans)\n\ntext \\<open>lubs are unique\\<close>\n\nlemma is_lub_unique: \"S <<| x \\<Longrightarrow> S <<| y \\<Longrightarrow> x = y\"\n  unfolding is_lub_def is_ub_def by (blast intro: below_antisym)\n\ntext \\<open>technical lemmas about \\<^term>\\<open>lub\\<close> and \\<^term>\\<open>is_lub\\<close>\\<close>\n\nlemma is_lub_lub: \"M <<| x \\<Longrightarrow> M <<| lub M\"\n  unfolding lub_def by (rule theI [OF _ is_lub_unique])\n\nlemma lub_eqI: \"M <<| l \\<Longrightarrow> lub M = l\"\n  by (rule is_lub_unique [OF is_lub_lub])\n\nlemma is_lub_singleton [simp]: \"{x} <<| x\"\n  by (simp add: is_lub_def)\n\nlemma lub_singleton [simp]: \"lub {x} = x\"\n  by (rule is_lub_singleton [THEN lub_eqI])\n\nlemma is_lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> {x, y} <<| y\"\n  by (simp add: is_lub_def)\n\nlemma lub_bin: \"x \\<sqsubseteq> y \\<Longrightarrow> lub {x, y} = y\"\n  by (rule is_lub_bin [THEN lub_eqI])\n\nlemma is_lub_maximal: \"S <| x \\<Longrightarrow> x \\<in> S \\<Longrightarrow> S <<| x\"\n  by (erule is_lubI, erule (1) is_ubD)\n\nlemma lub_maximal: \"S <| x \\<Longrightarrow> x \\<in> S \\<Longrightarrow> lub S = x\"\n  by (rule is_lub_maximal [THEN lub_eqI])\n\n\nsubsection \\<open>Countable chains\\<close>\n\ndefinition chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \\<comment> \\<open>Here we use countable chains and I prefer to code them as functions!\\<close>\n  \"chain Y = (\\<forall>i. Y i \\<sqsubseteq> Y (Suc i))\"\n\nlemma chainI: \"(\\<And>i. Y i \\<sqsubseteq> Y (Suc i)) \\<Longrightarrow> chain Y\"\n  unfolding chain_def by fast\n\nlemma chainE: \"chain Y \\<Longrightarrow> Y i \\<sqsubseteq> Y (Suc i)\"\n  unfolding chain_def by fast\n\ntext \\<open>chains are monotone functions\\<close>\n\nlemma chain_mono_less: \"chain Y \\<Longrightarrow> i < j \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (erule less_Suc_induct, erule chainE, erule below_trans)\n\nlemma chain_mono: \"chain Y \\<Longrightarrow> i \\<le> j \\<Longrightarrow> Y i \\<sqsubseteq> Y j\"\n  by (cases \"i = j\") (simp_all add: chain_mono_less)\n\nlemma chain_shift: \"chain Y \\<Longrightarrow> chain (\\<lambda>i. Y (i + j))\"\n  by (rule chainI, simp, erule chainE)\n\ntext \\<open>technical lemmas about (least) upper bounds of chains\\<close>\n\nlemma is_lub_rangeD1: \"range S <<| x \\<Longrightarrow> S i \\<sqsubseteq> x\"\n  by (rule is_lubD1 [THEN ub_rangeD])\n\nlemma is_ub_range_shift: \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <| x = range S <| x\"\n  apply (rule iffI)\n   apply (rule ub_rangeI)\n   apply (rule_tac y=\"S (i + j)\" in below_trans)\n    apply (erule chain_mono)\n    apply (rule le_add1)\n   apply (erule ub_rangeD)\n  apply (rule ub_rangeI)\n  apply (erule ub_rangeD)\n  done\n\nlemma is_lub_range_shift: \"chain S \\<Longrightarrow> range (\\<lambda>i. S (i + j)) <<| x = range S <<| x\"\n  by (simp add: is_lub_def is_ub_range_shift)\n\ntext \\<open>the lub of a constant chain is the constant\\<close>\n\nlemma chain_const [simp]: \"chain (\\<lambda>i. c)\"\n  by (simp add: chainI)\n\nlemma is_lub_const: \"range (\\<lambda>x. c) <<| c\"\nby (blast dest: ub_rangeD intro: is_lubI ub_rangeI)\n\nlemma lub_const [simp]: \"(\\<Squnion>i. c) = c\"\n  by (rule is_lub_const [THEN lub_eqI])\n\n\nsubsection \\<open>Finite chains\\<close>\n\ndefinition max_in_chain :: \"nat \\<Rightarrow> (nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \\<comment> \\<open>finite chains, needed for monotony of continuous functions\\<close>\n  \"max_in_chain i C \\<longleftrightarrow> (\\<forall>j. i \\<le> j \\<longrightarrow> C i = C j)\"\n\ndefinition finite_chain :: \"(nat \\<Rightarrow> 'a) \\<Rightarrow> bool\"\n  where \"finite_chain C = (chain C \\<and> (\\<exists>i. max_in_chain i C))\"\n\ntext \\<open>results about finite chains\\<close>\n\nlemma max_in_chainI: \"(\\<And>j. i \\<le> j \\<Longrightarrow> Y i = Y j) \\<Longrightarrow> max_in_chain i Y\"\n  unfolding max_in_chain_def by fast\n\nlemma max_in_chainD: \"max_in_chain i Y \\<Longrightarrow> i \\<le> j \\<Longrightarrow> Y i = Y j\"\n  unfolding max_in_chain_def by fast\n\nlemma finite_chainI: \"chain C \\<Longrightarrow> max_in_chain i C \\<Longrightarrow> finite_chain C\"\n  unfolding finite_chain_def by fast\n\nlemma finite_chainE: \"\\<lbrakk>finite_chain C; \\<And>i. \\<lbrakk>chain C; max_in_chain i C\\<rbrakk> \\<Longrightarrow> R\\<rbrakk> \\<Longrightarrow> R\"\n  unfolding finite_chain_def by fast\n\nlemma lub_finch1: \"chain C \\<Longrightarrow> max_in_chain i C \\<Longrightarrow> range C <<| C i\"\n  apply (rule is_lubI)\n   apply (rule ub_rangeI, rename_tac j)\n   apply (rule_tac x=i and y=j in linorder_le_cases)\n    apply (drule (1) max_in_chainD, simp)\n   apply (erule (1) chain_mono)\n  apply (erule ub_rangeD)\n  done\n\nlemma lub_finch2: \"finite_chain C \\<Longrightarrow> range C <<| C (LEAST i. max_in_chain i C)\"\n  apply (erule finite_chainE)\n  apply (erule LeastI2 [where Q=\"\\<lambda>i. range C <<| C i\"])\n  apply (erule (1) lub_finch1)\n  done\n\nlemma finch_imp_finite_range: \"finite_chain Y \\<Longrightarrow> finite (range Y)\"\n  apply (erule finite_chainE)\n  apply (rule_tac B=\"Y ` {..i}\" in finite_subset)\n   apply (rule subsetI)\n   apply (erule rangeE, rename_tac j)\n   apply (rule_tac x=i and y=j in linorder_le_cases)\n    apply (subgoal_tac \"Y j = Y i\", simp)\n    apply (simp add: max_in_chain_def)\n   apply simp\n  apply simp\n  done\n\nlemma finite_range_has_max:\n  fixes f :: \"nat \\<Rightarrow> 'a\"\n    and r :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"\n  assumes mono: \"\\<And>i j. i \\<le> j \\<Longrightarrow> r (f i) (f j)\"\n  assumes finite_range: \"finite (range f)\"\n  shows \"\\<exists>k. \\<forall>i. r (f i) (f k)\"\nproof (intro exI allI)\n  fix i :: nat\n  let ?j = \"LEAST k. f k = f i\"\n  let ?k = \"Max ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n  have \"?j \\<le> ?k\"\n  proof (rule Max_ge)\n    show \"finite ((\\<lambda>x. LEAST k. f k = x) ` range f)\"\n      using finite_range by (rule finite_imageI)\n    show \"?j \\<in> (\\<lambda>x. LEAST k. f k = x) ` range f\"\n      by (intro imageI rangeI)\n  qed\n  hence \"r (f ?j) (f ?k)\"\n    by (rule mono)\n  also have \"f ?j = f i\"\n    by (rule LeastI, rule refl)\n  finally show \"r (f i) (f ?k)\" .\nqed\n\nlemma finite_range_imp_finch: \"chain Y \\<Longrightarrow> finite (range Y) \\<Longrightarrow> finite_chain Y\"\n  apply (subgoal_tac \"\\<exists>k. \\<forall>i. Y i \\<sqsubseteq> Y k\")\n   apply (erule exE)\n   apply (rule finite_chainI, assumption)\n   apply (rule max_in_chainI)\n   apply (rule below_antisym)\n    apply (erule (1) chain_mono)\n   apply (erule spec)\n  apply (rule finite_range_has_max)\n   apply (erule (1) chain_mono)\n  apply assumption\n  done\n\nlemma bin_chain: \"x \\<sqsubseteq> y \\<Longrightarrow> chain (\\<lambda>i. if i=0 then x else y)\"\n  by (rule chainI) simp\n\nlemma bin_chainmax: \"x \\<sqsubseteq> y \\<Longrightarrow> max_in_chain (Suc 0) (\\<lambda>i. if i=0 then x else y)\"\n  by (simp add: max_in_chain_def)\n\nlemma is_lub_bin_chain: \"x \\<sqsubseteq> y \\<Longrightarrow> range (\\<lambda>i::nat. if i=0 then x else y) <<| y\"\n  apply (frule bin_chain)\n  apply (drule bin_chainmax)\n  apply (drule (1) lub_finch1)\n  apply simp\n  done\n\ntext \\<open>the maximal element in a chain is its lub\\<close>\n\nlemma lub_chain_maxelem: \"Y i = c \\<Longrightarrow> \\<forall>i. Y i \\<sqsubseteq> c \\<Longrightarrow> lub (range Y) = c\"\n  by (blast dest: ub_rangeD intro: lub_eqI is_lubI ub_rangeI)\n\nend\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/HOLCF/Porder.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8705972583359805, "lm_q1q2_score": 0.7532617201889928}}
{"text": "(*  Title:      FOL/ex/Propositional_Cla.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1991  University of Cambridge\n*)\n\nsection \\<open>First-Order Logic: propositional examples (classical version)\\<close>\n\ntheory Propositional_Cla\nimports FOL\nbegin\n\ntext \\<open>commutative laws of \\<open>\\<and>\\<close> and \\<open>\\<or>\\<close>\\<close>\n\nlemma \"P \\<and> Q \\<longrightarrow> Q \\<and> P\"\n  by (tactic \"IntPr.fast_tac @{context} 1\")\n\nlemma \"P \\<or> Q \\<longrightarrow> Q \\<or> P\"\n  by fast\n\n\ntext \\<open>associative laws of \\<open>\\<and>\\<close> and \\<open>\\<or>\\<close>\\<close>\nlemma \"(P \\<and> Q) \\<and> R \\<longrightarrow> P \\<and> (Q \\<and> R)\"\n  by fast\n\nlemma \"(P \\<or> Q) \\<or> R \\<longrightarrow>  P \\<or> (Q \\<or> R)\"\n  by fast\n\n\ntext \\<open>distributive laws of \\<open>\\<and>\\<close> and \\<open>\\<or>\\<close>\\<close>\nlemma \"(P \\<and> Q) \\<or> R \\<longrightarrow> (P \\<or> R) \\<and> (Q \\<or> R)\"\n  by fast\n\nlemma \"(P \\<or> R) \\<and> (Q \\<or> R) \\<longrightarrow> (P \\<and> Q) \\<or> R\"\n  by fast\n\nlemma \"(P \\<or> Q) \\<and> R \\<longrightarrow> (P \\<and> R) \\<or> (Q \\<and> R)\"\n  by fast\n\nlemma \"(P \\<and> R) \\<or> (Q \\<and> R) \\<longrightarrow> (P \\<or> Q) \\<and> R\"\n  by fast\n\n\ntext \\<open>Laws involving implication\\<close>\n\nlemma \"(P \\<longrightarrow> R) \\<and> (Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<or> Q \\<longrightarrow> R)\"\n  by fast\n\nlemma \"(P \\<and> Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<longrightarrow> (Q \\<longrightarrow> R))\"\n  by fast\n\nlemma \"((P \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> ((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> (P \\<and> Q \\<longrightarrow> R) \\<longrightarrow> R\"\n  by fast\n\nlemma \"\\<not> (P \\<longrightarrow> R) \\<longrightarrow> \\<not> (Q \\<longrightarrow> R) \\<longrightarrow> \\<not> (P \\<and> Q \\<longrightarrow> R)\"\n  by fast\n\nlemma \"(P \\<longrightarrow> Q \\<and> R) \\<longleftrightarrow> (P \\<longrightarrow> Q) \\<and> (P \\<longrightarrow> R)\"\n  by fast\n\n\ntext \\<open>Propositions-as-types\\<close>\n\n\\<comment> \\<open>The combinator K\\<close>\nlemma \"P \\<longrightarrow> (Q \\<longrightarrow> P)\"\n  by fast\n\n\\<comment> \\<open>The combinator S\\<close>\nlemma \"(P \\<longrightarrow> Q \\<longrightarrow> R) \\<longrightarrow> (P \\<longrightarrow> Q) \\<longrightarrow> (P \\<longrightarrow> R)\"\n  by fast\n\n\n\\<comment> \\<open>Converse is classical\\<close>\nlemma \"(P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R) \\<longrightarrow> (P \\<longrightarrow> Q \\<or> R)\"\n  by fast\n\nlemma \"(P \\<longrightarrow> Q) \\<longrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\"\n  by fast\n\n\ntext \\<open>Schwichtenberg's examples (via T. Nipkow)\\<close>\n\nlemma stab_imp: \"(((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> Q) \\<longrightarrow> (((P \\<longrightarrow> Q) \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> P \\<longrightarrow> Q\"\n  by fast\n\nlemma stab_to_peirce:\n  \"(((P \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> P) \\<longrightarrow> (((Q \\<longrightarrow> R) \\<longrightarrow> R) \\<longrightarrow> Q)\n    \\<longrightarrow> ((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P\"\n  by fast\n\nlemma peirce_imp1:\n  \"(((Q \\<longrightarrow> R) \\<longrightarrow> Q) \\<longrightarrow> Q)\n    \\<longrightarrow> (((P \\<longrightarrow> Q) \\<longrightarrow> R) \\<longrightarrow> P \\<longrightarrow> Q) \\<longrightarrow> P \\<longrightarrow> Q\"\n  by fast\n\nlemma peirce_imp2: \"(((P \\<longrightarrow> R) \\<longrightarrow> P) \\<longrightarrow> P) \\<longrightarrow> ((P \\<longrightarrow> Q \\<longrightarrow> R) \\<longrightarrow> P) \\<longrightarrow> P\"\n  by fast\n\nlemma mints: \"((((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P) \\<longrightarrow> Q) \\<longrightarrow> Q\"\n  by fast\n\nlemma mints_solovev: \"(P \\<longrightarrow> (Q \\<longrightarrow> R) \\<longrightarrow> Q) \\<longrightarrow> ((P \\<longrightarrow> Q) \\<longrightarrow> R) \\<longrightarrow> R\"\n  by fast\n\nlemma tatsuta:\n  \"(((P7 \\<longrightarrow> P1) \\<longrightarrow> P10) \\<longrightarrow> P4 \\<longrightarrow> P5)\n  \\<longrightarrow> (((P8 \\<longrightarrow> P2) \\<longrightarrow> P9) \\<longrightarrow> P3 \\<longrightarrow> P10)\n  \\<longrightarrow> (P1 \\<longrightarrow> P8) \\<longrightarrow> P6 \\<longrightarrow> P7\n  \\<longrightarrow> (((P3 \\<longrightarrow> P2) \\<longrightarrow> P9) \\<longrightarrow> P4)\n  \\<longrightarrow> (P1 \\<longrightarrow> P3) \\<longrightarrow> (((P6 \\<longrightarrow> P1) \\<longrightarrow> P2) \\<longrightarrow> P9) \\<longrightarrow> P5\"\n  by fast\n\nlemma tatsuta1:\n  \"(((P8 \\<longrightarrow> P2) \\<longrightarrow> P9) \\<longrightarrow> P3 \\<longrightarrow> P10)\n  \\<longrightarrow> (((P3 \\<longrightarrow> P2) \\<longrightarrow> P9) \\<longrightarrow> P4)\n  \\<longrightarrow> (((P6 \\<longrightarrow> P1) \\<longrightarrow> P2) \\<longrightarrow> P9)\n  \\<longrightarrow> (((P7 \\<longrightarrow> P1) \\<longrightarrow> P10) \\<longrightarrow> P4 \\<longrightarrow> P5)\n  \\<longrightarrow> (P1 \\<longrightarrow> P3) \\<longrightarrow> (P1 \\<longrightarrow> P8) \\<longrightarrow> P6 \\<longrightarrow> P7 \\<longrightarrow> P5\"\n  by fast\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/FOL/ex/Propositional_Cla.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.8418256432832333, "lm_q1q2_score": 0.7532567226285338}}
{"text": "theory P22 imports Main begin\n\ndatatype bdd = Leaf bool | Branch bdd bdd\n\nprimrec eval :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> bdd \\<Rightarrow> bool\" where\n\"eval p i (Leaf b) = b\" |\n\"eval p i (Branch b1 b2) = (if (p i) then (eval p (i+1) b2) else (eval p (i+1) b1))\"\n\nprimrec bdd_unop :: \"(bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n\"bdd_unop f (Leaf b) = (Leaf (f b))\" |\n\"bdd_unop f (Branch b1 b2) = (Branch (bdd_unop f b1) (bdd_unop f b2))\"\n\nprimrec bdd_binop :: \"(bool \\<Rightarrow> bool \\<Rightarrow> bool) \\<Rightarrow> bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n\"bdd_binop f (Leaf b) c = bdd_unop (f b) c\" |\n\"bdd_binop f (Branch b1 b2) c = (case c of\n  Leaf x \\<Rightarrow> Branch (bdd_binop f b1 (Leaf x)) (bdd_binop f b2 (Leaf x)) |\n  Branch x1 x2 \\<Rightarrow> Branch (bdd_binop f b1 x1) (bdd_binop f b2 x2))\"\n\ntheorem bdd_unop_correctness : \"\\<forall>i. eval g i (bdd_unop f b) = f (eval g i b)\"\n  apply (induct b)\n  apply auto\n  done\n\ntheorem bdd_binop_correctness : \"\\<forall>i. eval g i (bdd_binop f b1 b2) = f (eval g i b1) (eval g i b2)\"\n  apply (induct b1 arbitrary: b2)\n   apply (auto simp add: bdd_unop_correctness)\n     apply (case_tac b2)\n      apply auto\n     apply (case_tac b2)\n      apply auto\n     apply (case_tac b2)\n  apply auto\n     apply (case_tac b2)\n      apply auto\n  done\n\ndefinition bdd_and:: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n\"bdd_and \\<equiv> bdd_binop (\\<and>)\"\n\ndefinition bdd_or:: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n\"bdd_or \\<equiv> bdd_binop (\\<or>)\"\n\ndefinition bdd_not:: \"bdd \\<Rightarrow> bdd\" where\n\"bdd_not \\<equiv> bdd_unop (Not)\"\n\ndefinition bdd_xor:: \"bdd \\<Rightarrow> bdd \\<Rightarrow> bdd\" where\n\"bdd_xor \\<equiv> bdd_binop (\\<lambda>x y. (x \\<and> (\\<not> y)) \\<or> (\\<not>x \\<and> y))\"\n\nlemma bdd_and_correctness: \"eval p i (bdd_and b1 b2) = (eval p i b1 \\<and> eval p i b2)\"\n  apply (auto simp add: bdd_and_def bdd_binop_correctness)\n  done\n\nlemma bdd_or_correctness: \"eval p i (bdd_or b1 b2) = (eval p i b1 \\<or> eval p i b2)\"\n  apply (auto simp add: bdd_or_def bdd_binop_correctness)\n  done\n\nlemma bdd_not_correctness: \"eval p i (bdd_not b) = (\\<not> (eval p i b))\"\n  apply (auto simp add: bdd_not_def bdd_unop_correctness)\n  done\n\nlemma bdd_xor_correctness: \n\"eval p i (bdd_xor b1 b2) = (eval p i b1 \\<and> (\\<not> eval p i b2)) \\<or> (\\<not> eval p i b1 \\<and> eval p i b2)\"\n  apply (auto simp add: bdd_xor_def bdd_binop_correctness)\n  done\n\nfun bdd_var :: \"nat \\<Rightarrow> bdd\" where\n  \"bdd_var 0 = (Branch (Leaf False) (Leaf True))\" |\n  \"bdd_var (Suc n) = (Branch (bdd_var n) (bdd_var n))\"\n\ntheorem bdd_var_correctness:\"\\<forall>n. eval p n (bdd_var m) = p (m+n)\"\n  apply (induct m)\n  apply auto\n  done\n\ndatatype form = T | Var nat | And form form | Xor form form\n\ndefinition xor :: \"bool \\<Rightarrow> bool \\<Rightarrow> bool\" where\n  \"xor x y \\<equiv> (x \\<and> \\<not> y) \\<or> (\\<not> x \\<and> y)\"\n\nprimrec evalf :: \"(nat \\<Rightarrow> bool) \\<Rightarrow> form \\<Rightarrow> bool\" where\n  \"evalf e T = True\"\n  | \"evalf e (Var i) = e i\"\n  | \"evalf e (And f1 f2) = (evalf e f1 \\<and> evalf e f2)\"\n  | \"evalf e (Xor f1 f2) = xor (evalf e f1) (evalf e f2)\"\n\nfun mk_bdd :: \"form \\<Rightarrow> bdd\" where\n\"mk_bdd T = Leaf True\" |\n\"mk_bdd (Var i) = bdd_var i\" |\n\"mk_bdd (And f1 f2) = bdd_and (mk_bdd f1) (mk_bdd f2)\" |\n\"mk_bdd (Xor f1 f2) = bdd_xor (mk_bdd f1) (mk_bdd f2)\"\n\ntheorem mk_bdd_correct: \"eval e 0 (mk_bdd f) = evalf e f\"\n  apply (induct f)\n  using bdd_xor_correctness bdd_xor_def apply auto[1]\n  apply (simp add: bdd_var_correctness)\n  apply (simp add: bdd_and_correctness)\n  apply (simp add: bdd_binop_correctness bdd_xor_def xor_def)\n  done\n\nend", "meta": {"author": "albertqjiang", "repo": "Isa100days", "sha": "a8e1069390243033f993328421526d2ff077d1ca", "save_path": "github-repos/isabelle/albertqjiang-Isa100days", "path": "github-repos/isabelle/albertqjiang-Isa100days/Isa100days-a8e1069390243033f993328421526d2ff077d1ca/P22.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.8221891261650248, "lm_q1q2_score": 0.7532153607853288}}
{"text": "(* Property from Case-Analysis for Rippling and Inductive Proof, \n   Moa Johansson, Lucas Dixon and Alan Bundy, ITP 2010. \n   This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n   Some proofs were added by Yutaka Nagashima.*)\ntheory TIP_prop_29\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun x :: \"Nat => Nat => bool\" where\n  \"x (Z) (Z) = True\"\n| \"x (Z) (S z2) = False\"\n| \"x (S x2) (Z) = False\"\n| \"x (S x2) (S y2) = x x2 y2\"\n\nfun ins1 :: \"Nat => Nat list => Nat list\" where\n  \"ins1 y (nil2) = cons2 y (nil2)\"\n| \"ins1 y (cons2 z2 xs) =\n     (if x y z2 then cons2 z2 xs else cons2 z2 (ins1 y xs))\"\n\nfun elem :: \"Nat => Nat list => bool\" where\n  \"elem y (nil2) = False\"\n| \"elem y (cons2 z2 xs) = (if x y z2 then True else elem y xs)\"\n\ntheorem property0 :\n  \"elem y (ins1 y xs)\"\n  (*\"arbitrary:y\" also works well.*)\n  apply(induct xs (*arbitrary: y*))\n   apply clarsimp\n   apply(induct_tac y)\n  by auto\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/Isaplanner/Isaplanner/TIP_prop_29.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.8289388040954684, "lm_q1q2_score": 0.7531886410681704}}
{"text": "theory List_Demo\nimports Main\nbegin\n\ndatatype 'a list = Nil | Cons \"'a\" \"'a list\"\n\nterm \"Nil\"\n\ndeclare [[names_short]]\n\nfun app :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"app Nil ys = ys\" |\n\"app (Cons x xs) ys = Cons x (app xs ys)\"\n\nfun rev :: \"'a list \\<Rightarrow> 'a list\" where\n\"rev Nil = Nil\" |\n\"rev (Cons x xs) = app (rev xs) (Cons x Nil)\"\n\nvalue \"rev(Cons True (Cons False Nil))\"\n\nvalue \"rev(Cons a (Cons b Nil))\"\n\n\nlemma app_Nil2[simp]: \"app xs Nil = xs\"\napply (induction xs)\napply auto\ndone\n\nlemma app_assoc[simp]: \"app (app xs ys) zs = app xs (app ys zs)\"\napply (induction xs)\napply auto\ndone\n\nlemma rev_app[simp]: \"rev (app xs ys) = app (rev ys) (rev xs)\"\napply (induction xs)\napply auto\ndone\n\ntheorem rev_rev[simp]: \"rev (rev xs) = xs\"\napply (induction xs)\napply auto\ndone\n\n(* Hint for demo:\n   do the proof top down, discovering the lemmas one by one,\n*)\n\nend\n", "meta": {"author": "david-wang-0", "repo": "concrete-semantics", "sha": "master", "save_path": "github-repos/isabelle/david-wang-0-concrete-semantics", "path": "github-repos/isabelle/david-wang-0-concrete-semantics/concrete-semantics-main/Demos/Complete/List_Demo.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8289388019824946, "lm_q1q2_score": 0.7531886350458188}}
{"text": "(*  Title:       Executable Transitive Closures of Finite Relations\n    Author:      Christian Sternagel <c.sternagel@gmail.com>\n                 René Thiemann       <rene.thiemann@uibk.ac.at>\n    Maintainer:  Christian Sternagel and René Thiemann\n    License:     LGPL\n*)\n\nheader \\<open>A Generic Work-List Algorithm\\<close>\n\ntheory Transitive_Closure_Impl\nimports Main\nbegin\n\ntext \\<open>\n  Let @{term R} be some finite relation. We start to present a standard work-list algorithm to\n  compute all elements that are reachable from some initial set by at most @{term n} @{term\n  R}-steps. Then, we obtain algorithms for the (reflexive) transitive closure from a given starting\n  set by exploiting the fact that for finite relations we have to iterate at most @{term \"card R\"}\n  times. The presented algorithms are generic in the sense that the underlying data structure can\n  freely be chosen, you just have to provide certain operations like union, membership, etc.\n\\<close>\n\nsubsection \\<open>Bounded Reachability\\<close>\n\ntext \\<open>\n  We provide an algorithm @{text relpow_impl} that computes all states that are reachable from an\n  initial set of states @{term new} by at most @{term n} steps. The algorithm also stores a set of\n  states that have already been visited @{term have}, and then show, do not have to be expanded a\n  second time. The algorithm is parametric in the underlying data structure, it just requires\n  operations for union and membership as well as a function to compute the successors of a list.\n\\<close>\nfun\n  relpow_impl ::\n    \"('a list \\<Rightarrow> 'a list) \\<Rightarrow>\n      ('a list \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> 'b \\<Rightarrow> nat \\<Rightarrow> 'b\"\nwhere\n  \"relpow_impl succ un memb new have 0 = un new have\" |\n  \"relpow_impl succ un memb new have (Suc m) =\n    (if new = [] then have\n    else\n      let\n        maybe = succ new;\n        have' = un new have;\n        new' = filter (\\<lambda> n. \\<not> memb n have') maybe\n      in relpow_impl succ un memb new' have' m)\"\n\ntext \\<open>\n  We need to know that the provided operations behave correctly.\n\\<close>\n\nlocale set_access =\n  fixes un :: \"'a list \\<Rightarrow> 'b \\<Rightarrow> 'b\"\n    and set_of :: \"'b \\<Rightarrow> 'a set\"\n    and memb :: \"'a \\<Rightarrow> 'b \\<Rightarrow> bool\"\n    and empty :: 'b\n  assumes un: \"set_of (un as bs) = set as \\<union> set_of bs\"\n    and memb: \"memb a bs \\<longleftrightarrow> (a \\<in> set_of bs)\"\n    and empty: \"set_of empty = {}\"\n\nlocale set_access_succ = set_access un \n  for un :: \"'a list \\<Rightarrow> 'b \\<Rightarrow> 'b\" +\n  fixes succ :: \"'a list \\<Rightarrow> 'a list\"\n   and  rel :: \"('a \\<times> 'a) set\"\n  assumes succ: \"set (succ as) = {b. \\<exists> a \\<in> set as. (a, b) \\<in> rel}\"\nbegin\n\nabbreviation \"relpow_i \\<equiv> relpow_impl succ un memb\"\n\ntext \\<open>\n  What follows is the main technical result of the @{const relpow_impl} algorithm: what it computes\n  for arbitrary values of @{term new} and @{term have}.\n\\<close>\n\nlemma relpow_impl_main: \n  \"set_of (relpow_i new have n) = \n    {b | a b m. a \\<in> set new \\<and> m \\<le> n \\<and> (a, b) \\<in> (rel \\<inter> {(a, b). b \\<notin> set_of have}) ^^ m} \\<union>\n    set_of have\"\n  (is \"?l new have n = ?r new have n\")\nproof (induction n arbitrary: \"have\" new)\n  case (Suc n hhave nnew)\n  show ?case\n  proof (cases \"nnew = []\")\n    case True\n    then show ?thesis by auto\n  next\n    case False\n    let ?have = \"set_of hhave\"\n    let ?new = \"set nnew\"\n    obtain \"have\" new where hav: \"have = ?have\" and new: \"new = ?new\" by auto\n    let ?reln = \"\\<lambda> m. (rel \\<inter> {(a, b). b \\<notin> new \\<and> b \\<notin> have}) ^^  m\"\n    let ?rel = \"\\<lambda> m. (rel \\<inter> {(a, b). b \\<notin> have}) ^^  m\"\n    have idl: \"?l nnew hhave (Suc n) = \n      {uu. \\<exists>a. (\\<exists>aa\\<in> new. (aa,a) \\<in> rel) \\<and> a \\<notin> new \\<and> a \\<notin> have \\<and> (\\<exists>m \\<le> n. (a, uu) \\<in> ?reln m)} \\<union>\n      (new \\<union> have)\"\n      (is \"_ = ?l1 \\<union> (?l2 \\<union> ?l3)\")\n      by (simp add: hav new False Let_def Suc, simp add: memb un succ)\n    let ?l = \"?l1 \\<union> (?l2 \\<union> ?l3)\"\n    have idr: \"?r nnew hhave (Suc n) = {b. \\<exists> a m. a \\<in> new \\<and> m \\<le> Suc n \\<and> (a, b) \\<in> ?rel m} \\<union> have\"\n      (is \"_ = (?r1 \\<union> ?r2)\") by (simp add: hav new)\n    let ?r = \"?r1 \\<union> ?r2\"\n    {\n      fix b\n      assume b: \"b \\<in> ?l\"      \n      have \"b \\<in> ?r\" \n      proof (cases \"b \\<in> new \\<or> b \\<in> have\")\n        case True then show ?thesis \n        proof\n          assume \"b \\<in> have\" then show ?thesis by auto\n        next\n          assume b: \"b \\<in> new\"\n          have \"b \\<in> ?r1\"\n            by (intro CollectI, rule exI, rule exI [of _ 0], intro conjI, rule b, auto)\n          then show ?thesis by auto\n        qed\n      next\n        case False\n        with b have \"b \\<in> ?l1\" by auto\n        then obtain a2 a1 m where a2n: \"a2 \\<notin> new\" and a2h: \"a2 \\<notin> have\" and a1: \"a1 \\<in> new\"\n          and a1a2: \"(a1,a2) \\<in> rel\" and m: \"m \\<le> n\" and a2b: \"(a2,b) \\<in> ?reln m\" by auto\n        have \"b \\<in> ?r1\"\n          by (rule CollectI, rule exI, rule exI [of _ \"Suc m\"], intro conjI, rule a1, simp add: m, rule relpow_Suc_I2, rule, rule a1a2, simp add: a2h, insert a2b, induct m arbitrary: a2 b, auto)\n        then show ?thesis by auto\n      qed\n    }     \n    moreover\n    { \n      fix b\n      assume b: \"b \\<in> ?r\"\n      then have \"b \\<in> ?l\" \n      proof (cases \"b \\<in> have\")\n        case True then show ?thesis by auto\n      next\n        case False\n        with b have \"b \\<in> ?r1\" by auto\n        then obtain a m where a: \"a \\<in> new\" and m: \"m \\<le> Suc n\" and ab: \"(a, b) \\<in> ?rel m\" by auto\n        have seq: \"\\<exists> a \\<in> new. (a, b) \\<in> ?rel m\"\n          using a  ab by auto\n        obtain l where l: \"l = (LEAST m. (\\<exists> a \\<in> new. (a, b) \\<in> ?rel m))\" by auto\n        have least: \"(\\<exists> a \\<in> new. (a, b) \\<in> ?rel l)\"\n          by (unfold l, rule LeastI, rule seq)\n        have lm: \"l \\<le> m\" unfolding l\n          by (rule Least_le, rule seq)\n        with m have ln: \"l \\<le> Suc n\" by auto\n        from least obtain a where a: \"a \\<in> new\"\n          and ab: \"(a, b) \\<in> ?rel l\" by auto\n        from ab [unfolded relpow_fun_conv]\n        obtain f where fa: \"f 0 = a\" and fb: \"b = f l\"\n          and steps: \"\\<And> i. i < l \\<Longrightarrow> (f i, f (Suc i)) \\<in> ?rel 1\" by auto\n        {\n          fix i\n          assume i: \"i < l\"\n          have main: \"f (Suc i) \\<notin> new\" \n          proof\n            assume new: \"f (Suc i) \\<in> new\"\n            let ?f = \"\\<lambda> j. f (Suc i + j)\"\n            have seq: \"(f (Suc i), b) \\<in> ?rel (l - Suc i)\"\n              unfolding relpow_fun_conv\n            proof (rule exI[of _ ?f], intro conjI allI impI)\n              from i show \"f (Suc i + (l - Suc i)) = b\"\n                unfolding fb by auto\n            next\n              fix j\n              assume \"j < l - Suc i\"\n              then have small: \"Suc i + j < l\" by auto\n              show \"(?f j, ?f (Suc j)) \\<in> rel \\<inter> {(a, b). b \\<notin> have}\" using steps [OF small] by auto\n            qed simp\n            from i have small: \"l - Suc i < l\" by auto\n            from seq new have \"\\<exists> a \\<in> new. (a, b) \\<in> ?rel (l - Suc i)\"  by auto\n            with not_less_Least [OF small [unfolded l]]\n            show False unfolding l by auto\n          qed\n          then have \"(f i, f (Suc i)) \\<in> ?reln 1\"\n            using steps [OF i] by auto\n        } note steps = this\n        have ab: \"(a, b) \\<in> ?reln l\" unfolding relpow_fun_conv\n          by (intro exI conjI, insert fa fb steps, auto)\n        have \"b \\<in> ?l1 \\<union> ?l2\" \n        proof (cases l)\n          case 0\n          with ab a show ?thesis by auto\n        next\n          case (Suc ll)\n          from relpow_Suc_D2 [OF ab [unfolded Suc]] a ln Suc \n          show ?thesis by auto\n        qed\n        then show ?thesis by auto\n      qed\n    }\n    ultimately show ?thesis\n      unfolding idl idr by blast\n  qed\nqed (simp add: un)\n\ntext \\<open>\n  From the previous lemma we can directly derive that @{const relpow_impl} works correctly if @{term\n  have} is initially set to @{text empty}\n\\<close>\nlemma relpow_impl:\n  \"set_of (relpow_i new empty n) = {b | a b m. a \\<in> set new \\<and> m \\<le> n \\<and> (a, b) \\<in> rel ^^ m}\" \nproof -\n  have id: \"rel \\<inter> {(a ,b). True} = rel\" by auto\n  show ?thesis unfolding relpow_impl_main empty by (simp add: id)\nqed\n\nend\n\n\nsubsection \\<open>Reflexive Transitive Closure and Transitive closure\\<close>\n\ntext \\<open>\n  Using @{const relpow_impl} it is now easy to obtain algorithms for the reflexive transitive\n  closure and the transitive closure by restricting the number of steps to the size of the finite\n  relation. Note that @{const relpow_impl} will abort the computation as soon as no new states are\n  detected. Hence, there is no penalty in using this large bound.\n\\<close>\n\ndefinition\n  rtrancl_impl ::\n    \"(('a \\<times> 'a) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list) \\<Rightarrow>\n      ('a list \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'b \\<Rightarrow> ('a \\<times> 'a) list \\<Rightarrow> 'a list \\<Rightarrow> 'b\"\nwhere\n  \"rtrancl_impl gen_succ un memb emp rel =\n    (let\n      succ = gen_succ rel;\n      n = length rel\n    in (\\<lambda> as. relpow_impl succ un memb as emp n))\"\n\ndefinition\n  trancl_impl ::\n    \"(('a \\<times> 'a) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list) \\<Rightarrow>\n      ('a list \\<Rightarrow> 'b \\<Rightarrow> 'b) \\<Rightarrow> ('a \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> 'b \\<Rightarrow> ('a \\<times> 'a) list \\<Rightarrow> 'a list \\<Rightarrow> 'b\"\nwhere\n  \"trancl_impl gen_succ un memb emp rel =\n    (let\n      succ = gen_succ rel;\n      n = length rel\n    in (\\<lambda> as. relpow_impl succ un memb (succ as) emp n))\"\n\ntext {*\n  The soundness of both @{const rtrancl_impl} and @{const trancl_impl} follows from the soundness of\n  @{const relpow_impl} and the fact that for finite relations, we can limit the number of steps to\n  explore all elements in the reflexive transitive closure.\n*}\n\nlemma rtrancl_finite_relpow:\n  \"(a, b) \\<in> (set rel)\\<^sup>* \\<longleftrightarrow> (\\<exists> n \\<le> length rel. (a, b) \\<in> set rel ^^ n)\" (is \"?l = ?r\")\nproof\n  assume ?r\n  then show ?l\n    unfolding rtrancl_power by auto\nnext\n  assume ?l\n  from this [unfolded rtrancl_power]\n    obtain n where ab: \"(a,b) \\<in> set rel ^^ n\" ..\n  obtain l where l: \"l = (LEAST n. (a,b) \\<in> set rel ^^ n)\" by auto\n  have ab: \"(a, b) \\<in> set rel ^^ l\" unfolding l\n    by (intro LeastI, rule ab)\n  from this [unfolded relpow_fun_conv]\n  obtain f where a: \"f 0 = a\" and b: \"f l = b\"\n    and steps: \"\\<And> i. i < l \\<Longrightarrow> (f i, f (Suc i)) \\<in> set rel\" by auto\n  let ?hits = \"map (\\<lambda> i. f (Suc i)) [0 ..< l]\"\n  from steps have subset: \"set ?hits \\<subseteq> snd ` set rel\" by force\n  have \"l \\<le> length rel\"\n  proof (cases \"distinct ?hits\")\n    case True\n    have \"l = length ?hits\" by simp\n    also have \"... = card (set ?hits)\" unfolding distinct_card [OF True] ..\n    also have \"... \\<le> card (snd ` set rel)\" by (rule card_mono [OF _ subset], auto)\n    also have \"... = card (set (map snd rel))\" by auto\n    also have \"... \\<le> length (map snd rel)\" by (rule card_length)\n    finally  show ?thesis by simp\n  next\n    case False\n    from this [unfolded distinct_conv_nth]\n    obtain i j where i: \"i < l\" and j: \"j < l\" and ij: \"i \\<noteq> j\" and fij: \"f (Suc i) = f (Suc j)\" by auto\n    let ?i = \"min i j\"\n    let ?j = \"max i j\"\n    have i: \"?i < l\" and j: \"?j < l\" and fij: \"f (Suc ?i) = f (Suc ?j)\" \n      and ij: \"?i < ?j\"\n      using i j ij fij unfolding min_def max_def by (cases \"i \\<le> j\", auto)\n    from i j fij ij obtain i j where i: \"i < l\" and j: \"j < l\" and ij: \"i < j\" and fij: \"f (Suc i) = f (Suc j)\" by blast\n    let ?g = \"\\<lambda> n. if n \\<le> i then f n else f (n + (j - i))\"\n    let ?l = \"l - (j - i)\"\n    have abl: \"(a,b) \\<in> set rel ^^ ?l\"\n      unfolding relpow_fun_conv\n    proof (rule exI [of _ ?g], intro conjI impI allI)\n      show \"?g ?l = b\" unfolding b [symmetric] using j ij by auto\n    next\n      fix k\n      assume k: \"k < ?l\"\n      show \"(?g k, ?g (Suc k)) \\<in> set rel\" \n      proof (cases \"k < i\")\n        case True\n        with i have \"k < l\" by auto\n        from steps [OF this] show ?thesis using True by simp\n      next\n        case False\n        then have ik: \"i \\<le> k\" by auto\n        show ?thesis\n        proof (cases \"k = i\")\n          case True\n          then show ?thesis using ij fij steps [OF i] by simp\n        next\n          case False\n          with ik have ik: \"i < k\" by auto\n          then have small: \"k + (j - i) < l\" using k by auto\n          show ?thesis using steps[OF small] ik by auto\n        qed\n      qed\n    qed (simp add: a)\n    from ij i have ll: \"?l < l\" by auto\n    have \"l \\<le> ?l\" unfolding l\n      by (rule Least_le, rule abl [unfolded l])\n    with ll have False by simp\n    then show ?thesis by simp\n  qed\n  with ab show ?r by auto\nqed\n\nlocale set_access_gen = set_access un\n  for un :: \"'a list \\<Rightarrow> 'b \\<Rightarrow> 'b\" +\n  fixes gen_succ :: \"('a \\<times> 'a) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  assumes gen_succ: \"set (gen_succ rel as) = {b. \\<exists> a \\<in> set as. (a, b) \\<in> set rel}\"\nbegin\n\nabbreviation \"rtrancl_i \\<equiv> rtrancl_impl gen_succ un memb empty\"\nabbreviation \"trancl_i \\<equiv> trancl_impl gen_succ un memb empty\"\n\nlemma rtrancl_impl:\n  \"set_of (rtrancl_i rel as) = {b. (\\<exists> a \\<in> set as. (a, b) \\<in> (set rel)\\<^sup>*)}\"\nproof -\n  interpret set_access_succ set_of memb empty un \"gen_succ rel\" \"set rel\"\n    by (unfold_locales, insert gen_succ, auto)\n  show ?thesis unfolding rtrancl_impl_def Let_def relpow_impl\n    by (auto simp: rtrancl_finite_relpow)\nqed\n\nlemma trancl_impl:\n  \"set_of (trancl_i rel as) = {b. (\\<exists> a \\<in> set as. (a, b) \\<in> (set rel)\\<^sup>+)}\"\nproof -\n  interpret set_access_succ set_of memb empty un \"gen_succ rel\" \"set rel\"\n    by (unfold_locales, insert gen_succ, auto)\n  show ?thesis\n    unfolding trancl_impl_def Let_def relpow_impl trancl_unfold_left relcomp_unfold rtrancl_finite_relpow succ by auto\nqed\n\nend\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Transitive-Closure/Transitive_Closure_Impl.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473713594991, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7531774014144734}}
{"text": "(*\nTitle: FriendshipTheory.thy\nAuthor:Wenda Li\n*)\n\ntheory FriendshipTheory \n  imports MoreGraph  \"~~/src/HOL/Number_Theory/Number_Theory\"\nbegin\n\n(*Proofs in this section are the common steps for both combinatorial and algebraic proofs for the\nFriendship Theorem*)\nsection{*Common steps*}\n\ndefinition (in valid_unSimpGraph) non_adj :: \"'v \\<Rightarrow> 'v \\<Rightarrow> bool\" where\n  \"non_adj v v' \\<equiv> v\\<in>V \\<and> v'\\<in>V \\<and> v\\<noteq>v' \\<and> \\<not>adjacent v v'\" \n\nlemma (in valid_unSimpGraph) no_quad:\n  assumes \"\\<And>v u. v\\<in>V \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<noteq>u \\<Longrightarrow> \\<exists>! n. adjacent v n \\<and> adjacent u n\"\n  shows \"\\<not> (\\<exists>v1 v2 v3 v4. v2\\<noteq>v4 \\<and> v1\\<noteq>v3 \\<and> adjacent v1 v2 \\<and> adjacent v2 v3 \\<and> adjacent v3 v4 \n      \\<and> adjacent v4 v1)\"\nproof\n  assume \"\\<exists>v1 v2 v3 v4. v2\\<noteq>v4  \\<and> v1\\<noteq>v3 \\<and> adjacent v1 v2 \\<and> adjacent v2 v3 \\<and> adjacent v3 v4 \\<and> adjacent v4 v1\"\n  then obtain v1 v2 v3 v4 where \n    \"v2\\<noteq>v4\" \"v1\\<noteq>v3\" \"adjacent v1 v2\" \"adjacent v2 v3\" \"adjacent v3 v4\" \"adjacent v4 v1\"\n    by auto\n  hence \"\\<exists>!n. adjacent v1 n \\<and> adjacent v3 n\" using assms[of v1 v3] by auto\n  thus False \n    by (metis `adjacent v1 v2` `adjacent v2 v3` `adjacent v3 v4` `adjacent v4 v1` `v2 \\<noteq> v4` \n      adjacent_sym)\nqed \n\nlemma even_card_set: \n  assumes \"finite A\" and \"\\<forall>x\\<in>A. f x\\<in>A \\<and> f x\\<noteq> x \\<and> f (f x)=x\"\n  shows \"even(card A)\" using assms\nproof (induct \"card A\"  arbitrary:A rule:less_induct)\n  case less\n  have \"A={}\\<Longrightarrow>?case\" by auto\n  moreover have \"A\\<noteq>{}\\<Longrightarrow>?case\" \n    proof -\n      assume \"A\\<noteq>{}\"\n      then obtain x where \"x\\<in>A\" by auto\n      hence \"f x\\<in>A\" and \"f x\\<noteq>x\" by (metis less.prems(2))+\n      obtain B where B:\"B=A-{x,f x}\" by auto\n      hence \"finite B\" using `finite A` by auto\n      moreover have \"card B<card A\" using B `finite A` \n        by (metis Diff_insert `f x \\<in> A` `x \\<in> A` card_Diff2_less)\n      moreover have \"\\<forall>x\\<in>B. f x \\<in> B \\<and> f x \\<noteq> x \\<and> f (f x) = x\" \n        proof \n          fix y assume \"y\\<in>B\"\n          hence \"y\\<in>A\" using B by auto\n          hence \"f y\\<noteq>y\" and \"f (f y)=y\" by (metis less.prems(2))+\n          moreover have \"f y\\<in>B\" \n            proof (rule ccontr)\n              assume \"f y\\<notin>B\"\n              have \"f y\\<in>A\" by (metis `y \\<in> A` less.prems(2))\n              hence \"f y\\<in>{x, f x}\" by (metis B DiffI `f y \\<notin> B`)\n              moreover have \"f y=x \\<Longrightarrow> False\" \n                by (metis B Diff_iff Diff_insert2 `f (f y) = y` `y \\<in> B` singleton_iff)\n              moreover have \"f y= f x\\<Longrightarrow> False\" \n                by (metis B Diff_iff `x \\<in> A` `y \\<in> B` insertCI less.prems(2))\n              ultimately show False by auto\n            qed\n          ultimately show \"f y \\<in> B \\<and> f y \\<noteq> y \\<and> f (f y) = y\"  by auto\n        qed\n      ultimately have \"even (card B)\" by (metis (full_types) less.hyps)\n      moreover have \"{x,f x}\\<subseteq>A\" using `f x\\<in>A` `x\\<in>A` by auto\n      moreover have \"card {x, f x} = 2\" using `f x\\<noteq>x` by auto\n      ultimately show ?case using B `finite A` card_mono [of A \"{x, f x}\"] \n        by (simp add: card_Diff_subset)\n    qed\n  ultimately show ?case by metis\nqed\n\nlemma (in valid_unSimpGraph) even_degree:\n  assumes friend_assm:\"\\<And>v u. v\\<in>V \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<noteq>u \\<Longrightarrow> \\<exists>! n. adjacent v n \\<and> adjacent u n\" \n      and \"finite E\"\n  shows \"\\<forall>v\\<in>V. even(degree v G)\"\nproof \n  fix v assume \"v\\<in>V\"\n  obtain f where f:\"f = (\\<lambda>n. (SOME v'. n\\<in>V \\<longrightarrow>n\\<noteq>v\\<longrightarrow>adjacent n v' \\<and> adjacent v v'))\" by auto\n  have \"\\<And>n.  n\\<in>V \\<longrightarrow> n\\<noteq>v \\<longrightarrow> (\\<exists>v'. adjacent n v' \\<and> adjacent v v')\" \n    proof (rule,rule)\n      fix n assume  \"n \\<in> V\" \"n \\<noteq> v\" \n      hence \"\\<exists>!v'. adjacent n v' \\<and> adjacent v v'\" \n        using friend_assm[of n v] `v\\<in>V`  unfolding non_adj_def by auto\n      thus \"\\<exists>v'. adjacent n v' \\<and> adjacent v v'\"  by auto\n    qed\n  hence f_ex:\"\\<And>n.  (\\<exists>v'. n\\<in>V \\<longrightarrow> n\\<noteq>v \\<longrightarrow>  adjacent n v' \\<and> adjacent v v')\" by auto\n  have \"\\<forall>x\\<in>{n. adjacent v n}. f x\\<in>{n. adjacent v n} \\<and> f x\\<noteq> x \\<and> f (f x)=x\" \n    proof \n      fix x assume \"x \\<in> {n. adjacent v n}\"\n      hence \"adjacent v x\" by auto\n      have \"f x\\<in>{n. adjacent v n}\" \n        using someI_ex[OF f_ex,of x] \n        by (metis `adjacent v x` adjacent_V(2) adjacent_no_loop f mem_Collect_eq)\n      moreover have \"f x\\<noteq>x\" \n        using someI_ex[OF f_ex,of x] \n        by (metis `adjacent v x` adjacent_V(2) adjacent_no_loop f)\n      moreover have \"f (f x)=x\" \n        proof (rule ccontr)\n          assume \"f (f x)\\<noteq>x\"\n          have \"adjacent (f x) (f (f x))\"  \n            using someI_ex[OF f_ex,of \"f x\"] \n            by (metis (full_types) adjacent_V(2) adjacent_no_loop calculation(1) f mem_Collect_eq) \n          moreover have \"adjacent (f (f x)) v\"\n            using someI_ex[OF f_ex,of \"f x\"] by (metis adjacent_V(1) adjacent_sym calculation f)\n          moreover have \"adjacent x (f x)\" \n            using someI_ex[OF f_ex,of x] by (metis `adjacent v x` adjacent_V(2) adjacent_no_loop f)\n          moreover have \"v\\<noteq>f x\" \n            by (metis `f x \\<in> {n. adjacent v n}` adjacent_no_loop mem_Collect_eq)\n          ultimately show False \n            using no_quad[OF friend_assm] using `adjacent v x` `f (f x)\\<noteq>x` \n            by metis\n        qed \n      ultimately show \"f x \\<in> {n. adjacent v n} \\<and> f x \\<noteq> x \\<and> f (f x) = x\" by auto\n    qed\n  moreover have \"finite {n. adjacent v n}\" by (metis adjacent_finite assms(2))\n  ultimately have \"even (card {n. adjacent v n})\" \n    using even_card_set[of \"{n. adjacent v n}\" f] by auto\n  thus \"even(degree v G)\" by (metis assms(2) degree_adjacent)\nqed\n\nlemma (in valid_unSimpGraph) degree_two_windmill:\n  assumes friend_assm:\"\\<And>v u. v\\<in>V \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<noteq>u \\<Longrightarrow> \\<exists>! n. adjacent v n \\<and> adjacent u n\"\n      and \"finite E\" and \"card V\\<ge>2\"\n  shows \"(\\<exists>v\\<in>V. degree v G = 2) \\<longleftrightarrow>(\\<exists>v. \\<forall>n\\<in>V. n\\<noteq>v \\<longrightarrow> adjacent v n)\"\nproof \n  assume \"\\<exists>v\\<in>V. degree v G = 2 \"\n  then obtain v where \"degree v G=2\" by auto\n  hence \"card {n. adjacent v n}=2\" using degree_adjacent[OF `finite E`,of v] by auto  \n  then obtain v1 v2 where v1v2:\"{n. adjacent v n}={v1,v2}\" and \"v1\\<noteq>v2\"\n    proof -\n      obtain v1 S where \"{n. adjacent v n} = insert v1 S\" and  \"v1 \\<notin> S\" and \"card S = 1\"\n        using `card {n. adjacent v n}=2` card_Suc_eq[of \"{n. adjacent v n}\" 1] by auto\n      then obtain v2 where \"S=insert v2 {}\" \n        using card_Suc_eq[of S 0] by auto\n      hence \"{n. adjacent v n}={v1,v2}\" and \"v1\\<noteq>v2\" \n        using `{n. adjacent v n} = insert v1 S` `v1 \\<notin> S` by auto\n      thus ?thesis using that[of v1 v2] by auto\n    qed\n  have \"adjacent v1 v2\" \n    proof -\n      obtain n where \"adjacent v n\" \"adjacent v1 n\" using friend_assm[of v v1] \n        by (metis (full_types) adjacent_V(2) adjacent_sym insertI1 mem_Collect_eq v1v2)\n      hence \"n\\<in>{n. adjacent v n}\" by auto\n      moreover have \"n\\<noteq>v1\" by (metis `adjacent v1 n` adjacent_no_loop)\n      ultimately have \"n=v2\" using v1v2 by auto\n      thus ?thesis by (metis `adjacent v1 n`)\n    qed\n  have v1v2_adj:\"\\<forall>x\\<in>V. x\\<in>{n. adjacent v1 n} \\<union> {n. adjacent v2 n}\"\n    proof \n      fix x assume \"x\\<in>V\"\n      have \"x=v \\<Longrightarrow> x \\<in> {n. adjacent v1 n} \\<union> {n. adjacent v2 n}\" \n        by (metis Un_iff adjacent_sym insertI1 mem_Collect_eq v1v2)\n      moreover have \"x\\<noteq>v \\<Longrightarrow> x \\<in> {n. adjacent v1 n} \\<union> {n. adjacent v2 n}\" \n        proof -\n          assume \"x\\<noteq>v\"\n          then obtain y where \"adjacent v y\" \"adjacent x y\"\n            using friend_assm[of v x] \n            by (metis Collect_empty_eq `x \\<in> V` adjacent_V(1) all_not_in_conv insertCI v1v2)\n          hence \"y=v1 \\<or> y=v2\" using v1v2 by auto\n          thus \"x \\<in> {n. adjacent v1 n} \\<union> {n. adjacent v2 n}\" using `adjacent x y` \n            by (metis UnI1 UnI2 adjacent_sym mem_Collect_eq)\n        qed\n      ultimately show \"x \\<in> {n. adjacent v1 n} \\<union> {n. adjacent v2 n}\" by auto\n    qed\n  have \"{n. adjacent v1 n}-{v2,v}={} \\<Longrightarrow> \\<exists>v. \\<forall>n\\<in>V. n \\<noteq> v \\<longrightarrow> adjacent v n\" \n    proof (rule exI[of _ v2],rule,rule) \n      fix n assume v1_adj:\"{n. adjacent v1 n} - {v2, v} = {}\" and \"n \\<in> V\" and \"n \\<noteq> v2\"\n      have \"n\\<in>{n. adjacent v2 n}\" \n        proof (cases \"n=v\") \n          case True\n          show ?thesis by (metis True adjacent_sym insertI1 insert_commute mem_Collect_eq v1v2)\n        next\n          case False\n          have \"n\\<notin>{n. adjacent v1 n}\" by (metis DiffI False `n \\<noteq> v2` empty_iff insert_iff v1_adj)\n          thus ?thesis by (metis Un_iff `n \\<in> V` v1v2_adj)\n        qed\n      thus \"adjacent v2 n\" by auto \n    qed\n  moreover have \"{n. adjacent v2 n}-{v1,v}={} \\<Longrightarrow> \\<exists>v. \\<forall>n\\<in>V. n \\<noteq> v \\<longrightarrow> adjacent v n\" \n    proof (rule exI[of _ v1],rule,rule) \n      fix n assume v2_adj:\"{n. adjacent v2 n} - {v1, v} = {}\" and \"n \\<in> V\" and \"n \\<noteq> v1\"\n      have \"n\\<in>{n. adjacent v1 n}\" \n        proof (cases \"n=v\") \n          case True\n          show ?thesis by (metis True adjacent_sym insertI1 mem_Collect_eq v1v2)\n        next\n          case False\n          have \"n\\<notin>{n. adjacent v2 n}\" by (metis DiffI False `n \\<noteq> v1` empty_iff insert_iff v2_adj)\n          thus ?thesis by (metis Un_iff `n \\<in> V` v1v2_adj)\n        qed\n      thus \"adjacent v1 n\" by auto \n    qed\n  moreover have \"{n. adjacent v1 n}-{v2,v}\\<noteq>{} \\<Longrightarrow> {n. adjacent v2 n}-{v1,v}\\<noteq>{} \\<Longrightarrow>False\" \n    proof -\n      assume \"{n. adjacent v1 n} - {v2, v} \\<noteq> {}\"  \"{n. adjacent v2 n} - {v1, v} \\<noteq> {}\"\n      then obtain a b where a:\"a\\<in>{n. adjacent v1 n} - {v2, v}\" \n          and b:\"b\\<in>{n. adjacent v2 n} - {v1, v}\"\n        by auto\n      have \"a=b \\<Longrightarrow> False\"\n        proof -\n          assume \"a=b\"\n          have \"adjacent v1 a\" using a by auto\n          moreover have \"adjacent a v2\" using b `a=b` adjacent_sym by auto\n          moreover have \"a\\<noteq>v\" by (metis DiffD2 `a = b` b doubleton_eq_iff insertI1)\n          moreover have \"adjacent v2 v\" \n            by (metis (full_types) adjacent_sym inf_sup_aci(5) insertI1 insert_is_Un mem_Collect_eq \n              v1v2)\n          moreover have \"adjacent v v1\" by (metis (full_types) insertI1 mem_Collect_eq v1v2)\n          ultimately show False using no_quad[OF friend_assm] \n            using `v1\\<noteq>v2` by auto\n        qed\n      moreover have \"a\\<noteq>b\\<Longrightarrow>False\"\n        proof -\n          assume \"a\\<noteq>b\"\n          moreover have \"a\\<in>V\" using a by (metis DiffD1 adjacent_V(2) mem_Collect_eq)\n          moreover have \"b\\<in>V\" using b by (metis DiffD1 adjacent_V(2) mem_Collect_eq)\n          ultimately obtain c where \"adjacent a c\" \"adjacent b c\"\n            using friend_assm[of a b] by auto\n          hence \"c\\<in>{n. adjacent v1 n} \\<union> {n. adjacent v2 n}\" \n            by (metis (full_types) adjacent_V(2) v1v2_adj)\n          moreover have \"c\\<in>{n. adjacent v1 n} \\<Longrightarrow> False\" \n            proof -\n              assume \"c\\<in>{n. adjacent v1 n}\"\n              hence \"adjacent v1 c\" by auto\n              moreover have \"adjacent c b\" by (metis `adjacent b c` adjacent_sym)\n              moreover have \"adjacent b v2\" \n                by (metis (full_types) Diff_iff adjacent_sym b mem_Collect_eq)\n              moreover have \"adjacent v2 v1\" by (metis `adjacent v1 v2` adjacent_sym)\n              moreover have \"c\\<noteq>v2\" \n                proof (rule ccontr)\n                  assume \"\\<not> c \\<noteq> v2\"\n                  hence \"c=v2\" by auto\n                  hence \"adjacent v2 a\" by (metis `adjacent a c` adjacent_sym)\n                  moreover have \"adjacent v2 v\" \n                    by (metis adjacent_sym insert_iff mem_Collect_eq v1v2)\n                  moreover have \"adjacent v1 v\" \n                    using adjacent_sym v1v2 by auto\n                  moreover have \"adjacent v1 a\" by (metis (full_types) Diff_iff a mem_Collect_eq)\n                  ultimately have \"a=v\" using friend_assm[of v1 v2] \n                    by (metis `v1 \\<noteq> v2` adjacent_V(1)) \n                  thus False using a by auto\n                qed\n              moreover have \"b\\<noteq>v1\" by (metis DiffD2 b insertI1)\n              ultimately show False using no_quad[OF friend_assm] by auto\n            qed\n          moreover have \"c\\<in>{n. adjacent v2 n} \\<Longrightarrow> False\" \n            proof -\n              assume \"c\\<in>{n. adjacent v2 n}\"\n              hence \"adjacent c v2\" by (metis adjacent_sym mem_Collect_eq)\n              moreover have \"adjacent a c\" using `adjacent a c` .\n              moreover have \"adjacent v1 a\" by (metis (full_types) Diff_iff a mem_Collect_eq) \n              moreover have \"adjacent v2 v1\" by (metis `adjacent v1 v2` adjacent_sym)\n              moreover have \"c\\<noteq>v1\" \n                proof (rule ccontr)\n                  assume \"\\<not> c \\<noteq> v1\"\n                  hence \"c=v1\" by auto\n                  hence \"adjacent v1 b\" by (metis `adjacent b c` adjacent_sym)\n                  moreover have \"adjacent v2 v\" \n                    by (metis adjacent_sym insert_iff mem_Collect_eq v1v2)\n                  moreover have \"adjacent v1 v\" \n                    using adjacent_sym v1v2 by auto\n                  moreover have \"adjacent v2 b\" by (metis Diff_iff b mem_Collect_eq)\n                  ultimately have \"b=v\" using friend_assm[of v1 v2] \n                    by (metis `v1 \\<noteq> v2` adjacent_V(1)) \n                  thus False using b by auto\n                qed\n              moreover have \"a\\<noteq>v2\" by (metis DiffD2 a insertI1)\n              ultimately show False using no_quad[OF friend_assm] by auto\n            qed\n          ultimately show False by auto\n        qed\n      ultimately show False by auto\n    qed\n  ultimately show \"\\<exists>v. \\<forall>n\\<in>V. n \\<noteq> v \\<longrightarrow> adjacent v n\" by auto\nnext\n  assume \"\\<exists>v. \\<forall>n\\<in>V. n \\<noteq> v \\<longrightarrow> adjacent v n\"\n  then obtain v where v:\"\\<forall>n\\<in>V. n \\<noteq> v \\<longrightarrow> adjacent v n\" by auto\n  obtain v1 where \"v1\\<in>V\" \"v1\\<noteq>v\" \n    proof (cases \"v\\<in>V\") \n      case False\n      have \"V\\<noteq>{}\" using `2\\<le>card V` by auto \n      then obtain v1 where \"v1\\<in>V\" by auto\n      thus ?thesis using False that[of v1] by auto\n    next\n      case True\n      then obtain S where  \"V = insert v S\" \"v \\<notin> S\"\n        using  mk_disjoint_insert[OF True] by auto\n      moreover have \"finite V\" using `2\\<le>card V` \n        by (metis add_leE card_infinite not_one_le_zero numeral_Bit0 numeral_One)\n      ultimately have \"1\\<le>card S\" \n        using `2\\<le>card V`  card.insert[of S v]  finite_insert[of v S] by auto\n      hence \"S\\<noteq>{}\" by auto\n      then obtain v1 where \"v1\\<in>S\" by auto\n      hence \"v1\\<noteq>v\" using `v\\<notin>S` by auto\n      thus thesis using that[of v1] `v1\\<in>S` `V=insert v S` by auto\n    qed\n  hence \"v\\<in>V\" using v by (metis adjacent_V(1)) \n  then obtain v2 where \"adjacent v1 v2\" \"adjacent v v2\" using friend_assm[of v v1] \n    by (metis `v1 \\<in> V` `v1 \\<noteq> v`)\n  have \"degree v1 G\\<noteq>2 \\<Longrightarrow> False\" \n    proof -\n      assume \"degree v1 G\\<noteq>2\"\n      hence \"card {n. adjacent v1 n}\\<noteq>2\" by (metis assms(2) degree_adjacent)\n      have \"{v,v2} \\<subseteq> {n. adjacent v1 n}\" \n        by (metis ` adjacent v1 v2 ` ` v1 \\<in> V ` ` v1 \\<noteq> v ` adjacent_sym bot_least insert_subset \n          mem_Collect_eq v)\n      moreover have \"v\\<noteq>v2\" using `adjacent v v2` adjacent_no_loop by auto\n      hence \"card {v,v2} = 2\" by auto \n      ultimately have \"card {n. adjacent v1 n} \\<ge>2\" \n        using adjacent_finite[OF `finite E`, of v1] by (metis card_mono)\n      hence \"card {n. adjacent v1 n} \\<ge>3\" using `card {n. adjacent v1 n}\\<noteq>2` by auto\n      then obtain v3 where \"v3\\<in>{n. adjacent v1 n}\" and \"v3\\<notin>{v,v2}\"\n        using `{v,v2} \\<subseteq> {n. adjacent v1 n}` `card {v, v2} = 2`  \n        by (metis `card {n. adjacent v1 n} \\<noteq> 2` subsetI subset_antisym)\n      hence \"adjacent v1 v3\" by auto\n      moreover have \"adjacent v3 v\" using v \n        by (metis `v3 \\<notin> {v, v2}` adjacent_V(2) adjacent_sym calculation insertCI)\n      moreover have \"adjacent v v2\" using `adjacent v v2` .\n      moreover have \"adjacent v2 v1\" using `adjacent v1 v2` adjacent_sym by auto\n      moreover have \"v1\\<noteq>v\" using `v1 \\<noteq> v` .\n      moreover have \"v3\\<noteq>v2\" by (metis `v3 \\<notin> {v, v2}` insert_subset subset_insertI)\n      ultimately show False using no_quad[OF friend_assm] by auto\n    qed\n  thus \"\\<exists>v\\<in>V. degree v G = 2\" using `v1\\<in>V` by auto\nqed\n\nlemma (in valid_unSimpGraph) regular:\n  assumes friend_assm:\"\\<And>v u. v\\<in>V \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<noteq>u \\<Longrightarrow> \\<exists>! n. adjacent v n \\<and> adjacent u n\" \n      and \"finite E\" and \"finite V\" and \"\\<not>(\\<exists>v\\<in>V. degree v G = 2)\"\n  shows \"\\<exists>k. \\<forall>v\\<in>V. degree v G = k\"\nproof -\n  { fix v u assume \"non_adj v u\"  \n    obtain v_adj where v_adj:\"v_adj={n. adjacent v n}\" by auto\n    obtain u_adj where u_adj:\"u_adj={n. adjacent u n}\" by auto\n    obtain f where f:\"f = (\\<lambda>n. (SOME v'. n\\<in>V \\<longrightarrow>n\\<noteq>u\\<longrightarrow>adjacent n v' \\<and> adjacent u v'))\" by auto\n    have \"\\<And>n.  n\\<in>V \\<longrightarrow> n\\<noteq>u \\<longrightarrow> (\\<exists>v'. adjacent n v' \\<and> adjacent u v')\" \n      proof (rule,rule)\n        fix n assume  \"n \\<in> V\" \"n \\<noteq> u\" \n        hence \"\\<exists>!v'. adjacent n v' \\<and> adjacent u v'\" \n          using friend_assm[of n u] `non_adj v u` unfolding non_adj_def by auto\n        thus \"\\<exists>v'. adjacent n v' \\<and> adjacent u v'\"  by auto\n      qed\n    hence f_ex:\"\\<And>n.  (\\<exists>v'. n\\<in>V \\<longrightarrow> n\\<noteq>u \\<longrightarrow>  adjacent n v' \\<and> adjacent u v')\" by auto\n    obtain v_adj_u where v_adj_u:\"v_adj_u= f ` v_adj\" by auto \n    have \"finite u_adj\" using u_adj adjacent_finite[OF `finite E`] by auto\n    have \"finite v_adj\" using v_adj adjacent_finite[OF `finite E`] by auto\n    hence \"finite v_adj_u\" using v_adj_u adjacent_finite[OF `finite E`] by auto\n    have \"inj_on f v_adj\" unfolding inj_on_def\n      proof (rule ccontr)\n        assume \"\\<not> (\\<forall>x\\<in>v_adj. \\<forall>y\\<in>v_adj. f x = f y \\<longrightarrow> x = y)\"\n        then obtain x y where \"x\\<in>v_adj\" \"y\\<in>v_adj\" \"f x=f y\" \"x\\<noteq>y\" by auto\n        have \"x\\<in>V\" by (metis `x \\<in> v_adj` adjacent_V(2) mem_Collect_eq v_adj)\n        moreover have \"x\\<noteq>u\" by (metis `non_adj v u` `x \\<in> v_adj` mem_Collect_eq non_adj_def v_adj)\n        ultimately have \"adjacent (f x) u\" and \"adjacent x (f x)\" \n          using someI_ex[OF f_ex[of x]] adjacent_sym by (metis f)+\n        hence \"f x \\<noteq> v\" by (metis `non_adj v u` non_adj_def)\n        have \"y\\<in>V\" by (metis `y \\<in> v_adj` adjacent_V(2) mem_Collect_eq v_adj) \n        moreover have \"y\\<noteq>u\" by (metis `non_adj v u` `y \\<in> v_adj` mem_Collect_eq non_adj_def v_adj)\n        ultimately have \"adjacent y (f y)\" using someI_ex[OF f_ex[of y]] by (metis f)\n        hence \" x \\<noteq> y \\<and> v \\<noteq> f x \\<and> adjacent v x \\<and> adjacent x (f x) \\<and> adjacent (f x) y \n            \\<and> adjacent y v\" \n          using `x\\<in>v_adj` `y\\<in>v_adj` `f x=f y` `x\\<noteq>y` `adjacent x (f x)` v_adj adjacent_sym `f x \\<noteq> v` \n          by auto\n        thus False using no_quad[OF friend_assm] by auto\n      qed\n    then have \"card v_adj =card v_adj_u\" by (metis card_image v_adj_u)\n    moreover have \"v_adj_u \\<subseteq> u_adj\" \n      proof \n        fix x assume \"x\\<in>v_adj_u\"\n        then obtain y where \"y\\<in>v_adj\" \n            and \"x = (SOME v'. y \\<in> V \\<longrightarrow> y \\<noteq> u \\<longrightarrow> adjacent y v' \\<and> adjacent u v')\"\n          using f image_def v_adj_u by auto\n        hence \"y \\<in> V \\<longrightarrow> y \\<noteq> u \\<longrightarrow> adjacent y x \\<and> adjacent u x\" using someI_ex[OF f_ex[of y]]\n          by auto\n        moreover have \"y\\<in>V\" by (metis `y \\<in> v_adj` adjacent_V(2) mem_Collect_eq v_adj) \n        moreover have \"y\\<noteq>u\" by (metis `non_adj v u` `y \\<in> v_adj` mem_Collect_eq non_adj_def v_adj)\n        ultimately have \"adjacent u x\" by auto\n        thus \"x\\<in>u_adj\" unfolding u_adj by auto\n      qed\n    moreover have \"card v_adj=degree v G\" using degree_adjacent[OF `finite E`, of v] v_adj by auto\n    moreover have \"card u_adj=degree u G\" using degree_adjacent[OF `finite E`, of u] u_adj by auto\n    ultimately have \"degree v G \\<le> degree u G\" using `finite u_adj` \n      by (metis `inj_on f v_adj` card_inj_on_le v_adj_u) }\n  hence non_adj_degree:\"\\<And>v u. non_adj v u \\<Longrightarrow> degree v G = degree u G\" \n    by (metis adjacent_sym antisym non_adj_def)\n  have \"card V=3 \\<Longrightarrow> ?thesis\" \n    proof \n      assume \"card V=3\" \n      then obtain v1 v2 v3 where \"V={v1,v2,v3}\" \"v1\\<noteq>v2\" \"v2\\<noteq>v3\" \"v1\\<noteq>v3\"\n        proof -\n          obtain v1 S1 where VS1:\"V = insert v1 S1\" and \"v1 \\<notin> S1\"  and \"card S1 = 2\"\n            using card_Suc_eq[of V 2] `card V=3` by auto\n          then obtain v2 S2 where S1S2:\"S1 = insert v2 S2\" and \"v2 \\<notin> S2\" and \"card S2 = 1\"\n            using card_Suc_eq[of S1 1] by auto\n          then obtain v3 where \"S2={v3}\"\n            using card_Suc_eq[of S2 0] by auto\n          hence \"V={v1,v2,v3}\" using VS1 S1S2 by auto\n          moreover have \"v1\\<noteq>v2\" \"v2\\<noteq>v3\" \"v1\\<noteq>v3\"using VS1 S1S2 `v1\\<notin>S1` `v2\\<notin>S2` `S2={v3}` by auto\n          ultimately show ?thesis using that by auto\n        qed\n      obtain n where \"adjacent v1 n\" \"adjacent v2 n\" \n        using friend_assm[of v1 v2] by (metis `V = {v1, v2, v3}` `v1 \\<noteq> v2` insertI1 insertI2)\n      moreover hence \"n=v3\" \n        using `V = {v1, v2, v3}` adjacent_V(2) adjacent_no_loop \n        by (metis (mono_tags) empty_iff insertE)\n      moreover obtain n' where \"adjacent v2 n'\" \"adjacent v3 n'\" \n        using friend_assm[of v2 v3] by (metis `V = {v1, v2, v3}` `v2 \\<noteq> v3` insertI1 insertI2)\n      moreover hence \"n'=v1\" \n        using `V = {v1, v2, v3}` adjacent_V(2) adjacent_no_loop\n        by (metis (mono_tags) empty_iff insertE)\n      ultimately have \"adjacent v1 v2\" and  \"adjacent v2 v3\" and \"adjacent v3 v1\" \n        using adjacent_sym by auto\n      have \"degree v1 G=2\" \n        proof -\n          have \"v2\\<in>{n. adjacent v1 n}\" and \"v3\\<in>{n. adjacent v1 n}\" and \"v1\\<notin>{n. adjacent v1 n}\"\n            using `adjacent v1 v2` `adjacent v3 v1` adjacent_sym \n            by (auto,metis adjacent_no_loop)\n          hence \"{n. adjacent v1 n}={v2,v3}\" using `V={v1,v2,v3}` by auto \n            thus ?thesis using degree_adjacent[OF `finite E`,of v1] `v2\\<noteq>v3` by auto\n        qed\n      moreover have \"degree v2 G=2\"\n        proof -\n          have \"v1\\<in>{n. adjacent v2 n}\" and \"v3\\<in>{n. adjacent v2 n}\" and \"v2\\<notin>{n. adjacent v2 n}\"\n            using `adjacent v1 v2` `adjacent v2 v3` adjacent_sym \n            by (auto,metis adjacent_no_loop)\n          hence \"{n. adjacent v2 n}={v1,v3}\" using `V={v1,v2,v3}` by force \n            thus ?thesis using degree_adjacent[OF `finite E`,of v2] `v1\\<noteq>v3` by auto \n        qed\n      moreover have \"degree v3 G=2\"\n        proof -\n          have \"v1\\<in>{n. adjacent v3 n}\" and \"v2\\<in>{n. adjacent v3 n}\" and \"v3\\<notin>{n. adjacent v3 n}\"\n            using `adjacent v3 v1` `adjacent v2 v3` adjacent_sym \n            by (auto,metis adjacent_no_loop)\n          hence \"{n. adjacent v3 n}={v1,v2}\" using `V={v1,v2,v3}` by force \n          thus ?thesis using degree_adjacent[OF `finite E`,of v3] `v1\\<noteq>v2` by auto\n        qed\n      ultimately show \"\\<forall>v\\<in>V. degree v G = 2\" using `V={v1,v2,v3}` by auto\n    qed\n  moreover have \"card V=2 \\<Longrightarrow> False\" \n    proof -\n      assume \"card V=2\"\n      obtain v1 v2 where \"V={v1,v2}\" \"v1\\<noteq>v2\"\n        proof -\n          obtain v1 S1 where VS1:\"V = insert v1 S1\" and \"v1 \\<notin> S1\" and \"card S1 = 1\" \n            using card_Suc_eq[of V 1] `card V=2` by auto\n          then obtain v2 where \"S1={v2}\"\n            using card_Suc_eq[of S1 0] by auto\n          hence \"V={v1,v2}\" using VS1 by auto\n          moreover have \"v1\\<noteq>v2\" using `v1\\<notin>S1` `S1={v2}` by auto\n          ultimately show ?thesis using that by auto\n        qed\n      then obtain v3 where \"adjacent v1 v3\" \"adjacent v2 v3\" \n        using friend_assm[of v1 v2] by auto   \n      hence \"v3\\<noteq>v2\" and \"v3\\<noteq>v1\" by (metis adjacent_no_loop)+\n      hence \"v3\\<notin>V\" using `V={v1,v2}` by auto\n      thus False using `adjacent v1 v3` by (metis (full_types) adjacent_V(2))\n    qed\n  moreover have \"card V=1 \\<Longrightarrow> ?thesis\" \n    proof \n      assume \"card V=1\"\n      then obtain v1 where \"V={v1}\" using card_eq_SucD[of V 0] by auto\n      have \"E={}\" \n        proof (rule ccontr) \n          assume \"E\\<noteq>{}\"\n          then obtain x1 x2 x3 where x:\"(x1,x2,x3)\\<in>E\" by auto\n          hence \"x1=v1\" and \"x3=v1\" using `V={v1}` E_validD by auto\n          thus False using no_id x by auto\n        qed\n      hence \"degree v1 G=0\" unfolding degree_def by auto\n      thus  \"\\<forall>v\\<in>V. degree v G =0\" using `V={v1}`by auto\n    qed\n  moreover have \"card V=0 \\<Longrightarrow> ?thesis\"\n    proof -\n      assume \"card V=0\"\n      hence \"V={}\" using `finite V` by auto\n      thus ?thesis by auto\n    qed\n  moreover have \"card V \\<ge>4 \\<Longrightarrow> \\<not>(\\<exists>v u. non_adj v u) \\<Longrightarrow> False\" \n    proof -\n      assume \"\\<not>(\\<exists>v u. non_adj v u)\" \"card V\\<ge>4\"\n      hence non_non_adj:\"\\<And>v u. v\\<notin>V \\<or> u\\<notin>V \\<or> v=u \\<or> adjacent v u\" unfolding non_adj_def by auto\n      obtain v1 v2 v3 v4 where \"v1\\<in>V\" \"v2\\<in>V\" \"v3\\<in>V\" \"v4\\<in>V\" \"v1\\<noteq>v2\" \"v1\\<noteq>v3\" \"v1\\<noteq>v4\"\n              \"v2\\<noteq>v3\" \"v2\\<noteq>v4\" \"v3\\<noteq>v4\" \n        proof -\n          obtain v1 B1 where \"V = insert v1 B1\"  \"v1 \\<notin> B1\"  \"card B1 \\<ge>3\" \"finite B1\"\n            using `card V\\<ge>4` card_le_Suc_iff[OF `finite V`, of 3] by auto\n          then obtain v2 B2 where \"B1 = insert v2 B2\"  \"v2 \\<notin> B2\"  \"card B2 \\<ge>2\" \"finite B2\"\n            using card_le_Suc_iff[of B1 2] by auto\n          then obtain v3 B3 where \"B2= insert v3 B3\" \"v3\\<notin>B3\" \"card B3\\<ge>1\" \"finite B3\"\n            using card_le_Suc_iff[of B2 1] by auto\n          then obtain v4 B4 where \"B3=insert v4 B4\" \"v4\\<notin>B4\" \n            using card_le_Suc_iff[of B3 0] by auto\n          have \"v1\\<in>V\" by (metis `V = insert v1 B1` insert_subset order_refl)\n          moreover have \"v2\\<in>V\" \n            by (metis `B1 = insert v2 B2` `V = insert v1 B1` insert_subset subset_insertI)\n          moreover have \"v3\\<in>V\" \n            by (metis `B1 = insert v2 B2` `B2 = insert v3 B3` `V = insert v1 B1` insert_iff)\n          moreover have \"v4\\<in>V\" \n            by (metis `B1 = insert v2 B2` `B2 = insert v3 B3` `B3 = insert v4 B4` \n              `V = insert v1 B1` insert_iff)\n          moreover have \"v1\\<noteq>v2\" \n            by (metis (full_types) `B1 = insert v2 B2` `v1 \\<notin> B1` insertI1)\n          moreover have \"v1\\<noteq>v3\" \n            by (metis `B1 = insert v2 B2` `B2 = insert v3 B3` `v1 \\<notin> B1` insert_iff)\n          moreover have \"v1\\<noteq>v4\" \n            by (metis `B1 = insert v2 B2` `B2 = insert v3 B3` `B3 = insert v4 B4` `v1 \\<notin> B1` \n              insert_iff)\n          moreover have \"v2\\<noteq>v3\" \n            by (metis (full_types) `B2 = insert v3 B3` `v2 \\<notin> B2` insertI1)\n          moreover have \"v2\\<noteq>v4\" \n            by (metis `B2 = insert v3 B3` `B3 = insert v4 B4` `v2 \\<notin> B2` insert_iff)\n          moreover have \"v3\\<noteq>v4\" \n            by (metis (full_types) `B3 = insert v4 B4` `v3 \\<notin> B3` insertI1)\n          ultimately show ?thesis using that by auto\n        qed\n      hence \"adjacent v1 v2\" using non_non_adj by auto\n      moreover have \"adjacent v2 v3\" using non_non_adj by (metis `v2 \\<in> V` `v2 \\<noteq> v3` `v3 \\<in> V`)\n      moreover have \"adjacent v3 v4\" using non_non_adj by (metis `v3 \\<in> V` `v3 \\<noteq> v4` `v4 \\<in> V`)\n      moreover have \"adjacent v4 v1\" using non_non_adj by (metis `v1 \\<in> V` `v1 \\<noteq> v4` `v4 \\<in> V`)\n      ultimately show False using no_quad[OF friend_assm] \n        by (metis `v1 \\<noteq> v3` `v2 \\<noteq> v4`)\n    qed  \n  moreover have \"card V\\<ge>4 \\<Longrightarrow> (\\<exists>v u. non_adj v u) \\<Longrightarrow> ?thesis\" \n    proof - \n      assume \"(\\<exists>v u. non_adj v u)\" \"card V\\<ge>4\"\n      then obtain v u where \"non_adj v u\" by auto\n      then obtain w where \"adjacent v w\" and \"adjacent u w\" \n          and unique:\"\\<forall>n. adjacent v n \\<and> adjacent u n \\<longrightarrow> n=w\"\n        using friend_assm[of v u] unfolding non_adj_def by auto \n      have \"\\<forall>n\\<in>V. degree n G = degree v G\" \n        proof \n          fix n assume \"n\\<in>V\"\n          moreover have \"n=v \\<Longrightarrow> degree n G = degree v G\" by auto\n          moreover have \"n=u \\<Longrightarrow> degree n G = degree v G\" \n            using non_adj_degree `non_adj v u` by auto\n          moreover have \"n\\<noteq>v \\<Longrightarrow> n\\<noteq>u \\<Longrightarrow> n\\<noteq>w \\<Longrightarrow> degree n G = degree v G\" \n            proof -\n              assume \"n\\<noteq>v\" \"n\\<noteq>u\" \"n\\<noteq>w\"\n              have \"non_adj v n \\<Longrightarrow> degree n G = degree v G\" by (metis non_adj_degree)\n              moreover have \"non_adj u n \\<Longrightarrow> degree n G = degree v G\" \n                by (metis `non_adj v u` non_adj_degree)\n              moreover have \"\\<not>non_adj u n \\<Longrightarrow> \\<not>non_adj v n \\<Longrightarrow> degree n G = degree v G\" \n                by (metis `n \\<in> V` `n \\<noteq> w` `non_adj v u` non_adj_def unique)\n              ultimately show \"degree n G = degree v G\" by auto\n            qed\n          moreover have \"n=w \\<Longrightarrow> degree n G = degree v G\" \n            proof -\n              assume \"n=w\" \n              moreover have \"\\<not>(\\<exists>v. \\<forall>n\\<in>V. n\\<noteq>v \\<longrightarrow> adjacent v n)\" \n                using `card V\\<ge>4` degree_two_windmill assms(2) assms(4) friend_assm\n                by auto\n              ultimately obtain w1 where \"w1\\<in>V\" \"w1\\<noteq>w\" \"non_adj w w1\"\n                by (metis `n\\<in>V` non_adj_def)\n              have \"w1=v \\<Longrightarrow> degree n G = degree v G\" \n                by (metis `n = w` `non_adj w w1` non_adj_degree)\n              moreover have \"w1=u \\<Longrightarrow> degree n G = degree v G\" \n                by (metis `adjacent u w` `non_adj w w1` adjacent_sym non_adj_def)\n              moreover have \"w1\\<noteq>u \\<Longrightarrow> w1\\<noteq>v \\<Longrightarrow> degree n G = degree v G\" \n                by (metis `n = w` `non_adj v u` `non_adj w w1` non_adj_def non_adj_degree unique)\n              ultimately show \"degree n G = degree v G\" by auto\n            qed\n          ultimately show \"degree n G = degree v G\" by auto\n        qed\n      thus ?thesis by auto\n    qed\n  ultimately show ?thesis by force\nqed \n\n(*In this section, combinatorial proofs for the Friendship Theorem differ from the algebraic ones.\nThe main difference between these two approaches is that combinatorial proofs show Lemma \nexist_degree_two by counting the number of paths while algebraic proofs show it by computing\nthe eigenvalue of adjacency matrices.*)\nsection{*Exclusive steps for combinatorial proofs*}\n\nfun (in valid_unSimpGraph) adj_path:: \"'v \\<Rightarrow> 'v list \\<Rightarrow>bool\" where\n  \"adj_path v [] =  (v\\<in>V)\" \n  | \"adj_path v (u#us)= (adjacent v u \\<and> adj_path u us)\"\n\nlemma (in valid_unSimpGraph) adj_path_butlast:\n  \"adj_path v ps \\<Longrightarrow> adj_path v (butlast ps)\"\nby (induct ps arbitrary:v,auto)\n\nlemma (in valid_unSimpGraph) adj_path_V:\n  \"adj_path v ps \\<Longrightarrow> set ps \\<subseteq> V\"\nby (induct ps arbitrary:v, auto)\n\nlemma (in valid_unSimpGraph) adj_path_V':\n  \"adj_path v ps \\<Longrightarrow> v\\<in> V\"\nby (induct ps arbitrary:v, auto)\n\nlemma (in valid_unSimpGraph) adj_path_app:\n  \"adj_path v ps \\<Longrightarrow> ps\\<noteq>[] \\<Longrightarrow> adjacent (last ps) u \\<Longrightarrow> adj_path v (ps@[u])\"\nproof (induct ps arbitrary:v)\n  case Nil \n  thus ?case by auto\nnext\n  case (Cons x xs)\n  thus ?case by (cases xs,auto)\nqed\n\n\nlemma (in valid_unSimpGraph) adj_path_app':\n  \"adj_path v (ps @ [q] ) \\<Longrightarrow> ps \\<noteq> [] \\<Longrightarrow> adjacent (last ps) q\"\nproof (induct ps arbitrary:v)\n  case Nil \n  thus ?case by auto\nnext\n  case (Cons x xs)\n  thus ?case by (cases xs,auto)\nqed\n\nlemma card_partition':\n  assumes \"\\<forall>v\\<in>A. card {n. R v n} = k\" \"k>0\" \"finite A\" \n      \"\\<forall>v1 v2. v1\\<noteq>v2 \\<longrightarrow> {n. R v1 n} \\<inter> {n. R v2 n}={}\"\n  shows \"card (\\<Union>v\\<in>A. {n. R v n}) = k * card A\"\nproof -\n  have \"\\<And>C. C \\<in> (\\<lambda>x. {n. R x n}) ` A \\<Longrightarrow> card C = k\"\n    proof -\n      fix C assume \"C \\<in> (\\<lambda>x. {n. R x n}) ` A\"\n      show \"card C=k\" by (metis (mono_tags) `C \\<in> (\\<lambda>x. {n. R x n}) \\` A` assms(1) imageE)\n    qed\n  moreover have \"\\<And>C1 C2. C1 \\<in>(\\<lambda>x. {n. R x n}) ` A  \\<Longrightarrow> C2 \\<in> (\\<lambda>x. {n. R x n}) ` A \\<Longrightarrow> C1 \\<noteq> C2 \n      \\<Longrightarrow> C1 \\<inter> C2 = {}\"\n    proof -\n      fix C1 C2 assume \"C1 \\<in> (\\<lambda>x. {n. R x n}) ` A\"  \"C2 \\<in> (\\<lambda>x. {n. R x n}) ` A\"  \"C1 \\<noteq> C2\"\n      obtain v1 where \"v1\\<in>A\" \"C1={n. R v1 n}\" by (metis `C1 \\<in> (\\<lambda>x. {n. R x n}) \\` A` imageE)\n      obtain v2 where \"v2\\<in>A\" \"C2={n. R v2 n}\" by (metis `C2 \\<in> (\\<lambda>x. {n. R x n}) \\` A` imageE)\n      have \"v1\\<noteq>v2\" by (metis `C1 = {n. R v1 n}` `C1 \\<noteq> C2` `C2 = {n. R v2 n}`)\n      thus \"C1 \\<inter> C2 ={}\" by (metis `C1 = {n. R v1 n}` `C2 = {n. R v2 n}` assms(4))\n    qed\n  moreover have \"\\<Union>((\\<lambda>x. {n. R x n}) ` A) = (\\<Union>x\\<in>A. {n. R x n})\" by auto\n  moreover have \"finite ((\\<lambda>x. {n. R x n}) ` A )\" by (metis assms(3) finite_imageI)\n  moreover have \"finite (\\<Union>((\\<lambda>x. {n. R x n}) ` A))\" by (metis (full_types) Union_image_eq assms(1) \n    assms(2) assms(3) card_eq_0_iff finite_UN_I less_nat_zero_code)\n  moreover have \" card A = card ((\\<lambda>x. {n. R x n}) ` A)\" \n    proof -\n      have \"inj_on (\\<lambda>x. {n. R x n}) A\" unfolding inj_on_def\n        using `\\<forall>v1 v2. v1\\<noteq>v2 \\<longrightarrow> {n. R v1 n} \\<inter> {n. R v2 n}={}` \n        by (metis assms(1) assms(2) card_empty inf.idem less_le)\n      thus ?thesis by (metis card_image)\n    qed\n  ultimately show ?thesis using card_partition[of \"(\\<lambda>x. {n. R x n}) ` A\"] by auto\nqed\n\nlemma (in valid_unSimpGraph) path_count:\n  assumes k_adj:\"\\<And>v. v\\<in>V \\<Longrightarrow> card {n. adjacent v n} = k\" and  \"v\\<in>V\" and \"finite V\" and \"k>0\"\n  shows \"card {ps. length ps=l \\<and> adj_path v ps}=k^l\"\nproof (induct l rule:nat.induct)  \n  case zero\n  have \"{ps. length ps=0 \\<and> adj_path v ps}={[]}\" using `v\\<in>V` by auto \n  thus ?case by auto\nnext\n  case (Suc n)\n  obtain ext where ext: \"ext=(\\<lambda>ps ps'.  ps'\\<noteq>[] \\<and> (butlast ps'=ps) \\<and> adj_path v ps')\" by auto\n  have \"\\<forall>ps\\<in>{ps. length ps = n \\<and> adj_path v ps}. card {ps'. ext ps ps'} = k\" \n    proof \n      fix ps assume \"ps\\<in>{ps. length ps = n \\<and> adj_path v ps}\"\n      hence \"adj_path v ps\" and \"length ps = n\" by auto\n      obtain qs where qs:\"qs = {n. if ps=[] then adjacent v n else adjacent (last ps) n}\" by auto\n      hence \"card qs = k\" \n        proof (cases \"ps=[]\")\n          case True\n          thus ?thesis using qs k_adj[OF `v\\<in>V`] by auto\n        next\n          case False\n          have \"last ps \\<in> V\" using adj_path_V by (metis False `adj_path v ps` last_in_set set_mp)\n          thus ?thesis using k_adj[of \"last ps\"] False qs by auto\n        qed\n      obtain app where app:\"app=(\\<lambda>q. ps@[q])\" by auto\n      have \"app ` qs = {ps'. ext ps ps'}\" \n        proof -\n          have \"\\<And>xs. xs\\<in> app ` qs \\<Longrightarrow> xs \\<in> {ps'. ext ps ps'}\" \n            proof (rule,cases \"ps=[]\")\n              case True\n              fix xs assume \"xs\\<in> app ` qs\"\n              then obtain q where \"q\\<in> qs\" \"app q=xs\" by (metis imageE)\n              hence  \"adjacent v q\" and \"xs=ps@[q]\" using qs app True by auto\n              hence \"adj_path v xs\" \n                by (metis True adj_path.simps(1) adj_path.simps(2) adjacent_V(2) append_Nil)\n              moreover have \"butlast xs = ps\" using  `xs=ps@[q]` by auto              \n              ultimately show \"ext ps xs\" using ext `xs=ps@[q]` by auto\n            next\n              case False\n              fix xs assume \"xs\\<in> app ` qs\"\n              then obtain q where \"q\\<in> qs\" \"app q=xs\" by (metis imageE)\n              hence  \"adjacent (last ps) q\" using qs app False by auto\n              hence \"adj_path v (ps@[q])\" using  `adj_path v ps` False adj_path_app by auto  \n              hence \"adj_path v xs\" by (metis `app q = xs` app)\n              moreover have \"butlast xs=ps\" by (metis `app q = xs` app butlast_snoc)\n              ultimately show \"ext ps xs\" by (metis False butlast.simps(1) ext) \n            qed\n          moreover have \"\\<And>xs. xs\\<in>{ps'. ext ps ps'} \\<Longrightarrow> xs\\<in> app ` qs\" \n            proof (cases \"ps=[]\")\n              case True\n              hence \"qs = {n. adjacent v n }\" using qs by auto\n              fix xs assume \"xs \\<in> {ps'. ext ps ps'}\" \n              hence \"xs\\<noteq>[]\" and \"(butlast xs=ps)\" and \"adj_path v xs\" using ext by auto\n              thus \"xs \\<in> app ` qs\" \n                using True app `qs = {n. adjacent v n}`\n                by (metis  adj_path.simps(2) append_butlast_last_id append_self_conv2 image_iff \n                  mem_Collect_eq)\n            next\n              case False\n              fix xs assume \"xs \\<in> {ps'. ext ps ps'}\" \n              hence \"xs\\<noteq>[]\" and \"(butlast xs=ps)\" and \"adj_path v xs\" using ext by auto\n              then obtain q where \"xs=ps@[q]\" by (metis append_butlast_last_id)\n              hence \"adjacent (last ps) q\" using `adj_path v xs` False adj_path_app' by auto\n              thus \"xs \\<in> app ` qs\" using qs \n                by (metis (lifting, full_types) False `xs = ps @ [q]` app imageI mem_Collect_eq)\n            qed\n          ultimately show ?thesis by auto\n        qed\n      moreover have \"inj_on app qs\" using app unfolding inj_on_def by auto \n      ultimately show \"card {ps'. ext ps ps'}=k\" by (metis `card qs = k` card_image)\n    qed\n  moreover have \"\\<forall>ps1 ps2. ps1\\<noteq>ps2 \\<longrightarrow> {n. ext ps1 n} \\<inter> {n. ext ps2 n}={}\" using ext by auto\n  moreover have \"finite {ps. length ps = n \\<and> adj_path v ps}\" \n    by (metis Suc.hyps assms(4) card_infinite nat_less_le power_eq_0_iff)\n  ultimately have \"card (\\<Union>v\\<in>{ps. length ps = n \\<and> adj_path v ps}. {n. ext v n}) \n      = k * card {ps. length ps = n \\<and> adj_path v ps}\" \n    using card_partition'[of \"{ps. length ps = n \\<and> adj_path v ps}\" ext k] `k>0` by auto \n  moreover have \"{ps. length ps = n+1 \\<and> adj_path v ps}\n      =(\\<Union>ps\\<in>{ps. length ps = n \\<and> adj_path v ps}. {ps'. ext ps ps'})\" \n    proof -\n      have \"\\<And>xs. xs \\<in> {ps. length ps = n + 1 \\<and> adj_path v ps} \\<Longrightarrow> \n          xs \\<in> (\\<Union>ps\\<in>{ps. length ps = n \\<and> adj_path v ps}. {ps'. ext ps ps'})\"\n        proof -\n          fix xs assume \"xs \\<in> {ps. length ps = n + 1 \\<and> adj_path v ps}\"\n          hence \"length xs = n +1\" and \"adj_path v xs\" by auto\n          hence \"butlast xs \\<in>{ps. length ps = n \\<and> adj_path v ps}\" \n            using adj_path_butlast length_butlast mem_Collect_eq by auto\n          thus \"xs \\<in> (\\<Union>ps\\<in>{ps. length ps = n \\<and> adj_path v ps}. {ps'. ext ps ps'})\"\n            using `adj_path v xs` `length xs = n + 1` UN_iff  ext length_greater_0_conv \n              mem_Collect_eq \n            by auto\n        qed\n      moreover have \"\\<And>xs . xs\\<in>(\\<Union>ps\\<in>{ps. length ps = n \\<and> adj_path v ps}. {ps'. ext ps ps'}) \\<Longrightarrow>\n          xs \\<in> {ps. length ps = n + 1 \\<and> adj_path v ps}\"\n        proof -\n          fix xs assume \"xs\\<in>(\\<Union>ps\\<in>{ps. length ps = n \\<and> adj_path v ps}. {ps'. ext ps ps'})\"\n          then obtain ys where \"length ys=n\" \"adj_path v ys\" \"ext ys xs\" by auto\n          hence \"length xs=n+1\" using ext by auto\n          thus \"xs\\<in>{ps. length ps = n + 1 \\<and> adj_path v ps}\" \n            by (metis (lifting, full_types) `ext ys xs` ext mem_Collect_eq)\n        qed\n      ultimately show ?thesis by fast\n    qed\n  ultimately show \"card {ps. length ps = (Suc n) \\<and> adj_path v ps} = k ^ (Suc n)\" \n    using Suc.hyps by auto\nqed\n\n\n\nlemma rotate_eq:\"rotate1 xs=rotate1 ys \\<Longrightarrow> xs=ys\" \nproof (induct xs arbitrary:ys)\n  case Nil\n  thus ?case by (metis rotate1_is_Nil_conv)\nnext\n  case (Cons n ns)\n  hence \"ys\\<noteq>[]\" by (metis list.distinct(1) rotate1_is_Nil_conv)\n  thus \"?case\" using Cons by (metis butlast_snoc last_snoc list.exhaust rotate1.simps(2))\nqed\n  \n\nlemma rotate_diff:\"rotate m xs=rotate n xs \\<Longrightarrow>rotate (m-n) xs = xs\"\nproof (induct m arbitrary:n)\n  case 0\n  thus ?case by auto\nnext \n  case (Suc m')\n  hence \"n=0 \\<Longrightarrow> ?case\" by auto\n  moreover have \"n\\<noteq>0 \\<Longrightarrow>?case\" \n    proof -\n      assume \"n\\<noteq>0\" \n      then obtain n' where n': \"n = Suc n'\" by (metis nat.exhaust)\n      hence \"rotate m' xs = rotate n' xs\" \n        using `rotate (Suc m') xs = rotate n xs` rotate_eq rotate_Suc \n        by auto\n      hence \"rotate (m' - n') xs = xs\" by (metis Suc.hyps) \n      moreover have \"Suc m' - n = m'-n'\"\n        by (metis n' diff_Suc_Suc) \n      ultimately show ?case by auto\n    qed\n  ultimately show ?case by fast \nqed    \n\nlemma (in valid_unSimpGraph) exist_degree_two:\n  assumes friend_assm:\"\\<And>v u. v\\<in>V \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<noteq>u \\<Longrightarrow> \\<exists>! n. adjacent v n \\<and> adjacent u n\"\n      and \"finite E\" and \"finite V\" and \"card V\\<ge>2\" \n  shows \"\\<exists>v\\<in>V. degree v G = 2\"\nproof (rule ccontr)\n  assume \"\\<not> (\\<exists>v\\<in>V. degree v G = 2)\"\n  hence \"\\<And>v. v\\<in>V \\<Longrightarrow> degree v G\\<noteq>2\" by auto\n  obtain k where k_adj: \"\\<And>v. v\\<in>V\\<Longrightarrow> card {n. adjacent v n}=k\" using regular[OF friend_assm] \n    by (metis `\\<not> (\\<exists>v\\<in>V. degree v G = 2)` assms(2) assms(3) degree_adjacent)\n  have \"k\\<ge>4\"\n    proof -\n      obtain v1 v2 where \"v1\\<in>V\" \"v2\\<in>V\" \"v1\\<noteq>v2\"\n        using `card V\\<ge>2` by (metis `\\<not>(\\<exists>v\\<in>V. degree v G = 2)` assms(2) degree_two_windmill)\n      have \"k\\<noteq>0\"\n        proof \n          assume \"k=0\"\n          obtain v3 where \"adjacent v1 v3\" using friend_assm[OF `v1\\<in>V` `v2\\<in>V` `v1\\<noteq>v2`] by auto\n          hence \"card {n. adjacent v1 n} \\<noteq> 0\" using adjacent_finite[OF `finite E`] by auto\n          moreover have \"card {n. adjacent v1 n} = 0\" using k_adj[OF `v1\\<in>V`] \n            by (metis `k = 0`)\n          ultimately show False by simp\n        qed\n      moreover have \"even k\" using even_degree[OF friend_assm] \n        by (metis `v1 \\<in> V` assms(2) degree_adjacent k_adj)\n      hence \"k\\<noteq>1\" and \"k\\<noteq>3\" by auto\n      moreover have \"k\\<noteq>2\" using `\\<And>v. v\\<in>V \\<Longrightarrow> degree v G\\<noteq>2` degree_adjacent k_adj \n        by (metis `v1 \\<in> V` assms(2))  \n      ultimately show ?thesis by auto\n    qed\n  obtain T where T:\"T=(\\<lambda>l::nat. {ps. length ps = l+1 \\<and> adj_path (hd ps) (tl ps)})\" by auto\n  have T_count:\"\\<And>l::nat. card (T l) = (k*k-k+1)*k^l\" using card_partition'\n    proof -\n      fix l::nat\n      obtain ext where ext:\"ext=(\\<lambda>v ps. adj_path v (tl ps) \\<and> hd ps=v \\<and> length ps=l+1)\" by auto\n      have \"\\<forall>v\\<in>V. card {ps. ext v ps} = k^l\" \n        proof \n          fix v assume \"v \\<in> V\" \n          have \"\\<And>ps. ps\\<in>tl ` {ps. ext v ps} \\<Longrightarrow>  ps\\<in>{ps. length ps=l \\<and> adj_path v ps}\" \n            proof -\n              fix ps assume  \"ps \\<in> tl ` {ps. ext v ps}\"\n              then obtain ps' where \"adj_path v (tl ps')\" \"hd ps'=v\" \"length ps'=l+1\" \"ps=tl ps'\"\n                using ext by auto\n              hence \"adj_path v ps\" and \"length ps=l\" by auto\n              thus \"ps\\<in>{ps. length ps=l \\<and> adj_path v ps}\" by auto\n            qed\n          moreover have \"\\<And>ps. ps\\<in>{ps. length ps=l \\<and> adj_path v ps} \\<Longrightarrow> ps\\<in> tl ` {ps. ext v ps}\" \n            proof -\n              fix ps assume \"ps \\<in> {ps. length ps = l \\<and> adj_path v ps}\"\n              hence \"length ps=l\" and \"adj_path v ps\" by auto\n              moreover obtain ps' where \"ps'=v#ps\" by auto\n              ultimately have \"adj_path v (tl ps')\" and \"hd ps'=v\" and \"length ps'=l+1\" by auto\n              thus \"ps \\<in> tl ` {ps. ext v ps}\" \n                by (metis `ps' = v # ps` ext imageI mem_Collect_eq list.sel(3))\n            qed\n          ultimately have \"tl ` {ps. ext v ps} = {ps. length ps=l \\<and> adj_path v ps}\" by fast\n          moreover have \"inj_on tl {ps. ext v ps}\"  unfolding inj_on_def \n            proof (rule,rule,rule)\n              fix x y assume \"x \\<in> Collect (ext v)\"  \"y \\<in> Collect (ext v)\"  \"tl x = tl y\"\n              hence \"hd x=hd y\" and \"x\\<noteq>[]\" and \"y\\<noteq>[]\"using ext by auto\n              thus \"x=y\" using `tl x= tl y` by (metis list.sel(1,3) list.exhaust)\n            qed\n          moreover have \"card {ps. length ps=l \\<and> adj_path v ps} = k^l\" \n            using path_count[OF k_adj,of v l]  `4 \\<le> k` `v \\<in> V` assms(3)\n            by auto\n          ultimately show \" card {ps. ext v ps} = k ^ l\" by (metis card_image)\n        qed\n      moreover have \"\\<forall>v1 v2. v1 \\<noteq> v2 \\<longrightarrow> {n. ext v1 n} \\<inter> {n. ext v2 n} = {}\" using ext by auto\n      moreover have \"(\\<Union>v\\<in>V. {n. ext v n})=T l\" \n        proof -\n          have \"\\<And>ps. ps\\<in>(\\<Union>v\\<in>V. {n. ext v n}) \\<Longrightarrow> ps\\<in>T l\" using T\n            proof -\n              fix ps assume \"ps\\<in>(\\<Union>v\\<in>V. {n. ext v n})\"\n              then obtain v where \"v\\<in>V\" \"adj_path v (tl ps)\" \"hd ps = v\" \"length ps = l + 1\"\n                using ext by auto\n              hence \"length ps = l + 1\" and  \"adj_path (hd ps) (tl ps)\" by auto\n              thus \"ps\\<in>T l\" using T by auto\n            qed\n          moreover have \"\\<And>ps. ps\\<in>T l \\<Longrightarrow> ps\\<in>(\\<Union>v\\<in>V. {n. ext v n})\" \n            proof -\n              fix ps assume \"ps\\<in>T l\"\n              hence \"length ps = l + 1\" and  \"adj_path (hd ps) (tl ps)\" using T by auto\n              moreover then obtain v where \"v=hd ps\" \"v\\<in>V\" \n                by (metis adj_path.simps(1) adj_path.simps(2) adjacent_V(1) list.exhaust)\n              ultimately show \"ps\\<in>(\\<Union>v\\<in>V. {n. ext v n})\" using ext by auto\n            qed\n          ultimately show ?thesis by auto\n        qed\n      ultimately have \"card (T l) = card V * k^l\" \n        using card_partition'[of V ext \"k^l\"] ` 4 \\<le> k ` assms(3) mult.commute nat_one_le_power\n        by auto\n      moreover have \"card V=(k * k - k + 1)\" \n        using total_v_num[OF friend_assm,of k] k_adj degree_adjacent `finite E` `finite V` \n          `card V\\<ge>2` `4 \\<le> k` card_gt_0_iff\n        by force\n      ultimately show \"card (T l) = (k * k - k + 1) * k ^ l\" by auto\n    qed\n  obtain C where C:\"C=(\\<lambda>l::nat. {ps. length ps = l+1 \\<and> adj_path (hd ps) (tl ps) \n      \\<and> adjacent (last ps) (hd ps)})\" by auto\n  obtain C_star where C_star:\"C_star=(\\<lambda>l::nat. {ps. length ps = l+1 \\<and> adj_path (hd ps) (tl ps) \n      \\<and> (last ps) = (hd ps)})\" by auto\n  have \"\\<And>l::nat. card (C (l+1)) = k* card (C_star l) + card (T l - C_star l)\"\n    proof -\n      fix l::nat\n      have \"C (l+1) = {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> adjacent (last ps) (hd ps)\n          \\<and> last (butlast ps)=hd ps} \\<union> {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n          adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}\" using C by auto\n      moreover have \" {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> adjacent (last ps) (hd ps)\n          \\<and> last (butlast ps)=hd ps} \\<inter> {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n          adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps} ={}\" by auto\n      moreover have \"finite (C (l+1))\" \n        proof -\n          have \"C (l+1) \\<subseteq> T (l+1)\" using C T by auto\n          moreover have \"(k * k - k + 1) * k ^ (l + 1)\\<noteq>0\" using `k\\<ge>4` by auto\n          hence \"finite (T (l+1))\" using T_count[of \"l+1\"] by (metis card_infinite) \n          ultimately show ?thesis by (metis finite_subset)\n        qed\n      ultimately have \"card (C (l+1)) = card {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \n          \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)=hd ps} + card {ps. length ps = l+2 \\<and> \n          adj_path (hd ps) (tl ps) \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}\" \n        using card_Un_disjoint[of \"{ps. length ps = l + 2 \\<and> adj_path (hd ps) (tl ps) \\<and> adjacent \n          (last ps) (hd ps) \\<and> last (butlast ps) = hd ps}\" \"{ps. length ps = l + 2 \\<and> adj_path (hd ps) \n          (tl ps) \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps) \\<noteq> hd ps}\"] finite_Un\n        by auto\n      moreover have \"card {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \n          \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)=hd ps}=k * card (C_star l)\" \n        proof -\n          obtain ext where ext: \"ext=(\\<lambda>ps ps'.  ps'\\<noteq>[] \\<and> (butlast ps'=ps) \n              \\<and> adj_path (hd ps') (tl ps'))\" by auto\n          have \"\\<forall>ps\\<in>(C_star l). card {ps'. ext ps ps'} = k\" \n            proof \n              fix ps assume \"ps\\<in>C_star l\"\n              hence \"length ps = l + 1\" and \"adj_path (hd ps) (tl ps)\" and \"last ps = hd ps\" \n                using C_star by auto\n              obtain qs where qs:\"qs={v. adjacent (last ps) v}\" by auto\n              obtain app where app:\"app=(\\<lambda>v. ps@[v])\" by auto\n              have \"app ` qs = {ps'. ext ps ps'}\" \n                proof -\n                  have \"\\<And>x. x\\<in>app`qs \\<Longrightarrow> x\\<in>{ps'. ext ps ps'}\" \n                    proof \n                      fix x assume \"x \\<in> app ` qs\"\n                      then obtain y where \"adjacent (last ps) y\" \"x=ps@[y]\" using qs app by auto\n                      moreover hence \"adj_path (hd x) (tl x)\" \n                        by (cases \"tl ps = []\", metis adj_path.simps(1) adj_path.simps(2) \n                          adjacent_V(2) append_Nil list.sel(1,3) hd_append snoc_eq_iff_butlast \n                          tl_append2, metis `adj_path (hd ps) (tl ps)` adj_path_app hd_append\n                          last_tl list.sel(2) tl_append2)\n                      ultimately show \"ext ps x\" using ext by (metis snoc_eq_iff_butlast)\n                    qed\n                  moreover have \"\\<And>x. x\\<in>{ps'. ext ps ps'}\\<Longrightarrow> x\\<in> app`qs\"\n                    proof -\n                      fix x  assume \"x \\<in> {ps'. ext ps ps'}\" \n                      hence \"x\\<noteq>[]\" and \"butlast x=ps\" and \"adj_path (hd x) (tl x)\" \n                        using ext by auto\n                      have \"adjacent (last ps) (last x)\"\n                        proof (cases \"length ps=1\")\n                          case True\n                          hence \"length x=2\" using `butlast x=ps` by auto\n                          then obtain x1 t1 where \"x=x1#t1\" and \"length t1=1\" \n                            using Suc_length_conv[of 1 x] by auto\n                          then obtain x2 where \"t1=[x2]\"\n                            using Suc_length_conv[of 0 t1] by auto\n                          have \"x=[x1,x2]\" using `x=x1#t1` `t1=[x2]` by auto\n                          thus \"adjacent (last ps) (last x)\"\n                             using `adj_path (hd x) (tl x)` `butlast x=ps` by auto\n                        next\n                          case False\n                          hence \"tl ps\\<noteq>[]\" \n                            by (metis `length ps = l + 1` add_0_iff add_diff_cancel_left' \n                              length_0_conv length_tl add.commute)\n                          moreover have \"adj_path (hd x) (tl ps @ [last x])\"\n                            using `adj_path (hd x) (tl x)` `butlast x=ps` `x \\<noteq> []`\n                            by (metis append_butlast_last_id calculation list.sel(2) tl_append2)\n                          ultimately have \"adjacent (last (tl ps)) (last x)\" \n                            using adj_path_app'[of \"hd x\" \"tl ps\" \"last x\"]\n                            by auto\n                          thus \"adjacent (last ps) (last x)\" by (metis `tl ps \\<noteq> []` last_tl)\n                        qed\n                      thus \"x \\<in> app ` qs\" using app qs \n                        by (metis `butlast x = ps` `x \\<noteq> []` append_butlast_last_id mem_Collect_eq \n                          rev_image_eqI)\n                    qed\n                  ultimately show ?thesis by auto\n                qed\n              moreover have \"inj_on app qs\" using app unfolding inj_on_def by auto \n              moreover have \"last ps\\<in>V\" \n                using `length ps = l + 1`  `adj_path (hd ps) (tl ps)` adj_path_V \n                by (metis `last ps = hd ps` adj_path.simps(1) last_in_set last_tl subset_code(1))\n              hence \"card qs=k\" using qs k_adj by auto\n              ultimately show \"card {ps'. ext ps ps'} = k\" by (metis card_image)\n            qed\n          moreover have \"finite (C_star l)\" \n            proof -\n              have \"C_star l \\<subseteq> T l\" using C_star T by auto\n              moreover have \"(k * k - k + 1) * k ^ l\\<noteq>0\" using `k\\<ge>4` by auto\n              hence \"finite (T l)\" using T_count[of \"l\"] by (metis card_infinite) \n              ultimately show ?thesis by (metis finite_subset)\n            qed\n          moreover have \"\\<forall>ps1 ps2. ps1 \\<noteq> ps2 \\<longrightarrow> {ps'. ext ps1 ps'} \\<inter> {ps'. ext ps2 ps'} = {}\" \n            using ext by auto\n          moreover have \"(\\<Union>ps\\<in>(C_star l). {ps'. ext ps ps'}) = {ps. length ps = l+2 \n              \\<and> adj_path (hd ps) (tl ps) \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)=hd ps}\" \n            proof -\n              have \"\\<And>x. x\\<in>(\\<Union>ps\\<in>(C_star l). {ps'. ext ps ps'}) \\<Longrightarrow> x\\<in>{ps. length ps = l+2 \n                  \\<and> adj_path (hd ps) (tl ps) \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)=hd ps}\"\n                proof \n                  fix x assume \"x \\<in> (\\<Union>ps\\<in>C_star l. {ps'. ext ps ps'})\"\n                  then obtain ps where \"ps\\<in>C_star l\" \"ext ps x\" by auto\n                  hence \"length ps = l + 1\" and \"adj_path (hd ps) (tl ps)\" and \"last ps = hd ps\" \n                      and \"x \\<noteq> []\" and  \"butlast x = ps\" \"adj_path (hd x) (tl x)\" \n                    using C_star ext by auto\n                  have \"length x = l + 2\" \n                    using ` butlast x = ps ` ` length ps = l + 1 ` length_butlast by auto\n                  moreover have \"adj_path (hd x) (tl x)\" by (metis `adj_path (hd x) (tl x)`)\n                  moreover have \"adjacent (last x) (hd x)\" \n                    proof -\n                      have \"length x\\<ge>2\" using `length x=l+2` by auto\n                      hence \"adjacent (last (butlast x)) (last x)\" using `adj_path (hd x) (tl x)`\n                        by (induct x,auto, metis adj_path.simps(2) append_butlast_last_id \n                          append_eq_Cons_conv, metis adj_path_app' append_butlast_last_id)\n                      hence \"adjacent (last ps) (last x)\" using `butlast x=ps` by auto\n                      hence \"adjacent (hd ps) (last x)\" using `last ps=hd ps` by auto\n                      hence \"adjacent (hd x) (last x)\" \n                        using `butlast x=ps` `length ps=l+1`\n                        by (cases x)  auto\n                      thus ?thesis using adjacent_sym by auto\n                    qed\n                  moreover have \"last (butlast x) = hd x\" \n                    by (metis `butlast x = ps` `last ps = hd ps` `x \\<noteq> []` adjacent_no_loop \n                      butlast.simps(2) calculation(3) list.sel(1) last_ConsL neq_Nil_conv)\n                  ultimately show \"length x = l + 2 \\<and> adj_path (hd x) (tl x) \n                      \\<and> adjacent (last x) (hd x) \\<and> last (butlast x) = hd x\"\n                    by auto\n                qed\n              moreover have \"\\<And>x. x\\<in>{ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \n                  \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)=hd ps} \\<Longrightarrow>  \n                  x\\<in>(\\<Union>ps\\<in>(C_star l). {ps'. ext ps ps'})\" \n                proof -\n                  fix x assume \"x\\<in>{ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \n                      \\<and> adjacent (last ps) (hd ps) \\<and> last (butlast ps)=hd ps}\"\n                  hence \"length x=l+2\" and \"adj_path (hd x) (tl x)\" and \"adjacent (last x) (hd x)\"\n                      and \"last (butlast x)=hd x\" by auto\n                  obtain ps where ps:\"ps=butlast x\" by auto\n                  have \"ps\\<in>C_star l\" \n                    proof -\n                      have \"length ps = l + 1\" using ps `length x=l+2` by auto\n                      moreover have \"hd ps=hd x\" \n                        using ps `length x=l+2` \n                        by (metis (full_types) ` adjacent (last x) (hd x) ` adjacent_no_loop \n                          append_Nil append_butlast_last_id butlast.simps(1) list.sel(1) hd_append2)\n                      hence \"adj_path (hd ps) (tl ps)\" using adj_path_butlast \n                        by (metis `adj_path (hd x) (tl x)` butlast_tl ps)\n                      moreover have \"last ps = hd ps\" \n                        by (metis `hd ps = hd x` `last (butlast x) = hd x` ps)\n                      ultimately show ?thesis using C_star by auto\n                    qed\n                  moreover have \"ext ps x\" using ext \n                    by (metis `adj_path (hd x) (tl x)` `adjacent (last x) (hd x)` \n                      `last (butlast x) = hd x` adjacent_no_loop butlast.simps(1) ps)\n                  ultimately show \"x\\<in>(\\<Union>ps\\<in>(C_star l). {ps'. ext ps ps'})\" by auto\n                qed\n              ultimately show ?thesis by fast\n            qed\n          ultimately show ?thesis using card_partition'[of \"C_star l\" ext k] `k\\<ge>4` by auto\n        qed\n      moreover have \"card {ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n          adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}=card (T l - C_star l)\" \n        proof -\n          obtain app where app:\"app=(\\<lambda>ps. ps@[SOME n. adjacent (last ps) n \\<and> adjacent (hd ps) n])\"\n            by auto\n          have \"\\<And>x. x\\<in>app`(T l - C_star l) \\<Longrightarrow> x\\<in>{ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n              adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}\" \n            proof \n              fix x assume \"x \\<in> app ` (T l - C_star l)\"\n              then obtain ps where \"length ps = l + 1\" \"adj_path (hd ps) (tl ps)\" \"last ps \\<noteq> hd ps\"\n                  \"x=app ps\"\n                using T C_star by auto\n              hence \"last ps\\<in>V\" \n                using adj_path_V[OF `adj_path (hd ps) (tl ps)`]\n                by (cases ps) auto\n              hence \"\\<exists>n. adjacent (last ps) n \\<and> adjacent (hd ps) n\"\n                using adj_path_V'[OF `adj_path (hd ps) (tl ps)`] `last ps\\<noteq>hd ps`  \n                  friend_assm[of \"last ps\" \"hd ps\"]\n                by auto\n              moreover have \"last x=(SOME n. adjacent (last ps) n \\<and> adjacent (hd ps) n)\"\n                using app `x=app ps` by auto\n              ultimately have \"adjacent (last ps) (last x)\" and \"adjacent (hd ps) (last x)\"\n                using someI_ex by (metis (lifting))+ \n              have \"hd x=hd ps\" using `x=app ps` `length ps=l+1` app\n                by (cases ps) auto\n              have \"length x = l + 2\" using `x=app ps` `length ps=l+1` app by auto\n              moreover have \"adj_path (hd x) (tl x)\" \n                proof -\n                  have \"last (tl ps)=last ps\" using `length ps=l+1` \n                    by (metis `last ps \\<noteq> hd ps` list.sel(1,3) last_ConsL last_tl neq_Nil_conv)\n                  moreover have \"length ps\\<noteq>1\" using `last ps \\<noteq> hd ps` \n                    by (metis Suc_eq_plus1_left gen_length_code(1) gen_length_def list.sel(1) \n                      last_ConsL length_Suc_conv neq_Nil_conv)\n                  hence \"tl ps\\<noteq>[]\" using `length ps=l+1` \n                    by (metis add_diff_cancel_right' length_splice length_tl add.commute \n                      splice_Nil2)\n                  ultimately have \"adj_path (hd ps) (tl ps @ [last x])\"\n                    using  adj_path_app[OF `adj_path (hd ps) (tl ps)`,of \"last x\"]  \n                      `adjacent (last ps) (last x)`  \n                    by auto\n                  moreover have \"tl ps @ [last x]=tl x\" \n                    using `x=app ps` app\n                    by (metis ` last x = (SOME n. adjacent (last ps) n \\<and> adjacent (hd ps) n) ` \n                      ` tl ps \\<noteq> [] ` list.sel(2) tl_append2)\n                  ultimately show ?thesis using `hd x=hd ps` by auto\n                qed\n              moreover have \"adjacent (last x) (hd x)\" \n                using `hd x=hd ps` `adjacent (hd ps) (last x)` adjacent_sym by auto\n              moreover have \"last (butlast x) \\<noteq> hd x\" \n                using `last ps \\<noteq> hd ps` `hd x=hd ps`\n                by (metis `x = app ps` app butlast_snoc)\n              ultimately show \"length x = l + 2 \\<and> adj_path (hd x) (tl x) \\<and> adjacent (last x) (hd x) \n                  \\<and> last (butlast x) \\<noteq> hd x\"\n                by auto\n            qed\n          moreover have \"\\<And>x. x\\<in>{ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n              adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}\\<Longrightarrow> x\\<in>app`(T l - C_star l)\"\n            proof -\n              fix x assume \"x\\<in>{ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n                  adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}\"\n              hence \"length x=l+2\" and \"adj_path (hd x) (tl x)\" and \"adjacent (last x) (hd x)\"\n                  and \"last (butlast x)\\<noteq>hd x\"\n                by auto\n              hence \"butlast x\\<in>T l - C_star l\"\n                proof -\n                  have \"length (butlast x) = l + 1\" \n                    using `length x = l + 2` length_butlast by auto\n                  moreover have \"hd (butlast x)=hd x\" \n                    using `length x=l+2` \n                    by (metis append_butlast_last_id butlast.simps(1) calculation diff_add_inverse \n                      diff_cancel2 hd_append length_butlast add.commute num.distinct(1) \n                      one_eq_numeral_iff)\n                  hence \"adj_path (hd (butlast x)) (tl (butlast x))\" \n                    using `adj_path (hd x) (tl x)` by (metis adj_path_butlast butlast_tl)\n                  moreover have \"last (butlast x) \\<noteq> hd (butlast x)\" \n                    using `last (butlast x)\\<noteq>hd x` `hd (butlast x)=hd x` by auto\n                  ultimately show ?thesis using T C_star by auto\n                qed\n              moreover have \"app (butlast x)=x\" using app \n                proof -\n                  have \"last (butlast x)\\<in>V\" \n                    proof (cases \"length x\\<ge>3\")\n                      case True\n                      hence \"last (butlast x)\\<in>set (tl x)\"\n                        proof (induct x)\n                          case Nil\n                          thus ?case by auto\n                        next\n                          case (Cons x1 t1)\n                          have \"length t1<3 \\<Longrightarrow>?case\" \n                            proof -\n                              assume \"length t1<3\"\n                              hence \"length t1=2\" using `3 \\<le> length (x1 # t1)` by auto\n                              then obtain x2 t2 where \"t1=x2#t2\" \"length t2=1\" \n                                using Suc_length_conv[of 1 t1] by auto\n                              then obtain x3 where \"t2=[x3]\"\n                                using  Suc_length_conv[of 0 t2] by auto\n                              have \"t1=[x2,x3]\" using `t1=x2#t2` `t2=[x3]` by auto\n                              thus ?case by auto\n                            qed\n                          moreover have \"length t1\\<ge>3\\<Longrightarrow>?case\"\n                            proof -\n                              assume \"length t1\\<ge>3\"\n                              hence \"last (butlast t1) \\<in> set (tl t1)\" \n                                using Cons.hyps by auto\n                              thus ?case \n                                by (metis butlast.simps(2) in_set_butlastD last.simps last_in_set \n                                  length_butlast length_greater_0_conv length_pos_if_in_set \n                                  length_tl list.sel(3))\n                            qed\n                          ultimately show ?case by force \n                        qed\n                      thus ?thesis using adj_path_V[OF `adj_path (hd x) (tl x)`] by auto\n                    next\n                      case False\n                      hence \"length x=2\" using `length x=l+2`  by auto\n                      then obtain x1 x2 where \"x=[x1,x2]\" \n                        proof -\n                          obtain x1 t1 where \"x=x1#t1\" \"length t1=1\" \n                            using Suc_length_conv[of 1 x] `length x=2` by auto\n                          then obtain x2 where \"t1=[x2]\"\n                            using  Suc_length_conv[of 0 t1] by auto\n                          have \"x=[x1,x2]\" using `x=x1#t1` `t1=[x2]` by auto\n                          thus ?thesis using that by auto\n                        qed\n                      hence \"last (butlast x)=hd x\" by auto\n                      thus ?thesis using adj_path_V'[OF `adj_path (hd x) (tl x)`] by auto\n                    qed\n                  moreover have \"hd (butlast x)=hd x\" using `length x=l+2`\n                    by (metis `adjacent (last x) (hd x)` adjacent_no_loop append_butlast_last_id \n                      butlast.simps(1) list.sel(1) hd_append)\n                  hence  \"hd (butlast x)\\<in>V\" using adj_path_V'[OF `adj_path (hd x) (tl x)`] by auto\n                  moreover have \"last (butlast x)\\<noteq>hd (butlast x)\" \n                    using `last (butlast x)\\<noteq>hd x` `hd (butlast x)=hd x` by auto\n                  ultimately have \"\\<exists>! n. adjacent (last (butlast x)) n \\<and> adjacent (hd (butlast x)) n\" \n                    using friend_assm by auto\n                  moreover have \"length x\\<ge>2\" using `length x=l+2` by auto\n                  hence \"adjacent (last (butlast x)) (last x)\" \n                    using `adj_path (hd x) (tl x)` \n                    by (induct x,auto, metis (full_types) adj_path.simps(2) append_Nil \n                      append_butlast_last_id, metis adj_path_app' append_butlast_last_id)\n                  moreover have \"adjacent (hd (butlast x)) (last x)\" \n                    using `adjacent (last x) (hd x)` `hd (butlast x)=hd x` adjacent_sym\n                    by auto\n                  ultimately have \"(SOME n. adjacent (last (butlast x)) n \n                      \\<and> adjacent (hd (butlast x)) n) = last x\" \n                    using some1_equality by fast \n                  moreover have \"x=(butlast x)@[last x]\" \n                    by (metis `adjacent (last (butlast x)) (last x)` adjacent_no_loop \n                      append_butlast_last_id butlast.simps(1))\n                  ultimately show ?thesis using app by auto\n                qed\n              ultimately show \"x\\<in>app`(T l - C_star l)\" by (metis image_iff)  \n            qed\n          ultimately have \"app`(T l - C_star l)={ps. length ps = l+2 \\<and> adj_path (hd ps) (tl ps) \\<and> \n              adjacent (last ps) (hd ps) \\<and> last (butlast ps)\\<noteq>hd ps}\" by fast\n          moreover have \"inj_on app (T l - C_star l)\" using app unfolding inj_on_def by auto\n          ultimately show ?thesis by (metis card_image)\n        qed\n      ultimately show \"card (C (l + 1)) = k * card (C_star l) + card (T l - C_star l)\" by auto\n    qed\n  hence \"\\<And>l::nat. card (C (l+1)) mod (k-(1::nat))=1\"\n    proof -\n      fix l::nat\n      have \"C_star l \\<subseteq> T l\" using C_star T by auto\n      moreover have \"card (T l)\\<noteq>0\" using T_count `k\\<ge>4` by auto\n      hence \"finite (T l)\" using `k\\<ge>4` by (metis card_infinite)\n      ultimately have \"card (T l - C_star l)=card(T l) - card(C_star l)\" \n        by (metis card_Diff_subset rev_finite_subset) \n      hence \"card (C (l + 1))=k*card (C_star l) + (card (T l) - card (C_star l))\" \n        using `\\<And>l::nat. card (C (l+1)) = k* card (C_star l) + card (T l - C_star l)`\n        by auto\n      also have \"...=k*card (C_star l) + card (T l) - card (C_star l)\" \n        proof -\n          have \"card (T l) \\<ge> card (C_star l)\" \n            using `C_star l \\<subseteq> T l` `finite (T l)` by (metis card_mono)\n          thus ?thesis by auto\n        qed\n      also have \"...=k*card (C_star l) - card (C_star l) + card (T l)\" \n        proof -\n          have \"card (T l) \\<ge> card (C_star l)\" \n            using `C_star l \\<subseteq> T l` `finite (T l)` by (metis card_mono)\n          moreover have \"k*card (C_star l) \\<ge> card (C_star l)\" using `k\\<ge>4` by auto\n          ultimately show ?thesis by auto\n        qed\n      also have \"...=(k-(1::nat))*card(C_star l)+card(T l)\" using `k\\<ge>4` \n        by (metis comm_monoid_mult_class.mult.left_neutral diff_mult_distrib)\n      finally have \"card (C (l + 1))=(k-(1::nat))*card(C_star l)+card(T l)\" .\n      hence \"card (C (l+1)) mod (k-(1::nat)) = card(T l) mod (k-(1::nat))\" using `k>=4` \n        by (metis mod_mult_self3 mult.commute)\n      also have \"...=((k*k-k+1)*k^l) mod (k-(1::nat))\" using T_count by auto\n      also have \"...=((k-(1::nat))*k+1)*k^l  mod (k-(1::nat))\" \n        proof -\n          have \"k*k-k+1=(k-(1::nat))*k+1\" using `k\\<ge>4` by (metis diff_mult_distrib nat_mult_1)\n          thus ?thesis by auto\n        qed\n      also have \"...=1*k^l  mod (k-(1::nat))\" \n        by (metis mod_mult_right_eq mod_mult_self1 add.commute mult.commute)\n      also have \"...=k^l mod (k-(1::nat))\" by auto\n      also have \"...=(k-(1::nat)+1)^l mod (k-(1::nat))\" using `k\\<ge>4` by auto\n      also have \"...=1^l mod (k-(1::nat))\" by (metis mod_add_self2 add.commute power_mod)\n      also have \"...=1 mod (k-(1::nat))\" by auto\n      also have \"...=1\" using `k\\<ge>4` by auto\n      finally show \"card (C (l+1)) mod (k-(1::nat)) =1\" .\n    qed\n  obtain p::nat where \"prime p\" \"p dvd (k-(1::nat))\"  using `k\\<ge>4` \n    by (metis Suc_eq_plus1 Suc_numeral add_One_commute eq_iff le_diff_conv numeral_le_iff  \n      one_le_numeral one_plus_BitM prime_factor_nat semiring_norm(69) semiring_norm(71))\n  hence p_minus_1:\"p-(1::nat)+1=p\" \n    by (metis add_diff_inverse add.commute not_less_iff_gr_or_eq prime_nat_def)\n  hence \"\\<And>l::nat. card (C (l+1)) mod p=1\"\n    using `\\<And>l::nat. card (C (l+1)) mod (k-(1::nat))=1` mod_mod_cancel[OF `p dvd (k-(1::nat))`]\n      `prime p`\n    by (metis mod_if prime_gt_1_nat)\n  hence \"card (C (p-(1::nat))) mod p=1\" \n    by (metis  comm_semiring_1_class.normalizing_semiring_rules(24) dvd_imp_mod_0 gcd_add1_nat \n      gcd_lcm_complete_lattice_nat.bot_unique gcd_lcm_complete_lattice_nat.inf_top_right \n      mod_mod_trivial mult_eq_if nat_mult_1_right p_minus_1)\n  moreover have \"card (C (p-(1::nat))) mod p=0\" using C\n    proof -\n      have closure1:\"\\<And>x. x\\<in>C (p-(1::nat))\\<Longrightarrow> rotate1 x \\<in>C (p-(1::nat))\" \n        proof -\n          fix x assume \"x\\<in>C (p-(1::nat))\"\n          hence \"length x = p\" and  \"adj_path (hd x) (tl x)\" and \"adjacent (last x) (hd x)\" \n            using C p_minus_1 by auto\n          have \"adjacent (last (rotate1 x)) (hd (rotate1 x))\" \n            proof -\n              have \"x\\<noteq>[]\" using `length x=p` `prime p` by auto\n              hence \"adjacent (last (rotate1 x)) (hd (rotate1 x))=adjacent (hd x) (hd (tl x))\"\n                by (metis ` adjacent (last x) (hd x) ` adjacent_no_loop append_Nil list.sel(1,3)\n                  hd_append2 last_snoc list.exhaust rotate1_hd_tl)\n              also have \"...=True\" using `adj_path (hd x) (tl x)` \n                using `adjacent (last x) (hd x)` `x \\<noteq> []`\n                by (metis  adj_path.simps(2) adjacent_no_loop append1_eq_conv append_Nil \n                  append_butlast_last_id list.sel(1,3) list.exhaust)\n              finally show ?thesis by auto\n            qed\n          moreover have \"adj_path (hd (rotate1 x)) (tl (rotate1 x))\" \n            proof -\n              have \"x\\<noteq>[]\" using `length x=p` `prime p` by auto\n              then obtain y ys where \"y=hd x\" \"ys=tl x\" by auto\n              hence  \"adj_path y ys\" and \"adjacent (last ys) y\" and \"ys\\<noteq>[]\" \n                by (metis `adj_path (hd x) (tl x)`, metis `adjacent (last x) (hd x)` `y = hd x` \n                  `ys = tl x` adjacent_no_loop list.sel(1,3) last.simps last_tl list.exhaust\n                  , metis `adjacent (last x) (hd x)` `x \\<noteq> []` `ys = tl x` adjacent_no_loop list.sel(1,3)\n                  last_ConsL neq_Nil_conv)\n              hence \"adj_path (hd (rotate1 x)) (tl (rotate1 x))\n                  =adj_path (hd (ys@[y])) (tl (ys@[y]))\" \n                using `x\\<noteq>[]` `y=hd x` `ys=tl x` by (metis rotate1_hd_tl)\n              also have \"...=adj_path (hd ys) ((tl ys)@[y])\" \n                by (metis `ys \\<noteq> []` hd_append tl_append2)\n              also have \"...=True\" \n                using adj_path_app[OF `adj_path y ys` `ys\\<noteq>[]` `adjacent (last ys) y`] `ys\\<noteq>[]`\n                by (metis adj_path.simps(2) append_Cons list.sel(1,3) list.exhaust)\n              finally show ?thesis by auto\n            qed\n          moreover have \"length (rotate1 x) = p\" using `length x=p` by auto\n          ultimately show \"rotate1 x \\<in> C (p-(1::nat))\" using C p_minus_1 by auto\n        qed\n      have closure:\"\\<And>n x. x\\<in>C (p-(1::nat))\\<Longrightarrow> rotate n x \\<in>C (p-(1::nat))\" \n        proof -\n          fix n x assume \"x\\<in>C (p-(1::nat))\"\n          thus \"rotate n x \\<in>C (p-(1::nat))\"\n            by (induct n,auto,metis One_nat_def closure1)\n        qed\n      obtain r where r:\"r={(x,y). x\\<in>C (p-(1::nat)) \\<and> (\\<exists>n<p. rotate n x=y)}\" by auto \n      have \"\\<And>x. x\\<in>C (p-(1::nat)) \\<Longrightarrow> p dvd card {y.(\\<exists>n<p. rotate n x=y)}\"  \n        proof -\n          fix x assume \"x \\<in> C (p-(1::nat))\"\n          hence \"length x=p\" using C p_minus_1 by auto\n          have \"{y. (\\<exists>n<p. rotate n x=y)}= (\\<lambda>n. rotate n x)` {0..<p}\" by auto\n          moreover have \"\\<And>n1 n2. n1\\<in>{0..<p} \\<Longrightarrow> n2\\<in>{0..<p} \\<Longrightarrow> n1\\<noteq>n2 \\<Longrightarrow> rotate n1 x\\<noteq>rotate n2 x\" \n            proof \n              fix n1 n2 assume \"n1 \\<in> {0..<p}\" \"n2 \\<in> {0..<p}\" \"n1 \\<noteq> n2\" \"rotate n1 x = rotate n2 x\"\n              { fix n1 n2  \n                assume \"n1 \\<in> {0..<p}\" \"n2 \\<in> {0..<p}\" \"rotate n1 x = rotate n2 x\" \"n1>n2\"\n                obtain s::nat where \"s*(n1-n2) mod p=1\" \"s>0\" \n                  proof -\n                    have \"n1-n2>0\" and \"n1-n2<p\" \n                      using `n1 \\<in> {0..<p}` `n2 \\<in> {0..<p}` `n1>n2` by auto\n                    hence \"coprime (n1 - n2) p\" using `prime p` \n                      by (metis (full_types) gcd_nat.commute nat_dvd_not_less prime_imp_coprime_nat)\n                    hence  \"\\<exists>x. [(n1-n2) * x = 1] (mod p)\" by (metis cong_solve_coprime_nat)\n                    then obtain s::nat where \"s*(n1-n2) mod p=1\" \n                      by (metis `card (C (p-(1::nat))) mod p = 1` cong_nat_def mod_mod_trivial \n                        mult.commute)\n                    moreover hence \"s>0\" by (metis mod_0 mult_0 neq0_conv zero_neq_one) \n                    ultimately show ?thesis using that by auto \n                  qed\n                have \"rotate (s*n1) x=rotate (s*n2) x\" \n                  using `rotate n1 x=rotate n2 x`\n                  by (induct s,auto,metis comm_semiring_1_class.normalizing_semiring_rules(24) \n                    rotate_rotate)\n                hence \"rotate (s*n1 - s*n2) x= x\" \n                  using rotate_diff by auto\n                hence \"rotate (s*(n1-n2)) x=x\" by (metis diff_mult_distrib mult.commute)\n                hence \"rotate 1 x = x\" using `s*(n1-n2) mod p=1` `length x=p` \n                  by (metis rotate_conv_mod) \n                hence \"rotate1 x=x\" by auto\n                have \"hd x=hd (tl x)\" using `prime p` `length x=p` \n                  proof -\n                    have \"length x\\<ge>2\" using `prime p` `length x=p` by auto\n                    hence \"length (tl x)\\<ge>1\" by force\n                    hence \"x\\<noteq>[]\" and \"tl x\\<noteq>[]\" by auto+\n                    hence \"x=(hd x)#(hd (tl x))#(tl (tl x))\" using hd_Cons_tl by auto\n                    hence \"(hd (tl x))#(tl (tl x))@[hd x]=(hd x)#(hd (tl x))#(tl (tl x))\"\n                      using `rotate1 x = x` by (metis Cons_eq_appendI rotate1.simps(2))\n                    thus ?thesis by auto\n                  qed\n                moreover have \"hd x\\<noteq>hd (tl x)\"\n                  proof -\n                    have \"adj_path (hd x) (tl x)\" using `x \\<in> C (p-(1::nat))` C by auto\n                    moreover have \"length x\\<ge>2\" using `prime p` `length x=p` by auto\n                    hence \"length (tl x)\\<ge>1\" by force\n                    hence \"tl x\\<noteq>[]\" by force\n                    ultimately have \"adjacent (hd x) (hd (tl x))\" \n                      by (metis adj_path.simps(2) list.sel(1) list.exhaust)\n                    thus ?thesis by (metis adjacent_no_loop)\n                  qed\n                ultimately have False by auto } \n              thus False \n                by (metis `n1 \\<in> {0..<p}` `n1 \\<noteq> n2` `n2 \\<in> {0..<p}` `rotate n1 x = rotate n2 x` \n                  less_linear)\n            qed\n          hence \"inj_on (\\<lambda>n. rotate n x) {0..<p}\" unfolding inj_on_def by fast\n          ultimately have \"card {y. (\\<exists>n<p. rotate n x=y)}=card {0..<p}\" by (metis card_image) \n          hence \"card {y. (\\<exists>n<p. rotate n x=y)}=p\" by auto\n          thus \"p dvd card {y. (\\<exists>n<p. rotate n x=y)}\" by auto\n        qed\n      hence \"\\<forall>X\\<in>C (p-(1::nat)) // r. p dvd card X\" unfolding quotient_def Image_def r by auto\n      moreover have \"refl_on (C (p - 1)) r\" \n        proof -\n          have \"r \\<subseteq> C (p - 1) \\<times> C (p - 1)\" \n            proof \n              fix x assume \"x\\<in>r\"\n              hence \"fst x\\<in>C (p - 1)\" and \"\\<exists>n. snd x=rotate n (fst x)\" using r by auto\n              moreover then obtain n where \"snd x=rotate n (fst x)\" by auto\n              ultimately have \"snd x\\<in>C (p - 1)\" using closure by auto\n              moreover have \"x=(fst x,snd x)\" using `x\\<in>r` r by auto\n              ultimately show  \"x \\<in> C (p - 1) \\<times> C (p - 1)\" using `fst x\\<in> C (p - 1)` \n                by (metis SigmaI)\n            qed\n          moreover have \"\\<forall>x\\<in>C (p - 1). (x, x) \\<in> r\" \n            proof \n              fix x assume \"x \\<in> C (p - 1)\"\n              hence \"rotate 0 x \\<in> C (p - 1)\" using closure by auto\n              moreover have \"0<p\" using `prime p` by auto\n              ultimately have \"(x,rotate 0 x)\\<in> r\" using `x\\<in>C (p - 1 )` r by auto\n              moreover have \"rotate 0 x=x\" by auto\n              ultimately show \"(x,x)\\<in>r\" by auto\n            qed\n          ultimately show ?thesis using refl_on_def by auto\n        qed\n      moreover have \"sym r\" unfolding sym_def \n        proof (rule,rule,rule)\n          fix x y assume \"(x, y) \\<in> r\"\n          hence \"x\\<in>C (p - 1)\" using r by auto\n          hence \"length x=p\" using C p_minus_1 by auto\n          obtain n where \"n<p\" \"rotate n x = y\" using `(x,y)\\<in>r` r by auto\n          hence \"y\\<in> C (p - 1)\" using closure[OF `x\\<in> C (p - 1)`] by auto\n          have \"n=0\\<Longrightarrow>(y, x) \\<in> r\" \n            proof -\n              assume \"n=0\"\n              hence \"x=y\" using `rotate n x=y` by auto\n              thus \"(y,x)\\<in>r\" using `refl_on (C (p - 1)) r` `y \\<in> C (p - 1)` refl_on_def by fast\n            qed\n          moreover have \"n\\<noteq>0 \\<Longrightarrow> (y,x)\\<in>r\" \n            proof -\n              assume \"n\\<noteq>0\"\n              have \"rotate (p-n) y = x\" \n                proof -\n                  have \"rotate (p-n) y = rotate (p-n) (rotate n x)\"\n                    using `rotate n x=y` by auto\n                  also have \"rotate (p-n) (rotate n x)=rotate (p-n+n) x\" \n                    using rotate_rotate by auto\n                  also have \"...=rotate p x\" using `n<p` by auto\n                  also have \"...=rotate 0 x\" using `length x=p` by auto\n                  also have \"...=x\" by auto\n                  finally show ?thesis .\n                qed\n              moreover have \"p-n<p\" using `n<p` `n\\<noteq>0` by auto\n              ultimately show \"(y,x)\\<in>r\" using r `y\\<in> C (p - 1)` by auto\n            qed\n          ultimately show \"(y,x)\\<in>r\" by auto\n        qed\n      moreover have \"trans r\" unfolding trans_def\n        proof (rule,rule,rule,rule,rule)\n          fix x y z assume \"(x, y) \\<in> r\" \"(y, z) \\<in> r\"\n          hence \"x\\<in>C (p - 1)\" using r by auto\n          hence \"length x=p\" using C p_minus_1 by auto\n          obtain n1 n2 where \"n1<p\" \"n2<p\" \"y=rotate n1 x\" \"z=rotate n2 y\" \n            using r `(x,y)\\<in>r` `(y,z)\\<in>r` by auto\n          hence \"z=rotate (n2+n1) x\" by (metis rotate_rotate)\n          hence \"z=rotate ((n2+n1) mod p) x\" using `length x=p` by (metis rotate_conv_mod)\n          moreover have \"(n2+n1) mod p < p\" by (metis `prime p` mod_less_divisor prime_gt_0_nat)\n          ultimately show \"(x,z)\\<in>r\" using `x\\<in> C (p - 1)` r by auto \n        qed\n      moreover have \"finite (C (p - 1))\" \n        by (metis `card (C (p - 1)) mod p = 1` card_eq_0_iff mod_0 zero_neq_one)\n      ultimately have \"p dvd card (C (p-(1::nat)))\" using equiv_imp_dvd_card equiv_def by fast\n      thus \"card (C (p-(1::nat))) mod p=0\" by (metis dvd_eq_mod_eq_0)\n    qed \n  ultimately show False by auto\nqed\n\ntheorem (in valid_unSimpGraph) friendship_thm:\n  assumes friend_assm:\"\\<And>v u. v\\<in>V \\<Longrightarrow> u\\<in>V \\<Longrightarrow> v\\<noteq>u \\<Longrightarrow> \\<exists>! n. adjacent v n \\<and> adjacent u n\"\n      and \"finite V\" \n  shows \"\\<exists>v. \\<forall>n\\<in>V. n\\<noteq>v \\<longrightarrow> adjacent v n\"    \nproof -\n  have \"card V=0 \\<Longrightarrow> ?thesis\"\n    using `finite V`\n    by (metis all_not_in_conv card_seteq empty_subsetI le0)\n  moreover have \"card V=1 \\<Longrightarrow> ?thesis\" \n    proof -\n      assume \"card V=1\"\n      then obtain v where \"V={v}\" \n        using card_eq_SucD[of V 0] by auto\n      hence \"\\<forall>n\\<in>V. n=v\" by auto\n      thus \"\\<exists>v. \\<forall>n\\<in>V. n \\<noteq> v \\<longrightarrow> adjacent v n\" by auto\n    qed\n  moreover have \"card V\\<ge>2 \\<Longrightarrow> ?thesis\" \n    proof -\n      assume \"card V\\<ge>2\"\n      hence \"\\<exists>v\\<in>V. degree v G = 2\" \n        using exist_degree_two[OF friend_assm] `finite V` by auto\n      thus ?thesis \n        using degree_two_windmill[OF friend_assm] `card V\\<ge>2` `finite V` by auto\n    qed\n  ultimately show ?thesis by force\nqed\n\nend  \n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Koenigsberg_Friendship/FriendshipTheory.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.8459424411924673, "lm_q1q2_score": 0.7531376661004803}}
{"text": "theory BExp imports AExp begin\n\ndatatype bexp = Bc bool | Not bexp | And bexp bexp | Less aexp aexp\n\ntext_raw\\<open>\\snip{BExpbvaldef}{1}{2}{%\\<close>\nfun bval :: \"bexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"bval (Bc v) s = v\" |\n\"bval (Not b) s = (\\<not> bval b s)\" |\n\"bval (And b\\<^sub>1 b\\<^sub>2) s = (bval b\\<^sub>1 s \\<and> bval b\\<^sub>2 s)\" |\n\"bval (Less a\\<^sub>1 a\\<^sub>2) s = (aval a\\<^sub>1 s < aval a\\<^sub>2 s)\"\ntext_raw\\<open>}%endsnip\\<close>\n\nvalue \"bval (Less (V ''x'') (Plus (N 3) (V ''y'')))\n            <''x'' := 3, ''y'' := 1>\"\n\n\nsubsection \"Constant Folding\"\n\ntext\\<open>Optimizing constructors:\\<close>\n\ntext_raw\\<open>\\snip{BExplessdef}{0}{2}{%\\<close>\nfun less :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"less (N n\\<^sub>1) (N n\\<^sub>2) = Bc(n\\<^sub>1 < n\\<^sub>2)\" |\n\"less a\\<^sub>1 a\\<^sub>2 = Less a\\<^sub>1 a\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\n\n\ntext_raw\\<open>\\snip{BExpanddef}{2}{2}{%\\<close>\nfun \"and\" :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"and (Bc True) b = b\" |\n\"and b (Bc True) = b\" |\n\"and (Bc False) b = Bc False\" |\n\"and b (Bc False) = Bc False\" |\n\"and b\\<^sub>1 b\\<^sub>2 = And b\\<^sub>1 b\\<^sub>2\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma bval_and[simp]: \"bval (and b1 b2) s = (bval b1 s \\<and> bval b2 s)\"\napply(induction b1 b2 rule: and.induct)\napply simp_all\ndone\n\ntext_raw\\<open>\\snip{BExpnotdef}{2}{2}{%\\<close>\nfun not :: \"bexp \\<Rightarrow> bexp\" where\n\"not (Bc True) = Bc False\" |\n\"not (Bc False) = Bc True\" |\n\"not b = Not b\"\ntext_raw\\<open>}%endsnip\\<close>\n\nlemma bval_not[simp]: \"bval (not b) s = (\\<not> bval b s)\"\napply(induction b rule: not.induct)\napply simp_all\ndone\n\ntext\\<open>Now the overall optimizer:\\<close>\n\ntext_raw\\<open>\\snip{BExpbsimpdef}{0}{2}{%\\<close>\nfun bsimp :: \"bexp \\<Rightarrow> bexp\" where\n\"bsimp (Bc v) = Bc v\" |\n\"bsimp (Not b) = not(bsimp b)\" |\n\"bsimp (And b\\<^sub>1 b\\<^sub>2) = and (bsimp b\\<^sub>1) (bsimp b\\<^sub>2)\" |\n\"bsimp (Less a\\<^sub>1 a\\<^sub>2) = less (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\ntext_raw\\<open>}%endsnip\\<close>\n\nvalue \"bsimp (And (Less (N 0) (N 1)) b)\"\n\nvalue \"bsimp (And (Less (N 1) (N 0)) (Bc True))\"\n\ntheorem \"bval (bsimp b) s = bval b s\"\napply(induction b)\napply simp_all\ndone\n\nend", "meta": {"author": "RinGotou", "repo": "Isabelle-Practice", "sha": "41fb1aff3b7a08e010055bd5c887480d09cbfa05", "save_path": "github-repos/isabelle/RinGotou-Isabelle-Practice", "path": "github-repos/isabelle/RinGotou-Isabelle-Practice/Isabelle-Practice-41fb1aff3b7a08e010055bd5c887480d09cbfa05/from_csem_book/BExp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.7530071421067279}}
{"text": "section {*control\\_theory\\_on\\_languages*}\ntheory control_theory_on_languages\n\nimports \n  PRJ_04__ENTRY\n\nbegin\n\ndefinition nonblockingness_language :: \"\n  '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> bool\" where\n  \"nonblockingness_language A B \\<equiv>\n  A \\<subseteq> prefix_closure B\"\n\nlemma example1_nonblockingness_language: \"\n  nonblockingness_language {[0], [0, 1]} {[0, 1, 2]}\"\n  apply(simp add: nonblockingness_language_def prefix_closure_def prefix_def)\n  done\n\nlemma example2_nonblockingness_language: \"\n  \\<not> nonblockingness_language {[0, 1, 2, 3], [0, 1, 2]} {[0, 1, 2]}\"\n  apply(simp add: nonblockingness_language_def prefix_closure_def prefix_def)\n  done\n\nlemma example3_nonblockingness_language: \"\n  \\<not> nonblockingness_language {[1::nat]} {[0, 1, 2]}\"\n  apply(simp add: nonblockingness_language_def prefix_closure_def prefix_def)\n  done\n\ndefinition controllable_language :: \"\n  '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> bool\" where\n  \"controllable_language A \\<Sigma>UC L \\<equiv>\n  (append_alphabet A \\<Sigma>UC) \\<inter> L \\<subseteq> A\"\n\nlemma example2_controllable_language: \"\n  controllable_language { [] , [ 0 ] } { 0 } { [ 0 ] }\"\n  apply(simp add: _controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n  done\n\nlemma example3_controllable_language: \"\n  \\<not> controllable_language { [] } { 0 } { [ 0 ] }\"\n  apply(simp add: _controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n  done\n\nlemma example4_controllable_language: \"\n  controllable_language { [] , [ 1 ] , [ 1, 0 ] , [ 1, 0, 2 ] } { 0 } { [ 1, 0 ] }\"\n  apply(simp add: _controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n  done\n\nlemma example5_controllable_language: \"\n  \\<not> controllable_language { [] , [ 1 ] , [ 1, 0, 2 ] } { 0 } { [ 1, 0 ] }\"\n  apply(simp add: _controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n  done\n\ndefinition controllable_word :: \"\n  '\\<Sigma> list\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> bool\" where\n  \"controllable_word w Luc L A \\<equiv>\n  \\<forall>u  \\<in> Luc. w @ u  \\<in> L \\<longrightarrow> w @ u  \\<in> A\"\n\nlemma example1_controllable_word: \"\n  controllable_word [] {[0]} (kleene_star {0,1}) {[],[0]}\"\n  apply(simp add: controllable_word_def kleene_star_def)\n  done\n\nlemma example2_controllable_word: \"\n  \\<not> controllable_word [] (kleene_star {0}) (kleene_star {0,1}) {[],[0]}\"\n  apply(simp add: controllable_word_def kleene_star_def)\n  apply(rule_tac\n      x = \"[0,0]\"\n      in exI)\n  apply(clarsimp)\n  done\n\ntheorem Soundness_of_Controllable_Word: \"\n  (\\<forall>w  \\<in> A. controllable_word w (alphabet_to_language \\<Sigma>UC) L A) \\<longleftrightarrow> controllable_language A \\<Sigma>UC L\"\n  apply(simp add: controllable_word_def controllable_language_def append_alphabet_def alphabet_to_language_def append_language_def)\n  apply(force)\n  done\n\ndefinition controllable_sublanguage :: \"\n  '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> '\\<Sigma> list set\n  \\<Rightarrow> bool\" where\n  \"controllable_sublanguage A1 Luc L A2 \\<equiv>\n  \\<forall>w  \\<in> A1. controllable_word w Luc L A2\"\n\ntheorem Soundness_of_Controllable_Sublanguage: \"\n  controllable_sublanguage A (alphabet_to_language SU) L A \\<longleftrightarrow> controllable_language A SU L\"\n  apply(simp add: alphabet_to_language_def controllable_language_def controllable_sublanguage_def append_alphabet_def append_language_def controllable_word_def)\n  apply(force)\n  done\n\nlemma nonblockingness_languageclosedUnderSubset: \"\n  A\\<subseteq>B\n  \\<Longrightarrow> nonblockingness_language B C\n  \\<Longrightarrow> nonblockingness_language A C\"\n  apply(simp add: nonblockingness_language_def)\n  done\n\nlemma nonblockingness_languagetriv: \"\n  nonblockingness_language (prefix_closure B) B\"\n  apply(simp add: nonblockingness_language_def prefix_closure_def prefix_def)\n  done\n\nlemma nonblockingness_language_sym: \"\n  nonblockingness_language A (A\\<inter>B)\n  \\<Longrightarrow> nonblockingness_language A (B\\<inter>A)\"\n  apply(rule_tac\n      s = \"A\\<inter>B\"\n      and t = \"B\\<inter>A\"\n      in ssubst)\n   apply(auto)\n  done\n\ndefinition Nonblockingness :: \"'\\<Sigma> list set \\<Rightarrow> '\\<Sigma> list set \\<Rightarrow> bool\" where\n  \"Nonblockingness A B \\<equiv> (A = prefix_closure B)\"\n\ndefinition Nonblockingness2 :: \"'\\<Sigma> list set \\<Rightarrow> '\\<Sigma> list set \\<Rightarrow> bool\" where\n  \"Nonblockingness2 A B \\<equiv> (A\\<supseteq> prefix_closure B)\"\n\nlemma nonblockingness_language_subset: \"\n  nonblockingness_language A' B\n  \\<Longrightarrow> A \\<subseteq> A'\n  \\<Longrightarrow> nonblockingness_language A B\"\n  apply(simp add: nonblockingness_language_def)\n  done\n\nlemma NonblockingnessI: \"\n  nonblockingness_language A B\n  \\<Longrightarrow> Nonblockingness2 A B\n  \\<Longrightarrow> Nonblockingness A B\"\n  apply(simp add: Nonblockingness_def nonblockingness_language_def Nonblockingness2_def)\n  done\n\nlemma NonblockingnessE1: \"\n  Nonblockingness A B\n  \\<Longrightarrow> nonblockingness_language A B\"\n  apply(simp add: Nonblockingness_def nonblockingness_language_def)\n  done\n\nlemma NonblockingnessE2: \"\n  Nonblockingness A B\n  \\<Longrightarrow> Nonblockingness2 A B\"\n  apply(simp add: Nonblockingness_def Nonblockingness2_def)\n  done\n\nlemma nonblockingness_language_and_Nonblockingness2_EQ: \"\n  nonblockingness_language A B\n  \\<Longrightarrow> Nonblockingness2 A B\n  \\<Longrightarrow> A=prefix_closure B\"\n  apply(simp add: nonblockingness_language_def Nonblockingness2_def)\n  done\n\nlemma nonblockingness_language_to_perfect_langBF: \"\n  nonblockingness_language UM M\n  \\<Longrightarrow> M \\<subseteq> UM\n  \\<Longrightarrow> prefix_closure UM = UM\n  \\<Longrightarrow> UM = prefix_closure M\"\n  apply(simp add: nonblockingness_language_def)\n  apply(rule order_antisym)\n   apply(clarsimp)\n  apply(clarsimp)\n  apply(rename_tac x)(*strict*)\n  apply(simp add: prefix_closure_def)\n  apply(force)\n  done\n\nlemma prefix_closure_closed_sets_closed_under_intersection: \"\n  A = prefix_closure A\n  \\<Longrightarrow> B = prefix_closure B\n  \\<Longrightarrow> prefix_closure (A \\<inter> B) = A \\<inter> B\"\n  apply(simp add: prefix_def prefix_closure_def)\n  apply(rule order_antisym)\n   apply(clarsimp)\n   prefer 2\n   apply(clarsimp)\n   apply(rename_tac x)(*strict*)\n   apply(force)\n  apply(rule conjI)\n   apply(clarsimp)\n   apply(rename_tac x c)(*strict*)\n   apply(force)\n  apply(force)\n  done\n\nlemma Cont_vs_controllable_word_strict_case: \"\n  controllable_sublanguage ((prefix_closure{x}) - {x}) X Y Z \\<longleftrightarrow> (\\<forall>w. strict_prefix w x \\<longrightarrow> controllable_word w X Y Z) \"\n  apply(rule order_antisym)\n   apply(simp add: controllable_sublanguage_def)\n   apply(clarsimp)\n   apply(rename_tac w)(*strict*)\n   apply(erule_tac\n      x=\"w\"\n      in ballE)\n    apply(rename_tac w)(*strict*)\n    apply(clarsimp)\n   apply(rename_tac w)(*strict*)\n   apply(simp add: prefix_closure_def prefix_def strict_prefix_def)\n   apply(erule disjE)\n    apply(rename_tac w)(*strict*)\n    apply(force)\n   apply(rename_tac w)(*strict*)\n   apply(force)\n  apply(simp add: controllable_sublanguage_def)\n  apply(clarsimp)\n  apply(rename_tac w')(*strict*)\n  apply(case_tac \"strict_prefix w' x\")\n   apply(rename_tac w')(*strict*)\n   apply(force)\n  apply(rename_tac w')(*strict*)\n  apply(simp add: prefix_closure_def prefix_def strict_prefix_def)\n  apply(rule_tac\n      xs=\"c\"\n      in rev_cases)\n   apply(rename_tac w')(*strict*)\n   apply(force)\n  apply(rename_tac w' ys y)(*strict*)\n  apply(force)\n  done\n\nlemma controllable_sublanguage_vs_controllable_word_strict_case1: \"\n  controllable_sublanguage ((prefix_closure{x}) - {x}) X Y Z\n  \\<Longrightarrow> (\\<forall>w. strict_prefix w x \\<longrightarrow> controllable_word w X Y Z) \"\n  apply (metis Cont_vs_controllable_word_strict_case)\n  done\n\nlemma preserve_controllable_language: \"\n  (\\<And>B. B \\<in> C\n    \\<Longrightarrow> (append_alphabet (prefix_closure B) \\<Sigma>UC) \\<inter> L \\<subseteq> (prefix_closure B))\n  \\<Longrightarrow> (append_alphabet (prefix_closure (\\<Union> C)) \\<Sigma>UC) \\<inter> L \\<subseteq> prefix_closure (\\<Union> C)\"\n  apply(rule_tac\n      P=\"\\<lambda>x. (append_alphabet x \\<Sigma>UC) \\<inter> L \\<subseteq> x\"\n      and t=\"prefix_closure (\\<Union>C)\"\n      and s=\"prefix_closure (\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = B})\"\n      in ssubst)\n   apply(force)\n  apply(rule_tac\n      P=\"\\<lambda>x. (append_alphabet x \\<Sigma>UC) \\<inter> L \\<subseteq> x\"\n      and t=\"prefix_closure (\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = B})\"\n      and s=\"\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (prefix_closure B)}\"\n      in ssubst)\n   apply(simp add: prefix_closure_def prefix_def)\n   apply(thin_tac \"(\\<And>B. B \\<in> C \\<Longrightarrow> append_alphabet {w. \\<exists>v. v \\<in> B \\<and> (\\<exists>c. w @ c = v)} \\<Sigma>UC \\<inter> L \\<subseteq> {w. \\<exists>v. v \\<in> B \\<and> (\\<exists>c. w @ c = v)})\")\n   apply(rule antisym)\n    apply(clarsimp)\n    apply(rename_tac x X c)(*strict*)\n    apply(rule_tac\n      x=\"{w. \\<exists>v. v \\<in> X \\<and> (\\<exists>c. w @ c = v)}\"\n      in exI)\n    apply(force)\n   apply(clarsimp)\n   apply(rename_tac x B c)(*strict*)\n   apply(rule_tac\n      x=\"x@c\"\n      in exI)\n   apply(force)\n  apply(rule_tac\n      P=\"\\<lambda>x. x \\<inter> L \\<subseteq> (\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (prefix_closure B)})\"\n      and t=\"append_alphabet (\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (prefix_closure B)}) \\<Sigma>UC\"\n      and s=\"\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = append_alphabet (prefix_closure B) \\<Sigma>UC}\"\n      in ssubst)\n   apply (simp add: append_alphabet_def append_language_def alphabet_to_language_def)\n   apply(rule antisym)\n    apply(clarsimp)\n    apply(rename_tac v B s)(*strict*)\n    apply(rule_tac\n      x=\"{w. \\<exists>v\\<in> prefix_closure B. \\<exists>s\\<in> \\<Sigma>UC. w = v @ [s]}\"\n      in exI)\n    apply(blast)\n   apply(clarsimp)\n   apply(rename_tac B v s)(*strict*)\n   apply(rule_tac\n      x=\"prefix_closure B\"\n      in exI)\n   apply(blast)\n  apply(rule_tac\n      P=\"\\<lambda>x. x \\<subseteq> (\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (prefix_closure B)})\"\n      and t=\"\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = append_alphabet (prefix_closure B) \\<Sigma>UC} \\<inter> L\"\n      and s=\"\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (append_alphabet (prefix_closure B) \\<Sigma>UC) \\<inter> L}\"\n      in ssubst)\n   apply (metis Int_commute UN_eq UN_extend_simps(4))\n  apply(clarsimp)\n  apply(rename_tac x B)(*strict*)\n  apply(erule_tac\n      x=\"B\"\n      in meta_allE)\n  apply(clarsimp)\n  apply(rule_tac\n      x=\"(prefix_closure B)\"\n      in exI)\n  apply(rule conjI)\n   apply(rename_tac x B)(*strict*)\n   apply(rule_tac\n      x=\"B\"\n      in exI)\n   apply(clarsimp)\n  apply(rename_tac x B)(*strict*)\n  apply(force)\n  done\n\nlemma preserve_controllable_language2: \"\n  (\\<And>B. B \\<in> C\n    \\<Longrightarrow> controllable_language (prefix_closure B) \\<Sigma>UC L)\n    \\<Longrightarrow> controllable_language (prefix_closure (\\<Union> C)) \\<Sigma>UC L\"\n  apply(simp add: controllable_language_def)\n  apply(rule preserve_controllable_language)\n  apply(rename_tac B)(*strict*)\n  apply(force)\n  done\n\nlemma Sup_Cont_contained_lang: \"\n  (\\<And>X. X\\<in> A \\<Longrightarrow> controllable_language X SigmaUC P)\n  \\<Longrightarrow> controllable_language (Sup A) SigmaUC P\"\n  apply(unfold SupDES_def InfDES_def Inf_DES_ext_def Sup_DES_ext_def topDES_def botDES_def top_DES_ext_def bot_DES_ext_def sup_DES_ext_def inf_DES_ext_def supDES_def infDES_def lessDES_def lesseqDES_def less_eq_DES_ext_def less_DES_ext_def des_langUM_def des_langM_def append_alphabet_def append_language_def alphabet_to_language_def controllable_language_def)\n  apply(clarsimp)\n  apply(rename_tac a v s)(*strict*)\n  apply(erule_tac\n      x=\"a\"\n      in meta_allE)\n  apply(clarsimp)\n  apply(rule_tac\n      x=\"a\"\n      in bexI)\n   apply(rename_tac a v s)(*strict*)\n   apply(force)\n  apply(rename_tac a v s)(*strict*)\n  apply(force)\n  done\n\nlemma contSubset2: \"\n  controllable_language A \\<Sigma>UC L\n  \\<Longrightarrow> controllable_language (A \\<inter> L) \\<Sigma>UC L\"\n  apply(simp add: controllable_language_def)\n  apply(simp add: append_alphabet_def append_language_def alphabet_to_language_def)\n  apply(force)\n  done\n\nlemma preservePrec: \"\n  (\\<And>B. B \\<in> C \\<Longrightarrow> B = prefix_closure B)\n  \\<Longrightarrow> \\<Union> C = prefix_closure (\\<Union> C)\"\n  apply(subgoal_tac \"\\<Union>C = \\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = B}\")\n   prefer 2\n   apply(force)\n  apply(subgoal_tac \"prefix_closure (\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = B}) = \\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (prefix_closure B)}\")\n   prefer 2\n   apply (simp add: prefix_closure_def prefix_def)\n   apply(rule order_antisym)\n    apply(clarsimp)\n    apply(rename_tac x xa c)(*strict*)\n    apply(erule_tac\n      x=\"xa\"\n      in meta_allE)\n    apply(clarsimp)\n    apply(rule_tac\n      x=\"{w. \\<exists>v. v \\<in> xa \\<and> (\\<exists>c. w @ c = v)}\"\n      in exI)\n    apply(clarsimp)\n    apply(rule conjI)\n     apply(rename_tac x xa c)(*strict*)\n     apply(rule_tac\n      x=\"xa\"\n      in exI)\n     apply(force)\n    apply(rename_tac x xa c)(*strict*)\n    apply(force)\n   apply(force)\n  apply(force)\n  done\n\ntheorem precCanBePulledIn: \"\n  \\<Union> {A. P A \\<and> A = prefix_closure A}\n  = prefix_closure (\\<Union> {A. P (prefix_closure A)})\"\n  apply(rule_tac\n      P=\"\\<lambda>x. x=prefix_closure (\\<Union>{A. P (prefix_closure A)})\"\n      and s=\"prefix_closure(\\<Union>{A. P A \\<and> A = prefix_closure A})\"\n      in ssubst)\n   apply(rule preservePrec)\n   apply(rename_tac B)(*strict*)\n   apply(clarsimp)\n  apply(simp add: prefix_closure_def)\n  apply(rule antisym)\n   apply(clarsimp)\n   apply(rename_tac x v xa)(*strict*)\n   apply(rule_tac\n      x=\"v\"\n      in exI)\n   apply(rule conjI)\n    apply(rename_tac x v xa)(*strict*)\n    apply(rule_tac\n      x=\"xa\"\n      in exI)\n    apply(simp)\n   apply(rename_tac x v xa)(*strict*)\n   apply(simp)\n  apply(clarsimp)\n  apply(rename_tac x v xa)(*strict*)\n  apply(rule_tac\n      x=\"v\"\n      in exI)\n  apply(rule conjI)\n   apply(rename_tac x v xa)(*strict*)\n   apply(rule_tac\n      x=\"prefix_closure{w. \\<exists>v. v \\<in> xa \\<and> w \\<sqsubseteq> v}\"\n      in exI)\n   apply(rule conjI)\n    apply(rename_tac x v xa)(*strict*)\n    apply(fold prefix_closure_def)\n    apply(rule_tac\n      P=\"\\<lambda>x. P x\"\n      and s=\"prefix_closure xa\"\n      in ssubst)\n     apply(rename_tac x v xa)(*strict*)\n     apply(rule sym)\n     apply(rule prefix_closure_idempotent)\n    apply(rename_tac x v xa)(*strict*)\n    apply(simp)\n   apply(rename_tac x v xa)(*strict*)\n   apply(rule conjI)\n    apply(rename_tac x v xa)(*strict*)\n    apply(rule prefix_closure_idempotent)\n   apply(rename_tac x v xa)(*strict*)\n   apply(rule_tac\n      A=\"xa\"\n      in set_mp)\n    apply(rename_tac x v xa)(*strict*)\n    apply(simp add: prefix_closure_def prefix_def)\n    apply(blast)\n   apply(rename_tac x v xa)(*strict*)\n   apply(blast)+\n  done\n\nlemma preservePrecNonBlock: \"\n  (\\<And>B. B \\<in> C \\<Longrightarrow> B = prefix_closure B \\<and> B \\<subseteq> prefix_closure (D \\<inter> B))\n  \\<Longrightarrow> \\<Union> C \\<subseteq> prefix_closure (D \\<inter> \\<Union> C)\"\n  apply(rule_tac\n      P=\"\\<lambda> x . \\<Union>x \\<subseteq> prefix_closure (D \\<inter> \\<Union>x)\"\n      and t=\"C\"\n      and s=\"{A. \\<exists>B. B \\<in> C \\<and> A = B}\"\n      in ssubst)\n   apply(force)\n  apply(rule_tac\n      P=\"\\<lambda> x . \\<Union>{A. \\<exists>B. B \\<in> C \\<and> A = B} \\<subseteq> prefix_closure x\"\n      and t=\"D\\<inter>\\<Union>{A. \\<exists>B. B \\<in> C \\<and> A = B}\"\n      and s=\"(\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = D \\<inter> B})\"\n      in ssubst)\n   apply(blast)\n  apply(rule_tac\n      P=\"\\<lambda> x . \\<Union>{A. \\<exists>B. B \\<in> C \\<and> A = B} \\<subseteq> x\"\n      and t=\"prefix_closure(\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = D \\<inter> B})\"\n      and s=\"\\<Union>{A. \\<exists>B. B\\<in> C \\<and> A = (prefix_closure (D \\<inter> B))}\"\n      in ssubst)\n   apply(simp add: prefix_closure_def prefix_def)\n   apply(blast)\n  apply(rule Union_mono)\n  apply(rule_tac\n      A=\"{A. \\<exists>B. B \\<in> C \\<and> A = B}\"\n      and B=\"{A. \\<exists>B. B \\<in> C \\<and> A = prefix_closure (D \\<inter> B)}\"\n      in subsetI)\n  apply(rename_tac x)(*strict*)\n  apply(simp)\n  apply(rule_tac\n      x=\"prefix_closure x\"\n      in exI)\n  apply(simp add: prefix_closure_def prefix_def)\n  apply(blast)\n  done\n\ncorollary preservePrecNonBlock_3: \"\n  (\\<And>B. B \\<in> C \\<Longrightarrow> nonblockingness_language B D)\n  \\<Longrightarrow> nonblockingness_language (\\<Union> C) D\"\n  apply(subgoal_tac \"C = {A. A\\<in> C \\<and> nonblockingness_language A D}\")\n   prefer 2\n   apply(rule equalityI)\n    apply(rule subsetI)\n    apply(rename_tac x)(*strict*)\n    apply(clarsimp)\n   apply(force)\n  apply(simp add: nonblockingness_language_def)\n  apply(clarsimp)\n  apply(rename_tac x X)(*strict*)\n  apply(rule_tac\n      A=\"X\"\n      in set_mp)\n   apply(rename_tac x X)(*strict*)\n   apply(fold nonblockingness_language_def)\n   apply(force)\n  apply(rename_tac x X)(*strict*)\n  apply(force)\n  done\n\nlemma helpLem: \"\n  \\<forall>C. P C \\<longrightarrow> (C = prefix_closure C\n              \\<and> C \\<subseteq> prefix_closure (B \\<inter> C)\n              \\<and> controllable_language C \\<Sigma>UC L)\n  \\<Longrightarrow> controllable_language (prefix_closure (B \\<inter> \\<Union> Collect P)) \\<Sigma>UC L\"\n  apply(simp add: controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n  apply(clarsimp)\n  apply(rename_tac v s)(*strict*)\n  apply(rule_tac\n      A=\"\\<Union>Collect P\"\n      in set_mp)\n   apply(rename_tac v s)(*strict*)\n   apply(rule preservePrecNonBlock)\n   apply(rename_tac v s Ba)(*strict*)\n   apply(simp)\n  apply(rename_tac v s)(*strict*)\n  apply(rule_tac\n      A=\"prefix_closure (\\<Union>(Collect P))\"\n      in set_mp)\n   apply(rename_tac v s)(*strict*)\n   apply(subgoal_tac \"prefix_closure (\\<Union>Collect P) = \\<Union>Collect P\")\n    apply(rename_tac v s)(*strict*)\n    apply(blast)\n   apply(rename_tac v s)(*strict*)\n   apply(rule sym)\n   apply(rule preservePrec)\n   apply(rename_tac v s Ba)(*strict*)\n   apply(blast)\n  apply(rename_tac v s)(*strict*)\n  apply(subgoal_tac \"v\\<in> prefix_closure (\\<Union>Collect P)\")\n   apply(rename_tac v s)(*strict*)\n   apply(subgoal_tac \"controllable_language (prefix_closure(\\<Union>Collect P)) \\<Sigma>UC L\")\n    apply(rename_tac v s)(*strict*)\n    apply(simp add: controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n    apply(blast)\n   apply(rename_tac v s)(*strict*)\n   apply(simp add: controllable_language_def)\n   apply(rule_tac\n      C=\"(Collect P)\"\n      and \\<Sigma>UC=\"\\<Sigma>UC\"\n      and L=\"L\"\n      in preserve_controllable_language)\n   apply(rename_tac v s Ba)(*strict*)\n   apply(simp add: append_alphabet_def prefix_closure_def prefix_def append_language_def alphabet_to_language_def)\n  apply(rename_tac v s)(*strict*)\n  apply(rule_tac\n      A=\"prefix_closure (B \\<inter> \\<Union>Collect P)\"\n      in set_mp)\n   apply(rename_tac v s)(*strict*)\n   apply(simp add: prefix_closure_def prefix_def)\n   apply(blast)\n  apply(rename_tac v s)(*strict*)\n  apply(blast)\n  done\n\nlemma SCP_UPsol_in_SCP_Controller_Satisfactory_Maximal_Closed_Loop_hlp2_2: \"\n  Pum = prefix_closure Pum\n  \\<Longrightarrow> a = prefix_closure a\n  \\<Longrightarrow> a \\<inter> Pum = prefix_closure (a \\<inter> Pum)\"\n  apply(rule sym)\n  apply(rule prefix_closure_intersection3)\n   apply(simp)+\n  done\n\nlemma SCP_UPsol_in_SCP_Controller_Satisfactory_Maximal_Closed_Loop_hlp2_3: \"\n  b \\<inter> Pm \\<subseteq> Sm\n  \\<Longrightarrow> a \\<inter> Pum \\<subseteq> prefix_closure (b\\<inter>Pm)\n  \\<Longrightarrow> Pum = prefix_closure Pum\n  \\<Longrightarrow> a = prefix_closure a\n  \\<Longrightarrow> Pm \\<subseteq> Pum\n  \\<Longrightarrow> b \\<subseteq> a\n  \\<Longrightarrow> a \\<inter> Pum \\<subseteq> prefix_closure ((Pm \\<inter> Sm) \\<inter> (a \\<inter> Pum))\"\n  apply(rule_tac\n      A=\"a \\<inter> Pum\"\n      and B=\"prefix_closure (b \\<inter> Pm)\"\n      and C=\"(prefix_closure (Pm\\<inter> Sm \\<inter> (a \\<inter> Pum)))\"\n      in subset_trans)\n   apply(simp)\n  apply(rule_tac\n      A=\"prefix_closure(b \\<inter> Pm)\"\n      and B=\"(prefix_closure (Pm\\<inter> Sm \\<inter> (b \\<inter> Pm)))\"\n      and C=\"(prefix_closure (Pm\\<inter>Sm \\<inter> (a \\<inter> Pum)))\"\n      in subset_trans)\n   apply(rule prefix_closure_preserves_subseteq)\n   apply(rule Set.Int_greatest)\n    apply(rule Set.Int_greatest)\n     apply(blast)\n    apply(blast)\n   apply(blast)\n  apply(rule prefix_closure_preserves_subseteq)\n  apply(rule Set.Int_greatest)\n   apply(rule Set.Int_greatest)\n    apply(blast)\n   apply(blast)\n  apply(rule Set.Int_greatest)\n   apply(blast)\n  apply(blast)\n  done\n\nlemma controllable_language_infimum: \"\n  controllable_language C'um \\<Sigma>UC Pum\n  \\<Longrightarrow> controllable_language (C'um \\<inter> Pum) \\<Sigma>UC Pum\"\n  apply(simp add: controllable_language_def append_alphabet_def append_language_def alphabet_to_language_def)\n  apply(clarsimp)\n  apply(rename_tac a v)(*strict*)\n  apply(rule_tac\n      A=\"{w. \\<exists>a\\<in> C'um. \\<exists>b. (\\<exists>v\\<in> \\<Sigma>UC. b = [v]) \\<and> w = a @ b} \\<inter> Pum\"\n      in set_mp)\n   apply(rename_tac a v)(*strict*)\n   apply(force)\n  apply(rename_tac a v)(*strict*)\n  apply(clarsimp)\n  apply(rule_tac\n      x=\"a\"\n      in bexI)\n   apply(rename_tac a v)(*strict*)\n   apply(force)\n  apply(rename_tac a v)(*strict*)\n  apply(force)\n  done\n\nlemma prefix_closedness_closed_under_union: \"\n  prefix_closure A = A\n  \\<Longrightarrow> prefix_closure B = B\n  \\<Longrightarrow> prefix_closure (A \\<union> B) = A \\<union> B\"\n  apply(simp add: prefix_closure_def prefix_def)\n  apply(rule antisym)\n   apply(clarsimp)\n   apply(rename_tac x c)(*strict*)\n   apply(erule disjE)\n    apply(rename_tac x c)(*strict*)\n    apply(force)\n   apply(rename_tac x c)(*strict*)\n   apply(force)\n  apply(clarsimp)\n  apply(rule conjI)\n   apply(force)\n  apply(force)\n  done\n\nlemma SCP_UPsol_in_SCP_Controller_Satisfactory_Maximal_Closed_Loop_hlp2_1: \"\n  b \\<inter> Pm \\<subseteq> Sm\n  \\<Longrightarrow> a \\<inter> Pum \\<subseteq> prefix_closure (b \\<inter> Pm)\n  \\<Longrightarrow> a \\<inter> Pum \\<subseteq> prefix_closure (Pm \\<inter> Sm)\"\n  apply(rule_tac\n      A=\"a \\<inter> Pum\"\n      and B=\"prefix_closure(b \\<inter> Pm)\"\n      and C=\"prefix_closure (Pm \\<inter> Sm)\"\n      in subset_trans)\n   apply(simp)\n  apply(rule prefix_closure_preserves_subseteq)\n  apply(simp)\n  done\n\nend\n", "meta": {"author": "ControllerSynthesis", "repo": "Isabelle", "sha": "fc776edec292363e49785e5d3a752d9f9cfcf1c9", "save_path": "github-repos/isabelle/ControllerSynthesis-Isabelle", "path": "github-repos/isabelle/ControllerSynthesis-Isabelle/Isabelle-fc776edec292363e49785e5d3a752d9f9cfcf1c9/PRJ_04/control_theory_on_languages.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.8311430436757313, "lm_q1q2_score": 0.7530071347429947}}
{"text": "theory Ch2ProfTree0\n  imports Main\nbegin\n\n(* arithmetic Example *)\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where \n\"eval Var x = x\" | \n\"eval (Const c) x = c\" | \n\"eval (Add e1 e2) x = eval e1 x + eval e2 x\" | \n\"eval (Mult e1 e2) x = eval e1 x * eval e2 x\"\n\nfun build_exp:: \"int list \\<Rightarrow> exp\" where \n\"build_exp (x #xs) = Add (Const x) (Mult Var (build_exp xs))\" | \n\"build_exp [] = Const 0\"\n\nfun evalp :: \"int list  \\<Rightarrow> int \\<Rightarrow> int\" where \n\"evalp xs i = eval (build_exp xs) i\"\n\nfun array_add :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list \" where \n\"array_add (x # xs ) (y # ys) = (x+ y) # (array_add xs ys)\"|\n\"array_add xs [] = xs\" | \n\"array_add [] ys = ys\"\n\nfun array_times :: \"int list \\<Rightarrow> int list \\<Rightarrow> int list\" where \n\"array_times (x # xs ) (y # ys) = x * y # (array_add (array_times xs (y#ys)) (array_times [x] ys))\" | \n\"array_times _ _ = []\"\n\nvalue \"array_times [1,1] [1,-1]\"\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where \n\"coeffs Var = [0,1]\" |\n\"coeffs (Const c ) = [c]\" |\n\"coeffs (Add e1 e2) = array_add (coeffs e1) (coeffs e2)\" |\n\"coeffs (Mult e1 e2) = array_times (coeffs e1) (coeffs e2)\"\n\n\nvalue \"evalp [0, 1] (- 1)\"\n\nvalue \"coeffs Var \"\nlemma \"eval (build_exp (array_add (coeffs e1) (coeffs e2))) x = eval e1 x + eval e2 x\"\n  \n  oops\nlemma \"eval (build_exp (array_times (coeffs e1) (coeffs e2))) x = eval e1 x * eval e2 x\"\n  oops\n\n\nlemma \"evalp (coeffs e) x = eval e x \"\n  apply (induction rule:coeffs.induct)\n  apply auto\n  oops\nend", "meta": {"author": "tecty", "repo": "COMP4161", "sha": "95aa77d289c14cb85477c7f91467f81cd66fcd62", "save_path": "github-repos/isabelle/tecty-COMP4161", "path": "github-repos/isabelle/tecty-COMP4161/COMP4161-95aa77d289c14cb85477c7f91467f81cd66fcd62/Ch2ProfTree0.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951680216529, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.7527788180459584}}
{"text": "(*  Title:      HOL/Isar_Examples/Knaster_Tarski.thy\n    Author:     Makarius\n\nTypical textbook proof example.\n*)\n\nsection \\<open>Textbook-style reasoning: the Knaster-Tarski Theorem\\<close>\n\ntheory Knaster_Tarski\n  imports Main \"~~/src/HOL/Library/Lattice_Syntax\"\nbegin\n\n\nsubsection \\<open>Prose version\\<close>\n\ntext \\<open>\n  According to the textbook @{cite \\<open>pages 93--94\\<close> \"davey-priestley\"}, the\n  Knaster-Tarski fixpoint theorem is as follows.\\<^footnote>\\<open>We have dualized the\n  argument, and tuned the notation a little bit.\\<close>\n\n  \\<^bold>\\<open>The Knaster-Tarski Fixpoint Theorem.\\<close> Let \\<open>L\\<close> be a complete lattice and\n  \\<open>f: L \\<rightarrow> L\\<close> an order-preserving map. Then \\<open>\\<Sqinter>{x \\<in> L | f(x) \\<le> x}\\<close> is a fixpoint\n  of \\<open>f\\<close>.\n\n  \\<^bold>\\<open>Proof.\\<close> Let \\<open>H = {x \\<in> L | f(x) \\<le> x}\\<close> and \\<open>a = \\<Sqinter>H\\<close>. For all \\<open>x \\<in> H\\<close> we have\n  \\<open>a \\<le> x\\<close>, so \\<open>f(a) \\<le> f(x) \\<le> x\\<close>. Thus \\<open>f(a)\\<close> is a lower bound of \\<open>H\\<close>, whence\n  \\<open>f(a) \\<le> a\\<close>. We now use this inequality to prove the reverse one (!) and\n  thereby complete the proof that \\<open>a\\<close> is a fixpoint. Since \\<open>f\\<close> is\n  order-preserving, \\<open>f(f(a)) \\<le> f(a)\\<close>. This says \\<open>f(a) \\<in> H\\<close>, so \\<open>a \\<le> f(a)\\<close>.\\<close>\n\n\nsubsection \\<open>Formal versions\\<close>\n\ntext \\<open>\n  The Isar proof below closely follows the original presentation. Virtually\n  all of the prose narration has been rephrased in terms of formal Isar\n  language elements. Just as many textbook-style proofs, there is a strong\n  bias towards forward proof, and several bends in the course of reasoning.\n\\<close>\n\ntheorem Knaster_Tarski:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"\\<exists>a. f a = a\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof -\n    {\n      fix x\n      assume \"x \\<in> ?H\"\n      then have \"?a \\<le> x\" by (rule Inf_lower)\n      with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n      also from \\<open>x \\<in> ?H\\<close> have \"\\<dots> \\<le> x\" ..\n      finally have \"f ?a \\<le> x\" .\n    }\n    then have \"f ?a \\<le> ?a\" by (rule Inf_greatest)\n    {\n      also presume \"\\<dots> \\<le> f ?a\"\n      finally (order_antisym) show ?thesis .\n    }\n    from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n    then have \"f ?a \\<in> ?H\" ..\n    then show \"?a \\<le> f ?a\" by (rule Inf_lower)\n  qed\nqed\n\ntext \\<open>\n  Above we have used several advanced Isar language elements, such as explicit\n  block structure and weak assumptions. Thus we have mimicked the particular\n  way of reasoning of the original text.\n\n  In the subsequent version the order of reasoning is changed to achieve\n  structured top-down decomposition of the problem at the outer level, while\n  only the inner steps of reasoning are done in a forward manner. We are\n  certainly more at ease here, requiring only the most basic features of the\n  Isar language.\n\\<close>\n\ntheorem Knaster_Tarski':\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"\\<exists>a. f a = a\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof (rule order_antisym)\n    show \"f ?a \\<le> ?a\"\n    proof (rule Inf_greatest)\n      fix x\n      assume \"x \\<in> ?H\"\n      then have \"?a \\<le> x\" by (rule Inf_lower)\n      with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n      also from \\<open>x \\<in> ?H\\<close> have \"\\<dots> \\<le> x\" ..\n      finally show \"f ?a \\<le> x\" .\n    qed\n    show \"?a \\<le> f ?a\"\n    proof (rule Inf_lower)\n      from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n      then show \"f ?a \\<in> ?H\" ..\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Isar_Examples/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.8856314783461302, "lm_q1q2_score": 0.7527612221177131}}
{"text": "   \ntheory ReTest\n  imports \"Main\" \nbegin\n\n\nsection {* Sequential Composition of Sets *}\n\ndefinition\n  Sequ :: \"string set \\<Rightarrow> string set \\<Rightarrow> string set\" (\"_ ;; _\" [100,100] 100)\nwhere \n  \"A ;; B = {s1 @ s2 | s1 s2. s1 \\<in> A \\<and> s2 \\<in> B}\"\n\nfun spow where\n  \"spow s 0 = []\"\n| \"spow s (Suc n) = s @ spow s n\"\n\ntext {* Two Simple Properties about Sequential Composition *}\n\nlemma seq_empty [simp]:\n  shows \"A ;; {[]} = A\"\n  and   \"{[]} ;; A = A\"\nby (simp_all add: Sequ_def)\n\nlemma seq_null [simp]:\n  shows \"A ;; {} = {}\"\n  and   \"{} ;; A = {}\"\nby (simp_all add: Sequ_def)\n\ndefinition\n  Der :: \"char \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere\n  \"Der c A \\<equiv> {s. [c] @ s \\<in> A}\"\n\ndefinition \n  Ders :: \"string \\<Rightarrow> string set \\<Rightarrow> string set\"\nwhere  \n  \"Ders s A \\<equiv> {s' | s'. s @ s' \\<in> A}\"\n\nlemma Der_null [simp]:\n  shows \"Der c {} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_empty [simp]:\n  shows \"Der c {[]} = {}\"\nunfolding Der_def\nby auto\n\nlemma Der_char [simp]:\n  shows \"Der c {[d]} = (if c = d then {[]} else {})\"\nunfolding Der_def\nby auto\n\nlemma Der_union [simp]:\n  shows \"Der c (A \\<union> B) = Der c A \\<union> Der c B\"\nunfolding Der_def\nby auto\n\nlemma Der_seq [simp]:\n  shows \"Der c (A ;; B) = (Der c A) ;; B \\<union> (if [] \\<in> A then Der c B else {})\"\nunfolding Der_def Sequ_def\napply (auto simp add: Cons_eq_append_conv)\ndone\n\nlemma seq_image:\n  assumes \"\\<forall>s1 s2. f (s1 @ s2) = (f s1) @ (f s2)\"\n  shows \"f ` (A ;; B) = (f ` A) ;; (f ` B)\"\napply(auto simp add: Sequ_def image_def)\napply(rule_tac x=\"f s1\" in exI)\napply(rule_tac x=\"f s2\" in exI)\nusing assms\napply(auto)\napply(rule_tac x=\"xa @ xb\" in exI)\nusing assms\napply(auto)\ndone\n\nsection {* Kleene Star for Sets *}\n\ninductive_set\n  Star :: \"string set \\<Rightarrow> string set\" (\"_\\<star>\" [101] 102)\n  for A :: \"string set\"\nwhere\n  start[intro]: \"[] \\<in> A\\<star>\"\n| step[intro]:  \"\\<lbrakk>s1 \\<in> A; s2 \\<in> A\\<star>\\<rbrakk> \\<Longrightarrow> s1 @ s2 \\<in> A\\<star>\"\n\nlemma star_cases:\n  shows \"A\\<star> = {[]} \\<union> A ;; A\\<star>\"\nunfolding Sequ_def\nby (auto) (metis Star.simps)\n\n\nfun \n  pow :: \"string set \\<Rightarrow> nat \\<Rightarrow> string set\" (\"_ \\<up> _\" [100,100] 100)\nwhere\n  \"A \\<up> 0 = {[]}\"\n| \"A \\<up> (Suc n) = A ;; (A \\<up> n)\"  \n\nlemma star1: \n  shows \"s \\<in> A\\<star> \\<Longrightarrow> \\<exists>n. s \\<in> A \\<up> n\"\n  apply(induct rule: Star.induct)\n  apply (metis pow.simps(1) insertI1)\n  apply(auto)\n  apply(rule_tac x=\"Suc n\" in exI)\n  apply(auto simp add: Sequ_def)\n  done\n\nlemma star2:\n  shows \"s \\<in> A \\<up> n \\<Longrightarrow> s \\<in> A\\<star>\"\n  apply(induct n arbitrary: s)\n  apply (metis pow.simps(1) Star.simps empty_iff insertE)\n  apply(auto simp add: Sequ_def)\n  done\n\nlemma star3:\n  shows \"A\\<star> = (\\<Union>i. A \\<up> i)\"\nusing star1 star2\napply(auto)\ndone\n\nlemma star4:\n  shows \"s \\<in> A \\<up> n \\<Longrightarrow> \\<exists>ss. s = concat ss \\<and> (\\<forall>s' \\<in> set ss. s' \\<in> A)\"\n  apply(induct n arbitrary: s)\n  apply(auto simp add: Sequ_def)\n  apply(rule_tac x=\"[]\" in exI)\n  apply(auto)\n  apply(drule_tac x=\"s2\" in meta_spec)\n  apply(auto)\nby (metis concat.simps(2) insertE set_simps(2))\n\nlemma star5:\n  assumes \"f [] = []\"\n  assumes \"\\<forall>s1 s2. f (s1 @ s2) = (f s1) @ (f s2)\"\n  shows \"(f ` A) \\<up> n = f ` (A \\<up> n)\"\napply(induct n)\napply(simp add: assms)\napply(simp)\napply(subst seq_image[OF assms(2)])\napply(simp)\ndone\n\nlemma star6:\n  assumes \"f [] = []\"\n  assumes \"\\<forall>s1 s2. f (s1 @ s2) = (f s1) @ (f s2)\"\n  shows \"(f ` A)\\<star> = f ` (A\\<star>)\"\napply(simp add: star3)\napply(simp add: image_UN)\napply(subst star5[OF assms])\napply(simp)\ndone\n\nlemma star_decomp: \n  assumes a: \"c # x \\<in> A\\<star>\" \n  shows \"\\<exists>a b. x = a @ b \\<and> c # a \\<in> A \\<and> b \\<in> A\\<star>\"\nusing a\nby (induct x\\<equiv>\"c # x\" rule: Star.induct) \n   (auto simp add: append_eq_Cons_conv)\n\nlemma Der_star [simp]:\n  shows \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\"\nproof -    \n  have \"Der c (A\\<star>) = Der c ({[]} \\<union> A ;; A\\<star>)\"\n    \n    by (simp only: star_cases[symmetric])\n  also have \"... = Der c (A ;; A\\<star>)\"\n    by (simp only: Der_union Der_empty) (simp)\n  also have \"... = (Der c A) ;; A\\<star> \\<union> (if [] \\<in> A then Der c (A\\<star>) else {})\"\n    by simp\n  also have \"... =  (Der c A) ;; A\\<star>\"\n    unfolding Sequ_def Der_def\n    by (auto dest: star_decomp)\n  finally show \"Der c (A\\<star>) = (Der c A) ;; A\\<star>\" .\nqed\n\n\n\nsection {* Regular Expressions *}\n\ndatatype rexp =\n  NULL\n| EMPTY\n| CHAR char\n| SEQ rexp rexp\n| ALT rexp rexp\n| STAR rexp\n\nsection {* Semantics of Regular Expressions *}\n \nfun\n  L :: \"rexp \\<Rightarrow> string set\"\nwhere\n  \"L (NULL) = {}\"\n| \"L (EMPTY) = {[]}\"\n| \"L (CHAR c) = {[c]}\"\n| \"L (SEQ r1 r2) = (L r1) ;; (L r2)\"\n| \"L (ALT r1 r2) = (L r1) \\<union> (L r2)\"\n| \"L (STAR r) = (L r)\\<star>\"\n\nfun\n nullable :: \"rexp \\<Rightarrow> bool\"\nwhere\n  \"nullable (NULL) = False\"\n| \"nullable (EMPTY) = True\"\n| \"nullable (CHAR c) = False\"\n| \"nullable (ALT r1 r2) = (nullable r1 \\<or> nullable r2)\"\n| \"nullable (SEQ r1 r2) = (nullable r1 \\<and> nullable r2)\"\n| \"nullable (STAR r) = True\"\n\nlemma nullable_correctness:\n  shows \"nullable r  \\<longleftrightarrow> [] \\<in> (L r)\"\napply (induct r) \napply(auto simp add: Sequ_def) \ndone\n\n\n\nsection {* Values *}\n\ndatatype val = \n  Void\n| Char char\n| Seq val val\n| Right val\n| Left val\n| Stars \"val list\"\n\nsection {* The string behind a value *}\n\nfun \n  flat :: \"val \\<Rightarrow> string\"\nwhere\n  \"flat (Void) = []\"\n| \"flat (Char c) = [c]\"\n| \"flat (Left v) = flat v\"\n| \"flat (Right v) = flat v\"\n| \"flat (Seq v1 v2) = (flat v1) @ (flat v2)\"\n| \"flat (Stars []) = []\"\n| \"flat (Stars (v#vs)) = (flat v) @ (flat (Stars vs))\" \n\n\n\nsection {* Relation between values and regular expressions *}\n\ninductive \n  NPrf :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<Turnstile> _ : _\" [100, 100] 100)\nwhere\n \"\\<lbrakk>\\<Turnstile> v1 : r1; \\<Turnstile> v2 : r2\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Seq v1 v2 : SEQ r1 r2\"\n| \"\\<Turnstile> v1 : r1 \\<Longrightarrow> \\<Turnstile> Left v1 : ALT r1 r2\"\n| \"\\<Turnstile> v2 : r2 \\<Longrightarrow> \\<Turnstile> Right v2 : ALT r1 r2\"\n| \"\\<Turnstile> Void : EMPTY\"\n| \"\\<Turnstile> Char c : CHAR c\"\n| \"\\<Turnstile> Stars [] : STAR r\"\n| \"\\<lbrakk>\\<Turnstile> v : r; \\<Turnstile> Stars vs : STAR r; flat v \\<noteq> []\\<rbrakk> \\<Longrightarrow> \\<Turnstile> Stars (v # vs) : STAR r\"\n\ninductive \n  Prf :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<turnstile> _ : _\" [100, 100] 100)\nwhere\n \"\\<lbrakk>\\<turnstile> v1 : r1; \\<turnstile> v2 : r2\\<rbrakk> \\<Longrightarrow> \\<turnstile> Seq v1 v2 : SEQ r1 r2\"\n| \"\\<turnstile> v1 : r1 \\<Longrightarrow> \\<turnstile> Left v1 : ALT r1 r2\"\n| \"\\<turnstile> v2 : r2 \\<Longrightarrow> \\<turnstile> Right v2 : ALT r1 r2\"\n| \"\\<turnstile> Void : EMPTY\"\n| \"\\<turnstile> Char c : CHAR c\"\n| \"\\<turnstile> Stars [] : STAR r\"\n| \"\\<lbrakk>\\<turnstile> v : r; \\<turnstile> Stars vs : STAR r\\<rbrakk> \\<Longrightarrow> \\<turnstile> Stars (v # vs) : STAR r\"\n\nlemma NPrf_imp_Prf:\n  assumes \"\\<Turnstile> v : r\" \n  shows \"\\<turnstile> v : r\"\nusing assms\napply(induct)\napply(auto intro: Prf.intros)\ndone\n\nlemma NPrf_Prf_val:\n  shows \"\\<turnstile> v : r \\<Longrightarrow> \\<exists>v'. flat v' = flat v \\<and> \\<Turnstile> v' : r\"\n  and   \"\\<turnstile> Stars vs : r \\<Longrightarrow> \\<exists>vs'. flat (Stars vs') = flat (Stars vs) \\<and> \\<Turnstile> Stars vs' : r\"\nusing assms\napply(induct v and vs arbitrary: r and r rule: val.inducts)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule_tac x=\"Void\" in exI)\napply(simp)\napply(rule NPrf.intros)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule_tac x=\"Char c\" in exI)\napply(simp)\napply(rule NPrf.intros)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)[1]\napply(drule_tac x=\"r1\" in meta_spec)\napply(drule_tac x=\"r2\" in meta_spec)\napply(simp)\napply(auto)[1]\napply(rule_tac x=\"Seq v' v'a\" in exI)\napply(simp)\napply (metis NPrf.intros(1))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(drule_tac x=\"r2\" in meta_spec)\napply(simp)\napply(auto)[1]\napply(rule_tac x=\"Right v'\" in exI)\napply(simp)\napply (metis NPrf.intros)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(drule_tac x=\"r1\" in meta_spec)\napply(simp)\napply(auto)[1]\napply(rule_tac x=\"Left v'\" in exI)\napply(simp)\napply (metis NPrf.intros)\napply(drule_tac x=\"r\" in meta_spec)\napply(simp)\napply(auto)[1]\napply(rule_tac x=\"Stars vs'\" in exI)\napply(simp)\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis NPrf.intros(6))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)[1]\napply(drule_tac x=\"ra\" in meta_spec)\napply(simp)\napply(drule_tac x=\"STAR ra\" in meta_spec)\napply(simp)\napply(auto)\napply(case_tac \"flat v = []\")\napply(rule_tac x=\"vs'\" in exI)\napply(simp)\napply(rule_tac x=\"v' # vs'\" in exI)\napply(simp)\napply(rule NPrf.intros)\napply(auto)\ndone\n\nlemma NPrf_Prf:\n  shows \"{flat v | v. \\<turnstile> v : r} = {flat v | v. \\<Turnstile> v : r}\"\napply(auto)\napply (metis NPrf_Prf_val(1))\nby (metis NPrf_imp_Prf)\n\n\nlemma not_nullable_flat:\n  assumes \"\\<turnstile> v : r\" \"\\<not>nullable r\"\n  shows \"flat v \\<noteq> []\"\nusing assms\napply(induct)\napply(auto)\ndone\n\nlemma Prf_flat_L:\n  assumes \"\\<turnstile> v : r\" shows \"flat v \\<in> L r\"\nusing assms\napply(induct v r rule: Prf.induct)\napply(auto simp add: Sequ_def)\ndone\n\nlemma NPrf_flat_L:\n  assumes \"\\<Turnstile> v : r\" shows \"flat v \\<in> L r\"\nusing assms\nby (metis NPrf_imp_Prf Prf_flat_L)\n\nlemma Prf_Stars:\n  assumes \"\\<forall>v \\<in> set vs. \\<turnstile> v : r\"\n  shows \"\\<turnstile> Stars vs : STAR r\"\nusing assms\napply(induct vs)\napply (metis Prf.intros(6))\nby (metis Prf.intros(7) insert_iff set_simps(2))\n\nlemma Star_string:\n  assumes \"s \\<in> A\\<star>\"\n  shows \"\\<exists>ss. concat ss = s \\<and> (\\<forall>s \\<in> set ss. s \\<in> A)\"\nusing assms\napply(induct rule: Star.induct)\napply(auto)\napply(rule_tac x=\"[]\" in exI)\napply(simp)\napply(rule_tac x=\"s1#ss\" in exI)\napply(simp)\ndone\n\nlemma Star_val:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<turnstile> v : r\"\n  shows \"\\<exists>vs. concat (map flat vs) = concat ss \\<and> (\\<forall>v\\<in>set vs. \\<turnstile> v : r)\"\nusing assms\napply(induct ss)\napply(auto)\napply (metis empty_iff list.set(1))\nby (metis concat.simps(2) list.simps(9) set_ConsD)\n\nlemma Star_valN:\n  assumes \"\\<forall>s\\<in>set ss. \\<exists>v. s = flat v \\<and> \\<Turnstile> v : r\"\n  shows \"\\<exists>vs. concat (map flat vs) = concat ss \\<and> (\\<forall>v\\<in>set vs. \\<Turnstile> v : r)\"\nusing assms\napply(induct ss)\napply(auto)\napply (metis empty_iff list.set(1))\nby (metis concat.simps(2) list.simps(9) set_ConsD)\n\nlemma L_flat_Prf:\n  \"L(r) = {flat v | v. \\<turnstile> v : r}\"\napply(induct r)\napply(auto dest: Prf_flat_L simp add: Sequ_def)\napply (metis Prf.intros(4) flat.simps(1))\napply (metis Prf.intros(5) flat.simps(2))\napply (metis Prf.intros(1) flat.simps(5))\napply (metis Prf.intros(2) flat.simps(3))\napply (metis Prf.intros(3) flat.simps(4))\napply(erule Prf.cases)\napply(auto)\napply(subgoal_tac \"\\<exists>vs::val list. concat (map flat vs) = x \\<and> (\\<forall>v \\<in> set vs. \\<turnstile> v : r)\")\napply(auto)[1]\napply(rule_tac x=\"Stars vs\" in exI)\napply(simp)\napply(rule Prf_Stars)\napply(simp)\napply(drule Star_string)\napply(auto)\napply(rule Star_val)\napply(simp)\ndone\n\nlemma L_flat_NPrf:\n  \"L(r) = {flat v | v. \\<Turnstile> v : r}\"\nby (metis L_flat_Prf NPrf_Prf)\n\ntext {* nicer proofs by Fahad *}\n\nlemma Prf_Star_flat_L:\n  assumes \"\\<turnstile> v : STAR r\" shows \"flat v \\<in> (L r)\\<star>\"\nusing assms\napply(induct v r\\<equiv>\"STAR r\" arbitrary: r rule: Prf.induct)\napply(auto)\napply(simp add: star3)\napply(auto)\napply(rule_tac x=\"Suc x\" in exI)\napply(auto simp add: Sequ_def)\napply(rule_tac x=\"flat v\" in exI)\napply(rule_tac x=\"flat (Stars vs)\" in exI)\napply(auto)\nby (metis Prf_flat_L)\n\nlemma L_flat_Prf2:\n  \"L(r) = {flat v | v. \\<turnstile> v : r}\"\napply(induct r)\napply(auto)\nusing L.simps(1) Prf_flat_L \napply(blast)\nusing Prf.intros(4) \napply(force)\nusing L.simps(2) Prf_flat_L \napply(blast)\nusing Prf.intros(5) apply force\nusing L.simps(3) Prf_flat_L apply blast\nusing L_flat_Prf apply auto[1]\napply (smt L.simps(4) Sequ_def mem_Collect_eq)\nusing Prf_flat_L \napply(fastforce)\napply(metis Prf.intros(2) flat.simps(3))\napply(metis Prf.intros(3) flat.simps(4))\napply(erule Prf.cases)\napply(simp)\napply(simp)\napply(auto)\nusing L_flat_Prf apply auto[1]\napply (smt Collect_cong L.simps(6) mem_Collect_eq)\nusing Prf_Star_flat_L \napply(fastforce)\ndone\n\n\nsection {* Values Sets *}\n\ndefinition prefix :: \"string \\<Rightarrow> string \\<Rightarrow> bool\" (\"_ \\<sqsubseteq> _\" [100, 100] 100)\nwhere\n  \"s1 \\<sqsubseteq> s2 \\<equiv> \\<exists>s3. s1 @ s3 = s2\"\n\ndefinition sprefix :: \"string \\<Rightarrow> string \\<Rightarrow> bool\" (\"_ \\<sqsubset> _\" [100, 100] 100)\nwhere\n  \"s1 \\<sqsubset> s2 \\<equiv> (s1 \\<sqsubseteq> s2 \\<and> s1 \\<noteq> s2)\"\n\nlemma length_sprefix:\n  \"s1 \\<sqsubset> s2 \\<Longrightarrow> length s1 < length s2\"\nunfolding sprefix_def prefix_def\nby (auto)\n\ndefinition Prefixes :: \"string \\<Rightarrow> string set\" where\n  \"Prefixes s \\<equiv> {sp. sp \\<sqsubseteq> s}\"\n\ndefinition Suffixes :: \"string \\<Rightarrow> string set\" where\n  \"Suffixes s \\<equiv> rev ` (Prefixes (rev s))\"\n\ndefinition SPrefixes :: \"string \\<Rightarrow> string set\" where\n  \"SPrefixes s \\<equiv> {sp. sp \\<sqsubset> s}\"\n\ndefinition SSuffixes :: \"string \\<Rightarrow> string set\" where\n  \"SSuffixes s \\<equiv> rev ` (SPrefixes (rev s))\"\n\nlemma Suffixes_in: \n  \"\\<exists>s1. s1 @ s2 = s3 \\<Longrightarrow> s2 \\<in> Suffixes s3\"\nunfolding Suffixes_def Prefixes_def prefix_def image_def\napply(auto)\nby (metis rev_rev_ident)\n\nlemma SSuffixes_in: \n  \"\\<exists>s1. s1 \\<noteq> [] \\<and> s1 @ s2 = s3 \\<Longrightarrow> s2 \\<in> SSuffixes s3\"\nunfolding SSuffixes_def Suffixes_def SPrefixes_def Prefixes_def sprefix_def prefix_def image_def\napply(auto)\nby (metis append_self_conv rev.simps(1) rev_rev_ident)\n\nlemma Prefixes_Cons:\n  \"Prefixes (c # s) = {[]} \\<union> {c # sp | sp. sp \\<in> Prefixes s}\"\nunfolding Prefixes_def prefix_def\napply(auto simp add: append_eq_Cons_conv) \ndone\n\nlemma finite_Prefixes:\n  \"finite (Prefixes s)\"\napply(induct s)\napply(auto simp add: Prefixes_def prefix_def)[1]\napply(simp add: Prefixes_Cons)\ndone\n\nlemma finite_Suffixes:\n  \"finite (Suffixes s)\"\nunfolding Suffixes_def\napply(rule finite_imageI)\napply(rule finite_Prefixes)\ndone\n\nlemma prefix_Cons:\n  \"((c # s1) \\<sqsubseteq> (c # s2)) = (s1 \\<sqsubseteq> s2)\"\napply(auto simp add: prefix_def)\ndone\n\nlemma prefix_append:\n  \"((s @ s1) \\<sqsubseteq> (s @ s2)) = (s1 \\<sqsubseteq> s2)\"\napply(induct s)\napply(simp)\napply(simp add: prefix_Cons)\ndone\n\n\ndefinition Values :: \"rexp \\<Rightarrow> string \\<Rightarrow> val set\" where\n  \"Values r s \\<equiv> {v. \\<turnstile> v : r \\<and> flat v \\<sqsubseteq> s}\"\n\ndefinition SValues :: \"rexp \\<Rightarrow> string \\<Rightarrow> val set\" where\n  \"SValues r s \\<equiv> {v. \\<turnstile> v : r \\<and> flat v = s}\"\n\n\ndefinition NValues :: \"rexp \\<Rightarrow> string \\<Rightarrow> val set\" where\n  \"NValues r s \\<equiv> {v. \\<Turnstile> v : r \\<and> flat v \\<sqsubseteq> s}\"\n\nlemma NValues_STAR_Nil:\n  \"NValues (STAR r) [] = {Stars []}\"\napply(auto simp add: NValues_def prefix_def)\napply(erule NPrf.cases)\napply(auto)\nby (metis NPrf.intros(6))\n\n\ndefinition rest :: \"val \\<Rightarrow> string \\<Rightarrow> string\" where\n  \"rest v s \\<equiv> drop (length (flat v)) s\"\n\nlemma rest_Nil:\n  \"rest v [] = []\"\napply(simp add: rest_def)\ndone\n\nlemma rest_Suffixes:\n  \"rest v s \\<in> Suffixes s\"\nunfolding rest_def\nby (metis Suffixes_in append_take_drop_id)\n\nlemma rest_SSuffixes:\n  assumes \"flat v \\<noteq> []\" \"s \\<noteq> []\"\n  shows \"rest v s \\<in> SSuffixes s\"\nusing assms\nunfolding rest_def\nthm SSuffixes_in\napply(rule_tac SSuffixes_in)\napply(rule_tac x=\"take (length (flat v)) s\" in exI)\napply(simp add: sprefix_def)\ndone\n\n\nlemma Values_recs:\n  \"Values (NULL) s = {}\"\n  \"Values (EMPTY) s = {Void}\"\n  \"Values (CHAR c) s = (if [c] \\<sqsubseteq> s then {Char c} else {})\" \n  \"Values (ALT r1 r2) s = {Left v | v. v \\<in> Values r1 s} \\<union> {Right v | v. v \\<in> Values r2 s}\"\n  \"Values (SEQ r1 r2) s = {Seq v1 v2 | v1 v2. v1 \\<in> Values r1 s \\<and> v2 \\<in> Values r2 (rest v1 s)}\"\n  \"Values (STAR r) s = \n      {Stars []} \\<union> {Stars (v # vs) | v vs. v \\<in> Values r s \\<and> Stars vs \\<in> Values (STAR r) (rest v s)}\"\nunfolding Values_def\napply(auto)\n(*NULL*)\napply(erule Prf.cases)\napply(simp_all)[7]\n(*EMPTY*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule Prf.intros)\napply (metis append_Nil prefix_def)\n(*CHAR*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule Prf.intros)\napply(erule Prf.cases)\napply(simp_all)[7]\n(*ALT*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf.intros(2))\napply (metis Prf.intros(3))\n(*SEQ*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (simp add: append_eq_conv_conj prefix_def rest_def)\napply (metis Prf.intros(1))\napply (simp add: append_eq_conv_conj prefix_def rest_def)\n(*STAR*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule conjI)\napply(simp add: prefix_def)\napply(auto)[1]\napply(simp add: prefix_def)\napply(auto)[1]\napply (metis append_eq_conv_conj rest_def)\napply (metis Prf.intros(6))\napply (metis append_Nil prefix_def)\napply (metis Prf.intros(7))\nby (metis append_eq_conv_conj prefix_append prefix_def rest_def)\n\nlemma NValues_recs:\n  \"NValues (NULL) s = {}\"\n  \"NValues (EMPTY) s = {Void}\"\n  \"NValues (CHAR c) s = (if [c] \\<sqsubseteq> s then {Char c} else {})\" \n  \"NValues (ALT r1 r2) s = {Left v | v. v \\<in> NValues r1 s} \\<union> {Right v | v. v \\<in> NValues r2 s}\"\n  \"NValues (SEQ r1 r2) s = {Seq v1 v2 | v1 v2. v1 \\<in> NValues r1 s \\<and> v2 \\<in> NValues r2 (rest v1 s)}\"\n  \"NValues (STAR r) s = \n  {Stars []} \\<union> {Stars (v # vs) | v vs. v \\<in> NValues r s \\<and> flat v \\<noteq> [] \\<and>  Stars vs \\<in> NValues (STAR r) (rest v s)}\"\nunfolding NValues_def\napply(auto)\n(*NULL*)\napply(erule NPrf.cases)\napply(simp_all)[7]\n(*EMPTY*)\napply(erule NPrf.cases)\napply(simp_all)[7]\napply(rule NPrf.intros)\napply (metis append_Nil prefix_def)\n(*CHAR*)\napply(erule NPrf.cases)\napply(simp_all)[7]\napply(rule NPrf.intros)\napply(erule NPrf.cases)\napply(simp_all)[7]\n(*ALT*)\napply(erule NPrf.cases)\napply(simp_all)[7]\napply (metis NPrf.intros(2))\napply (metis NPrf.intros(3))\n(*SEQ*)\napply(erule NPrf.cases)\napply(simp_all)[7]\napply (simp add: append_eq_conv_conj prefix_def rest_def)\napply (metis NPrf.intros(1))\napply (simp add: append_eq_conv_conj prefix_def rest_def)\n(*STAR*)\napply(erule NPrf.cases)\napply(simp_all)\napply(rule conjI)\napply(simp add: prefix_def)\napply(auto)[1]\napply(simp add: prefix_def)\napply(auto)[1]\napply (metis append_eq_conv_conj rest_def)\napply (metis NPrf.intros(6))\napply (metis append_Nil prefix_def)\napply (metis NPrf.intros(7))\nby (metis append_eq_conv_conj prefix_append prefix_def rest_def)\n\nlemma SValues_recs:\n \"SValues (NULL) s = {}\"\n \"SValues (EMPTY) s = (if s = [] then {Void} else {})\"\n \"SValues (CHAR c) s = (if [c] = s then {Char c} else {})\" \n \"SValues (ALT r1 r2) s = {Left v | v. v \\<in> SValues r1 s} \\<union> {Right v | v. v \\<in> SValues r2 s}\"\n \"SValues (SEQ r1 r2) s = {Seq v1 v2 | v1 v2. \\<exists>s1 s2. s = s1 @ s2 \\<and> v1 \\<in> SValues r1 s1 \\<and> v2 \\<in> SValues r2 s2}\"\n \"SValues (STAR r) s = (if s = [] then {Stars []} else {}) \\<union> \n   {Stars (v # vs) | v vs. \\<exists>s1 s2. s = s1 @ s2 \\<and> v \\<in> SValues r s1 \\<and> Stars vs \\<in> SValues (STAR r) s2}\"\nunfolding SValues_def\napply(auto)\n(*NULL*)\napply(erule Prf.cases)\napply(simp_all)[7]\n(*EMPTY*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule Prf.intros)\napply(erule Prf.cases)\napply(simp_all)[7]\n(*CHAR*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[7]\n(*ALT*)\napply(erule Prf.cases)\napply(simp_all)[7]\napply metis\napply(erule Prf.intros)\napply(erule Prf.intros)\n(* SEQ case *)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf.intros(1))\n(* STAR case *)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule Prf.intros)\napply (metis Prf.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf.intros(7))\nby (metis Prf.intros(7))\n\nlemma finite_image_set2:\n  \"finite {x. P x} \\<Longrightarrow> finite {y. Q y} \\<Longrightarrow> finite {(x, y) | x y. P x \\<and> Q y}\"\n  by (rule finite_subset [where B = \"\\<Union>x \\<in> {x. P x}. \\<Union>y \\<in> {y. Q y}. {(x, y)}\"]) auto\n\n\nlemma NValues_finite_aux:\n  \"(\\<lambda>(r, s). finite (NValues r s)) (r, s)\"\napply(rule wf_induct[of \"measure size <*lex*> measure length\",where P=\"\\<lambda>(r, s). finite (NValues r s)\"])\napply (metis wf_lex_prod wf_measure)\napply(auto)\napply(case_tac a)\napply(simp_all)\napply(simp add: NValues_recs)\napply(simp add: NValues_recs)\napply(simp add: NValues_recs)\napply(simp add: NValues_recs)\napply(rule_tac f=\"\\<lambda>(x, y). Seq x y\" and \n               A=\"{(v1, v2) | v1 v2. v1 \\<in> NValues rexp1 b \\<and> v2 \\<in> NValues rexp2 (rest v1 b)}\" in finite_surj)\nprefer 2\napply(auto)[1]\napply(rule_tac B=\"\\<Union>sp \\<in> Suffixes b. {(v1, v2). v1 \\<in> NValues rexp1 b \\<and> v2 \\<in> NValues rexp2 sp}\" in finite_subset)\napply(auto)[1]\napply (metis rest_Suffixes)\napply(rule finite_UN_I)\napply(rule finite_Suffixes)\napply(simp)\napply(simp add: NValues_recs)\napply(clarify)\napply(subst NValues_recs)\napply(simp)\napply(rule_tac f=\"\\<lambda>(v, vs). Stars (v # vs)\" and \n               A=\"{(v, vs) | v vs. v \\<in> NValues rexp b \\<and> (flat v \\<noteq> [] \\<and> Stars vs \\<in> NValues (STAR rexp) (rest v b))}\" in finite_surj)\nprefer 2\napply(auto)[1]\napply(auto)\napply(case_tac b)\napply(simp)\ndefer\napply(rule_tac B=\"\\<Union>sp \\<in> SSuffixes b. {(v, vs) | v vs. v \\<in> NValues rexp b \\<and> Stars vs \\<in> NValues (STAR rexp) sp}\" in finite_subset)\napply(auto)[1]\napply(rule_tac x=\"rest aa (a # list)\" in bexI)\napply(simp)\napply (rule rest_SSuffixes)\napply(simp)\napply(simp)\napply(rule finite_UN_I)\ndefer\napply(frule_tac x=\"rexp\" in spec)\napply(drule_tac x=\"b\" in spec)\napply(drule conjunct1)\napply(drule mp)\napply(simp)\napply(drule_tac x=\"STAR rexp\" in spec)\napply(drule_tac x=\"sp\" in spec)\napply(drule conjunct2)\napply(drule mp)\napply(simp)\napply(simp add: prefix_def SPrefixes_def SSuffixes_def)\napply(auto)[1]\napply (metis length_Cons length_rev length_sprefix rev.simps(2))\napply(simp)\napply(rule finite_cartesian_product)\napply(simp)\napply(rule_tac f=\"Stars\" in finite_imageD)\nprefer 2\napply(auto simp add: inj_on_def)[1]\napply (metis finite_subset image_Collect_subsetI)\napply(simp add: rest_Nil)\napply(simp add: NValues_STAR_Nil)\napply(rule_tac B=\"{(v, vs). v \\<in> NValues rexp [] \\<and> vs = []}\" in finite_subset)\napply(auto)[1]\napply(simp)\napply(rule_tac B=\"Suffixes b\" in finite_subset)\napply(auto simp add: SSuffixes_def Suffixes_def Prefixes_def SPrefixes_def sprefix_def)[1]\nby (metis finite_Suffixes)\n\nlemma NValues_finite:\n  \"finite (NValues r s)\"\nusing NValues_finite_aux\napply(simp)\ndone\n\nsection {* Sulzmann functions *}\n\nfun \n  mkeps :: \"rexp \\<Rightarrow> val\"\nwhere\n  \"mkeps(EMPTY) = Void\"\n| \"mkeps(SEQ r1 r2) = Seq (mkeps r1) (mkeps r2)\"\n| \"mkeps(ALT r1 r2) = (if nullable(r1) then Left (mkeps r1) else Right (mkeps r2))\"\n| \"mkeps(STAR r) = Stars []\"\n\nsection {* Derivatives *}\n\nfun\n der :: \"char \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"der c (NULL) = NULL\"\n| \"der c (EMPTY) = NULL\"\n| \"der c (CHAR c') = (if c = c' then EMPTY else NULL)\"\n| \"der c (ALT r1 r2) = ALT (der c r1) (der c r2)\"\n| \"der c (SEQ r1 r2) = \n     (if nullable r1\n      then ALT (SEQ (der c r1) r2) (der c r2)\n      else SEQ (der c r1) r2)\"\n| \"der c (STAR r) = SEQ (der c r) (STAR r)\"\n\nfun \n ders :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp\"\nwhere\n  \"ders [] r = r\"\n| \"ders (c # s) r = ders s (der c r)\"\n\n\nlemma der_correctness:\n  shows \"L (der c r) = Der c (L r)\"\napply(induct r) \napply(simp_all add: nullable_correctness)\ndone\n\nlemma ders_correctness:\n  shows \"L (ders s r) = Ders s (L r)\"\napply(induct s arbitrary: r) \napply(simp add: Ders_def)\napply(simp)\napply(subst der_correctness)\napply(simp add: Ders_def Der_def)\ndone\n\nsection {* Injection function *}\n\nfun injval :: \"rexp \\<Rightarrow> char \\<Rightarrow> val \\<Rightarrow> val\"\nwhere\n  \"injval (CHAR d) c Void = Char d\"\n| \"injval (ALT r1 r2) c (Left v1) = Left(injval r1 c v1)\"\n| \"injval (ALT r1 r2) c (Right v2) = Right(injval r2 c v2)\"\n| \"injval (SEQ r1 r2) c (Seq v1 v2) = Seq (injval r1 c v1) v2\"\n| \"injval (SEQ r1 r2) c (Left (Seq v1 v2)) = Seq (injval r1 c v1) v2\"\n| \"injval (SEQ r1 r2) c (Right v2) = Seq (mkeps r1) (injval r2 c v2)\"\n| \"injval (STAR r) c (Seq v (Stars vs)) = Stars ((injval r c v) # vs)\" \n\nfun \n  lex :: \"rexp \\<Rightarrow> string \\<Rightarrow> val option\"\nwhere\n  \"lex r [] = (if nullable r then Some(mkeps r) else None)\"\n| \"lex r (c#s) = (case (lex (der c r) s) of  \n                    None \\<Rightarrow> None\n                  | Some(v) \\<Rightarrow> Some(injval r c v))\"\n\nfun \n  lex2 :: \"rexp \\<Rightarrow> string \\<Rightarrow> val\"\nwhere\n  \"lex2 r [] = mkeps r\"\n| \"lex2 r (c#s) = injval r c (lex2 (der c r) s)\"\n\n\nsection {* Projection function *}\n\nfun projval :: \"rexp \\<Rightarrow> char \\<Rightarrow> val \\<Rightarrow> val\"\nwhere\n  \"projval (CHAR d) c _ = Void\"\n| \"projval (ALT r1 r2) c (Left v1) = Left (projval r1 c v1)\"\n| \"projval (ALT r1 r2) c (Right v2) = Right (projval r2 c v2)\"\n| \"projval (SEQ r1 r2) c (Seq v1 v2) = \n     (if flat v1 = [] then Right(projval r2 c v2) \n      else if nullable r1 then Left (Seq (projval r1 c v1) v2)\n                          else Seq (projval r1 c v1) v2)\"\n| \"projval (STAR r) c (Stars (v # vs)) = Seq (projval r c v) (Stars vs)\"\n\n\n\nlemma mkeps_nullable:\n  assumes \"nullable(r)\" \n  shows \"\\<turnstile> mkeps r : r\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto intro: Prf.intros)\ndone\n\nlemma mkeps_flat:\n  assumes \"nullable(r)\" \n  shows \"flat (mkeps r) = []\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto)\ndone\n\n\nlemma v3:\n  assumes \"\\<turnstile> v : der c r\" \n  shows \"\\<turnstile> (injval r c v) : r\"\nusing assms\napply(induct arbitrary: v rule: der.induct)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(case_tac \"c = c'\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf.intros(5))\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf.intros(2))\napply (metis Prf.intros(3))\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)[1]\napply (metis Prf.intros(1))\napply(auto)[1]\napply (metis Prf.intros(1) mkeps_nullable)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)[1]\napply(rule Prf.intros)\napply(auto)[2]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)\napply (metis Prf.intros(6) Prf.intros(7))\nby (metis Prf.intros(7))\n\nlemma v3_proj:\n  assumes \"\\<Turnstile> v : r\" and \"\\<exists>s. (flat v) = c # s\"\n  shows \"\\<Turnstile> (projval r c v) : der c r\"\nusing assms\napply(induct rule: NPrf.induct)\nprefer 4\napply(simp)\nprefer 4\napply(simp)\napply (metis NPrf.intros(4))\nprefer 2\napply(simp)\napply (metis NPrf.intros(2))\nprefer 2\napply(simp)\napply (metis NPrf.intros(3))\napply(auto)\napply(rule NPrf.intros)\napply(simp)\napply (metis NPrf_imp_Prf not_nullable_flat)\napply(rule NPrf.intros)\napply(rule NPrf.intros)\napply (metis Cons_eq_append_conv)\napply(simp)\napply(rule NPrf.intros)\napply (metis Cons_eq_append_conv)\napply(simp)\n(* Stars case *)\napply(rule NPrf.intros)\napply (metis Cons_eq_append_conv)\napply(auto)\ndone\n\nlemma v4:\n  assumes \"\\<turnstile> v : der c r\" \n  shows \"flat (injval r c v) = c # (flat v)\"\nusing assms\napply(induct arbitrary: v rule: der.induct)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(case_tac \"c = c'\")\napply(simp)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all (no_asm_use))[7]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(simp only: injval.simps flat.simps)\napply(auto)[1]\napply (metis mkeps_flat)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)[7]\ndone\n\nlemma v4_proj:\n  assumes \"\\<Turnstile> v : r\" and \"\\<exists>s. (flat v) = c # s\"\n  shows \"c # flat (projval r c v) = flat v\"\nusing assms\napply(induct rule: NPrf.induct)\nprefer 4\napply(simp)\nprefer 4\napply(simp)\nprefer 2\napply(simp)\nprefer 2\napply(simp)\napply(auto)\napply (metis Cons_eq_append_conv)\napply(simp add: append_eq_Cons_conv)\napply(auto)\ndone\n\nlemma v4_proj2:\n  assumes \"\\<Turnstile> v : r\" and \"(flat v) = c # s\"\n  shows \"flat (projval r c v) = s\"\nusing assms\nby (metis list.inject v4_proj)\n\n\ndefinition \n  PC31 :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp \\<Rightarrow> bool\"\nwhere\n  \"PC31 s r r' \\<equiv> s \\<notin> L r\"\n\ndefinition \n  PC41 :: \"string \\<Rightarrow> string \\<Rightarrow> rexp \\<Rightarrow> rexp \\<Rightarrow> bool\"\nwhere\n  \"PC41 s s' r r' \\<equiv> (\\<forall>x. (s @ x \\<in> L r \\<longrightarrow> s' \\<in> {x} ;; L r' \\<longrightarrow> x = []))\"\n\n\nlemma\n L1: \"\\<not>(nullable r1) \\<longrightarrow> [] \\<in> L r2 \\<longrightarrow> PC31 [] r1 r2\" and\n L2: \"s1 \\<in> L(r1) \\<longrightarrow> [] \\<in> L(r2) \\<longrightarrow> PC41 s1 [] r1 r2\" and\n L3: \"s2 \\<in> L(der c r2) \\<longrightarrow> PC31 s2 (der c r1) (der c r2) \\<longrightarrow> PC31 (c#s2) r1 r2\" and\n L4: \"s1 \\<in> L(der c r1) \\<longrightarrow> s2 \\<in> L(r2) \\<longrightarrow> PC41 s1 s2 (der c r1) r2 \\<longrightarrow> PC41 (c#s1) s2 r1 r2\" and\n L5: \"nullable(r1) \\<longrightarrow> s2 \\<in> L(der c r2) \\<longrightarrow> PC31 s2 (SEQ (der c r1) r2) (der c r2) \\<longrightarrow> PC41 [] (c#s2) r1 r2\" and\n L6: \"s0 \\<in> L(der c r0) \\<longrightarrow>  s \\<in> L(STAR r0) \\<longrightarrow>  PC41 s0 s (der c r0) (STAR r0) \\<longrightarrow> PC41 (c#s0) s r0 (STAR r0)\" and\n L7: \"s' \\<in> L(r') \\<longrightarrow> s' \\<in> L(r) \\<longrightarrow> \\<not>PC31 s' r r'\" and\n L8: \"s \\<in> L(r) \\<longrightarrow> s' \\<in> L(r') \\<longrightarrow> s @ x \\<in> L(r) \\<longrightarrow> s' \\<in> {x} ;; (L(r') ;; {y}) \\<longrightarrow>  x \\<noteq> [] \\<longrightarrow> \\<not>PC41 s s' r r'\"\napply(auto simp add: PC31_def PC41_def)[1]\napply (metis nullable_correctness)\napply(auto simp add: PC31_def PC41_def)[1]\napply(simp add: Sequ_def)\napply(auto simp add: PC31_def PC41_def)[1]\napply(simp add: der_correctness Der_def)\napply(auto simp add: PC31_def PC41_def)[1]\napply(simp add: der_correctness Der_def Sequ_def)\napply(auto simp add: PC31_def PC41_def)[1]\napply(simp add: Sequ_def)\napply(simp add: der_correctness Der_def)\napply(auto)[1]\napply (metis append_eq_Cons_conv)\napply(auto simp add: PC31_def PC41_def)[1]\napply(simp add: Sequ_def)\napply(simp add: der_correctness Der_def)\napply(auto simp add: PC31_def PC41_def)[1]\napply(rule impI)+\napply(rule notI)\n(* 8 fails *)\noops\n\ndefinition \n  PC32 :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp \\<Rightarrow> bool\"\nwhere\n  \"PC32 s r r' \\<equiv> \\<forall>y. s \\<notin> (L r ;; {y})\"\n\ndefinition \n  PC42 :: \"string \\<Rightarrow> string \\<Rightarrow> rexp \\<Rightarrow> rexp \\<Rightarrow> bool\"\nwhere\n  \"PC42 s s' r r' \\<equiv> (\\<forall>x. (s @ x \\<in> L r \\<longrightarrow> (\\<exists>y. s' \\<in> {x} ;; (L r' ;; {y})) \\<longrightarrow> x = []))\"\n\n\nlemma\n L1: \"\\<not>(nullable r1) \\<longrightarrow> [] \\<in> L r2 \\<longrightarrow> PC32 [] r1 r2\" and\n L2: \"s1 \\<in> L(r1) \\<longrightarrow> [] \\<in> L(r2) \\<longrightarrow> PC42 s1 [] r1 r2\" and\n L3: \"s2 \\<in> L(der c r2) \\<longrightarrow> PC32 s2 (der c r1) (der c r2) \\<longrightarrow> PC32 (c#s2) r1 r2\" and\n L4: \"s1 \\<in> L(der c r1) \\<longrightarrow> s2 \\<in> L(r2) \\<longrightarrow> PC42 s1 s2 (der c r1) r2 \\<longrightarrow> PC42 (c#s1) s2 r1 r2\" and\n L5: \"nullable(r1) \\<longrightarrow> s2 \\<in> L(der c r2) \\<longrightarrow> PC32 s2 (SEQ (der c r1) r2) (der c r2) \\<longrightarrow> PC42 [] (c#s2) r1 r2\" and\n L6: \"s0 \\<in> L(der c r0) \\<longrightarrow>  s \\<in> L(STAR r0) \\<longrightarrow>  PC42 s0 s (der c r0) (STAR r0) \\<longrightarrow> PC42 (c#s0) s r0 (STAR r0)\" and\n L7: \"s' \\<in> L(r') \\<longrightarrow> s' \\<in> L(r) \\<longrightarrow> \\<not>PC32 s' r r'\" and\n L8: \"s \\<in> L(r) \\<longrightarrow> s' \\<in> L(r') \\<longrightarrow> s @ x \\<in> L(r) \\<longrightarrow> s' \\<in> {x} ;; (L(r') ;; {y}) \\<longrightarrow>  x \\<noteq> [] \\<longrightarrow> \\<not>PC42 s s' r r'\"\napply(auto simp add: PC32_def PC42_def)[1]\napply(simp add: Sequ_def)\napply (metis nullable_correctness)\napply(auto simp add: PC32_def PC42_def Sequ_def)[1]\napply(auto simp add: PC32_def PC42_def Sequ_def der_correctness Der_def)[1]\napply(simp add: Cons_eq_append_conv)\napply(auto)[1]\ndefer\napply(auto simp add: PC32_def PC42_def Sequ_def der_correctness Der_def)[1]\napply(auto simp add: PC32_def PC42_def Sequ_def der_correctness Der_def nullable_correctness)[1]\napply (metis append_Cons append_assoc hd_Cons_tl list.discI list.inject)\napply(auto simp add: PC32_def PC42_def Sequ_def der_correctness Der_def)[1]\napply(auto simp add: PC32_def PC42_def Sequ_def der_correctness Der_def)[1]\napply(auto simp add: PC32_def PC42_def Sequ_def der_correctness Der_def)[1]\noops\n\ndefinition \n  PC33 :: \"string \\<Rightarrow> rexp \\<Rightarrow> rexp \\<Rightarrow> bool\"\nwhere\n  \"PC33 s r r' \\<equiv> s \\<notin> L r\"\n\ndefinition \n  PC43 :: \"string \\<Rightarrow> string \\<Rightarrow> rexp \\<Rightarrow> rexp \\<Rightarrow> bool\"\nwhere\n  \"PC43 s s' r r' \\<equiv> (\\<forall>x. (s @ x \\<in> L r \\<longrightarrow> (\\<exists>y. s' \\<in> {x} ;; (L r' ;; {y})) \\<longrightarrow> x = []))\"\n\nlemma\n L1: \"\\<not>(nullable r1) \\<longrightarrow> [] \\<in> L r2 \\<longrightarrow> PC33 [] r1 r2\" and\n L2: \"s1 \\<in> L(r1) \\<longrightarrow> [] \\<in> L(r2) \\<longrightarrow> PC43 s1 [] r1 r2\" and\n L3: \"s2 \\<in> L(der c r2) \\<longrightarrow> PC33 s2 (der c r1) (der c r2) \\<longrightarrow> PC33 (c#s2) r1 r2\" and\n L4: \"s1 \\<in> L(der c r1) \\<longrightarrow> s2 \\<in> L(r2) \\<longrightarrow> PC43 s1 s2 (der c r1) r2 \\<longrightarrow> PC43 (c#s1) s2 r1 r2\" and\n L5: \"nullable(r1) \\<longrightarrow> s2 \\<in> L(der c r2) \\<longrightarrow> PC33 s2 (SEQ (der c r1) r2) (der c r2) \\<longrightarrow> PC43 [] (c#s2) r1 r2\" and\n L6: \"s0 \\<in> L(der c r0) \\<longrightarrow>  s \\<in> L(STAR r0) \\<longrightarrow>  PC43 s0 s (der c r0) (STAR r0) \\<longrightarrow> PC43 (c#s0) s r0 (STAR r0)\" and\n L7: \"s' \\<in> L(r') \\<longrightarrow> s' \\<in> L(r) \\<longrightarrow> \\<not>PC33 s' r r'\" and\n L8: \"s \\<in> L(r) \\<longrightarrow> s' \\<in> L(r') \\<longrightarrow> s @ x \\<in> L(r) \\<longrightarrow> s' \\<in> {x} ;; (L(r') ;; {y}) \\<longrightarrow>  x \\<noteq> [] \\<longrightarrow> \\<not>PC43 s s' r r'\"\napply(auto simp add: PC33_def PC43_def)[1]\napply (metis nullable_correctness)\napply(auto simp add: PC33_def PC43_def)[1]\napply(simp add: Sequ_def)\napply(auto simp add: PC33_def PC43_def)[1]\napply(simp add: der_correctness Der_def)\napply(auto simp add: PC33_def PC43_def)[1]\napply(simp add: der_correctness Der_def Sequ_def)\napply metis\n(* 5 *)\napply(auto simp add: PC33_def PC43_def)[1]\napply(simp add: Sequ_def)\napply(simp add: der_correctness Der_def)\napply(auto)[1]\ndefer\napply(auto simp add: PC33_def PC43_def)[1]\napply(simp add: Sequ_def)\napply(simp add: der_correctness Der_def)\napply metis\napply(auto simp add: PC33_def PC43_def)[1]\napply(auto simp add: PC33_def PC43_def)[1]\n(* 5 fails *)\napply(simp add: Cons_eq_append_conv)\napply(auto)[1]\napply(drule_tac x=\"ys'\" in spec)\napply(simp)\noops\n\nsection {* Roy's Definition *}\n\ninductive \n  Roy :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"\\<rhd> _ : _\" [100, 100] 100)\nwhere\n  \"\\<rhd> Void : EMPTY\"\n| \"\\<rhd> Char c : CHAR c\"\n| \"\\<rhd> v : r1 \\<Longrightarrow> \\<rhd> Left v : ALT r1 r2\"\n| \"\\<lbrakk>\\<rhd> v : r2; flat v \\<notin> L r1\\<rbrakk> \\<Longrightarrow> \\<rhd> Right v : ALT r1 r2\"\n| \"\\<lbrakk>\\<rhd> v1 : r1; \\<rhd> v2 : r2; \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = flat v2 \\<and> (flat v1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\\<rbrakk> \\<Longrightarrow>\n      \\<rhd> Seq v1 v2 : SEQ r1 r2\"\n| \"\\<lbrakk>\\<rhd> v : r; \\<rhd> Stars vs : STAR r; flat v \\<noteq> []; \n   \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = flat (Stars vs) \\<and> (flat v @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\\<rbrakk> \\<Longrightarrow>\n      \\<rhd> Stars (v#vs) : STAR r\"\n| \"\\<rhd> Stars [] : STAR r\"\n\nlemma drop_append:\n  assumes \"s1 \\<sqsubseteq> s2\"\n  shows \"s1 @ drop (length s1) s2 = s2\"\nusing assms\napply(simp add: prefix_def)\napply(auto)\ndone\n\nlemma royA: \n  assumes \"\\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = flat v2 \\<and> (flat v1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\"\n  shows \"\\<forall>s. (s \\<in> L(ders (flat v1) r1) \\<and> \n              s \\<sqsubseteq> (flat v2) \\<and> drop (length s) (flat v2) \\<in> L r2 \\<longrightarrow> s = [])\" \nusing assms\napply -\napply(rule allI)\napply(rule impI)\napply(simp add: ders_correctness)\napply(simp add: Ders_def)\nthm rest_def\napply(drule_tac x=\"s\" in spec)\napply(simp)\napply(erule disjE)\napply(simp)\napply(drule_tac x=\"drop (length s) (flat v2)\" in spec)\napply(simp add: drop_append)\ndone\n\nlemma royB:\n  assumes \"\\<forall>s. (s \\<in> L(ders (flat v1) r1) \\<and> \n              s \\<sqsubseteq> (flat v2) \\<and> drop (length s) (flat v2) \\<in> L r2 \\<longrightarrow> s = [])\"\n  shows \"\\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = flat v2 \\<and> (flat v1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\" \nusing assms\napply -\napply(auto simp add: prefix_def ders_correctness Ders_def)\nby (metis append_eq_conv_conj)\n\nlemma royC: \n  assumes \"\\<forall>s t. (s \\<in> L(ders (flat v1) r1) \\<and> \n                s \\<sqsubseteq> (flat v2 @ t) \\<and> drop (length s) (flat v2 @ t) \\<in> L r2 \\<longrightarrow> s = [])\" \n  shows \"\\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = flat v2 \\<and> (flat v1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\"\nusing assms\napply -\napply(rule royB)\napply(rule allI)\napply(drule_tac x=\"s\" in spec)\napply(drule_tac x=\"[]\" in spec)\napply(simp)\ndone\n\ninductive \n  Roy2 :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" (\"2\\<rhd> _ : _\" [100, 100] 100)\nwhere\n  \"2\\<rhd> Void : EMPTY\"\n| \"2\\<rhd> Char c : CHAR c\"\n| \"2\\<rhd> v : r1 \\<Longrightarrow> 2\\<rhd> Left v : ALT r1 r2\"\n| \"\\<lbrakk>2\\<rhd> v : r2; \\<forall>t. flat v \\<notin> (L r1 ;; {t})\\<rbrakk> \\<Longrightarrow> 2\\<rhd> Right v : ALT r1 r2\"\n| \"\\<lbrakk>2\\<rhd> v1 : r1; 2\\<rhd> v2 : r2;\n    \\<forall>s. ((flat v1 @ s \\<in> L r1) \\<and> \n         (\\<exists>t. s \\<sqsubseteq> (flat v2 @ t) \\<and> drop (length s) (flat v2) \\<in> (L r2 ;; {t}))) \\<longrightarrow> s = []\\<rbrakk> \\<Longrightarrow>\n    2\\<rhd> Seq v1 v2 : SEQ r1 r2\"\n| \"\\<lbrakk>2\\<rhd> v : r; 2\\<rhd> Stars vs : STAR r; flat v \\<noteq> []; \n    \\<forall>s. ((flat v @ s \\<in> L r) \\<and> \n       (\\<exists>t. s \\<sqsubseteq> (flat (Stars vs) @ t) \\<and> drop (length s) (flat (Stars vs)) \\<in> (L (STAR r) ;; {t}))) \\<longrightarrow> s = []\\<rbrakk>\n    \\<Longrightarrow> 2\\<rhd> Stars (v#vs) : STAR r\"\n| \"2\\<rhd> Stars [] : STAR r\"\n\nlemma Roy2_props:\n  assumes \"2\\<rhd> v : r\"\n  shows \"\\<turnstile> v : r\"\nusing assms\napply(induct)\napply(auto intro: Prf.intros)\ndone\n\nlemma Roy_mkeps_nullable:\n  assumes \"nullable(r)\" \n  shows \"2\\<rhd> (mkeps r) : r\"\nusing assms\napply(induct rule: nullable.induct)\napply(auto intro: Roy2.intros)\napply(rule Roy2.intros)\napply(simp_all)\napply(simp add: mkeps_flat)\napply(simp add: Sequ_def)\napply (metis nullable_correctness)\napply(rule Roy2.intros)\napply(simp_all)\napply(rule allI)\napply(rule impI)\napply(auto simp add: Sequ_def)\napply(simp add: mkeps_flat)\napply(auto simp add: prefix_def)\ndone\n\nsection {* Alternative Posix definition *}\n\ninductive \n  PMatch :: \"string \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ \\<in> _ \\<rightarrow> _\" [100, 100, 100] 100)\nwhere\n  \"[] \\<in> EMPTY \\<rightarrow> Void\"\n| \"[c] \\<in> (CHAR c) \\<rightarrow> (Char c)\"\n| \"s \\<in> r1 \\<rightarrow> v \\<Longrightarrow> s \\<in> (ALT r1 r2) \\<rightarrow> (Left v)\"\n| \"\\<lbrakk>s \\<in> r2 \\<rightarrow> v; s \\<notin> L(r1)\\<rbrakk> \\<Longrightarrow> s \\<in> (ALT r1 r2) \\<rightarrow> (Right v)\"\n| \"\\<lbrakk>s1 \\<in> r1 \\<rightarrow> v1; s2 \\<in> r2 \\<rightarrow> v2;\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r1 \\<and> s\\<^sub>4 \\<in> L r2)\\<rbrakk> \\<Longrightarrow> \n    (s1 @ s2) \\<in> (SEQ r1 r2) \\<rightarrow> (Seq v1 v2)\"\n| \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; s2 \\<in> STAR r \\<rightarrow> Stars vs; flat v \\<noteq> [];\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> s\\<^sub>3 @ s\\<^sub>4 = s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\\<rbrakk>\n    \\<Longrightarrow> (s1 @ s2) \\<in> STAR r \\<rightarrow> Stars (v # vs)\"\n| \"[] \\<in> STAR r \\<rightarrow> Stars []\"\n\ninductive \n  PMatchX :: \"string \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"\\<turnstile> _ \\<in> _ \\<rightarrow> _\" [100, 100, 100] 100)\nwhere\n  \"\\<turnstile> s \\<in> EMPTY \\<rightarrow> Void\"\n| \"\\<turnstile> (c # s) \\<in> (CHAR c) \\<rightarrow> (Char c)\"\n| \"\\<turnstile> s \\<in> r1 \\<rightarrow> v \\<Longrightarrow> \\<turnstile> s \\<in> (ALT r1 r2) \\<rightarrow> (Left v)\"\n| \"\\<lbrakk>\\<turnstile> s \\<in> r2 \\<rightarrow> v; \\<not>(\\<exists>s'. s' \\<sqsubseteq> s \\<and> flat v \\<sqsubseteq> s' \\<and> s' \\<in> L(r1))\\<rbrakk> \\<Longrightarrow> \\<turnstile> s \\<in> (ALT r1 r2) \\<rightarrow> (Right v)\"\n| \"\\<lbrakk>s1 \\<in> r1 \\<rightarrow> v1; \\<turnstile> s2 \\<in> r2 \\<rightarrow> v2;\n    \\<not>(\\<exists>s3 s4. s3 \\<noteq> [] \\<and> (s3 @ s4) \\<sqsubseteq> s2 \\<and> (s1 @ s3) \\<in> L r1 \\<and> s4 \\<in> L r2)\\<rbrakk> \\<Longrightarrow> \n    \\<turnstile> (s1 @ s2) \\<in> (SEQ r1 r2) \\<rightarrow> (Seq v1 v2)\"\n| \"\\<lbrakk>s1 \\<in> r \\<rightarrow> v; \\<turnstile> s2 \\<in> STAR r \\<rightarrow> Stars vs; flat v \\<noteq> [];\n    \\<not>(\\<exists>s\\<^sub>3 s\\<^sub>4. s\\<^sub>3 \\<noteq> [] \\<and> (s\\<^sub>3 @ s\\<^sub>4) \\<sqsubseteq> s2 \\<and> (s1 @ s\\<^sub>3) \\<in> L r \\<and> s\\<^sub>4 \\<in> L (STAR r))\\<rbrakk>\n    \\<Longrightarrow> \\<turnstile> (s1 @ s2) \\<in> STAR r \\<rightarrow> Stars (v # vs)\"\n| \"\\<turnstile> s \\<in> STAR r \\<rightarrow> Stars []\"\n\nlemma PMatch1:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"\\<turnstile> v : r\" \"flat v = s\"\nusing assms\napply(induct s r v rule: PMatch.induct)\napply(auto)\napply (metis Prf.intros(4))\napply (metis Prf.intros(5))\napply (metis Prf.intros(2))\napply (metis Prf.intros(3))\napply (metis Prf.intros(1))\napply (metis Prf.intros(7))\nby (metis Prf.intros(6))\n\n\nlemma PMatchX1:\n  assumes \"\\<turnstile> s \\<in> r \\<rightarrow> v\"\n  shows \"\\<turnstile> v : r\"\nusing assms\napply(induct s r v rule: PMatchX.induct)\napply(auto simp add: prefix_def intro: Prf.intros)\napply (metis PMatch1(1) Prf.intros(1))\nby (metis PMatch1(1) Prf.intros(7))\n\n\nlemma PMatchX:\n  assumes \"\\<turnstile> s \\<in> r \\<rightarrow> v\"\n  shows \"flat v \\<sqsubseteq> s\"\nusing assms\napply(induct s r v rule: PMatchX.induct)\napply(auto simp add: prefix_def PMatch1)\ndone\n\nlemma PMatchX_PMatch:\n  assumes \"\\<turnstile> s \\<in> r \\<rightarrow> v\" \"flat v = s\"\n  shows \"s \\<in> r \\<rightarrow> v\"\nusing assms\napply(induct s r v rule: PMatchX.induct)\napply(auto intro: PMatch.intros)\napply(rule PMatch.intros)\napply(simp)\napply (metis PMatchX Prefixes_def mem_Collect_eq)\napply (smt2 PMatch.intros(5) PMatch1(2) PMatchX append_Nil2 append_assoc append_self_conv prefix_def)\nby (metis L.simps(6) PMatch.intros(6) PMatch1(2) append_Nil2 append_eq_conv_conj prefix_def)\n\nlemma PMatch_PMatchX:\n  assumes \"s \\<in> r \\<rightarrow> v\" \n  shows \"\\<turnstile> s \\<in> r \\<rightarrow> v\"\nusing assms\napply(induct s r v arbitrary: s' rule: PMatch.induct)\napply(auto intro: PMatchX.intros)\napply(rule PMatchX.intros)\napply(simp)\napply(rule notI)\napply(auto)[1]\napply (metis PMatch1(2) append_eq_conv_conj length_sprefix less_imp_le_nat prefix_def sprefix_def take_all)\napply(rule PMatchX.intros)\napply(simp)\napply(simp)\napply(auto)[1]\noops\n\nlemma \n  assumes \"\\<rhd> v : r\"\n  shows \"(flat v) \\<in> r \\<rightarrow> v\"\nusing assms\napply(induct)\napply(auto intro: PMatch.intros)\napply(rule PMatch.intros)\napply(simp)\napply(simp)\napply(simp)\napply(auto)[1]\ndone\n\nlemma \n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"\\<rhd> v : r\"\nusing assms\napply(induct)\napply(auto intro: Roy.intros)\napply (metis PMatch1(2) Roy.intros(4))\napply (metis PMatch1(2) Roy.intros(5))\nby (metis L.simps(6) PMatch1(2) Roy.intros(6))\n\n\nlemma PMatch_mkeps:\n  assumes \"nullable r\"\n  shows \"[] \\<in> r \\<rightarrow> mkeps r\"\nusing assms\napply(induct r)\napply(auto)\napply (metis PMatch.intros(1))\napply(subst append.simps(1)[symmetric])\napply (rule PMatch.intros)\napply(simp)\napply(simp)\napply(auto)[1]\napply (rule PMatch.intros)\napply(simp)\napply (rule PMatch.intros)\napply(simp)\napply (rule PMatch.intros)\napply(simp)\napply (metis nullable_correctness)\napply(metis PMatch.intros(7))\ndone\n\n\nlemma PMatch1N:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"\\<Turnstile> v : r\" \nusing assms\napply(induct s r v rule: PMatch.induct)\napply(auto)\napply (metis NPrf.intros(4))\napply (metis NPrf.intros(5))\napply (metis NPrf.intros(2))\napply (metis NPrf.intros(3))\napply (metis NPrf.intros(1))\napply(rule NPrf.intros)\napply(simp)\napply(simp)\napply(simp)\napply(rule NPrf.intros)\ndone\n\nlemma PMatch_determ:\n  shows \"\\<lbrakk>s \\<in> r \\<rightarrow> v1; s \\<in> r \\<rightarrow> v2\\<rbrakk> \\<Longrightarrow> v1 = v2\"\n  and   \"\\<lbrakk>s \\<in> (STAR r) \\<rightarrow> Stars vs1; s \\<in> (STAR r) \\<rightarrow> Stars vs2\\<rbrakk> \\<Longrightarrow> vs1 = vs2\"\napply(induct v1 and vs1 arbitrary: s r v2 and s r vs2 rule: val.inducts)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(subgoal_tac \"s1 = s1a \\<and> s2 = s2a\")\napply metis\napply(rule conjI)\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply (metis PMatch1(1) PMatch1(2) Prf_flat_L)\napply (metis PMatch1(1) PMatch1(2) Prf_flat_L)\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply (metis PMatch1(1) PMatch1(2) Prf_flat_L)\napply (metis PMatch1(1) PMatch1(2) Prf_flat_L)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply (metis NPrf_flat_L PMatch1(2) PMatch1N)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply (metis NPrf_flat_L PMatch1(2) PMatch1N)\n(* star case *)\ndefer\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply (metis PMatch1(2))\napply(rotate_tac  3)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(subgoal_tac \"s1 = s1a \\<and> s2 = s2a\")\napply metis\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply (metis L.simps(6) PMatch1(1) PMatch1(2) Prf_flat_L)\napply (metis L.simps(6) PMatch1(1) PMatch1(2) Prf_flat_L)\napply (metis L.simps(6) PMatch1(1) PMatch1(2) Prf_flat_L)\napply (metis L.simps(6) PMatch1(1) PMatch1(2) Prf_flat_L)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply (metis PMatch1(2))\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(subgoal_tac \"s1 = s1a \\<and> s2 = s2a\")\napply(drule_tac x=\"s1 @ s2\" in meta_spec)\napply(drule_tac x=\"rb\" in meta_spec)\napply(drule_tac x=\"(va#vsa)\" in meta_spec)\napply(simp)\napply(drule meta_mp)\napply (metis L.simps(6) PMatch.intros(6))\napply (metis L.simps(6) PMatch.intros(6))\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply (metis L.simps(6) NPrf_flat_L PMatch1(2) PMatch1N)\napply (metis L.simps(6) NPrf_flat_L PMatch1(2) PMatch1N)\napply (metis L.simps(6) NPrf_flat_L PMatch1(2) PMatch1N)\napply (metis L.simps(6) NPrf_flat_L PMatch1(2) PMatch1N)\napply (metis PMatch1(2))\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\nby (metis PMatch1(2))\n\n\nlemma PMatch_Values:\n  assumes \"s \\<in> r \\<rightarrow> v\"\n  shows \"v \\<in> Values r s\"\nusing assms\napply(simp add: Values_def PMatch1)\nby (metis append_Nil2 prefix_def)\n\nlemma PMatch2:\n  assumes \"s \\<in> (der c r) \\<rightarrow> v\"\n  shows \"(c#s) \\<in> r \\<rightarrow> (injval r c v)\"\nusing assms\napply(induct c r arbitrary: s v rule: der.induct)\napply(auto)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(case_tac \"c = c'\")\napply(simp)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis PMatch.intros(2))\napply(simp)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis PMatch.intros(3))\napply(clarify)\napply(rule PMatch.intros)\napply metis\napply(simp add: L_flat_NPrf)\napply(auto)[1]\napply(frule_tac c=\"c\" in v3_proj)\napply metis\napply(drule_tac x=\"projval r1 c v\" in spec)\napply(drule mp)\napply (metis v4_proj2)\napply (metis NPrf_imp_Prf)\n(* SEQ case *)\napply(case_tac \"nullable r1\")\napply(simp)\nprefer 2\napply(simp)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(subst append.simps(2)[symmetric])\napply(rule PMatch.intros)\napply metis\napply metis\napply(auto)[1]\napply(simp add: der_correctness Der_def)\napply(auto)[1]\n(* nullable case *)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[4]\napply(clarify)\napply(simp (no_asm))\napply(subst append.simps(2)[symmetric])\napply(rule PMatch.intros)\napply metis\napply metis\napply(erule contrapos_nn)\napply(erule exE)+\napply(auto)[1]\napply(simp add: L_flat_NPrf)\napply(auto)[1]\nthm v3_proj\napply(frule_tac c=\"c\" in v3_proj)\napply metis\napply(rule_tac x=\"s\\<^sub>3\" in exI)\napply(simp)\napply (metis NPrf_imp_Prf v4_proj2)\napply(simp)\n(* interesting case *)\napply(clarify)\napply(clarify)\napply(simp)\napply(subst (asm) L.simps(4)[symmetric])\napply(simp only: L_flat_Prf)\napply(simp)\napply(subst append.simps(1)[symmetric])\napply(rule PMatch.intros)\napply (metis PMatch_mkeps)\napply metis\napply(auto)\napply(simp only: L_flat_NPrf)\napply(simp)\napply(auto)\napply(drule_tac x=\"Seq (projval r1 c v) vb\" in spec)\napply(drule mp)\napply(simp)\n\napply (metis append_Cons butlast_snoc list.sel(1) neq_Nil_conv rotate1.simps(2) v4_proj2)\napply(subgoal_tac \"\\<turnstile> projval r1 c v : der c r1\")\napply (metis NPrf_imp_Prf Prf.intros(1))\napply(rule NPrf_imp_Prf)\napply(rule v3_proj)\napply(simp)\napply (metis Cons_eq_append_conv)\n(* Stars case *)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(rotate_tac 2)\napply(frule_tac PMatch1)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(subst append.simps(2)[symmetric])\napply(rule PMatch.intros)\napply metis\napply(auto)[1]\napply(rule PMatch.intros)\napply(simp)\napply(simp)\napply(simp)\napply (metis L.simps(6))\napply(subst v4)\napply (metis NPrf_imp_Prf PMatch1N)\napply(simp)\napply(auto)[1]\napply(drule_tac x=\"s\\<^sub>3\" in spec)\napply(drule mp)\ndefer\napply metis\napply(clarify)\napply(drule_tac x=\"s1\" in meta_spec)\napply(drule_tac x=\"v1\" in meta_spec)\napply(simp)\napply(rotate_tac 2)\napply(drule PMatch.intros(6))\napply(rule PMatch.intros(7))\napply (metis PMatch1(1) list.distinct(1) v4)\napply (metis Nil_is_append_conv)\napply(simp)\napply(subst der_correctness)\napply(simp add: Der_def)\ndone\n\n\n\nlemma Sequ_single:\n  \"(A ;; {t}) = {s @ t | s . s \\<in> A}\"\napply(simp add: Sequ_def)\ndone\n\nlemma Sequ_not:\n  assumes \"\\<forall>t. s \\<notin> (L(der c r1) ;; {t})\" \"L r1 \\<noteq> {}\" \n  shows \"\\<forall>t. c # s \\<notin> (L r1 ;; {t})\"\nusing assms\napply(simp add: der_correctness)\napply(simp add: Der_def)\napply(simp add: Sequ_def)\napply(rule allI)+\napply(rule impI)\napply(simp add: Cons_eq_append_conv)\napply(auto)\n\noops\n\nlemma PMatch_Roy2:\n  assumes \"2\\<rhd> v : (der c r)\" \"\\<exists>s. c # s \\<in> L r\"\n  shows \"2\\<rhd> (injval r c v) : r\"\nusing assms\napply(induct c r arbitrary: v rule: der.induct)\napply(auto)\napply(erule Roy2.cases)\napply(simp_all)\napply (metis Roy2.intros(2))\n(* alt case *)\napply(erule Roy2.cases)\napply(simp_all)\napply(clarify)\napply (metis Roy2.intros(3))\napply(clarify)\napply(rule Roy2.intros(4))\napply (metis (full_types) Prf_flat_L Roy2_props v3 v4)\napply(subgoal_tac \"\\<forall>t. c # flat va \\<notin> L r1 ;; {t}\")\nprefer 2\napply(simp add: der_correctness)\napply(simp add: Der_def)\napply(simp add: Sequ_def)\napply(rule allI)+\napply(rule impI)\napply(simp add: Cons_eq_append_conv)\napply(erule disjE)\napply(erule conjE)\nprefer 2\napply metis\napply(simp)\napply(drule_tac x=\"[]\" in spec)\napply(drule_tac x=\"drop 1 t\" in spec)\napply(clarify)\napply(simp)\noops \n\nlemma lex_correct1:\n  assumes \"s \\<notin> L r\"\n  shows \"lex r s = None\"\nusing assms\napply(induct s arbitrary: r)\napply(simp)\napply (metis nullable_correctness)\napply(auto)\napply(drule_tac x=\"der a r\" in meta_spec)\napply(drule meta_mp)\napply(auto)\napply(simp add: L_flat_Prf)\nby (metis v3 v4)\n\n\nlemma lex_correct2:\n  assumes \"s \\<in> L r\"\n  shows \"\\<exists>v. lex r s = Some(v) \\<and> \\<turnstile> v : r \\<and> flat v = s\"\nusing assms\napply(induct s arbitrary: r)\napply(simp)\napply (metis mkeps_flat mkeps_nullable nullable_correctness)\napply(drule_tac x=\"der a r\" in meta_spec)\napply(drule meta_mp)\napply(simp add: L_flat_NPrf)\napply(auto)\napply (metis v3_proj v4_proj2)\napply (metis v3)\napply(rule v4)\nby metis\n\nlemma lex_correct3:\n  assumes \"s \\<in> L r\"\n  shows \"\\<exists>v. lex r s = Some(v) \\<and> s \\<in> r \\<rightarrow> v\"\nusing assms\napply(induct s arbitrary: r)\napply(simp)\napply (metis PMatch_mkeps nullable_correctness)\napply(drule_tac x=\"der a r\" in meta_spec)\napply(drule meta_mp)\napply(simp add: L_flat_NPrf)\napply(auto)\napply (metis v3_proj v4_proj2)\napply(rule PMatch2)\napply(simp)\ndone\n\nlemma lex_correct4:\n  assumes \"s \\<in> L r\"\n  shows \"\\<exists>v. lex r s = Some(v) \\<and> \\<Turnstile> v : r \\<and> flat v = s\"\nusing lex_correct3[OF assms]\napply(auto)\napply (metis PMatch1N)\nby (metis PMatch1(2))\n\n\nlemma lex_correct5:\n  assumes \"s \\<in> L r\"\n  shows \"s \\<in> r \\<rightarrow> (lex2 r s)\"\nusing assms\napply(induct s arbitrary: r)\napply(simp)\napply (metis PMatch_mkeps nullable_correctness)\napply(simp)\napply(rule PMatch2)\napply(drule_tac x=\"der a r\" in meta_spec)\napply(drule meta_mp)\napply(simp add: L_flat_NPrf)\napply(auto)\napply (metis v3_proj v4_proj2)\ndone\n\nlemma \n  \"lex2 (ALT (CHAR a) (ALT (CHAR b) (SEQ (CHAR a) (CHAR b)))) [a,b] = Right (Right (Seq (Char a) (Char b)))\"\napply(simp)\ndone\n\n\n(* NOT DONE YET *)\n\nsection {* Sulzmann's Ordering of values *}\n\ninductive ValOrd :: \"val \\<Rightarrow> rexp \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ \\<succ>_ _\" [100, 100, 100] 100)\nwhere\n  \"v2 \\<succ>r2 v2' \\<Longrightarrow> (Seq v1 v2) \\<succ>(SEQ r1 r2) (Seq v1 v2')\" \n| \"\\<lbrakk>v1 \\<succ>r1 v1'; v1 \\<noteq> v1'\\<rbrakk> \\<Longrightarrow> (Seq v1 v2) \\<succ>(SEQ r1 r2) (Seq v1' v2')\" \n| \"length (flat v1) \\<ge> length (flat v2) \\<Longrightarrow> (Left v1) \\<succ>(ALT r1 r2) (Right v2)\"\n| \"length (flat v2) > length (flat v1) \\<Longrightarrow> (Right v2) \\<succ>(ALT r1 r2) (Left v1)\"\n| \"v2 \\<succ>r2 v2' \\<Longrightarrow> (Right v2) \\<succ>(ALT r1 r2) (Right v2')\"\n| \"v1 \\<succ>r1 v1' \\<Longrightarrow> (Left v1) \\<succ>(ALT r1 r2) (Left v1')\"\n| \"Void \\<succ>EMPTY Void\"\n| \"(Char c) \\<succ>(CHAR c) (Char c)\"\n| \"flat (Stars (v # vs)) = [] \\<Longrightarrow> (Stars []) \\<succ>(STAR r) (Stars (v # vs))\"\n| \"flat (Stars (v # vs)) \\<noteq> [] \\<Longrightarrow> (Stars (v # vs)) \\<succ>(STAR r) (Stars [])\"\n| \"\\<lbrakk>v1 \\<succ>r v2; v1 \\<noteq> v2\\<rbrakk> \\<Longrightarrow> (Stars (v1 # vs1)) \\<succ>(STAR r) (Stars (v2 # vs2))\"\n| \"(Stars vs1) \\<succ>(STAR r) (Stars vs2) \\<Longrightarrow> (Stars (v # vs1)) \\<succ>(STAR r) (Stars (v # vs2))\"\n| \"(Stars []) \\<succ>(STAR r) (Stars [])\"\n\nlemma PMatch_ValOrd:\n  assumes \"s \\<in> r \\<rightarrow> v\" \"v' \\<in> SValues r s\"\n  shows \"v \\<succ>r v'\"\nusing assms\napply(induct r arbitrary: v v' s rule: rexp.induct)\napply(simp add: SValues_recs)\napply(simp add: SValues_recs)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(7))\napply(simp add: SValues_recs)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(8) empty_iff singletonD)\napply(simp add: SValues_recs)\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply(clarify)\napply(case_tac \"v1a = v1\")\napply(simp)\napply(rule ValOrd.intros)\napply(rotate_tac 1)\napply(drule_tac x=\"v2a\" in meta_spec)\napply(rotate_tac 8)\napply(drule_tac x=\"v2\" in meta_spec)\napply(drule_tac x=\"s2a\" in meta_spec)\napply(simp)\napply(drule_tac meta_mp)\napply(simp add: SValues_def)\napply (metis PMatch1(2) same_append_eq)\napply(simp)\napply(rule ValOrd.intros)\napply(drule_tac x=\"v1a\" in meta_spec)\napply(rotate_tac 8)\napply(drule_tac x=\"v1\" in meta_spec)\napply(drule_tac x=\"s1a\" in meta_spec)\napply(simp)\napply(drule_tac meta_mp)\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply(case_tac \"us=[]\")\napply(simp)\napply(drule_tac x=\"us\" in spec)\napply(drule mp)\napply(simp add: SValues_def)\napply (metis Prf_flat_L)\napply(erule disjE)\napply(simp)\napply(simp)\napply(simp add: SValues_def)\napply (metis Prf_flat_L)\n\napply(subst (asm) (2) Values_def)\napply(simp)\napply(clarify)\napply(simp add: rest_def)\napply(simp add: prefix_def)\napply(auto)[1]\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply(case_tac \"us = []\")\napply(simp)\napply(simp add: Values_def)\napply (metis append_Nil2 prefix_def)\napply(drule_tac x=\"us\" in spec)\napply(simp)\napply(drule_tac mp)\n\n\noops\n(*HERE *)\n\ninductive ValOrd2 :: \"val \\<Rightarrow> string \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ 2\\<succ>_ _\" [100, 100, 100] 100)\nwhere \n  \"v2 2\\<succ>s v2' \\<Longrightarrow> (Seq v1 v2) 2\\<succ>(flat v1 @ s) (Seq v1 v2')\" \n| \"\\<lbrakk>v1 2\\<succ>s v1'; v1 \\<noteq> v1'\\<rbrakk> \\<Longrightarrow> (Seq v1 v2) 2\\<succ>s (Seq v1' v2')\" \n| \"(flat v2) \\<sqsubseteq> (flat v1) \\<Longrightarrow> (Left v1) 2\\<succ>(flat v1) (Right v2)\"\n| \"(flat v1) \\<sqsubset> (flat v2) \\<Longrightarrow> (Right v2) 2\\<succ>(flat v2) (Left v1)\"\n| \"v2 2\\<succ>s v2' \\<Longrightarrow> (Right v2) 2\\<succ>s (Right v2')\"\n| \"v1 2\\<succ>s v1' \\<Longrightarrow> (Left v1) 2\\<succ>s (Left v1')\" \n| \"Void 2\\<succ>[] Void\"\n| \"(Char c) 2\\<succ>[c] (Char c)\" \n| \"flat (Stars (v # vs)) = [] \\<Longrightarrow> (Stars []) 2\\<succ>[] (Stars (v # vs))\"\n| \"flat (Stars (v # vs)) \\<noteq> [] \\<Longrightarrow> (Stars (v # vs)) 2\\<succ>(flat (Stars (v # vs))) (Stars [])\"\n| \"\\<lbrakk>v1 2\\<succ>s v2; v1 \\<noteq> v2\\<rbrakk> \\<Longrightarrow> (Stars (v1 # vs1)) 2\\<succ>s (Stars (v2 # vs2))\"\n| \"(Stars vs1) 2\\<succ>s (Stars vs2) \\<Longrightarrow> (Stars (v # vs1)) 2\\<succ>(flat v @ s) (Stars (v # vs2))\"\n| \"(Stars []) 2\\<succ>[] (Stars [])\"\n\nlemma ValOrd2_string1:\n  assumes \"v1 2\\<succ>s v2\"\n  shows \"s \\<sqsubseteq> flat v1\"\nusing assms\napply(induct)\napply(auto simp add: prefix_def)\napply (metis append_assoc)\nby (metis append_assoc)\n\n\nlemma admissibility:\n  assumes \"s \\<in> r \\<rightarrow> v\" \"\\<turnstile> v' : r\" \n  shows \"(\\<forall>s'. (s' \\<in> L(r) \\<and> s' \\<sqsubseteq> s) \\<longrightarrow> v 2\\<succ>s' v')\"\nusing assms\napply(induct arbitrary: v')\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd2.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd2.intros(8) append_Nil2 prefix_Cons prefix_append prefix_def)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)[1]\napply (metis ValOrd2.intros(6))\napply(rule ValOrd2.intros)\napply(drule_tac x=\"v1\" in meta_spec)\napply(simp)\n\napply(clarify)\napply (metis PMatch1(2) ValOrd2.intros(3))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)\n\napply(case_tac \"v1 = v1a\")\napply(simp)\napply(rotate_tac 3)\napply(drule_tac x=\"v2a\" in meta_spec)\napply(drule meta_mp)\napply(simp)\napply(auto)\napply(rule_tac x=\"flat v1a @ s'\" in exI)\napply (metis PMatch1(2) ValOrd2.intros(1) prefix_append)\napply (metis PMatch1(2) ValOrd2.intros(2) ValOrd2_string1 flat.simps(5))\nprefer 4\napply(erule Prf.cases)\napply(simp_all)[7]\nprefer 2\napply (metis ValOrd2.intros(5))\n\n\napply (metis ValOrd.intros(6))\noops\n\n\nlemma admissibility:\n  assumes \"\\<turnstile> s \\<in> r \\<rightarrow> v\" \"\\<turnstile> v' : r\" \n  shows \"v \\<succ>r v'\"\nusing assms\napply(induct arbitrary: v')\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(6))\noops\n\nlemma admissibility:\n  assumes \"2\\<rhd> v : r\" \"\\<turnstile> v' : r\" \"flat v' \\<sqsubseteq> flat v\"\n  shows \"v \\<succ>r v'\"\nusing assms\napply(induct arbitrary: v')\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(6))\napply (metis ValOrd.intros(3) length_sprefix less_imp_le_nat order_refl sprefix_def)\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis Prf_flat_L ValOrd.intros(4) length_sprefix seq_empty(1) sprefix_def)\napply (metis ValOrd.intros(5))\noops\n\n\nlemma admisibility:\n  assumes \"\\<rhd> v : r\" \"\\<turnstile> v' : r\"\n  shows \"v \\<succ>r v'\"\nusing assms\napply(induct arbitrary: v')\nprefer 5\napply(drule royA)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(case_tac \"v1 = v1a\")\napply(simp)\napply(rule ValOrd.intros)\napply metis\napply (metis ValOrd.intros(2))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(6))\napply(rule ValOrd.intros)\ndefer\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(rule ValOrd.intros)\n(* seq case goes through *)\noops\n\n\nlemma admisibility:\n  assumes \"\\<rhd> v : r\" \"\\<turnstile> v' : r\" \"flat v' \\<sqsubseteq> flat v\"\n  shows \"v \\<succ>r v'\"\nusing assms\napply(induct arbitrary: v')\nprefer 5\napply(drule royA)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(case_tac \"v1 = v1a\")\napply(simp)\napply(rule ValOrd.intros)\napply(subst (asm) (3) prefix_def)\napply(erule exE)\napply(simp)\napply (metis prefix_def)\n(* the unequal case *)\napply(subgoal_tac \"flat v1 \\<sqsubset> flat v1a \\<or> flat v1a \\<sqsubseteq> flat v1\")\nprefer 2\napply(simp add: prefix_def sprefix_def)\napply (metis append_eq_append_conv2)\napply(erule disjE)\n(* first case  flat v1 \\<sqsubset> flat v1a *)\napply(subst (asm) sprefix_def)\napply(subst (asm) (5) prefix_def)\napply(clarify)\napply(subgoal_tac \"(s3 @ flat v2a) \\<sqsubseteq> flat v2\")\nprefer 2\napply(simp)\napply (metis append_assoc prefix_append)\napply(subgoal_tac \"s3 \\<noteq> []\")\nprefer 2\napply (metis append_Nil2)\n(* HERE *)\napply(subst (asm) (5) prefix_def)\napply(erule exE)\napply(simp add: ders_correctness Ders_def)\napply(simp add: prefix_def)\napply(clarify)\napply(subst (asm) append_eq_append_conv2)\napply(erule exE)\napply(erule disjE)\napply(clarify)\noops\n\n\n\nlemma ValOrd_refl:\n  assumes \"\\<turnstile> v : r\"\n  shows \"v \\<succ>r v\"\nusing assms\napply(induct)\napply(auto intro: ValOrd.intros)\ndone\n\nlemma ValOrd_total:\n  shows \"\\<lbrakk>\\<turnstile> v1 : r; \\<turnstile> v2 : r\\<rbrakk>  \\<Longrightarrow> v1 \\<succ>r v2 \\<or> v2 \\<succ>r v1\"\napply(induct r arbitrary: v1 v2)\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply(case_tac \"v1a = v1b\")\napply(simp)\napply(rule ValOrd.intros(1))\napply (metis ValOrd.intros(1))\napply(rule ValOrd.intros(2))\napply(auto)[2]\napply(erule contrapos_np)\napply(rule ValOrd.intros(2))\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(clarify)\napply (metis ValOrd.intros(6))\napply(rule ValOrd.intros)\napply(erule contrapos_np)\napply(rule ValOrd.intros)\napply (metis le_eq_less_or_eq neq_iff)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(rule ValOrd.intros)\napply(erule contrapos_np)\napply(rule ValOrd.intros)\napply (metis le_eq_less_or_eq neq_iff)\napply(rule ValOrd.intros)\napply(erule contrapos_np)\napply(rule ValOrd.intros)\napply(metis)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)\napply (metis ValOrd.intros(13))\napply (metis ValOrd.intros(10) ValOrd.intros(9))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(auto)\napply (metis ValOrd.intros(10) ValOrd.intros(9))\napply(case_tac \"v = va\")\nprefer 2\napply (metis ValOrd.intros(11))\napply(simp)\napply(rule ValOrd.intros(12))\napply(erule contrapos_np)\napply(rule ValOrd.intros(12))\noops\n\nlemma Roy_posix:\n  assumes \"\\<rhd> v : r\" \"\\<turnstile> v' : r\" \"flat v' \\<sqsubseteq> flat v\"\n  shows \"v \\<succ>r v'\"\nusing assms\napply(induct r arbitrary: v v' rule: rexp.induct)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Roy.cases)\napply(simp_all)\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Roy.cases)\napply(simp_all)\napply (metis ValOrd.intros(8))\nprefer 2\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Roy.cases)\napply(simp_all)\napply(clarify)\napply (metis ValOrd.intros(6))\napply(clarify)\napply (metis Prf_flat_L ValOrd.intros(4) length_sprefix sprefix_def)\napply(erule Roy.cases)\napply(simp_all)\napply (metis ValOrd.intros(3) length_sprefix less_imp_le_nat order_refl sprefix_def)\napply(clarify)\napply (metis ValOrd.intros(5))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Roy.cases)\napply(simp_all)\napply(clarify)\napply(case_tac \"v1a = v1\")\napply(simp)\napply(rule ValOrd.intros)\napply (metis prefix_append)\napply(rule ValOrd.intros)\nprefer 2\napply(simp)\napply(simp add: prefix_def)\napply(auto)[1]\napply(simp add: append_eq_append_conv2)\napply(auto)[1]\napply(drule_tac x=\"v1a\" in meta_spec)\napply(rotate_tac 9)\napply(drule_tac x=\"v1\" in meta_spec)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac x=\"us\" in spec)\napply(drule_tac mp)\napply (metis Prf_flat_L)\napply(auto)[1]\noops\n\n\nlemma ValOrd_anti:\n  shows \"\\<lbrakk>\\<turnstile> v1 : r; \\<turnstile> v2 : r; v1 \\<succ>r v2; v2 \\<succ>r v1\\<rbrakk> \\<Longrightarrow> v1 = v2\"\n  and   \"\\<lbrakk>\\<turnstile> Stars vs1 : r; \\<turnstile> Stars vs2 : r; Stars vs1 \\<succ>r Stars vs2; Stars vs2 \\<succ>r Stars vs1\\<rbrakk>  \\<Longrightarrow> vs1 = vs2\"\napply(induct v1 and vs1 arbitrary: r v2 and r vs2 rule: val.inducts)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(erule ValOrd.cases)\napply(simp_all)\napply(auto)[1]\nprefer 2\noops\n\n\n(*\n\nlemma ValOrd_PMatch:\n  assumes \"s \\<in> r \\<rightarrow> v1\" \"\\<turnstile> v2 : r\" \"flat v2  \\<sqsubseteq> s\"\n  shows \"v1 \\<succ>r v2\"\nusing assms\napply(induct r arbitrary: s v1 v2 rule: rexp.induct)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(8))\ndefer\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis ValOrd.intros(6))\napply (metis PMatch1(2) Prf_flat_L ValOrd.intros(4) length_sprefix sprefix_def)\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)[7]\napply (metis PMatch1(2) ValOrd.intros(3) length_sprefix less_imp_le_nat order_refl sprefix_def)\napply(clarify)\napply (metis ValOrd.intros(5))\n(* Stars case *)\napply(erule Prf.cases)\napply(simp_all)[7]\napply(erule PMatch.cases)\napply(simp_all)\napply (metis Nil_is_append_conv ValOrd.intros(10) flat.simps(7))\napply (metis ValOrd.intros(13))\napply(clarify)\napply(erule PMatch.cases)\napply(simp_all)\nprefer 2\napply(rule ValOrd.intros)\napply(simp add: prefix_def)\napply(rule ValOrd.intros)\napply(drule_tac x=\"s1\" in meta_spec)\napply(drule_tac x=\"va\" in meta_spec)\napply(drule_tac x=\"v\" in meta_spec)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\napply(simp add: prefix_def)\napply(auto)[1]\nprefer 3\n(* Seq case *)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(erule PMatch.cases)\napply(simp_all)[5]\napply(auto)\napply(case_tac \"v1b = v1a\")\napply(auto)\napply(simp add: prefix_def)\napply(auto)[1]\napply (metis PMatch1(2) ValOrd.intros(1) same_append_eq)\napply(simp add: prefix_def)\napply(auto)[1]\napply(simp add: append_eq_append_conv2)\napply(auto)\nprefer 2\napply (metis ValOrd.intros(2))\nprefer 2\napply (metis ValOrd.intros(2))\napply(case_tac \"us = []\")\napply(simp)\napply (metis ValOrd.intros(2) append_Nil2)\napply(drule_tac x=\"us\" in spec)\napply(simp)\napply(drule_tac mp)\napply (metis Prf_flat_L)\napply(drule_tac x=\"s1 @ us\" in meta_spec)\napply(drule_tac x=\"v1b\" in meta_spec)\napply(drule_tac x=\"v1a\" in meta_spec)\napply(drule_tac meta_mp)\n\napply(simp)\napply(drule_tac meta_mp)\napply(simp)\napply(simp)\napply(simp)\napply(clarify)\napply (metis ValOrd.intros(6))\napply(clarify)\napply (metis PMatch1(2) ValOrd.intros(3) length_sprefix less_imp_le_nat order_refl sprefix_def)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis PMatch1(2) Prf_flat_L ValOrd.intros(4) length_sprefix sprefix_def)\napply (metis ValOrd.intros(5))\n(* Seq case *)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(case_tac \"v1 = v1a\")\napply(auto)\napply(simp add: prefix_def)\napply(auto)[1]\napply (metis PMatch1(2) ValOrd.intros(1) same_append_eq)\napply(simp add: prefix_def)\napply(auto)[1]\napply(frule PMatch1)\napply(frule PMatch1(2)[symmetric])\napply(clarify)\napply(simp add: append_eq_append_conv2)\napply(auto)\nprefer 2\napply (metis ValOrd.intros(2))\nprefer 2\napply (metis ValOrd.intros(2))\napply(case_tac \"us = []\")\napply(simp)\napply (metis ValOrd.intros(2) append_Nil2)\napply(drule_tac x=\"us\" in spec)\napply(simp)\napply(drule mp)\napply (metis  Prf_flat_L)\napply(drule_tac x=\"v1a\" in meta_spec)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\napply(simp)\n\nlemma ValOrd_PMatch:\n  assumes \"s \\<in> r \\<rightarrow> v1\" \"\\<turnstile> v2 : r\" \"flat v2  \\<sqsubseteq> s\"\n  shows \"v1 \\<succ>r v2\"\nusing assms\napply(induct arbitrary: v2 rule: .induct)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis ValOrd.intros(6))\napply(clarify)\napply (metis PMatch1(2) ValOrd.intros(3) length_sprefix less_imp_le_nat order_refl sprefix_def)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis PMatch1(2) Prf_flat_L ValOrd.intros(4) length_sprefix sprefix_def)\napply (metis ValOrd.intros(5))\n(* Seq case *)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(case_tac \"v1 = v1a\")\napply(auto)\napply(simp add: prefix_def)\napply(auto)[1]\napply (metis PMatch1(2) ValOrd.intros(1) same_append_eq)\napply(simp add: prefix_def)\napply(auto)[1]\napply(frule PMatch1)\napply(frule PMatch1(2)[symmetric])\napply(clarify)\napply(simp add: append_eq_append_conv2)\napply(auto)\nprefer 2\napply (metis ValOrd.intros(2))\nprefer 2\napply (metis ValOrd.intros(2))\napply(case_tac \"us = []\")\napply(simp)\napply (metis ValOrd.intros(2) append_Nil2)\napply(drule_tac x=\"us\" in spec)\napply(simp)\napply(drule mp)\napply (metis  Prf_flat_L)\napply(drule_tac x=\"v1a\" in meta_spec)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\napply(simp)\n\napply (metis PMatch1(2) ValOrd.intros(1) same_append_eq)\napply(rule ValOrd.intros(2))\napply(auto)\napply(drule_tac x=\"v1a\" in meta_spec)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\nprefer 2\napply(simp)\nthm append_eq_append_conv\napply(simp add: append_eq_append_conv2)\napply(auto)\napply (metis Prf_flat_L)\napply(case_tac \"us = []\")\napply(simp)\napply(drule_tac x=\"us\" in spec)\napply(drule mp)\n\n\ninductive ValOrd2 :: \"val \\<Rightarrow> val \\<Rightarrow> bool\" (\"_ 2\\<succ> _\" [100, 100] 100)\nwhere\n  \"v2 2\\<succ> v2' \\<Longrightarrow> (Seq v1 v2) 2\\<succ> (Seq v1 v2')\" \n| \"\\<lbrakk>v1 2\\<succ> v1'; v1 \\<noteq> v1'\\<rbrakk> \\<Longrightarrow> (Seq v1 v2) 2\\<succ> (Seq v1' v2')\" \n| \"length (flat v1) \\<ge> length (flat v2) \\<Longrightarrow> (Left v1) 2\\<succ> (Right v2)\"\n| \"length (flat v2) > length (flat v1) \\<Longrightarrow> (Right v2) 2\\<succ> (Left v1)\"\n| \"v2 2\\<succ> v2' \\<Longrightarrow> (Right v2) 2\\<succ> (Right v2')\"\n| \"v1 2\\<succ> v1' \\<Longrightarrow> (Left v1) 2\\<succ> (Left v1')\"\n| \"Void 2\\<succ> Void\"\n| \"(Char c) 2\\<succ> (Char c)\"\n\nlemma Ord1:\n  \"v1 \\<succ>r v2 \\<Longrightarrow> v1 2\\<succ> v2\"\napply(induct rule: ValOrd.induct)\napply(auto intro: ValOrd2.intros)\ndone\n\nlemma Ord2:\n  \"v1 2\\<succ> v2 \\<Longrightarrow> \\<exists>r. v1 \\<succ>r v2\"\napply(induct v1 v2 rule: ValOrd2.induct)\napply(auto intro: ValOrd.intros)\ndone\n\nlemma Ord3:\n  \"\\<lbrakk>v1 2\\<succ> v2; \\<turnstile> v1 : r\\<rbrakk> \\<Longrightarrow> v1 \\<succ>r v2\"\napply(induct v1 v2 arbitrary: r rule: ValOrd2.induct)\napply(auto intro: ValOrd.intros elim: Prf.cases)\ndone\n\nsection {* Posix definition *}\n\ndefinition POSIX :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" \nwhere\n  \"POSIX v r \\<equiv> (\\<turnstile> v : r \\<and> (\\<forall>v'. (\\<turnstile> v' : r \\<and> flat v' \\<sqsubseteq> flat v) \\<longrightarrow> v \\<succ>r v'))\"\n\nlemma ValOrd_refl:\n  assumes \"\\<turnstile> v : r\"\n  shows \"v \\<succ>r v\"\nusing assms\napply(induct)\napply(auto intro: ValOrd.intros)\ndone\n\nlemma ValOrd_total:\n  shows \"\\<lbrakk>\\<turnstile> v1 : r; \\<turnstile> v2 : r\\<rbrakk>  \\<Longrightarrow> v1 \\<succ>r v2 \\<or> v2 \\<succ>r v1\"\napply(induct r arbitrary: v1 v2)\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(case_tac \"v1a = v1b\")\napply(simp)\napply(rule ValOrd.intros(1))\napply (metis ValOrd.intros(1))\napply(rule ValOrd.intros(2))\napply(auto)[2]\napply(erule contrapos_np)\napply(rule ValOrd.intros(2))\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Ord1 Ord3 Prf.intros(2) ValOrd2.intros(6))\napply(rule ValOrd.intros)\napply(erule contrapos_np)\napply(rule ValOrd.intros)\napply (metis le_eq_less_or_eq neq_iff)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule ValOrd.intros)\napply(erule contrapos_np)\napply(rule ValOrd.intros)\napply (metis le_eq_less_or_eq neq_iff)\napply(rule ValOrd.intros)\napply(erule contrapos_np)\napply(rule ValOrd.intros)\nby metis\n\nlemma ValOrd_anti:\n  shows \"\\<lbrakk>\\<turnstile> v1 : r; \\<turnstile> v2 : r; v1 \\<succ>r v2; v2 \\<succ>r v1\\<rbrakk> \\<Longrightarrow> v1 = v2\"\napply(induct r arbitrary: v1 v2)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(erule ValOrd.cases)\napply(simp_all)[8]\ndone\n\nlemma POSIX_ALT_I1:\n  assumes \"POSIX v1 r1\" \n  shows \"POSIX (Left v1) (ALT r1 r2)\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply (metis Prf.intros(2))\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd.intros)\napply(auto)\napply(rule ValOrd.intros)\nby (metis le_eq_less_or_eq length_sprefix sprefix_def)\n\nlemma POSIX_ALT_I2:\n  assumes \"POSIX v2 r2\" \"\\<forall>v'. \\<turnstile> v' : r1 \\<longrightarrow> length (flat v2) > length (flat v')\"\n  shows \"POSIX (Right v2) (ALT r1 r2)\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply (metis Prf.intros)\napply(rotate_tac 3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd.intros)\napply metis\napply(rule ValOrd.intros)\napply metis\ndone\n\nthm PMatch.intros[no_vars]\n\nlemma POSIX_PMatch:\n  assumes \"s \\<in> r \\<rightarrow> v\" \"\\<turnstile> v' : r\"\n  shows \"length (flat v') \\<le> length (flat v)\" \nusing assms\napply(induct arbitrary: s v v' rule: rexp.induct)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule PMatch.cases)\napply(simp_all)[5]\ndefer\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule PMatch.cases)\napply(simp_all)[5]\napply(clarify)\napply(simp add: L_flat_Prf)\n\napply(clarify)\napply (metis ValOrd.intros(8))\napply (metis POSIX_ALT_I1)\napply(rule POSIX_ALT_I2)\napply(simp)\napply(auto)[1]\napply(simp add: POSIX_def)\napply(frule PMatch1(1))\napply(frule PMatch1(2))\napply(simp)\n\n\nlemma POSIX_PMatch:\n  assumes \"s \\<in> r \\<rightarrow> v\" \n  shows \"POSIX v r\" \nusing assms\napply(induct arbitrary: rule: PMatch.induct)\napply(auto)\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(4))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(7))\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply (metis POSIX_ALT_I1)\napply(rule POSIX_ALT_I2)\napply(simp)\napply(auto)[1]\napply(simp add: POSIX_def)\napply(frule PMatch1(1))\napply(frule PMatch1(2))\napply(simp)\n\n\n\nlemma ValOrd_PMatch:\n  assumes \"s \\<in> r \\<rightarrow> v1\" \"\\<turnstile> v2 : r\" \"flat v2 = s\"\n  shows \"v1 \\<succ>r v2\"\nusing assms\napply(induct arbitrary: v2 rule: PMatch.induct)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis ValOrd.intros(6))\napply(clarify)\napply (metis PMatch1(2) ValOrd.intros(3) order_refl)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis Prf_flat_L)\napply (metis ValOrd.intros(5))\n(* Seq case *)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(case_tac \"v1 = v1a\")\napply(auto)\napply (metis PMatch1(2) ValOrd.intros(1) same_append_eq)\napply(rule ValOrd.intros(2))\napply(auto)\napply(drule_tac x=\"v1a\" in meta_spec)\napply(drule_tac meta_mp)\napply(simp)\napply(drule_tac meta_mp)\nprefer 2\napply(simp)\napply(simp add: append_eq_append_conv2)\napply(auto)\napply (metis Prf_flat_L)\napply(case_tac \"us = []\")\napply(simp)\napply(drule_tac x=\"us\" in spec)\napply(drule mp)\n\nthm L_flat_Prf\napply(simp add: L_flat_Prf)\nthm append_eq_append_conv2\napply(simp add: append_eq_append_conv2)\napply(auto)\napply(drule_tac x=\"us\" in spec)\napply(drule mp)\napply metis\napply (metis append_Nil2)\napply(case_tac \"us = []\")\napply(auto)\napply(drule_tac x=\"s2\" in spec)\napply(drule mp)\n\napply(auto)[1]\napply(drule_tac x=\"v1a\" in meta_spec)\napply(simp)\n\nlemma refl_on_ValOrd:\n  \"refl_on (Values r s) {(v1, v2). v1 \\<succ>r v2 \\<and> v1 \\<in> Values r s \\<and> v2 \\<in> Values r s}\"\nunfolding refl_on_def\napply(auto)\napply(rule ValOrd_refl)\napply(simp add: Values_def)\ndone\n\n\nsection {* Posix definition *}\n\ndefinition POSIX :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" \nwhere\n  \"POSIX v r \\<equiv> (\\<turnstile> v : r \\<and> (\\<forall>v'. (\\<turnstile> v' : r \\<and> flat v = flat v') \\<longrightarrow> v \\<succ>r v'))\"\n\ndefinition POSIX2 :: \"val \\<Rightarrow> rexp \\<Rightarrow> bool\" \nwhere\n  \"POSIX2 v r \\<equiv> (\\<turnstile> v : r \\<and> (\\<forall>v'. (\\<turnstile> v' : r \\<and> flat v = flat v') \\<longrightarrow> v 2\\<succ> v'))\"\n\nlemma \"POSIX v r = POSIX2 v r\"\nunfolding POSIX_def POSIX2_def\napply(auto)\napply(rule Ord1)\napply(auto)\napply(rule Ord3)\napply(auto)\ndone\n\nsection {* POSIX for some constructors *}\n\nlemma POSIX_SEQ1:\n  assumes \"POSIX (Seq v1 v2) (SEQ r1 r2)\" \"\\<turnstile> v1 : r1\" \"\\<turnstile> v2 : r2\"\n  shows \"POSIX v1 r1\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply(drule_tac x=\"Seq v' v2\" in spec)\napply(simp)\napply(erule impE)\napply(rule Prf.intros)\napply(simp)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)\napply(clarify)\nby (metis ValOrd_refl)\n\nlemma POSIX_SEQ2:\n  assumes \"POSIX (Seq v1 v2) (SEQ r1 r2)\" \"\\<turnstile> v1 : r1\" \"\\<turnstile> v2 : r2\" \n  shows \"POSIX v2 r2\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply(drule_tac x=\"Seq v1 v'\" in spec)\napply(simp)\napply(erule impE)\napply(rule Prf.intros)\napply(simp)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)\ndone\n\nlemma POSIX_ALT2:\n  assumes \"POSIX (Left v1) (ALT r1 r2)\"\n  shows \"POSIX v1 r1\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(drule_tac x=\"Left v'\" in spec)\napply(simp)\napply(drule mp)\napply(rule Prf.intros)\napply(auto)\napply(erule ValOrd.cases)\napply(simp_all)\ndone\n\nlemma POSIX_ALT1a:\n  assumes \"POSIX (Right v2) (ALT r1 r2)\"\n  shows \"POSIX v2 r2\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(drule_tac x=\"Right v'\" in spec)\napply(simp)\napply(drule mp)\napply(rule Prf.intros)\napply(auto)\napply(erule ValOrd.cases)\napply(simp_all)\ndone\n\nlemma POSIX_ALT1b:\n  assumes \"POSIX (Right v2) (ALT r1 r2)\"\n  shows \"(\\<forall>v'. (\\<turnstile> v' : r2 \\<and> flat v' = flat v2) \\<longrightarrow> v2 \\<succ>r2 v')\"\nusing assms\napply(drule_tac POSIX_ALT1a)\nunfolding POSIX_def\napply(auto)\ndone\n\nlemma POSIX_ALT_I1:\n  assumes \"POSIX v1 r1\" \n  shows \"POSIX (Left v1) (ALT r1 r2)\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply (metis Prf.intros(2))\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd.intros)\napply(auto)\napply(rule ValOrd.intros)\nby simp\n\nlemma POSIX_ALT_I2:\n  assumes \"POSIX v2 r2\" \"\\<forall>v'. \\<turnstile> v' : r1 \\<longrightarrow> length (flat v2) > length (flat v')\"\n  shows \"POSIX (Right v2) (ALT r1 r2)\"\nusing assms\nunfolding POSIX_def\napply(auto)\napply (metis Prf.intros)\napply(rotate_tac 3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)\napply(rule ValOrd.intros)\napply metis\ndone\n\nlemma mkeps_POSIX:\n  assumes \"nullable r\"\n  shows \"POSIX (mkeps r) r\"\nusing assms\napply(induct r)\napply(auto)[1]\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(4))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros)\napply(simp)\napply(auto)[1]\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis mkeps.simps(2) mkeps_nullable nullable.simps(5))\napply(rotate_tac 6)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (simp add: mkeps_flat)\napply(case_tac \"mkeps r1a = v1\")\napply(simp)\napply (metis ValOrd.intros(1))\napply (rule ValOrd.intros(2))\napply metis\napply(simp)\n(* ALT case *)\nthm mkeps.simps\napply(simp)\napply(erule disjE)\napply(simp)\napply (metis POSIX_ALT_I1)\n(* *)\napply(auto)[1]\nthm  POSIX_ALT_I1\napply (metis POSIX_ALT_I1)\napply(simp (no_asm) add: POSIX_def)\napply(auto)[1]\napply(rule Prf.intros(3))\napply(simp only: POSIX_def)\napply(rotate_tac 4)\napply(erule Prf.cases)\napply(simp_all)[5]\nthm mkeps_flat\napply(simp add: mkeps_flat)\napply(auto)[1]\nthm Prf_flat_L nullable_correctness\napply (metis Prf_flat_L nullable_correctness)\napply(rule ValOrd.intros)\napply(subst (asm) POSIX_def)\napply(clarify)\napply(drule_tac x=\"v2\" in spec)\nby simp\n\n\n\ntext {*\n  Injection value is related to r\n*}\n\n\n\ntext {*\n  The string behind the injection value is an added c\n*}\n\n\nlemma injval_inj: \"inj_on (injval r c) {v. \\<turnstile> v : der c r}\"\napply(induct c r rule: der.induct)\nunfolding inj_on_def\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis list.distinct(1) mkeps_flat v4)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(rotate_tac 6)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis list.distinct(1) mkeps_flat v4)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\ndone\n\nlemma Values_nullable:\n  assumes \"nullable r1\"\n  shows \"mkeps r1 \\<in> Values r1 s\"\nusing assms\napply(induct r1 arbitrary: s)\napply(simp_all)\napply(simp add: Values_recs)\napply(simp add: Values_recs)\napply(simp add: Values_recs)\napply(auto)[1]\ndone\n\nlemma Values_injval:\n  assumes \"v \\<in> Values (der c r) s\"\n  shows \"injval r c v \\<in> Values r (c#s)\"\nusing assms\napply(induct c r arbitrary: v s rule: der.induct)\napply(simp add: Values_recs)\napply(simp add: Values_recs)\napply(case_tac \"c = c'\")\napply(simp)\napply(simp add: Values_recs)\napply(simp add: prefix_def)\napply(simp)\napply(simp add: Values_recs)\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(case_tac \"nullable r1\")\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(simp add: rest_def)\napply(subst v4)\napply(simp add: Values_def)\napply(simp add: Values_def)\napply(rule Values_nullable)\napply(assumption)\napply(simp add: rest_def)\napply(subst mkeps_flat)\napply(assumption)\napply(simp)\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(simp add: rest_def)\napply(subst v4)\napply(simp add: Values_def)\napply(simp add: Values_def)\ndone\n\nlemma Values_projval:\n  assumes \"v \\<in> Values r (c#s)\" \"\\<exists>s. flat v = c # s\"\n  shows \"projval r c v \\<in> Values (der c r) s\"\nusing assms\napply(induct r arbitrary: v s c rule: rexp.induct)\napply(simp add: Values_recs)\napply(simp add: Values_recs)\napply(case_tac \"c = char\")\napply(simp)\napply(simp add: Values_recs)\napply(simp)\napply(simp add: Values_recs)\napply(simp add: prefix_def)\napply(case_tac \"nullable rexp1\")\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(simp add: rest_def)\napply (metis hd_Cons_tl hd_append2 list.sel(1))\napply(simp add: rest_def)\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(subst v4_proj2)\napply(simp add: Values_def)\napply(assumption)\napply(simp)\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(auto simp add: Values_def not_nullable_flat)[1]\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(simp add: append_eq_Cons_conv)\napply(auto)[1]\napply(simp add: rest_def)\napply(subst v4_proj2)\napply(simp add: Values_def)\napply(assumption)\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\ndone\n\n\ndefinition \"MValue v r s \\<equiv> (v \\<in> Values r s \\<and> (\\<forall>v' \\<in> Values r s. v 2\\<succ> v'))\"\n\nlemma MValue_ALTE:\n  assumes \"MValue v (ALT r1 r2) s\"\n  shows \"(\\<exists>vl. v = Left vl \\<and> MValue vl r1 s \\<and> (\\<forall>vr \\<in> Values r2 s. length (flat vr) \\<le> length (flat vl))) \\<or> \n         (\\<exists>vr. v = Right vr \\<and> MValue vr r2 s \\<and> (\\<forall>vl \\<in> Values r1 s. length (flat vl) < length (flat vr)))\"\nusing assms\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(auto)\napply(drule_tac x=\"Left x\" in bspec)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\napply(drule_tac x=\"Right vr\" in bspec)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\napply(drule_tac x=\"Right x\" in bspec)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\napply(drule_tac x=\"Left vl\" in bspec)\napply(simp)\napply(erule ValOrd2.cases)\napply(simp_all)\ndone\n\nlemma MValue_ALTI1:\n  assumes \"MValue vl r1 s\"  \"\\<forall>vr \\<in> Values r2 s. length (flat vr) \\<le> length (flat vl)\"\n  shows \"MValue (Left vl) (ALT r1 r2) s\"\nusing assms\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(auto)\napply(rule ValOrd2.intros)\napply metis\napply(rule ValOrd2.intros)\napply metis\ndone\n\nlemma MValue_ALTI2:\n  assumes \"MValue vr r2 s\"  \"\\<forall>vl \\<in> Values r1 s. length (flat vl) < length (flat vr)\"\n  shows \"MValue (Right vr) (ALT r1 r2) s\"\nusing assms\napply(simp add: MValue_def)\napply(simp add: Values_recs)\napply(auto)\napply(rule ValOrd2.intros)\napply metis\napply(rule ValOrd2.intros)\napply metis\ndone\n\nlemma t: \"(c#xs = c#ys) \\<Longrightarrow> xs = ys\"\nby (metis list.sel(3))\n\nlemma t2: \"(xs = ys) \\<Longrightarrow> (c#xs) = (c#ys)\"\nby (metis)\n\nlemma \"\\<not>(nullable r) \\<Longrightarrow> \\<not>(\\<exists>v. \\<turnstile> v : r \\<and> flat v = [])\"\nby (metis Prf_flat_L nullable_correctness)\n\n\nlemma LeftRight:\n  assumes \"(Left v1) \\<succ>(der c (ALT r1 r2)) (Right v2)\"\n  and \"\\<turnstile> v1 : der c r1\" \"\\<turnstile> v2 : der c r2\" \n  shows \"(injval (ALT r1 r2) c (Left v1)) \\<succ>(ALT r1 r2) (injval (ALT r1 r2) c (Right v2))\"\nusing assms\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd.intros)\napply(clarify)\napply(subst v4)\napply(simp)\napply(subst v4)\napply(simp)\napply(simp)\ndone\n\nlemma RightLeft:\n  assumes \"(Right v1) \\<succ>(der c (ALT r1 r2)) (Left v2)\"\n  and \"\\<turnstile> v1 : der c r2\" \"\\<turnstile> v2 : der c r1\" \n  shows \"(injval (ALT r1 r2) c (Right v1)) \\<succ>(ALT r1 r2) (injval (ALT r1 r2) c (Left v2))\"\nusing assms\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd.intros)\napply(clarify)\napply(subst v4)\napply(simp)\napply(subst v4)\napply(simp)\napply(simp)\ndone\n\nlemma h: \n  assumes \"nullable r1\" \"\\<turnstile> v1 : der c r1\"\n  shows \"injval r1 c v1 \\<succ>r1 mkeps r1\"\nusing assms\napply(induct r1 arbitrary: v1 rule: der.induct)\napply(simp)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(auto)[1]\napply (metis ValOrd.intros(6))\napply (metis ValOrd.intros(6))\napply (metis ValOrd.intros(3) le_add2 list.size(3) mkeps_flat monoid_add_class.add.right_neutral)\napply(auto)[1]\napply (metis ValOrd.intros(4) length_greater_0_conv list.distinct(1) list.size(3) mkeps_flat v4)\napply (metis ValOrd.intros(4) length_greater_0_conv list.distinct(1) list.size(3) mkeps_flat v4)\napply (metis ValOrd.intros(5))\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply (metis ValOrd.intros(2) list.distinct(1) mkeps_flat v4)\napply(clarify)\nby (metis ValOrd.intros(1))\n\nlemma LeftRightSeq:\n  assumes \"(Left (Seq v1 v2)) \\<succ>(der c (SEQ r1 r2)) (Right v3)\"\n  and \"nullable r1\" \"\\<turnstile> v1 : der c r1\"\n  shows \"(injval (SEQ r1 r2) c (Seq v1 v2)) \\<succ>(SEQ r1 r2) (injval (SEQ r1 r2) c (Right v2))\"\nusing assms\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(simp)\napply(rule ValOrd.intros(2))\nprefer 2\napply (metis list.distinct(1) mkeps_flat v4)\nby (metis h)\n\nlemma rr1: \n  assumes \"\\<turnstile> v : r\" \"\\<not>nullable r\" \n  shows \"flat v \\<noteq> []\"\nusing assms\nby (metis Prf_flat_L nullable_correctness)\n\n(* HERE *)\n\nlemma Prf_inj_test:\n  assumes \"v1 \\<succ>(der c r) v2\" \n          \"v1 \\<in> Values (der c r) s\"\n          \"v2 \\<in> Values (der c r) s\"\n          \"injval r c v1 \\<in> Values r (c#s)\"\n          \"injval r c v2 \\<in> Values r (c#s)\"\n  shows \"(injval r c v1) 2\\<succ>  (injval r c v2)\"\nusing assms\napply(induct c r arbitrary: v1 v2 s rule: der.induct)\n(* NULL case *)\napply(simp add: Values_recs)\n(* EMPTY case *)\napply(simp add: Values_recs)\n(* CHAR case *)\napply(case_tac \"c = c'\")\napply(simp)\napply(simp add: Values_recs)\napply (metis ValOrd2.intros(8))\napply(simp add: Values_recs)\n(* ALT case *)\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply (metis ValOrd2.intros(6))\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd2.intros)\napply(subst v4)\napply(simp add: Values_def)\napply(subst v4)\napply(simp add: Values_def)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd2.intros)\napply(subst v4)\napply(simp add: Values_def)\napply(subst v4)\napply(simp add: Values_def)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply (metis ValOrd2.intros(5))\n(* SEQ case*)\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\ndefer\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(rule ValOrd2.intros)\napply(simp)\napply (metis Ord1)\napply(clarify)\napply(rule ValOrd2.intros)\napply(subgoal_tac \"rest v1 (flat v1 @ flat v2) = flat v2\")\napply(simp)\napply(subgoal_tac \"rest (injval r1 c v1) (c # flat v1 @ flat v2) = flat v2\")\napply(simp)\noops\n\nlemma Prf_inj_test:\n  assumes \"v1 \\<succ>(der c r) v2\" \n          \"v1 \\<in> Values (der c r) s\"\n          \"v2 \\<in> Values (der c r) s\"\n          \"injval r c v1 \\<in> Values r (c#s)\"\n          \"injval r c v2 \\<in> Values r (c#s)\"\n  shows \"(injval r c v1) 2\\<succ>  (injval r c v2)\"\nusing assms\napply(induct c r arbitrary: v1 v2 s rule: der.induct)\n(* NULL case *)\napply(simp add: Values_recs)\n(* EMPTY case *)\napply(simp add: Values_recs)\n(* CHAR case *)\napply(case_tac \"c = c'\")\napply(simp)\napply(simp add: Values_recs)\napply (metis ValOrd2.intros(8))\napply(simp add: Values_recs)\n(* ALT case *)\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply (metis ValOrd2.intros(6))\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd2.intros)\napply(subst v4)\napply(simp add: Values_def)\napply(subst v4)\napply(simp add: Values_def)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd2.intros)\napply(subst v4)\napply(simp add: Values_def)\napply(subst v4)\napply(simp add: Values_def)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply (metis ValOrd2.intros(5))\n(* SEQ case*)\napply(simp)\napply(case_tac \"nullable r1\")\napply(simp)\ndefer\napply(simp)\napply(simp add: Values_recs)\napply(auto)[1]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(rule ValOrd2.intros)\napply(simp)\napply (metis Ord1)\napply(clarify)\napply(rule ValOrd2.intros)\napply metis\nusing injval_inj\napply(simp add: Values_def inj_on_def)\napply metis\napply(simp add: Values_recs)\napply(auto)[1]\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply (metis Ord1 ValOrd2.intros(1))\napply(clarify)\napply(rule ValOrd2.intros(2))\napply metis\nusing injval_inj\napply(simp add: Values_def inj_on_def)\napply metis\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd2.intros(2))\nthm h\napply(rule Ord1)\napply(rule h)\napply(simp)\napply(simp add: Values_def)\napply(simp add: Values_def)\napply (metis list.distinct(1) mkeps_flat v4)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(simp add: Values_def)\ndefer\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(rule ValOrd2.intros(1))\napply(rotate_tac 1)\napply(drule_tac x=\"v2\" in meta_spec)\napply(rotate_tac 8)\napply(drule_tac x=\"v2'\" in meta_spec)\napply(rotate_tac 8)\noops\n\nlemma POSIX_der:\n  assumes \"POSIX v (der c r)\" \"\\<turnstile> v : der c r\"\n  shows \"POSIX (injval r c v) r\"\nusing assms\nunfolding POSIX_def\napply(auto)\nthm v3\napply (erule v3)\nthm v4\napply(subst (asm) v4)\napply(assumption)\napply(drule_tac x=\"projval r c v'\" in spec)\napply(drule mp)\napply(rule conjI)\nthm v3_proj\napply(rule v3_proj)\napply(simp)\napply(rule_tac x=\"flat v\" in exI)\napply(simp)\nthm t\napply(rule_tac c=\"c\" in  t)\napply(simp)\nthm v4_proj\napply(subst v4_proj)\napply(simp)\napply(rule_tac x=\"flat v\" in exI)\napply(simp)\napply(simp)\noops\n\nlemma POSIX_der:\n  assumes \"POSIX v (der c r)\" \"\\<turnstile> v : der c r\"\n  shows \"POSIX (injval r c v) r\"\nusing assms\napply(induct c r arbitrary: v rule: der.induct)\n(* null case*)\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\n(* empty case *)\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\n(* char case *)\napply(simp add: POSIX_def)\napply(case_tac \"c = c'\")\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\n(* alt case *)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(simp (no_asm) add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(2) v3)\napply(rotate_tac 4)\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis POSIX_ALT2 POSIX_def ValOrd.intros(6))\napply (metis ValOrd.intros(3) order_refl)\napply(simp (no_asm) add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(3) v3)\napply(rotate_tac 4)\napply(erule Prf.cases)\napply(simp_all)[5]\ndefer\napply (metis POSIX_ALT1a POSIX_def ValOrd.intros(5))\nprefer 2\napply(subst (asm) (5) POSIX_def)\napply(auto)[1]\napply(rotate_tac 5)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule ValOrd.intros)\napply(subst (asm) v4)\napply(simp)\napply(drule_tac x=\"Left (projval r1a c v1)\" in spec)\napply(clarify)\napply(drule mp)\napply(rule conjI)\napply (metis Prf.intros(2) v3_proj)\napply(simp)\napply (metis v4_proj2)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply (metis less_not_refl v4_proj2)\n(* seq case *)\napply(case_tac \"nullable r1\")\ndefer\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis Prf.intros(1) v3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(subst (asm) (3) v4)\napply(simp)\napply(simp)\napply(subgoal_tac \"flat v1a \\<noteq> []\")\nprefer 2\napply (metis Prf_flat_L nullable_correctness)\napply(subgoal_tac \"\\<exists>s. flat v1a = c # s\")\nprefer 2\napply (metis append_eq_Cons_conv)\napply(auto)[1]\noops\n\n\nlemma POSIX_ex: \"\\<turnstile> v : r \\<Longrightarrow> \\<exists>v. POSIX v r\"\napply(induct r arbitrary: v)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule_tac x=\"Void\" in exI)\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(4))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(7))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule_tac x=\"Char c\" in exI)\napply(simp add: POSIX_def)\napply(auto)[1]\napply (metis Prf.intros(5))\napply(erule Prf.cases)\napply(simp_all)[5]\napply (metis ValOrd.intros(8))\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(drule_tac x=\"v1\" in meta_spec)\napply(drule_tac x=\"v2\" in meta_spec)\napply(auto)[1]\ndefer\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply (metis POSIX_ALT_I1)\napply (metis POSIX_ALT_I1 POSIX_ALT_I2)\napply(case_tac \"nullable r1a\")\napply(rule_tac x=\"Seq (mkeps r1a) va\" in exI)\napply(auto simp add: POSIX_def)[1]\napply (metis Prf.intros(1) mkeps_nullable)\napply(simp add: mkeps_flat)\napply(rotate_tac 7)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(case_tac \"mkeps r1 = v1a\")\napply(simp)\napply (rule ValOrd.intros(1))\napply (metis append_Nil mkeps_flat)\napply (rule ValOrd.intros(2))\napply(drule mkeps_POSIX)\napply(simp add: POSIX_def)\noops\n\nlemma POSIX_ex2: \"\\<turnstile> v : r \\<Longrightarrow> \\<exists>v. POSIX v r \\<and> \\<turnstile> v : r\"\napply(induct r arbitrary: v)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule_tac x=\"Void\" in exI)\napply(simp add: POSIX_def)\napply(auto)[1]\noops\n\nlemma POSIX_ALT_cases:\n  assumes \"\\<turnstile> v : (ALT r1 r2)\" \"POSIX v (ALT r1 r2)\"\n  shows \"(\\<exists>v1. v = Left v1 \\<and> POSIX v1 r1) \\<or> (\\<exists>v2. v = Right v2 \\<and> POSIX v2 r2)\"\nusing assms\napply(erule_tac Prf.cases)\napply(simp_all)\nunfolding POSIX_def\napply(auto)\napply (metis POSIX_ALT2 POSIX_def assms(2))\nby (metis POSIX_ALT1b assms(2))\n\nlemma POSIX_ALT_cases2:\n  assumes \"POSIX v (ALT r1 r2)\" \"\\<turnstile> v : (ALT r1 r2)\" \n  shows \"(\\<exists>v1. v = Left v1 \\<and> POSIX v1 r1) \\<or> (\\<exists>v2. v = Right v2 \\<and> POSIX v2 r2)\"\nusing assms POSIX_ALT_cases by auto\n\nlemma Prf_flat_empty:\n  assumes \"\\<turnstile> v : r\" \"flat v = []\"\n  shows \"nullable r\"\nusing assms\napply(induct)\napply(auto)\ndone\n\nlemma POSIX_proj:\n  assumes \"POSIX v r\" \"\\<turnstile> v : r\" \"\\<exists>s. flat v = c#s\"\n  shows \"POSIX (projval r c v) (der c r)\"\nusing assms\napply(induct r c v arbitrary: rule: projval.induct)\ndefer\ndefer\ndefer\ndefer\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\noops\n\nlemma POSIX_proj:\n  assumes \"POSIX v r\" \"\\<turnstile> v : r\" \"\\<exists>s. flat v = c#s\"\n  shows \"POSIX (projval r c v) (der c r)\"\nusing assms\napply(induct r arbitrary: c v rule: rexp.induct)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\noops\n\nlemma POSIX_proj:\n  assumes \"POSIX v r\" \"\\<turnstile> v : r\" \"\\<exists>s. flat v = c#s\"\n  shows \"POSIX (projval r c v) (der c r)\"\nusing assms\napply(induct r c v arbitrary: rule: projval.induct)\ndefer\ndefer\ndefer\ndefer\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp add: POSIX_def)\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\noops\n\nlemma Prf_inj:\n  assumes \"v1 \\<succ>(der c r) v2\" \"\\<turnstile> v1 : der c r\" \"\\<turnstile> v2 : der c r\" \"flat v1 = flat v2\"\n  shows \"(injval r c v1) \\<succ>r (injval r c v2)\"\nusing assms\napply(induct arbitrary: v1 v2 rule: der.induct)\n(* NULL case *)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\n(* EMPTY case *)\napply(erule ValOrd.cases)\napply(simp_all)[8]\n(* CHAR case *)\napply(case_tac \"c = c'\")\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd.intros)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\n(* ALT case *)\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(rule ValOrd.intros)\napply(subst v4)\napply(clarify)\napply(rotate_tac 3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(subst v4)\napply(clarify)\napply(rotate_tac 2)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(rule ValOrd.intros)\napply(clarify)\napply(rotate_tac 3)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(rule ValOrd.intros)\napply(clarify)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\n(* SEQ case*)\napply(simp)\napply(case_tac \"nullable r1\")\ndefer\napply(simp)\napply(erule ValOrd.cases)\napply(simp_all)[8]\napply(clarify)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(clarify)\napply(rule ValOrd.intros)\napply(simp)\noops\n\n\ntext {*\n  Injection followed by projection is the identity.\n*}\n\nlemma proj_inj_id:\n  assumes \"\\<turnstile> v : der c r\" \n  shows \"projval r c (injval r c v) = v\"\nusing assms\napply(induct r arbitrary: c v rule: rexp.induct)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(case_tac \"c = char\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\ndefer\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(simp)\napply(case_tac \"nullable rexp1\")\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply (metis list.distinct(1) v4)\napply(auto)[1]\napply (metis mkeps_flat)\napply(auto)\napply(erule Prf.cases)\napply(simp_all)[5]\napply(auto)[1]\napply(simp add: v4)\ndone\n\ntext {* \n\n  HERE: Crucial lemma that does not go through in the sequence case. \n\n*}\nlemma v5:\n  assumes \"\\<turnstile> v : der c r\" \"POSIX v (der c r)\"\n  shows \"POSIX (injval r c v) r\"\nusing assms\napply(induct arbitrary: v rule: der.induct)\n(* NULL case *)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\n(* EMPTY case *)\napply(simp)\napply(erule Prf.cases)\napply(simp_all)[5]\n(* CHAR case *)\napply(simp)\napply(case_tac \"c = c'\")\napply(auto simp add: POSIX_def)[1]\napply(erule Prf.cases)\napply(simp_all)[5]\noops\n*)\n\n\nend", "meta": {"author": "fahadausaf", "repo": "POSIX-Parsing", "sha": "f077315e6dafc02f4d49c1669bb9bcb303fea23a", "save_path": "github-repos/isabelle/fahadausaf-POSIX-Parsing", "path": "github-repos/isabelle/fahadausaf-POSIX-Parsing/POSIX-Parsing-f077315e6dafc02f4d49c1669bb9bcb303fea23a/Theorems/ReTest.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7526716034773723}}
{"text": "(*\n    Original Author of Riddle: Tjark Weber\n    Updates and additions by Jacques Fleuriot\n*)\n\ntheory Tut4Soln imports Main begin \n\n(* Note that most of these can be proved in more than one way *)\n\nlemma \"(P \\<longrightarrow>(Q\\<longrightarrow>R))\\<longrightarrow>((P\\<longrightarrow>Q)\\<longrightarrow>(P\\<longrightarrow>R))\"\nproof (rule impI)+\n  assume \"P\" \"P \\<longrightarrow> Q \\<longrightarrow> R\" then have qr: \"Q \\<longrightarrow> R\"\n    (* try sledgehammer here instead to see what it suggests *)\n    by fast \n  assume \"P\" \"P \\<longrightarrow> Q\" then have \"Q\" \n    by blast\n  then show \"R\" using qr\n    by blast \nqed\n\nlemma \"(\\<forall>x. P x \\<longrightarrow> Q)\\<longrightarrow>(\\<exists>x. P x\\<longrightarrow>Q)\"\nproof \n  assume \"\\<forall>x. P x \\<longrightarrow> Q\" then have \"P a \\<longrightarrow> Q\" ..\n  then show \"\\<exists>x. P x\\<longrightarrow>Q\" ..\nqed\nlemma foo: assumes ex: \"\\<not>(\\<exists>x. P x)\" shows all: \"\\<forall>x. \\<not>P x\"\nproof\n  fix x \n  show  \"\\<not> P x\"\n  proof \n    assume \"P x\" then have \"\\<exists>x. P x\" by (rule exI)\n    then show False using ex by simp\n  qed\nqed\n\nlemma foo2: assumes ex: \"\\<not>(\\<exists>x. P x)\" shows \"\\<forall>x. \\<not>P x\"\n(* \"safe\" is a method that will not make any provable goal become unprovable. \n    It does not do any exI or spec/allE steps. You can use other methods instead *)\nproof(safe)\n  fix x\n  assume \"P x\" then have \"\\<exists>x. P x\" by (rule exI)\n  then show False using ex\n    by simp\nqed\n\n(* A proof showing the use of a raw proof block. More elegant proofs are possible. *)\n\nlemma assumes n_all: \"\\<not>(\\<forall>x. P x)\" shows \"\\<exists>x. \\<not>P x\"\nproof (rule ccontr)\n  assume n_ex: \"\\<nexists>x. \\<not> P x\"  \n  have \"\\<forall>x. P x\" \n    proof - (* dash means don't apply any default ND steps *)\n      {fix z   (* arbitrary z *)\n        have \"P z\"\n        proof (rule ccontr)\n          assume \"\\<not> P z\" then have \"\\<exists>x. \\<not> P x\" ..\n          then show False using n_ex  by simp\n        qed\n      }\n      then show ?thesis .. (* method \"..\" is one that can do straightforward ND steps but you could e.g. use simp instead*)\n    qed\n    then show False using n_all by simp\nqed\n\n(* Shorter proof of same theorem as above *)\n\nlemma assumes n_all: \"\\<not>(\\<forall>x. P x)\" shows \"\\<exists>x. \\<not>P x\"\nproof (rule ccontr)\n  assume n_ex: \"\\<nexists>x. \\<not> P x\"     \n  {fix x \n    have \"P x\" \n    proof (rule ccontr)\n      assume \"\\<not> P x\" then have \"\\<exists>x. \\<not> P x\" ..\n      then show False using n_ex  by simp\n    qed\n  }\n  then have \"\\<forall>x. P x\" ..\n  then show False using n_all by simp\nqed\n\n\n(* Another Proof using previous result *)\nlemma assumes n_all: \"\\<not>(\\<forall>x. P x)\" shows \"\\<exists>x. \\<not>P x\"\nproof (rule ccontr)\n  assume \"\\<nexists>x. \\<not> P x\" \n  then have \"\\<forall>x. \\<not>\\<not>P x\" by (rule foo)\n  then have \"\\<forall>x. P x\" by simp\n  from n_all this show False by (rule notE)\nqed\n\n(* A possible proof, without named assumptions and goals. Other proofs are possible *)   \n\nlemma \"(R\\<longrightarrow>P)\\<longrightarrow>(((\\<not>R \\<or> P)\\<longrightarrow>(Q\\<longrightarrow>S))\\<longrightarrow>(Q\\<longrightarrow>S))\"\nproof (rule impI)+\n  assume \"R \\<longrightarrow> P\" \"Q\" \"\\<not> R \\<or> P \\<longrightarrow> Q \\<longrightarrow> S\"\n  show \"S\"\n  proof (cases)\n    assume  \"R\" \n    then have \"P\" using `R \\<longrightarrow> P` by blast \n    then have \"\\<not>R \\<or> P\" ..\n    then have \"Q \\<longrightarrow> S\" using `\\<not> R \\<or> P \\<longrightarrow> Q \\<longrightarrow> S` by blast \n    then show \"S\" using  `Q` by simp\n  next\n    assume notr: \"\\<not>R\" \n    then have \"\\<not>R \\<or> P\" ..\n    then have \"Q \\<longrightarrow> S\" using `\\<not> R \\<or> P \\<longrightarrow> Q \\<longrightarrow> S` by blast \n    then show \"S\" using  `Q` by simp    \n  qed\nqed\n\n(* Another proof of the above, without explicit use of cases *)\nlemma \"(R \\<longrightarrow> P) \\<longrightarrow> (((\\<not>R \\<or> P) \\<longrightarrow> (Q \\<longrightarrow> S)) \\<longrightarrow> (Q \\<longrightarrow> S))\"\nproof (rule impI, rule impI)\n  assume a: \"R \\<longrightarrow> P\" \"\\<not> R \\<or> P \\<longrightarrow> Q \\<longrightarrow> S\"\n  { assume R \n    hence P using a(1) by (rule_tac mp) \n    hence \"\\<not> R \\<or> P\" by (rule disjI2)\n  }\n  moreover \n  { assume \"\\<not>R\" \n    hence \"\\<not> R \\<or> P\" by (rule disjI1)\n  }\n  ultimately have \"\\<not> R \\<or> P\" by (rule_tac disjE, rule_tac excluded_middle)\n  from this a(2) show \"Q \\<longrightarrow> S\" by (rule_tac mp)\nqed\n\n\ntext {* A Riddle: Rich Grandfather *}\n\ntext {*\n  First prove the following formula, which is valid in classical predicate\n  logic, informally with pen and paper.  Use case distinctions and/or proof by\n  contradiction.\n\n  \"If every poor man has a rich father,\n   then there is a rich man who has a rich grandfather\"\n*}\n\n\ntext {*\nProof\n(1) We first show: \"\\<exists>x. rich x\".\nProof by contradiction.\n    Assume \"\\<not> (\\<exists>x. rich x)\"\n      Then \"\\<forall>x. \\<not> rich x\" \n      We consider an arbitrary \"y\" with \"\\<not> rich y\"\n      Then \"rich (father y)\"\n\n(2) Now we show the theorem. \nProof by cases.  \n    Case 1:  \"rich (father (father x))\" \n             We are done.\n    Case 2: \"\\<not> rich (father (father x))\" \n            Then \"rich (father (father (father x))) \n            Also \"rich (father x)\"\n            because otherwise \"rich (father (father x))\"\nqed\n*}\n\ntext {*\n  Now prove the formula in Isabelle using a sequence of rule applications (i.e.\\\n  only using the methods rule, erule and assumption).\n*}\n\ntheorem\n  \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x) \\<Longrightarrow>\n  \\<exists>x. rich (father (father x)) \\<and> rich x\"\napply (rule classical)\napply (rule exI)\napply (rule conjI)\n  \n  apply (rule classical)\n  apply (rule allE) apply assumption\n  apply (erule impE) apply assumption\n  apply (erule notE) \n  apply (rule exI)\n  apply (rule conjI) apply assumption\n  apply (rule classical)\n  apply (erule allE)\n  apply (erule notE)\n  apply (erule impE) apply assumption\n  apply assumption\n\napply (rule classical)\napply (rule allE) apply assumption\napply (erule impE) apply assumption\napply (erule notE)\napply (rule exI)\napply (rule conjI) apply assumption\napply (rule classical)\napply (erule allE)\napply (erule notE)\napply (erule impE) apply assumption\napply assumption\ndone\n\n\ntext{* An alternative proof of the above that does not rely on meta variables and uses additional\n       tactics/methods such as drule and cut_tac .Note the use of rule exCI too. \n\n       Note also that the order in which the subgoals are tackled are dictated by Isabelle but \n       there are ways of doing the proof in a way closer to the informal one e.g. using \"prefer\" \n       to change the order of the goals (although this makes the proof potentially more \"brittle\" \n       to changes in future versions of Isabelle *}\n\ntheorem\n  \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x) \\<Longrightarrow>\n  \\<exists>x. rich (father (father x)) \\<and> rich x\"\napply (subgoal_tac \"\\<exists>x. rich x\")\napply (erule exE)\n(* Tackling (2) first *)\napply (cut_tac P=\"rich (father(father x))\" in excluded_middle)\napply (erule disjE)\n(* Case 2 *)\napply (subgoal_tac \"rich(father x)\")\napply (drule_tac x=\"father(father x)\" in spec)\napply (drule mp, assumption)\napply (rule_tac x=\"father x\" in exI)\napply (rule conjI)\napply assumption\napply assumption\napply (rule ccontr)\napply (drule_tac x=\"father x\" in spec)\napply (drule mp, assumption)\napply (erule notE, assumption)\n(* Case 1*)\napply (rule_tac x=x in exI)\napply (rule conjI)\napply assumption\napply assumption\n(* Tackling (1) now *)\napply (rule_tac a=\"father x\" in exCI)\napply (drule_tac x=x in spec)\napply (drule_tac x=x in spec)\napply (drule mp, assumption)\napply assumption\ndone\n\n\ntext {*\n  Here is a proof in Isar that resembles the informal reasoning above:\n*}\n\ntheorem rich_grandfather: \n  \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x) \n   \\<Longrightarrow> \\<exists>x. rich x \\<and> rich (father (father x))\"\nproof -\n  assume a: \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x)\"\n  have \"\\<exists>x. rich x\"\n  proof (rule classical)\n    fix y \n    assume \"\\<not> (\\<exists>x. rich x)\"\n    then have \"\\<forall>x. \\<not> rich x\" by simp \n    then have \"\\<not> rich y\" by simp\n    with a have \"rich (father y)\" by simp\n    then show ?thesis by rule\n  qed\n  then obtain x where x: \"rich x\" by auto\n  show ?thesis\n  proof cases\n    assume \"rich (father (father x))\"\n    with x show ?thesis by auto\n  next\n    assume b: \"\\<not> rich (father (father x))\"\n    with a have \"rich (father (father (father x)))\" by blast\n    moreover have \"rich (father x)\" \n    proof (rule classical)\n      assume \"\\<not> rich (father x)\" \n      with a have \"rich (father (father x))\" by simp\n      with b show ?thesis by contradiction \n    qed\n    ultimately show ?thesis by auto\n  qed\nqed\n\ntext {*\n  An slightly modified proof of the above, with a named assumption right from the beginning:\n*}\n\n\ntheorem rich_grandfather2: \n  assumes a: \"\\<forall>x. \\<not> rich x \\<longrightarrow> rich (father x)\" \n  shows \"\\<exists>x. rich x \\<and> rich (father (father x))\"\nproof -\n  have \"\\<exists>x. rich x\"\n  proof (rule classical)\n    fix y \n    assume \"\\<not> (\\<exists>x. rich x)\"\n    then have \"\\<forall>x. \\<not> rich x\" by simp \n    then have \"\\<not> rich y\" by simp\n    with a have \"rich (father y)\" by simp\n    then show ?thesis by rule \n  qed\n  then obtain x where x: \"rich x\" by auto\n  show ?thesis\n  proof cases\n    assume \"rich (father (father x))\"\n    with x show ?thesis by auto\n  next\n    assume b: \"\\<not> rich (father (father x))\"\n    with a have \"rich (father (father (father x)))\" by simp\n    moreover have \"rich (father x)\" \n    proof (rule classical)\n      assume \"\\<not> rich (father x)\" \n      with a have \"rich (father (father x))\" by simp\n      with b show ?thesis by contradiction \n    qed\n    ultimately show ?thesis by auto\n  qed\nqed\n\n\n end \n", "meta": {"author": "timothypmurphy", "repo": "Automated-Reasoning", "sha": "9377466c77fc3e20c88ab5054fa5dce655160e32", "save_path": "github-repos/isabelle/timothypmurphy-Automated-Reasoning", "path": "github-repos/isabelle/timothypmurphy-Automated-Reasoning/Automated-Reasoning-9377466c77fc3e20c88ab5054fa5dce655160e32/Tut4Soln.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681122619883, "lm_q2_score": 0.8774767746654976, "lm_q1q2_score": 0.752671596558562}}
{"text": "(*  Author: John Harrison, Marco Maggesi, Graziano Gentili, Gianni Ciolli, Valentina Bruno\n    Ported from \"hol_light/Multivariate/canal.ml\" by L C Paulson (2014)\n*)\n\nsection \\<open>Complex Analysis Basics\\<close>\ntext \\<open>Definitions of analytic and holomorphic functions, limit theorems, complex differentiation\\<close>\n\ntheory Complex_Analysis_Basics\n  imports Derivative \"HOL-Library.Nonpos_Ints\" Uncountable_Sets\nbegin\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>General lemmas\\<close>\n\nlemma nonneg_Reals_cmod_eq_Re: \"z \\<in> \\<real>\\<^sub>\\<ge>\\<^sub>0 \\<Longrightarrow> norm z = Re z\"\n  by (simp add: complex_nonneg_Reals_iff cmod_eq_Re)\n\nlemma fact_cancel:\n  fixes c :: \"'a::real_field\"\n  shows \"of_nat (Suc n) * c / (fact (Suc n)) = c / (fact n)\"\n  using of_nat_neq_0 by force\n\nlemma vector_derivative_cnj_within:\n  assumes \"at x within A \\<noteq> bot\" and \"f differentiable at x within A\"\n  shows   \"vector_derivative (\\<lambda>z. cnj (f z)) (at x within A) = \n             cnj (vector_derivative f (at x within A))\" (is \"_ = cnj ?D\")\nproof -\n  let ?D = \"vector_derivative f (at x within A)\"\n  from assms have \"(f has_vector_derivative ?D) (at x within A)\"\n    by (subst (asm) vector_derivative_works)\n  hence \"((\\<lambda>x. cnj (f x)) has_vector_derivative cnj ?D) (at x within A)\"\n    by (rule has_vector_derivative_cnj)\n  thus ?thesis using assms by (auto dest: vector_derivative_within)\nqed\n\nlemma vector_derivative_cnj:\n  assumes \"f differentiable at x\"\n  shows   \"vector_derivative (\\<lambda>z. cnj (f z)) (at x) = cnj (vector_derivative f (at x))\"\n  using assms by (intro vector_derivative_cnj_within) auto\n\nlemma\n  shows open_halfspace_Re_lt: \"open {z. Re(z) < b}\"\n    and open_halfspace_Re_gt: \"open {z. Re(z) > b}\"\n    and closed_halfspace_Re_ge: \"closed {z. Re(z) \\<ge> b}\"\n    and closed_halfspace_Re_le: \"closed {z. Re(z) \\<le> b}\"\n    and closed_halfspace_Re_eq: \"closed {z. Re(z) = b}\"\n    and open_halfspace_Im_lt: \"open {z. Im(z) < b}\"\n    and open_halfspace_Im_gt: \"open {z. Im(z) > b}\"\n    and closed_halfspace_Im_ge: \"closed {z. Im(z) \\<ge> b}\"\n    and closed_halfspace_Im_le: \"closed {z. Im(z) \\<le> b}\"\n    and closed_halfspace_Im_eq: \"closed {z. Im(z) = b}\"\n  by (intro open_Collect_less closed_Collect_le closed_Collect_eq continuous_on_Re\n            continuous_on_Im continuous_on_id continuous_on_const)+\n\nlemma uncountable_halfspace_Im_gt: \"uncountable {z. Im z > c}\"\nproof -\n  obtain r where r: \"r > 0\" \"ball ((c + 1) *\\<^sub>R \\<i>) r \\<subseteq> {z. Im z > c}\"\n    using open_halfspace_Im_gt[of c] unfolding open_contains_ball by force\n  then show ?thesis\n    using countable_subset uncountable_ball by blast\nqed\n\nlemma uncountable_halfspace_Im_lt: \"uncountable {z. Im z < c}\"\nproof -\n  obtain r where r: \"r > 0\" \"ball ((c - 1) *\\<^sub>R \\<i>) r \\<subseteq> {z. Im z < c}\"\n    using open_halfspace_Im_lt[of c] unfolding open_contains_ball by force\n  then show ?thesis\n    using countable_subset uncountable_ball by blast\nqed\n\nlemma uncountable_halfspace_Re_gt: \"uncountable {z. Re z > c}\"\nproof -\n  obtain r where r: \"r > 0\" \"ball (of_real(c + 1)) r \\<subseteq> {z. Re z > c}\"\n    using open_halfspace_Re_gt[of c] unfolding open_contains_ball by force\n  then show ?thesis\n    using countable_subset uncountable_ball by blast\nqed\n\nlemma uncountable_halfspace_Re_lt: \"uncountable {z. Re z < c}\"\nproof -\n  obtain r where r: \"r > 0\" \"ball (of_real(c - 1)) r \\<subseteq> {z. Re z < c}\"\n    using open_halfspace_Re_lt[of c] unfolding open_contains_ball by force\n  then show ?thesis\n    using countable_subset uncountable_ball by blast\nqed\n\nlemma connected_halfspace_Im_gt [intro]: \"connected {z. c < Im z}\"\n  by (intro convex_connected convex_halfspace_Im_gt)\n\nlemma connected_halfspace_Im_lt [intro]: \"connected {z. c > Im z}\"\n  by (intro convex_connected convex_halfspace_Im_lt)\n\nlemma connected_halfspace_Re_gt [intro]: \"connected {z. c < Re z}\"\n  by (intro convex_connected convex_halfspace_Re_gt)\n\nlemma connected_halfspace_Re_lt [intro]: \"connected {z. c > Re z}\"\n  by (intro convex_connected convex_halfspace_Re_lt)\n  \nlemma closed_complex_Reals: \"closed (\\<real> :: complex set)\"\nproof -\n  have \"(\\<real> :: complex set) = {z. Im z = 0}\"\n    by (auto simp: complex_is_Real_iff)\n  then show ?thesis\n    by (metis closed_halfspace_Im_eq)\nqed\n\nlemma closed_Real_halfspace_Re_le: \"closed (\\<real> \\<inter> {w. Re w \\<le> x})\"\n  by (simp add: closed_Int closed_complex_Reals closed_halfspace_Re_le)\n\nlemma closed_nonpos_Reals_complex [simp]: \"closed (\\<real>\\<^sub>\\<le>\\<^sub>0 :: complex set)\"\nproof -\n  have \"\\<real>\\<^sub>\\<le>\\<^sub>0 = \\<real> \\<inter> {z. Re(z) \\<le> 0}\"\n    using complex_nonpos_Reals_iff complex_is_Real_iff by auto\n  then show ?thesis\n    by (metis closed_Real_halfspace_Re_le)\nqed\n\nlemma closed_Real_halfspace_Re_ge: \"closed (\\<real> \\<inter> {w. x \\<le> Re(w)})\"\n  using closed_halfspace_Re_ge\n  by (simp add: closed_Int closed_complex_Reals)\n\nlemma closed_nonneg_Reals_complex [simp]: \"closed (\\<real>\\<^sub>\\<ge>\\<^sub>0 :: complex set)\"\nproof -\n  have \"\\<real>\\<^sub>\\<ge>\\<^sub>0 = \\<real> \\<inter> {z. Re(z) \\<ge> 0}\"\n    using complex_nonneg_Reals_iff complex_is_Real_iff by auto\n  then show ?thesis\n    by (metis closed_Real_halfspace_Re_ge)\nqed\n\nlemma closed_real_abs_le: \"closed {w \\<in> \\<real>. \\<bar>Re w\\<bar> \\<le> r}\"\nproof -\n  have \"{w \\<in> \\<real>. \\<bar>Re w\\<bar> \\<le> r} = (\\<real> \\<inter> {w. Re w \\<le> r}) \\<inter> (\\<real> \\<inter> {w. Re w \\<ge> -r})\"\n    by auto\n  then show \"closed {w \\<in> \\<real>. \\<bar>Re w\\<bar> \\<le> r}\"\n    by (simp add: closed_Int closed_Real_halfspace_Re_ge closed_Real_halfspace_Re_le)\nqed\n\nlemma real_lim:\n  fixes l::complex\n  assumes \"(f \\<longlongrightarrow> l) F\" and \"\\<not> trivial_limit F\" and \"eventually P F\" and \"\\<And>a. P a \\<Longrightarrow> f a \\<in> \\<real>\"\n  shows  \"l \\<in> \\<real>\"\nproof (rule Lim_in_closed_set[OF closed_complex_Reals _ assms(2,1)])\n  show \"eventually (\\<lambda>x. f x \\<in> \\<real>) F\"\n    using assms(3, 4) by (auto intro: eventually_mono)\nqed\n\nlemma real_lim_sequentially:\n  fixes l::complex\n  shows \"(f \\<longlongrightarrow> l) sequentially \\<Longrightarrow> (\\<exists>N. \\<forall>n\\<ge>N. f n \\<in> \\<real>) \\<Longrightarrow> l \\<in> \\<real>\"\nby (rule real_lim [where F=sequentially]) (auto simp: eventually_sequentially)\n\nlemma real_series:\n  fixes l::complex\n  shows \"f sums l \\<Longrightarrow> (\\<And>n. f n \\<in> \\<real>) \\<Longrightarrow> l \\<in> \\<real>\"\nunfolding sums_def\nby (metis real_lim_sequentially sum_in_Reals)\n\nlemma Lim_null_comparison_Re:\n  assumes \"eventually (\\<lambda>x. norm(f x) \\<le> Re(g x)) F\" \"(g \\<longlongrightarrow> 0) F\" shows \"(f \\<longlongrightarrow> 0) F\"\n  by (rule Lim_null_comparison[OF assms(1)] tendsto_eq_intros assms(2))+ simp\n\nsubsection\\<open>Holomorphic functions\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> holomorphic_on :: \"[complex \\<Rightarrow> complex, complex set] \\<Rightarrow> bool\"\n           (infixl \"(holomorphic'_on)\" 50)\n  where \"f holomorphic_on s \\<equiv> \\<forall>x\\<in>s. f field_differentiable (at x within s)\"\n\nnamed_theorems\\<^marker>\\<open>tag important\\<close> holomorphic_intros \"structural introduction rules for holomorphic_on\"\n\nlemma holomorphic_onI [intro?]: \"(\\<And>x. x \\<in> s \\<Longrightarrow> f field_differentiable (at x within s)) \\<Longrightarrow> f holomorphic_on s\"\n  by (simp add: holomorphic_on_def)\n\nlemma holomorphic_onD [dest?]: \"\\<lbrakk>f holomorphic_on s; x \\<in> s\\<rbrakk> \\<Longrightarrow> f field_differentiable (at x within s)\"\n  by (simp add: holomorphic_on_def)\n\nlemma holomorphic_on_imp_differentiable_on:\n    \"f holomorphic_on s \\<Longrightarrow> f differentiable_on s\"\n  unfolding holomorphic_on_def differentiable_on_def\n  by (simp add: field_differentiable_imp_differentiable)\n\nlemma holomorphic_on_imp_differentiable_at:\n   \"\\<lbrakk>f holomorphic_on s; open s; x \\<in> s\\<rbrakk> \\<Longrightarrow> f field_differentiable (at x)\"\nusing at_within_open holomorphic_on_def by fastforce\n\nlemma holomorphic_on_empty [holomorphic_intros]: \"f holomorphic_on {}\"\n  by (simp add: holomorphic_on_def)\n\nlemma holomorphic_on_open:\n    \"open s \\<Longrightarrow> f holomorphic_on s \\<longleftrightarrow> (\\<forall>x \\<in> s. \\<exists>f'. DERIV f x :> f')\"\n  by (auto simp: holomorphic_on_def field_differentiable_def has_field_derivative_def at_within_open [of _ s])\n\nlemma holomorphic_on_UN_open:\n  assumes \"\\<And>n. n \\<in> I \\<Longrightarrow> f holomorphic_on A n\" \"\\<And>n. n \\<in> I \\<Longrightarrow> open (A n)\"\n  shows   \"f holomorphic_on (\\<Union>n\\<in>I. A n)\"\nproof -\n  have \"f field_differentiable at z within (\\<Union>n\\<in>I. A n)\" if \"z \\<in> (\\<Union>n\\<in>I. A n)\" for z\n  proof -\n    from that obtain n where \"n \\<in> I\" \"z \\<in> A n\"\n      by blast\n    hence \"f holomorphic_on A n\" \"open (A n)\"\n      by (simp add: assms)+\n    with \\<open>z \\<in> A n\\<close> have \"f field_differentiable at z\"\n      by (auto simp: holomorphic_on_open field_differentiable_def)\n    thus ?thesis\n      by (meson field_differentiable_at_within)\n  qed\n  thus ?thesis\n    by (auto simp: holomorphic_on_def)\nqed\n\nlemma holomorphic_on_imp_continuous_on:\n    \"f holomorphic_on s \\<Longrightarrow> continuous_on s f\"\n  by (metis field_differentiable_imp_continuous_at continuous_on_eq_continuous_within holomorphic_on_def)\n\nlemma holomorphic_closedin_preimage_constant:\n  assumes \"f holomorphic_on D\" \n  shows \"closedin (top_of_set D) {z\\<in>D. f z = a}\"\n  by (simp add: assms continuous_closedin_preimage_constant holomorphic_on_imp_continuous_on)\n\nlemma holomorphic_closed_preimage_constant:\n  assumes \"f holomorphic_on UNIV\" \n  shows \"closed {z. f z = a}\"\n  using holomorphic_closedin_preimage_constant [OF assms] by simp\n\nlemma holomorphic_on_subset [elim]:\n    \"f holomorphic_on s \\<Longrightarrow> t \\<subseteq> s \\<Longrightarrow> f holomorphic_on t\"\n  unfolding holomorphic_on_def\n  by (metis field_differentiable_within_subset subsetD)\n\nlemma holomorphic_transform: \"\\<lbrakk>f holomorphic_on s; \\<And>x. x \\<in> s \\<Longrightarrow> f x = g x\\<rbrakk> \\<Longrightarrow> g holomorphic_on s\"\n  by (metis field_differentiable_transform_within linordered_field_no_ub holomorphic_on_def)\n\nlemma holomorphic_cong: \"s = t ==> (\\<And>x. x \\<in> s \\<Longrightarrow> f x = g x) \\<Longrightarrow> f holomorphic_on s \\<longleftrightarrow> g holomorphic_on t\"\n  by (metis holomorphic_transform)\n\nlemma holomorphic_on_linear [simp, holomorphic_intros]: \"((*) c) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis field_differentiable_linear)\n\nlemma holomorphic_on_const [simp, holomorphic_intros]: \"(\\<lambda>z. c) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis field_differentiable_const)\n\nlemma holomorphic_on_ident [simp, holomorphic_intros]: \"(\\<lambda>x. x) holomorphic_on s\"\n  unfolding holomorphic_on_def by (metis field_differentiable_ident)\n\nlemma holomorphic_on_id [simp, holomorphic_intros]: \"id holomorphic_on s\"\n  unfolding id_def by (rule holomorphic_on_ident)\n\nlemma constant_on_imp_holomorphic_on:\n  assumes \"f constant_on A\"\n  shows   \"f holomorphic_on A\"\nproof -\n  from assms obtain c where c: \"\\<forall>x\\<in>A. f x = c\"\n    unfolding constant_on_def by blast\n  have \"f holomorphic_on A \\<longleftrightarrow> (\\<lambda>_. c) holomorphic_on A\"\n    by (intro holomorphic_cong) (use c in auto)\n  thus ?thesis\n    by simp\nqed\n\nlemma holomorphic_on_compose:\n  \"f holomorphic_on s \\<Longrightarrow> g holomorphic_on (f ` s) \\<Longrightarrow> (g o f) holomorphic_on s\"\n  using field_differentiable_compose_within[of f _ s g]\n  by (auto simp: holomorphic_on_def)\n\nlemma holomorphic_on_compose_gen:\n  \"f holomorphic_on s \\<Longrightarrow> g holomorphic_on t \\<Longrightarrow> f ` s \\<subseteq> t \\<Longrightarrow> (g o f) holomorphic_on s\"\n  by (metis holomorphic_on_compose holomorphic_on_subset)\n\nlemma holomorphic_on_balls_imp_entire:\n  assumes \"\\<not>bdd_above A\" \"\\<And>r. r \\<in> A \\<Longrightarrow> f holomorphic_on ball c r\"\n  shows   \"f holomorphic_on B\"\nproof (rule holomorphic_on_subset)\n  show \"f holomorphic_on UNIV\" unfolding holomorphic_on_def\n  proof\n    fix z :: complex\n    from \\<open>\\<not>bdd_above A\\<close> obtain r where r: \"r \\<in> A\" \"r > norm (z - c)\"\n      by (meson bdd_aboveI not_le)\n    with assms(2) have \"f holomorphic_on ball c r\" by blast\n    moreover from r have \"z \\<in> ball c r\" by (auto simp: dist_norm norm_minus_commute)\n    ultimately show \"f field_differentiable at z\"\n      by (auto simp: holomorphic_on_def at_within_open[of _ \"ball c r\"])\n  qed\nqed auto\n\nlemma holomorphic_on_balls_imp_entire':\n  assumes \"\\<And>r. r > 0 \\<Longrightarrow> f holomorphic_on ball c r\"\n  shows   \"f holomorphic_on B\"\nproof (rule holomorphic_on_balls_imp_entire)\n  {\n    fix M :: real\n    have \"\\<exists>x. x > max M 0\" by (intro gt_ex)\n    hence \"\\<exists>x>0. x > M\" by auto\n  }\n  thus \"\\<not>bdd_above {(0::real)<..}\" unfolding bdd_above_def\n    by (auto simp: not_le)\nqed (insert assms, auto)\n\nlemma holomorphic_on_minus [holomorphic_intros]: \"f holomorphic_on A \\<Longrightarrow> (\\<lambda>z. -(f z)) holomorphic_on A\"\n  by (metis field_differentiable_minus holomorphic_on_def)\n\nlemma holomorphic_on_add [holomorphic_intros]:\n  \"\\<lbrakk>f holomorphic_on A; g holomorphic_on A\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z + g z) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_add)\n\nlemma holomorphic_on_diff [holomorphic_intros]:\n  \"\\<lbrakk>f holomorphic_on A; g holomorphic_on A\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z - g z) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_diff)\n\nlemma holomorphic_on_mult [holomorphic_intros]:\n  \"\\<lbrakk>f holomorphic_on A; g holomorphic_on A\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z * g z) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_mult)\n\nlemma holomorphic_on_inverse [holomorphic_intros]:\n  \"\\<lbrakk>f holomorphic_on A; \\<And>z. z \\<in> A \\<Longrightarrow> f z \\<noteq> 0\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. inverse (f z)) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_inverse)\n\nlemma holomorphic_on_divide [holomorphic_intros]:\n  \"\\<lbrakk>f holomorphic_on A; g holomorphic_on A; \\<And>z. z \\<in> A \\<Longrightarrow> g z \\<noteq> 0\\<rbrakk> \\<Longrightarrow> (\\<lambda>z. f z / g z) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_divide)\n\nlemma holomorphic_on_power [holomorphic_intros]:\n  \"f holomorphic_on A \\<Longrightarrow> (\\<lambda>z. (f z)^n) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_power)\n\nlemma holomorphic_on_power_int [holomorphic_intros]:\n  assumes nz: \"n \\<ge> 0 \\<or> (\\<forall>x\\<in>A. f x \\<noteq> 0)\" and f: \"f holomorphic_on A\"\n  shows   \"(\\<lambda>x. f x powi n) holomorphic_on A\"\nproof (cases \"n \\<ge> 0\")\n  case True\n  have \"(\\<lambda>x. f x ^ nat n) holomorphic_on A\"\n    by (simp add: f holomorphic_on_power)\n  with True show ?thesis\n    by (simp add: power_int_def)\nnext\n  case False\n  hence \"(\\<lambda>x. inverse (f x ^ nat (-n))) holomorphic_on A\"\n    using nz by (auto intro!: holomorphic_intros f)\n  with False show ?thesis\n    by (simp add: power_int_def power_inverse)\nqed\n\nlemma holomorphic_on_sum [holomorphic_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) holomorphic_on A) \\<Longrightarrow> (\\<lambda>x. sum (\\<lambda>i. f i x) I) holomorphic_on A\"\n  unfolding holomorphic_on_def by (metis field_differentiable_sum)\n\nlemma holomorphic_on_prod [holomorphic_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) holomorphic_on A) \\<Longrightarrow> (\\<lambda>x. prod (\\<lambda>i. f i x) I) holomorphic_on A\"\n  by (induction I rule: infinite_finite_induct) (auto intro: holomorphic_intros)\n\nlemma holomorphic_pochhammer [holomorphic_intros]:\n  \"f holomorphic_on A \\<Longrightarrow> (\\<lambda>s. pochhammer (f s) n) holomorphic_on A\"\n  by (induction n) (auto intro!: holomorphic_intros simp: pochhammer_Suc)\n\nlemma holomorphic_on_scaleR [holomorphic_intros]:\n  \"f holomorphic_on A \\<Longrightarrow> (\\<lambda>x. c *\\<^sub>R f x) holomorphic_on A\"\n  by (auto simp: scaleR_conv_of_real intro!: holomorphic_intros)\n\nlemma holomorphic_on_Un [holomorphic_intros]:\n  assumes \"f holomorphic_on A\" \"f holomorphic_on B\" \"open A\" \"open B\"\n  shows   \"f holomorphic_on (A \\<union> B)\"\n  using assms by (auto simp: holomorphic_on_def  at_within_open[of _ A]\n                             at_within_open[of _ B]  at_within_open[of _ \"A \\<union> B\"] open_Un)\n\nlemma holomorphic_on_If_Un [holomorphic_intros]:\n  assumes \"f holomorphic_on A\" \"g holomorphic_on B\" \"open A\" \"open B\"\n  assumes \"\\<And>z. z \\<in> A \\<Longrightarrow> z \\<in> B \\<Longrightarrow> f z = g z\"\n  shows   \"(\\<lambda>z. if z \\<in> A then f z else g z) holomorphic_on (A \\<union> B)\" (is \"?h holomorphic_on _\")\nproof (intro holomorphic_on_Un)\n  note \\<open>f holomorphic_on A\\<close>\n  also have \"f holomorphic_on A \\<longleftrightarrow> ?h holomorphic_on A\"\n    by (intro holomorphic_cong) auto\n  finally show \\<dots> .\nnext\n  note \\<open>g holomorphic_on B\\<close>\n  also have \"g holomorphic_on B \\<longleftrightarrow> ?h holomorphic_on B\"\n    using assms by (intro holomorphic_cong) auto\n  finally show \\<dots> .\nqed (insert assms, auto)\n\nlemma holomorphic_derivI:\n     \"\\<lbrakk>f holomorphic_on S; open S; x \\<in> S\\<rbrakk>\n      \\<Longrightarrow> (f has_field_derivative deriv f x) (at x within T)\"\nby (metis DERIV_deriv_iff_field_differentiable at_within_open  holomorphic_on_def has_field_derivative_at_within)\n\nlemma complex_derivative_transform_within_open:\n  \"\\<lbrakk>f holomorphic_on s; g holomorphic_on s; open s; z \\<in> s; \\<And>w. w \\<in> s \\<Longrightarrow> f w = g w\\<rbrakk>\n   \\<Longrightarrow> deriv f z = deriv g z\"\n  unfolding holomorphic_on_def\n  by (rule DERIV_imp_deriv)\n     (metis DERIV_deriv_iff_field_differentiable has_field_derivative_transform_within_open at_within_open)\n\nlemma holomorphic_on_compose_cnj_cnj:\n  assumes \"f holomorphic_on cnj ` A\" \"open A\"\n  shows   \"cnj \\<circ> f \\<circ> cnj holomorphic_on A\"\nproof -\n  have [simp]: \"open (cnj ` A)\"\n    unfolding image_cnj_conv_vimage_cnj using assms by (intro open_vimage) auto\n  show ?thesis\n    using assms unfolding holomorphic_on_def\n    by (auto intro!: field_differentiable_cnj_cnj simp: at_within_open_NO_MATCH)\nqed\n  \nlemma holomorphic_nonconstant:\n  assumes holf: \"f holomorphic_on S\" and \"open S\" \"\\<xi> \\<in> S\" \"deriv f \\<xi> \\<noteq> 0\"\n    shows \"\\<not> f constant_on S\"\n  by (rule nonzero_deriv_nonconstant [of f \"deriv f \\<xi>\" \\<xi> S])\n    (use assms in \\<open>auto simp: holomorphic_derivI\\<close>)\n\nsubsection\\<open>Analyticity on a set\\<close>\n\ndefinition\\<^marker>\\<open>tag important\\<close> analytic_on (infixl \"(analytic'_on)\" 50)\n  where \"f analytic_on S \\<equiv> \\<forall>x \\<in> S. \\<exists>e. 0 < e \\<and> f holomorphic_on (ball x e)\"\n\nnamed_theorems\\<^marker>\\<open>tag important\\<close> analytic_intros \"introduction rules for proving analyticity\"\n\nlemma analytic_imp_holomorphic: \"f analytic_on S \\<Longrightarrow> f holomorphic_on S\"\n  by (simp add: at_within_open [OF _ open_ball] analytic_on_def holomorphic_on_def)\n     (metis centre_in_ball field_differentiable_at_within)\n\nlemma analytic_on_open: \"open S \\<Longrightarrow> f analytic_on S \\<longleftrightarrow> f holomorphic_on S\"\n  by (meson analytic_imp_holomorphic analytic_on_def holomorphic_on_subset openE)\n\nlemma analytic_on_imp_differentiable_at:\n  \"f analytic_on S \\<Longrightarrow> x \\<in> S \\<Longrightarrow> f field_differentiable (at x)\"\n  using analytic_on_def holomorphic_on_imp_differentiable_at by auto\n\nlemma analytic_at_imp_isCont:\n  assumes \"f analytic_on {z}\"\n  shows   \"isCont f z\"\n  using assms by (meson analytic_on_imp_differentiable_at field_differentiable_imp_continuous_at insertI1)\n\nlemma analytic_at_neq_imp_eventually_neq:\n  assumes \"f analytic_on {x}\" \"f x \\<noteq> c\"\n  shows   \"eventually (\\<lambda>y. f y \\<noteq> c) (at x)\"\nproof (intro tendsto_imp_eventually_ne)\n  show \"f \\<midarrow>x\\<rightarrow> f x\"\n    using assms by (simp add: analytic_at_imp_isCont isContD)\nqed (use assms in auto)\n\nlemma analytic_on_subset: \"f analytic_on S \\<Longrightarrow> T \\<subseteq> S \\<Longrightarrow> f analytic_on T\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_Un: \"f analytic_on (S \\<union> T) \\<longleftrightarrow> f analytic_on S \\<and> f analytic_on T\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_Union: \"f analytic_on (\\<Union>\\<T>) \\<longleftrightarrow> (\\<forall>T \\<in> \\<T>. f analytic_on T)\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_UN: \"f analytic_on (\\<Union>i\\<in>I. S i) \\<longleftrightarrow> (\\<forall>i\\<in>I. f analytic_on (S i))\"\n  by (auto simp: analytic_on_def)\n\nlemma analytic_on_holomorphic:\n  \"f analytic_on S \\<longleftrightarrow> (\\<exists>T. open T \\<and> S \\<subseteq> T \\<and> f holomorphic_on T)\"\n  (is \"?lhs = ?rhs\")\nproof -\n  have \"?lhs \\<longleftrightarrow> (\\<exists>T. open T \\<and> S \\<subseteq> T \\<and> f analytic_on T)\"\n  proof safe\n    assume \"f analytic_on S\"\n    then show \"\\<exists>T. open T \\<and> S \\<subseteq> T \\<and> f analytic_on T\"\n      apply (simp add: analytic_on_def)\n      apply (rule exI [where x=\"\\<Union>{U. open U \\<and> f analytic_on U}\"], auto)\n      apply (metis open_ball analytic_on_open centre_in_ball)\n      by (metis analytic_on_def)\n  next\n    fix T\n    assume \"open T\" \"S \\<subseteq> T\" \"f analytic_on T\"\n    then show \"f analytic_on S\"\n        by (metis analytic_on_subset)\n  qed\n  also have \"... \\<longleftrightarrow> ?rhs\"\n    by (auto simp: analytic_on_open)\n  finally show ?thesis .\nqed\n\nlemma analytic_on_linear [analytic_intros,simp]: \"((*) c) analytic_on S\"\n  by (auto simp add: analytic_on_holomorphic)\n\nlemma analytic_on_const [analytic_intros,simp]: \"(\\<lambda>z. c) analytic_on S\"\n  by (metis analytic_on_def holomorphic_on_const zero_less_one)\n\nlemma analytic_on_ident [analytic_intros,simp]: \"(\\<lambda>x. x) analytic_on S\"\n  by (simp add: analytic_on_def gt_ex)\n\nlemma analytic_on_id [analytic_intros]: \"id analytic_on S\"\n  unfolding id_def by (rule analytic_on_ident)\n\nlemma analytic_on_compose:\n  assumes f: \"f analytic_on S\"\n      and g: \"g analytic_on (f ` S)\"\n    shows \"(g o f) analytic_on S\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix x\n  assume x: \"x \\<in> S\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball x e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball (f x) e'\" using g\n    by (metis analytic_on_def g image_eqI x)\n  have \"isCont f x\"\n    by (metis analytic_on_imp_differentiable_at field_differentiable_imp_continuous_at f x)\n  with e' obtain d where d: \"0 < d\" and fd: \"f ` ball x d \\<subseteq> ball (f x) e'\"\n     by (auto simp: continuous_at_ball)\n  have \"g \\<circ> f holomorphic_on ball x (min d e)\"\n    apply (rule holomorphic_on_compose)\n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis fd gh holomorphic_on_subset image_mono min.cobounded1 subset_ball)\n  then show \"\\<exists>e>0. g \\<circ> f holomorphic_on ball x e\"\n    by (metis d e min_less_iff_conj)\nqed\n\nlemma analytic_on_compose_gen:\n  \"f analytic_on S \\<Longrightarrow> g analytic_on T \\<Longrightarrow> (\\<And>z. z \\<in> S \\<Longrightarrow> f z \\<in> T)\n             \\<Longrightarrow> g o f analytic_on S\"\nby (metis analytic_on_compose analytic_on_subset image_subset_iff)\n\nlemma analytic_on_neg [analytic_intros]:\n  \"f analytic_on S \\<Longrightarrow> (\\<lambda>z. -(f z)) analytic_on S\"\nby (metis analytic_on_holomorphic holomorphic_on_minus)\n\nlemma analytic_on_add [analytic_intros]:\n  assumes f: \"f analytic_on S\"\n      and g: \"g analytic_on S\"\n    shows \"(\\<lambda>z. f z + g z) analytic_on S\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> S\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball z e'\" using g\n    by (metis analytic_on_def g z)\n  have \"(\\<lambda>z. f z + g z) holomorphic_on ball z (min e e')\"\n    apply (rule holomorphic_on_add)\n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis gh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n  then show \"\\<exists>e>0. (\\<lambda>z. f z + g z) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_diff [analytic_intros]:\n  assumes f: \"f analytic_on S\"\n      and g: \"g analytic_on S\"\n    shows \"(\\<lambda>z. f z - g z) analytic_on S\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> S\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball z e'\" using g\n    by (metis analytic_on_def g z)\n  have \"(\\<lambda>z. f z - g z) holomorphic_on ball z (min e e')\"\n    apply (rule holomorphic_on_diff)\n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis gh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n  then show \"\\<exists>e>0. (\\<lambda>z. f z - g z) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_mult [analytic_intros]:\n  assumes f: \"f analytic_on S\"\n      and g: \"g analytic_on S\"\n    shows \"(\\<lambda>z. f z * g z) analytic_on S\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> S\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  obtain e' where e': \"0 < e'\" and gh: \"g holomorphic_on ball z e'\" using g\n    by (metis analytic_on_def g z)\n  have \"(\\<lambda>z. f z * g z) holomorphic_on ball z (min e e')\"\n    apply (rule holomorphic_on_mult)\n    apply (metis fh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n    by (metis gh holomorphic_on_subset min.bounded_iff order_refl subset_ball)\n  then show \"\\<exists>e>0. (\\<lambda>z. f z * g z) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_inverse [analytic_intros]:\n  assumes f: \"f analytic_on S\"\n      and nz: \"(\\<And>z. z \\<in> S \\<Longrightarrow> f z \\<noteq> 0)\"\n    shows \"(\\<lambda>z. inverse (f z)) analytic_on S\"\nunfolding analytic_on_def\nproof (intro ballI)\n  fix z\n  assume z: \"z \\<in> S\"\n  then obtain e where e: \"0 < e\" and fh: \"f holomorphic_on ball z e\" using f\n    by (metis analytic_on_def)\n  have \"continuous_on (ball z e) f\"\n    by (metis fh holomorphic_on_imp_continuous_on)\n  then obtain e' where e': \"0 < e'\" and nz': \"\\<And>y. dist z y < e' \\<Longrightarrow> f y \\<noteq> 0\"\n    by (metis open_ball centre_in_ball continuous_on_open_avoid e z nz)\n  have \"(\\<lambda>z. inverse (f z)) holomorphic_on ball z (min e e')\"\n    apply (rule holomorphic_on_inverse)\n    apply (metis fh holomorphic_on_subset min.cobounded2 min.commute subset_ball)\n    by (metis nz' mem_ball min_less_iff_conj)\n  then show \"\\<exists>e>0. (\\<lambda>z. inverse (f z)) holomorphic_on ball z e\"\n    by (metis e e' min_less_iff_conj)\nqed\n\nlemma analytic_on_divide [analytic_intros]:\n  assumes f: \"f analytic_on S\"\n      and g: \"g analytic_on S\"\n      and nz: \"(\\<And>z. z \\<in> S \\<Longrightarrow> g z \\<noteq> 0)\"\n    shows \"(\\<lambda>z. f z / g z) analytic_on S\"\nunfolding divide_inverse\nby (metis analytic_on_inverse analytic_on_mult f g nz)\n\nlemma analytic_on_power [analytic_intros]:\n  \"f analytic_on S \\<Longrightarrow> (\\<lambda>z. (f z) ^ n) analytic_on S\"\nby (induct n) (auto simp: analytic_on_mult)\n\nlemma analytic_on_power_int [analytic_intros]:\n  assumes nz: \"n \\<ge> 0 \\<or> (\\<forall>x\\<in>A. f x \\<noteq> 0)\" and f: \"f analytic_on A\"\n  shows   \"(\\<lambda>x. f x powi n) analytic_on A\"\nproof (cases \"n \\<ge> 0\")\n  case True\n  have \"(\\<lambda>x. f x ^ nat n) analytic_on A\"\n    using analytic_on_power f by blast\n  with True show ?thesis\n    by (simp add: power_int_def)\nnext\n  case False\n  hence \"(\\<lambda>x. inverse (f x ^ nat (-n))) analytic_on A\"\n    using nz by (auto intro!: analytic_intros f)\n  with False show ?thesis\n    by (simp add: power_int_def power_inverse)\nqed\n\nlemma analytic_on_sum [analytic_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) analytic_on S) \\<Longrightarrow> (\\<lambda>x. sum (\\<lambda>i. f i x) I) analytic_on S\"\n  by (induct I rule: infinite_finite_induct) (auto simp: analytic_on_add)\n\nlemma analytic_on_prod [analytic_intros]:\n  \"(\\<And>i. i \\<in> I \\<Longrightarrow> (f i) analytic_on S) \\<Longrightarrow> (\\<lambda>x. prod (\\<lambda>i. f i x) I) analytic_on S\"\n  by (induct I rule: infinite_finite_induct) (auto simp: analytic_on_mult)\n\nlemma deriv_left_inverse:\n  assumes \"f holomorphic_on S\" and \"g holomorphic_on T\"\n      and \"open S\" and \"open T\"\n      and \"f ` S \\<subseteq> T\"\n      and [simp]: \"\\<And>z. z \\<in> S \\<Longrightarrow> g (f z) = z\"\n      and \"w \\<in> S\"\n    shows \"deriv f w * deriv g (f w) = 1\"\nproof -\n  have \"deriv f w * deriv g (f w) = deriv g (f w) * deriv f w\"\n    by (simp add: algebra_simps)\n  also have \"... = deriv (g o f) w\"\n    using assms\n    by (metis analytic_on_imp_differentiable_at analytic_on_open deriv_chain image_subset_iff)\n  also have \"... = deriv id w\"\n  proof (rule complex_derivative_transform_within_open [where s=S])\n    show \"g \\<circ> f holomorphic_on S\"\n      by (rule assms holomorphic_on_compose_gen holomorphic_intros)+\n  qed (use assms in auto)\n  also have \"... = 1\"\n    by simp\n  finally show ?thesis .\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Analyticity at a point\\<close>\n\nlemma analytic_at_ball:\n  \"f analytic_on {z} \\<longleftrightarrow> (\\<exists>e. 0<e \\<and> f holomorphic_on ball z e)\"\n  by (metis analytic_on_def singleton_iff)\n\nlemma analytic_at:\n  \"f analytic_on {z} \\<longleftrightarrow> (\\<exists>s. open s \\<and> z \\<in> s \\<and> f holomorphic_on s)\"\n  by (metis analytic_on_holomorphic empty_subsetI insert_subset)\n\nlemma holomorphic_on_imp_analytic_at:\n  assumes \"f holomorphic_on A\" \"open A\" \"z \\<in> A\"\n  shows   \"f analytic_on {z}\"\n  using assms by (meson analytic_at)\n\nlemma analytic_on_analytic_at:\n  \"f analytic_on s \\<longleftrightarrow> (\\<forall>z \\<in> s. f analytic_on {z})\"\n  by (metis analytic_at_ball analytic_on_def)\n\nlemma analytic_at_two:\n  \"f analytic_on {z} \\<and> g analytic_on {z} \\<longleftrightarrow>\n   (\\<exists>s. open s \\<and> z \\<in> s \\<and> f holomorphic_on s \\<and> g holomorphic_on s)\"\n  (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain s t\n    where st: \"open s\" \"z \\<in> s\" \"f holomorphic_on s\"\n              \"open t\" \"z \\<in> t\" \"g holomorphic_on t\"\n    by (auto simp: analytic_at)\n  show ?rhs\n    apply (rule_tac x=\"s \\<inter> t\" in exI)\n    using st\n    apply (auto simp: holomorphic_on_subset)\n    done\nnext\n  assume ?rhs\n  then show ?lhs\n    by (force simp add: analytic_at)\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Combining theorems for derivative with ``analytic at'' hypotheses\\<close>\n\nlemma\n  assumes \"f analytic_on {z}\" \"g analytic_on {z}\"\n  shows complex_derivative_add_at: \"deriv (\\<lambda>w. f w + g w) z = deriv f z + deriv g z\"\n    and complex_derivative_diff_at: \"deriv (\\<lambda>w. f w - g w) z = deriv f z - deriv g z\"\n    and complex_derivative_mult_at: \"deriv (\\<lambda>w. f w * g w) z =\n           f z * deriv g z + deriv f z * g z\"\nproof -\n  obtain s where s: \"open s\" \"z \\<in> s\" \"f holomorphic_on s\" \"g holomorphic_on s\"\n    using assms by (metis analytic_at_two)\n  show \"deriv (\\<lambda>w. f w + g w) z = deriv f z + deriv g z\"\n    apply (rule DERIV_imp_deriv [OF DERIV_add])\n    using s\n    apply (auto simp: holomorphic_on_open field_differentiable_def DERIV_deriv_iff_field_differentiable)\n    done\n  show \"deriv (\\<lambda>w. f w - g w) z = deriv f z - deriv g z\"\n    apply (rule DERIV_imp_deriv [OF DERIV_diff])\n    using s\n    apply (auto simp: holomorphic_on_open field_differentiable_def DERIV_deriv_iff_field_differentiable)\n    done\n  show \"deriv (\\<lambda>w. f w * g w) z = f z * deriv g z + deriv f z * g z\"\n    apply (rule DERIV_imp_deriv [OF DERIV_mult'])\n    using s\n    apply (auto simp: holomorphic_on_open field_differentiable_def DERIV_deriv_iff_field_differentiable)\n    done\nqed\n\nlemma deriv_cmult_at:\n  \"f analytic_on {z} \\<Longrightarrow>  deriv (\\<lambda>w. c * f w) z = c * deriv f z\"\nby (auto simp: complex_derivative_mult_at)\n\nlemma deriv_cmult_right_at:\n  \"f analytic_on {z} \\<Longrightarrow>  deriv (\\<lambda>w. f w * c) z = deriv f z * c\"\nby (auto simp: complex_derivative_mult_at)\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close>\\<open>Complex differentiation of sequences and series\\<close>\n\n(* TODO: Could probably be simplified using Uniform_Limit *)\nlemma has_complex_derivative_sequence:\n  fixes S :: \"complex set\"\n  assumes cvs: \"convex S\"\n      and df:  \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within S)\"\n      and conv: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>N. \\<forall>n x. n \\<ge> N \\<longrightarrow> x \\<in> S \\<longrightarrow> norm (f' n x - g' x) \\<le> e\"\n      and \"\\<exists>x l. x \\<in> S \\<and> ((\\<lambda>n. f n x) \\<longlongrightarrow> l) sequentially\"\n    shows \"\\<exists>g. \\<forall>x \\<in> S. ((\\<lambda>n. f n x) \\<longlongrightarrow> g x) sequentially \\<and>\n                       (g has_field_derivative (g' x)) (at x within S)\"\nproof -\n  from assms obtain x l where x: \"x \\<in> S\" and tf: \"((\\<lambda>n. f n x) \\<longlongrightarrow> l) sequentially\"\n    by blast\n  { fix e::real assume e: \"e > 0\"\n    then obtain N where N: \"\\<forall>n\\<ge>N. \\<forall>x. x \\<in> S \\<longrightarrow> cmod (f' n x - g' x) \\<le> e\"\n      by (metis conv)\n    have \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>h. cmod (f' n x * h - g' x * h) \\<le> e * cmod h\"\n    proof (rule exI [of _ N], clarify)\n      fix n y h\n      assume \"N \\<le> n\" \"y \\<in> S\"\n      then have \"cmod (f' n y - g' y) \\<le> e\"\n        by (metis N)\n      then have \"cmod h * cmod (f' n y - g' y) \\<le> cmod h * e\"\n        by (auto simp: antisym_conv2 mult_le_cancel_left norm_triangle_ineq2)\n      then show \"cmod (f' n y * h - g' y * h) \\<le> e * cmod h\"\n        by (simp add: norm_mult [symmetric] field_simps)\n    qed\n  } note ** = this\n  show ?thesis\n    unfolding has_field_derivative_def\n  proof (rule has_derivative_sequence [OF cvs _ _ x])\n    show \"(\\<lambda>n. f n x) \\<longlonglongrightarrow> l\"\n      by (rule tf)\n  next show \"\\<And>e. e > 0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. cmod (f' n x * h - g' x * h) \\<le> e * cmod h\"\n      unfolding eventually_sequentially by (blast intro: **)\n  qed (metis has_field_derivative_def df)\nqed\n\nlemma has_complex_derivative_series:\n  fixes S :: \"complex set\"\n  assumes cvs: \"convex S\"\n      and df:  \"\\<And>n x. x \\<in> S \\<Longrightarrow> (f n has_field_derivative f' n x) (at x within S)\"\n      and conv: \"\\<And>e. 0 < e \\<Longrightarrow> \\<exists>N. \\<forall>n x. n \\<ge> N \\<longrightarrow> x \\<in> S\n                \\<longrightarrow> cmod ((\\<Sum>i<n. f' i x) - g' x) \\<le> e\"\n      and \"\\<exists>x l. x \\<in> S \\<and> ((\\<lambda>n. f n x) sums l)\"\n    shows \"\\<exists>g. \\<forall>x \\<in> S. ((\\<lambda>n. f n x) sums g x) \\<and> ((g has_field_derivative g' x) (at x within S))\"\nproof -\n  from assms obtain x l where x: \"x \\<in> S\" and sf: \"((\\<lambda>n. f n x) sums l)\"\n    by blast\n  { fix e::real assume e: \"e > 0\"\n    then obtain N where N: \"\\<forall>n x. n \\<ge> N \\<longrightarrow> x \\<in> S\n            \\<longrightarrow> cmod ((\\<Sum>i<n. f' i x) - g' x) \\<le> e\"\n      by (metis conv)\n    have \"\\<exists>N. \\<forall>n\\<ge>N. \\<forall>x\\<in>S. \\<forall>h. cmod ((\\<Sum>i<n. h * f' i x) - g' x * h) \\<le> e * cmod h\"\n    proof (rule exI [of _ N], clarify)\n      fix n y h\n      assume \"N \\<le> n\" \"y \\<in> S\"\n      then have \"cmod ((\\<Sum>i<n. f' i y) - g' y) \\<le> e\"\n        by (metis N)\n      then have \"cmod h * cmod ((\\<Sum>i<n. f' i y) - g' y) \\<le> cmod h * e\"\n        by (auto simp: antisym_conv2 mult_le_cancel_left norm_triangle_ineq2)\n      then show \"cmod ((\\<Sum>i<n. h * f' i y) - g' y * h) \\<le> e * cmod h\"\n        by (simp add: norm_mult [symmetric] field_simps sum_distrib_left)\n    qed\n  } note ** = this\n  show ?thesis\n  unfolding has_field_derivative_def\n  proof (rule has_derivative_series [OF cvs _ _ x])\n    fix n x\n    assume \"x \\<in> S\"\n    then show \"((f n) has_derivative (\\<lambda>z. z * f' n x)) (at x within S)\"\n      by (metis df has_field_derivative_def mult_commute_abs)\n  next show \" ((\\<lambda>n. f n x) sums l)\"\n    by (rule sf)\n  next show \"\\<And>e. e>0 \\<Longrightarrow> \\<forall>\\<^sub>F n in sequentially. \\<forall>x\\<in>S. \\<forall>h. cmod ((\\<Sum>i<n. h * f' i x) - g' x * h) \\<le> e * cmod h\"\n      unfolding eventually_sequentially by (blast intro: **)\n  qed\nqed\n\nsubsection\\<^marker>\\<open>tag unimportant\\<close> \\<open>Taylor on Complex Numbers\\<close>\n\nlemma sum_Suc_reindex:\n  fixes f :: \"nat \\<Rightarrow> 'a::ab_group_add\"\n    shows  \"sum f {0..n} = f 0 - f (Suc n) + sum (\\<lambda>i. f (Suc i)) {0..n}\"\nby (induct n) auto\n\nlemma field_Taylor:\n  assumes S: \"convex S\"\n      and f: \"\\<And>i x. x \\<in> S \\<Longrightarrow> i \\<le> n \\<Longrightarrow> (f i has_field_derivative f (Suc i) x) (at x within S)\"\n      and B: \"\\<And>x. x \\<in> S \\<Longrightarrow> norm (f (Suc n) x) \\<le> B\"\n      and w: \"w \\<in> S\"\n      and z: \"z \\<in> S\"\n    shows \"norm(f 0 z - (\\<Sum>i\\<le>n. f i w * (z-w) ^ i / (fact i)))\n          \\<le> B * norm(z - w)^(Suc n) / fact n\"\nproof -\n  have wzs: \"closed_segment w z \\<subseteq> S\" using assms\n    by (metis convex_contains_segment)\n  { fix u\n    assume \"u \\<in> closed_segment w z\"\n    then have \"u \\<in> S\"\n      by (metis wzs subsetD)\n    have \"(\\<Sum>i\\<le>n. f i u * (- of_nat i * (z-u)^(i - 1)) / (fact i) +\n                      f (Suc i) u * (z-u)^i / (fact i)) =\n              f (Suc n) u * (z-u) ^ n / (fact n)\"\n    proof (induction n)\n      case 0 show ?case by simp\n    next\n      case (Suc n)\n      have \"(\\<Sum>i\\<le>Suc n. f i u * (- of_nat i * (z-u) ^ (i - 1)) / (fact i) +\n                             f (Suc i) u * (z-u) ^ i / (fact i)) =\n           f (Suc n) u * (z-u) ^ n / (fact n) +\n           f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n) / (fact (Suc n)) -\n           f (Suc n) u * ((1 + of_nat n) * (z-u) ^ n) / (fact (Suc n))\"\n        using Suc by simp\n      also have \"... = f (Suc (Suc n)) u * (z-u) ^ Suc n / (fact (Suc n))\"\n      proof -\n        have \"(fact(Suc n)) *\n             (f(Suc n) u *(z-u) ^ n / (fact n) +\n               f(Suc(Suc n)) u *((z-u) *(z-u) ^ n) / (fact(Suc n)) -\n               f(Suc n) u *((1 + of_nat n) *(z-u) ^ n) / (fact(Suc n))) =\n            ((fact(Suc n)) *(f(Suc n) u *(z-u) ^ n)) / (fact n) +\n            ((fact(Suc n)) *(f(Suc(Suc n)) u *((z-u) *(z-u) ^ n)) / (fact(Suc n))) -\n            ((fact(Suc n)) *(f(Suc n) u *(of_nat(Suc n) *(z-u) ^ n))) / (fact(Suc n))\"\n          by (simp add: algebra_simps del: fact_Suc)\n        also have \"... = ((fact (Suc n)) * (f (Suc n) u * (z-u) ^ n)) / (fact n) +\n                         (f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n)) -\n                         (f (Suc n) u * ((1 + of_nat n) * (z-u) ^ n))\"\n          by (simp del: fact_Suc)\n        also have \"... = (of_nat (Suc n) * (f (Suc n) u * (z-u) ^ n)) +\n                         (f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n)) -\n                         (f (Suc n) u * ((1 + of_nat n) * (z-u) ^ n))\"\n          by (simp only: fact_Suc of_nat_mult ac_simps) simp\n        also have \"... = f (Suc (Suc n)) u * ((z-u) * (z-u) ^ n)\"\n          by (simp add: algebra_simps)\n        finally show ?thesis\n        by (simp add: mult_left_cancel [where c = \"(fact (Suc n))\", THEN iffD1] del: fact_Suc)\n      qed\n      finally show ?case .\n    qed\n    then have \"((\\<lambda>v. (\\<Sum>i\\<le>n. f i v * (z - v)^i / (fact i)))\n                has_field_derivative f (Suc n) u * (z-u) ^ n / (fact n))\n               (at u within S)\"\n      apply (intro derivative_eq_intros)\n      apply (blast intro: assms \\<open>u \\<in> S\\<close>)\n      apply (rule refl)+\n      apply (auto simp: field_simps)\n      done\n  } note sum_deriv = this\n  { fix u\n    assume u: \"u \\<in> closed_segment w z\"\n    then have us: \"u \\<in> S\"\n      by (metis wzs subsetD)\n    have \"norm (f (Suc n) u) * norm (z - u) ^ n \\<le> norm (f (Suc n) u) * norm (u - z) ^ n\"\n      by (metis norm_minus_commute order_refl)\n    also have \"... \\<le> norm (f (Suc n) u) * norm (z - w) ^ n\"\n      by (metis mult_left_mono norm_ge_zero power_mono segment_bound [OF u])\n    also have \"... \\<le> B * norm (z - w) ^ n\"\n      by (metis norm_ge_zero zero_le_power mult_right_mono  B [OF us])\n    finally have \"norm (f (Suc n) u) * norm (z - u) ^ n \\<le> B * norm (z - w) ^ n\" .\n  } note cmod_bound = this\n  have \"(\\<Sum>i\\<le>n. f i z * (z - z) ^ i / (fact i)) = (\\<Sum>i\\<le>n. (f i z / (fact i)) * 0 ^ i)\"\n    by simp\n  also have \"\\<dots> = f 0 z / (fact 0)\"\n    by (subst sum_zero_power) simp\n  finally have \"norm (f 0 z - (\\<Sum>i\\<le>n. f i w * (z - w) ^ i / (fact i)))\n                \\<le> norm ((\\<Sum>i\\<le>n. f i w * (z - w) ^ i / (fact i)) -\n                        (\\<Sum>i\\<le>n. f i z * (z - z) ^ i / (fact i)))\"\n    by (simp add: norm_minus_commute)\n  also have \"... \\<le> B * norm (z - w) ^ n / (fact n) * norm (w - z)\"\n    apply (rule field_differentiable_bound\n      [where f' = \"\\<lambda>w. f (Suc n) w * (z - w)^n / (fact n)\"\n         and S = \"closed_segment w z\", OF convex_closed_segment])\n    apply (auto simp: DERIV_subset [OF sum_deriv wzs]\n                  norm_divide norm_mult norm_power divide_le_cancel cmod_bound)\n    done\n  also have \"...  \\<le> B * norm (z - w) ^ Suc n / (fact n)\"\n    by (simp add: algebra_simps norm_minus_commute)\n  finally show ?thesis .\nqed\n\nlemma complex_Taylor:\n  assumes S: \"convex S\"\n      and f: \"\\<And>i x. x \\<in> S \\<Longrightarrow> i \\<le> n \\<Longrightarrow> (f i has_field_derivative f (Suc i) x) (at x within S)\"\n      and B: \"\\<And>x. x \\<in> S \\<Longrightarrow> cmod (f (Suc n) x) \\<le> B\"\n      and w: \"w \\<in> S\"\n      and z: \"z \\<in> S\"\n    shows \"cmod(f 0 z - (\\<Sum>i\\<le>n. f i w * (z-w) ^ i / (fact i)))\n          \\<le> B * cmod(z - w)^(Suc n) / fact n\"\n  using assms by (rule field_Taylor)\n\n\ntext\\<open>Something more like the traditional MVT for real components\\<close>\n\nlemma complex_mvt_line:\n  assumes \"\\<And>u. u \\<in> closed_segment w z \\<Longrightarrow> (f has_field_derivative f'(u)) (at u)\"\n    shows \"\\<exists>u. u \\<in> closed_segment w z \\<and> Re(f z) - Re(f w) = Re(f'(u) * (z - w))\"\nproof -\n  have twz: \"\\<And>t. (1 - t) *\\<^sub>R w + t *\\<^sub>R z = w + t *\\<^sub>R (z - w)\"\n    by (simp add: real_vector.scale_left_diff_distrib real_vector.scale_right_diff_distrib)\n  note assms[unfolded has_field_derivative_def, derivative_intros]\n  show ?thesis\n    apply (cut_tac mvt_simple\n                     [of 0 1 \"Re o f o (\\<lambda>t. (1 - t) *\\<^sub>R w +  t *\\<^sub>R z)\"\n                      \"\\<lambda>u. Re o (\\<lambda>h. f'((1 - u) *\\<^sub>R w + u *\\<^sub>R z) * h) o (\\<lambda>t. t *\\<^sub>R (z - w))\"])\n    apply auto\n    apply (rule_tac x=\"(1 - x) *\\<^sub>R w + x *\\<^sub>R z\" in exI)\n    apply (auto simp: closed_segment_def twz) []\n    apply (intro derivative_eq_intros has_derivative_at_withinI, simp_all)\n    apply (simp add: fun_eq_iff real_vector.scale_right_diff_distrib)\n    apply (force simp: twz closed_segment_def)\n    done\nqed\n\nlemma complex_Taylor_mvt:\n  assumes \"\\<And>i x. \\<lbrakk>x \\<in> closed_segment w z; i \\<le> n\\<rbrakk> \\<Longrightarrow> ((f i) has_field_derivative f (Suc i) x) (at x)\"\n    shows \"\\<exists>u. u \\<in> closed_segment w z \\<and>\n            Re (f 0 z) =\n            Re ((\\<Sum>i = 0..n. f i w * (z - w) ^ i / (fact i)) +\n                (f (Suc n) u * (z-u)^n / (fact n)) * (z - w))\"\nproof -\n  { fix u\n    assume u: \"u \\<in> closed_segment w z\"\n    have \"(\\<Sum>i = 0..n.\n               (f (Suc i) u * (z-u) ^ i - of_nat i * (f i u * (z-u) ^ (i - Suc 0))) /\n               (fact i)) =\n          f (Suc 0) u -\n             (f (Suc (Suc n)) u * ((z-u) ^ Suc n) - (of_nat (Suc n)) * (z-u) ^ n * f (Suc n) u) /\n             (fact (Suc n)) +\n             (\\<Sum>i = 0..n.\n                 (f (Suc (Suc i)) u * ((z-u) ^ Suc i) - of_nat (Suc i) * (f (Suc i) u * (z-u) ^ i)) /\n                 (fact (Suc i)))\"\n       by (subst sum_Suc_reindex) simp\n    also have \"... = f (Suc 0) u -\n             (f (Suc (Suc n)) u * ((z-u) ^ Suc n) - (of_nat (Suc n)) * (z-u) ^ n * f (Suc n) u) /\n             (fact (Suc n)) +\n             (\\<Sum>i = 0..n.\n                 f (Suc (Suc i)) u * ((z-u) ^ Suc i) / (fact (Suc i))  -\n                 f (Suc i) u * (z-u) ^ i / (fact i))\"\n      by (simp only: diff_divide_distrib fact_cancel ac_simps)\n    also have \"... = f (Suc 0) u -\n             (f (Suc (Suc n)) u * (z-u) ^ Suc n - of_nat (Suc n) * (z-u) ^ n * f (Suc n) u) /\n             (fact (Suc n)) +\n             f (Suc (Suc n)) u * (z-u) ^ Suc n / (fact (Suc n)) - f (Suc 0) u\"\n      by (subst sum_Suc_diff) auto\n    also have \"... = f (Suc n) u * (z-u) ^ n / (fact n)\"\n      by (simp only: algebra_simps diff_divide_distrib fact_cancel)\n    finally have \"(\\<Sum>i = 0..n. (f (Suc i) u * (z - u) ^ i\n                             - of_nat i * (f i u * (z-u) ^ (i - Suc 0))) / (fact i)) =\n                  f (Suc n) u * (z - u) ^ n / (fact n)\" .\n    then have \"((\\<lambda>u. \\<Sum>i = 0..n. f i u * (z - u) ^ i / (fact i)) has_field_derivative\n                f (Suc n) u * (z - u) ^ n / (fact n))  (at u)\"\n      apply (intro derivative_eq_intros)+\n      apply (force intro: u assms)\n      apply (rule refl)+\n      apply (auto simp: ac_simps)\n      done\n  }\n  then show ?thesis\n    apply (cut_tac complex_mvt_line [of w z \"\\<lambda>u. \\<Sum>i = 0..n. f i u * (z-u) ^ i / (fact i)\"\n               \"\\<lambda>u. (f (Suc n) u * (z-u)^n / (fact n))\"])\n    apply (auto simp add: intro: open_closed_segment)\n    done\nqed\n\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Analysis/Complex_Analysis_Basics.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.8774767778695834, "lm_q1q2_score": 0.752671580164194}}
{"text": "(*\n  File:    Sophomores_Dream.thy\n  Author:  Manuel Eberl, University of Innsbruck\n*)\nsection \\<open>The Sophomore's Dream\\<close>\ntheory Sophomores_Dream\n  imports \"HOL-Analysis.Analysis\" \"HOL-Real_Asymp.Real_Asymp\"\nbegin\n\ntext \\<open>\n  This formalisation mostly follows the very clear proof sketch from Wikipedia~\\<^cite>\\<open>\"wikipedia\"\\<close>.\n  That article also provides an interesting historical perspective. A more detailed \n  exploration of Bernoulli's historical proof can be found in the book by Dunham~\\<^cite>\\<open>\"dunham\"\\<close>.\n\n  The name `Sophomore's Dream' apparently comes from a book by Borwein et al., in analogy to\n  the `Freshman's Dream' equation $(x+y)^n = x^n + y^n$ (which is generally \\<^emph>\\<open>not\\<close> true except\n  in rings of characteristic $n$).\n\\<close>\n\nsubsection \\<open>Continuity and bounds for $x \\log x$\\<close>\n\nlemma x_log_x_continuous: \"continuous_on {0..1} (\\<lambda>x::real. x * ln x)\"\nproof -\n  have \"continuous (at x within {0..1}) (\\<lambda>x::real. x * ln x)\" if \"x \\<in> {0..1}\" for x\n  proof (cases \"x = 0\")\n    case True\n    have \"((\\<lambda>x::real. x * ln x) \\<longlongrightarrow> 0) (at_right 0)\"\n      by real_asymp\n    thus ?thesis using True\n      by (simp add: continuous_def Lim_ident_at at_within_Icc_at_right)\n  qed (auto intro!: continuous_intros)\n  thus ?thesis\n    using continuous_on_eq_continuous_within by blast\nqed\n\nlemma x_log_x_within_01_le:\n  assumes \"x \\<in> {0..(1::real)}\"\n  shows   \"x * ln x \\<in> {-exp (-1)..0}\"\nproof -\n  have \"x * ln x \\<le> 0\"\n    using assms by (cases \"x = 0\") (auto simp: mult_nonneg_nonpos)\n  let ?f = \"\\<lambda>x::real. x * ln x\"\n  have diff: \"(?f has_field_derivative (ln x + 1)) (at x)\" if \"x > 0\" for x\n    using that by (auto intro!: derivative_eq_intros)\n  have diff': \"?f differentiable at x\" if \"x > 0\" for x\n    using diff[OF that] real_differentiable_def by blast\n\n  consider \"x = 0\" | \"x = 1\" | \"x = exp (-1)\" | \"0 < x\" \"x < exp (-1)\" | \"exp (-1) < x\" \"x < 1\"\n    using assms unfolding atLeastAtMost_iff by linarith\n  hence \"x * ln x \\<ge> -exp (-1)\"\n  proof cases\n    assume x: \"0 < x\" \"x < exp (-1)\"\n    have \"\\<exists>l z. x < z \\<and> z < exp (-1) \\<and> (?f has_real_derivative l) (at z) \\<and>\n             ?f (exp (-1)) - ?f x = (exp (-1) - x) * l\"\n      using x by (intro MVT continuous_on_subset [OF x_log_x_continuous] diff') auto\n    then obtain l z where lz:\n      \"x < z\" \"z < exp (-1)\" \"(?f has_real_derivative l) (at z)\"\n      \"?f x = -exp (-1) - (exp (-1) - x) * l\"\n      by (auto simp: algebra_simps)\n    have [simp]: \"l = ln z + 1\"\n      using DERIV_unique[OF diff[of z] lz(3)] lz(1) x by auto\n    have \"ln z \\<le> ln (exp (-1))\"\n      using lz x by (subst ln_le_cancel_iff) auto\n    hence \"(exp (- 1) - x) * l \\<le> 0\"\n      using x lz by (intro mult_nonneg_nonpos) auto\n    with lz show ?thesis\n      by linarith\n  next\n    assume x: \"exp (-1) < x\" \"x < 1\"\n    have \"\\<exists>l z. exp (-1) < z \\<and> z < x \\<and> (?f has_real_derivative l) (at z) \\<and>\n             ?f x - ?f (exp (-1)) = (x - exp (-1)) * l\"\n    proof (intro MVT continuous_on_subset [OF x_log_x_continuous] diff')\n      fix t :: real assume t: \"exp (-1) < t\"\n      show \"t > 0\"\n        by (rule less_trans [OF _ t]) auto\n    qed (use x in auto)\n    then obtain l z where lz:\n      \"exp (-1) < z\" \"z < x\" \"(?f has_real_derivative l) (at z)\"\n      \"?f x = -exp (-1) - (exp (-1) - x) * l\"\n      by (auto simp: algebra_simps)\n    have \"z > 0\"\n      by (rule less_trans [OF _ lz(1)]) auto\n    have [simp]: \"l = ln z + 1\"\n      using DERIV_unique[OF diff[of z] lz(3)] \\<open>z > 0\\<close> by auto\n    have \"ln z \\<ge> ln (exp (-1))\"\n      using lz \\<open>z > 0\\<close> by (subst ln_le_cancel_iff) auto\n    hence \"(exp (- 1) - x) * l \\<le> 0\"\n      using x lz by (intro mult_nonpos_nonneg) auto\n    with lz show ?thesis\n      by linarith\n  qed auto\n\n  with \\<open>x * ln x \\<le> 0\\<close> show ?thesis\n    by auto\nqed\n\n\nsubsection \\<open>Convergence, Summability, Integrability\\<close>\n\ntext \\<open>\n  As a first result we can show that the two sums that occur in the two different versions\n  of the Sophomore's Dream are absolutely summable. This is achieved by a simple comparison \n  test with the series $\\sum_{k=1}^\\infty k^{-2}$, as $k^{-k} \\in O(k^{-2})$.\n\\<close>\ntheorem abs_summable_sophomores_dream: \"summable (\\<lambda>k. 1 / real (k ^ k))\"\nproof (rule summable_comparison_test_bigo)\n  show \"(\\<lambda>k. 1 / real (k ^ k)) \\<in> O(\\<lambda>k. 1 / real k ^ 2)\"\n    by real_asymp\n  show \"summable (\\<lambda>n. norm (1 / real n ^ 2))\"\n    using inverse_power_summable[of 2, where ?'a = real] by (simp add: field_simps)\nqed\n\ntext \\<open>\n  The existence of the integral is also fairly easy to show since the integrand is continuous\n  and the integration domain is compact. There is, however, one hiccup: The integrand is not\n  actually continuous.\n\n  We have $\\lim_{x\\to 0} x^x = 1$, but in Isabelle $0^0$ is defined as \\<open>0\\<close> (for real numbers).\n  Thus, there is a discontinuity at \\<open>x = 0\\<close>\n\n  However, this is a removable discontinuity since for any $x>0$ we have $x^x = e^{x\\log x}$, and\n  as we have just shown, $e^{x \\log x}$ \\<^emph>\\<open>is\\<close> continuous on $[0, 1]$. Since the two integrands\n  differ only for \\<open>x = 0\\<close> (which is negligible), the integral still exists.\n\\<close>\ntheorem integrable_sophomores_dream: \"(\\<lambda>x::real. x powr x) integrable_on {0..1}\"\nproof -\n  have \"(\\<lambda>x::real. exp (x * ln x)) integrable_on {0..1}\"\n    by (intro integrable_continuous_real continuous_on_exp x_log_x_continuous)\n  also have \"?this \\<longleftrightarrow> (\\<lambda>x::real. exp (x * ln x)) integrable_on {0<..<1}\"\n    by (simp add: integrable_on_Icc_iff_Ioo)\n  also have \"\\<dots> \\<longleftrightarrow> (\\<lambda>x::real. x powr x) integrable_on {0<..<1}\"\n    by (intro integrable_cong) (auto simp: powr_def)\n  also have \"\\<dots> \\<longleftrightarrow> ?thesis\"\n    by (simp add: integrable_on_Icc_iff_Ioo)\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  Next, we have to show the absolute convergence of the two auxiliary sums that will occur in\n  our proofs so that we can exchange the order of integration and summation. This is done\n  with a straightforward application of the Weierstra\\ss\\ \\<open>M\\<close> test.\n\\<close>\nlemma uniform_limit_sophomores_dream1:\n  \"uniform_limit {0..(1::real)}\n      (\\<lambda>n x. \\<Sum>k<n. (x * ln x) ^ k / fact k)\n      (\\<lambda>x. \\<Sum>k. (x * ln x) ^ k / fact k)\n      sequentially\"\nproof (rule Weierstrass_m_test)\n  show \"summable (\\<lambda>k. exp (-1) ^ k / fact k :: real)\"\n    using summable_exp[of \"exp (-1)\"] by (simp add: field_simps)\nnext\n  fix k :: nat and x :: real\n  assume x: \"x \\<in> {0..1}\"\n  have \"norm ((x * ln x) ^ k / fact k) = norm (x * ln x) ^ k / fact k\"\n    by (simp add: power_abs)\n  also have \"\\<dots> \\<le> exp (-1) ^ k / fact k\"\n    by (intro divide_right_mono power_mono) (use x_log_x_within_01_le [of x] x in auto)\n  finally show \"norm ((x * ln x) ^ k / fact k) \\<le> exp (- 1) ^ k / fact k\" .\nqed\n\nlemma uniform_limit_sophomores_dream2:\n  \"uniform_limit {0..(1::real)}\n      (\\<lambda>n x. \\<Sum>k<n. (-(x * ln x)) ^ k / fact k)\n      (\\<lambda>x. \\<Sum>k. (-(x * ln x)) ^ k / fact k)\n      sequentially\"\nproof (rule Weierstrass_m_test)\n  show \"summable (\\<lambda>k. exp (-1) ^ k / fact k :: real)\"\n    using summable_exp[of \"exp (-1)\"] by (simp add: field_simps)\nnext\n  fix k :: nat and x :: real\n  assume x: \"x \\<in> {0..1}\"\n  have \"norm ((-x * ln x) ^ k / fact k) = norm (x * ln x) ^ k / fact k\"\n    by (simp add: power_abs)\n  also have \"\\<dots> \\<le> exp (-1) ^ k / fact k\"\n    by (intro divide_right_mono power_mono) (use x_log_x_within_01_le [of x] x in auto)\n  finally show \"norm ((-(x * ln x)) ^ k / fact k) \\<le> exp (- 1) ^ k / fact k\" by simp\nqed\n\n\nsubsection \\<open>An auxiliary integral\\<close>\n\ntext \\<open>\n  Next we compute the integral\n    \\[\\int_0^1 (x\\log x)^n\\,\\text{d}x = \\frac{(-1)^n\\, n!}{(n+1)^{n+1}}\\ ,\\]\n  which is a key ingredient in our proof.\n\\<close>\nlemma sophomores_dream_aux_integral:\n  \"((\\<lambda>x. (x * ln x) ^ n) has_integral (- 1) ^ n * fact n / real ((n + 1) ^ (n + 1))) {0<..<1}\"\nproof -\n  have \"((\\<lambda>t. t powr real n / exp t) has_integral fact n) {0..}\"\n    using Gamma_integral_real[of \"n + 1\"] by (auto simp: Gamma_fact powr_realpow)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>t. t powr real n / exp t) has_integral fact n) {0<..}\"\n  proof (rule has_integral_spike_set_eq)\n    have eq: \"{x \\<in> {0<..} - {0..}. x powr real n / exp x \\<noteq> 0} = {}\"\n      by auto\n    thus \"negligible {x \\<in> {0<..} - {0..}. x powr real n / exp x \\<noteq> 0}\"\n      by (subst eq) auto\n    have \"{x \\<in> {0..} - {0<..}. x powr real n / exp x \\<noteq> 0} \\<subseteq> {0}\"\n      by auto\n    moreover have \"negligible {0::real}\"\n      by simp\n    ultimately show \"negligible {x \\<in> {0..} - {0<..}. x powr real n / exp x \\<noteq> 0}\"\n      by (meson negligible_subset)\n  qed\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>t::real. t ^ n / exp t) has_integral fact n) {0<..}\"\n    by (intro has_integral_spike_eq) (auto simp: powr_realpow)\n  finally have 1: \"((\\<lambda>t::real. t ^ n / exp t) has_integral fact n) {0<..}\" .\n\n  have \"(\\<lambda>x::real. \\<bar>x\\<bar> ^ n / exp x) integrable_on {0<..} \\<longleftrightarrow>\n        (\\<lambda>x::real. x ^ n / exp x) integrable_on {0<..}\"\n    by (intro integrable_cong) auto\n  hence 2: \"(\\<lambda>t::real. t ^ n / exp t) absolutely_integrable_on {0<..}\"\n    using 1 by (simp add: absolutely_integrable_on_def power_abs has_integral_iff)\n\n  define g :: \"real \\<Rightarrow> real\" where \"g = (\\<lambda>x. -ln x * (n + 1))\"\n  define g' :: \"real \\<Rightarrow> real\" where \"g' = (\\<lambda>x. -(n + 1) / x)\"\n  define h :: \"real \\<Rightarrow> real\" where \"h = (\\<lambda>u. exp (-u / (n + 1)))\"\n  have bij: \"bij_betw g {0<..<1} {0<..}\"\n    by (rule bij_betwI[of _ _ _ h]) (auto simp: g_def h_def mult_neg_pos)\n  have deriv: \"(g has_real_derivative g' x) (at x within {0<..<1})\"\n    if \"x \\<in> {0<..<1}\" for x\n    unfolding g_def g'_def using that by (auto intro!: derivative_eq_intros simp: field_simps)\n\n  have \"(\\<lambda>t::real. t ^ n / exp t) absolutely_integrable_on g ` {0<..<1} \\<and>\n        integral (g ` {0<..<1}) (\\<lambda>t::real. t ^ n / exp t) = fact n\"\n    using 1 2 bij by (simp add: bij_betw_def has_integral_iff)\n  also have \"?this \\<longleftrightarrow> ((\\<lambda>x. \\<bar>g' x\\<bar> *\\<^sub>R (g x ^ n / exp (g x))) absolutely_integrable_on {0<..<1} \\<and>\n                       integral {0<..<1} (\\<lambda>x. \\<bar>g' x\\<bar> *\\<^sub>R (g x ^ n / exp (g x))) = fact n)\"\n    by (intro has_absolute_integral_change_of_variables_1' [symmetric] deriv)\n       (auto simp: inj_on_def g_def)\n  finally have \"((\\<lambda>x. \\<bar>g' x\\<bar> *\\<^sub>R (g x ^ n / exp (g x))) has_integral fact n) {0<..<1}\"\n    using eq_integralD set_lebesgue_integral_eq_integral(1) by blast\n  also have \"?this \\<longleftrightarrow>\n     ((\\<lambda>x::real. ((-1)^n*(n+1)^(n+1)) *\\<^sub>R (ln x ^ n * x ^ n)) has_integral fact n) {0<..<1}\"\n  proof (rule has_integral_cong)\n    fix x :: real assume x: \"x \\<in> {0<..<1}\"\n    have \"\\<bar>g' x\\<bar> *\\<^sub>R (g x ^ n / exp (g x)) =\n            (-1) ^ n * (real n + 1) ^ (n + 1) * ln x ^ n * (exp (ln x * (n + 1)) / x)\"\n      using x by (simp add: g_def g'_def exp_minus power_minus' divide_simps add_ac)\n    also have \"exp (ln x * (n + 1)) = x powr real (n + 1)\"\n      using x by (simp add: powr_def)\n    also have \"\\<dots> / x = x ^ n\"\n      using x by (subst powr_realpow) auto\n    finally show \"\\<bar>g' x\\<bar> *\\<^sub>R (g x ^ n / exp (g x)) =\n                    ((-1)^n*(n+1)^(n+1)) *\\<^sub>R (ln x ^ n * x ^ n)\"\n      by (simp add: algebra_simps)\n  qed\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x::real. ln x ^ n * x ^ n) has_integral\n                      fact n /\\<^sub>R real_of_int ((- 1) ^ n * int ((n + 1) ^ (n + 1)))) {0<..<1}\"\n    by (intro has_integral_cmul_iff') (auto simp del: power_Suc)\n  also have \"fact n /\\<^sub>R real_of_int ((- 1) ^ n * int ((n + 1) ^ (n + 1))) =\n             (-1) ^ n * fact n / (n+1) ^ (n+1)\"\n    by (auto simp: divide_simps)\n  finally show ?thesis\n    by (simp add: power_mult_distrib mult_ac)\nqed\n\nsubsection \\<open>Main proofs\\<close>\n\n\ntext \\<open>\n  We can now show the first formula: $\\int_0^1 x^{-x}\\,\\text{d}x = \\sum_{n=1}^\\infty n^{-n}$\n\\<close>\nlemma sophomores_dream_aux1:\n  \"summable (\\<lambda>k. 1 / real ((k+1)^(k+1)))\"\n  \"integral {0..1} (\\<lambda>x. x powr (-x)) = (\\<Sum>n. 1 / (n+1)^(n+1))\"\nproof -\n  define S where \"S = (\\<lambda>x::real. \\<Sum>k. (-(x * ln x)) ^ k / fact k)\"\n  have S_eq: \"S x = x powr (-x)\" if \"x > 0\" for x\n  proof -\n    have \"S x = exp (-x * ln x)\"\n      by (simp add: S_def exp_def field_simps)\n    also have \"\\<dots> = x powr (-x)\"\n      using \\<open>x > 0\\<close> by (simp add: powr_def)\n    finally show ?thesis .\n  qed\n\n  have cont: \"continuous_on {0..1} (\\<lambda>x::real. \\<Sum>k<n. (-(x * ln x)) ^ k / fact k)\" for n\n    by (intro continuous_on_sum continuous_on_divide x_log_x_continuous continuous_on_power\n              continuous_on_const continuous_on_minus) auto\n\n  obtain I J where IJ: \"\\<And>n. ((\\<lambda>x. \\<Sum>k<n. (-(x * ln x)) ^ k / fact k) has_integral I n) {0..1}\"\n                       \"(S has_integral J) {0..1}\" \"I \\<longlonglongrightarrow> J\"\n    using uniform_limit_integral [OF uniform_limit_sophomores_dream2 cont] by (auto simp: S_def)\n\n  note \\<open>(S has_integral J) {0..1}\\<close>\n  also have \"(S has_integral J) {0..1} \\<longleftrightarrow> (S has_integral J) {0<..<1}\"\n    by (simp add: has_integral_Icc_iff_Ioo)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. x powr (-x)) has_integral J) {0<..<1}\"\n    by (intro has_integral_cong) (use S_eq in auto)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. x powr (-x)) has_integral J) {0..1}\"\n    by (simp add: has_integral_Icc_iff_Ioo)\n  finally have integral: \"((\\<lambda>x. x powr (-x)) has_integral J) {0..1}\" .\n\n  have I_eq: \"I = (\\<lambda>n. \\<Sum>k<n. 1 / real ((k+1)^(k+1)))\"\n  proof\n    fix n :: nat\n    have \"((\\<lambda>x::real. \\<Sum>k<n. (-1)^k * ((x * ln x) ^ k / fact k)) has_integral\n            (\\<Sum>k<n. (-1)^k * ((-1)^k * fact k / real ((k + 1) ^ (k + 1)) / fact k))) {0<..<1}\"\n      by (intro has_integral_sum[OF _ has_integral_mult_right] has_integral_divide\n                sophomores_dream_aux_integral) auto\n    also have \"(\\<lambda>x::real. \\<Sum>k<n. (-1)^k * ((x * ln x) ^ k / fact k)) =\n               (\\<lambda>x::real. \\<Sum>k<n. (-(x * ln x)) ^ k / fact k)\"\n      by (simp add: power_minus')\n    also have \"(\\<Sum>k<n. (-1)^k * ((-1) ^ k * fact k / real ((k + 1) ^ (k + 1)) / fact k)) =\n               (\\<Sum>k<n. 1 / real ((k + 1) ^ (k + 1)))\"\n      by simp\n    also note has_integral_Icc_iff_Ioo [symmetric]\n    finally show \"I n = (\\<Sum>k<n. 1 / real ((k+1)^(k+1)))\"\n      by (rule has_integral_unique [OF IJ(1)[of n]])\n  qed\n  hence sums: \"(\\<lambda>k. 1 / real ((k + 1) ^ (k + 1))) sums J\"\n    using IJ(3) I_eq by (simp add: sums_def)\n  \n  from sums show \"summable (\\<lambda>k. 1 / real ((k+1)^(k+1)))\"\n    by (simp add: sums_iff)\n  from integral sums show \"integral {0..1} (\\<lambda>x. x powr (-x)) = (\\<Sum>n. 1 / (n+1)^(n+1))\"\n    by (simp add: sums_iff has_integral_iff)\nqed\n\ntheorem sophomores_dream1:\n  \"(\\<lambda>k::nat. norm (k powi (-k))) summable_on {1..}\"\n  \"integral {0..1} (\\<lambda>x. x powr (-x)) = (\\<Sum>\\<^sub>\\<infinity> k\\<in>{(1::nat)..}. k powi (-k))\"\nproof -\n  let ?I = \"integral {0..1} (\\<lambda>x. x powr (-x))\"\n  have \"(\\<lambda>k::nat. norm (k powi (-k))) summable_on UNIV\"\n    using abs_summable_sophomores_dream\n    by (intro norm_summable_imp_summable_on) (auto simp: power_int_minus field_simps)\n  thus \"(\\<lambda>k::nat. norm (k powi (-k))) summable_on {1..}\"\n    by (rule summable_on_subset_banach) auto\n\n  have \"(\\<lambda>n. 1 / (n+1)^(n+1)) sums ?I\"\n    using sophomores_dream_aux1 by (simp add: sums_iff)\n  moreover have \"summable (\\<lambda>n. norm (1 / real (Suc n ^ Suc n)))\"\n    by (subst summable_Suc_iff) (use abs_summable_sophomores_dream in \\<open>auto simp: field_simps\\<close>)\n  ultimately have \"((\\<lambda>n::nat. 1 / (n+1)^(n+1)) has_sum ?I) UNIV\"\n    by (intro norm_summable_imp_has_sum) auto\n  also have \"?this \\<longleftrightarrow> (((\\<lambda>n::nat. 1 / n^n) \\<circ> Suc) has_sum ?I) UNIV\"\n    by (simp add: o_def field_simps)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>n::nat. 1 / n^n) has_sum ?I) (Suc ` UNIV)\"\n    by (intro has_sum_reindex [symmetric]) auto\n  also have \"Suc ` UNIV = {1..}\"\n    using greaterThan_0 by auto\n  also have \"((\\<lambda>n::nat. (1 / real (n ^ n))) has_sum ?I) {1..} \\<longleftrightarrow>\n             ((\\<lambda>n::nat. n powi (-n)) has_sum ?I) {1..}\"\n    by (intro has_sum_cong) (auto simp: power_int_minus field_simps power_minus')\n  finally show \"integral {0..1} (\\<lambda>x. x powr (-x)) = (\\<Sum>\\<^sub>\\<infinity>k\\<in>{(1::nat)..}. k powi (-k))\"\n    by (auto dest!: infsumI simp: algebra_simps)\nqed\n\n\ntext \\<open>\n  Next, we show the second formula: $\\int_0^1 x^x\\,\\text{d}x = -\\sum_{n=1}^\\infty (-n)^{-n}$\n\\<close>\nlemma sophomores_dream_aux2:\n  \"summable (\\<lambda>k. (-1) ^ k / real ((k+1)^(k+1)))\"\n  \"integral {0..1} (\\<lambda>x. x powr x) = (\\<Sum>n. (-1)^n / (n+1)^(n+1))\"\nproof -\n  define S where \"S = (\\<lambda>x::real. \\<Sum>k. (x * ln x) ^ k / fact k)\"\n  have S_eq: \"S x = x powr x\" if \"x > 0\" for x\n  proof -\n    have \"S x = exp (x * ln x)\"\n      by (simp add: S_def exp_def field_simps)\n    also have \"\\<dots> = x powr x\"\n      using \\<open>x > 0\\<close> by (simp add: powr_def)\n    finally show ?thesis .\n  qed\n\n  have cont: \"continuous_on {0..1} (\\<lambda>x::real. \\<Sum>k<n. (x * ln x) ^ k / fact k)\" for n\n    by (intro continuous_on_sum continuous_on_divide x_log_x_continuous continuous_on_power\n              continuous_on_const) auto\n\n  obtain I J where IJ: \"\\<And>n. ((\\<lambda>x. \\<Sum>k<n. (x * ln x) ^ k / fact k) has_integral I n) {0..1}\"\n                       \"(S has_integral J) {0..1}\" \"I \\<longlonglongrightarrow> J\"\n    using uniform_limit_integral [OF uniform_limit_sophomores_dream1 cont] by (auto simp: S_def)\n\n  note \\<open>(S has_integral J) {0..1}\\<close>\n  also have \"(S has_integral J) {0..1} \\<longleftrightarrow> (S has_integral J) {0<..<1}\"\n    by (simp add: has_integral_Icc_iff_Ioo)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. x powr x) has_integral J) {0<..<1}\"\n    by (intro has_integral_cong) (use S_eq in auto)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>x. x powr x) has_integral J) {0..1}\"\n    by (simp add: has_integral_Icc_iff_Ioo)\n  finally have integral: \"((\\<lambda>x. x powr x) has_integral J) {0..1}\" .\n\n  have I_eq: \"I = (\\<lambda>n. \\<Sum>k<n. (-1) ^ k / real ((k+1)^(k+1)))\"\n  proof\n    fix n :: nat\n    have \"((\\<lambda>x::real. \\<Sum>k<n. (x * ln x) ^ k / fact k) has_integral\n            (\\<Sum>k<n. (-1) ^ k * fact k / real ((k + 1) ^ (k + 1)) / fact k)) {0<..<1}\"\n      by (intro has_integral_sum has_integral_divide sophomores_dream_aux_integral) auto\n    also have \"(\\<Sum>k<n. (- 1) ^ k * fact k / real ((k + 1) ^ (k + 1)) / fact k) =\n               (\\<Sum>k<n. (- 1) ^ k / real ((k + 1) ^ (k + 1)))\"\n      by simp\n    also note has_integral_Icc_iff_Ioo [symmetric]\n    finally show \"I n = (\\<Sum>k<n. (-1) ^ k / real ((k+1)^(k+1)))\"\n      by (rule has_integral_unique [OF IJ(1)[of n]])\n  qed\n  hence sums: \"(\\<lambda>k. (-1) ^ k / real ((k + 1) ^ (k + 1))) sums J\"\n    using IJ(3) I_eq by (simp add: sums_def)\n  \n  from sums show \"summable (\\<lambda>k. (-1) ^ k / real ((k+1)^(k+1)))\"\n    by (simp add: sums_iff)\n  from integral sums show \"integral {0..1} (\\<lambda>x. x powr x) = (\\<Sum>n. (-1)^n / (n+1)^(n+1))\"\n    by (simp add: sums_iff has_integral_iff)\nqed\n\ntheorem sophomores_dream2:\n  \"(\\<lambda>k::nat. norm ((-k) powi (-k))) summable_on {1..}\"\n  \"integral {0..1} (\\<lambda>x. x powr x) = -(\\<Sum>\\<^sub>\\<infinity> k\\<in>{(1::nat)..}. (-k) powi (-k))\"\nproof -\n  let ?I = \"integral {0..1} (\\<lambda>x. x powr x)\"\n  have \"(\\<lambda>k::nat. norm ((-k) powi (-k))) summable_on UNIV\"\n    using abs_summable_sophomores_dream\n    by (intro norm_summable_imp_summable_on) (auto simp: power_int_minus field_simps)\n  thus \"(\\<lambda>k::nat. norm ((-k) powi (-k))) summable_on {1..}\"\n    by (rule summable_on_subset_banach) auto\n\n  have \"(\\<lambda>n. (-1)^n / (n+1)^(n+1)) sums ?I\"\n    using sophomores_dream_aux2 by (simp add: sums_iff)\n  moreover have \"summable (\\<lambda>n. 1 / real (Suc n ^ Suc n))\"\n    by (subst summable_Suc_iff) (use abs_summable_sophomores_dream in \\<open>auto simp: field_simps\\<close>)\n  hence \"summable (\\<lambda>n. norm ((- 1) ^ n / real (Suc n ^ Suc n)))\"\n    by simp\n  ultimately have \"((\\<lambda>n::nat. (-1)^n / (n+1)^(n+1)) has_sum ?I) UNIV\"\n    by (intro norm_summable_imp_has_sum) auto\n  also have \"?this \\<longleftrightarrow> (((\\<lambda>n::nat. -((-1)^n / n^n)) \\<circ> Suc) has_sum ?I) UNIV\"\n    by (simp add: o_def field_simps)\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>n::nat. -((-1)^n / n ^ n)) has_sum ?I) (Suc ` UNIV)\"\n    by (intro has_sum_reindex [symmetric]) auto\n  also have \"Suc ` UNIV = {1..}\"\n    using greaterThan_0 by auto\n  also have \"((\\<lambda>n::nat. -((- 1) ^ n / real (n ^ n))) has_sum ?I) {1..} \\<longleftrightarrow>\n             ((\\<lambda>n::nat. -((-n) powi (-n))) has_sum ?I) {1..}\"\n    by (intro has_sum_cong) (auto simp: power_int_minus field_simps power_minus')\n  also have \"\\<dots> \\<longleftrightarrow> ((\\<lambda>n::nat. (-n) powi (-n)) has_sum (-?I)) {1..}\"\n    by (simp add: has_sum_uminus)\n  finally show \"integral {0..1} (\\<lambda>x. x powr x) = -(\\<Sum>\\<^sub>\\<infinity>k\\<in>{(1::nat)..}. (-k) powi (-k))\"\n    by (auto dest!: infsumI simp: algebra_simps)\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Sophomores_Dream/Sophomores_Dream.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8962513752119936, "lm_q1q2_score": 0.7526127233384683}}
{"text": "(*  Title:      HOL/Complete_Partial_Order.thy\n    Author:     Brian Huffman, Portland State University\n    Author:     Alexander Krauss, TU Muenchen\n*)\n\nsection \\<open>Chain-complete partial orders and their fixpoints\\<close>\n\ntheory Complete_Partial_Order\n  imports Product_Type\nbegin\n\nsubsection \\<open>Monotone functions\\<close>\n\ntext \\<open>Dictionary-passing version of \\<^const>\\<open>Orderings.mono\\<close>.\\<close>\n\ndefinition monotone :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('b \\<Rightarrow> 'b \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> 'b) \\<Rightarrow> bool\"\n  where \"monotone orda ordb f \\<longleftrightarrow> (\\<forall>x y. orda x y \\<longrightarrow> ordb (f x) (f y))\"\n\nlemma monotoneI[intro?]: \"(\\<And>x y. orda x y \\<Longrightarrow> ordb (f x) (f y)) \\<Longrightarrow> monotone orda ordb f\"\n  unfolding monotone_def by iprover\n\nlemma monotoneD[dest?]: \"monotone orda ordb f \\<Longrightarrow> orda x y \\<Longrightarrow> ordb (f x) (f y)\"\n  unfolding monotone_def by iprover\n\n\nsubsection \\<open>Chains\\<close>\n\ntext \\<open>\n  A chain is a totally-ordered set. Chains are parameterized over\n  the order for maximal flexibility, since type classes are not enough.\n\\<close>\n\ndefinition chain :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a set \\<Rightarrow> bool\"\n  where \"chain ord S \\<longleftrightarrow> (\\<forall>x\\<in>S. \\<forall>y\\<in>S. ord x y \\<or> ord y x)\"\n\nlemma chainI:\n  assumes \"\\<And>x y. x \\<in> S \\<Longrightarrow> y \\<in> S \\<Longrightarrow> ord x y \\<or> ord y x\"\n  shows \"chain ord S\"\n  using assms unfolding chain_def by fast\n\nlemma chainD:\n  assumes \"chain ord S\" and \"x \\<in> S\" and \"y \\<in> S\"\n  shows \"ord x y \\<or> ord y x\"\n  using assms unfolding chain_def by fast\n\nlemma chainE:\n  assumes \"chain ord S\" and \"x \\<in> S\" and \"y \\<in> S\"\n  obtains \"ord x y\" | \"ord y x\"\n  using assms unfolding chain_def by fast\n\nlemma chain_empty: \"chain ord {}\"\n  by (simp add: chain_def)\n\nlemma chain_equality: \"chain (=) A \\<longleftrightarrow> (\\<forall>x\\<in>A. \\<forall>y\\<in>A. x = y)\"\n  by (auto simp add: chain_def)\n\nlemma chain_subset: \"chain ord A \\<Longrightarrow> B \\<subseteq> A \\<Longrightarrow> chain ord B\"\n  by (rule chainI) (blast dest: chainD)\n\nlemma chain_imageI:\n  assumes chain: \"chain le_a Y\"\n    and mono: \"\\<And>x y. x \\<in> Y \\<Longrightarrow> y \\<in> Y \\<Longrightarrow> le_a x y \\<Longrightarrow> le_b (f x) (f y)\"\n  shows \"chain le_b (f ` Y)\"\n  by (blast intro: chainI dest: chainD[OF chain] mono)\n\n\nsubsection \\<open>Chain-complete partial orders\\<close>\n\ntext \\<open>\n  A \\<open>ccpo\\<close> has a least upper bound for any chain.  In particular, the\n  empty set is a chain, so every \\<open>ccpo\\<close> must have a bottom element.\n\\<close>\n\nclass ccpo = order + Sup +\n  assumes ccpo_Sup_upper: \"chain (\\<le>) A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> x \\<le> Sup A\"\n  assumes ccpo_Sup_least: \"chain (\\<le>) A \\<Longrightarrow> (\\<And>x. x \\<in> A \\<Longrightarrow> x \\<le> z) \\<Longrightarrow> Sup A \\<le> z\"\nbegin\n\nlemma chain_singleton: \"Complete_Partial_Order.chain (\\<le>) {x}\"\n  by (rule chainI) simp\n\nlemma ccpo_Sup_singleton [simp]: \"\\<Squnion>{x} = x\"\n  by (rule antisym) (auto intro: ccpo_Sup_least ccpo_Sup_upper simp add: chain_singleton)\n\n\nsubsection \\<open>Transfinite iteration of a function\\<close>\n\ncontext notes [[inductive_internals]]\nbegin\n\ninductive_set iterates :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a set\"\n  for f :: \"'a \\<Rightarrow> 'a\"\n  where\n    step: \"x \\<in> iterates f \\<Longrightarrow> f x \\<in> iterates f\"\n  | Sup: \"chain (\\<le>) M \\<Longrightarrow> \\<forall>x\\<in>M. x \\<in> iterates f \\<Longrightarrow> Sup M \\<in> iterates f\"\n\nend\n\nlemma iterates_le_f: \"x \\<in> iterates f \\<Longrightarrow> monotone (\\<le>) (\\<le>) f \\<Longrightarrow> x \\<le> f x\"\n  by (induct x rule: iterates.induct)\n    (force dest: monotoneD intro!: ccpo_Sup_upper ccpo_Sup_least)+\n\nlemma chain_iterates:\n  assumes f: \"monotone (\\<le>) (\\<le>) f\"\n  shows \"chain (\\<le>) (iterates f)\" (is \"chain _ ?C\")\nproof (rule chainI)\n  fix x y\n  assume \"x \\<in> ?C\" \"y \\<in> ?C\"\n  then show \"x \\<le> y \\<or> y \\<le> x\"\n  proof (induct x arbitrary: y rule: iterates.induct)\n    fix x y\n    assume y: \"y \\<in> ?C\"\n      and IH: \"\\<And>z. z \\<in> ?C \\<Longrightarrow> x \\<le> z \\<or> z \\<le> x\"\n    from y show \"f x \\<le> y \\<or> y \\<le> f x\"\n    proof (induct y rule: iterates.induct)\n      case (step y)\n      with IH f show ?case by (auto dest: monotoneD)\n    next\n      case (Sup M)\n      then have chM: \"chain (\\<le>) M\"\n        and IH': \"\\<And>z. z \\<in> M \\<Longrightarrow> f x \\<le> z \\<or> z \\<le> f x\" by auto\n      show \"f x \\<le> Sup M \\<or> Sup M \\<le> f x\"\n      proof (cases \"\\<exists>z\\<in>M. f x \\<le> z\")\n        case True\n        then have \"f x \\<le> Sup M\"\n          apply rule\n          apply (erule order_trans)\n          apply (rule ccpo_Sup_upper[OF chM])\n          apply assumption\n          done\n        then show ?thesis ..\n      next\n        case False\n        with IH' show ?thesis\n          by (auto intro: ccpo_Sup_least[OF chM])\n      qed\n    qed\n  next\n    case (Sup M y)\n    show ?case\n    proof (cases \"\\<exists>x\\<in>M. y \\<le> x\")\n      case True\n      then have \"y \\<le> Sup M\"\n        apply rule\n        apply (erule order_trans)\n        apply (rule ccpo_Sup_upper[OF Sup(1)])\n        apply assumption\n        done\n      then show ?thesis ..\n    next\n      case False with Sup\n      show ?thesis by (auto intro: ccpo_Sup_least)\n    qed\n  qed\nqed\n\nlemma bot_in_iterates: \"Sup {} \\<in> iterates f\"\n  by (auto intro: iterates.Sup simp add: chain_empty)\n\n\nsubsection \\<open>Fixpoint combinator\\<close>\n\ndefinition fixp :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a\"\n  where \"fixp f = Sup (iterates f)\"\n\nlemma iterates_fixp:\n  assumes f: \"monotone (\\<le>) (\\<le>) f\"\n  shows \"fixp f \\<in> iterates f\"\n  unfolding fixp_def\n  by (simp add: iterates.Sup chain_iterates f)\n\nlemma fixp_unfold:\n  assumes f: \"monotone (\\<le>) (\\<le>) f\"\n  shows \"fixp f = f (fixp f)\"\nproof (rule antisym)\n  show \"fixp f \\<le> f (fixp f)\"\n    by (intro iterates_le_f iterates_fixp f)\n  have \"f (fixp f) \\<le> Sup (iterates f)\"\n    by (intro ccpo_Sup_upper chain_iterates f iterates.step iterates_fixp)\n  then show \"f (fixp f) \\<le> fixp f\"\n    by (simp only: fixp_def)\nqed\n\nlemma fixp_lowerbound:\n  assumes f: \"monotone (\\<le>) (\\<le>) f\"\n    and z: \"f z \\<le> z\"\n  shows \"fixp f \\<le> z\"\n  unfolding fixp_def\nproof (rule ccpo_Sup_least[OF chain_iterates[OF f]])\n  fix x\n  assume \"x \\<in> iterates f\"\n  then show \"x \\<le> z\"\n  proof (induct x rule: iterates.induct)\n    case (step x)\n    from f \\<open>x \\<le> z\\<close> have \"f x \\<le> f z\" by (rule monotoneD)\n    also note z\n    finally show \"f x \\<le> z\" .\n  next\n    case (Sup M)\n    then show ?case\n      by (auto intro: ccpo_Sup_least)\n  qed\nqed\n\nend\n\n\nsubsection \\<open>Fixpoint induction\\<close>\n\nsetup \\<open>Sign.map_naming (Name_Space.mandatory_path \"ccpo\")\\<close>\n\ndefinition admissible :: \"('a set \\<Rightarrow> 'a) \\<Rightarrow> ('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> ('a \\<Rightarrow> bool) \\<Rightarrow> bool\"\n  where \"admissible lub ord P \\<longleftrightarrow> (\\<forall>A. chain ord A \\<longrightarrow> A \\<noteq> {} \\<longrightarrow> (\\<forall>x\\<in>A. P x) \\<longrightarrow> P (lub A))\"\n\nlemma admissibleI:\n  assumes \"\\<And>A. chain ord A \\<Longrightarrow> A \\<noteq> {} \\<Longrightarrow> \\<forall>x\\<in>A. P x \\<Longrightarrow> P (lub A)\"\n  shows \"ccpo.admissible lub ord P\"\n  using assms unfolding ccpo.admissible_def by fast\n\nlemma admissibleD:\n  assumes \"ccpo.admissible lub ord P\"\n  assumes \"chain ord A\"\n  assumes \"A \\<noteq> {}\"\n  assumes \"\\<And>x. x \\<in> A \\<Longrightarrow> P x\"\n  shows \"P (lub A)\"\n  using assms by (auto simp: ccpo.admissible_def)\n\nsetup \\<open>Sign.map_naming Name_Space.parent_path\\<close>\n\nlemma (in ccpo) fixp_induct:\n  assumes adm: \"ccpo.admissible Sup (\\<le>) P\"\n  assumes mono: \"monotone (\\<le>) (\\<le>) f\"\n  assumes bot: \"P (Sup {})\"\n  assumes step: \"\\<And>x. P x \\<Longrightarrow> P (f x)\"\n  shows \"P (fixp f)\"\n  unfolding fixp_def\n  using adm chain_iterates[OF mono]\nproof (rule ccpo.admissibleD)\n  show \"iterates f \\<noteq> {}\"\n    using bot_in_iterates by auto\nnext\n  fix x\n  assume \"x \\<in> iterates f\"\n  then show \"P x\"\n  proof (induct rule: iterates.induct)\n    case prems: (step x)\n    from this(2) show ?case by (rule step)\n  next\n    case (Sup M)\n    then show ?case by (cases \"M = {}\") (auto intro: step bot ccpo.admissibleD adm)\n  qed\nqed\n\nlemma admissible_True: \"ccpo.admissible lub ord (\\<lambda>x. True)\"\n  unfolding ccpo.admissible_def by simp\n\n(*lemma admissible_False: \"\\<not> ccpo.admissible lub ord (\\<lambda>x. False)\"\nunfolding ccpo.admissible_def chain_def by simp\n*)\nlemma admissible_const: \"ccpo.admissible lub ord (\\<lambda>x. t)\"\n  by (auto intro: ccpo.admissibleI)\n\nlemma admissible_conj:\n  assumes \"ccpo.admissible lub ord (\\<lambda>x. P x)\"\n  assumes \"ccpo.admissible lub ord (\\<lambda>x. Q x)\"\n  shows \"ccpo.admissible lub ord (\\<lambda>x. P x \\<and> Q x)\"\n  using assms unfolding ccpo.admissible_def by simp\n\nlemma admissible_all:\n  assumes \"\\<And>y. ccpo.admissible lub ord (\\<lambda>x. P x y)\"\n  shows \"ccpo.admissible lub ord (\\<lambda>x. \\<forall>y. P x y)\"\n  using assms unfolding ccpo.admissible_def by fast\n\nlemma admissible_ball:\n  assumes \"\\<And>y. y \\<in> A \\<Longrightarrow> ccpo.admissible lub ord (\\<lambda>x. P x y)\"\n  shows \"ccpo.admissible lub ord (\\<lambda>x. \\<forall>y\\<in>A. P x y)\"\n  using assms unfolding ccpo.admissible_def by fast\n\nlemma chain_compr: \"chain ord A \\<Longrightarrow> chain ord {x \\<in> A. P x}\"\n  unfolding chain_def by fast\n\ncontext ccpo\nbegin\n\nlemma admissible_disj:\n  fixes P Q :: \"'a \\<Rightarrow> bool\"\n  assumes P: \"ccpo.admissible Sup (\\<le>) (\\<lambda>x. P x)\"\n  assumes Q: \"ccpo.admissible Sup (\\<le>) (\\<lambda>x. Q x)\"\n  shows \"ccpo.admissible Sup (\\<le>) (\\<lambda>x. P x \\<or> Q x)\"\nproof (rule ccpo.admissibleI)\n  fix A :: \"'a set\"\n  assume chain: \"chain (\\<le>) A\"\n  assume A: \"A \\<noteq> {}\" and P_Q: \"\\<forall>x\\<in>A. P x \\<or> Q x\"\n  have \"(\\<exists>x\\<in>A. P x) \\<and> (\\<forall>x\\<in>A. \\<exists>y\\<in>A. x \\<le> y \\<and> P y) \\<or> (\\<exists>x\\<in>A. Q x) \\<and> (\\<forall>x\\<in>A. \\<exists>y\\<in>A. x \\<le> y \\<and> Q y)\"\n    (is \"?P \\<or> ?Q\" is \"?P1 \\<and> ?P2 \\<or> _\")\n  proof (rule disjCI)\n    assume \"\\<not> ?Q\"\n    then consider \"\\<forall>x\\<in>A. \\<not> Q x\" | a where \"a \\<in> A\" \"\\<forall>y\\<in>A. a \\<le> y \\<longrightarrow> \\<not> Q y\"\n      by blast\n    then show ?P\n    proof cases\n      case 1\n      with P_Q have \"\\<forall>x\\<in>A. P x\" by blast\n      with A show ?P by blast\n    next\n      case 2\n      note a = \\<open>a \\<in> A\\<close>\n      show ?P\n      proof\n        from P_Q 2 have *: \"\\<forall>y\\<in>A. a \\<le> y \\<longrightarrow> P y\" by blast\n        with a have \"P a\" by blast\n        with a show ?P1 by blast\n        show ?P2\n        proof\n          fix x\n          assume x: \"x \\<in> A\"\n          with chain a show \"\\<exists>y\\<in>A. x \\<le> y \\<and> P y\"\n          proof (rule chainE)\n            assume le: \"a \\<le> x\"\n            with * a x have \"P x\" by blast\n            with x le show ?thesis by blast\n          next\n            assume \"a \\<ge> x\"\n            with a \\<open>P a\\<close> show ?thesis by blast\n          qed\n        qed\n      qed\n    qed\n  qed\n  moreover\n  have \"Sup A = Sup {x \\<in> A. P x}\" if \"\\<forall>x\\<in>A. \\<exists>y\\<in>A. x \\<le> y \\<and> P y\" for P\n  proof (rule antisym)\n    have chain_P: \"chain (\\<le>) {x \\<in> A. P x}\"\n      by (rule chain_compr [OF chain])\n    show \"Sup A \\<le> Sup {x \\<in> A. P x}\"\n      apply (rule ccpo_Sup_least [OF chain])\n      apply (drule that [rule_format])\n      apply clarify\n      apply (erule order_trans)\n      apply (simp add: ccpo_Sup_upper [OF chain_P])\n      done\n    show \"Sup {x \\<in> A. P x} \\<le> Sup A\"\n      apply (rule ccpo_Sup_least [OF chain_P])\n      apply clarify\n      apply (simp add: ccpo_Sup_upper [OF chain])\n      done\n  qed\n  ultimately\n  consider \"\\<exists>x. x \\<in> A \\<and> P x\" \"Sup A = Sup {x \\<in> A. P x}\"\n    | \"\\<exists>x. x \\<in> A \\<and> Q x\" \"Sup A = Sup {x \\<in> A. Q x}\"\n    by blast\n  then show \"P (Sup A) \\<or> Q (Sup A)\"\n    apply cases\n     apply simp_all\n     apply (rule disjI1)\n     apply (rule ccpo.admissibleD [OF P chain_compr [OF chain]]; simp)\n    apply (rule disjI2)\n    apply (rule ccpo.admissibleD [OF Q chain_compr [OF chain]]; simp)\n    done\nqed\n\nend\n\ninstance complete_lattice \\<subseteq> ccpo\n  by standard (fast intro: Sup_upper Sup_least)+\n\nlemma lfp_eq_fixp:\n  assumes mono: \"mono f\"\n  shows \"lfp f = fixp f\"\nproof (rule antisym)\n  from mono have f': \"monotone (\\<le>) (\\<le>) f\"\n    unfolding mono_def monotone_def .\n  show \"lfp f \\<le> fixp f\"\n    by (rule lfp_lowerbound, subst fixp_unfold [OF f'], rule order_refl)\n  show \"fixp f \\<le> lfp f\"\n    by (rule fixp_lowerbound [OF f']) (simp add: lfp_fixpoint [OF mono])\nqed\n\nhide_const (open) iterates fixp\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Complete_Partial_Order.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8397339676722394, "lm_q1q2_score": 0.7526127215931876}}
{"text": "(*  Title:      HOL/Library/Countable_Set.thy\n    Author:     Johannes Hölzl\n    Author:     Andrei Popescu\n*)\n\nsection \\<open>Countable sets\\<close>\n\ntheory Countable_Set\nimports Countable Infinite_Set\nbegin\n\nsubsection \\<open>Predicate for countable sets\\<close>\n\ndefinition countable :: \"'a set \\<Rightarrow> bool\" where\n  \"countable S \\<longleftrightarrow> (\\<exists>f::'a \\<Rightarrow> nat. inj_on f S)\"\n\nlemma countableE:\n  assumes S: \"countable S\" obtains f :: \"'a \\<Rightarrow> nat\" where \"inj_on f S\"\n  using S by (auto simp: countable_def)\n\nlemma countableI: \"inj_on (f::'a \\<Rightarrow> nat) S \\<Longrightarrow> countable S\"\n  by (auto simp: countable_def)\n\nlemma countableI': \"inj_on (f::'a \\<Rightarrow> 'b::countable) S \\<Longrightarrow> countable S\"\n  using comp_inj_on[of f S to_nat] by (auto intro: countableI)\n\nlemma countableE_bij:\n  assumes S: \"countable S\" obtains f :: \"nat \\<Rightarrow> 'a\" and C :: \"nat set\" where \"bij_betw f C S\"\n  using S by (blast elim: countableE dest: inj_on_imp_bij_betw bij_betw_inv)\n\nlemma countableI_bij: \"bij_betw f (C::nat set) S \\<Longrightarrow> countable S\"\n  by (blast intro: countableI bij_betw_inv_into bij_betw_imp_inj_on)\n\nlemma countable_finite: \"finite S \\<Longrightarrow> countable S\"\n  by (blast dest: finite_imp_inj_to_nat_seg countableI)\n\nlemma countableI_bij1: \"bij_betw f A B \\<Longrightarrow> countable A \\<Longrightarrow> countable B\"\n  by (blast elim: countableE_bij intro: bij_betw_trans countableI_bij)\n\nlemma countableI_bij2: \"bij_betw f B A \\<Longrightarrow> countable A \\<Longrightarrow> countable B\"\n  by (blast elim: countableE_bij intro: bij_betw_trans bij_betw_inv_into countableI_bij)\n\nlemma countable_iff_bij[simp]: \"bij_betw f A B \\<Longrightarrow> countable A \\<longleftrightarrow> countable B\"\n  by (blast intro: countableI_bij1 countableI_bij2)\n\nlemma countable_subset: \"A \\<subseteq> B \\<Longrightarrow> countable B \\<Longrightarrow> countable A\"\n  by (auto simp: countable_def intro: subset_inj_on)\n\nlemma countableI_type[intro, simp]: \"countable (A:: 'a :: countable set)\"\n  using countableI[of to_nat A] by auto\n\nsubsection \\<open>Enumerate a countable set\\<close>\n\nlemma countableE_infinite:\n  assumes \"countable S\" \"infinite S\"\n  obtains e :: \"'a \\<Rightarrow> nat\" where \"bij_betw e S UNIV\"\nproof -\n  obtain f :: \"'a \\<Rightarrow> nat\" where \"inj_on f S\"\n    using \\<open>countable S\\<close> by (rule countableE)\n  then have \"bij_betw f S (f`S)\"\n    unfolding bij_betw_def by simp\n  moreover\n  from \\<open>inj_on f S\\<close> \\<open>infinite S\\<close> have inf_fS: \"infinite (f`S)\"\n    by (auto dest: finite_imageD)\n  then have \"bij_betw (the_inv_into UNIV (enumerate (f`S))) (f`S) UNIV\"\n    by (intro bij_betw_the_inv_into bij_enumerate)\n  ultimately have \"bij_betw (the_inv_into UNIV (enumerate (f`S)) \\<circ> f) S UNIV\"\n    by (rule bij_betw_trans)\n  then show thesis ..\nqed\n\nlemma countable_infiniteE':\n  assumes \"countable A\" \"infinite A\"\n  obtains g where \"bij_betw g (UNIV :: nat set) A\"\n  by (meson assms bij_betw_inv countableE_infinite)\n\nlemma countable_enum_cases:\n  assumes \"countable S\"\n  obtains (finite) f :: \"'a \\<Rightarrow> nat\" where \"finite S\" \"bij_betw f S {..<card S}\"\n        | (infinite) f :: \"'a \\<Rightarrow> nat\" where \"infinite S\" \"bij_betw f S UNIV\"\n  using ex_bij_betw_finite_nat[of S] countableE_infinite \\<open>countable S\\<close>\n  by (cases \"finite S\") (auto simp add: atLeast0LessThan)\n\ndefinition to_nat_on :: \"'a set \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"to_nat_on S = (SOME f. if finite S then bij_betw f S {..< card S} else bij_betw f S UNIV)\"\n\ndefinition from_nat_into :: \"'a set \\<Rightarrow> nat \\<Rightarrow> 'a\" where\n  \"from_nat_into S n = (if n \\<in> to_nat_on S ` S then inv_into S (to_nat_on S) n else SOME s. s\\<in>S)\"\n\nlemma to_nat_on_finite: \"finite S \\<Longrightarrow> bij_betw (to_nat_on S) S {..< card S}\"\n  using ex_bij_betw_finite_nat unfolding to_nat_on_def\n  by (intro someI2_ex[where Q=\"\\<lambda>f. bij_betw f S {..<card S}\"]) (auto simp add: atLeast0LessThan)\n\nlemma to_nat_on_infinite: \"countable S \\<Longrightarrow> infinite S \\<Longrightarrow> bij_betw (to_nat_on S) S UNIV\"\n  using countableE_infinite unfolding to_nat_on_def\n  by (intro someI2_ex[where Q=\"\\<lambda>f. bij_betw f S UNIV\"]) auto\n\nlemma bij_betw_from_nat_into_finite: \"finite S \\<Longrightarrow> bij_betw (from_nat_into S) {..< card S} S\"\n  unfolding from_nat_into_def[abs_def]\n  using to_nat_on_finite[of S]\n  apply (subst bij_betw_cong)\n  apply (split if_split)\n  apply (simp add: bij_betw_def)\n  apply (auto cong: bij_betw_cong\n              intro: bij_betw_inv_into to_nat_on_finite)\n  done\n\nlemma bij_betw_from_nat_into: \"countable S \\<Longrightarrow> infinite S \\<Longrightarrow> bij_betw (from_nat_into S) UNIV S\"\n  unfolding from_nat_into_def[abs_def]\n  using to_nat_on_infinite[of S, unfolded bij_betw_def]\n  by (auto cong: bij_betw_cong intro: bij_betw_inv_into to_nat_on_infinite)\n\ntext \\<open>\n  The sum/product over the enumeration of a finite set equals simply the sum/product over the set\n\\<close>\ncontext comm_monoid_set\nbegin\n\nlemma card_from_nat_into:\n  \"F (\\<lambda>i. h (from_nat_into A i)) {..<card A} = F h A\"\nproof (cases \"finite A\")\n  case True\n  have \"F (\\<lambda>i. h (from_nat_into A i)) {..<card A} = F h (from_nat_into A ` {..<card A})\"\n    by (metis True bij_betw_def bij_betw_from_nat_into_finite reindex_cong)\n  also have \"... = F h A\"\n    by (metis True bij_betw_def bij_betw_from_nat_into_finite)\n  finally show ?thesis .\nqed auto\n\nend\n\nlemma countable_as_injective_image:\n  assumes \"countable A\" \"infinite A\"\n  obtains f :: \"nat \\<Rightarrow> 'a\" where \"A = range f\" \"inj f\"\nby (metis bij_betw_def bij_betw_from_nat_into [OF assms])\n\nlemma inj_on_to_nat_on[intro]: \"countable A \\<Longrightarrow> inj_on (to_nat_on A) A\"\n  using to_nat_on_infinite[of A] to_nat_on_finite[of A]\n  by (cases \"finite A\") (auto simp: bij_betw_def)\n\nlemma to_nat_on_inj[simp]:\n  \"countable A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> b \\<in> A \\<Longrightarrow> to_nat_on A a = to_nat_on A b \\<longleftrightarrow> a = b\"\n  using inj_on_to_nat_on[of A] by (auto dest: inj_onD)\n\nlemma from_nat_into_to_nat_on[simp]: \"countable A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> from_nat_into A (to_nat_on A a) = a\"\n  by (auto simp: from_nat_into_def intro!: inv_into_f_f)\n\nlemma subset_range_from_nat_into: \"countable A \\<Longrightarrow> A \\<subseteq> range (from_nat_into A)\"\n  by (auto intro: from_nat_into_to_nat_on[symmetric])\n\nlemma from_nat_into: \"A \\<noteq> {} \\<Longrightarrow> from_nat_into A n \\<in> A\"\n  unfolding from_nat_into_def by (metis equals0I inv_into_into someI_ex)\n\nlemma range_from_nat_into_subset: \"A \\<noteq> {} \\<Longrightarrow> range (from_nat_into A) \\<subseteq> A\"\n  using from_nat_into[of A] by auto\n\nlemma range_from_nat_into[simp]: \"A \\<noteq> {} \\<Longrightarrow> countable A \\<Longrightarrow> range (from_nat_into A) = A\"\n  by (metis equalityI range_from_nat_into_subset subset_range_from_nat_into)\n\nlemma image_to_nat_on: \"countable A \\<Longrightarrow> infinite A \\<Longrightarrow> to_nat_on A ` A = UNIV\"\n  using to_nat_on_infinite[of A] by (simp add: bij_betw_def)\n\nlemma to_nat_on_surj: \"countable A \\<Longrightarrow> infinite A \\<Longrightarrow> \\<exists>a\\<in>A. to_nat_on A a = n\"\n  by (metis (no_types) image_iff iso_tuple_UNIV_I image_to_nat_on)\n\nlemma to_nat_on_from_nat_into[simp]: \"n \\<in> to_nat_on A ` A \\<Longrightarrow> to_nat_on A (from_nat_into A n) = n\"\n  by (simp add: f_inv_into_f from_nat_into_def)\n\nlemma to_nat_on_from_nat_into_infinite[simp]:\n  \"countable A \\<Longrightarrow> infinite A \\<Longrightarrow> to_nat_on A (from_nat_into A n) = n\"\n  by (metis image_iff to_nat_on_surj to_nat_on_from_nat_into)\n\nlemma from_nat_into_inj:\n  \"countable A \\<Longrightarrow> m \\<in> to_nat_on A ` A \\<Longrightarrow> n \\<in> to_nat_on A ` A \\<Longrightarrow>\n    from_nat_into A m = from_nat_into A n \\<longleftrightarrow> m = n\"\n  by (subst to_nat_on_inj[symmetric, of A]) auto\n\nlemma from_nat_into_inj_infinite[simp]:\n  \"countable A \\<Longrightarrow> infinite A \\<Longrightarrow> from_nat_into A m = from_nat_into A n \\<longleftrightarrow> m = n\"\n  using image_to_nat_on[of A] from_nat_into_inj[of A m n] by simp\n\nlemma eq_from_nat_into_iff:\n  \"countable A \\<Longrightarrow> x \\<in> A \\<Longrightarrow> i \\<in> to_nat_on A ` A \\<Longrightarrow> x = from_nat_into A i \\<longleftrightarrow> i = to_nat_on A x\"\n  by auto\n\nlemma from_nat_into_surj: \"countable A \\<Longrightarrow> a \\<in> A \\<Longrightarrow> \\<exists>n. from_nat_into A n = a\"\n  by (rule exI[of _ \"to_nat_on A a\"]) simp\n\nlemma from_nat_into_inject[simp]:\n  \"A \\<noteq> {} \\<Longrightarrow> countable A \\<Longrightarrow> B \\<noteq> {} \\<Longrightarrow> countable B \\<Longrightarrow> from_nat_into A = from_nat_into B \\<longleftrightarrow> A = B\"\n  by (metis range_from_nat_into)\n\nlemma inj_on_from_nat_into: \"inj_on from_nat_into ({A. A \\<noteq> {} \\<and> countable A})\"\n  unfolding inj_on_def by auto\n\nsubsection \\<open>Closure properties of countability\\<close>\n\nlemma countable_SIGMA[intro, simp]:\n  \"countable I \\<Longrightarrow> (\\<And>i. i \\<in> I \\<Longrightarrow> countable (A i)) \\<Longrightarrow> countable (SIGMA i : I. A i)\"\n  by (intro countableI'[of \"\\<lambda>(i, a). (to_nat_on I i, to_nat_on (A i) a)\"]) (auto simp: inj_on_def)\n\nlemma countable_image[intro, simp]:\n  assumes \"countable A\"\n  shows \"countable (f`A)\"\nproof -\n  obtain g :: \"'a \\<Rightarrow> nat\" where \"inj_on g A\"\n    using assms by (rule countableE)\n  moreover have \"inj_on (inv_into A f) (f`A)\" \"inv_into A f ` f ` A \\<subseteq> A\"\n    by (auto intro: inj_on_inv_into inv_into_into)\n  ultimately show ?thesis\n    by (blast dest: comp_inj_on subset_inj_on intro: countableI)\nqed\n\nlemma countable_image_inj_on: \"countable (f ` A) \\<Longrightarrow> inj_on f A \\<Longrightarrow> countable A\"\n  by (metis countable_image the_inv_into_onto)\n\nlemma countable_image_inj_Int_vimage:\n   \"\\<lbrakk>inj_on f S; countable A\\<rbrakk> \\<Longrightarrow> countable (S \\<inter> f -` A)\"\n  by (meson countable_image_inj_on countable_subset image_subset_iff_subset_vimage inf_le2 inj_on_Int)\n\nlemma countable_image_inj_gen:\n   \"\\<lbrakk>inj_on f S; countable A\\<rbrakk> \\<Longrightarrow> countable {x \\<in> S. f x \\<in> A}\"\n  using countable_image_inj_Int_vimage\n  by (auto simp: vimage_def Collect_conj_eq)\n\nlemma countable_image_inj_eq:\n   \"inj_on f S \\<Longrightarrow> countable(f ` S) \\<longleftrightarrow> countable S\"\n  using countable_image_inj_on by blast\n\nlemma countable_image_inj:\n   \"\\<lbrakk>countable A; inj f\\<rbrakk> \\<Longrightarrow> countable {x. f x \\<in> A}\"\n  by (metis (mono_tags, lifting) countable_image_inj_eq countable_subset image_Collect_subsetI inj_on_inverseI the_inv_f_f)\n\nlemma countable_UN[intro, simp]:\n  fixes I :: \"'i set\" and A :: \"'i => 'a set\"\n  assumes I: \"countable I\"\n  assumes A: \"\\<And>i. i \\<in> I \\<Longrightarrow> countable (A i)\"\n  shows \"countable (\\<Union>i\\<in>I. A i)\"\nproof -\n  have \"(\\<Union>i\\<in>I. A i) = snd ` (SIGMA i : I. A i)\" by (auto simp: image_iff)\n  then show ?thesis by (simp add: assms)\nqed\n\nlemma countable_Un[intro]: \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> countable (A \\<union> B)\"\n  by (rule countable_UN[of \"{True, False}\" \"\\<lambda>True \\<Rightarrow> A | False \\<Rightarrow> B\", simplified])\n     (simp split: bool.split)\n\nlemma countable_Un_iff[simp]: \"countable (A \\<union> B) \\<longleftrightarrow> countable A \\<and> countable B\"\n  by (metis countable_Un countable_subset inf_sup_ord(3,4))\n\nlemma countable_Plus[intro, simp]:\n  \"countable A \\<Longrightarrow> countable B \\<Longrightarrow> countable (A <+> B)\"\n  by (simp add: Plus_def)\n\nlemma countable_empty[intro, simp]: \"countable {}\"\n  by (blast intro: countable_finite)\n\nlemma countable_insert[intro, simp]: \"countable A \\<Longrightarrow> countable (insert a A)\"\n  using countable_Un[of \"{a}\" A] by (auto simp: countable_finite)\n\nlemma countable_Int1[intro, simp]: \"countable A \\<Longrightarrow> countable (A \\<inter> B)\"\n  by (force intro: countable_subset)\n\nlemma countable_Int2[intro, simp]: \"countable B \\<Longrightarrow> countable (A \\<inter> B)\"\n  by (blast intro: countable_subset)\n\nlemma countable_INT[intro, simp]: \"i \\<in> I \\<Longrightarrow> countable (A i) \\<Longrightarrow> countable (\\<Inter>i\\<in>I. A i)\"\n  by (blast intro: countable_subset)\n\nlemma countable_Diff[intro, simp]: \"countable A \\<Longrightarrow> countable (A - B)\"\n  by (blast intro: countable_subset)\n\nlemma countable_insert_eq [simp]: \"countable (insert x A) = countable A\"\n    by auto (metis Diff_insert_absorb countable_Diff insert_absorb)\n\nlemma countable_vimage: \"B \\<subseteq> range f \\<Longrightarrow> countable (f -` B) \\<Longrightarrow> countable B\"\n  by (metis Int_absorb2 countable_image image_vimage_eq)\n\nlemma surj_countable_vimage: \"surj f \\<Longrightarrow> countable (f -` B) \\<Longrightarrow> countable B\"\n  by (metis countable_vimage top_greatest)\n\nlemma countable_Collect[simp]: \"countable A \\<Longrightarrow> countable {a \\<in> A. \\<phi> a}\"\n  by (metis Collect_conj_eq Int_absorb Int_commute Int_def countable_Int1)\n\nlemma countable_Image:\n  assumes \"\\<And>y. y \\<in> Y \\<Longrightarrow> countable (X `` {y})\"\n  assumes \"countable Y\"\n  shows \"countable (X `` Y)\"\nproof -\n  have \"countable (X `` (\\<Union>y\\<in>Y. {y}))\"\n    unfolding Image_UN by (intro countable_UN assms)\n  then show ?thesis by simp\nqed\n\nlemma countable_relpow:\n  fixes X :: \"'a rel\"\n  assumes Image_X: \"\\<And>Y. countable Y \\<Longrightarrow> countable (X `` Y)\"\n  assumes Y: \"countable Y\"\n  shows \"countable ((X ^^ i) `` Y)\"\n  using Y by (induct i arbitrary: Y) (auto simp: relcomp_Image Image_X)\n\nlemma countable_funpow:\n  fixes f :: \"'a set \\<Rightarrow> 'a set\"\n  assumes \"\\<And>A. countable A \\<Longrightarrow> countable (f A)\"\n  and \"countable A\"\n  shows \"countable ((f ^^ n) A)\"\nby(induction n)(simp_all add: assms)\n\nlemma countable_rtrancl:\n  \"(\\<And>Y. countable Y \\<Longrightarrow> countable (X `` Y)) \\<Longrightarrow> countable Y \\<Longrightarrow> countable (X\\<^sup>* `` Y)\"\n  unfolding rtrancl_is_UN_relpow UN_Image by (intro countable_UN countableI_type countable_relpow)\n\nlemma countable_lists[intro, simp]:\n  assumes A: \"countable A\" shows \"countable (lists A)\"\nproof -\n  have \"countable (lists (range (from_nat_into A)))\"\n    by (auto simp: lists_image)\n  with A show ?thesis\n    by (auto dest: subset_range_from_nat_into countable_subset lists_mono)\nqed\n\nlemma Collect_finite_eq_lists: \"Collect finite = set ` lists UNIV\"\n  using finite_list by auto\n\nlemma countable_Collect_finite: \"countable (Collect (finite::'a::countable set\\<Rightarrow>bool))\"\n  by (simp add: Collect_finite_eq_lists)\n\nlemma countable_int: \"countable \\<int>\"\n  unfolding Ints_def by auto\n\nlemma countable_rat: \"countable \\<rat>\"\n  unfolding Rats_def by auto\n\nlemma Collect_finite_subset_eq_lists: \"{A. finite A \\<and> A \\<subseteq> T} = set ` lists T\"\n  using finite_list by (auto simp: lists_eq_set)\n\nlemma countable_Collect_finite_subset:\n  \"countable T \\<Longrightarrow> countable {A. finite A \\<and> A \\<subseteq> T}\"\n  unfolding Collect_finite_subset_eq_lists by auto\n\nlemma countable_Fpow: \"countable S \\<Longrightarrow> countable (Fpow S)\"\n  using countable_Collect_finite_subset\n  by (force simp add: Fpow_def conj_commute)\n\nlemma countable_set_option [simp]: \"countable (set_option x)\"\n  by (cases x) auto\n\nsubsection \\<open>Misc lemmas\\<close>\n\nlemma countable_subset_image:\n   \"countable B \\<and> B \\<subseteq> (f ` A) \\<longleftrightarrow> (\\<exists>A'. countable A' \\<and> A' \\<subseteq> A \\<and> (B = f ` A'))\"\n   (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  show ?rhs\n    by (rule exI [where x=\"inv_into A f ` B\"])\n      (use \\<open>?lhs\\<close> in \\<open>auto simp: f_inv_into_f subset_iff image_inv_into_cancel inv_into_into\\<close>)\nnext\n  assume ?rhs\n  then show ?lhs by force\nqed\n\nlemma ex_subset_image_inj:\n   \"(\\<exists>T. T \\<subseteq> f ` S \\<and> P T) \\<longleftrightarrow> (\\<exists>T. T \\<subseteq> S \\<and> inj_on f T \\<and> P (f ` T))\"\n  by (auto simp: subset_image_inj)\n\nlemma all_subset_image_inj:\n   \"(\\<forall>T. T \\<subseteq> f ` S \\<longrightarrow> P T) \\<longleftrightarrow> (\\<forall>T. T \\<subseteq> S \\<and> inj_on f T \\<longrightarrow> P(f ` T))\"\n  by (metis subset_image_inj)\n\nlemma ex_countable_subset_image_inj:\n   \"(\\<exists>T. countable T \\<and> T \\<subseteq> f ` S \\<and> P T) \\<longleftrightarrow>\n    (\\<exists>T. countable T \\<and> T \\<subseteq> S \\<and> inj_on f T \\<and> P (f ` T))\"\n  by (metis countable_image_inj_eq subset_image_inj)\n\nlemma all_countable_subset_image_inj:\n   \"(\\<forall>T. countable T \\<and> T \\<subseteq> f ` S \\<longrightarrow> P T) \\<longleftrightarrow> (\\<forall>T. countable T \\<and> T \\<subseteq> S \\<and> inj_on f T \\<longrightarrow>P(f ` T))\"\n  by (metis countable_image_inj_eq subset_image_inj)\n\nlemma ex_countable_subset_image:\n   \"(\\<exists>T. countable T \\<and> T \\<subseteq> f ` S \\<and> P T) \\<longleftrightarrow> (\\<exists>T. countable T \\<and> T \\<subseteq> S \\<and> P (f ` T))\"\n  by (metis countable_subset_image)\n\nlemma all_countable_subset_image:\n   \"(\\<forall>T. countable T \\<and> T \\<subseteq> f ` S \\<longrightarrow> P T) \\<longleftrightarrow> (\\<forall>T. countable T \\<and> T \\<subseteq> S \\<longrightarrow> P(f ` T))\"\n  by (metis countable_subset_image)\n\nlemma countable_image_eq:\n   \"countable(f ` S) \\<longleftrightarrow> (\\<exists>T. countable T \\<and> T \\<subseteq> S \\<and> f ` S = f ` T)\"\n  by (metis countable_image countable_image_inj_eq order_refl subset_image_inj)\n\nlemma countable_image_eq_inj:\n   \"countable(f ` S) \\<longleftrightarrow> (\\<exists>T. countable T \\<and> T \\<subseteq> S \\<and> f ` S = f ` T \\<and> inj_on f T)\"\n  by (metis countable_image_inj_eq order_refl subset_image_inj)\n\nlemma infinite_countable_subset':\n  assumes X: \"infinite X\" shows \"\\<exists>C\\<subseteq>X. countable C \\<and> infinite C\"\nproof -\n  obtain f :: \"nat \\<Rightarrow> 'a\" where \"inj f\" \"range f \\<subseteq> X\"\n    using infinite_countable_subset [OF X] by blast\n  then show ?thesis\n    by (intro exI[of _ \"range f\"]) (auto simp: range_inj_infinite)\nqed\n\nlemma countable_all:\n  assumes S: \"countable S\"\n  shows \"(\\<forall>s\\<in>S. P s) \\<longleftrightarrow> (\\<forall>n::nat. from_nat_into S n \\<in> S \\<longrightarrow> P (from_nat_into S n))\"\n  using S[THEN subset_range_from_nat_into] by auto\n\nlemma finite_sequence_to_countable_set:\n  assumes \"countable X\"\n  obtains F where \"\\<And>i. F i \\<subseteq> X\" \"\\<And>i. F i \\<subseteq> F (Suc i)\" \"\\<And>i. finite (F i)\" \"(\\<Union>i. F i) = X\"\nproof -\n  show thesis\n    apply (rule that[of \"\\<lambda>i. if X = {} then {} else from_nat_into X ` {..i}\"])\n       apply (auto simp add: image_iff intro: from_nat_into split: if_splits)\n    using assms from_nat_into_surj by (fastforce cong: image_cong)\nqed\n\nlemma transfer_countable[transfer_rule]:\n  \"bi_unique R \\<Longrightarrow> rel_fun (rel_set R) (=) countable countable\"\n  by (rule rel_funI, erule (1) bi_unique_rel_set_lemma)\n     (auto dest: countable_image_inj_on)\n\nsubsection \\<open>Uncountable\\<close>\n\nabbreviation uncountable where\n  \"uncountable A \\<equiv> \\<not> countable A\"\n\nlemma uncountable_def: \"uncountable A \\<longleftrightarrow> A \\<noteq> {} \\<and> \\<not> (\\<exists>f::(nat \\<Rightarrow> 'a). range f = A)\"\n  by (auto intro: inj_on_inv_into simp: countable_def)\n     (metis all_not_in_conv inj_on_iff_surj subset_UNIV)\n\nlemma uncountable_bij_betw: \"bij_betw f A B \\<Longrightarrow> uncountable B \\<Longrightarrow> uncountable A\"\n  unfolding bij_betw_def by (metis countable_image)\n\nlemma uncountable_infinite: \"uncountable A \\<Longrightarrow> infinite A\"\n  by (metis countable_finite)\n\nlemma uncountable_minus_countable:\n  \"uncountable A \\<Longrightarrow> countable B \\<Longrightarrow> uncountable (A - B)\"\n  using countable_Un[of B \"A - B\"] by auto\n\nlemma countable_Diff_eq [simp]: \"countable (A - {x}) = countable A\"\n  by (meson countable_Diff countable_empty countable_insert uncountable_minus_countable)\n\ntext \\<open>Every infinite set can be covered by a pairwise disjoint family of infinite sets.\n      This version doesn't achieve equality, as it only covers a countable subset\\<close>\nlemma infinite_infinite_partition:\n  assumes \"infinite A\"\n  obtains C :: \"nat \\<Rightarrow> 'a set\" \n    where \"pairwise (\\<lambda>i j. disjnt (C i) (C j)) UNIV\" \"(\\<Union>i. C i) \\<subseteq> A\" \"\\<And>i. infinite (C i)\"\nproof -\n  obtain f :: \"nat\\<Rightarrow>'a\" where \"range f \\<subseteq> A\" \"inj f\"\n    using assms infinite_countable_subset by blast\n  let ?C = \"\\<lambda>i. range (\\<lambda>j. f (prod_encode (i,j)))\"\n  show thesis\n  proof\n    show \"pairwise (\\<lambda>i j. disjnt (?C i) (?C j)) UNIV\"\n      by (auto simp: pairwise_def disjnt_def inj_on_eq_iff [OF \\<open>inj f\\<close>] inj_on_eq_iff [OF inj_prod_encode, of _ UNIV])\n    show \"(\\<Union>i. ?C i) \\<subseteq> A\"\n      using \\<open>range f \\<subseteq> A\\<close> by blast\n    have \"infinite (range (\\<lambda>j. f (prod_encode (i, j))))\" for i\n      by (rule range_inj_infinite) (meson Pair_inject \\<open>inj f\\<close> inj_def prod_encode_eq)\n    then show \"\\<And>i. infinite (?C i)\"\n      using that by auto\n  qed\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Library/Countable_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8791467770088162, "lm_q2_score": 0.8558511469672594, "lm_q1q2_score": 0.7524187774555647}}
{"text": "(*<*)\ntheory sol03\nimports \"~~/src/HOL/IMP/BExp\" \"~~/src/HOL/IMP/ASM\"\nbegin\n(*>*)\ntext {* \\ExerciseSheet{3}{29.~10.~2013} *}\n\n\n\n\ntext {* \\Exercise{Relational @{text \"aval\"}}\n\n  Theory @{text AExp} defines an evaluation function\n  @{text \"aval :: aexp \\<Rightarrow> state \\<Rightarrow> val\"} for arithmetic expressions.\n  Define a corresponding evaluation relation\n  @{text \"is_aval :: aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\"} as an inductive predicate:\n*}\n\ninductive is_aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" (*<*)where\n  \"is_aval (N n) s n\" |\n  \"s x = v \\<Longrightarrow> is_aval (V x) s v\" |\n  \"\\<lbrakk>is_aval a1 s v1; is_aval a2 s v2; v'=v1+v2\\<rbrakk> \\<Longrightarrow> is_aval (Plus a1 a2) s v'\"\n(*>*)\n\ntext {* Use the introduction rules @{text is_aval.intros} to prove\n  this example lemma. *}\n\nlemma \"is_aval (Plus (N 2) (Plus (V x) (N 3))) s (2 + (s x + 3))\"\n(*<*) by (auto intro!: is_aval.intros) (*>*)\n\ntext {* Prove that the evaluation relation @{text is_aval} agrees with\n  the evaluation function @{text aval}. Show implications in both\n  directions, and then prove the if-and-only-if form.\n*}\n\nlemma aval1: \"is_aval a s v \\<Longrightarrow> aval a s = v\"\n(*<*) by (induction rule: is_aval.induct) auto (*>*)\n\nlemma aval2: \"aval a s = v \\<Longrightarrow> is_aval a s v\"\n(*<*) by (induction a arbitrary: v) (auto intro: is_aval.intros) (*>*)\n\ntheorem \"is_aval a s v \\<longleftrightarrow> aval a s = v\"\n(*<*)\nproof\n  assume \"is_aval a s v\" thus \"aval a s = v\" by (rule aval1)\nnext\n  assume \"aval a s = v\" thus \"is_aval a s v\" by (rule aval2)\nqed\n(*>*)\n\n(*<*)\n(*The version without equality assumptions also works.*)\ninductive is_aval' :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\n  \"is_aval' (N n) s n\" |\n  \"is_aval' (V x) s (s x)\" |\n  \"\\<lbrakk>is_aval' a1 s v1; is_aval' a2 s v2\\<rbrakk> \\<Longrightarrow> is_aval' (Plus a1 a2) s (v1 + v2)\"\n\nlemma \"is_aval' (Plus (V x) (Plus (V y) (N 3))) s (s x + (s y + 3))\"\nby (auto intro!: is_aval'.intros)\n\ntheorem \"is_aval' a s v \\<longleftrightarrow> aval a s = v\"\n  apply (rule iffI)\n  apply (induction rule: is_aval'.induct)\n  apply auto\n  apply (induction a arbitrary: v)\n  apply (auto intro: is_aval'.intros)\n  done\n(*>*)\n\n\ntext {* \\Exercise{Avoiding Stack Underflow}*}\n\ntext {* A \\emph{stack underflow} occurs when executing an instruction\n  on a stack containing too few values -- e.g., executing an @{text ADD}\n  instruction on an stack of size less than two. A well-formed sequence of\n  instructions (e.g., one generated by @{text comp}) should never\n  cause a stack underflow. *}\n\n(* Alternative: functional solution: *)\n\ntext {*\n  In this exercise, you will define a semantics for the \n  stack-machine that throws an exception if the program underflows the stack.\n*}\n\ntext {* Modify the @{text \"exec1\"} and @{text \"exec\"} - functions, such\n  that they return an option value, @{text \"None\"} indicating a \n  stack-underflow. *}\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\" \n(*<*)\nwhere\n\"exec1 (LOADI n) _ stk  =  Some (n # stk)\" |\n\"exec1 (LOAD x) s stk  =  Some (s(x) # stk)\" |\n\"exec1  ADD _ stk  =  (\n  if length (stk)\\<ge>2 then \n    Some ((hd2 stk + hd stk) # tl2 stk)\n  else None)\"\n(*>*)\n\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack option\"\n(*<*)\n where\n\"exec [] _ stk = Some stk\" |\n\"exec (i#is) s stk = (case exec1 i s stk of\n    Some stk \\<Rightarrow> exec is s stk\n  | None \\<Rightarrow> None)\"\n(*>*)\n\ntext {*\n  Now adjust the proof of theorem @{text \"exec_comp\"} to show that programs\n  output by the compiler never underflow the stack:\n*}\n(*<*)\nlemma exec_append[simp]:\n  \"exec (is1@is2) s stk = (case exec is1 s stk of\n    Some stk \\<Rightarrow> exec is2 s stk\n  | None \\<Rightarrow> None)\"\napply(induction is1 arbitrary: stk)\napply (auto split: option.split)\ndone\n(*>*)\ntheorem exec_comp: \"exec (comp a) s stk = Some (aval a s # stk)\"\n(*<*)\napply(induction a arbitrary: stk)\napply (auto)\ndone\n(*>*)\n\n\n\n(*<*)\n(* Alternative: Relational solution *)\ntext {*\n  In this exercise, you will define a relational semantics for the \n  stack-machine. The relation does not contain elements for programs causing\n  a stack underflow.\n*}\n\ninductive execi1 :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack \\<Rightarrow> bool\" where\n  \"execi1 (LOADI n) s stk (n#stk)\"\n| \"execi1 (LOAD x) s stk (s x#stk)\"\n| \"execi1 (ADD) _ (v1#v2#stk) ((v1+v2)#stk)\"\n\nlemma \n  assumes \"execi1 i s stk stk'\"  \n  shows \"ASM.exec1 i s stk = stk'\"\n  using assms\n  by induction auto\n\nlemma \n  assumes \"ASM.exec1 i s stk = stk'\"\n  shows \"execi1 i s stk stk'\"\n  nitpick\n  oops\n\ninductive execi :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack \\<Rightarrow> bool\" where\n  \"execi [] s stk stk\"\n| \"\\<lbrakk> execi1 i s stk stk2; execi is s stk2 stk' \\<rbrakk> \\<Longrightarrow> execi (i#is) s stk stk'\"\n\nlemma execi_appendI: \n  assumes E1: \"execi is1 s stk stk2\" and E2: \"execi is2 s stk2 stk'\"\n  shows \"execi (is1@is2) s stk stk'\"\n  using E1 E2\n  by (induction) (auto intro: execi.intros)\n\nlemma execi_appendE[elim]:\n  assumes \"execi (is1@is2) s stk stk'\"\n  obtains stk2 where \"execi is1 s stk stk2\" and \"execi is2 s stk2 stk'\"\n  using assms\n  apply (induction is1 arbitrary: stk)\n  apply (auto intro: execi.intros) []\n  apply (erule execi.cases)\n  apply (auto intro: execi.intros)\n  (*apply (force intro: execi.intros elim!: execi.cases)*)\n  done\n\nlemma execi_sound:\n  shows \"execi (comp a) s stk (aval a s # stk)\"\n  apply (induction a arbitrary: stk)\n  apply (auto \n    intro!: execi.intros execi1.intros execi_appendI\n    simp: add.commute)\n  done\n\ninductive_cases [elim!]: \n  \"execi [LOADI i] s stk stk'\"\n  \"execi [LOAD x] s stk stk'\"\n  \"execi [ADD] s stk stk'\"\n  \"execi [] s stk stk'\"\n\nlemma execi_complete:\n  assumes \"execi (comp a) s stk stk'\"\n  shows \"stk' = aval a s#stk\"\n  using assms\n  apply (induction a arbitrary: s stk stk')\n  apply (auto elim: execi1.cases)  [2]\n  apply (fastforce elim: execi1.cases)\n  done\n\ntheorem execi_correct:\n  \"execi (comp a) s stk stk' \\<longleftrightarrow> (stk' = aval a s # stk)\"\n  using execi_sound execi_complete\n  by blast\n(*>*)\n\n\ntext {* \\Exercise{Boolean If expressions}\n\nWe consider an alternative definition of boolean expressions, which\n  feature a conditional construct: *}\n\ndatatype ifexp = Bc' bool | If ifexp ifexp ifexp | Less' aexp aexp\n\ntext {*\n\\begin{enumerate}\n\\item Define a function @{text ifval} analogous to @{const bval},\n  which evaluates @{typ ifexp} expressions.\n\n\\item\nDefine a function @{term translate},\nwhich translates @{typ ifexp}s to @{typ bexp}s.\n  State and prove a lemma showing that the translation is correct.\n\\end{enumerate}\n*}\n(*<*)\nprimrec ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc' b) _ = b\" |\n\"ifval (If b1 b2 b3) st = (if ifval b1 st then ifval b2 st else ifval b3 st)\" |\n\"ifval (Less' a1 a2) st = (aval a1 st < aval a2 st)\"\n\nfun Or :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"Or b1 b2 = Not (And (Not b1) (Not b2))\"\n\nfun If_bexp :: \"bexp \\<Rightarrow> bexp \\<Rightarrow> bexp \\<Rightarrow> bexp\" where\n\"If_bexp b1 b2 b3 = Or (And b1 b2) (And (Not b1) b3)\"\n\nprimrec translate :: \"ifexp \\<Rightarrow> bexp\" where\n\"translate (Bc' b) = (Bc b)\" |\n\"translate (If b1 b2 b3) =\n  If_bexp (translate b1) (translate b2) (translate b3)\" |\n\"translate (Less' a1 a2) = Less a1 a2\"\n\nlemma translate_sound: \"bval (translate exp) s = ifval exp s\"\nby (induction exp) auto\n(*>*)\n\n(*<*)\nend\n(*>*)\n", "meta": {"author": "glimonta", "repo": "Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "save_path": "github-repos/isabelle/glimonta-Semantics", "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise3/sol03.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.8558511488056151, "lm_q1q2_score": 0.7524187682317817}}
{"text": "theory FiniteGraph\nimports Main \nbegin\n\n(*Lots of this theory is based on a work by Benedikt Nordhoff and Peter Lammich*)\n\nsection \\<open>Specification of a finite directed graph\\<close>\n\ntext\\<open>A graph \\<open>G=(V,E)\\<close> consits of a set of vertices \\<open>V\\<close>, also called nodes, \n       and a set of edges \\<open>E\\<close>. The edges are tuples of vertices. Both, \n       the set of vertices and edges is finite.\\<close>\n\n(* Inspired by\nTitle: Dijkstra's Shortest Path Algorithm\nAuthor: Benedikt Nordhoff and Peter Lammich\nhttp://isa-afp.org/entries/Dijkstra_Shortest_Path.shtml\n*)\n\nsection \\<open>Graph\\<close>\nsubsection\\<open>Definitions\\<close>\n  text \\<open>A graph is represented by a record.\\<close>\n  record 'v graph =\n    nodes :: \"'v set\"\n    edges :: \"('v \\<times>'v) set\"\n\n  text \\<open>In a well-formed graph, edges only go from nodes to nodes.\\<close>\n  locale wf_graph = \n    fixes G :: \"'v graph\"\n    \\<comment> \\<open>Edges only reference to existing nodes\\<close>\n    assumes E_wf: \"fst ` (edges G) \\<subseteq> (nodes G)\"\n                     \"snd ` (edges G) \\<subseteq> (nodes G)\"\n    and finiteE: \"finite (edges G)\" (*implied by finiteV*)\n    and finiteV: \"finite (nodes G)\"\n  begin\n    abbreviation \"V \\<equiv> (nodes G)\"\n    abbreviation \"E \\<equiv> (edges G)\"\n\n    \n\n    lemma E_wfD2: \"\\<forall>e \\<in> E. fst e \\<in> V \\<and> snd e \\<in> V\"\n    by (auto simp add: E_wfD)\n  end\n\nsubsection \\<open>Basic operations on Graphs\\<close>\n  text \\<open>The empty graph.\\<close>\n  definition empty :: \"'v graph\" where \n    \"empty \\<equiv> \\<lparr> nodes = {}, edges = {} \\<rparr>\"\n\n  text \\<open>Adds a node to a graph.\\<close>\n  definition add_node :: \"'v \\<Rightarrow> 'v graph \\<Rightarrow> 'v graph\" where \n    \"add_node v G \\<equiv> \\<lparr> nodes = ({v} \\<union> (nodes G)), edges=edges G \\<rparr>\"\n\n  text \\<open>Deletes a node from a graph. Also deletes all adjacent edges.\\<close>\n  definition delete_node where \"delete_node v G \\<equiv> \\<lparr> \n      nodes = (nodes G) - {v},   \n      edges = {(e1, e2). (e1, e2) \\<in> edges G \\<and> e1 \\<noteq> v \\<and> e2 \\<noteq> v}\n    \\<rparr>\"\n\n  text \\<open>Adds an edge to a graph.\\<close>\n  definition add_edge where \n  \"add_edge v v' G = \\<lparr>nodes = nodes G \\<union> {v,v'}, edges = {(v, v')} \\<union> edges G \\<rparr>\"\n\n  text \\<open>Deletes an edge from a graph.\\<close>\n  definition delete_edge where \"delete_edge v v' G \\<equiv> \\<lparr>\n      nodes = nodes G, \n      edges = {(e1,e2). (e1, e2) \\<in> edges G \\<and> (e1,e2) \\<noteq> (v,v')}\n    \\<rparr>\"\n  \n  definition delete_edges::\"'v graph \\<Rightarrow> ('v \\<times> 'v) set \\<Rightarrow> 'v graph\" where \n    \"delete_edges G es \\<equiv> \\<lparr>\n      nodes = nodes G, \n      edges = {(e1,e2). (e1, e2) \\<in> edges G \\<and> (e1,e2) \\<notin> es}\n    \\<rparr>\"\n\n  fun delete_edges_list::\"'v graph \\<Rightarrow> ('v \\<times> 'v) list \\<Rightarrow> 'v graph\" where \n    \"delete_edges_list G [] = G\"|\n    \"delete_edges_list G ((v,v')#es) = delete_edges_list (delete_edge v v' G) es\"\n\n  definition fully_connected :: \"'v graph \\<Rightarrow> 'v graph\" where\n    \"fully_connected G \\<equiv> \\<lparr>nodes = nodes G, edges = nodes G \\<times> nodes G \\<rparr>\"\n\n\ntext \\<open>Extended graph operations\\<close>\n  text \\<open>Reflexive transitive successors of a node. Or: All reachable nodes for \\<open>v\\<close> including \\<open>v\\<close>.\\<close>\n  definition succ_rtran :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> 'v set\" where\n    \"succ_rtran G v = {e2. (v,e2) \\<in> (edges G)\\<^sup>*}\"\n\n  text \\<open>Transitive successors of a node. Or: All reachable nodes for \\<open>v\\<close>.\\<close>\n  definition succ_tran :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> 'v set\" where\n    \"succ_tran G v = {e2. (v,e2) \\<in> (edges G)\\<^sup>+}\"\n\n  \\<comment> \\<open>succ_tran is always finite\\<close>\n  lemma succ_tran_finite: \"wf_graph G \\<Longrightarrow> finite (succ_tran G v)\"\n  proof -\n    assume \"wf_graph G\"\n    from wf_graph.finiteE[OF this] have \"finite ((edges G)\\<^sup>+)\" using finite_trancl[symmetric, of \"edges G\"] by metis\n    from this have \"finite {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by simp\n    from this have finite: \"finite (snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+})\" by (metis finite_imageI)\n    have \"{(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+ \\<and> e1 = v} \\<subseteq> {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by blast\n    have 1: \"snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+ \\<and> e1 = v} \\<subseteq> snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by blast\n    have 2: \"snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+ \\<and> e1 = v} = {e2. (v,e2) \\<in> (edges G)\\<^sup>+}\" by force\n    from 1 2 have \"{e2. (v,e2) \\<in> (edges G)\\<^sup>+} \\<subseteq> snd ` {(e1,e2). (e1, e2) \\<in> (edges G)\\<^sup>+}\" by blast\n    from this finite have \"finite {e2. (v, e2) \\<in> (edges G)\\<^sup>+}\" by (metis finite_subset)\n    thus \"finite (succ_tran G v)\" using succ_tran_def by metis\n  qed\n  \n  text\\<open>If there is no edge leaving from \\<open>v\\<close>, then \\<open>v\\<close> has no successors\\<close>\n  lemma succ_tran_empty: \"\\<lbrakk> wf_graph G; v \\<notin> (fst ` edges G) \\<rbrakk> \\<Longrightarrow> succ_tran G v = {}\"\n    unfolding succ_tran_def using image_iff tranclD by fastforce\n\n  text\\<open>@{const succ_tran} is subset of nodes\\<close>\n  lemma succ_tran_subseteq_nodes: \"\\<lbrakk> wf_graph G \\<rbrakk> \\<Longrightarrow> succ_tran G v \\<subseteq> nodes G\"\n    unfolding succ_tran_def using tranclD2 wf_graph.E_wfD(2) by fastforce\n\n  text \\<open>The number of reachable nodes from \\<open>v\\<close>\\<close>\n  definition num_reachable :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n    \"num_reachable G v = card (succ_tran G v)\"\n\n  definition num_reachable_norefl :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> nat\" where\n    \"num_reachable_norefl G v = card (succ_tran G v - {v})\"\n\n  text\\<open>@{const card} returns @{term 0} for infinite sets.\n        Here, for a well-formed graph, if @{const num_reachable} is zero, there are actually no nodes reachable.\\<close>\n  lemma num_reachable_zero: \"\\<lbrakk>wf_graph G; num_reachable G v = 0\\<rbrakk> \\<Longrightarrow> succ_tran G v = {}\"\n  unfolding num_reachable_def\n  apply(subgoal_tac \"finite (succ_tran G v)\")\n   apply(simp)\n  apply(blast intro: succ_tran_finite)\n  done\n  lemma num_succtran_zero: \"\\<lbrakk>succ_tran G v = {}\\<rbrakk> \\<Longrightarrow> num_reachable G v = 0\"\n    unfolding num_reachable_def by simp\n  lemma num_reachable_zero_iff: \"\\<lbrakk>wf_graph G\\<rbrakk> \\<Longrightarrow> (num_reachable G v = 0) \\<longleftrightarrow> (succ_tran G v = {})\"\n  by(metis num_succtran_zero num_reachable_zero)\n\n\nsection\\<open>Undirected Graph\\<close>\n\nsubsection\\<open>undirected graph simulation\\<close>\n  text \\<open>Create undirected graph from directed graph by adding backward links\\<close>\n\n  definition backflows :: \"('v \\<times> 'v) set \\<Rightarrow> ('v \\<times> 'v) set\" where\n    \"backflows E \\<equiv> {(r,s). (s,r) \\<in> E}\"\n\n  definition undirected :: \"'v graph \\<Rightarrow> 'v graph\"\n    where \"undirected G = \\<lparr> nodes = nodes G, edges = (edges G) \\<union> {(b,a). (a,b) \\<in> edges G} \\<rparr>\"\n\nsection \\<open>Graph Lemmas\\<close>\n\n  lemma graph_eq_intro: \"(nodes (G::'a graph) = nodes G') \\<Longrightarrow> (edges G = edges G') \\<Longrightarrow> G = G'\" by simp\n\n  \\<comment> \\<open>finite\\<close>\n  lemma wf_graph_finite_filterE: \"wf_graph G \\<Longrightarrow> finite {(e1, e2). (e1, e2) \\<in> edges G \\<and> P e1 e2}\"\n  by(simp add: wf_graph.finiteE split_def)\n  lemma wf_graph_finite_filterV: \"wf_graph G \\<Longrightarrow> finite {n. n \\<in> nodes G \\<and> P n}\"\n  by(simp add: wf_graph.finiteV)\n\n  \\<comment> \\<open>empty\\<close>\n  lemma empty_wf[simp]: \"wf_graph empty\"\n    unfolding empty_def by unfold_locales auto\n  lemma nodes_empty[simp]: \"nodes empty = {}\" unfolding empty_def by simp\n  lemma edges_empty[simp]: \"edges empty = {}\" unfolding empty_def by simp\n\n  \\<comment> \\<open>add node\\<close>\n  lemma add_node_wf[simp]: \"wf_graph g \\<Longrightarrow> wf_graph (add_node v g)\"\n    unfolding add_node_def wf_graph_def by (auto)\n\n  lemma delete_node_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_node v G)\"\n    by(auto simp add: delete_node_def wf_graph_def wf_graph_finite_filterE)\n\n  \\<comment> \\<open>add edgde\\<close>\n  lemma add_edge_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (add_edge v v' G)\"\n    by(auto simp add: add_edge_def add_node_def wf_graph_def)\n\n  \\<comment> \\<open>delete edge\\<close>\n  lemma delete_edge_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_edge v v' G)\"\n    by(auto simp add: delete_edge_def add_node_def wf_graph_def split_def)\n \n  \\<comment> \\<open>delte edges\\<close>\n  lemma delete_edges_list_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_edges_list G E)\"\n    by(induction E arbitrary: G, simp, force)\n  lemma delete_edges_wf[simp]: \"wf_graph G \\<Longrightarrow> wf_graph (delete_edges G E)\"\n    by(auto simp add: delete_edges_def add_node_def wf_graph_def split_def)\n  lemma delete_edges_list_set: \"delete_edges_list G E = delete_edges G (set E)\"\n    proof(induction E arbitrary: G)\n    case Nil thus ?case by (simp add: delete_edges_def)\n    next\n    case (Cons e E) thus ?case by(cases e)(simp add: delete_edge_def delete_edges_def)\n    qed\n  lemma delete_edges_list_union: \"delete_edges_list G (ff @ keeps) = delete_edges G (set ff \\<union> set keeps)\"\n   by(simp add: delete_edges_list_set)\n  lemma add_edge_delete_edges_list: \n    \"(add_edge (fst a) (snd a) (delete_edges_list G (a # ff))) = (add_edge (fst a) (snd a) (delete_edges G (set ff)))\"\n   by(auto simp add: delete_edges_list_set delete_edges_def add_edge_def add_node_def)\n  lemma delete_edges_empty[simp]: \"delete_edges G {} = G\"\n   by(simp add: delete_edges_def)\n  lemma delete_edges_simp2: \"delete_edges G E = \\<lparr> nodes = nodes G, edges = edges G - E\\<rparr>\"\n   by(auto simp add: delete_edges_def)\n  lemma delete_edges_set_nodes: \"nodes (delete_edges G E) = nodes G\"\n   by(simp add: delete_edges_simp2)\n  lemma delete_edges_edges_mono: \"E' \\<subseteq> E \\<Longrightarrow> edges (delete_edges G E) \\<subseteq> edges (delete_edges G E')\"\n    by(simp add: delete_edges_def, fast)\n  lemma delete_edges_edges_empty: \"(delete_edges G (edges G)) = G\\<lparr>edges := {}\\<rparr>\"\n    by(simp add: delete_edges_simp2)\n\n \\<comment> \\<open>add delete\\<close>\n  lemma add_delete_edge: \"wf_graph (G::'a graph) \\<Longrightarrow> (a,b) \\<in> edges G \\<Longrightarrow> add_edge a b (delete_edge a b G) = G\"\n   apply(simp add: delete_edge_def add_edge_def wf_graph_def)\n   apply(intro graph_eq_intro)\n    by auto\n\n  lemma add_delete_edges: \"wf_graph (G::'v graph) \\<Longrightarrow> (a,b) \\<in> edges G \\<Longrightarrow> (a,b) \\<notin> fs \\<Longrightarrow>\n    add_edge a b (delete_edges G (insert (a, b) fs)) = (delete_edges G fs)\"\n    by(auto simp add: delete_edges_simp2 add_edge_def wf_graph_def)\n\n\n \\<comment> \\<open>fully_connected\\<close>\n  lemma fully_connected_simp: \"fully_connected \\<lparr>nodes = N, edges = ignore \\<rparr>\\<equiv> \\<lparr>nodes = N, edges = N \\<times> N \\<rparr>\"\n    by(simp add: fully_connected_def)\n  lemma fully_connected_wf: \"wf_graph G \\<Longrightarrow> wf_graph (fully_connected G)\"\n    by(simp add: fully_connected_def wf_graph_def)\n\n \\<comment> \\<open>succ_tran\\<close>\n lemma succ_tran_mono: \n  \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> E' \\<subseteq> E \\<Longrightarrow> succ_tran \\<lparr>nodes=N, edges=E'\\<rparr> v \\<subseteq> succ_tran \\<lparr>nodes=N, edges=E\\<rparr> v\"\n   apply(drule wf_graph.finiteE)\n   apply(frule_tac A=\"E'\" in rev_finite_subset, simp)\n   apply(simp add: num_reachable_def)\n   apply(simp add: succ_tran_def)\n   apply(metis (lifting, full_types) Collect_mono trancl_mono)\n  done\n\n  \\<comment> \\<open>num_reachable\\<close>\n  lemma num_reachable_mono:\n  \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> E' \\<subseteq> E \\<Longrightarrow> num_reachable \\<lparr>nodes=N, edges=E'\\<rparr> v \\<le> num_reachable \\<lparr>nodes=N, edges=E\\<rparr> v\"\n   apply(simp add: num_reachable_def)\n   apply(frule_tac E'=\"E'\" and v=\"v\" in succ_tran_mono, simp)\n   apply(frule_tac v=\"v\" in succ_tran_finite)\n   apply(simp add: card_mono)\n  done\n\n  \\<comment> \\<open>num_reachable_norefl\\<close>\n  lemma num_reachable_norefl_mono:\n  \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> E' \\<subseteq> E \\<Longrightarrow> num_reachable_norefl \\<lparr>nodes=N, edges=E'\\<rparr> v \\<le> num_reachable_norefl \\<lparr>nodes=N, edges=E\\<rparr> v\"\n   apply(simp add: num_reachable_norefl_def)\n   apply(frule_tac E'=\"E'\" and v=\"v\" in succ_tran_mono, simp)\n   apply(frule_tac v=\"v\" in succ_tran_finite)\n   using card_mono by (metis Diff_mono finite_Diff subset_refl)\n\n  \\<comment> \\<open>backflows\\<close>\n  lemma backflows_wf: \n    \"wf_graph \\<lparr>nodes=N, edges=E\\<rparr> \\<Longrightarrow> wf_graph \\<lparr>nodes=N, edges=backflows E\\<rparr>\"\n    using [[simproc add: finite_Collect]] by(auto simp add: wf_graph_def backflows_def)\n  lemma undirected_backflows: \n    \"undirected G = \\<lparr> nodes = nodes G, edges = (edges G) \\<union> backflows (edges G) \\<rparr>\"\n    by(simp add: backflows_def undirected_def)\n  lemma backflows_id: \n    \"backflows (backflows E) = E\"\n    by(simp add: backflows_def)\n  \n\n\nlemmas graph_ops=add_node_def delete_node_def add_edge_def delete_edge_def delete_edges_simp2\n\n\n  \\<comment> \\<open>wf_graph\\<close>\n  lemma wf_graph_remove_edges: \"wf_graph \\<lparr> nodes = V, edges = E \\<rparr> \\<Longrightarrow> wf_graph \\<lparr> nodes = V, edges=E - X\\<rparr>\"\n    by (metis delete_edges_simp2 delete_edges_wf select_convs(1) select_convs(2))\n\n  lemma wf_graph_remove_edges_union: \n    \"wf_graph \\<lparr> nodes = V, edges = E \\<union> E' \\<rparr> \\<Longrightarrow> wf_graph \\<lparr> nodes = V, edges=E\\<rparr>\"\n    by(auto simp add: wf_graph_def)\n\n  lemma wf_graph_union_edges: \"\\<lbrakk> wf_graph \\<lparr> nodes = V, edges = E \\<rparr>; wf_graph \\<lparr> nodes = V, edges=E'\\<rparr> \\<rbrakk> \\<Longrightarrow>\n     wf_graph \\<lparr> nodes = V, edges=E \\<union> E'\\<rparr>\"\n    by(auto simp add: wf_graph_def)\n\n  lemma wf_graph_add_subset_edges: \"\\<lbrakk> wf_graph \\<lparr> nodes = V, edges = E \\<rparr>; E' \\<subseteq> E \\<rbrakk> \\<Longrightarrow>\n     wf_graph \\<lparr> nodes = V, edges= E \\<union> E'\\<rparr>\"\n    by(auto simp add: wf_graph_def) (metis rev_finite_subset)\n\n\n(*Inspired by \nBenedikt Nordhoff and Peter Lammich\nDijkstra's Shortest Path Algorithm\nhttp://isa-afp.org/entries/Dijkstra_Shortest_Path.shtml*)\n(*more a literal copy of http://isa-afp.org/browser_info/current/AFP/Dijkstra_Shortest_Path/Graph.html*)\n\n  text \\<open>Successors of a node.\\<close>\n  definition succ :: \"'v graph \\<Rightarrow> 'v \\<Rightarrow> 'v set\"\n    where \"succ G v \\<equiv> {v'. (v,v')\\<in>edges G}\"\n\n\n  lemma succ_finite[simp, intro]: \"finite (edges G) \\<Longrightarrow> finite (succ G v)\"\n    unfolding succ_def\n    by (rule finite_subset[where B=\"snd`edges G\"]) force+\n\n  lemma succ_empty: \"succ empty v = {}\" unfolding empty_def succ_def by auto\n\n  lemma (in wf_graph) succ_subset: \"succ G v \\<subseteq> V\"\n    unfolding succ_def using E_wf\n    by (force)\n\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Network_Security_Policy_Verification/Lib/FiniteGraph.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9005297967961706, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7523778198943039}}
{"text": "theory Natural\n  imports Main \"~~/src/HOL/Eisbach/Eisbach_Tools\"\nbegin\n\nlemma give: \"P \\<Longrightarrow> (P \\<Longrightarrow> Q) \\<Longrightarrow> Q\" by simp\nlemma take: \"(P \\<Longrightarrow> Q) \\<Longrightarrow> P \\<Longrightarrow> Q\" by simp\nmethod gives for t :: bool = rule give[of t]\nmethod takes for t :: bool = rule take[of t]\nmethod give for t :: bool methods how = (gives t, (how ; fail)[1])\nmethod take for t :: bool methods how = (takes t, (how ; fail)[1])\n\n-- \"Natural numbers, starting from 1\"\n\ndatatype natural = one | succ natural\n\nfun add_nat where\n  \"add_nat one n = succ n\" |\n  \"add_nat (succ n) m = succ (add_nat n m)\"\n\nlemma add_nat_associative: \"add_nat (add_nat a b) c = add_nat a (add_nat b c)\"\n  by (induction a b rule: add_nat.induct, auto)\n    \n\ninstantiation natural :: one begin\ndefinition \"one_natural = one\"\ndeclare one_natural_def [simp]\ninstance by standard end\n\ninstantiation natural :: semigroup_add begin\ndefinition \"plus_natural = add_nat\"\ndeclare plus_natural_def [simp]\ninstance \n  apply standard\n  apply simp\n  using add_nat_associative apply assumption\n  done\nend\n\ninstantiation natural :: numeral begin\ninstance by standard end\n\ninstantiation natural :: ord begin\n\nfun less_natural where\n  \"less_natural one (succ _) = True\" |\n  \"less_natural (succ a) (succ b) = less_natural a b\" |\n  \"less_natural _ _ = False\"\n\nfun less_eq_natural where\n  \"less_eq_natural one _ = True\" |\n  \"less_eq_natural (succ a) (succ b) = less_eq_natural a b\" |\n  \"less_eq_natural _ _ = False\"\n\ninstance by standard end\n\ninstantiation natural :: linorder begin\ninstance proof\n  fix x y z :: natural\n  show \"(x < y) = (x \\<le> y \\<and> \\<not> y \\<le> x)\"\n    by (induction x y rule: less_natural.induct, auto)\n  show \"x \\<le> x\"\n    by (induction x, auto)\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> z \\<Longrightarrow> x \\<le> z\"\n    apply (induction x y arbitrary: z rule: less_eq_natural.induct, auto)\n    apply (metis Natural.natural.distinct(1) Natural.natural.inject less_eq_natural.elims(2) less_eq_natural.elims(3))\n    done\n  show \"x \\<le> y \\<Longrightarrow> y \\<le> x \\<Longrightarrow> x = y\"\n    apply (induction x y arbitrary: z rule: less_eq_natural.induct, auto)\n    using less_eq_natural.elims(2) apply blast\n    done\n  show \"x \\<le> y \\<or> y \\<le> x\"\n    by (induction x y arbitrary: z rule: less_eq_natural.induct, auto)\nqed\nend\n  \nfun to_builtin_nat where\n  \"to_builtin_nat one = Suc 0\" |\n  \"to_builtin_nat (succ n) = Suc (to_builtin_nat n)\"\n\nfun mul_nat where\n  \"mul_nat one n = n\" |\n  \"mul_nat (succ n) m = add_nat m (mul_nat n m)\"\n\nfun succ_abs_diff_nat where\n  \"succ_abs_diff_nat one one = one\" |\n  \"succ_abs_diff_nat one (succ b) = succ b\" |\n  \"succ_abs_diff_nat (succ a) one = succ a\" |\n  \"succ_abs_diff_nat (succ a) (succ b) = succ_abs_diff_nat a b\"\n\nlemma diff_commute: \"succ_abs_diff_nat a b = succ_abs_diff_nat b a\"\n  by (induction a b rule: succ_abs_diff_nat.induct, auto)\n\nlemma less_succ_self [simp]: \"a < succ a\"\n  by (induction a \"succ a\" rule: less_natural.induct, auto)\n\nlemma less_succ: \"a < b \\<Longrightarrow> a < succ b\"\n  by (induction a b rule: less_natural.induct, auto)\n\nlemma diff_inc: \"succ_abs_diff_nat a b = succ_abs_diff_nat (succ a) (succ b)\"\n  by simp\n\nlemma le_inc: \"a < b \\<Longrightarrow> a < succ b\"\n  by (induction a b rule: less_natural.induct, auto)\n\nlemma \"a < b \\<Longrightarrow> succ_abs_diff_nat a b = succ c \\<Longrightarrow> c < b\"\nproof (induction a b arbitrary: c rule: succ_abs_diff_nat.induct)\n  fix a b c\n  assume IH: \"\\<And>c. a < b \\<Longrightarrow> succ_abs_diff_nat a b = succ c \\<Longrightarrow> c < b\"\n  assume \"succ a < succ b\"\n  then have \"a < b\" by simp\n  then have \"succ_abs_diff_nat a b = succ c \\<Longrightarrow> c < b\" using IH by blast\n  then show \"succ_abs_diff_nat (succ a) (succ b) = succ c \\<Longrightarrow> c < succ b\"\n    using diff_inc le_inc by simp\nqed simp+\n\nlemma add_nat_commutative: \"add_nat a b = add_nat b a\"\nproof (induction a b rule: add_nat.induct)\n  fix n\n  show \"add_nat one n = add_nat n one\"\n  proof (simp, induction n one rule: add_nat.induct)\n    show \"succ one = add_nat one one\" by simp\n    fix n\n    assume \"succ n = add_nat n one\"\n    then have \"succ (succ n) = succ (add_nat n one)\" by simp\n    then show \"succ (succ n) = add_nat (succ n) one\"\n      by (simp add: \\<open>succ (succ n) = succ (add_nat n one)\\<close>)\n  qed\nnext\n  fix n m\n  assume IH: \"add_nat n m = add_nat m n\"\n  have \"succ (add_nat m n) = add_nat m (succ n)\"\n    by (induction m n rule: add_nat.induct, auto)\n  then show \"add_nat (succ n) m = add_nat m (succ n)\" using IH by simp\nqed\n  \nlemma diff_res2: \"succ_abs_diff_nat a b = c \\<Longrightarrow> add_nat c a = succ b \\<or> add_nat c b = succ a\"\n  apply (induction a b rule: succ_abs_diff_nat.induct)\n  apply (auto simp add: add_nat_commutative)\n  done\n\nfun leftover_nat where\n  \"leftover_nat one one _ _ = undefined\" |\n  \"leftover_nat (succ a) one _ d = leftover_nat a d a d\" |\n  \"leftover_nat one (succ a) c _ = c\" |\n  \"leftover_nat (succ a) (succ b) c d = leftover_nat a b c d\"\n\ndefinition \"uncurry f ab = f (fst ab, snd ab)\"\ndeclare uncurry_def [simp]\n\nlemma max_cod: \"max a b = c \\<Longrightarrow> a = c \\<or> b = c\"\n  by (metis max_def)\n\nlemma lt_imp_le_nat: \"(a :: natural) < b \\<Longrightarrow> a \\<le> b\"\n  by (induction a b rule: less_natural.induct, auto)\n\nlemma max_res: \"(a :: natural) < b \\<Longrightarrow> max a b = b\"\n  by (simp add: lt_imp_le_nat max_absorb2)\n\nlemma to_builtin_nat_zero [simp]: \"0 < to_builtin_nat a\"\n  by (cases a; auto)\n\nlemma lt_nats: \"a < b \\<Longrightarrow> to_builtin_nat a < to_builtin_nat b\"\n  by (induction a b rule: less_natural.induct; auto)\n\nlemma diff_eq [simp]: \"succ_abs_diff_nat a a = one\"\n  by (induction a, auto)\n\nlemma diff_res [simp]:\n  \"a < b \\<Longrightarrow> succ_abs_diff_nat a b = c \\<Longrightarrow> add_nat a c = succ b\"\n  by (induction a b arbitrary: c rule: succ_abs_diff_nat.induct, auto)\n\nlemma diff_one [simp]: \"succ_abs_diff_nat one a = a\"\n  by (induction a, auto)\n\nlemma \"or_split\": \"(C \\<Longrightarrow> P) \\<Longrightarrow> (\\<not>C \\<Longrightarrow> Q) \\<Longrightarrow> P \\<or> Q\" by auto\n  \nlemma lt_eq_gt_complete_nat:\n  \"((a :: natural) < b \\<Longrightarrow> P) \\<Longrightarrow> (a = b \\<Longrightarrow> P) \\<Longrightarrow> (a > b \\<Longrightarrow> P) \\<Longrightarrow> P\"\n  using not_less_iff_gr_or_eq by blast\n  \nlemma add_nat_res_gt: \"add_nat a b = c \\<Longrightarrow> a < c &&& b < c\"\n  by (induction a b arbitrary: c rule: add_nat.induct, auto simp add: less_succ)\n    \nfunction (sequential) gcd_nat where\n  \"gcd_nat one b = one\" |\n  \"gcd_nat a one = one\" |\n  \"gcd_nat a b = (case succ_abs_diff_nat a b of\n    one \\<Rightarrow> a |\n    succ c \\<Rightarrow> if a < b then gcd_nat a c else gcd_nat b c)\"\nby (pat_completeness, auto)\ntermination\nproof (relation \"measure (\\<lambda>(a,b). to_builtin_nat (max a b))\", auto)\n  fix a b c :: natural\n  assume diff: \"succ_abs_diff_nat a b = succ c\"\n  assume alt: \"a < b\"\n  from diff alt have clt: \"c < b\"\n    apply (induction a b arbitrary: c rule: succ_abs_diff_nat.induct)\n    apply (auto simp add: less_succ) done\n  from alt clt have l: \"max (succ a) c < succ b\"\n    by (metis less_natural.simps(2) less_succ max_cod)\n  from alt have \"succ a < succ b\" by simp\n  then have r: \"max (succ a) (succ b) = succ b\" by (rule max_res)\n  show \"to_builtin_nat (max (succ a) c) < to_builtin_nat (max (succ a) (succ b))\"\n    using l r lt_nats by fastforce\nnext\n  fix a b c :: natural\n  assume c: \"succ_abs_diff_nat a b = succ c\"\n  assume ge: \"\\<not>(a < b)\"\n  have \"max (succ b) c < max (succ a) (succ b)\"\n  proof (rule lt_eq_gt_complete_nat[of a b])\n    assume \"a < b\"\n    then have \"False\" using ge by simp\n    then show ?thesis by simp\n  next\n    assume \"a = b\"\n    then show ?thesis using c by simp\n  next\n    assume gt: \"a > b\"\n    then have sum: \"add_nat b c = a\"\n      by (metis diff_commute natural.inject add_nat.simps(2) add_nat_commutative c diff_res)\n    from gt have nle: \"\\<not>(a \\<le> b)\" by simp\n    have r: \"max (succ a) (succ b) = succ a\"\n      by (subst max_def, auto simp add: nle) \n    from sum have \"c < succ a\" using add_nat_res_gt less_succ by blast\n    show ?thesis by (subst r, auto simp add: gt \\<open>c < succ a\\<close>)\n  qed\n  then show \"to_builtin_nat (max (succ b) c)\n             < to_builtin_nat (max (succ a) (succ b))\"\n    using lt_nats by force\nqed\n\nvalue \"gcd_nat 3 2\"\nvalue \"succ_abs_diff_nat 3 2\"\n\nfun succ_diff_nat where\n  \"succ_diff_nat a one = a\" |\n  \"succ_diff_nat one b = one\" |\n  \"succ_diff_nat (succ a) (succ b) = succ_diff_nat a b\"\n\nlemma add_one_nat [simp]: \"add_nat a one = succ a\"\n  by (simp add: add_nat_commutative)\n    \nlemma add_succ_nat [simp]: \"add_nat a (succ b) = succ (add_nat a b)\"\n  by (induction a \"succ b\" rule: add_nat.induct, auto)\n\nlemma diff_sum: \"(succ_diff_nat a b = succ c) = (c + b = a)\"\n  by (induction a b arbitrary: c rule: succ_diff_nat.induct; simp; blast)\n\nlemma diff_lt: \"(succ_diff_nat a b = succ c) \\<Longrightarrow> c < a\"\n  by (induction a b arbitrary: c rule: succ_diff_nat.induct, auto simp add: less_succ)\n    \ndefinition pred_nat :: \"(natural \\<times> natural) set\" where\n  \"pred_nat = {(m, n). n = succ m}\"\n  \ndefinition less_than :: \"(natural \\<times> natural) set\"\n  where \"less_than = pred_nat\\<^sup>+\"\n\ndefinition measure :: \"('a \\<Rightarrow> natural) \\<Rightarrow> ('a \\<times> 'a) set\"\n  where \"measure = inv_image less_than\"\n\nlemma wf_pred_nat: \"wf pred_nat\"\n  apply (unfold wf_def pred_nat_def)\n  apply clarify\n  apply (induct_tac x)\n   apply blast+\n  done\n\nlemma wf_less_than [iff]: \"wf less_than\"\n  by (simp add: less_than_def wf_pred_nat [THEN wf_trancl])\n\nlemma wf_measure [iff]: \"wf (measure f)\"\n  unfolding measure_def\n  by (rule wf_less_than [THEN wf_inv_image])\n\nfunction div_nat where\n  \"div_nat a b = (case succ_diff_nat a b of\n    one \\<Rightarrow> one |\n    succ c \\<Rightarrow> succ (div_nat c b))\"\n  by auto\ntermination\nproof (relation \"measure (\\<lambda>(a, _) \\<Rightarrow> a)\")\n  show \"wf (Natural.measure (\\<lambda>x. case x of (a, x) \\<Rightarrow> a))\"\n    by blast\n  fix a b c\n  assume diff: \"succ_diff_nat a b = succ c\"\n  then have \"c < a\"\n    by (induction a b arbitrary: c rule: succ_diff_nat.induct, auto simp: less_succ)\n  from diff have \"((\\<lambda>x xa. xa = succ x) ^^ to_builtin_nat b) c a\"\n  proof (induction b arbitrary: a)\n    fix a\n    assume \"succ_diff_nat a one = succ c\"\n    then show \"((\\<lambda>x xa. xa = succ x) ^^ to_builtin_nat one) c a\" by auto\n  next\n    fix b a\n    assume IH: \"(\\<And>a. succ_diff_nat a b = succ c \\<Longrightarrow>\n                ((\\<lambda>x xa. xa = succ x) ^^ to_builtin_nat b) c a)\"\n    assume assm: \"succ_diff_nat a (succ b) = succ c\"\n    then obtain d where d: \"a = succ d\" by (cases a, auto)\n    from d assm have \"succ_diff_nat d b = succ c\" by force\n    then have \"((\\<lambda>x xa. xa = succ x) ^^ to_builtin_nat b) c d\" using IH by blast\n    then show \"((\\<lambda>x xa. xa = succ x) ^^ to_builtin_nat (succ b)) c a\" \n      by (auto simp: funpow_Suc_right d)\n  qed\n  then show \"((c, b), a, b) \\<in> measure (\\<lambda>x. case x of (a, x) \\<Rightarrow> a)\"\n    apply (simp add: measure_def less_than_def pred_nat_def trancl_def)\n    apply (subst tranclp_power)\n    apply (rule exI[of _ \"to_builtin_nat b\"])\n    apply (simp)\n    done\nqed\n    \nlemma div_one [simp]: \"div_nat_h a one one = a\"\n  apply (induction a one one rule: div_nat.induct, auto)\n\nlemma mul_one [simp]: \"mul_nat a one = a\"\n  by (induction a, auto)\n\nlemma mul_succ [simp]: \"mul_nat a (succ b) = add_nat a (mul_nat a b)\"\n  apply (induction a \"succ b\" rule: mul_nat.induct)\n   apply (auto)\n  using add_nat_associative add_nat_commutative apply auto\n  done\n    \nlemma mul_commute_nat: \"mul_nat a b = mul_nat b a\"\n  by (induction a b rule: mul_nat.induct, auto)\n\ndefinition \"divides_nat a b = (\\<exists>c. mul_nat a c = b)\"\n\nlemma mul_div_nat: \"divides_nat a b \\<Longrightarrow> mul_nat a (div_nat b a) = b\"\nproof (induction a \"div_nat a b\" arbitrary: b rule: mul_nat.induct, auto)\n  show base: \"mul_nat one (div_nat b one) = b\" by simp\n  fix a\n  assume IH: \"divides_nat a b \\<Longrightarrow> mul_nat a (div_nat b a) = b\"\n    \n    \n    \nlemma mul_div_commute_nat:\n  \"divides_nat c b \\<Longrightarrow> mul_nat a (div_nat b c) = div_nat (mul_nat a b) c\" (is \"_ \\<Longrightarrow> ?a = ?b\")\nproof -\n  assume hyp: \"divides_nat c b\"\n  \n(*\nlemma \"gcd_nat a b = c \\<Longrightarrow> mul_nat a (div_nat b c) = mul_nat (div_nat a c) b\"\nproof (induction a b arbitrary: c rule: gcd_nat.induct, simp, simp)\n  fix a b c\n  assume IH:\n    \"\\<And>d e. succ_abs_diff_nat (succ a)\n            (succ b) =\n           succ d \\<Longrightarrow>\n           succ a < succ b \\<Longrightarrow>\n           gcd_nat (succ a) d = e \\<Longrightarrow>\n           mul_nat (succ a) (div_nat d e) =\n           mul_nat (div_nat (succ a) e) d\"\n    \"\\<And>d e. succ_abs_diff_nat (succ a)\n            (succ b) =\n           succ d \\<Longrightarrow>\n           \\<not> succ a < succ b \\<Longrightarrow>\n           gcd_nat (succ b) d = e \\<Longrightarrow>\n           mul_nat (succ b) (div_nat d e) =\n           mul_nat (div_nat (succ b) e) d\"\n  assume c: \"gcd_nat (succ a) (succ b) = c\"\n  obtain sd where sd: \"succ_abs_diff_nat (succ a) (succ b) = sd\" by simp\n  show \"mul_nat (succ a) (div_nat (succ b) c) =\n        mul_nat (div_nat (succ a) c) (succ b)\" *)\n\nend", "meta": {"author": "AtnNn", "repo": "isabelle-learn", "sha": "da71fb60bea0089fe473c104be16a4545e031be8", "save_path": "github-repos/isabelle/AtnNn-isabelle-learn", "path": "github-repos/isabelle/AtnNn-isabelle-learn/isabelle-learn-da71fb60bea0089fe473c104be16a4545e031be8/knopp-infinite-series/Natural.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.8479677602988601, "lm_q1q2_score": 0.7523208973191063}}
{"text": "(*\n    $Id: ex.thy,v 1.2 2004/11/23 15:14:34 webertj Exp $\n    Author: Gerwin Klein\n*)\n\nheader {* Quantifying Lists *}\n\n(*<*) theory ex imports Main begin (*>*)\n\ntext {* Define a universal and an existential quantifier on lists\nusing primitive recursion.  Expression @{term \"alls P xs\"} should\nbe true iff @{term \"P x\"} holds for every element @{term x} of\n@{term xs}, and @{term \"exs P xs\"} should be true iff @{term \"P x\"}\nholds for some element @{term x} of @{term xs}.\n*}\n\nconsts \n  alls :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n  exs  :: \"('a \\<Rightarrow> bool) \\<Rightarrow> 'a list \\<Rightarrow> bool\"\n\ntext {*\nProve or disprove (by counterexample) the following theorems.\nYou may have to prove some lemmas first.\n\nUse the @{text \"[simp]\"}-attribute only if the equation is truly a\nsimplification and is necessary for some later proof.\n*}\n\nlemma \"alls (\\<lambda>x. P x \\<and> Q x) xs = (alls P xs \\<and> alls Q xs)\"\n(*<*)oops(*>*)\n\nlemma \"alls P (rev xs) = alls P xs\"\n(*<*)oops(*>*)\n\nlemma \"exs (\\<lambda>x. P x \\<and> Q x) xs = (exs P xs \\<and> exs Q xs)\"\n(*<*)oops(*>*)\n\nlemma \"exs P (map f xs) = exs (P o f) xs\"\n(*<*)oops(*>*)\n\nlemma \"exs P (rev xs) = exs P xs\"\n(*<*)oops(*>*)\n\ntext {* Find a (non-trivial) term @{text Z} such that the following equation holds: *}\n\nlemma \"exs (\\<lambda>x. P x \\<or> Q x) xs = Z\"\n(*<*)oops(*>*)\n\ntext {* Express the existential via the universal quantifier --\n@{text exs} should not occur on the right-hand side: *}\n\nlemma \"exs P xs = Z\"\n(*<*)oops(*>*)\n\ntext {*\nDefine a primitive-recursive function @{term \"is_in x xs\"} that\nchecks if @{term x} occurs in @{term xs}. Now express\n@{text is_in} via @{term exs}:\n*}\n\nlemma \"is_in a xs = Z\"\n(*<*)oops(*>*)\n\ntext {* Define a primitive-recursive function @{term \"nodups xs\"}\nthat is true iff @{term xs} does not contain duplicates, and a\nfunction @{term \"deldups xs\"} that removes all duplicates.  Note\nthat @{term \"deldups[x,y,x]\"} (where @{term x} and @{term y} are\ndistinct) can be either @{term \"[x,y]\"} or @{term \"[y,x]\"}.\n\nProve or disprove (by counterexample) the following theorems.\n*}\n\nlemma \"length (deldups xs) <= length xs\"\n(*<*)oops(*>*)\n\nlemma \"nodups (deldups xs)\"\n(*<*)oops(*>*)\n\nlemma \"deldups (rev xs) = rev (deldups xs)\"\n(*<*)oops(*>*)\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/isabelle.in.tum.de/exercises/lists/quant/ex.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8872046056466901, "lm_q1q2_score": 0.7523208904466027}}
{"text": "theory MyTree\n  \n  imports Main\n    \nbegin\n  \n  (* declare [[names_short]] *)\n  \ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n  \n  (*\nExercise 2.6. \nStarting from the type 'a tree defined in the text, define a function\ncontents :: 'a tree \\<Rightarrow> 'a list that collects all values in a tree in a list,\nin any order, without removing duplicates. \nThen define a function \ntreesum :: nat tree \\<Rightarrow> nat \nthat sums up all values in a tree of natural numbers and prove\ntreesum t = listsum (contents t)\n  *)\n  \nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n  \"contents Tip = Nil\" |\n  \"contents (Node l x r) = (contents l) @ (x # (contents r))\"\n  \nfun treesum :: \"nat tree \\<Rightarrow> nat\" where\n  \"treesum Tip = 0\" |\n  \"treesum (Node l x r) = (treesum l) + x + (treesum r)\"\n  \nfun listsum :: \"nat list \\<Rightarrow> nat\" where\n  \"listsum [] = 0\" |\n  \"listsum (x # xs) = x + (listsum xs)\"\n  \nlemma l0 [simp] : \"listsum(xs @ ys) = (listsum xs) + (listsum ys)\"\n  apply(induction xs)\n   apply(auto)\n  done\n    \ntheorem treesum_is_listsum_of_contents: \"treesum t = listsum (contents t)\"\n  apply(induction t)\n   apply(auto)\n  done\n", "meta": {"author": "paolo-crisafulli", "repo": "isabelle_tutorial", "sha": "5a11cf22ff0c7cd07de5d74a8d6aa0636bed0327", "save_path": "github-repos/isabelle/paolo-crisafulli-isabelle_tutorial", "path": "github-repos/isabelle/paolo-crisafulli-isabelle_tutorial/isabelle_tutorial-5a11cf22ff0c7cd07de5d74a8d6aa0636bed0327/MyTree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.8479677526147223, "lm_q1q2_score": 0.7523208829147773}}
{"text": "section \"General VS Proofs\"\nsubsection \"Univariate Atoms\"\ntheory UniAtoms\n  imports Debruijn\nbegin\n\ndatatype atomUni = LessUni \"real * real * real\" | EqUni \"real * real * real\" | LeqUni \"real * real * real\" | NeqUni \"real * real * real\"\ndatatype (atoms: 'a) fmUni =\n  TrueFUni | FalseFUni | AtomUni 'a | AndUni \"'a fmUni\" \"'a fmUni\" | OrUni \"'a fmUni\" \"'a fmUni\" \n\nfun aEvalUni :: \"atomUni \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"aEvalUni (EqUni (a,b,c)) x = (a*x^2+b*x+c = 0)\" |\n  \"aEvalUni (LessUni (a,b,c)) x = (a*x^2+b*x+c < 0)\" |\n  \"aEvalUni (LeqUni (a,b,c)) x = (a*x^2+b*x+c \\<le> 0)\" |\n  \"aEvalUni (NeqUni (a,b,c)) x = (a*x^2+b*x+c \\<noteq> 0)\"\n\nfun aNegUni :: \"atomUni \\<Rightarrow> atomUni\" where\n  \"aNegUni (LessUni (a,b,c)) = LeqUni (-a,-b,-c)\" |\n  \"aNegUni (EqUni p) = NeqUni p\" |\n  \"aNegUni (LeqUni (a,b,c)) = LessUni (-a,-b,-c)\" |\n  \"aNegUni (NeqUni p) = EqUni p\"\n\n\nfun evalUni :: \"atomUni fmUni \\<Rightarrow> real \\<Rightarrow> bool\" where\n  \"evalUni (AtomUni a) x = aEvalUni a x\" |\n  \"evalUni (TrueFUni) _ = True\" |\n  \"evalUni (FalseFUni) _ = False\" |\n  \"evalUni (AndUni \\<phi> \\<psi>) x = ((evalUni \\<phi> x) \\<and> (evalUni \\<psi> x))\" |\n  \"evalUni (OrUni \\<phi> \\<psi>) x = ((evalUni \\<phi> x) \\<or> (evalUni \\<psi> x))\"\n\n\nfun negUni :: \"atomUni fmUni \\<Rightarrow> atomUni fmUni\" where\n  \"negUni (AtomUni a) = AtomUni(aNegUni a)\" |\n  \"negUni (TrueFUni) = FalseFUni\" |\n  \"negUni (FalseFUni) = TrueFUni\" |\n  \"negUni (AndUni \\<phi> \\<psi>) = (OrUni (negUni \\<phi>) (negUni \\<psi>))\" |\n  \"negUni (OrUni \\<phi> \\<psi>) = (AndUni (negUni \\<phi>) (negUni \\<psi>))\"\n\nfun convert_poly :: \"nat \\<Rightarrow> real mpoly \\<Rightarrow> real list \\<Rightarrow> (real * real * real) option\" where\n  \"convert_poly var p xs = (\n  if MPoly_Type.degree p var < 3\n  then let (A,B,C) = get_coeffs var p in Some(insertion (nth_default 0 (xs)) A,insertion (nth_default 0 (xs)) B,insertion (nth_default 0 (xs)) C)\n else None)\"\n\nfun convert_atom :: \"nat \\<Rightarrow> atom \\<Rightarrow> real list \\<Rightarrow> atomUni option\" where\n  \"convert_atom var (Less p) xs = map_option LessUni (convert_poly var p xs)\"|\n  \"convert_atom var (Eq p) xs = map_option EqUni (convert_poly var p xs)\"|\n  \"convert_atom var (Leq p) xs = map_option LeqUni (convert_poly var p xs)\"|\n  \"convert_atom var (Neq p) xs = map_option NeqUni (convert_poly var p xs)\"\n\nlemma convert_atom_change :\n  assumes \"length xs' = var\"\n  shows \"convert_atom var At (xs' @ x # \\<Gamma>) = convert_atom var At (xs' @ x' # \\<Gamma>)\"\n  apply(cases At)using assms apply simp_all\n  by (metis insertion_lowerPoly1 not_in_isovarspar)+\n\nlemma degree_convert_eq : \n  assumes \"convert_poly var p xs = Some(a)\"\n  shows \"MPoly_Type.degree p var < 3\"\n  using assms apply(cases \"MPoly_Type.degree p var < 3\") by auto\n\nlemma poly_to_univar :\n  assumes \"MPoly_Type.degree p var < 3\"\n  assumes \"get_coeffs var p = (A,B,C)\"\n  assumes \"a = insertion (nth_default 0 (xs'@y#xs)) A\"\n  assumes \"b = insertion (nth_default 0 (xs'@y#xs)) B\"\n  assumes \"c = insertion (nth_default 0 (xs'@y#xs)) C\"\n  assumes \"length xs' = var\"\n  shows \"insertion (nth_default 0 (xs'@x#xs)) p = (a*x^2)+(b*x)+c\"\nproof-\n  have ha: \"\\<And>x. a = insertion (nth_default 0 (xs'@x # xs)) A\" using assms(2) apply auto\n    by (metis assms(3) assms(6) insertion_lowerPoly1 not_in_isovarspar)\n  have hb: \"\\<And>x. b = insertion (nth_default 0 (xs'@x # xs)) B\" using assms(2) apply auto\n    by (metis assms(4) assms(6) insertion_lowerPoly1 not_in_isovarspar)\n  have hc: \"\\<And>x. c = insertion (nth_default 0 (xs'@x # xs)) C\" using assms(2) apply auto\n    by (metis assms(5) assms(6) insertion_lowerPoly1 not_in_isovarspar)\n  show ?thesis\n  proof(cases \"MPoly_Type.degree p var = 0\")\n    case True\n    have h1 : \"var < length (xs'@x#xs)\" using assms by auto\n    show ?thesis using assms ha hb hc sum_over_degree_insertion[OF h1 True, of y] apply(simp add: isovar_greater_degree[of p ] True)\n      using True degree0isovarspar by force\n  next\n    case False\n    then have notzero : \"MPoly_Type.degree p var \\<noteq> 0\" by auto\n    show ?thesis proof(cases \"MPoly_Type.degree p var = 1\" )\n      case True\n      have h1 : \"var < length (xs'@x#xs)\" using assms by auto\n      show ?thesis using  sum_over_degree_insertion[OF h1 True, of x,  symmetric] unfolding assms(6)[symmetric] list_update_length unfolding assms(6) apply simp using ha hb hc assms apply auto\n        by (smt (verit, ccfv_threshold) One_nat_def True express_poly h1 insertion_add insertion_mult insertion_pow insertion_var list_update_length)    \n    next\n      case False\n      then have deg2 : \"MPoly_Type.degree p var = 2\" using notzero assms by auto\n      have h1 : \"var < length (xs'@x#xs)\" using assms by auto\n      have two : \"2 = Suc(Suc 0)\" by auto\n      show ?thesis\n        using  sum_over_degree_insertion[OF h1 deg2, of x,  symmetric] unfolding assms(6)[symmetric] list_update_length unfolding assms(6) two apply simp using ha hb hc assms apply auto\n        using deg2 express_poly h1 insertion_add insertion_mult insertion_pow insertion_var list_update_length\n        by (smt (verit, best) numeral_2_eq_2)\n    qed\n  qed\nqed\n\nlemma \"aEval_aEvalUni\":\n  assumes \"convert_atom var a (xs'@x#xs) = Some a'\"\n  assumes \"length xs' = var\"\n  shows \"aEval a (xs'@x#xs) = aEvalUni a' x\"\nproof(cases a)\n  case (Less x)\n  then show ?thesis\n  proof(cases \"MPoly_Type.degree x var < 3\")\n    case True\n    then show ?thesis\n      using assms apply(simp add:Less)\n      using poly_to_univar[OF True]\n      by (metis One_nat_def aEvalUni.simps(2) get_coeffs.elims) \n  next\n    case False\n    then show ?thesis using assms Less by auto\n  qed\nnext\n  case (Eq x)\n  then show ?thesis\n  proof(cases \"MPoly_Type.degree x var < 3\")\n    case True\n    then show ?thesis\n      using assms apply(simp add:Eq)\n      using poly_to_univar[OF True]\n      by (metis One_nat_def aEvalUni.simps(1) get_coeffs.elims) \n  next\n    case False\n    then show ?thesis using assms Eq by auto\n  qed\nnext\n  case (Leq x)\n  then show ?thesis\n  proof(cases \"MPoly_Type.degree x var < 3\")\n    case True\n    then show ?thesis\n      using assms apply(simp add:Leq)\n      using poly_to_univar[OF True]\n      by (metis One_nat_def aEvalUni.simps(3) get_coeffs.elims) \n  next\n    case False\n    then show ?thesis using assms Leq by auto\n  qed\nnext\n  case (Neq x)\n  then show ?thesis\n  proof(cases \"MPoly_Type.degree x var < 3\")\n    case True\n    then show ?thesis\n      using assms apply(simp add:Neq)\n      using poly_to_univar[OF True]\n      by (metis One_nat_def aEvalUni.simps(4) get_coeffs.elims) \n  next\n    case False\n    then show ?thesis using assms Neq by auto\n  qed\nqed\n\n\nfun convert_fm :: \"nat \\<Rightarrow> atom fm \\<Rightarrow> real list \\<Rightarrow> (atomUni fmUni) option\" where\n  \"convert_fm var (Atom a) \\<Gamma> = map_option (AtomUni) (convert_atom var a \\<Gamma>)\" |\n  \"convert_fm var (TrueF) _ = Some TrueFUni\" |\n  \"convert_fm var (FalseF) _ = Some FalseFUni\" |\n  \"convert_fm var (And \\<phi> \\<psi>) \\<Gamma> = (case ((convert_fm var \\<phi> \\<Gamma>),(convert_fm var \\<psi> \\<Gamma>)) of (Some a, Some b) \\<Rightarrow> Some (AndUni a b) | _ \\<Rightarrow> None)\" |\n  \"convert_fm var (Or \\<phi> \\<psi>) \\<Gamma> = (case ((convert_fm var \\<phi> \\<Gamma>),(convert_fm var \\<psi> \\<Gamma>)) of (Some a, Some b) \\<Rightarrow> Some (OrUni a b) | _ \\<Rightarrow> None)\" |\n  \"convert_fm var (Neg \\<phi>) \\<Gamma> = None \" |\n  \"convert_fm var (ExQ \\<phi>) \\<Gamma> = None\" |\n  \"convert_fm var (AllQ \\<phi>) \\<Gamma> = None\"|\n  \"convert_fm var (AllN i \\<phi>) \\<Gamma> = None\"|\n  \"convert_fm var (ExN i \\<phi>) \\<Gamma> = None\"\n\n\nlemma \"eval_evalUni\":\n  assumes \"convert_fm var F (xs'@x#xs) = Some F'\"\n  assumes \"length xs' = var\"\n  shows \"eval F (xs'@x#xs) = evalUni F' x\"\n  using assms\nproof(induction F arbitrary: F')\n  case TrueF\n  then show ?case by auto\nnext\n  case FalseF\n  then show ?case by auto\nnext\n  case (Atom x)\n  then show ?case using aEval_aEvalUni by auto\nnext\n  case (And F1 F2)\n  then show ?case apply(cases \"convert_fm var F1 (xs'@x#xs)\") apply simp apply(cases \"convert_fm var F2 (xs'@x#xs)\") by auto\nnext\n  case (Or F1 F2)\n  then show ?case apply(cases \"convert_fm var F1 (xs'@x#xs)\") apply simp apply(cases \"convert_fm var F2 (xs'@x#xs)\") by auto\nnext\n  case (Neg F)\n  then show ?case by auto\nnext\n  case (ExQ F)\n  then show ?case by auto\nnext\n  case (AllQ F)\n  then show ?case by auto\nnext\n  case (ExN x1 \\<phi>)\n  then show ?case by auto\nnext\n  case (AllN x1 \\<phi>)\n  then show ?case by auto\nqed\n\nfun grab_atoms :: \"nat \\<Rightarrow> atom fm \\<Rightarrow> atom list option\" where\n  \"grab_atoms var TrueF = Some([])\" |\n  \"grab_atoms var FalseF = Some([])\" |\n  \"grab_atoms var (Atom(Eq p)) = (if MPoly_Type.degree p var < 3 then (if MPoly_Type.degree p var > 0 then Some([Eq p]) else Some([])) else None)\"|\n  \"grab_atoms var (Atom(Less p)) = (if MPoly_Type.degree p var < 3 then (if MPoly_Type.degree p var > 0 then Some([Less p]) else Some([])) else None)\"|\n  \"grab_atoms var (Atom(Leq p)) = (if MPoly_Type.degree p var < 3 then (if MPoly_Type.degree p var > 0 then Some([Leq p]) else Some([])) else None)\"|\n  \"grab_atoms var (Atom(Neq p)) = (if MPoly_Type.degree p var < 3 then (if MPoly_Type.degree p var > 0 then Some([Neq p]) else Some([])) else None)\"|\n  \"grab_atoms var (And a b) = (\ncase grab_atoms var a of \n  Some(al) \\<Rightarrow> (\n    case grab_atoms var b of\n      Some(bl) \\<Rightarrow> Some(al@bl)\n    | None \\<Rightarrow> None\n  )\n| None \\<Rightarrow> None\n)\"|\n  \"grab_atoms var (Or a b) = (\ncase grab_atoms var a of \n  Some(al) \\<Rightarrow> (\n    case grab_atoms var b of\n      Some(bl) \\<Rightarrow> Some(al@bl)\n    | None \\<Rightarrow> None\n  )\n| None \\<Rightarrow> None\n)\"|\n\n\"grab_atoms var (Neg _) = None\"|\n\"grab_atoms var (ExQ _) = None\"|\n\"grab_atoms var (AllQ _) = None\"|\n\"grab_atoms var (AllN i _) = None\"|\n\"grab_atoms var (ExN i _) = None\"\n\n\n\nlemma nil_grab : \"(grab_atoms var F = Some []) \\<Longrightarrow> (freeIn var F)\"\nproof(induction F)\n  case TrueF\n  then show ?case by auto\nnext\n  case FalseF\n  then show ?case by auto\nnext\n  case (Atom x)\n  then show ?case proof(cases x)\n    case (Less p)\n    then show ?thesis using Atom apply(cases \"MPoly_Type.degree p var < 3\") apply auto apply(cases \"MPoly_Type.degree p var > 0\") apply auto\n      using degree0isovarspar not_in_isovarspar by blast\n  next\n    case (Eq p)\n    then show ?thesis using Atom apply(cases \"MPoly_Type.degree p var < 3\") apply auto apply(cases \"MPoly_Type.degree p var > 0\") apply auto\n      using degree0isovarspar not_in_isovarspar by blast\n  next\n    case (Leq p)\n    then show ?thesis using Atom apply(cases \"MPoly_Type.degree p var < 3\") apply auto apply(cases \"MPoly_Type.degree p var > 0\") apply auto\n      using degree0isovarspar not_in_isovarspar by blast\n  next\n    case (Neq p)\n    then show ?thesis using Atom apply(cases \"MPoly_Type.degree p var < 3\") apply auto apply(cases \"MPoly_Type.degree p var > 0\") apply auto\n      using degree0isovarspar not_in_isovarspar by blast\n  qed\nnext\n  case (And F1 F2)\n  then show ?case apply(cases \"grab_atoms var F1\")\n    apply(cases \"grab_atoms var F2\") apply(auto)\n    apply(cases \"grab_atoms var F2\") apply(auto)\n    apply(cases \"grab_atoms var F2\") by(auto)\nnext\n  case (Or F1 F2)\n  then show ?case apply(cases \"grab_atoms var F1\")\n    apply(cases \"grab_atoms var F2\") apply(auto)\n    apply(cases \"grab_atoms var F2\") apply(auto)\n    apply(cases \"grab_atoms var F2\") by(auto)\nnext\n  case (Neg F)\n  then show ?case by auto\nnext\n  case (ExQ F)\n  then show ?case by auto\nnext\n  case (AllQ F)\n  then show ?case by auto\nnext\n  case (ExN x1 F)\n  then show ?case by auto\nnext\n  case (AllN x1 F)\n  then show ?case by auto\nqed\n\nfun isSome :: \"'a option \\<Rightarrow> bool\" where\n  \"isSome (Some _) = True\" |\n  \"isSome None = False\"\n\nlemma \"grab_atoms_convert\" : \"(isSome (grab_atoms var F)) = (isSome (convert_fm var F xs))\"\nproof(induction F)\n  case TrueF\n  then show ?case by auto\nnext\n  case FalseF\n  then show ?case by auto\nnext\n  case (Atom a)\n  then show ?case apply(cases a) by auto\nnext\n  case (And F1 F2)\n  then show ?case\n    by (smt convert_fm.simps(4) grab_atoms.simps(7) isSome.elims(2) isSome.elims(3) option.distinct(1) option.simps(5) option.split_sel_asm prod.simps(2)) \nnext\n  case (Or F1 F2)\n  then show ?case\n    by (smt convert_fm.simps(5) grab_atoms.simps(8) isSome.elims(2) isSome.elims(3) option.distinct(1) option.simps(5) option.split_sel_asm prod.simps(2))\nnext\n  case (Neg F)\n  then show ?case by auto\nnext\n  case (ExQ F)\n  then show ?case by auto\nnext\n  case (AllQ F)\n  then show ?case by auto\nnext\n  case (ExN x1 F)\n  then show ?case by auto\nnext\n  case (AllN x1 F)\n  then show ?case by auto\nqed\n\nlemma convert_aNeg :\n  assumes \"convert_atom var A (xs'@x#xs) = Some(A')\"\n  assumes \"length xs' = var\"\n  shows \"aEval (aNeg A) (xs'@x#xs) = aEvalUni (aNegUni A') x\"\nproof-\n  have \"aEval (aNeg A) (xs'@x#xs) = (\\<not> aEval A (xs'@x#xs))\"\n    using aNeg_aEval[of A \"(xs'@x#xs)\"] by auto\n  also have \"... = (\\<not> aEvalUni A' x)\"\n    using assms aEval_aEvalUni by auto\n  also have \"... = aEvalUni (aNegUni A') x\"\n    by(cases A')(auto)\n  finally show ?thesis .\nqed\n\nlemma convert_neg : \n  assumes \"convert_fm var F (xs'@x#xs) = Some(F')\"\n  assumes \"length xs' = var\"\n  shows \"eval (Neg F) (xs'@x#xs) = evalUni (negUni F') x\"\n  using assms\nproof(induction F arbitrary:F')\n  case TrueF\n  then show ?case by auto\nnext\n  case FalseF\n  then show ?case by auto\nnext\n  case (Atom p)\n  then show ?case\n    using convert_aNeg[of _ p]\n    by (smt aNeg_aEval convert_fm.simps(1) evalUni.simps(1) eval.simps(1) eval.simps(6) map_option_eq_Some negUni.simps(1)) \nnext\n  case (And F1 F2)\n  then show ?case apply auto\n    apply (metis (no_types, lifting) evalUni.simps(5) negUni.simps(4) option.case_eq_if option.collapse option.distinct(1) option.sel)\n    apply (smt (verit, del_insts) evalUni.simps(5) isSome.elims(1) negUni.simps(4) option.inject option.simps(4) option.simps(5))\n    by (smt (verit, del_insts) evalUni.simps(5) isSome.elims(1) negUni.simps(4) option.inject option.simps(4) option.simps(5))\nnext\n  case (Or F1 F2)\n  then show ?case apply auto\n    apply (smt (verit, del_insts) evalUni.simps(4) isSome.elims(1) negUni.simps(5) option.inject option.simps(4) option.simps(5))\n    apply (smt (verit, del_insts) evalUni.simps(4) isSome.elims(1) negUni.simps(5) option.inject option.simps(4) option.simps(5))\n    by (smt (verit, del_insts) evalUni.simps(4) isSome.elims(1) negUni.simps(5) option.inject option.simps(4) option.simps(5))\nnext\n  case (Neg F)\n  then show ?case by auto\nnext\n  case (ExQ F)\n  then show ?case by auto\nnext\n  case (AllQ F)\n  then show ?case by auto\nnext\n  case (ExN x1 F)\n  then show ?case by auto\nnext\n  case (AllN x1 F)\n  then show ?case by auto\nqed\n\n\nfun list_disj_Uni :: \"'a fmUni list \\<Rightarrow> 'a fmUni\" where\n  \"list_disj_Uni [] = FalseFUni\"|\n  \"list_disj_Uni (x#xs) = OrUni x (list_disj_Uni xs)\"\n\nfun list_conj_Uni :: \"'a fmUni list \\<Rightarrow> 'a fmUni\" where\n  \"list_conj_Uni [] = TrueFUni\"|\n  \"list_conj_Uni (x#xs) = AndUni x (list_conj_Uni xs)\"\n\nlemma eval_list_disj_Uni : \"evalUni (list_disj_Uni L) x = (\\<exists>l\\<in>set(L). evalUni l x)\"\n  by(induction L)(auto)\n\nlemma eval_list_conj_Uni : \"evalUni (list_conj_Uni A) x = (\\<forall>l\\<in>set A. evalUni l x)\"\n  apply(induction A)by auto\n\nlemma eval_list_conj_Uni_append : \"evalUni (list_conj_Uni (A @ B)) x = (evalUni (list_conj_Uni (A)) x \\<and> evalUni (list_conj_Uni (B)) x)\"\n  apply(induction A)by auto\n\nfun map_atomUni :: \"('a \\<Rightarrow> 'a fmUni) \\<Rightarrow> 'a fmUni \\<Rightarrow> 'a fmUni\" where\n  \"map_atomUni f (AtomUni a) = f a\" |\n  \"map_atomUni f (TrueFUni) = TrueFUni\" |\n  \"map_atomUni f (FalseFUni) = FalseFUni\" |\n  \"map_atomUni f (AndUni \\<phi> \\<psi>) = (AndUni (map_atomUni f \\<phi>) (map_atomUni f \\<psi>))\" |\n  \"map_atomUni f (OrUni \\<phi> \\<psi>) = (OrUni (map_atomUni f \\<phi>) (map_atomUni f \\<psi>))\"\n\nfun map_atom :: \"(atom \\<Rightarrow> atom fm) \\<Rightarrow> atom fm \\<Rightarrow> atom fm\" where\n  \"map_atom f TrueF = TrueF\"|\n  \"map_atom f FalseF = FalseF\"|\n  \"map_atom f (Atom a) = f a\"|\n  \"map_atom f (And \\<phi> \\<psi>) = And (map_atom f \\<phi>) (map_atom f \\<psi>)\"|\n  \"map_atom f (Or \\<phi> \\<psi>) = Or (map_atom f \\<phi>) (map_atom f \\<psi>)\"|\n  \"map_atom f (Neg \\<phi>) = TrueF\"|\n  \"map_atom f (ExQ \\<phi>) = TrueF\"|\n  \"map_atom f (AllQ \\<phi>) = TrueF\"|\n  \"map_atom f (ExN i \\<phi>) = TrueF\"|\n  \"map_atom f (AllN i \\<phi>) = TrueF\"\n\nfun getPoly :: \"atomUni => real * real * real\" where\n  \"getPoly (EqUni p) = p\"|\n  \"getPoly (LeqUni p) = p\"|\n  \"getPoly (NeqUni p) = p\"|\n  \"getPoly (LessUni p) = p\"\n\nlemma liftatom_map_atom : \n  assumes \"\\<exists>F'. convert_fm var F xs = Some F'\"\n  shows \"liftmap f F 0 = map_atom (f 0) F\"\n  using assms\n  apply(induction F)\n  apply(auto)\n  apply fastforce\n  apply (metis (no_types, lifting) isSome.elims(2) isSome.elims(3) option.case_eq_if)\n  apply fastforce\n  by (metis (no_types, lifting) isSome.elims(2) isSome.elims(3) option.case_eq_if)\n\n\nlemma eval_map : \"(\\<exists>l\\<in>set(map f L). evalUni l x) = (\\<exists>l\\<in>set(L). evalUni (f l) x)\"\n  by auto\n\nlemma eval_map_all : \"(\\<forall>l\\<in>set(map f L). evalUni l x) = (\\<forall>l\\<in>set(L). evalUni (f l) x)\"\n  by auto\n\nlemma eval_append : \"(\\<exists>l\\<in>set (A#B).evalUni l x) = (evalUni A x \\<or> (\\<exists>l\\<in>set (B).evalUni l x))\"\n  by auto\n\nlemma eval_conj_atom : \"evalUni (list_conj_Uni (map AtomUni L)) x = (\\<forall>l\\<in>set(L). aEvalUni l x)\"\n  unfolding eval_list_conj_Uni\n  by auto\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Virtual_Substitution/UniAtoms.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769413, "lm_q2_score": 0.8244619306896956, "lm_q1q2_score": 0.752268878497912}}
{"text": "theory SList\nimports Main\nbegin\n\nfun valid_set :: \"'a::linorder list \\<Rightarrow> bool\" where\n  \"valid_set x = (List.distinct x \\<and> List.sorted x)\"\n\ndefinition empty :: \"'a::linorder list\" where\n  \"empty = Nil\"\n\nlemma valid_empty : \"valid_set empty\"\n  by (simp add:SList.empty_def)\n\nfun insert :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"insert a Nil = Cons a Nil\" |\n  \"insert a (Cons x z) =\n    (if a < x\n     then (Cons a (Cons x z))\n     else (if a > x\n           then (Cons x (insert a z))\n           else (Cons x z)))\"\n\nlemma insert_in_middle : \"x < a \\<Longrightarrow> valid_set (a # z)\n                            \\<Longrightarrow> valid_set (x # a # z)\"\n  by auto\n\nlemma remove_from_middle : \"valid_set (x # a # z) \\<Longrightarrow> x < a\"\n  by auto\n\nlemma sublist_valid : \"valid_set (x # c) \\<Longrightarrow>\n                       valid_set c\"\n  by simp\n\nlemma insert_valid_aux :\n  \"x < a \\<Longrightarrow>\n   valid_set (x # c) \\<Longrightarrow>\n   valid_set (SList.insert a c) \\<Longrightarrow>\n   valid_set (x # SList.insert a c)\"\n  apply (induction c arbitrary: a x)\n  apply auto[1]\n  by (metis insert.simps(2) insert_in_middle remove_from_middle)\n\nlemma insert_valid_aux2 :\n  \"(\\<And>a. valid_set c \\<Longrightarrow> valid_set (SList.insert a c)) \\<Longrightarrow>\n    valid_set (x # c) \\<Longrightarrow>\n    x < a \\<Longrightarrow>\n    valid_set (x # SList.insert a c)\"\n  using insert_valid_aux sublist_valid by blast\n\nlemma insert_valid_aux3 :\n  \"(\\<And>a. valid_set c \\<Longrightarrow> valid_set (SList.insert a c)) \\<Longrightarrow>\n   valid_set (x # c) \\<Longrightarrow> valid_set (SList.insert a (x # c))\"\n  apply (simp only:insert.simps)\n  apply (cases \"a < x\")\n  apply auto[1]\n  apply (cases \"x < a\")\n  apply (smt insert_valid_aux2)\n  by auto\n\ntheorem insert_valid : \"valid_set c \\<Longrightarrow> valid_set (SList.insert a c)\"\n  apply (induction c arbitrary:a)\n  apply simp\n  using insert_valid_aux3 by blast\n\nfun delete :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n  \"delete a Nil = Nil\" |\n  \"delete a (Cons x z) =\n    (if a = x\n     then z\n     else (if a > x\n           then (Cons x (delete a z))\n           else (Cons x z)))\"\n\nlemma delete_valid_aux :\n  \"valid_set (a # c) \\<Longrightarrow> valid_set (a # delete b c)\"\n  apply (induction c arbitrary: a b)\n  apply simp\n  by fastforce\n\nlemma delete_valid_aux2 :\n  \"(\\<And>a. valid_set c \\<Longrightarrow> valid_set (delete a c)) \\<Longrightarrow>\n   valid_set (b # c) \\<Longrightarrow> valid_set (delete a (b # c))\"\n  using delete_valid_aux by auto\n\ntheorem delete_valid : \"valid_set c \\<Longrightarrow> valid_set (SList.delete a c)\"\n  apply (induction c arbitrary: a)\n  apply auto[1]\n  using delete_valid_aux2 by blast\n\nfun element :: \"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n  \"element a Nil = False\" |\n  \"element a (Cons x z) =\n    (if a = x\n     then True\n     else (if a > x\n           then element a z\n           else False))\"\n\nlemma delete_lookup_None_aux :\n  \"valid_set (c # b) \\<Longrightarrow> element c b = False\"\n  by (metis element.elims(2) not_less_iff_gr_or_eq remove_from_middle)\n\nlemma delete_lookup_None_aux2 :\n  \"(valid_set b \\<Longrightarrow> element a (delete a b) = False) \\<Longrightarrow>\n   valid_set (c # b) \\<Longrightarrow> element a (delete a (c # b)) = False\"\n  using delete_lookup_None_aux by auto\n\ntheorem delete_lookup_None : \"valid_set b \\<Longrightarrow>\n                              SList.element a (SList.delete a b) = False\"\n  apply (induction b)\n  apply simp\n  using delete_lookup_None_aux2 by fastforce\n\ntheorem insert_lookup_Some : \"valid_set c \\<Longrightarrow>\n                              SList.element a (SList.insert a c) = True\"\n  apply (induction c)\n  apply simp\n  by force\n\nlemma different_delete_lookup_aux :\n  \"(valid_set c \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow> element a (delete b c) = element a c) \\<Longrightarrow>\n   valid_set (x # c) \\<Longrightarrow>\n   a \\<noteq> b \\<Longrightarrow> element a (delete b (x # c)) = element a (x # c)\"\n  by (metis (full_types) delete.simps(2) delete_lookup_None_aux\n      delete_valid_aux element.simps(2) insert_in_middle\n      not_less_iff_gr_or_eq sublist_valid)\n\ntheorem different_delete_lookup :\n  \"valid_set c \\<Longrightarrow> a \\<noteq> b \\<Longrightarrow>\n   SList.element a (SList.delete b c) = SList.element a c\"\n  apply (induction c)\n  apply simp\n  using different_delete_lookup_aux by blast\n\nend\n", "meta": {"author": "input-output-hk", "repo": "marlowe", "sha": "d2f7b3108894b7c3169c71214f1a2772716544bf", "save_path": "github-repos/isabelle/input-output-hk-marlowe", "path": "github-repos/isabelle/input-output-hk-marlowe/marlowe-d2f7b3108894b7c3169c71214f1a2772716544bf/isabelle/Util/SList.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.824461928533133, "lm_q1q2_score": 0.7522688765301864}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_nat_MSortBU2Count\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun pairwise :: \"(Nat list) list => (Nat list) list\" where\n  \"pairwise (nil2) = nil2\"\n| \"pairwise (cons2 xs (nil2)) = cons2 xs (nil2)\"\n| \"pairwise (cons2 xs (cons2 ys xss)) =\n     cons2 (lmerge xs ys) (pairwise xss)\"\n\n(*fun did not finish the proof*)\nfunction mergingbu2 :: \"(Nat list) list => Nat list\" where\n  \"mergingbu2 (nil2) = nil2\"\n| \"mergingbu2 (cons2 xs (nil2)) = xs\"\n| \"mergingbu2 (cons2 xs (cons2 z x2)) =\n     mergingbu2 (pairwise (cons2 xs (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun risers :: \"Nat list => (Nat list) list\" where\n  \"risers (nil2) = nil2\"\n| \"risers (cons2 y (nil2)) = cons2 (cons2 y (nil2)) (nil2)\"\n| \"risers (cons2 y (cons2 y2 xs)) =\n     (if le y y2 then\n        (case risers (cons2 y2 xs) of\n           nil2 => nil2\n           | cons2 ys yss => cons2 (cons2 y ys) yss)\n        else\n        cons2 (cons2 y (nil2)) (risers (cons2 y2 xs)))\"\n\nfun msortbu2 :: \"Nat list => Nat list\" where\n  \"msortbu2 x = mergingbu2 (risers x)\"\n\nfun count :: \"'a => 'a list => Nat\" where\n  \"count x (nil2) = Z\"\n| \"count x (cons2 z ys) =\n     (if (x = z) then plus (S Z) (count x ys) else count x ys)\"\n\ntheorem property0 :\n  \"((count x (msortbu2 xs)) = (count x xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_nat_MSortBU2Count.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.8244619285331332, "lm_q1q2_score": 0.7522688706408106}}
{"text": "theory ex_2_6\n  imports Main\nbegin\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents::\"'a tree \\<Rightarrow> 'a list\" where\n\"contents Tip = []\" |\n\"contents (Node l a r) = a # (contents(l) @ contents(r))\"\n\nfun sum_tree::\"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l a r) = a + sum_tree(l) + sum_tree(r)\"\n\ntheorem contents_equiv:\"sum_tree t = sum_list(contents t)\"\n  apply (induction t)\n  by (auto)\nend", "meta": {"author": "20051615", "repo": "Gale-Shapley-formalization", "sha": "d601131b66c039561f8a72cd4913fcf8c84f08fa", "save_path": "github-repos/isabelle/20051615-Gale-Shapley-formalization", "path": "github-repos/isabelle/20051615-Gale-Shapley-formalization/Gale-Shapley-formalization-d601131b66c039561f8a72cd4913fcf8c84f08fa/tutorials/prog-prove/ex_2_6.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9099070109242132, "lm_q2_score": 0.8267118026095992, "lm_q1q2_score": 0.7522308652082685}}
{"text": "(*  Title:      HOL/Number_Theory/Eratosthenes.thy\n    Author:     Florian Haftmann, TU Muenchen\n*)\n\nsection \\<open>The sieve of Eratosthenes\\<close>\n\ntheory Eratosthenes\n  imports MainRLT \"HOL-Computational_Algebra.Primes\"\nbegin\n\n\nsubsection \\<open>Preliminary: strict divisibility\\<close>\n\ncontext dvd\nbegin\n\nabbreviation dvd_strict :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\" (infixl \"dvd'_strict\" 50)\nwhere\n  \"b dvd_strict a \\<equiv> b dvd a \\<and> \\<not> a dvd b\"\n\nend\n\n\nsubsection \\<open>Main corpus\\<close>\n\ntext \\<open>The sieve is modelled as a list of booleans, where \\<^const>\\<open>False\\<close> means \\emph{marked out}.\\<close>\n\ntype_synonym marks = \"bool list\"\n\ndefinition numbers_of_marks :: \"nat \\<Rightarrow> marks \\<Rightarrow> nat set\"\nwhere\n  \"numbers_of_marks n bs = fst ` {x \\<in> set (enumerate n bs). snd x}\"\n\nlemma numbers_of_marks_simps [simp, code]:\n  \"numbers_of_marks n [] = {}\"\n  \"numbers_of_marks n (True # bs) = insert n (numbers_of_marks (Suc n) bs)\"\n  \"numbers_of_marks n (False # bs) = numbers_of_marks (Suc n) bs\"\n  by (auto simp add: numbers_of_marks_def intro!: image_eqI)\n\nlemma numbers_of_marks_Suc:\n  \"numbers_of_marks (Suc n) bs = Suc ` numbers_of_marks n bs\"\n  by (auto simp add: numbers_of_marks_def enumerate_Suc_eq image_iff Bex_def)\n\nlemma numbers_of_marks_replicate_False [simp]:\n  \"numbers_of_marks n (replicate m False) = {}\"\n  by (auto simp add: numbers_of_marks_def enumerate_replicate_eq)\n\nlemma numbers_of_marks_replicate_True [simp]:\n  \"numbers_of_marks n (replicate m True) = {n..<n+m}\"\n  by (auto simp add: numbers_of_marks_def enumerate_replicate_eq image_def)\n\nlemma in_numbers_of_marks_eq:\n  \"m \\<in> numbers_of_marks n bs \\<longleftrightarrow> m \\<in> {n..<n + length bs} \\<and> bs ! (m - n)\"\n  by (simp add: numbers_of_marks_def in_set_enumerate_eq image_iff add.commute)\n\nlemma sorted_list_of_set_numbers_of_marks:\n  \"sorted_list_of_set (numbers_of_marks n bs) = map fst (filter snd (enumerate n bs))\"\n  by (auto simp add: numbers_of_marks_def distinct_map\n    intro!: sorted_filter distinct_filter inj_onI sorted_distinct_set_unique)\n\n\ntext \\<open>Marking out multiples in a sieve\\<close>\n\ndefinition mark_out :: \"nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"mark_out n bs = map (\\<lambda>(q, b). b \\<and> \\<not> Suc n dvd Suc (Suc q)) (enumerate n bs)\"\n\nlemma mark_out_Nil [simp]: \"mark_out n [] = []\"\n  by (simp add: mark_out_def)\n\nlemma length_mark_out [simp]: \"length (mark_out n bs) = length bs\"\n  by (simp add: mark_out_def)\n\nlemma numbers_of_marks_mark_out:\n    \"numbers_of_marks n (mark_out m bs) = {q \\<in> numbers_of_marks n bs. \\<not> Suc m dvd Suc q - n}\"\n  by (auto simp add: numbers_of_marks_def mark_out_def in_set_enumerate_eq image_iff\n    nth_enumerate_eq less_eq_dvd_minus)\n\n\ntext \\<open>Auxiliary operation for efficient implementation\\<close>\n\ndefinition mark_out_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"mark_out_aux n m bs =\n    map (\\<lambda>(q, b). b \\<and> (q < m + n \\<or> \\<not> Suc n dvd Suc (Suc q) + (n - m mod Suc n))) (enumerate n bs)\"\n\nlemma mark_out_code [code]: \"mark_out n bs = mark_out_aux n n bs\"\nproof -\n  have aux: False\n    if A: \"Suc n dvd Suc (Suc a)\"\n    and B: \"a < n + n\"\n    and C: \"n \\<le> a\"\n    for a\n  proof (cases \"n = 0\")\n    case True\n    with A B C show ?thesis by simp\n  next\n    case False\n    define m where \"m = Suc n\"\n    then have \"m > 0\" by simp\n    from False have \"n > 0\" by simp\n    from A obtain q where q: \"Suc (Suc a) = Suc n * q\" by (rule dvdE)\n    have \"q > 0\"\n    proof (rule ccontr)\n      assume \"\\<not> q > 0\"\n      with q show False by simp\n    qed\n    with \\<open>n > 0\\<close> have \"Suc n * q \\<ge> 2\" by (auto simp add: gr0_conv_Suc)\n    with q have a: \"a = Suc n * q - 2\" by simp\n    with B have \"q + n * q < n + n + 2\" by auto\n    then have \"m * q < m * 2\" by (simp add: m_def)\n    with \\<open>m > 0\\<close> have \"q < 2\" by simp\n    with \\<open>q > 0\\<close> have \"q = 1\" by simp\n    with a have \"a = n - 1\" by simp\n    with \\<open>n > 0\\<close> C show False by simp\n  qed\n  show ?thesis\n    by (auto simp add: mark_out_def mark_out_aux_def in_set_enumerate_eq intro: aux)\nqed\n\nlemma mark_out_aux_simps [simp, code]:\n  \"mark_out_aux n m [] = []\"\n  \"mark_out_aux n 0 (b # bs) = False # mark_out_aux n n bs\"\n  \"mark_out_aux n (Suc m) (b # bs) = b # mark_out_aux n m bs\"\nproof goal_cases\n  case 1\n  show ?case\n    by (simp add: mark_out_aux_def)\nnext\n  case 2\n  show ?case\n    by (auto simp add: mark_out_code [symmetric] mark_out_aux_def mark_out_def\n      enumerate_Suc_eq in_set_enumerate_eq less_eq_dvd_minus)\nnext\n  case 3\n  { define v where \"v = Suc m\"\n    define w where \"w = Suc n\"\n    fix q\n    assume \"m + n \\<le> q\"\n    then obtain r where q: \"q = m + n + r\" by (auto simp add: le_iff_add)\n    { fix u\n      from w_def have \"u mod w < w\" by simp\n      then have \"u + (w - u mod w) = w + (u - u mod w)\"\n        by simp\n      then have \"u + (w - u mod w) = w + u div w * w\"\n        by (simp add: minus_mod_eq_div_mult)\n    }\n    then have \"w dvd v + w + r + (w - v mod w) \\<longleftrightarrow> w dvd m + w + r + (w - m mod w)\"\n      by (simp add: add.assoc add.left_commute [of m] add.left_commute [of v]\n        dvd_add_left_iff dvd_add_right_iff)\n    moreover from q have \"Suc q = m + w + r\" by (simp add: w_def)\n    moreover from q have \"Suc (Suc q) = v + w + r\" by (simp add: v_def w_def)\n    ultimately have \"w dvd Suc (Suc (q + (w - v mod w))) \\<longleftrightarrow> w dvd Suc (q + (w - m mod w))\"\n      by (simp only: add_Suc [symmetric])\n    then have \"Suc n dvd Suc (Suc (Suc (q + n) - Suc m mod Suc n)) \\<longleftrightarrow>\n      Suc n dvd Suc (Suc (q + n - m mod Suc n))\"\n      by (simp add: v_def w_def Suc_diff_le trans_le_add2)\n  }\n  then show ?case\n    by (auto simp add: mark_out_aux_def\n      enumerate_Suc_eq in_set_enumerate_eq not_less)\nqed\n\n\ntext \\<open>Main entry point to sieve\\<close>\n\nfun sieve :: \"nat \\<Rightarrow> marks \\<Rightarrow> marks\"\nwhere\n  \"sieve n [] = []\"\n| \"sieve n (False # bs) = False # sieve (Suc n) bs\"\n| \"sieve n (True # bs) = True # sieve (Suc n) (mark_out n bs)\"\n\ntext \\<open>\n  There are the following possible optimisations here:\n\n  \\begin{itemize}\n\n    \\item \\<^const>\\<open>sieve\\<close> can abort as soon as \\<^term>\\<open>n\\<close> is too big to let\n      \\<^const>\\<open>mark_out\\<close> have any effect.\n\n    \\item Search for further primes can be given up as soon as the search\n      position exceeds the square root of the maximum candidate.\n\n  \\end{itemize}\n\n  This is left as an constructive exercise to the reader.\n\\<close>\n\nlemma numbers_of_marks_sieve:\n  \"numbers_of_marks (Suc n) (sieve n bs) =\n    {q \\<in> numbers_of_marks (Suc n) bs. \\<forall>m \\<in> numbers_of_marks (Suc n) bs. \\<not> m dvd_strict q}\"\nproof (induct n bs rule: sieve.induct)\n  case 1\n  show ?case by simp\nnext\n  case 2\n  then show ?case by simp\nnext\n  case (3 n bs)\n  have aux: \"n \\<in> Suc ` M \\<longleftrightarrow> n > 0 \\<and> n - 1 \\<in> M\" (is \"?lhs \\<longleftrightarrow> ?rhs\") for M n\n  proof\n    show ?rhs if ?lhs using that by auto\n    show ?lhs if ?rhs\n    proof -\n      from that have \"n > 0\" and \"n - 1 \\<in> M\" by auto\n      then have \"Suc (n - 1) \\<in> Suc ` M\" by blast\n      with \\<open>n > 0\\<close> show \"n \\<in> Suc ` M\" by simp\n    qed\n  qed\n  have aux1: False if \"Suc (Suc n) \\<le> m\" and \"m dvd Suc n\" for m :: nat\n  proof -\n    from \\<open>m dvd Suc n\\<close> obtain q where \"Suc n = m * q\" ..\n    with \\<open>Suc (Suc n) \\<le> m\\<close> have \"Suc (m * q) \\<le> m\" by simp\n    then have \"m * q < m\" by arith\n    then have \"q = 0\" by simp\n    with \\<open>Suc n = m * q\\<close> show ?thesis by simp\n  qed\n  have aux2: \"m dvd q\"\n    if 1: \"\\<forall>q>0. 1 < q \\<longrightarrow> Suc n < q \\<longrightarrow> q \\<le> Suc (n + length bs) \\<longrightarrow>\n      bs ! (q - Suc (Suc n)) \\<longrightarrow> \\<not> Suc n dvd q \\<longrightarrow> q dvd m \\<longrightarrow> m dvd q\"\n    and 2: \"\\<not> Suc n dvd m\" \"q dvd m\"\n    and 3: \"Suc n < q\" \"q \\<le> Suc (n + length bs)\" \"bs ! (q - Suc (Suc n))\"\n    for m q :: nat\n  proof -\n    from 1 have *: \"\\<And>q. Suc n < q \\<Longrightarrow> q \\<le> Suc (n + length bs) \\<Longrightarrow>\n      bs ! (q - Suc (Suc n)) \\<Longrightarrow> \\<not> Suc n dvd q \\<Longrightarrow> q dvd m \\<Longrightarrow> m dvd q\"\n      by auto\n    from 2 have \"\\<not> Suc n dvd q\" by (auto elim: dvdE)\n    moreover note 3\n    moreover note \\<open>q dvd m\\<close>\n    ultimately show ?thesis by (auto intro: *)\n  qed\n  from 3 show ?case\n    apply (simp_all add: numbers_of_marks_mark_out numbers_of_marks_Suc Compr_image_eq\n      inj_image_eq_iff in_numbers_of_marks_eq Ball_def imp_conjL aux)\n    apply safe\n    apply (simp_all add: less_diff_conv2 le_diff_conv2 dvd_minus_self not_less)\n    apply (clarsimp dest!: aux1)\n    apply (simp add: Suc_le_eq less_Suc_eq_le)\n    apply (rule aux2)\n    apply (clarsimp dest!: aux1)+\n    done\nqed\n\n\ntext \\<open>Relation of the sieve algorithm to actual primes\\<close>\n\ndefinition primes_upto :: \"nat \\<Rightarrow> nat list\"\nwhere\n  \"primes_upto n = sorted_list_of_set {m. m \\<le> n \\<and> prime m}\"\n\nlemma set_primes_upto: \"set (primes_upto n) = {m. m \\<le> n \\<and> prime m}\"\n  by (simp add: primes_upto_def)\n\nlemma sorted_primes_upto [iff]: \"sorted (primes_upto n)\"\n  by (simp add: primes_upto_def)\n\nlemma distinct_primes_upto [iff]: \"distinct (primes_upto n)\"\n  by (simp add: primes_upto_def)\n\nlemma set_primes_upto_sieve:\n  \"set (primes_upto n) = numbers_of_marks 2 (sieve 1 (replicate (n - 1) True))\"\nproof -\n  consider \"n = 0 \\<or> n = 1\" | \"n > 1\" by arith\n  then show ?thesis\n  proof cases\n    case 1\n    then show ?thesis\n      by (auto simp add: numbers_of_marks_sieve numeral_2_eq_2 set_primes_upto\n        dest: prime_gt_Suc_0_nat)\n  next\n    case 2\n    {\n      fix m q\n      assume \"Suc (Suc 0) \\<le> q\"\n        and \"q < Suc n\"\n        and \"m dvd q\"\n      then have \"m < Suc n\" by (auto dest: dvd_imp_le)\n      assume *: \"\\<forall>m\\<in>{Suc (Suc 0)..<Suc n}. m dvd q \\<longrightarrow> q dvd m\"\n        and \"m dvd q\" and \"m \\<noteq> 1\"\n      have \"m = q\"\n      proof (cases \"m = 0\")\n        case True with \\<open>m dvd q\\<close> show ?thesis by simp\n      next\n        case False with \\<open>m \\<noteq> 1\\<close> have \"Suc (Suc 0) \\<le> m\" by arith\n        with \\<open>m < Suc n\\<close> * \\<open>m dvd q\\<close> have \"q dvd m\" by simp\n        with \\<open>m dvd q\\<close> show ?thesis by (simp add: dvd_antisym)\n      qed\n    }\n    then have aux: \"\\<And>m q. Suc (Suc 0) \\<le> q \\<Longrightarrow>\n      q < Suc n \\<Longrightarrow>\n      m dvd q \\<Longrightarrow>\n      \\<forall>m\\<in>{Suc (Suc 0)..<Suc n}. m dvd q \\<longrightarrow> q dvd m \\<Longrightarrow>\n      m dvd q \\<Longrightarrow> m \\<noteq> q \\<Longrightarrow> m = 1\" by auto\n    from 2 show ?thesis\n      apply (auto simp add: numbers_of_marks_sieve numeral_2_eq_2 set_primes_upto\n        dest: prime_gt_Suc_0_nat)\n      apply (metis One_nat_def Suc_le_eq less_not_refl prime_nat_iff)\n      apply (metis One_nat_def Suc_le_eq aux prime_nat_iff)\n      done\n  qed\nqed\n\nlemma primes_upto_sieve [code]:\n  \"primes_upto n = map fst (filter snd (enumerate 2 (sieve 1 (replicate (n - 1) True))))\"\nproof -\n  have \"primes_upto n = sorted_list_of_set (numbers_of_marks 2 (sieve 1 (replicate (n - 1) True)))\"\n    apply (rule sorted_distinct_set_unique)\n    apply (simp_all only: set_primes_upto_sieve numbers_of_marks_def)\n    apply auto\n    done\n  then show ?thesis\n    by (simp add: sorted_list_of_set_numbers_of_marks)\nqed\n\nlemma prime_in_primes_upto: \"prime n \\<longleftrightarrow> n \\<in> set (primes_upto n)\"\n  by (simp add: set_primes_upto)\n\n\nsubsection \\<open>Application: smallest prime beyond a certain number\\<close>\n\ndefinition smallest_prime_beyond :: \"nat \\<Rightarrow> nat\"\nwhere\n  \"smallest_prime_beyond n = (LEAST p. prime p \\<and> p \\<ge> n)\"\n\nlemma prime_smallest_prime_beyond [iff]: \"prime (smallest_prime_beyond n)\" (is ?P)\n  and smallest_prime_beyond_le [iff]: \"smallest_prime_beyond n \\<ge> n\" (is ?Q)\nproof -\n  let ?least = \"LEAST p. prime p \\<and> p \\<ge> n\"\n  from primes_infinite obtain q where \"prime q \\<and> q \\<ge> n\"\n    by (metis finite_nat_set_iff_bounded_le mem_Collect_eq nat_le_linear)\n  then have \"prime ?least \\<and> ?least \\<ge> n\"\n    by (rule LeastI)\n  then show ?P and ?Q\n    by (simp_all add: smallest_prime_beyond_def)\nqed\n\nlemma smallest_prime_beyond_smallest: \"prime p \\<Longrightarrow> p \\<ge> n \\<Longrightarrow> smallest_prime_beyond n \\<le> p\"\n  by (simp only: smallest_prime_beyond_def) (auto intro: Least_le)\n\nlemma smallest_prime_beyond_eq:\n  \"prime p \\<Longrightarrow> p \\<ge> n \\<Longrightarrow> (\\<And>q. prime q \\<Longrightarrow> q \\<ge> n \\<Longrightarrow> q \\<ge> p) \\<Longrightarrow> smallest_prime_beyond n = p\"\n  by (simp only: smallest_prime_beyond_def) (auto intro: Least_equality)\n\ndefinition smallest_prime_between :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat option\"\nwhere\n  \"smallest_prime_between m n =\n    (if (\\<exists>p. prime p \\<and> m \\<le> p \\<and> p \\<le> n) then Some (smallest_prime_beyond m) else None)\"\n\nlemma smallest_prime_between_None:\n  \"smallest_prime_between m n = None \\<longleftrightarrow> (\\<forall>q. m \\<le> q \\<and> q \\<le> n \\<longrightarrow> \\<not> prime q)\"\n  by (auto simp add: smallest_prime_between_def)\n\nlemma smallest_prime_betwen_Some:\n  \"smallest_prime_between m n = Some p \\<longleftrightarrow> smallest_prime_beyond m = p \\<and> p \\<le> n\"\n  by (auto simp add: smallest_prime_between_def dest: smallest_prime_beyond_smallest [of _ m])\n\n\n\ndefinition smallest_prime_beyond_aux :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"smallest_prime_beyond_aux k n = smallest_prime_beyond n\"\n\nlemma [code]:\n  \"smallest_prime_beyond_aux k n =\n    (case smallest_prime_between n (k * n) of\n      Some p \\<Rightarrow> p\n    | None \\<Rightarrow> smallest_prime_beyond_aux (Suc k) n)\"\n  by (simp add: smallest_prime_beyond_aux_def smallest_prime_betwen_Some split: option.split)\n\nlemma [code]: \"smallest_prime_beyond n = smallest_prime_beyond_aux 2 n\"\n  by (simp add: smallest_prime_beyond_aux_def)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Number_Theory/Eratosthenes.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.8289388146603364, "lm_q1q2_score": 0.7521063235341668}}
{"text": "(* author: wzh*)\n\ntheory Exercise2_1\n  imports Main\n\nbegin\n(* Exer 2.1 *)\nvalue \"1 + (2 :: nat)\"\nvalue \"1 + (2 :: int)\"\nvalue \"1 - (2 :: nat)\"\nvalue \"1 - (2 :: int)\"\n\n(* Exer 2.2 *)\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n\"add 0 n = n\" |\n\"add (Suc m) n = Suc(add m n)\"\n\ntheorem add_assoc [simp]: \"add (add x y) z = add x (add y z)\"\n  apply(induction x)\n   apply(auto)\n  done\n\nlemma add_zero [simp]:  \"add x 0 = x\"\n  apply(induction x)\n   apply(auto)\n  done\n\nlemma add_suc1 [simp]: \"add x (Suc(y)) = Suc(add x y) \"\n  apply(induction x)\n  apply(auto)\n  done\n\nlemma add_suc2 [simp]: \"add x (Suc(y)) = Suc(add y x) \"\n  apply(induction x)\n  apply(auto)\n  done\n\ntheorem add_commu [simp]: \"add x y = add y x\"\n  apply(induction y)\n   apply(auto)\n  done\n\nfun double :: \"nat \\<Rightarrow> nat\" where\n\"double x = x*2\"\n\ntheorem dou: \"double x = add x x\"\n  apply(induction x)\n   apply(auto)\n  done\n\n(* Exer 2.3 *)\nfun count :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> nat\" where\n\"count x Nil = 0\" |\n\"count x xs = (if x = (hd xs) then 1 + count x (tl xs) else count x (tl xs))\"\n\ntheorem count_len: \"count x xs \\<le> length xs\"\napply(induction xs)\n  apply(auto)\n  done\n\n(* Exer 2.4 *)\nfun snoc2 :: \"'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list\" where\n\"snoc2 [] x = [x]\" |\n\"snoc2 (x # xs) ys = (x # (snoc2 xs ys))\"\n\n\nfun reverse2 :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse2 [] = []\" |\n\"reverse2 (x#xs) = snoc2 (reverse2(xs)) x\"\n\n\n\ntheorem [simp]: \"reverse2 (reverse2 xs) = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\n\n\n(* Exer 2.5 *)\nfun sum_upto :: \"nat \\<Rightarrow> nat\" where\n\"sum_upto 0 = 0\" |\n\"sum_upto x = x + sum_upto (x-1)\"\n\ntheorem sum: \"sum_upto n*2 = n*(n+1)\"\n  apply(induction n)\n   apply(auto)\n  done\n\nend", "meta": {"author": "yogurt-shadow", "repo": "Isar_Exercise", "sha": "27658bff434e0845a23aeb310eeb971e4fc20b98", "save_path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise", "path": "github-repos/isabelle/yogurt-shadow-Isar_Exercise/Isar_Exercise-27658bff434e0845a23aeb310eeb971e4fc20b98/Exercise2_1.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480667, "lm_q2_score": 0.8289387998695209, "lm_q1q2_score": 0.7521062997265215}}
{"text": "(*  Title:      ZF/ex/NatSum.thy\n    Author:     Tobias Nipkow & Lawrence C Paulson\n\nA summation operator. sum(f,n+1) is the sum of all f(i), i=0...n.\n\nNote: n is a natural number but the sum is an integer,\n                            and f maps integers to integers\n\nSumming natural numbers, squares, cubes, etc.\n\nOriginally demonstrated permutative rewriting, but add_ac is no longer needed\n  thanks to new simprocs.\n\nThanks to Sloane's On-Line Encyclopedia of Integer Sequences,\n  http://www.research.att.com/\\<not>njas/sequences/\n*)\n\n\ntheory NatSum imports ZF begin\n\nconsts sum :: \"[i\\<Rightarrow>i, i] \\<Rightarrow> i\"\nprimrec \n  \"sum (f,0) = #0\"\n  \"sum (f, succ(n)) = f($#n) $+ sum(f,n)\"\n\ndeclare zadd_zmult_distrib [simp]  zadd_zmult_distrib2 [simp]\ndeclare zdiff_zmult_distrib [simp] zdiff_zmult_distrib2 [simp]\n\n(*The sum of the first n odd numbers equals n squared.*)\nlemma sum_of_odds: \"n \\<in> nat \\<Longrightarrow> sum (\\<lambda>i. i $+ i $+ #1, n) = $#n $* $#n\"\nby (induct_tac \"n\", auto)\n\n(*The sum of the first n odd squares*)\nlemma sum_of_odd_squares:\n     \"n \\<in> nat \\<Longrightarrow> #3 $* sum (\\<lambda>i. (i $+ i $+ #1) $* (i $+ i $+ #1), n) =  \n      $#n $* (#4 $* $#n $* $#n $- #1)\"\nby (induct_tac \"n\", auto)\n\n(*The sum of the first n odd cubes*)\nlemma sum_of_odd_cubes:\n     \"n \\<in> nat  \n      \\<Longrightarrow> sum (\\<lambda>i. (i $+ i $+ #1) $* (i $+ i $+ #1) $* (i $+ i $+ #1), n) =  \n          $#n $* $#n $* (#2 $* $#n $* $#n $- #1)\"\nby (induct_tac \"n\", auto)\n\n(*The sum of the first n positive integers equals n(n+1)/2.*)\nlemma sum_of_naturals:\n     \"n \\<in> nat \\<Longrightarrow> #2 $* sum(\\<lambda>i. i, succ(n)) = $#n $* $#succ(n)\"\nby (induct_tac \"n\", auto)\n\nlemma sum_of_squares:\n     \"n \\<in> nat \\<Longrightarrow> #6 $* sum (\\<lambda>i. i$*i, succ(n)) =  \n                  $#n $* ($#n $+ #1) $* (#2 $* $#n $+ #1)\"\nby (induct_tac \"n\", auto)\n\nlemma sum_of_cubes:\n     \"n \\<in> nat \\<Longrightarrow> #4 $* sum (\\<lambda>i. i$*i$*i, succ(n)) =  \n                  $#n $* $#n $* ($#n $+ #1) $* ($#n $+ #1)\"\nby (induct_tac \"n\", auto)\n\n(** Sum of fourth powers **)\n\nlemma sum_of_fourth_powers:\n     \"n \\<in> nat \\<Longrightarrow> #30 $* sum (\\<lambda>i. i$*i$*i$*i, succ(n)) =  \n                    $#n $* ($#n $+ #1) $* (#2 $* $#n $+ #1) $*  \n                    (#3 $* $#n $* $#n $+ #3 $* $#n $- #1)\"\nby (induct_tac \"n\", auto)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/ZF/ex/NatSum.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.8198933425148214, "lm_q1q2_score": 0.7520903418118903}}
{"text": "section \\<open>Faces, Extreme Points, Polytopes, Polyhedra etc.\\<close>\n\ntext\\<open>Ported from HOL Light by L C Paulson\\<close>\n\ntheory Polytope\nimports Cartesian_Euclidean_Space\nbegin\n\nsubsection \\<open>Faces of a (usually convex) set\\<close>\n\ndefinition face_of :: \"['a::real_vector set, 'a set] \\<Rightarrow> bool\" (infixr \"(face'_of)\" 50)\n  where\n  \"T face_of S \\<longleftrightarrow>\n        T \\<subseteq> S \\<and> convex T \\<and>\n        (\\<forall>a \\<in> S. \\<forall>b \\<in> S. \\<forall>x \\<in> T. x \\<in> open_segment a b \\<longrightarrow> a \\<in> T \\<and> b \\<in> T)\"\n\nlemma face_ofD: \"\\<lbrakk>T face_of S; x \\<in> open_segment a b; a \\<in> S; b \\<in> S; x \\<in> T\\<rbrakk> \\<Longrightarrow> a \\<in> T \\<and> b \\<in> T\"\n  unfolding face_of_def by blast\n\nlemma face_of_translation_eq [simp]:\n    \"(op + a ` T face_of op + a ` S) \\<longleftrightarrow> T face_of S\"\nproof -\n  have *: \"\\<And>a T S. T face_of S \\<Longrightarrow> (op + a ` T face_of op + a ` S)\"\n    apply (simp add: face_of_def Ball_def, clarify)\n    apply (drule open_segment_translation_eq [THEN iffD1])\n    using inj_image_mem_iff inj_add_left apply metis\n    done\n  show ?thesis\n    apply (rule iffI)\n    apply (force simp: image_comp o_def dest: * [where a = \"-a\"])\n    apply (blast intro: *)\n    done\nqed\n\nlemma face_of_linear_image:\n  assumes \"linear f\" \"inj f\"\n    shows \"(f ` c face_of f ` S) \\<longleftrightarrow> c face_of S\"\nby (simp add: face_of_def inj_image_subset_iff inj_image_mem_iff open_segment_linear_image assms)\n\nlemma face_of_refl: \"convex S \\<Longrightarrow> S face_of S\"\n  by (auto simp: face_of_def)\n\nlemma face_of_refl_eq: \"S face_of S \\<longleftrightarrow> convex S\"\n  by (auto simp: face_of_def)\n\nlemma empty_face_of [iff]: \"{} face_of S\"\n  by (simp add: face_of_def)\n\nlemma face_of_empty [simp]: \"S face_of {} \\<longleftrightarrow> S = {}\"\n  by (meson empty_face_of face_of_def subset_empty)\n\nlemma face_of_trans [trans]: \"\\<lbrakk>S face_of T; T face_of u\\<rbrakk> \\<Longrightarrow> S face_of u\"\n  unfolding face_of_def by (safe; blast)\n\nlemma face_of_face: \"T face_of S \\<Longrightarrow> (f face_of T \\<longleftrightarrow> f face_of S \\<and> f \\<subseteq> T)\"\n  unfolding face_of_def by (safe; blast)\n\nlemma face_of_subset: \"\\<lbrakk>F face_of S; F \\<subseteq> T; T \\<subseteq> S\\<rbrakk> \\<Longrightarrow> F face_of T\"\n  unfolding face_of_def by (safe; blast)\n\nlemma face_of_slice: \"\\<lbrakk>F face_of S; convex T\\<rbrakk> \\<Longrightarrow> (F \\<inter> T) face_of (S \\<inter> T)\"\n  unfolding face_of_def by (blast intro: convex_Int)\n\nlemma face_of_Int: \"\\<lbrakk>t1 face_of S; t2 face_of S\\<rbrakk> \\<Longrightarrow> (t1 \\<inter> t2) face_of S\"\n  unfolding face_of_def by (blast intro: convex_Int)\n\nlemma face_of_Inter: \"\\<lbrakk>A \\<noteq> {}; \\<And>T. T \\<in> A \\<Longrightarrow> T face_of S\\<rbrakk> \\<Longrightarrow> (\\<Inter> A) face_of S\"\n  unfolding face_of_def by (blast intro: convex_Inter)\n\nlemma face_of_Int_Int: \"\\<lbrakk>F face_of T; F' face_of t'\\<rbrakk> \\<Longrightarrow> (F \\<inter> F') face_of (T \\<inter> t')\"\n  unfolding face_of_def by (blast intro: convex_Int)\n\nlemma face_of_imp_subset: \"T face_of S \\<Longrightarrow> T \\<subseteq> S\"\n  unfolding face_of_def by blast\n\nlemma face_of_imp_eq_affine_Int:\n     fixes S :: \"'a::euclidean_space set\"\n     assumes S: \"convex S\" \"closed S\" and T: \"T face_of S\"\n     shows \"T = (affine hull T) \\<inter> S\"\nproof -\n  have \"convex T\" using T by (simp add: face_of_def)\n  have *: False if x: \"x \\<in> affine hull T\" and \"x \\<in> S\" \"x \\<notin> T\" and y: \"y \\<in> rel_interior T\" for x y\n  proof -\n    obtain e where \"e>0\" and e: \"cball y e \\<inter> affine hull T \\<subseteq> T\"\n      using y by (auto simp: rel_interior_cball)\n    have \"y \\<noteq> x\" \"y \\<in> S\" \"y \\<in> T\"\n      using face_of_imp_subset rel_interior_subset T that by blast+\n    then have zne: \"\\<And>u. \\<lbrakk>u \\<in> {0<..<1}; (1 - u) *\\<^sub>R y + u *\\<^sub>R x \\<in> T\\<rbrakk> \\<Longrightarrow>  False\"\n      using \\<open>x \\<in> S\\<close> \\<open>x \\<notin> T\\<close> \\<open>T face_of S\\<close> unfolding face_of_def\n      apply clarify\n      apply (drule_tac x=x in bspec, assumption)\n      apply (drule_tac x=y in bspec, assumption)\n      apply (subst (asm) open_segment_commute)\n      apply (force simp: open_segment_image_interval image_def)\n      done\n    have in01: \"min (1/2) (e / norm (x - y)) \\<in> {0<..<1}\"\n      using \\<open>y \\<noteq> x\\<close> \\<open>e > 0\\<close> by simp\n    show ?thesis\n      apply (rule zne [OF in01])\n      apply (rule e [THEN subsetD])\n      apply (rule IntI)\n        using \\<open>y \\<noteq> x\\<close> \\<open>e > 0\\<close>\n        apply (simp add: cball_def dist_norm algebra_simps)\n        apply (simp add: Real_Vector_Spaces.scaleR_diff_right [symmetric] norm_minus_commute min_mult_distrib_right)\n      apply (rule mem_affine [OF affine_affine_hull _ x])\n      using \\<open>y \\<in> T\\<close>  apply (auto simp: hull_inc)\n      done\n  qed\n  show ?thesis\n    apply (rule subset_antisym)\n    using assms apply (simp add: hull_subset face_of_imp_subset)\n    apply (cases \"T={}\", simp)\n    apply (force simp: rel_interior_eq_empty [symmetric] \\<open>convex T\\<close> intro: *)\n    done\nqed\n\nlemma face_of_imp_closed:\n     fixes S :: \"'a::euclidean_space set\"\n     assumes \"convex S\" \"closed S\" \"T face_of S\" shows \"closed T\"\n  by (metis affine_affine_hull affine_closed closed_Int face_of_imp_eq_affine_Int assms)\n\nlemma face_of_Int_supporting_hyperplane_le_strong:\n    assumes \"convex(S \\<inter> {x. a \\<bullet> x = b})\" and aleb: \"\\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<le> b\"\n      shows \"(S \\<inter> {x. a \\<bullet> x = b}) face_of S\"\nproof -\n  have *: \"a \\<bullet> u = a \\<bullet> x\" if \"x \\<in> open_segment u v\" \"u \\<in> S\" \"v \\<in> S\" and b: \"b = a \\<bullet> x\"\n          for u v x\n  proof (rule antisym)\n    show \"a \\<bullet> u \\<le> a \\<bullet> x\"\n      using aleb \\<open>u \\<in> S\\<close> \\<open>b = a \\<bullet> x\\<close> by blast\n  next\n    obtain \\<xi> where \"b = a \\<bullet> ((1 - \\<xi>) *\\<^sub>R u + \\<xi> *\\<^sub>R v)\" \"0 < \\<xi>\" \"\\<xi> < 1\"\n      using \\<open>b = a \\<bullet> x\\<close> \\<open>x \\<in> open_segment u v\\<close> in_segment\n      by (auto simp: open_segment_image_interval split: if_split_asm)\n    then have \"b + \\<xi> * (a \\<bullet> u) \\<le> a \\<bullet> u + \\<xi> * b\"\n      using aleb [OF \\<open>v \\<in> S\\<close>] by (simp add: algebra_simps)\n    then have \"(1 - \\<xi>) * b \\<le> (1 - \\<xi>) * (a \\<bullet> u)\"\n      by (simp add: algebra_simps)\n    then have \"b \\<le> a \\<bullet> u\"\n      using \\<open>\\<xi> < 1\\<close> by auto\n    with b show \"a \\<bullet> x \\<le> a \\<bullet> u\" by simp\n  qed\n  show ?thesis\n    apply (simp add: face_of_def assms)\n    using \"*\" open_segment_commute by blast\nqed\n\nlemma face_of_Int_supporting_hyperplane_ge_strong:\n   \"\\<lbrakk>convex(S \\<inter> {x. a \\<bullet> x = b}); \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<ge> b\\<rbrakk>\n    \\<Longrightarrow> (S \\<inter> {x. a \\<bullet> x = b}) face_of S\"\n  using face_of_Int_supporting_hyperplane_le_strong [of S \"-a\" \"-b\"] by simp\n\nlemma face_of_Int_supporting_hyperplane_le:\n    \"\\<lbrakk>convex S; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<le> b\\<rbrakk> \\<Longrightarrow> (S \\<inter> {x. a \\<bullet> x = b}) face_of S\"\n  by (simp add: convex_Int convex_hyperplane face_of_Int_supporting_hyperplane_le_strong)\n\nlemma face_of_Int_supporting_hyperplane_ge:\n    \"\\<lbrakk>convex S; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<ge> b\\<rbrakk> \\<Longrightarrow> (S \\<inter> {x. a \\<bullet> x = b}) face_of S\"\n  by (simp add: convex_Int convex_hyperplane face_of_Int_supporting_hyperplane_ge_strong)\n\nlemma face_of_imp_convex: \"T face_of S \\<Longrightarrow> convex T\"\n  using face_of_def by blast\n\nlemma face_of_imp_compact:\n    fixes S :: \"'a::euclidean_space set\"\n    shows \"\\<lbrakk>convex S; compact S; T face_of S\\<rbrakk> \\<Longrightarrow> compact T\"\n  by (meson bounded_subset compact_eq_bounded_closed face_of_imp_closed face_of_imp_subset)\n\nlemma face_of_Int_subface:\n     \"\\<lbrakk>A \\<inter> B face_of A; A \\<inter> B face_of B; C face_of A; D face_of B\\<rbrakk>\n      \\<Longrightarrow> (C \\<inter> D) face_of C \\<and> (C \\<inter> D) face_of D\"\n  by (meson face_of_Int_Int face_of_face inf_le1 inf_le2)\n\nlemma subset_of_face_of:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"T face_of S\" \"u \\<subseteq> S\" \"T \\<inter> (rel_interior u) \\<noteq> {}\"\n      shows \"u \\<subseteq> T\"\nproof\n  fix c\n  assume \"c \\<in> u\"\n  obtain b where \"b \\<in> T\" \"b \\<in> rel_interior u\" using assms by auto\n  then obtain e where \"e>0\" \"b \\<in> u\" and e: \"cball b e \\<inter> affine hull u \\<subseteq> u\"\n    by (auto simp: rel_interior_cball)\n  show \"c \\<in> T\"\n  proof (cases \"b=c\")\n    case True with \\<open>b \\<in> T\\<close> show ?thesis by blast\n  next\n    case False\n    define d where \"d = b + (e / norm(b - c)) *\\<^sub>R (b - c)\"\n    have \"d \\<in> cball b e \\<inter> affine hull u\"\n      using \\<open>e > 0\\<close> \\<open>b \\<in> u\\<close> \\<open>c \\<in> u\\<close>\n      by (simp add: d_def dist_norm hull_inc mem_affine_3_minus False)\n    with e have \"d \\<in> u\" by blast\n    have nbc: \"norm (b - c) + e > 0\" using \\<open>e > 0\\<close>\n      by (metis add.commute le_less_trans less_add_same_cancel2 norm_ge_zero)\n    then have [simp]: \"d \\<noteq> c\" using False scaleR_cancel_left [of \"1 + (e / norm (b - c))\" b c]\n      by (simp add: algebra_simps d_def) (simp add: divide_simps)\n    have [simp]: \"((e - e * e / (e + norm (b - c))) / norm (b - c)) = (e / (e + norm (b - c)))\"\n      using False nbc\n      apply (simp add: algebra_simps divide_simps)\n      by (metis mult_eq_0_iff norm_eq_zero norm_imp_pos_and_ge norm_pths(2) real_scaleR_def scaleR_left.add zero_less_norm_iff)\n    have \"b \\<in> open_segment d c\"\n      apply (simp add: open_segment_image_interval)\n      apply (simp add: d_def algebra_simps image_def)\n      apply (rule_tac x=\"e / (e + norm (b - c))\" in bexI)\n      using False nbc \\<open>0 < e\\<close>\n      apply (auto simp: algebra_simps)\n      done\n    then have \"d \\<in> T \\<and> c \\<in> T\"\n      apply (rule face_ofD [OF \\<open>T face_of S\\<close>])\n      using \\<open>d \\<in> u\\<close>  \\<open>c \\<in> u\\<close> \\<open>u \\<subseteq> S\\<close>  \\<open>b \\<in> T\\<close>  apply auto\n      done\n    then show ?thesis ..\n  qed\nqed\n\nlemma face_of_eq:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"T face_of S\" \"u face_of S\" \"(rel_interior T) \\<inter> (rel_interior u) \\<noteq> {}\"\n      shows \"T = u\"\n  apply (rule subset_antisym)\n  apply (metis assms disjoint_iff_not_equal face_of_imp_subset rel_interior_subset subsetCE subset_of_face_of)\n  by (metis assms disjoint_iff_not_equal face_of_imp_subset rel_interior_subset subset_iff subset_of_face_of)\n\nlemma face_of_disjoint_rel_interior:\n      fixes S :: \"'a::real_normed_vector set\"\n      assumes \"T face_of S\" \"T \\<noteq> S\"\n        shows \"T \\<inter> rel_interior S = {}\"\n  by (meson assms subset_of_face_of face_of_imp_subset order_refl subset_antisym)\n\nlemma face_of_disjoint_interior:\n      fixes S :: \"'a::real_normed_vector set\"\n      assumes \"T face_of S\" \"T \\<noteq> S\"\n        shows \"T \\<inter> interior S = {}\"\nproof -\n  have \"T \\<inter> interior S \\<subseteq> rel_interior S\"\n    by (meson inf_sup_ord(2) interior_subset_rel_interior order.trans)\n  thus ?thesis\n    by (metis (no_types) Int_greatest assms face_of_disjoint_rel_interior inf_sup_ord(1) subset_empty)\nqed\n\nlemma face_of_subset_rel_boundary:\n  fixes S :: \"'a::real_normed_vector set\"\n  assumes \"T face_of S\" \"T \\<noteq> S\"\n    shows \"T \\<subseteq> (S - rel_interior S)\"\nby (meson DiffI assms disjoint_iff_not_equal face_of_disjoint_rel_interior face_of_imp_subset rev_subsetD subsetI)\n\nlemma face_of_subset_rel_frontier:\n    fixes S :: \"'a::real_normed_vector set\"\n    assumes \"T face_of S\" \"T \\<noteq> S\"\n      shows \"T \\<subseteq> rel_frontier S\"\n  using assms closure_subset face_of_disjoint_rel_interior face_of_imp_subset rel_frontier_def by fastforce\n\nlemma face_of_aff_dim_lt:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"convex S\" \"T face_of S\" \"T \\<noteq> S\"\n    shows \"aff_dim T < aff_dim S\"\nproof -\n  have \"aff_dim T \\<le> aff_dim S\"\n    by (simp add: face_of_imp_subset aff_dim_subset assms)\n  moreover have \"aff_dim T \\<noteq> aff_dim S\"\n  proof (cases \"T = {}\")\n    case True then show ?thesis\n      by (metis aff_dim_empty \\<open>T \\<noteq> S\\<close>)\n  next case False then show ?thesis\n    by (metis Set.set_insert assms convex_rel_frontier_aff_dim dual_order.irrefl face_of_imp_convex face_of_subset_rel_frontier insert_not_empty subsetI)\n  qed\n  ultimately show ?thesis\n    by simp\nqed\n\n\nlemma affine_diff_divide:\n    assumes \"affine S\" \"k \\<noteq> 0\" \"k \\<noteq> 1\" and xy: \"x \\<in> S\" \"y /\\<^sub>R (1 - k) \\<in> S\"\n      shows \"(x - y) /\\<^sub>R k \\<in> S\"\nproof -\n  have \"inverse(k) *\\<^sub>R (x - y) = (1 - inverse k) *\\<^sub>R inverse(1 - k) *\\<^sub>R y + inverse(k) *\\<^sub>R x\"\n    using assms\n    by (simp add: algebra_simps) (simp add: scaleR_left_distrib [symmetric] divide_simps)\n  then show ?thesis\n    using \\<open>affine S\\<close> xy by (auto simp: affine_alt)\nqed\n\nlemma face_of_convex_hulls:\n      assumes S: \"finite S\" \"T \\<subseteq> S\" and disj: \"affine hull T \\<inter> convex hull (S - T) = {}\"\n      shows  \"(convex hull T) face_of (convex hull S)\"\nproof -\n  have fin: \"finite T\" \"finite (S - T)\" using assms\n    by (auto simp: finite_subset)\n  have *: \"x \\<in> convex hull T\"\n          if x: \"x \\<in> convex hull S\" and y: \"y \\<in> convex hull S\" and w: \"w \\<in> convex hull T\" \"w \\<in> open_segment x y\"\n          for x y w\n  proof -\n    have waff: \"w \\<in> affine hull T\"\n      using convex_hull_subset_affine_hull w by blast\n    obtain a b where a: \"\\<And>i. i \\<in> S \\<Longrightarrow> 0 \\<le> a i\" and asum: \"sum a S = 1\" and aeqx: \"(\\<Sum>i\\<in>S. a i *\\<^sub>R i) = x\"\n                 and b: \"\\<And>i. i \\<in> S \\<Longrightarrow> 0 \\<le> b i\" and bsum: \"sum b S = 1\" and beqy: \"(\\<Sum>i\\<in>S. b i *\\<^sub>R i) = y\"\n      using x y by (auto simp: assms convex_hull_finite)\n    obtain u where \"(1 - u) *\\<^sub>R x + u *\\<^sub>R y \\<in> convex hull T\" \"x \\<noteq> y\" and weq: \"w = (1 - u) *\\<^sub>R x + u *\\<^sub>R y\"\n               and u01: \"0 < u\" \"u < 1\"\n      using w by (auto simp: open_segment_image_interval split: if_split_asm)\n    define c where \"c i = (1 - u) * a i + u * b i\" for i\n    have cge0: \"\\<And>i. i \\<in> S \\<Longrightarrow> 0 \\<le> c i\"\n      using a b u01 by (simp add: c_def)\n    have sumc1: \"sum c S = 1\"\n      by (simp add: c_def sum.distrib sum_distrib_left [symmetric] asum bsum)\n    have sumci_xy: \"(\\<Sum>i\\<in>S. c i *\\<^sub>R i) = (1 - u) *\\<^sub>R x + u *\\<^sub>R y\"\n      apply (simp add: c_def sum.distrib scaleR_left_distrib)\n      by (simp only: scaleR_scaleR [symmetric] Real_Vector_Spaces.scaleR_right.sum [symmetric] aeqx beqy)\n    show ?thesis\n    proof (cases \"sum c (S - T) = 0\")\n      case True\n      have ci0: \"\\<And>i. i \\<in> (S - T) \\<Longrightarrow> c i = 0\"\n        using True cge0 by (simp add: \\<open>finite S\\<close> sum_nonneg_eq_0_iff)\n      have a0: \"a i = 0\" if \"i \\<in> (S - T)\" for i\n        using ci0 [OF that] u01 a [of i] b [of i] that\n        by (simp add: c_def Groups.ordered_comm_monoid_add_class.add_nonneg_eq_0_iff)\n      have [simp]: \"sum a T = 1\"\n        using assms by (metis sum.mono_neutral_cong_right a0 asum)\n      show ?thesis\n        apply (simp add: convex_hull_finite \\<open>finite T\\<close>)\n        apply (rule_tac x=a in exI)\n        using a0 assms\n        apply (auto simp: cge0 a aeqx [symmetric] sum.mono_neutral_right)\n        done\n    next\n      case False\n      define k where \"k = sum c (S - T)\"\n      have \"k > 0\" using False\n        unfolding k_def by (metis DiffD1 antisym_conv cge0 sum_nonneg not_less)\n      have weq_sumsum: \"w = sum (\\<lambda>x. c x *\\<^sub>R x) T + sum (\\<lambda>x. c x *\\<^sub>R x) (S - T)\"\n        by (metis (no_types) add.commute S(1) S(2) sum.subset_diff sumci_xy weq)\n      show ?thesis\n      proof (cases \"k = 1\")\n        case True\n        then have \"sum c T = 0\"\n          by (simp add: S k_def sum_diff sumc1)\n        then have [simp]: \"sum c (S - T) = 1\"\n          by (simp add: S sum_diff sumc1)\n        have ci0: \"\\<And>i. i \\<in> T \\<Longrightarrow> c i = 0\"\n          by (meson \\<open>finite T\\<close> \\<open>sum c T = 0\\<close> \\<open>T \\<subseteq> S\\<close> cge0 sum_nonneg_eq_0_iff subsetCE)\n        then have [simp]: \"(\\<Sum>i\\<in>S-T. c i *\\<^sub>R i) = w\"\n          by (simp add: weq_sumsum)\n        have \"w \\<in> convex hull (S - T)\"\n          apply (simp add: convex_hull_finite fin)\n          apply (rule_tac x=c in exI)\n          apply (auto simp: cge0 weq True k_def)\n          done\n        then show ?thesis\n          using disj waff by blast\n      next\n        case False\n        then have sumcf: \"sum c T = 1 - k\"\n          by (simp add: S k_def sum_diff sumc1)\n        have \"(\\<Sum>i\\<in>T. c i *\\<^sub>R i) /\\<^sub>R (1 - k) \\<in> convex hull T\"\n          apply (simp add: convex_hull_finite fin)\n          apply (rule_tac x=\"\\<lambda>i. inverse (1-k) * c i\" in exI)\n          apply auto\n          apply (metis sumcf cge0 inverse_nonnegative_iff_nonnegative mult_nonneg_nonneg S(2) sum_nonneg subsetCE)\n          apply (metis False mult.commute right_inverse right_minus_eq sum_distrib_left sumcf)\n          by (metis (mono_tags, lifting) scaleR_right.sum scaleR_scaleR sum.cong)\n        with \\<open>0 < k\\<close>  have \"inverse(k) *\\<^sub>R (w - sum (\\<lambda>i. c i *\\<^sub>R i) T) \\<in> affine hull T\"\n          by (simp add: affine_diff_divide [OF affine_affine_hull] False waff convex_hull_subset_affine_hull [THEN subsetD])\n        moreover have \"inverse(k) *\\<^sub>R (w - sum (\\<lambda>x. c x *\\<^sub>R x) T) \\<in> convex hull (S - T)\"\n          apply (simp add: weq_sumsum convex_hull_finite fin)\n          apply (rule_tac x=\"\\<lambda>i. inverse k * c i\" in exI)\n          using \\<open>k > 0\\<close> cge0\n          apply (auto simp: scaleR_right.sum sum_distrib_left [symmetric] k_def [symmetric])\n          done\n        ultimately show ?thesis\n          using disj by blast\n      qed\n    qed\n  qed\n  have [simp]: \"convex hull T \\<subseteq> convex hull S\"\n    by (simp add: \\<open>T \\<subseteq> S\\<close> hull_mono)\n  show ?thesis\n    using open_segment_commute by (auto simp: face_of_def intro: *)\nqed\n\nproposition face_of_convex_hull_insert:\n   \"\\<lbrakk>finite S; a \\<notin> affine hull S; T face_of convex hull S\\<rbrakk> \\<Longrightarrow> T face_of convex hull insert a S\"\n  apply (rule face_of_trans, blast)\n  apply (rule face_of_convex_hulls; force simp: insert_Diff_if)\n  done\n\nproposition face_of_affine_trivial:\n    assumes \"affine S\" \"T face_of S\"\n    shows \"T = {} \\<or> T = S\"\nproof (rule ccontr, clarsimp)\n  assume \"T \\<noteq> {}\" \"T \\<noteq> S\"\n  then obtain a where \"a \\<in> T\" by auto\n  then have \"a \\<in> S\"\n    using \\<open>T face_of S\\<close> face_of_imp_subset by blast\n  have \"S \\<subseteq> T\"\n  proof\n    fix b  assume \"b \\<in> S\"\n    show \"b \\<in> T\"\n    proof (cases \"a = b\")\n      case True with \\<open>a \\<in> T\\<close> show ?thesis by auto\n    next\n      case False\n      then have \"a \\<in> open_segment (2 *\\<^sub>R a - b) b\"\n        apply (auto simp: open_segment_def closed_segment_def)\n        apply (rule_tac x=\"1/2\" in exI)\n        apply (simp add: algebra_simps)\n        by (simp add: scaleR_2)\n      moreover have \"2 *\\<^sub>R a - b \\<in> S\"\n        by (rule mem_affine [OF \\<open>affine S\\<close> \\<open>a \\<in> S\\<close> \\<open>b \\<in> S\\<close>, of 2 \"-1\", simplified])\n      moreover note \\<open>b \\<in> S\\<close> \\<open>a \\<in> T\\<close>\n      ultimately show ?thesis\n        by (rule face_ofD [OF \\<open>T face_of S\\<close>, THEN conjunct2])\n    qed\n  qed\n  then show False\n    using \\<open>T \\<noteq> S\\<close> \\<open>T face_of S\\<close> face_of_imp_subset by blast\nqed\n\n\nlemma face_of_affine_eq:\n   \"affine S \\<Longrightarrow> (T face_of S \\<longleftrightarrow> T = {} \\<or> T = S)\"\nusing affine_imp_convex face_of_affine_trivial face_of_refl by auto\n\n\nlemma Inter_faces_finite_altbound:\n    fixes T :: \"'a::euclidean_space set set\"\n    assumes cfaI: \"\\<And>c. c \\<in> T \\<Longrightarrow> c face_of S\"\n    shows \"\\<exists>F'. finite F' \\<and> F' \\<subseteq> T \\<and> card F' \\<le> DIM('a) + 2 \\<and> \\<Inter>F' = \\<Inter>T\"\nproof (cases \"\\<forall>F'. finite F' \\<and> F' \\<subseteq> T \\<and> card F' \\<le> DIM('a) + 2 \\<longrightarrow> (\\<exists>c. c \\<in> T \\<and> c \\<inter> (\\<Inter>F') \\<subset> (\\<Inter>F'))\")\n  case True\n  then obtain c where c:\n       \"\\<And>F'. \\<lbrakk>finite F'; F' \\<subseteq> T; card F' \\<le> DIM('a) + 2\\<rbrakk> \\<Longrightarrow> c F' \\<in> T \\<and> c F' \\<inter> (\\<Inter>F') \\<subset> (\\<Inter>F')\"\n    by metis\n  define d where \"d = rec_nat {c{}} (\\<lambda>n r. insert (c r) r)\"\n  have [simp]: \"d 0 = {c {}}\"\n    by (simp add: d_def)\n  have dSuc [simp]: \"\\<And>n. d (Suc n) = insert (c (d n)) (d n)\"\n    by (simp add: d_def)\n  have dn_notempty: \"d n \\<noteq> {}\" for n\n    by (induction n) auto\n  have dn_le_Suc: \"d n \\<subseteq> T \\<and> finite(d n) \\<and> card(d n) \\<le> Suc n\" if \"n \\<le> DIM('a) + 2\" for n\n  using that\n  proof (induction n)\n    case 0\n    then show ?case by (simp add: c)\n  next\n    case (Suc n)\n    then show ?case by (auto simp: c card_insert_if)\n  qed\n  have aff_dim_le: \"aff_dim(\\<Inter>(d n)) \\<le> DIM('a) - int n\" if \"n \\<le> DIM('a) + 2\" for n\n  using that\n  proof (induction n)\n    case 0\n    then show ?case\n      by (simp add: aff_dim_le_DIM)\n  next\n    case (Suc n)\n    have fs: \"\\<Inter>d (Suc n) face_of S\"\n      by (meson Suc.prems cfaI dn_le_Suc dn_notempty face_of_Inter subsetCE)\n    have condn: \"convex (\\<Inter>d n)\"\n      using Suc.prems nat_le_linear not_less_eq_eq\n      by (blast intro: face_of_imp_convex cfaI convex_Inter dest: dn_le_Suc)\n    have fdn: \"\\<Inter>d (Suc n) face_of \\<Inter>d n\"\n      by (metis (no_types, lifting) Inter_anti_mono Suc.prems dSuc cfaI dn_le_Suc dn_notempty face_of_Inter face_of_imp_subset face_of_subset subset_iff subset_insertI)\n    have ne: \"\\<Inter>d (Suc n) \\<noteq> \\<Inter>d n\"\n      by (metis (no_types, lifting) Suc.prems Suc_leD c complete_lattice_class.Inf_insert dSuc dn_le_Suc less_irrefl order.trans)\n    have *: \"\\<And>m::int. \\<And>d. \\<And>d'::int. d < d' \\<and> d' \\<le> m - n \\<Longrightarrow> d \\<le> m - of_nat(n+1)\"\n      by arith\n    have \"aff_dim (\\<Inter>d (Suc n)) < aff_dim (\\<Inter>d n)\"\n      by (rule face_of_aff_dim_lt [OF condn fdn ne])\n    moreover have \"aff_dim (\\<Inter>d n) \\<le> int (DIM('a)) - int n\"\n      using Suc by auto\n    ultimately\n    have \"aff_dim (\\<Inter>d (Suc n)) \\<le> int (DIM('a)) - (n+1)\" by arith\n    then show ?case by linarith\n  qed\n  have \"aff_dim (\\<Inter>d (DIM('a) + 2)) \\<le> -2\"\n      using aff_dim_le [OF order_refl] by simp\n  with aff_dim_geq [of \"\\<Inter>d (DIM('a) + 2)\"] show ?thesis\n    using order.trans by fastforce\nnext\n  case False\n  then show ?thesis\n    apply simp\n    apply (erule ex_forward)\n    by blast\nqed\n\nlemma faces_of_translation:\n   \"{F. F face_of image (\\<lambda>x. a + x) S} = image (image (\\<lambda>x. a + x)) {F. F face_of S}\"\napply (rule subset_antisym, clarify)\napply (auto simp: image_iff)\napply (metis face_of_imp_subset face_of_translation_eq subset_imageE)\ndone\n\nproposition face_of_Times:\n  assumes \"F face_of S\" and \"F' face_of S'\"\n    shows \"(F \\<times> F') face_of (S \\<times> S')\"\nproof -\n  have \"F \\<times> F' \\<subseteq> S \\<times> S'\"\n    using assms [unfolded face_of_def] by blast\n  moreover\n  have \"convex (F \\<times> F')\"\n    using assms [unfolded face_of_def] by (blast intro: convex_Times)\n  moreover\n    have \"a \\<in> F \\<and> a' \\<in> F' \\<and> b \\<in> F \\<and> b' \\<in> F'\"\n       if \"a \\<in> S\" \"b \\<in> S\" \"a' \\<in> S'\" \"b' \\<in> S'\" \"x \\<in> F \\<times> F'\" \"x \\<in> open_segment (a,a') (b,b')\"\n       for a b a' b' x\n  proof (cases \"b=a \\<or> b'=a'\")\n    case True with that show ?thesis\n      using assms\n      by (force simp: in_segment dest: face_ofD)\n  next\n    case False with assms [unfolded face_of_def] that show ?thesis\n      by (blast dest!: open_segment_PairD)\n  qed\n  ultimately show ?thesis\n    unfolding face_of_def by blast\nqed\n\ncorollary face_of_Times_decomp:\n    fixes S :: \"'a::euclidean_space set\" and S' :: \"'b::euclidean_space set\"\n    shows \"c face_of (S \\<times> S') \\<longleftrightarrow> (\\<exists>F F'. F face_of S \\<and> F' face_of S' \\<and> c = F \\<times> F')\"\n     (is \"?lhs = ?rhs\")\nproof\n  assume c: ?lhs\n  show ?rhs\n  proof (cases \"c = {}\")\n    case True then show ?thesis by auto\n  next\n    case False\n    have 1: \"fst ` c \\<subseteq> S\" \"snd ` c \\<subseteq> S'\"\n      using c face_of_imp_subset by fastforce+\n    have \"convex c\"\n      using c by (metis face_of_imp_convex)\n    have conv: \"convex (fst ` c)\" \"convex (snd ` c)\"\n      by (simp_all add: \\<open>convex c\\<close> convex_linear_image fst_linear snd_linear)\n    have fstab: \"a \\<in> fst ` c \\<and> b \\<in> fst ` c\"\n            if \"a \\<in> S\" \"b \\<in> S\" \"x \\<in> open_segment a b\" \"(x,x') \\<in> c\" for a b x x'\n    proof -\n      have *: \"(x,x') \\<in> open_segment (a,x') (b,x')\"\n        using that by (auto simp: in_segment)\n      show ?thesis\n        using face_ofD [OF c *] that face_of_imp_subset [OF c] by force\n    qed\n    have fst: \"fst ` c face_of S\"\n      by (force simp: face_of_def 1 conv fstab)\n    have sndab: \"a' \\<in> snd ` c \\<and> b' \\<in> snd ` c\"\n            if \"a' \\<in> S'\" \"b' \\<in> S'\" \"x' \\<in> open_segment a' b'\" \"(x,x') \\<in> c\" for a' b' x x'\n    proof -\n      have *: \"(x,x') \\<in> open_segment (x,a') (x,b')\"\n        using that by (auto simp: in_segment)\n      show ?thesis\n        using face_ofD [OF c *] that face_of_imp_subset [OF c] by force\n    qed\n    have snd: \"snd ` c face_of S'\"\n      by (force simp: face_of_def 1 conv sndab)\n    have cc: \"rel_interior c \\<subseteq> rel_interior (fst ` c) \\<times> rel_interior (snd ` c)\"\n      by (force simp: face_of_Times rel_interior_Times conv fst snd \\<open>convex c\\<close> fst_linear snd_linear rel_interior_convex_linear_image [symmetric])\n    have \"c = fst ` c \\<times> snd ` c\"\n      apply (rule face_of_eq [OF c])\n      apply (simp_all add: face_of_Times rel_interior_Times conv fst snd)\n      using False rel_interior_eq_empty \\<open>convex c\\<close> cc\n      apply blast\n      done\n    with fst snd show ?thesis by metis\n  qed\nnext\n  assume ?rhs with face_of_Times show ?lhs by auto\nqed\n\nlemma face_of_Times_eq:\n    fixes S :: \"'a::euclidean_space set\" and S' :: \"'b::euclidean_space set\"\n    shows \"(F \\<times> F') face_of (S \\<times> S') \\<longleftrightarrow>\n           F = {} \\<or> F' = {} \\<or> F face_of S \\<and> F' face_of S'\"\nby (auto simp: face_of_Times_decomp times_eq_iff)\n\nlemma hyperplane_face_of_halfspace_le: \"{x. a \\<bullet> x = b} face_of {x. a \\<bullet> x \\<le> b}\"\nproof -\n  have \"{x. a \\<bullet> x \\<le> b} \\<inter> {x. a \\<bullet> x = b} = {x. a \\<bullet> x = b}\"\n    by auto\n  with face_of_Int_supporting_hyperplane_le [OF convex_halfspace_le [of a b], of a b]\n  show ?thesis by auto\nqed\n\nlemma hyperplane_face_of_halfspace_ge: \"{x. a \\<bullet> x = b} face_of {x. a \\<bullet> x \\<ge> b}\"\nproof -\n  have \"{x. a \\<bullet> x \\<ge> b} \\<inter> {x. a \\<bullet> x = b} = {x. a \\<bullet> x = b}\"\n    by auto\n  with face_of_Int_supporting_hyperplane_ge [OF convex_halfspace_ge [of b a], of b a]\n  show ?thesis by auto\nqed\n\nlemma face_of_halfspace_le:\n  fixes a :: \"'n::euclidean_space\"\n  shows \"F face_of {x. a \\<bullet> x \\<le> b} \\<longleftrightarrow>\n         F = {} \\<or> F = {x. a \\<bullet> x = b} \\<or> F = {x. a \\<bullet> x \\<le> b}\"\n     (is \"?lhs = ?rhs\")\nproof (cases \"a = 0\")\n  case True then show ?thesis\n    using face_of_affine_eq affine_UNIV by auto\nnext\n  case False\n  then have ine: \"interior {x. a \\<bullet> x \\<le> b} \\<noteq> {}\"\n    using halfspace_eq_empty_lt interior_halfspace_le by blast\n  show ?thesis\n  proof\n    assume L: ?lhs\n    have \"F \\<noteq> {x. a \\<bullet> x \\<le> b} \\<Longrightarrow> F face_of {x. a \\<bullet> x = b}\"\n      using False\n      apply (simp add: frontier_halfspace_le [symmetric] rel_frontier_nonempty_interior [OF ine, symmetric])\n      apply (rule face_of_subset [OF L])\n      apply (simp add: face_of_subset_rel_frontier [OF L])\n      apply (force simp: rel_frontier_def closed_halfspace_le)\n      done\n    with L show ?rhs\n      using affine_hyperplane face_of_affine_eq by blast\n  next\n    assume ?rhs\n    then show ?lhs\n      by (metis convex_halfspace_le empty_face_of face_of_refl hyperplane_face_of_halfspace_le)\n  qed\nqed\n\nlemma face_of_halfspace_ge:\n  fixes a :: \"'n::euclidean_space\"\n  shows \"F face_of {x. a \\<bullet> x \\<ge> b} \\<longleftrightarrow>\n         F = {} \\<or> F = {x. a \\<bullet> x = b} \\<or> F = {x. a \\<bullet> x \\<ge> b}\"\nusing face_of_halfspace_le [of F \"-a\" \"-b\"] by simp\n\nsubsection\\<open>Exposed faces\\<close>\n\ntext\\<open>That is, faces that are intersection with supporting hyperplane\\<close>\n\ndefinition exposed_face_of :: \"['a::euclidean_space set, 'a set] \\<Rightarrow> bool\"\n                               (infixr \"(exposed'_face'_of)\" 50)\n  where \"T exposed_face_of S \\<longleftrightarrow>\n         T face_of S \\<and> (\\<exists>a b. S \\<subseteq> {x. a \\<bullet> x \\<le> b} \\<and> T = S \\<inter> {x. a \\<bullet> x = b})\"\n\nlemma empty_exposed_face_of [iff]: \"{} exposed_face_of S\"\n  apply (simp add: exposed_face_of_def)\n  apply (rule_tac x=0 in exI)\n  apply (rule_tac x=1 in exI, force)\n  done\n\nlemma exposed_face_of_refl_eq [simp]: \"S exposed_face_of S \\<longleftrightarrow> convex S\"\n  apply (simp add: exposed_face_of_def face_of_refl_eq, auto)\n  apply (rule_tac x=0 in exI)+\n  apply force\n  done\n\nlemma exposed_face_of_refl: \"convex S \\<Longrightarrow> S exposed_face_of S\"\n  by simp\n\nlemma exposed_face_of:\n    \"T exposed_face_of S \\<longleftrightarrow>\n     T face_of S \\<and>\n     (T = {} \\<or> T = S \\<or>\n      (\\<exists>a b. a \\<noteq> 0 \\<and> S \\<subseteq> {x. a \\<bullet> x \\<le> b} \\<and> T = S \\<inter> {x. a \\<bullet> x = b}))\"\nproof (cases \"T = {}\")\n  case True then show ?thesis\n    by simp\nnext\n  case False\n  show ?thesis\n  proof (cases \"T = S\")\n    case True then show ?thesis\n      by (simp add: face_of_refl_eq)\n  next\n    case False\n    with \\<open>T \\<noteq> {}\\<close> show ?thesis\n      apply (auto simp: exposed_face_of_def)\n      apply (metis inner_zero_left)\n      done\n  qed\nqed\n\nlemma exposed_face_of_Int_supporting_hyperplane_le:\n   \"\\<lbrakk>convex S; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<le> b\\<rbrakk> \\<Longrightarrow> (S \\<inter> {x. a \\<bullet> x = b}) exposed_face_of S\"\nby (force simp: exposed_face_of_def face_of_Int_supporting_hyperplane_le)\n\nlemma exposed_face_of_Int_supporting_hyperplane_ge:\n   \"\\<lbrakk>convex S; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<ge> b\\<rbrakk> \\<Longrightarrow> (S \\<inter> {x. a \\<bullet> x = b}) exposed_face_of S\"\nusing exposed_face_of_Int_supporting_hyperplane_le [of S \"-a\" \"-b\"] by simp\n\nproposition exposed_face_of_Int:\n  assumes \"T exposed_face_of S\"\n      and \"u exposed_face_of S\"\n    shows \"(T \\<inter> u) exposed_face_of S\"\nproof -\n  obtain a b where T: \"S \\<inter> {x. a \\<bullet> x = b} face_of S\"\n               and S: \"S \\<subseteq> {x. a \\<bullet> x \\<le> b}\"\n               and teq: \"T = S \\<inter> {x. a \\<bullet> x = b}\"\n    using assms by (auto simp: exposed_face_of_def)\n  obtain a' b' where u: \"S \\<inter> {x. a' \\<bullet> x = b'} face_of S\"\n                 and s': \"S \\<subseteq> {x. a' \\<bullet> x \\<le> b'}\"\n                 and ueq: \"u = S \\<inter> {x. a' \\<bullet> x = b'}\"\n    using assms by (auto simp: exposed_face_of_def)\n  have tu: \"T \\<inter> u face_of S\"\n    using T teq u ueq by (simp add: face_of_Int)\n  have ss: \"S \\<subseteq> {x. (a + a') \\<bullet> x \\<le> b + b'}\"\n    using S s' by (force simp: inner_left_distrib)\n  show ?thesis\n    apply (simp add: exposed_face_of_def tu)\n    apply (rule_tac x=\"a+a'\" in exI)\n    apply (rule_tac x=\"b+b'\" in exI)\n    using S s'\n    apply (fastforce simp: ss inner_left_distrib teq ueq)\n    done\nqed\n\nproposition exposed_face_of_Inter:\n    fixes P :: \"'a::euclidean_space set set\"\n  assumes \"P \\<noteq> {}\"\n      and \"\\<And>T. T \\<in> P \\<Longrightarrow> T exposed_face_of S\"\n    shows \"\\<Inter>P exposed_face_of S\"\nproof -\n  obtain Q where \"finite Q\" and QsubP: \"Q \\<subseteq> P\" \"card Q \\<le> DIM('a) + 2\" and IntQ: \"\\<Inter>Q = \\<Inter>P\"\n    using Inter_faces_finite_altbound [of P S] assms [unfolded exposed_face_of]\n    by force\n  show ?thesis\n  proof (cases \"Q = {}\")\n    case True then show ?thesis\n      by (metis Inf_empty Inf_lower IntQ assms ex_in_conv subset_antisym top_greatest)\n  next\n    case False\n    have \"Q \\<subseteq> {T. T exposed_face_of S}\"\n      using QsubP assms by blast\n    moreover have \"Q \\<subseteq> {T. T exposed_face_of S} \\<Longrightarrow> \\<Inter>Q exposed_face_of S\"\n      using \\<open>finite Q\\<close> False\n      apply (induction Q rule: finite_induct)\n      using exposed_face_of_Int apply fastforce+\n      done\n    ultimately show ?thesis\n      by (simp add: IntQ)\n  qed\nqed\n\nproposition exposed_face_of_sums:\n  assumes \"convex S\" and \"convex T\"\n      and \"F exposed_face_of {x + y | x y. x \\<in> S \\<and> y \\<in> T}\"\n          (is \"F exposed_face_of ?ST\")\n  obtains k l\n    where \"k exposed_face_of S\" \"l exposed_face_of T\"\n          \"F = {x + y | x y. x \\<in> k \\<and> y \\<in> l}\"\nproof (cases \"F = {}\")\n  case True then show ?thesis\n    using that by blast\nnext\n  case False\n  show ?thesis\n  proof (cases \"F = ?ST\")\n    case True then show ?thesis\n      using assms exposed_face_of_refl_eq that by blast\n  next\n    case False\n    obtain p where \"p \\<in> F\" using \\<open>F \\<noteq> {}\\<close> by blast\n    moreover\n    obtain u z where T: \"?ST \\<inter> {x. u \\<bullet> x = z} face_of ?ST\"\n                 and S: \"?ST \\<subseteq> {x. u \\<bullet> x \\<le> z}\"\n                 and feq: \"F = ?ST \\<inter> {x. u \\<bullet> x = z}\"\n      using assms by (auto simp: exposed_face_of_def)\n    ultimately obtain a0 b0\n            where p: \"p = a0 + b0\" and \"a0 \\<in> S\" \"b0 \\<in> T\" and z: \"u \\<bullet> p = z\"\n      by auto\n    have lez: \"u \\<bullet> (x + y) \\<le> z\" if \"x \\<in> S\" \"y \\<in> T\" for x y\n      using S that by auto\n    have sef: \"S \\<inter> {x. u \\<bullet> x = u \\<bullet> a0} exposed_face_of S\"\n      apply (rule exposed_face_of_Int_supporting_hyperplane_le [OF \\<open>convex S\\<close>])\n      apply (metis p z add_le_cancel_right inner_right_distrib lez [OF _ \\<open>b0 \\<in> T\\<close>])\n      done\n    have tef: \"T \\<inter> {x. u \\<bullet> x = u \\<bullet> b0} exposed_face_of T\"\n      apply (rule exposed_face_of_Int_supporting_hyperplane_le [OF \\<open>convex T\\<close>])\n      apply (metis p z add.commute add_le_cancel_right inner_right_distrib lez [OF \\<open>a0 \\<in> S\\<close>])\n      done\n    have \"{x + y |x y. x \\<in> S \\<and> u \\<bullet> x = u \\<bullet> a0 \\<and> y \\<in> T \\<and> u \\<bullet> y = u \\<bullet> b0} \\<subseteq> F\"\n      by (auto simp: feq) (metis inner_right_distrib p z)\n    moreover have \"F \\<subseteq> {x + y |x y. x \\<in> S \\<and> u \\<bullet> x = u \\<bullet> a0 \\<and> y \\<in> T \\<and> u \\<bullet> y = u \\<bullet> b0}\"\n      apply (auto simp: feq)\n      apply (rename_tac x y)\n      apply (rule_tac x=x in exI)\n      apply (rule_tac x=y in exI, simp)\n      using z p \\<open>a0 \\<in> S\\<close> \\<open>b0 \\<in> T\\<close>\n      apply clarify\n      apply (simp add: inner_right_distrib)\n      apply (metis add_le_cancel_right antisym lez [unfolded inner_right_distrib] add.commute)\n      done\n    ultimately have \"F = {x + y |x y. x \\<in> S \\<inter> {x. u \\<bullet> x = u \\<bullet> a0} \\<and> y \\<in> T \\<inter> {x. u \\<bullet> x = u \\<bullet> b0}}\"\n      by blast\n    then show ?thesis\n      by (rule that [OF sef tef])\n  qed\nqed\n\nsubsection\\<open>Extreme points of a set: its singleton faces\\<close>\n\ndefinition extreme_point_of :: \"['a::real_vector, 'a set] \\<Rightarrow> bool\"\n                               (infixr \"(extreme'_point'_of)\" 50)\n  where \"x extreme_point_of S \\<longleftrightarrow>\n         x \\<in> S \\<and> (\\<forall>a \\<in> S. \\<forall>b \\<in> S. x \\<notin> open_segment a b)\"\n\nlemma extreme_point_of_stillconvex:\n   \"convex S \\<Longrightarrow> (x extreme_point_of S \\<longleftrightarrow> x \\<in> S \\<and> convex(S - {x}))\"\n  by (fastforce simp add: convex_contains_segment extreme_point_of_def open_segment_def)\n\nlemma face_of_singleton:\n   \"{x} face_of S \\<longleftrightarrow> x extreme_point_of S\"\nby (fastforce simp add: extreme_point_of_def face_of_def)\n\nlemma extreme_point_not_in_REL_INTERIOR:\n    fixes S :: \"'a::real_normed_vector set\"\n    shows \"\\<lbrakk>x extreme_point_of S; S \\<noteq> {x}\\<rbrakk> \\<Longrightarrow> x \\<notin> rel_interior S\"\napply (simp add: face_of_singleton [symmetric])\napply (blast dest: face_of_disjoint_rel_interior)\ndone\n\nlemma extreme_point_not_in_interior:\n    fixes S :: \"'a::{real_normed_vector, perfect_space} set\"\n    shows \"x extreme_point_of S \\<Longrightarrow> x \\<notin> interior S\"\napply (case_tac \"S = {x}\")\napply (simp add: empty_interior_finite)\nby (meson contra_subsetD extreme_point_not_in_REL_INTERIOR interior_subset_rel_interior)\n\nlemma extreme_point_of_face:\n     \"F face_of S \\<Longrightarrow> v extreme_point_of F \\<longleftrightarrow> v extreme_point_of S \\<and> v \\<in> F\"\n  by (meson empty_subsetI face_of_face face_of_singleton insert_subset)\n\nlemma extreme_point_of_convex_hull:\n   \"x extreme_point_of (convex hull S) \\<Longrightarrow> x \\<in> S\"\napply (simp add: extreme_point_of_stillconvex)\nusing hull_minimal [of S \"(convex hull S) - {x}\" convex]\nusing hull_subset [of S convex]\napply blast\ndone\n\nlemma extreme_points_of_convex_hull:\n   \"{x. x extreme_point_of (convex hull S)} \\<subseteq> S\"\nusing extreme_point_of_convex_hull by auto\n\nlemma extreme_point_of_empty [simp]: \"~ (x extreme_point_of {})\"\n  by (simp add: extreme_point_of_def)\n\nlemma extreme_point_of_singleton [iff]: \"x extreme_point_of {a} \\<longleftrightarrow> x = a\"\n  using extreme_point_of_stillconvex by auto\n\nlemma extreme_point_of_translation_eq:\n   \"(a + x) extreme_point_of (image (\\<lambda>x. a + x) S) \\<longleftrightarrow> x extreme_point_of S\"\nby (auto simp: extreme_point_of_def)\n\nlemma extreme_points_of_translation:\n   \"{x. x extreme_point_of (image (\\<lambda>x. a + x) S)} =\n    (\\<lambda>x. a + x) ` {x. x extreme_point_of S}\"\nusing extreme_point_of_translation_eq\nby auto (metis (no_types, lifting) image_iff mem_Collect_eq minus_add_cancel)\n\nlemma extreme_point_of_Int:\n   \"\\<lbrakk>x extreme_point_of S; x extreme_point_of T\\<rbrakk> \\<Longrightarrow> x extreme_point_of (S \\<inter> T)\"\nby (simp add: extreme_point_of_def)\n\nlemma extreme_point_of_Int_supporting_hyperplane_le:\n   \"\\<lbrakk>S \\<inter> {x. a \\<bullet> x = b} = {c}; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<le> b\\<rbrakk> \\<Longrightarrow> c extreme_point_of S\"\napply (simp add: face_of_singleton [symmetric])\nby (metis face_of_Int_supporting_hyperplane_le_strong convex_singleton)\n\nlemma extreme_point_of_Int_supporting_hyperplane_ge:\n   \"\\<lbrakk>S \\<inter> {x. a \\<bullet> x = b} = {c}; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<ge> b\\<rbrakk> \\<Longrightarrow> c extreme_point_of S\"\napply (simp add: face_of_singleton [symmetric])\nby (metis face_of_Int_supporting_hyperplane_ge_strong convex_singleton)\n\nlemma exposed_point_of_Int_supporting_hyperplane_le:\n   \"\\<lbrakk>S \\<inter> {x. a \\<bullet> x = b} = {c}; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<le> b\\<rbrakk> \\<Longrightarrow> {c} exposed_face_of S\"\napply (simp add: exposed_face_of_def face_of_singleton)\napply (force simp: extreme_point_of_Int_supporting_hyperplane_le)\ndone\n\nlemma exposed_point_of_Int_supporting_hyperplane_ge:\n    \"\\<lbrakk>S \\<inter> {x. a \\<bullet> x = b} = {c}; \\<And>x. x \\<in> S \\<Longrightarrow> a \\<bullet> x \\<ge> b\\<rbrakk> \\<Longrightarrow> {c} exposed_face_of S\"\nusing exposed_point_of_Int_supporting_hyperplane_le [of S \"-a\" \"-b\" c]\nby simp\n\nlemma extreme_point_of_convex_hull_insert:\n   \"\\<lbrakk>finite S; a \\<notin> convex hull S\\<rbrakk> \\<Longrightarrow> a extreme_point_of (convex hull (insert a S))\"\napply (case_tac \"a \\<in> S\")\napply (simp add: hull_inc)\nusing face_of_convex_hulls [of \"insert a S\" \"{a}\"]\napply (auto simp: face_of_singleton hull_same)\ndone\n\nsubsection\\<open>Facets\\<close>\n\ndefinition facet_of :: \"['a::euclidean_space set, 'a set] \\<Rightarrow> bool\"\n                    (infixr \"(facet'_of)\" 50)\n  where \"F facet_of S \\<longleftrightarrow> F face_of S \\<and> F \\<noteq> {} \\<and> aff_dim F = aff_dim S - 1\"\n\nlemma facet_of_empty [simp]: \"~ S facet_of {}\"\n  by (simp add: facet_of_def)\n\nlemma facet_of_irrefl [simp]: \"~ S facet_of S \"\n  by (simp add: facet_of_def)\n\nlemma facet_of_imp_face_of: \"F facet_of S \\<Longrightarrow> F face_of S\"\n  by (simp add: facet_of_def)\n\nlemma facet_of_imp_subset: \"F facet_of S \\<Longrightarrow> F \\<subseteq> S\"\n  by (simp add: face_of_imp_subset facet_of_def)\n\nlemma hyperplane_facet_of_halfspace_le:\n   \"a \\<noteq> 0 \\<Longrightarrow> {x. a \\<bullet> x = b} facet_of {x. a \\<bullet> x \\<le> b}\"\nunfolding facet_of_def hyperplane_eq_empty\nby (auto simp: hyperplane_face_of_halfspace_ge hyperplane_face_of_halfspace_le\n           DIM_positive Suc_leI of_nat_diff aff_dim_halfspace_le)\n\nlemma hyperplane_facet_of_halfspace_ge:\n    \"a \\<noteq> 0 \\<Longrightarrow> {x. a \\<bullet> x = b} facet_of {x. a \\<bullet> x \\<ge> b}\"\nunfolding facet_of_def hyperplane_eq_empty\nby (auto simp: hyperplane_face_of_halfspace_le hyperplane_face_of_halfspace_ge\n           DIM_positive Suc_leI of_nat_diff aff_dim_halfspace_ge)\n\nlemma facet_of_halfspace_le:\n    \"F facet_of {x. a \\<bullet> x \\<le> b} \\<longleftrightarrow> a \\<noteq> 0 \\<and> F = {x. a \\<bullet> x = b}\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume c: ?lhs\n  with c facet_of_irrefl show ?rhs\n    by (force simp: aff_dim_halfspace_le facet_of_def face_of_halfspace_le cong: conj_cong split: if_split_asm)\nnext\n  assume ?rhs then show ?lhs\n    by (simp add: hyperplane_facet_of_halfspace_le)\nqed\n\nlemma facet_of_halfspace_ge:\n    \"F facet_of {x. a \\<bullet> x \\<ge> b} \\<longleftrightarrow> a \\<noteq> 0 \\<and> F = {x. a \\<bullet> x = b}\"\nusing facet_of_halfspace_le [of F \"-a\" \"-b\"] by simp\n\nsubsection \\<open>Edges: faces of affine dimension 1\\<close>\n\ndefinition edge_of :: \"['a::euclidean_space set, 'a set] \\<Rightarrow> bool\"  (infixr \"(edge'_of)\" 50)\n  where \"e edge_of S \\<longleftrightarrow> e face_of S \\<and> aff_dim e = 1\"\n\nlemma edge_of_imp_subset:\n   \"S edge_of T \\<Longrightarrow> S \\<subseteq> T\"\nby (simp add: edge_of_def face_of_imp_subset)\n\nsubsection\\<open>Existence of extreme points\\<close>\n\nlemma different_norm_3_collinear_points:\n  fixes a :: \"'a::euclidean_space\"\n  assumes \"x \\<in> open_segment a b\" \"norm(a) = norm(b)\" \"norm(x) = norm(b)\"\n  shows False\nproof -\n  obtain u where \"norm ((1 - u) *\\<^sub>R a + u *\\<^sub>R b) = norm b\"\n             and \"a \\<noteq> b\"\n             and u01: \"0 < u\" \"u < 1\"\n    using assms by (auto simp: open_segment_image_interval if_splits)\n  then have \"(1 - u) *\\<^sub>R a \\<bullet> (1 - u) *\\<^sub>R a + ((1 - u) * 2) *\\<^sub>R a \\<bullet> u *\\<^sub>R b =\n             (1 - u * u) *\\<^sub>R (a \\<bullet> a)\"\n    using assms by (simp add: norm_eq algebra_simps inner_commute)\n  then have \"(1 - u) *\\<^sub>R ((1 - u) *\\<^sub>R a \\<bullet> a + (2 * u) *\\<^sub>R  a \\<bullet> b) =\n             (1 - u) *\\<^sub>R ((1 + u) *\\<^sub>R (a \\<bullet> a))\"\n    by (simp add: algebra_simps)\n  then have \"(1 - u) *\\<^sub>R (a \\<bullet> a) + (2 * u) *\\<^sub>R (a \\<bullet> b) = (1 + u) *\\<^sub>R (a \\<bullet> a)\"\n    using u01 by auto\n  then have \"a \\<bullet> b = a \\<bullet> a\"\n    using u01 by (simp add: algebra_simps)\n  then have \"a = b\"\n    using \\<open>norm(a) = norm(b)\\<close> norm_eq vector_eq by fastforce\n  then show ?thesis\n    using \\<open>a \\<noteq> b\\<close> by force\nqed\n\nproposition extreme_point_exists_convex:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"compact S\" \"convex S\" \"S \\<noteq> {}\"\n  obtains x where \"x extreme_point_of S\"\nproof -\n  obtain x where \"x \\<in> S\" and xsup: \"\\<And>y. y \\<in> S \\<Longrightarrow> norm y \\<le> norm x\"\n    using distance_attains_sup [of S 0] assms by auto\n  have False if \"a \\<in> S\" \"b \\<in> S\" and x: \"x \\<in> open_segment a b\" for a b\n  proof -\n    have noax: \"norm a \\<le> norm x\" and nobx: \"norm b \\<le> norm x\" using xsup that by auto\n    have \"a \\<noteq> b\"\n      using empty_iff open_segment_idem x by auto\n    have *: \"(1 - u) * na + u * nb < norm x\" if \"na < norm x\"  \"nb \\<le> norm x\" \"0 < u\" \"u < 1\" for na nb u\n    proof -\n      have \"(1 - u) * na + u * nb < (1 - u) * norm x + u * nb\"\n        by (simp add: that)\n      also have \"... \\<le> (1 - u) * norm x + u * norm x\"\n        by (simp add: that)\n      finally have \"(1 - u) * na + u * nb < (1 - u) * norm x + u * norm x\" .\n      then show ?thesis\n      using scaleR_collapse [symmetric, of \"norm x\" u] by auto\n    qed\n    have \"norm x < norm x\" if \"norm a < norm x\"\n      using x\n      apply (clarsimp simp only: open_segment_image_interval \\<open>a \\<noteq> b\\<close> if_False)\n      apply (rule norm_triangle_lt)\n      apply (simp add: norm_mult)\n      using * [of \"norm a\" \"norm b\"] nobx that\n        apply blast\n      done\n    moreover have \"norm x < norm x\" if \"norm b < norm x\"\n      using x\n      apply (clarsimp simp only: open_segment_image_interval \\<open>a \\<noteq> b\\<close> if_False)\n      apply (rule norm_triangle_lt)\n      apply (simp add: norm_mult)\n      using * [of \"norm b\" \"norm a\" \"1-u\" for u] noax that\n        apply (simp add: add.commute)\n      done\n    ultimately have \"~ (norm a < norm x) \\<and> ~ (norm b < norm x)\"\n      by auto\n    then show ?thesis\n      using different_norm_3_collinear_points noax nobx that(3) by fastforce\n  qed\n  then show ?thesis\n    apply (rule_tac x=x in that)\n    apply (force simp: extreme_point_of_def \\<open>x \\<in> S\\<close>)\n    done\nqed\n\nsubsection\\<open>Krein-Milman, the weaker form\\<close>\n\nproposition Krein_Milman:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"compact S\" \"convex S\"\n    shows \"S = closure(convex hull {x. x extreme_point_of S})\"\nproof (cases \"S = {}\")\n  case True then show ?thesis   by simp\nnext\n  case False\n  have \"closed S\"\n    by (simp add: \\<open>compact S\\<close> compact_imp_closed)\n  have \"closure (convex hull {x. x extreme_point_of S}) \\<subseteq> S\"\n    apply (rule closure_minimal [OF hull_minimal \\<open>closed S\\<close>])\n    using assms\n    apply (auto simp: extreme_point_of_def)\n    done\n  moreover have \"u \\<in> closure (convex hull {x. x extreme_point_of S})\"\n                if \"u \\<in> S\" for u\n  proof (rule ccontr)\n    assume unot: \"u \\<notin> closure(convex hull {x. x extreme_point_of S})\"\n    then obtain a b where \"a \\<bullet> u < b\"\n          and ab: \"\\<And>x. x \\<in> closure(convex hull {x. x extreme_point_of S}) \\<Longrightarrow> b < a \\<bullet> x\"\n      using separating_hyperplane_closed_point [of \"closure(convex hull {x. x extreme_point_of S})\"]\n      by blast\n    have \"continuous_on S (op \\<bullet> a)\"\n      by (rule continuous_intros)+\n    then obtain m where \"m \\<in> S\" and m: \"\\<And>y. y \\<in> S \\<Longrightarrow> a \\<bullet> m \\<le> a \\<bullet> y\"\n      using continuous_attains_inf [of S \"\\<lambda>x. a \\<bullet> x\"] \\<open>compact S\\<close> \\<open>u \\<in> S\\<close>\n      by auto\n    define T where \"T = S \\<inter> {x. a \\<bullet> x = a \\<bullet> m}\"\n    have \"m \\<in> T\"\n      by (simp add: T_def \\<open>m \\<in> S\\<close>)\n    moreover have \"compact T\"\n      by (simp add: T_def compact_Int_closed [OF \\<open>compact S\\<close> closed_hyperplane])\n    moreover have \"convex T\"\n      by (simp add: T_def convex_Int [OF \\<open>convex S\\<close> convex_hyperplane])\n    ultimately obtain v where v: \"v extreme_point_of T\"\n      using extreme_point_exists_convex [of T] by auto\n    then have \"{v} face_of T\"\n      by (simp add: face_of_singleton)\n    also have \"T face_of S\"\n      by (simp add: T_def m face_of_Int_supporting_hyperplane_ge [OF \\<open>convex S\\<close>])\n    finally have \"v extreme_point_of S\"\n      by (simp add: face_of_singleton)\n    then have \"b < a \\<bullet> v\"\n      using closure_subset by (simp add: closure_hull hull_inc ab)\n    then show False\n      using \\<open>a \\<bullet> u < b\\<close> \\<open>{v} face_of T\\<close> face_of_imp_subset m T_def that by fastforce\n  qed\n  ultimately show ?thesis\n    by blast\nqed\n\ntext\\<open>Now the sharper form.\\<close>\n\nlemma Krein_Milman_Minkowski_aux:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes n: \"dim S = n\" and S: \"compact S\" \"convex S\" \"0 \\<in> S\"\n    shows \"0 \\<in> convex hull {x. x extreme_point_of S}\"\nusing n S\nproof (induction n arbitrary: S rule: less_induct)\n  case (less n S) show ?case\n  proof (cases \"0 \\<in> rel_interior S\")\n    case True with Krein_Milman show ?thesis\n      by (metis subsetD convex_convex_hull convex_rel_interior_closure less.prems(2) less.prems(3) rel_interior_subset)\n  next\n    case False\n    have \"rel_interior S \\<noteq> {}\"\n      by (simp add: rel_interior_convex_nonempty_aux less)\n    then obtain c where c: \"c \\<in> rel_interior S\" by blast\n    obtain a where \"a \\<noteq> 0\"\n              and le_ay: \"\\<And>y. y \\<in> S \\<Longrightarrow> a \\<bullet> 0 \\<le> a \\<bullet> y\"\n              and less_ay: \"\\<And>y. y \\<in> rel_interior S \\<Longrightarrow> a \\<bullet> 0 < a \\<bullet> y\"\n      by (blast intro: supporting_hyperplane_rel_boundary intro!: less False)\n    have face: \"S \\<inter> {x. a \\<bullet> x = 0} face_of S\"\n      apply (rule face_of_Int_supporting_hyperplane_ge [OF \\<open>convex S\\<close>])\n      using le_ay by auto\n    then have co: \"compact (S \\<inter> {x. a \\<bullet> x = 0})\" \"convex (S \\<inter> {x. a \\<bullet> x = 0})\"\n      using less.prems by (blast intro: face_of_imp_compact face_of_imp_convex)+\n    have \"a \\<bullet> y = 0\" if \"y \\<in> span (S \\<inter> {x. a \\<bullet> x = 0})\" for y\n    proof -\n      have \"y \\<in> span {x. a \\<bullet> x = 0}\"\n        by (metis inf.cobounded2 span_mono subsetCE that)\n      then show ?thesis\n        by (blast intro: span_induct [OF _ subspace_hyperplane])\n    qed\n    then have \"dim (S \\<inter> {x. a \\<bullet> x = 0}) < n\"\n      by (metis (no_types) less_ay c subsetD dim_eq_span inf.strict_order_iff\n           inf_le1 \\<open>dim S = n\\<close> not_le rel_interior_subset span_0 span_clauses(1))\n    then have \"0 \\<in> convex hull {x. x extreme_point_of (S \\<inter> {x. a \\<bullet> x = 0})}\"\n      by (rule less.IH) (auto simp: co less.prems)\n    then show ?thesis\n      by (metis (mono_tags, lifting) Collect_mono_iff \\<open>S \\<inter> {x. a \\<bullet> x = 0} face_of S\\<close> extreme_point_of_face hull_mono subset_iff)\n  qed\nqed\n\n\ntheorem Krein_Milman_Minkowski:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"compact S\" \"convex S\"\n    shows \"S = convex hull {x. x extreme_point_of S}\"\nproof\n  show \"S \\<subseteq> convex hull {x. x extreme_point_of S}\"\n  proof\n    fix a assume [simp]: \"a \\<in> S\"\n    have 1: \"compact (op + (- a) ` S)\"\n      by (simp add: \\<open>compact S\\<close> compact_translation)\n    have 2: \"convex (op + (- a) ` S)\"\n      by (simp add: \\<open>convex S\\<close> convex_translation)\n    show a_invex: \"a \\<in> convex hull {x. x extreme_point_of S}\"\n      using Krein_Milman_Minkowski_aux [OF refl 1 2]\n            convex_hull_translation [of \"-a\"]\n      by (auto simp: extreme_points_of_translation translation_assoc)\n    qed\nnext\n  show \"convex hull {x. x extreme_point_of S} \\<subseteq> S\"\n  proof -\n    have \"{a. a extreme_point_of S} \\<subseteq> S\"\n      using extreme_point_of_def by blast\n    then show ?thesis\n      by (simp add: \\<open>convex S\\<close> hull_minimal)\n  qed\nqed\n\n\nsubsection\\<open>Applying it to convex hulls of explicitly indicated finite sets\\<close>\n\nlemma Krein_Milman_polytope:\n  fixes S :: \"'a::euclidean_space set\"\n  shows\n   \"finite S\n       \\<Longrightarrow> convex hull S =\n           convex hull {x. x extreme_point_of (convex hull S)}\"\nby (simp add: Krein_Milman_Minkowski finite_imp_compact_convex_hull)\n\nlemma extreme_points_of_convex_hull_eq:\n  fixes S :: \"'a::euclidean_space set\"\n  shows\n   \"\\<lbrakk>compact S; \\<And>T. T \\<subset> S \\<Longrightarrow> convex hull T \\<noteq> convex hull S\\<rbrakk>\n        \\<Longrightarrow> {x. x extreme_point_of (convex hull S)} = S\"\nby (metis (full_types) Krein_Milman_Minkowski compact_convex_hull convex_convex_hull extreme_points_of_convex_hull psubsetI)\n\n\nlemma extreme_point_of_convex_hull_eq:\n  fixes S :: \"'a::euclidean_space set\"\n  shows\n   \"\\<lbrakk>compact S; \\<And>T. T \\<subset> S \\<Longrightarrow> convex hull T \\<noteq> convex hull S\\<rbrakk>\n    \\<Longrightarrow> (x extreme_point_of (convex hull S) \\<longleftrightarrow> x \\<in> S)\"\nusing extreme_points_of_convex_hull_eq by auto\n\nlemma extreme_point_of_convex_hull_convex_independent:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"compact S\" and S: \"\\<And>a. a \\<in> S \\<Longrightarrow> a \\<notin> convex hull (S - {a})\"\n  shows \"(x extreme_point_of (convex hull S) \\<longleftrightarrow> x \\<in> S)\"\nproof -\n  have \"convex hull T \\<noteq> convex hull S\" if \"T \\<subset> S\" for T\n  proof -\n    obtain a where  \"T \\<subseteq> S\" \"a \\<in> S\" \"a \\<notin> T\" using \\<open>T \\<subset> S\\<close> by blast\n    then show ?thesis\n      by (metis (full_types) Diff_eq_empty_iff Diff_insert0 S hull_mono hull_subset insert_Diff_single subsetCE)\n  qed\n  then show ?thesis\n    by (rule extreme_point_of_convex_hull_eq [OF \\<open>compact S\\<close>])\nqed\n\nlemma extreme_point_of_convex_hull_affine_independent:\n  fixes S :: \"'a::euclidean_space set\"\n  shows\n   \"~ affine_dependent S\n         \\<Longrightarrow> (x extreme_point_of (convex hull S) \\<longleftrightarrow> x \\<in> S)\"\nby (metis aff_independent_finite affine_dependent_def affine_hull_convex_hull extreme_point_of_convex_hull_convex_independent finite_imp_compact hull_inc)\n\ntext\\<open>Elementary proofs exist, not requiring Euclidean spaces and all this development\\<close>\nlemma extreme_point_of_convex_hull_2:\n  fixes x :: \"'a::euclidean_space\"\n  shows \"x extreme_point_of (convex hull {a,b}) \\<longleftrightarrow> x = a \\<or> x = b\"\nproof -\n  have \"x extreme_point_of (convex hull {a,b}) \\<longleftrightarrow> x \\<in> {a,b}\"\n    by (intro extreme_point_of_convex_hull_affine_independent affine_independent_2)\n  then show ?thesis\n    by simp\nqed\n\nlemma extreme_point_of_segment:\n  fixes x :: \"'a::euclidean_space\"\n  shows\n   \"x extreme_point_of closed_segment a b \\<longleftrightarrow> x = a \\<or> x = b\"\nby (simp add: extreme_point_of_convex_hull_2 segment_convex_hull)\n\nlemma face_of_convex_hull_subset:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"compact S\" and T: \"T face_of (convex hull S)\"\n  obtains s' where \"s' \\<subseteq> S\" \"T = convex hull s'\"\napply (rule_tac s' = \"{x. x extreme_point_of T}\" in that)\nusing T extreme_point_of_convex_hull extreme_point_of_face apply blast\nby (metis (no_types) Krein_Milman_Minkowski assms compact_convex_hull convex_convex_hull face_of_imp_compact face_of_imp_convex)\n\n\nproposition face_of_convex_hull_affine_independent:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"~ affine_dependent S\"\n    shows \"(T face_of (convex hull S) \\<longleftrightarrow> (\\<exists>c. c \\<subseteq> S \\<and> T = convex hull c))\"\n          (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (meson \\<open>T face_of convex hull S\\<close> aff_independent_finite assms face_of_convex_hull_subset finite_imp_compact)\nnext\n  assume ?rhs\n  then obtain c where \"c \\<subseteq> S\" and T: \"T = convex hull c\"\n    by blast\n  have \"affine hull c \\<inter> affine hull (S - c) = {}\"\n    apply (rule disjoint_affine_hull [OF assms \\<open>c \\<subseteq> S\\<close>], auto)\n    done\n  then have \"affine hull c \\<inter> convex hull (S - c) = {}\"\n    using convex_hull_subset_affine_hull by fastforce\n  then show ?lhs\n    by (metis face_of_convex_hulls \\<open>c \\<subseteq> S\\<close> aff_independent_finite assms T)\nqed\n\nlemma facet_of_convex_hull_affine_independent:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"~ affine_dependent S\"\n    shows \"T facet_of (convex hull S) \\<longleftrightarrow>\n           T \\<noteq> {} \\<and> (\\<exists>u. u \\<in> S \\<and> T = convex hull (S - {u}))\"\n          (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then have \"T face_of (convex hull S)\" \"T \\<noteq> {}\"\n        and afft: \"aff_dim T = aff_dim (convex hull S) - 1\"\n    by (auto simp: facet_of_def)\n  then obtain c where \"c \\<subseteq> S\" and c: \"T = convex hull c\"\n    by (auto simp: face_of_convex_hull_affine_independent [OF assms])\n  then have affs: \"aff_dim S = aff_dim c + 1\"\n    by (metis aff_dim_convex_hull afft eq_diff_eq)\n  have \"~ affine_dependent c\"\n    using \\<open>c \\<subseteq> S\\<close> affine_dependent_subset assms by blast\n  with affs have \"card (S - c) = 1\"\n    apply (simp add: aff_dim_affine_independent [symmetric] aff_dim_convex_hull)\n    by (metis aff_dim_affine_independent aff_independent_finite One_nat_def \\<open>c \\<subseteq> S\\<close> add.commute\n                add_diff_cancel_right' assms card_Diff_subset card_mono of_nat_1 of_nat_diff of_nat_eq_iff)\n  then obtain u where u: \"u \\<in> S - c\"\n    by (metis DiffI \\<open>c \\<subseteq> S\\<close> aff_independent_finite assms cancel_comm_monoid_add_class.diff_cancel\n                card_Diff_subset subsetI subset_antisym zero_neq_one)\n  then have u: \"S = insert u c\"\n    by (metis Diff_subset \\<open>c \\<subseteq> S\\<close> \\<open>card (S - c) = 1\\<close> card_1_singletonE double_diff insert_Diff insert_subset singletonD)\n  have \"T = convex hull (c - {u})\"\n    by (metis Diff_empty Diff_insert0 \\<open>T facet_of convex hull S\\<close> c facet_of_irrefl insert_absorb u)\n  with \\<open>T \\<noteq> {}\\<close> show ?rhs\n    using c u by auto\nnext\n  assume ?rhs\n  then obtain u where \"T \\<noteq> {}\" \"u \\<in> S\" and u: \"T = convex hull (S - {u})\"\n    by (force simp: facet_of_def)\n  then have \"\\<not> S \\<subseteq> {u}\"\n    using \\<open>T \\<noteq> {}\\<close> u by auto\n  have [simp]: \"aff_dim (convex hull (S - {u})) = aff_dim (convex hull S) - 1\"\n    using assms \\<open>u \\<in> S\\<close>\n    apply (simp add: aff_dim_convex_hull affine_dependent_def)\n    apply (drule bspec, assumption)\n    by (metis add_diff_cancel_right' aff_dim_insert insert_Diff [of u S])\n  show ?lhs\n    apply (subst u)\n    apply (simp add: \\<open>\\<not> S \\<subseteq> {u}\\<close> facet_of_def face_of_convex_hull_affine_independent [OF assms], blast)\n    done\nqed\n\nlemma facet_of_convex_hull_affine_independent_alt:\n  fixes S :: \"'a::euclidean_space set\"\n  shows\n   \"~affine_dependent S\n        \\<Longrightarrow> (T facet_of (convex hull S) \\<longleftrightarrow>\n             2 \\<le> card S \\<and> (\\<exists>u. u \\<in> S \\<and> T = convex hull (S - {u})))\"\napply (simp add: facet_of_convex_hull_affine_independent)\napply (auto simp: Set.subset_singleton_iff)\napply (metis Diff_cancel Int_empty_right Int_insert_right_if1  aff_independent_finite card_eq_0_iff card_insert_if card_mono card_subset_eq convex_hull_eq_empty eq_iff equals0D finite_insert finite_subset inf.absorb_iff2 insert_absorb insert_not_empty  not_less_eq_eq numeral_2_eq_2)\ndone\n\nlemma segment_face_of:\n  assumes \"(closed_segment a b) face_of S\"\n  shows \"a extreme_point_of S\" \"b extreme_point_of S\"\nproof -\n  have as: \"{a} face_of S\"\n    by (metis (no_types) assms convex_hull_singleton empty_iff extreme_point_of_convex_hull_insert face_of_face face_of_singleton finite.emptyI finite.insertI insert_absorb insert_iff segment_convex_hull)\n  moreover have \"{b} face_of S\"\n  proof -\n    have \"b \\<in> convex hull {a} \\<or> b extreme_point_of convex hull {b, a}\"\n      by (meson extreme_point_of_convex_hull_insert finite.emptyI finite.insertI)\n    moreover have \"closed_segment a b = convex hull {b, a}\"\n      using closed_segment_commute segment_convex_hull by blast\n    ultimately show ?thesis\n      by (metis as assms face_of_face convex_hull_singleton empty_iff face_of_singleton insertE)\n    qed\n  ultimately show \"a extreme_point_of S\" \"b extreme_point_of S\"\n    using face_of_singleton by blast+\nqed\n\n\nlemma Krein_Milman_frontier:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"convex S\" \"compact S\"\n    shows \"S = convex hull (frontier S)\"\n          (is \"?lhs = ?rhs\")\nproof\n  have \"?lhs \\<subseteq> convex hull {x. x extreme_point_of S}\"\n    using Krein_Milman_Minkowski assms by blast\n  also have \"... \\<subseteq> ?rhs\"\n    apply (rule hull_mono)\n    apply (auto simp: frontier_def extreme_point_not_in_interior)\n    using closure_subset apply (force simp: extreme_point_of_def)\n    done\n  finally show \"?lhs \\<subseteq> ?rhs\" .\nnext\n  have \"?rhs \\<subseteq> convex hull S\"\n    by (metis Diff_subset \\<open>compact S\\<close> closure_closed compact_eq_bounded_closed frontier_def hull_mono)\n  also have \"... \\<subseteq> ?lhs\"\n    by (simp add: \\<open>convex S\\<close> hull_same)\n  finally show \"?rhs \\<subseteq> ?lhs\" .\nqed\n\nsubsection\\<open>Polytopes\\<close>\n\ndefinition polytope where\n \"polytope S \\<equiv> \\<exists>v. finite v \\<and> S = convex hull v\"\n\nlemma polytope_translation_eq: \"polytope (image (\\<lambda>x. a + x) S) \\<longleftrightarrow> polytope S\"\napply (simp add: polytope_def, safe)\napply (metis convex_hull_translation finite_imageI translation_galois)\nby (metis convex_hull_translation finite_imageI)\n\nlemma polytope_linear_image: \"\\<lbrakk>linear f; polytope p\\<rbrakk> \\<Longrightarrow> polytope(image f p)\"\n  unfolding polytope_def using convex_hull_linear_image by blast\n\nlemma polytope_empty: \"polytope {}\"\n  using convex_hull_empty polytope_def by blast\n\nlemma polytope_convex_hull: \"finite S \\<Longrightarrow> polytope(convex hull S)\"\n  using polytope_def by auto\n\nlemma polytope_Times: \"\\<lbrakk>polytope S; polytope T\\<rbrakk> \\<Longrightarrow> polytope(S \\<times> T)\"\n  unfolding polytope_def\n  by (metis finite_cartesian_product convex_hull_Times)\n\nlemma face_of_polytope_polytope:\n  fixes S :: \"'a::euclidean_space set\"\n  shows \"\\<lbrakk>polytope S; F face_of S\\<rbrakk> \\<Longrightarrow> polytope F\"\nunfolding polytope_def\nby (meson face_of_convex_hull_subset finite_imp_compact finite_subset)\n\nlemma finite_polytope_faces:\n  fixes S :: \"'a::euclidean_space set\"\n  assumes \"polytope S\"\n  shows \"finite {F. F face_of S}\"\nproof -\n  obtain v where \"finite v\" \"S = convex hull v\"\n    using assms polytope_def by auto\n  have \"finite (op hull convex ` {T. T \\<subseteq> v})\"\n    by (simp add: \\<open>finite v\\<close>)\n  moreover have \"{F. F face_of S} \\<subseteq> (op hull convex ` {T. T \\<subseteq> v})\"\n    by (metis (no_types, lifting) \\<open>finite v\\<close> \\<open>S = convex hull v\\<close> face_of_convex_hull_subset finite_imp_compact image_eqI mem_Collect_eq subsetI)\n  ultimately show ?thesis\n    by (blast intro: finite_subset)\nqed\n\nlemma finite_polytope_facets:\n  assumes \"polytope S\"\n  shows \"finite {T. T facet_of S}\"\nby (simp add: assms facet_of_def finite_polytope_faces)\n\nlemma polytope_scaling:\n  assumes \"polytope S\"  shows \"polytope (image (\\<lambda>x. c *\\<^sub>R x) S)\"\nby (simp add: assms polytope_linear_image)\n\nlemma polytope_imp_compact:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"polytope S \\<Longrightarrow> compact S\"\nby (metis finite_imp_compact_convex_hull polytope_def)\n\nlemma polytope_imp_convex: \"polytope S \\<Longrightarrow> convex S\"\n  by (metis convex_convex_hull polytope_def)\n\nlemma polytope_imp_closed:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"polytope S \\<Longrightarrow> closed S\"\nby (simp add: compact_imp_closed polytope_imp_compact)\n\nlemma polytope_imp_bounded:\n  fixes S :: \"'a::real_normed_vector set\"\n  shows \"polytope S \\<Longrightarrow> bounded S\"\nby (simp add: compact_imp_bounded polytope_imp_compact)\n\nlemma polytope_interval: \"polytope(cbox a b)\"\n  unfolding polytope_def by (meson closed_interval_as_convex_hull)\n\nlemma polytope_sing: \"polytope {a}\"\n  using polytope_def by force\n\n\nsubsection\\<open>Polyhedra\\<close>\n\ndefinition polyhedron where\n \"polyhedron S \\<equiv>\n        \\<exists>F. finite F \\<and>\n            S = \\<Inter> F \\<and>\n            (\\<forall>h \\<in> F. \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b})\"\n\nlemma polyhedron_Int [intro,simp]:\n   \"\\<lbrakk>polyhedron S; polyhedron T\\<rbrakk> \\<Longrightarrow> polyhedron (S \\<inter> T)\"\n  apply (simp add: polyhedron_def, clarify)\n  apply (rename_tac F G)\n  apply (rule_tac x=\"F \\<union> G\" in exI, auto)\n  done\n\nlemma polyhedron_UNIV [iff]: \"polyhedron UNIV\"\n  unfolding polyhedron_def\n  by (rule_tac x=\"{}\" in exI) auto\n\nlemma polyhedron_Inter [intro,simp]:\n   \"\\<lbrakk>finite F; \\<And>S. S \\<in> F \\<Longrightarrow> polyhedron S\\<rbrakk> \\<Longrightarrow> polyhedron(\\<Inter>F)\"\nby (induction F rule: finite_induct) auto\n\n\nlemma polyhedron_empty [iff]: \"polyhedron ({} :: 'a :: euclidean_space set)\"\nproof -\n  have \"\\<exists>a. a \\<noteq> 0 \\<and>\n             (\\<exists>b. {x. (SOME i. i \\<in> Basis) \\<bullet> x \\<le> - 1} = {x. a \\<bullet> x \\<le> b})\"\n    by (rule_tac x=\"(SOME i. i \\<in> Basis)\" in exI) (force simp: SOME_Basis nonzero_Basis)\n  moreover have \"\\<exists>a b. a \\<noteq> 0 \\<and>\n                       {x. - (SOME i. i \\<in> Basis) \\<bullet> x \\<le> - 1} = {x. a \\<bullet> x \\<le> b}\"\n      apply (rule_tac x=\"-(SOME i. i \\<in> Basis)\" in exI)\n      apply (rule_tac x=\"-1\" in exI)\n      apply (simp add: SOME_Basis nonzero_Basis)\n      done\n  ultimately show ?thesis\n    unfolding polyhedron_def\n    apply (rule_tac x=\"{{x. (SOME i. i \\<in> Basis) \\<bullet> x \\<le> -1},\n                        {x. -(SOME i. i \\<in> Basis) \\<bullet> x \\<le> -1}}\" in exI)\n    apply force\n    done\nqed\n\nlemma polyhedron_halfspace_le:\n  fixes a :: \"'a :: euclidean_space\"\n  shows \"polyhedron {x. a \\<bullet> x \\<le> b}\"\nproof (cases \"a = 0\")\n  case True then show ?thesis by auto\nnext\n  case False\n  then show ?thesis\n    unfolding polyhedron_def\n    by (rule_tac x=\"{{x. a \\<bullet> x \\<le> b}}\" in exI) auto\nqed\n\nlemma polyhedron_halfspace_ge:\n  fixes a :: \"'a :: euclidean_space\"\n  shows \"polyhedron {x. a \\<bullet> x \\<ge> b}\"\nusing polyhedron_halfspace_le [of \"-a\" \"-b\"] by simp\n\nlemma polyhedron_hyperplane:\n  fixes a :: \"'a :: euclidean_space\"\n  shows \"polyhedron {x. a \\<bullet> x = b}\"\nproof -\n  have \"{x. a \\<bullet> x = b} = {x. a \\<bullet> x \\<le> b} \\<inter> {x. a \\<bullet> x \\<ge> b}\"\n    by force\n  then show ?thesis\n    by (simp add: polyhedron_halfspace_ge polyhedron_halfspace_le)\nqed\n\nlemma affine_imp_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"affine S \\<Longrightarrow> polyhedron S\"\nby (metis affine_hull_eq polyhedron_Inter polyhedron_hyperplane affine_hull_finite_intersection_hyperplanes [of S])\n\nlemma polyhedron_imp_closed:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<Longrightarrow> closed S\"\napply (simp add: polyhedron_def)\nusing closed_halfspace_le by fastforce\n\nlemma polyhedron_imp_convex:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<Longrightarrow> convex S\"\napply (simp add: polyhedron_def)\nusing convex_Inter convex_halfspace_le by fastforce\n\nlemma polyhedron_affine_hull:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron(affine hull S)\"\nby (simp add: affine_imp_polyhedron)\n\n\nsubsection\\<open>Canonical polyhedron representation making facial structure explicit\\<close>\n\nlemma polyhedron_Int_affine:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<longleftrightarrow>\n           (\\<exists>F. finite F \\<and> S = (affine hull S) \\<inter> \\<Inter>F \\<and>\n                (\\<forall>h \\<in> F. \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}))\"\n        (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs then show ?rhs\n    apply (simp add: polyhedron_def)\n    apply (erule ex_forward)\n    using hull_subset apply force\n    done\nnext\n  assume ?rhs then show ?lhs\n    apply clarify\n    apply (erule ssubst)\n    apply (force intro: polyhedron_affine_hull polyhedron_halfspace_le)\n    done\nqed\n\nproposition rel_interior_polyhedron_explicit:\n  assumes \"finite F\"\n      and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n      and faceq: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n      and psub: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> affine hull S \\<inter> \\<Inter>F'\"\n    shows \"rel_interior S = {x \\<in> S. \\<forall>h \\<in> F. a h \\<bullet> x < b h}\"\nproof -\n  have rels: \"\\<And>x. x \\<in> rel_interior S \\<Longrightarrow> x \\<in> S\"\n    by (meson IntE mem_rel_interior)\n  moreover have \"a i \\<bullet> x < b i\" if x: \"x \\<in> rel_interior S\" and \"i \\<in> F\" for x i\n  proof -\n    have fif: \"F - {i} \\<subset> F\"\n      using \\<open>i \\<in> F\\<close> Diff_insert_absorb Diff_subset set_insert psubsetI by blast\n    then have \"S \\<subset> affine hull S \\<inter> \\<Inter>(F - {i})\"\n      by (rule psub)\n    then obtain z where ssub: \"S \\<subseteq> \\<Inter>(F - {i})\" and zint: \"z \\<in> \\<Inter>(F - {i})\"\n                    and \"z \\<notin> S\" and zaff: \"z \\<in> affine hull S\"\n      by auto\n    have \"z \\<noteq> x\"\n      using \\<open>z \\<notin> S\\<close> rels x by blast\n    have \"z \\<notin> affine hull S \\<inter> \\<Inter>F\"\n      using \\<open>z \\<notin> S\\<close> seq by auto\n    then have aiz: \"a i \\<bullet> z > b i\"\n      using faceq zint zaff by fastforce\n    obtain e where \"e > 0\" \"x \\<in> S\" and e: \"ball x e \\<inter> affine hull S \\<subseteq> S\"\n      using x by (auto simp: mem_rel_interior_ball)\n    then have ins: \"\\<And>y. \\<lbrakk>norm (x - y) < e; y \\<in> affine hull S\\<rbrakk> \\<Longrightarrow> y \\<in> S\"\n      by (metis IntI subsetD dist_norm mem_ball)\n    define \\<xi> where \"\\<xi> = min (1/2) (e / 2 / norm(z - x))\"\n    have \"norm (\\<xi> *\\<^sub>R x - \\<xi> *\\<^sub>R z) = norm (\\<xi> *\\<^sub>R (x - z))\"\n      by (simp add: \\<xi>_def algebra_simps norm_mult)\n    also have \"... = \\<xi> * norm (x - z)\"\n      using \\<open>e > 0\\<close> by (simp add: \\<xi>_def)\n    also have \"... < e\"\n      using \\<open>z \\<noteq> x\\<close> \\<open>e > 0\\<close> by (simp add: \\<xi>_def min_def divide_simps norm_minus_commute)\n    finally have lte: \"norm (\\<xi> *\\<^sub>R x - \\<xi> *\\<^sub>R z) < e\" .\n    have \\<xi>_aff: \"\\<xi> *\\<^sub>R z + (1 - \\<xi>) *\\<^sub>R x \\<in> affine hull S\"\n      by (metis \\<open>x \\<in> S\\<close> add.commute affine_affine_hull diff_add_cancel hull_inc mem_affine zaff)\n    have \"\\<xi> *\\<^sub>R z + (1 - \\<xi>) *\\<^sub>R x \\<in> S\"\n      apply (rule ins [OF _ \\<xi>_aff])\n      apply (simp add: algebra_simps lte)\n      done\n    then obtain l where l: \"0 < l\" \"l < 1\" and ls: \"(l *\\<^sub>R z + (1 - l) *\\<^sub>R x) \\<in> S\"\n      apply (rule_tac l = \\<xi> in that)\n      using \\<open>e > 0\\<close> \\<open>z \\<noteq> x\\<close>  apply (auto simp: \\<xi>_def)\n      done\n    then have i: \"l *\\<^sub>R z + (1 - l) *\\<^sub>R x \\<in> i\"\n      using seq \\<open>i \\<in> F\\<close> by auto\n    have \"b i * l + (a i \\<bullet> x) * (1 - l) < a i \\<bullet> (l *\\<^sub>R z + (1 - l) *\\<^sub>R x)\"\n      using l by (simp add: algebra_simps aiz)\n    also have \"\\<dots> \\<le> b i\" using i l\n      using faceq mem_Collect_eq \\<open>i \\<in> F\\<close> by blast\n    finally have \"(a i \\<bullet> x) * (1 - l) < b i * (1 - l)\"\n      by (simp add: algebra_simps)\n    with l show ?thesis\n      by simp\n  qed\n  moreover have \"x \\<in> rel_interior S\"\n           if \"x \\<in> S\" and less: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<bullet> x < b h\" for x\n  proof -\n    have 1: \"\\<And>h. h \\<in> F \\<Longrightarrow> x \\<in> interior h\"\n      by (metis interior_halfspace_le mem_Collect_eq less faceq)\n    have 2: \"\\<And>y. \\<lbrakk>\\<forall>h\\<in>F. y \\<in> interior h; y \\<in> affine hull S\\<rbrakk> \\<Longrightarrow> y \\<in> S\"\n      by (metis IntI Inter_iff contra_subsetD interior_subset seq)\n    show ?thesis\n      apply (simp add: rel_interior \\<open>x \\<in> S\\<close>)\n      apply (rule_tac x=\"\\<Inter>h\\<in>F. interior h\" in exI)\n      apply (auto simp: \\<open>finite F\\<close> open_INT 1 2)\n      done\n  qed\n  ultimately show ?thesis by blast\nqed\n\n\nlemma polyhedron_Int_affine_parallel:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<longleftrightarrow>\n         (\\<exists>F. finite F \\<and>\n              S = (affine hull S) \\<inter> (\\<Inter>F) \\<and>\n              (\\<forall>h \\<in> F. \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b} \\<and>\n                             (\\<forall>x \\<in> affine hull S. (x + a) \\<in> affine hull S)))\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain F where \"finite F\" and seq: \"S = (affine hull S) \\<inter> \\<Inter>F\"\n                  and faces: \"\\<And>h. h \\<in> F \\<Longrightarrow> \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}\"\n    by (fastforce simp add: polyhedron_Int_affine)\n  then obtain a b where ab: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n    by metis\n  show ?rhs\n  proof -\n    have \"\\<exists>a' b'. a' \\<noteq> 0 \\<and>\n                  affine hull S \\<inter> {x. a' \\<bullet> x \\<le> b'} = affine hull S \\<inter> h \\<and>\n                  (\\<forall>w \\<in> affine hull S. (w + a') \\<in> affine hull S)\"\n        if \"h \\<in> F\" \"~(affine hull S \\<subseteq> h)\" for h\n    proof -\n      have \"a h \\<noteq> 0\" and \"h = {x. a h \\<bullet> x \\<le> b h}\" \"h \\<inter> \\<Inter>F = \\<Inter>F\"\n        using \\<open>h \\<in> F\\<close> ab by auto\n      then have \"(affine hull S) \\<inter> {x. a h \\<bullet> x \\<le> b h} \\<noteq> {}\"\n        by (metis (no_types) affine_hull_eq_empty inf.absorb_iff2 inf_assoc inf_bot_right inf_commute seq that(2))\n      moreover have \"~ (affine hull S \\<subseteq> {x. a h \\<bullet> x \\<le> b h})\"\n        using \\<open>h = {x. a h \\<bullet> x \\<le> b h}\\<close> that(2) by blast\n      ultimately show ?thesis\n        using affine_parallel_slice [of \"affine hull S\"]\n        by (metis \\<open>h = {x. a h \\<bullet> x \\<le> b h}\\<close> affine_affine_hull)\n    qed\n    then obtain a b\n         where ab: \"\\<And>h. \\<lbrakk>h \\<in> F; ~ (affine hull S \\<subseteq> h)\\<rbrakk>\n             \\<Longrightarrow> a h \\<noteq> 0 \\<and>\n                  affine hull S \\<inter> {x. a h \\<bullet> x \\<le> b h} = affine hull S \\<inter> h \\<and>\n                  (\\<forall>w \\<in> affine hull S. (w + a h) \\<in> affine hull S)\"\n      by metis\n    have seq2: \"S = affine hull S \\<inter> (\\<Inter>h\\<in>{h \\<in> F. \\<not> affine hull S \\<subseteq> h}. {x. a h \\<bullet> x \\<le> b h})\"\n      by (subst seq) (auto simp: ab INT_extend_simps)\n    show ?thesis\n      apply (rule_tac x=\"(\\<lambda>h. {x. a h \\<bullet> x \\<le> b h}) ` {h. h \\<in> F \\<and> ~(affine hull S \\<subseteq> h)}\" in exI)\n      apply (intro conjI seq2)\n        using \\<open>finite F\\<close> apply force\n       using ab apply blast\n       done\n  qed\nnext\n  assume ?rhs then show ?lhs\n    apply (simp add: polyhedron_Int_affine)\n    by metis\nqed\n\n\nproposition polyhedron_Int_affine_parallel_minimal:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<longleftrightarrow>\n         (\\<exists>F. finite F \\<and>\n              S = (affine hull S) \\<inter> (\\<Inter>F) \\<and>\n              (\\<forall>h \\<in> F. \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b} \\<and>\n                             (\\<forall>x \\<in> affine hull S. (x + a) \\<in> affine hull S)) \\<and>\n              (\\<forall>F'. F' \\<subset> F \\<longrightarrow> S \\<subset> (affine hull S) \\<inter> (\\<Inter>F')))\"\n    (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then obtain f0\n           where f0: \"finite f0\"\n                 \"S = (affine hull S) \\<inter> (\\<Inter>f0)\"\n                   (is \"?P f0\")\n                 \"\\<forall>h \\<in> f0. \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b} \\<and>\n                             (\\<forall>x \\<in> affine hull S. (x + a) \\<in> affine hull S)\"\n                   (is \"?Q f0\")\n    by (force simp: polyhedron_Int_affine_parallel)\n  define n where \"n = (LEAST n. \\<exists>F. card F = n \\<and> finite F \\<and> ?P F \\<and> ?Q F)\"\n  have nf: \"\\<exists>F. card F = n \\<and> finite F \\<and> ?P F \\<and> ?Q F\"\n    apply (simp add: n_def)\n    apply (rule LeastI [where k = \"card f0\"])\n    using f0 apply auto\n    done\n  then obtain F where F: \"card F = n\" \"finite F\" and seq: \"?P F\" and aff: \"?Q F\"\n    by blast\n  then have \"~ (finite g \\<and> ?P g \\<and> ?Q g)\" if \"card g < n\" for g\n    using that by (auto simp: n_def dest!: not_less_Least)\n  then have *: \"~ (?P g \\<and> ?Q g)\" if \"g \\<subset> F\" for g\n    using that \\<open>finite F\\<close> psubset_card_mono \\<open>card F = n\\<close>\n    by (metis finite_Int inf.strict_order_iff)\n  have 1: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subseteq> affine hull S \\<inter> \\<Inter>F'\"\n    by (subst seq) blast\n  have 2: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<noteq> affine hull S \\<inter> \\<Inter>F'\"\n    apply (frule *)\n    by (metis aff subsetCE subset_iff_psubset_eq)\n  show ?rhs\n    by (metis \\<open>finite F\\<close> seq aff psubsetI 1 2)\nnext\n  assume ?rhs then show ?lhs\n    by (auto simp: polyhedron_Int_affine_parallel)\nqed\n\n\nlemma polyhedron_Int_affine_minimal:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<longleftrightarrow>\n         (\\<exists>F. finite F \\<and> S = (affine hull S) \\<inter> \\<Inter>F \\<and>\n              (\\<forall>h \\<in> F. \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}) \\<and>\n              (\\<forall>F'. F' \\<subset> F \\<longrightarrow> S \\<subset> (affine hull S) \\<inter> \\<Inter>F'))\"\napply (rule iffI)\n apply (force simp: polyhedron_Int_affine_parallel_minimal elim!: ex_forward)\napply (auto simp: polyhedron_Int_affine elim!: ex_forward)\ndone\n\nproposition facet_of_polyhedron_explicit:\n  assumes \"finite F\"\n      and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n      and faceq: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n      and psub: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> affine hull S \\<inter> \\<Inter>F'\"\n    shows \"c facet_of S \\<longleftrightarrow> (\\<exists>h. h \\<in> F \\<and> c = S \\<inter> {x. a h \\<bullet> x = b h})\"\nproof (cases \"S = {}\")\n  case True with psub show ?thesis by force\nnext\n  case False\n  have \"polyhedron S\"\n    apply (simp add: polyhedron_Int_affine)\n    apply (rule_tac x=F in exI)\n    using assms  apply force\n    done\n  then have \"convex S\"\n    by (rule polyhedron_imp_convex)\n  with False rel_interior_eq_empty have \"rel_interior S \\<noteq> {}\" by blast\n  then obtain x where \"x \\<in> rel_interior S\" by auto\n  then obtain T where \"open T\" \"x \\<in> T\" \"x \\<in> S\" \"T \\<inter> affine hull S \\<subseteq> S\"\n    by (force simp: mem_rel_interior)\n  then have xaff: \"x \\<in> affine hull S\" and xint: \"x \\<in> \\<Inter>F\"\n    using seq hull_inc by auto\n  have \"rel_interior S = {x \\<in> S. \\<forall>h\\<in>F. a h \\<bullet> x < b h}\"\n    by (rule rel_interior_polyhedron_explicit [OF \\<open>finite F\\<close> seq faceq psub])\n  with \\<open>x \\<in> rel_interior S\\<close>\n  have [simp]: \"\\<And>h. h\\<in>F \\<Longrightarrow> a h \\<bullet> x < b h\" by blast\n  have *: \"(S \\<inter> {x. a h \\<bullet> x = b h}) facet_of S\" if \"h \\<in> F\" for h\n  proof -\n    have \"S \\<subset> affine hull S \\<inter> \\<Inter>(F - {h})\"\n      using psub that by (metis Diff_disjoint Diff_subset insert_disjoint(2) psubsetI)\n    then obtain z where zaff: \"z \\<in> affine hull S\" and zint: \"z \\<in> \\<Inter>(F - {h})\" and \"z \\<notin> S\"\n      by force\n    then have \"z \\<noteq> x\" \"z \\<notin> h\" using seq \\<open>x \\<in> S\\<close> by auto\n    have \"x \\<in> h\" using that xint by auto\n    then have able: \"a h \\<bullet> x \\<le> b h\"\n      using faceq that by blast\n    also have \"... < a h \\<bullet> z\" using \\<open>z \\<notin> h\\<close> faceq [OF that] xint by auto\n    finally have xltz: \"a h \\<bullet> x < a h \\<bullet> z\" .\n    define l where \"l = (b h - a h \\<bullet> x) / (a h \\<bullet> z - a h \\<bullet> x)\"\n    define w where \"w = (1 - l) *\\<^sub>R x + l *\\<^sub>R z\"\n    have \"0 < l\" \"l < 1\"\n      using able xltz \\<open>b h < a h \\<bullet> z\\<close> \\<open>h \\<in> F\\<close>\n      by (auto simp: l_def divide_simps)\n    have awlt: \"a i \\<bullet> w < b i\" if \"i \\<in> F\" \"i \\<noteq> h\" for i\n    proof -\n      have \"(1 - l) * (a i \\<bullet> x) < (1 - l) * b i\"\n        by (simp add: \\<open>l < 1\\<close> \\<open>i \\<in> F\\<close>)\n      moreover have \"l * (a i \\<bullet> z) \\<le> l * b i\"\n        apply (rule mult_left_mono)\n        apply (metis Diff_insert_absorb Inter_iff Set.set_insert \\<open>h \\<in> F\\<close> faceq insertE mem_Collect_eq that zint)\n        using \\<open>0 < l\\<close>\n        apply simp\n        done\n      ultimately show ?thesis by (simp add: w_def algebra_simps)\n    qed\n    have weq: \"a h \\<bullet> w = b h\"\n      using xltz unfolding w_def l_def\n      by (simp add: algebra_simps) (simp add: field_simps)\n    have \"w \\<in> affine hull S\"\n      by (simp add: w_def mem_affine xaff zaff)\n    moreover have \"w \\<in> \\<Inter>F\"\n      using \\<open>a h \\<bullet> w = b h\\<close> awlt faceq less_eq_real_def by blast\n    ultimately have \"w \\<in> S\"\n      using seq by blast\n    with weq have \"S \\<inter> {x. a h \\<bullet> x = b h} \\<noteq> {}\" by blast\n    moreover have \"S \\<inter> {x. a h \\<bullet> x = b h} face_of S\"\n      apply (rule face_of_Int_supporting_hyperplane_le)\n      apply (rule \\<open>convex S\\<close>)\n      apply (subst (asm) seq)\n      using faceq that apply fastforce\n      done\n    moreover have \"affine hull (S \\<inter> {x. a h \\<bullet> x = b h}) =\n                   (affine hull S) \\<inter> {x. a h \\<bullet> x = b h}\"\n    proof\n      show \"affine hull (S \\<inter> {x. a h \\<bullet> x = b h}) \\<subseteq> affine hull S \\<inter> {x. a h \\<bullet> x = b h}\"\n        apply (intro Int_greatest hull_mono Int_lower1)\n        apply (metis affine_hull_eq affine_hyperplane hull_mono inf_le2)\n        done\n    next\n      show \"affine hull S \\<inter> {x. a h \\<bullet> x = b h} \\<subseteq> affine hull (S \\<inter> {x. a h \\<bullet> x = b h})\"\n      proof\n        fix y\n        assume yaff: \"y \\<in> affine hull S \\<inter> {y. a h \\<bullet> y = b h}\"\n        obtain T where \"0 < T\"\n                 and T: \"\\<And>j. \\<lbrakk>j \\<in> F; j \\<noteq> h\\<rbrakk> \\<Longrightarrow> T * (a j \\<bullet> y - a j \\<bullet> w) \\<le> b j - a j \\<bullet> w\"\n        proof (cases \"F - {h} = {}\")\n          case True then show ?thesis\n            by (rule_tac T=1 in that) auto\n        next\n          case False\n          then obtain h' where h': \"h' \\<in> F - {h}\" by auto\n          define inff where \"inff =\n            (INF j:F - {h}.\n              if 0 < a j \\<bullet> y - a j \\<bullet> w\n              then (b j - a j \\<bullet> w) / (a j \\<bullet> y - a j \\<bullet> w)\n              else 1)\"\n          have \"0 < inff\"\n            apply (simp add: inff_def)\n            apply (rule finite_imp_less_Inf)\n              using \\<open>finite F\\<close> apply blast\n             using h' apply blast\n            apply simp\n            using awlt apply (force simp: divide_simps)\n            done\n          moreover have \"inff * (a j \\<bullet> y - a j \\<bullet> w) \\<le> b j - a j \\<bullet> w\"\n                        if \"j \\<in> F\" \"j \\<noteq> h\" for j\n          proof (cases \"a j \\<bullet> w < a j \\<bullet> y\")\n            case True\n            then have \"inff \\<le> (b j - a j \\<bullet> w) / (a j \\<bullet> y - a j \\<bullet> w)\"\n              apply (simp add: inff_def)\n              apply (rule cInf_le_finite)\n              using \\<open>finite F\\<close> apply blast\n              apply (simp add: that split: if_split_asm)\n              done\n            then show ?thesis\n              using \\<open>0 < inff\\<close> awlt [OF that] mult_strict_left_mono\n              by (fastforce simp add: algebra_simps divide_simps split: if_split_asm)\n          next\n            case False\n            with \\<open>0 < inff\\<close> have \"inff * (a j \\<bullet> y - a j \\<bullet> w) \\<le> 0\"\n              by (simp add: mult_le_0_iff)\n            also have \"... < b j - a j \\<bullet> w\"\n              by (simp add: awlt that)\n            finally show ?thesis by simp\n          qed\n          ultimately show ?thesis\n            by (blast intro: that)\n        qed\n        define c where \"c = (1 - T) *\\<^sub>R w + T *\\<^sub>R y\"\n        have \"(1 - T) *\\<^sub>R w + T *\\<^sub>R y \\<in> j\" if \"j \\<in> F\" for j\n        proof (cases \"j = h\")\n          case True\n          have \"(1 - T) *\\<^sub>R w + T *\\<^sub>R y \\<in> {x. a h \\<bullet> x \\<le> b h}\"\n            using weq yaff by (auto simp: algebra_simps)\n          with True faceq [OF that] show ?thesis by metis\n        next\n          case False\n          with T that have \"(1 - T) *\\<^sub>R w + T *\\<^sub>R y \\<in> {x. a j \\<bullet> x \\<le> b j}\"\n            by (simp add: algebra_simps)\n          with faceq [OF that] show ?thesis by simp\n        qed\n        moreover have \"(1 - T) *\\<^sub>R w + T *\\<^sub>R y \\<in> affine hull S\"\n          apply (rule affine_affine_hull [simplified affine_alt, rule_format])\n          apply (simp add: \\<open>w \\<in> affine hull S\\<close>)\n          using yaff apply blast\n          done\n        ultimately have \"c \\<in> S\"\n          using seq by (force simp: c_def)\n        moreover have \"a h \\<bullet> c = b h\"\n          using yaff by (force simp: c_def algebra_simps weq)\n        ultimately have caff: \"c \\<in> affine hull (S \\<inter> {y. a h \\<bullet> y = b h})\"\n          by (simp add: hull_inc)\n        have waff: \"w \\<in> affine hull (S \\<inter> {y. a h \\<bullet> y = b h})\"\n          using \\<open>w \\<in> S\\<close> weq by (blast intro: hull_inc)\n        have yeq: \"y = (1 - inverse T) *\\<^sub>R w + c /\\<^sub>R T\"\n          using \\<open>0 < T\\<close> by (simp add: c_def algebra_simps)\n        show \"y \\<in> affine hull (S \\<inter> {y. a h \\<bullet> y = b h})\"\n          by (metis yeq affine_affine_hull [simplified affine_alt, rule_format, OF waff caff])\n      qed\n    qed\n    ultimately show ?thesis\n      apply (simp add: facet_of_def)\n      apply (subst aff_dim_affine_hull [symmetric])\n      using  \\<open>b h < a h \\<bullet> z\\<close> zaff\n      apply (force simp: aff_dim_affine_Int_hyperplane)\n      done\n  qed\n  show ?thesis\n  proof\n    show \"\\<exists>h. h \\<in> F \\<and> c = S \\<inter> {x. a h \\<bullet> x = b h} \\<Longrightarrow> c facet_of S\"\n      using * by blast\n  next\n    assume \"c facet_of S\"\n    then have \"c face_of S\" \"convex c\" \"c \\<noteq> {}\" and affc: \"aff_dim c = aff_dim S - 1\"\n      by (auto simp: facet_of_def face_of_imp_convex)\n    then obtain x where x: \"x \\<in> rel_interior c\"\n      by (force simp: rel_interior_eq_empty)\n    then have \"x \\<in> c\"\n      by (meson subsetD rel_interior_subset)\n    then have \"x \\<in> S\"\n      using \\<open>c facet_of S\\<close> facet_of_imp_subset by blast\n    have rels: \"rel_interior S = {x \\<in> S. \\<forall>h\\<in>F. a h \\<bullet> x < b h}\"\n      by (rule rel_interior_polyhedron_explicit [OF assms])\n    have \"c \\<noteq> S\"\n      using \\<open>c facet_of S\\<close> facet_of_irrefl by blast\n    then have \"x \\<notin> rel_interior S\"\n      by (metis IntI empty_iff \\<open>x \\<in> c\\<close> \\<open>c \\<noteq> S\\<close> \\<open>c face_of S\\<close> face_of_disjoint_rel_interior)\n    with rels \\<open>x \\<in> S\\<close> obtain i where \"i \\<in> F\" and i: \"a i \\<bullet> x \\<ge> b i\"\n      by force\n    have \"x \\<in> {u. a i \\<bullet> u \\<le> b i}\"\n      by (metis IntD2 InterE \\<open>i \\<in> F\\<close> \\<open>x \\<in> S\\<close> faceq seq)\n    then have \"a i \\<bullet> x \\<le> b i\" by simp\n    then have \"a i \\<bullet> x = b i\" using i by auto\n    have \"c \\<subseteq> S \\<inter> {x. a i \\<bullet> x = b i}\"\n      apply (rule subset_of_face_of [of _ S])\n        apply (simp add: \"*\" \\<open>i \\<in> F\\<close> facet_of_imp_face_of)\n       apply (simp add: \\<open>c face_of S\\<close> face_of_imp_subset)\n      using \\<open>a i \\<bullet> x = b i\\<close> \\<open>x \\<in> S\\<close> x by blast\n    then have cface: \"c face_of (S \\<inter> {x. a i \\<bullet> x = b i})\"\n      by (meson \\<open>c face_of S\\<close> face_of_subset inf_le1)\n    have con: \"convex (S \\<inter> {x. a i \\<bullet> x = b i})\"\n      by (simp add: \\<open>convex S\\<close> convex_Int convex_hyperplane)\n    show \"\\<exists>h. h \\<in> F \\<and> c = S \\<inter> {x. a h \\<bullet> x = b h}\"\n      apply (rule_tac x=i in exI)\n      apply (simp add: \\<open>i \\<in> F\\<close>)\n      by (metis (no_types) * \\<open>i \\<in> F\\<close> affc facet_of_def less_irrefl face_of_aff_dim_lt [OF con cface])\n  qed\nqed\n\n\nlemma face_of_polyhedron_subset_explicit:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"finite F\"\n      and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n      and faceq: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n      and psub: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> affine hull S \\<inter> \\<Inter>F'\"\n      and c: \"c face_of S\" and \"c \\<noteq> {}\" \"c \\<noteq> S\"\n   obtains h where \"h \\<in> F\" \"c \\<subseteq> S \\<inter> {x. a h \\<bullet> x = b h}\"\nproof -\n  have \"c \\<subseteq> S\" using \\<open>c face_of S\\<close>\n    by (simp add: face_of_imp_subset)\n  have \"polyhedron S\"\n    apply (simp add: polyhedron_Int_affine)\n    by (metis \\<open>finite F\\<close> faceq seq)\n  then have \"convex S\"\n    by (simp add: polyhedron_imp_convex)\n  then have *: \"(S \\<inter> {x. a h \\<bullet> x = b h}) face_of S\" if \"h \\<in> F\" for h\n    apply (rule face_of_Int_supporting_hyperplane_le)\n    using faceq seq that by fastforce\n  have \"rel_interior c \\<noteq> {}\"\n    using c \\<open>c \\<noteq> {}\\<close> face_of_imp_convex rel_interior_eq_empty by blast\n  then obtain x where \"x \\<in> rel_interior c\" by auto\n  have rels: \"rel_interior S = {x \\<in> S. \\<forall>h\\<in>F. a h \\<bullet> x < b h}\"\n    by (rule rel_interior_polyhedron_explicit [OF \\<open>finite F\\<close> seq faceq psub])\n  then have xnot: \"x \\<notin> rel_interior S\"\n    by (metis IntI \\<open>x \\<in> rel_interior c\\<close> c \\<open>c \\<noteq> S\\<close> contra_subsetD empty_iff face_of_disjoint_rel_interior rel_interior_subset)\n  then have \"x \\<in> S\"\n    using \\<open>c \\<subseteq> S\\<close> \\<open>x \\<in> rel_interior c\\<close> rel_interior_subset by auto\n  then have xint: \"x \\<in> \\<Inter>F\"\n    using seq by blast\n  have \"F \\<noteq> {}\" using assms\n    by (metis affine_Int affine_Inter affine_affine_hull ex_in_conv face_of_affine_trivial)\n  then obtain i where \"i \\<in> F\" \"~ (a i \\<bullet> x < b i)\"\n    using \\<open>x \\<in> S\\<close> rels xnot by auto\n  with xint have \"a i \\<bullet> x = b i\"\n    by (metis eq_iff mem_Collect_eq not_le Inter_iff faceq)\n  have face: \"S \\<inter> {x. a i \\<bullet> x = b i} face_of S\"\n    by (simp add: \"*\" \\<open>i \\<in> F\\<close>)\n  show ?thesis\n    apply (rule_tac h = i in that)\n     apply (rule \\<open>i \\<in> F\\<close>)\n    apply (rule subset_of_face_of [OF face \\<open>c \\<subseteq> S\\<close>])\n    using \\<open>a i \\<bullet> x = b i\\<close> \\<open>x \\<in> rel_interior c\\<close> \\<open>x \\<in> S\\<close> apply blast\n    done\nqed\n\ntext\\<open>Initial part of proof duplicates that above\\<close>\nproposition face_of_polyhedron_explicit:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"finite F\"\n      and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n      and faceq: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n      and psub: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> affine hull S \\<inter> \\<Inter>F'\"\n      and c: \"c face_of S\" and \"c \\<noteq> {}\" \"c \\<noteq> S\"\n    shows \"c = \\<Inter>{S \\<inter> {x. a h \\<bullet> x = b h} | h. h \\<in> F \\<and> c \\<subseteq> S \\<inter> {x. a h \\<bullet> x = b h}}\"\nproof -\n  let ?ab = \"\\<lambda>h. {x. a h \\<bullet> x = b h}\"\n  have \"c \\<subseteq> S\" using \\<open>c face_of S\\<close>\n    by (simp add: face_of_imp_subset)\n  have \"polyhedron S\"\n    apply (simp add: polyhedron_Int_affine)\n    by (metis \\<open>finite F\\<close> faceq seq)\n  then have \"convex S\"\n    by (simp add: polyhedron_imp_convex)\n  then have *: \"(S \\<inter> ?ab h) face_of S\" if \"h \\<in> F\" for h\n    apply (rule face_of_Int_supporting_hyperplane_le)\n    using faceq seq that by fastforce\n  have \"rel_interior c \\<noteq> {}\"\n    using c \\<open>c \\<noteq> {}\\<close> face_of_imp_convex rel_interior_eq_empty by blast\n  then obtain z where z: \"z \\<in> rel_interior c\" by auto\n  have rels: \"rel_interior S = {z \\<in> S. \\<forall>h\\<in>F. a h \\<bullet> z < b h}\"\n    by (rule rel_interior_polyhedron_explicit [OF \\<open>finite F\\<close> seq faceq psub])\n  then have xnot: \"z \\<notin> rel_interior S\"\n    by (metis IntI \\<open>z \\<in> rel_interior c\\<close> c \\<open>c \\<noteq> S\\<close> contra_subsetD empty_iff face_of_disjoint_rel_interior rel_interior_subset)\n  then have \"z \\<in> S\"\n    using \\<open>c \\<subseteq> S\\<close> \\<open>z \\<in> rel_interior c\\<close> rel_interior_subset by auto\n  with seq have xint: \"z \\<in> \\<Inter>F\" by blast\n  have \"open (\\<Inter>h\\<in>{h \\<in> F. a h \\<bullet> z < b h}. {w. a h \\<bullet> w < b h})\"\n    by (auto simp: \\<open>finite F\\<close> open_halfspace_lt open_INT)\n  then obtain e where \"0 < e\"\n                 \"ball z e \\<subseteq> (\\<Inter>h\\<in>{h \\<in> F. a h \\<bullet> z < b h}. {w. a h \\<bullet> w < b h})\"\n    by (auto intro: openE [of _ z])\n  then have e: \"\\<And>h. \\<lbrakk>h \\<in> F; a h \\<bullet> z < b h\\<rbrakk> \\<Longrightarrow> ball z e \\<subseteq> {w. a h \\<bullet> w < b h}\"\n    by blast\n  have \"c \\<subseteq> (S \\<inter> ?ab h) \\<longleftrightarrow> z \\<in> S \\<inter> ?ab h\" if \"h \\<in> F\" for h\n  proof\n    show \"z \\<in> S \\<inter> ?ab h \\<Longrightarrow> c \\<subseteq> S \\<inter> ?ab h\"\n      apply (rule subset_of_face_of [of _ S])\n      using that \\<open>c \\<subseteq> S\\<close> \\<open>z \\<in> rel_interior c\\<close>\n      using facet_of_polyhedron_explicit [OF \\<open>finite F\\<close> seq faceq psub]\n            unfolding facet_of_def\n      apply auto\n      done\n  next\n    show \"c \\<subseteq> S \\<inter> ?ab h \\<Longrightarrow> z \\<in> S \\<inter> ?ab h\"\n      using \\<open>z \\<in> rel_interior c\\<close> rel_interior_subset by force\n  qed\n  then have **: \"{S \\<inter> ?ab h | h. h \\<in> F \\<and> c \\<subseteq> S \\<and> c \\<subseteq> ?ab h} =\n                 {S \\<inter> ?ab h |h. h \\<in> F \\<and> z \\<in> S \\<inter> ?ab h}\"\n    by blast\n  have bsub: \"ball z e \\<inter> affine hull \\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h}\n             \\<subseteq> affine hull S \\<inter> \\<Inter>F \\<inter> \\<Inter>{?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h}\"\n            if \"i \\<in> F\" and i: \"a i \\<bullet> z = b i\" for i\n  proof -\n    have sub: \"ball z e \\<inter> \\<Inter>{?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h} \\<subseteq> j\"\n             if \"j \\<in> F\" for j\n    proof -\n      have \"a j \\<bullet> z \\<le> b j\" using faceq that xint by auto\n      then consider \"a j \\<bullet> z < b j\" | \"a j \\<bullet> z = b j\" by linarith\n      then have \"\\<exists>G. G \\<in> {?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h} \\<and> ball z e \\<inter> G \\<subseteq> j\"\n      proof cases\n        assume \"a j \\<bullet> z < b j\"\n        then have \"ball z e \\<inter> {x. a i \\<bullet> x = b i} \\<subseteq> j\"\n          using e [OF \\<open>j \\<in> F\\<close>] faceq that\n          by (fastforce simp: ball_def)\n        then show ?thesis\n          by (rule_tac x=\"{x. a i \\<bullet> x = b i}\" in exI) (force simp: \\<open>i \\<in> F\\<close> i)\n      next\n        assume eq: \"a j \\<bullet> z = b j\"\n        with faceq that show ?thesis\n          by (rule_tac x=\"{x. a j \\<bullet> x = b j}\" in exI) (fastforce simp add: \\<open>j \\<in> F\\<close>)\n      qed\n      then show ?thesis  by blast\n    qed\n    have 1: \"affine hull \\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h} \\<subseteq> affine hull S\"\n      apply (rule hull_mono)\n      using that \\<open>z \\<in> S\\<close> by auto\n    have 2: \"affine hull \\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h}\n          \\<subseteq> \\<Inter>{?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h}\"\n      by (rule hull_minimal) (auto intro: affine_hyperplane)\n    have 3: \"ball z e \\<inter> \\<Inter>{?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h} \\<subseteq> \\<Inter>F\"\n      by (iprover intro: sub Inter_greatest)\n    have *: \"\\<lbrakk>A \\<subseteq> (B :: 'a set); A \\<subseteq> C; E \\<inter> C \\<subseteq> D\\<rbrakk> \\<Longrightarrow> E \\<inter> A \\<subseteq> (B \\<inter> D) \\<inter> C\"\n             for A B C D E  by blast\n    show ?thesis by (intro * 1 2 3)\n  qed\n  have \"\\<exists>h. h \\<in> F \\<and> c \\<subseteq> ?ab h\"\n    apply (rule face_of_polyhedron_subset_explicit [OF \\<open>finite F\\<close> seq faceq psub])\n    using assms by auto\n  then have fac: \"\\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> c \\<subseteq> S \\<inter> ?ab h} face_of S\"\n    using * by (force simp: \\<open>c \\<subseteq> S\\<close> intro: face_of_Inter)\n  have red:\n     \"(\\<And>a. P a \\<Longrightarrow> T \\<subseteq> S \\<inter> \\<Inter>{F x |x. P x}) \\<Longrightarrow> T \\<subseteq> \\<Inter>{S \\<inter> F x |x. P x}\"\n     for P T F   by blast\n  have \"ball z e \\<inter> affine hull \\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h}\n        \\<subseteq> \\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> a h \\<bullet> z = b h}\"\n    apply (rule red)\n    apply (metis seq bsub)\n    done\n  with \\<open>0 < e\\<close> have zinrel: \"z \\<in> rel_interior\n                    (\\<Inter>{S \\<inter> ?ab h |h. h \\<in> F \\<and> z \\<in> S \\<and> a h \\<bullet> z = b h})\"\n    by (auto simp: mem_rel_interior_ball \\<open>z \\<in> S\\<close>)\n  show ?thesis\n    apply (rule face_of_eq [OF c fac])\n    using z zinrel apply (force simp: **)\n    done\nqed\n\n\nsubsection\\<open>More general corollaries from the explicit representation\\<close>\n\ncorollary facet_of_polyhedron:\n  assumes \"polyhedron S\" and \"c facet_of S\"\n  obtains a b where \"a \\<noteq> 0\" \"S \\<subseteq> {x. a \\<bullet> x \\<le> b}\" \"c = S \\<inter> {x. a \\<bullet> x = b}\"\nproof -\n  obtain F where \"finite F\" and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n             and faces: \"\\<And>h. h \\<in> F \\<Longrightarrow> \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}\"\n             and min: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> (affine hull S) \\<inter> \\<Inter>F'\"\n    using assms by (simp add: polyhedron_Int_affine_minimal) meson\n  then obtain a b where ab: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n    by metis\n  obtain i where \"i \\<in> F\" and c: \"c = S \\<inter> {x. a i \\<bullet> x = b i}\"\n    using facet_of_polyhedron_explicit [OF \\<open>finite F\\<close> seq ab min] assms\n    by force\n  moreover have ssub: \"S \\<subseteq> {x. a i \\<bullet> x \\<le> b i}\"\n     apply (subst seq)\n     using \\<open>i \\<in> F\\<close> ab by auto\n  ultimately show ?thesis\n    by (rule_tac a = \"a i\" and b = \"b i\" in that) (simp_all add: ab)\nqed\n\ncorollary face_of_polyhedron:\n  assumes \"polyhedron S\" and \"c face_of S\" and \"c \\<noteq> {}\" and \"c \\<noteq> S\"\n    shows \"c = \\<Inter>{F. F facet_of S \\<and> c \\<subseteq> F}\"\nproof -\n  obtain F where \"finite F\" and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n             and faces: \"\\<And>h. h \\<in> F \\<Longrightarrow> \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}\"\n             and min: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> (affine hull S) \\<inter> \\<Inter>F'\"\n    using assms by (simp add: polyhedron_Int_affine_minimal) meson\n  then obtain a b where ab: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n    by metis\n  show ?thesis\n    apply (subst face_of_polyhedron_explicit [OF \\<open>finite F\\<close> seq ab min])\n    apply (auto simp: assms facet_of_polyhedron_explicit [OF \\<open>finite F\\<close> seq ab min] cong: Collect_cong)\n    done\nqed\n\nlemma face_of_polyhedron_subset_facet:\n  assumes \"polyhedron S\" and \"c face_of S\" and \"c \\<noteq> {}\" and \"c \\<noteq> S\"\n  obtains F where \"F facet_of S\" \"c \\<subseteq> F\"\nusing face_of_polyhedron assms\nby (metis (no_types, lifting) Inf_greatest antisym_conv face_of_imp_subset mem_Collect_eq)\n\n\nlemma exposed_face_of_polyhedron:\n  assumes \"polyhedron S\"\n    shows \"F exposed_face_of S \\<longleftrightarrow> F face_of S\"\nproof\n  show \"F exposed_face_of S \\<Longrightarrow> F face_of S\"\n    by (simp add: exposed_face_of_def)\nnext\n  assume \"F face_of S\"\n  show \"F exposed_face_of S\"\n  proof (cases \"F = {} \\<or> F = S\")\n    case True then show ?thesis\n      using \\<open>F face_of S\\<close> exposed_face_of by blast\n  next\n    case False\n    then have \"{g. g facet_of S \\<and> F \\<subseteq> g} \\<noteq> {}\"\n      by (metis Collect_empty_eq_bot \\<open>F face_of S\\<close> assms empty_def face_of_polyhedron_subset_facet)\n    moreover have \"\\<And>T. \\<lbrakk>T facet_of S; F \\<subseteq> T\\<rbrakk> \\<Longrightarrow> T exposed_face_of S\"\n      by (metis assms exposed_face_of facet_of_imp_face_of facet_of_polyhedron)\n    ultimately have \"\\<Inter>{fa.\n       fa facet_of S \\<and> F \\<subseteq> fa} exposed_face_of S\"\n      by (metis (no_types, lifting) mem_Collect_eq exposed_face_of_Inter)\n    then show ?thesis\n      using False\n      apply (subst face_of_polyhedron [OF assms \\<open>F face_of S\\<close>], auto)\n      done\n  qed\nqed\n\nlemma face_of_polyhedron_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"polyhedron S\" \"c face_of S\"\n    shows \"polyhedron c\"\nby (metis assms face_of_imp_eq_affine_Int polyhedron_Int polyhedron_affine_hull polyhedron_imp_closed polyhedron_imp_convex)\n\nlemma finite_polyhedron_faces:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"polyhedron S\"\n    shows \"finite {F. F face_of S}\"\nproof -\n  obtain F where \"finite F\" and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n             and faces: \"\\<And>h. h \\<in> F \\<Longrightarrow> \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}\"\n             and min:   \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> (affine hull S) \\<inter> \\<Inter>F'\"\n    using assms by (simp add: polyhedron_Int_affine_minimal) meson\n  then obtain a b where ab: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n    by metis\n  have \"finite {\\<Inter>{S \\<inter> {x. a h \\<bullet> x = b h} |h. h \\<in> F'}| F'. F' \\<in> Pow F}\"\n    by (simp add: \\<open>finite F\\<close>)\n  moreover have \"{F. F face_of S} - {{}, S} \\<subseteq> {\\<Inter>{S \\<inter> {x. a h \\<bullet> x = b h} |h. h \\<in> F'}| F'. F' \\<in> Pow F}\"\n    apply clarify\n    apply (rename_tac c)\n    apply (drule face_of_polyhedron_explicit [OF \\<open>finite F\\<close> seq ab min, simplified], simp_all)\n    apply (erule ssubst)\n    apply (rule_tac x=\"{h \\<in> F. c \\<subseteq> S \\<inter> {x. a h \\<bullet> x = b h}}\" in exI, auto)\n    done\n  ultimately show ?thesis\n    by (meson finite.emptyI finite.insertI finite_Diff2 finite_subset)\nqed\n\nlemma finite_polyhedron_exposed_faces:\n   \"polyhedron S \\<Longrightarrow> finite {F. F exposed_face_of S}\"\nusing exposed_face_of_polyhedron finite_polyhedron_faces by fastforce\n\nlemma finite_polyhedron_extreme_points:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<Longrightarrow> finite {v. v extreme_point_of S}\"\napply (simp add: face_of_singleton [symmetric])\napply (rule finite_subset [OF _ finite_vimageI [OF finite_polyhedron_faces]], auto)\ndone\n\nlemma finite_polyhedron_facets:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<Longrightarrow> finite {F. F facet_of S}\"\nunfolding facet_of_def\nby (blast intro: finite_subset [OF _ finite_polyhedron_faces])\n\n\nproposition rel_interior_of_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"polyhedron S\"\n    shows \"rel_interior S = S - \\<Union>{F. F facet_of S}\"\nproof -\n  obtain F where \"finite F\" and seq: \"S = affine hull S \\<inter> \\<Inter>F\"\n             and faces: \"\\<And>h. h \\<in> F \\<Longrightarrow> \\<exists>a b. a \\<noteq> 0 \\<and> h = {x. a \\<bullet> x \\<le> b}\"\n             and min: \"\\<And>F'. F' \\<subset> F \\<Longrightarrow> S \\<subset> (affine hull S) \\<inter> \\<Inter>F'\"\n    using assms by (simp add: polyhedron_Int_affine_minimal) meson\n  then obtain a b where ab: \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> h = {x. a h \\<bullet> x \\<le> b h}\"\n    by metis\n  have facet: \"(c facet_of S) \\<longleftrightarrow> (\\<exists>h. h \\<in> F \\<and> c = S \\<inter> {x. a h \\<bullet> x = b h})\" for c\n    by (rule facet_of_polyhedron_explicit [OF \\<open>finite F\\<close> seq ab min])\n  have rel: \"rel_interior S = {x \\<in> S. \\<forall>h\\<in>F. a h \\<bullet> x < b h}\"\n    by (rule rel_interior_polyhedron_explicit [OF \\<open>finite F\\<close> seq ab min])\n  have \"a h \\<bullet> x < b h\" if \"x \\<in> S\" \"h \\<in> F\" and xnot: \"x \\<notin> \\<Union>{F. F facet_of S}\" for x h\n  proof -\n    have \"x \\<in> \\<Inter>F\" using seq that by force\n    with \\<open>h \\<in> F\\<close> ab have \"a h \\<bullet> x \\<le> b h\" by auto\n    then consider \"a h \\<bullet> x < b h\" | \"a h \\<bullet> x = b h\" by linarith\n    then show ?thesis\n    proof cases\n      case 1 then show ?thesis .\n    next\n      case 2\n      have \"Collect (op \\<in> x) \\<notin> Collect (op \\<in> (\\<Union>{A. A facet_of S}))\"\n        using xnot by fastforce\n      then have \"F \\<notin> Collect (op \\<in> h)\"\n        using 2 \\<open>x \\<in> S\\<close> facet by blast\n      with \\<open>h \\<in> F\\<close> have \"\\<Inter>F \\<subseteq> S \\<inter> {x. a h \\<bullet> x = b h}\" by blast\n      with 2 that \\<open>x \\<in> \\<Inter>F\\<close> show ?thesis\n        apply simp\n        apply (drule_tac x=\"\\<Inter>F\" in spec)\n        apply (simp add: facet)\n        apply (drule_tac x=h in spec)\n        using seq by auto\n      qed\n  qed\n  moreover have \"\\<exists>h\\<in>F. a h \\<bullet> x \\<ge> b h\" if \"x \\<in> \\<Union>{F. F facet_of S}\" for x\n    using that by (force simp: facet)\n  ultimately show ?thesis\n    by (force simp: rel)\nqed\n\nlemma rel_boundary_of_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"polyhedron S\"\n    shows \"S - rel_interior S = \\<Union> {F. F facet_of S}\"\nusing facet_of_imp_subset by (fastforce simp add: rel_interior_of_polyhedron assms)\n\nlemma rel_frontier_of_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"polyhedron S\"\n    shows \"rel_frontier S = \\<Union> {F. F facet_of S}\"\nby (simp add: assms rel_frontier_def polyhedron_imp_closed rel_boundary_of_polyhedron)\n\nlemma rel_frontier_of_polyhedron_alt:\n  fixes S :: \"'a :: euclidean_space set\"\n  assumes \"polyhedron S\"\n    shows \"rel_frontier S = \\<Union> {F. F face_of S \\<and> (F \\<noteq> S)}\"\napply (rule subset_antisym)\n  apply (force simp: rel_frontier_of_polyhedron facet_of_def assms)\nusing face_of_subset_rel_frontier by fastforce\n\n\ntext\\<open>A characterization of polyhedra as having finitely many faces\\<close>\n\nproposition polyhedron_eq_finite_exposed_faces:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<longleftrightarrow> closed S \\<and> convex S \\<and> finite {F. F exposed_face_of S}\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (auto simp: polyhedron_imp_closed polyhedron_imp_convex finite_polyhedron_exposed_faces)\nnext\n  assume ?rhs\n  then have \"closed S\" \"convex S\" and fin: \"finite {F. F exposed_face_of S}\" by auto\n  show ?lhs\n  proof (cases \"S = {}\")\n    case True then show ?thesis by auto\n  next\n    case False\n    define F where \"F = {h. h exposed_face_of S \\<and> h \\<noteq> {} \\<and> h \\<noteq> S}\"\n    have \"finite F\" by (simp add: fin F_def)\n    have hface: \"h face_of S\"\n      and \"\\<exists>a b. a \\<noteq> 0 \\<and> S \\<subseteq> {x. a \\<bullet> x \\<le> b} \\<and> h = S \\<inter> {x. a \\<bullet> x = b}\"\n      if \"h \\<in> F\" for h\n      using exposed_face_of F_def that by simp_all auto\n    then obtain a b where ab:\n      \"\\<And>h. h \\<in> F \\<Longrightarrow> a h \\<noteq> 0 \\<and> S \\<subseteq> {x. a h \\<bullet> x \\<le> b h} \\<and> h = S \\<inter> {x. a h \\<bullet> x = b h}\"\n      by metis\n    have *: \"False\"\n      if paff: \"p \\<in> affine hull S\" and \"p \\<notin> S\"\n      and pint: \"p \\<in> \\<Inter>{{x. a h \\<bullet> x \\<le> b h} |h. h \\<in> F}\" for p\n    proof -\n      have \"rel_interior S \\<noteq> {}\"\n        by (simp add: \\<open>S \\<noteq> {}\\<close> \\<open>convex S\\<close> rel_interior_eq_empty)\n      then obtain c where c: \"c \\<in> rel_interior S\" by auto\n      with rel_interior_subset have \"c \\<in> S\"  by blast\n      have ccp: \"closed_segment c p \\<subseteq> affine hull S\"\n        by (meson affine_affine_hull affine_imp_convex c closed_segment_subset hull_subset paff rel_interior_subset subsetCE)\n      obtain x where xcl: \"x \\<in> closed_segment c p\" and \"x \\<in> S\" and xnot: \"x \\<notin> rel_interior S\"\n        using connected_openin [of \"closed_segment c p\"]\n        apply simp\n        apply (drule_tac x=\"closed_segment c p \\<inter> rel_interior S\" in spec)\n        apply (erule impE)\n         apply (force simp: openin_rel_interior openin_Int intro: openin_subtopology_Int_subset [OF _ ccp])\n        apply (drule_tac x=\"closed_segment c p \\<inter> (- S)\" in spec)\n        using rel_interior_subset \\<open>closed S\\<close> c \\<open>p \\<notin> S\\<close> apply blast\n        done\n      then obtain \\<mu> where \"0 \\<le> \\<mu>\" \"\\<mu> \\<le> 1\" and xeq: \"x = (1 - \\<mu>) *\\<^sub>R c + \\<mu> *\\<^sub>R p\"\n        by (auto simp: in_segment)\n      show False\n      proof (cases \"\\<mu>=0 \\<or> \\<mu>=1\")\n        case True with xeq c xnot \\<open>x \\<in> S\\<close> \\<open>p \\<notin> S\\<close>\n        show False by auto\n      next\n        case False\n        then have xos: \"x \\<in> open_segment c p\"\n          using \\<open>x \\<in> S\\<close> c open_segment_def that(2) xcl xnot by auto\n        have xclo: \"x \\<in> closure S\"\n          using \\<open>x \\<in> S\\<close> closure_subset by blast\n        obtain d where \"d \\<noteq> 0\"\n              and dle: \"\\<And>y. y \\<in> closure S \\<Longrightarrow> d \\<bullet> x \\<le> d \\<bullet> y\"\n              and dless: \"\\<And>y. y \\<in> rel_interior S \\<Longrightarrow> d \\<bullet> x < d \\<bullet> y\"\n          by (metis supporting_hyperplane_relative_frontier [OF \\<open>convex S\\<close> xclo xnot])\n        have sex: \"S \\<inter> {y. d \\<bullet> y = d \\<bullet> x} exposed_face_of S\"\n          by (simp add: \\<open>closed S\\<close> dle exposed_face_of_Int_supporting_hyperplane_ge [OF \\<open>convex S\\<close>])\n        have sne: \"S \\<inter> {y. d \\<bullet> y = d \\<bullet> x} \\<noteq> {}\"\n          using \\<open>x \\<in> S\\<close> by blast\n        have sns: \"S \\<inter> {y. d \\<bullet> y = d \\<bullet> x} \\<noteq> S\"\n          by (metis (mono_tags) Int_Collect c subsetD dless not_le order_refl rel_interior_subset)\n        obtain h where \"h \\<in> F\" \"x \\<in> h\"\n          apply (rule_tac h=\"S \\<inter> {y. d \\<bullet> y = d \\<bullet> x}\" in that)\n          apply (simp_all add: F_def sex sne sns \\<open>x \\<in> S\\<close>)\n          done\n        have abface: \"{y. a h \\<bullet> y = b h} face_of {y. a h \\<bullet> y \\<le> b h}\"\n          using hyperplane_face_of_halfspace_le by blast\n        then have \"c \\<in> h\"\n          using face_ofD [OF abface xos] \\<open>c \\<in> S\\<close> \\<open>h \\<in> F\\<close> ab pint \\<open>x \\<in> h\\<close> by blast\n        with c have \"h \\<inter> rel_interior S \\<noteq> {}\" by blast\n        then show False\n          using \\<open>h \\<in> F\\<close> F_def face_of_disjoint_rel_interior hface by auto\n      qed\n    qed\n    have \"S \\<subseteq> affine hull S \\<inter> \\<Inter>{{x. a h \\<bullet> x \\<le> b h} |h. h \\<in> F}\"\n      using ab by (auto simp: hull_subset)\n    moreover have \"affine hull S \\<inter> \\<Inter>{{x. a h \\<bullet> x \\<le> b h} |h. h \\<in> F} \\<subseteq> S\"\n      using * by blast\n    ultimately have \"S = affine hull S \\<inter> \\<Inter> {{x. a h \\<bullet> x \\<le> b h} |h. h \\<in> F}\" ..\n    then show ?thesis\n      apply (rule ssubst)\n      apply (force intro: polyhedron_affine_hull polyhedron_halfspace_le simp: \\<open>finite F\\<close>)\n      done\n  qed\nqed\n\ncorollary polyhedron_eq_finite_faces:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polyhedron S \\<longleftrightarrow> closed S \\<and> convex S \\<and> finite {F. F face_of S}\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (simp add: finite_polyhedron_faces polyhedron_imp_closed polyhedron_imp_convex)\nnext\n  assume ?rhs\n  then show ?lhs\n    by (force simp: polyhedron_eq_finite_exposed_faces exposed_face_of intro: finite_subset)\nqed\n\nlemma polyhedron_linear_image_eq:\n  fixes h :: \"'a :: euclidean_space \\<Rightarrow> 'b :: euclidean_space\"\n  assumes \"linear h\" \"bij h\"\n    shows \"polyhedron (h ` S) \\<longleftrightarrow> polyhedron S\"\nproof -\n  have *: \"{f. P f} = (image h) ` {f. P (h ` f)}\" for P\n    apply safe\n    apply (rule_tac x=\"inv h ` x\" in image_eqI)\n    apply (auto simp: \\<open>bij h\\<close> bij_is_surj image_f_inv_f)\n    done\n  have \"inj h\" using bij_is_inj assms by blast\n  then have injim: \"inj_on (op ` h) A\" for A\n    by (simp add: inj_on_def inj_image_eq_iff)\n  show ?thesis\n    using \\<open>linear h\\<close> \\<open>inj h\\<close>\n    apply (simp add: polyhedron_eq_finite_faces closed_injective_linear_image_eq)\n    apply (simp add: * face_of_linear_image [of h _ S, symmetric] finite_image_iff injim)\n    done\nqed\n\nlemma polyhedron_negations:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows   \"polyhedron S \\<Longrightarrow> polyhedron(image uminus S)\"\nby (auto simp: polyhedron_linear_image_eq linear_uminus bij_uminus)\n\nsubsection\\<open>Relation between polytopes and polyhedra\\<close>\n\nlemma polytope_eq_bounded_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polytope S \\<longleftrightarrow> polyhedron S \\<and> bounded S\"\n         (is \"?lhs = ?rhs\")\nproof\n  assume ?lhs\n  then show ?rhs\n    by (simp add: finite_polytope_faces polyhedron_eq_finite_faces\n                  polytope_imp_closed polytope_imp_convex polytope_imp_bounded)\nnext\n  assume ?rhs then show ?lhs\n    unfolding polytope_def\n    apply (rule_tac x=\"{v. v extreme_point_of S}\" in exI)\n    apply (simp add: finite_polyhedron_extreme_points Krein_Milman_Minkowski compact_eq_bounded_closed polyhedron_imp_closed polyhedron_imp_convex)\n    done\nqed\n\nlemma polytope_Int:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"\\<lbrakk>polytope S; polytope T\\<rbrakk> \\<Longrightarrow> polytope(S \\<inter> T)\"\nby (simp add: polytope_eq_bounded_polyhedron bounded_Int)\n\n\nlemma polytope_Int_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"\\<lbrakk>polytope S; polyhedron T\\<rbrakk> \\<Longrightarrow> polytope(S \\<inter> T)\"\nby (simp add: bounded_Int polytope_eq_bounded_polyhedron)\n\nlemma polyhedron_Int_polytope:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"\\<lbrakk>polyhedron S; polytope T\\<rbrakk> \\<Longrightarrow> polytope(S \\<inter> T)\"\nby (simp add: bounded_Int polytope_eq_bounded_polyhedron)\n\nlemma polytope_imp_polyhedron:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"polytope S \\<Longrightarrow> polyhedron S\"\nby (simp add: polytope_eq_bounded_polyhedron)\n\nlemma polytope_facet_exists:\n  fixes p :: \"'a :: euclidean_space set\"\n  assumes \"polytope p\" \"0 < aff_dim p\"\n  obtains F where \"F facet_of p\"\nproof (cases \"p = {}\")\n  case True with assms show ?thesis by auto\nnext\n  case False\n  then obtain v where \"v extreme_point_of p\"\n    using extreme_point_exists_convex\n    by (blast intro: \\<open>polytope p\\<close> polytope_imp_compact polytope_imp_convex)\n  then\n  show ?thesis\n    by (metis face_of_polyhedron_subset_facet polytope_imp_polyhedron aff_dim_sing\n       all_not_in_conv assms face_of_singleton less_irrefl singletonI that)\nqed\n\nlemma polyhedron_interval [iff]: \"polyhedron(cbox a b)\"\nby (metis polytope_imp_polyhedron polytope_interval)\n\nlemma polyhedron_convex_hull:\n  fixes S :: \"'a :: euclidean_space set\"\n  shows \"finite S \\<Longrightarrow> polyhedron(convex hull S)\"\nby (simp add: polytope_convex_hull polytope_imp_polyhedron)\n\n\nsubsection\\<open>Relative and absolute frontier of a polytope\\<close>\n\nlemma rel_boundary_of_convex_hull:\n    fixes S :: \"'a::euclidean_space set\"\n    assumes \"~ affine_dependent S\"\n      shows \"(convex hull S) - rel_interior(convex hull S) = (\\<Union>a\\<in>S. convex hull (S - {a}))\"\nproof -\n  have \"finite S\" by (metis assms aff_independent_finite)\n  then consider \"card S = 0\" | \"card S = 1\" | \"2 \\<le> card S\" by arith\n  then show ?thesis\n  proof cases\n    case 1 then have \"S = {}\" by (simp add: \\<open>finite S\\<close>)\n    then show ?thesis by simp\n  next\n    case 2 show ?thesis\n      by (auto intro: card_1_singletonE [OF \\<open>card S = 1\\<close>])\n  next\n    case 3\n    with assms show ?thesis\n      by (auto simp: polyhedron_convex_hull rel_boundary_of_polyhedron facet_of_convex_hull_affine_independent_alt \\<open>finite S\\<close>)\n  qed\nqed\n\nproposition frontier_of_convex_hull:\n    fixes S :: \"'a::euclidean_space set\"\n    assumes \"card S = Suc (DIM('a))\"\n      shows \"frontier(convex hull S) = \\<Union> {convex hull (S - {a}) | a. a \\<in> S}\"\nproof (cases \"affine_dependent S\")\n  case True\n    have [iff]: \"finite S\"\n      using assms using card_infinite by force\n    then have ccs: \"closed (convex hull S)\"\n      by (simp add: compact_imp_closed finite_imp_compact_convex_hull)\n    { fix x T\n      assume \"finite T\" \"T \\<subseteq> S\" \"int (card T) \\<le> aff_dim S + 1\" \"x \\<in> convex hull T\"\n      then have \"S \\<noteq> T\"\n        using True \\<open>finite S\\<close> aff_dim_le_card affine_independent_iff_card by fastforce\n      then obtain a where \"a \\<in> S\" \"a \\<notin> T\"\n        using \\<open>T \\<subseteq> S\\<close> by blast\n      then have \"x \\<in> (\\<Union>a\\<in>S. convex hull (S - {a}))\"\n        using True affine_independent_iff_card [of S]\n        apply simp\n        apply (metis (no_types, hide_lams) Diff_eq_empty_iff Diff_insert0 \\<open>a \\<notin> T\\<close> \\<open>T \\<subseteq> S\\<close> \\<open>x \\<in> convex hull T\\<close>  hull_mono insert_Diff_single   subsetCE)\n        done\n    } note * = this\n    have 1: \"convex hull S \\<subseteq> (\\<Union> a\\<in>S. convex hull (S - {a}))\"\n      apply (subst caratheodory_aff_dim)\n      apply (blast intro: *)\n      done\n    have 2: \"\\<Union>((\\<lambda>a. convex hull (S - {a})) ` S) \\<subseteq> convex hull S\"\n      by (rule Union_least) (metis (no_types, lifting)  Diff_subset hull_mono imageE)\n    show ?thesis using True\n      apply (simp add: segment_convex_hull frontier_def)\n      using interior_convex_hull_eq_empty [OF assms]\n      apply (simp add: closure_closed [OF ccs])\n      apply (rule subset_antisym)\n      using 1 apply blast\n      using 2 apply blast\n      done\nnext\n  case False\n  then have \"frontier (convex hull S) = (convex hull S) - rel_interior(convex hull S)\"\n    apply (simp add: rel_boundary_of_convex_hull [symmetric] frontier_def)\n    by (metis aff_independent_finite assms closure_convex_hull finite_imp_compact_convex_hull hull_hull interior_convex_hull_eq_empty rel_interior_nonempty_interior)\n  also have \"... = \\<Union>{convex hull (S - {a}) |a. a \\<in> S}\"\n  proof -\n    have \"convex hull S - rel_interior (convex hull S) = rel_frontier (convex hull S)\"\n      by (simp add: False aff_independent_finite polyhedron_convex_hull rel_boundary_of_polyhedron rel_frontier_of_polyhedron)\n    then show ?thesis\n      by (simp add: False rel_frontier_convex_hull_cases)\n  qed\n  finally show ?thesis .\nqed\n\nsubsection\\<open>Special case of a triangle\\<close>\n\nproposition frontier_of_triangle:\n    fixes a :: \"'a::euclidean_space\"\n    assumes \"DIM('a) = 2\"\n    shows \"frontier(convex hull {a,b,c}) = closed_segment a b \\<union> closed_segment b c \\<union> closed_segment c a\"\n          (is \"?lhs = ?rhs\")\nproof (cases \"b = a \\<or> c = a \\<or> c = b\")\n  case True then show ?thesis\n    by (auto simp: assms segment_convex_hull frontier_def empty_interior_convex_hull insert_commute card_insert_le_m1 hull_inc insert_absorb)\nnext\n  case False then have [simp]: \"card {a, b, c} = Suc (DIM('a))\"\n    by (simp add: card_insert Set.insert_Diff_if assms)\n  show ?thesis\n  proof\n    show \"?lhs \\<subseteq> ?rhs\"\n      using False\n      by (force simp: segment_convex_hull frontier_of_convex_hull insert_Diff_if insert_commute split: if_split_asm)\n    show \"?rhs \\<subseteq> ?lhs\"\n      using False\n      apply (simp add: frontier_of_convex_hull segment_convex_hull)\n      apply (intro conjI subsetI)\n        apply (rule_tac X=\"convex hull {a,b}\" in UnionI; force simp: Set.insert_Diff_if)\n       apply (rule_tac X=\"convex hull {b,c}\" in UnionI; force)\n      apply (rule_tac X=\"convex hull {a,c}\" in UnionI; force simp: insert_commute Set.insert_Diff_if)\n      done\n  qed\nqed\n\ncorollary inside_of_triangle:\n    fixes a :: \"'a::euclidean_space\"\n    assumes \"DIM('a) = 2\"\n    shows \"inside (closed_segment a b \\<union> closed_segment b c \\<union> closed_segment c a) = interior(convex hull {a,b,c})\"\nby (metis assms frontier_of_triangle bounded_empty bounded_insert convex_convex_hull inside_frontier_eq_interior bounded_convex_hull)\n\ncorollary interior_of_triangle:\n    fixes a :: \"'a::euclidean_space\"\n    assumes \"DIM('a) = 2\"\n    shows \"interior(convex hull {a,b,c}) =\n           convex hull {a,b,c} - (closed_segment a b \\<union> closed_segment b c \\<union> closed_segment c a)\"\n  using interior_subset\n  by (force simp: frontier_of_triangle [OF assms, symmetric] frontier_def Diff_Diff_Int)\n\nsubsection\\<open>Subdividing a cell complex\\<close>\n\nlemma subdivide_interval:\n  fixes x::real\n  assumes \"a < \\<bar>x - y\\<bar>\" \"0 < a\"\n  obtains n where \"n \\<in> \\<int>\" \"x < n * a \\<and> n * a < y \\<or> y <  n * a \\<and> n * a < x\"\nproof -\n  consider \"a + x < y\" | \"a + y < x\"\n    using assms by linarith\n  then show ?thesis\n  proof cases\n    case 1\n    let ?n = \"of_int (floor (x/a)) + 1\"\n    have x: \"x < ?n * a\"\n      by (meson \\<open>0 < a\\<close> divide_less_eq floor_unique_iff)\n    have \"?n * a \\<le> a + x\"\n      apply (simp add: algebra_simps)\n      by (metis \\<open>0 < a\\<close> floor_correct less_irrefl nonzero_mult_div_cancel_left real_mult_le_cancel_iff2 times_divide_eq_right)\n    also have \"... < y\"\n      by (rule 1)\n    finally have \"?n * a < y\" .\n    with x show ?thesis\n      using Ints_1 Ints_add Ints_of_int that by blast\n  next\n    case 2\n    let ?n = \"of_int (floor (y/a)) + 1\"\n    have y: \"y < ?n * a\"\n      by (meson \\<open>0 < a\\<close> divide_less_eq floor_unique_iff)\n    have \"?n * a \\<le> a + y\"\n      apply (simp add: algebra_simps)\n      by (metis \\<open>0 < a\\<close> floor_correct less_irrefl nonzero_mult_div_cancel_left real_mult_le_cancel_iff2 times_divide_eq_right)\n    also have \"... < x\"\n      by (rule 2)\n    finally have \"?n * a < x\" .\n    then show ?thesis\n      using Ints_1 Ints_add Ints_of_int that y by blast\n  qed\nqed\n\n\nlemma cell_subdivision_lemma:\n  assumes \"finite \\<F>\"\n      and \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> polytope X\"\n      and \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> aff_dim X \\<le> d\"\n      and \"\\<And>X Y. \\<lbrakk>X \\<in> \\<F>; Y \\<in> \\<F>\\<rbrakk> \\<Longrightarrow> (X \\<inter> Y) face_of X \\<and> (X \\<inter> Y) face_of Y\"\n      and \"finite I\"\n    shows \"\\<exists>\\<F>'. \\<Union>\\<F>' = \\<Union>\\<F> \\<and>\n                 finite \\<F>' \\<and>\n                 (\\<forall>X \\<in> \\<F>'. polytope X) \\<and>\n                 (\\<forall>X \\<in> \\<F>'. aff_dim X \\<le> d) \\<and>\n                 (\\<forall>X \\<in> \\<F>'. \\<forall>Y \\<in> \\<F>'. X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y) \\<and>\n                 (\\<forall>X \\<in> \\<F>'. \\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<forall>a b.\n                          (a,b) \\<in> I \\<longrightarrow> a \\<bullet> x \\<le> b \\<and> a \\<bullet> y \\<le> b \\<or>\n                                        a \\<bullet> x \\<ge> b \\<and> a \\<bullet> y \\<ge> b)\"\n  using \\<open>finite I\\<close>\nproof induction\n  case empty\n  then show ?case\n    by (rule_tac x=\"\\<F>\" in exI) (simp add: assms)\nnext\n  case (insert ab I)\n  then obtain \\<F>' where eq: \"\\<Union>\\<F>' = \\<Union>\\<F>\" and \"finite \\<F>'\"\n                   and poly: \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> polytope X\"\n                   and aff: \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> aff_dim X \\<le> d\"\n                   and face: \"\\<And>X Y. \\<lbrakk>X \\<in> \\<F>'; Y \\<in> \\<F>'\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n                   and I: \"\\<And>X x y a b.  \\<lbrakk>X \\<in> \\<F>'; x \\<in> X; y \\<in> X; (a,b) \\<in> I\\<rbrakk> \\<Longrightarrow>\n                                    a \\<bullet> x \\<le> b \\<and> a \\<bullet> y \\<le> b \\<or> a \\<bullet> x \\<ge> b \\<and> a \\<bullet> y \\<ge> b\"\n    by (auto simp: that)\n  obtain a b where \"ab = (a,b)\"\n    by fastforce\n  let ?\\<G> = \"(\\<lambda>X. X \\<inter> {x. a \\<bullet> x \\<le> b}) ` \\<F>' \\<union> (\\<lambda>X. X \\<inter> {x. a \\<bullet> x \\<ge> b}) ` \\<F>'\"\n  have eqInt: \"(S \\<inter> Collect P) \\<inter> (T \\<inter> Collect Q) = (S \\<inter> T) \\<inter> (Collect P \\<inter> Collect Q)\" for S T::\"'a set\" and P Q\n    by blast\n  show ?case\n  proof (intro conjI exI)\n    show \"\\<Union>?\\<G> = \\<Union>\\<F>\"\n      by (force simp: eq [symmetric])\n    show \"finite ?\\<G>\"\n      using \\<open>finite \\<F>'\\<close> by force\n    show \"\\<forall>X \\<in> ?\\<G>. polytope X\"\n      by (force simp: poly polytope_Int_polyhedron polyhedron_halfspace_le polyhedron_halfspace_ge)\n    show \"\\<forall>X \\<in> ?\\<G>. aff_dim X \\<le> d\"\n      by (auto; metis order_trans aff aff_dim_subset inf_le1)\n    show \"\\<forall>X \\<in> ?\\<G>. \\<forall>x \\<in> X. \\<forall>y \\<in> X. \\<forall>a b.\n                          (a,b) \\<in> insert ab I \\<longrightarrow> a \\<bullet> x \\<le> b \\<and> a \\<bullet> y \\<le> b \\<or>\n                                                  a \\<bullet> x \\<ge> b \\<and> a \\<bullet> y \\<ge> b\"\n      using \\<open>ab = (a, b)\\<close> I by fastforce\n    show \"\\<forall>X \\<in> ?\\<G>. \\<forall>Y \\<in> ?\\<G>. X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n      by (auto simp: eqInt halfspace_Int_eq face_of_Int_Int face face_of_halfspace_le face_of_halfspace_ge)\n  qed\nqed\n\n\nproposition cell_complex_subdivision_exists:\n  fixes \\<F> :: \"'a::euclidean_space set set\"\n  assumes \"0 < e\" \"finite \\<F>\"\n      and poly: \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> polytope X\"\n      and aff: \"\\<And>X. X \\<in> \\<F> \\<Longrightarrow> aff_dim X \\<le> d\"\n      and face: \"\\<And>X Y. \\<lbrakk>X \\<in> \\<F>; Y \\<in> \\<F>\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n  obtains \"\\<F>'\" where \"finite \\<F>'\" \"\\<Union>\\<F>' = \\<Union>\\<F>\" \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> diameter X < e\"\n                \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> polytope X\" \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> aff_dim X \\<le> d\"\n                \"\\<And>X Y. \\<lbrakk>X \\<in> \\<F>'; Y \\<in> \\<F>'\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\nproof -\n  have \"bounded(\\<Union>\\<F>)\"\n    by (simp add: \\<open>finite \\<F>\\<close> poly bounded_Union polytope_imp_bounded)\n  then obtain B where \"B > 0\" and B: \"\\<And>x. x \\<in> \\<Union>\\<F> \\<Longrightarrow> norm x < B\"\n    by (meson bounded_pos_less)\n  define C where \"C \\<equiv> {z \\<in> \\<int>. \\<bar>z * e / 2 / real DIM('a)\\<bar> \\<le> B}\"\n  define I where \"I \\<equiv> \\<Union>i \\<in> Basis. \\<Union>j \\<in> C. { (i::'a, j * e / 2 / DIM('a)) }\"\n  have \"finite C\"\n    using finite_int_segment [of \"-B / (e / 2 / DIM('a))\" \"B / (e / 2 / DIM('a))\"]\n    apply (simp add: C_def)\n    apply (erule rev_finite_subset)\n    using \\<open>0 < e\\<close>\n    apply (auto simp: divide_simps)\n    done\n  then have \"finite I\"\n    by (simp add: I_def)\n  obtain \\<F>' where eq: \"\\<Union>\\<F>' = \\<Union>\\<F>\" and \"finite \\<F>'\"\n              and poly: \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> polytope X\"\n              and aff: \"\\<And>X. X \\<in> \\<F>' \\<Longrightarrow> aff_dim X \\<le> d\"\n              and face: \"\\<And>X Y. \\<lbrakk>X \\<in> \\<F>'; Y \\<in> \\<F>'\\<rbrakk> \\<Longrightarrow> X \\<inter> Y face_of X \\<and> X \\<inter> Y face_of Y\"\n              and I: \"\\<And>X x y a b.  \\<lbrakk>X \\<in> \\<F>'; x \\<in> X; y \\<in> X; (a,b) \\<in> I\\<rbrakk> \\<Longrightarrow>\n                                     a \\<bullet> x \\<le> b \\<and> a \\<bullet> y \\<le> b \\<or> a \\<bullet> x \\<ge> b \\<and> a \\<bullet> y \\<ge> b\"\n    apply (rule exE [OF cell_subdivision_lemma])\n         apply (rule assms \\<open>finite I\\<close> | assumption)+\n    apply (auto intro: that)\n    done\n  show ?thesis\n  proof (rule_tac \\<F>'=\"\\<F>'\" in that)\n    show \"diameter X < e\" if \"X \\<in> \\<F>'\" for X\n    proof -\n      have \"diameter X \\<le> e/2\"\n      proof (rule diameter_le)\n        show \"norm (x - y) \\<le> e / 2\" if \"x \\<in> X\" \"y \\<in> X\" for x y\n        proof -\n          have \"norm x < B\" \"norm y < B\"\n            using B \\<open>X \\<in> \\<F>'\\<close> eq that by fastforce+\n          have \"norm (x - y) \\<le> (\\<Sum>b\\<in>Basis. \\<bar>(x-y) \\<bullet> b\\<bar>)\"\n            by (rule norm_le_l1)\n          also have \"... \\<le> of_nat (DIM('a)) * (e / 2 / DIM('a))\"\n          proof (rule sum_bounded_above)\n            fix i::'a\n            assume \"i \\<in> Basis\"\n            then have I': \"\\<And>z b. \\<lbrakk>z \\<in> C; b = z * e / (2 * real DIM('a))\\<rbrakk> \\<Longrightarrow> i \\<bullet> x \\<le> b \\<and> i \\<bullet> y \\<le> b \\<or> i \\<bullet> x \\<ge> b \\<and> i \\<bullet> y \\<ge> b\"\n              using I \\<open>X \\<in> \\<F>'\\<close> that\n              by (fastforce simp: I_def)\n            show \"\\<bar>(x - y) \\<bullet> i\\<bar> \\<le> e / 2 / real DIM('a)\"\n            proof (rule ccontr)\n              assume \"\\<not> \\<bar>(x - y) \\<bullet> i\\<bar> \\<le> e / 2 / real DIM('a)\"\n              then have xyi: \"\\<bar>i \\<bullet> x - i \\<bullet> y\\<bar> > e / 2 / real DIM('a)\"\n                by (simp add: inner_commute inner_diff_right)\n              obtain n where \"n \\<in> \\<int>\" and n: \"i \\<bullet> x < n * (e / 2 / real DIM('a)) \\<and> n * (e / 2 / real DIM('a)) < i \\<bullet> y \\<or> i \\<bullet> y < n * (e / 2 / real DIM('a)) \\<and> n * (e / 2 / real DIM('a)) < i \\<bullet> x\"\n                using subdivide_interval [OF xyi] DIM_positive \\<open>0 < e\\<close>\n                by (auto simp: zero_less_divide_iff)\n              have \"\\<bar>i \\<bullet> x\\<bar> < B\"\n                by (metis \\<open>i \\<in> Basis\\<close> \\<open>norm x < B\\<close> inner_commute norm_bound_Basis_lt)\n              have \"\\<bar>i \\<bullet> y\\<bar> < B\"\n                by (metis \\<open>i \\<in> Basis\\<close> \\<open>norm y < B\\<close> inner_commute norm_bound_Basis_lt)\n              have *: \"\\<bar>n * e\\<bar> \\<le> B * (2 * real DIM('a))\"\n                      if \"\\<bar>ix\\<bar> < B\" \"\\<bar>iy\\<bar> < B\"\n                         and ix: \"ix * (2 * real DIM('a)) < n * e\"\n                         and iy: \"n * e < iy * (2 * real DIM('a))\" for ix iy\n              proof (rule abs_leI)\n                have \"iy * (2 * real DIM('a)) \\<le> B * (2 * real DIM('a))\"\n                  by (rule mult_right_mono) (use \\<open>\\<bar>iy\\<bar> < B\\<close> in linarith)+\n                then show \"n * e \\<le> B * (2 * real DIM('a))\"\n                  using iy by linarith\n              next\n                have \"- ix * (2 * real DIM('a)) \\<le> B * (2 * real DIM('a))\"\n                  by (rule mult_right_mono) (use \\<open>\\<bar>ix\\<bar> < B\\<close> in linarith)+\n                then show \"- (n * e) \\<le> B * (2 * real DIM('a))\"\n                  using ix by linarith\n              qed\n              have \"n \\<in> C\"\n                using \\<open>n \\<in> \\<int>\\<close> n  by (auto simp: C_def divide_simps intro: * \\<open>\\<bar>i \\<bullet> x\\<bar> < B\\<close> \\<open>\\<bar>i \\<bullet> y\\<bar> < B\\<close>)\n              show False\n                using  I' [OF \\<open>n \\<in> C\\<close> refl] n  by auto\n            qed\n          qed\n          also have \"... = e / 2\"\n            by simp\n          finally show ?thesis .\n        qed\n      qed (use \\<open>0 < e\\<close> in force)\n      also have \"... < e\"\n        by (simp add: \\<open>0 < e\\<close>)\n      finally show ?thesis .\n    qed\n  qed (auto simp: eq poly aff face  \\<open>finite \\<F>'\\<close>)\nqed\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Analysis/Polytope.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094174159127, "lm_q2_score": 0.8418256551882382, "lm_q1q2_score": 0.7520107856019741}}
{"text": "theory TestRecIndTac\n  imports Main  \"$HIPSTER_HOME/IsaHipster\" \nbegin\nsetup Misc_Data.set_bool_eq_split\n(*setup Misc_Data.set_noisy*)\n\nfun sorted :: \"nat list \\<Rightarrow> bool\"\n  where \"sorted [] = True\"\n  | \"sorted [x] = True\"\n  | \"sorted (x1#x2#xs) = ((x1 \\<le> x2) \\<and> sorted (x2#xs))\"\n\nfun ins :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat list\"\n  where \"ins x [] = [x]\"\n  | \"ins x (y#ys) = (if (x \\<le> y) then (x#y#ys) else y#(ins x ys))\"\n\nfun isort ::  \"nat list \\<Rightarrow> nat list\"\n  where \"isort [] = []\"\n  | \"isort (x#xs) = ins x (isort xs)\"\n\n\n\nML\\<open>\n(*val t = \"(sorted y) \\<Longrightarrow> (sorted (ins x y))\";\nval ctxt  =  @{context};\nVariable.is_fixed ctxt \"x\"; \nval prop = t |> Syntax.read_prop ctxt\nval thm2 = t |> Syntax.read_prop ctxt\n                   |> Goal.init o (Thm.cterm_of ctxt);\nval ctxt  = Variable.auto_fixes prop @{context};\nval tac = Induct_CTac.recursion_induction_ctac Induct_CTac.induct_and_sledgehammer_ctac;\n(* val tbad = \"(\\<And>x. TestRecIndTac.sorted [] \\<Longrightarrow> TestRecIndTac.sorted (ins x [])) \\<Longrightarrow> (\\<And>x xa. TestRecIndTac.sorted [x] \\<Longrightarrow> TestRecIndTac.sorted (ins xa [x])) \\<Longrightarrow> (\\<And>x1 x2 xs x. (\\<And>x. TestRecIndTac.sorted (if x \\<le> x2 then x # x2 # xs else x2 # ins x xs)) \\<Longrightarrow> x1 \\<le> x2 \\<and> TestRecIndTac.sorted (x2 # xs) \\<Longrightarrow> \\<not> x \\<le> x2 \\<longrightarrow> TestRecIndTac.sorted (x2 # ins x xs)) \\<Longrightarrow> (TestRecIndTac.sorted y \\<Longrightarrow> TestRecIndTac.sorted (ins x y))\"\nval thm2 = t |> Syntax.read_prop ctxt\n                   |> Goal.init o (Thm.cterm_of ctxt); *)\n*)\n\\<close>\nfun count :: \"nat \\<Rightarrow> nat list \\<Rightarrow> nat\"\n  where\n  \"count x [] = 0\"\n| \"count x (y#ys) = (if (x=y) then Suc(count x ys) else (count x ys))\"\n(* hipster sorted ins *)\nlemma lemma_a [thy_expl]: \"TestRecIndTac.sorted (ins x y) \\<Longrightarrow> TestRecIndTac.sorted y\"\napply (induct x y rule: TestRecIndTac.ins.induct)\napply simp\n  apply simp\napply (smt TestRecIndTac.sorted.simps(2) TestRecIndTac.sorted.simps(3) dual_order.trans ins.elims)\ndone\n\nlemma lemma_aa [thy_expl]: \"TestRecIndTac.sorted y \\<Longrightarrow> TestRecIndTac.sorted (ins x y)\"\n  apply (induct y arbitrary: x rule: TestRecIndTac.sorted.induct)\n  apply simp\n  apply simp\n  apply simp\n  apply presburger\n  done\n    \nlemma lemma_ab [thy_expl]: \"ins y (ins x z) = ins x (ins y z)\"\n  apply (induct x z arbitrary: y rule: TestRecIndTac.ins.induct)\n  apply simp\napply simp\ndone \nML\\<open>\nfun mytac ctxt = (Rec_Ind_Tacs.recinduct_simp_or_sledgehammer ctxt) ORELSE (Rec_Ind_Lemma_Spec_Tacs.koen_induct ctxt)\n\\<close>\nmethod_setup recind_lemma = \\<open>\n  Scan.lift (Scan.succeed \n    (fn ctxt => SIMPLE_METHOD \n      (mytac ctxt)))\n\\<close>\n(* hipster sorted isort *)\nlemma lemma_ac [thy_expl]: \"TestRecIndTac.sorted (isort x)\"\n  apply (induct x rule: TestRecIndTac.isort.induct)\n  apply simp\n  apply simp\n  apply (simp add: lemma_aa)\n  done\n    \nlemma lemma_ad [thy_expl]: \"isort (ins x y) = ins x (isort y)\"\n  apply (induct x y rule: TestRecIndTac.ins.induct)\napply simp\napply simp\nusing lemma_ab apply blast\n  done\n\nlemma lemma_ae [thy_expl]: \"isort (isort x) = isort x\"\napply (induct x rule: TestRecIndTac.isort.induct)\n  apply simp\n  apply simp\napply (simp add: lemma_ad)\n  done\n\nhipster count isort\nlemma lemma_af [thy_expl]: \"count x (ins y z) = count x (y # z)\"\n  apply (induct z arbitrary: x y)\n  apply simp\n  apply simp\n  done\n\nlemma lemma_ag [thy_expl]: \"count x (isort y) = count x y\"\n  apply (induct y arbitrary: x)\n  apply simp\n  apply simp\n  apply (simp add: lemma_af)\n  done\n\nend", "meta": {"author": "moajohansson", "repo": "IsaHipster", "sha": "91f6ea3f1166a9de547722ece6445fe843ad89b4", "save_path": "github-repos/isabelle/moajohansson-IsaHipster", "path": "github-repos/isabelle/moajohansson-IsaHipster/IsaHipster-91f6ea3f1166a9de547722ece6445fe843ad89b4/Examples/TestRecIndTac.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8418256492357358, "lm_q1q2_score": 0.7520107731112058}}
{"text": "\ntheory Trees2_3\nimports Main\nbegin\n\ndatatype tree = Tp | Nd tree tree\n\nprimrec tips :: \"tree \\<Rightarrow> nat\"\nwhere\n  \"tips Tp = 1\"\n| \"tips (Nd l r) = (tips l) + (tips r)\"\n\nprimrec height :: \"tree \\<Rightarrow> nat\"\nwhere\n  \"height Tp = 0\"\n| \"height (Nd l r) = 1 + max (height l) (height r)\"\n\nprimrec cbt :: \"nat \\<Rightarrow> tree\"\nwhere\n  \"cbt 0 = Tp\"\n| \"cbt (Suc n) = Nd (cbt n) (cbt n)\"\n\nprimrec iscbt ::\"(tree \\<Rightarrow> 'a) \\<Rightarrow> tree \\<Rightarrow> bool\"\nwhere\n  \"iscbt f Tp = True\"\n| \"iscbt f (Nd l r) = ((iscbt f l) \\<and> (iscbt f r) \\<and> (f l = f r))\"\n\nvalue \"iscbt tips Tp\"\nvalue \"iscbt tips (Nd Tp Tp)\"\n\nvalue \"size Tp\"\nvalue \"size (Nd Tp Tp)\"\n\nlemma tips_size: \"tips t = 1 + size t\"\n  apply (induct t)\n  apply auto\ndone\n\ntheorem iscbt_tips_size: \"iscbt tips t = iscbt size t\"\n  apply (induct t)\n  apply simp\n  apply (simp add:tips_size)\ndone\n\nvalue \"height Tp\"\nvalue \"size Tp\"\n\nvalue \"height (Nd Tp Tp)\"\nvalue \"size (Nd Tp Tp)\"\n\nvalue \"height (Nd (Nd Tp Tp) (Nd Tp Tp))\"\nvalue \"size (Nd (Nd Tp Tp) (Nd Tp Tp))\"\n\nlemma height_tips: \"iscbt height t \\<longrightarrow> tips t = (2 ^ height t)\"\n  apply (induct t)\n  apply simp\n  apply auto\ndone\n\ntheorem iscbt_height_tips: \"iscbt height t = iscbt tips t\"\n  apply (induct t)\n  apply simp\n  apply (auto simp add:height_tips)\ndone\n\n(* Can we prove the same using induction as well ? *)\ntheorem \"iscbt size t = iscbt height t\"\n  by (simp add:iscbt_height_tips iscbt_tips_size)\n\nend\n\n", "meta": {"author": "jineshkj", "repo": "cis700_assured_systems", "sha": "9fb270e519a3644f9713bee8cef082aefbc8228f", "save_path": "github-repos/isabelle/jineshkj-cis700_assured_systems", "path": "github-repos/isabelle/jineshkj-cis700_assured_systems/cis700_assured_systems-9fb270e519a3644f9713bee8cef082aefbc8228f/Isabelle_HOL_Exercies/Trees2_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.8418256452674008, "lm_q1q2_score": 0.7520107623929124}}
{"text": "theory Digits\n  imports Complex_Main\nbegin\n\nsection \\<open>Representation of integers in different bases\\<close>\n\ntext \\<open>\\<close>\n\ntext \\<open> First, we look at some useful lemmas for splitting sums. \\<close>\nlemma split_sum_first_elt_less: assumes \"n<m\" \n  shows \"(\\<Sum>i\\<in>{n..<m}. f i) = f n + (\\<Sum>i\\<in>{Suc n ..<m}. f i)\"\n  using sum.atLeast_Suc_lessThan assms by blast\n\nlemma split_sum_mid_less: assumes \"i<(n::nat)\"\n  shows \"(\\<Sum>j<n. f j) = (\\<Sum>j<i. f j) + (\\<Sum>j=i..<n. f j)\"\nproof -\n  have \"(\\<Sum>j<n. f j) = (\\<Sum>j\\<in>{..<i} \\<union> {i..<n}. f j)\"\n    using \\<open>i < n\\<close> by (intro sum.cong) auto\n  also have \"\\<dots> = (\\<Sum>j<i. f j) + (\\<Sum>j=i..<n. f j)\"\n    by (subst sum.union_disjoint) auto\n  finally show \"(\\<Sum>j<n. f j) = (\\<Sum>j<i. f j) + (\\<Sum>j=i..<n. f j)\" .\nqed\n\ntext \\<open>In order to use representation of numbers in a basis \\<open>base\\<close> and to calculate the conversion \nto and from integers, we introduce the following locale.\\<close>\nlocale digits =\n  fixes base :: nat\n  assumes base_pos: \"base > 0\"\nbegin\n\ntext \\<open>Conversion from basis base to integers: \\<open>from_digits n d\\<close>\n\n\\begin{tabular}{lcp{8cm}}\n  n:& \\<open>nat\\<close>& length of representation in basis base\\\\\n  d:& \\<open>nat \\<Rightarrow> nat\\<close>& function of digits in basis base where \\<open>d i\\<close> is the $i$-th digit in basis base\\\\\n  output:& \\<open>nat\\<close>& natural number corresponding to $d(n-1) \\dots d(0)$ as integer\\\\\n\\end{tabular}\n\\<close>\nfun from_digits :: \"nat \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> nat\" where\n  \"from_digits 0 d = 0\"\n| \"from_digits (Suc n) d = d 0 + base * from_digits n (d \\<circ> Suc)\"\n\ntext \\<open>Alternative definition using sum:\\<close>\nlemma from_digits_altdef: \"from_digits n d = (\\<Sum>i<n. d i * base ^ i)\"\n  by (induction n d rule: from_digits.induct)\n     (auto simp add: sum.lessThan_Suc_shift o_def sum_distrib_left \n       sum_distrib_right mult_ac simp del: sum.lessThan_Suc)\n\ntext \\<open>Digit in basis base of some integer number: \\<open>digit x i\\<close>\n\n\\begin{tabular}{lcp{8cm}}\n  x:& \\<open>nat\\<close>& integer\\\\\n  i:& \\<open>nat\\<close>& index\\\\\n  output:& \\<open>nat\\<close>& $i$-th digit of representation in basis base of $x$\\\\\n\\end{tabular}\n\\<close>\nfun digit :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"digit x 0 = x mod base\"\n| \"digit x (Suc i) = digit (x div base) i\"\n\ntext \\<open>Alternative definition using divisor and modulo:\\<close>\nlemma digit_altdef: \"digit x i = (x div (base ^ i)) mod base\"\n  by (induction x i rule: digit.induct) (auto simp: div_mult2_eq) \n\ntext \\<open>Every digit must be smaller that the base.\\<close>\nlemma digit_less_base: \"digit x i < base\"\n  using base_pos by (auto simp: digit_altdef)\n\ntext \\<open>A representation in basis \\<open>base\\<close> of length $n$ must be less than $\\<open>base\\<close> ^ n$.\\<close>\nlemma from_digits_less: \n  assumes \"\\<forall>i<n. d i < base\" \n  shows \"from_digits n d < base ^ n\"\nusing assms proof (induct n d rule: from_digits.induct)\n  case (2 n d)\n  have \"from_digits n (d \\<circ> Suc) \\<le> base ^ n -1\" using 2 \n    by (metis One_nat_def Suc_leI Suc_pred base_pos comp_apply \n        less_Suc_eq_le zero_less_power)\n  moreover have \"d 0 \\<le> base -1\" using 2 \n    by (metis One_nat_def Suc_pred base_pos less_Suc_eq_0_disj \n        less_Suc_eq_le)\n  ultimately have \"d 0 + base * from_digits n (d \\<circ> Suc) \\<le> \n      base - 1 + base * (base^(n) - 1)\"\n    by (simp add: add_mono_thms_linordered_semiring(1))\n  then show \"from_digits (Suc n) d < base ^ Suc n\" \n    using base_pos by (auto simp:comp_def) \n    (metis Suc_pred add_gr_0 le_imp_less_Suc mult_Suc_right \n      zero_less_power)\nqed auto\n\ntext \\<open>Lemmas for \\<open>mod\\<close> and \\<open>div\\<close> in number systems of basis \\<open>base\\<close>:\\<close>\nlemma mod_base:  assumes \"\\<And>i. i<n \\<Longrightarrow> d i < base\" \"n>0\"\n  shows \"from_digits n d mod base = d 0 \"\nproof -\n  have \"(\\<Sum>i<n. d i * base ^ i) mod base = \n          (\\<Sum>i<n. d i * base ^ i mod base) mod base\"  \n  by (subst mod_sum_eq[symmetric]) simp\n  then show ?thesis using assms \n      sum.lessThan_Suc_shift[of \"(\\<lambda>i. d i * base ^ i mod base)\" \"n-1\"]\n    unfolding from_digits_altdef by simp\nqed\n\nlemma mod_base_i:  \n  assumes \"\\<And>i. i<n \\<Longrightarrow> d i < base\" \"n>0\" \"i<n\"\n  shows \"(\\<Sum>j=i..<n. d j * base ^ (j-i)) mod base = d i \"\nproof -\n  have \"(\\<Sum>j=i..<n. d j * base ^ (j-i)) mod base = \n        (\\<Sum>j=i..<n. d j * base ^ (j-i) mod base) mod base\"  \n    by (subst mod_sum_eq[symmetric]) simp\n  then show ?thesis \n    using assms split_sum_first_elt_less[where \n        f = \"(\\<lambda>j. d j * base ^ (j-i) mod base)\"] \n    unfolding from_digits_altdef by simp\nqed\n\nlemma div_base_i: \n  assumes \"\\<And>i. i<n \\<Longrightarrow> d i < base\" \"n>0\" \"i<n\"\n  shows \"from_digits n d div (base ^i) = (\\<Sum>j=i..<n. d j * base ^ (j-i))\"\n  unfolding from_digits_altdef proof -\n  have base_exp: \"base^(j) =  base^(j-i) * base^i\" \n    if \"j\\<in>{i..<n}\" for j \n    by (metis Nat.add_diff_assoc2 add_diff_cancel_right' atLeastLessThan_iff \n        power_add that)\n  have first:\"(\\<Sum>j<i. d j * base ^ j)< base ^ i\" \n    using assms from_digits_less[where n=\"i\"] \n    unfolding from_digits_altdef by auto\n  have \"(\\<Sum>j<n. d j * base ^ j) = \n          (\\<Sum>j<i. d j * base ^ j) + (\\<Sum>j=i..<n. d j * base ^ j)\" \n    using assms split_sum_mid_less[where f=\"(\\<lambda>j. d j * base^j)\"] by auto\n  then have split_sum: \"(\\<Sum>j<n. d j * base ^ j) = \n      (\\<Sum>j<i. d j * base ^ j) + base^i * (\\<Sum>j=i..<n. d j * base ^ (j-i))\"\n    using base_exp mult.assoc sum_distrib_right \n    by (smt (z3) mult.commute sum.cong)\n  then show \"(\\<Sum>i<n. d i * base ^ i) div base ^ i = \n              (\\<Sum>j = i..<n. d j * base ^ (j - i))\" \n    using first by (simp add:split_sum base_pos)\nqed\n\n\n\ntext \\<open>Conversions are inverse to each other.\\<close>\nlemma digit_from_digits:\n  assumes \"\\<And>j. j<n \\<Longrightarrow> d j < base\" \"n>0\" \"i<n\"\n  shows   \"digit (from_digits n d) i = d i\"\n  using assms proof (cases \"i=0\")\n  case True\n  then show ?thesis \n    by (simp add: assms(1) assms(2) digits.mod_base digits_axioms)\nnext\n  case False\n  have \"from_digits n d div base^i mod base = d i\" \n    using assms by (auto simp add: div_base_i mod_base_i) \n  then show \"digit (from_digits n d) i = d i\" \n    unfolding digit_altdef by auto\nqed\n\nlemma div_distrib: assumes \"i<n\" \n  shows \"(a*base^n + b) div base^i mod base = b div base^i mod base\"\nproof -\n  have \"base^i dvd (a*base^n)\" using assms \n    by (simp add: le_imp_power_dvd)\n  moreover have \"a*base^n div base^i mod base = 0\" \n    by (metis Suc_leI assms dvd_imp_mod_0 dvd_mult \n        dvd_mult_imp_div le_imp_power_dvd power_Suc)\n  ultimately show ?thesis\n    by (metis add.right_neutral div_mult_mod_eq \n        div_plus_div_distrib_dvd_left mod_mult_self3)\nqed\n\nlemma from_digits_digit:\n  assumes \"x < base ^ n\"\n  shows   \"from_digits n (digit x) = x\"\n  using assms unfolding digit_altdef from_digits_altdef \nproof (induction n arbitrary: x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  define x_less where \"x_less = x mod base^n\"\n  define x_n where \"x_n = x div base^n\"\n  have \"x_less < base^n\" \n    using x_less_def base_pos mod_less_divisor by presburger\n  then have IH_x_less:\n    \"(\\<Sum>i<n. x_less div base ^ i mod base * base ^ i) = x_less\" \n    using Suc.IH by simp\n  have \"x_n < base\" using \\<open>x<base^Suc n\\<close> \n    by auto (metis less_mult_imp_div_less x_n_def)\n  then have \"x_n mod base = x_n\" by simp\n  have x_less_i_eq_x_i:\"x mod base^n div base ^i mod base = \n    x div base^i mod base\" if \"i<n\" for i\n  proof -\n    have \"x div base^i mod base = \n          ((x div base^n) * base^n + x mod base^n) div base^i mod base\"\n      using div_mult_mod_eq[of x \"base^n\"] by simp\n    also have \"\\<dots> = x mod base^n div base^i mod base\" \n      using div_distrib[where a=\"x div base^n\" and b = \"x mod base^n\"]\n        that by auto\n    finally show ?thesis by simp\n  qed\n  have \"x = (x_n mod base)*base^n + x_less\" \n    unfolding \\<open>x_n mod base=x_n\\<close> \n    using x_n_def x_less_def div_mod_decomp by blast \n  also have \"\\<dots> = (x div base^n mod base) * base^n + \n                (\\<Sum>i<n. x div base ^ i mod base * base ^ i)\"\n    using IH_x_less x_less_def x_less_i_eq_x_i x_n_def by auto\n  finally show ?case using sum.atMost_Suc \n    by (simp add: add.commute)\nqed\n\ntext \\<open>Stronger formulation of above lemma.\\<close>\nlemma from_digits_digit': \n  \"from_digits n (digit x) = x mod (base ^ n)\"\n  unfolding from_digits_altdef digit_altdef \nproof (induction n arbitrary: x)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  define x_less where \"x_less = x mod base^n\"\n  define x_n where \"x_n = x div base^n mod base\"\n  have \"x_less < base^n\" using x_less_def base_pos \n      mod_less_divisor by presburger\n  then have IH_x_less:\n    \"(\\<Sum>i<n. x_less div base ^ i mod base * base ^ i) = x_less\" \n    using Suc.IH by simp\n  have \"x_n < base\" using base_pos mod_less_divisor x_n_def \n    by blast\n  then have \"x_n mod base = x_n\" by simp\n  have x_less_i_eq_x_i:\"x mod base^n div base ^i mod base = \n    x div base^i mod base\" if \"i<n\" for i\n  proof -\n    have \"x div base^i mod base = \n      ((x div base^n) * base^n + x mod base^n) div base^i mod base\"\n      using div_mult_mod_eq[of x \"base^n\"] by simp\n    also have \"\\<dots> = x mod base^n div base^i mod base\" \n      using div_distrib[where a=\"x div base^n\" and b = \"x mod base^n\"] \n        that by auto\n    finally show ?thesis by simp\n  qed\n  have \"x mod base^Suc n = x_n*base^n + x_less\" \n    by (metis mod_mult2_eq mult.commute power_Suc2 x_less_def x_n_def)\n  also have \"\\<dots> = (x div base^n mod base) * base^n + \n                (\\<Sum>i<n. x div base ^ i mod base * base ^ i)\"\n    using IH_x_less x_less_def x_less_i_eq_x_i x_n_def by auto\n  finally show ?case using sum.atMost_Suc \n    by (simp add: add.commute)\nqed\n\nend\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Van_der_Waerden/Digits.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.8376199673867852, "lm_q1q2_score": 0.751927505883357}}
{"text": "(*<*)\ntheory CodeGen imports Main begin\n(*>*)\n\nsection{*Case Study: Compiling Expressions*}\n\ntext{*\\label{sec:ExprCompiler}\n\\index{compiling expressions example|(}%\nThe task is to develop a compiler from a generic type of expressions (built\nfrom variables, constants and binary operations) to a stack machine.  This\ngeneric type of expressions is a generalization of the boolean expressions in\n\\S\\ref{sec:boolex}.  This time we do not commit ourselves to a particular\ntype of variables or values but make them type parameters.  Neither is there\na fixed set of binary operations: instead the expression contains the\nappropriate function itself.\n*}\n\ntype_synonym 'v binop = \"'v \\<Rightarrow> 'v \\<Rightarrow> 'v\"\ndatatype (dead 'a, 'v) expr = Cex 'v\n                      | Vex 'a\n                      | Bex \"'v binop\"  \"('a,'v)expr\"  \"('a,'v)expr\"\n\ntext{*\\noindent\nThe three constructors represent constants, variables and the application of\na binary operation to two subexpressions.\n\nThe value of an expression with respect to an environment that maps variables to\nvalues is easily defined:\n*}\n\nprimrec \"value\" :: \"('a,'v)expr \\<Rightarrow> ('a \\<Rightarrow> 'v) \\<Rightarrow> 'v\" where\n\"value (Cex v) env = v\" |\n\"value (Vex a) env = env a\" |\n\"value (Bex f e1 e2) env = f (value e1 env) (value e2 env)\"\n\ntext{*\nThe stack machine has three instructions: load a constant value onto the\nstack, load the contents of an address onto the stack, and apply a\nbinary operation to the two topmost elements of the stack, replacing them by\nthe result. As for @{text\"expr\"}, addresses and values are type parameters:\n*}\n\ndatatype (dead 'a, 'v) instr = Const 'v\n                       | Load 'a\n                       | Apply \"'v binop\"\n\ntext{*\nThe execution of the stack machine is modelled by a function\n@{text\"exec\"} that takes a list of instructions, a store (modelled as a\nfunction from addresses to values, just like the environment for\nevaluating expressions), and a stack (modelled as a list) of values,\nand returns the stack at the end of the execution --- the store remains\nunchanged:\n*}\n\nprimrec exec :: \"('a,'v)instr list \\<Rightarrow> ('a\\<Rightarrow>'v) \\<Rightarrow> 'v list \\<Rightarrow> 'v list\"\nwhere\n\"exec [] s vs = vs\" |\n\"exec (i#is) s vs = (case i of\n    Const v  \\<Rightarrow> exec is s (v#vs)\n  | Load a   \\<Rightarrow> exec is s ((s a)#vs)\n  | Apply f  \\<Rightarrow> exec is s ((f (hd vs) (hd(tl vs)))#(tl(tl vs))))\"\n\ntext{*\\noindent\nRecall that @{term\"hd\"} and @{term\"tl\"}\nreturn the first element and the remainder of a list.\nBecause all functions are total, \\cdx{hd} is defined even for the empty\nlist, although we do not know what the result is. Thus our model of the\nmachine always terminates properly, although the definition above does not\ntell us much about the result in situations where @{term\"Apply\"} was executed\nwith fewer than two elements on the stack.\n\nThe compiler is a function from expressions to a list of instructions. Its\ndefinition is obvious:\n*}\n\nprimrec compile :: \"('a,'v)expr \\<Rightarrow> ('a,'v)instr list\" where\n\"compile (Cex v)       = [Const v]\" |\n\"compile (Vex a)       = [Load a]\" |\n\"compile (Bex f e1 e2) = (compile e2) @ (compile e1) @ [Apply f]\"\n\ntext{*\nNow we have to prove the correctness of the compiler, i.e.\\ that the\nexecution of a compiled expression results in the value of the expression:\n*}\ntheorem \"exec (compile e) s [] = [value e s]\"\n(*<*)oops(*>*)\ntext{*\\noindent\nThis theorem needs to be generalized:\n*}\n\ntheorem \"\\<forall>vs. exec (compile e) s vs = (value e s) # vs\"\n\ntxt{*\\noindent\nIt will be proved by induction on @{term\"e\"} followed by simplification.  \nFirst, we must prove a lemma about executing the concatenation of two\ninstruction sequences:\n*}\n(*<*)oops(*>*)\nlemma exec_app[simp]:\n  \"\\<forall>vs. exec (xs@ys) s vs = exec ys s (exec xs s vs)\" \n\ntxt{*\\noindent\nThis requires induction on @{term\"xs\"} and ordinary simplification for the\nbase cases. In the induction step, simplification leaves us with a formula\nthat contains two @{text\"case\"}-expressions over instructions. Thus we add\nautomatic case splitting, which finishes the proof:\n*}\napply(induct_tac xs, simp, simp split: instr.split)\n(*<*)done(*>*)\ntext{*\\noindent\nNote that because both \\methdx{simp_all} and \\methdx{auto} perform simplification, they can\nbe modified in the same way as @{text simp}.  Thus the proof can be\nrewritten as\n*}\n(*<*)\ndeclare exec_app[simp del]\n\n\nWe could now go back and prove @{prop\"exec (compile e) s [] = [value e s]\"}\nmerely by simplification with the generalized version we just proved.\nHowever, this is unnecessary because the generalized version fully subsumes\nits instance.%\n\\index{compiling expressions example|)}\n*}\n(*<*)\ntheorem \"\\<forall>vs. exec (compile e) s vs = (value e s) # vs\"\nby(induct_tac e, auto)\nend\n(*>*)\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/Doc/Tutorial/CodeGen/CodeGen.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587875995483, "lm_q2_score": 0.8459424373085146, "lm_q1q2_score": 0.7518387749613223}}
{"text": "section \\<open>Proof of Sturm's Theorem\\<close>\n(* Author: Manuel Eberl <manuel@pruvisto.org> *)\ntheory Sturm_Theorem\n  imports \"HOL-Computational_Algebra.Polynomial\"\n    \"Lib/Sturm_Library\" \"HOL-Computational_Algebra.Field_as_Ring\"\nbegin\n\nsubsection \\<open>Sign changes of polynomial sequences\\<close>\n\ntext \\<open>\n  For a given sequence of polynomials, this function computes the number of sign changes\n  of the sequence of polynomials evaluated at a given position $x$. A sign change is a\n  change from a negative value to a positive one or vice versa; zeros in the sequence are\n  ignored.\n\\<close>\n\ndefinition sign_changes where\n\"sign_changes ps (x::real) =\n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map (\\<lambda>p. sgn (poly p x)) ps))) - 1\"\n\ntext \\<open>\n  The number of sign changes of a sequence distributes over a list in the sense that\n  the number of sign changes of a sequence $p_1, \\ldots, p_i, \\ldots, p_n$ at $x$ is the same\n  as the sum of the sign changes of the sequence $p_1, \\ldots, p_i$ and $p_i, \\ldots, p_n$\n  as long as $p_i(x)\\neq 0$.\n\\<close>\n\nlemma sign_changes_distrib:\n  \"poly p x \\<noteq> 0 \\<Longrightarrow>\n      sign_changes (ps\\<^sub>1 @ [p] @ ps\\<^sub>2) x =\n      sign_changes (ps\\<^sub>1 @ [p]) x + sign_changes ([p] @ ps\\<^sub>2) x\"\n  by (simp add: sign_changes_def sgn_zero_iff, subst remdups_adj_append, simp)\n\ntext \\<open>\n  The following two congruences state that the number of sign changes is the same\n  if all the involved signs are the same.\n\\<close>\n\nlemma sign_changes_cong:\n  assumes \"length ps = length ps'\"\n  assumes \"\\<forall>i < length ps. sgn (poly (ps!i) x) = sgn (poly (ps'!i) y)\"\n  shows \"sign_changes ps x = sign_changes ps' y\"\nproof-\n from assms(2) have A: \"map (\\<lambda>p. sgn (poly p x)) ps = map (\\<lambda>p. sgn (poly p y)) ps'\"\n  proof (induction rule: list_induct2[OF assms(1)])\n    case 1\n      then show ?case by simp\n  next\n    case (2 p ps p' ps')\n      from 2(3)\n      have \"\\<forall>i<length ps. sgn (poly (ps ! i) x) =\n                         sgn (poly (ps' ! i) y)\" by auto\n      from 2(2)[OF this] 2(3) show ?case by auto\n  qed\n  show ?thesis unfolding sign_changes_def by (simp add: A)\nqed\n\nlemma sign_changes_cong':\n  assumes \"\\<forall>p \\<in> set ps. sgn (poly p x) = sgn (poly p y)\"\n  shows \"sign_changes ps x = sign_changes ps y\"\nusing assms by (intro sign_changes_cong, simp_all)\n\ntext \\<open>\n  For a sequence of polynomials of length 3, if the first and the third\n  polynomial have opposite and nonzero sign at some $x$, the number of\n  sign changes is always 1, irrespective of the sign of the second\n  polynomial.\n\\<close>\n\nlemma sign_changes_sturm_triple:\n  assumes \"poly p x \\<noteq> 0\" and \"sgn (poly r x) = - sgn (poly p x)\"\n  shows \"sign_changes [p,q,r] x = 1\"\nunfolding sign_changes_def by (insert assms, auto simp: sgn_real_def)\n\ntext \\<open>\n  Finally, we define two additional functions that count the sign changes ``at infinity''.\n\\<close>\n\ndefinition sign_changes_inf where\n\"sign_changes_inf ps =\n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map poly_inf ps))) - 1\"\n\ndefinition sign_changes_neg_inf where\n\"sign_changes_neg_inf ps =\n    length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map poly_neg_inf ps))) - 1\"\n\n\n\nsubsection \\<open>Definition of Sturm sequences locale\\<close>\n\ntext \\<open>\n  We first define the notion of a ``Quasi-Sturm sequence'', which is a weakening of\n  a Sturm sequence that captures the properties that are fulfilled by a nonempty\n  suffix of a Sturm sequence:\n  \\begin{itemize}\n    \\item The sequence is nonempty.\n    \\item The last polynomial does not change its sign.\n    \\item If the middle one of three adjacent polynomials has a root at $x$, the other\n          two have opposite and nonzero signs at $x$.\n  \\end{itemize}\n\\<close>\n\nlocale quasi_sturm_seq =\n  fixes ps :: \"(real poly) list\"\n  assumes last_ps_sgn_const[simp]:\n      \"\\<And>x y. sgn (poly (last ps) x) = sgn (poly (last ps) y)\"\n  assumes ps_not_Nil[simp]: \"ps \\<noteq> []\"\n  assumes signs: \"\\<And>i x. \\<lbrakk>i < length ps - 2; poly (ps ! (i+1)) x = 0\\<rbrakk>\n                     \\<Longrightarrow> (poly (ps ! (i+2)) x) * (poly (ps ! i) x) < 0\"\n\n\ntext \\<open>\n  Now we define a Sturm sequence $p_1,\\ldots,p_n$ of a polynomial $p$ in the following way:\n  \\begin{itemize}\n    \\item The sequence contains at least two elements.\n    \\item $p$ is the first polynomial, i.\\,e. $p_1 = p$.\n    \\item At any root $x$ of $p$, $p_2$ and $p$ have opposite sign left of $x$ and\n          the same sign right of $x$ in some neighbourhood around $x$.\n    \\item The first two polynomials in the sequence have no common roots.\n    \\item If the middle one of three adjacent polynomials has a root at $x$, the other\n          two have opposite and nonzero signs at $x$.\n  \\end{itemize}\n\\<close>\n\nlocale sturm_seq = quasi_sturm_seq +\n  fixes p :: \"real poly\"\n  assumes hd_ps_p[simp]: \"hd ps = p\"\n  assumes length_ps_ge_2[simp]: \"length ps \\<ge> 2\"\n  assumes deriv: \"\\<And>x\\<^sub>0. poly p x\\<^sub>0 = 0 \\<Longrightarrow>\n      eventually (\\<lambda>x. sgn (poly (p * ps!1) x) =\n                      (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\n  assumes p_squarefree: \"\\<And>x. \\<not>(poly p x = 0 \\<and> poly (ps!1) x = 0)\"\nbegin\n\n  text \\<open>\n    Any Sturm sequence is obviously a Quasi-Sturm sequence.\n\\<close>\n  lemma quasi_sturm_seq: \"quasi_sturm_seq ps\" ..\n\n(*<*)\n  lemma ps_first_two:\n    obtains q ps' where \"ps = p # q # ps'\"\n    using hd_ps_p length_ps_ge_2\n      by (cases ps, simp, clarsimp, rename_tac ps', case_tac ps', auto)\n\n  lemma ps_first: \"ps ! 0 = p\" by (rule ps_first_two, simp)\n\n  \n\n(*<*)\nlemma [simp]: \"\\<not>quasi_sturm_seq []\" by (simp add: quasi_sturm_seq_def)\n(*>*)\n\ntext \\<open>\n  Any suffix of a Quasi-Sturm sequence is again a Quasi-Sturm sequence.\n\\<close>\n\nlemma quasi_sturm_seq_Cons:\n  assumes \"quasi_sturm_seq (p#ps)\" and \"ps \\<noteq> []\"\n  shows \"quasi_sturm_seq ps\"\nproof (unfold_locales)\n  show \"ps \\<noteq> []\" by fact\nnext\n  from assms(1) interpret quasi_sturm_seq \"p#ps\" .\n  fix x y\n  from last_ps_sgn_const and \\<open>ps \\<noteq> []\\<close>\n      show \"sgn (poly (last ps) x) = sgn (poly (last ps) y)\" by simp_all\nnext\n  from assms(1) interpret quasi_sturm_seq \"p#ps\" .\n  fix i x\n  assume \"i < length ps - 2\" and \"poly (ps ! (i+1)) x = 0\"\n  with signs[of \"i+1\"]\n      show \"poly (ps ! (i+2)) x * poly (ps ! i) x < 0\" by simp\nqed\n\n\n\nsubsection \\<open>Auxiliary lemmas about roots and sign changes\\<close>\n\nlemma sturm_adjacent_root_aux:\n  assumes \"i < length (ps :: real poly list) - 1\"\n  assumes \"poly (ps ! i) x = 0\" and \"poly (ps ! (i + 1)) x = 0\"\n  assumes \"\\<And>i x. \\<lbrakk>i < length ps - 2; poly (ps ! (i+1)) x = 0\\<rbrakk>\n                   \\<Longrightarrow> sgn (poly (ps ! (i+2)) x) = - sgn (poly (ps ! i) x)\"\n  shows \"\\<forall>j\\<le>i+1. poly (ps ! j) x = 0\"\nusing assms\nproof (induction i)\n  case 0 thus ?case by (clarsimp, rename_tac j, case_tac j, simp_all)\nnext\n  case (Suc i)\n    from Suc.prems(1,2)\n        have \"sgn (poly (ps ! (i + 2)) x) = - sgn (poly (ps ! i) x)\"\n        by (intro assms(4)) simp_all\n    with Suc.prems(3) have \"poly (ps ! i) x = 0\" by (simp add: sgn_zero_iff)\n    with Suc.prems have \"\\<forall>j\\<le>i+1. poly (ps ! j) x = 0\"\n        by (intro Suc.IH, simp_all)\n    with Suc.prems(3) show ?case\n      by (clarsimp, rename_tac j, case_tac \"j = Suc (Suc i)\", simp_all)\nqed\n\n\ntext \\<open>\n  This function splits the sign list of a Sturm sequence at a\n  position @{term x} that is not a root of @{term p} into a\n  list of sublists such that the number of sign changes within\n  every sublist is constant in the neighbourhood of @{term x},\n  thus proving that the total number is also constant.\n\\<close>\nfun split_sign_changes where\n\"split_sign_changes [p] (x :: real) = [[p]]\" |\n\"split_sign_changes [p,q] x = [[p,q]]\" |\n\"split_sign_changes (p#q#r#ps) x =\n    (if poly p x \\<noteq> 0 \\<and> poly q x = 0 then\n       [p,q,r] # split_sign_changes (r#ps) x\n     else\n       [p,q] # split_sign_changes (q#r#ps) x)\"\n\nlemma (in quasi_sturm_seq) split_sign_changes_subset[dest]:\n  \"ps' \\<in> set (split_sign_changes ps x) \\<Longrightarrow> set ps' \\<subseteq> set ps\"\napply (insert ps_not_Nil)\napply (induction ps x rule: split_sign_changes.induct)\napply (simp, simp, rename_tac p q r ps x,\n       case_tac \"poly p x \\<noteq> 0 \\<and> poly q x = 0\", auto)\ndone\n\ntext \\<open>\n  A custom induction rule for @{term split_sign_changes} that\n  uses the fact that all the intermediate parameters in calls\n  of @{term split_sign_changes} are quasi-Sturm sequences.\n\\<close>\nlemma (in quasi_sturm_seq) split_sign_changes_induct:\n  \"\\<lbrakk>\\<And>p x. P [p] x; \\<And>p q x. quasi_sturm_seq [p,q] \\<Longrightarrow> P [p,q] x;\n    \\<And>p q r ps x. quasi_sturm_seq (p#q#r#ps) \\<Longrightarrow>\n       \\<lbrakk>poly p x \\<noteq> 0 \\<Longrightarrow> poly q x = 0 \\<Longrightarrow> P (r#ps) x;\n        poly q x \\<noteq> 0 \\<Longrightarrow> P (q#r#ps) x;\n        poly p x = 0 \\<Longrightarrow> P (q#r#ps) x\\<rbrakk>\n           \\<Longrightarrow> P (p#q#r#ps) x\\<rbrakk> \\<Longrightarrow> P ps x\"\nproof goal_cases\n  case prems: 1\n  have \"quasi_sturm_seq ps\" ..\n  with prems show ?thesis\n  proof (induction ps x rule: split_sign_changes.induct)\n    case (3 p q r ps x)\n      show ?case\n      proof (rule 3(5)[OF 3(6)])\n        assume A: \"poly p x \\<noteq> 0\" \"poly q x = 0\"\n        from 3(6) have \"quasi_sturm_seq (r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with 3 A show \"P (r # ps) x\" by blast\n      next\n        assume A: \"poly q x \\<noteq> 0\"\n        from 3(6) have \"quasi_sturm_seq (q#r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with 3 A show \"P (q # r # ps) x\" by blast\n      next\n        assume A: \"poly p x = 0\"\n        from 3(6) have \"quasi_sturm_seq (q#r#ps)\"\n            by (force dest: quasi_sturm_seq_Cons)\n        with 3 A show \"P (q # r # ps) x\" by blast\n      qed\n  qed simp_all\nqed\n\ntext \\<open>\n  The total number of sign changes in the split list is the same\n  as the number of sign changes in the original list.\n\\<close>\nlemma (in quasi_sturm_seq) split_sign_changes_correct:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  defines \"sign_changes' \\<equiv> \\<lambda>ps x.\n               \\<Sum>ps'\\<leftarrow>split_sign_changes ps x. sign_changes ps' x\"\n  shows \"sign_changes' ps x\\<^sub>0 = sign_changes ps x\\<^sub>0\"\nusing assms(1)\nproof (induction x\\<^sub>0 rule: split_sign_changes_induct)\ncase (3 p q r ps x\\<^sub>0)\n  hence \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n  note IH = 3(2,3,4)\n  show ?case\n  proof (cases \"poly q x\\<^sub>0 = 0\")\n    case True\n      from 3 interpret quasi_sturm_seq \"p#q#r#ps\" by simp\n      from signs[of 0] and True have\n           sgn_r_x0: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n      with 3 have \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n      from sign_changes_distrib[OF this, of \"[p,q]\" ps]\n        have \"sign_changes (p#q#r#ps) x\\<^sub>0 =\n                  sign_changes ([p, q, r]) x\\<^sub>0 + sign_changes (r # ps) x\\<^sub>0\" by simp\n      also have \"sign_changes (r#ps) x\\<^sub>0 = sign_changes' (r#ps) x\\<^sub>0\"\n          using \\<open>poly q x\\<^sub>0 = 0\\<close> \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\\<open>poly r x\\<^sub>0 \\<noteq> 0\\<close>\n          by (intro IH(1)[symmetric], simp_all)\n      finally show ?thesis unfolding sign_changes'_def\n          using True \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> by simp\n  next\n    case False\n      from sign_changes_distrib[OF this, of \"[p]\" \"r#ps\"]\n          have \"sign_changes (p#q#r#ps) x\\<^sub>0 =\n                  sign_changes ([p,q]) x\\<^sub>0 + sign_changes (q#r#ps) x\\<^sub>0\" by simp\n      also have \"sign_changes (q#r#ps) x\\<^sub>0 = sign_changes' (q#r#ps) x\\<^sub>0\"\n          using \\<open>poly q x\\<^sub>0 \\<noteq> 0\\<close> \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\n          by (intro IH(2)[symmetric], simp_all)\n      finally show ?thesis unfolding sign_changes'_def\n          using False by simp\n    qed\nqed (simp_all add: sign_changes_def sign_changes'_def)\n\n\ntext \\<open>\n  We now prove that if $p(x)\\neq 0$, the number of sign changes of a Sturm sequence of $p$\n  at $x$ is constant in a neighbourhood of $x$.\n\\<close>\n\nlemma (in quasi_sturm_seq) split_sign_changes_correct_nbh:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  defines \"sign_changes' \\<equiv> \\<lambda>x\\<^sub>0 ps x.\n               \\<Sum>ps'\\<leftarrow>split_sign_changes ps x\\<^sub>0. sign_changes ps' x\"\n  shows \"eventually (\\<lambda>x. sign_changes' x\\<^sub>0 ps x = sign_changes ps x) (at x\\<^sub>0)\"\nproof (rule eventually_mono)\n  show \"eventually (\\<lambda>x. \\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\"\n      by (rule eventually_ball_finite, auto intro: poly_neighbourhood_same_sign)\nnext\n  fix x\n  show \"(\\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)) \\<Longrightarrow>\n        sign_changes' x\\<^sub>0 ps x = sign_changes ps x\"\n  proof -\n    fix x assume nbh: \"\\<forall>p\\<in>{p \\<in> set ps. poly p x\\<^sub>0 \\<noteq> 0}. sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n    thus \"sign_changes' x\\<^sub>0 ps x = sign_changes ps x\" using assms(1)\n    proof (induction x\\<^sub>0 rule: split_sign_changes_induct)\n    case (3 p q r ps x\\<^sub>0)\n      hence \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n      note IH = 3(2,3,4)\n      show ?case\n      proof (cases \"poly q x\\<^sub>0 = 0\")\n        case True\n          from 3 interpret quasi_sturm_seq \"p#q#r#ps\" by simp\n          from signs[of 0] and True have\n               sgn_r_x0: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n          with 3 have \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n          with nbh 3(5) have \"poly r x \\<noteq> 0\" by (auto simp: sgn_zero_iff)\n          from sign_changes_distrib[OF this, of \"[p,q]\" ps]\n            have \"sign_changes (p#q#r#ps) x =\n                      sign_changes ([p, q, r]) x + sign_changes (r # ps) x\" by simp\n          also have \"sign_changes (r#ps) x = sign_changes' x\\<^sub>0 (r#ps) x\"\n              using \\<open>poly q x\\<^sub>0 = 0\\<close> nbh \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\\<open>poly r x\\<^sub>0 \\<noteq> 0\\<close>\n              by (intro IH(1)[symmetric], simp_all)\n          finally show ?thesis unfolding sign_changes'_def\n              using True \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close>by simp\n      next\n        case False\n          with nbh 3(5) have \"poly q x \\<noteq> 0\" by (auto simp: sgn_zero_iff)\n          from sign_changes_distrib[OF this, of \"[p]\" \"r#ps\"]\n              have \"sign_changes (p#q#r#ps) x =\n                      sign_changes ([p,q]) x + sign_changes (q#r#ps) x\" by simp\n          also have \"sign_changes (q#r#ps) x = sign_changes' x\\<^sub>0 (q#r#ps) x\"\n              using \\<open>poly q x\\<^sub>0 \\<noteq> 0\\<close> nbh \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> 3(5)\n              by (intro IH(2)[symmetric], simp_all)\n          finally show ?thesis unfolding sign_changes'_def\n              using False by simp\n        qed\n    qed (simp_all add: sign_changes_def sign_changes'_def)\n  qed\nqed\n\n\n\nlemma (in quasi_sturm_seq) hd_nonzero_imp_sign_changes_const_aux:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\" and \"ps' \\<in> set (split_sign_changes ps x\\<^sub>0)\"\n  shows \"eventually (\\<lambda>x. sign_changes ps' x = sign_changes ps' x\\<^sub>0) (at x\\<^sub>0)\"\nusing assms\nproof (induction x\\<^sub>0 rule: split_sign_changes_induct)\n  case (1 p x)\n    thus ?case by (simp add: sign_changes_def)\nnext\n  case (2 p q x\\<^sub>0)\n    hence [simp]: \"ps' = [p,q]\" by simp\n    from 2 have \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n    from 2(1) interpret quasi_sturm_seq \"[p,q]\" .\n    from poly_neighbourhood_same_sign[OF \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close>]\n        have \"eventually (\\<lambda>x. sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\" .\n    moreover from last_ps_sgn_const\n        have sgn_q: \"\\<And>x. sgn (poly q x) = sgn (poly q x\\<^sub>0)\" by simp\n    ultimately have A:  \"eventually (\\<lambda>x. \\<forall>p\\<in>set[p,q]. sgn (poly p x) =\n                           sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\" by simp\n    thus ?case by (force intro: eventually_mono[OF A]\n                                sign_changes_cong')\nnext\n  case (3 p q r ps'' x\\<^sub>0)\n    hence p_not_0: \"poly p x\\<^sub>0 \\<noteq> 0\" by simp\n    note sturm = 3(1)\n    note IH = 3(2,3)\n    note ps''_props = 3(6)\n    show ?case\n    proof (cases \"poly q x\\<^sub>0 = 0\")\n      case True\n        note q_0 = this\n        from sturm interpret quasi_sturm_seq \"p#q#r#ps''\" .\n        from signs[of 0] and q_0\n            have signs': \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n        with p_not_0 have r_not_0: \"poly r x\\<^sub>0 \\<noteq> 0\" by force\n        show ?thesis\n        proof (cases \"ps' \\<in> set (split_sign_changes (r # ps'') x\\<^sub>0)\")\n          case True\n            show ?thesis by (rule IH(1), fact, fact, simp add: r_not_0, fact)\n        next\n          case False\n            with ps''_props p_not_0 q_0 have ps'_props: \"ps' = [p,q,r]\" by simp\n            from signs[of 0] and q_0\n                have sgn_r: \"poly r x\\<^sub>0 * poly p x\\<^sub>0 < 0\" by simp\n            from p_not_0 sgn_r\n              have A: \"eventually (\\<lambda>x. sgn (poly p x) = sgn (poly p x\\<^sub>0) \\<and>\n                                     sgn (poly r x) = sgn (poly r x\\<^sub>0)) (at x\\<^sub>0)\"\n                  by (intro eventually_conj poly_neighbourhood_same_sign,\n                      simp_all add: r_not_0)\n            show ?thesis\n            proof (rule eventually_mono[OF A], clarify,\n                   subst ps'_props, subst sign_changes_sturm_triple)\n              fix x assume A: \"sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n                       and B: \"sgn (poly r x) = sgn (poly r x\\<^sub>0)\"\n              have prod_neg: \"\\<And>a (b::real). \\<lbrakk>a>0; b>0; a*b<0\\<rbrakk> \\<Longrightarrow> False\"\n                             \"\\<And>a (b::real). \\<lbrakk>a<0; b<0; a*b<0\\<rbrakk> \\<Longrightarrow> False\"\n                  by (drule mult_pos_pos, simp, simp,\n                      drule mult_neg_neg, simp, simp)\n              from A and \\<open>poly p x\\<^sub>0 \\<noteq> 0\\<close> show \"poly p x \\<noteq> 0\"\n                  by (force simp: sgn_zero_iff)\n\n              with sgn_r p_not_0 r_not_0 A B\n                  have \"poly r x * poly p x < 0\" \"poly r x \\<noteq> 0\"\n                  by (metis sgn_less sgn_mult, metis sgn_0_0)\n              with sgn_r show sgn_r': \"sgn (poly r x) = - sgn (poly p x)\"\n                  apply (simp add: sgn_real_def not_le not_less\n                             split: if_split_asm, intro conjI impI)\n                  using prod_neg[of \"poly r x\" \"poly p x\"] apply force+\n                  done\n\n              show \"1 = sign_changes ps' x\\<^sub>0\"\n                  by (subst ps'_props, subst sign_changes_sturm_triple,\n                      fact, metis A B sgn_r', simp)\n            qed\n        qed\n    next\n      case False\n        note q_not_0 = this\n        show ?thesis\n        proof (cases \"ps' \\<in> set (split_sign_changes (q # r # ps'') x\\<^sub>0)\")\n          case True\n            show ?thesis by (rule IH(2), fact, simp add: q_not_0, fact)\n        next\n          case False\n            with ps''_props and q_not_0 have \"ps' = [p, q]\" by simp\n            hence [simp]: \"\\<forall>p\\<in>set ps'. poly p x\\<^sub>0 \\<noteq> 0\"\n                using q_not_0 p_not_0 by simp\n            show ?thesis\n            proof (rule eventually_mono)\n              fix x assume \"\\<forall>p\\<in>set ps'. sgn (poly p x) = sgn (poly p x\\<^sub>0)\"\n              thus \"sign_changes ps' x = sign_changes ps' x\\<^sub>0\"\n                  by (rule sign_changes_cong')\n            next\n              show \"eventually (\\<lambda>x. \\<forall>p\\<in>set ps'.\n                        sgn (poly p x) = sgn (poly p x\\<^sub>0)) (at x\\<^sub>0)\"\n                  by (force intro: eventually_ball_finite\n                                   poly_neighbourhood_same_sign)\n            qed\n    qed\n  qed\nqed\n\n\nlemma (in quasi_sturm_seq) hd_nonzero_imp_sign_changes_const:\n  assumes \"poly (hd ps) x\\<^sub>0 \\<noteq> 0\"\n  shows \"eventually (\\<lambda>x. sign_changes ps x = sign_changes ps x\\<^sub>0) (at x\\<^sub>0)\"\nproof-\n  let ?pss = \"split_sign_changes ps x\\<^sub>0\"\n  let ?f = \"\\<lambda>pss x. \\<Sum>ps'\\<leftarrow>pss. sign_changes ps' x\"\n  {\n    fix pss assume \"\\<And>ps'. ps'\\<in>set pss \\<Longrightarrow>\n        eventually (\\<lambda>x. sign_changes ps' x = sign_changes ps' x\\<^sub>0) (at x\\<^sub>0)\"\n    hence \"eventually (\\<lambda>x. ?f pss x = ?f pss x\\<^sub>0) (at x\\<^sub>0)\"\n    proof (induction pss)\n      case (Cons ps' pss)\n      then show ?case\n        apply (rule eventually_mono[OF eventually_conj])\n        apply (auto simp add: Cons.prems)\n        done\n    qed simp\n  }\n  note A = this[of ?pss]\n  have B: \"eventually (\\<lambda>x. ?f ?pss x = ?f ?pss x\\<^sub>0) (at x\\<^sub>0)\"\n      by (rule A, rule hd_nonzero_imp_sign_changes_const_aux[OF assms], simp)\n  note C = split_sign_changes_correct_nbh[OF assms]\n  note D = split_sign_changes_correct[OF assms]\n  note E = eventually_conj[OF B C]\n  show ?thesis by (rule eventually_mono[OF E], auto simp: D)\nqed\n\n(*<*)\nhide_fact quasi_sturm_seq.split_sign_changes_correct_nbh\nhide_fact quasi_sturm_seq.hd_nonzero_imp_sign_changes_const_aux\n(*>*)\n\nlemma (in sturm_seq) p_nonzero_imp_sign_changes_const:\n  \"poly p x\\<^sub>0 \\<noteq> 0 \\<Longrightarrow>\n       eventually (\\<lambda>x. sign_changes ps x = sign_changes ps x\\<^sub>0) (at x\\<^sub>0)\"\n  using hd_nonzero_imp_sign_changes_const by simp\n\n\ntext \\<open>\n  If $x$ is a root of $p$ and $p$ is not the zero polynomial, the\n  number of sign changes of a Sturm chain of $p$ decreases by 1 at $x$.\n\\<close>\nlemma (in sturm_seq) p_zero:\n  assumes \"poly p x\\<^sub>0 = 0\" \"p \\<noteq> 0\"\n  shows \"eventually (\\<lambda>x. sign_changes ps x =\n      sign_changes ps x\\<^sub>0 + (if x<x\\<^sub>0 then 1 else 0)) (at x\\<^sub>0)\"\nproof-\n  from ps_first_two obtain q ps' where [simp]: \"ps = p#q#ps'\" .\n  hence \"ps!1 = q\" by simp\n  have \"eventually (\\<lambda>x. x \\<noteq> x\\<^sub>0) (at x\\<^sub>0)\"\n      by (simp add: eventually_at, rule exI[of _ 1], simp)\n  moreover from p_squarefree and assms(1) have \"poly q x\\<^sub>0 \\<noteq> 0\" by simp\n  {\n      have A: \"quasi_sturm_seq ps\" ..\n      with quasi_sturm_seq_Cons[of p \"q#ps'\"]\n          interpret quasi_sturm_seq \"q#ps'\" by simp\n      from \\<open>poly q x\\<^sub>0 \\<noteq> 0\\<close> have \"eventually (\\<lambda>x. sign_changes (q#ps') x =\n                                     sign_changes (q#ps') x\\<^sub>0) (at x\\<^sub>0)\"\n      using hd_nonzero_imp_sign_changes_const[where x\\<^sub>0=x\\<^sub>0] by simp\n  }\n  moreover note poly_neighbourhood_without_roots[OF assms(2)] deriv[OF assms(1)]\n  ultimately\n      have A: \"eventually (\\<lambda>x. x \\<noteq> x\\<^sub>0 \\<and> poly p x \\<noteq> 0 \\<and>\n                   sgn (poly (p*ps!1) x) = (if x > x\\<^sub>0 then 1 else -1) \\<and>\n                   sign_changes (q#ps') x = sign_changes (q#ps') x\\<^sub>0) (at x\\<^sub>0)\"\n           by (simp only: \\<open>ps!1 = q\\<close>, intro eventually_conj)\n  show ?thesis\n  proof (rule eventually_mono[OF A], clarify, goal_cases)\n    case prems: (1 x)\n    from zero_less_mult_pos have zero_less_mult_pos':\n        \"\\<And>a b. \\<lbrakk>(0::real) < a*b; 0 < b\\<rbrakk> \\<Longrightarrow> 0 < a\"\n        by (subgoal_tac \"a*b = b*a\", auto)\n    from prems have \"poly q x \\<noteq> 0\" and q_sgn: \"sgn (poly q x) =\n              (if x < x\\<^sub>0 then -sgn (poly p x) else sgn (poly p x))\"\n        by (auto simp add: sgn_real_def elim: linorder_neqE_linordered_idom\n                 dest: mult_neg_neg zero_less_mult_pos\n                 zero_less_mult_pos' split: if_split_asm)\n     from sign_changes_distrib[OF \\<open>poly q x \\<noteq> 0\\<close>, of \"[p]\" ps']\n        have \"sign_changes ps x = sign_changes [p,q] x + sign_changes (q#ps') x\"\n            by simp\n    also from q_sgn and \\<open>poly p x \\<noteq> 0\\<close>\n        have \"sign_changes [p,q] x = (if x<x\\<^sub>0 then 1 else 0)\"\n        by (simp add: sign_changes_def sgn_zero_iff split: if_split_asm)\n    also note prems(4)\n    also from assms(1) have \"sign_changes (q#ps') x\\<^sub>0 = sign_changes ps x\\<^sub>0\"\n        by (simp add: sign_changes_def)\n    finally show ?case by simp\n  qed\nqed\n\ntext \\<open>\n  With these two results, we can now show that if $p$ is nonzero, the number\n  of roots in an interval of the form $(a;b]$ is the difference of the sign changes\n  of a Sturm sequence of $p$ at $a$ and $b$.\\\\\n  First, however, we prove the following auxiliary lemma that shows that\n  if a function $f: \\RR\\to\\NN$ is locally constant at any $x\\in(a;b]$, it is constant\n  across the entire interval $(a;b]$:\n\\<close>\n\nlemma count_roots_between_aux:\n  assumes \"a \\<le> b\"\n  assumes \"\\<forall>x::real. a < x \\<and> x \\<le> b \\<longrightarrow> eventually (\\<lambda>\\<xi>. f \\<xi> = (f x::nat)) (at x)\"\n  shows \"\\<forall>x. a < x \\<and> x \\<le> b \\<longrightarrow> f x = f b\"\nproof (clarify)\n  fix x assume \"x > a\" \"x \\<le> b\"\n  with assms have \"\\<forall>x'. x \\<le> x' \\<and> x' \\<le> b \\<longrightarrow>\n                       eventually (\\<lambda>\\<xi>. f \\<xi> = f x') (at x')\" by auto\n  from fun_eq_in_ivl[OF \\<open>x \\<le> b\\<close> this] show \"f x = f b\" .\nqed\n\ntext \\<open>\n  Now we can prove the actual root-counting theorem:\n\\<close>\n\n\n              show \"sign_changes ps a = sign_changes ps b\"\n              proof (cases \"a = b\")\n                case False\n                  define x where \"x = min (a+\\<delta>/2) b\"\n                  with False have \"a < x\" \"x < a+\\<delta>\" \"x \\<le> b\"\n                     using \\<open>\\<delta> > 0\\<close> \\<open>a \\<le> b\\<close> by simp_all\n                  from \\<delta>_props \\<open>a < x\\<close> \\<open>x < a+\\<delta>\\<close>\n                      have \"sign_changes ps a = sign_changes ps x\" by simp\n                  also from A \\<open>a < x\\<close> \\<open>x \\<le> b\\<close> have \"... = sign_changes ps b\"\n                      by blast\n                  finally show ?thesis .\n              qed simp\n          qed\n\n      next\n        case True\n          from poly_roots_finite[OF assms(1)]\n            have fin: \"finite {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0}\"\n            by (force intro: finite_subset)\n          from True have \"{x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} \\<noteq> {}\" by blast\n          with fin have card_greater_0:\n              \"card {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} > 0\" by fastforce\n\n          define x\\<^sub>2 where \"x\\<^sub>2 = Min {x. x > a \\<and> x \\<le> b \\<and> poly p x = 0}\"\n          from Min_in[OF fin] and True\n              have x\\<^sub>2_props: \"x\\<^sub>2 > a\" \"x\\<^sub>2 \\<le> b\" \"poly p x\\<^sub>2 = 0\"\n              unfolding x\\<^sub>2_def by blast+\n          from Min_le[OF fin] x\\<^sub>2_props\n              have x\\<^sub>2_le: \"\\<And>x'. \\<lbrakk>x' > a; x' \\<le> b; poly p x' = 0\\<rbrakk> \\<Longrightarrow> x\\<^sub>2 \\<le> x'\"\n              unfolding x\\<^sub>2_def by simp\n\n          have left: \"{x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} = {x\\<^sub>2}\"\n              using x\\<^sub>2_props x\\<^sub>2_le by force\n          hence [simp]: \"card {x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} = 1\" by simp\n\n          from p_zero[OF \\<open>poly p x\\<^sub>2 = 0\\<close> \\<open>p \\<noteq> 0\\<close>,\n              unfolded eventually_at dist_real_def] guess \\<epsilon> ..\n          hence \\<epsilon>_props: \"\\<epsilon> > 0\"\n              \"\\<forall>x. x \\<noteq> x\\<^sub>2 \\<and> \\<bar>x - x\\<^sub>2\\<bar> < \\<epsilon> \\<longrightarrow>\n                   sign_changes ps x = sign_changes ps x\\<^sub>2 +\n                       (if x < x\\<^sub>2 then 1 else 0)\" by auto\n          define x\\<^sub>1 where \"x\\<^sub>1 = max (x\\<^sub>2 - \\<epsilon> / 2) a\"\n          have \"\\<bar>x\\<^sub>1 - x\\<^sub>2\\<bar> < \\<epsilon>\" using \\<open>\\<epsilon> > 0\\<close> x\\<^sub>2_props by (simp add: x\\<^sub>1_def)\n          hence \"sign_changes ps x\\<^sub>1 =\n              (if x\\<^sub>1 < x\\<^sub>2 then sign_changes ps x\\<^sub>2 + 1 else sign_changes ps x\\<^sub>2)\"\n              using \\<epsilon>_props(2) by (cases \"x\\<^sub>1 = x\\<^sub>2\", auto)\n          hence \"sign_changes ps x\\<^sub>1 - sign_changes ps x\\<^sub>2 = 1\"\n              unfolding x\\<^sub>1_def using x\\<^sub>2_props \\<open>\\<epsilon> > 0\\<close> by simp\n\n          also have \"x\\<^sub>2 \\<notin> {x. a < x \\<and> x \\<le> x\\<^sub>1 \\<and> poly p x = 0}\"\n              unfolding x\\<^sub>1_def using \\<open>\\<epsilon> > 0\\<close> by force\n          with left have \"{x. a < x \\<and> x \\<le> x\\<^sub>1 \\<and> poly p x = 0} = {}\" by force\n          with less(1)[of a x\\<^sub>1] have \"sign_changes ps x\\<^sub>1 = sign_changes ps a\"\n              unfolding x\\<^sub>1_def \\<open>\\<epsilon> > 0\\<close> by (force simp: card_greater_0)\n\n          finally have signs_left:\n              \"sign_changes ps a - int (sign_changes ps x\\<^sub>2) = 1\" by simp\n\n          have \"{x. x > a \\<and> x \\<le> b \\<and> poly p x = 0} =\n                {x. a < x \\<and> x \\<le> x\\<^sub>2 \\<and> poly p x = 0} \\<union>\n                {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0}\" using x\\<^sub>2_props by auto\n          also note left\n          finally have A: \"card {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0} + 1 =\n              card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" using fin by simp\n          hence \"card {x. x\\<^sub>2 < x \\<and> x \\<le> b \\<and> poly p x = 0} <\n                 card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by simp\n          from less(1)[OF this x\\<^sub>2_props(2)] and A\n              have signs_right: \"sign_changes ps x\\<^sub>2 - int (sign_changes ps b) + 1 =\n                  card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by simp\n\n          from signs_left and signs_right show ?thesis by simp\n        qed\n  qed\n  thus ?thesis by simp\nqed\n\ntext \\<open>\n  By applying this result to a sufficiently large upper bound, we can effectively count\n  the number of roots ``between $a$ and infinity'', i.\\,e. the roots greater than $a$:\n\\<close>\nlemma (in sturm_seq) count_roots_above:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes ps a - sign_changes_inf ps =\n             card {x. x > a \\<and> poly p x = 0}\"\nproof-\n  have \"p \\<in> set ps\" using hd_in_set[OF ps_not_Nil] by simp\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n  let ?u = \"max a u\"\n  {fix x assume \"poly p x = 0\" hence \"x \\<le> ?u\"\n   using lu_props(3)[OF \\<open>p \\<in> set ps\\<close>, of x] \\<open>p \\<noteq> 0\\<close>\n       by (cases \"u \\<le> x\", auto simp: sgn_zero_iff)\n  } note [simp] = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p ?u)) ps = map poly_inf ps\" by simp\n  hence \"sign_changes ps a - sign_changes_inf ps =\n             sign_changes ps a - sign_changes ps ?u\"\n      by (simp_all only: sign_changes_def sign_changes_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. a < x \\<and> x \\<le> ?u \\<and> poly p x = 0}\" by simp\n  also have \"{x. a < x \\<and> x \\<le> ?u \\<and> poly p x = 0} = {x. a < x \\<and> poly p x = 0}\"\n      using lu_props by auto\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The same works analogously for the number of roots below $a$ and the\n  total number of roots.\n\\<close>\n\nlemma (in sturm_seq) count_roots_below:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes_neg_inf ps - sign_changes ps a =\n             card {x. x \\<le> a \\<and> poly p x = 0}\"\nproof-\n  have \"p \\<in> set ps\" using hd_in_set[OF ps_not_Nil] by simp\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n  let ?l = \"min a l\"\n  {fix x assume \"poly p x = 0\" hence \"x > ?l\"\n   using lu_props(4)[OF \\<open>p \\<in> set ps\\<close>, of x] \\<open>p \\<noteq> 0\\<close>\n       by (cases \"l < x\", auto simp: sgn_zero_iff)\n  } note [simp] = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p ?l)) ps = map poly_neg_inf ps\" by simp\n  hence \"sign_changes_neg_inf ps - sign_changes ps a =\n             sign_changes ps ?l - sign_changes ps a\"\n      by (simp_all only: sign_changes_def sign_changes_neg_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. ?l < x \\<and> x \\<le> a \\<and> poly p x = 0}\" by simp\n  also have \"{x. ?l < x \\<and> x \\<le> a \\<and> poly p x = 0} = {x. a \\<ge> x \\<and> poly p x = 0}\"\n      using lu_props by auto\n  finally show ?thesis .\nqed\n\nlemma (in sturm_seq) count_roots:\n  assumes \"p \\<noteq> 0\"\n  shows \"sign_changes_neg_inf ps - sign_changes_inf ps =\n             card {x. poly p x = 0}\"\nproof-\n  have \"finite (set ps)\" by simp\n  from polys_inf_sign_thresholds[OF this] guess l u .\n  note lu_props = this\n\n  from lu_props\n    have \"map (\\<lambda>p. sgn (poly p l)) ps = map poly_neg_inf ps\"\n         \"map (\\<lambda>p. sgn (poly p u)) ps = map poly_inf ps\" by simp_all\n  hence \"sign_changes_neg_inf ps - sign_changes_inf ps =\n             sign_changes ps l - sign_changes ps u\"\n      by (simp_all only: sign_changes_def sign_changes_inf_def\n                         sign_changes_neg_inf_def)\n  also from count_roots_between[OF assms] lu_props\n      have \"... =  card {x. l < x \\<and> x \\<le> u \\<and> poly p x = 0}\" by simp\n  also have \"{x. l < x \\<and> x \\<le> u \\<and> poly p x = 0} = {x. poly p x = 0}\"\n      using lu_props assms by simp\n  finally show ?thesis .\nqed\n\n\n\nsubsection \\<open>Constructing Sturm sequences\\<close>\n\nsubsection \\<open>The canonical Sturm sequence\\<close>\n\ntext \\<open>\n  In this subsection, we will present the canonical Sturm sequence construction for\n  a polynomial $p$ without multiple roots that is very similar to the Euclidean\n  algorithm:\n  $$p_i = \\begin{cases}\n    p & \\text{for}\\ i = 1\\\\\n    p' & \\text{for}\\ i = 2\\\\\n    -p_{i-2}\\ \\text{mod}\\ p_{i-1} & \\text{otherwise}\n  \\end{cases}$$\n  We break off the sequence at the first constant polynomial.\n\\<close>\n\n(*<*)\nlemma degree_mod_less': \"degree q \\<noteq> 0 \\<Longrightarrow> degree (p mod q) < degree q\"\n  by (metis degree_0 degree_mod_less not_gr0)\n(*>*)\n\nfunction sturm_aux where\n\"sturm_aux (p :: real poly) q =\n    (if degree q = 0 then [p,q] else p # sturm_aux q (-(p mod q)))\"\n  by (pat_completeness, simp_all)\ntermination by (relation \"measure (degree \\<circ> snd)\",\n                simp_all add: o_def degree_mod_less')\n\n(*<*)\ndeclare sturm_aux.simps[simp del]\n(*>*)\n\ndefinition sturm where \"sturm p = sturm_aux p (pderiv p)\"\n\ntext \\<open>Next, we show some simple facts about this construction:\\<close>\n\nlemma sturm_0[simp]: \"sturm 0 = [0,0]\"\n    by (unfold sturm_def, subst sturm_aux.simps, simp)\n\nlemma [simp]: \"sturm_aux p q = [] \\<longleftrightarrow> False\"\n    by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, auto)\n\nlemma sturm_neq_Nil[simp]: \"sturm p \\<noteq> []\" unfolding sturm_def by simp\n\nlemma [simp]: \"hd (sturm p) = p\"\n  unfolding sturm_def by (subst sturm_aux.simps, simp)\n\nlemma [simp]: \"p \\<in> set (sturm p)\"\n  using hd_in_set[OF sturm_neq_Nil] by simp\n\nlemma [simp]: \"length (sturm p) \\<ge> 2\"\nproof-\n  {fix q have \"length (sturm_aux p q) \\<ge> 2\"\n           by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, auto)\n  }\n  thus ?thesis unfolding sturm_def .\nqed\n\nlemma [simp]: \"degree (last (sturm p)) = 0\"\nproof-\n  {fix q have \"degree (last (sturm_aux p q)) = 0\"\n           by (induction p q rule: sturm_aux.induct, subst sturm_aux.simps, simp)\n  }\n  thus ?thesis unfolding sturm_def .\nqed\n\nlemma [simp]: \"sturm_aux p q ! 0 = p\"\n    by (subst sturm_aux.simps, simp)\nlemma [simp]: \"sturm_aux p q ! Suc 0 = q\"\n    by (subst sturm_aux.simps, simp)\n\nlemma [simp]: \"sturm p ! 0 = p\"\n    unfolding sturm_def by simp\nlemma [simp]: \"sturm p ! Suc 0 = pderiv p\"\n    unfolding sturm_def by simp\n\n\nlemma sturm_indices:\n  assumes \"i < length (sturm p) - 2\"\n  shows \"sturm p!(i+2) = -(sturm p!i mod sturm p!(i+1))\"\nproof-\n {fix ps q\n  have \"\\<lbrakk>ps = sturm_aux p q; i < length ps - 2\\<rbrakk>\n            \\<Longrightarrow> ps!(i+2) = -(ps!i mod ps!(i+1))\"\n  proof (induction p q arbitrary: ps i rule: sturm_aux.induct)\n    case (1 p q)\n      show ?case\n      proof (cases \"i = 0\")\n        case False\n          then obtain i' where [simp]: \"i = Suc i'\" by (cases i, simp_all)\n          hence \"length ps \\<ge> 4\" using 1 by simp\n          with 1(2) have deg: \"degree q \\<noteq> 0\"\n              by (subst (asm) sturm_aux.simps, simp split: if_split_asm)\n          with 1(2) obtain ps' where [simp]: \"ps = p # ps'\"\n              by (subst (asm) sturm_aux.simps, simp)\n          with 1(2) deg have ps': \"ps' = sturm_aux q (-(p mod q))\"\n              by (subst (asm) sturm_aux.simps, simp)\n          from \\<open>length ps \\<ge> 4\\<close> and \\<open>ps = p # ps'\\<close> 1(3) False\n              have \"i - 1 < length ps' - 2\" by simp\n          from 1(1)[OF deg ps' this]\n              show ?thesis by simp\n      next\n        case True\n          with 1(3) have \"length ps \\<ge> 3\" by simp\n          with 1(2) have \"degree q \\<noteq> 0\"\n              by (subst (asm) sturm_aux.simps, simp split: if_split_asm)\n          with 1(2) have [simp]: \"sturm_aux p q ! Suc (Suc 0) = -(p mod q)\"\n              by (subst sturm_aux.simps, simp)\n          from True have \"ps!i = p\" \"ps!(i+1) = q\" \"ps!(i+2) = -(p mod q)\"\n              by (simp_all add: 1(2))\n          thus ?thesis by simp\n      qed\n    qed}\n  from this[OF sturm_def assms] show ?thesis .\nqed\n\ntext \\<open>\n  If the Sturm sequence construction is applied to polynomials $p$ and $q$,\n  the greatest common divisor of $p$ and $q$ a divisor of every element in the\n  sequence. This is obvious from the similarity to Euclid's algorithm for\n  computing the GCD.\n\\<close>\n\nlemma sturm_aux_gcd: \"r \\<in> set (sturm_aux p q) \\<Longrightarrow> gcd p q dvd r\"\nproof (induction p q rule: sturm_aux.induct)\n  case (1 p q)\n    show ?case\n    proof (cases \"r = p\")\n      case False\n        with 1(2) have r: \"r \\<in> set (sturm_aux q (-(p mod q)))\"\n          by (subst (asm) sturm_aux.simps, simp split: if_split_asm,\n              subst sturm_aux.simps, simp)\n        show ?thesis\n        proof (cases \"degree q = 0\")\n          case False\n            hence \"q \\<noteq> 0\" by force\n            with 1(1) [OF False r] show ?thesis\n              by (simp add: gcd_mod_right ac_simps)\n        next\n          case True\n            with 1(2) and \\<open>r \\<noteq> p\\<close> have \"r = q\"\n                by (subst (asm) sturm_aux.simps, simp)\n            thus ?thesis by simp\n        qed\n    qed simp\nqed\n\nlemma sturm_gcd: \"r \\<in> set (sturm p) \\<Longrightarrow> gcd p (pderiv p) dvd r\"\n    unfolding sturm_def by (rule sturm_aux_gcd)\n\ntext \\<open>\n  If two adjacent polynomials in the result of the canonical Sturm chain construction\n  both have a root at some $x$, this $x$ is a root of all polynomials in the sequence.\n\\<close>\n\nlemma sturm_adjacent_root_propagate_left:\n  assumes \"i < length (sturm (p :: real poly)) - 1\"\n  assumes \"poly (sturm p ! i) x = 0\"\n      and \"poly (sturm p ! (i + 1)) x = 0\"\n  shows \"\\<forall>j\\<le>i+1. poly (sturm p ! j) x = 0\"\nusing assms(2)\nproof (intro sturm_adjacent_root_aux[OF assms(1,2,3)], goal_cases)\n  case prems: (1 i x)\n    let ?p = \"sturm p ! i\"\n    let ?q = \"sturm p ! (i + 1)\"\n    let ?r = \"sturm p ! (i + 2)\"\n    from sturm_indices[OF prems(2)] have \"?p = ?p div ?q * ?q - ?r\"\n        by (simp add: div_mult_mod_eq)\n    hence \"poly ?p x = poly (?p div ?q * ?q - ?r) x\" by simp\n    hence \"poly ?p x = -poly ?r x\" using prems(3) by simp\n    thus ?case by (simp add: sgn_minus)\nqed\n\ntext \\<open>\n  Consequently, if this is the case in the canonical Sturm chain of $p$,\n  $p$ must have multiple roots.\n\\<close>\nlemma sturm_adjacent_root_not_squarefree:\n  assumes \"i < length (sturm (p :: real poly)) - 1\"\n          \"poly (sturm p ! i) x = 0\" \"poly (sturm p ! (i + 1)) x = 0\"\n  shows \"\\<not>rsquarefree p\"\nproof-\n  from sturm_adjacent_root_propagate_left[OF assms]\n      have \"poly p x = 0\" \"poly (pderiv p) x = 0\" by auto\n  thus ?thesis by (auto simp: rsquarefree_roots)\nqed\n\n\ntext \\<open>\n  Since the second element of the sequence is chosen to be the derivative of $p$,\n  $p_1$ and $p_2$ fulfil the property demanded by the definition of a Sturm sequence\n  that they locally have opposite sign left of a root $x$ of $p$ and the same sign\n  to the right of $x$.\n\\<close>\n\nlemma sturm_firsttwo_signs_aux:\n  assumes \"(p :: real poly) \\<noteq> 0\" \"q \\<noteq> 0\"\n  assumes q_pderiv:\n      \"eventually (\\<lambda>x. sgn (poly q x) = sgn (poly (pderiv p) x)) (at x\\<^sub>0)\"\n  assumes p_0: \"poly p (x\\<^sub>0::real) = 0\"\n  shows \"eventually (\\<lambda>x. sgn (poly (p*q) x) = (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\nproof-\n  have A: \"eventually (\\<lambda>x. poly p x \\<noteq> 0 \\<and> poly q x \\<noteq> 0 \\<and>\n               sgn (poly q x) = sgn (poly (pderiv p) x)) (at x\\<^sub>0)\"\n      using \\<open>p \\<noteq> 0\\<close>  \\<open>q \\<noteq> 0\\<close>\n      by (intro poly_neighbourhood_same_sign q_pderiv\n                poly_neighbourhood_without_roots eventually_conj)\n  then obtain \\<epsilon> where \\<epsilon>_props: \"\\<epsilon> > 0\" \"\\<forall>x. x \\<noteq> x\\<^sub>0 \\<and> \\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon> \\<longrightarrow>\n      poly p x \\<noteq> 0 \\<and> poly q x \\<noteq> 0 \\<and> sgn (poly (pderiv p) x) = sgn (poly q x)\"\n      by (auto simp: eventually_at dist_real_def)\n  have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> sgn x * sgn x = 1\"\n      by (auto simp: sgn_real_def)\n\n  show ?thesis\n  proof (simp only: eventually_at dist_real_def, rule exI[of _ \\<epsilon>],\n         intro conjI, fact \\<open>\\<epsilon> > 0\\<close>, clarify)\n    fix x assume \"x \\<noteq> x\\<^sub>0\" \"\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\"\n    with \\<epsilon>_props have [simp]: \"poly p x \\<noteq> 0\" \"poly q x \\<noteq> 0\"\n        \"sgn (poly (pderiv p) x) = sgn (poly q x)\" by auto\n    show \"sgn (poly (p*q) x) = (if x > x\\<^sub>0 then 1 else -1)\"\n    proof (cases \"x \\<ge> x\\<^sub>0\")\n      case True\n        with \\<open>x \\<noteq> x\\<^sub>0\\<close> have \"x > x\\<^sub>0\" by simp\n        from poly_MVT[OF this, of p] guess \\<xi> ..\n        note \\<xi>_props = this\n        with \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close> \\<open>poly p x\\<^sub>0 = 0\\<close> \\<open>x > x\\<^sub>0\\<close> \\<epsilon>_props\n            have \"\\<bar>\\<xi> - x\\<^sub>0\\<bar> < \\<epsilon>\" \"sgn (poly p x) = sgn (x - x\\<^sub>0) * sgn (poly q \\<xi>)\"\n            by (auto simp add: q_pderiv sgn_mult)\n        moreover from \\<xi>_props \\<epsilon>_props \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close>\n            have \"\\<forall>t. \\<xi> \\<le> t \\<and> t \\<le> x \\<longrightarrow> poly q t \\<noteq> 0\" by auto\n        hence \"sgn (poly q \\<xi>) = sgn (poly q x)\" using \\<xi>_props \\<epsilon>_props\n            by (intro no_roots_inbetween_imp_same_sign, simp_all)\n        ultimately show ?thesis using True \\<open>x \\<noteq> x\\<^sub>0\\<close> \\<epsilon>_props \\<xi>_props\n            by (auto simp: sgn_mult sqr_pos)\n    next\n      case False\n        hence \"x < x\\<^sub>0\" by simp\n        hence sgn: \"sgn (x - x\\<^sub>0) = -1\" by simp\n        from poly_MVT[OF \\<open>x < x\\<^sub>0\\<close>, of p] guess \\<xi> ..\n        note \\<xi>_props = this\n        with \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close> \\<open>poly p x\\<^sub>0 = 0\\<close> \\<open>x < x\\<^sub>0\\<close> \\<epsilon>_props\n            have \"\\<bar>\\<xi> - x\\<^sub>0\\<bar> < \\<epsilon>\" \"poly p x = (x - x\\<^sub>0) * poly (pderiv p) \\<xi>\"\n                 \"poly p \\<xi> \\<noteq> 0\" by (auto simp: field_simps)\n        hence \"sgn (poly p x) = sgn (x - x\\<^sub>0) * sgn (poly q \\<xi>)\"\n            using \\<epsilon>_props \\<xi>_props by (auto simp: q_pderiv sgn_mult)\n        moreover from \\<xi>_props \\<epsilon>_props \\<open>\\<bar>x - x\\<^sub>0\\<bar> < \\<epsilon>\\<close>\n            have \"\\<forall>t. x \\<le> t \\<and> t \\<le> \\<xi> \\<longrightarrow> poly q t \\<noteq> 0\" by auto\n        hence \"sgn (poly q \\<xi>) = sgn (poly q x)\" using \\<xi>_props \\<epsilon>_props\n            by (rule_tac sym, intro no_roots_inbetween_imp_same_sign, simp_all)\n        ultimately show ?thesis using False \\<open>x \\<noteq> x\\<^sub>0\\<close>\n            by (auto simp: sgn_mult sqr_pos)\n    qed\n  qed\nqed\n\nlemma sturm_firsttwo_signs:\n  fixes ps :: \"real poly list\"\n  assumes squarefree: \"rsquarefree p\"\n  assumes p_0: \"poly p (x\\<^sub>0::real) = 0\"\n  shows \"eventually (\\<lambda>x. sgn (poly (p * sturm p ! 1) x) =\n             (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\"\nproof-\n  from assms have [simp]: \"p \\<noteq> 0\" by (auto simp add: rsquarefree_roots)\n  with squarefree p_0 have [simp]: \"pderiv p \\<noteq> 0\"\n      by (auto simp  add:rsquarefree_roots)\n  from assms show ?thesis\n      by (intro sturm_firsttwo_signs_aux,\n          simp_all add: rsquarefree_roots)\nqed\n\n\ntext \\<open>\n  The construction also obviously fulfils the property about three\n  adjacent polynomials in the sequence.\n\\<close>\n\nlemma sturm_signs:\n  assumes squarefree: \"rsquarefree p\"\n  assumes i_in_range: \"i < length (sturm (p :: real poly)) - 2\"\n  assumes q_0: \"poly (sturm p ! (i+1)) x = 0\" (is \"poly ?q x = 0\")\n  shows \"poly (sturm p ! (i+2)) x * poly (sturm p ! i) x < 0\"\n            (is \"poly ?p x * poly ?r x < 0\")\nproof-\n  from sturm_indices[OF i_in_range]\n      have \"sturm p ! (i+2) = - (sturm p ! i mod sturm p ! (i+1))\"\n           (is \"?r = - (?p mod ?q)\") .\n  hence \"-?r = ?p mod ?q\" by simp\n  with div_mult_mod_eq[of ?p ?q] have \"?p div ?q * ?q - ?r = ?p\" by simp\n  hence \"poly (?p div ?q) x * poly ?q x - poly ?r x = poly ?p x\"\n      by (metis poly_diff poly_mult)\n  with q_0 have r_x: \"poly ?r x = -poly ?p x\" by simp\n  moreover have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> x * x > 0\" apply (case_tac \"x \\<ge> 0\")\n      by (simp_all add: mult_neg_neg)\n  from sturm_adjacent_root_not_squarefree[of i p] assms r_x\n      have \"poly ?p x * poly ?p x > 0\" by (force intro: sqr_pos)\n  ultimately show \"poly ?r x * poly ?p x < 0\" by simp\nqed\n\n\ntext \\<open>\n  Finally, if $p$ contains no multiple roots, @{term \"sturm p\"}, i.e.\n  the canonical Sturm sequence for $p$, is a Sturm sequence\n  and can be used to determine the number of roots of $p$.\n\\<close>\nlemma sturm_seq_sturm[simp]:\n   assumes \"rsquarefree p\"\n   shows \"sturm_seq (sturm p) p\"\nproof\n  show \"sturm p \\<noteq> []\" by simp\n  show \"hd (sturm p) = p\" by simp\n  show \"length (sturm p) \\<ge> 2\" by simp\n  from assms show \"\\<And>x. \\<not>(poly p x = 0 \\<and> poly (sturm p ! 1) x = 0)\"\n      by (simp add: rsquarefree_roots)\nnext\n  fix x :: real and y :: real\n  have \"degree (last (sturm p)) = 0\" by simp\n  then obtain c where \"last (sturm p) = [:c:]\"\n      by (cases \"last (sturm p)\", simp split: if_split_asm)\n  thus \"\\<And>x y. sgn (poly (last (sturm p)) x) =\n            sgn (poly (last (sturm p)) y)\" by simp\nnext\n  from sturm_firsttwo_signs[OF assms]\n    show \"\\<And>x\\<^sub>0. poly p x\\<^sub>0 = 0 \\<Longrightarrow>\n         eventually (\\<lambda>x. sgn (poly (p*sturm p ! 1) x) =\n                         (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\" by simp\nnext\n  from sturm_signs[OF assms]\n    show \"\\<And>i x. \\<lbrakk>i < length (sturm p) - 2; poly (sturm p ! (i + 1)) x = 0\\<rbrakk>\n          \\<Longrightarrow> poly (sturm p ! (i + 2)) x * poly (sturm p ! i) x < 0\" by simp\nqed\n\n\nsubsubsection \\<open>Canonical squarefree Sturm sequence\\<close>\n\ntext \\<open>\n  The previous construction does not work for polynomials with multiple roots,\n  but we can simply ``divide away'' multiple roots by dividing $p$ by the\n  GCD of $p$ and $p'$. The resulting polynomial has the same roots as $p$,\n  but with multiplicity 1, allowing us to again use the canonical construction.\n\\<close>\ndefinition sturm_squarefree where\n  \"sturm_squarefree p = sturm (p div (gcd p (pderiv p)))\"\n\nlemma sturm_squarefree_not_Nil[simp]: \"sturm_squarefree p \\<noteq> []\"\n  by (simp add: sturm_squarefree_def)\n\n\nlemma sturm_seq_sturm_squarefree:\n  assumes [simp]: \"p \\<noteq> 0\"\n  defines [simp]: \"p' \\<equiv> p div gcd p (pderiv p)\"\n  shows \"sturm_seq (sturm_squarefree p) p'\"\nproof\n  have \"rsquarefree p'\"\n  proof (subst rsquarefree_roots, clarify)\n    fix x assume \"poly p' x = 0\" \"poly (pderiv p') x = 0\"\n    hence \"[:-x,1:] dvd gcd p' (pderiv p')\" by (simp add: poly_eq_0_iff_dvd)\n    also from poly_div_gcd_squarefree(1)[OF assms(1)]\n        have \"gcd p' (pderiv p') = 1\" by simp\n    finally show False by (simp add: poly_eq_0_iff_dvd[symmetric])\n  qed\n\n  from sturm_seq_sturm[OF \\<open>rsquarefree p'\\<close>]\n      interpret sturm_seq: sturm_seq \"sturm_squarefree p\" p'\n      by (simp add: sturm_squarefree_def)\n\n  show \"\\<And>x y. sgn (poly (last (sturm_squarefree p)) x) =\n      sgn (poly (last (sturm_squarefree p)) y)\" by simp\n  show \"sturm_squarefree p \\<noteq> []\" by simp\n  show \"hd (sturm_squarefree p) = p'\" by (simp add: sturm_squarefree_def)\n  show \"length (sturm_squarefree p) \\<ge> 2\" by simp\n\n  have [simp]: \"sturm_squarefree p ! 0 = p'\"\n               \"sturm_squarefree p ! Suc 0 = pderiv p'\"\n      by (simp_all add: sturm_squarefree_def)\n\n  from \\<open>rsquarefree p'\\<close>\n      show \"\\<And>x. \\<not> (poly p' x = 0 \\<and> poly (sturm_squarefree p ! 1) x = 0)\"\n      by (simp add: rsquarefree_roots)\n\n  from sturm_seq.signs show \"\\<And>i x. \\<lbrakk>i < length (sturm_squarefree p) - 2;\n                                 poly (sturm_squarefree p ! (i + 1)) x = 0\\<rbrakk>\n                                 \\<Longrightarrow> poly (sturm_squarefree p ! (i + 2)) x *\n                                         poly (sturm_squarefree p ! i) x < 0\" .\n\n  from sturm_seq.deriv show \"\\<And>x\\<^sub>0. poly p' x\\<^sub>0 = 0 \\<Longrightarrow>\n         eventually (\\<lambda>x. sgn (poly (p' * sturm_squarefree p ! 1) x) =\n                         (if x > x\\<^sub>0 then 1 else -1)) (at x\\<^sub>0)\" .\nqed\n\n\nsubsubsection \\<open>Optimisation for multiple roots\\<close>\n\ntext \\<open>\n  We can also define the following non-canonical Sturm sequence that\n  is obtained by taking the canonical Sturm sequence of $p$\n  (possibly with multiple roots) and then dividing the entire\n  sequence by the GCD of $p$ and its derivative.\n\\<close>\ndefinition sturm_squarefree' where\n\"sturm_squarefree' p = (let d = gcd p (pderiv p)\n                         in map (\\<lambda>p'. p' div d) (sturm p))\"\n\ntext \\<open>\n  This construction also has all the desired properties:\n\\<close>\n\nlemma sturm_squarefree'_adjacent_root_propagate_left:\n  assumes \"p \\<noteq> 0\"\n  assumes \"i < length (sturm_squarefree' (p :: real poly)) - 1\"\n  assumes \"poly (sturm_squarefree' p ! i) x = 0\"\n      and \"poly (sturm_squarefree' p ! (i + 1)) x = 0\"\n  shows \"\\<forall>j\\<le>i+1. poly (sturm_squarefree' p ! j) x = 0\"\nproof (intro sturm_adjacent_root_aux[OF assms(2,3,4)], goal_cases)\n  case prems: (1 i x)\n    define q where \"q = sturm p ! i\"\n    define r where \"r = sturm p ! (Suc i)\"\n    define s where \"s = sturm p ! (Suc (Suc i))\"\n    define d where \"d = gcd p (pderiv p)\"\n    define q' r' s' where \"q' = q div d\" and \"r' = r div d\" and \"s' = s div d\"\n    from \\<open>p \\<noteq> 0\\<close> have \"d \\<noteq> 0\" unfolding d_def by simp\n    from prems(1) have i_in_range: \"i < length (sturm p) - 2\"\n        unfolding sturm_squarefree'_def Let_def by simp\n    have [simp]: \"d dvd q\" \"d dvd r\" \"d dvd s\" unfolding q_def r_def s_def d_def\n        using i_in_range by (auto intro: sturm_gcd)\n    hence qrs_simps: \"q = q' * d\" \"r = r' * d\" \"s = s' * d\"\n        unfolding q'_def r'_def s'_def by (simp_all)\n    with prems(2) i_in_range have r'_0: \"poly r' x = 0\"\n        unfolding r'_def r_def d_def sturm_squarefree'_def Let_def by simp\n    hence r_0: \"poly r x = 0\" by (simp add: \\<open>r = r' * d\\<close>)\n    from sturm_indices[OF i_in_range] have \"q = q div r * r - s\"\n        unfolding q_def r_def s_def by (simp add: div_mult_mod_eq)\n    hence \"q' = (q div r * r - s) div d\" by (simp add: q'_def)\n    also have \"... = (q div r * r) div d - s'\"\n      by (simp add: s'_def poly_div_diff_left)\n    also have \"... = q div r * r' - s'\"\n        using dvd_div_mult[OF \\<open>d dvd r\\<close>, of \"q div r\"]\n        by (simp add: algebra_simps r'_def)\n    also have \"q div r = q' div r'\" by (simp add: qrs_simps \\<open>d \\<noteq> 0\\<close>)\n    finally have \"poly q' x = poly (q' div r' * r' - s') x\" by simp\n    also from r'_0 have \"... = -poly s' x\" by simp\n    finally have \"poly s' x = -poly q' x\" by simp\n    thus ?case using i_in_range\n        unfolding q'_def s'_def q_def s_def sturm_squarefree'_def Let_def\n        by (simp add: d_def sgn_minus)\nqed\n\nlemma sturm_squarefree'_adjacent_roots:\n  assumes \"p \\<noteq> 0\"\n           \"i < length (sturm_squarefree' (p :: real poly)) - 1\"\n          \"poly (sturm_squarefree' p ! i) x = 0\"\n          \"poly (sturm_squarefree' p ! (i + 1)) x = 0\"\n  shows False\nproof-\n  define d where \"d = gcd p (pderiv p)\"\n  from sturm_squarefree'_adjacent_root_propagate_left[OF assms]\n      have \"poly (sturm_squarefree' p ! 0) x = 0\"\n           \"poly (sturm_squarefree' p ! 1) x = 0\" by auto\n  hence \"poly (p div d) x = 0\" \"poly (pderiv p div d) x = 0\"\n      using assms(2)\n      unfolding sturm_squarefree'_def Let_def d_def by auto\n  moreover from div_gcd_coprime assms(1)\n      have \"coprime (p div d) (pderiv p div d)\" unfolding d_def by auto\n  ultimately show False using coprime_imp_no_common_roots by auto\nqed\n\nlemma sturm_squarefree'_signs:\n  assumes \"p \\<noteq> 0\"\n  assumes i_in_range: \"i < length (sturm_squarefree' (p :: real poly)) - 2\"\n  assumes q_0: \"poly (sturm_squarefree' p ! (i+1)) x = 0\" (is \"poly ?q x = 0\")\n  shows \"poly (sturm_squarefree' p ! (i+2)) x *\n         poly (sturm_squarefree' p ! i) x < 0\"\n            (is \"poly ?r x * poly ?p x < 0\")\nproof-\n  define d where \"d = gcd p (pderiv p)\"\n  with \\<open>p \\<noteq> 0\\<close> have [simp]: \"d \\<noteq> 0\" by simp\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>]\n       coprime_imp_no_common_roots\n      have rsquarefree: \"rsquarefree (p div d)\"\n      by (auto simp: rsquarefree_roots d_def)\n\n  from i_in_range have i_in_range': \"i < length (sturm p) - 2\"\n      unfolding sturm_squarefree'_def by simp\n  hence \"d dvd (sturm p ! i)\" (is \"d dvd ?p'\")\n        \"d dvd (sturm p ! (Suc i))\" (is \"d dvd ?q'\")\n        \"d dvd (sturm p ! (Suc (Suc i)))\" (is \"d dvd ?r'\")\n      unfolding d_def by (auto intro: sturm_gcd)\n  hence pqr_simps: \"?p' = ?p * d\" \"?q' = ?q * d\" \"?r' = ?r * d\"\n    unfolding sturm_squarefree'_def Let_def d_def using i_in_range'\n    by (auto simp: dvd_div_mult_self)\n  with q_0 have q'_0: \"poly ?q' x = 0\" by simp\n  from sturm_indices[OF i_in_range']\n      have \"sturm p ! (i+2) = - (sturm p ! i mod sturm p ! (i+1))\" .\n  hence \"-?r' = ?p' mod ?q'\" by simp\n  with div_mult_mod_eq[of ?p' ?q'] have \"?p' div ?q' * ?q' - ?r' = ?p'\" by simp\n  hence \"d*(?p div ?q * ?q - ?r) = d* ?p\" by (simp add: pqr_simps algebra_simps)\n  hence \"?p div ?q * ?q - ?r = ?p\" by simp\n  hence \"poly (?p div ?q) x * poly ?q x - poly ?r x = poly ?p x\"\n      by (metis poly_diff poly_mult)\n  with q_0 have r_x: \"poly ?r x = -poly ?p x\" by simp\n\n  from sturm_squarefree'_adjacent_roots[OF \\<open>p \\<noteq> 0\\<close>] i_in_range q_0\n      have \"poly ?p x \\<noteq> 0\" by force\n  moreover have sqr_pos: \"\\<And>x::real. x \\<noteq> 0 \\<Longrightarrow> x * x > 0\" apply (case_tac \"x \\<ge> 0\")\n      by (simp_all add: mult_neg_neg)\n  ultimately show ?thesis using r_x by simp\nqed\n\n\ntext \\<open>\n  This approach indeed also yields a valid squarefree Sturm sequence\n  for the polynomial $p/\\text{gcd}(p,p')$.\n\\<close>\nlemma sturm_seq_sturm_squarefree':\n  assumes \"(p :: real poly) \\<noteq> 0\"\n  defines \"d \\<equiv> gcd p (pderiv p)\"\n  shows \"sturm_seq (sturm_squarefree' p) (p div d)\"\n      (is \"sturm_seq ?ps' ?p'\")\nproof\n  show \"?ps' \\<noteq> []\" \"hd ?ps' = ?p'\" \"2 \\<le> length ?ps'\"\n      by (simp_all add: sturm_squarefree'_def d_def hd_map)\n\n  from assms have \"d \\<noteq> 0\" by simp\n  {\n    have \"d dvd last (sturm p)\" unfolding d_def\n        by (rule sturm_gcd, simp)\n    hence *: \"last (sturm p) = last ?ps' * d\"\n        by (simp add: sturm_squarefree'_def last_map d_def dvd_div_mult_self)\n    then have \"last ?ps' dvd last (sturm p)\" by simp\n    with * dvd_imp_degree_le[OF this] have \"degree (last ?ps') \\<le> degree (last (sturm p))\"\n        using \\<open>d \\<noteq> 0\\<close> by (cases \"last ?ps' = 0\") auto\n    hence \"degree (last ?ps') = 0\" by simp\n    then obtain c where \"last ?ps' = [:c:]\"\n        by (cases \"last ?ps'\", simp split: if_split_asm)\n    thus \"\\<And>x y. sgn (poly (last ?ps') x) = sgn (poly (last ?ps') y)\" by simp\n  }\n\n  have squarefree: \"rsquarefree ?p'\" using \\<open>p \\<noteq> 0\\<close>\n    by (subst rsquarefree_roots, unfold d_def,\n        intro allI coprime_imp_no_common_roots poly_div_gcd_squarefree)\n  have [simp]: \"sturm_squarefree' p ! Suc 0 = pderiv p div d\"\n      unfolding sturm_squarefree'_def Let_def sturm_def d_def\n          by (subst sturm_aux.simps, simp)\n  have coprime: \"coprime ?p' (pderiv p div d)\"\n      unfolding d_def using div_gcd_coprime \\<open>p \\<noteq> 0\\<close> by blast\n  thus squarefree':\n      \"\\<And>x. \\<not> (poly (p div d) x = 0 \\<and> poly (sturm_squarefree' p ! 1) x = 0)\"\n      using coprime_imp_no_common_roots by simp\n\n  from sturm_squarefree'_signs[OF \\<open>p \\<noteq> 0\\<close>]\n      show \"\\<And>i x. \\<lbrakk>i < length ?ps' - 2; poly (?ps' ! (i + 1)) x = 0\\<rbrakk>\n                \\<Longrightarrow> poly (?ps' ! (i + 2)) x * poly (?ps' ! i) x < 0\" .\n\n  have [simp]: \"?p' \\<noteq> 0\" using squarefree by (simp add: rsquarefree_def)\n  have A: \"?p' = ?ps' ! 0\" \"pderiv p div d = ?ps' ! 1\"\n      by (simp_all add: sturm_squarefree'_def Let_def d_def sturm_def,\n          subst sturm_aux.simps, simp)\n  have [simp]: \"?ps' ! 0 \\<noteq> 0\" using squarefree\n      by (auto simp: A rsquarefree_def)\n\n  fix x\\<^sub>0 :: real\n  assume \"poly ?p' x\\<^sub>0 = 0\"\n  hence \"poly p x\\<^sub>0 = 0\" using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      unfolding d_def by simp\n  hence \"pderiv p \\<noteq> 0\" using \\<open>p \\<noteq> 0\\<close> by (auto dest: pderiv_iszero)\n  with \\<open>p \\<noteq> 0\\<close> \\<open>poly p x\\<^sub>0 = 0\\<close>\n      have A: \"eventually (\\<lambda>x. sgn (poly (p * pderiv p) x) =\n                              (if x\\<^sub>0 < x then 1 else -1)) (at x\\<^sub>0)\"\n      by (intro sturm_firsttwo_signs_aux, simp_all)\n  note ev = eventually_conj[OF A poly_neighbourhood_without_roots[OF \\<open>d \\<noteq> 0\\<close>]]\n\n  show \"eventually (\\<lambda>x. sgn (poly (p div d * sturm_squarefree' p ! 1) x) =\n                        (if x\\<^sub>0 < x then 1 else -1)) (at x\\<^sub>0)\"\n  proof (rule eventually_mono[OF ev], goal_cases)\n      have [intro]:\n          \"\\<And>a (b::real). b \\<noteq> 0 \\<Longrightarrow> a < 0 \\<Longrightarrow> a / (b * b) < 0\"\n          \"\\<And>a (b::real). b \\<noteq> 0 \\<Longrightarrow> a > 0 \\<Longrightarrow> a / (b * b) > 0\"\n          by ((case_tac \"b > 0\",\n              auto simp: mult_neg_neg field_simps) [])+\n    case prems: (1 x)\n      hence  [simp]: \"poly d x * poly d x > 0\"\n           by (cases \"poly d x > 0\", auto simp: mult_neg_neg)\n      from poly_div_gcd_squarefree_aux(2)[OF \\<open>pderiv p \\<noteq> 0\\<close>]\n          have \"poly (p div d) x = 0 \\<longleftrightarrow> poly p x = 0\" by (simp add: d_def)\n      moreover have \"d dvd p\" \"d dvd pderiv p\" unfolding d_def by simp_all\n      ultimately show ?case using prems\n          by (auto simp: sgn_real_def poly_div not_less[symmetric]\n                         zero_less_divide_iff split: if_split_asm)\n  qed\nqed\n\n\ntext \\<open>\n  This construction is obviously more expensive to compute than the one that \\emph{first}\n  divides $p$ by $\\text{gcd}(p,p')$ and \\emph{then} applies the canonical construction.\n  In this construction, we \\emph{first} compute the canonical Sturm sequence of $p$ as if\n  it had no multiple roots and \\emph{then} divide by the GCD.\n  However, it can be seen quite easily that unless $x$ is a multiple root of $p$,\n  i.\\,e. as long as $\\text{gcd}(P,P')\\neq 0$, the number of sign changes in a sequence of\n  polynomials does not actually change when we divide the polynomials by $\\text{gcd}(p,p')$.\\\\\n  There\\-fore we can use the ca\\-no\\-ni\\-cal Sturm se\\-quence even in the non-square\\-free\n  case as long as the borders of the interval we are interested in are not multiple roots\n  of the polynomial.\n\\<close>\n\nlemma sign_changes_mult_aux:\n  assumes \"d \\<noteq> (0::real)\"\n  shows \"length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map ((*) d \\<circ> f) xs))) =\n         length (remdups_adj (filter (\\<lambda>x. x \\<noteq> 0) (map f xs)))\"\nproof-\n  from assms have inj: \"inj ((*) d)\" by (auto intro: injI)\n  from assms have [simp]: \"filter (\\<lambda>x. ((*) d \\<circ> f) x \\<noteq> 0) = filter (\\<lambda>x. f x \\<noteq> 0)\"\n                          \"filter ((\\<lambda>x. x \\<noteq> 0) \\<circ> f) = filter (\\<lambda>x. f x \\<noteq> 0)\"\n      by (simp_all add: o_def)\n  have \"filter (\\<lambda>x. x \\<noteq> 0) (map ((*) d \\<circ> f) xs) =\n        map ((*) d \\<circ> f) (filter (\\<lambda>x. ((*) d \\<circ> f) x \\<noteq> 0) xs)\"\n      by (simp add: filter_map o_def)\n  thus ?thesis using remdups_adj_map_injective[OF inj] assms\n      by (simp add: filter_map map_map[symmetric] del: map_map)\nqed\n\nlemma sturm_sturm_squarefree'_same_sign_changes:\n  fixes p :: \"real poly\"\n  defines \"ps \\<equiv> sturm p\" and \"ps' \\<equiv> sturm_squarefree' p\"\n  shows \"poly p x \\<noteq> 0 \\<or> poly (pderiv p) x \\<noteq> 0 \\<Longrightarrow>\n             sign_changes ps' x = sign_changes ps x\"\n        \"p \\<noteq> 0 \\<Longrightarrow> sign_changes_inf ps' = sign_changes_inf ps\"\n        \"p \\<noteq> 0 \\<Longrightarrow> sign_changes_neg_inf ps' = sign_changes_neg_inf ps\"\nproof-\n  define d where \"d = gcd p (pderiv p)\"\n  define p' where \"p' = p div d\"\n  define s' where \"s' = poly_inf d\"\n  define s'' where \"s'' = poly_neg_inf d\"\n\n  {\n    fix x :: real and q :: \"real poly\"\n    assume \"q \\<in> set ps\"\n    hence \"d dvd q\" unfolding d_def ps_def using sturm_gcd by simp\n    hence q_prod: \"q = (q div d) * d\" unfolding p'_def d_def\n        by (simp add: algebra_simps dvd_mult_div_cancel)\n\n    have \"poly q x = poly d x * poly (q div d) x\"  by (subst q_prod, simp)\n    hence s1: \"sgn (poly q x) = sgn (poly d x) * sgn (poly (q div d) x)\"\n        by (subst q_prod, simp add: sgn_mult)\n    from poly_inf_mult have s2: \"poly_inf q = s' * poly_inf (q div d)\"\n        unfolding s'_def by (subst q_prod, simp)\n    from poly_inf_mult have s3: \"poly_neg_inf q = s'' * poly_neg_inf (q div d)\"\n        unfolding s''_def by (subst q_prod, simp)\n    note s1 s2 s3\n  }\n  note signs = this\n\n  {\n    fix f :: \"real poly \\<Rightarrow> real\" and s :: real\n    assume f: \"\\<And>q. q \\<in> set ps \\<Longrightarrow> f q = s * f (q div d)\" and s: \"s \\<noteq> 0\"\n    hence \"inverse s \\<noteq> 0\" by simp\n    {fix q assume \"q \\<in> set ps\"\n     hence \"f (q div d) = inverse s * f q\"\n         by (subst f[of q], simp_all add: s)\n    } note f' = this\n    have \"length (remdups_adj [x\\<leftarrow>map f (map (\\<lambda>q. q div d) ps). x \\<noteq> 0]) - 1 =\n           length (remdups_adj [x\\<leftarrow>map (\\<lambda>q. f (q div d)) ps . x \\<noteq> 0]) - 1\"\n        by (simp only: sign_changes_def o_def map_map)\n    also have \"map (\\<lambda>q. q div d) ps = ps'\"\n        by (simp add: ps_def ps'_def sturm_squarefree'_def Let_def d_def)\n    also from f' have \"map (\\<lambda>q. f (q div d)) ps =\n                      map (\\<lambda>x. ((*)(inverse s) \\<circ> f) x) ps\" by (simp add: o_def)\n    also note sign_changes_mult_aux[OF \\<open>inverse s \\<noteq> 0\\<close>, of f ps]\n    finally have\n        \"length (remdups_adj [x\\<leftarrow>map f ps' . x \\<noteq> 0]) - 1 =\n         length (remdups_adj [x\\<leftarrow>map f ps . x \\<noteq> 0]) - 1\" by simp\n  }\n  note length_remdups_adj = this\n\n  {\n    fix x assume A: \"poly p x \\<noteq> 0 \\<or> poly (pderiv p) x \\<noteq> 0\"\n    have \"d dvd p\" \"d dvd pderiv p\" unfolding d_def by simp_all\n    with A have \"sgn (poly d x) \\<noteq> 0\"\n        by (auto simp add: sgn_zero_iff elim: dvdE)\n    thus \"sign_changes ps' x = sign_changes ps x\" using signs(1)\n        unfolding sign_changes_def\n        by (intro length_remdups_adj[of \"\\<lambda>q. sgn (poly q x)\"], simp_all)\n  }\n\n  assume \"p \\<noteq> 0\"\n  hence \"d \\<noteq> 0\" unfolding d_def by simp\n  hence \"s' \\<noteq> 0\" \"s'' \\<noteq> 0\" unfolding s'_def s''_def by simp_all\n  from length_remdups_adj[of poly_inf s', OF signs(2) \\<open>s' \\<noteq> 0\\<close>]\n      show \"sign_changes_inf ps' = sign_changes_inf ps\"\n      unfolding sign_changes_inf_def .\n  from length_remdups_adj[of poly_neg_inf s'', OF signs(3) \\<open>s'' \\<noteq> 0\\<close>]\n      show \"sign_changes_neg_inf ps' = sign_changes_neg_inf ps\"\n      unfolding sign_changes_neg_inf_def .\nqed\n\n\n\nsubsection \\<open>Root-counting functions\\<close>\n\ntext \\<open>\n  With all these results, we can now define functions that count roots\n  in bounded and unbounded intervals:\n\\<close>\n\ndefinition count_roots_between where\n\"count_roots_between p a b = (if a \\<le> b \\<and> p \\<noteq> 0 then\n  (let ps = sturm_squarefree p\n    in sign_changes ps a - sign_changes ps b) else 0)\"\n\ndefinition count_roots where\n\"count_roots p = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes_neg_inf ps - sign_changes_inf ps))\"\n\ndefinition count_roots_above where\n\"count_roots_above p a = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes ps a - sign_changes_inf ps))\"\n\ndefinition count_roots_below where\n\"count_roots_below p a = (if (p::real poly) = 0 then 0 else\n  (let ps = sturm_squarefree p\n    in sign_changes_neg_inf ps - sign_changes ps a))\"\n\n\nlemma count_roots_between_correct:\n  \"count_roots_between p a b = card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\"\nproof (cases \"p \\<noteq> 0 \\<and> a \\<le> b\")\n  case False\n    note False' = this\n    hence \"card {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0} = 0\"\n    proof (cases \"a < b\")\n      case True\n        with False have [simp]: \"p = 0\" by simp\n        have subset: \"{a<..<b} \\<subseteq> {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" by auto\n        from infinite_Ioo[OF True] have \"\\<not>finite {a<..<b}\" .\n        hence \"\\<not>finite {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\"\n            using finite_subset[OF subset] by blast\n        thus ?thesis by simp\n    next\n      case False\n        with False' show ?thesis by (auto simp: not_less card_eq_0_iff)\n    qed\n    thus ?thesis unfolding count_roots_between_def Let_def using False by auto\nnext\n  case True\n  hence \"p \\<noteq> 0\" \"a \\<le> b\" by simp_all\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from poly_roots_finite[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"finite {x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0}\" by fast\n  have \"count_roots_between p a b = card {x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0}\"\n      unfolding count_roots_between_def Let_def\n      using True count_roots_between[OF \\<open>p' \\<noteq> 0\\<close> \\<open>a \\<le> b\\<close>] by simp\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. a < x \\<and> x \\<le> b \\<and> poly p' x = 0} =\n            {x. a < x \\<and> x \\<le> b \\<and> poly p x = 0}\" unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots p = card {x. poly p x = 0}\" (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with finite_subset[of \"{0<..<1}\" ?S]\n    have \"\\<not>finite {x. poly p x = 0}\" by (auto simp: infinite_Ioo)\n    thus ?thesis by (simp add: count_roots_def True)\nnext\n  case False\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"count_roots p = card {x. poly p' x = 0}\"\n      unfolding count_roots_def Let_def by (simp add: \\<open>p \\<noteq> 0\\<close>)\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. poly p' x = 0} = {x. poly p x = 0}\" unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_above_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots_above p a = card {x. x > a \\<and> poly p x = 0}\"\n         (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n  with finite_subset[of \"{a<..<a+1}\" ?S]\n    have \"\\<not>finite {x. x > a \\<and> poly p x = 0}\" by (auto simp: infinite_Ioo subset_eq)\n  thus ?thesis by (simp add: count_roots_above_def True)\nnext\n  case False\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots_above[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"count_roots_above p a = card {x. x > a \\<and> poly p' x = 0}\"\n      unfolding count_roots_above_def Let_def by (simp add: \\<open>p \\<noteq> 0\\<close>)\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. x > a \\<and> poly p' x = 0} = {x. x > a \\<and> poly p x = 0}\"\n      unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\nlemma count_roots_below_correct:\n  fixes p :: \"real poly\"\n  shows \"count_roots_below p a = card {x. x \\<le> a \\<and> poly p x = 0}\"\n         (is \"_ = card ?S\")\nproof (cases \"p = 0\")\n  case True\n    with finite_subset[of \"{a - 1<..<a}\" ?S]\n        have \"\\<not>finite {x. x \\<le> a \\<and> poly p x = 0}\" by (auto simp: infinite_Ioo subset_eq)\n    thus ?thesis by (simp add: count_roots_below_def True)\nnext\n  case False\n  define p' where \"p' = p div (gcd p (pderiv p))\"\n  from poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] have \"p' \\<noteq> 0\"\n      unfolding p'_def by clarsimp\n\n  from sturm_seq_sturm_squarefree[OF \\<open>p \\<noteq> 0\\<close>]\n      interpret sturm_seq \"sturm_squarefree p\" p'\n      unfolding p'_def .\n  from count_roots_below[OF \\<open>p' \\<noteq> 0\\<close>]\n      have \"count_roots_below p a = card {x. x \\<le> a \\<and> poly p' x = 0}\"\n      unfolding count_roots_below_def Let_def by (simp add: \\<open>p \\<noteq> 0\\<close>)\n  also from poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      have \"{x. x \\<le> a \\<and> poly p' x = 0} = {x. x \\<le> a \\<and> poly p x = 0}\"\n      unfolding p'_def by blast\n  finally show ?thesis .\nqed\n\ntext \\<open>\n  The optimisation explained above can be used to prove more efficient code equations that\n  use the more efficient construction in the case that the interval borders are not\n  multiple roots:\n\\<close>\n\nlemma count_roots_between[code]:\n  \"count_roots_between p a b =\n     (let q = pderiv p\n       in if a > b \\<or> p = 0 then 0\n       else if (poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0) \\<and> (poly p b \\<noteq> 0 \\<or> poly q b \\<noteq> 0)\n            then (let ps = sturm p\n                   in sign_changes ps a - sign_changes ps b)\n            else (let ps = sturm_squarefree p\n                   in sign_changes ps a - sign_changes ps b))\"\nproof (cases \"a > b \\<or> p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_between_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"a \\<le> b\" \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0) \\<and>\n                  (poly p b \\<noteq> 0 \\<or> poly (pderiv p) b \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1\n          by (auto simp add: Let_def count_roots_between_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" and\n            B: \"poly p b \\<noteq> 0 \\<or> poly (pderiv p) b \\<noteq> 0\" by auto\n      define d where \"d = gcd p (pderiv p)\"\n      from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n          using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_between_correct\n      also have \"{x. a < x \\<and> x \\<le> b \\<and> poly p x = 0} =\n                 {x. a < x \\<and> x \\<le> b \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n      also note count_roots_between[OF \\<open>p div d \\<noteq> 0\\<close> \\<open>a \\<le> b\\<close>, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF B]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\n\nlemma count_roots_code[code]:\n  \"count_roots (p::real poly) =\n    (if p = 0 then 0\n     else let ps = sturm p\n           in sign_changes_neg_inf ps - sign_changes_inf ps)\"\nproof (cases \"p = 0\", simp add: count_roots_def)\n  case False\n    define d where \"d = gcd p (pderiv p)\"\n    from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n        using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n    from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n        interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n        unfolding sturm_squarefree'_def Let_def d_def .\n\n    note count_roots_correct\n    also have \"{x. poly p x = 0} = {x. poly (p div d) x = 0}\"\n        unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n    also note count_roots[OF \\<open>p div d \\<noteq> 0\\<close>, symmetric]\n    also note sturm_sturm_squarefree'_same_sign_changes(2)[OF \\<open>p \\<noteq> 0\\<close>]\n    also note sturm_sturm_squarefree'_same_sign_changes(3)[OF \\<open>p \\<noteq> 0\\<close>]\n    finally show ?thesis using False unfolding Let_def by simp\nqed\n\n\nlemma count_roots_above_code[code]:\n  \"count_roots_above p a =\n     (let q = pderiv p\n       in if p = 0 then 0\n       else if poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0\n            then (let ps = sturm p\n                   in sign_changes ps a - sign_changes_inf ps)\n            else (let ps = sturm_squarefree p\n                   in sign_changes ps a - sign_changes_inf ps))\"\nproof (cases \"p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_above_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1\n          by (auto simp add: Let_def count_roots_above_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" by simp\n      define d where \"d = gcd p (pderiv p)\"\n      from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n          using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_above_correct\n      also have \"{x. a < x \\<and> poly p x = 0} =\n                 {x. a < x \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n      also note count_roots_above[OF \\<open>p div d \\<noteq> 0\\<close>, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(2)[OF \\<open>p \\<noteq> 0\\<close>]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\nlemma count_roots_below_code[code]:\n  \"count_roots_below p a =\n     (let q = pderiv p\n       in if p = 0 then 0\n       else if poly p a \\<noteq> 0 \\<or> poly q a \\<noteq> 0\n            then (let ps = sturm p\n                   in sign_changes_neg_inf ps - sign_changes ps a)\n            else (let ps = sturm_squarefree p\n                   in sign_changes_neg_inf ps - sign_changes ps a))\"\nproof (cases \"p = 0\")\n  case True\n    thus ?thesis by (auto simp add: count_roots_below_def Let_def)\nnext\n  case False\n    note False1 = this\n    hence \"p \\<noteq> 0\" by simp_all\n    thus ?thesis\n    proof (cases \"(poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0)\")\n    case False\n      thus ?thesis using False1\n          by (auto simp add: Let_def count_roots_below_def)\n    next\n    case True\n      hence A: \"poly p a \\<noteq> 0 \\<or> poly (pderiv p) a \\<noteq> 0\" by simp\n      define d where \"d = gcd p (pderiv p)\"\n      from \\<open>p \\<noteq> 0\\<close> have [simp]: \"p div d \\<noteq> 0\"\n          using poly_div_gcd_squarefree(1)[OF \\<open>p \\<noteq> 0\\<close>] by (auto simp add: d_def)\n      from sturm_seq_sturm_squarefree'[OF \\<open>p \\<noteq> 0\\<close>]\n          interpret sturm_seq \"sturm_squarefree' p\" \"p div d\"\n          unfolding sturm_squarefree'_def Let_def d_def .\n      note count_roots_below_correct\n      also have \"{x. x \\<le> a \\<and> poly p x = 0} =\n                 {x. x \\<le> a \\<and> poly (p div d) x = 0}\"\n          unfolding d_def using poly_div_gcd_squarefree(2)[OF \\<open>p \\<noteq> 0\\<close>] by simp\n      also note count_roots_below[OF \\<open>p div d \\<noteq> 0\\<close>, symmetric]\n      also note sturm_sturm_squarefree'_same_sign_changes(1)[OF A]\n      also note sturm_sturm_squarefree'_same_sign_changes(3)[OF \\<open>p \\<noteq> 0\\<close>]\n      finally show ?thesis using True False by (simp add: Let_def)\n    qed\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Sturm_Sequences/Sturm_Theorem.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.867035763237924, "lm_q2_score": 0.8670357563664174, "lm_q1q2_score": 0.7517510087757274}}
{"text": "section \"Stack Machine and Compilation\"\n\ntheory ASM imports AExp begin\n\nsubsection \"Stack Machine\"\n\ntext_raw{*\\snip{ASMinstrdef}{0}{1}{% *}\ndatatype instr = LOADI val | LOAD vname | ADD\ntext_raw{*}%endsnip*}\n\ntext_raw{*\\snip{ASMstackdef}{1}{2}{% *}\ntype_synonym stack = \"val list\"\ntext_raw{*}%endsnip*}\n\ntext \\<open>Execution of a single instruction is straightforward, \n  except for the special case if one tries to execute ADD with \n  a stack of less than two elements. \n  We leave this case explicitly undefined, where undefined \n  is just an ordinary HOL term, but without any additional theorems on it.\n  That is, @{term \"undefined::'a\"} may be every value of type @{typ 'a}, but \n  you don't know which one.\n\\<close>  \nfun exec1  :: \"instr \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where \n  \"exec1 (LOADI n) _ stk  =  n # stk\"\n| \"exec1 (LOAD x) s stk  =  s(x) # stk\"\n| \"exec1 ADD _ (a#b#stk) = (a+b)#stk\"\n| \"exec1 ADD _ _ = undefined\"   \n  \n  \ntext \\<open>Executing a list of statements is straightforward\\<close>\ntext_raw{*\\snip{ASMexecdef}{1}{2}{% *}\nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> stack \\<Rightarrow> stack\" where\n\"exec [] _ stk = stk\" |\n\"exec (i#is) s stk = exec is s (exec1 i s stk)\"\ntext_raw{*}%endsnip*}\n\nvalue \"exec [LOADI 5, LOAD ''y'', ADD] <''x'' := 42, ''y'' := 43> [50]\"\n\nlemma exec_append[simp]:\n  \"exec (is1@is2) s stk = exec is2 s (exec is1 s stk)\"\napply(induction is1 arbitrary: stk)\napply (auto)\ndone\n\n\nsubsection \"Compilation\"\n\ntext \\<open>Compilation of expressions to stack-machines is particularly easy:\n  Each expression compiles to a program that effectively pushes its result\n  to the top of stack.\n\\<close>\ntext_raw{*\\snip{ASMcompdef}{0}{2}{% *}\nfun comp :: \"aexp \\<Rightarrow> instr list\" where\n\"comp (N n) = [LOADI n]\" |\n\"comp (V x) = [LOAD x]\" |\n\"comp (Plus e\\<^sub>1 e\\<^sub>2) = comp e\\<^sub>1 @ comp e\\<^sub>2 @ [ADD]\"\ntext_raw{*}%endsnip*}\n\nvalue \"comp (Plus (Plus (V ''x'') (N 1)) (V ''z''))\"\n\ntext \\<open>This theorem intuitively states: When running the compiled program for \n  \\<open>a\\<close>, it will push the value of \\<open>a\\<close> on the stack, not changing anything on \n  the original stack.\n\\<close>  \ntheorem exec_comp: \"exec (comp a) s stk = aval a s # stk\"\napply(induction a arbitrary: stk)\napply (auto)\ndone\n\ntext \\<open>Special case for starting with an empty stack. \n  Note, this theorem cannot be proved by induction directly, but needs \n  to be generalized to @{thm exec_comp} first.\n\\<close>  \ntheorem exec_comp': \"exec (comp a) s [] = [aval a s]\"\n  by (simp add: exec_comp)\n  \n  \nend\n", "meta": {"author": "bcliu430", "repo": "ECE5984", "sha": "6846d1bba065999d5b1878d3339677b14768ba90", "save_path": "github-repos/isabelle/bcliu430-ECE5984", "path": "github-repos/isabelle/bcliu430-ECE5984/ECE5984-6846d1bba065999d5b1878d3339677b14768ba90/IMP/ASM.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267898240861, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.751729869692464}}
{"text": "section \\<open>Carter-Wegman Hash Family\\label{sec:carter_wegman}\\<close>\n\ntheory Carter_Wegman_Hash_Family\n  imports\n    Interpolation_Polynomials_HOL_Algebra.Interpolation_Polynomial_Cardinalities\n    Preliminary_Results\nbegin\n\ntext \\<open>The Carter-Wegman hash family is a generic method to obtain\n$k$-universal hash families for arbitrary $k$. (There are faster solutions, such as tabulation\nhashing, which are limited to a specific $k$. See for example \\<^cite>\\<open>\"thorup2010\"\\<close>.)\n\nThe construction was described by Wegman and Carter~\\<^cite>\\<open>\"wegman1981\"\\<close>, it is a hash\nfamily between the elements of a finite field and works by choosing randomly a polynomial\nover the field with degree less than $k$. The hash function is the evaluation of a such a\npolynomial.\n\nUsing the property that the fraction of polynomials interpolating a given set of $s \\leq k$\npoints is @{term \"1/(card (carrier R)^s)\"}, which is shown in\n\\<^cite>\\<open>\"Interpolation_Polynomials_HOL_Algebra-AFP\"\\<close>, it is possible to obtain both that\nthe hash functions are $k$-wise independent and uniformly distributed.\n\nIn the following two locales are introduced, the main reason for both is to make the statements\nof the theorems and proofs more concise. The first locale @{term \"poly_hash_family\"} fixes a finite\nring $R$ and the probability space of the polynomials of degree less than $k$. Because the ring is\nnot a field, the family is not yet $k$-universal, but it is still possible to state a few results such\nas the fact that the range of the hash function is a subset of the carrier of the ring.\n\nThe second locale @{term \"carter_wegman_hash_family\"} is an extension of the former with the\nassumption that $R$ is a field with which the $k$-universality follows.\n\nThe reason for using two separate locales is to support use cases, where the ring is only probably\na field. For example if it is the set of integers modulo an approximate prime, in such a situation a\nsubset of the properties of an algorithm using approximate primes would need to be verified\neven if $R$ is only a ring.\\<close>\n\ndefinition (in ring) \"hash x \\<omega> = eval \\<omega> x\"\n\nlocale poly_hash_family = ring +\n  fixes k :: nat\n  assumes finite_carrier[simp]: \"finite (carrier R)\"\n  assumes k_ge_0: \"k > 0\"\nbegin\n\ndefinition space where \"space = bounded_degree_polynomials R k\"\ndefinition M where \"M = measure_pmf (pmf_of_set space)\"\n\nlemma finite_space[simp]:\"finite space\"\n    unfolding space_def using fin_degree_bounded finite_carrier by simp\n\nlemma non_empty_bounded_degree_polynomials[simp]:\"space \\<noteq> {}\"\n    unfolding space_def using non_empty_bounded_degree_polynomials by simp\n\ntext \\<open>This is to add @{thm [source] carrier_not_empty} to the simp set in the context of\n@{locale \"poly_hash_family\"}:\\<close>\n\nlemma non_empty_carrier[simp]: \"carrier R \\<noteq> {}\"\n  by (simp add:carrier_not_empty)\n\nsublocale prob_space \"M\"\n  by (simp add:M_def prob_space_measure_pmf)\n\nlemma hash_range[simp]:\n  assumes \"\\<omega> \\<in> space\"\n  assumes \"x \\<in> carrier R\"\n  shows \"hash x \\<omega> \\<in> carrier R\"\n  using assms unfolding hash_def space_def bounded_degree_polynomials_def\n  by (simp, metis eval_in_carrier polynomial_incl univ_poly_carrier)\n\nlemma  hash_range_2:\n  assumes \"\\<omega> \\<in> space\"\n  shows \"(\\<lambda>x. hash x \\<omega>) ` carrier R \\<subseteq> carrier R\"\n  using hash_range assms by auto\n\nlemma integrable_M[simp]:\n  fixes f :: \"'a list \\<Rightarrow> 'c::{banach, second_countable_topology}\"\n  shows \"integrable M f\"\n    unfolding M_def\n    by (rule integrable_measure_pmf_finite, simp)\n\nend\n\nlocale carter_wegman_hash_family = poly_hash_family +\n  assumes field_R: \"field R\"\nbegin\nsublocale field\n  using field_R by simp\n\nabbreviation \"field_size \\<equiv> card (carrier R)\"\n\nlemma poly_cards:\n  assumes \"K \\<subseteq> carrier R\"\n  assumes \"card K \\<le> k\"\n  assumes \"y ` K \\<subseteq> (carrier R)\"\n  shows\n    \"card {\\<omega> \\<in> space. (\\<forall>k \\<in> K. eval \\<omega> k = y k)} = field_size^(k-card K)\"\n  unfolding space_def\n  using interpolating_polynomials_card[where n=\"k-card K\" and K=\"K\"] assms\n  using finite_carrier finite_subset by fastforce\n\nlemma poly_cards_single:\n  assumes \"x \\<in> carrier R\"\n  assumes \"y \\<in> carrier R\"\n  shows \"card {\\<omega> \\<in> space. eval \\<omega> x = y} = field_size^(k-1)\"\n  using poly_cards[where K=\"{x}\" and y=\"\\<lambda>_. y\", simplified] assms k_ge_0 by simp\n\nlemma hash_prob:\n  assumes \"K \\<subseteq> carrier R\"\n  assumes \"card K \\<le> k\"\n  assumes \"y ` K \\<subseteq> carrier R\"\n  shows\n    \"prob {\\<omega>. (\\<forall>x \\<in> K. hash x \\<omega> = y x)} = 1/(real field_size)^card K\"\nproof -\n  have \"\\<zero> \\<in> carrier R\" by simp\n\n  hence a:\"field_size > 0\"\n    using finite_carrier card_gt_0_iff by blast\n\n  have b:\"real (card {\\<omega> \\<in> space. \\<forall>x\\<in>K. eval \\<omega> x = y x}) / real (card space) =\n    1 / real field_size ^ card K\"\n    using a assms(2)\n    apply (simp add: frac_eq_eq poly_cards[OF assms(1,2,3)] power_add[symmetric])\n    by (simp add:space_def bounded_degree_polynomials_card)\n\n  show ?thesis\n    unfolding M_def\n    by (simp add:hash_def measure_pmf_of_set Int_def b)\nqed\n\nlemma prob_single:\n  assumes \"x \\<in> carrier R\" \"y \\<in> carrier R\"\n  shows \"prob {\\<omega>. hash x \\<omega> = y} = 1/(real field_size)\"\n  using hash_prob[where K=\"{x}\"] assms finite_carrier k_ge_0 by simp\n\nlemma prob_range:\n  assumes [simp]:\"x \\<in> carrier R\"\n  shows \"prob {\\<omega>. hash x \\<omega> \\<in> A} = card (A \\<inter> carrier R) / field_size\"\nproof -\n  have \"prob {\\<omega>. hash x \\<omega> \\<in> A} = prob (\\<Union>a \\<in> A \\<inter> carrier R. {\\<omega>. hash x \\<omega> = a})\"\n    by (rule measure_pmf_eq, auto simp:M_def)\n  also have \"... = (\\<Sum> a \\<in> (A \\<inter> carrier R). prob {\\<omega>. hash x \\<omega> = a})\"\n    by (rule measure_finite_Union, auto simp:M_def disjoint_family_on_def)\n  also have \"... = (\\<Sum> a \\<in> (A \\<inter> carrier R). 1/(real field_size))\"\n    by (rule sum.cong, auto simp:prob_single)\n  also have \"... = card (A \\<inter> carrier R) / field_size\"\n    by simp\n  finally show ?thesis by simp\nqed\n\nlemma indep:\n  assumes \"J \\<subseteq> carrier R\"\n  assumes \"card J \\<le> k\"\n  shows \"indep_vars (\\<lambda>_. discrete) hash J\"\nproof -\n  have \"\\<zero> \\<in> carrier R\" by simp\n  hence card_R_ge_0:\"field_size > 0\"\n    using card_gt_0_iff finite_carrier by blast\n\n  have fin_J: \"finite J\"\n    using finite_carrier assms(1) finite_subset by blast\n\n  show ?thesis\n  proof (rule indep_vars_pmf[OF M_def])\n    fix a\n    fix J'\n    assume a: \"J' \\<subseteq> J\" \"finite J'\"\n    have card_J': \"card J' \\<le> k\"\n      by (metis card_mono order_trans a(1) assms(2) fin_J)\n    have J'_in_carr: \"J' \\<subseteq> carrier R\" by (metis order_trans a(1) assms(1))\n\n    show \"prob {\\<omega>. \\<forall>x\\<in>J'. hash x \\<omega> = a x} = (\\<Prod>x\\<in>J'. prob  {\\<omega>. hash x \\<omega> = a x})\"\n    proof (cases \"a ` J' \\<subseteq> carrier R\")\n      case True\n      have a_carr: \"\\<And>x. x \\<in> J' \\<Longrightarrow> a x \\<in> carrier R\"  using True by force\n      have \"prob {\\<omega>. \\<forall>x\\<in>J'. hash x \\<omega> = a x} =\n        real (card {\\<omega> \\<in> space. \\<forall>x\\<in>J'. eval \\<omega> x = a x}) / real (card space)\"\n        by (simp add:M_def measure_pmf_of_set Int_def hash_def)\n      also have \"... = real (field_size ^ (k - card J')) / real (card space)\"\n        using True by (simp add: poly_cards[OF J'_in_carr card_J'])\n      also have\n        \"... = real field_size ^ (k - card J') / real field_size ^ k\"\n        by (simp add:space_def bounded_degree_polynomials_card)\n      also have\n        \"... = real field_size ^ ((k - 1) * card J') / real field_size ^ (k * card J')\"\n        using card_J' by (simp add:power_add[symmetric] power_mult[symmetric]\n            diff_mult_distrib frac_eq_eq add.commute)\n      also have\n        \"... = (real field_size ^ (k - 1)) ^ card J' / (real field_size ^ k) ^ card J'\"\n        by (simp add:power_add power_mult)\n      also have\n        \"... =  (\\<Prod>x\\<in>J'. real (card {\\<omega> \\<in> space. eval \\<omega> x = a x}) / real (card space))\"\n        using a_carr poly_cards_single[OF subsetD[OF J'_in_carr]]\n        by (simp add:space_def bounded_degree_polynomials_card power_divide)\n      also have \"... = (\\<Prod>x\\<in>J'. prob {\\<omega>. hash x \\<omega> = a x})\"\n        by (simp add:measure_pmf_of_set M_def Int_def hash_def)\n      finally show ?thesis by simp\n    next\n      case False\n      then obtain j where j_def: \"j \\<in> J'\" \"a j \\<notin> carrier R\" by blast\n      have \"{\\<omega> \\<in> space. hash j \\<omega> = a j} \\<subseteq> {\\<omega> \\<in> space. hash j \\<omega> \\<notin> carrier R}\"\n        by (rule subsetI, simp add:j_def)\n      also have \"... \\<subseteq> {}\" using j_def(1) J'_in_carr hash_range by blast\n      finally have b:\"{\\<omega> \\<in> space. hash j \\<omega> = a j} = {}\" by simp\n      hence \"real (card ({\\<omega> \\<in> space. hash j \\<omega> = a j})) = 0\" by simp\n      hence \"(\\<Prod>x\\<in>J'. real (card {\\<omega> \\<in> space. hash x \\<omega> = a x})) = 0\"\n        using a(2) prod_zero[OF a(2)] j_def(1) by auto\n      moreover have\n        \"{\\<omega> \\<in> space. \\<forall>x\\<in>J'. hash x \\<omega> = a x} \\<subseteq> {\\<omega> \\<in> space. hash j \\<omega> = a j}\"\n        using j_def by blast\n      hence \"{\\<omega> \\<in> space. \\<forall>x\\<in>J'. hash x \\<omega> = a x} = {}\" using b by blast\n      ultimately show ?thesis\n        by (simp add:measure_pmf_of_set M_def Int_def prod_dividef)\n    qed\n  qed\nqed\n\nlemma k_wise_indep:\n  \"k_wise_indep_vars k (\\<lambda>_. discrete) hash (carrier R)\"\n  unfolding k_wise_indep_vars_def using indep by simp\n\nlemma inj_if_degree_1:\n  assumes \"\\<omega> \\<in> space\"\n  assumes \"degree \\<omega> = 1\"\n  shows \"inj_on (\\<lambda>x. hash x \\<omega>) (carrier R)\"\n  using assms eval_inj_if_degree_1\n  by (simp add:M_def space_def bounded_degree_polynomials_def hash_def)\n\nlemma uniform:\n  assumes \"i \\<in> carrier R\"\n  shows \"uniform_on (hash i) (carrier R)\"\nproof -\n  have a:\n    \"\\<And>a. prob {\\<omega>. hash i \\<omega> \\<in> {a}} = indicat_real (carrier R) a / real field_size\"\n    by (subst prob_range[OF assms], simp add:indicator_def)\n  show ?thesis\n    by (rule uniform_onI, use a M_def in auto)\nqed\n\ntext \\<open>This the main result of this section - the Carter-Wegman hash family is $k$-universal.\\<close>\n\ntheorem k_universal:\n  \"k_universal k hash (carrier R) (carrier R)\"\n  using uniform k_wise_indep by (simp add:k_universal_def)\n\nend\n\nlemma poly_hash_familyI:\n  assumes \"ring R\"\n  assumes \"finite (carrier R)\"\n  assumes \"0 < k\"\n  shows \"poly_hash_family R k\"\n  using assms\n  by (simp add:poly_hash_family_def poly_hash_family_axioms_def)\n\nlemma carter_wegman_hash_familyI:\n  assumes \"field F\"\n  assumes \"finite (carrier F)\"\n  assumes \"0 < k\"\n  shows \"carter_wegman_hash_family F k\"\n  using assms field.is_ring[OF assms(1)] poly_hash_familyI\n  by (simp add:carter_wegman_hash_family_def carter_wegman_hash_family_axioms_def)\n\nlemma hash_k_wise_indep:\n  assumes \"field F \\<and> finite (carrier F)\"\n  assumes \"1 \\<le> n\"\n  shows\n    \"prob_space.k_wise_indep_vars (pmf_of_set (bounded_degree_polynomials F n)) n\n    (\\<lambda>_. pmf_of_set (carrier F)) (ring.hash F) (carrier F)\"\nproof -\n  interpret carter_wegman_hash_family \"F\" \"n\"\n    using assms carter_wegman_hash_familyI by force\n  have \"k_wise_indep_vars n (\\<lambda>_. pmf_of_set (carrier F)) hash (carrier F)\"\n    by (rule k_wise_indep_vars_compose[OF k_wise_indep], simp)\n  thus ?thesis\n    by (simp add:M_def space_def)\nqed\n\nlemma hash_prob_single:\n  assumes \"field F \\<and> finite (carrier F)\"\n  assumes \"x \\<in> carrier F\"\n  assumes \"1 \\<le> n\"\n  assumes \"y \\<in> carrier F\"\n  shows\n    \"\\<P>(\\<omega> in pmf_of_set (bounded_degree_polynomials F n). ring.hash F x \\<omega> = y)\n      = 1/(real (card (carrier F)))\"\nproof -\n  interpret carter_wegman_hash_family \"F\" \"n\"\n    using assms carter_wegman_hash_familyI by force\n  show ?thesis\n    using prob_single[OF assms(2,4)] by (simp add:M_def space_def)\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Universal_Hash_Families/Carter_Wegman_Hash_Family.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267660487572, "lm_q2_score": 0.8652240773641087, "lm_q1q2_score": 0.7517298370437783}}
{"text": "theory CadeInsa\n  imports Main \"Relation_Algebra/Relation_Algebra\" \"Relation_Algebra/Relation_Algebra_Functions\"  \"Relation_Algebra/Relation_Algebra_Models\"\n\nbegin \n\ncontext relation_algebra\nbegin\n\n(* definitions/predicates *)\ndefinition symmetric :: \"'a \\<Rightarrow> bool\"\n  where \"symmetric x \\<equiv> x=x\\<^sup>\\<smile>\"\n\ndefinition reflexive :: \"'a \\<Rightarrow> bool\"\n  where \"reflexive x \\<equiv> 1' \\<le> x\"\n\ndefinition irreflexive :: \"'a \\<Rightarrow> bool\"\n  where \"irreflexive x \\<equiv> x \\<le> -(1')\"\n\n\n(* the used libraries use different notation. We adapted the notions to fit our paper\n in case the definitions are slightly different, we show equivalence *)\ndefinition univalent :: \"'a \\<Rightarrow> bool\"\n  where \"univalent x \\<equiv> x\\<^sup>\\<smile>;x \\<le> 1'\"\nlemma \"univalent x = is_p_fun x\"\n  by(simp add: univalent_def is_p_fun_def)\n\ndefinition total :: \"'a \\<Rightarrow> bool\"\n  where \"total x \\<equiv> x;1=1\"\nlemma total_is_total: \"total x = is_total x\"\n  by (simp add: total_def total_def_var_1)\n\ndefinition is_function :: \"'a \\<Rightarrow> bool\"\n  where \"is_function  x \\<equiv> univalent x \\<and> total x\"\nlemma \"is_function x = is_map x\"\n  by (simp add: is_function_def is_map_def is_p_fun_def total_def_var_1 total_def univalent_def)\n\ndefinition injective :: \"'a \\<Rightarrow> bool\"\n  where \"injective x \\<equiv> univalent (x\\<^sup>\\<smile>)\"\nlemma \"injective x = is_inj x\"\n  unfolding injective_def is_inj_def univalent_def\n  by(simp)\n\ndefinition surjective :: \"'a \\<Rightarrow> bool\"\n  where \"surjective x \\<equiv> total (x\\<^sup>\\<smile>)\"\nlemma \"surjective x = is_sur x\"\n  by(simp add: surjective_def total_is_total is_total_def is_sur_def)\n\ndefinition coloringProperty\n  where \"coloringProperty x e \\<equiv> x;x\\<^sup>\\<smile> \\<le> -e\"\n\nlemmas unfold_defs = symmetric_def reflexive_def irreflexive_def univalent_def total_def is_function_def injective_def surjective_def\n                      coloringProperty_def is_p_fun_def is_point_def is_vector_def is_inj_def\n(* end definitions *)\n\n(* logical equivalences in the model of relations *)\nlemma rel_subset:\n  \"(\\<forall> x y. (x,y) \\<in> r \\<longrightarrow> (x,y) \\<in> s) = (r \\<subseteq> s)\"\nby(auto)\n\nlemma rel_reflexive:  \n  \"(\\<forall> x. (x,x) \\<in> r) = (Id \\<subseteq> r)\"\nby(simp add: subset_iff)\n\nlemma rel_irreflexive:  \n  \"(\\<forall> x y. (x,y) \\<in> r \\<longrightarrow> x \\<noteq> y) = (r \\<subseteq> -Id)\"\nby(auto)\n\nlemma rel_transitive:\n  \"(\\<forall> x y z. ((x,y) \\<in> r \\<and> (y,z) \\<in> r) \\<longrightarrow> (x,z) \\<in> r) = (r O r \\<subseteq> r)\"\nby(auto)\n\nlemma rel_symmetric:\n  \"(\\<forall> x y. (x,y) \\<in> r \\<longrightarrow> (y,x) \\<in> r) = (r =  r\\<inverse>)\"\nby(auto simp add: subset_iff)\n\nlemma rel_antisymmetric:\n  \"(\\<forall> x y. (x,y) \\<in> r \\<and> (y,x) \\<in> r \\<longrightarrow> x=y) = (r \\<inter> r\\<inverse> \\<subseteq> Id)\"\nby(simp add: subset_iff)\n\nlemma rel_asymmetric:\n  \"(\\<forall> x y. (x,y) \\<in> r \\<longrightarrow> (y,x) \\<notin> r) = (r \\<inter> r\\<inverse> = {})\"\nby(auto simp add: subset_iff)\n\nlemma rel_total:\n  \"(\\<forall> x y. (x,y) \\<in> r \\<or> (y,x) \\<in> r) = (UNIV = r \\<union> r\\<inverse>)\"\nby(auto simp add: subset_iff)\n(*end logical equivalences in the model of relations *)\n\n(* main lemmata of the paper *)\nlemma lemma31:\n \"univalent 0 \\<and> coloringProperty 0 e\"\n by(simp add: univalent_def coloringProperty_def)\n\nlemma lemma32:\n  assumes \"univalent x\"\n      and \"is_point p\"\n      and \"is_point q\"\n      and \"p \\<le> -(x;1)\"\n      shows \"univalent(x + p;q\\<^sup>\\<smile>)\"  \n\nproof (simp add: unfold_defs distrib_left distrib_right, safe)\n(* after unfolding sledgehammer is impressive *)\n\n  from assms(1) show \"x\\<^sup>\\<smile> ; x \\<le> 1'\"\n    by(unfold univalent_def)\n\n  from assms(4) show goal2: \"q ; p\\<^sup>\\<smile> ; x \\<le> 1'\"\n    by (metis compl_bot_eq compl_le_swap1 conv_galois_1 conv_galois_2 conv_one double_compl inf.boundedE inf_compl_bot mult_assoc)\n\n  from goal2 show \"x\\<^sup>\\<smile> ; (p ; q\\<^sup>\\<smile>) \\<le> 1'\"\n    by (metis conv_contrav conv_invol conv_iso mult_oner)\n\n  from assms(3) and assms(4) show \"q;p\\<^sup>\\<smile>;(p;q\\<^sup>\\<smile>)  \\<le> 1'\"\n    unfolding unfold_defs\n    by (metis dual_order.trans mult_isol mult_isor top_greatest mult_assoc)\nqed\n\nlemma lemma33:\n  assumes \"symmetric e\"\n      and \"irreflexive e\"\n      and \"is_point p\"\n      and \"is_point q\"\n      and \"coloringProperty x e\"\n      and \"q \\<le> -(x\\<^sup>\\<smile> ; e ; p)\"\n    shows \"coloringProperty (x + p;q\\<^sup>\\<smile>) e\"\nproof (simp add: unfold_defs distrib_left distrib_right, safe)\n\n  show goal1: \"x ; x\\<^sup>\\<smile> \\<le> -e\" by (metis assms(5) coloringProperty_def)\n\n  from assms(1) and assms(6) \n  show goal3: \"p ; q\\<^sup>\\<smile> ; x\\<^sup>\\<smile> \\<le> - e\"\n    by (metis symmetric_def comp_anti conv_galois_1 conv_galois_2 double_compl mult_assoc)\n\n  from goal3 show \"x ; (q ; p\\<^sup>\\<smile>) \\<le> - e\"\n    by (metis assms(6) conv_galois_1 conv_galois_2 conv_invol double_compl)\n\n  from assms(2) and assms(3) and assms(4) show \"p ; q\\<^sup>\\<smile> ; (q ; p\\<^sup>\\<smile>) \\<le> -e\"\n    unfolding unfold_defs\n    by (metis dual_order.trans mult_isol mult_isor top_greatest mult_assoc compl_le_swap1)\nqed\n\nlemma lemma21:\n  \"\\<lbrakk> is_point p ; is_point q ; (\\<forall> x. (x\\<noteq>0 \\<longrightarrow> 1 ; x ; 1 = 1)) \\<rbrakk> \\<Longrightarrow> p\\<noteq>0 \\<and> p;q\\<^sup>\\<smile> \\<noteq> 0\"\nunfolding unfold_defs\nby (metis mult_assoc sur_def_var1 sur_total total_1)\n\nlemma lemma34:\n  assumes \"is_point p\"\n      and \"is_point q\"\n      and \"x;1\\<noteq>1\"\n      and \"p \\<le> -(x;1)\"\n      and \"\\<forall> x. (x\\<noteq>0 \\<longrightarrow> 1 ; x ; 1 = 1)\"\n      shows \"x \\<le> x + p;q\\<^sup>\\<smile> \\<and> x \\<noteq> x + p;q\\<^sup>\\<smile> \"\nproof \n  show \"x \\<le> x + p;q\\<^sup>\\<smile>\" by simp\n\n  from assms have temp: \"p;q\\<^sup>\\<smile> \\<le> -x\"\n    unfolding is_point_def is_vector_def is_inj_def                                     \n    by (metis comp_anti comp_res_aux compl_bot_eq conv_galois_1 conv_galois_2 double_compl le_iff_inf order_trans top_greatest)\n  {\n    assume \"x = x + p;q\\<^sup>\\<smile>\" (* proof by contradiction *)\n     with assms(1) and assms(2) and assms(5) have \"False\" \n     by (metis aux6 inf.orderE inf_compl_bot temp lemma21)\n  }\n  then show \"x \\<noteq> x + p;q\\<^sup>\\<smile>\" by blast\nqed\n    \nend\nend", "meta": {"author": "insastucke", "repo": "RAProgramVerification", "sha": "e435b2d59ddd3c1e5ba94a38a532a29dc040c015", "save_path": "github-repos/isabelle/insastucke-RAProgramVerification", "path": "github-repos/isabelle/insastucke-RAProgramVerification/RAProgramVerification-e435b2d59ddd3c1e5ba94a38a532a29dc040c015/RelationalColoring/Isabelle/ColoringIsabelle.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.8333245870332531, "lm_q1q2_score": 0.7515926840933271}}
{"text": "(*  Title:      HOL/Power.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1997  University of Cambridge\n*)\n\nsection {* Exponentiation *}\n\ntheory Power\nimports Num Equiv_Relations\nbegin\n\nsubsection {* Powers for Arbitrary Monoids *}\n\nclass power = one + times\nbegin\n\nprimrec power :: \"'a \\<Rightarrow> nat \\<Rightarrow> 'a\" (infixr \"^\" 80) where\n    power_0: \"a ^ 0 = 1\"\n  | power_Suc: \"a ^ Suc n = a * a ^ n\"\n\nnotation (latex output)\n  power (\"(_\\<^bsup>_\\<^esup>)\" [1000] 1000)\n\nnotation (HTML output)\n  power (\"(_\\<^bsup>_\\<^esup>)\" [1000] 1000)\n\ntext {* Special syntax for squares. *}\n\nabbreviation (xsymbols)\n  power2 :: \"'a \\<Rightarrow> 'a\"  (\"(_\\<^sup>2)\" [1000] 999) where\n  \"x\\<^sup>2 \\<equiv> x ^ 2\"\n\nnotation (latex output)\n  power2  (\"(_\\<^sup>2)\" [1000] 999)\n\nnotation (HTML output)\n  power2  (\"(_\\<^sup>2)\" [1000] 999)\n\nend\n\ncontext monoid_mult\nbegin\n\nsubclass power .\n\nlemma power_one [simp]:\n  \"1 ^ n = 1\"\n  by (induct n) simp_all\n\nlemma power_one_right [simp]:\n  \"a ^ 1 = a\"\n  by simp\n\nlemma power_commutes:\n  \"a ^ n * a = a * a ^ n\"\n  by (induct n) (simp_all add: mult.assoc)\n\nlemma power_Suc2:\n  \"a ^ Suc n = a ^ n * a\"\n  by (simp add: power_commutes)\n\nlemma power_add:\n  \"a ^ (m + n) = a ^ m * a ^ n\"\n  by (induct m) (simp_all add: algebra_simps)\n\nlemma power_mult:\n  \"a ^ (m * n) = (a ^ m) ^ n\"\n  by (induct n) (simp_all add: power_add)\n\nlemma power2_eq_square: \"a\\<^sup>2 = a * a\"\n  by (simp add: numeral_2_eq_2)\n\nlemma power3_eq_cube: \"a ^ 3 = a * a * a\"\n  by (simp add: numeral_3_eq_3 mult.assoc)\n\nlemma power_even_eq:\n  \"a ^ (2 * n) = (a ^ n)\\<^sup>2\"\n  by (subst mult.commute) (simp add: power_mult)\n\nlemma power_odd_eq:\n  \"a ^ Suc (2*n) = a * (a ^ n)\\<^sup>2\"\n  by (simp add: power_even_eq)\n\nlemma power_numeral_even:\n  \"z ^ numeral (Num.Bit0 w) = (let w = z ^ (numeral w) in w * w)\"\n  unfolding numeral_Bit0 power_add Let_def ..\n\nlemma power_numeral_odd:\n  \"z ^ numeral (Num.Bit1 w) = (let w = z ^ (numeral w) in z * w * w)\"\n  unfolding numeral_Bit1 One_nat_def add_Suc_right add_0_right\n  unfolding power_Suc power_add Let_def mult.assoc ..\n\nlemma funpow_times_power:\n  \"(times x ^^ f x) = times (x ^ f x)\"\nproof (induct \"f x\" arbitrary: f)\n  case 0 then show ?case by (simp add: fun_eq_iff)\nnext\n  case (Suc n)\n  def g \\<equiv> \"\\<lambda>x. f x - 1\"\n  with Suc have \"n = g x\" by simp\n  with Suc have \"times x ^^ g x = times (x ^ g x)\" by simp\n  moreover from Suc g_def have \"f x = g x + 1\" by simp\n  ultimately show ?case by (simp add: power_add funpow_add fun_eq_iff mult.assoc)\nqed\n\nlemma power_commuting_commutes:\n  assumes \"x * y = y * x\"\n  shows \"x ^ n * y = y * x ^n\"\nproof (induct n)\n  case (Suc n)\n  have \"x ^ Suc n * y = x ^ n * y * x\"\n    by (subst power_Suc2) (simp add: assms ac_simps)\n  also have \"\\<dots> = y * x ^ Suc n\"\n    unfolding Suc power_Suc2\n    by (simp add: ac_simps)\n  finally show ?case .\nqed simp\n\nend\n\ncontext comm_monoid_mult\nbegin\n\nlemma power_mult_distrib [field_simps]:\n  \"(a * b) ^ n = (a ^ n) * (b ^ n)\"\n  by (induct n) (simp_all add: ac_simps)\n\nend\n\ncontext semiring_numeral\nbegin\n\nlemma numeral_sqr: \"numeral (Num.sqr k) = numeral k * numeral k\"\n  by (simp only: sqr_conv_mult numeral_mult)\n\nlemma numeral_pow: \"numeral (Num.pow k l) = numeral k ^ numeral l\"\n  by (induct l, simp_all only: numeral_class.numeral.simps pow.simps\n    numeral_sqr numeral_mult power_add power_one_right)\n\nlemma power_numeral [simp]: \"numeral k ^ numeral l = numeral (Num.pow k l)\"\n  by (rule numeral_pow [symmetric])\n\nend\n\ncontext semiring_1\nbegin\n\n\n\nlemma zero_power:\n  \"0 < n \\<Longrightarrow> 0 ^ n = 0\"\n  by (cases n) simp_all\n\nlemma power_zero_numeral [simp]:\n  \"0 ^ numeral k = 0\"\n  by (simp add: numeral_eq_Suc)\n\nlemma zero_power2: \"0\\<^sup>2 = 0\" (* delete? *)\n  by (rule power_zero_numeral)\n\nlemma one_power2: \"1\\<^sup>2 = 1\" (* delete? *)\n  by (rule power_one)\n\nend\n\ncontext comm_semiring_1\nbegin\n\ntext {* The divides relation *}\n\nlemma le_imp_power_dvd:\n  assumes \"m \\<le> n\" shows \"a ^ m dvd a ^ n\"\nproof\n  have \"a ^ n = a ^ (m + (n - m))\"\n    using `m \\<le> n` by simp\n  also have \"\\<dots> = a ^ m * a ^ (n - m)\"\n    by (rule power_add)\n  finally show \"a ^ n = a ^ m * a ^ (n - m)\" .\nqed\n\nlemma power_le_dvd:\n  \"a ^ n dvd b \\<Longrightarrow> m \\<le> n \\<Longrightarrow> a ^ m dvd b\"\n  by (rule dvd_trans [OF le_imp_power_dvd])\n\nlemma dvd_power_same:\n  \"x dvd y \\<Longrightarrow> x ^ n dvd y ^ n\"\n  by (induct n) (auto simp add: mult_dvd_mono)\n\nlemma dvd_power_le:\n  \"x dvd y \\<Longrightarrow> m \\<ge> n \\<Longrightarrow> x ^ n dvd y ^ m\"\n  by (rule power_le_dvd [OF dvd_power_same])\n\nlemma dvd_power [simp]:\n  assumes \"n > (0::nat) \\<or> x = 1\"\n  shows \"x dvd (x ^ n)\"\nusing assms proof\n  assume \"0 < n\"\n  then have \"x ^ n = x ^ Suc (n - 1)\" by simp\n  then show \"x dvd (x ^ n)\" by simp\nnext\n  assume \"x = 1\"\n  then show \"x dvd (x ^ n)\" by simp\nqed\n\nend\n\ncontext ring_1\nbegin\n\nlemma power_minus:\n  \"(- a) ^ n = (- 1) ^ n * a ^ n\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n) then show ?case\n    by (simp del: power_Suc add: power_Suc2 mult.assoc)\nqed\n\nlemma power_minus_Bit0:\n  \"(- x) ^ numeral (Num.Bit0 k) = x ^ numeral (Num.Bit0 k)\"\n  by (induct k, simp_all only: numeral_class.numeral.simps power_add\n    power_one_right mult_minus_left mult_minus_right minus_minus)\n\nlemma power_minus_Bit1:\n  \"(- x) ^ numeral (Num.Bit1 k) = - (x ^ numeral (Num.Bit1 k))\"\n  by (simp only: eval_nat_numeral(3) power_Suc power_minus_Bit0 mult_minus_left)\n\nlemma power2_minus [simp]:\n  \"(- a)\\<^sup>2 = a\\<^sup>2\"\n  by (rule power_minus_Bit0)\n\nlemma power_minus1_even [simp]:\n  \"(- 1) ^ (2*n) = 1\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n) then show ?case by (simp add: power_add power2_eq_square)\nqed\n\nlemma power_minus1_odd:\n  \"(- 1) ^ Suc (2*n) = -1\"\n  by simp\n\nlemma power_minus_even [simp]:\n  \"(-a) ^ (2*n) = a ^ (2*n)\"\n  by (simp add: power_minus [of a])\n\nend\n\nlemma power_eq_0_nat_iff [simp]:\n  fixes m n :: nat\n  shows \"m ^ n = 0 \\<longleftrightarrow> m = 0 \\<and> n > 0\"\n  by (induct n) auto\n\ncontext ring_1_no_zero_divisors\nbegin\n\nlemma power_eq_0_iff [simp]:\n  \"a ^ n = 0 \\<longleftrightarrow> a = 0 \\<and> n > 0\"\n  by (induct n) auto\n\nlemma field_power_not_zero:\n  \"a \\<noteq> 0 \\<Longrightarrow> a ^ n \\<noteq> 0\"\n  by (induct n) auto\n\nlemma zero_eq_power2 [simp]:\n  \"a\\<^sup>2 = 0 \\<longleftrightarrow> a = 0\"\n  unfolding power2_eq_square by simp\n\nlemma power2_eq_1_iff:\n  \"a\\<^sup>2 = 1 \\<longleftrightarrow> a = 1 \\<or> a = - 1\"\n  unfolding power2_eq_square by (rule square_eq_1_iff)\n\nend\n\ncontext idom\nbegin\n\nlemma power2_eq_iff: \"x\\<^sup>2 = y\\<^sup>2 \\<longleftrightarrow> x = y \\<or> x = - y\"\n  unfolding power2_eq_square by (rule square_eq_iff)\n\nend\n\ncontext division_ring\nbegin\n\ntext {* FIXME reorient or rename to @{text nonzero_inverse_power} *}\nlemma nonzero_power_inverse:\n  \"a \\<noteq> 0 \\<Longrightarrow> inverse (a ^ n) = (inverse a) ^ n\"\n  by (induct n)\n    (simp_all add: nonzero_inverse_mult_distrib power_commutes field_power_not_zero)\n\nend\n\ncontext field\nbegin\n\nlemma nonzero_power_divide:\n  \"b \\<noteq> 0 \\<Longrightarrow> (a / b) ^ n = a ^ n / b ^ n\"\n  by (simp add: divide_inverse power_mult_distrib nonzero_power_inverse)\n\nend\n\n\nsubsection {* Exponentiation on ordered types *}\n\ncontext linordered_ring (* TODO: move *)\nbegin\n\nlemma sum_squares_ge_zero:\n  \"0 \\<le> x * x + y * y\"\n  by (intro add_nonneg_nonneg zero_le_square)\n\nlemma not_sum_squares_lt_zero:\n  \"\\<not> x * x + y * y < 0\"\n  by (simp add: not_less sum_squares_ge_zero)\n\nend\n\ncontext linordered_semidom\nbegin\n\nlemma zero_less_power [simp]:\n  \"0 < a \\<Longrightarrow> 0 < a ^ n\"\n  by (induct n) simp_all\n\nlemma zero_le_power [simp]:\n  \"0 \\<le> a \\<Longrightarrow> 0 \\<le> a ^ n\"\n  by (induct n) simp_all\n\nlemma power_mono:\n  \"a \\<le> b \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a ^ n \\<le> b ^ n\"\n  by (induct n) (auto intro: mult_mono order_trans [of 0 a b])\n\nlemma one_le_power [simp]: \"1 \\<le> a \\<Longrightarrow> 1 \\<le> a ^ n\"\n  using power_mono [of 1 a n] by simp\n\nlemma power_le_one: \"\\<lbrakk>0 \\<le> a; a \\<le> 1\\<rbrakk> \\<Longrightarrow> a ^ n \\<le> 1\"\n  using power_mono [of a 1 n] by simp\n\nlemma power_gt1_lemma:\n  assumes gt1: \"1 < a\"\n  shows \"1 < a * a ^ n\"\nproof -\n  from gt1 have \"0 \\<le> a\"\n    by (fact order_trans [OF zero_le_one less_imp_le])\n  have \"1 * 1 < a * 1\" using gt1 by simp\n  also have \"\\<dots> \\<le> a * a ^ n\" using gt1\n    by (simp only: mult_mono `0 \\<le> a` one_le_power order_less_imp_le\n        zero_le_one order_refl)\n  finally show ?thesis by simp\nqed\n\nlemma power_gt1:\n  \"1 < a \\<Longrightarrow> 1 < a ^ Suc n\"\n  by (simp add: power_gt1_lemma)\n\nlemma one_less_power [simp]:\n  \"1 < a \\<Longrightarrow> 0 < n \\<Longrightarrow> 1 < a ^ n\"\n  by (cases n) (simp_all add: power_gt1_lemma)\n\nlemma power_le_imp_le_exp:\n  assumes gt1: \"1 < a\"\n  shows \"a ^ m \\<le> a ^ n \\<Longrightarrow> m \\<le> n\"\nproof (induct m arbitrary: n)\n  case 0\n  show ?case by simp\nnext\n  case (Suc m)\n  show ?case\n  proof (cases n)\n    case 0\n    with Suc.prems Suc.hyps have \"a * a ^ m \\<le> 1\" by simp\n    with gt1 show ?thesis\n      by (force simp only: power_gt1_lemma\n          not_less [symmetric])\n  next\n    case (Suc n)\n    with Suc.prems Suc.hyps show ?thesis\n      by (force dest: mult_left_le_imp_le\n          simp add: less_trans [OF zero_less_one gt1])\n  qed\nqed\n\ntext{*Surely we can strengthen this? It holds for @{text \"0<a<1\"} too.*}\nlemma power_inject_exp [simp]:\n  \"1 < a \\<Longrightarrow> a ^ m = a ^ n \\<longleftrightarrow> m = n\"\n  by (force simp add: order_antisym power_le_imp_le_exp)\n\ntext{*Can relax the first premise to @{term \"0<a\"} in the case of the\nnatural numbers.*}\nlemma power_less_imp_less_exp:\n  \"1 < a \\<Longrightarrow> a ^ m < a ^ n \\<Longrightarrow> m < n\"\n  by (simp add: order_less_le [of m n] less_le [of \"a^m\" \"a^n\"]\n    power_le_imp_le_exp)\n\nlemma power_strict_mono [rule_format]:\n  \"a < b \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 < n \\<longrightarrow> a ^ n < b ^ n\"\n  by (induct n)\n   (auto simp add: mult_strict_mono le_less_trans [of 0 a b])\n\ntext{*Lemma for @{text power_strict_decreasing}*}\nlemma power_Suc_less:\n  \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a * a ^ n < a ^ n\"\n  by (induct n)\n    (auto simp add: mult_strict_left_mono)\n\nlemma power_strict_decreasing [rule_format]:\n  \"n < N \\<Longrightarrow> 0 < a \\<Longrightarrow> a < 1 \\<longrightarrow> a ^ N < a ^ n\"\nproof (induct N)\n  case 0 then show ?case by simp\nnext\n  case (Suc N) then show ?case \n  apply (auto simp add: power_Suc_less less_Suc_eq)\n  apply (subgoal_tac \"a * a^N < 1 * a^n\")\n  apply simp\n  apply (rule mult_strict_mono) apply auto\n  done\nqed\n\ntext{*Proof resembles that of @{text power_strict_decreasing}*}\nlemma power_decreasing [rule_format]:\n  \"n \\<le> N \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> a \\<le> 1 \\<longrightarrow> a ^ N \\<le> a ^ n\"\nproof (induct N)\n  case 0 then show ?case by simp\nnext\n  case (Suc N) then show ?case \n  apply (auto simp add: le_Suc_eq)\n  apply (subgoal_tac \"a * a^N \\<le> 1 * a^n\", simp)\n  apply (rule mult_mono) apply auto\n  done\nqed\n\nlemma power_Suc_less_one:\n  \"0 < a \\<Longrightarrow> a < 1 \\<Longrightarrow> a ^ Suc n < 1\"\n  using power_strict_decreasing [of 0 \"Suc n\" a] by simp\n\ntext{*Proof again resembles that of @{text power_strict_decreasing}*}\nlemma power_increasing [rule_format]:\n  \"n \\<le> N \\<Longrightarrow> 1 \\<le> a \\<Longrightarrow> a ^ n \\<le> a ^ N\"\nproof (induct N)\n  case 0 then show ?case by simp\nnext\n  case (Suc N) then show ?case \n  apply (auto simp add: le_Suc_eq)\n  apply (subgoal_tac \"1 * a^n \\<le> a * a^N\", simp)\n  apply (rule mult_mono) apply (auto simp add: order_trans [OF zero_le_one])\n  done\nqed\n\ntext{*Lemma for @{text power_strict_increasing}*}\nlemma power_less_power_Suc:\n  \"1 < a \\<Longrightarrow> a ^ n < a * a ^ n\"\n  by (induct n) (auto simp add: mult_strict_left_mono less_trans [OF zero_less_one])\n\nlemma power_strict_increasing [rule_format]:\n  \"n < N \\<Longrightarrow> 1 < a \\<longrightarrow> a ^ n < a ^ N\"\nproof (induct N)\n  case 0 then show ?case by simp\nnext\n  case (Suc N) then show ?case \n  apply (auto simp add: power_less_power_Suc less_Suc_eq)\n  apply (subgoal_tac \"1 * a^n < a * a^N\", simp)\n  apply (rule mult_strict_mono) apply (auto simp add: less_trans [OF zero_less_one] less_imp_le)\n  done\nqed\n\nlemma power_increasing_iff [simp]:\n  \"1 < b \\<Longrightarrow> b ^ x \\<le> b ^ y \\<longleftrightarrow> x \\<le> y\"\n  by (blast intro: power_le_imp_le_exp power_increasing less_imp_le)\n\nlemma power_strict_increasing_iff [simp]:\n  \"1 < b \\<Longrightarrow> b ^ x < b ^ y \\<longleftrightarrow> x < y\"\nby (blast intro: power_less_imp_less_exp power_strict_increasing) \n\nlemma power_le_imp_le_base:\n  assumes le: \"a ^ Suc n \\<le> b ^ Suc n\"\n    and ynonneg: \"0 \\<le> b\"\n  shows \"a \\<le> b\"\nproof (rule ccontr)\n  assume \"~ a \\<le> b\"\n  then have \"b < a\" by (simp only: linorder_not_le)\n  then have \"b ^ Suc n < a ^ Suc n\"\n    by (simp only: assms power_strict_mono)\n  from le and this show False\n    by (simp add: linorder_not_less [symmetric])\nqed\n\nlemma power_less_imp_less_base:\n  assumes less: \"a ^ n < b ^ n\"\n  assumes nonneg: \"0 \\<le> b\"\n  shows \"a < b\"\nproof (rule contrapos_pp [OF less])\n  assume \"~ a < b\"\n  hence \"b \\<le> a\" by (simp only: linorder_not_less)\n  hence \"b ^ n \\<le> a ^ n\" using nonneg by (rule power_mono)\n  thus \"\\<not> a ^ n < b ^ n\" by (simp only: linorder_not_less)\nqed\n\nlemma power_inject_base:\n  \"a ^ Suc n = b ^ Suc n \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> a = b\"\nby (blast intro: power_le_imp_le_base antisym eq_refl sym)\n\nlemma power_eq_imp_eq_base:\n  \"a ^ n = b ^ n \\<Longrightarrow> 0 \\<le> a \\<Longrightarrow> 0 \\<le> b \\<Longrightarrow> 0 < n \\<Longrightarrow> a = b\"\n  by (cases n) (simp_all del: power_Suc, rule power_inject_base)\n\nlemma power2_le_imp_le:\n  \"x\\<^sup>2 \\<le> y\\<^sup>2 \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x \\<le> y\"\n  unfolding numeral_2_eq_2 by (rule power_le_imp_le_base)\n\nlemma power2_less_imp_less:\n  \"x\\<^sup>2 < y\\<^sup>2 \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x < y\"\n  by (rule power_less_imp_less_base)\n\nlemma power2_eq_imp_eq:\n  \"x\\<^sup>2 = y\\<^sup>2 \\<Longrightarrow> 0 \\<le> x \\<Longrightarrow> 0 \\<le> y \\<Longrightarrow> x = y\"\n  unfolding numeral_2_eq_2 by (erule (2) power_eq_imp_eq_base) simp\n\nend\n\ncontext linordered_ring_strict\nbegin\n\nlemma sum_squares_eq_zero_iff:\n  \"x * x + y * y = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (simp add: add_nonneg_eq_0_iff)\n\nlemma sum_squares_le_zero_iff:\n  \"x * x + y * y \\<le> 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (simp add: le_less not_sum_squares_lt_zero sum_squares_eq_zero_iff)\n\nlemma sum_squares_gt_zero_iff:\n  \"0 < x * x + y * y \\<longleftrightarrow> x \\<noteq> 0 \\<or> y \\<noteq> 0\"\n  by (simp add: not_le [symmetric] sum_squares_le_zero_iff)\n\nend\n\ncontext linordered_idom\nbegin\n\nlemma power_abs:\n  \"abs (a ^ n) = abs a ^ n\"\n  by (induct n) (auto simp add: abs_mult)\n\nlemma abs_power_minus [simp]:\n  \"abs ((-a) ^ n) = abs (a ^ n)\"\n  by (simp add: power_abs)\n\nlemma zero_less_power_abs_iff [simp]:\n  \"0 < abs a ^ n \\<longleftrightarrow> a \\<noteq> 0 \\<or> n = 0\"\nproof (induct n)\n  case 0 show ?case by simp\nnext\n  case (Suc n) show ?case by (auto simp add: Suc zero_less_mult_iff)\nqed\n\nlemma zero_le_power_abs [simp]:\n  \"0 \\<le> abs a ^ n\"\n  by (rule zero_le_power [OF abs_ge_zero])\n\nlemma zero_le_power2 [simp]:\n  \"0 \\<le> a\\<^sup>2\"\n  by (simp add: power2_eq_square)\n\nlemma zero_less_power2 [simp]:\n  \"0 < a\\<^sup>2 \\<longleftrightarrow> a \\<noteq> 0\"\n  by (force simp add: power2_eq_square zero_less_mult_iff linorder_neq_iff)\n\nlemma power2_less_0 [simp]:\n  \"\\<not> a\\<^sup>2 < 0\"\n  by (force simp add: power2_eq_square mult_less_0_iff)\n\nlemma power2_less_eq_zero_iff [simp]:\n  \"a\\<^sup>2 \\<le> 0 \\<longleftrightarrow> a = 0\"\n  by (simp add: le_less)\n\nlemma abs_power2 [simp]:\n  \"abs (a\\<^sup>2) = a\\<^sup>2\"\n  by (simp add: power2_eq_square abs_mult abs_mult_self)\n\nlemma power2_abs [simp]:\n  \"(abs a)\\<^sup>2 = a\\<^sup>2\"\n  by (simp add: power2_eq_square abs_mult_self)\n\nlemma odd_power_less_zero:\n  \"a < 0 \\<Longrightarrow> a ^ Suc (2*n) < 0\"\nproof (induct n)\n  case 0\n  then show ?case by simp\nnext\n  case (Suc n)\n  have \"a ^ Suc (2 * Suc n) = (a*a) * a ^ Suc(2*n)\"\n    by (simp add: ac_simps power_add power2_eq_square)\n  thus ?case\n    by (simp del: power_Suc add: Suc mult_less_0_iff mult_neg_neg)\nqed\n\nlemma odd_0_le_power_imp_0_le:\n  \"0 \\<le> a ^ Suc (2*n) \\<Longrightarrow> 0 \\<le> a\"\n  using odd_power_less_zero [of a n]\n    by (force simp add: linorder_not_less [symmetric]) \n\nlemma zero_le_even_power'[simp]:\n  \"0 \\<le> a ^ (2*n)\"\nproof (induct n)\n  case 0\n    show ?case by simp\nnext\n  case (Suc n)\n    have \"a ^ (2 * Suc n) = (a*a) * a ^ (2*n)\" \n      by (simp add: ac_simps power_add power2_eq_square)\n    thus ?case\n      by (simp add: Suc zero_le_mult_iff)\nqed\n\nlemma sum_power2_ge_zero:\n  \"0 \\<le> x\\<^sup>2 + y\\<^sup>2\"\n  by (intro add_nonneg_nonneg zero_le_power2)\n\nlemma not_sum_power2_lt_zero:\n  \"\\<not> x\\<^sup>2 + y\\<^sup>2 < 0\"\n  unfolding not_less by (rule sum_power2_ge_zero)\n\nlemma sum_power2_eq_zero_iff:\n  \"x\\<^sup>2 + y\\<^sup>2 = 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  unfolding power2_eq_square by (simp add: add_nonneg_eq_0_iff)\n\nlemma sum_power2_le_zero_iff:\n  \"x\\<^sup>2 + y\\<^sup>2 \\<le> 0 \\<longleftrightarrow> x = 0 \\<and> y = 0\"\n  by (simp add: le_less sum_power2_eq_zero_iff not_sum_power2_lt_zero)\n\nlemma sum_power2_gt_zero_iff:\n  \"0 < x\\<^sup>2 + y\\<^sup>2 \\<longleftrightarrow> x \\<noteq> 0 \\<or> y \\<noteq> 0\"\n  unfolding not_le [symmetric] by (simp add: sum_power2_le_zero_iff)\n\nend\n\n\nsubsection {* Miscellaneous rules *}\n\nlemma self_le_power:\n  fixes x::\"'a::linordered_semidom\" \n  shows \"1 \\<le> x \\<Longrightarrow> 0 < n \\<Longrightarrow> x \\<le> x ^ n\"\n  using power_increasing[of 1 n x] power_one_right[of x] by auto\n\nlemma power_eq_if: \"p ^ m = (if m=0 then 1 else p * (p ^ (m - 1)))\"\n  unfolding One_nat_def by (cases m) simp_all\n\nlemma (in comm_semiring_1) power2_sum:\n  \"(x + y)\\<^sup>2 = x\\<^sup>2 + y\\<^sup>2 + 2 * x * y\"\n  by (simp add: algebra_simps power2_eq_square mult_2_right)\n\nlemma (in comm_ring_1) power2_diff:\n  \"(x - y)\\<^sup>2 = x\\<^sup>2 + y\\<^sup>2 - 2 * x * y\"\n  by (simp add: algebra_simps power2_eq_square mult_2_right)\n\nlemma power_0_Suc [simp]:\n  \"(0::'a::{power, semiring_0}) ^ Suc n = 0\"\n  by simp\n\ntext{*It looks plausible as a simprule, but its effect can be strange.*}\nlemma power_0_left:\n  \"0 ^ n = (if n = 0 then 1 else (0::'a::{power, semiring_0}))\"\n  by (induct n) simp_all\n\nlemma (in field) power_diff:\n  assumes nz: \"a \\<noteq> 0\"\n  shows \"n \\<le> m \\<Longrightarrow> a ^ (m - n) = a ^ m / a ^ n\"\n  by (induct m n rule: diff_induct) (simp_all add: nz field_power_not_zero)\n\ntext{*Perhaps these should be simprules.*}\nlemma power_inverse:\n  fixes a :: \"'a::division_ring_inverse_zero\"\n  shows \"inverse (a ^ n) = inverse a ^ n\"\napply (cases \"a = 0\")\napply (simp add: power_0_left)\napply (simp add: nonzero_power_inverse)\ndone (* TODO: reorient or rename to inverse_power *)\n\nlemma power_one_over:\n  \"1 / (a::'a::{field_inverse_zero, power}) ^ n =  (1 / a) ^ n\"\n  by (simp add: divide_inverse) (rule power_inverse)\n\nlemma power_divide [field_simps, divide_simps]:\n  \"(a / b) ^ n = (a::'a::field_inverse_zero) ^ n / b ^ n\"\napply (cases \"b = 0\")\napply (simp add: power_0_left)\napply (rule nonzero_power_divide)\napply assumption\ndone\n\ntext {* Simprules for comparisons where common factors can be cancelled. *}\n\nlemmas zero_compare_simps =\n    add_strict_increasing add_strict_increasing2 add_increasing\n    zero_le_mult_iff zero_le_divide_iff \n    zero_less_mult_iff zero_less_divide_iff \n    mult_le_0_iff divide_le_0_iff \n    mult_less_0_iff divide_less_0_iff \n    zero_le_power2 power2_less_0\n\n\nsubsection {* Exponentiation for the Natural Numbers *}\n\nlemma nat_one_le_power [simp]:\n  \"Suc 0 \\<le> i \\<Longrightarrow> Suc 0 \\<le> i ^ n\"\n  by (rule one_le_power [of i n, unfolded One_nat_def])\n\nlemma nat_zero_less_power_iff [simp]:\n  \"x ^ n > 0 \\<longleftrightarrow> x > (0::nat) \\<or> n = 0\"\n  by (induct n) auto\n\nlemma nat_power_eq_Suc_0_iff [simp]: \n  \"x ^ m = Suc 0 \\<longleftrightarrow> m = 0 \\<or> x = Suc 0\"\n  by (induct m) auto\n\nlemma power_Suc_0 [simp]:\n  \"Suc 0 ^ n = Suc 0\"\n  by simp\n\ntext{*Valid for the naturals, but what if @{text\"0<i<1\"}?\nPremises cannot be weakened: consider the case where @{term \"i=0\"},\n@{term \"m=1\"} and @{term \"n=0\"}.*}\nlemma nat_power_less_imp_less:\n  assumes nonneg: \"0 < (i\\<Colon>nat)\"\n  assumes less: \"i ^ m < i ^ n\"\n  shows \"m < n\"\nproof (cases \"i = 1\")\n  case True with less power_one [where 'a = nat] show ?thesis by simp\nnext\n  case False with nonneg have \"1 < i\" by auto\n  from power_strict_increasing_iff [OF this] less show ?thesis ..\nqed\n\nlemma power_dvd_imp_le:\n  \"i ^ m dvd i ^ n \\<Longrightarrow> (1::nat) < i \\<Longrightarrow> m \\<le> n\"\n  apply (rule power_le_imp_le_exp, assumption)\n  apply (erule dvd_imp_le, simp)\n  done\n\nlemma power2_nat_le_eq_le:\n  fixes m n :: nat\n  shows \"m\\<^sup>2 \\<le> n\\<^sup>2 \\<longleftrightarrow> m \\<le> n\"\n  by (auto intro: power2_le_imp_le power_mono)\n\nlemma power2_nat_le_imp_le:\n  fixes m n :: nat\n  assumes \"m\\<^sup>2 \\<le> n\"\n  shows \"m \\<le> n\"\nproof (cases m)\n  case 0 then show ?thesis by simp\nnext\n  case (Suc k)\n  show ?thesis\n  proof (rule ccontr)\n    assume \"\\<not> m \\<le> n\"\n    then have \"n < m\" by simp\n    with assms Suc show False\n      by (auto simp add: algebra_simps) (simp add: power2_eq_square)\n  qed\nqed\n\nsubsubsection {* Cardinality of the Powerset *}\n\nlemma card_UNIV_bool [simp]: \"card (UNIV :: bool set) = 2\"\n  unfolding UNIV_bool by simp\n\nlemma card_Pow: \"finite A \\<Longrightarrow> card (Pow A) = 2 ^ card A\"\nproof (induct rule: finite_induct)\n  case empty \n    show ?case by auto\nnext\n  case (insert x A)\n  then have \"inj_on (insert x) (Pow A)\" \n    unfolding inj_on_def by (blast elim!: equalityE)\n  then have \"card (Pow A) + card (insert x ` Pow A) = 2 * 2 ^ card A\" \n    by (simp add: mult_2 card_image Pow_insert insert.hyps)\n  then show ?case using insert\n    apply (simp add: Pow_insert)\n    apply (subst card_Un_disjoint, auto)\n    done\nqed\n\n\nsubsubsection {* Generalized sum over a set *}\n\nlemma setsum_zero_power [simp]:\n  fixes c :: \"nat \\<Rightarrow> 'a::division_ring\"\n  shows \"(\\<Sum>i\\<in>A. c i * 0^i) = (if finite A \\<and> 0 \\<in> A then c 0 else 0)\"\napply (cases \"finite A\")\n  by (induction A rule: finite_induct) auto\n\nlemma setsum_zero_power' [simp]:\n  fixes c :: \"nat \\<Rightarrow> 'a::field\"\n  shows \"(\\<Sum>i\\<in>A. c i * 0^i / d i) = (if finite A \\<and> 0 \\<in> A then c 0 / d 0 else 0)\"\n  using setsum_zero_power [of \"\\<lambda>i. c i / d i\" A]\n  by auto\n\n\nsubsubsection {* Generalized product over a set *}\n\nlemma setprod_constant: \"finite A ==> (\\<Prod>x\\<in> A. (y::'a::{comm_monoid_mult})) = y^(card A)\"\napply (erule finite_induct)\napply auto\ndone\n\nlemma setprod_power_distrib:\n  fixes f :: \"'a \\<Rightarrow> 'b::comm_semiring_1\"\n  shows \"setprod f A ^ n = setprod (\\<lambda>x. (f x) ^ n) A\"\nproof (cases \"finite A\") \n  case True then show ?thesis \n    by (induct A rule: finite_induct) (auto simp add: power_mult_distrib)\nnext\n  case False then show ?thesis \n    by simp\nqed\n\nlemma power_setsum:\n  \"c ^ (\\<Sum>a\\<in>A. f a) = (\\<Prod>a\\<in>A. c ^ f a)\"\n  by (induct A rule: infinite_finite_induct) (simp_all add: power_add)\n\nlemma setprod_gen_delta:\n  assumes fS: \"finite S\"\n  shows \"setprod (\\<lambda>k. if k=a then b k else c) S = (if a \\<in> S then (b a ::'a::comm_monoid_mult) * c^ (card S - 1) else c^ card S)\"\nproof-\n  let ?f = \"(\\<lambda>k. if k=a then b k else c)\"\n  {assume a: \"a \\<notin> S\"\n    hence \"\\<forall> k\\<in> S. ?f k = c\" by simp\n    hence ?thesis  using a setprod_constant[OF fS, of c] by simp }\n  moreover \n  {assume a: \"a \\<in> S\"\n    let ?A = \"S - {a}\"\n    let ?B = \"{a}\"\n    have eq: \"S = ?A \\<union> ?B\" using a by blast \n    have dj: \"?A \\<inter> ?B = {}\" by simp\n    from fS have fAB: \"finite ?A\" \"finite ?B\" by auto  \n    have fA0:\"setprod ?f ?A = setprod (\\<lambda>i. c) ?A\"\n      apply (rule setprod.cong) by auto\n    have cA: \"card ?A = card S - 1\" using fS a by auto\n    have fA1: \"setprod ?f ?A = c ^ card ?A\"  unfolding fA0 apply (rule setprod_constant) using fS by auto\n    have \"setprod ?f ?A * setprod ?f ?B = setprod ?f S\"\n      using setprod.union_disjoint[OF fAB dj, of ?f, unfolded eq[symmetric]]\n      by simp\n    then have ?thesis using a cA\n      by (simp add: fA1 field_simps cong add: setprod.cong cong del: if_weak_cong)}\n  ultimately show ?thesis by blast\nqed\n\nsubsection {* Code generator tweak *}\n\nlemma power_power_power [code]:\n  \"power = power.power (1::'a::{power}) (op *)\"\n  unfolding power_def power.power_def ..\n\ndeclare power.power.simps [code]\n\ncode_identifier\n  code_module Power \\<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/Power.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.8615382147637196, "lm_q1q2_score": 0.7515606084116686}}
{"text": "(*\n  File:     Regexp_Constructions.thy\n  Author:   Manuel Eberl <manuel@pruvisto.org>\n\n  Some simple constructions on regular expressions to illustrate closure properties of regular\n  languages: reversal, substitution, prefixes, suffixes, subwords (\"fragments\")\n*)\nsection \\<open>Basic constructions on regular expressions\\<close>\ntheory Regexp_Constructions\nimports\n  Main\n  \"HOL-Library.Sublist\"\n  Regular_Exp\nbegin\n\nsubsection \\<open>Reverse language\\<close>\n\nlemma rev_conc [simp]: \"rev ` (A @@ B) = rev ` B @@ rev ` A\"\n  unfolding conc_def image_def by force\n\nlemma rev_compower [simp]: \"rev ` (A ^^ n) = (rev ` A) ^^ n\"\n  by (induction n) (simp_all add: conc_pow_comm)\n\nlemma rev_star [simp]: \"rev ` star A = star (rev ` A)\"\n  by (simp add: star_def image_UN)\n\n\nsubsection \\<open>Substituting characters in a language\\<close>    \n\ndefinition subst_word :: \"('a \\<Rightarrow> 'b list) \\<Rightarrow> 'a list \\<Rightarrow> 'b list\" where\n  \"subst_word f xs = concat (map f xs)\"\n  \nlemma subst_word_Nil [simp]: \"subst_word f [] = []\"\n  by (simp add: subst_word_def)\n    \nlemma subst_word_singleton [simp]: \"subst_word f [x] = f x\"\n  by (simp add: subst_word_def)\n    \nlemma subst_word_append [simp]: \"subst_word f (xs @ ys) = subst_word f xs @ subst_word f ys\"\n  by (simp add: subst_word_def)\n    \nlemma subst_word_Cons [simp]: \"subst_word f (x # xs) = f x @ subst_word f xs\"\n  by (simp add: subst_word_def)\n    \nlemma subst_word_conc [simp]: \"subst_word f ` (A @@ B) = subst_word f ` A @@ subst_word f ` B\"\n  unfolding conc_def image_def by force \n\nlemma subst_word_compower [simp]: \"subst_word f ` (A ^^ n) = (subst_word f ` A) ^^ n\"\n  by (induction n) simp_all\n    \nlemma subst_word_star [simp]: \"subst_word f ` (star A) = star (subst_word f ` A)\"\n  by (simp add: star_def image_UN)\n    \n\ntext \\<open>Suffix language\\<close>\n\ndefinition Suffixes :: \"'a list set \\<Rightarrow> 'a list set\" where\n  \"Suffixes A = {w. \\<exists>q. q @ w \\<in> A}\"\n\nlemma Suffixes_altdef [code]: \"Suffixes A = (\\<Union>w\\<in>A. set (suffixes w))\"\n  unfolding Suffixes_def set_suffixes_eq suffix_def by blast\n\n\n\nlemma Suffixes_empty [simp]: \"Suffixes {} = {}\"\n  by (auto simp: Suffixes_def)\n    \nlemma Suffixes_empty_iff [simp]: \"Suffixes A = {} \\<longleftrightarrow> A = {}\"\n  by (auto simp: Suffixes_altdef)\n    \nlemma Suffixes_singleton [simp]: \"Suffixes {xs} = set (suffixes xs)\"\n  by (auto simp: Suffixes_altdef)\n    \nlemma Suffixes_insert: \"Suffixes (insert xs A) = set (suffixes xs) \\<union> Suffixes A\"\n  by (simp add: Suffixes_altdef)\n\nlemma Suffixes_conc [simp]: \"A \\<noteq> {} \\<Longrightarrow> Suffixes (A @@ B) = Suffixes B \\<union> (Suffixes A @@ B)\"\n  unfolding Suffixes_altdef conc_def by (force simp: suffix_append)\n    \nlemma Suffixes_union [simp]: \"Suffixes (A \\<union> B) = Suffixes A \\<union> Suffixes B\"\n  by (auto simp: Suffixes_def)\n  \nlemma Suffixes_UNION [simp]: \"Suffixes (\\<Union>(f ` A)) = \\<Union>((\\<lambda>x. Suffixes (f x)) ` A)\"\n  by (auto simp: Suffixes_def)\n\nlemma Suffixes_compower: \n  assumes \"A \\<noteq> {}\"\n  shows   \"Suffixes (A ^^ n) = insert [] (Suffixes A @@ (\\<Union>k<n. A ^^ k))\"\nproof (induction n)\n  case (Suc n)\n  from Suc have \"Suffixes (A ^^ Suc n) = \n                   insert [] (Suffixes A @@ ((\\<Union>k<n. A ^^ k) \\<union> A ^^ n))\"\n    by (simp_all add: assms conc_Un_distrib)\n  also have \"(\\<Union>k<n. A ^^ k) \\<union> A ^^ n = (\\<Union>k\\<in>insert n {..<n}. A ^^ k)\"  by blast\n  also have \"insert n {..<n} = {..<Suc n}\" by auto\n  finally show ?case .\nqed simp_all\n\nlemma Suffixes_star [simp]: \n  assumes \"A \\<noteq> {}\"\n  shows   \"Suffixes (star A) = Suffixes A @@ star A\"\nproof -\n  have \"star A = (\\<Union>n. A ^^ n)\" unfolding star_def ..\n  also have \"Suffixes \\<dots> = (\\<Union>x. Suffixes (A ^^ x))\" by simp\n  also have \"\\<dots> = (\\<Union>n. insert [] (Suffixes A @@ (\\<Union>k<n. A ^^ k)))\"\n    using assms by (subst Suffixes_compower) auto\n  also have \"\\<dots> = insert [] (Suffixes A @@ (\\<Union>n. (\\<Union>k<n. A ^^ k)))\"\n    by (simp_all add: conc_UNION_distrib)\n  also have \"(\\<Union>n. (\\<Union>k<n. A ^^ k)) = (\\<Union>n. A ^^ n)\" by auto\n  also have \"\\<dots> = star A\" unfolding star_def ..\n  also have \"insert [] (Suffixes A @@ star A) = Suffixes A @@ star A\" \n    using assms by auto\n  finally show ?thesis .\nqed\n  \ntext \\<open>Prefix language\\<close>\n\ndefinition Prefixes :: \"'a list set \\<Rightarrow> 'a list set\" where\n  \"Prefixes A = {w. \\<exists>q. w @ q \\<in> A}\"\n\nlemma Prefixes_altdef [code]: \"Prefixes A = (\\<Union>w\\<in>A. set (prefixes w))\"\n  unfolding Prefixes_def set_prefixes_eq prefix_def by blast\n\nlemma Nil_in_Prefixes_iff [simp]: \"[] \\<in> Prefixes A \\<longleftrightarrow> A \\<noteq> {}\"\n  by (auto simp: Prefixes_def)\n\n\n\nlemma Prefixes_conc [simp]: \"B \\<noteq> {} \\<Longrightarrow> Prefixes (A @@ B) = Prefixes A \\<union> (A @@ Prefixes B)\"\n  unfolding Prefixes_altdef conc_def by (force simp: prefix_append)\n    \nlemma Prefixes_union [simp]: \"Prefixes (A \\<union> B) = Prefixes A \\<union> Prefixes B\"\n  by (auto simp: Prefixes_def)\n  \nlemma Prefixes_UNION [simp]: \"Prefixes (\\<Union>(f ` A)) = \\<Union>((\\<lambda>x. Prefixes (f x)) ` A)\"\n  by (auto simp: Prefixes_def)\n\n\nlemma Prefixes_rev: \"Prefixes (rev ` A) = rev ` Suffixes A\"\n  by (auto simp: Prefixes_altdef prefixes_rev Suffixes_altdef)\n\nlemma Suffixes_rev: \"Suffixes (rev ` A) = rev ` Prefixes A\"\n  by (auto simp: Prefixes_altdef suffixes_rev Suffixes_altdef)    \n\n\nlemma Prefixes_compower:\n  assumes \"A \\<noteq> {}\"\n  shows   \"Prefixes (A ^^ n) = insert [] ((\\<Union>k<n. A ^^ k) @@ Prefixes A)\"\nproof -\n  have \"A ^^ n = rev ` ((rev ` A) ^^ n)\" by (simp add: image_image)\n  also have \"Prefixes \\<dots> = insert [] ((\\<Union>k<n. A ^^ k) @@ Prefixes A)\"\n    unfolding Prefixes_rev \n    by (subst Suffixes_compower) (simp_all add: image_UN image_image Suffixes_rev assms)\n  finally show ?thesis .\nqed\n\nlemma Prefixes_star [simp]:\n  assumes \"A \\<noteq> {}\"\n  shows   \"Prefixes (star A) = star A @@ Prefixes A\"\nproof -\n  have \"star A = rev ` star (rev ` A)\" by (simp add: image_image)\n  also have \"Prefixes \\<dots> = star A @@ Prefixes A\"\n    unfolding Prefixes_rev\n    by (subst Suffixes_star) (simp_all add: assms image_image Suffixes_rev)\n  finally show ?thesis .\nqed\n  \n\nsubsection \\<open>Subword language\\<close>\n\ntext \\<open>\n  The language of all sub-words, i.e. all words that are a contiguous sublist of a word in\n  the original language.\n\\<close>\ndefinition Sublists :: \"'a list set \\<Rightarrow> 'a list set\" where\n  \"Sublists A = {w. \\<exists>q\\<in>A. sublist w q}\"\n\nlemma Sublists_altdef [code]: \"Sublists A = (\\<Union>w\\<in>A. set (sublists w))\"\n  by (auto simp: Sublists_def)\n\nlemma Sublists_empty [simp]: \"Sublists {} = {}\"\n  by (auto simp: Sublists_def)\n    \nlemma Sublists_singleton [simp]: \"Sublists {w} = set (sublists w)\"\n  by (auto simp: Sublists_altdef)\n\nlemma Sublists_insert: \"Sublists (insert w A) = set (sublists w) \\<union> Sublists A\"\n  by (auto simp: Sublists_altdef)\n    \nlemma Sublists_Un [simp]: \"Sublists (A \\<union> B) = Sublists A \\<union> Sublists B\"\n  by (auto simp: Sublists_altdef)\n\nlemma Sublists_UN [simp]: \"Sublists (\\<Union>(f ` A)) = \\<Union>((\\<lambda>x. Sublists (f x)) ` A)\"\n  by (auto simp: Sublists_altdef)\n\nlemma Sublists_conv_Prefixes: \"Sublists A = Prefixes (Suffixes A)\"\n  by (auto simp: Sublists_def Prefixes_def Suffixes_def sublist_def)\n    \nlemma Sublists_conv_Suffixes: \"Sublists A = Suffixes (Prefixes A)\"\n  by (auto simp: Sublists_def Prefixes_def Suffixes_def sublist_def)\n\nlemma Sublists_conc [simp]: \n  assumes \"A \\<noteq> {}\" \"B \\<noteq> {}\"\n  shows   \"Sublists (A @@ B) = Sublists A \\<union> Sublists B \\<union> Suffixes A @@ Prefixes B\"\n  using assms unfolding Sublists_conv_Suffixes by auto\n\nlemma star_not_empty [simp]: \"star A \\<noteq> {}\"\n  by auto\n    \nlemma Sublists_star:\n  \"A \\<noteq> {} \\<Longrightarrow> Sublists (star A) = Sublists A \\<union> Suffixes A @@ star A @@ Prefixes A\"\n  by (simp add: Sublists_conv_Prefixes)\n\nlemma Prefixes_subset_Sublists: \"Prefixes A \\<subseteq> Sublists A\"\n  unfolding Prefixes_def Sublists_def by auto\n\nlemma Suffixes_subset_Sublists: \"Suffixes A \\<subseteq> Sublists A\"\n  unfolding Suffixes_def Sublists_def by auto\n\n\nsubsection \\<open>Fragment language\\<close>\n  \ntext \\<open>\n  The following is the fragment language of a given language, i.e. the set of all words that\n  are (not necessarily contiguous) sub-sequences of a word in the original language.\n\\<close>\ndefinition Subseqs where \"Subseqs A = (\\<Union>w\\<in>A. set (subseqs w))\"\n\nlemma Subseqs_empty [simp]: \"Subseqs {} = {}\"\n  by (simp add: Subseqs_def)\n\nlemma Subseqs_insert [simp]: \"Subseqs (insert xs A) = set (subseqs xs) \\<union> Subseqs A\"\n  by (simp add: Subseqs_def)\n    \nlemma Subseqs_singleton [simp]: \"Subseqs {xs} = set (subseqs xs)\"\n  by simp\n    \nlemma Subseqs_Un [simp]: \"Subseqs (A \\<union> B) = Subseqs A \\<union> Subseqs B\"\n  by (simp add: Subseqs_def)\n    \nlemma Subseqs_UNION [simp]: \"Subseqs (\\<Union>(f ` A)) = \\<Union>((\\<lambda>x. Subseqs (f x)) ` A)\"\n  by (simp add: Subseqs_def)\n  \nlemma Subseqs_conc [simp]: \"Subseqs (A @@ B) = Subseqs A @@ Subseqs B\"\nproof safe\n  fix xs assume \"xs \\<in> Subseqs (A @@ B)\"\n  then obtain ys zs where *: \"ys \\<in> A\" \"zs \\<in> B\" \"subseq xs (ys @ zs)\" \n    by (auto simp: Subseqs_def conc_def)\n  from *(3) obtain xs1 xs2 where \"xs = xs1 @ xs2\" \"subseq xs1 ys\" \"subseq xs2 zs\"\n    by (rule subseq_appendE)\n  with *(1,2) show \"xs \\<in> Subseqs A @@ Subseqs B\" by (auto simp: Subseqs_def set_subseqs_eq)\nnext\n  fix xs assume \"xs \\<in> Subseqs A @@ Subseqs B\"\n  then obtain xs1 xs2 ys zs \n    where \"xs = xs1 @ xs2\" \"subseq xs1 ys\" \"subseq xs2 zs\" \"ys \\<in> A\" \"zs \\<in> B\"\n    by (auto simp: conc_def Subseqs_def)\n  thus \"xs \\<in> Subseqs (A @@ B)\" by (force simp: Subseqs_def conc_def intro: list_emb_append_mono)\nqed\n\nlemma Subseqs_compower [simp]: \"Subseqs (A ^^ n) = Subseqs A ^^ n\"\n  by (induction n) simp_all\n    \nlemma Subseqs_star [simp]: \"Subseqs (star A) = star (Subseqs A)\"\n  by (simp add: star_def)\n    \nlemma Sublists_subset_Subseqs: \"Sublists A \\<subseteq> Subseqs A\"\n  by (auto simp: Sublists_def Subseqs_def dest!: sublist_imp_subseq)\n\n\nsubsection \\<open>Various regular expression constructions\\<close>\n\ntext \\<open>A construction for language reversal of a regular expression:\\<close>\n\nprimrec rexp_rev where\n  \"rexp_rev Zero = Zero\"\n| \"rexp_rev One = One\"\n| \"rexp_rev (Atom x) = Atom x\"\n| \"rexp_rev (Plus r s) = Plus (rexp_rev r) (rexp_rev s)\"\n| \"rexp_rev (Times r s) = Times (rexp_rev s) (rexp_rev r)\"\n| \"rexp_rev (Star r) = Star (rexp_rev r)\"\n\nlemma lang_rexp_rev [simp]: \"lang (rexp_rev r) = rev ` lang r\"\n  by (induction r) (simp_all add: image_Un)  \n    \n\ntext \\<open>The obvious construction for a singleton-language regular expression:\\<close>\n\nfun rexp_of_word where\n  \"rexp_of_word [] = One\"\n| \"rexp_of_word [x] = Atom x\"\n| \"rexp_of_word (x#xs) = Times (Atom x) (rexp_of_word xs)\"\n  \nlemma lang_rexp_of_word [simp]: \"lang (rexp_of_word xs) = {xs}\"\n  by (induction xs rule: rexp_of_word.induct) (simp_all add: conc_def)\n\nlemma size_rexp_of_word [simp]: \"size (rexp_of_word xs) = Suc (2 * (length xs - 1))\"\n  by (induction xs rule: rexp_of_word.induct) auto\n\n\ntext \\<open>Character substitution in a regular expression:\\<close>\n\nprimrec rexp_subst where\n  \"rexp_subst f Zero = Zero\"\n| \"rexp_subst f One = One\"\n| \"rexp_subst f (Atom x) = rexp_of_word (f x)\"\n| \"rexp_subst f (Plus r s) = Plus (rexp_subst f r) (rexp_subst f s)\"\n| \"rexp_subst f (Times r s) = Times (rexp_subst f r) (rexp_subst f s)\"\n| \"rexp_subst f (Star r) = Star (rexp_subst f r)\"\n\nlemma lang_rexp_subst: \"lang (rexp_subst f r) = subst_word f ` lang r\"\n  by (induction r) (simp_all add: image_Un)\n\n\ntext \\<open>Suffix language of a regular expression:\\<close>\n\nprimrec suffix_rexp :: \"'a rexp \\<Rightarrow> 'a rexp\" where\n  \"suffix_rexp Zero = Zero\"\n| \"suffix_rexp One = One\"\n| \"suffix_rexp (Atom a) = Plus (Atom a) One\"\n| \"suffix_rexp (Plus r s) = Plus (suffix_rexp r) (suffix_rexp s)\"\n| \"suffix_rexp (Times r s) =\n    (if rexp_empty r then Zero else Plus (Times (suffix_rexp r) s) (suffix_rexp s))\"\n| \"suffix_rexp (Star r) =\n    (if rexp_empty r then One else Times (suffix_rexp r) (Star r))\"\n\ntheorem lang_suffix_rexp [simp]:\n  \"lang (suffix_rexp r) = Suffixes (lang r)\"\n  by (induction r) (auto simp: rexp_empty_iff)\n\n\ntext \\<open>Prefix language of a regular expression:\\<close>\n\nprimrec prefix_rexp :: \"'a rexp \\<Rightarrow> 'a rexp\" where\n  \"prefix_rexp Zero = Zero\"\n| \"prefix_rexp One = One\"\n| \"prefix_rexp (Atom a) = Plus (Atom a) One\"\n| \"prefix_rexp (Plus r s) = Plus (prefix_rexp r) (prefix_rexp s)\"\n| \"prefix_rexp (Times r s) =\n    (if rexp_empty s then Zero else Plus (Times r (prefix_rexp s)) (prefix_rexp r))\"\n| \"prefix_rexp (Star r) =\n    (if rexp_empty r then One else Times (Star r) (prefix_rexp r))\"\n\ntheorem lang_prefix_rexp [simp]:\n  \"lang (prefix_rexp r) = Prefixes (lang r)\"\n  by (induction r) (auto simp: rexp_empty_iff)\n\n\ntext \\<open>Sub-word language of a regular expression\\<close>    \n\nprimrec sublist_rexp :: \"'a rexp \\<Rightarrow> 'a rexp\" where\n  \"sublist_rexp Zero = Zero\"\n| \"sublist_rexp One = One\"\n| \"sublist_rexp (Atom a) = Plus (Atom a) One\"\n| \"sublist_rexp (Plus r s) = Plus (sublist_rexp r) (sublist_rexp s)\"\n| \"sublist_rexp (Times r s) =\n    (if rexp_empty r \\<or> rexp_empty s then Zero else \n       Plus (sublist_rexp r) (Plus (sublist_rexp s) (Times (suffix_rexp r) (prefix_rexp s))))\"\n| \"sublist_rexp (Star r) =\n    (if rexp_empty r then One else \n       Plus (sublist_rexp r) (Times (suffix_rexp r) (Times (Star r) (prefix_rexp r))))\"\n\ntheorem lang_sublist_rexp [simp]:\n  \"lang (sublist_rexp r) = Sublists (lang r)\"\n  by (induction r) (auto simp: rexp_empty_iff Sublists_star)\n\n\ntext \\<open>Fragment language of a regular expression:\\<close>\n  \nprimrec subseqs_rexp :: \"'a rexp \\<Rightarrow> 'a rexp\" where\n  \"subseqs_rexp Zero = Zero\"\n| \"subseqs_rexp One = One\"\n| \"subseqs_rexp (Atom x) = Plus (Atom x) One\"\n| \"subseqs_rexp (Plus r s) = Plus (subseqs_rexp r) (subseqs_rexp s)\"\n| \"subseqs_rexp (Times r s) = Times (subseqs_rexp r) (subseqs_rexp s)\"\n| \"subseqs_rexp (Star r) = Star (subseqs_rexp r)\"\n\nlemma lang_subseqs_rexp [simp]: \"lang (subseqs_rexp r) = Subseqs (lang r)\"\n  by (induction r) auto\n\n\ntext \\<open>Subword language of a regular expression\\<close>\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Regular-Sets/Regexp_Constructions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.8615382112085969, "lm_q1q2_score": 0.7515606024511711}}
{"text": "section \"Some Auxiliary Results\"\n\ntheory Auxiliary imports Main\nbegin\n\nlemma disjE3: \"P \\<or> Q \\<or> R \\<Longrightarrow> (P \\<Longrightarrow> S) \\<Longrightarrow> (Q \\<Longrightarrow> S) \\<Longrightarrow> (R \\<Longrightarrow> S) \\<Longrightarrow> S\" by auto\n\nlemma ge_induct[consumes 1, case_names step]:\n  fixes i::nat and j::nat and P::\"nat \\<Rightarrow> bool\"\n  shows \"i \\<le> j \\<Longrightarrow> (\\<And>n. i \\<le> n \\<Longrightarrow> ((\\<forall>m \\<ge> i.  m<n \\<longrightarrow> P m) \\<Longrightarrow> P n)) \\<Longrightarrow> P j\"\nproof -\n  assume a0: \"i \\<le> j\" and a1: \"(\\<And>n. i \\<le> n \\<Longrightarrow> ((\\<forall>m \\<ge> i.  m<n \\<longrightarrow> P m) \\<Longrightarrow> P n))\"\n  have \"(\\<And>n. \\<forall>m<n. i \\<le> m \\<longrightarrow> P m \\<Longrightarrow> i \\<le> n \\<longrightarrow> P n)\"\n  proof\n    fix n\n    assume a2: \"\\<forall>m<n. i \\<le> m \\<longrightarrow> P m\"\n    show \"i \\<le> n \\<Longrightarrow> P n\"\n    proof -\n      assume \"i \\<le> n\"\n      with a1 have \"(\\<forall>m \\<ge> i.  m<n \\<longrightarrow> P m) \\<Longrightarrow> P n\" by simp\n      moreover from a2 have \"\\<forall>m \\<ge> i.  m<n \\<longrightarrow> P m\" by simp\n      ultimately show \"P n\" by simp\n    qed\n  qed\n  with nat_less_induct[of \"\\<lambda>j. i \\<le> j \\<longrightarrow> P j\" j] have \"i \\<le> j \\<longrightarrow> P j\" .\n  with a0 show ?thesis by simp\nqed\n\nlemma my_induct[consumes 1, case_names base step]:\n  fixes P::\"nat\\<Rightarrow>bool\"\nassumes less: \"i \\<le> j\"\n    and base: \"P j\"\n    and step: \"\\<And>n. i \\<le> n \\<Longrightarrow> n < j \\<Longrightarrow> (\\<forall>n'>n. n'\\<le>j \\<longrightarrow> P n') \\<Longrightarrow> P n\"\n  shows \"P i\"\nproof cases\n  assume \"j=0\"\n  thus ?thesis using less base by simp\nnext\n  assume \"\\<not> j=0\"\n  have \"j - (j - i) \\<ge> i \\<longrightarrow> P (j - (j - i))\"\n  proof (rule less_induct[of \"\\<lambda>n::nat. j-n \\<ge> i \\<longrightarrow> P (j-n)\" \"j-i\"])\n    fix x assume asmp: \"\\<And>y. y < x \\<Longrightarrow> i \\<le> j - y \\<longrightarrow> P (j - y)\"\n    show \"i \\<le> j - x \\<longrightarrow> P (j - x)\"\n    proof cases\n      assume \"x=0\"\n      with base show ?thesis by simp\n    next\n      assume \"\\<not> x=0\"\n      with \\<open>j \\<noteq> 0\\<close> have \"j - x < j\" by simp\n      show ?thesis\n      proof\n        assume \"i \\<le> j - x\"\n        moreover have \"\\<forall>n'>j-x. n'\\<le>j \\<longrightarrow> P n'\"\n        proof\n          fix n'\n          show \"n'>j-x \\<longrightarrow> n'\\<le>j \\<longrightarrow> P n'\"\n          proof (rule HOL.impI[OF HOL.impI])\n            assume \"j - x < n'\" and \"n' \\<le> j\"\n            hence \"j - n' < x\" by simp\n            moreover from \\<open>i \\<le> j - x\\<close> \\<open>j - x < n'\\<close> have \"i \\<le> n'\" using le_less_trans less_imp_le_nat by blast\n            with \\<open>n' \\<le> j\\<close> have \"i \\<le> j - (j - n')\" by simp\n            ultimately have  \"P (j - (j - n'))\" using asmp by simp\n            moreover from \\<open>n' \\<le> j\\<close> have \"j - (j - n') = n'\" by simp\n            ultimately show \"P n'\" by simp\n          qed\n        qed\n        ultimately show \"P (j - x)\" using \\<open>j-x<j\\<close> step[of \"j-x\"] by simp\n      qed\n    qed\n  qed\n  moreover from less have \"j - (j - i) = i\" by simp\n  ultimately show ?thesis by simp\nqed\n\nlemma Greatest_ex_le_nat: assumes \"\\<exists>k. P k \\<and> (\\<forall>k'. P k' \\<longrightarrow> k' \\<le> k)\" shows \"\\<not>(\\<exists>n'>Greatest P. P n')\"\n  by (metis Greatest_equality assms less_le_not_le)\n\nlemma cardEx: assumes \"finite A\" and \"finite B\" and \"card A > card B\" shows \"\\<exists>x\\<in>A. \\<not> x\\<in>B\"\nproof cases\n  assume \"A \\<subseteq> B\"\n  with assms have \"card A\\<le>card B\" using card_mono by blast\n  with assms have False by simp\n  thus ?thesis by simp\nnext\n  assume \"\\<not> A \\<subseteq> B\" \n  thus ?thesis by auto\nqed\n\nlemma cardshift: \"card {i::nat. i>n \\<and> i \\<le> n' \\<and> p (n'' + i)} = card {i. i>(n + n'') \\<and> i \\<le> (n' + n'') \\<and> p i}\"\nproof -\n  let ?f=\"\\<lambda>i. i+n''\"\n  have \"bij_betw ?f {i::nat. i>n \\<and> i \\<le> n' \\<and> p (n'' + i)} {i. i>(n + n'') \\<and> i \\<le> (n' + n'') \\<and> p i}\"\n  proof (rule bij_betwI')\n    fix x y assume \"x \\<in> {i. n < i \\<and> i \\<le> n' \\<and> p (n'' + i)}\" and \"y \\<in> {i. n < i \\<and> i \\<le> n' \\<and> p (n'' + i)}\"\n    show \"(x + n'' = y + n'') = (x = y)\" by simp\n  next\n    fix x::nat assume \"x \\<in> {i. n < i \\<and> i \\<le> n' \\<and> p (n'' + i)}\"\n    hence \"n<x\" and \"x \\<le> n'\" and \"p(n''+x)\" by auto\n    moreover have \"n''+x=x+n''\" by simp\n    ultimately have \"n + n'' < x + n''\" and \"x + n'' \\<le> n' + n''\" and \"p (x + n'')\" by auto\n    thus \"x + n'' \\<in> {i. n + n'' < i \\<and> i \\<le> n' + n'' \\<and> p i}\" by auto\n  next\n    fix y::nat assume \"y \\<in> {i. n + n'' < i \\<and> i \\<le> n' + n'' \\<and> p i}\"\n    hence \"n+n''<y\" and \"y\\<le>n'+n''\" and \"p y\" by auto\n    then obtain x where \"x=y-n''\" by simp\n    with \\<open>n+n''<y\\<close> have \"y=x+n''\" by simp\n    moreover from \\<open>x=y-n''\\<close> \\<open>n+n''<y\\<close> have \"x>n\" by simp\n    moreover from \\<open>x=y-n''\\<close> \\<open>y\\<le>n'+n''\\<close> have \"x\\<le>n'\" by simp\n    moreover from \\<open>y=x+n''\\<close> have \"y=n''+x\" by simp\n    with \\<open>p y\\<close> have \"p (n'' + x)\" by simp\n    ultimately show \"\\<exists>x\\<in>{i. n < i \\<and> i \\<le> n' \\<and> p (n'' + i)}. y = x + n''\" by auto\n  qed\n  thus ?thesis using bij_betw_same_card by auto\nqed\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Architectural_Design_Patterns/Auxiliary.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8723473614033683, "lm_q2_score": 0.8615382040983515, "lm_q1q2_score": 0.7515605790933935}}
{"text": "(*\n  File: ProductTopology.thy\n  Author: Bohua Zhan\n\n  Basic results about product topology.\n*)\n\ntheory ProductTopology\n  imports Topology\nbegin\n\nsection \\<open>Product topology\\<close>\n  \ndefinition prod_basis :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"prod_basis(X,Y) = (\\<Union>U\\<in>X. \\<Union>V\\<in>Y. {U \\<times> V})\"\n  \nlemma prod_basis_iff [rewrite]:\n  \"W \\<in> prod_basis(X,Y) \\<longleftrightarrow> (\\<exists>U\\<in>X. \\<exists>V\\<in>Y. W = U \\<times> V)\" by auto2\nsetup {* del_prfstep_thm @{thm prod_basis_def} *}\n\nlemma prod_basis_is_basis:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> collection_is_basis(prod_basis(open_sets(X),open_sets(Y)))\"\n@proof\n  @let \"\\<B> = prod_basis(open_sets(X),open_sets(Y))\"\n  @have \"\\<forall>U\\<in>\\<B>. \\<forall>V\\<in>\\<B>. U \\<inter> V \\<in> \\<B>\"\n@qed\nsetup {* add_forward_prfstep_cond @{thm prod_basis_is_basis}\n  [with_term \"prod_basis(open_sets(?X),open_sets(?Y))\"] *}\n      \ndefinition product_space :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixr \"\\<times>\\<^sub>T\" 80) where [rewrite]:\n  \"product_space(X,Y) = Top(carrier(X)\\<times>carrier(Y), top_from_basis(prod_basis(open_sets(X),open_sets(Y))))\"\n  \nlemma product_space_type [typing]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> product_space(X,Y) \\<in> raw_top_spaces(carrier(X)\\<times>carrier(Y))\" by auto2\n\nlemma product_space_is_top_space [forward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> is_top_space(X \\<times>\\<^sub>T Y)\" by auto2\n    \nlemma product_space_is_openD [backward2]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> is_open(X \\<times>\\<^sub>T Y, U) \\<Longrightarrow> x \\<in> U \\<Longrightarrow>\n   \\<exists>V W. is_open(X,V) \\<and> is_open(Y,W) \\<and> x \\<in> V\\<times>W \\<and> V\\<times>W \\<subseteq> U\" by auto2\n  \nlemma product_space_is_openI [forward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow>\n   \\<forall>x\\<in>U. \\<exists>V W. is_open(X,V) \\<and> is_open(Y,W) \\<and> x \\<in> V\\<times>W \\<and> V\\<times>W \\<subseteq> U \\<Longrightarrow> is_open(X \\<times>\\<^sub>T Y, U)\" by auto2\n  \nlemma product_space_is_open_prod [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> is_open(X,U) \\<Longrightarrow> is_open(Y,V) \\<Longrightarrow> is_open(X \\<times>\\<^sub>T Y, U \\<times> V)\" by auto2\n\nsetup {* del_prfstep_thm @{thm product_space_def} *}\n\nlemma product_space_is_closed_prod [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> is_closed(X,A) \\<Longrightarrow> is_closed(Y,B) \\<Longrightarrow> is_closed(X \\<times>\\<^sub>T Y, A \\<times> B)\"\n@proof\n  @have \"is_closed(X \\<times>\\<^sub>T Y, carrier(X) \\<times> B)\"\n  @have \"is_closed(X \\<times>\\<^sub>T Y, A \\<times> carrier(Y))\"\n  @have \"A \\<times> B = carrier(X) \\<times> B \\<inter> A \\<times> carrier(Y)\"\n@qed\n\nlemma product_space_is_closed_prod1 [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> is_closed(Y,B) \\<Longrightarrow> is_closed(X \\<times>\\<^sub>T Y, carrier(X) \\<times> B)\" by auto2\n\nlemma product_space_is_closed_prod2 [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> is_closed(X,A) \\<Longrightarrow> is_closed(X \\<times>\\<^sub>T Y, A \\<times> carrier(Y))\" by auto2\n\nlemma product_space_has_basis [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> top_has_basis(X,\\<B>) \\<Longrightarrow> top_has_basis(Y,\\<C>) \\<Longrightarrow>\n   top_has_basis(X \\<times>\\<^sub>T Y, prod_basis(\\<B>,\\<C>))\"\n@proof\n  @have \"\\<forall>W\\<in>open_sets(X\\<times>\\<^sub>TY). \\<forall>x\\<in>W. \\<exists>C\\<in>prod_basis(\\<B>,\\<C>). x \\<in> C \\<and> C \\<subseteq> W\" @with\n    @obtain U V where \"is_open(X,U)\" \"is_open(Y,V)\" \"x \\<in> U\\<times>V \\<and> U\\<times>V \\<subseteq> W\"\n    @obtain \"B\\<in>\\<B>\" where \"fst(x)\\<in>B\" \"B \\<subseteq> U\"\n    @obtain \"C\\<in>\\<C>\" where \"snd(x)\\<in>C\" \"C \\<subseteq> V\"\n    @have \"B \\<times> C \\<subseteq> U \\<times> V\" @end\n@qed\n\n(* Commutativity between subspace and product space *)\nlemma product_sub_spaces [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow> B \\<subseteq> carrier(Y) \\<Longrightarrow>\n   subspace(X \\<times>\\<^sub>T Y, A \\<times> B) = subspace(X,A) \\<times>\\<^sub>T subspace(Y,B)\"\n@proof\n  @let \"\\<A> = {A \\<inter> U. U \\<in> open_sets(X)}\"\n  @let \"\\<B> = {B \\<inter> U. U \\<in> open_sets(Y)}\"\n  @have \"top_has_basis(subspace(X,A), \\<A>)\"\n  @have \"top_has_basis(subspace(Y,B), \\<B>)\"\n  @have \"top_has_basis(subspace(X,A) \\<times>\\<^sub>T subspace(Y,B), prod_basis(\\<A>,\\<B>))\"\n  @let \"\\<C> = prod_basis(open_sets(X), open_sets(Y))\"\n  @have \"top_has_basis(X \\<times>\\<^sub>T Y, \\<C>)\"\n  @have \"top_has_basis(subspace(X \\<times>\\<^sub>T Y, A \\<times> B), {(A\\<times>B) \\<inter> U. U \\<in> \\<C>})\"\n@qed\n\nlemma product_sub_spaces1 [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> B \\<subseteq> carrier(Y) \\<Longrightarrow>\n   subspace(X \\<times>\\<^sub>T Y, carrier(X) \\<times> B) = X \\<times>\\<^sub>T subspace(Y,B)\"\n@proof\n  @let \"\\<B> = {B \\<inter> U. U \\<in> open_sets(Y)}\"\n  @have \"top_has_basis(subspace(Y,B), \\<B>)\"\n  @have \"top_has_basis(X \\<times>\\<^sub>T subspace(Y,B), prod_basis(open_sets(X),\\<B>))\"\n  @let \"\\<C> = prod_basis(open_sets(X), open_sets(Y))\"\n  @have \"top_has_basis(X \\<times>\\<^sub>T Y, \\<C>)\"\n  @have \"top_has_basis(subspace(X \\<times>\\<^sub>T Y, carrier(X) \\<times> B), {(carrier(X)\\<times>B) \\<inter> U. U \\<in> \\<C>})\"\n  @have \"prod_basis(open_sets(X),\\<B>) = {(carrier(X)\\<times>B)\\<inter>U. U \\<in> \\<C>}\" @with\n    @have \"\\<forall>U\\<in>prod_basis(open_sets(X),\\<B>). U \\<in> {(carrier(X)\\<times>B)\\<inter>U. U \\<in> \\<C>}\" @with\n      @obtain \"V\\<in>open_sets(X)\" \"W\\<in>\\<B>\" where \"U = V \\<times> W\"\n      @obtain \"W'\\<in>open_sets(Y)\" where \"W = B \\<inter> W'\"\n      @have \"U = carrier(X)\\<times>B \\<inter> V\\<times>W'\" @end @end\n@qed\n\nlemma product_sub_spaces2 [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> A \\<subseteq> carrier(X) \\<Longrightarrow>\n   subspace(X \\<times>\\<^sub>T Y, A \\<times> carrier(Y)) = subspace(X,A) \\<times>\\<^sub>T Y\"\n@proof\n  @let \"\\<A> = {A \\<inter> U. U \\<in> open_sets(X)}\"\n  @have \"top_has_basis(subspace(X,A), \\<A>)\"\n  @have \"top_has_basis(subspace(X,A) \\<times>\\<^sub>T Y, prod_basis(\\<A>,open_sets(Y)))\"\n  @let \"\\<C> = prod_basis(open_sets(X), open_sets(Y))\"\n  @have \"top_has_basis(X \\<times>\\<^sub>T Y, \\<C>)\"\n  @have \"top_has_basis(subspace(X \\<times>\\<^sub>T Y, A \\<times> carrier(Y)), {(A\\<times>carrier(Y)) \\<inter> U. U \\<in> \\<C>})\"\n  @have \"prod_basis(\\<A>,open_sets(Y)) = {(A\\<times>carrier(Y))\\<inter>U. U \\<in> \\<C>}\" @with\n    @have \"\\<forall>U\\<in>prod_basis(\\<A>,open_sets(Y)). U \\<in> {(A\\<times>carrier(Y))\\<inter>U. U \\<in> \\<C>}\" @with\n      @obtain \"V\\<in>\\<A>\" \"W\\<in>open_sets(Y)\" where \"U = V \\<times> W\"\n      @obtain \"V'\\<in>open_sets(X)\" where \"V = A \\<inter> V'\"\n      @have \"U = A\\<times>carrier(Y) \\<inter> V'\\<times>W\" @end @end\n@qed\n\nsection \\<open>Continuous functions on product spaces\\<close>\n\ndefinition proj1_top :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"proj1_top(A,B) = Mor(A \\<times>\\<^sub>T B, A, \\<lambda>p. fst(p))\"\n\nlemma proj1_top_is_morphism [typing]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> proj1_top(A,B) \\<in> A \\<times>\\<^sub>T B \\<rightharpoonup> A\" by auto2\nlemma proj1_top_eval [rewrite]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> p \\<in> source(proj1_top(A,B)) \\<Longrightarrow> proj1_top(A,B)`p = fst(p)\" by auto2\nsetup {* del_prfstep_thm @{thm proj1_top_def} *}\nsetup {* add_rewrite_rule_back @{thm proj1_top_def} *}\n  \nlemma proj1_top_continuous [forward]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> continuous(proj1_top(A,B))\"\n@proof\n  @let \"f = proj1_top(A,B)\"\n  @have \"\\<forall>V\\<in>open_sets(A). is_open(A\\<times>\\<^sub>TB, f -`` V)\" @with\n    @have \"f -`` V = V \\<times> carrier(B)\" @end\n@qed\n\nlemma proj1_top_continuous' [backward]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> C \\<subseteq> carrier(A) \\<Longrightarrow>\n   f = Mor(subspace(A,C) \\<times>\\<^sub>T B, A, \\<lambda>p. fst(p)) \\<Longrightarrow> continuous(f)\"\n@proof @have \"f = inj_mor(subspace(A,C),A) \\<circ>\\<^sub>m proj1_top(subspace(A,C),B)\" @qed\n\ndefinition proj2_top :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"proj2_top(A,B) = Mor(A \\<times>\\<^sub>T B, B, \\<lambda>p. snd(p))\"\n\nlemma proj2_top_is_morphism [typing]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> proj2_top(A,B) \\<in> A \\<times>\\<^sub>T B \\<rightharpoonup> B\" by auto2\nlemma proj2_top_eval [rewrite]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> p \\<in> source(proj2_top(A,B)) \\<Longrightarrow> proj2_top(A,B)`p = snd(p)\" by auto2\nsetup {* del_prfstep_thm @{thm proj2_top_def} *}\nsetup {* add_rewrite_rule_back @{thm proj2_top_def} *}\n  \nlemma proj2_top_continuous [forward]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> continuous(proj2_top(A,B))\"\n@proof\n  @let \"f = proj2_top(A,B)\"\n  @have \"\\<forall>V\\<in>open_sets(B). is_open(A\\<times>\\<^sub>TB, f -`` V)\" @with\n    @have \"f -`` V = carrier(A) \\<times> V\" @end\n@qed\n\nlemma proj2_top_continuous' [backward]:\n  \"is_top_space(A) \\<Longrightarrow> is_top_space(B) \\<Longrightarrow> C \\<subseteq> carrier(B) \\<Longrightarrow>\n   f = Mor(A \\<times>\\<^sub>T subspace(B,C), B, \\<lambda>p. snd(p)) \\<Longrightarrow> continuous(f)\"\n@proof @have \"f = inj_mor(subspace(B,C),B) \\<circ>\\<^sub>m proj2_top(A,subspace(B,C))\" @qed\n\ndefinition diag_top_map :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"diag_top_map(A) = Mor(A, A \\<times>\\<^sub>T A, \\<lambda>x. \\<langle>x,x\\<rangle>)\"\n  \nlemma diag_top_map_is_morphism [typing]:\n  \"is_top_space(A) \\<Longrightarrow> diag_top_map(A) \\<in> A \\<rightharpoonup> A \\<times>\\<^sub>T A\" by auto2\nlemma diag_top_map_eval [rewrite]:\n  \"is_top_space(A) \\<Longrightarrow> x \\<in> source(diag_top_map(A)) \\<Longrightarrow> diag_top_map(A)`x = \\<langle>x,x\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm diag_top_map_def} *}\n  \nlemma diag_top_map_continuous [forward]:\n  \"is_top_space(A) \\<Longrightarrow> continuous(diag_top_map(A))\"\n@proof\n  @let \"f = diag_top_map(A)\"\n  @let \"\\<B> = prod_basis(open_sets(A),open_sets(A))\"\n  @have \"top_has_basis(A \\<times>\\<^sub>T A, \\<B>)\"\n  @have \"\\<forall>V\\<in>\\<B>. is_open(A, f -`` V)\" @with\n    @obtain \"U1\\<in>open_sets(A)\" \"U2\\<in>open_sets(A)\" where \"V = U1 \\<times> U2\"\n    @have \"f -`` V = U1 \\<inter> U2\" @end\n@qed\n\ndefinition prod_top_map :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"prod_top_map(u,v) = Mor(source_str(u) \\<times>\\<^sub>T source_str(v), target_str(u) \\<times>\\<^sub>T target_str(v), \\<lambda>\\<langle>x,y\\<rangle>. \\<langle>u`x, v`y\\<rangle>)\"\n\nlemma prod_top_map_is_morphism [typing]:\n  \"is_morphism_top(u) \\<Longrightarrow> is_morphism_top(v) \\<Longrightarrow>\n   prod_top_map(u,v) \\<in> source_str(u) \\<times>\\<^sub>T source_str(v) \\<rightharpoonup> target_str(u) \\<times>\\<^sub>T target_str(v)\" by auto2\n  \nlemma prod_top_map_eval [rewrite]:\n  \"is_morphism_top(u) \\<Longrightarrow> is_morphism_top(v) \\<Longrightarrow>\n   \\<langle>x,y\\<rangle> \\<in> source(prod_top_map(u,v)) \\<Longrightarrow> prod_top_map(u,v)`\\<langle>x,y\\<rangle> = \\<langle>u`x, v`y\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm prod_top_map_def} *}\n  \nlemma prod_top_map_continuous [forward]:\n  \"continuous(u) \\<Longrightarrow> continuous(v) \\<Longrightarrow> continuous(prod_top_map(u,v))\"\n@proof\n  @let \"f = prod_top_map(u,v)\"\n  @let \"A = source_str(u)\" \"B = source_str(v)\"\n  @let \"C = target_str(u)\" \"D = target_str(v)\"\n  @let \"\\<B> = prod_basis(open_sets(C), open_sets(D))\"\n  @have \"top_has_basis(C \\<times>\\<^sub>T D, \\<B>)\"\n  @have \"\\<forall>V\\<in>\\<B>. is_open(A \\<times>\\<^sub>T B, f -`` V)\" @with\n    @obtain \"U1\\<in>open_sets(C)\" \"U2\\<in>open_sets(D)\" where \"V = U1 \\<times> U2\"\n    @have \"f -`` V = (u -`` U1) \\<times> (v -`` U2)\" @end\n@qed\n\ndefinition incl1_top :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"incl1_top(X,Y,x) = Mor(Y, X \\<times>\\<^sub>T Y, \\<lambda>y. \\<langle>x,y\\<rangle>)\"\nsetup {* register_wellform_data (\"incl1_top(X,Y,x)\", [\"x \\<in>. X\"]) *}\n  \nlemma incl1_top_eval [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> y \\<in> source(incl1_top(X,Y,x)) \\<Longrightarrow>\n   incl1_top(X,Y,x)`y = \\<langle>x,y\\<rangle>\" by auto2\n\nlemma incl1_top_continuous [typing]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> incl1_top(X,Y,x) \\<in> Y \\<rightharpoonup>\\<^sub>T X \\<times>\\<^sub>T Y\"\n@proof\n  @let \"f = incl1_top(X,Y,x)\"\n  @let \"B = prod_basis(open_sets(X),open_sets(Y))\"\n  @have \"top_has_basis(X \\<times>\\<^sub>T Y, B)\"\n  @have \"\\<forall>W\\<in>B. is_open(Y, f -`` W)\" @with\n    @obtain \"U\\<in>open_sets(X)\" \"V\\<in>open_sets(Y)\" where \"W = U \\<times> V\"\n    @case \"x \\<in> U\" @with @have \"f -`` W = V\" @end\n    @case \"x \\<notin> U\" @with @have \"f -`` W = \\<emptyset>\" @end\n  @end\n@qed\nsetup {* del_prfstep_thm @{thm incl1_top_def} *}\n  \ndefinition incl2_top :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"incl2_top(X,Y,y) = Mor(X, X \\<times>\\<^sub>T Y, \\<lambda>x. \\<langle>x,y\\<rangle>)\"\nsetup {* register_wellform_data (\"incl2_top(X,Y,y)\", [\"y \\<in>. Y\"]) *}\n  \nlemma incl2_top_eval [rewrite]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> y \\<in>. Y \\<Longrightarrow> x \\<in> source(incl2_top(X,Y,y)) \\<Longrightarrow>\n   incl2_top(X,Y,y)`x = \\<langle>x,y\\<rangle>\" by auto2\n  \nlemma incl2_top_continuous [typing]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> y \\<in>. Y \\<Longrightarrow> incl2_top(X,Y,y) \\<in> X \\<rightharpoonup>\\<^sub>T X \\<times>\\<^sub>T Y\"\n@proof\n  @let \"f = incl2_top(X,Y,y)\"\n  @let \"B = prod_basis(open_sets(X),open_sets(Y))\"\n  @have \"top_has_basis(X \\<times>\\<^sub>T Y, B)\"\n  @have \"\\<forall>W\\<in>B. is_open(X, f -`` W)\" @with\n    @obtain \"U\\<in>open_sets(X)\" \"V\\<in>open_sets(Y)\" where \"W = U \\<times> V\"\n    @case \"y \\<in> V\" @with @have \"f -`` W = U\" @end\n    @case \"y \\<notin> V\" @with @have \"f -`` W = \\<emptyset>\" @end\n  @end\n@qed\nsetup {* del_prfstep_thm @{thm incl2_top_def} *}\n\n(* Homeomorphisms on product spaces *)\nlemma product_slice1 [typing]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> A = {x} \\<times> carrier(Y) \\<Longrightarrow>\n   f = mor_restrict_image_top(incl1_top(X,Y,x),A) \\<Longrightarrow> f \\<in> Y \\<cong>\\<^sub>T subspace(X \\<times>\\<^sub>T Y, A)\"\n@proof\n  @let \"g = proj2_top(X,Y) \\<circ>\\<^sub>m inj_mor(subspace(X \\<times>\\<^sub>T Y, A), X \\<times>\\<^sub>T Y)\"\n  @have \"inverse_mor_pair(f,g)\"\n@qed\n      \nlemma product_slice1' [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> x \\<in>. X \\<Longrightarrow> A = {x} \\<times> carrier(Y) \\<Longrightarrow>\n   homeomorphic(Y, subspace(X \\<times>\\<^sub>T Y, A))\"\n@proof\n  @have \"mor_restrict_image_top(incl1_top(X,Y,x),A) \\<in> Y \\<cong>\\<^sub>T subspace(X \\<times>\\<^sub>T Y, A)\"\n@qed\n\nlemma product_slice2 [typing]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> y \\<in>. Y \\<Longrightarrow> A = carrier(X) \\<times> {y} \\<Longrightarrow>\n   f = mor_restrict_image_top(incl2_top(X,Y,y),A) \\<Longrightarrow> f \\<in> X \\<cong>\\<^sub>T subspace(X \\<times>\\<^sub>T Y, A)\"\n@proof\n  @let \"g = proj1_top(X,Y) \\<circ>\\<^sub>m inj_mor(subspace(X \\<times>\\<^sub>T Y, A), X \\<times>\\<^sub>T Y)\"\n  @have \"inverse_mor_pair(f,g)\"\n@qed\n      \nlemma product_slice2' [backward]:\n  \"is_top_space(X) \\<Longrightarrow> is_top_space(Y) \\<Longrightarrow> y \\<in>. Y \\<Longrightarrow> A = carrier(X) \\<times> {y} \\<Longrightarrow>\n   homeomorphic(X, subspace(X \\<times>\\<^sub>T Y, A))\"\n@proof\n  @have \"mor_restrict_image_top(incl2_top(X,Y,y),A) \\<in> X \\<cong>\\<^sub>T subspace(X \\<times>\\<^sub>T Y, A)\"\n@qed\n\nend\n", "meta": {"author": "bzhan", "repo": "auto2", "sha": "2e83c30b095f2ed9fa5257f79570eb354ed6e6a7", "save_path": "github-repos/isabelle/bzhan-auto2", "path": "github-repos/isabelle/bzhan-auto2/auto2-2e83c30b095f2ed9fa5257f79570eb354ed6e6a7/FOL/Topology/ProductTopology.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.8740772318846386, "lm_q1q2_score": 0.751412517682609}}
{"text": "section \\<open> Alternating lists \\<close>\n\ntext \\<open>In lists where even and odd elements play different roles, it helps to define functions to\n      take out the even elements. We defined the function (l)alternate on (coinductive) lists to\n      do exactly this, and define certain properties.\\<close>\n\ntheory AlternatingLists\n  imports MoreCoinductiveList2 (* for notation and lemmas like infinite_small_llength *)\nbegin\n\ntext \\<open>The functions ``alternate\" and ``lalternate\" are our main workhorses:\n      they take every other item, so every item at even indices.\\<close>\n\nfun alternate where\n  \"alternate Nil = Nil\" |\n  \"alternate (Cons x xs) = Cons x (alternate (tl xs))\"\n\ntext \\<open>``lalternate\" takes every other item from a co-inductive list.\\<close>\nprimcorec lalternate :: \"'a llist \\<Rightarrow> 'a llist\"\n  where\n    \"lalternate xs = (case xs of LNil \\<Rightarrow> LNil |\n                                 (LCons x xs) \\<Rightarrow> LCons x (lalternate (ltl xs)))\"\n\nlemma lalternate_ltake:\n  \"ltake (enat n) (lalternate xs) = lalternate (ltake (2*n) xs)\"\nproof(induct n arbitrary:xs)\n  case 0\n  then show ?case by (metis LNil_eq_ltake_iff enat_defs(1) lalternate.ctr(1) lnull_def mult_zero_right)\nnext\n  case (Suc n)\n  hence lt:\"ltake (enat n) (lalternate (ltl (ltl xs))) = lalternate (ltake (enat (2 * n)) (ltl (ltl xs)))\".\n  show ?case\n  proof(cases \"lalternate xs\")\n    case LNil\n    then show ?thesis by(metis lalternate.disc(2) lnull_def ltake_LNil)\n  next\n    case (LCons x21 x22)\n    thus ?thesis unfolding ltake_ltl mult_Suc_right add_2_eq_Suc\n      using eSuc_enat lalternate.code lalternate.ctr(1) lhd_LCons_ltl llist.sel(1)\n      by (smt (z3) lt ltake_ltl llist.simps(3) llist.simps(5) ltake_eSuc_LCons)\n  qed\nqed\n\nlemma lalternate_llist_of[simp]:\n  \"lalternate (llist_of xs) = llist_of (alternate xs)\"\nproof(induct \"alternate xs\" arbitrary:xs)\n  case Nil\n  then show ?case\n    by (metis alternate.elims lalternate.ctr(1) list.simps(3) llist_of.simps(1) lnull_llist_of)\nnext\n  case (Cons a xs)\n  then show ?case by(cases xs,auto simp: lalternate.ctr)\nqed\n\nlemma lalternate_finite_helper: (* The other direction is proved later, added as SIMP rule *)\n  assumes \"lfinite (lalternate xs)\"\n  shows \"lfinite xs\"\nusing assms proof(induct \"lalternate xs\" arbitrary:xs rule:lfinite_induct)\n  case LNil\n  then show ?case unfolding lalternate.code[of xs] by(cases xs;auto)\nnext\n  case (LCons xs)\n  then show ?case unfolding lalternate.code[of xs] by(cases \"xs\";cases \"ltl xs\";auto)\nqed\n\nlemma alternate_list_of: (* Note that this only holds for finite lists,\n                    as the other direction is left undefined with arguments (not just undefined) *)\n  assumes \"lfinite xs\"\n  shows \"alternate (list_of xs) = list_of (lalternate xs)\"\n  using assms by (metis lalternate_llist_of list_of_llist_of llist_of_list_of)\n\nlemma alternate_length:\n  \"length (alternate xs) = (1+length xs) div 2\"\n  by (induct xs rule:induct_list012;simp)\n\nlemma lalternate_llength:\n  \"llength (lalternate xs) * 2 = (1+llength xs) \\<or> llength (lalternate xs) * 2 = llength xs\"\nproof(cases \"lfinite xs\")\n  case True\n  let ?xs = \"list_of xs\"\n  have \"length (alternate ?xs) = (1+length ?xs) div 2\" using alternate_length by auto\n  hence \"length (alternate ?xs) * 2 = (1+length ?xs) \\<or> length (alternate ?xs) * 2 = length ?xs\"\n    by auto\n  then show ?thesis using alternate_list_of[OF True] lalternate_llist_of True\n    length_list_of_conv_the_enat[OF True] llist_of_list_of[OF True]\n    by (metis llength_llist_of numeral_One of_nat_eq_enat of_nat_mult of_nat_numeral plus_enat_simps(1))\nnext\n  case False\n  have \"\\<not> lfinite (lalternate xs)\" using False lalternate_finite_helper by auto\n  hence l1:\"llength (lalternate xs) = \\<infinity>\" by(rule not_lfinite_llength)\n  from False have l2:\"llength xs = \\<infinity>\" using not_lfinite_llength by auto\n  show ?thesis using l1 l2 by (simp add: mult_2_right)\nqed\n\nlemma lalternate_finite[simp]:\n  shows \"lfinite (lalternate xs) = lfinite xs\"\nproof(cases \"lfinite xs\")\n  case True\n  then show ?thesis\n  proof(cases \"lfinite (lalternate xs)\")\n    case False\n    hence False using not_lfinite_llength[OF False] True[unfolded lfinite_conv_llength_enat]\n                      lalternate_llength[of xs]\n                by (auto simp:one_enat_def numeral_eq_enat)\n    thus ?thesis by metis\n  qed auto\nnext\n  case False\n  then show ?thesis using lalternate_finite_helper by blast\nqed\n\nlemma nth_alternate:\n  assumes \"2*n < length xs\"\n  shows \"alternate xs ! n = xs ! (2 * n)\"\n  using assms proof (induct xs arbitrary:n rule:induct_list012)\n  case (3 x y zs)\n  then show ?case proof(cases n)\n    case (Suc nat)\n    show ?thesis using \"3.hyps\"(1) \"3.prems\" Suc by force\n  qed simp\nqed auto\n\nlemma lnth_lalternate:\n  assumes \"2*n < llength xs\"\n  shows \"lalternate xs $ n = xs $ (2 * n)\"\nproof -\n  let ?xs = \"ltake (2*Suc n) xs\"\n  have \"lalternate ?xs $ n = ?xs $ (2 * n)\"\n    using assms alternate_list_of[of \"ltake (2*Suc n) xs\"] nth_alternate[of n \"list_of ?xs\"]\n    by (smt (z3) Suc_1 Suc_mult_less_cancel1 enat_ord_simps(2) infinite_small_llength lalternate_ltake length_list_of lessI llength_eq_enat_lfiniteD llength_ltake' ltake_all not_less nth_list_of numeral_eq_enat the_enat.simps times_enat_simps(1))\n  thus ?thesis\n    by (metis Suc_1 Suc_mult_less_cancel1 enat_ord_simps(2) lalternate_ltake lessI lnth_ltake)\nqed\n\nlemma lnth_lalternate2[simp]:\n  assumes \"n < llength (lalternate xs)\"\n  shows \"lalternate xs $ n = xs $ (2 * n)\"\nproof -\n  from assms have \"2*enat n < llength xs\"\n    by (metis enat_numeral lalternate_ltake leI linorder_neq_iff llength_ltake' ltake_all times_enat_simps(1))\n  from lnth_lalternate[OF this] show ?thesis.\nqed\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/GaleStewart_Games/AlternatingLists.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.8596637433190939, "lm_q1q2_score": 0.7514124994721519}}
{"text": "(*  Title:      HOL/Isar_Examples/Knaster_Tarski.thy\n    Author:     Makarius\n\nTypical textbook proof example.\n*)\n\nsection \\<open>Textbook-style reasoning: the Knaster-Tarski Theorem\\<close>\n\ntheory Knaster_Tarski\n  imports Main \"HOL-Library.Lattice_Syntax\"\nbegin\n\n\nsubsection \\<open>Prose version\\<close>\n\ntext \\<open>\n  According to the textbook @{cite \\<open>pages 93--94\\<close> \"davey-priestley\"}, the\n  Knaster-Tarski fixpoint theorem is as follows.\\<^footnote>\\<open>We have dualized the\n  argument, and tuned the notation a little bit.\\<close>\n\n  \\<^bold>\\<open>The Knaster-Tarski Fixpoint Theorem.\\<close> Let \\<open>L\\<close> be a complete lattice and\n  \\<open>f: L \\<rightarrow> L\\<close> an order-preserving map. Then \\<open>\\<Sqinter>{x \\<in> L | f(x) \\<le> x}\\<close> is a fixpoint\n  of \\<open>f\\<close>.\n\n  \\<^bold>\\<open>Proof.\\<close> Let \\<open>H = {x \\<in> L | f(x) \\<le> x}\\<close> and \\<open>a = \\<Sqinter>H\\<close>. For all \\<open>x \\<in> H\\<close> we have\n  \\<open>a \\<le> x\\<close>, so \\<open>f(a) \\<le> f(x) \\<le> x\\<close>. Thus \\<open>f(a)\\<close> is a lower bound of \\<open>H\\<close>, whence\n  \\<open>f(a) \\<le> a\\<close>. We now use this inequality to prove the reverse one (!) and\n  thereby complete the proof that \\<open>a\\<close> is a fixpoint. Since \\<open>f\\<close> is\n  order-preserving, \\<open>f(f(a)) \\<le> f(a)\\<close>. This says \\<open>f(a) \\<in> H\\<close>, so \\<open>a \\<le> f(a)\\<close>.\\<close>\n\n\nsubsection \\<open>Formal versions\\<close>\n\ntext \\<open>\n  The Isar proof below closely follows the original presentation. Virtually\n  all of the prose narration has been rephrased in terms of formal Isar\n  language elements. Just as many textbook-style proofs, there is a strong\n  bias towards forward proof, and several bends in the course of reasoning.\n\\<close>\n\ntheorem Knaster_Tarski:\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"\\<exists>a. f a = a\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof -\n    {\n      fix x\n      assume \"x \\<in> ?H\"\n      then have \"?a \\<le> x\" by (rule Inf_lower)\n      with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n      also from \\<open>x \\<in> ?H\\<close> have \"\\<dots> \\<le> x\" ..\n      finally have \"f ?a \\<le> x\" .\n    }\n    then have \"f ?a \\<le> ?a\" by (rule Inf_greatest)\n    {\n      also presume \"\\<dots> \\<le> f ?a\"\n      finally (order_antisym) show ?thesis .\n    }\n    from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n    then have \"f ?a \\<in> ?H\" ..\n    then show \"?a \\<le> f ?a\" by (rule Inf_lower)\n  qed\nqed\n\ntext \\<open>\n  Above we have used several advanced Isar language elements, such as explicit\n  block structure and weak assumptions. Thus we have mimicked the particular\n  way of reasoning of the original text.\n\n  In the subsequent version the order of reasoning is changed to achieve\n  structured top-down decomposition of the problem at the outer level, while\n  only the inner steps of reasoning are done in a forward manner. We are\n  certainly more at ease here, requiring only the most basic features of the\n  Isar language.\n\\<close>\n\ntheorem Knaster_Tarski':\n  fixes f :: \"'a::complete_lattice \\<Rightarrow> 'a\"\n  assumes \"mono f\"\n  shows \"\\<exists>a. f a = a\"\nproof\n  let ?H = \"{u. f u \\<le> u}\"\n  let ?a = \"\\<Sqinter>?H\"\n  show \"f ?a = ?a\"\n  proof (rule order_antisym)\n    show \"f ?a \\<le> ?a\"\n    proof (rule Inf_greatest)\n      fix x\n      assume \"x \\<in> ?H\"\n      then have \"?a \\<le> x\" by (rule Inf_lower)\n      with \\<open>mono f\\<close> have \"f ?a \\<le> f x\" ..\n      also from \\<open>x \\<in> ?H\\<close> have \"\\<dots> \\<le> x\" ..\n      finally show \"f ?a \\<le> x\" .\n    qed\n    show \"?a \\<le> f ?a\"\n    proof (rule Inf_lower)\n      from \\<open>mono f\\<close> and \\<open>f ?a \\<le> ?a\\<close> have \"f (f ?a) \\<le> f ?a\" ..\n      then show \"f ?a \\<in> ?H\" ..\n    qed\n  qed\nqed\n\nend\n", "meta": {"author": "landonf", "repo": "isabelle-legacy", "sha": "e40f3ca7e9a42bb91e57fd15f969388e6e83f692", "save_path": "github-repos/isabelle/landonf-isabelle-legacy", "path": "github-repos/isabelle/landonf-isabelle-legacy/isabelle-legacy-e40f3ca7e9a42bb91e57fd15f969388e6e83f692/src/HOL/Isar_Examples/Knaster_Tarski.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8840392832736084, "lm_q1q2_score": 0.7514078954927459}}
{"text": "(*  Title:      HOL/SPARK/Examples/Liseq/Longest_Increasing_Subsequence.thy\n    Author:     Stefan Berghofer\n    Copyright:  secunet Security Networks AG\n*)\n\ntheory Longest_Increasing_Subsequence\nimports \"../../SPARK\"\nbegin\n\ntext \\<open>\nSet of all increasing subsequences in a prefix of an array\n\\<close>\n\ndefinition iseq :: \"(nat \\<Rightarrow> 'a::linorder) \\<Rightarrow> nat \\<Rightarrow> nat set set\" where\n  \"iseq xs l = {is. (\\<forall>i\\<in>is. i < l) \\<and>\n     (\\<forall>i\\<in>is. \\<forall>j\\<in>is. i \\<le> j \\<longrightarrow> xs i \\<le> xs j)}\"\n\ntext \\<open>\nLength of longest increasing subsequence in a prefix of an array\n\\<close>\n\ndefinition liseq :: \"(nat \\<Rightarrow> 'a::linorder) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"liseq xs i = Max (card ` iseq xs i)\"\n\ntext \\<open>\nLength of longest increasing subsequence ending at a particular position\n\\<close>\n\ndefinition liseq' :: \"(nat \\<Rightarrow> 'a::linorder) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"liseq' xs i = Max (card ` (iseq xs (Suc i) \\<inter> {is. Max is = i}))\"\n\nlemma iseq_finite: \"finite (iseq xs i)\"\n  apply (simp add: iseq_def)\n  apply (rule finite_subset [OF _\n    finite_Collect_subsets [of \"{j. j < i}\"]])\n  apply auto\n  done\n\nlemma iseq_finite': \"is \\<in> iseq xs i \\<Longrightarrow> finite is\"\n  by (auto simp add: iseq_def bounded_nat_set_is_finite)\n\nlemma iseq_singleton: \"i < l \\<Longrightarrow> {i} \\<in> iseq xs l\"\n  by (simp add: iseq_def)\n\nlemma iseq_trivial: \"{} \\<in> iseq xs i\"\n  by (simp add: iseq_def)\n\nlemma iseq_nonempty: \"iseq xs i \\<noteq> {}\"\n  by (auto intro: iseq_trivial)\n\nlemma liseq'_ge1: \"1 \\<le> liseq' xs x\"\n  apply (simp add: liseq'_def)\n  apply (subgoal_tac \"iseq xs (Suc x) \\<inter> {is. Max is = x} \\<noteq> {}\")\n  apply (simp add: Max_ge_iff iseq_finite)\n  apply (rule_tac x=\"{x}\" in bexI)\n  apply (auto intro: iseq_singleton)\n  done\n\nlemma liseq_expand:\n  assumes R: \"\\<And>is. liseq xs i = card is \\<Longrightarrow> is \\<in> iseq xs i \\<Longrightarrow>\n    (\\<And>js. js \\<in> iseq xs i \\<Longrightarrow> card js \\<le> card is) \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  have \"Max (card ` iseq xs i) \\<in> card ` iseq xs i\"\n    by (rule Max_in) (simp_all add: iseq_finite iseq_nonempty)\n  then obtain js where js: \"liseq xs i = card js\" and \"js \\<in> iseq xs i\"\n    by (rule imageE) (simp add: liseq_def)\n  moreover {\n    fix js'\n    assume \"js' \\<in> iseq xs i\"\n    then have \"card js' \\<le> card js\"\n      by (simp add: js [symmetric] liseq_def iseq_finite iseq_trivial)\n  }\n  ultimately show ?thesis by (rule R)\nqed\n\nlemma liseq'_expand:\n  assumes R: \"\\<And>is. liseq' xs i = card is \\<Longrightarrow> is \\<in> iseq xs (Suc i) \\<Longrightarrow>\n    finite is \\<Longrightarrow> Max is = i \\<Longrightarrow>\n    (\\<And>js. js \\<in> iseq xs (Suc i) \\<Longrightarrow> Max js = i \\<Longrightarrow> card js \\<le> card is) \\<Longrightarrow>\n    is \\<noteq> {} \\<Longrightarrow> P\"\n  shows \"P\"\nproof -\n  have \"Max (card ` (iseq xs (Suc i) \\<inter> {is. Max is = i})) \\<in>\n    card ` (iseq xs (Suc i) \\<inter> {is. Max is = i})\"\n    by (auto simp add: iseq_finite intro!: iseq_singleton Max_in)\n  then obtain js where js: \"liseq' xs i = card js\" and \"js \\<in> iseq xs (Suc i)\"\n    and \"finite js\" and \"Max js = i\"\n    by (auto simp add: liseq'_def intro: iseq_finite')\n  moreover {\n    fix js'\n    assume \"js' \\<in> iseq xs (Suc i)\" \"Max js' = i\"\n    then have \"card js' \\<le> card js\"\n      by (auto simp add: js [symmetric] liseq'_def iseq_finite intro!: iseq_singleton)\n  }\n  note max = this\n  moreover have \"card {i} \\<le> card js\"\n    by (rule max) (simp_all add: iseq_singleton)\n  then have \"js \\<noteq> {}\" by auto\n  ultimately show ?thesis by (rule R)\nqed\n\nlemma liseq'_ge:\n  \"j = card js \\<Longrightarrow> js \\<in> iseq xs (Suc i) \\<Longrightarrow> Max js = i \\<Longrightarrow>\n  js \\<noteq> {} \\<Longrightarrow> j \\<le> liseq' xs i\"\n  by (simp add: liseq'_def iseq_finite)\n\nlemma liseq'_eq:\n  \"j = card js \\<Longrightarrow> js \\<in> iseq xs (Suc i) \\<Longrightarrow> Max js = i \\<Longrightarrow>\n  js \\<noteq> {} \\<Longrightarrow> (\\<And>js'. js' \\<in> iseq xs (Suc i) \\<Longrightarrow> Max js' = i \\<Longrightarrow> finite js' \\<Longrightarrow>\n    js' \\<noteq> {} \\<Longrightarrow> card js' \\<le> card js) \\<Longrightarrow>\n  j = liseq' xs i\"\n  by (fastforce simp add: liseq'_def iseq_finite\n    intro: Max_eqI [symmetric])\n\nlemma liseq_ge:\n  \"j = card js \\<Longrightarrow> js \\<in> iseq xs i \\<Longrightarrow> j \\<le> liseq xs i\"\n  by (auto simp add: liseq_def iseq_finite)\n\nlemma liseq_eq:\n  \"j = card js \\<Longrightarrow> js \\<in> iseq xs i \\<Longrightarrow>\n  (\\<And>js'. js' \\<in> iseq xs i \\<Longrightarrow> finite js' \\<Longrightarrow>\n    js' \\<noteq> {} \\<Longrightarrow> card js' \\<le> card js) \\<Longrightarrow>\n  j = liseq xs i\"\n  by (fastforce simp add: liseq_def iseq_finite\n    intro: Max_eqI [symmetric])\n\nlemma max_notin: \"finite xs \\<Longrightarrow> Max xs < x \\<Longrightarrow> x \\<notin> xs\"\n  by (cases \"xs = {}\") auto\n\nlemma iseq_insert:\n  \"xs (Max is) \\<le> xs i \\<Longrightarrow> is \\<in> iseq xs i \\<Longrightarrow>\n  is \\<union> {i} \\<in> iseq xs (Suc i)\"\n  apply (frule iseq_finite')\n  apply (cases \"is = {}\")\n  apply (auto simp add: iseq_def)\n  apply (rule order_trans [of _ \"xs (Max is)\"])\n  apply auto\n  apply (thin_tac \"\\<forall>a\\<in>is. a < i\")\n  apply (drule_tac x=ia in bspec)\n  apply assumption\n  apply (drule_tac x=\"Max is\" in bspec)\n  apply (auto intro: Max_in)\n  done\n\nlemma iseq_diff: \"is \\<in> iseq xs (Suc (Max is)) \\<Longrightarrow>\n  is - {Max is} \\<in> iseq xs (Suc (Max (is - {Max is})))\"\n  apply (frule iseq_finite')\n  apply (simp add: iseq_def less_Suc_eq_le)\n  done\n\nlemma iseq_butlast:\n  assumes \"js \\<in> iseq xs (Suc i)\" and \"js \\<noteq> {}\"\n  and \"Max js \\<noteq> i\"\n  shows \"js \\<in> iseq xs i\"\nproof -\n  from assms have fin: \"finite js\"\n    by (simp add: iseq_finite')\n  with assms have \"Max js \\<in> js\"\n    by auto\n  with assms have \"Max js < i\"\n    by (auto simp add: iseq_def)\n  with fin assms have \"\\<forall>j\\<in>js. j < i\"\n    by simp\n  with assms show ?thesis\n    by (simp add: iseq_def)\nqed\n\nlemma iseq_mono: \"is \\<in> iseq xs i \\<Longrightarrow> i \\<le> j \\<Longrightarrow> is \\<in> iseq xs j\"\n  by (auto simp add: iseq_def)\n\nlemma diff_nonempty:\n  assumes \"1 < card is\"\n  shows \"is - {i} \\<noteq> {}\"\nproof -\n  from assms have fin: \"finite is\" by (auto intro: card_ge_0_finite)\n  with assms fin have \"card is - 1 \\<le> card (is - {i})\"\n    by (simp add: card_Diff_singleton_if)\n  with assms have \"0 < card (is - {i})\" by simp\n  then show ?thesis by (simp add: card_gt_0_iff)\nqed\n\nlemma Max_diff:\n  assumes \"1 < card is\"\n  shows \"Max (is - {Max is}) < Max is\"\nproof -\n  from assms have \"finite is\" by (auto intro: card_ge_0_finite)\n  moreover from assms have \"is - {Max is} \\<noteq> {}\"\n    by (rule diff_nonempty)\n  ultimately show ?thesis using assms\n    apply (auto simp add: not_less)\n    apply (subgoal_tac \"a \\<le> Max is\")\n    apply auto\n    done\nqed\n\nlemma iseq_nth: \"js \\<in> iseq xs l \\<Longrightarrow> 1 < card js \\<Longrightarrow>\n  xs (Max (js - {Max js})) \\<le> xs (Max js)\"\n  apply (auto simp add: iseq_def)\n  apply (subgoal_tac \"Max (js - {Max js}) \\<in> js\")\n  apply (thin_tac \"\\<forall>i\\<in>js. i < l\")\n  apply (drule_tac x=\"Max (js - {Max js})\" in bspec)\n  apply assumption\n  apply (drule_tac x=\"Max js\" in bspec)\n  using card_gt_0_iff [of js]\n  apply simp\n  using Max_diff [of js]\n  apply simp\n  using Max_in [of \"js - {Max js}\", OF _ diff_nonempty] card_gt_0_iff [of js]\n  apply auto\n  done\n\nlemma card_leq1_singleton:\n  assumes \"finite xs\" \"xs \\<noteq> {}\" \"card xs \\<le> 1\"\n  obtains x where \"xs = {x}\"\n  using assms\n  by induct simp_all\n\nlemma longest_iseq1:\n  \"liseq' xs i =\n   Max ({0} \\<union> {liseq' xs j |j. j < i \\<and> xs j \\<le> xs i}) + 1\"\nproof -\n  have \"Max ({0} \\<union> {liseq' xs j |j. j < i \\<and> xs j \\<le> xs i}) = liseq' xs i - 1\"\n  proof (rule Max_eqI)\n    fix y\n    assume \"y \\<in> {0} \\<union> {liseq' xs j |j. j < i \\<and> xs j \\<le> xs i}\"\n    then show \"y \\<le> liseq' xs i - 1\"\n    proof\n      assume \"y \\<in> {liseq' xs j |j. j < i \\<and> xs j \\<le> xs i}\"\n      then obtain j where j: \"j < i\" \"xs j \\<le> xs i\" \"y = liseq' xs j\"\n        by auto\n      have \"liseq' xs j + 1 \\<le> liseq' xs i\"\n      proof (rule liseq'_expand)\n        fix \"is\"\n        assume H: \"liseq' xs j = card is\" \"is \\<in> iseq xs (Suc j)\"\n          \"finite is\" \"Max is = j\" \"is \\<noteq> {}\"\n        from H j have \"card is + 1 = card (is \\<union> {i})\"\n          by (simp add: card_insert max_notin)\n        moreover {\n          from H j have \"xs (Max is) \\<le> xs i\" by simp\n          moreover from \\<open>j < i\\<close> have \"Suc j \\<le> i\" by simp\n          with \\<open>is \\<in> iseq xs (Suc j)\\<close> have \"is \\<in> iseq xs i\"\n            by (rule iseq_mono)\n          ultimately have \"is \\<union> {i} \\<in> iseq xs (Suc i)\"\n          by (rule iseq_insert)\n        } moreover from H j have \"Max (is \\<union> {i}) = i\" by simp\n        moreover have \"is \\<union> {i} \\<noteq> {}\" by simp\n        ultimately have \"card is + 1 \\<le> liseq' xs i\"\n          by (rule liseq'_ge)\n        with H show ?thesis by simp\n      qed\n      with j show \"y \\<le> liseq' xs i - 1\"\n        by simp\n    qed simp\n  next\n    have \"liseq' xs i \\<le> 1 \\<or>\n      (\\<exists>j. liseq' xs i - 1 = liseq' xs j \\<and> j < i \\<and> xs j \\<le> xs i)\"\n    proof (rule liseq'_expand)\n      fix \"is\"\n      assume H: \"liseq' xs i = card is\" \"is \\<in> iseq xs (Suc i)\"\n        \"finite is\" \"Max is = i\" \"is \\<noteq> {}\"\n      assume R: \"\\<And>js. js \\<in> iseq xs (Suc i) \\<Longrightarrow> Max js = i \\<Longrightarrow>\n        card js \\<le> card is\"\n      show ?thesis\n      proof (cases \"card is \\<le> 1\")\n        case True with H show ?thesis by simp\n      next\n        case False\n        then have \"1 < card is\" by simp\n        then have \"Max (is - {Max is}) < Max is\"\n          by (rule Max_diff)\n        from \\<open>is \\<in> iseq xs (Suc i)\\<close> \\<open>1 < card is\\<close>\n        have \"xs (Max (is - {Max is})) \\<le> xs (Max is)\"\n          by (rule iseq_nth)\n        have \"card is - 1 = liseq' xs (Max (is - {i}))\"\n        proof (rule liseq'_eq)\n          from \\<open>Max is = i\\<close> [symmetric] \\<open>finite is\\<close> \\<open>is \\<noteq> {}\\<close>\n          show \"card is - 1 = card (is - {i})\" by simp\n        next\n          from \\<open>is \\<in> iseq xs (Suc i)\\<close> \\<open>Max is = i\\<close> [symmetric]\n          show \"is - {i} \\<in> iseq xs (Suc (Max (is - {i})))\"\n            by simp (rule iseq_diff)\n        next\n          from \\<open>1 < card is\\<close>\n          show \"is - {i} \\<noteq> {}\" by (rule diff_nonempty)\n        next\n          fix js\n          assume \"js \\<in> iseq xs (Suc (Max (is - {i})))\"\n            \"Max js = Max (is - {i})\" \"finite js\" \"js \\<noteq> {}\"\n          from \\<open>xs (Max (is - {Max is})) \\<le> xs (Max is)\\<close>\n            \\<open>Max js = Max (is - {i})\\<close> \\<open>Max is = i\\<close>\n          have \"xs (Max js) \\<le> xs i\" by simp\n          moreover from \\<open>Max is = i\\<close> \\<open>Max (is - {Max is}) < Max is\\<close>\n          have \"Suc (Max (is - {i})) \\<le> i\"\n            by simp\n          with \\<open>js \\<in> iseq xs (Suc (Max (is - {i})))\\<close>\n          have \"js \\<in> iseq xs i\"\n            by (rule iseq_mono)\n          ultimately have \"js \\<union> {i} \\<in> iseq xs (Suc i)\"\n            by (rule iseq_insert)\n          moreover from \\<open>js \\<noteq> {}\\<close> \\<open>finite js\\<close> \\<open>Max js = Max (is - {i})\\<close>\n            \\<open>Max is = i\\<close> [symmetric] \\<open>Max (is - {Max is}) < Max is\\<close>\n          have \"Max (js \\<union> {i}) = i\"\n            by simp\n          ultimately have \"card (js \\<union> {i}) \\<le> card is\" by (rule R)\n          moreover from \\<open>Max is = i\\<close> [symmetric] \\<open>finite js\\<close>\n            \\<open>Max (is - {Max is}) < Max is\\<close> \\<open>Max js = Max (is - {i})\\<close>\n          have \"i \\<notin> js\" by (simp add: max_notin)\n          with \\<open>finite js\\<close>\n          have \"card (js \\<union> {i}) = card ((js \\<union> {i}) - {i}) + 1\"\n            by simp\n          ultimately show \"card js \\<le> card (is - {i})\"\n            using \\<open>i \\<notin> js\\<close> \\<open>Max is = i\\<close> [symmetric] \\<open>is \\<noteq> {}\\<close> \\<open>finite is\\<close>\n            by simp\n        qed simp\n        with H \\<open>Max (is - {Max is}) < Max is\\<close>\n          \\<open>xs (Max (is - {Max is})) \\<le> xs (Max is)\\<close>\n        show ?thesis by auto\n      qed\n    qed\n    then show \"liseq' xs i - 1 \\<in> {0} \\<union>\n      {liseq' xs j |j. j < i \\<and> xs j \\<le> xs i}\" by simp\n  qed simp\n  moreover have \"1 \\<le> liseq' xs i\" by (rule liseq'_ge1)\n  ultimately show ?thesis by simp\nqed\n\nlemma longest_iseq2': \"liseq xs i < liseq' xs i \\<Longrightarrow>\n  liseq xs (Suc i) = liseq' xs i\"\n  apply (rule_tac xs=xs and i=i in liseq'_expand)\n  apply simp\n  apply (rule liseq_eq [symmetric])\n  apply (rule refl)\n  apply assumption\n  apply (case_tac \"Max js' = i\")\n  apply simp\n  apply (drule_tac js=js' in iseq_butlast)\n  apply assumption+\n  apply (drule_tac js=js' in liseq_ge [OF refl])\n  apply simp\n  done\n\nlemma longest_iseq2: \"liseq xs i < liseq' xs i \\<Longrightarrow>\n  liseq xs i + 1 = liseq' xs i\"\n  apply (rule_tac xs=xs and i=i in liseq'_expand)\n  apply simp\n  apply (rule_tac xs=xs and i=i in liseq_expand)\n  apply (drule_tac s=\"Max is\" in sym)\n  apply simp\n  apply (case_tac \"card is \\<le> 1\")\n  apply simp\n  apply (drule iseq_diff)\n  apply (drule_tac i=\"Suc (Max (is - {Max is}))\" and j=\"Max is\" in iseq_mono)\n  apply (simp add: less_eq_Suc_le [symmetric])\n  apply (rule Max_diff)\n  apply simp\n  apply (drule_tac x=\"is - {Max is}\" in meta_spec,\n    drule meta_mp, assumption)\n  apply simp\n  done\n\nlemma longest_iseq3:\n  \"liseq xs j = liseq' xs i \\<Longrightarrow> xs i \\<le> xs j \\<Longrightarrow> i < j \\<Longrightarrow>\n  liseq xs (Suc j) = liseq xs j + 1\"\n  apply (rule_tac xs=xs and i=j in liseq_expand)\n  apply simp\n  apply (rule_tac xs=xs and i=i in liseq'_expand)\n  apply simp\n  apply (rule_tac js=\"isa \\<union> {j}\" in liseq_eq [symmetric])\n  apply (simp add: card_insert card_Diff_singleton_if max_notin)\n  apply (rule iseq_insert)\n  apply simp\n  apply (erule iseq_mono)\n  apply simp\n  apply (case_tac \"j = Max js'\")\n  apply simp\n  apply (drule iseq_diff)\n  apply (drule_tac x=\"js' - {j}\" in meta_spec)\n  apply (drule meta_mp)\n  apply simp\n  apply (case_tac \"card js' \\<le> 1\")\n  apply (erule_tac xs=js' in card_leq1_singleton)\n  apply assumption+\n  apply (simp add: iseq_trivial)\n  apply (erule iseq_mono)\n  apply (simp add: less_eq_Suc_le [symmetric])\n  apply (rule Max_diff)\n  apply simp\n  apply (rule le_diff_iff [THEN iffD1, of 1])\n  apply (simp add: card_0_eq [symmetric] del: card_0_eq)\n  apply (simp add: card_insert)\n  apply (subgoal_tac \"card (js' - {j}) = card js' - 1\")\n  apply (simp add: card_insert card_Diff_singleton_if max_notin)\n  apply (frule_tac A=js' in Max_in)\n  apply assumption\n  apply (simp add: card_Diff_singleton_if)\n  apply (drule_tac js=js' in iseq_butlast)\n  apply assumption\n  apply (erule not_sym)\n  apply (drule_tac x=js' in meta_spec)\n  apply (drule meta_mp)\n  apply assumption\n  apply (simp add: card_insert_disjoint max_notin)\n  done\n\nlemma longest_iseq4:\n  \"liseq xs j = liseq' xs i \\<Longrightarrow> xs i \\<le> xs j \\<Longrightarrow> i < j \\<Longrightarrow>\n  liseq' xs j = liseq' xs i + 1\"\n  apply (rule_tac xs=xs and i=j in liseq_expand)\n  apply simp\n  apply (rule_tac xs=xs and i=i in liseq'_expand)\n  apply simp\n  apply (rule_tac js=\"isa \\<union> {j}\" in liseq'_eq [symmetric])\n  apply (simp add: card_insert card_Diff_singleton_if max_notin)\n  apply (rule iseq_insert)\n  apply simp\n  apply (erule iseq_mono)\n  apply simp\n  apply simp\n  apply simp\n  apply (drule_tac s=\"Max js'\" in sym)\n  apply simp\n  apply (drule iseq_diff)\n  apply (drule_tac x=\"js' - {j}\" in meta_spec)\n  apply (drule meta_mp)\n  apply simp\n  apply (case_tac \"card js' \\<le> 1\")\n  apply (erule_tac xs=js' in card_leq1_singleton)\n  apply assumption+\n  apply (simp add: iseq_trivial)\n  apply (erule iseq_mono)\n  apply (simp add: less_eq_Suc_le [symmetric])\n  apply (rule Max_diff)\n  apply simp\n  apply (rule le_diff_iff [THEN iffD1, of 1])\n  apply (simp add: card_0_eq [symmetric] del: card_0_eq)\n  apply (simp add: card_insert)\n  apply (subgoal_tac \"card (js' - {j}) = card js' - 1\")\n  apply (simp add: card_insert card_Diff_singleton_if max_notin)\n  apply (frule_tac A=js' in Max_in)\n  apply assumption\n  apply (simp add: card_Diff_singleton_if)\n  done\n\nlemma longest_iseq5: \"liseq' xs i \\<le> liseq xs i \\<Longrightarrow>\n  liseq xs (Suc i) = liseq xs i\"\n  apply (rule_tac i=i and xs=xs in liseq'_expand)\n  apply simp\n  apply (rule_tac xs=xs and i=i in liseq_expand)\n  apply simp\n  apply (rule liseq_eq [symmetric])\n  apply (rule refl)\n  apply (erule iseq_mono)\n  apply simp\n  apply (case_tac \"Max js' = i\")\n  apply (drule_tac x=js' in meta_spec)\n  apply simp\n  apply (drule iseq_butlast, assumption, assumption)\n  apply simp\n  done\n\nlemma liseq_empty: \"liseq xs 0 = 0\"\n  apply (rule_tac js=\"{}\" in liseq_eq [symmetric])\n  apply simp\n  apply (rule iseq_trivial)\n  apply (simp add: iseq_def)\n  done\n\nlemma liseq'_singleton: \"liseq' xs 0 = 1\"\n  by (simp add: longest_iseq1 [of _ 0])\n\nlemma liseq_singleton: \"liseq xs (Suc 0) = Suc 0\"\n  by (simp add: longest_iseq2' liseq_empty liseq'_singleton)\n\nlemma liseq'_Suc_unfold:\n  \"A j \\<le> x \\<Longrightarrow>\n   (insert 0 {liseq' A j' |j'. j' < Suc j \\<and> A j' \\<le> x}) =\n   (insert 0 {liseq' A j' |j'. j' < j \\<and> A j' \\<le> x}) \\<union>\n   {liseq' A j}\"\n  by (auto simp add: less_Suc_eq)\n\nlemma liseq'_Suc_unfold':\n  \"\\<not> (A j \\<le> x) \\<Longrightarrow>\n   {liseq' A j' |j'. j' < Suc j \\<and> A j' \\<le> x} =\n   {liseq' A j' |j'. j' < j \\<and> A j' \\<le> x}\"\n  by (auto simp add: less_Suc_eq)\n\nlemma iseq_card_limit:\n  assumes \"is \\<in> iseq A i\"\n  shows \"card is \\<le> i\"\nproof -\n  from assms have \"is \\<subseteq> {0..<i}\"\n    by (auto simp add: iseq_def)\n  with finite_atLeastLessThan have \"card is \\<le> card {0..<i}\"\n    by (rule card_mono)\n  with card_atLeastLessThan show ?thesis by simp\nqed\n\nlemma liseq_limit: \"liseq A i \\<le> i\"\n  by (rule_tac xs=A and i=i in liseq_expand)\n    (simp add: iseq_card_limit)\n\nlemma liseq'_limit: \"liseq' A i \\<le> i + 1\"\n  by (rule_tac xs=A and i=i in liseq'_expand)\n    (simp add: iseq_card_limit)\n\ndefinition max_ext :: \"(nat \\<Rightarrow> 'a::linorder) \\<Rightarrow> nat \\<Rightarrow> nat \\<Rightarrow> nat\" where\n  \"max_ext A i j = Max ({0} \\<union> {liseq' A j' |j'. j' < j \\<and> A j' \\<le> A i})\"\n\nlemma max_ext_limit: \"max_ext A i j \\<le> j\"\n  apply (auto simp add: max_ext_def)\n  apply (drule Suc_leI)\n  apply (cut_tac i=j' and A=A in liseq'_limit)\n  apply simp\n  done\n\n\ntext \\<open>Proof functions\\<close>\n\nabbreviation (input)\n  \"arr_conv a \\<equiv> (\\<lambda>n. a (int n))\"\n\nlemma idx_conv_suc:\n  \"0 \\<le> i \\<Longrightarrow> nat (i + 1) = nat i + 1\"\n  by simp\n\nabbreviation liseq_ends_at' :: \"(int \\<Rightarrow> 'a::linorder) \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"liseq_ends_at' A i \\<equiv> int (liseq' (\\<lambda>l. A (int l)) (nat i))\"\n\nabbreviation liseq_prfx' :: \"(int \\<Rightarrow> 'a::linorder) \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"liseq_prfx' A i \\<equiv> int (liseq (\\<lambda>l. A (int l)) (nat i))\"\n\nabbreviation max_ext' :: \"(int \\<Rightarrow> 'a::linorder) \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\" where\n  \"max_ext' A i j \\<equiv> int (max_ext (\\<lambda>l. A (int l)) (nat i) (nat j))\"\n\nspark_proof_functions\n  liseq_ends_at = \"liseq_ends_at' :: (int \\<Rightarrow> int) \\<Rightarrow> int \\<Rightarrow> int\"\n  liseq_prfx = \"liseq_prfx' :: (int \\<Rightarrow> int) \\<Rightarrow> int \\<Rightarrow> int\"\n  max_ext = \"max_ext' :: (int \\<Rightarrow> int) \\<Rightarrow> int \\<Rightarrow> int \\<Rightarrow> int\"\n\n\ntext \\<open>The verification conditions\\<close>\n\nspark_open \"liseq/liseq_length\"\n\nspark_vc procedure_liseq_length_5\n  by (simp_all add: liseq_singleton liseq'_singleton)\n\nspark_vc procedure_liseq_length_6\nproof -\n  from H1 H2 H3 H4\n  have eq: \"liseq (arr_conv a) (nat i) =\n    liseq' (arr_conv a) (nat pmax)\"\n    by simp\n  from H14 H3 H4\n  have pmax1: \"arr_conv a (nat pmax) \\<le> arr_conv a (nat i)\"\n    by simp\n  from H3 H4 have pmax2: \"nat pmax < nat i\"\n    by simp\n  {\n    fix i2\n    assume i2: \"0 \\<le> i2\" \"i2 \\<le> i\"\n    have \"(l(i := l pmax + 1)) i2 =\n      int (liseq' (arr_conv a) (nat i2))\"\n    proof (cases \"i2 = i\")\n      case True\n      from eq pmax1 pmax2 have \"liseq' (arr_conv a) (nat i) =\n        liseq' (arr_conv a) (nat pmax) + 1\"\n        by (rule longest_iseq4)\n      with True H1 H3 H4 show ?thesis\n        by simp\n    next\n      case False\n      with H1 i2 show ?thesis\n        by simp\n    qed\n  }\n  then show ?C1 by simp\n  from eq pmax1 pmax2\n  have \"liseq (arr_conv a) (Suc (nat i)) =\n    liseq (arr_conv a) (nat i) + 1\"\n    by (rule longest_iseq3)\n with H2 H3 H4 show ?C2\n    by (simp add: idx_conv_suc)\nqed\n\nspark_vc procedure_liseq_length_7\nproof -\n  from H1 show ?C1\n    by (simp add: max_ext_def longest_iseq1 [of _ \"nat i\"])\n  from H6\n  have m: \"max_ext (arr_conv a) (nat i) (nat i) + 1 =\n    liseq' (arr_conv a) (nat i)\"\n    by (simp add: max_ext_def longest_iseq1 [of _ \"nat i\"])\n  with H2 H18\n  have gt: \"liseq (arr_conv a) (nat i) < liseq' (arr_conv a) (nat i)\"\n    by simp\n  then have \"liseq' (arr_conv a) (nat i) = liseq (arr_conv a) (nat i) + 1\"\n    by (rule longest_iseq2 [symmetric])\n  with H2 m show ?C2 by simp\n  from gt have \"liseq (arr_conv a) (Suc (nat i)) = liseq' (arr_conv a) (nat i)\"\n    by (rule longest_iseq2')\n  with m H6 show ?C3 by (simp add: idx_conv_suc)\nqed\n\nspark_vc procedure_liseq_length_8\nproof -\n  {\n    fix i2\n    assume i2: \"0 \\<le> i2\" \"i2 \\<le> i\"\n    have \"(l(i := max_ext' a i i + 1)) i2 =\n      int (liseq' (arr_conv a) (nat i2))\"\n    proof (cases \"i2 = i\")\n      case True\n      with H1 show ?thesis\n        by (simp add: max_ext_def longest_iseq1 [of _ \"nat i\"])\n    next\n      case False\n      with H1 i2 show ?thesis by simp\n    qed\n  }\n  then show ?C1 by simp\n  from H2 H6 H18\n  have \"liseq' (arr_conv a) (nat i) \\<le> liseq (arr_conv a) (nat i)\"\n    by (simp add: max_ext_def longest_iseq1 [of _ \"nat i\"])\n  then have \"liseq (arr_conv a) (Suc (nat i)) = liseq (arr_conv a) (nat i)\"\n    by (rule longest_iseq5)\n  with H2 H6 show ?C2 by (simp add: idx_conv_suc)\nqed\n\nspark_vc procedure_liseq_length_12\n  by (simp add: max_ext_def)\n\nspark_vc procedure_liseq_length_13\n  using H1 H6 H13 H21 H22\n  by (simp add: max_ext_def\n    idx_conv_suc liseq'_Suc_unfold max_def del: Max_less_iff)\n\nspark_vc procedure_liseq_length_14\n  using H1 H6 H13 H21\n  by (cases \"a j \\<le> a i\")\n    (simp_all add: max_ext_def\n      idx_conv_suc liseq'_Suc_unfold liseq'_Suc_unfold')\n\nspark_vc procedure_liseq_length_19\n  using H3 H4 H5 H8 H9\n  apply (rule_tac y=\"int (nat i)\" in order_trans)\n  apply (cut_tac A=\"arr_conv a\" and i=\"nat i\" and j=\"nat i\" in max_ext_limit)\n  apply simp_all\n  done\n\nspark_vc procedure_liseq_length_23\n  using H2 H3 H4 H7 H8 H11\n  apply (rule_tac y=\"int (nat i)\" in order_trans)\n  apply (cut_tac A=\"arr_conv a\" and i=\"nat i\" in liseq_limit)\n  apply simp_all\n  done\n\nspark_vc procedure_liseq_length_29\n  using H2 H3 H8 H13\n  by (simp add: add1_zle_eq [symmetric])\n\nspark_end\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/SPARK/Examples/Liseq/Longest_Increasing_Subsequence.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894576856561, "lm_q2_score": 0.8397339656668287, "lm_q1q2_score": 0.7513850997392469}}
{"text": "(*  Title:      Fun With Functions\n    Author:     Tobias Nipkow\n*)\n\ntheory FunWithFunctions imports Complex_Main begin\n\ntext{* See \\cite{Tao2006}. Was first brought to our attention by Herbert\nEhler who provided a similar proof. *}\n\ntheorem identity1: fixes f :: \"nat \\<Rightarrow> nat\"\nassumes fff: \"\\<And>n. f(f(n)) < f(Suc(n))\"\nshows \"f(n) = n\"\nproof -\n  { fix m n have key: \"n \\<le> m \\<Longrightarrow> n \\<le> f(m)\"\n    proof(induct n arbitrary: m)\n      case 0 show ?case by simp\n    next\n      case (Suc n)\n      hence \"m \\<noteq> 0\" by simp\n      then obtain k where [simp]: \"m = Suc k\" by (metis not0_implies_Suc)\n      have \"n \\<le> f(k)\" using Suc by simp\n      hence \"n \\<le> f(f(k))\" using Suc by simp\n      also have \"\\<dots> < f(m)\" using fff by simp\n      finally show ?case by simp\n    qed }\n  hence \"\\<And>n. n \\<le> f(n)\" by simp\n  hence \"\\<And>n. f(n) < f(Suc n)\" by(metis fff order_le_less_trans)\n  hence \"f(n) < n+1\" by (metis fff lift_Suc_mono_less_iff[of f] Suc_eq_plus1)\n  with `n \\<le> f(n)` show \"f n = n\" by arith\nqed\n\n\ntext{* See \\cite{Tao2006}. Possible extension:\nShould also hold if the range of @{text f} is the reals!\n*}\n\nlemma identity2: fixes f :: \"nat \\<Rightarrow> nat\"\nassumes \"f(k) = k\" and \"k \\<ge> 2\"\nand f_times: \"\\<And>m n. f(m*n) = f(m)*f(n)\"\nand f_mono: \"\\<And>m n. m<n \\<Longrightarrow> f m < f n\"\nshows \"f(n) = n\"\nproof -\n  have 0: \"f(0) = 0\"\n    by (metis f_mono f_times mult_1_right mult_is_0 nat_less_le nat_mult_eq_cancel_disj not_less_eq)\n  have 1: \"f(1) = 1\"\n    by (metis f_mono f_times gr_implies_not0 mult_eq_self_implies_10 nat_mult_1_right zero_less_one)\n  have 2: \"f 2 = 2\"\n  proof -\n    have \"2 + (k - 2) = k\" using `k \\<ge> 2` by arith\n    hence \"f(2) \\<le> 2\"\n      using mono_nat_linear_lb[of f 2 \"k - 2\",OF f_mono] `f k = k`\n      by simp arith\n    thus \"f 2 = 2\" using 1 f_mono[of 1 2] by arith\n  qed\n  show ?thesis\n  proof(induct rule:less_induct)\n    case (less i)\n    show ?case\n    proof cases\n      assume \"i\\<le>1\" thus ?case using 0 1 by (auto simp add:le_Suc_eq)\n    next\n      assume \"~i\\<le>1\"\n      show ?case\n      proof cases\n        assume \"i mod 2 = 0\"\n        hence \"EX k. i=2*k\" by arith\n        then obtain k where \"i = 2*k\" ..\n        hence \"0 < k\" and \"k<i\" using `~i\\<le>1` by arith+\n        hence \"f(k) = k\" using less(1) by blast\n        thus \"f(i) = i\" using `i = 2*k` by(simp add:f_times 2)\n      next\n        assume \"i mod 2 \\<noteq> 0\"\n        hence \"EX k. i=2*k+1\" by arith\n        then obtain k where \"i = 2*k+1\" ..\n        hence \"0<k\" and \"k+1<i\" using `~i\\<le>1` by arith+\n        have \"2*k < f(2*k+1)\"\n        proof -\n          have \"2*k = 2*f(k)\" using less(1) `i=2*k+1` by simp\n          also have \"\\<dots> = f(2*k)\" by(simp add:f_times 2)\n          also have \"\\<dots> < f(2*k+1)\" using f_mono[of \"2*k\" \"2*k+1\"] by simp\n          finally show ?thesis .\n        qed\n        moreover\n        have \"f(2*k+1) < 2*(k+1)\"\n        proof -\n          have \"f(2*k+1) < f(2*k+2)\" using f_mono[of \"2*k+1\" \"2*k+2\"] by simp\n          also have \"\\<dots> = f(2*(k+1))\" by simp\n          also have \"\\<dots> = 2*f(k+1)\" by(simp only:f_times 2)\n          also have \"f(k+1) = k+1\" using less(1) `i=2*k+1` `~i\\<le>1` by simp\n          finally show ?thesis .\n        qed\n        ultimately show \"f(i) = i\" using `i = 2*k+1` by arith\n      qed\n    qed\n  qed\nqed\n\n\ntext{* One more from Tao's booklet. If @{text f} is also assumed to be\ncontinuous, @{term\"f(x::real) = x+1\"} holds for all reals, not only\nrationals. Extend the proof! *}\n\ntheorem plus1:\nfixes f :: \"real \\<Rightarrow> real\"\nassumes 0: \"f 0 = 1\" and f_add: \"\\<And>x y. f(x+y+1) = f x + f y\"\n\nassumes \"r : \\<rat>\" shows \"f(r) = r + 1\"\nproof -\n  { fix i :: int have \"f(real i) = real i + 1\"\n    proof (induct i rule: int_induct [where k=0])\n      case base show ?case using 0 by simp\n    next\n      case (step1 i)\n      have \"f(real(i+1)) = f(real i + 0 + 1)\" by simp\n      also have \"\\<dots> = f(real i) + f 0\" by(rule f_add)\n      also have \"\\<dots> = real(i+1) + 1\" using step1 0 by simp\n      finally show ?case .\n    next\n      case (step2 i)\n      have \"f(real i) = f(real(i - 1) + 0 + 1)\" by simp\n      also have \"\\<dots> = f(real(i - 1)) + f 0\" by(rule f_add)\n      also have \"\\<dots> = f(real(i - 1)) + 1 \" using 0 by simp\n      finally show ?case using step2 by simp\n    qed }\n  note f_int = this\n  { fix n r have \"f(real(Suc n)*r + real n) = real(Suc n) * f r\"\n    proof(induct n)\n      case 0 show ?case by simp\n    next\n      case (Suc n)\n      have \"real(Suc(Suc n))*r + real(Suc n) =\n            r + (real(Suc n)*r + real n) + 1\" (is \"?a = ?b\")\n        by(simp add:real_of_nat_Suc field_simps)\n      hence \"f ?a = f ?b\" by simp\n      also have \"\\<dots> = f r + f(real(Suc n)*r + real n)\" by(rule f_add)\n      also have \"\\<dots> = f r + real(Suc n) * f r\" by(simp only:Suc)\n      finally show ?case by(simp add:real_of_nat_Suc field_simps)\n    qed }\n  note 1 = this\n  { fix n::nat and r assume \"n\\<noteq>0\"\n    have \"f(real(n)*r + real(n - 1)) = real(n) * f r\"\n    proof(cases n)\n      case 0 thus ?thesis using `n\\<noteq>0` by simp\n    next\n      case Suc thus ?thesis using `n\\<noteq>0` by (simp add:1)\n    qed }\n  note f_mult = this\n  from `r:\\<rat>` obtain i::int and n::nat where r: \"r = real i/real n\" and \"n\\<noteq>0\"\n    by(fastforce simp:Rats_eq_int_div_nat)\n  have \"real(n)*f(real i/real n) = f(real i + real(n - 1))\"\n    using `n\\<noteq>0` by(simp add:f_mult[symmetric])\n  also have \"\\<dots> = f(real(i + int n - 1))\" using `n\\<noteq>0`[simplified]\n    by (metis One_nat_def Suc_leI int_1 add_diff_eq real_of_int_add real_of_int_of_nat_eq zdiff_int)\n  also have \"\\<dots> = real(i + int n - 1) + 1\" by(rule f_int)\n  also have \"\\<dots> = real i + real n\" by arith\n  finally show ?thesis using `n\\<noteq>0` unfolding r by (simp add:field_simps)\nqed\n\n\ntext{* The only total model of a naive recursion equation of factorial on\nintegers is 0 for all negative arguments. Probably folklore. *}\n\ntheorem ifac_neg0: fixes ifac :: \"int \\<Rightarrow> int\"\nassumes ifac_rec: \"\\<And>i. ifac i = (if i=0 then 1 else i*ifac(i - 1))\"\nshows \"i<0 \\<Longrightarrow> ifac i = 0\"\nproof(rule ccontr)\n  assume 0: \"i<0\" \"ifac i \\<noteq> 0\"\n  { fix j assume \"j \\<le> i\"\n    have \"ifac j \\<noteq> 0\"\n      apply(rule int_le_induct[OF `j\\<le>i`])\n       apply(rule `ifac i \\<noteq> 0`)\n      apply (metis `i<0` ifac_rec linorder_not_le mult_eq_0_iff)\n      done\n  } note below0 = this\n  { fix j assume \"j<i\"\n    have \"1 < -j\" using `j<i` `i<0` by arith\n    have \"ifac(j - 1) \\<noteq> 0\" using `j<i` by(simp add: below0)\n    then have \"\\<bar>ifac (j - 1)\\<bar> < (-j) * \\<bar>ifac (j - 1)\\<bar>\" using `j<i`\n      mult_le_less_imp_less[OF order_refl[of \"abs(ifac(j - 1))\"] `1 < -j`]\n      by(simp add:mult.commute)\n    hence \"abs(ifac(j - 1)) < abs(ifac j)\"\n      using `1 < -j` by(simp add: ifac_rec[of \"j\"] abs_mult)\n  } note not_wf = this\n  let ?f = \"%j. nat(abs(ifac(i - int(j+1))))\"\n  obtain k where \"\\<not> ?f (Suc k) < ?f k\"\n    using wf_no_infinite_down_chainE[OF wf_less, of \"?f\"] by blast\n  moreover have \"i - int (k + 1) - 1 = i - int (Suc k + 1)\" by arith\n  ultimately show False using not_wf[of \"i - int(k+1)\"]\n    by (simp only:) arith\nqed\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/FunWithFunctions/FunWithFunctions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.8947894632969137, "lm_q1q2_score": 0.7513850990679494}}
{"text": "(* Author: Tobias Nipkow *)\n\nsubsection \\<open>Invariant\\<close>\n\ntheory AVL_Set\nimports\n  AVL_Set_Code\n  \"HOL-Number_Theory.Fib\"\nbegin\n\nfun avl :: \"'a tree_ht \\<Rightarrow> bool\" where\n\"avl Leaf = True\" |\n\"avl (Node l (a,n) r) =\n (abs(int(height l) - int(height r)) \\<le> 1 \\<and>\n  n = max (height l) (height r) + 1 \\<and> avl l \\<and> avl r)\"\n\nsubsubsection \\<open>Insertion maintains AVL balance\\<close>\n\ndeclare Let_def [simp]\n\nlemma ht_height[simp]: \"avl t \\<Longrightarrow> ht t = height t\"\nby (cases t rule: tree2_cases) simp_all\n\ntext \\<open>First, a fast but relatively manual proof with many lemmas:\\<close>\n\nlemma height_balL:\n  \"\\<lbrakk> avl l; avl r; height l = height r + 2 \\<rbrakk> \\<Longrightarrow>\n   height (balL l a r) \\<in> {height r + 2, height r + 3}\"\nby (auto simp:node_def balL_def split:tree.split)\n\nlemma height_balR:\n  \"\\<lbrakk> avl l; avl r; height r = height l + 2 \\<rbrakk> \\<Longrightarrow>\n   height (balR l a r) : {height l + 2, height l + 3}\"\nby(auto simp add:node_def balR_def split:tree.split)\n\nlemma height_node[simp]: \"height(node l a r) = max (height l) (height r) + 1\"\nby (simp add: node_def)\n\nlemma height_balL2:\n  \"\\<lbrakk> avl l; avl r; height l \\<noteq> height r + 2 \\<rbrakk> \\<Longrightarrow>\n   height (balL l a r) = 1 + max (height l) (height r)\"\nby (simp_all add: balL_def)\n\nlemma height_balR2:\n  \"\\<lbrakk> avl l;  avl r;  height r \\<noteq> height l + 2 \\<rbrakk> \\<Longrightarrow>\n   height (balR l a r) = 1 + max (height l) (height r)\"\nby (simp_all add: balR_def)\n\nlemma avl_balL: \n  \"\\<lbrakk> avl l; avl r; height r - 1 \\<le> height l \\<and> height l \\<le> height r + 2 \\<rbrakk> \\<Longrightarrow> avl(balL l a r)\"\nby(auto simp: balL_def node_def split!: if_split tree.split)\n\nlemma avl_balR: \n  \"\\<lbrakk> avl l; avl r; height l - 1 \\<le> height r \\<and> height r \\<le> height l + 2 \\<rbrakk> \\<Longrightarrow> avl(balR l a r)\"\nby(auto simp: balR_def node_def split!: if_split tree.split)\n\ntext\\<open>Insertion maintains the AVL property. Requires simultaneous proof.\\<close>\n\ntheorem avl_insert:\n  \"avl t \\<Longrightarrow> avl(insert x t)\"\n  \"avl t \\<Longrightarrow> height (insert x t) \\<in> {height t, height t + 1}\"\nproof (induction t rule: tree2_induct)\n  case (Node l a _ r)\n  case 1\n  show ?case\n  proof(cases \"x = a\")\n    case True with 1 show ?thesis by simp\n  next\n    case False\n    show ?thesis \n    proof(cases \"x<a\")\n      case True with 1 Node(1,2) show ?thesis by (auto intro!:avl_balL)\n    next\n      case False with 1 Node(3,4) \\<open>x\\<noteq>a\\<close> show ?thesis by (auto intro!:avl_balR)\n    qed\n  qed\n  case 2\n  show ?case\n  proof(cases \"x = a\")\n    case True with 2 show ?thesis by simp\n  next\n    case False\n    show ?thesis \n    proof(cases \"x<a\")\n      case True\n      show ?thesis\n      proof(cases \"height (insert x l) = height r + 2\")\n        case False with 2 Node(1,2) \\<open>x < a\\<close> show ?thesis by (auto simp: height_balL2)\n      next\n        case True \n        hence \"(height (balL (insert x l) a r) = height r + 2) \\<or>\n          (height (balL (insert x l) a r) = height r + 3)\" (is \"?A \\<or> ?B\")\n          using 2 Node(1,2) height_balL[OF _ _ True] by simp\n        thus ?thesis\n        proof\n          assume ?A with 2 \\<open>x < a\\<close> show ?thesis by (auto)\n        next\n          assume ?B with 2 Node(2) True \\<open>x < a\\<close> show ?thesis by (simp) arith\n        qed\n      qed\n    next\n      case False\n      show ?thesis\n      proof(cases \"height (insert x r) = height l + 2\")\n        case False with 2 Node(3,4) \\<open>\\<not>x < a\\<close> show ?thesis by (auto simp: height_balR2)\n      next\n        case True \n        hence \"(height (balR l a (insert x r)) = height l + 2) \\<or>\n          (height (balR l a (insert x r)) = height l + 3)\"  (is \"?A \\<or> ?B\")\n          using 2 Node(3) height_balR[OF _ _ True] by simp\n        thus ?thesis\n        proof\n          assume ?A with 2 \\<open>\\<not>x < a\\<close> show ?thesis by (auto)\n        next\n          assume ?B with 2 Node(4) True \\<open>\\<not>x < a\\<close> show ?thesis by (simp) arith\n        qed\n      qed\n    qed\n  qed\nqed simp_all\n\ntext \\<open>Now an automatic proof without lemmas:\\<close>\n\ntheorem avl_insert_auto: \"avl t \\<Longrightarrow>\n  avl(insert x t) \\<and> height (insert x t) \\<in> {height t, height t + 1}\"\napply (induction t rule: tree2_induct)\n (* if you want to save a few secs: apply (auto split!: if_split) *)\n apply (auto simp: balL_def balR_def node_def max_absorb2 split!: if_split tree.split)\ndone\n\n\nsubsubsection \\<open>Deletion maintains AVL balance\\<close>\n\nlemma avl_split_max:\n  \"\\<lbrakk> avl t; t \\<noteq> Leaf \\<rbrakk> \\<Longrightarrow>\n  avl (fst (split_max t)) \\<and>\n  height t \\<in> {height(fst (split_max t)), height(fst (split_max t)) + 1}\"\nby(induct t rule: split_max_induct)\n  (auto simp: balL_def node_def max_absorb2 split!: prod.split if_split tree.split)\n\ntext\\<open>Deletion maintains the AVL property:\\<close>\n\ntheorem avl_delete:\n  \"avl t \\<Longrightarrow> avl(delete x t)\"\n  \"avl t \\<Longrightarrow> height t \\<in> {height (delete x t), height (delete x t) + 1}\"\nproof (induct t rule: tree2_induct)\n  case (Node l a n r)\n  case 1\n  show ?case\n  proof(cases \"x = a\")\n    case True thus ?thesis\n      using 1 avl_split_max[of l] by (auto intro!: avl_balR split: prod.split)\n  next\n    case False thus ?thesis\n      using Node 1 by (auto intro!: avl_balL avl_balR)\n  qed\n  case 2\n  show ?case\n  proof(cases \"x = a\")\n    case True thus ?thesis using 2 avl_split_max[of l]\n      by(auto simp: balR_def max_absorb2 split!: if_splits prod.split tree.split)\n  next\n    case False\n    show ?thesis\n    proof(cases \"x<a\")\n      case True\n      show ?thesis\n      proof(cases \"height r = height (delete x l) + 2\")\n        case False\n        thus ?thesis using 2 Node(1,2) \\<open>x < a\\<close> by(auto simp: balR_def)\n      next\n        case True\n        thus ?thesis using height_balR[OF _ _ True, of a] 2 Node(1,2) \\<open>x < a\\<close> by simp linarith\n      qed\n    next\n      case False\n      show ?thesis\n      proof(cases \"height l = height (delete x r) + 2\")\n        case False\n        thus ?thesis using 2 Node(3,4) \\<open>\\<not>x < a\\<close> \\<open>x \\<noteq> a\\<close> by(auto simp: balL_def)\n      next\n        case True\n        thus ?thesis\n          using height_balL[OF _ _ True, of a] 2 Node(3,4) \\<open>\\<not>x < a\\<close> \\<open>x \\<noteq> a\\<close> by simp linarith\n      qed\n    qed\n  qed\nqed simp_all\n\ntext \\<open>A more automatic proof.\nComplete automation as for insertion seems hard due to resource requirements.\\<close>\n\ntheorem avl_delete_auto:\n  \"avl t \\<Longrightarrow> avl(delete x t)\"\n  \"avl t \\<Longrightarrow> height t \\<in> {height (delete x t), height (delete x t) + 1}\"\nproof (induct t rule: tree2_induct)\n  case (Node l a n r)\n  case 1\n  thus ?case\n    using Node avl_split_max[of l] by (auto intro!: avl_balL avl_balR split: prod.split)\n  case 2\n  show ?case\n    using 2 Node avl_split_max[of l]\n      by auto\n         (auto simp: balL_def balR_def max_absorb1 max_absorb2  split!: tree.splits prod.splits if_splits)\nqed simp_all\n\n\nsubsection \"Overall correctness\"\n\ninterpretation S: Set_by_Ordered\nwhere empty = empty and isin = isin and insert = insert and delete = delete\nand inorder = inorder and inv = avl\nproof (standard, goal_cases)\n  case 1 show ?case by (simp add: empty_def)\nnext\n  case 2 thus ?case by(simp add: isin_set_inorder)\nnext\n  case 3 thus ?case by(simp add: inorder_insert)\nnext\n  case 4 thus ?case by(simp add: inorder_delete)\nnext\n  case 5 thus ?case by (simp add: empty_def)\nnext\n  case 6 thus ?case by (simp add: avl_insert(1))\nnext\n  case 7 thus ?case by (simp add: avl_delete(1))\nqed\n\n\nsubsection \\<open>Height-Size Relation\\<close>\n\ntext \\<open>Any AVL tree of height \\<open>n\\<close> has at least \\<open>fib (n+2)\\<close> leaves:\\<close>\n\ntheorem avl_fib_bound:\n  \"avl t \\<Longrightarrow> fib(height t + 2) \\<le> size1 t\"\nproof (induction rule: tree2_induct)\n  case (Node l a h r)\n  have 1: \"height l + 1 \\<le> height r + 2\" and 2: \"height r + 1 \\<le> height l + 2\"\n    using Node.prems by auto\n  have \"fib (max (height l) (height r) + 3) \\<le> size1 l + size1 r\"\n  proof cases\n    assume \"height l \\<ge> height r\"\n    hence \"fib (max (height l) (height r) + 3) = fib (height l + 3)\"\n      by(simp add: max_absorb1)\n    also have \"\\<dots> = fib (height l + 2) + fib (height l + 1)\"\n      by (simp add: numeral_eq_Suc)\n    also have \"\\<dots> \\<le> size1 l + fib (height l + 1)\"\n      using Node by (simp)\n    also have \"\\<dots> \\<le> size1 r + size1 l\"\n      using Node fib_mono[OF 1] by auto\n    also have \"\\<dots> = size1 (Node l (a,h) r)\"\n      by simp\n    finally show ?thesis \n      by (simp)\n  next\n    assume \"\\<not> height l \\<ge> height r\"\n    hence \"fib (max (height l) (height r) + 3) = fib (height r + 3)\"\n      by(simp add: max_absorb1)\n    also have \"\\<dots> = fib (height r + 2) + fib (height r + 1)\"\n      by (simp add: numeral_eq_Suc)\n    also have \"\\<dots> \\<le> size1 r + fib (height r + 1)\"\n      using Node by (simp)\n    also have \"\\<dots> \\<le> size1 r + size1 l\"\n      using Node fib_mono[OF 2] by auto\n    also have \"\\<dots> = size1 (Node l (a,h) r)\"\n      by simp\n    finally show ?thesis \n      by (simp)\n  qed\n  also have \"\\<dots> = size1 (Node l (a,h) r)\"\n    by simp\n  finally show ?case by (simp del: fib.simps add: numeral_eq_Suc)\nqed auto\n\nlemma avl_fib_bound_auto: \"avl t \\<Longrightarrow> fib (height t + 2) \\<le> size1 t\"\nproof (induction t rule: tree2_induct)\n  case Leaf thus ?case by (simp)\nnext\n  case (Node l a h r)\n  have 1: \"height l + 1 \\<le> height r + 2\" and 2: \"height r + 1 \\<le> height l + 2\"\n    using Node.prems by auto\n  have left: \"height l \\<ge> height r \\<Longrightarrow> ?case\" (is \"?asm \\<Longrightarrow> _\")\n    using Node fib_mono[OF 1] by (simp add: max.absorb1)\n  have right: \"height l \\<le> height r \\<Longrightarrow> ?case\"\n    using Node fib_mono[OF 2] by (simp add: max.absorb2)\n  show ?case using left right using Node.prems by simp linarith\nqed\n\ntext \\<open>An exponential lower bound for \\<^const>\\<open>fib\\<close>:\\<close>\n\nlemma fib_lowerbound:\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n  shows \"real (fib(n+2)) \\<ge> \\<phi> ^ n\"\nproof (induction n rule: fib.induct)\n  case 1\n  then show ?case by simp\nnext\n  case 2\n  then show ?case by (simp add: \\<phi>_def real_le_lsqrt)\nnext\n  case (3 n)\n  have \"\\<phi> ^ Suc (Suc n) = \\<phi> ^ 2 * \\<phi> ^ n\"\n    by (simp add: field_simps power2_eq_square)\n  also have \"\\<dots> = (\\<phi> + 1) * \\<phi> ^ n\"\n    by (simp_all add: \\<phi>_def power2_eq_square field_simps)\n  also have \"\\<dots> = \\<phi> ^ Suc n + \\<phi> ^ n\"\n      by (simp add: field_simps)\n  also have \"\\<dots> \\<le> real (fib (Suc n + 2)) + real (fib (n + 2))\"\n      by (intro add_mono \"3.IH\")\n  finally show ?case by simp\nqed\n\ntext \\<open>The size of an AVL tree is (at least) exponential in its height:\\<close>\n\nlemma avl_size_lowerbound:\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n  assumes \"avl t\"\n  shows   \"\\<phi> ^ (height t) \\<le> size1 t\"\nproof -\n  have \"\\<phi> ^ height t \\<le> fib (height t + 2)\"\n    unfolding \\<phi>_def by(rule fib_lowerbound)\n  also have \"\\<dots> \\<le> size1 t\"\n    using avl_fib_bound[of t] assms by simp\n  finally show ?thesis .\nqed\n\ntext \\<open>The height of an AVL tree is most \\<^term>\\<open>(1/log 2 \\<phi>)\\<close> \\<open>\\<approx> 1.44\\<close> times worse\nthan \\<^term>\\<open>log 2 (size1 t)\\<close>:\\<close>\n\nlemma  avl_height_upperbound:\n  defines \"\\<phi> \\<equiv> (1 + sqrt 5) / 2\"\n  assumes \"avl t\"\n  shows   \"height t \\<le> (1/log 2 \\<phi>) * log 2 (size1 t)\"\nproof -\n  have \"\\<phi> > 0\" \"\\<phi> > 1\" by(auto simp: \\<phi>_def pos_add_strict)\n  hence \"height t = log \\<phi> (\\<phi> ^ height t)\" by(simp add: log_nat_power)\n  also have \"\\<dots> \\<le> log \\<phi> (size1 t)\"\n    using avl_size_lowerbound[OF assms(2), folded \\<phi>_def] \\<open>1 < \\<phi>\\<close>\n    by (simp add: le_log_of_power) \n  also have \"\\<dots> = (1/log 2 \\<phi>) * log 2 (size1 t)\"\n    by(simp add: log_base_change[of 2 \\<phi>])\n  finally show ?thesis .\nqed\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/AVL_Set.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789454880027, "lm_q2_score": 0.8397339656668286, "lm_q1q2_score": 0.7513850973832649}}
{"text": "(*  Title:      HOL/Library/Boolean_Algebra.thy\n    Author:     Brian Huffman\n*)\n\nsection \\<open>Boolean Algebras\\<close>\n\ntheory Boolean_Algebra\n  imports Main\nbegin\n\nlocale boolean =\n  fixes conj :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<sqinter>\" 70)\n  fixes disj :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" (infixr \"\\<squnion>\" 65)\n  fixes compl :: \"'a \\<Rightarrow> 'a\" (\"\\<sim> _\" [81] 80)\n  fixes zero :: \"'a\" (\"\\<zero>\")\n  fixes one  :: \"'a\" (\"\\<one>\")\n  assumes conj_assoc: \"(x \\<sqinter> y) \\<sqinter> z = x \\<sqinter> (y \\<sqinter> z)\"\n  assumes disj_assoc: \"(x \\<squnion> y) \\<squnion> z = x \\<squnion> (y \\<squnion> z)\"\n  assumes conj_commute: \"x \\<sqinter> y = y \\<sqinter> x\"\n  assumes disj_commute: \"x \\<squnion> y = y \\<squnion> x\"\n  assumes conj_disj_distrib: \"x \\<sqinter> (y \\<squnion> z) = (x \\<sqinter> y) \\<squnion> (x \\<sqinter> z)\"\n  assumes disj_conj_distrib: \"x \\<squnion> (y \\<sqinter> z) = (x \\<squnion> y) \\<sqinter> (x \\<squnion> z)\"\n  assumes conj_one_right [simp]: \"x \\<sqinter> \\<one> = x\"\n  assumes disj_zero_right [simp]: \"x \\<squnion> \\<zero> = x\"\n  assumes conj_cancel_right [simp]: \"x \\<sqinter> \\<sim> x = \\<zero>\"\n  assumes disj_cancel_right [simp]: \"x \\<squnion> \\<sim> x = \\<one>\"\nbegin\n\nsublocale conj: abel_semigroup conj\n  by standard (fact conj_assoc conj_commute)+\n\nsublocale disj: abel_semigroup disj\n  by standard (fact disj_assoc disj_commute)+\n\nlemmas conj_left_commute = conj.left_commute\n\nlemmas disj_left_commute = disj.left_commute\n\nlemmas conj_ac = conj.assoc conj.commute conj.left_commute\nlemmas disj_ac = disj.assoc disj.commute disj.left_commute\n\nlemma dual: \"boolean disj conj compl one zero\"\n  apply (rule boolean.intro)\n  apply (rule disj_assoc)\n  apply (rule conj_assoc)\n  apply (rule disj_commute)\n  apply (rule conj_commute)\n  apply (rule disj_conj_distrib)\n  apply (rule conj_disj_distrib)\n  apply (rule disj_zero_right)\n  apply (rule conj_one_right)\n  apply (rule disj_cancel_right)\n  apply (rule conj_cancel_right)\n  done\n\n\nsubsection \\<open>Complement\\<close>\n\nlemma complement_unique:\n  assumes 1: \"a \\<sqinter> x = \\<zero>\"\n  assumes 2: \"a \\<squnion> x = \\<one>\"\n  assumes 3: \"a \\<sqinter> y = \\<zero>\"\n  assumes 4: \"a \\<squnion> y = \\<one>\"\n  shows \"x = y\"\nproof -\n  have \"(a \\<sqinter> x) \\<squnion> (x \\<sqinter> y) = (a \\<sqinter> y) \\<squnion> (x \\<sqinter> y)\"\n    using 1 3 by simp\n  then have \"(x \\<sqinter> a) \\<squnion> (x \\<sqinter> y) = (y \\<sqinter> a) \\<squnion> (y \\<sqinter> x)\"\n    using conj_commute by simp\n  then have \"x \\<sqinter> (a \\<squnion> y) = y \\<sqinter> (a \\<squnion> x)\"\n    using conj_disj_distrib by simp\n  then have \"x \\<sqinter> \\<one> = y \\<sqinter> \\<one>\"\n    using 2 4 by simp\n  then show \"x = y\"\n    using conj_one_right by simp\nqed\n\nlemma compl_unique: \"x \\<sqinter> y = \\<zero> \\<Longrightarrow> x \\<squnion> y = \\<one> \\<Longrightarrow> \\<sim> x = y\"\n  by (rule complement_unique [OF conj_cancel_right disj_cancel_right])\n\nlemma double_compl [simp]: \"\\<sim> (\\<sim> x) = x\"\nproof (rule compl_unique)\n  from conj_cancel_right show \"\\<sim> x \\<sqinter> x = \\<zero>\"\n    by (simp only: conj_commute)\n  from disj_cancel_right show \"\\<sim> x \\<squnion> x = \\<one>\"\n    by (simp only: disj_commute)\nqed\n\nlemma compl_eq_compl_iff [simp]: \"\\<sim> x = \\<sim> y \\<longleftrightarrow> x = y\"\n  by (rule inj_eq [OF inj_on_inverseI]) (rule double_compl)\n\n\nsubsection \\<open>Conjunction\\<close>\n\nlemma conj_absorb [simp]: \"x \\<sqinter> x = x\"\nproof -\n  have \"x \\<sqinter> x = (x \\<sqinter> x) \\<squnion> \\<zero>\"\n    using disj_zero_right by simp\n  also have \"... = (x \\<sqinter> x) \\<squnion> (x \\<sqinter> \\<sim> x)\"\n    using conj_cancel_right by simp\n  also have \"... = x \\<sqinter> (x \\<squnion> \\<sim> x)\"\n    using conj_disj_distrib by (simp only:)\n  also have \"... = x \\<sqinter> \\<one>\"\n    using disj_cancel_right by simp\n  also have \"... = x\"\n    using conj_one_right by simp\n  finally show ?thesis .\nqed\n\nlemma conj_zero_right [simp]: \"x \\<sqinter> \\<zero> = \\<zero>\"\nproof -\n  have \"x \\<sqinter> \\<zero> = x \\<sqinter> (x \\<sqinter> \\<sim> x)\"\n    using conj_cancel_right by simp\n  also have \"... = (x \\<sqinter> x) \\<sqinter> \\<sim> x\"\n    using conj_assoc by (simp only:)\n  also have \"... = x \\<sqinter> \\<sim> x\"\n    using conj_absorb by simp\n  also have \"... = \\<zero>\"\n    using conj_cancel_right by simp\n  finally show ?thesis .\nqed\n\nlemma compl_one [simp]: \"\\<sim> \\<one> = \\<zero>\"\n  by (rule compl_unique [OF conj_zero_right disj_zero_right])\n\nlemma conj_zero_left [simp]: \"\\<zero> \\<sqinter> x = \\<zero>\"\n  by (subst conj_commute) (rule conj_zero_right)\n\nlemma conj_one_left [simp]: \"\\<one> \\<sqinter> x = x\"\n  by (subst conj_commute) (rule conj_one_right)\n\nlemma conj_cancel_left [simp]: \"\\<sim> x \\<sqinter> x = \\<zero>\"\n  by (subst conj_commute) (rule conj_cancel_right)\n\nlemma conj_left_absorb [simp]: \"x \\<sqinter> (x \\<sqinter> y) = x \\<sqinter> y\"\n  by (simp only: conj_assoc [symmetric] conj_absorb)\n\nlemma conj_disj_distrib2: \"(y \\<squnion> z) \\<sqinter> x = (y \\<sqinter> x) \\<squnion> (z \\<sqinter> x)\"\n  by (simp only: conj_commute conj_disj_distrib)\n\nlemmas conj_disj_distribs = conj_disj_distrib conj_disj_distrib2\n\n\nsubsection \\<open>Disjunction\\<close>\n\nlemma disj_absorb [simp]: \"x \\<squnion> x = x\"\n  by (rule boolean.conj_absorb [OF dual])\n\nlemma disj_one_right [simp]: \"x \\<squnion> \\<one> = \\<one>\"\n  by (rule boolean.conj_zero_right [OF dual])\n\nlemma compl_zero [simp]: \"\\<sim> \\<zero> = \\<one>\"\n  by (rule boolean.compl_one [OF dual])\n\nlemma disj_zero_left [simp]: \"\\<zero> \\<squnion> x = x\"\n  by (rule boolean.conj_one_left [OF dual])\n\nlemma disj_one_left [simp]: \"\\<one> \\<squnion> x = \\<one>\"\n  by (rule boolean.conj_zero_left [OF dual])\n\nlemma disj_cancel_left [simp]: \"\\<sim> x \\<squnion> x = \\<one>\"\n  by (rule boolean.conj_cancel_left [OF dual])\n\nlemma disj_left_absorb [simp]: \"x \\<squnion> (x \\<squnion> y) = x \\<squnion> y\"\n  by (rule boolean.conj_left_absorb [OF dual])\n\nlemma disj_conj_distrib2: \"(y \\<sqinter> z) \\<squnion> x = (y \\<squnion> x) \\<sqinter> (z \\<squnion> x)\"\n  by (rule boolean.conj_disj_distrib2 [OF dual])\n\nlemmas disj_conj_distribs = disj_conj_distrib disj_conj_distrib2\n\n\nsubsection \\<open>De Morgan's Laws\\<close>\n\nlemma de_Morgan_conj [simp]: \"\\<sim> (x \\<sqinter> y) = \\<sim> x \\<squnion> \\<sim> y\"\nproof (rule compl_unique)\n  have \"(x \\<sqinter> y) \\<sqinter> (\\<sim> x \\<squnion> \\<sim> y) = ((x \\<sqinter> y) \\<sqinter> \\<sim> x) \\<squnion> ((x \\<sqinter> y) \\<sqinter> \\<sim> y)\"\n    by (rule conj_disj_distrib)\n  also have \"... = (y \\<sqinter> (x \\<sqinter> \\<sim> x)) \\<squnion> (x \\<sqinter> (y \\<sqinter> \\<sim> y))\"\n    by (simp only: conj_ac)\n  finally show \"(x \\<sqinter> y) \\<sqinter> (\\<sim> x \\<squnion> \\<sim> y) = \\<zero>\"\n    by (simp only: conj_cancel_right conj_zero_right disj_zero_right)\nnext\n  have \"(x \\<sqinter> y) \\<squnion> (\\<sim> x \\<squnion> \\<sim> y) = (x \\<squnion> (\\<sim> x \\<squnion> \\<sim> y)) \\<sqinter> (y \\<squnion> (\\<sim> x \\<squnion> \\<sim> y))\"\n    by (rule disj_conj_distrib2)\n  also have \"... = (\\<sim> y \\<squnion> (x \\<squnion> \\<sim> x)) \\<sqinter> (\\<sim> x \\<squnion> (y \\<squnion> \\<sim> y))\"\n    by (simp only: disj_ac)\n  finally show \"(x \\<sqinter> y) \\<squnion> (\\<sim> x \\<squnion> \\<sim> y) = \\<one>\"\n    by (simp only: disj_cancel_right disj_one_right conj_one_right)\nqed\n\nlemma de_Morgan_disj [simp]: \"\\<sim> (x \\<squnion> y) = \\<sim> x \\<sqinter> \\<sim> y\"\n  by (rule boolean.de_Morgan_conj [OF dual])\n\nend\n\n\nsubsection \\<open>Symmetric Difference\\<close>\n\nlocale boolean_xor = boolean +\n  fixes xor :: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a\"  (infixr \"\\<oplus>\" 65)\n  assumes xor_def: \"x \\<oplus> y = (x \\<sqinter> \\<sim> y) \\<squnion> (\\<sim> x \\<sqinter> y)\"\nbegin\n\nsublocale xor: abel_semigroup xor\nproof\n  fix x y z :: 'a\n  let ?t = \"(x \\<sqinter> y \\<sqinter> z) \\<squnion> (x \\<sqinter> \\<sim> y \\<sqinter> \\<sim> z) \\<squnion>\n            (\\<sim> x \\<sqinter> y \\<sqinter> \\<sim> z) \\<squnion> (\\<sim> x \\<sqinter> \\<sim> y \\<sqinter> z)\"\n  have \"?t \\<squnion> (z \\<sqinter> x \\<sqinter> \\<sim> x) \\<squnion> (z \\<sqinter> y \\<sqinter> \\<sim> y) =\n        ?t \\<squnion> (x \\<sqinter> y \\<sqinter> \\<sim> y) \\<squnion> (x \\<sqinter> z \\<sqinter> \\<sim> z)\"\n    by (simp only: conj_cancel_right conj_zero_right)\n  then show \"(x \\<oplus> y) \\<oplus> z = x \\<oplus> (y \\<oplus> z)\"\n    apply (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\n    apply (simp only: conj_disj_distribs conj_ac disj_ac)\n    done\n  show \"x \\<oplus> y = y \\<oplus> x\"\n    by (simp only: xor_def conj_commute disj_commute)\nqed\n\nlemmas xor_assoc = xor.assoc\nlemmas xor_commute = xor.commute\nlemmas xor_left_commute = xor.left_commute\n\nlemmas xor_ac = xor.assoc xor.commute xor.left_commute\n\nlemma xor_def2: \"x \\<oplus> y = (x \\<squnion> y) \\<sqinter> (\\<sim> x \\<squnion> \\<sim> y)\"\n  by (simp only: xor_def conj_disj_distribs disj_ac conj_ac conj_cancel_right disj_zero_left)\n\nlemma xor_zero_right [simp]: \"x \\<oplus> \\<zero> = x\"\n  by (simp only: xor_def compl_zero conj_one_right conj_zero_right disj_zero_right)\n\nlemma xor_zero_left [simp]: \"\\<zero> \\<oplus> x = x\"\n  by (subst xor_commute) (rule xor_zero_right)\n\nlemma xor_one_right [simp]: \"x \\<oplus> \\<one> = \\<sim> x\"\n  by (simp only: xor_def compl_one conj_zero_right conj_one_right disj_zero_left)\n\nlemma xor_one_left [simp]: \"\\<one> \\<oplus> x = \\<sim> x\"\n  by (subst xor_commute) (rule xor_one_right)\n\nlemma xor_self [simp]: \"x \\<oplus> x = \\<zero>\"\n  by (simp only: xor_def conj_cancel_right conj_cancel_left disj_zero_right)\n\nlemma xor_left_self [simp]: \"x \\<oplus> (x \\<oplus> y) = y\"\n  by (simp only: xor_assoc [symmetric] xor_self xor_zero_left)\n\nlemma xor_compl_left [simp]: \"\\<sim> x \\<oplus> y = \\<sim> (x \\<oplus> y)\"\n  apply (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\n  apply (simp only: conj_disj_distribs)\n  apply (simp only: conj_cancel_right conj_cancel_left)\n  apply (simp only: disj_zero_left disj_zero_right)\n  apply (simp only: disj_ac conj_ac)\n  done\n\nlemma xor_compl_right [simp]: \"x \\<oplus> \\<sim> y = \\<sim> (x \\<oplus> y)\"\n  apply (simp only: xor_def de_Morgan_disj de_Morgan_conj double_compl)\n  apply (simp only: conj_disj_distribs)\n  apply (simp only: conj_cancel_right conj_cancel_left)\n  apply (simp only: disj_zero_left disj_zero_right)\n  apply (simp only: disj_ac conj_ac)\n  done\n\nlemma xor_cancel_right: \"x \\<oplus> \\<sim> x = \\<one>\"\n  by (simp only: xor_compl_right xor_self compl_zero)\n\nlemma xor_cancel_left: \"\\<sim> x \\<oplus> x = \\<one>\"\n  by (simp only: xor_compl_left xor_self compl_zero)\n\nlemma conj_xor_distrib: \"x \\<sqinter> (y \\<oplus> z) = (x \\<sqinter> y) \\<oplus> (x \\<sqinter> z)\"\nproof -\n  have *: \"(x \\<sqinter> y \\<sqinter> \\<sim> z) \\<squnion> (x \\<sqinter> \\<sim> y \\<sqinter> z) =\n        (y \\<sqinter> x \\<sqinter> \\<sim> x) \\<squnion> (z \\<sqinter> x \\<sqinter> \\<sim> x) \\<squnion> (x \\<sqinter> y \\<sqinter> \\<sim> z) \\<squnion> (x \\<sqinter> \\<sim> y \\<sqinter> z)\"\n    by (simp only: conj_cancel_right conj_zero_right disj_zero_left)\n  then show \"x \\<sqinter> (y \\<oplus> z) = (x \\<sqinter> y) \\<oplus> (x \\<sqinter> z)\"\n    by (simp (no_asm_use) only:\n        xor_def de_Morgan_disj de_Morgan_conj double_compl\n        conj_disj_distribs conj_ac disj_ac)\nqed\n\nlemma conj_xor_distrib2: \"(y \\<oplus> z) \\<sqinter> x = (y \\<sqinter> x) \\<oplus> (z \\<sqinter> x)\"\nproof -\n  have \"x \\<sqinter> (y \\<oplus> z) = (x \\<sqinter> y) \\<oplus> (x \\<sqinter> z)\"\n    by (rule conj_xor_distrib)\n  then show \"(y \\<oplus> z) \\<sqinter> x = (y \\<sqinter> x) \\<oplus> (z \\<sqinter> x)\"\n    by (simp only: conj_commute)\nqed\n\nlemmas conj_xor_distribs = conj_xor_distrib conj_xor_distrib2\n\nend\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Library/Boolean_Algebra.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894548800271, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.7513850937944243}}
{"text": "\ntheory Lists1_8\nimports Main\nbegin\n\nprimrec ListSum :: \"nat list \\<Rightarrow> nat\"\nwhere\n  \"ListSum [] = 0\"\n| \"ListSum (x#xs) = x + ListSum xs\"\n\nvalue \"ListSum []\"\nvalue \"ListSum [1]\"\nvalue \"ListSum [1,1,2]\"\n\nvalue \"[0..<4]\"\nvalue \"ListSum [0..<Suc 0]\"\n\nlemma listsum_append: \"ListSum (xs @ ys) = ListSum xs + ListSum ys\"\n  apply (induct xs)\n  apply simp\n  apply auto\ndone\n\ntheorem \"2 * ListSum [0..<n+1] = n * (n + 1)\"\n  apply (induct n)\n  apply (simp add:listsum_append)+\ndone\n\nvalue \"replicate 10 (1::nat)\"\n\ntheorem \"ListSum (replicate n a) = n * a\"\n  apply (induct n)\n  apply simp\n  apply simp\ndone\n\nfun ListSumTAux :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\"\nwhere\n  \"ListSumTAux [] n = n\"\n| \"ListSumTAux (x#xs) n = ListSumTAux xs (n + x)\"\n\nvalue \"ListSumTAux [] 0\"\nvalue \"ListSumTAux [1] 0\"\nvalue \"ListSumTAux [1,2] 0\"\n\nfun ListSumT :: \"nat list \\<Rightarrow> nat\"\nwhere\n  \"ListSumT xs = ListSumTAux xs 0\"\n\nvalue \"ListSumT []\"\nvalue \"ListSumT [1]\"\nvalue \"ListSumT [1,2]\"\n\nlemma list_sumtaux_add: \"\\<forall> a b. ListSumTAux xs (a + b) = a + ListSumTAux xs b\"\n  apply (induct xs)\n  apply auto\ndone\n\n(* Proving the lemma with reversed sides does not help in proving\n   the main lemma proved later *)\nlemma list_sumtaux_val: \"a + ListSumTAux xs 0 = ListSumTAux xs a\"\n  apply (induct xs)\n  (* using [[simp_trace=true]] *)\n  apply simp\n  apply (simp add:list_sumtaux_add)\ndone\n\ntheorem \"ListSum xs = ListSumT xs\"\n  apply (induct xs)\n  apply simp\n  (* using [[simp_trace = true]] *)\n  apply (simp add:list_sumtaux_val)\ndone\n\n\nend\n\n", "meta": {"author": "jineshkj", "repo": "cis700_assured_systems", "sha": "9fb270e519a3644f9713bee8cef082aefbc8228f", "save_path": "github-repos/isabelle/jineshkj-cis700_assured_systems", "path": "github-repos/isabelle/jineshkj-cis700_assured_systems/cis700_assured_systems-9fb270e519a3644f9713bee8cef082aefbc8228f/Isabelle_HOL_Exercies/Lists1_8.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8438951064805861, "lm_q1q2_score": 0.7513149481215435}}
{"text": "theory Algebras_of_Cells\nimports Padic_Cells\nbegin\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsection\\<open>Algebras Generated by Cells with a Common Center\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Basic Combinatorial Fact about Intervals\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\ntext\\<open>An important combinatorial property of $p$-adic cells is that the intersection of two $p$-adic \ncells with the same center is again a $p$-adic cell, and that sets which can be decomposed into \n$p$-adic cells form a boolean algebra. In order to reason about boolean combinations of cells, we \nneed to be able to understand boolean combinations of intervals over the value group. This theory \nestablishes the basic properties of those boolean combinations.\\<close>\ncontext padic_fields\nbegin\n\nlemma closed_interval_memE:\n  assumes \"x \\<in> closed_interval \\<alpha> \\<beta>\"\n  shows \"\\<alpha> \\<le> x\"\n        \"x \\<le> \\<beta>\"\n  unfolding closed_interval_def\n  using assms closed_interval_def apply blast\n  using assms closed_interval_def by blast\n\nlemma closed_interval_memI:\n  assumes \"\\<alpha> \\<le> x\"\n  assumes \"x \\<le> \\<beta>\"\n  shows \"x \\<in> closed_interval \\<alpha> \\<beta>\"\n  using assms unfolding closed_interval_def  by blast \n\nlemma left_closed_interval_memE:\n  assumes \"x \\<in> left_closed_interval \\<alpha> \\<beta>\"\n  shows \"\\<alpha> \\<le> x\"\n        \"x < \\<beta>\"\n  using assms left_closed_interval_def apply blast\n  using assms left_closed_interval_def by blast\n\nlemma left_closed_interval_memI:\n  assumes \"\\<alpha> \\<le> x\"\n  assumes \"x < \\<beta>\"\n  shows \"x \\<in> left_closed_interval \\<alpha> \\<beta>\"\n  using assms unfolding left_closed_interval_def  by blast \n\nlemma closed_ray_memE:\n  assumes \"x \\<in> closed_ray \\<alpha> \\<beta>\"\n  shows  \"x \\<le> \\<beta>\"\n  using assms closed_ray_def[of \\<alpha> \\<beta>] by blast\n\nlemma closed_ray_memI:\n  assumes \"x \\<le> \\<beta>\"\n  shows \"x \\<in> closed_ray \\<alpha> \\<beta>\"\n  using assms unfolding closed_ray_def  by blast \n\nlemma open_ray_memE:\n  assumes \"x \\<in> open_ray \\<alpha> \\<beta>\"\n  shows  \"x < \\<beta>\"\n  using assms open_ray_def[of \\<alpha> \\<beta>] by blast\n\nlemma open_ray_memI:\n  assumes \"x < \\<beta>\"\n  shows \"x \\<in> open_ray \\<alpha> \\<beta>\"\n  using assms unfolding open_ray_def by blast \n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsubsection\\<open>Intersecting Convex Sets\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\ntext\\<open>This section is a library of formulas for intersections of intervals. \\<close>\n\nlemma closed_interval_intersection:\n\"closed_interval (\\<alpha>::eint) \\<beta> \\<inter> closed_interval \\<gamma> \\<delta> = closed_interval (max \\<alpha> \\<gamma>) (min \\<beta> \\<delta>)\"\n  apply(rule equalityI')\n  unfolding mem_Collect_eq \n   apply (simp add: max_def min_def closed_interval_def )\nproof- fix x assume A: \"x \\<in> closed_interval (max \\<alpha> \\<gamma>) (min \\<beta> \\<delta>)\"\n  have B: \"(max \\<alpha> \\<gamma>) \\<le> x\"\n    using A closed_interval_memE(1) by blast\n  have C: \"x \\<le> (min \\<beta> \\<delta>)\"\n    using A closed_interval_memE(2) by blast \n  have 0: \"\\<alpha> \\<le> x\"\n    using B  max.bounded_iff by blast\n  have 1: \"\\<gamma> \\<le> x\"\n    using B  by simp\n  have 2: \"x \\<le> \\<beta>\"\n    using C by simp\n  have 3: \"x \\<le> \\<delta>\"\n    using C by simp\n  show \"x \\<in> I[\\<alpha> \\<beta>] \\<inter> I[\\<gamma> \\<delta>]\"\n    using \"0\" \"1\" \"2\" \"3\" closed_interval_memI by blast\nqed\n\nlemma closed_interval_as_left_closed_interval:\n  assumes \"\\<beta> \\<noteq> \\<infinity>\"\n  shows \"closed_interval (\\<alpha>::eint) \\<beta>  = left_closed_interval \\<alpha>  (\\<beta> + 1)\"\n  apply(rule equalityI')\n  apply(rule left_closed_interval_memI)  \n  using closed_interval_memE(1) apply blast\nproof-\n  show \"\\<And>x. x \\<in> I[\\<alpha> \\<beta>] \\<Longrightarrow> x < \\<beta> + 1\"\n  proof- fix x assume A: \"x \\<in> I[\\<alpha> \\<beta>]\"\n    then have \"x \\<le> \\<beta>\"\n      using closed_interval_memE(2) by blast\n    then have \"x < \\<beta> + 1\"\n      using assms \n      by (metis add.commute eSuc_eint eint.exhaust eint_ord_code(2) less_add_one order_trans_rules(21) top_eint_def)\n    then show \"x < \\<beta> + 1 \"\n      by blast\n  qed\n  show \"\\<And>x. x \\<in> left_closed_interval \\<alpha> (\\<beta> + 1) \\<Longrightarrow> x \\<in> I[\\<alpha> \\<beta>]\"\n    apply(rule closed_interval_memI)\n    using left_closed_interval_memE(1) apply blast\n    using eSuc_ile_mono ileI1 left_closed_interval_memE(2) by blast\nqed\n\nlemma closed_interval_left_closed_interval_intersection:\n\"closed_interval (\\<alpha>::eint) \\<beta> \\<inter> left_closed_interval \\<gamma> \\<delta> = left_closed_interval (max \\<alpha> \\<gamma>) (min (\\<beta>+1) \\<delta>)\"   \n  apply(rule equalityI')\n  apply(rule left_closed_interval_memI)\n  using closed_interval_memE(1) left_closed_interval_memE(1) max.bounded_iff apply blast\nproof-\n  show \" \\<And>x. x \\<in> I[\\<alpha> \\<beta>] \\<inter> left_closed_interval \\<gamma> \\<delta> \\<Longrightarrow> x < min (\\<beta> + 1) \\<delta>\"\n    apply(cases \"\\<beta> \\<noteq> \\<infinity>\")\n    using closed_interval_as_left_closed_interval[of \\<beta> \\<alpha>]\n          left_closed_interval_memE \n    apply (metis mem_simps(4) min_less_iff_conj)\n     by (metis eSuc_infinity left_closed_interval_memE(2) mem_simps(4) min_eint_simps(3))\n  show \"\\<And>x. x \\<in> left_closed_interval (max \\<alpha> \\<gamma>) (min (\\<beta> + 1) \\<delta>) \\<Longrightarrow> x \\<in> I[\\<alpha> \\<beta>] \\<inter> left_closed_interval \\<gamma> \\<delta>\"\n     apply(rule IntI)\n      apply(rule closed_interval_memI)\n     using left_closed_interval_memE(1) max.bounded_iff apply blast\n     using left_closed_interval_memE[of \"(max \\<alpha> \\<gamma>)\" \"(min (\\<beta> + 1) \\<delta>)\"]\n      apply (meson ileI1 left_closed_interval_memE(2) min_le_iff_disj not_le)\n     by (meson left_closed_interval_memE(1) left_closed_interval_memE(2) left_closed_interval_memI max.bounded_iff min_less_iff_conj)\nqed\n\nlemma closed_interval_closed_ray_intersection:\n\"closed_interval (\\<alpha>::eint) \\<beta> \\<inter> closed_ray \\<gamma> \\<delta> = closed_interval \\<alpha> (min \\<beta> \\<delta>)\"   \n  apply(rule equalityI')\n  apply(rule closed_interval_memI) \n  using closed_interval_memE(1) apply blast\n  apply (meson IntD1 IntD2 closed_interval_memE(2) closed_ray_memE min.bounded_iff)\n  apply(rule IntI)\n  apply(rule closed_interval_memI) \n  using closed_interval_memE(1) apply blast\n  using closed_interval_memE(2) min.bounded_iff apply blast\n  by (meson closed_interval_memE(2) closed_ray_memI min.boundedE)\n\nlemma closed_interval_open_ray_intersection:\n\"closed_interval (\\<alpha>::eint) \\<beta> \\<inter> open_ray \\<gamma> \\<delta> = left_closed_interval \\<alpha> (min (\\<beta>+1) \\<delta>)\"   \n  apply(rule equalityI')\n  apply(rule left_closed_interval_memI)\n  using closed_interval_memE(1) left_closed_interval_memE(1) max.bounded_iff apply blast\nproof-\n  show \"\\<And>x. x \\<in> I[\\<alpha> \\<beta>] \\<inter> open_ray \\<gamma> \\<delta> \\<Longrightarrow> x < min (\\<beta> + 1) \\<delta>\"\n    apply(cases \"\\<beta> \\<noteq> \\<infinity>\")\n  proof-\n    show \" \\<And>x. x \\<in> I[\\<alpha> \\<beta>] \\<inter> open_ray \\<gamma> \\<delta> \\<Longrightarrow> \\<beta> \\<noteq> \\<infinity> \\<Longrightarrow> x < min (\\<beta> + 1) \\<delta>\" \n    proof- fix x assume A: \" x \\<in> I[\\<alpha> \\<beta>] \\<inter> open_ray \\<gamma> \\<delta>\" then show \"x < min (\\<beta> + 1) \\<delta>\" \n    using closed_interval_as_left_closed_interval[of \\<beta> \\<alpha>]\n          left_closed_interval_memE[of x \\<alpha> \"\\<beta> + 1\"] open_ray_memE[of x \\<gamma> \\<delta>] IntE[of x]\n    by (metis min_eint_simps(2) min_less_iff_conj plus_eint_simps(2))\n    qed\n    show \"\\<And>x. x \\<in> I[\\<alpha> \\<beta>] \\<inter> open_ray \\<gamma> \\<delta> \\<Longrightarrow> \\<not> \\<beta> \\<noteq> \\<infinity> \\<Longrightarrow> x < min (\\<beta> + 1) \\<delta>\"\n      by (metis mem_simps(4) min_eint_simps(3) open_ray_memE plus_eint_simps(2))\n  qed\n  show \"\\<And>x. x \\<in> left_closed_interval \\<alpha> (min (\\<beta> + 1) \\<delta>) \\<Longrightarrow> x \\<in> I[\\<alpha> \\<beta>] \\<inter> open_ray \\<gamma> \\<delta>\"\n    apply(rule IntI) apply(rule closed_interval_memI) \n    using left_closed_interval_memE(1) apply blast\n    using eSuc_ile_mono ileI1 left_closed_interval_memE(2) min.bounded_iff apply blast\n    by (meson left_closed_interval_memE(2) min_less_iff_conj open_rayE)\nqed  \n\nlemma left_closed_interval_intersection:\n\"left_closed_interval (\\<alpha>::eint) \\<beta> \\<inter> left_closed_interval \\<gamma> \\<delta> = left_closed_interval (max \\<alpha> \\<gamma>) (min \\<beta> \\<delta>)\"   \n  apply(rule equalityI')\n  apply(rule left_closed_interval_memI) \n  apply (meson left_closed_interval_memE(1) max.bounded_iff mem_simps(4))\n  apply (meson IntD1 IntD2 left_closed_interval_memE(2) min_less_iff_conj)\n  apply(rule IntI) \n  apply (meson left_closed_interval_memE(1) left_closed_interval_memE(2) left_closed_interval_memI max.bounded_iff min_less_iff_conj)\n  by (meson left_closed_interval_memE(1) left_closed_interval_memE(2) left_closed_interval_memI max.bounded_iff min_less_iff_conj)\n  \nlemma left_closed_interval_closed_ray_intersection:\n\"left_closed_interval (\\<alpha>::eint) \\<beta> \\<inter> closed_ray \\<gamma> \\<delta> = left_closed_interval \\<alpha> (min \\<beta> (\\<delta>+1))\"   \n  apply(rule equalityI')\n  apply (metis closed_interval_closed_ray_intersection closed_interval_open_ray_intersection mem_simps(4) min.commute min_eint_simps(3) plus_eint_simps(2))\n  by (metis closed_interval_closed_ray_intersection closed_interval_left_closed_interval_intersection closed_interval_open_ray_intersection mem_simps(4) min.commute min_eint_simps(3))\n\nlemma left_closed_interval_open_ray_intersection:\n\"left_closed_interval (\\<alpha>::eint) \\<beta> \\<inter> open_ray \\<gamma> \\<delta> = left_closed_interval \\<alpha> (min \\<beta> \\<delta>)\"   \n  apply(rule equalityI')\n  apply (meson left_closed_interval_memE(1) left_closed_interval_memE(2) left_closed_interval_memI mem_simps(4) min_less_iff_conj open_ray_memE)\n  by (meson left_closed_interval_memE(1) left_closed_interval_memE(2) left_closed_interval_memI mem_simps(4) min_less_iff_conj open_rayE)\n\nlemma closed_ray_intersection:\n\"closed_ray (\\<alpha>::eint) (\\<beta>::eint) \\<inter> closed_ray (\\<gamma>::eint) \\<delta> = closed_ray \\<alpha> (min \\<beta> \\<delta>)\"  \n  apply(rule equalityI')\n  apply(rule closed_ray_memI)  \n  apply (metis IntD1 IntD2 closed_ray_memE min_def)\n  apply(rule IntI) \n   apply(rule closed_ray_memI)  \nproof-\n  show \"\\<And>x::eint . x \\<in> closed_ray \\<alpha> (min \\<beta> \\<delta>) \\<Longrightarrow> x \\<le> \\<beta>\" proof- fix x assume A: \"x \\<in> closed_ray \\<alpha> (min \\<beta> \\<delta>)\"\n    then show \"x \\<le> \\<beta>\"\n      using closed_ray_memE[of x \\<alpha> \"min \\<beta> \\<delta>\"] min.bounded_iff[of \"x::eint\" \\<beta> \\<delta>] by blast \n  qed\n  show \"\\<And>x. x \\<in> closed_ray \\<alpha> (min \\<beta> \\<delta>) \\<Longrightarrow> x \\<in> closed_ray \\<gamma> \\<delta>\"\n  proof- fix x assume A: \"x \\<in> closed_ray \\<alpha> (min \\<beta> \\<delta>)\"\n    then show \"x \\<in> closed_ray \\<gamma> \\<delta>\"\n    using closed_ray_memE \n    by (metis closed_ray_memI min.bounded_iff)\n  qed\nqed\n\nlemma closed_ray_open_ray_intersection:\n\"closed_ray (\\<alpha>::eint) \\<beta> \\<inter> open_ray \\<gamma> \\<delta> = open_ray \\<alpha> (min (\\<beta>+1) \\<delta> )\"\n  apply(rule equalityI')\n   apply(rule open_ray_memI)  \nproof-\n  show \"\\<And>x. x \\<in> closed_ray \\<alpha> \\<beta> \\<inter> open_ray \\<gamma> \\<delta> \\<Longrightarrow> x < min (\\<beta> + 1) \\<delta>\"\n  proof- fix x assume A: \"x \\<in> closed_ray \\<alpha> \\<beta> \\<inter> open_ray \\<gamma> \\<delta>\"\n    have 0: \"x \\<le> \\<beta>\"\n      by (meson A IntD1 closed_ray_memE)\n    have 1: \"x < \\<delta>\"\n      by (meson A mem_simps(4) open_ray_memE)\n    show \"x < min (\\<beta> + 1) \\<delta>\"\n    proof(cases \"\\<beta> \\<noteq> \\<infinity>\")\n      case True\n      then show ?thesis \n        by (metis \"0\" \"1\" closed_interval_as_left_closed_interval closed_interval_memI left_closed_interval_memE(2) min_less_iff_conj order_refl)\n    next\n      case False\n      then show ?thesis \n        by (simp add: \"1\")\n    qed\n  qed\n  show \"\\<And>x. x \\<in> open_ray \\<alpha> (min (\\<beta> + 1) \\<delta>) \\<Longrightarrow> x \\<in> closed_ray \\<alpha> \\<beta> \\<inter> open_ray \\<gamma> \\<delta>\"\n    apply(rule IntI)\n     apply (meson closed_ray_memI eSuc_ile_mono ileI1 min_less_iff_conj open_ray_memE)\n    by (meson min.strict_boundedE open_ray_memE open_ray_memI)\nqed\n\nlemma open_ray_intersection:\n\"open_ray (\\<alpha>::eint) (\\<beta>::eint) \\<inter> open_ray (\\<gamma>::eint) \\<delta> = open_ray \\<alpha> (min \\<beta> \\<delta>)\"  \n  apply(rule equalityI')\n  apply (meson IntD1 IntD2 min_less_iff_conj open_rayE open_ray_memE)\n  by (meson mem_simps(4) min_less_iff_conj open_rayE open_ray_memE)\n\nlemma notin_closed:\n\"(\\<not> ((c::eint) \\<le> x \\<and> x \\<le> d)) = (x < c \\<or> d < x)\" \n  by auto\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsubsection\\<open>Set Differences of Convex Sets\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\nlemma minus_left_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  shows \"A -  left_closed_interval c d = (A \\<inter> open_ray c c) \\<union> (A \\<inter> closed_interval d \\<infinity>)\"\n  apply(intro equalityI', \n        unfold Int_iff Un_iff Diff_iff open_ray_def  closed_interval_def mem_Collect_eq \n          left_closed_interval_def)\n  by auto \n\nlemma minus_closed_ray:\n  assumes \"(d::eint) \\<noteq> \\<infinity>\"\n  shows \"A - closed_ray c d = (A \\<inter> closed_interval (d+1) \\<infinity>)\"\nproof(rule equalityI')  \n  obtain m where m_def: \"d = eint m\"\n    using assms by blast \n  have 0: \"d+1 = eint (m+1)\"\n    using eSuc_eint_iff m_def by blast\n  show \"\\<And>x. x \\<in> A - closed_ray c d \\<Longrightarrow> x \\<in> A \\<inter> I[d + 1 \\<infinity>]\"\n    unfolding closed_ray_def closed_interval_def unfolding m_def\n    apply(rule IntI) apply blast\n  proof- fix x assume A: \"x \\<in> A - {a. a \\<le> eint m}\" \n    show \"x \\<in> {a. eint m + 1 \\<le> a \\<and> a \\<le> \\<infinity>}\" using A apply (rule DiffE)\n    unfolding mem_Collect_eq \n    by (metis \"0\" add.commute eSuc_eint eSuc_mono eint_ord_simps(4) eint_ord_simps(6) iless_Suc_eq m_def notin_closed plus_eint_def)\n  qed\n  show \"\\<And>x. x \\<in> A \\<inter> I[d + 1 \\<infinity>] \\<Longrightarrow> x \\<in> A - closed_ray c d\"\n    unfolding closed_ray_def closed_interval_def 0 apply(rule DiffI) apply blast \n  proof fix x assume A: \"x \\<in> A \\<inter> {a. eint (m + 1) \\<le> a \\<and> a \\<le> \\<infinity>}\" \"x \\<in> {a. a \\<le> d} \"\n    then have 0: \"x \\<in> {a. eint (m + 1) \\<le> a \\<and> a \\<le> \\<infinity>}\"\n      by blast \n    show False using 0  A(2) unfolding mem_Collect_eq m_def   \n      by (metis eSuc_eint eint_ile iless_Suc_eq leD)\n  qed\nqed\n\nlemma minus_open_ray:\n  assumes \"(d::eint) \\<noteq> \\<infinity>\"\n  shows \"A - open_ray c d = (A \\<inter> closed_interval d \\<infinity>)\"\nproof(rule equalityI')  \n  obtain m where m_def: \"d = eint m\"\n    using assms by blast \n  show \" \\<And>x. x \\<in> A - open_ray c d \\<Longrightarrow> x \\<in> A \\<inter> I[d \\<infinity>]\"\n    unfolding closed_ray_def closed_interval_def unfolding m_def\n    apply(rule IntI) apply blast \n    unfolding open_ray_def mem_Collect_eq \n    by (meson Diff_iff eint_ord_simps(6) mem_Collect_eq notin_closed)\n  show \"\\<And>x. x \\<in> A \\<inter> I[d \\<infinity>] \\<Longrightarrow> x \\<in> A - open_ray c d\"\n    unfolding open_ray_def closed_interval_def apply(rule DiffI) apply blast \n    by (metis Int_iff mem_Collect_eq notin_closed)\nqed\n\nlemma minus_left_closed_interval':\n  assumes \"d = \\<infinity>\"\n  shows \"A -  left_closed_interval c d = (A \\<inter> open_ray c c) \\<union> (A \\<inter> closed_interval \\<infinity> \\<infinity>)\"\n  by(intro equalityI', \n        unfold open_ray_def  closed_interval_def Diff_iff Int_iff Un_iff assms\n              left_closed_interval_def mem_Collect_eq, auto )\n\nlemma minus_closed_ray':\n  assumes \"(d::eint) = \\<infinity>\"\n  shows \"A - closed_ray c d = {}\"\n  unfolding closed_ray_def assms  \n  using eint_ord_simps(3) by blast\n\nlemma minus_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  shows \"A -  closed_interval c d = (A \\<inter> open_ray c c) \\<union> (A \\<inter> closed_interval (d+1) \\<infinity>)\"\nproof(rule equalityI')\n  obtain m where m_def: \"d = eint m\"\n    using assms by blast \n  have 0: \"d+1 = eint (m+1)\"\n    using eSuc_eint_iff m_def by blast\n  show \" \\<And>x. x \\<in> A - I[c d] \\<Longrightarrow> x \\<in> A \\<inter> open_ray c c \\<union> A \\<inter> I[d + 1 \\<infinity>]\"\n    unfolding open_ray_def  closed_interval_def 0 unfolding m_def\n    by (metis (no_types, lifting) DiffD2 Diff_iff Int_iff UnI1 UnI2 eSuc_eint_iff eint_ord_simps(3) eint_ord_simps(6) ileI1 m_def mem_Collect_eq notin_closed val_p_int_pow)\n  show \"\\<And>x. x \\<in> A \\<inter> open_ray c c \\<union> A \\<inter> I[d + 1 \\<infinity>] \\<Longrightarrow> x \\<in> A - I[c d] \"\n    apply(rule DiffI) apply blast \n  proof fix x::eint assume A: \"x \\<in> A \\<inter> open_ray (c::eint) c \\<union> A \\<inter> I[d + 1 \\<infinity>]\" \" x \\<in> I[c d]\"\n    show False\n      apply(cases \"x \\<in> A \\<inter> {a. a < c}\")\n      using A(2) unfolding open_ray_def  closed_interval_def 0 unfolding m_def mem_Collect_eq \n       apply (meson Int_iff mem_Collect_eq notin_closed)\n    proof-\n      assume \"x \\<notin> A \\<inter> {a. a < c}\"\n      then have 1: \"x \\<in> I[d + 1 \\<infinity>]\"\n      using A unfolding open_ray_def  closed_interval_def 0 unfolding m_def mem_Collect_eq\n      by blast \n      thus False \n       using A(2) unfolding open_ray_def  closed_interval_def 0 unfolding m_def mem_Collect_eq\n      by (metis \"0\" Int_iff add.commute assms dual_order.trans eSuc_eint eSuc_infinity eint.inject eint2_cases eint_iless eint_ord_Suc eint_ord_code(4) eint_ord_simps(3) eint_ord_simps(4) eint_ord_simps(5) eint_ord_simps(6) ex_val_less ile_eSuc infinity_ne_i1 int.lless_eq less_infinityE m_def mem_Collect_eq not_eint_eq notin_closed order.trans order_class.order.antisym sum_infinity_imp_summand_infinity top_eint_def zless_add1_eq)\n  qed\nqed\nqed\n\nlemma minus_closed_interval':\n  assumes \"d = \\<infinity>\"\n  shows \"A -  closed_interval c d = (A \\<inter> open_ray c c)\"\nproof(rule equalityI')\n  show \"\\<And>x. x \\<in> A - I[c d] \\<Longrightarrow> x \\<in> A \\<inter> open_ray c c\"\n    unfolding assms open_ray_def closed_interval_def \n    by (metis Diff_iff Int_iff eint_ord_code(3) inf_set_def mem_Collect_eq notin_closed)\n  show \"\\<And>x. x \\<in> A \\<inter> open_ray c c \\<Longrightarrow> x \\<in> A - I[c d] \"\n    unfolding assms open_ray_def closed_interval_def \n  by (metis DiffI IntD1 IntD2 mem_Collect_eq notin_closed)\nqed\n\nlemma closed_interval_minus_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min (b+1) c) \\<union> closed_interval (max a (d+1)) b\" \nproof(rule equalityI)\n  show \"(I::eint set) - J \\<subseteq> left_closed_interval a (min (b+1) c) \\<union> closed_interval (max a (d+1)) b\" \n  proof \n    fix x::eint assume A: \"x \\<in> I - J\" \n    show \"x \\<in> left_closed_interval a (min (b+1) c) \\<union> I[(max a (d+1)) b] \"\n    proof assume A': \" x \\<notin> I[(max a (d+1)) b]\"\n      show \" x \\<in> left_closed_interval a (min (b+1) c)\"\n        apply(rule left_closed_interval_memI)         \n        using A A'\n        unfolding assms closed_interval_def left_closed_interval_def mem_Collect_eq \n        using  Extended_Int.ileI1 \n         apply blast\n        using A apply(rule DiffE)\n                using A'\n        unfolding assms closed_interval_def left_closed_interval_def mem_Collect_eq  notin_closed\n        apply(cases \"x < b+1\")\n         using ileI1 leD apply auto[1]         \n        by (metis A' antisym closed_interval_as_left_closed_interval closed_interval_memI eSuc_inject eint_add_left_cancel eint_ord_code(3) iadd_Suc_right ile_eSuc left_closed_interval_memE(2) min.absorb1 min.assoc min.commute min.left_commute min.orderI min.strict_order_iff min_le_iff_disj neqE notin_closed)\n    qed\n  qed\n  obtain m where m_def: \"d = eint m\"\n    using assms(1) by blast\n  show \"left_closed_interval a (min (b + 1) c) \\<union> I[(max a (d+1)) b] \\<subseteq> I - J\"\n    apply(intro subsetI, \n          unfold left_closed_interval_def closed_interval_def mem_Collect_eq Un_iff Int_iff Diff_iff\n                  m_def assms, intro conjI)\n      apply auto[1]\n    using Extended_Int.eSuc_ile_mono Extended_Int.ileI1 min.bounded_iff apply blast \n    by (meson Extended_Int.iless_Suc_eq dual_order.eq_iff max.bounded_iff min_less_iff_conj \n              not_less order_trans_rules(22))\nqed\n\nlemma closed_interval_minus_closed_interval':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min (b+1) c)\" \n  using minus_closed_interval'[of d I c] unfolding assms closed_interval_open_ray_intersection by blast \n\nlemma closed_interval_minus_left_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min (b + 1) c) \\<union> I[(max a d) b]\"\nproof-\n  have \"(I::eint set) - J = (I \\<inter> open_ray c c) \\<union> (I \\<inter> closed_interval d \\<infinity>)\"\n    unfolding assms \n    by (simp add: assms(1) minus_left_closed_interval)\n  thus \"I - J = left_closed_interval a (min (b + 1) c) \\<union> I[(max a d) b]\"\n    unfolding assms closed_interval_open_ray_intersection[of a b c c] closed_interval_intersection[of a b d \\<infinity>]\n    by simp\nqed\n\nlemma closed_interval_minus_left_closed_interval':\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min (b + 1) c) \\<union> I[(max a d) b]\"\nproof(cases \"d = \\<infinity>\")\n  case True\n    have \"(I::eint set) - J = (I \\<inter> open_ray c c) \\<union> (I \\<inter> closed_interval \\<infinity> \\<infinity>)\"\n    unfolding assms \n    by (simp add: True assms(1) minus_left_closed_interval')\n  thus \"I - J = left_closed_interval a (min (b + 1) c) \\<union> I[(max a d) b]\"\n    unfolding assms closed_interval_open_ray_intersection[of a b c c] closed_interval_intersection[of a b d \\<infinity>]\n    by (simp add: True closed_interval_intersection)\nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) closed_interval_minus_left_closed_interval)\nqed\n\nlemma closed_interval_minus_closed_ray:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = closed_interval (max a (d + 1)) (min b \\<infinity>)\"\nproof-\n  obtain m where m_def: \"d = eint m\"\n    using assms(1) by blast\n  have 0: \"d+1 = eint (m+1)\"\n    using eSuc_eint_iff m_def by blast\n  have \"I - J = I \\<inter> closed_interval (d+1) \\<infinity>\"\n    apply(rule equalityI')\n    apply(rule IntI) \n    unfolding 0 assms closed_interval_def closed_ray_def unfolding m_def\n     apply blast\n    using assms minus_closed_ray[of d] unfolding mem_Collect_eq closed_interval_def closed_ray_def 0\n    using m_def apply blast\n    apply(rule DiffI) unfolding mem_Collect_eq \n     apply blast \n  proof fix x assume A: \"x \\<in> {aa. a \\<le> aa \\<and> aa \\<le> b} \\<inter> {a. eint (m + 1) \\<le> a \\<and> a \\<le> \\<infinity>}\" \"x \\<le> eint m\"\n    then have \"eint (m + 1) \\<le> x\" by blast  \n    thus False using A(2) 0 dual_order.antisym dual_order.trans eint.inject ile_eSuc\n      unfolding  m_def \n      by (simp add: Extended_Int.Suc_ile_eq)\n  qed\n  thus ?thesis unfolding assms closed_interval_intersection by blast   \nqed\n\nlemma closed_interval_minus_closed_ray':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = {}\"\n  by (simp add: assms(1) assms(3) minus_closed_ray')\n\nlemma closed_interval_minus_open_ray:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J = closed_interval (max a d) b\"\nproof- \n  obtain m where m_def: \"d = eint m\"\n    using assms(1) by blast\n  have \"I - J = I \\<inter> closed_interval d \\<infinity>\"\n    apply(intro equalityI', \n          unfold Un_iff Diff_iff Int_iff closed_interval_def mem_Collect_eq m_def assms open_ray_def, \n          intro conjI)\n    using assms by auto \n  thus ?thesis unfolding assms closed_interval_intersection\n    by simp\nqed\n\nlemma closed_interval_minus_open_ray':\n  assumes \"(I::eint set) = closed_interval a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J = closed_interval (max a d) b\"\nproof(cases \"d = \\<infinity>\")\n  case True\n  have 0: \"max a \\<infinity> = \\<infinity>\" \n    by simp\n  show ?thesis \n    apply(intro equalityI', \n          unfold Diff_iff closed_interval_def mem_Collect_eq True 0 assms open_ray_def)\n    by auto \nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) closed_interval_minus_open_ray)\nqed\n\nlemma left_closed_interval_minus_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J =  left_closed_interval a (min b c) \\<union> left_closed_interval (max a (d + 1)) b\"\nproof-\n  have 0: \"I - J = I \\<inter> open_ray c c \\<union> (I \\<inter> I[d + 1 \\<infinity>])\"\n    using minus_closed_interval[of d I c] assms by blast \n  have 1: \"I \\<inter> I[d + 1 \\<infinity>] =  left_closed_interval (max (d + 1) a) (min (\\<infinity> + 1) b)\"\n  unfolding assms left_closed_interval_open_ray_intersection[of a b c c]\n    using   closed_interval_left_closed_interval_intersection[of \"d+1\" \\<infinity> a b ] assms unfolding Int_commute[of \"I[d + 1 \\<infinity>] \"] \n    by blast\n  have 2: \" I \\<inter> open_ray c c =  left_closed_interval a (min b c)\"\n    using left_closed_interval_open_ray_intersection[of a b c c] unfolding assms by blast \n  show ?thesis    \n    using 0 unfolding 1 2  \n  by (simp add: max.commute)  \nqed\n\nlemma left_closed_interval_minus_closed_interval':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J =  left_closed_interval a (min b c)\"\n  using minus_closed_interval'[of d I c] unfolding assms left_closed_interval_open_ray_intersection by blast \n\nlemma left_closed_interval_minus_left_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min b c) \\<union> left_closed_interval a b \\<inter> I[d \\<infinity>]\"\nproof-\n  have 0: \"(I::eint set) - J = left_closed_interval a b \\<inter> open_ray c c \\<union> left_closed_interval a b \\<inter> I[d \\<infinity>]\"\n    using assms minus_left_closed_interval[of d I c] unfolding assms \n    by blast \n  show ?thesis \n    using 0  unfolding left_closed_interval_open_ray_intersection using closed_interval_left_closed_interval_intersection\n    unfolding Int_commute[of \"I[d \\<infinity>]\"]\n    by blast \nqed\n\nlemma left_closed_interval_minus_left_closed_interval':\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min b c) \\<union> left_closed_interval a b \\<inter> I[d \\<infinity>]\"\nproof(cases \"d = \\<infinity>\")\n  case True \n  have 0: \"(I::eint set) - J = left_closed_interval a b \\<inter> open_ray c c \\<union> left_closed_interval a b \\<inter> I[\\<infinity> \\<infinity>]\"\n    using True  assms minus_left_closed_interval'[of d I c] unfolding assms \n    by blast \n  show ?thesis \n    using 0  unfolding True left_closed_interval_open_ray_intersection using closed_interval_left_closed_interval_intersection\n    unfolding Int_commute[of \"I[d \\<infinity>]\"]\n    by blast \nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) left_closed_interval_minus_left_closed_interval)\nqed\n\nlemma left_closed_interval_minus_left_closed_interval'':\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = left_closed_interval a (min b c) \\<union> left_closed_interval (max d a) b\"\n  using closed_interval_left_closed_interval_intersection[of d \\<infinity> a b]\n        left_closed_interval_minus_left_closed_interval' assms \n  by (simp add: Int_commute)\n\nlemma left_closed_interval_minus_closed_ray:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = left_closed_interval (max (d + 1) a) (min (\\<infinity> + 1) b)\"\nproof-\n  have 0: \"I - J =  left_closed_interval a b \\<inter> I[d + 1 \\<infinity>]\"\n    using assms minus_closed_ray[of d I c] unfolding assms \n    by blast \n  thus ?thesis using closed_interval_left_closed_interval_intersection[of \"d+1\" \\<infinity> a b] \n    unfolding Int_commute[of \"I[d + 1 \\<infinity>]\"] by blast \nqed\n\nlemma left_closed_interval_minus_closed_ray':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = {}\"\n  by (simp add: assms(1) assms(3) minus_closed_ray')\n\nlemma left_closed_interval_minus_open_ray:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J = left_closed_interval (max d a) b\"\nproof-\n  have 0: \"I - J =  left_closed_interval a b \\<inter> I[d \\<infinity>]\"\n    using assms minus_open_ray[of d I c] unfolding assms \n    by blast \n  thus ?thesis using closed_interval_left_closed_interval_intersection[of \"d\" \\<infinity>  a b  ] \n    unfolding Int_commute[of \"I[d \\<infinity>]\"] \n    by simp\nqed\n\nlemma left_closed_interval_minus_open_ray':\n  assumes \"(I::eint set) = left_closed_interval a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J = left_closed_interval (max d a) b\"\nproof(cases \"d = \\<infinity>\")\n  case True\n  have 0: \"max d a = \\<infinity>\"\n    by (simp add: True)\n  show ?thesis\n    by(rule equalityI', \n       unfold Diff_iff Un_iff Int_iff left_closed_interval_def assms mem_Collect_eq open_ray_def True, \n       auto)\nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) left_closed_interval_minus_open_ray)\nqed\n\nlemma closed_ray_minus_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_ray (a::eint) b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min (b + 1) c) \\<union> I[d + 1 b]\"\nproof-\n  have 0: \"I - J = I \\<inter> open_ray c c \\<union> I \\<inter> I[d + 1 \\<infinity>]\"\n    using assms minus_closed_interval[of d I c] unfolding assms \n    by blast \n  have 1: \"I \\<inter> open_ray c c = open_ray a (min (b + 1) c)\"\n    unfolding closed_ray_open_ray_intersection assms by blast \n  have 2: \"I \\<inter> I[d + 1 \\<infinity>] = I[d + 1 b]\"\n    using closed_interval_closed_ray_intersection[of \"d+1\" \\<infinity> a b] unfolding assms \n    by (simp add: Int_commute)\n  show ?thesis using 0 unfolding 1 2 by blast \nqed\n\nlemma closed_ray_minus_closed_interval':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = closed_ray (a::eint) b\"\n  assumes \"J = closed_interval (c::eint) d\"\n  shows \"(I::eint set) - J = open_ray a (min (b + 1) c)\"\nproof(cases \"b = \\<infinity>\")\n  case True \n  show ?thesis\n    by(rule equalityI', \n       unfold Diff_iff Un_iff Int_iff closed_interval_def assms mem_Collect_eq open_ray_def True \n              closed_ray_def,  auto)\nnext\n  case False\n  obtain m where m_def: \"b = eint m\"\n    using False by blast\n  show ?thesis \n    apply(intro equalityI', \n        unfold Diff_iff Un_iff Int_iff closed_interval_def assms mem_Collect_eq open_ray_def m_def \n              closed_ray_def)\n     apply (metis Extended_Int.iless_Suc_eq eint_ord_simps(3) min_less_iff_conj not_eint_eq notin_closed)\n    by (metis Extended_Int.ileI1 min.strict_boundedE notin_closed)\nqed\n\nlemma closed_ray_minus_left_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_ray (a::eint) b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min (b + 1) c) \\<union> I[d b]\"\nproof-\n  have 0: \"I - J =  I \\<inter> open_ray c c \\<union> I \\<inter> I[d \\<infinity>]\"\n    using assms minus_left_closed_interval[of d I c] unfolding assms \n    by blast \n  have 1: \"I \\<inter> open_ray c c = open_ray a (min (b + 1) c)\"\n    unfolding closed_ray_open_ray_intersection assms by blast \n  have 2: \"I \\<inter> I[d  \\<infinity>] = I[d  b]\"\n    using closed_interval_closed_ray_intersection[of \"d\" \\<infinity> a b] unfolding assms \n    by (simp add: Int_commute)\n  show ?thesis using 0 unfolding 1 2 by blast \nqed\n\nlemma closed_ray_minus_left_closed_interval':\n  assumes \"(I::eint set) = closed_ray (a::eint) b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min (b + 1) c) \\<union> I[d b]\"\nproof(cases \"d = \\<infinity>\")\n  case True\n  have 0: \"I - J =  I \\<inter> open_ray c c \\<union> I \\<inter> I[d \\<infinity>]\"\n    using True assms minus_left_closed_interval'[of d I c] unfolding assms \n    by blast \n  have 1: \"I \\<inter> open_ray c c = open_ray a (min (b + 1) c)\"\n    unfolding closed_ray_open_ray_intersection assms by blast \n  have 2: \"I \\<inter> I[d  \\<infinity>] = I[d  b]\"\n    using closed_interval_closed_ray_intersection[of \"d\" \\<infinity> a b] unfolding assms \n    by (simp add: Int_commute)\n  show ?thesis using 0 unfolding 1 2 by blast \nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) closed_ray_minus_left_closed_interval)\nqed\n\nlemma closed_ray_minus_closed_ray:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_ray a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = I[(d + 1) b]\"\nproof-\n  have \"I - J = I \\<inter> I[d + 1 \\<infinity>]\"\n    using minus_closed_ray[of d I c] assms by blast \n  thus ?thesis unfolding assms  closed_interval_closed_ray_intersection\n    using closed_interval_closed_ray_intersection[of \"d+1\" \\<infinity> a b] \n    by (simp add: Int_commute)\nqed\n\nlemma closed_ray_minus_closed_ray':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = closed_ray a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = {}\"\n  unfolding assms closed_ray_def \n  by simp\n\nlemma closed_ray_minus_open_ray:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = closed_ray a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J =  I[d b]\"\nproof-\n  have \"I - J = I \\<inter> I[d  \\<infinity>]\"\n    using minus_open_ray[of d I c] assms by blast \n  thus ?thesis unfolding assms \n    using  closed_interval_closed_ray_intersection[of d \\<infinity> a b]\n    by (simp add: Int_commute)\nqed\n\nlemma closed_ray_minus_open_ray':\n  assumes \"(I::eint set) = closed_ray (a::eint) b\"\n  assumes \"J = open_ray (c::eint) d\"\n  shows \"(I::eint set) - J = I[d b]\"\nproof(cases \"d = \\<infinity>\")\n  case True\n  then show ?thesis unfolding assms True closed_ray_def open_ray_def closed_interval_def \n    by fastforce\nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) closed_ray_minus_open_ray)\nqed\n\nlemma minus_open_ray':\n  assumes \"(d::eint) = \\<infinity>\"\n  shows \"(A::eint set) - open_ray c d = (A \\<inter> closed_interval (\\<infinity>::eint) (\\<infinity>::eint))\"\nproof(rule equalityI')  \n  show \" \\<And>x. x \\<in> A - open_ray c d \\<Longrightarrow> x \\<in> A \\<inter> closed_interval \\<infinity> \\<infinity>\"\n    unfolding assms open_ray_def closed_ray_def \n    by (metis DiffD1 DiffD2 DiffI Diff_Diff_Int mem_Collect_eq minus_closed_interval' open_ray_memE)\n  show \"\\<And>x. x \\<in> A \\<inter> I[\\<infinity> \\<infinity>] \\<Longrightarrow> x \\<in> A - open_ray c d\"\n       unfolding assms open_ray_def closed_ray_def \n       by (metis DiffI IntD1 IntD2 closed_interval_memE(1) closed_interval_memE(2) mem_Collect_eq notin_closed)\nqed\n\nlemma open_ray_minus_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min b c) \\<union> left_closed_interval (d + 1) b\"\nproof-\n  have 0: \"I - J = I \\<inter> open_ray c c \\<union> I \\<inter> I[d + 1 \\<infinity>]\"\n    using assms minus_closed_interval[of d I c] unfolding assms \n    by blast \n  have 1: \"I \\<inter> open_ray c c = open_ray a (min b c)\"\n    unfolding assms open_ray_intersection assms by blast \n  have 2: \"I \\<inter> I[d + 1 \\<infinity>] = left_closed_interval (d + 1) b\"\n    using closed_interval_open_ray_intersection[of \"d+1\" \\<infinity> a b] unfolding assms \n    by (simp add: Int_commute)\n  show ?thesis using 0 unfolding 1 2 by blast \nqed\n\nlemma open_ray_minus_closed_interval':\n  assumes \"d = \\<infinity>\"\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min b c)\"\n  unfolding assms open_ray_def closed_interval_def \n  by force\n\nlemma open_ray_minus_left_closed_interval:\n  assumes \"d \\<noteq> \\<infinity>\"\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min b c) \\<union> left_closed_interval d b\"\nproof-\n  have 0: \"I - J =  I \\<inter> open_ray c c \\<union> I \\<inter> I[d \\<infinity>]\"\n    using assms minus_left_closed_interval[of d I c] unfolding assms \n    by blast \n  have 1: \"I \\<inter> open_ray c c = open_ray a (min b c)\"\n    unfolding open_ray_intersection assms by blast \n  have 2: \"I \\<inter> I[d  \\<infinity>] = left_closed_interval d b\"\n    using closed_interval_open_ray_intersection[of \"d\" \\<infinity> a b] unfolding assms \n    by (simp add: Int_commute)\n  show ?thesis using 0 unfolding 1 2 by blast \nqed\n\nlemma open_ray_minus_left_closed_interval':\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = left_closed_interval c d\"\n  shows \"(I::eint set) - J = open_ray a (min b c) \\<union> left_closed_interval d b\"\nproof(cases \"d = \\<infinity>\")\ncase True\n  show ?thesis apply(rule equalityI') \n    unfolding assms True open_ray_def left_closed_interval_def \n    apply (metis Diff_iff True Un_iff assms(2) eint_ord_simps(6) left_closed_interval_def left_closed_interval_memI mem_Collect_eq min_less_iff_conj notin_closed)\n    by (metis Diff_iff True Un_commute Un_iff eint_ord_code(3) mem_Collect_eq min.commute min_less_iff_conj notin_closed)\nnext\n  case False \n  then show ?thesis \n    by (simp add: assms(1) assms(2) open_ray_minus_left_closed_interval) \nqed\n\nlemma open_ray_minus_closed_ray:\n  assumes \"d \\<noteq>\\<infinity>\"\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J =left_closed_interval (d + 1) b\"\nproof-\n  have \"I - J = I \\<inter> I[d + 1 \\<infinity>]\"\n    using minus_closed_ray[of d I c] assms by blast \n  thus ?thesis unfolding assms using closed_interval_open_ray_intersection[of \"d+1\" \\<infinity> a b]\n  by (simp add: Int_commute)\nqed\n\nlemma open_ray_minus_closed_ray':\n  assumes \"d =\\<infinity>\"\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = closed_ray c d\"\n  shows \"(I::eint set) - J = {}\"\n  unfolding assms open_ray_def closed_ray_def \n  by simp\n\nlemma open_ray_minus_open_ray:\n  assumes \"d \\<noteq>\\<infinity>\"\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J = left_closed_interval d b\"\nproof-\n  have \"I - J = I \\<inter> I[d  \\<infinity>]\"\n    using minus_open_ray[of d I c] assms by blast \n  thus ?thesis unfolding assms using closed_interval_open_ray_intersection[of d \\<infinity> a b]\n  by (simp add: Int_commute)\nqed\n\nlemma open_ray_minus_open_ray':\n  assumes \"(I::eint set) = open_ray a b\"\n  assumes \"J = open_ray c d\"\n  shows \"(I::eint set) - J = left_closed_interval d b\"\nproof(cases \"d = \\<infinity>\")\n  case True\n  show ?thesis apply(rule equalityI') \n    unfolding True assms left_closed_interval_def using \nDiff_eq_empty_iff assms(1) assms(2) eint_ord_simps(4) eint_ord_simps(6) left_closed_interval_memE(2)\n   left_closed_interval_minus_open_ray' max_eint_simps(3) open_rayE open_ray_memE subset_iff \n     apply (metis DiffD1 DiffD2 DiffI True max.strict_order_iff mem_Collect_eq minus_open_ray' notin_closed)\n  by (metis eint_ord_simps(5) eint_ord_simps(6) mem_Collect_eq)\nnext\n  case False\n  then show ?thesis \n    by (simp add: assms(1) assms(2) open_ray_minus_open_ray)\nqed\nend\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Intersections of Cells with the Same Center\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ncontext padic_fields\nbegin\n\nlemma cell_intersection_bounds:\n  assumes \"a1 \\<in> carrier (SA m)\"\n  assumes \"a1' \\<in> carrier (SA m)\"\n  shows \"\\<exists> a1'' \\<in> carrier (SA m). \\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a1'' x) = max (val (a1 x)) (val (a1' x))\"\nproof- \n  obtain S where S_def: \"S = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a1 x)  < val (a1' x)}\"\n    by blast \n  have S_semialg: \"is_semialgebraic m S\"\n    unfolding S_def using assms semialg_val_strict_ineq_set_is_semialg by blast\n  obtain a1'' where  a1''_def: \"a1'' = fun_glue m S a1' a1\"\n    by blast \n  have a1''_semialg: \"a1'' \\<in> carrier (SA m)\"\n    unfolding a1''_def using assms S_semialg fun_glue_closed by blast\n  have \"\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a1'' x) = max (val (a1 x)) (val (a1' x))\"\n  proof fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    show \" val (a1'' x) = max (val (a1 x)) (val (a1' x))\"\n    proof(cases \"x \\<in> S\")\n      case True\n      then have T0: \"max (val (a1 x)) (val (a1' x)) = val (a1' x)\"\n        unfolding S_def using max.commute max.strict_order_iff mem_Collect_eq by auto \n      have T1: \"(if x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (a1 x) < val (a1' x) then a1' x else a1 x) = a1' x \"\n        using True A unfolding S_def mem_Collect_eq  by presburger \n      have T2: \"a1'' x = (if x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (a1 x) < val (a1' x) then a1' x else a1 x)\"\n        unfolding a1''_def fun_glue_def S_def mem_Collect_eq restrict_def using A by presburger \n      show ?thesis\n        using A True unfolding T0 S_def T2 T1 by blast \n    next\n      case False\n      then show ?thesis         \n        using A unfolding S_def a1''_def fun_glue_def mem_Collect_eq restrict_def max_def\n        by (auto simp: basic_trans_rules(17)) \n    qed\n  qed\n  thus ?thesis using a1''_semialg \n    by blast\nqed\n\nlemma cell_intersection_bounds':\n  assumes \"a1 \\<in> carrier (SA m)\"\n  assumes \"a1' \\<in> carrier (SA m)\"\n  shows \"\\<exists> a1'' \\<in> carrier (SA m). \\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a1'' x) = min (val (a1 x)) (val (a1' x))\"\nproof- \n  obtain S where S_def: \"S = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a1' x)  < val (a1 x)}\"\n    by blast \n  have S_semialg: \"is_semialgebraic m S\"\n    unfolding S_def using assms semialg_val_strict_ineq_set_is_semialg by blast\n  obtain a1'' where  a1''_def: \"a1'' = fun_glue m S a1' a1\"\n    by blast \n  have a1''_semialg: \"a1'' \\<in> carrier (SA m)\"\n    unfolding a1''_def using assms S_semialg fun_glue_closed by blast\n  have \"\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a1'' x) = min (val (a1 x)) (val (a1' x))\"\n  proof fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    show \" val (a1'' x) = min (val (a1 x)) (val (a1' x))\"\n    proof(cases \"x \\<in> S\")\n      case True\n      then have T0: \"min (val (a1 x)) (val (a1' x)) = val (a1' x)\"\n        unfolding S_def using  min.commute min.strict_order_iff mem_Collect_eq by auto \n      have T1: \"(if x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (a1' x) < val (a1 x) then a1' x else a1 x) = a1' x \"\n        using True A unfolding S_def mem_Collect_eq  by presburger \n      have T2: \"a1'' x = (if x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (a1' x) < val (a1 x) then a1' x else a1 x)\"\n        unfolding a1''_def fun_glue_def S_def mem_Collect_eq restrict_def using A by presburger \n      show ?thesis\n        using A True unfolding T0 S_def T2 T1 by blast \n    next\n      case False\n      then have F0: \" min (val (a1 x)) (val (a1' x)) = val (a1 x)\"\n        using A unfolding S_def mem_Collect_eq by auto \n      show ?thesis         \n        using A False unfolding F0 S_def a1''_def fun_glue_def mem_Collect_eq restrict_def\n        by presburger        \n    qed\n  qed\n  thus ?thesis using a1''_semialg \n    by blast\nqed\n\nlemma convex_intersection:\n  assumes \"is_convex A\"\n  assumes \"is_convex B\"\n  shows \"is_convex (A \\<inter> B)\"\n  apply(rule is_convexI)\n  using assms is_convexE[of A] is_convexE[of B]\n  by blast\n\nlemma convex_condition_intersection:\n  assumes \"is_convex_condition I\"\n  assumes \"is_convex_condition I'\"\n  assumes \"a1 \\<in> carrier (SA m)\"\n  assumes \"a1' \\<in> carrier (SA m)\"\n  assumes \"a2 \\<in> carrier (SA m)\"\n  assumes \"a2' \\<in> carrier (SA m)\"\n  shows \"\\<exists> l u J. is_convex_condition J \\<and> l \\<in> carrier (SA m) \\<and> u \\<in> carrier (SA m) \\<and>\n               (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). (J (val (l x)) (val (u x)) = I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x))))\"\nproof-\n  obtain l where l_def: \"l \\<in> carrier (SA m) \\<and> (\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (l x) = max (val (a1 x)) (val (a1' x)))\"\n    using assms by (metis (no_types, opaque_lifting) cell_intersection_bounds)\n  obtain u where u_def: \"u \\<in> carrier (SA m) \\<and> (\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (u x) = min (val (a2 x)) (val (a2' x)))\"\n    using assms by (metis (no_types, opaque_lifting) cell_intersection_bounds')\n  obtain u' where u'_def: \"u' \\<in> carrier (SA m) \\<and> (\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (u' x) = min (val (a2 x)) (val ((\\<pp>\\<odot>\\<^bsub>SA m\\<^esub>a2') x)))\"\n    using assms \n    by (metis (no_types, opaque_lifting) Qp.int_inc_closed SA_smult_closed cell_intersection_bounds')\n  obtain u'' where u''_def: \"u'' \\<in> carrier (SA m) \\<and> (\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (u'' x) = min (val ((\\<pp>\\<odot>\\<^bsub>SA m\\<^esub>a2) x)) (val ((a2') x)))\"\n    using assms \n    by (metis (no_types, opaque_lifting) Qp.int_inc_closed SA_smult_closed cell_intersection_bounds')\n  have 0: \"(\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (u'' x) = min (val ((a2 x)) + 1) (val ((a2') x)))\"\n    using u''_def by (metis assms(5) p_mult_function_val)\n  have 1: \"(\\<forall> x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (u' x) = min (val (a2 x)) (val ((a2' x)) + 1) )\"\n    using u''_def  by (metis assms(6) p_mult_function_val u'_def)\n  show ?thesis\n  proof(cases \"I = closed_interval\")\n  case True\n  show ?thesis\n  proof(cases \"I' = closed_interval\")\n    case T: True\n    have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = I (val (l x)) (val (u x))\"\n      unfolding True T using l_def u_def \n      by (metis closed_interval_intersection)\n    show ?thesis \n      using \\<open>\\<forall>x\\<in>carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = I (val (l x)) (val (u x))\\<close> assms(1) l_def u_def \n      by blast    \n  next\n    case False\n    show ?thesis \n     proof(cases \"I' = left_closed_interval\")\n       case T: True\n       have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (l x)) (val (u'' x))\"\n         unfolding True T using l_def u''_def 1 by (metis \"0\" closed_interval_left_closed_interval_intersection)\n      then show ?thesis \n        using T assms(2) l_def u''_def by blast\n    next\n      case F0: False\n      show ?thesis\n        proof(cases \"I' = closed_ray\")\n          case T: True\n          have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = closed_interval (val (a1 x)) (val (u x))\"\n            unfolding True T using u_def by (metis closed_interval_closed_ray_intersection)\n          then show ?thesis using l_def u_def  True eval_hom_def is_convex_condition_def assms(3) \n            by metis\n        next\n          case F1: False\n          have F10: \"I' = open_ray\"\n            using assms False F0 F1 unfolding is_convex_condition_def by blast \n          have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (a1 x)) (val (u'' x))\"\n            unfolding True F10 using u''_def 0 closed_interval_open_ray_intersection[of ] by metis\n              then show ?thesis using assms l_def u''_def  by (metis eval_hom_def is_convex_condition_def)\n     qed\n    qed\n  qed\nnext\n  case False\n  show ?thesis \n    proof(cases \"I = left_closed_interval\")\n      case True\n      show ?thesis\n      proof(cases \"I' = closed_interval\")\n        case T: True\n        have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = I (val (l x)) (val (u' x))\"\n          unfolding True T using min.commute l_def u'_def 1 closed_interval_left_closed_interval_intersection\n          by (metis inf_sup_aci(1) max.commute)\n        thus ?thesis \n          using assms(1) assms l_def u'_def   by blast\n      next\n        case False\n        show ?thesis \n        proof(cases \"I' = left_closed_interval\")\n          case T: True\n          have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (l x)) (val (u x))\"\n            unfolding True T using l_def u_def \n            by (metis left_closed_interval_intersection)\n          then show ?thesis \n            using T assms(2) assms l_def u_def  by blast\n        next\n          case F0: False\n          show ?thesis\n          proof(cases \"I' = closed_ray\")\n            case T: True\n            have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (a1 x)) (val (u' x))\"\n              unfolding True T using u'_def 1 left_closed_interval_closed_ray_intersection by metis\n            then show ?thesis \n              using True assms l_def u'_def assms(1) by blast\n          next\n            case F1: False\n            have F10: \"I' = open_ray\"\n              using assms False F0 F1 unfolding is_convex_condition_def by blast \n            have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (a1 x)) (val (u x))\"\n              unfolding True F10 using u_def 0 left_closed_interval_open_ray_intersection[of ] by metis\n            then show ?thesis using assms l_def u_def \n              by (metis eval_hom_def is_convex_condition_def)\n          qed\n        qed\n      qed\n    next\n      case F0: False\n      show ?thesis\n        proof(cases \"I = closed_ray\")\n          case True\n          show ?thesis \n          proof(cases \"I' = closed_interval\")\n            case T: True\n            have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = I' (val (a1' x)) (val (u x))\"\n              unfolding True T using min.commute l_def u_def closed_interval_closed_ray_intersection\n              by (metis (no_types, lifting) inf_sup_aci(1))    \n            thus ?thesis \n              using assms l_def u_def assms by blast\n          next\n            case False\n            show ?thesis \n            proof(cases \"I' = left_closed_interval\")\n              case T: True\n              have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (a1' x)) (val (u'' x))\"\n                unfolding True T using 0  left_closed_interval_closed_ray_intersection min.commute \n                by (metis inf_sup_aci(1))\n              then show ?thesis \n                using T assms(2) assms l_def u''_def  by blast\n            next\n              case F0: False\n              show ?thesis\n              proof(cases \"I' = closed_ray\")\n                case T: True\n                have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = closed_ray (val (a1 x)) (val (u x))\"\n                  unfolding True T using u_def 1 closed_ray_intersection by metis\n                then show ?thesis \n                  using True assms(1) assms l_def u_def  by blast\n              next\n                case F1: False\n                have F10: \"I' = open_ray\"\n                  using assms False F0 F1 unfolding is_convex_condition_def by blast \n                have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = open_ray (val (a1 x)) (val (u'' x))\"\n                  unfolding True F10 using u'_def 1 closed_ray_open_ray_intersection[of ] min.commute \n                  by (metis \"0\")            \n                then show ?thesis using assms l_def u''_def \n                  by (metis eval_hom_def is_convex_condition_def)\n              qed\n            qed\n          qed\n          next\n          case F1: False\n          have True: \"I = open_ray\"\n            using assms False F0 F1 unfolding is_convex_condition_def by blast \n          then show ?thesis \n          proof(cases \"I' = closed_interval\")\n            case T: True\n            have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (a1' x)) (val (u' x))\"\n              unfolding True T using 1 min.commute closed_interval_open_ray_intersection\n              by (metis inf_sup_aci(1))            \n                thus ?thesis \n                  using assms assms l_def u'_def \n                  by (metis eval_hom_def is_convex_condition_def)                \n              next\n                case False\n                show ?thesis \n                proof(cases \"I' = left_closed_interval\")\n                  case T: True\n                  have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = left_closed_interval (val (a1' x)) (val (u x))\"\n                    unfolding True T using u_def  left_closed_interval_open_ray_intersection min.commute \n                    by (metis inf_sup_aci(1))\n                  then show ?thesis \n                    using T assms(2) assms l_def u_def  by blast\n                next\n                  case F0: False\n                  show ?thesis\n                  proof(cases \"I' = closed_ray\")\n                    case T: True\n                    have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = open_ray (val (a1' x)) (val (u' x))\"\n                      unfolding True T using 1 closed_ray_open_ray_intersection \n                      by (metis inf_commute min.commute)\n                    then show ?thesis \n                      using assms l_def u'_def True assms(1) by blast\n                  next\n                    case F1: False\n                    have F10: \"I' = open_ray\"\n                      using assms False F0 F1 unfolding is_convex_condition_def by blast \n                    have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x)) = open_ray (val (a1 x)) (val (u x))\"\n                      unfolding True F10 using u_def 1 open_ray_intersection[of ] min.commute \n                      by (metis \"0\")            \n                    then show ?thesis using assms l_def u_def \n                      by (metis eval_hom_def is_convex_condition_def)\n                  qed\n                qed\n              qed\n            qed\n          qed\n        qed\nqed\n\nlemma cell_intersection_same_center:\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  assumes \"\\<C> = Cond m C c a1 a2 I\"\n  assumes \"\\<C>' = Cond m C' c a1' a2' I'\"\n  shows \"\\<exists> \\<C>''. is_cell_condition \\<C>'' \\<and> arity \\<C>' = m \\<and> center \\<C>' = c \n                \\<and> condition_to_set \\<C>'' = condition_to_set \\<C> \\<inter> condition_to_set \\<C>'\"\nproof-\n  obtain l u J where luJ_def: \" is_convex_condition J \\<and> l \\<in> carrier (SA m) \\<and> u \\<in> carrier (SA m) \\<and>\n               (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). (J (val (l x)) (val (u x)) = I (val (a1 x)) (val (a2 x)) \\<inter> I' (val (a1' x)) (val (a2' x))))\"\n    using convex_condition_intersection[of I I' a1 m a1' a2 a2'] assms[of ] \n    by (metis (mono_tags, lifting) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5))\n  obtain \\<C>'' where def: \"\\<C>'' = Cond m (C \\<inter> C') c l u J\"\n    by blast \n  have 0:\"is_cell_condition \\<C>''\"\n    apply(rule is_cell_conditionI)\n    using assms\n    unfolding def assms fibre_set.simps arity.simps center.simps l_bound.simps u_bound.simps boundary_condition.simps\n        apply (meson is_cell_conditionE(1) padic_fields.intersection_is_semialg padic_fields_axioms)\n    using assms padic_fields.is_cell_conditionE(2) padic_fields_axioms apply blast\n    using assms luJ_def apply blast \n    using assms luJ_def apply blast \n    using assms luJ_def by blast \n  have 1: \"condition_to_set \\<C>'' = condition_to_set \\<C> \\<inter> condition_to_set \\<C>'\"\n    unfolding assms def condition_to_set.simps \n    apply(rule equalityI')\n     apply(rule IntI)\n    apply(rule cell_memI) using cell_memE \n    apply blast\n    using cell_memE(2) apply blast\n  proof- \n    show \" \\<And>x. x \\<in> cell m (C \\<inter> C') c l u J \\<Longrightarrow> val (lead_coeff x \\<ominus> c (tl x)) \\<in> I (val (a1 (tl x))) (val (a2 (tl x)))\"\n    proof-  fix x assume A: \" x \\<in> cell m (C \\<inter> C') c l u J\"\n      have 0: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using A cell_memE \n        by (meson Qp_pow_ConsE(1))\n      have 1: \" J (val (l (tl x))) (val (u (tl x))) = I (val (a1 (tl x))) (val (a2 (tl x))) \\<inter> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n        using \"0\" luJ_def by blast\n      have 2: \"val (lead_coeff x \\<ominus> c (tl x)) \\<in> I (val (a1 (tl x))) (val (a2 (tl x))) \\<inter> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n        using luJ_def cell_memE[of x m \"C \\<inter> C'\" c l u J] IntE unfolding 1\n        using A by blast\n      thus \"val (lead_coeff x \\<ominus> c (tl x)) \\<in> I (val (a1 (tl x))) (val (a2 (tl x)))\"\n        by blast \n    qed\n    show \"\\<And>x. x \\<in> cell m (C \\<inter> C') c l u J \\<Longrightarrow> x \\<in> cell m C' c a1' a2' I'\"\n      apply(rule cell_memI)\n      using cell_memE(1) apply blast\n      using cell_memE(2) apply blast\n    proof- \n    show \" \\<And>x. x \\<in> cell m (C \\<inter> C') c l u J \\<Longrightarrow> val (lead_coeff x \\<ominus> c (tl x)) \\<in> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n    proof-  fix x assume A: \" x \\<in> cell m (C \\<inter> C') c l u J\"\n      have 0: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using A cell_memE \n        by (meson Qp_pow_ConsE(1))\n      have 1: \" J (val (l (tl x))) (val (u (tl x))) = I (val (a1 (tl x))) (val (a2 (tl x))) \\<inter> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n        using \"0\" luJ_def by blast\n      have 2: \"val (lead_coeff x \\<ominus> c (tl x)) \\<in> I (val (a1 (tl x))) (val (a2 (tl x))) \\<inter> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n        using luJ_def cell_memE[of x m \"C \\<inter> C'\" c l u J] IntE unfolding 1\n        using A by blast\n      thus \"val (lead_coeff x \\<ominus> c (tl x)) \\<in> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n        by blast \n    qed\n    qed\n    show \"\\<And>x. x \\<in> cell m C c a1 a2 I \\<inter> cell m C' c a1' a2' I' \\<Longrightarrow> x \\<in> cell m (C \\<inter> C') c l u J\"\n      apply(rule cell_memI)\n        apply (meson Int_iff cell_memE(1))\n      using cell_memE(2) apply blast\n    proof- \n      fix x assume A: \"x \\<in> cell m C c a1 a2 I \\<inter> cell m C' c a1' a2' I'\"\n      then have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        by (meson basic_trans_rules(31) cell_subset inf_le1)\n      have 0:\" J (val (l (tl x))) (val (u (tl x))) = I (val (a1 (tl x))) (val (a2 (tl x))) \\<inter> I' (val (a1' (tl x))) (val (a2' (tl x)))\"\n        using luJ_def x_closed Qp_pow_ConsE(1) by blast\n      show \"val (lead_coeff x \\<ominus> c (tl x)) \\<in> J (val (l (tl x))) (val (u (tl x)))\"\n        unfolding 0 using A cell_memE[of x m C' c a1' a2' I'] cell_memE[of x m C c a1 a2 I] \n        by (metis Int_iff Qp_pow_ConsE(1) luJ_def)\n    qed\n  qed\n  show \"\\<exists>\\<C>''. is_cell_condition \\<C>'' \\<and> arity \\<C>' = m \\<and> center \\<C>' = c \\<and> condition_to_set \\<C>'' = condition_to_set \\<C> \\<inter> condition_to_set \\<C>'\"\n    by (metis (mono_tags, opaque_lifting) \"0\" \"1\" arity.elims assms(4) cell_condition.simps(1) center.simps padic_fields.cell_condition.exhaust padic_fields.cell_condition.simps(1) padic_fields.condition_decomp' padic_fields_axioms)\nqed\nend\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Formalizing a Remark of Denef\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext\\<open>This section works for formalize the important remark at the beginning of Denef's proof of cell \ndecomposition $II$: \"We will often use without mentioning the trivial fact that a boolean \ncombination of cells with the same center $c(x)$ can be partitioned into a finite number of cells \nwith the same center $c(x)$.\"\n\nOur proof of this fact is somewhat artificially long because it tediously proves various results in \ncases for the four different types of convexity conditions we have chosen to consider. A reworking \nof this could likely bring the line count down considerably. Denef's trivial fact is the content of \nthe theorem \\texttt{c\\_decomposable\\_is\\_gen\\_boolean\\_algebra}. \\<close>\n\ncontext padic_fields\nbegin\n\nlemma cell_cond_semialg:\n  assumes \"is_convex_condition I\"\n  assumes \"f \\<in> carrier (SA m)\"\n  assumes \"a1 \\<in> carrier (SA m)\"\n  assumes \"a2 \\<in> carrier (SA m)\"\n  shows \"is_semialgebraic m ({a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> I (val (a1 a)) (val (a2 a))})\"\nproof-\n\n  obtain \\<phi> where varphi_def: \"\\<phi> =  (function_tuple_eval Q\\<^sub>p m [a1,f,  a2])\"\n    by blast \n  have 0: \"length [a1,f,  a2] = 3\"\n    by auto \n  have varphi_is_semialg_map: \"is_semialg_map m 3 \\<phi>\"\n    unfolding varphi_def apply(rule semialg_function_tuple_is_semialg_map)\n    apply(rule is_semialg_function_tupleI) using assms \n    apply (metis SA_imp_semialg list.distinct(1) list.set_cases set_ConsD)\n    using 0 by blast \n  show ?thesis \n  proof(rule convex_condition_induct)\n    show \"is_convex_condition I\"\n      using assms by blast \n    show \" is_semialgebraic m {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_interval (val (a1 a)) (val (a2 a))}\"\n    proof-\n      have  1: \"{a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_interval (val (a1 a)) (val (a2 a))} = \\<phi>  \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!0) \\<le> val (as!1) \\<and> val (as!1) \\<le> val (as!2)}\"\n      proof(rule equalityI')\n        show \" \\<And>x. x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_interval (val (a1 a)) (val (a2 a))} \\<Longrightarrow> x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!0) \\<le> val (as!1) \\<and> val (as!1) \\<le> val (as!2)}\"\n        proof- fix x assume A: \"x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_interval (val (a1 a)) (val (a2 a))}\"\n          have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto\n       have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n       have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n        have 00: \"2 = Suc 1\"\n        by auto \n       have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n       have varphi_closed: \"\\<phi> x \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>)\"\n        using varphi_is_semialg_map A unfolding mem_Collect_eq \n        by (metis (mono_tags) PiE is_semialg_map_closed)\n        have 4: \"\\<phi> x \\<in> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!0) \\<le> val (as!1) \\<and> val (as!1) \\<le> val (as!2)}\"\n        using A varphi_closed unfolding mem_Collect_eq 1 2 3 closed_interval_def by blast \n       thus \"x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 0) \\<le> val (as ! 1) \\<and> val (as ! 1) \\<le> val (as ! 2)}\"\n        unfolding evimage_def using A by blast\n       qed\n      show \"\\<And>x. x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 0) \\<le> val (as ! 1) \\<and> val (as ! 1) \\<le> val (as ! 2)} \\<Longrightarrow>\n         x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_interval (val (a1 a)) (val (a2 a))}\"\n      proof fix x assume A: \" x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 0) \\<le> val (as ! 1) \\<and> val (as ! 1) \\<le> val (as ! 2)}\"\n      have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto \n      have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n      have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n      have 00: \"2 = Suc 1\"\n        by auto \n      have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n      show \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (f x) \\<in> closed_interval (val (a1 x)) (val (a2 x))\"\n        using A 0 1 2 3unfolding mem_Collect_eq evimage_def  \n        by (metis (no_types, lifting) A closed_interval_memI evimage_eq mem_Collect_eq)\n      qed\n      qed\n      show ?thesis unfolding 1 \n        using semialg_map_evimage_is_semialg triple_val_ineq_set_semialg varphi_is_semialg_map by blast\n    qed\n    show \"is_semialgebraic m {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> left_closed_interval (val (a1 a)) (val (a2 a))}\"\n    proof-\n      have  1: \"{a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> left_closed_interval (val (a1 a)) (val (a2 a))} = \\<phi>  \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!0) \\<le> val (as!1) \\<and> val (as!1) < val (as!2)}\"\n      proof(rule equalityI')\n        show \" \\<And>x. x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> left_closed_interval (val (a1 a)) (val (a2 a))} \\<Longrightarrow> x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!0) \\<le> val (as!1) \\<and> val (as!1) < val (as!2)}\"\n        proof- fix x assume A: \"x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> left_closed_interval (val (a1 a)) (val (a2 a))}\"\n          have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto \n       have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n       have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n        have 00: \"2 = Suc 1\"\n        by auto \n       have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n       have varphi_closed: \"\\<phi> x \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>)\"\n        using varphi_is_semialg_map A unfolding mem_Collect_eq \n        by (metis (mono_tags) PiE is_semialg_map_closed)\n        have 4: \"\\<phi> x \\<in> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!0) \\<le> val (as!1) \\<and> val (as!1) < val (as!2)}\"\n        using A varphi_closed unfolding mem_Collect_eq 1 2 3 left_closed_interval_def by blast \n       thus \"x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 0) \\<le> val (as ! 1) \\<and> val (as ! 1) <val (as ! 2)}\"\n        unfolding evimage_def using A by blast\n       qed\n      show \"\\<And>x. x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 0) \\<le> val (as ! 1) \\<and> val (as ! 1) < val (as ! 2)} \\<Longrightarrow>\n         x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> left_closed_interval (val (a1 a)) (val (a2 a))}\"\n      proof fix x assume A: \" x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 0) \\<le> val (as ! 1) \\<and> val (as ! 1) < val (as ! 2)}\"\n      have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto\n      have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n      have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n      have 00: \"2 = Suc 1\"\n        by auto \n      have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n      show \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (f x) \\<in> left_closed_interval (val (a1 x)) (val (a2 x))\"\n        using A 0 1 2 3 unfolding mem_Collect_eq evimage_def  \n        by (metis (no_types, lifting) A left_closed_interval_memI evimage_eq mem_Collect_eq)\n      qed\n      qed\n      show ?thesis unfolding 1 \n        using semialg_map_evimage_is_semialg triple_val_ineq_set_semialg' varphi_is_semialg_map by blast\n    qed\n    show \"is_semialgebraic m {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_ray (val (a1 a)) (val (a2 a))}\"\n        proof-\n      have  1: \"{a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_ray (val (a1 a)) (val (a2 a))} = \\<phi>  \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!1) \\<le> val (as!2)}\"\n      proof(rule equalityI')\n        show \" \\<And>x. x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_ray (val (a1 a)) (val (a2 a))} \\<Longrightarrow> x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!1) \\<le> val (as!2)}\"\n        proof- fix x assume A: \"x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_ray (val (a1 a)) (val (a2 a))}\"\n          have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto \n       have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n       have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n        have 00: \"2 = Suc 1\"\n        by auto \n       have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n       have varphi_closed: \"\\<phi> x \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>)\"\n        using varphi_is_semialg_map A unfolding mem_Collect_eq \n        by (metis (mono_tags) PiE is_semialg_map_closed)\n        have 4: \"\\<phi> x \\<in> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!1) \\<le>  val (as!2)}\"\n        using A varphi_closed unfolding mem_Collect_eq 1 2 3 closed_ray_def by blast \n       thus \"x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 1) \\<le> val (as ! 2)}\"\n        unfolding evimage_def using A by blast\n        qed\n      show \"\\<And>x. x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 1) \\<le> val (as ! 2)} \\<Longrightarrow>\n         x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> closed_ray (val (a1 a)) (val (a2 a))}\"\n      proof fix x assume A: \" x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 1) \\<le> val (as ! 2)}\"\n      have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto \n      have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n      have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n      have 00: \"2 = Suc 1\"\n        by auto \n      have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n      show \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (f x) \\<in> closed_ray (val (a1 x)) (val (a2 x))\"\n        using A 0 1 2 3 unfolding mem_Collect_eq evimage_def  \n        by (metis (no_types, lifting) A closed_ray_memI evimage_eq mem_Collect_eq)\n      qed\n      qed\n      show ?thesis unfolding 1\n        using semialg_map_evimage_is_semialg reverse_val_relation_set_semialg  varphi_is_semialg_map triple_val_ineq_set_semialg''' by blast\n    qed\n    show \"is_semialgebraic m {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> open_ray (val (a1 a)) (val (a2 a))}\"\n        proof-\n      have  1: \"{a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> open_ray (val (a1 a)) (val (a2 a))} = \\<phi>  \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!1) < val (as!2)}\"\n      proof(rule equalityI')\n        show \" \\<And>x. x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> open_ray (val (a1 a)) (val (a2 a))} \\<Longrightarrow> x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!1) < val (as!2)}\"\n        proof- fix x assume A: \"x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> open_ray (val (a1 a)) (val (a2 a))}\"\n          have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto \n       have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n       have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n        have 00: \"2 = Suc 1\"\n        by auto \n       have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n       have varphi_closed: \"\\<phi> x \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>)\"\n        using varphi_is_semialg_map A unfolding mem_Collect_eq \n        by (metis (mono_tags) PiE is_semialg_map_closed)\n        have 4: \"\\<phi> x \\<in> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as!1) <  val (as!2)}\"\n        using A varphi_closed unfolding mem_Collect_eq 1 2 3 open_ray_def by blast \n       thus \"x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 1) < val (as ! 2)}\"\n        unfolding evimage_def using A by blast\n        qed\n      show \"\\<And>x. x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 1) < val (as ! 2)} \\<Longrightarrow>\n         x \\<in> {a \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f a) \\<in> open_ray (val (a1 a)) (val (a2 a))}\"\n      proof fix x assume A: \" x \\<in> \\<phi> \\<inverse>\\<^bsub>m\\<^esub> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>3\\<^esup>). val (as ! 1) < val (as ! 2)}\"\n      have 0: \"\\<phi> x = [a1 x, f x,  a2 x]\"\n        using A unfolding mem_Collect_eq assms varphi_def function_tuple_eval_def \n        by auto \n      have 1: \"\\<phi> x ! 0  = a1 x\"\n        unfolding 0 using nth.simps \n        by (metis nth_Cons_0)\n      have 2: \"\\<phi> x ! 1  = f x\"\n        unfolding 0 using nth.simps \n        by (metis cancel_comm_monoid_add_class.diff_cancel not_gr_zero nth_Cons_0 nth_Cons_pos zero_neq_one_class.one_neq_zero)\n      have 00: \"2 = Suc 1\"\n        by auto \n      have 3: \"\\<phi> x ! 2  = a2 x\"\n        unfolding 0 00 using nth.simps \n        by (metis One_nat_def nth_Cons_0 nth_Cons_Suc)\n      show \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (f x) \\<in> open_ray (val (a1 x)) (val (a2 x))\"\n        using A 0 1 2 3 unfolding mem_Collect_eq evimage_def  \n        by (metis (no_types, lifting) A open_ray_memI evimage_eq mem_Collect_eq)\n      qed\n      qed\n      show ?thesis unfolding 1 \n        using semialg_map_evimage_is_semialg triple_val_ineq_set_semialg'' varphi_is_semialg_map by blast\n    qed\n  qed\nqed\n\nlemma condition_to_set_is_semialgebraic:\n  assumes \"is_cell_condition \\<C>\"\n  shows \"is_semialgebraic (Suc (arity \\<C>)) (condition_to_set \\<C>)\"  \nproof-\n  obtain m C c a1 a2 I where conds: \"\\<C> = Cond m C c a1 a2 I\"\n    using arity.cases by blast\n  have 0: \"are_cell_condition_params m C c a1 a2 I\"\n    using assms conds by blast\n  have 1: \"(condition_to_set \\<C>) = {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C \\<and> val (hd as \\<ominus> c (tl as)) \\<in> I (val (a1 (tl as))) (val (a2 (tl as)))}\"\n    using 0 \n    unfolding conds condition_to_set.simps unfolding cell_def by blast \n  have c_closed: \"c \\<in> carrier (SA m)\"\n    using 0 assms conds is_cell_condition.simps by blast\n  have a1_closed: \"a1 \\<in> carrier (SA m)\"\n    using 0 assms conds is_cell_condition.simps by blast\n  have a2_closed: \"a2 \\<in> carrier (SA m)\"\n    using 0 assms conds is_cell_condition.simps by blast\n  have 2: \"(\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x)) \\<in> carrier (SA (Suc m))\"\n  proof-\n    have 20:\"(\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x)) = restrict (c \\<circ> tl) (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n      by (metis o_def)\n    show ?thesis unfolding 20 \n      using c_closed tl_is_semialg_map[of m] \n      by (metis SA_car padic_fields.SA_car_memE(1) padic_fields_axioms restrict_in_semialg_functions semialg_function_comp_closed tl_is_semialg_map)\n  qed  \n  obtain f where f_def: \"f = ext_hd (Suc m) \\<ominus>\\<^bsub>SA (Suc m)\\<^esub> (\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x))\"\n    by blast \n  have f_closed: \"f \\<in> carrier (SA (Suc m))\"\n    unfolding f_def using 2 ext_hd_closed[of \"Suc m\"] \n    by blast\n  have f_eval: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> f x = hd x \\<ominus> c (tl x)\"\n  proof- fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n    have \"(ext_hd (Suc m) \\<ominus>\\<^bsub>SA (Suc m)\\<^esub> (\\<lambda>x\\<in>carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x))) x = ext_hd (Suc m) x \\<ominus> (\\<lambda>x\\<in>carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x)) x\"\n    unfolding f_def using A ext_hd_closed[of \"Suc m\"] 2   SA_minus_eval[of \"ext_hd (Suc m)\" \"Suc m\" \"(\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x))\" x]\n    by blast\n    then show \"f x = hd x \\<ominus> c (tl x)\"\n    unfolding f_def using A ext_hd_closed[of \"Suc m\"] 2   SA_minus_eval[of \"ext_hd (Suc m)\" \"Suc m\" \"(\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). c (tl x))\" x]\n    unfolding ext_hd_def restrict_def \n    by presburger\n  qed\n\n  have 2: \"(condition_to_set \\<C>) = {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C \\<and> val (f as) \\<in> I (val (a1 (tl as))) (val (a2 (tl as)))}\"\n    using 1 f_eval by auto \n  obtain b1 where b1_def: \"b1 = (\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). a1 (tl x))\"\n    by blast \n  have b1_closed: \"b1 \\<in> carrier (SA (Suc m))\"\n  proof-\n    have 20:\"(\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). a1 (tl x)) = restrict (a1 \\<circ> tl) (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n      by (metis o_def)\n    show ?thesis unfolding 20 \n      using 20 tl_is_semialg_map[of m] a1_closed unfolding b1_def  using tl_comp_in_SA by blast\n  qed\n  obtain b2 where b2_def: \"b2 = (\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). a2 (tl x))\"\n    by blast \n  have b2_closed: \"b2 \\<in> carrier (SA (Suc m))\"\n  proof-\n    have 20:\"(\\<lambda>x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). a2 (tl x)) = restrict (a2 \\<circ> tl) (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n      by (metis o_def)\n    show ?thesis unfolding 20 \n      using 20 tl_is_semialg_map[of m] a2_closed unfolding b2_def  using tl_comp_in_SA by blast\n  qed\n  have 2: \"(condition_to_set \\<C>) = {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C \\<and> val (f as) \\<in> I (val (b1 as)) (val (b2 as))}\"\n    using 2 b1_closed b2_closed b1_def b2_def unfolding restrict_def  \n    by auto \n  have 3: \"(condition_to_set \\<C>) = {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C} \\<inter> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). val (f as) \\<in> I (val (b1 as)) (val (b2 as))}\"\n    unfolding 2 by blast\n  have 4: \"is_semialgebraic (Suc m) {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C}\"\n  proof-\n    have 40: \"{as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C} = tl  \\<inverse>\\<^bsub>Suc m\\<^esub> C\"\n      by(unfold evimage_def, auto )\n    have 41: \"is_semialgebraic m C\"\n      using 0  is_cell_conditionE''(1) by blast\n    show ?thesis \n      unfolding 40 using  41  tl_is_semialg_map[of m] semialg_map_evimage_is_semialg by blast\n  qed\n  have 5: \"is_convex_condition I\"\n    using 0  is_cell_conditionE(5) by blast\n  have 6: \"arity \\<C> = m\"\n    using 0  arity.simps conds by blast    \n  have 5: \"is_semialgebraic (Suc m) {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). val (f as) \\<in> I (val (b1 as)) (val (b2 as))}\"\n    using cell_cond_semialg[of I f \"Suc m\" b1 b2] \"5\" b1_closed b2_closed f_closed by blast\n  show ?thesis unfolding 3 6 using  4 5 intersection_is_semialg by blast  \nqed\n\ntext\\<open>This predicate identifies those subsets of $\\mathbb{Q}_p^{m+1}$ which can be decomposed into \ncells, all with the common center $c$.\\<close>\ndefinition is_c_decomposable where\n\"is_c_decomposable m c Y = (\\<exists>S. S \\<noteq> {} \\<and> is_cell_decomp m S Y \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow>  center C = c))\"\n\nlemma is_c_decomposableE:\n  assumes \"is_c_decomposable m c Y\"\n  shows \"\\<exists>S. S \\<noteq> {}  \\<and>  is_cell_decomp m S Y \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n        \"c \\<in> carrier (SA m)\"\n        \"is_semialgebraic (Suc m) Y\"\n  using assms is_c_decomposable_def apply blast\nproof- \n  obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S Y \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n  by (meson assms is_c_decomposable_def)\n  obtain C where C_def: \"C \\<in> S\"\n    using S_def \n    by blast\n  have \"center C \\<in> carrier (SA m)\"\n    by (metis C_def S_def is_cell_conditionE''(5) is_cell_decompE(4) padic_fields.condition_decomp' padic_fields.is_cell_decompE(3) padic_fields_axioms)\n  have \"\\<And>C. C \\<in> S \\<Longrightarrow> is_semialgebraic (Suc m) (condition_to_set C)\"\n    using S_def is_cell_decompE(3)[of m S Y] is_cell_conditionE \n    by (metis condition_to_set_is_semialgebraic padic_fields.is_cell_decompE(4) padic_fields_axioms)\n  hence 0: \"is_semialgebraic (Suc m) (\\<Union> C \\<in> S. condition_to_set C)\"\n    by (meson S_def finite_union_is_semialgebraic'' is_cell_decompE(1))     \n  have 1: \"\\<Union> (condition_to_set ` S) = Y\"\n    using S_def is_cell_decompE(2)[of m S Y] is_partitionE(2)[of \"condition_to_set ` S\" Y] by blast \n  then show \"is_semialgebraic (Suc m) Y\"\n    using 0 unfolding 1 by blast \n  show \"c \\<in> carrier (SA m)\"\n  proof-\n    have \"c = center C\"\n      using C_def  S_def by blast\n    then show ?thesis \n      using \\<open>center C \\<in> carrier (SA m)\\<close> by blast\n  qed\nqed\n\nlemma is_c_decomposableI:\n  assumes \"S \\<noteq> {}\"\n  assumes \"is_cell_decomp m S Y \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n  shows \"is_c_decomposable m c Y\"\n  unfolding is_c_decomposable_def using assms \n  by blast\n\ndefinition is_c_cell where\n\"is_c_cell m c Y =  (\\<exists>\\<C>. is_cell_condition \\<C> \\<and> arity \\<C> = m \\<and> center \\<C> = c \\<and> Y = condition_to_set \\<C>)\"\n\ndefinition c_cells (\"Cells\\<^bsub>_, _\\<^esub>(_)\") where \n\"c_cells m c C = {Y. is_c_cell m c Y \\<and> Y \\<subseteq> C}\"\n\ndefinition c_decomposables where \n\"c_decomposables m c C = {Y. is_c_decomposable m c Y \\<and> Y \\<subseteq> C}\"\n\nlemma c_decomposables_closed: \n  assumes \"A \\<in> c_decomposables m c C\"\n  shows \"A \\<subseteq> C\"\n  using assms unfolding c_decomposables_def is_c_decomposable_def \n  by blast \n\nlemma c_cell_is_c_decomposable:\n  assumes \"is_cell_condition (Cond m C c a b I)\"\n  shows \"is_c_decomposable m c (condition_to_set (Cond m C c a b I))\"\n  apply(rule is_c_decomposableI[of \"{(Cond m C c a b I)}\"]) \n   apply blast \nproof\n  show \"is_cell_decomp m {Cond m C c a b I} (condition_to_set (Cond m C c a b I))\"\n    apply(rule is_cell_decompI) \n    apply blast\n       apply(rule is_partitionI) \n    apply(rule disjointI) \n    apply blast\n    apply blast\n    using arity.simps assms apply blast\n    unfolding condition_to_set.simps cell_def apply blast \n    by blast \n  show \"\\<forall>Ca. Ca \\<in> {Cond m C c a b I} \\<longrightarrow> center Ca = c\"\n    using center.simps by blast \nqed\n\nlemma boolean_algebra_alt_induct:\nassumes \" A \\<in> gen_boolean_algebra S B\"\nassumes \"P S\"\nassumes \"\\<And>A. A \\<in> B \\<Longrightarrow> P (A \\<inter> S)\"\nassumes \"\\<And> A C.  A \\<in> gen_boolean_algebra S B \\<Longrightarrow> C \\<in> gen_boolean_algebra S B \\<Longrightarrow> P A \\<Longrightarrow> P C \\<Longrightarrow> A \\<inter> C = {} \\<Longrightarrow>  P (A \\<union> C)\"\nassumes \"\\<And> A C.  A \\<in> gen_boolean_algebra S B \\<Longrightarrow> C \\<in> gen_boolean_algebra S B \\<Longrightarrow> P A \\<Longrightarrow> P C \\<Longrightarrow> P (A - C)\"\nshows \"P A\"\n  apply(rule gen_boolean_algebra.induct[of A S B])\n  using assms apply blast \n  using assms apply blast \n  using assms apply blast \nproof- \n  show \"\\<And>A C. A \\<in> gen_boolean_algebra S B \\<Longrightarrow> P A \\<Longrightarrow> C \\<in> gen_boolean_algebra S B \\<Longrightarrow> P C \\<Longrightarrow> P (A \\<union> C)\"\n  proof- fix A C assume A: \"A \\<in> gen_boolean_algebra S B\" \"P A\" \"C \\<in> gen_boolean_algebra S B\" \"P C\"\n    show \" P (A \\<union> C)\"\n    proof- \n      have 0: \"P (S - A)\"\n        using assms(5)[of S A] assms  A(1) A(2) gen_boolean_algebra.simps by blast\n      have 1: \"P (S - C)\"\n        by (simp add: A(3) A(4) assms(2) assms(5) gen_boolean_algebra.intros(1))\n      have 2: \"P ((S - A) \\<union> (A - C))\"\n        apply(rule assms(4)) \n        using A(1) gen_boolean_algebra.intros(4) apply blast\n        using A(1) A(3) gen_boolean_algebra_diff apply blast\n        apply (simp add: \"0\")\n        apply (simp add: A(1) A(2) A(3) A(4) assms(5))\n        by blast   \n      have 3: \"P (S - ((S - A) \\<union> (A - C)))\"\n        using 2 assms(5)[of S \"(S - A \\<union> (A - C))\"] \n        by (meson A(1) A(3) assms(2) gen_boolean_algebra.simps gen_boolean_algebra_diff)\n      have 4: \"A \\<subseteq> S\"\n        using A(1) gen_boolean_algebra_subset by blast\n      have 5: \"C \\<subseteq> S\"\n        using A(3) gen_boolean_algebra_subset by blast\n      have 6: \"S - ((S - A) \\<union> (A - C)) = S - ((S - A) \\<union> (S - C))\" \n        using 4 5 by blast \n      have 7: \"S - ((S - A) \\<union> (A - C)) = A \\<inter> C\" unfolding 6 using 4 5 by blast \n      have 8: \"P (A \\<inter> C)\" using 3 unfolding 7 by blast \n      have 9: \"P ((A \\<inter> C) \\<union> ((A - C) \\<union> (C - A)))\"\n        apply(rule assms(4)) \n        using A(1) A(3) gen_boolean_algebra_intersect apply blast\n           apply(rule gen_boolean_algebra.intros(3)[of \"A - C\" S B \"C - A\"])\n        using A A(1) A(3) gen_boolean_algebra_diff apply blast\n        using A A(1) A(3) gen_boolean_algebra_diff apply blast\n        using 8 apply blast \n         apply(rule assms(4)) \n        using A A(1) A(3) gen_boolean_algebra_diff apply blast\n        using A A(1) A(3) gen_boolean_algebra_diff apply blast\n        using assms A A(1) A(3) gen_boolean_algebra_diff apply blast\n        using assms A A(1) A(3) gen_boolean_algebra_diff apply blast\n        apply blast \n        by blast \n      have 10: \"((A \\<inter> C) \\<union> ((A - C) \\<union> (C - A))) = A \\<union> C\"\n        by blast \n      show ?thesis using 9 unfolding 10 by blast \n    qed\n  qed\n  show \"\\<And>A. A \\<in> gen_boolean_algebra S B \\<Longrightarrow> P A \\<Longrightarrow> P (S - A)\"\n    using assms(2) assms(5) gen_boolean_algebra.intros(1) by blast\nqed\n\nlemma empty_in_cells:\n  assumes \"is_semialgebraic m C\"\n  assumes \"c \\<in> carrier (SA m)\"\n  shows \"{} \\<in> Cells\\<^bsub>m,c\\<^esub>(C)\"\nproof- \n  obtain a where a_def: \"a \\<in> carrier (SA m)\"\n    by blast \n  obtain \\<C> where \\<C>_def: \"\\<C> = Cond m C c a a left_closed_interval\"\n    by blast \n  have 0: \"is_cell_condition \\<C>\" unfolding \\<C>_def \n    apply(rule is_cell_conditionI') \n        apply (simp add: assms(1))\n      using assms(2) apply linarith\n      using a_def apply blast\n      using a_def apply blast\n      unfolding is_convex_condition_def by blast \n  have 1: \"condition_to_set \\<C> = {}\"\n    unfolding \\<C>_def condition_to_set.simps cell_def left_closed_interval_def \n    apply(rule equalityI') unfolding mem_Collect_eq \n    using notin_closed apply blast\n    by blast \n  show ?thesis unfolding c_cells_def is_c_cell_def using 0 1 \\<C>_def \n    by (metis (mono_tags, lifting) arity.simps center.simps empty_subsetI mem_Collect_eq)\nqed\n\nlemma SA_min_fun:\n  assumes \"a \\<in> carrier (SA m)\"\n  assumes \"b \\<in> carrier (SA m)\"\n  shows \"\\<exists>c \\<in> carrier (SA m). (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (c x) = min (val (a x)) (val (b x)))\"\nproof- \n  obtain c where c_def: \"c = fun_glue m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)} a b\"\n    by blast \n  have \"c \\<in> carrier (SA m)\"\n    unfolding c_def apply(rule fun_glue_closed)\n    using assms apply blast \n    using assms apply blast \n    using assms semialg_val_strict_ineq_set_is_semialg by blast\n  have \"\\<forall>x\\<in>carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (c x) = min (val (a x)) (val (b x))\"\n  proof fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    show \"val (c x) = min (val (a x)) (val (b x))\"\n    proof(cases \"x \\<in>  {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)}\")\n      case True\n      then show ?thesis \n        unfolding c_def mem_Collect_eq \n        using fun_glueE[of a m b \"{x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)}\" x] \n      proof -\n        assume a1: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (a x) < val (b x)\"\n        have \"fun_glue m {rs \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a rs) < val (b rs)} a b x = a x\"\n          using True \\<open>\\<lbrakk>a \\<in> carrier (SA m); b \\<in> carrier (SA m); {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)} \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>); x \\<in> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)}\\<rbrakk> \\<Longrightarrow> fun_glue m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)} a b x = a x\\<close> assms(1) assms(2) by blast\n        then show \"val (fun_glue m {rs \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a rs) < val (b rs)} a b x) = min (val (a x)) (val (b x))\"\n          using a1 by (metis min.strict_order_iff)\n      qed\n    next\n      case False\n      then have F0: \"val (b x) \\<le> val (a x)\"\n        unfolding mem_Collect_eq using A not_le by blast\n      hence \" fun_glue m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)} a b x = b x\"\n        using assms False A fun_glueE'[of a m b \"{x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) < val (b x)}\" x]\n        unfolding c_def  \n        by blast\n      thus ?thesis using F0   \n        by (metis c_def min.absorb2)\n    qed\n  qed\n  thus ?thesis \n    using \\<open>c \\<in> carrier (SA m)\\<close> by blast\nqed\n\nlemma SA_max_fun:\n  assumes \"a \\<in> carrier (SA m)\"\n  assumes \"b \\<in> carrier (SA m)\"\n  shows \"\\<exists>c \\<in> carrier (SA m). (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (c x) = max (val (a x)) (val (b x)))\"\nproof- \n  obtain c where c_def: \"c = fun_glue m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)} a b\"\n    by blast \n  have \"c \\<in> carrier (SA m)\"\n    unfolding c_def apply(rule fun_glue_closed)\n    using assms apply blast \n    using assms apply blast \n    using assms semialg_val_strict_ineq_set_is_semialg by blast\n  have \"\\<forall>x\\<in>carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (c x) = max (val (a x)) (val (b x))\"\n  proof fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    show \"val (c x) = max (val (a x)) (val (b x))\"\n    proof(cases \"x \\<in>  {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)}\")\n      case True\n      then show ?thesis \n        unfolding c_def mem_Collect_eq \n        using fun_glueE[of a m b \"{x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)}\" x] \n      proof -\n        assume a1: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<and> val (a x) >val (b x)\"\n        have \"fun_glue m {rs \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a rs) >val (b rs)} a b x = a x\"\n          using True \\<open>\\<lbrakk>a \\<in> carrier (SA m); b \\<in> carrier (SA m); {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)} \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>); x \\<in> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)}\\<rbrakk> \\<Longrightarrow> fun_glue m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)} a b x = a x\\<close> assms(1) assms(2) by blast\n        then show \"val (fun_glue m {rs \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a rs) > val (b rs)} a b x) = max (val (a x)) (val (b x))\"\n          using a1 by (metis max.strict_order_iff)\n      qed\n    next\n      case False\n      then have F0: \"val (b x) \\<ge> val (a x)\"\n        unfolding mem_Collect_eq using A not_le by blast\n      hence \" fun_glue m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)} a b x = b x\"\n        using assms False A fun_glueE'[of a m b \"{x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (a x) > val (b x)}\" x]\n        unfolding c_def  \n        by blast\n      thus ?thesis using F0   \n        by (metis c_def max.absorb2)\n    qed\n  qed\n  thus ?thesis \n    using \\<open>c \\<in> carrier (SA m)\\<close> by blast\nqed\n\nlemma SA_Suc_fun:\n  assumes \"a \\<in> carrier (SA m)\"\n  shows \"\\<exists>b \\<in> carrier (SA m). (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (b x) = val (a x) + 1)\"\n  using assms p_mult_function_val[of a m]  \n  using Qp.int_inc_closed SA_smult_closed by blast\n\nlemma c_decomposable_disjoint_union:\n  assumes \"is_c_decomposable m c A\"\n  assumes \"is_c_decomposable m c B\"\n  assumes \"A \\<inter> B = {}\"\n  shows \"is_c_decomposable m c (A \\<union> B)\"\nproof-\n          obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S A \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n            using assms unfolding mem_Collect_eq using is_c_decomposableE[of m c A] \n            by blast\n          obtain S' where S'_def: \"S' \\<noteq> {} \\<and>is_cell_decomp m S' B \\<and> (\\<forall>C. C \\<in> S' \\<longrightarrow> center C = c)\"\n            using assms unfolding c_decomposables_def mem_Collect_eq using is_c_decomposableE[of m c B] \n            by blast\n          have 0: \"A \\<union> B - A = B\"\n            using assms by blast \n          have 1: \"is_cell_decomp m (S \\<union> S') (A \\<union> B)\"\n            apply(rule cell_decomp_union[of \"A\"]) \n               apply blast \n            using assms 0 apply (meson S'_def S_def Un_subset_iff is_cell_decompE(6))\n            using S_def apply blast\n            using S'_def unfolding 0 by blast \n          show \"is_c_decomposable m c (A \\<union> B)\"\n            apply(rule is_c_decomposableI[of \"S \\<union> S'\"])\n            using  S_def apply blast \n            using 1 S_def S'_def by blast \nqed\n\nlemma change_of_fibres:\n  assumes \"is_cell_condition (Cond m C c a b I)\"\n  assumes \"is_semialgebraic m A\"\n  shows \"is_cell_condition (Cond m A c a b I)\"\n  apply(rule is_cell_conditionI')\n  using assms apply blast \n  using assms is_cell_conditionE apply blast \n  using assms is_cell_conditionE apply blast \n  using assms is_cell_conditionE apply meson\n  using assms is_cell_conditionE by meson\n\nlemma disjoint_fibres:\n  assumes \"is_cell_condition (Cond m C c a b I)\"\n  assumes \"is_cell_condition (Cond m A c' d e J)\"\n  assumes \"C \\<inter> A = {}\"\n  shows \"condition_to_set (Cond m C c a b I) \\<inter> condition_to_set (Cond m A c' d e J) = {}\"\n  unfolding condition_to_set.simps cell_def  using assms by blast \n\nlemma union_fibres:\n  assumes \"is_cell_condition (Cond m C c a b I)\"\n  assumes \"is_cell_condition (Cond m A c a b I)\"\n  shows \"condition_to_set (Cond m (C \\<union> A) c a b I) = condition_to_set (Cond m C c a b I) \\<union> condition_to_set (Cond m A c a b I)\"\n  unfolding condition_to_set.simps cell_def by blast \n \nlemma closed_interval_minus_left_closed_interval_cell_diff0:\n  assumes \"\\<C> = Cond m A cent a b closed_interval\"\n  assumes \"\\<C>' = Cond m B cent c d left_closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  assumes \"\\<forall>x \\<in> B. val (c x) \\<le> val (d x)\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof-\n  have a_closed: \"a \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  have b_closed: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  have c_closed: \"c \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  have d_closed: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  obtain b' where b'_def: \"b' \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (b' x) = val (b x) + 1)\"\n    using b_closed SA_Suc_fun \n    by metis\n  obtain mi where mi_def: \"mi \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (mi x) = min (val (b' x)) (val (c x)))\"\n    using b'_def c_closed SA_min_fun \n    by (metis (no_types, lifting))\n  have mi_val: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> val (mi x) = min (val (b x) + 1) (val (c x))\"\n    using mi_def b'_def c_closed  \n    by metis\n  obtain ma where ma_def: \"ma \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (ma x) = max (val (a x)) (val (d x)))\"\n    using a_closed d_closed SA_max_fun \n    by (metis (no_types, opaque_lifting))\n  have ma_val: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> val (ma x) = max (val (a x)) (val (d x))\"\n    using ma_def a_closed b_closed  \n    by blast\n  have 0: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> \n  closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (min (val (b x) + 1) (val (c x))) \\<union> closed_interval (max (val (a x)) (val (d x))) (val (b x))\"\n  proof- fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\" \n    then show \"closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (min (val (b x) + 1) (val (c x))) \\<union> closed_interval (max (val (a x)) (val (d x))) (val (b x))\"\n    using closed_interval_minus_left_closed_interval'[of _ \"val (a x)\" \"val (b x)\" _ \"val (c x)\" \"val (d x)\"] \n    by blast \n  qed\n  have 1: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> \n  closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (val (mi x)) \\<union> closed_interval (val (ma x)) (val (b x))\"\n  proof- fix x  assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\" \n    have 10: \" val (ma x) = max (val (a x)) (val (d x))\"\n      using A  ma_val by blast \n    have 11: \"val (mi x) = min (val (b x) + 1) (val (c x))\"\n      using A mi_val by blast \n    show \" closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (val (mi x)) \\<union> closed_interval (val (ma x)) (val (b x))\"\n      using A 0[of  x] unfolding 10 11 by blast    \n  qed\n  have 2: \"is_semialgebraic m A\"\n    using assms is_cell_conditionE by blast \n  have 3: \"is_semialgebraic m B\"\n    using assms is_cell_conditionE by blast\n  obtain C0 where C0_def: \"C0 = Cond m (A \\<inter> B) cent a mi left_closed_interval\"\n    by blast\n  obtain C1 where C1_def: \"C1 = Cond m (A \\<inter> B) cent ma b closed_interval\"\n    by blast\n  obtain C2 where C2_def: \"C2 = Cond m (A - B) cent a b closed_interval\"\n    by blast\n  have 4: \"is_cell_condition C0\" unfolding C0_def \n    apply(rule is_cell_conditionI')  \n    using 2 3 intersection_is_semialg apply blast\n    using assms is_cell_conditionE apply blast\n    using a_closed apply blast \n    using mi_def apply blast \n    unfolding is_convex_condition_def by blast \n  have 5: \"is_cell_condition C1\" unfolding C1_def \n    apply(rule is_cell_conditionI')  \n    using 2 3 intersection_is_semialg apply blast\n    using assms is_cell_conditionE apply blast\n    using ma_def apply blast \n    using b_closed apply blast \n    unfolding is_convex_condition_def by blast \n  have 6: \"is_cell_condition C2\" unfolding C2_def \n    apply(rule is_cell_conditionI')  \n    using 2 3 diff_is_semialgebraic apply blast\n    using assms is_cell_conditionE apply blast\n    using a_closed apply blast \n    using b_closed apply blast \n    unfolding is_convex_condition_def by blast \n  have 7: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2\"\n  proof(rule equalityI')\n    show \"\\<And>x. x \\<in> condition_to_set \\<C> - condition_to_set \\<C>' \\<Longrightarrow> x \\<in> condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C> - condition_to_set \\<C>'\" \"x \\<notin> condition_to_set C2\"\n      show \" x \\<in> condition_to_set C0 \\<union> condition_to_set C1\"\n      proof assume  B: \"x \\<notin> condition_to_set C1\" \n        show \"x \\<in> condition_to_set C0\"\n        proof- \n          have 7: \"tl x \\<in> A\"\n            using A condition_to_set_memE unfolding assms cell_def \n            using assms(1) assms(5) by blast\n          have 8: \"val (hd x \\<ominus> (cent (tl x))) \\<in> closed_interval (val (a (tl x))) (val (b (tl x)))\"\n            using assms  A condition_to_set_memE(2) unfolding assms cell_def \n            using assms by blast\n          have 9: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n            using A unfolding assms condition_to_set.simps cell_def \n            by (metis (no_types, lifting) Diff_iff cartesian_power_tail mem_Collect_eq)\n          have 10: \"tl x \\<notin> (A  - B)\"\n            using 8 9 1[of \"tl x\"] A unfolding  condition_to_set.simps cell_def  \n            by (metis C2_def Diff_iff assms(1) assms(5) cell_condition_set_memE(1) cell_condition_set_memI)\n          then have 11: \"tl x \\<in> B\"\n            using 7 by blast \n          have 12: \"val (hd x \\<ominus> (cent (tl x))) \\<notin> left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using A 11 unfolding condition_to_set.simps cell_def assms by blast \n          hence 13: \"val (hd x \\<ominus> (cent (tl x))) \\<in> closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using 8  by blast \n          hence 14: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n            using 8  1[of \"tl x\"] 9 by blast \n          have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n            using A  unfolding assms condition_to_set.simps cell_def by blast \n          have 15: \"tl x \\<in> A \\<inter> B\"\n            using \"11\" \"7\" by blast\n          hence 16: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x)))\"\n            using 15 14 B 11 7 x_closed unfolding C1_def assms  condition_to_set.simps cell_def mem_Collect_eq \n            by blast\n          show \"x \\<in> condition_to_set C0\"\n            unfolding condition_to_set.simps C0_def apply(rule cell_memI) \n            using x_closed apply linarith\n            using \"15\" apply blast\n            using \"16\" by blast\n        qed\n      qed\n    qed\n    show \"\\<And>x. x \\<in> condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2 \\<Longrightarrow> x \\<in> condition_to_set \\<C> - condition_to_set \\<C>'\"\n    proof- fix x assume A: \"x \\<in> condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2\"\n      have  0: \" closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x))) = left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n        using 1 A unfolding C0_def C1_def C2_def condition_to_set.simps cell_def \n        using Qp_pow_ConsE(1) by blast\n      show \"x \\<in> condition_to_set \\<C> - condition_to_set \\<C>'\"\n      proof \n        show \"x \\<in> condition_to_set \\<C>\"\n          apply(cases \"x \\<in> condition_to_set C0\")\n          unfolding C0_def condition_to_set.simps assms \n           apply(rule cell_memI) \n          using cell_memE apply blast \n          using cell_memE apply blast\n          using 0 cell_memE \n          apply (metis Diff_iff Int_iff inf_sup_absorb)\n          unfolding C0_def condition_to_set.simps assms \n          apply(cases \"x \\<in> condition_to_set C1\")\n           apply(rule cell_memI) \n          using 1 A unfolding C0_def C1_def C2_def condition_to_set.simps cell_def apply blast \n          using cell_memE A unfolding mem_Collect_eq apply blast\n          using 0 cell_memE apply blast\n        proof- \n          assume A' : \" \\<not> (x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A \\<inter> B \\<and> val (hd x \\<ominus> cent (tl x)) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))))\"\n                      \" \\<not> (x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A \\<inter> B \\<and> val (hd x \\<ominus> cent (tl x)) \\<in> I[val (ma (tl x)) val (b (tl x))])\"\n          then have 00: \"x \\<in> condition_to_set C2\"\n            using A  unfolding condition_to_set.simps C0_def C1_def cell_def C2_def by blast \n          have 01: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n            using 00 unfolding condition_to_set.simps C2_def cell_def by blast \n          have 02: \"tl x \\<in> A\" \n            using 00 unfolding condition_to_set.simps C2_def cell_def by blast \n          have 03: \"val (hd x \\<ominus> cent (tl x)) \\<in> I[val (a (tl x)) val (b (tl x))]\"\n            using 00 unfolding condition_to_set.simps C2_def cell_def by blast \n          show \" x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A \\<and> val (hd x \\<ominus> cent (tl x)) \\<in> I[val (a (tl x)) val (b (tl x))] \"\n            using 01 02 03 by blast \n        qed\n        have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n          using A unfolding C0_def C1_def C2_def  condition_to_set.simps cell_def by blast \n        have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n          using x_closed Qp_pow_ConsE(1) by blast\n        show \"x \\<notin> condition_to_set \\<C>'\"\n        proof(cases \"x \\<in> condition_to_set C0\")\n          case True\n          have 0: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n            using True unfolding C0_def condition_to_set.simps cell_def mem_Collect_eq by blast \n          hence 1: \"val (hd x \\<ominus> (cent (tl x))) \\<in> closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using 1[of \"tl x\"] True tl_x_closed by blast \n          show \"x \\<notin> condition_to_set \\<C>'\"\n            unfolding condition_to_set.simps cell_def mem_Collect_eq assms \n            using  x_closed True condition_to_set_memE unfolding C0_def \n            using \"1\" by blast\n        next\n          case False\n          show ?thesis\n          proof(cases \"x \\<in> condition_to_set C1\")\n          case  True\n          have 0: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n            using True unfolding C1_def condition_to_set.simps cell_def mem_Collect_eq by blast \n          hence 1: \"val (hd x \\<ominus> (cent (tl x))) \\<in> closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using 1[of \"tl x\"] True tl_x_closed by blast \n          show \"x \\<notin> condition_to_set \\<C>'\"\n            unfolding condition_to_set.simps cell_def mem_Collect_eq assms \n            using  x_closed True condition_to_set_memE unfolding C0_def \n            using \"1\" by blast\n        next \n          case F: False \n          then have True: \"x \\<in> condition_to_set C2\"\n            using False A by blast \n          then have \"tl x  \\<notin> B\"\n            unfolding C2_def condition_to_set.simps cell_def by blast \n          then show \"x \\<notin> condition_to_set \\<C>'\"\n            unfolding assms condition_to_set.simps cell_def by blast \n        qed\n      qed\n    qed\n  qed\n  qed\n  have d0:  \"condition_to_set C0 \\<inter> condition_to_set C1 = {}\"\n  proof(rule equalityI') \n    show \"\\<And>x. x \\<in> condition_to_set C0 \\<inter> condition_to_set C1 \\<Longrightarrow> x \\<in> {}\"\n    proof fix x assume A: \"x \\<in> condition_to_set C0 \\<inter> condition_to_set C1\"\n      have 00: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x)))\"\n        using A unfolding C0_def condition_to_set.simps cell_def by blast  \n      have 01: \"val (hd x \\<ominus> (cent (tl x))) \\<in> closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n        using A unfolding C1_def condition_to_set.simps cell_def by blast  \n      have 02: \"val (mi (tl x)) = min (val (b (tl x)) + 1) (val (c (tl x)))\"\n        using mi_val[of \"tl x\"] A  unfolding C0_def condition_to_set.simps cell_def \n        by (metis (no_types, lifting) Int_iff Qp_pow_ConsE(1) mem_Collect_eq mi_val)\n      have 03: \"val (ma (tl x)) = max (val (a (tl x))) (val (d (tl x)))\"\n        using ma_val[of \"tl x\"] A\n        unfolding C0_def condition_to_set.simps cell_def\n        by (metis (no_types, lifting) Int_iff Qp_pow_ConsE(1) mem_Collect_eq mi_val)\n      have 04: \"tl x \\<in> B\"\n        using A unfolding C0_def condition_to_set.simps cell_def by blast  \n      have 05: \"val (c (tl x)) \\<le> val (d (tl x))\"\n        using assms(7) 04 by blast \n      show \"x \\<in> {}\"\n        using 00 01 05 unfolding 02 03 left_closed_interval_def closed_interval_def  mem_Collect_eq \n        by fastforce\n      show \"\\<And>x. x \\<in> condition_to_set C0 \\<inter> condition_to_set C1 \\<Longrightarrow> {} \\<subseteq> {}\"\n        by blast \n    qed\n    show \"\\<And>x. x \\<in> {} \\<Longrightarrow> x \\<in> condition_to_set C0 \\<inter> condition_to_set C1\"\n      by blast \n  qed\n  have d1: \"condition_to_set C0 \\<inter> condition_to_set C2 = {}\"\n    unfolding C0_def C2_def condition_to_set.simps cell_def by blast \n  have d2: \"condition_to_set C1 \\<inter> condition_to_set C2 = {}\"\n    unfolding C1_def C2_def condition_to_set.simps cell_def by blast \n  obtain S where S_def: \"S = {C0, C1, C2}\"\n    by blast \n  have 8: \"disjoint (condition_to_set ` {C0, C1, C2})\"\n    unfolding disjoint_def using d0 d1 d2 \n    by blast\n  have 9: \"is_cell_decomp m S (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    apply(rule is_cell_decompI) \n    unfolding S_def apply blast \n    apply(rule is_partitionI) \n    using 8 apply blast \n    using 7 apply blast \n    using 4 5 6 unfolding C0_def C1_def  C2_def \n    using condition_decomp(1) apply blast\n    unfolding assms condition_to_set.simps cell_def apply blast \n    using 8 disjointE unfolding C0_def C1_def  C2_def  \n    using C0_def C1_def C2_def d0 d1 d2 by blast\n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    apply(rule is_c_decomposableI[of S]) \n    unfolding S_def apply blast \n    unfolding C0_def C1_def C2_def \n    using \"9\" C0_def C1_def C2_def S_def center.simps by blast\nqed    \n\nlemma closed_interval_minus_left_closed_interval_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b closed_interval\"\n  assumes \"\\<C>' = Cond m B cent c d left_closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof-\n  obtain B' where B'_def: \"B' = B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (c x) \\<le> val (d x)}\"\n    by blast \n  have c_closed: \"c \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE(3) by blast\n  have d_closed : \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE(4) by blast\n  have B'_semialg: \"is_semialgebraic m B'\"\n    unfolding B'_def \n    apply(rule intersection_is_semialg)\n    using assms is_cell_conditionE(1) apply blast\n    using c_closed d_closed semialg_val_ineq_set_is_semialg by blast \n  have 0: \"condition_to_set \\<C>' = condition_to_set (Cond m B' cent c d left_closed_interval)\"\n  proof(rule equalityI')\n    show \" \\<And>x. x \\<in> condition_to_set \\<C>' \\<Longrightarrow> x \\<in> condition_to_set (Cond m B' cent c d left_closed_interval)\"\n    proof- fix x assume a: \"x \\<in> condition_to_set \\<C>'\"\n      have 0: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using a assms unfolding assms condition_to_set.simps cell_def \n        using Qp_pow_ConsE(1) by blast\n      have  1: \"tl x \\<in> B'\"\n        unfolding B'_def using 0 a le_less basic_trans_rules(21)[of \"val (c (tl x))\" \"val (hd x \\<ominus> cent (tl x))\" \"val (d (tl x))\"] unfolding assms condition_to_set.simps cell_def mem_Collect_eq left_closed_interval_def  \n        by blast    \n      show \"x \\<in> condition_to_set (Cond m B' cent c d left_closed_interval)\"\n        using a unfolding assms condition_to_set.simps assms cell_def left_closed_interval_def mem_Collect_eq B'_def \n        using \"1\" B'_def by blast\n    qed\n    show \"\\<And>x. x \\<in> condition_to_set (Cond m B' cent c d left_closed_interval) \\<Longrightarrow> x \\<in> condition_to_set \\<C>'\"\n      unfolding assms  condition_to_set.simps B'_def cell_def by blast \n  qed\n  have 1: \"is_cell_condition (Cond m B' cent c d left_closed_interval)\"\n    apply(rule is_cell_conditionI') \n    using B'_semialg apply blast \n    using assms is_cell_conditionE apply blast \n      using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE[of m B cent c d left_closed_interval] apply blast \n    using assms is_cell_conditionE[of m B cent c d left_closed_interval] by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 0  apply(rule closed_interval_minus_left_closed_interval_cell_diff0[of _ _ A _ a b _ B' c d  C])\n    using assms B'_def 1  apply blast\n         apply blast \n    using assms apply blast \n    using assms B'_def 1 apply blast \n    using assms apply blast \n    using 1  apply blast \n    unfolding B'_def by blast \nqed\n\nlemma left_closed_interval_minus_left_closed_interval_cell_diff0:\n  assumes \"\\<C> = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C>' = Cond m B cent c d left_closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  assumes \"\\<forall>x \\<in> B. val (c x) \\<le> val (d x)\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof-\n  have a_closed: \"a \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  have b_closed: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  have c_closed: \"c \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  have d_closed: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE \n    by meson\n  obtain mi where mi_def: \"mi \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (mi x) = min (val (b x)) (val (c x)))\"\n    using b_closed c_closed SA_min_fun \n    by (metis (no_types, lifting))\n  have mi_val: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> val (mi x) = min (val (b x)) (val (c x))\"\n    using mi_def  c_closed  \n    by metis\n  obtain ma where ma_def: \"ma \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (ma x) = max (val (a x)) (val (d x)))\"\n    using a_closed d_closed SA_max_fun \n    by (metis (no_types, opaque_lifting))\n  have ma_val: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> val (ma x) = max (val (a x)) (val (d x))\"\n    using ma_def a_closed b_closed  \n    by blast\n  have 0: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> \n  left_closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (min (val (b x)) (val (c x))) \\<union> left_closed_interval (max (val (a x)) (val (d x))) (val (b x))\"\n  proof- fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\" \n    then show \"left_closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (min (val (b x)) (val (c x))) \\<union> left_closed_interval (max (val (a x)) (val (d x))) (val (b x))\"\n    using max.commute left_closed_interval_minus_left_closed_interval''[of _ \"val (a x)\" \"val (b x)\" _ \"val (c x)\" \"val (d x)\"] \n    by metis  \n  qed\n  have 1: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>) \\<Longrightarrow> \n  left_closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (val (mi x)) \\<union> left_closed_interval (val (ma x)) (val (b x))\"\n  proof- fix x  assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\" \n    have 10: \" val (ma x) = max (val (a x)) (val (d x))\"\n      using A  ma_val by blast \n    have 11: \"val (mi x) = min (val (b x)) (val (c x))\"\n      using A mi_val by blast \n    show \" left_closed_interval (val (a x)) (val (b x)) - left_closed_interval (val (c x)) (val (d x)) = left_closed_interval (val (a x)) (val (mi x)) \\<union> left_closed_interval (val (ma x)) (val (b x))\"\n      using A 0[of  x] unfolding 10 11 by blast    \n  qed\n  have 2: \"is_semialgebraic m A\"\n    using assms is_cell_conditionE by blast \n  have 3: \"is_semialgebraic m B\"\n    using assms is_cell_conditionE by blast\n  obtain C0 where C0_def: \"C0 = Cond m (A \\<inter> B) cent a mi left_closed_interval\"\n    by blast\n  obtain C1 where C1_def: \"C1 = Cond m (A \\<inter> B) cent ma b left_closed_interval\"\n    by blast\n  obtain C2 where C2_def: \"C2 = Cond m (A - B) cent a b left_closed_interval\"\n    by blast\n  have 4: \"is_cell_condition C0\" unfolding C0_def \n    apply(rule is_cell_conditionI')  \n    using 2 3 intersection_is_semialg apply blast\n    using assms is_cell_conditionE apply blast\n    using a_closed apply blast \n    using mi_def apply blast \n    unfolding is_convex_condition_def by blast \n  have 5: \"is_cell_condition C1\" unfolding C1_def \n    apply(rule is_cell_conditionI')  \n    using 2 3 intersection_is_semialg apply blast\n    using assms is_cell_conditionE apply blast\n    using ma_def apply blast \n    using b_closed apply blast \n    unfolding is_convex_condition_def by blast \n  have 6: \"is_cell_condition C2\" unfolding C2_def \n    apply(rule is_cell_conditionI')  \n    using 2 3 diff_is_semialgebraic apply blast\n    using assms is_cell_conditionE apply blast\n    using a_closed apply blast \n    using b_closed apply blast \n    unfolding is_convex_condition_def by blast \n  have 7: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2\"\n  proof(rule equalityI')\n    show \"\\<And>x. x \\<in> condition_to_set \\<C> - condition_to_set \\<C>' \\<Longrightarrow> x \\<in> condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C> - condition_to_set \\<C>'\" \"x \\<notin> condition_to_set C2\"\n      show \" x \\<in> condition_to_set C0 \\<union> condition_to_set C1\"\n      proof assume  B: \"x \\<notin> condition_to_set C1\" \n        show \"x \\<in> condition_to_set C0\"\n        proof- \n          have 7: \"tl x \\<in> A\"\n            using A condition_to_set_memE unfolding assms cell_def \n            using assms(1) assms(5) by blast\n          have 8: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (b (tl x)))\"\n            using assms  A condition_to_set_memE(2) unfolding assms cell_def \n            using assms by blast\n          have 9: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n            using A unfolding assms condition_to_set.simps cell_def \n            by (metis (no_types, lifting) Diff_iff cartesian_power_tail mem_Collect_eq)\n          have 10: \"tl x \\<notin> (A  - B)\"\n            using 8 9 1[of \"tl x\"] A unfolding  condition_to_set.simps cell_def  \n            by (metis C2_def Diff_iff assms(1) assms(5) cell_condition_set_memE(1) cell_condition_set_memI)\n          then have 11: \"tl x \\<in> B\"\n            using 7 by blast \n          have 12: \"val (hd x \\<ominus> (cent (tl x))) \\<notin> left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using A 11 unfolding condition_to_set.simps cell_def assms by blast \n          hence 13: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using 8  by blast \n          hence 14: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> left_closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n            using 8  1[of \"tl x\"] 9 by blast \n          have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n            using A  unfolding assms condition_to_set.simps cell_def by blast \n          have 15: \"tl x \\<in> A \\<inter> B\"\n            using \"11\" \"7\" by blast\n          hence 16: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x)))\"\n            using 15 14 B 11 7 x_closed unfolding C1_def assms  condition_to_set.simps cell_def mem_Collect_eq \n            by blast\n          show \"x \\<in> condition_to_set C0\"\n            unfolding condition_to_set.simps C0_def apply(rule cell_memI) \n            using x_closed apply linarith\n            using \"15\" apply blast\n            using \"16\" by blast\n        qed\n      qed\n    qed\n    show \"\\<And>x. x \\<in> condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2 \\<Longrightarrow> x \\<in> condition_to_set \\<C> - condition_to_set \\<C>'\"\n    proof- fix x assume A: \"x \\<in> condition_to_set C0 \\<union> condition_to_set C1 \\<union> condition_to_set C2\"\n      have  0: \"left_closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x))) = left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> left_closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n        using 1 A unfolding C0_def C1_def C2_def condition_to_set.simps cell_def \n        using Qp_pow_ConsE(1) by blast\n      show \"x \\<in> condition_to_set \\<C> - condition_to_set \\<C>'\"\n      proof \n        show \"x \\<in> condition_to_set \\<C>\"\n          apply(cases \"x \\<in> condition_to_set C0\")\n          unfolding C0_def condition_to_set.simps assms \n           apply(rule cell_memI) \n          using cell_memE apply blast \n          using cell_memE apply blast\n          using 0 cell_memE \n          apply (metis Diff_iff Int_iff inf_sup_absorb)\n          unfolding C0_def condition_to_set.simps assms \n          apply(cases \"x \\<in> condition_to_set C1\")\n           apply(rule cell_memI) \n          using 1 A unfolding C0_def C1_def C2_def condition_to_set.simps cell_def apply blast \n          using cell_memE A unfolding mem_Collect_eq apply blast\n          using 0 cell_memE apply blast\n        proof- \n          assume A' : \" \\<not> (x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A \\<inter> B \\<and> val (hd x \\<ominus> cent (tl x)) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))))\"\n                      \" \\<not> (x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A \\<inter> B \\<and> val (hd x \\<ominus> cent (tl x)) \\<in> left_closed_interval (val (ma (tl x))) (val (b (tl x))))\"\n          then have 00: \"x \\<in> condition_to_set C2\"\n            using A  unfolding condition_to_set.simps C0_def C1_def cell_def C2_def by blast \n          have 01: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n            using 00 unfolding condition_to_set.simps C2_def cell_def by blast \n          have 02: \"tl x \\<in> A\" \n            using 00 unfolding condition_to_set.simps C2_def cell_def by blast \n          have 03: \"val (hd x \\<ominus> cent (tl x)) \\<in> left_closed_interval (val (a (tl x))) (val (b (tl x)))\"\n            using 00 unfolding condition_to_set.simps C2_def cell_def by blast \n          show \" x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A \\<and> val (hd x \\<ominus> cent (tl x)) \\<in> left_closed_interval (val (a (tl x))) (val (b (tl x)))\"\n            using 01 02 03 by blast \n        qed\n        have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n          using A unfolding C0_def C1_def C2_def  condition_to_set.simps cell_def by blast \n        have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n          using x_closed Qp_pow_ConsE(1) by blast\n        show \"x \\<notin> condition_to_set \\<C>'\"\n        proof(cases \"x \\<in> condition_to_set C0\")\n          case True\n          have 0: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> left_closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n            using True unfolding C0_def condition_to_set.simps cell_def mem_Collect_eq by blast \n          hence 1: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using 1[of \"tl x\"] True tl_x_closed by blast \n          show \"x \\<notin> condition_to_set \\<C>'\"\n            unfolding condition_to_set.simps cell_def mem_Collect_eq assms \n            using  x_closed True condition_to_set_memE unfolding C0_def \n            using \"1\" by blast\n        next\n          case False\n          show ?thesis\n          proof(cases \"x \\<in> condition_to_set C1\")\n          case  True\n          have 0: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x))) \\<union> left_closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n            using True unfolding C1_def condition_to_set.simps cell_def mem_Collect_eq by blast \n          hence 1: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (b (tl x))) - left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n            using 1[of \"tl x\"] True tl_x_closed by blast \n          show \"x \\<notin> condition_to_set \\<C>'\"\n            unfolding condition_to_set.simps cell_def mem_Collect_eq assms \n            using  x_closed True condition_to_set_memE unfolding C0_def \n            using \"1\" by blast\n        next \n          case F: False \n          then have True: \"x \\<in> condition_to_set C2\"\n            using False A by blast \n          then have \"tl x  \\<notin> B\"\n            unfolding C2_def condition_to_set.simps cell_def by blast \n          then show \"x \\<notin> condition_to_set \\<C>'\"\n            unfolding assms condition_to_set.simps cell_def by blast \n        qed\n      qed\n    qed\n  qed\n  qed\n  have d0:  \"condition_to_set C0 \\<inter> condition_to_set C1 = {}\"\n  proof(rule equalityI') \n    show \"\\<And>x. x \\<in> condition_to_set C0 \\<inter> condition_to_set C1 \\<Longrightarrow> x \\<in> {}\"\n    proof fix x assume A: \"x \\<in> condition_to_set C0 \\<inter> condition_to_set C1\"\n      have 00: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (a (tl x))) (val (mi (tl x)))\"\n        using A unfolding C0_def condition_to_set.simps cell_def by blast  \n      have 01: \"val (hd x \\<ominus> (cent (tl x))) \\<in> left_closed_interval (val (ma (tl x))) (val (b (tl x)))\"\n        using A unfolding C1_def condition_to_set.simps cell_def by blast  \n      have 02: \"val (mi (tl x)) = min (val (b (tl x))) (val (c (tl x)))\"\n        using mi_val[of \"tl x\"] A  unfolding C0_def condition_to_set.simps cell_def \n        by (metis (no_types, lifting) Int_iff Qp_pow_ConsE(1) mem_Collect_eq mi_val)\n      have 03: \"val (ma (tl x)) = max (val (a (tl x))) (val (d (tl x)))\"\n        using ma_val[of \"tl x\"] A\n        unfolding C0_def condition_to_set.simps cell_def\n        by (metis (no_types, lifting) Int_iff Qp_pow_ConsE(1) mem_Collect_eq mi_val)\n      have 04: \"tl x \\<in> B\"\n        using A unfolding C0_def condition_to_set.simps cell_def by blast  \n      have 05: \"val (c (tl x)) \\<le> val (d (tl x))\"\n        using assms(7) 04 by blast \n      show \"x \\<in> {}\"\n        using 00 01 05 unfolding 02 03 left_closed_interval_def closed_interval_def  mem_Collect_eq \n        by fastforce\n      show \"\\<And>x. x \\<in> condition_to_set C0 \\<inter> condition_to_set C1 \\<Longrightarrow> {} \\<subseteq> {}\"\n        by blast \n    qed\n    show \"\\<And>x. x \\<in> {} \\<Longrightarrow> x \\<in> condition_to_set C0 \\<inter> condition_to_set C1\"\n      by blast \n  qed\n  have d1: \"condition_to_set C0 \\<inter> condition_to_set C2 = {}\"\n    unfolding C0_def C2_def condition_to_set.simps cell_def by blast \n  have d2: \"condition_to_set C1 \\<inter> condition_to_set C2 = {}\"\n    unfolding C1_def C2_def condition_to_set.simps cell_def by blast \n  obtain S where S_def: \"S = {C0, C1, C2}\"\n    by blast \n  have 8: \"disjoint (condition_to_set ` {C0, C1, C2})\"\n    unfolding disjoint_def using d0 d1 d2 \n    by blast\n  have 9: \"is_cell_decomp m S (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    apply(rule is_cell_decompI) \n    unfolding S_def apply blast \n    apply(rule is_partitionI) \n    using 8 apply blast \n    using 7 apply blast \n    using 4 5 6 unfolding C0_def C1_def  C2_def \n    using condition_decomp(1) apply blast\n    unfolding assms condition_to_set.simps cell_def apply blast \n    using 8 disjointE unfolding C0_def C1_def  C2_def  \n    using C0_def C1_def C2_def d0 d1 d2 by blast\n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    apply(rule is_c_decomposableI[of S]) \n    unfolding S_def apply blast \n    unfolding C0_def C1_def C2_def \n    using \"9\" C0_def C1_def C2_def S_def center.simps by blast\nqed    \n\nlemma left_closed_interval_minus_left_closed_interval_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C>' = Cond m B cent c d left_closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof-\n  obtain B' where B'_def: \"B' = B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (c x) \\<le> val (d x)}\"\n    by blast \n  have c_closed: \"c \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE(3) by blast\n  have d_closed : \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE(4) by blast\n  have B'_semialg: \"is_semialgebraic m B'\"\n    unfolding B'_def \n    apply(rule intersection_is_semialg)\n    using assms is_cell_conditionE(1) apply blast\n    using c_closed d_closed semialg_val_ineq_set_is_semialg by blast \n  have 0: \"condition_to_set \\<C>' = condition_to_set (Cond m B' cent c d left_closed_interval)\"\n  proof(rule equalityI')\n    show \" \\<And>x. x \\<in> condition_to_set \\<C>' \\<Longrightarrow> x \\<in> condition_to_set (Cond m B' cent c d left_closed_interval)\"\n    proof- fix x assume a: \"x \\<in> condition_to_set \\<C>'\"\n      have 0: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using a assms unfolding assms condition_to_set.simps cell_def \n        using Qp_pow_ConsE(1) by blast\n      have  1: \"tl x \\<in> B'\"\n        unfolding B'_def using 0 a le_less basic_trans_rules(21)[of \"val (c (tl x))\" \"val (hd x \\<ominus> cent (tl x))\" \"val (d (tl x))\"] unfolding assms condition_to_set.simps cell_def mem_Collect_eq left_closed_interval_def  \n        by blast    \n      show \"x \\<in> condition_to_set (Cond m B' cent c d left_closed_interval)\"\n        using a unfolding assms condition_to_set.simps assms cell_def left_closed_interval_def mem_Collect_eq B'_def \n        using \"1\" B'_def by blast\n    qed\n    show \"\\<And>x. x \\<in> condition_to_set (Cond m B' cent c d left_closed_interval) \\<Longrightarrow> x \\<in> condition_to_set \\<C>'\"\n      unfolding assms  condition_to_set.simps B'_def cell_def by blast \n  qed\n  have 1: \"is_cell_condition (Cond m B' cent c d left_closed_interval)\"\n    apply(rule is_cell_conditionI') \n    using B'_semialg apply blast \n    using assms is_cell_conditionE apply blast \n      using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE[of m B cent c d left_closed_interval] apply blast \n    using assms is_cell_conditionE[of m B cent c d left_closed_interval] by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 0  apply(rule left_closed_interval_minus_left_closed_interval_cell_diff0[of _ _ A _ a b _ B' c d  C])\n    using assms B'_def 1  apply blast\n         apply blast \n    using assms apply blast \n    using assms B'_def 1 apply blast \n    using assms apply blast \n    using 1  apply blast \n    unfolding B'_def by blast \nqed\n\nlemma left_closed_interval_minus_closed_interval_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C>' = Cond m B cent c d closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  have d_semialg: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE[of m B cent c d] by blast \n  obtain d' where d'_def: \"d' \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (d' x) = val (d x) + 1)\"\n    using d_semialg SA_Suc_fun by blast\n  obtain B0 where B0_def: \"B0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> B\"\n    by blast \n  have B0_semialg: \"is_semialgebraic m B0\"\n    unfolding B0_def apply(rule intersection_is_semialg)\n    using d_semialg SA_nonzero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] by blast \n  obtain B1 where B1_def: \"B1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> B\"\n    by blast \n  have B1_semialg: \"is_semialgebraic m B1\"\n    unfolding B1_def apply(rule intersection_is_semialg)\n    using d_semialg SA_zero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] by blast \n  obtain \\<C>0 where \\<C>0_def: \"\\<C>0 = Cond m B0 cent c d' left_closed_interval\"\n    by blast \n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B1 cent c d closed_interval\"\n    by blast \n  have \\<C>0_cell_cond: \"is_cell_condition \\<C>0\"\n    unfolding \\<C>0_def apply(rule is_cell_conditionI') \n    using B0_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using d'_def apply blast \n    by (simp add: is_convex_condition_def)\n  have \\<C>1_cell_cond: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def apply(rule is_cell_conditionI') \n    using B1_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    by (simp add: is_convex_condition_def)\n  have 0: \"condition_to_set \\<C>' = condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n  proof\n    show \"condition_to_set \\<C>' \\<subseteq> condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>'\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using A unfolding assms using assms cell_condition_set_memE(1) by blast\n    have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n      using Qp_pow_ConsE(1) x_closed by blast\n    show \"x \\<in> condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n    proof(cases \"d (tl x) = \\<zero>\")\n        case True\n        have \"tl x \\<in> B1\"\n          unfolding B1_def using tl_x_closed assms A condition_to_set_memE(1)[of \\<C>' m B cent c d closed_interval x] True \n          by blast \n        then show ?thesis \n          using A unfolding assms \\<C>1_def condition_to_set.simps B1_def cell_def \n          by blast \n      next\n        case False\n        have F0: \"tl x \\<in> B0\"\n          unfolding B0_def using tl_x_closed assms A condition_to_set_memE(1)[of \\<C>' m B cent c d closed_interval x] False \n          by blast   \n        have F1: \"val (d' (tl x)) =  val (d (tl x)) + 1\"\n          using d'_def tl_x_closed by blast \n        have F2: \"val (d (tl x)) \\<noteq> \\<infinity>\"\n        proof-\n          have \"d (tl x) \\<in> carrier (Q\\<^sub>p)\"\n            using tl_x_closed d_semialg function_ring_car_closed SA_car semialg_functions_memE(2) by metis \n        thus ?thesis \n          using F0  tl_x_closed d_semialg unfolding B0_def \n          by (metis (no_types, opaque_lifting) False eint_ord_code(3) val_ineq)\n        qed\n        have F3: \"left_closed_interval (val (c (tl x))) (val (d' (tl x))) = closed_interval (val (c (tl x))) (val (d (tl x))) \"\n          unfolding left_closed_interval_def closed_interval_def unfolding F1 \n          apply(rule equalityI')\n          unfolding mem_Collect_eq \n          using eSuc_ile_mono ileI1 apply blast\n          using F2 F0  \n          by (metis F1 add.commute add.left_commute basic_trans_rules(18) basic_trans_rules(21) basic_trans_rules(22) basic_trans_rules(24) closed_interval_as_left_closed_interval closed_interval_memI eSuc_ile_mono eSuc_infinity eSuc_mono eint_add_left_cancel ile_eSuc infinity_ne_i1 left_closed_interval_memE(2) notin_closed order_eq_iff plus_eint_simps(2) plus_eint_simps(3))\n        then show ?thesis \n          using F0 F1 A unfolding assms \\<C>0_def condition_to_set.simps B0_def cell_def \n          by blast \n    qed\n    qed\n    show \"condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>'\"\n    proof fix x assume a: \"x \\<in> condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using a unfolding assms using assms cell_condition_set_memE(1) \n        by (metis Un_iff \\<C>0_def \\<C>1_def cell_memE(1) condition_to_set.simps)\n    have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n      using Qp_pow_ConsE(1) x_closed by blast\n    show \"x \\<in> condition_to_set \\<C>'\"\n    proof(cases \"x \\<in> condition_to_set \\<C>0\")\n      case True\n        have F0: \"tl x \\<in> B0\"\n          unfolding B0_def using tl_x_closed assms True condition_to_set_memE(1)[of \\<C>0 m B0 cent c d closed_interval x]  \n          B0_def \\<C>0_cell_cond \\<C>0_def cell_condition_set_memE(2) \n          by (meson padic_fields.cell_condition_set_memE(2) padic_fields_axioms) \n        have F1: \"val (d' (tl x)) =  val (d (tl x)) + 1\"\n          using d'_def tl_x_closed by blast \n        have F2: \"val (d (tl x)) \\<noteq> \\<infinity>\"\n        proof-\n          have \"d (tl x) \\<in> carrier (Q\\<^sub>p)\"\n            using tl_x_closed d_semialg function_ring_car_closed SA_car semialg_functions_memE(2) by metis \n        thus ?thesis \n          using F0  tl_x_closed  unfolding val_def unfolding B0_def \n          by (metis (mono_tags, lifting) Int_iff eint.simps(2) mem_Collect_eq)\n        qed\n        have F3: \"left_closed_interval (val (c (tl x))) (val (d' (tl x))) = closed_interval (val (c (tl x))) (val (d (tl x))) \"\n          unfolding left_closed_interval_def closed_interval_def unfolding F1 \n          apply(rule equalityI')\n          unfolding mem_Collect_eq \n          using eSuc_ile_mono ileI1 apply blast\n          using F2 F0  \n          by (metis F1 add.commute add.left_commute basic_trans_rules(18) basic_trans_rules(21) basic_trans_rules(22) basic_trans_rules(24) closed_interval_as_left_closed_interval closed_interval_memI eSuc_ile_mono eSuc_infinity eSuc_mono eint_add_left_cancel ile_eSuc infinity_ne_i1 left_closed_interval_memE(2) notin_closed order_eq_iff plus_eint_simps(2) plus_eint_simps(3))\n        show ?thesis\n             using True \n             unfolding assms \\<C>0_def condition_to_set.simps B0_def cell_def mem_Collect_eq F3 by blast \n    next\n           case False\n           then show ?thesis\n             using a unfolding assms \\<C>1_def condition_to_set.simps cell_def B1_def by blast \n    qed\n    qed\n  qed\n  have 1: \"condition_to_set \\<C>0 \\<inter> condition_to_set \\<C>1 = {}\"\n    unfolding \\<C>0_def \\<C>1_def condition_to_set.simps B1_def B0_def cell_def by blast \n  obtain A0 where A0_def: \"A0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> A\"\n    by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    unfolding A0_def apply(rule intersection_is_semialg)\n    using d_semialg SA_nonzero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m A cent a b] by blast \n  obtain A1 where A1_def: \"A1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> A\"\n    by blast \n  have A1_semialg: \"is_semialgebraic m A1\"\n    unfolding A1_def apply(rule intersection_is_semialg)\n    using d_semialg SA_zero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m A cent a b] by blast \n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m A0 cent a b left_closed_interval\"\n    by blast \n  obtain \\<C>3 where \\<C>3_def: \"\\<C>3 = Cond m A1 cent a b left_closed_interval\"\n    by blast \n  have \\<C>2_is_cell_cond: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def using assms change_of_fibres A0_semialg by blast\n  have \\<C>3_is_cell_cond: \"is_cell_condition \\<C>3\"\n    unfolding \\<C>3_def using assms change_of_fibres A1_semialg by blast\n  have disjoint: \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>3 = {}\"\n    unfolding \\<C>2_def \\<C>3_def apply(rule disjoint_fibres) \n    using \\<C>2_is_cell_cond unfolding \\<C>2_def apply blast \n    using \\<C>3_is_cell_cond unfolding \\<C>3_def apply blast \n    unfolding A1_def A0_def by blast \n  have A_closed: \"A \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    using assms is_cell_conditionE(1) is_semialgebraic_closed by blast\n  have 2: \"A = A0 \\<union> A1\"\n    using A_closed unfolding   A0_def A1_def by blast \n  have union: \"condition_to_set \\<C> = condition_to_set \\<C>2 \\<union> condition_to_set \\<C>3\"\n    unfolding assms \\<C>2_def \\<C>3_def 2 apply(rule union_fibres) \n    using \\<C>2_is_cell_cond unfolding \\<C>2_def apply blast \n    using \\<C>3_is_cell_cond unfolding \\<C>3_def by blast \n  have 3: \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>1 = {}\"\n    unfolding \\<C>2_def \\<C>1_def apply(rule disjoint_fibres)  unfolding \\<C>2_def \\<C>1_def \n    using \\<C>2_def \\<C>2_is_cell_cond apply blast\n    using \\<C>1_cell_cond \\<C>1_def apply blast\n    unfolding A0_def B1_def by blast \n  have 4: \"condition_to_set \\<C>3 \\<inter> condition_to_set \\<C>0 = {}\"\n    unfolding \\<C>3_def \\<C>0_def apply(rule disjoint_fibres)  unfolding \\<C>3_def \\<C>0_def \n    using \\<C>3_def \\<C>3_is_cell_cond apply blast\n    using \\<C>0_cell_cond \\<C>0_def apply blast\n    unfolding A1_def B0_def by blast \n  have 5: \"condition_to_set \\<C> - condition_to_set \\<C>' = \n          (condition_to_set \\<C>2 - condition_to_set \\<C>0) \\<union> (condition_to_set \\<C>3 - condition_to_set \\<C>1)\"\n    using union 3 4 disjoint 0 by blast \n  have 6: \"is_c_decomposable m cent (condition_to_set \\<C>2 - condition_to_set \\<C>0)\"\n    apply (rule left_closed_interval_minus_left_closed_interval_cell_diff[of _ _ A0 _ a b _ B0 c d' \"A0 \\<union> B0\"])\n    unfolding \\<C>2_def \\<C>0_def \n    apply blast apply blast apply blast apply blast \n    using \\<C>2_def \\<C>2_is_cell_cond apply blast\n    using \\<C>0_cell_cond \\<C>0_def by blast\n  have 7: \"condition_to_set \\<C>3 - condition_to_set \\<C>1 = condition_to_set \\<C>3 - condition_to_set (Cond m B1 cent c d left_closed_interval)\"\n  proof\n    show \"condition_to_set \\<C>3 - condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>3 - condition_to_set (Cond m B1 cent c d left_closed_interval)\"\n    proof fix x assume A: \"x \\<in>  condition_to_set \\<C>3 - condition_to_set \\<C>1\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using A using \\<C>3_is_cell_cond unfolding \\<C>3_def \n        by (meson Diff_iff cell_condition_set_memE(1))\n      have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using Qp_pow_ConsE(1) x_closed by blast\n      have dx: \"d (tl x) = \\<zero> \"\n        using A unfolding \\<C>3_def condition_to_set.simps cell_def A1_def \n        unfolding  \\<C>3_def \\<C>1_def using closed_interval_def left_closed_interval_def\n        by blast \n      have val_dx: \"val (d (tl x)) = \\<infinity>\"\n        using dx  local.val_zero by presburger\n      have 70: \"closed_interval (val (c (tl x))) (val (d (tl x))) = {\\<infinity>} \\<union> left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n        unfolding val_dx left_closed_interval_def closed_interval_def \n        apply(rule equalityI')\n         apply (metis Un_commute Un_iff eint_ord_simps(4) mem_Collect_eq singletonI)\n        by (metis (no_types, lifting) Un_commute Un_iff eint_ord_code(3) emptyE insert_iff mem_Collect_eq)\n      have 71: \"val (hd x \\<ominus> cent (tl x)) \\<noteq> \\<infinity>\"\n        using A unfolding \\<C>3_def condition_to_set.simps cell_def left_closed_interval_def \n        using Diff_iff eint_ord_simps(6) mem_Collect_eq \n        by (metis (no_types, lifting))\n      show \" x \\<in> condition_to_set \\<C>3 - condition_to_set (Cond m B1 cent c d left_closed_interval)\"\n        using A 71 70 unfolding condition_to_set.simps cell_def \\<C>1_def by blast\n    qed\n    show \"condition_to_set \\<C>3 - condition_to_set (Cond m B1 cent c d left_closed_interval) \\<subseteq> condition_to_set \\<C>3 - condition_to_set \\<C>1\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>3 - condition_to_set (Cond m B1 cent c d left_closed_interval)\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using A using \\<C>3_is_cell_cond unfolding \\<C>3_def \n        by (meson Diff_iff cell_condition_set_memE(1))\n      have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using Qp_pow_ConsE(1) x_closed by blast\n      have dx: \"d (tl x) = \\<zero> \"\n        using A unfolding \\<C>3_def condition_to_set.simps cell_def A1_def \n        unfolding  \\<C>3_def \\<C>1_def using closed_interval_def left_closed_interval_def\n        by blast \n      have val_dx: \"val (d (tl x)) = \\<infinity>\"\n        using dx  local.val_zero by presburger\n      have 70: \"closed_interval (val (c (tl x))) (val (d (tl x))) = {\\<infinity>} \\<union> left_closed_interval (val (c (tl x))) (val (d (tl x)))\"\n        unfolding val_dx left_closed_interval_def closed_interval_def \n        apply(rule equalityI')\n         apply (metis Un_commute Un_iff eint_ord_simps(4) mem_Collect_eq singletonI)\n        by (metis (no_types, lifting) Un_commute Un_iff eint_ord_code(3) emptyE insert_iff mem_Collect_eq)\n      have 71: \"val (hd x \\<ominus> cent (tl x)) \\<noteq> \\<infinity>\"\n        using A unfolding \\<C>3_def condition_to_set.simps cell_def left_closed_interval_def \n        by force        \n      show \"x \\<in> condition_to_set \\<C>3 - condition_to_set \\<C>1\"\n        using A 71 70 unfolding condition_to_set.simps cell_def \\<C>1_def  \n        by (metis (no_types, lifting) Diff_iff Un_iff empty_iff insert_iff mem_Collect_eq)\n    qed\n  qed\n  have 8: \"is_c_decomposable m cent (condition_to_set \\<C>3 - condition_to_set \\<C>1)\"\n    unfolding 7 unfolding \\<C>3_def apply(rule left_closed_interval_minus_left_closed_interval_cell_diff[of _ _ A1 _ a b _ B1 c d \"A1 \\<union> B1\"])\n         apply auto[1]  apply simp apply blast apply blast \n          using \\<C>3_def \\<C>3_is_cell_cond apply blast\n          by (metis (no_types, lifting) B1_semialg assms(1) assms(2) assms(5) assms(6) is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) is_cell_conditionI')\n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 5  apply (rule   c_decomposable_disjoint_union)\n    using 6 apply blast \n    using 8 apply blast \n    unfolding \\<C>2_def \\<C>3_def condition_to_set.simps cell_def A0_def A1_def by blast \nqed\n\nlemma closed_interval_minus_closed_interval_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b closed_interval\"\n  assumes \"\\<C>' = Cond m B cent c d closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C>' - condition_to_set \\<C>)\"\nproof-\n  have d_semialg: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE[of m B cent c d] by blast \n  obtain d' where d'_def: \"d' \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (d' x) = val (d x) + 1)\"\n    using d_semialg SA_Suc_fun by blast\n  obtain B0 where B0_def: \"B0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> B\"\n    by blast \n  have B0_semialg: \"is_semialgebraic m B0\"\n    unfolding B0_def apply(rule intersection_is_semialg)\n    using d_semialg SA_nonzero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] by blast \n  obtain B1 where B1_def: \"B1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> B\"\n    by blast \n  have B1_semialg: \"is_semialgebraic m B1\"\n    unfolding B1_def apply(rule intersection_is_semialg)\n    using d_semialg SA_zero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] by blast \n  obtain \\<C>0 where \\<C>0_def: \"\\<C>0 = Cond m B0 cent c d' left_closed_interval\"\n    by blast \n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B1 cent c d closed_interval\"\n    by blast \n  have \\<C>0_cell_cond: \"is_cell_condition \\<C>0\"\n    unfolding \\<C>0_def apply(rule is_cell_conditionI') \n    using B0_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using d'_def apply blast \n    by (simp add: is_convex_condition_def)\n  have \\<C>1_cell_cond: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def apply(rule is_cell_conditionI') \n    using B1_semialg apply blast\n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    using assms is_cell_conditionE[of m B cent c d] apply  blast \n    by (simp add: is_convex_condition_def)\n  have 0: \"condition_to_set \\<C>' = condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n  proof\n    show \"condition_to_set \\<C>' \\<subseteq> condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>'\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using A unfolding assms using assms cell_condition_set_memE(1) by blast\n    have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n      using Qp_pow_ConsE(1) x_closed by blast\n    show \"x \\<in> condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n    proof(cases \"d (tl x) = \\<zero>\")\n        case True\n        have \"tl x \\<in> B1\"\n          unfolding B1_def using tl_x_closed assms A condition_to_set_memE(1)[of \\<C>' m B cent c d closed_interval x] True \n          by blast \n        then show ?thesis \n          using A unfolding assms \\<C>1_def condition_to_set.simps B1_def cell_def \n          by blast \n      next\n        case False\n        have F0: \"tl x \\<in> B0\"\n          unfolding B0_def using tl_x_closed assms A condition_to_set_memE(1)[of \\<C>' m B cent c d closed_interval x] False \n          by blast   \n        have F1: \"val (d' (tl x)) =  val (d (tl x)) + 1\"\n          using d'_def tl_x_closed by blast \n        have F2: \"val (d (tl x)) \\<noteq> \\<infinity>\"\n        proof-\n          have \"d (tl x) \\<in> carrier (Q\\<^sub>p)\"\n            using tl_x_closed d_semialg function_ring_car_closed SA_car semialg_functions_memE(2) by metis \n        thus ?thesis \n          using F0  tl_x_closed d_semialg unfolding B0_def \n          by (metis (no_types, opaque_lifting) False eint_ord_code(3) val_ineq)\n        qed\n        have F3: \"left_closed_interval (val (c (tl x))) (val (d' (tl x))) = closed_interval (val (c (tl x))) (val (d (tl x))) \"\n          unfolding left_closed_interval_def closed_interval_def unfolding F1 \n          apply(rule equalityI')\n          unfolding mem_Collect_eq \n          using eSuc_ile_mono ileI1 apply blast\n          using F2 F0  \n          by (metis F1 add.commute add.left_commute basic_trans_rules(18) basic_trans_rules(21) basic_trans_rules(22) basic_trans_rules(24) closed_interval_as_left_closed_interval closed_interval_memI eSuc_ile_mono eSuc_infinity eSuc_mono eint_add_left_cancel ile_eSuc infinity_ne_i1 left_closed_interval_memE(2) notin_closed order_eq_iff plus_eint_simps(2) plus_eint_simps(3))\n        then show ?thesis \n          using F0 F1 A unfolding assms \\<C>0_def condition_to_set.simps B0_def cell_def \n          by blast \n    qed\n    qed\n    show \"condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>'\"\n    proof fix x assume a: \"x \\<in> condition_to_set \\<C>0 \\<union> condition_to_set \\<C>1\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using a unfolding assms using assms cell_condition_set_memE(1) \n        by (metis Un_iff \\<C>0_def \\<C>1_def cell_memE(1) condition_to_set.simps)\n    have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n      using Qp_pow_ConsE(1) x_closed by blast\n    show \"x \\<in> condition_to_set \\<C>'\"\n    proof(cases \"x \\<in> condition_to_set \\<C>0\")\n      case True\n        have F0: \"tl x \\<in> B0\"\n          unfolding B0_def using tl_x_closed assms True condition_to_set_memE(1)[of \\<C>0 m B0 cent c d closed_interval x]  \n          B0_def \\<C>0_cell_cond \\<C>0_def cell_condition_set_memE(2) \n          by (meson padic_fields.cell_condition_set_memE(2) padic_fields_axioms) \n        have F1: \"val (d' (tl x)) =  val (d (tl x)) + 1\"\n          using d'_def tl_x_closed by blast \n        have F2: \"val (d (tl x)) \\<noteq> \\<infinity>\"\n        proof-\n          have \"d (tl x) \\<in> carrier (Q\\<^sub>p)\"\n            using tl_x_closed d_semialg function_ring_car_closed SA_car semialg_functions_memE(2) by metis \n        thus ?thesis \n          using F0  tl_x_closed  unfolding val_def unfolding B0_def \n          by (metis (mono_tags, lifting) Int_iff eint.simps(2) mem_Collect_eq)\n        qed\n        have F3: \"left_closed_interval (val (c (tl x))) (val (d' (tl x))) = closed_interval (val (c (tl x))) (val (d (tl x))) \"\n          unfolding left_closed_interval_def closed_interval_def unfolding F1 \n          apply(rule equalityI')\n          unfolding mem_Collect_eq \n          using eSuc_ile_mono ileI1 apply blast\n          using F2 F0  \n          by (metis F1 add.commute add.left_commute basic_trans_rules(18) basic_trans_rules(21) basic_trans_rules(22) basic_trans_rules(24) closed_interval_as_left_closed_interval closed_interval_memI eSuc_ile_mono eSuc_infinity eSuc_mono eint_add_left_cancel ile_eSuc infinity_ne_i1 left_closed_interval_memE(2) notin_closed order_eq_iff plus_eint_simps(2) plus_eint_simps(3))\n        show ?thesis\n             using True \n             unfolding assms \\<C>0_def condition_to_set.simps B0_def cell_def mem_Collect_eq F3 by blast \n    next\n           case False\n           then show ?thesis\n             using a unfolding assms \\<C>1_def condition_to_set.simps cell_def B1_def by blast \n    qed\n    qed\n  qed\n  have 1: \"condition_to_set \\<C>' - condition_to_set \\<C> \n        = (condition_to_set \\<C>0 - condition_to_set \\<C>) \\<union> (condition_to_set \\<C>1 - condition_to_set \\<C>)\"\n    unfolding 0 by blast \n  have 2: \"condition_to_set \\<C>0 \\<inter> condition_to_set \\<C>1 = {}\"\n    unfolding \\<C>0_def \\<C>1_def condition_to_set.simps B1_def B0_def cell_def by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C>' - condition_to_set \\<C>)\"\n    unfolding 1 apply(rule c_decomposable_disjoint_union)\n    apply(rule left_closed_interval_minus_closed_interval_cell_diff[of _ _ B0 _ c d' _ A a b \"A \\<union> B0\"])\n    unfolding  \\<C>0_def assms apply blast apply blast apply blast apply blast\n    using \\<C>0_cell_cond \\<C>0_def apply blast\n    using assms(1) assms(5) apply blast\n  proof-\n    have b_semialg: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE[of m A cent a b] by blast \n  obtain b' where b'_def: \"b' \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (b' x) = val (b x) + 1)\"\n    using b_semialg SA_Suc_fun by blast\n  obtain A0 where A0_def: \"A0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). b x \\<noteq> \\<zero>} \\<inter> A\"\n    by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    unfolding A0_def apply(rule intersection_is_semialg)\n    using b_semialg SA_nonzero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m A cent a b] by blast \n  obtain A1 where A1_def: \"A1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). b x = \\<zero>} \\<inter> A\"\n    by blast \n  have A1_semialg: \"is_semialgebraic m A1\"\n    unfolding A1_def apply(rule intersection_is_semialg)\n    using b_semialg SA_zero_set_is_semialg apply blast\n    using assms is_cell_conditionE[of m A cent a b] by blast \n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m A0 cent a b' left_closed_interval\"\n    by blast \n  obtain \\<C>3 where \\<C>3_def: \"\\<C>3 = Cond m A1 cent a b closed_interval\"\n    by blast \n  have \\<C>2_cell_cond: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def apply(rule is_cell_conditionI') \n    using A0_semialg apply blast\n    using assms is_cell_conditionE[of m A cent a b] apply  blast \n    using assms is_cell_conditionE[of m A cent a b] apply  blast \n    using b'_def apply blast \n    by (simp add: is_convex_condition_def)\n  have \\<C>3_cell_cond: \"is_cell_condition \\<C>3\"\n    unfolding \\<C>3_def apply(rule is_cell_conditionI') \n    using A1_semialg apply blast\n    using assms is_cell_conditionE[of m A cent a b] apply  blast \n    using assms is_cell_conditionE[of m A cent a b] apply  blast \n    using assms is_cell_conditionE[of m A cent a b] apply  blast \n    by (simp add: is_convex_condition_def)\n  have 0: \"condition_to_set \\<C> = condition_to_set \\<C>2 \\<union> condition_to_set \\<C>3\"\n  proof\n    show \"condition_to_set \\<C> \\<subseteq> condition_to_set \\<C>2 \\<union> condition_to_set \\<C>3\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using A unfolding assms using assms cell_condition_set_memE(1) by blast\n    have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n      using Qp_pow_ConsE(1) x_closed by blast\n    show \"x \\<in> condition_to_set \\<C>2 \\<union> condition_to_set \\<C>3\"\n    proof(cases \"b (tl x) = \\<zero>\")\n        case True\n        have \"tl x \\<in> A1\"\n          unfolding A1_def using tl_x_closed assms A condition_to_set_memE(1)[of \\<C> m A cent a b closed_interval x] True \n          by blast \n        then show ?thesis \n          using A unfolding assms \\<C>3_def condition_to_set.simps A1_def cell_def \n          by blast \n      next\n        case False\n        have F0: \"tl x \\<in> A0\"\n          unfolding A0_def using tl_x_closed assms A condition_to_set_memE(1)[of \\<C> m A cent a b closed_interval x] False \n          by blast   \n        have F1: \"val (b' (tl x)) =  val (b (tl x)) + 1\"\n          using b'_def tl_x_closed by blast \n        have F2: \"val (b (tl x)) \\<noteq> \\<infinity>\"\n        proof-\n          have \"b (tl x) \\<in> carrier (Q\\<^sub>p)\"\n            using tl_x_closed b_semialg function_ring_car_closed SA_car semialg_functions_memE(2) by metis \n        thus ?thesis \n          using F0  tl_x_closed b_semialg unfolding A0_def \n          by (metis (no_types, opaque_lifting) False eint_ord_code(3) val_ineq)\n        qed\n        have F3: \"left_closed_interval (val (a (tl x))) (val (b' (tl x))) = closed_interval (val (a (tl x))) (val (b (tl x))) \"\n          unfolding left_closed_interval_def closed_interval_def unfolding F1 \n          apply(rule equalityI')\n          unfolding mem_Collect_eq \n          using eSuc_ile_mono ileI1 apply blast\n          using F2 F0  \n          by (metis F1 add.commute add.left_commute basic_trans_rules(18) basic_trans_rules(21) basic_trans_rules(22) basic_trans_rules(24) closed_interval_as_left_closed_interval closed_interval_memI eSuc_ile_mono eSuc_infinity eSuc_mono eint_add_left_cancel ile_eSuc infinity_ne_i1 left_closed_interval_memE(2) notin_closed order_eq_iff plus_eint_simps(2) plus_eint_simps(3))\n        then show ?thesis \n          using F0 F1 A unfolding assms \\<C>2_def condition_to_set.simps A0_def cell_def \n          by blast \n      qed\n    qed\n    show \"condition_to_set \\<C>2 \\<union> condition_to_set \\<C>3 \\<subseteq> condition_to_set \\<C>\"\n    proof fix x assume a: \"x \\<in> condition_to_set \\<C>2 \\<union> condition_to_set \\<C>3\"\n      have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n        using a unfolding assms using assms cell_condition_set_memE(1) \n        by (metis Un_iff \\<C>2_def \\<C>3_def cell_memE(1) condition_to_set.simps)\n    have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n      using Qp_pow_ConsE(1) x_closed by blast\n    show \"x \\<in> condition_to_set \\<C>\"\n    proof(cases \"x \\<in> condition_to_set \\<C>2\")\n      case True\n        have F0: \"tl x \\<in> A0\"\n          unfolding A0_def using tl_x_closed assms True condition_to_set_memE(1)[of \\<C>2 m A0 cent a b closed_interval x]  \n          A0_def \\<C>2_cell_cond \\<C>2_def cell_condition_set_memE(2) \n          by (meson padic_fields.cell_condition_set_memE(2) padic_fields_axioms) \n        have F1: \"val (b' (tl x)) =  val (b (tl x)) + 1\"\n          using b'_def tl_x_closed by blast \n        have F2: \"val (b (tl x)) \\<noteq> \\<infinity>\"\n        proof-\n          have \"b (tl x) \\<in> carrier (Q\\<^sub>p)\"\n            using tl_x_closed b_semialg function_ring_car_closed SA_car semialg_functions_memE(2) by metis \n        thus ?thesis \n          using F0  tl_x_closed  unfolding val_def unfolding A0_def \n          by (metis (mono_tags, lifting) Int_iff eint.simps(2) mem_Collect_eq)\n        qed\n        have F3: \"left_closed_interval (val (a (tl x))) (val (b' (tl x))) = closed_interval (val (a (tl x))) (val (b (tl x))) \"\n          unfolding left_closed_interval_def closed_interval_def unfolding F1 \n          apply(rule equalityI')\n          unfolding mem_Collect_eq \n          using eSuc_ile_mono ileI1 apply blast\n          using F2 F0  \n          by (metis F1 add.commute add.left_commute basic_trans_rules(18) basic_trans_rules(21) basic_trans_rules(22) basic_trans_rules(24) closed_interval_as_left_closed_interval closed_interval_memI eSuc_ile_mono eSuc_infinity eSuc_mono eint_add_left_cancel ile_eSuc infinity_ne_i1 left_closed_interval_memE(2) notin_closed order_eq_iff plus_eint_simps(2) plus_eint_simps(3))\n        show ?thesis\n             using True \n             unfolding assms \\<C>2_def condition_to_set.simps A0_def cell_def mem_Collect_eq F3 by blast \n    next\n           case False\n           then show ?thesis\n             using a unfolding assms \\<C>3_def condition_to_set.simps cell_def A1_def by blast \n    qed\n    qed\n  qed\n  obtain C0 where C0_def: \"C0 = B1 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). b x = \\<zero>}\"\n    by blast \n  have C0_semialg: \"is_semialgebraic m C0\"\n    unfolding C0_def apply(rule intersection_is_semialg) \n    using B1_semialg apply blast\n    using b_semialg SA_zero_set_is_semialg by blast\n  obtain C1 where C1_def: \"C1 = B1 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). b x \\<noteq> \\<zero>}\"\n    by blast \n  have C1_semialg: \"is_semialgebraic m C1\"\n    unfolding C1_def apply(rule intersection_is_semialg) \n    using B1_semialg apply blast\n    using b_semialg  SA_nonzero_set_is_semialg by blast\n  obtain \\<C>4 where \\<C>4_def: \"\\<C>4 = Cond m C0 cent c d closed_interval\"\n    by blast \n  have 00: \"is_cell_condition \\<C>4\"\n    unfolding \\<C>4_def apply(rule change_of_fibres[of _  B1]) \n    using \\<C>1_cell_cond \\<C>1_def apply blast \n    by (simp add: C0_semialg)\n  obtain \\<C>5 where \\<C>5_def: \"\\<C>5 = Cond m C1 cent c d closed_interval\"\n    by blast \n  have 00: \"is_cell_condition \\<C>5\"\n    unfolding \\<C>5_def apply(rule change_of_fibres[of _  B1]) \n    using \\<C>1_cell_cond \\<C>1_def apply blast \n    by (simp add: C1_semialg)\n  have 01: \"B1 = C0 \\<union> C1\"\n    unfolding C0_def C1_def B1_def by blast \n  have 02: \"condition_to_set \\<C>1 = condition_to_set \\<C>4 \\<union> condition_to_set \\<C>5\"\n    unfolding \\<C>1_def \\<C>4_def \\<C>5_def 01\n    apply(rule union_fibres)\n    using \"00\" C0_semialg \\<C>5_def change_of_fibres apply blast\n    using \"00\" \\<C>5_def by blast\n  have 03: \"condition_to_set \\<C>4 \\<inter> condition_to_set \\<C>2 = {}\"\n    unfolding \\<C>4_def \\<C>2_def condition_to_set.simps cell_def C0_def A0_def by blast \n  have 04: \"condition_to_set \\<C>5 \\<inter> condition_to_set \\<C>3 = {}\"\n    unfolding \\<C>5_def \\<C>3_def condition_to_set.simps cell_def C1_def A1_def by blast \n  have 05: \"condition_to_set \\<C>1 - condition_to_set (Cond m A cent a b closed_interval) =\n  (condition_to_set \\<C>4 - condition_to_set \\<C>3) \\<union> (condition_to_set \\<C>5 - condition_to_set \\<C>2)\"\n    using 0 03 04  unfolding 02 assms by blast\n  have 06: \"is_c_decomposable m cent (condition_to_set \\<C>4 - condition_to_set \\<C>3)\"\n  proof-\n    obtain S0 where S0_def: \"S0 = C0 - A1\"\n      by blast \n    have S0_semialg: \"is_semialgebraic m S0\"\n      unfolding S0_def  by (simp add: A1_semialg C0_semialg diff_is_semialgebraic)\n    obtain S1 where S1_def: \"S1 = C0 \\<inter> A1\"\n      by blast \n    have S1_semialg: \"is_semialgebraic m S1\"\n      unfolding S1_def \n      by (simp add: A1_semialg C0_semialg intersection_is_semialg)\n    have  060: \"C0 = S0 \\<union> S1\"\n      unfolding S0_def S1_def by blast \n    have 061: \"condition_to_set \\<C>4 =\n            condition_to_set (Cond m S0 cent c d closed_interval) \\<union> condition_to_set (Cond m S1 cent c d closed_interval)\"\n      unfolding \\<C>4_def 060 apply(rule  union_fibres)  \n       apply(rule change_of_fibres[of _  C0]) \n      using \"00\" C0_semialg \\<C>5_def change_of_fibres apply blast\n       apply (simp add: S0_semialg)\n       apply(rule change_of_fibres[of _  C0]) \n      using \"00\" C0_semialg \\<C>5_def change_of_fibres apply blast\n      by (simp add: S1_semialg)\n    have 062: \"condition_to_set (Cond m S0 cent c d closed_interval) - condition_to_set \\<C>3 = \n                condition_to_set (Cond m S0 cent c d closed_interval)\"\n      unfolding \\<C>3_def condition_to_set.simps S0_def cell_def by blast \n    have 063: \"condition_to_set (Cond m S1 cent c d closed_interval) - condition_to_set \\<C>3 = condition_to_set (Cond m S1 cent c a left_closed_interval) \"\n      unfolding \\<C>3_def \n    proof\n      show \"condition_to_set (Cond m (S1) cent c d closed_interval) - condition_to_set (Cond m A1 cent a b closed_interval)\n    \\<subseteq> condition_to_set (Cond m (S1) cent c a left_closed_interval)\"\n      proof fix x assume A: \"x \\<in> condition_to_set (Cond m S1 cent c d closed_interval) - condition_to_set (Cond m A1 cent a b closed_interval)\"\n        have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n          using A condition_to_set_memE by (metis Diff_iff Qp_pow_ConsE(1) cell_memE(1) condition_to_set.simps)\n        have 0620:\"val (b (tl x)) = \\<infinity>\"\n          using tl_x_closed using A condition_to_set_memE unfolding S1_def A1_def condition_to_set.simps cell_def \n          by (metis (mono_tags, lifting) Diff_iff Int_iff local.val_zero mem_Collect_eq)\n        have 0621: \"val (d (tl x)) = \\<infinity>\"\n          using tl_x_closed using A condition_to_set_memE unfolding S1_def C0_def B1_def  condition_to_set.simps cell_def \n          by (metis (mono_tags, lifting) Diff_iff Int_iff local.val_zero mem_Collect_eq)  \n        show \"x \\<in> condition_to_set (Cond m S1 cent c a left_closed_interval)\"\n          unfolding condition_to_set.simps\n          apply(rule cell_memI) \n          using A unfolding condition_to_set.simps cell_def apply blast \n          using A unfolding condition_to_set.simps cell_def apply blast \n          using A apply(rule  DiffE) \n          unfolding condition_to_set.simps cell_def closed_interval_def mem_Collect_eq 0620 0621 S1_def\n          apply(rule left_closed_interval_memI) \n           apply blast\n        proof-  \n          assume A0: \" x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> C0 \\<inter> A1 \\<and> val (c (tl x)) \\<le> val (hd x \\<ominus> cent (tl x)) \\<and> val (hd  x \\<ominus> cent (tl x)) \\<le> \\<infinity>\"\n          assume A1: \"   \\<not> (x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<and> tl x \\<in> A1 \\<and> val (a (tl x)) \\<le> val (hd x \\<ominus> cent (tl x)) \\<and> val (hd x \\<ominus> cent (tl x)) \\<le> \\<infinity>) \"\n          have \" \\<not> val (a (tl x)) \\<le> val (hd x \\<ominus> cent (tl x))\"\n            using A0 A1 by blast \n          thus \" val (hd x \\<ominus> cent (tl x)) < val (a (tl x)) \"\n          using not_le[of \"val (a (tl x))\" \"val (hd x \\<ominus> cent (tl x))\"] by blast \n        qed\n      qed\n      show \"condition_to_set (Cond m S1 cent c a left_closed_interval)\n    \\<subseteq> condition_to_set (Cond m S1 cent c d closed_interval) - condition_to_set (Cond m A1 cent a b closed_interval)\"\n      proof fix x assume A: \"  x \\<in> condition_to_set (Cond m S1 cent c a left_closed_interval)\"\n        show  \"x \\<in> condition_to_set (Cond m S1 cent c d closed_interval) - condition_to_set (Cond m A1 cent a b closed_interval)\"\n        proof\n        have tl_x_closed: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n          using A condition_to_set_memE by (metis Qp_pow_ConsE(1) cell_memE(1) condition_to_set.simps)\n        have 0620:\"val (b (tl x)) = \\<infinity>\"\n          using tl_x_closed using A condition_to_set_memE unfolding S1_def A1_def condition_to_set.simps cell_def \n          by (metis (mono_tags, lifting) Int_iff local.val_zero mem_Collect_eq)\n        have 0621: \"val (d (tl x)) = \\<infinity>\"\n          using tl_x_closed using A condition_to_set_memE unfolding S1_def C0_def B1_def  condition_to_set.simps cell_def \n          by (metis (mono_tags, lifting) Int_iff local.val_zero mem_Collect_eq)  \n        show \"x \\<in> condition_to_set (Cond m S1 cent c d closed_interval)\"\n          unfolding condition_to_set.simps\n          apply(rule cell_memI)\n          using A unfolding condition_to_set.simps cell_def apply blast \n          using A unfolding condition_to_set.simps cell_def apply blast \n          unfolding closed_interval_def \n          using A unfolding condition_to_set.simps cell_def mem_Collect_eq left_closed_interval_def  0621 \n          using eint_ord_code(3) by blast\n        show \"x \\<notin> condition_to_set (Cond m A1 cent a b closed_interval)\"\n          using A condition_to_set_memE(2)[of \"Cond m S1 cent c a left_closed_interval\" m S1 cent c a left_closed_interval x] \n          unfolding condition_to_set.simps cell_def closed_interval_def mem_Collect_eq left_closed_interval_def \n          using notin_closed by blast\n        qed\n      qed\n    qed\n    have 064: \"condition_to_set \\<C>4 - condition_to_set \\<C>3 = (condition_to_set (Cond m S0 cent c d closed_interval) - condition_to_set \\<C>3) \n            \\<union>(condition_to_set (Cond m S1 cent c d closed_interval) - condition_to_set \\<C>3)\"\n      unfolding 061 by blast \n    have 065: \"condition_to_set \\<C>4 - condition_to_set \\<C>3 =  condition_to_set (Cond m S0 cent c d closed_interval) \n            \\<union>condition_to_set (Cond m S1 cent c a left_closed_interval)\"\n      unfolding 064 063 062 by blast \n    show ?thesis \n      unfolding 065 apply(rule c_decomposable_disjoint_union)\n        apply(rule c_cell_is_c_decomposable) \n          apply(rule change_of_fibres[of _ B]) using assms apply blast \n          using S0_semialg apply blast \n        apply(rule c_cell_is_c_decomposable) \n           apply(rule is_cell_conditionI') \n          using S1_semialg apply blast\n          using assms  is_cell_conditionE apply blast \n          using assms  is_cell_conditionE apply blast \n          using assms  is_cell_conditionE apply blast \n          unfolding is_convex_condition_def apply blast \n          unfolding condition_to_set.simps cell_def S0_def S1_def by blast \n  qed\n  have 07: \"is_c_decomposable m cent (condition_to_set \\<C>5 - condition_to_set \\<C>2)\"\n    apply(rule closed_interval_minus_left_closed_interval_cell_diff[of  _ _ C1 _ c d _ A0 a b' \"C1 \\<union> A0\" ]) \n    unfolding \\<C>5_def \\<C>2_def apply blast apply blast apply blast apply blast\n    using \"00\" \\<C>5_def apply blast\n    using \\<C>2_cell_cond \\<C>2_def by blast\n  have 08: \"(condition_to_set \\<C>4 - condition_to_set \\<C>3) \\<inter> (condition_to_set \\<C>5 - condition_to_set \\<C>2) = {}\"\n    unfolding condition_to_set.simps \\<C>4_def \\<C>5_def cell_def C0_def C1_def by blast \n  show \" is_c_decomposable m cent (condition_to_set \\<C>1 - condition_to_set (Cond m A cent a b closed_interval))\"\n    unfolding 05 apply(rule c_decomposable_disjoint_union)\n    using 06 apply blast \n    using 07 apply blast \n    using 08 by blast \n  show \"(condition_to_set (Cond m B0 cent c d' left_closed_interval) - condition_to_set (Cond m A cent a b closed_interval)) \\<inter>\n    (condition_to_set \\<C>1 - condition_to_set (Cond m A cent a b closed_interval)) =\n    {}\"\n    unfolding condition_to_set.simps \\<C>1_def  B0_def B1_def cell_def  by blast \n  qed\nqed\n\ndefinition constant_fun_glue where\n\"constant_fun_glue m A f c = fun_glue m A f (Qp_const m c)\"\n\nlemma constant_fun_glue_closed:\n  assumes \"is_semialgebraic m A\"\n  assumes \"f \\<in> carrier (SA m)\"\n  assumes \"c \\<in> carrier Q\\<^sub>p\"\n  shows  \"constant_fun_glue m A f c \\<in> carrier (SA m)\"\nproof- \n  have 0: \"Qp_const m c \\<in> carrier (SA m)\"\n    using assms SA_car constant_function_in_semialg_functions by blast\n  show ?thesis unfolding constant_fun_glue_def \n    apply(rule fun_glue_closed)\n    using assms apply blast \n    using assms \"0\" apply linarith\n    using assms by blast \nqed\n\nlemma constant_fun_glue_formula1:\n  assumes \"is_semialgebraic m A\"\n  assumes \"f \\<in> carrier (SA m)\"\n  assumes \"c \\<in> carrier Q\\<^sub>p\"\n  assumes \"x \\<in> A\"\n  shows  \"constant_fun_glue m A f c x = f x\"\n  unfolding constant_fun_glue_def\n  apply(rule fun_glueE) \n  using assms apply blast \n  using assms SA_car constant_function_in_semialg_functions apply blast\n  using assms is_semialgebraic_closed apply blast\n  using assms by blast \n\nlemma constant_fun_glue_formula2:\n  assumes \"is_semialgebraic m A\"\n  assumes \"f \\<in> carrier (SA m)\"\n  assumes \"c \\<in> carrier Q\\<^sub>p\"\n  assumes \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n  assumes \"x \\<notin> A\"\n  shows  \"constant_fun_glue m A f c x = c\"\nproof-\n  have 0: \"constant_fun_glue m A f c x = (Qp_const m c) x\"\n  unfolding constant_fun_glue_def\n  using  fun_glueE'[of f m \"(Qp_const m c)\" A x]  assms  SA_car constant_function_in_semialg_functions  is_semialgebraic_closed \n  by blast \n  show ?thesis unfolding 0 constant_function_def using assms \n    by (metis constant_functionE constant_function_def) \nqed\n\nlemma SA_less_fun:\n  assumes \"f \\<in> carrier (SA m)\"\n  shows \"\\<exists>g \\<in> carrier (SA m). (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (f x))\"\nproof-\n  obtain A where A_def: \"A = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). f x \\<noteq> \\<zero>}\"\n    by blast \n  obtain g where g_def: \"g = fun_glue m A (\\<pp>[^](-1::int) \\<odot>\\<^bsub>SA m\\<^esub>f) (Qp_const m \\<one>)\"\n    by blast \n  have g_closed: \"g \\<in> carrier (SA m)\"\n    unfolding g_def apply(rule fun_glue_closed) \n    using assms SA_smult_closed p_intpow_closed(1) apply blast\n    using SA_car constant_function_in_semialg_functions apply blast\n    unfolding A_def using assms SA_nonzero_set_is_semialg by blast\n  have 1: \" \\<pp> [^] (-1::int) \\<in> carrier Q\\<^sub>p\"\n    using  p_intpow_closed(1)[of \"(-1::int)\"]  by blast\n  have 0: \" \\<pp> [^] (-1::int) \\<odot>\\<^bsub>SA m\\<^esub> f \\<in> carrier (SA m)\"\n    using 1 SA_smult_closed[of f m \"\\<pp>[^](-1::int)\" ]  assms by blast \n  have 2: \"\\<And>x. x \\<in> A \\<Longrightarrow> g x = \\<pp>[^](-1::int) \\<otimes> (f x)\"\n  proof- fix x assume A: \"x \\<in> A\" \n    have 2: \"(\\<pp> [^] (-1::int) \\<odot>\\<^bsub>SA m\\<^esub> f) x = \\<pp> [^] (-1::int) \\<otimes> f x\"\n      apply(rule SA_smult_formula[of f m \"\\<pp>[^](-1::int)\" x])\n      using assms apply blast using 1 apply blast  using A unfolding A_def by blast  \n    have 3: \"constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<one> \\<in> carrier (SA m)\"\n      using  constant_function_in_semialg_functions[of \\<one> m] Qp.cring_simprules(6) SA_car by blast\n    show \"g x = \\<pp>[^](-1::int) \\<otimes> (f x)\"\n    using A 0 1  3 assms \n          fun_glueE[of \"\\<pp>[^](-1::int) \\<odot>\\<^bsub>SA m\\<^esub>f\" m \"constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<one>\" A x] \n    unfolding g_def A_def 2 by blast \n  qed\n  have 3: \"val (\\<pp>[^](-1::int)) = eint (-1)\"\n  using val_p_int_pow by blast\n  have 4: \"\\<And>x. x \\<in> A \\<Longrightarrow> val (f x) \\<noteq> \\<infinity>\"\n    using assms unfolding A_def mem_Collect_eq val_def  \n    using eint.distinct(1) by presburger\n  hence 5: \"\\<And>x. x \\<in> A \\<Longrightarrow> val( g x) = (eint (-1)) + val (f x)\"\n  proof- fix x assume A: \"x \\<in> A\"\n    have \"f x \\<in> carrier Q\\<^sub>p\"\n      using A assms unfolding A_def mem_Collect_eq  \n      using function_ring_car_closed SA_car_memE(2) by blast\n    thus \"val( g x) = (eint (-1)) + val (f x)\"\n      using A val_mult[of \"\\<pp>[^](-1::int)\" ] assms 3 4 unfolding A_def   \n      using \"1\" \"2\" A by presburger\n  qed\n  hence 6: \"\\<And>x. x \\<in> A \\<Longrightarrow> val( g x) <  val (f x)\"\n  proof- fix x assume  A: \"x \\<in> A\"\n    then have 60: \"val (g x) = (eint (-1)) + val (f x)\" using 5 by blast \n    obtain m where m_def: \"val (f x) = eint m \"\n      using A 4 by (meson eint2_cases)\n    show \"val (g x) < val (f x)\"\n      unfolding 60 m_def using 4 eint_ord_code(2) plus_eint_simps(1) by presburger   \n  qed\n  have \"\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (f x)\"\n  proof fix x assume A: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    show \"val (g x) < val (f x)\"\n    proof(cases \"x \\<in> A\")\n      case True \n      then show ?thesis using 6 by blast  \n    next\n      case False\n      then have 00: \"val (f x) = \\<infinity>\"\n        using A unfolding A_def \n        by (metis (mono_tags, lifting) local.val_zero mem_Collect_eq)\n      have 01: \"g x = \\<one> \"\n        using SA_nonzero_set_is_semialg SA_smult_closed[of f m \"\\<pp>[^](-1::int)\" ] assms A False constant_fun_glue_formula2[of m A \"\\<pp> [^] (-1::int) \\<odot>\\<^bsub>SA m\\<^esub> f\" \\<one>  x] 0 Qp.one_closed\n        unfolding constant_fun_glue_def g_def A_def by blast \n      show ?thesis unfolding 00 01 val_one\n        by simp\n    qed\n  qed\n  then show ?thesis using g_closed by blast \nqed\n\nlemma closed_interval_minus_closed_ray_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C>' - condition_to_set \\<C>)\"\nproof-\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (a x))\"\n    using SA_less_fun assms is_cell_conditionE by metis   \n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d closed_interval\" \n    by blast \n  have 0: \"condition_to_set \\<C>' \\<inter>  condition_to_set \\<C> =  condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    apply(rule equalityI)\n  proof\n    show \" \\<And>x. x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    proof fix x assume A: \" x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      have 0: \"val (a (tl x)) \\<le> val (hd x \\<ominus>  (cent (tl x)))\"\n        apply(rule closed_interval_memE[of _ _ \"val (b (tl x))\"])\n        using A condition_to_set.simps[of m A cent a b closed_interval] cell_memE(3)[of x m A cent a b closed_interval] assms \n        unfolding assms  by blast \n      have 1: \"val (hd x \\<ominus>  (cent (tl x))) \\<le> val (d (tl x))\"\n        apply(rule closed_ray_memE[of _ \"val (c (tl x))\" \"val (d (tl x))\" ])\n        using A condition_to_set.simps[of m A cent c d closed_ray] cell_memE(3)[of x m B cent c d closed_ray] assms \n        unfolding  condition_to_set.simps assms  by blast \n      show \"x \\<in> condition_to_set \\<C>'\"\n        using A by blast \n      have 2: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using A unfolding assms condition_to_set.simps cell_def \n        using cartesian_power_tail by blast\n      have 3: \"val (g (tl x)) < val (a (tl x))\"\n        using 2 g_def by blast\n      show \" x \\<in> condition_to_set \\<C>1 \"\n        unfolding \\<C>1_def condition_to_set.simps\n        apply(rule cell_memI) using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(1))\n        using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(2))\n        apply(rule closed_interval_memI)\n        using 0 3 less_le_trans unfolding le_less  assms condition_to_set.simps \n        using \"0\" apply blast\n        using 1 unfolding le_less by blast \n    qed\n    show \"condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      unfolding \\<C>1_def assms(2) condition_to_set.simps cell_def closed_interval_def closed_ray_def by blast \n  qed\n  then have 1: \"condition_to_set \\<C>' - condition_to_set \\<C> = condition_to_set \\<C>' - condition_to_set \\<C>1\"\n    by blast \n  show ?thesis unfolding 1 \\<C>1_def unfolding assms  \n    apply(rule closed_interval_minus_closed_interval_cell_diff[of _ _ B _ g d _ A a b \"B \\<union> A\" ]) \n         apply blast apply blast apply blast apply blast \n     apply(rule is_cell_conditionI') \n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast \n    using assms is_cell_conditionE apply meson\n    unfolding is_convex_condition_def apply blast \n    using assms unfolding assms by blast \nqed\n\nlemma closed_interval_minus_open_ray_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C>' - condition_to_set \\<C>)\"\nproof-\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (a x))\"\n    using SA_less_fun assms is_cell_conditionE by metis   \n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d left_closed_interval\" \n    by blast \n  have 0: \"condition_to_set \\<C>' \\<inter>  condition_to_set \\<C> =  condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    apply(rule equalityI)\n  proof\n    show \" \\<And>x. x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    proof fix x assume A: \" x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      have 0: \"val (a (tl x)) \\<le> val (hd x \\<ominus>  (cent (tl x)))\"\n        apply(rule closed_interval_memE[of _ _ \"val (b (tl x))\"])\n        using A condition_to_set.simps[of m A cent a b closed_interval] cell_memE(3)[of x m A cent a b closed_interval] assms \n        unfolding assms  by blast \n      have 1: \"val (hd x \\<ominus>  (cent (tl x))) < val (d (tl x))\"\n        apply(rule open_ray_memE[of _ \"val (c (tl x))\" \"val (d (tl x))\" ])\n        using A condition_to_set.simps[of m A cent c d open_ray] cell_memE(3)[of x m B cent c d open_ray] assms \n        unfolding  condition_to_set.simps assms  by blast \n      show \"x \\<in> condition_to_set \\<C>'\"\n        using A by blast \n      have 2: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using A unfolding assms condition_to_set.simps cell_def \n        using cartesian_power_tail by blast\n      have 3: \"val (g (tl x)) < val (a (tl x))\"\n        using 2 g_def by blast\n      show \" x \\<in> condition_to_set \\<C>1 \"\n        unfolding \\<C>1_def condition_to_set.simps\n        apply(rule cell_memI) using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(1))\n        using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(2))\n        apply(rule left_closed_interval_memI)\n        using 0 3 less_le_trans unfolding le_less  assms condition_to_set.simps \n        using \"0\" apply blast\n        using 1 unfolding le_less by blast \n    qed\n    show \"condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      unfolding \\<C>1_def assms(2) condition_to_set.simps cell_def left_closed_interval_def open_ray_def by blast \n  qed\n  then have 1: \"condition_to_set \\<C>' - condition_to_set \\<C> = condition_to_set \\<C>' - condition_to_set \\<C>1\"\n    by blast \n  show ?thesis unfolding 1 \\<C>1_def unfolding assms  \n    apply(rule closed_interval_minus_left_closed_interval_cell_diff[of _ _ A _ a b _ B g d \"B \\<union> A\" ]) \n         apply blast apply blast apply blast apply blast \n    using assms apply blast \n     apply(rule is_cell_conditionI') \n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast \n    using assms is_cell_conditionE apply meson\n    unfolding is_convex_condition_def by blast \nqed\n\nlemma left_closed_interval_minus_closed_ray_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C>' - condition_to_set \\<C>)\"\nproof-\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (a x))\"\n    using SA_less_fun assms is_cell_conditionE by metis   \n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d closed_interval\" \n    by blast \n  have 0: \"condition_to_set \\<C>' \\<inter>  condition_to_set \\<C> =  condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    apply(rule equalityI)\n  proof\n    show \" \\<And>x. x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    proof fix x assume A: \" x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      have 0: \"val (a (tl x)) \\<le> val (hd x \\<ominus>  (cent (tl x)))\"\n        apply(rule left_closed_interval_memE[of _ _ \"val (b (tl x))\"])\n        using A condition_to_set.simps[of m A cent a b left_closed_interval] cell_memE(3)[of x m A cent a b left_closed_interval] assms \n        unfolding assms  by blast \n      have 1: \"val (hd x \\<ominus>  (cent (tl x))) \\<le> val (d (tl x))\"\n        apply(rule closed_ray_memE[of _ \"val (c (tl x))\" \"val (d (tl x))\" ])\n        using A condition_to_set.simps[of m A cent c d closed_ray] cell_memE(3)[of x m B cent c d closed_ray] assms \n        unfolding  condition_to_set.simps assms  by blast \n      show \"x \\<in> condition_to_set \\<C>'\"\n        using A by blast \n      have 2: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using A unfolding assms condition_to_set.simps cell_def \n        using cartesian_power_tail by blast\n      have 3: \"val (g (tl x)) < val (a (tl x))\"\n        using 2 g_def by blast\n      show \" x \\<in> condition_to_set \\<C>1 \"\n        unfolding \\<C>1_def condition_to_set.simps\n        apply(rule cell_memI) using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(1))\n        using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(2))\n        apply(rule closed_interval_memI)\n        using 0 3 less_le_trans unfolding le_less  assms condition_to_set.simps \n        using \"0\" apply blast\n        using 1 unfolding le_less by blast \n    qed\n    show \"condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      unfolding \\<C>1_def assms(2) condition_to_set.simps cell_def closed_interval_def closed_ray_def by blast \n  qed\n  then have 1: \"condition_to_set \\<C>' - condition_to_set \\<C> = condition_to_set \\<C>' - condition_to_set \\<C>1\"\n    by blast \n  show ?thesis unfolding 1 \\<C>1_def unfolding assms  \n    apply(rule left_closed_interval_minus_closed_interval_cell_diff[of _ _ A _ a b _ B g d \"B \\<union> A\" ]) \n         apply blast apply blast apply blast apply blast \n    using assms apply blast \n     apply(rule is_cell_conditionI') \n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast \n    using assms is_cell_conditionE apply meson\n    unfolding is_convex_condition_def by blast \nqed\n\nlemma left_closed_interval_minus_open_ray_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C>' - condition_to_set \\<C>)\"\nproof-\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (a x))\"\n    using SA_less_fun assms is_cell_conditionE by metis   \n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d left_closed_interval\" \n    by blast \n  have 0: \"condition_to_set \\<C>' \\<inter>  condition_to_set \\<C> =  condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    apply(rule equalityI)\n  proof\n    show \" \\<And>x. x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1\"\n    proof fix x assume A: \" x \\<in> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      have 0: \"val (a (tl x)) \\<le> val (hd x \\<ominus>  (cent (tl x)))\"\n        apply(rule left_closed_interval_memE[of _ _ \"val (b (tl x))\"])\n        using A condition_to_set.simps[of m A cent a b left_closed_interval] cell_memE(3)[of x m A cent a b left_closed_interval] assms \n        unfolding assms  by blast \n      have 1: \"val (hd x \\<ominus>  (cent (tl x))) < val (d (tl x))\"\n        apply(rule open_ray_memE[of _ \"val (c (tl x))\" \"val (d (tl x))\" ])\n        using A condition_to_set.simps[of m A cent c d open_ray] cell_memE(3)[of x m B cent c d open_ray] assms \n        unfolding  condition_to_set.simps assms  by blast \n      show \"x \\<in> condition_to_set \\<C>'\"\n        using A by blast \n      have 2: \"tl x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n        using A unfolding assms condition_to_set.simps cell_def \n        using cartesian_power_tail by blast\n      have 3: \"val (g (tl x)) < val (a (tl x))\"\n        using 2 g_def by blast\n      show \" x \\<in> condition_to_set \\<C>1 \"\n        unfolding \\<C>1_def condition_to_set.simps\n        apply(rule cell_memI) using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(1))\n        using A unfolding assms condition_to_set.simps \n        apply (meson Int_iff cell_memE(2))\n        apply(rule left_closed_interval_memI)\n        using 0 3 less_le_trans unfolding le_less  assms condition_to_set.simps \n        using \"0\" apply blast\n        using 1 unfolding le_less by blast \n    qed\n    show \"condition_to_set \\<C>' \\<inter> condition_to_set \\<C>1 \\<subseteq> condition_to_set \\<C>' \\<inter> condition_to_set \\<C>\"\n      unfolding \\<C>1_def assms(2) condition_to_set.simps cell_def left_closed_interval_def open_ray_def by blast \n  qed\n  then have 1: \"condition_to_set \\<C>' - condition_to_set \\<C> = condition_to_set \\<C>' - condition_to_set \\<C>1\"\n    by blast \n  show ?thesis unfolding 1 \\<C>1_def unfolding assms  \n    apply(rule left_closed_interval_minus_left_closed_interval_cell_diff[of _ _ A _ a b _ B g d \"B \\<union> A\" ]) \n         apply blast apply blast apply blast apply blast \n    using assms apply blast \n     apply(rule is_cell_conditionI') \n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast \n    using assms is_cell_conditionE apply meson\n    unfolding is_convex_condition_def by blast \nqed\n\nlemma closed_interval_minus_convex_condition_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b I\"\n  assumes \"\\<C> = Cond m B cent c d closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n  apply(cases \"I = closed_interval\")\n  using assms closed_interval_minus_closed_interval_cell_diff apply blast\n  apply(cases \"I = left_closed_interval\")\n  using assms closed_interval_minus_left_closed_interval_cell_diff apply blast\n  apply(cases \"I = closed_ray\")\n  using assms closed_interval_minus_closed_ray_cell_diff apply blast\n  using assms closed_interval_minus_open_ray_cell_diff is_cell_conditionE(5)[of m A cent a b I] \n  unfolding is_convex_condition_def  by blast  \n\nlemma left_closed_interval_minus_convex_condition_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b I\"\n  assumes \"\\<C> = Cond m B cent c d left_closed_interval\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n  apply(cases \"I = closed_interval\")\n  using assms left_closed_interval_minus_closed_interval_cell_diff apply blast\n  apply(cases \"I = left_closed_interval\")\n  using assms left_closed_interval_minus_left_closed_interval_cell_diff apply blast\n  apply(cases \"I = closed_ray\")\n  using assms left_closed_interval_minus_closed_ray_cell_diff apply blast\n  using assms left_closed_interval_minus_open_ray_cell_diff is_cell_conditionE(5)[of m A cent a b I] \n  unfolding is_convex_condition_def  by blast  \n\nlemma open_ray_minus_closed_interval_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain h where h_def: \"h \\<in> carrier (SA m) \\<and>(\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (h x) = min (val (a x)) (val (d x)))\"\n    using assms is_cell_conditionE by (metis (mono_tags, opaque_lifting) SA_min_fun)\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (h x))\"\n    using h_def  by (metis SA_less_fun)\n  have g_le1: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (a (tl x))\"\n    using h_def g_def  min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  have g_le2: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (d (tl x))\"\n    using h_def g_def min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d left_closed_interval\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using assms is_cell_conditionE apply meson \n    unfolding is_convex_condition_def by blast \n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m B cent g g open_ray\"\n    by blast \n  have 1: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using g_def apply blast\n    unfolding is_convex_condition_def by blast \n  have 2: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    apply(rule equalityI) \n  proof\n    show \"\\<And>x. x \\<in> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    proof\n      fix x assume A: \"x \\<in> condition_to_set \\<C>\" \"x \\<notin> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>1\" unfolding \\<C>1_def condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        apply(rule left_closed_interval_memI)\n        using A unfolding \\<C>2_def left_closed_interval_def assms condition_to_set.simps cell_def mem_Collect_eq \n         apply (metis (no_types, lifting) \"0\" Qp.cring_simprules(4) Qp_pow_ConsE(1) Qp_pow_ConsE(2) \\<C>1_def assms(1) assms(2) assms(5) assms(6) g_def is_cell_condition_closure'(1) is_cell_condition_closure'(2) notin_closed open_ray_memI ultrametric_equal_eq ultrametric_equal_eq' val_ultrametric_noteq'')\n        using A unfolding \\<C>2_def left_closed_interval_def open_ray_def assms condition_to_set.simps cell_def mem_Collect_eq \n        by blast \n    qed\n    show \"condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2 \\<subseteq> condition_to_set \\<C>\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>\"\n        unfolding assms condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        apply(rule open_ray_memI) \n        apply(cases \"x \\<in> condition_to_set \\<C>1\")\n        using A unfolding open_ray_def left_closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n      proof- \n        assume A0: \"x \\<notin> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> B \\<and> val (hd as \\<ominus> cent (tl as)) \\<in> {a. val (g (tl as)) \\<le> a \\<and> a < val (d (tl as))}}\"\n        then have A1: \"x \\<in> condition_to_set \\<C>2\"\n          using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def left_closed_interval_def by blast \n        show \"val (hd x \\<ominus> cent (tl x)) < val (d (tl x))\"\n        using A1 g_le2[of x] less_trans unfolding mem_Collect_eq open_ray_def left_closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def\n        by blast\n      qed\n    qed\n  qed\n  have 3: \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' = {}\"\n  proof\n    show \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' \\<subseteq> {}\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      have 30: \"val (hd x \\<ominus> cent (tl x)) \\<ge> val (a (tl x))\"\n        using A cell_memE(3) unfolding assms condition_to_set.simps \n        by (meson Int_iff closed_interval_memE)\n      have 31: \"val (hd x \\<ominus> cent (tl x)) < val (g (tl x))\"\n        using A cell_memE(3) unfolding \\<C>2_def condition_to_set.simps \n        by (meson Int_iff open_ray_memE)      \n      show \"x \\<in> {}\"\n        using 30 31 g_le1[of x] A\n        unfolding assms condition_to_set.simps cell_def \\<C>2_def mem_Collect_eq \n                  open_ray_def closed_interval_def Int_iff by auto \n    qed\n    show \"{} \\<subseteq> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      by blast \n  qed\n  have 4: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>2 \\<union> (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using 3 2 by blast \n  have 5: \"is_c_decomposable m cent (condition_to_set \\<C>2)\"\n    using 1 unfolding \\<C>2_def using c_cell_is_c_decomposable by blast\n  have 6: \"is_c_decomposable m cent (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using left_closed_interval_minus_closed_interval_cell_diff \\<C>1_def assms  \"0\" by blast\n  have 7: \"(condition_to_set \\<C>2) \\<inter> (condition_to_set \\<C>1 - condition_to_set \\<C>') = {}\"\n    apply(rule equalityI')\n    unfolding \\<C>2_def \\<C>1_def condition_to_set.simps \n    using cell_memE(3)  open_ray_memE left_closed_interval_memE\n     apply (metis Diff_iff Int_iff basic_trans_rules(17) basic_trans_rules(20))\n    by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 4 using 7 6 5 \n    by (simp add: c_decomposable_disjoint_union)\nqed\n\nlemma closed_ray_minus_closed_interval_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain h where h_def: \"h \\<in> carrier (SA m) \\<and>(\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (h x) = min (val (a x)) (val (d x)))\"\n    using assms is_cell_conditionE by (metis (mono_tags, opaque_lifting) SA_min_fun)\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (h x))\"\n    using h_def  by (metis SA_less_fun)\n  have g_le1: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (a (tl x))\"\n    using h_def g_def  min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  have g_le2: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (d (tl x))\"\n    using h_def g_def min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d closed_interval\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using assms is_cell_conditionE apply meson \n    unfolding is_convex_condition_def by blast \n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m B cent g g open_ray\"\n    by blast \n  have 1: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using g_def apply blast\n    unfolding is_convex_condition_def by blast \n  have 2: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    apply(rule equalityI) \n  proof\n    show \"\\<And>x. x \\<in> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    proof\n      fix x assume A: \"x \\<in> condition_to_set \\<C>\" \"x \\<notin> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>1\" unfolding \\<C>1_def condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        apply(rule closed_interval_memI)\n        using A unfolding \\<C>2_def closed_interval_def assms condition_to_set.simps cell_def mem_Collect_eq \n         apply (metis (no_types, lifting) \"0\" Qp.cring_simprules(4) Qp_pow_ConsE(1) Qp_pow_ConsE(2) \\<C>1_def assms(1) assms(2) assms(5) assms(6) g_def is_cell_condition_closure'(1) is_cell_condition_closure'(2) notin_closed open_ray_memI ultrametric_equal_eq ultrametric_equal_eq' val_ultrametric_noteq'')\n        using A unfolding \\<C>2_def closed_ray_def left_closed_interval_def open_ray_def assms condition_to_set.simps cell_def mem_Collect_eq \n        by blast \n    qed\n    show \"condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2 \\<subseteq> condition_to_set \\<C>\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>\"\n        unfolding assms condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        apply(rule closed_ray_memI) \n        apply(cases \"x \\<in> condition_to_set \\<C>1\")\n        using A unfolding open_ray_def closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n      proof- \n        assume A0: \"x \\<notin> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> B \\<and> val (hd as \\<ominus> cent (tl as)) \\<in> {a. val (g (tl as)) \\<le> a \\<and> a \\<le> val (d (tl as))}}\"\n        then have A1: \"x \\<in> condition_to_set \\<C>2\"\n          using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def open_ray_def closed_interval_def by blast \n        show \"val (hd x \\<ominus> cent (tl x)) \\<le> val (d (tl x))\"\n          using A1 g_le2[of x] less_trans unfolding mem_Collect_eq open_ray_def left_closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def        \n          by (metis (no_types, opaque_lifting) basic_trans_rules(20) g_le2 notin_closed)        \n      qed\n    qed\n  qed\n  have 3: \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' = {}\"\n  proof\n    show \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' \\<subseteq> {}\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      have 30: \"val (hd x \\<ominus> cent (tl x)) \\<ge> val (a (tl x))\"\n        using A cell_memE(3) unfolding assms condition_to_set.simps \n        by (meson Int_iff closed_interval_memE)\n      have 31: \"val (hd x \\<ominus> cent (tl x)) < val (g (tl x))\"\n        using A cell_memE(3) unfolding \\<C>2_def condition_to_set.simps \n        by (meson Int_iff open_ray_memE)      \n      show \"x \\<in> {}\"\n        using 30 31 g_le1[of x] A unfolding assms condition_to_set.simps cell_def \n              \\<C>2_def open_ray_def closed_interval_def Int_iff mem_Collect_eq by auto           \n    qed\n    show \"{} \\<subseteq> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      by blast \n  qed\n  have 4: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>2 \\<union> (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using 3 2 by blast \n  have 5: \"is_c_decomposable m cent (condition_to_set \\<C>2)\"\n    using 1 unfolding \\<C>2_def using c_cell_is_c_decomposable by blast\n  have 6: \"is_c_decomposable m cent (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using closed_interval_minus_closed_interval_cell_diff \\<C>1_def assms  \"0\" by blast\n  have 7: \"(condition_to_set \\<C>2) \\<inter> (condition_to_set \\<C>1 - condition_to_set \\<C>') = {}\"\n    apply(rule equalityI')\n    unfolding \\<C>2_def \\<C>1_def condition_to_set.simps \n    using cell_memE(3)  open_ray_memE closed_interval_memE\n     apply (metis Diff_iff Int_iff basic_trans_rules(17) basic_trans_rules(20))\n    by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 4 using 7 6 5 \n    by (simp add: c_decomposable_disjoint_union)\nqed\n\nlemma open_ray_minus_left_closed_interval_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain h where h_def: \"h \\<in> carrier (SA m) \\<and>(\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (h x) = min (val (a x)) (val (d x)))\"\n    using assms is_cell_conditionE by (metis (mono_tags, opaque_lifting) SA_min_fun)\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (h x))\"\n    using h_def  by (metis SA_less_fun)\n  have g_le1: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (a (tl x))\"\n    using h_def g_def  min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  have g_le2: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (d (tl x))\"\n    using h_def g_def min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d left_closed_interval\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using assms is_cell_conditionE apply meson \n    unfolding is_convex_condition_def by blast \n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m B cent g g open_ray\"\n    by blast \n  have 1: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using g_def apply blast\n    unfolding is_convex_condition_def by blast \n  have 2: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    apply(rule equalityI) \n  proof\n    show \"\\<And>x. x \\<in> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    proof\n      fix x assume A: \"x \\<in> condition_to_set \\<C>\" \"x \\<notin> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>1\" unfolding \\<C>1_def condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        apply(rule left_closed_interval_memI)\n        using A unfolding \\<C>2_def left_closed_interval_def assms condition_to_set.simps cell_def mem_Collect_eq \n         apply (metis (no_types, lifting) \"0\" Qp.cring_simprules(4) Qp_pow_ConsE(1) Qp_pow_ConsE(2) \\<C>1_def assms(1) assms(2) assms(5) assms(6) g_def is_cell_condition_closure'(1) is_cell_condition_closure'(2) notin_closed open_ray_memI ultrametric_equal_eq ultrametric_equal_eq' val_ultrametric_noteq'')\n        using A unfolding \\<C>2_def left_closed_interval_def open_ray_def assms condition_to_set.simps cell_def mem_Collect_eq \n        by blast \n    qed\n    show \"condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2 \\<subseteq> condition_to_set \\<C>\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>\"\n        unfolding assms condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        apply(rule open_ray_memI) \n        apply(cases \"x \\<in> condition_to_set \\<C>1\")\n        using A unfolding open_ray_def left_closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n      proof- \n        assume A0: \"x \\<notin> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> B \\<and> val (hd as \\<ominus> cent (tl as)) \\<in> {a. val (g (tl as)) \\<le> a \\<and> a < val (d (tl as))}}\"\n        then have A1: \"x \\<in> condition_to_set \\<C>2\"\n          using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def left_closed_interval_def by blast \n        show \"val (hd x \\<ominus> cent (tl x)) < val (d (tl x))\"\n        using A1 g_le2[of x] less_trans unfolding mem_Collect_eq open_ray_def left_closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def\n        by blast\n      qed\n    qed\n  qed\n  have 3: \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' = {}\"\n  proof\n    show \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' \\<subseteq> {}\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      have 30: \"val (hd x \\<ominus> cent (tl x)) \\<ge> val (a (tl x))\"\n        using A cell_memE(3) unfolding assms condition_to_set.simps \n        by (meson Int_iff left_closed_interval_memE)\n      have 31: \"val (hd x \\<ominus> cent (tl x)) < val (g (tl x))\"\n        using A cell_memE(3) unfolding \\<C>2_def condition_to_set.simps \n        by (meson Int_iff open_ray_memE)      \n      show \"x \\<in> {}\"\n        using 30 31 g_le1[of x] A less_trans \n        unfolding assms condition_to_set.simps cell_def \\<C>2_def open_ray_def left_closed_interval_def\n                  mem_Collect_eq Int_iff Un_iff by auto \n    qed\n    show \"{} \\<subseteq> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      by blast \n  qed\n  have 4: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>2 \\<union> (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using 3 2 by blast \n  have 5: \"is_c_decomposable m cent (condition_to_set \\<C>2)\"\n    using 1 unfolding \\<C>2_def using c_cell_is_c_decomposable by blast\n  have 6: \"is_c_decomposable m cent (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using left_closed_interval_minus_left_closed_interval_cell_diff \\<C>1_def assms  \"0\" by blast\n  have 7: \"(condition_to_set \\<C>2) \\<inter> (condition_to_set \\<C>1 - condition_to_set \\<C>') = {}\"\n    apply(rule equalityI')\n    unfolding \\<C>2_def \\<C>1_def condition_to_set.simps \n    using cell_memE(3)  open_ray_memE left_closed_interval_memE\n     apply (metis Diff_iff Int_iff basic_trans_rules(17) basic_trans_rules(20))\n    by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 4 using 7 6 5 \n    by (simp add: c_decomposable_disjoint_union)\nqed\n\nlemma closed_ray_minus_left_closed_interval_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b left_closed_interval\"\n  assumes \"\\<C> = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain h where h_def: \"h \\<in> carrier (SA m) \\<and>(\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (h x) = min (val (a x)) (val (d x)))\"\n    using assms is_cell_conditionE by (metis (mono_tags, opaque_lifting) SA_min_fun)\n  obtain g where g_def: \"g \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (g x) < val (h x))\"\n    using h_def  by (metis SA_less_fun)\n  have g_le1: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (a (tl x))\"\n    using h_def g_def  min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  have g_le2: \"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow> val (g (tl x)) < val (d (tl x))\"\n    using h_def g_def min.strict_boundedE by (metis Qp_pow_ConsE(1))\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m B cent g d closed_interval\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using assms is_cell_conditionE apply meson \n    unfolding is_convex_condition_def by blast \n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m B cent g g open_ray\"\n    by blast \n  have 1: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def apply(rule is_cell_conditionI')\n    using assms is_cell_conditionE apply blast \n    using assms is_cell_conditionE apply blast \n    using g_def apply blast\n    using g_def apply blast\n    unfolding is_convex_condition_def by blast \n  have 2: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    apply(rule equalityI) \n  proof\n    show \"\\<And>x. x \\<in> condition_to_set \\<C> \\<Longrightarrow> x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    proof\n      fix x assume A: \"x \\<in> condition_to_set \\<C>\" \"x \\<notin> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>1\" unfolding \\<C>1_def condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        using A unfolding assms condition_to_set.simps cell_def apply blast \n        apply(rule closed_interval_memI)\n        using A unfolding \\<C>2_def closed_interval_def assms condition_to_set.simps cell_def mem_Collect_eq \n         apply (metis (no_types, lifting) \"0\" Qp.cring_simprules(4) Qp_pow_ConsE(1) Qp_pow_ConsE(2) \\<C>1_def assms(1) assms(2) assms(5) assms(6) g_def is_cell_condition_closure'(1) is_cell_condition_closure'(2) notin_closed open_ray_memI ultrametric_equal_eq ultrametric_equal_eq' val_ultrametric_noteq'')\n        using A unfolding \\<C>2_def closed_ray_def left_closed_interval_def open_ray_def assms condition_to_set.simps cell_def mem_Collect_eq \n        by blast \n    qed\n    show \"condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2 \\<subseteq> condition_to_set \\<C>\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n      show \"x \\<in> condition_to_set \\<C>\"\n        unfolding assms condition_to_set.simps \n        apply(rule cell_memI) \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n        apply(rule closed_ray_memI) \n        apply(cases \"x \\<in> condition_to_set \\<C>1\")\n        using A unfolding open_ray_def closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def apply blast \n      proof- \n        assume A0: \"x \\<notin> {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> B \\<and> val (hd as \\<ominus> cent (tl as)) \\<in> {a. val (g (tl as)) \\<le> a \\<and> a \\<le> val (d (tl as))}}\"\n        then have A1: \"x \\<in> condition_to_set \\<C>2\"\n          using A unfolding \\<C>1_def \\<C>2_def condition_to_set.simps cell_def open_ray_def closed_interval_def by blast \n        show \"val (hd x \\<ominus> cent (tl x)) \\<le> val (d (tl x))\"\n          using A1 g_le2[of x] less_trans unfolding mem_Collect_eq open_ray_def left_closed_interval_def  \\<C>1_def \\<C>2_def condition_to_set.simps cell_def        \n          by (metis (no_types, opaque_lifting) basic_trans_rules(20) g_le2 notin_closed)        \n      qed\n    qed\n  qed\n  have 3: \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' = {}\"\n  proof\n    show \"condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>' \\<subseteq> {}\"\n    proof fix x assume A: \"x \\<in> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      have 30: \"val (hd x \\<ominus> cent (tl x)) \\<ge> val (a (tl x))\"\n        using A cell_memE(3) unfolding assms condition_to_set.simps \n        by (meson Int_iff left_closed_interval_memE)\n      have 31: \"val (hd x \\<ominus> cent (tl x)) < val (g (tl x))\"\n        using A cell_memE(3) unfolding \\<C>2_def condition_to_set.simps \n        by (meson Int_iff open_ray_memE)      \n      show \"x \\<in> {}\"\n        using 30 31 g_le1[of x ] A le_less_trans[of \"val (a (tl x)) \" \"val (hd x \\<ominus> cent (tl x))\"  \" val (g (tl x))\"] unfolding assms condition_to_set.simps cell_def   \n        by (metis (mono_tags, lifting) A Int_iff assms(1) basic_trans_rules(20) cell_memE(1) condition_to_set.simps)\n    qed\n    show \"{} \\<subseteq> condition_to_set \\<C>2 \\<inter> condition_to_set \\<C>'\"\n      by blast \n  qed\n  have 4: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>2 \\<union> (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using 3 2 by blast \n  have 5: \"is_c_decomposable m cent (condition_to_set \\<C>2)\"\n    using 1 unfolding \\<C>2_def using c_cell_is_c_decomposable by blast\n  have 6: \"is_c_decomposable m cent (condition_to_set \\<C>1 - condition_to_set \\<C>')\"\n    using closed_interval_minus_left_closed_interval_cell_diff \\<C>1_def assms  \"0\" by blast\n  have 7: \"(condition_to_set \\<C>2) \\<inter> (condition_to_set \\<C>1 - condition_to_set \\<C>') = {}\"\n    apply(rule equalityI')\n    unfolding \\<C>2_def \\<C>1_def condition_to_set.simps \n    using cell_memE(3)  open_ray_memE closed_interval_memE\n     apply (metis Diff_iff Int_iff basic_trans_rules(17) basic_trans_rules(20))\n    by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 4 using 7 6 5 \n    by (simp add: c_decomposable_disjoint_union)\nqed\n\nlemma open_ray_minus_closed_ray_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b open_ray\"\n  assumes \"\\<C>' = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain A0 where A0_def: \"A0 = A - B\"\n    by blast \n  obtain A1 where A1_def: \"A1 = A \\<inter> B\"\n    by blast \n  have A_semialg: \"is_semialgebraic m A\"\n    using assms is_cell_conditionE by blast \n  have B_semialg: \"is_semialgebraic m B\"\n    using assms is_cell_conditionE by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    unfolding A0_def using A_semialg B_semialg diff_is_semialgebraic by blast\n  have A1_semialg: \"is_semialgebraic m A1\"\n    unfolding A1_def by (simp add: A_semialg B_semialg intersection_is_semialg)\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m A0 cent a b open_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def using assms A0_semialg change_of_fibres by blast\n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m A1 cent a b open_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def using assms A1_semialg change_of_fibres by blast\n  have 1: \"condition_to_set \\<C>1 \\<inter> condition_to_set \\<C>' = {}\"\n    unfolding \\<C>1_def assms A0_def by (metis Diff_disjoint disj_fibres_imp_disj_cells inf_commute)\n  have d_semialg: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson \n  have b_semialg: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson\n  obtain d' where d'_def: \"d' \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (d' x) = val (d x) + 1)\"\n    using d_semialg SA_Suc_fun by blast\n  obtain B0 where B0_def: \"B0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> B\"\n    by blast \n  obtain B1 where B1_def: \"B1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> B\"\n    by blast\n  have B0_closed: \"is_semialgebraic m B0\"\n    unfolding B0_def using assms is_cell_conditionE d_semialg SA_zero_set_is_semialg \n    by (meson intersection_is_semialg)\n  have B1_closed: \"is_semialgebraic m B1 \"\n    unfolding B1_def using assms is_cell_conditionE d_semialg nonzero_evimage_closed \n    by (meson intersection_is_semialg)\n  have B_closed: \"B \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    using assms is_cell_conditionE B_semialg is_semialgebraic_closed by presburger\n  obtain \\<C>3 where \\<C>3_def: \"\\<C>3 = Cond m B0 cent c d closed_ray\"\n    by blast \n  obtain \\<C>4 where \\<C>4_def: \"\\<C>4 = Cond m B1 cent c d closed_ray\"\n    by blast \n  have \\<C>3_is_cell: \"is_cell_condition \\<C>3\"\n    unfolding \\<C>3_def using assms B0_closed change_of_fibres by blast\n  have \\<C>4_is_cell: \"is_cell_condition \\<C>4\"\n    unfolding \\<C>4_def using assms B1_closed change_of_fibres by blast\n  have 2: \"B = B0 \\<union> B1\"\n    using assms is_cell_conditionE(1)[of m B cent c d closed_ray] B_closed \n    unfolding B0_def B1_def assms  by blast\n  have 3: \"B0 \\<inter> B1 = {}\"\n    unfolding B0_def B1_def by blast \n  have 4: \"condition_to_set \\<C>' = condition_to_set \\<C>3 \\<union> condition_to_set \\<C>4\"\n    unfolding assms \\<C>4_def \\<C>3_def 2 using  union_fibres \\<C>3_def \\<C>3_is_cell \\<C>4_def \\<C>4_is_cell by blast\n  have 5: \"condition_to_set \\<C>3 \\<inter> condition_to_set \\<C>4 = {}\"\n    unfolding assms \\<C>4_def \\<C>3_def 2 using 3 disjoint_fibres \\<C>3_def \\<C>3_is_cell \\<C>4_def \\<C>4_is_cell by blast\n  have 6: \"A = A0 \\<union> A1\"\n    unfolding A0_def A1_def by blast \n  have 7: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    unfolding assms \\<C>1_def \\<C>2_def 6 using union_fibres A0_semialg A1_semialg assms(1) assms(5) change_of_fibres \n    by blast\n  have 8: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>1 \\<union> (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n    unfolding 7 using 1 by blast \n  obtain D0 where D0_def: \"D0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> A1\"\n    by blast \n  have D0_semialg: \"is_semialgebraic m D0\"\n    unfolding D0_def by (metis (no_types, lifting) A1_def A_semialg B0_closed B0_def Int_ac(4) intersection_is_semialg)\n  obtain D1 where D1_def: \"D1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> A1\"\n    by blast \n  have D1_semialg: \"is_semialgebraic m D1\"\n    unfolding D1_def \n    apply(intro intersection_is_semialg A1_semialg)\n    using d_semialg nonzero_evimage_closed  by auto \n  obtain \\<C>20 where \\<C>20_def: \"\\<C>20 = Cond m D0 cent a b open_ray\"\n    by blast \n  obtain \\<C>21 where \\<C>21_def: \"\\<C>21 = Cond m D1 cent a b open_ray\"\n    by blast \n  have 9: \"is_cell_condition \\<C>20 \"\n    unfolding \\<C>20_def using assms D0_semialg change_of_fibres by blast\n  have 10: \"is_cell_condition \\<C>21 \"\n    unfolding \\<C>21_def using assms D1_semialg change_of_fibres by blast\n  have 11: \"A1 = D0 \\<union> D1\"\n    unfolding D0_def D1_def A1_def using assms 2 B0_def B1_def by blast\n  have 12: \"condition_to_set \\<C>2 = condition_to_set \\<C>20 \\<union> condition_to_set \\<C>21\"\n    unfolding \\<C>20_def \\<C>21_def \\<C>2_def 11 using union_fibres \"10\" \"9\" \\<C>20_def \\<C>21_def by blast\n  have 13: \"condition_to_set \\<C>20 \\<inter> condition_to_set \\<C>4 = {}\"\n    unfolding \\<C>20_def \\<C>4_def B1_def D0_def condition_to_set.simps cell_def mem_Collect_eq by blast \n  have 14: \"condition_to_set \\<C>21 \\<inter> condition_to_set \\<C>3 = {}\"\n    unfolding \\<C>21_def \\<C>3_def B0_def D1_def condition_to_set.simps cell_def mem_Collect_eq by blast \n  have 15: \"D0 \\<inter> D1 = {}\"\n    unfolding D0_def D1_def by blast \n  have 16: \"condition_to_set \\<C>20 \\<inter> condition_to_set \\<C>21 = {}\"\n    unfolding \\<C>20_def \\<C>21_def using 15 disjoint_fibres \n    by (meson disj_fibres_imp_disj_cells)\n  have 17: \"condition_to_set \\<C>2 - condition_to_set \\<C>'\n    = (condition_to_set \\<C>20 - condition_to_set \\<C>3) \\<union> (condition_to_set \\<C>21 - condition_to_set \\<C>4)\"\n    unfolding 12 4 using 13 14 16  by blast \n  have 18: \"is_c_decomposable m cent (condition_to_set \\<C>20 - condition_to_set \\<C>3)\" \n  proof- \n    obtain E0 where E0_def: \"E0 = D0 \\<inter> B0\"\n      by blast \n    obtain E1 where E1_def: \"E1 = D0 - B0\"\n      by blast \n    have E0_semialg: \"is_semialgebraic m E0\"\n      unfolding E0_def by (simp add: B0_closed D0_semialg intersection_is_semialg)\n    have E1_semialg: \"is_semialgebraic m E1\"\n      unfolding E1_def by (simp add: B0_closed D0_semialg diff_is_semialgebraic)\n    obtain \\<C>200 where \\<C>200_def: \"\\<C>200 = Cond m E0 cent a b open_ray\"\n      by blast \n    have 180: \"is_cell_condition \\<C>200\"\n      unfolding \\<C>200_def using assms \n      by (metis (no_types, lifting) \"9\" E0_def \\<C>20_def \\<C>3_def \\<C>3_is_cell intersection_is_semialg is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) padic_fields.is_cell_conditionE(1) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    obtain \\<C>201 where \\<C>201_def: \"\\<C>201 = Cond m E1 cent a b open_ray\"\n      by blast \n    have 181: \"is_cell_condition \\<C>201\"\n      unfolding \\<C>201_def using assms \n      by (metis (no_types, lifting) \"9\" E1_def \\<C>20_def \\<C>3_def \\<C>3_is_cell is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) padic_fields.diff_is_semialgebraic padic_fields.is_cell_conditionE(1) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    have 182: \"D0 = E0 \\<union> E1\"\n      unfolding E1_def E0_def by blast \n    have 183: \"E0 \\<inter> E1 = {}\"\n      unfolding E1_def E0_def by blast \n    have 184: \"condition_to_set \\<C>20 = condition_to_set \\<C>200 \\<union> condition_to_set \\<C>201\"\n      unfolding \\<C>20_def \\<C>200_def \\<C>201_def 182 \n      using \"180\" E1_semialg \\<C>200_def change_of_fibres union_fibres by blast\n    have 185: \"condition_to_set \\<C>201 \\<inter> condition_to_set \\<C>3 = {}\"\n      unfolding \\<C>3_def \\<C>201_def E1_def condition_to_set.simps cell_def mem_Collect_eq by blast \n    have 186: \"condition_to_set \\<C>200 - condition_to_set \\<C>3 = {}\"\n    proof\n      show \"condition_to_set \\<C>200 - condition_to_set \\<C>3 \\<subseteq> {}\"\n      proof fix x assume A: \"x \\<in> condition_to_set \\<C>200 - condition_to_set \\<C>3\"\n        then have 1860: \"val (d (tl x)) = \\<infinity>\"\n          unfolding condition_to_set.simps \\<C>200_def \\<C>3_def cell_def E0_def B0_def Diff_iff mem_Collect_eq \n          using val_zero by (metis (mono_tags, lifting) Int_iff mem_Collect_eq)\n        have 1861: \"val (hd x \\<ominus> cent (tl x)) \\<in> open_ray (val (a (tl x))) (val (b (tl x))) - closed_ray (val (c (tl x))) (val (d (tl x)))\"\n          using A unfolding \\<C>200_def \\<C>3_def E0_def B0_def condition_to_set.simps cell_def \n          by blast \n        then show \"x \\<in> {}\"\n          using  open_ray_minus_closed_ray'[of \"val (d (tl x))\" \"open_ray (val (a (tl x))) (val (b (tl x)))\" \"val (a (tl x))\" \"val (b (tl x))\" \"closed_ray (val (c (tl x))) (val (d (tl x)))\" \"val (c (tl x))\"]\n                 1860 by blast \n      qed\n      show \"{} \\<subseteq> condition_to_set \\<C>200 - condition_to_set \\<C>3\"\n        by blast \n    qed\n    have 187: \"condition_to_set \\<C>20 - condition_to_set \\<C>3 = condition_to_set \\<C>201 \"\n      unfolding 184 using 186 185 by blast \n    show \"is_c_decomposable m cent (condition_to_set \\<C>20 - condition_to_set \\<C>3)\"\n      using 181 unfolding 187 \\<C>201_def  \n      using c_cell_is_c_decomposable by blast\n  qed\n  have 19: \"is_c_decomposable m cent (condition_to_set \\<C>21 - condition_to_set \\<C>4)\"\n  proof-\n    obtain E0 where E0_def: \"E0 = D1 \\<inter> B1\"\n      by blast \n    obtain E1 where E1_def: \"E1 = D1 - B1\"\n      by blast \n    have E0_semialg: \"is_semialgebraic m E0\"\n      unfolding E0_def by (simp add: B1_closed D1_semialg intersection_is_semialg)\n    have E1_semialg: \"is_semialgebraic m E1\"\n      unfolding E1_def by (simp add: B1_closed D1_semialg diff_is_semialgebraic)\n    obtain \\<C>200 where \\<C>200_def: \"\\<C>200 = Cond m E0 cent a b open_ray\"\n      by blast \n    have 180: \"is_cell_condition \\<C>200\"\n      unfolding \\<C>200_def using assms \n      by (metis (no_types, lifting) \"10\" E0_def \\<C>21_def \\<C>4_def \\<C>4_is_cell intersection_is_semialg \n          is_cell_conditionE(1) is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) \n          is_cell_conditionE(5) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    obtain \\<C>201 where \\<C>201_def: \"\\<C>201 = Cond m E1 cent a b open_ray\"\n      by blast \n    have 181: \"is_cell_condition \\<C>201\"\n      unfolding \\<C>201_def using assms \n      by (metis (no_types, lifting) \"10\" E1_def \\<C>21_def \\<C>4_def \\<C>4_is_cell is_cell_conditionE(1)\n          is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) \n          padic_fields.diff_is_semialgebraic padic_fields.is_cell_conditionI' padic_fields_axioms)\n    have 182: \"D1 = E0 \\<union> E1\"\n      unfolding E1_def E0_def by blast \n    have 183: \"E0 \\<inter> E1 = {}\"\n      unfolding E1_def E0_def by blast \n    have 184: \"condition_to_set \\<C>21 = condition_to_set \\<C>200 \\<union> condition_to_set \\<C>201\"\n      unfolding \\<C>21_def \\<C>200_def \\<C>201_def 182 \n      using \"180\" E1_semialg \\<C>201_def change_of_fibres union_fibres \\<C>200_def by blast      \n    have 185: \"condition_to_set \\<C>201 \\<inter> condition_to_set \\<C>4 = {}\"\n      unfolding \\<C>4_def \\<C>201_def E1_def D1_def condition_to_set.simps cell_def mem_Collect_eq \n      using A1_def B0_def D1_def by blast      \n    have 186: \"condition_to_set \\<C>200 - condition_to_set \\<C>4 = condition_to_set (Cond m E0 cent d' b left_closed_interval)\"\n    proof\n      show \"condition_to_set \\<C>200 - condition_to_set \\<C>4 \\<subseteq> condition_to_set (Cond m E0 cent d' b left_closed_interval)\"\n      proof fix x assume A: \"x \\<in> condition_to_set \\<C>200 - condition_to_set \\<C>4\"\n        then have 1860: \"val (d (tl x)) \\<noteq> \\<infinity>\"\n          unfolding D1_def condition_to_set.simps \\<C>200_def \\<C>4_def cell_def E0_def B0_def Diff_iff mem_Collect_eq Int_iff \n          using A1_def D1_def \n          by (metis (no_types, opaque_lifting) closed_ray_memI eint_ord_code(3))            \n        have 1861: \"val (hd x \\<ominus> cent (tl x)) \\<in> open_ray (val (a (tl x))) (val (b (tl x))) - closed_ray (val (c (tl x))) (val (d (tl x)))\"\n          using A unfolding \\<C>200_def \\<C>4_def D1_def E0_def  condition_to_set.simps cell_def \n          by blast\n        have 1862: \"val (d' (tl x)) = val (d (tl x)) + 1\"\n          using d'_def A unfolding \\<C>200_def condition_to_set.simps cell_def \n          using B0_def D1_def E0_def by blast\n        show \"x \\<in> condition_to_set (Cond m E0 cent d' b left_closed_interval)\"\n          unfolding condition_to_set.simps \n          apply(rule cell_memI) \n          using A unfolding condition_to_set.simps \\<C>200_def cell_def apply blast \n          using A unfolding condition_to_set.simps \\<C>200_def cell_def apply blast \n          using  open_ray_minus_closed_ray[of \"val (d (tl x))\" \"open_ray (val (a (tl x))) (val (b (tl x)))\" \"val (a (tl x))\" \"val (b (tl x))\" \"closed_ray (val (c (tl x))) (val (d (tl x)))\" \"val (c (tl x))\"]\n                 1860 1861 unfolding 1862 by blast \n      qed\n      show \"condition_to_set (Cond m E0 cent d' b left_closed_interval) \\<subseteq> condition_to_set \\<C>200 - condition_to_set \\<C>4\"\n      proof fix x assume A: \"x \\<in> condition_to_set (Cond m E0 cent d' b left_closed_interval)\"\n        show \"x \\<in> condition_to_set \\<C>200 - condition_to_set \\<C>4\"\n        proof \n          show \"x \\<in> condition_to_set \\<C>200\"\n            unfolding condition_to_set.simps \\<C>200_def apply(rule  cell_memI)\n            using A unfolding condition_to_set.simps cell_def apply blast \n            using A unfolding condition_to_set.simps cell_def apply blast \n            apply(rule open_ray_memI)\n            using A cell_memE(3)[of x] left_closed_interval_memE\n            unfolding condition_to_set.simps by blast \n          show \"x \\<notin> condition_to_set \\<C>4\"\n          proof- \n            have 00: \"val (hd x \\<ominus> cent (tl x)) \\<ge>  val (d' (tl x))\"\n              using A cell_memE(3)[of x] left_closed_interval_memE\n              unfolding condition_to_set.simps by blast \n            have 01: \"val (d (tl x)) \\<noteq>  \\<infinity>\"\n              using A unfolding val_def condition_to_set.simps cell_def E0_def D1_def mem_Collect_eq Int_iff \n              using eint.distinct(1) by presburger \n            have 02: \"val (d' (tl x)) = val (d (tl x)) + 1\"\n              using d'_def A unfolding condition_to_set.simps cell_def \n              using Qp_pow_ConsE(1) by blast\n            have 03:  \"val (d' (tl x)) > val (d (tl x))\"\n            proof- obtain m where m_def: \"val (d (tl x)) = eint m \"\n                using 01 by blast\n              show ?thesis  using 01 02 unfolding m_def\n               using eint_ord_simps(1) iless_Suc_eq by presburger\n            qed\n            then have \"\\<not> (val (hd x \\<ominus> cent (tl x)) \\<le> val (d (tl x)))\"\n              using 00 less_le_trans by blast\n            thus \"x \\<notin> condition_to_set \\<C>4\"\n              using A \n              unfolding E0_def \\<C>4_def condition_to_set.simps cell_def closed_ray_def mem_Collect_eq\n              by blast \n          qed\n        qed\n      qed\n    qed\n    have 187: \"condition_to_set \\<C>21 - condition_to_set \\<C>4 = condition_to_set \\<C>201 \\<union> condition_to_set (Cond m E0 cent d' b left_closed_interval) \"\n      unfolding 184 using 186 185 by blast \n    show \"is_c_decomposable m cent (condition_to_set \\<C>21 - condition_to_set \\<C>4)\"\n      unfolding 187 \n      apply(rule c_decomposable_disjoint_union)\n      using \"181\" \\<C>201_def c_cell_is_c_decomposable apply blast\n       apply(rule c_cell_is_c_decomposable)\n       apply(rule is_cell_conditionI')\n      using E0_semialg apply blast\n      using assms is_cell_conditionE apply blast \n      using d'_def apply blast \n      using assms is_cell_conditionE apply meson \n      using is_convex_condition_def apply blast\n      apply(rule equalityI')\n      unfolding E1_def E0_def  \\<C>201_def condition_to_set.simps cell_def  Int_iff mem_Collect_eq apply blast \n      by blast      \n  qed\n  have 20:  \"is_c_decomposable m cent (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n    unfolding 17 \n      apply(rule c_decomposable_disjoint_union)\n    using 18 apply blast \n    using 19 apply blast \n    using 16 by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 8 \n      apply(rule c_decomposable_disjoint_union)\n    using 1 unfolding \\<C>1_def \n      apply (metis (no_types, lifting) A0_semialg assms(1) assms(5) c_cell_is_c_decomposable is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    using 20 apply blast \n    unfolding \\<C>2_def A0_def A1_def condition_to_set.simps  cell_def \n    by blast \nqed\n\nlemma closed_ray_minus_closed_ray_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b closed_ray\"\n  assumes \"\\<C>' = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain A0 where A0_def: \"A0 = A - B\"\n    by blast \n  obtain A1 where A1_def: \"A1 = A \\<inter> B\"\n    by blast \n  have A_semialg: \"is_semialgebraic m A\"\n    using assms is_cell_conditionE by blast \n  have B_semialg: \"is_semialgebraic m B\"\n    using assms is_cell_conditionE by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    unfolding A0_def using A_semialg B_semialg diff_is_semialgebraic by blast\n  have A1_semialg: \"is_semialgebraic m A1\"\n    unfolding A1_def by (simp add: A_semialg B_semialg intersection_is_semialg)\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m A0 cent a b closed_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def using assms A0_semialg change_of_fibres by blast\n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m A1 cent a b closed_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def using assms A1_semialg change_of_fibres by blast\n  have 1: \"condition_to_set \\<C>1 \\<inter> condition_to_set \\<C>' = {}\"\n    unfolding \\<C>1_def assms A0_def by (metis Diff_disjoint disj_fibres_imp_disj_cells inf_commute)\n  have d_semialg: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson \n  have b_semialg: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson\n  obtain d' where d'_def: \"d' \\<in> carrier (SA m) \\<and> (\\<forall>x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (d' x) = val (d x) + 1)\"\n    using d_semialg SA_Suc_fun by blast\n  obtain B0 where B0_def: \"B0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> B\"\n    by blast \n  obtain B1 where B1_def: \"B1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> B\"\n    by blast\n  have B0_closed: \"is_semialgebraic m B0\"\n    unfolding B0_def using assms is_cell_conditionE d_semialg SA_zero_set_is_semialg \n    by (meson intersection_is_semialg)\n  have B1_closed: \"is_semialgebraic m B1 \"\n    unfolding B1_def using assms is_cell_conditionE d_semialg nonzero_evimage_closed \n    by (meson intersection_is_semialg)\n  have B_closed: \"B \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    using assms is_cell_conditionE B_semialg is_semialgebraic_closed by presburger\n  obtain \\<C>3 where \\<C>3_def: \"\\<C>3 = Cond m B0 cent c d closed_ray\"\n    by blast \n  obtain \\<C>4 where \\<C>4_def: \"\\<C>4 = Cond m B1 cent c d closed_ray\"\n    by blast \n  have \\<C>3_is_cell: \"is_cell_condition \\<C>3\"\n    unfolding \\<C>3_def using assms B0_closed change_of_fibres by blast\n  have \\<C>4_is_cell: \"is_cell_condition \\<C>4\"\n    unfolding \\<C>4_def using assms B1_closed change_of_fibres by blast\n  have 2: \"B = B0 \\<union> B1\"\n    using assms is_cell_conditionE(1)[of m B cent c d closed_ray] B_closed \n    unfolding B0_def B1_def assms  by blast\n  have 3: \"B0 \\<inter> B1 = {}\"\n    unfolding B0_def B1_def by blast \n  have 4: \"condition_to_set \\<C>' = condition_to_set \\<C>3 \\<union> condition_to_set \\<C>4\"\n    unfolding assms \\<C>4_def \\<C>3_def 2 using  union_fibres \\<C>3_def \\<C>3_is_cell \\<C>4_def \\<C>4_is_cell by blast\n  have 5: \"condition_to_set \\<C>3 \\<inter> condition_to_set \\<C>4 = {}\"\n    unfolding assms \\<C>4_def \\<C>3_def 2 using 3 disjoint_fibres \\<C>3_def \\<C>3_is_cell \\<C>4_def \\<C>4_is_cell by blast\n  have 6: \"A = A0 \\<union> A1\"\n    unfolding A0_def A1_def by blast \n  have 7: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    unfolding assms \\<C>1_def \\<C>2_def 6 using union_fibres A0_semialg A1_semialg assms(1) assms(5) change_of_fibres \n    by blast\n  have 8: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>1 \\<union> (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n    unfolding 7 using 1 by blast \n  obtain D0 where D0_def: \"D0 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x = \\<zero>} \\<inter> A1\"\n    by blast \n  have D0_semialg: \"is_semialgebraic m D0\"\n    unfolding D0_def by (metis (no_types, lifting) A1_def A_semialg B0_closed B0_def Int_ac(4) intersection_is_semialg)\n  obtain D1 where D1_def: \"D1 = {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). d x \\<noteq> \\<zero>} \\<inter> A1\"\n    by blast \n  have D1_semialg: \"is_semialgebraic m D1\"\n    unfolding D1_def \n    by(intro intersection_is_semialg SA_nonzero_set_is_semialg d_semialg A1_semialg)\n  obtain \\<C>20 where \\<C>20_def: \"\\<C>20 = Cond m D0 cent a b closed_ray\"\n    by blast \n  obtain \\<C>21 where \\<C>21_def: \"\\<C>21 = Cond m D1 cent a b closed_ray\"\n    by blast \n  have 9: \"is_cell_condition \\<C>20 \"\n    unfolding \\<C>20_def using assms D0_semialg change_of_fibres by blast\n  have 10: \"is_cell_condition \\<C>21 \"\n    unfolding \\<C>21_def using assms D1_semialg change_of_fibres by blast\n  have 11: \"A1 = D0 \\<union> D1\"\n    unfolding D0_def D1_def A1_def using assms 2 B0_def B1_def by blast\n  have 12: \"condition_to_set \\<C>2 = condition_to_set \\<C>20 \\<union> condition_to_set \\<C>21\"\n    unfolding \\<C>20_def \\<C>21_def \\<C>2_def 11 using union_fibres \"10\" \"9\" \\<C>20_def \\<C>21_def by blast\n  have 13: \"condition_to_set \\<C>20 \\<inter> condition_to_set \\<C>4 = {}\"\n    unfolding \\<C>20_def \\<C>4_def B1_def D0_def condition_to_set.simps cell_def mem_Collect_eq by blast \n  have 14: \"condition_to_set \\<C>21 \\<inter> condition_to_set \\<C>3 = {}\"\n    unfolding \\<C>21_def \\<C>3_def B0_def D1_def condition_to_set.simps cell_def mem_Collect_eq by blast \n  have 15: \"D0 \\<inter> D1 = {}\"\n    unfolding D0_def D1_def by blast \n  have 16: \"condition_to_set \\<C>20 \\<inter> condition_to_set \\<C>21 = {}\"\n    unfolding \\<C>20_def \\<C>21_def using 15 disjoint_fibres \n    by (meson disj_fibres_imp_disj_cells)\n  have 17: \"condition_to_set \\<C>2 - condition_to_set \\<C>'\n    = (condition_to_set \\<C>20 - condition_to_set \\<C>3) \\<union> (condition_to_set \\<C>21 - condition_to_set \\<C>4)\"\n    unfolding 12 4 using 13 14 16  by blast \n  have 18: \"is_c_decomposable m cent (condition_to_set \\<C>20 - condition_to_set \\<C>3)\" \n  proof- \n    obtain E0 where E0_def: \"E0 = D0 \\<inter> B0\"\n      by blast \n    obtain E1 where E1_def: \"E1 = D0 - B0\"\n      by blast \n    have E0_semialg: \"is_semialgebraic m E0\"\n      unfolding E0_def by (simp add: B0_closed D0_semialg intersection_is_semialg)\n    have E1_semialg: \"is_semialgebraic m E1\"\n      unfolding E1_def by (simp add: B0_closed D0_semialg diff_is_semialgebraic)\n    obtain \\<C>200 where \\<C>200_def: \"\\<C>200 = Cond m E0 cent a b closed_ray\"\n      by blast \n    have 180: \"is_cell_condition \\<C>200\"\n      unfolding \\<C>200_def using assms \n      by (metis (no_types, lifting) \"9\" E0_def \\<C>20_def \\<C>3_def \\<C>3_is_cell intersection_is_semialg is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) padic_fields.is_cell_conditionE(1) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    obtain \\<C>201 where \\<C>201_def: \"\\<C>201 = Cond m E1 cent a b closed_ray\"\n      by blast \n    have 181: \"is_cell_condition \\<C>201\"\n      unfolding \\<C>201_def using assms \n      by (metis (no_types, lifting) \"9\" E1_def \\<C>20_def \\<C>3_def \\<C>3_is_cell is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) padic_fields.diff_is_semialgebraic padic_fields.is_cell_conditionE(1) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    have 182: \"D0 = E0 \\<union> E1\"\n      unfolding E1_def E0_def by blast \n    have 183: \"E0 \\<inter> E1 = {}\"\n      unfolding E1_def E0_def by blast \n    have 184: \"condition_to_set \\<C>20 = condition_to_set \\<C>200 \\<union> condition_to_set \\<C>201\"\n      unfolding \\<C>20_def \\<C>200_def \\<C>201_def 182 \n      using \"180\" E1_semialg \\<C>200_def change_of_fibres union_fibres by blast\n    have 185: \"condition_to_set \\<C>201 \\<inter> condition_to_set \\<C>3 = {}\"\n      unfolding \\<C>3_def \\<C>201_def E1_def condition_to_set.simps cell_def mem_Collect_eq by blast \n    have 186: \"condition_to_set \\<C>200 - condition_to_set \\<C>3 = {}\"\n    proof\n      show \"condition_to_set \\<C>200 - condition_to_set \\<C>3 \\<subseteq> {}\"\n      proof fix x assume A: \"x \\<in> condition_to_set \\<C>200 - condition_to_set \\<C>3\"\n        then have 1860: \"val (d (tl x)) = \\<infinity>\"\n          unfolding condition_to_set.simps \\<C>200_def \\<C>3_def cell_def E0_def B0_def Diff_iff mem_Collect_eq \n          using val_zero by (metis (mono_tags, lifting) Int_iff mem_Collect_eq)\n        have 1861: \"val (hd x \\<ominus> cent (tl x)) \\<in> closed_ray (val (a (tl x))) (val (b (tl x))) - closed_ray (val (c (tl x))) (val (d (tl x)))\"\n          using A unfolding \\<C>200_def \\<C>3_def E0_def B0_def condition_to_set.simps cell_def \n          by blast \n        then show \"x \\<in> {}\"\n          using  closed_ray_minus_closed_ray'[of \"val (d (tl x))\" \"closed_ray (val (a (tl x))) (val (b (tl x)))\" \"val (a (tl x))\" \"val (b (tl x))\" \"closed_ray (val (c (tl x))) (val (d (tl x)))\" \"val (c (tl x))\"]\n                 1860 by blast \n      qed\n      show \"{} \\<subseteq> condition_to_set \\<C>200 - condition_to_set \\<C>3\"\n        by blast \n    qed\n    have 187: \"condition_to_set \\<C>20 - condition_to_set \\<C>3 = condition_to_set \\<C>201 \"\n      unfolding 184 using 186 185 by blast \n    show \"is_c_decomposable m cent (condition_to_set \\<C>20 - condition_to_set \\<C>3)\"\n      using 181 unfolding 187 \\<C>201_def  \n      using c_cell_is_c_decomposable by blast\n  qed\n  have 19: \"is_c_decomposable m cent (condition_to_set \\<C>21 - condition_to_set \\<C>4)\"\n  proof-\n    obtain E0 where E0_def: \"E0 = D1 \\<inter> B1\"\n      by blast \n    obtain E1 where E1_def: \"E1 = D1 - B1\"\n      by blast \n    have E0_semialg: \"is_semialgebraic m E0\"\n      unfolding E0_def by (simp add: B1_closed D1_semialg intersection_is_semialg)\n    have E1_semialg: \"is_semialgebraic m E1\"\n      unfolding E1_def by (simp add: B1_closed D1_semialg diff_is_semialgebraic)\n    obtain \\<C>200 where \\<C>200_def: \"\\<C>200 = Cond m E0 cent a b closed_ray\"\n      by blast \n    have 180: \"is_cell_condition \\<C>200\"\n      unfolding \\<C>200_def using assms \n      by (metis (no_types, lifting) \"10\" E0_def \\<C>21_def \\<C>4_def \\<C>4_is_cell intersection_is_semialg \n          is_cell_conditionE(1) is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) \n          is_cell_conditionE(5) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    obtain \\<C>201 where \\<C>201_def: \"\\<C>201 = Cond m E1 cent a b closed_ray\"\n      by blast \n    have 181: \"is_cell_condition \\<C>201\"\n      unfolding \\<C>201_def using assms \n      by (metis (no_types, lifting) \"10\" E1_def \\<C>21_def \\<C>4_def \\<C>4_is_cell is_cell_conditionE(1)\n          is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) \n          padic_fields.diff_is_semialgebraic padic_fields.is_cell_conditionI' padic_fields_axioms)\n    have 182: \"D1 = E0 \\<union> E1\"\n      unfolding E1_def E0_def by blast \n    have 183: \"E0 \\<inter> E1 = {}\"\n      unfolding E1_def E0_def by blast \n    have 184: \"condition_to_set \\<C>21 = condition_to_set \\<C>200 \\<union> condition_to_set \\<C>201\"\n      unfolding \\<C>21_def \\<C>200_def \\<C>201_def 182 \n      using \"180\" E1_semialg \\<C>201_def change_of_fibres union_fibres \\<C>200_def by blast      \n    have 185: \"condition_to_set \\<C>201 \\<inter> condition_to_set \\<C>4 = {}\"\n      unfolding \\<C>4_def \\<C>201_def E1_def D1_def condition_to_set.simps cell_def mem_Collect_eq \n      using A1_def B0_def D1_def by blast      \n    have 186: \"condition_to_set \\<C>200 - condition_to_set \\<C>4 = condition_to_set (Cond m E0 cent d' b closed_interval)\"\n    proof\n      show \"condition_to_set \\<C>200 - condition_to_set \\<C>4 \\<subseteq> condition_to_set (Cond m E0 cent d' b closed_interval)\"\n      proof fix x assume A: \"x \\<in> condition_to_set \\<C>200 - condition_to_set \\<C>4\"\n        then have 1860: \"val (d (tl x)) \\<noteq> \\<infinity>\"\n          unfolding D1_def condition_to_set.simps \\<C>200_def \\<C>4_def cell_def E0_def B0_def Diff_iff mem_Collect_eq Int_iff \n          using A1_def D1_def \n          by (metis (no_types, opaque_lifting) closed_ray_memI eint_ord_code(3))            \n        have 1861: \"val (hd x \\<ominus> cent (tl x)) \\<in> closed_ray (val (a (tl x))) (val (b (tl x))) - closed_ray (val (c (tl x))) (val (d (tl x)))\"\n          using A unfolding \\<C>200_def \\<C>4_def D1_def E0_def  condition_to_set.simps cell_def \n          by blast\n        have 1862: \"val (d' (tl x)) = val (d (tl x)) + 1\"\n          using d'_def A unfolding \\<C>200_def condition_to_set.simps cell_def \n          using B0_def D1_def E0_def by blast\n        show \"x \\<in> condition_to_set (Cond m E0 cent d' b closed_interval)\"\n          unfolding condition_to_set.simps \n          apply(rule cell_memI) \n          using A unfolding condition_to_set.simps \\<C>200_def cell_def apply blast \n          using A unfolding condition_to_set.simps \\<C>200_def cell_def apply blast \n          using  closed_ray_minus_closed_ray[of \"val (d (tl x))\" \"closed_ray (val (a (tl x))) (val (b (tl x)))\" \"val (a (tl x))\" \"val (b (tl x))\" \"closed_ray (val (c (tl x))) (val (d (tl x)))\" \"val (c (tl x))\"]\n                 1860 1861 unfolding 1862 by blast \n      qed\n      show \"condition_to_set (Cond m E0 cent d' b closed_interval) \\<subseteq> condition_to_set \\<C>200 - condition_to_set \\<C>4\"\n      proof fix x assume A: \"x \\<in> condition_to_set (Cond m E0 cent d' b closed_interval)\"\n        show \"x \\<in> condition_to_set \\<C>200 - condition_to_set \\<C>4\"\n        proof \n          show \"x \\<in> condition_to_set \\<C>200\"\n            unfolding condition_to_set.simps \\<C>200_def apply(rule  cell_memI)\n            using A unfolding condition_to_set.simps cell_def apply blast \n            using A unfolding condition_to_set.simps cell_def apply blast \n            apply(rule closed_ray_memI)\n            using A cell_memE(3)[of x] closed_interval_memE\n            unfolding condition_to_set.simps by blast \n          show \"x \\<notin> condition_to_set \\<C>4\"\n          proof- \n            have 00: \"val (hd x \\<ominus> cent (tl x)) \\<ge>  val (d' (tl x))\"\n              using A cell_memE(3)[of x] closed_interval_memE\n              unfolding condition_to_set.simps by blast \n            have 01: \"val (d (tl x)) \\<noteq>  \\<infinity>\"\n              using A unfolding val_def condition_to_set.simps cell_def E0_def D1_def mem_Collect_eq Int_iff \n              using eint.distinct(1) by presburger \n            have 02: \"val (d' (tl x)) = val (d (tl x)) + 1\"\n              using d'_def A unfolding condition_to_set.simps cell_def \n              using Qp_pow_ConsE(1) by blast\n            have 03:  \"val (d' (tl x)) > val (d (tl x))\"\n            proof- obtain m where m_def: \"val (d (tl x)) = eint m \"\n                using 01 by blast\n              show ?thesis  using 01 02 unfolding m_def\n               using eint_ord_simps(1) iless_Suc_eq by presburger\n            qed\n            then have \"\\<not> (val (hd x \\<ominus> cent (tl x)) \\<le> val (d (tl x)))\"\n              using 00 less_le_trans by blast\n            thus \"x \\<notin> condition_to_set \\<C>4\"\n              using A \n              unfolding E0_def \\<C>4_def condition_to_set.simps cell_def closed_ray_def mem_Collect_eq\n              by blast \n          qed\n        qed\n      qed\n    qed\n    have 187: \"condition_to_set \\<C>21 - condition_to_set \\<C>4 = condition_to_set \\<C>201 \\<union> condition_to_set (Cond m E0 cent d' b closed_interval) \"\n      unfolding 184 using 186 185 by blast \n    show \"is_c_decomposable m cent (condition_to_set \\<C>21 - condition_to_set \\<C>4)\"\n      unfolding 187 \n      apply(rule c_decomposable_disjoint_union)\n      using \"181\" \\<C>201_def c_cell_is_c_decomposable apply blast\n       apply(rule c_cell_is_c_decomposable)\n       apply(rule is_cell_conditionI')\n      using E0_semialg apply blast\n      using assms is_cell_conditionE apply blast \n      using d'_def apply blast \n      using assms is_cell_conditionE apply meson \n      using is_convex_condition_def apply blast\n      unfolding E1_def E0_def  \\<C>201_def condition_to_set.simps cell_def by blast \n  qed\n  have 20:  \"is_c_decomposable m cent (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n    unfolding 17 \n      apply(rule c_decomposable_disjoint_union)\n    using 18 apply blast \n    using 19 apply blast \n    using 16 by blast \n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 8 \n      apply(rule c_decomposable_disjoint_union)\n    using 1 unfolding \\<C>1_def \n      apply (metis (no_types, lifting) A0_semialg assms(1) assms(5) c_cell_is_c_decomposable is_cell_conditionE(2) is_cell_conditionE(3) is_cell_conditionE(4) is_cell_conditionE(5) padic_fields.is_cell_conditionI' padic_fields_axioms)\n    using 20 apply blast \n    unfolding \\<C>2_def A0_def A1_def condition_to_set.simps  cell_def \n    by blast \nqed\n\nlemma closed_ray_minus_open_ray_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b closed_ray\"\n  assumes \"\\<C>' = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain A0 where A0_def: \"A0 = A - B\"\n    by blast \n  obtain A1 where A1_def: \"A1 = A \\<inter> B\"\n    by blast \n  have A_semialg: \"is_semialgebraic m A\"\n    using assms is_cell_conditionE by blast \n  have B_semialg: \"is_semialgebraic m B\"\n    using assms is_cell_conditionE by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    unfolding A0_def using A_semialg B_semialg diff_is_semialgebraic by blast\n  have A1_semialg: \"is_semialgebraic m A1\"\n    unfolding A1_def by (simp add: A_semialg B_semialg intersection_is_semialg)\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m A0 cent a b closed_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def using assms A0_semialg change_of_fibres by blast\n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m A1 cent a b closed_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def using assms A1_semialg change_of_fibres by blast\n  have 1: \"condition_to_set \\<C>1 \\<inter> condition_to_set \\<C>' = {}\"\n    unfolding \\<C>1_def assms A0_def by (metis Diff_disjoint disj_fibres_imp_disj_cells inf_commute)\n  have d_semialg: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson \n  have b_semialg: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson\n  have B_closed: \"B \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    using assms is_cell_conditionE B_semialg is_semialgebraic_closed by presburger\n  have 6: \"A = A0 \\<union> A1\"\n    unfolding A0_def A1_def by blast \n  have 7: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    unfolding assms \\<C>1_def \\<C>2_def 6 using union_fibres A0_semialg A1_semialg assms(1) assms(5) change_of_fibres \n    by blast\n  have 8: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>1 \\<union> (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n    unfolding 7 using 1 by blast \n  have 9: \"is_c_decomposable  m cent (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n  proof-\n    have 90: \"condition_to_set \\<C>2 - condition_to_set \\<C>' = condition_to_set (Cond m A1 cent d b closed_interval)\"\n    proof\n      show \"condition_to_set \\<C>2 - condition_to_set \\<C>' \\<subseteq> condition_to_set (Cond m A1 cent d b closed_interval)\"\n      proof fix x assume A: \"x \\<in> condition_to_set \\<C>2 - condition_to_set \\<C>'\"\n        show \"x \\<in> condition_to_set (Cond m A1 cent d b closed_interval)\"\n          unfolding condition_to_set.simps  apply(rule cell_memI) \n          using A unfolding condition_to_set.simps \\<C>2_def cell_def apply blast \n          using A unfolding condition_to_set.simps \\<C>2_def cell_def apply blast \n          apply(rule closed_interval_memI)\n          using A unfolding A1_def assms open_ray_def condition_to_set.simps \\<C>2_def cell_def Diff_iff mem_Collect_eq\n          apply auto[1]\n          using A unfolding A1_def assms closed_ray_def condition_to_set.simps \\<C>2_def cell_def Diff_iff mem_Collect_eq\n          by blast \n      qed\n      show \"condition_to_set (Cond m A1 cent d b closed_interval) \\<subseteq> condition_to_set \\<C>2 - condition_to_set \\<C>'\"\n      proof fix x assume A: \"x \\<in> condition_to_set (Cond m A1 cent d b closed_interval)\"\n        show \"x \\<in> condition_to_set \\<C>2 - condition_to_set \\<C>'\"\n        proof\n          show \"x \\<in> condition_to_set \\<C>2\"\n            unfolding \\<C>2_def condition_to_set.simps apply(rule cell_memI)\n            using A unfolding condition_to_set.simps cell_def apply blast\n            using A unfolding condition_to_set.simps cell_def apply blast \n            apply(rule closed_ray_memI)\n            using A unfolding condition_to_set.simps cell_def  closed_interval_def by blast \n          show \" x \\<notin> condition_to_set \\<C>'\"\n            using A unfolding assms condition_to_set.simps  cell_def  \n                          closed_interval_def open_ray_def  mem_Collect_eq A1_def \n            using not_less[of \"val (hd x \\<ominus> cent (tl x))\" \"val (d (tl x))\"]\n            by blast \n        qed\n      qed\n    qed\n    have 91: \"is_cell_condition (Cond m A1 cent d b closed_interval)\"\n      apply(rule is_cell_conditionI')\n      using A1_semialg apply blast\n      using assms is_cell_conditionE apply blast \n      using assms is_cell_conditionE apply meson\n      using assms is_cell_conditionE apply meson\n      unfolding is_convex_condition_def by blast \n    show ?thesis unfolding 90 \n      using 91 c_cell_is_c_decomposable by blast\n  qed\n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 8 \n    apply(rule c_decomposable_disjoint_union)\n    using 0 unfolding \\<C>2_def  using A0_semialg \\<C>1_def c_cell_is_c_decomposable change_of_fibres apply blast\n    using 9  unfolding \\<C>2_def apply blast \n    unfolding \\<C>1_def A0_def A1_def condition_to_set.simps cell_def  by blast \nqed\n\nlemma open_ray_minus_open_ray_cell_diff:\n  assumes \"\\<C> = Cond m A cent a b open_ray\"\n  assumes \"\\<C>' = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\nproof- \n  obtain A0 where A0_def: \"A0 = A - B\"\n    by blast \n  obtain A1 where A1_def: \"A1 = A \\<inter> B\"\n    by blast \n  have A_semialg: \"is_semialgebraic m A\"\n    using assms is_cell_conditionE by blast \n  have B_semialg: \"is_semialgebraic m B\"\n    using assms is_cell_conditionE by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    unfolding A0_def using A_semialg B_semialg diff_is_semialgebraic by blast\n  have A1_semialg: \"is_semialgebraic m A1\"\n    unfolding A1_def by (simp add: A_semialg B_semialg intersection_is_semialg)\n  obtain \\<C>1 where \\<C>1_def: \"\\<C>1 = Cond m A0 cent a b open_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>1\"\n    unfolding \\<C>1_def using assms A0_semialg change_of_fibres by blast\n  obtain \\<C>2 where \\<C>2_def: \"\\<C>2 = Cond m A1 cent a b open_ray\"\n    by blast \n  have 0: \"is_cell_condition \\<C>2\"\n    unfolding \\<C>2_def using assms A1_semialg change_of_fibres by blast\n  have 1: \"condition_to_set \\<C>1 \\<inter> condition_to_set \\<C>' = {}\"\n    unfolding \\<C>1_def assms A0_def by (metis Diff_disjoint disj_fibres_imp_disj_cells inf_commute)\n  have d_semialg: \"d \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson \n  have b_semialg: \"b \\<in> carrier (SA m)\"\n    using assms is_cell_conditionE by meson\n  have B_closed: \"B \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n    using assms is_cell_conditionE B_semialg is_semialgebraic_closed by presburger\n  have 6: \"A = A0 \\<union> A1\"\n    unfolding A0_def A1_def by blast \n  have 7: \"condition_to_set \\<C> = condition_to_set \\<C>1 \\<union> condition_to_set \\<C>2\"\n    unfolding assms \\<C>1_def \\<C>2_def 6 using union_fibres A0_semialg A1_semialg assms(1) assms(5) change_of_fibres \n    by blast\n  have 8: \"condition_to_set \\<C> - condition_to_set \\<C>' = condition_to_set \\<C>1 \\<union> (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n    unfolding 7 using 1 by blast \n  have 9: \"is_c_decomposable  m cent (condition_to_set \\<C>2 - condition_to_set \\<C>')\"\n  proof-\n    have 90: \"condition_to_set \\<C>2 - condition_to_set \\<C>' = condition_to_set (Cond m A1 cent d b left_closed_interval)\"\n    proof\n      show \"condition_to_set \\<C>2 - condition_to_set \\<C>' \\<subseteq> condition_to_set (Cond m A1 cent d b left_closed_interval)\"\n      proof fix x assume A: \"x \\<in> condition_to_set \\<C>2 - condition_to_set \\<C>'\"\n        show \"x \\<in> condition_to_set (Cond m A1 cent d b left_closed_interval)\"\n          unfolding condition_to_set.simps  apply(rule cell_memI) \n          using A unfolding condition_to_set.simps \\<C>2_def cell_def apply blast \n          using A unfolding condition_to_set.simps \\<C>2_def cell_def apply blast \n          apply(rule left_closed_interval_memI)\n          using A unfolding A1_def assms open_ray_def condition_to_set.simps \\<C>2_def cell_def Diff_iff mem_Collect_eq\n          by auto \n      qed\n      show \"condition_to_set (Cond m A1 cent d b left_closed_interval) \\<subseteq> condition_to_set \\<C>2 - condition_to_set \\<C>'\"\n      proof fix x assume A: \"x \\<in> condition_to_set (Cond m A1 cent d b left_closed_interval)\"\n        show \"x \\<in> condition_to_set \\<C>2 - condition_to_set \\<C>'\"\n        proof\n          show \"x \\<in> condition_to_set \\<C>2\"\n            unfolding \\<C>2_def condition_to_set.simps apply(rule cell_memI)\n            using A unfolding condition_to_set.simps cell_def apply blast\n            using A unfolding condition_to_set.simps cell_def apply blast \n            apply(rule open_ray_memI)\n            using A unfolding condition_to_set.simps cell_def  left_closed_interval_def by blast \n          show \" x \\<notin> condition_to_set \\<C>'\"\n            using A unfolding assms condition_to_set.simps  cell_def  \n                          left_closed_interval_def open_ray_def  mem_Collect_eq A1_def \n            using not_less[of \"val (hd x \\<ominus> cent (tl x))\" \"val (d (tl x))\"]\n            by blast \n        qed\n      qed\n    qed\n    have 91: \"is_cell_condition (Cond m A1 cent d b left_closed_interval)\"\n      apply(rule is_cell_conditionI')\n      using A1_semialg apply blast\n      using assms is_cell_conditionE apply blast \n      using assms is_cell_conditionE apply meson\n      using assms is_cell_conditionE apply meson\n      unfolding is_convex_condition_def by blast \n    show ?thesis unfolding 90 \n      using 91 c_cell_is_c_decomposable by blast\n  qed\n  show \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n    unfolding 8 \n    apply(rule c_decomposable_disjoint_union)\n    using 0 unfolding \\<C>2_def  using A0_semialg \\<C>1_def c_cell_is_c_decomposable change_of_fibres apply blast\n    using 9  unfolding \\<C>2_def apply blast \n    unfolding \\<C>1_def A0_def A1_def condition_to_set.simps cell_def  by blast \nqed\n\nlemma closed_ray_minus_convex_condition_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b I\"\n  assumes \"\\<C> = Cond m B cent c d closed_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n  apply(cases \"I = closed_interval\")\n  using assms closed_ray_minus_closed_interval_cell_diff apply blast\n  apply(cases \"I = left_closed_interval\")\n  using assms closed_ray_minus_left_closed_interval_cell_diff apply blast\n  apply(cases \"I = closed_ray\")\n  using assms closed_ray_minus_closed_ray_cell_diff apply blast\n  using assms closed_ray_minus_open_ray_cell_diff is_cell_conditionE(5)[of m A cent a b I] \n  unfolding is_convex_condition_def  by blast  \n\nlemma open_ray_minus_convex_condition_cell_diff:\n  assumes \"\\<C>' = Cond m A cent a b I\"\n  assumes \"\\<C> = Cond m B cent c d open_ray\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n  apply(cases \"I = closed_interval\")\n  using assms open_ray_minus_closed_interval_cell_diff apply blast\n  apply(cases \"I = left_closed_interval\")\n  using assms open_ray_minus_left_closed_interval_cell_diff apply blast\n  apply(cases \"I = closed_ray\")\n  using assms open_ray_minus_closed_ray_cell_diff apply blast\n  using assms open_ray_minus_open_ray_cell_diff is_cell_conditionE(5)[of m A cent a b I] \n  unfolding is_convex_condition_def  by blast \n\nlemma cell_diff_is_c_decomposable:\n  assumes \"\\<C>' = Cond m A cent a b I\"\n  assumes \"\\<C> = Cond m B cent c d J\"\n  assumes \"A \\<subseteq> C\"\n  assumes \"B \\<subseteq> C\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  shows \"is_c_decomposable m cent (condition_to_set \\<C> - condition_to_set \\<C>')\"\n  apply(cases \"J = closed_interval\")\n    using assms padic_fields.closed_interval_minus_convex_condition_cell_diff padic_fields_axioms apply blast\n  apply(cases \"J = left_closed_interval\")\n    using assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) padic_fields.left_closed_interval_minus_convex_condition_cell_diff padic_fields_axioms apply blast\n  apply(cases  \"J = open_ray\")\n    using assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) open_ray_minus_convex_condition_cell_diff apply blast\n  apply(cases \"J = closed_ray\")\n    using assms(1) assms(2) assms(3) assms(4) assms(5) assms(6) padic_fields.closed_ray_minus_convex_condition_cell_diff padic_fields_axioms apply blast\n    using assms is_cell_conditionE(5) unfolding assms is_convex_condition_def by blast \n\nlemma empty_is_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  shows \"is_c_decomposable m c {}\"\nproof-\n  obtain \\<C> where \\<C>_def: \"is_cell_condition \\<C> \\<and> arity \\<C>  = m \\<and>center \\<C> = c \\<and> condition_to_set \\<C> = {}\"\n    using empty_in_cells[of m \"carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\" c]  unfolding is_c_decomposable_def c_cells_def  is_c_cell_def\n    using assms carrier_is_semialgebraic by blast\n  show ?thesis \n    apply(rule is_c_decomposableI[of \"{\\<C>}\"])\n     apply blast\n  proof-\n    have 0:  \"(\\<forall>C. C \\<in> {\\<C>} \\<longrightarrow> center C = c)\"\n      using \\<C>_def by blast \n    have 1: \"is_cell_decomp m {\\<C>} {}\"\n      apply(rule is_cell_decompI) \n          apply blast \n      apply(rule is_partitionI)\n      apply(rule disjointI)\n          apply blast \n      using \\<C>_def apply blast \n      using \\<C>_def apply blast \n       apply blast  \n      using \\<C>_def by blast \n    show \" is_cell_decomp m {\\<C>} {} \\<and> (\\<forall>C. C \\<in> {\\<C>} \\<longrightarrow> center C = c)\"\n      using 0 1 by blast \n  qed\nqed\n\nlemma finite_disjoint_union_is_c_decomposable:\n  assumes \"disjoint S\"\n  assumes \"finite S\"\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> is_c_decomposable m c s\"\n  shows \"is_c_decomposable m c (\\<Union> S)\"\nproof- \n  have \"disjoint S \\<and> (\\<forall>s \\<in> S. is_c_decomposable m c s) \\<longrightarrow> is_c_decomposable m c (\\<Union> S)\"\n  proof(rule finite.induct[of S])\n    show \"finite S\"\n      using assms by blast \n    show \"disjoint {} \\<and> (\\<forall>s\\<in>{}. is_c_decomposable m c s) \\<longrightarrow> is_c_decomposable m c (\\<Union> {})\"\n      unfolding disjoint_def using assms empty_is_c_decomposable \n      by (metis Sup_empty)\n    show \"\\<And>A a. finite A \\<Longrightarrow>\n           disjoint A \\<and> (\\<forall>s\\<in>A. is_c_decomposable m c s) \\<longrightarrow> is_c_decomposable m c (\\<Union> A) \\<Longrightarrow>\n           disjoint (insert a A) \\<and> (\\<forall>s\\<in>insert a A. is_c_decomposable m c s) \\<longrightarrow> is_c_decomposable m c (\\<Union> (insert a A))\"\n    proof fix A a \n      assume A: \"finite A\"\n           \"disjoint A \\<and> (\\<forall>s\\<in>A. is_c_decomposable m c s) \\<longrightarrow> is_c_decomposable m c (\\<Union> A)\"\n           \"disjoint (insert a A) \\<and> (\\<forall>s\\<in>insert a A. is_c_decomposable m c s)\"\n      show \"is_c_decomposable m c (\\<Union> (insert a A))\"\n        apply(cases \"a \\<in> A\")\n        using A \n        apply (metis insert_absorb)\n      proof-\n        assume 00: \"a \\<notin> A\"\n        have 0: \"disjoint A\"\n          using A unfolding disjoint_def by blast \n        have 1: \"(\\<forall>s\\<in>A. is_c_decomposable m c s)\"\n          using A by blast \n        have 2: \"\\<Union>A \\<inter>  a = {}\"\n        proof(rule equalityI')\n          show \"\\<And>x. x \\<in> \\<Union> A \\<inter> a \\<Longrightarrow> x \\<in> {}\"\n          proof- fix x assume A0: \"x \\<in> \\<Union> A \\<inter> a\"\n            then obtain s where s_def: \"s \\<in> A \\<and> x \\<in> s \\<inter> a\"\n              by blast \n            then have \"s \\<inter> a = {}\"\n              using 0 1 A disjointE[of \"insert a A\" s a] 00  by blast \n            then show \"x \\<in> {}\"\n              using s_def by blast \n          qed\n          show \"\\<And>x. x \\<in> {} \\<Longrightarrow> x \\<in> \\<Union> A \\<inter> a\" by blast \n        qed\n        have 3: \"is_c_decomposable m  c a\"\n          using A by blast \n        have 4: \"is_c_decomposable m c (\\<Union> A)\"\n          using A 0 1 by blast \n        hence \"is_c_decomposable m c (\\<Union>A \\<union> a)\"\n          using 2 3 4 c_decomposable_disjoint_union by blast \n        thus ?thesis \n          by (simp add: Un_commute)\n      qed\n    qed\n  qed\n  then show ?thesis \n    using assms by blast \nqed\n\nlemma c_decomposable_minus_c_cell_is_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"is_c_decomposable m c A\"\n  assumes \"\\<C> = Cond m C c a b I\"\n  assumes \"is_cell_condition \\<C>\"\n  shows \"is_c_decomposable m c (A - condition_to_set \\<C>)\"\nproof-\n  obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S A \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n    using assms is_c_decomposableE[of m c A]\n    by blast \n  have 0: \"disjoint (condition_to_set ` S)\"\n    apply(rule disjointI)\n    using S_def is_cell_decompE(5)[of m S A] by blast  \n  have 1: \"A - condition_to_set \\<C> = (\\<Union> s \\<in> S. condition_to_set s - condition_to_set \\<C>)\"\n    using S_def is_cell_decompE(2)[of m S A] is_partitionE(2)[of \"condition_to_set ` S\" A]\n    by blast \n  have  2: \"disjoint ((\\<lambda>s . condition_to_set s - condition_to_set \\<C>) ` S)\"\n  proof(rule disjointI) fix a b assume A: \" a \\<in> (\\<lambda>s. condition_to_set s - condition_to_set \\<C>) ` S \"\n           \"b \\<in> (\\<lambda>s. condition_to_set s - condition_to_set \\<C>) ` S\" \"a \\<noteq> b\"\n    then obtain s where s_def: \"s \\<in> S \\<and> a =   condition_to_set s - condition_to_set \\<C>\"\n      by (metis (no_types, lifting) imageE image_restrict_eq)\n    then obtain s' where s'_def: \"s' \\<in> S \\<and> b =   condition_to_set s' - condition_to_set \\<C>\"\n      using A by (metis (no_types, lifting) imageE image_restrict_eq)\n    have \"s \\<noteq> s'\"\n      using s_def s'_def A by blast \n    hence \"condition_to_set s \\<inter> condition_to_set s' = {}\"\n      using s_def s'_def is_cell_decompE S_def \n      by meson\n    thus \"a \\<inter> b = {}\"\n      using s_def s'_def  A  0 disjointE by blast \n  qed\n  have 3: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_c_decomposable m c (condition_to_set s - condition_to_set \\<C>)\"\n  proof- fix s assume A: \"s \\<in> S\"\n    obtain B c' d J where BcdJ_def: \"s = Cond m B c c' d J\"\n      using A S_def is_cell_decompE \n      by (metis condition_decomp')\n    show \"is_c_decomposable m c (condition_to_set s - condition_to_set \\<C>)\"\n    using assms S_def cell_diff_is_c_decomposable[of \\<C> m C c a b I s B c' d J  \"carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"] \n    by (metis A BcdJ_def is_cell_conditionE''(1) is_cell_decompE(3) is_semialgebraic_closed)\n  qed\n  show \"is_c_decomposable m c (A - condition_to_set \\<C>)\"\n    unfolding 1 \n    apply(rule finite_disjoint_union_is_c_decomposable)\n    using 2 apply blast \n    using S_def is_cell_decompE(1) apply blast \n    using assms apply blast using 3 by blast \nqed\n\nlemma c_decomposable_difference0:\n  assumes \"is_c_decomposable m c C\"\n  assumes \"S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n  shows \"is_c_decomposable m c (C - B)\"\nproof- \n  obtain n where n_def: \"n = card S\"\n    by blast \n  have \"\\<forall> C S B . is_c_decomposable m c C \\<longrightarrow> ( n = card S \\<longrightarrow> ((S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)) \\<longrightarrow>  is_c_decomposable m c (C - B)))\"\n  proof(induction n)\n    case 0\n    then show ?case  \n      by (metis bot_nat_def card_0_eq padic_fields.is_cell_decompE(1) padic_fields_axioms)\n  next\n    case (Suc n) fix n \n    assume IH: \" \\<forall>C S B.\n            is_c_decomposable m c C \\<longrightarrow>\n            n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n    show \" \\<forall>C S B.\n            is_c_decomposable m c C \\<longrightarrow>\n            Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n    proof fix C \n      show \"\\<forall>S B. is_c_decomposable m c C \\<longrightarrow>\n               Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n      proof fix S \n        show \"\\<forall>B. is_c_decomposable m c C \\<longrightarrow>\n             Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n        proof fix B \n          show \"is_c_decomposable m c C \\<longrightarrow>\n         Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n          proof assume A0: \"is_c_decomposable m c C \"\n            show \"Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n            proof assume A1: \"Suc n = card S\"\n              show \"S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<longrightarrow> is_c_decomposable m c (C - B)\"\n              proof assume A2: \" S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n                show \"is_c_decomposable m c (C - B)\"\n                proof- \n                  obtain C' where C'_def: \"C' \\<in> S\" using A2 by blast \n                  obtain S' where S'_def: \"S' = S - {C'}\" by blast \n                  obtain D where D_def: \"D = (\\<Union> c \\<in> S'. condition_to_set c)\"\n                    by blast \n                  have 00: \"\\<Union> (condition_to_set ` (S - {C'})) \\<subseteq> \\<Union> (condition_to_set ` S) \"\n                    by blast\n                  have 0: \"is_cell_decomp m S' D \\<and> (\\<forall>C. C \\<in> S' \\<longrightarrow> center C = c)\"\n                  proof\n                    show \"is_cell_decomp m S' D\"\n                      apply(rule is_cell_decompI) \n                      unfolding S'_def using A2 is_cell_decompE(1) apply blast\n                         apply(rule is_partitionI) using A2 is_cell_decompE(2)[of m S B] \n                      unfolding disjoint_def using  is_partitionE(1)[of \"condition_to_set ` S\" B]  \n                      apply (metis (mono_tags, lifting) DiffD1 image_iff disjoint_def)\n                        unfolding D_def S'_def apply blast \n                        using A2 is_cell_decompE(4)[of m S B] \n                        apply (meson DiffD1 is_cell_decompE(3))\n                        using A2 is_cell_decompE(2)[of m S B] is_partitionE[of \"condition_to_set ` S\" B]\n                              is_cell_decompE(6)[of m S B] 00 apply blast\n                        using A2 is_cell_decompE(2)[of m S B] is_partitionE(1)[of \"condition_to_set ` S\" B]\n                        unfolding disjoint_def using is_cell_decompE(6)[of m S B] 00 \n                        by (meson Diff_iff is_cell_decompE(5))\n                      show \" \\<forall>C. C \\<in> S' \\<longrightarrow> center C = c\"\n                        using A2 unfolding S'_def by blast\n                  qed\n                  have 1: \"is_c_decomposable m c (C - D)\"\n                  proof(cases \"D = {}\")\n                    case True\n                    then show ?thesis using A0 unfolding True by simp\n                  next\n                    case False\n                    have F0: \"S' \\<noteq> {}\"\n                    proof assume A: \"S' = {}\"\n                      then have \"D = {}\"\n                        using 0 is_cell_decompE(2)[of m S' D] is_partitionE[of \"condition_to_set ` S'\" D]\n                        unfolding A by blast\n                      then show False using False by blast \n                    qed\n                    have F1: \"is_c_decomposable m c D\"\n                      apply(rule is_c_decomposableI[of S']) \n                      using F0 apply blast \n                      using 0 by blast \n                    have F2: \"\\<And> C S B. is_c_decomposable m c C \\<Longrightarrow> n = card S \\<Longrightarrow> \n                                    S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c) \\<Longrightarrow>\n                                     is_c_decomposable m c (C - B)\"\n                      using IH by blast \n                    have F3: \"n = card (S - {C'})\"\n                      by (metis A1 C'_def Diff_empty card.infinite card_Diff_insert diff_Suc_1 mem_simps(2) zero_less_Suc zero_less_iff_neq_zero)\n                    show ?thesis\n                      using A0 F0 F2[of C S' D] 0 F1 F3  unfolding S'_def  by blast \n                  qed\n                  have 2: \"B = \\<Union> (condition_to_set ` S)\"\n                    using A2 is_cell_decompE(2)[of m S B] is_partitionE[of \"condition_to_set ` S\" B] by blast \n                  have 3: \"C - B = (C - D) - condition_to_set C'\"\n                    unfolding D_def S'_def 2 using C'_def by blast \n                  obtain D' a b J where  def: \"C' = Cond m D' c a b J\"\n                    using C'_def A2 is_cell_decompE \n                    by (metis condition_decomp')\n                  have 4: \"is_c_decomposable m c ((C - D) - condition_to_set C')\"\n                    apply(rule c_decomposable_minus_c_cell_is_c_decomposable[of _ _ _ _ D' a b J])\n                    using assms is_c_decomposableE apply blast \n                    using 1 apply blast \n                    using def apply blast \n                    using C'_def A2 is_cell_decompE by blast \n                  show ?thesis using 4 unfolding D_def S'_def \n                    using A2 is_cell_decompE(2) is_partitionE (2) \"3\" \"4\" by presburger\n                qed\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis using assms n_def by blast\nqed\n\nlemma c_decomposable_difference:\n  assumes \"is_c_decomposable m c C\"\n  assumes \"is_c_decomposable m c B\"\n  shows \"is_c_decomposable m c (C - B)\"\nproof- \n  obtain S where S_def: \" S \\<noteq> {} \\<and>\n        is_cell_decomp m S B \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n    using assms unfolding is_c_decomposable_def by blast \n  show ?thesis \n    by(rule c_decomposable_difference0[of _ _ _ S], \n        rule assms, rule S_def)\nqed  \n\ntheorem c_decomposable_is_gen_boolean_algebra:\n  assumes \"is_c_decomposable m c C\"\n  shows \"c_decomposables m c C = gen_boolean_algebra C (Cells\\<^bsub>m,c\\<^esub>(C))\"\nproof\n  show \"c_decomposables m c C \\<subseteq> gen_boolean_algebra C (Cells\\<^bsub>m,c\\<^esub>(C))\"\n  proof fix x assume A: \"x \\<in> c_decomposables m c C\"\n    show \"x \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C\"\n    proof-\n      obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S x \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n        using A c_decomposables_def \n        by (metis (no_types, lifting) is_c_decomposableE(1) mem_Collect_eq)\n      have 0: \"x = (\\<Union> Y \\<in> S. condition_to_set Y )\"\n        using S_def \n        by (metis is_cell_decompE(2) is_partitionE(2))\n      have 1: \"\\<And>Y. Y \\<in> S \\<Longrightarrow> condition_to_set Y \\<in> Cells\\<^bsub>m,c\\<^esub>(C)\"\n      proof- fix Y assume A0: \"Y \\<in> S\"\n        have 0: \"arity Y = m\"\n          using A0 S_def is_cell_decompE(4) by blast\n        have 1: \"is_cell_condition Y\"\n          using A0 S_def is_cell_decompE(3) by blast\n        have 2: \"center Y = c\"\n          using A0  S_def by blast\n        have 3: \"(\\<exists>\\<C>. is_cell_condition \\<C> \\<and> arity \\<C> = m \\<and> center \\<C> = c \\<and> condition_to_set Y = condition_to_set \\<C>)\"\n          using 0 1 2 \n          by blast\n        have 4: \"condition_to_set Y \\<subseteq> C\"\n        proof-\n          have \"condition_to_set Y \\<subseteq> x\"\n            using A0 S_def is_cell_decomp_subset by blast\n          thus ?thesis using A c_decomposables_closed by blast \n        qed\n        thus \"condition_to_set Y \\<in> Cells\\<^bsub>m, c\\<^esub>C\"\n          using 0 1 2 3 4 is_cell_decompE(3)[of m S x Y] is_cell_decompE(4)[of m S x Y] S_def \n          unfolding c_cells_def  is_c_cell_def mem_Collect_eq \n          by blast\n      qed\n      show ?thesis \n        unfolding 0 apply(rule gen_boolean_algebra_finite_union[of \"condition_to_set ` S\" C \"Cells\\<^bsub>m, c\\<^esub>C\"])\n         apply(rule gen_boolean_algebra_generators) using c_cells_def  mem_Collect_eq apply blast \n        using 1 apply blast \n        using S_def is_cell_decompE(1) by blast\n    qed\n  qed\n  show \"gen_boolean_algebra C (Cells\\<^bsub>m, c\\<^esub>(C)) \\<subseteq> c_decomposables m c C\"\n  proof fix x assume A: \"x \\<in> gen_boolean_algebra C (Cells\\<^bsub>m, c\\<^esub>(C))\"\n    show \"x \\<in>  c_decomposables m c C\"\n    proof(rule boolean_algebra_alt_induct[of x C \"Cells\\<^bsub>m, c\\<^esub>(C)\"])\n      show \"x \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C\" using A by blast \n      show \"C \\<in> c_decomposables m c C\" using assms unfolding c_decomposables_def  \n        by blast\n      show \"\\<And>A. A \\<in> Cells\\<^bsub>m, c\\<^esub>C \\<Longrightarrow> A \\<inter> C \\<in> c_decomposables m c C\"\n      proof- fix A assume A0: \"A \\<in> Cells\\<^bsub>m,c\\<^esub>(C)\"\n        then have 0: \"A \\<subseteq> C\"\n          using A0 c_cells_def by blast\n        obtain \\<C> where \\<C>_def: \"is_cell_condition \\<C> \\<and> arity \\<C> = m \\<and> center \\<C> = c \\<and> A = condition_to_set \\<C>\"\n          using A0 unfolding c_cells_def is_c_cell_def by blast \n        obtain S where S_def: \"S = {\\<C>}\"\n          by blast \n        have 1: \"is_cell_decomp m S A\"\n          apply(rule is_cell_decompI) \n          unfolding S_def apply blast \n          apply(rule is_partitionI) \n          unfolding disjoint_def apply blast \n          using \\<C>_def apply blast \n          using \\<C>_def apply blast \n          using 0 assms is_c_decomposableE[of m c C] apply (meson basic_trans_rules(23) is_cell_decompE(6))\n          by blast \n        show \"A \\<inter> C \\<in> c_decomposables m c C\"\n          unfolding c_decomposables_def mem_Collect_eq using 1 is_c_decomposableI[of S m A c]\n          unfolding S_def using \\<C>_def \n          by (metis \"0\" Int_absorb2 insert_not_empty singletonD)\n      qed          \n      show \"\\<And>A Ca.\n       A \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C \\<Longrightarrow>\n       Ca \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C \\<Longrightarrow>\n       A \\<in> c_decomposables m c C \\<Longrightarrow> Ca \\<in> c_decomposables m c C \\<Longrightarrow> A \\<inter> Ca = {} \\<Longrightarrow> A \\<union> Ca \\<in> c_decomposables m c C\"\n      proof- fix A B assume A: \" A \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C\"  \"A \\<in> c_decomposables m c C\" \n                            \"B \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C\" \"B \\<in> c_decomposables m c C\" \"A \\<inter> B= {}\"\n        show \"A \\<union> B \\<in> c_decomposables m c C\"\n          unfolding c_decomposables_def mem_Collect_eq\n        proof\n          obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S A \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n            using A unfolding c_decomposables_def mem_Collect_eq using is_c_decomposableE[of m c A] \n            by blast\n          obtain S' where S'_def: \"S' \\<noteq> {} \\<and>is_cell_decomp m S' B \\<and> (\\<forall>C. C \\<in> S' \\<longrightarrow> center C = c)\"\n            using A unfolding c_decomposables_def mem_Collect_eq using is_c_decomposableE[of m c B] \n            by blast\n          have 0: \"A \\<union> B - A = B\"\n            using A(5) by blast \n          have 1: \"is_cell_decomp m (S \\<union> S') (A \\<union> B)\"\n            apply(rule cell_decomp_union[of \"A\"]) \n               apply blast \n            using assms A  apply (meson S'_def S_def Un_subset_iff is_cell_decompE(6))\n            using S_def apply blast\n            using S'_def unfolding 0 by blast \n          show \"is_c_decomposable m c (A \\<union> B)\"\n            apply(rule is_c_decomposableI[of \"S \\<union> S'\"])\n            using  S_def apply blast \n            using 1 S_def S'_def by blast \n          show \"A \\<union> B \\<subseteq> C\"\n            using A assms c_decomposables_closed by blast\n        qed\n      qed\n\n      show \" \\<And>A B.\n       A \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C \\<Longrightarrow>\n      B \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C \\<Longrightarrow> A \\<in> c_decomposables m c C \\<Longrightarrow> B \\<in> c_decomposables m c C \\<Longrightarrow> A - B \\<in> c_decomposables m c C \"\n      proof- fix A B assume A: \"A \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C\" \"B \\<in> gen_boolean_algebra C Cells\\<^bsub>m, c\\<^esub>C\" \n                               \"A \\<in> c_decomposables m c C\" \"B \\<in> c_decomposables m c C\"\n        show \"A - B \\<in> c_decomposables m c C\"\n          using A c_decomposable_difference unfolding c_decomposables_def mem_Collect_eq by blast \n      qed\n    qed\n  qed\nqed\n\nlemma cell_decomp_same_center:\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"\\<C> = Cond m C c a1 a2 I\"\n  assumes \"B \\<subseteq> condition_to_set \\<C>\"\n  assumes \"\\<exists>S. is_cell_decomp m S B \\<and> (\\<forall> A \\<in> S. center A = c)\"\n  shows \"\\<exists>S'. is_cell_decomp m S' (condition_to_set \\<C> - B) \\<and> (\\<forall>A \\<in> S'. center A = c)\"\nproof(cases \"B = {}\")\n  case True\n  have \"is_cell_decomp m {\\<C>} (condition_to_set \\<C> - B)\"\n    apply(rule is_cell_decompI)\n    apply blast \n       apply(rule is_partitionI) apply(rule disjointI)\n        apply blast unfolding True apply blast \n    unfolding assms using arity.simps \n    using assms(1) assms(2) apply blast\n    unfolding condition_to_set.simps cell_def apply blast \n    by blast \n  then show ?thesis unfolding assms using center.simps by blast \nnext\n  case False\n  obtain S where S_def: \"is_cell_decomp m S B \\<and> (\\<forall> A \\<in> S. center A = c)\"\n    using  assms by blast \n  have 0: \"S \\<noteq> {}\"\n    using S_def False is_cell_decompE is_partitionE \n    by (metis ccSup_empty image_empty)\n  have 1: \"is_c_decomposable m c B\"\n    apply(rule is_c_decomposableI[of S])\n    using 0 apply blast \n    using S_def by blast \n  have \"is_c_decomposable m c (condition_to_set \\<C> - B)\"\n    apply(rule c_decomposable_difference)\n    using assms unfolding assms using c_cell_is_c_decomposable apply blast\n    using 1 by blast \n  then show ?thesis using is_c_decomposableE by blast \nqed\nend\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Refining Cells Against a Set of Endpoints\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext\\<open>Given a finite set \\texttt{Fs} of semialgebraic functions, and a cell condition $\\mathcal{C}$ \n\\texttt{= Cond m C c a1 a2 I}, we would like to decompose the underlying set of $\\mathcal{C}$ into \nfinitely many cells \\texttt{S} which are compatible with \\texttt{Fs} in the sense that for any cell \n$\\mathcal{D} \\in$ \\texttt{S}, and any cell $\\mathcal{B}$\\texttt{ = Cond m C c f g J} where \n\\texttt{f, g }$\\in$\\texttt{ Fs} and \\texttt{J} is arbitrary, either \\texttt{condition\\_to\\_set} \n$\\mathcal{D} \\subseteq$ \\texttt{condition\\_to\\_set }$\\mathcal{B}$ or they are disjoint. This will \nbe useful in the proof of Denef's Theorem $II$. In particular, it will be crucial for establishing \nequation $(3)$ from Denef's proof of cell decompostion theorem $II_d$. This proof will use the \nresults from the previous section that sets which can be decomposed into cells with a common center \nform a boolean algebra. We can proceed as follows:\n\\begin{enumerate}\n\n\\item Form the collection of underlying sets of cells $\\mathcal{B}$ \\texttt{= Cond m C c f g J} \nwhere $f, g \\in Fs \\cup \\{a1, a2\\}$, which are contained in \n\\texttt{condition\\_to\\_set }$\\mathcal{C}$. \nThese generate a subalgebra of all $c$-decomposable sets contained in \n\\texttt{condition\\_to\\_set }$\\mathcal{C}$. This subalgebra is what we call \n\\texttt{endpoint\\_c\\_algebra} below.  \n\n\\item Since there are finitely many sets above, we can obtain the atoms of the subalgebra they \ngenerate. Since $c$-decomposable sets form a boolean algebra, these atoms themselves will be \n$c$-decomposable. Thus each atom can be further decomposed into a finite disjoint union of cells \ncentered at $c$. Collecting the cells in each of these decompositions will give us our desired \ndecomposition of $\\mathcal{C}$. \n\\end{enumerate}\n   \\<close>\ncontext padic_fields\nbegin\n\nlemma static_order_type_decomp_0:\n  assumes \"finite Fs\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"is_semialgebraic m B\"\n  shows \"\\<exists>Bs. finite Bs \\<and> Bs partitions B \\<and> (\\<forall>b \\<in> Bs. is_semialgebraic m b \\<and> \n          (\\<forall>f \\<in> Fs. \\<forall>g \\<in> Fs. \\<forall>x \\<in> b.\\<forall>y \\<in> b. (val (f x) < val (g x) \\<longleftrightarrow> val (f y) < val (g y)) \\<and> (val (f x) = val (g x) \\<longleftrightarrow> val (f y) = val (g y))))\"\nproof- \n  obtain Fs_pairs where Fs_pairs_def: \"Fs_pairs = {(f, g). f \\<noteq> g} \\<inter> ( Fs \\<times> Fs)\"\n    by blast \n  have Fs_pairs_finite: \"finite Fs_pairs\"\n  proof- have \"finite (Fs \\<times> Fs)\"\n      using assms by blast \n    thus ?thesis \n      unfolding Fs_pairs_def by blast \n  qed\n  obtain S1 where S1_def: \"S1 = (\\<lambda>(f,g). B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) < val (g x)})\"\n    by blast \n  have S1_semialg: \"\\<And>f g. (f,g) \\<in> Fs_pairs \\<Longrightarrow> is_semialgebraic m (S1 (f,g))\"\n  proof- fix f g assume A: \"(f,g) \\<in> Fs_pairs\"\n    have 0: \"f \\<in> Fs\"\n      using A unfolding Fs_pairs_def by blast \n    have 1: \"g \\<in> Fs\"\n      using A unfolding Fs_pairs_def by blast \n    have f_closed: \"f \\<in> carrier (SA m)\"\n      using 0 assms by blast \n    have g_closed: \"g \\<in> carrier (SA m)\"\n      using 1 assms by blast \n    have 3: \"S1 (f,g) =  B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) < val (g x)}\"\n      using S1_def by blast \n    show \"is_semialgebraic m (S1 (f,g))\"\n      unfolding 3\n      by(rule intersection_is_semialg, rule assms, rule semialg_val_strict_ineq_set_is_semialg, rule f_closed, rule g_closed)\n  qed\n  obtain S2 where S2_def: \"S2 = (\\<lambda>(f,g). B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})\"\n    by blast \n  have S2_semialg: \"\\<And>f g. (f,g) \\<in> Fs_pairs \\<Longrightarrow> is_semialgebraic m (S2 (f,g))\"\n  proof- fix f g assume A: \"(f,g) \\<in> Fs_pairs\"\n    have 0: \"f \\<in> Fs\"\n      using A unfolding Fs_pairs_def by blast \n    have 1: \"g \\<in> Fs\"\n      using A unfolding Fs_pairs_def by blast \n    have f_closed: \"f \\<in> carrier (SA m)\"\n      using 0 assms by blast \n    have g_closed: \"g \\<in> carrier (SA m)\"\n      using 1 assms by blast \n    have 3: \"S2 (f,g) =  B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)}\"\n      using S2_def by blast \n    show \"is_semialgebraic m (S2 (f,g))\"\n      unfolding 3\n      by(rule intersection_is_semialg, rule assms, rule semialg_val_eq_set_is_semialg, rule f_closed, rule g_closed)\n  qed\n  obtain S where S_def: \"S = (S1 ` Fs_pairs)\\<union>(S2 ` Fs_pairs)\"\n    by blast \n  have S_semialg: \"\\<And>s. s \\<in> S \\<Longrightarrow> is_semialgebraic m s\"\n    unfolding S_def using S1_semialg S2_semialg unfolding Fs_pairs_def \n    by blast\n  have S_finite: \"finite S\"\n    using Fs_pairs_finite unfolding S_def by blast \n  obtain P where P_def: \"P = atoms_of S\"\n    by blast \n  have finite_P: \"finite P\"\n    unfolding P_def using S_finite \n    by (simp add: finite_set_imp_finite_atoms)\n  have P_semialg: \"\\<And>s. s \\<in> P \\<Longrightarrow> is_semialgebraic m s\"\n    using S_finite S_semialg atoms_of_gen_boolean_algebra\n    unfolding P_def is_semialgebraic_def semialg_sets_def \n    by (metis (no_types, opaque_lifting) Set.basic_monos(7) local.P_def subsetI)\n  show \" \\<exists>Bs. finite Bs \\<and>\n         Bs partitions B \\<and>\n         (\\<forall>b\\<in>Bs.\n             is_semialgebraic m b \\<and>\n             (\\<forall>f\\<in>Fs. \\<forall>g\\<in>Fs. \\<forall>x\\<in>b. \\<forall>y\\<in>b. ((val (f x) < val (g x)) = (val (f y) < val (g y)) \\<and> (val (f x) = val (g x)) = (val (f y) = val (g y))))) \"\n  proof(cases \"Fs = {}\")\n    case True\n    obtain Bs where Bs_def: \"Bs = {B}\"\n      by blast \n    have T0: \"Bs partitions B\" unfolding Bs_def \n      by(rule is_partitionI, rule Generated_Boolean_Algebra.disjointI, blast, blast)\n    show ?thesis using True T0 assms Bs_def by blast\n  next\n    case False\n    show ?thesis \n    proof(cases \"Fs_pairs = {}\")\n      case True\n      obtain f where f_def: \"f \\<in> Fs\"\n        using False by blast \n      have T0: \"\\<And>g. g \\<in> Fs \\<Longrightarrow> g = f\"\n        apply(rule ccontr)\n        using f_def True unfolding Fs_pairs_def by blast \n      obtain Bs where Bs_def: \"Bs = {B}\"\n        by blast \n      have T1: \"Bs partitions B\" unfolding Bs_def \n        by(rule is_partitionI, rule Generated_Boolean_Algebra.disjointI, blast, blast)\n      have T2: \"(\\<forall>f\\<in>Fs. \\<forall>g\\<in>Fs. \\<forall>x\\<in>B. \\<forall>y\\<in>B. ((val (f x) < val (g x)) = (val (f y) < val (g y)) \\<and> (val (f x) = val (g x)) = (val (f y) = val (g y))))\"\n        using T0 by blast  \n      show ?thesis\n        using T1 T2 assms Bs_def by blast \n    next\n      case F: False\n      have S_union: \"\\<Union> S = B\"\n      proof(rule equalityI')\n        fix x assume A: \"x \\<in> \\<Union>S\"\n        show \"x \\<in> B\"\n          using A unfolding S_def S1_def S2_def by blast \n      next \n        fix x assume A: \"x \\<in> B\"\n        show \"x \\<in> \\<Union> S\"\n        proof- \n          have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n            using A assms  is_semialgebraic_closed by blast\n          obtain f g where fg_def: \"(f,g) \\<in>  Fs_pairs\"\n            using F \n            by (metis equals0I surj_pair)\n          have 0: \"(g, f) \\<in> Fs_pairs\"\n            using fg_def unfolding Fs_pairs_def \n            by blast\n          have 1: \"val (f x) = val (g x) \\<Longrightarrow> x \\<in> S2 (f,g)\"\n            unfolding S2_def using x_closed A \n            by blast\n          have 2: \"val (f x) < val (g x) \\<Longrightarrow> x \\<in> S1 (f,g)\"\n            unfolding S1_def using x_closed A \n            by blast\n          have 3: \"val (f x) > val (g x) \\<Longrightarrow> x \\<in> S1 (g,f)\"\n            unfolding S1_def using x_closed A \n            by blast\n          have 4: \"val (f x) \\<noteq> val (g x) \\<Longrightarrow> \\<not>val (f x) < val (g x) \\<Longrightarrow> val (f x) > val (g x)\"\n            by (meson basic_trans_rules(18) padic_fields.notin_closed padic_fields_axioms)\n          show ?thesis \n            apply(cases \"val (f x) = val (g x)\")\n            using 1 fg_def unfolding S_def  apply blast\n            apply(cases \"val (f x) < val (g x)\")\n            using 2 fg_def unfolding S_def  apply blast\n            using 0 3 4 unfolding S_def by blast \n        qed\n      qed\n      have P_union: \"\\<Union> P = B\"\n        unfolding P_def using atoms_of_covers[of B] S_union S_finite by blast \n      have P_partitions: \"P partitions B\"\n        apply(rule is_partitionI, rule Generated_Boolean_Algebra.disjointI)\n        using P_def atoms_of_disjoint S_finite apply blast\n        by(rule P_union)\n      have \"(\\<forall>b\\<in>P.\n             is_semialgebraic m b \\<and>\n             (\\<forall>f\\<in>Fs. \\<forall>g\\<in>Fs. \\<forall>x\\<in>b. \\<forall>y\\<in>b. (val (f x) < val (g x) \\<longleftrightarrow> val (f y) < val (g y)) \\<and> (val (f x) = val (g x) \\<longleftrightarrow> val (f y) = val (g y))))\"\n      proof(rule , rule, rule P_semialg, blast, rule , rule , rule , rule )\n        fix b f g x y \n        assume A0: \"b \\<in> P\"    \"f \\<in> Fs\" \"g \\<in> Fs\" \"x \\<in> b\" \"y \\<in> b\"\n        show \"(val (f x) < val (g x) \\<longleftrightarrow> val (f y) < val (g y)) \\<and> (val (f x) = val (g x) \\<longleftrightarrow> val (f y) = val (g y))\"\n        proof(cases \"f = g\")\n          case True\n          show ?thesis unfolding True by blast \n        next\n          case False\n          have 0: \"(f,g) \\<in> Fs_pairs\"\n            using A0 Fs_pairs_def  False by blast\n          obtain s1 where s1_def: \"s1 = S1 (f,g)\"\n            by blast \n          have s1_in_S: \"s1 \\<in> S\"\n            using 0 s1_def S_def by blast \n          obtain s2 where s2_def: \"s2 = S2 (f,g)\"\n            by blast \n          have s2_in_S: \"s2 \\<in> S\"\n            using 0 s2_def S_def by blast \n          have 1: \"b \\<subseteq> s1 \\<or> b \\<inter> s1 = {}\"\n            using A0 s1_in_S P_def atoms_are_minimal by blast \n          have 2: \"b \\<subseteq> s2 \\<or> b \\<inter> s2 = {}\"\n            using A0 s2_in_S P_def atoms_are_minimal by blast \n          have x_closed: \"x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n            using A0 P_semialg[of b] is_semialgebraic_closed by blast\n          have y_closed: \"y \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)\"\n            using A0 P_semialg[of b] is_semialgebraic_closed by blast\n          have 3: \"x \\<in> s1 \\<longleftrightarrow> y \\<in> s1\"\n            using A0 1 by blast \n          have 4: \"x \\<in> s2 \\<longleftrightarrow> y \\<in> s2\"\n            using A0 2 by blast \n          have 5: \"s1 = B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) < val (g x)}\"\n            unfolding s1_def S1_def by blast \n          have 6: \"s2 = B \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)}\"\n            unfolding s2_def S2_def by blast \n          have x_in_B: \"x \\<in> B\"\n            using P_union A0 by blast \n          have y_in_B: \"y \\<in> B\"\n            using P_union A0 by blast \n          have 7: \"(val (f x) < val (g x)) = (val (f y) < val (g y))\"\n            using y_closed x_closed 3  x_in_B y_in_B unfolding 5 by blast\n          have 8: \"(val (f x) = val (g x)) = (val (f y) = val (g y))\"\n            using y_closed x_closed 4  x_in_B y_in_B unfolding 6 by blast \n          show ?thesis using 7 8 by blast \n        qed\n      qed\n      thus ?thesis using P_partitions P_semialg \n        using finite_P by blast\n    qed\n  qed\nqed\n\ndefinition static_order_type where\n\"static_order_type Fs b = (\\<forall>f \\<in> Fs. \\<forall>g \\<in> Fs. \\<forall>x \\<in> b.\\<forall>y \\<in> b. (val (f x) < val (g x) \\<longleftrightarrow> val (f y) < val (g y)) \\<and> (val (f x) = val (g x) \\<longleftrightarrow> val (f y) = val (g y)))\"\n\nlemma static_ord_typeI: \n  assumes \"\\<And>f g x y. f \\<in> Fs \\<Longrightarrow> g \\<in> Fs \\<Longrightarrow> x \\<in> b \\<Longrightarrow> y \\<in> b \\<Longrightarrow> (val (f x) < val (g x) \\<Longrightarrow> val (f y) < val (g y))\"\n  assumes \"\\<And>f g x y. f \\<in> Fs \\<Longrightarrow> g \\<in> Fs \\<Longrightarrow> x \\<in> b \\<Longrightarrow> y \\<in> b \\<Longrightarrow> (val (f x) = val (g x) \\<Longrightarrow> val (f y) = val (g y))\"\n  shows \"static_order_type Fs b\"\n  unfolding static_order_type_def\n  apply(rule, rule, rule , rule , rule conjI)\n  using assms apply blast using assms by blast \n\nlemma static_ord_typeE: \n  assumes \"static_order_type Fs b\"\n  assumes \"f \\<in> Fs\"\n  assumes \"g \\<in> Fs\"\n  assumes \"x \\<in> b\"\n  assumes \"y \\<in> b\"\n  shows \"val (f x) < val (g x) \\<Longrightarrow> val (f y) < val (g y)\"\n        \"val (f x) = val (g x) \\<Longrightarrow> val (f y) = val (g y)\"\n  using assms unfolding static_order_type_def  apply blast\n  using assms unfolding static_order_type_def  by blast\n\nlemma static_order_type_decomp:\n  assumes \"finite Fs\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"is_semialgebraic m B\"\n  shows \"\\<exists>Bs. finite Bs \\<and> Bs partitions B \\<and> (\\<forall>b \\<in> Bs. is_semialgebraic m b \\<and> \n                      static_order_type Fs b)\"\n  unfolding static_order_type_def \nby(rule static_order_type_decomp_0, rule assms, rule assms, rule assms)\n\ndefinition endpoint_generators where\n\"endpoint_generators m c B f g = {\\<C>. \\<exists>I. is_convex_condition I \\<and> \\<C> = Cond m B c f g I} \"\n\nlemma endpoint_generators_cell_cond:\n  assumes \"is_semialgebraic m B\"\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"f \\<in> carrier (SA m)\"\n  assumes \"g \\<in> carrier (SA m)\"\n  assumes \"\\<C> \\<in> endpoint_generators m c B f g\"\n  shows \"is_cell_condition \\<C>\"\nproof- \n  obtain I where I_def: \"is_convex_condition I \\<and> \\<C> = Cond m B c f g I\"\n    using assms(5) unfolding endpoint_generators_def by blast \n  have \\<C>_eq: \"\\<C> = Cond m B c f g I\"\n    using I_def by blast \n  show ?thesis \n    unfolding \\<C>_eq apply(rule is_cell_conditionI', rule assms , rule assms, rule assms, rule assms)\n    using I_def by blast \nqed\n\nlemma endpoint_generators_finite:\n\"finite (endpoint_generators m c B f g)\"\nproof- \n  have 0: \"finite {closed_interval, left_closed_interval, closed_ray, open_ray}\"\n    by blast\n  obtain Is where Is_def: \"Is = {closed_interval, left_closed_interval, closed_ray, open_ray}\"\n    by blast \n  have 1: \"\\<And>I. is_convex_condition I \\<Longrightarrow> I \\<in> Is\"\n    unfolding is_convex_condition_def Is_def \n    by(erule disjE, blast,erule disjE, blast,erule disjE, blast, blast)\n  have 2: \"\\<And>I. I \\<in> Is \\<Longrightarrow> is_convex_condition I\"\n  proof- fix I assume A: \"I \\<in> Is\" show \"is_convex_condition I\"\n    unfolding Is_def is_convex_condition_def \n    apply(cases \"I = closed_interval\", blast)\n    apply(cases \"I = left_closed_interval\", blast)\n    apply(cases \"I = closed_ray\", blast)\n    using A unfolding Is_def by force \n  qed\n  have 3:  \"(endpoint_generators m c B f g) = Cond m B c f g ` Is\"\n    apply(rule equalityI')\n    using 1  unfolding endpoint_generators_def mem_Collect_eq image_iff \n    apply blast\n    using 2 by blast  \n  thus ?thesis unfolding Is_def using 0 by force \nqed\n\ndefinition endpoint_c_algebra where\n  \"endpoint_c_algebra m c B a1 a2 I Fs = gen_boolean_algebra (condition_to_set (Cond m B c a1 a2 I))\n                                                      (condition_to_set ` (\\<Union> (f,g) \\<in> Fs \\<times> Fs. (endpoint_generators m c B f g))) \"\n\nlemma is_c_decomposable_algebra:\n  assumes \"is_c_decomposable m c C\"\n  shows \"C \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\nproof-\n  have 0: \"C \\<subseteq> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"\n    using assms is_cell_decompE unfolding is_c_decomposable_def \n    by meson\n  show ?thesis \n    using assms unfolding is_c_decomposable_def c_decomposables_def mem_Collect_eq \n    using 0 by blast \nqed\n\nlemma singleton_mem:\n\"x \\<in> {y} = (x = y)\"\n  by blast \n\nlemma constant_zero:\n\"\\<And>x. x \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) \\<Longrightarrow>\n         (constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<zero> (tl x)) = \\<zero>\"\n  by(intro constant_functionE Qp_pow_ConsE, auto )\n\nlemma carrier_is_c_decomposable: \n  assumes \"c \\<in> carrier (SA m)\"\n  shows \"is_c_decomposable m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\nproof- \n  have 0: \"carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>) = condition_to_set (Cond m (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) c c (constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<zero>) closed_ray)\"\n    apply(rule equalityI')\n    unfolding condition_to_set.simps apply(rule cell_memI, blast)\n    using cartesian_power_tail apply blast\n     by(rule closed_ray_memI, unfold constant_zero val_zero cell_def mem_Collect_eq, auto )      \n  have 1: \"is_cell_condition  (Cond m (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) c c (constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<zero>) closed_ray)\"\n    apply(rule is_cell_conditionI', rule carrier_is_semialgebraic, rule assms, rule assms, rule constant_fun_closed, rule Qp.zero_closed)\n    unfolding is_convex_condition_def by blast\n  have 2: \"is_cell_decomp m {(Cond m (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) c c (constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<zero>) closed_ray)} (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    apply(rule is_cell_decompI, blast, rule is_partitionI, rule Generated_Boolean_Algebra.disjointI, blast)\n    using 0 apply blast unfolding singleton_mem using 1 arity.simps  apply blast\n     apply blast by blast \n  show ?thesis apply(rule is_c_decomposableI[of \" {(Cond m (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) c c (constant_function (carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>)) \\<zero>) closed_ray)}\"], \n        blast) unfolding singleton_mem using center.simps 1 \n    using \"2\" by blast\nqed\n    \nlemma carrier_is_c_decomposable': \n  assumes \"is_c_decomposable m c A\"\n  shows \"is_c_decomposable m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\nby(rule carrier_is_c_decomposable, rule is_c_decomposableE, rule assms)\n\nlemma intersection_is_c_decomposable:\n  assumes \"is_c_decomposable m c A\"\n  assumes \"is_c_decomposable m c B\"\n  shows \"is_c_decomposable m c (A \\<inter> B)\"\nproof-\n  have 0: \"A \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    by(rule is_c_decomposable_algebra, rule assms )\n  have 1: \"B \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    by(rule is_c_decomposable_algebra, rule assms )\n  have 2: \"c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) = gen_boolean_algebra (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (Cells\\<^bsub>m,c\\<^esub>((carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))))\"\n    by(rule c_decomposable_is_gen_boolean_algebra, rule carrier_is_c_decomposable', rule assms )\n  have 3: \"A \\<inter> B\\<in> gen_boolean_algebra (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (Cells\\<^bsub>m,c\\<^esub>((carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))))\"\n    apply(rule gen_boolean_algebra_intersect)\n    using 0 unfolding 2 apply blast\n    using 1 unfolding 2 by blast\n  show ?thesis using 3 2 c_decomposables_def by blast\nqed\n\nlemma union_is_c_decomposable:\n  assumes \"is_c_decomposable m c A\"\n  assumes \"is_c_decomposable m c B\"\n  shows \"is_c_decomposable m c (A \\<union> B)\"\nproof-\n  have 0: \"A \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    by(rule is_c_decomposable_algebra, rule assms )\n  have 1: \"B \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    by(rule is_c_decomposable_algebra, rule assms )\n  have 2: \"c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) = gen_boolean_algebra (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (Cells\\<^bsub>m,c\\<^esub>((carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))))\"\n    by(rule c_decomposable_is_gen_boolean_algebra, rule carrier_is_c_decomposable', rule assms )\n  have 3: \"A \\<union> B\\<in> gen_boolean_algebra (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (Cells\\<^bsub>m,c\\<^esub>((carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))))\"\n    apply(rule gen_boolean_algebra.union)\n    using 0 unfolding 2 apply blast\n    using 1 unfolding 2 by blast\n  show ?thesis using 3 2 c_decomposables_def by blast\nqed\n\nlemma diff_is_c_decomposable:\n  assumes \"is_c_decomposable m c A\"\n  assumes \"is_c_decomposable m c B\"\n  shows \"is_c_decomposable m c (A - B)\"\nproof-\n  have 0: \"A \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    by(rule is_c_decomposable_algebra, rule assms )\n  have 1: \"B \\<in> c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    by(rule is_c_decomposable_algebra, rule assms )\n  have 2: \"c_decomposables m c (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) = gen_boolean_algebra (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (Cells\\<^bsub>m,c\\<^esub>((carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))))\"\n    by(rule c_decomposable_is_gen_boolean_algebra, rule carrier_is_c_decomposable', rule assms )\n  have 3: \"A - B\\<in> gen_boolean_algebra (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (Cells\\<^bsub>m,c\\<^esub>((carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))))\"\n    apply(rule gen_boolean_algebra_diff)\n    using 0 unfolding 2 apply blast\n    using 1 unfolding 2 by blast\n  show ?thesis using 3 2 c_decomposables_def by blast\nqed\n\nlemma intersection_in_c_decomposables: \n  assumes \"is_c_decomposable m c A\"\n  assumes \"B \\<in> c_decomposables m c C\"\n  shows \"(A \\<inter> B) \\<in> c_decomposables m c C\"\n  unfolding c_decomposables_def mem_Collect_eq \n  apply(rule conjI, rule intersection_is_c_decomposable, rule assms)\n  using assms unfolding c_decomposables_def apply blast\n  using assms unfolding c_decomposables_def by blast\n\nlemma intersection_in_c_decomposables': \n  assumes \"is_c_decomposable m c A\"\n  assumes \"B \\<in> c_decomposables m c C\"\n  shows \"(B \\<inter> A) \\<in> c_decomposables m c C\"\n  unfolding c_decomposables_def mem_Collect_eq \n  apply(rule conjI, rule intersection_is_c_decomposable)\n  using assms unfolding c_decomposables_def apply blast\n  using assms apply blast\n  using assms unfolding c_decomposables_def by blast\n\nlemma condition_to_set_cell_decomp:\n  assumes \"A = condition_to_set \\<C>\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"arity \\<C> = m\"\n  shows \"is_cell_decomp m {\\<C>} A\"\n  apply(rule is_cell_decompI, blast, rule is_partitionI, rule Generated_Boolean_Algebra.disjointI, blast)\n  using assms apply blast using assms arity.simps apply blast\n  using assms condition_to_set.simps unfolding cell_def \n   apply (meson cell_condition_to_set_subset)\n  by blast \n\nlemma cell_is_c_decomposable: \n  assumes \"is_cell_condition (Cond m C c a1 a2 I)\"\n  shows \"is_c_decomposable m c (condition_to_set (Cond m C c a1 a2 I))\"\n  apply(rule is_c_decomposableI[of \"{Cond m C c a1 a2 I}\"], blast, rule conjI, rule condition_to_set_cell_decomp\n        , blast, rule assms, rule arity.simps)\n  unfolding singleton_mem using center.simps by blast\n\nlemma endpoint_c_algebra_is_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"is_semialgebraic m B\"\n  assumes \"a1 \\<in> carrier (SA m)\"\n  assumes \"a2 \\<in> carrier (SA m)\"\n  assumes \"is_convex_condition I\"\n  assumes \"finite Fs\"\n  assumes \"\\<And>f. f \\<in> Fs \\<Longrightarrow> f \\<in> carrier (SA m)\"\n  assumes \"C \\<in> endpoint_c_algebra m c B a1 a2 I Fs\"\n  shows \"is_c_decomposable m c C\"\napply(rule gen_boolean_algebra.induct[of _  \" (condition_to_set (Cond m B c a1 a2 I))\" \" (condition_to_set ` (\\<Union> (f,g) \\<in> Fs \\<times> Fs. (endpoint_generators m c B f g)))\"])\n  using assms unfolding endpoint_c_algebra_def apply blast\n     apply(rule c_cell_is_c_decomposable, rule is_cell_conditionI', rule assms, rule assms, rule assms, rule assms, rule assms )\n  proof- \n    fix x assume A: \"x \\<in>  condition_to_set ` (\\<Union>(f, g)\\<in>Fs \\<times> Fs. endpoint_generators m c B f g)\"\n    then obtain f g \\<C> where fg_def: \"(f,g) \\<in> Fs \\<times> Fs \\<and> \\<C> \\<in>  endpoint_generators m c B f g \\<and> x = condition_to_set  \\<C>\"\n      by blast \n    have f_in: \"f \\<in> Fs\"\n      using fg_def by blast \n    have g_in: \"g \\<in> Fs\"\n      using fg_def by blast\n    obtain J where J_def: \"is_convex_condition J \\<and> \\<C> = Cond m B c f g J\"\n      using fg_def endpoint_generators_def by blast \n    have \\<C>_eq: \"\\<C> = Cond m B c f g J\"\n      using J_def by blast \n    have \\<C>_cell_cond: \"is_cell_condition \\<C>\"\n      apply(rule endpoint_generators_cell_cond[of m B c f g], rule assms, rule assms, rule assms, rule f_in, rule assms, rule g_in)\n      using fg_def by blast \n    have 0: \" c_decomposables m c (condition_to_set (Cond m B c a1 a2 I)) =\n      gen_boolean_algebra (condition_to_set (Cond m B c a1 a2 I)) (Cells\\<^bsub>m, c\\<^esub>(condition_to_set (Cond m B c a1 a2 I)))\"\n      apply(rule c_decomposable_is_gen_boolean_algebra[of m c ])\n      by(rule c_cell_is_c_decomposable, rule is_cell_conditionI', rule assms, rule assms, rule assms, rule assms, rule assms )\n    have x_eq: \"x = condition_to_set \\<C>\"\n      using fg_def by blast \n    have 1:  \"(x \\<inter> condition_to_set (Cond m B c a1 a2 I))  \\<in> c_decomposables m c (condition_to_set (Cond m B c a1 a2 I))\"\n      apply(rule intersection_in_c_decomposables)\n      unfolding x_eq \\<C>_eq apply(rule cell_is_c_decomposable)\n      using \\<C>_cell_cond unfolding \\<C>_eq apply blast\n      unfolding c_decomposables_def mem_Collect_eq apply(rule conjI)\n       apply(rule cell_is_c_decomposable)\n      by(rule is_cell_conditionI', rule assms, rule assms, rule assms, rule assms, rule assms, blast)\n    show \"is_c_decomposable m c (x \\<inter> condition_to_set (Cond m B c a1 a2 I))\"\n      using 1 unfolding c_decomposables_def by blast \n  next\n    fix A C assume A: \" A \\<in> gen_boolean_algebra (condition_to_set (Cond m B c a1 a2 I)) (condition_to_set ` (\\<Union>(f, g)\\<in>Fs \\<times> Fs. endpoint_generators m c B f g))\"\n                      \"is_c_decomposable m c A\"\n                      \" C \\<in> gen_boolean_algebra (condition_to_set (Cond m B c a1 a2 I)) (condition_to_set ` (\\<Union>(f, g)\\<in>Fs \\<times> Fs. endpoint_generators m c B f g))\"\n                      \"is_c_decomposable m c C\"\n    show \"is_c_decomposable m c (A \\<union> C)\"\n      by(rule union_is_c_decomposable, rule A, rule A)\n  next\n    fix A assume A: \" A \\<in> gen_boolean_algebra (condition_to_set (Cond m B c a1 a2 I)) (condition_to_set ` (\\<Union>(f, g)\\<in>Fs \\<times> Fs. endpoint_generators m c B f g))\"\n                    \" is_c_decomposable m c A\"\n    show \"is_c_decomposable m c (condition_to_set (Cond m B c a1 a2 I) - A)\"\n      by(rule diff_is_c_decomposable, rule cell_is_c_decomposable, rule is_cell_conditionI', \n            rule assms, rule assms, rule assms, rule assms, rule assms, rule A)\n  qed\n\nlemma endpoint_c_algebra_atomic_cell_decomp:\n  assumes \"is_cell_condition (Cond m C c a1 a2 I)\"\n  assumes \"finite Gs\"\n  assumes \"Gs \\<subseteq> carrier (SA m)\"\n  shows \"\\<exists>S. is_cell_decomp m S (condition_to_set (Cond m C c a1 a2 I)) \\<and> (\\<forall>B \\<in> S. center B = c \\<and> \n            (\\<forall>f \\<in> Gs. \\<forall>g \\<in> Gs. \\<forall>I. is_convex_condition I \\<longrightarrow> \n        condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g I) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g I) = {}))\"\nproof-\n  obtain Fs where Fs_def: \"Fs = Gs \\<union> {a1, a2}\"\n    by blast \n  have finite_Fs: \"finite Fs\"\n    unfolding Fs_def finite_Un by(rule conjI, rule assms, blast)\n  obtain As where As_def: \"As = atoms_of (endpoint_c_algebra m c C a1 a2 I (Fs))\"\n    by blast \n  have 0: \"\\<Union> As = condition_to_set (Cond m C c a1 a2 I)\"\n    unfolding As_def apply(rule atoms_of_covers)\n    apply(rule equalityI)\n    using gen_boolean_algebra.universe[of \"condition_to_set (Cond m C c a1 a2 I)\" \"(condition_to_set ` (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y))\"]\n    unfolding endpoint_c_algebra_def apply blast\n    using gen_boolean_algebra_subset[of _ \"condition_to_set (Cond m C c a1 a2 I)\" \"(condition_to_set ` (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y))\"]\n    by blast\n  have 1: \"finite ((\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y))\"\n    apply(rule Finite_Set.finite_UN_I)\n    using assms finite_Fs apply blast \n  proof- fix a assume A: \"a \\<in> Fs \\<times> Fs\"\n    then obtain x y where xy_def: \"a = (x,y)\"\n      by blast \n    have 0: \" (case a of (x, y) \\<Rightarrow> endpoint_generators m c C x y) =  endpoint_generators m c C x y\"\n      unfolding xy_def by blast\n    show \"finite (case a of (x, y) \\<Rightarrow> endpoint_generators m c C x y)\"\n      unfolding 0 by(rule endpoint_generators_finite )\n  qed   \n  have 2: \"gen_boolean_algebra (condition_to_set (Cond m C c a1 a2 I)) (condition_to_set ` (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y)) = gen_boolean_algebra (condition_to_set (Cond m C c a1 a2 I))\n   ((\\<inter>) (condition_to_set (Cond m C c a1 a2 I)) ` condition_to_set ` (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y))\"\n    using gen_boolean_algebra_restrict_generators[of \"condition_to_set (Cond m C c a1 a2 I)\" \"(condition_to_set ` (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y))\"]\n    by blast \n  have 3: \"condition_to_set  (Cond m C c a1 a2 I) \\<in> ((\\<inter>) (condition_to_set (Cond m C c a1 a2 I)) ` condition_to_set ` (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y))\"\n  proof- \n    have 00: \"(a1, a2) \\<in> Fs \\<times> Fs\"\n      unfolding Fs_def by blast \n    have 01: \"Cond m C c a1 a2 I \\<in>  (\\<Union>(x, y)\\<in>Fs \\<times> Fs. endpoint_generators m c C x y)\"\n    proof-\n      have 000: \"Cond m C c a1 a2 I \\<in> {\\<C>. \\<exists>I. is_convex_condition I \\<and> \\<C> = Cond m C c a1 a2 I}\"\n        using assms is_cell_conditionE(5) by blast \n      show ?thesis \n      unfolding endpoint_generators_def using 00 000  by blast \n    qed\n    show ?thesis using 00 01 by blast \n  qed\n  have 4: \"As \\<subseteq> endpoint_c_algebra m c C a1 a2 I Fs\"\n    apply(rule subsetI)\n    unfolding endpoint_c_algebra_def 2\n    apply(rule atoms_closed) using 1 apply blast\n    unfolding As_def endpoint_c_algebra_def unfolding 2 apply blast\n    unfolding 2 using 3 by blast \n  have 5: \"\\<And>a. a \\<in> As \\<Longrightarrow> is_c_decomposable m c a\"\n    apply(rule endpoint_c_algebra_is_c_decomposable[of c m C a1 a2 I Fs])\n    apply(rule is_cell_conditionE[of m C c a1 a2 I], rule assms)\n    apply(rule is_cell_conditionE[of m C c a1 a2 I], rule assms)\n    apply(rule is_cell_conditionE[of m C c a1 a2 I], rule assms)\n    apply(rule is_cell_conditionE[of m C c a1 a2 I], rule assms)\n    apply(rule is_cell_conditionE[of m C c a1 a2 I], rule assms)\n      apply(rule finite_Fs)\n    unfolding Fs_def using assms is_cell_conditionE(4,3)[of m C c a1 a2 I]\n     apply blast\n    using 4 unfolding Fs_def by blast\n  obtain F where F_def: \"F = (\\<lambda>a. (SOME S.  S \\<noteq> {} \\<and> is_cell_decomp m S a \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)))\"\n    by blast\n  have 6: \"\\<And>a. a \\<in> As \\<Longrightarrow> \\<exists>S. S \\<noteq> {} \\<and> is_cell_decomp m S a \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n    using is_c_decomposableE[of m c ] 5 by blast\n  have 7: \"\\<And>a. a \\<in> As \\<Longrightarrow> (F a) \\<noteq> {} \\<and> is_cell_decomp m (F a) a \\<and> (\\<forall>C. C \\<in> (F a)  \\<longrightarrow> center C = c)\"\n  proof- fix a assume A: \"a \\<in> As\"\n    obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S a \\<and> (\\<forall>C. C \\<in> S \\<longrightarrow> center C = c)\"\n      using 6 A by blast \n    show \" (F a) \\<noteq> {} \\<and>is_cell_decomp m (F a) a \\<and> (\\<forall>C. C \\<in> F a \\<longrightarrow> center C = c)\"\n      apply(rule SomeE[of \"F a\" _ S]) unfolding F_def apply blast\n      by(rule S_def)\n  qed\n  have 8: \"finite (\\<Union> (F ` As))\"\n    apply(rule Finite_Set.finite_UN_I)\n    unfolding As_def endpoint_c_algebra_def apply(rule atoms_finite)\n    using 1 unfolding endpoint_generators_def apply blast\n    using 7 is_cell_decompE(1) unfolding As_def endpoint_c_algebra_def endpoint_generators_def \n    by blast\n  have 9: \"condition_to_set ` \\<Union> (F ` As) partitions condition_to_set (Cond m C c a1 a2 I)\"\n  proof(rule is_partitionI, rule Generated_Boolean_Algebra.disjointI)\n    fix A B assume A: \"A \\<in> condition_to_set ` \\<Union> (F ` As)\" \"B \\<in> condition_to_set ` \\<Union> (F ` As)\" \"A \\<noteq> B\"\n    obtain a C where a_def: \"a \\<in> As \\<and> C \\<in> F a \\<and>  A = condition_to_set C \"\n      using A by blast \n    obtain b C' where b_def: \"b \\<in> As \\<and> C' \\<in> F b \\<and>  B = condition_to_set C' \"\n      using A by blast \n    have A_eq: \"A = condition_to_set C\"\n      using a_def by blast \n    have B_eq: \"B = condition_to_set C'\"\n      using b_def by blast \n    have A_sub: \"A \\<subseteq> a\"\n      using a_def 7[of a] is_cell_decompE(2) is_partitionE(2) \n      by (metis is_cell_decomp_subset)\n    have B_sub: \"B \\<subseteq> b\"\n      using b_def 7[of b] is_cell_decompE(2) is_partitionE(2) \n      by (metis is_cell_decomp_subset)  \n    have 0: \"a \\<noteq> b \\<Longrightarrow> a \\<inter> b = {}\"\n      using a_def b_def unfolding As_def \n      using atoms_of_disjoint by blast\n    show \"A \\<inter> B = {}\"\n      apply(cases \"a = b\")\n      using a_def b_def is_cell_decompE is_partitionE 7 \n       apply (metis (no_types, lifting) A(3))\n      using 0 A_sub B_sub by blast \n  next \n    have 10: \"\\<And>a. a \\<in> As \\<Longrightarrow> a \\<subseteq> condition_to_set (Cond m C c a1 a2 I)\"\n      using 0 by blast\n    show \"\\<Union> (condition_to_set ` \\<Union> (F ` As)) = condition_to_set (Cond m C c a1 a2 I)\"\n    proof(rule equalityI') fix x assume A: \"x \\<in> \\<Union> (condition_to_set ` \\<Union> (F ` As))\"\n    obtain a \\<C> where a_def: \"a \\<in> As \\<and> \\<C> \\<in> F a \\<and> x \\<in>  condition_to_set \\<C> \"\n      using A by blast \n    have 11: \"condition_to_set \\<C>  \\<subseteq> a\"\n      using a_def 7 is_cell_decompE(2) is_partitionE(2) by blast \n    show \"x \\<in> condition_to_set (Cond m C c a1 a2 I)\"\n      using a_def 11 10[of a] A by blast \n    next\n      fix x assume A: \"x \\<in> condition_to_set (Cond m C c a1 a2 I)\"\n      obtain a where a_def: \"a \\<in> As \\<and> x \\<in> a\"\n      using A 0 by blast \n    obtain \\<C> where \\<C>_def: \"\\<C> \\<in> F a \\<and> x \\<in> condition_to_set \\<C>\"\n      using a_def 7[of a] is_cell_decompE(2) is_partitionE(2) by blast \n    show \"x \\<in> \\<Union> (condition_to_set ` \\<Union> (F ` As))\"\n      using A \\<C>_def a_def by blast \n    qed\n  qed\n  have 10: \"is_cell_decomp m (\\<Union> (F ` As)) (condition_to_set (Cond m C c a1 a2 I))\"\n    apply(rule is_cell_decompI, rule 8, rule 9)\n    using 7 is_cell_decompE apply blast\n    unfolding condition_to_set.simps cell_def  apply blast\n  proof- \n    fix \\<C> \\<C>' assume A: \"\\<C> \\<in> \\<Union> (F ` As)\" \"\\<C>' \\<in> \\<Union> (F ` As)\" \"\\<C> \\<noteq> \\<C>'\"\n    obtain a where a_def: \"a \\<in> As \\<and> \\<C> \\<in> F a\"\n      using A by blast \n    obtain b where b_def: \"b \\<in> As \\<and> \\<C>' \\<in> F b\"\n      using A by blast    \n    have A_sub: \"condition_to_set \\<C> \\<subseteq> a\"\n      using a_def 7[of a] is_cell_decompE(2) is_partitionE(2) \n      by (metis is_cell_decomp_subset)\n    have B_sub: \"condition_to_set \\<C>' \\<subseteq> b\"\n      using b_def 7[of b] is_cell_decompE(2) is_partitionE(2) \n      by (metis is_cell_decomp_subset) \n    have 0: \"a \\<noteq> b \\<Longrightarrow> a \\<inter> b = {}\"\n      using a_def b_def unfolding As_def \n      using atoms_of_disjoint by blast\n    show \"condition_to_set \\<C> \\<inter> condition_to_set \\<C>' = {}\"\n      apply(cases \"a = b\")\n       apply(rule is_cell_decompE(5)[of m \"F a\" a])\n      using a_def  7[of a] apply blast\n      using a_def apply blast using a_def b_def apply blast\n      using A apply blast\n      using 0 A_sub B_sub by blast \n  qed\n  have 11: \" (\\<forall>B\\<in>(\\<Union> (F ` As)). center B = c \\<and>\n                (\\<forall>f\\<in>Gs.\n                    \\<forall>g\\<in>Gs.\n                       \\<forall>I. is_convex_condition I \\<longrightarrow>\n                           condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g I) \\<or>\n                           condition_to_set B \\<inter> condition_to_set (Cond m C c f g I) = {}))\"\n  proof fix B assume A: \"B \\<in>(\\<Union> (F ` As))\"\n    obtain a where a_def: \"a \\<in> As \\<and> B\\<in> F a\"\n      using A by blast \n    have 110: \"center B = c\"\n      using a_def 7 [of a] by blast \n    have 111: \" (\\<forall>f\\<in>Gs.\n             \\<forall>g\\<in>Gs.\n                \\<forall>I. is_convex_condition I \\<longrightarrow>\n                    condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g I) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g I) = {})\"\n    proof(rule, rule, rule, rule) fix f g J\n      assume A': \"f \\<in> Gs\" \"g \\<in> Gs\" \"is_convex_condition J\"\n      have 00: \"(Cond m C c f g J) \\<in> endpoint_generators m c C f g\"\n        unfolding endpoint_generators_def using A' by blast \n      have 01: \"(f,g) \\<in> Gs \\<times> Gs\"\n        using A' by blast\n      have 02: \"condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I)  \\<in>  endpoint_c_algebra m c C a1 a2 I Fs\"\n        unfolding endpoint_c_algebra_def \n        apply(rule gen_boolean_algebra.generator)\n        using 00 01 Fs_def  by blast \n      have 03: \"condition_to_set B \\<subseteq>condition_to_set (Cond m C c a1 a2 I)\"\n        using a_def As_def 0 \n        by (metis \"7\" Sup_upper2 is_cell_decomp_subset)\n      show \" condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g J) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g J) = {}\"\n      proof(cases \"condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I) = {}\")\n        case True\n        then show ?thesis using 03 by blast \n      next\n        case False\n        show \"condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g J) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g J) = {}\"\n        proof(cases \"condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g J)\")\n          case True\n          then show ?thesis by blast \n        next\n        case F: False\n        obtain x where x_def: \"x \\<in> condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I)\"\n          using False by blast \n        have F0: \"x \\<in> \\<Union> (endpoint_c_algebra m c C a1 a2 I Fs)\"\n          using x_def 02 by blast  \n        obtain b where b_def: \"b\\<in> As \\<and> x \\<in> b\"\n          using F0 atoms_of_covers' unfolding As_def  \n          using \"0\" As_def x_def by blast\n        have F1: \"b \\<subseteq>condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I)\"\n          using atoms_are_minimal[of b \"endpoint_c_algebra m c C a1 a2 I Fs\" \"condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I)\"]\n                b_def  x_def unfolding As_def \n          using \"02\" by blast\n        have F2: \"condition_to_set  B \\<subseteq> a\"\n          using a_def A is_cell_decompE(2)[of m \"F a\" a] is_partitionE(2) 7[of a] by blast\n        obtain y where y_def: \"y \\<in> condition_to_set B \\<and> y \\<notin>condition_to_set (Cond m C c f g J) \"\n          using F by blast \n        have F3: \"condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I) \\<inter> a = {} \\<or>\n                   a \\<subseteq> condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I)\"\n          apply(rule atoms_are_minimal[of a \" endpoint_c_algebra m c C a1 a2 I Fs\" \"condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I)\"])\n          using a_def unfolding As_def apply blast\n          by(rule 02)\n        have F4:  \"condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g J) \\<inter> condition_to_set (Cond m C c a1 a2 I) = {}\"\n          using F3 F2 by blast\n        show \"condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g J) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g J) = {}\"\n          using F  F4  03 by blast\n      qed\n    qed\n     qed\n     show \" center B = c \\<and>\n         (\\<forall>f\\<in>Gs.\n             \\<forall>g\\<in>Gs.\n                \\<forall>I. is_convex_condition I \\<longrightarrow>\n                    condition_to_set B \\<subseteq> condition_to_set (Cond m C c f g I) \\<or> condition_to_set B \\<inter> condition_to_set (Cond m C c f g I) = {})\"\n       using 110 111 by blast \n  qed\n  show ?thesis using 10 11 by blast \nqed\n\nlemma semialg_boundary_cell_decomp:\n  assumes \"finite Fs\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"\\<C> = Cond m B c a1 a2 I\"\n  shows \"\\<exists>S. is_cell_decomp m S (condition_to_set (Cond m B c a1 a2 I)) \\<and> (\\<forall>C \\<in> S. center C = c \\<and> \n            (\\<forall>f \\<in> Fs. \\<forall>g \\<in> Fs. \\<forall>I. is_convex_condition I \\<longrightarrow> \n        condition_to_set C \\<subseteq> condition_to_set (Cond m B c f g I) \\<or> condition_to_set C \\<inter> condition_to_set (Cond m B c f g I) = {}))\"\n  apply(rule endpoint_c_algebra_atomic_cell_decomp)\n  using assms unfolding assms apply blast\n  by(rule assms, rule assms )\nend \n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsubsection\\<open>Cell Algebras\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext\\<open>This section formalizes a type of set system which we call a cell algebra. The intent is to \ncapture the basic properties of the class of sets which can be generated from disjoint unions of \nsome basic type of set. We call the generators cells, and in application we will apply this \nformalization to certain classes of $p$-adic cells. The main point is that we are interested in \nshowing that such systems are closed under finite unions, even if they may not be disjoint.\\<close>\n\ncontext padic_fields\nbegin\n\ninductive_set cell_algebra\n  for Cells  where\n    empty: \"{} \\<in> cell_algebra Cells\"\n  | generator:  \"A \\<in> Cells \\<Longrightarrow> A \\<in> cell_algebra Cells\"\n  | disjoint_union:      \"\\<lbrakk>A \\<in> cell_algebra Cells ; C \\<in> cell_algebra Cells; A \\<inter> C = {}\\<rbrakk> \\<Longrightarrow> A \\<union> C \\<in> cell_algebra Cells\"\n\nlemma cell_algebra_union:\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> cell_algebra B ; C \\<in> cell_algebra B\\<rbrakk> \\<Longrightarrow> A \\<inter> C \\<in> cell_algebra B\"\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> cell_algebra B ; C \\<in> cell_algebra B\\<rbrakk> \\<Longrightarrow> A - C \\<in> cell_algebra B\"\n  shows \"\\<And> A C. \\<lbrakk>A \\<in> cell_algebra B ; C \\<in> cell_algebra B\\<rbrakk> \\<Longrightarrow> A \\<union> C \\<in> cell_algebra B\"\nproof- fix A C assume A: \"A \\<in> cell_algebra B\" \"C \\<in> cell_algebra B\"\n  have 0: \"A \\<union> C = (A - C) \\<union> (C - A) \\<union> (A \\<inter> C)\"\n    by blast \n  show \"A \\<union> C \\<in> cell_algebra B\" unfolding 0 \n    apply(rule cell_algebra.disjoint_union)\n    apply(rule cell_algebra.disjoint_union)\n    apply(rule assms ) using A apply blast using A apply blast \n    apply(rule assms ) using A apply blast using A apply blast \n      apply blast \n    apply(rule assms ) using A apply blast using A apply blast \n    by blast \nqed\n\nlemma cell_algebra_cell_union:\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<in> Cells\\<rbrakk> \\<Longrightarrow> A \\<inter> C \\<in> cell_algebra B\"\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<in> Cells\\<rbrakk> \\<Longrightarrow> A - C \\<in> cell_algebra B\"\n  shows \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<in> Cells\\<rbrakk> \\<Longrightarrow> A \\<union> C \\<in> cell_algebra B\"\nproof- fix A C assume A: \"A \\<in> Cells\" \"C \\<in> Cells\"\n  have 0: \"A \\<union> C = (A - C) \\<union> (C - A) \\<union> (A \\<inter> C)\"\n    by blast \n  show \"A \\<union> C \\<in> cell_algebra B\" unfolding 0 \n    apply(rule cell_algebra.disjoint_union)\n    apply(rule cell_algebra.disjoint_union)\n    using A cell_algebra.generator assms A \n    apply auto[1]\n        using A cell_algebra.generator assms A \n           apply auto[1]\n        apply blast \n        apply(rule assms(1))\n        using  A by auto \nqed\n\nlemma disjoint_insert:\n  assumes \"disjoint S\"\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> A \\<inter> s = {}\"\n  shows \"disjoint (insert A S)\"\nproof(rule disjointI)\n  fix s s' assume A: \"s \\<in> insert A S\" \"s' \\<in> insert A S\" \"s \\<noteq> s'\"\n  show \" s \\<inter> s' = {}\"\n    apply(cases \"s = A\")\n    using A assms apply blast \n    apply(cases \"s' = A\")\n    using A assms apply blast \n    using A assms disjointE by blast \nqed\n\nlemma cell_algebra_finite_disjoint_union:\n  assumes \"S \\<subseteq> cell_algebra B\"\n  assumes  \"finite S\"\n  assumes \"disjoint S\"\n  shows \"\\<Union> S \\<in> cell_algebra B\"\nproof-\n  have \"S \\<subseteq> cell_algebra B \\<and> disjoint S \\<longrightarrow> \\<Union> S \\<in> cell_algebra B\"\n    apply(rule finite.induct[of S], intro assms)\n    using cell_algebra.empty apply auto[1]\n    unfolding insert_subset \n    using assms cell_algebra.disjoint_union \n    Generated_Boolean_Algebra.disjoint_def Sup_insert insert_absorb \n    insert_partition \n    by (metis DiffD1 Diff_insert_absorb)  \n  thus ?thesis using assms by auto \nqed\n\ndefinition cell_disjointify where\n\"cell_disjointify A S = insert (A - (\\<Union>  S)) (((\\<inter>) A ` S) \\<union> (\\<lambda>x. x - A) ` S)\"\n\ntext\\<open>If A is a set and S is a disjoint collection of sets, then cell\\_disjointify A S will return a \nnew collection of disjoint sets which has the same union as $\\bigcup$ (insert A S)\\<close>\n\nlemma disjoint_fact:\n  assumes \"disjoint S\"\n  shows \"disjoint (((\\<inter>) A ` S) \\<union> (\\<lambda>x. x - A) ` S)\"\nproof(rule disjointI)\n  fix s s' assume A: \" s \\<in> (\\<inter>) A ` S \\<union> (\\<lambda>x. x - A) ` S\" \"s' \\<in> (\\<inter>) A ` S \\<union> (\\<lambda>x. x - A) ` S\" \"s \\<noteq> s'\"\n  show \" s \\<inter> s' = {}\" \n    apply(cases \"s \\<in> (\\<inter>) A ` S\")\n     apply(cases \"s' \\<in> (\\<inter>) A ` S\") using A assms disjointE[of S] \n    by auto \nqed\n\nlemma cell_disjointify_disjoint:\n  assumes  \"disjoint S\"\n  shows \"disjoint (cell_disjointify A S)\"\n  unfolding cell_disjointify_def \n  apply(rule disjoint_insert)\n  using assms disjoint_fact[of S A] apply blast \n  by auto \n\nlemma cell_disjointify_union:\n  assumes  \"disjoint S\"\n  shows \"\\<Union>(cell_disjointify A S) = \\<Union> (insert A S)\"\n  apply(rule equalityI) \n  apply (rule subsetI)\n  using assms unfolding cell_disjointify_def apply blast \n  using assms unfolding cell_disjointify_def by blast \n\nlemma empty_disjoint:\n\"disjoint {}\"\n  apply(rule disjointI)\n  by auto \n\nlemma cell_algebra_cell_decomp:\n  assumes \"A \\<in> cell_algebra Cells\"\n  shows \"\\<exists>S \\<subseteq> Cells. finite S \\<and> disjoint S \\<and> \\<Union> S = A\"\n  apply(rule cell_algebra.induct[of A Cells])\n  using assms apply blast \n    using disjointI empty_disjoint apply blast \n   using insert_subset disjointI disjoint_insert \n   apply (metis bot.extremum ccpo_Sup_singleton empty_disjoint equals0D finite.simps insert_subsetI)\n proof- fix A C assume A: \"A \\<in> cell_algebra Cells\"\n           \"\\<exists>S\\<subseteq>Cells. finite S \\<and> disjoint S \\<and> \\<Union> S = A\"\n           \"C \\<in> cell_algebra Cells\"\n           \"\\<exists>S\\<subseteq>Cells. finite S \\<and> disjoint S \\<and> \\<Union> S = C\"\n           \"A \\<inter> C = {}\"\n   obtain S where S_def: \"S\\<subseteq>Cells \\<and> finite S \\<and> disjoint S \\<and> \\<Union> S = A\"\n     using A by blast \n   obtain S' where S'_def: \"S'\\<subseteq>Cells \\<and> finite S' \\<and> disjoint S' \\<and> \\<Union> S' = C\"\n     using A by blast \n   have \"finite (S \\<union> S') \\<and> disjoint (S \\<union> S') \\<and> \\<Union> (S \\<union> S') = A \\<union> C\"\n     apply(rule conjI)\n     using S_def S'_def apply blast \n     apply(rule conjI)\n     apply(rule disjointI)\n     using S_def S'_def A disjointE[of S] disjointE[of S'] \n      apply (metis Sup_inf_eq_bot_iff Un_iff inf_commute)\n     using S_def S'_def by blast \n   thus \"\\<exists>S\\<subseteq>Cells. finite S \\<and> disjoint S \\<and> \\<Union> S = A \\<union> C\"\n     using S_def S'_def \n     by (meson Un_subset_iff)\n qed\n\nlemma cell_algebra_minus_union:\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<in> Cells\\<rbrakk> \\<Longrightarrow> A - C \\<in> cell_algebra Cells\"\n  shows \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<subseteq> Cells ; finite C\\<rbrakk> \\<Longrightarrow> A - \\<Union>C \\<in> cell_algebra Cells\"\nproof- fix A C assume A: \"A \\<in> Cells\" \"C \\<subseteq> Cells\" \"finite C\"\n  have \"C \\<subseteq> Cells \\<longrightarrow> A - \\<Union>C \\<in> cell_algebra Cells\"\n    apply(rule finite.induct[of C])\n    using A apply blast \n    using A cell_algebra.generator[of A Cells] apply auto[1]\n  proof- fix C c assume AA: \"finite C\" \"C \\<subseteq> Cells \\<longrightarrow> A - \\<Union> C \\<in> cell_algebra Cells\"\n    show \"insert c C \\<subseteq> Cells \\<longrightarrow> A - \\<Union> (insert c C) \\<in> cell_algebra Cells\"\n    proof assume AAA: \"insert c C \\<subseteq> Cells\"\n      hence 0: \"A - \\<Union> C \\<in> cell_algebra Cells\"\n        using AA by blast \n      obtain S where S_def: \"S \\<subseteq> Cells \\<and> disjoint S \\<and> finite S \\<and> \\<Union> S =  A - \\<Union> C\"\n        using 0 cell_algebra_cell_decomp[of \"A - \\<Union> C\" Cells] by blast \n      have  1: \"A - \\<Union> (insert c C) = \\<Union> S - c\"\n        using S_def by blast \n      hence 2: \"A - \\<Union> (insert c C) = \\<Union> ((\\<lambda>s. s- c) ` S)\"\n        by auto\n      have 3: \"c \\<in> Cells\"\n        using AAA by blast \n      show \"A - \\<Union> (insert c C) \\<in> cell_algebra Cells\"\n        unfolding 2 apply(rule cell_algebra_finite_disjoint_union)\n        using S_def assms[of _ c] 3 apply blast \n        using S_def apply blast \n        apply(rule disjointI)\n        using S_def disjointE by blast \n    qed\n  qed\n  thus \"A - \\<Union>C \\<in> cell_algebra Cells\"\n    using A by blast \nqed\n\nlemma cell_algebra_finite_union:\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<in> Cells\\<rbrakk> \\<Longrightarrow> A \\<inter> C \\<in> cell_algebra Cells\"\n  assumes \"\\<And> A C. \\<lbrakk>A \\<in> Cells ; C \\<in> Cells\\<rbrakk> \\<Longrightarrow> A - C \\<in> cell_algebra Cells\"\n  shows \"\\<And>S. finite S \\<and> S \\<subseteq> Cells \\<Longrightarrow> \\<Union> S \\<in> cell_algebra Cells\"\nproof- \n  fix S assume A: \"finite S \\<and> S \\<subseteq> Cells\"\n  have \"finite S \\<and> S \\<subseteq> Cells \\<longrightarrow> \\<Union> S \\<in> cell_algebra Cells\"\n    apply(rule finite.induct[of S])\n    using A apply blast \n    using cell_algebra.empty \n    apply (simp add: cell_algebra.empty)\n  proof fix A a\n    assume AA: \"finite A\" \" finite A \\<and> A \\<subseteq> Cells \\<longrightarrow> \\<Union> A \\<in> cell_algebra Cells\" \"finite (insert a A) \\<and> insert a A \\<subseteq> Cells\"\n    then have 0: \" \\<Union> A \\<in> cell_algebra Cells\"\n      by blast \n    obtain S where S_def: \"S \\<subseteq> Cells \\<and> finite S \\<and> disjoint S \\<and> \\<Union> S =  \\<Union> A\"\n      using 0 by (meson cell_algebra_cell_decomp)\n    obtain S' where S'_def: \"S' = cell_disjointify a S\"\n      by blast \n    have 1: \" \\<Union> (insert a A) = \\<Union> S'\"\n      unfolding S'_def using S_def \n      by (simp add: cell_disjointify_union)\n    have 2: \"a \\<in> Cells\"\n      using AA by blast \n    have 3: \"S' \\<subseteq> cell_algebra Cells\"\n    proof fix x assume AA: \"x \\<in> S'\"\n      show \"x \\<in> cell_algebra Cells\"\n        using AA unfolding S'_def unfolding cell_disjointify_def \n        apply(cases \"x = a - \\<Union> S\")\n        using 2 assms cell_algebra_minus_union[of Cells a S] S_def \n        apply simp\n        apply(cases \"x \\<in> (\\<inter>) a ` S\")\n        using assms(1)[of a ] S_def AA 2 apply auto[1]\n        using assms(2)[of _ a ] S_def AA 2 by auto \n    qed\n    show \"\\<Union> (insert a A) \\<in> cell_algebra Cells\"\n      unfolding 1 using  3 S'_def cell_disjointify_disjoint S_def \n      by (metis cell_algebra_finite_disjoint_union cell_disjointify_def finite_UnI finite_imageI finite_insert)\n  qed\n  thus \"\\<Union> S \\<in> cell_algebra Cells\"\n    using A by blast \nqed\nend\n\n(**************************************************************************************************)\n(**************************************************************************************************)\nsubsection\\<open>Cells Whose Convex Condition is a Single Point\\<close>\n(**************************************************************************************************)\n(**************************************************************************************************)\n\ntext\\<open>Given a cell $\\mathcal{C}$\\texttt{ = Cond m C c a1 a2 I}, we will frequently be interested in \ndecomposing $\\mathcal{C}$ into pieces where \n\\texttt{val (t }$\\ominus$\\texttt{ c x) = val (}$\\varphi$\\texttt{ x)} for some fixed semialgebriaic \nfunction $\\varphi$. This section elaborates on the properties of sets which can be decomposed into \nfinite disjoint unions of such cells. Our main concern will be showing that these structures form \nwhat we called a cell algebra in the previous section. This will be used to proved that finite \n(possibly not disjoint) unions of sets which can be decomposed into these cells can again be \ndecomposed into these cells.  \\<close>\n\ncontext padic_fields\nbegin\n\nlemma one_point_closed_interval:\n\"condition_to_set (Cond m C c f f closed_interval) = {as \\<in> carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>). tl as \\<in> C \\<and> val (hd as \\<ominus> c (tl as)) =  val (f (tl as))}\"\n  unfolding condition_to_set.simps  cell_def closed_interval_def mem_Collect_eq \n  apply(rule equalityI')\n  unfolding mem_Collect_eq using basic_trans_rules(24) apply blast\n   by (metis basic_trans_rules(20) notin_closed)\n\nlemma finite_closed_interval_cell_intersection:\n  shows \n\"condition_to_set (Cond m C c f f closed_interval) \\<inter> condition_to_set (Cond m C' c g g closed_interval)\n = condition_to_set (Cond m (C \\<inter> C' \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)}) c f f closed_interval)\"\n  unfolding one_point_closed_interval apply(rule equalityI')\n  by(auto simp: Qp_pow_ConsE(1))\n\nlemma finite_closed_interval_cell_diff:\n  shows \"condition_to_set (Cond m C c f f closed_interval) - condition_to_set (Cond m C' c g g closed_interval) \n          = condition_to_set (Cond m ((C \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)}) - C' \\<union> (C - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)}) ) c f f closed_interval)\"\n  unfolding one_point_closed_interval\n  apply(rule equalityI')\n  unfolding mem_Collect_eq \n  apply (metis (mono_tags, lifting) DiffD1 DiffD2 DiffI Int_iff UnCI mem_Collect_eq)\n  using Qp_pow_ConsE(1) by auto\n  \ndefinition c_cells_at_one_val_point where\n\"c_cells_at_one_val_point m c Fs C = \n    {\\<C>. condition_to_set \\<C>  \\<subseteq> C \\<and> is_cell_condition \\<C> \\<and> arity \\<C> = m \\<and> \n      center \\<C> = c \\<and> u_bound \\<C> = l_bound \\<C> \\<and> u_bound \\<C> \\<in> Fs \\<and>\n       boundary_condition \\<C> = closed_interval }\"\n\ndefinition one_val_point_c_decomposable where\n\"one_val_point_c_decomposable m c Fs C A = \n          (\\<exists>S. is_cell_decomp m S A \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs C)\"\n\ndefinition one_val_point_decomposables where\n\"one_val_point_decomposables m c Fs C = {A. one_val_point_c_decomposable m c Fs C A}\"\n\nlemma  c_cells_at_one_val_point_is_c_decomposable:\n  assumes \"A \\<in> c_cells_at_one_val_point m c Fs C\"\n  shows \"condition_to_set A \\<in> one_val_point_decomposables m c Fs C\"\nproof-\n  have 0: \"arity A = m\"\n    using assms unfolding c_cells_at_one_val_point_def by blast \n  have 1: \"is_cell_decomp m {A} (condition_to_set A)\"\n    apply(rule is_cell_decompI)\n        apply blast\n    apply(rule is_partitionI)\n    apply(rule disjointI)\n        apply blast \n    apply blast \n    using assms unfolding c_cells_at_one_val_point_def apply blast \n    using condition_decomp'[of A]  condition_to_set.simps  cell_def 0 \n    apply (meson cell_condition_to_set_subset)\n    by blast \n  show \"condition_to_set A \\<in> one_val_point_decomposables m c Fs C\"\n    unfolding one_val_point_decomposables_def one_val_point_c_decomposable_def mem_Collect_eq \n    using 0 1 assms by blast \nqed\n\nlemma one_val_point_decomposables_disjoint_union:\n  assumes \"A \\<in> one_val_point_decomposables m c Fs C\"\n  assumes \"B \\<in> one_val_point_decomposables m c Fs C\"\n  assumes \"A \\<inter> B = {}\"\n  shows \"A \\<union> B \\<in> one_val_point_decomposables m c Fs C\"\nproof-\n  obtain S1 where S1_def: \"is_cell_decomp m S1 A \\<and> S1 \\<subseteq> c_cells_at_one_val_point m c Fs C\"\n    using assms unfolding one_val_point_decomposables_def \n    by (metis one_val_point_c_decomposable_def mem_Collect_eq)\n  obtain S2 where S2_def: \"is_cell_decomp m S2 B \\<and> S2 \\<subseteq> c_cells_at_one_val_point m c Fs C\"\n    using assms unfolding one_val_point_decomposables_def \n    by (metis one_val_point_c_decomposable_def mem_Collect_eq)    \n  have p: \"A \\<union> B - A = B - A\"\n    by auto \n  have q: \"B - A = B\"\n    using assms by auto \n  have \"is_cell_decomp m (S1 \\<union> S2) (A \\<union> B)\"\n    apply(rule cell_decomp_union[of \"A\"])\n       apply blast \n    using S1_def S2_def is_cell_decompE(6) apply auto[1]\n    using S1_def apply blast \n    unfolding p q using S2_def  by auto \n  thus ?thesis \n    unfolding one_val_point_decomposables_def one_val_point_c_decomposable_def mem_Collect_eq \n    using S1_def S2_def \n    by auto\nqed\n\nlemma one_val_point_c_cell_diff:\n  assumes \"A \\<in> c_cells_at_one_val_point m c Fs C\"\n  assumes \"B \\<in> c_cells_at_one_val_point m c Fs C\"\n  shows \"\\<exists>D \\<in> c_cells_at_one_val_point m c Fs C. \n            condition_to_set A - condition_to_set B = condition_to_set D\"\n          \"condition_to_set A - condition_to_set B \\<in> one_val_point_decomposables m c Fs C\"\nproof- \n  obtain A0 f where fA0_def: \"f \\<in> Fs\" \"A = Cond m A0 c f f closed_interval\"\n    using assms unfolding c_cells_at_one_val_point_def \n    by (metis (mono_tags, lifting) condition_decomp' mem_Collect_eq)\n  obtain B0 g where gB0_def: \"g \\<in> Fs\" \"B = Cond m B0 c g g  closed_interval\"\n    using assms unfolding c_cells_at_one_val_point_def \n    by (metis (mono_tags, lifting) condition_decomp' mem_Collect_eq)\n  have AinC: \"condition_to_set A \\<subseteq> C\"\n    using assms unfolding fA0_def c_cells_at_one_val_point_def mem_Collect_eq by blast \n  have 0: \"condition_to_set A - condition_to_set B = condition_to_set\n     (Cond m (A0 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)} - B0 \\<union> (A0 - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})) c f f\n       closed_interval)\"\n    unfolding fA0_def gB0_def finite_closed_interval_cell_diff by blast \n  have A0_semialg: \"is_semialgebraic m A0\"\n    using assms unfolding fA0_def c_cells_at_one_val_point_def mem_Collect_eq  \n    using is_cell_conditionE(1) by blast\n  have B0_semialg: \"is_semialgebraic m B0\"\n    using assms unfolding gB0_def c_cells_at_one_val_point_def mem_Collect_eq   \n    using is_cell_conditionE''(1) by blast\n  have 1: \"f \\<in> carrier (SA m)\"\n    using assms unfolding gB0_def c_cells_at_one_val_point_def mem_Collect_eq   \n    using is_cell_conditionE'' by (metis fA0_def)\n  have 2: \"g \\<in> carrier (SA m)\"\n    using assms unfolding gB0_def c_cells_at_one_val_point_def mem_Collect_eq   \n    using is_cell_conditionE'' by (metis gB0_def)    \n  have 3: \"is_semialgebraic m {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)}\"\n    using 1 2 semialg_val_eq_set_is_semialg by blast\n  have 4: \"c \\<in> carrier (SA m)\"\n    using assms unfolding gB0_def c_cells_at_one_val_point_def mem_Collect_eq   \n    using is_cell_conditionE'' by (metis gB0_def)    \n  have 5: \"is_cell_condition (Cond m (A0 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)} - B0 \\<union> (A0 - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})) c f f\n       closed_interval)\"\n    apply(rule is_cell_conditionI') \n        apply(rule union_is_semialgebraic ) apply(rule diff_is_semialgebraic) apply(rule intersection_is_semialg)\n    using A0_semialg apply blast using 3 apply blast using  B0_semialg apply blast \n    apply(rule diff_is_semialgebraic) using A0_semialg apply blast using 3 apply blast\n    using 4 apply blast using 1 apply blast using 1 apply blast unfolding is_convex_condition_def by blast \n  have 6: \"is_cell_decomp m {Cond m (A0 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)} - B0 \\<union> (A0 - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})) c f f\n       closed_interval}\n         (condition_to_set\n           (Cond m (A0 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)} - B0 \\<union> (A0 - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})) c f f\n             closed_interval))\"\n    apply(rule is_cell_decompI)\n        apply blast \n       apply(rule is_partitionI)\n    apply(rule disjointI)\n        apply blast \n       apply blast \n    using 5 condition_decomp(1) apply blast\n    unfolding condition_to_set.simps cell_def apply blast \n    by blast \n  have 7: \"condition_to_set\n     (Cond m (A0 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)} - B0 \\<union> (A0 - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})) c f f\n       closed_interval)\n    \\<subseteq> C\"\n    using AinC 0 by blast \n  have 8: \"Cond m (A0 \\<inter> {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)} - B0 \\<union> (A0 - {x \\<in> carrier (Q\\<^sub>p\\<^bsup>m\\<^esup>). val (f x) = val (g x)})) c f f\n       closed_interval \\<in> c_cells_at_one_val_point m c Fs C \"\n    unfolding c_cells_at_one_val_point_def mem_Collect_eq arity.simps u_bound.simps l_bound.simps boundary_condition.simps center.simps \n    using 5 7 fA0_def by blast\n  show \"condition_to_set A - condition_to_set B \\<in> one_val_point_decomposables m c Fs C\"\n    unfolding 0 one_val_point_decomposables_def one_val_point_c_decomposable_def mem_Collect_eq \n    using 5 6 7 8 by blast \n  show \"\\<exists>D\\<in>c_cells_at_one_val_point m c Fs C. condition_to_set A - condition_to_set B = condition_to_set D\"\n    using 0 c_cells_at_one_val_point_def \n    using \"8\" by blast\nqed\n\nlemma empty_is_one_val_point_c_cell:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"f \\<in> Fs\"\n  assumes \"f \\<in> carrier (SA m)\"\n  shows \"{} \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs C \"\nproof-\n  obtain \\<C> where \\<C>_def: \"\\<C> = Cond m {} c f f closed_interval\"\n    by blast\n  have 0: \"is_cell_condition \\<C>\"\n    unfolding \\<C>_def apply(rule is_cell_conditionI')\n  apply (simp add: empty_is_semialgebraic)\n  apply (simp add: assms)\n  using assms apply blast\n  using assms apply blast\n  using is_convex_condition_def by auto\n  have 1: \"\\<C> \\<in> c_cells_at_one_val_point m c Fs C \"\n    using 0 assms\n    unfolding \\<C>_def c_cells_at_one_val_point_def mem_Collect_eq arity.simps center.simps u_bound.simps l_bound.simps boundary_condition.simps condition_to_set.simps cell_def by blast \n  have 2: \"{} = condition_to_set \\<C>\"\n    unfolding \\<C>_def condition_to_set.simps cell_def by blast \n  show \" {} \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs C\"\n    unfolding  2 using 0 1 assms by blast\nqed\n\nlemma empty_one_val_point_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"f \\<in> Fs\"\n  assumes \"f \\<in> carrier (SA m)\"\n  shows \"one_val_point_c_decomposable m c Fs C {}\"\n  using assms empty_is_one_val_point_c_cell[of c m f Fs C] c_cells_at_one_val_point_is_c_decomposable[of _ m c Fs C]\n  unfolding one_val_point_decomposables_def mem_Collect_eq \n  by (metis image_iff)\n\nlemma finite_disjoint_union_one_val_point_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"disjoint S\"\n  assumes \"finite S\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"\\<And>s. s \\<in> S \\<Longrightarrow> one_val_point_c_decomposable m c Fs C s\"\n  shows \"one_val_point_c_decomposable m c Fs C (\\<Union> S)\"\nproof- \n  have \"disjoint S \\<and> (\\<forall>s \\<in> S. one_val_point_c_decomposable m c Fs C s) \\<longrightarrow> one_val_point_c_decomposable m c Fs C (\\<Union> S)\"\n  proof(rule finite.induct[of S])\n    obtain f where f_def: \"f \\<in> Fs\"\n      using assms by auto \n    have f_semialg: \"f \\<in> carrier (SA m)\"\n      using f_def assms by auto \n    show \"finite S\"\n      using assms by blast \n    show \"disjoint {} \\<and> (\\<forall>s\\<in>{}. one_val_point_c_decomposable m c Fs C s) \\<longrightarrow> one_val_point_c_decomposable m c Fs C (\\<Union> {})\"\n      unfolding disjoint_def using assms f_def empty_one_val_point_c_decomposable[of c m f Fs C] f_semialg\n      by (metis Sup_empty)\n    show \"\\<And>A a. finite A \\<Longrightarrow>\n           disjoint A \\<and> (\\<forall>s\\<in>A. one_val_point_c_decomposable m c Fs C s) \\<longrightarrow> one_val_point_c_decomposable m c Fs C (\\<Union> A) \\<Longrightarrow>\n           disjoint (insert a A) \\<and> (\\<forall>s\\<in>insert a A. one_val_point_c_decomposable m c Fs C s) \\<longrightarrow>\n           one_val_point_c_decomposable m c Fs C (\\<Union> (insert a A))\"\n    proof fix A a \n      assume A: \"finite A\"\n           \"disjoint A \\<and> (\\<forall>s\\<in>A. one_val_point_c_decomposable m c Fs C s) \\<longrightarrow> one_val_point_c_decomposable m c Fs C (\\<Union> A)\"\n           \"disjoint (insert a A) \\<and> (\\<forall>s\\<in>insert a A. one_val_point_c_decomposable m c Fs C s)\"\n      show \" one_val_point_c_decomposable m c Fs C (\\<Union> (insert a A))\"\n        apply(cases \"a \\<in> A\")\n        using A \n        apply (metis insert_absorb)\n      proof-\n        assume 00: \"a \\<notin> A\"\n        have 0: \"disjoint A\"\n          using A unfolding disjoint_def by blast \n        have 1: \"(\\<forall>s\\<in>A. one_val_point_c_decomposable m c Fs C s)\"\n          using A by blast \n        have 2: \"\\<Union>A \\<inter>  a = {}\"\n        proof(rule equalityI')\n          show \"\\<And>x. x \\<in> \\<Union> A \\<inter> a \\<Longrightarrow> x \\<in> {}\"\n          proof- fix x assume A0: \"x \\<in> \\<Union> A \\<inter> a\"\n            then obtain s where s_def: \"s \\<in> A \\<and> x \\<in> s \\<inter> a\"\n              by blast \n            then have \"s \\<inter> a = {}\"\n              using 0 1 A disjointE[of \"insert a A\" s a] 00  by blast \n            then show \"x \\<in> {}\"\n              using s_def by blast \n          qed\n          show \"\\<And>x. x \\<in> {} \\<Longrightarrow> x \\<in> \\<Union> A \\<inter> a\" by blast \n        qed\n        have 3: \"one_val_point_c_decomposable m c Fs C  a\"\n          using A by blast \n        have 4: \"one_val_point_c_decomposable m c Fs C (\\<Union> A)\"\n          using A 0 1 by blast \n        hence \"one_val_point_c_decomposable m c Fs C (\\<Union>A \\<union> a)\"\n          using 2 3 4 one_val_point_decomposables_disjoint_union unfolding one_val_point_decomposables_def mem_Collect_eq \n          by blast \n        thus ?thesis \n          by (simp add: Un_commute)\n      qed\n    qed\n  qed\n  then show ?thesis \n    using assms by blast \nqed\n\nlemma one_val_point_c_decomposable_minus_one_val_point_c_cell_one_val_point_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"A \\<in> one_val_point_decomposables m c Fs C\"\n  assumes \"\\<C> \\<in> c_cells_at_one_val_point m c Fs C \"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  shows \"one_val_point_c_decomposable m c Fs C (A - condition_to_set \\<C>)\"\nproof-\n  obtain S where S_def: \"is_cell_decomp m S A \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs C\"\n    using assms unfolding one_val_point_decomposables_def one_val_point_c_decomposable_def mem_Collect_eq by blast \n  have 0: \"disjoint (condition_to_set ` S)\"\n    apply(rule disjointI)\n    using S_def is_cell_decompE(5)[of m S A] by blast  \n  have 1: \"A - condition_to_set \\<C> = (\\<Union> s \\<in> S. condition_to_set s - condition_to_set \\<C>)\"\n    using S_def is_cell_decompE(2)[of m S A] is_partitionE(2)[of \"condition_to_set ` S\" A]\n    by blast \n  have  2: \"disjoint ((\\<lambda>s . condition_to_set s - condition_to_set \\<C>) ` S)\"\n  proof(rule disjointI) fix a b assume A: \" a \\<in> (\\<lambda>s. condition_to_set s - condition_to_set \\<C>) ` S \"\n           \"b \\<in> (\\<lambda>s. condition_to_set s - condition_to_set \\<C>) ` S\" \"a \\<noteq> b\"\n    then obtain s where s_def: \"s \\<in> S \\<and> a =   condition_to_set s - condition_to_set \\<C>\"\n      by (metis (no_types, lifting) imageE image_restrict_eq)\n    then obtain s' where s'_def: \"s' \\<in> S \\<and> b =   condition_to_set s' - condition_to_set \\<C>\"\n      using A by (metis (no_types, lifting) imageE image_restrict_eq)\n    have \"s \\<noteq> s'\"\n      using s_def s'_def A by blast \n    hence \"condition_to_set s \\<inter> condition_to_set s' = {}\"\n      using s_def s'_def is_cell_decompE S_def \n      by meson\n    thus \"a \\<inter> b = {}\"\n      using s_def s'_def  A  0 disjointE by blast \n  qed\n  have 3: \"\\<And>s. s \\<in> S \\<Longrightarrow> one_val_point_c_decomposable m c Fs C (condition_to_set s - condition_to_set \\<C>)\"\n  proof-\n    fix s assume A: \"s \\<in> S\"\n    obtain B f where Bf_def: \"s = Cond m B c f f closed_interval\"\n      using A S_def is_cell_decompE(4)[of m S A s] unfolding c_cells_at_one_val_point_def  \n      using Diff_eq_empty_iff Diff_iff all_not_in_conv mem_Collect_eq \n            condition_decomp'[of s] by auto \n    show \" one_val_point_c_decomposable m c Fs C (condition_to_set s - condition_to_set \\<C>)\"\n    using assms S_def one_val_point_c_cell_diff unfolding  one_val_point_decomposables_def mem_Collect_eq  \n    using A by blast\n  qed\n  show \"one_val_point_c_decomposable m c Fs C (A - condition_to_set \\<C>)\"\n    unfolding 1 \n    apply(rule finite_disjoint_union_one_val_point_c_decomposable)\n    using assms apply blast \n    using 2 apply blast \n    using S_def is_cell_decompE(1) apply blast \n    using assms using 3 by auto \nqed\n\nlemma one_val_point_c_decomposable_diff0:\n  assumes \"c \\<in> carrier (SA m)\" \n  assumes \"one_val_point_c_decomposable m c Fs A C\"\n  assumes \"S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs A\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  shows \"one_val_point_c_decomposable m c Fs A (C - B)\"\nproof- \n  obtain n where n_def: \"n = card S\"\n    by blast \n  have \"\\<forall> C S B . one_val_point_c_decomposable m c Fs A C \\<longrightarrow> ( n = card S \\<longrightarrow> ((S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A)) \\<longrightarrow>  one_val_point_c_decomposable m c Fs A (C - B))\"\n  proof(induction n)\n    case 0\n    then show ?case  \n      by (metis bot_nat_def card_0_eq padic_fields.is_cell_decompE(1) padic_fields_axioms)\n  next\n    case (Suc n) fix n \n    assume IH: \" \\<forall>C S B.\n            one_val_point_c_decomposable m c Fs A C \\<longrightarrow>\n            n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n    show \" \\<forall>C S B.\n            one_val_point_c_decomposable m c Fs A C \\<longrightarrow>\n            Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n    proof fix C \n      show \"\\<forall>S B. one_val_point_c_decomposable m c Fs A C \\<longrightarrow>\n               Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n      proof fix S \n        show \"\\<forall>B. one_val_point_c_decomposable m c Fs A C \\<longrightarrow>\n             Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n        proof fix B \n          show \"one_val_point_c_decomposable m c Fs A C \\<longrightarrow>\n         Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n          proof assume A0: \"one_val_point_c_decomposable m c Fs A C \"\n            show \"Suc n = card S \\<longrightarrow> S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n            proof assume A1: \"Suc n = card S\"\n              show \"S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<longrightarrow> one_val_point_c_decomposable m c Fs A (C - B)\"\n              proof assume A2: \" S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A\"\n                show \"one_val_point_c_decomposable m c Fs A (C - B)\"\n                proof- \n                  obtain C' where C'_def: \"C' \\<in> S\" using A2 by blast \n                  obtain S' where S'_def: \"S' = S - {C'}\" by blast \n                  obtain D where D_def: \"D = (\\<Union> c \\<in> S'. condition_to_set c)\"\n                    by blast \n                  have 00: \"\\<Union> (condition_to_set ` (S - {C'})) \\<subseteq> \\<Union> (condition_to_set ` S) \"\n                    by blast\n                  have 0: \"is_cell_decomp m S' D \\<and>  S' \\<subseteq> c_cells_at_one_val_point m c Fs A\"\n                  proof\n                    show \"is_cell_decomp m S' D\"\n                      apply(rule is_cell_decompI) \n                      unfolding S'_def using A2 is_cell_decompE(1) apply blast\n                         apply(rule is_partitionI) using A2 is_cell_decompE(2)[of m S B] \n                      unfolding disjoint_def using  is_partitionE(1)[of \"condition_to_set ` S\" B]  \n                      apply (metis (mono_tags, lifting) DiffD1 image_iff disjoint_def)\n                        unfolding D_def S'_def apply blast \n                        using A2 is_cell_decompE(4)[of m S B] \n                        apply (meson DiffD1 is_cell_decompE(3))\n                        using A2 is_cell_decompE(2)[of m S B] is_partitionE[of \"condition_to_set ` S\" B]\n                              is_cell_decompE(6)[of m S B] 00 apply blast\n                        using A2 is_cell_decompE(2)[of m S B] is_partitionE(1)[of \"condition_to_set ` S\" B]\n                        unfolding disjoint_def using is_cell_decompE(6)[of m S B] 00 \n                        by (meson Diff_iff is_cell_decompE(5))\n                      show \" S' \\<subseteq> c_cells_at_one_val_point m c Fs A\"\n                        using A2 unfolding S'_def by blast\n                  qed\n                  have 1: \"one_val_point_c_decomposable m c Fs A (C - D)\"\n                  proof(cases \"D = {}\")\n                    case True\n                    then show ?thesis using A0 unfolding True by simp\n                  next\n                    case False\n                    have F0: \"S' \\<noteq> {}\"\n                    proof assume A: \"S' = {}\"\n                      then have \"D = {}\"\n                        using 0 is_cell_decompE(2)[of m S' D] is_partitionE[of \"condition_to_set ` S'\" D]\n                        unfolding A by blast\n                      then show False using False by blast \n                    qed\n                    have F1: \"one_val_point_c_decomposable m c Fs A D\"\n                      unfolding one_val_point_c_decomposable_def \n                      using \"0\" by auto\n                    have F2: \"\\<And> C S B. one_val_point_c_decomposable m c Fs A C \\<Longrightarrow> n = card S \\<Longrightarrow> \n                                    S \\<noteq> {} \\<and> is_cell_decomp m S B \\<and>  S \\<subseteq> c_cells_at_one_val_point m c Fs A \\<Longrightarrow>\n                                     one_val_point_c_decomposable m c Fs A (C - B)\"\n                      using IH by blast \n                    have F3: \"n = card (S - {C'})\"\n                      by (metis A1 C'_def Diff_empty card.infinite card_Diff_insert diff_Suc_1 mem_simps(2) zero_less_Suc zero_less_iff_neq_zero)\n                    show ?thesis\n                      using A0 F0 F2[of C S' D] 0 F1 F3  unfolding S'_def  by blast \n                  qed\n                  have 2: \"B = \\<Union> (condition_to_set ` S)\"\n                    using A2 is_cell_decompE(2)[of m S B] is_partitionE[of \"condition_to_set ` S\" B] by blast \n                  have 3: \"C - B = (C - D) - condition_to_set C'\"\n                    unfolding D_def S'_def 2 using C'_def by blast \n                  have 5: \"condition_to_set C' \\<subseteq> A \\<and>\n             is_cell_condition C' \\<and> arity C' = m \\<and> center C' = c \\<and> u_bound C' = l_bound C'\\<and> u_bound C' \\<in> Fs \\<and> boundary_condition C' = closed_interval\"\n using C'_def A2 is_cell_decompE condition_decomp'[of C'] unfolding c_cells_at_one_val_point_def  by blast \n                  then obtain D' a  where  def: \"C' = Cond m D' c a a closed_interval\"\n                    using C'_def A2 is_cell_decompE condition_decomp'[of C'] unfolding c_cells_at_one_val_point_def \n                    by metis\n                  have 4: \"one_val_point_c_decomposable m c Fs A ((C - D) - condition_to_set C')\"\n                    apply(rule one_val_point_c_decomposable_minus_one_val_point_c_cell_one_val_point_c_decomposable)\n                    using assms unfolding one_val_point_c_decomposable_def apply blast \n                    using 1 unfolding one_val_point_decomposables_def mem_Collect_eq  apply blast \n                    using def C'_def A2 is_cell_decompE(3)[of m S B C'] \n                     unfolding c_cells_at_one_val_point_def mem_Collect_eq \n                     using 5 assms by auto              \n                  show ?thesis using 4 unfolding D_def S'_def \n                    using A2 is_cell_decompE(2) is_partitionE (2) \"3\" \"4\" by presburger\n                qed\n              qed\n            qed\n          qed\n        qed\n      qed\n    qed\n  qed\n  then show ?thesis using assms n_def by blast\nqed\n\nlemma one_val_point_c_decomposable_nonempty:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"one_val_point_c_decomposable m c Fs A C\"\n  shows \"\\<exists>S. S \\<noteq> {} \\<and> is_cell_decomp m S C \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs A\"\nproof(cases \"C = {}\")\n  case True\n  obtain f where f_def: \"f \\<in> Fs\"\n    using assms by auto \n  obtain \\<C> where \\<C>_def: \"\\<C> = Cond m {} c f f  closed_interval\"\n    by blast\n  have 0: \"is_cell_condition \\<C>\"\n    unfolding \\<C>_def apply(rule is_cell_conditionI')\n  apply (simp add: empty_is_semialgebraic)\n  apply (simp add: assms)\n  using assms f_def assms f_def is_convex_condition_def by auto\n  have 1: \"\\<C> \\<in> c_cells_at_one_val_point m c Fs A\"\n    using 0 assms f_def\n    unfolding \\<C>_def c_cells_at_one_val_point_def mem_Collect_eq arity.simps center.simps\n u_bound.simps l_bound.simps boundary_condition.simps condition_to_set.simps cell_def\n    by auto \n  have 2: \"{} = condition_to_set \\<C>\"\n    unfolding \\<C>_def condition_to_set.simps cell_def by blast \n  have 3: \"{\\<C>} \\<noteq> {} \\<and> is_cell_decomp m {\\<C>} C \\<and> {\\<C>} \\<subseteq> c_cells_at_one_val_point m c Fs A\"\n    apply(rule conjI)\n     apply blast \n    apply(rule conjI)\n    apply(rule is_cell_decompI)\n         apply blast apply(rule is_partitionI)\n         apply(rule disjointI) apply blast unfolding True \\<C>_def using 2  \\<C>_def apply blast\n    using arity.simps \\<C>_def 0 apply blast \n      apply blast apply blast apply(rule subsetI) using 1 unfolding \\<C>_def by blast    \n  then show ?thesis by blast \nnext\n  case False\n  obtain S where S_def: \"is_cell_decomp m S C \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs A\"\n    using False assms  unfolding one_val_point_c_decomposable_def by blast \n  then have \"S \\<noteq> {}\"\n    using False  S_def is_cell_decompE is_partitionE \n    by (metis ccSup_empty image_empty)\n  then show ?thesis using S_def by blast \nqed\n\nlemma one_val_point_c_decomposable_diff:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"one_val_point_c_decomposable m c Fs A C\"\n  assumes \"one_val_point_c_decomposable m c Fs A B\"\n  shows \"one_val_point_c_decomposable m c Fs A (C - B)\"\n  using one_val_point_c_decomposable_diff0 assms one_val_point_c_decomposable_nonempty\n  by metis \n\nlemma one_val_point_decomposables_is_gen_boolean_algebra:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"C \\<in> one_val_point_decomposables m c Fs C\"\n  shows \"gen_boolean_algebra C (condition_to_set ` (c_cells_at_one_val_point m c Fs C)) =  (one_val_point_decomposables m c Fs C) \"\nproof\n  show \"gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C) \\<subseteq> one_val_point_decomposables m c Fs C\"\n  proof fix x assume A: \"x \\<in> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\n    show \"x \\<in> one_val_point_decomposables m c Fs C\"\n      apply(rule boolean_algebra_alt_induct[of x C \"(condition_to_set ` (c_cells_at_one_val_point m c Fs C))\"])\n      using A apply blast \n      using assms apply blast \n    proof- \n      show \"\\<And>A. A \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs C \\<Longrightarrow> A \\<inter> C \\<in> one_val_point_decomposables m c Fs C\"\n      proof-  fix A assume AA: \"A \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs C\"\n        then have \"A \\<subseteq> C\"\n          unfolding c_cells_at_one_val_point_def by blast \n        thus \"A \\<inter> C \\<in> one_val_point_decomposables m c Fs C\" \n          using c_cells_at_one_val_point_is_c_decomposable AA \n          by (metis image_iff inf_absorb1)\n      qed\n      show \"\\<And>A Ca.\n       A \\<in> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C) \\<Longrightarrow>\n       Ca \\<in> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C) \\<Longrightarrow>\n       A \\<in> one_val_point_decomposables m c Fs C \\<Longrightarrow>\n       Ca \\<in> one_val_point_decomposables m c Fs C \\<Longrightarrow> A \\<inter> Ca = {} \\<Longrightarrow> A \\<union> Ca \\<in> one_val_point_decomposables m c Fs C\"\n        using one_val_point_decomposables_disjoint_union by metis\n      show \" \\<And>A Ca.\n       A \\<in> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C) \\<Longrightarrow>\n       Ca \\<in> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C) \\<Longrightarrow>\n       A \\<in> one_val_point_decomposables m c Fs C \\<Longrightarrow> Ca \\<in> one_val_point_decomposables m c Fs C \\<Longrightarrow> A - Ca \\<in> one_val_point_decomposables m c Fs C\"\n        using one_val_point_c_decomposable_diff[of c m Fs C] assms \n        unfolding one_val_point_decomposables_def mem_Collect_eq by blast \n    qed\n  qed\n  show \"one_val_point_decomposables m c Fs C \\<subseteq> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\n  proof fix x assume A: \"x \\<in> one_val_point_decomposables m c Fs C\"\n    show \" x \\<in> gen_boolean_algebra C (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\n    proof-\n      obtain S where S_def: \"S \\<noteq> {} \\<and> is_cell_decomp m S x \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs C\"\n        using A assms one_val_point_c_decomposable_nonempty[of c m Fs C x] \n        unfolding one_val_point_decomposables_def mem_Collect_eq by blast         \n      have 0: \"x = (\\<Union> Y \\<in> S. condition_to_set Y )\"\n        using S_def \n        by (metis is_cell_decompE(2) is_partitionE(2))\n      have 1: \"\\<And>Y. Y \\<in> S \\<Longrightarrow> Y \\<in> c_cells_at_one_val_point m c Fs C\"\n        using S_def by blast \n      show ?thesis \n        unfolding 0 apply(rule gen_boolean_algebra_finite_union[of ])\n         apply(rule gen_boolean_algebra_generators) using S_def unfolding c_cells_at_one_val_point_def mem_Collect_eq \n        using 1 apply blast \n        using 0 1 S_def is_cell_decompE(1) unfolding  c_cells_at_one_val_point_def   \n        apply blast\n        using S_def is_cell_decompE by blast \n    qed\n  qed\nqed\n\nlemma c_cells_at_one_val_point_union0:\n  assumes \"\\<C> = (Cond m A c f f closed_interval)\"\n  assumes \"\\<C>' = (Cond m C c g g closed_interval)\"\n  assumes \"is_cell_condition \\<C>\"\n  assumes \"is_cell_condition \\<C>'\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"f \\<in> Fs\"\n  assumes \"g \\<in> Fs\"\n  shows \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (condition_to_set \\<C> \\<union> condition_to_set \\<C>')\"\nproof-\n  have 0: \"\\<C> \\<in> c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    using assms \n    unfolding c_cells_at_one_val_point_def mem_Collect_eq assms arity.simps\n              center.simps u_bound.simps l_bound.simps boundary_condition.simps condition_to_set.simps cell_def \n    by blast \n  have 1: \"\\<C>' \\<in> c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    using assms \n    unfolding c_cells_at_one_val_point_def mem_Collect_eq assms arity.simps\n              center.simps u_bound.simps l_bound.simps boundary_condition.simps condition_to_set.simps cell_def \n    by blast \n  have 2: \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (condition_to_set \\<C>)\"\n    using assms 0 c_cells_at_one_val_point_is_c_decomposable \n    unfolding one_val_point_decomposables_def mem_Collect_eq   by blast \n  have 3: \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (condition_to_set \\<C>')\"\n    using assms 1 c_cells_at_one_val_point_is_c_decomposable \n    unfolding one_val_point_decomposables_def mem_Collect_eq   by blast \n  have 4: \"condition_to_set \\<C> \\<union> condition_to_set \\<C>' = \n      (condition_to_set \\<C> - condition_to_set \\<C>') \\<union> (condition_to_set \\<C>' - condition_to_set \\<C>) \\<union> (condition_to_set \\<C> \\<inter> condition_to_set \\<C>')\"\n    by blast \n  have 5: \"(condition_to_set \\<C> - condition_to_set \\<C>') \\<union> (condition_to_set \\<C>' - condition_to_set \\<C>) \\<in> one_val_point_decomposables m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    apply(rule one_val_point_decomposables_disjoint_union)\n    unfolding one_val_point_decomposables_def mem_Collect_eq \n    apply(rule one_val_point_c_decomposable_minus_one_val_point_c_cell_one_val_point_c_decomposable)\n    using assms unfolding assms using is_cell_conditionE apply blast\n    using 2 unfolding one_val_point_decomposables_def mem_Collect_eq assms apply blast \n    using 1 unfolding one_val_point_decomposables_def mem_Collect_eq assms apply blast\n    using assms apply blast using assms apply blast\n    apply(rule one_val_point_c_decomposable_minus_one_val_point_c_cell_one_val_point_c_decomposable)\n    using assms unfolding assms using is_cell_conditionE apply blast\n    using 3 0 assms one_val_point_decomposables_def mem_Collect_eq assms by auto \n  have 6: \"(condition_to_set \\<C> \\<inter> condition_to_set \\<C>')  \\<in> one_val_point_decomposables m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    unfolding assms finite_closed_interval_cell_intersection\n    apply(rule c_cells_at_one_val_point_is_c_decomposable )\n    unfolding c_cells_at_one_val_point_def mem_Collect_eq arity.simps center.simps u_bound.simps l_bound.simps boundary_condition.simps \n    apply(rule conjI)\n    unfolding condition_to_set.simps cell_def apply blast \n    apply(rule conjI)\n     apply(rule is_cell_conditionI')\n         apply(rule intersection_is_semialg)\n    apply(rule intersection_is_semialg)\n    using assms unfolding assms using is_cell_conditionE apply blast \n    using assms unfolding assms using is_cell_conditionE apply blast \n    using assms unfolding assms \n    using is_cell_conditionE(3)[of m A c f f closed_interval] is_cell_conditionE(3)[of m C c g g closed_interval]\n          semialg_val_eq_set_is_semialg apply blast\n     using assms unfolding assms using is_cell_conditionE apply blast \n    using assms unfolding assms using is_cell_conditionE apply blast \n    using assms unfolding assms using is_cell_conditionE apply blast \n    using assms unfolding assms using is_cell_conditionE apply meson \n    using assms by auto \n  have 7: \"(condition_to_set \\<C> - condition_to_set \\<C>') \\<union> (condition_to_set \\<C>' - condition_to_set \\<C>) \\<union> (condition_to_set \\<C> \\<inter> condition_to_set \\<C>') \\<in> \none_val_point_decomposables m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    apply(rule one_val_point_decomposables_disjoint_union)\n    using 5 apply blast using 6 apply blast by blast \n  thus ?thesis unfolding one_val_point_decomposables_def mem_Collect_eq 4 by blast\nqed\n\nlemma c_cells_at_one_val_point_union:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"\\<C> \\<in> c_cells_at_one_val_point m c Fs C\"\n  assumes \"\\<C>' \\<in> c_cells_at_one_val_point m c Fs C\"\n  shows \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (condition_to_set \\<C> \\<union> condition_to_set \\<C>')\"\nproof- \n  obtain A f where Af_def: \"f \\<in> Fs\" \"\\<C> = (Cond m A c f f closed_interval)\"\n    using assms condition_decomp'  unfolding c_cells_at_one_val_point_def mem_Collect_eq \n    by metis\n  obtain C g where Bg_def: \"g \\<in> Fs\" \"\\<C>' = (Cond m C c g g closed_interval)\"\n    using assms condition_decomp'  unfolding c_cells_at_one_val_point_def mem_Collect_eq \n    by metis\n  show ?thesis \n    apply(rule c_cells_at_one_val_point_union0[of _ _ A _ f _ C g])\n    unfolding Af_def Bg_def apply blast apply blast \n    using assms unfolding Af_def c_cells_at_one_val_point_def mem_Collect_eq apply blast  \n    using assms Af_def Bg_def unfolding Bg_def c_cells_at_one_val_point_def mem_Collect_eq by auto  \nqed\n\nlemma c_cells_at_one_val_point_intersection:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \"\\<C> \\<in> c_cells_at_one_val_point m c Fs C\"\n  assumes \"\\<C>' \\<in> c_cells_at_one_val_point m c Fs C\"\n  shows \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (condition_to_set \\<C> \\<inter> condition_to_set \\<C>')\"\nproof- \n  obtain A f where Af_def:\"f \\<in> Fs\" \"\\<C> = (Cond m A c f f closed_interval)\"\n    using assms condition_decomp'  unfolding c_cells_at_one_val_point_def mem_Collect_eq \n    by metis\n  obtain C g where Bg_def:\"g \\<in> Fs\" \"\\<C>' = (Cond m C c g g closed_interval)\"\n    using assms condition_decomp'  unfolding c_cells_at_one_val_point_def mem_Collect_eq \n    by metis\n  have \" (condition_to_set \\<C> \\<inter> condition_to_set \\<C>') \\<in> one_val_point_decomposables m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\" \n    unfolding Af_def Bg_def finite_closed_interval_cell_intersection\n    apply(rule c_cells_at_one_val_point_is_c_decomposable ) \n    unfolding c_cells_at_one_val_point_def mem_Collect_eq arity.simps center.simps u_bound.simps l_bound.simps boundary_condition.simps \n              condition_to_set.simps cell_def \n    apply(rule conjI)\n    apply blast \n    apply(rule conjI)\n    apply(rule is_cell_conditionI')\n     apply(rule intersection_is_semialg)\n    apply(rule intersection_is_semialg)\n    using assms unfolding assms c_cells_at_one_val_point_def mem_Collect_eq  Af_def Bg_def using is_cell_conditionE apply blast \n    using assms unfolding assms c_cells_at_one_val_point_def mem_Collect_eq  Af_def Bg_def using is_cell_conditionE apply blast \n    using assms is_cell_conditionE(3)[of m A c f f closed_interval] is_cell_conditionE(3)[of m C c g g closed_interval]\n          semialg_val_eq_set_is_semialg unfolding assms c_cells_at_one_val_point_def mem_Collect_eq  Af_def Bg_def apply blast\n    using assms unfolding assms using is_cell_conditionE apply blast\n    using assms Af_def is_convex_condition_def by auto\n  then show ?thesis  unfolding one_val_point_decomposables_def mem_Collect_eq by blast \nqed\n\nlemma one_val_point_decomposables_is_cell_algebra:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  shows \"one_val_point_decomposables m c Fs C = cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\nproof\n  obtain f where f_def: \"f \\<in> Fs\"\n    using assms by auto \n  show \" one_val_point_decomposables m c Fs C \\<subseteq> cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\n  proof fix x assume A: \"x \\<in> one_val_point_decomposables m c Fs C\"\n    then obtain S where S_def: \"is_cell_decomp m S x \\<and> S \\<subseteq> c_cells_at_one_val_point m c Fs C\"\n      unfolding one_val_point_decomposables_def mem_Collect_eq one_val_point_c_decomposable_def\n      by blast \n    have 0: \"x = \\<Union> (condition_to_set ` S)\"\n      using S_def is_cell_decompE(2)[of m S x] is_partitionE[of \"condition_to_set ` S \" x] by blast \n    show \"x \\<in> cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\n      unfolding 0 \n      apply(rule cell_algebra_finite_disjoint_union)\n      apply(rule subsetI)\n      using cell_algebra.generator[of _ \"condition_to_set `c_cells_at_one_val_point m c Fs C\"] S_def \n      apply blast\n      using S_def is_cell_decompE apply blast \n      apply(rule disjointI) using S_def is_cell_decompE disjointE \n      by (metis is_partitionE(1))\n  qed\n  show \"cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs C) \\<subseteq> one_val_point_decomposables m c Fs C\"\n  proof fix x assume A: \"x \\<in> cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs C)\"\n    show \"x \\<in> one_val_point_decomposables m c Fs C\"\n      apply(rule cell_algebra.induct[of x \"(condition_to_set ` c_cells_at_one_val_point m c Fs C)\"])\n      using A apply blast \n      using empty_one_val_point_c_decomposable[of c m f Fs C] f_def assms\n            one_val_point_decomposables_def \n          apply auto[1]\n      using assms c_cells_at_one_val_point_is_c_decomposable[of _ m c Fs C] unfolding image_iff apply blast   \n      using one_val_point_decomposables_disjoint_union[of _ m c Fs C] unfolding image_iff by blast \n  qed\nqed\n\nlemma finite_union_one_val_point_c_decomposable:\n  assumes \"c \\<in> carrier (SA m)\"\n  assumes \"finite S\"\n  assumes \"Fs \\<noteq> {}\"\n  assumes \"Fs \\<subseteq> carrier (SA m)\"\n  assumes \" S \\<subseteq> condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n  shows \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) (\\<Union> S)\"\nproof-\n  have 00: \"\\<And>s. s \\<in> S \\<Longrightarrow> one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) s\"\n  proof- \n    fix s assume A: \"s \\<in> S\"\n    obtain \\<C> where \\<C>_def: \"\\<C> \\<in> c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\" \n                          \"s = condition_to_set \\<C>\"\n      using A assms by auto \n    show \"one_val_point_c_decomposable m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) s\" \n      using \\<C>_def assms basic_trans_rules(31) image_iff inf.idem \n            c_cells_at_one_val_point_intersection[of _ _ _ \\<C> _ \\<C>]\n      unfolding \\<C>_def by auto \n  qed\n  have 0: \"cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))) = one_val_point_decomposables m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    using 00 assms one_val_point_decomposables_is_cell_algebra by metis \n  have \"(\\<Union> S) \\<in> cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)))\"\n    apply(rule cell_algebra_finite_union)\n  proof- \n    fix A B assume A: \" A \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\" \"B \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n    obtain \\<C> where \\<C>_def: \"\\<C> \\<in>  c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) \\<and> A = condition_to_set \\<C>\"\n      using A by blast \n    have \\<C>: \"A = condition_to_set \\<C>\"\n      using \\<C>_def by blast \n    obtain \\<C>' where \\<C>'_def: \"\\<C>' \\<in>  c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) \\<and> B = condition_to_set \\<C>'\"\n      using A by blast \n    have \\<C>': \"B = condition_to_set \\<C>'\"\n      using \\<C>'_def by blast \n    show \"A \\<inter> B \\<in> cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)))\"\n      unfolding \\<C> \\<C>' 0  one_val_point_decomposables_def mem_Collect_eq \n      apply(rule c_cells_at_one_val_point_intersection[of _ _ _ _ \"carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"])\n      using assms \\<C>_def \\<C>'_def  by auto \n    show \"\\<And>A C. A \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) \\<Longrightarrow>\n           C \\<in> condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)) \\<Longrightarrow>\n           A - C \\<in> cell_algebra (condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)))\"\n      unfolding one_val_point_decomposables_def mem_Collect_eq 0\n      apply(rule one_val_point_c_decomposable_diff)\n      using assms apply blast \n      using assms apply blast \n      using assms apply blast \n      using c_cells_at_one_val_point_is_c_decomposable[of _ m c _ \"carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"]\n      unfolding one_val_point_decomposables_def mem_Collect_eq apply blast \n      using c_cells_at_one_val_point_is_c_decomposable[of _ m c _  \"carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>)\"]\n      unfolding one_val_point_decomposables_def mem_Collect_eq by blast\n  next \n    show \"finite S \\<and> S \\<subseteq> condition_to_set ` c_cells_at_one_val_point m c Fs (carrier (Q\\<^sub>p\\<^bsup>Suc m\\<^esup>))\"\n      using assms by blast \n  qed\n  thus ?thesis unfolding 0  unfolding one_val_point_decomposables_def mem_Collect_eq  by blast \nqed\nend\n\nend ", "meta": {"author": "Aaroncri", "repo": "Macintyre-Theorem-in-Isabelle", "sha": "a13c75b5d3fc12fb3290b7c92326e13618612c6c", "save_path": "github-repos/isabelle/Aaroncri-Macintyre-Theorem-in-Isabelle", "path": "github-repos/isabelle/Aaroncri-Macintyre-Theorem-in-Isabelle/Macintyre-Theorem-in-Isabelle-a13c75b5d3fc12fb3290b7c92326e13618612c6c/Macintyre_Theorem/Algebras_of_Cells.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942348544446, "lm_q2_score": 0.843895106480586, "lm_q1q2_score": 0.7513149481215433}}
{"text": "text{*\nExercise 3.4. Take a copy of theory AExp and modify it as follows. Extend type aexp\n              with a binary constructor Times that represents multiplication.\n              Modify the definition of the functions aval and asimp accordingly.\n              You can remove asimp_const. Function asimp should eliminate 0 and 1\n              from multiplication as well as evaluate constant subterms. Update\n              all proofs concerned.\n*}\n\ntheory AExpMul \n  imports Main \nbegin\n  \nsubsection \"Arithmetic Expressions with multiplication\"\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\n\ndatatype aexp \n  = N int \n  | V vname \n  | Plus aexp aexp\n  | Times aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" \n  where \"aval (N n) s = n\" \n  | \"aval (V x) s = s x\" \n  | \"aval (Plus a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s + aval a\\<^sub>2 s\"\n  | \"aval (Times a\\<^sub>1 a\\<^sub>2) s = aval a\\<^sub>1 s * aval a\\<^sub>2 s\"\n\nvalue \"aval (Plus (V ''x'') (N 5)) (\\<lambda>x. if x = ''x'' then 7 else 0)\"\n\nvalue \"aval (Times (N 3) (N 2)) (\\<lambda>x.0)\"\n\ntext {* The same state more concisely: *}\nvalue \"aval (Plus (V ''x'') (N 5)) ((\\<lambda>x. 0) (''x'':= 7))\"\n\ntext {* A little syntax magic to write larger states compactly: *}\n\ndefinition null_state (\"<>\") where\n  \"null_state \\<equiv> \\<lambda>x. 0\"\nsyntax \n  \"_State\" :: \"updbinds => 'a\" (\"<_>\")\ntranslations\n  \"_State ms\" == \"_Update <> ms\"\n  \"_State (_updbinds b bs)\" <= \"_Update (_State b) bs\"\n\ntext {* \\noindent\n  We can now write a series of updates to the function @{text \"\\<lambda>x. 0\"} compactly:\n*}\n  \nlemma \"<a := 1, b := 2> = (<> (a := 1)) (b := (2::int))\"\n  by (rule refl)\n\nvalue \"aval (Plus (V ''x'') (N 5)) <''x'' := 7>\"\n\ntext {* In  the @{term[source] \"<a := b>\"} syntax, variables that are not mentioned are 0 by default:\n*}\nvalue \"aval (Plus (V ''x'') (N 5)) <''y'' := 7>\"\n\ntext{* Note that this @{text\"<\\<dots>>\"} syntax works for any function space\n@{text\"\\<tau>\\<^sub>1 \\<Rightarrow> \\<tau>\\<^sub>2\"} where @{text \"\\<tau>\\<^sub>2\"} has a @{text 0}. *}\n\n\nsubsection \"Constant Folding\"\n\ntext{* Now we also eliminate all occurrences 0 in additions. The standard\nmethod: optimized versions of the constructors: *}\n\nfun plus :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" \n  where \"plus (N i\\<^sub>1) (N i\\<^sub>2) = N(i\\<^sub>1+i\\<^sub>2)\" \n  | \"plus (N i) a = (if i=0 then a else Plus (N i) a)\" \n  | \"plus a (N i) = (if i=0 then a else Plus a (N i))\" \n  | \"plus a\\<^sub>1 a\\<^sub>2 = Plus a\\<^sub>1 a\\<^sub>2\"\n\nlemma aval_plus[simp]: \"aval (plus a1 a2) s = aval a1 s + aval a2 s\"\n apply(induction a1 a2 rule: plus.induct)\n apply(auto)\n done\n\nfun times :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\"\n  where \"times (N i\\<^sub>1) (N i\\<^sub>2) = N (i\\<^sub>1 * i\\<^sub>2)\"\n  | \"times (N i) a = (if i=1 then a else (if i=0 then N 0 else Times (N i) a))\"\n  | \"times a (N i) = (if i=1 then a else (if i=0 then N 0 else Times (N i) a))\"\n  | \"times a\\<^sub>1 a\\<^sub>2 = Times a\\<^sub>1 a\\<^sub>2\"\n\nlemma aval_times [simp]: \"aval (times a1 a2) s = aval a1 s * aval a2 s\"\n apply(induction a1 a2 rule: times.induct)\n apply simp_all\n done\n    \nfun asimp :: \"aexp \\<Rightarrow> aexp\" \n  where \"asimp (N n) = N n\" \n  | \"asimp (V x) = V x\" \n  | \"asimp (Plus a\\<^sub>1 a\\<^sub>2) = plus (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n  | \"asimp (Times a\\<^sub>1 a\\<^sub>2) = times (asimp a\\<^sub>1) (asimp a\\<^sub>2)\"\n\nvalue \"asimp (Plus (Plus (N 0) (N 0)) (Plus (V ''x'') (N 0)))\"\n\ntheorem aval_asimp[simp]: \"aval (asimp a) s = aval a s\"\n  apply(induction a rule: asimp.induct)\n  apply(auto)\n  done\n\nend", "meta": {"author": "juanbono", "repo": "concrete-semantics-exercises", "sha": "b873ab9191509e285b89ee1f34484b226e1de95d", "save_path": "github-repos/isabelle/juanbono-concrete-semantics-exercises", "path": "github-repos/isabelle/juanbono-concrete-semantics-exercises/concrete-semantics-exercises-b873ab9191509e285b89ee1f34484b226e1de95d/chapter-3/AExpMul.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942348544447, "lm_q2_score": 0.8438950986284991, "lm_q1q2_score": 0.7513149411308757}}
{"text": "(*  Title:      HOL/Algebra/Bij.thy\n    Author:     Florian Kammueller, with new proofs by L C Paulson\n*)\n\ntheory Bij\nimports Group\nbegin\n\nsection \\<open>Bijections of a Set, Permutation and Automorphism Groups\\<close>\n\ndefinition\n  Bij :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n    \\<comment>\\<open>Only extensional functions, since otherwise we get too many.\\<close>\n   where \"Bij S = extensional S \\<inter> {f. bij_betw f S S}\"\n\ndefinition\n  BijGroup :: \"'a set \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"BijGroup S =\n    \\<lparr>carrier = Bij S,\n     mult = \\<lambda>g \\<in> Bij S. \\<lambda>f \\<in> Bij S. compose S g f,\n     one = \\<lambda>x \\<in> S. x\\<rparr>\"\n\n\ndeclare Id_compose [simp] compose_Id [simp]\n\nlemma Bij_imp_extensional: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> extensional S\"\n  by (simp add: Bij_def)\n\nlemma Bij_imp_funcset: \"f \\<in> Bij S \\<Longrightarrow> f \\<in> S \\<rightarrow> S\"\n  by (auto simp add: Bij_def bij_betw_imp_funcset)\n\n\nsubsection \\<open>Bijections Form a Group\\<close>\n\nlemma restrict_inv_into_Bij: \"f \\<in> Bij S \\<Longrightarrow> (\\<lambda>x \\<in> S. (inv_into S f) x) \\<in> Bij S\"\n  by (simp add: Bij_def bij_betw_inv_into)\n\nlemma id_Bij: \"(\\<lambda>x\\<in>S. x) \\<in> Bij S \"\n  by (auto simp add: Bij_def bij_betw_def inj_on_def)\n\nlemma compose_Bij: \"\\<lbrakk>x \\<in> Bij S; y \\<in> Bij S\\<rbrakk> \\<Longrightarrow> compose S x y \\<in> Bij S\"\n  by (auto simp add: Bij_def bij_betw_compose) \n\nlemma Bij_compose_restrict_eq:\n     \"f \\<in> Bij S \\<Longrightarrow> compose S (restrict (inv_into S f) S) f = (\\<lambda>x\\<in>S. x)\"\n  by (simp add: Bij_def compose_inv_into_id)\n\ntheorem group_BijGroup: \"group (BijGroup S)\"\napply (simp add: BijGroup_def)\napply (rule groupI)\n    apply (simp add: compose_Bij)\n   apply (simp add: id_Bij)\n  apply (simp add: compose_Bij)\n  apply (blast intro: compose_assoc [symmetric] dest: Bij_imp_funcset)\n apply (simp add: id_Bij Bij_imp_funcset Bij_imp_extensional, simp)\napply (blast intro: Bij_compose_restrict_eq restrict_inv_into_Bij)\ndone\n\n\nsubsection\\<open>Automorphisms Form a Group\\<close>\n\nlemma Bij_inv_into_mem: \"\\<lbrakk> f \\<in> Bij S;  x \\<in> S\\<rbrakk> \\<Longrightarrow> inv_into S f x \\<in> S\"\nby (simp add: Bij_def bij_betw_def inv_into_into)\n\nlemma Bij_inv_into_lemma:\n assumes eq: \"\\<And>x y. \\<lbrakk>x \\<in> S; y \\<in> S\\<rbrakk> \\<Longrightarrow> h(g x y) = g (h x) (h y)\"\n shows \"\\<lbrakk>h \\<in> Bij S;  g \\<in> S \\<rightarrow> S \\<rightarrow> S;  x \\<in> S;  y \\<in> S\\<rbrakk>\n        \\<Longrightarrow> inv_into S h (g x y) = g (inv_into S h x) (inv_into S h y)\"\napply (simp add: Bij_def bij_betw_def)\napply (subgoal_tac \"\\<exists>x'\\<in>S. \\<exists>y'\\<in>S. x = h x' & y = h y'\", clarify)\n apply (simp add: eq [symmetric] inv_f_f funcset_mem [THEN funcset_mem], blast)\ndone\n\n\ndefinition\n  auto :: \"('a, 'b) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) set\"\n  where \"auto G = hom G G \\<inter> Bij (carrier G)\"\n\ndefinition\n  AutoGroup :: \"('a, 'c) monoid_scheme \\<Rightarrow> ('a \\<Rightarrow> 'a) monoid\"\n  where \"AutoGroup G = BijGroup (carrier G) \\<lparr>carrier := auto G\\<rparr>\"\n\nlemma (in group) id_in_auto: \"(\\<lambda>x \\<in> carrier G. x) \\<in> auto G\"\n  by (simp add: auto_def hom_def restrictI group.axioms id_Bij)\n\nlemma (in group) mult_funcset: \"mult G \\<in> carrier G \\<rightarrow> carrier G \\<rightarrow> carrier G\"\n  by (simp add:  Pi_I group.axioms)\n\nlemma (in group) restrict_inv_into_hom:\n      \"\\<lbrakk>h \\<in> hom G G; h \\<in> Bij (carrier G)\\<rbrakk>\n       \\<Longrightarrow> restrict (inv_into (carrier G) h) (carrier G) \\<in> hom G G\"\n  by (simp add: hom_def Bij_inv_into_mem restrictI mult_funcset\n                group.axioms Bij_inv_into_lemma)\n\nlemma inv_BijGroup:\n     \"f \\<in> Bij S \\<Longrightarrow> m_inv (BijGroup S) f = (\\<lambda>x \\<in> S. (inv_into S f) x)\"\napply (rule group.inv_equality)\napply (rule group_BijGroup)\napply (simp_all add:BijGroup_def restrict_inv_into_Bij Bij_compose_restrict_eq)\ndone\n\nlemma (in group) subgroup_auto:\n      \"subgroup (auto G) (BijGroup (carrier G))\"\nproof (rule subgroup.intro)\n  show \"auto G \\<subseteq> carrier (BijGroup (carrier G))\"\n    by (force simp add: auto_def BijGroup_def)\nnext\n  fix x y\n  assume \"x \\<in> auto G\" \"y \\<in> auto G\" \n  thus \"x \\<otimes>\\<^bsub>BijGroup (carrier G)\\<^esub> y \\<in> auto G\"\n    by (force simp add: BijGroup_def is_group auto_def Bij_imp_funcset \n                        group.hom_compose compose_Bij)\nnext\n  show \"\\<one>\\<^bsub>BijGroup (carrier G)\\<^esub> \\<in> auto G\" by (simp add:  BijGroup_def id_in_auto)\nnext\n  fix x \n  assume \"x \\<in> auto G\" \n  thus \"inv\\<^bsub>BijGroup (carrier G)\\<^esub> x \\<in> auto G\"\n    by (simp del: restrict_apply\n        add: inv_BijGroup auto_def restrict_inv_into_Bij restrict_inv_into_hom)\nqed\n\ntheorem (in group) AutoGroup: \"group (AutoGroup G)\"\nby (simp add: AutoGroup_def subgroup.subgroup_is_group subgroup_auto \n              group_BijGroup)\n\nend\n", "meta": {"author": "SEL4PROJ", "repo": "jormungand", "sha": "bad97f9817b4034cd705cd295a1f86af880a7631", "save_path": "github-repos/isabelle/SEL4PROJ-jormungand", "path": "github-repos/isabelle/SEL4PROJ-jormungand/jormungand-bad97f9817b4034cd705cd295a1f86af880a7631/case_study/isabelle/src/HOL/Algebra/Bij.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.8438951104066293, "lm_q1q2_score": 0.7513149393348058}}
{"text": "theory Scratch4\n  imports Main\nbegin\n\n(* Exercise 4.1 *)\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun set :: \"'a tree \\<Rightarrow> 'a set\" where\n\"set Tip = {}\"|\n\"set (Node l a r) = {a} \\<union> (set l) \\<union> (set r)\"\n\nfun ord :: \"int tree \\<Rightarrow> bool\" where\n\"ord Tip = True\"|\n\"ord (Node l a r) = ((ord l) \\<and> (ord r) \\<and>\n  (case l of\n  Tip \\<Rightarrow> True |\n  Node _ a1 _ \\<Rightarrow> a1 < a) \\<and>\n  (case r of\n  Tip \\<Rightarrow> True |\n  Node _ a2 _ \\<Rightarrow> a < a2))\"\n\nfun ins :: \"int tree \\<Rightarrow> int \\<Rightarrow> int tree\" where\n\"ins Tip x = (Node Tip x Tip)\"|\n\"ins (Node l y r)  x = (if (y = x)\n                        then Node l y r\n                        else (if (x < y)\n                              then Node (ins l x) y r\n                              else Node l y (ins r x)))\"\n\nlemma \"set (ins t x) = {x} \\<union> set t\"\n  apply (induction t)\n   apply (auto)\n  done\n\nlemma \"ord t \\<Longrightarrow> ord (ins t i)\"\n  apply (induction t arbitrary: i)\n   apply (auto split: tree.split)\n  done\n\nlemma \"\\<forall> x. \\<exists> y. x = y\"\n  by auto\n\nlemma \"A \\<subseteq> B \\<inter> C \\<Longrightarrow> A \\<subseteq> B \\<union> C\"\n  by auto\n\nlemma \"\\<forall> xs \\<in> A. \\<exists> ys. xs = ys @ ys \\<Longrightarrow> us \\<in> A \\<Longrightarrow> \\<exists> n . length us = n + n\"\n  by fastforce\n\nlemma \"\\<forall> x y. T x y \\<or> T y x \\<Longrightarrow>\n       \\<forall> x y. A x y \\<and> A y x \\<longrightarrow> x = y \\<Longrightarrow>\n       \\<forall> x y. T x y \\<longrightarrow> A x y \\<Longrightarrow>\n       \\<forall> x y. A x y \\<longrightarrow> T x y\"\n  by blast\n\nlemma \"[a] = [b] \\<Longrightarrow> a = b\"\n  by simp\n\nlemma \"(a :: nat) \\<le> x + b \\<Longrightarrow> 2 * x < c \\<Longrightarrow> 2 * a + 1 \\<le> 2 * b + c\"\n  by arith\n\ninductive ev :: \"nat \\<Rightarrow> bool\" where\nev0 : \"ev 0\"|\nevSS : \"ev n \\<Longrightarrow> ev (Suc (Suc n))\"\n\nthm evSS\nthm ev.intros\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\n  apply (auto intro: evSS ev0)\n  done\n\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\n  apply (rule evSS)\n  apply (rule evSS)\n  apply (rule ev0)\n  done\n\n\nlemma \"ev (Suc(Suc(Suc(Suc 0))))\"\n  apply (rule)\n  apply (rule)\n  apply (rule)\n  done\n\nvalue \"ev0 \\<Longrightarrow> ev(0+2) \\<Longrightarrow>  ev((0+2) +2) = ev 4\"\n\nfun evn :: \"nat \\<Rightarrow> bool\" where\n\"evn 0 = True\"|\n\"evn (Suc 0) = False\"|\n\"evn (Suc (Suc n)) = evn n\"\n\nlemma \"ev m \\<Longrightarrow> evn m\"\n  apply (induction rule: ev.induct)\n  by (simp_all)\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply (induction n rule: evn.induct)\n    apply (auto  intro: ev0 evSS)\n  done\n\nlemma \"evn n \\<Longrightarrow> ev n\"\n  apply (induction n rule: evn.induct)\n  by (simp_all add: ev0 evSS)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl: \"star r x x\"|\nstep: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\nlemma star_trans: \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n   apply (auto intro: refl step)\n  done\n\nlemma star_trans': \"star r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n   apply (assumption)\n  apply (metis step)\n  done\n\n(* exercise 4.2 *)\ninductive palindrome :: \"'a list \\<Rightarrow> bool\" where\npal0: \"palindrome []\"|\npal1: \"palindrome [x]\"|\npaln: \"palindrome xs \\<Longrightarrow> palindrome (a # xs @ [a])\"\n\nlemma \"palindrome xs \\<Longrightarrow> palindrome (rev xs)\"\n  apply (induction rule : palindrome.induct)\n  by (simp_all add: pal0 pal1 paln)\n\n(* exercise 4.3 *)\ninductive star' :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\nrefl': \"star' r x x\"|\nstep': \"star' r x y \\<Longrightarrow> r y z \\<Longrightarrow> star' r x z\"\n\nlemma star_then_step[simp]:\"\\<lbrakk>star r x y; r y z\\<rbrakk> \\<Longrightarrow> star r x z\"\n  apply (induction rule: star.induct)\n   apply (auto intro: refl step)\n  done\n\nlemma \"star' r x y \\<Longrightarrow> star r x y\"\n  apply (induction rule: star'.induct)\n   apply (auto simp add: refl)\n  done\n\nlemma star'_then_step[simp]:\"\\<lbrakk>star' r y z; r x y\\<rbrakk> \\<Longrightarrow> star' r x z\"\n  apply (induction rule: star'.induct)\n   apply (auto intro: refl' step')\n  done\n\nlemma \"star r x y \\<Longrightarrow> star' r x y\"\n  apply (induction rule: star.induct)\n   apply (auto simp add: refl')\n  done\n\n(* exercise 4.4 *)\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\niter0: \"iter r 0 x x\"|\nitern: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Succ n) x z\"\n\nlemma \"star r x y \\<Longrightarrow> \\<exists> n . iter r n x y\"\n  apply (induction rule: star.induct)\n   apply (auto intro: iter0 itern)\n  done\n\n(* exercise 4.5 *)\ndatatype alpha = a | b\n\ninductive S :: \"alpha list \\<Rightarrow> bool\" where\nS\\<^sub>\\<epsilon>: \"S []\"|\nS\\<^sub>1: \"S x \\<Longrightarrow> S (a # x @ [b])\"|\nS\\<^sub>2: \"S x \\<Longrightarrow> S y \\<Longrightarrow> S (x @ y)\"\n\ninductive T :: \"alpha list \\<Rightarrow> bool\" where\nT\\<^sub>\\<epsilon>: \"T []\"|\nT\\<^sub>1: \"T x \\<Longrightarrow> T y \\<Longrightarrow> T (x @ [a] @ y @ [b])\"\n\nlemma T_imp_S: \"T w \\<Longrightarrow> S w\"\n  apply (induction rule: T.induct)\n  by (auto intro: S\\<^sub>\\<epsilon> S\\<^sub>1 S\\<^sub>2)\n\nlemma T_app_nil:\"T ([] @ [a] @ x @ [b]) \\<Longrightarrow> T (a # x @ [b])\"\n  by auto\n\nlemma helper: \"\\<lbrakk>T y; T x\\<rbrakk> \\<Longrightarrow> T (x @ y)\"\n  apply (induction rule: T.induct)\n   apply (auto)\n  using T\\<^sub>1 by force\n\nlemma S_imp_T: \"S w \\<Longrightarrow> T w\"\n  apply (induction rule: S.induct)\n    apply (auto simp add: helper intro: T\\<^sub>\\<epsilon> T\\<^sub>1 T_app_nil)\n  done\n\nlemma \"S w = T w\"\n  apply (rule) using S_imp_T T_imp_S by auto\n\ntype_synonym vname = string\ntype_synonym val = int\ntype_synonym state = \"vname \\<Rightarrow> val\"\ndatatype aexp = N int | V vname | Plus aexp aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\"|\n\"aval (V v) s = s v\"|\n\"aval (Plus a1 a2) s = (aval a1 s) + (aval a2 s)\"\n  \ninductive aval_rel' :: \"aexp \\<Rightarrow> state \\<Rightarrow> val \\<Rightarrow> bool\" where\nnaval: \"aval_rel' (N n) s n\"|\nvaval: \"aval_rel' (V v) s (s v)\"|\nplaval: \"aval_rel' a1 s v1 \\<Longrightarrow>\n         aval_rel' a2 s v2 \\<Longrightarrow>\n         aval_rel' (Plus a1 a2) s (v1 + v2)\"\n\nlemma \"(aval_rel' e s v) \\<Longrightarrow> (aval e s = v)\"\n  apply (induction rule: aval_rel'.induct)\n  by auto\n\nlemma \"(aval e s = v) \\<Longrightarrow> (aval_rel' e s v)\"\n  apply (induction e arbitrary: v)\n    apply (auto intro: naval vaval plaval)\n  done\n  \n\nend", "meta": {"author": "tomssem", "repo": "concrete_semantics", "sha": "a1c52efba72b4abb85a52c489812b32c2d1aee36", "save_path": "github-repos/isabelle/tomssem-concrete_semantics", "path": "github-repos/isabelle/tomssem-concrete_semantics/concrete_semantics-a1c52efba72b4abb85a52c489812b32c2d1aee36/Chapter4/Scratch4.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.8244619350028204, "lm_q1q2_score": 0.7512329848631031}}
{"text": "theory HoareLogicTR \n\nimports Main \"HOL-Hoare.Hoare_Logic\"\n\nbegin\n\nsection \\<open>Hoare Logic in Isabelle/HOL\\<close>\n\n\nlemma slow_sub_isa:\n\"VARS  (x::nat) (z::nat)\n{x=M \\<and> z=P}\nWHILE \\<not>(x=0)\n  INV { z-x = P-M \\<and> x\\<ge>0}\n  DO z:=z-1;x:=x-1 OD\n{z = P-M}\"\napply (vcg)\napply (auto)\ndone\n\nlemma imp_pot:\n\"VARS (a::int) (b::nat) (p::int) (i::nat)\n{a=A \\<and> b=B}\ni := 0; p := 1;\nWHILE i<b\n  INV { p = a^i \\<and> i\\<le> b \\<and> a=A \\<and> b = B}\n  DO p := p * a;i:=i+1 OD\n{p = A^B}\"\napply (vcg)\napply (auto)\ndone\n\nlemma imp_pot_isar:\"VARS (a::int) (b::nat) p i\n{a=A \\<and> b=B}\ni := 0; p := 1;\nWHILE i<b\n  INV { p = a^i \\<and> i\\<le> b \\<and> a=A \\<and> b = B}\n  DO p := p * a;i:=i+1 OD\n{p = A^B}\"\n\n  proof (vcg)\n    fix a b p i \n    let ?INV = \"p = a ^ i \\<and> i \\<le> b \\<and> a = A \\<and> b = B\"\n    assume ass:\"?INV  \\<and> i < b\"\n    show \"p * a = a ^ (i + 1) \\<and> i + 1 \\<le> b\n          \\<and> a = A \\<and> b = B\"\n      proof - \n        from ass obtain 1: \"p = a ^ i\" and 2:\"i \\<le> b\"\n        and 3:\"a = A \\<and> b = B\" and 5:\"i<b\"  by blast\n        from 1 have 6:\"p*a=a^i*a\" by simp\n        from this have 7:\"p * a = a ^ (i + 1)\" by simp\n        from 5 have 8:\"i+1\\<le>b\" by simp\n        from this 3 7 show ?thesis by simp\n      qed \n  qed (auto)\n\nsection \\<open>Preliminary Example - List Reversal\\<close>\n\nlemma hd_tl:\"xs \\<noteq> [] \\<Longrightarrow> xs = hd xs # tl xs\"\n  by simp \n\n\nfun tail_rev::\"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where \n\"tail_rev [] acc = acc\" |\n\"tail_rev (x#xs) acc = tail_rev xs (x # acc)\"\n\nlemma tail_rev:\"\\<forall>ys. tail_rev xs ys = rev xs @ ys\"\napply (induction xs)\napply (auto)\ndone\n\nlemma \"tail_rev xs [] = rev xs\" by (simp add:tail_rev)\n\n\nlemma hd_tl_app:\"xs \\<noteq> [] \\<Longrightarrow> \n        xs = [hd xs] @ tl xs\"\n            by simp\n \nlemma impRev: \"VARS (acc::'a list) (xs::'a list)\n {xs=X}\n acc:=[];\n WHILE xs \\<noteq> []\n   INV {rev(xs)@acc = rev(X)}\n DO acc := (hd xs # acc); xs := tl xs OD\n {acc=rev(X)}\"\napply (vcg) \napply (simp)\n    using hd_tl_app apply (force)\napply (auto)\ndone\n\n\nlemma impRev_isar: \"VARS acc x\n {x=X}  acc:=[];\n WHILE x \\<noteq> []  INV {rev(x)@acc = rev(X)}\n DO acc := (hd x # acc); x := tl x OD\n {acc=rev(X)}\"\nproof (vcg)\n  fix acc x\n  assume ass:\"rev x @ acc = rev X \\<and> x \\<noteq> []\"\n  show \"rev (tl x) @ hd x # acc = rev X\"\n    proof - \n      from ass obtain 1:\"rev x @ acc = rev X\" \n        and 2:\" x\\<noteq>[]\" by blast\n      from 2 have \"x = hd x # tl x\"  by simp\n      from 1 and this  \n        have 3:\"rev x = rev (hd x # tl x)\" \n            by simp\n        have \"rev (hd x # tl x) = \n              rev (tl x) @ [hd x]\" by simp\n      from 3 and this \n        have \"rev x =  \n              rev (tl x) @ [hd x]\" by simp\n      from this and 1 show ?thesis by simp\n    qed \nqed (auto)\n\n\nsection \\<open>Case Study: Insertion Sort\\<close> \n\nfun ins::\"'a::linorder \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere  \"ins x [] = [x]\" |\n \"ins x (y # ys)=(if x \\<le> y then (x # y # ys)\n                    else y#ins x ys)\" \n\nfun iSort::\"('a::linorder) list \\<Rightarrow> 'a list\" \nwhere \"iSort [] = []\" | \n      \"iSort (x # xs) = ins x (iSort xs)\"\n\nfun le::\"('a::linorder) \\<Rightarrow> 'a list \\<Rightarrow> bool\"  \nwhere  \"le x [] = True\" | \n       \"le x (y # ys) = (x \\<le>y \\<and> le x ys)\"\n\nfun isorted::\"('a::linorder) list \\<Rightarrow> bool\"\nwhere   \n  \"isorted [] = True\" | \n  \"isorted (x # xs) = (le x xs \\<and> isorted xs)\"\n\nfun count:: \"'a \\<Rightarrow> 'a list \\<Rightarrow> int\"  where \n  \"count x [] = 0\" |\n  \"count x (y # ys) = (if x=y then \n     1 + count x ys else count x ys)\"\n\n\n\nfun tail_iSort::\"('a::linorder) list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"tail_iSort [] acc = acc\" |  \n\"tail_iSort (x#xs)  acc = tail_iSort xs (ins x acc)\"\n\nvalue \"iSort [12,-3,-4,200,2::int]\"\nvalue \"tail_iSort [12,-3,-4,200,2::int] []\"\nvalue \"isorted(tail_iSort [12,-3,-4,200,2::int] [1,2,3])\"\n\ntext\\<open>\n  lemma le_ins: \"le x (ins a xs) = (x \\<le> a \\<and> le x xs)\"                       sorry\n  lemma le_mon:\"x\\<le>y \\<Longrightarrow> le y xs \\<Longrightarrow> le x xs\"                                sorry\n  lemma ins_sorted: \"isorted (ins a xs) = isorted xs\"                        sorry\n  lemma is_sorted:\"isorted(iSort xs)\"                                        sorry\n  lemma ins_count:\n   \"count x (ins k xs) = (if x = k then 1 \n          + count x xs else count x xs)\"                                     sorry\n  lemma count_sum:\"count x (xs @ ys) =\n          count x xs + count x ys\"                                           sorry\n  lemma len_sort:\"length(iSort xs) = length xs\"                              sorry\n  lemma count_iSort: \"count x (iSort xs) = count x xs\"                       sorry\n  lemma ins_len:\"length (ins k xs) = 1 + length xs\"                          sorry\n\\<close>\n\nlemma le_ins: \"le x (ins a xs) = (x \\<le> a \\<and> le x xs)\"\n  apply (induction xs)\n  apply auto\ndone\n\nlemma le_mon:\"x\\<le>y \\<Longrightarrow> le y xs \\<Longrightarrow> le x xs\" \n  apply (induction xs)\n  apply (auto)\ndone \n\nlemma ins_sorted: \"isorted (ins a xs) = isorted xs\"\n  apply (induct_tac xs)\n  apply (auto simp add: le_ins le_mon)\ndone\n\nlemma is_sorted:\"isorted(iSort xs)\" \n  apply (induction xs)\n  apply (auto simp add:ins_sorted)\ndone  \n\nlemma ins_count:\n   \"count x (ins k xs) = (if x = k then 1 + count x xs \n                          else count x xs)\" \napply (induction xs)\napply (auto)\ndone \n\n\nlemma count_sum:\"count x (xs @ ys) = count x xs + count x ys\" \n      (is \"?P xs\")\nproof (induction xs)\n  show \"?P []\" by simp \nnext \n  fix a xs \n  assume IH: \"count x (xs @ ys) = count x xs + count x ys\"\n  show \"count x ((a # xs) @ ys) = count x (a # xs) +  count x ys\"\n    proof (cases \"x=a\")\n      assume h0:\"x=a\" \n      have \"count x ((a # xs) @ ys) = count x (a # (xs @ ys))\" \n          by simp\n      also have \"\\<dots> = 1 + count x (xs @ ys)\" using h0 by simp\n      also have \"\\<dots> = (1 + count x xs)  + count x ys\" \n          using IH h0 by simp\n      also have \"\\<dots> =  count x (a # xs) + count x ys\" using h0 by simp\n      finally show ?thesis by this\n    next\n      assume h1:\"x\\<noteq>a\" \n      have \"count x ((a # xs) @ ys) = count x (a # (xs @ ys))\" \n          by simp\n      also have \"\\<dots> =  count x (xs @ ys)\" using h1 by simp\n      also have \"\\<dots> = count x xs  + count x ys\" \n          using IH h1 by simp\n      also have \"\\<dots> =  count x (a # xs) + count x ys\" using h1 by simp\n      finally show ?thesis by this\n    qed\nqed\n\nlemma ins_len:\"length (ins k xs) = 1 + length xs\" \napply (induction xs)\napply (auto)\ndone \n\nlemma len_sort:\"length(iSort xs) = length xs\" \napply (induction xs)\napply (simp_all add:ins_len)\ndone \n\nlemma count_iSort: \"count x (iSort xs) = count x xs\" \napply (induction xs)\napply (auto simp add: ins_count)\n  done \n\n \ndefinition is_perm::\"'a list \\<Rightarrow> 'a list \\<Rightarrow> bool\" \nwhere \"is_perm l1 l2 \\<equiv> length l1 = length l2 \n              \\<and> (\\<forall>x. count x l1 = count x l2)\"\n\n  lemma inss_hoare:\n    \"VARS xs ys :: ('a::linorder) list\n   {xs=X}\n   ys:=[];\n   WHILE xs \\<noteq> []\n      INV {isorted ys \\<and> is_perm X (ys @ xs)}\n   DO ys := ins (hd xs) ys; xs := tl xs OD\n  {isorted ys \\<and> is_perm X ys}\"\n   apply (vcg)  \n   apply (auto simp add:is_perm_def) \\<comment> \\<open> 1 \\<close>\n     apply (simp add: ins_sorted) \\<comment> \\<open>1.1\\<close>\n     apply (simp add: ins_len) \\<comment> \\<open>1.2\\<close>\n     apply  (smt count.simps(2) count_sum \n            ins_count list.collapse) \\<comment>\\<open>1.3\\<close>\n  done\n     \n\n\nlemma inss_hoareb: \"VARS xs ys :: ('a::linorder) list\n {xs=X}\n ys:=[];\n WHILE xs \\<noteq> []\n    INV {isorted ys \\<and> is_perm X (ys @ xs)}\n DO ys := ins (hd xs) ys; xs := tl xs OD\n{isorted ys \\<and> is_perm X ys}\" \n  apply (vcg)  \n  apply (simp add:is_perm_def) \\<comment> \\<open> 1 \\<close>\n  apply (rule conjI)  \\<comment> \\<open> 2 \\<close>\n      apply (simp add: ins_sorted) \\<comment> \\<open>2.1\\<close>\n      apply (simp add:is_perm_def) \\<comment>\\<open>2.2\\<close>\n        apply (rule conjI)\n        apply (simp add: ins_len)\n        apply (smt count.simps(2) count_sum \n              ins_count list.collapse)\n      apply (auto) \\<comment>\\<open>2.3\\<close>\n  done           \n          \n\nlemma inss_isar_draft:\n\"VARS xs ys :: ('a::linorder) list\n {xs=X} ys:=[];\n WHILE xs \\<noteq> []\n    INV {isorted ys \\<and> is_perm X (ys @ xs)}\n DO ys := ins (hd xs) ys; xs := tl xs OD\n{isorted ys \\<and> is_perm X ys}\"\nproof (vcg)\n   fix xs ys \n   assume ass:\"(isorted ys \\<and> \n      is_perm X (ys @ xs)) \\<and> xs \\<noteq> []\"   \n   show \"isorted (ins (hd xs) ys) \n     \\<and> is_perm X ((ins (hd xs) ys) @ tl xs)\" \n   proof (rule conjI)\n     show \"isorted (ins (hd xs) ys)\" \n        sorry\n   next\n       have pg1:\"length X  =  \n        length ((ins (hd xs) ys) @ tl xs)\"\n           sorry \n       have pg2:\"\\<forall> k. count k X = \n        count k (ins (hd xs) ys @ tl xs)\"  \n           sorry\n       from pg1 pg2 show \n        \"is_perm X (ins (hd xs) ys @ tl xs)\"\n           sorry \n   qed\nqed (auto simp add:is_perm_def)\n\n\nlemma inss_isar: \"VARS xs ys :: ('a::linorder) list\n       {xs=X}\n       ys:=[];\n       WHILE xs \\<noteq> []\n       INV {isorted ys \\<and> is_perm X (ys @ xs)}\n       DO ys := ins (hd xs) ys; xs := tl xs OD\n       {isorted ys \\<and> is_perm X ys}\"\nproof (vcg)\n fix xs ys \n assume ass:\"(isorted ys \\<and> is_perm X (ys @ xs))\n               \\<and> xs \\<noteq> []\"   \n show \"isorted (ins (hd xs) ys)\n      \\<and> is_perm X ((ins (hd xs) ys) @ tl xs)\" \n  proof (rule conjI)\n     from ass have \"isorted ys\" by simp\n     from this show \"isorted (ins (hd xs) ys)\" \n        by (simp add:ins_sorted)\n  next \n    from ass have 1:\"is_perm X (ys @ xs)\" \n       and 2:\"xs \\<noteq> []\" by auto \n    from 2 have hdtl:\"xs = hd xs # tl xs\" by simp \n    from 1 have \n         3:\"\\<forall> x. count x X = count x (ys @ xs)\" \n             by (simp add:is_perm_def)\n    have pg1:\"length X \n          =  length ((ins (hd xs) ys) @ tl xs)\"\n     proof - \n       from 1 have 4:\"length X = length (xs @ ys)\" \n             by (simp add:is_perm_def)\n       also have \"\\<dots>= length xs + length ys\" by simp\n       also have \"\\<dots> =  1 + length ys + \n               length xs - 1\" by simp\n       also have \"\\<dots> = length (ins (hd xs) ys) + \n                 length (tl xs)\"\n                        by (simp add: \"2\" ins_len)\n       also have \"\\<dots> = \n         length ((ins (hd xs) ys) @ tl xs)\" by simp\n       finally show ?thesis  by simp\n     qed \n    have pg2:\"\\<forall> k. count k X = count k (ins (hd xs) ys @ tl xs)\" \n       proof (rule allI)\n         fix k\n         have \"count k X = count k ((ins (hd xs) ys) @ tl xs)\"\n            proof (cases \"k= hd xs\")\n               assume case1: \"k = hd xs\" \n               have \"count k ((ins (hd xs) ys) @ tl xs) = \n                     count k (ins (hd xs) ys) + count k (tl xs)\"  \n                         by (simp add:count_sum)\n               also have \"\\<dots> = 1 + count k ys + count k (tl xs)\" \n                   by (simp add:case1 ins_count)\n               also have \"\\<dots> =  count k ys + 1 + count k (tl xs)\" by simp\n               also have \"\\<dots>= count k ys + count k ((hd xs) # tl xs)\" \n                    by (simp add: case1) \n               also have \"\\<dots>= count k ys + count k xs\"  using hdtl by auto \n               also have \"\\<dots>= count k (ys @ xs)\" by (simp add:count_sum)\n               also have \"\\<dots>= count k X\" by (simp add: \"3\")\n               finally show \"count k X = count k ((ins (hd xs) ys) @ tl xs)\"\n                  by simp\n            next \n               assume case2: \"k \\<noteq> hd xs\" \n                have \"count k ((ins (hd xs) ys) @ tl xs) = \n                     count k (ins (hd xs) ys) + count k (tl xs)\"  \n                         by (simp add:count_sum)\n               also have \"\\<dots> = count k ys + count k (tl xs)\" \n                   by (simp add:case2 ins_count)\n               also have \"\\<dots>= count k ys + count k ((hd xs) # tl xs)\" \n                    by (simp add: case2) \n               also have \"\\<dots>= count k ys + count k xs\"  using hdtl by auto \n               also have \"\\<dots>= count k (ys @ xs)\" by (simp add:count_sum)\n               also have \"\\<dots>= count k X\" by (simp add: \"3\")\n               finally show \"count k X = count k ((ins (hd xs) ys) @ tl xs)\"\n                  by simp\n            qed\n            from this show \"count k X = count k (ins (hd xs) ys @ tl xs)\"\n              by assumption\n         qed\n    from pg1 pg2 show \"is_perm X (ins (hd xs) ys @ tl xs)\" \n         by (simp add:is_perm_def)\n  qed\nqed (auto simp add:is_perm_def)\n\nend", "meta": {"author": "alfiomartini", "repo": "hoare-imp-isab", "sha": "ece8ef97f9217a8cf4cf967e5d39e138b60d0abf", "save_path": "github-repos/isabelle/alfiomartini-hoare-imp-isab", "path": "github-repos/isabelle/alfiomartini-hoare-imp-isab/hoare-imp-isab-ece8ef97f9217a8cf4cf967e5d39e138b60d0abf/Theories/HoareLogicTR.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681086260461, "lm_q2_score": 0.8757869965109765, "lm_q1q2_score": 0.751222155556506}}
{"text": "theory Prog_Prove_2_3\n  imports Main\nbegin\n\nfun reverse :: \"'a list \\<Rightarrow> 'a list\" where\n\"reverse [] = []\" |\n\"reverse (x # xs) = (reverse xs) @ [x]\"\n\nlemma rev_distributes_over_app: \"reverse (xs @ ys) = (reverse ys) @ (reverse xs)\"\napply(induction xs)\napply(auto)\ndone\n\nlemma rev_undos_self: \"reverse (reverse xs) = xs\"\napply(induction xs)\napply(auto)\napply(simp add: rev_distributes_over_app)\ndone\n\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun mirror :: \"'a tree \\<Rightarrow> 'a tree\" where\n\"mirror Tip = Tip\" |\n\"mirror (Node l a r) = Node (mirror r) a (mirror l)\"\n\nlemma \"mirror(mirror t) = t\"\n  apply(induction t)\n   apply(auto)\n  done\n\ndatatype 'a option = None | Some 'a\n\nfun lookup :: \"('a * 'b) list \\<Rightarrow> 'a \\<Rightarrow> 'b option\" where\n\"lookup [] x = None\" |\n\"lookup ((a,b) # ps) x = (if a = x then Some b else lookup ps x)\"\n\ndefinition sq :: \"nat \\<Rightarrow> nat\" where\n\"sq n = n * n\"\n\nabbreviation sq' :: \"nat \\<Rightarrow> nat\" where\n\"sq' n \\<equiv> n * n\"\n\nfun div2 :: \"nat \\<Rightarrow> nat\" where\n\"div2 0 = 0\" |\n\"div2 (Suc 0) = 0\" |\n\"div2 (Suc(Suc n)) = Suc(div2 n)\"\n\nlemma \"div2(n) = n div 2\"\n  apply(induction n rule: div2.induct)\n  apply(auto)\n  done\n\nfun contents :: \"'a tree \\<Rightarrow> 'a list\" where\n\"contents (Tip) = []\" |\n\"contents (Node l a r) = \n  (contents l)@(a # (contents r))\"\n\nfun sum_tree :: \"nat tree \\<Rightarrow> nat\" where\n\"sum_tree Tip = 0\" |\n\"sum_tree (Node l a r) = sum_tree(l) + a + sum_tree(r)\"\n\nlemma sum_tree_is_sum_list_of_contents :\n  \"sum_tree t = sum_list (contents t)\"\n  apply(induction t )\n  apply(auto)\n  done\n\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2\" \"'a tree2\"\n\nfun mirror2 :: \"'a tree2 \\<Rightarrow> 'a tree2\" where\n\"mirror2 (Tip x) = Tip x\" |\n\"mirror2 (Node l r) = Node (mirror2 r) (mirror2 l)\"\n\nfun pre_order2 :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"pre_order2 (Tip x) = [x]\" |\n\"pre_order2 (Node l r) = pre_order2 l @ pre_order2 r\"\n\nfun post_order2 :: \"'a tree2 \\<Rightarrow> 'a list\" where\n\"post_order2 (Tip x) = [x]\" |\n\"post_order2 (Node l r) = post_order2 r @ post_order2 l\"\n\nlemma \"pre_order2 (mirror2 t) = rev (pre_order2 t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\nfun intersperse :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n\"intersperse _ Nil = Nil\" |\n\"intersperse _ [x] = [x]\" |\n\"intersperse x (y # ys) = [y, x] @ intersperse x ys \"\n\n\nlemma \"map f (intersperse a xs) = intersperse (f a) (map f xs)\"\n  apply(induction xs rule:intersperse.induct)\n   apply(auto)\n  done\n\n", "meta": {"author": "2222-42", "repo": "ConcreteSemantics", "sha": "2b0deccbb51edc31462c0a853fb13346e4e9eeb6", "save_path": "github-repos/isabelle/2222-42-ConcreteSemantics", "path": "github-repos/isabelle/2222-42-ConcreteSemantics/ConcreteSemantics-2b0deccbb51edc31462c0a853fb13346e4e9eeb6/previous_studied_result/Prog_Prove_2_3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.8577681013541613, "lm_q1q2_score": 0.7512221422356306}}
{"text": "theory Generate\n  imports General_Groups \"HOL-Algebra.Algebra\"\nbegin\n\nlemma (in group) generate_sincl:\n  \"A \\<subseteq> generate G A\"\n  using generate.incl by fast\n\nlemma (in group) generate_idem:\n  assumes \"A \\<subseteq> carrier G\"\n  shows \"generate G (generate G A) = generate G A\"\n  using assms generateI group.generate_is_subgroup by blast\n\nlemma (in group) generate_idem':\n  assumes \"A \\<subseteq> carrier G\" \"B \\<subseteq> carrier G\"\n  shows \"generate G (generate G A \\<union> B) = generate G (A \\<union> B)\"\nproof\n  show \"generate G (generate G A \\<union> B) \\<subseteq> generate G (A \\<union> B)\"\n  proof -\n    have \"generate G A \\<union> B \\<subseteq> generate G (A \\<union> B)\"\n    proof -\n      have \"generate G A \\<subseteq> generate G (A \\<union> B)\" using mono_generate by simp\n      moreover have \"B \\<subseteq> generate G (A \\<union> B)\" by (simp add: generate.incl subset_iff)\n      ultimately show ?thesis by simp\n    qed\n    then have \"generate G (generate G A \\<union> B) \\<subseteq> generate G (generate G (A \\<union> B))\" using mono_generate by auto\n    with generate_idem[of \"A \\<union> B\"] show ?thesis using assms by simp\n  qed\n  show \"generate G (A \\<union> B) \\<subseteq> generate G (generate G A \\<union> B)\"\n  proof -\n    have \"A \\<subseteq> generate G A\" using generate.incl by fast\n    thus ?thesis using mono_generate[of \"A \\<union> B\" \"generate G A \\<union> B\"] by blast\n  qed\nqed\n\nlemma (in group) generate_subset_change_eqI:\n  assumes \"A \\<subseteq> carrier G\" \"B \\<subseteq> carrier G\" \"C \\<subseteq> carrier G\" \"generate G A = generate G B\"\n  shows \"generate G (A \\<union> C) = generate G (B \\<union> C)\"\n  by (metis assms generate_idem')\n\nlemma (in group) generate_subgroup_id:\n  assumes \"subgroup H G\"\n  shows \"generate G H = H\"\n  using assms generateI by auto\n\nlemma (in group) generate_consistent':\n  assumes \"subgroup H G\" \"A \\<subseteq> H\"\n  shows \"\\<forall>x \\<in> A. generate G {x} = generate (G\\<lparr>carrier := H\\<rparr>) {x}\"\n  using generate_consistent assms by auto\n\nlemma (in group) generate_idem_Un:\n  assumes \"A \\<subseteq> carrier G\"\n  shows \"generate G (\\<Union>x\\<in>A. generate G {x}) = generate G A\"\nproof\n  have \"A \\<subseteq> (\\<Union>x\\<in>A. generate G {x})\" using generate.incl by force\n  thus \"generate G A \\<subseteq> generate G (\\<Union>x\\<in>A. generate G {x})\" using mono_generate by presburger\n  have \"\\<And>x. x \\<in> A \\<Longrightarrow> generate G {x} \\<subseteq> generate G A\" using mono_generate by auto\n  then have \"(\\<Union>x\\<in>A. generate G {x}) \\<subseteq> generate G A\" by blast\n  thus \"generate G (\\<Union>x\\<in>A. generate G {x}) \\<subseteq> generate G A\" using generate_idem[OF assms] mono_generate by blast\nqed\n\nlemma (in group) generate_idem_fUn:\n  assumes \"f A \\<subseteq> carrier G\"\n  shows \"generate G (\\<Union> {generate G {x} |x. x \\<in> f A}) = generate G (f A)\"\nproof\n  have \"f A \\<subseteq> \\<Union> {generate G {x} |x. x \\<in> f A}\"\n  proof\n    fix x\n    assume x: \"x \\<in> f A\"\n    have \"x \\<in> generate G {x}\" using generate.incl by fast\n    thus \"x \\<in> \\<Union> {generate G {x} |x. x \\<in> f A}\" using x by blast\n  qed\n  thus \"generate G (f A) \\<subseteq> generate G (\\<Union> {generate G {x} |x. x \\<in> f A})\" using mono_generate by auto\n  have \"\\<And>x. x \\<in> f A \\<Longrightarrow> generate G {x} \\<subseteq> generate G (f A)\" using mono_generate by simp\n  then have \"(\\<Union> {generate G {x} |x. x \\<in> f A}) \\<subseteq> generate G (f A)\" by blast\n  with mono_generate[OF this] show \"generate G (\\<Union> {generate G {x} |x. x \\<in> f A}) \\<subseteq> generate G (f A)\" using generate_idem[OF assms] by simp\nqed\n\nlemma (in group) generate_idem_fim_Un:\n  assumes \"\\<Union>(f ` A) \\<subseteq> carrier G\"\n  shows \"generate G (\\<Union>S \\<in> A. generate G (f S)) = generate G (\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)})\"\nproof\n  \n  have \"\\<And>S. S \\<in> A \\<Longrightarrow> generate G (f S) = generate G (\\<Union> {generate G {x} |x. x \\<in> f S})\" using generate_idem_fUn[of f] assms by blast\n  then have \"generate G (\\<Union>S \\<in> A. generate G (f S)) = generate G (\\<Union>S \\<in> A. generate G (\\<Union> {generate G {x} |x. x \\<in> f S}))\" by simp\n\n  have \"\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)} \\<subseteq> (\\<Union>S\\<in>A. generate G (f S))\"\n  proof\n    fix x\n    assume x: \"x \\<in> \\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)}\"\n    then obtain a where a: \"x \\<in> generate G {a}\" \"a \\<in> \\<Union> (f ` A)\" by blast\n    then obtain M where M: \"a \\<in> f M\" \"M \\<in> A\" by blast\n    then have \"generate G {a} \\<subseteq> generate G (f M)\"\n      using generate.incl[OF M(1), of G] mono_generate[of \"{a}\" \"generate G (f M)\"] generate_idem assms by auto\n    then have \"x \\<in> generate G (f M)\" using a by blast\n    thus \"x \\<in> (\\<Union>S\\<in>A. generate G (f S))\" using M by blast\n  qed\n  thus \"generate G (\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)}) \\<subseteq> generate G (\\<Union>S\\<in>A. generate G (f S))\" using mono_generate by simp\n  have a: \"generate G (\\<Union>S\\<in>A. generate G (f S)) \\<subseteq> generate G (\\<Union> (f ` A))\"\n  proof -\n    have \"\\<And>S. S \\<in> A \\<Longrightarrow> generate G (f S) \\<subseteq> generate G (\\<Union> (f ` A))\" using mono_generate[of _ \"\\<Union> (f ` A)\"] by blast\n    then have \"(\\<Union>S\\<in>A. generate G (f S)) \\<subseteq> generate G (\\<Union> (f ` A))\" by blast\n    then have \"generate G (\\<Union>S\\<in>A. generate G (f S)) \\<subseteq> generate G (generate G (\\<Union> (f ` A)))\" using mono_generate by meson\n    thus \"generate G (\\<Union>S\\<in>A. generate G (f S)) \\<subseteq>  generate G (\\<Union> (f ` A))\" using generate_idem assms by blast\n  qed\n  have \"\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)} = (\\<Union>x\\<in>\\<Union> (f ` A). generate G {x})\" by blast\n  with generate_idem_Un[OF assms] have \"generate G (\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)}) = generate G (\\<Union> (f ` A))\" by simp\n  with a show \"generate G (\\<Union>S\\<in>A. generate G (f S)) \\<subseteq> generate G (\\<Union> {generate G {x} |x. x \\<in> \\<Union> (f ` A)})\" by blast\nqed\n\nlemma (in group) generate_singleton_one:\n  assumes \"generate G {a} = {\\<one>}\"\n  shows \"a = \\<one>\"\n  using generate.incl[of a \"{a}\" G] assms by auto\n\nlemma (in group) generate_eqI:\n  assumes \"A \\<subseteq> carrier G\" \"B \\<subseteq> carrier G\" \"A \\<subseteq> generate G B\" \"B \\<subseteq> generate G A\"\n  shows \"generate G A = generate G B\"\n  by (meson assms generate_subgroup_incl group.generate_is_subgroup is_group order_class.order.antisym)\n\nlemma (in group) generate_inv_eq:\n  assumes \"a \\<in> carrier G\"\n  shows \"generate G {a} = generate G {inv a}\"\n  by (intro generate_eqI; use assms generate.inv[of a] generate.inv[of \"inv a\" \"{inv a}\" G] inv_inv[OF assms] in auto)\n\nlemma (in group) generate_eq_imp_subset:\n  assumes \"generate G A = generate G B\"\n  shows \"A \\<subseteq> generate G B\"\n  using generate.incl assms by fast\n\nlemma (in group) generate_subset_eqI:\n  assumes \"A \\<subseteq> carrier G\" \"B \\<subseteq> A\" \"A - B \\<subseteq> generate G B\"\n  shows \"generate G A = generate G B\"\nproof\n  show \"generate G B \\<subseteq> generate G A\" by (intro mono_generate, fact)\n  show \"generate G A \\<subseteq> generate G B\"\n  proof(subst generate_idem[of \"B\", symmetric])\n    show \"generate G A \\<subseteq> generate G (generate G B)\"\n      by (intro mono_generate, use assms generate_sincl[of B] in auto)\n  qed (use assms in blast)\nqed\n\nlemma (in group) generate_one_irrel:\n  \"generate G A = generate G (A \\<union> {\\<one>})\"\nproof\n  show \"generate G A \\<subseteq> generate G (A \\<union> {\\<one>})\" by (intro mono_generate, blast)\n  show \"generate G (A \\<union> {\\<one>}) \\<subseteq> generate G A\"\n  proof\n    fix x\n    assume x: \"x \\<in> generate G (A \\<union> {\\<one>})\"\n    thus \"x \\<in> generate G A\"\n    proof(induction rule: generate.induct)\n    case one\n      then show ?case using generate.one by auto\n    next\n      case (incl h)\n      then show ?case using generate.one generate.incl by fast\n    next\n      case (inv h)\n      then show ?case using generate.one generate.inv by fastforce\n    next\n      case (eng h1 h2)\n      then show ?case using generate.eng by fast\n    qed\n  qed\nqed\n\nlemma (in group) generate_one_irrel':\n  \"generate G A = generate G (A - {\\<one>})\"\nproof\n  show \"generate G (A - {\\<one>}) \\<subseteq> generate G A\" by (intro mono_generate, blast)\n  show \"generate G A \\<subseteq> generate G (A - {\\<one>})\"\n  proof\n    fix x\n    assume x: \"x \\<in> generate G A\"\n    thus \"x \\<in> generate G (A - {\\<one>})\"\n    proof(induction rule: generate.induct)\n    case one\n      then show ?case using generate.one by auto\n    next\n      case i: (incl h)\n      then show ?case\n      proof(cases \"h = \\<one>\")\n        case True\n        then show ?thesis using generate.one by blast\n      next\n        case False\n        with i have \"h \\<in> (A - {\\<one>})\" by blast\n        then show ?thesis using generate.incl by metis\n      qed\n    next\n      case i: (inv h)\n      then show ?case\n      proof(cases \"h = \\<one>\")\n        case True\n        then show ?thesis using generate.one by auto\n      next\n        case False\n        with i have \"h \\<in> (A - {\\<one>})\" by blast\n        then show ?thesis using generate.inv by metis\n      qed\n    next\n      case (eng h1 h2)\n      then show ?case using generate.eng by fast\n    qed\n  qed\nqed\n\nlemma (in group) generate_one_switched_eqI:\n  assumes \"A \\<subseteq> carrier G\" \"a \\<in> A\" \"B = (A - {a}) \\<union> {b}\"\n  and \"b \\<in> generate G A\" \"a \\<in> generate G B\"\n  shows \"generate G A = generate G B\"\nproof\n  have gAc: \"generate G A \\<subseteq> carrier G\" by (intro generate_incl[OF assms(1)])\n  hence Bc: \"B \\<subseteq> carrier G\" using assms by blast\n  show \"generate G A \\<subseteq> generate G B\"\n  proof(subst generate_idem[OF Bc, symmetric], intro mono_generate, rule)\n    fix x\n    assume x: \"x \\<in> A\"\n    show \"x \\<in> generate G B\"\n    proof (cases \"x = a\")\n      case True\n      then show ?thesis using assms by blast\n    next\n      case False\n      with x assms have \"x \\<in> B\" by blast\n      thus ?thesis using generate.incl by metis\n    qed\n  qed\n  show \"generate G B \\<subseteq> generate G A\"\n  proof(subst generate_idem[OF assms(1), symmetric], intro mono_generate, rule)\n    fix x\n    assume x: \"x \\<in> B\"\n    show \"x \\<in> generate G A\"\n    proof (cases \"x = b\")\n      case True\n      then show ?thesis using assms by blast\n    next\n      case False\n      with x assms have \"x \\<in> A\" by blast\n      thus ?thesis using generate.incl by metis\n    qed\n  qed\nqed\n\nlemma (in group) generate_nat_pow:\n  assumes \"ord a \\<noteq> 0\" \"a \\<in> carrier G\"\n  shows \"generate G {a} = {a [^] k |k. k \\<in> {0..ord a - 1}}\"\nproof -\n  obtain n where n: \"n = ord a\" \"n > 0\" using assms by blast\n  have \"\\<And>m. a [^] m = a [^] (m mod int n)\"\n    using n pow_int_mod_ord assms assms(2) by blast\n  moreover have \"\\<And>m. a [^] (m mod int n) \\<in> {a [^] k |k::int. k \\<in> {0..(int n) - 1}}\"\n    using pos_mod_conj[of n] n(2) by auto\n  ultimately have gp:\"\\<And>m::int. a [^] m \\<in> {a [^] k |k::int. k \\<in> {0..(int n) - 1}}\"\n    by presburger\n  then have 1:\"generate G {a} = {a [^] k|k::int. k \\<in> {0..(int n) - 1}}\"\n    using generate_pow[of a] assms(2) by auto\n  have 2:\"{a [^] k|k::int. k \\<in> {0..(int n - 1)}} = {a [^] k|k::nat. k \\<in> {0..n - 1}}\" (is \"?L = ?R\")\n  proof(intro equalityI subsetI)\n    fix x\n    assume \"x \\<in> ?L\"\n    then obtain k where k:\"x = a [^] (k::int)\" \"0 \\<le> k\" \"k < n\" by auto\n    then have \"x = a [^] (nat k)\" by auto\n    moreover have \"nat k \\<in> {0..n-1}\" using k by fastforce\n    ultimately show \"x \\<in> ?R\" by fast\n  next\n    fix x\n    assume \"x \\<in> ?R\"\n    then obtain k where k:\"x = a [^] (k::nat)\" \"k \\<le> n\" by force\n    then have g: \"x = a [^] (int k)\" using int_pow_int[of G a k] by argo\n    thus \"x \\<in> ?L\"\n    proof (cases \"k = n\")\n      case True\n      then have \"x = \\<one>\" using n k assms(2) by auto\n      then show ?thesis using gp by force\n    next\n      case False\n      then have \"int k \\<in> {0::int..(int n - 1)}\" using k by fastforce\n      with g show ?thesis by blast\n    qed\n  qed\n  show ?thesis using 1 2 n by algebra\nqed\n\nlemma (in group) generate_nat_pow':\n  assumes \"ord a \\<noteq> 0\" \"a \\<in> carrier G\"\n  shows \"generate G {a} = {a [^] k |k. k \\<in> {1..ord a}}\"\nproof -\n  have \"{a [^] k |k. k \\<in> {1..ord a}} = {a [^] k |k. k \\<in> {0..ord a - 1}}\"\n  proof -\n    have \"a [^] k \\<in> {a [^] k |k. k \\<in> {0..ord a - 1}}\" if \"k \\<in> {1..ord a}\" for k\n      using that pow_nat_mod_ord[OF assms(2, 1), of \"ord a\"] assms by (cases \"k = ord a\"; force)\n    moreover have \"a [^] k \\<in> {a [^] k |k. k \\<in> {1..ord a}}\" if \"k \\<in> {0..ord a - 1}\" for k\n    proof(cases \"k = 0\")\n      case True\n      hence \"a [^] k = a [^] ord a\" using pow_ord_eq_1[OF assms(2)] by auto\n      moreover have \"ord a \\<in> {1..ord a}\" using assms unfolding atLeastAtMost_def atLeast_def atMost_def by auto\n      ultimately show ?thesis by blast\n    next\n      case False\n      then show ?thesis using that by auto\n    qed \n    ultimately show ?thesis by blast\n  qed\n  with generate_nat_pow[OF assms] show ?thesis by simp\nqed\n\nend", "meta": {"author": "jthomme1", "repo": "group-theory-isabelle", "sha": "ca78c5c929c1fb40e9828a686b83c84d8d295f0e", "save_path": "github-repos/isabelle/jthomme1-group-theory-isabelle", "path": "github-repos/isabelle/jthomme1-group-theory-isabelle/group-theory-isabelle-ca78c5c929c1fb40e9828a686b83c84d8d295f0e/Generate.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8757869786798663, "lm_q2_score": 0.8577681068080749, "lm_q1q2_score": 0.7512221386693928}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.*)\n  theory TIP_sort_nat_NMSortTDSorts\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun minus :: \"Nat => Nat => Nat\" where\n  \"minus (Z) y = Z\"\n| \"minus (S z) (S y2) = minus z y2\"\n\n(*fun did not finish the proof*)\nfunction nmsorttdhalf1 :: \"Nat => Nat\" where\n  \"nmsorttdhalf1 x =\n   (if (x = (S Z)) then Z else\n      (case x of\n         Z => Z\n         | S y => plus (S Z) (nmsorttdhalf1 (minus x (S (S Z))))))\"\n  by pat_completeness auto\n\nfun length :: \"'a list => Nat\" where\n  \"length (nil2) = Z\"\n| \"length (cons2 y l) = plus (S Z) (length l)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun lmerge :: \"Nat list => Nat list => Nat list\" where\n  \"lmerge (nil2) y = y\"\n| \"lmerge (cons2 z x2) (nil2) = cons2 z x2\"\n| \"lmerge (cons2 z x2) (cons2 x3 x4) =\n     (if le z x3 then cons2 z (lmerge x2 (cons2 x3 x4)) else\n        cons2 x3 (lmerge (cons2 z x2) x4))\"\n\nfun ordered :: \"Nat list => bool\" where\n  \"ordered (nil2) = True\"\n| \"ordered (cons2 y (nil2)) = True\"\n| \"ordered (cons2 y (cons2 y2 xs)) =\n     ((le y y2) & (ordered (cons2 y2 xs)))\"\n\nfun take :: \"Nat => 'a list => 'a list\" where\n  \"take x y =\n   (if le x Z then nil2 else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs => (case x of S x2 => cons2 z (take x2 xs))))\"\n\nfun drop :: \"Nat => 'a list => 'a list\" where\n  \"drop x y =\n   (if le x Z then y else\n      (case y of\n         nil2 => nil2\n         | cons2 z xs1 => (case x of S x2 => drop x2 xs1)))\"\n\n(*fun did not finish the proof*)\nfunction nmsorttd :: \"Nat list => Nat list\" where\n  \"nmsorttd (nil2) = nil2\"\n| \"nmsorttd (cons2 y (nil2)) = cons2 y (nil2)\"\n| \"nmsorttd (cons2 y (cons2 x2 x3)) =\n     (let k :: Nat = nmsorttdhalf1 (length (cons2 y (cons2 x2 x3)))\n     in lmerge\n          (nmsorttd (take k (cons2 y (cons2 x2 x3))))\n          (nmsorttd (drop k (cons2 y (cons2 x2 x3)))))\"\n  by pat_completeness auto\n\ntheorem property0 :\n  \"ordered (nmsorttd xs)\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP/TIP15/TIP15/TIP_sort_nat_NMSortTDSorts.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.8128673201042492, "lm_q1q2_score": 0.7512046863006812}}
{"text": "theory Bondy\nimports Main\nbegin\n\nlemma card_less_if_surj_not_inj:\n  \"\\<lbrakk> finite A; f ` A = B; \\<not> inj_on f A \\<rbrakk> \\<Longrightarrow> card B < card A\"\nby (metis assms card_image_le inj_on_iff_eq_card order_le_neq_trans)\n\ntheorem Bondy : \n  assumes \"\\<forall>A \\<in> F. A \\<subseteq> X\" and \"card X \\<ge> 1\" and \"card F = card X\"\n  shows \"\\<exists>D. D \\<subseteq> X & card D < card X & card (inter D ` F) = card F\"\nproof -\n  from assms(2,3) have \"finite F\" and \"finite X\"\n    by (metis card_infinite not_one_le_zero)+\n  { fix m\n    have \"m < card F \\<Longrightarrow> \\<exists>D. D \\<subseteq> X & card D \\<le> m & card (inter D ` F) \\<ge> m + 1\"\n    proof (induction m)\n      case 0\n      hence \"{} \\<subseteq> X & card {} \\<le> 0 & card (inter {} ` F) \\<ge> 0 + 1\"\n        by auto (metis Suc_leI card_eq_0_iff empty_is_image finite_imageI gr0I)\n      thus \"\\<exists>D. (D \\<subseteq> X & card D \\<le> 0 & card (inter D ` F) \\<ge> 0 + 1)\" by blast\n    next\n      case (Suc m)\n      hence \"m < card F\" by arith\n      with Suc.IH obtain D\n        where D: \"D \\<subseteq> X \\<and> card D \\<le> m \\<and> m + 1 \\<le> card (inter D ` F)\" by auto\n      with `finite X` have \"finite D\" by (auto intro: finite_subset)\n      show ?case\n      proof (cases \"card (inter D ` F) = card F\")\n        case True\n        hence \"D \\<subseteq> X \\<and> card D \\<le> Suc m \\<and> Suc m + 1 \\<le> card(inter D ` F)\"\n          using D Suc.prems by auto\n        thus ?thesis by blast\n      next\n        case False\n        hence \"~ inj_on (inter D) F\" by (auto simp: card_image)\n        then obtain A1 A2 where \"A1 \\<in> F\" and \"A2 \\<in> F\" and \n          \"D \\<inter> A1 = D \\<inter> A2\" and \"A1 \\<noteq> A2\"  by (auto simp: inj_on_def)\n        then obtain x where x: \"x : (A1 - A2) \\<union> (A2 - A1)\" by auto\n        from `\\<forall>A \\<in> F. A \\<subseteq> X` `A1 \\<in> F` `A2 \\<in> F` x have \"x : X\" by auto\n        let ?E = \"insert x D\"\n        from D `finite D` have \"card ?E \\<le> Suc m\"\n          by (metis (full_types) Suc_le_mono card_insert_if le_Suc_eq)\n        moreover with D `x:X` have \"?E \\<subseteq> X\" by auto\n        moreover have \"Suc m < card (inter ?E ` F)\"\n        proof -\n          from `D \\<inter> A1 = D \\<inter> A2` have 1: \"(D \\<inter> (?E \\<inter> A1)) = (D \\<inter> (?E \\<inter> A2))\"\n            by auto\n          from x have 2: \"?E Int A1 \\<noteq> ?E Int A2\" by auto\n          have 3: \"inter D \\<circ> inter ?E = inter D\" by auto\n          have 4: \"~ inj_on (inter D) (inter ?E ` F)\"\n            unfolding inj_on_def using 1 2 `A1 \\<in> F` `A2 \\<in> F` by blast\n          from D have \"Suc m \\<le> card (inter D ` F)\" by auto\n          also have \"... < card (inter ?E ` F)\"\n            by (rule card_less_if_surj_not_inj[of _ \"inter D\"])\n              (auto simp add: image_image 3 4 `finite F`)\n          finally show ?thesis .\n        qed\n        ultimately have \"?E\\<subseteq>X \\<and> card ?E \\<le> Suc m \\<and> Suc m + 1 \\<le> card (inter ?E ` F)\" \n          by auto\n        thus \"\\<exists>D\\<subseteq>X. card D \\<le> Suc m \\<and> Suc m + 1 \\<le> card (inter D ` F)\" by blast\n      qed\n    qed\n  }\n  moreover from assms(2,3) have \"card X - 1 < card F\" by auto\n  ultimately obtain D where \n    \"D \\<subseteq> X & card D \\<le> card X - 1 & card (inter D ` F) \\<ge> (card X - 1) + 1\"\n    by auto\n  moreover with `finite F` have \"card (inter D ` F) \\<le> card F\"\n    by (elim card_image_le)\n  ultimately have \"D \\<subseteq> X & card D < card X & card (inter D ` F) = card F\"\n    using `card F = card X` by auto\n  thus ?thesis by auto\nqed\n\nend\n\n", "meta": {"author": "Josh-Tilles", "repo": "AFP", "sha": "f4bf1d502bde2a3469d482b62c531f1c3af3e881", "save_path": "github-repos/isabelle/Josh-Tilles-AFP", "path": "github-repos/isabelle/Josh-Tilles-AFP/AFP-f4bf1d502bde2a3469d482b62c531f1c3af3e881/thys/Bondy/Bondy.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.7512011067252469}}
{"text": "theory Heap \nimports Main\nbegin\n\nsubsection \"References\"\n\ndefinition \"ref = (UNIV::nat set)\"\n\ntypedef ref = ref by (simp add: ref_def)\n\ncode_datatype Abs_ref\n\nlemma finite_nat_ex_max: \n  assumes fin: \"finite (N::nat set)\"\n  shows \"\\<exists>m. \\<forall>n\\<in>N. n < m\"\nusing fin\nproof (induct)\n  case empty\n  show ?case by auto\nnext\n  case (insert k N)\n  have \"\\<exists>m. \\<forall>n\\<in>N. n < m\" by fact\n  then obtain m where m_max: \"\\<forall>n\\<in>N. n < m\"..\n  show \"\\<exists>m. \\<forall>n\\<in>insert k N. n < m\"\n  proof (rule exI [where x=\"Suc (max k m)\"])\n  qed (insert m_max, auto simp add: max_def)\nqed\n\nlemma infinite_nat: \"\\<not>finite (UNIV::nat set)\"\nproof \n  assume fin: \"finite (UNIV::nat set)\"\n  then obtain m::nat where \"\\<forall>n\\<in>UNIV. n < m\"\n    by (rule finite_nat_ex_max [elim_format] ) auto\n  moreover have \"m\\<in>UNIV\"..\n  ultimately show False by blast\nqed \n\nlemma infinite_ref [simp,intro]: \"\\<not>finite (UNIV::ref set)\"\nproof\n  assume \"finite (UNIV::ref set)\"\n  hence \"finite (range Rep_ref)\"\n    by simp\n  moreover\n  have \"range Rep_ref = ref\"\n  proof\n    show \"range Rep_ref \\<subseteq> ref\"\n      by (simp add: ref_def)\n  next\n    show \"ref \\<subseteq> range Rep_ref\"\n    proof\n      fix x\n      assume x: \"x \\<in> ref\"\n      show \"x \\<in> range Rep_ref\"\n        by (rule Rep_ref_induct) (auto simp add: ref_def)\n    qed\n  qed\n  ultimately have \"finite ref\"\n    by simp\n  thus False\n    by (simp add: ref_def infinite_nat)\nqed\n\nconsts Null :: ref \n\ndefinition new :: \"ref set \\<Rightarrow> ref\" where\n  \"new A = (SOME a. a \\<notin> {Null} \\<union> A)\"\n\ntext \\<open>\n  Constant @{const \"Null\"} can be defined later on.  Conceptually\n  @{const \"Null\"} and @{const \"new\"} are \\<open>fixes\\<close> of a locale\n  with @{prop \"finite A \\<Longrightarrow> new A \\<notin> A \\<union> {Null}\"}.  But since definitions\n  relative to a locale do not yet work in Isabelle2005 we use this\n  workaround to avoid lots of parameters in definitions.\n\\<close>\n\nlemma new_notin [simp,intro]:\n \"finite A \\<Longrightarrow> new (A) \\<notin> A\"\n  apply (unfold new_def)\n  apply (rule someI2_ex)\n  apply (fastforce intro: ex_new_if_finite)\n  apply simp\n  done\n\nlemma new_not_Null [simp,intro]:\n  \"finite A \\<Longrightarrow> new (A) \\<noteq> Null\"\n  apply (unfold new_def)\n  apply (rule someI2_ex)\n  apply (fastforce intro: ex_new_if_finite)\n  apply simp\ndone\n\nend", "meta": {"author": "SunHuan321", "repo": "uc-OS-verification", "sha": "760e159857c4015d6a9e3ccbe9f8247e4518862a", "save_path": "github-repos/isabelle/SunHuan321-uc-OS-verification", "path": "github-repos/isabelle/SunHuan321-uc-OS-verification/uc-OS-verification-760e159857c4015d6a9e3ccbe9f8247e4518862a/ucOS_mem_mailbox/Heap.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213691605412, "lm_q2_score": 0.8354835371034368, "lm_q1q2_score": 0.7512011017915339}}
{"text": "(*  Title:       Map Function on Two Parallel Lists\n    Author:      Anders Schlichtkrull <andschl at dtu.dk>, 2017\n    Maintainer:  Anders Schlichtkrull <andschl at dtu.dk>\n*)\n\nsection \\<open>Map Function on Two Parallel Lists\\<close>\n\ntheory Map2\n  imports Main\nbegin\n\ntext \\<open>\nThis theory defines a map function that applies a (curried) binary function elementwise to two\nparallel lists.\n\nThe definition is taken from @{url \"https://www.isa-afp.org/browser_info/current/AFP/Jinja/Listn.html\"}.\n\\<close>\n\nabbreviation map2 :: \"('a \\<Rightarrow> 'b \\<Rightarrow> 'c) \\<Rightarrow> 'a list \\<Rightarrow> 'b list \\<Rightarrow> 'c list\" where\n  \"map2 f xs ys \\<equiv> map (case_prod f) (zip xs ys)\"\n\nlemma map2_empty_iff[simp]: \"map2 f xs ys = [] \\<longleftrightarrow> xs = [] \\<or> ys = []\"\n  by (metis Nil_is_map_conv list.exhaust list.simps(3) zip.simps(1) zip_Cons_Cons zip_Nil)\n\nlemma image_map2: \"length t = length s \\<Longrightarrow> g ` set (map2 f t s) = set (map2 (\\<lambda>a b. g (f a b)) t s)\"\n  by auto\n\nlemma map2_tl: \"length t = length s \\<Longrightarrow> map2 f (tl t) (tl s) = tl (map2 f t s)\"\n  by (metis (no_types, lifting) hd_Cons_tl list.sel(3) map2_empty_iff map_tl tl_Nil zip_Cons_Cons)\n\nlemma map_zip_assoc:\n  \"map f (zip (zip xs ys) zs) = map (\\<lambda>(x, y, z). f ((x, y), z)) (zip xs (zip ys zs))\"\n  by (induct zs arbitrary: xs ys) (auto simp add: zip.simps(2) split: list.splits)\n\nlemma set_map2_ex:\n  assumes \"length t = length s\"\n  shows \"set (map2 f s t) = {x. \\<exists>i < length t. x = f (s ! i) (t ! i)}\"\nproof (rule; rule)\n  fix x\n  assume \"x \\<in> set (map2 f s t)\"\n  then obtain i where i_p: \"i < length (map2 f s t) \\<and> x = map2 f s t ! i\"\n    by (metis in_set_conv_nth)\n  from i_p have \"i < length t\"\n    by auto\n  moreover from this i_p have \"x = f (s ! i) (t ! i)\"\n    using assms by auto\n  ultimately show \"x \\<in> {x. \\<exists>i < length t. x = f (s ! i) (t ! i)}\"\n    using assms by auto\nnext\n  fix x\n  assume \"x \\<in> {x. \\<exists>i < length t. x = f (s ! i) (t ! i)}\"\n  then obtain i where i_p: \"i < length t \\<and> x = f (s ! i) (t ! i)\"\n    by auto\n  then have \"i < length (map2 f s t)\"\n    using assms by auto\n  moreover from i_p have \"x = map2 f s t ! i\"\n    using assms by auto\n  ultimately show \"x \\<in> set (map2 f s t)\"\n    by (metis in_set_conv_nth)\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Ordered_Resolution_Prover/Map2.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8354835207180243, "lm_q2_score": 0.8991213705121083, "lm_q1q2_score": 0.7512010881882715}}
{"text": "(* -------------------------------------------------------------------------- *)\nsection \\<open>Möbius transformations\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Möbius transformations (also called homographic, linear fractional, or bilinear\ntransformations) are the fundamental transformations of the extended complex plane. Here they are\nintroduced algebraically. Each transformation is represented by a regular (non-singular,\nnon-degenerate) $2\\times 2$ matrix that acts linearly on homogeneous coordinates. As proportional\nhomogeneous coordinates represent same points of $\\mathbb{\\overline{C}}$, proportional matrices will\nrepresent the same Möbius transformation.\\<close>\n\ntheory Moebius\nimports Homogeneous_Coordinates\nbegin\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Definition of Möbius transformations\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntypedef moebius_mat = \"{M::complex_mat. mat_det M \\<noteq> 0}\"\n  by (rule_tac x=\"eye\" in exI, simp)\n\nsetup_lifting type_definition_moebius_mat\n\ndefinition moebius_cmat_eq :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> bool\" where                     \n  [simp]: \"moebius_cmat_eq A B \\<longleftrightarrow>  (\\<exists> k::complex. k \\<noteq> 0 \\<and> B = k *\\<^sub>s\\<^sub>m A)\"\n\nlift_definition moebius_mat_eq :: \"moebius_mat \\<Rightarrow> moebius_mat \\<Rightarrow> bool\" is moebius_cmat_eq\n  done\n\nlemma moebius_mat_eq_refl [simp]: \n  shows \"moebius_mat_eq x x\"\n  by transfer simp\n\nquotient_type moebius = moebius_mat / moebius_mat_eq\nproof (rule equivpI)\n  show \"reflp moebius_mat_eq\"\n    unfolding reflp_def\n    by transfer auto\nnext\n  show \"symp moebius_mat_eq\"\n    unfolding symp_def\n    by transfer (auto simp add: symp_def, rule_tac x=\"1/k\" in exI, simp)\nnext\n  show \"transp moebius_mat_eq\"\n    unfolding transp_def\n    by transfer (auto simp add: transp_def, rule_tac x=\"ka*k\" in exI, simp)\nqed\n\ndefinition mk_moebius_cmat :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex_mat\" where\n [simp]: \"mk_moebius_cmat a b c d =\n           (let M = (a, b, c, d)\n             in if mat_det M \\<noteq> 0 then\n                M\n             else\n                eye)\"\n\nlift_definition mk_moebius_mat :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> moebius_mat\" is mk_moebius_cmat\n  by simp\n\nlift_definition mk_moebius :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> moebius\" is mk_moebius_mat\n  done\n\nlemma ex_mk_moebius:\n  shows \"\\<exists> a b c d. M = mk_moebius a b c d \\<and> mat_det (a, b, c, d) \\<noteq> 0\"\nproof (transfer, transfer)\n  fix M :: complex_mat\n  assume \"mat_det M \\<noteq> 0\"\n  obtain a b c d where \"M = (a, b, c, d)\"\n    by (cases M, auto)\n  hence \"moebius_cmat_eq M (mk_moebius_cmat a b c d) \\<and> mat_det (a, b, c, d) \\<noteq> 0\"\n    using \\<open>mat_det M \\<noteq> 0\\<close>\n    by auto (rule_tac x=1 in exI, simp)\n  thus \"\\<exists>a b c d. moebius_cmat_eq M (mk_moebius_cmat a b c d) \\<and> mat_det (a, b, c, d) \\<noteq> 0\"\n    by blast\nqed\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Action on points\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Möbius transformations are given as the action of Möbius group on the points of the\nextended complex plane (in homogeneous coordinates).\\<close>\n\ndefinition moebius_pt_cmat_cvec :: \"complex_mat \\<Rightarrow> complex_vec \\<Rightarrow> complex_vec\" where\n   [simp]: \"moebius_pt_cmat_cvec M z = M *\\<^sub>m\\<^sub>v z\"\n\nlift_definition moebius_pt_mmat_hcoords :: \"moebius_mat \\<Rightarrow> complex_homo_coords \\<Rightarrow> complex_homo_coords\" is moebius_pt_cmat_cvec\n  by auto algebra+\n\nlift_definition moebius_pt :: \"moebius \\<Rightarrow> complex_homo \\<Rightarrow> complex_homo\" is moebius_pt_mmat_hcoords\nproof transfer\n  fix M M' x x'\n  assume \"moebius_cmat_eq M M'\" \"x \\<approx>\\<^sub>v x'\"\n  thus \"moebius_pt_cmat_cvec M x \\<approx>\\<^sub>v moebius_pt_cmat_cvec M' x'\"\n    by (cases \"M\", cases \"x\", auto simp add: field_simps) (rule_tac x=\"k*ka\" in exI, simp)\nqed\n\nlemma bij_moebius_pt [simp]:\n  shows \"bij (moebius_pt M)\"\n  unfolding bij_def inj_on_def surj_def\nproof safe\n  fix x y\n  assume \"moebius_pt M x = moebius_pt M y\"\n  thus \"x = y\"\n  proof (transfer, transfer)\n    fix M x y\n    assume \"mat_det M \\<noteq> 0\" \"moebius_pt_cmat_cvec M x \\<approx>\\<^sub>v moebius_pt_cmat_cvec M y\"\n    thus \"x \\<approx>\\<^sub>v y\"\n      using mult_sv_mv[of _ M x] mult_mv_inv[of _ M]\n      unfolding moebius_pt_cmat_cvec_def\n      by (metis complex_cvec_eq_def)\n  qed\nnext\n  fix y\n  show \"\\<exists>x. y = moebius_pt M x\"\n  proof (transfer, transfer)\n    fix y :: complex_vec and M :: complex_mat\n    assume *: \"y \\<noteq> vec_zero\" \"mat_det M \\<noteq> 0\"\n    let ?iM = \"mat_inv M\"\n    let ?x = \"?iM *\\<^sub>m\\<^sub>v y\"\n    have \"?x \\<noteq> vec_zero\"\n      using *\n      by (metis mat_det_mult mat_eye_r mat_inv_r mult_cancel_right1 mult_mv_nonzero)\n    moreover\n    have \"y \\<approx>\\<^sub>v moebius_pt_cmat_cvec M ?x\"\n      by (simp del: eye_def add: mat_inv_r[OF \\<open>mat_det M \\<noteq> 0\\<close>])\n    ultimately\n    show \"\\<exists>x\\<in>{v. v \\<noteq> vec_zero}. y \\<approx>\\<^sub>v moebius_pt_cmat_cvec M x\"\n      by (rule_tac x=\"?x\" in bexI, simp_all)\n  qed\nqed\n\nlemma moebius_pt_eq_I:                                          \n  assumes \"moebius_pt M z1 = moebius_pt M z2\"\n  shows \"z1 = z2\"\n  using assms\n  using bij_moebius_pt[of M]\n  unfolding bij_def inj_on_def\n  by blast\n\nlemma moebius_pt_neq_I [simp]:\n  assumes \"z1 \\<noteq> z2\"\n  shows \"moebius_pt M z1 \\<noteq> moebius_pt M z2\"\n  using assms\n  by (auto simp add: moebius_pt_eq_I)\n\ndefinition is_moebius :: \"(complex_homo \\<Rightarrow> complex_homo) \\<Rightarrow> bool\" where\n  \"is_moebius f \\<longleftrightarrow> (\\<exists> M. f = moebius_pt M)\"\n\ntext \\<open>In the classic literature Möbius transformations are often expressed in the form\n$\\frac{az+b}{cz+d}$. The following lemma shows that when restricted to finite points, the action\nof Möbius transformations is bilinear.\\<close>\n\nlemma moebius_pt_bilinear:\n  assumes \"mat_det (a, b, c, d) \\<noteq> 0\"\n  shows \"moebius_pt (mk_moebius a b c d) z =\n            (if z \\<noteq> \\<infinity>\\<^sub>h then\n                 ((of_complex a) *\\<^sub>h z +\\<^sub>h (of_complex b)) :\\<^sub>h\n                 ((of_complex c) *\\<^sub>h z +\\<^sub>h (of_complex d))\n             else\n                 (of_complex a) :\\<^sub>h\n                 (of_complex c))\"\n  unfolding divide_def\n  using assms\nproof (transfer, transfer)\n  fix a b c d :: complex and z :: complex_vec\n  obtain z1 z2 where zz: \"z = (z1, z2)\"\n    by (cases z, auto)\n  assume *: \"mat_det (a, b, c, d) \\<noteq> 0\" \"z \\<noteq> vec_zero\"\n  let ?oc = \"of_complex_cvec\"\n  show \"moebius_pt_cmat_cvec (mk_moebius_cmat a b c d) z \\<approx>\\<^sub>v\n       (if \\<not> z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\n        then (?oc a *\\<^sub>v z +\\<^sub>v ?oc b) *\\<^sub>v\n             reciprocal_cvec (?oc c *\\<^sub>v z +\\<^sub>v ?oc d)\n        else ?oc a *\\<^sub>v\n             reciprocal_cvec (?oc c))\"\n  proof (cases \"z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\")\n    case True\n    thus ?thesis\n      using zz *\n      by auto\n  next\n    case False\n    hence \"z2 \\<noteq> 0\"\n      using zz inf_cvec_z2_zero_iff \\<open>z \\<noteq> vec_zero\\<close>\n      by auto\n    thus ?thesis\n      using zz * False\n      using regular_homogenous_system[of a b c d z1 z2]\n      by auto\n  qed\nqed\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Möbius group\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Möbius elements form a group under composition. This group is called the \\emph{projective\ngeneral linear group} and denoted by $PGL(2, \\mathbb{C})$ (the group $SGL(2, \\mathbb{C})$ containing elements\nwith the determinant $1$ can also be considered).\\<close>\n\ntext \\<open>Identity Möbius transformation is represented by the identity matrix.\\<close>\n\ndefinition id_moebius_cmat :: \"complex_mat\" where\n  [simp]: \"id_moebius_cmat = eye\"\n\nlift_definition id_moebius_mmat :: \"moebius_mat\" is id_moebius_cmat\n  by simp\n\nlift_definition id_moebius :: \"moebius\" is id_moebius_mmat\n  done\n\nlemma moebius_pt_moebius_id [simp]:\n  shows \"moebius_pt id_moebius = id\"\n  unfolding id_def\n  apply (rule ext, transfer, transfer)\n  using eye_mv_l\n  by simp\n\nlemma mk_moeibus_id [simp]:\n  shows \"mk_moebius a 0 0 a = id_moebius\"\n  by (transfer, transfer, simp)\n\ntext \\<open>The inverse Möbius transformation is obtained by taking the inverse representative matrix.\\<close>\n\ndefinition moebius_inv_cmat :: \"complex_mat \\<Rightarrow> complex_mat\" where\n  [simp]: \"moebius_inv_cmat M = mat_inv M\"\n\nlift_definition moebius_inv_mmat :: \"moebius_mat \\<Rightarrow> moebius_mat\" is moebius_inv_cmat\n  by (simp add: mat_det_inv)\n\nlift_definition moebius_inv :: \"moebius \\<Rightarrow> moebius\" is \"moebius_inv_mmat\"\nproof (transfer)\n  fix x y\n  assume \"moebius_cmat_eq x y\"\n  thus \"moebius_cmat_eq (moebius_inv_cmat x) (moebius_inv_cmat y)\"\n    by (auto simp add: mat_inv_mult_sm) (rule_tac x=\"1/k\" in exI, simp)\nqed\n\nlemma moebius_inv:\n  shows \"moebius_pt (moebius_inv M) = inv (moebius_pt M)\"\nproof (rule inv_equality[symmetric])\n  fix x\n  show \"moebius_pt (moebius_inv M) (moebius_pt M x) = x\"\n  proof (transfer, transfer)\n    fix M::complex_mat and x::complex_vec\n    assume \"mat_det M \\<noteq> 0\" \"x \\<noteq> vec_zero\"\n    show \"moebius_pt_cmat_cvec (moebius_inv_cmat M) (moebius_pt_cmat_cvec M x) \\<approx>\\<^sub>v x\"\n      using eye_mv_l\n      by (simp add: mat_inv_l[OF \\<open>mat_det M \\<noteq> 0\\<close>])\n  qed\nnext\n  fix y\n  show \"moebius_pt M (moebius_pt (moebius_inv M) y) = y\"\n  proof (transfer, transfer)\n    fix M::complex_mat and y::complex_vec\n    assume \"mat_det M \\<noteq> 0\" \"y \\<noteq> vec_zero\"\n    show \"moebius_pt_cmat_cvec M (moebius_pt_cmat_cvec (moebius_inv_cmat M) y) \\<approx>\\<^sub>v y\"\n      using eye_mv_l\n      by (simp add: mat_inv_r[OF \\<open>mat_det M \\<noteq> 0\\<close>])\n  qed\nqed\n\nlemma is_moebius_inv [simp]:\n  assumes \"is_moebius m\"\n  shows \"is_moebius (inv m)\"\n  using assms\n  using moebius_inv\n  unfolding is_moebius_def\n  by metis\n\nlemma moebius_inv_mk_moebus [simp]:\n  assumes \"mat_det (a, b, c, d) \\<noteq> 0\"\n  shows \"moebius_inv (mk_moebius a b c d) =\n         mk_moebius (d/(a*d-b*c)) (-b/(a*d-b*c)) (-c/(a*d-b*c)) (a/(a*d-b*c))\"\n  using assms\n  by (transfer, transfer) (auto, rule_tac x=1 in exI, simp_all add: field_simps)\n\ntext \\<open>Composition of Möbius elements is obtained by multiplying their representing matrices.\\<close>\n\ndefinition moebius_comp_cmat :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> complex_mat\" where\n  [simp]: \"moebius_comp_cmat M1 M2 = M1 *\\<^sub>m\\<^sub>m M2\"\n\nlift_definition moebius_comp_mmat :: \"moebius_mat \\<Rightarrow> moebius_mat \\<Rightarrow> moebius_mat\" is moebius_comp_cmat\n  by simp\n\nlift_definition moebius_comp :: \"moebius \\<Rightarrow> moebius \\<Rightarrow> moebius\" is moebius_comp_mmat\n  by transfer (simp, (erule exE)+, rule_tac x=\"k*ka\" in exI, simp add: field_simps)\n\nlemma moebius_comp: \n  shows \"moebius_pt (moebius_comp M1 M2) = moebius_pt M1 \\<circ> moebius_pt M2\"\n  unfolding comp_def\n  by (rule ext, transfer, transfer, simp)\n\nlemma moebius_pt_comp [simp]:\n  shows \"moebius_pt (moebius_comp M1 M2) z = moebius_pt M1 (moebius_pt M2 z)\"\n  by (auto simp add: moebius_comp)\n\nlemma is_moebius_comp [simp]:\n  assumes \"is_moebius m1\" and \"is_moebius m2\"\n  shows \"is_moebius (m1 \\<circ> m2)\"\n  using assms\n  unfolding is_moebius_def\n  using moebius_comp\n  by metis\n\nlemma moebius_comp_mk_moebius [simp]:\n  assumes \"mat_det (a, b, c, d) \\<noteq> 0\" and \"mat_det (a', b', c', d') \\<noteq> 0\"\n  shows \"moebius_comp (mk_moebius a b c d) (mk_moebius a' b' c' d') =\n           mk_moebius (a * a' + b * c') (a * b' + b * d') (c * a' + d * c') (c * b' + d * d')\"\n  using mat_det_mult[of \"(a, b, c, d)\" \"(a', b', c', d')\"]\n  using assms\n  by (transfer, transfer) (auto, rule_tac x=1 in exI, simp)\n\ninstantiation moebius :: group_add\nbegin\ndefinition plus_moebius :: \"moebius \\<Rightarrow> moebius \\<Rightarrow> moebius\" where\n  [simp]: \"plus_moebius = moebius_comp\"\n\ndefinition uminus_moebius :: \"moebius \\<Rightarrow> moebius\" where\n  [simp]: \"uminus_moebius = moebius_inv\"\n\ndefinition zero_moebius :: \"moebius\" where\n  [simp]: \"zero_moebius = id_moebius\"\n\ndefinition minus_moebius :: \"moebius \\<Rightarrow> moebius \\<Rightarrow> moebius\" where\n  [simp]: \"minus_moebius A B = A + (-B)\"\n\ninstance proof\n  fix a b c :: moebius\n  show \"a + b + c = a + (b + c)\"\n    unfolding plus_moebius_def\n  proof (transfer, transfer)\n    fix a b c :: complex_mat\n    assume \"mat_det a \\<noteq> 0\" \"mat_det b \\<noteq> 0\" \"mat_det c \\<noteq> 0\"\n    show \"moebius_cmat_eq (moebius_comp_cmat (moebius_comp_cmat a b) c) (moebius_comp_cmat a (moebius_comp_cmat b c))\"\n      by simp (rule_tac x=\"1\" in exI, simp add: mult_mm_assoc)\n  qed\nnext\n  fix a :: moebius\n  show \"a + 0 = a\"\n    unfolding plus_moebius_def zero_moebius_def\n  proof (transfer, transfer)\n    fix A :: complex_mat\n    assume \"mat_det A \\<noteq> 0\"\n    thus \"moebius_cmat_eq (moebius_comp_cmat A id_moebius_cmat) A\"\n      using mat_eye_r\n      by simp\n  qed\nnext\n  fix a :: moebius\n  show \"0 + a = a\"\n    unfolding plus_moebius_def zero_moebius_def\n  proof (transfer, transfer)\n    fix A :: complex_mat\n    assume \"mat_det A \\<noteq> 0\"\n    thus \"moebius_cmat_eq (moebius_comp_cmat id_moebius_cmat A) A\"\n      using mat_eye_l\n      by simp\n  qed\nnext\n  fix a :: moebius\n  show \"- a + a = 0\"\n    unfolding plus_moebius_def uminus_moebius_def zero_moebius_def\n  proof (transfer, transfer)\n    fix a :: complex_mat\n    assume \"mat_det a \\<noteq> 0\"\n    thus \"moebius_cmat_eq (moebius_comp_cmat (moebius_inv_cmat a) a) id_moebius_cmat\"\n      by (simp add: mat_inv_l)\n  qed\nnext\n  fix a b :: moebius\n  show \"a + - b = a - b\"\n    unfolding minus_moebius_def\n    by simp\nqed\nend\n\ntext \\<open>Composition with inverse\\<close>\n\nlemma moebius_comp_inv_left [simp]: \n  shows \"moebius_comp (moebius_inv M) M = id_moebius\"\n  by (metis left_minus plus_moebius_def uminus_moebius_def zero_moebius_def)\n\nlemma moebius_comp_inv_right [simp]:\n  shows \"moebius_comp M (moebius_inv M) = id_moebius\"\n  by (metis right_minus plus_moebius_def uminus_moebius_def zero_moebius_def)\n\nlemma moebius_pt_comp_inv_left [simp]:\n  shows \"moebius_pt (moebius_inv M) (moebius_pt M z) = z\"\n  by (subst moebius_pt_comp[symmetric], simp)\n\nlemma moebius_pt_comp_inv_right [simp]: \n  shows \"moebius_pt M (moebius_pt (moebius_inv M) z) = z\"\n  by (subst moebius_pt_comp[symmetric], simp)\n\nlemma moebius_pt_comp_inv_image_left [simp]:\n  shows \"moebius_pt (moebius_inv M) ` moebius_pt M ` A = A\"\n  by force\n\nlemma moebius_pt_comp_inv_image_right [simp]:\n  shows \"moebius_pt M ` moebius_pt (moebius_inv M) ` A = A\"\n  by force\n\nlemma moebius_pt_invert:\n  assumes \"moebius_pt M z1 = z2\"\n  shows \"moebius_pt (moebius_inv M) z2 = z1\"\n  using assms[symmetric]\n  by simp\n\nlemma moebius_pt_moebius_inv_in_set [simp]:\n  assumes \"moebius_pt M z \\<in> A\"\n  shows \"z \\<in> moebius_pt (moebius_inv M) ` A\"\n  using assms\n  using image_iff\n  by fastforce\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Special kinds of Möbius transformations\\<close>\n(* -------------------------------------------------------------------------- *)\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Reciprocal (1/z) as a Möbius transformation\\<close>\n(* -------------------------------------------------------------------------- *)\n\ndefinition moebius_reciprocal :: \"moebius\" where\n  \"moebius_reciprocal = mk_moebius 0 1 1 0\"\n\nlemma moebius_reciprocal [simp]:\n  shows \"moebius_pt moebius_reciprocal = reciprocal\"\n  unfolding moebius_reciprocal_def\n  by (rule ext, transfer, transfer) (force simp add: split_def)\n\nlemma moebius_reciprocal_inv [simp]:\n  shows \"moebius_inv moebius_reciprocal = moebius_reciprocal\"\n  unfolding moebius_reciprocal_def\n  by (transfer, transfer) simp\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Euclidean similarities as a Möbius transform\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext\\<open>Euclidean similarities include Euclidean isometries (translations and rotations) and \ndilatations.\\<close>\n\ndefinition moebius_similarity :: \"complex \\<Rightarrow> complex \\<Rightarrow> moebius\" where\n  \"moebius_similarity a b = mk_moebius a b 0 1\"\n\nlemma moebius_pt_moebius_similarity [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_pt (moebius_similarity a b) z = (of_complex a) *\\<^sub>h z +\\<^sub>h (of_complex b)\"\n  unfolding moebius_similarity_def\n  using assms\n  using mult_inf_right[of \"of_complex a\"]\n  by (subst moebius_pt_bilinear, auto)\n\ntext \\<open>Their action is a linear transformation of $\\mathbb{C}.$\\<close>\nlemma moebius_pt_moebius_similarity':\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_pt (moebius_similarity a b) = (\\<lambda> z. (of_complex a) *\\<^sub>h z +\\<^sub>h (of_complex b))\"\n  using moebius_pt_moebius_similarity[OF assms, symmetric]\n  by simp\n\nlemma is_moebius_similarity':\n  assumes \"a \\<noteq> 0\\<^sub>h\" and \"a \\<noteq> \\<infinity>\\<^sub>h\" and \"b \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"(\\<lambda> z. a *\\<^sub>h z +\\<^sub>h b) = moebius_pt (moebius_similarity (to_complex a) (to_complex b))\"\nproof-\n  obtain ka kb where *: \"a = of_complex ka\"  \"ka \\<noteq> 0\" \"b = of_complex kb\"\n    using assms\n    using inf_or_of_complex[of a]  inf_or_of_complex[of b]\n    by auto\n  thus ?thesis\n    unfolding is_moebius_def\n    using moebius_pt_moebius_similarity'[of ka kb]\n    by simp\nqed\n\nlemma is_moebius_similarity:\n  assumes \"a \\<noteq> 0\\<^sub>h\" and \"a \\<noteq> \\<infinity>\\<^sub>h\" and \"b \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"is_moebius (\\<lambda> z. a *\\<^sub>h z +\\<^sub>h b)\"\n  using is_moebius_similarity'[OF assms]\n  unfolding is_moebius_def\n  by auto\n\ntext \\<open>Euclidean similarities form a group.\\<close>\n\nlemma moebius_similarity_id [simp]:\n  shows \"moebius_similarity 1 0 = id_moebius\"\n  unfolding moebius_similarity_def\n  by simp\n\nlemma moebius_similarity_inv [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_inv (moebius_similarity a b) = moebius_similarity (1/a) (-b/a)\"\n  using assms\n  unfolding moebius_similarity_def\n  by simp\n\nlemma moebius_similarity_uminus [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"- moebius_similarity a b = moebius_similarity (1/a) (-b/a)\"\n  using assms\n  by simp\n\nlemma moebius_similarity_comp [simp]:\n  assumes \"a \\<noteq> 0\" and \"c \\<noteq> 0\"\n  shows \"moebius_comp (moebius_similarity a b) (moebius_similarity c d) = moebius_similarity (a*c) (a*d+b)\"\n  using assms\n  unfolding moebius_similarity_def\n  by simp\n\nlemma moebius_similarity_plus [simp]:\n  assumes \"a \\<noteq> 0\" and \"c \\<noteq> 0\"\n  shows \"moebius_similarity a b + moebius_similarity c d = moebius_similarity (a*c) (a*d+b)\"\n  using assms\n  by simp\n\ntext \\<open>Euclidean similarities are the only Möbius group elements such that their action leaves the\n$\\infty_{h}$ fixed.\\<close>\nlemma moebius_similarity_inf [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_pt (moebius_similarity a b) \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  using assms\n  unfolding moebius_similarity_def\n  by (transfer, transfer, simp)\n\nlemma moebius_similarity_only_inf_to_inf:\n  assumes \"a \\<noteq> 0\"  \"moebius_pt (moebius_similarity a b) z = \\<infinity>\\<^sub>h\"\n  shows \"z = \\<infinity>\\<^sub>h\"\n  using assms\n  using inf_or_of_complex[of z]\n  by auto\n\nlemma moebius_similarity_inf_iff [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_pt (moebius_similarity a b) z = \\<infinity>\\<^sub>h \\<longleftrightarrow> z = \\<infinity>\\<^sub>h\"\n  using assms\n  using moebius_similarity_only_inf_to_inf[of a b z]\n  by auto\n\nlemma inf_fixed_only_moebius_similarity:\n  assumes \"moebius_pt M \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  shows \"\\<exists> a b. a \\<noteq> 0 \\<and> M = moebius_similarity a b\"\n  using assms\n  unfolding moebius_similarity_def\nproof (transfer, transfer)\n  fix M :: complex_mat\n  obtain a b c d where MM: \"M = (a, b, c, d)\"\n    by (cases M, auto)\n  assume \"mat_det M \\<noteq> 0\" \"moebius_pt_cmat_cvec M \\<infinity>\\<^sub>v \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n  hence *: \"c = 0\" \"a \\<noteq> 0 \\<and> d \\<noteq> 0\"\n    using MM\n    by auto\n  show \"\\<exists>a b. a \\<noteq> 0 \\<and> moebius_cmat_eq M (mk_moebius_cmat a b 0 1)\"\n  proof (rule_tac x=\"a/d\" in exI, rule_tac x=\"b/d\" in exI)\n    show \"a/d \\<noteq> 0 \\<and> moebius_cmat_eq M (mk_moebius_cmat (a / d) (b / d) 0 1)\"\n      using MM *\n      by simp (rule_tac x=\"1/d\" in exI, simp)\n  qed\nqed\n\ntext \\<open>Euclidean similarities include translations, rotations, and dilatations.\\<close>\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Translation\\<close>\n(* -------------------------------------------------------------------------- *)\n\ndefinition moebius_translation where\n  \"moebius_translation v = moebius_similarity 1 v\"\n\nlemma moebius_translation_comp [simp]:\n  shows \"moebius_comp (moebius_translation v1) (moebius_translation v2) = moebius_translation (v1 + v2)\"\n  unfolding moebius_translation_def\n  by (simp add: field_simps)\n\nlemma moebius_translation_plus [simp]:\n  shows \"(moebius_translation v1) + (moebius_translation v2) = moebius_translation (v1 + v2)\"\n  by simp\n\nlemma moebius_translation_zero [simp]:\n  shows \"moebius_translation 0 = id_moebius\"\n  unfolding moebius_translation_def moebius_similarity_id\n  by simp\n\nlemma moebius_translation_inv [simp]:\n  shows \"moebius_inv (moebius_translation v1) = moebius_translation (-v1)\"\n  using moebius_translation_comp[of v1 \"-v1\"] moebius_translation_zero\n  using minus_unique[of \"moebius_translation v1\" \"moebius_translation (-v1)\"]\n  by simp\n\nlemma moebius_translation_uminus [simp]:\n  shows \"- (moebius_translation v1) = moebius_translation (-v1)\"\n  by simp\n\nlemma moebius_translation_inv_translation [simp]:\n  shows \"moebius_pt (moebius_translation v) (moebius_pt (moebius_translation (-v)) z) = z\"\n  using moebius_translation_inv[symmetric, of v]\n  by (simp del: moebius_translation_inv)\n\nlemma moebius_inv_translation_translation [simp]:\n  shows \"moebius_pt (moebius_translation (-v)) (moebius_pt (moebius_translation v) z) = z\"\n  using moebius_translation_inv[symmetric, of v]\n  by (simp del: moebius_translation_inv)\n\nlemma moebius_pt_moebius_translation [simp]:\n  shows \"moebius_pt (moebius_translation v) (of_complex z) = of_complex (z + v)\"\n  unfolding moebius_translation_def\n  by (simp add: field_simps)\n\nlemma moebius_pt_moebius_translation_inf [simp]:\n  shows \"moebius_pt (moebius_translation v) \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  unfolding moebius_translation_def\n  by simp\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Rotation\\<close>\n(* -------------------------------------------------------------------------- *)\n\ndefinition moebius_rotation where\n  \"moebius_rotation \\<phi> = moebius_similarity (cis \\<phi>) 0\"\n\nlemma moebius_rotation_comp [simp]:\n  shows \"moebius_comp (moebius_rotation \\<phi>1) (moebius_rotation \\<phi>2) = moebius_rotation (\\<phi>1 + \\<phi>2)\"\n  unfolding moebius_rotation_def\n  using moebius_similarity_comp[of \"cis \\<phi>1\" \"cis \\<phi>2\" 0 0]\n  by (simp add: cis_mult)\n\nlemma moebius_rotation_plus [simp]:\n  shows \"(moebius_rotation \\<phi>1) + (moebius_rotation \\<phi>2) = moebius_rotation (\\<phi>1 + \\<phi>2)\"\n  by simp\n\nlemma moebius_rotation_zero [simp]:\n  shows \"moebius_rotation 0 = id_moebius\"\n  unfolding moebius_rotation_def\n  using moebius_similarity_id\n  by simp\n\nlemma moebius_rotation_inv [simp]:\n  shows \"moebius_inv (moebius_rotation \\<phi>) = moebius_rotation (- \\<phi>)\"\n  using moebius_rotation_comp[of \\<phi> \"-\\<phi>\"] moebius_rotation_zero\n  using minus_unique[of \"moebius_rotation \\<phi>\" \"moebius_rotation (-\\<phi>)\"]\n  by simp\n\nlemma moebius_rotation_uminus [simp]:\n  shows \"- (moebius_rotation \\<phi>) = moebius_rotation (- \\<phi>)\"\n  by simp\n                                                                                          \nlemma moebius_rotation_inv_rotation [simp]:\n  shows \"moebius_pt (moebius_rotation \\<phi>) (moebius_pt (moebius_rotation (-\\<phi>)) z) = z\"\n  using moebius_rotation_inv[symmetric, of \\<phi>]\n  by (simp del: moebius_rotation_inv)\n\nlemma moebius_inv_rotation_rotation [simp]:\n  shows \"moebius_pt (moebius_rotation (-\\<phi>)) (moebius_pt (moebius_rotation \\<phi>) z) = z\"\n  using moebius_rotation_inv[symmetric, of \\<phi>]\n  by (simp del: moebius_rotation_inv)\n\nlemma moebius_pt_moebius_rotation [simp]:\n  shows \"moebius_pt (moebius_rotation \\<phi>) (of_complex z) = of_complex (cis \\<phi> * z)\"\n  unfolding moebius_rotation_def\n  by simp\n\nlemma moebius_pt_moebius_rotation_inf [simp]:\n  shows \"moebius_pt (moebius_rotation v) \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  unfolding moebius_rotation_def\n  by simp\n\nlemma moebius_pt_rotation_inf_iff [simp]:\n  shows \"moebius_pt (moebius_rotation v) x = \\<infinity>\\<^sub>h \\<longleftrightarrow> x = \\<infinity>\\<^sub>h\"\n  unfolding moebius_rotation_def\n  using cis_neq_zero moebius_similarity_only_inf_to_inf\n  by (simp del: moebius_pt_moebius_similarity)\n\nlemma moebius_pt_moebius_rotation_zero [simp]:\n  shows \"moebius_pt (moebius_rotation \\<phi>) 0\\<^sub>h = 0\\<^sub>h\"\n  unfolding moebius_rotation_def \n  by simp\n\nlemma moebius_pt_moebius_rotation_zero_iff [simp]:\n  shows \"moebius_pt (moebius_rotation \\<phi>) x = 0\\<^sub>h \\<longleftrightarrow> x = 0\\<^sub>h\"\n  using moebius_pt_invert[of \"moebius_rotation \\<phi>\" x \"0\\<^sub>h\"]\n  by auto\n\nlemma moebius_rotation_preserve_cmod [simp]:\n  assumes \"u \\<noteq> \\<infinity>\\<^sub>h\"\n  shows \"cmod (to_complex (moebius_pt (moebius_rotation \\<phi>) u)) = cmod (to_complex u)\"\n  using assms\n  using inf_or_of_complex[of u]\n  by auto\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Dilatation\\<close>\n(* -------------------------------------------------------------------------- *)\n\ndefinition moebius_dilatation where\n  \"moebius_dilatation a = moebius_similarity (cor a) 0\"\n\nlemma moebius_dilatation_comp [simp]:\n  assumes \"a1 > 0\" and \"a2 > 0\"\n  shows \"moebius_comp (moebius_dilatation a1) (moebius_dilatation a2) = moebius_dilatation (a1 * a2)\"\n  using assms                                  \n  unfolding moebius_dilatation_def\n  by simp\n\nlemma moebius_dilatation_plus [simp]:\n  assumes \"a1 > 0\" and \"a2 > 0\"\n  shows \"(moebius_dilatation a1) + (moebius_dilatation a2) = moebius_dilatation (a1 * a2)\"\n  using assms\n  by simp\n\nlemma moebius_dilatation_zero [simp]:\n  shows \"moebius_dilatation 1 = id_moebius\"\n  unfolding moebius_dilatation_def\n  using moebius_similarity_id\n  by simp\n\nlemma moebius_dilatation_inverse [simp]:\n  assumes \"a > 0\"\n  shows \"moebius_inv (moebius_dilatation a) = moebius_dilatation (1/a)\"\n  using assms\n  unfolding moebius_dilatation_def\n  by simp\n\nlemma moebius_dilatation_uminus [simp]:\n  assumes \"a > 0\"\n  shows \"- (moebius_dilatation a) = moebius_dilatation (1/a)\"\n  using assms\n  by simp\n\nlemma moebius_pt_dilatation [simp]:\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_pt (moebius_dilatation a) (of_complex z) = of_complex (cor a * z)\"\n  using assms\n  unfolding moebius_dilatation_def\n  by simp\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Rotation-dilatation\\<close>\n(* -------------------------------------------------------------------------- *)\n\ndefinition moebius_rotation_dilatation where\n  \"moebius_rotation_dilatation a = moebius_similarity a 0\"\n\nlemma moebius_rotation_dilatation:                                     \n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_rotation_dilatation a = moebius_rotation (arg a) + moebius_dilatation (cmod a)\"\n  using assms\n  unfolding moebius_rotation_dilatation_def moebius_rotation_def moebius_dilatation_def\n  by simp\n\n(* -------------------------------------------------------------------------- *)\nsubsubsection \\<open>Conjugate Möbius\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Conjugation is not a Möbius transformation, and conjugate Möbius transformations (obtained\nby conjugating each matrix element) do not represent conjugation function (although they are\nsomewhat related).\\<close>\n\nlift_definition conjugate_moebius_mmat :: \"moebius_mat \\<Rightarrow> moebius_mat\" is mat_cnj\n  by auto\nlift_definition conjugate_moebius :: \"moebius \\<Rightarrow> moebius\" is conjugate_moebius_mmat\n  by transfer (auto simp add: mat_cnj_def)\n\nlemma conjugate_moebius:\n  shows \"conjugate \\<circ> moebius_pt M = moebius_pt (conjugate_moebius M) \\<circ> conjugate\"\n  apply (rule ext, simp)\n  apply (transfer, transfer)\n  using vec_cnj_mult_mv by auto\n\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Decomposition of M\\\"obius transformations\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Every Euclidean similarity can be decomposed using translations, rotations, and dilatations.\\<close>\nlemma similarity_decomposition:\n  assumes \"a \\<noteq> 0\"\n  shows \"moebius_similarity a b = (moebius_translation b) + (moebius_rotation (arg a)) + (moebius_dilatation (cmod a))\"\nproof-\n  have \"moebius_similarity a b = (moebius_translation b) + (moebius_rotation_dilatation a)\"\n    using assms\n    unfolding moebius_rotation_dilatation_def moebius_translation_def moebius_similarity_def\n    by auto\n  thus ?thesis\n    using moebius_rotation_dilatation [OF assms]\n    by (auto simp add: add.assoc simp del: plus_moebius_def)\nqed\n\ntext \\<open>A very important fact is that every Möbius transformation can be\ncomposed of Euclidean similarities and a reciprocation.\\<close>\nlemma moebius_decomposition:\n  assumes \"c \\<noteq> 0\" and \"a*d - b*c \\<noteq> 0\"\n  shows \"mk_moebius a b c d =\n             moebius_translation (a/c) +\n             moebius_rotation_dilatation ((b*c - a*d)/(c*c)) +\n             moebius_reciprocal +\n             moebius_translation (d/c)\"\n  using assms\n  unfolding moebius_rotation_dilatation_def moebius_translation_def moebius_similarity_def plus_moebius_def moebius_reciprocal_def\n  by (simp add: field_simps) (transfer, transfer, auto simp add: field_simps, rule_tac x=\"1/c\" in exI, simp)\n\nlemma moebius_decomposition_similarity:\n  assumes \"a \\<noteq> 0\"\n  shows \"mk_moebius a b 0 d = moebius_similarity (a/d) (b/d)\"\n  using assms\n  unfolding moebius_similarity_def\n  by (transfer, transfer, auto, rule_tac x=\"1/d\" in exI, simp)\n\ntext \\<open>Decomposition is used in many proofs. Namely, to show that every Möbius transformation has\nsome property, it suffices to show that reciprocation and all Euclidean similarities have that\nproperty, and that the property is preserved under compositions.\\<close>\nlemma wlog_moebius_decomposition:\n  assumes\n    trans: \"\\<And> v. P (moebius_translation v)\" and\n    rot: \"\\<And> \\<alpha>. P (moebius_rotation \\<alpha>)\" and\n    dil: \"\\<And> k. P (moebius_dilatation k)\" and\n    recip: \"P (moebius_reciprocal)\" and\n    comp: \"\\<And> M1 M2. \\<lbrakk>P M1; P M2\\<rbrakk> \\<Longrightarrow> P (M1 + M2)\"\n  shows \"P M\"\nproof-\n    obtain a b c d where \"M = mk_moebius a b c d\" \"mat_det (a, b, c, d) \\<noteq> 0\"\n      using ex_mk_moebius[of M]\n      by auto\n    show ?thesis\n    proof (cases \"c = 0\")\n      case False\n      show ?thesis\n        using moebius_decomposition[of c a d b] \\<open>mat_det (a, b, c, d) \\<noteq> 0\\<close> \\<open>c \\<noteq> 0\\<close> \\<open>M = mk_moebius a b c d\\<close>\n        using moebius_rotation_dilatation[of \"(b*c - a*d) / (c*c)\"]\n        using trans[of \"a/c\"] rot[of \"arg ((b*c - a*d) / (c*c))\"] dil[of \"cmod ((b*c - a*d) / (c*c))\"] recip\n        using comp\n        by (simp add: trans)\n    next\n      case True\n      hence \"M = moebius_similarity (a/d) (b/d)\"\n        using \\<open>M = mk_moebius a b c d\\<close> \\<open>mat_det (a, b, c, d) \\<noteq> 0\\<close>\n        using moebius_decomposition_similarity\n        by auto\n      thus ?thesis\n        using \\<open>c = 0\\<close> \\<open>mat_det (a, b, c, d) \\<noteq> 0\\<close>\n        using similarity_decomposition[of \"a/d\" \"b/d\"]\n        using trans[of \"b/d\"] rot[of \"arg (a/d)\"] dil[of \"cmod (a/d)\"] comp\n        by simp\n    qed\nqed\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Cross ratio and Möbius existence\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>For any fixed three points $z1$, $z2$ and $z3$, @{term \"cross_ratio z z1 z2 z3\"} can be seen as\na function of a single variable $z$.\\<close>\n\n\nlemma is_moebius_cross_ratio:\n  assumes \"z1 \\<noteq> z2\" and  \"z2 \\<noteq> z3\" and \"z1 \\<noteq> z3\"\n  shows \"is_moebius (\\<lambda> z. cross_ratio z z1 z2 z3)\"\nproof-\n  have \"\\<exists> M. \\<forall> z. cross_ratio z z1 z2 z3 = moebius_pt M z\"\n    using assms\n  proof (transfer, transfer)\n    fix z1 z2 z3\n    assume vz: \"z1 \\<noteq> vec_zero\" \"z2 \\<noteq> vec_zero\" \"z3 \\<noteq> vec_zero\"\n    obtain z1' z1'' where zz1: \"z1 = (z1', z1'')\"\n      by (cases z1, auto)\n    obtain z2' z2'' where zz2: \"z2 = (z2', z2'')\"\n      by (cases z2, auto)\n    obtain z3' z3'' where zz3: \"z3 = (z3', z3'')\"\n      by (cases z3, auto)\n\n    let ?m23 = \"z2'*z3''-z3'*z2''\"\n    let ?m21 = \"z2'*z1''-z1'*z2''\"\n    let ?m13 = \"z1'*z3''-z3'*z1''\"\n    let ?M = \"(z1''*?m23, -z1'*?m23, z3''*?m21, -z3'*?m21)\"\n    assume \"\\<not> z1 \\<approx>\\<^sub>v z2\" \"\\<not> z2 \\<approx>\\<^sub>v z3\" \"\\<not> z1 \\<approx>\\<^sub>v z3\"\n    hence *: \"?m23 \\<noteq> 0\" \"?m21 \\<noteq> 0\" \"?m13 \\<noteq> 0\"\n      using vz zz1 zz2 zz3\n      using complex_cvec_eq_mix[of z1' z1'' z2' z2'']\n      using complex_cvec_eq_mix[of z1' z1'' z3' z3'']\n      using complex_cvec_eq_mix[of z2' z2'' z3' z3'']\n      by (auto simp del: complex_cvec_eq_def simp add: field_simps)\n\n    have \"mat_det ?M = ?m21*?m23*?m13\"\n      by (simp add: field_simps)\n    hence \"mat_det ?M \\<noteq> 0\"\n      using *\n      by simp\n    moreover\n    have \"\\<forall>z\\<in>{v. v \\<noteq> vec_zero}. cross_ratio_cvec z z1 z2 z3 \\<approx>\\<^sub>v moebius_pt_cmat_cvec ?M z\"\n    proof\n      fix z\n      assume \"z \\<in> {v. v \\<noteq> vec_zero}\"\n      hence \"z \\<noteq> vec_zero\"\n        by simp\n      obtain z' z'' where zz: \"z = (z', z'')\"\n        by (cases z, auto)\n\n      let ?m01 = \"z'*z1''-z1'*z''\"\n      let ?m03 = \"z'*z3''-z3'*z''\"\n\n      have \"?m01 \\<noteq> 0 \\<or> ?m03 \\<noteq> 0\"\n      proof (cases \"z'' = 0 \\<or> z1'' = 0 \\<or> z3'' = 0\")\n        case True\n        thus ?thesis\n          using * \\<open>z \\<noteq> vec_zero\\<close>  zz\n          by auto\n      next\n        case False\n        hence 1: \"z'' \\<noteq> 0 \\<and> z1'' \\<noteq> 0 \\<and> z3'' \\<noteq> 0\"\n          by simp\n        show ?thesis\n        proof (rule ccontr)\n          assume \"\\<not> ?thesis\"\n          hence \"z' * z1'' - z1' * z'' = 0\" \"z' * z3'' - z3' * z'' = 0\"\n            by auto\n          hence \"z1'/z1'' = z3'/z3''\"\n            using 1 zz \\<open>z \\<noteq> vec_zero\\<close>\n            by (metis frac_eq_eq right_minus_eq)\n          thus False\n            using * 1\n            using frac_eq_eq\n            by auto\n        qed\n      qed\n      note * = * this\n      show \"cross_ratio_cvec z z1 z2 z3 \\<approx>\\<^sub>v moebius_pt_cmat_cvec ?M z\"\n        using * zz zz1 zz2 zz3 mult_mv_nonzero[of \"z\" ?M] \\<open>mat_det ?M \\<noteq> 0\\<close>\n        by simp (rule_tac x=\"1\" in exI, simp add: field_simps)\n    qed\n    ultimately\n    show \"\\<exists>M\\<in>{M. mat_det M \\<noteq> 0}.\n              \\<forall>z\\<in>{v. v \\<noteq> vec_zero}. cross_ratio_cvec z z1 z2 z3 \\<approx>\\<^sub>v moebius_pt_cmat_cvec M z\"\n      by blast\n  qed\n  thus ?thesis\n    by (auto simp add: is_moebius_def)\nqed\n\ntext \\<open>Using properties of the cross-ratio, it is shown that there is a Möbius transformation\nmapping any three different points to $0_{hc}$, $1_{hc}$ and $\\infty_{hc}$, respectively.\\<close>\nlemma ex_moebius_01inf:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\"\n  shows \"\\<exists> M. ((moebius_pt M z1 = 0\\<^sub>h) \\<and> (moebius_pt M z2 = 1\\<^sub>h) \\<and> (moebius_pt M z3 = \\<infinity>\\<^sub>h))\"\n  using assms\n  using is_moebius_cross_ratio[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close> \\<open>z1 \\<noteq> z3\\<close>]\n  using cross_ratio_0[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z1 \\<noteq> z3\\<close>] cross_ratio_1[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close>] cross_ratio_inf[OF \\<open>z1 \\<noteq> z3\\<close> \\<open>z2 \\<noteq> z3\\<close>]\n  by (metis is_moebius_def)\n\ntext \\<open>There is a Möbius transformation mapping any three different points to any three different\npoints.\\<close>\nlemma ex_moebius:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\" \n          \"w1 \\<noteq> w2\" and \"w1 \\<noteq> w3\" and \"w2 \\<noteq> w3\"\n  shows \"\\<exists> M. ((moebius_pt M z1 = w1) \\<and> (moebius_pt M z2 = w2) \\<and> (moebius_pt M z3 = w3))\"\nproof-\n  obtain M1 where *: \"moebius_pt M1 z1 = 0\\<^sub>h \\<and> moebius_pt M1 z2 = 1\\<^sub>h \\<and> moebius_pt M1 z3 = \\<infinity>\\<^sub>h\"\n    using ex_moebius_01inf[OF assms(1-3)]\n    by auto\n  obtain M2 where **: \"moebius_pt M2 w1 = 0\\<^sub>h \\<and> moebius_pt M2 w2 = 1\\<^sub>h \\<and> moebius_pt M2 w3 = \\<infinity>\\<^sub>h\"\n    using ex_moebius_01inf[OF assms(4-6)]\n    by auto\n  let ?M = \"moebius_comp (moebius_inv M2) M1\"\n  show ?thesis\n    using * **\n    by (rule_tac x=\"?M\" in exI, auto simp add: moebius_pt_invert)\nqed\n\nlemma ex_moebius_1:\n  shows \"\\<exists> M. moebius_pt M z1 = w1\"\nproof-\n  obtain z2 z3 where \"z1 \\<noteq> z2\" \"z1 \\<noteq> z3\" \"z2 \\<noteq> z3\"\n    using ex_3_different_points[of z1]\n    by auto\n  moreover\n  obtain w2 w3 where \"w1 \\<noteq> w2\" \"w1 \\<noteq> w3\" \"w2 \\<noteq> w3\"\n    using ex_3_different_points[of w1]\n    by auto\n  ultimately\n  show ?thesis\n    using ex_moebius[of z1 z2 z3 w1 w2 w3]\n    by auto\nqed\n\ntext \\<open>The next lemma turns out to have very important applications in further proof development, as\nit enables so called ,,without-loss-of-generality (wlog)'' reasoning \\cite{wlog}. Namely, if the\nproperty is preserved under Möbius transformations, then instead of three arbitrary different\npoints one can consider only the case of points $0_{hc}$, $1_{hc}$, and $\\infty_{hc}$.\\<close>\nlemma wlog_moebius_01inf:\n  fixes M::moebius\n  assumes \"P 0\\<^sub>h 1\\<^sub>h \\<infinity>\\<^sub>h\" and \"z1 \\<noteq> z2\" and \"z2 \\<noteq> z3\" and \"z1 \\<noteq> z3\"\n   \"\\<And> M a b c. P a b c \\<Longrightarrow> P (moebius_pt M a) (moebius_pt M b) (moebius_pt M c)\"\n  shows \"P z1 z2 z3\"\nproof-\n  from assms obtain M where *:\n    \"moebius_pt M z1 = 0\\<^sub>h\"  \"moebius_pt M z2 = 1\\<^sub>h\"   \"moebius_pt M z3 = \\<infinity>\\<^sub>h\"\n    using ex_moebius_01inf[of z1 z2 z3]\n    by auto\n  have **: \"moebius_pt (moebius_inv M) 0\\<^sub>h = z1\"  \"moebius_pt (moebius_inv M) 1\\<^sub>h = z2\" \"moebius_pt (moebius_inv M) \\<infinity>\\<^sub>h = z3\"\n    by (subst *[symmetric], simp)+\n  thus ?thesis\n    using assms\n    by auto\nqed\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Fixed points and Möbius transformation uniqueness\\<close>\n(* -------------------------------------------------------------------------- *)\n\nlemma three_fixed_points_01inf:\n  assumes \"moebius_pt M 0\\<^sub>h = 0\\<^sub>h\" and \"moebius_pt M 1\\<^sub>h = 1\\<^sub>h\" and \"moebius_pt M \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  shows \"M = id_moebius\"\n  using assms\n  by (transfer, transfer, auto)\n\n\n\n  have \"M' + M + (-M') = 0\"\n    unfolding zero_moebius_def\n    apply (rule three_fixed_points_01inf)\n    using * ** assms\n    by (simp add: moebius_comp[symmetric])+\n  thus ?thesis\n    by (metis eq_neg_iff_add_eq_0 minus_add_cancel zero_moebius_def)\nqed\n\nlemma unique_moebius_three_points:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\"\n  assumes \"moebius_pt M1 z1 = w1\" and \"moebius_pt M1 z2 = w2\" and \"moebius_pt M1 z3 = w3\"\n          \"moebius_pt M2 z1 = w1\" and \"moebius_pt M2 z2 = w2\" and \"moebius_pt M2 z3 = w3\"\n  shows \"M1 = M2\"\nproof-\n  let ?M = \"moebius_comp (moebius_inv M2) M1\"\n  have \"moebius_pt ?M z1 = z1\"\n    using \\<open>moebius_pt M1 z1 = w1\\<close> \\<open>moebius_pt M2 z1 = w1\\<close>\n    by (auto simp add: moebius_pt_invert)\n  moreover\n  have \"moebius_pt ?M z2 = z2\"\n    using \\<open>moebius_pt M1 z2 = w2\\<close> \\<open>moebius_pt M2 z2 = w2\\<close>\n    by (auto simp add: moebius_pt_invert)\n  moreover\n  have \"moebius_pt ?M z3 = z3\"\n    using \\<open>moebius_pt M1 z3 = w3\\<close> \\<open>moebius_pt M2 z3 = w3\\<close>\n    by (auto simp add: moebius_pt_invert)\n  ultimately\n  have \"?M = id_moebius\"\n    using assms three_fixed_points\n    by auto\n  thus ?thesis\n    by (metis add_minus_cancel left_minus plus_moebius_def uminus_moebius_def zero_moebius_def)\nqed\n\ntext \\<open>There is a unique Möbius transformation mapping three different points to other three\ndifferent points.\\<close>\n\nlemma ex_unique_moebius_three_points:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\" \n          \"w1 \\<noteq> w2\" and \"w1 \\<noteq> w3\" and \"w2 \\<noteq> w3\"\n  shows \"\\<exists>! M. ((moebius_pt M z1 = w1) \\<and> (moebius_pt M z2 = w2) \\<and> (moebius_pt M z3 = w3))\"\nproof-\n  obtain M where *: \"moebius_pt M z1 = w1 \\<and> moebius_pt M z2 = w2 \\<and> moebius_pt M z3 = w3\"\n    using ex_moebius[OF assms]\n    by auto\n  show ?thesis\n    unfolding Ex1_def\n  proof (rule_tac x=\"M\" in exI, rule)\n    show \"\\<forall>y. moebius_pt y z1 = w1 \\<and> moebius_pt y z2 = w2 \\<and> moebius_pt y z3 = w3 \\<longrightarrow> y = M\"\n      using *\n      using unique_moebius_three_points[OF assms(1-3)]\n      by simp\n  qed (simp add: *)\nqed\n\nlemma ex_unique_moebius_three_points_fun:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\" \n          \"w1 \\<noteq> w2\" and \"w1 \\<noteq> w3\" and \"w2 \\<noteq> w3\"\n  shows \"\\<exists>! f. is_moebius f \\<and> (f z1 = w1) \\<and> (f z2 = w2) \\<and> (f z3 = w3)\"\nproof-\n  obtain M where \"moebius_pt M z1 = w1\" \"moebius_pt M z2 = w2\" \"moebius_pt M z3 = w3\"\n    using ex_unique_moebius_three_points[OF assms]\n    by auto\n  thus ?thesis\n    using ex_unique_moebius_three_points[OF assms]\n    unfolding Ex1_def\n    by (rule_tac x=\"moebius_pt M\" in exI) (auto simp add: is_moebius_def)\nqed\n\ntext \\<open>Different Möbius transformations produce different actions.\\<close>\nlemma unique_moebius_pt:\n  assumes \"moebius_pt M1 = moebius_pt M2\"\n  shows \"M1 = M2\"\n  using assms unique_moebius_three_points[of \"0\\<^sub>h\" \"1\\<^sub>h\" \"\\<infinity>\\<^sub>h\"]\n  by auto\n\nlemma is_cross_ratio_01inf:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\" and \"is_moebius f\"\n  assumes \"f z1 = 0\\<^sub>h\" and \"f z2 = 1\\<^sub>h\" and \"f z3 = \\<infinity>\\<^sub>h\"\n  shows \"f = (\\<lambda> z. cross_ratio z z1 z2 z3)\"\n  using assms\n  using cross_ratio_0[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z1 \\<noteq> z3\\<close>] cross_ratio_1[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close>] cross_ratio_inf[OF \\<open>z1 \\<noteq> z3\\<close> \\<open>z2 \\<noteq> z3\\<close>]\n  using is_moebius_cross_ratio[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close> \\<open>z1 \\<noteq> z3\\<close>]\n  using ex_unique_moebius_three_points_fun[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z1 \\<noteq> z3\\<close> \\<open>z2 \\<noteq> z3\\<close>, of \"0\\<^sub>h\" \"1\\<^sub>h\" \"\\<infinity>\\<^sub>h\"]\n  by auto\n\ntext \\<open>Möbius transformations preserve cross-ratio.\\<close>\nlemma moebius_preserve_cross_ratio [simp]:\n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\"\n  shows \"cross_ratio (moebius_pt M z) (moebius_pt M z1) (moebius_pt M z2) (moebius_pt M z3) =\n         cross_ratio z z1 z2 z3\"\nproof-\n  let ?f = \"\\<lambda> z. cross_ratio z z1 z2 z3\"\n  let ?M = \"moebius_pt M\"\n  let ?iM = \"inv ?M\"\n  have \"(?f \\<circ> ?iM) (?M z1) = 0\\<^sub>h\"\n    using bij_moebius_pt[of M] cross_ratio_0[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z1 \\<noteq> z3\\<close>]\n    by (simp add: bij_def)\n  moreover\n  have \"(?f \\<circ> ?iM) (?M z2) = 1\\<^sub>h\"\n    using bij_moebius_pt[of M]  cross_ratio_1[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close>]\n    by (simp add: bij_def)\n  moreover\n  have \"(?f \\<circ> ?iM) (?M z3) = \\<infinity>\\<^sub>h\"\n    using bij_moebius_pt[of M] cross_ratio_inf[OF \\<open>z1 \\<noteq> z3\\<close> \\<open>z2 \\<noteq> z3\\<close>]\n    by (simp add: bij_def)\n  moreover\n  have \"is_moebius (?f \\<circ> ?iM)\"\n    by (rule is_moebius_comp, rule is_moebius_cross_ratio[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close> \\<open>z1 \\<noteq> z3\\<close>], rule is_moebius_inv, auto simp add: is_moebius_def)\n  moreover\n  have \"?M z1 \\<noteq> ?M z2\" \"?M z1 \\<noteq> ?M z3\"  \"?M z2 \\<noteq> ?M z3\"\n    using assms\n    by simp_all\n  ultimately\n  have \"?f \\<circ> ?iM = (\\<lambda> z. cross_ratio z (?M z1) (?M z2) (?M z3))\"\n    using assms\n    using is_cross_ratio_01inf[of \"?M z1\" \"?M z2\" \"?M z3\" \"?f \\<circ> ?iM\"]\n    by simp\n  moreover\n  have \"(?f \\<circ> ?iM) (?M z) = cross_ratio z z1 z2 z3\"\n    using bij_moebius_pt[of M]\n    by (simp add: bij_def)                             \n  moreover\n  have \"(\\<lambda> z. cross_ratio z (?M z1) (?M z2) (?M z3)) (?M z) = cross_ratio (?M z) (?M z1) (?M z2) (?M z3)\"\n    by simp\n  ultimately\n  show ?thesis\n    by simp\nqed\n\nlemma conjugate_cross_ratio [simp]:                                  \n  assumes \"z1 \\<noteq> z2\" and \"z1 \\<noteq> z3\" and \"z2 \\<noteq> z3\"\n  shows \"cross_ratio (conjugate z) (conjugate z1) (conjugate z2) (conjugate z3) =\n         conjugate (cross_ratio z z1 z2 z3)\"\nproof-\n  let ?f = \"\\<lambda> z. cross_ratio z z1 z2 z3\"\n  let ?M = \"conjugate\"\n  let ?iM = \"conjugate\"\n  have \"(conjugate \\<circ> ?f \\<circ> ?iM) (?M z1) = 0\\<^sub>h\"\n    using cross_ratio_0[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z1 \\<noteq> z3\\<close>]\n    by simp\n  moreover\n  have \"(conjugate \\<circ> ?f \\<circ> ?iM) (?M z2) = 1\\<^sub>h\"\n    using cross_ratio_1[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close>]\n    by simp\n  moreover\n  have \"(conjugate \\<circ> ?f \\<circ> ?iM) (?M z3) = \\<infinity>\\<^sub>h\"\n    using cross_ratio_inf[OF \\<open>z1 \\<noteq> z3\\<close> \\<open>z2 \\<noteq> z3\\<close>]\n    by simp\n  moreover\n  have \"is_moebius (conjugate \\<circ> ?f \\<circ> ?iM)\"\n  proof-\n    obtain M where \"?f = moebius_pt M\"\n      using is_moebius_cross_ratio[OF \\<open>z1 \\<noteq> z2\\<close> \\<open>z2 \\<noteq> z3\\<close> \\<open>z1 \\<noteq> z3\\<close>]\n      by (auto simp add: is_moebius_def)\n    thus ?thesis\n      using conjugate_moebius[of M]\n      by (auto simp add: comp_assoc is_moebius_def)\n  qed\n  moreover\n  have \"?M z1 \\<noteq> ?M z2\" \"?M z1 \\<noteq> ?M z3\"  \"?M z2 \\<noteq> ?M z3\"\n    using assms\n    by (auto simp add: conjugate_inj)\n  ultimately\n  have \"conjugate \\<circ> ?f \\<circ> ?iM = (\\<lambda> z. cross_ratio z (?M z1) (?M z2) (?M z3))\"\n    using assms\n    using is_cross_ratio_01inf[of \"?M z1\" \"?M z2\" \"?M z3\" \"conjugate \\<circ> ?f \\<circ> ?iM\"]\n    by simp\n  moreover\n  have \"(conjugate \\<circ> ?f \\<circ> ?iM) (?M z) = conjugate (cross_ratio z z1 z2 z3)\"\n    by simp\n  moreover\n  have \"(\\<lambda> z. cross_ratio z (?M z1) (?M z2) (?M z3)) (?M z) = cross_ratio (?M z) (?M z1) (?M z2) (?M z3)\"\n    by simp\n  ultimately\n  show ?thesis\n    by simp\nqed\n\nlemma cross_ratio_reciprocal [simp]:\n  assumes \"u \\<noteq> v\" and \"v \\<noteq> w\" and \"u \\<noteq> w\"\n  shows \"cross_ratio (reciprocal z) (reciprocal u) (reciprocal v) (reciprocal w) = \n         cross_ratio z u v w\"\n  using assms\n  by (subst moebius_reciprocal[symmetric])+ (simp del: moebius_reciprocal)                           \n\nlemma cross_ratio_inversion [simp]:\n  assumes \"u \\<noteq> v\" and \"v \\<noteq> w\" and \"u \\<noteq> w\"\n  shows \"cross_ratio (inversion z) (inversion u) (inversion v) (inversion w) = \n         conjugate (cross_ratio z u v w)\"\nproof-                                               \n  have \"reciprocal u \\<noteq> reciprocal v\" \"reciprocal u \\<noteq> reciprocal w\" \"reciprocal v \\<noteq> reciprocal w\"\n    using assms\n    by ((subst moebius_reciprocal[symmetric])+, simp del: moebius_reciprocal)+\n  thus ?thesis\n    using assms\n    unfolding inversion_def\n    by simp\nqed\n\n\nlemma fixed_points_0inf':\n  assumes \"moebius_pt M 0\\<^sub>h = 0\\<^sub>h\" and \"moebius_pt M \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  shows \"\\<exists> k::complex_homo. (k \\<noteq> 0\\<^sub>h \\<and> k \\<noteq> \\<infinity>\\<^sub>h) \\<and> (\\<forall> z. moebius_pt M z = k *\\<^sub>h z)\"\nusing assms\nproof (transfer, transfer)\n  fix M :: complex_mat\n  assume \"mat_det M \\<noteq> 0\"\n  obtain a b c d where MM: \"M = (a, b, c, d)\"\n    by (cases M) auto\n  assume \"moebius_pt_cmat_cvec M 0\\<^sub>v \\<approx>\\<^sub>v 0\\<^sub>v\" \"moebius_pt_cmat_cvec M \\<infinity>\\<^sub>v \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n  hence *: \"b = 0\" \"c = 0\" \"a \\<noteq> 0 \\<and> d \\<noteq> 0\"\n    using MM\n    by auto\n  let ?z = \"(a, d)\"\n  have \"?z \\<noteq> vec_zero\"\n    using *\n    by simp\n  moreover\n  have \"\\<not> ?z \\<approx>\\<^sub>v 0\\<^sub>v \\<and> \\<not> ?z \\<approx>\\<^sub>v \\<infinity>\\<^sub>v\"\n    using *\n    by simp\n  moreover\n  have \"\\<forall>z\\<in>{v. v \\<noteq> vec_zero}. moebius_pt_cmat_cvec M z \\<approx>\\<^sub>v ?z *\\<^sub>v z\"\n    using MM \\<open>mat_det M \\<noteq> 0\\<close> *\n    by force\n  ultimately\n  show \"\\<exists>k\\<in>{v. v \\<noteq> vec_zero}.\n                   (\\<not> k \\<approx>\\<^sub>v 0\\<^sub>v \\<and> \\<not> k \\<approx>\\<^sub>v \\<infinity>\\<^sub>v) \\<and>\n                   (\\<forall>z\\<in>{v. v \\<noteq> vec_zero}. moebius_pt_cmat_cvec M z \\<approx>\\<^sub>v k *\\<^sub>v z)\"\n    by blast\nqed\n\nlemma fixed_points_0inf:\n  assumes \"moebius_pt M 0\\<^sub>h = 0\\<^sub>h\" and \"moebius_pt M \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n  shows \"\\<exists> k::complex_homo. (k \\<noteq> 0\\<^sub>h \\<and> k \\<noteq> \\<infinity>\\<^sub>h) \\<and> moebius_pt M = (\\<lambda> z. k *\\<^sub>h z)\"\n  using fixed_points_0inf'[OF assms]\n  by auto\n\nlemma ex_cross_ratio:\n  assumes \"u \\<noteq> v\" and \"u \\<noteq> w\" and \"v \\<noteq> w\"\n  shows \"\\<exists> z. cross_ratio z u v w = c\"\nproof-\n  obtain M where \"(\\<lambda> z. cross_ratio z u v w) = moebius_pt M\"    \n    using assms is_moebius_cross_ratio[of u v w]\n    unfolding is_moebius_def\n    by auto\n  hence *: \"\\<forall> z. cross_ratio z u v w = moebius_pt M z\"\n    by metis\n  let ?z = \"moebius_pt (-M) c\"\n  have \"cross_ratio ?z u v w = c\"\n    using *\n    by auto\n  thus ?thesis\n    by auto\nqed\n\nlemma unique_cross_ratio:\n  assumes \"u \\<noteq> v\" and \"v \\<noteq> w\" and \"u \\<noteq> w\"\n  assumes \"cross_ratio z u v w = cross_ratio z' u v w\"\n  shows \"z = z'\"\nproof-\n  obtain M where \"(\\<lambda> z. cross_ratio z u v w) = moebius_pt M\"\n    using is_moebius_cross_ratio[OF assms(1-3)]\n    unfolding is_moebius_def\n    by auto\n  hence \"moebius_pt M z = moebius_pt M z'\"\n    using assms(4)\n    by metis\n  thus ?thesis\n    using moebius_pt_eq_I\n    by metis\nqed\n\nlemma ex1_cross_ratio:\n  assumes \"u \\<noteq> v\" and \"u \\<noteq> w\" and \"v \\<noteq> w\"\n  shows \"\\<exists>! z. cross_ratio z u v w = c\"\n  using assms ex_cross_ratio[OF assms, of c] unique_cross_ratio[of u v w]\n  by blast\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Pole\\<close>\n(* -------------------------------------------------------------------------- *)\n\ndefinition is_pole :: \"moebius \\<Rightarrow> complex_homo \\<Rightarrow> bool\" where\n  \"is_pole M z \\<longleftrightarrow> moebius_pt M z = \\<infinity>\\<^sub>h\"\n\nlemma ex1_pole:\n  shows \"\\<exists>! z. is_pole M z\"\n  using bij_moebius_pt[of M]\n  unfolding is_pole_def bij_def inj_on_def surj_def\n  unfolding Ex1_def\n  by (metis UNIV_I)\n\ndefinition pole :: \"moebius \\<Rightarrow> complex_homo\" where\n  \"pole M = (THE z. is_pole M z)\"\n\n\n\nlemma pole_similarity:\n  assumes \"is_pole (moebius_similarity a b) z\" and \"a \\<noteq> 0\"\n  shows \"z = \\<infinity>\\<^sub>h\"\n  using assms\n  unfolding is_pole_def\n  using moebius_similarity_only_inf_to_inf[of a b z]\n  by simp\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Homographies and antihomographies\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Inversion is not a Möbius transformation (it is a canonical example of so called\nanti-Möbius transformations, or antihomographies). All antihomographies are compositions of\nhomographies and conjugation. The fundamental theorem of projective geometry (that we shall not\nprove) states that all automorphisms (bijective functions that preserve the cross-ratio) of\n$\\mathbb{C}P^1$ are either homographies or antihomographies.\\<close>\n\ndefinition is_homography :: \"(complex_homo \\<Rightarrow> complex_homo) \\<Rightarrow> bool\" where\n \"is_homography f \\<longleftrightarrow> is_moebius f\"\n\ndefinition is_antihomography :: \"(complex_homo \\<Rightarrow> complex_homo) \\<Rightarrow> bool\" where\n \"is_antihomography f \\<longleftrightarrow> (\\<exists> f'. is_moebius f' \\<and> f = f' \\<circ> conjugate)\"\n\ntext \\<open>Conjugation is not a Möbius transformation, but is antihomograhpy.\\<close>\nlemma not_moebius_conjugate: \n  shows \"\\<not> is_moebius conjugate\"\nproof\n  assume \"is_moebius conjugate\"\n  then obtain M where *: \"moebius_pt M = conjugate\"\n    unfolding is_moebius_def\n    by metis\n  hence \"moebius_pt M 0\\<^sub>h = 0\\<^sub>h\" \"moebius_pt M 1\\<^sub>h = 1\\<^sub>h\" \"moebius_pt M \\<infinity>\\<^sub>h = \\<infinity>\\<^sub>h\"\n    by auto\n  hence \"M = id_moebius\"\n    using three_fixed_points_01inf\n    by auto\n  hence \"conjugate = id\"\n    using *\n    by simp\n  moreover\n  have \"conjugate ii\\<^sub>h \\<noteq> ii\\<^sub>h\"\n    using of_complex_inj[of \"\\<i>\" \"-\\<i>\"]\n    by (subst of_complex_ii[symmetric])+ (auto simp del: of_complex_ii)\n  ultimately\n  show False\n    by simp\nqed\n\nlemma conjugation_is_antihomography[simp]:\n  shows \"is_antihomography conjugate\"\n  unfolding is_antihomography_def\n  by (rule_tac x=\"id\" in exI, metis fun.map_id0 id_apply is_moebius_def moebius_pt_moebius_id)\n\nlemma inversion_is_antihomography [simp]: \n  shows \"is_antihomography inversion\"\n  using moebius_reciprocal\n  unfolding inversion_sym is_antihomography_def is_moebius_def\n  by metis\n\ntext \\<open>Functions cannot simultaneously be homographies and antihomographies - the disjunction is exclusive.\\<close>\nlemma homography_antihomography_exclusive:\n  assumes \"is_antihomography f\"\n  shows \"\\<not> is_homography f\"\nproof\n  assume \"is_homography f\"\n  then obtain M where \"f = moebius_pt M\"\n    unfolding is_homography_def is_moebius_def\n    by auto\n  then obtain M' where \"moebius_pt M = moebius_pt M' \\<circ> conjugate\"\n    using assms\n    unfolding is_antihomography_def is_moebius_def\n    by auto\n  hence \"conjugate = moebius_pt (-M') \\<circ> moebius_pt M\"\n    by auto\n  hence \"conjugate = moebius_pt (-M' + M)\"\n    by (simp add: moebius_comp)\n  thus False\n    using not_moebius_conjugate\n    unfolding is_moebius_def\n    by metis\nqed\n\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Classification of Möbius transformations\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Möbius transformations can be classified to parabolic, elliptic and loxodromic. We do not\ndevelop this part of the theory in depth.\\<close>\n\nlemma similarity_scale_1:\n  assumes \"k \\<noteq> 0\"\n  shows \"similarity (k *\\<^sub>s\\<^sub>m I) M = similarity I M\"\n  using assms\n  unfolding similarity_def\n  using mat_inv_mult_sm[of k I]\n  by simp\n\nlemma similarity_scale_2:\n  shows \"similarity I (k *\\<^sub>s\\<^sub>m M) = k *\\<^sub>s\\<^sub>m (similarity I M)\"\n  unfolding similarity_def\n  by auto\n\nlemma mat_trace_mult_sm [simp]:\n  shows \"mat_trace (k *\\<^sub>s\\<^sub>m M) = k * mat_trace M\"\n  by (cases M) (simp add: field_simps)\n\ndefinition moebius_mb_cmat :: \"complex_mat \\<Rightarrow> complex_mat \\<Rightarrow> complex_mat\" where\n  [simp]: \"moebius_mb_cmat I M = similarity I M\"\n\nlift_definition moebius_mb_mmat :: \"moebius_mat \\<Rightarrow> moebius_mat \\<Rightarrow> moebius_mat\" is moebius_mb_cmat\n  by (simp add: similarity_def mat_det_inv)\n\nlift_definition moebius_mb :: \"moebius \\<Rightarrow> moebius \\<Rightarrow> moebius\" is moebius_mb_mmat\nproof transfer\n  fix M M' I I'\n  assume \"moebius_cmat_eq M M'\" \"moebius_cmat_eq I I'\"\n  thus \"moebius_cmat_eq (moebius_mb_cmat I M) (moebius_mb_cmat I' M')\"\n    by (auto simp add: similarity_scale_1 similarity_scale_2)\nqed\n\ndefinition similarity_invar_cmat :: \"complex_mat \\<Rightarrow> complex\" where\n  [simp]: \"similarity_invar_cmat M = (mat_trace M)\\<^sup>2 / mat_det M - 4\"\n\nlift_definition similarity_invar_mmat :: \"moebius_mat \\<Rightarrow> complex\" is similarity_invar_cmat\n  done\n\nlift_definition similarity_invar :: \"moebius \\<Rightarrow> complex\" is similarity_invar_mmat\n  by transfer (auto simp add: power2_eq_square field_simps)\n\nlemma similarity_invar_moeibus_mb:\n  shows \"similarity_invar (moebius_mb I M) = similarity_invar M\"\n  by (transfer, transfer, simp)\n\ndefinition similar :: \"moebius \\<Rightarrow> moebius \\<Rightarrow> bool\" where\n  \"similar M1 M2 \\<longleftrightarrow> (\\<exists> I. moebius_mb I M1 = M2)\"\n\nlemma similar_refl [simp]:\n  shows \"similar M M\"\n  unfolding similar_def\n  by (rule_tac x=\"id_moebius\" in exI) (transfer, transfer, simp)\n\nlemma similar_sym:\n  assumes \"similar M1 M2\"\n  shows \"similar M2 M1\"\nproof-\n  from assms obtain I where \"M2 = moebius_mb I M1\"\n    unfolding similar_def\n    by auto\n  hence \"M1 = moebius_mb (moebius_inv I) M2\"\n  proof (transfer, transfer)\n    fix M2 I M1\n    assume \"moebius_cmat_eq M2 (moebius_mb_cmat I M1)\" \"mat_det I \\<noteq> 0\"\n    then obtain k where \"k \\<noteq> 0\" \"similarity I M1 = k *\\<^sub>s\\<^sub>m M2\"\n      by auto\n    thus \"moebius_cmat_eq M1 (moebius_mb_cmat (moebius_inv_cmat I) M2)\"\n      using similarity_inv[of I M1 \"k *\\<^sub>s\\<^sub>m M2\", OF _ \\<open>mat_det I \\<noteq> 0\\<close>]\n      by (auto simp add: similarity_scale_2) (rule_tac x=\"1/k\" in exI, simp)\n  qed\n  thus ?thesis\n    unfolding similar_def\n    by auto\nqed\n\nlemma similar_trans:\n  assumes \"similar M1 M2\" and \"similar M2 M3\"\n  shows \"similar M1 M3\"\nproof-\n  obtain I1 I2 where \"moebius_mb I1 M1 = M2\" \"moebius_mb I2 M2 = M3\"\n    using assms\n    by (auto simp add: similar_def)\n  thus ?thesis\n    unfolding similar_def\n  proof (rule_tac x=\"moebius_comp I1 I2\" in exI, transfer, transfer)\n    fix I1 I2 M1 M2 M3\n    assume \"moebius_cmat_eq (moebius_mb_cmat I1 M1) M2\"\n           \"moebius_cmat_eq (moebius_mb_cmat I2 M2) M3\"\n           \"mat_det I1 \\<noteq> 0\" \"mat_det I2 \\<noteq> 0\"\n    thus \"moebius_cmat_eq (moebius_mb_cmat (moebius_comp_cmat I1 I2) M1) M3\"\n      by (auto simp add: similarity_scale_2) (rule_tac x=\"ka*k\" in exI, simp)\n  qed\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/Moebius.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.8267117962054048, "lm_q1q2_score": 0.7511651377291607}}
{"text": "(* ----------------------------------------------------------------- *)\nsection \\<open>Elementary complex geometry\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>In this section equations and basic properties of the most fundamental objects and relations in\ngeometry -- collinearity, lines, circles and circlines. These are defined by equations in\n$\\mathbb{C}$ (not extended by an infinite point). Later these equations will be generalized to\nequations in the extended complex plane, over homogenous coordinates.\\<close>\n\ntheory Elementary_Complex_Geometry\nimports More_Complex Linear_Systems Angles\nbegin\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Collinear points\\<close>\n(* ----------------------------------------------------------------- *)\n\ndefinition collinear :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex \\<Rightarrow> bool\" where\n  \"collinear z1 z2 z3 \\<longleftrightarrow> z1 = z2 \\<or> Im ((z3 - z1) / (z2 - z1)) = 0\"\n\nlemma collinear_ex_real:\n  shows \"collinear z1 z2 z3 \\<longleftrightarrow>\n         (\\<exists> k::real. z1 = z2 \\<or> z3 - z1 = complex_of_real k * (z2 - z1))\"\n  unfolding collinear_def\n  by (metis Im_complex_of_real add_diff_cancel_right' complex_eq diff_zero legacy_Complex_simps(15) nonzero_mult_div_cancel_right right_minus_eq times_divide_eq_left zero_complex.code)\n\ntext \\<open>Collinearity characterization using determinants\\<close>\nlemma collinear_det:\n  assumes \"\\<not> collinear z1 z2 z3\"\n  shows \"det2 (z3 - z1) (cnj (z3 - z1)) (z1 - z2) (cnj (z1 - z2)) \\<noteq> 0\"\nproof-\n  from assms have \"((z3 - z1) / (z2 - z1)) - cnj ((z3 - z1) / (z2 - z1)) \\<noteq> 0\" \"z2 \\<noteq> z1\"\n    unfolding collinear_def\n    using Complex_Im_express_cnj[of \"(z3 - z1) / (z2 - z1)\"]\n    by (auto simp add: Complex_eq)\n  thus ?thesis\n    by (auto simp add: field_simps)\nqed\n\ntext \\<open>Properties of three collinear points\\<close>\n\nlemma collinear_sym1:\n  shows \"collinear z1 z2 z3 \\<longleftrightarrow> collinear z1 z3 z2\"\n  unfolding collinear_def\n  using div_reals[of \"1\" \"(z3 - z1)/(z2 - z1)\"]  div_reals[of \"1\" \"(z2 - z1)/(z3 - z1)\"]\n  by auto\n\nlemma collinear_sym2':\n  assumes \"collinear z1 z2 z3\"\n  shows \"collinear z2 z1 z3\"\nproof-\n  obtain k where \"z1 = z2 \\<or> z3 - z1 = complex_of_real k * (z2 - z1)\"\n    using assms\n    unfolding collinear_ex_real\n    by auto\n  thus ?thesis\n  proof\n    assume \"z3 - z1 = complex_of_real k * (z2 - z1)\"\n    thus ?thesis\n      unfolding collinear_ex_real\n      by (rule_tac x=\"1-k\" in exI) (auto simp add: field_simps)\n  qed (simp add: collinear_def)\nqed\n\nlemma collinear_sym2:\n  shows \"collinear z1 z2 z3 \\<longleftrightarrow> collinear z2 z1 z3\"\n  using collinear_sym2'[of z1 z2 z3] collinear_sym2'[of z2 z1 z3]\n  by auto\n\ntext \\<open>Properties of four collinear points\\<close>\n\nlemma collinear_trans1:\n  assumes \"collinear z0 z2 z1\" and \"collinear z0 z3 z1\" and \"z0 \\<noteq> z1\"\n  shows \"collinear z0 z2 z3\"\n  using assms\n  unfolding collinear_ex_real\n  by (cases \"z0 = z2\", auto) (rule_tac x=\"k/ka\" in exI, case_tac \"ka = 0\", auto simp add: field_simps)\n\n\n(* ----------------------------------------------------------------- *)\nsubsection \\<open>Euclidean line\\<close>\n(* ----------------------------------------------------------------- *)\n\ntext \\<open>Line is defined by using collinearity\\<close>\ndefinition line :: \"complex \\<Rightarrow> complex \\<Rightarrow> complex set\" where\n  \"line z1 z2 = {z. collinear z1 z2 z}\"\n\nlemma line_points_collinear:\n  assumes \"z1 \\<in> line z z'\" and \"z2 \\<in> line z z'\" and \"z3 \\<in> line z z'\" and \"z \\<noteq> z'\"\n  shows \"collinear z1 z2 z3\"\n  using assms\n  unfolding line_def\n  by (smt collinear_sym1 collinear_sym2' collinear_trans1 mem_Collect_eq)\n\ntext \\<open>Parametric equation of a line\\<close>\nlemma line_param:\n  shows \"z1 + cor k * (z2 - z1) \\<in> line z1 z2\"\n  unfolding line_def\n  by (auto simp add: collinear_def)\n\ntext \\<open>Equation of the line containing two different given points\\<close>\nlemma line_equation:\n  assumes \"z1 \\<noteq> z2\" and \"\\<mu> = rot90 (z2 - z1)\"\n  shows \"line z1 z2 = {z. cnj \\<mu>*z + \\<mu>*cnj z - (cnj \\<mu> * z1 + \\<mu> * cnj z1)  = 0}\"\nproof-\n  {\n    fix z\n    have \"z \\<in> line z1 z2 \\<longleftrightarrow> Im ((z - z1)/(z2 - z1)) = 0\"\n      using assms\n      by (simp add: line_def collinear_def)\n    also have \"... \\<longleftrightarrow> (z - z1)/(z2 - z1) = cnj ((z - z1)/(z2 - z1))\"\n      using complex_diff_cnj[of \"(z - z1)/(z2 - z1)\"]\n      by auto\n    also have \"... \\<longleftrightarrow> (z - z1)*(cnj z2 - cnj z1) = (cnj z - cnj z1)*(z2 - z1)\"\n      using assms(1)\n      using \\<open>(z \\<in> line z1 z2) = is_real ((z - z1) / (z2 - z1))\\<close> calculation is_real_div\n      by auto\n    also have \"... \\<longleftrightarrow> cnj(z2 - z1)*z - (z2 - z1)*cnj z - (cnj(z2 - z1)*z1 - (z2 - z1)*cnj z1) = 0\"\n      by (simp add: field_simps)\n    also have \"... \\<longleftrightarrow> cnj \\<mu> * z + \\<mu> * cnj z  - (cnj \\<mu> * z1 + \\<mu> * cnj z1) = 0\"\n      apply (subst assms)+\n      apply (subst cnj_mix_minus)+\n      by simp\n    finally have \"z \\<in> line z1 z2 \\<longleftrightarrow> cnj \\<mu> * z + \\<mu> * cnj z  - (cnj \\<mu> * z1 + \\<mu> * cnj z1) = 0\"\n      .\n  }\n  thus ?thesis\n    by auto\nqed\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Euclidean circle\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>Definition of the circle with given center and radius. It consists of all\npoints on the distance $r$ from the center $\\mu$.\\<close>\ndefinition circle :: \"complex \\<Rightarrow> real \\<Rightarrow> complex set\" where\n  \"circle \\<mu> r = {z. cmod (z - \\<mu>) = r}\"\n\ntext \\<open>Equation of the circle centered at $\\mu$ with the radius $r$.\\<close>\nlemma circle_equation:\n  assumes \"r \\<ge> 0\"\n  shows \"circle \\<mu> r = {z. z*cnj z - z*cnj \\<mu> - cnj z*\\<mu> + \\<mu>*cnj \\<mu> - cor (r*r) = 0}\"\nproof (safe)\n  fix z\n  assume \"z \\<in> circle \\<mu> r\"\n  hence \"(z - \\<mu>)*cnj (z - \\<mu>) = complex_of_real (r*r)\"\n    unfolding circle_def\n    using complex_mult_cnj_cmod[of \"z - \\<mu>\"]\n    by (auto simp add: power2_eq_square)\n  thus \"z * cnj z - z * cnj \\<mu> - cnj z * \\<mu> + \\<mu> * cnj \\<mu> - cor (r * r) = 0\"\n    by (auto simp add: field_simps)\nnext\n  fix z\n  assume \"z * cnj z - z * cnj \\<mu> - cnj z * \\<mu> + \\<mu> * cnj \\<mu> - cor (r * r) = 0\"\n  hence \"(z - \\<mu>)*cnj (z - \\<mu>) = cor (r*r)\"\n    by (auto simp add: field_simps)\n  thus \"z \\<in> circle \\<mu> r\"\n    using assms\n    using complex_mult_cnj_cmod[of \"z - \\<mu>\"]\n    using power2_eq_imp_eq[of \"cmod (z - \\<mu>)\" r]\n    unfolding circle_def power2_eq_square[symmetric] complex_of_real_def\n    by auto\nqed\n\n(* -------------------------------------------------------------------------- *)\nsubsection \\<open>Circline\\<close>\n(* -------------------------------------------------------------------------- *)\n\ntext \\<open>A very important property of the extended complex plane is that it is possible to treat circles\nand lines in a uniform way. The basic object is \\emph{generalized circle}, or \\emph{circline} for\nshort. We introduce circline equation given in $\\mathbb{C}$, and it will later be generalized to an\nequation in the extended complex plane $\\overline{\\mathbb{C}}$ given in matrix form using a\nHermitean matrix and a quadratic form over homogenous coordinates.\\<close>\n\ndefinition circline where\n  \"circline A BC D = {z. cor A*z*cnj z + cnj BC*z + BC*cnj z + cor D = 0}\"\n\ntext \\<open>Connection between circline and Euclidean circle\\<close>\n\ntext \\<open>Every circline with positive determinant and $A \\neq 0$ represents an Euclidean circle\\<close>\n\nlemma circline_circle:\n  assumes \"A \\<noteq> 0\" and \"A * D \\<le> (cmod BC)\\<^sup>2\"\n  \"cl = circline A BC D\" and\n  \"\\<mu> = -BC/cor A\" and \n  \"r2 = ((cmod BC)\\<^sup>2 - A*D) / A\\<^sup>2\" and \"r = sqrt r2\"\n  shows \"cl = circle \\<mu> r\"\nproof-\n  have *: \"cl = {z. z * cnj z + cnj (BC / cor A) * z + (BC / cor A) * cnj z + cor (D / A) = 0}\"\n    using \\<open>cl = circline A BC D\\<close> \\<open>A \\<noteq> 0\\<close>\n    by (auto simp add: circline_def field_simps)\n\n  have \"r2 \\<ge> 0\"\n  proof-\n    have \"(cmod BC)\\<^sup>2 - A * D \\<ge>  0\"\n      using \\<open>A * D \\<le> (cmod BC)\\<^sup>2\\<close>\n      by auto\n    thus ?thesis\n      using \\<open>A \\<noteq> 0\\<close> \\<open>r2 = ((cmod BC)\\<^sup>2 - A*D) / A\\<^sup>2\\<close>\n      by (metis zero_le_divide_iff zero_le_power2)\n  qed\n  hence **: \"r * r = r2\" \"r \\<ge> 0\"\n    using \\<open>r = sqrt r2\\<close>\n    by (auto simp add: real_sqrt_mult[symmetric])\n\n  have ***: \"- \\<mu> * - cnj \\<mu> - cor r2 = cor (D / A)\"\n    using \\<open>\\<mu> = - BC / complex_of_real A\\<close> \\<open>r2 = ((cmod BC)\\<^sup>2 - A * D) / A\\<^sup>2\\<close>\n    by (auto simp add: power2_eq_square complex_mult_cnj_cmod field_simps)\n       (simp add: add_divide_eq_iff assms(1))\n  thus ?thesis\n    using \\<open>r2 = ((cmod BC)\\<^sup>2 - A*D) / A\\<^sup>2\\<close> \\<open>\\<mu> = - BC / cor A\\<close>\n    by (subst *, subst circle_equation[of r \\<mu>, OF \\<open>r \\<ge> 0\\<close>], subst **) (auto simp add: field_simps power2_eq_square)\nqed\n\nlemma circline_ex_circle:\n  assumes \"A \\<noteq> 0\" and \"A * D \\<le> (cmod BC)\\<^sup>2\" and \"cl = circline A BC D\"\n  shows \"\\<exists> \\<mu> r. cl = circle \\<mu> r\"\n  using circline_circle[OF assms]\n  by auto\n\ntext \\<open>Every Euclidean circle can be represented by a circline\\<close>\n\nlemma circle_circline:\n  assumes \"cl = circle \\<mu> r\" and \"r \\<ge> 0\"\n  shows \"cl = circline 1 (-\\<mu>) ((cmod \\<mu>)\\<^sup>2 - r\\<^sup>2)\"\nproof-\n  have \"complex_of_real ((cmod \\<mu>)\\<^sup>2 - r\\<^sup>2) = \\<mu> * cnj \\<mu> - complex_of_real (r\\<^sup>2)\"\n    by (auto simp add: complex_mult_cnj_cmod)\n  thus \"cl = circline 1 (- \\<mu>) ((cmod \\<mu>)\\<^sup>2 - r\\<^sup>2)\"\n    using assms\n    using circle_equation[of r \\<mu>]\n    unfolding circline_def power2_eq_square\n    by (simp add: field_simps)\nqed\n\nlemma circle_ex_circline:\n  assumes \"cl = circle \\<mu> r\" and \"r \\<ge> 0\"\n  shows \"\\<exists> A BC D. A \\<noteq> 0 \\<and> A*D \\<le> (cmod BC)\\<^sup>2 \\<and> cl = circline A BC D\"\n  using circle_circline[OF assms]\n  using \\<open>r \\<ge> 0\\<close>\n  by (rule_tac x=1 in exI, rule_tac x=\"-\\<mu>\" in exI, rule_tac x=\"Re (\\<mu> * cnj \\<mu>) - (r * r)\" in exI) (simp add: complex_mult_cnj_cmod power2_eq_square)\n\ntext \\<open>Connection between circline and Euclidean line\\<close>\n\ntext \\<open>Every circline with a positive determinant and $A = 0$ represents an Euclidean line\\<close>\n\nlemma circline_line:\n  assumes\n    \"A = 0\" and \"BC \\<noteq> 0\" and\n    \"cl = circline A BC D\" and\n    \"z1 = - cor D * BC / (2 * BC * cnj BC)\" and\n    \"z2 = z1 + \\<i> * sgn (if arg BC > 0 then -BC else BC)\"\n  shows\n    \"cl = line z1 z2\"\nproof-\n  have \"cl = {z. cnj BC*z + BC*cnj z + complex_of_real D = 0}\"\n    using assms\n    by (simp add: circline_def)\n    have \"{z. cnj BC*z + BC*cnj z + complex_of_real D = 0} =\n          {z. cnj BC*z + BC*cnj z - (cnj BC*z1 + BC*cnj z1) = 0}\"\n      using  \\<open>BC \\<noteq> 0\\<close> assms\n      by simp\n    moreover\n    have \"z1 \\<noteq> z2\"\n      using \\<open>BC \\<noteq> 0\\<close> assms\n      by (auto simp add: sgn_eq)\n    moreover\n    have \"\\<exists> k. k \\<noteq> 0 \\<and> BC = cor k*rot90 (z2 - z1)\"\n    proof (cases \"arg BC > 0\")\n      case True\n      thus ?thesis\n        using assms\n        by (rule_tac x=\"(cmod BC)\" in exI, auto simp add: Complex_scale4)\n    next\n      case False\n      thus ?thesis\n        using assms\n        by (rule_tac x=\"-(cmod BC)\" in exI, simp)\n           (smt Complex.Re_sgn Im_sgn cis_arg complex_minus complex_surj mult_minus_right rcis_cmod_arg rcis_def)\n    qed\n    then obtain k where \"cor k \\<noteq> 0\" \"BC = cor k*rot90 (z2 - z1)\"\n      by auto\n    moreover\n    have *: \"\\<And> z. cnj_mix (BC / cor k) z - cnj_mix (BC / cor k) z1 = (1/cor k) * (cnj_mix BC z - cnj_mix BC z1)\"\n      using \\<open>cor k \\<noteq> 0\\<close>\n      by (simp add: field_simps)\n    hence \"{z. cnj_mix BC z - cnj_mix BC z1 = 0} = {z. cnj_mix (BC / cor k) z - cnj_mix (BC / cor k) z1 = 0}\"\n      using \\<open>cor k \\<noteq> 0\\<close>\n      by auto\n    ultimately\n    have \"cl = line z1 z2\"\n      using line_equation[of z1 z2 \"BC/cor k\"] \\<open>cl = {z. cnj BC*z + BC*cnj z + complex_of_real D = 0}\\<close>\n      by auto\n    thus ?thesis\n      using \\<open>z1 \\<noteq> z2\\<close>\n      by blast\nqed\n\nlemma circline_ex_line:\n  assumes \"A = 0\" and \"BC \\<noteq> 0\" and \"cl = circline A BC D\"\n  shows \"\\<exists> z1 z2. z1 \\<noteq> z2 \\<and> cl = line z1 z2\"\nproof-\n  let ?z1 = \"- cor D * BC / (2 * BC * cnj BC)\"\n  let ?z2 = \"?z1 + \\<i> * sgn (if 0 < arg BC then - BC else BC)\"\n  have \"?z1 \\<noteq> ?z2\"\n    using \\<open>BC \\<noteq> 0\\<close>\n    by (simp add: sgn_eq)\n  thus ?thesis\n    using circline_line[OF assms, of ?z1 ?z2] \\<open>BC \\<noteq> 0\\<close>\n    by (rule_tac x=\"?z1\" in exI, rule_tac x=\"?z2\" in exI, simp)\nqed\n\ntext \\<open>Every Euclidean line can be represented by a circline\\<close>\n\nlemma line_ex_circline:\n  assumes \"cl = line z1 z2\" and \"z1 \\<noteq> z2\"\n  shows \"\\<exists> BC D. BC \\<noteq> 0 \\<and> cl = circline 0 BC D\"\nproof-\n  let ?BC = \"rot90 (z2 - z1)\"\n  let ?D = \"Re (- 2 * scalprod z1 ?BC)\"\n  show ?thesis\n  proof (rule_tac x=\"?BC\" in exI, rule_tac x=\"?D\" in exI, rule conjI)\n    show \"?BC \\<noteq> 0\"\n      using \\<open>z1 \\<noteq> z2\\<close> rot90_ii[of \"z2 - z1\"]\n      by auto\n  next\n    have *: \"complex_of_real (Re (- 2 * scalprod z1 (rot90 (z2 - z1)))) = - (cnj_mix z1 (rot90 (z2 - z1)))\"\n      using rot90_ii[of \"z2 - z1\"]\n      by (cases z1, cases z2, simp add: Complex_eq field_simps)\n    show \"cl = circline 0 ?BC ?D\"\n      apply (subst assms, subst line_equation[of z1 z2 ?BC])\n      unfolding circline_def\n      by (fact, simp, subst *, simp add: field_simps)\n  qed\nqed\n\nlemma circline_line':\n  assumes \"z1 \\<noteq> z2\"\n  shows \"circline 0 (\\<i> * (z2 - z1)) (Re (- cnj_mix (\\<i> * (z2 - z1)) z1)) = line z1 z2\"\nproof-\n  let ?B = \"\\<i> * (z2 - z1)\"\n  let ?D = \"Re (- cnj_mix ?B z1)\"\n  have \"circline 0 ?B ?D = {z. cnj ?B*z + ?B*cnj z + complex_of_real ?D = 0}\"\n    using assms\n    by (simp add: circline_def)\n  moreover\n  have \"is_real (- cnj_mix (\\<i> * (z2 - z1)) z1)\"\n    using cnj_mix_real[of ?B z1]\n    by auto\n  hence \"{z. cnj ?B*z + ?B*cnj z + complex_of_real ?D = 0} =\n         {z. cnj ?B*z + ?B*cnj z - (cnj ?B*z1 + ?B*cnj z1) = 0}\"\n    apply (subst complex_of_real_Re, simp)\n    unfolding diff_conv_add_uminus\n    by simp\n  moreover\n  have \"line z1 z2 = {z. cnj_mix (\\<i> * (z2 - z1)) z - cnj_mix (\\<i> * (z2 - z1)) z1 = 0}\"\n    using line_equation[of z1 z2 ?B] assms\n    unfolding rot90_ii\n    by simp\n  ultimately\n  show ?thesis\n    by simp\nqed\n\n(* ---------------------------------------------------------------------------- *)\nsubsection \\<open>Angle between two circles\\<close>\n(* ---------------------------------------------------------------------------- *)\n\ntext \\<open>Given a center $\\mu$ of an Euclidean circle and a point $E$ on it, we define the tangent vector\nin $E$ as the radius vector $\\overrightarrow{\\mu E}$, rotated by $\\pi/2$, clockwise or\ncounterclockwise, depending on the circle orientation. The Boolean @{term p} encodes the orientation\nof the circle, and the function @{term \"sgn_bool p\"} returns $1$ when @{term p} is true, and\n$-1$ when @{term p} is false.\\<close>\n\nabbreviation sgn_bool where\n  \"sgn_bool p \\<equiv> if p then 1 else -1\"\n\ndefinition circ_tang_vec :: \"complex \\<Rightarrow> complex \\<Rightarrow> bool \\<Rightarrow> complex\" where\n  \"circ_tang_vec \\<mu> E p = sgn_bool p * \\<i> * (E - \\<mu>)\"\n\ntext \\<open>Tangent vector is orthogonal to the radius.\\<close>\nlemma circ_tang_vec_ortho:\n  shows \"scalprod (E - \\<mu>) (circ_tang_vec \\<mu> E p) = 0\"\n  unfolding circ_tang_vec_def Let_def\n  by auto\n\ntext \\<open>Changing the circle orientation gives the opposite tangent vector.\\<close>\nlemma circ_tang_vec_opposite_orient:\n  shows \"circ_tang_vec \\<mu> E p = - circ_tang_vec \\<mu> E (\\<not> p)\"\n  unfolding circ_tang_vec_def\n  by auto\n\ntext \\<open>Angle between two oriented circles at their common point $E$ is defined as the angle between\ntangent vectors at $E$. Again we define three different angle measures.\\<close>\n\ntext \\<open>The oriented angle between two circles at the point $E$. The first circle is\ncentered at $\\mu_1$ and its orientation is given by the Boolean $p_1$, \nwhile the second circle is centered at $\\mu_2$ and its orientation is given by \nthe Boolea $p_2$.\\<close>\ndefinition ang_circ where \n  \"ang_circ E \\<mu>1 \\<mu>2 p1 p2 = \\<angle> (circ_tang_vec \\<mu>1 E p1) (circ_tang_vec \\<mu>2 E p2)\"\n\ntext \\<open>The unoriented angle between the two circles\\<close>\ndefinition ang_circ_c where\n  \"ang_circ_c E \\<mu>1 \\<mu>2 p1 p2 = \\<angle>c (circ_tang_vec \\<mu>1 E p1) (circ_tang_vec \\<mu>2 E p2)\"\n\ntext \\<open>The acute angle between the two circles\\<close>\ndefinition ang_circ_a where\n  \"ang_circ_a E \\<mu>1 \\<mu>2 p1 p2 = \\<angle>a (circ_tang_vec \\<mu>1 E p1) (circ_tang_vec \\<mu>2 E p2)\"\n\ntext \\<open>Explicit expression for oriented angle between two circles\\<close>\nlemma ang_circ_simp:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"ang_circ E \\<mu>1 \\<mu>2 p1 p2 =\n         \\<downharpoonright>arg (E - \\<mu>2) - arg (E - \\<mu>1) + sgn_bool p1 * pi / 2 - sgn_bool p2 * pi / 2\\<downharpoonleft>\"\n  unfolding ang_circ_def ang_vec_def circ_tang_vec_def\n  apply (rule canon_ang_eq)\n  using assms\n  using arg_mult_2kpi[of \"sgn_bool p2*\\<i>\" \"E - \\<mu>2\"]\n  using arg_mult_2kpi[of \"sgn_bool p1*\\<i>\" \"E - \\<mu>1\"]\n  apply auto\n     apply (rule_tac x=\"x-xa\" in exI, auto simp add: field_simps)\n    apply (rule_tac x=\"-1+x-xa\" in exI, auto simp add: field_simps)\n   apply (rule_tac x=\"1+x-xa\" in exI, auto simp add: field_simps)\n  apply (rule_tac x=\"x-xa\" in exI, auto simp add: field_simps)\n  done\n\ntext \\<open>Explicit expression for the cosine of angle between two circles\\<close>\nlemma cos_ang_circ_simp:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"cos (ang_circ E \\<mu>1 \\<mu>2 p1 p2) =\n         sgn_bool (p1 = p2) * cos (arg (E - \\<mu>2) - arg (E - \\<mu>1))\"\n  using assms\n  using cos_periodic_pi2[of \"arg (E - \\<mu>2) - arg (E - \\<mu>1)\"]\n  using cos_minus_pi[of \"arg (E - \\<mu>2) - arg (E - \\<mu>1)\"]\n  using ang_circ_simp[OF assms, of p1 p2]\n  by auto\n\ntext \\<open>Explicit expression for the unoriented angle between two circles\\<close>\nlemma ang_circ_c_simp:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"ang_circ_c E \\<mu>1 \\<mu>2 p1 p2 = \n        \\<bar>\\<downharpoonright>arg (E - \\<mu>2) - arg (E - \\<mu>1) + sgn_bool p1 * pi / 2 - sgn_bool p2 * pi / 2\\<downharpoonleft>\\<bar>\"\n  unfolding ang_circ_c_def ang_vec_c_def\n  using ang_circ_simp[OF assms]\n  unfolding ang_circ_def\n  by auto\n\ntext \\<open>Explicit expression for the acute angle between two circles\\<close>\nlemma ang_circ_a_simp:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"ang_circ_a E \\<mu>1 \\<mu>2 p1 p2 = \n         acute_ang (abs (canon_ang (arg(E - \\<mu>2) - arg(E - \\<mu>1) + (sgn_bool p1) * pi/2 - (sgn_bool p2) * pi/2)))\"\n  unfolding ang_circ_a_def ang_vec_a_def\n  using ang_circ_c_simp[OF assms]\n  unfolding ang_circ_c_def\n  by auto\n\ntext \\<open>Acute angle between two circles does not depend on the circle orientation.\\<close>\nlemma ang_circ_a_pTrue:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"ang_circ_a E \\<mu>1 \\<mu>2 p1 p2 = ang_circ_a E \\<mu>1 \\<mu>2 True True\"\nproof (cases \"p1\")\n  case True\n  show ?thesis\n  proof (cases \"p2\")\n    case True\n    show ?thesis\n      using \\<open>p1\\<close> \\<open>p2\\<close>\n      by simp\n  next\n    case False\n    show ?thesis\n      using \\<open>p1\\<close> \\<open>\\<not> p2\\<close>\n      unfolding ang_circ_a_def\n      using circ_tang_vec_opposite_orient[of \\<mu>2 E p2]\n      using ang_vec_a_opposite2\n      by simp\n  qed\nnext\n  case False\n  show ?thesis\n  proof (cases \"p2\")\n    case True\n    show ?thesis\n      using \\<open>\\<not> p1\\<close> \\<open>p2\\<close>\n      unfolding ang_circ_a_def\n      using circ_tang_vec_opposite_orient[of \\<mu>1 E p1]\n      using ang_vec_a_opposite1\n      by simp\n  next\n    case False\n    show ?thesis\n      using \\<open>\\<not> p1\\<close> \\<open>\\<not> p2\\<close>\n      unfolding ang_circ_a_def\n      using circ_tang_vec_opposite_orient[of \\<mu>1 E p1] circ_tang_vec_opposite_orient[of \\<mu>2 E p2]\n      using ang_vec_a_opposite1  ang_vec_a_opposite2\n      by simp\n  qed\nqed\n\ntext \\<open>Definition of the acute angle between the two unoriented circles \\<close>\nabbreviation ang_circ_a' where\n  \"ang_circ_a' E \\<mu>1 \\<mu>2 \\<equiv> ang_circ_a E \\<mu>1 \\<mu>2 True True\"\n\ntext \\<open>A very simple expression for the acute angle between the two circles\\<close>\nlemma ang_circ_a_simp1:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"ang_circ_a E \\<mu>1 \\<mu>2 p1 p2 = \\<angle>a (E - \\<mu>1) (E - \\<mu>2)\"\n  unfolding ang_vec_a_def ang_vec_c_def ang_vec_def\n  by (subst ang_circ_a_pTrue[OF assms, of p1 p2], subst ang_circ_a_simp[OF assms, of True True]) (metis add_diff_cancel)\n\nlemma ang_circ_a'_simp:\n  assumes \"E \\<noteq> \\<mu>1\" and \"E \\<noteq> \\<mu>2\"\n  shows \"ang_circ_a' E \\<mu>1 \\<mu>2 = \\<angle>a (E - \\<mu>1) (E - \\<mu>2)\"\n  by (rule ang_circ_a_simp1[OF assms])\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Complex_Geometry/Elementary_Complex_Geometry.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.826711791935942, "lm_q1q2_score": 0.7511651358955724}}
{"text": "section\\<open>Background material for the graph-theoretic aspects of the main proof\\<close>\ntext \\<open>This section includes a number of lemmas on project specific definitions for graph theory, \nbuilding on the general undirected graph theory library \\cite{Undirected_Graph_Theory-AFP} \\<close>\n\n(*\n  Session: Balog_Szemeredi_Gowers\n  Title:   Graph_Theory_Preliminaries.thy\n  Authors: Angeliki Koutsoukou-Argyraki, Mantas Bakšys, and Chelsea Edmonds\n  Affiliation: University of Cambridge\n  Date: August 2022.\n*)\n\ntheory Graph_Theory_Preliminaries\n  imports \n    Miscellaneous_Lemmas\n    Undirected_Graph_Theory.Bipartite_Graphs\n    Undirected_Graph_Theory.Connectivity\n    Random_Graph_Subgraph_Threshold.Ugraph_Misc\nbegin\n\nsubsection\\<open>On graphs with loops\\<close>\n\ncontext ulgraph\n\nbegin\n\ndefinition degree_normalized:: \"'a \\<Rightarrow> 'a set \\<Rightarrow> real\" where \n  \"degree_normalized v S \\<equiv> card (neighbors_ss v S) / (card S)\"\n\nlemma degree_normalized_le_1: \"degree_normalized x S \\<le> 1\"\n\nproof(cases \"finite S\")\n  assume hA: \"finite S\"\n  then have \"card (neighbors_ss x S) \\<le> card S\" using neighbors_ss_def card_mono hA \n    by fastforce\n  then show ?thesis using degree_normalized_def divide_le_eq_1\n    by (metis antisym_conv3 of_nat_le_iff of_nat_less_0_iff)\nnext\n  case False\n  then show ?thesis using degree_normalized_def by auto\nqed\n\nend\n\nsubsection\\<open>On bipartite graphs \\<close>\n\n\ncontext bipartite_graph\nbegin\n\n(* codegree counts the number of paths between two vertices, including loops *)\ndefinition codegree:: \"'a \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"codegree v u \\<equiv> card {x \\<in> V . vert_adj v x \\<and> vert_adj u x}\"\n\nlemma codegree_neighbors: \"codegree v u = card (neighborhood v \\<inter> neighborhood u)\"\n  unfolding codegree_def neighborhood_def \n\nproof -\n  have \"{x \\<in> V. vert_adj v x \\<and> vert_adj u x} = {va \\<in> V. vert_adj v va} \\<inter> {v \\<in> V. vert_adj u v}\"\n    by blast\n  thus \"card {x \\<in> V. vert_adj v x \\<and> vert_adj u x} = card ({va \\<in> V. vert_adj v va} \\<inter> {v \\<in> V. vert_adj u v})\"\n    by auto\nqed\n\nlemma codegree_sym: \"codegree v u = codegree u v\"\n  by (simp add: Int_commute codegree_neighbors) \n\ndefinition codegree_normalized:: \"'a \\<Rightarrow> 'a \\<Rightarrow> 'a set \\<Rightarrow> real\" where \n  \"codegree_normalized v u S \\<equiv> codegree v u / card S\"\n\nlemma codegree_normalized_altX: \n  assumes \"x \\<in> X\" and \"x' \\<in> X\"\n  shows \"codegree_normalized x x' Y = card (neighbors_ss x Y \\<inter> neighbors_ss x' Y) / card Y\"\n\nproof -\n  have \"((neighbors_ss x Y) \\<inter> (neighbors_ss x' Y)) = neighborhood x \\<inter> neighborhood x'\"\n    using neighbors_ss_eq_neighborhoodX assms by auto\n  then show ?thesis unfolding codegree_normalized_def\n    using codegree_def codegree_neighbors by presburger \nqed\n\nlemma codegree_normalized_altY: \n  assumes \"y \\<in> Y\" and \"y' \\<in> Y\"\n  shows \"codegree_normalized y y' X = card (neighbors_ss y X \\<inter> neighbors_ss y' X) / card X\"\n\nproof -\n  have \"neighbors_ss y X \\<inter> neighbors_ss y' X = neighborhood y \\<inter> neighborhood y'\"\n    using neighbors_ss_eq_neighborhoodY assms by auto\n  then show ?thesis unfolding codegree_normalized_def\n    using codegree_def codegree_neighbors by presburger \nqed\n\nlemma codegree_normalized_sym: \"codegree_normalized u v S = codegree_normalized v u S\"\n  unfolding codegree_normalized_def using codegree_sym by simp\n\ndefinition bad_pair:: \" 'a \\<Rightarrow> 'a \\<Rightarrow> 'a set \\<Rightarrow> real \\<Rightarrow> bool\" where \n  \"bad_pair v u S c \\<equiv> codegree_normalized v u S < c\"\n\nlemma bad_pair_sym: \n  assumes \"bad_pair v u S c\" shows \"bad_pair u v S c\"\n  using assms bad_pair_def codegree_normalized_def\n  by (simp add: codegree_normalized_sym)\n\ndefinition bad_pair_set:: \"'a set \\<Rightarrow> 'a set \\<Rightarrow> real \\<Rightarrow> ('a \\<times> 'a) set\" where \n  \"bad_pair_set S T c  \\<equiv> {(u, v) \\<in> S \\<times> S. bad_pair u v T c}\"\n\nlemma bad_pair_set_ss: \"bad_pair_set S T c \\<subseteq> S \\<times> S\"\n  by (auto simp add: bad_pair_set_def)\n\nlemma bad_pair_set_filter_alt: \n  \"bad_pair_set S T c = Set.filter (\\<lambda> p . bad_pair (fst p) (snd p) T c) (S \\<times> S)\" \n  using bad_pair_set_def by auto\n\nlemma bad_pair_set_finite: \n  assumes \"finite S\"\n  shows \"finite (bad_pair_set S T c)\"\nproof -\n  have \"finite (S \\<times> S)\" using finite_cartesian_product assms by blast\n  thus ?thesis using bad_pair_set_filter_alt finite_filter by auto\nqed\n\nlemma codegree_is_path_length_two:\n  \"codegree x x' = card {p . connecting_path x x' p \\<and> walk_length p = 2}\" \n  unfolding codegree_def \nproof-\n  define f:: \"'a list \\<Rightarrow> 'a\" where \"f = (\\<lambda> p. p!1)\"\n  have f_inj: \"inj_on f {p . connecting_path x x' p \\<and> walk_length p = 2}\"\n    unfolding f_def \n  proof (intro inj_onI, simp del: One_nat_def)\n    fix a b assume ha: \"connecting_path x x' a \\<and> walk_length a = 2\" and \n      hb: \"connecting_path x x' b \\<and> walk_length b = 2\" and 1: \"a!1 = b!1\"\n    then have len: \"length a = 3\" \"length b = 3\" using walk_length_conv by auto\n    show \"a = b\" using list2_middle_singleton 1 len list_middle_eq ha hb connecting_path_def len by metis \n  qed\n  have f_image: \"f ` {p . connecting_path x x' p \\<and> walk_length p = 2} = \n    {xa \\<in> V. vert_adj x xa \\<and> vert_adj x' xa}\"\n  proof(intro subset_antisym)\n    show \"f ` {p. connecting_path x x' p \\<and> walk_length p = 2}\n    \\<subseteq> {xa \\<in> V. vert_adj x xa \\<and> vert_adj x' xa}\"\n    proof (intro subsetI)\n      fix a assume \"a \\<in> f ` {p. connecting_path x x' p \\<and> walk_length p = 2}\"\n      then obtain p where ha: \"p!1 = a\" and hp: \"connecting_path x x' p\" and hpl: \"length p = 3\" \n        using f_def walk_length_conv by auto\n      have \"p ! 0 = x\" using hd_conv_nth[of p] hpl hp connecting_path_def by fastforce \n      then have va1: \"vert_adj x a\" using is_walk_index[of 0 p] hp connecting_path_def is_gen_path_def \n          vert_adj_def ha hpl by auto\n      have \"p ! 2 = x'\" using last_conv_nth[of p] hpl hp connecting_path_def by fastforce\n      then have \"vert_adj a x'\" using is_walk_index[of 1 p] hp connecting_path_def is_gen_path_def \n          vert_adj_def ha hpl by (metis One_nat_def le0 lessI numeral_3_eq_3 one_add_one)\n      then show \"a \\<in> {a \\<in> V. vert_adj x a \\<and> vert_adj x' a}\" \n        using va1 vert_adj_sym by (simp add: vert_adj_imp_inV)\n    qed\n    show \"{xa \\<in> V. vert_adj x xa \\<and> vert_adj x' xa}\n      \\<subseteq> f ` {p. connecting_path x x' p \\<and> walk_length p = 2}\"\n    proof (intro subsetI)\n      fix a assume ha: \"a \\<in> {xa \\<in> V. vert_adj x xa \\<and> vert_adj x' xa}\"\n      then have \"a \\<in> V\" and \"x \\<in> V\" and \"x' \\<in> V\" and \"vert_adj x a\" and \"vert_adj x' a\"\n        using vert_adj_imp_inV by auto\n      then have \"is_gen_path [x, a, x']\" \n        using is_walk_def vert_adj_def vert_adj_sym ha singleton_not_edge is_gen_path_def by auto (* Slow *)\n      then have \"connecting_path x x' [x, a, x']\"\n        unfolding connecting_path_def vert_adj_def hd_conv_nth last_conv_nth by simp\n      moreover have \"walk_length [x, a, x'] = 2\" using walk_length_conv by simp\n      ultimately show \"a \\<in> f ` {p. connecting_path x x' p \\<and> walk_length p = 2}\" using f_def by force\n    qed\n  qed\n  then show \"card {xa \\<in> V. vert_adj x xa \\<and> vert_adj x' xa} =\n    card {p. connecting_path x x' p \\<and> walk_length p = 2}\" \n    using f_inj card_image by fastforce\nqed\n\nlemma codegree_bipartite_eq: \n  \"\\<forall> x \\<in> X. \\<forall> x' \\<in> X. codegree x x' = card {y \\<in> Y. vert_adj x y \\<and> vert_adj x' y}\"\n  unfolding codegree_def using vert_adj_imp_inV X_vert_adj_Y\n  by (metis (no_types, lifting) Collect_cong)\n\nlemma (in fin_bipartite_graph) bipartite_deg_square_eq:\n  \"\\<forall> y \\<in> Y. (\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. indicator {z. vert_adj x z \\<and> vert_adj x' z} y) = (degree y)^2\"\nproof\n  have hX: \"finite X\" by (simp add: partitions_finite(1))\n  fix y assume hy: \"y \\<in> Y\"\n  have 1: \"\\<forall> x' \\<in> X. \\<forall> x \\<in> X. indicator {z. vert_adj x z \\<and> vert_adj x' z} y = \n    indicator ({z. vert_adj x' z} \\<inter> {z. vert_adj x z}) y\"\n    by (metis (mono_tags, lifting) Int_Collect indicator_simps(1) indicator_simps(2) mem_Collect_eq)\n  have 2: \"\\<forall> x' \\<in> X. \\<forall> x \\<in> X. (indicator ({z. vert_adj x' z} \\<inter> {z. vert_adj x z}) y:: nat) =\n    indicator {z. vert_adj x' z} y * indicator {z. vert_adj x z} y\" using indicator_inter_arith \n    by auto\n  have \"(\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. (indicator {z. vert_adj x z \\<and> vert_adj x' z} y:: nat)) = \n    (\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. indicator ({z. vert_adj x' z} \\<inter> {z. vert_adj x z}) y)\" \n    using 1 sum.cong by (metis (no_types, lifting))\n  also have \"... = (\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. indicator {z. vert_adj x' z} y *\n    indicator {z. vert_adj x z} y)\" using 2 sum.cong by auto\n  also have \"... = sum (\\<lambda> x. indicator {z. vert_adj x z} y) X * sum (\\<lambda> x. indicator {z. vert_adj x z} y) X\" \n    using sum_product[of \"(\\<lambda> x. (indicator {z. vert_adj x z} y:: nat))\" \"X\" \n      \"(\\<lambda> x. indicator {z. vert_adj x z} y)\" \"X\"] by auto\n  finally have 3: \"(\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. (indicator {z. vert_adj x z \\<and> vert_adj x' z} y:: nat)) = \n    (sum (\\<lambda> x. indicator {z. vert_adj x z} y) X) ^ 2\" using power2_eq_square\n    by (metis (no_types, lifting))\n  have \"\\<forall> x \\<in> X. indicator {z. vert_adj x z} y = indicator {x. vert_adj x y} x\"\n    by (simp add: indicator_def)\n  from this have \"(sum (\\<lambda> x. indicator {z. vert_adj x z} y) X) = sum (\\<lambda> x. indicator {x. vert_adj x y} x) X\"\n    using sum.cong by fastforce\n  also have \"... = card ({x \\<in> X. vert_adj x y})\" using sum_indicator_eq_card hX\n    by (metis Collect_conj_eq Collect_mem_eq)\n  finally show \"(\\<Sum>x'\\<in>X. \\<Sum>x\\<in>X. indicator {z. vert_adj x z \\<and> vert_adj x' z} y) = (degree y)^2\" \n    using 3 hy degree_neighbors_ssY neighbors_ss_def vert_adj_sym by presburger \nqed\n\nlemma (in fin_bipartite_graph) codegree_degree:          \n  \"(\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. (codegree x x')) = (\\<Sum> y \\<in> Y. (degree y)^2)\"\n\nproof-\n  have hX: \"finite X\" and hY: \"finite Y\"\n    by (simp_all add: partitions_finite)\n  have \"\\<forall> x' \\<in> X. \\<forall> x \\<in> X. {z \\<in> V. vert_adj x z \\<and> vert_adj x' z} = Y \\<inter> {z. vert_adj x z \\<and> vert_adj x' z}\"\n    using XY_union X_vert_adj_Y by fastforce\n  from this have \"(\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. (codegree x x')) = (\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. card (Y \\<inter> {z. vert_adj x z \\<and> vert_adj x' z}))\"\n    using codegree_def sum.cong by auto \n  also have \"... = (\\<Sum> x' \\<in> X. \\<Sum> x \\<in> X. \\<Sum> y \\<in> Y. indicator {z. vert_adj x z \\<and> vert_adj x' z} y)\" \n    using sum_indicator_eq_card hY by fastforce\n  also have \"... =  (\\<Sum> x' \\<in> X. \\<Sum> y \\<in> Y. (\\<Sum> x \\<in> X. indicator {z. vert_adj x z \\<and> vert_adj x' z} y))\"\n    using sum.swap by (metis (no_types))\n  also have \"... = (\\<Sum> y \\<in> Y. \\<Sum> x' \\<in> X. (\\<Sum> x \\<in> X. indicator {z. vert_adj x z \\<and> vert_adj x' z} y))\" \n    using sum.swap by fastforce\n  also have \"... = (\\<Sum> y \\<in> Y. (degree y)^2)\" using bipartite_deg_square_eq sum.cong by force\n  finally show ?thesis by simp\nqed\n\nlemma (in fin_bipartite_graph) sum_degree_normalized_X_density:\n  \"(\\<Sum> x \\<in> X. degree_normalized x Y) / card X = edge_density X Y\"\n  by (smt (z3) card_all_edges_betw_neighbor card_edges_between_set degree_normalized_def\n    divide_divide_eq_left' density_simp of_nat_mult of_nat_sum partitions_finite(1) \n    partitions_finite(2) sum.cong sum_left_div_distrib)\n\nlemma (in fin_bipartite_graph) sum_degree_normalized_Y_density:\n  \"(\\<Sum> y \\<in> Y. degree_normalized y X) / card Y = edge_density X Y\"\n  using bipartite_sym fin_bipartite_graph.sum_degree_normalized_X_density fin_bipartite_graph_def \n    fin_graph_system_axioms edge_density_commute by fastforce\n\nend\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Balog_Szemeredi_Gowers/Graph_Theory_Preliminaries.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9161096158798115, "lm_q2_score": 0.8198933359135361, "lm_q1q2_score": 0.7511121690261668}}
{"text": "(*  Title:      HOL/UNITY/Comp/PriorityAux.thy\n    Author:     Sidi O Ehmety, Cambridge University Computer Laboratory\n    Copyright   2001  University of Cambridge\n\nAuxiliary definitions needed in Priority.thy\n*)\n\ntheory PriorityAux \nimports \"../UNITY_Main\"\nbegin\n\ntypedecl vertex\n  \ndefinition symcl :: \"(vertex*vertex)set=>(vertex*vertex)set\" where\n  \"symcl r == r \\<union> (r^-1)\"\n    --{* symmetric closure: removes the orientation of a relation*}\n\ndefinition neighbors :: \"[vertex, (vertex*vertex)set]=>vertex set\" where\n  \"neighbors i r == ((r \\<union> r^-1)``{i}) - {i}\"\n    --{* Neighbors of a vertex i *}\n\ndefinition R :: \"[vertex, (vertex*vertex)set]=>vertex set\" where\n  \"R i r == r``{i}\"\n\ndefinition A :: \"[vertex, (vertex*vertex)set]=>vertex set\" where\n  \"A i r == (r^-1)``{i}\"\n\ndefinition reach :: \"[vertex, (vertex*vertex)set]=> vertex set\" where\n  \"reach i r == (r^+)``{i}\"\n    --{* reachable and above vertices: the original notation was R* and A* *}\n\ndefinition above :: \"[vertex, (vertex*vertex)set]=> vertex set\" where\n  \"above i r == ((r^-1)^+)``{i}\"  \n\ndefinition reverse :: \"[vertex, (vertex*vertex) set]=>(vertex*vertex)set\" where\n  \"reverse i r == (r - {(x,y). x=i | y=i} \\<inter> r) \\<union> ({(x,y). x=i|y=i} \\<inter> r)^-1\"\n\ndefinition derive1 :: \"[vertex, (vertex*vertex)set, (vertex*vertex)set]=>bool\" where\n    --{* The original definition *}\n  \"derive1 i r q == symcl r = symcl q &\n                    (\\<forall>k k'. k\\<noteq>i & k'\\<noteq>i -->((k,k'):r) = ((k,k'):q)) &\n                    A i r = {} & R i q = {}\"\n\ndefinition derive :: \"[vertex, (vertex*vertex)set, (vertex*vertex)set]=>bool\" where\n    --{* Our alternative definition *}\n  \"derive i r q == A i r = {} & (q = reverse i r)\"\n\naxiomatization where\n  finite_vertex_univ:  \"finite (UNIV :: vertex set)\"\n    --{* we assume that the universe of vertices is finite  *}\n\ndeclare derive_def [simp] derive1_def [simp] symcl_def [simp] \n        A_def [simp] R_def [simp] \n        above_def [simp] reach_def [simp] \n        reverse_def [simp] neighbors_def [simp]\n\ntext{*All vertex sets are finite*}\ndeclare finite_subset [OF subset_UNIV finite_vertex_univ, iff]\n\ntext{* and relatons over vertex are finite too *}\n\nlemmas finite_UNIV_Prod =\n       finite_Prod_UNIV [OF finite_vertex_univ finite_vertex_univ] \n\ndeclare finite_subset [OF subset_UNIV finite_UNIV_Prod, iff]\n\n\n(* The equalities (above i r = {}) = (A i r = {}) \n   and (reach i r = {}) = (R i r) rely on the following theorem  *)\n\nlemma image0_trancl_iff_image0_r: \"((r^+)``{i} = {}) = (r``{i} = {})\"\napply auto\napply (erule trancl_induct, auto)\ndone\n\n(* Another form usefull in some situation *)\nlemma image0_r_iff_image0_trancl: \"(r``{i}={}) = (ALL x. ((i,x):r^+) = False)\"\napply auto\napply (drule image0_trancl_iff_image0_r [THEN ssubst], auto)\ndone\n\n\n(* In finite universe acyclic coincides with wf *)\nlemma acyclic_eq_wf: \"!!r::(vertex*vertex)set. acyclic r = wf r\"\nby (auto simp add: wf_iff_acyclic_if_finite)\n\n(* derive and derive1 are equivalent *)\nlemma derive_derive1_eq: \"derive i r q = derive1 i r q\"\nby auto\n\n(* Lemma 1 *)\nlemma lemma1_a: \n     \"[| x \\<in> reach i q; derive1 k r q |] ==> x\\<noteq>k --> x \\<in> reach i r\"\napply (unfold reach_def)\napply (erule ImageE)\napply (erule trancl_induct) \n apply (cases \"i=k\", simp_all) \n apply (blast, blast, clarify) \napply (drule_tac x = y in spec)\napply (drule_tac x = z in spec)\napply (blast dest: r_into_trancl intro: trancl_trans)\ndone\n\nlemma reach_lemma: \"derive k r q ==> reach i q \\<subseteq> (reach i r \\<union> {k})\"\napply clarify \napply (drule lemma1_a)\napply (auto simp add: derive_derive1_eq \n            simp del: reach_def derive_def derive1_def)\ndone\n\n(* An other possible formulation of the above theorem based on\n   the equivalence x \\<in> reach y r = y \\<in> above x r                  *)\nlemma reach_above_lemma:\n      \"(\\<forall>i. reach i q \\<subseteq> (reach i r \\<union> {k})) = \n       (\\<forall>x. x\\<noteq>k --> (\\<forall>i. i \\<notin> above x r --> i \\<notin> above x q))\"\nby (auto simp add: trancl_converse)\n\n(* Lemma 2 *)\nlemma maximal_converse_image0: \n     \"(z, i):r^+ ==> (\\<forall>y. (y, z):r --> (y,i) \\<notin> r^+) = ((r^-1)``{z}={})\"\napply auto\napply (frule_tac r = r in trancl_into_trancl2, auto)\ndone\n\nlemma above_lemma_a: \n     \"acyclic r ==> A i r\\<noteq>{}-->(\\<exists>j \\<in> above i r. A j r = {})\"\napply (simp add: acyclic_eq_wf wf_eq_minimal) \napply (drule_tac x = \" ((r^-1) ^+) ``{i}\" in spec)\napply auto\napply (simp add: maximal_converse_image0 trancl_converse)\ndone\n\nlemma above_lemma_b: \n     \"acyclic r ==> above i r\\<noteq>{}-->(\\<exists>j \\<in> above i r. above j r = {})\"\napply (drule above_lemma_a)\napply (auto simp add: image0_trancl_iff_image0_r)\ndone\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/UNITY/Comp/PriorityAux.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.8289388146603365, "lm_q1q2_score": 0.7510101278029697}}
{"text": "theory Exercise10\n  imports Main\nbegin\n\ndatatype tree0 = Tip | Node \"tree0\" \"tree0\"\n\nfun nodes :: \"tree0 => nat\" where\n  \"nodes Tip = 1\"\n  | \"nodes (Node l r) = 1 + (nodes l) + (nodes r)\"\n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n  \"explode 0 t = t\"\n  | \"explode (Suc n) t = explode n (Node t t)\"\n\nfun nodes_explode_calc :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> nat\" where\n  \"nodes_explode_calc n t = ((nodes t) * (2 ^ n)) + (2^n - 1)\"\n\n(*\nlemma nodes_suc_explode [simp]: \"nodes (explode (Suc n) t) = 1 + (2 * (nodes (explode n t)))\"\n  apply (induction n arbitrary: t)\n  apply (simp add: algebra_simps)\n  apply (simp add: algebra_simps)\ndone\n\nlemma nodes_explode_algebra_manip_lhs [simp]: \"1 + (2 * (n + ((Suc n) * ((2^m) - 1)))) = (n * (2 ^ (Suc m))) + (2 ^ (Suc m)) - 1\"\n  apply (induction m)\n  apply (auto simp add: algebra_simps)\ndone\n\nlemma nodes_explode_algebra_manip_rhs [simp]: \"(n * (2 ^ (Suc m))) + (2 ^ (Suc m)) - 1 = n + ((Suc n) * (2 ^ (Suc m) - 1))\"\n  apply (induction m)\n  apply (auto simp add: algebra_simps)\ndone\n\nlemma nodes_explode_algebra_manip [simp]: \"1 + (2 * (n + ((Suc n) * ((2^m) -1)))) = n + ((Suc n) * (2^(Suc m) - 1))\"\n  apply (induction m arbitrary: n)\n  apply (simp add: algebra_simps)\n  unfolding nodes_explode_algebra_manip_lhs\n  unfolding nodes_explode_algebra_manip_rhs\nby (rule HOL.refl)\n\ntheorem explosion_size: \"nodes (explode n t) = (nodes t) + (((nodes t) + 1) * ((2 ^ n) - 1))\"\n  apply (induction n arbitrary: t)\n  apply (simp add: algebra_simps)\ndone\n*)\n\ntheorem explosion_size: \"nodes (explode n t) = nodes_explode_calc n t\"\n  apply (induction n arbitrary: t)\n  apply (auto simp add: algebra_simps)\ndone\n\nend", "meta": {"author": "proidiot", "repo": "concrete-semantics-book", "sha": "dd1b736dec8b78b75b45b2d0c8da22d7a35f3745", "save_path": "github-repos/isabelle/proidiot-concrete-semantics-book", "path": "github-repos/isabelle/proidiot-concrete-semantics-book/concrete-semantics-book-dd1b736dec8b78b75b45b2d0c8da22d7a35f3745/ch2/Exercise10.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554445, "lm_q2_score": 0.8479677622198947, "lm_q1q2_score": 0.750986944124515}}
{"text": "theory Exercise3p11\nimports AExp\nbegin\n\n(*\nThis exercise is about a register machine and compiler for aexp. The machine instructions are\n\ndatatype instr = LDI int reg | LD vname reg | ADD reg reg\n\nwhere type reg is a synonym for nat. Instruction LDI i r loads i into register r, \nLD x r loads the value of x into register r, and ADD r1 r2 adds register r2 to register r1.\n\nDefine the execution of an instruction given a state and a register state (= function from registers to integers); the result is the new register state:\n\nfun exec1 :: instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\n\nDefine the execution exec of a list of instructions as for the stack machine. The compiler\ntakes an arithmetic expression a and a register r and produces a list of instructions whose \nexecution places the value of a into r. The registers > r should be used in a stack-like \nfashion for intermediate results, the ones < r should be left alone. Define the compiler \nand prove it correct:\n\nexec (comp a r) s rs r = aval a s.\n\n*)\n\ntype_synonym reg = nat  \n\ndatatype instr = LDI int reg | LD vname reg | ADD reg reg\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n  \"exec1 (LDI i r) s rs = rs (r := i)\"  |\n  \"exec1 (LD x r) s  rs = rs (r := s x)\" |\n  \"exec1 (ADD r1 r2) s rs = rs (r1 := rs r1 + rs r2)\"\n  \nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> (reg \\<Rightarrow> int) \\<Rightarrow> reg \\<Rightarrow> int\" where\n  \"exec [] s rs = rs\" |\n  \"exec (i#is) s rs = exec is s (exec1 i s rs)\"\n  \nlemma exec_append[simp]: \"exec (is1 @ is2) s rs = exec is2 s (exec is1 s rs)\"\n  apply (induction is1 arbitrary: rs)\n   apply auto\n  done\n\nvalue \"exec1 (ADD 0 1) <> <0 := 1, 1 := 3> 0\"\n    \nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n  \"comp (N n) r = [LDI n r]\" |\n  \"comp (V x) r = [LD  x r]\" |\n  \"comp (Plus a1 a2) r = comp a1 r @ comp a2 (r+1) @ [ ADD r (r+1) ]\" \n\nvalue \"comp (Plus (N 1) (V ''x'')) 0\"\nvalue \"exec (comp (Plus (N 1) (V ''x'')) 0) <''x'' := 10> <> 0\"\n\n\n\nlemma \"exec (comp a r) s rs r = aval a s\"\n  apply (induction a arbitrary: r rs)\n    apply (auto)\n    done\n  \n  \n      \nend", "meta": {"author": "sseefried", "repo": "concrete-semantics-solutions", "sha": "ca562994bc36b2d9c9e6047bf481056e0be7bbcd", "save_path": "github-repos/isabelle/sseefried-concrete-semantics-solutions", "path": "github-repos/isabelle/sseefried-concrete-semantics-solutions/concrete-semantics-solutions-ca562994bc36b2d9c9e6047bf481056e0be7bbcd/Exercise3p11.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294209307224, "lm_q2_score": 0.8311430562234877, "lm_q1q2_score": 0.750766709792585}}
{"text": "(* Author: Tobias Nipkow, Daniel Stüwe *)\n\nsection \\<open>Three-Way Comparison\\<close>\n\ntheory Cmp\nimports Main\nbegin\n\ndatatype cmp_val = LT | EQ | GT\n\ndefinition cmp :: \"'a:: linorder \\<Rightarrow> 'a \\<Rightarrow> cmp_val\" where\n\"cmp x y = (if x < y then LT else if x=y then EQ else GT)\"\n\nlemma \n    LT[simp]: \"cmp x y = LT \\<longleftrightarrow> x < y\"\nand EQ[simp]: \"cmp x y = EQ \\<longleftrightarrow> x = y\"\nand GT[simp]: \"cmp x y = GT \\<longleftrightarrow> x > y\"\nby (auto simp: cmp_def)\n\nlemma case_cmp_if[simp]: \"(case c of EQ \\<Rightarrow> e | LT \\<Rightarrow> l | GT \\<Rightarrow> g) =\n  (if c = LT then l else if c = GT then g else e)\"\nby(simp split: cmp_val.split)\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/HOL/Data_Structures/Cmp.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8918110569397306, "lm_q2_score": 0.8418256412990657, "lm_q1q2_score": 0.7507494149258863}}
{"text": "section \\<open> Space.thy \\<close>\n\ntheory Space\nimports Main\nbegin\n\n(* Space type *)\n\ntype_synonym 'A Open = \"'A set\"\n\nrecord 'A Space =\n  opens :: \"'A Open set\"\n  universe :: \"'A set\"\n\ndefinition valid :: \"'A Space \\<Rightarrow> bool\" where\n  \"valid T \\<equiv>\n    (\\<forall>A. A \\<in> opens T \\<longrightarrow> A \\<subseteq> universe T) \\<and>\n    ({} \\<in> opens T \\<and> universe T \\<in> opens T \\<and>\n    (\\<forall>A B. A \\<in> opens T \\<longrightarrow> B \\<in> opens T \\<longrightarrow> A \\<inter> B \\<in> opens T) \\<and>\n    (\\<forall>U. U \\<subseteq> opens T  \\<longrightarrow> \\<Union>U \\<in> opens T))\"\n\n(* Inclusion type *)\n\nrecord 'A Inclusion =\n  dom :: \"'A Open\"\n  cod :: \"'A Open\"\n\nabbreviation (input) valid_inc :: \"'A Inclusion \\<Rightarrow> bool\" where\n  \"valid_inc i \\<equiv> dom i \\<subseteq> cod i\"\n\nabbreviation inclusions :: \"'A Space \\<Rightarrow> 'A Inclusion set\" where\n  \"inclusions T \\<equiv> {i. valid_inc i \\<and> dom i \\<in> opens T \\<and> cod i \\<in> opens T}\"\n\n(* There are built-in constructors (Inclusion.make), but the simplifier/SH doesn't seem to like them? *)\nabbreviation (input) make_inc :: \"'A Open \\<Rightarrow> 'A Open \\<Rightarrow> 'A Inclusion\" where\n\"make_inc B A \\<equiv> \\<lparr> dom = B, cod = A \\<rparr>\"\n\n(* Validity *)\n\nlemma valid_welldefined : \"valid T \\<Longrightarrow> (A \\<in> opens T \\<Longrightarrow> A \\<subseteq> universe T)\"\n  using valid_def by blast\n\nlemma valid_empty : \"valid T \\<Longrightarrow> {} \\<in> opens T\"\n  using valid_def by blast\n\nlemma valid_universe : \"valid T \\<Longrightarrow> universe T \\<in> opens T\"\n  using valid_def by blast\n\nlemma valid_union : \"valid T \\<Longrightarrow> U \\<subseteq> opens T \\<Longrightarrow> \\<Union>U \\<in> opens T\"\n  using valid_def by blast\n\nlemma valid_union2 : \"valid T \\<Longrightarrow> A \\<in> opens T \\<Longrightarrow> B \\<in> opens T \\<Longrightarrow> A \\<union> B \\<in> opens T\"\n  using valid_union [where ?T=T and ?U=\"{A,B}\"]\n  by force\n\nlemma valid_inter : \"valid T \\<Longrightarrow> A \\<in> opens T \\<Longrightarrow> B \\<in> opens T \\<Longrightarrow> A \\<inter> B \\<in> opens T\"\n  using valid_def by blast\n\nlemma valid_inc_dom : \"i \\<in> inclusions T \\<Longrightarrow> dom i \\<in> opens T\"\n  by simp\n\nlemma valid_inc_cod: \"i \\<in> inclusions T \\<Longrightarrow> cod i \\<in> opens T\"\n  by simp\n\nlemma validI [intro]: \"(\\<And>A. A \\<in> opens T \\<Longrightarrow> A \\<subseteq> universe T) \\<Longrightarrow> {} \\<in> opens T \\<Longrightarrow> universe T \\<in> opens T \n\\<Longrightarrow> (\\<And>U. U \\<subseteq> opens T \\<Longrightarrow> \\<Union>U \\<in> opens T) \\<Longrightarrow> (\\<And>A B. A \\<in> opens T \\<Longrightarrow> B \\<in> opens T \\<Longrightarrow> A \\<inter> B \\<in> opens T) \\<Longrightarrow> valid T\"\n  by (simp add: valid_def)\n\n(* Inclusion composition *)\n\ndefinition \"Space_compose_inclusion_endpoint_mistmatch _ _ \\<equiv> undefined\"\n\ndefinition compose_inc :: \"'A Inclusion \\<Rightarrow> 'A Inclusion \\<Rightarrow> 'A Inclusion\" (infixl \"\\<propto>\" 55) where\n  \"compose_inc j i \\<equiv>\n    if dom j = cod i\n    then \\<lparr> dom = dom i, cod = cod j \\<rparr>\n    else Space_compose_inclusion_endpoint_mistmatch j i\"\n\nlemma compose_inc_valid : \"valid_inc j \\<Longrightarrow> valid_inc i \\<Longrightarrow> dom j = cod i \\<Longrightarrow> valid_inc (j \\<propto> i)\"\n  by (metis Inclusion.select_convs(1) Inclusion.select_convs(2) compose_inc_def dual_order.trans)\n\nlemma dom_compose_inc [simp] : \"dom j = cod i \\<Longrightarrow> dom (j \\<propto> i) = dom i\"\n  by (simp add: compose_inc_def)\n\nlemma cod_compose_inc [simp] : \"dom j = cod i \\<Longrightarrow> cod (j \\<propto> i) = cod j\"\n  by (simp add: compose_inc_def)\n\n(* Identity inclusion *)\n\ndefinition ident :: \"'A Open \\<Rightarrow> 'A Inclusion\" where\n  \"ident A \\<equiv> make_inc A A\"\n\nlemma ident_valid : \"A \\<in> opens T \\<Longrightarrow> valid_inc (ident A)\"\n  by (simp add: ident_def)\n\nlemma valid_ident_inc : \"A \\<in> opens T \\<Longrightarrow> ident A \\<in> inclusions T\" \n  by (simp add: ident_def)\n\nlemma compose_inc_ident_left [simp] : \"ident (cod i) \\<propto> i = i\"\n  by (simp add: compose_inc_def ident_def)\n\nlemma compose_inc_ident_right [simp] : \"i \\<propto> ident (dom i) = i\"\n  by (simp add: compose_inc_def ident_def)\n\n(* Properties *)\n\nlemma inc_cod_sup [simp] : \"i \\<in> inclusions T \\<Longrightarrow> dom i \\<union> cod i = cod i\"\n  by blast\n\nlemma inc_dom_inf [simp] : \"i \\<in> inclusions T \\<Longrightarrow> dom i \\<inter> cod i = dom i\"\n  by blast\n\n(* Examples *)\n\ndefinition discrete :: \"'a Space\" where\n  \"discrete = \\<lparr> opens = Pow UNIV, universe = UNIV \\<rparr>\"\n\nlemma valid_discrete : \"valid discrete\"\n  by (simp add: discrete_def valid_def) \n\ndefinition codiscrete :: \"'a Space\" where\n  \"codiscrete = \\<lparr> opens = {{}, UNIV}, universe = UNIV \\<rparr>\"\n\nlemma valid_codiscrete : \"valid codiscrete\" \n  unfolding codiscrete_def valid_def \n  apply clarsimp\n  by blast\n\ndefinition sierpinski :: \"bool Space\" where\n  \"sierpinski = \n    \\<lparr> opens = {{}, {False}, UNIV }, \n      universe = UNIV \\<rparr>\"\n\nlemma valid_sierpinski : \"valid sierpinski\"  \n  unfolding sierpinski_def valid_def \n  apply clarsimp\n  by blast\n\nend\n", "meta": {"author": "nasosev", "repo": "cva", "sha": "master", "save_path": "github-repos/isabelle/nasosev-cva", "path": "github-repos/isabelle/nasosev-cva/cva-main/Space.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.8376199552262967, "lm_q1q2_score": 0.7507180350356899}}
{"text": "section \\<open>Standard gates\\<close>\n\ntheory Gates\n  imports Complex_Matrix\nbegin\n\ntext \\<open>Pauli matrices\\<close>\ndefinition sigma_x :: \"complex mat\" where\n  \"sigma_x = mat_of_rows_list 2 [[0, 1], [1, 0]]\"\n\ndefinition sigma_y :: \"complex mat\" where\n  \"sigma_y = mat_of_rows_list 2 [[0, -\\<i>], [\\<i>, 0]]\"\n\ndefinition sigma_z :: \"complex mat\" where\n  \"sigma_z = mat_of_rows_list 2 [[1, 0], [0, -1]]\"\n\ntext \\<open>Hadamard matrices\\<close>\ndefinition hadamard :: \"complex mat\" where\n  \"hadamard = mat 2 2 (\\<lambda>(i, j). if (i = 0 \\<or> j = 0) then 1 / csqrt 2 else - 1 / sqrt 2)\"\n\nlemma hadamard_dim:\n  \"hadamard \\<in> carrier_mat 2 2\" \n  unfolding hadamard_def mat_of_rows_list_def by auto\n\nlemma hermitian_hadamard:\n  \"hermitian hadamard\"\n  unfolding hermitian_def hadamard_def\n  apply (rule eq_matI) by (auto simp add: adjoint_eval adjoint_dim)\n\nlemma csqrt_2_sq:\n  \"complex_of_real (sqrt 2) * complex_of_real (sqrt 2) = 2\"\n  by (smt of_real_add of_real_hom.hom_one of_real_power one_add_one power2_eq_square real_sqrt_pow2)\n\nlemma sum_le_2:\n  \"\\<And>(f::nat\\<Rightarrow>complex). sum f {0..<2} = f 0 + f 1\"\n  by (simp add: numeral_2_eq_2)\n\nlemma unitary_hadamard:\n  \"unitary hadamard\"\n  unfolding unitary_def apply (rule)\n  subgoal using carrier_matD[OF hadamard_dim] hadamard_def by auto\n  apply (subst hermitian_hadamard[unfolded hermitian_def])\n  unfolding inverts_mat_def\n  apply (rule eq_matI) unfolding hadamard_def\n    apply (auto simp add: carrier_matD[OF hadamard_dim] scalar_prod_def)\n  by (auto simp add: sum_le_2 csqrt_2_sq)\n\ntext \\<open>The matrix\n  [0 0 .. 0 1\n   1 0 .. 0 0\n   0 1 .. 0 0\n   . . .. . .\n   0 0 .. 1 0]\n  implements i := i + 1 in the last variable.\n\\<close>\ndefinition mat_incr :: \"nat \\<Rightarrow> complex mat\" where\n  \"mat_incr n = mat n n (\\<lambda>(i,j). if i = 0 then (if j = n - 1 then 1 else 0) else (if i = j + 1 then 1 else 0))\"\n\n\n\nlemma adjoint_mat_incr:\n  \"adjoint (mat_incr n) = mat n n (\\<lambda>(i,j). if j = 0 then (if i = n - 1 then 1 else 0) else (if j = i + 1 then 1 else 0))\"\n  apply (rule eq_matI) unfolding mat_incr_def\n  by (auto simp add: adjoint_eval)\n\n\n\nlemma unitary_mat_incr:\n  \"unitary (mat_incr n)\"\n  unfolding unitary_def inverts_mat_def\n  using carrier_matD[OF mat_incr_dim] mat_incr_mult_adjoint_mat_incr by auto\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/QHLProver/Gates.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896671963206, "lm_q2_score": 0.8152324960856177, "lm_q1q2_score": 0.7506576587583016}}
{"text": "(* Author: Peter Gammie\n   Author: Andreas Lochbihler, ETH Zurich *)\n\nsection \\<open>The Stern-Brocot Tree\\<close>\n\ntheory Stern_Brocot_Tree\nimports\n  HOL.Rat\n  \"HOL-Library.Sublist\"\n  Cotree_Algebra\n  Applicative_Lifting.Stream_Algebra\nbegin\n\ntext\\<open>\n  The Stern-Brocot tree is discussed at length by \\<^citet>\\<open>\\<open>\\S4.5\\<close> in \"GrahamKnuthPatashnik1994CM\"\\<close>.\n  In essence the tree enumerates the rational numbers in their lowest terms by constructing the\n  \\<open>mediant\\<close> of two bounding fractions.\n\\<close>\n\ntype_synonym fraction = \"nat \\<times> nat\"\n\ndefinition mediant :: \"fraction \\<times> fraction \\<Rightarrow> fraction\"\nwhere \"mediant \\<equiv> \\<lambda>((a, c), (b, d)). (a + b, c + d)\"\n\ndefinition stern_brocot :: \"fraction tree\"\nwhere \n  \"stern_brocot = unfold_tree\n    (\\<lambda>(lb, ub). mediant (lb, ub))\n    (\\<lambda>(lb, ub). (lb, mediant (lb, ub)))\n    (\\<lambda>(lb, ub). (mediant (lb, ub), ub))\n    ((0, 1), (1, 0))\"\n\ntext\\<open>\n  This process is visualised in Figure~\\ref{fig:stern-brocot-iterate}.\n  Intuitively each node is labelled with the mediant of it's rightmost and leftmost ancestors.\n\n  \\begin{figure}\n    \\centering\n    \\begin{tikzpicture}[auto,thick,node distance=3cm,main node/.style={circle,draw,font=\\sffamily\\Large\\bfseries}]\n      \\node[main node] (0) at (0, 0) {$\\frac{1}{1}$};\n      \\node[main node] (1) at (-4, 1) {$\\frac{0}{1}$};\n      \\node[main node] (2) at (4, 1) {$\\frac{1}{0}$};\n      \\node[main node] (3) at (-2, -1) {$\\frac{1}{2}$};\n      \\node[main node] (4) at (2, -1) {$\\frac{2}{1}$};\n      \\node[main node] (5) at (-3, -2) {$\\frac{1}{3}$};\n      \\node[main node] (6) at (3, -2) {$\\frac{3}{1}$};\n      \\node[main node] (7) at (-1, -2) {$\\frac{2}{3}$};\n      \\node[main node] (8) at (1, -2) {$\\frac{3}{2}$};\n      \\node (9) at (-3.5, -3) {};\n      \\node (10) at (-2.5, -3) {};\n      \\node (11) at (-1.5, -3) {};\n      \\node (12) at (-0.5, -3) {};\n      \\node (13) at (0.5, -3) {};\n      \\node (14) at (1.5, -3) {};\n      \\node (15) at (2.5, -3) {};\n      \\node (16) at (3.5, -3) {};\n      \\path\n        (1) edge[dashed] (0)\n        (2) edge[dashed] (0)\n        (0) edge (3)\n        (0) edge (4)\n        (3) edge (5)\n        (3) edge (7)\n        (4) edge (6)\n        (4) edge (8)\n        (5) edge[dotted] (9)\n        (5) edge[dotted] (10)\n        (6) edge[dotted] (15)\n        (6) edge[dotted] (16)\n        (7) edge[dotted] (11)\n        (7) edge[dotted] (12)\n        (8) edge[dotted] (13)\n        (8) edge[dotted] (14);\n    \\end{tikzpicture}\n    \\label{fig:stern-brocot-iterate}\n    \\caption{Constructing the Stern-Brocot tree iteratively.}\n  \\end{figure}\n  \n  Our ultimate goal is to show that the Stern-Brocot tree contains all rationals (in lowest terms),\n  and that each occurs exactly once in the tree. A proof is sketched in \\<^citet>\\<open>\\<open>\\S4.5\\<close> in \"GrahamKnuthPatashnik1994CM\"\\<close>.\n\\<close>\n\nsubsection \\<open>Specification via a recursion equation\\<close>\n\ntext \\<open>\n  \\<^cite>\\<open>\"Hinze2009JFP\"\\<close> derives the following recurrence relation for the Stern-Brocot tree. \n  We will show in \\S\\ref{section:eq:rec:iterative} that his derivation is sound with respect to the\n  standard iterative definition of the tree shown above.\n\\<close>\n\nabbreviation succ :: \"fraction \\<Rightarrow> fraction\"\nwhere \"succ \\<equiv> \\<lambda>(m, n). (m + n, n)\"\n\nabbreviation recip :: \"fraction \\<Rightarrow> fraction\"\nwhere \"recip \\<equiv> \\<lambda>(m, n). (n, m)\"\n\ncorec stern_brocot_recurse :: \"fraction tree\"\nwhere\n  \"stern_brocot_recurse =\n   Node (1, 1)\n     (map_tree recip (map_tree succ (map_tree recip stern_brocot_recurse)))\n     (map_tree succ stern_brocot_recurse)\"\n\ntext \\<open>Actually, we would like to write the specification below, but \\<open>(\\<diamondop>)\\<close> cannot be registered as friendly due to varying type parameters\\<close>\nlemma stern_brocot_unfold:\n  \"stern_brocot_recurse =\n   Node (1, 1)\n        (pure recip \\<diamondop> (pure succ \\<diamondop> (pure recip \\<diamondop> stern_brocot_recurse)))\n        (pure succ \\<diamondop> stern_brocot_recurse)\"\nby(fact stern_brocot_recurse.code[unfolded map_tree_ap_tree_pure_tree[symmetric]])\n\nlemma stern_brocot_simps [simp]:\n  \"root stern_brocot_recurse = (1, 1)\"\n  \"left stern_brocot_recurse = pure recip \\<diamondop> (pure succ \\<diamondop> (pure recip \\<diamondop> stern_brocot_recurse))\"\n  \"right stern_brocot_recurse = pure succ \\<diamondop> stern_brocot_recurse\"\nby (subst stern_brocot_unfold, simp)+\n\nlemma stern_brocot_conv:\n  \"stern_brocot_recurse = tree_recurse (recip \\<circ> succ \\<circ> recip) succ (1, 1)\"\napply(rule tree_recurse.unique)\napply(subst stern_brocot_unfold)\napply(simp add: o_assoc)\napply(rule conjI; applicative_nf; simp)\ndone\n\nsubsection \\<open>Basic properties\\<close>\n\ntext \\<open>\n  The recursive definition is useful for showing some basic properties of the tree, \n  such as that the pairs of numbers at each node are coprime, and have non-zero denominators.\n  Both are simple inductions on the path.\n\\<close>\n\nlemma stern_brocot_denominator_non_zero:\n  \"case root (traverse_tree path stern_brocot_recurse) of (m, n) \\<Rightarrow> m > 0 \\<and> n > 0\"\nby(induct path)(auto split: dir.splits)\n\nlemma stern_brocot_coprime:\n  \"case root (traverse_tree path stern_brocot_recurse) of (m, n) \\<Rightarrow> coprime m n\"\n  by (induct path) (auto split: dir.splits simp add: coprime_iff_gcd_eq_1, metis gcd.commute gcd_add1)\n\n\nsubsection \\<open>All the rationals\\<close>\n\ntext\\<open>\n  For every pair of positive naturals, we can construct a path into the Stern-Brocot tree such that the naturals at the end of the path define the same rational as the pair we started with.\n  Intuitively, the choices made by Euclid's algorithm define this path.\n\\<close>\n\nfunction mk_path :: \"nat \\<Rightarrow> nat \\<Rightarrow> path\" where\n  \"m = n \\<Longrightarrow> mk_path (Suc m) (Suc n) = []\"\n| \"m < n \\<Longrightarrow> mk_path (Suc m) (Suc n) = L # mk_path (Suc m) (n - m)\"\n| \"m > n \\<Longrightarrow> mk_path (Suc m) (Suc n) = R # mk_path (m - n) (Suc n)\"\n| \"mk_path 0 _ = undefined\"\n| \"mk_path _ 0 = undefined\"\nby atomize_elim(auto, arith)\ntermination mk_path by lexicographic_order\n\nlemmas mk_path_induct[case_names equal less greater] = mk_path.induct\n\nabbreviation rat_of :: \"fraction \\<Rightarrow> rat\"\nwhere \"rat_of \\<equiv> \\<lambda>(x, y). Fract (int x) (int y)\"\n\ntheorem stern_brocot_rationals:\n  \"\\<lbrakk> m > 0; n > 0 \\<rbrakk> \\<Longrightarrow>\n  root (traverse_tree (mk_path m n) (pure rat_of \\<diamondop> stern_brocot_recurse)) = Fract (int m) (int n)\"\nproof(induction m n rule: mk_path_induct)\n  case (less m n)\n  with stern_brocot_denominator_non_zero[where path=\"mk_path (Suc m) (n - m)\"]\n  show ?case\n    by (simp add: eq_rat field_simps of_nat_diff split: prod.split_asm)\nnext\n  case (greater m n)\n  with stern_brocot_denominator_non_zero[where path=\"mk_path (m - n) (Suc n)\"]\n  show ?case\n    by (simp add: eq_rat field_simps of_nat_diff split: prod.split_asm)\nqed (simp_all add: eq_rat)\n\nsubsection \\<open>No repetitions\\<close>\n\ntext \\<open>\n  We establish that the Stern-Brocot tree does not contain repetitions, i.e.,\n  that each rational number appears at most once in it.\n  Note that this property is stronger than merely requiring that pairs of naturals not be repeated,\n  though it is implied by that property and @{thm [source] \"stern_brocot_coprime\"}.\n  \n  Intuitively, the tree enjoys the \\emph{binary search tree} ordering property when we map our\n  pairs of naturals into rationals. This suffices to show that each rational appears at most once\n  in the tree. To establish this seems to require more structure than is present in the recursion\n  equations, and so we follow \\<^citet>\\<open>\"BackhouseFerreira2008MPC\"\\<close> and \\<^citet>\\<open>\"Hinze2009JFP\"\\<close> by\n  introducing another definition of the tree, which summarises the path to each node using a matrix.\n\n  We then derive an iterative version and use invariant reasoning on that.\n  We begin by defining some matrix machinery.\n  This is all elementary and primitive (we do not need much algebra).\n\\<close>\n\ntype_synonym matrix = \"fraction \\<times> fraction\"\ntype_synonym vector = fraction\n\ndefinition times_matrix :: \"matrix \\<Rightarrow> matrix \\<Rightarrow> matrix\" (infixl \"\\<otimes>\" 70)\nwhere \"times_matrix = (\\<lambda>((a, c), (b, d)) ((a', c'), (b', d')).\n       ((a * a' + b * c', c * a' + d * c'),\n        (a * b' + b * d', c * b' + d * d')))\"\n\ndefinition times_vector :: \"matrix \\<Rightarrow> vector \\<Rightarrow> vector\" (infixr \"\\<odot>\" 70)\nwhere \"times_vector = (\\<lambda>((a, c), (b, d)) (a', c'). (a * a' + b * c', c * a' + d * c'))\"\n\ncontext begin\n\nprivate definition F :: matrix where \"F = ((0, 1), (1, 0))\"\nprivate definition I :: matrix where \"I = ((1, 0), (0, 1))\"\nprivate definition LL :: matrix where \"LL = ((1, 1), (0, 1))\"\nprivate definition UR :: matrix where \"UR = ((1, 0), (1, 1))\"\n\ndefinition Det :: \"matrix \\<Rightarrow> nat\" where \"Det \\<equiv> \\<lambda>((a, c), (b, d)). a * d - b * c\"\n\nlemma Dets [iff]:\n  \"Det I = 1\"\n  \"Det LL = 1\"\n  \"Det UR = 1\"\nunfolding Det_def I_def LL_def UR_def by simp_all\n\nlemma LL_UR_Det:\n  \"Det m = 1 \\<Longrightarrow> Det (m \\<otimes> LL) = 1\"\n  \"Det m = 1 \\<Longrightarrow> Det (LL \\<otimes> m) = 1\"\n  \"Det m = 1 \\<Longrightarrow> Det (m \\<otimes> UR) = 1\"\n  \"Det m = 1 \\<Longrightarrow> Det (UR \\<otimes> m) = 1\"\nby (cases m, simp add: Det_def LL_def UR_def times_matrix_def split_def field_simps)+\n\n\n\nlemma times_matrix_I [simp]:\n  \"I \\<otimes> x = x\"\n  \"x \\<otimes> I = x\"\nby (simp_all add: times_matrix_def I_def split_def)\n\nlemma times_matrix_assoc [simp]:\n  \"(x \\<otimes> y) \\<otimes> z = x \\<otimes> (y \\<otimes> z)\"\nby (simp add: times_matrix_def field_simps split_def)\n\nlemma LL_UR_pos:\n  \"0 < snd (mediant m) \\<Longrightarrow> 0 < snd (mediant (m \\<otimes> LL))\"\n  \"0 < snd (mediant m) \\<Longrightarrow> 0 < snd (mediant (m \\<otimes> UR))\"\nby (cases m) (simp_all add: LL_def UR_def times_matrix_def split_def field_simps mediant_def)\n\nlemma recip_succ_recip: \"recip \\<circ> succ \\<circ> recip = (\\<lambda>(x, y). (x, x + y))\"\nby (clarsimp simp: fun_eq_iff)\n\ntext \\<open>\n  \\citeauthor{BackhouseFerreira2008MPC} work with the identity matrix @{const \"I\"} at the root.\n  This has the advantage that all relevant matrices have determinants of @{term \"1 :: nat\"}.\n\\<close>\n\ndefinition stern_brocot_iterate_aux :: \"matrix \\<Rightarrow> matrix tree\"\nwhere \"stern_brocot_iterate_aux \\<equiv> tree_iterate (\\<lambda>s. s \\<otimes> LL) (\\<lambda>s. s \\<otimes> UR)\"\n\ndefinition stern_brocot_iterate :: \"fraction tree\"\nwhere \"stern_brocot_iterate \\<equiv> map_tree mediant (stern_brocot_iterate_aux I)\"\n\nlemma stern_brocot_recurse_iterate: \"stern_brocot_recurse = stern_brocot_iterate\" (is \"?lhs = ?rhs\")\nproof -\n  have \"?rhs = map_tree mediant (tree_recurse ((\\<otimes>) LL) ((\\<otimes>) UR) I)\"\n    using tree_recurse_iterate[where f=\"(\\<otimes>)\" and l=\"LL\" and r=\"UR\" and \\<epsilon>=\"I\"]\n    by (simp add: stern_brocot_iterate_def stern_brocot_iterate_aux_def)\n also have \"\\<dots> = tree_recurse ((\\<odot>) LL) ((\\<odot>) UR) (1, 1)\"\n   unfolding mediant_I_F(2)[symmetric]\n   by (rule tree_recurse_fusion)(simp_all add: fun_eq_iff mediant_def times_matrix_def times_vector_def LL_def UR_def)[2]\n also have \"\\<dots> = ?lhs\"\n   by (simp add: stern_brocot_conv recip_succ_recip times_vector_def LL_def UR_def)\n finally show ?thesis by simp\nqed\n\ntext\\<open>\n  The following are the key ordering properties derived by \\<^citet>\\<open>\"BackhouseFerreira2008MPC\"\\<close>.\n  They hinge on the matrices containing only natural numbers.\n\\<close>\n\nlemma tree_ordering_left:\n  assumes DX: \"Det X = 1\"\n  assumes DY: \"Det Y = 1\"\n  assumes MX: \"0 < snd (mediant X)\"\n  shows \"rat_of (mediant (X \\<otimes> LL \\<otimes> Y)) < rat_of (mediant X)\"\nproof -\n  from DX DY have F: \"0 < snd (mediant (X \\<otimes> LL \\<otimes> Y))\"\n    by (auto simp: Det_def times_matrix_def LL_def split_def mediant_def)\n  obtain x11 x12 x21 x22 where X: \"X = ((x11, x12), (x21, x22))\" by(cases X) auto\n  obtain y11 y12 y21 y22 where Y: \"Y = ((y11, y12), (y21, y22))\" by(cases Y) auto\n  from DX DY have *: \"(x12 * x21) * (y12 + y22) < (x11 * x22) * (y12 + y22)\"\n    by(simp add: X Y Det_def)(cases y12, simp_all add: field_simps)\n  from DX DY MX F show ?thesis\n    apply (simp add: split_def X Y of_nat_mult [symmetric] del: of_nat_mult)\n    apply (clarsimp simp: Det_def times_matrix_def LL_def UR_def mediant_def split_def)\n    using * by (simp add: field_simps)\nqed\n\nlemma tree_ordering_right:\n  assumes DX: \"Det X = 1\"\n  assumes DY: \"Det Y = 1\"\n  assumes MX: \"0 < snd (mediant X)\"\n  shows \"rat_of (mediant X) < rat_of (mediant (X \\<otimes> UR \\<otimes> Y))\"\nproof -\n  from DX DY have F: \"0 < snd (mediant (X \\<otimes> UR \\<otimes> Y))\"\n    by (auto simp: Det_def times_matrix_def UR_def split_def mediant_def)\n  obtain x11 x12 x21 x22 where X: \"X = ((x11, x12), (x21, x22))\" by(cases X) auto\n  obtain y11 y12 y21 y22 where Y: \"Y = ((y11, y12), (y21, y22))\" by(cases Y) auto\n  show ?thesis using DX DY MX F\n    apply (simp add: X Y split_def of_nat_mult [symmetric] del: of_nat_mult)\n    apply (simp add: Det_def times_matrix_def LL_def UR_def mediant_def split_def algebra_simps)\n    apply (simp add: add_mult_distrib2[symmetric] mult.assoc[symmetric])\n    apply (cases y21; simp)\n    done\nqed\n\n\n\nlemma stern_brocot_iterate_aux_decompose:\n  \"\\<exists>m''. m \\<otimes> m'' = root (traverse_tree path (stern_brocot_iterate_aux m)) \\<and> Det m'' = 1\"\nproof(induction path arbitrary: m)\n  case Nil show ?case\n    by (auto simp add: stern_brocot_iterate_aux_def intro: exI[where x=I] simp del: split_paired_Ex)\nnext\n  case (Cons d ds m)\n  from Cons.IH[where m=\"m \\<otimes> UR\"] Cons.IH[where m=\"m \\<otimes> LL\"] show ?case\n    by(simp add: stern_brocot_iterate_aux_def split: dir.splits del: split_paired_Ex)(fastforce simp: LL_UR_Det)\nqed\n\nlemma stern_brocot_fractions_not_repeated_strict_prefix:\n  assumes \"root (traverse_tree path stern_brocot_iterate) = root (traverse_tree path' stern_brocot_iterate)\"\n  assumes pp': \"strict_prefix path path'\"\n  shows False\nproof -\n  from pp' obtain d ds where pp': \"path' = path @ [d] @ ds\" by (auto elim!: strict_prefixE')\n  define m where \"m = root (traverse_tree path (stern_brocot_iterate_aux I))\"\n  then have Dm: \"Det m = 1\" and Pm: \"0 < snd (mediant m)\"\n    using stern_brocot_iterate_aux_Det[where path=\"path\" and m=\"I\"] by simp_all\n  define m' where \"m' = root (traverse_tree path' (stern_brocot_iterate_aux I))\"\n  then have Dm': \"Det m' = 1\"\n    using stern_brocot_iterate_aux_Det[where path=path' and m=\"I\"] by simp\n  let ?M = \"case d of L \\<Rightarrow> m \\<otimes> LL | R \\<Rightarrow> m \\<otimes> UR\"\n  from pp' have \"root (traverse_tree ds (stern_brocot_iterate_aux ?M)) = m'\"\n    by(simp add: m_def m'_def stern_brocot_iterate_aux_def traverse_tree_tree_iterate split: dir.splits)\n  then obtain m'' where mm'm'': \"?M \\<otimes> m''= m'\" and Dm'': \"Det m'' = 1\"\n    using stern_brocot_iterate_aux_decompose[where path=\"ds\" and m=\"?M\"] by clarsimp\n  hence \"case d of L \\<Rightarrow> rat_of (mediant m') < rat_of (mediant m) | R \\<Rightarrow> rat_of (mediant m) < rat_of (mediant m')\"\n    using tree_ordering_left[OF Dm Dm'' Pm] tree_ordering_right[OF Dm Dm'' Pm]\n    by (simp split: dir.splits)\n  with assms show False\n    by (simp add: stern_brocot_iterate_def m_def m'_def split: dir.splits)\nqed\n\nlemma stern_brocot_fractions_not_repeated_parallel:\n  assumes \"root (traverse_tree path stern_brocot_iterate) = root (traverse_tree path' stern_brocot_iterate)\"\n  assumes p: \"path = pref @ d # ds\"\n  assumes p': \"path' = pref @ d' # ds'\"\n  assumes dd': \"d \\<noteq> d'\"\n  shows False\nproof -\n  define m where \"m = root (traverse_tree pref (stern_brocot_iterate_aux I))\"\n  then have Dm: \"Det m = 1\" and Pm: \"0 < snd (mediant m)\"\n    using stern_brocot_iterate_aux_Det[where path=\"pref\" and m=\"I\"] by simp_all\n  define pm where \"pm = root (traverse_tree path (stern_brocot_iterate_aux I))\"\n  then have Dpm: \"Det pm = 1\"\n    using stern_brocot_iterate_aux_Det[where path=path and m=\"I\"] by simp\n  let ?M = \"case d of L \\<Rightarrow> m \\<otimes> LL | R \\<Rightarrow> m \\<otimes> UR\"\n  from p\n  have \"root (traverse_tree ds (stern_brocot_iterate_aux ?M)) = pm\"\n    by(simp add: stern_brocot_iterate_aux_def m_def pm_def traverse_tree_tree_iterate split: dir.splits)\n  then obtain pm'\n    where pm': \"?M \\<otimes> pm'= pm\" and Dpm': \"Det pm' = 1\"\n    using stern_brocot_iterate_aux_decompose[where path=\"ds\" and m=\"?M\"] by clarsimp\n  hence \"case d of L \\<Rightarrow> rat_of (mediant pm) < rat_of (mediant m) | R \\<Rightarrow> rat_of (mediant m) < rat_of (mediant pm)\"\n    using tree_ordering_left[OF Dm Dpm' Pm, unfolded pm']\n          tree_ordering_right[OF Dm Dpm' Pm, unfolded pm']\n    by (simp split: dir.splits)\n  moreover\n  define p'm where \"p'm = root (traverse_tree path' (stern_brocot_iterate_aux I))\"\n  then have Dp'm: \"Det p'm = 1\"\n    using stern_brocot_iterate_aux_Det[where path=path' and m=\"I\"] by simp\n  let ?M' = \"case d' of L \\<Rightarrow> m \\<otimes> LL | R \\<Rightarrow> m \\<otimes> UR\"\n  from p'\n  have \"root (traverse_tree ds' (stern_brocot_iterate_aux ?M')) = p'm\"\n    by(simp add: stern_brocot_iterate_aux_def m_def p'm_def traverse_tree_tree_iterate split: dir.splits)\n  then obtain p'm'\n    where p'm': \"?M' \\<otimes> p'm' = p'm\" and Dp'm': \"Det p'm' = 1\"\n    using stern_brocot_iterate_aux_decompose[where path=\"ds'\" and m=\"?M'\"] by clarsimp\n  hence \"case d' of L \\<Rightarrow> rat_of (mediant p'm) < rat_of (mediant m) | R \\<Rightarrow> rat_of (mediant m) < rat_of (mediant p'm)\"\n    using tree_ordering_left[OF Dm Dp'm' Pm, unfolded pm']\n          tree_ordering_right[OF Dm Dp'm' Pm, unfolded pm']\n    by (simp split: dir.splits)\n  ultimately show False using pm' p'm' assms\n    by(simp add: m_def pm_def p'm_def stern_brocot_iterate_def split: dir.splits)\nqed\n\nlemma lists_not_eq:\n  assumes \"xs \\<noteq> ys\"\n  obtains\n    (c1) \"strict_prefix xs ys\"\n  | (c2) \"strict_prefix ys xs\"\n  | (c3) ps x y xs' ys'\n          where \"xs = ps @ x # xs'\" and \"ys = ps @ y # ys'\" and \"x \\<noteq> y\"\nusing assms\nby (cases xs ys rule: prefix_cases)\n   (blast dest: parallel_decomp prefix_order.neq_le_trans)+\n\n\n\ntext \\<open> The function @{const Fract} is injective under certain conditions. \\<close>\n\nlemma rat_inv_eq:\n  assumes \"Fract a b = Fract c d\"\n  assumes \"b > 0\"\n  assumes \"d > 0\"\n  assumes \"coprime a b\"\n  assumes \"coprime c d\"\n  shows \"a = c \\<and> b = d\"\nproof -\n  from \\<open>b > 0\\<close> \\<open>d > 0\\<close> \\<open>Fract a b = Fract c d\\<close>\n  have *: \"a * d = c * b\" by (simp add: eq_rat)\n  from arg_cong[where f=sgn, OF this] \\<open>b > 0\\<close> \\<open>d > 0\\<close>\n  have \"sgn a = sgn c\" by (simp add: sgn_mult)\n  with * show ?thesis\n    using \\<open>b > 0\\<close> \\<open>d > 0\\<close> coprime_crossproduct_int[OF \\<open>coprime a b\\<close> \\<open>coprime c d\\<close>]\n    by (simp add: abs_sgn)\nqed\n\ntheorem stern_brocot_rationals_not_repeated:\n  assumes \"root (traverse_tree path (pure rat_of \\<diamondop> stern_brocot_recurse))\n         = root (traverse_tree path' (pure rat_of \\<diamondop> stern_brocot_recurse))\"\n  shows \"path = path'\"\nusing assms\nusing stern_brocot_coprime[where path=path]\n      stern_brocot_coprime[where path=path']\n      stern_brocot_denominator_non_zero[where path=path]\n      stern_brocot_denominator_non_zero[where path=path']\nby(auto simp: gcd_int_def dest!: rat_inv_eq intro: stern_brocot_fractions_not_repeated simp add: stern_brocot_recurse_iterate[symmetric] split: prod.splits)\n\n\nsubsection \\<open>Equivalence of recursive and iterative version \\label{section:eq:rec:iterative}\\<close>\n\ntext \\<open>\n  \\citeauthor{Hinze2009JFP} shows that it does not matter whether we use @{const I} or\n  @{const \"F\"} at the root provided we swap the left and right matrices too.\n\\<close>\n\ndefinition stern_brocot_Hinze_iterate :: \"fraction tree\"\nwhere \"stern_brocot_Hinze_iterate = map_tree mediant (tree_iterate (\\<lambda>s. s \\<otimes> UR) (\\<lambda>s. s \\<otimes> LL) F)\"\n\nlemma mediant_times_F: \"mediant \\<circ> (\\<lambda>s. s \\<otimes> F) = mediant\"\nby(simp add: times_matrix_def F_def mediant_def split_def o_def add.commute)\n\nlemma stern_brocot_iterate: \"stern_brocot = stern_brocot_iterate\"\nproof -\n  have \"stern_brocot = stern_brocot_Hinze_iterate\"\n    unfolding stern_brocot_def stern_brocot_Hinze_iterate_def\n    by(subst unfold_tree_tree_iterate)(simp add: F_def times_matrix_def mediant_def UR_def LL_def split_def)\n  also have \"\\<dots> = map_tree mediant (map_tree (\\<lambda>s. s \\<otimes> F) (tree_iterate (\\<lambda>s. s \\<otimes> LL) (\\<lambda>s. s \\<otimes> UR) I))\"\n    unfolding stern_brocot_Hinze_iterate_def\n    by(subst tree_iterate_fusion[where l'=\"\\<lambda>s. s \\<otimes> UR\" and r'=\"\\<lambda>s. s \\<otimes> LL\"])\n      (simp_all add: fun_eq_iff times_matrix_def UR_def LL_def F_def I_def)\n  also have \"\\<dots> = stern_brocot_iterate\"\n    by(simp only: tree.map_comp mediant_times_F stern_brocot_iterate_def stern_brocot_iterate_aux_def)\n  finally show ?thesis .\nqed\n\ntheorem stern_brocot_mediant_recurse: \"stern_brocot = stern_brocot_recurse\"\nby(simp add: stern_brocot_recurse_iterate stern_brocot_iterate)\n\nend\n\nno_notation times_matrix (infixl \"\\<otimes>\" 70)\n  and times_vector (infixl \"\\<odot>\" 70)\n\nsection \\<open>Linearising the Stern-Brocot Tree\\<close>\n\nsubsection \\<open>Turning a tree into a stream\\<close>\n\ncorec tree_chop :: \"'a tree \\<Rightarrow> 'a tree\"\nwhere \"tree_chop t = Node (root (left t)) (right t) (tree_chop (left t))\"\n\nlemma tree_chop_sel [simp]:\n  \"root (tree_chop t) = root (left t)\"\n  \"left (tree_chop t) = right t\"\n  \"right (tree_chop t) = tree_chop (left t)\"\nby(subst tree_chop.code; simp; fail)+\n\ntext \\<open>@{const tree_chop} is a idiom homomorphism\\<close>\n\nlemma tree_chop_pure_tree [simp]:\n  \"tree_chop (pure x) = pure x\"\nby(coinduction rule: tree.coinduct_strong) auto\n\nlemma tree_chop_ap_tree [simp]:\n  \"tree_chop (f \\<diamondop> x) = tree_chop f \\<diamondop> tree_chop x\"\nby(coinduction arbitrary: f x rule: tree.coinduct_strong) auto\n\nlemma tree_chop_plus: \"tree_chop (t + t') = tree_chop t + tree_chop t'\"\nby(simp add: plus_tree_def)\n\ncorec stream :: \"'a tree \\<Rightarrow> 'a stream\"\nwhere \"stream t = root t ## stream (tree_chop t)\"\n\nlemma stream_sel [simp]:\n  \"shd (stream t) = root t\"\n  \"stl (stream t) = stream (tree_chop t)\"\nby(subst stream.code; simp; fail)+\n\ntext\\<open>@{const \"stream\"} is an idiom homomorphism.\\<close>\n\nlemma stream_pure [simp]: \"stream (pure x) = pure x\"\nby coinduction auto\n\nlemma stream_ap [simp]: \"stream (f \\<diamondop> x) = stream f \\<diamondop> stream x\"\nby(coinduction arbitrary: f x) auto\n\nlemma stream_plus [simp]: \"stream (t + t') = stream t + stream t'\"\nby(simp add: plus_stream_def plus_tree_def)\n\nlemma stream_minus [simp]: \"stream (t - t') = stream t - stream t'\"\nby(simp add: minus_stream_def minus_tree_def)\n\nlemma stream_times [simp]: \"stream (t * t') = stream t * stream t'\"\nby(simp add: times_stream_def times_tree_def)\n\nlemma stream_mod [simp]: \"stream (t mod t') = stream t mod stream t'\"\nby(simp add: modulo_stream_def modulo_tree_def)\n\nlemma stream_1 [simp]: \"stream 1 = 1\"\nby(simp add: one_tree_def one_stream_def)\n\nlemma stream_numeral [simp]: \"stream (numeral n) = numeral n\"\nby(induct n)(simp_all only: numeral.simps stream_plus stream_1)\n\nsubsection \\<open>Split the Stern-Brocot tree into numerators and denumerators\\<close>\n\ncorec num_den :: \"bool \\<Rightarrow> nat tree\"\nwhere\n  \"num_den x =\n   Node 1\n     (if x then num_den True else num_den True + num_den False)\n     (if x then num_den True + num_den False else num_den False)\"\n\nabbreviation num where \"num \\<equiv> num_den True\"\nabbreviation den where \"den \\<equiv> num_den False\"\n\nlemma num_unfold: \"num = Node 1 num (num + den)\"\nby(subst num_den.code; simp)\n\nlemma den_unfold: \"den = Node 1 (num + den) den\"\nby(subst num_den.code; simp)\n\nlemma num_simps [simp]:\n  \"root num = 1\"\n  \"left num = num\"\n  \"right num = num + den\"\nby(subst num_unfold, simp)+\n\nlemma den_simps [simp]:\n  \"root den = 1\"\n  \"left den = num + den\"\n  \"right den = den\"\nby (subst den_unfold, simp)+\n\nlemma stern_brocot_num_den:\n  \"pure_tree Pair \\<diamondop> num \\<diamondop> den = stern_brocot_recurse\"\napply(rule stern_brocot_recurse.unique)\napply(subst den_unfold)\napply(subst num_unfold)\napply(simp; intro conjI)\napply(applicative_lifting; simp)+\ndone\n\nlemma den_eq_chop_num: \"den = tree_chop num\"\nby(coinduction rule: tree.coinduct_strong) simp\n\nlemma num_conv: \"num = pure fst \\<diamondop> stern_brocot_recurse\"\nunfolding stern_brocot_num_den[symmetric]\napply(simp add: map_tree_ap_tree_pure_tree stern_brocot_num_den[symmetric])\napply(applicative_lifting; simp)\ndone\n\nlemma den_conv: \"den = pure snd \\<diamondop> stern_brocot_recurse\"\nunfolding stern_brocot_num_den[symmetric]\napply(simp add: map_tree_ap_tree_pure_tree stern_brocot_num_den[symmetric])\napply(applicative_lifting; simp)\ndone\n\ncorec num_mod_den :: \"nat tree\"\nwhere \"num_mod_den = Node 0 num num_mod_den\"\n\nlemma num_mod_den_simps [simp]:\n  \"root num_mod_den = 0\"\n  \"left num_mod_den = num\"\n  \"right num_mod_den = num_mod_den\"\nby(subst num_mod_den.code; simp; fail)+\n\ntext\\<open>\n  The arithmetic transformations need the precondition that @{const den} contains only\n  positive numbers, no @{term \"0 :: nat\"}. \\<^citet>\\<open>\\<open>p502\\<close> in \"Hinze2009JFP\"\\<close> gets a bit sloppy here; it is\n  not straightforward to adapt his lifting framework \\<^cite>\\<open>\"Hinze2010Lifting\"\\<close> to conditional equations.\n\\<close>\n\nlemma mod_tree_lemma1:\n  fixes x :: \"nat tree\"\n  assumes \"\\<forall>i\\<in>set_tree y. 0 < i\"\n  shows \"x mod (x + y) = x\"\nproof -\n  have \"rel_tree (=) (x mod (x + y)) x\" by applicative_lifting(simp add: assms)\n  thus ?thesis by(unfold tree.rel_eq)\nqed\n\nlemma mod_tree_lemma2:\n  fixes x y :: \"'a :: unique_euclidean_semiring tree\"\n  shows \"(x + y) mod y = x mod y\"\nby applicative_lifting simp\n\nlemma set_tree_pathD: \"x \\<in> set_tree t \\<Longrightarrow> \\<exists>p. x = root (traverse_tree p t)\"\nby(induct rule: set_tree_induct)(auto intro: exI[where x=\"[]\"] exI[where x=\"L # p\" for p] exI[where x=\"R # p\" for p])\n\nlemma den_gt_0: \"0 < x\" if \"x \\<in> set_tree den\"\nproof -\n  from that obtain p where \"x = root (traverse_tree p den)\" by(blast dest: set_tree_pathD)\n  with stern_brocot_denominator_non_zero[of p] show \"0 < x\" by(simp add: den_conv split_beta)\nqed\n\nlemma num_mod_den: \"num mod den = num_mod_den\"\nby(rule num_mod_den.unique)(rule tree.expand, simp add: mod_tree_lemma2 mod_tree_lemma1 den_gt_0)\n\nlemma tree_chop_den: \"tree_chop den = num + den - 2 * (num mod den)\"\nproof -\n  have le: \"0 < y \\<Longrightarrow> 2 * (x mod y) \\<le> x + y\" for x y :: nat\n    by (simp add: mult_2 add_mono)\n\n  text \\<open>We switch to @{typ int} such that all cancellation laws are available.\\<close>\n  define den' where \"den' = pure int \\<diamondop> den\"\n  define num' where \"num' = pure int \\<diamondop> num\"\n  define num_mod_den' where \"num_mod_den' = pure int \\<diamondop> num_mod_den\"\n\n  have [simp]: \"root num' = 1\" \"left num' = num'\" unfolding den'_def num'_def by simp_all\n  have [simp]: \"right num' = num' + den'\" unfolding den'_def num'_def ap_tree.sel pure_tree_simps num_simps\n    by applicative_lifting simp\n\n  have num_mod_den'_simps [simp]: \"root num_mod_den' = 0\" \"left num_mod_den' = num'\" \"right num_mod_den' = num_mod_den'\"\n    by(simp_all add: num_mod_den'_def num'_def)\n  have den'_eq_chop_num': \"den' = tree_chop num'\" by(simp add: den'_def num'_def den_eq_chop_num)\n  have num_mod_den'2_unique: \"\\<And>x. x = Node 0 (2 * num') x \\<Longrightarrow> x = 2 * num_mod_den'\"\n    by(corec_unique)(rule tree.expand; simp)\n  have num'_plus_den'_minus_chop_den': \"num' + den' - tree_chop den' = 2 * num_mod_den'\"\n    by(rule num_mod_den'2_unique)(rule tree.expand, simp add: tree_chop_plus den'_eq_chop_num')\n\n  have \"tree_chop den = pure nat \\<diamondop> (tree_chop den')\"\n    unfolding den_conv tree_chop_ap_tree tree_chop_pure_tree den'_def by applicative_nf simp\n  also have \"tree_chop den' = num' + den' - tree_chop den' + tree_chop den' - 2 * num_mod_den'\"\n    by(subst num'_plus_den'_minus_chop_den') simp\n  also have \"\\<dots> = num' + den' - 2 * (num' mod den')\"\n    unfolding num_mod_den'_def num'_def den'_def num_mod_den[symmetric]\n    by applicative_lifting(simp add: zmod_int)\n  also have [unfolded tree.rel_eq]: \"rel_tree (=) \\<dots> (pure int \\<diamondop> (num + den - 2 * (num mod den)))\"\n    unfolding num'_def den'_def by(applicative_lifting)(simp add: of_nat_diff zmod_int le den_gt_0)\n  also have \"pure nat \\<diamondop> (pure int \\<diamondop> (num + den - 2 * (num mod den))) = num + den - 2 * (num mod den)\" by(applicative_nf) simp\n  finally show ?thesis .\nqed\n\nsubsection\\<open>Loopless linearisation of the Stern-Brocot tree.\\<close>\n\ntext \\<open>\n  This is a loopless linearisation of the Stern-Brocot tree that gives Stern's diatomic sequence,\n  which is also known as Dijkstra's fusc function \\<^cite>\\<open>\"Dijkstra1982EWD570\" and \"Dijkstra1982EWD578\"\\<close>.\n  Loopless \\`a la \\<^cite>\\<open>\"Bird2006MPC\"\\<close> means that the first element of the stream can be computed in linear\n  time and every further element in constant time.\n\\<close>\n\nfriend_of_corec smap :: \"('a \\<Rightarrow> 'a) \\<Rightarrow> 'a stream \\<Rightarrow> 'a stream\"\nwhere \"smap f xs = SCons (f (shd xs)) (smap f (stl xs))\"\nsubgoal by(rule stream.expand) simp\nsubgoal by(fold relator_eq)(transfer_prover)\ndone\n\ndefinition step :: \"nat \\<times> nat \\<Rightarrow> nat \\<times> nat\"\nwhere \"step = (\\<lambda>(n, d). (d, n + d - 2 * (n mod d)))\"\n\ncorec stern_brocot_loopless :: \"fraction stream\"\nwhere \"stern_brocot_loopless = (1, 1) ## smap step stern_brocot_loopless\"\n\nlemmas stern_brocot_loopless_rec = stern_brocot_loopless.code\n\nfriend_of_corec plus where \"s + s' = (shd s + shd s') ## (stl s + stl s')\"\nsubgoal by (rule stream.expand; simp add: plus_stream_shd plus_stream_stl)\nsubgoal by transfer_prover\ndone\n\nfriend_of_corec minus where \"t - t' = (shd t - shd t') ## (stl t - stl t')\"\nsubgoal by (rule stream.expand; simp add: minus_stream_def)\nsubgoal by transfer_prover\ndone\n\nfriend_of_corec times where \"t * t' = (shd t * shd t') ## (stl t * stl t')\"\nsubgoal by (rule stream.expand; simp add: times_stream_def)\nsubgoal by transfer_prover\ndone\n\nfriend_of_corec modulo where \"t mod t' = (shd t mod shd t') ## (stl t mod stl t')\"\nsubgoal by (rule stream.expand; simp add: modulo_stream_def)\nsubgoal by transfer_prover\ndone\n\ncorec fusc' :: \"nat stream\"\nwhere \"fusc' = 1 ## (((1 ## fusc') + fusc') - 2 * ((1 ## fusc') mod fusc'))\"\n\ndefinition fusc where \"fusc = 1 ## fusc'\"\n\nlemma fusc_unfold: \"fusc = 1 ## fusc'\" by(fact fusc_def)\n\nlemma fusc'_unfold: \"fusc' = 1 ## (fusc + fusc' - 2 * (fusc mod fusc'))\"\nby(subst fusc'.code)(simp add: fusc_def)\n\nlemma fusc_simps [simp]:\n  \"shd fusc = 1\"\n  \"stl fusc = fusc'\"\nby(simp_all add: fusc_unfold)\n\nlemma fusc'_simps [simp]:\n  \"shd fusc' = 1\"\n  \"stl fusc' = fusc + fusc' - 2 * (fusc mod fusc')\"\nby(subst fusc'_unfold, simp)+\n\nsubsection \\<open>Equivalence with Dijkstra's fusc function\\<close>\n\nlemma stern_brocot_loopless_siterate: \"stern_brocot_loopless = siterate step (1, 1)\"\nby(rule stern_brocot_loopless.unique[symmetric])(rule stream.expand; simp add: smap_siterate[symmetric])\n\nlemma fusc_fusc'_iterate: \"pure Pair \\<diamondop> fusc \\<diamondop> fusc' = stern_brocot_loopless\"\napply(rule stern_brocot_loopless.unique)\napply(rule stream.expand; simp add: step_def)\napply(applicative_lifting; simp)\ndone\n\ntheorem stern_brocot_loopless:\n  \"stream stern_brocot_recurse = stern_brocot_loopless\" (is \"?lhs = ?rhs\")\nproof(rule stern_brocot_loopless.unique)\n  have eq: \"?lhs = stream (pure_tree Pair \\<diamondop> num \\<diamondop> den)\" by (simp only: stern_brocot_num_den)\n  have num: \"stream num = 1 ## stream den\"\n    by (rule stream.expand) (simp add: den_eq_chop_num)\n  have den: \"stream den = 1 ## (stream num + stream den - 2 * (stream num mod stream den))\"\n    by (rule stream.expand)(simp add: tree_chop_den)\n  show \"?lhs = (1, 1) ## smap step ?lhs\" unfolding eq\n    by(rule stream.expand)(simp add: den_eq_chop_num[symmetric] tree_chop_den; applicative_lifting; simp add: step_def)\nqed\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Stern_Brocot/Stern_Brocot_Tree.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8872046026642944, "lm_q1q2_score": 0.7505240239691654}}
{"text": "(*\n    $Id: sol.thy,v 1.4 2011/06/28 18:11:38 webertj Exp $\n*)\n\nheader {* Sum of List Elements, Tail-Recursively *}\n\n(*<*) theory sol imports Main begin (*>*)\n\ntext {*\n\\begin{description}\n\\item[\\bf (a)] Define a primitive recursive function @{term ListSum} that\ncomputes the sum of all elements of a list of natural numbers.\n\nProve the following equations.  Note that @{term  \"[0..n]\"} und @{term\n\"replicate n a\"} are already defined in a theory {\\tt List.thy}.\n\\end{description}\n*}\n\n  primrec ListSum :: \"nat list \\<Rightarrow> nat\" where \n    \"ListSum []     = 0\"\n  | \"ListSum (x#xs) = x + ListSum xs\"\n\n  theorem ListSum_append[simp]: \"ListSum (xs @ ys) = ListSum xs + ListSum ys\"\n    apply (induct xs)\n    apply auto\n  done\n\n  theorem \"2 * ListSum [0..<n+1] = n * (n + 1)\"\n    apply (induct n)\n    apply auto\n  done\n\n  theorem \"ListSum (replicate n a) = n * a\"\n    apply (induct n)\n    apply auto\n  done\n\n\ntext {* \n\\begin{description}\n\\item[\\bf (b)] Define an equivalent function @{term ListSumT} using a\ntail-recursive function @{term ListSumTAux}.  Prove that @{term ListSum}\nand @{term ListSumT} are in fact equivalent.\n\\end{description}\n*}\n\n  primrec ListSumTAux :: \"nat list \\<Rightarrow> nat \\<Rightarrow> nat\" where\n    \"ListSumTAux []     n = n\"\n  | \"ListSumTAux (x#xs) n = ListSumTAux xs (x + n)\"\n\n  definition ListSumT :: \"nat list \\<Rightarrow> nat\" where\n    \"ListSumT xs == ListSumTAux xs 0\"\n\n  lemma ListSumTAux_add [rule_format]: \"\\<forall>a b. ListSumTAux xs (a+b) = a + ListSumTAux xs b\"\n    apply (induct xs)\n    apply auto\n  done\n\n  \n\n  lemma [simp]: \"ListSumT (x#xs) = x + ListSumT xs\"\n    by (auto simp add: ListSumT_def ListSumTAux_add[THEN sym])\n\n  theorem \"ListSumT xs = ListSum xs\"\n    apply (induct xs)\n    apply auto\n  done\n\n(*<*) end (*>*)\n", "meta": {"author": "zchn", "repo": "isabelle-practice", "sha": "1c6de196ca011593faeed229808e65c9bfeb659e", "save_path": "github-repos/isabelle/zchn-isabelle-practice", "path": "github-repos/isabelle/zchn-isabelle-practice/isabelle-practice-1c6de196ca011593faeed229808e65c9bfeb659e/exercises/solutions/isabelle.in.tum.de/exercises/lists/sum-tail/sol.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.8807970842359877, "lm_q1q2_score": 0.7503975571238343}}
{"text": "(* This Isabelle theory is produced using the TIP tool offered at the following website: \n     https://github.com/tip-org/tools \n   This file was originally provided as part of TIP benchmark at the following website:\n     https://github.com/tip-org/benchmarks \n   Yutaka Nagashima at CIIRC, CTU changed the TIP output theory file slightly \n   to make it compatible with Isabelle2017.\n\\:w\n   Some proofs were added by Yutaka Nagashima.*)\n  theory TIP_sort_nat_HSortCount\n  imports \"../../Test_Base\"\nbegin\n\ndatatype 'a list = nil2 | cons2 \"'a\" \"'a list\"\n\ndatatype Nat = Z | S \"Nat\"\n\ndatatype Heap = Node \"Heap\" \"Nat\" \"Heap\" | Nil\n\nfun toHeap :: \"Nat list => Heap list\" where\n  \"toHeap (nil2) = nil2\"\n| \"toHeap (cons2 y z) = cons2 (Node Nil y Nil) (toHeap z)\"\n\nfun plus :: \"Nat => Nat => Nat\" where\n  \"plus (Z) y = y\"\n| \"plus (S z) y = S (plus z y)\"\n\nfun le :: \"Nat => Nat => bool\" where\n  \"le (Z) y = True\"\n| \"le (S z) (Z) = False\"\n| \"le (S z) (S x2) = le z x2\"\n\nfun hmerge :: \"Heap => Heap => Heap\" where\n  \"hmerge (Node z x2 x3) (Node x4 x5 x6) =\n   (if le x2 x5 then Node (hmerge x3 (Node x4 x5 x6)) x2 z else\n      Node (hmerge (Node z x2 x3) x6) x5 x4)\"\n| \"hmerge (Node z x2 x3) (Nil) = Node z x2 x3\"\n| \"hmerge (Nil) y = y\"\n\nfun hpairwise :: \"Heap list => Heap list\" where\n  \"hpairwise (nil2) = nil2\"\n| \"hpairwise (cons2 q (nil2)) = cons2 q (nil2)\"\n| \"hpairwise (cons2 q (cons2 r qs)) =\n     cons2 (hmerge q r) (hpairwise qs)\"\n\n(*fun did not finish the proof*)\nfunction hmerging :: \"Heap list => Heap\" where\n  \"hmerging (nil2) = Nil\"\n| \"hmerging (cons2 q (nil2)) = q\"\n| \"hmerging (cons2 q (cons2 z x2)) =\n     hmerging (hpairwise (cons2 q (cons2 z x2)))\"\n  by pat_completeness auto\n\nfun toHeap2 :: \"Nat list => Heap\" where\n  \"toHeap2 x = hmerging (toHeap x)\"\n\n(*fun did not finish the proof*)\nfunction toList :: \"Heap => Nat list\" where\n  \"toList (Node q y r) = cons2 y (toList (hmerge q r))\"\n| \"toList (Nil) = nil2\"\n  by pat_completeness auto\n\nfun hsort :: \"Nat list => Nat list\" where\n  \"hsort x = toList (toHeap2 x)\"\n\nfun count :: \"'a => 'a list => Nat\" where\n  \"count x (nil2) = Z\"\n| \"count x (cons2 z ys) =\n     (if (x = z) then plus (S Z) (count x ys) else count x ys)\"\n\ntheorem property0 :\n  \"((count x (hsort xs)) = (count x xs))\"\n  oops\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/UR/TIP_with_Proof/TIP15/TIP15/TIP_sort_nat_HSortCount.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811306, "lm_q2_score": 0.8244619220634457, "lm_q1q2_score": 0.7501836811113529}}
{"text": "(*  Title:      HOL/Library/Quotient_Type.thy\n    Author:     Markus Wenzel, TU Muenchen\n*)\n\nsection \\<open>Quotient types\\<close>\n\ntheory Quotient_Type\nimports \"MainRLT\"\nbegin\n\ntext \\<open>We introduce the notion of quotient types over equivalence relations\n  via type classes.\\<close>\n\n\nsubsection \\<open>Equivalence relations and quotient types\\<close>\n\ntext \\<open>Type class \\<open>equiv\\<close> models equivalence relations\n  \\<open>\\<sim> :: 'a \\<Rightarrow> 'a \\<Rightarrow> bool\\<close>.\\<close>\n\nclass eqv =\n  fixes eqv :: \"'a \\<Rightarrow> 'a \\<Rightarrow> bool\"  (infixl \"\\<sim>\" 50)\n\nclass equiv = eqv +\n  assumes equiv_refl [intro]: \"x \\<sim> x\"\n    and equiv_trans [trans]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> x \\<sim> z\"\n    and equiv_sym [sym]: \"x \\<sim> y \\<Longrightarrow> y \\<sim> x\"\nbegin\n\nlemma equiv_not_sym [sym]: \"\\<not> x \\<sim> y \\<Longrightarrow> \\<not> y \\<sim> x\"\nproof -\n  assume \"\\<not> x \\<sim> y\"\n  then show \"\\<not> y \\<sim> x\" by (rule contrapos_nn) (rule equiv_sym)\nqed\n\nlemma not_equiv_trans1 [trans]: \"\\<not> x \\<sim> y \\<Longrightarrow> y \\<sim> z \\<Longrightarrow> \\<not> x \\<sim> z\"\nproof -\n  assume \"\\<not> x \\<sim> y\" and \"y \\<sim> z\"\n  show \"\\<not> x \\<sim> z\"\n  proof\n    assume \"x \\<sim> z\"\n    also from \\<open>y \\<sim> z\\<close> have \"z \\<sim> y\" ..\n    finally have \"x \\<sim> y\" .\n    with \\<open>\\<not> x \\<sim> y\\<close> show False by contradiction\n  qed\nqed\n\nlemma not_equiv_trans2 [trans]: \"x \\<sim> y \\<Longrightarrow> \\<not> y \\<sim> z \\<Longrightarrow> \\<not> x \\<sim> z\"\nproof -\n  assume \"\\<not> y \\<sim> z\"\n  then have \"\\<not> z \\<sim> y\" ..\n  also\n  assume \"x \\<sim> y\"\n  then have \"y \\<sim> x\" ..\n  finally have \"\\<not> z \\<sim> x\" .\n  then show \"\\<not> x \\<sim> z\" ..\nqed\n\nend\n\ntext \\<open>The quotient type \\<open>'a quot\\<close> consists of all \\emph{equivalence\n  classes} over elements of the base type \\<^typ>\\<open>'a\\<close>.\\<close>\n\ndefinition (in eqv) \"quot = {{x. a \\<sim> x} | a. True}\"\n\ntypedef (overloaded) 'a quot = \"quot :: 'a::eqv set set\"\n  unfolding quot_def by blast\n\nlemma quotI [intro]: \"{x. a \\<sim> x} \\<in> quot\"\n  unfolding quot_def by blast\n\nlemma quotE [elim]:\n  assumes \"R \\<in> quot\"\n  obtains a where \"R = {x. a \\<sim> x}\"\n  using assms unfolding quot_def by blast\n\ntext \\<open>Abstracted equivalence classes are the canonical representation of\n  elements of a quotient type.\\<close>\n\ndefinition \"class\" :: \"'a::equiv \\<Rightarrow> 'a quot\"  (\"\\<lfloor>_\\<rfloor>\")\n  where \"\\<lfloor>a\\<rfloor> = Abs_quot {x. a \\<sim> x}\"\n\ntheorem quot_exhaust: \"\\<exists>a. A = \\<lfloor>a\\<rfloor>\"\nproof (cases A)\n  fix R\n  assume R: \"A = Abs_quot R\"\n  assume \"R \\<in> quot\"\n  then have \"\\<exists>a. R = {x. a \\<sim> x}\" by blast\n  with R have \"\\<exists>a. A = Abs_quot {x. a \\<sim> x}\" by blast\n  then show ?thesis unfolding class_def .\nqed\n\nlemma quot_cases [cases type: quot]:\n  obtains a where \"A = \\<lfloor>a\\<rfloor>\"\n  using quot_exhaust by blast\n\n\nsubsection \\<open>Equality on quotients\\<close>\n\ntext \\<open>Equality of canonical quotient elements coincides with the original\n  relation.\\<close>\n\ntheorem quot_equality [iff?]: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor> \\<longleftrightarrow> a \\<sim> b\"\nproof\n  assume eq: \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor>\"\n  show \"a \\<sim> b\"\n  proof -\n    from eq have \"{x. a \\<sim> x} = {x. b \\<sim> x}\"\n      by (simp only: class_def Abs_quot_inject quotI)\n    moreover have \"a \\<sim> a\" ..\n    ultimately have \"a \\<in> {x. b \\<sim> x}\" by blast\n    then have \"b \\<sim> a\" by blast\n    then show ?thesis ..\n  qed\nnext\n  assume ab: \"a \\<sim> b\"\n  show \"\\<lfloor>a\\<rfloor> = \\<lfloor>b\\<rfloor>\"\n  proof -\n    have \"{x. a \\<sim> x} = {x. b \\<sim> x}\"\n    proof (rule Collect_cong)\n      fix x show \"(a \\<sim> x) = (b \\<sim> x)\"\n      proof\n        from ab have \"b \\<sim> a\" ..\n        also assume \"a \\<sim> x\"\n        finally show \"b \\<sim> x\" .\n      next\n        note ab\n        also assume \"b \\<sim> x\"\n        finally show \"a \\<sim> x\" .\n      qed\n    qed\n    then show ?thesis by (simp only: class_def)\n  qed\nqed\n\n\nsubsection \\<open>Picking representing elements\\<close>\n\ndefinition pick :: \"'a::equiv quot \\<Rightarrow> 'a\"\n  where \"pick A = (SOME a. A = \\<lfloor>a\\<rfloor>)\"\n\ntheorem pick_equiv [intro]: \"pick \\<lfloor>a\\<rfloor> \\<sim> a\"\nproof (unfold pick_def)\n  show \"(SOME x. \\<lfloor>a\\<rfloor> = \\<lfloor>x\\<rfloor>) \\<sim> a\"\n  proof (rule someI2)\n    show \"\\<lfloor>a\\<rfloor> = \\<lfloor>a\\<rfloor>\" ..\n    fix x assume \"\\<lfloor>a\\<rfloor> = \\<lfloor>x\\<rfloor>\"\n    then have \"a \\<sim> x\" ..\n    then show \"x \\<sim> a\" ..\n  qed\nqed\n\ntheorem pick_inverse [intro]: \"\\<lfloor>pick A\\<rfloor> = A\"\nproof (cases A)\n  fix a assume a: \"A = \\<lfloor>a\\<rfloor>\"\n  then have \"pick A \\<sim> a\" by (simp only: pick_equiv)\n  then have \"\\<lfloor>pick A\\<rfloor> = \\<lfloor>a\\<rfloor>\" ..\n  with a show ?thesis by simp\nqed\n\ntext \\<open>The following rules support canonical function definitions on quotient\n  types (with up to two arguments). Note that the stripped-down version\n  without additional conditions is sufficient most of the time.\\<close>\n\ntheorem quot_cond_function:\n  assumes eq: \"\\<And>X Y. P X Y \\<Longrightarrow> f X Y \\<equiv> g (pick X) (pick Y)\"\n    and cong: \"\\<And>x x' y y'. \\<lfloor>x\\<rfloor> = \\<lfloor>x'\\<rfloor> \\<Longrightarrow> \\<lfloor>y\\<rfloor> = \\<lfloor>y'\\<rfloor>\n      \\<Longrightarrow> P \\<lfloor>x\\<rfloor> \\<lfloor>y\\<rfloor> \\<Longrightarrow> P \\<lfloor>x'\\<rfloor> \\<lfloor>y'\\<rfloor> \\<Longrightarrow> g x y = g x' y'\"\n    and P: \"P \\<lfloor>a\\<rfloor> \\<lfloor>b\\<rfloor>\"\n  shows \"f \\<lfloor>a\\<rfloor> \\<lfloor>b\\<rfloor> = g a b\"\nproof -\n  from eq and P have \"f \\<lfloor>a\\<rfloor> \\<lfloor>b\\<rfloor> = g (pick \\<lfloor>a\\<rfloor>) (pick \\<lfloor>b\\<rfloor>)\" by (simp only:)\n  also have \"... = g a b\"\n  proof (rule cong)\n    show \"\\<lfloor>pick \\<lfloor>a\\<rfloor>\\<rfloor> = \\<lfloor>a\\<rfloor>\" ..\n    moreover\n    show \"\\<lfloor>pick \\<lfloor>b\\<rfloor>\\<rfloor> = \\<lfloor>b\\<rfloor>\" ..\n    moreover\n    show \"P \\<lfloor>a\\<rfloor> \\<lfloor>b\\<rfloor>\" by (rule P)\n    ultimately show \"P \\<lfloor>pick \\<lfloor>a\\<rfloor>\\<rfloor> \\<lfloor>pick \\<lfloor>b\\<rfloor>\\<rfloor>\" by (simp only:)\n  qed\n  finally show ?thesis .\nqed\n\ntheorem quot_function:\n  assumes \"\\<And>X Y. f X Y \\<equiv> g (pick X) (pick Y)\"\n    and \"\\<And>x x' y y'. \\<lfloor>x\\<rfloor> = \\<lfloor>x'\\<rfloor> \\<Longrightarrow> \\<lfloor>y\\<rfloor> = \\<lfloor>y'\\<rfloor> \\<Longrightarrow> g x y = g x' y'\"\n  shows \"f \\<lfloor>a\\<rfloor> \\<lfloor>b\\<rfloor> = g a b\"\n  using assms and TrueI\n  by (rule quot_cond_function)\n\ntheorem quot_function':\n  \"(\\<And>X Y. f X Y \\<equiv> g (pick X) (pick Y)) \\<Longrightarrow>\n    (\\<And>x x' y y'. x \\<sim> x' \\<Longrightarrow> y \\<sim> y' \\<Longrightarrow> g x y = g x' y') \\<Longrightarrow>\n    f \\<lfloor>a\\<rfloor> \\<lfloor>b\\<rfloor> = g a b\"\n  by (rule quot_function) (simp_all only: quot_equality)\n\nend\n", "meta": {"author": "dtraytel", "repo": "HOLRLT", "sha": "e9029da59bb3af0c835604a65308498f9696a364", "save_path": "github-repos/isabelle/dtraytel-HOLRLT", "path": "github-repos/isabelle/dtraytel-HOLRLT/HOLRLT-e9029da59bb3af0c835604a65308498f9696a364/HOLRLT/Library/Quotient_Type.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.8670357718273068, "lm_q1q2_score": 0.7501802362671608}}
{"text": "subsection \\<open>Local versions of relations\\<close>\n\ntheory Relations\n  imports\n    \"HOL-Library.Multiset\"\n    \"Abstract-Rewriting.Abstract_Rewriting\"\nbegin\n\ntext\\<open>Common predicates on relations\\<close>\n\ndefinition compatible_l :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> bool\" where\n  \"compatible_l R1 R2 \\<equiv> R1 O R2 \\<subseteq> R2\"\n\ndefinition compatible_r :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> bool\" where\n  \"compatible_r R1 R2 \\<equiv> R2 O R1 \\<subseteq> R2\"\n\ntext\\<open>Local reflexivity\\<close>\n\ndefinition locally_refl :: \"'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_refl R A \\<equiv> (\\<forall> a. a \\<in># A \\<longrightarrow> (a,a) \\<in> R)\"\n\ndefinition locally_irrefl :: \"'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_irrefl R A \\<equiv> (\\<forall>t. t \\<in># A \\<longrightarrow> (t,t) \\<notin> R)\"\n\ntext\\<open>Local symmetry\\<close>\n\ndefinition locally_sym :: \"'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_sym R A \\<equiv> (\\<forall>t u. t \\<in># A \\<longrightarrow> u \\<in># A \\<longrightarrow>\n               (t,u) \\<in> R \\<longrightarrow> (u,t) \\<in> R)\"\n\ndefinition locally_antisym :: \"'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_antisym R A \\<equiv> (\\<forall>t u. t \\<in># A \\<longrightarrow> u \\<in># A \\<longrightarrow>\n               (t,u) \\<in> R \\<longrightarrow> (u,t) \\<in> R \\<longrightarrow> t = u)\"\n\ntext\\<open>Local transitivity\\<close>\n\ndefinition locally_trans :: \"'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_trans R A B C \\<equiv> (\\<forall>t u v.\n               t \\<in># A \\<longrightarrow> u \\<in># B \\<longrightarrow> v \\<in># C \\<longrightarrow>\n               (t,u) \\<in> R \\<longrightarrow> (u,v) \\<in> R \\<longrightarrow> (t,v) \\<in> R)\"\n\ntext\\<open>Local inclusion\\<close>\n\ndefinition locally_included :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_included R1 R2 A B \\<equiv> (\\<forall>t u. t \\<in># A \\<longrightarrow> u \\<in># B \\<longrightarrow>\n               (t,u) \\<in> R1 \\<longrightarrow>  (t,u) \\<in> R2)\"\n\ntext\\<open>Local transitivity compatibility\\<close>\n\ndefinition locally_compatible_l :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_compatible_l R1 R2 A B C \\<equiv> (\\<forall>t u v. t \\<in># A \\<longrightarrow> u \\<in># B \\<longrightarrow> v \\<in># C \\<longrightarrow>\n               (t,u) \\<in> R1 \\<longrightarrow> (u,v) \\<in> R2 \\<longrightarrow> (t,v) \\<in> R2)\"\n\ndefinition locally_compatible_r :: \"'a rel \\<Rightarrow> 'a rel \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> 'a multiset \\<Rightarrow> bool\" where\n  \"locally_compatible_r R1 R2 A B C \\<equiv> (\\<forall>t u v. t \\<in># A \\<longrightarrow> u \\<in># B \\<longrightarrow> v \\<in># C \\<longrightarrow>\n               (t,u) \\<in> R2 \\<longrightarrow> (u,v) \\<in> R1 \\<longrightarrow> (t,v) \\<in> R2)\" \n\ntext\\<open>included + compatible $\\longrightarrow$  transitive\\<close>\n\nlemma in_cl_tr:\n  assumes \"R1 \\<subseteq> R2\"\n    and \"compatible_l R2 R1\"\n  shows \"trans R1\"\nproof-\n  {\n    fix x y z\n    assume s_x_y: \"(x,y) \\<in> R1\" and s_y_z: \"(y,z) \\<in> R1\"\n    from assms s_x_y have \"(x,y) \\<in> R2\" by auto\n    with s_y_z assms(2)[unfolded compatible_l_def]  have \"(x,z) \\<in> R1\" by blast\n  }\n  then show ?thesis unfolding trans_def by fast\nqed\n\nlemma in_cr_tr:\n  assumes \"R1 \\<subseteq> R2\"\n    and \"compatible_r R2 R1\"\n  shows \"trans R1\"\nproof-\n  {\n    fix x y z\n    assume s_x_y: \"(x,y) \\<in> R1\" and s_y_z: \"(y,z) \\<in> R1\"\n    with assms have \"(y,z) \\<in> R2\" by auto\n    with s_x_y assms(2)[unfolded compatible_r_def] have \"(x,z) \\<in> R1\" by blast\n  }\n  then show ?thesis unfolding trans_def by fast\nqed\n\ntext\\<open>If a property holds globally, it also holds locally. Obviously.\\<close>\n\nlemma r_lr:\n  assumes \"refl R\"\n  shows \"locally_refl R A\"\n  using assms unfolding refl_on_def locally_refl_def by blast\n\nlemma tr_ltr:\n  assumes \"trans R\"\n  shows \"locally_trans R A B C\"\n  using assms unfolding trans_def and locally_trans_def by fast\n\nlemma in_lin:\n  assumes \"R1 \\<subseteq> R2\"\n  shows \"locally_included R1 R2 A B\"\n  using assms unfolding locally_included_def by auto\n\nlemma cl_lcl:\n  assumes \"compatible_l R1 R2\"\n  shows \"locally_compatible_l R1 R2 A B C\"\n  using assms unfolding compatible_l_def and locally_compatible_l_def by auto\n\nlemma cr_lcr:\n  assumes \"compatible_r R1 R2\"\n  shows \"locally_compatible_r R1 R2 A B C\"\n  using assms unfolding compatible_r_def and locally_compatible_r_def by auto\n\ntext\\<open>If a predicate holds on a set then it holds on\n  all the subsets:\\<close>\n\nlemma lr_trans_l:\n  assumes \"locally_refl R (A + B)\"\n  shows \"locally_refl R A\"\n  using assms unfolding locally_refl_def\n  by auto\n\nlemma li_trans_l:\n  assumes \"locally_irrefl R (A + B)\"\n  shows \"locally_irrefl R A\"\n  using assms unfolding locally_irrefl_def\n  by auto\n\nlemma ls_trans_l:\n  assumes \"locally_sym R (A + B)\"\n  shows \"locally_sym R A\"\n  using assms unfolding locally_sym_def\n  by auto\n\nlemma las_trans_l:\n  assumes \"locally_antisym R (A + B)\"\n  shows \"locally_antisym R A\"\n  using assms unfolding locally_antisym_def\n  by auto\n\nlemma lt_trans_l:\n  assumes \"locally_trans R (A + B) (C + D) (E + F)\"\n  shows \"locally_trans R A C E\"\n  using assms[unfolded locally_trans_def, rule_format]\n  unfolding locally_trans_def by auto\n\nlemma lin_trans_l: \n  assumes \"locally_included R1 R2 (A + B) (C + D)\"\n  shows \"locally_included R1 R2 A C\"\n  using assms unfolding locally_included_def by auto\n\nlemma lcl_trans_l: \n  assumes \"locally_compatible_l R1 R2 (A + B) (C + D) (E + F)\"\n  shows \"locally_compatible_l R1 R2 A C E\"\n  using assms[unfolded locally_compatible_l_def, rule_format]\n  unfolding locally_compatible_l_def by auto\n\nlemma lcr_trans_l: \n  assumes \"locally_compatible_r R1 R2 (A + B) (C + D) (E + F)\"\n  shows \"locally_compatible_r R1 R2 A C E\"\n  using assms[unfolded locally_compatible_r_def, rule_format]\n  unfolding locally_compatible_r_def by auto\n\nlemma lr_trans_r:\n  assumes \"locally_refl R (A + B)\"\n  shows \"locally_refl R B\"\n  using assms unfolding locally_refl_def\n  by auto\n\nlemma li_trans_r:\n  assumes \"locally_irrefl R (A + B)\"\n  shows \"locally_irrefl R B\"\n  using assms unfolding locally_irrefl_def\n  by auto\n\nlemma ls_trans_r:\n  assumes \"locally_sym R (A + B)\"\n  shows \"locally_sym R B\"\n  using assms unfolding locally_sym_def\n  by auto\n\nlemma las_trans_r:\n  assumes \"locally_antisym R (A + B)\"\n  shows \"locally_antisym R B\"\n  using assms unfolding locally_antisym_def\n  by auto\n\nlemma lt_trans_r:\n  assumes \"locally_trans R (A + B) (C + D) (E + F)\"\n  shows \"locally_trans R B D F\"\n  using assms[unfolded locally_trans_def, rule_format]\n  unfolding locally_trans_def\n  by auto\n\nlemma lin_trans_r: \n  assumes \"locally_included R1 R2 (A + B) (C + D)\"\n  shows \"locally_included R1 R2 B D\"\n  using assms unfolding locally_included_def by auto\n\nlemma lcl_trans_r:\n  assumes \"locally_compatible_l R1 R2 (A + B) (C + D) (E + F)\"\n  shows \"locally_compatible_l R1 R2 B D F\"\n  using assms[unfolded locally_compatible_l_def, rule_format]\n  unfolding locally_compatible_l_def by auto\n\nlemma lcr_trans_r: \n  assumes \"locally_compatible_r R1 R2 (A + B) (C + D) (E + F)\"\n  shows \"locally_compatible_r R1 R2 B D F\"\n  using assms[unfolded locally_compatible_r_def, rule_format]\n  unfolding locally_compatible_r_def by auto\n\nlemma lr_minus:\n  assumes \"locally_refl R A\"\n  shows \"locally_refl R (A - B)\"\n  using assms unfolding locally_refl_def by (meson in_diffD)\n\nlemma li_minus:\n  assumes \"locally_irrefl R A\"\n  shows \"locally_irrefl R (A - B)\"\n  using assms unfolding locally_irrefl_def by (meson in_diffD)\n\nlemma ls_minus:\n  assumes \"locally_sym R A\"\n  shows \"locally_sym R (A - B)\"\n  using assms unfolding locally_sym_def by (meson in_diffD)\n\n\nlemma las_minus:\n  assumes \"locally_antisym R A\"\n  shows \"locally_antisym R (A - B)\"\n  using assms unfolding locally_antisym_def by (meson in_diffD)\n\nlemma lt_minus:\n  assumes \"locally_trans R A C E\"\n  shows \"locally_trans R (A - B) (C - D) (E - F)\"\n  using assms[unfolded locally_trans_def, rule_format]\n  unfolding locally_trans_def by (meson in_diffD)\n\n\nlemma lin_minus: \n  assumes \"locally_included R1 R2 A C\"\n  shows \"locally_included R1 R2 (A - B) (C - D)\"\n  using assms unfolding locally_included_def by (meson in_diffD)\n\nlemma lcl_minus:\n  assumes \"locally_compatible_l R1 R2 A C E\"\n  shows \"locally_compatible_l R1 R2 (A - B) (C - D) (E - F)\"\n  using assms[unfolded locally_compatible_l_def, rule_format]\n  unfolding locally_compatible_l_def by (meson in_diffD)\n\nlemma lcr_minus: \n  assumes \"locally_compatible_r R1 R2 A C E\"\n  shows \"locally_compatible_r R1 R2 (A - B) (C - D) (E - F)\"\n  using assms[unfolded locally_compatible_r_def, rule_format]\n  unfolding locally_compatible_r_def by (meson in_diffD)\n\n\ntext \\<open>Notations\\<close>\n\nnotation restrict (infixl \"\\<restriction>\" 80)\n\nlemma mem_restrictI[intro!]: assumes \"x \\<in> X\" \"y \\<in> X\" \"(x,y) \\<in> R\" shows \"(x,y) \\<in> R \\<restriction> X\"\n  using assms unfolding restrict_def by auto\n\nlemma mem_restrictD[dest]: assumes \"(x,y) \\<in> R \\<restriction> X\" shows \"x \\<in> X\" \"y \\<in> X\" \"(x,y) \\<in> R\"\n  using assms unfolding restrict_def by auto\n\n\nend\n", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Weighted_Path_Order/Relations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.8670357701094304, "lm_q1q2_score": 0.7501802317676125}}
{"text": "(*  Title:      HOL/ex/MergeSort.thy\n    Author:     Tobias Nipkow\n    Copyright   2002 TU Muenchen\n*)\n\nsection{*Merge Sort*}\n\ntheory MergeSort\nimports \"~~/src/HOL/Library/Multiset\"\nbegin\n\ncontext linorder\nbegin\n\nfun merge :: \"'a list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\nwhere\n  \"merge (x#xs) (y#ys) =\n         (if x \\<le> y then x # merge xs (y#ys) else y # merge (x#xs) ys)\"\n| \"merge xs [] = xs\"\n| \"merge [] ys = ys\"\n\nlemma multiset_of_merge [simp]:\n  \"multiset_of (merge xs ys) = multiset_of xs + multiset_of ys\"\n  by (induct xs ys rule: merge.induct) (simp_all add: ac_simps)\n\nlemma set_merge [simp]:\n  \"set (merge xs ys) = set xs \\<union> set ys\"\n  by (induct xs ys rule: merge.induct) auto\n\nlemma sorted_merge [simp]:\n  \"sorted (merge xs ys) \\<longleftrightarrow> sorted xs \\<and> sorted ys\"\n  by (induct xs ys rule: merge.induct) (auto simp add: ball_Un not_le less_le sorted_Cons)\n\nfun msort :: \"'a list \\<Rightarrow> 'a list\"\nwhere\n  \"msort [] = []\"\n| \"msort [x] = [x]\"\n| \"msort xs = merge (msort (take (size xs div 2) xs))\n                    (msort (drop (size xs div 2) xs))\"\n\nlemma sorted_msort:\n  \"sorted (msort xs)\"\n  by (induct xs rule: msort.induct) simp_all\n\nlemma multiset_of_msort:\n  \"multiset_of (msort xs) = multiset_of xs\"\n  by (induct xs rule: msort.induct)\n    (simp_all, metis append_take_drop_id drop_Suc_Cons multiset_of.simps(2) multiset_of_append take_Suc_Cons)\n\ntheorem msort_sort:\n  \"sort = msort\"\n  by (rule ext, rule properties_for_sort) (fact multiset_of_msort sorted_msort)+\n\nend\n\nend\n", "meta": {"author": "Josh-Tilles", "repo": "isabelle", "sha": "990accf749b8a6e037d25012258ecae20d59ca62", "save_path": "github-repos/isabelle/Josh-Tilles-isabelle", "path": "github-repos/isabelle/Josh-Tilles-isabelle/isabelle-990accf749b8a6e037d25012258ecae20d59ca62/src/HOL/ex/MergeSort.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8670357460591569, "lm_q2_score": 0.865224091265267, "lm_q1q2_score": 0.7501802154785369}}
{"text": "theory Exercises\nimports Main\nbegin\n\ntext \\<open> Exercise 2.1 \\<close>\nvalue \"1 + (2::nat)\"\nvalue \"1 + (2::int)\"\nvalue \"1 - (2::nat)\"\nvalue \"1 - (2::int)\"\ntext \\<open> End of exercise 2.1 \\<close>\n\n\ntext \\<open> Exercise 2.2 \\<close>\nfun add :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"add 0 n = n\" | \"add (Suc m) n = Suc (add m n)\"\n\nlemma add_m0[simp]: \"add m 0 = m\"\n  apply(induction m)\n  apply(auto)\ndone \n\nlemma add_suc[simp]: \"add n (Suc m) = Suc (add n m)\"\n  apply(induction n)\n  apply(auto)\n done\n\nlemma add_assoc[simp]: \"add (add a b) c = add a (add b c)\"\n  apply(induction a)\n  apply(auto)\ndone\n\nlemma add_comm[simp]: \"add a b = add b a\"\n  apply(induction a)\n  apply(auto)\ndone\n\nfun double :: \"nat \\<Rightarrow> nat\"\n  where \"double 0 = 0\" | \"double (Suc n) = add (Suc (Suc 0 ) ) (double n)\"\n\nlemma double_and_add : \"double m = add m m\"\n  apply(induction m)\n  apply(auto)\ndone\ntext \\<open> Exercise 2.2 \\<close>\n\n\n\ntext \\<open> Exercise 2.3 \\<close>\nfun count :: \" 'a \\<Rightarrow> 'a list \\<Rightarrow> nat \"\n  where \n    \"count n Nil = 0\" |\n    \"count n (Cons x xs) = add 0 (if n = x then add 1 (count n xs) else add 0 (count n xs))\"\n\ntheorem upperBound_of_count : \"count n xs \\<le> length xs\"\n  apply(induction xs)\n  apply(auto)\n  done\ntext \\<open> End of exercise 2.3 \\<close>\n\n\n\ntext \\<open> Exercise 2.4 \\<close>\nfun snoc :: \" 'a list \\<Rightarrow> 'a \\<Rightarrow> 'a list \"\n  where \n    \"snoc [] n =  [n]\" |\n    \"snoc (x # xs) n = x # (snoc xs n) \"\n\nfun reverse :: \" 'a list \\<Rightarrow> 'a list \"\n  where\n    \"reverse [] = []\" |\n    \"reverse (x # xs) = snoc (reverse xs) x\"\n\n\n\ntheorem rev_rev : \"reverse (reverse xs) = xs\"\n  apply(induction xs)\n  apply(auto)\n  done\ntext \\<open> End of exercise 2.4 \\<close>\n\n\n\ntext \\<open> Exercise 2.5 \\<close>\nfun sum :: \" nat \\<Rightarrow> nat \"\n  where \"sum 0 = 0\" | \"sum (Suc n) = (Suc n) + (sum n)\"\n\ntheorem known_fact : \"sum n = n * (n+1) div 2\"\n  apply(induction n)\n  apply(auto)\ndone\ntext \\<open> End of exercise 2.5 \\<close>\n\n\ntext \\<open> Exercise 2.6 \\<close>\ndatatype 'a tree = Tip | Node \"'a tree\" 'a \"'a tree\"\n\nfun contents :: \" 'a tree \\<Rightarrow> 'a list \"\n  where \"contents Tip = []\" |\n        \"contents (Node t1 x t2) = x # (contents t1 @ contents t2)\"\n\nfun treesum :: \" nat tree \\<Rightarrow> nat  \"\n  where \"treesum Tip = 0\" |\n        \"treesum (Node t1 x t2) = sum_list (contents (Node t1 x t2))\"\n\nlemma treesum_equals_sum_list : \"treesum myTree = sum_list (contents myTree)\"\n   apply(induction)\n   apply(auto)\ndone\ntext \\<open> End of exercise 2.6 \\<close>\n\ntext \\<open> Exercise 2.7 \\<close>\n\ndatatype 'a tree2 = Tip 'a | Node \"'a tree2\" 'a \"'a tree2\"\n\nfun mirror :: \" 'a tree2 \\<Rightarrow> 'a tree2\"\n  where \"mirror (Tip x) = Tip x\"|\n        \"mirror (Node t1 x t2) = Node (mirror t2) x (mirror t1)\"\n\nfun pre_order :: \" 'a tree2 \\<Rightarrow> 'a list \"\n  where \"pre_order (Tip x) = x # []\" |\n        \"pre_order (Node t1 x t2) = x # ( (pre_order t1) @ (pre_order t2) )\"\n\nfun post_order :: \" 'a tree2 \\<Rightarrow> 'a list \"\n  where \"post_order (Tip x) = x # []\" |\n        \"post_order (Node t1 x t2) = ( (post_order t1) @ (post_order t2) ) @ (x # [])\"\n\ntext \\<open>\n      1\n     /\\\n    2  3\n   /\\  /\\\n  4 5  6 7\npre: 1-2-4-5-3-6-7\npost: 4-5-2-6-7-3-1\n\\<close>\n\nvalue \"rev(post_order (Node (Node (Tip 4) 2 (Tip 5)) 1 (Node (Tip 6) 3 (Tip (7::int)))))\"\nvalue \"pre_order (mirror ((Node (Node (Tip 4) 2 (Tip 5)) 1 (Node (Tip 6) 3 (Tip (7::int))))))\"\n\nlemma relation_between_pre_and_post_order : \"pre_order (mirror t) = rev (post_order t)\"\n  apply(induction t)\n  apply(auto)\ndone\n\ntext \\<open> End of exercise 2.7 \\<close>\n\ntext \\<open> End of exercise 2.8 \\<close>\n\nfun interspere :: \"'a \\<Rightarrow> 'a list \\<Rightarrow> 'a list\"\n  where \"interspere n [] = [n]\" |\n        \"interspere n [x] = [x]\" |\n        \"interspere n (x # xs) = [x,n] @ (interspere n xs)\"\n\nlemma map_interspere_propertie : \"map f (interspere n l) = interspere (f n) (map f l)\"\n  apply(induction l rule: interspere.induct)\n  apply(auto)\ndone\n\ntext \\<open> End of exercise 2.8 \\<close>\n\ntext \\<open> Exercise 2.9 \\<close>\n\nfun itadd :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat\"\n  where \"itadd 0 n = n\"|\n        \"itadd (Suc m) n = itadd m (Suc n)\"\n\nlemma itadd_equals_add : \"itadd m n = add m n\"\n  apply(induction m arbitrary: n)\n  apply(auto)\ndone\n\n\ntext \\<open> End of exercise 2.9 \\<close>\n\ntext \\<open> Exercise 2.10 \\<close>\n\n\ndatatype tree0 = Tip | Node \"tree0\" \"tree0\"\n\nfun nodes :: \"tree0 \\<Rightarrow> nat\"\n  where \"nodes Tip = 1\" |\n        \"nodes (Node t1 t2) = 1 + nodes t1 + nodes t2\"\n\ntext \\<open>\n    N\n   / \\\n  T   N\n     / \\\n    T   T\n\\<close>\nvalue \"nodes (Node (Node Tip Tip) Tip)\" \n\nfun explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> tree0\" where\n\"explode 0 t = t\" |\n\"explode (Suc n) t = explode n (Node t t )\"\n\nvalue \"nodes (explode 0 (Node (Node Tip Tip) Tip))\"\ntext \\<open>\n  So... My Tree0 has 5 elements. \n  Explode 0 -> 5. Right\n  Explode 1 -> 5 + 5 + 1, since it duplicates the previous and add a node.\n  Explode 2 -> 11 + 11 + 1, same reasoning as before...\n  Therefore let's define n := nodes myTree and f(x) = 2x + 1\n    0 -> n              :5\n    1 -> f(n)           :11 2*5 + 1\n    2 -> f(f(n))        :23 2(2*5+1) + 1\n    3 -> f(f(f(n)))     :47 2*(2*(2*5 + 1) + 1\n\\<close>\n\nfun size_explode :: \"nat \\<Rightarrow> tree0 \\<Rightarrow> nat\" where\n\"size_explode n t = 2^n * (nodes t) + 2^n - 1\"\n\nvalue \"nodes (explode 0 (Node (Node Tip Tip) Tip))\"\nvalue \"nodes (explode 1 (Node (Node Tip Tip) Tip))\"\nvalue \"nodes (explode 2 (Node (Node Tip Tip) Tip))\"\n\nvalue \"size_explode 0 (Node (Node Tip Tip) Tip)\"\nvalue \"size_explode 1 (Node (Node Tip Tip) Tip)\"\nvalue \"size_explode 2 (Node (Node Tip Tip) Tip)\"\n\nlemma expression : \"nodes (explode n t) = size_explode n t\"\n  apply(induction n arbitrary:t)\n  apply(auto simp add: algebra_simps)\ndone\n\n\ntext \\<open> End of exercise 2.10 \\<close>\n\ntext \\<open> Exercise 2.11 \\<close>\n\ndatatype exp = Var | Const int | Add exp exp | Mult exp exp\n\nfun eval :: \"exp \\<Rightarrow> int \\<Rightarrow> int\" where\n\"eval Var x = x\" |\n\"eval (Const a) x = a\" |\n\"eval (Add a b) x = (eval a x) + (eval b x)\" |\n\"eval (Mult a b) x = (eval a x) * (eval b x)\"\n\n\nvalue\"Add (Var) (Add (Var) (Const 3))\"\ntext \\<open> This seems to be x + x + 3 \\<close>\nvalue\"eval (Add (Var) (Add (Var) (Const 3))) 10\"\ntext \\<open> 10 + 10 + 3 = 23, which is exactly the output. Wow. think I got it. \\<close>\n\nfun evalp :: \"int list \\<Rightarrow> int \\<Rightarrow> int\" where\n\"evalp [] x = 0\" |\n\"evalp (n # xs) x = n + evalp xs x * x\"\n\nvalue \"evalp [4::int,2] 0\"\nvalue \"evalp [4::int,2] 1\"\nvalue \"evalp [4::int,2] 2\"\n\ntext \\<open>\nThe above definition is based on the fact that we can put the Var (namely x) in evidence.\n\\<close>\n\nfun coeffs :: \"exp \\<Rightarrow> int list\" where\n\"coeffs Var = [0,1]\"|\n\"coeffs (Const n) = [n]\"|\n\"coeffs (Add a b) = (coeffs a) @ (coeffs b)\"|\n\"coeffs (Mult a b) = coeffs a\"\n\nvalue \"evalp (coeffs (Add (Const (4)) (Mult (Const (2)) Var))) 0\"\nvalue \"evalp (coeffs (Add (Const (4)) (Mult (Const (2)) Var))) 1\"\nvalue \"evalp (coeffs (Add (Const (4)) (Mult (Const (2)) Var))) 2\"\n\nvalue \"eval (Add (Const (4)) (Mult (Const (2)) Var)) 0\"\nvalue \"eval (Add (Const (4)) (Mult (Const (2)) Var)) 1\"\nvalue \"eval (Add (Const (4)) (Mult (Const (2)) Var)) 2\"\n\ntext \\<open>\nIt seems to work fine when the expression is indeed a linear polynomial in it's most compact form.\nBut it's not working when it's not... For example x + x is returning [1,1] \nand the correct output is [2]\n \\<close>\n\n\ntheorem voila : \"evalp (coeffs e) x = eval e x\"\n  apply(induction e arbitrary:x)\n  apply(auto)\n\n\ntext \\<open> End of exercise 2.11 \\<close>\nend\n", "meta": {"author": "reisfmb", "repo": "Learning-Isabelle", "sha": "c44d332d59d722bed5cc35a00de2b8e84b5b6e16", "save_path": "github-repos/isabelle/reisfmb-Learning-Isabelle", "path": "github-repos/isabelle/reisfmb-Learning-Isabelle/Learning-Isabelle-c44d332d59d722bed5cc35a00de2b8e84b5b6e16/Chap2/Exercises.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8652240686758842, "lm_q2_score": 0.8670357460591569, "lm_q1q2_score": 0.7501801958927344}}
{"text": "theory CombinatoricsBackground\n  imports Main \"$ISABELLE_HOME/src/HOL/Library/FSet\" \"$ISABELLE_HOME/src/HOL/Orderings\"\nbegin\n  \n  \n  (* This file proves general facts about Finite Sets, Trees, Forests, and Languages *)\n  \n  (* --------------------------------------------------------- *)\n  (* ------- MAXIMA OF FINITE SETS OF NATURAL NUMBERS -------- *)\n  (* --------------------------------------------------------- *)\n  \n    (* immediate generalization of finite_maxlen from List.thy *)\n  lemma finite_maxvalue:\n  fixes M\n  fixes \\<ff> :: \"'a \\<Rightarrow> nat\"\n  shows  \"finite (M::'a set) ==> EX n. ALL s:M. \\<ff> s < n\"\nproof (induct rule: finite.induct)\n  case emptyI show ?case by simp\nnext\n  case (insertI M xs)\n  then obtain n where \"\\<forall>s\\<in>M. \\<ff> s < n\" by blast\n  hence \"ALL s:insert xs M. \\<ff> s < max n (\\<ff> xs) + 1\" by auto\n  thus ?case ..\nqed\n  \n  \nlemma finite_maxvalue2:\n  fixes M\n  fixes \\<ff> :: \"'a \\<Rightarrow> nat\"\n  shows  \"finite (M::'a set) ==> EX n. ALL s:M. \\<ff> s \\<le> n\"\nproof (induct rule: finite.induct)\n  case emptyI show ?case by simp\nnext\n  case (insertI M xs)\n  then obtain n where \"\\<forall>s\\<in>M. \\<ff> s \\<le> n\" by blast\n  hence \"ALL s:insert xs M. \\<ff> s \\<le> max n (\\<ff> xs) \" by auto\n  thus ?case ..\nqed\n  \ndefinition maxFset :: \"nat fset \\<Rightarrow> nat\" where \"maxFset s = (SOME x. ((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> x)) \\<and> (s = {||} \\<longrightarrow> x=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> (x |\\<in>| s))))\"\n  \n  \nlemma finite_maxvalue3:\n  fixes M\n  fixes \\<ff> :: \"'a \\<Rightarrow> nat\"\n  shows  \"finite (M::'a set) ==> M \\<noteq> {} \\<Longrightarrow>  EX n. ALL s:M. \\<ff> s \\<le> n \\<and> n \\<in> (\\<ff> ` M)\"\nproof (induct rule: finite.induct)\n  case emptyI show ?case by simp\nnext\n  case (insertI M xs)\n  then obtain n where b1 : \"\\<forall>s\\<in>M. ((\\<ff> s \\<le> n) \\<and> n \\<in> (\\<ff> ` M))\" by blast\n  hence b20 : \"ALL s:insert xs M. \\<ff> s \\<le> max n (\\<ff> xs)\" by auto\n  have b2 : \"(\\<ff> ` (insert xs M)) = insert (\\<ff> xs) (\\<ff> ` M)\" by simp\n      \n  show \"\\<exists>n. \\<forall>s\\<in>insert xs M. \\<ff> s \\<le> n \\<and> n \\<in> \\<ff> ` insert xs M\"\n  proof (rule disjE)\n    show \"M = {} \\<or> M \\<noteq> {}\" by auto\n    show \"M = {} \\<Longrightarrow> \\<exists>n. \\<forall>s\\<in>insert xs M. \\<ff> s \\<le> n \\<and> n \\<in> \\<ff> ` insert xs M\" by auto\n        \n    show \"M \\<noteq> {} \\<Longrightarrow> \\<exists>n. \\<forall>s\\<in>insert xs M. \\<ff> s \\<le> n \\<and> n \\<in> \\<ff> ` insert xs M\"\n    proof -\n      \n      have b10 : \"M \\<noteq> {} \\<Longrightarrow> \\<exists> element . element \\<in> M\"  by auto\n      from b1 b10 have b3 : \"M \\<noteq> {} \\<Longrightarrow> n \\<in> (\\<ff> ` M)\"        by blast \n      from b2  b3 have b21 : \"M \\<noteq> {} \\<Longrightarrow> max n (\\<ff> xs) \\<in> (\\<ff> ` insert xs M)\"      by (simp add: max_def)  \n      from b20 b21   have \"M \\<noteq> {} \\<Longrightarrow> \\<forall>s\\<in>insert xs M. \\<ff> s \\<le> (max n (\\<ff> xs)) \\<and> (max n (\\<ff> xs)) \\<in> \\<ff> ` insert xs M\" by simp\n      then show \"M \\<noteq> {} \\<Longrightarrow> \\<exists>n. \\<forall>s\\<in>insert xs M. \\<ff> s \\<le> n \\<and> n \\<in> \\<ff> ` insert xs M\" by blast\n    qed\n      \n  qed\nqed\n  \n  \nlemma finiteMaxExists :\n  shows \"\\<And> t . t |\\<in>| s \\<Longrightarrow> t \\<le> (maxFset s)\"\n    and \"(s = {||} \\<Longrightarrow> (maxFset s)=0)\"\n    and \"(s \\<noteq> {||} \\<Longrightarrow> ((maxFset s) |\\<in>| s))\"\nproof (rule disjE)\n  show \"s = {||} \\<or> (s \\<noteq> {||}) \" by auto\n  have h1 : \"finite (fset s)\" by auto\n  {\n    assume k1 : \"(s \\<noteq> {||}) \" \n    then obtain max where \"\\<And> t . (t |\\<in>| s \\<Longrightarrow> (t \\<le> max \\<and> max |\\<in>| s))\" using h1 finite_maxvalue3  notin_fset  finite_nat_set_iff_bounded less_or_eq_imp_le    by (metis bot_fset.rep_eq fset_inject infinite_growing leI) \n    then have \"((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> max)) \\<and> (s = {||} \\<longrightarrow> max=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> (max |\\<in>| s)))\" using k1 by blast\n    then have n4775 : \"\\<exists> max. ((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> max)) \\<and> (s = {||} \\<longrightarrow> max=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> (max |\\<in>| s)))\" by auto\n    def P == \"\\<lambda> max. ((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> max)) \\<and> (s = {||} \\<longrightarrow> max=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> (max |\\<in>| s)))\"\n    from n4775 P_def have \"\\<exists> max. P max\" by auto\n    then have j90 : \"P (SOME x. P x)\"       by (simp add: someI_ex) \n    from maxFset_def P_def    have \"(SOME x. P x) = maxFset s\" by auto\n    then have q1 : \"((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> (maxFset s))) \\<and> (s = {||} \\<longrightarrow> (maxFset s)=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> ((maxFset s) |\\<in>| s)))\" using j90 P_def by auto\n    then show \"\\<And>t. t |\\<in>| s \\<Longrightarrow> s \\<noteq> {||} \\<Longrightarrow> t \\<le> maxFset s\" by blast\n    show  \"maxFset s |\\<in>| s\" using  k1 q1 by auto\n  }\n  have \"(s = {||}) \\<Longrightarrow> ((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> 0)) \\<and> (s = {||} \\<longrightarrow> 0=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> (0 |\\<in>| s)))\" by blast\n  then have j1 : \"(s = {||}) \\<Longrightarrow> ((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> (maxFset s))) \\<and> (s = {||} \\<longrightarrow> (maxFset s)=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> ((maxFset s) |\\<in>| s)))\" using someI_ex    using maxFset_def by auto\n  then show  \"s = {||} \\<Longrightarrow> (\\<And> t . t |\\<in>| s \\<Longrightarrow> t \\<le> (maxFset s))\" using finite_maxvalue2 maxFset_def notin_fset    by (smt someI_ex)\n  from j1 show \"s = {||} \\<Longrightarrow> (maxFset s) = 0\" by auto\nqed\n  \n  (* --------------------------------------------------------- *)\n  (*  UNIONS OF FINITE SETS OF SETS  *)\n  (* --------------------------------------------------------- *)\n  \n  \nlemma  ffUnionLemma :\n  fixes a\n  fixes b\n  assumes \"a |\\<in>| \\<Union>| b \"\n  obtains c where \"c |\\<in>| b\" and \"a |\\<in>| c\"\n  using assms by auto\n    \n  \n  (* --------------------------------------------------------- *)\n  (*  STATES, ALPHABETS, TREES  *)\n  (* --------------------------------------------------------- *)\n  \n  \ndatatype ot = \\<aa>\\<^sub>1 | \\<aa>\\<^sub>2\ndatatype tv = PLACEHOLDER\n    \ndefinition numberOfLettersAndStates :: \"nat\" where \"numberOfLettersAndStates = (SOME x. x> 1)\"\ntypedef abc = \"{n . n \\<le> numberOfLettersAndStates}\"  by auto\ntypedef stt = \"{n . n \\<le> numberOfLettersAndStates}\"  by auto\n    (*datatype abc = A \"abcIndex\"*)\n(*datatype stt = B \"stateIndex\"*)\n  \n  \n  \n(*definition asdf :: \"nat\" where \"asdf = (GREATEST x.(x=x))\"*)\n  \ndatatype 'l tree = NODE \"'l\" \"'l tree fset\"\n  \n  \n  \n  \nfun childrenSet where \"childrenSet (NODE symb2 set2) = set2\"\nfun root where \"root (NODE symb2 set2) = symb2\"\n  \n  \n  (* --------------------------------------------------------- *)\n  (*  NODES IN TREES, AND SEQUENCES OF NODES  *)\n  (* --------------------------------------------------------- *)\n  \ndatatype 'l contxt = cNODE \"'l\" \"'l contxt\" \"'l tree fset\" | PLACEHOLDER \n\nprimrec insertIntoContext where\n  \"(insertIntoContext tr (cNODE symb contextChild children)) = (NODE symb (finsert (insertIntoContext tr contextChild) children))\" |\n  \"insertIntoContext tr PLACEHOLDER = tr\"\n  \nprimrec insertContextIntoContext where\n  \"(insertContextIntoContext contxt (cNODE symb contextChild children)) = (cNODE symb  (insertContextIntoContext contxt contextChild)  children)\" |\n  \"insertContextIntoContext contxt PLACEHOLDER = contxt\"\n  \nrecord 'L node =\n  up :: \"'L contxt\"\n  down :: \"'L tree\"\n  \n  \ndefinition isNodeIn where\n  \"isNodeIn n tr = ((insertIntoContext (down n) (up n))  = tr)\"\ndefinition isRootNode where\n  \"isRootNode n = ((up n) = PLACEHOLDER)\"\ndefinition isLeafNode where\n  \"isLeafNode n = (childrenSet (down n) = {||})\"\ndefinition labelOfNode where\n  \"labelOfNode n = (root (down n))\"\n  \n  \nlemma nodeExists:\n  shows \"\\<exists> node . down node = tr\"\n  by (meson select_convs(2))\n    \n    \ndefinition turnIntoContextByRemovingChild where\n  \"turnIntoContextByRemovingChild tr child = (cNODE (root tr) PLACEHOLDER    ( (childrenSet tr) |-| {|child|}   )  )\"\n  \ndefinition immediatelyDominates :: \"'l node \\<Rightarrow> 'l node \\<Rightarrow> bool\" where\n  \"immediatelyDominates n1 n2 = (   ((down n2) |\\<in>| (childrenSet (down n1))) \n                                  (*\\<and> ((up n2) = insertContextIntoContext ( turnIntoContextByRemovingChild (down n1) (down n2)    ) (up n1))*)\n                                )\"\n  \n  (* the empty path is not a good path. *)\n  (* \\<Pi> do not need to go up to a leaf *)\ninductive_set isAPath :: \"'l node list set\" where\n  \"[node] \\<in> isAPath\" |\n  \"path \\<in> isAPath \\<Longrightarrow> (\\<exists>e1.\\<exists>tail.(path = (e1#tail)) \\<and> immediatelyDominates e2 e1) \\<Longrightarrow> e2#path \\<in> isAPath\"\n  \n  \n  (* the empty path is not a good path *)\ndefinition pathsInTree where\n  \"pathsInTree tr = {p . (isAPathp p) \\<and> (( \\<exists>e1.\\<exists>tail.(p = (e1#tail) \\<and> down e1 = tr)))}\" (* \\<and> (isNodeIn e1 tr) \\<and> (isRootNode e1)        )      ))}\"*)\n  \nlemma noEmptyPaths:\n  shows \"[] \\<notin> isAPath\"\n  using isAPath.cases by blast\n    \nlemma noEmptyPathsInTree:\n  shows \"[] \\<notin> pathsInTree tr\"\n  using noEmptyPaths pathsInTree_def by blast\n    \n    \n    \nlemma theSingletonPathExists :\n  fixes tree :: \"abc tree\"\n  shows \"\\<exists>path. \\<exists> node. (isAPathp path) \\<and> path = [node] \\<and> down node = tree \\<and> path \\<in> pathsInTree tree\"\nproof -\n  from nodeExists obtain node :: \"abc node\" where a1 : \"down node = tree\" by auto\n  from a1 isAPathp.simps pathsInTree_def have \"(isAPathp [node]) \\<and> [node] = [node] \\<and> down node = tree \\<and> [node] \\<in> pathsInTree tree\" by blast\n  then show \"\\<exists>path. \\<exists>node. isAPathp path \\<and> path = [node] \\<and> down node = tree \\<and> path \\<in> pathsInTree tree\" by blast\nqed\n  \n  (*================================================*)\n  \n  (*http://stackoverflow.com/questions/28633353/converting-a-set-to-a-list-in-isabelle*)\ndefinition set_to_list :: \"'a set \\<Rightarrow> 'a list\"\n  where \"set_to_list s = (SOME l. set l = s)\"\nlemma  set_set_to_list:\n  \"finite s \\<Longrightarrow> set (set_to_list s) = s\"\n  unfolding set_to_list_def by (metis (mono_tags) finite_list some_eq_ex)\ndefinition set_to_fset :: \"'a set \\<Rightarrow> 'a fset\"\n  where \"set_to_fset s = Abs_fset s\"\n    \n    \ndefinition emptyTree :: \"'L tree\" where\n  \"emptyTree = (NODE (SOME x.(x=x)) fempty )\"\n  \n  (* --------------------------------------------------------- *)\n  (*  TREE AUTOMATA AND RECOGNITION OF TREE LANGUAGES  *)\n  (* --------------------------------------------------------- *)\n  \nsubsection \"Tree Automata\"\n  \nrecord ('Q,'L) rule =\n  states :: \"'Q fset\"\n  symbol :: \"'L\"\n    \n  -- \"Finite Tree \\<A>omata\"\nrecord ('Q,'L) tree_automaton =\n  transition :: \"'Q fset \\<Rightarrow> 'L \\<Rightarrow> 'Q\"\n  rule_set :: \"('Q,'L) rule fset\"\n  \ndefinition state_set :: \"('Q,'L) tree_automaton \\<Rightarrow> 'Q fset\" where \"state_set automaton = ((Abs_fset UNIV) :: ('Q fset))\"\n  \n   \ndefinition is_tree_automaton :: \"('Q,'L) tree_automaton \\<Rightarrow> bool\" where\n  \"is_tree_automaton automaton = (\\<forall> s :: 'Q fset . (\\<forall> x :: 'L . ((transition automaton) s x) |\\<in>| (state_set automaton)))\"\n  \n  (*definition is_finite_tree_automaton :: \"('Q,'L) tree_automaton \\<Rightarrow> bool\" where\n   \"is_finite_tree_automaton automaton = ((is_tree_automaton automaton))\"\n   (*\"is_finite_tree_automaton automaton = ((is_tree_automaton automaton) \\<and> (finite (state_set automaton)))\"*)\n*)\n  \nprimrec evaluation where\n  \"(evaluation automaton) (NODE symbol1 fset2) = (((transition automaton) (fimage (evaluation automaton) fset2)) symbol1)\"\n  \ndefinition\n  preImage :: \"('a => 'b) => 'b set => 'a set\" where\n  \"preImage \\<ff> y = { x . \\<ff> x \\<in> y}\"\n  \nfun recognized_tree :: \"('Q,'L) tree_automaton \\<Rightarrow> 'Q set \\<Rightarrow> 'L tree set \\<Rightarrow> bool\" where\n  \"recognized_tree automaton stateSet language = (preImage (evaluation automaton) stateSet = language)\"  \n  \n  \nfun regular_tree :: \"'L tree set \\<Rightarrow> bool\" where\n  \"regular_tree language = (\\<exists> automaton :: (nat,'L) tree_automaton . (is_tree_automaton automaton) \\<and> (\\<exists> stateSet . (recognized_tree automaton stateSet language)))\"   \n  \n  \ndefinition prefixLetter :: \"abc \\<Rightarrow> abc list set \\<Rightarrow> abc list set\" where\n  \"prefixLetter \\<alpha> I = (\\<lambda>x.(\\<alpha>#x)) ` I\"\n  \nabbreviation prefixLetterAbb :: \"abc \\<Rightarrow> abc list set \\<Rightarrow> abc list set\" (infixr \"\\<bullet>\" 80) where \"(x \\<bullet> y) \\<equiv> prefixLetter x y\"\n  \nabbreviation fstAbb :: \"'a \\<times> 'b \\<Rightarrow> 'a\" (\"\\<pi>\\<^sup>1\" 1000) where \"\\<pi>\\<^sup>1 x \\<equiv> fst x\"\nabbreviation sndAbb :: \"'a \\<times> 'b \\<Rightarrow> 'b\" (\"\\<pi>\\<^sup>2\" 1000) where \"\\<pi>\\<^sup>2 x \\<equiv> snd x\"\n  \n(*lemma hallo :\n  assumes \"l1 \\<subseteq> l2\"\n  assumes \"\\<And>x. \\<pi>\\<^sup>1 x = y\"\n  shows \"\\<alpha> \\<bullet> l1 \\<subseteq> \\<alpha> \\<bullet> l2\"\n  using assms prefixLetter_def by auto*)\n    \n  \n  \n  (* --------------------------------------------------------- *)\n  (*  FACTORS OF FOREST LANGUAGES  *)\n  (* --------------------------------------------------------- *)\n    \nlemma prefixLetterMono :\n  assumes \"l1 \\<subseteq> l2\"\n  shows \"\\<alpha> \\<bullet> l1 \\<subseteq> \\<alpha> \\<bullet> l2\"\n  using assms prefixLetter_def by auto\n    \ndefinition factorByRootSymbol :: \"abc \\<Rightarrow> abc tree set \\<Rightarrow> abc tree set\" where \n  \"factorByRootSymbol symb language = {t. (\\<exists>tree \\<in> language . (root tree = symb \\<and> t |\\<in>| childrenSet tree))}\"\n  \ndefinition factorByRootSymbolF :: \"abc \\<Rightarrow> abc tree fset \\<Rightarrow> abc tree fset\" where \n  \"factorByRootSymbolF symb language = set_to_fset {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}\"\n  \nabbreviation factorByRootSymbolFAbb :: \"abc \\<Rightarrow> abc tree fset \\<Rightarrow> abc tree fset\" (infixr \"\\<diamondop>\" 80) where \"(x \\<diamondop> y) \\<equiv> factorByRootSymbolF x y\"\n  \nabbreviation factorByRootSymbolAbb :: \"abc \\<Rightarrow> abc tree set \\<Rightarrow> abc tree set\" (infixr \"\\<diamondop>\\<tau>\\<lambda>\" 80) where \"(x \\<diamondop>\\<tau>\\<lambda> y) \\<equiv> factorByRootSymbol x y\"\n  \n  \n  (* --------------------------------------------------------- *)\n  (*  TREES AND PATHSETS  *)\n  (* --------------------------------------------------------- *)\nsection \"Trees\"\n  \nprimrec height :: \"abc tree \\<Rightarrow> nat\" where\n  \"height (NODE symb2 set2) = 1 + (maxFset (fimage height set2))\" \n  \n  (*lemma is_measure_size [measure_function]: \"is_measure height\"\n  by (simp add: is_measure_trivial)*)\n  \n  \n  \ndefinition topRule :: \"('Q,'L) tree_automaton \\<Rightarrow> 'L tree \\<Rightarrow> ('Q,'L) rule\" where\n  \"topRule automaton tr = rule.make (fimage (evaluation automaton) (childrenSet tr)) (root tr)\"\n  \n  \n  \nprimrec \\<Pi> :: \"'L tree \\<Rightarrow> 'L list fset\" where\n  \"\\<Pi> (NODE symb2 set2) = fimage (append [symb2]) ((\\<Union>| (fimage \\<Pi> set2)) |\\<union>|  (finsert [] {||})) \"\n  \nlemma pathAlternateDef :\n    \"\\<Pi> (NODE symb2 set2) = fimage (\\<lambda> tail.(symb2#tail)) ((\\<Union>| (fimage \\<Pi> set2)) |\\<union>|  (finsert [] {||})) \"\n  using \\<Pi>.simps by auto\n    \n  \nlemma noEmptyPathsInPi :\n  assumes \"a |\\<in>| \\<Pi> tr\"\n  obtains y where \"a = (root tr)#y\"\n  using pathAlternateDef    by (metis assms childrenSet.elims fimageE root.simps)\n    \n  \nlemma rootIsPath :\n  \"[symb] |\\<in>| \\<Pi> (NODE symb set2)\"\nproof -\n  have \"[] |\\<in>| ((\\<Union>| (fimage \\<Pi> set2)) |\\<union>|  (finsert [] {||}))\" by blast\n  then have \"[symb]  |\\<in>| fimage (append [symb]) ((\\<Union>| (fimage \\<Pi> set2)) |\\<union>|  (finsert [] {||})) \" by blast\n  then show ?thesis using \\<Pi>_def by simp\nqed\n  \n  lemma rootIsPath2 :\n  \"[root tree] |\\<in>| \\<Pi> tree\"\nusing rootIsPath root.simps   by (metis tree.exhaust) \n  \n    \n  \n  \nlemma pathsEq : \"\\<Pi> (NODE symb2 set2) = fimage (\\<lambda> x. symb2#x) (\\<Union>| (fimage \\<Pi> set2) |\\<union>|  (finsert [] {||}))\" using \\<Pi>.simps by auto\n    \nlemma paths_def : \"tail |\\<in>| \\<Pi> child \\<Longrightarrow> child |\\<in>| set2 \\<Longrightarrow> \\<alpha>#tail |\\<in>| \\<Pi> (NODE \\<alpha> set2)\" using pathsEq  by (simp add: rev_fBexI) \n    \n    (*termination\nproof -\nfix z :: \"'L tree\"\nfix set2 :: \"'L tree fset\"\nfix symb2 :: \"'L\"\nassume 1 : \"z \\<in> fset set2\"\nfrom 1 children_smaller_depth have \"Suc (height z) \\<le> ( height (NODE symb2 set2))\" by blast\nfrom this have \"height z < Suc (ffold max 0 (height |`| set2))\" by blast*)\n    (* \\<And> set2 z. z \\<in> fset set2 \\<Longrightarrow> height z < Suc (ffold max 0 (height |`| set2)*)\n    \n    \ndefinition pathsInForest :: \"'L tree fset \\<Rightarrow> 'L list fset\" where\n  \"pathsInForest forest = \\<Union>| (\\<Pi> |`| forest)\"\n  \nlemma pathsTreeForest :\n  fixes p\n  shows \"(p |\\<in>| pathsInForest f) = (\\<exists> tr. (tr |\\<in>| f \\<and> p |\\<in>| \\<Pi> tr))\"\nproof -\n  have \"(p |\\<in>|  \\<Union>| (\\<Pi> |`| f)) = (\\<exists> trset . (p |\\<in>| trset \\<and>  trset |\\<in>| (\\<Pi> |`| f)))\" by auto\n  then show ?thesis        using pathsInForest_def by fastforce\nqed\n  \n  \n  \nabbreviation deltaF :: \"abc tree fset \\<Rightarrow> abc list fset\" (\"\\<delta>\\<^sub>\\<phi>\") where \"\\<delta>\\<^sub>\\<phi> x \\<equiv> pathsInForest x\"\nabbreviation deltaT :: \"abc tree \\<Rightarrow> abc list fset\" (\"\\<delta>\\<^sub>\\<tau>\") where \"\\<delta>\\<^sub>\\<tau> x \\<equiv> \\<Pi> x\"\nabbreviation deltaFL :: \"abc tree fset set \\<Rightarrow> abc list fset set\" (\"\\<delta>\\<^sub>\\<phi>\\<^sub>\\<lambda>\") where \"\\<delta>\\<^sub>\\<phi>\\<^sub>\\<lambda> x \\<equiv> \\<delta>\\<^sub>\\<phi> ` x\"\nabbreviation deltaTL :: \"abc tree set \\<Rightarrow> abc list fset set\" (\"\\<delta>\\<^sub>\\<tau>\\<^sub>\\<lambda>\") where \"\\<delta>\\<^sub>\\<tau>\\<^sub>\\<lambda> x \\<equiv> \\<delta>\\<^sub>\\<tau> ` x\"\n  \ndefinition pathsForForestLanguage :: \"'L tree fset set \\<Rightarrow> 'L list set\" where\n  \"pathsForForestLanguage language = {p . (\\<exists> t \\<in> language . p |\\<in>| pathsInForest t)}\"\n  \ndefinition pathsForTreeLanguage :: \"'L tree set \\<Rightarrow> 'L list set\" where\n  \"pathsForTreeLanguage language = {p . (\\<exists> t \\<in> language . p |\\<in>| \\<Pi> t)}\" (* ((Union :: ('L list fset set \\<Rightarrow> 'L list set)) (image \\<Pi> language))\"*)\n  \nabbreviation \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>\" :: \"'L tree fset \\<Rightarrow> 'L list fset\" (\"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>\") where \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> \\<equiv> pathsInForest\"\n  \nabbreviation \"\\<Pi>\\<^sub>\\<phi>\" :: \"'L tree fset set \\<Rightarrow> 'L list set\" (\"\\<Pi>\\<^sub>\\<phi>\") where \"\\<Pi>\\<^sub>\\<phi> \\<equiv> pathsForForestLanguage\"\nabbreviation \"\\<Pi>\\<^sub>\\<tau>\" :: \"'L tree set \\<Rightarrow> 'L list set\" (\"\\<Pi>\\<^sub>\\<tau>\") where \"\\<Pi>\\<^sub>\\<tau> \\<equiv> pathsForTreeLanguage\"\n  \nabbreviation \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F\" :: \"'L tree fset \\<Rightarrow> 'L list set\" (\"\\<Pi>\\<^sub>\\<tau>\\<^sub>F\") where \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F x \\<equiv> pathsForTreeLanguage (fset x)\"  \n  \nabbreviation \"\\<Pi>\\<^sub>\\<delta>\" :: \"'L list fset set \\<Rightarrow> 'L list set\" (\"\\<Pi>\\<^sub>\\<delta>\") where \"\\<Pi>\\<^sub>\\<delta> x \\<equiv> \\<Union> (fset ` x)\"\n  \n  \n  \nabbreviation \"bounded\"  :: \"nat \\<Rightarrow> abc tree fset\" where \"bounded n \\<equiv> Abs_fset {f . height f \\<le> n}\"\n  \nabbreviation \"boundedForests\"  :: \"nat \\<Rightarrow> abc tree fset fset\" where \"boundedForests n \\<equiv> Abs_fset {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\"\n  \n  \n  (* For each n, there are only finitely many trees of height \\<le> n *)\nlemma restrictionIsFinite:\n  fixes n\n  shows \"fset (bounded n) = {(f :: abc tree) . height f \\<le> n}\"\nproof (induct n)\n  case 0\n  have \"\\<And>f. \\<not> (height f \\<le> 0)\" using height.simps        by (metis add_eq_0_iff_both_eq_0 childrenSet.cases le_zero_eq not_one_le_zero) \n  then have \"{f . height f \\<le> 0} = {}\"          by blast \n  then show ?case by (metis (no_types)  bot_fset.rep_eq bot_fset_def)\nnext\n  case (Suc n)\n  assume b1 : \"fset (bounded n) = {f. height f \\<le> n}\"\n  def smaller_set == \"{(f :: abc tree). height f \\<le> n}\"\n  then have n76 : \"fset (bounded n) = smaller_set\" using b1 by simp\n  have w1 : \"finite {f. height f = Suc n}\"\n  proof -\n    have \"\\<And>f . (height f = Suc n \\<Longrightarrow> (f |\\<in>| (\\<Union>| ((\\<lambda> alpha. ((\\<lambda> x.(NODE alpha x)) |`| fPow (bounded n))) |`| (Abs_fset (UNIV :: abc set))))))\"\n    proof -\n      fix f :: \"abc tree\"\n      assume k76789 : \"height f = Suc n\"\n      have \"((height f = Suc n) = (Suc n = 1 + (maxFset (fimage height (childrenSet f)))))\" using height.simps           by (metis childrenSet.elims) \n      also have u1 : \"(... = (n = (maxFset (fimage height (childrenSet f)))))\"           by auto\n      have u5678 : \"Rep_abc ` (UNIV :: abc set) = {n . n \\<le> numberOfLettersAndStates}\"            using type_definition.Rep_range type_definition_abc by blast\n      have u5678b : \"finite {n . n \\<le> numberOfLettersAndStates}\"           by simp\n      from u5678 u5678b have \"finite (Rep_abc ` (UNIV :: abc set))\"            by simp\n      then have n5456 : \"finite ( (UNIV :: abc set))\"                by (metis (full_types) Rep_abc_inverse UNIV_I ex_new_if_finite finite_imageI image_eqI)\n      have n767890 : \"(height f = Suc n \\<Longrightarrow> ((childrenSet f) |\\<in>| fPow (bounded n)))\"\n      proof \n        assume \"(height f = Suc n)\"\n        then have n1 : \"(n = (maxFset (fimage height (childrenSet f))))\" using u1 calculation by auto \n        show \"childrenSet f |\\<subseteq>| (bounded n)\"\n        proof \n          fix child\n          assume m1 : \"child |\\<in>| childrenSet f\"\n          from n1 m1 have \"height child \\<le> n\"                     by (simp add: finiteMaxExists)\n          then have \"child \\<in> {f . height f \\<le> n}\" using m1 by blast\n          then have \"child \\<in> smaller_set\" using smaller_set_def by simp\n          then have \"child \\<in> (fset (bounded n))\" using b1 n76 by simp\n          then show \"child |\\<in>| ((bounded n))\" using notin_fset by metis\n        qed\n      qed\n      have n56568 : \"(height f = Suc n \\<Longrightarrow> (f |\\<in>| ((\\<lambda> x.(NODE (root f) x)) |`| fPow (bounded n))))\"\n      proof\n        show \"f = NODE (root f) (childrenSet f)\" using childrenSet.simps childrenSet.elims            by (metis root.simps) \n        show \"height f = Suc n  \\<Longrightarrow> childrenSet f |\\<in>| fPow (bounded n)\"   using n767890 by auto\n      qed\n      show \"f |\\<in>| (\\<Union>| ((\\<lambda> alpha. ((\\<lambda> x.(NODE alpha x)) |`| fPow (bounded n))) |`| (Abs_fset (UNIV :: abc set))))\"\n      proof -\n        from n56568 k76789 obtain alpha where b7 : \"(f |\\<in>| ((\\<lambda> x.(NODE alpha x)) |`| fPow (bounded n)))\" by auto\n        have b8 : \"alpha |\\<in>| (Abs_fset (UNIV :: abc set))\" using n5456                 by (metis UNIV_I fset_inverse fset_to_fset notin_fset) \n        from b7 b8 show \"f |\\<in>| (\\<Union>| ((\\<lambda> alpha. ((\\<lambda> x.(NODE alpha x)) |`| fPow (bounded n))) |`| (Abs_fset (UNIV :: abc set))))\" by auto\n      qed\n    qed\n    then have \"{f. height f = Suc n} \\<subseteq> (fset (\\<Union>| ((\\<lambda> alpha. ((\\<lambda> x.(NODE alpha x)) |`| fPow (bounded n))) |`| (Abs_fset (UNIV :: abc set)))))\"               by (metis (mono_tags, lifting) mem_Collect_eq notin_fset subsetI)\n    then show \"finite {f. height f = Suc n}\"                  using finite_fset infinite_super by blast\n  qed\n  have w2 : \"{f. height f \\<le> Suc n} = {f. height f \\<le> n} \\<union> {f. height f = Suc n}\"      by auto\n  from b1 have w3 : \"finite {f. height f \\<le> n}\"      by (metis finite_fset) \n  from w1 w2 w3 have \"finite {f. height (f :: abc tree) \\<le> Suc n}\" by auto\n  then show \"fset (bounded (Suc n)) = {f. height f \\<le> Suc n}\"      by (simp add: Abs_fset_inverse) \nqed\n  \n  \n  \nlemma restrictionIsFinite2:\n  fixes n\n  shows \"\\<And> p . (p |\\<in>| (bounded n)) = (height p \\<le> n)\"\n  using restrictionIsFinite  by (metis (full_types) mem_Collect_eq notin_fset)\n    \n    \n    \nlemma restrictionIsFiniteForests:\n  fixes n\n  shows \"fset (boundedForests n) = {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\"\nproof -\n  have a1 : \"\\<And> p. ((p |\\<in>| fPow (bounded n)) = (\\<forall> t . t |\\<in>| p \\<longrightarrow> height t \\<le> n))\" using restrictionIsFinite2    by blast \n  then have a10 : \"(fset ( fPow (bounded n))) = {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\" \n  proof -\n    from a1 have \"\\<And>p . ((p \\<in> (fset ( fPow (bounded n)))) =  (\\<forall> t . t |\\<in>| p \\<longrightarrow> height t \\<le> n))\" using notin_fset by metis\n    then have \"\\<And>p . ((p \\<in> (fset ( fPow (bounded n)))) = (p \\<in> {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}))\" by blast\n    then show \"(fset ( fPow (bounded n))) = {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\" using set_eqI by blast\n  qed\n  then    have \"Abs_fset (fset ( fPow (bounded n))) = Abs_fset {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\"  by (simp add: \\<open>fset (fPow (bounded n)) = {f. \\<forall>t. t |\\<in>| f \\<longrightarrow> height t \\<le> n}\\<close>) \n  then have \"( ( fPow (bounded n))) = Abs_fset {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\"  by (simp add: fset_inverse)  \n  then have \"fset (Abs_fset {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}) = {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\" using a10    by (simp add: \\<open>fPow (bounded n) = boundedForests n\\<close>) \n  then show \"fset (boundedForests n) = {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\" by auto\nqed\n  \n  \ndefinition Z :: \"nat \\<Rightarrow> abc tree set \\<Rightarrow> abc tree set\" where\n  \"Z n L = { \\<ff> . ((\\<ff> \\<in> L) \\<and> (height \\<ff> \\<le> n))}\"\n  \ndefinition \\<Z>\\<^sub>\\<tau> :: \"nat \\<Rightarrow> abc tree set \\<Rightarrow> abc tree fset\" where\n  \"\\<Z>\\<^sub>\\<tau> n L = inf_fset2 (bounded n) L\" (*(SOME x. fset x = { \\<ff> . ((\\<ff> \\<in> L) \\<and> (height \\<ff> \\<le> n))})\"   *)\n  \nlemma \\<Z>\\<tau>_lemma : \"fset (\\<Z>\\<^sub>\\<tau> nm l1) = Z nm l1\" using restrictionIsFinite inf_fset2_def\n  by (metis Collect_conj_eq Collect_mem_eq Int_commute Z_def \\<Z>\\<^sub>\\<tau>_def inf_fset2.rep_eq) \n    \nlemma \\<Z>\\<tau>_subset : \"fset (\\<Z>\\<^sub>\\<tau> n l) \\<subseteq> l\" using \\<Z>\\<tau>_lemma\n  using \\<Z>\\<^sub>\\<tau>_def inf_fset2.rep_eq by fastforce\n    \ndefinition \\<Z>\\<^sub>\\<delta> :: \"nat \\<Rightarrow> abc list fset set \\<Rightarrow> abc list fset fset\" where\n  \"\\<Z>\\<^sub>\\<delta> n L = \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> |`| (inf_fset2 (boundedForests n) {f . (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> f \\<in> L)} )\"\n  \n  \ndefinition \\<Z>\\<^sub>\\<phi> :: \"nat \\<Rightarrow> abc tree fset set \\<Rightarrow> abc tree fset fset\" where\n  \"\\<Z>\\<^sub>\\<phi> n L = inf_fset2 (boundedForests n) L\" (*(SOME x. fset x = { \\<ff> . ((\\<ff> \\<in> L) \\<and> (\\<forall> t. t|\\<in>| \\<ff> \\<longrightarrow> (height t \\<le> n)))})\"   *)\ndefinition \\<Z>\\<^sub>\\<phi>\\<^sub>F :: \"nat \\<Rightarrow> abc tree fset set \\<Rightarrow> abc tree fset set\" where\n  \"\\<Z>\\<^sub>\\<phi>\\<^sub>F n L = L \\<inter> {f . (\\<forall> t . t |\\<in>| f \\<longrightarrow> height t \\<le> n)}\"  \n  \nlemma \\<Z>\\<^sub>\\<phi>\\<Z>\\<^sub>\\<phi>\\<^sub>Flemma :\n  shows \"\\<Z>\\<^sub>\\<phi>\\<^sub>F n L = fset (\\<Z>\\<^sub>\\<phi> n L)\"\n  by (simp add: restrictionIsFiniteForests Int_commute \\<Z>\\<^sub>\\<phi>\\<^sub>F_def \\<Z>\\<^sub>\\<phi>_def inf_fset2.rep_eq)\n    \n    \nlemma \\<Z>\\<^sub>\\<phi>\\<^sub>F_subset : \"\\<Z>\\<^sub>\\<phi>\\<^sub>F n lang \\<subseteq> lang\" using \\<Z>\\<^sub>\\<phi>\\<^sub>F_def by blast\n    \nlemma aux50 : \"\\<And> x . \\<Pi>\\<^sub>\\<phi> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) = \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))\"\nproof -\n  fix x\n  have \"\\<And>p . p \\<in> \\<Pi>\\<^sub>\\<phi> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) = (p \\<in> {p . (\\<exists> t \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) . p |\\<in>| pathsInForest t)})\" using pathsForForestLanguage_def by auto\n  then have k10 : \"\\<And>p . p \\<in> \\<Pi>\\<^sub>\\<phi> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) = (\\<exists> t \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) . p |\\<in>| pathsInForest t)\" by blast\n  have \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (p \\<in> {p . (\\<exists> t \\<in>  (fset (\\<Union>| (\\<Z>\\<^sub>\\<phi> n x))     )     . p |\\<in>| \\<Pi> t)})\" using pathsForTreeLanguage_def by blast\n  then have \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (\\<exists> t \\<in>  (fset (\\<Union>| (\\<Z>\\<^sub>\\<phi> n x))     )     . p |\\<in>| \\<Pi> t)\" by blast\n  then have \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (\\<exists> t. (t |\\<in>|  ( (\\<Union>| (\\<Z>\\<^sub>\\<phi> n x))     )     \\<and> p |\\<in>| \\<Pi> t))\"        by (meson notin_fset) \n  then have \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (\\<exists> t. (t |\\<in>|  ( (\\<Union>| (inf_fset2 (boundedForests n) x))     )     \\<and> p |\\<in>| \\<Pi> t))\"  using \\<Z>\\<^sub>\\<phi>_def          by (simp add: \\<Z>\\<^sub>\\<phi>_def)\n  then have \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (\\<exists> t. (\\<exists> for . (t |\\<in>| for \\<and> for |\\<in>| (inf_fset2 (boundedForests n) x))     )     \\<and> p |\\<in>| \\<Pi> t)\"    by auto\n  then have a1 : \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (\\<exists> t. (\\<exists> for . (t |\\<in>| for \\<and> for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x))     )     \\<and> p |\\<in>| \\<Pi> t)\" using \\<Z>\\<^sub>\\<phi>\\<Z>\\<^sub>\\<phi>\\<^sub>Flemma        by (smt \\<open>\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Union>| (\\<Z>\\<^sub>\\<phi> n x))) = (\\<exists>t. t |\\<in>| \\<Union>| (\\<Z>\\<^sub>\\<phi> n x) \\<and> p |\\<in>| \\<Pi> t)\\<close> ffUnionI ffUnionLemma notin_fset) \n  from pathsInForest_def   have q5678 : \"\\<And>p t. ((p |\\<in>| pathsInForest t) = (\\<exists> tr. (tr |\\<in>| t   \\<and> p |\\<in>| \\<Pi> tr)))\" by auto\n  then have \"\\<And>p. (\\<exists> t. (\\<exists> for . (t |\\<in>| for \\<and> for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x))     )     \\<and> p |\\<in>| \\<Pi> t) = (\\<exists> t. (\\<exists> for . (t |\\<in>| for \\<and> for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) \\<and> p |\\<in>| pathsInForest for     )))\"    by blast\n  then have i6778 : \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = (\\<exists> t. (\\<exists> for . (t |\\<in>| for \\<and> for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) \\<and> p |\\<in>| pathsInForest for     )))\" using a1 by auto\n  have \"\\<And>p. (\\<exists> t. (\\<exists> for . (t |\\<in>| for \\<and> for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) \\<and> p |\\<in>| pathsInForest for     ))) = ( (\\<exists> for . (for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) \\<and> p |\\<in>| pathsInForest for     )))\" using q5678 by blast\n  then have \"\\<And>p. (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))) = ( (\\<exists> for . (for \\<in> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) \\<and> p |\\<in>| pathsInForest for     )))\" using i6778 by auto\n  then have \"\\<And>p . p \\<in> \\<Pi>\\<^sub>\\<phi> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) = (p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x))))\" using k10 by auto\n  then show \"\\<Pi>\\<^sub>\\<phi> (\\<Z>\\<^sub>\\<phi>\\<^sub>F n x) = \\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| (\\<Z>\\<^sub>\\<phi> n x)))\" by auto\nqed\n  \nsection \"Some basic concepts\"\n  \ndefinition tree_for_rule :: \"('Q,'L) tree_automaton \\<Rightarrow> ('Q,'L) rule \\<Rightarrow> 'L tree \\<Rightarrow> bool\" where\n  \"(tree_for_rule automaton rule1 tree1) = ((root tree1 = symbol rule1) \\<and> ((fimage (((evaluation automaton))) (childrenSet tree1)) = states rule1))\"\n  \ndefinition language_for_rule :: \"('Q, 'L) tree_automaton \\<Rightarrow> ('Q,'L) rule \\<Rightarrow> (('L tree) set)\" where\n  \"language_for_rule automaton rule = {tree . tree_for_rule automaton rule tree}\"\n  \n  (* the empty forest cannot satisfy any rule *)\ndefinition forest_language_for_rule :: \"('Q, 'L) tree_automaton \\<Rightarrow> ('Q,'L) rule \\<Rightarrow> (('L tree fset) set)\" where\n  \"forest_language_for_rule automaton rule = {forest . (\\<forall>tree.(tree|\\<in>|forest \\<longrightarrow>  tree_for_rule automaton rule tree)) \\<and> (\\<exists> tree. tree |\\<in>| forest)}\"\n  \ndefinition language_for_state :: \"('Q, 'L) tree_automaton \\<Rightarrow> 'Q \\<Rightarrow> (('L tree) set)\" where\n  \"language_for_state automaton state = {tree . evaluation automaton tree = state}\"\n  \ndefinition forest_language_for_state :: \"('Q, 'L) tree_automaton \\<Rightarrow> 'Q \\<Rightarrow> (('L tree fset) set)\" where\n  \"forest_language_for_state automaton state = {forest . (\\<forall>tree.(tree|\\<in>|forest \\<longrightarrow> evaluation automaton tree = state)) \\<and> (\\<exists> tree. tree |\\<in>| forest)}\"\n  \nabbreviation \"\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma>\" :: \"('Q, 'L) tree_automaton \\<Rightarrow> 'Q \\<Rightarrow> (('L tree fset) set)\" (\"\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma>\") where \"\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<equiv> forest_language_for_state\"\nabbreviation \"\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma>\" :: \"('Q, 'L) tree_automaton \\<Rightarrow> 'Q \\<Rightarrow> (('L tree) set)\" (\"\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma>\") where \"\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> \\<equiv> language_for_state\"\nabbreviation \"\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho>\" :: \"('Q, 'L) tree_automaton \\<Rightarrow> ('Q,'L) rule \\<Rightarrow> (('L tree fset) set)\" (\"\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho>\") where \"\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<equiv> forest_language_for_rule\"\nabbreviation \"\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho>\" :: \"('Q, 'L) tree_automaton \\<Rightarrow> ('Q,'L) rule \\<Rightarrow> (('L tree) set)\" (\"\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho>\") where \"\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> \\<equiv> language_for_rule\"\n  \n  \n  \nabbreviation \"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma>\" (\"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma>\") where \"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> x \\<equiv>  \\<delta>\\<^sub>\\<phi>\\<^sub>\\<lambda> \\<circ> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> x\"\nabbreviation \"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho>\" (\"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho>\") where \"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> x \\<equiv>  \\<delta>\\<^sub>\\<phi>\\<^sub>\\<lambda> \\<circ> \\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> x\"\nabbreviation \"\\<delta>\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma>\" (\"\\<delta>\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma>\") where \"\\<delta>\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> x \\<equiv>  \\<delta>\\<^sub>\\<tau>\\<^sub>\\<lambda> \\<circ> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> x\"\nabbreviation \"\\<delta>\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho>\" (\"\\<delta>\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho>\") where \"\\<delta>\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> x \\<equiv>  \\<delta>\\<^sub>\\<tau>\\<^sub>\\<lambda> \\<circ> \\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> x\"\n  \ndefinition evalRule :: \"('Q,'L) tree_automaton \\<Rightarrow> ('Q,'L) rule \\<Rightarrow> 'Q\" where\n  \"evalRule automaton rule = transition automaton (states rule) (symbol rule)\" \n  \n  \n  \ndefinition childrenWithSymbol where \"childrenWithSymbol symbol2 set2 = inf_fset2 set2 {child1 . (root child1 = symbol2)}\"\n  \n  \ndefinition plus :: \"'L tree fset \\<Rightarrow> 'L tree fset \\<Rightarrow> 'L tree fset\" where\n  \"plus f1 f2 = f1 |\\<union>| f2\"   \n  \n  (*fun plus :: \"'L tree \\<Rightarrow> 'L tree \\<Rightarrow> 'L tree\" where\n   \"plus (NODE s1 c1) (NODE s2 c2) = (NODE s1 (c1 |\\<union>| c2))\"*)\n  \n  (*definition oplus :: \"'L tree \\<Rightarrow> 'L tree \\<Rightarrow> 'L tree\" where\n   \"oplus t1 t2 =  psi (plus t1 t2)\"*)\n  \ndefinition plusl :: \"'L tree fset set \\<Rightarrow> 'L tree fset set \\<Rightarrow> 'L tree fset set\" where\n  \"plusl l1 l2 = {tr . (\\<exists> t1 \\<in> l1. (\\<exists> t2 \\<in> l2. (tr = t1 |\\<union>| t2)))}\"\n  \ndefinition uplus :: \"'L tree fset set \\<Rightarrow> 'L tree fset set \\<Rightarrow> 'L tree fset set\" where\n  \"(uplus l1 l2) = (l1 \\<union> (l2 \\<union> (plusl l1 l2)))\"\n  \n  \ndefinition plusD :: \"'L list fset \\<Rightarrow> 'L list fset \\<Rightarrow> 'L list fset\" where\n  \"plusD f1 f2 = f1 |\\<union>| f2\"   \n  \n  (*fun plus :: \"'L tree \\<Rightarrow> 'L tree \\<Rightarrow> 'L tree\" where\n   \"plus (NODE s1 c1) (NODE s2 c2) = (NODE s1 (c1 |\\<union>| c2))\"*)\n  \n  (*definition oplus :: \"'L tree \\<Rightarrow> 'L tree \\<Rightarrow> 'L tree\" where\n   \"oplus t1 t2 =  psi (plus t1 t2)\"*)\n  \ndefinition pluslD :: \"'L list fset set \\<Rightarrow> 'L list fset set \\<Rightarrow> 'L list fset set\" where\n  \"pluslD l1 l2 = {tr . (\\<exists> t1 \\<in> l1. (\\<exists> t2 \\<in> l2. (tr = t1 |\\<union>| t2)))}\"\n  \ndefinition uplusD :: \"'L list fset set \\<Rightarrow> 'L list fset set \\<Rightarrow> 'L list fset set\" where\n  \"(uplusD l1 l2) = (l1 \\<union> (l2 \\<union> (pluslD l1 l2)))\"   \n  \n  \n  \n  \ndefinition realizedIn :: \"'L tree set \\<Rightarrow> 'L list set \\<Rightarrow> bool\" where\n  \"realizedIn l \\<ff> = (\\<exists>\\<gg> . ((\\<gg> \\<in> l) \\<and> (fset (\\<Pi> \\<gg>) \\<subseteq> \\<ff>)))\"\n  \ndefinition realizedInForest :: \"'L tree fset set \\<Rightarrow> 'L list set \\<Rightarrow> bool\" where\n  \"realizedInForest l \\<ff> = (\\<exists>\\<gg> . ((\\<gg> \\<in> l) \\<and> (fset (pathsInForest  \\<gg>) \\<subseteq> \\<ff>)))\"\n  \n  \ndefinition realizedInD :: \"'L list fset set \\<Rightarrow> 'L list set \\<Rightarrow> bool\" where\n  \"realizedInD l \\<ff> = (\\<exists>\\<gg> . ((\\<gg> \\<in> l) \\<and> ((fset \\<gg>) \\<subseteq> \\<ff>)))\"\n  \n  \n  \n  \n  (* ============================================= *)\nsection \"Introducing fixed constants for the separation proof\"\n  \n  \ndefinition \\<A>\\<^sub>1 :: \"(stt,abc) tree_automaton\" where\n  \"\\<A>\\<^sub>1 = Eps(is_tree_automaton)\"\ndefinition \\<A>\\<^sub>2 :: \"(stt,abc) tree_automaton\" where\n  \"\\<A>\\<^sub>2 = Eps(\\<lambda>x.(is_tree_automaton x \\<and> x \\<noteq> \\<A>\\<^sub>1))\"\n  (* TODO needs to say that this is about psi *)\nfun \\<A> :: \"ot \\<Rightarrow> (stt,abc) tree_automaton\" where\n  \"\\<A> \\<aa>\\<^sub>1 = \\<A>\\<^sub>1\"\n| \"\\<A> \\<aa>\\<^sub>2 = \\<A>\\<^sub>2\"\nlemma aut_def : \"\\<A>\\<^sub>1 = \\<A> \\<aa>\\<^sub>1 \\<and> \\<A>\\<^sub>2 = \\<A> \\<aa>\\<^sub>2\"\n  by simp \n    \n    \ndefinition rules_of_state :: \"('Q,'L) tree_automaton \\<Rightarrow> 'Q \\<Rightarrow> ('Q,'L) rule set\" where\n  \"rules_of_state automaton state = {r . evalRule automaton r = state}\"\ndefinition rulesForState :: \"ot \\<Rightarrow> stt \\<Rightarrow> (stt,abc) rule fset\" where\n  \"(rulesForState \\<ii> sta) = (ffilter (\\<lambda>r. transition (\\<A> \\<ii>) (states r) (symbol r) = sta) (rule_set (\\<A> \\<ii>)))\"\n  \n  \n  \n\n  (* ============================================= *)\nsection \"Upper Bound N\"\n  \ndefinition existential_satisfaction_set :: \"'L list set \\<Rightarrow> 'L tree set\" where\n  \"existential_satisfaction_set i = {t . (\\<exists> x . x \\<in> ((fset (\\<Pi> t)) \\<inter> i))}\"\n  \ndefinition existential_satisfaction_setForest :: \"'L list set \\<Rightarrow> 'L tree fset set\" where\n  \"existential_satisfaction_setForest i = {t . (\\<exists> x . x \\<in> ((fset (pathsInForest  t)) \\<inter> i))}\"\n  \ndefinition entails :: \"'L tree set \\<Rightarrow> 'L list set \\<Rightarrow> bool\" where\n  \"entails l i \n     = (l \\<subseteq> (existential_satisfaction_set i))\"    \n  \nabbreviation entailsAbb :: \"'L tree set \\<Rightarrow> 'L list set \\<Rightarrow> bool\" (infixr \"\\<Turnstile>\" 80) where \"(x \\<Turnstile> y) \\<equiv> entails x y\"\n  \ndefinition entailsForest :: \"'L tree fset set \\<Rightarrow> 'L list set \\<Rightarrow> bool\" where\n  \"entailsForest l i \n     = (l \\<subseteq> (existential_satisfaction_setForest i))\"    \n  \n  \nlemma entails_altdef :\n  fixes l\n  fixes I\n  shows \"l \\<Turnstile> I = (\\<forall>x \\<in> l.((fset (\\<Pi> x)) \\<inter> I \\<noteq> {}))\"\n  by (smt IntI disjoint_iff_not_equal emptyE entails_def existential_satisfaction_set_def mem_Collect_eq subsetCE subsetI) \n    \n    \n    \ndefinition emptyForest :: \"'L tree fset\" where\n  \"emptyForest = fempty\"\n  \n  \n  \ndefinition distEquivalenceClassForests :: \"'L tree fset set \\<Rightarrow> 'L tree fset set\" where\n  \"distEquivalenceClassForests lang = {forest . (\\<exists> forest2 \\<in> lang. pathsInForest forest = pathsInForest forest2)}\"\n  \ndefinition biguplusForests :: \"'L tree fset set fset \\<Rightarrow> 'L tree fset set\" where\n  \"biguplusForests languages = {(forest :: 'L tree fset) . (\\<forall> (tr :: 'L tree) . tr |\\<in>| forest \\<longrightarrow> (\\<exists> lang . lang |\\<in>| languages \\<and> (\\<exists> (subforest :: 'L tree fset) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| forest \\<and> subforest \\<in> lang)))) }\"\ndefinition biguplusForestsD :: \"'L list fset set fset \\<Rightarrow> 'L list fset set\" where\n  \"biguplusForestsD languages = {(forest :: 'L list fset) . (\\<forall> (tr :: 'L list) . tr |\\<in>| forest \\<longrightarrow> (\\<exists> lang . lang |\\<in>| languages \\<and> (\\<exists> (subforest :: 'L list fset) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| forest \\<and> subforest \\<in> lang)))) }\"\n  \nabbreviation biguplusForestsAbb :: \"'L tree fset set fset \\<Rightarrow> 'L tree fset set\" (\"\\<Uplus>\") where \"\\<Uplus> x \\<equiv> biguplusForests x\"\nabbreviation biguplusForestsDAbb :: \"'L list fset set fset \\<Rightarrow> 'L list fset set\" (\"\\<Uplus>\\<^sub>\\<delta>\") where \"\\<Uplus>\\<^sub>\\<delta> x \\<equiv> biguplusForestsD x\"\n  \ndefinition bigoplusForests :: \"'L tree fset set fset \\<Rightarrow> 'L tree fset set\" where\n  \"bigoplusForests languages = {(forest :: 'L tree fset) . forest \\<in> (biguplusForests languages) \\<and> (\\<forall> lang . lang |\\<in>| languages \\<longrightarrow> (\\<exists> subforest . (subforest \\<in> lang \\<and> subforest |\\<subseteq>| forest))) }\"\ndefinition bigoplusForestsD :: \"'L list fset set fset \\<Rightarrow> 'L list fset set\" where\n  \"bigoplusForestsD (languages :: 'L list fset set fset) = {(forest :: 'L list fset) . forest \\<in> (biguplusForestsD languages) \\<and> (\\<forall> lang . lang |\\<in>| languages \\<longrightarrow> (\\<exists> subforest . (subforest \\<in> lang \\<and> subforest |\\<subseteq>| forest))) }\"\n  \nabbreviation bigoplusForestsAbb :: \"'L tree fset set fset \\<Rightarrow> 'L tree fset set\" (\"\\<Oplus>\") where \"\\<Oplus> x \\<equiv> bigoplusForests x\"\nabbreviation bigoplusForestsDAbb :: \"'L list fset set fset \\<Rightarrow> 'L list fset set\" (\"\\<Oplus>\\<^sub>\\<delta>\") where \"\\<Oplus>\\<^sub>\\<delta> x \\<equiv> bigoplusForestsD x\"\n  \n  \n  lemma uplusInOplus :\n  \"\\<Uplus> S1 \\<supseteq> \\<Oplus> S1\"\n  using bigoplusForests_def by blast\n    \n    \nlemma uplusInOplusD :\n  \"\\<Uplus>\\<^sub>\\<delta> S1 \\<supseteq> \\<Oplus>\\<^sub>\\<delta> S1\"\n  using bigoplusForestsD_def by auto\n    \n    \nlemma realizedForestTreeRule :\n  fixes r\n  fixes \\<ii>\n  fixes pathset\n  shows \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset = realizedInForest  (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset\"\nproof\n  {\n    assume \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset\"\n    from realizedIn_def obtain \\<gg> where k1 : \"((\\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r)) \\<and> (fset (\\<Pi> \\<gg>) \\<subseteq> pathset))\" using \\<open>realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset\\<close> by blast\n    from realizedInForest_def have  l2 : \"realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset = (\\<exists>\\<gg> . ((\\<gg> \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r)) \\<and> (fset (pathsInForest  \\<gg>) \\<subseteq> pathset)))\" by auto\n    def \\<gg>F == \"finsert \\<gg> {||}\"\n    from k1 \\<gg>F_def forest_language_for_rule_def have l3 : \"\\<gg>F \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r)\"       by (simp add: forest_language_for_rule_def language_for_rule_def) \n    from k1 \\<gg>F_def pathsInForest_def pathsTreeForest have l1 : \"(fset (pathsInForest  \\<gg>F) \\<subseteq> pathset)\"          by (smt fsingleton_iff notin_fset subset_eq)\n    from l1 l2 l3 show \"realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset\" by auto\n  }\n  {\n    assume u1 : \"realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset\"\n    from u1 realizedInForest_def obtain \\<gg> where j2 : \"((\\<gg> \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r)) \\<and> (fset (pathsInForest  \\<gg>) \\<subseteq> pathset))\" by blast\n    then obtain tree where j1 : \"((tree|\\<in>|\\<gg> \\<and> tree_for_rule (\\<A> \\<ii>) r tree))\" using forest_language_for_rule_def   mem_Collect_eq\n      by smt\n    from j2 j1 pathsInForest_def have j6 : \"(fset (\\<Pi> tree) \\<subseteq> pathset)\"              by (metis notin_fset pathsTreeForest set_mp subsetI)\n    from j1 j6 have  \"(\\<exists>\\<gg> . ((\\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r)) \\<and> (fset (\\<Pi> \\<gg>) \\<subseteq> pathset)))\"      using language_for_rule_def by blast \n    then show \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r) pathset\" using realizedIn_def by auto\n  }\nqed\n  \n  \nlemma pathsForestLangMonotone : \"L1 \\<subseteq> L2 \\<Longrightarrow> \\<Pi>\\<^sub>\\<phi> L1 \\<subseteq> \\<Pi>\\<^sub>\\<phi> L2\" by (smt mem_Collect_eq pathsForForestLanguage_def subset_eq)\nlemma pathsTreeLangMonotone : \"L1 \\<subseteq> L2 \\<Longrightarrow> \\<Pi>\\<^sub>\\<tau> L1 \\<subseteq> \\<Pi>\\<^sub>\\<tau> L2\" by (smt mem_Collect_eq pathsForTreeLanguage_def subset_eq)\n    \n    \n    \n  \nlemma realizedForestTreeState :\n  fixes state\n  fixes \\<ii>\n  fixes pathset\n  shows \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset = realizedInForest  (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset\"\nproof \n  from realizedIn_def have \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset = (\\<exists>\\<gg> . ((\\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) \\<and> (fset (\\<Pi> \\<gg>) \\<subseteq> pathset)))\" by auto\n  from realizedInForest_def have \"realizedInForest  (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset = (\\<exists>\\<gg> . ((\\<gg> \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) \\<and> (fset (pathsInForest  \\<gg>) \\<subseteq> pathset)))\" by auto\n  from forest_language_for_state_def have  \"\\<And> \\<gg>. ((\\<gg> \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) =  ((\\<forall>tree.(tree|\\<in>|\\<gg> \\<longrightarrow> evaluation (\\<A> \\<ii>) tree = state)) \\<and> (\\<exists> tree. tree |\\<in>| \\<gg>)))\"    by (simp add: forest_language_for_state_def)\n  {\n    assume \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset\"\n    then obtain \\<gg> where b1 : \"(((\\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) \\<and> (fset (\\<Pi> \\<gg>) \\<subseteq> pathset)))\" using realizedIn_def by blast\n    def forest == \"(finsert \\<gg> fempty)\"\n    from b1 forest_def have \"forest \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)\"          by (simp add: \\<open>\\<And>\\<gg>. (\\<gg> \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) = ((\\<forall>tree.(tree|\\<in>|\\<gg> \\<longrightarrow> evaluation (\\<A> \\<ii>) tree = state)) \\<and> (\\<exists> tree. tree |\\<in>| \\<gg>))\\<close> language_for_state_def)\n    from b1 forest_def have \"(fset (pathsInForest  forest) \\<subseteq> pathset)\"              by (metis (full_types) fsingleton_iff notin_fset pathsTreeForest subset_iff)\n    show \"realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset\"  using \\<open>forest \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state\\<close> \\<open>fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> forest) \\<subseteq> pathset\\<close> \\<open>realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset = (\\<exists>\\<gg>. \\<gg> \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state \\<and> fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> \\<gg>) \\<subseteq> pathset)\\<close> by auto \n  }        \n  {\n    assume \"realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset\"\n    then obtain forest where m1 : \"forest \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)\" and m2 : \"(fset (pathsInForest  forest) \\<subseteq> pathset)\"        using \\<open>realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset = (\\<exists>\\<gg>. \\<gg> \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state \\<and> fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> \\<gg>) \\<subseteq> pathset)\\<close> by blast \n    then obtain tr where m3 : \"tr |\\<in>| forest\"      using \\<open>\\<And>\\<gg>. (\\<gg> \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) = ((\\<forall>tree. tree |\\<in>| \\<gg> \\<longrightarrow> evaluation (\\<A> \\<ii>) tree = state) \\<and> (\\<exists>tree. tree |\\<in>| \\<gg>))\\<close> by auto \n    then have  \"tr \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)\"      using \\<open>\\<And>\\<gg>. (\\<gg> \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) = ((\\<forall>tree. tree |\\<in>| \\<gg> \\<longrightarrow> evaluation (\\<A> \\<ii>) tree = state) \\<and> (\\<exists>tree. tree |\\<in>| \\<gg>))\\<close> language_for_state_def m1 by fastforce \n    have \"fset (\\<Pi> tr) \\<subseteq> pathset\" using m1 m2 m3  by (meson notin_fset pathsTreeForest subset_iff)\n    show \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset\"      using \\<open>fset (\\<delta>\\<^sub>\\<tau> tr) \\<subseteq> pathset\\<close> \\<open>realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset = (\\<exists>\\<gg>. \\<gg> \\<in> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state \\<and> fset (\\<delta>\\<^sub>\\<tau> \\<gg>) \\<subseteq> pathset)\\<close> \\<open>tr \\<in> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state\\<close> by auto \n  }\nqed\n  \n  \n  \ndefinition necess :: \"('Q,abc) tree_automaton \\<Rightarrow> abc list set set \\<Rightarrow> ('Q,abc) rule \\<Rightarrow> abc list set set\" where\n  \"necess automaton I r \n     = (\\<lambda>x.(symbol r) \\<bullet> x) ` {i . (i \\<in> I) \\<and> \n            (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> automaton r) \\<subseteq> (existential_satisfaction_set ((symbol r) \\<bullet> i))}\"    \n  \ndefinition upwardClosure :: \"('L list fset set \\<Rightarrow> 'L list fset set)\" where            \n  \"upwardClosure L = {tr . \\<exists> t2 \\<in> L . fset tr \\<supseteq> fset t2}\"\n  \n  \n    (* ================================================================================ *)\n    \n    (* Here I'm showing a few basic facts about the maximum of a finite set of integers *)\n    \nlemma maxIsUnique :\n  fixes x s\n  assumes \"((\\<forall> y. (y|\\<in>|s \\<longrightarrow> y \\<le> x)) \\<and> (s = {||} \\<longrightarrow> x=0) \\<and> (s \\<noteq> {||} \\<longrightarrow> (x |\\<in>| s)))\"\n  shows \"x = maxFset s\"\n  by (metis antisym_conv assms finiteMaxExists(1) finiteMaxExists(2) finiteMaxExists(3))\n    \n    \n    (* Addition commutes with Maximum *)\nlemma maxAndSuc :\n  shows  \"\\<And> (q :: nat fset) . q \\<noteq> {||} \\<Longrightarrow> maxFset (fimage (Suc) q) = 1 + maxFset q\" \nproof -\n  fix q :: \"nat fset\"\n  assume \"q \\<noteq> {||}\"\n  then have \"(fimage (Suc) q) \\<noteq> {||}\" by auto\n  then have \"((\\<forall> y. (y|\\<in>|(fimage (Suc) q) \\<longrightarrow> y \\<le> (1 + maxFset (fimage (Suc) q)))) \\<and> ((fimage (Suc) q) = {||} \\<longrightarrow> (1 + maxFset (fimage (Suc) q))=0) \\<and> ((fimage (Suc) q) \\<noteq> {||} \\<longrightarrow> ((1 + maxFset q) |\\<in>| (fimage (Suc) q))))\"\n    by (metis One_nat_def \\<open>q \\<noteq> {||}\\<close> add.left_neutral add_Suc fimage_eqI finiteMaxExists(1) finiteMaxExists(3) trans_le_add2)\n  then show \"maxFset (fimage (Suc) q) = 1 + maxFset q\" using  maxIsUnique\n  proof -\n    obtain nn :: \"nat fset \\<Rightarrow> (nat \\<Rightarrow> nat) \\<Rightarrow> nat \\<Rightarrow> nat\" where\n      f1: \"\\<forall>x0 x1 x2. (\\<exists>v3. x2 = x1 v3 \\<and> v3 |\\<in>| x0) = (x2 = x1 (nn x0 x1 x2) \\<and> nn x0 x1 x2 |\\<in>| x0)\"\n      by moura\n    have \"Suc |`| q \\<noteq> {||}\"\n      using \\<open>(\\<forall>y. y |\\<in>| Suc |`| q \\<longrightarrow> y \\<le> 1 + maxFset (Suc |`| q)) \\<and> (Suc |`| q = {||} \\<longrightarrow> 1 + maxFset (Suc |`| q) = 0) \\<and> (Suc |`| q \\<noteq> {||} \\<longrightarrow> 1 + maxFset q |\\<in>| Suc |`| q)\\<close> by fastforce\n    then have f2: \"maxFset (Suc |`| q) = Suc (nn q Suc (maxFset (Suc |`| q))) \\<and> nn q Suc (maxFset (Suc |`| q)) |\\<in>| q\"\n      using f1 by (meson fimageE finiteMaxExists(3))\n    then have f3: \"nn q Suc (maxFset (Suc |`| q)) \\<le> maxFset q\"\n      by (metis finiteMaxExists(1))\n    have \"0 + Suc (maxFset q) \\<le> maxFset (Suc |`| q)\"\n      using \\<open>(\\<forall>y. y |\\<in>| Suc |`| q \\<longrightarrow> y \\<le> 1 + maxFset (Suc |`| q)) \\<and> (Suc |`| q = {||} \\<longrightarrow> 1 + maxFset (Suc |`| q) = 0) \\<and> (Suc |`| q \\<noteq> {||} \\<longrightarrow> 1 + maxFset q |\\<in>| Suc |`| q)\\<close> finiteMaxExists(1) by auto\n    then show ?thesis\n      using f3 f2 by linarith\n  qed \nqed\n  \n  \n  (* The maximum of a (finite) union of (finite) sets is equal to the maximum of the set of maxima of the sets *)\nlemma maxDistrib :\n  fixes f x2a g\n  shows \"maxFset ((g |`| ( (((\\<Union>| (fimage f x2a))))))) = maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a)\"\nproof (rule disjE)\n  def num == \"maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a)\"\n  from num_def  have \"\\<And> x . x |\\<in>| x2a \\<Longrightarrow> (num \\<ge> (maxFset  (g |`| (f x))))\"    by (simp add: finiteMaxExists(1)) \n  hence \"\\<And> x y . x |\\<in>| x2a \\<Longrightarrow> y |\\<in>| (g |`| (f x)) \\<Longrightarrow> num \\<ge> y\"   by (meson finiteMaxExists(1) order_trans) \n  hence n400 : \"\\<And> y . y |\\<in>| ((g |`| ( (((\\<Union>| (fimage f x2a))))))) \\<Longrightarrow> num \\<ge> y\" by auto\n  def leftSet == \"((g |`| ( (((\\<Union>| (fimage f x2a)))))))\"\n  show \"leftSet = {||}  \\<or> leftSet \\<noteq> {||}\" by auto\n  show \"leftSet = {||} \\<Longrightarrow> maxFset ((g |`| ( (((\\<Union>| (fimage f x2a))))))) = maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a)\"\n  proof -\n    assume m800 : \"leftSet = {||}\"\n    hence m801 :  \"maxFset ((g |`| ( (((\\<Union>| (fimage f x2a))))))) = 0\" using leftSet_def        by (simp add: finiteMaxExists(2))\n    have m802 : \"maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a) = 0\"\n    proof -\n      from m800 leftSet_def have \"( (((\\<Union>| (fimage f x2a))))) = {||}\"        by (simp add: leftSet_def)\n      hence \"\\<And>x . (x |\\<in>| x2a \\<Longrightarrow> ( f x = {||}))\"            by blast \n      hence \"\\<And>x . (x |\\<in>| x2a \\<Longrightarrow> ( maxFset (g |`| (f x)) = 0))\"            by (simp add: finiteMaxExists(2))\n      then show \"maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a) = 0\"            by (metis (no_types, lifting) fimageE finiteMaxExists(2) finiteMaxExists(3))\n    qed\n    from m801 m802 show \"maxFset ((g |`| ( (((\\<Union>| (fimage f x2a))))))) = maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a)\" by auto\n  qed\n  show \"leftSet \\<noteq> {||} \\<Longrightarrow> maxFset ((g |`| ( (((\\<Union>| (fimage f x2a))))))) = maxFset ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a)\" \n  proof -\n    assume m900 : \"leftSet \\<noteq> {||}\"\n    then obtain member where m300 : \"member |\\<in>| leftSet\" by auto\n    from n400 leftSet_def have n500 :  \"((\\<forall> y. (y|\\<in>|leftSet \\<longrightarrow> y \\<le> num)))\"  by auto\n    have n501 : \"((num |\\<in>| leftSet))\"\n    proof -\n      from m900 leftSet_def have \"(\\<Union>| (fimage f x2a))  \\<noteq> {||}\" by simp\n      then obtain member2 where \"member2 |\\<in>| x2a\" and \"f member2 \\<noteq> {||}\"            by fastforce\n      then have \"((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a) \\<noteq> {||}\"            by auto\n      then have \"num |\\<in>| ((\\<lambda> x. (maxFset  (g |`| (f x)))     ) |`| x2a)\" using num_def finiteMaxExists(3) by blast\n      then obtain member3 where \"member3 |\\<in>| x2a\" and y749 :  \"num = (((maxFset  (g |`| (f member3)))     ))\"            by blast\n      show \"num |\\<in>| leftSet\"\n      proof (rule disjE)\n        show \"num = 0 \\<or> num > 0\" by auto\n        show \"num = 0 \\<Longrightarrow> num |\\<in>| leftSet\"\n        proof -\n          from n500 have \"num = 0 \\<Longrightarrow> (\\<And>y. y |\\<in>| leftSet \\<Longrightarrow> y = 0)\" by simp\n          then show \"num = 0 \\<Longrightarrow> num |\\<in>| leftSet\" using m300 by metis\n        qed\n        show \"0 < num \\<Longrightarrow> num |\\<in>| leftSet\"\n        proof -\n          assume y750 : \"0 < num\"\n          then have \"num |\\<in>| g |`| (f member3)\" using y749 finiteMaxExists            by (metis neq0_conv) \n          then show \"num |\\<in>| leftSet\"            using \\<open>member3 |\\<in>| x2a\\<close> leftSet_def by blast\n        qed\n      qed\n    qed\n    from n500 n501 have \"((\\<forall> y. (y|\\<in>|leftSet \\<longrightarrow> y \\<le> num)) \\<and> (leftSet = {||} \\<longrightarrow> num=0) \\<and> (leftSet \\<noteq> {||} \\<longrightarrow> (num |\\<in>| leftSet)))\" using m900 by auto\n    show \"leftSet \\<noteq> {||} \\<Longrightarrow> maxFset (g |`| \\<Union>| (f |`| x2a)) = maxFset ((\\<lambda>x. maxFset (g |`| f x)) |`| x2a)\"      using leftSet_def maxIsUnique n500 n501 num_def by auto\n  qed\nqed\n  \n  \n  \nlemma maxFsetUnion :\n  fixes a b\n  shows  \"maxFset (a |\\<union>| b) = (max (maxFset a) (maxFset b))\"\nproof -\n  have \"max (maxFset a) (maxFset b) = maxFset {|maxFset a, maxFset b|}\"    by (smt antisym_conv2 finiteMaxExists(1) finiteMaxExists(3) finsertI1 finsert_absorb finsert_iff finsert_not_fempty max_def not_le)\n  then have \"maxFset (a |\\<union>| b) = maxFset {|maxFset a, maxFset b|}\" using maxDistrib\n    by (smt antisym_conv finiteMaxExists(1) finiteMaxExists(2) finiteMaxExists(3) fset_rev_mp funionE max_0R max_def sup_ge1 sup_ge2 sup_max)\n  then show \"maxFset (a |\\<union>| b) = (max (maxFset a) (maxFset b))\"    by (simp add: \\<open>max (maxFset a) (maxFset b) = maxFset {|maxFset a, maxFset b|}\\<close>)\nqed\n  \n      \nlemma maxMonotonic :\n  assumes \"( t |\\<subseteq>|  s)\"\n  shows \"maxFset t \\<le> maxFset s\"\n  by (metis assms finiteMaxExists(1) finiteMaxExists(2) finiteMaxExists(3) fset_rev_mp le_0_eq nat_le_linear)\n    \n    \n    (* ================================================================================ *)\n  \n  (* The height of a tree is equal to the maximal length of any of its paths *)\nlemma heightOnlyDependsOnPaths :\n  shows \"height t = (maxFset (length |`| (\\<Pi> t)))\"\nproof (induct t)\n  case (NODE x1a x2a)\n  assume q1 : \"\\<And>x2aa. x2aa \\<in> fset x2a \\<Longrightarrow> height x2aa = maxFset (length |`| \\<delta>\\<^sub>\\<tau> x2aa)\"\n  have \"height (NODE x1a x2a) = 1 + (maxFset (fimage height x2a))\" by auto\n  have n1 : \"\\<Pi> (NODE x1a x2a) = fimage (append [x1a]) ((\\<Union>| (fimage \\<Pi> x2a))  |\\<union>|  (finsert [] {||}))\" by auto\n  have y10 : \" (length |`| (fimage (append [x1a]) (\\<Union>| (fimage \\<Pi> x2a)))) =  (fimage (Suc) (length |`| ( (\\<Union>| (fimage \\<Pi> x2a)))))\"        by (smt One_nat_def Suc_eq_plus1_left fimage_fimage fset.map_cong0 length_Cons length_append list.size(3)) \n  then have y1 : \"maxFset (length |`| (fimage (append [x1a]) (\\<Union>| (fimage \\<Pi> x2a)))) = maxFset (fimage (Suc) (length |`| ( (\\<Union>| (fimage \\<Pi> x2a)))))\" by auto\n  have   \"(((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||})) \\<noteq> {||}\"    using n1 by auto\n  then have \"(length |`| (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))) \\<noteq> {||}\" by blast\n  then have y2 : \"maxFset (fimage (Suc) (length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))))) = 1 + maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||})))))\" using maxAndSuc    by meson\n  have y9 : \"(maxFset (fimage height x2a)) = maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||})))))\"\n  proof (rule disjE)\n    show \"x2a = {||} \\<or> x2a \\<noteq> {||}\" by auto\n    {\n      assume o1 : \"x2a = {||}\"\n      have \"(maxFset (fimage height {||})) = maxFset {||}\"  by auto\n      then have s1 : \"(maxFset (fimage height x2a)) = 0\" using finiteMaxExists               by (simp add: o1)\n      from o1 have \" ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))) = (finsert [] {||})\"               by (simp add: ffUnion_empty) \n      then have s2 : \"((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))))) = (finsert 0 {||})\"               by auto  \n      have s3 : \"maxFset (finsert 0 {||}) = 0\"               using finiteMaxExists(3) by blast\n      from s3 have \"maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))))) = 0\"               using s2 by presburger\n      then show \"(maxFset (fimage height x2a)) = maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||})))))\" using s1 by auto\n    }\n    {\n      assume o1 : \"x2a \\<noteq> {||}\"\n      have \"((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))))) = (length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))) |\\<union>| (length |`| (finsert [] {||}))\"             by simp \n      from maxFsetUnion have r1 :  \"maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))) |\\<union>| (length |`| (finsert [] {||}))) = max (maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))))) (maxFset (length |`| (finsert [] {||})))\"           by (metis \\<open>length |`| (\\<Union>| (\\<delta>\\<^sub>\\<tau> |`| x2a) |\\<union>| {|[]|}) = length |`| \\<Union>| (\\<delta>\\<^sub>\\<tau> |`| x2a) |\\<union>| length |`| {|[]|}\\<close>) \n      have r2 : \"(maxFset (length |`| (finsert [] {||}))) = 0\"               using finiteMaxExists(3) by auto\n      then have r3 : \"max (maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))))) (maxFset (length |`| (finsert [] {||}))) = maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))))\"  by simp\n      from r1 r2 r3   have k500 : \"maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))) |\\<union>| (length |`| (finsert [] {||}))) = maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a)))))))\"          by simp\n      have \"maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))))))) = maxFset ((\\<lambda> x. (maxFset  (length |`| (\\<Pi> x)))     ) |`| x2a)\"       by (simp add: maxDistrib) \n      then have k501 : \"maxFset ((length |`| ( (((\\<Union>| (fimage \\<Pi> x2a))))))) = (maxFset (fimage height x2a))\" using q1         using fset.map_cong0 by force \n      from k500 k501 show \"maxFset (height |`| x2a) = maxFset (length |`| (\\<Union>| (\\<delta>\\<^sub>\\<tau> |`| x2a) |\\<union>| {|[]|}))\" by simp\n    }\n  qed\n  have y3 : \"1 + (maxFset (fimage height x2a)) = maxFset (length |`| (fimage (append [x1a]) (((\\<Union>| (fimage \\<Pi> x2a))) |\\<union>|  (finsert [] {||}))))\"    using y1 y2 y9    using y10 by auto \n  then have y4 : \"1 + (maxFset (fimage height x2a)) = maxFset (length |`| \\<delta>\\<^sub>\\<tau> (NODE x1a x2a))\" using n1 by auto\n  then show \"height (NODE x1a x2a) = maxFset (length |`| \\<delta>\\<^sub>\\<tau> (NODE x1a x2a))\"    by simp\nqed\n  \n  \n  \nlemma heightOfChild:\n  assumes b1 : \"x |\\<in>| childrenSet tree\"\n  shows \"height x < height tree\"\nproof -\n  obtain symb2 set2 where b2:  \"tree = (NODE symb2 set2)\"    using tree.exhaust by blast\n  from b2 have b5 : \"height tree = 1 + (maxFset (fimage height set2))\" using height.simps by auto\n  from b1 b2 have \"x |\\<in>| set2\" by (simp add: childrenSet.simps)\n  then have \"height x \\<le> (maxFset (fimage height set2))\"        by (simp add: finiteMaxExists)\n  then show ?thesis using b5 by arith\nqed\n    \nlemma childDepth :\n  assumes \"child |\\<in>| children\"\n    shows \"height (NODE parent children) > ((height child))\"\n  by (metis assms childrenSet.simps heightOfChild)\n    \n    \n  (* --------------------------------------------------------- *)\n  (*  PSI, the distributive normal form  *)\n  (* --------------------------------------------------------- *)\n    \nfunction psi :: \"abc tree \\<Rightarrow> abc tree\" where\n  \"psi (NODE symbol1 children1)\n      = NODE symbol1 (fimage (\\<lambda> symbol2 .\n                              psi (NODE symbol2 (\\<Union>| (fimage childrenSet (childrenWithSymbol symbol2 children1)))\n                                  )\n                              )\n                              (fimage root children1)\n                     )\"\n  by pat_completeness auto\n(*termination apply (relation \"measure height\")\nproof -\n  show \"wf (measure height)\" by auto\n  show \"\\<And>symbol1 children1 z. z \\<in> fset (root |`| children1) \\<Longrightarrow> (NODE z (\\<Union>| (childrenSet |`| childrenWithSymbol z children1)), NODE symbol1 children1) \\<in> measure height\"\n  proof (simp add : measure_def)\n    fix children1 z\n    def upMax == \"maxFset (height |`| children1)\"\n    def downMax == \"maxFset (height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1))\"\n    show \"z \\<in> root ` fset children1 \\<Longrightarrow> maxFset (height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1)) < maxFset (height |`| children1)\"\n    proof -\n      assume n875654 : \"z \\<in> root ` fset children1\"\n      have \"downMax < upMax\"\n      proof (rule disjE)\n        show \"height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1) = fempty \\<or> height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1) \\<noteq> fempty\" by auto\n        {\n          assume \"height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1) = fempty\"\n          hence \"downMax = 0\" using downMax_def           using finiteMaxExists(2) by auto \n          from n875654 obtain tree where \"z = root tree\" and \"tree |\\<in>| children1\" using childrenWithSymbol_def equalsffemptyD fimageE fimage_is_fempty imageE notin_fset    by fastforce  \n          hence \"height tree \\<le> upMax\" using upMax_def      by (simp add: finiteMaxExists(1)) \n          from theSingletonPathExists heightOnlyDependsOnPaths finiteMaxExists(3) have \"height tree > 0\"              by (metis fimage_eqI finiteMaxExists(1) gr0I impossible_Cons list.size(3) rootIsPath2) \n          then show \"downMax < upMax\"              using \\<open>downMax = 0\\<close> \\<open>height tree \\<le> upMax\\<close> less_le_trans by blast \n        }\n        {\n          assume \"height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1) \\<noteq> fempty\"\n          then obtain child tree where \"tree |\\<in>| childrenWithSymbol z children1\" and n764543 : \"child |\\<in>| childrenSet tree\" and nu754543 : \"height child = downMax\" using ffUnionLemma    downMax_def  finiteMaxExists(3)              by (smt fimageE) \n          hence ni8764543 : \"tree |\\<in>| children1\" using childrenWithSymbol_def                  by (metis finterD1) \n          have  \"downMax < height tree\" using n764543 nu754543        using heightOfChild by blast \n          then show \"downMax < upMax\" using upMax_def ni8764543 finiteMaxExists(1)            by (metis fimage_eqI less_le_trans) \n        }\n      qed\n      then show \"z \\<in> root ` fset children1 \\<Longrightarrow> maxFset (height |`| \\<Union>| (childrenSet |`| childrenWithSymbol z children1)) < maxFset (height |`| children1)\" using upMax_def downMax_def by auto\n    qed\n  qed\nqed*)\n  \n\ndefinition psiF where \"psiF trees = fimage (\\<lambda> symbol2 .\n                              psi (NODE symbol2 (\\<Union>| (fimage childrenSet (childrenWithSymbol symbol2 trees)))\n                                  )\n                              )\n                              (fimage root trees)\"\n  \n  \n  \nabbreviation psiFAbb :: \"abc tree fset \\<Rightarrow> abc tree fset\" (\"\\<Psi>\\<^sub>\\<phi>\") where \"\\<Psi>\\<^sub>\\<phi> x \\<equiv> psiF x\"\n  \ndefinition psiFLang where \"psiFLang language = \\<Psi>\\<^sub>\\<phi> ` language\"\n  \n    \ndefinition \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma> :: \"stt fset \\<Rightarrow> stt fset \\<Rightarrow> abc tree fset set\" where\n  \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma> Sa1 Sa2 = ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)))) \n                                    \\<inter> (\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>2) |`| Sa2))))))\"\ndefinition \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> :: \"(stt,abc) rule fset \\<Rightarrow> (stt,abc) rule fset \\<Rightarrow> abc tree fset set\" where\n  \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> Sa1 Sa2 = ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| Sa1)))) \n                                              \\<inter> (\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| Sa2))))))\" \n  \n  \n  \ndefinition \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> :: \"stt fset \\<Rightarrow> stt fset \\<Rightarrow> abc list fset set\" where\n  \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2 = ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)))) \n                                    \\<inter> ((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>2) |`| Sa2))))))\"\ndefinition \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> :: \"(stt,abc) rule fset \\<Rightarrow> (stt,abc) rule fset \\<Rightarrow> abc list fset set\" where\n  \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> Sa1 Sa2 = ( (((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| Sa1)))) \n                                              \\<inter> ((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| Sa2))))))\" \n  \n  \n  \n  \n  \ndefinition dist_intersectionLanguageOplusD :: \"stt fset \\<Rightarrow> stt fset \\<Rightarrow> abc list fset set\" where\n  \"dist_intersectionLanguageOplusD Sa1 Sa2 = ( (((\\<Oplus>\\<^sub>\\<delta> ( (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1))) \n                       \\<inter> ( (\\<Oplus>\\<^sub>\\<delta> ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>2) |`| Sa2)))))\"\ndefinition dist_intersectionLanguageOplusRulesD :: \"(stt,abc) rule fset \\<Rightarrow> (stt,abc) rule fset \\<Rightarrow> abc list fset set\" where\n  \"dist_intersectionLanguageOplusRulesD Sa1 Sa2 = ( (((\\<Oplus>\\<^sub>\\<delta> ( (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| Sa1))) \n                            \\<inter> ((\\<Oplus>\\<^sub>\\<delta> ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| Sa2)))))\"                                                  \n  \ndefinition dist_intersectionLanguageOplus :: \"stt fset \\<Rightarrow> stt fset \\<Rightarrow> abc tree fset set\" where\n  \"dist_intersectionLanguageOplus Sa1 Sa2 = ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Oplus> ( (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1))) \n                       \\<inter> ( \\<Psi>\\<^sub>\\<phi> `(\\<Oplus> ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>2) |`| Sa2)))))\"\ndefinition dist_intersectionLanguageOplusRules :: \"(stt,abc) rule fset \\<Rightarrow> (stt,abc) rule fset \\<Rightarrow> abc tree fset set\" where\n  \"dist_intersectionLanguageOplusRules Sa1 Sa2 = ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Oplus> ( (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| Sa1))) \n                            \\<inter> (\\<Psi>\\<^sub>\\<phi> ` (\\<Oplus> ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| Sa2)))))\"                                               \n  \n  \nabbreviation dist_intersectionLanguageOplusAbb :: \"stt fset \\<Rightarrow> stt fset \\<Rightarrow> abc tree fset set\" (\"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<sigma>\") where \"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<sigma> x y \\<equiv> dist_intersectionLanguageOplus x y\"\nabbreviation dist_intersectionLanguageOplusRulesAbb :: \"(stt,abc) rule fset \\<Rightarrow> (stt,abc) rule fset \\<Rightarrow> abc tree fset set\" (\"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<rho>\") where \"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<rho> x y \\<equiv> dist_intersectionLanguageOplusRules x y\"\n  \nabbreviation dist_intersectionLanguageOplusAbbD :: \"stt fset \\<Rightarrow> stt fset \\<Rightarrow> abc list fset set\" (\"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<sigma>\\<^sub>\\<delta>\") where \"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<sigma>\\<^sub>\\<delta> x y \\<equiv> dist_intersectionLanguageOplusD x y\"\nabbreviation dist_intersectionLanguageOplusRulesAbbD :: \"(stt,abc) rule fset \\<Rightarrow> (stt,abc) rule fset \\<Rightarrow> abc list fset set\" (\"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<rho>\\<^sub>\\<delta>\") where \"\\<Psi>\\<^sub>\\<Oplus>\\<^sub>\\<rho>\\<^sub>\\<delta> x y \\<equiv> dist_intersectionLanguageOplusRulesD x y\"\n  \n  \n  \n\n    \n    \n    \n    \n    \n    (* ============================================= *)\nsection \"Basic Lemma On Approximation Beyond N\"\n  \n  \n  \n  \ndefinition \\<I> :: \"abc list set set\" where\n  \"\\<I> = (\\<lambda>pair . \\<pi>\\<^sup>1 pair - \\<pi>\\<^sup>2 pair) `\n                     {setPair . (\\<exists> i Sa1 Sa2 s . \n(*                                (((s |\\<in>| (state_set) (\\<A> i))) \\<and> (((Sa1 |\\<subseteq>| (state_set) \\<A>\\<^sub>1))) \\<and> ((Sa2 |\\<subseteq>| (state_set) \\<A>\\<^sub>2)) \\<and>*)\n                                (\\<pi>\\<^sup>1 setPair = (\\<Pi>\\<^sub>\\<phi> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s))) \n                              \\<and> (\\<pi>\\<^sup>2 setPair = (\\<Pi>\\<^sub>\\<delta> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>  Sa1 Sa2))))}\"\n  \n  \ndefinition constantIsSuitableForStates :: \"ot \\<Rightarrow> stt \\<Rightarrow> stt fset \\<Rightarrow> stt fset \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"constantIsSuitableForStates i s Sa1 Sa2 N = (\\<exists> I \\<in> \\<I>. ((\\<forall> n . ((Suc n > N) \\<longrightarrow> ((\\<not>(realizedIn \n                                                           (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s)  \n                                                           (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))\n                                                     ) )\n                                                     \\<longrightarrow> ( ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) \\<Turnstile> I)\n                                                                       \\<and> ((I \\<inter> \\<Pi>\\<^sub>\\<delta> ( (( \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2  )))) = {})\n                                                                      )\n                                                               )\n                                                          )\n                                            ))))\"\n  \ndefinition constantIsSuitableForAllStates  :: \"nat \\<Rightarrow> bool\" where\n  \"constantIsSuitableForAllStates N = (\\<forall> i . \n                                         (\\<forall> s . \n                                           (\\<forall> Sa1 . \n                                             (\\<forall> Sa2 . (s |\\<in>| (state_set (\\<A> i))\n                                                        \\<longrightarrow>  ( Sa1 |\\<subseteq>| state_set \\<A>\\<^sub>1 \n                                                           \\<longrightarrow> ( Sa2 |\\<subseteq>| state_set \\<A>\\<^sub>2 \n                                                               \\<longrightarrow> ( constantIsSuitableForStates i s Sa1 Sa2 N\n               ))))))))\"\n  \ndefinition heightForestBounded :: \"abc tree fset \\<Rightarrow> nat \\<Rightarrow> bool\" where\n  \"heightForestBounded \\<ff> n = (\\<forall>t.(t|\\<in>|\\<ff> \\<longrightarrow> height t \\<le> n))\"\n  \n    \n  \nlemma factorByRootSymbolF_lemma :\n  fixes symb\n  fixes language\n  shows \"\\<And>a. ((a |\\<in>| symb \\<diamondop> language) = (a \\<in> factorByRootSymbol symb (fset language)))\"\n    and \"fset  ( symb \\<diamondop> language) = factorByRootSymbol symb (fset language)\"\nproof -\n  have k9 : \"finite {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}\"\n  proof -\n    def setsOfChildren == \"\\<Union>| (childrenSet |`| (ffilter (\\<lambda> tr . root tr = symb) language))\"\n    have \"\\<And>x . ((x |\\<in>| (\\<Union>| (childrenSet |`| (ffilter (\\<lambda> tr . root tr = symb) language)))) = (x \\<in> {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}))\"\n    proof -\n      fix x\n      from setsOfChildren_def have \"((x |\\<in>| (\\<Union>| (childrenSet |`| (ffilter (\\<lambda> tr . root tr = symb) language))))  = (\\<exists> y. ( y|\\<in>| (ffilter (\\<lambda> tr . root tr = symb) language) \\<and> x |\\<in>| childrenSet y    )))\"        by auto\n      also have \"... = (\\<exists> y. ( y|\\<in>| language \\<and> root y = symb \\<and> x |\\<in>| childrenSet y    ))\" by auto\n      also have \"... = (x \\<in> {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))})\" by auto\n      then show \"((x |\\<in>| (\\<Union>| (childrenSet |`| (ffilter (\\<lambda> tr . root tr = symb) language)))) = (x \\<in> {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}))\" by auto\n    qed\n    then   have \"\\<And>x . ((x |\\<in>| setsOfChildren) = (x \\<in> {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}))\" using setsOfChildren_def by auto \n    then  have \"(fset setsOfChildren) = {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}\"        by (meson notin_fset subsetI subset_antisym)  \n    then show \"finite {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}\"            by (metis finite_fset)\n  qed\n    \n  show \"\\<And>a. ((a |\\<in>| symb \\<diamondop> language) = (a \\<in> factorByRootSymbol symb (fset language)))\"\n  proof -\n    fix a\n    show \"(a |\\<in>| symb \\<diamondop> language) = (a \\<in> symb \\<diamondop>\\<tau>\\<lambda> fset language)\"\n    proof -\n      from factorByRootSymbolF_def have i1a : \"(a |\\<in>| symb \\<diamondop> language) = (a |\\<in>| set_to_fset {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))})\" by auto\n      from factorByRootSymbol_def have \"(a \\<in> symb \\<diamondop>\\<tau>\\<lambda> fset language) = (a \\<in> {t. (\\<exists>tree \\<in> fset language . (root tree = symb \\<and> t |\\<in>| childrenSet tree))})\" by auto\n      also have \"... = (a \\<in> {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))})\"          by (smt mem_Collect_eq notin_fset) \n      from k9 set_to_fset_def have \"(a |\\<in>| set_to_fset {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))}) = (a \\<in> {t. (\\<exists>tree . tree |\\<in>| language \\<and> (root tree = symb \\<and> t |\\<in>| childrenSet tree))})\"      by (metis (mono_tags, lifting) Abs_fset_inverse mem_Collect_eq notin_fset) \n      then show \"(a |\\<in>| symb \\<diamondop> language) = (a \\<in> symb \\<diamondop>\\<tau>\\<lambda> fset language)\" using calculation i1a          using \\<open>(a \\<in> {t. \\<exists>tree\\<in>fset language. root tree = symb \\<and> t |\\<in>| childrenSet tree}) = (a \\<in> {t. \\<exists>tree. tree |\\<in>| language \\<and> root tree = symb \\<and> t |\\<in>| childrenSet tree})\\<close> by blast\n    qed\n  qed\n    \n  show \"fset (symb \\<diamondop> language) = symb \\<diamondop>\\<tau>\\<lambda> fset language\"    by (meson \\<open>\\<And>a. (a |\\<in>| symb \\<diamondop> language) = (a \\<in> symb \\<diamondop>\\<tau>\\<lambda> fset language)\\<close> notin_fset subsetI subset_antisym) \nqed\n  \ndefinition heightD where \"heightD pathset = (maxFset (length |`| pathset))\"\n  \nlemma heightHeightD :\n  shows \"height tr = heightD (\\<Pi> tr)\"\n  using  heightOnlyDependsOnPaths heightD_def  by (simp add: heightD_def) \n    \n    \n  \n    \nlemma unionAppend :\n  shows \"\\<And>q . (\\<alpha> \\<bullet> q) \\<union> {[\\<alpha>]} = \\<alpha> \\<bullet> (q \\<union> {[]})\"\nproof \n  fix q\n  show \"(\\<alpha> \\<bullet> q) \\<union> {[\\<alpha>]} \\<subseteq> \\<alpha> \\<bullet> (q \\<union> {[]})\"\n  proof \n    fix x\n    assume \"x \\<in> \\<alpha> \\<bullet> q \\<union> {[\\<alpha>]}\"\n    hence \"x \\<in> \\<alpha> \\<bullet> q \\<or> x \\<in> {[\\<alpha>]}\"  by auto\n    then show \"x \\<in> \\<alpha> \\<bullet> (q \\<union> {[]})\"  using prefixLetter_def  by auto\n  qed\n  show \"\\<alpha> \\<bullet> (q \\<union> {[]}) \\<subseteq> \\<alpha> \\<bullet> q \\<union> {[\\<alpha>]}\"\n  proof\n    fix x\n    assume \" x \\<in> \\<alpha> \\<bullet> (q \\<union> {[]})\"\n    then have \"x \\<in> \\<alpha> \\<bullet> q \\<or> x \\<in> \\<alpha> \\<bullet> {[]}\" using prefixLetter_def  by auto\n    then have \"x \\<in> \\<alpha> \\<bullet> q \\<or> x \\<in> {[\\<alpha>]}\" using prefixLetter_def  by auto\n    then show \" x \\<in> (\\<alpha> \\<bullet> q) \\<union> {[\\<alpha>]}\" by auto\n  qed\nqed\n  \n  \nlemma realized_rule_state : \n  fixes \\<alpha> :: \"abc\"\n  assumes \"symbol r = \\<alpha>\"\n  assumes \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r) (\\<alpha> \\<bullet> (pathset \\<union> {[]}))\"\n  assumes \"state |\\<in>| (states r)\"\n  shows \"(realizedIn  (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset)\"\nproof -\n  from assms realizedIn_def obtain \\<gg> where a1 : \" ((\\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r)))\" and a2 :\"(fset (\\<Pi> \\<gg>) \\<subseteq> (\\<alpha> \\<bullet> (pathset \\<union> {[]})))\" by metis\n  from a1 tree_for_rule_def language_for_rule_def have a10 : \"((root \\<gg> = symbol r) \\<and> ((fimage (((evaluation (\\<A> \\<ii>)))) (childrenSet \\<gg>)) = states r))\" by blast\n  then obtain child where a12 : \"child |\\<in>| childrenSet \\<gg>\" and \"((evaluation (\\<A> \\<ii>))) child = state\" using assms(3)        by (metis fimageE)  \n  then have a30 : \"child \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)\" using language_for_state_def    by (simp add: language_for_state_def) \n  from a10 assms(1)  have a11 : \"((root \\<gg> = \\<alpha>))\" by auto \n  from pathAlternateDef  root.simps a11 have a25 : \"\\<Pi> \\<gg> = op # \\<alpha> |`| ((\\<Union>| (\\<Pi> |`| (childrenSet \\<gg>))) |\\<union>| {|[]|})\"    by (metis childrenSet.elims) \n  have \"((\\<lambda> x.(\\<alpha>#x)) ` (fset (\\<Pi> child))) \\<subseteq> (fset (\\<Pi> \\<gg>))\"\n  proof \n    fix x\n    assume \"x \\<in> ((\\<lambda> x.(\\<alpha>#x)) ` (fset (\\<Pi> child)))\"\n    then obtain y where a20 : \"x = \\<alpha>#y\" and \"y \\<in> (fset (\\<Pi> child))\" by auto\n    then have \"y |\\<in>| (\\<Union>| (\\<Pi> |`| (childrenSet \\<gg>)))\" using notin_fset a12          by (metis (full_types) ffUnionI fimage_eqI)\n    then have \"y |\\<in>| (((\\<Union>| (\\<Pi> |`| (childrenSet \\<gg>))) |\\<union>| {|[]|}))\" by auto\n    then have \"x |\\<in>| op # \\<alpha> |`| ((\\<Union>| (\\<Pi> |`| (childrenSet \\<gg>))) |\\<union>| {|[]|})\" using a20 by auto\n    then show \"x \\<in> (fset (\\<Pi> \\<gg>))\" using a25 notin_fset by metis\n  qed\n  then have \"(\\<alpha> \\<bullet> (fset (\\<Pi> child))) \\<subseteq> (fset (\\<Pi> \\<gg>))\"      by (simp add: prefixLetter_def) \n  then have \"(\\<alpha> \\<bullet> (fset (\\<Pi> child))) \\<subseteq> (\\<alpha> \\<bullet> (pathset \\<union> {[]}))\" using a2        by auto\n  then have \"((\\<lambda> x.(\\<alpha>#x)) ` (fset (\\<Pi> child))) \\<subseteq> ((\\<lambda> x.(\\<alpha>#x)) ` (pathset \\<union> {[]}))\" using a2   prefixLetter_def     by auto\n  then have \"(fset (\\<Pi> child)) \\<subseteq> ((pathset \\<union> {[]}))\"        by blast \n  then have \"(fset (\\<Pi> child)) \\<subseteq> ((pathset))\"\n  proof -\n    obtain aas :: \"abc list set \\<Rightarrow> abc list set \\<Rightarrow> abc list\" where\n      f1: \"\\<forall>A Aa. (\\<not> A \\<subseteq> Aa \\<or> (\\<forall>as. as \\<notin> A \\<or> as \\<in> Aa)) \\<and> (aas A Aa \\<in> A \\<and> aas A Aa \\<notin> Aa \\<or> A \\<subseteq> Aa)\"\n      by moura\n    moreover\n    { assume \"[] \\<noteq> aas (fset (\\<delta>\\<^sub>\\<tau> child)) pathset\"\n      then have \"aas (fset (\\<delta>\\<^sub>\\<tau> child)) pathset \\<in> fset (\\<delta>\\<^sub>\\<tau> child) \\<longrightarrow> fset (\\<delta>\\<^sub>\\<tau> child) \\<subseteq> pathset\"\n        using f1 by (metis Un_iff \\<open>fset (\\<delta>\\<^sub>\\<tau> child) \\<subseteq> pathset \\<union> {[]}\\<close> all_not_in_conv insert_iff) }\n    ultimately show ?thesis\n      by (metis (no_types) list.distinct(1) noEmptyPathsInPi notin_fset)\n  qed       \n  then  have \" ((child \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)))\" and  \"(fset (\\<Pi> child) \\<subseteq> ( (pathset)))\" using a30 by auto\n      then show \"realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset\"        using realizedIn_def by auto\nqed\n  \n  \n  \n  \nproposition commuteExistsAll :\n  fixes D :: \"'a fset\"\n  fixes P :: \"'a \\<Rightarrow> nat \\<Rightarrow> bool\"\n  assumes  \"\\<And> d .  d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P d n2)))\"\n  shows  \"(\\<exists> N. \\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P  d n2))))\"\nproof -\n  def choices == \"\\<lambda> d. (SOME n. ((\\<forall> n2 . (n2 > n \\<longrightarrow> P d n2))))\"\n  have ny756787 : \"\\<And> d .  d |\\<in>| D \\<Longrightarrow>(\\<And> n2 . (n2 > (choices d) \\<Longrightarrow> P d n2))\" \n  proof -\n    fix d\n    assume \"d |\\<in>| D\"\n    hence \"(\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P d n2)))\" using assms by auto\n    hence \"(\\<forall> n2 . (n2 > (choices d) \\<longrightarrow> P d n2))\" using choices_def          by (smt someI_ex) \n    then show \"(\\<And> n2 . (n2 > (choices d) \\<Longrightarrow> P d n2))\" by auto\n  qed\n  def maxChoice == \"maxFset (choices |`| D)\"\n  hence \"\\<And> d .  d |\\<in>| D \\<Longrightarrow>(\\<And> n2 . (n2 > maxChoice \\<Longrightarrow> P d n2))\" using ny756787      by (metis dual_order.strict_trans fimage_eqI finiteMaxExists(1) leD linorder_neqE_nat) \n  then show ?thesis by auto\nqed\n  \n  \nproposition commuteExistsAll2 :\n  shows  \"\\<And> (P :: 'a \\<Rightarrow> nat \\<Rightarrow> bool) (D :: 'a fset) . ((\\<forall> d .  d |\\<in>| D \\<longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P d n2)))) \\<longrightarrow> (\\<exists> N. \\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P  d n2)))))\"\n  using commuteExistsAll by auto\n    \n      \n      \nproposition chainMaximum :\n  fixes A :: \"'a fset\"\n  fixes B :: \"'b fset\"\n  fixes C :: \"'c fset\"\n  fixes D :: \"'d fset\"\n  fixes P :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> nat \\<Rightarrow> bool\"\n  assumes \"\\<And> a b c d . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P a b c d n2)))\"\n  shows \"\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))\"\nproof -\n  from commuteExistsAll2 have n54687a : \"\\<And>(P :: 'a \\<Rightarrow> nat \\<Rightarrow> bool)  (D :: 'a fset). ((\\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<exists>n. \\<forall>n2>n. P d n2)) \\<longrightarrow> (\\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2)))\" by auto\n  from commuteExistsAll2 have n54687b : \"\\<And>(P :: 'b \\<Rightarrow> nat \\<Rightarrow> bool)  (D :: 'b fset). ((\\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<exists>n. \\<forall>n2>n. P d n2)) \\<longrightarrow> (\\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2)))\" by auto\n  from commuteExistsAll2 have n54687c : \"\\<And>(P :: 'c \\<Rightarrow> nat \\<Rightarrow> bool)  (D :: 'c fset). ((\\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<exists>n. \\<forall>n2>n. P d n2)) \\<longrightarrow> (\\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2)))\" by auto\n  from commuteExistsAll2 have n54687d : \"\\<And>(P :: 'd \\<Rightarrow> nat \\<Rightarrow> bool)  (D :: 'd fset). ((\\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<exists>n. \\<forall>n2>n. P d n2)) \\<longrightarrow> (\\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2)))\" by auto\n      \n  have j1 : \"(\\<And> a b c  . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> (\\<exists> N. \\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2)))))\"\n  proof -\n    fix a b c\n    def Q == \"P a b c\"\n    assume \"a |\\<in>| A\" and  \"b|\\<in>|B\" and \"c |\\<in>| C\"\n    then have n6578 : \"\\<forall> d . d |\\<in>| D \\<longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> Q d n2)))\" using Q_def assms        by auto\n    from n6578 n54687d have \" (\\<exists> N. \\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> Q d n2))))\" by auto\n    then show \"(\\<exists> N. \\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))\" using Q_def by auto\n  qed\n    \n  then have j2 : \"(\\<And> a b   . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> (\\<exists> N. \\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))\" \n  proof -\n    fix a b \n    assume \"a |\\<in>| A\" and  \"b|\\<in>|B\"\n    then have \"(\\<And>  c  .  c |\\<in>| C \\<Longrightarrow> (\\<exists> N. \\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2)))))\" using j1 by auto\n    then have n6787 : \"(\\<And>  c  .  c |\\<in>| C \\<Longrightarrow> (\\<exists> N. (\\<forall> n2 . (n2 > N \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> (P a b c d n2))))))\" by blast\n    def Q == \"\\<lambda> c n2. ((\\<forall> d . d |\\<in>| D \\<longrightarrow> (P a b c d n2)))\"\n    then have \"(\\<And>  (c :: 'c)  .  c |\\<in>| C \\<Longrightarrow> (\\<exists> N. (\\<forall> n2 . (n2 > N \\<longrightarrow> ((Q c n2))))))\" using n6787 by blast \n    then have \"(\\<exists> N. \\<forall>  c  .  c |\\<in>| C \\<longrightarrow> (\\<forall> n2 . (n2 > N \\<longrightarrow> ( ((Q c n2))))))\" using n54687c  by auto\n    then have \"(\\<exists> N. (\\<forall> n2 . (n2 > N \\<longrightarrow> (\\<forall>  c  .  c |\\<in>| C \\<longrightarrow> ((Q c n2))))))\" by blast\n    then show \"(\\<exists> N. \\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2)))))\" using Q_def by blast\n  qed\n    \n  then have j3 : \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N. (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))))\"\n  proof -\n    fix a \n    assume \"a |\\<in>| A\"\n    then have \"(\\<And>  b   .  b|\\<in>|B \\<Longrightarrow> (\\<exists> N. \\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))\"  using j2 by auto\n    then have n6787 : \"(\\<And>  b   .  b|\\<in>|B \\<Longrightarrow> (\\<exists> N. (\\<forall> n2 . (n2 > N \\<longrightarrow> (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> (P a b c d n2)))))))\"  by blast\n    def Q == \"\\<lambda> b n2. ((\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> (P a b c d n2))))\"\n    then have \"(\\<And>  b   .  b|\\<in>|B \\<Longrightarrow> (\\<exists> N. (\\<forall> n2 . (n2 > N \\<longrightarrow> Q b n2))))\" using n6787 by blast \n    then have \"\\<exists> N. (\\<forall>    b   .  b|\\<in>|B \\<longrightarrow>((\\<forall> n2 . (n2 > N \\<longrightarrow> Q b n2))))\" using n54687b  by auto\n    then show \"((\\<exists> N. (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))))\" using Q_def by blast\n  qed\n  then have \"(\\<exists> N. (\\<forall> a . (a |\\<in>| A \\<longrightarrow> (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2)))))))))\"\n  proof -\n    have \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N. (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))))\"  using j3 by auto\n    hence \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N.  (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d .\\<forall> n2. d |\\<in>| D \\<longrightarrow> (( (n2 > N \\<longrightarrow> P a b c d n2))))))))\"\n      by simp  \n    hence \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N.  (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow>(\\<forall> n2.  (\\<forall> d .d |\\<in>| D \\<longrightarrow> (( (n2 > N \\<longrightarrow> P a b c d n2)))))))))\"\n      by metis  \n    hence \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N.  (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> n2. (\\<forall> c. c |\\<in>| C \\<longrightarrow>( (\\<forall> d .d |\\<in>| D \\<longrightarrow> (( (n2 > N \\<longrightarrow> P a b c d n2))))))))))\"\n      by metis\n    hence \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N. (\\<forall> n2. (\\<forall> b. b|\\<in>|B \\<longrightarrow>   (\\<forall> c. c |\\<in>| C \\<longrightarrow>( (\\<forall> d .d |\\<in>| D \\<longrightarrow> (( (n2 > N \\<longrightarrow> P a b c d n2))))))))))\"\n      by metis\n    hence \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N. (\\<forall> n2. (n2 > N \\<longrightarrow>(\\<forall> b. b|\\<in>|B \\<longrightarrow>   (\\<forall> c. c |\\<in>| C \\<longrightarrow>( (\\<forall> d .d |\\<in>| D \\<longrightarrow> ((  P a b c d n2))))))))))\"\n      by metis\n    then have n6787 : \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N. (\\<forall> n2 . (n2 > N \\<longrightarrow>  (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> (P a b c d n2))))))))\" by auto\n    def Q == \"\\<lambda> a n2. (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> (P a b c d n2))))\"\n    then have \"(\\<And> a   . a |\\<in>| A \\<Longrightarrow> (\\<exists> N.(\\<forall> n2 . (n2 > N \\<longrightarrow>  Q a n2))))\" using n6787 by blast \n    then have \"\\<exists> N. (\\<forall>    a   .  a|\\<in>|A \\<longrightarrow>((\\<forall> n2 . (n2 > N \\<longrightarrow> Q a n2))))\" using n54687a  by auto\n    then show \"(\\<exists> N. (\\<forall> a . (a |\\<in>| A \\<longrightarrow> (\\<forall> b. b|\\<in>|B \\<longrightarrow>  (\\<forall> c. c |\\<in>| C \\<longrightarrow> (\\<forall> d . d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2)))))))))\" using Q_def by blast\n  qed\n  then show \"\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))\" by auto\n      \nqed\n  \n  \n    \n  \n  \nlemma piDeltaPhi :\n  shows \"(\\<Pi>\\<^sub>\\<phi> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)) = (\\<Pi>\\<^sub>\\<delta> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s))\" \nproof\n  show \"\\<Pi>\\<^sub>\\<phi> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s) \\<subseteq> UNION ((op ` \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> \\<circ> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i)) s) fset\" using pathsForForestLanguage_def  by (smt Collect_mono Union_eq comp_apply image_eqI notin_fset) \n  show \"UNION ((op ` \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> \\<circ> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i)) s) fset \\<subseteq> \\<Pi>\\<^sub>\\<phi> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)\" using pathsForForestLanguage_def  by (smt Collect_mono UNION_eq imageE notin_fset o_apply)\nqed\n  \n          \n  \nlemma plusUplusD :\n  assumes \"\\<And>x . (x |\\<in>| totalForests \\<Longrightarrow> (\\<Union>| (\\<Pi> |`| (x))) \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)))))))\"\n  assumes \"totalForest == \\<Union>|  totalForests\"\n    shows \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1))))))\" \nproof -                                     \n  \n  have \"(\\<forall> tr  . tr |\\<in>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<longrightarrow> (\\<exists> lang . lang |\\<in>| (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest ) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<and> subforest \\<in> lang)))) \"\n  proof \n    \n    show \"(\\<And> tr  . tr |\\<in>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<longrightarrow> (\\<exists> lang . lang |\\<in>| (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest ) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<and> subforest \\<in> lang))))\"\n    proof \n      show \"(\\<And> tr  . tr |\\<in>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<Longrightarrow> (\\<exists> lang . lang |\\<in>| (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest ) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<and> subforest \\<in> lang))))\"\n        proof -\n    fix path\n    assume \"path |\\<in>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest)\"\n    then obtain tr where \"tr |\\<in>| totalForest\" and \"path |\\<in>| \\<Pi> tr\" using pathsInForest_def using pathsTreeForest by blast \n    then obtain forest where ny66788 : \"forest |\\<in>| totalForests\" and \"tr |\\<in>| forest\" using assms(2)    by auto \n    then have \"(\\<Union>| (\\<Pi> |`| (forest))) \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1))))))\" using assms(1) by auto\n    then have a6587 : \"\\<And> tr . tr |\\<in>| (\\<Union>| (\\<Pi> |`| (forest))) \\<Longrightarrow> (\\<exists> lang . lang |\\<in>| (  ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Union>| (\\<Pi> |`| (forest))) \\<and> subforest \\<in> lang)))\" using biguplusForestsD_def by blast\n    have \"path |\\<in>| (\\<Union>| (\\<Pi> |`| (forest)))\"     using \\<open>path |\\<in>| \\<delta>\\<^sub>\\<tau> tr\\<close> \\<open>tr |\\<in>| forest\\<close> by blast \n        \n    then have \"(\\<exists> lang . lang |\\<in>| (  ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest) . (path |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Union>| (\\<Pi> |`| (forest))) \\<and> subforest \\<in> lang)))\" using a6587 by auto\n    then obtain lang where \"lang |\\<in>| (  ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1))\" and \"(\\<exists> (subforest) . (path |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Union>| (\\<Pi> |`| (forest))) \\<and> subforest \\<in> lang))\" by auto\n    then obtain subforest where \"lang |\\<in>| (  ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1))\" and \" (path |\\<in>| subforest)\" and n6798 : \" subforest |\\<subseteq>| (\\<Union>| (\\<Pi> |`| (forest)))\" and \"subforest \\<in> lang\" by auto\n        \n        \n    from n6798 assms(2) pathsInForest_def  ny66788 have \"(\\<Union>| (\\<Pi> |`| (forest))) |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest)\"       by (simp add: pathsInForest_def ffUnion_upper fimage_mono) \n    then have \"subforest |\\<subseteq>|\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest\" using n6798 by auto\n        \n        \n    then have \"lang |\\<in>| (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest ) . (path |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<and> subforest \\<in> lang))\"  using \\<open>lang |\\<in>| (op ` \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> \\<circ> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1\\<close> \\<open>path |\\<in>| subforest\\<close> \\<open>subforest \\<in> lang\\<close> by auto\n        \n    then have \"(\\<exists> lang . lang |\\<in>| (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest ) . (path |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<and> subforest \\<in> lang)))\" by auto\n    then show \"(\\<exists> lang . lang |\\<in>| (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1)) \\<and> (\\<exists> (subforest ) . (path |\\<in>| subforest \\<and> subforest |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) \\<and> subforest \\<in> lang)))\" by auto\n  qed\nqed\nqed\nthen show \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> aut) |`| Sa1))))))\" using biguplusForestsD_def by blast\nqed\n  \n        \n        \n\n        \n    \nlemma psiSigmaDClosedUnderPlus0 :\n  fixes totalForestForPath totalForests\n  fixes forest\n    fixes Sa1 Sa2\n  defines \"totalForest == \\<Union>|  totalForests\"\n    assumes \"\\<And>x . (x |\\<in>| totalForests \\<Longrightarrow> (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x) \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))\" \n    shows \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\" \nproof -\n  from assms(2) have n766787 : \"\\<And>x . (x |\\<in>| totalForests \\<Longrightarrow> (\\<Union>| (\\<Pi> |`| (x))) \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))\"   using pathsInForest_def by metis\n  then have  \"\\<And>x . (x |\\<in>| totalForests \\<Longrightarrow> (\\<Union>| (\\<Pi> |`| (x))) \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)))))))\" using n766787 \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>_def  by auto\n  then have n76898 : \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1))))))\"  using assms  using plusUplusD by blast  \n  from n766787 have  \"\\<And>x . (x |\\<in>| totalForests \\<Longrightarrow> (\\<Union>| (\\<Pi> |`| (x))) \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>2) |`| Sa2)))))))\" using n766787 \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>_def  by auto\n  then have n657 : \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>2) |`| Sa2))))))\"  using assms  using plusUplusD by blast  \n  from n76898 n657 show \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\" using \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>_def by blast\nqed\n  \n  \n  \nlemma psiSigmaDClosedUnderPlus :\n  fixes totalForestForPath\n  fixes forest\n    fixes Sa1 Sa2\n  defines \"totalForest == \\<Union>|  (totalForestForPath  |`| (\\<Pi> ( forest)))\"\n    assumes \"\\<And>x . (x |\\<in>| \\<Pi> ( forest) \\<Longrightarrow> (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  (totalForestForPath x)) \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))\" \n    shows \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\" \nusing psiSigmaDClosedUnderPlus0 using assms(2) totalForest_def by blast\n  \n    \n      \nlemma constantLemma :\n  fixes s\n  fixes Sa1\n  fixes Sa2\n  fixes i\n  assumes y1 : \"((s |\\<in>| (state_set) (\\<A> i)))\"\n  assumes y2 : \"(( Sa1 |\\<subseteq>| (state_set) \\<A>\\<^sub>1))\"\n  assumes y3 : \"(( Sa2 |\\<subseteq>| (state_set) \\<A>\\<^sub>2))\"\n  shows \"\\<exists> N. constantIsSuitableForStates i s Sa1 Sa2 N\"\nproof -\n  def auti == \"\\<A> i\"\n  def LSa == \"(\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>  Sa1 Sa2)\"\n  def LS == \"\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> auti s\"\n  def I == \"(\\<Pi>\\<^sub>\\<delta> LS) - (\\<Pi>\\<^sub>\\<delta> LSa)\"\n  have 0 : \"I \\<in> \\<I>\" \n  proof -\n    from y1 y2 y3 auti_def LSa_def LS_def obtain setPair where y4 : \"(\n                              (*  (((s |\\<in>| (state_set) (\\<A> i))) \\<and> ((( Sa1 |\\<subseteq>| (state_set) \\<A>\\<^sub>1))) \\<and> (( Sa2 |\\<subseteq>| (state_set) \\<A>\\<^sub>2)) \\<and>*)\n                                (\\<pi>\\<^sup>1 setPair = (\\<Pi>\\<^sub>\\<phi> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s))) \n                              \\<and> (\\<pi>\\<^sup>2 setPair = UNION (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) fset))\" by (meson fst_conv snd_conv)\n    from auti_def y4 I_def LSa_def LS_def piDeltaPhi have y5 : \"I = (\\<lambda>pair . \\<pi>\\<^sup>1 pair - \\<pi>\\<^sup>2 pair) setPair\" by auto\n    from y4   have \"\\<exists>i Sa1 Sa2 s. \\<pi>\\<^sup>1 setPair = \\<Pi>\\<^sub>\\<phi> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s) \\<and> \\<pi>\\<^sup>2 setPair = UNION (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) fset\" by auto\n    then show \"I \\<in> \\<I>\"  using \\<I>_def      by (simp add: \\<I>_def y5)\n  qed\n  have n545688 : \"(\\<not> ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) \\<Turnstile> I))) \\<Longrightarrow> (\\<exists>n. (\\<forall> n2 . (n2 \\<ge> n \\<longrightarrow> (realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)))))\"\n  proof -\n    assume \"\\<not> ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) \\<Turnstile> I))\"\n    then obtain forest where a7 : \"forest \\<in> ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s)))\" and a8 : \"(fset (\\<Pi> forest)) \\<inter> I = {}\"       using entails_altdef by blast\n    have n65687a : \"(fset (\\<Pi> ( forest))) \\<subseteq> \\<Pi>\\<^sub>\\<delta> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)\"\n    proof -\n      from a7 have  a7 : \"forest \\<in> ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s)))\" by auto\n      hence a8 : \"(finsert forest {||}) \\<in> ( \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)\"           by (simp add: forest_language_for_state_def language_for_state_def) \n      hence a78775 : \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (finsert forest {||}) \\<in> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)  \"           by auto   \n      have \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (finsert forest {||}) = \\<Pi> ( forest)\" (*using pathsInForest_def *)\n      proof\n        fix x\n        show \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> {|forest|} |\\<subseteq>| \\<delta>\\<^sub>\\<tau> forest\" using pathsInForest_def          by (metis fsingleton_iff fsubsetI pathsTreeForest)\n        show \"\\<delta>\\<^sub>\\<tau> forest |\\<subseteq>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> {|forest|} \"  using pathsInForest_def          by (metis fsingleton_iff fsubsetI pathsTreeForest)\n      qed\n      hence \"\\<Pi> ( forest) \\<in> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)  \"    using a78775    by auto\n      then show \"(fset (\\<Pi> ( forest))) \\<subseteq> \\<Pi>\\<^sub>\\<delta> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)  \"               by blast\n    qed\n    have n65687 : \"(fset (\\<Pi> forest)) \\<subseteq> \\<Pi>\\<^sub>\\<delta> LS\"\n    proof \n      fix x\n      assume n56898 : \"x \\<in> fset (\\<delta>\\<^sub>\\<tau> forest)\"\n      from n65687a have \"(fset (\\<Pi> ( forest))) \\<subseteq> \\<Pi>\\<^sub>\\<delta> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)  \"               by blast\n      hence \"x \\<in> \\<Pi>\\<^sub>\\<delta> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)  \" using n56898  by auto\n      then show \"x \\<in> \\<Pi>\\<^sub>\\<delta> LS\" using LS_def auti_def by auto\n    qed\n    then have n65489 : \"(fset (\\<Pi> forest)) \\<subseteq> \\<Pi>\\<^sub>\\<delta> LSa\" using I_def a8 by blast\n    show \" \\<exists>n. (\\<forall> n2 . (n2 \\<ge> n \\<longrightarrow> (realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset))))\"\n    proof -\n        fix n\n        from realizedIn_def have \"((realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s)   (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))) = (\\<exists>\\<gg>. \\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) \\<and> fset (\\<Pi> \\<gg>) \\<subseteq> (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))))\" by auto\n        from a7 have  a7 : \"forest \\<in> ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s)))\" by auto\n        from n65687a  have \"(fset (\\<Pi> ( forest))) \\<subseteq> \\<Pi>\\<^sub>\\<delta> (\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) s)\" by auto\n        have n54568 : \"\\<exists> fullHeight . (\\<forall> path . (path |\\<in>| (\\<Pi> ( forest)) \\<longrightarrow> (\\<forall> n2 . n2 \\<ge> fullHeight \\<longrightarrow> (path \\<in> (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))))))\"\n        proof -\n          from n65687a notin_fset n65489 LSa_def    have n8768 : \"\\<And>path. path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> path \\<in> UNION (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) fset\" by (metis (no_types, lifting) subsetCE) \n          have n656787 : \"\\<And>path. path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (\\<exists> pathsetForPath . (path |\\<in>| (pathsetForPath ) \\<and> (pathsetForPath ) \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)))\" using notin_fset  n8768   UN_iff               by (metis (full_types)) \n          def pathsetForPath == \"\\<lambda> path. (SOME pathset. (path |\\<in>| pathset \\<and> pathset \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)))\"\n          have n7687 : \"\\<And>path. path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (path |\\<in>| (pathsetForPath path) \\<and> (pathsetForPath path) \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))\" using n656787 pathsetForPath_def    by (smt someI_ex) \n          have a90 : \"\\<And> path tr . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> tr |\\<in>| (pathsetForPath path) \\<Longrightarrow> (\\<exists> lang . lang |\\<in>| ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)) \\<and> (\\<exists> (subforest) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (pathsetForPath path) \\<and> subforest \\<in> lang)))\"\n          proof -\n            fix path\n            assume n767898 : \"path |\\<in>| (\\<Pi> ( forest))\"\n            def pathset == \"pathsetForPath path\"\n            from n7687 n767898 pathset_def  have a20 : \"path |\\<in>| pathset\" and a21 : \"pathset \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\"     by auto\n            from a21 have \"\\<And>path. path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> pathset \\<in> ( (((\\<Uplus>\\<^sub>\\<delta> ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)))))) \" using \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>_def by auto\n            hence \"\\<And> tr . tr |\\<in>| pathset \\<Longrightarrow> (\\<exists> lang . lang |\\<in>| ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)) \\<and> (\\<exists> (subforest) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| pathset \\<and> subforest \\<in> lang)))\" using biguplusForestsD_def           by (smt IntE \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta>_def a21 mem_Collect_eq) \n            then show \"\\<And>  tr .   tr |\\<in>| (pathsetForPath path) \\<Longrightarrow> (\\<exists> lang . lang |\\<in>| ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)) \\<and> (\\<exists> (subforest) . (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (pathsetForPath path) \\<and> subforest \\<in> lang)))\" using pathset_def by auto\n          qed\n          def pathsetForEachPath == \"\\<lambda> path tr. (SOME  subforest. (\\<exists> lang . lang |\\<in>| ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)) \\<and> ( (tr |\\<in>| subforest \\<and> subforest |\\<subseteq>| (pathsetForPath path) \\<and> subforest \\<in> lang))))\"\n          have n8775 : \"\\<And>path tr . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow>tr |\\<in>| (pathsetForPath path) \\<Longrightarrow> (\\<exists> lang . lang |\\<in>| ( ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)) \\<and> ((tr |\\<in>| (pathsetForEachPath path tr) \\<and> (pathsetForEachPath path tr) |\\<subseteq>| (pathsetForPath path) \\<and> (pathsetForEachPath path tr) \\<in> lang)))\" using a90 pathsetForEachPath_def              by (smt someI_ex) \n          hence n6798 : \"\\<And>path tr . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow>tr |\\<in>| (pathsetForPath path) \\<Longrightarrow> (\\<exists> forest . \\<exists> lang . \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> forest = (pathsetForEachPath path tr) \\<and> forest \\<in> lang \\<and> lang |\\<in>| ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)))\"  by fastforce  \n          def forestsForEachPath == \"\\<lambda> path tr . (SOME forest. (\\<exists> lang . \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> forest = (pathsetForEachPath path tr) \\<and> forest \\<in> lang \\<and> lang |\\<in>| ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1))))\"\n          then have n657897 : \"\\<And>path tr . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> tr |\\<in>| (pathsetForPath path) \\<Longrightarrow> ( \\<exists> lang . \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (forestsForEachPath path tr) = (pathsetForEachPath path tr) \\<and> (forestsForEachPath path tr) \\<in> lang \\<and> lang |\\<in>| ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> \\<A>\\<^sub>1) |`| Sa1)))\" using n6798        by (smt someI_ex) \n          have n7698 : \"\\<And>path . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (\\<exists>  totalForest .(pathsetForPath path = \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<and>  (\\<exists> heightForForest .((\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)) \\<and> (\\<forall> t n2. t |\\<in>| totalForest \\<longrightarrow> heightForForest \\<le> n2 \\<longrightarrow> height t \\<le>  n2)))))\"\n          proof -\n            fix path\n            assume \"path |\\<in>| (\\<Pi> ( forest))\"\n            def pathset == \"pathsetForPath path\"\n            def totalForest == \"\\<Union>| ((forestsForEachPath path) |`| pathset)\"\n            def totalForestPathset == \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (\\<Union>| ((forestsForEachPath path) |`| pathset))\"\n            have n657o98 : \"totalForestPathset = pathset\" proof\n              show \"totalForestPathset |\\<subseteq>| pathset\" \n              proof\n                fix x\n                assume \" x |\\<in>| totalForestPathset \"\n                then obtain oldTree where \"oldTree |\\<in>| (\\<Union>| ((forestsForEachPath path) |`| pathset))\" and \"x |\\<in>| \\<Pi> oldTree\" using totalForestPathset_def               using pathsTreeForest by blast\n                then obtain path2 where \"path2 |\\<in>| pathset\" and \"oldTree |\\<in>| ((forestsForEachPath path)  path2)\"               by auto \n                then show \"x |\\<in>| pathset\" using n8775      \\<open>x |\\<in>| \\<delta>\\<^sub>\\<tau> oldTree\\<close> less_eq_fset.rep_eq n657897 notin_fset pathsTreeForest subsetCE               by (smt \\<open>path |\\<in>| \\<delta>\\<^sub>\\<tau> forest\\<close> fset_mp pathset_def) \n              qed\n              show \"pathset |\\<subseteq>| totalForestPathset\"\n              proof \n                fix x\n                assume n87789 : \" x |\\<in>| pathset\"\n                hence \"x |\\<in>| ((pathsetForEachPath path) x)\" using n8775               using \\<open>path |\\<in>| \\<delta>\\<^sub>\\<tau> forest\\<close> pathset_def by blast \n                then show \"x |\\<in>| totalForestPathset\" using n87789 totalForestPathset_def      ffUnionI fimage_eqI n657897 pathsTreeForest               by (metis \\<open>path |\\<in>| \\<delta>\\<^sub>\\<tau> forest\\<close> pathset_def)\n              qed\n            qed\n            then have n876765 : \"(\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))\" using  totalForestPathset_def totalForest_def           by (simp add: \\<open>path |\\<in>| \\<delta>\\<^sub>\\<tau> forest\\<close> n7687 pathset_def) \n            def heightForForest == \"maxFset (height |`| totalForest)\"\n            have \"\\<And>t . t |\\<in>| totalForest \\<Longrightarrow> height t \\<le> heightForForest\" using heightForForest_def finiteMaxExists(1) by simp\n            have n545787 : \"\\<And>t n2 . t |\\<in>| totalForest \\<Longrightarrow> heightForForest \\<le> n2 \\<Longrightarrow> height t \\<le>  n2\" using heightForForest_def finiteMaxExists(1)                 using \\<open>\\<And>ta. ta |\\<in>| totalForest \\<Longrightarrow> height ta \\<le> heightForForest\\<close> dual_order.trans by blast \n            from n876765 n545787 n657o98 totalForest_def totalForestPathset_def show \"(\\<exists>  totalForest .(pathsetForPath path = \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<and>  (\\<exists> heightForForest .((\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)) \\<and> (\\<forall> t n2. t |\\<in>| totalForest \\<longrightarrow> heightForForest \\<le> n2 \\<longrightarrow> height t \\<le>  n2)))))\"             by (metis pathset_def)\n          qed\n          def isGood == \"\\<lambda> (path :: abc list) totalForest .(pathsetForPath path = \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<and> (\\<exists> heightForForest .((\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)) \\<and> (\\<forall> t n2. t |\\<in>| totalForest \\<longrightarrow> heightForForest \\<le> n2 \\<longrightarrow> height t \\<le>  n2))))\"\n          from n7698 have n7698b : \"\\<And>path . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (\\<exists>  totalForest .isGood path totalForest)\" using isGood_def by auto\n          def totalForestForPath ==   \"\\<lambda> (path :: abc list) .(SOME totalForest. isGood path totalForest)\"\n          from n7698 totalForestForPath_def            have n545787 : \"\\<And>(path :: abc list) . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> isGood path (totalForestForPath path)\" using someI_ex    by (simp add: someI_ex n7698b) \n          then have n659 : \"\\<And>(path :: abc list) . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> ((\\<exists> heightForForest .(((\\<forall> t n2. t |\\<in>|  (totalForestForPath path) \\<longrightarrow> heightForForest \\<le> n2 \\<longrightarrow> height t \\<le>  n2)))))\" using isGood_def by blast\n          def totalForest == \"\\<Union>|  (totalForestForPath  |`| (\\<Pi> ( forest)))\"\n          have \"\\<Pi> ( forest) |\\<subseteq>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest\" \n          proof\n            fix x\n            assume \"x |\\<in>| \\<Pi> ( forest)\"\n            hence \"x |\\<in>| (pathsetForPath  x)\"            by (simp add: n7687)\n            hence \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  (totalForestForPath x)\"                using \\<open>x |\\<in>| \\<delta>\\<^sub>\\<tau> forest\\<close> isGood_def n545787 by auto\n            then show \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest\"                by (metis \\<open>x |\\<in>| \\<delta>\\<^sub>\\<tau> forest\\<close> ffUnionI fimage_eqI pathsTreeForest totalForest_def) \n          qed\n          have n54e7 :  \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\" \n          proof -\n            have \"\\<And>x . x |\\<in>| \\<Pi> ( forest) \\<Longrightarrow> (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  (totalForestForPath x)) \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\"                  using isGood_def n545787 by blast\n            then show \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2)\" using totalForest_def psiSigmaDClosedUnderPlus by blast\n          qed\n          def heightIsGood == \"\\<lambda> path heightForForest . (\\<forall> t n2. t |\\<in>| (totalForestForPath path) \\<longrightarrow> heightForForest \\<le> n2 \\<longrightarrow> height t \\<le>  n2)\"\n          from n659 heightIsGood_def have n546898 : \"\\<And>(path :: abc list) . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (\\<exists> heightForForest. heightIsGood path heightForForest)\" by auto\n          def sufficientHeights == \"\\<lambda> path. (SOME heightForForest.(heightIsGood path heightForForest))\"\n          from n546898 sufficientHeights_def n659  have n56898 : \"\\<And>(path :: abc list) . path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (heightIsGood path (sufficientHeights path))\" using someI_ex by (simp add: someI_ex)\n          def goodHeight == \"maxFset (sufficientHeights |`| (\\<Pi> ( forest)))\"\n          from goodHeight_def finiteMaxExists(1) totalForest_def n56898 heightIsGood_def have \"(((\\<forall> t n2. t |\\<in>|  (totalForest) \\<longrightarrow> goodHeight \\<le> n2 \\<longrightarrow> height t \\<le>  n2)))\"  by (smt ffUnionLemma fimageE fimage_eqI le_trans)\n          hence \"\\<And> n2 .goodHeight \\<le> n2 \\<Longrightarrow>totalForest \\<in> (fset (boundedForests  n2))\" using  restrictionIsFiniteForests   by blast\n          hence \"\\<And> n2 .goodHeight \\<le> n2 \\<Longrightarrow>totalForest |\\<in>| ((boundedForests  n2))\" using   notin_fset               by fastforce  \n          then have \"\\<And> n2 .goodHeight \\<le> n2 \\<Longrightarrow> (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest) |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> |`| (inf_fset2 (boundedForests n2) {f . (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> f \\<in> (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))} )\"  using n54e7\n          proof -\n            fix n2 :: nat\n            assume a1: \"goodHeight \\<le> n2\"\n            have \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2\"\n              by (metis \\<open>\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest \\<in> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2\\<close>)\n            then have f2: \"totalForest \\<in> {f. \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> f \\<in> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2}\"\n              by blast\n            have \"totalForest |\\<in>| boundedForests n2\"\n              using a1 \\<open>\\<And>n2. goodHeight \\<le> n2 \\<Longrightarrow> totalForest |\\<in>| boundedForests n2\\<close> by auto\n            then show \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> |`| inf_fset2 (boundedForests n2) {f. \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> f \\<in> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2}\"\n              using f2 by blast\n          qed\n          then have \" (\\<forall> path . (path |\\<in>| (\\<Pi> ( forest)) \\<longrightarrow> (\\<forall> n2 . n2 \\<ge> goodHeight \\<longrightarrow> (path \\<in> (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))))))\"             by (metis Collect_cong \\<Z>\\<^sub>\\<delta>_def \\<open>\\<delta>\\<^sub>\\<tau> forest |\\<subseteq>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> totalForest\\<close> ffUnion.rep_eq ffUnionI fset_mp notin_fset)\n          then show \"\\<exists> fullHeight . (\\<forall> path . (path |\\<in>| (\\<Pi> ( forest)) \\<longrightarrow> (\\<forall> n2 . n2 \\<ge> fullHeight \\<longrightarrow> (path \\<in> (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))))))\" by auto\n        qed\n        def fullHeight == \"SOME fullHeight. ((\\<forall> path . (path |\\<in>| (\\<Pi> ( forest)) \\<longrightarrow> (\\<forall> n2 . n2 \\<ge> fullHeight \\<longrightarrow> (path \\<in> (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) ))))))))\"\n        hence \"(\\<And> path . (path |\\<in>| (\\<Pi> ( forest)) \\<Longrightarrow> (\\<And> n2 . n2 \\<ge> fullHeight \\<Longrightarrow> (path \\<in> (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) )))))))\" using n54568 someI_ex  LSa_def   by smt\n        then have \"(\\<And> n2 . n2 \\<ge> fullHeight \\<longrightarrow> fset (\\<Pi> forest) \\<subseteq> (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset))\"          by (meson notin_fset subsetI)\n        then have \"(\\<And> n2 . n2 \\<ge> fullHeight \\<longrightarrow> (realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)))\"          using a7 realizedIn_def\n        proof -\n          fix n2 :: nat\n          { assume \"\\<exists>t. t \\<in> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s \\<and> fset (\\<delta>\\<^sub>\\<tau> t) \\<subseteq> UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset\"\n            then have \"fullHeight \\<le> n2 \\<longrightarrow> realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)\"              by (meson realizedIn_def) }\n          then show \"fullHeight \\<le> n2 \\<longrightarrow> realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)\"            using \\<open>\\<And>n2. fullHeight \\<le> n2 \\<longrightarrow> fset (\\<delta>\\<^sub>\\<tau> forest) \\<subseteq> UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset\\<close> a7 by blast\n        qed \n        then show \" \\<exists>n. (\\<forall> n2 . (n2 \\<ge> n \\<longrightarrow> (realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset))))\" by auto\n    qed\n  qed\n  then have n545688b : \" \\<exists>n. ((\\<not> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s \\<Turnstile> I) \\<longrightarrow> (\\<forall>n2\\<ge>n. realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)))\" by blast\n  def constantForStates == \"SOME n. ((\\<not> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s \\<Turnstile> I) \\<longrightarrow> (\\<forall>n2\\<ge>n. realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)))\"\n  from n545688b constantForStates_def have n65687 : \" ((\\<not> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s \\<Turnstile> I) \\<longrightarrow> (\\<forall>n2\\<ge>constantForStates. realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset)))\" using someI_ex by smt\n  hence n65687b : \"(\\<And>n2. n2 \\<ge>constantForStates \\<Longrightarrow> ( ((\\<not> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s \\<Turnstile> I) \\<Longrightarrow> realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) (UNION (fset (\\<Z>\\<^sub>\\<delta> n2 (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2))) fset))))\" by auto\n      have n545787 : \"((I \\<inter> \\<Pi>\\<^sub>\\<delta> ( (( \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2  )))) = {})\"        using I_def LSa_def by blast\n  have \"(((\\<And> n . ((Suc n > constantForStates) \\<Longrightarrow> ((\\<not>(realizedIn    (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s)      (\\<Pi>\\<^sub>\\<delta> (fset (\\<Z>\\<^sub>\\<delta> n (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2) ))) ) )   \\<Longrightarrow> ( ( ( (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) s) \\<Turnstile> I)  \\<and> ((I \\<inter> \\<Pi>\\<^sub>\\<delta> ( (( \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<sigma>\\<^sub>\\<delta> Sa1 Sa2  )))) = {}))))))))\" using n545787 n65687b by auto\n  then have \"constantIsSuitableForStates i s Sa1 Sa2 constantForStates\" using constantIsSuitableForStates_def 0 by auto\n  then show \"\\<exists> N. constantIsSuitableForStates i s Sa1 Sa2 N\" by auto\nqed\n    \n  \n  \n  \n  \n  \n  \nlemma greaterConstantsAreGood :\n  fixes s\n  fixes Sa1\n  fixes Sa2\n  fixes i\n  assumes \"((s |\\<in>| (state_set) (\\<A> i)))\"\n  assumes \"(( Sa1 |\\<subseteq>| (state_set) \\<A>\\<^sub>1))\"\n  assumes \"(( Sa2 |\\<subseteq>| (state_set) \\<A>\\<^sub>2))\"\n  fixes n\n  fixes N\n  assumes \"constantIsSuitableForStates i s Sa1 Sa2 N\"\n  assumes \"n > N\"\n  shows \"constantIsSuitableForStates i s Sa1 Sa2 n\"\n  by (meson assms constantIsSuitableForStates_def less_trans)\n    \n    \n    \n    \nlemma n67789564 : \n              assumes \"(x |\\<in>| (fimage f ((\\<Union>| (fimage g h)))))\"\n              obtains child where \"child |\\<in>| h\" and \"x |\\<in>| (fimage f (g child))\"\n  using assms by auto\n                \n    \n    \ndefinition realizesUniv where \"realizesUniv n = (\\<forall> i \\<alpha> r n2. (Suc n2 > n \\<longrightarrow> (r |\\<in>| rule_set (\\<A> i) \\<longrightarrow> symbol r = \\<alpha> \\<longrightarrow> (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) r) (\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> n2 UNIV) \\<union> {[]}))))))\"\n  \n  \nlemma pathsSingeton :\n  shows \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (finsert tr {||}) = \\<Pi> tr\"\nproof\n  show \" \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> {|tr|} |\\<subseteq>| \\<Pi> tr\"  using pathsInForest_def    by (metis fsingleton_iff fsubsetI pathsTreeForest)\n      show \"\\<Pi> tr |\\<subseteq>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> {|tr|} \" using pathsInForest_def    by (metis fsingleton_iff fsubsetI pathsTreeForest)\n  qed\n  \n  \nlemma rootRule :\n  assumes \"tr \\<in> ((\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> i) rule))\"\n  shows  \"symbol rule = root tr\"\n  by (metis assms language_for_rule_def mem_Collect_eq tree_for_rule_def) \n    \n    \nlemma  commuteExistsAll3 : \"\\<And> (D :: 'a fset) (P :: 'a \\<Rightarrow> nat \\<Rightarrow> bool) . ((\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. P (d :: 'a) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2))\"\n  using commuteExistsAll by blast\n  \n    \n    \nlemma realizedInUniv1:\n  assumes rulesLangsNonempty : \"\\<And> \\<R> i r . (r |\\<in>| rule_set (\\<A> i) \\<Longrightarrow>  ((\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> i) r)  \\<noteq> {}))\"\n  shows \"\\<exists> n . realizesUniv n\"\nproof -\n  def heightPerRule == \"\\<lambda> i . \\<lambda> rule . (SOME goodHeight . ( (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) ((symbol rule) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> goodHeight UNIV) \\<union> {[]})))))\"\n  have n6567987 : \"\\<And>i rule . (rule |\\<in>| rule_set (\\<A> i) \\<Longrightarrow> (\\<exists> goodHeight.(\\<forall> ht.(ht > goodHeight \\<longrightarrow>  (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) ((symbol rule) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]})))))))\"\n  proof -\n    fix i rule\n    assume \"rule |\\<in>| rule_set (\\<A> i)\"\n    then obtain tr where n1 : \"tr \\<in> ((\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> i) rule))\" using assms        by auto\n    def forest == \"(finsert tr {||})\"\n    have n65687 : \"forest \\<in> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule)\" using n1 forest_def by (simp add: forest_language_for_rule_def language_for_rule_def) \n    def goodHeight == \"height tr\"\n    have \"\\<And> ht child. ht > goodHeight \\<Longrightarrow> child |\\<in>| childrenSet tr \\<Longrightarrow> child |\\<in>| \\<Z>\\<^sub>\\<tau> ht UNIV\" using Z_def \\<Z>\\<tau>_lemma goodHeight_def heightOfChild notin_fset by fastforce \n        \n        \n        \n    have n7588 : \"\\<And> ht child. ht > goodHeight \\<Longrightarrow> child |\\<in>| childrenSet tr \\<Longrightarrow> (fset (\\<Pi> child)) \\<subseteq> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV))\" using pathsForTreeLanguage_def \\<Z>\\<tau>_lemma mem_Collect_eq notin_fset subsetI  by (smt UNIV_I Z_def goodHeight_def heightOfChild less_imp_le_nat order_trans)\n        \n    have n65458 :  \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> forest = \\<Pi> tr\" using forest_def pathsSingeton by auto\n        \n    from n1   have n54687 : \"symbol rule = root tr\"  using rootRule by auto\n        \n    have \"\\<And> ht . ht > goodHeight \\<Longrightarrow> fset (\\<Pi> tr) \\<subseteq> ((root tr) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))\" \n    proof \n      fix x\n      assume a7678 : \"x \\<in> fset (\\<delta>\\<^sub>\\<tau> tr)\"\n        \n      obtain \\<alpha> children where n54457 : \"tr = NODE \\<alpha> children\"\n        using tree.exhaust by auto \n      hence \"x \\<in> fset (fimage (\\<lambda> tail.( \\<alpha>#tail)) ((\\<Union>| (fimage \\<Pi> children)) |\\<union>|  (finsert [] {||})))\" using pathAlternateDef notin_fset  a7678 by auto\n      hence n6587 : \"x |\\<in>| (fimage (\\<lambda> tail.( \\<alpha>#tail)) ((\\<Union>| (fimage \\<Pi> children)) |\\<union>|  (finsert [] {||})))\" using  notin_fset  by metis\n      have n656898 : \"childrenSet tr = children\" using n54457 by auto\n      have n656898b : \"root tr = \\<alpha>\" using n54457 by auto\n          \n      show \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> ((root tr) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))\" \n      proof (rule disjE)\n        from n6587 show \"(x |\\<in>| (fimage (\\<lambda> tail.( \\<alpha>#tail)) ((\\<Union>| (fimage \\<Pi> children))))) \\<or> (x |\\<in>| (fimage (\\<lambda> tail.( \\<alpha>#tail))  (finsert [] {||})))\" by blast\n        {\n          assume \"(x |\\<in>| (fimage (\\<lambda> tail.( \\<alpha>#tail)) ((\\<Union>| (fimage \\<Pi> children)))))\"\n          then obtain child where \"child |\\<in>| children\" and \"x |\\<in>| (fimage (\\<lambda> tail.( \\<alpha>#tail)) (\\<Pi> child))\" using n67789564 by auto\n          then have n5458o98 : \"x \\<in> (image (\\<lambda> tail.( \\<alpha>#tail)) (fset (\\<Pi> child)))\" using notin_fset\n            by force \n          from n6587 n656898 n5458o98 have \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> (image (\\<lambda> tail.( \\<alpha>#tail)) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV)))\"\n            using \\<open>child |\\<in>| children\\<close> n7588 by fastforce \n          then have \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> (image (\\<lambda> tail.( (root tr)#tail)) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV)))\" using n656898b by auto\n          then have \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> (image (\\<lambda> tail.( (root tr)#tail)) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))\" by auto\n          then show \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> ((root tr) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))\" using prefixLetter_def by auto\n        }\n        {\n          assume \"(x |\\<in>| (fimage (\\<lambda> tail.( \\<alpha>#tail))  (finsert [] {||})))\"\n          then have \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> (image (\\<lambda> tail.( (root tr)#tail)) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))\" using n656898b by auto\n          then show \"\\<And> ht . ht > goodHeight \\<Longrightarrow>x \\<in> ((root tr) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))\" using prefixLetter_def by auto\n        }\n      qed\n    qed\n    then have \"((\\<And> ht.(ht > goodHeight \\<Longrightarrow>  (forest \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule \\<and>  fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> forest) \\<subseteq> root tr \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]})))))\" using realizedInForest_def n65687 n65458  n54687 by auto\n    then have \"((\\<And> ht.(ht > goodHeight \\<Longrightarrow>  (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) ((root tr) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))))))\" using realizedInForest_def n65687 n65458  n54687 by blast\n    then have \"((\\<And> ht.(ht > goodHeight \\<Longrightarrow>  (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) ((symbol rule) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))))))\" using  n54687 by simp\n    then show \"(\\<exists> goodHeight.(\\<forall> ht.(ht > goodHeight \\<longrightarrow>  (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) ((symbol rule) \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))))))\" by auto\n  qed\n    \n  from n6567987 have n6587 : \"\\<And>i. \\<exists>goodHeight. (\\<forall> ht . (ht>goodHeight \\<longrightarrow>  (\\<forall> rule. rule |\\<in>| rule_set (\\<A> i) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]})))))\"  \n  proof -\n    fix i\n    def P == \"\\<lambda> rule ht . (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]})))\"\n    from commuteExistsAll2 have \"\\<And> (D :: (stt,abc) rule fset) (P :: (stt,abc) rule \\<Rightarrow> nat \\<Rightarrow> bool) . ((\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. P (d :: (stt,abc) rule) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2))\" by blast\n        \n    hence \"\\<And> (D :: (stt,abc) rule fset)  . ((\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. P (d :: (stt,abc) rule) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2))\" by auto\n    hence ny687 : \"((\\<And>d. d |\\<in>| (rule_set (\\<A> i)) \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. P (d :: (stt,abc) rule) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| (rule_set (\\<A> i)) \\<longrightarrow> (\\<forall>n2>N. P d n2))\" by auto\n    have \"(\\<And>d. d |\\<in>| (rule_set (\\<A> i)) \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. P (d :: (stt,abc) rule) n2)\" using P_def n6567987\n      by simp \n    hence \"\\<exists>N. \\<forall>d. d |\\<in>| (rule_set (\\<A> i)) \\<longrightarrow> (\\<forall>n2>N. P d n2)\" using ny687 by auto\n    then show \"\\<exists>goodHeight. (\\<forall> ht . (ht>goodHeight \\<longrightarrow>  (\\<forall> rule. rule |\\<in>| rule_set (\\<A> i) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]})))))\"   using P_def by blast\n  qed\n    \n  def Q == \"\\<lambda> i ht. (\\<forall> rule. rule |\\<in>| rule_set (\\<A> i) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]})))\"\n    \n  def D == \" (finsert \\<aa>\\<^sub>1  (finsert \\<aa>\\<^sub>2 fempty))\"\n  have n767987 : \"\\<And>i .i |\\<in>| D\" using D_def \\<A>.cases by blast \n      \n      \n  from commuteExistsAll2 have \"\\<And> (D :: ot fset) (P :: ot \\<Rightarrow> nat \\<Rightarrow> bool) . ((\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. P (d :: ot ) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. P d n2))\" by blast\n      \n  hence \"\\<And> (D :: ot fset)  . ((\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. Q (d :: ot ) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. Q d n2))\" by auto\n  hence n76898 : \"((\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. Q (d :: ot ) n2) \\<Longrightarrow> \\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. Q d n2))\" by auto\n  have \"(\\<And>d. d |\\<in>| D \\<Longrightarrow> \\<exists>n. \\<forall>n2>n. Q (d :: ot ) n2)\"  using Q_def n6587 by auto \n  hence \"\\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. Q d n2)\" using n76898 by auto\n  hence \"\\<exists>N. \\<forall>d. d |\\<in>| D \\<longrightarrow> (\\<forall>n2>N. (\\<forall> rule. rule |\\<in>| rule_set (\\<A> d) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> d) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> n2 UNIV) \\<union> {[]}))))\" using Q_def by auto\n      \n  hence \"\\<exists>N. \\<forall>d.  (\\<forall>n2>N. (\\<forall> rule. rule |\\<in>| rule_set (\\<A> d) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> d) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> n2 UNIV) \\<union> {[]}))))\" using n767987 by auto\n  then have \"\\<exists>goodHeight. (\\<forall> i. (\\<forall> ht . (ht>goodHeight \\<longrightarrow>  (\\<forall> rule. rule |\\<in>| rule_set (\\<A> i) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))))))\"  using commuteExistsAll n6587 by auto \n  then have \"\\<exists>goodHeight. (\\<forall> \\<alpha> . (\\<forall> i. (\\<forall> ht . (ht>goodHeight \\<longrightarrow>  (\\<forall> rule. rule |\\<in>| rule_set (\\<A> i) \\<longrightarrow> (\\<alpha> = (symbol rule) \\<longrightarrow> realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) rule) (symbol rule \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> ht UNIV) \\<union> {[]}))))))))\" by auto\n  then show \" \\<exists>n. realizesUniv n\" using realizesUniv_def by blast\nqed\n  \n  \n  \n  \n    \n    \ndefinition \\<N> :: \"nat\" where\n  \"\\<N> = (SOME N.(constantIsSuitableForAllStates N \\<and> realizesUniv N \\<and> 1 \\<le> N))\"\n  \n  \nlemma stateSets : \"(state_set (\\<A> \\<aa>\\<^sub>1)) = (state_set (\\<A> \\<aa>\\<^sub>2))\"  by (simp add: state_set_def) \n    \n    \nlemma chainMax2 : \n  shows \" \\<And> (A :: 'a fset) (B :: 'b fset) (C :: 'c fset) (D :: 'd fset) (P :: 'a \\<Rightarrow> 'b \\<Rightarrow> 'c \\<Rightarrow> 'd \\<Rightarrow> nat \\<Rightarrow> bool). \n((\\<And> a b c d . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P a b c d n2)))) \n  \\<Longrightarrow> (\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))\"\n  using CombinatoricsBackground.chainMaximum by blast\n    \n         \nproposition existsUniformConstant :\n  assumes rulesLangsNonempty : \"\\<And> \\<R> i r . (r |\\<in>| rule_set (\\<A> i) \\<Longrightarrow>  ((\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> i) r)  \\<noteq> {}))\"\n  shows \"constantIsSuitableForAllStates \\<N>\"\n    and \"realizesUniv \\<N>\"\n    and \"1 \\<le> \\<N>\"\nproof -\n  have n655687 : \"\\<And>i . i = \\<aa>\\<^sub>1 \\<or> i = \\<aa>\\<^sub>2\"    using \\<A>.cases by blast \n  then have n6568 : \"\\<And>i . i |\\<in>| (finsert \\<aa>\\<^sub>1  (finsert \\<aa>\\<^sub>2 fempty))\"    by auto\n  def A == \"((finsert \\<aa>\\<^sub>1  (finsert \\<aa>\\<^sub>2 fempty)) :: ot fset)\"\n  def B ==  \"(state_set (\\<A> \\<aa>\\<^sub>1)) |\\<union>|(state_set (\\<A> \\<aa>\\<^sub>2))\"\n  def C == \"(fPow (state_set (\\<A> \\<aa>\\<^sub>1)))\"\n  def D == \"(fPow (state_set (\\<A> \\<aa>\\<^sub>2)))\"\n  from chainMax2 have \"\\<And> (B :: stt fset) (C :: (stt fset) fset) (D :: (stt fset) fset) (P :: ot \\<Rightarrow> stt \\<Rightarrow> stt fset \\<Rightarrow> stt fset \\<Rightarrow> nat \\<Rightarrow> bool). ((\\<And> a b c d . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P a b c d n2)))) \\<Longrightarrow> (\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))\" by blast\n  then have \" \\<And> (P :: ot \\<Rightarrow> stt \\<Rightarrow> stt fset \\<Rightarrow> stt fset \\<Rightarrow> nat \\<Rightarrow> bool). ((\\<And> a b c d . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> P a b c d n2)))) \\<Longrightarrow> (\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> P a b c d n2))))))\" by blast\n  then have n7667987 : \" ((\\<And> a b c d . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> constantIsSuitableForStates a b c d n2)))) \\<Longrightarrow> (\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> constantIsSuitableForStates a b c d n2))))))\" by blast\n  from  constantLemma have \"(\\<And> i s Sa1 Sa2 . (s |\\<in>| (state_set (\\<A> i))  \\<Longrightarrow>  ( Sa1 |\\<subseteq>| state_set \\<A>\\<^sub>1   \\<Longrightarrow> ( Sa2 |\\<subseteq>| state_set \\<A>\\<^sub>2  \\<Longrightarrow> (\\<exists> N. constantIsSuitableForStates i s Sa1 Sa2 N )))))\" by blast\n  then have \"(\\<And> i s Sa1 Sa2 . (s |\\<in>| (state_set (\\<A> i)) \\<Longrightarrow>  ( Sa1 |\\<subseteq>| state_set \\<A>\\<^sub>1 \\<Longrightarrow> ( Sa2 |\\<subseteq>| state_set \\<A>\\<^sub>2  \\<Longrightarrow> (\\<exists> N. constantIsSuitableForStates i s Sa1 Sa2 N )))))\" by blast\n  then have \"(\\<And> i s Sa1 Sa2 . (s |\\<in>| (state_set (\\<A> i))\\<Longrightarrow>  ( Sa1 |\\<subseteq>| state_set \\<A>\\<^sub>1  \\<Longrightarrow> ( Sa2 |\\<subseteq>| state_set \\<A>\\<^sub>2 \\<Longrightarrow>(\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow>  constantIsSuitableForStates i s Sa1 Sa2 n2 )))))))\" using greaterConstantsAreGood  by metis\n  hence \"(\\<And> i s Sa1 Sa2 . (s |\\<in>| (state_set (\\<A> i)) \\<Longrightarrow>  ( Sa1 |\\<in>| C \\<Longrightarrow> ( Sa2 |\\<in>| D  \\<Longrightarrow>  (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow> constantIsSuitableForStates i s Sa1 Sa2 n2 )))))))\" using C_def D_def by auto\n  then have \"(\\<And> a b c d . a |\\<in>| A \\<Longrightarrow> b|\\<in>|B \\<Longrightarrow> c |\\<in>| C \\<Longrightarrow> d |\\<in>| D \\<Longrightarrow> (\\<exists> n. (\\<forall> n2 . (n2 > n \\<longrightarrow>constantIsSuitableForStates a b c d n2))))\" using A_def B_def stateSets  n655687 by blast\n  then have \"(\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<in>| C \\<longrightarrow> d |\\<in>| D \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> constantIsSuitableForStates a b c d n2)))))\" using n7667987 by auto\n  then have n767988 : \"(\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b|\\<in>|B \\<longrightarrow> c |\\<subseteq>| state_set \\<A>\\<^sub>1  \\<longrightarrow> d |\\<subseteq>| state_set \\<A>\\<^sub>2  \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> constantIsSuitableForStates a b c d n2)))))\" using C_def D_def by auto\n  have \"\\<And> a b. ((a |\\<in>| A \\<and>  b|\\<in>|B) = (a |\\<in>| A \\<and> b |\\<in>| (state_set (\\<A> a))))\"  proof\n    show \"\\<And>a b. a |\\<in>| A \\<and> b |\\<in>| B \\<Longrightarrow> a |\\<in>| A \\<and> b |\\<in>| state_set (\\<A> a)\" using A_def B_def  using stateSets by blast \n    show \"\\<And>a b. a |\\<in>| A \\<and> b |\\<in>| state_set (\\<A> a) \\<Longrightarrow> a |\\<in>| A \\<and> b |\\<in>| B\" using A_def B_def  using stateSets by blast \n  qed\n  then have \"(\\<exists> N. (\\<forall> a b c d . a |\\<in>| A \\<longrightarrow> b |\\<in>| (state_set (\\<A> a)) \\<longrightarrow> c |\\<subseteq>| state_set \\<A>\\<^sub>1  \\<longrightarrow> d |\\<subseteq>| state_set \\<A>\\<^sub>2  \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> constantIsSuitableForStates a b c d n2)))))\" using n767988 by metis\n  then have \"(\\<exists> N. (\\<forall> a b c d . b |\\<in>| (state_set (\\<A> a)) \\<longrightarrow> c |\\<subseteq>| state_set \\<A>\\<^sub>1  \\<longrightarrow> d |\\<subseteq>| state_set \\<A>\\<^sub>2  \\<longrightarrow> ((\\<forall> n2 . (n2 > N \\<longrightarrow> constantIsSuitableForStates a b c d n2)))))\" using n655687 A_def    by simp \n  then have n6y5687 : \"\\<exists> N.  (\\<forall> n2. n2 > N \\<longrightarrow> constantIsSuitableForAllStates n2)\" using constantIsSuitableForAllStates_def n6568  by (meson gt_ex)\n  from assms realizedInUniv1 realizesUniv_def have \"\\<exists> n . \\<forall> n2 . n2 > n \\<longrightarrow> realizesUniv n2\" by (meson less_trans)\n      hence \"\\<exists> n . \\<forall> n2 . n2 > n \\<longrightarrow> (constantIsSuitableForAllStates n2 \\<and> realizesUniv n2)\" using n6y5687 less_add_Suc1 less_add_Suc2 less_trans\n        by (metis add.left_commute add_lessD1) \n  then have  \"\\<exists> N. constantIsSuitableForAllStates N \\<and> realizesUniv N \\<and> 1 \\<le> N\" using n6y5687  less_add_Suc1 less_add_Suc2  by auto\n  then have n5457 : \"constantIsSuitableForAllStates \\<N> \\<and> realizesUniv \\<N> \\<and> 1 \\<le> \\<N>\" using \\<N>_def someI_ex    by (metis (mono_tags, lifting)) \n  then show \"constantIsSuitableForAllStates \\<N>\"  by auto\n  from n5457 show \"realizesUniv \\<N>\" by auto\n      from n5457 show \"1 \\<le> \\<N>\" by auto\nqed\n  \n  \n  \n        \n        \n  \nlemma realizedInUniv:\n  fixes n r \\<ii> \n  fixes \\<alpha> :: abc\n  assumes rulesLangsNonempty : \"\\<And> \\<R> i r . (r |\\<in>| rule_set (\\<A> i) \\<Longrightarrow>  ((\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> i) r)  \\<noteq> {}))\"\n  assumes \"\\<N> < Suc n\"\n  assumes \"r |\\<in>| rule_set (\\<A> \\<ii>)\"\n  assumes \"symbol r = \\<alpha>\"\n  shows \"realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) (\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> n UNIV) \\<union> {[]}))\"\nproof -\n  from existsUniformConstant assms(1) have \"realizesUniv \\<N>\" by auto\n  then have \"(\\<forall> i \\<alpha> r n2. (Suc n2 > \\<N> \\<longrightarrow> (r |\\<in>| rule_set (\\<A> i) \\<longrightarrow> symbol r = \\<alpha> \\<longrightarrow> (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) r) (\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> n2 UNIV) \\<union> {[]}))))))\" using realizesUniv_def by auto\n  then show \"(realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) (\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<Z>\\<^sub>\\<tau> n UNIV) \\<union> {[]})))\" using assms by auto\nqed\n  \n  \n  \n  \n  \ndefinition \\<V>\\<^sub>\\<tau> :: \"ot \\<Rightarrow> (stt,abc) rule \\<Rightarrow> abc tree set\" where\n  \"\\<V>\\<^sub>\\<tau> ot r = {tr . (root tr = (symbol r)) \\<and> \\<Pi> tr \\<in> ((upwardClosure (image \\<Pi> (((Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> ot) r)))))) \n                                 \\<union> (image \\<Pi> {t . height t > \\<N>})) \n                              \\<inter> (\\<Inter>I \\<in> (necess (\\<A> ot) \\<I> r) . (image \\<Pi> (existential_satisfaction_set I)   ))}\"\n  \n  (* ============================================= *)\nsection \"Some Notions\"   \n  \nfun numRange :: \"nat \\<Rightarrow> nat \\<Rightarrow> nat set\" where\n  \"numRange k l = {i . k \\<le> i \\<and> i \\<le> l}\"\n  \nfun prependWordToLanguage :: \"'L list \\<Rightarrow> 'L list fset set \\<Rightarrow> 'L list fset set\" where\n  \"prependWordToLanguage p l = image ((fimage (append p))) l\"\n  \nfun prependWordToWordLanguage :: \"'L list \\<Rightarrow> 'L list set \\<Rightarrow> 'L list set\" where\n  \"prependWordToWordLanguage p l = image (((append p))) l\"\n  \n  (* ============================================= *)\nsection \"Basic Definitions For Lists\"\n  \n  \nfun pathFitsListAndListIsARun :: \"ot \\<Rightarrow>  abc node list \\<Rightarrow> (stt,abc) rule list \\<Rightarrow> bool\" where\n  \"pathFitsListAndListIsARun \\<ii> [] [] = True\"\n| \"pathFitsListAndListIsARun \\<ii> (a#b) (c#d) = (( (labelOfNode a = symbol c)\n                                      \\<and> (c |\\<in>| rule_set (\\<A> \\<ii>))\n                                      \\<and> (( (down a)) \\<in> ( \\<V>\\<^sub>\\<tau> \\<ii> c  )   )    )\n                                      \\<and> (pathFitsListAndListIsARun \\<ii> b d)\n                                      \\<and> (\\<forall> h.\\<forall> t.(d = (h#t) \\<longrightarrow>  (        (((transition (\\<A> \\<ii>) (states h) (symbol h) )  |\\<in>| states c) )        )))        \n                                      )\"\n| \"pathFitsListAndListIsARun \\<ii> (a#b) [] = False\"\n| \"pathFitsListAndListIsARun \\<ii> [] (a#b) = False\"\n  \n  \n  \n  \n  \nlemma pathFitsListAndListIsARunImpliesV :\n  fixes i\n  fixes pi\n  fixes run\n  assumes \"\\<exists> a.\\<exists>b.(pi = a#b)\"\n  assumes \"(pathFitsListAndListIsARun i pi run)\"\n  shows \"(( (down (hd pi))) \\<in> ( \\<V>\\<^sub>\\<tau> i (hd run)  )   ) \"\n  by (metis assms(1) assms(2) hd_Cons_tl list.sel(1) pathFitsListAndListIsARun.simps(2) pathFitsListAndListIsARun.simps(3))\n    \n    \nlemma nonMatching :\n  fixes i\n  shows \"\\<And> e1 e2 . (pathFitsListAndListIsARun i (e1#e2) [] = False)\"\n  by simp\n    \n    \ndefinition stateFromRule where \"stateFromRule \\<ii> r = (transition (\\<A> \\<ii>) (states (r)) (symbol (r)))\"\n  \n  \ndefinition pathSatisfiesApproximatorForRuleSet where\n  \"pathSatisfiesApproximatorForRuleSet p rules \\<ii> = \n          (\\<exists> r  . (hd r |\\<in>| rules) \\<and>\n                      (pathFitsListAndListIsARun \\<ii> p r))\"\n  \ndefinition pathSatisfiesApproximatorForStateFromRuleSet where\n  \"pathSatisfiesApproximatorForStateFromRuleSet p rules \\<ii> = \n          (\\<exists> r  . \\<exists>rule \\<in> (fset rules) . ((stateFromRule  \\<ii> (hd r)) |\\<in>| (states rule)) \\<and>\n                      (pathFitsListAndListIsARun \\<ii> p r))\"\n  \n  \ndefinition satisfiesApproximatorForStatesFromRuleSet where\n  \"satisfiesApproximatorForStatesFromRuleSet tr rules \\<ii> = \n          (\\<forall> p \\<in> (pathsInTree tr) . \n             pathSatisfiesApproximatorForStateFromRuleSet p rules \\<ii>)\"\n  \ndefinition satisfiesApproximatorForRuleSet where\n  \"satisfiesApproximatorForRuleSet tr rules \\<ii> = \n          (\\<forall> p \\<in> (pathsInTree tr) . \n             pathSatisfiesApproximatorForRuleSet p rules \\<ii>)\"\n  \ndefinition approximatorLanguageForRuleSet where\n  \"approximatorLanguageForRuleSet rules \\<ii> = {tr .  satisfiesApproximatorForRuleSet tr rules \\<ii>}\"\n  \n  \n  \n  \n  (* ============================================== *)\n  \ndefinition closedUnderPlus :: \"'L tree fset set \\<Rightarrow> bool\" where\n  \"closedUnderPlus l = (\\<forall> a \\<in> l. (\\<forall> b \\<in> l. (plus a b \\<in> l)))\"\n  \ndefinition closedUnderArbitraryPlus :: \"'L tree fset set \\<Rightarrow> bool\" where\n  \"closedUnderArbitraryPlus l = (\\<forall> a . a \\<noteq> fempty \\<longrightarrow> (fset a) \\<subseteq> l \\<longrightarrow> (\\<Union>| a) \\<in> l)\"\n  \n  \ndefinition closedUnderPlusD :: \"'L list fset set \\<Rightarrow> bool\" where\n  \"closedUnderPlusD l = (\\<forall> a \\<in> l. (\\<forall> b \\<in> l. (plusD a b \\<in> l)))\"\n  \n  \n  \nlemma pathInPlus :\n  fixes f1 :: \"abc tree fset\"\n  fixes f2 :: \"abc tree fset\"\n  assumes b0 : \"x |\\<in>|\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> f1\"\n  shows \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (plus f1 f2)\"\nproof -\n  from  plus_def fimage_mono sup_ge1 have b2 : \"(\\<Pi> |`| f1) |\\<subseteq>| (\\<Pi> |`| (plus f1 f2))\" by  blast\n  from ffUnionMono pathsInForest_def b2 pathsInForest_def b0 show ?thesis using fset_rev_mp by metis\nqed\n  \nlemma plusComm :\n  shows \"plus f1 f2 = plus f2 f1\"\n  by (simp add: plus_def sup_commute)\n    \nlemma plusCommD :\n  shows \"plusD f1 f2 = plusD f2 f1\"\n  by (simp add: plusD_def sup_commute)\n    \n    \n  \nfun caseDistinction :: \"bool \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"caseDistinction True x y = x\"\n| \"caseDistinction False x y = y\"\n  \nlemma caseDistinctionLemma :\n  shows \"(\\<W> \\<longrightarrow> (caseDistinction \\<W> x y = x)) \\<and> ((\\<not> \\<W>) \\<longrightarrow> (caseDistinction \\<W> x y = y))\"\n  by simp \n    \n    \ndefinition unrealizedRules :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc list set) \\<Rightarrow> (ot \\<times> (stt,abc) rule) set\" where\n  \"unrealizedRules \\<W> prevF = {(\\<ii>,r) . r |\\<in>| (\\<W> \\<ii>) \\<and> (\\<not> (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) ((symbol r)  \\<bullet> (prevF \\<union> {[]}))))}\"\ndefinition thereIsAnUnrealizedRule :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc list set) \\<Rightarrow> bool\" where\n  \"thereIsAnUnrealizedRule \\<W> prevF = (unrealizedRules \\<W> prevF \\<noteq> {})\"\ndefinition chosenUnrealizedRule :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc list set) \\<Rightarrow> (ot \\<times> (stt,abc) rule)\" where\n  \"chosenUnrealizedRule \\<W> prevF = (SOME x. x \\<in> (unrealizedRules \\<W> prevF))\"\ndefinition chosenSide :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc list set) \\<Rightarrow> ot\" where\n  \"chosenSide \\<W> prevF = \\<pi>\\<^sup>1 (chosenUnrealizedRule \\<W> prevF)\"\n  \ndefinition treesWithoutAnalysis :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc tree fset) \\<Rightarrow> (ot \\<times> abc tree) set\" where\n  \"treesWithoutAnalysis \\<W> \\<ff> = {(i,p). p |\\<in>| \\<ff> \\<and> \\<not> (satisfiesApproximatorForStatesFromRuleSet  p (\\<W> i) i  )  }\"\ndefinition thereIsTreeWithoutAnalysis :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc tree fset) \\<Rightarrow> bool\" where\n  \"thereIsTreeWithoutAnalysis \\<W> \\<ff> = (\\<exists> x . x \\<in> (treesWithoutAnalysis \\<W> \\<ff>))\"\ndefinition chosenTreeWithoutAnalysis :: \"(ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> (abc tree fset) \\<Rightarrow> abc tree\" where\n  \"chosenTreeWithoutAnalysis \\<W> \\<ff> = \\<pi>\\<^sup>2 (SOME x. x\\<in> (treesWithoutAnalysis \\<W> \\<ff>))\"\n  \n  \ndefinition fInter :: \"('a \\<Rightarrow> 'b fset) \\<Rightarrow> 'b fset\" where\n  \"fInter u = Abs_fset (\\<Inter> j. fset (u j))\"\n  \n  \n  \n  \nlemma pathsOfChildren :\n  fixes pi tr \\<alpha>\n  assumes h1 : \"pi |\\<in>| \\<Pi> tr\"\n  assumes \"root tr = \\<alpha>\"\n  assumes \"pi = x#y#z\"\n  obtains tail child where \"pi = \\<alpha>#tail\" and \"child |\\<in>| childrenSet tr\" and \"tail |\\<in>| \\<Pi> child\"\nproof -\n  assume h0 : \"(\\<And> tail child. pi = \\<alpha> # tail \\<Longrightarrow> child |\\<in>| childrenSet tr \\<Longrightarrow> tail |\\<in>| \\<Pi> child \\<Longrightarrow> thesis)\"\n  from h1 have h2 : \"pi |\\<in>| fimage (append [\\<alpha>]) ((\\<Union>| (fimage \\<Pi> (childrenSet tr))) |\\<union>|  (finsert [] {||}))\" by (metis (full_types) assms(2) childrenSet.elims \\<Pi>.simps root.simps)\n  from h2 obtain tail where h3 : \"tail |\\<in>| (\\<Union>| (fimage \\<Pi> (childrenSet tr))) |\\<union>|  (finsert [] {||})\" and h4 : \"pi = \\<alpha>#tail\" using append_Cons append_Nil fimageE    by force\n  from h3 h4 assms(3) have h3b : \"tail |\\<in>| (\\<Union>| (fimage \\<Pi> (childrenSet tr)))\"        by blast\n  from h3b obtain child where h5 : \"child |\\<in>| childrenSet tr\" and h6 : \"tail |\\<in>| \\<Pi> child\" by (metis (no_types, lifting) ffUnionLemma fimageE)\n  from h0 h3 h4 h5 h6 show \"thesis\" by metis\nqed\n  \n  \nlemma pathsOfFactorDown :\n  fixes p \\<alpha> l tail\n  assumes h1 : \"p \\<in> \\<Pi>\\<^sub>\\<tau> l\"\n  assumes h2 : \"p = \\<alpha>#tail\"\n  assumes h10 : \"tail = q#r\"\n  shows \"tail \\<in> \\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)\"\nproof -\n  from h1 obtain tr where h3 : \"p |\\<in>| \\<Pi> tr\" and h7 : \"tr \\<in> l\" using mem_Collect_eq pathsForTreeLanguage_def by auto\n  from h3 h2 h10 have h4 : \"root tr = \\<alpha>\" using list.inject pathsOfChildren by fastforce\n  from h2 h3 h4 h10 pathsOfChildren obtain child where h5 : \"child |\\<in>| childrenSet tr\" and h6 : \"tail |\\<in>| \\<Pi> child\" using list.inject by force\n  from h7 h5 h4 h6 have h8 : \"child \\<in> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)\" using factorByRootSymbol_def mem_Collect_eq by auto\n  from h6 h8 show \"tail \\<in> \\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)\" using mem_Collect_eq pathsForTreeLanguage_def by auto\nqed\n  \n  \n  \n  \n\n  \nlemma factorAndPrefix :\n  fixes \\<alpha>\n  assumes b0 : \"\\<And> tr . tr \\<in> l \\<Longrightarrow> root tr = \\<alpha>\"\n  assumes b20 : \"witness \\<in> l\"\n  shows \"\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) \\<union> (insert [\\<alpha>] {}) = \\<Pi>\\<^sub>\\<tau> l\"\nproof\n  from prefixLetter_def have \"\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) = (\\<lambda>x.(\\<alpha>#x)) ` (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l))\" by auto\n  show \"\\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) \\<union> (insert [\\<alpha>] {}) \\<subseteq> \\<Pi>\\<^sub>\\<tau> l\"\n  proof\n    fix x\n    assume b1 : \"x \\<in> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l))\\<union> (insert [\\<alpha>] {})\"\n    show \"x \\<in> \\<Pi>\\<^sub>\\<tau> l\"\n    proof (rule disjE)\n      from b1 show b1b : \"x \\<in> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) \\<or> x \\<in> (insert [\\<alpha>] {})\" by auto\n      {\n        assume b1c : \"x \\<in> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l))\"\n        from b1c prefixLetter_def obtain tail where b3 : \"x = \\<alpha>#tail\" and b2 : \"tail \\<in> \\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)\" by blast\n        from b2 pathsForTreeLanguage_def obtain tree where b4 : \"tree \\<in> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)\" and b5 : \"tail |\\<in>| \\<Pi> tree\" by blast\n        from b4 b4 factorByRootSymbol_def obtain tree0 where b6 : \"tree0 \\<in> l\" and b7 : \"root tree0 = \\<alpha>\" and b8 : \"tree |\\<in>| childrenSet tree0\" by blast\n        from paths_def b3 b5 b7 b8 root.simps  have b9 : \"x |\\<in>| \\<Pi> tree0\" by (metis childrenSet.elims)   \n        from b9 b6 pathsForTreeLanguage_def show \"x \\<in> \\<Pi>\\<^sub>\\<tau> l\" by blast\n      }\n      from b0 have  \"\\<And> tr . (tr \\<in> l \\<Longrightarrow> ([\\<alpha>] |\\<in>| \\<Pi> tr))\" using rootIsPath    by (metis root.elims) \n      then have \"[\\<alpha>]\\<in> \\<Pi>\\<^sub>\\<tau> l\" using pathsForTreeLanguage_def b20 by blast\n      then  show \"x \\<in> (insert [\\<alpha>] {}) \\<Longrightarrow> x \\<in> \\<Pi>\\<^sub>\\<tau> l\" by blast\n    qed\n      \n  qed\n  show \"\\<Pi>\\<^sub>\\<tau> l \\<subseteq> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) \\<union> (insert [\\<alpha>] {})\"\n  proof\n    fix x\n    assume b1 : \"x \\<in> \\<Pi>\\<^sub>\\<tau> l\"\n    from b1 pathsForTreeLanguage_def obtain tree where b2 : \"x |\\<in>| \\<Pi> tree\" and b3 : \"tree \\<in> l\" by blast\n    from b0 b3 have b4 : \"root tree = \\<alpha>\" by auto\n    from b4 b2 noEmptyPathsInPi b4 obtain tail where b5 : \"x = \\<alpha>#tail\" by (metis pathsOfChildren)\n    show \"x \\<in> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l))\\<union> (insert [\\<alpha>] {})\"\n    proof (rule disjE)\n      show \"tail = [] \\<or> (\\<exists> p . (\\<exists> q. (tail=p#q)))\" using list.exhaust by blast\n          \n          \n      from b2 b5 have b6 : \"(\\<exists> p . (\\<exists> q. (tail=p#q))) \\<Longrightarrow> tail \\<in> \\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)\" using b1 pathsOfFactorDown by auto\n      from prefixLetter_def b6 b5 show \"(\\<exists> p . (\\<exists> q. (tail=p#q))) \\<Longrightarrow> x \\<in> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) \\<union> (insert [\\<alpha>] {})\" by (simp add: rev_image_eqI) \n      from b5 show \"tail = [] \\<Longrightarrow> x \\<in> \\<alpha> \\<bullet> (\\<Pi>\\<^sub>\\<tau> (\\<alpha> \\<diamondop>\\<tau>\\<lambda> l)) \\<union> (insert [\\<alpha>] {})\"          by simp\n          \n    qed\n  qed\nqed\n  \n  \ndefinition \\<P> where\n  \"\\<P> rules = {tr . \\<forall> \\<ii>. satisfiesApproximatorForRuleSet tr (rules \\<ii>) \\<ii>}\"\n  \n  \ndefinition \\<P>\\<^sub>\\<sigma> where\n  \"\\<P>\\<^sub>\\<sigma> rules = {tr . \\<forall> \\<ii>. satisfiesApproximatorForStatesFromRuleSet tr (rules \\<ii>) \\<ii>}\"\n  \ndefinition \\<P>\\<^sub>1 where\n  \"\\<P>\\<^sub>1 rules \\<ii> = {tr . satisfiesApproximatorForRuleSet tr (rules \\<ii>) \\<ii>}\"\n  \n  \n  \nlemma pathInChild:\n  fixes pi :: \"abc node list\"\n  assumes b1 : \"p |\\<in>| childrenSet p2\"\n  assumes b2 : \"pi \\<in> (pathsInTree p)\"\n  obtains piExt rootNode where \"piExt = rootNode#pi\" and \"piExt \\<in> (pathsInTree p2)\"\nproof \n  def rootNode == \"SOME node . down (node :: abc node) = p2\"\n  from rootNode_def have a21 : \"down rootNode = p2\"      by (metis (mono_tags, lifting) node.select_convs(2) someI_ex)\n  def piExt == \"rootNode#pi\"\n  from b2 pathsInTree_def have \"isAPathp pi\"    by (simp add: pathsInTree_def)\n  then obtain e1 tail where a20 : \"pi = e1#tail\" using isAPathp.simps        by blast\n  have a10 : \"(immediatelyDominates rootNode e1)\"\n  proof -\n    from a20 b2 pathsInTree_def have \"down e1 = p\"      by (simp add: pathsInTree_def)\n    then have \"(   ((down e1) |\\<in>| (childrenSet (down rootNode)))                                 )\" using b1 a21 by auto\n    then show \"(immediatelyDominates rootNode e1)\" using immediatelyDominates_def by auto\n  qed\n  have a25 : \"(isAPathp piExt)\" using a20    using \\<open>isAPathp pi\\<close> a10 isAPathp.intros(2) piExt_def by blast\n  from piExt_def show \"piExt = rootNode#pi\" by auto\n  from a25 a21 piExt_def show \"piExt \\<in> (pathsInTree p2)\"      by (simp add: pathsInTree_def)\nqed\n  \n  \n  (* the following two are almost the same *)\nlemma approximatorChildren :\n  fixes p\n  fixes p2\n  fixes \\<R>\n  fixes i\n  assumes b3 : \"p |\\<in>| childrenSet p2\"\n  assumes b4 : \"(\\<forall> pi \\<in> (pathsInTree p2) . pathSatisfiesApproximatorForRuleSet pi  (\\<R> i ) i)\"\n  shows \"(\\<forall> pi \\<in> (pathsInTree p) . pathSatisfiesApproximatorForStateFromRuleSet pi  ((\\<R> i )) i)\"\nproof \n  fix pi\n  assume b0 : \"pi \\<in> (pathsInTree p)\"\n  from pathSatisfiesApproximatorForStateFromRuleSet_def have b14 : \"pathSatisfiesApproximatorForStateFromRuleSet pi (\\<R> i) i = \n          (\\<exists> r  . \\<exists>rule \\<in> (fset (\\<R> i)) . ((stateFromRule  i (hd r)) |\\<in>| (states rule)) \\<and>\n                      (pathFitsListAndListIsARun i pi r))\" by metis\n  from b0 b3 pathInChild obtain piExt rootNode where b1 : \"piExt = rootNode#pi\" and b2 : \"piExt \\<in> (pathsInTree p2)\" by blast\n  from b4 b2 have b5 : \"pathSatisfiesApproximatorForRuleSet piExt  (\\<R> i ) i\" by metis\n  from b5 pathSatisfiesApproximatorForRuleSet_def obtain r where b6 : \"hd r |\\<in>| (\\<R> i)\" and b7 : \"pathFitsListAndListIsARun i piExt r\" by auto\n  from b7 b1 obtain rTail where b8 : \"r = (hd r)#rTail\" and b9 : \"pathFitsListAndListIsARun i (rootNode#pi) ((hd r)#rTail)\" by (metis list.exhaust_sel nonMatching) \n  from b8 b9 have b10 : \"(( (labelOfNode rootNode = symbol (hd r)) \n                                      \\<and> (( (down rootNode)) \\<in> ( \\<V>\\<^sub>\\<tau> i (hd r)  )   )    )\n                                      \\<and> (pathFitsListAndListIsARun i pi rTail)\n                                      \\<and> (\\<forall> h.\\<forall> t.(rTail = (h#t) \\<longrightarrow>  (        (((transition (\\<A> i) (states h) (symbol h) )  |\\<in>| states (hd r)) )        )))        \n                                      )\" using pathFitsListAndListIsARun.simps(2) by blast \n  from b10 have b11 : \"(pathFitsListAndListIsARun i pi rTail)\" by auto\n  def rule == \"hd r\"\n  from b6 rule_def have b12 : \"rule \\<in> (fset (\\<R> i))\" using notin_fset by force\n  from b10 have b16 : \"(pathFitsListAndListIsARun i pi rTail)\" by auto\n  from b10 have b17 : \" (\\<forall> h.\\<forall> t.(rTail = (h#t) \\<longrightarrow>  (        (((transition (\\<A> i) (states h) (symbol h) )  |\\<in>| states (hd r)) )        ))) \" by auto\n  from rule_def b10 have b18 : \" (\\<forall> h.\\<forall> t.(rTail = (h#t) \\<longrightarrow>  (        (((transition (\\<A> i) (states h) (symbol h) )  |\\<in>| states rule) )        ))) \" by auto\n  from noEmptyPaths pathsInTree_def b0 have b30 : \"pi \\<noteq> []\" using list.distinct(1) mem_Collect_eq by auto \n  from b11 b30 have b21 : \"rTail \\<noteq> []\" by (metis list.exhaust nonMatching)\n  from b21 have b19 : \"\\<exists>t. rTail = ((hd rTail)#t)\" by (metis list.collapse) \n  from b17 b18 b19 stateFromRule_def b18 b19 have b13 : \"((stateFromRule  i (hd rTail)) |\\<in>| (states rule))\" by metis\n  from b11 b12 b13 have b15 : \"(\\<exists>rule \\<in> (fset (\\<R> i)) . ((stateFromRule  i (hd rTail)) |\\<in>| (states rule)) \\<and>\n                      (pathFitsListAndListIsARun i pi rTail))\" by metis\n  from b14 b15 show \"pathSatisfiesApproximatorForStateFromRuleSet pi  (\\<R> i ) i\" by metis\nqed\n  \n  \n  \nlemma approxForRuleAndChildrenStates :\n  fixes tree\n  fixes \\<R>\n  fixes x\n  assumes \"tree \\<in> \\<P> \\<R>\"\n  assumes \"x |\\<in>| childrenSet tree\"\n  shows \"x \\<in> \\<P>\\<^sub>\\<sigma> \\<R>\"\nproof -\n  from \\<P>_def \\<P>\\<^sub>\\<sigma>_def approximatorChildren show ?thesis by (smt assms(1) assms(2) mem_Collect_eq satisfiesApproximatorForRuleSet_def satisfiesApproximatorForStatesFromRuleSet_def)\nqed\n  \n  \n  \n  \n  \ndefinition \\<ff> where \"\\<ff> n \\<R> = \\<Z>\\<^sub>\\<tau> n (\\<P> \\<R>)\"\n  \ndefinition \\<gg> where \"\\<gg> n \\<R> = \\<Union>| (\\<Z>\\<^sub>\\<phi> n (\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> (((\\<R>) \\<aa>\\<^sub>1))((((\\<R>) \\<aa>\\<^sub>2)))))\"\n  \nfun \\<W> :: \"nat \\<Rightarrow> nat \\<Rightarrow> (ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> ot \\<Rightarrow> (stt,abc) rule fset\"\n  and \\<ff>\\<^sub>1 :: \"nat \\<Rightarrow> nat \\<Rightarrow>  (ot \\<Rightarrow> (stt,abc) rule fset) \\<Rightarrow> abc tree fset\"\n  where \n    \"\\<W> n 0 \\<R> i = \\<R> i\"\n  | \"\\<ff>\\<^sub>1 n 0 \\<R> = \\<Z>\\<^sub>\\<tau> n UNIV\"\n  | \"\\<W>  n (Suc k) \\<R> i = caseDistinction (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))) \n                                           \\<and>  (i = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))))\n                                           ((\\<W> n k \\<R> i) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})\n                                           (\\<W> n k \\<R> i)\"\n  | \"\\<ff>\\<^sub>1 n (Suc k) \\<R> = inf_fset2 (\\<ff>\\<^sub>1 n k \\<R>)  (\\<P>\\<^sub>\\<sigma> (\\<W> n (k) \\<R>))\"\n    \n    \n    \n    \nlemma fa_def2 : \"\\<And> n . \\<ff>\\<^sub>1 n (Suc k) \\<R> = inf_fset2 (\\<ff>\\<^sub>1 n k \\<R>)  (\\<P>\\<^sub>\\<sigma> (\\<W> n (k) \\<R>))\" by auto\n    \n    \n    \nlemma wStationaryLemma : \n  fixes l\n  shows \"(\\<W> n l \\<R>) = (\\<W> n (Suc l) \\<R>) \\<Longrightarrow> \\<not> (thereIsAnUnrealizedRule  (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>))))\"\nproof \n  assume y65 : \"\\<W> n l \\<R> = \\<W> n (Suc l) \\<R>\"\n  assume y66 : \"thereIsAnUnrealizedRule (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n l \\<R>))\"\n  def i == \"chosenSide  (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>)))\"\n  from i_def y66 have y67 : \"\\<W> n (Suc l) \\<R> i = ((\\<W> n l \\<R> i) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>))))|})\" by (simp add: \\<W>.simps(2) caseDistinction.elims)\n  from y66 i_def chosenUnrealizedRule_def thereIsAnUnrealizedRule_def have y68 : \"\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>)))) |\\<in>| \\<W> n (Suc l) \\<R> i\"\n  proof -\n    from thereIsAnUnrealizedRule_def y66 have n65 :  \"(unrealizedRules (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n l \\<R>)) \\<noteq> {})\" by auto\n    from chosenUnrealizedRule_def n65 have n66 : \"chosenUnrealizedRule (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>))) \\<in> (unrealizedRules (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n l \\<R>)))\" by (metis all_not_in_conv someI_ex)\n    from i_def chosenSide_def have n67 : \"\\<pi>\\<^sup>1 (chosenUnrealizedRule (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>)))) = i\" by simp\n    from n66 n67 show \"\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n l \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n l \\<R>)))) |\\<in>| \\<W> n (Suc l) \\<R> i\" by (metis (no_types, lifting) case_prodE mem_Collect_eq prod.sel(1) prod.sel(2) unrealizedRules_def y65) \n  qed\n  from y67 y68 have \"\\<W> n l \\<R> \\<noteq> \\<W> n (Suc l) \\<R>\" by blast\n  then show \"False\" using y65 by auto\nqed\n  \n  \n  \n  \n  \nlemma factoredFInFa0 :\n  fixes n\n  fixes \\<A>\n  fixes \\<R>\n  assumes \"\\<And> i r . r |\\<in>| \\<R> i \\<Longrightarrow> symbol r = \\<alpha>\"\n  shows \"(\\<alpha> \\<diamondop> (\\<ff> (Suc n)  \\<R>)) |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R>\"\nproof\n  have \"\\<ff>\\<^sub>1 n 0 \\<R> = \\<Z>\\<^sub>\\<tau> n UNIV\" by (simp)\n  have b2 : \"\\<alpha> \\<diamondop> (\\<ff> (Suc n)  \\<R>) = set_to_fset {t. (\\<exists>tree. tree |\\<in>| ((\\<ff> (Suc n)  \\<R>)) \\<and> (root tree = \\<alpha> \\<and> t |\\<in>| childrenSet tree))}\" by (simp add: factorByRootSymbolF_def)\n  from b2 have b3 : \"\\<alpha> \\<diamondop>\\<tau>\\<lambda> (fset (\\<ff> (Suc n)  \\<R>)) = {t. (\\<exists>tree. tree \\<in> (fset (\\<ff> (Suc n)  \\<R>)) \\<and> (root tree = \\<alpha> \\<and> t |\\<in>| childrenSet tree))}\"\n    using factorByRootSymbol_def by auto\n  fix x\n  assume b1 : \"x |\\<in>| \\<alpha> \\<diamondop> (\\<ff> (Suc n) \\<R>)\"\n  from factorByRootSymbolF_lemma b1 have b4 : \"x \\<in> \\<alpha> \\<diamondop>\\<tau>\\<lambda> (fset (\\<ff> (Suc n)  \\<R>))\" by metis\n  from b4 b3 have b5 : \"(\\<exists>tree. tree \\<in> (fset (\\<ff> (Suc n) \\<R>)) \\<and> (root tree = \\<alpha> \\<and> x |\\<in>| childrenSet tree))\" by blast\n  from \\<ff>_def have b6 : \"(\\<ff> (Suc n)  \\<R>) = \\<Z>\\<^sub>\\<tau> (Suc n) (\\<P> \\<R>)\" by metis\n  from b5 obtain tree where b8 : \" tree \\<in> (fset (\\<ff> (Suc n) \\<R>))\" and b7 : \"(root tree = \\<alpha> \\<and> x |\\<in>| childrenSet tree)\" by blast\n  from b6 b8 have b9 : \"tree \\<in> (fset (\\<Z>\\<^sub>\\<tau> (Suc n) (\\<P> \\<R>)))\" by metis\n  from b9 \\<Z>\\<^sub>\\<tau>_def Z_def \\<Z>\\<tau>_lemma mem_Collect_eq have b10 : \"tree \\<in> (\\<P> \\<R>)\" by blast\n  from b9 Z_def \\<Z>\\<tau>_lemma mem_Collect_eq have b11 : \"height tree \\<le> (Suc n)\" by metis\n  from b11 heightOfChild  have b18 : \"height x \\<le> n\" using b7 less_trans_Suc not_less by fastforce \n  from b7 have \"x |\\<in>| childrenSet tree\" by metis\n  from approxForRuleAndChildrenStates b10 b7 have b15 : \"x \\<in> (\\<P>\\<^sub>\\<sigma> (\\<R>))\" by metis\n  show \"x |\\<in>| \\<ff>\\<^sub>1 n 0 \\<R>\"\n  proof -\n    have \"x \\<in> Z n UNIV\" using  Z_def b18 by blast\n    then have \"x |\\<in>| \\<Z>\\<^sub>\\<tau> n UNIV\" using \\<Z>\\<tau>_lemma notin_fset by metis\n    then show \"x |\\<in>| \\<ff>\\<^sub>1 n 0 \\<R>\" by simp \n  qed\nqed\n  \n  \n  \n  \n  \nlemma zIntersectLemmaNofin :\n  fixes l\n  fixes n\n  fixes x\n  shows \"(x \\<in> Z n l) = ((x \\<in> Z n UNIV) \\<and> (x \\<in> l))\"\n  using Z_def by auto\n    \n    \nlemma zIntersectLemma :\n  fixes l\n  fixes n\n  fixes x\n  shows \"(x |\\<in>| \\<Z>\\<^sub>\\<tau> n l) = ((x |\\<in>| \\<Z>\\<^sub>\\<tau> n UNIV) \\<and> (x \\<in> l))\"\n  using zIntersectLemmaNofin \\<Z>\\<tau>_lemma\n  by (metis fmember.rep_eq) \n    \n    \nlemma zIntersectLemmaFin :\n  fixes l\n  fixes n\n  fixes x\n  shows \"\\<Z>\\<^sub>\\<tau> n l = inf_fset2 (\\<Z>\\<^sub>\\<tau> n UNIV) l\"\n  using zIntersectLemma\n  by (smt Int_iff fset_eqI inf_fset2.rep_eq notin_fset) \n    \nlemma everythingAnalyzedImpliesSatisfiesImplications :\n  fixes \\<W>\n  fixes \\<ff>\n  assumes b1 : \"(\\<not> (thereIsTreeWithoutAnalysis \\<W> \\<ff>))\"\n  assumes b5 : \"\\<ff> |\\<subseteq>| \\<Z>\\<^sub>\\<tau> n (UNIV)\"\n  shows \"\\<ff> |\\<subseteq>| (((\\<Z>\\<^sub>\\<tau> n (\\<P>\\<^sub>\\<sigma>  \\<W>))))\"\nproof \n  fix x\n  assume b0 : \"x |\\<in>| \\<ff>\"\n  from thereIsTreeWithoutAnalysis_def b1 treesWithoutAnalysis_def have b2 : \"\\<And> i p . p |\\<in>| \\<ff> \\<Longrightarrow> (satisfiesApproximatorForStatesFromRuleSet p (\\<W> i) i)\" by (simp add: mem_Collect_eq prod.simps(2))\n  from b0 b2 have b4 : \"x \\<in> (\\<P>\\<^sub>\\<sigma> \\<W>)\" by (simp add: \\<P>\\<^sub>\\<sigma>_def mem_Collect_eq)\n  from b0 b5 b4 zIntersectLemma show \"x |\\<in>| (((\\<Z>\\<^sub>\\<tau> n (\\<P>\\<^sub>\\<sigma> \\<W>))))\" using fset_rev_mp by blast \nqed\n  \n  \n  \n  \n  \nlemma realized_rule_state_reverse : \n  fixes r\n  fixes \\<ii>\n  assumes b0 : \"symbol r = \\<alpha>\"\n  assumes b1 : \"\\<And> state . (state |\\<in>| (states r) \\<Longrightarrow>  realizedIn (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) pathset)\"\n  shows \"(realizedIn  (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r) (\\<alpha> \\<bullet>  (pathset \\<union> (insert [] {}))))\"\nproof -\n  from b1 realizedIn_def have b2 : \"\\<And> state . (state |\\<in>| (states r) \\<Longrightarrow>   (\\<exists>\\<gg> . ((\\<gg> \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) \\<and> (fset (\\<Pi> \\<gg>) \\<subseteq> pathset))))\" by metis\n  def realizor == \"\\<lambda> state.(SOME g. ((g \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) \\<and> (fset (\\<Pi> g) \\<subseteq> pathset)))\"\n  from b2 realizor_def have b3 : \"\\<And> state . (state |\\<in>| (states r) \\<Longrightarrow>   ( (((realizor state) \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)) \\<and> (fset (\\<Pi> (realizor state)) \\<subseteq> pathset))))\"\n    by (metis (no_types, lifting) someI_ex) \n  def children == \"realizor |`| (states r)\"\n  def exampleTree == \"(NODE \\<alpha> children)\"\n  have b4 : \"exampleTree \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r)\"\n  proof -\n    from realizor_def b2 have realizorLemma : \"\\<And> state0 . state0 |\\<in>| (states r) \\<Longrightarrow> evaluation (\\<A> \\<ii>) (realizor state0) = state0\" using b3 language_for_state_def by fastforce \n    from tree_for_rule_def language_for_rule_def \n    have c2 : \"\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) r = {tree . ((root tree = symbol r) \\<and> ((fimage (((evaluation (\\<A> \\<ii>)))) (childrenSet tree)) = states r))}\" by (smt Collect_cong)\n    from b0 exampleTree_def have \"(root exampleTree = symbol r)\" by (simp add: root.simps) \n    have g1 : \"(fimage (((evaluation (\\<A> \\<ii>)))) (childrenSet exampleTree)) = states r\"\n    proof -\n      from children_def exampleTree_def have f1 : \"(realizor |`| (states r)) =  (childrenSet exampleTree)\" by (simp add: childrenSet.simps)\n      have f2 : \"fimage (((evaluation (\\<A> \\<ii>)))) (realizor |`| (states r)) = states r\"\n      proof\n        show \"evaluation (\\<A> \\<ii>) |`| realizor |`| states r |\\<subseteq>| states r\"\n        proof\n          fix x\n          assume d1 : \"x |\\<in>| evaluation (\\<A> \\<ii>) |`| (realizor |`| states r)\"\n          from d1 obtain y state0 where d2 : \"y |\\<in>| (realizor |`| states r)\" and d3 : \"x = evaluation (\\<A> \\<ii>) y\" and d4 : \"y = realizor state0\" and d5 : \"state0 |\\<in>| states r\"  using fimageE by blast\n          from d5 realizorLemma d3 d4 d5 show \"x |\\<in>| states r\" by metis\n        qed\n        show \"states r |\\<subseteq>| evaluation (\\<A> \\<ii>) |`| realizor |`| states r\"\n        proof\n          fix x\n          assume e1 : \"x |\\<in>| states r\"\n          from e1 realizorLemma show \"x |\\<in>| evaluation (\\<A> \\<ii>) |`| realizor |`| states r\" by (metis fimageI)\n        qed\n      qed\n      from f1 f2 show ?thesis by metis\n    qed\n    from c2 b0 g1 show ?thesis using \\<open>root exampleTree = symbol r\\<close> mem_Collect_eq by auto \n  qed\n  have b5 : \"fset (\\<Pi> exampleTree) \\<subseteq> (\\<alpha> \\<bullet>  (pathset \\<union> (insert [] {})))\"\n  proof\n    fix x\n    assume g1 : \"x \\<in> fset (\\<Pi> exampleTree)\"\n    from b2 realizor_def have y2 : \"\\<And> child. child |\\<in>| children \\<Longrightarrow> (fset (\\<Pi> child) \\<subseteq> pathset)\" using b3 children_def by blast\n    have y1 : \"\\<Pi> exampleTree = fimage (\\<lambda> tail.(\\<alpha>#tail)) ((\\<Union>| (fimage \\<Pi> children)) |\\<union>|  (finsert [] {||})) \" using  exampleTree_def pathAlternateDef by metis\n    from g1 have g2 : \"x |\\<in>| (\\<Pi> exampleTree)\" by (meson notin_fset)\n    from y1 g2 have g3 : \"x |\\<in>| fimage (\\<lambda> tail.(\\<alpha>#tail)) ((\\<Union>| (fimage \\<Pi> children)) |\\<union>|  (finsert [] {||}))\" by simp\n    from g3 obtain y where g4 : \"x = \\<alpha>#y\" and g5 : \"y |\\<in>| ((\\<Union>| (fimage \\<Pi> children)) |\\<union>|  (finsert [] {||}))\" by blast\n    from g4 append_def have g6 : \"x = \\<alpha>#y\" using Cons_eq_appendI self_append_conv2 by auto\n    show \"x \\<in> (\\<alpha> \\<bullet>  (pathset \\<union> (insert [] {})))\" \n    proof (rule disjE)\n      show \"y = [] \\<or> (\\<exists> p .(\\<exists>q.(y = p#q)))\" using list.exhaust by auto\n      from g6  show \"y = [] \\<Longrightarrow>   x \\<in> (\\<alpha> \\<bullet>  (pathset \\<union> (insert [] {})))\"        by (simp add: prefixLetter_def)\n      from g5 obtain child where g7 : \"(\\<exists> p .(\\<exists>q.(y = p#q))) \\<Longrightarrow> child |\\<in>| children\" and g8 : \"(\\<exists> p .(\\<exists>q.(y = p#q))) \\<Longrightarrow> y |\\<in>| \\<Pi> child\" by (metis childrenSet.simps exampleTree_def g2 g6 list.sel(3) pathsOfChildren)\n      from g8 y2 have g9 : \"(\\<exists> p .(\\<exists>q.(y = p#q))) \\<Longrightarrow> y \\<in> pathset\" using g7 notin_fset subsetCE      by fastforce\n      from g6 g9 prefixLetter_def show \"(\\<exists> p .(\\<exists>q.(y = p#q))) \\<Longrightarrow> x \\<in> (\\<alpha> \\<bullet>  (pathset \\<union> (insert [] {})))\" by (simp add: imageI)  \n    qed\n  qed\n  from realizedIn_def b4 b5 show ?thesis by metis\nqed\n  \n  \n    \n    \nlemma \\<Z>\\<^sub>\\<phi>\\<^sub>F_mono : \n  assumes \"L1 \\<subseteq> L2\"\n  shows \"\\<Z>\\<^sub>\\<phi>\\<^sub>F n L1 \\<subseteq> \\<Z>\\<^sub>\\<phi>\\<^sub>F n L2\"\n  by (smt Int_iff \\<Z>\\<^sub>\\<phi>\\<^sub>F_def assms inf.absorb_iff2 subsetI)\n    \n    \nlemma \\<Z>\\<^sub>\\<phi>_mono : \n  assumes \"L1 \\<subseteq> L2\"\n  shows \"\\<Z>\\<^sub>\\<phi> n L1 |\\<subseteq>| \\<Z>\\<^sub>\\<phi> n L2\"\n  by (metis \\<Z>\\<^sub>\\<phi>\\<Z>\\<^sub>\\<phi>\\<^sub>Flemma \\<Z>\\<^sub>\\<phi>\\<^sub>F_mono assms less_eq_fset.rep_eq)\n    \n    \nlemma z_mono : \n  assumes \"L1 \\<subseteq> L2\"\n  shows \"Z n L1 \\<subseteq> Z n L2\"\n  by (metis (no_types, lifting) Collect_mono Z_def assms subsetCE)\n    \n    \nlemma paths_monoForest : \n  assumes \"L1 \\<subseteq> L2\"\n  shows \"\\<Pi>\\<^sub>\\<phi> L1 \\<subseteq> \\<Pi>\\<^sub>\\<phi> L2\"\n  by (simp add: assms pathsForestLangMonotone)\n    \nlemma paths_monoTree : \n  assumes \"L1 \\<subseteq> L2\"\n  shows \"\\<Pi>\\<^sub>\\<tau> L1 \\<subseteq> \\<Pi>\\<^sub>\\<tau> L2\"\n  by (simp add: assms pathsTreeLangMonotone)\n    \n    \nlemma wInR : shows \"\\<W> n k \\<R> i |\\<subseteq>| \\<R> i\" proof (induct k)\n  case 0\n  then show ?case\n    by simp \nnext\n  case (Suc k)\n  from \\<W>.simps obtain cond diff where a1 : \"\\<W> n (Suc k) \\<R> i = caseDistinction cond                                           ((\\<W> n k \\<R> i) |-| diff)                                           (\\<W> n k \\<R> i)\" by auto\n  have \"cond = True \\<Longrightarrow> \\<W> n (Suc k) \\<R> i = ((\\<W> n k \\<R> i) |-| diff)\" using a1 caseDistinction.simps by simp\n  then have a10 : \"cond = True \\<Longrightarrow> \\<W> n (Suc k) \\<R> i |\\<subseteq>| ((\\<W> n k \\<R> i))\" by blast \n  have a11 : \"cond = False \\<Longrightarrow> \\<W> n (Suc k) \\<R> i = ((\\<W> n k \\<R> i))\" using a1 caseDistinction.simps by simp\n  from a10 a11 show \"\\<W> n k \\<R> i |\\<subseteq>| \\<R> i \\<Longrightarrow> \\<W> n (Suc k) \\<R> i |\\<subseteq>| \\<R> i\" by blast\nqed\n  \n  \nlemma w_mono :\n  shows \"(\\<W> n k \\<R>) \\<ii> |\\<subseteq>| \\<R> \\<ii>\"\n  by (simp add: wInR)\n    \n    \n    \n    (* ======================================= *)\n    \nlemma biguplusMono :\n  fixes X Y\n  assumes \"X |\\<subseteq>| Y\"\n  shows \"(\\<Uplus> X) \\<subseteq> (\\<Uplus> Y)\"\n  by (smt assms biguplusForests_def fset_rev_mp mem_Collect_eq subsetI)\n    \n    \nlemma biguplusMonoD :\n  fixes X Y\n  assumes \"X |\\<subseteq>| Y\"\n  shows \"(\\<Uplus>\\<^sub>\\<delta> X) \\<subseteq> (\\<Uplus>\\<^sub>\\<delta> Y)\"\n  by (smt assms biguplusForestsD_def fset_rev_mp mem_Collect_eq subsetI)\n    \n    \nlemma intersectMonoD :\n  fixes R1 R2 S1 S2\n  assumes \\<aa>\\<^sub>1 : \"R1 |\\<subseteq>| R2\"\n  assumes \\<aa>\\<^sub>2 : \"S1 |\\<subseteq>| S2\"\n  shows \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> R1 S1 \\<subseteq> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> R2 S2\"\nproof -\n  from \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta>_def have a3 : \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> R1 S1 = ( (((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1)))) \n                                              \\<inter> ((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| S1))))))\" by metis \n  from \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta>_def have a4 : \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> R2 S2 = ( (((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)))) \n                                              \\<inter> ((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| S2))))))\" by simp\n  from \\<aa>\\<^sub>1 have a5 : \"((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1) |\\<subseteq>| ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)\" by blast\n  from \\<aa>\\<^sub>2 have a6 : \"((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S1) |\\<subseteq>| ((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S2)\" by blast\n  from biguplusMonoD a5 have a7 : \"(\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1))) \\<subseteq> (\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)))\" by auto\n  from biguplusMonoD a6 have a8 : \"(\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S1))) \\<subseteq> (\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S2)))\" by auto\n  from a7 have a9 : \" ( (((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1)))) \\<subseteq> ((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)))) ))\" by blast\n  from a8 have a10 : \" ( (((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S1)))) \\<subseteq> ((\\<Uplus>\\<^sub>\\<delta> (((\\<delta>\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S2)))) ))\" by blast\n  from a9 a10 a3 a4 show \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> R1 S1 \\<subseteq> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>\\<^sub>\\<delta> R2 S2\"  by (smt \\<aa>\\<^sub>2 biguplusMonoD fimage_finter_fsubset image_mono inf.boundedE inf.orderE inf_mono)\nqed\n  \nlemma intersectMono :\n  fixes R1 R2 S1 S2\n  assumes \\<aa>\\<^sub>1 : \"R1 |\\<subseteq>| R2\"\n  assumes \\<aa>\\<^sub>2 : \"S1 |\\<subseteq>| S2\"\n  shows \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> R1 S1 \\<subseteq> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> R2 S2\"\nproof -\n  from \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>_def have a3 : \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> R1 S1 = ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1)))) \n                                              \\<inter> (\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| S1))))))\" by metis \n  from \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho>_def have a4 : \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> R2 S2 = ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)))) \n                                              \\<inter> (\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>2) |`| S2))))))\" by simp\n  from \\<aa>\\<^sub>1 have a5 : \"((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1) |\\<subseteq>| ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)\" by blast\n  from \\<aa>\\<^sub>2 have a6 : \"((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S1) |\\<subseteq>| ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S2)\" by blast\n  from biguplusMono a5 have a7 : \"(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1))) \\<subseteq> (\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)))\" by auto\n  from biguplusMono a6 have a8 : \"(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S1))) \\<subseteq> (\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S2)))\" by auto\n  from a7 have a9 : \" ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R1)))) \\<subseteq> (\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| R2)))) ))\" by blast\n  from a8 have a10 : \" ( ((\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S1)))) \\<subseteq> (\\<Psi>\\<^sub>\\<phi> `(\\<Uplus> (((\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> \\<A>\\<^sub>1) |`| S2)))) ))\" by blast\n  from a9 a10 a3 a4 show \"\\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> R1 S1 \\<subseteq> \\<Psi>\\<^sub>\\<Sigma>\\<^sub>\\<rho> R2 S2\"  by (smt \\<aa>\\<^sub>2 biguplusMono fimage_finter_fsubset image_mono inf.boundedE inf.orderE inf_mono)\nqed\n  \n  (* ======================================= *)\n  \nlemma ruleWentMissing :\n  fixes r\n  fixes \\<R>\n  fixes n\n  fixes k\n  fixes \\<ii>\n  assumes \"r |\\<in>| \\<R> \\<ii>\"\n  shows\n    \"(\\<not>(r |\\<in>|  ((\\<W> n k \\<R>) \\<ii>))) \\<Longrightarrow> (\\<exists> k0. (k0 < k \n    \\<and> r |\\<in>| ((\\<W> n k0 \\<R>) \\<ii>) \n    \\<and> \\<not> (r |\\<in>| ((\\<W> n (Suc k0) \\<R>) \\<ii>)) \n    \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k0 \\<R>))) = (\\<ii>,r) \n    \\<and> ((\\<ii>,r) \\<in> (unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k0 \\<R>))))))\n    \\<and> (\\<ii>,r) \\<in> (unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k0 \\<R>)))))\"\nproof (induct k)\n  case 0\n  assume \"r |\\<notin>| \\<W> n 0 \\<R> \\<ii>\"\n  then have \"False\" using assms \\<W>.simps by simp\n  then show ?case by auto\nnext\n  case (Suc k)\n  assume b59 : \"r |\\<notin>| \\<W> n (Suc k) \\<R> \\<ii>\"\n  have \"r |\\<notin>| \\<W> n k \\<R> \\<ii> \\<Longrightarrow>\n    \\<exists>k0. (k0 < k \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"      using Suc.hyps by auto\n  show ?case\n  proof (rule disjE)\n    show \"(True = (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))) \\<or> (False = ((((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))))\" by auto\n    {\n      assume \"False = (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))\" \n      hence w1 : \"(False = (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))))) \\<or> (False = (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))\" by auto\n      assume b60 : \"False = (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))\"\n      have \"\\<W>  n (Suc k) \\<R> \\<ii> = caseDistinction (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))) \n                                           \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))))\n                                           ((\\<W> n k \\<R> \\<ii>) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})\n                                           (\\<W> n k \\<R> \\<ii>)\" using \\<W>.simps(2) by auto\n      then have \"\\<W>  n (Suc k) \\<R> \\<ii> = caseDistinction False ((\\<W> n k \\<R> \\<ii>) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})  (\\<W> n k \\<R> \\<ii>)\" using b60 by auto\n      then have \"\\<W>  n (Suc k) \\<R> \\<ii> = (\\<W> n k \\<R> \\<ii>)\" using caseDistinction.simps(2) by auto\n      then have \"r |\\<notin>| \\<W> n k \\<R> \\<ii>\" using b59        using b60 by auto \n      hence \"    \\<exists>k0. (k0 < k \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"      using Suc.hyps by auto\n      then show \"    \\<exists>k0. (k0 < (Suc k) \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"            using less_SucI by blast\n    }\n    {\n      assume b70 : \"True = (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))\"\n      have \"\\<W>  n (Suc k) \\<R> \\<ii> = caseDistinction (((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))))\n                                           ((\\<W> n k \\<R> \\<ii>) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})\n                                           (\\<W> n k \\<R> \\<ii>)\" using \\<W>.simps(2) by auto\n      also have \"... = caseDistinction True ((\\<W> n k \\<R> \\<ii>) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})  (\\<W> n k \\<R> \\<ii>)\" using b70 by auto\n      then have b7657 :  \"\\<W>  n (Suc k) \\<R> \\<ii> = ((\\<W> n k \\<R> \\<ii>) |-| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})\" using caseDistinction.simps(1) by simp\n      show \"    \\<exists>k0. (k0 < (Suc k) \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"\n      proof (rule disjE)\n        from b7657 have \"(r |\\<notin>|  (\\<W> n k \\<R> \\<ii>)) \\<or> (r |\\<in>| {|\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))|})\" using b59 notin_fset          by blast\n        then show \"(r |\\<notin>|  (\\<W> n k \\<R> \\<ii>)) \\<or> (r=  (\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))))\" by auto\n        {\n          assume p1 : \"(r=  (\\<pi>\\<^sup>2 (chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))))\"\n          have  \"(k < (Suc k) \\<and> r |\\<in>| \\<W> n k \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))\"\n          proof -\n            have q1 : \"k < Suc k\" by arith\n            from b70 have b70 : \"(((thereIsAnUnrealizedRule  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))))) \\<and>  (\\<ii> = chosenSide  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>)))))\" by auto\n            then have \"unrealizedRules (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<ff>\\<^sub>1 n k \\<R>))) \\<noteq> {}\" using thereIsAnUnrealizedRule_def by auto\n            then have g89 : \"(chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))) \\<in> (unrealizedRules  (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>)))\" using chosenUnrealizedRule_def                  by (simp add: some_in_eq) \n            then obtain i1 r1 where g90 :  \"(chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))) = (i1,r1)\" \n              and g91 : \"r1 |\\<in>| ((\\<W> n k \\<R>) i1) \\<and> (\\<not> (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i1) r1) ((symbol r1)  \\<bullet> ((\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))\\<union> {[]}))))\" using unrealizedRules_def              by auto \n            then have g93 : \"r1 = r\" using p1                  by simp \n            from g90 have g94 : \"i1 = \\<ii>\" using chosenSide_def b70 by simp\n            from g90 g91 g93 g94 have g98 : \"(chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))) = (\\<ii>,r)\" and g99 : \"r |\\<in>| ((\\<W> n k \\<R>) \\<ii>) \\<and> (\\<not> (realizedInForest (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> \\<ii>) r) ((symbol r)  \\<bullet> ((\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>)) \\<union> {[]}))))\" by auto\n            from g99 have q2 : \"r |\\<in>| \\<W> n k \\<R> \\<ii>\"  by auto\n            from b59 have q3 : \" r |\\<notin>| \\<W> n (Suc k) \\<R> \\<ii>\" by auto\n            have q4 : \"chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>)) = (\\<ii>, r)\" using g98 by auto\n            have q5 : \"(\\<ii>, r) \\<in> unrealizedRules (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))\" using g89 g98 by auto\n            from q1 q2 q3 q4 q5 show \"(k < (Suc k) \\<and> r |\\<in>| \\<W> n k \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k \\<R>))\" by auto\n          qed\n          then show \"    \\<exists>k0. (k0 < (Suc k) \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"      by blast\n        }\n        {\n          assume \"r |\\<notin>|  (\\<W> n k \\<R> \\<ii>)\"\n          hence \"    \\<exists>k0. (k0 < k \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"      using Suc.hyps by auto\n          then show \"    \\<exists>k0. (k0 < (Suc k) \\<and> r |\\<in>| \\<W> n k0 \\<R> \\<ii> \\<and> r |\\<notin>| \\<W> n (Suc k0) \\<R> \\<ii> \\<and> chosenUnrealizedRule (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>)) = (\\<ii>, r) \\<and> (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))) \\<and>\n         (\\<ii>, r) \\<in> unrealizedRules (\\<W> n k0 \\<R>) (\\<Pi>\\<^sub>\\<tau>\\<^sub>F (\\<ff>\\<^sub>1 n k0 \\<R>))\"            using less_SucI by blast\n        }\n      qed\n    }\n  qed\nqed\n  \n  \n  \n  \n  \nlemma lemmaPathExistence :\n  fixes tr\n  fixes I\n  assumes \"\\<Pi> tr \\<in>  (image \\<Pi> (existential_satisfaction_set I)   )\"\n  shows  \"tr \\<in> existential_satisfaction_set I\"\n  by (smt assms existential_satisfaction_set_def imageE mem_Collect_eq)\n    \n    \n    \nlemma entailsStateRule :\n  fixes \\<ii>\n  fixes state\n  fixes I\n  fixes rule\n  fixes \\<alpha>\n  assumes \"entails (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) I\"\n  assumes \"state |\\<in>| states rule\"\n  assumes \"\\<alpha> = symbol rule\"\n  shows \"entails (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) rule) (\\<alpha> \\<bullet> I)\"\nproof -\n  from assms(1) entails_def existential_satisfaction_set_def have q0 : \"\\<And> tr . tr \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state) \\<Longrightarrow> (\\<exists> x . x \\<in> ((fset (\\<Pi> tr)) \\<inter> I))\" by blast\n  have \"\\<And>tr . tr \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) rule) \\<Longrightarrow> tr \\<in> existential_satisfaction_set (\\<alpha> \\<bullet> I)\"\n  proof -\n    fix tr\n    assume \"tr \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) rule)\"\n    then obtain parent children where q1 : \"tr = NODE parent children\" and q2 : \"((root tr = symbol rule) \\<and> ((fimage (((evaluation (\\<A> \\<ii>)))) (childrenSet tr)) = states rule))\"  by (metis childrenSet.cases language_for_rule_def mem_Collect_eq tree_for_rule_def)\n    from q2 obtain child where q3 : \"child |\\<in>| childrenSet tr\" and q4 : \"evaluation (\\<A> \\<ii>) child = state\" using assms(2)        by (metis fimageE)\n    from q4 have q5 : \"child \\<in> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> \\<ii>) state)\"     by (simp add: language_for_state_def) \n    from q5 q0 obtain x where q6 : \"x \\<in> I\" and q7 : \"x \\<in> ((fset (\\<Pi> child)))\"        by (meson IntD1 IntD2)\n    from q2 q3 assms(3) notin_fset have \"\\<alpha>#x \\<in> ((fset (\\<Pi> tr)))\"        by (metis childrenSet.simps paths_def q1 q7 root.simps)\n    then show \"tr \\<in> existential_satisfaction_set (\\<alpha> \\<bullet> I)\" using existential_satisfaction_set_def q6        using prefixLetter_def by auto\n  qed\n  then show ?thesis using entails_def      by (simp add: entails_def subset_iff) \nqed\n  \n  \n    \n    \n    \n    \nsection \"Main Lemma\"\n  (*    MAIN LEMMA      *)\n  \n  (*definition \\<alpha> :: \"abc\" where\n   \"\\<alpha> = (SOME x.(x=x))\" *)\n  \n  \n  \n  \ndefinition stateSetFromRuleSet where\n  \"stateSetFromRuleSet ruleSet = (\\<Union>| (states |`| (ruleSet)))\"\n  \n  \n  \n  \nlemma z_subset : \"Z n l \\<subseteq> l\"\n  by (simp add: Z_def subset_eq)\n    \n    \n    \n    \nlemma boundedDepthInZ :\n  fixes l :: \"abc tree fset\"\n  assumes \"l |\\<subseteq>| \\<Z>\\<^sub>\\<tau> n UNIV\"\n  shows \"l |\\<subseteq>| \\<Z>\\<^sub>\\<tau> n (fset l)\"\nproof -\n  obtain tt :: \"abc tree set \\<Rightarrow> abc tree set \\<Rightarrow> abc tree\" where\n    \"\\<forall>x0 x1. (\\<exists>v2. v2 \\<in> x1 \\<and> v2 \\<notin> x0) = (tt x0 x1 \\<in> x1 \\<and> tt x0 x1 \\<notin> x0)\"\n    by moura\n  then have f1: \"(\\<not> fset l \\<subseteq> Z n (fset l) \\<or> (\\<forall>t. t \\<notin> fset l \\<or> t \\<in> Z n (fset l))) \\<and> (fset l \\<subseteq> Z n (fset l) \\<or> tt (Z n (fset l)) (fset l) \\<in> fset l \\<and> tt (Z n (fset l)) (fset l) \\<notin> Z n (fset l))\"\n    by blast\n  have f2: \"\\<forall>t. t \\<notin> fset l \\<or> t \\<in> Z n UNIV\"\n    by (metis (no_types) \\<Z>\\<tau>_lemma assms less_eq_fset.rep_eq subset_eq)\n  { assume \"\\<not> (tt (Z n (fset l)) (fset l) \\<in> UNIV \\<and> height (tt (Z n (fset l)) (fset l)) \\<le> n)\"\n    then have \"tt (Z n (fset l)) (fset l) \\<notin> fset l \\<or> tt (Z n (fset l)) (fset l) \\<in> Z n (fset l)\"\n      using f2 Z_def by blast }\n  then have \"fset l \\<subseteq> Z n (fset l)\"\n    using f1 Z_def by auto\n  then show ?thesis\n    by (metis \\<Z>\\<tau>_lemma less_eq_fset.rep_eq)\nqed\n  \nlemma fbBoundedDepth :\n  fixes n\n  fixes k\n  fixes m\n  fixes \\<R>\n  shows   \"\\<ff>\\<^sub>1 n k \\<R> |\\<subseteq>| \\<Z>\\<^sub>\\<tau> n UNIV\"\nproof -\n  have b0 : \"\\<Z>\\<^sub>\\<tau> n (\\<P>\\<^sub>\\<sigma> (\\<R>))|\\<subseteq>| \\<Z>\\<^sub>\\<tau> n UNIV\" by (metis (no_types) fsubsetI zIntersectLemma)\n  have \"\\<ff>\\<^sub>1 n 0 \\<R> = \\<Z>\\<^sub>\\<tau> n UNIV\" by (simp)\n  have b2 : \"\\<ff>\\<^sub>1 n k \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R>\"\n  proof (induct k)\n    show \"\\<ff>\\<^sub>1 n 0 \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R>\" by auto\n    show \"\\<And>k. \\<ff>\\<^sub>1 n k \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R> \\<Longrightarrow> \\<ff>\\<^sub>1 n (Suc k) \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R>\"\n    proof -\n      fix k\n      assume k7655 :  \"\\<ff>\\<^sub>1 n k \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R>\"\n      have k7656 : \"\\<ff>\\<^sub>1 n (Suc k) \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n k \\<R>\" by (metis dual_order.refl fa_def2 finter_assoc inf.absorb_iff2)\n      from k7655 k7656 show \"\\<ff>\\<^sub>1 n (Suc k) \\<R> |\\<subseteq>| \\<ff>\\<^sub>1 n 0 \\<R>\" by auto\n    qed\n  qed\n  from b0 b2 show \"\\<ff>\\<^sub>1 n k \\<R> |\\<subseteq>| \\<Z>\\<^sub>\\<tau> n UNIV\" using \\<open>\\<ff>\\<^sub>1 n 0 \\<R> = \\<Z>\\<^sub>\\<tau> n UNIV\\<close> order.trans by auto \nqed\n  \n  \n  \n  \nlemma fSupportsRules :\n  fixes p\n  fixes n\n  fixes \\<R>\n  fixes i\n  assumes b1 : \"p |\\<in>| \\<ff> n  \\<R>\"\n  shows \"(satisfiesApproximatorForRuleSet p (\\<R> i ) i)\"\nproof -\n  from b1 \\<ff>_def have b4 : \"p \\<in> (\\<P> \\<R>)\" by (metis \\<Z>\\<tau>_lemma notin_fset subsetCE z_subset) \n  from \\<P>_def show \"satisfiesApproximatorForRuleSet p (\\<R> i) i\" using b4 mem_Collect_eq by auto\nqed\n  \n  \n  \n  \nlemma pathsIntersectionLangTree : \n  fixes p\n  fixes l\n  fixes I\n  assumes \"fset (\\<Pi> p) \\<inter> I \\<noteq> {}\"\n  assumes \"p |\\<in>| l\"\n  shows \"I \\<inter> \\<Pi>\\<^sub>\\<tau>\\<^sub>F (l) \\<noteq> {}\"\n  using assms(1) assms(2) disjoint_iff_not_equal mem_Collect_eq notin_fset pathsForTreeLanguage_def\nproof -\n  have f1: \"p \\<in> fset l\"\n    by (metis (lifting) assms(2) notin_fset)\n  obtain aas :: \"'a list set \\<Rightarrow> 'a list set \\<Rightarrow> 'a list\" where\n    f2: \"\\<And>A Aa as Ab Ac. (aas A Aa \\<in> A \\<or> A \\<inter> Aa = {}) \\<and> (aas A Aa \\<in> Aa \\<or> A \\<inter> Aa = {}) \\<and> ((as::'a list) \\<notin> Ab \\<or> as \\<notin> Ac \\<or> Ac \\<inter> Ab \\<noteq> {})\"\n    by (metis (no_types) disjoint_iff_not_equal)\n  then have f3: \"aas (fset (\\<Pi> p)) I \\<in> I\"\n    by (metis (lifting) assms(1))\n  have \"aas (fset (\\<Pi> p)) I |\\<in>| \\<Pi> p\"\n    using f2 by (meson assms(1) notin_fset)\n  then have \"I \\<inter> {as. \\<exists>t. t \\<in> fset l \\<and> as |\\<in>| \\<Pi> t} \\<noteq> {}\"\n    using f3 f1 by blast\n  then show ?thesis\n    using pathsForTreeLanguage_def by blast\nqed \n    \n    \n    \n    \nlemma orderLemma  :\n  fixes n :: nat\n  fixes m :: nat\n  shows \"(n \\<le> m) = (n < Suc m)\"\n  by (simp add: less_Suc_eq_le)\n    \n    \n    \n  \nlemma pathsForestsTrees:\n  fixes l\n  shows \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| l)) =  \\<Pi>\\<^sub>\\<phi> (fset l)\"\nproof -\n  from pathsForForestLanguage_def pathsInForest_def \n  have b1 : \"\\<Pi>\\<^sub>\\<phi> (fset l) = {p . (\\<exists> t \\<in> (fset l) . p |\\<in>| (\\<Union>| (\\<Pi> |`| t)))}\"    by (smt Collect_cong) \n  have b2 : \"\\<And> p q. ((p |\\<in>| (\\<Union>| q)) = (\\<exists>pSet. (pSet |\\<in>| q \\<and> p |\\<in>| pSet)))\" by auto\n  from b2 have b3 : \"\\<And> p t. ((p |\\<in>| (\\<Union>| (\\<Pi> |`| t))) = (\\<exists>pSet. (pSet |\\<in>| (\\<Pi> |`| t) \\<and> p |\\<in>| pSet)))\" by metis\n  have b4 : \"\\<And> p t. ((\\<exists>pSet. (pSet |\\<in>| (\\<Pi> |`| t) \\<and> p |\\<in>| pSet)) = (\\<exists>tree. (tree |\\<in>| t \\<and> p |\\<in>| ((\\<Pi> tree)))))\" by auto\n  from b3 b4 have b5 : \"\\<And> p. ((\\<exists> t \\<in> (fset l) . p |\\<in>| (\\<Union>| (\\<Pi> |`| t))) = (\\<exists> t \\<in> (fset l). (\\<exists>tree. (tree |\\<in>| t \\<and> p |\\<in>| ((\\<Pi> tree))))))\" by metis\n  have b6 : \"\\<And> p.(\\<exists> t \\<in> (fset l). (\\<exists>tree. (tree |\\<in>| t \\<and> p |\\<in>| ((\\<Pi> tree))))) = (\\<exists> t \\<in> (fset (\\<Union>| l)) . p |\\<in>| \\<Pi> t)\"\n    by (meson b2 notin_fset) \n  from b2 b3 b4 b5 b6 have b8 : \"\\<Pi>\\<^sub>\\<phi> (fset l) = {p . (\\<exists> t \\<in> (fset (\\<Union>| l)) . p |\\<in>| \\<Pi> t)}\"\n    using b1 by auto \n  from pathsForTreeLanguage_def have b7 : \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| l)) = {p . (\\<exists> t \\<in> (fset (\\<Union>| l)) . p |\\<in>| \\<Pi> t)}\" by auto\n  from b8 b7 show \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F ((\\<Union>| l)) =  \\<Pi>\\<^sub>\\<phi> (fset l)\" by auto\n      (*using pathsForTreeLanguage_def  pathsForForestLanguage_def pathsInForest_def*) \nqed\n  \n  \n  \nlemma stateLanguagesClosedArbitraryOplus :\n  fixes \\<ii> state\n  defines \"l == ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>)) state))\"\n  shows \"closedUnderArbitraryPlus (l)\"\nproof (simp add :closedUnderArbitraryPlus_def)\n  show \"\\<forall>a. a \\<noteq> fempty \\<longrightarrow> fset a \\<subseteq> l \\<longrightarrow> \\<Union>| a \\<in> l\"\n  proof\n    fix a\n      \n    show \"a \\<noteq> fempty \\<longrightarrow> fset a \\<subseteq> l \\<longrightarrow> \\<Union>| a \\<in> l\"\n    proof -\n      have \"a \\<noteq> fempty \\<Longrightarrow> fset a \\<subseteq> l \\<Longrightarrow> \\<Union>| a \\<in> l\"\n      proof -\n        assume n8764654 : \"fset a \\<subseteq> l\"\n        assume n75454 : \"a \\<noteq> fempty\"\n        then obtain forest where nu6465r : \"forest |\\<in>| a\" by auto\n        hence \"forest \\<in> l\" using n8764654          by (meson notin_fset subsetCE) \n        hence \"forest \\<in> ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>)) state))\" using assms by auto\n        then obtain tree where \"tree |\\<in>| forest\" using forest_language_for_state_def by fastforce\n        hence n8765654 : \"tree |\\<in>| \\<Union>| a\"\n          using nu6465r by auto \n            \n        have n864543 : \"\\<And> tree.(tree|\\<in>| (\\<Union>| a) \\<Longrightarrow> evaluation (\\<A> \\<ii>) tree = state)\"\n        proof -\n          fix tree\n          assume \"tree|\\<in>| (\\<Union>| a)\"\n          then obtain forest where n7645 : \"tree |\\<in>| forest\" and \"forest |\\<in>| a\" using ffUnionLemma by auto\n          then have \"forest \\<in> l\" using n8764654 notin_fset            by fastforce \n          hence \"forest \\<in> ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>)) state))\" using assms by auto\n          then show \" evaluation (\\<A> \\<ii>) tree = state\" using forest_language_for_state_def n7645            by (simp add: forest_language_for_state_def) \n        qed\n        show \"\\<Union>| a \\<in> l\"  \n        proof (simp add : assms)\n          \n          from n864543 n8765654 show \" \\<Union>| a \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>) state\" using forest_language_for_state_def\n            by (smt mem_Collect_eq)\n        qed\n      qed\n      then show \"a \\<noteq> {||} \\<longrightarrow> fset a \\<subseteq> l \\<longrightarrow> \\<Union>| a \\<in> l\" by simp\n    qed\n  qed\nqed\n  \n  \n  \n            \n            \n              \n  \nlemma stateLanguagesClosedOplus :\n  fixes \\<ii> state\n  defines \"l == ( ((\\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> \\<ii>)) state))\"\n  shows \"closedUnderPlus (l)\"\nproof -\n  have b5 : \"\\<And> a b.(a \\<in> l \\<Longrightarrow> b \\<in> l \\<Longrightarrow> plus a b \\<in> l)\"\n  proof -\n    fix a b\n    assume b2 : \"a \\<in> l\" and b3 : \"b \\<in> l\"\n    from b2 b3 have b7 : \"\\<And> tree.(tree|\\<in>|(plus a b) \\<Longrightarrow> evaluation (\\<A> \\<ii>) tree = state)\"\n    proof -\n      fix tree\n      assume b10 : \"tree|\\<in>|(plus a b)\"\n      from b10 plus_def have b11 : \"tree|\\<in>|a \\<or> tree|\\<in>|b\" by blast\n      from b2 b3 forest_language_for_state_def b11 show \"evaluation (\\<A> \\<ii>) tree = state\" using l_def mem_Collect_eq\n        by fastforce \n    qed\n    from b7 b2 b3 forest_language_for_state_def l_def show b4 : \"plus a b \\<in> l\" using mem_Collect_eq      by (smt funionCI plusComm plus_def) \n  qed\n  from b5 closedUnderPlus_def show ?thesis by metis\nqed\n  \n  \nlemma \\<P>\\<sigma>_mono :\n  fixes Sa1 Sa2\n  assumes \"\\<And> i . (Sa1 i |\\<subseteq>| Sa2 i)\"\n  shows \"(\\<P>\\<^sub>\\<sigma> Sa1) \\<subseteq> (\\<P>\\<^sub>\\<sigma> Sa2)\"\nproof \n  fix x\n  assume \"x \\<in> \\<P>\\<^sub>\\<sigma> Sa1\"\n  then have \"\\<And> \\<ii> . (\\<forall> p \\<in> (pathsInTree x) .        (\\<exists> r  . \\<exists>rule \\<in> (fset (Sa1 \\<ii>)) . ((stateFromRule  \\<ii> (hd r)) |\\<in>| (states rule)) \\<and>                      (pathFitsListAndListIsARun \\<ii> p r)))\" using \\<P>\\<^sub>\\<sigma>_def satisfiesApproximatorForStatesFromRuleSet_def pathSatisfiesApproximatorForStateFromRuleSet_def by blast\n  then have \"\\<And> \\<ii> . (\\<forall> p \\<in> (pathsInTree x) .        (\\<exists> r  . \\<exists>rule \\<in> (fset (Sa2 \\<ii>)) . ((stateFromRule  \\<ii> (hd r)) |\\<in>| (states rule)) \\<and>                      (pathFitsListAndListIsARun \\<ii> p r)))\" using assms notin_fset    by (metis less_eq_fset.rep_eq subsetCE) \n  then show \"x \\<in> \\<P>\\<^sub>\\<sigma> Sa2\" by (simp add: \\<P>\\<^sub>\\<sigma>_def pathSatisfiesApproximatorForStateFromRuleSet_def satisfiesApproximatorForStatesFromRuleSet_def) \nqed\n  \n  \n  \n  \n  \n  \n  \n  \nlemma piFset  :\n  shows \"\\<And>l. \\<Pi>\\<^sub>\\<tau>\\<^sub>F l = (fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> l))\"\nproof -\n  fix l\n  from pathsForTreeLanguage_def have   \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F l = {p . (\\<exists> t \\<in> fset (l) . p |\\<in>| \\<Pi> t)}\" by auto\n  then have a1: \"\\<And>p. p \\<in> \\<Pi>\\<^sub>\\<tau>\\<^sub>F l = (\\<exists> t \\<in> fset (l) . p |\\<in>| \\<Pi> t)\" by auto\n  from pathsTreeForest have \"\\<And>p. (p |\\<in>| pathsInForest l) = (\\<exists> tr. (tr |\\<in>| l \\<and> p |\\<in>| \\<Pi> tr))\" by auto\n  then have a2 :\"\\<And>p. (p \\<in> (fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> l))) = (\\<exists> tr. (tr |\\<in>| l \\<and> p |\\<in>| \\<Pi> tr))\"        by (meson notin_fset)\n  from a1 a2 notin_fset show \"\\<Pi>\\<^sub>\\<tau>\\<^sub>F l = (fset (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> l))\"        by (metis subsetI subset_antisym) \nqed\n  \n  \n    \nlemma heightContainLemma :\n  assumes \"(\\<Pi> t |\\<subseteq>| \\<Pi> s)\"\n  shows \"(\\<Pi> t) \\<in> ((image \\<Pi> {t . height t > n})) \\<Longrightarrow> (\\<Pi> s) \\<in> (image \\<Pi> {t . height t > n})\"\n  using heightOnlyDependsOnPaths maxMonotonic  by (smt assms dual_order.strict_implies_order fimage_mono imageE image_eqI leD le_trans mem_Collect_eq order.not_eq_order_implies_strict)\n    \n    \n    \nlemma satisfiesPiContain:\n  assumes \"(\\<Pi> t |\\<subseteq>| \\<Pi> s)\"\n  assumes \"(\\<Pi> t) \\<in> ( (image \\<Pi> (existential_satisfaction_set I)   ))\"\n  shows \"(\\<Pi> s) \\<in> ( (image \\<Pi> (existential_satisfaction_set I )))  \"\nproof -\n  have \"t \\<in> (existential_satisfaction_set I)   \"    by (simp add: assms(2) lemmaPathExistence)\n  then have \"s \\<in> (existential_satisfaction_set I)   \" using assms(1) existential_satisfaction_set_def        by (smt Int_iff less_eq_fset.rep_eq mem_Collect_eq subsetCE)\n  then show ?thesis by blast\nqed\n  \nlemma vUpwardsClosedLemma :\n  assumes  \"(\\<Pi> t) \\<in> ((upwardClosure (image \\<Pi> (((Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) (hd r))))))) \n                                 \\<union> (image \\<Pi> {t . height t > \\<N>})) \n                              \\<inter> (\\<Inter>I \\<in> (necess (\\<A> \\<ii>) \\<I> (hd r)) . (image \\<Pi> (existential_satisfaction_set I)   ))\"\n  assumes \"(\\<Pi> t |\\<subseteq>| \\<Pi> s)\"\n  shows \"(\\<Pi> s) \\<in> ((upwardClosure (image \\<Pi> (((Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) (hd r))))))) \n                                 \\<union> (image \\<Pi> {t . height t > \\<N>})) \n                              \\<inter> (\\<Inter>I \\<in> (necess (\\<A> \\<ii>) \\<I> (hd r)) . (image \\<Pi> (existential_satisfaction_set I)   ))\"\nproof \n  from assms have u1 : \"(\\<Pi> t) \\<in> ((upwardClosure (image \\<Pi> (((Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) (hd r))))))) \n                                 \\<union> (image \\<Pi> {t . height t > \\<N>}))\" by auto\n  from assms upwardClosure_def have u2 : \"(\\<Pi> t) \\<in> ((upwardClosure (image \\<Pi> (((Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) (hd r)))))))) \\<Longrightarrow> (\\<Pi> s) \\<in> ((upwardClosure (image \\<Pi> (((Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) (hd r))))))))\"\n    by (smt less_eq_fset.rep_eq mem_Collect_eq subsetCE subsetI)\n  from assms(2) have u3 : \"(\\<Pi> t) \\<in> ((image \\<Pi> {t . height t > \\<N>})) \\<Longrightarrow> (\\<Pi> s) \\<in> (image \\<Pi> {t . height t > \\<N>})\" using heightContainLemma by blast\n  from u1 u2 u3      show \" \\<delta>\\<^sub>\\<tau> s \\<in> upwardClosure (\\<delta>\\<^sub>\\<tau>\\<^sub>\\<lambda> (Z \\<N> (\\<L>\\<^sub>\\<tau>\\<^sub>\\<rho> (\\<A> \\<ii>) (hd r)))) \\<union> \\<delta>\\<^sub>\\<tau>\\<^sub>\\<lambda> {t. \\<N> < height t}\" by auto\n  from assms have \"(\\<Pi> t) \\<in> (\\<Inter>I \\<in> (necess (\\<A> \\<ii>) \\<I> (hd r)) . (image \\<Pi> (existential_satisfaction_set I)   ))\" by blast\n  then have \"\\<And> I . (I \\<in> (necess (\\<A> \\<ii>) \\<I> (hd r)))  \\<Longrightarrow> (\\<Pi> t) \\<in> ( (image \\<Pi> (existential_satisfaction_set I)   ))\" by blast\n  then have \"\\<And> I . (I \\<in> (necess (\\<A> \\<ii>) \\<I> (hd r)))  \\<Longrightarrow> (\\<Pi> s) \\<in> ( (image \\<Pi> (existential_satisfaction_set I)   ))\" using assms(2) satisfiesPiContain by blast\n  then show \"(\\<Pi> s) \\<in> (\\<Inter>I \\<in> (necess (\\<A> \\<ii>) \\<I> (hd r)) . (image \\<Pi> (existential_satisfaction_set I)   ))\" by blast\nqed\n  \n  \n  \n  \nlemma  lemmaUnionUnion :\n  shows  \" \\<Union>| (mapping |`| (\\<Union>| ((\\<lambda>symbol. selector symbol) |`| rootSymbols))) = \\<Union>| ((\\<lambda>symbol. \\<Union>| (mapping |`| selector symbol)) |`| rootSymbols)\" \nproof \n  show \"\\<Union>| (mapping |`| \\<Union>| (selector |`| rootSymbols)) |\\<subseteq>| \\<Union>| ((\\<lambda>symbol. \\<Union>| (mapping |`| selector symbol)) |`| rootSymbols)\"\n    by fastforce \n  show \"\\<Union>| ((\\<lambda>symbol. \\<Union>| (mapping |`| selector symbol)) |`| rootSymbols) |\\<subseteq>| \\<Union>| (mapping |`| \\<Union>| (selector |`| rootSymbols))\" by fastforce \nqed\n  \n  \n  \nlemma pathE : \"\\<And>tree . path |\\<in>| \\<delta>\\<^sub>\\<tau> tree = (\\<exists> tail. path = (root tree)#tail \\<and> tail  |\\<in>| (pathsInForest (childrenSet tree)) |\\<union>| (finsert [] fempty))\" \nproof -\n  fix tree :: \"abc tree\"\n  show \"path |\\<in>| \\<delta>\\<^sub>\\<tau> tree = (\\<exists> tail. path = (root tree)#tail \\<and> tail  |\\<in>| (pathsInForest (childrenSet tree)) |\\<union>| (finsert [] fempty))\" \n  proof (simp add : pathAlternateDef pathsInForest_def)\n    \n    from tree.exhaust obtain roota childrena where n76687 : \"tree = (NODE roota childrena)\" by blast\n        \n    from n76687 have \" (path |\\<in>| \\<delta>\\<^sub>\\<tau> tree) = (\\<exists>tail. path = roota  # tail \\<and> (tail = [] \\<or> fBex (childrena) (\\<lambda>x. tail |\\<in>| \\<delta>\\<^sub>\\<tau> x)))\"\n      using childrenSet.simps eq_fmem_trans fBexE fBex_cong fBex_triv_one_point1 fBex_triv_one_point2 rev_fBexI by fastforce\n        \n    then show \"(path |\\<in>| \\<delta>\\<^sub>\\<tau> tree) = (\\<exists>tail. path = root tree # tail \\<and> (tail = [] \\<or> fBex (childrenSet tree) (\\<lambda>x. tail |\\<in>| \\<delta>\\<^sub>\\<tau> x)))\"  using root.simps childrenSet.simps  n76687\n      by (simp add: pathsInForest_def) \n  qed\nqed\n  \n    \n    \n    \nlemma pathsContainment:\n  assumes \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x1 |\\<union>| (finsert [] fempty) |\\<subseteq>| ((\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x2 |\\<union>| (finsert [] fempty)))\"\n  shows \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x1  |\\<subseteq>| (\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x2)\"\nproof \n  fix x\n  assume n65898 : \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> x1\"\n  hence \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x1 |\\<union>| (finsert [] fempty)\" by auto\n  hence \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x2 |\\<union>| (finsert [] fempty)\" using assms(1) by auto\n  hence \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x2 \\<or> x = []\"    by blast    \n  from n65898 noEmptyPathsInPi pathsInForest_def have \"x \\<noteq> []\"\n    by (metis list.distinct(1) pathsTreeForest) \n  show \"x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi>  x2\"\n    using \\<open>x \\<noteq> []\\<close> \\<open>x |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> x2 \\<or> x = []\\<close> by blast \nqed\n  \n                \n    \nlemma heightSingleton : \n  assumes \"maxFset (height |`| x) \\<le> n\"\n  shows \" {|NODE \\<alpha> x|} |\\<in>| boundedForests (Suc n)\"\nproof -\n  have \"{|NODE \\<alpha> x|} \\<in> fset (boundedForests (Suc n))\"\n    by (simp add : restrictionIsFiniteForests assms(1))\n  then show ?thesis using notin_fset\n    by fastforce\nqed\n  \n  \nlemma fixOplusRulesRoot :\n  fixes i \\<R>\n  assumes \"originalForest \\<in> \\<Oplus> (\\<L>\\<^sub>\\<phi>\\<^sub>\\<rho> (\\<A> i) |`| \\<R>)\"\n  assumes \"\\<And> rule . rule |\\<in>| \\<R> \\<Longrightarrow> symbol rule = \\<alpha>\"\n  assumes \"x |\\<in>| originalForest\"\n  shows \"root x = \\<alpha>\"\n  using bigoplusForests_def  forest_language_for_rule_def tree_for_rule_def\n  by (smt assms(1) assms(2) assms(3) biguplusForests_def fimageE mem_Collect_eq) \n  \n  \nlemma stateRuleSet :\n  assumes \"state |\\<in>| states rule\"\nassumes \"    rule |\\<in>| \\<R> \"\nshows \"state |\\<in>| stateSetFromRuleSet (\\<R> )\"\n  using stateSetFromRuleSet_def\n  using assms(1) assms(2) by fastforce \n    \nlemma singletonRuleLang :\n  assumes \"tr \\<in> \\<L>\\<^sub>\\<tau>\\<^sub>\\<sigma> (\\<A> i) state\"\n    shows \"(finsert tr fempty) \\<in> \\<L>\\<^sub>\\<phi>\\<^sub>\\<sigma> (\\<A> i) state\"\n  using assms forest_language_for_state_def language_for_state_def by fastforce \n\n  \n    \n  \nlemma heightBoundedPaths :\n  assumes \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> x = \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> y\"\n  assumes \" x |\\<in>| boundedForests n\"\n  shows \"y |\\<in>| boundedForests n\"\nproof -\n  from assms(2) have \"x \\<in> fset ( boundedForests n)\" using notin_fset by fastforce\n  hence  \"x \\<in> {f. \\<forall>t. t |\\<in>| f \\<longrightarrow> height t \\<le> n}\" using restrictionIsFiniteForests by auto\n  hence \"\\<And> tr . tr |\\<in>| x \\<Longrightarrow> height tr \\<le> n\" by auto\n  hence \"\\<And> path tr . tr |\\<in>| x \\<Longrightarrow> path |\\<in>| \\<Pi> tr \\<Longrightarrow> length path \\<le> n\" using heightOnlyDependsOnPaths\n    by (metis dual_order.trans fimage_eqI finiteMaxExists(1)) \n  hence \"\\<And> path . path |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> x \\<Longrightarrow> length path \\<le> n\" using pathsInTree_def\n    by (metis pathsTreeForest) \n  hence \"\\<And> path . path |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> y \\<Longrightarrow> length path \\<le> n\" using assms(1) by auto\n  hence \"\\<And> path tr . tr |\\<in>| y \\<Longrightarrow> path |\\<in>| \\<Pi> tr \\<Longrightarrow> length path \\<le> n\" using pathsInTree_def\n    using pathsTreeForest by fastforce \n  hence \"\\<And> tr . tr |\\<in>| y \\<Longrightarrow> height tr \\<le> n\" using heightOnlyDependsOnPaths\n    by (metis fimageE finiteMaxExists(2) finiteMaxExists(3) le_zero_eq nat_le_linear) \n  hence \"y \\<in> fset ( boundedForests n)\" using restrictionIsFiniteForests  by auto\n  then show \"y |\\<in>| boundedForests n\" using notin_fset by fastforce\nqed\n  \n  \nlemma suffixSets :\n  fixes symbol\n  assumes \"  ((\\<lambda> x. symbol#x) |`| a) |\\<subseteq>|  ((\\<lambda> x. symbol#x) |`| b)\"\n  shows \"a |\\<subseteq>| b\"\nproof \n  fix x\n  assume \"x |\\<in>| a\"\n  hence \"symbol#x |\\<in>| ((\\<lambda> x. symbol#x) |`| b)\" using assms by auto\n  then show \"x |\\<in>| b\"\n    by auto \nqed\n  \n  \n    \n    \nlemma rootsPaths :\n  shows \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> otherForest1 |\\<subseteq>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> otherForest2 \\<Longrightarrow> root |`| otherForest1 |\\<subseteq>| root |`| otherForest2\"\nproof (simp add :pathsInForest_def)\n  show \" \\<Union>| (\\<Pi> |`| otherForest1) |\\<subseteq>| \\<Union>| (\\<Pi> |`| otherForest2) \\<Longrightarrow> root |`| otherForest1 |\\<subseteq>| root |`| otherForest2\"\n  proof -\n    assume n76578767 : \" \\<Union>| (\\<Pi> |`| otherForest1) |\\<subseteq>| \\<Union>| (\\<Pi> |`| otherForest2)\"\n    show \"root |`| otherForest1 |\\<subseteq>| root |`| otherForest2\" \n    proof\n      show \"\\<And>x. x |\\<in>| root |`| otherForest1 \\<Longrightarrow> x |\\<in>| root |`| otherForest2\"\n      proof -\n        fix x\n        assume \"x |\\<in>| root |`| otherForest1\"\n        obtain tree where \"x = root tree\" and ny6r5t7 : \"tree |\\<in>| otherForest1\"\n          using \\<open>x |\\<in>| root |`| otherForest1\\<close> by blast \n        then have \"[x] |\\<in>| \\<Pi> tree\" using rootIsPath root.simps  by (metis tree.exhaust) \n        then have \"[x] |\\<in>| \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> otherForest2\" using pathsInForest_def ny6r5t7 n76578767\n          by fastforce \n        then obtain tree2 where \"[x] |\\<in>| \\<Pi> tree2\" and n6556897 : \"tree2 |\\<in>| otherForest2\" using pathsInForest_def\n          using pathsTreeForest by blast \n        then have \"root tree2 = x\" using \\<Pi>.simps tree.exhaust root.simps\n          using noEmptyPathsInPi by fastforce \n        then show \"x |\\<in>| root |`| otherForest2\" using n6556897\n          by blast \n      qed\n    qed\n  qed\nqed\n  \n  \n  \nlemma pathForestEmpty :\n  assumes \"\\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (otherForest2) = fempty\"\n  shows \"otherForest2 = fempty\"\nproof -\n  have \"\\<And>x . x |\\<in>| otherForest2 \\<Longrightarrow> [root x] |\\<in>| \\<Pi> x\" using rootIsPath2 by auto\n  hence \"\\<And>x . x |\\<in>| otherForest2 \\<Longrightarrow> [root x] |\\<in>| pathsInForest otherForest2\" using pathsInForest_def by blast\n  hence \"\\<And>x . x |\\<in>| otherForest2 \\<Longrightarrow> \\<Pi>\\<^sub>\\<iota>\\<^sub>\\<phi> (otherForest2) \\<noteq> fempty\" by auto\n  then show \"otherForest2 = fempty\" using assms by auto\nqed\n  \nlemma dependentChoice :\n  assumes \"\\<And>x . \\<exists> y. P x y\"\n  obtains choice where \"\\<And>x . P x (choice x)\"\nproof -\n  def choice == \"\\<lambda> x. SOME y . P x y\"\n  then  have \"\\<And>x . P x (choice x)\" using assms(1)    by (simp add: someI_ex) \n  then show \"(\\<And>choice. (\\<And>x. P x (choice x)) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\" by auto\nqed\n  \n       \nlemma psiDef :\n  shows \"psi (NODE symbol1 children1)\n      = NODE symbol1 (fimage (\\<lambda> symbol2 .\n                              psi (NODE symbol2 (\\<Union>| (fimage childrenSet (childrenWithSymbol symbol2 children1)))\n                                  )\n                              )\n                              (fimage root children1)\n                     )\"\n    sorry\n(*  using CombinatoricsBackground.psi.simps by blast*)\n    \n    \n    \n \n  (*lemma smaller_than_max_aux :\n  fixes n :: nat\n  fixes y :: nat\n  shows \"(\\<forall> (x :: nat fset) . size x = n \\<longrightarrow> (y |\\<in>| x \\<longrightarrow> y \\<le> (ffold max 0 x)))\"\nproof (induction n)\n  show \" \\<And> n. \\<forall>x. size x = n \\<longrightarrow> y |\\<in>| x \\<longrightarrow> y \\<le> ffold max 0 x \\<Longrightarrow>\n         \\<forall>x. size x = Suc n \\<longrightarrow> y |\\<in>| x \\<longrightarrow> y \\<le> ffold max 0 x\" sorry\n  show \"\\<forall>(x :: nat fset). size x = 0 \\<longrightarrow> y |\\<in>| x \\<longrightarrow> y \\<le> ffold max 0 x\" sorry*)\n  (*proof\nfix x :: \"nat fset\"\nassume 0: \"size x = 0\"\nassume 1: \"y |\\<in>| x\"\nfrom 0 have 2: \"x = {||}\" sorry\nfrom 2 have 3: \"y |\\<notin>| x\" by blast\nfrom 1 3 have 4: \"False\" by blast\nfrom 4 have  \"y \\<le> ffold max 0 x\" by blast\nfrom 1 4 have 5: \"y |\\<in>| x \\<longrightarrow> y \\<le> ffold max 0 x\" by blast\nfrom 0 5 have \"size x = 0 \\<longrightarrow> y |\\<in>| x \\<longrightarrow> y \\<le> ffold max 0 x\" by blast\nhave ?thesis sorry\nqed*)\n  (*qed*)\n  \n  (*lemma smaller_than_max:\n  fixes y :: nat\n  fixes x :: \"nat fset\"\n  shows \"y |\\<in>| x \\<longrightarrow> y \\<le> (ffold max 0 x)\"\n  sorry*)\n  (*proof -\ndef n == \"size x\"\nfrom smaller_than_max_aux have \"(\\<forall> (x :: nat fset) . size x = n \\<longrightarrow> (y |\\<in>| x \\<longrightarrow> y \\<le> (ffold max 0 x)))\" by blast\nfrom this have \"size x = n \\<longrightarrow> (y |\\<in>| x \\<longrightarrow> y \\<le> (ffold max 0 x))\" by blast\nwith n_def this show ?thesis by blast\nqed*)\n  \n  (*\nlemma children_smaller_depth :\n  fixes x :: \"'L tree\"\n  fixes y :: \"'L tree\"\n  assumes \"y |\\<in>| childrenSet x\"\n  shows \"height x \\<ge> 1 + height y\"\n  sorry*)\n  (*proof -\nfrom height_def have 1 : \"height x = 1 + (ffold max 0 (fimage height (childrenSet x)))\" sorry\nfrom smaller_than_max have \"(ffold max 0 (fimage height (childrenSet x))) \\<ge> height y\" by blast\nfrom this have \"1 + (ffold max 0 (fimage height (childrenSet x))) \\<ge> 1 + height y\" by arith\nfrom 1 this have \"height x \\<ge> Suc (height y)\" by arith\nthus ?thesis by arith\nqed*)\n    \nend\n  ", "meta": {"author": "m-hahn", "repo": "lics2018-wreath-products", "sha": "e730a7ff0863abab1a82d3f37f44cec4b952cb5b", "save_path": "github-repos/isabelle/m-hahn-lics2018-wreath-products", "path": "github-repos/isabelle/m-hahn-lics2018-wreath-products/lics2018-wreath-products-e730a7ff0863abab1a82d3f37f44cec4b952cb5b/Isabelle/CombinatoricsBackground.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8933094088947399, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.750142248915766}}
{"text": "theory Chapter3\nimports \"~~/src/HOL/IMP/BExp\"\n        \"~~/src/HOL/IMP/ASM\"\nbegin\n\ntext{*\n\\section*{Chapter 3}\n\n\\exercise\nTo show that @{const asimp_const} really folds all subexpressions of the form\n@{term \"Plus (N i) (N j)\"}, define a function\n*}\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n  \"optimal (N _) = True\" |\n  \"optimal (V _) = True\" |\n  \"optimal (Plus (N _) (N _)) = False\" |\n  \"optimal (Plus a b) = (optimal a \\<and> optimal b)\"\n\nprint_theorems\n\ntext{*\nthat checks that its argument does not contain a subexpression of the form\n@{term \"Plus (N i) (N j)\"}. Then prove that the result of @{const asimp_const}\nis optimal:\n*}\n\nlemma \"optimal (asimp_const a)\"\nproof (induction a rule: asimp_const.induct)\n  show \"\\<And>n. optimal (asimp_const (N n))\" by simp\nnext\n  show \"\\<And>v. optimal (asimp_const (V v))\" by simp\nnext\n  fix a b\n  assume IH: \"optimal (asimp_const a)\" \"optimal (asimp_const b)\"\n  show \"optimal (asimp_const (Plus a b))\"\n  proof (rule asimp_const.elims) \n\ntext{*\nThis proof needs the same @{text \"split:\"} directive as the correctness proof of\n@{const asimp_const}. This increases the chance of nontermination\nof the simplifier. Therefore @{const optimal} should be defined purely by\npattern matching on the left-hand side,\nwithout @{text case} expressions on the right-hand side.\n\\endexercise\n\n\n\\exercise\nIn this exercise we verify constant folding for @{typ aexp}\nwhere we sum up all constants, even if they are not next to each other.\nFor example, @{term \"Plus (N 1) (Plus (V x) (N 2))\"} becomes\n@{term \"Plus (V x) (N 3)\"}. This goes beyond @{const asimp}.\nBelow we follow a particular solution strategy but there are many others.\n\nFirst, define a function @{text sumN} that returns the sum of all\nconstants in an expression and a function @{text zeroN} that replaces all\nconstants in an expression by zeroes (they will be optimized away later):\n*}\n\nfun sumN :: \"aexp \\<Rightarrow> int\" where\n(* your definition/proof here *)\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\ntext {*\nNext, define a function @{text sepN} that produces an arithmetic expression\nthat adds the results of @{const sumN} and @{const zeroN}. Prove that\n@{text sepN} preserves the value of an expression.\n*}\n\ndefinition sepN :: \"aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\nlemma aval_sepN: \"aval (sepN t) s = aval t s\"\n(* your definition/proof here *)\n\ntext {*\nFinally, define a function @{text full_asimp} that uses @{const asimp}\nto eliminate the zeroes left over by @{const sepN}.\nProve that it preserves the value of an arithmetic expression.\n*}\n\ndefinition full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\nlemma aval_full_asimp: \"aval (full_asimp t) s = aval t s\"\n(* your definition/proof here *)\n\n\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:subst}\nSubstitution is the process of replacing a variable\nby an expression in an expression. Define a substitution function\n*}\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n(* your definition/proof here *)\n\ntext{*\nsuch that @{term \"subst x a e\"} is the result of replacing\nevery occurrence of variable @{text x} by @{text a} in @{text e}.\nFor example:\n@{lemma[display] \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\" by simp}\n\nProve the so-called \\concept{substitution lemma} that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\n*}\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\n(* your definition/proof here *)\n\ntext {*\nAs a consequence prove that we can substitute equal expressions by equal expressions\nand obtain the same result under evaluation:\n*}\nlemma \"aval a1 s = aval a2 s\n  \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nTake a copy of theory @{theory AExp} and modify it as follows.\nExtend type @{typ aexp} with a binary constructor @{text Times} that\nrepresents multiplication. Modify the definition of the functions @{const aval}\nand @{const asimp} accordingly. You can remove @{const asimp_const}.\nFunction @{const asimp} should eliminate 0 and 1 from multiplications\nas well as evaluate constant subterms. Update all proofs concerned.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a datatype @{text aexp2} of extended arithmetic expressions that has,\nin addition to the constructors of @{typ aexp}, a constructor for\nmodelling a C-like post-increment operation $x{++}$, where $x$ must be a\nvariable. Define an evaluation function @{text \"aval2 :: aexp2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state\"}\nthat returns both the value of the expression and the new state.\nThe latter is required because post-increment changes the state.\n\nExtend @{text aexp2} and @{text aval2} with a division operation. Model partiality of\ndivision by changing the return type of @{text aval2} to\n@{typ \"(val \\<times> state) option\"}. In case of division by 0 let @{text aval2}\nreturn @{const None}. Division on @{typ int} is the infix @{text div}.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nThe following type adds a @{text LET} construct to arithmetic expressions:\n*}\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\ntext{* The @{const LET} constructor introduces a local variable:\nthe value of @{term \"LET x e\\<^sub>1 e\\<^sub>2\"} is the value of @{text e\\<^sub>2}\nin the state where @{text x} is bound to the value of @{text e\\<^sub>1} in the original state.\nDefine a function @{const lval} @{text\"::\"} @{typ \"lexp \\<Rightarrow> state \\<Rightarrow> int\"}\nthat evaluates @{typ lexp} expressions. Remember @{term\"s(x := i)\"}.\n\nDefine a conversion @{const inline} @{text\"::\"} @{typ \"lexp \\<Rightarrow> aexp\"}.\nThe expression \\mbox{@{term \"LET x e\\<^sub>1 e\\<^sub>2\"}} is inlined by substituting\nthe converted form of @{text e\\<^sub>1} for @{text x} in the converted form of @{text e\\<^sub>2}.\nSee Exercise~\\ref{exe:subst} for more on substitution.\nProve that @{const inline} is correct w.r.t.\\ evaluation.\n\\endexercise\n\n\n\\exercise\nShow that equality and less-or-equal tests on @{text aexp} are definable\n*}\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ntext{*\nand prove that they do what they are supposed to:\n*}\n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\n(* your definition/proof here *)\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider an alternative type of boolean expressions featuring a conditional: *}\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\ntext {*  First define an evaluation function analogously to @{const bval}: *}\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{* Then define two translation functions *}\n\nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n(* your definition/proof here *)\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n(* your definition/proof here *)\n\ntext{* and prove their correctness: *}\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\n(* your definition/proof here *)\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\nWe define a new type of purely boolean expressions without any arithmetic\n*}\n\ndatatype pbexp =\n  VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\ntext{*\nwhere variables range over values of type @{typ bool},\nas can be seen from the evaluation function:\n*}\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\"  |\n\"pbval (NOT b) s = (\\<not> pbval b s)\" |\n\"pbval (AND b1 b2) s = (pbval b1 s \\<and> pbval b2 s)\" |\n\"pbval (OR b1 b2) s = (pbval b1 s \\<or> pbval b2 s)\" \n\ntext {* Define a function that checks whether a boolean exression is in NNF\n(negation normal form), i.e., if @{const NOT} is only applied directly\nto @{const VAR}s: *}\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext{*\nNow define a function that converts a @{text bexp} into NNF by pushing\n@{const NOT} inwards as much as possible:\n*}\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n(* your definition/proof here *)\n\ntext{*\nProve that @{const nnf} does what it is supposed to do:\n*}\n\nlemma pbval_nnf: \"pbval (nnf b) s = pbval b s\"\n(* your definition/proof here *)\n\nlemma is_nnf_nnf: \"is_nnf (nnf b)\"\n(* your definition/proof here *)\n\ntext{*\nAn expression is in DNF (disjunctive normal form) if it is in NNF\nand if no @{const OR} occurs below an @{const AND}. Define a corresponding\ntest:\n*}\n\nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n(* your definition/proof here *)\n\ntext {*\nAn NNF can be converted into a DNF in a bottom-up manner.\nThe critical case is the conversion of @{term (sub) \"AND b1 b2\"}.\nHaving converted @{text b\\<^sub>1} and @{text b\\<^sub>2}, apply distributivity of @{const AND}\nover @{const OR}. If we write @{const OR} as a multi-argument function,\nwe can express the distributivity step as follows:\n@{text \"dist_AND (OR a\\<^sub>1 ... a\\<^sub>n) (OR b\\<^sub>1 ... b\\<^sub>m)\"}\n= @{text \"OR (AND a\\<^sub>1 b\\<^sub>1) (AND a\\<^sub>1 b\\<^sub>2) ... (AND a\\<^sub>n b\\<^sub>m)\"}. Define\n*}\n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n(* your definition/proof here *)\n\ntext {* and prove that it behaves as follows: *}\n\nlemma pbval_dist: \"pbval (dist_AND b1 b2) s = pbval (AND b1 b2) s\"\n(* your definition/proof here *)\n\nlemma is_dnf_dist: \"is_dnf b1 \\<Longrightarrow> is_dnf b2 \\<Longrightarrow> is_dnf (dist_AND b1 b2)\"\n(* your definition/proof here *)\n\ntext {* Use @{const dist_AND} to write a function that converts an NNF\n  to a DNF in the above bottom-up manner.\n*}\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n(* your definition/proof here *)\n\ntext {* Prove the correctness of your function: *}\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\n(* your definition/proof here *)\n\nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:stack-underflow}\nA \\concept{stack underflow} occurs when executing an @{text ADD}\ninstruction on a stack of size less than two. In our semantics\nstack underflow leads to a term involving @{term \"hd []\"},\nwhich is not an error or exception --- HOL does not\nhave those concepts --- but some unspecified value. Modify\ntheory @{theory ASM} such that stack underflow is modelled by @{const None}\nand normal execution by @{text Some}, i.e., the execution functions\nhave return type @{typ \"stack option\"}. Modify all theorems and proofs\naccordingly.\nHint: you may find @{text\"split: option.split\"} useful in your proofs.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:register-machine}\nThis exercise is about a register machine\nand compiler for @{typ aexp}. The machine instructions are\n*}\ntype_synonym reg = nat\ndatatype instr = LDI val reg | LD vname reg | ADD reg reg\n\ntext {*\nwhere type @{text reg} is a synonym for @{typ nat}.\nInstruction @{term \"LDI i r\"} loads @{text i} into register @{text r},\n@{term \"LD x r\"} loads the value of @{text x} into register @{text r},\nand @{term[names_short] \"ADD r\\<^sub>1 r\\<^sub>2\"} adds register @{text r\\<^sub>2} to register @{text r\\<^sub>1}.\n\nDefine the execution of an instruction given a state and a register state;\nthe result is the new register state: *}\n\ntype_synonym rstate = \"reg \\<Rightarrow> val\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n(* your definition/proof here *)\n\ntext{*\nDefine the execution @{const[source] exec} of a list of instructions as for the stack machine.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto @{text r}. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"< r\"} should be left alone.\nDefine the compiler and prove it correct:\n*}\n\ntheorem \"exec (comp a r) s rs r = aval a s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:accumulator}\nThis exercise is a variation of the previous one\nwith a different instruction set:\n*}\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\ntext{*\nAll instructions refer implicitly to register 0 as a source or target:\n@{const LDI0} and @{const LD0} load a value into register 0, @{term \"MV0 r\"}\ncopies the value in register 0 into register @{text r}, and @{term \"ADD0 r\"}\nadds the value in register @{text r} to the value in register 0;\n@{term \"MV0 0\"} and @{term \"ADD0 0\"} are legal. Define the execution functions\n*}\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n(* your definition/proof here *)\n\ntext{*\nand @{const exec0} for instruction lists.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto register 0. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"\\<le> r\"} should be left alone\n(with the exception of 0). Define the compiler and prove it correct:\n*}\n\ntheorem \"exec0 (comp0 a r) s rs 0 = aval a s\"\n(* your definition/proof here *)\n\ntext{*\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "AtnNn", "repo": "isabelle-learn", "sha": "da71fb60bea0089fe473c104be16a4545e031be8", "save_path": "github-repos/isabelle/AtnNn-isabelle-learn", "path": "github-repos/isabelle/AtnNn-isabelle-learn/isabelle-learn-da71fb60bea0089fe473c104be16a4545e031be8/concrete-semantics/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.8688267898240861, "lm_q1q2_score": 0.7501377700165579}}
{"text": "(*  Title:       Examples of hybrid systems verifications\n    Author:      Jonathan Julián Huerta y Munive, 2020\n    Maintainer:  Jonathan Julián Huerta y Munive <jonjulian23@gmail.com>\n*)\n\nsubsection \\<open> Examples \\<close>\n\ntext \\<open> We prove partial correctness specifications of some hybrid systems with our\nverification components.\\<close>\n\ntheory HS_VC_Examples\n  imports HS_VC_Spartan\n\nbegin\n\n\nsubsubsection \\<open>Pendulum\\<close>\n\ntext \\<open> The ODEs @{text \"x' t = y t\"} and {text \"y' t = - x t\"} describe the circular motion of\na mass attached to a string looked from above. We use @{text \"s$1\"} to represent the x-coordinate\nand @{text \"s$2\"} for the y-coordinate. We prove that this motion remains circular. \\<close>\n\nabbreviation fpend :: \"real^2 \\<Rightarrow> real^2\" (\"f\")\n  where \"f s \\<equiv> (\\<chi> i. if i = 1 then s$2 else -s$1)\"\n\nabbreviation pend_flow :: \"real \\<Rightarrow> real^2 \\<Rightarrow> real^2\" (\"\\<phi>\")\n  where \"\\<phi> t s \\<equiv> (\\<chi> i. if i = 1 then s$1 * cos t + s$2 * sin t else - s$1 * sin t + s$2 * cos t)\"\n\n\\<comment> \\<open>Verified with annotated dynamics. \\<close>\n\nlemma pendulum_dyn: \"(\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2) \\<le> |EVOL \\<phi> G T] (\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2)\"\n  by force\n\n\\<comment> \\<open>Verified with differential invariants. \\<close>\n\nlemma pendulum_inv: \"(\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2) \\<le> |x\\<acute>= f & G] (\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2)\"\n  by (auto intro!: diff_invariant_rules poly_derivatives)\n\n\\<comment> \\<open>Verified with the flow. \\<close>\n\nlemma local_flow_pend: \"local_flow f UNIV UNIV \\<phi>\"\n  apply(unfold_locales, simp_all add: local_lipschitz_def lipschitz_on_def vec_eq_iff, clarsimp)\n    apply(rule_tac x=\"1\" in exI, clarsimp, rule_tac x=1 in exI)\n    apply(simp add: dist_norm norm_vec_def L2_set_def power2_commute UNIV_2)\n  by (auto simp: forall_2 intro!: poly_derivatives)\n\nlemma pendulum_flow: \"(\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2) \\<le> |x\\<acute>=f & G] (\\<lambda>s. r\\<^sup>2 = (s$1)\\<^sup>2 + (s$2)\\<^sup>2)\"\n  by (force simp: local_flow.fbox_g_ode_subset[OF local_flow_pend])\n\nno_notation fpend (\"f\")\n        and pend_flow (\"\\<phi>\")\n\n\nsubsubsection \\<open> Bouncing Ball \\<close>\n\ntext \\<open> A ball is dropped from rest at an initial height @{text \"h\"}. The motion is described with\nthe free-fall equations @{text \"x' t = v t\"} and @{text \"v' t = g\"} where @{text \"g\"} is the\nconstant acceleration due to gravity. The bounce is modelled with a variable assignment that\nflips the velocity. That is, we model it as a completely elastic collision with the ground. We use \n@{text \"s$1\"} to represent the ball's height and @{text \"s$2\"} for its velocity. We prove that the \nball remains above ground and below its initial resting position. \\<close>\n\nabbreviation fball :: \"real \\<Rightarrow> real^2 \\<Rightarrow> real^2\" (\"f\")\n  where \"f g s \\<equiv> (\\<chi> i. if i = 1 then s$2 else g)\"\n\nabbreviation ball_flow :: \"real \\<Rightarrow> real \\<Rightarrow> real^2 \\<Rightarrow> real^2\" (\"\\<phi>\")\n  where \"\\<phi> g t s \\<equiv> (\\<chi> i. if i = 1 then g * t ^ 2/2 + s$2 * t + s$1 else g * t + s$2)\"\n\n\\<comment> \\<open>Verified with differential invariants. \\<close>\n\nnamed_theorems bb_real_arith \"real arithmetic properties for the bouncing ball.\"\n\nlemma inv_imp_pos_le[bb_real_arith]:\n  assumes \"0 > g\" and inv: \"2 * g * x - 2 * g * h = v * v\"\n  shows \"(x::real) \\<le> h\"\nproof-\n  have \"v * v = 2 * g * x - 2 * g * h \\<and> 0 > g\"\n    using inv and \\<open>0 > g\\<close> by auto\n  hence obs:\"v * v = 2 * g * (x - h) \\<and> 0 > g \\<and> v * v \\<ge> 0\"\n    using left_diff_distrib mult.commute by (metis zero_le_square)\n  hence \"(v * v)/(2 * g) = (x - h)\"\n    by auto\n  also from obs have \"(v * v)/(2 * g) \\<le> 0\"\n    using divide_nonneg_neg by fastforce\n  ultimately have \"h - x \\<ge> 0\"\n    by linarith\n  thus ?thesis by auto\nqed\n\nlemma \"diff_invariant (\\<lambda>s. 2 * g * s$1 - 2 * g * h - s$2 * s$2 = 0) (\\<lambda>t. f g) (\\<lambda>s. UNIV) S t\\<^sub>0 G\"\n  by (auto intro!: poly_derivatives diff_invariant_rules)\n\nlemma bouncing_ball_inv: \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  (\\<lambda>s. s$1 = h \\<and> s$2 = 0) \\<le>\n  |LOOP (\n    (x\\<acute>=(f g) & (\\<lambda> s. s$1 \\<ge> 0) DINV (\\<lambda>s. 2 * g * s$1 - 2 * g * h - s$2 * s$2 = 0)) ;\n    (IF (\\<lambda> s. s$1 = 0) THEN (2 ::= (\\<lambda>s. - s$2)) ELSE skip))\n  INV (\\<lambda>s. 0 \\<le> s$1 \\<and> 2 * g * s$1 - 2 * g * h - s$2 * s$2 = 0)]\n  (\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h)\"\n  apply(rule fbox_loopI, simp_all, force, force simp: bb_real_arith)\n  by (rule fbox_g_odei) (auto intro!: poly_derivatives diff_invariant_rules)\n\n\\<comment> \\<open>Verified with annotated dynamics. \\<close>\n\nlemma inv_conserv_at_ground[bb_real_arith]:\n  assumes invar: \"2 * g * x = 2 * g * h + v * v\"\n    and pos: \"g * \\<tau>\\<^sup>2 / 2 + v * \\<tau> + (x::real) = 0\"\n  shows \"2 * g * h + (g * \\<tau> + v) * (g * \\<tau> + v) = 0\"\nproof-\n  from pos have \"g * \\<tau>\\<^sup>2  + 2 * v * \\<tau> + 2 * x = 0\" by auto\n  then have \"g\\<^sup>2 * \\<tau>\\<^sup>2  + 2 * g * v * \\<tau> + 2 * g * x = 0\"\n    by (metis (mono_tags) Groups.mult_ac(1,3) mult_zero_right\n        monoid_mult_class.power2_eq_square semiring_class.distrib_left)\n  hence \"g\\<^sup>2 * \\<tau>\\<^sup>2 + 2 * g * v * \\<tau> + v\\<^sup>2 + 2 * g * h = 0\"\n    using invar by (simp add: monoid_mult_class.power2_eq_square)\n  hence obs: \"(g * \\<tau> + v)\\<^sup>2 + 2 * g * h = 0\"\n    apply(subst power2_sum) by (metis (no_types) Groups.add_ac(2, 3)\n        Groups.mult_ac(2, 3) monoid_mult_class.power2_eq_square nat_distrib(2))\n  thus \"2 * g * h + (g * \\<tau> + v) * (g * \\<tau> + v) = 0\"\n    by (simp add: add.commute distrib_right power2_eq_square)\nqed\n\nlemma inv_conserv_at_air[bb_real_arith]:\n  assumes invar: \"2 * g * x = 2 * g * h + v * v\"\n  shows \"2 * g * (g * \\<tau>\\<^sup>2 / 2 + v * \\<tau> + (x::real)) =\n  2 * g * h + (g * \\<tau> + v) * (g * \\<tau> + v)\" (is \"?lhs = ?rhs\")\nproof-\n  have \"?lhs = g\\<^sup>2 * \\<tau>\\<^sup>2 + 2 * g * v * \\<tau> + 2 * g * x\"\n    by(auto simp: algebra_simps semiring_normalization_rules(29))\n  also have \"... = g\\<^sup>2 * \\<tau>\\<^sup>2 + 2 * g * v * \\<tau> + 2 * g * h + v * v\" (is \"... = ?middle\")\n    by(subst invar, simp)\n  finally have \"?lhs = ?middle\".\n  moreover\n  {have \"?rhs = g * g * (\\<tau> * \\<tau>) + 2 * g * v * \\<tau> + 2 * g * h + v * v\"\n    by (simp add: Groups.mult_ac(2,3) semiring_class.distrib_left)\n  also have \"... = ?middle\"\n    by (simp add: semiring_normalization_rules(29))\n  finally have \"?rhs = ?middle\".}\n  ultimately show ?thesis by auto\nqed\n\nlemma bouncing_ball_dyn: \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  (\\<lambda>s. s$1 = h \\<and> s$2 = 0) \\<le>\n  |LOOP (\n    (EVOL (\\<phi> g) (\\<lambda> s. s$1 \\<ge> 0) T) ;\n    (IF (\\<lambda> s. s$1 = 0) THEN (2 ::= (\\<lambda>s. - s$2)) ELSE skip))\n  INV (\\<lambda>s. 0 \\<le> s$1 \\<and>2 * g * s$1 = 2 * g * h + s$2 * s$2)]\n  (\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h)\"\n  by (rule fbox_loopI) (auto simp: bb_real_arith)\n\n\\<comment> \\<open>Verified with the flow. \\<close>\n\nlemma local_flow_ball: \"local_flow (f g) UNIV UNIV (\\<phi> g)\"\n  apply(unfold_locales, simp_all add: local_lipschitz_def lipschitz_on_def vec_eq_iff, clarsimp)\n    apply(rule_tac x=\"1/2\" in exI, clarsimp, rule_tac x=1 in exI)\n    apply(simp add: dist_norm norm_vec_def L2_set_def UNIV_2)\n  by (auto simp: forall_2 intro!: poly_derivatives)\n\nlemma bouncing_ball_flow: \"g < 0 \\<Longrightarrow> h \\<ge> 0 \\<Longrightarrow>\n  (\\<lambda>s. s$1 = h \\<and> s$2 = 0) \\<le>\n  |LOOP (\n    (x\\<acute>=(\\<lambda>t. f g) & (\\<lambda> s. s$1 \\<ge> 0) on (\\<lambda>s. UNIV) UNIV @ 0) ;\n    (IF (\\<lambda> s. s$1 = 0) THEN (2 ::= (\\<lambda>s. - s$2)) ELSE skip))\n  INV (\\<lambda>s. 0 \\<le> s$1 \\<and>2 * g * s$1 = 2 * g * h + s$2 * s$2)]\n  (\\<lambda>s. 0 \\<le> s$1 \\<and> s$1 \\<le> h)\"\n  apply(rule fbox_loopI, simp_all add: local_flow.fbox_g_ode_subset[OF local_flow_ball])\n  by (auto simp: bb_real_arith)\n\nno_notation fball (\"f\")\n        and ball_flow (\"\\<phi>\")\n\n\nsubsubsection \\<open> Thermostat \\<close>\n\ntext \\<open> A thermostat has a chronometer, a thermometer and a switch to turn on and off a heater.\nAt most every @{text \"t\"} minutes, it sets its chronometer to @{term \"0::real\"}, it registers\nthe room temperature, and it turns the heater on (or off) based on this reading. The temperature\nfollows the ODE @{text \"T' = - a * (T - U)\"} where @{text \"U\"} is @{text \"L \\<ge> 0\"} when the heater\nis on, and @{text \"0\"} when it is off. We use @{term \"1::4\"} to denote the room's temperature,\n@{term \"2::4\"} is time as measured by the thermostat's chronometer, @{term \"3::4\"} is the\ntemperature detected by the thermometer, and @{term \"4::4\"} states whether the heater is on\n(@{text \"s$4 = 1\"}) or off (@{text \"s$4 = 0\"}). We prove that the thermostat keeps the room's\ntemperature between @{text \"Tmin\"} and @{text \"Tmax\"}. \\<close>\n\nabbreviation temp_vec_field :: \"real \\<Rightarrow> real \\<Rightarrow> real^4 \\<Rightarrow> real^4\" (\"f\")\n  where \"f a L s \\<equiv> (\\<chi> i. if i = 2 then 1 else (if i = 1 then - a * (s$1 - L) else 0))\"\n\nabbreviation temp_flow :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real^4 \\<Rightarrow> real^4\" (\"\\<phi>\")\n  where \"\\<phi> a L t s \\<equiv> (\\<chi> i. if i = 1 then - exp(-a * t) * (L - s$1) + L else\n  (if i = 2 then t + s$2 else s$i))\"\n\n\\<comment> \\<open>Verified with the flow. \\<close>\n\nlemma norm_diff_temp_dyn: \"0 < a \\<Longrightarrow> \\<parallel>f a L s\\<^sub>1 - f a L s\\<^sub>2\\<parallel> = \\<bar>a\\<bar> * \\<bar>s\\<^sub>1$1 - s\\<^sub>2$1\\<bar>\"\nproof(simp add: norm_vec_def L2_set_def, unfold UNIV_4, simp)\n  assume a1: \"0 < a\"\n  have f2: \"\\<And>r ra. \\<bar>(r::real) + - ra\\<bar> = \\<bar>ra + - r\\<bar>\"\n    by (metis abs_minus_commute minus_real_def)\n  have \"\\<And>r ra rb. (r::real) * ra + - (r * rb) = r * (ra + - rb)\"\n    by (metis minus_real_def right_diff_distrib)\n  hence \"\\<bar>a * (s\\<^sub>1$1 + - L) + - (a * (s\\<^sub>2$1 + - L))\\<bar> = a * \\<bar>s\\<^sub>1$1 + - s\\<^sub>2$1\\<bar>\"\n    using a1 by (simp add: abs_mult)\n  thus \"\\<bar>a * (s\\<^sub>2$1 - L) - a * (s\\<^sub>1$1 - L)\\<bar> = a * \\<bar>s\\<^sub>1$1 - s\\<^sub>2$1\\<bar>\"\n    using f2 minus_real_def by presburger\nqed\n\nlemma local_lipschitz_temp_dyn:\n  assumes \"0 < (a::real)\"\n  shows \"local_lipschitz UNIV UNIV (\\<lambda>t::real. f a L)\"\n  apply(unfold local_lipschitz_def lipschitz_on_def dist_norm)\n  apply(clarsimp, rule_tac x=1 in exI, clarsimp, rule_tac x=a in exI)\n  using assms\n  apply(simp add: norm_diff_temp_dyn)\n  apply(simp add: norm_vec_def L2_set_def, unfold UNIV_4, clarsimp)\n  unfolding real_sqrt_abs[symmetric] by (rule real_le_lsqrt) auto\n\nlemma local_flow_temp: \"a > 0 \\<Longrightarrow> local_flow (f a L) UNIV UNIV (\\<phi> a L)\"\n  by (unfold_locales, auto intro!: poly_derivatives local_lipschitz_temp_dyn simp: forall_4 vec_eq_iff)\n\nlemma temp_dyn_down_real_arith:\n  assumes \"a > 0\" and Thyps: \"0 < Tmin\" \"Tmin \\<le> T\" \"T \\<le> Tmax\"\n    and thyps: \"0 \\<le> (t::real)\" \"\\<forall>\\<tau>\\<in>{0..t}. \\<tau> \\<le> - (ln (Tmin / T) / a) \"\n  shows \"Tmin \\<le> exp (-a * t) * T\" and \"exp (-a * t) * T \\<le> Tmax\"\nproof-\n  have \"0 \\<le> t \\<and> t \\<le> - (ln (Tmin / T) / a)\"\n    using thyps by auto\n  hence \"ln (Tmin / T) \\<le> - a * t \\<and> - a * t \\<le> 0\"\n    using assms(1) divide_le_cancel by fastforce\n  also have \"Tmin / T > 0\"\n    using Thyps by auto\n  ultimately have obs: \"Tmin / T \\<le> exp (-a * t)\" \"exp (-a * t) \\<le> 1\"\n    using exp_ln exp_le_one_iff by (metis exp_less_cancel_iff not_less, simp)\n  thus \"Tmin \\<le> exp (-a * t) * T\"\n    using Thyps by (simp add: pos_divide_le_eq)\n  show \"exp (-a * t) * T \\<le> Tmax\"\n    using Thyps mult_left_le_one_le[OF _ exp_ge_zero obs(2), of T]\n      less_eq_real_def order_trans_rules(23) by blast\nqed\n\nlemma temp_dyn_up_real_arith:\n  assumes \"a > 0\" and Thyps: \"Tmin \\<le> T\" \"T \\<le> Tmax\" \"Tmax < (L::real)\"\n    and thyps: \"0 \\<le> t\" \"\\<forall>\\<tau>\\<in>{0..t}. \\<tau> \\<le> - (ln ((L - Tmax) / (L - T)) / a) \"\n  shows \"L - Tmax \\<le> exp (-(a * t)) * (L - T)\"\n    and \"L - exp (-(a * t)) * (L - T) \\<le> Tmax\"\n    and \"Tmin \\<le> L - exp (-(a * t)) * (L - T)\"\nproof-\n  have \"0 \\<le> t \\<and> t \\<le> - (ln ((L - Tmax) / (L - T)) / a)\"\n    using thyps by auto\n  hence \"ln ((L - Tmax) / (L - T)) \\<le> - a * t \\<and> - a * t \\<le> 0\"\n    using assms(1) divide_le_cancel by fastforce\n  also have \"(L - Tmax) / (L - T) > 0\"\n    using Thyps by auto\n  ultimately have \"(L - Tmax) / (L - T) \\<le> exp (-a * t) \\<and> exp (-a * t) \\<le> 1\"\n    using exp_ln exp_le_one_iff by (metis exp_less_cancel_iff not_less)\n  moreover have \"L - T > 0\"\n    using Thyps by auto\n  ultimately have obs: \"(L - Tmax) \\<le> exp (-a * t) * (L - T) \\<and> exp (-a * t) * (L - T) \\<le> (L - T)\"\n    by (simp add: pos_divide_le_eq)\n  thus \"(L - Tmax) \\<le> exp (-(a * t)) * (L - T)\"\n    by auto\n  thus \"L - exp (-(a * t)) * (L - T) \\<le> Tmax\"\n    by auto\n  show \"Tmin \\<le> L - exp (-(a * t)) * (L - T)\"\n    using Thyps and obs by auto\nqed\n\nlemmas fbox_temp_dyn = local_flow.fbox_g_ode_subset[OF local_flow_temp]\n\nlemma thermostat:\n  assumes \"a > 0\" and \"0 < Tmin\" and \"Tmax < L\"\n  shows \"(\\<lambda>s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax \\<and> s$4 = 0) \\<le>\n  |LOOP\n    \\<comment> \\<open>control\\<close>\n    ((2 ::= (\\<lambda>s. 0));(3 ::= (\\<lambda>s. s$1));\n    (IF (\\<lambda>s. s$4 = 0 \\<and> s$3 \\<le> Tmin + 1) THEN (4 ::= (\\<lambda>s.1)) ELSE\n    (IF (\\<lambda>s. s$4 = 1 \\<and> s$3 \\<ge> Tmax - 1) THEN (4 ::= (\\<lambda>s.0)) ELSE skip));\n    \\<comment> \\<open>dynamics\\<close>\n    (IF (\\<lambda>s. s$4 = 0) THEN (x\\<acute>= f a 0 & (\\<lambda>s. s$2 \\<le> - (ln (Tmin/s$3))/a))\n    ELSE (x\\<acute>= f a L & (\\<lambda>s. s$2 \\<le> - (ln ((L-Tmax)/(L-s$3)))/a))) )\n  INV (\\<lambda>s. Tmin \\<le>s$1 \\<and> s$1 \\<le> Tmax \\<and> (s$4 = 0 \\<or> s$4 = 1))]\n  (\\<lambda>s. Tmin \\<le> s$1 \\<and> s$1 \\<le> Tmax)\"\n  apply(rule fbox_loopI, simp_all add: fbox_temp_dyn[OF assms(1)] le_fun_def)\n  using temp_dyn_up_real_arith[OF assms(1) _ _ assms(3), of Tmin]\n    and temp_dyn_down_real_arith[OF assms(1,2), of _ Tmax] by auto\n\nno_notation temp_vec_field (\"f\")\n        and temp_flow (\"\\<phi>\")\n\nsubsubsection \\<open> Tank \\<close>\n\ntext \\<open> A controller turns a water pump on and off to keep the level of water @{text \"h\"} in a tank\nwithin an acceptable range @{text \"hmin \\<le> h \\<le> hmax\"}. Just like in the previous example, after \neach intervention, the controller registers the current level of water and resets its chronometer,\nthen it changes the status of the water pump accordingly. The level of water grows linearly \n@{text \"h' = k\"} at a rate of @{text \"k = c\\<^sub>i-c\\<^sub>o\"} if the pump is on, and at a rate of \n@{text \"k = -c\\<^sub>o\"} if the pump is off. We use @{term \"1::4\"} to denote the tank's level of water,\n@{term \"2::4\"} is time as measured by the controller's chronometer, @{term \"3::4\"} is the\nlevel of water measured by the chronometer, and @{term \"4::4\"} states whether the pump is on\n(@{text \"s$4 = 1\"}) or off (@{text \"s$4 = 0\"}). We prove that the controller keeps the level of\nwater between @{text \"hmin\"} and @{text \"hmax\"}. \\<close>\n\nabbreviation tank_vec_field :: \"real \\<Rightarrow> real^4 \\<Rightarrow> real^4\" (\"f\")\n  where \"f k s \\<equiv> (\\<chi> i. if i = 2 then 1 else (if i = 1 then k else 0))\"\n\nabbreviation tank_flow :: \"real \\<Rightarrow> real \\<Rightarrow> real^4 \\<Rightarrow> real^4\" (\"\\<phi>\")\n  where \"\\<phi> k \\<tau> s \\<equiv> (\\<chi> i. if i = 1 then k * \\<tau> + s$1 else \n  (if i = 2 then \\<tau> + s$2 else s$i))\"\n\nabbreviation tank_guard :: \"real \\<Rightarrow> real \\<Rightarrow> real^4 \\<Rightarrow> bool\" (\"G\")\n  where \"G Hm k s \\<equiv> s$2 \\<le> (Hm - s$3)/k\"\n\nabbreviation tank_loop_inv :: \"real \\<Rightarrow> real \\<Rightarrow> real^4 \\<Rightarrow> bool\" (\"I\")\n  where \"I hmin hmax s \\<equiv> hmin \\<le> s$1 \\<and> s$1 \\<le> hmax \\<and> (s$4 = 0 \\<or> s$4 = 1)\"\n\nabbreviation tank_diff_inv :: \"real \\<Rightarrow> real \\<Rightarrow> real \\<Rightarrow> real^4 \\<Rightarrow> bool\" (\"dI\")\n  where \"dI hmin hmax k s \\<equiv> s$1 = k * s$2 + s$3 \\<and> 0 \\<le> s$2 \\<and> \n    hmin \\<le> s$3 \\<and> s$3 \\<le> hmax \\<and> (s$4 =0 \\<or> s$4 = 1)\"\n\nlemma local_flow_tank: \"local_flow (f k) UNIV UNIV (\\<phi> k)\"\n  apply (unfold_locales, unfold local_lipschitz_def lipschitz_on_def, simp_all, clarsimp)\n  apply(rule_tac x=\"1/2\" in exI, clarsimp, rule_tac x=1 in exI)\n  apply(simp add: dist_norm norm_vec_def L2_set_def, unfold UNIV_4)\n  by (auto intro!: poly_derivatives simp: vec_eq_iff)\n\nlemma tank_arith:\n  assumes \"0 \\<le> (\\<tau>::real)\" and \"0 < c\\<^sub>o\" and \"c\\<^sub>o < c\\<^sub>i\"\n  shows \"\\<forall>\\<tau>\\<in>{0..\\<tau>}. \\<tau> \\<le> - ((hmin - y) / c\\<^sub>o) \\<Longrightarrow>  hmin \\<le> y - c\\<^sub>o * \\<tau>\"\n    and \"\\<forall>\\<tau>\\<in>{0..\\<tau>}. \\<tau> \\<le> (hmax - y) / (c\\<^sub>i - c\\<^sub>o) \\<Longrightarrow>  (c\\<^sub>i - c\\<^sub>o) * \\<tau> + y \\<le> hmax\"\n    and \"hmin \\<le> y \\<Longrightarrow> hmin \\<le> (c\\<^sub>i - c\\<^sub>o) * \\<tau> + y\"\n    and \"y \\<le> hmax \\<Longrightarrow> y - c\\<^sub>o * \\<tau> \\<le> hmax\"\n  apply(simp_all add: field_simps le_divide_eq assms)\n  using assms apply (meson add_mono less_eq_real_def mult_left_mono)\n  using assms by (meson add_increasing2 less_eq_real_def mult_nonneg_nonneg) \n\nlemma tank_flow:\n  assumes \"0 < c\\<^sub>o\" and \"c\\<^sub>o < c\\<^sub>i\"\n  shows \"I hmin hmax \\<le>\n  |LOOP \n    \\<comment> \\<open>control\\<close>\n    ((2 ::=(\\<lambda>s.0));(3 ::=(\\<lambda>s. s$1));\n    (IF (\\<lambda>s. s$4 = 0 \\<and> s$3 \\<le> hmin + 1) THEN (4 ::= (\\<lambda>s.1)) ELSE \n    (IF (\\<lambda>s. s$4 = 1 \\<and> s$3 \\<ge> hmax - 1) THEN (4 ::= (\\<lambda>s.0)) ELSE skip));\n    \\<comment> \\<open>dynamics\\<close>\n    (IF (\\<lambda>s. s$4 = 0) THEN (x\\<acute>= f (c\\<^sub>i-c\\<^sub>o) & (G hmax (c\\<^sub>i-c\\<^sub>o))) \n     ELSE (x\\<acute>= f (-c\\<^sub>o) & (G hmin (-c\\<^sub>o)))) ) INV I hmin hmax]  \n  I hmin hmax\"\n  apply(rule fbox_loopI, simp_all add: le_fun_def)\n  apply(clarsimp simp: le_fun_def local_flow.fbox_g_ode_subset[OF local_flow_tank])\n  using assms tank_arith[OF _ assms] by auto\n\nno_notation tank_vec_field (\"f\")\n        and tank_flow (\"\\<phi>\")\n        and tank_loop_inv (\"I\")\n        and tank_diff_inv (\"dI\")\n        and tank_guard (\"G\")\n\nend", "meta": {"author": "isabelle-prover", "repo": "mirror-afp-devel", "sha": "c84055551f07621736c3eb6a1ef4fb7e8cc57dd1", "save_path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel", "path": "github-repos/isabelle/isabelle-prover-mirror-afp-devel/mirror-afp-devel-c84055551f07621736c3eb6a1ef4fb7e8cc57dd1/thys/Hybrid_Systems_VCs/HS_VC_Examples.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.8633916099737806, "lm_q1q2_score": 0.7501377549895926}}
{"text": "theory\n  Vector_Derivative_On\nimports\n  \"HOL-Analysis.Analysis\"\nbegin\n\nsubsection \\<open>Vector derivative on a set\\<close>\n  \\<comment> \\<open>TODO: also for the other derivatives?!\\<close>\n  \\<comment> \\<open>TODO: move to repository and rewrite assumptions of common lemmas?\\<close>\n\ndefinition\n  has_vderiv_on :: \"(real \\<Rightarrow> 'a::real_normed_vector) \\<Rightarrow> (real \\<Rightarrow> 'a) \\<Rightarrow> real set \\<Rightarrow> bool\"\n  (infix \"(has'_vderiv'_on)\" 50)\nwhere\n  \"(f has_vderiv_on f') S \\<longleftrightarrow> (\\<forall>x \\<in> S. (f has_vector_derivative f' x) (at x within S))\"\n\nlemma has_vderiv_on_empty[intro, simp]: \"(f has_vderiv_on f') {}\"\n  by (auto simp: has_vderiv_on_def)\n\nlemma has_vderiv_on_subset:\n  assumes \"(f has_vderiv_on f') S\"\n  assumes \"T \\<subseteq> S\"\n  shows \"(f has_vderiv_on f') T\"\n  by (meson assms(1) assms(2) contra_subsetD has_vderiv_on_def has_vector_derivative_within_subset)\n\nlemma has_vderiv_on_compose:\n  assumes \"(f has_vderiv_on f') (g ` T)\"\n  assumes \"(g has_vderiv_on g') T\"\n  shows \"(f o g has_vderiv_on (\\<lambda>x. g' x *\\<^sub>R f' (g x))) T\"\n  using assms\n  unfolding has_vderiv_on_def\n  by (auto intro!: vector_diff_chain_within)\n\nlemma has_vderiv_on_open:\n  assumes \"open T\"\n  shows \"(f has_vderiv_on f') T \\<longleftrightarrow> (\\<forall>t \\<in> T. (f has_vector_derivative f' t) (at t))\"\n  by (auto simp: has_vderiv_on_def at_within_open[OF _ \\<open>open T\\<close>])\n\nlemma has_vderiv_on_eq_rhs:\\<comment> \\<open>TODO: integrate intro \\<open>derivative_eq_intros\\<close>\\<close>\n  \"(f has_vderiv_on g') T \\<Longrightarrow> (\\<And>x. x \\<in> T \\<Longrightarrow> g' x = f' x) \\<Longrightarrow> (f has_vderiv_on f') T\"\n  by (auto simp: has_vderiv_on_def)\n\nlemma [THEN has_vderiv_on_eq_rhs, derivative_intros]:\n  shows has_vderiv_on_id: \"((\\<lambda>x. x) has_vderiv_on (\\<lambda>x. 1)) T\"\n    and has_vderiv_on_const: \"((\\<lambda>x. c) has_vderiv_on (\\<lambda>x. 0)) T\"\n  by (auto simp: has_vderiv_on_def intro!: derivative_eq_intros)\n\nlemma [THEN has_vderiv_on_eq_rhs, derivative_intros]:\n  fixes f::\"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"(f has_vderiv_on f') T\"\n  shows has_vderiv_on_uminus: \"((\\<lambda>x. - f x) has_vderiv_on (\\<lambda>x. - f' x)) T\"\n  using assms\n  by (auto simp: has_vderiv_on_def intro!: derivative_eq_intros)\n\nlemma [THEN has_vderiv_on_eq_rhs, derivative_intros]:\n  fixes f g::\"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"(f has_vderiv_on f') T\"\n  assumes \"(g has_vderiv_on g') T\"\n  shows has_vderiv_on_add: \"((\\<lambda>x. f x + g x) has_vderiv_on (\\<lambda>x. f' x + g' x)) T\"\n   and has_vderiv_on_diff: \"((\\<lambda>x. f x - g x) has_vderiv_on (\\<lambda>x. f' x - g' x)) T\"\n  using assms\n  by (auto simp: has_vderiv_on_def intro!: derivative_eq_intros)\n\nlemma [THEN has_vderiv_on_eq_rhs, derivative_intros]:\n  fixes f::\"real \\<Rightarrow> real\" and g::\"real \\<Rightarrow> 'a::real_normed_vector\"\n  assumes \"(f has_vderiv_on f') T\"\n  assumes \"(g has_vderiv_on g') T\"\n  shows has_vderiv_on_scaleR: \"((\\<lambda>x. f x *\\<^sub>R g x) has_vderiv_on (\\<lambda>x. f x *\\<^sub>R g' x + f' x *\\<^sub>R g x)) T\"\n  using assms\n  by (auto simp: has_vderiv_on_def has_field_derivative_iff_has_vector_derivative\n    intro!: derivative_eq_intros)\n\nlemma [THEN has_vderiv_on_eq_rhs, derivative_intros]:\n  fixes f g::\"real \\<Rightarrow> 'a::real_normed_algebra\"\n  assumes \"(f has_vderiv_on f') T\"\n  assumes \"(g has_vderiv_on g') T\"\n  shows has_vderiv_on_mult: \"((\\<lambda>x. f x * g x) has_vderiv_on (\\<lambda>x. f x * g' x + f' x * g x)) T\"\n  using assms\n  by (auto simp: has_vderiv_on_def intro!: derivative_eq_intros)\n\nlemma has_vderiv_on_ln[THEN has_vderiv_on_eq_rhs, derivative_intros]:\n  fixes g::\"real \\<Rightarrow> real\"\n  assumes \"\\<And>x. x \\<in> s \\<Longrightarrow> 0 < g x\"\n  assumes \"(g has_vderiv_on g') s\"\n  shows \"((\\<lambda>x. ln (g x)) has_vderiv_on (\\<lambda>x. g' x / g x)) s\"\n  using assms\n  unfolding has_vderiv_on_def\n  by (auto simp: has_vderiv_on_def has_field_derivative_iff_has_vector_derivative[symmetric]\n    intro!: derivative_eq_intros)\n\n\nlemma fundamental_theorem_of_calculus':\n  fixes f :: \"real \\<Rightarrow> 'a::banach\"\n  shows \"a \\<le> b \\<Longrightarrow> (f has_vderiv_on f') {a .. b} \\<Longrightarrow> (f' has_integral (f b - f a)) {a .. b}\"\n  by (auto intro!: fundamental_theorem_of_calculus simp: has_vderiv_on_def)\n\nlemma has_vderiv_on_If:\n  assumes \"U = S \\<union> T\"\n  assumes \"(f has_vderiv_on f') (S \\<union> (closure T \\<inter> closure S))\"\n  assumes \"(g has_vderiv_on g') (T \\<union> (closure T \\<inter> closure S))\"\n  assumes \"\\<And>x. x \\<in> closure T \\<Longrightarrow> x \\<in> closure S \\<Longrightarrow> f x = g x\"\n  assumes \"\\<And>x. x \\<in> closure T \\<Longrightarrow> x \\<in> closure S \\<Longrightarrow> f' x = g' x\"\n  shows \"((\\<lambda>t. if t \\<in> S then f t else g t) has_vderiv_on (\\<lambda>t. if t \\<in> S then f' t else g' t)) U\"\n  using assms\n  by (auto simp: has_vderiv_on_def ac_simps\n      intro!: has_vector_derivative_If_within_closures\n      split del: if_split)\n\nlemma mvt_very_simple_closed_segmentE:\n  fixes f::\"real\\<Rightarrow>real\"\n  assumes \"(f has_vderiv_on f') (closed_segment a b)\"\n  obtains y where \"y \\<in> closed_segment a b\"  \"f b - f a = (b - a) * f' y\"\nproof cases\n  assume \"a \\<le> b\"\n  with mvt_very_simple[of a b f \"\\<lambda>x i. i *\\<^sub>R f' x\"] assms\n  obtain y where \"y \\<in> closed_segment a b\"  \"f b - f a = (b - a) * f' y\"\n    by (auto simp: has_vector_derivative_def closed_segment_eq_real_ivl has_vderiv_on_def)\n  thus ?thesis ..\nnext\n  assume \"\\<not> a \\<le> b\"\n  with mvt_very_simple[of b a f \"\\<lambda>x i. i *\\<^sub>R f' x\"] assms\n  obtain y where \"y \\<in> closed_segment a b\"  \"f b - f a = (b - a) * f' y\"\n    by (force simp: has_vector_derivative_def has_vderiv_on_def closed_segment_eq_real_ivl algebra_simps)\n  thus ?thesis ..\nqed\n\nlemma mvt_simple_closed_segmentE:\n  fixes f::\"real\\<Rightarrow>real\"\n  assumes \"(f has_vderiv_on f') (closed_segment a b)\"\n  assumes \"a \\<noteq> b\"\n  obtains y where \"y \\<in> open_segment a b\"  \"f b - f a = (b - a) * f' y\"\nproof cases\n  assume \"a \\<le> b\"\n  with assms have \"a < b\" by simp\n  with mvt_simple[of a b f \"\\<lambda>x i. i *\\<^sub>R f' x\"] assms\n  obtain y where \"y \\<in> open_segment a b\"  \"f b - f a = (b - a) * f' y\"\n    by (auto simp: has_vector_derivative_def closed_segment_eq_real_ivl has_vderiv_on_def\n        open_segment_eq_real_ivl)\n  thus ?thesis ..\nnext\n  assume \"\\<not> a \\<le> b\"\n  then have \"b < a\" by simp\n  with mvt_simple[of b a f \"\\<lambda>x i. i *\\<^sub>R f' x\"] assms\n  obtain y where \"y \\<in> open_segment a b\"  \"f b - f a = (b - a) * f' y\"\n    by (force simp: has_vector_derivative_def has_vderiv_on_def closed_segment_eq_real_ivl algebra_simps\n      open_segment_eq_real_ivl)\n  thus ?thesis ..\nqed\n\nlemma differentiable_bound_general_open_segment:\n  fixes a :: \"real\"\n    and b :: \"real\"\n    and f :: \"real \\<Rightarrow> 'a::real_normed_vector\"\n    and f' :: \"real \\<Rightarrow> 'a\"\n  assumes \"continuous_on (closed_segment a b) f\"\n  assumes \"continuous_on (closed_segment a b) g\"\n    and \"(f has_vderiv_on f') (open_segment a b)\"\n    and \"(g has_vderiv_on g') (open_segment a b)\"\n    and \"\\<And>x. x \\<in> open_segment a b \\<Longrightarrow> norm (f' x) \\<le> g' x\"\n  shows \"norm (f b - f a) \\<le> abs (g b - g a)\"\nproof -\n  {\n    assume \"a = b\"\n    hence ?thesis by simp\n  } moreover {\n    assume \"a < b\"\n    with assms\n    have \"continuous_on {a .. b} f\"\n      and \"continuous_on {a .. b} g\"\n      and \"\\<And>x. x\\<in>{a<..<b} \\<Longrightarrow> (f has_vector_derivative f' x) (at x)\"\n      and \"\\<And>x. x\\<in>{a<..<b} \\<Longrightarrow> (g has_vector_derivative g' x) (at x)\"\n      and \"\\<And>x. x\\<in>{a<..<b} \\<Longrightarrow> norm (f' x) \\<le> g' x\"\n      by (auto simp: open_segment_eq_real_ivl closed_segment_eq_real_ivl has_vderiv_on_def\n        at_within_open[where S=\"{a<..<b}\"])\n    from differentiable_bound_general[OF \\<open>a < b\\<close> this]\n    have ?thesis by auto\n  } moreover {\n    assume \"b < a\"\n    with assms\n    have \"continuous_on {b .. a} f\"\n      and \"continuous_on {b .. a} g\"\n      and \"\\<And>x. x\\<in>{b<..<a} \\<Longrightarrow> (f has_vector_derivative f' x) (at x)\"\n      and \"\\<And>x. x\\<in>{b<..<a} \\<Longrightarrow> (g has_vector_derivative g' x) (at x)\"\n      and \"\\<And>x. x\\<in>{b<..<a} \\<Longrightarrow> norm (f' x) \\<le> g' x\"\n      by (auto simp: open_segment_eq_real_ivl closed_segment_eq_real_ivl has_vderiv_on_def\n        at_within_open[where S=\"{b<..<a}\"])\n    from differentiable_bound_general[OF \\<open>b < a\\<close> this]\n    have \"norm (f a - f b) \\<le> g a - g b\" by simp\n    also have \"\\<dots> \\<le> abs (g b - g a)\" by simp\n    finally have ?thesis by (simp add: norm_minus_commute)\n  } ultimately show ?thesis by arith\nqed\n\n\n\nlemma has_vderiv_on_union_closed:\n  assumes \"(f has_vderiv_on g) s\"\n  assumes \"(f has_vderiv_on g) t\"\n  assumes \"closed s\" \"closed t\"\n  shows \"(f has_vderiv_on g) (s \\<union> t)\"\n  using has_vderiv_on_If[OF refl, of f g s t f g] assms\n  by (auto simp: has_vderiv_on_subset)\n\nlemma vderiv_on_continuous_on: \"(f has_vderiv_on f') S \\<Longrightarrow> continuous_on S f\"\n  by (auto intro!: continuous_on_vector_derivative simp: has_vderiv_on_def)\n\nlemma has_vderiv_on_cong[cong]:\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> f' x = g' x\"\n  assumes \"S = T\"\n  shows \"(f has_vderiv_on f') S = (g has_vderiv_on g') T\"\n  using assms\n  by (metis has_vector_derivative_transform has_vderiv_on_def)\n\nlemma has_vderiv_eq:\n  assumes \"(f has_vderiv_on f') S\"\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> f x = g x\"\n  assumes \"\\<And>x. x \\<in> S \\<Longrightarrow> f' x = g' x\"\n  assumes \"S = T\"\n  shows \"(g has_vderiv_on g') T\"\n  using assms by simp\n\nlemma has_vderiv_on_compose':\n  assumes \"(f has_vderiv_on f') (g ` T)\"\n  assumes \"(g has_vderiv_on g') T\"\n  shows \"((\\<lambda>x. f (g x)) has_vderiv_on (\\<lambda>x. g' x *\\<^sub>R f' (g x))) T\"\n  using has_vderiv_on_compose[OF assms]\n  by simp\n\nlemma has_vderiv_on_compose2:\n  assumes \"(f has_vderiv_on f') S\"\n  assumes \"(g has_vderiv_on g') T\"\n  assumes \"\\<And>t. t \\<in> T \\<Longrightarrow> g t \\<in> S\"\n  shows \"((\\<lambda>x. f (g x)) has_vderiv_on (\\<lambda>x. g' x *\\<^sub>R f' (g x))) T\"\n  using has_vderiv_on_compose[OF has_vderiv_on_subset[OF assms(1)] assms(2)] assms(3)\n  by force\n\nlemma has_vderiv_on_singleton: \"(y has_vderiv_on y') {t0}\"\n  by (auto simp: has_vderiv_on_def has_vector_derivative_def has_derivative_within_singleton_iff\n      bounded_linear_scaleR_left)\n\nlemma\n  has_vderiv_on_zero_constant:\n  assumes \"convex s\"\n  assumes \"(f has_vderiv_on (\\<lambda>h. 0)) s\"\n  obtains c where \"\\<And>x. x \\<in> s \\<Longrightarrow> f x = c\"\n  using has_vector_derivative_zero_constant[of s f] assms\n  by (auto simp: has_vderiv_on_def)\n\nlemma bounded_vderiv_on_imp_lipschitz:\n  assumes \"(f has_vderiv_on f') X\"\n  assumes convex: \"convex X\"\n  assumes \"\\<And>x. x \\<in> X \\<Longrightarrow> norm (f' x) \\<le> C\" \"0 \\<le> C\"\n  shows \"C-lipschitz_on X f\"\n  using assms\n  by (auto simp: has_vderiv_on_def has_vector_derivative_def onorm_scaleR_left onorm_id\n    intro!: bounded_derivative_imp_lipschitz[where f' = \"\\<lambda>x d. d *\\<^sub>R f' x\"])\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Ordinary_Differential_Equations/Library/Vector_Derivative_On.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.8688267762381843, "lm_q1q2_score": 0.7501377521786118}}
{"text": "theory Ex5_5\n  imports Main\nbegin\n\n(*\nBy: Vadim Zaliva <vzaliva@cmu.edu>\nFrom: T. Nipkow and G. Klein, Concrete Semantics with Isabelle/HOL. Springer, 2014.\nExercise 5.5:\n*)\n\ninductive star :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  refl: \"star r x x\" |\n  step: \"r x y \\<Longrightarrow> star r y z \\<Longrightarrow> star r x z\"\n\ninductive iter :: \"('a \\<Rightarrow> 'a \\<Rightarrow> bool) \\<Rightarrow> nat \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> bool\" for r where\n  zero: \"iter r 0 x x\" |\n  step: \"r x y \\<Longrightarrow> iter r n y z \\<Longrightarrow> iter r (Suc n) x z\"\n\nlemma iter_star :  \"iter r n x y \\<Longrightarrow> star r x y\"\nproof (induction rule: iter.induct)\n  case zero\n  show ?case by (rule star.refl)\nnext\n  case step\n  then show ?case by (metis star.step)\nqed\n\nend\n", "meta": {"author": "vzaliva", "repo": "isabelle-semantics-ex", "sha": "4e1acf1c9850f17057dd98454e42262d01301670", "save_path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex", "path": "github-repos/isabelle/vzaliva-isabelle-semantics-ex/isabelle-semantics-ex-4e1acf1c9850f17057dd98454e42262d01301670/Ex5_5.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.8267117983401363, "lm_q1q2_score": 0.7500857264649051}}
{"text": "section \\<open>\\isaheader{Operations on sorted Lists}\\<close>\ntheory Sorted_List_Operations\nimports Main Automatic_Refinement.Misc\nbegin \n\nfun inter_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"inter_sorted [] l2 = []\"\n | \"inter_sorted l1 [] = []\"\n | \"inter_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then (inter_sorted l1 (x2 # l2)) else \n     (if (x1 = x2) then x1 # (inter_sorted l1 l2) else inter_sorted (x1 # l1) l2))\"\n\nlemma inter_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"distinct (inter_sorted l1 l2) \\<and> sorted (inter_sorted l1 l2) \\<and> \n       set (inter_sorted l1 l2) = set l1 \\<inter> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply (auto simp add: Ball_def)\n        apply (metis linorder_not_le)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis by (simp add: x1_eq_x2 Ball_def)\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n        show ?thesis \n          apply (auto simp add: x2_less_x1 Ball_def)\n          apply (metis linorder_not_le x2_less_x1)\n        done\n      qed\n    qed\n  qed\nqed\n\nfun diff_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> 'a list\" where\n   \"diff_sorted [] l2 = []\"\n | \"diff_sorted l1 [] = l1\"\n | \"diff_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then x1 # (diff_sorted l1 (x2 # l2)) else \n     (if (x1 = x2) then (diff_sorted l1 l2) else diff_sorted (x1 # l1) l2))\"\n\nlemma diff_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"distinct (diff_sorted l1 l2) \\<and> sorted (diff_sorted l1 l2) \\<and> \n       set (diff_sorted l1 l2) = set l1 - set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply simp\n        apply (simp add: Ball_def set_eq_iff)\n        apply (metis linorder_not_le order_less_imp_not_eq2)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis by (simp add: x1_eq_x2 Ball_def)\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from x2_less_x1 x1_le have x2_nin_l1: \"x2 \\<notin> set l1\"\n           by (metis linorder_not_less)\n\n        from ind_hyp_l2 x1_le x2_nin_l1\n        show ?thesis \n          apply (simp add: x2_less_x1 x1_neq_x2 x2_le_x1 x1_nin_l1 Ball_def set_eq_iff)\n          apply (metis x1_neq_x2)\n        done\n      qed\n    qed\n  qed\nqed\n\nfun subset_sorted :: \"'a::{linorder} list \\<Rightarrow> 'a list \\<Rightarrow> bool\" where\n   \"subset_sorted [] l2 = True\"\n | \"subset_sorted (x1 # l1) [] = False\"\n | \"subset_sorted (x1 # l1) (x2 # l2) =\n    (if (x1 < x2) then False else \n     (if (x1 = x2) then (subset_sorted l1 l2) else subset_sorted (x1 # l1) l2))\"\n\nlemma subset_sorted_correct :\nassumes l1_OK: \"distinct l1 \\<and> sorted l1\"\nassumes l2_OK: \"distinct l2 \\<and> sorted l2\"\nshows \"subset_sorted l1 l2 \\<longleftrightarrow> set l1 \\<subseteq> set l2\"\nusing assms\nproof (induct l1 arbitrary: l2) \n  case Nil thus ?case by simp\nnext\n  case (Cons x1 l1 l2) \n  note x1_l1_props = Cons(2)\n  note l2_props = Cons(3)\n\n  from x1_l1_props have l1_props: \"distinct l1 \\<and> sorted l1\"\n                    and x1_nin_l1: \"x1 \\<notin> set l1\"\n                    and x1_le: \"\\<And>x. x \\<in> set l1 \\<Longrightarrow> x1 \\<le> x\"\n    by (simp_all add: Ball_def)\n\n  note ind_hyp_l1 = Cons(1)[OF l1_props]\n\n  show ?case\n  using l2_props \n  proof (induct l2)\n    case Nil with x1_l1_props show ?case by simp\n  next\n    case (Cons x2 l2)\n    note x2_l2_props = Cons(2)\n    from x2_l2_props have l2_props: \"distinct l2 \\<and> sorted l2\"\n                    and x2_nin_l2: \"x2 \\<notin> set l2\"\n                    and x2_le: \"\\<And>x. x \\<in> set l2 \\<Longrightarrow> x2 \\<le> x\"\n    by (simp_all add: Ball_def)\n\n    note ind_hyp_l2 = Cons(1)[OF l2_props]\n    show ?case\n    proof (cases \"x1 < x2\")\n      case True note x1_less_x2 = this\n\n      from ind_hyp_l1[OF x2_l2_props] x1_less_x2 x1_nin_l1 x1_le x2_le\n      show ?thesis\n        apply (auto simp add: Ball_def)\n        apply (metis linorder_not_le)\n      done\n    next\n      case False note x2_le_x1 = this\n      \n      show ?thesis\n      proof (cases \"x1 = x2\")\n        case True note x1_eq_x2 = this\n\n        from ind_hyp_l1[OF l2_props] x1_le x2_le x2_nin_l2 x1_eq_x2 x1_nin_l1\n        show ?thesis \n          apply (simp add: subset_iff x1_eq_x2 Ball_def)\n          apply metis\n        done\n      next\n        case False note x1_neq_x2 = this\n        with x2_le_x1 have x2_less_x1 : \"x2 < x1\" by auto\n\n        from ind_hyp_l2 x2_le_x1 x1_neq_x2 x2_le x2_nin_l2 x1_le\n        show ?thesis \n          apply (simp add: subset_iff x2_less_x1 Ball_def)\n          apply (metis linorder_not_le x2_less_x1)\n        done\n      qed\n    qed\n  qed\nqed\n\nlemma set_eq_sorted_correct :\n  assumes l1_OK: \"distinct l1 \\<and> sorted l1\"\n  assumes l2_OK: \"distinct l2 \\<and> sorted l2\"\n  shows \"l1 = l2 \\<longleftrightarrow> set l1 = set l2\"\n  using assms\nproof -\n  have l12_eq: \"l1 = l2 \\<longleftrightarrow> subset_sorted l1 l2 \\<and> subset_sorted l2 l1\"\n  proof (induct l1 arbitrary: l2)\n    case Nil thus ?case by (cases l2) auto\n  next\n    case (Cons x1 l1')\n    note ind_hyp = Cons(1)\n\n    show ?case\n    proof (cases l2)\n      case Nil thus ?thesis by simp\n    next\n      case (Cons x2 l2')\n      thus ?thesis by (simp add: ind_hyp)\n    qed\n  qed\n  also have \"\\<dots> \\<longleftrightarrow> ((set l1 \\<subseteq> set l2) \\<and> (set l2 \\<subseteq> set l1))\"\n    using subset_sorted_correct[OF l1_OK l2_OK] subset_sorted_correct[OF l2_OK l1_OK]\n    by simp\n  also have \"\\<dots> \\<longleftrightarrow> set l1 = set l2\" by auto\n  finally show ?thesis .\nqed\n\nfun memb_sorted where\n   \"memb_sorted [] x = False\"\n | \"memb_sorted (y # xs) x =\n    (if (y < x) then memb_sorted xs x else (x = y))\"\n\nlemma memb_sorted_correct :\n  \"sorted xs \\<Longrightarrow> memb_sorted xs x \\<longleftrightarrow> x \\<in> set xs\"\nby (induct xs) (auto simp add: Ball_def)\n\n\nfun insertion_sort where\n   \"insertion_sort x [] = [x]\"\n | \"insertion_sort x (y # xs) =\n    (if (y < x) then y # insertion_sort x xs else \n     (if (x = y) then y # xs else x # y # xs))\"\n\nlemma insertion_sort_correct :\n  \"sorted xs \\<Longrightarrow> distinct xs \\<Longrightarrow>\n   distinct (insertion_sort x xs) \\<and> \n   sorted (insertion_sort x xs) \\<and>\n   set (insertion_sort x xs) = set (x # xs)\"\nby (induct xs) (auto simp add: Ball_def)\n\nfun delete_sorted where\n   \"delete_sorted x [] = []\"\n | \"delete_sorted x (y # xs) =\n    (if (y < x) then y # delete_sorted x xs else \n     (if (x = y) then xs else y # xs))\"\n\nlemma delete_sorted_correct :\n  \"sorted xs \\<Longrightarrow> distinct xs \\<Longrightarrow>\n   distinct (delete_sorted x xs) \\<and> \n   sorted (delete_sorted x xs) \\<and>\n   set (delete_sorted x xs) = set xs - {x}\"\napply (induct xs) \napply simp\napply (simp add: Ball_def set_eq_iff)\napply (metis order_less_le)\ndone\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Evaluation/Collections/Lib/Sorted_List_Operations.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382129861583, "lm_q2_score": 0.8705972784807408, "lm_q1q2_score": 0.7500528235329101}}
{"text": "(*  Title:      Sequents/LK/Propositional.thy\n    Author:     Lawrence C Paulson, Cambridge University Computer Laboratory\n    Copyright   1992  University of Cambridge\n*)\n\nsection \\<open>Classical sequent calculus: examples with propositional connectives\\<close>\n\ntheory Propositional\nimports \"../LK\"\nbegin\n\ntext \"absorptive laws of \\<and> and \\<or>\"\n\nlemma \"\\<turnstile> P \\<and> P \\<longleftrightarrow> P\"\n  by fast_prop\n\nlemma \"\\<turnstile> P \\<or> P \\<longleftrightarrow> P\"\n  by fast_prop\n\n\ntext \"commutative laws of \\<and> and \\<or>\"\n\nlemma \"\\<turnstile> P \\<and> Q \\<longleftrightarrow> Q \\<and> P\"\n  by fast_prop\n\nlemma \"\\<turnstile> P \\<or> Q \\<longleftrightarrow> Q \\<or> P\"\n  by fast_prop\n\n\ntext \"associative laws of \\<and> and \\<or>\"\n\nlemma \"\\<turnstile> (P \\<and> Q) \\<and> R \\<longleftrightarrow> P \\<and> (Q \\<and> R)\"\n  by fast_prop\n\nlemma \"\\<turnstile> (P \\<or> Q) \\<or> R \\<longleftrightarrow> P \\<or> (Q \\<or> R)\"\n  by fast_prop\n\n\ntext \"distributive laws of \\<and> and \\<or>\"\n\nlemma \"\\<turnstile> (P \\<and> Q) \\<or> R \\<longleftrightarrow> (P \\<or> R) \\<and> (Q \\<or> R)\"\n  by fast_prop\n\nlemma \"\\<turnstile> (P \\<or> Q) \\<and> R \\<longleftrightarrow> (P \\<and> R) \\<or> (Q \\<and> R)\"\n  by fast_prop\n\n\ntext \"Laws involving implication\"\n\nlemma \"\\<turnstile> (P \\<or> Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<longrightarrow> R) \\<and> (Q \\<longrightarrow> R)\"\n  by fast_prop\n\nlemma \"\\<turnstile> (P \\<and> Q \\<longrightarrow> R) \\<longleftrightarrow> (P \\<longrightarrow> (Q \\<longrightarrow> R))\"\n  by fast_prop\n\nlemma \"\\<turnstile> (P \\<longrightarrow> Q \\<and> R) \\<longleftrightarrow> (P \\<longrightarrow> Q) \\<and> (P \\<longrightarrow> R)\"\n  by fast_prop\n\n\ntext \"Classical theorems\"\n\nlemma \"\\<turnstile> P \\<or> Q \\<longrightarrow> P \\<or> \\<not> P \\<and> Q\"\n  by fast_prop\n\nlemma \"\\<turnstile> (P \\<longrightarrow> Q) \\<and> (\\<not> P \\<longrightarrow> R) \\<longrightarrow> (P \\<and> Q \\<or> R)\"\n  by fast_prop\n\nlemma \"\\<turnstile> P \\<and> Q \\<or> \\<not> P \\<and> R \\<longleftrightarrow> (P \\<longrightarrow> Q) \\<and> (\\<not> P \\<longrightarrow> R)\"\n  by fast_prop\n\nlemma \"\\<turnstile> (P \\<longrightarrow> Q) \\<or> (P \\<longrightarrow> R) \\<longleftrightarrow> (P \\<longrightarrow> Q \\<or> R)\"\n  by fast_prop\n\n\n(*If and only if*)\n\nlemma \"\\<turnstile> (P \\<longleftrightarrow> Q) \\<longleftrightarrow> (Q \\<longleftrightarrow> P)\"\n  by fast_prop\n\nlemma \"\\<turnstile> \\<not> (P \\<longleftrightarrow> \\<not> P)\"\n  by fast_prop\n\n\n(*Sample problems from \n  F. J. Pelletier, \n  Seventy-Five Problems for Testing Automatic Theorem Provers,\n  J. Automated Reasoning 2 (1986), 191-216.\n  Errata, JAR 4 (1988), 236-236.\n*)\n\n(*1*)\nlemma \"\\<turnstile> (P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> \\<not> P)\"\n  by fast_prop\n\n(*2*)\nlemma \"\\<turnstile> \\<not> \\<not> P \\<longleftrightarrow> P\"\n  by fast_prop\n\n(*3*)\nlemma \"\\<turnstile> \\<not> (P \\<longrightarrow> Q) \\<longrightarrow> (Q \\<longrightarrow> P)\"\n  by fast_prop\n\n(*4*)\nlemma \"\\<turnstile> (\\<not> P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> Q \\<longrightarrow> P)\"\n  by fast_prop\n\n(*5*)\nlemma \"\\<turnstile> ((P \\<or> Q) \\<longrightarrow> (P \\<or> R)) \\<longrightarrow> (P \\<or> (Q \\<longrightarrow> R))\"\n  by fast_prop\n\n(*6*)\nlemma \"\\<turnstile> P \\<or> \\<not> P\"\n  by fast_prop\n\n(*7*)\nlemma \"\\<turnstile> P \\<or> \\<not> \\<not> \\<not> P\"\n  by fast_prop\n\n(*8.  Peirce's law*)\nlemma \"\\<turnstile> ((P \\<longrightarrow> Q) \\<longrightarrow> P) \\<longrightarrow> P\"\n  by fast_prop\n\n(*9*)\nlemma \"\\<turnstile> ((P \\<or> Q) \\<and> (\\<not> P \\<or> Q) \\<and> (P \\<or> \\<not> Q)) \\<longrightarrow> \\<not> (\\<not> P \\<or> \\<not> Q)\"\n  by fast_prop\n\n(*10*)\nlemma \"Q \\<longrightarrow> R, R \\<longrightarrow> P \\<and> Q, P \\<longrightarrow> (Q \\<or> R) \\<turnstile> P \\<longleftrightarrow> Q\"\n  by fast_prop\n\n(*11.  Proved in each direction (incorrectly, says Pelletier!!)  *)\nlemma \"\\<turnstile> P \\<longleftrightarrow> P\"\n  by fast_prop\n\n(*12.  \"Dijkstra's law\"*)\nlemma \"\\<turnstile> ((P \\<longleftrightarrow> Q) \\<longleftrightarrow> R) \\<longleftrightarrow> (P \\<longleftrightarrow> (Q \\<longleftrightarrow> R))\"\n  by fast_prop\n\n(*13.  Distributive law*)\nlemma \"\\<turnstile> P \\<or> (Q \\<and> R) \\<longleftrightarrow> (P \\<or> Q) \\<and> (P \\<or> R)\"\n  by fast_prop\n\n(*14*)\nlemma \"\\<turnstile> (P \\<longleftrightarrow> Q) \\<longleftrightarrow> ((Q \\<or> \\<not> P) \\<and> (\\<not> Q \\<or> P))\"\n  by fast_prop\n\n(*15*)\nlemma \"\\<turnstile> (P \\<longrightarrow> Q) \\<longleftrightarrow> (\\<not> P \\<or> Q)\"\n  by fast_prop\n\n(*16*)\nlemma \"\\<turnstile> (P \\<longrightarrow> Q) \\<or> (Q \\<longrightarrow> P)\"\n  by fast_prop\n\n(*17*)\nlemma \"\\<turnstile> ((P \\<and> (Q \\<longrightarrow> R)) \\<longrightarrow> S) \\<longleftrightarrow> ((\\<not> P \\<or> Q \\<or> S) \\<and> (\\<not> P \\<or> \\<not> R \\<or> S))\"\n  by fast_prop\n\nend\n", "meta": {"author": "seL4", "repo": "isabelle", "sha": "e1ab32a3bb41728cd19541063283e37919978a4c", "save_path": "github-repos/isabelle/seL4-isabelle", "path": "github-repos/isabelle/seL4-isabelle/isabelle-e1ab32a3bb41728cd19541063283e37919978a4c/src/Sequents/LK/Propositional.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7500528152601696}}
{"text": "(*  Title:       Computing Square Roots using the Babylonian Method\n    Author:      René Thiemann       <rene.thiemann@uibk.ac.at>\n    Maintainer:  René Thiemann\n    License:     LGPL\n*)\n\n(*\nCopyright 2009-2014 René Thiemann\n\nThis file is part of IsaFoR/CeTA.\n\nIsaFoR/CeTA is free software: you can redistribute it and/or modify it under the\nterms of the GNU Lesser General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\n\nIsaFoR/CeTA is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License along\nwith IsaFoR/CeTA. If not, see <http://www.gnu.org/licenses/>.\n*)\n\ntheory Sqrt_Babylonian\nimports \n  Sqrt_Babylonian_Auxiliary\n  NthRoot_Impl\nbegin\n\nsection \\<open>Executable algorithms for square roots\\<close>\n\ntext \\<open>\n  This theory provides executable algorithms for computing square-roots of numbers which\n  are all based on the Babylonian method (which is also known as Heron's method or Newton's method).\n  \n  For integers / naturals / rationals precise algorithms are given, i.e., here $sqrt\\ x$ delivers\n  a list of all integers / naturals / rationals $y$ where $y^2 = x$. \n  To this end, the Babylonian method has been adapted by using integer-divisions.\n\n  In addition to the precise algorithms, we also provide approximation algorithms. One works for \n  arbitrary linear ordered fields, where some number $y$ is computed such that\n  @{term \"abs(y^2 - x) < \\<epsilon>\"}. Moreover, for the naturals, integers, and rationals we provide algorithms to compute\n  @{term \"floor (sqrt x)\"} and @{term \"ceiling (sqrt x)\"} which are all based\n  on the underlying algorithm that is used to compute the precise square-roots on integers, if these \n  exist.\n\n  The major motivation for developing the precise algorithms was given by \\ceta{} \\cite{CeTA},\n  a tool for certifiying termination proofs. Here, non-linear equations of the form\n  $(a_1x_1 + \\dots a_nx_n)^2 = p$ had to be solved over the integers, where $p$ is a concrete polynomial.\n  For example, for the equation $(ax + by)^2 = 4x^2 - 12xy + 9y^2$ one easily figures out that\n  $a^2 = 4, b^2 = 9$, and $ab = -6$, which results in a possible solution $a = \\sqrt 4 = 2, b = - \\sqrt 9 = -3$.\n\\<close>\n\nsubsection \\<open>The Babylonian method\\<close>\n\ntext \\<open>\nThe Babylonian method for computing $\\sqrt n$ iteratively computes \n\\[\nx_{i+1} = \\frac{\\frac n{x_i} + x_i}2\n\\]\nuntil $x_i^2 \\approx n$. Note that if $x_0^2 \\geq n$, then for all $i$ we have both\n$x_i^2 \\geq n$ and $x_i \\geq x_{i+1}$. \n\\<close>\n\nsubsection \\<open>The Babylonian method using integer division\\<close>\ntext \\<open>\n  First, the algorithm is developed for the non-negative integers.\n  Here, the division operation $\\frac xy$ is replaced by @{term \"x div y = \\<lfloor>of_int x / of_int y\\<rfloor>\"}.\n  Note that replacing @{term \"\\<lfloor>of_int x / of_int y\\<rfloor>\"} by @{term \"\\<lceil>of_int x / of_int y\\<rceil>\"} would lead to non-termination\n  in the following algorithm.\n\n  We explicititly develop the algorithm on the integers and not on the naturals, as the calculations\n  on the integers have been much easier. For example, $y - x + x = y$ on the integers, which would require\n  the side-condition $y \\geq x$ for the naturals. These conditions will make the reasoning much more tedious---as\n  we have experienced in an earlier state of this development where everything was based on naturals.\n\n  Since the elements\n  $x_0, x_1, x_2,\\dots$ are monotone decreasing, in the main algorithm we abort as soon as $x_i^2 \\leq n$.\\<close>\n\n\ntext \\<open>\\textbf{Since in the meantime, all of these algorithms have been generalized to arbitrary\n  $p$-th roots in @{theory Sqrt_Babylonian.NthRoot_Impl}, we just instantiate the general algorithms by $p = 2$ and then provide \n  specialized code equations which are more efficient than the general purpose algorithms.}\\<close>\n\ndefinition sqrt_int_main' :: \"int \\<Rightarrow> int \\<Rightarrow> int \\<times> bool\" where\n  [simp]: \"sqrt_int_main' x n = root_int_main' 1 1 2 x n\"\n\nlemma sqrt_int_main'_code[code]: \"sqrt_int_main' x n = (let x2 = x * x in if x2 \\<le> n then (x, x2 = n)\n    else sqrt_int_main' ((n div x + x) div 2) n)\"\n  using root_int_main'.simps[of 1 1 2 x n]\n  unfolding Let_def by auto\n\ndefinition sqrt_int_main :: \"int \\<Rightarrow> int \\<times> bool\" where\n  [simp]: \"sqrt_int_main x = root_int_main 2 x\"\n\nlemma sqrt_int_main_code[code]: \"sqrt_int_main x = sqrt_int_main' (start_value x 2) x\"\n  by (simp add: root_int_main_def Let_def)\n\ndefinition sqrt_int :: \"int \\<Rightarrow> int list\" where\n  \"sqrt_int x = root_int 2 x\"\n\nlemma sqrt_int_code[code]: \"sqrt_int x = (if x < 0 then [] else case sqrt_int_main x of (y,True) \\<Rightarrow> if y = 0 then [0] else [y,-y] | _ \\<Rightarrow> [])\"\nproof -\n  interpret fixed_root 2 1 by (unfold_locales, auto)\n  obtain b y where res: \"root_int_main 2 x = (b,y)\" by force\n  show ?thesis\n    unfolding sqrt_int_def root_int_def Let_def\n    using root_int_main[OF _ res]\n    using res\n    by simp\nqed\n\nlemma sqrt_int[simp]: \"set (sqrt_int x) = {y. y * y = x}\"\n  unfolding sqrt_int_def by (simp add: power2_eq_square)\n\n\nlemma sqrt_int_pos: assumes res: \"sqrt_int x = Cons s ms\"\n  shows \"s \\<ge> 0\"\nproof -\n  note res = res[unfolded sqrt_int_code Let_def, simplified]\n  from res have x0: \"x \\<ge> 0\" by (cases ?thesis, auto)\n  obtain ss b where call: \"sqrt_int_main x = (ss,b)\" by force\n  from res[unfolded call] x0 have \"ss = s\" \n    by (cases b, cases \"ss = 0\", auto)\n  from root_int_main(1)[OF x0 call[unfolded this sqrt_int_main_def]]\n  show ?thesis .\nqed\n\ndefinition [simp]: \"sqrt_int_floor_pos x = root_int_floor_pos 2 x\"\n\nlemma sqrt_int_floor_pos_code[code]: \"sqrt_int_floor_pos x = fst (sqrt_int_main x)\"\n  by (simp add: root_int_floor_pos_def)\n\nlemma sqrt_int_floor_pos: assumes x: \"x \\<ge> 0\" \n  shows \"sqrt_int_floor_pos x = \\<lfloor> sqrt (of_int x) \\<rfloor>\"\n  using root_int_floor_pos[OF x, of 2] by (simp add: sqrt_def)\n\ndefinition [simp]: \"sqrt_int_ceiling_pos x = root_int_ceiling_pos 2 x\"\n\nlemma sqrt_int_ceiling_pos_code[code]: \"sqrt_int_ceiling_pos x = (case sqrt_int_main x of (y,b) \\<Rightarrow> if b then y else y + 1)\"\n  by (simp add: root_int_ceiling_pos_def)\n\nlemma sqrt_int_ceiling_pos: assumes x: \"x \\<ge> 0\" \n  shows \"sqrt_int_ceiling_pos x = \\<lceil> sqrt (of_int x) \\<rceil>\"\n  using root_int_ceiling_pos[OF x, of 2] by (simp add: sqrt_def)\n\ndefinition \"sqrt_int_floor x = root_int_floor 2 x\"\n\nlemma sqrt_int_floor_code[code]: \"sqrt_int_floor x = (if x \\<ge> 0 then sqrt_int_floor_pos x else - sqrt_int_ceiling_pos (- x))\"\n  unfolding sqrt_int_floor_def root_int_floor_def by simp\n\nlemma sqrt_int_floor[simp]: \"sqrt_int_floor x = \\<lfloor> sqrt (of_int x) \\<rfloor>\"\n  by (simp add: sqrt_int_floor_def sqrt_def)\n\ndefinition \"sqrt_int_ceiling x = root_int_ceiling 2 x\"\n\nlemma sqrt_int_ceiling_code[code]: \"sqrt_int_ceiling x = (if x \\<ge> 0 then sqrt_int_ceiling_pos x else - sqrt_int_floor_pos (- x))\"\n  unfolding sqrt_int_ceiling_def root_int_ceiling_def by simp\n\nlemma sqrt_int_ceiling[simp]: \"sqrt_int_ceiling x = \\<lceil> sqrt (of_int x) \\<rceil>\"\n  by (simp add: sqrt_int_ceiling_def sqrt_def)\n\nlemma sqrt_int_ceiling_bound: \"0 \\<le> x \\<Longrightarrow> x \\<le> (sqrt_int_ceiling x)^2\"\n  unfolding sqrt_int_ceiling using le_of_int_ceiling sqrt_le_D\n  by (metis of_int_power_le_of_int_cancel_iff)\n\n\nsubsection \\<open>Square roots for the naturals\\<close>\n\n\ndefinition sqrt_nat :: \"nat \\<Rightarrow> nat list\"\n  where \"sqrt_nat x = root_nat 2 x\"\n \nlemma sqrt_nat_code[code]: \"sqrt_nat x \\<equiv> map nat (take 1 (sqrt_int (int x)))\"\n  unfolding sqrt_nat_def root_nat_def sqrt_int_def by simp\n\nlemma sqrt_nat[simp]: \"set (sqrt_nat x) = { y. y * y = x}\" \n  unfolding sqrt_nat_def using root_nat[of 2 x] by (simp add: power2_eq_square)\n\ndefinition sqrt_nat_floor :: \"nat \\<Rightarrow> int\" where\n  \"sqrt_nat_floor x = root_nat_floor 2 x\"\n\nlemma sqrt_nat_floor_code[code]: \"sqrt_nat_floor x = sqrt_int_floor_pos (int x)\"\n  unfolding sqrt_nat_floor_def root_nat_floor_def by simp\n\nlemma sqrt_nat_floor[simp]: \"sqrt_nat_floor x = \\<lfloor> sqrt (real x) \\<rfloor>\"\n  unfolding sqrt_nat_floor_def by (simp add: sqrt_def)\n\ndefinition sqrt_nat_ceiling :: \"nat \\<Rightarrow> int\" where\n  \"sqrt_nat_ceiling x = root_nat_ceiling 2 x\"\n\nlemma sqrt_nat_ceiling_code[code]: \"sqrt_nat_ceiling x = sqrt_int_ceiling_pos (int x)\"\n  unfolding sqrt_nat_ceiling_def root_nat_ceiling_def by simp\n\nlemma sqrt_nat_ceiling[simp]: \"sqrt_nat_ceiling x = \\<lceil> sqrt (real x) \\<rceil>\"\n  unfolding sqrt_nat_ceiling_def by (simp add: sqrt_def)\n\nsubsection \\<open>Square roots for the rationals\\<close>\n\ndefinition sqrt_rat :: \"rat \\<Rightarrow> rat list\" where\n  \"sqrt_rat x = root_rat 2 x\"\n\nlemma sqrt_rat_code[code]: \"sqrt_rat x = (case quotient_of x of (z,n) \\<Rightarrow> (case sqrt_int n of \n    [] \\<Rightarrow> [] \n  | sn # xs \\<Rightarrow> map (\\<lambda> sz. of_int sz / of_int sn) (sqrt_int z)))\"\nproof -\n  obtain z n where q: \"quotient_of x = (z,n)\" by force\n  show ?thesis\n  unfolding sqrt_rat_def root_rat_def q split sqrt_int_def\n  by (cases \"root_int 2 n\", auto)\nqed\n\nlemma sqrt_rat[simp]: \"set (sqrt_rat x) = { y. y * y = x}\"\n  unfolding sqrt_rat_def using root_rat[of 2 x]\n  by (simp add: power2_eq_square)\n\nlemma sqrt_rat_pos: assumes sqrt: \"sqrt_rat x = Cons s ms\" \n  shows \"s \\<ge> 0\"\nproof -\n  obtain z n where q: \"quotient_of x = (z,n)\" by force\n  note sqrt = sqrt[unfolded sqrt_rat_code q, simplified]\n  let ?sz = \"sqrt_int z\"\n  let ?sn = \"sqrt_int n\"\n  from q have n: \"n > 0\" by (rule quotient_of_denom_pos)\n  from sqrt obtain sz mz where sz: \"?sz = sz # mz\" by (cases ?sn, auto)\n  from sqrt obtain sn mn where sn: \"?sn = sn # mn\" by (cases ?sn, auto)\n  from sqrt_int_pos[OF sz] sqrt_int_pos[OF sn] have pos: \"0 \\<le> sz\" \"0 \\<le> sn\" by auto\n  from sqrt sz sn have s: \"s = of_int sz / of_int sn\" by auto\n  show ?thesis unfolding s using pos\n    by (metis of_int_0_le_iff zero_le_divide_iff)\nqed\n\ndefinition sqrt_rat_floor :: \"rat \\<Rightarrow> int\" where\n  \"sqrt_rat_floor x = root_rat_floor 2 x\"\n\nlemma sqrt_rat_floor_code[code]: \"sqrt_rat_floor x = (case quotient_of x of (a,b) \\<Rightarrow> sqrt_int_floor (a * b) div b)\"\n  unfolding sqrt_rat_floor_def root_rat_floor_def by (simp add: sqrt_def)\n\nlemma sqrt_rat_floor[simp]: \"sqrt_rat_floor x = \\<lfloor> sqrt (of_rat x) \\<rfloor>\"\n  unfolding sqrt_rat_floor_def by (simp add: sqrt_def)\n\ndefinition sqrt_rat_ceiling :: \"rat \\<Rightarrow> int\" where\n  \"sqrt_rat_ceiling x = root_rat_ceiling 2 x\"\n\nlemma sqrt_rat_ceiling_code[code]: \"sqrt_rat_ceiling x = - (sqrt_rat_floor (-x))\"\n  unfolding sqrt_rat_ceiling_def sqrt_rat_floor_def root_rat_ceiling_def by simp\n\nlemma sqrt_rat_ceiling: \"sqrt_rat_ceiling x = \\<lceil> sqrt (of_rat x) \\<rceil>\"\n  unfolding sqrt_rat_ceiling_def by (simp add: sqrt_def)\n\nlemma sqr_rat_of_int: assumes x: \"x * x = rat_of_int i\"\n  shows \"\\<exists> j :: int. j * j = i\"\nproof -\n  from x have mem: \"x \\<in> set (sqrt_rat (rat_of_int i))\" by simp\n  from x have \"rat_of_int i \\<ge> 0\" by (metis zero_le_square)\n  hence *: \"quotient_of (rat_of_int i) = (i,1)\" by (metis quotient_of_int)\n  have 1: \"sqrt_int 1 = [1,-1]\" by code_simp\n  from mem sqrt_rat_code * split 1 \n  have x: \"x \\<in> rat_of_int ` {y. y * y = i}\" by auto\n  thus ?thesis by auto\nqed\n\nsubsection \\<open>Approximating square roots\\<close>\n\ntext \\<open>\n  The difference to the previous algorithms is that now we abort, once the distance is below\n  $\\epsilon$.  \n  Moreover, here we use standard division and not integer division.\n  This part is not yet generalized by @{theory Sqrt_Babylonian.NthRoot_Impl}.\n\n  We first provide the executable version without guard @{term \"x > 0\"} as partial function,\n  and afterwards prove termination and soundness for a similar algorithm that is defined within the upcoming\nlocale.\n\\<close>\n\npartial_function (tailrec) sqrt_approx_main_impl :: \"'a :: linordered_field \\<Rightarrow> 'a \\<Rightarrow> 'a \\<Rightarrow> 'a\" where \n  [code]: \"sqrt_approx_main_impl \\<epsilon> n x = (if x * x - n < \\<epsilon> then x else sqrt_approx_main_impl \\<epsilon> n \n    ((n / x + x) / 2))\"\n\ntext \\<open>We setup a locale where we ensure that we have standard assumptions: positive $\\epsilon$ and\n  positive $n$. We require sort @{term floor_ceiling}, since @{term \"\\<lfloor> x \\<rfloor>\"} is used for the termination\n  argument.\\<close>\nlocale sqrt_approximation = \n  fixes \\<epsilon> :: \"'a :: {linordered_field,floor_ceiling}\"\n  and n :: 'a\n  assumes \\<epsilon> : \"\\<epsilon> > 0\"\n  and n: \"n > 0\"\nbegin\n\nfunction sqrt_approx_main :: \"'a \\<Rightarrow> 'a\" where \n  \"sqrt_approx_main x = (if x > 0 then (if x * x - n < \\<epsilon> then x else sqrt_approx_main \n    ((n / x + x) / 2)) else 0)\"\n    by pat_completeness auto\n\ntext \\<open>Termination essentially is a proof of convergence. Here, one complication is the fact\n  that the limit is not always defined. E.g., if @{typ \"'a\"} is @{typ rat} then there is no\n  square root of 2. Therefore, the error-rate $\\frac x{\\sqrt n} - 1$ is not expressible. \n  Instead we use the expression $\\frac{x^2}n - 1$ as error-rate which\n  does not require any square-root operation.\\<close>\ntermination\nproof -\n  define er where \"er x = (x * x / n - 1)\" for x\n  define c where \"c = 2 * n / \\<epsilon>\"\n  define m where \"m x = nat \\<lfloor> c * er x \\<rfloor>\" for x\n  have c: \"c > 0\" unfolding c_def using n \\<epsilon> by auto\n  show ?thesis\n  proof\n    show \"wf (measures [m])\" by simp\n  next\n    fix x \n    assume x: \"0 < x\" and xe: \"\\<not> x * x - n < \\<epsilon>\"\n    define y where \"y = (n / x + x) / 2\"    \n    show \"((n / x + x) / 2,x) \\<in> measures [m]\" unfolding y_def[symmetric]\n    proof (rule measures_less)\n      from n have inv_n: \"1 / n > 0\" by auto\n      from xe have \"x * x - n \\<ge> \\<epsilon>\" by simp\n      from this[unfolded mult_le_cancel_left_pos[OF inv_n, of \\<epsilon>, symmetric]]\n      have erxen: \"er x \\<ge> \\<epsilon> / n\" unfolding er_def using n by (simp add: field_simps)\n      have en: \"\\<epsilon> / n > 0\" and ne: \"n / \\<epsilon> > 0\" using \\<epsilon> n by auto\n      from en erxen have erx: \"er x > 0\" by linarith\n      have pos: \"er x * 4 + er x * (er x * 4) > 0\" using erx\n        by (auto intro: add_pos_nonneg)\n      have \"er y = 1 / 4 * (n / (x * x) - 2  + x * x / n)\" unfolding er_def y_def using x n\n        by (simp add: field_simps)\n      also have \"\\<dots> = 1 / 4 * er x * er x / (1 + er x)\" unfolding er_def using x n\n        by (simp add: field_simps)\n      finally have \"er y = 1 / 4 * er x * er x / (1 + er x)\" .\n      also have \"\\<dots> < 1 / 4 * (1 + er x) * er x / (1 + er x)\" using erx erx pos\n        by (auto simp: field_simps)\n      also have \"\\<dots> = er x / 4\" using erx by (simp add: field_simps)\n      finally have er_y_x: \"er y \\<le> er x / 4\" by linarith\n      from erxen have \"c * er x \\<ge> 2\" unfolding c_def mult_le_cancel_left_pos[OF ne, of _ \"er x\", symmetric]\n        using n \\<epsilon> by (auto simp: field_simps)\n      hence pos: \"\\<lfloor>c * er x\\<rfloor> > 0\" \"\\<lfloor>c * er x\\<rfloor> \\<ge> 2\" by auto\n      show \"m y < m x\" unfolding m_def nat_mono_iff[OF pos(1)]\n      proof -      \n        have \"\\<lfloor>c * er y\\<rfloor> \\<le> \\<lfloor>c * (er x / 4)\\<rfloor>\"\n          by (rule floor_mono, unfold mult_le_cancel_left_pos[OF c], rule er_y_x)\n        also have \"\\<dots> < \\<lfloor>c * er x / 4 + 1\\<rfloor>\" by auto\n        also have \"\\<dots> \\<le> \\<lfloor>c * er x\\<rfloor>\"\n          by (rule floor_mono, insert pos(2), simp add: field_simps)\n        finally show \"\\<lfloor>c * er y\\<rfloor> < \\<lfloor>c * er x\\<rfloor>\" .\n      qed\n    qed\n  qed\nqed\n\ntext \\<open>Once termination is proven, it is easy to show equivalence of \n  @{const sqrt_approx_main_impl} and @{const sqrt_approx_main}.\\<close>\nlemma sqrt_approx_main_impl: \"x > 0 \\<Longrightarrow> sqrt_approx_main_impl \\<epsilon> n x = sqrt_approx_main x\"\nproof (induct x rule: sqrt_approx_main.induct)\n  case (1 x)\n  hence x: \"x > 0\" by auto\n  hence nx: \"0 < (n / x + x) / 2\" using n by (auto intro: pos_add_strict)\n  note simps = sqrt_approx_main_impl.simps[of _ _ x] sqrt_approx_main.simps[of x]\n  show ?case \n  proof (cases \"x * x - n < \\<epsilon>\")\n    case True\n    thus ?thesis unfolding simps using x by auto\n  next\n    case False\n    show ?thesis using 1(1)[OF x False nx] unfolding simps using x False by auto\n  qed\nqed\n\ntext \\<open>Also soundness is not complicated.\\<close>\n\nlemma sqrt_approx_main_sound: assumes x: \"x > 0\" and xx: \"x * x > n\"\n  shows \"sqrt_approx_main x * sqrt_approx_main x > n \\<and> sqrt_approx_main x * sqrt_approx_main x - n < \\<epsilon>\"\n  using assms\nproof (induct x rule: sqrt_approx_main.induct)\n  case (1 x)\n  from 1 have x:  \"x > 0\" \"(x > 0) = True\" by auto\n  note simp = sqrt_approx_main.simps[of x, unfolded x if_True]\n  show ?case\n  proof (cases \"x * x - n < \\<epsilon>\")\n    case True\n    with 1 show ?thesis unfolding simp by simp\n  next\n    case False\n    let ?y = \"(n / x + x) / 2\"\n    from False simp have simp: \"sqrt_approx_main x = sqrt_approx_main ?y\" by simp\n    from n x have y: \"?y > 0\" by (auto intro: pos_add_strict)\n    note IH = 1(1)[OF x(1) False y]\n    from x have x4: \"4 * x * x > 0\" by (auto intro: mult_sign_intros)\n    show ?thesis unfolding simp\n    proof (rule IH)\n      show \"n < ?y * ?y\"\n        unfolding mult_less_cancel_left_pos[OF x4, of n, symmetric]\n      proof -\n        have id: \"4 * x * x * (?y * ?y) = 4 * x * x * n + (n - x * x) * (n - x * x)\" using x(1)\n          by (simp add: field_simps)\n        from 1(3) have \"x * x - n > 0\" by auto\n        from mult_pos_pos[OF this this]\n        show \"4 * x * x * n < 4 * x * x * (?y * ?y)\" unfolding id \n          by (simp add: field_simps)\n      qed\n    qed\n  qed\nqed   \n\nend\n\ntext \\<open>It remains to assemble everything into one algorithm.\\<close>\n\ndefinition sqrt_approx :: \"'a :: {linordered_field,floor_ceiling} \\<Rightarrow> 'a \\<Rightarrow> 'a\" where\n  \"sqrt_approx \\<epsilon> x \\<equiv> if \\<epsilon> > 0 then (if x = 0 then 0 else let xpos = abs x in sqrt_approx_main_impl \\<epsilon> xpos (xpos + 1)) else 0\"\n\n\nlemma sqrt_approx: assumes \\<epsilon>: \"\\<epsilon> > 0\"\n  shows \"\\<bar>sqrt_approx \\<epsilon> x * sqrt_approx \\<epsilon> x - \\<bar>x\\<bar>\\<bar> < \\<epsilon>\"\nproof (cases \"x = 0\")\n  case True\n  with \\<epsilon> show ?thesis unfolding sqrt_approx_def by auto\nnext\n  case False\n  let ?x = \"\\<bar>x\\<bar>\" \n  let ?sqrti = \"sqrt_approx_main_impl \\<epsilon> ?x (?x + 1)\"\n  let ?sqrt = \"sqrt_approximation.sqrt_approx_main \\<epsilon> ?x (?x + 1)\"\n  define sqrt where \"sqrt = ?sqrt\"\n  from False have x: \"?x > 0\" \"?x + 1 > 0\" by auto\n  interpret sqrt_approximation \\<epsilon> ?x\n    by (unfold_locales, insert x \\<epsilon>, auto)\n  from False \\<epsilon> have \"sqrt_approx \\<epsilon> x = ?sqrti\" unfolding sqrt_approx_def by (simp add: Let_def)\n  also have \"?sqrti = ?sqrt\"\n    by (rule sqrt_approx_main_impl, auto)\n  finally have id: \"sqrt_approx \\<epsilon> x = sqrt\" unfolding sqrt_def .\n  have sqrt: \"sqrt * sqrt > ?x \\<and> sqrt * sqrt - ?x < \\<epsilon>\" unfolding sqrt_def\n    by (rule sqrt_approx_main_sound[OF x(2)], insert x mult_pos_pos[OF x(1) x(1)], auto simp: field_simps)\n  show ?thesis unfolding id using sqrt by auto\nqed\n\nsubsection \\<open>Some tests\\<close>\n\ntext \\<open>Testing executabity and show that sqrt 2 is irrational\\<close>\nlemma \"\\<not> (\\<exists> i :: rat. i * i = 2)\"\nproof -\n  have \"set (sqrt_rat 2) = {}\" by eval\n  thus ?thesis by simp\nqed\n\ntext \\<open>Testing speed\\<close>\nlemma \"\\<not> (\\<exists> i :: int. i * i = 1234567890123456789012345678901234567890)\"\nproof -\n  have \"set (sqrt_int 1234567890123456789012345678901234567890) = {}\" by eval\n  thus ?thesis by simp\nqed\n\ntext \\<open>The following test\\<close>\n\nvalue \"let \\<epsilon> = 1 / 100000000 :: rat; s = sqrt_approx \\<epsilon> 2 in (s, s * s - 2, \\<bar>s * s - 2\\<bar> < \\<epsilon>)\"\n\ntext \\<open>results in (1.4142135623731116, 4.738200762148612e-14, True).\\<close>\n \nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Sqrt_Babylonian/Sqrt_Babylonian.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8615381987656672, "lm_q2_score": 0.8705972768020108, "lm_q1q2_score": 0.7500528097062994}}
{"text": " (*\n    File:      Group_Adjoin.thy\n    Author:    Manuel Eberl, TU München\n*)\nsection \\<open>Adjoining Elements to a Finite Abelian Group\\<close>\ntheory Group_Adjoin\nimports \n  Complex_Main\n  \"HOL-Algebra.Multiplicative_Group\"\nbegin\n\ntext \\<open>\n  This theory provides the notion of adjoining a single element to a subgroup of a finite\n  abelian group, and, in particular, an induction principle based upon this: We can show that\n  some property holds for a group by showing that it holds for some fixed subgroup and that\n  it is preserved when adjoining a single element.\n\n  The general idea for this was taken from Apostol's \n  ``Analytic Number Theory''~\\cite{apostol1976analytic}.\n\\<close>\n\nsubsection \\<open>Miscellaneous Group Theory\\<close>\n\nlemma (in group) ord_min:\n  assumes \"m \\<ge> 1\" \"x \\<in> carrier G\" \"x [^] m = \\<one>\"\n  shows   \"ord x \\<le> m\"\n  using assms pow_eq_id by auto\n\nlemma (in group) bij_betw_mult_left [intro]:\n  assumes [simp]: \"x \\<in> carrier G\"\n  shows \"bij_betw (\\<lambda>y. x \\<otimes> y) (carrier G) (carrier G)\"\n  by (intro bij_betwI[where ?g = \"\\<lambda>y. inv x \\<otimes> y\"])\n     (auto simp: m_assoc [symmetric])\n\nlocale finite_comm_group = comm_group +\n  assumes fin [intro]: \"finite (carrier G)\"\nbegin\n\nlemma order_gt_0 [simp,intro]: \"order G > 0\"\n  by (subst order_gt_0_iff_finite) auto\n\nlemma subgroup_imp_finite_comm_group:\n  assumes \"subgroup H G\"\n  shows   \"finite_comm_group (G\\<lparr>carrier := H\\<rparr>)\"\nproof -\n  interpret G': group \"G\\<lparr>carrier := H\\<rparr>\" by (intro subgroup_imp_group) fact+\n  interpret H: subgroup H G by fact\n  show ?thesis by standard (insert finite_subset[OF H.subset fin], auto simp: m_comm)\nqed\n\nend\n\n\nsubsection \\<open>Subgroup indicators and adjoining elements\\<close>\n\ndefinition subgroup_indicator :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> nat\" where\n  \"subgroup_indicator G H a = (LEAST k. k > 0 \\<and> a [^]\\<^bsub>G\\<^esub> k \\<in> H)\"\n\ndefinition adjoin :: \"('a, 'b) monoid_scheme \\<Rightarrow> 'a set \\<Rightarrow> 'a \\<Rightarrow> 'a set\" where\n  \"adjoin G H a = {x \\<otimes>\\<^bsub>G\\<^esub> a [^]\\<^bsub>G\\<^esub> k |x k. x \\<in> H \\<and> k < subgroup_indicator G H a}\"\n\nlemma (in subgroup) nat_pow_closed [simp,intro]: \"a \\<in> H \\<Longrightarrow> pow G a (n::nat) \\<in> H\"\n  by (induction n) (auto simp: nat_pow_def)\n\nlemma nat_pow_modify_carrier: \"a [^]\\<^bsub>G\\<lparr>carrier := H\\<rparr>\\<^esub> b = a [^]\\<^bsub>G\\<^esub> (b::nat)\"\n  by (simp add: nat_pow_def)\n\nlemma subgroup_indicator_modify_carrier [simp]:\n  \"subgroup_indicator (G\\<lparr>carrier := H'\\<rparr>) H a = subgroup_indicator G H a\"\n  by (auto simp: subgroup_indicator_def nat_pow_def)\n\nlemma adjoin_modify_carrier [simp]:\n  \"adjoin (G\\<lparr>carrier := H'\\<rparr>) H a = adjoin G H a\"\n  by (simp_all add: adjoin_def nat_pow_def)\n\ncontext group\nbegin\n\nlemma subgroup_indicator_eq_1:\n  assumes \"a \\<in> H\" \"a \\<in> carrier G\"\n  shows   \"subgroup_indicator G H a = 1\"\nproof -\n  from assms show ?thesis\n    unfolding subgroup_indicator_def\n    by (intro Least_equality) (auto simp: nat_pow_def)\nqed\n\nlemma subgroup_indicator_le:\n  assumes \"a [^] n \\<in> H\" \"n > 0\"  \"a \\<in> carrier G\"\n  shows   \"subgroup_indicator G H a \\<le> n\"\n  using assms unfolding subgroup_indicator_def by (intro Least_le) auto\n\nend\n\ncontext finite_comm_group\nbegin\n\nlemma ord_pos: \n  assumes \"x \\<in> carrier G\"\n  shows   \"ord x > 0\"\n  using ord_ge_1[of x] assms fin by auto\n\nlemma \n  assumes \"subgroup H G\" and a: \"a \\<in> carrier G\"\n  shows subgroup_indicator_pos: \"subgroup_indicator G H a > 0\" (is \"?h > 0\")\n  and   pow_subgroup_indicator: \"a [^] subgroup_indicator G H a \\<in> H\"\nproof -\n  interpret subgroup H G by fact\n  from a have \"\\<exists>h>0. a [^] (h::nat) \\<in> H\"\n    by (intro exI[of _ \"ord a\"]) (auto simp: ord_pos pow_ord_eq_1 fin)\n  hence \"?h > 0 \\<and> a [^] ?h \\<in> H\" unfolding subgroup_indicator_def\n    by (rule LeastI_ex)\n  thus \"?h > 0\" and \"a [^] ?h \\<in> H\" by auto\nqed\n\nlemma subgroup_indicator_le_ord:\n  assumes \"a \\<in> carrier G\" \"subgroup H G\"\n  shows   \"subgroup_indicator G H a \\<le> ord a\"\nproof -\n  interpret subgroup H G by fact\n  from assms show ?thesis by (intro subgroup_indicator_le) (auto simp: pow_ord_eq_1 fin ord_pos)\nqed\n\nlemma subgroup_indicator_trivial: \n  assumes \"a \\<in> carrier G\"\n  shows   \"subgroup_indicator G {\\<one>} a = group.ord G a\"\nproof -\n  have sg[simp]: \"subgroup {\\<one>} G\" by standard auto\n  from pow_subgroup_indicator[OF sg assms] and assms show ?thesis\n    by (intro antisym subgroup_indicator_le_ord ord_min)\n       (auto simp: Suc_le_eq subgroup_indicator_pos)\nqed\n\nlemma mem_adjoin:\n  assumes \"subgroup H G\" \"x \\<in> H\" \"a \\<in> carrier G\"\n  shows   \"x \\<in> adjoin G H a\"\nproof -\n  interpret subgroup H G by fact\n  from assms show ?thesis\n    by (auto simp: adjoin_def intro!: exI[of _ x] exI[of _ 0] subgroup_indicator_pos)\nqed\n\nlemma adjoin_subgroup:\n  assumes \"subgroup H G\" and a: \"a \\<in> carrier G\"\n  shows   \"subgroup (adjoin G H a) G\"\nproof (standard, goal_cases)\n  case 1\n  interpret subgroup H G by fact\n  from a show ?case by (auto simp: adjoin_def)\nnext\n  case (2 x y)\n  interpret subgroup H G by fact\n  define h where \"h = subgroup_indicator G H a\"\n  from assms have [simp]: \"h > 0\" \n    unfolding h_def by (intro subgroup_indicator_pos) auto\n  from 2(1) obtain x' :: 'a and k :: nat where [simp]: \"x' \\<in> H\" \"x = x' \\<otimes> a [^] k\"\n    by (auto simp: adjoin_def)\n  from 2(2) obtain y' :: 'a and l :: nat where [simp]: \"y' \\<in> H\" \"y = y' \\<otimes> a [^] l\"\n    by (auto simp: adjoin_def)\n  define a' where \"a' = (a [^] h) [^] ((k + l) div h)\"\n  have [simp]: \"a' \\<in> H\" unfolding a'_def\n    by (rule nat_pow_closed) (insert assms, auto simp: h_def intro!: pow_subgroup_indicator)\n  from a have \"x \\<otimes> y = (x' \\<otimes> y') \\<otimes> a [^] (k + l)\"\n    by (simp add: nat_pow_mult [symmetric] m_ac)\n  also have \"k + l = h * ((k + l) div h) + (k + l) mod h\"\n    by (rule mult_div_mod_eq [symmetric])\n  also from a fin have \"a [^] \\<dots> = a' \\<otimes> a [^] ((k + l) mod h)\"\n    by (subst nat_pow_mult [symmetric]) \n       (simp_all add: nat_pow_pow [symmetric] pow_ord_eq_1 a'_def [symmetric])\n  finally have \"x \\<otimes> y = x' \\<otimes> y' \\<otimes> a' \\<otimes> a [^] ((k + l) mod h)\" \n    using a by (simp add: m_ac)\n  moreover from a have \"(k + l) mod h < h\"\n    by (intro mod_less_divisor) (auto simp: ord_pos)\n  ultimately show ?case\n    by (auto simp: adjoin_def h_def intro!: exI[of _ \"x' \\<otimes> y' \\<otimes> a'\"] exI[of _ \"(k + l) mod h\"])\nnext\n  case 3\n  interpret subgroup H G by fact\n  from assms show ?case\n    by (auto simp: adjoin_def intro!: exI[of _ \\<one>] exI[of _ 0] subgroup_indicator_pos)\nnext\n  case (4 x)\n  interpret H: subgroup H G by fact\n  define h where \"h = subgroup_indicator G H a\"\n  define a' where \"a' = a [^] h\"\n  from assms have [simp]: \"a' \\<in> H\" unfolding a'_def h_def\n    by (intro pow_subgroup_indicator) auto\n  from 4 obtain x' and k :: nat where [simp]: \"x' \\<in> H\" \"x = x' \\<otimes> a [^] k\" and \"k < h\"\n    by (auto simp: adjoin_def h_def)\n  show ?case\n  proof (cases \"k = 0\")\n    case True\n    with assms show ?thesis\n      by (auto simp: mem_adjoin)\n  next\n    case False\n    from a have \"inv x = inv x' \\<otimes> inv (a [^] k)\"\n      by (simp add: inv_mult)\n    also have \"\\<dots> = inv x' \\<otimes> (inv a' \\<otimes> a') \\<otimes> inv (a [^] k)\" by simp\n    also have \"\\<dots> = inv x' \\<otimes> inv a' \\<otimes> (a' \\<otimes> inv (a [^] k))\"\n      by (simp only: \\<open>a' \\<in> H\\<close> \\<open>x' \\<in> H\\<close> inv_closed m_closed H.mem_carrier m_ac nat_pow_closed a)\n    also from a have \"a' \\<otimes> inv (a [^] k) = a [^] (int h - int k)\"\n      by (subst int_pow_diff) (auto simp: a'_def int_pow_int)\n    also from \\<open>k < h\\<close> have \"int h - int k = int (h - k)\"\n      by simp\n    also have \"a [^] \\<dots> = a [^] (h - k)\" \n      by (simp add: int_pow_int)\n    finally have \"inv x = inv x' \\<otimes> inv a' \\<otimes> a [^] (h - k)\" .\n    moreover have \"h - k < h\" using \\<open>k < h\\<close> and False by simp\n    ultimately show ?thesis\n      by (auto simp: adjoin_def h_def intro!: exI[of _ \"inv x' \\<otimes> inv a'\"] exI[of _ \"h - k\"])\n  qed\nqed\n\nlemma adjoin_id:\n  assumes \"subgroup H G\" and a: \"a \\<in> H\"\n  shows   \"adjoin G H a = H\"\nproof -\n  interpret subgroup H G by fact\n  show ?thesis\n  proof safe\n    fix x assume \"x \\<in> H\"\n    with assms show \"x \\<in> adjoin G H a\"\n      by (auto simp: adjoin_def intro!: exI[of _ x] exI[of _ 0] subgroup_indicator_pos)\n  qed (insert a, auto simp: adjoin_def)\nqed\n\nlemma adjoined_in_adjoin:\n  assumes \"subgroup H G\" and a: \"a \\<in> carrier G\"\n  shows   \"a \\<in> adjoin G H a\"\nproof (cases \"a \\<in> H\")\n  case True\n  with assms show ?thesis by (subst adjoin_id) auto\nnext\n  case False\n  interpret subgroup H G by fact\n  from assms have \"subgroup_indicator G H a > 0\" \n    by (intro subgroup_indicator_pos) auto\n  moreover from False and assms and pow_subgroup_indicator[OF assms] \n    have \"subgroup_indicator G H a \\<noteq> 1\" by (intro notI) auto\n  ultimately have \"subgroup_indicator G H a > 1\" by simp\n  with assms show ?thesis\n    by (auto simp: adjoin_def intro!: exI[of _ \\<one>] exI[of _ 1])\nqed\n\nlemma adjoin_subset:\n  assumes \"subgroup H G\" and a: \"a \\<in> carrier G\"\n  shows   \"adjoin G H a \\<subseteq> carrier G\"\nproof -\n  interpret subgroup H G by fact\n  from a show ?thesis by (auto simp: adjoin_def)\nqed\n\nlemma inj_on_adjoin:\n  assumes \"subgroup H G\" and a: \"a \\<in> carrier G\" \"a \\<notin> H\"\n  defines \"h \\<equiv> subgroup_indicator G H a\"\n  shows   \"inj_on (\\<lambda>(x, k). x \\<otimes> a [^] k) (H \\<times> {..<h})\"\nproof (intro inj_onI, clarify, goal_cases)\n  case (1 x k y l)\n  interpret H: subgroup H G by fact\n  have wf: \"x \\<in> carrier G\" \"y \\<in> carrier G\" \"a [^] k \\<in> carrier G\" \"a [^] l \\<in> carrier G\"\n    using 1 a by auto\n  have \"x \\<otimes> inv y = (x \\<otimes> inv y) \\<otimes> (a [^] k \\<otimes> inv (a [^] k))\"\n    by (simp add: wf)\n  also have \"\\<dots> = x \\<otimes> a [^] k \\<otimes> inv y \\<otimes> inv (a [^] k)\"\n    by (simp only: m_ac wf inv_closed m_closed)\n  also from a have \"\\<dots> = y \\<otimes> a [^] l \\<otimes> inv y \\<otimes> inv (a [^] k)\"\n    by (subst 1) (simp_all)\n  also have \"\\<dots> = y \\<otimes> inv y \\<otimes> (a [^] l \\<otimes> inv (a [^] k))\"\n    by (simp only: m_ac wf inv_closed m_closed)\n  also from wf have \"\\<dots> = a [^] int l \\<otimes> inv (a [^] int k)\"\n    by (simp add: int_pow_int)\n  also have \"\\<dots> = a [^] (int l - int k)\"\n    by (rule int_pow_diff [symmetric]) fact+\n  finally have *: \"x \\<otimes> inv y = a [^] (int l - int k)\" .\n\n  have **: \"a [^] (nat \\<bar>int l - int k\\<bar>) \\<in> H\"\n  proof (cases \"k \\<le> l\")\n    case True\n    from 1 have \"a [^] (int l - int k) \\<in> H\" by (subst * [symmetric]) auto\n    also have \"a [^] (int l - int k) = a [^] (nat \\<bar>int l - int k\\<bar>)\"\n      using True by (simp add: nat_diff_distrib int_pow_int [symmetric] of_nat_diff)\n    finally show ?thesis .\n  next\n    case False\n    from 1 have \"inv (a [^] (int l - int k)) \\<in> H\" by (subst * [symmetric]) auto\n    also have \"inv (a [^] (int l - int k)) = a [^] (nat \\<bar>int l - int k\\<bar>)\" using False a \n      by (simp add: int_pow_neg [symmetric] nat_diff_distrib int_pow_int [symmetric] of_nat_diff)\n    finally show ?thesis .\n  qed\n  have \"k = l\"\n  proof (rule ccontr)\n    assume \"k \\<noteq> l\"\n    with a and ** have \"h \\<le> nat \\<bar>int l - int k\\<bar>\" unfolding h_def\n      by (intro subgroup_indicator_le) auto\n    also have \"\\<dots> < h\" using \\<open>l < h\\<close> and \\<open>k < h\\<close> by linarith\n    finally show False ..\n  qed\n  with 1 and a show ?case by simp\nqed\n\nlemma card_adjoin:\n  assumes \"subgroup H G\" and a: \"a \\<in> carrier G\" \"a \\<notin> H\"\n  shows   \"card (adjoin G H a) = card H * subgroup_indicator G H a\"\nproof -\n  interpret H: subgroup H G by fact\n  define h where \"h = subgroup_indicator G H a\"\n  have \"adjoin G H a = (\\<lambda>(x,k). x \\<otimes> a [^] k) ` (H \\<times> {..<h})\"\n    by (auto simp: adjoin_def h_def)\n  also have \"card \\<dots> = card (H \\<times> {..<h})\" unfolding h_def\n    by (intro card_image inj_on_adjoin assms)\n  finally show ?thesis by (simp add: h_def card_cartesian_product)\nqed\n\nend\n\nlocale finite_comm_group_adjoin = finite_comm_group + subgroup H\n  for H +\n  fixes a :: 'a\n  assumes a_in_carrier [simp]: \"a \\<in> carrier G\"\n  assumes a_notin_subgroup: \"a \\<notin> H\"\nbegin\n\ndefinition unadjoin :: \"'a \\<Rightarrow> 'a \\<times> nat\"  where\n  \"unadjoin x = \n     (THE z. z \\<in> H \\<times> {..<subgroup_indicator G H a} \\<and> x = fst z \\<otimes>\\<^bsub>G\\<^esub> a [^]\\<^bsub>G\\<^esub> snd z)\"\n\nlemma adjoin_unique:\n  assumes \"x \\<in> adjoin G H a\"\n  defines \"h \\<equiv> subgroup_indicator G H a\"\n  shows   \"\\<exists>!z. z \\<in> H \\<times> {..<subgroup_indicator G H a} \\<and> x = fst z \\<otimes>\\<^bsub>G\\<^esub> a [^]\\<^bsub>G\\<^esub> snd z\"\nproof (rule ex_ex1I, goal_cases)\n  case 1\n  from assms show ?case by (auto simp: adjoin_def)\nnext\n  case (2 z1 z2)\n  have \"subgroup H G\" ..\n  from inj_on_adjoin[OF this a_in_carrier a_notin_subgroup]\n  show ?case by (rule inj_onD) (use 2 in auto)\nqed\n\nlemma unadjoin_correct:\n  assumes \"x \\<in> adjoin G H a\"\n  shows   \"fst (unadjoin x) \\<in> H\" and \"snd (unadjoin x) < subgroup_indicator G H a\"\n          \"fst (unadjoin x) \\<otimes> a [^] snd (unadjoin x) = x\"\n  using theI'[OF adjoin_unique[OF assms], folded unadjoin_def] by auto\n\nlemma unadjoin_unique:\n  assumes \"y \\<in> H\" \"h < subgroup_indicator G H a\"\n  shows   \"unadjoin (y \\<otimes> a [^] h) = (y, h)\"\nproof -\n  from assms have \"y \\<otimes> a [^] h \\<in> adjoin G H a\" by (auto simp: adjoin_def)\n  note * = theI'[OF adjoin_unique[OF this], folded unadjoin_def]\n  from inj_on_adjoin[OF is_subgroup a_in_carrier a_notin_subgroup] show ?thesis\n    by (rule inj_onD) (insert * assms, auto)\nqed\n\nlemma unadjoin_unique':\n  assumes \"y \\<in> H\" \"h < subgroup_indicator G H a\" \"x = y \\<otimes> a [^] h\"\n  shows   \"unadjoin x = (y, h)\"\n  using unadjoin_unique[OF assms(1,2)] assms(3) by simp\n\nlemma unadjoin_1 [simp]: \"unadjoin \\<one> = (\\<one>, 0)\"\n  by (intro unadjoin_unique') (auto intro!: subgroup_indicator_pos is_subgroup)\n\nlemma unadjoin_in_base [simp]: \"x \\<in> H \\<Longrightarrow> unadjoin x = (x, 0)\"\n  by (intro unadjoin_unique') (auto intro!: subgroup_indicator_pos is_subgroup)\n\nlemma unadjoin_adjoined [simp]: \"unadjoin a = (\\<one>, 1)\"\nproof (rule unadjoin_unique')\n  have \"subgroup_indicator G H a \\<noteq> 1\" using is_subgroup a_notin_subgroup\n    using pow_subgroup_indicator[of H a] by auto\n  with subgroup_indicator_pos [OF is_subgroup a_in_carrier] \n    show \"subgroup_indicator G H a > 1\" by simp\nqed auto\n\nend\n\n\nsubsection \\<open>Induction by adjoining elements\\<close>\n\ncontext finite_comm_group\nbegin\n\nlemma group_decompose_adjoin_aux:\n  assumes \"subgroup H G\"\n  shows   \"H = carrier G \\<or> \n           (\\<exists>H' a. H \\<subseteq> H' \\<and> subgroup H' G \\<and> a \\<in> carrier G - H' \\<and> carrier G = adjoin G H' a)\"\nproof -\n  have ind: \"(\\<And>H. subgroup H G \\<Longrightarrow> H \\<noteq> carrier G \\<Longrightarrow> P (adjoin G H (SOME a. a \\<in> carrier G - H))\n                \\<Longrightarrow> P H) \\<Longrightarrow> (\\<And>H. subgroup H G \\<Longrightarrow> H = carrier G \\<Longrightarrow> P H) \\<Longrightarrow>\n                (\\<And>H. \\<not> subgroup H G \\<Longrightarrow> P H) \\<Longrightarrow> P a0\" for P a0\n  proof (induction_schema, force, rule wf_bounded_set)\n    fix H assume H: \"subgroup H G\" \"H \\<noteq> carrier G\"\n    interpret subgroup H G by fact\n    from H have H': \"H \\<subset> carrier G\" by auto\n    define a where \"a = (SOME a. a \\<in> carrier G - H)\"\n    have a: \"a \\<in> carrier G - H\" unfolding a_def\n      by (rule someI_ex) (insert H', auto)  \n    from a and H have \"adjoin G H a \\<subseteq> carrier G\" by (intro adjoin_subset) auto\n    from a and H have \"a \\<in> adjoin G H a\" \"a \\<notin> H\"\n      by (auto simp: adjoined_in_adjoin)\n    hence \"adjoin G H a \\<noteq> H\" by blast\n    with H and a show \"(adjoin G H a, H) \\<in> {(B,A). A \\<subset> B \\<and> B \\<subseteq> carrier G}\"\n      using adjoin_subset[of H a] by (auto intro: mem_adjoin)\n  next\n    fix A B assume \"(B, A) \\<in> {(B, A). A \\<subset> B \\<and> B \\<subseteq> carrier G}\"\n    thus \"finite (carrier G) \\<and> carrier G \\<subseteq> carrier G \\<and> B \\<subseteq> carrier G \\<and> A \\<subset> B\"\n      by auto\n  qed\n\n  from assms show ?thesis\n  proof (induction H rule: ind)\n    case (1 H)\n    interpret subgroup H G by fact\n    define a where \"a = (SOME a. a \\<in> carrier G - H)\"\n    from \"1.hyps\" have \"\\<exists>a. a \\<in> carrier G - H\" by auto\n    hence a: \"a \\<in> carrier G - H\" unfolding a_def by (rule someI_ex)\n  \n    from \"1.hyps\" and a have \"subgroup (adjoin G H a) G\"\n      by (intro adjoin_subgroup) auto\n    from \"1.IH\"[folded a_def, OF this] \n      have \"(\\<exists>H' a. H \\<subseteq> H' \\<and> subgroup H' G \\<and> a \\<in> carrier G - H' \\<and> carrier G = adjoin G H' a)\"\n    proof (elim disjE, goal_cases)\n      case 1\n      with a and \\<open>subgroup H G\\<close> show ?case\n        by (intro exI[of _ H] exI[of _ a]) simp_all\n    next\n      case 2\n      then obtain H' a' where *: \"adjoin G H a \\<subseteq> H'\" \"subgroup H' G\" \n                                 \"a' \\<in> carrier G - H'\" \"carrier G = adjoin G H' a'\" by blast\n      thus ?case using mem_adjoin[OF \\<open>subgroup H G\\<close>, of _ a] a\n        by (intro exI[of _ H'] exI[of _ a']) auto\n    qed\n    thus ?case by blast\n  qed auto\nqed\n\nlemma group_decompose_adjoin:\n  assumes \"subgroup H0 G\" \"H0 \\<noteq> carrier G\"\n  obtains H a where \"H0 \\<subseteq> H\" \"subgroup H G\" \"a \\<in> carrier G - H\" \"carrier G = adjoin G H a\"\nproof -\n  from group_decompose_adjoin_aux[OF assms(1)] and assms(2) and that show ?thesis by blast\nqed\n\nlemma subgroup_adjoin_induct [consumes 1, case_names base adjoin]:\n  assumes \"subgroup H0 G\"\n  assumes base: \"P (G\\<lparr>carrier := H0\\<rparr>)\"\n  assumes adjoin: \"\\<And>H a. subgroup H G \\<Longrightarrow> H0 \\<subseteq> H \\<Longrightarrow> a \\<in> carrier G - H \\<Longrightarrow> P (G\\<lparr>carrier := H\\<rparr>) \\<Longrightarrow> \n                           P (G\\<lparr>carrier := adjoin G H a\\<rparr>)\"\n  shows   \"P G\"\nproof -\n  define H where \"H = carrier G\"\n  have \"finite H\" by (auto simp: H_def fin)\n  moreover have \"subgroup H G\" unfolding H_def by standard auto\n  moreover {\n    interpret subgroup H0 G by fact\n    have \"H0 \\<subseteq> H\" by (simp add: H_def subset)\n  }\n  ultimately have \"P (G\\<lparr>carrier := H\\<rparr>)\"\n  proof (induction H rule: finite_psubset_induct)\n    case (psubset H)\n    show ?case\n    proof (cases \"H = H0\")\n      case True\n      thus ?thesis by (simp add: base)\n    next\n      case False\n      interpret H_sg: subgroup H G by fact\n      interpret H: finite_comm_group \"G\\<lparr>carrier := H\\<rparr>\"\n        by (rule subgroup_imp_finite_comm_group) fact\n      have sg: \"subgroup H0 (G\\<lparr>carrier := H\\<rparr>)\"\n        by (simp add: H_sg.subgroup_axioms \\<open>subgroup H0 G\\<close> psubset.prems(2) subgroup_incl)\n      from H.group_decompose_adjoin[OF sg] and False\n        obtain H' a where H': \"H0 \\<subseteq> H'\" \"subgroup H' (G\\<lparr>carrier := H\\<rparr>)\" \"a \\<in> H - H'\" \n                              \"H = adjoin G H' a\" by (auto simp: order_def)\n      have \"subgroup H' G\"\n        using \\<open>subgroup H G\\<close> and H'(2) group.incl_subgroup by blast\n      from H' and adjoined_in_adjoin[of H' a] and \\<open>subgroup H' G\\<close> and mem_adjoin[of H' _ a]\n        have \"a \\<in> H\" and \"a \\<notin> H'\" and \"H' \\<subseteq> H\" by auto\n      hence \"H' \\<subset> H\" by blast\n      from psubset.IH [OF \\<open>H' \\<subset> H\\<close> \\<open>subgroup H' G\\<close> \\<open>H0 \\<subseteq> H'\\<close>] have \"P (G\\<lparr>carrier := H'\\<rparr>)\" .\n      with H' and \\<open>subgroup H' G\\<close> have \"P (G\\<lparr>carrier := adjoin G H' a\\<rparr>)\"\n        by (intro adjoin) auto\n      also from H' have \"adjoin G H' a = H\" by simp\n      finally show ?thesis .\n    qed\n  qed\n  thus \"P G\" by (simp add: H_def)\nqed\n\nlemma subgroup_adjoin_induct' [case_names singleton adjoin]:\n  assumes singleton: \"P (G\\<lparr>carrier := {\\<one>}\\<rparr>)\"\n  assumes adjoin: \"\\<And>H a. subgroup H G \\<Longrightarrow> a \\<in> carrier G - H \\<Longrightarrow> P (G\\<lparr>carrier := H\\<rparr>) \\<Longrightarrow> \n                           P (G\\<lparr>carrier := adjoin G H a\\<rparr>)\"\n  shows   \"P G\"\nproof -\n  have \"subgroup {\\<one>} G\" by standard auto\n  from this and assms show ?thesis by (rule subgroup_adjoin_induct)\nqed\n\nend\n\nend", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Dirichlet_L/Group_Adjoin.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.86153820232079, "lm_q2_score": 0.8705972616934408, "lm_q1q2_score": 0.7500527997847694}}
{"text": "theory Chapter3\nimports \"~~/src/HOL/IMP/BExp\"\n        \"~~/src/HOL/IMP/ASM\"\nbegin\n\ntext{*\n\\section*{Chapter 3}\n\n\\exercise\nTo show that @{const asimp_const} really folds all subexpressions of the form\n@{term \"Plus (N i) (N j)\"}, define a function\n*}\n\nfun optimal :: \"aexp \\<Rightarrow> bool\" where\n\"optimal (N i) = True\" | \n\"optimal (V v) = True\" | \n\"optimal (Plus (N i) (N j)) = False\" |\n\"optimal (Plus a1 a2) = ((optimal a1) \\<or> (optimal a2))\"\n  \nvalue \"optimal (N 0)\"\nvalue \"optimal (Plus (N 0) (N 1))\"\n\ntext{*\nthat checks that its argument does not contain a subexpression of the form\n@{term \"Plus (N i) (N j)\"}. Then prove that the result of @{const asimp_const}\nis optimal:\n*}\n\nlemma \"optimal (asimp_const a)\"\napply(induction a rule: optimal.induct)\napply(auto split: aexp.split)\ndone\n\ntext{*\nThis proof needs the same @{text \"split:\"} directive as the correctness proof of\n@{const asimp_const}. This increases the chance of nontermination\nof the simplifier. Therefore @{const optimal} should be defined purely by\npattern matching on the left-hand side,\nwithout @{text case} expressions on the right-hand side.\n\\endexercise\n\n\n\\exercise\nIn this exercise we verify constant folding for @{typ aexp}\nwhere we sum up all constants, even if they are not next to each other.\nFor example, @{term \"Plus (N 1) (Plus (V x) (N 2))\"} becomes\n@{term \"Plus (V x) (N 3)\"}. This goes beyond @{const asimp}.\nBelow we follow a particular solution strategy but there are many others.\n\nFirst, define a function @{text sumN} that returns the sum of all\nconstants in an expression and a function @{text zeroN} that replaces all\nconstants in an expression by zeroes (they will be optimized away later):\n*}\n\nfun sumN :: \"aexp \\<Rightarrow> int\" where\n\"sumN (N n) = n\" |\n\"sumN (V x) = 0\" |\n\"sumN (Plus a1 a2) = sumN a1 + sumN a2\"\n\nvalue \"sumN (Plus (N 1) (Plus (V x) (N 2)))\"\n\nfun zeroN :: \"aexp \\<Rightarrow> aexp\" where\n\"zeroN (N n) = (N 0)\" |\n\"zeroN (V x) = (V x)\" |\n\"zeroN (Plus a1 a2) = (Plus (zeroN a1) (zeroN a2))\"\n\ntext {*\nNext, define a function @{text sepN} that produces an arithmetic expression\nthat adds the results of @{const sumN} and @{const zeroN}. Prove that\n@{text sepN} preserves the value of an expression.\n*}\n\ndefinition sepN :: \"aexp \\<Rightarrow> aexp\" where\n\"sepN a = (Plus (N (sumN a)) (zeroN a))\"\n\nlemma aval_sepN: \"aval (sepN t) s = aval t s\"\napply(induction t)\napply(auto simp add: sepN_def)  \ndone\n\ntext {*\nFinally, define a function @{text full_asimp} that uses @{const asimp}\nto eliminate the zeroes left over by @{const sepN}.\nProve that it preserves the value of an arithmetic expression.\n*}\n\ndefinition full_asimp :: \"aexp \\<Rightarrow> aexp\" where\n\"full_asimp a = asimp (sepN a)\"\n  \nlemma aval_full_asimp: \"aval (full_asimp t) s = aval t s\"\napply(induction t)\napply(auto simp add:full_asimp_def aval_sepN)     \ndone\n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:subst}\nSubstitution is the process of replacing a variable\nby an expression in an expression. Define a substitution function\n*}\n\nfun subst :: \"vname \\<Rightarrow> aexp \\<Rightarrow> aexp \\<Rightarrow> aexp\" where\n\"subst x a (N n) = N n\" |\n\"subst x a (V y) = (if x = y then a else V y)\" |\n\"subst x a (Plus a1 a2) = Plus (subst x a a1) (subst x a a2)\"\n\nvalue \"subst ''x'' (N 3) (Plus (V ''x'' ) (V ''y''))\"\n\ntext{*\nsuch that @{term \"subst x a e\"} is the result of replacing\nevery occurrence of variable @{text x} by @{text a} in @{text e}.\nFor example:\n@{lemma[display] \"subst ''x'' (N 3) (Plus (V ''x'') (V ''y'')) = Plus (N 3) (V ''y'')\" by simp}\n\nProve the so-called \\concept{substitution lemma} that says that we can either\nsubstitute first and evaluate afterwards or evaluate with an updated state:\n*}\n\nlemma subst_lemma: \"aval (subst x a e) s = aval e (s(x := aval a s))\"\napply(induction e)\napply(auto)\ndone\n\ntext {*\nAs a consequence prove that we can substitute equal expressions by equal expressions\nand obtain the same result under evaluation:\n*}\nlemma \"aval a1 s = aval a2 s\n  \\<Longrightarrow> aval (subst x a1 e) s = aval (subst x a2 e) s\"\napply(induction a1)\napply(auto simp add: subst_lemma)\ndone\n\ntext{*\n\\endexercise\n\n\\exercise\nTake a copy of theory @{theory AExp} and modify it as follows.\nExtend type @{typ aexp} with a binary constructor @{text Times} that\nrepresents multiplication. Modify the definition of the functions @{const aval}\nand @{const asimp} accordingly. You can remove @{const asimp_const}.\nFunction @{const asimp} should eliminate 0 and 1 from multiplications\nas well as evaluate constant subterms. Update all proofs concerned.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nDefine a datatype @{text aexp2} of extended arithmetic expressions that has,\nin addition to the constructors of @{typ aexp}, a constructor for\nmodelling a C-like post-increment operation $x{++}$, where $x$ must be a\nvariable. Define an evaluation function @{text \"aval2 :: aexp2 \\<Rightarrow> state \\<Rightarrow> val \\<times> state\"}\nthat returns both the value of the expression and the new state.\nThe latter is required because post-increment changes the state.\n\nExtend @{text aexp2} and @{text aval2} with a division operation. Model partiality of\ndivision by changing the return type of @{text aval2} to\n@{typ \"(val \\<times> state) option\"}. In case of division by 0 let @{text aval2}\nreturn @{const None}. Division on @{typ int} is the infix @{text div}.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\nThe following type adds a @{text LET} construct to arithmetic expressions:\n*}\n\ndatatype lexp = Nl int | Vl vname | Plusl lexp lexp | LET vname lexp lexp\n\ntext{* The @{const LET} constructor introduces a local variable:\nthe value of @{term \"LET x e\\<^sub>1 e\\<^sub>2\"} is the value of @{text e\\<^sub>2}\nin the state where @{text x} is bound to the value of @{text e\\<^sub>1} in the original state.\nDefine a function @{const lval} @{text\"::\"} @{typ \"lexp \\<Rightarrow> state \\<Rightarrow> int\"}\nthat evaluates @{typ lexp} expressions. Remember @{term\"s(x := i)\"}.\n\nDefine a conversion @{const inline} @{text\"::\"} @{typ \"lexp \\<Rightarrow> aexp\"}.\nThe expression \\mbox{@{term \"LET x e\\<^sub>1 e\\<^sub>2\"}} is inlined by substituting\nthe converted form of @{text e\\<^sub>1} for @{text x} in the converted form of @{text e\\<^sub>2}.\nSee Exercise~\\ref{exe:subst} for more on substitution.\nProve that @{const inline} is correct w.r.t.\\ evaluation.\n\\endexercise\n\n\n\\exercise\nShow that equality and less-or-equal tests on @{text aexp} are definable\n*}\n\ndefinition Le :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Le a1 a2 = Not (Less a2 a1)\"\n\ndefinition Eq :: \"aexp \\<Rightarrow> aexp \\<Rightarrow> bexp\" where\n\"Eq a1 a2 = And (Le a1 a2) (Le a2 a1)\"\n\ntext{*\nand prove that they do what they are supposed to:\n*}\n\nlemma bval_Le: \"bval (Le a1 a2) s = (aval a1 s \\<le> aval a2 s)\"\napply(induction a1)\napply(auto simp add: Le_def)\ndone\n\nlemma bval_Eq: \"bval (Eq a1 a2) s = (aval a1 s = aval a2 s)\"\napply(induction a1)\napply(auto simp add: Eq_def Le_def)\ndone\n\ntext{*\n\\endexercise\n\n\\exercise\nConsider an alternative type of boolean expressions featuring a conditional: *}\n\ndatatype ifexp = Bc2 bool | If ifexp ifexp ifexp | Less2 aexp aexp\n\ntext {*  First define an evaluation function analogously to @{const bval}: *}\n\nfun ifval :: \"ifexp \\<Rightarrow> state \\<Rightarrow> bool\" where\n\"ifval (Bc2 v) s = v\" |\n\"ifval (If c b1 b2) s = (if (ifval c s) then (ifval b1 s) else (ifval b2 s))\" |\n\"ifval (Less2 a1 a2) s = ((aval a1 s) < (aval a2 s))\"\n\ntext{* Then define two translation functions *}\n\nvalue \"true\"  \nvalue \"True\"  \n  \nfun b2ifexp :: \"bexp \\<Rightarrow> ifexp\" where\n\"b2ifexp (Bc v) = (Bc2 v)\" |\n\"b2ifexp (Not b) = (If (b2ifexp b) (Bc2 False) (Bc2 True))\" |\n\"b2ifexp (And b1 b2) = (If (b2ifexp b1) (b2ifexp b2) (Bc2 False))\" |\n\"b2ifexp (Less a1 a2) = (Less2 a1 a2)\"\n\nfun if2bexp :: \"ifexp \\<Rightarrow> bexp\" where\n\"if2bexp (Bc2 v) = (Bc v)\" |\n\"if2bexp (If c b1 b2) = (Not (And (Not (And (if2bexp c) (if2bexp b1))) \n                                  (Not (And (Not (if2bexp c)) (if2bexp b2)))))\" |\n\"if2bexp (Less2 a1 a2) = (Less a1 a2)\"\n\ntext{* and prove their correctness: *}\n\nlemma \"bval (if2bexp exp) s = ifval exp s\"\napply(induction exp)\napply(auto)  \ndone\n\nlemma \"ifval (b2ifexp exp) s = bval exp s\"\napply(induction exp)\napply(auto)  \ndone\n\ntext{*\n\\endexercise\n\n\\exercise\nWe define a new type of purely boolean expressions without any arithmetic\n*}\n\ndatatype pbexp =\n  VAR vname | NOT pbexp | AND pbexp pbexp | OR pbexp pbexp\n\ntext{*\nwhere variables range over values of type @{typ bool},\nas can be seen from the evaluation function:\n*}\n\nfun pbval :: \"pbexp \\<Rightarrow> (vname \\<Rightarrow> bool) \\<Rightarrow> bool\" where\n\"pbval (VAR x) s = s x\"  |\n\"pbval (NOT b) s = (\\<not> (pbval b s))\" |\n\"pbval (AND b1 b2) s = ((pbval b1 s) \\<and> (pbval b2 s))\" |\n\"pbval (OR b1 b2) s = ((pbval b1 s) \\<or> (pbval b2 s))\" \n\ntext {* Define a function that checks whether a boolean exression is in NNF\n(negation normal form), i.e., if @{const NOT} is only applied directly\nto @{const VAR}s: *}\n\nfun is_nnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_nnf (VAR x) = True\" |\n\"is_nnf (NOT (VAR x)) = True\" |\n\"is_nnf (NOT b) = False\" |\n\"is_nnf (AND b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\" |\n\"is_nnf (OR b1 b2) = (is_nnf b1 \\<and> is_nnf b2)\"\n\ntext{*\nNow define a function that converts a @{text bexp} into NNF by pushing\n@{const NOT} inwards as much as possible:\n*}\n\nfun nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"nnf (VAR x) = (VAR x)\" |\n\"nnf (NOT (VAR x)) = (NOT (VAR x))\" |\n\"nnf (NOT (NOT b)) = nnf b\" |\n\"nnf (NOT (AND b1 b2)) = (OR (nnf (NOT b1)) (nnf (NOT b2)))\" |\n\"nnf (NOT (OR b1 b2)) = (AND (nnf (NOT b1)) (nnf (NOT b2)))\" |\n\"nnf (AND b1 b2) = (AND (nnf b1) (nnf b2))\" |\n\"nnf (OR b1 b2) = (OR (nnf b1) (nnf b2))\"\n\ntext{*\nProve that @{const nnf} does what it is supposed to do:\n*}\n\nlemma pbval_nnf: \"pbval (nnf b) s = pbval b s\"\napply(induction b rule: nnf.induct)\napply(auto)  \ndone\n    \nlemma is_nnf_nnf: \"is_nnf (nnf b)\"\napply(induction b rule: nnf.induct)\napply(auto)  \ndone\n\ntext{*\nAn expression is in DNF (disjunctive normal form) if it is in NNF\nand if no @{const OR} occurs below an @{const AND}. Define a corresponding\ntest:\n*}\n\nfun no_or :: \"pbexp \\<Rightarrow> bool\" where\n\"no_or (VAR x) = True\" |\n\"no_or (NOT b) = no_or b\" |\n\"no_or (OR b1 b2) = False\" |\n\"no_or (AND b1 b2) = (no_or b1 \\<and> no_or b2)\"\n  \nfun is_dnf :: \"pbexp \\<Rightarrow> bool\" where\n\"is_dnf (VAR x) = True\" |\n\"is_dnf (NOT (VAR x)) = True\" |\n\"is_dnf (NOT b) = False\" |\n\"is_dnf (AND b1 b2) = (is_nnf b1 \\<and> no_or b1 \\<and> is_nnf b2 \\<and> no_or b2)\" |\n\"is_dnf (OR b1 b2) = (is_dnf b1 \\<and> is_dnf b2)\"\n\nlemma is_dnf_nnf: \"is_dnf b1 \\<Longrightarrow> is_nnf b1\"\napply(induction b1 rule: is_dnf.induct)\napply(auto)  \ndone\n\nlemma is_dnf_not_no_or: \"is_dnf (NOT v) \\<Longrightarrow> no_or v\"\napply(induction v rule: is_dnf.induct)\napply(auto)  \ndone  \n\ntext {*\nAn NNF can be converted into a DNF in a bottom-up manner.\nThe critical case is the conversion of @{term (sub) \"AND b1 b2\"}.\nHaving converted @{text b\\<^sub>1} and @{text b\\<^sub>2}, apply distributivity of @{const AND}\nover @{const OR}. If we write @{const OR} as a multi-argument function,\nwe can express the distributivity step as follows:\n@{text \"dist_AND (OR a\\<^sub>1 ... a\\<^sub>n) (OR b\\<^sub>1 ... b\\<^sub>m)\"}\n= @{text \"OR (AND a\\<^sub>1 b\\<^sub>1) (AND a\\<^sub>1 b\\<^sub>2) ... (AND a\\<^sub>n b\\<^sub>m)\"}. Define\n*}\n\nfun dist_AND :: \"pbexp \\<Rightarrow> pbexp \\<Rightarrow> pbexp\" where\n(*\"dist_AND (OR a1 a2) (OR b1 b2) = (OR (OR (dist_AND a1 b1) (dist_AND a1 b2)) (OR (dist_AND a2 b1) (dist_AND a2 b2)))\" |*)\n\"dist_AND a (OR b1 b2) = (OR (dist_AND a b1) (dist_AND a b2))\" |\n\"dist_AND (OR a1 a2) b = (OR (dist_AND a1 b) (dist_AND a2 b))\" |\n\"dist_AND b1 b2 = (AND b1 b2)\"\n\ntext {* and prove that it behaves as follows: *}\n\nlemma pbval_dist: \"pbval (dist_AND b1 b2) s = pbval (AND b1 b2) s\"\napply(induction b1 b2 rule: dist_AND.induct)\napply(auto)\ndone\n\n\n\nlemma [simp]:\"is_dnf b2 \\<Longrightarrow>\n       is_nnf b1 \\<Longrightarrow> no_or b1 \\<Longrightarrow> is_nnf b2a \\<Longrightarrow> no_or b2a \\<Longrightarrow> is_dnf (dist_AND (AND b1 b2a) b2)\"\napply(induction b2)\napply(auto simp add: is_dnf_nnf is_dnf_not_no_or)\ndone\n\nlemma [simp]:\"is_dnf (dist_AND b1 b2) \\<Longrightarrow>\n       is_dnf (dist_AND b2a b2) \\<Longrightarrow>\n       is_dnf b2 \\<Longrightarrow> is_dnf b1 \\<Longrightarrow> is_dnf b2a \\<Longrightarrow> is_dnf (dist_AND (OR b1 b2a) b2)\"\napply(induction b2)\napply(auto simp add: is_dnf_nnf is_dnf_not_no_or)\ndone\n  \nlemma is_dnf_dist: \"is_dnf b1 \\<Longrightarrow> is_dnf b2 \\<Longrightarrow> is_dnf (dist_AND b1 b2)\"\napply(induction b1 rule: is_dnf.induct)\napply(auto simp add: is_dnf_nnf)\napply(induction b2 rule: dist_AND.induct)\napply(auto simp add: is_dnf_nnf is_dnf_not_no_or)\ndone\n\ntext {* Use @{const dist_AND} to write a function that converts an NNF\n  to a DNF in the above bottom-up manner.\n*}\n\nfun dnf_of_nnf :: \"pbexp \\<Rightarrow> pbexp\" where\n\"dnf_of_nnf (VAR x) = (VAR x)\" |\n\"dnf_of_nnf (NOT b) = (NOT b)\" |\n\"dnf_of_nnf (AND b1 b2) = dist_AND (dnf_of_nnf b1) (dnf_of_nnf b2)\" |\n\"dnf_of_nnf (OR b1 b2) = (OR (dnf_of_nnf b1) (dnf_of_nnf b2))\"\n\ntext {* Prove the correctness of your function: *}\n\nlemma \"pbval (dnf_of_nnf b) s = pbval b s\"\napply(induction b)\napply(auto simp add:pbval_dist)\ndone\n\nlemma not_is_dnf_if_nnf: \"is_nnf (NOT b) \\<Longrightarrow> is_dnf (NOT b)\"\napply(induction b)\napply(auto)  \ndone\n    \nlemma \"is_nnf b \\<Longrightarrow> is_dnf (dnf_of_nnf b)\"\napply(induction b)\napply(auto simp add:is_dnf_dist not_is_dnf_if_nnf)  \ndone    \n\ntext{*\n\\endexercise\n\n\n\\exercise\\label{exe:stack-underflow}\nA \\concept{stack underflow} occurs when executing an @{text ADD}\ninstruction on a stack of size less than two. In our semantics\nstack underflow leads to a term involving @{term \"hd []\"},\nwhich is not an error or exception --- HOL does not\nhave those concepts --- but some unspecified value. Modify\ntheory @{theory ASM} such that stack underflow is modelled by @{const None}\nand normal execution by @{text Some}, i.e., the execution functions\nhave return type @{typ \"stack option\"}. Modify all theorems and proofs\naccordingly.\nHint: you may find @{text\"split: option.split\"} useful in your proofs.\n*}\n\ntext{*\n\\endexercise\n\n\\exercise\\label{exe:register-machine}\nThis exercise is about a register machine\nand compiler for @{typ aexp}. The machine instructions are\n*}\ntype_synonym reg = nat\ndatatype instr = LDI val reg | LD vname reg | ADD reg reg\n\ntext {*\nwhere type @{text reg} is a synonym for @{typ nat}.\nInstruction @{term \"LDI i r\"} loads @{text i} into register @{text r},\n@{term \"LD x r\"} loads the value of @{text x} into register @{text r},\nand @{term[names_short] \"ADD r\\<^sub>1 r\\<^sub>2\"} adds register @{text r\\<^sub>2} to register @{text r\\<^sub>1}.\n\nDefine the execution of an instruction given a state and a register state;\nthe result is the new register state: *}\n\ntype_synonym rstate = \"reg \\<Rightarrow> val\"\n\nfun exec1 :: \"instr \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec1 (LDI i r) s rs = rs(r := i)\" |\n\"exec1 (LD x r) s rs = rs(r := s(x))\" |\n\"exec1 (ADD r1 r2) s rs = rs(r1 := rs(r1) + rs(r2))\"\n\ntext{*\nDefine the execution @{const[source] exec} of a list of instructions as for the stack machine.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto @{text r}. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"< r\"} should be left alone.\nDefine the compiler and prove it correct:\n*}\n\nfun execn :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"execn [] s rs = rs\" |\n\"execn (i#is) s rs = execn is s (exec1 i s rs)\"\n  \nfun exec :: \"instr list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> reg \\<Rightarrow> val\" where\n\"exec [] s rs r = rs(r)\" |\n\"exec (i#is) s rs r = exec is s (exec1 i s rs) r\"\n\nfun comp :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr list\" where\n\"comp (N n) r = [LDI n r]\" |\n\"comp (V v) r = [LD v r]\" |\n\"comp (Plus a1 a2) r = (comp a1 r) @ (comp a2 (r + 1)) @ [ADD r (r + 1)]\"\n\nlemma exec_execn:\"exec is1 s rs r = (let rs1 = execn is1 s rs in rs1(r))\"\napply(induction is1 arbitrary: rs)\napply(auto)  \ndone\n    \nlemma execn_dist_append:\"(execn (is1 @ is2) s rs) = (execn is2 s (execn is1 s rs))\"\napply(induction is1 arbitrary: rs)\napply(auto)\ndone\n\nlemma execn_comp_append:\"(execn ((comp a r) @ is2) s rs) = (execn is2 s (execn (comp a r) s rs))\"\napply(auto simp add:execn_dist_append)\ndone\n      \nlemma comp_left_rs_not_changed:\"r1 > r \\<Longrightarrow> execn (comp a r1) s rs r = rs(r)\"\napply(induction a arbitrary: r r1 rs)\napply(auto simp add:execn_dist_append)\ndone\n    \ntheorem \"exec (comp a r) s rs r = aval a s\"\napply(induction a arbitrary: r rs)\napply(auto simp add:exec_execn execn_comp_append comp_left_rs_not_changed)\ndone\n    \ntext{*\n\\endexercise\n\n\\exercise\\label{exe:accumulator}\nThis exercise is a variation of the previous one\nwith a different instruction set:\n*}\n\ndatatype instr0 = LDI0 val | LD0 vname | MV0 reg | ADD0 reg\n\ntext{*\nAll instructions refer implicitly to register 0 as a source or target:\n@{const LDI0} and @{const LD0} load a value into register 0, @{term \"MV0 r\"}\ncopies the value in register 0 into register @{text r}, and @{term \"ADD0 r\"}\nadds the value in register @{text r} to the value in register 0;\n@{term \"MV0 0\"} and @{term \"ADD0 0\"} are legal. Define the execution functions\n*}\n\nfun exec01 :: \"instr0 \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec01 (LDI0 x) s rs = rs(0 := x)\" |\n\"exec01 (LD0 v) s rs = rs(0 := s(v))\" |\n\"exec01 (MV0 r) s rs = rs(r := rs(0))\" |\n\"exec01 (ADD0 r) s rs = rs(0 := rs(0) + rs(r))\"\n\nfun exec0 :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> reg \\<Rightarrow> val\" where\n\"exec0 [] s rs r = rs(r)\" |\n\"exec0 (is#rest) s rs r = exec0 rest s (exec01 is s rs) r\"\n\nfun comp0 :: \"aexp \\<Rightarrow> reg \\<Rightarrow> instr0 list\" where\n\"comp0 (N n) r = [LDI0 n, MV0 r]\" |\n\"comp0 (V v) r = [LD0 v, MV0 r]\" |\n\"comp0 (Plus a1 a2) r = (comp0 a1 (r + 1)) @ (comp0 a2 (r + 2)) @ [ADD0 (r + 1), MV0 r]\"\n\ntext{*\nand @{const exec0} for instruction lists.\n\nThe compiler takes an arithmetic expression @{text a} and a register @{text r}\nand produces a list of instructions whose execution places the value of @{text a}\ninto register 0. The registers @{text \"> r\"} should be used in a stack-like fashion\nfor intermediate results, the ones @{text \"\\<le> r\"} should be left alone\n(with the exception of 0). Define the compiler and prove it correct:\n*}\n\nfun exec0n :: \"instr0 list \\<Rightarrow> state \\<Rightarrow> rstate \\<Rightarrow> rstate\" where\n\"exec0n [] s rs = rs\" |\n\"exec0n (i#is) s rs = exec0n is s (exec01 i s rs)\"\n\nlemma exec0_exec0n[simp]:\"exec0 is1 s rs r = (let rs1 = exec0n is1 s rs in rs1(r))\"\napply(induction is1 arbitrary: rs)\napply(auto)  \ndone\n\nlemma exec0n_dist_append:\"(exec0n (is1 @ is2) s rs) = (exec0n is2 s (exec0n is1 s rs))\"\napply(induction is1 arbitrary: rs)\napply(auto)\ndone\n\nlemma exec0n_comp0_append:\"(exec0n ((comp0 a r) @ is2) s rs) = (exec0n is2 s (exec0n (comp0 a r) s rs))\"\napply(auto simp add:exec0n_dist_append)\ndone\n      \nlemma comp0_left_rs_not_changed:\"r1 > r \\<and> r > 0 \\<Longrightarrow> exec0n (comp0 a r1) s rs r = rs(r)\"\napply(induction a arbitrary: r r1 rs)\napply(auto simp add:exec0n_dist_append)\ndone\n\nlemma exec0_comp0_rsr_is_equal_rs0:\"exec0 (comp0 a r) s rs r = exec0 (comp0 a r) s rs 0\"\napply(induction a arbitrary: r rs)\napply(auto simp add:exec0n_dist_append)\ndone\n\nlemma exec0n_comp0_rs0_is_equal_rsr:\"exec0n (comp0 a r) s rs 0 = exec0n (comp0 a r) s rs r\"\napply(induction a arbitrary: r rs)\napply(auto simp add:exec0n_dist_append)\ndone\n\nlemma exec0n_cond:\"(exec0n (comp0 a2 r2) s (exec0n (comp0 a1 r1) s rs1) 0 = exec0n (comp0 a2 r2) s (exec0n (comp0 a1 r1) s rs2) 0) \\<and>\n       (exec0n (comp0 a1 r1) s rs1 r1 = exec0n (comp0 a1 r1) s rs2 r1) \\<Longrightarrow>\n       exec0n (comp0 a2 r2) s (exec0n (comp0 a1 r1) s rs1) 0 +\n       exec0n (comp0 a1 r1) s rs1 r1 =\n       exec0n (comp0 a2 r2) s (exec0n (comp0 a1 r1) s rs2) 0 +\n       exec0n (comp0 a1 r1) s rs2 r1\"\napply(auto)  \ndone\n\nlemma exec0n_rs1_arbitrary: \"exec0n (comp0 a r) s rs1 r = exec0n (comp0 a r) s rs2 r\"\napply(induction a arbitrary: r rs1 rs2)\napply(auto simp add:exec0n_dist_append exec0n_comp0_append comp0_left_rs_not_changed)    \napply(subst exec0n_cond)\napply(auto simp add: exec0n_comp0_rs0_is_equal_rsr)\ndone\n    \ntheorem \"exec0 (comp0 a r) s rs 0 = aval a s\"\napply(induction a arbitrary: r rs)\napply(auto simp add:exec0n_dist_append exec0n_comp0_append comp0_left_rs_not_changed)    \napply(auto simp add:exec0n_comp0_rs0_is_equal_rsr)    \ndone\n\ntext{*\n\\endexercise\n*}\n\nend\n\n", "meta": {"author": "masateruk", "repo": "isabelle_concrete_semantics", "sha": "fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab", "save_path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics", "path": "github-repos/isabelle/masateruk-isabelle_concrete_semantics/isabelle_concrete_semantics-fc607bbbcd63d59fcb3b10c5ec68388c1b1f9aab/chapter3/Chapter3.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8499711604559846, "lm_q2_score": 0.8824278772763472, "lm_q1q2_score": 0.750038246867288}}
{"text": "(*\n  File:    Angles.thy\n  Author:  Manuel Eberl <eberlm@in.tum.de>\n\n  Definition of angles between vectors and between three points.\n*)\n\nsection \\<open>Definition of angles\\<close>\ntheory Angles\nimports\n  \"HOL-Analysis.Multivariate_Analysis\"\nbegin\n\nlemma collinear_translate_iff: \"collinear (((+) a) ` A) \\<longleftrightarrow> collinear A\"\n  by (auto simp: collinear_def)\n\n\ndefinition vangle where\n  \"vangle u v = (if u = 0 \\<or> v = 0 then pi / 2 else arccos (u \\<bullet> v / (norm u * norm v)))\"\n\ndefinition angle where\n  \"angle a b c = vangle (a - b) (c - b)\"\n\nlemma angle_altdef: \"angle a b c = arccos ((a - b) \\<bullet> (c - b) / (dist a b * dist c b))\"\n  by (simp add: angle_def vangle_def dist_norm)\n\nlemma vangle_0_left [simp]: \"vangle 0 v = pi / 2\"\n  and vangle_0_right [simp]: \"vangle u 0 = pi / 2\"\n  by (simp_all add: vangle_def)\n\nlemma vangle_refl [simp]: \"u \\<noteq> 0 \\<Longrightarrow> vangle u u = 0\"\n  by (simp add: vangle_def dot_square_norm power2_eq_square)\n\nlemma angle_refl [simp]: \"angle a a b = pi / 2\" \"angle a b b = pi / 2\"\n  by (simp_all add: angle_def)\n\nlemma angle_refl_mid [simp]: \"a \\<noteq> b \\<Longrightarrow> angle a b a = 0\"\n  by (simp add: angle_def)\n\n\nlemma cos_vangle: \"cos (vangle u v) = u \\<bullet> v / (norm u * norm v)\"\n  unfolding vangle_def using Cauchy_Schwarz_ineq2[of u v] by (auto simp: field_simps)\n\nlemma cos_angle: \"cos (angle a b c) = (a - b) \\<bullet> (c - b) / (dist a b * dist c b)\"\n  by (simp add: angle_def cos_vangle dist_norm)\n\nlemma inner_conv_angle: \"(a - b) \\<bullet> (c - b) = dist a b * dist c b * cos (angle a b c)\"\n  by (simp add: cos_angle)\n\nlemma vangle_commute: \"vangle u v = vangle v u\"\n  by (simp add: vangle_def inner_commute mult.commute)\n\n\n\nlemma vangle_nonneg: \"vangle u v \\<ge> 0\" and vangle_le_pi: \"vangle u v \\<le> pi\"\n  using Cauchy_Schwarz_ineq2[of u v]\n  by (auto simp: vangle_def field_simps intro!: arccos_lbound arccos_ubound)\n\nlemmas vangle_bounds = vangle_nonneg vangle_le_pi\n\nlemma angle_nonneg: \"angle a b c \\<ge> 0\" and angle_le_pi: \"angle a b c \\<le> pi\"\n  using vangle_bounds unfolding angle_def by blast+\n\nlemmas angle_bounds = angle_nonneg angle_le_pi\n\nlemma sin_vangle_nonneg: \"sin (vangle u v) \\<ge> 0\"\n  using vangle_bounds by (rule sin_ge_zero)\n\nlemma sin_angle_nonneg: \"sin (angle a b c) \\<ge> 0\"\n  using angle_bounds by (rule sin_ge_zero)\n\n\nlemma vangle_eq_0D:\n  assumes \"vangle u v = 0\"\n  shows   \"norm u *\\<^sub>R v = norm v *\\<^sub>R u\"\nproof -\n  from assms have \"u \\<bullet> v = norm u * norm v\"\n    using arccos_eq_iff[of \"(u \\<bullet> v) / (norm u * norm v)\" 1] Cauchy_Schwarz_ineq2[of u v]\n    by (fastforce simp: vangle_def split: if_split_asm)\n  thus ?thesis by (subst (asm) norm_cauchy_schwarz_eq) simp_all\nqed\n\nlemma vangle_eq_piD:\n  assumes \"vangle u v = pi\"\n  shows   \"norm u *\\<^sub>R v + norm v *\\<^sub>R u = 0\"\nproof -\n  from assms have \"(-u) \\<bullet> v = norm (-u) * norm v\"\n    using arccos_eq_iff[of \"(u \\<bullet> v) / (norm u * norm v)\" \"-1\"] Cauchy_Schwarz_ineq2[of u v]\n    by (simp add: field_simps vangle_def split: if_split_asm)\n  thus ?thesis by (subst (asm) norm_cauchy_schwarz_eq) simp_all\nqed\n\nlemma dist_triangle_eq:\n  fixes a b c :: \"'a :: real_inner\"\n  shows \"(dist a c = dist a b + dist b c) \\<longleftrightarrow> dist a b *\\<^sub>R (c - b) + dist b c *\\<^sub>R (a - b) = 0\"\n  using norm_triangle_eq[of \"b - a\" \"c - b\"]\n  by (simp add: dist_norm norm_minus_commute algebra_simps)\n\nlemma angle_eq_pi_imp_dist_additive:\n  assumes \"angle a b c = pi\"\n  shows   \"dist a c = dist a b + dist b c\"\n  using vangle_eq_piD[OF assms[unfolded angle_def]]\n  by (subst dist_triangle_eq) (simp add: dist_norm norm_minus_commute)\n\n\nlemma orthogonal_iff_vangle: \"orthogonal u v \\<longleftrightarrow> vangle u v = pi / 2\"\n  using arccos_eq_iff[of \"u \\<bullet> v / (norm u * norm v)\" 0] Cauchy_Schwarz_ineq2[of u v]\n  by (auto simp: vangle_def orthogonal_def)\n\nlemma cos_minus1_imp_pi:\n  assumes \"cos x = -1\" \"x \\<ge> 0\" \"x < 3 * pi\"\n  shows   \"x = pi\"\nproof -\n  have \"cos (x - pi) = 1\" by (simp add: assms)\n  then obtain n :: int where n: \"of_int n = (x / pi - 1) / 2\"\n    by (subst (asm) cos_one_2pi_int) (auto simp: field_simps)\n  also from assms have \"\\<dots> \\<in> {-1<..<1}\" by (auto simp: field_simps)\n  finally have \"n = 0\" by simp\n  with n show ?thesis by simp\nqed\n\n\nlemma vangle_eqI:\n  assumes \"u \\<noteq> 0\" \"v \\<noteq> 0\" \"w \\<noteq> 0\" \"x \\<noteq> 0\"\n  assumes \"(u \\<bullet> v) * norm w * norm x = (w \\<bullet> x) * norm u * norm v\"\n  shows   \"vangle u v = vangle w x\"\n  using assms Cauchy_Schwarz_ineq2[of u v] Cauchy_Schwarz_ineq2[of w x]\n  unfolding vangle_def by (auto simp: arccos_eq_iff field_simps)\n\n\n\nlemma cos_vangle_eqD: \"cos (vangle u v) = cos (vangle w x) \\<Longrightarrow> vangle u v = vangle w x\"\n  by (rule cos_inj_pi) (simp_all add: vangle_bounds)\n\nlemma cos_angle_eqD: \"cos (angle a b c) = cos (angle d e f) \\<Longrightarrow> angle a b c = angle d e f\"\n  unfolding angle_def by (rule cos_vangle_eqD)\n\nlemma sin_vangle_zero_iff: \"sin (vangle u v) = 0 \\<longleftrightarrow> vangle u v \\<in> {0, pi}\"\nproof\n  assume \"sin (vangle u v) = 0\"\n  then obtain n :: int where n: \"of_int n = vangle u v / pi\"\n    by (subst (asm) sin_zero_iff_int2) auto\n  also have \"\\<dots> \\<in> {0..1}\" using vangle_bounds by (auto simp: field_simps)\n  finally have \"n \\<in> {0,1}\" by auto\n  thus \"vangle u v \\<in> {0,pi}\" using n by (auto simp: field_simps)\nqed auto\n\nlemma sin_angle_zero_iff: \"sin (angle a b c) = 0 \\<longleftrightarrow> angle a b c \\<in> {0, pi}\"\n  unfolding angle_def by (simp only: sin_vangle_zero_iff)\n\nlemma vangle_collinear: \"vangle u v \\<in> {0, pi} \\<Longrightarrow> collinear {0, u, v}\"\napply (subst norm_cauchy_schwarz_equal [symmetric])\napply (subst norm_cauchy_schwarz_abs_eq)\napply (auto dest!: vangle_eq_0D vangle_eq_piD simp: eq_neg_iff_add_eq_0)\ndone\n\nlemma angle_collinear: \"angle a b c \\<in> {0, pi} \\<Longrightarrow> collinear {a, b, c}\"\napply (unfold angle_def, drule vangle_collinear)\napply (subst collinear_translate_iff[symmetric, of _ \"-b\"])\napply (auto simp: insert_commute)\ndone\n\nlemma not_collinear_vangle: \"\\<not>collinear {0,u,v} \\<Longrightarrow> vangle u v \\<in> {0<..<pi}\"\n  using vangle_bounds[of u v] vangle_collinear[of u v]\n  by (cases \"vangle u v = 0 \\<or> vangle u v = pi\") auto\n\nlemma not_collinear_angle: \"\\<not>collinear {a,b,c} \\<Longrightarrow> angle a b c \\<in> {0<..<pi}\"\n  using angle_bounds[of a b c] angle_collinear[of a b c]\n  by (cases \"angle a b c = 0 \\<or> angle a b c = pi\") auto\n\nsubsection\\<open>Contributions from Lukas Bulwahn\\<close>\n\nlemma vangle_scales:\n  assumes \"0 < c\"\n  shows \"vangle (c *\\<^sub>R v\\<^sub>1) v\\<^sub>2 = vangle v\\<^sub>1 v\\<^sub>2\"\nusing assms unfolding vangle_def by auto\n\nlemma vangle_inverse:\n  \"vangle (- v\\<^sub>1) v\\<^sub>2 = pi - vangle v\\<^sub>1 v\\<^sub>2\"\nproof -\n  have \"\\<bar>v\\<^sub>1 \\<bullet> v\\<^sub>2 / (norm v\\<^sub>1 * norm v\\<^sub>2)\\<bar> \\<le> 1\"\n  proof cases\n    assume \"v\\<^sub>1 \\<noteq> 0 \\<and> v\\<^sub>2 \\<noteq> 0\"\n    from this show ?thesis by (simp add: Cauchy_Schwarz_ineq2)\n  next\n    assume \"\\<not> (v\\<^sub>1 \\<noteq> 0 \\<and> v\\<^sub>2 \\<noteq> 0)\"\n    from this show ?thesis by auto\n  qed\n  from this show ?thesis\n    unfolding vangle_def\n    by (simp add: arccos_minus_abs)\nqed\n\nlemma orthogonal_iff_angle:\n  shows \"orthogonal (A - B) (C - B) \\<longleftrightarrow> angle A B C = pi / 2\"\nunfolding angle_def by (auto simp only: orthogonal_iff_vangle)\n\nlemma angle_inverse:\n  assumes \"between (A, C) B\"\n  assumes \"A \\<noteq> B\" \"B \\<noteq> C\"\n  shows \"angle A B D = pi - angle C B D\"\nproof -\n  from \\<open>between (A, C) B\\<close> obtain u where u: \"u \\<ge> 0\" \"u \\<le> 1\"\n    and X: \"B = u *\\<^sub>R A + (1 - u) *\\<^sub>R C\"\n    by (metis add.commute betweenE between_commute)\n  from \\<open>A \\<noteq> B\\<close> \\<open>B \\<noteq> C\\<close> X have \"u \\<noteq> 0\" \"u \\<noteq> 1\" by auto\n  have \"0 < ((1 - u) / u)\"\n    using \\<open>u \\<noteq> 0\\<close> \\<open>u \\<noteq> 1\\<close> \\<open>u \\<ge> 0\\<close> \\<open>u \\<le> 1\\<close> by simp\n  from X have \"A - B = - (1 - u) *\\<^sub>R (C - A)\"\n    by (simp add: real_vector.scale_right_diff_distrib real_vector.scale_left_diff_distrib)\n  moreover from X have \"C - B = u *\\<^sub>R (C - A)\"\n    by (simp add: scaleR_diff_left real_vector.scale_right_diff_distrib)\n  ultimately have \"A - B = - (((1 - u) / u) *\\<^sub>R (C - B))\"\n    using \\<open>u \\<noteq> 0\\<close> by simp (metis minus_diff_eq real_vector.scale_minus_left)\n  from this have \"vangle (A - B) (D - B) = pi - vangle (C - B) (D - B)\"\n    using \\<open>0 < (1 - u) / u\\<close> by (simp add: vangle_inverse vangle_scales)\n  from this show ?thesis\n    unfolding angle_def by simp\nqed\n\nlemma strictly_between_implies_angle_eq_pi:\n  assumes \"between (A, C) B\"\n  assumes \"A \\<noteq> B\" \"B \\<noteq> C\"\n  shows \"angle A B C = pi\"\nproof -\n  from \\<open>between (A, C) B\\<close> obtain u where u: \"u \\<ge> 0\" \"u \\<le> 1\"\n    and X: \"B = u *\\<^sub>R A + (1 - u) *\\<^sub>R C\"\n    by (metis add.commute betweenE between_commute)\n  from \\<open>A \\<noteq> B\\<close> \\<open>B \\<noteq> C\\<close> X have \"u \\<noteq> 0\" \"u \\<noteq> 1\" by auto\n  from \\<open>A \\<noteq> B\\<close> \\<open>B \\<noteq> C\\<close> \\<open>between (A, C) B\\<close> have \"A \\<noteq> C\" by auto\n  from X have \"A - B = - (1 - u) *\\<^sub>R (C - A)\"\n    by (simp add: real_vector.scale_right_diff_distrib real_vector.scale_left_diff_distrib)\n  moreover from this have \"dist A B = norm ((1 - u) *\\<^sub>R (C - A))\"\n    using \\<open>u \\<ge> 0\\<close> \\<open>u \\<le> 1\\<close> by (simp add: dist_norm)\n  moreover from X have \"C - B = u *\\<^sub>R (C - A)\"\n    by (simp add: scaleR_diff_left real_vector.scale_right_diff_distrib)\n  moreover from this have \"dist C B = norm (u *\\<^sub>R (C - A))\"\n    by (simp add: dist_norm)\n  ultimately have \"(A - B) \\<bullet> (C - B) / (dist A B * dist C B) = u * (u - 1) / (\\<bar>1 - u\\<bar> * \\<bar>u\\<bar>)\"\n    using \\<open>A \\<noteq> C\\<close> by (simp add: dot_square_norm power2_eq_square)\n  also have \"\\<dots> = - 1\"\n    using \\<open>u \\<noteq> 0\\<close> \\<open>u \\<noteq> 1\\<close> \\<open>u \\<ge> 0\\<close> \\<open>u \\<le> 1\\<close> by (simp add: divide_eq_minus_1_iff)\n  finally show ?thesis\n    unfolding angle_altdef by simp\nqed\n\nend\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Triangle/Angles.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.8438951084436077, "lm_q1q2_score": 0.7500192033875235}}
{"text": "(*\nAuction Theory Toolbox (http://formare.github.io/auctions/)\n\nAuthors:\n* Marco B. Caminati http://caminati.co.nr\n* Manfred Kerber <mnfrd.krbr@gmail.com>\n* Christoph Lange <math.semantic.web@gmail.com>\n* Colin Rowat <c.rowat@bham.ac.uk>\n\n\nDually licenced under\n* Creative Commons Attribution (CC-BY) 3.0\n* ISC License (1-clause BSD License)\nSee LICENSE file for details\n(Rationale for this dual licence: http://arxiv.org/abs/1107.3212)\n*)\n\nsection \\<open>Locus where a function or a list (of linord type) attains its maximum value\\<close>\n\ntheory Argmax\nimports Main\n\nbegin\n\ntext \\<open>Structural induction is used in proofs on lists.\\<close>\nlemma structInduct: assumes \"P []\" and \"\\<forall>x xs. P (xs) \\<longrightarrow> P (x#xs)\" \n                    shows \"P l\" \n      using assms list_nonempty_induct by (metis)\n\ntext \\<open>the subset of elements of a set where a function reaches its maximum\\<close>\nfun argmax :: \"('a \\<Rightarrow> 'b::linorder) \\<Rightarrow> 'a set \\<Rightarrow> 'a set\"\n    where \"argmax f A = { x \\<in> A . f x = Max (f ` A) }\"\n\n(* For reasons we do not understand we have to duplicate the definition as a lemma \n   in order to prove lm16 in CombinatorialAuctions.thy. *)\nlemma argmaxLemma: \"argmax f A = { x \\<in> A . f x = Max (f ` A) }\" \n  by simp\n\nlemma maxLemma: \n  assumes \"x \\<in> X\" \"finite X\" \n  shows \"Max (f`X) >= f x\" \n  (is \"?L >= ?R\") using assms \n  by (metis (hide_lams, no_types) Max.coboundedI finite_imageI image_eqI)\n\nlemma lm01: \n  \"argmax f A = A \\<inter> f -` {Max (f ` A)}\" \n  by force\n\nlemma lm02: \n  assumes \"y \\<in> f`A\" \n  shows \"A \\<inter> f -` {y} \\<noteq> {}\" \n  using assms by blast\n\nlemma argmaxEquivalence: \n  assumes \"\\<forall>x\\<in>X. f x = g x\" \n  shows \"argmax f X = argmax g X\" \n  using assms argmaxLemma Collect_cong image_cong \n  by (metis(no_types,lifting))\n\ntext \\<open>The arg max of a function over a non-empty set is non-empty.\\<close>\ncorollary argmax_non_empty_iff: assumes \"finite X\" \"X \\<noteq> {}\" \n                                shows \"argmax f X \\<noteq>{}\"\n                                using assms Max_in finite_imageI image_is_empty lm01 lm02 \n                                by (metis(no_types))\n\ntext \\<open>The previous definition of argmax operates on sets. In the following we define a corresponding notion on lists. To this end, we start with defining a filter predicate and are looking for the elements of a list satisfying a given predicate;\nbut, rather than returning them directly, we return the (sorted) list of their indices. \nThis is done, in different ways, by @{term filterpositions} and @{term filterpositions2}.\\<close>\n\n(* Given a list l, filterpositions yields the indices of its elements which satisfy a given pred P*)\ndefinition filterpositions :: \"('a => bool) => 'a list => nat list\"\n           where \"filterpositions P l = map snd (filter (P o fst) (zip l (upt 0 (size l))))\"\n(* That is, you take the list [a0, a1, ..., an] pair with the indices [0, 1, ..., n], i.e., you get\n   [(a0,0), (a1,1), ..., (an,n)] look where the predicate (P o fst) holds and return the list of the\n   corresponding snd elements. *)\n\n\n(* Alternative definition, making use of list comprehension. In the next line the type info is\n   commented out, since the type inference can be left to Isabelle. *)\ndefinition filterpositions2 (*  :: \"('a => bool) => 'a list => nat list\" *)\n           where \"filterpositions2 P l = [n. n \\<leftarrow> [0..<size l], P (l!n)]\"\n\ndefinition maxpositions (*:: \"'a::linorder list => nat list\"*) \n           where \"maxpositions l = filterpositions2 (%x . x \\<ge> Max (set l)) l\"\n\nlemma lm03: \"maxpositions l = [n. n\\<leftarrow>[0..<size l], l!n \\<ge> Max(set l)]\" \n      unfolding maxpositions_def filterpositions2_def by fastforce\n\n(* argmaxList takes a function and a list as arguments and looks for the positions of the elements at which the function applied to the list element is maximal, e.g., \nfor the list [9, 3, 5, 9, 13] and the function `modulo 8', the function applied to the list would give the list [1, 3, 5, 1, 5], that is, argmaxList will return [2, 4]. *)\ndefinition argmaxList (*:: \"('a => ('b::linorder)) => 'a list => 'a list\"*)\n           where \"argmaxList f l = map (nth l) (maxpositions (map f l))\"\n\n(* The following lemmas state some relationships between different representation such as map and list comprehension *)\nlemma lm04: \"[n . n <- l, P n] = [n . n <- l, n \\<in> set l, P n]\" \nproof - \n(*sledgehammer-generated proof. \n  Commented out the first three lines (they look quite useless), making it more readable. \n  assume \"\\<forall>v0. SMT2.fun_app uu__ v0 = (if P v0 then [v0] else [])\"\n  assume \"\\<forall>v0. SMT2.fun_app uua__ v0 = (if v0 \\<in> set l then if P v0 then [v0] else [] else [])\" \n  obtain v3_0 :: \"('a \\<Rightarrow> 'a list) \\<Rightarrow> 'a list \\<Rightarrow> ('a \\<Rightarrow> 'a list) \\<Rightarrow> 'a\" where *) \n  have \"map (\\<lambda>uu. if P uu then [uu] else []) l = \n    map (\\<lambda>uu. if uu \\<in> set l then if P uu then [uu] else [] else []) l\" by simp\n  thus \"concat (map (\\<lambda>n. if P n then [n] else []) l) = \n    concat (map (\\<lambda>n. if n \\<in> set l then if P n then [n] else [] else []) l)\" by presburger\nqed\n\nlemma lm05: \"[n . n <- [0..<m], P n] = [n . n <- [0..<m], n \\<in> set [0..<m], P n]\" \n      using lm04 by fast\n (* sledgehammer suggested:  concat_map_singleton map_ident  map_ext by smt*)\n\nlemma lm06: fixes f m P \n            shows \"(map f [n . n <- [0..<m], P n]) = [ f n . n <- [0..<m], P n]\" \n      by (induct m) auto\n\n(* Base case stating the property for the empty list *)\nlemma map_commutes_a: \"[f n . n <- [], Q (f n)] = [x <- (map f []). Q x]\" \n      by simp\n\n(* Step case where the element x is added to the list xs *)\nlemma map_commutes_b: \"\\<forall> x xs. ([f n . n <- xs,     Q (f n)] = [x <- (map f xs).     Q x] \\<longrightarrow> \n                                [f n . n <- (x#xs), Q (f n)] = [x <- (map f (x#xs)). Q x])\" \n      by simp\n\n(* General case comprising the two previous cases. *)\nlemma map_commutes: fixes f::\"'a => 'b\" fixes Q::\"'b => bool\" fixes xs::\"'a list\" \n                    shows \"[f n . n <- xs, Q (f n)] = [x <- (map f xs). Q x]\"\n      using map_commutes_a map_commutes_b structInduct by fast\n\nlemma lm07: fixes f l \n            shows \"maxpositions (map f l) = \n                   [n . n <- [0..<size l], f (l!n) \\<ge> Max (f`(set l))]\" \n            (is \"maxpositions (?fl) = _\") (* Pattern matching abbreviation ?fl corresponds to (map f l). Used in the proof, not part of lemma itself *)\nproof -\n  have \"maxpositions ?fl = \n  [n. n <- [0..<size ?fl], n\\<in> set[0..<size ?fl], ?fl!n \\<ge> Max (set ?fl)]\"\n  using lm04 unfolding filterpositions2_def maxpositions_def .\n  also have \"... = \n  [n . n <- [0..<size l], (n<size l), (?fl!n  \\<ge> Max (set ?fl))]\" by simp\n  also have \"... = \n  [n . n <- [0..<size l], (n<size l) \\<and> (f (l!n)  \\<ge> Max (set ?fl))]\" \n  using nth_map by (metis (poly_guards_query, hide_lams)) also have \"... = \n  [n . n <- [0..<size l], (n\\<in> set [0..<size l]),(f (l!n)  \\<ge> Max (set ?fl))]\" \n  using atLeastLessThan_iff le0 set_upt by (metis(no_types))\n  also have \"... =  \n  [n . n <- [0..<size l], f (l!n) \\<ge> Max (set ?fl)]\" using lm05 by presburger \n  finally show ?thesis by auto\nqed\n\nlemma lm08: fixes f l \n            shows \"argmaxList f l = \n                   [ l!n . n <- [0..<size l], f (l!n) \\<ge> Max (f`(set l))]\"\n      unfolding lm07 argmaxList_def by (metis lm06)\n\ntext\\<open>The theorem expresses that argmaxList is the list of arguments greater equal the Max of the list.\\<close>\n\ntheorem argmaxadequacy: fixes f::\"'a => ('b::linorder)\" fixes l::\"'a list\" \n                        shows \"argmaxList f l = [ x <- l. f x \\<ge> Max (f`(set l))]\"\n                        (is \"?lh=_\") (* pattern match ?lh abbreviates \"argmaxList f l\" *)\nproof -\n  let ?P=\"% y::('b::linorder) . y \\<ge> Max (f`(set l))\"\n  let ?mh=\"[nth l n . n <- [0..<size l], ?P (f (nth l n))]\"\n  let ?rh=\"[ x <- (map (nth l) [0..<size l]). ?P (f x)]\"\n  have \"?lh = ?mh\" using lm08 by fast\n  also have \"... = ?rh\" using map_commutes by fast\n  also have \"...= [x <- l. ?P (f x)]\" using map_nth by metis\n  finally show ?thesis by force\nqed\n\nend\n\n", "meta": {"author": "data61", "repo": "PSL", "sha": "2a71eac0db39ad490fe4921a5ce1e4344dc43b12", "save_path": "github-repos/isabelle/data61-PSL", "path": "github-repos/isabelle/data61-PSL/PSL-2a71eac0db39ad490fe4921a5ce1e4344dc43b12/SeLFiE/Example/afp-2020-05-16/thys/Vickrey_Clarke_Groves/Argmax.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7500192013819086}}
{"text": "(*\n  File: Functions.thy\n  Author: Bohua Zhan\n\n  Basic results on (set-theoretic) functions.\n*)\n\ntheory Functions\n  imports Choice\nbegin\n\nsection \\<open>Functions\\<close>  (* Bourbaki II.3.4 -- II.3.6 *)\n\n(* Image under a function *)\ndefinition image_on :: \"i \\<Rightarrow> i \\<Rightarrow> i\" (infixl \"``\" 90) where [rewrite]:\n  \"f `` A = {y\\<in>target(f). \\<exists>x\\<in>source(f). x\\<in>A \\<and> f`x=y}\"\n\nlemma image_onI [backward]: \"is_function(f) \\<Longrightarrow> x \\<in> source(f) \\<Longrightarrow> x \\<in> A \\<Longrightarrow> f ` x \\<in> f `` A\" by auto2\nlemma image_onD [forward]: \"is_function(f) \\<Longrightarrow> y \\<in> f `` A \\<Longrightarrow> \\<exists>x\\<in>source(f). x \\<in> A \\<and> f`x = y\" by auto2\nsetup {* del_prfstep_thm @{thm image_on_def} *}\n\nlemma image_on_empty [rewrite]: \"is_function(f) \\<Longrightarrow> f `` \\<emptyset> = \\<emptyset>\" by auto2\nlemma image_on_mono [backward]: \"is_function(f) \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f `` A \\<subseteq> f `` B\" by auto2\n\nlemma image_non_empty [backward]: \"is_function(f) \\<Longrightarrow> S \\<subseteq> source(f) \\<Longrightarrow> S \\<noteq> \\<emptyset> \\<Longrightarrow> f `` S \\<noteq> \\<emptyset>\"\n@proof\n  @obtain x where \"x \\<in> S\"\n  @have \"f`x \\<in> f``S\"\n@qed\n\ndefinition image :: \"i \\<Rightarrow> i\" where image_def [rewrite_bidir]:\n  \"image(f) = f `` source(f)\"\nlemma image_in_target: \"is_function(f) \\<Longrightarrow> image(f) \\<subseteq> target(f)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm image_in_target} [with_term \"image(?f)\"] *}\n\nlemma imageI: \"is_function(f) \\<Longrightarrow> x \\<in> source(f) \\<Longrightarrow> f`x \\<in> image(f)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm imageI} [with_term \"?f`?x\", with_term \"image(?f)\"] *}\n\n(* Inverse image under a function *)\ndefinition fVImage :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixl \"-``\" 90) where [rewrite]:\n  \"fVImage(f,A) = {x\\<in>source(f). f`x\\<in>A}\"\n\nlemma fVImageI [typing2]: \"is_function(f) \\<Longrightarrow> x \\<in> source(f) \\<Longrightarrow> f ` x \\<in> A \\<Longrightarrow> x \\<in> f -`` A\" by auto2\nlemma fVImage_iff [rewrite]: \"is_function(f) \\<Longrightarrow> x \\<in> f -`` A \\<longleftrightarrow> (x \\<in> source(f) \\<and> f ` x \\<in> A)\" by auto2\nsetup {* del_prfstep_thm @{thm fVImage_def} *}\n\nlemma fVImage_empty [rewrite]: \"is_function(f) \\<Longrightarrow> f -`` \\<emptyset> = \\<emptyset>\" by auto2\nlemma fVImage_mono [backward]: \"is_function(f) \\<Longrightarrow> A \\<subseteq> B \\<Longrightarrow> f -`` A \\<subseteq> f -`` B\" by auto2\nlemma fVImage_compl [rewrite]: \"is_function(f) \\<Longrightarrow> f -`` (target(f) \\<midarrow> A) = source(f) \\<midarrow> (f -`` A)\" by auto2    \nlemma fVImage_union [rewrite]: \"is_function(f) \\<Longrightarrow> (f -`` A) \\<union> (f -`` B) = f -`` (A \\<union> B)\" by auto2\nlemma fVImage_target [rewrite]: \"is_function(f) \\<Longrightarrow> f -`` target(f) = source(f)\" by auto2\n\nlemma fVImage_subset [backward1]: \"is_function(f) \\<Longrightarrow> U \\<subseteq> source(f) \\<Longrightarrow> f `` U \\<subseteq> V \\<Longrightarrow> U \\<subseteq> f -`` V\"\n@proof\n  @have \"\\<forall>x'\\<in>U. x'\\<in>f-``V\" @with\n    @have \"f`x' \\<in> f``U\" @have \"f`x' \\<in> V\"\n  @end\n@qed\n\n(* Here we characterize when a function space is empty. *)\nlemma empty_fun_space [rewrite]: \"A \\<rightarrow> B = \\<emptyset> \\<longleftrightarrow> A \\<noteq> \\<emptyset> \\<and> B = \\<emptyset>\"\n@proof\n  @case \"A \\<rightarrow> B = \\<emptyset>\" @with  (* Show A \\<noteq> 0 and B = 0 *)\n    @case \"A = \\<emptyset>\" @with @have \"Fun(A,B,\\<lambda>_.\\<emptyset>) \\<in> A \\<rightarrow> B\" @end\n    @case \"B \\<noteq> \\<emptyset>\" @with @obtain \"b \\<in> B\" @have \"Fun(A,B,\\<lambda>_.b) \\<in> A \\<rightarrow> B\" @end\n  @end\n  @case \"A \\<noteq> \\<emptyset> \\<and> B = \\<emptyset>\" @with\n    @obtain \"f \\<in> A \\<rightarrow> B\" \"a \\<in> A\" @have \"f ` a \\<in> B\"\n  @end\n@qed\n\nsection \\<open>Important examples of functions\\<close>\n\n(* Identity function *)\ndefinition id_fun :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"id_fun(A) = Fun(A,A, \\<lambda>x. x)\"\n\nlemma id_fun_is_function [typing]: \"id_fun(A) \\<in> A \\<rightarrow> A\" by auto2\nlemma id_fun_eval [rewrite]: \"x \\<in> source(id_fun(A)) \\<Longrightarrow> id_fun(A) ` x = x\" by auto2\nsetup {* del_prfstep_thm @{thm id_fun_def} *}\n\nlemma id_fun_image [rewrite]: \"S \\<subseteq> A \\<Longrightarrow> id_fun(A) `` S = S\"\n@proof @have \"\\<forall>x\\<in>S. x \\<in> id_fun(A)``S\" @with @have \"id_fun(A)`x = x\" @end @qed\n\n(* Constant function *)\ndefinition const_fun :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"const_fun(A,B,y) = Fun(A,B, \\<lambda>x. y)\"\nsetup {* register_wellform_data (\"const_fun(A,B,y)\", [\"y \\<in> B\"]) *}\n\nlemma const_fun_is_function [typing]: \"y \\<in> B \\<Longrightarrow> const_fun(A,B,y) \\<in> A \\<rightarrow> B\" by auto2\nlemma const_fun_eval [rewrite]: \"y \\<in> B \\<Longrightarrow> x \\<in> source(const_fun(A,B,y)) \\<Longrightarrow> const_fun(A,B,y) ` x = y\" by auto2\nsetup {* del_prfstep_thm @{thm const_fun_def} *}\n\n(* Restriction of function to a set A *)\ndefinition func_restrict :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"func_restrict(f,A) = Fun(A, target(f), \\<lambda>x. f`x)\"\nsetup {* register_wellform_data (\"func_restrict(f,A)\", [\"A \\<subseteq> source(f)\"]) *}\nsetup {* add_prfstep_check_req (\"func_restrict(f,A)\", \"A \\<subseteq> source(f)\") *}\n\nlemma func_restrict_is_function [typing]:\n  \"is_function(f) \\<Longrightarrow> A \\<subseteq> source(f) \\<Longrightarrow> func_restrict(f,A) \\<in> A \\<rightarrow> target(f)\" by auto2\n\nlemma func_restrict_eval [rewrite]:\n  \"is_function(f) \\<Longrightarrow> A \\<subseteq> source(f) \\<Longrightarrow> x \\<in> source(func_restrict(f,A)) \\<Longrightarrow>\n   func_restrict(f,A) ` x = f ` x\" by auto2\nsetup {* del_prfstep_thm @{thm func_restrict_def} *}\n\nlemma func_restrict_trans [rewrite]:\n  \"is_function(f) \\<Longrightarrow> B \\<subseteq> source(func_restrict(f,A)) \\<Longrightarrow> A \\<subseteq> source(f) \\<Longrightarrow>\n   func_restrict(func_restrict(f,A),B) = func_restrict(f,B)\" by auto2\n\nlemma func_restrict_fImage [rewrite]:\n  \"is_function(f) \\<Longrightarrow> A \\<subseteq> source(f) \\<Longrightarrow> func_restrict(f,A) `` A = f `` A\"\n@proof\n  @let \"g = func_restrict(f,A)\"\n  @have \"\\<forall>x\\<in>f``A. x \\<in> g``A\" @with\n    @obtain y where \"y \\<in> A\" \"f`y = x\"\n    @have \"g`y \\<in> g``A\"\n  @end\n@qed\n\ndefinition func_coincide :: \"i \\<Rightarrow> i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"func_coincide(f,g,E) \\<longleftrightarrow> (E \\<subseteq> source(f) \\<and> E \\<subseteq> source(g) \\<and> (\\<forall>x\\<in>E. f`x = g`x))\"\n\nlemma func_coincideD1 [forward]:\n  \"func_coincide(f,g,E) \\<Longrightarrow> E \\<subseteq> source(f) \\<and> E \\<subseteq> source(g)\" by auto2\n\nlemma func_coincideD2 [rewrite_bidir]:\n  \"func_coincide(f,g,E) \\<Longrightarrow> x \\<in> E \\<Longrightarrow> f`x = g`x\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm func_coincide_def} *}\n\ndefinition is_func_extension :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"is_func_extension(f,g) \\<longleftrightarrow> (source(g) \\<subseteq> source(f) \\<and> func_coincide(f,g,source(g)))\"\n\nlemma extension_of_restrict [backward]:\n  \"is_function(f) \\<Longrightarrow> A \\<subseteq> source(f) \\<Longrightarrow> is_func_extension(f,func_restrict(f,A))\" by auto2\n\n(* Any function can be restricted to its image. *)\ndefinition func_restrict_image :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"func_restrict_image(f) = Fun(source(f),image(f), \\<lambda>x. f`x)\"\n\nlemma func_restrict_image_is_fun [typing]:\n  \"is_function(f) \\<Longrightarrow> func_restrict_image(f) \\<in> source(f) \\<rightarrow> image(f)\" by auto2\n\nlemma func_restrict_image_type [backward]:\n  \"is_function(f) \\<Longrightarrow> f `` source(f) = C \\<Longrightarrow> func_restrict_image(f) \\<in> source(f) \\<rightarrow> C\" by auto2\n\nlemma func_restrict_image_eval [rewrite]:\n  \"is_function(f) \\<Longrightarrow> x \\<in> source(func_restrict_image(f)) \\<Longrightarrow> func_restrict_image(f)`x = f`x\" by auto2\nsetup {* del_prfstep_thm @{thm func_restrict_image_def} *}\n\n(* Projection functions *)\ndefinition proj1_fun :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"proj1_fun(A,B) = Fun(A\\<times>B, A, \\<lambda>p. fst(p))\"\n\nlemma proj1_fun_is_function [typing]: \"proj1_fun(A,B) \\<in> A\\<times>B \\<rightarrow> A\" by auto2\nlemma proj1_eval [rewrite]: \"p \\<in> source(proj1_fun(A,B)) \\<Longrightarrow> proj1_fun(A,B)`p = fst(p)\" by auto2\nsetup {* del_prfstep_thm @{thm proj1_fun_def} *}\n\ndefinition proj2_fun :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"proj2_fun(A,B) = Fun(A\\<times>B, B, \\<lambda>p. snd(p))\"\n\nlemma proj2_fun_is_function [typing]: \"proj2_fun(A,B) \\<in> A\\<times>B \\<rightarrow> B\" by auto2\nlemma proj2_fun_eval [rewrite]: \"p \\<in> source(proj2_fun(A,B)) \\<Longrightarrow> proj2_fun(A,B)`p = snd(p)\" by auto2\nsetup {* del_prfstep_thm @{thm proj2_fun_def} *}\n\nsection \\<open>Composition of functions\\<close>  (* Bourbaki II.3.7 *)\n\n(* Composition of two functions. *)\ndefinition fun_comp :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infixr \"\\<circ>\" 60) where [rewrite]:\n  \"f' \\<circ> f = Fun(source(f), target(f'), \\<lambda>x. f' ` (f ` x))\"\nsetup {* register_wellform_data (\"f' \\<circ> f\", [\"func_form(f')\", \"func_form(f)\", \"target(f) = source(f')\"]) *}\nsetup {* add_prfstep_check_req (\"f' \\<circ> f\", \"target(f) = source(f')\") *}\n\nlemma comp_is_function [typing]:\n  \"is_function(f) \\<Longrightarrow> is_function(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> f' \\<circ> f \\<in> source(f) \\<rightarrow> target(f')\" by auto2\n\nlemma comp_eval [rewrite]:\n  \"is_function(f) \\<Longrightarrow> is_function(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow>\n   x \\<in> source(f) \\<Longrightarrow> (f' \\<circ> f) ` x = f' ` (f ` x)\" by auto2\nsetup {* add_rewrite_rule_back_cond @{thm comp_eval} [with_term \"?f' \\<circ> ?f\"] *}\nsetup {* del_prfstep_thm @{thm fun_comp_def} *}\n\nlemma comp_assoc_l:\n  \"func_form(x) \\<Longrightarrow> func_form(y) \\<Longrightarrow> func_form(z) \\<Longrightarrow> target(z) = source(y) \\<Longrightarrow>\n   target(y \\<circ> z) = source(x) \\<Longrightarrow> x \\<circ> (y \\<circ> z) = (x \\<circ> y) \\<circ> z \\<and>\n   func_form(x \\<circ> y) \\<and> target(y) = source(x) \\<and> target(z) = source(x \\<circ> y)\" by auto2\nsetup {* add_prfstep (FOL_Assoc.alg_assoc_prfstep (@{term fun_comp}, @{thm comp_assoc_l})) *}\n\nlemma comp_id_left [rewrite]:\n  \"func_form(f) \\<Longrightarrow> id_fun(target(f)) \\<circ> f = f\" by auto2\n\nlemma comp_id_right [rewrite]:\n  \"func_form(f) \\<Longrightarrow> f \\<circ> id_fun(source(f)) = f\" by auto2\n\nlemma func_vImage_comp [rewrite]:\n  \"is_function(f) \\<Longrightarrow> is_function(g) \\<Longrightarrow> target(f) = source(g) \\<Longrightarrow>\n   (g \\<circ> f) -`` V = f -`` (g -`` V)\" by auto2\nsetup {* add_rewrite_rule_back_cond @{thm func_vImage_comp} [with_term \"?g \\<circ> ?f\"] *}\n\nsection \\<open>Injective, surjective, and bijective functions.\\<close>\n\ndefinition injective :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"injective(f) \\<longleftrightarrow> (is_function(f) \\<and> (\\<forall>x\\<in>source(f). \\<forall>y\\<in>source(f). f`x = f`y \\<longrightarrow> x=y))\"\n\nlemma injectiveI [backward]:\n  \"is_function(f) \\<Longrightarrow> (\\<forall>x\\<in>source(f). \\<forall>y\\<in>source(f). f`x = f`y \\<longrightarrow> x=y) \\<Longrightarrow> injective(f)\" by auto2\n\nlemma injectiveD [forward]:\n  \"injective(f) \\<Longrightarrow> is_function(f)\"\n  \"injective(f) \\<Longrightarrow> x \\<in> source(f) \\<Longrightarrow> y \\<in> source(f) \\<Longrightarrow> f`x = f`y \\<Longrightarrow> x = y\" by auto2+\n\ndefinition surjective :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"surjective(f) \\<longleftrightarrow> (is_function(f) \\<and> image(f) = target(f))\"\n  \nlemma surjectiveD:\n  \"surjective(f) \\<Longrightarrow> is_function(f)\"\n  \"surjective(f) \\<Longrightarrow> y \\<in> target(f) \\<Longrightarrow> \\<exists>x\\<in>source(f). f ` x = y\"\n  \"surjective(f) \\<Longrightarrow> image(f) = target(f)\" by auto2+\nsetup {* add_forward_prfstep @{thm surjectiveD(1)} *}\nsetup {* add_backward_prfstep @{thm surjectiveD(2)} *}\nsetup {* add_rewrite_rule @{thm surjectiveD(3)} *}\n\nlemma surjectiveI [backward]:\n  \"is_function(f) \\<Longrightarrow> \\<forall>y\\<in>target(f). \\<exists>x\\<in>source(f). f`x = y \\<Longrightarrow> surjective(f)\" by auto2\n\nlemma surjectiveI' [forward]:\n  \"is_function(f) \\<Longrightarrow> image(f) = target(f) \\<Longrightarrow> surjective(f)\" by auto2\n\ndefinition bijective :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"bijective(f) \\<longleftrightarrow> (injective(f) \\<and> surjective(f))\"\n\nlemma bijectiveD [forward]:\n  \"bijective(f) \\<Longrightarrow> injective(f)\"\n  \"bijective(f) \\<Longrightarrow> surjective(f)\" by auto2+\n\nlemma bijectiveI [backward]:\n  \"injective(f) \\<and> surjective(f) \\<Longrightarrow> bijective(f)\" by auto2\n\nsetup {* fold del_prfstep_thm [@{thm injective_def}, @{thm surjective_def}, @{thm bijective_def}] *}\n\ndefinition bijection_space :: \"i \\<Rightarrow> i \\<Rightarrow> i\"  (infix \"\\<cong>\" 60) where [rewrite]:\n  \"A \\<cong> B = {f \\<in> A \\<rightarrow> B. bijective(f)}\"\n\nlemma bijective_spaceD [forward]:\n  \"f \\<in> A \\<cong> B \\<Longrightarrow> f \\<in> A \\<rightarrow> B \\<and> bijective(f)\" by auto2\n\nlemma bijective_spaceI [backward]:\n  \"func_form(f) \\<Longrightarrow> bijective(f) \\<Longrightarrow> f \\<in> source(f) \\<cong> target(f)\" by auto2\nsetup {* del_prfstep_thm @{thm bijection_space_def} *}\n\n(* Some properties of surjective functions *)\nlemma surjective_to_singleton [backward2]:\n  \"f \\<in> A \\<rightarrow> {x} \\<Longrightarrow> A \\<noteq> \\<emptyset> \\<Longrightarrow> surjective(f)\" by auto2\n\nlemma surj_source_nonempty [forward, backward]:\n  \"surjective(f) \\<Longrightarrow> target(f) \\<noteq> \\<emptyset> \\<Longrightarrow> source(f) \\<noteq> \\<emptyset>\"\n@proof\n  @obtain b where \"b \\<in> target(f)\"\n  @obtain \"a \\<in> source(f)\" where \"f`a = b\"\n@qed\n    \nlemma surjective_inv_image [backward2]:\n  \"surjective(f) \\<Longrightarrow> U \\<subseteq> target(f) \\<Longrightarrow> U \\<noteq> \\<emptyset> \\<Longrightarrow> f -`` U \\<noteq> \\<emptyset>\"\n@proof\n  @obtain u where \"u \\<in> U\"\n  @obtain \"x \\<in> source(f)\" where \"f`x = u\"\n@qed\n\n(* Properties of bijective functions *)\nlemma bijective_exist_unique [backward]:\n  \"bijective(f) \\<Longrightarrow> y \\<in> target(f) \\<Longrightarrow> \\<exists>!x. x\\<in>source(f) \\<and> f`x=y\" by auto2\n\n(* Restrictions of functions *)\nlemma func_restrict_injective:\n  \"injective(f) \\<Longrightarrow> A \\<subseteq> source(f) \\<Longrightarrow> injective(func_restrict(f,A))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm func_restrict_injective} [with_term \"func_restrict(?f,?A)\"] *}\n\nlemma func_restrict_image_bij [forward]:\n  \"injective(f) \\<Longrightarrow> bijective(func_restrict_image(f))\" by auto2\n\n(* Example: canonical injection. *)\ndefinition inj_fun :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"inj_fun(A,B) = Fun(A,B, \\<lambda>x. x)\"\nsetup {* register_wellform_data (\"inj_fun(A,B)\", [\"A \\<subseteq> B\"]) *}\n\nlemma inj_fun_is_function [typing]: \"A \\<subseteq> B \\<Longrightarrow> inj_fun(A,B) \\<in> A \\<rightarrow> B\" by auto2\nlemma inj_fun_eval [rewrite]: \"A \\<subseteq> B \\<Longrightarrow> x \\<in> source(inj_fun(A,B)) \\<Longrightarrow> inj_fun(A,B) ` x = x\" by auto2\nsetup {* del_prfstep_thm @{thm inj_fun_def} *}\n\nlemma inj_fun_is_injection: \"A \\<subseteq> B \\<Longrightarrow> injective(inj_fun(A,B))\" by auto2\n\nlemma func_factorize [rewrite_back]:\n  \"func_form(f) \\<Longrightarrow> f = inj_fun(image(f),target(f)) \\<circ> func_restrict_image(f)\" by auto2\n\nlemma inj_restrict_image_bij [typing]:\n  \"injective(f) \\<Longrightarrow> func_restrict_image(f) \\<in> source(f) \\<cong> image(f)\" by auto2\n\nlemma inj_restrict_image_bij' [backward]:\n  \"injective(f) \\<Longrightarrow> f `` source(f) = C \\<Longrightarrow> func_restrict_image(f) \\<in> source(f) \\<cong> C\" by auto2\n\n(* Other examples. *)\nlemma id_bij: \"id_fun(A) \\<in> A \\<cong> A\" by auto2\nlemma proj1_surj: \"B \\<noteq> \\<emptyset> \\<Longrightarrow> surjective(proj1_fun(A,B))\" by auto2\nlemma proj2_surj: \"A \\<noteq> \\<emptyset> \\<Longrightarrow> surjective(proj2_fun(A,B))\" by auto2\nlemma swap_bij: \"Fun(A\\<times>B, B\\<times>A, \\<lambda>p. \\<langle>snd(p),fst(p)\\<rangle>) \\<in> A\\<times>B \\<cong> B\\<times>A\" by auto2\nlemma pair_bij: \"Fun(A, A\\<times>{b}, \\<lambda>x. \\<langle>x,b\\<rangle>) \\<in> A \\<cong> A\\<times>{b}\" by auto2\nlemma rpair_bij: \"Fun(A, {b}\\<times>A, \\<lambda>x. \\<langle>b,x\\<rangle>) \\<in> A \\<cong> {b}\\<times>A\" by auto2\n\nsection \\<open>Inverse function\\<close>\n\ndefinition inverse :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"inverse(f) = Fun(target(f),source(f), \\<lambda>y. THE x. x\\<in>source(f) \\<and> f`x=y)\"\nsetup {* add_prfstep_check_req (\"inverse(f)\", \"bijective(f)\") *}\n\nlemma has_inverse [typing]:\n  \"bijective(f) \\<Longrightarrow> inverse(f) \\<in> target(f) \\<rightarrow> source(f)\" by auto2\n\nlemma inverse_eval1 [rewrite]:\n  \"bijective(f) \\<Longrightarrow> x \\<in> source(f) \\<Longrightarrow> f ` x = y \\<Longrightarrow> inverse(f) ` y = x\" by auto2\n\nlemma inverse_eval2 [rewrite]:\n  \"bijective(f) \\<Longrightarrow> y \\<in> source(inverse(f)) \\<Longrightarrow> inverse(f) ` y = x \\<Longrightarrow> f ` x = y\" by auto2\nsetup {* del_prfstep_thm @{thm inverse_def} *}\n\nlemma inv_bijective [typing]:\n  \"bijective(f) \\<Longrightarrow> inverse(f) \\<in> target(f) \\<cong> source(f)\"\n@proof @have (@rule) \"\\<forall>x\\<in>source(f). inverse(f)`(f`x) = x\" @qed\n\nlemma inverse_of_inj [rewrite]:\n  \"injective(f) \\<Longrightarrow> X \\<subseteq> source(f) \\<Longrightarrow> f -`` (f `` X) = X\" by auto2\n\nlemma inverse_of_surj [rewrite]:\n  \"surjective(f) \\<Longrightarrow> Y \\<subseteq> target(f) \\<Longrightarrow> f `` (f -`` Y) = Y\"\n@proof\n  @have \"\\<forall>y\\<in>Y. y \\<in> f``(f-``Y)\" @with\n    @obtain \"x\\<in>source(f)\" where \"f`x = y\"\n  @end\n@qed\n\nlemma inverse_is_left_inv [rewrite]:\n  \"bijective(f) \\<Longrightarrow> inverse(f) \\<circ> f = id_fun(source(f))\" by auto2\n\nlemma inverse_is_right_inv [rewrite]:\n  \"bijective(f) \\<Longrightarrow> f \\<circ> inverse(f) = id_fun(target(f))\" by auto2\n\nsection \\<open>Left and right inverses\\<close>  (* Bourbaki II.3.8 *)\n\n(* Left and right inverses always exists, but that takes more work. *)\nlemma has_left_inverse_inj [forward]:\n  \"is_function(f) \\<Longrightarrow> is_function(r) \\<Longrightarrow> target(f) = source(r) \\<Longrightarrow>\n   r \\<circ> f = id_fun(source(f)) \\<Longrightarrow> injective(f)\"\n@proof\n  @have \"\\<forall>x\\<in>source(f). \\<forall>y\\<in>source(f). f`x = f`y \\<longrightarrow> x=y\" @with @have \"r`(f`x)=x\" @end\n@qed\n\nlemma has_right_inverse_surj [forward]:\n  \"is_function(f) \\<Longrightarrow> is_function(s) \\<Longrightarrow> target(s) = source(f) \\<Longrightarrow>\n   f \\<circ> s = id_fun(source(s)) \\<Longrightarrow> surjective(f)\"\n@proof\n  @have \"\\<forall>x\\<in>target(f). x\\<in>image(f)\" @with @have \"f`(s`x) = x\" @end\n@qed\n\nlemma has_left_right_inverse_bij [forward]:\n  \"func_form(f) \\<Longrightarrow> is_function(r) \\<Longrightarrow> is_function(s) \\<Longrightarrow> target(f) = source(r) \\<Longrightarrow>\n   target(s) = source(f) \\<Longrightarrow> r \\<circ> f = id_fun(A) \\<Longrightarrow> f \\<circ> s = id_fun(B) \\<Longrightarrow> f \\<in> A \\<cong> B\" by auto2\n\nlemma right_inverse_unique:\n  \"is_function(f) \\<Longrightarrow> f \\<circ> s = id_fun(B) \\<Longrightarrow> f \\<circ> s' = id_fun(B) \\<Longrightarrow>\n   f \\<in> A \\<rightarrow> B \\<Longrightarrow> s \\<in> B \\<rightarrow> A \\<Longrightarrow> s' \\<in> B \\<rightarrow> A \\<Longrightarrow> s `` B = s' `` B \\<Longrightarrow> s = s'\"\n@proof\n  @have \"\\<forall>x\\<in>B. s`x = s'`x\" @with @have \"f`(s`x) = x\" @end\n@qed\n\n(* Six parts of Theorem 1 in Bourbaki II.3.8. May be easier with existence\n   of left/right-inverse, but not necessary. *)\nlemma comp_is_inj:\n  \"injective(f) \\<Longrightarrow> injective(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> injective(f' \\<circ> f)\" by auto2\nsetup {* add_forward_prfstep_cond @{thm comp_is_inj} [with_term \"?f' \\<circ> ?f\"] *}\n\nlemma comp_is_surj:\n  \"surjective(f) \\<Longrightarrow> surjective(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> surjective(f' \\<circ> f)\"\n@proof\n  @have \"\\<forall>z\\<in>target(f'). \\<exists>x\\<in>source(f). (f' \\<circ> f) ` x = z\" @with\n    @obtain \"y \\<in> source(f')\" where \"f' ` y = z\"\n    @obtain \"x \\<in> source(f)\" where \"f ` x = y\"\n  @end\n@qed\nsetup {* add_forward_prfstep_cond @{thm comp_is_surj} [with_term \"?f' \\<circ> ?f\"] *}\n\nlemma comp_is_inj_to_first_inj [forward]:\n  \"is_function(f) \\<Longrightarrow> is_function(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> injective(f' \\<circ> f) \\<Longrightarrow> injective(f)\"\n@proof\n  @have \"\\<forall>x\\<in>source(f). \\<forall>y\\<in>source(f). f`x = f`y \\<longrightarrow> x=y\" @with\n    @have \"(f' \\<circ> f) ` x = (f' \\<circ> f) ` y\" @end\n@qed\n\nlemma comp_is_surj_to_second_surj [forward]:\n  \"is_function(f) \\<Longrightarrow> is_function(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> surjective(f' \\<circ> f) \\<Longrightarrow> surjective(f')\"\n@proof\n  @have \"\\<forall>y\\<in>target(f'). \\<exists>x\\<in>source(f'). f' ` x = y\" @with\n    @obtain \"x \\<in> source(f)\" where \"(f' \\<circ> f) ` x = y\"\n  @end\n@qed\n\nlemma comp_is_surj_to_first_surj [forward]:\n  \"is_function(f) \\<Longrightarrow> injective(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> surjective(f' \\<circ> f) \\<Longrightarrow> surjective(f)\"\n@proof\n  @have \"\\<forall>y\\<in>target(f). \\<exists>x\\<in>source(f). f ` x = y\" @with\n    @obtain \"x \\<in> source(f)\" where \"(f' \\<circ> f) ` x = f' ` y\"\n  @end\n@qed\n\nlemma comp_is_inj_to_second_inj [forward]:\n  \"surjective(f) \\<Longrightarrow> func_form(f') \\<Longrightarrow> target(f) = source(f') \\<Longrightarrow> injective(f' \\<circ> f) \\<Longrightarrow> injective(f')\"\n@proof @have \"f' = (f' \\<circ> f) \\<circ> inverse(f)\" @qed\n\nlemma inverse_unique [rewrite]:\n  \"bijective(f) \\<Longrightarrow> func_form(g) \\<Longrightarrow> target(f) = source(g) \\<Longrightarrow>\n   g \\<circ> f = id_fun(source(f)) \\<Longrightarrow> inverse(f) = g\"\n@proof\n  @have \"\\<forall>x\\<in>target(f). inverse(f)`x = g`x\" @with\n    @obtain \"y\\<in>source(f)\" where \"f`y = x\"\n  @end\n@qed\n\nlemma inverse_unique' [rewrite]:\n  \"bijective(f) \\<Longrightarrow> func_form(g) \\<Longrightarrow> target(g) = source(f) \\<Longrightarrow>\n   f \\<circ> g = id_fun(target(f)) \\<Longrightarrow> inverse(f) = g\"\n@proof\n  @have \"\\<forall>x\\<in>target(f). inverse(f)`x = g`x\" @with\n    @have \"f ` (g ` x) = (f \\<circ> g) ` x\"\n  @end\n@qed\n\n(* Now we construct the left and right inverses explicitly. *)\nlemma exists_right_inverse [resolve]:\n  \"surjective(f) \\<Longrightarrow> A = source(f) \\<Longrightarrow> B = target(f) \\<Longrightarrow> \\<exists>s\\<in>B\\<rightarrow>A. f \\<circ> s = id_fun(B)\"\n@proof @let \"s = Fun(B,A, \\<lambda>y. SOME x\\<in>A. f`x=y)\" @qed\n\ndefinition right_inverse :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"right_inverse(f) = (SOME s\\<in>target(f)\\<rightarrow>source(f). f \\<circ> s = id_fun(target(f)))\"\n\nlemma right_inverse_prop:\n  \"surjective(f) \\<Longrightarrow>\n   right_inverse(f) \\<in> target(f) \\<rightarrow> source(f) \\<and> f \\<circ> right_inverse(f) = id_fun(target(f))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm right_inverse_prop} [with_term \"right_inverse(?f)\"] *}\nsetup {* del_prfstep_thm @{thm right_inverse_def} *}\n\nlemma exists_left_inverse [backward]:\n  \"injective(f) \\<Longrightarrow> A = source(f) \\<Longrightarrow> B = target(f) \\<Longrightarrow> A \\<noteq> \\<emptyset> \\<Longrightarrow> \\<exists>r\\<in>B\\<rightarrow>A. r \\<circ> f = id_fun(A)\"\n@proof\n  @obtain \"a \\<in> A\"\n  @let \"r = Fun(B, A, \\<lambda>y. if \\<exists>x\\<in>A. f`x=y then SOME x\\<in>A. f`x=y else a)\"\n  @have (@rule) \"\\<forall>x\\<in>A. r`(f`x) = x\" @with @have \"\\<exists>x'\\<in>A. f`x' = f`x\" @end\n@qed\n\ndefinition left_inverse :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"left_inverse(f) = (SOME r\\<in>target(f)\\<rightarrow>source(f). r \\<circ> f = id_fun(source(f)))\"\nsetup {* register_wellform_data (\"left_inverse(f)\", [\"source(f) \\<noteq> \\<emptyset>\"]) *}\nsetup {* add_prfstep_check_req (\"left_inverse(f)\", \"source(f) \\<noteq> \\<emptyset>\") *}\n\nlemma left_inverse_prop:\n  \"injective(f) \\<Longrightarrow> source(f) \\<noteq> \\<emptyset> \\<Longrightarrow>\n   left_inverse(f) \\<in> target(f) \\<rightarrow> source(f) \\<and> left_inverse(f) \\<circ> f = id_fun(source(f))\" by auto2\nsetup {* add_forward_prfstep_cond @{thm left_inverse_prop} [with_term \"left_inverse(?f)\"] *}\nsetup {* del_prfstep_thm @{thm left_inverse_def} *}\n\n(* Using left and right inverses to construct functions. *)\nlemma exists_pullback_surj [backward1]:\n  \"surjective(g) \\<Longrightarrow> g \\<in> E \\<rightarrow> F \\<Longrightarrow> f \\<in> E \\<rightarrow> G \\<Longrightarrow> \\<forall>x\\<in>E. \\<forall>y\\<in>E. g`x=g`y \\<longrightarrow> f`x=f`y \\<Longrightarrow>\n   \\<exists>!h. h\\<in>F\\<rightarrow>G \\<and> f = h \\<circ> g\"\n@proof\n  @have \"\\<exists>h\\<in>F\\<rightarrow>G. f = h \\<circ> g\" @with\n    @obtain \"s \\<in> F \\<rightarrow> E\" where \"g \\<circ> s = id_fun(F)\"\n    @obtain \"h \\<in> F \\<rightarrow> G\" where \"h = f \\<circ> s\"\n  @end\n  @have \"\\<forall>h1 h2. h1 \\<in> F \\<rightarrow> G \\<and> f = h1 \\<circ> g \\<longrightarrow> h2 \\<in> F \\<rightarrow> G \\<and> f = h2 \\<circ> g \\<longrightarrow> h1 = h2\" @with\n    @have \"\\<forall>x\\<in>F. h1`x = h2`x\" @with\n      @obtain \"y\\<in>E\" where \"g`y = x\"\n    @end\n  @end\n@qed\n\nlemma exists_pullback_inj:\n  \"injective(g) \\<Longrightarrow> g \\<in> F \\<rightarrow> E \\<Longrightarrow> f \\<in> G \\<rightarrow> E \\<Longrightarrow> F \\<noteq> \\<emptyset> \\<Longrightarrow> image(f) \\<subseteq> image(g) \\<Longrightarrow>\n   \\<exists>!h. h\\<in>G\\<rightarrow>F \\<and> f = g \\<circ> h\"\n@proof\n  @have \"\\<exists>h\\<in>G\\<rightarrow>F. f = g \\<circ> h\" @with\n    @obtain \"r \\<in> E \\<rightarrow> F\" where \"r \\<circ> g = id_fun(F)\"\n    @obtain \"h \\<in> G \\<rightarrow> F\" where \"h = r \\<circ> f\"\n  @end\n  @have \"\\<forall>h1 h2. h1 \\<in> G \\<rightarrow> F \\<and> f = g \\<circ> h1 \\<longrightarrow> h2 \\<in> G \\<rightarrow> F \\<and> f = g \\<circ> h2 \\<longrightarrow> h1 = h2\" @with\n    @have \"\\<forall>x\\<in>G. h1`x = h2`x\" @with\n      @have \"g`(h1`x) = g`(h2`x)\"\n    @end\n  @end\n@qed\n\nsection \\<open>Inverse pair\\<close>\n\n(* Two functions are inverses of each other. This pattern occurs very frequently. *)\ndefinition inverse_pair :: \"i \\<Rightarrow> i \\<Rightarrow> o\" where [rewrite]:\n  \"inverse_pair(f,g) \\<longleftrightarrow> (is_function(f) \\<and> is_function(g) \\<and> source(f) = target(g) \\<and> target(f) = source(g) \\<and>\n                          f \\<circ> g = id_fun(source(g)) \\<and> g \\<circ> f = id_fun(source(f)))\"\n\nlemma inverse_pair_bijective [forward]:\n  \"inverse_pair(f,g) \\<Longrightarrow> source(f) = target(g) \\<and> source(g) = target(f) \\<and> bijective(f) \\<and> bijective(g)\" by auto2\n\nlemma inverse_pairI [backward]:\n  \"is_function(f) \\<Longrightarrow> is_function(g) \\<Longrightarrow> source(f) = target(g) \\<Longrightarrow> source(g) = target(f) \\<Longrightarrow>\n   \\<forall>x\\<in>source(g). f`(g`x) = x \\<Longrightarrow> \\<forall>x\\<in>source(f). g`(f`x) = x \\<Longrightarrow> inverse_pair(f,g)\" by auto2\n\nlemma inverse_pairE [rewrite]:\n  \"inverse_pair(f,g) \\<Longrightarrow> f \\<circ> g = id_fun(source(g))\"\n  \"inverse_pair(f,g) \\<Longrightarrow> g \\<circ> f = id_fun(source(f))\" by auto2+\nsetup {* del_prfstep_thm @{thm inverse_pair_def} *}\n\nlemma inverse_pair_inverse [rewrite]: \"func_form(g) \\<Longrightarrow> inverse_pair(f,g) \\<Longrightarrow> inverse(f) = g\"\n@proof @have \"g \\<circ> f = id_fun(source(f))\" @qed\n\nlemma inverse_pair_inverse2 [rewrite]: \"func_form(f) \\<Longrightarrow> inverse_pair(f,g) \\<Longrightarrow> inverse(g) = f\"\n@proof @have \"g \\<circ> f = id_fun(source(f))\" @qed\n\nsection \\<open>Function of two arguments\\<close>  (* Bourbaki II.3.9 *)\n\n(* We consider functions on product sets only. *)\n\n(* Currying: given a function (A \\<times> B) \\<rightarrow> D, return a function A \\<rightarrow> (B \\<rightarrow> D). *)\ndefinition curry :: \"[i, i, i] \\<Rightarrow> i\" where [rewrite]:\n  \"curry(A,B,D) = Fun(A\\<times>B\\<rightarrow>D, A\\<rightarrow>B\\<rightarrow>D, \\<lambda>f. Fun(A, B\\<rightarrow>D, \\<lambda>x. Fun(B, D, \\<lambda>y. f`\\<langle>x,y\\<rangle>)))\"\n\nlemma curry_is_function [typing]:\n  \"curry(A,B,D) \\<in> ((A \\<times> B) \\<rightarrow> D) \\<rightarrow> (A \\<rightarrow> (B \\<rightarrow> D))\" by auto2\n\nlemma curry_eval [rewrite]:\n  \"f \\<in> source(curry(A,B,D)) \\<Longrightarrow> x \\<in> source(curry(A,B,D)`f) \\<Longrightarrow> y \\<in> source(curry(A,B,D)`f`x) \\<Longrightarrow>\n   curry(A,B,D)`f`x`y = f`\\<langle>x,y\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm curry_def} *}\n\n(* Constant functions *)\ndefinition is_const_fun :: \"i \\<Rightarrow> o\" where [rewrite]:\n  \"is_const_fun(f) \\<longleftrightarrow> (\\<forall>x\\<in>source(f). \\<forall>y\\<in>source(f). f`x = f`y)\"\n\nlemma is_const_funD [forward]:\n  \"is_const_fun(f) \\<Longrightarrow> x \\<in> source(f) \\<Longrightarrow> y \\<in> source(f) \\<Longrightarrow> f`x = f`y\" by auto2\nsetup {* del_prfstep_thm_eqforward @{thm is_const_fun_def} *}\n\n(* Functions that do not depend on the second argument. *)\nlemma exists_proj_fun:\n  \"B \\<noteq> \\<emptyset> \\<Longrightarrow> f \\<in> (A \\<times> B) \\<rightarrow> D \\<Longrightarrow> \\<forall>x\\<in>A. is_const_fun(curry(A,B,D)`f`x) \\<Longrightarrow>\n   \\<exists>g\\<in>A\\<rightarrow>D. \\<forall>x\\<in>A. \\<forall>y\\<in>B. f`\\<langle>x,y\\<rangle> = g`x\"\n@proof\n  @obtain \"y \\<in> B\" @let \"g = Fun(A,D, \\<lambda>x. f`\\<langle>x,y\\<rangle>)\"\n@qed\n\n(* Product map *)\ndefinition prod_map :: \"i \\<Rightarrow> i \\<Rightarrow> i\" (infixr \"\\<times>\\<^sub>f\" 80) where [rewrite]:\n  \"u \\<times>\\<^sub>f v = Fun(source(u)\\<times>source(v), target(u)\\<times>target(v), \\<lambda>p. \\<langle>u`fst(p), v`snd(p)\\<rangle>)\"\n\nlemma prod_map_is_function [typing]:\n  \"is_function(u) \\<Longrightarrow> is_function(v) \\<Longrightarrow> u \\<times>\\<^sub>f v \\<in> source(u)\\<times>source(v) \\<rightarrow> target(u)\\<times>target(v)\" by auto2\n\nlemma prod_map_eval [rewrite]:\n  \"is_function(u) \\<Longrightarrow> is_function(v) \\<Longrightarrow> \\<langle>x,y\\<rangle> \\<in> source(u \\<times>\\<^sub>f v) \\<Longrightarrow> (u \\<times>\\<^sub>f v) ` \\<langle>x,y\\<rangle> = \\<langle>u`x, v`y\\<rangle>\" by auto2\nsetup {* del_prfstep_thm @{thm prod_map_def} *}\n\nlemma prod_map_inj [forward]:\n  \"injective(u) \\<Longrightarrow> injective(v) \\<Longrightarrow> injective(u \\<times>\\<^sub>f v)\" by auto2\n\nlemma prod_map_surj [forward]:\n  \"surjective(u) \\<Longrightarrow> surjective(v) \\<Longrightarrow> surjective(u \\<times>\\<^sub>f v)\"\n@proof\n  @let \"f = u \\<times>\\<^sub>f v\"\n  @have \"\\<forall>q\\<in>target(f). \\<exists>p\\<in>source(f). f`p = q\" @with\n    @obtain \"x\\<in>source(u)\" where \"u`x = fst(q)\"\n    @obtain \"y\\<in>source(v)\" where \"v`y = snd(q)\"\n  @end\n@qed\n\nlemma prod_map_bij [forward]:\n  \"bijective(u) \\<Longrightarrow> bijective(v) \\<Longrightarrow> bijective(u \\<times>\\<^sub>f v)\" by auto2\n\nlemma prod_map_comp [resolve]:\n  \"is_function(u) \\<Longrightarrow> is_function(u') \\<Longrightarrow> is_function(v) \\<Longrightarrow> is_function(v') \\<Longrightarrow>\n   target(u) = source(u') \\<Longrightarrow> target(v) = source(v') \\<Longrightarrow>\n   (u' \\<circ> u) \\<times>\\<^sub>f (v' \\<circ> v) = (u' \\<times>\\<^sub>f v') \\<circ> (u \\<times>\\<^sub>f v)\" by auto2\n\nlemma prod_map_id_fun [rewrite]:\n  \"id_fun(A) \\<times>\\<^sub>f id_fun(B) = id_fun(A\\<times>B)\" by auto2\n\nlemma prod_inverse [resolve]:\n  \"bijective(u) \\<Longrightarrow> bijective(v) \\<Longrightarrow> inverse(u \\<times>\\<^sub>f v) = inverse(u) \\<times>\\<^sub>f inverse(v)\"\n@proof\n  @have \"inverse_pair(inverse(u) \\<times>\\<^sub>f inverse(v), u \\<times>\\<^sub>f v)\"\n@qed\n\nsection \\<open>Extension of a function to Pow\\<close>  (* Bourbaki II.5.1 *)\n\ndefinition pow_ext :: \"i \\<Rightarrow> i\" where [rewrite]:\n  \"pow_ext(f) = Fun(Pow(source(f)), Pow(target(f)), \\<lambda>X. f `` X)\"\n\nlemma pow_ext_is_function [typing]:\n  \"is_function(f) \\<Longrightarrow> pow_ext(f) \\<in> Pow(source(f)) \\<rightarrow> Pow(target(f))\" by auto2\n\nlemma pow_ext_eval [rewrite]:\n  \"is_function(f) \\<Longrightarrow> X \\<in> source(pow_ext(f)) \\<Longrightarrow> pow_ext(f) ` X = f `` X\" by auto2\nsetup {* del_prfstep_thm @{thm pow_ext_def} *}\n\nlemma pow_ext_comp [rewrite]:\n  \"is_function(f) \\<Longrightarrow> is_function(g) \\<Longrightarrow> target(f) = source(g) \\<Longrightarrow>\n   pow_ext(g \\<circ> f) = pow_ext(g) \\<circ> pow_ext(f)\" by auto2\n\nlemma pow_ext_id [rewrite]:\n  \"pow_ext(id_fun(A)) = id_fun(Pow(A))\" by auto2\n\nlemma pow_ext_surj [forward]:\n  \"is_function(f) \\<Longrightarrow> surjective(f) \\<Longrightarrow> surjective(pow_ext(f))\"\n@proof\n  @let \"A = source(f)\" \"B = target(f)\"\n  @obtain \"s \\<in> B \\<rightarrow> A\" where \"f \\<circ> s = id_fun(target(f))\"\n  @have \"pow_ext(f \\<circ> s) = pow_ext(f) \\<circ> pow_ext(s)\"\n@qed\n\nlemma pow_ext_inj [forward]:\n  \"injective(f) \\<Longrightarrow> injective(pow_ext(f))\"\n@proof\n  @let \"U = source(pow_ext(f))\"\n  @have (@rule) \"\\<forall>S\\<in>U. \\<forall>T\\<in>U. f `` S = f `` T \\<longrightarrow> S = T\" @with\n    @have \"\\<forall>x. x \\<in> S \\<longleftrightarrow> x \\<in> T\" @with\n      @case \"x \\<in> S\" @with @have \"f`x \\<in> f``S\" @end\n      @case \"x \\<in> T\" @with @have \"f`x \\<in> f``T\" @end\n    @end\n  @end\n@qed\n\nsection \\<open>Map on function spaces\\<close>  (* Bourbaki II.5.2 *)\n\n(* Define left and right composition separately. *)\n\ndefinition left_comp :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"left_comp(u,E) = Fun(E\\<rightarrow>source(u), E\\<rightarrow>target(u), \\<lambda>f. u \\<circ> f)\"\n\nlemma left_comp_is_function [typing]:\n  \"is_function(u) \\<Longrightarrow> left_comp(u,E) \\<in> (E\\<rightarrow>source(u)) \\<rightarrow> (E\\<rightarrow>target(u))\" by auto2\n\nlemma left_comp_eval [rewrite]:\n  \"is_function(u) \\<Longrightarrow> f \\<in> source(left_comp(u,E)) \\<Longrightarrow> left_comp(u,E) ` f = u \\<circ> f\" by auto2\nsetup {* del_prfstep_thm @{thm left_comp_def} *}\n\nlemma injective_left_comp [forward]:\n  \"injective(u) \\<Longrightarrow> injective(left_comp(u,E))\"\n@proof\n  @contradiction\n  @obtain \"r \\<in> target(u) \\<rightarrow> source(u)\" where \"r \\<circ> u = id_fun(source(u))\"\n  @have \"left_comp(r,E) \\<circ> left_comp(u,E) = id_fun(E\\<rightarrow>source(u))\"\n@qed\n\nlemma surjective_left_comp [forward]:\n  \"surjective(u) \\<Longrightarrow> surjective(left_comp(u,E))\"\n@proof\n  @obtain \"s \\<in> target(u) \\<rightarrow> source(u)\" where \"u \\<circ> s = id_fun(target(u))\"\n  @have \"left_comp(u,E) \\<circ> left_comp(s,E) = id_fun(E\\<rightarrow>target(u))\"\n@qed\n\nlemma bijective_left_comp [forward]:\n  \"bijective(u) \\<Longrightarrow> bijective(left_comp(u,E))\" by auto2\n\ndefinition right_comp :: \"i \\<Rightarrow> i \\<Rightarrow> i\" where [rewrite]:\n  \"right_comp(E,u) = Fun(target(u)\\<rightarrow>E, source(u)\\<rightarrow>E, \\<lambda>f. f \\<circ> u)\"\n\nlemma right_comp_is_function [typing]:\n  \"is_function(u) \\<Longrightarrow> right_comp(E,u) \\<in> (target(u)\\<rightarrow>E) \\<rightarrow> (source(u)\\<rightarrow>E)\" by auto2\n\nlemma right_comp_eval [rewrite]:\n  \"is_function(u) \\<Longrightarrow> f \\<in> source(right_comp(E,u)) \\<Longrightarrow> right_comp(E,u) ` f = f \\<circ> u\" by auto2\nsetup {* del_prfstep_thm @{thm right_comp_def} *}\n\nlemma injective_right_comp [forward]:\n  \"surjective(u) \\<Longrightarrow> injective(right_comp(E,u))\"\n@proof\n  @obtain \"s \\<in> target(u) \\<rightarrow> source(u)\" where \"u \\<circ> s = id_fun(target(u))\"\n  @have \"right_comp(E,s) \\<circ> right_comp(E,u) = id_fun(target(u)\\<rightarrow>E)\"\n@qed\n\nlemma surjective_right_comp [backward]:\n  \"injective(u) \\<Longrightarrow> source(u) \\<noteq> \\<emptyset> \\<Longrightarrow> surjective(right_comp(E,u))\"\n@proof\n  @obtain \"r \\<in> target(u) \\<rightarrow> source(u)\" where \"r \\<circ> u = id_fun(source(u))\"\n  @have \"right_comp(E,u) \\<circ> right_comp(E,r) = id_fun(target(r)\\<rightarrow>E)\"\n@qed\n\n(* The requirement that source(u) \\<noteq> \\<emptyset> is necessary here, as the following example shows. *)\nlemma injective_two_side_comp_counterexample:\n  \"u = const_fun(\\<emptyset>,{\\<emptyset>},\\<emptyset>) \\<Longrightarrow> injective(u) \\<and> \\<not>surjective(right_comp(\\<emptyset>,u))\"\n@proof @have \"target(u) \\<rightarrow> \\<emptyset> = \\<emptyset>\" @qed\n\n(* Nevertheless, no condition is required when u is bijective. *)\nlemma bijective_right_comp [forward]:\n  \"bijective(u) \\<Longrightarrow> bijective(right_comp(E,u))\" by auto2\n\n(* Given a function A \\<rightarrow> (B \\<rightarrow> D), return a function (A \\<times> B) \\<rightarrow> D. *)\ndefinition uncurry :: \"[i, i, i] \\<Rightarrow> i\" where [rewrite]:\n  \"uncurry(A,B,D) = Fun(A\\<rightarrow>B\\<rightarrow>D, A\\<times>B\\<rightarrow>D, \\<lambda>f. Fun(A\\<times>B, D, \\<lambda>x. f`fst(x)`snd(x)))\"\n\nlemma uncurry_is_function [typing]:\n  \"uncurry(A,B,D) \\<in> (A \\<rightarrow> B \\<rightarrow> D) \\<rightarrow> (A \\<times> B \\<rightarrow> D)\" by auto2\n\nlemma uncurry_eval [rewrite]:\n  \"f \\<in> source(uncurry(A,B,D)) \\<Longrightarrow> \\<langle>x,y\\<rangle>\\<in>source(uncurry(A,B,D)`f) \\<Longrightarrow> uncurry(A,B,D)`f`\\<langle>x,y\\<rangle> = f`x`y\" by auto2\nsetup {* del_prfstep_thm @{thm uncurry_def} *}\n\nlemma curry_bijective [forward]: \"bijective(curry(A,B,D))\"\n@proof\n  @have \"inverse_pair(curry(A,B,D), uncurry(A,B,D))\"\n@qed\n\nend\n", "meta": {"author": "bzhan", "repo": "auto2", "sha": "2e83c30b095f2ed9fa5257f79570eb354ed6e6a7", "save_path": "github-repos/isabelle/bzhan-auto2", "path": "github-repos/isabelle/bzhan-auto2/auto2-2e83c30b095f2ed9fa5257f79570eb354ed6e6a7/FOL/Functions.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8887587993853655, "lm_q2_score": 0.8438950966654772, "lm_q1q2_score": 0.7500191929196065}}
{"text": "theory GabrielaLimonta\nimports \"~~/src/HOL/IMP/AExp\"\nbegin\n\n(* Homework 2.1 *)\ndatatype bst = Leaf | node int bst bst\n\nfun \\<alpha> :: \"bst \\<Rightarrow> (int) set\" where\n  \"\\<alpha> Leaf = {}\"\n| \"\\<alpha> (node e l r) = {e} \\<union> \\<alpha> l \\<union> \\<alpha> r\"\n\nvalue \"\\<alpha> (node 4 (node 2 (node 1 Leaf Leaf) (node 3 Leaf Leaf)) (node 5 Leaf Leaf))\"\n\nfun invar :: \"bst \\<Rightarrow> bool\" where\n  \"invar Leaf = True\"\n| \"invar (node e l r) = (invar l \\<and> invar r \\<and> (\\<forall>x\\<in>(\\<alpha> l). e > x) \\<and> (\\<forall>x\\<in>(\\<alpha> r). e < x)) \"\n\nvalue \"invar (node 4 (node 2 (node 1 Leaf Leaf) (node 3 Leaf Leaf)) (node 5 Leaf Leaf))\"\nvalue \"invar (node 4 (node 1 (node 2 Leaf Leaf) (node 3 Leaf Leaf)) (node 5 Leaf Leaf))\"\n\nfun lookup :: \"int \\<Rightarrow> bst \\<Rightarrow> bool\" where\n  \"lookup e Leaf = False\"\n| \"lookup e (node x l r) = (if e = x then True else (if e > x then lookup e r else lookup e l))\"\n\nvalue \"lookup 1 Leaf\"\nvalue \"lookup 1 (node 1 Leaf Leaf)\"\nvalue \"lookup 1 (node 2 Leaf Leaf)\"\nvalue \"lookup 1 (node 4 (node 2 (node 1 Leaf Leaf) (node 3 Leaf Leaf)) (node 5 Leaf Leaf))\"\nvalue \"lookup 42 (node 4 (node 2 (node 1 Leaf Leaf) (node 3 Leaf Leaf)) (node 5 Leaf Leaf))\"\nvalue \"lookup 2 (node 4 (node 1 (node 2 Leaf Leaf) (node 3 Leaf Leaf)) (node 5 Leaf Leaf))\"\n\nlemma \"invar t \\<Longrightarrow> lookup x t \\<longleftrightarrow> x\\<in>\\<alpha> t\"\n  apply(induction t)\n  apply(auto)\n  done\n\nfun ins :: \"int \\<Rightarrow> bst \\<Rightarrow> bst\" where\n  \"ins e Leaf = (node e Leaf Leaf)\"\n| \"ins e (node x l r) = (if e = x then node x l r else (if e < x then node x (ins e l) r else node x l (ins e r)))\"\n\nvalue \"ins -4(ins -9(ins 5(ins 6(ins 56(ins 9(ins 3(ins 1 Leaf)))))))\"\n\nlemma ins_correct1: \"\\<lbrakk>invar t\\<rbrakk> \\<Longrightarrow> \\<alpha> (ins x t) = insert x (\\<alpha> t)\"\n  apply(induction t)\n  apply(auto)\n  done\n\nlemma ins_correct2: \"invar t \\<Longrightarrow> invar (ins x t)\"\n  apply(induction t)\n  apply(auto simp add: ins_correct1)\n  done\n\nfun dell :: \"int \\<Rightarrow> bst \\<Rightarrow> bst\" where\n  \"dell _ Leaf = Leaf\"\n| \"dell e (node x l r) = (if e = x then (node x Leaf r) else (if e < x then (node x (dell e l) r) else (dell e r)))\"\n\nvalue \"dell 5 (node 4 (node 2 (node 1 Leaf Leaf) (node 3 Leaf Leaf)) (node 10 Leaf Leaf))\"\n\nlemma dell_correct1: \"invar t \\<Longrightarrow> \\<alpha> (dell a t) = {x\\<in>\\<alpha> t. x\\<ge>a}\"\n  apply(induction t)\n  apply(auto)\n  done\n\nlemma dell_correct2: \"invar t \\<Longrightarrow> invar (dell a t)\"\n  apply(induction t)\n  apply(auto simp add: dell_correct1)\n  done\n\n(* Homework 2.2 *)\n\ntype_synonym vname = string\ntype_synonym state = \"string \\<Rightarrow> int\"\ntype_synonym val = \"int\"\n\ndeclare algebra_simps[simp]\n\ndatatype aexp = N int | V vname | Plus aexp aexp | Mult int aexp\n\nfun aval :: \"aexp \\<Rightarrow> state \\<Rightarrow> val\" where\n\"aval (N n) s = n\" |\n\"aval (V x) s = s x\" |\n\"aval (Plus a1 a2) s = aval a1 s + aval a2 s\" |\n\"aval (Mult i a) s = i * aval a s\"\n\nfun normal :: \"aexp \\<Rightarrow> bool\" where\n  \"normal (N n) = True\"\n| \"normal (V x) = True\"\n| \"normal (Mult i a) = (\n    case a of\n      (N n) \\<Rightarrow> False |\n      (V x) \\<Rightarrow> True |\n      (Mult i a) \\<Rightarrow> False |\n      (Plus a1 a2) \\<Rightarrow> False)\"\n| \"normal (Plus a1 a2) = (normal a1 \\<and> normal a2)\"\n\nvalue \"normal (Plus (N 6) (Mult 4 (V x)))\"\nvalue \"normal (Plus (N 6) (Mult 4 (Mult 3 (V y))))\"\n\nfun normalize :: \"aexp \\<Rightarrow> aexp\" where\n  \"normalize (N n) = (N n)\"\n| \"normalize (V x) = (V x)\"\n| \"normalize (Plus a1 a2) = (Plus (normalize a1) (normalize a2))\"\n| \"normalize (Mult i a) = (\n    case a of\n      (N n) \\<Rightarrow> (N (i*n)) |\n      (V x) \\<Rightarrow> (Mult i (V x)) |\n      (Mult x y) \\<Rightarrow> normalize (Mult (i*x) y) |\n      (Plus x y) \\<Rightarrow> (Plus (normalize (Mult i x)) (normalize (Mult i y)))\n)\"\n\nvalue \"normalize (Plus (N 6) (Mult 4 (Mult 3 (V y))))\"\nvalue \"normalize (Mult 2 (Plus (V x) (N 21)))\"\n\nlemma aux: \"aval (normalize a) s = aval a s\"\n  apply(induction a rule: normalize.induct)\n  apply(auto split: aexp.split)\n  done\n\nlemma \"normal (normalize a)\"\n  apply(induction a rule: normalize.induct)\n  apply(auto simp add: aux split: aexp.split)\n  done\n\nend\n\n", "meta": {"author": "glimonta", "repo": "Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "save_path": "github-repos/isabelle/glimonta-Semantics", "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise2/GabrielaLimonta.thy", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066391, "lm_q2_score": 0.8438951005915208, "lm_q1q2_score": 0.7500191814899217}}
